{"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_GOODE_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_GOODE_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#include <boost/geometry/srs/projections/proj/gn_sinu.hpp>\n#include <boost/geometry/srs/projections/proj/moll.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace srs { namespace par4\n{\n    struct goode {}; // Goode Homolosine\n\n}} //namespace srs::par4\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace goode\n    {\n\n            static const double Y_COR = 0.05280;\n            static const double PHI_LIM = .71093078197902358062;\n\n            // TODO: consider storing references to Parameters instead of copies\n            template <typename T, typename Par>\n            struct par_goode\n            {\n                sinu_spheroid<T, Par>    sinu;\n                moll_spheroid<T, Par>    moll;\n\n                par_goode(Par const& par) : sinu(par), moll(par) {}\n            };\n\n            template <typename T, typename Par>\n            inline void s_forward(T& lp_lon, T& lp_lat, T& xy_x, T& xy_y,\n                                  Par const& par, par_goode<T, Par> const& proj_par)\n            {\n                if (fabs(lp_lat) <= PHI_LIM)\n                    proj_par.sinu.fwd(lp_lon, lp_lat, xy_x, xy_y);\n                else {\n                    proj_par.moll.fwd(lp_lon, lp_lat, xy_x, xy_y);\n                    xy_y -= lp_lat >= 0.0 ? Y_COR : -Y_COR;\n                }\n            }\n\n            template <typename T, typename Par>\n            inline void s_inverse(T& xy_x, T& xy_y, T& lp_lon, T& lp_lat,\n                                  Par const& par, par_goode<T, Par> const& proj_par)\n            {\n                if (fabs(xy_y) <= PHI_LIM)\n                    proj_par.sinu.inv(xy_x, xy_y, lp_lon, lp_lat);\n                else {\n                    xy_y += xy_y >= 0.0 ? Y_COR : -Y_COR;\n                    proj_par.moll.inv(xy_x, xy_y, lp_lon, lp_lat);\n                }\n            }\n\n            // Goode Homolosine\n            template <typename Par>\n            inline void setup_goode(Par& par)\n            {\n                par.es = 0.;\n\n                // NOTE: The following explicit initialization of sinu projection\n                // is not needed because setup_goode() is called before proj_par.sinu\n                // is constructed and m_par of parent projection is used.\n\n                //proj_par.sinu.m_par.es = 0.;\n                //detail::gn_sinu::setup_sinu(proj_par.sinu.m_par, proj_par.sinu.m_proj_parm);\n            }\n\n    }} // namespace detail::goode\n    #endif // doxygen\n\n    /*!\n        \\brief Goode Homolosine 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 Example\n        \\image html ex_goode.gif\n    */\n    template <typename T, typename Parameters>\n    struct goode_spheroid : public detail::base_t_fi<goode_spheroid<T, Parameters>, T, Parameters>\n    {\n        detail::goode::par_goode<T, Parameters> m_proj_parm;\n\n        inline goode_spheroid(const Parameters& par)\n            : detail::base_t_fi<goode_spheroid<T, Parameters>, T, Parameters>(*this, par)\n            , m_proj_parm(setup(this->m_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            detail::goode::s_forward(lp_lon, lp_lat, xy_x, xy_y, this->m_par, this->m_proj_parm);\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            detail::goode::s_inverse(xy_x, xy_y, lp_lon, lp_lat, this->m_par, this->m_proj_parm);\n        }\n\n        static inline std::string get_name()\n        {\n            return \"goode_spheroid\";\n        }\n\n    private:\n        static Parameters& setup(Parameters& par)\n        {\n            detail::goode::setup_goode(par);\n            return par;\n        }\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::goode, goode_spheroid, goode_spheroid)\n\n        // Factory entry(s)\n        template <typename T, typename Parameters>\n        class goode_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<goode_spheroid<T, Parameters>, T, Parameters>(par);\n                }\n        };\n\n        template <typename T, typename Parameters>\n        inline void goode_init(detail::base_factory<T, Parameters>& factory)\n        {\n            factory.add_to_factory(\"goode\", new goode_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_GOODE_HPP\n", "meta": {"hexsha": "8b3747ded9f262099d6cc6823f76fc7ba867af02", "size": 7335, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/boost/geometry/srs/projections/proj/goode.hpp", "max_stars_repo_name": "Bpowers4/turicreate", "max_stars_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "src/external/boost/boost_1_68_0/boost/geometry/srs/projections/proj/goode.hpp", "max_issues_repo_name": "Bpowers4/turicreate", "max_issues_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "src/external/boost/boost_1_68_0/boost/geometry/srs/projections/proj/goode.hpp", "max_forks_repo_name": "Bpowers4/turicreate", "max_forks_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 36.4925373134, "max_line_length": 109, "alphanum_fraction": 0.6291751875, "num_tokens": 1754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2999749031844382}}
{"text": "#define ARMA_NO_DEBUG\r\n\r\n#include <armadillo>\r\n#include <RcppArmadillo.h>\r\n// [[Rcpp::depends(RcppArmadillo, BH, bigmemory)]]\r\n\r\n#include <Rcpp.h>\r\n#include <vector>\r\n\r\nusing namespace Rcpp;\r\nusing namespace arma;\r\n\r\n#include <bigmemory/BigMatrix.h>\r\n// [[Rcpp::plugins(cpp11)]]\r\n\r\n\r\n// [[Rcpp::depends(RcppArmadillo)]]\r\n// [[Rcpp::export()]]\r\nRcpp::List calcT0Wsim1 (arma::mat& CvSqrt,arma::mat& weight, arma::vec powV, int nperm) {\r\n    \r\n    //const int n = X1.n_rows;\r\n    const int npow = powV.n_rows;\r\n    const int k = CvSqrt.n_rows;\r\n    // containers\r\n    arma::mat T0s1(nperm,npow);\r\n    T0s1.fill(0);\r\n    \r\n    for (int i = 0; i < nperm; i++) {\r\n        arma::mat U00 = arma::randn(k,1);\r\n        arma::mat U0 = CvSqrt * U00;\r\n        arma::mat U0tmp = weight % U0;\r\n        \r\n        for (int j = 0; j < npow; j++) {\r\n            if (powV[j] == 0) {\r\n                arma::mat tmpU01 = abs(U0tmp);\r\n                T0s1(i,j) = tmpU01.max();\r\n            } else {\r\n                T0s1(i,j) = accu(pow(U0tmp,powV[j]));\r\n            }\r\n        }\r\n    }\r\n    Rcpp::List res;\r\n    res[\"T0\"] =T0s1;\r\n    \r\n    return(res);\r\n}\r\n\r\n\r\n// [[Rcpp::depends(RcppArmadillo)]]\r\n// [[Rcpp::export()]]\r\narma::vec avg_rank(arma::vec x) {\r\n    \r\n    arma::uvec w  = arma::stable_sort_index(x,\"descend\");\r\n    R_xlen_t sz = x.size();\r\n    arma::vec r(sz);\r\n    \r\n    for (R_xlen_t n, i = 0; i < sz; i += n) {\r\n        n = 1;\r\n        while (i + n < sz && x[w[i]] == x[w[i + n]]) ++n;\r\n        for (R_xlen_t k = 0; k < n; k++) {\r\n            r[w[i + k]] = i + (n + 1) / 2.;\r\n        }\r\n    }\r\n    \r\n    return r;\r\n    \r\n}\r\n\r\n\r\n// [[Rcpp::depends(RcppArmadillo)]]\r\n// [[Rcpp::export()]]\r\nRcpp::List calcT0Wsim3 (arma::mat& CvSqrt,arma::mat& weight, arma::vec powV, arma::vec Tsabs, SEXP pBigMat, int nperm) {\r\n    \r\n    //const int n = X1.n_rows;\r\n    const int npow = powV.n_rows;\r\n    const int k = CvSqrt.n_rows;\r\n    \r\n    // containers\r\n    XPtr<BigMatrix> xpMat(pBigMat);\r\n    arma::mat T0s = arma::Mat<double> ( (double *)xpMat->matrix(), xpMat->nrow(), xpMat->ncol(), false);\r\n    \r\n    for (int i = 0; i < nperm; i++) {\r\n        arma::mat U00 = arma::randn(k,1);\r\n        arma::mat U0 = CvSqrt * U00;\r\n        arma::mat U0tmp = weight % U0;\r\n        \r\n        for (int j = 0; j < npow; j++) {\r\n            if (powV[j] == 0) {\r\n                arma::mat tmpU01 = abs(U0tmp);\r\n                T0s(i,j) = tmpU01.max();\r\n            } else {\r\n                T0s(i,j) = accu(pow(U0tmp,powV[j]));\r\n            }\r\n        }\r\n    }\r\n    \r\n    T0s = arma::abs(T0s);\r\n    \r\n    arma::vec minp0(nperm);\r\n    arma::vec P0s(nperm);\r\n    arma::vec pPerm0(npow);\r\n    \r\n    for (int i = 0; i < npow; i++) {\r\n        \r\n        // Calculate p-value\r\n        arma::vec T0stmp = T0s.col(i);\r\n        int tmp3 = 0;\r\n        arma::vec rankarma  = avg_rank(T0stmp);\r\n        \r\n        for( int tt=0 ; tt < nperm ; tt++) {\r\n            if( Tsabs(i)  <= T0stmp(tt) ) {\r\n                tmp3++;\r\n            }\r\n            \r\n            P0s(tt) = (double) rankarma(tt) / (double) nperm;\r\n        }\r\n        \r\n        \r\n        if(i == 0) {\r\n            minp0 = P0s;\r\n        } else {\r\n            for( int ii = 0; ii < nperm; ii++) {\r\n                if( minp0(ii) > P0s(ii) ) {\r\n                    minp0(ii) = P0s(ii);\r\n                }\r\n            }\r\n        }\r\n        pPerm0(i) = (double) tmp3/ (double) nperm;\r\n        \r\n    }\r\n    \r\n    return Rcpp::List::create(Rcpp::Named(\"minp0\") = minp0,\r\n                              Rcpp::Named(\"pPerm0\") = pPerm0 );\r\n    \r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n// [[Rcpp::depends(RcppArmadillo)]]\r\n// [[Rcpp::export()]]\r\nRcpp::List calcT0Wsim4 (arma::mat& CvSqrt,arma::mat& weight, arma::vec Tsabs, arma::vec powV, SEXP pBigMat, SEXP pBigMat3, int nperm) {\r\n    \r\n    //const int n = X1.n_rows;\r\n    const int npow = powV.n_rows;\r\n    const int nweight = weight.n_cols;\r\n    const int k = CvSqrt.n_rows;\r\n    // containers\r\n    XPtr<BigMatrix> xpMat(pBigMat);\r\n    arma::mat T0s = arma::Mat<double> ( (double *)xpMat->matrix(), xpMat->nrow(), xpMat->ncol(), false);\r\n    \r\n    XPtr<BigMatrix> xpMat3(pBigMat3);\r\n    arma::mat minp0_sign = arma::Mat<double> ( (double *)xpMat3->matrix(), xpMat3->nrow(), xpMat3->ncol(), false);\r\n    \r\n    for (int i = 0; i < nperm; i++) {\r\n        arma::mat U00 = arma::randn(k,1);\r\n        arma::mat U0 = CvSqrt * U00;\r\n        \r\n        for (int k = 0; k < nweight; k++) {\r\n            arma::mat weight_tmp = weight.col(k);\r\n            arma::mat U0tmp = weight_tmp % U0;\r\n            \r\n            for (int j = 0; j < npow; j++) {\r\n                if (powV[j] == 0) {\r\n                    arma::mat tmpU01 = abs(U0tmp);\r\n                    T0s(i,j * nweight + k) = tmpU01.max();\r\n                } else {\r\n                    T0s(i,j * nweight + k) = accu(pow(U0tmp,powV[j]));\r\n                }\r\n            }\r\n        }\r\n    }\r\n    \r\n    for (int k =0; k<nweight; k++) {\r\n        minp0_sign.col(k) = T0s.col(k);\r\n    }\r\n    \r\n    int npw = npow * nweight;\r\n    arma::mat cov_res(npw,npw);\r\n    cov_res.fill(0);\r\n    cov_res = cov(T0s);\r\n    \r\n    T0s = arma::abs(T0s);\r\n    \r\n    arma::vec minp0(nperm);\r\n    arma::vec P0s(nperm);\r\n    arma::mat pPerm0(npow + 1,nweight);\r\n    pPerm0.fill(-1);\r\n    \r\n    for(int k = 0; k < nweight; k++) {\r\n        \r\n        double minP_tmp = 1.0;\r\n        \r\n        for (int j = 0; j < npow; j++) {\r\n            \r\n            // Calculate p-value\r\n            arma::vec T0stmp = T0s.col(j * nweight + k);\r\n            int tmp3 = 0;\r\n            arma::vec rankarma  = avg_rank(T0stmp);\r\n            \r\n            for( int tt=0 ; tt < nperm ; tt++) {\r\n                if( Tsabs(j * nweight + k)  <= T0stmp(tt) ) {\r\n                    tmp3++;\r\n                }\r\n                \r\n                P0s(tt) = (double) rankarma(tt) / (double) nperm;\r\n            }\r\n            \r\n            if(j == 0) {\r\n                minp0 = P0s;\r\n            } else {\r\n                for( int ii = 0; ii < nperm; ii++) {\r\n                    if( minp0(ii) > P0s(ii) ) {\r\n                        minp0(ii) = P0s(ii);\r\n                    }\r\n                }\r\n            }\r\n            double tmp_pvalue = (double) tmp3 / (double) nperm;\r\n            pPerm0(j,k) = tmp_pvalue;\r\n            \r\n            if (tmp_pvalue <= minP_tmp) {\r\n                minP_tmp = tmp_pvalue;\r\n            }\r\n        }\r\n        \r\n        int count_pvalue = 0;\r\n        for(int j=0; j < nperm; j++) {\r\n            if( minP_tmp > minp0(j) ) {\r\n                count_pvalue = count_pvalue + 1;\r\n            }\r\n        }\r\n        \r\n        pPerm0(npow,k) = (double) (count_pvalue + 1) / (double) (nperm + 1);\r\n        \r\n    }\r\n    \r\n    return Rcpp::List::create(Rcpp::Named(\"pPerm0\") = pPerm0,\r\n                              Rcpp::Named(\"cov\") = cov_res );\r\n    \r\n}\r\n\r\n\r\n\r\n\r\n\r\n// [[Rcpp::depends(RcppArmadillo)]]\r\n// [[Rcpp::export()]]\r\nRcpp::List calcT0WsimV3 (arma::mat& CvSqrt,arma::mat& weight, arma::vec powV, SEXP pBigMat, SEXP pBigMat3,int nperm) {\r\n    \r\n    //const int n = X1.n_rows;\r\n    const int npow = powV.n_rows;\r\n    const int nweight = weight.n_cols;\r\n    const int k = CvSqrt.n_rows;\r\n    // containers\r\n    XPtr<BigMatrix> xpMat(pBigMat);\r\n    arma::mat T0s = arma::Mat<double> ( (double *)xpMat->matrix(), xpMat->nrow(), xpMat->ncol(), false);\r\n    \r\n    XPtr<BigMatrix> xpMat3(pBigMat3);\r\n    arma::mat minp0_sign = arma::Mat<double> ( (double *)xpMat3->matrix(), xpMat3->nrow(), xpMat3->ncol(), false);\r\n    \r\n    for (int i = 0; i < nperm; i++) {\r\n        arma::mat U00 = arma::randn(k,1);\r\n        arma::mat U0 = CvSqrt * U00;\r\n        \r\n        for (int k = 0; k < nweight; k++) {\r\n            arma::mat weight_tmp = weight.col(k);\r\n            arma::mat U0tmp = weight_tmp % U0;\r\n            \r\n            for (int j = 0; j < npow; j++) {\r\n                if (powV[j] == 0) {\r\n                    arma::mat tmpU01 = abs(U0tmp);\r\n                    T0s(i,j * nweight + k) = tmpU01.max();\r\n                } else {\r\n                    T0s(i,j * nweight + k) = accu(pow(U0tmp,powV[j]));\r\n                }\r\n            }\r\n        }\r\n    }\r\n    \r\n    for (int k =0; k<nweight; k++) {\r\n        minp0_sign.col(k) = T0s.col(k);\r\n    }\r\n    \r\n    int npw = npow * nweight;\r\n    arma::mat cov_res(npw,npw);\r\n    cov_res.fill(0);\r\n    cov_res = arma::cov(T0s);\r\n    \r\n    arma::mat mean_res(npw,1);\r\n    mean_res.fill(0);\r\n    mean_res = arma::mean(T0s,0);\r\n    \r\n    return Rcpp::List::create(Rcpp::Named(\"cov\") = cov_res,\r\n                              Rcpp::Named(\"mean\") = mean_res );\r\n    \r\n}\r\n\r\n// [[Rcpp::depends(RcppArmadillo)]]\r\n// [[Rcpp::export()]]\r\nvoid calc_test_ch(arma::mat& cov, arma::mat& weight, arma::vec powV, SEXP pBigMat, SEXP pBigMat2,int nperm) {\r\n    \r\n    //const int n = X1.n_rows;\r\n    const int npow = powV.n_rows;\r\n    const int nweight = weight.n_cols;\r\n    \r\n    // containers\r\n    XPtr<BigMatrix> xpMat(pBigMat);\r\n    arma::mat T0s = arma::Mat<double> ( (double *)xpMat->matrix(), xpMat->nrow(), xpMat->ncol(), false);\r\n    \r\n    XPtr<BigMatrix> xpMat2(pBigMat2);\r\n    arma::mat T1s = arma::Mat<double> ( (double *)xpMat2->matrix(), xpMat2->nrow(), xpMat2->ncol(), false);\r\n    \r\n    arma::vec pPerm0(npow);\r\n    \r\n    for (int i = 0; i < npow; i++) {\r\n        \r\n        arma::mat subcov(nweight,nweight);\r\n        subcov.fill(0);\r\n        \r\n        subcov = cov.submat(i*nweight,i*nweight,((i+1)*nweight -1),((i+1)*nweight -1));\r\n        subcov = subcov.i();\r\n        \r\n        for (int j =0; j < nperm; j++) {\r\n            arma::vec tmp_ts = T0s.row(j);\r\n            arma::mat tmp_ts2(1,nweight);\r\n            tmp_ts2 = tmp_ts.subvec(i*nweight,((i+1) * nweight -1));\r\n            arma::mat tmp = tmp_ts2.t() * subcov * tmp_ts2;\r\n            T1s(j,i) = tmp(0,0);\r\n        }\r\n    }\r\n}\r\n\r\n\r\n\r\n\r\n// [[Rcpp::depends(RcppArmadillo)]]\r\n// [[Rcpp::export()]]\r\nvoid calc_test_ch_V3(arma::mat& cov,arma::vec & mean, arma::mat& weight, arma::vec powV, SEXP pBigMat, SEXP pBigMat2,int nperm) {\r\n    \r\n    //const int n = X1.n_rows;\r\n    const int npow = powV.n_rows;\r\n    const int nweight = weight.n_cols;\r\n    \r\n    // containers\r\n    XPtr<BigMatrix> xpMat(pBigMat);\r\n    arma::mat T0s = arma::Mat<double> ( (double *)xpMat->matrix(), xpMat->nrow(), xpMat->ncol(), false);\r\n    \r\n    XPtr<BigMatrix> xpMat2(pBigMat2);\r\n    arma::mat T1s = arma::Mat<double> ( (double *)xpMat2->matrix(), xpMat2->nrow(), xpMat2->ncol(), false);\r\n    \r\n    arma::vec pPerm0(npow);\r\n    \r\n    for (int i = 0; i < npow; i++) {\r\n        \r\n        arma::mat subcov(nweight,nweight);\r\n        subcov.fill(0);\r\n        \r\n        subcov = cov.submat(i*nweight,i*nweight,((i+1)*nweight -1),((i+1)*nweight -1));\r\n        subcov = subcov.i();\r\n        \r\n        arma::mat tmp_mean(1,nweight);\r\n        tmp_mean = mean.subvec(i*nweight,((i+1) * nweight -1));\r\n        for (int j =0; j < nperm; j++) {\r\n            arma::vec tmp_ts = T0s.row(j);\r\n            arma::mat tmp_ts2(1,nweight);\r\n            \r\n            tmp_ts2 = tmp_ts.subvec(i*nweight,((i+1) * nweight -1));\r\n            tmp_ts2 = tmp_ts2 - tmp_mean;\r\n            arma::mat tmp = tmp_ts2.t() * subcov * tmp_ts2;\r\n            T1s(j,i) = tmp(0,0);\r\n        }\r\n    }\r\n}\r\n\r\n\r\n// [[Rcpp::depends(RcppArmadillo)]]\r\n// [[Rcpp::export()]]\r\nvoid calc_test_pan(arma::mat& cov, arma::mat& weight, arma::vec powV, SEXP pBigMat,SEXP pBigMat2, int nperm) {\r\n    \r\n    //const int n = X1.n_rows;\r\n    const int npow = powV.n_rows;\r\n    const int nweight = weight.n_cols;\r\n    \r\n    // containers\r\n    XPtr<BigMatrix> xpMat(pBigMat);\r\n    arma::mat T1s = arma::Mat<double> ( (double *)xpMat->matrix(), xpMat->nrow(), xpMat->ncol(), false);\r\n    \r\n    XPtr<BigMatrix> xpMat2(pBigMat2);\r\n    arma::mat T2s = arma::Mat<double> ( (double *)xpMat2->matrix(), xpMat2->nrow(), xpMat2->ncol(), false);\r\n    \r\n    arma::vec pPerm0(npow);\r\n    \r\n    for (int i = 0; i < npow; i++) {\r\n        \r\n        arma::mat subcov(nweight,nweight);\r\n        subcov.fill(0);\r\n        \r\n        subcov = cov.submat(i*nweight,i*nweight,((i+1)*nweight -1),((i+1)*nweight -1));\r\n        \r\n        for (int j =0; j < nperm; j++) {\r\n            arma::vec tmp_ts = T2s.row(j);\r\n            arma::mat tmp_ts2(1,nweight);\r\n            tmp_ts2 = tmp_ts.subvec(i*nweight,((i+1) * nweight -1));\r\n            arma::mat tmp = tmp_ts2.t() * subcov * tmp_ts2;\r\n            T1s(j,i) = tmp(0,0);\r\n        }\r\n    }\r\n}\r\n\r\n// [[Rcpp::depends(RcppArmadillo)]]\r\n// [[Rcpp::export()]]\r\narma::mat calc_test_ts(arma::mat& cov, arma::mat& weight, arma::vec powV, arma::vec Ts) {\r\n    \r\n    //const int n = X1.n_rows;\r\n    const int npow = powV.n_rows;\r\n    const int nweight = weight.n_cols;\r\n    \r\n    arma::mat Ts2(npow,1);\r\n    Ts2.fill(0);\r\n    \r\n    for (int i = 0; i < npow; i++) {\r\n        arma::mat subcov(nweight,nweight);\r\n        subcov.fill(0);\r\n        \r\n        subcov = cov.submat(i*nweight,i*nweight,((i+1)*nweight -1),((i+1)*nweight -1));\r\n        \r\n        arma::mat tmp_ts2(1,nweight);\r\n        tmp_ts2 = Ts.subvec(i*nweight,((i+1)*nweight -1));\r\n        arma::mat tmp =  tmp_ts2.t() * subcov * tmp_ts2;\r\n        Ts2(i,0) = tmp(0,0);\r\n    }\r\n    \r\n    return Ts2;\r\n}\r\n\r\n\r\n\r\n// [[Rcpp::depends(RcppArmadillo)]]\r\n// [[Rcpp::export()]]\r\narma::mat calc_test_ts_V3(arma::mat& cov, arma::vec & mean, arma::mat& weight, arma::vec powV, arma::vec Ts) {\r\n    \r\n    //const int n = X1.n_rows;\r\n    const int npow = powV.n_rows;\r\n    const int nweight = weight.n_cols;\r\n    \r\n    arma::mat Ts2(npow,1);\r\n    Ts2.fill(0);\r\n    \r\n    for (int i = 0; i < npow; i++) {\r\n        arma::mat subcov(nweight,nweight);\r\n        subcov.fill(0);\r\n        \r\n        subcov = cov.submat(i*nweight,i*nweight,((i+1)*nweight -1),((i+1)*nweight -1));\r\n        subcov = subcov.i();\r\n        \r\n        arma::mat tmp_mean(1,nweight);\r\n        tmp_mean = mean.subvec(i*nweight,((i+1) * nweight -1));\r\n        \r\n        arma::mat tmp_ts2(1,nweight);\r\n        tmp_ts2 = Ts.subvec(i*nweight,((i+1)*nweight -1));\r\n        tmp_ts2 = tmp_ts2 - tmp_mean;\r\n        \r\n        arma::mat tmp =  tmp_ts2.t() * subcov * tmp_ts2;\r\n        Ts2(i,0) = tmp(0,0);\r\n    }\r\n    \r\n    return Ts2;\r\n}\r\n\r\n\r\n// [[Rcpp::depends(RcppArmadillo)]]\r\n// [[Rcpp::export()]]\r\nRcpp::List calc_p_ch (arma::vec powV, arma::vec Tsabs, SEXP pBigMat2, int nperm) {\r\n    \r\n    //const int n = X1.n_rows;\r\n    const int npow = powV.n_rows;\r\n    \r\n    // containers\r\n    XPtr<BigMatrix> xpMat2(pBigMat2);\r\n    arma::mat T1s = arma::Mat<double> ( (double *)xpMat2->matrix(), xpMat2->nrow(), xpMat2->ncol(), false);\r\n    \r\n    arma::vec minp0(nperm);\r\n    arma::vec P0s(nperm);\r\n    arma::vec pPerm0(npow);\r\n    \r\n    for (int i = 0; i < npow; i++) {\r\n        \r\n        // Calculate p-value\r\n        arma::vec T1stmp = T1s.col(i);\r\n        int tmp3 = 0;\r\n        \r\n        arma::vec rankarma  = avg_rank(T1stmp);\r\n        \r\n        for( int tt=0 ; tt < nperm ; tt++) {\r\n            if( Tsabs(i)  <= T1stmp(tt) ) {\r\n                tmp3++;\r\n            }\r\n            P0s(tt) = (double) rankarma(tt) / (double) nperm;\r\n        }\r\n        \r\n        \r\n        if(i == 0) {\r\n            minp0 = P0s;\r\n        } else {\r\n            for( int ii = 0; ii < nperm; ii++) {\r\n                if( minp0(ii) > P0s(ii) ) {\r\n                    minp0(ii) = P0s(ii);\r\n                }\r\n            }\r\n        }\r\n        pPerm0(i) = (double) tmp3 / (double) nperm;\r\n        \r\n    }\r\n    \r\n    return Rcpp::List::create(Rcpp::Named(\"minp0\") = minp0,\r\n                              Rcpp::Named(\"pPerm0\") = pPerm0 );\r\n    \r\n}\r\n\r\n\r\n// [[Rcpp::depends(RcppArmadillo)]]\r\n// [[Rcpp::export()]]\r\nRcpp::List calc_p_ch_pan (arma::vec powV, arma::vec Tsabs, SEXP pBigMat, int nperm) {\r\n    \r\n    //const int n = X1.n_rows;\r\n    const int npow = powV.n_rows;\r\n    \r\n    // containers\r\n    XPtr<BigMatrix> xpMat(pBigMat);\r\n    arma::mat T1s = arma::Mat<double> ( (double *)xpMat->matrix(), xpMat->nrow(), xpMat->ncol(), false);\r\n    \r\n    \r\n    arma::vec minp0(nperm);\r\n    arma::vec P0s(nperm);\r\n    arma::vec pPerm0(npow);\r\n    \r\n    for (int i = 0; i < npow; i++) {\r\n        \r\n        // Calculate p-value\r\n        arma::vec T1stmp = T1s.col(i);\r\n        int tmp3 = 0;\r\n        \r\n        arma::vec rankarma  = avg_rank(T1stmp);\r\n        \r\n        for( int tt=0 ; tt < nperm ; tt++) {\r\n            if( Tsabs(i)  <= T1stmp(tt) ) {\r\n                tmp3++;\r\n            }\r\n            P0s(tt) = (double) rankarma(tt) / (double) nperm;\r\n        }\r\n        \r\n        \r\n        if(i == 0) {\r\n            minp0 = P0s;\r\n        } else {\r\n            for( int ii = 0; ii < nperm; ii++) {\r\n                if( minp0(ii) > P0s(ii) ) {\r\n                    minp0(ii) = P0s(ii);\r\n                }\r\n            }\r\n        }\r\n        pPerm0(i) = (double) tmp3 / (double) nperm;\r\n        \r\n    }\r\n    \r\n    return Rcpp::List::create(Rcpp::Named(\"minp0\") = minp0,\r\n                              Rcpp::Named(\"pPerm0\") = pPerm0 );\r\n    \r\n}\r\n\r\n\r\n// [[Rcpp::depends(RcppArmadillo)]]\r\n// [[Rcpp::export()]]\r\nRcpp::List calc_p_pan (arma::vec Tsabs,SEXP pBigMat,SEXP pBigMat2,SEXP pBigMat3, int nTs,int nweight, int nperm) {\r\n    \r\n    // containers\r\n    XPtr<BigMatrix> xpMat(pBigMat);\r\n    arma::mat T0s = arma::Mat<double> ( (double *)xpMat->matrix(), xpMat->nrow(), xpMat->ncol(), false);\r\n    \r\n    XPtr<BigMatrix> xpMat2(pBigMat2);\r\n    arma::mat T2s = arma::Mat<double> ( (double *)xpMat2->matrix(), xpMat2->nrow(), xpMat2->ncol(), false);\r\n    \r\n    \r\n    XPtr<BigMatrix> xpMat3(pBigMat3);\r\n    arma::mat minp0_sign = arma::Mat<double> ( (double *)xpMat3->matrix(), xpMat3->nrow(), xpMat3->ncol(), false);\r\n    \r\n    \r\n    // T0s = arma::abs(T0s);\r\n    \r\n    arma::vec minp0(nperm);\r\n    arma::vec P0s(nperm);\r\n    arma::vec pPerm0(nTs);\r\n    \r\n    \r\n    for (int i = 0; i < nTs; i++) {\r\n        \r\n        // Calculate p-value\r\n        arma::vec T1stmp = T0s.col(i);\r\n        int tmp3 = 0;\r\n        \r\n        arma::vec rankarma  = avg_rank(T1stmp);\r\n        \r\n        int minp0_index = i - floor(i/nweight) * nweight;\r\n        \r\n        for( int tt=0 ; tt < nperm ; tt++) {\r\n            if( Tsabs(i)  <= T1stmp(tt) ) {\r\n                tmp3++;\r\n            }\r\n            \r\n            NumericVector tmp_res;\r\n            tmp_res = (double) rankarma(tt) / (double) nperm;\r\n            \r\n            int p0_sign = -1;\r\n            if (minp0_sign(tt,minp0_index) >0) {\r\n                p0_sign = 1;\r\n            }\r\n            \r\n            tmp_res = qnorm(1 - tmp_res/2) * p0_sign;\r\n            T2s(tt,i) = tmp_res[0];\r\n        }\r\n        \r\n        pPerm0(i) = (double) tmp3 / (double) nperm;\r\n    }\r\n    \r\n    arma::mat cov_res(nTs,nTs);\r\n    cov_res.fill(0);\r\n    cov_res = arma::cov(T2s);\r\n    \r\n    return Rcpp::List::create(Rcpp::Named(\"pPerm0\") = pPerm0,\r\n                              Rcpp::Named(\"cov\") = cov_res );\r\n    \r\n}\r\n\r\n\r\n// [[Rcpp::depends(RcppArmadillo)]]\r\n// [[Rcpp::export()]]\r\narma::vec calc_aSPU (arma::mat p_cov, SEXP pBigMat2, int nperm) {\r\n    \r\n    // containers\r\n    XPtr<BigMatrix> xpMat2(pBigMat2);\r\n    arma::mat minp0 = arma::Mat<double> ( (double *)xpMat2->matrix(), xpMat2->nrow(), xpMat2->ncol(), false);\r\n    \r\n    arma::vec res(nperm);\r\n    \r\n    for (int i = 0; i < nperm; i++) {\r\n        arma::mat tmp =  minp0.row(i) * p_cov * minp0.row(i).t();\r\n        res(i) = tmp(0,0);\r\n    }\r\n    \r\n    return res;\r\n}\r\n\r\n\r\n\r\n// [[Rcpp::depends(RcppArmadillo)]]\r\n// [[Rcpp::export()]]\r\nRcpp::List daSPU_calcT0Wsim4 (arma::mat& CvSqrt,arma::mat& weight, arma::vec powV, arma::vec Tsabs, SEXP pBigMat, SEXP pBigMat2,SEXP pBigMat3,int nperm) {\r\n    \r\n    //const int n = X1.n_rows;\r\n    const int npow = powV.n_rows;\r\n    const int nweight = weight.n_cols;\r\n    const int k = CvSqrt.n_rows;\r\n    // containers\r\n    XPtr<BigMatrix> xpMat(pBigMat);\r\n    arma::mat T0s = arma::Mat<double> ( (double *)xpMat->matrix(), xpMat->nrow(), xpMat->ncol(), false);\r\n    \r\n    // containers\r\n    XPtr<BigMatrix> xpMat2(pBigMat2);\r\n    arma::mat minp0 = arma::Mat<double> ( (double *)xpMat2->matrix(), xpMat2->nrow(), xpMat2->ncol(), false);\r\n    \r\n    // containers\r\n    XPtr<BigMatrix> xpMat3(pBigMat3);\r\n    arma::mat minp0_sign = arma::Mat<double> ( (double *)xpMat3->matrix(), xpMat3->nrow(), xpMat3->ncol(), false);\r\n    \r\n    for (int i = 0; i < nperm; i++) {\r\n        arma::mat U00 = arma::randn(k,1);\r\n        arma::mat U0 = CvSqrt * U00;\r\n        \r\n        for (int k = 0; k < nweight; k++) {\r\n            arma::mat weight_tmp = weight.col(k);\r\n            arma::mat U0tmp = weight_tmp % U0;\r\n            \r\n            for (int j = 0; j < npow; j++) {\r\n                if (powV[j] == 0) {\r\n                    arma::mat tmpU01 = abs(U0tmp);\r\n                    T0s(i,k * npow + j) = tmpU01.max();\r\n                } else {\r\n                    T0s(i,k * npow + j) = accu(pow(U0tmp,powV[j]));\r\n                }\r\n            }\r\n        }\r\n    }\r\n    \r\n    for (int k =0; k<nweight; k++) {\r\n        minp0_sign.col(k) = T0s.col(k * npow);\r\n    }\r\n    \r\n    T0s = arma::abs(T0s);\r\n    \r\n    arma::vec minp0_tmp(nperm);\r\n    \r\n    arma::vec P0s(nperm);\r\n    arma::vec pPerm0(npow* nweight);\r\n    \r\n    for (int k = 0; k < nweight; k++) {\r\n        \r\n        for (int i = (npow*k); i < (npow* (k + 1)); i++) {\r\n            \r\n            // Calculate p-value\r\n            arma::vec T0stmp = T0s.col(i);\r\n            int tmp3 = 0;\r\n            arma::vec rankarma  = avg_rank(T0stmp);\r\n            \r\n            for( int tt=0 ; tt < nperm ; tt++) {\r\n                if( Tsabs(i)  <= T0stmp(tt) ) {\r\n                    tmp3++;\r\n                }\r\n                \r\n                P0s(tt) = (double) rankarma(tt) / (double) nperm;\r\n            }\r\n            \r\n            \r\n            if(i == 0) {\r\n                minp0_tmp = P0s;\r\n            } else {\r\n                for( int ii = 0; ii < nperm; ii++) {\r\n                    if( minp0_tmp(ii) > P0s(ii) ) {\r\n                        minp0_tmp(ii) = P0s(ii);\r\n                    }\r\n                }\r\n            }\r\n            pPerm0(i) = (double) tmp3/ (double) nperm;\r\n        }\r\n        \r\n        minp0.col(k) = minp0_tmp;\r\n    }\r\n    \r\n    for (int k = 0; k < nweight; k++) {\r\n        for (int i = 0; i <nperm; i++) {\r\n            NumericVector tmp_res;\r\n            \r\n            tmp_res = minp0(i,k);\r\n            int p0_sign = -1;\r\n            if (minp0_sign(i,k) >0) {\r\n                p0_sign = 1;\r\n            }\r\n            tmp_res = qnorm(1 - tmp_res/2) * p0_sign;\r\n            minp0(i,k) = tmp_res[0];\r\n        }\r\n    }\r\n    \r\n    arma::mat cov_res(nweight,nweight);\r\n    cov_res.fill(0);\r\n    cov_res = arma::cov(minp0);\r\n    \r\n    return Rcpp::List::create(Rcpp::Named(\"pPerm0\") = pPerm0,\r\n                              Rcpp::Named(\"cov\") = cov_res );\r\n    \r\n    \r\n}\r\n\r\n\r\n// [[Rcpp::depends(RcppArmadillo)]]\r\n// [[Rcpp::export()]]\r\narma::vec daSPU_calc_aSPU (arma::mat p_cov, SEXP pBigMat2, int nperm) {\r\n    \r\n    // containers\r\n    XPtr<BigMatrix> xpMat2(pBigMat2);\r\n    arma::mat minp0 = arma::Mat<double> ( (double *)xpMat2->matrix(), xpMat2->nrow(), xpMat2->ncol(), false);\r\n    \r\n    arma::vec res(nperm);\r\n    \r\n    for (int i = 0; i < nperm; i++) {\r\n        arma::mat tmp =  minp0.row(i) * p_cov * minp0.row(i).t();\r\n        res(i) = tmp(0,0);\r\n    }\r\n    \r\n    return res;\r\n}\r\n\r\n\r\n// [[Rcpp::depends(RcppArmadillo)]]\r\n// [[Rcpp::export()]]\r\nRcpp::List calcT0Wsim2 (arma::mat& CvSqrt,arma::mat& weight, arma::vec pow1, arma::vec pow2, int nperm) {\r\n    \r\n    //const int n = X1.n_rows;\r\n    const int n_pow1 = pow1.size();\r\n    const int n_pow2 = pow2.size();\r\n    const int n_weight = weight.n_cols;\r\n    \r\n    const int k = CvSqrt.n_rows;\r\n    // containers\r\n    arma::mat T0s1(n_pow1,n_weight);\r\n    T0s1.fill(0);\r\n    arma::mat T0s(nperm,n_pow1 * n_pow2);\r\n    T0s.fill(0);\r\n    \r\n    for (int i = 0; i < nperm; i++) {\r\n        arma::mat U00 = arma::randn(k,1);\r\n        arma::mat U0 = CvSqrt * U00;\r\n        \r\n        for (int i2 = 0; i2 < n_weight; i2 ++) {\r\n            arma::mat U0tmp = weight.col(i2) % U0;\r\n            for (int j1 = 0; j1 < n_pow1; j1++) {\r\n                if( pow1[j1] > 0) {\r\n                    arma::vec tmp1 = pow(U0tmp,pow1[j1]);\r\n                    double tmp2 = sum(tmp1);\r\n                    \r\n                    if( tmp2 > 0 ) {\r\n                        T0s1(j1,i2) = pow(std::abs(tmp2), 1/pow1[j1]);\r\n                    } else {\r\n                        T0s1(j1,i2) = -pow(std::abs(tmp2), 1/pow1[j1]);\r\n                    }\r\n                    \r\n                } else {\r\n                    arma::vec tmp1 = abs(U0tmp);\r\n                    T0s1(j1,i2) = max(tmp1);\r\n                }\r\n            }\r\n        }\r\n        \r\n        for (int j1 = 0; j1 < n_pow1; j1++) {\r\n            for (int j2 = 0; j2 < n_pow2; j2++) {\r\n                if (pow2[j2] > 0) {\r\n                    arma::mat tmp3 = pow(T0s1.row(j1),pow2[j2]);\r\n                    T0s(i, j2 * n_pow1 + j1) = accu(tmp3);\r\n                } else {\r\n                    T0s(i, j2 * n_pow1 + j1) = max(abs(T0s1.row(j1)));\r\n                }\r\n            }\r\n        }\r\n    }\r\n    \r\n    \r\n    Rcpp::List res;\r\n    res[\"T0s\"] =T0s;\r\n    \r\n    return(res);\r\n}\r\n\r\n\r\n\r\n\r\n\r\n// [[Rcpp::depends(RcppArmadillo)]]\r\n// [[Rcpp::export()]]\r\narma::vec daSPU_calcT0 (arma::mat& CvSqrt,arma::mat& weight, arma::vec pow1, arma::vec pow2,  arma::vec Tsabs,SEXP pBigMat, int nperm) {\r\n    \r\n    //const int n = X1.n_rows;\r\n    const int n_pow1 = pow1.size();\r\n    const int n_pow2 = pow2.size();\r\n    const int n_pow = n_pow1 * n_pow2;\r\n    const int n_weight = weight.n_cols;\r\n    \r\n    const int k = CvSqrt.n_rows;\r\n    // containers\r\n    arma::mat T0s1(n_pow1,n_weight);\r\n    T0s1.fill(0);\r\n    \r\n    XPtr<BigMatrix> xpMat(pBigMat);\r\n    arma::mat T0s = arma::Mat<double> ( (double *)xpMat->matrix(), xpMat->nrow(), xpMat->ncol(), false);\r\n    \r\n    for (int i = 0; i < nperm; i++) {\r\n        arma::mat U00 = arma::randn(k,1);\r\n        arma::mat U0 = CvSqrt * U00;\r\n        \r\n        for (int i2 = 0; i2 < n_weight; i2 ++) {\r\n            arma::mat U0tmp = weight.col(i2) % U0;\r\n            for (int j1 = 0; j1 < n_pow1; j1++) {\r\n                if( pow1[j1] > 0) {\r\n                    arma::vec tmp1 = pow(U0tmp,pow1[j1]);\r\n                    double tmp2 = sum(tmp1);\r\n                    \r\n                    if( tmp2 > 0 ) {\r\n                        T0s1(j1,i2) = pow(std::abs(tmp2), 1/pow1[j1]);\r\n                    } else {\r\n                        T0s1(j1,i2) = -pow(std::abs(tmp2), 1/pow1[j1]);\r\n                    }\r\n                    \r\n                } else {\r\n                    arma::vec tmp1 = abs(U0tmp);\r\n                    T0s1(j1,i2) = max(tmp1);\r\n                }\r\n            }\r\n        }\r\n        \r\n        for (int j1 = 0; j1 < n_pow1; j1++) {\r\n            for (int j2 = 0; j2 < n_pow2; j2++) {\r\n                if (pow2[j2] > 0) {\r\n                    arma::mat tmp3 = pow(T0s1.row(j1),pow2[j2]);\r\n                    T0s(i, j2 * n_pow1 + j1) = accu(tmp3);\r\n                } else {\r\n                    T0s(i, j2 * n_pow1 + j1) = max(abs(T0s1.row(j1)));\r\n                }\r\n            }\r\n        }\r\n    }\r\n    \r\n    //\r\n    T0s = arma::abs(T0s);\r\n    \r\n    arma::vec minp0(nperm);\r\n    arma::vec P0s(nperm);\r\n    arma::vec pPerm0(n_pow + 1);\r\n    double minP_tmp = 1.0;\r\n\r\n    for(int k = 0; k < n_pow; k++) {\r\n        \r\n        \r\n        // Calculate p-value\r\n        arma::vec T0stmp = T0s.col(k);\r\n        int tmp3 = 0;\r\n        arma::vec rankarma  = avg_rank(T0stmp);\r\n        \r\n        for( int tt=0 ; tt < nperm ; tt++) {\r\n            if( Tsabs(k)  <= T0stmp(tt) ) {\r\n                tmp3++;\r\n            }\r\n            \r\n            P0s(tt) = (double) rankarma(tt) / (double) nperm;\r\n        }\r\n        \r\n        if(k == 0) {\r\n            minp0 = P0s;\r\n        } else {\r\n            for( int ii = 0; ii < nperm; ii++) {\r\n                if( minp0(ii) > P0s(ii) ) {\r\n                    minp0(ii) = P0s(ii);\r\n                }\r\n            }\r\n        }\r\n        double tmp_pvalue = (double) tmp3 / (double) nperm;\r\n        pPerm0(k) = tmp_pvalue;\r\n        \r\n        if (tmp_pvalue <= minP_tmp) {\r\n            minP_tmp = tmp_pvalue;\r\n        }\r\n        \r\n    }\r\n    \r\n    int count_pvalue = 0;\r\n    for(int j=0; j < nperm; j++) {\r\n        if( minP_tmp >= minp0(j) ) {\r\n            count_pvalue = count_pvalue + 1;\r\n        }\r\n    }\r\n    \r\n    pPerm0(n_pow) = (double) (count_pvalue + 1) / (double) (nperm + 1);\r\n\r\n    \r\n    return pPerm0;\r\n}\r\n\r\n\r\n// [[Rcpp::export]]\r\nvoid set_seed(unsigned int seed) {\r\n    Rcpp::Environment base_env(\"package:base\");\r\n    Rcpp::Function set_seed_r = base_env[\"set.seed\"];\r\n    set_seed_r(seed);\r\n}\r\n\r\n// This function is taken from http://stackoverflow.com/questions/39153082/rcpp-rank-function-that-does-average-ties\r\nclass Comparator {\r\n    private:\r\n    const Rcpp::NumericVector& ref;\r\n    \r\n    bool is_na(double x) const\r\n    {\r\n        return Rcpp::traits::is_na<REALSXP>(x);\r\n    }\r\n    \r\n    public:\r\n    Comparator(const Rcpp::NumericVector& ref_)\r\n    : ref(ref_)\r\n    {}\r\n    \r\n    bool operator()(const int ilhs, const int irhs) const\r\n    {\r\n        double lhs = ref[ilhs], rhs = ref[irhs];\r\n        if (is_na(lhs)) return false;\r\n        if (is_na(rhs)) return true;\r\n        return lhs < rhs;\r\n    }\r\n};\r\n\r\n\r\n// [[Rcpp::export]]\r\nRcpp::NumericVector avg_rank2(Rcpp::NumericVector x)\r\n{\r\n    R_xlen_t sz = x.size();\r\n    Rcpp::IntegerVector w = Rcpp::seq(0, sz - 1);\r\n    std::sort(w.begin(), w.end(), Comparator(x));\r\n    \r\n    Rcpp::NumericVector r = Rcpp::no_init_vector(sz);\r\n    for (R_xlen_t n, i = 0; i < sz; i += n) {\r\n        n = 1;\r\n        while (i + n < sz && x[w[i]] == x[w[i + n]]) ++n;\r\n        for (R_xlen_t k = 0; k < n; k++) {\r\n            r[w[i + k]] = i + (n + 1) / 2.;\r\n        }\r\n    }\r\n    \r\n    return r;\r\n}\r\n\r\n\r\n// [[Rcpp::depends(RcppArmadillo)]]\r\n// [[Rcpp::export]]\r\nRcpp::List aSPUsPathEngine2(Rcpp::List CH, Rcpp::List CHcovSq, arma::vec pow1, arma::vec pow2, int nGenes, int n_perm, int k, arma::vec nSNPs0, arma::vec nChrom0, arma::vec Ts2, int s) {\r\n    const int n_ch = CH.size();\r\n    const int n_pow1 = pow1.size();\r\n    const int n_pow2 = pow2.size();\r\n    \r\n    arma::vec T0s(n_perm);\r\n    arma::vec T0st(nGenes*n_pow1);\r\n    arma::vec Ts2t(n_pow1*n_pow2);\r\n    arma::vec pPerm0(n_pow1*n_pow2);\r\n    arma::vec minp0(n_perm);\r\n    arma::vec P0s(n_perm);\r\n    \r\n    // iterate for pow2\r\n    for(int j2=0 ; j2 < n_pow2; j2++) {\r\n        // iterate for pow1\r\n        for(int j=0 ; j < n_pow1; j++) {\r\n            \r\n            // set seed to use same random numbers for same b's\r\n            // This is necessary to use efficient memory\r\n            set_seed(s);\r\n            for(int b=0; b < n_perm; b++) {\r\n                \r\n                // Generate Score from null distribution\r\n                Rcpp::NumericVector U00 = rnorm(k,0,1);\r\n                arma::vec u0 = as<arma::vec>(U00);\r\n                arma::vec U0(1);\r\n                \r\n                int SNPstart = 0;\r\n                // iterate for chromosome\r\n                for(int b2 = 0; b2 < n_ch ; b2++) {\r\n                    \r\n                    \r\n                    // itreate for chromosome\r\n                    if( b2 != 0) {\r\n                        SNPstart = sum( nChrom0.subvec(0,b2-1) ) ;\r\n                    }\r\n                    int idx1 = SNPstart;\r\n                    int idx2 = SNPstart+nChrom0(b2)-1;\r\n                    \r\n                    arma::vec TT = as<arma::mat>(CHcovSq[b2])*u0.subvec(idx1, idx2) ;\r\n                    U0 = join_cols(U0,TT) ;\r\n                }\r\n                \r\n                arma::vec UU2 = U0.subvec(1,U0.size()-1);\r\n                \r\n                \r\n                // iterate for genes\r\n                SNPstart = 0;\r\n                for(int iGene = 0 ; iGene < nGenes ; iGene++ ) {\r\n                    \r\n                    // calculate starting and ending position of each gene from nSNPs0 vector\r\n                    if( iGene != 0) {\r\n                        SNPstart = sum( nSNPs0.subvec(0,iGene-1) ) ;\r\n                    }\r\n                    int idx1 = SNPstart;\r\n                    int idx2 = SNPstart+nSNPs0(iGene)-1;\r\n                    \r\n                    // calculate 1st level test statistic\r\n                    if( pow1[j] > 0) {\r\n                        arma::vec tmp1 = pow(UU2.subvec(idx1, idx2),pow1[j]);\r\n                        double tmp2 = sum(tmp1);\r\n                        \r\n                        if( tmp2 > 0 ) {\r\n                            T0st(j*nGenes+iGene) = pow(std::abs(tmp2)/nSNPs0[iGene] , 1/pow1[j]);\r\n                        } else {\r\n                            T0st(j*nGenes+iGene) = -pow(std::abs(tmp2)/nSNPs0[iGene] , 1/pow1[j]);\r\n                        }\r\n                        \r\n                    } else {\r\n                        arma::vec T0tp = abs(UU2.subvec(idx1, idx2));\r\n                        T0st(j*nGenes+iGene) = max(abs(T0tp));\r\n                    }\r\n                }\r\n                \r\n                // calculate 2nd level test statistics\r\n                if( pow2[j2] > 0) {\r\n                    arma::vec tmp3 = pow(T0st.subvec(j*nGenes,(j+1)*nGenes-1), pow2[j2]);\r\n                    double tmp4 = sum(tmp3);\r\n                    T0s(b) = tmp4;\r\n                } else {\r\n                    T0s(b) = max( arma::abs(T0st.subvec(j*nGenes,(j+1)*nGenes-1)) ) ;\r\n                }\r\n            }\r\n            \r\n            \r\n            // Calculate P-values\r\n            int tmp3 = 0;\r\n            arma::vec T0sabs = arma::abs(T0s);\r\n            Rcpp::NumericVector a( T0sabs.begin(), T0sabs.end() );\r\n            Rcpp::NumericVector ranka = avg_rank2(a);\r\n            arma::vec rankarma = as<arma::vec>(ranka);\r\n            \r\n            for( int tt=0 ; tt < n_perm ; tt++) {\r\n                if( std::abs(Ts2(j2*n_pow1 + j) ) <= std::abs(T0s(tt))) {\r\n                    tmp3++;\r\n                }\r\n                \r\n                P0s(tt) = (double) (n_perm - rankarma(tt) + 1) / (double) n_perm;\r\n            }\r\n            \r\n            minp0 = P0s;\r\n            \r\n            if(j == 1) {\r\n                for( int ii=0; ii < n_perm; ii++) {\r\n                    minp0(ii) = P0s(ii);\r\n                }\r\n            } else {\r\n                for( int ii=0; ii < n_perm; ii++) {\r\n                    if( minp0(ii) > P0s(ii) ) {\r\n                        minp0(ii) = P0s(ii);\r\n                    }\r\n                }\r\n            }\r\n            \r\n            pPerm0(j2*n_pow1 + j) = (double) tmp3 / (double) n_perm;\r\n            \r\n        }\r\n    }\r\n    return Rcpp::List::create(Rcpp::Named(\"minp0\") = minp0,\r\n                              Rcpp::Named(\"pPerm0\") = pPerm0,\r\n                              Rcpp::Named(\"P0s\") = P0s);\r\n}\r\n", "meta": {"hexsha": "362a4a30b28c98344a761fe75f6880cd664d17cf", "size": 34699, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/GMaSPU_support.cpp", "max_stars_repo_name": "blackcavalry/iwas2", "max_stars_repo_head_hexsha": "5742045ae832a8e17ac997faab8b3b6978fecabd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/GMaSPU_support.cpp", "max_issues_repo_name": "blackcavalry/iwas2", "max_issues_repo_head_hexsha": "5742045ae832a8e17ac997faab8b3b6978fecabd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GMaSPU_support.cpp", "max_forks_repo_name": "blackcavalry/iwas2", "max_forks_repo_head_hexsha": "5742045ae832a8e17ac997faab8b3b6978fecabd", "max_forks_repo_licenses": ["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.625772286, "max_line_length": 187, "alphanum_fraction": 0.4432116199, "num_tokens": 10569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2999748917119345}}
{"text": "\n/******************************************************************************\n\n  Markov random field model for regular 2D lattice.\n\n  Copyright (c) 2009 - 2012\n  Alexander Rukletsov <rukletsov@gmail.com>\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  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\n  THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS \"AS IS\" AND\n  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 AUTHOR 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\n  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\n  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n  SUCH DAMAGE.\n\n*******************************************************************************/\n\n#ifndef MRF_2D_HPP_1140ED81_1E3E_4AEB_AFBB_6CA70FE3EF9B_\n#define MRF_2D_HPP_1140ED81_1E3E_4AEB_AFBB_6CA70FE3EF9B_\n\n#include <cstddef>\n#include <cmath>\n#include <stdexcept>\n#include <boost/random.hpp>\n#include <boost/assert.hpp>\n#include <boost/noncopyable.hpp>\n#include <boost/function.hpp>\n\n#include \"bo/core/raw_image_2d.hpp\"\n\nnamespace bo {\nnamespace mrf {\n\n// A class representing a Markov random field on a regular 2D lattice. Operates on\n// random field configuration using given observation and clique functions. Only first\n// order (pairwise) neighbourhood is supproted. No copies of an instance are allowed.\ntemplate <typename NodeType, typename DataType, typename RealType>\nclass MRF2D: public boost::noncopyable\n{\npublic:\n    typedef NodeType& reference;\n    typedef const NodeType& const_reference;\n\n    typedef RawImage2D<NodeType> RandomLattice;\n    typedef RawImage2D<DataType> DataLattice;\n    typedef boost::function<RealType (DataType, NodeType)> LikelihoodEnergy;\n    typedef boost::function<RealType (NodeType, NodeType)> PriorEnergy;\n\n    MRF2D(const RandomLattice& initial_configuration, const DataLattice& observation,\n          LikelihoodEnergy likelihood, PriorEnergy prior);\n\n    RealType compute_full_energy() const;\n    RealType compute_local_energy(NodeType val, std::size_t col, std::size_t row) const;\n    RealType compute_local_likelihood(NodeType val, std::size_t col, std::size_t row) const;\n\n    const_reference operator()(std::size_t col, std::size_t row) const;\n    reference operator()(std::size_t col, std::size_t row);\n\n    std::size_t width() const;\n    std::size_t height() const;\n\nprivate:\n    RealType right_clique_(NodeType val, std::size_t col, std::size_t row) const;\n    RealType down_clique_(NodeType val, std::size_t col, std::size_t row) const;\n    RealType left_clique_(NodeType val, std::size_t col, std::size_t row) const;\n    RealType up_clique_(NodeType val, std::size_t col, std::size_t row) const;\n\n    RealType prior_fun_(NodeType val, std::size_t neigh_col, std::size_t neigh_row) const;\n    RealType likelihood_fun_(NodeType val, std::size_t col, std::size_t row) const;\n\nprivate:\n    RandomLattice configuration_;\n    DataLattice observation_;\n    LikelihoodEnergy likelihood_;\n    PriorEnergy prior_;\n};\n\n\ntemplate <typename NodeType, typename DataType, typename RealType>\nMRF2D<NodeType, DataType, RealType>::MRF2D(const RandomLattice& initial_configuration,\n    const DataLattice& observation, LikelihoodEnergy likelihood, PriorEnergy prior):\n    configuration_(initial_configuration),\n    observation_(observation),\n    likelihood_(likelihood),\n    prior_(prior)\n{\n    // Check if the dimensions of observation and configuration are the same.\n    if ((configuration_.width() != observation_.width()) ||\n        (configuration_.height() != configuration_.height()))\n    {\n        BOOST_ASSERT(false && \"Dimensions of the configuration and observation do not coincide.\");\n        throw std::logic_error(\"MRF2D: dimensions of the random field lattice and the \"\n                               \"observation data must be the same.\");\n    }\n}\n\n// Computes full energy of the current MRF state. It takes sum over all zero order\n// (single node) and first order (every two adjacent nodes) cliques using corresponding\n// clique functions. In order to iterate over all first order cliques, for every\n// node we can consider only right and down neighbour except for some border nodes.\ntemplate <typename NodeType, typename DataType, typename RealType>\nRealType MRF2D<NodeType, DataType, RealType>::compute_full_energy() const\n{\n    RealType energy(0);\n\n    for (std::size_t col = 0; col < configuration_.width(); ++col) {\n        for (std::size_t row = 0; row < configuration_.height(); ++row) {\n            NodeType value = configuration_(col, row);\n            energy += (likelihood_fun_(value, col, row) +\n                       right_clique_(value, col, row) +\n                       down_clique_(value, col, row));\n    }   }\n\n    return energy;\n}\n\n// Computes a local energy of the neighbourhood of the given node with provided value.\n// Border checks are done inside corresponding clique functions.\ntemplate <typename NodeType, typename DataType, typename RealType>\nRealType MRF2D<NodeType, DataType, RealType>::compute_local_energy(NodeType val,\n    std::size_t col, std::size_t row) const\n{\n    // Compute likelihood energy for the given value at the given position.\n    RealType energy = likelihood_fun_(val, col, row);\n\n    // Compute prior energy of the given node given its neighbours.\n    energy += (right_clique_(val, col, row) + down_clique_(val, col, row) +\n               left_clique_(val, col, row) + up_clique_(val, col, row));\n\n    return energy;\n}\n\n// Computes a likelihood function for the given node with provided value.\ntemplate <typename NodeType, typename DataType, typename RealType>\nRealType MRF2D<NodeType, DataType, RealType>::compute_local_likelihood(NodeType val,\n    std::size_t col, std::size_t row) const\n{\n    return\n        likelihood_fun_(val, col, row);\n}\n\ntemplate <typename NodeType, typename DataType, typename RealType> inline\ntypename MRF2D<NodeType, DataType, RealType>::const_reference\nMRF2D<NodeType, DataType, RealType>::operator()(std::size_t col, std::size_t row) const\n{\n    return configuration_(col, row);\n}\n\ntemplate <typename NodeType, typename DataType, typename RealType> inline\ntypename MRF2D<NodeType, DataType, RealType>::reference\nMRF2D<NodeType, DataType, RealType>::operator()(std::size_t col, std::size_t row)\n{\n    return configuration_(col, row);\n}\n\ntemplate <typename NodeType, typename DataType, typename RealType> inline\nstd::size_t MRF2D<NodeType, DataType, RealType>::width() const\n{\n    return configuration_.width();\n}\n\ntemplate <typename NodeType, typename DataType, typename RealType> inline\nstd::size_t MRF2D<NodeType, DataType, RealType>::height() const\n{\n    return configuration_.height();\n}\n\n\n// Next four functions represent cliques and neighbourhood relations in the model.\n// They check for border overrun and call the associated clique function.\ntemplate <typename NodeType, typename DataType, typename RealType> inline\nRealType MRF2D<NodeType, DataType, RealType>::right_clique_(NodeType val,\n    std::size_t col, std::size_t row) const\n{\n    return\n        (col < configuration_.width() - 1) ? prior_fun_(val, col + 1, row) : RealType(0);\n}\n\ntemplate <typename NodeType, typename DataType, typename RealType> inline\nRealType MRF2D<NodeType, DataType, RealType>::down_clique_(NodeType val,\n    std::size_t col, std::size_t row) const\n{\n    return\n        (row < configuration_.height() - 1) ? prior_fun_(val, col, row + 1) : RealType(0);\n}\n\ntemplate <typename NodeType, typename DataType, typename RealType> inline\nRealType MRF2D<NodeType, DataType, RealType>::left_clique_(NodeType val,\n    std::size_t col, std::size_t row) const\n{\n    return\n        (col > 0) ? prior_fun_(val, col - 1, row) : RealType(0);\n}\n\ntemplate <typename NodeType, typename DataType, typename RealType> inline\nRealType MRF2D<NodeType, DataType, RealType>::up_clique_(NodeType val,\n    std::size_t col, std::size_t row) const\n{\n    return\n        (row > 0) ? prior_fun_(val, col, row - 1) : RealType(0);\n}\n\n// Computes prior energy for two nodes.\ntemplate <typename NodeType, typename DataType, typename RealType> inline\nRealType MRF2D<NodeType, DataType, RealType>::prior_fun_(NodeType val,\n    std::size_t neigh_col, std::size_t neigh_row) const\n{\n    return prior_(val, configuration_(neigh_col, neigh_row));\n}\n\n// Computes likelihood energy for the given node.\ntemplate <typename NodeType, typename DataType, typename RealType> inline\nRealType MRF2D<NodeType, DataType, RealType>::likelihood_fun_(NodeType val,\n    std::size_t col, std::size_t row) const\n{\n    return likelihood_(observation_(col, row), val);\n}\n\n} // namespace mrf\n} // namespace bo\n\n#endif // MRF_2D_HPP_1140ED81_1E3E_4AEB_AFBB_6CA70FE3EF9B_\n", "meta": {"hexsha": "ae9ea304b5aeab5e5c981034cd253041aba03311", "size": 9508, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Bo/mrf/mrf_2d.hpp", "max_stars_repo_name": "rukletsov/bo", "max_stars_repo_head_hexsha": "bfece9e8f910b0c8f522733854405bf0a801b0e8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T03:30:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T10:53:32.000Z", "max_issues_repo_path": "Bo/mrf/mrf_2d.hpp", "max_issues_repo_name": "rukletsov/bo", "max_issues_repo_head_hexsha": "bfece9e8f910b0c8f522733854405bf0a801b0e8", "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": "Bo/mrf/mrf_2d.hpp", "max_forks_repo_name": "rukletsov/bo", "max_forks_repo_head_hexsha": "bfece9e8f910b0c8f522733854405bf0a801b0e8", "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": 39.9495798319, "max_line_length": 98, "alphanum_fraction": 0.7297013042, "num_tokens": 2286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.29972491183530847}}
{"text": "#ifndef EDGE_PLANE_PARALLEL_HPP\n#define EDGE_PLANE_PARALLEL_HPP\n\n#include <Eigen/Dense>\n#include <g2o/core/base_binary_edge.h>\n#include <g2o/types/slam3d_addons/vertex_plane.h>\n\nnamespace g2o {\n\nclass EdgePlaneParallel : public BaseBinaryEdge<3, Eigen::Vector3d, VertexPlane, VertexPlane> {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  EdgePlaneParallel() : BaseBinaryEdge<3, Eigen::Vector3d, VertexPlane, VertexPlane>() {\n    _information.setIdentity();\n    _error.setZero();\n  }\n\n  void computeError() override {\n    const VertexPlane* v1 = static_cast<const VertexPlane*>(_vertices[0]);\n    const VertexPlane* v2 = static_cast<const VertexPlane*>(_vertices[1]);\n\n    Eigen::Vector3d normal1 = v1->estimate().normal();\n    Eigen::Vector3d normal2 = v2->estimate().normal();\n\n    if (normal1.dot(normal2) < 0.0) {\n      normal2 = -normal2;\n    }\n\n    _error = (normal2 - normal1) - _measurement;\n  }\n  virtual bool read(std::istream& is) override {\n    Eigen::Vector3d v;\n    for (int i = 0; i < 3; ++i) {\n      is >> v[i];\n    }\n\n    setMeasurement(v);\n    for(int i = 0; i < information().rows(); ++i) {\n      for(int j = i; j < information().cols(); ++j) {\n        is >> information()(i, j);\n        if(i != j) {\n          information()(j, i) = information()(i, j);\n        }\n      }\n    }\n\n    return true;\n  }\n\n  virtual bool write(std::ostream& os) const override {\n    for(int i = 0; i < 3; ++i) {\n      os << _measurement[i] << \" \";\n    }\n\n    for(int i = 0; i < information().rows(); ++i) {\n      for(int j = i; j < information().cols(); ++j) {\n        os << \" \" << information()(i, j);\n      };\n    }\n    return os.good();\n  }\n\n  virtual void setMeasurement(const Eigen::Vector3d& m) override { _measurement = m; }\n\n  virtual int measurementDimension() const override { return 3; }\n};\n\nclass EdgePlanePerpendicular : public BaseBinaryEdge<1, Eigen::Vector3d, VertexPlane, VertexPlane> {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  EdgePlanePerpendicular() : BaseBinaryEdge<1, Eigen::Vector3d, VertexPlane, VertexPlane>() {\n    _information.setIdentity();\n    _error.setZero();\n  }\n\n  void computeError() override {\n    const VertexPlane* v1 = static_cast<const VertexPlane*>(_vertices[0]);\n    const VertexPlane* v2 = static_cast<const VertexPlane*>(_vertices[1]);\n\n    Eigen::Vector3d normal1 = v1->estimate().normal().normalized();\n    Eigen::Vector3d normal2 = v2->estimate().normal().normalized();\n\n    _error[0] = normal1.dot(normal2);\n  }\n  virtual bool read(std::istream& is) override {\n    Eigen::Vector3d v;\n    for (int i = 0; i < 3; ++i) {\n      is >> v[i];\n    }\n\n    setMeasurement(v);\n    for(int i = 0; i < information().rows(); ++i) {\n      for(int j = i; j < information().cols(); ++j) {\n        is >> information()(i, j);\n        if (i != j) {\n          information()(j, i) = information()(i, j);\n        }\n      }\n    }\n\n    return true;\n  }\n\n  virtual bool write(std::ostream& os) const override {\n    for (int i = 0; i < 3; ++i) {\n      os << _measurement[i] << \" \";\n    }\n\n    for(int i = 0; i < information().rows(); ++i) {\n      for(int j = i; j < information().cols(); ++j) {\n        os << \" \" << information()(i, j);\n      };\n    }\n    return os.good();\n  }\n\n  virtual void setMeasurement(const Eigen::Vector3d& m) override { _measurement = m; }\n\n  virtual int measurementDimension() const override { return 3; }\n};\n\n}  // namespace g2o\n\n#endif  // EDGE_PLANE_PARALLEL_HPP\n", "meta": {"hexsha": "014fc829e07fddcba3954d5864de0d3038fd2c13", "size": 3409, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/g2o/edge_plane_parallel.hpp", "max_stars_repo_name": "hyunbeen99/kuuve_slam", "max_stars_repo_head_hexsha": "afc7861ba69d656f08c4df73ed15f7721004ba87", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-04T01:44:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-04T01:44:31.000Z", "max_issues_repo_path": "include/g2o/edge_plane_parallel.hpp", "max_issues_repo_name": "hyunbeen99/kuuve_slam", "max_issues_repo_head_hexsha": "afc7861ba69d656f08c4df73ed15f7721004ba87", "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/g2o/edge_plane_parallel.hpp", "max_forks_repo_name": "hyunbeen99/kuuve_slam", "max_forks_repo_head_hexsha": "afc7861ba69d656f08c4df73ed15f7721004ba87", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-04T01:44:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-04T01:44:33.000Z", "avg_line_length": 27.272, "max_line_length": 100, "alphanum_fraction": 0.6025227339, "num_tokens": 975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.29972491183530847}}
{"text": "// Copyright (C) 2008-today The SG++ project\n// This file is part of the SG++ project. For conditions of distribution and\n// use, please see the copyright notice provided with SG++ or at\n// sgpp.sparsegrids.org\n\n/**\n * \\page example_optimization_cpp optimization.cpp\n *\n * On this page, we look at an example application of the sgpp::optimization module.\n * Versions of the example are given in all languages\n * currently supported by SG++: C++, Python, Java, and MATLAB.\n *\n * The example interpolates a bivariate test function with B-splines instead\n * of piecewise linear basis functions to obtain a smoother interpolant.\n * The resulting sparse grid function is then minimized with the method of steepest descent.\n * For comparison, we also minimize the objective function with Nelder-Mead's method.\n */\n\n/**\n * First, we include all the necessary headers, including those of the sgpp::base and\n * sgpp::optimization module.\n */\n#include <sgpp_base.hpp>\n#include <sgpp/base/grid/Grid.hpp>\n#include <sgpp/base/datatypes/DataMatrix.hpp>\n#include <sgpp/datadriven/DatadrivenOpFactory.hpp>\n#include <sgpp/datadriven/application/KernelDensityEstimator.hpp>\n#include <sgpp/datadriven/application/LearnerSGDE.hpp>\n#include <sgpp/datadriven/configuration/RegularizationConfiguration.hpp>\n#include <sgpp/datadriven/tools/ARFFTools.hpp>\n#include <sgpp_optimization.hpp>\n#include <sgpp/globaldef.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/ini_parser.hpp>\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <random>\n#include <string>\n\nusing sgpp::base::DataMatrix;\nusing sgpp::base::DataVector;\nusing sgpp::base::Grid;\nusing sgpp::base::GridGenerator;\nusing sgpp::base::GridStorage;\nusing boost::property_tree::ptree;\n\n/**\n * The function \\f$f\\colon [0, 1]^d \\to \\mathbb{R}\\f$ to be minimized\n * is called <i>objective function</i> and has to derive from\n * sgpp::optimization::ScalarFunction.\n * In the constructor, we give the dimensionality of the domain\n * (in this case \\f$d = 2\\f$).\n * The eval method evaluates the objective function and returns the function\n * value \\f$f(\\vec{x})\\f$ for a given point \\f$\\vec{x} \\in [0, 1]^d\\f$.\n * The clone method returns a std::unique_ptr to a clone of the object\n * and is used for parallelization (in case eval is not thread-safe).\n */\nclass ExampleFunction : public sgpp::optimization::ScalarFunction {\n public:\n  sgpp::base::DataVector featureVector;\n  sgpp::datadriven::LearnerSGDE& learner;\n  \n  // our optimization problem is 3dim\n  ExampleFunction(sgpp::datadriven::LearnerSGDE& _learner) : sgpp::optimization::ScalarFunction(3), learner(_learner) {}\n\n  // x is 3dim, we need to supply the rest (feature vector)\n  double eval(const sgpp::base::DataVector& x) {\n\n        sgpp::base::DataVector xNew(x);\n\n        //xNew.append(featureVector.get(0));\n        //xNew.append(featureVector.get(1));\n        //xNew.append(featureVector.get(2));\n        //xNew.append(featureVector.get(3));\n\n        xNew.append(featureVector.get(0));\n        xNew.append(featureVector.get(1));\n        xNew.append(featureVector.get(2));\n        xNew.append(featureVector.get(3));\n\n        return learner.pdf(xNew);\n  }\n\n  virtual void clone(std::unique_ptr<sgpp::optimization::ScalarFunction>& clone) const {\n    clone = std::unique_ptr<sgpp::optimization::ScalarFunction>(new ExampleFunction(*this));\n  }\n\n  void setParamters(const sgpp::base::DataVector& reqFeatureVector){\n    featureVector=reqFeatureVector;\n  }\n};\n\n/**\n * Now, we can start with the \\c main function.\n */\nvoid printLine() {\n  std::cout << \"----------------------------------------\"\n               \"----------------------------------------\\n\";\n}\n\nint main(int argc, const char* argv[]) {\n  (void)argc;\n  (void)argv;\n\n  double featureVectorCoeff_0 = atof(argv[3]);\n  double featureVectorCoeff_1 = atof(argv[4]);\n  double featureVectorCoeff_2 = atof(argv[5]);\n  double featureVectorCoeff_3 = atof(argv[6]);\n\n  std::string filename = \"../\" + std::string(argv[1]);\n  std::string ininame = \"../\" + std::string(argv[2]);\n\n  std::cout << \"# loading file: \" << filename << std::endl;\n  sgpp::datadriven::Dataset dataset =\n    sgpp::datadriven::ARFFTools::readARFFFromFile(filename);\n  sgpp::base::DataMatrix& samples = dataset.getData();\n\n  /**\n   * Configure the sparse grid of level 3 with linear basis functions and the same dimension as the\n   * given test data.\n   * Alternatively load a sparse grid that has been saved to a file, see the commented line.\n   */\n  std::cout << \"# create grid config\" << std::endl;\n  sgpp::base::RegularGridConfiguration gridConfig;\n  gridConfig.dim_ = dataset.getDimension();\n  gridConfig.level_ = 3;\n  gridConfig.type_ = sgpp::base::GridType::Linear; //TODO: BSplines not available, but does not matter\n  //  gridConfig.filename_ = \"/tmp/sgde-grid-4391dc6e-54cd-4ca2-9510-a9c02a2889ec.grid\";\n\n  /**\n   * Configure the adaptive refinement. Therefore the number of refinements and the number of points\n   * are specified.\n   */\n  std::cout << \"# create adaptive refinement config\" << std::endl;\n  sgpp::base::AdaptivityConfiguration adaptConfig;\n  adaptConfig.numRefinements_ = 0;\n  adaptConfig.noPoints_ = 10;\n\n  /**\n   * Configure the solver. The solver type is set to the conjugent gradient method and the maximum\n   * number of iterations, the tolerance epsilon and the threshold are specified.\n   */\n  std::cout << \"# create solver config\" << std::endl;\n  sgpp::solver::SLESolverConfiguration solverConfig;\n  solverConfig.type_ = sgpp::solver::SLESolverType::CG;\n  solverConfig.maxIterations_ = 1000;\n  solverConfig.eps_ = 1e-14;\n  solverConfig.threshold_ = 1e-14;\n\n  /**\n   * Configure the regularization for the laplacian operator.\n   */\n  std::cout << \"# create regularization config\" << std::endl;\n  sgpp::datadriven::RegularizationConfiguration regularizationConfig;\n  regularizationConfig.type_ = sgpp::datadriven::RegularizationType::Laplace;\n\n  /**\n   * Configure the learner by specifying:\n   * - an initial value for the lagrangian multiplier \\f$\\lambda\\f$ and the interval\n   *   \\f$ [\\lambda_{Start} , \\lambda_{End}] \\f$ in which \\f$\\lambda\\f$ will be searched,\n   * - whether a logarithmic scale is used,\n   * - the parameters shuffle and an initial seed for the random value generation,\n   * - whether parts of the output shall be kept off.\n   */\n  std::cout << \"# create learner config\" << std::endl;\n  sgpp::datadriven::CrossvalidationConfiguration crossvalidationConfig;\n  crossvalidationConfig.enable_ = false;\n  crossvalidationConfig.kfold_ = 3;\n  crossvalidationConfig.lambda_ = 3.16228e-06;\n  crossvalidationConfig.lambdaStart_ = 1e-1;\n  crossvalidationConfig.lambdaEnd_ = 1e-10;\n  crossvalidationConfig.lambdaSteps_ = 3;\n  crossvalidationConfig.logScale_ = true;\n  crossvalidationConfig.shuffle_ = true;\n  crossvalidationConfig.seed_ = 1234567;\n  crossvalidationConfig.silent_ = false;\n\n  /**\n   * Create the learner using the configuratons set above. Then initialize it with the data read\n   * from the file in the first step and train the learner.\n   */\n  std::cout << \"# creating the learner\" << std::endl;\n  sgpp::datadriven::LearnerSGDE learner(gridConfig, adaptConfig, solverConfig, regularizationConfig,\n                                        crossvalidationConfig);\n  learner.initialize(samples);\n  learner.train();\n  /**\n   * Estimate the probability density function (pdf) via a gaussian kernel density estimation (KDE)\n   * and print the corresponding values.\n   */\n  sgpp::datadriven::KernelDensityEstimator kde(samples);\n  sgpp::base::DataVector x(learner.getDim());\n  // samples.getRow(samples.getNrows()/2, x);\n  samples.getRow(1, x);\n  \n  std::cout << \"--------------------------------------------------------\\n\";\n  std::cout << \"x= \" << x.toString() << \"\\n\";\n  std::cout << \"SGDE dimensions \" << learner.getDim() << \"\\n\";\n  std::cout << \"SGDE sample count \" << learner.getNsamples() << \"\\n\";\n  std::cout << learner.getSurpluses()->getSize() << \" -> \" << learner.getSurpluses()->sum() << \"\\n\";\n  std::cout << \"pdf_SGDE(x) = \" << learner.pdf(x) << \" ~ \" << kde.pdf(x) << \" =pdf_KDE(x)\\n\";\n  std::cout << \"mean_SGDE(x) = \" << learner.mean() << \" ~ \" << kde.mean() << \" = mean_KDE(x)\\n\";\n  std::cout << \"var_SGDE(x) = \" << learner.variance() << \" ~ \" << kde.variance() << \"=var_KDE(x)\\n\";\n\n  std::cout << \"sgpp::optimization example program started.\\n\\n\";\n  // increase verbosity of the output\n  sgpp::optimization::Printer::getInstance().setVerbosity(2);\n\n  /**\n   * Here, we define some parameters: objective function, dimensionality,\n   * B-spline degree, maximal number of grid points, and adaptivity.\n   */\n  // objective function\n  ExampleFunction f(learner);\n  sgpp::base::DataVector testFV;\n  testFV.append(featureVectorCoeff_0);\n  testFV.append(featureVectorCoeff_1);\n  testFV.append(featureVectorCoeff_2);\n  testFV.append(featureVectorCoeff_3);\n\n  f.setParamters(testFV);\n  // dimension of domain\n  const size_t d = f.getNumberOfParameters();\n  // B-spline degree\n  const size_t p = 3;\n  // maximal number of grid points\n  const size_t N = 30;\n  // adaptivity of grid generation\n  const double gamma = 0.95;\n\n  /**\n   * First, we define a grid with modified B-spline basis functions and\n   * an iterative grid generator, which can generate the grid adaptively.\n   */\n  sgpp::base::ModBsplineGrid grid(d, p);\n  sgpp::optimization::IterativeGridGeneratorRitterNovak gridGen(f, grid, N, gamma);\n\n  /**\n   * With the iterative grid generator, we generate adaptively a sparse grid.\n   */\n  printLine();\n  std::cout << \"Generating grid...\\n\\n\";\n\n  if (!gridGen.generate()) {\n    std::cout << \"Grid generation failed, exiting.\\n\";\n    return 1;\n  }\n\n  /**\n   * Then, we hierarchize the function values to get hierarchical B-spline\n   * coefficients of the B-spline sparse grid interpolant\n   * \\f$\\tilde{f}\\colon [0, 1]^d \\to \\mathbb{R}\\f$.\n   */\n  printLine();\n  std::cout << \"Hierarchizing...\\n\\n\";\n  sgpp::base::DataVector functionValues(gridGen.getFunctionValues());\n  sgpp::base::DataVector coeffs(functionValues.getSize());\n  sgpp::optimization::HierarchisationSLE hierSLE(grid);\n  sgpp::optimization::sle_solver::Auto sleSolver;\n\n  // solve linear system\n  if (!sleSolver.solve(hierSLE, functionValues, coeffs)) {\n    std::cout << \"Solving failed, exiting.\\n\";\n    return 1;\n  }\n\n  /**\n   * We define the interpolant \\f$\\tilde{f}\\f$ and its gradient\n   * \\f$\\nabla\\tilde{f}\\f$ for use with the gradient method (steepest descent).\n   * Of course, one can also use other optimization algorithms from\n   * sgpp::optimization::optimizer.\n   */\n  printLine();\n  std::cout << \"Optimizing smooth interpolant...\\n\\n\";\n  sgpp::optimization::InterpolantScalarFunction ft(grid, coeffs);\n  sgpp::optimization::InterpolantScalarFunctionGradient ftGradient(grid, coeffs);\n  sgpp::optimization::optimizer::GradientDescent gradientDescent(ft, ftGradient);\n  sgpp::base::DataVector x0(d);\n  double fX0;\n  double ftX0;\n\n  /**\n   * The gradient method needs a starting point.\n   * We use a point of our adaptively generated sparse grid as starting point.\n   * More specifically, we use the point with the smallest\n   * (most promising) function value and save it in x0.\n   */\n  {\n    sgpp::base::GridStorage& gridStorage = grid.getStorage();\n\n    // index of grid point with minimal function value\n    size_t x0Index =\n        std::distance(functionValues.getPointer(),\n                      std::min_element(functionValues.getPointer(),\n                                       functionValues.getPointer() + functionValues.getSize()));\n\n    //x0 = gridStorage.getCoordinates(gridStorage[x0Index]);\n\n    x0.set(0, samples.get(0,0)/2);\n    x0.set(1, samples.get(0,1));\n    x0.set(2, samples.get(0,2));\n\n\n    fX0 = functionValues[x0Index];\n    ftX0 = ft.eval(x0);\n  }\n\n  std::cout << \"Gradient starting point:\\n\";\n  std::cout << \"x0 = \" << x0.toString() << \"\\n\";\n  std::cout << \"f(x0) = \" << fX0 << \", ft(x0) = \" << ftX0 << \"\\n\\n\";\n\n  /**\n   * We apply the gradient method and print the results.\n   */\n  gradientDescent.setStartingPoint(x0);\n  gradientDescent.optimize();\n  const sgpp::base::DataVector& xOpt = gradientDescent.getOptimalPoint();\n  const double ftXOpt = gradientDescent.getOptimalValue();\n  const double fXOpt = f.eval(xOpt);\n\n  std::cout << \"\\noptimal control point:\\n\";\n  std::cout << \"for feature vector\" << testFV.toString() << \"\\n\";\n  std::cout << \"xOpt = \" << xOpt.toString() << \"\\n\";\n  std::cout << \"f(xOpt) = \" << fXOpt << \", ft(xOpt) = \" << ftXOpt << \"\\n\\n\";\n  \n  /**\n   * We modify the control point inside the .ini file\n   */\n\n   ptree pt;\n\n   boost::property_tree::ini_parser::read_ini( ininame, pt );\n\n   pt.put(\"Simulation.cpX\", xOpt.get(0));\n   pt.put(\"Simulation.cpY\", xOpt.get(1));\n   pt.put(\"Simulation.cpZ\", xOpt.get(2));\n\n   boost::property_tree::write_ini( ininame, pt );\n\n  return 0;\n}", "meta": {"hexsha": "8ec768fcdfa2296cc5e5b9010dcc4adae1701f1a", "size": 12823, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "students/cpp/optimize.cpp", "max_stars_repo_name": "maierbn/peg-in-hole", "max_stars_repo_head_hexsha": "9c8075e2bb479b605af9fd73e22b5f6d74a3807b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-18T00:15:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T00:15:03.000Z", "max_issues_repo_path": "students/cpp/optimize.cpp", "max_issues_repo_name": "maierbn/peg-in-hole", "max_issues_repo_head_hexsha": "9c8075e2bb479b605af9fd73e22b5f6d74a3807b", "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": "students/cpp/optimize.cpp", "max_forks_repo_name": "maierbn/peg-in-hole", "max_forks_repo_head_hexsha": "9c8075e2bb479b605af9fd73e22b5f6d74a3807b", "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": 37.3848396501, "max_line_length": 120, "alphanum_fraction": 0.6818217266, "num_tokens": 3442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.29960685613250526}}
{"text": "//  (C) Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n//\n// This is not a complete header file, it is included by beta.hpp\n// after it has defined it's definitions.  This inverts the incomplete\n// beta functions ibeta and ibetac on the first parameters \"a\"\n// and \"b\" using a generic root finding algorithm (TOMS Algorithm 748).\n//\n\n#ifndef BOOST_MATH_SP_DETAIL_BETA_INV_AB\n#define BOOST_MATH_SP_DETAIL_BETA_INV_AB\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <boost/math/tools/toms748_solve.hpp>\n#include <boost/cstdint.hpp>\n\nnamespace boost{ namespace math{ namespace detail{\n\ntemplate <class T, class Policy>\nstruct beta_inv_ab_t\n{\n   beta_inv_ab_t(T b_, T z_, T p_, bool invert_, bool swap_ab_) : b(b_), z(z_), p(p_), invert(invert_), swap_ab(swap_ab_) {}\n   T operator()(T a)\n   {\n      return invert ? \n         p - boost::math::ibetac(swap_ab ? b : a, swap_ab ? a : b, z, Policy()) \n         : boost::math::ibeta(swap_ab ? b : a, swap_ab ? a : b, z, Policy()) - p;\n   }\nprivate:\n   T b, z, p;\n   bool invert, swap_ab;\n};\n\ntemplate <class T, class Policy>\nT inverse_negative_binomial_cornish_fisher(T n, T sf, T sfc, T p, T q, const Policy& pol)\n{\n   BOOST_MATH_STD_USING\n   // mean:\n   T m = n * (sfc) / sf;\n   T t = sqrt(n * (sfc));\n   // standard deviation:\n   T sigma = t / sf;\n   // skewness\n   T sk = (1 + sfc) / t;\n   // kurtosis:\n   T k = (6 - sf * (5+sfc)) / (n * (sfc));\n   // Get the inverse of a std normal distribution:\n   T x = boost::math::erfc_inv(p > q ? 2 * q : 2 * p, pol) * constants::root_two<T>();\n   // Set the sign:\n   if(p < 0.5)\n      x = -x;\n   T x2 = x * x;\n   // w is correction term due to skewness\n   T w = x + sk * (x2 - 1) / 6;\n   //\n   // Add on correction due to kurtosis.\n   //\n   if(n >= 10)\n      w += k * x * (x2 - 3) / 24 + sk * sk * x * (2 * x2 - 5) / -36;\n\n   w = m + sigma * w;\n   if(w < tools::min_value<T>())\n      return tools::min_value<T>();\n   return w;\n}\n\ntemplate <class T, class Policy>\nT ibeta_inv_ab_imp(const T& b, const T& z, const T& p, const T& q, bool swap_ab, const Policy& pol)\n{\n   BOOST_MATH_STD_USING  // for ADL of std lib math functions\n   //\n   // Special cases first:\n   //\n   BOOST_MATH_INSTRUMENT_CODE(\"b = \" << b << \" z = \" << z << \" p = \" << p << \" q = \" << \" swap = \" << swap_ab);\n   if(p == 0)\n   {\n      return swap_ab ? tools::min_value<T>() : tools::max_value<T>();\n   }\n   if(q == 0)\n   {\n      return swap_ab ? tools::max_value<T>() : tools::min_value<T>();\n   }\n   //\n   // Function object, this is the functor whose root\n   // we have to solve:\n   //\n   beta_inv_ab_t<T, Policy> f(b, z, (p < q) ? p : q, (p < q) ? false : true, swap_ab);\n   //\n   // Tolerance: full precision.\n   //\n   tools::eps_tolerance<T> tol(policies::digits<T, Policy>());\n   //\n   // Now figure out a starting guess for what a may be, \n   // we'll start out with a value that'll put p or q\n   // right bang in the middle of their range, the functions\n   // are quite sensitive so we should need too many steps\n   // to bracket the root from there:\n   //\n   T guess = 0;\n   T factor = 5;\n   //\n   // Convert variables to parameters of a negative binomial distribution:\n   //\n   T n = b;\n   T sf = swap_ab ? z : 1-z;\n   T sfc = swap_ab ? 1-z : z;\n   T u = swap_ab ? p : q;\n   T v = swap_ab ? q : p;\n   if(u <= pow(sf, n))\n   {\n      //\n      // Result is less than 1, negative binomial approximation\n      // is useless....\n      //\n      if((p < q) != swap_ab)\n      {\n         guess = (std::min)(T(b * 2), T(1));\n      }\n      else\n      {\n         guess = (std::min)(T(b / 2), T(1));\n      }\n   }\n   if(n * n * n * u * sf > 0.005)\n      guess = 1 + inverse_negative_binomial_cornish_fisher(n, sf, sfc, u, v, pol);\n\n   if(guess < 10)\n   {\n      //\n      // Negative binomial approximation not accurate in this area:\n      //\n      if((p < q) != swap_ab)\n      {\n         guess = (std::min)(T(b * 2), T(10));\n      }\n      else\n      {\n         guess = (std::min)(T(b / 2), T(10));\n      }\n   }\n   else\n      factor = (v < sqrt(tools::epsilon<T>())) ? 2 : (guess < 20 ? 1.2f : 1.1f);\n   BOOST_MATH_INSTRUMENT_CODE(\"guess = \" << guess);\n   //\n   // Max iterations permitted:\n   //\n   boost::uintmax_t max_iter = policies::get_max_root_iterations<Policy>();\n   std::pair<T, T> r = bracket_and_solve_root(f, guess, factor, swap_ab ? true : false, tol, max_iter, pol);\n   if(max_iter >= policies::get_max_root_iterations<Policy>())\n      return policies::raise_evaluation_error<T>(\"boost::math::ibeta_invab_imp<%1%>(%1%,%1%,%1%)\", \"Unable to locate the root within a reasonable number of iterations, closest approximation so far was %1%\", r.first, pol);\n   return (r.first + r.second) / 2;\n}\n\n} // namespace detail\n\ntemplate <class RT1, class RT2, class RT3, class Policy>\ntypename tools::promote_args<RT1, RT2, RT3>::type \n      ibeta_inva(RT1 b, RT2 x, RT3 p, const Policy& pol)\n{\n   typedef typename tools::promote_args<RT1, RT2, RT3>::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::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   static const char* function = \"boost::math::ibeta_inva<%1%>(%1%,%1%,%1%)\";\n   if(p == 0)\n   {\n      return policies::raise_overflow_error<result_type>(function, 0, Policy());\n   }\n   if(p == 1)\n   {\n      return tools::min_value<result_type>();\n   }\n\n   return policies::checked_narrowing_cast<result_type, forwarding_policy>(\n      detail::ibeta_inv_ab_imp(\n         static_cast<value_type>(b), \n         static_cast<value_type>(x), \n         static_cast<value_type>(p), \n         static_cast<value_type>(1 - static_cast<value_type>(p)), \n         false, pol), \n      function);\n}\n\ntemplate <class RT1, class RT2, class RT3, class Policy>\ntypename tools::promote_args<RT1, RT2, RT3>::type \n      ibetac_inva(RT1 b, RT2 x, RT3 q, const Policy& pol)\n{\n   typedef typename tools::promote_args<RT1, RT2, RT3>::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::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   static const char* function = \"boost::math::ibetac_inva<%1%>(%1%,%1%,%1%)\";\n   if(q == 1)\n   {\n      return policies::raise_overflow_error<result_type>(function, 0, Policy());\n   }\n   if(q == 0)\n   {\n      return tools::min_value<result_type>();\n   }\n\n   return policies::checked_narrowing_cast<result_type, forwarding_policy>(\n      detail::ibeta_inv_ab_imp(\n         static_cast<value_type>(b), \n         static_cast<value_type>(x), \n         static_cast<value_type>(1 - static_cast<value_type>(q)), \n         static_cast<value_type>(q), \n         false, pol),\n      function);\n}\n\ntemplate <class RT1, class RT2, class RT3, class Policy>\ntypename tools::promote_args<RT1, RT2, RT3>::type \n      ibeta_invb(RT1 a, RT2 x, RT3 p, const Policy& pol)\n{\n   typedef typename tools::promote_args<RT1, RT2, RT3>::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::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   static const char* function = \"boost::math::ibeta_invb<%1%>(%1%,%1%,%1%)\";\n   if(p == 0)\n   {\n      return tools::min_value<result_type>();\n   }\n   if(p == 1)\n   {\n      return policies::raise_overflow_error<result_type>(function, 0, Policy());\n   }\n\n   return policies::checked_narrowing_cast<result_type, forwarding_policy>(\n      detail::ibeta_inv_ab_imp(\n         static_cast<value_type>(a), \n         static_cast<value_type>(x), \n         static_cast<value_type>(p), \n         static_cast<value_type>(1 - static_cast<value_type>(p)), \n         true, pol),\n      function);\n}\n\ntemplate <class RT1, class RT2, class RT3, class Policy>\ntypename tools::promote_args<RT1, RT2, RT3>::type \n      ibetac_invb(RT1 a, RT2 x, RT3 q, const Policy& pol)\n{\n   static const char* function = \"boost::math::ibeta_invb<%1%>(%1%, %1%, %1%)\";\n   typedef typename tools::promote_args<RT1, RT2, RT3>::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::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   if(q == 1)\n   {\n      return tools::min_value<result_type>();\n   }\n   if(q == 0)\n   {\n      return policies::raise_overflow_error<result_type>(function, 0, Policy());\n   }\n\n   return policies::checked_narrowing_cast<result_type, forwarding_policy>(\n      detail::ibeta_inv_ab_imp(\n         static_cast<value_type>(a), \n         static_cast<value_type>(x), \n         static_cast<value_type>(1 - static_cast<value_type>(q)), \n         static_cast<value_type>(q),\n         true, pol),\n         function);\n}\n\ntemplate <class RT1, class RT2, class RT3>\ninline typename tools::promote_args<RT1, RT2, RT3>::type \n         ibeta_inva(RT1 b, RT2 x, RT3 p)\n{\n   return boost::math::ibeta_inva(b, x, p, policies::policy<>());\n}\n\ntemplate <class RT1, class RT2, class RT3>\ninline typename tools::promote_args<RT1, RT2, RT3>::type \n         ibetac_inva(RT1 b, RT2 x, RT3 q)\n{\n   return boost::math::ibetac_inva(b, x, q, policies::policy<>());\n}\n\ntemplate <class RT1, class RT2, class RT3>\ninline typename tools::promote_args<RT1, RT2, RT3>::type \n         ibeta_invb(RT1 a, RT2 x, RT3 p)\n{\n   return boost::math::ibeta_invb(a, x, p, policies::policy<>());\n}\n\ntemplate <class RT1, class RT2, class RT3>\ninline typename tools::promote_args<RT1, RT2, RT3>::type \n         ibetac_invb(RT1 a, RT2 x, RT3 q)\n{\n   return boost::math::ibetac_invb(a, x, q, policies::policy<>());\n}\n\n} // namespace math\n} // namespace boost\n\n#endif // BOOST_MATH_SP_DETAIL_BETA_INV_AB\n\n\n\n", "meta": {"hexsha": "f5735a84956d90f3bfdf6f0cfa8e180596f7f77d", "size": 10363, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/libboost/boost_1_62_0/boost/math/special_functions/detail/ibeta_inv_ab.hpp", "max_stars_repo_name": "189569400/ClickHouse", "max_stars_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "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": "contrib/libboost/boost_1_62_0/boost/math/special_functions/detail/ibeta_inv_ab.hpp", "max_issues_repo_name": "189569400/ClickHouse", "max_issues_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "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": "contrib/libboost/boost_1_62_0/boost/math/special_functions/detail/ibeta_inv_ab.hpp", "max_forks_repo_name": "189569400/ClickHouse", "max_forks_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 31.4984802432, "max_line_length": 221, "alphanum_fraction": 0.6240470906, "num_tokens": 3094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.29960685613250526}}
{"text": "/**\n * @Author: Julien Vial-Detambel <l3ninj>\n * @Date:   2018-06-12T11:23:27+01:00\n * @Email: julien.vial-detambel@epitech.eu\n * @Project: CUDA-Based Simulator of Quantum Systems\n * @Filename: Simulator.cpp\n * @Last modified by:   l3ninj\n * @Last modified time: 2018-08-23T12:13:08+02:00\n * @License: MIT License\n */\n\n#include <iostream>\n#include <cmath>\n#include <random>\n\n#include <boost/foreach.hpp>\n\n#include \"MatrixStore.hpp\"\n#include \"Worker/Simulator.hpp\"\n#include \"Logger.hpp\"\n\nusing namespace TaskGraph;\nusing namespace MeasurementResultsTree;\n\nSimulator::Simulator(SimulateCircuitTask &task, IMeasurementResultsTree &measurementsTree, Matrix const &state)\n: m_task(task), m_measurementsTree(measurementsTree), m_state(state) {\n  // Computing the offsets for each qregisters,\n  // and total qubits number of the system.\n  m_size = 0;\n  for (auto &reg: m_task.circuit.qreg) {\n    m_qRegOffsets.insert(make_pair(reg.name, m_size));\n    m_size += reg.size;\n  }\n}\n\nSimulator::StepVisitor::StepVisitor(Simulator& simulator) :\nm_simulator(simulator) {}\n\nvoid Simulator::StepVisitor::operator()(const Circuit::UGate& value) {\n  // Computing the offset of the target qubit\n  Circuit::Qubit target = value.target;\n  int id = m_simulator.m_qRegOffsets.find(target.registerName)->second;\n  id += target.element;\n\n  // Creating a gate according to the phi, theta and lambda parameters and\n  // setting it as the target qubit transformation gate.\n  using namespace std::complex_literals;\n  m_simulator.m_gates[id] = Matrix(std::shared_ptr<Tvcplxd>(new Tvcplxd({exp(-1i * (value.phi + value.lambda) / 2.0)\n    * cos(value.theta / 2.0),\n    -exp(-1i * (value.phi - value.lambda) / 2.0) * sin(value.theta / 2.0),\n    exp(1i * (value.phi - value.lambda) / 2.0) * sin(value.theta / 2.0),\n    exp(1i * (value.phi + value.lambda) / 2.0) * cos(value.theta / 2.0)\n  })), 2, 2);\n\n  // Debug logs\n  LOG(Logger::DEBUG, \"Applying a U Gate:\" << \"\\nU Gate:\\n\\ttheta: \"\n    << value.theta << \", phi: \" << value.phi << \", lambda: \" << value.lambda\n    << \"\\n\\ttarget: \" << value.target.registerName << \"[\"\n    << value.target.element << \"]\\n\" << std::endl);\n}\n\nvoid Simulator::StepVisitor::operator()(const Circuit::CXGate& value) {\n  // Apparently this method requires us to normalize the state afterward\n  m_simulator.m_shouldNormalize = true;\n  m_simulator.m_shouldAddSecondMatrix = true;\n\n  // Computing the offset of the control qubit.\n  Circuit::Qubit control = value.control;\n  int controlId = m_simulator.m_qRegOffsets.find(control.registerName)->second;\n  controlId += control.element;\n\n  // Computing the offset of the target qubit.\n  Circuit::Qubit target = value.target;\n  int targetId = m_simulator.m_qRegOffsets.find(target.registerName)->second;\n  targetId += target.element;\n\n  m_simulator.m_gates[controlId] = MatrixStore::pk0;\n  m_simulator.m_extraGates[controlId] = MatrixStore::pk1;\n  m_simulator.m_extraGates[targetId] = MatrixStore::x;\n\n  LOG(Logger::DEBUG, \"Applying a CX Gate:\" << \"\\nCX Gate:\\n\\tcontrol: \"\n    << value.control.registerName << \"[\" << value.control.element\n    << \"]\\n\\ttarget: \" << value.target.registerName << \"[\"\n    << value.target.element << \"]\\n\" << std::endl);\n}\n\nvoid Simulator::StepVisitor::operator()(const Circuit::Measurement& value) {\n  (void)(value);\n  LOG(Logger::ERROR, \"Measurement should not be present in the circuit anymore\");\n  assert(true == false);\n}\n\nvoid Simulator::StepVisitor::operator()(const Circuit::Barrier& __attribute__((unused)) value) {\n  // Nothing to be done for a barrier. It is the same as an identity, computationaly-wise\n  (void)value;\n}\n\nvoid Simulator::StepVisitor::operator()(const Circuit::Reset& value) {\n  m_simulator.m_shouldNormalize = true;\n  // Computing the offset of the target qubit\n  Circuit::Qubit target = value.target;\n  int id = m_simulator.m_qRegOffsets.find(target.registerName)->second;\n  id += target.element;\n\n  m_simulator.m_gates[id] = MatrixStore::pk0;\n}\nvoid Simulator::StepVisitor::operator()(const Circuit::ConditionalGate& cGate) {\n  const auto value = m_simulator.m_measurementsTree.getCregValueAtNode(cGate.testedRegister, m_simulator.m_task.measurementNodeId);\n  if (value == cGate.expectedValue) { cGate.gate.apply_visitor(*this); }\n}\n\nMatrix Simulator::simulate() {\n  auto visitor = StepVisitor(*this);\n  // Looping through each steps of the circuit.\n  for (std::vector<Circuit::Step>::iterator it = m_task.circuit.steps.begin();\n    it != m_task.circuit.steps.end(); ++it) {\n      // LOG(Logger::DEBUG, \"State before step:\" << m_state);\n      m_shouldNormalize = false;\n      m_shouldAddSecondMatrix = false;\n    // Initializing the gate vectors\n    m_gates = std::vector<Matrix>(m_size, MatrixStore::i2);\n    m_extraGates = std::vector<Matrix>(m_size, MatrixStore::i2);\n    for (auto &substep: *it) {\n      // Applying defined tranformations in the visitor.\n      boost::apply_visitor(visitor, substep);\n    }\n    // Computing the new state as the dot product between the kroenecker product\n    // of the transformation gates for each qubits and the actual simulator state.\n    Matrix op = Matrix::kron(m_gates);\n    if (m_shouldAddSecondMatrix) op = op + Matrix::kron(m_extraGates);\n    // for (auto const &g : m_extraGates) {\n    //   LOG(Logger::ERROR, g);\n    // }\n    // LOG(Logger::DEBUG, \"Applying matrix:\" << op);\n    // LOG(Logger::DEBUG, \"Submatrices:\" << Matrix::kron(m_gates) << Matrix::kron(m_extraGates));\n    m_state = op * m_state;\n\n    if (m_shouldNormalize) m_state = m_state.normalize();\n      // LOG(Logger::DEBUG, \"State after step:\" << m_state);\n  }\n  return m_state;\n}\n", "meta": {"hexsha": "f0480b2f307932f4943239f91c4619850c6ebbe3", "size": 5590, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Worker/Simulator.cpp", "max_stars_repo_name": "4rzael/quantum-cuda", "max_stars_repo_head_hexsha": "6c03d79f4ef68f6350e0659a1ef5a556d7915968", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-07-05T12:22:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-05T05:28:42.000Z", "max_issues_repo_path": "src/Worker/Simulator.cpp", "max_issues_repo_name": "4rzael/quantum-cuda", "max_issues_repo_head_hexsha": "6c03d79f4ef68f6350e0659a1ef5a556d7915968", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Worker/Simulator.cpp", "max_forks_repo_name": "4rzael/quantum-cuda", "max_forks_repo_head_hexsha": "6c03d79f4ef68f6350e0659a1ef5a556d7915968", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-14T17:58:11.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-14T17:58:11.000Z", "avg_line_length": 39.0909090909, "max_line_length": 131, "alphanum_fraction": 0.6976744186, "num_tokens": 1523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2995638701961429}}
{"text": "// STD headers\n#include <assert.h>\n#include <fstream>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <list>\n#include <string>\n#include <thread>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\n// Boost headers\n#include <boost/bimap.hpp>\n#include <boost/program_options.hpp>\n\n// Cereal headers\n#include <cereal/archives/binary.hpp>\n#include <cereal/types/vector.hpp>\n\n// Gurobi headers\n#include <gurobi_c++.h>\n\n// Custom headers\n#include \"flow_dict.hpp\"\n#include \"simulator.hpp\"\n#include \"utils.hpp\"\n\n// Typedefs\nnamespace bopt = boost::program_options;\ntypedef std::tuple<std::string, bool, std::string, std::string,\ndouble> Edge;  // Format: (flow_id, in_cache, src, dst, cost)\n\n// Constant hyperparameters\nconstexpr unsigned int kNumThreads = 24;\n\n/**\n * Implements a Multi-Commodity Min-Cost Flow-based\n * solver for the Delayed Hits caching problem.\n */\nclass MCMCFSolver {\nprivate:\n    typedef std::vector<size_t> Indices;\n\n    // Trace and cache parameters\n    const uint z_;\n    const uint c_;\n    const bool is_forced_;\n    const size_t trace_len_;\n    const std::string trace_file_path_;\n    const std::string model_file_prefix_;\n    const std::string packets_file_path_;\n    const std::vector<std::string> trace_;\n\n    // Housekeeping\n    std::vector<double> solution_;\n    std::unordered_set<size_t> cache_node_idxs_;\n    std::unordered_map<std::string, Indices> indices_;\n    boost::bimap<size_t, std::string> idx_to_nodename_;\n    std::unordered_map<size_t, double> idx_to_miss_cost_;\n    std::unordered_map<std::string, std::string> sink_nodes_;\n    std::unordered_map<std::string, Indices> cache_interval_start_idxs_;\n\n    // \"Split nodes\" are used to enforce forced admission, if required.\n    // We detect nodes where the forced admission constraint *might* be\n    // violated (i.e. an object doesn't remain in the cache for atleast\n    // one timestep), and add manually a constraint that enforces this.\n    std::unordered_set<size_t> split_node_idxs_;\n\n    // Internal helper methods\n    double getMissCostStartingAt(const size_t idx) const;\n    const std::string& cchNodeForMemAt(const size_t idx) const;\n    size_t getNextMemNodeIdx(const size_t idx, const std::string& flow_id,\n                             std::unordered_map<std::string,\n                             size_t>& next_idxs_map) const;\n\n    // Thread-safe, concurrent helper methods\n    void populateOutOfCchEdgesConcurrent(\n        const std::list<std::string>& flow_ids,\n        std::list<Edge>& edges, std::unordered_set<size_t>& cache_node_idxs);\n\n    void populateCchCapacityConstraintsConcurrent(\n        const std::pair<size_t, size_t> range,\n        const belatedly::FlowDict& flows, std::list<GRBLinExpr>& exprs) const;\n\n    // Setup and checkpointing\n    void setup();\n    bool loadOptimizedModelSolution(belatedly::FlowDict& flows);\n    void saveOptimizedModelSolution(const belatedly::FlowDict& flows) const;\n\n    // Model creation\n    void populateOutOfCchEdges(std::list<Edge>& all_edges);\n    void createFlowVariables(GRBModel& model, belatedly::FlowDict&\n                             flows, const std::list<Edge>& edges) const;\n\n    void populateCchCapacityConstraints(\n        GRBModel& model, const belatedly::FlowDict& flows) const;\n\n    void populateSplitNodeFlowConstraints(\n        GRBModel& model, const belatedly::FlowDict& flows) const;\n\n    void populateFlowConservationConstraints(\n        GRBModel& model, const belatedly::FlowDict& flows) const;\n\n    void addMissCostStartingAt(const size_t start_idx,\n                               const double coefficient,\n                               std::vector<utils::Packet>& packets) const;\n\n    // Cost computation and validation\n    double getCostLowerBound(const belatedly::FlowDict& flows,\n                             const std::list<Edge>& edges) const;\n\n    double getCostUpperBoundAndValidateSolution(\n        const belatedly::FlowDict& flows, const std::list<Edge>& edges) const;\n\npublic:\n    MCMCFSolver(const std::string& trace_fp, const std::string& model_fp,\n                const std::string& packets_fp, const bool forced, const\n                uint z, const uint c, const std::vector<std::string>& trace) :\n                z_(z), c_(c), is_forced_(forced), trace_len_(trace.size()),\n                trace_file_path_(trace_fp), model_file_prefix_(model_fp),\n                packets_file_path_(packets_fp), trace_(trace) {}\n\n    void solve();\n};\n\n/**\n * Given an index, returns the corresponding cache node.\n *\n * Thread-safe.\n */\nconst std::string& MCMCFSolver::cchNodeForMemAt(const size_t idx) const {\n    return idx_to_nodename_.left.at(idx);\n}\n\n/**\n * Returns the cost of a cache miss starting at idx.\n *\n * Thread-safe.\n */\ndouble MCMCFSolver::getMissCostStartingAt(const size_t idx) const {\n    const std::string& flow_id = trace_[idx];\n    double miss_cost = z_;\n\n    // Iterate over the next z timesteps, and add the\n    // latency cost corresponding to each subsequent\n    // packet of the same flow.\n    for (size_t offset = 1; offset < z_; offset++) {\n        if (idx + offset >= trace_len_) { break; }\n        else if (trace_[idx + offset] == flow_id) {\n            miss_cost += (z_ - offset);\n        }\n    }\n    return miss_cost;\n}\n\n/**\n * Returns the index of the first mem node corresponding to the given\n * flow ID occuring after idx. If no reference to this flow is found\n * in (idx, trace_len_), returns maxval.\n *\n * The state for each flow is cached in next_idxs_map. This dict must\n * be cleared before starting a new operation (that is, when indices\n * are no longer expected to continue increasing monotonically).\n *\n * Thread-safe.\n */\nsize_t MCMCFSolver::getNextMemNodeIdx(\n    const size_t idx, const std::string& flow_id,\n    std::unordered_map<std::string, size_t>& next_idxs_map) const {\n    const std::vector<size_t>& indices = indices_.at(flow_id);\n    size_t indices_len = indices.size();\n\n    while ((next_idxs_map[flow_id] < indices_len) &&\n           (indices[next_idxs_map[flow_id]] <= idx)) {\n        next_idxs_map[flow_id]++;\n    }\n    // If the next index is beyond the idxs list for\n    // this flow, return the corresponding sink node.\n    size_t next_idx = next_idxs_map[flow_id];\n    if (next_idx == indices_len) {\n        return std::numeric_limits<size_t>::max();\n    }\n    else {\n        size_t next_mem_idx = indices[next_idx];\n        assert(trace_[next_mem_idx] == flow_id);\n        return next_mem_idx;\n    }\n}\n\n/**\n * Attempts to load the optimal solution and the flow mappings\n * for the given model. Returns true if successful, else false.\n */\nbool MCMCFSolver::loadOptimizedModelSolution(belatedly::FlowDict& flows) {\n    if (model_file_prefix_.empty()) { return false; }\n    std::ifstream solution_ifs(model_file_prefix_ + \".sol\");\n    const std::string flows_fp = model_file_prefix_ + \".flows\";\n\n    // Either of the required model files is missing, indicating failure\n    if (!solution_ifs.good() || !std::ifstream(flows_fp).good()) {\n        return false;\n    }\n    // Load the solutions vector\n    {\n        cereal::BinaryInputArchive ar(solution_ifs);\n        ar(solution_);\n    }\n    // Load the flow mappings\n    flows.loadFlowMappings(flows_fp);\n\n    // Sanity check: The number of decision variables should\n    // be equal to the number of entries in the flows map.\n    assert(solution_.size() == flows.numVariables());\n    return true;\n}\n\n/**\n * Saves the optimal solution and flow mappings to disk.\n */\nvoid MCMCFSolver::saveOptimizedModelSolution(\n    const belatedly::FlowDict& flows) const {\n\n    if (model_file_prefix_.empty()) { return; }\n    std::ofstream solution_ofs(model_file_prefix_ + \".sol\");\n    const std::string flows_fp = model_file_prefix_ + \".flows\";\n\n    // Save the solutions vector\n    cereal::BinaryOutputArchive oarchive(solution_ofs);\n    oarchive(solution_);\n\n    // Save the flow mappings\n    flows.saveFlowMappings(flows_fp);\n}\n\n/**\n * Populate the indices map and internal data structures.\n */\nvoid MCMCFSolver::setup() {\n    size_t num_nonempty_packets = 0;\n    for (size_t idx = 0; idx < trace_len_; idx++) {\n        const std::string& flow_id = trace_[idx];\n\n        // If the packet is non-empty, append the idx to\n        // the corresponding flow's idxs. Also, populate\n        // the miss-costs map.\n        if (!flow_id.empty()) {\n            num_nonempty_packets++;\n            indices_[flow_id].push_back(idx);\n            idx_to_miss_cost_[idx] = getMissCostStartingAt(idx);\n        }\n        // Found a possible violation of forced admission; track this as a split node\n        if (is_forced_ && !flow_id.empty() && (idx > 0) && (idx < trace_len_ - z_) &&\n            (flow_id == trace_[idx - 1]) && (flow_id == trace_[idx + z_])) {\n            split_node_idxs_.insert(idx);\n        }\n        // Populate the nodenames map\n        idx_to_nodename_.insert(boost::bimap<size_t, std::string>::value_type(\n            idx, \"cch_t\" + std::to_string(idx + z_ - 1) + \"_\" + flow_id));\n    }\n    // Populate the sink nodes map and\n    // prime the cache intervals map.\n    for (const auto& iter : indices_) {\n        const std::string& flow_id = iter.first;\n        sink_nodes_[flow_id] = (\"x_\" + flow_id);\n        cache_interval_start_idxs_[flow_id];\n    }\n    // Debug\n    std::cout << \"Finished setup with \" << trace_len_\n              << \" packets (\" << num_nonempty_packets\n              << \" nonempty), \" << indices_.size()\n              << \" flows.\" << std::endl;\n}\n\n/**\n * Helper method. Populates the out-of-cache edges (mem->cch/admittance,\n * and cch->mem/eviction) for the given flow IDs in a thread-safe manner.\n *\n * Important note: This method relies on the fact that separate threads\n * operate on disjoint sets of flow IDs (and only ever access different\n * STL containers concurrently), precluding the need for mutexes.\n *\n * Thread-safe.\n */\nvoid MCMCFSolver::populateOutOfCchEdgesConcurrent(\n    const std::list<std::string>& flow_ids, std::list<Edge>& edges,\n    std::unordered_set<size_t>& local_cache_node_idxs) {\n\n    // Iterate over the given flow IDs to populate the edges list\n    std::unordered_map<std::string, size_t> next_idxs_map;\n    for (const std::string& flow_id : flow_ids) {\n        std::string evicted_reference = std::string();\n        bool has_flow_started = false;\n\n        // Iterate over each timestep and fetch the next mem reference\n        for (size_t idx = 0; idx < trace_len_; idx++) {\n            const std::string& trace_flow_id = trace_[idx];\n            bool is_same_flow = (!trace_flow_id.empty() &&\n                                 (trace_flow_id == flow_id));\n            if (has_flow_started) {\n\n                // Fetch the next mem reference corresponding to this flow\n                const size_t next_reference_idx = getNextMemNodeIdx(\n                    idx + z_ - 1, flow_id, next_idxs_map);\n\n                const bool is_dst_sink_node = (next_reference_idx ==\n                                               std::numeric_limits<size_t>::max());\n\n                // Fetch the dst node for this out-of-cache edge\n                const std::string& next_reference = is_dst_sink_node ?\n                                                    sink_nodes_.at(flow_id) :\n                                                    cchNodeForMemAt(next_reference_idx);\n                if (is_same_flow) {\n                    // In optional admission, unconditionally create an\n                    // outedge from this node to the next mem reference.\n                    if (!is_forced_) {\n                        evicted_reference = next_reference;\n                        edges.push_back(std::make_tuple(\n                            flow_id, false, cchNodeForMemAt(idx), next_reference,\n                            (is_dst_sink_node ? 0.0 : idx_to_miss_cost_.at(next_reference_idx)))\n                        );\n                    }\n                    // The following node in the trace (mem_t{idx + z}) maps to\n                    // this flow, but the previous node in the caching sequence\n                    // (cch_t{idx + z - 1}) also maps to it. Thus, this is the\n                    // final opportunity to reach mem_t{idx + z}, and we create\n                    // an edge to it.\n                    else if (split_node_idxs_.find(idx) != split_node_idxs_.end()) {\n                        assert(!is_dst_sink_node);\n                        edges.push_back(std::make_tuple(\n                            flow_id, false, cchNodeForMemAt(idx),\n                            next_reference, idx_to_miss_cost_.at(next_reference_idx))\n                        );\n                    }\n                    // Discard the next mem reference for this flow\n                    else {\n                        evicted_reference.clear();\n                    }\n\n                    // Mark this idx as the start of a new interval for this flow\n                    local_cache_node_idxs.insert(idx);\n                    cache_interval_start_idxs_.at(flow_id).push_back(idx);\n                }\n                // If we did not already created an eviction edge to the\n                // next mem reference for this flow, create one to it.\n                else if (evicted_reference != next_reference) {\n                    evicted_reference = next_reference;\n                    edges.push_back(std::make_tuple(\n                        flow_id, false, cchNodeForMemAt(idx), next_reference,\n                        (is_dst_sink_node ? 0.0 : idx_to_miss_cost_.at(next_reference_idx)))\n                    );\n\n                    // Mark this idx as the start of a new interval for this flow\n                    local_cache_node_idxs.insert(idx);\n                    cache_interval_start_idxs_.at(flow_id).push_back(idx);\n                }\n            }\n            // The flow has not yet started and the packet at this timestep\n            // belongs to this flow, indicating that this is the first ever\n            // request to it.\n            else if (is_same_flow) {\n                has_flow_started = true;\n\n                // In optional admission, unconditionally create an\n                // outedge from this node to the next mem reference.\n                if (!is_forced_) {\n                    // Fetch the next mem reference corresponding to this flow\n                    const size_t next_reference_idx = getNextMemNodeIdx(\n                        idx + z_ - 1, flow_id, next_idxs_map);\n\n                    const bool is_dst_sink_node = (next_reference_idx ==\n                                                   std::numeric_limits<size_t>::max());\n\n                    // Fetch the dst node for this out-of-cache edge\n                    const std::string& next_reference = is_dst_sink_node ?\n                                                        sink_nodes_.at(flow_id) :\n                                                        cchNodeForMemAt(next_reference_idx);\n                    evicted_reference = next_reference;\n                    edges.push_back(std::make_tuple(\n                        flow_id, false, cchNodeForMemAt(idx), next_reference,\n                        (is_dst_sink_node ? 0.0 : idx_to_miss_cost_.at(next_reference_idx)))\n                    );\n                }\n                // Mark this idx as the start of a new interval for this flow\n                local_cache_node_idxs.insert(idx);\n                cache_interval_start_idxs_.at(flow_id).push_back(idx);\n            }\n        }\n    }\n}\n\n/**\n * Populates the out-of-cache (eviction and admittance) edges.\n */\nvoid MCMCFSolver::populateOutOfCchEdges(std::list<Edge>& all_edges) {\n    size_t num_out_of_cch_edges = 0;\n    size_t num_total_flows = indices_.size();\n    size_t num_flows_per_thread = int(ceil(num_total_flows /\n                                      static_cast<double>(kNumThreads)));\n\n    // Temporary containers for each thread\n    size_t num_flows_allotted = 0;\n    std::array<std::list<Edge>, kNumThreads> edges;\n    std::array<std::list<std::string>, kNumThreads> flow_ids;\n    std::array<std::unordered_set<size_t>, kNumThreads> local_cache_node_idxs;\n\n    // Partition the entire set of flow IDs into kNumThreads disjoint sets\n    auto iter = indices_.begin();\n    for (size_t t_idx = 0; t_idx < kNumThreads; t_idx++) {\n        for (size_t i = 0; (i < num_flows_per_thread) &&\n             (iter != indices_.end()); i++, iter++) {\n            num_flows_allotted++;\n            flow_ids[t_idx].push_back(iter->first);\n        }\n    }\n    // Sanity check\n    assert(num_flows_allotted == num_total_flows);\n\n    // Launch kNumThreads on the corresponding sets of flow IDs\n    std::thread workers[kNumThreads];\n    for (size_t t_idx = 0; t_idx < kNumThreads; t_idx++) {\n        workers[t_idx] = std::thread(&MCMCFSolver::populateOutOfCchEdgesConcurrent, this,\n                                     std::ref(flow_ids[t_idx]), std::ref(edges[t_idx]),\n                                     std::ref(local_cache_node_idxs[t_idx]));\n    }\n    // Wait for all the worker threads to finish execution\n    for (size_t t_idx = 0; t_idx < kNumThreads; t_idx++) {\n        workers[t_idx].join();\n    }\n    // Then, combine their results\n    for (size_t t_idx = 0; t_idx < kNumThreads; t_idx++) {\n        num_out_of_cch_edges += edges[t_idx].size();\n        all_edges.splice(all_edges.end(), edges[t_idx]);\n        cache_node_idxs_.insert(local_cache_node_idxs[t_idx].begin(),\n                                local_cache_node_idxs[t_idx].end());\n    }\n    // Next, sort the cache intervals for each flow in-place\n    for (auto& iter : cache_interval_start_idxs_) {\n        std::vector<size_t>& start_idxs = iter.second;\n        std::sort(start_idxs.begin(), start_idxs.end());\n    }\n    // Finally, for the last packet in the trace, unconditionally\n    // create an outedge to the corresponding flow's sink node.\n    size_t idx = (trace_len_ - 1);\n    const std::string& flow_id = trace_[idx];\n    if (is_forced_ && !flow_id.empty()) {\n        num_out_of_cch_edges++;\n        all_edges.push_back(std::make_tuple(flow_id, false,\n                                            cchNodeForMemAt(idx),\n                                            sink_nodes_.at(flow_id), 0.0));\n    }\n    // Debug\n    std::cout << \"Finished populating \" << num_out_of_cch_edges\n              << \" out-of-cache edges concurrently, using \"\n              << kNumThreads << \" threads.\" << std::endl;\n}\n\n/**\n * Given a list of edges, populates the flow tupledict.\n */\nvoid MCMCFSolver::\ncreateFlowVariables(GRBModel& model, belatedly::FlowDict& flows,\n                    const std::list<Edge>& edges) const {\n    size_t num_total_cache_intervals = 0;\n\n    // First, create variables representing mem->cch and cch->mem edges\n    for (const Edge& edge : edges) {\n        flows.addVariable(std::get<0>(edge),\n                          std::get<1>(edge),\n                          std::get<2>(edge),\n                          std::get<3>(edge),\n                          std::get<4>(edge));\n    }\n    // Next, for every flow, create decision variables\n    // corresponding to each possible caching interval.\n    for (const auto& iter : cache_interval_start_idxs_) {\n        const std::string& flow_id = iter.first;\n        const std::vector<size_t>& start_idxs = iter.second;\n        const size_t num_intervals = (start_idxs.size() - 1);\n\n        // Iterate over each interval\n        for (size_t i = 0; i < num_intervals; i++) {\n            size_t idx = start_idxs[i];\n            size_t next_idx = start_idxs[i + 1];\n\n            // Sanity check: Both indices should be in the nodes set\n            assert((cache_node_idxs_.find(idx) != cache_node_idxs_.end()) &&\n                   (cache_node_idxs_.find(next_idx) != cache_node_idxs_.end()));\n\n            // Create a decision variable corresponding to cch_{idx}->cch_{next_idx}\n            num_total_cache_intervals++;\n            flows.addVariable(flow_id, true,\n                              cchNodeForMemAt(idx),\n                              cchNodeForMemAt(next_idx), 0.0);\n        }\n    }\n    // Finally, update the model\n    model.update();\n\n    // Debug\n    std::cout << \"Finished creating \" << flows.numVariables() << \" flow variables (for \"\n              << edges.size() << \" edges, plus \" << num_total_cache_intervals\n              << \" caching intervals).\" << std::endl;\n}\n\n/**\n * Helper method. Populates the cache capacity constraints for\n * the given range of trace indices in a thread-safe manner.\n *\n * Thread-safe.\n */\nvoid MCMCFSolver::populateCchCapacityConstraintsConcurrent(\n    const std::pair<size_t, size_t> range, const belatedly::\n    FlowDict& flows, std::list<GRBLinExpr>& exprs) const {\n    std::unordered_map<std::string, GRBVar> decision_variables;\n    std::unordered_map<std::string, size_t> current_idxs;\n\n    // Starting index is out-of-bounds, do nothing\n    if (range.first >= trace_len_) { return; }\n\n    // First, for each flow ID, forward its current iterator idx\n    // to point to the appropriate location in its indices list.\n    for (const auto& iter : cache_interval_start_idxs_) {\n        const std::vector<size_t>& intervals = iter.second;\n        const std::string& flow_id = iter.first;\n\n        size_t i = 0;\n        while (i < (intervals.size() - 1) &&\n               range.first > intervals[i + 1]) { i++; }\n\n        // Update the current iterator idx\n        current_idxs[flow_id] = i;\n    }\n    // Next, generate a linear-expression corresponding to the sum of\n    // all flow decision variables at every timestep, and impose that\n    // it is LEQ the cache size as a constraint.\n    for (size_t idx = range.first; idx < range.second; idx++) {\n        if (cache_node_idxs_.find(idx) ==\n            cache_node_idxs_.end()) { continue; }\n\n        bool is_split_node = (split_node_idxs_.find(idx) !=\n                              split_node_idxs_.end());\n        GRBLinExpr node_capacity_expr;\n        bool is_expr_changed = false;\n\n        // Update the current decision variable for each\n        // flow and add it to the LHS of the constraints.\n        for (const auto& iter : cache_interval_start_idxs_) {\n            const std::string& flow_id = iter.first;\n            const std::vector<size_t>& intervals = iter.second;\n            bool is_split_node_for_flow = (is_split_node &&\n                                           (trace_[idx] == flow_id));\n\n            // If this trace index either precedes the first decision\n            // variable, or is either at or beyond the last decision\n            // variable for this flow, do nothing.\n            size_t i = current_idxs[flow_id];\n            if (idx < intervals[0] || idx >= intervals.back()) {\n                continue;\n            }\n            // Reached the first interval or the end\n            // of the current interval for this flow.\n            else if ((decision_variables.find(flow_id) ==\n                      decision_variables.end()) ||\n                     (idx == intervals[i + 1])) {\n\n                // If this is the end of the current\n                // interval, update the idx iterator.\n                if (idx == intervals[i + 1]) {\n                    current_idxs[flow_id] = ++i;\n                }\n                // Fetch the current interval\n                size_t start_idx = intervals[i];\n                size_t end_idx = intervals[i + 1];\n\n                // This is a regular node\n                GRBVar decision_variable = (\n                    flows.getVariable(flow_id, true,\n                                      cchNodeForMemAt(start_idx),\n                                      cchNodeForMemAt(end_idx)));\n\n                // Update the decision variable for this flow\n                decision_variables[flow_id] = decision_variable;\n                node_capacity_expr += decision_variable;\n                is_expr_changed = true;\n            }\n            // Else, add the current decision variable to the expression\n            else {\n                GRBVar decision_variable = decision_variables.at(flow_id);\n                node_capacity_expr += decision_variable;\n                assert(!is_split_node_for_flow);\n            }\n        }\n        // Finally, add the expression as a cache constraints\n        if (is_expr_changed) { exprs.push_back(node_capacity_expr); }\n    }\n}\n\n/**\n * Populates the cache capacity constraints for the given flow variables.\n */\nvoid MCMCFSolver::populateCchCapacityConstraints(\n    GRBModel& model, const belatedly::FlowDict& flows) const {\n    std::array<std::list<GRBLinExpr>, kNumThreads> exprs;\n    std::thread workers[kNumThreads];\n    size_t num_constraints = 0;\n\n    // Partition the trace into kNumThreads disjoint sets\n    size_t start_idx = 0;\n    size_t idxs_per_thread = int(ceil(trace_len_ /\n                                 static_cast<double>(kNumThreads)));\n\n    // Launch kNumThreads on the corresponding range of indices\n    for (size_t t_idx = 0; t_idx < kNumThreads; t_idx++) {\n        size_t end_idx = std::min(trace_len_,\n                                  start_idx + idxs_per_thread);\n\n        workers[t_idx] = std::thread(\n            &MCMCFSolver::populateCchCapacityConstraintsConcurrent, this,\n            std::make_pair(start_idx, end_idx), std::ref(flows),\n            std::ref(exprs[t_idx]));\n\n        // Update the starting idx\n        start_idx = end_idx;\n    }\n    // Wait for all the worker threads to finish execution\n    for (size_t t_idx = 0; t_idx < kNumThreads; t_idx++) {\n        workers[t_idx].join();\n    }\n    // Populate the model constraints\n    for (size_t t_idx = 0; t_idx < kNumThreads; t_idx++) {\n        for (auto& expr : exprs[t_idx]) {\n            num_constraints++;\n            model.addConstr(expr, GRB_LESS_EQUAL, c_, \"\");\n        }\n        exprs[t_idx].clear();\n    }\n    // Debug\n    std::cout << \"Finished adding \" << num_constraints << \" arc-capacity\"\n              << \" constraints for cch->cch edges concurrently, using \"\n              << kNumThreads << \" threads.\" << std::endl;\n}\n\n/**\n * Populates flow constraints for split nodes. These ensure that once\n * flow enters the cache, it remains there for at least one timestep.\n */\nvoid MCMCFSolver::populateSplitNodeFlowConstraints(\n    GRBModel& model, const belatedly::FlowDict& flows) const {\n    size_t num_split_node_constraints = 0;\n\n    for (const size_t idx : split_node_idxs_) {\n        const std::string& flow_id = trace_[idx];\n        num_split_node_constraints++;\n\n        // Fetch the decision variable corresponding\n        // to the cch_{idx}->next_mem_node edge.\n        const GRBVar outflow = flows.getVariable(\n            flow_id, false, cchNodeForMemAt(idx),\n            cchNodeForMemAt(idx + z_));\n\n        // Fetch the expression corresponding\n        // to the mem_{idx}->cch_{idx} edge.\n        const GRBLinExpr inflow = (\n            flows.sumAcrossSrcNodes(flow_id, false,\n                                    cchNodeForMemAt(idx)));\n\n        // Ensure that the outflow is LEQ (1 - inflow)\n        model.addConstr(outflow + inflow, GRB_LESS_EQUAL, 1, \"\");\n    }\n    // Debug\n    std::cout << \"Finished populating \" << num_split_node_constraints\n              << \" flow constraints for split nodes.\" << std::endl;\n}\n\n/**\n * Populates the flow conservation constraints for all nodes.\n */\nvoid MCMCFSolver::populateFlowConservationConstraints(\n    GRBModel& model, const belatedly::FlowDict& flows) const {\n\n    // Flow-conservation constraints for sink nodes\n    size_t num_sink_node_constraints = 0;\n    for (const auto& iter : indices_) {\n        num_sink_node_constraints++;\n        const std::string& flow_id = iter.first;\n        const std::string& node = sink_nodes_.at(flow_id);\n        model.addConstr(flows.sumAcrossSrcNodes(flow_id, node), GRB_EQUAL, 1, \"\");\n    }\n    // Debug\n    std::cout << \"Finished adding \" << num_sink_node_constraints\n              << \" flow-conservation constraints for sink nodes.\"\n              << std::endl;\n\n    // Flow-conservation constraints for cache nodes\n    size_t num_cache_node_constraints = 0;\n    for (const auto& iter : cache_interval_start_idxs_) {\n        const std::string& flow_id = iter.first;\n        const std::vector<size_t>& start_idxs = iter.second;\n\n        for (size_t idx : start_idxs) {\n            num_cache_node_constraints++;\n            const std::string& node = cchNodeForMemAt(idx);\n            assert(cache_node_idxs_.find(idx) != cache_node_idxs_.end());\n\n            // This is the source node for this flow\n            if (idx == start_idxs.front()) {\n                model.addConstr(flows.sumAcrossDstNodes(flow_id, node), GRB_EQUAL, 1, \"\");\n            }\n            // Else, this is a regular node\n            else {\n                model.addConstr(flows.sumAcrossSrcNodes(flow_id, node), GRB_EQUAL,\n                                flows.sumAcrossDstNodes(flow_id, node), \"\");\n            }\n        }\n    }\n    // Debug\n    std::cout << \"Finished adding \" << num_cache_node_constraints\n              << \" flow-conservation constraints for cache nodes.\"\n              << std::endl;\n}\n\n/**\n * Helper method. Given a start idx and cost coefficient (flow fraction),\n * updates latencies of subsequent same-flow packets that occur within z\n * timesteps of start_idx.\n */\nvoid MCMCFSolver::\naddMissCostStartingAt(const size_t start_idx, const double coefficient,\n                      std::vector<utils::Packet>& packets) const {\n    if (utils::DoubleApproxEqual(coefficient, 0.)) { return; }\n\n    // Iterate over the next z timesteps, and add the weighted\n    // latency cost to each subsequent packet of the same flow.\n    const std::string& flow_id = trace_[start_idx];\n    for (size_t offset = 0; offset < z_; offset++) {\n        const size_t idx = start_idx + offset;\n\n        if (idx >= trace_len_) { break; }\n        else if (trace_[idx] == flow_id) {\n            packets[idx].addLatency((z_ - offset) * coefficient);\n        }\n    }\n}\n\n/**\n * Returns a (tight) lower-bound on the cost of the LP solution.\n */\ndouble MCMCFSolver::getCostLowerBound(const belatedly::FlowDict& flows,\n                                      const std::list<Edge>& edges) const {\n    // Create packets corresponding to each timestep\n    std::vector<utils::Packet> processed_packets;\n    for (const std::string& flow_id : trace_) {\n        processed_packets.push_back(utils::Packet(flow_id));\n    }\n    // Update the packet latency corresponding\n    // to the first occurence of each flow.\n    for (const auto& elem : indices_) {\n        const size_t src_idx = elem.second.front();\n        addMissCostStartingAt(src_idx, 1., processed_packets);\n    }\n    // Next, add the latency cost of flow\n    // routed through out-of-cch edges.\n    for (const auto& edge : edges) {\n        const bool in_cache = std::get<1>(edge);\n        const std::string& src = std::get<2>(edge);\n        const std::string& dst = std::get<3>(edge);\n        const std::string& flow_id = std::get<0>(edge);\n\n        // This is an out-of-cch edge and dst is not a sink node\n        if (!in_cache && dst != sink_nodes_.at(flow_id)) {\n            double flow_fraction = solution_[\n                flows.getVariableIdx(flow_id, in_cache, src, dst)];\n\n            size_t dst_idx = idx_to_nodename_.right.at(dst);\n            addMissCostStartingAt(dst_idx, flow_fraction,\n                                  processed_packets);\n        }\n    }\n    // Compute the total latency for this solution\n    double total_latency = 0;\n    for (const utils::Packet& packet : processed_packets) {\n        const std::string& flow_id = packet.getFlowId();\n        const double latency = packet.getTotalLatency();\n        if (!flow_id.empty()) {\n\n            // Sanity check: For non-empty packets, latency should be in [0, z]\n            assert(utils::DoubleApproxGreaterThanOrEqual(latency, 0.) &&\n                   utils::DoubleApproxGreaterThanOrEqual(z_, latency));\n\n            total_latency += latency;\n        }\n        // Else, for empty packets, do nothing\n        else { assert(latency == 0.); }\n    }\n    return total_latency;\n}\n\n/**\n * Validates the computed LP solution.\n */\ndouble MCMCFSolver::getCostUpperBoundAndValidateSolution(\n    const belatedly::FlowDict& flows, const std::list<Edge>& edges) const {\n    std::vector<std::tuple<size_t, std::string, double>> evictions;\n    std::vector<std::tuple<size_t, std::string, double>> inductions;\n\n    // Parse the eviction schedule from the computed LP solution\n    bool is_solution_integral = true;\n    size_t num_fractional_vars = 0;\n    for (const auto& edge : edges) {\n        const bool in_cache = std::get<1>(edge);\n        const std::string& flow_id = std::get<0>(edge);\n\n        // If this is an out-of-cch edge, fetch the\n        // decision variable corresponding to it.\n        if (!in_cache) {\n            const size_t src_idx = idx_to_nodename_.right.at(\n                    std::get<2>(edge)) + z_ - 1;\n\n            const size_t dst_idx =\n                (std::get<3>(edge) == sink_nodes_.at(flow_id)) ?\n                std::numeric_limits<size_t>::max() :\n                idx_to_nodename_.right.at(std::get<3>(edge)) + z_ - 1;\n\n            double value = solution_[flows.getVariableIdx(\n                flow_id, in_cache, std::get<2>(edge),\n                std::get<3>(edge))];\n\n            // The solution has non-integral variables\n            if (!utils::DoubleApproxEqual(value, 1.) &&\n                !utils::DoubleApproxEqual(value, 0.)) {\n                is_solution_integral = false;\n                num_fractional_vars++;\n            }\n            // Perform an eviction at this node\n            if (value > 0.) {\n                evictions.push_back(std::make_tuple(src_idx, flow_id, value));\n                if (dst_idx != std::numeric_limits<size_t>::max()) {\n                    inductions.push_back(std::make_tuple(dst_idx, flow_id, value));\n                }\n            }\n        }\n    }\n    // Populate the inductions list for source nodes\n    for (const auto& item : indices_) {\n        const std::string& flow_id = item.first;\n        const size_t src_idx = item.second.front() + z_ - 1;\n        inductions.push_back(std::make_tuple(src_idx, flow_id, 1.));\n    }\n    // Sort the eviction schedule\n    std::sort(evictions.begin(), evictions.end(), [](\n        const std::tuple<size_t, std::string, double>& a,\n            const std::tuple<size_t, std::string, double>& b) {\n                return (std::get<0>(a) < std::get<0>(b)); });\n\n    // Sort the induction schedule\n    std::sort(inductions.begin(), inductions.end(), [](\n        const std::tuple<size_t, std::string, double>& a,\n            const std::tuple<size_t, std::string, double>& b) {\n                return (std::get<0>(a) < std::get<0>(b)); });\n    // Debug\n    std::cout << \"Solution is \"\n              << (is_solution_integral ? \"INTEGRAL.\" : \"FRACTIONAL.\") << std::endl;\n\n    // For fractional solutions, output the fraction of non-integer decision variables\n    if (!is_solution_integral) {\n        double percentage_fractional = (num_fractional_vars * 100.) / flows.numVariables();\n        std::cout << \"Warning: Solution has \" << num_fractional_vars << \" fractional \"\n                  << \"decision variables (\" << flows.numVariables() << \" in total => \"\n                  << std::fixed << std::setprecision(2) << percentage_fractional\n                  << \"%).\" << std::endl;\n    }\n    // Finally, run the cache simulator and validate the computed LP solution\n    belatedly::CacheSimulator simulator(packets_file_path_, is_solution_integral,\n                                        is_forced_, z_, c_, trace_, evictions,\n                                        inductions);\n    return simulator.run();\n}\n\n/**\n * Solve the MCMCF instance for the given trace.\n */\nvoid MCMCFSolver::solve() {\n\n    // Populate the internal structs\n    setup();\n    std::list<Edge> edges;\n    populateOutOfCchEdges(edges);\n\n    // Create optimization model\n    GRBEnv env = GRBEnv();\n    GRBModel model = GRBModel(env);\n    belatedly::FlowDict flows = belatedly::FlowDict(model);\n\n    // If the solution does not already exist, re-run the optimizer\n    bool is_loaded_from_file = loadOptimizedModelSolution(flows);\n    double opt_cost = std::numeric_limits<double>::max();\n    if (!is_loaded_from_file) {\n\n        // Create variables, populate constraints\n        createFlowVariables(model, flows, edges);\n        populateCchCapacityConstraints(model, flows);\n        populateSplitNodeFlowConstraints(model, flows);\n        populateFlowConservationConstraints(model, flows);\n\n        // Compute the optimal solution\n        model.set(GRB_IntAttr_ModelSense, GRB_MINIMIZE);\n        model.set(GRB_DoubleParam_NodefileStart, 5);\n        model.set(GRB_IntParam_Threads, 1);\n        model.set(GRB_IntParam_Method, 1);\n        model.optimize();\n\n        // Populate the solution vector\n        int status = model.get(GRB_IntAttr_Status);\n        assert(status == GRB_OPTIMAL); // Sanity check\n        for (size_t idx = 0; idx < flows.numVariables(); idx++) {\n            solution_.push_back(flows.getVariableAt(idx).get(GRB_DoubleAttr_X));\n        }\n\n        // Save the optimal solution\n        saveOptimizedModelSolution(flows);\n\n        // Fetch the optimal cost\n        opt_cost = model.get(GRB_DoubleAttr_ObjVal);\n        for (const auto& iter : indices_) {\n            size_t first_idx = iter.second.front();\n            opt_cost += idx_to_miss_cost_.at(first_idx);\n        }\n\n        // Print the cost corresponding to the optimal solution\n        std::cout << \"Optimal cost is: \" << std::fixed\n                  << std::setprecision(3) << opt_cost\n                  << std::endl << std::endl;\n    }\n\n    // Note: This point onwards, we cannot assume that the Gurobi model parameters are\n    // available (since the solution may have been loaded from file). Instead, we use\n    // the flow mappings and the solutions vector in the remainder of the pipeline.\n    double lower_bound = getCostLowerBound(flows, edges);\n    double upper_bound = getCostUpperBoundAndValidateSolution(flows, edges);\n    double delta_percent = ((upper_bound - lower_bound) / lower_bound) * 100;\n\n    // Debug\n    std::cout << \"Lower-bound (LB) on the total latency cost is: \"\n              << std::fixed << std::setprecision(3) << lower_bound\n              << \".\" << std::endl;\n\n    std::cout << \"Upper-bound (UB) on the total latency cost is: \"\n              << std::fixed << std::setprecision(3) << upper_bound\n              << \" (\" << delta_percent << \"% worse than LB).\"\n              << std::endl << std::endl;\n\n    // If the model was solved in this instance, also validate the opt_cost\n    if (!is_loaded_from_file) {\n        assert(utils::DoubleApproxEqual(opt_cost, lower_bound, 1e-2));\n    }\n}\n\nint main(int argc, char **argv) {\n    // Parameters\n    uint z;\n    double c_scale;\n    std::string trace_fp;\n    std::string model_fp;\n    std::string packets_fp;\n\n    // Program options\n    bopt::variables_map variables;\n    bopt::options_description desc{\"BELATEDLY's MCMCF-based solver for\"\n                                   \" the Delayed Hits caching problem\"};\n    try {\n        // Command-line arguments\n        desc.add_options()\n            (\"help\",        \"Prints this message\")\n            (\"trace\",       bopt::value<std::string>(&trace_fp)->required(),            \"Input trace file path\")\n            (\"cscale\",      bopt::value<double>(&c_scale)->required(),                  \"Parameter: Cache size (%Concurrent Flows)\")\n            (\"zfactor\",     bopt::value<uint>(&z)->required(),                          \"Parameter: Z\")\n            (\"model\",       bopt::value<std::string>(&model_fp)->default_value(\"\"),     \"[Optional] Output model file prefix (for checkpointing)\")\n            (\"packets\",     bopt::value<std::string>(&packets_fp)->default_value(\"\"),   \"[Optional] Output packets file path\")\n            (\"forced,f\",                                                                \"[Optional] Use forced admission\");\n\n        // Parse model parameters\n        bopt::store(bopt::parse_command_line(argc, argv, desc), variables);\n\n        // Handle help flag\n        if (variables.count(\"help\")) {\n            std::cout << desc << std::endl;\n            return 0;\n        }\n        bopt::notify(variables);\n    }\n    // Flag argument errors\n    catch(const bopt::required_option& e) {\n        std::cerr << \"Error: \" << e.what() << std::endl;\n        return 1;\n    }\n    catch(...) {\n        std::cerr << \"Unknown Error.\" << std::endl;\n        return 1;\n    }\n\n    // Use forced admission?\n    bool is_forced = (variables.count(\"forced\") != 0);\n\n    // Parse the trace file, and compute the absolute cache size\n    std::vector<std::string> trace = utils::parseTrace(trace_fp);\n    size_t num_cfs = utils::getFlowCounts(trace).num_concurrent_flows;\n    uint c = std::max(1u, static_cast<uint>(round((num_cfs * c_scale) / 100.)));\n\n    // Debug\n    std::cout << \"Optimizing trace: \" << trace_fp << \" (with \" << num_cfs\n              << \" concurrent flows) using z = \" << z << \", c = \" << c\n              << \", and \" << (is_forced ? \"forced\" : \"optional\")\n              << \" admission.\" << std::endl;\n\n    // Instantiate the solver and optimize\n    MCMCFSolver solver(trace_fp, model_fp, packets_fp,\n                       is_forced, z, c, trace);\n    solver.solve();\n}\n", "meta": {"hexsha": "8851eb91b640daf6f65521884f718c6b6d402a14", "size": 41327, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "belatedly/src/belatedly.cpp", "max_stars_repo_name": "Ahziu/Delayed-Hits", "max_stars_repo_head_hexsha": "39e062a34ce7d3bb693dceff0a7e68ea1ee6864b", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2020-09-04T18:32:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:29:05.000Z", "max_issues_repo_path": "belatedly/src/belatedly.cpp", "max_issues_repo_name": "Ahziu/Delayed-Hits", "max_issues_repo_head_hexsha": "39e062a34ce7d3bb693dceff0a7e68ea1ee6864b", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-18T08:14:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-18T08:14:29.000Z", "max_forks_repo_path": "belatedly/src/belatedly.cpp", "max_forks_repo_name": "Ahziu/Delayed-Hits", "max_forks_repo_head_hexsha": "39e062a34ce7d3bb693dceff0a7e68ea1ee6864b", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-10-17T21:39:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T14:29:27.000Z", "avg_line_length": 40.3978494624, "max_line_length": 146, "alphanum_fraction": 0.599753188, "num_tokens": 9492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.29956386500056364}}
{"text": "#pragma once\n#ifndef CANNON_RAY_MESH_H\n#define CANNON_RAY_MESH_H \n\n/*!\n * \\file cannon/ray/mesh.hpp\n * \\brief File containing TriangleMesh and Triangle class definitions.\n */\n\n#include <vector>\n#include <string>\n#include <memory>\n\n#include <assimp/Importer.hpp>\n#include <assimp/scene.h>\n#include <assimp/postprocess.h>\n\n#include <Eigen/Dense>\n\n#include <cannon/ray/hittable.hpp>\n#include <cannon/log/registry.hpp>\n#include <cannon/utils/statistics.hpp>\n#include <cannon/utils/class_forward.hpp>\n\nusing namespace Eigen;\n\nusing namespace cannon::log;\nusing namespace cannon::utils;\n\nnamespace cannon {\n  namespace ray {\n\n    using MatrixX3u = Matrix<unsigned int, Dynamic, 3>;\n    using Vector3u = Matrix<unsigned int, 3, 1>;\n\n    CANNON_CLASS_FORWARD(HittableList);\n\n    /*!\n     * \\brief Class representing a mesh composed of a collection of triangles.\n     */\n    class TriangleMesh {\n      public:\n\n        TriangleMesh() = delete;\n        \n        /*!  \n         * Constructor taking object to world transform, vertices, normals,\n         * texture coords, and face indices defining this mesh.\n         */\n        TriangleMesh(std::shared_ptr<Affine3d> object_to_world,\n            std::shared_ptr<Material> mat, const MatrixX3d& vertices, const\n            MatrixX3d& normals, const MatrixX2d& tex_coords, const MatrixX3u&\n            indices) : object_to_world_(object_to_world), mat_ptr_(mat),\n        vertices_(vertices), normals_(normals), tex_coords_(tex_coords),\n        indices_(indices) {\n\n            // Transform all vertices and normals to world space to save on ray testing computation\n            assert(vertices.rows() == normals.rows());\n\n            for (unsigned int i = 0; i < vertices.rows(); i++) {\n              vertices_.row(i) = (*object_to_world) * vertices.row(i).transpose();\n              normals_.row(i) = object_to_world->linear() * normals.row(i).transpose();\n            }\n          }\n\n\n      public:\n        std::shared_ptr<Affine3d> object_to_world_; //!< Object to world transform for this mesh\n        std::shared_ptr<Material> mat_ptr_; //!< Material for this mesh\n\n        MatrixX3d vertices_; //!< Vertices\n        MatrixX3d normals_; //!< Normals\n        MatrixX2d tex_coords_; //!< Texture coordinates (UV)\n        MatrixX3u indices_; //!< Indices into vertices/normals for each face\n\n    };\n\n    /*!\n     * \\brief Class representing a single triangle hittable.\n     */\n    class Triangle : public Hittable {\n      public:\n\n        Triangle() = delete;\n\n        /*!\n         * Constructor taking object_to_world transform, parent mesh, and face\n         * index within mesh.\n         */\n        Triangle(std::shared_ptr<Affine3d> object_to_world,\n            std::shared_ptr<TriangleMesh> mesh, int mesh_index) :\n          Hittable(object_to_world), parent_mesh_(mesh),\n          mesh_index_(mesh_index) {}\n\n        /*!\n         * Destructor.\n         */\n        virtual ~Triangle() {}\n        \n        /*!\n         * Inherited from Hittable.\n         */\n        virtual bool bounding_box(double time_0, double time_1, Aabb& output_box) const override;\n\n        /*!\n         * Inherited from Hittable.\n         */\n        virtual bool object_space_bounding_box(double time_0, double time_1, Aabb& output_box) const override;\n\n        /*!\n         * Inherited from Hittable.\n         */\n        virtual bool hit(const Ray& r, double t_min, double t_max, hit_record& rec) const override;\n\n        /*!\n         * Inherited from Hittable.\n         */\n        virtual bool object_space_hit(const Ray& r, double t_min, double t_max, hit_record& rec) const override;\n\n      public:\n        std::shared_ptr<TriangleMesh> parent_mesh_; //!< Mesh that this triangle is a part of\n        int mesh_index_; //!< Index of this triangle in the parent mesh\n\n    };\n\n    // Public Functions\n    \n    /*!\n     * Function to load a collection of meshes from an object file.\n     *\n     * \\param t Object-to-world transform for the loaded model.\n     * \\param m Material for loaded model (not loading textures from file for now).\n     * \\param path The file to load.\n     *\n     * \\returns A vector of meshes loaded from the file.\n     */\n    std::vector<std::shared_ptr<TriangleMesh>>\n      load_model(std::shared_ptr<Affine3d> t, std::shared_ptr<Material> m, const std::string& path);\n\n    /*!\n     * Function to process an Assimp model node into a list of meshes.\n     *\n     * \\param t Object-to-world transform for the loaded model.\n     * \\param m Material for loaded model.\n     * \\param node The node to process\n     * \\param scene The overall Assimp scene\n     * \n     * \\returns A vector of meshes loaded from the node.\n     */\n    std::vector<std::shared_ptr<TriangleMesh>>\n      process_model_node(std::shared_ptr<Affine3d> t, std::shared_ptr<Material> m, aiNode *node, const\n          aiScene *scene);\n\n    /*!\n     * Function to process a single Assimp mesh\n     *\n     * \\param t Object-to-world transform for the loaded model.\n     * \\param m Material for loaded mesh\n     * \\param mesh The mesh to process\n     * \\param scene The overall Assimp scene\n     *\n     * \\returns The processed TriangleMesh\n     */\n    std::shared_ptr<TriangleMesh> process_model_mesh(std::shared_ptr<Affine3d>\n        t, std::shared_ptr<Material> m, aiMesh *mesh, const aiScene *scene);\n\n    /*!\n     * Create list of hittable triangles for the input mesh.\n     *\n     * \\param mesh The triangle mesh to process into triangles\n     *\n     * \\returns The list of hittables.\n     */\n    HittableListPtr make_mesh_triangle_list(std::shared_ptr<TriangleMesh> mesh);\n\n    /*!\n     * Permute the coordinates of an input vector.\n     *\n     * \\param p The vector to permute.\n     * \\param x Index of new x coordinate in orginal vector.\n     * \\param y Index of new y coordinate in orginal vector.\n     * \\param z Index of new z coordinate in orginal vector.\n     *\n     * \\return The permuted vector.\n     */\n    Vector3d permute_vec(const Vector3d& p, int x, int y, int z);\n    \n\n  } // namespace ray\n} // namespace cannon\n\n#endif /* ifndef CANNON_RAY_MESH_H */\n", "meta": {"hexsha": "688710e631d8f2ecfd5ef2da41f90496b7a7e84c", "size": 6076, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/ray/mesh.hpp", "max_stars_repo_name": "cannontwo/cannon", "max_stars_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cannon/ray/mesh.hpp", "max_issues_repo_name": "cannontwo/cannon", "max_issues_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2021-01-12T23:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-01T17:29:01.000Z", "max_forks_repo_path": "cannon/ray/mesh.hpp", "max_forks_repo_name": "cannontwo/cannon", "max_forks_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.481865285, "max_line_length": 112, "alphanum_fraction": 0.6374259381, "num_tokens": 1439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2995436234774605}}
{"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 <cmath>\n#include <iomanip>\n#include <algorithm>\n#include <map>\n#include <fstream>  \n#include <stdexcept> \n#define SHA1DETAIL_INLINE_IMPL\n#include <hashclash/sha1detail.hpp>\n#include <hashclash/sha1differentialpath.hpp>\n#include <hashclash/booleanfunction.hpp>\n#include <hashclash/rng.hpp>\n#include <hashclash/timer.hpp>\n#include <hashclash/bestof.hpp>\n#include <hashclash/progress_display.hpp>\n#include <hashclash/sha1messagespace.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/thread.hpp>\nusing namespace std;\nusing namespace hashclash;\n\n//#define FORCE_TEND 80\n//#define FORCE_TEND 27 // 24\n#define FORCE_TEND (20+1)\n\n#define BC_PREVR bc_or2\n#define BC_PREVRN bc_or2b\n\nvector<sha1differentialpath> maincase;\nvector<sha1differentialpath> okpaths;\nmap< sha1differentialpath, vector<sha1differentialpath> > okpaths_index;\n\n        void show_path2(const sha1differentialpath& path, ostream& o = cout)\n        {\n                for (int t = path.tbegin(); t < path.tend(); ++t)\n                {\n                        o << \"Q\" << t << \":\\t\" << path[t];\n                        if (t-4 >= path.tbegin() && t+1 < path.tend() && t >= 0 && t < 80)\n                        {\n                                o << path.getme(t);\n                                vector<unsigned> ambiguous, impossible;\n                                booleanfunction* F = 0;\n                                if (t < 20) F = & SHA1_F1_data;\n                                else if (t < 40) F = & SHA1_F2_data;\n                                else if (t < 60) F = & SHA1_F3_data;\n                                else F = & SHA1_F4_data;\n                                uint32 dF = 0;\n                                for (unsigned b = 0; b < 32; ++b)\n                                {\n                                        bitcondition qtm3b = path(t-3,(b+2)&31); if (qtm3b == BC_PREVR || qtm3b == BC_PREVRN) qtm3b = bc_constant;\n                                        bitcondition qtm2b = path(t-2,(b+2)&31); if (qtm2b == BC_PREVR || qtm2b == BC_PREVRN) qtm2b = bc_constant;\n                                        bitcondition qtm1b = path(t-1,b); if (qtm1b == bc_prev || qtm1b == bc_prevn) qtm1b = bc_constant;\n                                        if (qtm1b == BC_PREVR) qtm1b = bc_prev;\n                                        else if (qtm1b == BC_PREVRN) qtm1b = bc_prevn;\n\t\t\t\t\t\n                                        bf_outcome outcome = F->outcome(qtm1b, qtm2b, qtm3b);\n                                        if (outcome.size() == 1) {\n                                                if (outcome[0] == bc_plus)              dF += 1<<b;\n                                                else if (outcome[0] == bc_minus)        dF -= 1<<b;\n                                        } else {\n                                                if (outcome.size() == 0)\n                                                        impossible.push_back(b);\n                                                else {\n                                                        if (b == 31 && outcome.size() == 2 && outcome(0,31)==outcome(1,31)) {\n                                                                dF += 1<<31;\n                                                                continue;   \n                                                        }\n                                                        ambiguous.push_back(b);\n                                                }\n                                        }\n                                }\n                                uint32 dQtp1 = dF + path.getme(t).adddiff() + path[t].getsdr().rotate_left(5).adddiff() + path[t-4].getsdr().rotate_left(30).adddiff();\n                                if (dQtp1 == path[t+1].diff())\n                                        o << \" ok\";\n                                else\n                                        o << \" bad(\" << naf(dQtp1 - path[t+1].diff()) << \")\";\n                                if (ambiguous.size() > 0)\n                                {\n                                        o << \" amb:\" << ambiguous[0];\n                                        for (unsigned i = 1; i < ambiguous.size(); ++i)\n                                                o << \",\" << ambiguous[i];\n                                }\n                                if (impossible.size() > 0)\n                                {\n                                        o << \" imp:\" << impossible[0];\n                                        for (unsigned i = 1; i < impossible.size(); ++i)\n                                                o << \",\" << impossible[i];\n                                }\n                        } else   \n                                o << sdr();\n                        o << endl;\n                }\n        }\n\nvoid cleanuppath2(sha1differentialpath& path)\n{\n        sha1differentialpath newpath;\n        for (int t = path.tbegin(); t < path.tend(); ++t) {\n                if (t-4 >= path.tbegin() && t+1 < path.tend()) {\n                        newpath.getme(t) = path.getme(t);\n                        if (newpath.getme(t).get(31)!= 0)\n                          newpath.getme(t).sign |= 1<<31;\n                }\n                newpath[t] = path[t].getsdr();\n        }\n        for (int t = path.tend()-2; t-4 >= path.tbegin(); --t) {\n          booleanfunction* F = 0;\n          if (t < 20) F = & SHA1_F1_data;\n          else if (t < 40) F = & SHA1_F2_data;\n          else if (t < 60) F = & SHA1_F3_data;\n          else F = & SHA1_F4_data;\n          for (unsigned b = 0; b < 32; ++b) {\n              bitcondition qtm3bo = path(t-3,(b+2)&31);\n              bitcondition qtm2bo = path(t-2,(b+2)&31);\n              bitcondition qtm1bo = path(t-1,b);\n              bitcondition qtm3b = newpath(t-3,(b+2)&31); if (qtm3b == BC_PREVR || qtm3b == BC_PREVRN) qtm3b = bc_constant;\n              bitcondition qtm2b = newpath(t-2,(b+2)&31); if (qtm2b == BC_PREVR || qtm2b == BC_PREVRN) qtm2b = bc_constant;\n              bitcondition qtm1b = newpath(t-1,b); if (qtm1b == bc_prev || qtm1b == bc_prevn) qtm1b = bc_constant;\n              if (qtm1b == BC_PREVR) qtm1b = bc_prev;\n              else if (qtm1b == BC_PREVRN) qtm1b = bc_prevn;\n              bf_outcome outcome_path = F->outcome(qtm1bo, qtm2bo, qtm3bo);\n              if (outcome_path.size() != 1 && b < 31) {\n                cerr << \"multiple outcome \" << t << \" \" << b << endl;\n                show_path2(path);\n                exit(0);\n              }\n              bf_outcome outcome = F->outcome(qtm1b, qtm2b, qtm3b);\n              if (outcome.size() > 1 && b < 31) {\n                bf_conditions newcond = F->backwardconditions(qtm1b, qtm2b, qtm3b, outcome_path[0]);\n                if (newcond.first == bc_prev) newcond.first = BC_PREVR;\n                if (newcond.first == bc_prevn) newcond.first = BC_PREVRN;\n                newpath.setbitcondition(t-1,b,newcond.first);\n                newpath.setbitcondition(t-2,(b+2)&31,newcond.second);\n                newpath.setbitcondition(t-3,(b+2)&31,newcond.third);\n              } else if (b == 31 && outcome.size() > 1 && outcome_path[0] == bc_constant) {\n                bf_conditions newcond = F->backwardconditions(qtm1b, qtm2b, qtm3b, bc_constant);\n                if (newcond.first == bc_prev) newcond.first = BC_PREVR;\n                if (newcond.first == bc_prevn) newcond.first = BC_PREVRN;\n                newpath.setbitcondition(t-1,b,newcond.first);\n                newpath.setbitcondition(t-2,(b+2)&31,newcond.second);\n                newpath.setbitcondition(t-3,(b+2)&31,newcond.third);\n              } else if (b == 31 && outcome.size() > 1 && outcome_path[0] != bc_constant) {\n                if (outcome.size() == 3) {\n                  // request dF[b] = 0\n                  bf_conditions newcond = F->backwardconditions(qtm1b, qtm2b, qtm3b, bc_constant);\n                  // invert addition bitconditions\n                  if (newcond.second == bc_prev) newcond.second = bc_prevn;\n                  if (newcond.first == bc_prev) newcond.first = BC_PREVR;\n                  if (newcond.first == bc_prevn) newcond.first = BC_PREVRN;\n                  newpath.setbitcondition(t-1,b,newcond.first);\n                  newpath.setbitcondition(t-2,(b+2)&31,newcond.second);\n                  newpath.setbitcondition(t-3,(b+2)&31,newcond.third);\n                }\n              }\n          }\n        }\n  path = newpath;        \n}\n\nvoid loadokpaths()\n{\n  cout << \"Searching for files 'okpaths.*.bz2'...\" << endl;\n  for (boost::filesystem::directory_iterator dit(\".\"); dit != boost::filesystem::directory_iterator(); ++dit)\n#if BOOST_VERSION == 104300\n    if (dit->path().filename().substr(0,8) == \"okpaths.\" &&  dit->path().extension() == \".bz2\")\n#else\n    if (dit->path().filename().string().substr(0,8) == \"okpaths.\" &&  dit->path().extension() == \".bz2\")\n#endif\n    {\n#if BOOST_VERSION == 104300\n      string file = dit->path().filename();\n#else\n      string file = dit->path().filename().string();\n#endif\n      cout << \"Loading '\" << file << \"'...\" << flush;\n      vector<sha1differentialpath> tmp;\n      for (unsigned trycnt = 0; tmp.size()==0 && trycnt < 2; ++trycnt) {\n        try {\n          load_bz2(tmp, text_archive, dit->path());\n        } catch (std::exception& e) { \n          cout << e.what() << endl; tmp.clear();\n          boost::this_thread::sleep(boost::posix_time::milliseconds(100));\n        }\n      }\n      okpaths.insert(okpaths.end(), tmp.begin(), tmp.end());\n      cout << \"done: \" << tmp.size() << \" paths (new total: \" << okpaths.size() << \")\" << endl;\n    }\n}\nvoid index_okpaths()\n{\n#if 1\n  for (unsigned i = 0; i < okpaths.size(); ++i) {\n    cleanuppath2(okpaths[i]);\n    if (okpaths[i].tend() > FORCE_TEND) {\n      okpaths[i].path.resize( okpaths[i].path.size() + FORCE_TEND - okpaths[i].tend() );\n      okpaths[i].me.resize( okpaths[i].path.size() ); \n    }\n    okpaths_index[okpaths[i]].push_back(okpaths[i]);\n  }\n#else\n  for (unsigned i = 0; i < okpaths.size(); ++i) {\n    sha1differentialpath tmp;\n    for (int t = okpaths[i].tbegin(); t < okpaths[i].tend() && t < FORCE_TEND; ++t) {\n      tmp[t] = okpaths[i][t].getsdr();\n      \n      if (t-4 >= okpaths[i].tbegin() && t+1 < okpaths[i].tend() && t+1 < FORCE_TEND) {\n        tmp.getme(t) = okpaths[i].getme(t);\n        sdr me = tmp.getme(t);\n        if (me.mask & (1<<31)) me.sign |= 1<<31;\n        tmp.getme(t) = me;\n      }\n    }\n    if (okpaths[i].tend() > FORCE_TEND) {\n      okpaths[i].path.resize( okpaths[i].path.size() + FORCE_TEND - okpaths[i].tend() );\n      okpaths[i].me.resize( okpaths[i].path.size() ); \n    }\n    okpaths_index[tmp].push_back(okpaths[i]);\n  }\n#endif\n  cout << \"Total # cases: \" << okpaths_index.size() << endl;\n  unsigned totalcasecnts = 0;\n  vector<unsigned> casecnts;\n  for (map< sha1differentialpath, vector<sha1differentialpath> >::const_iterator\n       cit = okpaths_index.begin(); cit != okpaths_index.end(); ++cit)\n  {\n    totalcasecnts += cit->second.size();\n    casecnts.push_back(cit->second.size());\n    if (cit->second.size() > maincase.size())\n      maincase = cit->second;\n  }\n  vector<unsigned> casecntsbu = casecnts;\n  unsigned cumcasecnts = 0;\n  while (double(cumcasecnts) < double(totalcasecnts)*1.0)\n  {\n    int highind = -1, highval = 0;\n    for (unsigned i = 0; i < casecntsbu.size(); ++i)\n      if (casecntsbu[i] > highval) { highind = i; highval = casecntsbu[i]; }\n    if (highind == -1) throw;\n    cumcasecnts += highval;\n    casecntsbu[highind] = 0;   \n  }\n  unsigned i = 0;\n  for (map< sha1differentialpath, vector<sha1differentialpath> >::const_iterator\n       cit = okpaths_index.begin(); cit != okpaths_index.end(); ++cit,++i)\n  {\n    if (casecntsbu[i] == 0) {\n      cout << \"Case \" << i << \": # paths = \" << casecnts[i] << \" (\" << double(100*casecnts[i])/double(totalcasecnts) << \"%)\" << endl;\n      show_path2(cit->second[0]);\n    }\n  }\n}\n\nvoid checkokpaths()\n{\n  loadokpaths();\n  index_okpaths();\n  exit(0);\n}\n", "meta": {"hexsha": "8975017ca43df4b783f7052aac0f2b4208cae7b9", "size": 12871, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sha1attackgenerator/checkokpaths.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/checkokpaths.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/checkokpaths.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": 46.2985611511, "max_line_length": 167, "alphanum_fraction": 0.4794499262, "num_tokens": 3344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723316860482762, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.2995436234774605}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   MonteCarlo_SubshellIncoherentPhotonScatteringDistribution.cpp\n//! \\author Alex Robinson\n//! \\brief  The subshell incoherent photon scattering distribution decl.\n//!\n//---------------------------------------------------------------------------//\n\n// Std Lib Includes\n#include <limits>\n\n// Boost Includes\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\n// FRENSIE Includes\n#include \"MonteCarlo_SubshellIncoherentPhotonScatteringDistribution.hpp\"\n#include \"MonteCarlo_PhotonKinematicsHelpers.hpp\"\n#include \"MonteCarlo_ElectronState.hpp\"\n#include \"Utility_PhysicalConstants.hpp\"\n#include \"Utility_RandomNumberGenerator.hpp\"\n#include \"Utility_GaussKronrodIntegrator.hpp\"\n#include \"Utility_ContractException.hpp\"\n\nnamespace MonteCarlo{\n\n// Constructor\n/*! \\details The occupation number grid must be in me*c units.\n */\nSubshellIncoherentPhotonScatteringDistribution::SubshellIncoherentPhotonScatteringDistribution(\n       const SubshellType interaction_subshell,\n       const double num_electrons_in_subshell,\n       const double binding_energy,\n       const Teuchos::RCP<const Utility::OneDDistribution>& occupation_number,\n       const double kahn_sampling_cutoff_energy )\n  : IncoherentPhotonScatteringDistribution( kahn_sampling_cutoff_energy ),\n    d_subshell( interaction_subshell ),\n    d_num_electrons_in_subshell( num_electrons_in_subshell ),\n    d_binding_energy( binding_energy ),\n    d_occupation_number( occupation_number )\n{\n  // Make sure the interaction subshell is valid\n  testPrecondition( interaction_subshell != INVALID_SUBSHELL );\n  testPrecondition( interaction_subshell != UNKNOWN_SUBSHELL );\n  // Make sure the number of electrons is valid\n  testPrecondition( num_electrons_in_subshell > 0.0 );\n  // Make sure the binding energy is valid\n  testPrecondition( binding_energy > 0.0 );\n  // Make sure the occupation number is valid\n  testPrecondition( !occupation_number.is_null() );\n  testPrecondition( occupation_number->getLowerBoundOfIndepVar() == -1.0 );  \n}\n\n\n// Return the subshell\nSubshellType \nSubshellIncoherentPhotonScatteringDistribution::getSubshell() const\n{\n  return d_subshell;\n}\n\n// Return the number of electrons in the subshell\ndouble SubshellIncoherentPhotonScatteringDistribution::getNumberOfElectronsInSubshell() const\n{\n  return d_num_electrons_in_subshell;\n}\n\n// Return the binding energy\ndouble SubshellIncoherentPhotonScatteringDistribution::getBindingEnergy() const\n{\n  return d_binding_energy;\n}\n\n// Evaluate the distribution\ndouble SubshellIncoherentPhotonScatteringDistribution::evaluate( \n\t\t\t           const double incoming_energy,\n\t\t\t           const double scattering_angle_cosine ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > d_binding_energy );\n  // Make sure the scattering angle cosine is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n\n  const double occupation_number = \n    this->evaluateOccupationNumber( incoming_energy, scattering_angle_cosine );\n  \n  const double diff_kn_cross_section = \n    this->evaluateKleinNishinaDist( incoming_energy,\n\t\t\t\t    scattering_angle_cosine );\n\n  return d_num_electrons_in_subshell*occupation_number*diff_kn_cross_section;\n}\n\n// Evaluate the integrated cross section (cm^2)\ndouble SubshellIncoherentPhotonScatteringDistribution::evaluateIntegratedCrossSection( \n\t\t\t\t\t\t  const double incoming_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 > d_binding_energy );\n\n  // Evaluate the integrated cross section\n  boost::function<double (double x)> diff_cs_wrapper = \n    boost::bind<double>( &SubshellIncoherentPhotonScatteringDistribution::evaluate,\n\t\t\t boost::cref( *this ),\n\t\t\t incoming_energy,\n\t\t\t _1 );\n\n  double abs_error, integrated_cs;\n\n  Utility::GaussKronrodIntegrator quadrature_gkq_set( precision );\n\n  quadrature_gkq_set.integrateAdaptively<15>( diff_cs_wrapper,\n\t\t\t\t\t     -1.0,\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 a Compton line energy (no\n * Doppler broadening).\n */ \nvoid SubshellIncoherentPhotonScatteringDistribution::sample( \n\t\t\t\t     const double incoming_energy,\n\t\t\t\t     double& outgoing_energy,\n\t\t\t\t     double& scattering_angle_cosine ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > d_binding_energy );\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 a Compton line energy (no\n * Doppler broadening).\n */ \nvoid SubshellIncoherentPhotonScatteringDistribution::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 > d_binding_energy );\n\n  // Evaluate the maximum occupation number\n  const double max_occupation_number = \n    this->evaluateOccupationNumber( incoming_energy, -1.0 );\n\n  while( true )\n  {\n    this->sampleAndRecordTrialsKleinNishina( incoming_energy,\n\t\t\t\t\t     outgoing_energy,\n\t\t\t\t\t     scattering_angle_cosine,\n\t\t\t\t\t     trials );\n\n    const double occupation_number = \n      this->evaluateOccupationNumber( incoming_energy, \n\t\t\t\t      scattering_angle_cosine );\n\n    const double scaled_random_number = max_occupation_number*\n      Utility::RandomNumberGenerator::getRandomNumber<double>();\n\n    if( scaled_random_number <= occupation_number )\n      break;\n  }\n\n  // Make sure the scattering angle cosine is valid\n  testPostcondition( scattering_angle_cosine >= -1.0 );\n  testPostcondition( scattering_angle_cosine <= 1.0 );\n  // Make sure the compton line energy is valid\n  testPostcondition( outgoing_energy <= incoming_energy );\n  remember( double alpha = incoming_energy/\n\t    Utility::PhysicalConstants::electron_rest_mass_energy );\n  testPostcondition( outgoing_energy >= incoming_energy/(1+2*alpha) );\n}\n\n// Evaluate the occupation number \ndouble \nSubshellIncoherentPhotonScatteringDistribution::evaluateOccupationNumber(\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 >= d_binding_energy );\n  // Make sure the scattering angle cosine is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n  \n  const double occupation_number_arg = \n    this->calculateOccupationNumberArgument( incoming_energy,\n\t\t\t\t\t     scattering_angle_cosine );\n\n  return d_occupation_number->evaluate( occupation_number_arg );\n}\n\n// Calculate the occupation number argument (pz max)\ndouble SubshellIncoherentPhotonScatteringDistribution::calculateOccupationNumberArgument(\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 >= d_binding_energy );\n  // Make sure the scattering angle cosine is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n\n  double occupation_number_arg = \n    calculateMaxElectronMomentumProjection( incoming_energy,\n\t\t\t\t\t    d_binding_energy,\n\t\t\t\t\t    scattering_angle_cosine );\n\n  if( occupation_number_arg >= d_occupation_number->getUpperBoundOfIndepVar() )\n    occupation_number_arg = d_occupation_number->getUpperBoundOfIndepVar();\n\n  // Make sure the occupation number arg is valid\n  testPostcondition( occupation_number_arg >= \n\t\t     d_occupation_number->getLowerBoundOfIndepVar() );\n  testPostcondition( occupation_number_arg <=\n\t\t     d_occupation_number->getUpperBoundOfIndepVar() );\n\n  return occupation_number_arg;\n}\n\n// Randomly scatter the photon\n/*! \\details The particle bank is used to store the electron that is emitted\n * from the collision. Whether or not Doppler broadening is done, the \n * energy and direction of the outgoing electron is calculated as if it were\n * at rest initially (feel free to update this model!).\n */\nvoid SubshellIncoherentPhotonScatteringDistribution::scatterPhoton( \n\t\t\t\t     PhotonState& photon,\n\t\t\t\t     ParticleBank& bank,\n\t\t\t\t     SubshellType& shell_of_interaction ) const\n{\n  // Make sure the photon energy is valid\n  testPrecondition( photon.getEnergy() > d_binding_energy );\n\n  double outgoing_energy, scattering_angle_cosine;\n\n  // Sample an outgoing energy and direction\n  this->sample( photon.getEnergy(),\n\t\toutgoing_energy,\n\t\tscattering_angle_cosine );\n\n  // Set the interaction subshell\n  shell_of_interaction = d_subshell;\n\n  // Sample the azimuthal angle of the outgoing photon\n  const double azimuthal_angle = this->sampleAzimuthalAngle();\n\n  // Create the ejectected electron\n  this->createEjectedElectron( photon, \n\t\t\t       scattering_angle_cosine, \n\t\t\t       azimuthal_angle,\n\t\t\t       bank );\n  \n  // Set the new energy\n  if( outgoing_energy > 0.0 )\n  {\n    photon.setEnergy( outgoing_energy );\n    \n    // Set the new direction\n    photon.rotateDirection( scattering_angle_cosine, azimuthal_angle );\n  }\n  else\n  {\n    photon.setEnergy( std::numeric_limits<double>::min() );\n\n    photon.setAsGone();\n  }\n}\n \n} // end MonteCarlo namespace\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_SubshellIncoherentPhotonScatteringDistribution.cpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "e67cbcd35cf891dd7ff29f5aa79d4b6a47b9cd41", "size": 9988, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/collision/native/src/MonteCarlo_SubshellIncoherentPhotonScatteringDistribution.cpp", "max_stars_repo_name": "lkersting/SCR-2123", "max_stars_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "packages/monte_carlo/collision/native/src/MonteCarlo_SubshellIncoherentPhotonScatteringDistribution.cpp", "max_issues_repo_name": "lkersting/SCR-2123", "max_issues_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "packages/monte_carlo/collision/native/src/MonteCarlo_SubshellIncoherentPhotonScatteringDistribution.cpp", "max_forks_repo_name": "lkersting/SCR-2123", "max_forks_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2054794521, "max_line_length": 95, "alphanum_fraction": 0.7338806568, "num_tokens": 2176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.29954279967694514}}
{"text": "/**\n * Copyright (c) 2020 libnuls developers (see AUTHORS)\n *\n * This file is part of libnuls.\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 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 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#include <nuls/system/math/elliptic_curve.hpp>\n\n#include <algorithm>\n#include <utility>\n#include <secp256k1.h>\n#include <secp256k1_recovery.h>\n#include <boost/ptr_container/ptr_vector.hpp>\n#include <nuls/system/math/hash.hpp>\n#include <nuls/system/math/limits.hpp>\n#include <nuls/system/utility/assert.hpp>\n#include <nuls/system/utility/data.hpp>\n#include <nuls/system/wallet/hd_private.hpp>\n#include \"../math/external/lax_der_parsing.h\"\n#include \"secp256k1_initializer.hpp\"\n\nnamespace libnuls {\nnamespace system {\n\nusing namespace boost;\n\nstatic constexpr uint8_t compressed_even = 0x02;\nstatic constexpr uint8_t compressed_odd = 0x03;\nstatic constexpr uint8_t uncompressed = 0x04;\n\nBC_CONSTFUNC int to_flags(bool compressed)\n{\n    return compressed ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED;\n}\n\n// Helper templates\n// ----------------------------------------------------------------------------\n// These allow strong typing of private keys without redundant code.\n\ntemplate <size_t Size>\nbool parse(const secp256k1_context* context, secp256k1_pubkey& out,\n    const byte_array<Size>& point)\n{\n    return secp256k1_ec_pubkey_parse(context, &out, point.data(), Size) == 1;\n}\n\ntemplate <size_t Size>\nbool serialize(const secp256k1_context* context, byte_array<Size>& out,\n    const secp256k1_pubkey point)\n{\n    auto size = Size;\n    const auto flags = to_flags(Size == ec_compressed_size);\n    secp256k1_ec_pubkey_serialize(context, out.data(), &size, &point, flags);\n    return size == Size;\n}\n\ntemplate <size_t Size>\nbool ec_add(const secp256k1_context* context, byte_array<Size>& in_out,\n    const ec_secret& secret)\n{\n    secp256k1_pubkey pubkey;\n    return parse(context, pubkey, in_out) &&\n        secp256k1_ec_pubkey_tweak_add(context, &pubkey, secret.data()) == 1 &&\n        serialize(context, in_out, pubkey);\n}\n\ntemplate <size_t Size>\nbool ec_multiply(const secp256k1_context* context, byte_array<Size>& in_out,\n    const ec_secret& secret)\n{\n    secp256k1_pubkey pubkey;\n    return parse(context, pubkey, in_out) &&\n        secp256k1_ec_pubkey_tweak_mul(context, &pubkey, secret.data()) == 1 &&\n        serialize(context, in_out, pubkey);\n}\n\ntemplate <size_t Size>\nbool ec_negate(const secp256k1_context* context, byte_array<Size>& in_out)\n{\n    secp256k1_pubkey pubkey;\n    return parse(context, pubkey, in_out) &&\n        secp256k1_ec_pubkey_negate(context, &pubkey) == 1 &&\n        serialize(context, in_out, pubkey);\n}\n\ntemplate <size_t Size>\nbool secret_to_public(const secp256k1_context* context, byte_array<Size>& out,\n    const ec_secret& secret)\n{\n    secp256k1_pubkey pubkey;\n    return secp256k1_ec_pubkey_create(context, &pubkey, secret.data()) == 1 &&\n        serialize(context, out, pubkey);\n}\n\ntemplate <size_t Size>\nbool recover_public(const secp256k1_context* context, byte_array<Size>& out,\n    const recoverable_signature& recoverable, const hash_digest& hash)\n{\n    secp256k1_pubkey pubkey;\n    secp256k1_ecdsa_recoverable_signature sign;\n    const auto recovery_id = safe_to_signed<int>(recoverable.recovery_id);\n    return\n        secp256k1_ecdsa_recoverable_signature_parse_compact(context,\n            &sign, recoverable.signature.data(), recovery_id) == 1 &&\n        secp256k1_ecdsa_recover(context, &pubkey, &sign, hash.data()) == 1 &&\n            serialize(context, out, pubkey);\n}\n\nbool verify_signature(const secp256k1_context* context,\n    const secp256k1_pubkey point, const hash_digest& hash,\n    const ec_signature& signature)\n{\n    // Copy to avoid exposing external types.\n    secp256k1_ecdsa_signature parsed;\n    std::copy_n(signature.begin(), ec_signature_size, std::begin(parsed.data));\n\n    // secp256k1_ecdsa_verify rejects non-normalized (low-s) signatures, but\n    // bitcoin does not have such a limitation, so we always normalize.\n    secp256k1_ecdsa_signature normal;\n    secp256k1_ecdsa_signature_normalize(context, &normal, &parsed);\n    return secp256k1_ecdsa_verify(context, &normal, hash.data(), &point) == 1;\n}\n\n// Add and multiply EC values\n// ----------------------------------------------------------------------------\n\nbool ec_add(ec_compressed& point, const ec_secret& scalar)\n{\n    const auto context = verification.context();\n    return ec_add(context, point, scalar);\n}\n\nbool ec_add(ec_uncompressed& point, const ec_secret& scalar)\n{\n    const auto context = verification.context();\n    return ec_add(context, point, scalar);\n}\n\nbool ec_add(ec_secret& left, const ec_secret& right)\n{\n    const auto context = verification.context();\n    return secp256k1_ec_privkey_tweak_add(context, left.data(),\n        right.data()) == 1;\n}\n\nbool ec_multiply(ec_compressed& point, const ec_secret& scalar)\n{\n    const auto context = verification.context();\n    return ec_multiply(context, point, scalar);\n}\n\nbool ec_multiply(ec_uncompressed& point, const ec_secret& scalar)\n{\n    const auto context = verification.context();\n    return ec_multiply(context, point, scalar);\n}\n\nbool ec_multiply(ec_secret& left, const ec_secret& right)\n{\n    const auto context = verification.context();\n    return secp256k1_ec_privkey_tweak_mul(context, left.data(),\n        right.data()) == 1;\n}\n\nbool ec_negate(ec_secret& scalar)\n{\n    const auto context = verification.context();\n    return secp256k1_ec_privkey_negate(context, scalar.data()) == 1;\n}\n\nbool ec_negate(ec_compressed& point)\n{\n    const auto context = verification.context();\n    return ec_negate(context, point);\n}\n\nbool ec_sum(ec_compressed& result, const point_list& points)\n{\n    secp256k1_pubkey pubkey;\n    ptr_vector<secp256k1_pubkey> keys(points.size());\n    const auto context = verification.context();\n\n    for (const auto& point: points)\n    {\n        keys.push_back(new secp256k1_pubkey);\n        if (!parse(context, keys.back(), point))\n            return false;\n    }\n\n    return secp256k1_ec_pubkey_combine(context, &pubkey, keys.c_array(),\n        points.size()) == 1 && serialize(context, result, pubkey);\n}\n\n// Convert keys\n// ----------------------------------------------------------------------------\n\nbool compress(ec_compressed& out, const ec_uncompressed& point)\n{\n    secp256k1_pubkey pubkey;\n    const auto context = verification.context();\n    return parse(context, pubkey, point) && serialize(context, out, pubkey);\n}\n\nbool decompress(ec_uncompressed& out, const ec_compressed& point)\n{\n    secp256k1_pubkey pubkey;\n    const auto context = verification.context();\n    return parse(context, pubkey, point) && serialize(context, out, pubkey);\n}\n\nbool secret_to_public(ec_compressed& out, const ec_secret& secret)\n{\n    const auto context = signing.context();\n    return secret_to_public(context, out, secret);\n}\n\nbool secret_to_public(ec_uncompressed& out, const ec_secret& secret)\n{\n    const auto context = signing.context();\n    return secret_to_public(context, out, secret);\n}\n\n// Verify keys\n// ----------------------------------------------------------------------------\n\nbool verify(const ec_secret& secret)\n{\n    const auto context = verification.context();\n    return secp256k1_ec_seckey_verify(context, secret.data()) == 1;\n}\n\nbool verify(const ec_compressed& point)\n{\n    secp256k1_pubkey pubkey;\n    const auto context = verification.context();\n    return parse(context, pubkey, point);\n}\n\nbool verify(const ec_uncompressed& point)\n{\n    secp256k1_pubkey pubkey;\n    const auto context = verification.context();\n    return parse(context, pubkey, point);\n}\n\n// Detect public keys\n// ----------------------------------------------------------------------------\n\nbool is_compressed_key(const data_slice& point)\n{\n    const auto size = point.size();\n    if (size != ec_compressed_size)\n        return false;\n\n    const auto first = point.data()[0];\n    return first == compressed_even || first == compressed_odd;\n}\n\nbool is_uncompressed_key(const data_slice& point)\n{\n    const auto size = point.size();\n    if (size != ec_uncompressed_size)\n        return false;\n\n    const auto first = point.data()[0];\n    return first == uncompressed;\n}\n\nbool is_public_key(const data_slice& point)\n{\n    return is_compressed_key(point) || is_uncompressed_key(point);\n}\n\nbool is_even_key(const ec_compressed& point)\n{\n    return point.front() == ec_even_sign;\n}\n\nbool is_endorsement(const endorsement& endorsement)\n{\n    const auto size = endorsement.size();\n    return size >= min_endorsement_size && size <= max_endorsement_size;\n}\n\n// DER parse/encode\n// ----------------------------------------------------------------------------\n\nbool parse_endorsement(uint8_t& sighash_type, der_signature& der_signature,\n    const endorsement& endorsement)\n{\n    if (endorsement.empty())\n        return false;\n\n    sighash_type = endorsement.back();\n    der_signature = { endorsement.begin(), endorsement.end() - 1 };\n    return true;\n}\n\nbool parse_signature(ec_signature& out, const der_signature& der_signature,\n    bool strict)\n{\n    if (der_signature.empty())\n        return false;\n\n    bool valid;\n    secp256k1_ecdsa_signature parsed;\n    const auto context = verification.context();\n\n    if (strict)\n        valid = secp256k1_ecdsa_signature_parse_der(context, &parsed,\n            der_signature.data(), der_signature.size()) == 1;\n    else\n        valid = ecdsa_signature_parse_der_lax(context, &parsed,\n            der_signature.data(), der_signature.size()) == 1;\n\n    if (valid)\n        std::copy_n(std::begin(parsed.data), ec_signature_size, out.begin());\n\n    return valid;\n}\n\nbool encode_signature(der_signature& out, const ec_signature& signature)\n{\n    // Copy to avoid exposing external types.\n    secp256k1_ecdsa_signature sign;\n    std::copy_n(signature.begin(), ec_signature_size, std::begin(sign.data));\n\n    const auto context = signing.context();\n    auto size = max_der_signature_size;\n    out.resize(size);\n\n    if (secp256k1_ecdsa_signature_serialize_der(context, out.data(), &size,\n        &sign) != 1)\n        return false;\n\n    out.resize(size);\n    return true;\n}\n\n// EC sign/verify\n// ----------------------------------------------------------------------------\n\nbool sign(ec_signature& out, const ec_secret& secret, const hash_digest& hash)\n{\n    secp256k1_ecdsa_signature signature;\n    const auto context = signing.context();\n\n    if (secp256k1_ecdsa_sign(context, &signature, hash.data(), secret.data(),\n        secp256k1_nonce_function_rfc6979, nullptr) != 1)\n        return false;\n\n    std::copy_n(std::begin(signature.data), out.size(), out.begin());\n    return true;\n}\n\nbool verify_signature(const ec_compressed& point, const hash_digest& hash,\n    const ec_signature& signature)\n{\n    secp256k1_pubkey pubkey;\n    const auto context = verification.context();\n    return parse(context, pubkey, point) &&\n        verify_signature(context, pubkey, hash, signature);\n}\n\nbool verify_signature(const ec_uncompressed& point, const hash_digest& hash,\n    const ec_signature& signature)\n{\n    secp256k1_pubkey pubkey;\n    const auto context = verification.context();\n    return parse(context, pubkey, point) &&\n        verify_signature(context, pubkey, hash, signature);\n}\n\nbool verify_signature(const data_slice& point, const hash_digest& hash,\n    const ec_signature& signature)\n{\n    // Copy to avoid exposing external types.\n    secp256k1_ecdsa_signature parsed;\n    std::copy_n(signature.begin(), ec_signature_size, std::begin(parsed.data));\n\n    // secp256k1_ecdsa_verify rejects non-normalized (low-s) signatures, but\n    // bitcoin does not have such a limitation, so we always normalize.\n    secp256k1_ecdsa_signature normal;\n    const auto context = verification.context();\n    secp256k1_ecdsa_signature_normalize(context, &normal, &parsed);\n\n    // This uses a data slice and calls secp256k1_ec_pubkey_parse() in place of\n    // parse() so that we can support the der_verify data_chunk optimization.\n    secp256k1_pubkey pubkey;\n    const auto size = point.size();\n    return\n        secp256k1_ec_pubkey_parse(context, &pubkey, point.data(), size) == 1 &&\n        secp256k1_ecdsa_verify(context, &normal, hash.data(), &pubkey) == 1;\n}\n\n// Recoverable sign/recover\n// ----------------------------------------------------------------------------\n\nbool sign_recoverable(recoverable_signature& out, const ec_secret& secret,\n    const hash_digest& hash)\n{\n    int recovery_id = 0;\n    const auto context = signing.context();\n    secp256k1_ecdsa_recoverable_signature signature;\n\n    const auto result =\n        secp256k1_ecdsa_sign_recoverable(context, &signature, hash.data(),\n            secret.data(), secp256k1_nonce_function_rfc6979, nullptr) == 1 &&\n        secp256k1_ecdsa_recoverable_signature_serialize_compact(context,\n            out.signature.data(), &recovery_id, &signature) == 1;\n\n    BITCOIN_ASSERT(recovery_id >= 0 && recovery_id <= 3);\n    out.recovery_id = safe_to_unsigned<uint8_t>(recovery_id);\n    return result;\n}\n\nbool recover_public(ec_compressed& out,\n    const recoverable_signature& recoverable, const hash_digest& hash)\n{\n    const auto context = verification.context();\n    return recover_public(context, out, recoverable, hash);\n}\n\nbool recover_public(ec_uncompressed& out,\n    const recoverable_signature& recoverable, const hash_digest& hash)\n{\n    const auto context = verification.context();\n    return recover_public(context, out, recoverable, hash);\n}\n\n} // namespace system\n} // namespace libnuls\n", "meta": {"hexsha": "3b8f8d81cdb0197062189402a5bdab57cb90f233", "size": 14072, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/elliptic_curve.cpp", "max_stars_repo_name": "ccccbjcn/nuls-v2-cplusplus-sdk", "max_stars_repo_head_hexsha": "3d5a76452fe0673eba490b26e5a95fea3d5788df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-26T07:32:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-26T07:32:52.000Z", "max_issues_repo_path": "src/math/elliptic_curve.cpp", "max_issues_repo_name": "CCC-NULS/nuls-cplusplus-sdk", "max_issues_repo_head_hexsha": "3d5a76452fe0673eba490b26e5a95fea3d5788df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/elliptic_curve.cpp", "max_forks_repo_name": "CCC-NULS/nuls-cplusplus-sdk", "max_forks_repo_head_hexsha": "3d5a76452fe0673eba490b26e5a95fea3d5788df", "max_forks_repo_licenses": ["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.6224719101, "max_line_length": 79, "alphanum_fraction": 0.6890278567, "num_tokens": 3297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2995037328812037}}
{"text": "//\n// Created by Nathan on 7/10/2015.\n//\n\n#include \"world/PlainsCell.h\"\n#include \"world/DesertCell.h\"\n#include \"world/ForestCell.h\"\n#include \"game/Civilian.h\"\n#include \"game/generation/ClusterSeederV2.h\"\n#include <boost/math/constants/constants.hpp>\n#include <numeric/Random.h>\n#include <boost/generator_iterator.hpp>\n\n\nnamespace undocked {\n    namespace game {\n        namespace generation {\n            numeric::Random random(10);\n\n            using namespace world;\n\n            ClusterSeederV2::ClusterSeederV2() {\n\n            }\n\n            ClusterSeederV2::~ClusterSeederV2() {\n\n            }\n\n            void ClusterSeederV2::seedTerrain(GameState *state) {\n                std::cout << \"Seeding terrain!\" << std::endl;\n                CellularBoard *board = state->getBoard();\n                int width = board->getWidth(), height = board->getHeight();\n\n\n                std::vector<AnchorPoint*> anchors;\n                boost::multi_array<AnchorPoint*, 2> closestAnchors(boost::extents[height][width]);\n\n                std::vector<AnchorPoint*> desertAnchors;\n                boost::multi_array<AnchorPoint*, 2> closestDesertAnchors(boost::extents[height][width]);\n\n\n                // fill in with the default: PlainsCell\n                for (int v = 0; v < height; v++) {\n                    for (int u = 0; u < width; u++) {\n                        board->setCell(u, v, PlainsCell());\n                    }\n                }\n\n                // seed clusters of desert\n                int dcc = 1 + (random.get() > 0.5 ? 0 : 1);\n\n                auto widthGen = random.createUniformInteger(3, 7);\n                for (int i = 0; i < dcc; i++) {\n                    int cw = widthGen();\n                    int ch = widthGen();\n\n                    random.setUniform(0, width - cw - 1);\n                    int tu = random.getUniformInteger();\n\n                    random.setUniform(0, width - ch - 1);\n                    int tv = random.getUniformInteger();\n\n                    int cx = tu + cw / 2;\n                    int cy = tv + ch / 2;\n                    AnchorPoint *current = new AnchorPoint(sf::Vector2f(cx, cy));\n\n                    desertAnchors.push_back(current);\n\n                    for (int u = tu; u < tu + cw; u++) {\n                        for (int v = tv; v < tv + ch; v++) {\n                            if (random.get() < 0.8)\n                                board->setCell(u, v, DesertCell());\n                        }\n                    }\n                }\n\n                // seed clusters of forest\n                random.setUniform(2, 6);\n                int fcc = random.getUniformInteger();\n\n                for (int i = 0; i < fcc; i++) {\n                    int cw = widthGen();\n                    int ch = widthGen();\n                    random.setUniform(0, width - cw - 1);\n                    int tu = random.getUniformInteger();\n\n                    random.setUniform(0, width - ch - 1);\n                    int tv = random.getUniformInteger();\n\n                    int cx = tu + cw / 2;\n                    int cy = tv + ch / 2;\n                    AnchorPoint *current = new AnchorPoint(sf::Vector2f(cx, cy));\n\n                    anchors.push_back(current);\n\n                    for (int u = tu; u < tu + cw; u++) {\n                        for (int v = tv; v < tv + ch; v++) {\n                            if (random.get() < 0.8)\n                                board->setCell(u, v, ForestCell());\n                        }\n                    }\n                }\n\n                std::cout << \"Calculating Anchor points!\" << std::endl;\n                for (int v = 0; v < height; v++) {\n                    for (int u = 0; u < width; u++) {\n                        AnchorPoint *closest = nullptr;\n                        double minDist = 999999;\n                        for (auto anchor : anchors) {\n                            double dist = std::abs(anchor->location.x - u) + std::abs(anchor->location.y - v);\n                            if (dist < minDist) {\n                                closest = anchor;\n                                minDist = dist;\n                            }\n                        }\n\n                        closestAnchors[v][u] = closest;\n                    }\n                }\n\n\n                for (int v = 0; v < height; v++) {\n                    for (int u = 0; u < width; u++) {\n                        AnchorPoint *closest = nullptr;\n                        double minDist = 999999;\n                        for (auto anchor : desertAnchors) {\n                            double dist = std::abs(anchor->location.x - u) + std::abs(anchor->location.y - v);\n                            if (dist < minDist) {\n                                closest = anchor;\n                                minDist = dist;\n                            }\n                        }\n                        closestDesertAnchors[v][u] = closest;\n                    }\n                }\n\n\n                std::cout << \"Propagating terrain...\" << std::endl;\n                // propagate the desert and forest terrains\n                int iterations = (int) ceil((sqrt(width * height) / 40) * 6) * 3;\n                int ruleSet = 0;\n                for (int iteration = 0; iteration < iterations; iteration++) {\n                    std::cout << \"\\tIteration \" << iteration << \" / \" << iterations - 1 << std::endl;\n                    boost::multi_array<std::pair<int, int>, 2> neighbors(boost::extents[height][width]);\n\n                    for (int v = 0; v < height; v++) {\n                        for (int u = 0; u < width; u++) {\n                            int right = (u + 1);\n                            int up = (v + 1);\n                            int down = v - 1;\n                            int left = u - 1;\n                            int d_incident = 0, f_incident = 0;\n\n                            auto in = [height, width](int a, bool isUp) {\n                                if (isUp) {\n                                    return a >= 0 && a < height;\n                                } else {\n                                    return a >= 0 && a < width;\n                                }\n                            };\n\n                            if (in(right, 0) && board->getCell(right, v).getType() == BoardCell::TYPE::Desert) {\n                                d_incident += 1;\n                            }\n                            else if (in(right, 0) && board->getCell(right, v).getType() == BoardCell::TYPE::Forest) {\n                                f_incident += 1;\n                            }\n\n                            if (in(left, 0) && board->getCell(left, v).getType() == BoardCell::TYPE::Desert) {\n                                d_incident += 1;\n                            }\n                            else if (in(left, 0) && board->getCell(left, v).getType() == BoardCell::TYPE::Forest) {\n                                f_incident += 1;\n                            }\n\n                            if (in(up, 1) && board->getCell(u, up).getType() == BoardCell::TYPE::Desert) {\n                                d_incident += 1;\n                            }\n                            else if (in(up, 1) && board->getCell(u, up).getType() == BoardCell::TYPE::Forest) {\n                                f_incident += 1;\n                            }\n\n                            if (in(down, 1) && board->getCell(u, down).getType() == BoardCell::TYPE::Desert) {\n                                d_incident += 1;\n                            }\n                            else if (in(down, 1) && board->getCell(u, down).getType() == BoardCell::TYPE::Forest) {\n                                f_incident += 1;\n                            }\n\n                            neighbors[v][u] = std::make_pair(d_incident, f_incident);\n                        }\n                    }\n\n\n                    if ((iteration % 8) == 0) ruleSet = !ruleSet;\n\n                    if (ruleSet == 0) {\n                        for (int v = 0; v < height; v++) {\n                            for (int u = 0; u < width; u++) {\n                                BoardCell cell = board->getCell(u, v);\n                                std::pair<int, int> pair = (std::pair<int, int>) neighbors[v][u];\n                                int d_count = pair.first;\n                                int f_count = pair.second;\n\n                                if (cell.getType() == BoardCell::TYPE::Desert) {\n                                    if (d_count == 1) {\n                                        if (random.get() < 0)\n                                            board->setCell(u, v, PlainsCell());\n\n                                    }\n                                    else if (d_count == 0) {\n                                        board->setCell(u, v, PlainsCell());\n                                    }\n                                }\n                                else if (cell.getType() == BoardCell::TYPE::Plains) {\n                                    AnchorPoint *p = closestAnchors[v][u];\n                                    AnchorPoint *dp = closestDesertAnchors[v][u];\n                                    if (d_count > 1 && dp->getComponent(sf::Vector2f(u, v)) > random.get() + 0.1)\n                                        board->setCell(u, v, DesertCell());\n                                    else if (d_count > 0 && dp->getComponent(sf::Vector2f(u, v)) > random.get() + 0.1 && random.get() > 0.5) {\n                                        board->setCell(u, v, DesertCell());\n                                    }\n                                    else if (f_count > 1 && p->getComponent(sf::Vector2f(u, v)) > random.get() + 0.1) {\n                                        board->setCell(u, v, ForestCell());\n                                    }\n                                    else if (f_count > 0 && p->getComponent(sf::Vector2f(u, v)) > random.get() + 0.1 && random.get() > 0.5) {\n                                        board->setCell(u, v, ForestCell());\n                                    }\n\n                                }\n                                else if (cell.getType() == BoardCell::TYPE::Forest) {\n                                    if (d_count > 0)\n                                        board->setCell(u, v, PlainsCell());\n                                    else if (f_count == 1 && random.get() > 0.9)\n                                        board->setCell(u, v, PlainsCell());\n                                    else if (f_count == 0 && random.get() > 0.5)\n                                        board->setCell(u, v, PlainsCell());\n                                }\n                            }\n                        }\n                    } else {\n                        for (int v = 0; v < height; v++) {\n                            for (int u = 0; u < width; u++) {\n                                BoardCell cell = board->getCell(u, v);\n                                std::pair<int, int> pair = (std::pair<int, int>) neighbors[v][u];\n                                int d_count = pair.first;\n                                int f_count = pair.second;\n\n                                if (cell.getType() == BoardCell::TYPE::Desert) {\n                                    if (d_count == 1) {\n                                        if (random.get() < 0.5)\n                                            board->setCell(u, v, PlainsCell());\n                                    }\n                                    else if (d_count == 0) {\n                                        board->setCell(u, v, PlainsCell());\n                                    }\n                                }\n                                else if (cell.getType() == BoardCell::TYPE::Plains) {\n                                    AnchorPoint *p = closestAnchors[v][u];\n                                    AnchorPoint *dp = closestDesertAnchors[v][u];\n                                    if (d_count > 1 && dp->getComponent(sf::Vector2f(u, v)) > random.get() + 0.1)\n                                        board->setCell(u, v, DesertCell());\n                                    else if (d_count > 0 && dp->getComponent(sf::Vector2f(u, v)) > random.get() + 0.1 && random.get() > 0.5) {\n                                        board->setCell(u, v, DesertCell());\n                                    }\n                                    else if (f_count > 1 && p->getComponent(sf::Vector2f(u, v)) > random.get() + 0.1) {\n                                        board->setCell(u, v, ForestCell());\n                                    }\n                                    else if (f_count > 0 && p->getComponent(sf::Vector2f(u, v)) > random.get() + 0.1 && random.get() > 0.5) {\n                                        board->setCell(u, v, ForestCell());\n                                    }\n\n                                }\n                                else if (cell.getType() == BoardCell::TYPE::Forest) {\n                                    if (d_count > 0)\n                                        board->setCell(u, v, PlainsCell());\n                                    else if (f_count == 1 && random.get() > 0.7)\n                                        board->setCell(u, v, PlainsCell());\n                                    else if (f_count == 0 && random.get() > 0.4)\n                                        board->setCell(u, v, PlainsCell());\n                                }\n                            }\n                        }\n                    }\n                }\n\n                board->generateAdjacencyGraph();\n\n                // clean up\n                for (auto anchor : desertAnchors) {\n                    delete anchor;\n                }\n\n                for (auto anchor : anchors) {\n                    delete anchor;\n                }\n            }\n\n            void ClusterSeederV2::seedInfrastructure(GameState *state) {\n\n            }\n\n            void ClusterSeederV2::seedUnits(GameState *state) {\n                int width = state->getBoard()->getWidth(),\n                        height = state->getBoard()->getHeight();\n\n                auto widthGen = random.createUniformInteger(4, 8);\n                int cw = widthGen();\n                int ch = widthGen();\n\n                int tu = random.createUniformInteger(0, width - cw - 1)();\n                int tv = random.createUniformInteger(0, height - ch - 1)();\n\n                std::vector<int> locations((unsigned) cw * ch);\n                std::iota(locations.begin(), locations.end(), 0);\n\n                // random_shuffle should not be used, as it utilized rand()\n                std::random_shuffle(locations.begin(), locations.end());\n\n                for (int i = 0; i < 10; i++) {\n                    Civilian *civvie = new Civilian();\n                    int u = tu + locations[i] % cw,\n                            v = tv + locations[i] / cw;\n                    civvie->setLocation(sf::Vector2i(u, v));\n                    state->units.push_back(civvie);\n                }\n\n                std::sort(state->units.begin(), state->units.end(), [](Unit* a, Unit* b) {\n                    return a->getLocation().y < b->getLocation().y;\n                });\n            }\n\n            double ClusterSeederV2::AnchorPoint::getComponent(sf::Vector2f loc) {\n                sf::Vector2f displacement = loc - this->location;\n                double theta = std::atan2(displacement.y, displacement.x);\n                double num = func(theta) / 3.5;\n                return std::min<double>(num, 1);\n            }\n\n            double ClusterSeederV2::AnchorPoint::dSigmoid(double x) {\n                return std::exp(x) / ((1 + std::exp(x)) * (1 + std::exp(x)));\n            }\n\n            double ClusterSeederV2::AnchorPoint::func(double theta) {\n                double value1 = 1, value2 = 1;\n                double PI = boost::math::constants::pi<double>();\n\n                for (auto pair : sizesAndPhases) {\n                    double size = pair.first;\n                    double phase = pair.second;\n\n                    // warning: some kind of wrapping will be needed for this!\n                    // this might explain some of the harsh edges seen; however this is a minor problem\n                    value1 += size * dSigmoid(10 * (theta - phase));\n                    value2 += size * dSigmoid(10 * (theta - 2 * PI - phase));\n                }\n\n                // two values in case a sigmoid function borders PI or -PI\n                return std::abs(value1) > std::abs(value2) ? value1 : value2;\n            }\n\n            ClusterSeederV2::AnchorPoint::AnchorPoint(sf::Vector2f location) : location(location) {\n                double PI = boost::math::constants::pi<double>();\n\n                auto sizeGen = random.createUniformDouble(-0.5, 12);\n                auto phaseGen = random.createUniformDouble(-PI, PI);\n\n                for (int i = 0; i < 10; i++) {\n                    sizesAndPhases.push_back(std::make_pair(sizeGen(), phaseGen()));\n                }\n            }\n\n        }\n    }\n}", "meta": {"hexsha": "70df5d09bf5afff7eccbcb13a15ed4b4911e4ba6", "size": 17125, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/game/generation/ClusterSeederV2.cpp", "max_stars_repo_name": "ciscprocess/pe-econ-sim", "max_stars_repo_head_hexsha": "0d33507a451aace0d8157b45c29bfc582e6b3c18", "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/game/generation/ClusterSeederV2.cpp", "max_issues_repo_name": "ciscprocess/pe-econ-sim", "max_issues_repo_head_hexsha": "0d33507a451aace0d8157b45c29bfc582e6b3c18", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2015-07-14T02:30:37.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-26T22:11:28.000Z", "max_forks_repo_path": "src/game/generation/ClusterSeederV2.cpp", "max_forks_repo_name": "ciscprocess/pe-econ-sim", "max_forks_repo_head_hexsha": "0d33507a451aace0d8157b45c29bfc582e6b3c18", "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": 45.545212766, "max_line_length": 142, "alphanum_fraction": 0.3751240876, "num_tokens": 3474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2995037328812037}}
{"text": "/*\n* TS Elements\n* Copyright 2015-2018 M. Newhouse\n* Released under the MIT license.\n*/\n\n#include \"handling_v2.hpp\"\n#include \"car.hpp\"\n#include \"world.hpp\"\n\n#include \"resources/terrain_definition.hpp\"\n\n#include \"utility/transform.hpp\"\n#include \"utility/interpolate.hpp\"\n#include \"utility/math_utilities.hpp\"\n\n#include <boost/container/small_vector.hpp>\n\n#include <array>\n#include <algorithm>\n\n\nnamespace ts\n{\n  namespace world\n  {\n    HandlingState update_car_state(Car& car, const World& world, double frame_duration)\n    {\n      auto& handling = car.handling();\n\n      using controls::Control;\n      auto half_wheelbase = handling.wheelbase_length * 0.5;\n\n      std::array<Vector2d, 2> front_wheel_positions =\n      { {\n        { 0.0, -half_wheelbase + handling.wheelbase_offset }\n        } };\n\n      std::array<Vector2d, 2> rear_wheel_positions =\n      { {\n        { 0.0, half_wheelbase + handling.wheelbase_offset }\n        } };\n\n      if (handling.num_front_wheels >= 2)\n      {\n        front_wheel_positions =\n        { {\n          { -handling.front_axle_width * 0.5, -half_wheelbase + handling.wheelbase_offset },\n          { handling.front_axle_width * 0.5, -half_wheelbase + handling.wheelbase_offset },\n          } };\n      }\n\n      if (handling.num_rear_wheels >= 2)\n      {\n        rear_wheel_positions =\n        { {\n          { -handling.rear_axle_width * 0.5, half_wheelbase + handling.wheelbase_offset },\n          { handling.rear_axle_width * 0.5, half_wheelbase + handling.wheelbase_offset }\n        } };\n      }\n\n      auto transform = make_transformation(car.rotation());\n      auto inv_transform = make_transformation(-car.rotation());\n\n      auto handling_state = car.handling_state();\n      handling_state.wheel_states.clear();\n\n      auto local_velocity = transform_point(car.velocity(), inv_transform);\n      auto local_heading = normalize(local_velocity);\n      auto speed = magnitude(local_velocity);\n      auto angular_velocity = car.angular_velocity();\n      auto mass = car.mass();\n      auto center_of_mass = car.center_of_mass();\n\n      auto inv_moment = 1.0 / car.moment_of_inertia();\n\n      auto num_wheels = handling.num_front_wheels + handling.num_rear_wheels;\n      auto inv_num_wheels = 1.0 / num_wheels;\n      auto wheel_traction_limit = handling.traction_limit * inv_num_wheels;\n\n      auto total_downforce = local_heading.y * local_heading.y * speed * speed * handling.downforce_coefficient;\n      if (local_heading.y > 0.0) total_downforce = 0.0;\n\n      auto weight_distribution = clamp(center_of_mass.y / (handling.wheelbase_length * 0.5) + 0.5, 0.25, 0.75);\n\n      auto rear_downforce = total_downforce * (0.5 + handling.downforce_balance);\n      auto front_downforce = total_downforce * (0.5 - handling.downforce_balance);\n\n      auto inv_num_front_wheels = 1.0 / handling.num_front_wheels;\n      auto inv_num_rear_wheels = 1.0 / handling.num_rear_wheels;\n\n      auto front_base_load = wheel_traction_limit * 2.0 * (1.0 - weight_distribution);\n      auto rear_base_load = wheel_traction_limit * 2.0 * weight_distribution;\n\n      auto front_load_transfer = handling_state.net_force.y * handling.load_transfer * 0.5;\n      auto rear_load_transfer = -handling_state.net_force.y * handling.load_transfer * 0.5;\n\n      auto front_traction_limit = std::max(front_base_load + (front_load_transfer + front_downforce) * inv_num_front_wheels, 0.0);\n      auto rear_traction_limit = std::max(rear_base_load + (rear_load_transfer + rear_downforce) * inv_num_rear_wheels, 0.0);\n\n      auto throttle_rate = car.control_state(Control::Throttle) / 255.0;\n      auto braking_rate = car.control_state(Control::Brake) / 255.0;\n      auto turning_left_rate = car.control_state(Control::Left) / 255.0;\n      auto turning_right_rate = car.control_state(Control::Right) / 255.0;\n      auto turning_rate = -turning_left_rate + turning_right_rate;\n      auto net_throttle = throttle_rate - braking_rate;\n\n      auto inv_frame_duration = 1.0 / frame_duration;\n\n      auto front_steering = 0.5 - handling.steering_balance;\n      auto rear_steering = 0.5 + handling.steering_balance;\n      auto steering_multiplier = 1.0 / std::max(front_steering, rear_steering);\n      front_steering *= steering_multiplier;\n      rear_steering *= steering_multiplier;\n\n      auto front_braking = 0.5 - handling.brake_balance;\n      auto rear_braking = 0.5 + handling.brake_balance;\n      auto braking_multiplier = 1.0 / std::max(front_steering, rear_steering);\n      front_braking *= braking_multiplier;\n      rear_braking *= braking_multiplier;\n\n      auto front_acceleration = 0.0;\n      auto rear_acceleration = 0.0;\n      if (handling.front_driven && handling.rear_driven)\n      {\n        front_acceleration = 0.5 * inv_num_front_wheels;\n        rear_acceleration = 0.5 * inv_num_rear_wheels;\n      }\n\n      else if (handling.front_driven)\n      {\n        front_acceleration = inv_num_front_wheels;\n      }\n\n      else if (handling.rear_driven)\n      {\n        rear_acceleration = inv_num_rear_wheels;\n      }\n\n      auto num_gears = static_cast<int>(handling.gear_ratios.size());\n      if (handling_state.current_gear >= 0 && (speed <= 0.0001 || local_heading.y > 0.7) && net_throttle < 0.0)\n      {\n        handling_state.current_gear = -1;\n      }\n\n      if (handling_state.current_gear <= 0 && (speed <= 0.0001 || local_heading.y < -0.7) && net_throttle > 0.0)\n      {\n        auto gear = 0;        \n\n        while (gear < num_gears && speed * handling.gear_ratios[gear] >= handling.max_engine_revs * 0.8)\n        {\n          ++gear;\n        }\n\n        handling_state.current_gear = gear + 1;        \n      }\n\n      if (handling_state.gear_shift_state != 0)\n      {\n        auto new_gear = handling_state.current_gear;\n        if (handling_state.gear_shift_state > 0) ++new_gear;\n        else --new_gear;\n\n        auto old_ratio = handling.gear_ratios[handling_state.current_gear - 1];\n        auto new_ratio = handling.gear_ratios[new_gear - 1];\n\n        auto frame_progress = 1.0 / handling.gear_shift_duration;\n        auto progress = 1.0 - (std::abs(handling_state.gear_shift_state) * frame_progress);\n\n        auto current_ratio = interpolate_linearly(old_ratio, new_ratio, progress);\n        auto updated_ratio = interpolate_linearly(old_ratio, new_ratio, progress + frame_progress);\n\n        handling_state.engine_rev_speed /= current_ratio;\n        handling_state.engine_rev_speed *= updated_ratio;\n\n        if (handling_state.gear_shift_state > 0) --handling_state.gear_shift_state;\n        else ++handling_state.gear_shift_state;\n\n        if (handling_state.gear_shift_state == 0)\n        {\n          handling_state.current_gear = new_gear;\n        }\n      }\n\n      else if (handling_state.engine_rev_speed >= 0.99)\n      {\n        if (handling_state.current_gear >= 1 && handling_state.current_gear < num_gears)\n        {\n          handling_state.gear_shift_state = handling.gear_shift_duration;\n        }\n      }\n\n      else if (handling_state.engine_rev_speed < 0.8 && handling_state.current_gear > 1)\n      {\n        auto prev_gear = handling_state.current_gear - 1;\n        auto new_revs = handling_state.engine_rev_speed;\n        new_revs /= handling.gear_ratios[handling_state.current_gear - 1];\n        new_revs *= handling.gear_ratios[prev_gear - 1];\n        if (new_revs < 0.8)\n        {\n          handling_state.gear_shift_state = -handling.gear_shift_duration;\n        }\n      }\n\n      auto gear_ratio = 1.0;\n      if (handling_state.current_gear < 0)\n      {\n        net_throttle = -net_throttle;\n        gear_ratio = -handling.reverse_gear_ratio;\n      }\n\n      else if (handling_state.current_gear == 0)\n      {\n        gear_ratio = 0.0;\n      }\n\n      else if (handling_state.current_gear - 1 < num_gears)\n      {\n        gear_ratio = handling.gear_ratios[handling_state.current_gear - 1];\n      }\n\n      if (handling_state.gear_shift_state == 0)\n      {\n        handling_state.engine_rev_speed = std::min(speed * std::abs(gear_ratio) / handling.max_engine_revs, 1.05);\n      }\n\n      else\n      {\n        gear_ratio = 0.0;\n      }      \n\n      auto throttle_factor = 1.0;\n      if (handling_state.engine_rev_speed > 1.0)\n      {\n        throttle_factor = 0.0;\n      }\n\n      auto acceleration_force_1d = std::max(net_throttle, 0.0) * handling.max_acceleration_force * gear_ratio * throttle_factor;\n      auto braking_force_1d = std::max(-net_throttle, 0.0) * handling.max_braking_force;\n\n      struct WheelState\n      {\n        Vector2d pos;\n        Vector2d velocity;\n        Vector2d bias;\n        Vector2d wheel_facing;\n        double heading_angle;\n        double traction_limit;\n        double vertical_load;\n        double acceleration;\n        double braking;\n        double cornering;\n        double max_steering_angle;\n        double acceleration_force;\n        double braking_force;\n        double cornering_force;\n        double slide_ratio;\n\n        resources::TerrainDefinition terrain;\n      };\n\n      auto throttle_bias = 1.0;\n      auto brake_bias = 1.0;\n      auto cornering_bias = 1.0;\n      auto antislide_bias = 1.0;\n      auto longitudinal_bias = net_throttle >= 0.0 ? throttle_bias : brake_bias;\n\n      auto cornering_bias_2d = normalize(make_vector2(cornering_bias, longitudinal_bias));\n      auto antislide_bias_2d = normalize(make_vector2(cornering_bias, longitudinal_bias));\n\n      boost::container::small_vector<WheelState, 4> wheel_states;\n      for (auto p : front_wheel_positions)\n      {\n        WheelState ws{};\n        ws.pos = p;\n        ws.traction_limit = front_traction_limit;\n        ws.acceleration = front_acceleration;\n        ws.braking = front_braking;\n        ws.cornering = handling.cornering;\n        ws.max_steering_angle = front_steering * degrees(handling.max_steering_angle).radians();\n        ws.bias = cornering_bias_2d;        \n        wheel_states.push_back(ws);\n      }\n\n      for (auto p : rear_wheel_positions)\n      {\n        WheelState ws{};\n        ws.pos = p;\n        ws.traction_limit = rear_traction_limit;\n        ws.acceleration = rear_acceleration;\n        ws.braking = rear_braking;\n        ws.cornering = handling.cornering;\n        ws.max_steering_angle = -rear_steering * degrees(handling.max_steering_angle).radians();\n        ws.bias = antislide_bias_2d;\n        wheel_states.push_back(ws);\n      }\n\n      auto max_cornering_multiplier = speed * mass * inv_num_wheels * inv_frame_duration;\n      auto is_turning = std::abs(turning_rate) >= 0.0001;\n\n      auto adjusted_steering_rate = 0.0;\n\n      for (auto& ws : wheel_states)\n      {        \n        auto global_pos = car.position() + transform_point(ws.pos, transform);\n\n        ws.vertical_load = ws.traction_limit;\n        ws.terrain = world.terrain_at(global_pos, car.z_level());\n        ws.velocity = local_velocity + angular_velocity * make_vector2(-ws.pos.y, ws.pos.x);\n        ws.heading_angle = std::atan2(ws.velocity.x, -ws.velocity.y);\n\n        if (is_turning && std::abs(ws.max_steering_angle) >= 0.00001)\n        {\n          auto max_angle = turning_rate < 0.0 ? -ws.max_steering_angle : ws.max_steering_angle;\n          auto desired_angle = degrees(handling.non_slide_angle);\n          if (max_angle < 0.0) desired_angle = -desired_angle;\n\n          auto steering_angle = radians(ws.heading_angle) + desired_angle;\n          if (std::abs(steering_angle.degrees()) >= 90.0)\n          {\n            steering_angle -= degrees(180.0);\n            steering_angle.normalize();\n          }\n\n          auto steering_rate = std::min(steering_angle.radians() / max_angle, 1.0);\n          if (steering_rate > adjusted_steering_rate)\n          {\n            adjusted_steering_rate = steering_rate;\n          }\n        }\n      }\n\n      turning_rate *= adjusted_steering_rate;\n\n      auto pedal_adjustment = 1.0;      \n      for (auto& ws : wheel_states)\n      {\n        ws.wheel_facing = make_vector2(0.0, -1.0);\n        auto steering_angle = radians(turning_rate * ws.max_steering_angle);\n        if (std::abs(steering_angle.radians()) >= 0.00001)\n        {\n          ws.wheel_facing = transform_point(ws.wheel_facing, steering_angle);\n        }\n\n        auto slip_angle = radians(ws.heading_angle) - steering_angle;\n        if (std::abs(slip_angle.degrees()) >= 90.0)\n        {\n          slip_angle -= degrees(180.0);\n          slip_angle.normalize();\n        }\n\n        auto slip_degrees = std::abs(slip_angle.degrees());\n\n        ws.slide_ratio = 1.0;\n        auto cornering_ratio = 1.0;\n        if (slip_degrees < handling.full_slide_angle)\n        {\n          if (slip_degrees < handling.non_slide_angle)\n          {            \n            //cornering_ratio = slip_degrees / handling.non_slide_angle;\n            ws.slide_ratio = 0.0;\n          }\n\n          else\n          {\n            ws.slide_ratio = (slip_degrees - handling.non_slide_angle) /\n              (handling.full_slide_angle - handling.non_slide_angle);\n            ws.slide_ratio *= ws.slide_ratio;\n          }\n        }\n\n        ws.traction_limit *= interpolate_linearly(ws.terrain.traction, \n                                                  handling.sliding_grip * ws.terrain.sliding_traction, \n                                                  ws.slide_ratio);\n\n        auto facing = ws.wheel_facing;\n        if (ws.velocity.y > 0.0) facing = -facing;\n\n        auto max_cornering = std::abs(slip_angle.radians()) * max_cornering_multiplier;\n        ws.cornering_force = std::min(cornering_ratio * ws.cornering * ws.traction_limit, max_cornering);\n\n        auto braking_factor = facing.y * facing.y;\n        ws.acceleration_force = ws.acceleration * acceleration_force_1d;\n        ws.braking_force = ws.braking * braking_force_1d * braking_factor;\n\n        auto longitudinal_force = (std::abs(ws.acceleration_force) + ws.braking_force) * pedal_adjustment;\n        auto applied_force = make_vector2(ws.cornering_force, longitudinal_force);\n\n        if (magnitude_squared(applied_force) > ws.traction_limit * ws.traction_limit)\n        {\n          auto reduce_x = applied_force.x > ws.bias.x * ws.traction_limit;\n          auto reduce_y = applied_force.y > ws.bias.y * ws.traction_limit;\n\n          if (reduce_y)\n          {\n            if (reduce_x)\n            {\n              pedal_adjustment = (ws.traction_limit * ws.bias.y) /\n                (std::abs(ws.acceleration_force) + ws.braking_force);\n            }\n\n            else\n            {\n              auto rem = ws.traction_limit * ws.traction_limit - ws.cornering_force * ws.cornering_force;\n              pedal_adjustment = std::sqrt(rem) / (std::abs(ws.acceleration_force) + ws.braking_force);\n            }\n          }\n        }\n      }\n\n      handling_state.wheel_states.clear();\n      auto net_force = make_vector2(0.0, 0.0);\n      for (auto& ws : wheel_states)\n      {\n        {\n          auto longitudinal_force = (std::abs(ws.acceleration_force) + ws.braking_force) * pedal_adjustment;\n          auto rem = std::max(ws.traction_limit * ws.traction_limit - longitudinal_force * longitudinal_force, 0.0);\n\n          if (rem < ws.cornering_force * ws.cornering_force)\n          {\n            ws.cornering_force = std::sqrt(rem);\n          }\n        }\n\n        auto force = make_vector2(0.0, 0.0);\n\n        auto wheel_heading = normalize(ws.velocity);\n        auto target_heading = ws.wheel_facing;\n        if (ws.velocity.y > 0.0) target_heading = -target_heading;\n        auto slide_direction = normalize(target_heading - wheel_heading);\n\n        auto terrain_cornering_multiplier = ws.terrain.cornering;\n        if (&ws - wheel_states.data() >= handling.num_front_wheels)\n        {\n          terrain_cornering_multiplier = ws.terrain.antislide;\n        }                \n\n        force += ws.acceleration_force * pedal_adjustment * ws.wheel_facing * ws.terrain.acceleration;\n        force += ws.braking_force * pedal_adjustment * -target_heading * ws.terrain.braking;\n        force += ws.cornering_force * slide_direction * terrain_cornering_multiplier;\n\n        auto rolling_resistance = (1.0 - ws.slide_ratio) * handling.rolling_drag_coefficient * \n          ws.vertical_load * ws.terrain.rolling_resistance;\n\n        force += rolling_resistance * -wheel_heading;\n\n        force += ws.terrain.roughness * mass * -ws.velocity * inv_num_wheels;\n        \n        car.apply_force(force, ws.pos);       \n\n        net_force += force;\n\n        HandlingState::WheelState stored_info;\n        stored_info.pos = car.position() + transform_point(ws.pos, transform);\n        stored_info.slide_ratio = ws.slide_ratio;\n        stored_info.terrain_color = ws.terrain.color;\n        stored_info.terrain_roughness = ws.terrain.roughness;\n        stored_info.speed = dot_product(wheel_heading, ws.velocity);        \n        handling_state.wheel_states.push_back(stored_info);\n      }\n\n      auto drag = speed * -local_velocity * handling.drag_coefficient;\n      car.apply_force(drag, center_of_mass);\n      net_force += drag;\n      \n      auto torque_effect = car.applied_torque() * inv_moment * mass;\n      auto min_lateral_force = net_force.x + -wheel_states.front().pos.y * torque_effect;\n      auto max_lateral_force = min_lateral_force;\n      for (std::uint32_t idx = 1; idx < wheel_states.size(); ++idx)\n      {\n        auto lateral_force = net_force.x + -wheel_states[idx].pos.y * torque_effect;\n        if (lateral_force < min_lateral_force)\n        {\n          min_lateral_force = lateral_force;\n        }\n\n        if (lateral_force > max_lateral_force)\n        {\n          max_lateral_force = lateral_force;\n        }\n      }\n\n      if (std::signbit(min_lateral_force) == std::signbit(max_lateral_force))\n      {\n        auto m = (max_lateral_force - min_lateral_force) * 0.5;\n        auto f = clamp(min_lateral_force < 0.0 ? -max_lateral_force : -min_lateral_force, -m, m);\n        car.apply_force(make_vector2(f, 0.0), center_of_mass);\n        net_force.x += f;\n      }\n\n      angular_velocity -= angular_velocity * handling.angular_damping * frame_duration;\n      car.set_angular_velocity(angular_velocity);\n      handling_state.net_force = net_force;     \n      return handling_state;      \n    }\n  }\n}\n", "meta": {"hexsha": "dd783a2090469a170b76b4dc60d58d2901ddd723", "size": 18103, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/world/handling_v2.cpp", "max_stars_repo_name": "mnewhouse/tselements", "max_stars_repo_head_hexsha": "bd1c6724018e862156948a680bb1bc70dd28bef6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/world/handling_v2.cpp", "max_issues_repo_name": "mnewhouse/tselements", "max_issues_repo_head_hexsha": "bd1c6724018e862156948a680bb1bc70dd28bef6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/world/handling_v2.cpp", "max_forks_repo_name": "mnewhouse/tselements", "max_forks_repo_head_hexsha": "bd1c6724018e862156948a680bb1bc70dd28bef6", "max_forks_repo_licenses": ["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.3514056225, "max_line_length": 130, "alphanum_fraction": 0.640225377, "num_tokens": 4390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2994937877325997}}
{"text": "// GMTL is (C) Copyright 2001-2010 by Allen Bierbaum\n// Distributed under the GNU Lesser General Public License 2.1 with an\n// addendum covering inlined code. (See accompanying files LICENSE and\n// LICENSE.addendum or http://www.gnu.org/copyleft/lesser.txt)\n\n// Includes ====================================================================\n#include <boost/python.hpp>\n#include <gmtl-VecOps.h>\n\n// Using =======================================================================\nusing namespace boost::python;\n\n// Declarations ================================================================\n\n\nnamespace  {\n\n\nBOOST_PYTHON_FUNCTION_OVERLOADS(isNormalized_overloads_1_2, gmtl::isNormalized, 1, 2)\n\n\n}// namespace \n\n\n// Module ======================================================================\nvoid _Export_gmtl_VecOps_h()\n{\n    def(\"cross\", (gmtl::Vec<double,3> & (*)(gmtl::Vec<double,3> &, const gmtl::Vec<double,3> &, const gmtl::Vec<double,3> &))&gmtl::cross, return_internal_reference< 1 >());\n    def(\"cross\", (gmtl::Vec<float,3> & (*)(gmtl::Vec<float,3> &, const gmtl::Vec<float,3> &, const gmtl::Vec<float,3> &))&gmtl::cross, return_internal_reference< 1 >());\n    def(\"cross\", (gmtl::Vec<int,3> & (*)(gmtl::Vec<int,3> &, const gmtl::Vec<int,3> &, const gmtl::Vec<int,3> &))&gmtl::cross, return_internal_reference< 1 >());\n    def(\"dot\", (double (*)(const gmtl::VecBase<double,4> &, const gmtl::VecBase<double,4> &))&gmtl::dot);\n    def(\"dot\", (double (*)(const gmtl::VecBase<double,3> &, const gmtl::VecBase<double,3> &))&gmtl::dot);\n    def(\"dot\", (double (*)(const gmtl::VecBase<double,2> &, const gmtl::VecBase<double,2> &))&gmtl::dot);\n    def(\"dot\", (float (*)(const gmtl::VecBase<float,4> &, const gmtl::VecBase<float,4> &))&gmtl::dot);\n    def(\"dot\", (float (*)(const gmtl::VecBase<float,3> &, const gmtl::VecBase<float,3> &))&gmtl::dot);\n    def(\"dot\", (float (*)(const gmtl::VecBase<float,2> &, const gmtl::VecBase<float,2> &))&gmtl::dot);\n    def(\"dot\", (int (*)(const gmtl::VecBase<int,4> &, const gmtl::VecBase<int,4> &))&gmtl::dot);\n    def(\"dot\", (int (*)(const gmtl::VecBase<int,3> &, const gmtl::VecBase<int,3> &))&gmtl::dot);\n    def(\"dot\", (int (*)(const gmtl::VecBase<int,2> &, const gmtl::VecBase<int,2> &))&gmtl::dot);\n    def(\"isNormalized\", (bool (*)(const gmtl::Vec<double,4> &, const double))&gmtl::isNormalized, isNormalized_overloads_1_2());\n    def(\"isNormalized\", (bool (*)(const gmtl::Vec<double,3> &, const double))&gmtl::isNormalized, isNormalized_overloads_1_2());\n    def(\"isNormalized\", (bool (*)(const gmtl::Vec<double,2> &, const double))&gmtl::isNormalized, isNormalized_overloads_1_2());\n    def(\"isNormalized\", (bool (*)(const gmtl::Vec<float,4> &, const float))&gmtl::isNormalized, isNormalized_overloads_1_2());\n    def(\"isNormalized\", (bool (*)(const gmtl::Vec<float,3> &, const float))&gmtl::isNormalized, isNormalized_overloads_1_2());\n    def(\"isNormalized\", (bool (*)(const gmtl::Vec<float,2> &, const float))&gmtl::isNormalized, isNormalized_overloads_1_2());\n    def(\"isNormalized\", (bool (*)(const gmtl::Vec<int,4> &, const int))&gmtl::isNormalized, isNormalized_overloads_1_2());\n    def(\"isNormalized\", (bool (*)(const gmtl::Vec<int,3> &, const int))&gmtl::isNormalized, isNormalized_overloads_1_2());\n    def(\"isNormalized\", (bool (*)(const gmtl::Vec<int,2> &, const int))&gmtl::isNormalized, isNormalized_overloads_1_2());\n    def(\"length\", (double (*)(const gmtl::Vec<double,4> &))&gmtl::length);\n    def(\"length\", (double (*)(const gmtl::Vec<double,3> &))&gmtl::length);\n    def(\"length\", (double (*)(const gmtl::Vec<double,2> &))&gmtl::length);\n    def(\"length\", (float (*)(const gmtl::Vec<float,4> &))&gmtl::length);\n    def(\"length\", (float (*)(const gmtl::Vec<float,3> &))&gmtl::length);\n    def(\"length\", (float (*)(const gmtl::Vec<float,2> &))&gmtl::length);\n    def(\"length\", (int (*)(const gmtl::Vec<int,4> &))&gmtl::length);\n    def(\"length\", (int (*)(const gmtl::Vec<int,3> &))&gmtl::length);\n    def(\"length\", (int (*)(const gmtl::Vec<int,2> &))&gmtl::length);\n    def(\"lengthSquared\", (double (*)(const gmtl::Vec<double,4> &))&gmtl::lengthSquared);\n    def(\"lengthSquared\", (double (*)(const gmtl::Vec<double,3> &))&gmtl::lengthSquared);\n    def(\"lengthSquared\", (double (*)(const gmtl::Vec<double,2> &))&gmtl::lengthSquared);\n    def(\"lengthSquared\", (float (*)(const gmtl::Vec<float,4> &))&gmtl::lengthSquared);\n    def(\"lengthSquared\", (float (*)(const gmtl::Vec<float,3> &))&gmtl::lengthSquared);\n    def(\"lengthSquared\", (float (*)(const gmtl::Vec<float,2> &))&gmtl::lengthSquared);\n    def(\"lengthSquared\", (int (*)(const gmtl::Vec<int,4> &))&gmtl::lengthSquared);\n    def(\"lengthSquared\", (int (*)(const gmtl::Vec<int,3> &))&gmtl::lengthSquared);\n    def(\"lengthSquared\", (int (*)(const gmtl::Vec<int,2> &))&gmtl::lengthSquared);\n    def(\"lerp\", (gmtl::VecBase<double,4> & (*)(gmtl::VecBase<double,4> &, const double &, const gmtl::VecBase<double,4> &, const gmtl::VecBase<double,4> &))&gmtl::lerp, return_internal_reference< 1 >());\n    def(\"lerp\", (gmtl::VecBase<double,3> & (*)(gmtl::VecBase<double,3> &, const double &, const gmtl::VecBase<double,3> &, const gmtl::VecBase<double,3> &))&gmtl::lerp, return_internal_reference< 1 >());\n    def(\"lerp\", (gmtl::VecBase<double,2> & (*)(gmtl::VecBase<double,2> &, const double &, const gmtl::VecBase<double,2> &, const gmtl::VecBase<double,2> &))&gmtl::lerp, return_internal_reference< 1 >());\n    def(\"lerp\", (gmtl::VecBase<float,4> & (*)(gmtl::VecBase<float,4> &, const float &, const gmtl::VecBase<float,4> &, const gmtl::VecBase<float,4> &))&gmtl::lerp, return_internal_reference< 1 >());\n    def(\"lerp\", (gmtl::VecBase<float,3> & (*)(gmtl::VecBase<float,3> &, const float &, const gmtl::VecBase<float,3> &, const gmtl::VecBase<float,3> &))&gmtl::lerp, return_internal_reference< 1 >());\n    def(\"lerp\", (gmtl::VecBase<float,2> & (*)(gmtl::VecBase<float,2> &, const float &, const gmtl::VecBase<float,2> &, const gmtl::VecBase<float,2> &))&gmtl::lerp, return_internal_reference< 1 >());\n    def(\"lerp\", (gmtl::VecBase<int,4> & (*)(gmtl::VecBase<int,4> &, const int &, const gmtl::VecBase<int,4> &, const gmtl::VecBase<int,4> &))&gmtl::lerp, return_internal_reference< 1 >());\n    def(\"lerp\", (gmtl::VecBase<int,3> & (*)(gmtl::VecBase<int,3> &, const int &, const gmtl::VecBase<int,3> &, const gmtl::VecBase<int,3> &))&gmtl::lerp, return_internal_reference< 1 >());\n    def(\"lerp\", (gmtl::VecBase<int,2> & (*)(gmtl::VecBase<int,2> &, const int &, const gmtl::VecBase<int,2> &, const gmtl::VecBase<int,2> &))&gmtl::lerp, return_internal_reference< 1 >());\n    def(\"normalize\", (double (*)(gmtl::Vec<double,4> &))&gmtl::normalize);\n    def(\"normalize\", (double (*)(gmtl::Vec<double,3> &))&gmtl::normalize);\n    def(\"normalize\", (double (*)(gmtl::Vec<double,2> &))&gmtl::normalize);\n    def(\"normalize\", (float (*)(gmtl::Vec<float,4> &))&gmtl::normalize);\n    def(\"normalize\", (float (*)(gmtl::Vec<float,3> &))&gmtl::normalize);\n    def(\"normalize\", (float (*)(gmtl::Vec<float,2> &))&gmtl::normalize);\n    def(\"normalize\", (int (*)(gmtl::Vec<int,4> &))&gmtl::normalize);\n    def(\"normalize\", (int (*)(gmtl::Vec<int,3> &))&gmtl::normalize);\n    def(\"normalize\", (int (*)(gmtl::Vec<int,2> &))&gmtl::normalize);\n    def(\"reflect\", (gmtl::VecBase<double,4> & (*)(gmtl::VecBase<double,4> &, const gmtl::VecBase<double,4> &, const gmtl::Vec<double,4> &))&gmtl::reflect, return_internal_reference< 1 >());\n    def(\"reflect\", (gmtl::VecBase<double,3> & (*)(gmtl::VecBase<double,3> &, const gmtl::VecBase<double,3> &, const gmtl::Vec<double,3> &))&gmtl::reflect, return_internal_reference< 1 >());\n    def(\"reflect\", (gmtl::VecBase<double,2> & (*)(gmtl::VecBase<double,2> &, const gmtl::VecBase<double,2> &, const gmtl::Vec<double,2> &))&gmtl::reflect, return_internal_reference< 1 >());\n    def(\"reflect\", (gmtl::VecBase<float,4> & (*)(gmtl::VecBase<float,4> &, const gmtl::VecBase<float,4> &, const gmtl::Vec<float,4> &))&gmtl::reflect, return_internal_reference< 1 >());\n    def(\"reflect\", (gmtl::VecBase<float,3> & (*)(gmtl::VecBase<float,3> &, const gmtl::VecBase<float,3> &, const gmtl::Vec<float,3> &))&gmtl::reflect, return_internal_reference< 1 >());\n    def(\"reflect\", (gmtl::VecBase<float,2> & (*)(gmtl::VecBase<float,2> &, const gmtl::VecBase<float,2> &, const gmtl::Vec<float,2> &))&gmtl::reflect, return_internal_reference< 1 >());\n    def(\"reflect\", (gmtl::VecBase<int,4> & (*)(gmtl::VecBase<int,4> &, const gmtl::VecBase<int,4> &, const gmtl::Vec<int,4> &))&gmtl::reflect, return_internal_reference< 1 >());\n    def(\"reflect\", (gmtl::VecBase<int,3> & (*)(gmtl::VecBase<int,3> &, const gmtl::VecBase<int,3> &, const gmtl::Vec<int,3> &))&gmtl::reflect, return_internal_reference< 1 >());\n    def(\"reflect\", (gmtl::VecBase<int,2> & (*)(gmtl::VecBase<int,2> &, const gmtl::VecBase<int,2> &, const gmtl::Vec<int,2> &))&gmtl::reflect, return_internal_reference< 1 >());\n    def(\"isEqual\", (bool (*)(const gmtl::VecBase<double,4> &, const gmtl::VecBase<double,4> &, const double))&gmtl::isEqual);\n    def(\"isEqual\", (bool (*)(const gmtl::VecBase<double,3> &, const gmtl::VecBase<double,3> &, const double))&gmtl::isEqual);\n    def(\"isEqual\", (bool (*)(const gmtl::VecBase<double,2> &, const gmtl::VecBase<double,2> &, const double))&gmtl::isEqual);\n    def(\"isEqual\", (bool (*)(const gmtl::VecBase<float,4> &, const gmtl::VecBase<float,4> &, const float))&gmtl::isEqual);\n    def(\"isEqual\", (bool (*)(const gmtl::VecBase<float,3> &, const gmtl::VecBase<float,3> &, const float))&gmtl::isEqual);\n    def(\"isEqual\", (bool (*)(const gmtl::VecBase<float,2> &, const gmtl::VecBase<float,2> &, const float))&gmtl::isEqual);\n    def(\"isEqual\", (bool (*)(const gmtl::VecBase<int,4> &, const gmtl::VecBase<int,4> &, const int))&gmtl::isEqual);\n    def(\"isEqual\", (bool (*)(const gmtl::VecBase<int,3> &, const gmtl::VecBase<int,3> &, const int))&gmtl::isEqual);\n    def(\"isEqual\", (bool (*)(const gmtl::VecBase<int,2> &, const gmtl::VecBase<int,2> &, const int))&gmtl::isEqual);\n}\n", "meta": {"hexsha": "e8e0859bec70e51d345befcd57da6a653396314e", "size": 10000, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gmtl-0.6.1/python/src/gmtl/_gmtl_VecOps_h.cpp", "max_stars_repo_name": "Glitch0011/QuadTree-Example", "max_stars_repo_head_hexsha": "3558c999f68475bc98b8fa33b0f6d14076c9ec48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gmtl-0.6.1/python/src/gmtl/_gmtl_VecOps_h.cpp", "max_issues_repo_name": "Glitch0011/QuadTree-Example", "max_issues_repo_head_hexsha": "3558c999f68475bc98b8fa33b0f6d14076c9ec48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gmtl-0.6.1/python/src/gmtl/_gmtl_VecOps_h.cpp", "max_forks_repo_name": "Glitch0011/QuadTree-Example", "max_forks_repo_head_hexsha": "3558c999f68475bc98b8fa33b0f6d14076c9ec48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 96.1538461538, "max_line_length": 203, "alphanum_fraction": 0.6243, "num_tokens": 3336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.29940597603736574}}
{"text": "#include \"interpolate.h\"\n#include \"geoutil.h\"\n#include \"lambert_conformal_grid.h\"\n#include \"latitude_longitude_grid.h\"\n#include \"numerical_functions.h\"\n#include \"point_list.h\"\n#include \"reduced_gaussian_grid.h\"\n#include \"stereographic_grid.h\"\n#include \"util.h\"\n\n#include \"plugin_factory.h\"\n#include <Eigen/Dense>\n\n#define HIMAN_AUXILIARY_INCLUDE\n\n#include \"querydata.h\"\n\n#undef HIMAN_AUXILIARY_INCLUDE\n\nusing namespace himan;\nusing namespace Eigen;\n\nnamespace himan\n{\nnamespace interpolate\n{\n// Function to return identifier for each supported datatype\n// In the interpolation weight cache we store weights separately\n// for each data type.\n\ntemplate <typename T>\nint DataTypeId();\n\ntemplate <>\nint DataTypeId<float>()\n{\n\treturn 1;\n}\n\ntemplate <>\nint DataTypeId<double>()\n{\n\treturn 2;\n}\n\ntemplate <>\nint DataTypeId<short>()\n{\n\treturn 3;\n}\ntemplate <>\nint DataTypeId<unsigned char>()\n{\n\treturn 4;\n}\n\nbool IsSupportedGridForRotation(HPGridType type)\n{\n\tswitch (type)\n\t{\n\t\tcase kRotatedLatitudeLongitude:\n\t\tcase kStereographic:\n\t\tcase kLambertConformalConic:\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\ntemplate <typename T>\nbool InterpolateArea(const grid* baseGrid, std::shared_ptr<info<T>> source)\n{\n\tif (!source)\n\t{\n\t\treturn false;\n\t}\n\n#ifdef HAVE_CUDA\n\tif (source->PackedData()->HasData())\n\t{\n\t\tutil::Unpack<T>({source});\n\t}\n#endif\n\n\tbase<T> target;\n\ttarget.grid = std::shared_ptr<himan::grid>(baseGrid->Clone());\n\n\tif (baseGrid->Class() == kRegularGrid)\n\t{\n\t\ttarget.data.Resize(dynamic_cast<const regular_grid*>(baseGrid)->Ni(),\n\t\t                   dynamic_cast<const regular_grid*>(baseGrid)->Nj());\n\t}\n\telse if (baseGrid->Class() == kIrregularGrid)\n\t{\n\t\ttarget.data.Resize(baseGrid->Size(), 1);\n\t}\n\n\tauto method = InterpolationMethod(source->Param().Name(), source->Param().InterpolationMethod());\n\n\tlogger logr(\"interpolation\");\n\tlogr.Trace(fmt::format(\"Grid interpolation with method '{}'\", HPInterpolationMethodToString.at(method)));\n\n\tif (interpolate::interpolator<T>().Interpolate(*source->Base(), target, method))\n\t{\n\t\tauto interpGrid = std::shared_ptr<grid>(baseGrid->Clone());\n\n\t\tinterpGrid->UVRelativeToGrid(source->Grid()->UVRelativeToGrid());\n\n\t\tsource->Base()->grid = interpGrid;\n\t\tsource->Base()->data = std::move(target.data);\n\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\ntemplate bool InterpolateArea<double>(const grid*, std::shared_ptr<info<double>>);\ntemplate bool InterpolateArea<float>(const grid*, std::shared_ptr<info<float>>);\ntemplate bool InterpolateArea<short>(const grid*, std::shared_ptr<info<short>>);\ntemplate bool InterpolateArea<unsigned char>(const grid*, std::shared_ptr<info<unsigned char>>);\n\ntemplate <typename T>\nbool ReorderPoints(const grid* baseGrid, std::shared_ptr<info<T>> info)\n{\n\tif (!info)\n\t{\n\t\treturn false;\n\t}\n\n\t// Worst case: cartesian product ie O(n^2)\n\n\tauto targetStations = dynamic_cast<const point_list*>(baseGrid)->Stations();\n\tauto sourceStations = std::dynamic_pointer_cast<point_list>(info->Grid())->Stations();\n\tconst auto& sourceData = info->Data();\n\tmatrix<T> newData(targetStations.size(), 1, 1, MissingValue<T>());\n\n\tif (targetStations.size() == 0 || sourceStations.size() == 0)\n\t{\n\t\treturn false;\n\t}\n\n\tstd::vector<station> newStations;\n\n\tfor (size_t i = 0; i < targetStations.size(); i++)\n\t{\n\t\tstation s1 = targetStations[i];\n\n\t\tbool found = false;\n\n\t\tfor (size_t j = 0; j < sourceStations.size() && !found; j++)\n\t\t{\n\t\t\tstation s2 = sourceStations[j];\n\n\t\t\tif (s1.Id() == s2.Id())\n\t\t\t{\n\t\t\t\tnewStations.push_back(s1);\n\t\t\t\tnewData.Set(i, sourceData.At(j));\n\n\t\t\t\tfound = true;\n\t\t\t}\n\t\t}\n\n\t\tif (!found)\n\t\t{\n\t\t\t// throw std::runtime_error(\"Failed, source data does not contain all the same points as target\");\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tstd::dynamic_pointer_cast<point_list>(info->Grid())->Stations(newStations);\n\n\tauto b = info->Base();\n\tb->data = std::move(newData);\n\n\treturn true;\n}\n\ntemplate bool ReorderPoints<double>(const grid*, std::shared_ptr<info<double>>);\ntemplate bool ReorderPoints<float>(const grid*, std::shared_ptr<info<float>>);\ntemplate bool ReorderPoints<short>(const grid*, std::shared_ptr<info<short>>);\ntemplate bool ReorderPoints<unsigned char>(const grid*, std::shared_ptr<info<unsigned char>>);\n\ntemplate <typename T>\nbool Interpolate(const grid* baseGrid, const std::vector<std::shared_ptr<info<T>>>& infos)\n{\n\tfor (const auto& info : infos)\n\t{\n\t\tbool needInterpolation = false;\n\t\tbool needPointReordering = false;\n\n\t\t/*\n\t\t * Possible scenarios:\n\t\t * 1. from regular to regular (basic area&grid interpolation)\n\t\t * 2. from regular to irregular (area to point)\n\t\t * 3. from irregular to irregular (limited functionality, basically just point reordering)\n\t\t * 4. from irregular to regular, not supported, except if source is gaussian\n\t\t */\n\n\t\t// 1.\n\n\t\tif (baseGrid->Class() == kRegularGrid && info->Grid()->Class() == kRegularGrid)\n\t\t{\n\t\t\tif (*baseGrid != *info->Grid())\n\t\t\t{\n\t\t\t\tneedInterpolation = true;\n\t\t\t}\n\n\t\t\t// == operator does not test scanning mode !\n\n\t\t\telse if (dynamic_cast<const regular_grid*>(baseGrid)->ScanningMode() !=\n\t\t\t         std::dynamic_pointer_cast<regular_grid>(info->Grid())->ScanningMode())\n\t\t\t{\n#ifdef HAVE_CUDA\n\t\t\t\tif (info->PackedData()->HasData())\n\t\t\t\t{\n\t\t\t\t\t// must unpack before swapping\n\t\t\t\t\tutil::Unpack<T>({info});\n\t\t\t\t}\n#endif\n\t\t\t\tutil::Flip<T>(info->Data());\n\t\t\t\tauto base = info->Base();\n\t\t\t\tconst bool uv = base->grid->UVRelativeToGrid();\n\t\t\t\tbase->grid = std::shared_ptr<himan::grid>(baseGrid->Clone());\n\t\t\t\tbase->grid->UVRelativeToGrid(uv);\n\t\t\t}\n\t\t}\n\n\t\t// 2.\n\n\t\telse if (baseGrid->Class() == kIrregularGrid && info->Grid()->Class() == kRegularGrid)\n\t\t{\n\t\t\tneedInterpolation = true;\n\t\t}\n\n\t\t// 3.\n\n\t\telse if (baseGrid->Class() == kIrregularGrid && info->Grid()->Class() == kIrregularGrid)\n\t\t{\n\t\t\tif (*baseGrid != *info->Grid())\n\t\t\t{\n\t\t\t\tneedPointReordering = true;\n\t\t\t}\n\t\t}\n\n\t\t// 4.\n\n\t\telse if (baseGrid->Class() == kRegularGrid && info->Grid()->Class() == kIrregularGrid)\n\t\t{\n\t\t\tif (info->Grid()->Type() == kReducedGaussian)\n\t\t\t{\n\t\t\t\tneedInterpolation = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tthrow std::runtime_error(\"Unable to extrapolate from points to grid\");\n\t\t\t}\n\t\t}\n\n\t\tif (needInterpolation && InterpolateArea<T>(baseGrid, info) == false)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\telse if (needPointReordering && ReorderPoints<T>(baseGrid, info) == false)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\telse if (needInterpolation == false && needPointReordering == false)\n\t\t{\n\t\t\tlogger logr(\"interpolate\");\n\t\t\tlogr.Trace(\"Areas are equal, no need to interpolate\");\n\t\t}\n\t}\n\n\treturn true;\n}\n\ntemplate bool Interpolate<double>(const grid*, const std::vector<std::shared_ptr<info<double>>>&);\ntemplate bool Interpolate<float>(const grid*, const std::vector<std::shared_ptr<info<float>>>&);\ntemplate bool Interpolate<short>(const grid*, const std::vector<std::shared_ptr<info<short>>>&);\ntemplate bool Interpolate<unsigned char>(const grid*, const std::vector<std::shared_ptr<info<unsigned char>>>&);\n\nbool IsVectorComponent(const std::string& paramName)\n{\n\tif (paramName == \"U-MS\" || paramName == \"V-MS\" || paramName == \"WGU-MS\" || paramName == \"WGV-MS\" ||\n\t    paramName == \"IVELU-MS\" || paramName == \"IVELV-MS\" || paramName == \"WVELU-MS\" || paramName == \"WVELV-MS\")\n\t{\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nbool IsNumericCodeTable(const std::string& paramName)\n{\n\tif (paramName.find(\"NWCSAF_CLDTYPE\") != std::string::npos ||\n\t    paramName.find(\"NWCSAF_CLDMASK\") != std::string::npos || paramName == \"NWCSAF_CTTH_QC-N\" ||\n\t    paramName == \"CLDTYPE-N\")\n\t{\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nHPInterpolationMethod InterpolationMethod(const std::string& paramName, HPInterpolationMethod interpolationMethod)\n{\n\t// Later we'll add this information to radon directly\n\tif (interpolationMethod == kBiLinear &&\n\t    (\n\t        // vector parameters\n\t        IsVectorComponent(paramName) || paramName == \"DD-D\" || paramName == \"FF-MS\" ||\n\t        // precipitation\n\t        paramName == \"RR-KGM2\" || paramName == \"SNR-KGM2\" || paramName == \"GRI-KGM2\" || paramName == \"RRR-KGM2\" ||\n\t        paramName == \"RRRC-KGM2\" || paramName == \"RRRL-KGM2\" || paramName == \"SNRC-KGM2\" ||\n\t        paramName == \"SNRL-KGM2\" || paramName == \"RRRS-KGM2\" || paramName == \"RR-1-MM\" || paramName == \"RR-3-MM\" ||\n\t        paramName == \"RR-6-MM\" || paramName == \"RRI-KGM2\" || paramName == \"SNRI-KGM2\" ||\n\t        paramName == \"SNACC-KGM2\" ||\n\t        // symbols\n\t        paramName == \"CLDSYM-N\" || paramName == \"PRECFORM-N\" || paramName == \"PRECFORM2-N\" ||\n\t        paramName == \"FOGSYM-N\" || paramName == \"ICING-N\" || paramName == \"POTPRECT-N\" ||\n\t        paramName == \"POTPRECF-N\" || paramName == \"FOGINT-N\" || paramName == \"PRECTYPE-N\" ||\n\t        // code tables\n\t        IsNumericCodeTable(paramName)))\n\t{\n#ifdef DEBUG\n\t\tstd::cout << \"Debug::interpolation Switching interpolation method from bilinear to nearest point\" << std::endl;\n#endif\n\t\treturn kNearestPoint;  // nearest point in himan and newbase\n\t}\n\n\treturn interpolationMethod;\n}\n\ntemplate <typename T>\nvoid RotateVectorComponentsCPU(const grid* from, const grid* to, himan::matrix<T>& U, himan::matrix<T>& V)\n{\n\t// First convert to earth relative\n\n\tlogger log(\"interpolate\");\n\n\tif (from->UVRelativeToGrid() && from->Type() != kLatitudeLongitude)\n\t{\n\t\tlog.Trace(\"Rotating from \" + HPGridTypeToString.at(from->Type()) + \" to earth relative\");\n\n\t\tswitch (from->Type())  // source type\n\t\t{\n\t\t\tcase kLatitudeLongitude:\n\t\t\t\tbreak;\n\t\t\tcase kRotatedLatitudeLongitude:\n\t\t\t{\n\t\t\t\tconst auto rll = dynamic_cast<const rotated_latitude_longitude_grid*>(from);\n\t\t\t\tpoint southPole = rll->SouthPole();\n\n\t\t\t\tif (southPole.Y() > 0)\n\t\t\t\t{\n\t\t\t\t\tsouthPole.Y(-southPole.Y());\n\t\t\t\t\tsouthPole.X(0);\n\t\t\t\t}\n\n\t\t\t\tfor (size_t i = 0; i < U.Size(); i++)\n\t\t\t\t{\n\t\t\t\t\tT u = U[i];\n\t\t\t\t\tT v = V[i];\n\n\t\t\t\t\tconst point rotPoint = rll->RotatedLatLon(i);\n\t\t\t\t\tconst point regPoint = rll->LatLon(i);\n\n\t\t\t\t\t// Algorithm by J.E. HAUGEN (HIRLAM JUNE -92), modified by K. EEROLA\n\t\t\t\t\t// Algorithm originally defined in hilake/TURNDD.F\n\n\t\t\t\t\tconst double southPoleY = constants::kDeg * (southPole.Y() + 90);\n\n\t\t\t\t\tdouble sinPoleY, cosPoleY;\n\t\t\t\t\tsincos(southPoleY, &sinPoleY, &cosPoleY);\n\n\t\t\t\t\tconst double cosRegY = cos(constants::kDeg * regPoint.Y());  // zcyreg\n\t\t\t\t\tconst double zxmxc = constants::kDeg * (regPoint.X() - southPole.X());\n\n\t\t\t\t\tdouble sinxmxc, cosxmxc;\n\t\t\t\t\tsincos(zxmxc, &sinxmxc, &cosxmxc);\n\n\t\t\t\t\tconst double rotXRad = constants::kDeg * rotPoint.X();\n\t\t\t\t\tconst double rotYRad = constants::kDeg * rotPoint.Y();\n\n\t\t\t\t\tdouble sinRotX, cosRotX;\n\t\t\t\t\tsincos(rotXRad, &sinRotX, &cosRotX);\n\n\t\t\t\t\tdouble sinRotY, cosRotY;\n\t\t\t\t\tsincos(rotYRad, &sinRotY, &cosRotY);\n\n\t\t\t\t\tconst double PA = cosxmxc * cosRotX + cosPoleY * sinxmxc * sinRotX;\n\t\t\t\t\tconst double PB = cosPoleY * sinxmxc * cosRotX * sinRotY + sinPoleY * sinxmxc * cosRotY -\n\t\t\t\t\t                  cosxmxc * sinRotX * sinRotY;\n\t\t\t\t\tconst double PC = (-sinPoleY) * sinRotX / cosRegY;\n\t\t\t\t\tconst double PD = (cosPoleY * cosRotY - sinPoleY * cosRotX * sinRotY) / cosRegY;\n\n\t\t\t\t\tU[i] = static_cast<T>(PA * u + PB * v);\n\t\t\t\t\tV[i] = static_cast<T>(PC * u + PD * v);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase kLambertConformalConic:\n\t\t\t{\n\t\t\t\tauto lcc = dynamic_cast<const lambert_conformal_grid*>(from);\n\t\t\t\tconst double cone = lcc->Cone();\n\t\t\t\tconst double orientation = lcc->Orientation();\n\n\t\t\t\tfor (size_t i = 0; i < U.Size(); i++)\n\t\t\t\t{\n\t\t\t\t\tT u = U[i];\n\t\t\t\t\tT v = V[i];\n\n\t\t\t\t\t// http://www.mcs.anl.gov/~emconsta/wind_conversion.txt\n\n\t\t\t\t\tdouble angle = from->LatLon(i).X() - orientation;\n\t\t\t\t\tASSERT(angle >= -180 && angle <= 180);\n\n\t\t\t\t\tconst double anglex = cone * angle * constants::kDeg;\n\t\t\t\t\tdouble sinx, cosx;\n\t\t\t\t\tsincos(anglex, &sinx, &cosx);\n\n\t\t\t\t\tU[i] = static_cast<T>(cosx * u + sinx * v);\n\t\t\t\t\tV[i] = static_cast<T>(-1 * sinx * u + cosx * v);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase kStereographic:\n\t\t\t{\n\t\t\t\t// The same as lambert but with cone = 1\n\n\t\t\t\tconst double orientation = dynamic_cast<const stereographic_grid*>(from)->Orientation();\n\n\t\t\t\tfor (size_t i = 0; i < U.Size(); i++)\n\t\t\t\t{\n\t\t\t\t\tT u = U[i];\n\t\t\t\t\tT v = V[i];\n\n\t\t\t\t\tconst double angle = (from->LatLon(i).X() - orientation) * constants::kDeg;\n\t\t\t\t\tdouble sinx, cosx;\n\n\t\t\t\t\tsincos(angle, &sinx, &cosx);\n\n\t\t\t\t\tU[i] = static_cast<T>(cosx * u + sinx * v);\n\t\t\t\t\tV[i] = static_cast<T>(-1 * sinx * u + cosx * v);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow std::runtime_error(\"Unable to rotate from \" + HPGridTypeToString.at(from->Type()) + \" to \" +\n\t\t\t\t                         HPGridTypeToString.at(to->Type()));\n\t\t}\n\t}\n\n\tif (to->UVRelativeToGrid() == false)\n\t{\n\t\tlog.Trace(\"Result grid has UVRelativeToGrid=false, no need for further rotation\");\n\t\treturn;\n\t}\n\n\tswitch (to->Type())\n\t{\n\t\tcase kLatitudeLongitude:\n\t\t\tbreak;\n\n\t\tcase kRotatedLatitudeLongitude:\n\t\t{\n\t\t\tconst auto rll = dynamic_cast<const rotated_latitude_longitude_grid*>(to);\n\t\t\tpoint southPole = rll->SouthPole();\n\n\t\t\tif (southPole.Y() > 0)\n\t\t\t{\n\t\t\t\tsouthPole.Y(-southPole.Y());\n\t\t\t\tsouthPole.X(0);\n\t\t\t}\n\n\t\t\tfor (size_t i = 0; i < U.Size(); i++)\n\t\t\t{\n\t\t\t\tT u = U[i];\n\t\t\t\tT v = V[i];\n\n\t\t\t\tconst point rotPoint = rll->RotatedLatLon(i);\n\t\t\t\tconst point regPoint = rll->LatLon(i);\n\n\t\t\t\t// Algorithm by J.E. HAUGEN (HIRLAM JUNE -92), modified by K. EEROLA\n\t\t\t\t// Algorithm originally defined in hilake/TURNDD.F\n\n\t\t\t\tconst double southPoleY = constants::kDeg * (southPole.Y() + 90);\n\n\t\t\t\tdouble sinPoleY, cosPoleY;\n\t\t\t\tsincos(southPoleY, &sinPoleY, &cosPoleY);\n\n\t\t\t\tconst double sinRegY = sin(constants::kDeg * regPoint.Y());  // zsyreg\n\t\t\t\tconst double cosRegY = cos(constants::kDeg * regPoint.Y());  // zcyreg\n\n\t\t\t\tdouble zxmxc = constants::kDeg * (regPoint.X() - southPole.X());\n\n\t\t\t\tdouble sinxmxc, cosxmxc;\n\t\t\t\tsincos(zxmxc, &sinxmxc, &cosxmxc);\n\n\t\t\t\tconst double rotXRad = constants::kDeg * rotPoint.X();\n\n\t\t\t\tdouble sinRotX, cosRotX;\n\t\t\t\tsincos(rotXRad, &sinRotX, &cosRotX);\n\n\t\t\t\tconst double cosRotY = cos(constants::kDeg * rotPoint.Y());  // zcyrot\n\n\t\t\t\tconst double PA = cosPoleY * sinxmxc * sinRotX + cosxmxc * cosRotX;\n\t\t\t\tconst double PB =\n\t\t\t\t    cosPoleY * cosxmxc * sinRegY * sinRotX - sinPoleY * cosRegY * sinRotX - sinxmxc * sinRegY * cosRotX;\n\t\t\t\tconst double PC = sinPoleY * sinxmxc / cosRotY;\n\t\t\t\tconst double PD = (sinPoleY * cosxmxc * sinRegY + cosPoleY * cosRegY) / cosRotY;\n\n\t\t\t\tU[i] = static_cast<T>(PA * u + PB * v);\n\t\t\t\tV[i] = static_cast<T>(PC * u + PD * v);\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\t\tcase kLambertConformalConic:\n\t\t{\n\t\t\tauto lcc = dynamic_cast<const lambert_conformal_grid*>(to);\n\t\t\tconst double cone = lcc->Cone();\n\t\t\tconst double orientation = lcc->Orientation();\n\n\t\t\tfor (size_t i = 0; i < U.Size(); i++)\n\t\t\t{\n\t\t\t\tT u = U[i];\n\t\t\t\tT v = V[i];\n\n\t\t\t\t// http://www.mcs.anl.gov/~emconsta/wind_conversion.txt\n\n\t\t\t\tconst double angle = to->LatLon(i).X() - orientation;\n\t\t\t\tASSERT(angle >= -180 && angle <= 180);\n\n\t\t\t\tconst double anglex = cone * angle * constants::kDeg;\n\t\t\t\tdouble sinx, cosx;\n\t\t\t\tsincos(anglex, &sinx, &cosx);\n\n\t\t\t\tU[i] = static_cast<T>(cosx * u - sinx * v);\n\t\t\t\tV[i] = static_cast<T>(sinx * u + cosx * v);\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase kStereographic:\n\t\t{\n\t\t\tconst double orientation = dynamic_cast<const stereographic_grid*>(to)->Orientation();\n\n\t\t\tfor (size_t i = 0; i < U.Size(); i++)\n\t\t\t{\n\t\t\t\tT u = U[i];\n\t\t\t\tT v = V[i];\n\n\t\t\t\tconst double angle = (to->LatLon(i).X() - orientation) * constants::kDeg;\n\t\t\t\tdouble sinx, cosx;\n\n\t\t\t\tsincos(angle, &sinx, &cosx);\n\n\t\t\t\tU[i] = static_cast<T>(cosx * u - sinx * v);\n\t\t\t\tV[i] = static_cast<T>(sinx * u + cosx * v);\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\t\tdefault:\n\t\t\tthrow std::runtime_error(\"Unable to rotate from \" + HPGridTypeToString.at(from->Type()) + \" to \" +\n\t\t\t                         HPGridTypeToString.at(to->Type()));\n\t}\n}\n\ntemplate void RotateVectorComponentsCPU<double>(const grid*, const grid*, himan::matrix<double>&,\n                                                himan::matrix<double>&);\ntemplate void RotateVectorComponentsCPU<float>(const grid*, const grid*, himan::matrix<float>&, himan::matrix<float>&);\ntemplate void RotateVectorComponentsCPU<short>(const grid*, const grid*, himan::matrix<short>&, himan::matrix<short>&);\ntemplate void RotateVectorComponentsCPU<unsigned char>(const grid*, const grid*, himan::matrix<unsigned char>&,\n                                                       himan::matrix<unsigned char>&);\n\ntemplate <typename T>\nvoid RotateVectorComponents(const grid* from, const grid* to, himan::info<T>& UInfo, himan::info<T>& VInfo,\n                            bool useCuda)\n{\n\tASSERT(UInfo.Grid()->UVRelativeToGrid() == VInfo.Grid()->UVRelativeToGrid());\n\n\tlogger log(\"interpolate\");\n\tif (!UInfo.Grid()->UVRelativeToGrid())\n\t{\n\t\tlog.Trace(\"Source data is not relative to grid -- skipping rotation\");\n\t\treturn;\n\t}\n\n#ifdef HAVE_CUDA\n\tif (useCuda)\n\t{\n\t\tif (UInfo.PackedData()->HasData() || VInfo.PackedData()->HasData())\n\t\t{\n\t\t\tthrow std::runtime_error(\"Packed data needs to be unpacked before rotation on GPU\");\n\t\t}\n\n\t\tcudaStream_t stream;\n\t\tCUDA_CHECK(cudaStreamCreate(&stream));\n\t\tRotateVectorComponentsGPU<T>(from, to, UInfo.Data(), VInfo.Data(), stream, 0, 0, 0);\n\t\tCUDA_CHECK(cudaStreamSynchronize(stream));\n\t}\n\telse\n#endif\n\t{\n\t\tRotateVectorComponentsCPU<T>(from, to, UInfo.Data(), VInfo.Data());\n\t}\n\n\tUInfo.Grid()->UVRelativeToGrid(false);\n\tVInfo.Grid()->UVRelativeToGrid(false);\n}\n\ntemplate void RotateVectorComponents<double>(const grid*, const grid*, info<double>&, info<double>&, bool);\ntemplate void RotateVectorComponents<float>(const grid*, const grid*, info<float>&, info<float>&, bool);\ntemplate void RotateVectorComponents<short>(const grid*, const grid*, info<short>&, info<short>&, bool);\ntemplate void RotateVectorComponents<unsigned char>(const grid*, const grid*, info<unsigned char>&,\n                                                    info<unsigned char>&, bool);\n\ntemplate <typename T>\nstd::pair<std::vector<size_t>, std::vector<T>> InterpolationWeights(reduced_gaussian_grid& source, point target)\n{\n\t// target lon 0 <= lon < 360\n\tif (target.X() < 0.0)\n\t\ttarget.X(target.X() + 360.0);\n\telse if (target.X() >= 360.0)\n\t\ttarget.X(target.X() - 360.0);\n\n\tconst auto lats = source.Latitudes();\n\n\t// check if point is inside domain\n\tif (target.Y() >= lats.front())\n\t{\n\t\t// point north of domain\n\t\treturn std::make_pair(std::vector<size_t>{0}, std::vector<T>{MissingValue<T>()});\n\t}\n\n\tif (target.Y() <= lats.back())\n\t{\n\t\t// point south of domain\n\t\treturn std::make_pair(std::vector<size_t>{0}, std::vector<T>{MissingValue<T>()});\n\t}\n\n\t// find y-indices\n\tauto south = std::lower_bound(lats.begin(), lats.end(), target.Y(), std::greater_equal<double>());\n\tauto north = south;\n\tnorth--;\n\n\tsize_t y_north = static_cast<size_t>(std::distance(lats.begin(), north));\n\tsize_t y_south = static_cast<size_t>(std::distance(lats.begin(), south));\n\n\t// find x-indices\n\tsize_t x_north_west = static_cast<size_t>(\n\t    std::floor(static_cast<double>(source.NumberOfPointsAlongParallels()[y_north]) * target.X() / 360.));\n\tsize_t x_north_east =\n\t    x_north_west < static_cast<size_t>(source.NumberOfPointsAlongParallels()[y_north] - 1) ? x_north_west + 1 : 0;\n\tsize_t x_south_west = static_cast<size_t>(\n\t    std::floor(static_cast<double>(source.NumberOfPointsAlongParallels()[y_south]) * target.X() / 360.));\n\tsize_t x_south_east =\n\t    x_south_west < static_cast<size_t>(source.NumberOfPointsAlongParallels()[y_south] - 1) ? x_south_west + 1 : 0;\n\n\t/*\n\t *\n\t *  a---------------b\n\t *  |               |\n\t *   \\     p        |\n\t *   |              |\n\t *   c--------------d\n\t *\n\t *  Now we know the indices x|y of the four points a,b,c,d that surround p\n\t */\n\n\tstd::vector<size_t> idxs;\n\tidxs.reserve(4);\n\tidxs.push_back(source.LocationIndex(x_north_west, y_north));\n\tidxs.push_back(source.LocationIndex(x_north_east, y_north));\n\tidxs.push_back(source.LocationIndex(x_south_west, y_south));\n\tidxs.push_back(source.LocationIndex(x_south_east, y_south));\n\n\t// calculate weights by bilinear interpolation to point target (p) surrounded by points A|B|C|D\n\tconst point& p = target;\n\tconst point a = source.LatLon(idxs[0]);\n\tconst point b = source.LatLon(idxs[1]);\n\tconst point c = source.LatLon(idxs[2]);\n\tconst point d = source.LatLon(idxs[3]);\n\n\tstd::vector<T> weights(4);\n\n\t// Matrices and Vectors\n\tEigen::Matrix4d A(4, 4);\n\tEigen::MatrixXd xi(4, 2);\n\tEigen::Vector4d x(4);\n\tEigen::Vector2d phi(2);\n\n\t// Construct linear system of equations to be solved\n\tA(0, 0) = 1;\n\tA(1, 0) = 1;\n\tA(2, 0) = 1;\n\tA(3, 0) = 1;\n\tA(0, 1) = a.X();\n\tA(1, 1) = b.X() == 0.0 ? 360 : b.X();\n\n\tA(2, 1) = c.X();\n\tA(3, 1) = d.X() == 0.0 ? 360 : d.X();\n\n\tA(0, 2) = a.Y();\n\tA(1, 2) = b.Y();\n\tA(2, 2) = c.Y();\n\tA(3, 2) = d.Y();\n\tA(0, 3) = a.X() * a.Y();\n\tA(1, 3) = b.X() == 0.0 ? 360 * b.Y() : b.X() * b.Y();\n\tA(2, 3) = c.X() * c.Y();\n\tA(3, 3) = d.X() == 0.0 ? 360 * d.Y() : d.X() * d.Y();\n\n\txi(0, 0) = 0;\n\txi(1, 0) = 1;\n\txi(2, 0) = 0;\n\txi(3, 0) = 1;\n\txi(0, 1) = 1;\n\txi(1, 1) = 1;\n\txi(2, 1) = 0;\n\txi(3, 1) = 0;\n\n\t// Solve linear system\n\txi = A.colPivHouseholderQr().solve(xi);\n\n\tx[0] = 1;\n\tx[1] = p.X();\n\tx[2] = p.Y();\n\tx[3] = p.X() * p.Y();\n\n\txi.transposeInPlace();\n\tphi = xi * x;\n\n\tweights[0] = static_cast<T>((1 - phi[0]) * phi[1]);\n\tweights[1] = static_cast<T>(phi[0] * phi[1]);\n\tweights[2] = static_cast<T>((1 - phi[0]) * (1 - phi[1]));\n\tweights[3] = static_cast<T>(phi[0] * (1 - phi[1]));\n\n\treturn std::make_pair(idxs, weights);\n}\n\ntemplate <typename T>\nstd::pair<std::vector<size_t>, std::vector<T>> InterpolationWeights(const regular_grid& source, const point& xy)\n{\n\tif (IsMissing(xy.X()) || IsMissing(xy.Y()))\n\t\treturn std::make_pair(std::vector<size_t>{0}, std::vector<T>{MissingValue<T>()});\n\n\tstd::vector<size_t> idxs{static_cast<size_t>(xy.X()) + source.Ni() * static_cast<size_t>(xy.Y()),\n\t                         static_cast<size_t>(xy.X()) + source.Ni() * static_cast<size_t>(xy.Y()) + 1 -\n\t                             (static_cast<size_t>(xy.X()) == source.Ni() - 1 ? source.Ni() : 0),\n\t                         static_cast<size_t>(xy.X()) + source.Ni() * static_cast<size_t>(xy.Y() + 1),\n\t                         static_cast<size_t>(xy.X()) + source.Ni() * static_cast<size_t>(xy.Y() + 1) + 1 -\n\t                             (static_cast<size_t>(xy.X()) == source.Ni() - 1 ? source.Ni() : 0)};\n\n\tstd::vector<T> weights(4);\n\n\tweights[0] = static_cast<T>((1 - std::fmod(xy.X(), 1)) * (1 - std::fmod(xy.Y(), 1)));\n\tweights[1] = static_cast<T>(std::fmod(xy.X(), 1) * (1 - std::fmod(xy.Y(), 1)));\n\tweights[2] = static_cast<T>((1 - std::fmod(xy.X(), 1)) * std::fmod(xy.Y(), 1));\n\tweights[3] = static_cast<T>(std::fmod(xy.X(), 1) * std::fmod(xy.Y(), 1));\n\n\t// Index is outside grid. This happens when target point is located on bottom edge\n\t// Set index to first grid point\n\tfor (auto& idx : idxs)\n\t{\n\t\tif (idx > source.Size() - 1)\n\t\t{\n\t\t\tidx = 0;\n\t\t}\n\t}\n\n\treturn std::make_pair(idxs, weights);\n}\n\ntemplate <typename T>\nstd::vector<std::pair<std::vector<size_t>, std::vector<T>>> InterpolationWeights(const regular_grid& source,\n                                                                                 const std::vector<point>& targets)\n{\n\tstd::vector<std::pair<std::vector<size_t>, std::vector<T>>> ret;\n\tret.reserve(targets.size());\n\n\tfor (const auto& xy : targets)\n\t{\n\t\tret.push_back(InterpolationWeights<T>(source, xy));\n\t}\n\n\treturn ret;\n}\n\ntemplate <typename T>\nstd::pair<size_t, T> NearestPoint(reduced_gaussian_grid& source, point target)\n{\n\t// target lon 0 <= lon < 360\n\tif (target.X() < 0.0)\n\t\ttarget.X(target.X() + 360.0);\n\telse if (target.X() >= 360.0)\n\t\ttarget.X(target.X() - 360.0);\n\n\tconst auto lats = source.Latitudes();\n\n\t// find y-indices\n\tauto south = std::lower_bound(lats.begin(), lats.end(), target.Y(), std::greater_equal<double>());\n\tauto north = south;\n\tnorth--;\n\n\tsize_t y_north = std::distance(lats.begin(), north);\n\tsize_t y_south = std::distance(lats.begin(), south);\n\n\t// find x-indices\n\tsize_t x_north_west = static_cast<size_t>(\n\t    std::floor(static_cast<double>(source.NumberOfPointsAlongParallels()[y_north]) * target.X() / 360.));\n\tsize_t x_north_east =\n\t    x_north_west < static_cast<size_t>(source.NumberOfPointsAlongParallels()[y_north] - 1) ? x_north_west + 1 : 0;\n\tsize_t x_south_west = static_cast<size_t>(\n\t    std::floor(static_cast<double>(source.NumberOfPointsAlongParallels()[y_south]) * target.X() / 360.));\n\tsize_t x_south_east =\n\t    x_south_west < static_cast<size_t>(source.NumberOfPointsAlongParallels()[y_south] - 1) ? x_south_west + 1 : 0;\n\n\tsize_t nearest = x_north_west;\n\tfor (auto p : {x_north_east, x_south_west, x_south_east})\n\t{\n\t\tif (geoutil::Distance(source.LatLon(p), target) < geoutil::Distance(source.LatLon(nearest), target))\n\t\t\tnearest = p;\n\t}\n\n\treturn std::make_pair(nearest, 1.0);\n}\n\ntemplate <typename T>\nstd::pair<size_t, T> NearestPoint(const regular_grid& source, const point& xy)\n{\n\tif (IsMissing(xy.X()) || IsMissing(xy.Y()))\n\t{\n\t\treturn std::make_pair(0, MissingValue<T>());\n\t}\n\t// In case of point in wrap-around region on global grid\n\tif (static_cast<size_t>(std::round(xy.X())) == source.Ni())\n\t{\n\t\treturn std::make_pair(source.Ni() * static_cast<size_t>(std::round(xy.Y())), 1.0);\n\t}\n\treturn std::make_pair(\n\t    static_cast<size_t>(std::round(xy.X())) + source.Ni() * static_cast<size_t>(std::round(xy.Y())), 1.0);\n}\n\ntemplate <typename T>\nstd::vector<std::pair<size_t, T>> NearestPoint(const regular_grid& source, const std::vector<point>& targets)\n{\n\tstd::vector<std::pair<size_t, T>> ret;\n\tret.reserve(targets.size());\n\n\tfor (const auto& xy : targets)\n\t{\n\t\tret.push_back(NearestPoint<T>(source, xy));\n\t}\n\n\treturn ret;\n}\n\n// area_interpolation class member functions definitions\ntemplate <typename T>\narea_interpolation<T>::area_interpolation(grid& source, grid& target, HPInterpolationMethod method)\n    : itsInterpolation(target.Size(), source.Size())\n{\n\tstd::vector<Triplet<T>> coefficients;\n\n\tstd::string useOldMethod = \"no\";\n\ttry\n\t{\n\t\tuseOldMethod = util::GetEnv(\"HIMAN_USE_OLD_PROJECTION_METHOD\");\n\t}\n\tcatch (...)\n\t{\n\t}\n\n\t// default to using new 'bulk' method\n\tif (source.Class() == target.Class() && source.Class() == kRegularGrid && useOldMethod == \"no\")\n\t{\n\t\tconst regular_grid& sg = dynamic_cast<regular_grid&>(source);\n\t\tconst regular_grid& tg = dynamic_cast<regular_grid&>(target);\n\n\t\tstd::vector<point> xy = sg.XY(tg);\n\t\tstd::vector<std::pair<std::vector<size_t>, std::vector<T>>> ws;\n\n\t\tif (method == kBiLinear)\n\t\t{\n\t\t\tws = InterpolationWeights<T>(sg, xy);\n\t\t}\n\t\telse if (method == kNearestPoint)\n\t\t{\n\t\t\tauto np = NearestPoint<T>(sg, xy);\n\n\t\t\tfor (size_t i = 0; i < np.size(); i++)\n\t\t\t{\n\t\t\t\tstd::pair<std::vector<size_t>, std::vector<T>> w;\n\t\t\t\tw.first.push_back(np[i].first);\n\t\t\t\tw.second.push_back(np[i].second);\n\t\t\t\tws.push_back(w);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow std::bad_typeid();\n\t\t}\n\n\t\tfor (size_t i = 0; i < ws.size(); i++)\n\t\t{\n\t\t\tconst auto& w = ws[i];\n\t\t\tfor (size_t j = 0; j < w.first.size(); ++j)\n\t\t\t{\n\t\t\t\tcoefficients.push_back(Triplet<T>(static_cast<int>(i), static_cast<int>(w.first[j]), w.second[j]));\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\t// compute weights in the interpolation matrix line by line, i.e. point by point on target grid\n\t\tfor (size_t i = 0; i < target.Size(); ++i)\n\t\t{\n\t\t\tstd::pair<std::vector<size_t>, std::vector<T>> w;\n\t\t\tswitch (source.Type())\n\t\t\t{\n\t\t\t\tcase kLatitudeLongitude:\n\t\t\t\tcase kRotatedLatitudeLongitude:\n\t\t\t\tcase kStereographic:\n\t\t\t\tcase kLambertConformalConic:\n\t\t\t\tcase kLambertEqualArea:\n\t\t\t\tcase kTransverseMercator:\n\t\t\t\t\tif (method == kBiLinear)\n\t\t\t\t\t{\n\t\t\t\t\t\tw = InterpolationWeights<T>(dynamic_cast<regular_grid&>(source),\n\t\t\t\t\t\t                            dynamic_cast<regular_grid&>(source).XY(target.LatLon(i)));\n\t\t\t\t\t}\n\t\t\t\t\telse if (method == kNearestPoint)\n\t\t\t\t\t{\n\t\t\t\t\t\tauto np = NearestPoint<T>(dynamic_cast<regular_grid&>(source),\n\t\t\t\t\t\t                          dynamic_cast<regular_grid&>(source).XY(target.LatLon(i)));\n\t\t\t\t\t\tw.first.push_back(np.first);\n\t\t\t\t\t\tw.second.push_back(np.second);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tthrow std::bad_typeid();\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase kReducedGaussian:\n\t\t\t\t\tif (method == kBiLinear)\n\t\t\t\t\t{\n\t\t\t\t\t\tw = InterpolationWeights<T>(dynamic_cast<reduced_gaussian_grid&>(source), target.LatLon(i));\n\t\t\t\t\t}\n\t\t\t\t\telse if (method == kNearestPoint)\n\t\t\t\t\t{\n\t\t\t\t\t\tauto np = NearestPoint<T>(dynamic_cast<reduced_gaussian_grid&>(source), target.LatLon(i));\n\t\t\t\t\t\tw.first.push_back(np.first);\n\t\t\t\t\t\tw.second.push_back(np.second);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tthrow std::bad_typeid();\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t// what to throw?\n\t\t\t\t\tthrow std::bad_typeid();\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tfor (size_t j = 0; j < w.first.size(); ++j)\n\t\t\t{\n\t\t\t\tcoefficients.push_back(Triplet<T>(static_cast<int>(i), static_cast<int>(w.first[j]), w.second[j]));\n\t\t\t}\n\t\t}\n\t}\n\n\titsInterpolation.setFromTriplets(coefficients.begin(), coefficients.end());\n}\n\ntemplate <typename T>\nvoid area_interpolation<T>::Interpolate(base<T>& source, base<T>& target)\n{\n\tMap<Matrix<T, Dynamic, Dynamic>> srcValues(source.data.ValuesAsPOD(), source.data.Size(), 1);\n\tMap<Matrix<T, Dynamic, Dynamic>> trgValues(target.data.ValuesAsPOD(), target.data.Size(), 1);\n\n\ttrgValues = itsInterpolation * srcValues;\n}\n\ntemplate <typename T>\nsize_t area_interpolation<T>::SourceSize() const\n{\n\treturn itsInterpolation.cols();\n}\n\ntemplate <typename T>\nsize_t area_interpolation<T>::TargetSize() const\n{\n\treturn itsInterpolation.rows();\n}\n\n// Interpolator member functions\ntemplate <typename T>\nstd::map<size_t, area_interpolation<T>> interpolator<T>::cache;\n\ntemplate <typename T>\nstd::mutex interpolator<T>::interpolatorAccessMutex;\n\ntemplate <typename T>\nbool interpolator<T>::Insert(const base<T>& source, const base<T>& target, HPInterpolationMethod method)\n{\n\tstd::lock_guard<std::mutex> guard(interpolatorAccessMutex);\n\n\tstd::pair<size_t, himan::interpolate::area_interpolation<T>> insertValue;\n\n\ttry\n\t{\n\t\tstd::vector<size_t> hashes{method, source.grid->Hash(), target.grid->Hash()};\n\t\tinsertValue.first = boost::hash_range(hashes.begin(), hashes.end());\n\n\t\t// area_interpolation is already present in cache\n\t\tif (cache.count(insertValue.first) > 0)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\n\t\tinsertValue.second = himan::interpolate::area_interpolation<T>(*source.grid, *target.grid, method);\n\t}\n\tcatch (const std::exception& e)\n\t{\n\t\tstd::cerr << \"Creating interpolation coefficients failed with \" << e.what() << \"\\n\";\n\t\thiman::Abort();\n\t}\n\n\treturn cache.insert(std::move(insertValue)).second;\n}\n\n// template bool interpolator::Insert<double>(const base<double>&, const base<double>&, HPInterpolationMethod);\n// template bool interpolator::Insert<float>(const base<float>&, const base<float>&, HPInterpolationMethod);\n\ntemplate <typename T>\nbool interpolator<T>::Interpolate(base<T>& source, base<T>& target, HPInterpolationMethod method)\n{\n\tstd::vector<size_t> hashes{method, source.grid->Hash(), target.grid->Hash()};\n\tauto it = cache.find(boost::hash_range(hashes.begin(), hashes.end()));\n\n\tif (it != cache.end())\n\t{\n\t\ttry\n\t\t{\n\t\t\tit->second.Interpolate(source, target);\n\t\t\treturn true;\n\t\t}\n\t\tcatch (const boost::bad_get& e)\n\t\t{\n\t\t\tstd::cout << e.what() << std::endl;\n\t\t\treturn false;\n\t\t}\n\t}\n\n\telse\n\t{\n\t\tInsert(source, target, method);\n\t\treturn Interpolate(source, target, method);\n\t}\n}\n\n// template bool interpolator::Interpolate<double>(base<double>&, base<double>&, HPInterpolationMethod);\n// template bool interpolator::Interpolate<float>(base<float>&, base<float>&, HPInterpolationMethod);\n\n}  // namespace interpolate\n}  // namespace himan\n", "meta": {"hexsha": "ed437795b96b1905d846513751ecc54c8d7d1022", "size": 31199, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "himan-lib/source/interpolate.cpp", "max_stars_repo_name": "fmidev/himan", "max_stars_repo_head_hexsha": "481e0cf9a3d15c900e07d08cf7e22de1c50a6823", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2017-04-20T18:51:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T21:12:49.000Z", "max_issues_repo_path": "himan-lib/source/interpolate.cpp", "max_issues_repo_name": "fmidev/himan", "max_issues_repo_head_hexsha": "481e0cf9a3d15c900e07d08cf7e22de1c50a6823", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-07-05T02:15:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-01T09:36:51.000Z", "max_forks_repo_path": "himan-lib/source/interpolate.cpp", "max_forks_repo_name": "fmidev/himan", "max_forks_repo_head_hexsha": "481e0cf9a3d15c900e07d08cf7e22de1c50a6823", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-02-18T06:32:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-29T15:17:09.000Z", "avg_line_length": 29.1307189542, "max_line_length": 119, "alphanum_fraction": 0.6406615597, "num_tokens": 9216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.29940256556230654}}
{"text": "/*\n * Copyright (c) 2019, 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// 14D quadrotor dynamics.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include <quads/quadrotor14d.h>\n#include <quads/types.h>\n\n#include <ros/ros.h>\n#include <Eigen/Dense>\n#include <string>\n#include <iostream>\n\nnamespace quads {\n\nVector14d Quadrotor14D::operator()(const Vector14d& x,\n                                   const Vector4d& u) const {\n  ROS_ASSERT(initialized_);\n\n  // Precompute sines/consines.\n  const double cpsi = std::cos(x(kPsiIdx));\n  const double spsi = std::sin(x(kPsiIdx));\n  const double cphi = std::cos(x(kPhiIdx));\n  const double sphi = std::sin(x(kPhiIdx));\n  const double ctheta = std::cos(x(kThetaIdx));\n  const double stheta = std::sin(x(kThetaIdx));\n\n  const double gx = (cpsi * stheta * cphi + spsi * sphi) / m_;\n  const double gy = (spsi * stheta * cphi - cpsi * sphi) / m_;\n  const double gz = cphi * ctheta / m_;\n\n  Vector14d xdot;\n  xdot << x(kDxIdx), x(kDyIdx), x(kDzIdx), x(kQIdx), x(kRIdx), x(kPIdx),\n      gx * x(kZetaIdx), gy * x(kZetaIdx), gz * x(kZetaIdx) - 9.81, x(kXiIdx),\n      u(0), u(2) / Iy_, u(1) / Ix_, u(3) / Iz_;\n\n  return xdot;\n}\n\nMatrix14x14d Quadrotor14D::StateJacobian(const Vector14d& x,\n                                         const Vector4d& u) const {\n  const double theta = x(kThetaIdx);\n  const double psi = x(kPsiIdx);\n  const double phi = x(kPhiIdx);\n  const double zeta = x(kZetaIdx);\n\n  Matrix14x14d F;\n  F << 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,\n      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n      0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,\n      0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,\n      zeta * std::cos(phi) * std::cos(psi) * std::cos(theta),\n      zeta * (std::cos(phi) * std::sin(psi) -\n              std::cos(psi) * std::sin(phi) * std::sin(theta)),\n      zeta * (std::cos(psi) * std::sin(phi) -\n              std::cos(phi) * std::sin(psi) * std::sin(theta)),\n      0, 0, 0, std::sin(phi) * std::sin(psi) +\n                   std::cos(phi) * std::cos(psi) * std::sin(theta),\n      0, 0, 0, 0, 0, 0, 0,\n      zeta * std::cos(phi) * std::cos(theta) * std::sin(psi),\n      -zeta * (std::cos(phi) * std::cos(psi) +\n               std::sin(phi) * std::sin(psi) * std::sin(theta)),\n      zeta * (std::sin(phi) * std::sin(psi) +\n              std::cos(phi) * std::cos(psi) * std::sin(theta)),\n      0, 0, 0, std::cos(phi) * std::sin(psi) * std::sin(theta) -\n                   std::cos(psi) * std::sin(phi),\n      0, 0, 0, 0, 0, 0, 0, -zeta * std::cos(phi) * std::sin(theta),\n      -zeta * std::cos(theta) * std::sin(phi), 0, 0, 0, 0,\n      std::cos(phi) * std::cos(theta), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n      1, 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, 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, 0, 0, 0, 0, 0, 0;\n\n  return F;\n}\n\nMatrix6x14d Quadrotor14D::OutputJacobian(const Vector14d& x) const {\n  Matrix6x14d H(Matrix6x14d::Zero());\n  H(0, 0) = 1.0;\n  H(1, 1) = 1.0;\n  H(2, 2) = 1.0;\n  H(3, 3) = 1.0;\n  H(4, 4) = 1.0;\n  H(5, 5) = 1.0;\n  return H;\n}\n\nbool Quadrotor14D::Initialize(const ros::NodeHandle& n) {\n  name_ = ros::names::append(n.getNamespace(), \"quadrotor14d\");\n\n  if (!LoadParameters(n)) {\n    ROS_ERROR(\"%s: Failed to load parameters.\", name_.c_str());\n    return false;\n  }\n\n  initialized_ = true;\n  return true;\n}\n\nbool Quadrotor14D::LoadParameters(const ros::NodeHandle& n) {\n  ros::NodeHandle nl(n);\n\n  // Mass and inertia.\n  if (!nl.getParam(\"dynamics/m\", m_)) return false;\n  if (!nl.getParam(\"dynamics/Ix\", Ix_)) return false;\n  if (!nl.getParam(\"dynamics/Iy\", Iy_)) return false;\n  if (!nl.getParam(\"dynamics/Iz\", Iz_)) return false;\n\n  return true;\n}\n\n}  // namespace quads\n", "meta": {"hexsha": "631c6ad5c76ed1af457c45c1df0c925662035dbc", "size": 5694, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ros/src/quads/src/quadrotor14d.cpp", "max_stars_repo_name": "HJReachability/learning_feedback_linearization", "max_stars_repo_head_hexsha": "cb655ade4cfbf53f5dd19f79c943f7665666f2cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-12-18T01:51:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T14:49:31.000Z", "max_issues_repo_path": "ros/src/quads/src/quadrotor14d.cpp", "max_issues_repo_name": "HJReachability/learning_feedback_linearization", "max_issues_repo_head_hexsha": "cb655ade4cfbf53f5dd19f79c943f7665666f2cb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-19T22:41:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-19T22:41:51.000Z", "max_forks_repo_path": "ros/src/quads/src/quadrotor14d.cpp", "max_forks_repo_name": "HJReachability/learning_feedback_linearization", "max_forks_repo_head_hexsha": "cb655ade4cfbf53f5dd19f79c943f7665666f2cb", "max_forks_repo_licenses": ["BSD-3-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.96, "max_line_length": 80, "alphanum_fraction": 0.588338602, "num_tokens": 2009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.29940256556230654}}
{"text": "#include <CGAL/Three/Polyhedron_demo_plugin_interface.h>\n#include <CGAL/Three/Scene_interface.h>\n#include <QApplication>\n#include <QObject>\n#include <QAction>\n#include <QMainWindow>\n#include <QInputDialog>\n#include <QMessageBox>\n#include <QMap>\n#include \"Messages_interface.h\"\n#ifdef USE_SURFACE_MESH\n#include \"Kernel_type.h\"\n#include \"Scene_surface_mesh_item.h\"\n#else\n#include \"Scene_polyhedron_item.h\"\n#include \"Polyhedron_type.h\"\n#endif\n#include \"Color_ramp.h\"\n#include \"triangulate_primitive.h\"\n#include <CGAL/Polygon_mesh_processing/bbox.h>\n#include <CGAL/Polygon_mesh_processing/distance.h>\n#include <CGAL/Polygon_mesh_processing/compute_normal.h>\n#include <boost/iterator/counting_iterator.hpp>\n#include <CGAL/Search_traits_3.h>\n#include <CGAL/Spatial_sort_traits_adapter_3.h>\n#include <CGAL/property_map.h>\n#include <boost/container/flat_map.hpp>\n\nusing namespace CGAL::Three;\nnamespace PMP = CGAL::Polygon_mesh_processing;\n\n#ifdef USE_SURFACE_MESH\ntypedef Scene_surface_mesh_item Scene_face_graph_item;\n#else\ntypedef Scene_polyhedron_item Scene_face_graph_item;\n#endif\n\ntypedef Scene_face_graph_item::Face_graph Face_graph;\n\n#if defined(CGAL_LINKED_WITH_TBB)\ntemplate <class AABB_tree, class Point_3>\nstruct Distance_computation{\n  const AABB_tree& tree;\n  const std::vector<Point_3>& sample_points;\n  Point_3 initial_hint;\n  tbb::atomic<double>* distance;\n  std::vector<double>& output;\n\n  Distance_computation(const AABB_tree& tree,\n                       const Point_3 p,\n                       const std::vector<Point_3>& sample_points,\n                       tbb::atomic<double>* d,\n                       std::vector<double>& out )\n    : tree(tree)\n    , sample_points(sample_points)\n    , initial_hint(p)\n    , distance(d)\n    , output(out)\n  {\n  }\n  void\n  operator()(const tbb::blocked_range<std::size_t>& range) const\n  {\n    Point_3 hint = initial_hint;\n    double hdist = 0;\n    for( std::size_t i = range.begin(); i != range.end(); ++i)\n    {\n      hint = tree.closest_point(sample_points[i], hint);\n      Kernel::FT dist = squared_distance(hint,sample_points[i]);\n      double d = CGAL::sqrt(dist);\n      output[i] = d;\n      if (d>hdist) hdist=d;\n    }\n\n    if (hdist > distance->load())\n      distance->store(hdist);\n  }\n};\n#endif\n\nclass Scene_distance_polyhedron_item: public Scene_item\n{\n  Q_OBJECT\npublic:\n  Scene_distance_polyhedron_item(Face_graph* poly, Face_graph* polyB, QString other_name, int sampling_pts)\n    :Scene_item(NbOfVbos,NbOfVaos),\n      poly(poly),\n      poly_B(polyB),\n      are_buffers_filled(false),\n      other_poly(other_name)\n  {\n    nb_pts_per_face = sampling_pts;\n    this->setRenderingMode(FlatPlusEdges);\n    thermal_ramp.build_thermal();\n  }\n  bool supportsRenderingMode(RenderingMode m) const {\n    return (m == Flat || m == FlatPlusEdges);\n  }\n  Scene_item* clone() const {return 0;}\n  QString toolTip() const {return QString(\"Item %1 with color indicating distance with %2\").arg(this->name()).arg(other_poly);}\n  void draw(Viewer_interface *viewer) const\n  {\n    if(!are_buffers_filled)\n    {\n      computeElements();\n      initializeBuffers(viewer);\n      compute_bbox();\n    }\n    vaos[Facets]->bind();\n    attribBuffers(viewer, PROGRAM_WITH_LIGHT);\n    program = getShaderProgram(PROGRAM_WITH_LIGHT);\n    program->bind();\n    program->setUniformValue(\"is_selected\", false);\n    viewer->glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(nb_pos/3));\n    program->release();\n    vaos[Facets]->release();\n  }\n  void drawEdges(Viewer_interface* viewer) const\n  {\n    vaos[Edges]->bind();\n\n    attribBuffers(viewer, PROGRAM_WITHOUT_LIGHT);\n    program = getShaderProgram(PROGRAM_WITHOUT_LIGHT);\n    program->bind();\n    //draw the edges\n    program->setAttributeValue(\"colors\", QColor(Qt::black));\n    program->setUniformValue(\"is_selected\", false);\n    viewer->glDrawArrays(GL_LINES, 0, static_cast<GLsizei>(nb_edge_pos/3));\n    vaos[Edges]->release();\n    program->release();\n  }\n\n  void compute_bbox() const {\n    _bbox = PMP::bbox(*poly);\n  }\n\nprivate:\n  Face_graph* poly;\n  Face_graph* poly_B;\n  mutable bool are_buffers_filled;\n  QString other_poly;\n  mutable std::vector<float> m_vertices;\n  mutable std::vector<float> edge_vertices;\n  mutable std::vector<float> normals;\n  mutable std::vector<float> colors;\n  Color_ramp thermal_ramp;\n  int nb_pts_per_face;\n\n  enum VAOs {\n    Facets=0,\n    Edges,\n    NbOfVaos};\n\n  enum VBOs {\n    Vertices=0,\n    Edge_vertices,\n    Normals,\n    Colors,\n    NbOfVbos};\n\n  mutable std::size_t nb_pos;\n  mutable std::size_t nb_edge_pos;\n  mutable QOpenGLShaderProgram *program;\n\n  //fills 'out' and returns the hausdorff distance for calibration of the color_ramp.\n\n  double compute_distances(const Face_graph& m, const std::vector<Kernel::Point_3>& sample_points,\n                           std::vector<double>& out)const\n  {\n    typedef CGAL::AABB_face_graph_triangle_primitive<Face_graph> Primitive;\n    typedef CGAL::AABB_traits<Kernel, Primitive> Traits;\n    typedef CGAL::AABB_tree< Traits > Tree;\n\n    Tree tree( faces(m).first, faces(m).second, m);\n    tree.accelerate_distance_queries();\n    tree.build();\n    boost::graph_traits<Face_graph>::vertex_descriptor vd = *(vertices(m).first);\n    Traits::Point_3 hint = get(CGAL::vertex_point,*poly, vd);\n\n#if !defined(CGAL_LINKED_WITH_TBB)\n    double hdist = 0;\n    for(std::size_t i = 0; i<sample_points.size(); ++i)\n    {\n      hint = tree.closest_point(sample_points[i], hint);\n      Kernel::FT dist = squared_distance(hint,sample_points[i]);\n      double d = CGAL::sqrt(dist);\n      out[i]= d;\n      if (d>hdist) hdist=d;\n    }\n      return hdist;\n#else\n    tbb::atomic<double> distance;\n    distance.store(0);\n    Distance_computation<Tree, Kernel::Point_3> f(tree, hint, sample_points, &distance, out);\n    tbb::parallel_for(tbb::blocked_range<std::size_t>(0, sample_points.size()), f);\n    return distance;\n#endif\n  }\n\n  void computeElements()const\n  {\n    QApplication::setOverrideCursor(Qt::WaitCursor);\n    m_vertices.resize(0);\n    edge_vertices.resize(0);\n    normals.resize(0);\n    colors.resize(0);\n\n    typedef Kernel::Vector_3\t    Vector;\n    typedef boost::graph_traits<Face_graph>::face_descriptor   face_descriptor;\n    typedef boost::graph_traits<Face_graph>::vertex_descriptor vertex_descriptor;\n\n    typedef boost::property_map<Face_graph,CGAL::vertex_point_t>::type VPmap; \n    VPmap vpmap = get(CGAL::vertex_point,*poly);\n\n    //facets\n    {\n      boost::container::flat_map<face_descriptor, Vector> face_normals_map;\n      boost::associative_property_map< boost::container::flat_map<face_descriptor, Vector> >\n          nf_pmap(face_normals_map);\n      boost::container::flat_map<vertex_descriptor, Vector> vertex_normals_map;\n      boost::associative_property_map< boost::container::flat_map<vertex_descriptor, Vector> >\n          nv_pmap(vertex_normals_map);\n\n      PMP::compute_normals(*poly, nv_pmap, nf_pmap);\n      std::vector<Kernel::Point_3> total_points(0);\n\n      BOOST_FOREACH(boost::graph_traits<Face_graph>::face_descriptor f, faces(*poly)) {\n        Vector nf = get(nf_pmap, f);\n        typedef FacetTriangulator<Face_graph, Kernel, boost::graph_traits<Face_graph>::vertex_descriptor> FT;\n        double diagonal;\n        if(this->diagonalBbox() != std::numeric_limits<double>::infinity())\n          diagonal = this->diagonalBbox();\n        else\n          diagonal = 0.0;\n\n        //compute distance with other polyhedron\n        //sample facet\n        std::vector<Kernel::Point_3> sampled_points;\n        std::size_t nb_points =  (std::max)((int)std::ceil(nb_pts_per_face * PMP::face_area(f,*poly,PMP::parameters::geom_traits(Kernel()))),\n                                            1);\n        Kernel::Point_3 &p = get(vpmap,target(halfedge(f,*poly),*poly));\n        Kernel::Point_3 &q = get(vpmap,target(next(halfedge(f,*poly),*poly),*poly));\n        Kernel::Point_3 &r = get(vpmap,target(next(next(halfedge(f,*poly),*poly),*poly),*poly));\n        CGAL::Random_points_in_triangle_3<Kernel::Point_3> g(p, q, r);\n        CGAL::cpp11::copy_n(g, nb_points, std::back_inserter(sampled_points));\n        sampled_points.push_back(p);\n        sampled_points.push_back(q);\n        sampled_points.push_back(r);\n\n        //triangle facets with sample points for color display\n        FT triangulation(f,sampled_points,nf,poly,diagonal);\n\n        if(triangulation.cdt->dimension() != 2 )\n        {\n          qDebug()<<\"Error : cdt not right (dimension != 2). Facet not displayed\";\n          continue;\n        }\n\n        //iterates on the internal faces to add the vertices to the positions\n        //and the normals to the appropriate vectors\n\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\n          for (int i = 0; i<3; ++i)\n          {\n            total_points.push_back(ffit->vertex(i)->point());\n            m_vertices.push_back(ffit->vertex(i)->point().x());\n            m_vertices.push_back(ffit->vertex(i)->point().y());\n            m_vertices.push_back(ffit->vertex(i)->point().z());\n\n            normals.push_back(nf.x());\n            normals.push_back(nf.y());\n            normals.push_back(nf.z());\n          }\n        }\n      }\n      //compute the distances\n      typedef CGAL::Spatial_sort_traits_adapter_3<Kernel,\n                CGAL::Pointer_property_map<Kernel::Point_3>::type > Search_traits_3;\n\n      std::vector<double> distances(total_points.size());\n      std::vector<std::size_t> indices;\n      indices.reserve(total_points.size());\n      std::copy(boost::counting_iterator<std::size_t>(0),\n                boost::counting_iterator<std::size_t>(total_points.size()),\n                std::back_inserter(indices));\n      spatial_sort(indices.begin(),\n                   indices.end(),\n                  Search_traits_3(CGAL::make_property_map(total_points)));\n      std::vector<Kernel::Point_3> sorted_points(total_points.size());\n      for(std::size_t i = 0; i < sorted_points.size(); ++i)\n      {\n        sorted_points[i] = total_points[indices[i]];\n      }\n\n      double hausdorff = compute_distances(*poly_B,\n                                           sorted_points,\n                                           distances);\n      //compute the colors\n      colors.resize(sorted_points.size()*3);\n      for(std::size_t i=0; i<sorted_points.size(); ++i)\n      {\n        std::size_t k = indices[i];\n        double d = distances[i]/hausdorff;\n        colors[3*k]=thermal_ramp.r(d);\n        colors[3*k+1]=thermal_ramp.g(d);\n        colors[3*k+2]=thermal_ramp.b(d);\n      }\n    }\n\n    //edges\n    {\n      //Lines\n      typedef Kernel::Point_3\t\tPoint;\n      typedef boost::graph_traits<Face_graph>::edge_descriptor\tedge_descriptor;\n\n      BOOST_FOREACH(edge_descriptor he, edges(*poly)){\n        const Point& a = get(vpmap,target(he,*poly));\n        const Point& b = get(vpmap,source(he,*poly));\n        {\n\n          edge_vertices.push_back(a.x());\n          edge_vertices.push_back(a.y());\n          edge_vertices.push_back(a.z());\n\n          edge_vertices.push_back(b.x());\n          edge_vertices.push_back(b.y());\n          edge_vertices.push_back(b.z());\n        }\n      }\n    }\n    QApplication::restoreOverrideCursor();\n  }\n  void initializeBuffers(Viewer_interface *viewer)const\n  {\n\n    program = getShaderProgram(PROGRAM_WITH_LIGHT, viewer);\n    program->bind();\n    vaos[Facets]->bind();\n    buffers[Vertices].bind();\n    buffers[Vertices].allocate(m_vertices.data(),\n                               static_cast<GLsizei>(m_vertices.size()*sizeof(float)));\n    program->enableAttributeArray(\"vertex\");\n    program->setAttributeBuffer(\"vertex\",GL_FLOAT,0,3);\n    buffers[Vertices].release();\n    buffers[Normals].bind();\n    buffers[Normals].allocate(normals.data(),\n                              static_cast<GLsizei>(normals.size()*sizeof(float)));\n    program->enableAttributeArray(\"normals\");\n    program->setAttributeBuffer(\"normals\",GL_FLOAT,0,3);\n    buffers[Normals].release();\n    buffers[Colors].bind();\n    buffers[Colors].allocate(colors.data(),\n                             static_cast<GLsizei>(colors.size()*sizeof(float)));\n    program->enableAttributeArray(\"colors\");\n    program->setAttributeBuffer(\"colors\",GL_FLOAT,0,3);\n    buffers[Colors].release();\n    vaos[Facets]->release();\n    program->release();\n\n    program = getShaderProgram(PROGRAM_WITHOUT_LIGHT, viewer);\n    program->bind();\n    vaos[Edges]->bind();\n    buffers[Edge_vertices].bind();\n    buffers[Edge_vertices].allocate(edge_vertices.data(),\n                                    static_cast<GLsizei>(edge_vertices.size()*sizeof(float)));\n    program->enableAttributeArray(\"vertex\");\n    program->setAttributeBuffer(\"vertex\",GL_FLOAT,0,3);\n    buffers[Edge_vertices].release();\n    vaos[Facets]->release();\n    program->release();\n\n    nb_pos = m_vertices.size();\n    m_vertices.resize(0);\n    //\"Swap trick\" insures that the memory is indeed freed and not kept available\n    std::vector<float>(m_vertices).swap(m_vertices);\n    nb_edge_pos = edge_vertices.size();\n    edge_vertices.resize(0);\n    std::vector<float>(edge_vertices).swap(edge_vertices);\n    normals.resize(0);\n    std::vector<float>(normals).swap(normals);\n    colors.resize(0);\n    std::vector<float>(colors).swap(colors);\n    are_buffers_filled = true;\n  }\n};\nclass DistancePlugin :\n    public QObject,\n    public Polyhedron_demo_plugin_interface\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\n  typedef Kernel::Point_3 Point_3;\npublic:\n  //decides if the plugin's actions will be displayed or not.\n  bool applicable(QAction*) const\n  {\n    return scene->selectionIndices().size() == 2 &&\n        qobject_cast<Scene_face_graph_item*>(scene->item(scene->selectionIndices().first())) &&\n        qobject_cast<Scene_face_graph_item*>(scene->item(scene->selectionIndices().last()));\n  }\n  //the list of the actions of the plugin.\n  QList<QAction*> actions() const\n  {\n    return _actions;\n  }\n  //this acts like a constructor for the plugin. It gets the references to the mainwindow and the scene, and connects the action.\n  void init(QMainWindow* mw, Scene_interface* sc, Messages_interface* mi)\n  {\n    //gets the reference to the message interface, to display text in the console widget\n    this->messageInterface = mi;\n    //get the references\n    this->scene = sc;\n    this->mw = mw;\n    //creates the action\n    QAction *actionComputeDistance= new QAction(QString(\"Compute Distance Between Polyhedra\"), mw);\n    //specifies the subMenu\n    actionComputeDistance->setProperty(\"subMenuName\", \"Polygon Mesh Processing\");\n    //links the action\n    if(actionComputeDistance) {\n      connect(actionComputeDistance, SIGNAL(triggered()),\n              this, SLOT(createDistanceItems()));\n      _actions << actionComputeDistance;\n    }\n  }\npublic Q_SLOTS:\n  void createDistanceItems()\n  {\n    bool ok = false;\n    nb_pts_per_face = QInputDialog::getInt(mw, tr(\"Sampling\"),\n                                               tr(\"Number of points per face:\"),40, 1,2147483647,1, &ok);\n    if (!ok)\n      return;\n\n    //check the initial conditions\n    Scene_face_graph_item* itemA = qobject_cast<Scene_face_graph_item*>(scene->item(scene->selectionIndices().first()));\n    Scene_face_graph_item* itemB = qobject_cast<Scene_face_graph_item*>(scene->item(scene->selectionIndices().last()));\n    if(! CGAL::is_triangle_mesh(*itemA->polyhedron()) ||\n       !CGAL::is_triangle_mesh(*itemB->polyhedron()) ){\n      messageInterface->error(QString(\"Distance not computed. (Both polyhedra must be triangulated)\"));\n      return;\n    }\n    QApplication::setOverrideCursor(Qt::WaitCursor);\n    Scene_distance_polyhedron_item* new_itemA = new Scene_distance_polyhedron_item(itemA->polyhedron(),itemB->polyhedron(), itemB->name(), nb_pts_per_face);\n    Scene_distance_polyhedron_item* new_itemB = new Scene_distance_polyhedron_item(itemB->polyhedron(),itemA->polyhedron(), itemA->name(), nb_pts_per_face);\n    itemA->setVisible(false);\n    itemB->setVisible(false);\n    new_itemA->setName(QString(\"%1 to %2\").arg(itemA->name()).arg(itemB->name()));\n    new_itemB->setName(QString(\"%1 to %2\").arg(itemB->name()).arg(itemA->name()));\n    scene->addItem(new_itemA);\n    scene->addItem(new_itemB);\n    QApplication::restoreOverrideCursor();\n  }\nprivate:\n  int nb_pts_per_face;\n  QList<QAction*> _actions;\n  Messages_interface* messageInterface;\n  //The reference to the scene\n  Scene_interface* scene;\n  //The reference to the main window\n  QMainWindow* mw;\n};\n#include \"Distance_plugin.moc\"\n", "meta": {"hexsha": "e84c3ca690795afc969c96ee7734b894d6c8afc4", "size": 16750, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/demo/Polyhedron/Plugins/PMP/Distance_plugin.cpp", "max_stars_repo_name": "liminchen/OptCuts", "max_stars_repo_head_hexsha": "cb85b06ece3a6d1279863e26b5fd17a5abb0834d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 187.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:44:58.000Z", "max_issues_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/demo/Polyhedron/Plugins/PMP/Distance_plugin.cpp", "max_issues_repo_name": "xiaoxie5002/OptCuts", "max_issues_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T13:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-18T13:23:23.000Z", "max_forks_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/demo/Polyhedron/Plugins/PMP/Distance_plugin.cpp", "max_forks_repo_name": "xiaoxie5002/OptCuts", "max_forks_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "avg_line_length": 35.4872881356, "max_line_length": 156, "alphanum_fraction": 0.6660895522, "num_tokens": 4085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.29940256556230654}}
{"text": "#include <algorithm>\n#include <cstdlib>\n#include <iostream>\n#include <numeric>\n#include <string>\n\n#include <boost/program_options.hpp>\n\n#include \"datastructs/matrix.h\"\n#include \"datastructs/equations.h\"\n\n\n#include \"polynomials/commutative_polynomial.h\"\n#include \"polynomials/non_commutative_polynomial.h\"\n\n#include \"semirings/commutativeRExp.h\"\n#include \"semirings/float-semiring.h\"\n#include \"semirings/prec-rat-semiring.h\"\n#include \"semirings/tropical-semiring.h\"\n#include \"semirings/pseudo_linear_set.h\"\n#include \"semirings/semilinear_set.h\"\n#include \"semirings/bool-semiring.h\"\n#include \"semirings/why-set.h\"\n#include \"semirings/viterbi-semiring.h\"\n#include \"semirings/maxmin-semiring.h\"\n\n#ifdef USE_LIBFA\n#include \"semirings/lossy-finite-automaton.h\"\n#include \"polynomials/lossy_non_commutative_polynomial.h\"\n#endif\n\n#ifdef USE_GENEPI\n#include \"semirings/semilinSetNdd.h\"\n#endif\n\n#include \"parser.h\"\n\n\n#include \"solvers/newton_generic.h\"\n#include \"solvers/kleene_seminaive.h\"\n#include \"solvers/solver_utils.h\"\n\n#include \"utils/string_util.h\"\n\n\ntemplate <typename SR, template <typename> class Poly>\nValuationMap<SR> call_solver(const std::string solver_name,  const GenericEquations<Poly, SR> &equations,\n   const bool scc, const bool iteration_flag, const std::size_t iterations, const bool graphviz_output){\n  if(0 == solver_name.compare(\"newtonSymb\")) {\n    std::cout << \"Solver: Newton Symbolic\" << std::endl;\n    return apply_solver<Newton, Poly>(equations, scc, iteration_flag, iterations, graphviz_output);\n  }\n  else if(0 == solver_name.compare(\"newtonConc\")) {\n    std::cout << \"Solver: Newton Concrete\"<< std::endl;\n    return apply_solver<NewtonCL, Poly>(equations, scc, iteration_flag, iterations, graphviz_output);\n  }\n  else if(0 == solver_name.compare(\"newtonCLDU\")) {\n    std::cout << \"Solver: Newton Concrete (LDU)\"<< std::endl;\n    return apply_solver<NewtonCLDU, Poly>(equations, scc, iteration_flag, iterations, graphviz_output);\n  }\n  else if(0 == solver_name.compare(\"newtonSLDU\")) {\n      std::cout << \"Solver: Newton Symbolic (LDU)\"<< std::endl;\n      return apply_solver<NewtonSLDU, Poly>(equations, scc, iteration_flag, iterations, graphviz_output);\n  }\n  else if(0 == solver_name.compare(\"kleene\")) {\n    std::cout << \"Solver: Kleene solver\"<< std::endl;\n    return apply_solver<KleeneComm, Poly>(equations, scc, iteration_flag, iterations, graphviz_output);\n  }\n  else {\n    // default-case\n    std::cout << \"Solver: Newton Concrete (LDU)\"<< std::endl;\n    return apply_solver<NewtonCLDU, Poly>(equations, scc, iteration_flag, iterations, graphviz_output);\n  }\n}\n\nint main(int argc, char* argv[]) {\n\n  namespace po = boost::program_options;\n\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()\n    ( \"scc\", \"apply newton method iteratively to strongly connected components of the equation graph\" )\n    ( \"help,h\", \"print this help message\" )\n    ( \"iterations,i\", po::value<int>(), \"specify the number of newton iterations. Default is number of equations + 1.\" )\n    //( \"verbose\", \"enable verbose output\" )\n    //( \"debug\", \"enable debug output\" )\n    ( \"test\", \"just for testing purposes ... explicit test defined in main()\" )\n    ( \"file,f\", po::value<std::string>(), \"input file\" )\n    ( \"float\", \"float semiring\" )\n    ( \"rat\", \"semiring of extended rationals (arbitrary precision)\" )\n    ( \"bool\", \"boolean semiring\" )\n    ( \"why\", \"why semiring\" )\n    ( \"maxmin\", \"MaxMin semiring\" )\n    ( \"viterbi\", \"Viterbi semiring\" )\n    ( \"tropical\", \"tropical semiring over the integers\" )\n    ( \"rexp\", \"commutative regular expression semiring\" )\n    ( \"slset\", \"explicit semilinear sets semiring, no simplification \" )\n#ifdef USE_GENEPI\n    ( \"slsetndd\", po::value<std::string>(), \"ndd semilinear sets semiring, give plugin name (lash-msdf, mona)\" )\n    ( \"n\", po::value<int>(), \"number of variables, used for slsetndd\" )\n#endif\n    ( \"mlset\", \"abstraction over semilinear sets\" )\n    ( \"vec-simpl\", \"vector simplification only (only semilinear and multilinear sets)\" )\n    ( \"lin-simpl\", \"linear set simplification (only semilinear sets)\" )\n    ( \"free\", \"free semiring\" )\n    ( \"lossy\", \"lossy semiring\" )\n    ( \"prefix\", po::value<int>(), \"prefix semiring with given length\")\n    ( \"graphviz\", \"create the file graph.dot with the equation graph (NOTE: currently only with option --scc) \" )\n    ( \"solver,s\", po::value<std::string>(), \"solver type (currently: \\\"newtonSymb\\\", \\\"newtonConc\\\", \\\"newtonCLDU\\\", \\\"newtonSLDU\\\", \\\"newtonNumeric\\\" (only for numeric semirings), or \\\"kleene\\\")\" )\n    ;\n\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n  po::notify(vm);\n\n  if (vm.count(\"test\")) {\n    Newton<SemilinSetExp> newton;\n    std::vector<VarId> variables;\n    variables.push_back(Var::GetVarId(\"x\"));\n    std::cout << \"- newton (cnt-SR):\" << std::endl;\n\n    std::vector<CommutativePolynomial<SemilinSetExp> > polynomials;\n    CommutativePolynomial<SemilinSetExp> f1 = CommutativePolynomial<SemilinSetExp>({\n        { SemilinSetExp(Var::GetVarId(\"a\")), CommutativeMonomial{ {Var::GetVarId(\"x\"),Var::GetVarId(\"x\")} } },\n        { SemilinSetExp(Var::GetVarId(\"c\")), CommutativeMonomial{} } });\n\n    polynomials.push_back(f1);\n\n    Matrix<SemilinSetExp> result = newton.solve_fixpoint(polynomials, variables, 2);\n    std::cout << result << std::endl;\n\n    /*              auto s1 = CommutativeRExp(Var::GetVarId(\"a\"));\n                    auto s2 = CommutativeRExp(Var::GetVarId(\"b\"));\n                    auto m1 = Matrix<CommutativeRExp>(1,1,{s1});\n                    auto m2 = Matrix<CommutativeRExp>(1,1,{s2});\n                    */\n\n    // this actually led to a strange bug with the ublas-matrix implementation!!\n    /*              auto s1 = SemilinSetExp(Var::GetVarId(\"a\"));\n                    auto s2 = SemilinSetExp(Var::GetVarId(\"b\"));\n                    auto m1 = Matrix<SemilinSetExp>(1,1,{s1});\n                    auto m2 = Matrix<SemilinSetExp>(1,1,{s2});\n\n                    auto m3 = m1*m2;\n                    std::cout << m3;\n                    */\n    return 0;\n  }\n\n  if (vm.count(\"help\")) {\n    std::cout << desc << std::endl;\n    return 0;\n  }\n\n#ifdef USE_GENEPI\n  SemilinSetNdd::genepi_init();\n#endif\n\n  int iterations=0;\n  if (vm.count(\"iterations\"))\n          iterations = vm[\"iterations\"].as<int>();\n\n  // check if we can do something useful\n  if (!vm.count(\"float\") &&\n      !vm.count(\"rat\") &&\n      !vm.count(\"rexp\") &&\n      !vm.count(\"slset\") &&\n#ifdef USE_GENEPI\n      !vm.count(\"slsetndd\") &&\n#endif\n      !vm.count(\"free\") &&\n      !vm.count(\"bool\") &&\n      !vm.count(\"why\") &&\n      !vm.count(\"tropical\") &&\n      !vm.count(\"mlset\") &&\n      !vm.count(\"prefix\") &&\n      !vm.count(\"lossy\") &&\n      !vm.count(\"maxmin\") &&\n      !vm.count(\"viterbi\"))\n    {\n    std::cout << \"Please supply a supported semiring :)\" << std::endl;\n    return 0;\n  }\n\n  std::vector<std::string> input;\n  std::string line;\n  if (vm.count(\"file\")) {\n    // we are reading the input from the given file\n    std::ifstream file;\n    file.open(vm[\"file\"].as<std::string>(), std::ifstream::in);\n    if (file.fail()) {\n      std::cerr << \"Could not open input file: \" << vm[\"file\"].as<std::string>() << std::endl;\n    }\n    while (std::getline(file, line)) {\n      input.push_back(line);\n    }\n  } else {\n    // we are reading from stdin\n    while (std::getline(std::cin, line)) {\n      input.push_back(line);\n    }\n  }\n\n  // join the input into one string\n  std::string input_all =\n    std::accumulate(input.begin(), input.end(), std::string(\"\"));\n\n  Parser p;\n  std::string solver_name;\n\n  if(vm.count(\"solver\")) {\n    solver_name = vm[\"solver\"].as<std::string>();\n  }\n  else {\n    solver_name = \"newtonConc\"; //seems to be the fastest\n  }\n\n\n  const auto iter_flag = vm.count(\"iterations\");\n  const auto graph_flag = vm.count(\"graphviz\");\n  const auto scc_flag = vm.count(\"scc\");\n\n  if (vm.count(\"slset\")) {\n    auto equations_raw = p.free_parser(input_all);\n    auto equations = MakeCommEquationsAndMap(equations_raw, [](const FreeSemiring &c) -> SemilinSetExp {\n      auto srconv = SRConverter<SemilinSetExp>();\n      return c.Eval(srconv);\n    });\n\n    if (equations.empty()) return EXIT_FAILURE;\n    //PrintEquations(equations);\n    if (!vm.count(\"vec-simpl\") && !vm.count(\"lin-simpl\")) {\n      DMSG(\"A\");\n      std::cout << result_string(\n          call_solver(solver_name, equations, scc_flag, iter_flag, iterations, graph_flag)\n          ) << std::endl;\n\n    } else if (vm.count(\"vec-simpl\") && !vm.count(\"lin-simpl\")) {\n      DMSG(\"B\");\n      auto equations2 = MapEquations(equations, [](const SemilinearSet<> &s) {\n        return SemilinearSetV{s};\n      });\n      std::cout << result_string(\n          call_solver(solver_name, equations2, scc_flag, iter_flag, iterations, graph_flag)\n          ) << std::endl;\n    } else {\n      DMSG(\"C\");\n      auto equations2 = MapEquations(equations, [](const SemilinearSet<> &s) {\n        return SemilinearSetL{s};\n      });\n      std::cout << result_string(\n          call_solver(solver_name, equations2, scc_flag, iter_flag, iterations, graph_flag)\n          ) << std::endl;\n    }\n#ifdef USE_GENEPI\n  } else if (vm.count(\"slsetndd\")) {\n      SemilinSetNdd::solver_init(vm[\"n\"].as<int>());\n      auto equations = p.slsetndd_parser(input_all);\n      if (equations.empty()) return EXIT_FAILURE;\n      std::cout << result_string(\n          call_solver(solver_name, equations, scc_flag, iter_flag, iterations, graph_flag)\n          ) << std::endl;\n      SemilinSetNdd::solver_dealloc();\n#endif\n  } else if (vm.count(\"mlset\")) {\n\n    auto equations_raw = p.free_parser(input_all);\n    auto equations = MakeCommEquationsAndMap(equations_raw, [](const FreeSemiring &c) -> SemilinSetExp {\n      auto srconv = SRConverter<SemilinSetExp>();\n      return c.Eval(srconv);\n    });\n\n    if (equations.empty()) return EXIT_FAILURE;\n    if (vm.count(\"vec-simpl\")) {\n      auto m_equations = SemilinearToPseudoLinearEquations<\n        DummyDivider, SparseVecSimplifier>(equations);\n      //PrintEquations(m_equations);\n      std::cout << result_string(\n          call_solver(solver_name, equations, scc_flag, iter_flag, iterations, graph_flag)\n          ) << std::endl;\n    } else {\n      auto m_equations = SemilinearToPseudoLinearEquations<\n        DummyDivider, DummyVecSimplifier>(equations);\n      //PrintEquations(m_equations);\n      std::cout << result_string(\n          call_solver(solver_name, equations, scc_flag, iter_flag, iterations, graph_flag)\n          ) << std::endl;\n    }\n\n  } else if (vm.count(\"rexp\")) {\n\n    // parse the input into a list of (Var → Polynomial[SR])\n    auto equations = p.rexp_parser(input_all);\n    if (equations.empty()) return EXIT_FAILURE;\n\n    //PrintEquations(equations);\n\n    // apply solver to the equations\n    std::cout << result_string(\n        call_solver(solver_name, equations, scc_flag, iter_flag, iterations, graph_flag)\n        ) << std::endl;\n\n  } else if (vm.count(\"free\")) {\n\n    // parse the input into a list of (Var → Polynomial[SR])\n\tauto equations = p.free_parser(input_all);\n  //auto equations2 = MakeCommEquations(equations);\n  //if (equations2.empty()) return EXIT_FAILURE;\n\n//    std::cout << result_string(\n//        call_solver(solver_name, equations2, scc_flag, iter_flag, iterations, graph_flag)\n//        ) << std::endl;\n#ifdef USE_LIBFA\n  } else if (vm.count(\"lossy\")) {\n\n    auto equations = p.free_parser(input_all);\n    if (equations.empty()) return EXIT_FAILURE;\n\n    //PrintEquations(equations);\n    auto equations2 = MapEquations(equations, [](const FreeSemiring &c) -> LossyFiniteAutomaton {\n      auto srconv = SRConverter<LossyFiniteAutomaton>();\n      return c.Eval(srconv);\n    });\n\n    VarId S_1 = equations2[0].first;\n\n    NCEquationsBase<LossyFiniteAutomaton> eq2 = NCEquationsBase<LossyFiniteAutomaton>(equations2.begin(), equations2.end());\n\n    auto approximation = NonCommutativePolynomial<LossyFiniteAutomaton>::downwardClosureCourcelle(eq2, S_1);\n    std::cout << \"dwc:\\t\" << approximation.string() << std::endl;\n    std::cout << \"size NFA for DWC:\\t\" << approximation.size() << std::endl;\n    std::cout << \"size minimal DFA for DWC:\\t\" << approximation.minimize().size() << std::endl;\n#endif\n  } else if (vm.count(\"prefix\")) {\n\n    // parse the input into a list of (Var → Polynomial[SR])\n    auto equations = p.prefix_parser(input_all, vm[\"prefix\"].as<int>());\n    if (equations.empty()) return EXIT_FAILURE;\n\n    //PrintEquations(equations);\n\n    // apply the newton method to the equations\n    //auto result = apply_solver<Kleene, PrefixSemiring>(equations,\n    //                                           vm.count(\"scc\"),\n    //                                           vm.count(\"iterations\"),\n    //                                           iterations,\n    //                                           vm.count(\"graphviz\"));\n    //std::cout << result_string(result) << std::endl;\n\n    //std::cout << result_string(\n    //    call_solver(solver_name, equations, scc_flag, iter_flag, iterations, graph_flag)\n    //    ) << std::endl;\n\n  } else if (vm.count(\"float\")) {\n    auto equations = p.free_parser(input_all);\n    //PrintEquations(equations);\n    auto equations2 = MakeCommEquationsAndMap(equations, [](const FreeSemiring &c) -> FloatSemiring {\n      auto srconv = SRConverter<FloatSemiring>();\n      return c.Eval(srconv);\n    });\n\n    if (equations2.empty()) return EXIT_FAILURE;\n\n    //PrintEquations(equations);\n    //PrintEquations(equations2);\n\n    if(0 == solver_name.compare(\"newtonNumeric\")) {\n      std::cout << \"Solver: Newton Numeric (Float)\"<< std::endl;\n      std::cout << result_string(\n          apply_solver<NewtonNumeric>(equations2, scc_flag, iter_flag, iterations, graph_flag)\n          ) << std::endl;\n    } else  {\n      std::cout << result_string(\n          call_solver(solver_name, equations2, scc_flag, iter_flag, iterations, graph_flag)\n          ) << std::endl;\n    }\n\n\n  } else if (vm.count(\"bool\")) {\n    auto equations = p.free_parser(input_all);\n    auto equations2 = MakeCommEquationsAndMap(equations, [](const FreeSemiring &c) -> BoolSemiring {\n      auto srconv = SRConverter<BoolSemiring>();\n      return c.Eval(srconv);\n    });\n\n    if (equations2.empty()) return EXIT_FAILURE;\n\n    PrintEquations(equations);\n    PrintEquations(equations2);\n      std::cout << result_string(\n          call_solver(solver_name, equations2, scc_flag, iter_flag, iterations, graph_flag)\n          ) << std::endl;\n\n  } else if (vm.count(\"rat\")) {\n    auto equations = p.free_parser(input_all);\n    auto equations2 = MakeCommEquationsAndMap(equations, [](const FreeSemiring &c) -> PrecRatSemiring {\n      auto srconv = SRConverter<PrecRatSemiring>();\n      return c.Eval(srconv);\n    });\n\n    if (equations2.empty()) return EXIT_FAILURE;\n\n    //PrintEquations(equations);\n    //PrintEquations(equations2);\n\n    if(0 == solver_name.compare(\"newtonNumeric\")) {\n      std::cout << \"Solver: Newton Numeric (Rat)\"<< std::endl;\n      std::cout << result_string(\n          apply_solver<NewtonNumeric>(equations2, scc_flag, iter_flag, iterations, graph_flag)\n          ) << std::endl;\n    } else  {\n      std::cout << result_string(\n          call_solver(solver_name, equations2, scc_flag, iter_flag, iterations, graph_flag)\n          ) << std::endl;\n    }\n  }\n  else if (vm.count(\"why\")) {\n      auto equations = p.free_parser(input_all);\n      auto equations2 = MakeCommEquationsAndMap(equations, [](const FreeSemiring &c) -> WhySemiring {\n        auto srconv = SRConverter<WhySemiring>();\n        return c.Eval(srconv);\n      });\n\n      if (equations2.empty()) return EXIT_FAILURE;\n\n        std::cout << result_string(\n            call_solver(solver_name, equations2, scc_flag, iter_flag, iterations, graph_flag)\n            ) << std::endl;\n\n    }\n    else if (vm.count(\"tropical\")) {\n      auto equations = p.free_parser(input_all);\n      auto equations2 = MakeCommEquationsAndMap(equations, [](const FreeSemiring &c) -> TropicalSemiring {\n        auto srconv = SRConverter<TropicalSemiring>();\n        return c.Eval(srconv);\n      });\n\n      if (equations2.empty()) return EXIT_FAILURE;\n\n        std::cout << result_string(\n            call_solver(solver_name, equations2, scc_flag, iter_flag, iterations, graph_flag)\n            ) << std::endl;\n\n    }\n    else if (vm.count(\"viterbi\")) {\n          auto equations = p.free_parser(input_all);\n          auto equations2 = MakeCommEquationsAndMap(equations, [](const FreeSemiring &c) -> ViterbiSemiring {\n            auto srconv = SRConverter<ViterbiSemiring>();\n            return c.Eval(srconv);\n          });\n\n          if (equations2.empty()) return EXIT_FAILURE;\n\n            std::cout << result_string(\n                call_solver(solver_name, equations2, scc_flag, iter_flag, iterations, graph_flag)\n                ) << std::endl;\n    }\n    else if (vm.count(\"maxmin\")) {\n          auto equations = p.free_parser(input_all);\n          auto equations2 = MakeCommEquationsAndMap(equations, [](const FreeSemiring &c) -> MaxMinSemiring {\n            auto srconv = SRConverter<MaxMinSemiring>();\n            return c.Eval(srconv);\n          });\n\n          if (equations2.empty()) return EXIT_FAILURE;\n\n            std::cout << result_string(\n                call_solver(solver_name, equations2, scc_flag, iter_flag, iterations, graph_flag)\n                ) << std::endl;\n\n    }\n\n#ifdef USE_GENEPI\n  SemilinSetNdd::genepi_dealloc();\n#endif\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "fc0164fbc530852105085ef44dfd4c8f62881dbd", "size": 17468, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c/src/main.cpp", "max_stars_repo_name": "mschlund/FPsolve", "max_stars_repo_head_hexsha": "4b8fbe87ed4eeac8a53e191aa34c5aa80b6e0490", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2015-01-17T23:30:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-13T20:42:54.000Z", "max_issues_repo_path": "c/src/main.cpp", "max_issues_repo_name": "mschlund/FPsolve", "max_issues_repo_head_hexsha": "4b8fbe87ed4eeac8a53e191aa34c5aa80b6e0490", "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": "c/src/main.cpp", "max_forks_repo_name": "mschlund/FPsolve", "max_forks_repo_head_hexsha": "4b8fbe87ed4eeac8a53e191aa34c5aa80b6e0490", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-02-21T11:13:38.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-11T03:50:09.000Z", "avg_line_length": 36.4676409186, "max_line_length": 198, "alphanum_fraction": 0.6352186856, "num_tokens": 4667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056040203136, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.29914585573027175}}
{"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#ifndef MTL_DOT_INCLUDE\n#define MTL_DOT_INCLUDE\n\n\n#include <boost/numeric/mtl/concept/std_concept.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/operation/conj.hpp>\n#include <boost/numeric/meta_math/loop1.hpp>\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n#include <boost/numeric/mtl/utility/omp_size_type.hpp>\n#include <boost/numeric/mtl/utility/static_assert.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n\nnamespace mtl { \n\n    namespace vector {\n\n\tnamespace detail {\n\t    \n\t    // Result type of dot product\n\t    template <typename Vector1, typename Vector2>\n\t    struct dot_result\n\t    {\n\t\ttypedef typename Multiplicable<typename Collection<Vector1>::value_type,\n\t\t\t\t\t       typename Collection<Vector2>::value_type>::result_type type;\n\t    };\n\n\t    // Whether or not conjugating first argument\n\t    struct without_conj\n\t    {\n\t\ttemplate <typename Value>\n\t\tValue operator()(const Value& v) { return v; }\n\t    };\n\n\t    struct with_conj\n\t    {\n\t\ttemplate <typename Value>\n\t\ttypename mtl::sfunctor::conj<Value>::result_type\n\t\toperator() (const Value& v)\n\t\t{\n\t\t    using mtl::conj;\n\t\t    return conj(v);\n\t\t}\n\t    };\n\t}\n\n\tnamespace sfunctor {\n\t    \n\t    template <unsigned long Index0, unsigned long Max0>\n\t    struct dot_aux\n\t\t: public meta_math::loop1<Index0, Max0>\n\t    {\n\t\ttypedef meta_math::loop1<Index0, Max0>                                    base;\n\t\ttypedef dot_aux<base::next_index0, Max0>                                  next_t;\n\t\t\n\t\ttemplate <typename Value, typename Vector1, typename Vector2, typename Size, typename ConjOpt>\n\t\tstatic inline void \n\t\tapply(Value& tmp00, Value& tmp01, Value& tmp02, Value& tmp03, Value& tmp04, \n\t\t      Value& tmp05, Value& tmp06, Value& tmp07, \n\t\t      const Vector1& v1, const Vector2& v2, Size i, ConjOpt conj_opt)\n\t\t{\n\t\t    // vampir_trace<9901> tracer;\n\t\t    tmp00+= conj_opt(v1[ i + base::index0 ]) * v2[ i + base::index0 ];\n\t\t    next_t::apply(tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07, tmp00,\n\t\t\t\t  v1, v2, i, conj_opt);\n\t\t}\n\t    };\n\n\n\t    template <unsigned long Max0>\n\t    struct dot_aux<Max0, Max0>\n\t    {\n\t\ttypedef meta_math::loop1<Max0, Max0>                                      base;\n\t\t\n\t\ttemplate <typename Value, typename Vector1, typename Vector2, typename Size, typename ConjOpt>\n\t\tstatic inline void \n\t\tapply(Value& tmp00, Value&, Value&, Value&, Value&, Value&, Value&, Value&, \n\t\t      const Vector1& v1, const Vector2& v2, Size i, ConjOpt conj_opt)\n\t\t{\n\t\t    tmp00+= conj_opt(v1[ i + base::index0 ]) * v2[ i + base::index0 ];\n\t\t}\n\t    };\n\n\n\t    template <unsigned long Unroll>\n\t    struct dot\n\t    {\n\t\ttemplate <typename Vector1, typename Vector2, typename ConjOpt>\n\t\ttypename detail::dot_result<Vector1, Vector2>::type\n\t\tstatic inline apply(const Vector1& v1, const Vector2& v2, ConjOpt conj_opt)\n\t\t{\n\t\t    MTL_STATIC_ASSERT((Unroll >= 1), \"Unroll size must be at least 1.\");\n\t\t    // MTL_STATIC_ASSERT((Unroll <= 8), \"Maximal unrolling is 8.\"); // Might be relaxed in future versions\n\n\t\t    vampir_trace<2003> tracer;\n\t\t    MTL_THROW_IF(mtl::size(v1) != mtl::size(v2), incompatible_size());\n\t\t    typedef typename detail::dot_result<Vector1, Vector2>::type  value_type;\n\t\t    \t\t    \n#                 ifdef MTL_WITH_OPENMP \n\t\t    value_type dummy, z= math::zero(dummy), result= z;\n\t\t    typedef typename mtl::traits::omp_size_type<typename Collection<Vector1>::size_type>::type size_type;\n\t\t    size_type  i_max= mtl::size(v1), i_block= Unroll * (i_max / Unroll);\n\n\n                    #pragma omp parallel\n\t\t    {\n\n\t\t\tvampir_trace<8001> tracer;\n\t\t\tvalue_type tmp00= z, tmp01= z, tmp02= z, tmp03= z, tmp04= z, tmp05= z, tmp06= z, tmp07= z;\n\n\t\t\t#pragma omp for\n\t\t\tfor (size_type i= 0; i < i_block; i+= Unroll)\n\t\t\t    dot_aux<1, Unroll>::apply(tmp00, tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07, v1, v2, i, conj_opt);\n\n\t\t\t#pragma omp critical\n\t\t\t    result+= ((tmp00 + tmp01) + (tmp02 + tmp03)) + ((tmp04 + tmp05) + (tmp06 + tmp07));\n\t\t    }\n\t\t    for (size_type i= i_block; i < i_max; i++) \n\t\t\tresult+= conj_opt(v1[i]) * v2[i];\n\n\t\t    return result;\n#                 else\n\t\t    typedef typename Collection<Vector1>::size_type              size_type;\n\n\t\t    value_type dummy, z= math::zero(dummy), tmp00= z, tmp01= z, tmp02= z, tmp03= z, tmp04= z,\n\t\t\t       tmp05= z, tmp06= z, tmp07= z;\n\t\t    size_type  i_max= mtl::size(v1), i_block= Unroll * (i_max / Unroll);\n\t\t    \n\t\t    for (size_type i= 0; i < i_block; i+= Unroll)\n\t\t\tdot_aux<1, Unroll>::apply(tmp00, tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07, v1, v2, i, conj_opt);\n\t\t    \n\t\t    for (size_type i= i_block; i < i_max; i++) \n\t\t\ttmp00+= conj_opt(v1[i]) * v2[i];\n\t\t    return ((tmp00 + tmp01) + (tmp02 + tmp03)) + ((tmp04 + tmp05) + (tmp06 + tmp07));\n#                 endif\n\t\t}\n\n\n\t    };\n\t}\n\n\ttemplate <typename Vector1, typename Vector2, typename ConjOpt>\n\ttypename detail::dot_result<Vector1, Vector2>::type\n\tinline dot_simple(const Vector1& v1, const Vector2& v2, ConjOpt conj_opt)\n\t{\n\t    vampir_trace<2040> tracer;\n\t    typedef typename Collection<Vector1>::size_type              size_type;\n\t    typedef typename detail::dot_result<Vector1, Vector2>::type  value_type;\n\n\t    value_type dummy, s= math::zero(dummy);\n\t    for (size_type i= 0, i_max= mtl::size(v1); i < i_max; ++i)\n\t\ts+= conj_opt(v1[i]) * v2[i];\n\t    return s;\n\t}\n\n\ttemplate <unsigned long Unroll, typename Vector1, typename Vector2, typename ConjOpt>\n\tstruct dot_class\n\t{\n\t    typedef typename detail::dot_result<Vector1, Vector2>::type result_type;\n\t    dot_class(const Vector1& v1, const Vector2& v2) : v1(v1), v2(v2) {}\n\n\t    operator result_type() const { return sfunctor::dot<Unroll>::apply(v1, v2, ConjOpt()); }\n\t    \n\t    const Vector1& v1;\n\t    const Vector2& v2;\n\t};\n\n\ttemplate <typename Vector1, typename Vector2, typename ConjOpt>\n\tstruct dot_class<1, Vector1, Vector2, ConjOpt>\n\t{\n\t    typedef typename detail::dot_result<Vector1, Vector2>::type result_type;\n\t    dot_class(const Vector1& v1, const Vector2& v2) : v1(v1), v2(v2) {}\n\n\t    operator result_type() const { return dot_simple(v1, v2, ConjOpt()); }\n\t    \n\t    const Vector1& v1;\n\t    const Vector2& v2;\n\t};\n\t\n\t/// Lazy dot product\n\t/** It is automatically evaluated when (implicitly) converted to result_type which doesn't work in template expressions.\n\t    Can be used for source-to-source transformations. **/\n\ttemplate <typename Vector1, typename Vector2>\n\tdot_class<4, Vector1, Vector2, detail::with_conj>\n\tinline lazy_dot(const Vector1& v1, const Vector2& v2)\n\t{\n\t    return dot_class<4, Vector1, Vector2, detail::with_conj>(v1, v2);\n\t}\n\n\ttemplate <unsigned long Unroll, typename Vector1, typename Vector2>\n\tdot_class<Unroll, Vector1, Vector2, detail::with_conj>\n\tinline lazy_dot(const Vector1& v1, const Vector2& v2)\n\t{\n\t    return dot_class<Unroll, Vector1, Vector2, detail::with_conj>(v1, v2);\n\t}\n\n\ttemplate <typename Vector1, typename Vector2>\n\tdot_class<4, Vector1, Vector2, detail::without_conj>\n\tinline lazy_dot_real(const Vector1& v1, const Vector2& v2)\n\t{\n\t    return dot_class<4, Vector1, Vector2, detail::without_conj>(v1, v2);\n\t}\n\n\ttemplate <unsigned long Unroll, typename Vector1, typename Vector2>\n\tdot_class<Unroll, Vector1, Vector2, detail::without_conj>\n\tinline lazy_dot_real(const Vector1& v1, const Vector2& v2)\n\t{\n\t    return dot_class<Unroll, Vector1, Vector2, detail::without_conj>(v1, v2);\n\t}\n\n\t/// Dot product defined as hermitian(v) * w\n\t/** Unrolled four times by default **/\n\ttemplate <typename Vector1, typename Vector2>\n\ttypename detail::dot_result<Vector1, Vector2>::type\n\tinline dot(const Vector1& v1, const Vector2& v2)\n\t{\n\t    // return dot_simple(v1, v2, detail::with_conj());\n\t    return sfunctor::dot<4>::apply(v1, v2, detail::with_conj());\n\t}\n\n\t/// Dot product with user-specified unrolling defined as hermitian(v) * w\n\ttemplate <unsigned long Unroll, typename Vector1, typename Vector2>\n\ttypename detail::dot_result<Vector1, Vector2>::type\n\tinline dot(const Vector1& v1, const Vector2& v2)\n\t{\n\t    return sfunctor::dot<Unroll>::apply(v1, v2, detail::with_conj());\n\t}\n\t/// Dot product without conjugate defined as trans(v) * w\n\t/** Unrolled four times by default **/\n\ttemplate <typename Vector1, typename Vector2>\n\ttypename detail::dot_result<Vector1, Vector2>::type\n\tinline dot_real(const Vector1& v1, const Vector2& v2)\n\t{\n\t    return sfunctor::dot<4>::apply(v1, v2, detail::without_conj());\n\t}\n\n\t/// Dot product without conjugate with user-specified unrolling defined as trans(v) * w\n\ttemplate <unsigned long Unroll, typename Vector1, typename Vector2>\n\ttypename detail::dot_result<Vector1, Vector2>::type\n\tinline dot_real(const Vector1& v1, const Vector2& v2)\n\t{\n\t    return sfunctor::dot<Unroll>::apply(v1, v2, detail::without_conj());\n\t}\n\n\n    } // namespace vector\n    \n    using vector::dot;\n    using vector::dot_real;\n    using vector::lazy_dot;\n    using vector::lazy_dot_real;\n\n} // namespace mtl\n\n#endif // MTL_DOT_INCLUDE\n", "meta": {"hexsha": "029cfa4a2b700f5f0db546e365d4df4ec2163f86", "size": 9407, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/operation/dot.hpp", "max_stars_repo_name": "spraetor/amdis2", "max_stars_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T16:44:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T07:26:27.000Z", "max_issues_repo_path": "lib/mtl4/boost/numeric/mtl/operation/dot.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/mtl4/boost/numeric/mtl/operation/dot.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.970260223, "max_line_length": 121, "alphanum_fraction": 0.6680131817, "num_tokens": 2693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.29907843659445144}}
{"text": "#include <iostream>\n#include <vector>\n#include <fstream>\n#include <utility>\n#include <iterator>\n#include <cstdlib>\n#include <string>\n#include <limits>\n#include <cerrno>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/concept_check.hpp>\n#include <boost/operators.hpp>\n#include <boost/iterator.hpp>\n#include <boost/multi_array.hpp>\n#include <boost/random.hpp>\n#include <sys/time.h>\n#include \"../src/edmonds_optimum_branching.hpp\"\n#include \"boost/tuple/tuple.hpp\"\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/io.hpp>\nusing boost::tuple;\nusing namespace std;\nusing namespace boost;\n\n#ifdef DEBUG\n#define DEBUG_MSG(str) do { std::cout << str << std::endl; } while( false )\n#else\n#define DEBUG_MSG(str) do { } while ( false )\n#endif\n\n// definitions of a complete graph that implements the EdgeListGraph\n// concept of Boost's graph library.\nnamespace boost {\n\tstruct complete_graph {\n\t\tcomplete_graph(int n_vertices) : n_vertices(n_vertices) {}\n\t\tint n_vertices;\n\t\t\n\t\tstruct edge_iterator : public input_iterator_helper<edge_iterator, int, std::ptrdiff_t, int const *, int>\n\t\t{\n\t\t\tint edge_idx, n_vertices;\n\t\t\tedge_iterator() : edge_idx(0), n_vertices(-1) {}\n\t\t\tedge_iterator(int n_vertices, int edge_idx) : edge_idx(edge_idx), n_vertices(n_vertices) {}\n\t\t\tedge_iterator &operator++()\n\t\t\t{\n\t\t\t\tif (edge_idx >= n_vertices * n_vertices)\n\t\t\t\t\treturn *this;\n\t\t\t\t++edge_idx;\n\t\t\t\tif (edge_idx / n_vertices == edge_idx % n_vertices)\n\t\t\t\t\t++edge_idx;\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tint operator*() const {return edge_idx;}\n\t\t\tbool operator==(const edge_iterator &iter) const\n\t\t\t{\n\t\t\t\treturn edge_idx == iter.edge_idx;\n\t\t\t}\n\t\t};\n\t};\n\t\n\ttemplate<>\n\tstruct graph_traits<complete_graph> {\n\t\ttypedef int                             vertex_descriptor;\n\t\ttypedef int                             edge_descriptor;\n\t\ttypedef directed_tag                    directed_category;\n\t\ttypedef disallow_parallel_edge_tag      edge_parallel_category;\n\t\ttypedef edge_list_graph_tag             traversal_category;\n\t\ttypedef complete_graph::edge_iterator   edge_iterator;\n\t\ttypedef unsigned                        edges_size_type;\n\t\t\n\t\tstatic vertex_descriptor null_vertex() {return -1;}\n\t};\n\n\tpair<complete_graph::edge_iterator, complete_graph::edge_iterator>\n\tedges(const complete_graph &g)\n\t{\n\t\treturn make_pair(complete_graph::edge_iterator(g.n_vertices, 1),\n\t\t\t\t\t\t complete_graph::edge_iterator(g.n_vertices, g.n_vertices*g.n_vertices));\n\t}\n\t\n\tunsigned\n\tnum_edges(const complete_graph &g)\n\t{\n\t\treturn (g.n_vertices - 1) * (g.n_vertices - 1);\n\t}\n\t\n\tint\n\tsource(int edge, const complete_graph &g)\n\t{\n\t\treturn edge / g.n_vertices;\n\t}\n\t\n\tint\n\ttarget(int edge, const complete_graph &g)\n\t{\n\t\treturn edge % g.n_vertices;\n\t}\n}\n\ntypedef graph_traits<complete_graph>::edge_descriptor Edge;\ntypedef graph_traits<complete_graph>::vertex_descriptor Vertex;\n\n\nint dirMST(string fin,string fout,string mode)\n{\n\tint n_vertices;\n\tvector< tuple<int,int,float> > edge_list;\n\ttuple<int,int,float> g_edge;\n\n\tstring line;\n\tint v1,v2,ctr = 0;\n\tfloat weight;\n\tifstream inputf (fin.c_str());\n\tfloat* nodeWeights = NULL;\n\tif(inputf.is_open())\n\t{\n\t\tgetline(inputf,line);\n\t\tsscanf(line.c_str(),\"%d\",&n_vertices);\n\t\tnodeWeights = new float[n_vertices];\n\t\tint ctr = 0;\n\t\twhile(getline(inputf,line))\n\t\t{\n\t\t\tif(ctr<n_vertices)\n\t\t\t{\n\t\t\t\tsscanf(line.c_str(),\"%f\",&nodeWeights[ctr]);\n\t\t\t\tDEBUG_MSG(\"v|\"<<ctr+1<<\"|:\"<<nodeWeights[ctr]);\n\t\t\t\tctr++;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsscanf (line.c_str(),\"%d,%d,%f\",&v1,&v2,&weight);\n\t\t\t\t//Assumes vertices start from 0...N-1\n\t\t\t\tedge_list.push_back(make_tuple(v1,v2,weight));\n\t\t\t}\n\t\t}\n\t\tinputf.close();\n\t}\n\telse\n\t{\n\t\tcerr<<\"Input file not found. Cannot be opened\\n\";\n\t\texit(1);\n\t}\n\t\n\t//Read in the edgelist and set the weights to their values, all other weights will\n\t//be -Inf\n\t//2 dimensional array of integer weights -Converting to float, make sure ok\n\n\t//Build a complete graph on n vertices (hack)\n\t//TODO: Fix to build it based on the graph structure\n\tcomplete_graph g(n_vertices);\n\tmulti_array<float, 2> weights(extents[n_vertices][n_vertices]);\n\tvector<Vertex> parent(n_vertices);\n\t//Vertex roots[] = {0, 1};\n\tVertex* roots = new Vertex[n_vertices];\n\tfor(int vi = 0;vi<n_vertices;vi++)\n\t\troots[vi]=vi;\n\t\t\n\tvector<Edge> branching;\n\t//Initialize all weights to 0\n\tfor(int i=0;i<n_vertices;i++)\n\t{\n\t\tfor(int j=0;j<n_vertices;j++)\n\t\t{   \n\t\t\t//If using Minimum Spanning Tree\n\t\t\tif(mode.compare(\"min\")==0)\n\t\t\t\tweights[i][j] = numeric_limits<int>::max();\n\t\t\telse//Maximum spanning tree\n\t\t\t\tweights[i][j] = numeric_limits<int>::min();\n\t\t}\n\t}\n\n\t//Write out the indices of the edge set that form the directed spanning tree\n\tnumeric::ublas::mapped_matrix<int> index_map (n_vertices,n_vertices);\n\tDEBUG_MSG(\"---Graph Read---\\nN: \"<<n_vertices);\n\tBOOST_FOREACH(g_edge,edge_list)\n\t{\n\t\tv1 = get<0>(g_edge);\n\t\tv2 = get<1>(g_edge);\n\t\tweight=get<2>(g_edge);\n\t\tDEBUG_MSG(v1<<\" | \"<<v2<<\" | \"<<weight);\n\t\tweights[v1][v2] = weight;\n\t\tindex_map(v1,v2) = ctr++;\n\t}\n\tbool isMax = true;\n\tif(mode.compare(\"min\")==0)\n\t{\n\t\tisMax = false;\n\t\t//TOptimum isMaximum set to false -> MinST\n\t\t//TOptimum isMaximum set to true -> MaxST\n\t}\n\tvector< vector< Edge > > rooted_branching(n_vertices);\n\n\tdouble optVal = numeric_limits<int>::max();\n\tif(isMax)\t\n\t\toptVal = numeric_limits<int>::min();\n\tint optRoot= -1;\n\tdouble branchingWeight;\n\tfor(int vi=0;vi<n_vertices;vi++)\n\t{\n\t\t//Compute rooted branching\n\t\tif(isMax)\n\t\t{\n\t\t\tedmonds_optimum_branching<true, true, true>\n\t\t\t(g, identity_property_map(), weights.origin(),\n\t\t\t roots+vi, roots + vi+1, back_inserter(rooted_branching[vi]));\n\t\t}\n\t\telse\n\t\t{\n\t\tedmonds_optimum_branching<false, true, true>\n\t\t\t(g, identity_property_map(), weights.origin(),\n\t\t\t roots+vi, roots + vi+1, back_inserter(rooted_branching[vi]));\n\t\t}\n\t\t//Track the weight of the branching\t\n\t\tbranchingWeight = nodeWeights[vi];\n\t\tBOOST_FOREACH(Edge e,rooted_branching[vi])\n\t\t{\n\t\t\tbranchingWeight += weights[source(e, g)][target(e, g)];\n\t\t}\n\t\t//Track the max/min branching weight\n\t\tif(isMax && branchingWeight>optVal)\t\n\t\t{\n\t\t\toptVal = branchingWeight;\n\t\t\toptRoot = vi;\n\t\t}\n\t\tif(!isMax && branchingWeight<optVal)\n\t\t{\n\t\t\toptVal = branchingWeight;\n\t\t\toptRoot = vi;\n\t\t}\n\t}\n\t\n\t//Write result to file\n\tDEBUG_MSG(\"--Optimal (\"<<mode<<\") Branching--\");\n\tofstream outf(fout.c_str());\n\tif(outf==NULL)\n\t{\n\t\tcerr<<\"Output file not created.\"<<endl;\n\t\texit(1);\n\t}\n\tBOOST_FOREACH(Edge e ,rooted_branching[optRoot])\n\t{\n\t\tv1 =source(e, g);\n\t\tv2 =target(e, g);\n\t\tctr = index_map(v1,v2);\n\n\t\tDEBUG_MSG(v1<<\"->\"<<v2<<\" idx:\"<<ctr);\n\t\toutf<<ctr<<endl;\n\t} \n\tdelete roots;\n\tdelete nodeWeights;\t\n\treturn EXIT_SUCCESS;\n\n}\nstring PNAME = \"mstwrapper\";\nint main(int argc, char *argv[])\n{\n\tif (argc != 4)\n\t{\n\t\tcerr << \"Usage: \" << PNAME\n\t\t\t << \" <input file name> <output file name> <min|max>\\n\";\n\t\texit(1);\n\t}\n\tstring mode = string(argv[3]);\n\tif(mode.compare(\"min\")==0 || mode.compare(\"max\")==0)//strcmp(argv[3],\"min\")==0 || strcmp(argv[3],\"max\"){\n\t{\n\t\treturn dirMST(argv[1],argv[2],mode);\n\t}\n\telse\n\t{\n\t\tcerr<<\"Final argument not <min> or <max>\"<<endl;\n\t\texit(1);\n\t}\n\t\n}\n", "meta": {"hexsha": "c412edc77cddc055d3cef2109c9127724f377110", "size": 7114, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mstwrapper_rooted.cpp", "max_stars_repo_name": "rahulk90/dir_rooted_mst_wrapper", "max_stars_repo_head_hexsha": "ece3c5396b74f52bd188a0cd87efe3b4466f91fa", "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": "mstwrapper_rooted.cpp", "max_issues_repo_name": "rahulk90/dir_rooted_mst_wrapper", "max_issues_repo_head_hexsha": "ece3c5396b74f52bd188a0cd87efe3b4466f91fa", "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": "mstwrapper_rooted.cpp", "max_forks_repo_name": "rahulk90/dir_rooted_mst_wrapper", "max_forks_repo_head_hexsha": "ece3c5396b74f52bd188a0cd87efe3b4466f91fa", "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.7753623188, "max_line_length": 107, "alphanum_fraction": 0.6727579421, "num_tokens": 1995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.2990784365944514}}
{"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\nconstexpr double deg_to_rad(double deg) {\n\treturn PI * deg / 180.0;\n}\n\nconstexpr double rad_to_deg(double rad) {\n\treturn rad * 180 / PI;\n}\n\n// 二次元ベクトルクラス\nclass Vec2d {\n\tdouble _x;\n\tdouble _y;\n\n\tpublic:\n\t// 原点の位置ベクトル\n\tstatic Vec2d origin() { return Vec2d(0.0, 0.0); }\n\n\t// ゼロベクトル\n\tstatic Vec2d zero() { return Vec2d::origin(); }\n\n\tVec2d(double a, double b) : _x(a), _y(b) {}\n\n\tdouble x() const { return this->_x; }\n\tdouble y() const { return this->_y; }\n\n\t// 外積\n\tdouble det(const Vec2d& rhs) const {\n\t\treturn this->x() * rhs.y() - this->y() * rhs.x();\n\t}\n\n\t// 内積\n\tdouble dot(const Vec2d& rhs) const {\n\t\treturn this->x() * rhs.x() + this->y() * rhs.y();\n\t}\n\n\t// 長さ\n\tdouble length() const { return this->distance(Vec2d::origin()); }\n\n\t// 2つの位置ベクトル間のユークリッド距離\n\tdouble distance(const Vec2d& rhs) const {\n\t\treturn std::sqrt(square(this->x() - rhs.x()) +\n\t\t\t\t\t\t square(this->y() - rhs.y()));\n\t}\n\n\t// 2つの位置ベクトル間のマンハッタン距離\n\tdouble manhattan_distance(const Vec2d& rhs) const {\n\t\treturn std::abs(this->x() - rhs.x()) + std::abs(this->y() - rhs.y());\n\t}\n\n\t// ベクトルとx軸のなす角\n\tdouble argument() const { return std::atan2(this->y(), this->x()); }\n\n\t// 反時計回りに回転したベクトル\n\tVec2d rotate(double rad) const {\n\t\tdouble xx = this->x();\n\t\tdouble yy = this->y();\n\t\treturn Vec2d(xx * cos(rad) - yy * sin(rad),\n\t\t\t\t\t xx * sin(rad) + yy * cos(rad));\n\t}\n\n\t// 単位ベクトル\n\tVec2d unit() const {\n\t\tdouble len = this->length();\n\t\treturn Vec2d(this->x() / len, this->y() / len);\n\t}\n\n\t// 法線ベクトル\n\tVec2d normal() const {\n\t\tdouble len = this->length();\n\t\treturn Vec2d(this->y() / len, -this->x() / len);\n\t}\n\n\t// 平行判定\n\tbool is_parallel(const Vec2d& rhs) const { return false; }\n\n\t// ベクトル和\n\tVec2d operator+() const { return *this; }\n\tVec2d operator+(const Vec2d& rhs) const {\n\t\treturn Vec2d(this->x() + rhs.x(), this->y() + rhs.y());\n\t}\n\n\t// ベクトル差\n\tVec2d operator-() const { return Vec2d(-this->x(), -this->y()); }\n\tVec2d operator-(const Vec2d& rhs) const {\n\t\treturn Vec2d(this->x() - rhs.x(), this->y() - rhs.y());\n\t}\n\n\t// スカラー積\n\tVec2d operator*(const double rhs) const {\n\t\treturn Vec2d(this->x() * rhs, this->y() * rhs);\n\t}\n\tVec2d operator/(const double rhs) const {\n\t\treturn Vec2d(this->x() / rhs, this->y() / rhs);\n\t}\n\n\tbool operator<(const Vec2d& rhs) const {\n\t\treturn sign(this->x()) ? this->y() < rhs.y() : this->x() < rhs.x();\n\t}\n\n\tprivate:\n};\n\nint main() {\n\tint n, x0, y0, xharf, yharf;\n\tcin >> n;\n\tcin >> x0 >> y0;\n\tcin >> xharf >> yharf;\n\n\tVec2d p0 = {x0, y0};\n\tVec2d ph = {xharf, yharf};\n\n\tVec2d center = (p0 + ph) / 2;\n\tVec2d c_to_p0 = p0 - center;\n\tVec2d c_to_pr = c_to_p0.rotate(PI * 2 / n);\n\tVec2d result = center + c_to_pr;\n\n\tcout << PRECISION(15) << result.x() << \" \" << result.y() << endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "a8630a3f940764d4ac696bb003411f977f47f141", "size": 5274, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/ABC197/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/ABC197/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/ABC197/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": 23.0305676856, "max_line_length": 76, "alphanum_fraction": 0.6230565036, "num_tokens": 1828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.299044887348973}}
{"text": "#include \"MapsMesh.h\"\n\n#include <igl/gaussian_curvature.h>\n#include <poly2tri.h>\n#include <tbb/tbb.h>\n\n#include <Eigen/Dense>\n#include <algorithm>\n#include <limits>\n#include <progressbar/progressbar.hpp>\n\nnamespace Maps {\n\ntemplate <class Mesh>\nstatic void OpenMesh2IGL(const Mesh *mesh, Eigen::MatrixX3d &V, Eigen::MatrixX3i &F) {\n\n    assert(mesh->is_trimesh());\n\n    auto verticesCount = std::distance(mesh->vertices_sbegin(), mesh->vertices_end());\n    auto facesCount = std::distance(mesh->faces_sbegin(), mesh->faces_end());\n    V.resize(verticesCount, 3);\n    F.resize(facesCount, 3);\n\n    std::map<typename Mesh::VertexHandle, int> newVertexHandleMap;\n    int j = 0;\n    for (auto i = mesh->vertices_sbegin(); i != mesh->vertices_end(); i++, j++) {\n        auto p = mesh->point(*i);\n        V(j, 0) = p[0];\n        V(j, 1) = p[1];\n        V(j, 2) = p[2];\n        newVertexHandleMap[*i] = j;\n    }\n\n    j = 0;\n    for (auto i = mesh->faces_sbegin(); i != mesh->faces_end(); i++, j++) {\n        auto fh = *i;\n        int vi = 0;\n        for (typename Mesh::ConstFaceVertexCCWIter fvi = mesh->cfv_ccwbegin(fh);\n             vi < 3 && fvi != mesh->cfv_ccwend(fh); ++fvi) {\n            F(j, vi) = newVertexHandleMap[*fvi];\n            vi++;\n        }\n    }\n}\n\nint MapMesh::CDTTrangle(const Coordinate2DPair &coordinates,\n                        std::vector<std::array<VertexHandle, 3>> &faces,\n                        BaryCoor &barycentricCoordinates) {\n\n    faces.clear();\n\n    std::vector<p2t::Point *> points(coordinates.size());\n    for (int i = 0; i < coordinates.size(); i++) {\n        double x = coordinates[i].second[0];\n        double y = coordinates[i].second[1];\n\n        points[i] = new p2t::Point(x, y);\n    }\n\n    p2t::CDT cdt(points);\n\n    try {\n        cdt.Triangulate();\n    } catch (const std::runtime_error &exception) {\n        std::cout << exception.what() << std::endl;\n        throw exception;\n    }\n\n    auto triangles = cdt.GetTriangles();\n    if (!p2t::IsDelaunay(triangles)) {\n        return -1;\n    }\n\n    int trangleIdx = -1;\n    for (int j = 0; j < triangles.size(); j++) {\n        auto &triangle = triangles[j];\n        std::array<Point2D, 3> triangle2D;\n        triangle2D[0] = Point2D(triangle->GetPoint(0)->x, triangle->GetPoint(0)->y);\n        triangle2D[1] = Point2D(triangle->GetPoint(1)->x, triangle->GetPoint(1)->y);\n        triangle2D[2] = Point2D(triangle->GetPoint(2)->x, triangle->GetPoint(2)->y);\n\n        std::array<VertexHandle, 3> face;\n        for (int i = 0; i < 3; i++) {\n            auto position = std::find(points.begin(), points.end(), triangle->GetPoint(i));\n            if (position == points.end()) return -1;\n            face[i] = coordinates[position - points.begin()].first;\n        }\n        faces.push_back(face);\n\n        /**\n         * 计算原点的重心坐标\n         */\n\n        if (!IsInTriangle(Point2D(0, 0), triangle2D)) continue;\n\n        auto [alpha, beta, gamma] = CalculateBaryCoor(Point2D(0, 0), triangle2D);\n        barycentricCoordinates[0] = std::make_pair(face[0], alpha);\n        barycentricCoordinates[1] = std::make_pair(face[1], beta);\n        barycentricCoordinates[2] = std::make_pair(face[2], gamma);\n        trangleIdx = j;\n    }\n\n    for (auto &point : points) {\n        delete point;\n    }\n\n    return trangleIdx;\n}\n\nint MapMesh::MVTTrangle(const Coordinate2DPair &coordinates, int startIdx,\n                        std::vector<std::array<VertexHandle, 3>> &faces,\n                        BaryCoor &barycentricCoordinates) {\n    faces.clear();\n    int trangleIdx = -1;\n    for (size_t i = 0, ii = 1; i < coordinates.size(); i++, ii++, ii %= coordinates.size()) {\n        if (i == startIdx || ii == startIdx) continue;\n\n        std::array<VertexHandle, 3> face(\n            {coordinates[i].first, coordinates[ii].first, coordinates[startIdx].first});\n\n        faces.push_back(face);\n\n        std::array<Point2D, 3> triangle;\n        triangle[0] = coordinates[startIdx].second;\n        triangle[1] = coordinates[i].second;\n        triangle[2] = coordinates[ii].second;\n\n        /**\n         * 计算原点的重心坐标\n         */\n\n        if (!IsInTriangle(Point2D(0, 0), triangle)) continue;\n\n        auto [alpha, beta, gamma] = CalculateBaryCoor(Point2D(0, 0), triangle);\n        barycentricCoordinates[0] = std::make_pair(coordinates[startIdx].first, alpha);\n        barycentricCoordinates[1] = std::make_pair(coordinates[i].first, beta);\n        barycentricCoordinates[2] = std::make_pair(coordinates[ii].first, gamma);\n\n        trangleIdx = static_cast<int>(faces.size() - 1);\n    }\n    return trangleIdx;\n}\n\nstd::optional<MapMesh::Point2D> MapMesh::ReCalculate2DCoordinates(\n    std::map<VertexHandle, Point2D> &originCoor, VertexHandle deleteVertex) const {\n    if (!IsVertexDeleted(deleteVertex)) return std::nullopt;\n    auto baryCoor = data(deleteVertex).baryCoor.value();\n\n    return originCoor[baryCoor[0].first] * baryCoor[0].second +\n           originCoor[baryCoor[1].first] * baryCoor[1].second +\n           originCoor[baryCoor[2].first] * baryCoor[2].second;\n}\n\nvoid MapMesh::ReTrangleAndAddFace(const VertexHandle &deleteVertex) {\n    // 记录1领域面中所有包含的点, 并更新这些点的参数\n    // 假设1领域面f上记录了一个点v, v中记录了v在f上的重心坐标(a, b, c), 面f在经过2维映射变成了f'\n    // 更新过程: 1. 根据f'和(a, b, c)计算v的二维映射点v'\n    //           2. 重新计算包含v'的三角形p‘, 并根据p’重新计算坐标(a', b', c')\n    //           3. 删除f, 添加面p, 更新v的重心坐标, 建立p与v的关联\n\n    std::vector<FaceHandle> ringFaces(vf_begin(deleteVertex), vf_end(deleteVertex));\n    Coordinate2DPair coordinates;\n    Calculate2D(deleteVertex, coordinates);\n\n    // 重新计算1领域面上所有包含的点的二维坐标\n    std::map<VertexHandle, Point2D> currentPoint2DMap(coordinates.begin(), coordinates.end());\n    std::map<VertexHandle, Point2D> deletePoint2DMap;\n    for (auto &face : ringFaces) {\n        for (auto &vertex : data(face).vertrices) {\n            auto newCoor = ReCalculate2DCoordinates(currentPoint2DMap, vertex);\n            if (!newCoor.has_value()) break;\n            deletePoint2DMap[vertex] = newCoor.value();\n        }\n    }\n\n    delete_vertex(deleteVertex, false);\n\n    BaryCoor barycentricCoordinates;\n    std::vector<std::array<VertexHandle, 3>> newFaces;\n\n    int trangleIdx = CDTTrangle(coordinates, newFaces, barycentricCoordinates);\n    std::vector<FaceHandle> facesHandle;\n    if (trangleIdx != -1 && TryToAddFaces(newFaces, facesHandle)) {\n        data(facesHandle[trangleIdx]).vertrices.push_back(deleteVertex);\n        data(deleteVertex).baryCoor = barycentricCoordinates;\n\n        // 判断被删除的点在那个三角形内部, 并计算重心坐标\n\n        for (auto &[vertex, point2D] : deletePoint2DMap) {\n            auto newParma = UpdateParam(newFaces, currentPoint2DMap, point2D);\n            if (!newParma.has_value()) continue;\n            auto [idx, alpha, beta, gamma] = newParma.value();\n            data(facesHandle[idx]).vertrices.push_back(vertex);\n\n            BaryCoor baryCoor;\n            baryCoor[0].first = newFaces[idx][0], baryCoor[0].second = alpha;\n            baryCoor[1].first = newFaces[idx][1], baryCoor[1].second = beta;\n            baryCoor[2].first = newFaces[idx][2], baryCoor[2].second = gamma;\n            data(vertex).baryCoor = baryCoor;\n        }\n\n        return;\n    }\n    for (int i = 0; i < coordinates.size(); i++) {\n        newFaces.clear();\n        trangleIdx = MVTTrangle(coordinates, i, newFaces, barycentricCoordinates);\n        if (TryToAddFaces(newFaces, facesHandle)) {\n\n            data(facesHandle[trangleIdx]).vertrices.push_back(deleteVertex);\n            data(deleteVertex).baryCoor = barycentricCoordinates;\n\n            for (auto &[vertex, point2D] : deletePoint2DMap) {\n                auto newParma = UpdateParam(newFaces, currentPoint2DMap, point2D);\n                if (!newParma.has_value()) continue;\n                auto [idx, alpha, beta, gamma] = newParma.value();\n                data(facesHandle[idx]).vertrices.push_back(vertex);\n\n                BaryCoor baryCoor;\n                baryCoor[0].first = newFaces[idx][0], baryCoor[0].second = alpha;\n                baryCoor[1].first = newFaces[idx][1], baryCoor[1].second = beta;\n                baryCoor[2].first = newFaces[idx][2], baryCoor[2].second = gamma;\n                data(vertex).baryCoor = baryCoor;\n            }\n            return;\n        }\n    }\n    throw std::runtime_error(\"can't add face\");\n}\n\nvoid MapMesh::Initialize() {\n    originFaces = std::vector<FaceHandle>(faces_sbegin(), faces_end());\n    for (const auto &face : originFaces) {\n        originFaceVertices[face] = std::vector<VertexHandle>(fv_begin(face), fv_end(face));\n    }\n}\n\nvoid MapMesh::CalculateCurvature() {\n    Eigen::MatrixX3d V;\n    Eigen::MatrixX3i F;\n    Eigen::VectorXd K;\n\n    OpenMesh2IGL(this, V, F);\n    igl::gaussian_curvature(V, F, K);\n\n    int j = 0;\n    maxCurvature = (std::numeric_limits<double>::min)();\n    for (auto i = vertices_sbegin(); i != vertices_end(); i++, j++) {\n        data(*i).curvature = K[j];\n        if (K[j] > maxCurvature) {\n            maxCurvature = K[j];\n        }\n    }\n}\n\nvoid MapMesh::CalculateWeight(double lambda) {\n    while (!curvatureQueue.empty()) {\n        curvatureQueue.pop();\n    }\n\n    for (auto i = vertices_sbegin(); i != vertices_end(); i++) {\n        data(*i).weight = lambda * data(*i).curvature / maxCurvature +\n                          (1 - lambda) * data(*i).ringArea / maxRingArea;\n        curvatureQueue.push(*i);\n    }\n}\n\nvoid MapMesh::CalculateAreas() {\n    maxRingArea = (std::numeric_limits<double>::min)();\n    for (auto faceIter = faces_sbegin(); faceIter != faces_end(); faceIter++) {\n        double area = CalculateArea(*faceIter);\n        data(*faceIter).area = area;\n    }\n\n    for (auto vertexIter = vertices_sbegin(); vertexIter != vertices_end(); vertexIter++) {\n        double ringArea = 0;\n        for (auto faceIter = vf_begin(*vertexIter); faceIter != vf_end(*vertexIter); faceIter++) {\n            ringArea += data(*faceIter).area;\n        }\n        if (ringArea > maxRingArea) {\n            maxRingArea = ringArea;\n        }\n        data(*vertexIter).ringArea = ringArea;\n    }\n}\n\nvoid MapMesh::MapFaceFromOriginMesh(const FaceHandle &face, std::array<Point, 3> &mapFace) const {\n    if (originFaceVertices.find(face) == originFaceVertices.end()) return;\n\n    const std::vector<VertexHandle> &vertices = originFaceVertices.at(face);\n    assert(vertices.size() == 3);\n    for (int i = 0; i < 3; i++) {\n        auto vertexHandle = vertices[i];\n        if (!IsVertexDeleted(vertexHandle)) {\n            mapFace[i] = point(vertexHandle);\n            continue;\n        }\n\n        auto baryCoor = data(vertexHandle).baryCoor.value();\n        mapFace[i] = point(baryCoor[0].first) * baryCoor[0].second +\n                     point(baryCoor[1].first) * baryCoor[1].second +\n                     point(baryCoor[2].first) * baryCoor[2].second;\n    }\n}\n\nvoid MapMesh::FaceSubDivision() {\n    std::vector<FaceHandle> originFaceHandle(faces_sbegin(), faces_end());\n\n    for (const auto &faceHandle : originFaceHandle) {\n        std::vector<VertexHandle> vertices(fv_begin(faceHandle), fv_end(faceHandle));\n        assert(vertices.size() == 3);\n\n        for (int i = 0, ii = 1; i < 3; i++, ii++, ii %= 3) {\n            auto newPoint = (point(vertices[i]) + point(vertices[ii])) / 2.0;\n            auto newPointHandle = add_vertex(newPoint);\n            data(newPointHandle).isNew = true;\n            vertices.push_back(newPointHandle);\n        }\n        delete_face(faceHandle);\n        add_face({vertices[0], vertices[3], vertices[5]});\n        add_face({vertices[3], vertices[1], vertices[4]});\n        add_face({vertices[5], vertices[4], vertices[2]});\n        add_face({vertices[3], vertices[4], vertices[5]});\n    }\n}\n\nvoid MapMesh::DownSampling() {\n    request_face_status();\n    request_vertex_status();\n    request_edge_status();\n\n    for (auto vertexIter = vertices_sbegin(); vertexIter != vertices_end(); vertexIter++) {\n        data(*vertexIter).canBeDeleted = true;\n    }\n\n    CalculateCurvature();\n    CalculateAreas();\n    CalculateWeight(0.5);\n    while (!curvatureQueue.empty()) {\n        auto vertexHandle = curvatureQueue.top();\n        curvatureQueue.pop();\n        if (!data(vertexHandle).canBeDeleted) continue;\n\n        for (auto ringVertex = vv_begin(vertexHandle); ringVertex != vv_end(vertexHandle);\n             ringVertex++) {\n            data(*ringVertex).canBeDeleted = false;\n        }\n\n        ReTrangleAndAddFace(vertexHandle);\n    }\n    SaveBaseLevelMesh();\n}\n\nvoid MapMesh::Remesh() {\n\n    int N = static_cast<int>(std::distance(vertices_sbegin(), vertices_end()));\n    progressbar bar(N);\n\n    std::mutex _mutex;\n\n    auto IsMapedInASingleFace = [&](const FaceHandle &faceHandle) -> bool {\n        std::set<VertexHandle> verticesHandle;\n        for (const auto &vertexHandle : originFaceVertices[faceHandle]) {\n            if (data(vertexHandle).baryCoor.has_value()) {\n                auto baryCoor = data(vertexHandle).baryCoor.value();\n                verticesHandle.insert(baryCoor[0].first);\n                verticesHandle.insert(baryCoor[1].first);\n                verticesHandle.insert(baryCoor[2].first);\n            } else {\n                verticesHandle.insert(vertexHandle);\n            }\n        }\n\n        return verticesHandle.size() == 3;\n    };\n\n    auto findMaxCommonVertex = [&](const std::vector<FaceHandle> &facesHandle) {\n        std::multiset<VertexHandle> verticesHandle;\n        for (const auto &faceHandle : facesHandle) {\n            for (const auto &vertexHandle : baseLevelMesh->fv_range(faceHandle)) {\n                verticesHandle.insert(vertexHandle);\n            }\n        }\n\n        VertexHandle maxCommonVertex;\n        int maxCount = -1;\n        for (const auto &vertex : verticesHandle) {\n            int count = static_cast<int>(verticesHandle.count(vertex));\n            if (count > maxCount) {\n                maxCount = static_cast<int>(verticesHandle.count(vertex));\n                maxCommonVertex = vertex;\n            }\n        }\n\n        return maxCommonVertex;\n    };\n\n    auto isRingFace = [&](const VertexHandle &vertexHandle, const FaceHandle &faceHandle) {\n        for (const auto &face : baseLevelMesh->vf_range(vertexHandle)) {\n            if (face == faceHandle) return true;\n        }\n        return false;\n    };\n\n    auto isRingPoint =\n        [&](const VertexHandle &vertexHandle, const std::vector<VertexHandle> &ringVertices) {\n        for (const auto &ringVertex : ringVertices) {\n            bool found = false;\n            for (const auto &realRingVertex : baseLevelMesh->vv_range(vertexHandle)) {\n                if (realRingVertex == ringVertex) {\n                    found = true;\n                }\n            }\n            if (!found) return false;\n        }\n        return true;\n    };\n\n    oneapi::tbb::parallel_for_each(vertices_sbegin(), vertices_end(),\n                                   [&](const VertexHandle &vertex) {\n        if (!data(vertex).isNew) {\n            _mutex.lock();\n            bar.update();\n            _mutex.unlock();\n            /* continue; */\n            return;\n        }\n\n        // 在基面上找到公共顶点，并展开到2维平面计算重心坐标\n        auto vertexFaceOption = baseLevelMesh->FindFace(point(vertex));\n        if (!vertexFaceOption.has_value()) {\n            _mutex.lock();\n            bar.update();\n            _mutex.unlock();\n            /* continue; */\n            return;\n        }\n        auto vertexFace = vertexFaceOption.value();\n\n        for (const auto &face : originFaces) {\n            std::array<Point, 3> mapFace;\n            const std::vector<VertexHandle> &fv = originFaceVertices[face];\n\n            if (IsMapedInASingleFace(face)) {  // 原面能够完全映射到基面上\n                MapFaceFromOriginMesh(face, mapFace);\n                if (IsInTriangle(point(vertex), mapFace)) {\n                    auto [alpha, beta, gamma] = CalculateBaryCoor(point(vertex), mapFace);\n                    Point newPoint =\n                        alpha * point(fv[0]) + beta * point(fv[1]) + gamma * point(fv[2]);\n                    point(vertex) = newPoint;\n                    break;\n                }\n            } else {\n\n                std::vector<FaceHandle> baseFaces;\n                std::vector<VertexHandle> fixVertex;\n                for (const auto &vertexHandle : fv) {\n                    if (!IsVertexDeleted(vertexHandle)) {\n                        fixVertex.push_back(vertexHandle);\n                        continue;\n                    }\n\n                    auto baryCoor = data(vertexHandle).baryCoor.value();\n                    auto face = baseLevelMesh->FindFace(\n                        {baryCoor[0].first, baryCoor[1].first, baryCoor[2].first});\n\n                    if (face.has_value()) {\n                        baseFaces.push_back(face.value());\n                    }\n                }\n\n                VertexHandle commonVertex;\n                if (baseFaces.size() == 3) {\n                    if (std::find(baseFaces.begin(), baseFaces.end(), vertexFace) ==\n                        baseFaces.end()) {\n                        continue;\n                    }\n                    commonVertex = findMaxCommonVertex(baseFaces);\n                } else {\n                    bool foundCommonVertex = false;\n                    for (const auto &baseFace : baseFaces) {\n                        for (const auto &baseVert : baseLevelMesh->fv_range(baseFace)) {\n                            if (isRingFace(baseVert, vertexFace) &&\n                                isRingPoint(baseVert, fixVertex)) {\n                                commonVertex = baseVert;\n                                foundCommonVertex = true;\n                                break;\n                            }\n                        }\n                        if (foundCommonVertex) break;\n                    }\n                    if (!foundCommonVertex) continue;\n                }\n\n                Coordinate2DPair coorPair;\n                baseLevelMesh->Calculate2D(commonVertex, coorPair);\n\n                Coordinate2DMap coorMap(coorPair.begin(), coorPair.end());\n                Point2D vertex2D(0, 0);\n                auto vertex2DBaryCoor = baseLevelMesh->CalculateBaryCoor(point(vertex), vertexFace);\n                for (const auto &vertex2DBaryCoorItem : vertex2DBaryCoor) {\n                    if (coorMap.find(vertex2DBaryCoorItem.first) == coorMap.end()) {\n                        continue;\n                    }\n                    vertex2D +=\n                        coorMap.at(vertex2DBaryCoorItem.first) * vertex2DBaryCoorItem.second;\n                }\n\n                std::array<std::pair<VertexHandle, Point2D>, 3> face2D;\n                bool canMapTo2D = true;\n                for (int i = 0; i < 3; i++) {\n                    face2D[i].first = fv[i];\n                    face2D[i].second = Point2D(0, 0);\n                    if (!IsVertexDeleted(fv[i])) {\n                        face2D[i].second = coorMap[fv[i]];\n                        continue;\n                    }\n\n                    auto baryCoor = data(fv[i]).baryCoor.value();\n                    for (const auto &baryCoorItem : baryCoor) {\n                        if (baryCoorItem.first == commonVertex) continue;\n                        if (coorMap.find(baryCoorItem.first) == coorMap.end()) {\n                            canMapTo2D = false;\n                            break;\n                            /* throw std::runtime_error(\"can't found item\"); */\n                        }\n                        face2D[i].second += coorMap.at(baryCoorItem.first) * baryCoorItem.second;\n                    }\n                }\n                if (!canMapTo2D) continue;\n\n                std::array<Point2D, 3> triangle{face2D[0].second, face2D[1].second,\n                                                face2D[2].second};\n\n                if (!IsInTriangle(vertex2D, triangle)) continue;\n\n                auto [alpha, beta, gamma] = CalculateBaryCoor(vertex2D, triangle);\n\n                point(vertex) = alpha * point(face2D[0].first) + beta * point(face2D[1].first) +\n                                gamma * point(face2D[2].first);\n                break;\n            }\n        }\n        _mutex.lock();\n        bar.update();\n        _mutex.unlock();\n    });\n}\n\nstd::optional<std::tuple<int, double, double, double>> MapMesh::UpdateParam(\n    const std::vector<std::array<VertexHandle, 3>> &faces,\n    const std::map<VertexHandle, Point2D> &point2DMap, const Point2D &point) {\n\n    for (int i = 0; i < faces.size(); i++) {\n        const auto &face = faces[i];\n        std::array<Point2D, 3> triangle;\n        triangle[0] = point2DMap.at(face[0]);\n        triangle[1] = point2DMap.at(face[1]);\n        triangle[2] = point2DMap.at(face[2]);\n        if (!IsInTriangle(point, triangle)) continue;\n\n        auto [alpha, beta, gamma] = CalculateBaryCoor(point, triangle);\n        return std::make_tuple(i, alpha, beta, gamma);\n    }\n\n    return std::nullopt;\n}\n\nvoid MapMesh::Calculate2D(VertexHandle vertex, Coordinate2DPair &coordinates) const {\n    coordinates.clear();\n    auto vertex3D = point(vertex);\n\n    double K_i = 0;\n    for (const auto &face : vf_range(vertex)) {\n        K_i += CalculateAngle(vertex, face);\n    }\n    double a = 2 * M_PI / K_i;\n\n    K_i = 0;\n\n    VertexHandle lastVertex;\n    int i = 0;\n    for (const auto &ringPoint : vv_range(vertex)) {\n        if (i != 0) {\n            auto Vec1 = point(lastVertex) - point(vertex);\n            auto Vec2 = point(ringPoint) - point(vertex);\n\n            K_i += std::acos(Vec1.normalized().dot(Vec2.normalized()));\n        }\n        auto point3D = point(ringPoint);\n        double r_k = (point3D - vertex3D).norm();\n\n        Point2D point2D{std::pow(r_k, a) * std::cos(K_i * a), std::pow(r_k, a) * std::sin(K_i * a)};\n\n        coordinates.emplace_back(ringPoint, point2D);\n        lastVertex = ringPoint;\n\n        i++;\n    }\n}\n\n}  // namespace Maps\n", "meta": {"hexsha": "cff6c6b539ce97723b22717ec5d4a86d5d8718a4", "size": 21795, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/MapsMesh.cc", "max_stars_repo_name": "45degree/MAPS", "max_stars_repo_head_hexsha": "aa2aacdda97ab67cc3e80aca3251000eed49d1e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MapsMesh.cc", "max_issues_repo_name": "45degree/MAPS", "max_issues_repo_head_hexsha": "aa2aacdda97ab67cc3e80aca3251000eed49d1e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MapsMesh.cc", "max_forks_repo_name": "45degree/MAPS", "max_forks_repo_head_hexsha": "aa2aacdda97ab67cc3e80aca3251000eed49d1e3", "max_forks_repo_licenses": ["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.2043189369, "max_line_length": 100, "alphanum_fraction": 0.5606331727, "num_tokens": 5684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.299044887348973}}
{"text": "// *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*\n// ** Copyright UCAR, CSU  (c) 1990 - 2018\n// ** University Corporation for Atmospheric Research (UCAR)\n// ** National Center for Atmospheric Research (NCAR)\n// ** Colorado State University\n// ** BSD licence applies\n// ** DISCLAIMER: THIS SOFTWARE IS PROVIDED \"AS IS\" AND WITHOUT ANY EXPRESS\n// ** OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n// ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n// *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*\n\n#include <iostream>\n#include <string>\n#include \"Fractl.hh\"\n#include \"Params.hh\"\n#include \"Filters.hh\"\n#include \"Interps.hh\"\n\n// Eigen linear algebra library\n// http://eigen.tuxfamily.org/index.php?title=Main_Page\n#include <Eigen/Dense>\n\ndouble sumTimea = 0;\nint cntTimeb = 0;\ndouble sumTimeb = 0;\ndouble sumTimec = 0;\ndouble sumTimee = 0;\ndouble sumTimef = 0;\n\nbool Fractl::calcWinds()\n{\n  // One approach is to iterate:\n  //   calculate V and U winds\n  //   calculate W winds\n  //   recalculate V and U winds using the new W winds\n  //   recalculate W with the new V, U.\n  //   etc.\n  //\n  // However, tests show that there is negligible gain\n  // in accuracy after the first iteration.\n  // So the loop limit is hardcoded at 1.\n\n  for (int imain = 0; imain < 1; imain++) {\n    // bool showStat = true;\n    // Based on current w, calc u, v.\n    if (gridType == Params::GRID_MISH)\n      calcAllVUOnMish(\n\t\tnumNbrMax,       // max num nearest nbrs\n\t\tpointVec,        // all observations\n\t\tradarKdTree,     // nearest nbr tree for pointVec\n\t\tcellMat);\n    else\n      calcAllVU(\n\t\tnumNbrMax,       // max num nearest nbrs\n\t\tpointVec,        // all observations\n\t\tradarKdTree,     // nearest nbr tree for pointVec\n\t\tcellMat);\n\n      \n    printRunTime(\"calcAllVU\", &timea);\n\n    // Run low-pass filtering if requested\n\n    Filter *filter = FilterFactory::createFilter(uvFilter);\t\t// TOD indices\n    if (filter != NULL) {\n      filter->filter_U(cellMat, nradx, nrady, nradz, 1, NULL);\n      filter->filter_V(cellMat, nradx, nrady, nradz, 1, NULL);\n      delete filter;\n    }\n\n    // Run interpolation for missing data if requested\n    // TODO: add old RadarWind interpolation and code Interp::interpolate\n\n    Interp *interp = InterpFactory::createInterp(uvInterp);\n    if (interp != NULL) {\n      interp->interpolate_U(cellMat, nradx, nrady, nradz, std::numeric_limits<double>::quiet_NaN());\n      interp->interpolate_V(cellMat, nradx, nrady, nradz, std::numeric_limits<double>::quiet_NaN());\n      delete interp;\n    }\n\n    // NO LONGER USED:\n    // Interpolate missing values from neighbors.\n    //\n    // The problem is that some cells don't have enough valid\n    // neighbors to calculate their winds, so their values are\n    // left as NaN.\n    //\n    // The idea was to fill the NaN cells\n    // by interpolating the wind values from nearby cells.\n    //\n    // But what happens is that generally if a cell doesn't have\n    // enough good neighbors for a valid wind calculation,\n    // any neighbor cells we might use for interpolation are\n    // pretty flakey.\n    //xxx del interpolation?\n    // Interpolate NaN values in cellMat.uu, cellMat.vv.\n    //interpMissing( bugs, nradz, nrady, nradx, cellMat, tmpmat);\n    //printRunTime(\"interpMissing for V,U\", &timea);\n\n    // Based on u, v, calc w\n\n    if (gridType == Params::GRID_MISH)    \n      calcAllWOnMish(cellMat);\n    else\n      calcAllW(cellMat);\n    \n    printRunTime(\"calcAllW\", &timea);\n\n    // Run low-pass filtering on W if requested\n\n    filter = FilterFactory::createFilter(wFilter);\n    if (filter != NULL) {\n      filter->filter_W(cellMat, nradx, nrady, nradz, 1, NULL);  // TODO indices\n      delete filter;\n    }\n\n    // Calc deltas using verification data, if any.\n    // Write outTxt file.\n    checkVerif(imain, cellMat);\n    printRunTime(\"checkVerif\", &timea);\n  } // for imain\n  return true;\n}\n\n//======================================================================\n\n// Calculate V and U winds at all cells in the z,y,x grid.\n\nvoid Fractl::calcAllVU(\n\t\t       long numNbrMax,              // max num nearest nbrs\n\t\t       vector<Point *> *pointVec,   // all observations\n\t\t       KD_tree * radarKdTree,       // nearest nbr tree for pointVec\n\t\t       Cell ***& cellMat)           // we set Cell.uu, vv\n{\n\n  KD_real * centerLoc = new KD_real[ndim];\n  long okCount = 0;\n\n  for (long iz = 0; iz < nradz; iz++) {\n    for (long iy = 0; iy < nrady; iy++) {\n      for (long ix = 0; ix < nradx; ix++) {\n\n        centerLoc[0] = zgridmin + iz * zgridinc;\n        centerLoc[1] = ygridmin + iy * ygridinc;\n        centerLoc[2] = xgridmin + ix * xgridinc;\n\n        if (bugs >= Params::DEBUG_NORM) {\n          cout << setprecision(5);\n          cout << endl << \"calcAllVU: iz: \" << iz\n\t       << \"  iy: \" << iy\n\t       << \"  ix: \" << ix\n\t       << \"  z: \" << centerLoc[0]\n\t       << \"  y: \" << centerLoc[1]\n\t       << \"  x: \" << centerLoc[2]\n\t       << endl;\n        }\n\n        Cell * pcell = & cellMat[iz][iy][ix];\n        calcCellVU(\n\t\t   centerLoc,             // query point\n\t\t   numNbrMax,             // max num nearest nbrs\n\t\t   pointVec,              // all observations\n\t\t   radarKdTree,           // nearest nbr tree for pointVec\n\t\t   pcell);                 // Cell.vv, uu are set.\n\n        bool ok = false;\n        if (isOkDouble( pcell->vv)\n\t    && isOkDouble( pcell->uu))\n\t  {\n\t    ok = true;\n\t    okCount++;\n\t  }\n\n        if (bugs >= Params::DEBUG_VERBOSE) {\n          cout << setprecision(7);\n          cout << \"calcAllVU: ok:\" << ok\n\t       << \"  iz: \" << iz\n\t       << \"  iy: \" << iy\n\t       << \"  ix: \" << ix\n\t       << \"  loc:\"\n\t       << \"  \" << centerLoc[0]\n\t       << \"  \" << centerLoc[1]\n\t       << \"  \" << centerLoc[2]\n\t       << \"  W: \" << cellMat[iz][iy][ix].ww\n\t       << \"  V: \" << cellMat[iz][iy][ix].vv\n\t       << \"  U: \" << cellMat[iz][iy][ix].uu << endl;\n        }\n\n      } // for ix\n    } // for iy\n  } // for iz\n\n  cout << \"---------------- okCount: \" << okCount << endl;\n\n  cout << \"sumTimea: \" << sumTimea << endl;\n  cout << \"cntTimeb: \" << cntTimeb << \"  sumTimeb: \" << sumTimeb << endl;\n  cout << \"sumTimec: \" << sumTimec << endl;\n  cout << \"sumTimee: \" << sumTimee << endl;\n  cout << \"sumTimef: \" << sumTimef << endl;\n\n  delete[] centerLoc;\n\n} // end calcAllVU\n\n//======================================================================\n\n// Try to calc V and U on the Samurai Mish grid\n\nvoid Fractl::calcAllVUOnMish(\n\t\t\t     long numNbrMax,              // max num nearest nbrs\n\t\t\t     vector<Point *> *pointVec,   // all observations\n\t\t\t     KD_tree * radarKdTree,       // nearest nbr tree for pointVec\n\t\t\t     Cell ***& cellMat)           // we set Cell.uu, vv\n{\n\n  KD_real * centerLoc = new KD_real[ndim];\n  long okCount = 0;\n  \n  // for (long iz = 0; iz < nradz; iz++)\n  //   for (long iy = 0; iy < nrady; iy++)\n  //     for (long ix = 0; ix < nradx; ix++)\n\n  //       centerLoc[0] = zgridmin + iz * zgridinc;\n  //       centerLoc[1] = ygridmin + iy * ygridinc;\n  //       centerLoc[2] = xgridmin + ix * xgridinc;\n\n  // This is the way Samurai iterates on the Mish.\n  // *Pos is the position in meter of the observation\n  // i*   is the index of the position in node table\n  \n  for (int ii = -1; ii < (nradx); ii++) {\n    for (int imu = -1; imu <= 1; imu += 2) {\n      double iPos = xgridmin + xgridinc * (ii + (0.5 * sqrt(1. / 3.) * imu + 0.5));\n\t    \n      for (int ji = -1; ji < (nrady); ji++) {\n\tfor (int jmu = -1; jmu <= 1; jmu += 2) {\n\t  double jPos = ygridmin + ygridinc * (ji + (0.5 * sqrt(1. / 3.) * jmu + 0.5));\n\t\t\n\t  for (int ki = -1; ki < (nradz); ki++) {\n\t    for (int kmu = -1; kmu <= 1; kmu += 2) {\n\t      double kPos = zgridmin + zgridinc * (ki + (0.5 * sqrt(1. / 3.) * kmu + 0.5));\n\t\n\t      int ix = (ii + 1) * 2 + (imu + 1) / 2;\n\t      int iy = (ji + 1) * 2 + (jmu + 1) / 2;\n\t      int iz = (ki + 1) * 2 + (kmu + 1) / 2;\n\n\t      // centerLoc[0] = zgridmin + iz * zgridinc;\n\t      // centerLoc[1] = ygridmin + iy * ygridinc;\n\t      // centerLoc[2] = xgridmin + ix * xgridinc;\n\n\t      centerLoc[0] = kPos;\n\t      centerLoc[1] = jPos;\n\t      centerLoc[2] = iPos;\n  \n\t      if (bugs >= Params::DEBUG_NORM) {\n\t\tstd::cout << setprecision(5);\n\t\tstd::cout << endl << \"calcAllVU: iz: \" << iz\n\t\t\t  << \"  iy: \" << iy\n\t\t\t  << \"  ix: \" << ix\n\t\t\t  << \"  z: \" << centerLoc[0]\n\t\t\t  << \"  y: \" << centerLoc[1]\n\t\t\t  << \"  x: \" << centerLoc[2]\n\t\t\t  << endl;\n\t      }             \n\n\t      Cell * pcell = & cellMat[iz][iy][ix];\n\t      calcCellVU(centerLoc,             // query point\n\t\t\t numNbrMax,             // max num nearest nbrs\n\t\t\t pointVec,              // all observations\n\t\t\t radarKdTree,           // nearest nbr tree for pointVec\n\t\t\t pcell);                 // Cell.vv, uu are set.\n\n\t      bool ok = false;\n\t      if (isOkDouble( pcell->vv) && isOkDouble( pcell->uu)) {\n\t\tok = true;\n\t\tokCount++;\n\t      }\n\n\t      if (bugs >= Params::DEBUG_VERBOSE) {\n\t\tcout << setprecision(7);\n\t\tcout << \"calcAllVU: ok:\" << ok\n\t\t     << \"  iz: \" << iz\n\t\t     << \"  iy: \" << iy\n\t\t     << \"  ix: \" << ix\n\t\t     << \"  loc:\"\n\t\t     << \"  \" << centerLoc[0]\n\t\t     << \"  \" << centerLoc[1]\n\t\t     << \"  \" << centerLoc[2]\n\t\t     << \"  W: \" << cellMat[iz][iy][ix].ww\n\t\t     << \"  V: \" << cellMat[iz][iy][ix].vv\n\t\t     << \"  U: \" << cellMat[iz][iy][ix].uu << endl;\n\t      }\n\t    } \n\t  } // ki\n\t}\n      } // ji\n    }\n  }  // ii\n\t\n  cout << \"---------------- okCount: \" << okCount << endl;\n\n  cout << \"sumTimea: \" << sumTimea << endl;\n  cout << \"cntTimeb: \" << cntTimeb << \"  sumTimeb: \" << sumTimeb << endl;\n  cout << \"sumTimec: \" << sumTimec << endl;\n  cout << \"sumTimee: \" << sumTimee << endl;\n  cout << \"sumTimef: \" << sumTimef << endl;\n\n  delete[] centerLoc;\n\n} // end calcAllVUOnMish\n\n\n//======================================================================\n\n// Calculate V and U winds for a single location.\n//\n// At a given location centerLoc, find the nearest nbrs\n// in pointVec, and use the radial velocities to calculate\n// the winds V, U, (not W).\n//\n// Let vx, vy, vz be estimates of the wind velocity,\n// and vr be the radial velocity.\n//\n// For each radar m, we use the linear model:\n//    vr_est[m] = cos(theta) cos(elev) vx\n//      + sin(theta) cos(elev) vy\n//      + sin(elev) vz\n//    vr_est[m] = conx vx + cony * vy + conz * vz\n//\n// Let E[m] = error = vr_true[m] - vr_est[m]\n//\n// We want to minimize Q = sum_m E[m]^2\n//\n//\n// Let\n//   sumxx = sum(conx * conx)\n//   sumxr = sum(conx * vr)\n//   etc.\n//\n// Normal equations, derived from\n// 0 = d(Q)/d(vx), 0 = d(Q)/d(vy), 0 = d(Q)/d(vz),\n// give:\n// vx sumxx + vy sumxy + vz sumxz = sumxr\n// vx sumxy + vy sumyy + vz sumyz = sumyr\n// vx sumxz + vy sumyz + vz sumzz = sumzr\n//\n// Or for 2 dim,\n// vx sumxx + vy sumxy = sumxr - vz sumxz\n// vx sumxy + vy sumyy = sumyr - vz sumyz\n//\n// Using Cramer's rule on the 2-dim case:\n// Let demom = sumxx sumyy - sumxy^2\n// vx_hat = ( (sumxr - vz sumxz) sumyy - (sumyr - vz sumyz) sumxy ) / denom\n// vy_hat = ( (sumyr - vz sumyz) sumxx - (sumxr - vz sumxz) sumxy ) / denom\n\nvoid Fractl::calcCellVU(\n\t\t\tKD_real * centerLoc,           // query point: z, y, x\n\t\t\tlong numNbrMax,                // max num nearest nbrs\n\t\t\tvector<Point *> *pointVec,     // all observations\n\t\t\tKD_tree * radarKdTree,         // nearest nbr tree for pointVec\n\t\t\tCell * pcell)                  // we fill vv, uu.\n{\n  struct timeval timea;\n  addDeltaTime( &timea, NULL);\n\n  pcell->uu = numeric_limits<double>::quiet_NaN();\n  pcell->vv = numeric_limits<double>::quiet_NaN();\n\n  bool showDetail = testDetail(\n\t\t\t       centerLoc[0],         // z\n\t\t\t       centerLoc[1],         // y\n\t\t\t       centerLoc[2]);        // x\n\n  if (bugs >= Params::DEBUG_EXTRA && showDetail) {\n    cout << setprecision(7);\n    cout << \"calcCellVU.entry: showDetail:\" << endl;\n    cout << \"    centerLoc: z: \" << centerLoc[0] << endl;\n    cout << \"    centerLoc: y: \" << centerLoc[1] << endl;\n    cout << \"    centerLoc: x: \" << centerLoc[2] << endl;\n    cout << \"    ww: \" << pcell->ww << endl;\n    cout << \"    vv: \" << pcell->vv << endl;\n    cout << \"    uu: \" << pcell->uu << endl;\n    cout << \"    meanNbrDbz: \" << pcell->meanNbrDbz << endl;\n    cout << \"    meanNbrNcp: \" << pcell->meanNbrNcp << endl;\n    cout << \"    meanNbrElevDeg: \" << pcell->meanNbrElevDeg << endl;\n    cout << \"    meanNbrKeepDist: \" << pcell->meanNbrKeepDist << endl;\n    cout << \"    meanNbrOmitDist: \" << pcell->meanNbrOmitDist << endl;\n    cout << \"    condNum: \" << pcell->conditionNumber << endl;\n  }\n\n  if (numNbrMax == 0) throwerr(\"cell numNbrMax == 0\");\n\n  int nbrIxs[numNbrMax];\n  KD_real nbrDistSqs[numNbrMax];              // nbr dist^2\n  for (long inbr = 0; inbr < numNbrMax; inbr++) {\n    nbrIxs[inbr] = -1;\n  }\n\n  Statistic nbrDbzStat;\n  Statistic nbrNcpStat;\n  Statistic nbrElevDegStat;\n  Statistic nbrKeepDistStat;\n  Statistic nbrOmitDistStat;\n\n  Point** nearPts = new Point *[numNbrMax];\n\n  addDeltaTime( &timea, &sumTimea);\n  struct timeval timeb;\n  addDeltaTime( &timeb, NULL);\n\n  // Find nearest nbrs\n  radarKdTree->nnquery(\n\t\t       centerLoc,        // query point\n\t\t       numNbrMax,        // desired num nearest nbrs\n\t\t       KD_EUCLIDEAN,     // Metric\n\t\t       1,                // MinkP\n\t\t       nbrIxs,           // out: parallel array, indices of nearest nbrs\n\t\t       nbrDistSqs);      // out: parallel array, squares of distances of nbrs\n\n  cntTimeb++;\n  addDeltaTime( &timeb, &sumTimeb);\n  struct timeval timec;\n  addDeltaTime( &timec, NULL);\n\n  if (bugs >= Params::DEBUG_VERBOSE && showDetail) {\n    cout << setprecision(7);\n    cout << \"  calcCellVU: showDetail:  nearPts for centerLoc: z: \"\n\t << centerLoc[0] << \"  y: \" << centerLoc[1]\n\t << \"  x: \" << centerLoc[2] << endl;\n  }\n\n  int numNbrActual = 0;\n\n  // Keep points within base + factor * aircraft dist\n\n  for (long inbr = 0; inbr < numNbrMax; inbr++) {\n    if (nbrIxs[inbr] < 0) throwerr(\"nbrIxs < 0\");\n\n    Point * nearPt = pointVec->at( nbrIxs[inbr]);\n    double aircraftDist = calcDistPtAircraft( nearPt);\n    double localDist = calcDistLocPt( centerLoc, nearPt);\n    double maxDist = maxDistBase + maxDistFactor * aircraftDist;\n\n    // Use local distance constraint from grid point center\n    double roi = sqrt(xgridinc * xgridinc + ygridinc * ygridinc + zgridinc * zgridinc);\n    if (roi < maxDist) maxDist = roi;\n\n    const char * msg;\n\n    if (localDist < maxDist) {\n      nbrDbzStat.addOb( nearPt->dbz);\n      nbrNcpStat.addOb( nearPt->ncp);\n      nbrElevDegStat.addOb( nearPt->elevRad * 180 / M_PI);\n      nbrKeepDistStat.addOb( localDist);\n      nearPts[numNbrActual++] = nearPt;\n      msg = \"KEEP\";\n    } // if localDist < maxDist\n\n    else {\n      nbrOmitDistStat.addOb( localDist);\n      msg = \"OMIT\";\n    }\n\n    if (bugs >= Params::DEBUG_VERBOSE && showDetail) {\n      cout << setprecision(5);\n      cout << \"    \" << msg\n\t   << \"  inbr: \" << inbr\n\t   << \"  dist: \" << localDist\n\t   << \"  pt:\"\n\t   << \"  coordz: \" << nearPt->coordz\n\t   << \"  coordy: \" << nearPt->coordy\n\t   << \"  coordx: \" << nearPt->coordx\n\t   << \"  vg: \" << nearPt->vg\n\t   << endl;\n    }\n\n  } // for inbr\n\n  if (bugs >= Params::DEBUG_EXTRA && showDetail) {\n    cout << \"  calcCellVU: showDetail: cell z: \"\n\t << centerLoc[0] << \"  y: \" << centerLoc[1]\n\t << \"  x: \" << centerLoc[2] << \"  numNbrActual: \" << numNbrActual << endl;\n  }\n\n  if (numNbrActual >= 2) {    // if numNbrActual is ok\n\n    pcell->meanNbrDbz = nbrDbzStat.dsum / nbrDbzStat.numGood;\n    pcell->meanNbrNcp = nbrNcpStat.dsum / nbrNcpStat.numGood;\n    pcell->meanNbrElevDeg = nbrElevDegStat.dsum / nbrElevDegStat.numGood;\n    pcell->meanNbrKeepDist = nbrKeepDistStat.dsum / nbrKeepDistStat.numGood;\n    pcell->meanNbrOmitDist = nbrOmitDistStat.dsum / nbrOmitDistStat.numGood;\n\n    if (bugs >= Params::DEBUG_EXTRA && showDetail) {\n      for (long inbr = 0; inbr < numNbrActual; inbr++) {\n\tPoint * pt = nearPts[inbr];\n\tcout << setprecision(7);\n\tcout << \"  calcCellVU: showDetail: nbr: inbr: \" << inbr\n\t     << \"  vg: \" << pt->vg\n\t     << \"  dbz: \" << pt->dbz\n\t     << \"  ncp: \" << pt->ncp\n\t     << \"  theta deg: \" << (pt->thetaRad * 180 / M_PI)\n\t     << \"  elev deg: \" << (pt->elevRad * 180 / M_PI)\n\t     << setprecision(15)\n\t     << \"  deltaTime: \"\n\t     << (pt->rayTime - nearPts[0]->rayTime)\n\t     << endl;\n      }\n      for (long inbr = 0; inbr < numNbrActual; inbr++) {\n\tPoint * pt = nearPts[inbr];\n\tcout << \"  showDetail.from.aircraft.to.nbr: set arrow \"\n\t     << (inbr + 1)\n\t     << \" from \" << pt->aircraftx << \",\" << pt->aircrafty\n\t     << \" to \" << pt->coordx << \",\" << pt->coordy\n\t     << endl;\n      }\n    } // if showDetail\n\n    addDeltaTime( &timec, &sumTimec);\n    struct timeval timee;\n    addDeltaTime( &timee, NULL);\n\n\n    // 3d solve\n    //    vr = cos(theta) cos(elev) vx\n    //      + sin(theta) cos(elev) vy\n    //      + sin(elev) vz\n\n    // 2d solve\n    //    vr - sin(elev) vz = cos(theta) cos(elev) vx\n    //      + sin(theta) cos(elev) vy\n\n\n    // Find wwind = W wind estimate near the pt.\n    double wwind = pcell->ww;\n    bool isCellOk = false;\n\n    if (useEigen) {\n\n      Eigen::MatrixXd amat( numNbrActual, 2);\n      Eigen::VectorXd bvec( numNbrActual);\n\n      for (long inbr = 0; inbr < numNbrActual; inbr++) {\n\tPoint * pt = nearPts[inbr];\n\tamat( inbr, 0) = cos( pt->thetaRad) * cos( pt->elevRad);\n\tamat( inbr, 1) = sin( pt->thetaRad) * cos( pt->elevRad);\n\n\t// Find wwind = W wind estimate near the pt.\n\tdouble wwind = pcell->ww;\n\n\tbvec( inbr) = pt->vg - wwind * sin( pt->elevRad);\n      }\n      if (bugs >= Params::DEBUG_EXTRA && showDetail) {\n\tcout << \"\\n  calcCellVU: eigen: amat:\\n\" << amat << endl;\n\tcout << \"\\n  calcCellVU: eigen: bvec:\\n\" << bvec << endl;\n      }\n\n      Eigen::JacobiSVD<Eigen::MatrixXd> svd(\n\t\t\t\t\t    amat, Eigen::ComputeThinU | Eigen::ComputeThinV);\n      Eigen::VectorXd singVals = svd.singularValues();\n      Eigen::MatrixXd thinV = svd.matrixV();\n      long slen = singVals.size();\n      // long vlen = thinV.rows();\n\n      pcell->conditionNumber = numeric_limits<double>::infinity();\n      if (slen > 0 && singVals[slen-1] != 0)\n\tpcell->conditionNumber = singVals[0] / singVals[slen-1];\n\n      if (bugs >= Params::DEBUG_EXTRA && showDetail) {\n\tcout << \"\\n  calcCellVU: eigen: singVals:\\n\" << singVals << endl;\n\tcout << \"\\n  calcCellVU: num nonzeroSingularValues:\\n\"\n\t     << svd.nonzeroSingularValues() << endl;\n\tcout << \"  calcCellVU: conditionNumber: \"\n\t     << pcell->conditionNumber << endl;\n      }\n\n      // Using a conditionNumberCutoff > 10 causes some cells\n      // to have extreme values for U and V.\n\n      if (pcell->conditionNumber < conditionNumberCutoff)\n\tisCellOk = true;\n      if (isCellOk) {\n\tEigen::VectorXd xvec = svd.solve( bvec);\n\tEigen::VectorXd errvec = amat * xvec - bvec;\n\t// double maxAbsErr = errvec.array().abs().maxCoeff();\n\t// double meanSqErr = errvec.dot( errvec) / numNbrActual;   // dot product\n\n\tpcell->vv = xvec(1);       // v\n\tpcell->uu = xvec(0);       // u\n\n\tdouble ustd = 0;\n\tdouble vstd = 0;\n\n\tfor (long s = 0; s < slen; s++) {\n\t  // double thin0 = TODO check if the calls to thinV() has side effects\n\t  thinV(0, s);\n\t  // double thin1 =\n\t  thinV(1, s);\n\t  // double sing =\n\t  singVals[s];\n\t  ustd += pow( (thinV(s, 0) / singVals[s]) , 2.0);\n\t  vstd += pow( (thinV(s, 1) / singVals[s]) , 2.0);\n\t}\n\tpcell->ustd = sqrt(ustd);\n\tpcell->vstd = sqrt(vstd);\n\n        if (fabs(pcell->vv) > maxV) {\n          pcell->vv = numeric_limits<double>::quiet_NaN();\n\t  pcell->vstd = numeric_limits<double>::quiet_NaN();\n\t}\n        if (fabs(pcell->uu) > maxU) {\n          pcell->uu = numeric_limits<double>::quiet_NaN();\n\t  pcell->ustd = numeric_limits<double>::quiet_NaN();\n\t}\n\n      } // if isCellOk\n    } // if useEigen\n\n\n    // Else use cramer's method\n    else {\n      double sxx = 0;\n      double sxy = 0;\n      double syy = 0;\n      double sxz = 0;\n      double syz = 0;\n\n      for (long inbr = 0; inbr < numNbrActual; inbr++) {\n\tPoint * pt = nearPts[inbr];\n\tdouble xval = cos( pt->thetaRad) * cos( pt->elevRad);\n\tdouble yval = sin( pt->thetaRad) * cos( pt->elevRad);\n\tdouble zval = pt->vg - wwind * sin( pt->elevRad);\n\n\tsxx += xval * xval;\n\tsxy += xval * yval;\n\tsyy += yval * yval;\n\tsxz += xval * zval;\n\tsyz += yval * zval;\n      }\n      double detbase = sxx*syy - sxy*sxy;\n      double det1    = sxz*syy - syz*sxy;\n      double det2    = sxx*syz - sxy*sxz;\n      if (bugs >= Params::DEBUG_EXTRA && showDetail) {\n\tcout << \"  calcCellVU: cramer: showDetail: \"\n\t     << \"  sxx: \" << sxx\n\t     << \"  sxy: \" << sxy\n\t     << \"  syy: \" << syy\n\t     << \"  sxz: \" << sxz\n\t     << \"  syz: \" << syz << endl;\n\tcout << \"  calcCellVU: cramer: showDetail: \"\n\t     << \"  detbase: \" << detbase\n\t     << \"  det1: \" << det1\n\t     << \"  det2: \" << det2 << endl;\n      }\n\n      // Using a detCutoff <= 0.01 causes some cells\n      // to have extreme values for U and V.\n      // A detCutoff of 0.1 gives roughly similar results to using\n      // a conditionNumber cutoff of 10.\n      double detCutoff = 0.1;    // xxxxxxxxx\n\n      if (fabs(detbase) > detCutoff) {\n\tpcell->uu = det1 / detbase;\n\tpcell->vv = det2 / detbase;\n      }\n    }\n\n    addDeltaTime( &timee, &sumTimee);\n    delete[] nearPts;\n  } // else numNbrActual is ok\n\n  struct timeval timef;\n  addDeltaTime( &timef, NULL);\n\n  if (bugs >= Params::DEBUG_EXTRA && showDetail) {\n    cout << setprecision(7);\n    cout << \"calcCellVU.exit: showDetail:\" << endl;\n    cout << \"    centerLoc: z: \" << centerLoc[0] << endl;\n    cout << \"    centerLoc: y: \" << centerLoc[1] << endl;\n    cout << \"    centerLoc: x: \" << centerLoc[2] << endl;\n    cout << \"    ww: \" << pcell->ww << endl;\n    cout << \"    vv: \" << pcell->vv << endl;\n    cout << \"    uu: \" << pcell->uu << endl;\n    cout << \"    meanNbrDbz: \" << pcell->meanNbrDbz << endl;\n    cout << \"    meanNbrNcp: \" << pcell->meanNbrNcp << endl;\n    cout << \"    meanNbrElevDeg: \" << pcell->meanNbrElevDeg << endl;\n    cout << \"    meanNbrKeepDist: \" << pcell->meanNbrKeepDist << endl;\n    cout << \"    meanNbrOmitDist: \" << pcell->meanNbrOmitDist << endl;\n    cout << \"    condNum: \" << pcell->conditionNumber << endl;\n  }\n\n} // end calcCellVU\n\n// xxx all alloc: delete\n\n//======================================================================\n\n\n// Calculate the W (vertical) winds for all cells in the z,y,x grid.\n//\n// Consider the vertical column of cells for some\n// given horizontal coordinates iy, ix.\n// By the mass continuity equation, the total volume of air coming\n// into the column must equal the total volume of air leaving the column.\n//\n// 0 = totalFlow = sum_iz (density_iz * sideFlow_iz) + endFlow\n// where\n//   density_iz = the density at level iz\n//   sideFlow_iz = flow through the sides of the cell at level iz\n//   endFlow = flow in the bottom and out the top end of the column\n//           = densityBot * bottomFlow - densityTop * topFlow\n//\n// We assume the end flows are 0, so\n//   bottendFlow = 0\n//   topFlow = 0\n//   endFlow = 0\n//\n// sideFlow_iz = uFlow_iz + vFlow_iz\n// uFlow_iz = (flow in from cell ix-1) - (flow out to cell ix+1)\n// uFlow_iz = 0.5 * (u[ix-1] + u[ix]) - 0.5 * (u[ix] + u[ix+1])\n//          = 0.5 * (u[ix-1] - u[ix+1])\n//\n// sideFlow_iz = 0.5 * (u[ix-1] - u[ix+1] + v[ix-1] - v[ix+1])\n//\n// 0 = totalFlow = sum_iz (density_iz * 0.5 * (\n//       v[iy-1] - v[iy+1]\n//     + u[ix-1] - u[ix+1]))\n//\n// But in real life the totalFlow sum is not 0.\n//\n// Now we ask what modifications to the U and V values\n// would make the totalFlow 0.\n// We want to modify those U,V values with larger elevation angles more.\n// xxx future: handle geometric uncertainty values too.\n//\n// At each layer, we have 4 terms to adjust: 2 U terms and 2 V terms.\n// Let us subtract h[iz] from each term on level iz.\n//\n// Find h[iz] such that:\n//   0 = sum_iz (density_iz * 0.5 * (\n//         (v[iy-1]-h[iz]) - (v[iy+1]+h[iz])\n//       + (u[ix-1]-h[iz]) - (u[ix+1])+h[iz]))\n//\n//     = totalFlow - sum_iz (density_iz * 0.5 * 4 * h[iz])\n//\n//   totalFlow = 2 * sum_iz (density_iz * h[iz])\n//\n// Let h[iz] be weighted by the elevation angle, so\n//   h[iz] = H * wgt[iz]\n//   wgt[iz] = cos(elevationAngle)\n//\n//   totalFlow = 2 * sum_iz (density[iz] * H * wgt[iz])\n//   H = totalFlow / (2 * sum_iz (density[iz] * wgt[iz]))\n\nvoid Fractl::calcAllWOnMish(\n\t\t      Cell ***& cellMat)           // We set Cell.ww\n{\n  long maxx = (xgridmax - xgridmin) * 2 / xgridinc + 1;\n  long maxy = (ygridmax - ygridmin) * 2 / ygridinc + 1;  \n  long maxz = (zgridmax - zgridmin) * 2 / zgridinc + 1;\n  \n  double * density = new double[maxz + 3];\t // range is 0..maxz\n  double * wgts = new double[maxz + 3];\n  \n  // double * density = new double[nradz];\n  // double * wgts = new double[nradz];\n  \n  //  for (long iz = 0; iz < nradz; iz++)\n  //    density[iz] = calcDensity( zgridmin + iz * zgridinc);\n\n  // Use samurai index computation since we need both position and index\n  \n  for (int ki = -1; ki < (nradz); ki++) {\n    for (int kmu = -1; kmu <= 1; kmu += 2) {\n      double kPos = zgridmin + zgridinc * (ki + (0.5 * sqrt(1. / 3.) * kmu + 0.5));\n      int ik = (ki + 1) * 2 + (kmu + 1) / 2;\n      density[ik] = calcDensity(kPos);\n    }\n  }\n\n  // Omit the edges of the region as we use ix-1, ix+1, iy-1, iy+1.\n  \n  // for (long iy = 1; iy < nrady - 1; iy++)\n  //   for (long ix = 1; ix < nradx - 1; ix++)\n\n  for (long iy = 1; iy < maxy - 1; iy++) {\n    for (long ix = 1; ix < maxx - 1; ix++) {\n\n      // for (long iz = 0; iz < nradz; iz++)\n      for (long iz = 0; iz < maxz; iz++) {\n        // xxx Future:\n        // Find c = the nearest cell to this one\n        // through which the aircraft flew.\n        // Let cosElev = horizDistToC / slantDistToC\n        // wgt = cosElev\n\n        wgts[iz] = 1.0;\n      }\n\n      // Calc totalFlow = sum of everything flowing into the column,\n      // not counting the top or bottom faces.\n\n      double totalFlow = 0;\n      double sumWgt = 0;\n\n      // for (long iz = 0; iz < nradz; iz++)\n      for (long iz = 0; iz < maxz; iz++) {\n\t\n        if ( isOkDouble( cellMat[iz][iy][ix-1].uu)\n\t     && isOkDouble( cellMat[iz][iy][ix+1].uu)\n\t     && isOkDouble( cellMat[iz][iy-1][ix].vv)\n\t     && isOkDouble( cellMat[iz][iy+1][ix].vv))\n\t  {\n\t    totalFlow += density[iz] * 0.5\n\t      * ( cellMat[iz][iy][ix-1].uu - cellMat[iz][iy][ix+1].uu\n\t\t  +  cellMat[iz][iy-1][ix].vv - cellMat[iz][iy+1][ix].vv);\n\t    sumWgt += density[iz] * wgts[iz];\n\t  }\n      } // for iz\n\n      double hcon;\n      if (fabs(sumWgt) < epsilon) hcon = 0;\n      else hcon = totalFlow / (2 * sumWgt);\n\n      // Calc W wind = totalFlow, starting at the bottom,\n      // using the modified U, V winds.\n      double wwind = baseW;\n      // for (long iz = 0; iz < nradz; iz++)\n      for (long iz = 0; iz < maxz; iz++) {\n        if ( isOkDouble( cellMat[iz][iy][ix-1].uu)\n\t     && isOkDouble( cellMat[iz][iy][ix+1].uu)\n\t     && isOkDouble( cellMat[iz][iy-1][ix].vv)\n\t     && isOkDouble( cellMat[iz][iy+1][ix].vv))\n\t  {\n\t    wwind += density[iz] * 0.5\n\t      * (  cellMat[iz][iy][ix-1].uu - cellMat[iz][iy][ix+1].uu\n\t\t   + cellMat[iz][iy-1][ix].vv - cellMat[iz][iy+1][ix].vv\n\t\t   - 4 * hcon * wgts[iz]);\n\t    if (! isOkDouble( wwind))\n\t      throwerr(\"calcAllW: invalid w wind\");\n\t    if (fabs(wwind) < maxW) {\n\t      cellMat[iz][iy][ix].ww = wwind;\n\t    } else cellMat[iz][iy][ix].ww = numeric_limits<double>::quiet_NaN();\n\t  } else cellMat[iz][iy][ix].ww = numeric_limits<double>::quiet_NaN();\n      } // for iz\n      if (fabs(wwind - baseW) > epsilon) {\n        cout << setprecision(15);\n        cout << \"calcAllW: iy: \" << iy << \"  ix: \" << ix\n\t     << \"  baseW: \" << baseW << \"  wwind: \" << wwind << endl;\n        cout.flush();\n        throwerr(\"wwind error\");\n      }\n    } // for ix\n  } // for iy\n\n  //xxx maybe omit:\n  // We only calculated the inner points for iy, ix.\n  // But we also will need the edge values when\n  // we calc the next iteration of U, V values.\n  // So set the edges from the nearest interior points.\n  // May be NaN.\n\n  // for (long iz = 0; iz < nradz; iz++)\n  for (long iz = 0; iz < maxz; iz++) {\n    // Corners\n    cellMat[iz][0][0].ww             = cellMat[iz][1][1].ww;\n    cellMat[iz][0][maxx-1].ww       = cellMat[iz][1][maxx-2].ww;\n    cellMat[iz][maxy-1][0].ww       = cellMat[iz][maxy-2][1].ww;\n    cellMat[iz][maxy-1][maxx-1].ww = cellMat[iz][maxy-2][maxx-2].ww;\n\n    // Side edges\n    // for (long iy = 1; iy < nrady - 1; iy++)\n    for (long iy = 1; iy < maxy - 1; iy++) {    \n      cellMat[iz][iy][0].ww       = cellMat[iz][iy][1].ww;\n      cellMat[iz][iy][maxx-1].ww = cellMat[iz][iy][maxx-2].ww;\n    }\n    // Top and bottom edges\n    // for (long ix = 1; ix < nradx - 1; ix++)\n    for (long ix = 1; ix < maxx - 1; ix++) {\n      cellMat[iz][0][ix].ww       = cellMat[iz][1][ix].ww;\n      cellMat[iz][maxy-1][ix].ww = cellMat[iz][maxy-2][ix].ww;\n    }\n  } // for iz\n\n  delete[] density;\n  delete[] wgts;\n\n} // end calcAllWOnMish\n\n//==================================================================\n\nvoid Fractl::calcAllW(\n\t\t      Cell ***& cellMat)           // We set Cell.ww\n{\n  double * density = new double[nradz];\n  double * wgts = new double[nradz];\n  for (long iz = 0; iz < nradz; iz++)\n    density[iz] = calcDensity( zgridmin + iz * zgridinc);\n\n  // Omit the edges of the region as we use ix-1, ix+1, iy-1, iy+1.\n  for (long iy = 1; iy < nrady - 1; iy++) {\n    for (long ix = 1; ix < nradx - 1; ix++) {\n\n      for (long iz = 0; iz < nradz; iz++) {\n        // xxx Future:\n        // Find c = the nearest cell to this one\n        // through which the aircraft flew.\n        // Let cosElev = horizDistToC / slantDistToC\n        // wgt = cosElev\n\n        wgts[iz] = 1.0;\n      }\n\n      // Calc totalFlow = sum of everything flowing into the column,\n      // not counting the top or bottom faces.\n\n      double totalFlow = 0;\n      double sumWgt = 0;\n\n      for (long iz = 0; iz < nradz; iz++) {\n        if ( isOkDouble( cellMat[iz][iy][ix-1].uu)\n\t     && isOkDouble( cellMat[iz][iy][ix+1].uu)\n\t     && isOkDouble( cellMat[iz][iy-1][ix].vv)\n\t     && isOkDouble( cellMat[iz][iy+1][ix].vv))\n\t  {\n\t    totalFlow += density[iz] * 0.5\n\t      * ( cellMat[iz][iy][ix-1].uu - cellMat[iz][iy][ix+1].uu\n\t\t  +  cellMat[iz][iy-1][ix].vv - cellMat[iz][iy+1][ix].vv);\n\t    sumWgt += density[iz] * wgts[iz];\n\n\t    bool showDetail = testDetail(\n\t\t\t\t\t zgridmin + iz * zgridinc,      // z\n\t\t\t\t\t ygridmin + iy * ygridinc,      // y\n\t\t\t\t\t xgridmin + ix * xgridinc);      // x\n\t    // detailSpec);                   // z, y, x, delta\n\n\t    if (showDetail) {\n\t      cout << setprecision(7);\n\t      cout << \"calcAllW: showDetail:\" << endl\n\t\t   << \"    iz: \" << iz << endl\n\t\t   << \"    iy: \" << iy << endl\n\t\t   << \"    ix: \" << ix << endl\n\t\t   << \"    den: \" << density[iz] << endl\n\t\t   << \"    wgt: \" << wgts[iz] << endl\n\t\t   << \"    U-: \" << cellMat[iz][iy][ix-1].uu << endl\n\t\t   << \"    U+: \" << cellMat[iz][iy][ix+1].uu << endl\n\t\t   << \"    V-: \" << cellMat[iz][iy-1][ix].vv << endl\n\t\t   << \"    V+: \" << cellMat[iz][iy+1][ix].vv << endl;\n\t    }\n\t  }\n      } // for iz\n\n      double hcon;\n      if (fabs(sumWgt) < epsilon) hcon = 0;\n      else hcon = totalFlow / (2 * sumWgt);\n\n      // Calc W wind = totalFlow, starting at the bottom,\n      // using the modified U, V winds.\n      double wwind = baseW;\n      for (long iz = 0; iz < nradz; iz++) {\n        if ( isOkDouble( cellMat[iz][iy][ix-1].uu)\n\t     && isOkDouble( cellMat[iz][iy][ix+1].uu)\n\t     && isOkDouble( cellMat[iz][iy-1][ix].vv)\n\t     && isOkDouble( cellMat[iz][iy+1][ix].vv))\n\t  {\n\t    wwind += density[iz] * 0.5\n\t      * (  cellMat[iz][iy][ix-1].uu - cellMat[iz][iy][ix+1].uu\n\t\t   + cellMat[iz][iy-1][ix].vv - cellMat[iz][iy+1][ix].vv\n\t\t   - 4 * hcon * wgts[iz]);\n\t    if (! isOkDouble( wwind))\n\t      throwerr(\"calcAllW: invalid w wind\");\n            if (fabs(wwind) < maxW) {\n              cellMat[iz][iy][ix].ww = wwind;\n            } else cellMat[iz][iy][ix].ww = numeric_limits<double>::quiet_NaN();\n\n\t    bool showDetail = testDetail(\n\t\t\t\t\t zgridmin + iz * zgridinc,      // z\n\t\t\t\t\t ygridmin + iy * ygridinc,      // y\n\t\t\t\t\t xgridmin + ix * xgridinc);      // x\n\n\t    if (showDetail) {\n\t      cout << setprecision(7);\n\t      cout << \"calcAllW: showDetail:\" << endl\n\t\t   << \"  iz: \" << iz << endl\n\t\t   << \"  iy: \" << iy << endl\n\t\t   << \"  ix: \" << ix << endl\n\t\t   << \"  den: \" << density[iz] << endl\n\t\t   << \"  U-: \" << cellMat[iz][iy][ix-1].uu << endl\n\t\t   << \"  U+: \" << cellMat[iz][iy][ix+1].uu << endl\n\t\t   << \"  V-: \" << cellMat[iz][iy-1][ix].vv << endl\n\t\t   << \"  V+: \" << cellMat[iz][iy+1][ix].vv << endl\n\t\t   << \"  hcon: \" << hcon << endl\n\t\t   << \"  wgt: \" << wgts[iz] << endl\n\t\t   << \"  con: \" << (4 * hcon * wgts[iz]) << endl\n\t\t   << \"  wwind: \" << wwind << endl;\n\t    }\n\t  }\n        else cellMat[iz][iy][ix].ww = numeric_limits<double>::quiet_NaN();\n      } // for iz\n      if (fabs(wwind - baseW) > epsilon) {\n        cout << setprecision(15);\n        cout << \"calcAllW: iy: \" << iy << \"  ix: \" << ix\n\t     << \"  baseW: \" << baseW << \"  wwind: \" << wwind << endl;\n        cout.flush();\n        throwerr(\"wwind error\");\n      }\n    } // for ix\n  } // for iy\n\n\n  //xxx maybe omit:\n  // We only calculated the inner points for iy, ix.\n  // But we also will need the edge values when\n  // we calc the next iteration of U, V values.\n  // So set the edges from the nearest interior points.\n  // May be NaN.\n\n  for (long iz = 0; iz < nradz; iz++) {\n    // Corners\n    cellMat[iz][0][0].ww             = cellMat[iz][1][1].ww;\n    cellMat[iz][0][nradx-1].ww       = cellMat[iz][1][nradx-2].ww;\n    cellMat[iz][nrady-1][0].ww       = cellMat[iz][nrady-2][1].ww;\n    cellMat[iz][nrady-1][nradx-1].ww = cellMat[iz][nrady-2][nradx-2].ww;\n\n    // Side edges\n    for (long iy = 1; iy < nrady - 1; iy++) {\n      cellMat[iz][iy][0].ww       = cellMat[iz][iy][1].ww;\n      cellMat[iz][iy][nradx-1].ww = cellMat[iz][iy][nradx-2].ww;\n    }\n    // Top and bottom edges\n    for (long ix = 1; ix < nradx - 1; ix++) {\n      cellMat[iz][0][ix].ww       = cellMat[iz][1][ix].ww;\n      cellMat[iz][nrady-1][ix].ww = cellMat[iz][nrady-2][ix].ww;\n    }\n  } // for iz\n\n  delete[] density;\n  delete[] wgts;\n\n} // end calcAllWOnMish\n\n//==================================================================\n\n// Calc distance from between a Point and the aircraft\n\ndouble Fractl::calcDistPtAircraft( Point * pta) {\n  double sumsq = 0;\n  double delta;\n  delta = pta->coordz - pta->aircraftz;\n  sumsq += delta * delta;\n  delta = pta->coordy - pta->aircrafty;\n  sumsq += delta * delta;\n  delta = pta->coordx - pta->aircraftx;\n  sumsq += delta * delta;\n  return sqrt( sumsq);\n}\n\n//==================================================================\n\n// Calc distance from a location to Point, in km.\n\ndouble Fractl::calcDistLocPt( double * loc, Point * pta) {\n  double sumsq = 0;\n  double delta;\n  delta = loc[0] - pta->coordz;\n  sumsq += delta * delta;\n  delta = loc[1] - pta->coordy;\n  sumsq += delta * delta;\n  delta = loc[2] - pta->coordx;\n  sumsq += delta * delta;\n  return sqrt( sumsq);\n}\n\n//==================================================================\n\n// Calc distance between two Points, in km.\n\ndouble Fractl::calcDistPtPt( Point * pta, Point * ptb) {\n  double sumsq = 0;\n  double delta;\n  delta = pta->coordz - ptb->coordz;\n  sumsq += delta * delta;\n  delta = pta->coordy - ptb->coordy;\n  sumsq += delta * delta;\n  delta = pta->coordx - ptb->coordx;\n  sumsq += delta * delta;\n  return sqrt( sumsq);\n}\n", "meta": {"hexsha": "b6fa54620955d676a1c9a87ee20806a2846e3e0c", "size": 35308, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/calcWinds.cc", "max_stars_repo_name": "nsf-lrose/FRACTL", "max_stars_repo_head_hexsha": "4c4dd6840fbc3319947f60e337484367dc22d252", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-03-17T03:29:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T03:30:07.000Z", "max_issues_repo_path": "src/calcWinds.cc", "max_issues_repo_name": "wujk1122/fractl", "max_issues_repo_head_hexsha": "4c4dd6840fbc3319947f60e337484367dc22d252", "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/calcWinds.cc", "max_forks_repo_name": "wujk1122/fractl", "max_forks_repo_head_hexsha": "4c4dd6840fbc3319947f60e337484367dc22d252", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-28T05:46:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T05:46:49.000Z", "avg_line_length": 32.4522058824, "max_line_length": 100, "alphanum_fraction": 0.5369038178, "num_tokens": 11813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2990306039958984}}
{"text": "/**\r\n * \\file Math.hpp\r\n * \\brief Header for GeographicLib::Math class\r\n *\r\n * Copyright (c) Charles Karney (2008-2019) <charles@karney.com> and licensed\r\n * under the MIT/X11 License.  For more information, see\r\n * https://geographiclib.sourceforge.io/\r\n **********************************************************************/\r\n\r\n// Constants.hpp includes Math.hpp.  Place this include outside Math.hpp's\r\n// include guard to enforce this ordering.\r\n#include <GeographicLib/Constants.hpp>\r\n\r\n#if !defined(GEOGRAPHICLIB_MATH_HPP)\r\n#define GEOGRAPHICLIB_MATH_HPP 1\r\n\r\n/**\r\n * Are C++11 math functions available?\r\n **********************************************************************/\r\n#if !defined(GEOGRAPHICLIB_CXX11_MATH)\r\n// Recent versions of g++ -std=c++11 (4.7 and later?) set __cplusplus to 201103\r\n// and support the new C++11 mathematical functions, std::atanh, etc.  However\r\n// the Android toolchain, which uses g++ -std=c++11 (4.8 as of 2014-03-11,\r\n// according to Pullan Lu), does not support std::atanh.  Android toolchains\r\n// might define __ANDROID__ or ANDROID; so need to check both.  With OSX the\r\n// version is GNUC version 4.2 and __cplusplus is set to 201103, so remove the\r\n// version check on GNUC.\r\n#  if defined(__GNUC__) && __cplusplus >= 201103 && \\\r\n  !(defined(__ANDROID__) || defined(ANDROID) || defined(__CYGWIN__))\r\n#    define GEOGRAPHICLIB_CXX11_MATH 1\r\n// Visual C++ 12 supports these functions\r\n#  elif defined(_MSC_VER) && _MSC_VER >= 1800\r\n#    define GEOGRAPHICLIB_CXX11_MATH 1\r\n#  else\r\n#    define GEOGRAPHICLIB_CXX11_MATH 0\r\n#  endif\r\n#endif\r\n\r\n#if !defined(GEOGRAPHICLIB_WORDS_BIGENDIAN)\r\n#  define GEOGRAPHICLIB_WORDS_BIGENDIAN 0\r\n#endif\r\n\r\n#if !defined(GEOGRAPHICLIB_HAVE_LONG_DOUBLE)\r\n#  define GEOGRAPHICLIB_HAVE_LONG_DOUBLE 0\r\n#endif\r\n\r\n#if !defined(GEOGRAPHICLIB_PRECISION)\r\n/**\r\n * The precision of floating point numbers used in %GeographicLib.  1 means\r\n * float (single precision); 2 (the default) means double; 3 means long double;\r\n * 4 is reserved for quadruple precision.  Nearly all the testing has been\r\n * carried out with doubles and that's the recommended configuration.  In order\r\n * for long double to be used, GEOGRAPHICLIB_HAVE_LONG_DOUBLE needs to be\r\n * defined.  Note that with Microsoft Visual Studio, long double is the same as\r\n * double.\r\n **********************************************************************/\r\n#  define GEOGRAPHICLIB_PRECISION 2\r\n#endif\r\n\r\n#include <cmath>\r\n#include <algorithm>\r\n#include <limits>\r\n\r\n#if GEOGRAPHICLIB_PRECISION == 4\r\n#include <boost/version.hpp>\r\n#include <boost/multiprecision/float128.hpp>\r\n#include <boost/math/special_functions.hpp>\r\n#elif GEOGRAPHICLIB_PRECISION == 5\r\n#include <mpreal.h>\r\n#endif\r\n\r\n#if GEOGRAPHICLIB_PRECISION > 3\r\n// volatile keyword makes no sense for multiprec types\r\n#define GEOGRAPHICLIB_VOLATILE\r\n// Signal a convergence failure with multiprec types by throwing an exception\r\n// at loop exit.\r\n#define GEOGRAPHICLIB_PANIC \\\r\n  (throw GeographicLib::GeographicErr(\"Convergence failure\"), false)\r\n#else\r\n#define GEOGRAPHICLIB_VOLATILE volatile\r\n// Ignore convergence failures with standard floating points types by allowing\r\n// loop to exit cleanly.\r\n#define GEOGRAPHICLIB_PANIC false\r\n#endif\r\n\r\nnamespace GeographicLib {\r\n\r\n  /**\r\n   * \\brief Mathematical functions needed by %GeographicLib\r\n   *\r\n   * Define mathematical functions in order to localize system dependencies and\r\n   * to provide generic versions of the functions.  In addition define a real\r\n   * type to be used by %GeographicLib.\r\n   *\r\n   * Example of use:\r\n   * \\include example-Math.cpp\r\n   **********************************************************************/\r\n  class GEOGRAPHICLIB_EXPORT Math {\r\n  private:\r\n    void dummy();               // Static check for GEOGRAPHICLIB_PRECISION\r\n    Math();                     // Disable constructor\r\n  public:\r\n\r\n#if GEOGRAPHICLIB_HAVE_LONG_DOUBLE\r\n    /**\r\n     * The extended precision type for real numbers, used for some testing.\r\n     * This is long double on computers with this type; otherwise it is double.\r\n     **********************************************************************/\r\n    typedef long double extended;\r\n#else\r\n    typedef double extended;\r\n#endif\r\n\r\n#if GEOGRAPHICLIB_PRECISION == 2\r\n    /**\r\n     * The real type for %GeographicLib. Nearly all the testing has been done\r\n     * with \\e real = double.  However, the algorithms should also work with\r\n     * float and long double (where available).  (<b>CAUTION</b>: reasonable\r\n     * accuracy typically cannot be obtained using floats.)\r\n     **********************************************************************/\r\n    typedef double real;\r\n#elif GEOGRAPHICLIB_PRECISION == 1\r\n    typedef float real;\r\n#elif GEOGRAPHICLIB_PRECISION == 3\r\n    typedef extended real;\r\n#elif GEOGRAPHICLIB_PRECISION == 4\r\n    typedef boost::multiprecision::float128 real;\r\n#elif GEOGRAPHICLIB_PRECISION == 5\r\n    typedef mpfr::mpreal real;\r\n#else\r\n    typedef double real;\r\n#endif\r\n\r\n    /**\r\n     * @return the number of bits of precision in a real number.\r\n     **********************************************************************/\r\n    static int digits();\r\n\r\n    /**\r\n     * Set the binary precision of a real number.\r\n     *\r\n     * @param[in] ndigits the number of bits of precision.\r\n     * @return the resulting number of bits of precision.\r\n     *\r\n     * This only has an effect when GEOGRAPHICLIB_PRECISION = 5.  See also\r\n     * Utility::set_digits for caveats about when this routine should be\r\n     * called.\r\n     **********************************************************************/\r\n    static int set_digits(int ndigits);\r\n\r\n    /**\r\n     * @return the number of decimal digits of precision in a real number.\r\n     **********************************************************************/\r\n    static int digits10();\r\n\r\n    /**\r\n     * Number of additional decimal digits of precision for real relative to\r\n     * double (0 for float).\r\n     **********************************************************************/\r\n    static int extra_digits();\r\n\r\n    /**\r\n     * true if the machine is big-endian.\r\n     **********************************************************************/\r\n    static const bool bigendian = GEOGRAPHICLIB_WORDS_BIGENDIAN;\r\n\r\n    /**\r\n     * @tparam T the type of the returned value.\r\n     * @return &pi;.\r\n     **********************************************************************/\r\n    template<typename T> static T pi() {\r\n      using std::atan2;\r\n      static const T pi = atan2(T(0), T(-1));\r\n      return pi;\r\n    }\r\n    /**\r\n     * A synonym for pi<real>().\r\n     **********************************************************************/\r\n    static real pi() { return pi<real>(); }\r\n\r\n    /**\r\n     * @tparam T the type of the returned value.\r\n     * @return the number of radians in a degree.\r\n     **********************************************************************/\r\n    template<typename T> static T degree() {\r\n      static const T degree = pi<T>() / 180;\r\n      return degree;\r\n    }\r\n    /**\r\n     * A synonym for degree<real>().\r\n     **********************************************************************/\r\n    static real degree() { return degree<real>(); }\r\n\r\n    /**\r\n     * Square a number.\r\n     *\r\n     * @tparam T the type of the argument and the returned value.\r\n     * @param[in] x\r\n     * @return <i>x</i><sup>2</sup>.\r\n     **********************************************************************/\r\n    template<typename T> static T sq(T x)\r\n    { return x * x; }\r\n\r\n    /**\r\n     * The hypotenuse function avoiding underflow and overflow.\r\n     *\r\n     * @tparam T the type of the arguments and the returned value.\r\n     * @param[in] x\r\n     * @param[in] y\r\n     * @return sqrt(<i>x</i><sup>2</sup> + <i>y</i><sup>2</sup>).\r\n     **********************************************************************/\r\n    template<typename T> static T hypot(T x, T y);\r\n\r\n    /**\r\n     * exp(\\e x) &minus; 1 accurate near \\e x = 0.\r\n     *\r\n     * @tparam T the type of the argument and the returned value.\r\n     * @param[in] x\r\n     * @return exp(\\e x) &minus; 1.\r\n     **********************************************************************/\r\n    template<typename T> static T expm1(T x);\r\n\r\n    /**\r\n     * log(1 + \\e x) accurate near \\e x = 0.\r\n     *\r\n     * @tparam T the type of the argument and the returned value.\r\n     * @param[in] x\r\n     * @return log(1 + \\e x).\r\n     **********************************************************************/\r\n    template<typename T> static T log1p(T x);\r\n\r\n    /**\r\n     * The inverse hyperbolic sine function.\r\n     *\r\n     * @tparam T the type of the argument and the returned value.\r\n     * @param[in] x\r\n     * @return asinh(\\e x).\r\n     **********************************************************************/\r\n    template<typename T> static T asinh(T x);\r\n\r\n    /**\r\n     * The inverse hyperbolic tangent function.\r\n     *\r\n     * @tparam T the type of the argument and the returned value.\r\n     * @param[in] x\r\n     * @return atanh(\\e x).\r\n     **********************************************************************/\r\n    template<typename T> static T atanh(T x);\r\n\r\n    /**\r\n     * Copy the sign.\r\n     *\r\n     * @tparam T the type of the argument.\r\n     * @param[in] x gives the magitude of the result.\r\n     * @param[in] y gives the sign of the result.\r\n     * @return value with the magnitude of \\e x and with the sign of \\e y.\r\n     *\r\n     * This routine correctly handles the case \\e y = &minus;0, returning\r\n     * &minus|<i>x</i>|.\r\n     **********************************************************************/\r\n    template<typename T> static T copysign(T x, T y);\r\n\r\n    /**\r\n     * The cube root function.\r\n     *\r\n     * @tparam T the type of the argument and the returned value.\r\n     * @param[in] x\r\n     * @return the real cube root of \\e x.\r\n     **********************************************************************/\r\n    template<typename T> static T cbrt(T x);\r\n\r\n    /**\r\n     * The remainder function.\r\n     *\r\n     * @tparam T the type of the arguments and the returned value.\r\n     * @param[in] x\r\n     * @param[in] y\r\n     * @return the remainder of \\e x/\\e y in the range [&minus;\\e y/2, \\e y/2].\r\n     **********************************************************************/\r\n    template<typename T> static T remainder(T x, T y);\r\n\r\n    /**\r\n     * The remquo function.\r\n     *\r\n     * @tparam T the type of the arguments and the returned value.\r\n     * @param[in] x\r\n     * @param[in] y\r\n     * @param[out] n the low 3 bits of the quotient\r\n     * @return the remainder of \\e x/\\e y in the range [&minus;\\e y/2, \\e y/2].\r\n     **********************************************************************/\r\n    template<typename T> static T remquo(T x, T y, int* n);\r\n\r\n    /**\r\n     * The round function.\r\n     *\r\n     * @tparam T the type of the argument and the returned value.\r\n     * @param[in] x\r\n     * @return \\e x round to the nearest integer (ties round away from 0).\r\n     **********************************************************************/\r\n    template<typename T> static T round(T x);\r\n\r\n    /**\r\n     * The lround function.\r\n     *\r\n     * @tparam T the type of the argument.\r\n     * @param[in] x\r\n     * @return \\e x round to the nearest integer as a long int (ties round away\r\n     *   from 0).\r\n     *\r\n     * If the result does not fit in a long int, the return value is undefined.\r\n     **********************************************************************/\r\n    template<typename T> static long lround(T x);\r\n\r\n    /**\r\n     * Fused multiply and add.\r\n     *\r\n     * @tparam T the type of the arguments and the returned value.\r\n     * @param[in] x\r\n     * @param[in] y\r\n     * @param[in] z\r\n     * @return <i>xy</i> + <i>z</i>, correctly rounded (on those platforms with\r\n     *   support for the <code>fma</code> instruction).\r\n     *\r\n     * On platforms without the <code>fma</code> instruction, no attempt is\r\n     * made to improve on the result of a rounded multiplication followed by a\r\n     * rounded addition.\r\n     **********************************************************************/\r\n    template<typename T> static T fma(T x, T y, T z);\r\n\r\n    /**\r\n     * Normalize a two-vector.\r\n     *\r\n     * @tparam T the type of the argument and the returned value.\r\n     * @param[in,out] x on output set to <i>x</i>/hypot(<i>x</i>, <i>y</i>).\r\n     * @param[in,out] y on output set to <i>y</i>/hypot(<i>x</i>, <i>y</i>).\r\n     **********************************************************************/\r\n    template<typename T> static void norm(T& x, T& y)\r\n    { T h = hypot(x, y); x /= h; y /= h; }\r\n\r\n    /**\r\n     * The error-free sum of two numbers.\r\n     *\r\n     * @tparam T the type of the argument and the returned value.\r\n     * @param[in] u\r\n     * @param[in] v\r\n     * @param[out] t the exact error given by (\\e u + \\e v) - \\e s.\r\n     * @return \\e s = round(\\e u + \\e v).\r\n     *\r\n     * See D. E. Knuth, TAOCP, Vol 2, 4.2.2, Theorem B.  (Note that \\e t can be\r\n     * the same as one of the first two arguments.)\r\n     **********************************************************************/\r\n    template<typename T> static T sum(T u, T v, T& t);\r\n\r\n    /**\r\n     * Evaluate a polynomial.\r\n     *\r\n     * @tparam T the type of the arguments and returned value.\r\n     * @param[in] N the order of the polynomial.\r\n     * @param[in] p the coefficient array (of size \\e N + 1).\r\n     * @param[in] x the variable.\r\n     * @return the value of the polynomial.\r\n     *\r\n     * Evaluate <i>y</i> = &sum;<sub><i>n</i>=0..<i>N</i></sub>\r\n     * <i>p</i><sub><i>n</i></sub> <i>x</i><sup><i>N</i>&minus;<i>n</i></sup>.\r\n     * Return 0 if \\e N &lt; 0.  Return <i>p</i><sub>0</sub>, if \\e N = 0 (even\r\n     * if \\e x is infinite or a nan).  The evaluation uses Horner's method.\r\n     **********************************************************************/\r\n    template<typename T> static T polyval(int N, const T p[], T x)\r\n    // This used to employ Math::fma; but that's too slow and it seemed not to\r\n    // improve the accuracy noticeably.  This might change when there's direct\r\n    // hardware support for fma.\r\n    { T y = N < 0 ? 0 : *p++; while (--N >= 0) y = y * x + *p++; return y; }\r\n\r\n    /**\r\n     * Normalize an angle.\r\n     *\r\n     * @tparam T the type of the argument and returned value.\r\n     * @param[in] x the angle in degrees.\r\n     * @return the angle reduced to the range (&minus;180&deg;, 180&deg;].\r\n     *\r\n     * The range of \\e x is unrestricted.\r\n     **********************************************************************/\r\n    template<typename T> static T AngNormalize(T x) {\r\n      x = remainder(x, T(360)); return x != -180 ? x : 180;\r\n    }\r\n\r\n    /**\r\n     * Normalize a latitude.\r\n     *\r\n     * @tparam T the type of the argument and returned value.\r\n     * @param[in] x the angle in degrees.\r\n     * @return x if it is in the range [&minus;90&deg;, 90&deg;], otherwise\r\n     *   return NaN.\r\n     **********************************************************************/\r\n    template<typename T> static T LatFix(T x)\r\n    { using std::abs; return abs(x) > 90 ? NaN<T>() : x; }\r\n\r\n    /**\r\n     * The exact difference of two angles reduced to\r\n     * (&minus;180&deg;, 180&deg;].\r\n     *\r\n     * @tparam T the type of the arguments and returned value.\r\n     * @param[in] x the first angle in degrees.\r\n     * @param[in] y the second angle in degrees.\r\n     * @param[out] e the error term in degrees.\r\n     * @return \\e d, the truncated value of \\e y &minus; \\e x.\r\n     *\r\n     * This computes \\e z = \\e y &minus; \\e x exactly, reduced to\r\n     * (&minus;180&deg;, 180&deg;]; and then sets \\e z = \\e d + \\e e where \\e d\r\n     * is the nearest representable number to \\e z and \\e e is the truncation\r\n     * error.  If \\e d = &minus;180, then \\e e &gt; 0; If \\e d = 180, then \\e e\r\n     * &le; 0.\r\n     **********************************************************************/\r\n    template<typename T> static T AngDiff(T x, T y, T& e) {\r\n      T t, d = AngNormalize(sum(remainder(-x, T(360)),\r\n                                remainder( y, T(360)), t));\r\n      // Here y - x = d + t (mod 360), exactly, where d is in (-180,180] and\r\n      // abs(t) <= eps (eps = 2^-45 for doubles).  The only case where the\r\n      // addition of t takes the result outside the range (-180,180] is d = 180\r\n      // and t > 0.  The case, d = -180 + eps, t = -eps, can't happen, since\r\n      // sum would have returned the exact result in such a case (i.e., given t\r\n      // = 0).\r\n      return sum(d == 180 && t > 0 ? -180 : d, t, e);\r\n    }\r\n\r\n    /**\r\n     * Difference of two angles reduced to [&minus;180&deg;, 180&deg;]\r\n     *\r\n     * @tparam T the type of the arguments and returned value.\r\n     * @param[in] x the first angle in degrees.\r\n     * @param[in] y the second angle in degrees.\r\n     * @return \\e y &minus; \\e x, reduced to the range [&minus;180&deg;,\r\n     *   180&deg;].\r\n     *\r\n     * The result is equivalent to computing the difference exactly, reducing\r\n     * it to (&minus;180&deg;, 180&deg;] and rounding the result.  Note that\r\n     * this prescription allows &minus;180&deg; to be returned (e.g., if \\e x\r\n     * is tiny and negative and \\e y = 180&deg;).\r\n     **********************************************************************/\r\n    template<typename T> static T AngDiff(T x, T y)\r\n    { T e; return AngDiff(x, y, e); }\r\n\r\n    /**\r\n     * Coarsen a value close to zero.\r\n     *\r\n     * @tparam T the type of the argument and returned value.\r\n     * @param[in] x\r\n     * @return the coarsened value.\r\n     *\r\n     * The makes the smallest gap in \\e x = 1/16 &minus; nextafter(1/16, 0) =\r\n     * 1/2<sup>57</sup> for reals = 0.7 pm on the earth if \\e x is an angle in\r\n     * degrees.  (This is about 1000 times more resolution than we get with\r\n     * angles around 90&deg;.)  We use this to avoid having to deal with near\r\n     * singular cases when \\e x is non-zero but tiny (e.g.,\r\n     * 10<sup>&minus;200</sup>).  This converts &minus;0 to +0; however tiny\r\n     * negative numbers get converted to &minus;0.\r\n     **********************************************************************/\r\n    template<typename T> static T AngRound(T x);\r\n\r\n    /**\r\n     * Evaluate the sine and cosine function with the argument in degrees\r\n     *\r\n     * @tparam T the type of the arguments.\r\n     * @param[in] x in degrees.\r\n     * @param[out] sinx sin(<i>x</i>).\r\n     * @param[out] cosx cos(<i>x</i>).\r\n     *\r\n     * The results obey exactly the elementary properties of the trigonometric\r\n     * functions, e.g., sin 9&deg; = cos 81&deg; = &minus; sin 123456789&deg;.\r\n     * If x = &minus;0, then \\e sinx = &minus;0; this is the only case where\r\n     * &minus;0 is returned.\r\n     **********************************************************************/\r\n    template<typename T> static void sincosd(T x, T& sinx, T& cosx);\r\n\r\n    /**\r\n     * Evaluate the sine function with the argument in degrees\r\n     *\r\n     * @tparam T the type of the argument and the returned value.\r\n     * @param[in] x in degrees.\r\n     * @return sin(<i>x</i>).\r\n     **********************************************************************/\r\n    template<typename T> static T sind(T x);\r\n\r\n    /**\r\n     * Evaluate the cosine function with the argument in degrees\r\n     *\r\n     * @tparam T the type of the argument and the returned value.\r\n     * @param[in] x in degrees.\r\n     * @return cos(<i>x</i>).\r\n     **********************************************************************/\r\n    template<typename T> static T cosd(T x);\r\n\r\n    /**\r\n     * Evaluate the tangent function with the argument in degrees\r\n     *\r\n     * @tparam T the type of the argument and the returned value.\r\n     * @param[in] x in degrees.\r\n     * @return tan(<i>x</i>).\r\n     *\r\n     * If \\e x = &plusmn;90&deg;, then a suitably large (but finite) value is\r\n     * returned.\r\n     **********************************************************************/\r\n    template<typename T> static T tand(T x);\r\n\r\n    /**\r\n     * Evaluate the atan2 function with the result in degrees\r\n     *\r\n     * @tparam T the type of the arguments and the returned value.\r\n     * @param[in] y\r\n     * @param[in] x\r\n     * @return atan2(<i>y</i>, <i>x</i>) in degrees.\r\n     *\r\n     * The result is in the range (&minus;180&deg; 180&deg;].  N.B.,\r\n     * atan2d(&plusmn;0, &minus;1) = +180&deg;; atan2d(&minus;&epsilon;,\r\n     * &minus;1) = &minus;180&deg;, for &epsilon; positive and tiny;\r\n     * atan2d(&plusmn;0, +1) = &plusmn;0&deg;.\r\n     **********************************************************************/\r\n    template<typename T> static T atan2d(T y, T x);\r\n\r\n    /**\r\n     * Evaluate the atan function with the result in degrees\r\n     *\r\n     * @tparam T the type of the argument and the returned value.\r\n     * @param[in] x\r\n     * @return atan(<i>x</i>) in degrees.\r\n     **********************************************************************/\r\n   template<typename T> static T atand(T x);\r\n\r\n    /**\r\n     * Evaluate <i>e</i> atanh(<i>e x</i>)\r\n     *\r\n     * @tparam T the type of the argument and the returned value.\r\n     * @param[in] x\r\n     * @param[in] es the signed eccentricity =  sign(<i>e</i><sup>2</sup>)\r\n     *    sqrt(|<i>e</i><sup>2</sup>|)\r\n     * @return <i>e</i> atanh(<i>e x</i>)\r\n     *\r\n     * If <i>e</i><sup>2</sup> is negative (<i>e</i> is imaginary), the\r\n     * expression is evaluated in terms of atan.\r\n     **********************************************************************/\r\n    template<typename T> static T eatanhe(T x, T es);\r\n\r\n    /**\r\n     * tan&chi; in terms of tan&phi;\r\n     *\r\n     * @tparam T the type of the argument and the returned value.\r\n     * @param[in] tau &tau; = tan&phi;\r\n     * @param[in] es the signed eccentricity = sign(<i>e</i><sup>2</sup>)\r\n     *   sqrt(|<i>e</i><sup>2</sup>|)\r\n     * @return &tau;&prime; = tan&chi;\r\n     *\r\n     * See Eqs. (7--9) of\r\n     * C. F. F. Karney,\r\n     * <a href=\"https://doi.org/10.1007/s00190-011-0445-3\">\r\n     * Transverse Mercator with an accuracy of a few nanometers,</a>\r\n     * J. Geodesy 85(8), 475--485 (Aug. 2011)\r\n     * (preprint\r\n     * <a href=\"https://arxiv.org/abs/1002.1417\">arXiv:1002.1417</a>).\r\n     **********************************************************************/\r\n    template<typename T> static T taupf(T tau, T es);\r\n\r\n    /**\r\n     * tan&phi; in terms of tan&chi;\r\n     *\r\n     * @tparam T the type of the argument and the returned value.\r\n     * @param[in] taup &tau;&prime; = tan&chi;\r\n     * @param[in] es the signed eccentricity = sign(<i>e</i><sup>2</sup>)\r\n     *   sqrt(|<i>e</i><sup>2</sup>|)\r\n     * @return &tau; = tan&phi;\r\n     *\r\n     * See Eqs. (19--21) of\r\n     * C. F. F. Karney,\r\n     * <a href=\"https://doi.org/10.1007/s00190-011-0445-3\">\r\n     * Transverse Mercator with an accuracy of a few nanometers,</a>\r\n     * J. Geodesy 85(8), 475--485 (Aug. 2011)\r\n     * (preprint\r\n     * <a href=\"https://arxiv.org/abs/1002.1417\">arXiv:1002.1417</a>).\r\n     **********************************************************************/\r\n    template<typename T> static T tauf(T taup, T es);\r\n\r\n    /**\r\n     * Test for finiteness.\r\n     *\r\n     * @tparam T the type of the argument.\r\n     * @param[in] x\r\n     * @return true if number is finite, false if NaN or infinite.\r\n     **********************************************************************/\r\n    template<typename T> static bool isfinite(T x);\r\n\r\n    /**\r\n     * The NaN (not a number)\r\n     *\r\n     * @tparam T the type of the returned value.\r\n     * @return NaN if available, otherwise return the max real of type T.\r\n     **********************************************************************/\r\n    template<typename T> static T NaN();\r\n\r\n    /**\r\n     * A synonym for NaN<real>().\r\n     **********************************************************************/\r\n    static real NaN() { return NaN<real>(); }\r\n\r\n    /**\r\n     * Test for NaN.\r\n     *\r\n     * @tparam T the type of the argument.\r\n     * @param[in] x\r\n     * @return true if argument is a NaN.\r\n     **********************************************************************/\r\n    template<typename T> static bool isnan(T x);\r\n\r\n    /**\r\n     * Infinity\r\n     *\r\n     * @tparam T the type of the returned value.\r\n     * @return infinity if available, otherwise return the max real.\r\n     **********************************************************************/\r\n    template<typename T> static T infinity();\r\n\r\n    /**\r\n     * A synonym for infinity<real>().\r\n     **********************************************************************/\r\n    static real infinity() { return infinity<real>(); }\r\n\r\n    /**\r\n     * Swap the bytes of a quantity\r\n     *\r\n     * @tparam T the type of the argument and the returned value.\r\n     * @param[in] x\r\n     * @return x with its bytes swapped.\r\n     **********************************************************************/\r\n    template<typename T> static T swab(T x) {\r\n      union {\r\n        T r;\r\n        unsigned char c[sizeof(T)];\r\n      } b;\r\n      b.r = x;\r\n      for (int i = sizeof(T)/2; i--; )\r\n        std::swap(b.c[i], b.c[sizeof(T) - 1 - i]);\r\n      return b.r;\r\n    }\r\n\r\n  };\r\n\r\n} // namespace GeographicLib\r\n\r\n#endif  // GEOGRAPHICLIB_MATH_HPP\r\n", "meta": {"hexsha": "dc13a1b06c56f39d3d90b50442436ff4fd42cbc1", "size": 25311, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/GeographicLib/Math.hpp", "max_stars_repo_name": "uav4geo/GeographicLib", "max_stars_repo_head_hexsha": "4427486381b405a02127688f1e7257cf85be912b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/GeographicLib/Math.hpp", "max_issues_repo_name": "uav4geo/GeographicLib", "max_issues_repo_head_hexsha": "4427486381b405a02127688f1e7257cf85be912b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/GeographicLib/Math.hpp", "max_forks_repo_name": "uav4geo/GeographicLib", "max_forks_repo_head_hexsha": "4427486381b405a02127688f1e7257cf85be912b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0601851852, "max_line_length": 80, "alphanum_fraction": 0.4997827032, "num_tokens": 6224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.2989226068355507}}
{"text": "// File: insert.cpp\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nusing namespace mtl;\n\ntemplate <typename Matrix>\nvoid fill(Matrix& m)\n{\n    // Matrices are not initialized by default\n    m= 0.0;\n\n    // Create inserter for matrix m\n    mat::inserter<Matrix> ins(m);\n    \n    // Insert value in m[0][0]\n    ins[0][0] << 2.0;\n    ins[1][2] << 0.5;\n    ins[2][1] << 3.0;\n\n    // Destructor of ins sets final state of m\n}\n\ntemplate <typename Matrix>\nvoid modify(Matrix& m)\n{\n    // Type of m's elements\n    typedef typename Collection<Matrix>::value_type value_type;\n\n    // Create inserter for matrix m\n    // Existing values are not overwritten but inserted\n    mat::inserter<Matrix, update_plus<value_type> > ins(m, 3);\n    \n    // Increment value in m[0][0]\n    ins[0][0] << 1.0;\n\n    // Elements that doesn't exist (in sparse matrices) are inserted\n    ins[1][1] << 2.5;\n    ins[2][1] << 1.0;\n    ins[2][2] << 4.0;\n\n    // Destructor of ins sets final state of m\n}\n\nint main(int, char**)\n{\n    // Matrices of different types\n    compressed2D<double>              A(3, 3);\n    dense2D<double>                   B(3, 3);\n    morton_dense<float, morton_mask>  C(3, 3);\n\n    // Fill the matrices generically\n    fill(A); fill(B); fill(C);\n    std::cout << \"A is \\n\" << A << \"\\nB is \\n\" << B << \"\\nC is \\n\" << C;\n\n    // Modify the matrices generically\n    modify(A); modify(B); modify(C);\n    std::cout << \"\\n\\nAfter modification:\\nA is \\n\" << A \n\t      << \"\\nB is \\n\" << B << \"\\nC is \\n\" << C;\n\n    return 0;\n}\n\n", "meta": {"hexsha": "7366b95b321f7fef1306a9e0bbea438359fad4aa", "size": 1525, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/insert.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/examples/insert.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/examples/insert.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 23.4615384615, "max_line_length": 72, "alphanum_fraction": 0.5744262295, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.2988502769805688}}
{"text": "//  Copyright Thijs van den Berg, 2008.\r\n//  Copyright John Maddock 2008.\r\n//  Copyright Paul A. Bristow 2008.\r\n\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// This module implements the Laplace distribution.\r\n// Weisstein, Eric W. \"Laplace Distribution.\" From MathWorld--A Wolfram Web Resource.\r\n// http://mathworld.wolfram.com/LaplaceDistribution.html\r\n// http://en.wikipedia.org/wiki/Laplace_distribution\r\n//\r\n// Abramowitz and Stegun 1972, p 930\r\n// http://www.math.sfu.ca/~cbm/aands/page_930.htm\r\n\r\n#ifndef BOOST_STATS_LAPLACE_HPP\r\n#define BOOST_STATS_LAPLACE_HPP\r\n\r\n#include <boost/math/distributions/detail/common_error_handling.hpp>\r\n#include <boost/math/distributions/complement.hpp>\r\n#include <boost/math/constants/constants.hpp>\r\n#include <limits>\r\n\r\nnamespace boost{ namespace math{\r\n\r\ntemplate <class RealType = double, class Policy = policies::policy<> >\r\nclass laplace_distribution\r\n{\r\npublic:\r\n   // ----------------------------------\r\n   // public Types\r\n   // ----------------------------------\r\n   typedef RealType value_type;\r\n   typedef Policy policy_type;\r\n\r\n   // ----------------------------------\r\n   // Constructor(s)\r\n   // ----------------------------------\r\n   laplace_distribution(RealType location = 0, RealType scale = 1)\r\n      : m_location(location), m_scale(scale)\r\n   {\r\n      RealType result;\r\n      check_parameters(\"boost::math::laplace_distribution<%1%>::laplace_distribution()\", &result);\r\n   }\r\n\r\n\r\n   // ----------------------------------\r\n   // Public functions\r\n   // ----------------------------------\r\n\r\n   RealType location() const\r\n   {\r\n      return m_location;\r\n   }\r\n\r\n   RealType scale() const\r\n   {\r\n      return m_scale;\r\n   }\r\n\r\n   bool check_parameters(const char* function, RealType* result) const\r\n   {\r\n         if(false == detail::check_scale(function, m_scale, result, Policy())) return false;\r\n         if(false == detail::check_location(function, m_location, result, Policy())) return false;\r\n         return true;\r\n   }\r\n\r\n\r\nprivate:\r\n   RealType m_location;\r\n   RealType m_scale;\r\n\r\n}; // class laplace_distribution\r\n\r\n\r\n\r\n//\r\n// Convenient type synonym\r\n//\r\ntypedef laplace_distribution<double> laplace;\r\n\r\n//\r\n// Non member functions\r\n//\r\ntemplate <class RealType, class Policy>\r\ninline const std::pair<RealType, RealType> range(const laplace_distribution<RealType, Policy>&)\r\n{\r\n   using boost::math::tools::max_value;\r\n   return std::pair<RealType, RealType>(-max_value<RealType>(), max_value<RealType>());\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline const std::pair<RealType, RealType> support(const laplace_distribution<RealType, Policy>&)\r\n{\r\n   using boost::math::tools::max_value;\r\n   return std::pair<RealType, RealType>(-max_value<RealType>(),  max_value<RealType>());\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType pdf(const laplace_distribution<RealType, Policy>& dist, const RealType& x)\r\n{\r\n   BOOST_MATH_STD_USING // for ADL of std functions\r\n\r\n   // Checking function argument\r\n   RealType result;\r\n   const char* function = \"boost::math::pdf(const laplace_distribution<%1%>&, %1%))\";\r\n   if (false == dist.check_parameters(function, &result)) return result;\r\n   if (false == detail::check_x(function, x, &result, Policy())) return result;\r\n\r\n   // Special pdf values\r\n   if((boost::math::isinf)(x))\r\n      return 0; // pdf + and - infinity is zero.\r\n\r\n   // General case\r\n   RealType scale( dist.scale() );\r\n   RealType location( dist.location() );\r\n\r\n   RealType exponent = x - location;\r\n   if (exponent>0) exponent = -exponent;\r\n   exponent /= scale;\r\n\r\n   result = exp(exponent);\r\n   result /= 2 * scale;\r\n\r\n   return result;\r\n} // pdf\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType cdf(const laplace_distribution<RealType, Policy>& dist, const RealType& x)\r\n{\r\n   BOOST_MATH_STD_USING  // for ADL of std functions\r\n\r\n   // Checking function argument\r\n   RealType result;\r\n   const char* function = \"boost::math::cdf(const laplace_distribution<%1%>&, %1%)\";\r\n   if (false == dist.check_parameters(function, &result)) return result;\r\n   if (false == detail::check_x(function, x, &result, Policy())) return result;\r\n\r\n   // Special cdf values\r\n   if((boost::math::isinf)(x))\r\n   {\r\n     if(x < 0) return 0; // -infinity\r\n     return 1; // + infinity\r\n   }\r\n\r\n   // General cdf  values\r\n   RealType scale( dist.scale() );\r\n   RealType location( dist.location() );\r\n\r\n   if (x < location)\r\n      result = exp( (x-location)/scale )/2;\r\n   else\r\n      result = 1 - exp( (location-x)/scale )/2;\r\n\r\n   return result;\r\n} // cdf\r\n\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType quantile(const laplace_distribution<RealType, Policy>& dist, const RealType& p)\r\n{\r\n   BOOST_MATH_STD_USING // for ADL of std functions\r\n\r\n   // Checking function argument\r\n   RealType result;\r\n   const char* function = \"boost::math::quantile(const laplace_distribution<%1%>&, %1%)\";\r\n   if (false == dist.check_parameters(function, &result)) return result;\r\n   if(false == detail::check_probability(function, p, &result, Policy())) return result;\r\n\r\n   // extreme values\r\n   if(p == 0) return -std::numeric_limits<RealType>::infinity();\r\n   if(p == 1) return std::numeric_limits<RealType>::infinity();\r\n\r\n   // Calculate Quantile\r\n   RealType scale( dist.scale() );\r\n   RealType location( dist.location() );\r\n\r\n   if (p - 0.5 < 0.0)\r\n      result = location + scale*log( static_cast<RealType>(p*2) );\r\n   else\r\n      result = location - scale*log( static_cast<RealType>(-p*2 + 2) );\r\n\r\n   return result;\r\n} // quantile\r\n\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType cdf(const complemented2_type<laplace_distribution<RealType, Policy>, RealType>& c)\r\n{\r\n   BOOST_MATH_STD_USING // for ADL of std functions\r\n\r\n   RealType scale = c.dist.scale();\r\n   RealType location = c.dist.location();\r\n   RealType x = c.param;\r\n\r\n   // Checking function argument\r\n   RealType result;\r\n   const char* function = \"boost::math::cdf(const complemented2_type<laplace_distribution<%1%>, %1%>&)\";\r\n   if(false == detail::check_x(function, x, &result, Policy()))return result;\r\n\r\n   // Calculate cdf\r\n\r\n   // Special cdf value\r\n   if((boost::math::isinf)(x))\r\n   {\r\n     if(x < 0) return 1; // cdf complement -infinity is unity.\r\n     return 0; // cdf complement +infinity is zero\r\n   }\r\n\r\n   // Cdf interval value\r\n   if (-x < location)\r\n      result = exp( (-x-location)/scale )/2;\r\n   else\r\n      result = 1 - exp( (location+x)/scale )/2;\r\n\r\n   return result;\r\n} // cdf complement\r\n\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType quantile(const complemented2_type<laplace_distribution<RealType, Policy>, RealType>& c)\r\n{\r\n   BOOST_MATH_STD_USING // for ADL of std functions\r\n\r\n   // Calculate quantile\r\n   RealType scale = c.dist.scale();\r\n   RealType location = c.dist.location();\r\n   RealType q = c.param;\r\n\r\n   // Checking function argument\r\n   RealType result;\r\n   const char* function = \"quantile(const complemented2_type<laplace_distribution<%1%>, %1%>&)\";\r\n   if(false == detail::check_probability(function, q, &result, Policy())) return result;\r\n\r\n\r\n   // extreme values\r\n   if(q == 0) return std::numeric_limits<RealType>::infinity();\r\n   if(q == 1) return -std::numeric_limits<RealType>::infinity();\r\n\r\n   if (0.5 - q < 0.0)\r\n      result = location + scale*log( static_cast<RealType>(-q*2 + 2) );\r\n   else\r\n      result = location - scale*log( static_cast<RealType>(q*2) );\r\n\r\n\r\n   return result;\r\n} // quantile\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType mean(const laplace_distribution<RealType, Policy>& dist)\r\n{\r\n   return dist.location();\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType standard_deviation(const laplace_distribution<RealType, Policy>& dist)\r\n{\r\n   return constants::root_two<RealType>() * dist.scale();\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType mode(const laplace_distribution<RealType, Policy>& dist)\r\n{\r\n   return dist.location();\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType median(const laplace_distribution<RealType, Policy>& dist)\r\n{\r\n   return dist.location();\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType skewness(const laplace_distribution<RealType, Policy>& /*dist*/)\r\n{\r\n   return 0;\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType kurtosis(const laplace_distribution<RealType, Policy>& /*dist*/)\r\n{\r\n   return 6;\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType kurtosis_excess(const laplace_distribution<RealType, Policy>& /*dist*/)\r\n{\r\n   return 3;\r\n}\r\n\r\n} // namespace math\r\n} // namespace boost\r\n\r\n// This include must be at the end, *after* the accessors\r\n// for this distribution have been defined, in order to\r\n// keep compilers that support two-phase lookup happy.\r\n#include <boost/math/distributions/detail/derived_accessors.hpp>\r\n\r\n#endif // BOOST_STATS_LAPLACE_HPP\r\n\r\n\r\n", "meta": {"hexsha": "c8814d99e5195e28e687754eeef4ab5e72414341", "size": 9014, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Compiler/boost/boost/math/distributions/laplace.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/math/distributions/laplace.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/math/distributions/laplace.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": 29.7491749175, "max_line_length": 105, "alphanum_fraction": 0.6575327269, "num_tokens": 2187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.2988502769805688}}
{"text": "\n/*\n * OptimalControlProblem.hpp\n *\n *  Created on: July 7, 2019\n *      Author: Quincy Jones\n *\n * Copyright (c) <2019> <Quincy Jones - quincy@implementedrobotics.com/>\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the Software\n * is furnished to do so, subject to the following conditions:\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n#ifndef NOMAD_CORE_OPTIMALCONTROL_OPTIMALCONTROLPROBLEM_H_\n#define NOMAD_CORE_OPTIMALCONTROL_OPTIMALCONTROLPROBLEM_H_\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <qpOASES.hpp>\n\nnamespace OptimalControl\n{\n\n    class OptimalControlProblem\n    {\n\n    public:\n        // Base Class Optimal Control Problem\n        // N = Prediction Steps\n        // T = Horizon Length\n        // num_states = Number of States of OCP\n        // num_inputs = Number of Inputs of OCP\n        OptimalControlProblem(const unsigned int N, const double T, const unsigned int num_states, const unsigned int num_inputs, const unsigned int max_iterations = 1000);\n\n        // Solve\n        virtual void Solve() = 0;\n\n        // Get System State Trajectory Vector\n        // TODO: Compute this depending on U solutions.  X_ = Ax+Bu\n        // TODO: Make pure virtual\n        virtual Eigen::MatrixXd X() const { return X_; }\n\n        //Get Current Input Sequence Solution\n        Eigen::MatrixXd U() const { return U_; }\n\n        // Set Weight Matrices\n        virtual void SetWeights(const Eigen::VectorXd &Q, const Eigen::VectorXd &R)\n        {\n            // TODO: Verify Vector Size Matches correct state and inputs\n            Q_ = Q.matrix().asDiagonal().toDenseMatrix();\n            R_ = R.matrix().asDiagonal().toDenseMatrix();\n        }\n\n        // Set Problem Initial Condition\n        void SetInitialCondition(const Eigen::VectorXd &x_0) { x_0_ = x_0; }\n\n        // Set Reference Trajectory\n        void SetReference(const Eigen::MatrixXd &X_ref) { X_ref_ = X_ref; }\n\n        // Time step sample time\n        double SampleTime() const { return T_s_; }\n\n        // Prediction Horizon Steps\n        int N() const { return N_; }\n\n    protected:\n        Eigen::VectorXd x_0_;   // Current State/Initial Condition\n        Eigen::MatrixXd X_ref_; // Reference Trajectory\n\n        Eigen::MatrixXd X_; // System State Trajectory\n        Eigen::MatrixXd U_; // Optimal Control Input Sequence Solution\n\n        Eigen::MatrixXd Q_; // State Weights\n        Eigen::MatrixXd R_; // Input Weights\n\n        int num_states_; // Number of System States\n        int num_inputs_; // Number of System Inputs\n\n        int N_; // Number of Prediction Steps\n\n        double T_s_; // Sample Time\n        double T_;   // Horizon Length\n\n        qpOASES::int_t max_iterations_;    // Max Iterations for Solver\n        qpOASES::int_t solver_iterations_; // Total number of Solver iterations for solution\n        double solver_time_;    // Total time for Solver to compute a solution\n\n        bool solved_;\n        // TODO:\n        // Infeasible, BlahBlah\n    };\n} // namespace OptimalControl\n\nnamespace OptimalControl\n{\n    namespace LinearOptimalControl\n    {\n        class LinearOptimalControlProblem : public OptimalControlProblem\n        {\n        public:\n            // Base Class Linear Optimal Control Problem\n            // N = Prediction Steps\n            // T = Horizon Length\n            // num_states = Number of States of OCP\n            // num_inputs = Number of Inputs of OCP\n            // max_iterations = Maximum number of solver iterations\n            LinearOptimalControlProblem(const unsigned int N,\n                                        const double T,\n                                        const unsigned int num_states,\n                                        const unsigned int num_inputs,\n                                        const unsigned int max_iterations = 1000);\n\n            // Set Model Matrices\n            void SetModelMatrices(const Eigen::MatrixXd &A, const Eigen::MatrixXd &B)\n            {\n                A_ = A;\n                B_ = B;\n            }\n\n            // Solve\n            virtual void Solve();\n\n        protected:\n            Eigen::MatrixXd A_; // System State Transition Matrix\n            Eigen::MatrixXd B_; // Control Input Matrix\n        };\n    } // namespace LinearOptimalControl\n} // namespace OptimalControl\n\n#endif // NOMAD_CORE_OPTIMALCONTROL_OPTIMALCONTROLPROBLEM_H_\n", "meta": {"hexsha": "e0445755a03887bff16897d2ee2db6949d7ef63a", "size": 5237, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Software/Core/OptimalControl/include/OptimalControl/OptimalControlProblem.hpp", "max_stars_repo_name": "implementedrobotics/Nomad", "max_stars_repo_head_hexsha": "de8c27ed79cdcde59b1fd6e9a0865d29b84b7d58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2019-08-11T18:24:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T01:22:55.000Z", "max_issues_repo_path": "Software/Core/OptimalControl/include/OptimalControl/OptimalControlProblem.hpp", "max_issues_repo_name": "implementedrobotics/Nomad", "max_issues_repo_head_hexsha": "de8c27ed79cdcde59b1fd6e9a0865d29b84b7d58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2019-05-29T12:57:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-29T02:26:06.000Z", "max_forks_repo_path": "Software/Core/OptimalControl/include/OptimalControl/OptimalControlProblem.hpp", "max_forks_repo_name": "implementedrobotics/Nomad", "max_forks_repo_head_hexsha": "de8c27ed79cdcde59b1fd6e9a0865d29b84b7d58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-08-12T03:05:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T05:34:16.000Z", "avg_line_length": 37.1418439716, "max_line_length": 172, "alphanum_fraction": 0.6408248998, "num_tokens": 1123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.2986334267609958}}
{"text": "#define NO_IMPORT_ARRAY\n\n#include <complex>\n#include <stdint.h>\n#include <stdio.h>\n#include <vector>\n#include <string>\nextern \"C\" {\n  #include <cblas.h>\n  // Additional prototypes for Fortran LAPACK routines.\n  // sposv: solve Ax = b for A positive definite.\n  void sposv_(const char* uplo, int* n, int* nrhs, float* a, int* lda,\n              float* b, int* ldb, int* info );\n}\n\n#include <boost/python.hpp>\n\n#include <pybindings.h>\n#include \"so3g_numpy.h\"\n#include \"numpy_assist.h\"\n#include \"Ranges.h\"\n\n// TODO: Generalize to double precision too.\n// This implements Jon's noise model for ACT. It takes in\n// * ft[ndet,nfreq]        the fourier transform of the time-ordered data\n// * bins[nbin,{from,to}]  the start and end of each bin\n// * iD[nbin,ndet]         the inverse uncorrelated variance for each detector per bin\n// * iV[nbin,ndet,nvec]    matrix representing the scaled eivenvectors per bin\nvoid nmat_detvecs_apply(const bp::object & ft, const bp::object & bins, const bp::object & iD, const bp::object & iV, float s, float norm) {\n\t// Should pass in this too\n\tBufferWrapper<float>               ft_buf  (\"ft\",   ft,   false, std::vector<int>{-1,-1});\n\tBufferWrapper<int32_t>             bins_buf(\"bins\", bins, false, std::vector<int>{-1, 2});\n\tint ndet = ft_buf->shape[0], nmode = ft_buf->shape[1], nbin = bins_buf->shape[0];\n\tBufferWrapper<float>               iD_buf  (\"iD\",   iD,   false, std::vector<int>{nbin,ndet});\n\tBufferWrapper<float>               iV_buf  (\"iV\",   iV,   false, std::vector<int>{nbin,ndet,-1});\n\tint nvec = iV_buf->shape[2];\n\tif (ft_buf->strides[1] != ft_buf->itemsize || ft_buf->strides[0] != ft_buf->itemsize*nmode)\n\t\tthrow buffer_exception(\"ft must be C-contiguous along last axis\");\n\tif (bins_buf->strides[1] != bins_buf->itemsize || bins_buf->strides[0] != bins_buf->itemsize*2)\n\t\tthrow buffer_exception(\"bins must be C-contiguous along last axis\");\n\tif (iD_buf->strides[1] != iD_buf->itemsize || iD_buf->strides[0] != iD_buf->itemsize*ndet)\n\t\tthrow buffer_exception(\"iD must be C-contiguous along last axis\");\n\tif (iV_buf->strides[2] != iV_buf->itemsize || iV_buf->strides[1] != iV_buf->itemsize*nvec || iV_buf->strides[0] != iV_buf->itemsize*nvec*ndet)\n\t\tthrow buffer_exception(\"iV must be C-contiguous along last axis\");\n\t// Internally we work with a real view of ft, with twice as many elements to compensate\n\t//int nmode = 2*nfreq;\n\tfloat   * ft_   = (float*)   ft_buf->buf;\n\tint32_t * bins_ = (int32_t*) bins_buf->buf;\n\tfloat   * iD_   = (float*)   iD_buf->buf;\n\tfloat   * iV_   = (float*)   iV_buf->buf;\n\n\t// Ok, actually do the work\n\tfor(int bi = 0; bi < nbin; bi++) {\n\t\tint b1 = min(2*bins_[2*bi+0],nmode-1);\n\t\tint b2 = min(2*bins_[2*bi+1],nmode);\n\t\tint nm = b2-b1;\n\t\tfloat * biD = iD_ + bi*ndet;\n\t\tfloat * biV = iV_ + bi*ndet*nvec;\n\n\t\t// what I want to do\n\t\t// ft    = ftod[:,b[0]:b[1]]\n\t\t// iD    = self.iD[bi]/norm\n\t\t// iV    = self.iV[bi]/norm**0.5\n\t\t// ft[:] = iD[:,None]*ft + self.s*iV.dot(iV.T.dot(ft))\n\t\t// So first do iV.T [nvec,ndet] dot ft [ndet,nm] -> Q [nvec,nm]\n\t\tfloat * Q = new float[nvec*nm];\n\t\tcblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, nvec, nm, ndet, 1.0f, biV, nvec, ft_+b1, nmode, 0.0f, Q, nm);\n\t\t// Handle the uncorrelated part\n\t\t//#pragma omp parallel for\n\t\tfor(int di = 0; di < ndet; di++)\n\t\t\tfor(int i = b1; i < b2; i++)\n\t\t\t\tft_[di*nmode+i] *= biD[di]/norm;\n\t\t// Do ft += s*iV[ndet,nvec] dot Q [nvec,nm]\n\t\tcblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, ndet, nm, nvec, s/norm, biV, nvec, Q, nm, 1.0f, ft_+b1, nmode);\n\t\tdelete [] Q;\n\t}\n}\n\n// Support of maximum-liklihood sample cut handling. This got a bit long, so it should\n// probably be moved into its own file.\n\n// Forward declarations of helper functions\nint get_dtype(const bp::object &);\nint pcut_full_measure_helper(const vector<RangesInt32> &);\ntemplate <typename T> void pcut_full_tod2vals_helper(const vector<RangesInt32> &, T *, int, int, T *);\ntemplate <typename T> void pcut_full_vals2tod_helper(const vector<RangesInt32> &, T *, int, int, T *);\nint pcut_poly_measure_helper(const vector<RangesInt32> &, int, int nmax);\ntemplate <typename T> void pcut_poly_tod2vals_helper(const vector<RangesInt32> &, int, int, T *, int, int, T *);\ntemplate <typename T> void pcut_poly_vals2tod_helper(const vector<RangesInt32> &, int, int, T *, int, int, T *);\ntemplate <typename T> void pcut_clear_helper(const vector<RangesInt32> &, T *, int, int);\n\n// The main cuts processing function. In Maximum-likelihood map-making cuts are handled\n// as special degrees of freedom, and are part of the pointing matrix. This function\n// provides the operations corresponding to the cuts part of the pointing matrix P and\n// P'. In particular, operation == \"insert\" corresponds to the model-to-data matrix P,\n// while operation == \"extract\" corresponds to the data-to-model matrix P'. Additionally,\n// we provide operation == \"measure\", which doesn't touch any of the arrays, and just returns\n// how long the vals argument should be.\n//\n// Note that \"extract\" does not in general estimate the coefficients of the model. It just does\n// P'd, while the coefficients would (in the absence of any sky signal etc) be (P'P)'P'd.\n//\n// Arguments:\n//  range_matrix: the .ranges member of a python RangesMatrix\n//  operation: \"measure\", \"insert\" or \"extract\"\n//  model: The type of model used\n//   * \"full\": One degree of freedom per sample\n//   * \"poly\": Model is a legendre polynomial in each range.\n//        Order of poly determined by params[\"resolution\"] (samples per order) and params[\"nmax\"] (max order)\n//  tod:  numpy array with shape [ndet,nsamp] of dtype float32 or float64\n//  vals: numpy array with shape [:] of same dtype as tod. Holds the model degrees of freedom.\n//\n// TODO: To be able to process cuts in parallel, we need a lookup table for where in vals each\n// cut range starts. This will be fast enough to build on the fly. Would pass this as an extra\n// argument to the helper functions.\n\nint process_cuts(const bp::object & range_matrix, const std::string & operation, const std::string & model, const bp::dict & params, const bp::object & tod, const bp::object & vals) {\n\tauto ranges = extract_ranges<int32_t>(range_matrix);\n\t// Decoding these up here lets us avoid some duplication later\n\tint resolution, nmax;\n\tif     (model == \"full\") {}\n\telse if(model == \"poly\") {\n\t\tresolution = bp::extract<int>(params.get(\"resolution\"));\n\t\tnmax       = bp::extract<int>(params.get(\"nmax\"));\n\t} else throw general_exception(\"process_cuts model can only be 'full' or 'poly'\");\n\n\tif(operation == \"measure\") {\n\t\tif     (model == \"full\") return pcut_full_measure_helper(ranges);\n\t\telse if(model == \"poly\") return pcut_poly_measure_helper(ranges, resolution, nmax);\n\t} else {\n\t\tint dtype = get_dtype(tod);\n\t\tif(dtype == NPY_FLOAT) {\n\t\t\tBufferWrapper<float> tod_buf  (\"tod\",  tod,  false, std::vector<int>{-1,-1});\n\t\t\tBufferWrapper<float> vals_buf (\"vals\", vals, false, std::vector<int>{-1});\n\t\t\tint ndet = tod_buf->shape[0], nsamp = tod_buf->shape[1];\n\t\t\tif(operation == \"insert\") {\n\t\t\t\tif     (model == \"full\")\n\t\t\t\t\tpcut_full_vals2tod_helper(ranges, (float*)tod_buf->buf, ndet, nsamp, (float*) vals_buf->buf);\n\t\t\t\telse if(model == \"poly\")\n\t\t\t\t\tpcut_poly_vals2tod_helper(ranges, resolution, nmax, (float*)tod_buf->buf, ndet, nsamp, (float*) vals_buf->buf);\n\t\t\t} else if(operation == \"extract\") {\n\t\t\t\tif     (model == \"full\")\n\t\t\t\t\tpcut_full_tod2vals_helper(ranges, (float*)tod_buf->buf, ndet, nsamp, (float*) vals_buf->buf);\n\t\t\t\telse if(model == \"poly\")\n\t\t\t\t\tpcut_poly_tod2vals_helper(ranges, resolution, nmax, (float*)tod_buf->buf, ndet, nsamp, (float*) vals_buf->buf);\n\t\t\t} else if(operation == \"clear\") {\n\t\t\t\tpcut_clear_helper(ranges, (float*)tod_buf->buf, ndet, nsamp);\n\t\t\t} else throw general_exception(\"process_cuts operation can only be 'measure', 'insert' or 'extract'\");\n\t\t} else if(dtype == NPY_DOUBLE) {\n\t\t\tBufferWrapper<double> tod_buf  (\"tod\",  tod,  false, std::vector<int>{-1,-1});\n\t\t\tBufferWrapper<double> vals_buf (\"vals\", vals, false, std::vector<int>{-1});\n\t\t\tint ndet = tod_buf->shape[0], nsamp = tod_buf->shape[1];\n\t\t\tif(operation == \"insert\") {\n\t\t\t\tif     (model == \"full\")\n\t\t\t\t\tpcut_full_vals2tod_helper(ranges, (double*)tod_buf->buf, ndet, nsamp, (double*) vals_buf->buf);\n\t\t\t\telse if(model == \"poly\")\n\t\t\t\t\tpcut_poly_vals2tod_helper(ranges, resolution, nmax, (double*)tod_buf->buf, ndet, nsamp, (double*) vals_buf->buf);\n\t\t\t} else if(operation == \"extract\") {\n\t\t\t\tif     (model == \"full\")\n\t\t\t\t\tpcut_full_tod2vals_helper(ranges, (double*)tod_buf->buf, ndet, nsamp, (double*) vals_buf->buf);\n\t\t\t\telse if(model == \"poly\")\n\t\t\t\t\tpcut_poly_tod2vals_helper(ranges, resolution, nmax, (double*)tod_buf->buf, ndet, nsamp, (double*) vals_buf->buf);\n\t\t\t} else if(operation == \"clear\") {\n\t\t\t\tpcut_clear_helper(ranges, (float*)tod_buf->buf, ndet, nsamp);\n\t\t\t} else throw general_exception(\"process_cuts operation can only be 'measure', 'insert' or 'extract'\");\n\t\t} else throw general_exception(\"process_cuts only supports float32 and float64\");\n\t}\n\treturn 0;\n}\n\n// Helpers for the cuts\n\nint get_dtype(const bp::object & arr) {\n\tPyObject *ob = PyArray_FromAny(arr.ptr(), NULL, 0, 0, 0, NULL);\n\tif (ob == NULL) throw exception();\n\tPyArrayObject * a = reinterpret_cast<PyArrayObject*>(ob);\n\tint res = PyArray_TYPE(a);\n\tPy_DECREF(a);\n\treturn PyArray_TYPE(a);\n}\n\n// This is all from Jon's work for ACT.\nint get_npoly(int gapsize, int resolution, int nmax) {\n\tif(nmax < 1) nmax = 1;\n\tif     (gapsize <=  1) return min<int>(1, nmax);\n\telse if(gapsize <=  3) return min<int>(2, nmax);\n\telse if(gapsize <=  6) return min<int>(3, nmax);\n\telse if(gapsize <= 20) return min<int>(4, nmax);\n\telse return min<int>(5 + gapsize/resolution, nmax);\n}\n\n// Full cut treatment, with one degree of freedom for each sample in the cut\nint pcut_full_measure_helper(const vector<RangesInt32> & rangemat) {\n\tint n = 0;\n\tfor(int di = 0; di < rangemat.size(); di++)\n\t\tfor (auto const &r: rangemat[di].segments)\n\t\t\tn += r.second-r.first;\n\treturn n;\n}\ntemplate <typename T>\nvoid pcut_full_tod2vals_helper(const vector<RangesInt32> & rangemat, T * tod, int ndet, int nsamp, T * vals) {\n\tint i = 0;\n\tfor(int di = 0; di < rangemat.size(); di++)\n\t\tfor (auto const &r: rangemat[di].segments)\n\t\t\tfor(int j = r.first; j < r.second; j++, i++)\n\t\t\t\tvals[i] = tod[di*nsamp+j];\n}\ntemplate <typename T>\nvoid pcut_full_vals2tod_helper(const vector<RangesInt32> & rangemat, T * tod, int ndet, int nsamp, T * vals) {\n\tint i = 0;\n\tfor(int di = 0; di < rangemat.size(); di++)\n\t\tfor (auto const &r: rangemat[di].segments)\n\t\t\tfor(int j = r.first; j < r.second; j++, i++)\n\t\t\t\ttod[di*nsamp+j] = vals[i];\n}\n\n// Polynomial cut treatment\nint pcut_poly_measure_helper(const vector<RangesInt32> & rangemat, int resolution, int nmax) {\n\tint n = 0;\n\tfor(int di = 0; di < rangemat.size(); di++)\n\t\tfor (auto const &r: rangemat[di].segments)\n\t\t\tn += get_npoly(r.second-r.first, resolution, nmax);\n\treturn n;\n}\ntemplate <typename T>\nvoid pcut_poly_tod2vals_helper(const vector<RangesInt32> & rangemat, int resolution, int nmax, T * tod, int ndet, int nsamp, T * vals) {\n\tint i = 0;\n\tfor(int di = 0; di < rangemat.size(); di++) {\n\t\tfor (auto const &r: rangemat[di].segments) {\n\t\t\tint np = get_npoly(r.second-r.first, resolution, nmax);\n\t\t\tif(np <= 1) {\n\t\t\t\tfor(int s = r.first; s < r.second; s++)\n\t\t\t\t\tvals[i] += tod[di*nsamp+s];\n\t\t\t\ti++;\n\t\t\t} else {\n\t\t\t\tfor(int p = 0; p < np; p++) vals[i+p] = 0;\n\t\t\t\tfor(int s = r.first; s < r.second; s++) {\n\t\t\t\t\tT x = -1 + 2*(s-r.first)/T(r.second-r.first-1);\n\t\t\t\t\tT t = tod[di*nsamp+s];\n\t\t\t\t\tvals[i] += t;\n\t\t\t\t\tif(np > 1) vals[i+1] += t*x;\n\t\t\t\t\tif(np > 2) {\n\t\t\t\t\t\tT Pa = x, Pb = 1, Pc = 0;\n\t\t\t\t\t\tfor(int p = 2; p < np; p++) {\n\t\t\t\t\t\t\tPc = Pb; Pb = Pa; Pa = ((2*p-1)*x*Pb-(p-1)*Pc)/p;\n\t\t\t\t\t\t\tvals[i+p] += t*Pa;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ti += np;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\ntemplate <typename T>\nvoid pcut_poly_vals2tod_helper(const vector<RangesInt32> & rangemat, int resolution, int nmax, T * tod, int ndet, int nsamp, T * vals) {\n\tint i = 0;\n\tfor(int di = 0; di < rangemat.size(); di++) {\n\t\tfor (auto const &r: rangemat[di].segments) {\n\t\t\tint np = get_npoly(r.second-r.first, resolution, nmax);\n\t\t\tif(np <= 1) {\n\t\t\t\tfor(int s = r.first; s < r.second; s++)\n\t\t\t\t\ttod[di*nsamp+s] = vals[i];\n\t\t\t\ti++;\n\t\t\t} else {\n\t\t\t\tfor(int s = r.first; s < r.second; s++) {\n\t\t\t\t\tT x = -1 + 2*(s-r.first)/T(r.second-r.first-1);\n\t\t\t\t\tT t = vals[i];\n\t\t\t\t\tif(np > 1) t += x*vals[i+1];\n\t\t\t\t\tif(np > 2) {\n\t\t\t\t\t\tT Pa = x, Pb = 1, Pc = 0;\n\t\t\t\t\t\tfor(int p = 2; p < np; p++) {\n\t\t\t\t\t\t\tPc = Pb; Pb = Pa; Pa = ((2*p-1)*x*Pb-(p-1)*Pc)/p;\n\t\t\t\t\t\t\tt += Pa*vals[i+p];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ttod[di*nsamp+s] = t;\n\t\t\t\t\ti += np;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\ntemplate <typename T>\nvoid pcut_clear_helper(const vector<RangesInt32> & rangemat, T * tod, int ndet, int nsamp) {\n\t#pragma omp parallel for\n\tfor(int di = 0; di < rangemat.size(); di++)\n\t\tfor (auto const &r: rangemat[di].segments)\n\t\t\tfor(int s = r.first; s < r.second; s++)\n\t\t\t\ttod[di*nsamp+s] = 0;\n}\n\n\n// get_gap_fill_poly_single\n//\n// Single detector processor for get_gap_fill_poly.  Fit polynomials\n// to each stretch of data in \"gaps\".  Requires square matrix a and\n// vector b to be preallocated for ncoeff.\n//\n// The arguments (inplace, extract) behave like this:\n//\n//   (true,  valid):   The data are replaced with the model, and the\n//                     replaced samples are copied into *extract.\n//   (false, valid):   The data are left unchanged and the model\n//                     values are placed in *extract.\n//   (true,  nullptr): The data are replaced with the model, and\n//                     the original data samples are discarded.\n//   (false, nullptr): The data is left unchanged and the model\n//                     is discarded (probably not what you want...).\n//\n// When extract is non-null, it needs to be the right size... this\n// should be checked by get_gap_fill_poly.\n\nvoid get_gap_fill_poly_single(const RangesInt32 &gaps, float *data,\n                             float *a, float *b,\n                             int buffer, int ncoeff,\n                             bool inplace, float *extract)\n{\n        // Generate Ranges corresponding to samples near the edges of\n        // intervals we want to fill.\n        RangesInt32 rsegs = gaps.buffered((int32_t)buffer);\n        rsegs.intersect(gaps.complement());\n\n        // We are guaranteed that there is one or two rseg intervals\n        // between each of our gaps, and zero or one rseg intervals\n        // before the first gap and after the second gap.\n\n        // Index of the rseg we're working with.\n        int model_i = 0;\n\n        for (auto const &gap: gaps.segments) {\n                // std::cout << \"GAP\\n\";\n                int contrib_samps = 0;\n                int contrib_segs = 0;\n                memset(a, 0, ncoeff*ncoeff*sizeof(*a));\n                memset(b, 0, ncoeff*sizeof(*b));\n                float x0 = gap.first;\n\n                for (; model_i < rsegs.segments.size(); model_i++) {\n                        // Advance until just before this gap.\n                        auto const &ival = rsegs.segments[model_i];\n                        if (ival.second + 1 < gap.first)\n                                continue;\n                        // Include this interval in the fit.\n                        for (int i=ival.first; i<ival.second; i++) {\n                                float xx = 1.;\n                                float yxx = data[i];\n                                float x = i - x0;\n                                for (int j=0; j<ncoeff; j++) {\n                                        b[j] += yxx;\n                                        yxx *= x;\n                                        a[j] += xx;\n                                        xx *= x;\n                                }\n                                // Now down...\n                                for (int k=2; k<ncoeff+1; k++) {\n                                        a[k*ncoeff - 1] += xx;\n                                        xx *= x;\n                                }\n                        }\n                        contrib_samps += ival.second - ival.first;\n                        contrib_segs += 1;\n                        // If this was the right side interval, bail\n                        // now (so we can possibly re-use this\n                        // interval for next gap).\n                        if (ival.first > gap.first)\n                                break;\n                }\n\n                // Restrict order based on number of contributing samples.\n                int n_keep = std::min(contrib_samps / 10 + 1, ncoeff);\n                if (contrib_samps > 0) {\n                        // Fill in a's interior.\n                        for (int r=1; r<ncoeff; r++)\n                                for (int c=0; c<ncoeff-1; c++)\n                                        a[r*ncoeff + c] = a[r*ncoeff + c - ncoeff + 1];\n\n                        // Re-organize a if the order has changed...\n                        if (n_keep < ncoeff) {\n                                for (int r=1; r<n_keep; r++)\n                                        for (int c=0; c<n_keep; c++)\n                                                a[r*n_keep+c] = a[r*ncoeff+c];\n                        }\n\n                        // Solve the system...\n                        int one = 1;\n                        int err = 0;\n                        sposv_(\"Upper\", &n_keep, &one, a, &n_keep, b, &n_keep, &err);\n                }\n                float *write_to = nullptr;\n                float *save_data = nullptr;\n                if (inplace) {\n\t\t\t// Copy original data to extract, write model to data.\n\t\t\tsave_data = extract;\n\t\t\twrite_to = data + gap.first;\n                } else {\n\t\t\t// Write results to extract, do not touch data.\n\t\t\twrite_to = extract;\n                }\n\n                if (save_data != nullptr) {\n\t\t\tfor (int i=gap.first; i<gap.second; i++, save_data++)\n\t\t\t\t*save_data = data[i];\n                }\n                if (write_to != nullptr) {\n\t\t\tfor (int i=gap.first; i<gap.second; i++, write_to++) {\n\t\t\t\tfloat xx = 1.;\n\t\t\t\t*write_to = 0.;\n\t\t\t\tfor (int j=0; j<n_keep; j++) {\n\t\t\t\t\t*write_to += xx * b[j];\n\t\t\t\t\txx *= (i - gap.first);\n\t\t\t\t}\n\t\t\t}\n                }\n                if (extract != nullptr)\n\t\t\textract += (gap.second - gap.first);\n        }\n}\n\nvoid get_gap_fill_poly(const bp::object ranges,\n\t\t       const bp::object tod,\n\t\t       int buffer,\n\t\t       int order,\n\t\t       bool inplace,\n\t\t       const bp::object ex)\n{\n        // As a test, copy data from rangemat into segment.\n\tauto rangemat = extract_ranges<int32_t>(ranges);\n        int ndet = rangemat.size();\n\n        BufferWrapper<float> tod_buf  (\"tod\",  tod,  false, std::vector<int>{ndet,-1});\n        int nsamp = tod_buf->shape[1];\n\n        int ncoeff = order + 1; // Let us not speak of order again.\n        float *a = (float*)malloc(ncoeff*(ncoeff+1)*sizeof(*a));\n        float *b = a + ncoeff*ncoeff;\n\n        float *ex_data = nullptr;\n        std::vector<int> ex_offsets;\n\n        if (ex.ptr() != Py_None) {\n\t\t// Compute offsets of each detector into ex.\n\t\tint n = 0;\n\t\tfor (auto const &r: rangemat) {\n\t\t\tex_offsets.push_back(n);\n\t\t\tfor (auto const &r: r.segments)\n\t\t\t\tn += (r.second - r.first);\n\t\t}\n\t\tBufferWrapper<float> ex_buf(\"ex\", ex, false, std::vector<int>{n});\n\t\tex_data = (float*)ex_buf->buf;\n        }\n\n        for (int di=0; di < rangemat.size(); di++) {\n                float* data = (float*)((char*)tod_buf->buf + di*tod_buf->strides[0]);\n                float* _ex = ex_data;\n                if (_ex != nullptr)\n\t\t\t_ex += ex_offsets[di];\n                get_gap_fill_poly_single(rangemat[di], data, a, b, buffer, ncoeff,\n\t\t\t\t\t inplace, _ex);\n        }\n\n        free(a);\n}\n\nPYBINDINGS(\"so3g\")\n{\n\tbp::def(\"nmat_detvecs_apply\", nmat_detvecs_apply);\n\tbp::def(\"process_cuts\",  process_cuts);\n\tbp::def(\"get_gap_fill_poly\",  get_gap_fill_poly,\n                \"get_gap_fill_poly(ranges, signal, buffer, order, extract)\\n\"\n                \"\\n\"\n                \"Do polynomial gap-filling.\\n\"\n                \"\\n\"\n                \"Args:\\n\"\n                \"  ranges: RangesMatrix with shape (ndet, nsamp)\\n\"\n                \"  signal: data array with shape (ndet, nsamp)\\n\"\n                \"  buffer: integer stating max number of samples to use on each end\\n\"\n                \"  order: order of polynomial to use (1 means linear)\\n\"\n\t\t\"  inplace: whether to overwrite data array with the model\\n\"\n\t\t\"  extract: array to write the original data samples (inplace)\\n\"\n\t\t\"    or the model (!inplace) into.\\n\");\n}\n", "meta": {"hexsha": "d1ef4589681cce6b5dc704928eff7b02c9556431", "size": 20508, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/array_ops.cxx", "max_stars_repo_name": "tskisner/so3g", "max_stars_repo_head_hexsha": "75c1d8dea84f862bdd2c9fa2c2f9d1c5b8da5eec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-09-02T14:17:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T16:43:14.000Z", "max_issues_repo_path": "src/array_ops.cxx", "max_issues_repo_name": "tskisner/so3g", "max_issues_repo_head_hexsha": "75c1d8dea84f862bdd2c9fa2c2f9d1c5b8da5eec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 70.0, "max_issues_repo_issues_event_min_datetime": "2019-05-16T23:42:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T14:35:35.000Z", "max_forks_repo_path": "src/array_ops.cxx", "max_forks_repo_name": "tskisner/so3g", "max_forks_repo_head_hexsha": "75c1d8dea84f862bdd2c9fa2c2f9d1c5b8da5eec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-05-17T18:20:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-22T20:35:44.000Z", "avg_line_length": 42.4596273292, "max_line_length": 183, "alphanum_fraction": 0.5818217281, "num_tokens": 5881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.29847093386864365}}
{"text": "#include \"ahrs.hpp\"\n\n/* C/C++ Includes */\n#include <stdint.h>\n#include <stdlib.h>\n#include <math.h>\n\n/* Thor Includes */\n#include \"Thor/include/thor.h\"\n#include \"Thor/include/spi.h\"\n#include \"Thor/include/gpio.h\"\n#include \"Thor/include/exceptions.h\"\n\n/* Boost Includes */\n#include <boost/smart_ptr.hpp>\n#include <boost/make_shared.hpp>\n\n/* FreeRTOS Includes */\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#include \"queue.h\"\n\n/* Project Includes */\n#include \"ahrs.hpp\"\n#include \"LSM9DS1.hpp\"\n#include \"config.hpp\"\n#include \"dataTypes.hpp\"\n#include \"threading.hpp\"\n\n/* Madgwick Filter */\n#include \"madgwick.hpp\"\n\n/* Kalman Filter */\n#include \"kalman/SquareRootUnscentedKalmanFilter.hpp\"\n#include \"IMUModel.hpp\"\n\n\n\nnamespace SOAR_AHRS\n{\n\ttypedef float T;\n\ttypedef IMU::State<T> State;\n\ttypedef IMU::Control<T> Control;\n\ttypedef IMU::Measurement<T> Measurement;\n\ttypedef IMU::SystemModel<T> SystemModel;\n\ttypedef IMU::MeasurementModel<T> MeasurementModel;\n\n\tconst int updateRate_mS = (1.0 / SENSOR_UPDATE_FREQ_HZ) * 1000.0;\n\tconst int magMaxUpdateRate_mS = (1.0 / LSM9DS1_M_MAX_BW) * 1000.0;\n\n\tconst float accelUncertainty = 0.8f;\n\tconst float gyroUncertainty = 1.05f;\n\n\tvoid ahrsTask(void* argument)\n\t{\n\t\t#ifdef DEBUG\n\t\tvolatile float pitch;\n\t\tvolatile float roll;\n\t\tvolatile float yaw;\n\t\tvolatile float ax;\n\t\tvolatile float ay;\n\t\tvolatile float az;\n\t\tvolatile float gx;\n\t\tvolatile float gy;\n\t\tvolatile float gz;\n\t\tvolatile float mx;\n\t\tvolatile float my;\n\t\tvolatile float mz;\n\t\tvolatile UBaseType_t stackHighWaterMark_AHRS = 0;\n\t\tvolatile size_t bytesRemaining = xPortGetFreeHeapSize();\n\t\t#endif\n\n\t\tAHRSData_t ahrsData;\t\t\t\t\t/* Output struct to push to the motor controller thread */\n\n\n\t\t/*----------------------------------\n\t\t* Initialize the UKF\n\t\t*----------------------------------*/\n\t\tState x, x_ukf;\n\t\tControl u;\n\t\tSystemModel sys;\n\t\tMeasurementModel om;\n\t\tMeasurement meas;\n\n\t\tEigen::Matrix<T, 6, 6> R;\n\t\tEigen::Matrix<T, 6, 6> processNoise;\n\n\t\tKalman::SquareRootUnscentedKalmanFilter<State> ukf(0.5f, 3.0f, 0.0f);\n\n\t\tx.setZero();\n\t\tu.setZero();\n\t\tR.setZero();\n\n\t\tT cnst = 5.00e-4f;\n\t\tT dnst = 3.33e-4f;\n\t\tT enst = 5.00e-4f;\n\n\t\tprocessNoise <<\n\t\t\tcnst, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,\n\t\t\t0.0f, dnst, 0.0f, 0.0f, 0.0f, 0.0f,\n\t\t\t0.0f, 0.0f, enst, 0.0f, 0.0f, 0.0f,\n\t\t\t0.0f, 0.0f, 0.0f, cnst, 0.0f, 0.0f,\n\t\t\t0.0f, 0.0f, 0.0f, 0.0f, dnst, 0.0f,\n\t\t\t0.0f, 0.0f, 0.0f, 0.0f, 0.0f, enst;\n\n\t\tsys.setCovariance(processNoise);\n\n\t\tR(0, 0) = accelUncertainty * accelUncertainty;\n\t\tR(1, 1) = accelUncertainty * accelUncertainty;\n\t\tR(2, 2) = accelUncertainty * accelUncertainty;\n\t\tR(3, 3) = gyroUncertainty * gyroUncertainty;\n\t\tR(4, 4) = gyroUncertainty * gyroUncertainty;\n\t\tR(5, 5) = gyroUncertainty * gyroUncertainty;\n\n\t\tom.setCovariance(R);\n\n\t\tukf.init(x);\n\n\n\t\t/*----------------------------------\n\t\t* Initialize the IMU\n\t\t*----------------------------------*/\n\t\tGPIOClass_sPtr lsm_ss_xg = boost::make_shared<GPIOClass>(GPIOC, PIN_4, ULTRA_SPD, NOALTERNATE);\n\t\tGPIOClass_sPtr lsm_ss_m = boost::make_shared<GPIOClass>(GPIOC, PIN_3, ULTRA_SPD, NOALTERNATE);\n\t\tSPIClass_sPtr lsm_spi = spi2;\n\n\t\tLSM9DS1 imu(lsm_spi, lsm_ss_xg, lsm_ss_m);\n\n\t\t/* Force halt of the device if the IMU cannot be reached */\n\t\tif (imu.begin() == 0)\n\t\t\tBasicErrorHandler(\"The IMU WHO_AM_I registers did not return valid readings\");\n\n\t\t//TODO: Switch this out to print over the serial port\n\n\t\timu.calibrate(true); /* \"true\" forces an automatic software subtraction of the calculated bias from all further data */\n\t\timu.calibrateMag(true); /* \"true\" writes the offest into the mag sensor hardware for automatic subtraction in results */\n\n\t\tint count = 0;\n\n\n\t\t/*----------------------------------\n\t\t* Initialize the Madgwick Filter\n\t\t*----------------------------------*/\n\t\tfloat beta = 10.0;\n\t\tEigen::Vector3f accel_raw, gyro_raw, mag_raw;\n\t\tEigen::Vector3f accel_filtered, gyro_filtered, mag_filtered, eulerDeg;\n\n\t\tMadgwickFilter ahrs((AHRS_UPDATE_RATE_MULTIPLIER * SENSOR_UPDATE_FREQ_HZ), beta);\n\n\t\tfloat dt = (1.0f / SENSOR_UPDATE_FREQ_HZ);\n\t\tfloat tau_accel = 0.01f;\n\t\tfloat alpha_lp_accel = dt / tau_accel;\n\n\n\t\t/* Tell init task that this thread's initialization is done and ok to run.\n\t\t* Wait for init task to resume operation. */\n\t\txTaskSendMessage(INIT_TASK, 1u);\n\t\tvTaskSuspend(NULL);\n\t\ttaskYIELD();\n\n\n\t\tTickType_t lastTimeWoken = xTaskGetTickCount();\n\t\tfor (;;)\n\t\t{\n\t\t\t#ifdef DEBUG\n\t\t\tstackHighWaterMark_AHRS = uxTaskGetStackHighWaterMark(NULL);\n\t\t\tbytesRemaining = xPortGetFreeHeapSize();\n\t\t\t#endif\n\n\t\t\t/*----------------------------\n\t\t\t* Sensor Reading\n\t\t\t*---------------------------*/\n\t\t\t/* Update Accel & Gyro Data at whatever frequency set by user. Max bandwidth on\n\t\t\t* chip is 952Hz which will saturate FreeRTOS if sampled that often.*/\n\t\t\t//taskENTER_CRITICAL();\n\t\t\timu.readAccel();\n\t\t\timu.readGyro();\n\t\t\t\n\n\t\t\t/* Update Mag Data at a max frequency set by LSM9DS1_M_MAX_BW (~75Hz) */\n\t\t\t#if (SENSOR_UPDATE_FREQ_HZ > LSM9DS1_M_MAX_BW)\n\t\t\tif (count > magMaxUpdateRate_mS)\n\t\t\t{\n\t\t\t\timu.readMag();\n\t\t\t\timu.calcMag();\n\t\t\t\tcount = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t\tcount += updateRate_mS;\n\t\t\t#else\n\t\t\timu.readMag();\n\t\t\timu.calcMag();\n\t\t\t#endif\n\t\t\t//taskEXIT_CRITICAL();\n\n\t\t\t/* Convert raw data from chip into meaningful data */\n\t\t\timu.calcAccel(); imu.calcGyro();\n\n// \t\t\t#ifdef DEBUG\n// \t\t\tax = imu.aRaw[0];\n// \t\t\tay = imu.aRaw[1];\n// \t\t\taz = imu.aRaw[2];\n// \n// \t\t\tgx = imu.gRaw[0];\n// \t\t\tgy = imu.gRaw[1];\n// \t\t\tgz = imu.gRaw[2];\n// \n// \t\t\tmx = imu.mRaw[0];\n// \t\t\tmy = imu.mRaw[1];\n// \t\t\tmz = imu.mRaw[2];\n// \t\t\t#endif\n\n\t\t\taccel_raw << imu.aRaw[0], imu.aRaw[1], imu.aRaw[2];\n\t\t\tgyro_raw << imu.gRaw[0], imu.gRaw[1], imu.gRaw[2];\n\t\t\tmag_raw <<\n\t\t\t\t-imu.mRaw[0],  //Align mag x with accel x\n\t\t\t\t-imu.mRaw[1],  //Align mag y with accel y\n\t\t\t\t-imu.mRaw[2];  //from LSM9DS1, mag z is opposite direction of accel z\n\n\n\t\t\t/*----------------------------\n\t\t\t* UKF Algorithm\n\t\t\t*---------------------------*/\n\t\t\t//Simulate the system\n\t\t\tx = sys.f(x, u);\n\n\t\t\t//Predict state for current time step \n\t\t\tx_ukf = ukf.predict(sys);\n\n\t\t\t//Take a measurement given system state\n\t\t\tmeas << accel_raw, gyro_raw;\n\n\t\t\t//Update the state equation given measurement\n\t\t\tx_ukf = ukf.update(om, meas);\n\n\n\t\t\taccel_filtered << x_ukf.ax(), x_ukf.ay(), x_ukf.az();\n\t\t\tgyro_filtered << x_ukf.gx(), x_ukf.gy(), x_ukf.gz();\n\t\t\tmag_filtered = mag_raw;\n\n\n\t\t\t/*----------------------------\n\t\t\t* AHRS Algorithm\n\t\t\t*---------------------------*/\n\t\t\t/* The Madgwick filter needs to run between 3-5 times as fast IMU measurements\n\t\t\t* to achieve decent convergence to a stable value. This thread only runs when\n\t\t\t* new data has arrived from the IMU, so frequency multiplication is as simple\n\t\t\t* as looping 3-5 times here. */\n\t\t\tfor (int i = 0; i < AHRS_UPDATE_RATE_MULTIPLIER; i++)\n\t\t\t\tahrs.update(accel_filtered, gyro_filtered, mag_filtered);\n\n\t\t\tahrs.getEulerDeg(eulerDeg);\n\t\t\tahrsData(eulerDeg, accel_filtered, gyro_filtered, mag_filtered);\n\n\t\t\t#ifdef DEBUG\n\t\t\tpitch = eulerDeg(0);\n\t\t\troll = eulerDeg(1);\n\t\t\tyaw = eulerDeg(2);\n\n\t\t\tax = accel_filtered(0);\n\t\t\tay = accel_filtered(1);\n\t\t\taz = accel_filtered(2);\n\n\t\t\tgx = gyro_filtered(0);\n\t\t\tgy = gyro_filtered(1);\n\t\t\tgz = gyro_filtered(2);\n\n\t\t\tmx = mag_filtered(0);\n\t\t\tmy = mag_filtered(1);\n\t\t\tmz = mag_filtered(2);\n\t\t\t#endif\n\n\t\t\t/* Send data over to the Serial thread*/\n\t\t\tif (xSemaphoreTake(ahrsBufferMutex, 0) == pdPASS)\n\t\t\t{\n\t\t\t\txQueueOverwrite(qAHRS, &ahrsData);\n\t\t\t\txSemaphoreGive(ahrsBufferMutex);\n\t\t\t}\n\n\t\t\tvTaskDelayUntil(&lastTimeWoken, pdMS_TO_TICKS(updateRate_mS));\n\t\t}\n\t}\n}\n\n", "meta": {"hexsha": "803d1a0cf6fb5cb0b774bdaca94403637d509a8c", "size": 7453, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ahrs.cpp", "max_stars_repo_name": "brandonbraun653/TeamSOAR", "max_stars_repo_head_hexsha": "472c7e900de20545476e76395ebe89ab5467ae11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ahrs.cpp", "max_issues_repo_name": "brandonbraun653/TeamSOAR", "max_issues_repo_head_hexsha": "472c7e900de20545476e76395ebe89ab5467ae11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ahrs.cpp", "max_forks_repo_name": "brandonbraun653/TeamSOAR", "max_forks_repo_head_hexsha": "472c7e900de20545476e76395ebe89ab5467ae11", "max_forks_repo_licenses": ["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.150877193, "max_line_length": 122, "alphanum_fraction": 0.6390715148, "num_tokens": 2402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.29843553307025994}}
{"text": "//\n// Created by dchansen on 10/12/18.\n//\n#include \"ConvolutionMatrix.h\"\n\n#include <GadgetronTimer.h>\n#include <numeric>\n#include \"vector_td_utilities.h\"\n#include <boost/range/irange.hpp>\n\nnamespace\n{\n    using namespace Gadgetron;\n\n    template<int N>\n    struct iteration_counter { };\n\n    template<class REAL, unsigned int D, template<class, unsigned int> class K>\n    void iterate_body(\n        const vector_td<REAL, D> &point,\n        const vector_td<size_t, D> &matrix_size,\n        std::vector<size_t> &indices,\n        std::vector<REAL> &weights,\n        vector_td<REAL, D> &image_point,\n        size_t index,\n        const ConvolutionKernel<REAL, D, K>& kernel,\n        iteration_counter<-1>)\n    {\n        auto delta = abs(image_point - point);\n        indices.push_back(index);\n        weights.push_back(kernel.get(delta));\n    }\n\n    template<class REAL, unsigned int D, template<class, unsigned int> class K, int N>\n    void iterate_body(\n        const vector_td<REAL, D> &point,\n        const vector_td<size_t, D> &matrix_size,\n        std::vector<size_t> &indices,\n        std::vector<REAL> &weights,\n        vector_td<REAL, D> &image_point,\n        size_t index,\n        const ConvolutionKernel<REAL, D, K>& kernel,\n        iteration_counter<N>)\n    {\n        size_t frame_offset = std::accumulate(&matrix_size[0], &matrix_size[N], 1, std::multiplies<size_t>());\n\n        for (int i = std::ceil(point[N] - kernel.get_radius());\n             i <= std::floor(point[N] + kernel.get_radius());\n             i++)\n        {\n            auto wrapped_i = (i + matrix_size[N]) % matrix_size[N];\n            size_t index2 = index + frame_offset * wrapped_i;\n            image_point[N] = i;\n            iterate_body(point, matrix_size, indices, weights, image_point,\n                         index2, kernel, iteration_counter<N - 1>());\n        }\n    }\n\n    template<class REAL, unsigned int D, template<class, unsigned int> class K>\n    std::tuple<std::vector<size_t>, std::vector<REAL>> get_indices(\n        const vector_td<REAL, D> &point,\n        const vector_td<size_t, D> &matrix_size,\n        const ConvolutionKernel<REAL, D, K>& kernel)\n    {\n        std::vector<size_t> indices;\n        indices.reserve(size_t(std::pow(std::ceil(kernel.get_width()), D)));\n\n        std::vector<REAL> weights;\n        weights.reserve(size_t(std::pow(std::ceil(kernel.get_width()), D)));\n\n        vector_td<REAL, D> image_point;\n        size_t index = 0;\n        iterate_body(point, matrix_size, indices, weights, image_point, index,\n                     kernel, iteration_counter<D - 1>());\n\n        return std::make_tuple(std::move(indices), std::move(weights));\n    }\n}\n\n\ntemplate<class REAL, unsigned int D, template<class, unsigned int> class K>\nGadgetron::ConvInternal::ConvolutionMatrix<REAL>\nGadgetron::ConvInternal::make_conv_matrix(\n    const Gadgetron::hoNDArray<Gadgetron::vector_td<REAL, D>> trajectory,\n    const Gadgetron::vector_td<size_t, D> &matrix_size,\n    const ConvolutionKernel<REAL, D, K>& kernel)\n{\n    ConvolutionMatrix<REAL> matrix(trajectory.get_number_of_elements(),\n                                   prod(matrix_size));\n    \n    #pragma omp parallel for \n    for (int i = 0; i < (int)trajectory.get_number_of_elements(); i++)\n    {\n        std::tie(matrix.indices[i], matrix.weights[i]) = get_indices(\n            trajectory[i], matrix_size, kernel);\n    }\n\n    return matrix;\n}\n\n\ntemplate<class REAL>\nGadgetron::ConvInternal::ConvolutionMatrix<REAL>\nGadgetron::ConvInternal::transpose(const Gadgetron::ConvInternal::ConvolutionMatrix<REAL> &matrix) {\n\n    auto work_index = boost::irange(size_t(0),matrix.n_cols);\n\n    ConvolutionMatrix<REAL> transposed(matrix.n_rows, matrix.n_cols);\n\n    std::vector<int> counts(matrix.n_rows, 0);\n\n    for (size_t i : work_index)\n    {\n        auto &rows = matrix.indices[i];\n        for (auto &row : rows)\n            counts[row]++;\n    }\n\n    for (size_t i = 0; i < counts.size(); i++)\n    {\n        transposed.indices[i].reserve(counts[i]);\n        transposed.weights[i].reserve(counts[i]);\n    }\n\n    for (size_t i : work_index )\n    {\n        auto &rows = matrix.indices[i];\n        auto &weights = matrix.weights[i];\n        for (size_t n = 0; n < rows.size(); n++)\n        {\n            transposed.indices[rows[n]].push_back(i);\n            transposed.weights[rows[n]].push_back(weights[n]);\n        }\n    }\n\n    return transposed;\n}\n\n\ntemplate Gadgetron::ConvInternal::ConvolutionMatrix<float>\nGadgetron::ConvInternal::make_conv_matrix<float, 1, Gadgetron::KaiserKernel>(\n    const Gadgetron::hoNDArray<Gadgetron::vector_td<float, 1>> trajectory,\n    const Gadgetron::vector_td<size_t, 1> &matrix_size,\n    const ConvolutionKernel<float, 1, Gadgetron::KaiserKernel>& kernel);\n\ntemplate Gadgetron::ConvInternal::ConvolutionMatrix<float>\nGadgetron::ConvInternal::make_conv_matrix<float, 2, Gadgetron::KaiserKernel>(\n    const Gadgetron::hoNDArray<Gadgetron::vector_td<float, 2>> trajectory,\n    const Gadgetron::vector_td<size_t, 2> &matrix_size,\n    const ConvolutionKernel<float, 2, Gadgetron::KaiserKernel>& kernel);\n\ntemplate Gadgetron::ConvInternal::ConvolutionMatrix<float>\nGadgetron::ConvInternal::make_conv_matrix<float, 3, Gadgetron::KaiserKernel>(\n    const Gadgetron::hoNDArray<Gadgetron::vector_td<float, 3>> trajectory,\n    const Gadgetron::vector_td<size_t, 3> &matrix_size,\n    const ConvolutionKernel<float, 3, Gadgetron::KaiserKernel>& kernel);\n\ntemplate Gadgetron::ConvInternal::ConvolutionMatrix<float>\nGadgetron::ConvInternal::make_conv_matrix<float, 4, Gadgetron::KaiserKernel>(\n    const Gadgetron::hoNDArray<Gadgetron::vector_td<float, 4>> trajectory,\n    const Gadgetron::vector_td<size_t, 4> &matrix_size,\n    const ConvolutionKernel<float, 4, Gadgetron::KaiserKernel>& kernel);\n\ntemplate Gadgetron::ConvInternal::ConvolutionMatrix<double>\nGadgetron::ConvInternal::make_conv_matrix<double, 1, Gadgetron::KaiserKernel>(\n    const Gadgetron::hoNDArray<Gadgetron::vector_td<double, 1>> trajectory,\n    const Gadgetron::vector_td<size_t, 1> &matrix_size,\n    const ConvolutionKernel<double, 1, Gadgetron::KaiserKernel>& kernel);\n\ntemplate Gadgetron::ConvInternal::ConvolutionMatrix<double>\nGadgetron::ConvInternal::make_conv_matrix<double, 2, Gadgetron::KaiserKernel>(\n    const Gadgetron::hoNDArray<Gadgetron::vector_td<double, 2>> trajectory,\n    const Gadgetron::vector_td<size_t, 2> &matrix_size,\n    const ConvolutionKernel<double, 2, Gadgetron::KaiserKernel>& kernel);\n\ntemplate Gadgetron::ConvInternal::ConvolutionMatrix<double>\nGadgetron::ConvInternal::make_conv_matrix<double, 3, Gadgetron::KaiserKernel>(\n    const Gadgetron::hoNDArray<Gadgetron::vector_td<double, 3>> trajectory,\n    const Gadgetron::vector_td<size_t, 3> &matrix_size,\n    const ConvolutionKernel<double, 3, Gadgetron::KaiserKernel>& kernel);\n\ntemplate Gadgetron::ConvInternal::ConvolutionMatrix<double>\nGadgetron::ConvInternal::make_conv_matrix<double, 4, Gadgetron::KaiserKernel>(\n    const Gadgetron::hoNDArray<Gadgetron::vector_td<double, 4>> trajectory,\n    const Gadgetron::vector_td<size_t, 4> &matrix_size,\n    const ConvolutionKernel<double, 4, Gadgetron::KaiserKernel>& kernel);\n\ntemplate Gadgetron::ConvInternal::ConvolutionMatrix<float>\nGadgetron::ConvInternal::make_conv_matrix<float, 1, Gadgetron::JincKernel>(\n    const Gadgetron::hoNDArray<Gadgetron::vector_td<float, 1>> trajectory,\n    const Gadgetron::vector_td<size_t, 1> &matrix_size,\n    const ConvolutionKernel<float, 1, Gadgetron::JincKernel>& kernel);\n\ntemplate Gadgetron::ConvInternal::ConvolutionMatrix<float>\nGadgetron::ConvInternal::make_conv_matrix<float, 2, Gadgetron::JincKernel>(\n    const Gadgetron::hoNDArray<Gadgetron::vector_td<float, 2>> trajectory,\n    const Gadgetron::vector_td<size_t, 2> &matrix_size,\n    const ConvolutionKernel<float, 2, Gadgetron::JincKernel>& kernel);\n\ntemplate Gadgetron::ConvInternal::ConvolutionMatrix<float>\nGadgetron::ConvInternal::make_conv_matrix<float, 3, Gadgetron::JincKernel>(\n    const Gadgetron::hoNDArray<Gadgetron::vector_td<float, 3>> trajectory,\n    const Gadgetron::vector_td<size_t, 3> &matrix_size,\n    const ConvolutionKernel<float, 3, Gadgetron::JincKernel>& kernel);\n\ntemplate Gadgetron::ConvInternal::ConvolutionMatrix<float>\nGadgetron::ConvInternal::make_conv_matrix<float, 4, Gadgetron::JincKernel>(\n    const Gadgetron::hoNDArray<Gadgetron::vector_td<float, 4>> trajectory,\n    const Gadgetron::vector_td<size_t, 4> &matrix_size,\n    const ConvolutionKernel<float, 4, Gadgetron::JincKernel>& kernel);\n\ntemplate Gadgetron::ConvInternal::ConvolutionMatrix<double>\nGadgetron::ConvInternal::make_conv_matrix<double, 1, Gadgetron::JincKernel>(\n    const Gadgetron::hoNDArray<Gadgetron::vector_td<double, 1>> trajectory,\n    const Gadgetron::vector_td<size_t, 1> &matrix_size,\n    const ConvolutionKernel<double, 1, Gadgetron::JincKernel>& kernel);\n\ntemplate Gadgetron::ConvInternal::ConvolutionMatrix<double>\nGadgetron::ConvInternal::make_conv_matrix<double, 2, Gadgetron::JincKernel>(\n    const Gadgetron::hoNDArray<Gadgetron::vector_td<double, 2>> trajectory,\n    const Gadgetron::vector_td<size_t, 2> &matrix_size,\n    const ConvolutionKernel<double, 2, Gadgetron::JincKernel>& kernel);\n\ntemplate Gadgetron::ConvInternal::ConvolutionMatrix<double>\nGadgetron::ConvInternal::make_conv_matrix<double, 3, Gadgetron::JincKernel>(\n    const Gadgetron::hoNDArray<Gadgetron::vector_td<double, 3>> trajectory,\n    const Gadgetron::vector_td<size_t, 3> &matrix_size,\n    const ConvolutionKernel<double, 3, Gadgetron::JincKernel>& kernel);\n\ntemplate Gadgetron::ConvInternal::ConvolutionMatrix<double>\nGadgetron::ConvInternal::make_conv_matrix<double, 4, Gadgetron::JincKernel>(\n    const Gadgetron::hoNDArray<Gadgetron::vector_td<double, 4>> trajectory,\n    const Gadgetron::vector_td<size_t, 4> &matrix_size,\n    const ConvolutionKernel<double, 4, Gadgetron::JincKernel>& kernel);\n\ntemplate Gadgetron::ConvInternal::ConvolutionMatrix<float>\nGadgetron::ConvInternal::transpose(\n    const Gadgetron::ConvInternal::ConvolutionMatrix<float> &matrix);\n\ntemplate Gadgetron::ConvInternal::ConvolutionMatrix<double>\nGadgetron::ConvInternal::transpose(\n        const Gadgetron::ConvInternal::ConvolutionMatrix<double> &matrix);\n\n", "meta": {"hexsha": "c26444862786fc1d3cc19ecbb9bd16698042e7c3", "size": 10216, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolboxes/nfft/cpu/ConvolutionMatrix.cpp", "max_stars_repo_name": "roopchansinghv/gadgetron", "max_stars_repo_head_hexsha": "fb6c56b643911152c27834a754a7b6ee2dd912da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T21:06:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T21:06:36.000Z", "max_issues_repo_path": "toolboxes/nfft/cpu/ConvolutionMatrix.cpp", "max_issues_repo_name": "apd47/gadgetron", "max_issues_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolboxes/nfft/cpu/ConvolutionMatrix.cpp", "max_forks_repo_name": "apd47/gadgetron", "max_forks_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_forks_repo_licenses": ["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.868852459, "max_line_length": 110, "alphanum_fraction": 0.7128034456, "num_tokens": 2695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.29843553307025994}}
{"text": "#include \"hoCuNDArray_utils.h\"\n#include \"radial_utilities.h\"\n#include \"cuNDArray_fileio.h\"\n#include \"cuNDArray_math.h\"\n#include \"imageOperator.h\"\n#include \"identityOperator.h\"\n#include \"hoPartialDerivativeOperator.h\"\n#include \"hoCuConebeamProjectionOperator.h\"\n#include \"cuConvolutionOperator.h\"\n#include \"hoCuNDArray_blas.h\"\n#include \"hoCuNDArray_elemwise.h\"\n#include \"hoCuNDArray_blas.h\"\n#include \"cgSolver.h\"\n#include \"CBCT_acquisition.h\"\n#include \"complext.h\"\n#include \"encodingOperatorContainer.h\"\n#include \"vector_td_io.h\"\n#include \"hoPartialDerivativeOperator.h\"\n#include \"hoCuGPBBSolver.h\"\n#include \"hoCuTvOperator.h\"\n#include \"hoCuTvPicsOperator.h\"\n#include \"hoCuNCGSolver.h\"\n#include \"hoCuCgDescentSolver.h\"\n#include \"hoNDArray_utils.h\"\n#include \"hoCuPartialDerivativeOperator.h\"\n#include \"cuTvOperator.h\"\n#include \"cuTv1dOperator.h\"\n#include \"cuTvPicsOperator.h\"\n#include \"CBSubsetOperator.h\"\n#include \"osSPSSolver.h\"\n#include \"osMOMSolver.h\"\n#include \"osMOMSolverD.h\"\n#include \"osMOMSolverD2.h\"\n#include \"hoCuNCGSolver.h\"\n#include \"osMOMSolverD3.h\"\n#include \"osMOMSolverL1.h\"\n#include \"osMOMSolverF.h\"\n#include \"osAHZCSolver.h\"\n#include \"ADMMSolver.h\"\n#include <iostream>\n#include <algorithm>\n#include <sstream>\n#include <math_constants.h>\n#include <boost/program_options.hpp>\n#include <boost/make_shared.hpp>\n#include <GPUTimer.h>\n#include \"cuSolverUtils.h\"\n#include \"osPDsolver.h\"\n#include \"osLALMSolver.h\"\n#include \"osLALMSolver2.h\"\n#include \"cuATrousOperator.h\"\n#include \"hdf5_utils.h\"\n#include \"cuEdgeATrousOperator.h\"\n#include \"cuDCTOperator.h\"\n#include \"cuDCTDerivativeOperator.h\"\n#include \"dicomWriter.h\"\n#include \"conebeam_projection.h\"\n#include \"weightingOperator.h\"\n#include \"hoNDArray_math.h\"\n#include \"cuNCGSolver.h\"\n#include \"CT_acquisition.h\"\n#include \"hoCuOSOMSolver.h\"\n\nusing namespace std;\nusing namespace Gadgetron;\n\nnamespace po = boost::program_options;\n\n\nboost::shared_ptr<cuNDArray<float> > calculate_prior(boost::shared_ptr<CBCT_binning>  binning,boost::shared_ptr<CBCT_acquisition> ps, hoCuNDArray<float>& projections, std::vector<size_t> is_dims, floatd3 imageDimensions){\n\tstd::cout << \"Calculating FDK prior\" << std::endl;\n\tboost::shared_ptr<CBCT_binning> binning_pics=binning->get_3d_binning();\n\tstd::vector<size_t> is_dims3d = is_dims;\n\tis_dims3d.pop_back();\n\tboost::shared_ptr< hoCuConebeamProjectionOperator >\n\tEp( new hoCuConebeamProjectionOperator() );\n\tEp->setup(ps,binning_pics,imageDimensions);\n\tEp->set_codomain_dimensions(ps->get_projections()->get_dimensions().get());\n\tEp->set_domain_dimensions(&is_dims3d);\n\tEp->set_use_filtered_backprojection(true);\n\tboost::shared_ptr<hoCuNDArray<float> > prior3d(new hoCuNDArray<float>(&is_dims3d));\n\tEp->mult_MH(&projections,prior3d.get());\n\n\thoCuNDArray<float> tmp_proj(*ps->get_projections());\n\tEp->mult_M(prior3d.get(),&tmp_proj);\n\tfloat s = dot(ps->get_projections().get(),&tmp_proj)/dot(&tmp_proj,&tmp_proj);\n\t*prior3d *= s;\n\tboost::shared_ptr<cuNDArray<float> > prior(new cuNDArray<float>(*expand( prior3d.get(), is_dims.back() )));\n\tstd::cout << \"Prior complete\" << std::endl;\n\treturn prior;\n}\n\n\nboost::shared_ptr<cuNDArray<float>> calculate_weightImage(boost::shared_ptr<CBCT_binning>  binning,boost::shared_ptr<CBCT_acquisition> ps, hoCuNDArray<float>& ho_projections, std::vector<size_t> is_dims, floatd3 imageDimensions){\n\n\tcuNDArray<float> projections(ho_projections);\n\tboost::shared_ptr<CBCT_binning> binning_pics=binning->get_3d_binning();\n\tstd::vector<size_t> is_dims3d = is_dims;\n\tis_dims3d.pop_back();\n\tauto Ep = boost::make_shared<cuConebeamProjectionOperator>();\n\tauto ps2 = boost::make_shared<CBCT_acquisition>(boost::shared_ptr<hoCuNDArray<float>>(),ps->get_geometry());\n\tEp->setup(ps2,binning_pics,imageDimensions);\n\tEp->set_codomain_dimensions(ps->get_projections()->get_dimensions().get());\n\tEp->set_domain_dimensions(&is_dims3d);\n\t//Ep->set_use_filtered_backprojection(true);\n\tEp->offset_correct(&projections);\n\t//Ep->mult_MH(&projections,prior3d.get());\n\t//cgSolver<hoCuNDArray<float>> solv;\n\tcuNCGSolver<float> solv;\n\tsolv.set_non_negativity_constraint(true);\n\tsolv.set_encoding_operator(Ep);\n\tsolv.set_max_iterations(10);\n\tauto prior3d = solv.solve(&projections);\n\t//auto prior3d = boost::make_shared<cuNDArray<float>>(is_dims3d);\n\twrite_nd_array(prior3d.get(),\"fdk.real\");\n\tcuNDArray<float> tmp_proj(projections);\n\tclear(&tmp_proj);\n\tEp->mult_M(prior3d.get(),&tmp_proj);\n\t//float s = dot(ps->get_projections().get(),&tmp_proj)/dot(&tmp_proj,&tmp_proj);\n\t//std::cout << \"Scaling \" << s << std::endl;\n/*\n\t //Ep->offset_correct(&tmp_proj);\n\t//tmp_proj *= s;\n\twrite_nd_array(&tmp_proj,\"projtmp.real\");\n\ttmp_proj -= projections;\n\ttmp_proj *= float(-1);\n\tabs_inplace(&tmp_proj);\n\n\twrite_nd_array(ps->get_projections().get(),\"proj.real\");\n\twrite_nd_array(&tmp_proj,\"projdiff.real\");\n\tstd::cout << \"Proj size \";\n\tauto pdims = *tmp_proj.get_dimensions();\n\tfor (auto p : pdims ) std::cout << p << \" \";\n\tstd::cout << std::endl;\n\t//Ep->set_use_filtered_backprojection(false);\n\t//Ep->mult_MH(&tmp_proj,prior3d.get());\n\t//solv.set_non_negativity_constraint(false);\n\tprior3d = solv.solve(&tmp_proj);\n\t//abs_inplace(prior.get());\n\tstd::cout << \"Prior complete\" << std::endl;\n\t*/\n\treturn prior3d;\n}\n\n\nint main(int argc, char** argv)\n{\n\n\tstring acquisition_filename;\n\tstring outputFile;\n\tuintd3 imageSize;\n\tfloatd3 voxelSize;\n\tint device;\n\tunsigned int downsamples;\n\tunsigned int iterations;\n\tunsigned int subsets;\n\tfloat rho,tau;\n\tfloat tv_weight,pics_weight, wavelet_weight,huber,sigma,dct_weight;\n\tfloat tv_4d;\n    bool use_non_negativity;\n\tint reg_iter;\n\n\tpo::options_description desc(\"Allowed options\");\n\n\tdesc.add_options()\n    \t\t\t\t(\"help\", \"produce help message\")\n    \t\t\t\t(\"acquisition,a\", po::value<string>(&acquisition_filename)->default_value(\"acquisition.hdf5\"), \"Acquisition data\")\n    \t\t\t\t(\"samples,n\",po::value<unsigned int>(),\"Number of samples per ray\")\n    \t\t\t\t(\"output,f\", po::value<string>(&outputFile)->default_value(\"reconstruction.hdf5\"), \"Output filename\")\n    \t\t\t\t(\"size,s\",po::value<uintd3>(&imageSize)->default_value(uintd3(512,512,1)),\"Image size in pixels\")\n    \t\t\t\t(\"binning,b\",po::value<string>(),\"Binning file for 4d reconstruction\")\n    \t\t\t\t(\"SAG\",\"Use exact SAG correction if present\")\n    \t\t\t\t(\"voxelSize,v\",po::value<floatd3>(&voxelSize)->default_value(floatd3(0.488f,0.488f,1.0f)),\"Voxel size in mm\")\n    \t\t\t\t(\"dimensions,d\",po::value<floatd3>(),\"Image dimensions in mm. Overwrites voxelSize.\")\n    \t\t\t\t(\"iterations,i\",po::value<unsigned int>(&iterations)->default_value(10),\"Number of iterations\")\n    \t\t\t\t(\"device\",po::value<int>(&device)->default_value(0),\"Number of the device to use (0 indexed)\")\n    \t\t\t\t(\"downsample,D\",po::value<unsigned int>(&downsamples)->default_value(0),\"Downsample projections this factor\")\n    \t\t\t\t(\"subsets,u\",po::value<unsigned int>(&subsets)->default_value(10),\"Number of subsets to use\")\n    \t\t\t\t(\"TV\",po::value<float>(&tv_weight)->default_value(0),\"Total variation weight in spatial dimensions\")\n\t\t\t\t\t\t\t(\"TV4D\",po::value<float>(&tv_4d)->default_value(0),\"Total variation weight in temporal dimensions\")\n    \t\t\t\t(\"PICS\",po::value<float>(&pics_weight)->default_value(0),\"PICS weight\")\n    \t\t\t\t(\"Wavelet,W\",po::value<float>(&wavelet_weight)->default_value(0),\"Weight of the wavelet operator\")\n    \t\t\t\t(\"Huber\",po::value<float>(&huber)->default_value(0),\"Huber weight\")\n    \t\t\t\t(\"use_prior\",\"Use an FDK prior\")\n    \t\t\t\t(\"use_non_negativity\",po::value<bool>(&use_non_negativity)->default_value(true),\"Prevent image from having negative attenuation\")\n    \t\t\t\t(\"sigma\",po::value<float>(&sigma)->default_value(0.1),\"Sigma for billateral filter\")\n    \t\t\t\t(\"DCT\",po::value<float>(&dct_weight)->default_value(0),\"DCT regularization\")\n    \t\t\t\t(\"3D\",\"Only use binning for selecting valid projections\")\n\t\t\t\t\t\t\t(\"tau\",po::value<float>(&tau)->default_value(1e-5),\"Tau value for solver\")\n\t\t\t\t\t\t\t(\"reg_iter\",po::value<int>(&reg_iter)->default_value(2))\n    \t\t\t\t;\n\n\tpo::variables_map vm;\n\tpo::store(po::parse_command_line(argc, argv, desc), vm);\n\tpo::notify(vm);\n\n\tif (vm.count(\"help\")) {\n\t\tcout << desc << \"\\n\";\n\t\treturn 1;\n\t}\n\n\tstd::stringstream command_line_string;\n\tstd::cout << \"Command line options:\" << std::endl;\n\tfor (po::variables_map::iterator it = vm.begin(); it != vm.end(); ++it){\n\t\tboost::any a = it->second.value();\n\t\tcommand_line_string << it->first << \": \";\n\t\tif (a.type() == typeid(std::string)) command_line_string << it->second.as<std::string>();\n\t\telse if (a.type() == typeid(int)) command_line_string << it->second.as<int>();\n\t\telse if (a.type() == typeid(unsigned int)) command_line_string << it->second.as<unsigned int>();\n\t\telse if (a.type() == typeid(float)) command_line_string << it->second.as<float>();\n\t\telse if (a.type() == typeid(vector_td<float,3>)) command_line_string << it->second.as<vector_td<float,3> >();\n\t\telse if (a.type() == typeid(vector_td<int,3>)) command_line_string << it->second.as<vector_td<int,3> >();\n\t\telse if (a.type() == typeid(vector_td<unsigned int,3>)) command_line_string << it->second.as<vector_td<unsigned int,3> >();\n        else if (a.type() == typeid(bool)) command_line_string << it->second.as<bool>();\n\t\telse command_line_string << \"Unknown type\" << std::endl;\n\t\tcommand_line_string << std::endl;\n\t}\n\tstd::cout << command_line_string.str();\n\n\tcudaSetDevice(device);\n\tcudaDeviceReset();\n\n\t//Really weird stuff. Needed to initialize the device?? Should find real bug.\n\tcudaDeviceManager::Instance()->lockHandle();\n\tcudaDeviceManager::Instance()->unlockHandle();\n\n\tboost::shared_ptr<CBCT_acquisition> ps(new CBCT_acquisition());\n\tps->load(acquisition_filename);\n\tps->get_geometry()->print(std::cout);\n\tps->downsample(downsamples);\n\n\tfloat SDD = ps->get_geometry()->get_SDD();\n\tfloat SAD = ps->get_geometry()->get_SAD();\n\n\tboost::shared_ptr<CBCT_binning> binning(new CBCT_binning());\n\tif (vm.count(\"binning\")){\n\t\tstd::cout << \"Loading binning data\" << std::endl;\n\t\tbinning->load(vm[\"binning\"].as<string>());\n\t\tif (vm.count(\"3D\"))\n\t\t\tbinning = binning->get_3d_binning();\n\t} else binning->set_as_default_3d_bin(ps->get_projections()->get_size(2));\n\tbinning->print(std::cout);\n\n\tfloatd3 imageDimensions;\n\tif (vm.count(\"dimensions\")){\n\t\timageDimensions = vm[\"dimensions\"].as<floatd3>();\n\t\tvoxelSize = imageDimensions/imageSize;\n\t}\n\telse imageDimensions = voxelSize*imageSize;\n\n\tfloat lengthOfRay_in_mm = norm(imageDimensions);\n\tunsigned int numSamplesPerPixel = 3;\n\tfloat minSpacing = min(voxelSize)/numSamplesPerPixel;\n\n\tunsigned int numSamplesPerRay;\n\tif (vm.count(\"samples\")) numSamplesPerRay = vm[\"samples\"].as<unsigned int>();\n\telse numSamplesPerRay = ceil( lengthOfRay_in_mm / minSpacing );\n\n\tfloat step_size_in_mm = lengthOfRay_in_mm / numSamplesPerRay;\n\tsize_t numProjs = ps->get_projections()->get_size(2);\n\tsize_t needed_bytes = 2 * prod(imageSize) * sizeof(float);\n\tstd::vector<size_t> is_dims = to_std_vector((uint64d3)imageSize);\n\n\tstd::cout << \"IS dimensions \" << is_dims[0] << \" \" << is_dims[1] << \" \" << is_dims[2] << std::endl;\n\tstd::cout << \"Image size \" << imageDimensions << std::endl;\n\n\tis_dims.push_back(binning->get_number_of_bins());\n\n\t//osLALMSolver<cuNDArray<float>> solver;\n\thoCuOSMOMSolver<float> solver;\n\t//osMOMSolverL1<cuNDArray<float>> solver;\n\t//osAHZCSolver<cuNDArray<float>> solver;\n\t//osMOMSolverF<cuNDArray<float>> solver;\n\t//ADMMSolver<cuNDArray<float>> solver;\n\tsolver.set_dump(false);\n\n\n\n\n\t//hoCuCgDescentSolver<float> solver;\n\n\t//osSPSSolver<hoNDArray<float>> solver;\n\t//hoCuNCGSolver<float> solver;\n\t//solver.set_domain_dimensions(&is_dims);\n\tsolver.set_max_iterations(iterations);\n\tsolver.set_output_mode(osSPSSolver<cuNDArray<float>>::OUTPUT_VERBOSE);\n\tsolver.set_tau(tau);\n\tsolver.set_non_negativity_constraint(use_non_negativity);\n\tsolver.set_huber(huber);\n\tsolver.set_reg_steps(reg_iter);\n\t//solver.set_rho(rho);\n\n  if (tv_weight > 0){\n\n  \tauto Dx = boost::make_shared<cuPartialDerivativeOperator<float,4>>(0);\n  \tDx->set_weight(tv_weight);\n  \tDx->set_domain_dimensions(&is_dims);\n  \tDx->set_codomain_dimensions(&is_dims);\n\n  \tauto Dy = boost::make_shared<cuPartialDerivativeOperator<float,4>>(1);\n  \tDy->set_weight(tv_weight);\n  \tDy->set_domain_dimensions(&is_dims);\n  \tDy->set_codomain_dimensions(&is_dims);\n\n\n  \tauto Dz = boost::make_shared<cuPartialDerivativeOperator<float,4>>(2);\n  \tDz->set_weight(tv_weight);\n  \tDz->set_domain_dimensions(&is_dims);\n  \tDz->set_codomain_dimensions(&is_dims);\n\n  \tsolver.add_regularization_group({Dx,Dy,Dz});\n    if (tv_4d > 0) {\n        auto Dt = boost::make_shared<cuPartialDerivativeOperator<float, 4>>(3);\n        Dt->set_weight(tv_4d);\n        Dt->set_domain_dimensions(&is_dims);\n        Dt->set_codomain_dimensions(&is_dims);\n        solver.add_regularization_operator(Dt);\n    }\n/*\n\tauto projections = *ps->get_projections();\n  \tauto prior_weight = calculate_weightImage(binning,ps,projections,is_dims,imageDimensions);\n  \t//sqrt_inplace(prior_weight.get());\n  \tstd::cout << \"Prior min \" << min(prior_weight.get()) << std::endl;\n  \t//*prior_weight -= min(prior_weight.get());\n  \t*prior_weight /= asum(prior_weight.get())/prior_weight->get_number_of_elements();\n  \t*prior_weight -= max(prior_weight.get());\n  \t*prior_weight *= float(-1);\n  \t//clamp_min(prior_weight.get(),float(1e-2));\n  \t//reciprocal_inplace(prior_weight.get());\n\n\n  \twrite_nd_array(prior_weight.get(),\"prior.real\");\n  \t//cudaDeviceReset();\n  \tauto Wt = boost::make_shared<weightingOperator<cuNDArray<float>>>(prior_weight,Dt);\n\tWt->set_weight(tv_weight);\n  \tWt->set_domain_dimensions(&is_dims);\n  \tWt->set_codomain_dimensions(&is_dims);\n*/\n  \t//lver.add_regularization_operator(Dt);\n\n\n\n\n  }\n  /*\n  if (pics_weight > 0){\n\n  \tauto Dx = boost::make_shared<cuPartialDerivativeOperator<float,4>>(0);\n  \tDx->set_weight(pics_weight);\n  \tDx->set_domain_dimensions(&is_dims);\n  \tDx->set_codomain_dimensions(&is_dims);\n\n  \tauto Dy = boost::make_shared<cuPartialDerivativeOperator<float,4>>(1);\n  \tDy->set_weight(pics_weight);\n  \tDy->set_domain_dimensions(&is_dims);\n  \tDy->set_codomain_dimensions(&is_dims);\n\n\n  \tauto Dz = boost::make_shared<cuPartialDerivativeOperator<float,4>>(2);\n  \tDz->set_weight(pics_weight);\n  \tDz->set_domain_dimensions(&is_dims);\n  \tDz->set_codomain_dimensions(&is_dims);\n\n  \tsolver.add_regularization_group({Dx,Dy,Dz},prior);\n\n\n  }*/\n\n/*\n\tif (tv_weight > 0){\n\n\t\tauto Dx = boost::make_shared<cuDCTDerivativeOperator<float>>(0);\n\t\tDx->set_weight(tv_weight);\n\t\tDx->set_domain_dimensions(&is_dims);\n\t\tDx->set_codomain_dimensions(&is_dims);\n\n\t\tauto Dy = boost::make_shared<cuDCTDerivativeOperator<float>>(1);\n\t\tDy->set_weight(tv_weight);\n\t\tDy->set_domain_dimensions(&is_dims);\n\t\tDy->set_codomain_dimensions(&is_dims);\n\n\n\t\tauto Dz = boost::make_shared<cuDCTDerivativeOperator<float>>(2);\n\t\tDz->set_weight(tv_weight);\n\t\tDz->set_domain_dimensions(&is_dims);\n\t\tDz->set_codomain_dimensions(&is_dims);\n\n\n\n\t\tsolver.add_regularization_group({Dx,Dy,Dz});\n\n\n\t}\n\n*/\n\n\tif (dct_weight > 0){\n\t\tauto dctOp = boost::make_shared<cuDCTOperator<float>>();\n\t\tdctOp->set_domain_dimensions(&is_dims);\n\t\tdctOp->set_weight(dct_weight);\n\t\tsolver.add_regularization_operator(dctOp);\n\t}\n\n\tauto E = boost::make_shared<CBSubsetOperator<cuNDArray> >(subsets);\n\n\n\t//E->setup(ps,binning,imageDimensions);\n\tE->setup(ps,binning,imageDimensions);\n\tE->set_domain_dimensions(&is_dims);\n\tE->set_codomain_dimensions(ps->get_projections()->get_dimensions().get());\n\n\tsolver.set_encoding_operator(E);\n\n\n\n\t//auto projections = boost::make_shared<cuNDArray<float>>(*ps->get_projections());\n\thoCuNDArray<float> projections = *ps->get_projections();\n\tps->set_projections(boost::shared_ptr<hoCuNDArray<float>>());\n\tstd::cout << \"Projection norm:\" << nrm2(&projections) << std::endl;\n\t//E->set_use_offset_correction(false);\n\n\t//boost::shared_ptr<cuNDArray<bool>> mask;\n\t//mask = E->calculate_mask(projections,0.03f);\n\t//ps->set_projections(boost::shared_ptr<hoCuNDArray<float>>()); //Clear projections from host memory.\n\t{\n\t\tauto cu_proj = cuNDArray<float>(projections);\n\t\tE->offset_correct(&cu_proj);\n\t\tcu_proj.to_host(&projections);\n\t}\n\t//E->set_mask(mask);\n\tstd::cout << \"Projection norm:\" << nrm2(&projections) << std::endl;\n\n\n\n\t//solver.set_damping(1e-6);\n\n\t/*\n    boost::shared_ptr<hoCuNDArray<float> > prior;\n\n  if (vm.count(\"use_prior\")) {\n  \tprior = calculate_prior(binning,ps,projections,is_dims,imageDimensions);\n  \tsolver.set_x0(prior);\n  }\n\t */\n\tboost::shared_ptr<hoNDArray<float>> result;\n\t{\n\t\tGPUTimer tim(\"Solver\");\n\t\tresult = solver.solve(&projections);\n\t}\n//\tglobal_timer.reset();\n\tstd::cout << \"Penguin\" << nrm2(result.get()) << std::endl;\n\n\tstd::cout << \"Result sum \" << asum(result.get()) << std::endl;\n\n\t//apply_mask(result.get(),mask.get());\n\n\tstd::cout << \"Result sum \" << asum(result.get()) << std::endl;\n\t//saveNDArray2HDF5(result.get(),outputFile,imageDimensions,vector_td<float,3>(0),command_line_string.str(),iterations);\n\n\n\n\tsaveNDArray2HDF5(result.get(),outputFile,imageDimensions,floatd3(0,0,0),command_line_string.str(),iterations);\n//\twrite_nd_array(result.get(),\"reconstruction.real\");\n\t//write_dicom(result.get(),command_line_string.str(),imageDimensions);\n\n\n\n}\n", "meta": {"hexsha": "4829388544f38e2c7a3474892803a53467dc6b66", "size": 17036, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xray/hoCuCBOS_reconstruct.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/hoCuCBOS_reconstruct.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/hoCuCBOS_reconstruct.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": 36.3240938166, "max_line_length": 229, "alphanum_fraction": 0.7218830711, "num_tokens": 4726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2984312616784296}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2009 Ilya Baran <ibaran@mit.edu>\n//\n// This Source Code Form is subject to the terms of the Mozilla\n// Public License v. 2.0. If a copy of the MPL was not distributed\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n#ifndef KDBVH_H_INCLUDED\n#define KDBVH_H_INCLUDED\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/StdVector>\n#include <algorithm>\n#include <queue>\n\n#include \"../BVHLeaf.hpp\"\n\nnamespace Eigen { \n\nnamespace internal {\n\n//internal pair class for the BVH--used instead of std::pair because of alignment\ntemplate<typename Scalar, int Dim>\nstruct vector_int_pair\n{\nEIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF_VECTORIZABLE_FIXED_SIZE(Scalar, Dim)\n  typedef Eigen::Matrix<Scalar, Dim, 1> VectorType;\n\n  vector_int_pair(const VectorType &v, int i) : first(v), second(i) {}\n\n  VectorType first;\n  int second;\n};\n\n//these templates help the tree initializer get the bounding boxes either from a provided\n//iterator range or using bounding_box in a unified way\ntemplate<typename ObjectList, typename VolumeList, typename BoxIter>\nstruct get_boxes_helper {\n  void operator()(const ObjectList &objects, BoxIter boxBegin, BoxIter boxEnd, VolumeList &outBoxes)\n  {\n    outBoxes.insert(outBoxes.end(), boxBegin, boxEnd);\n    eigen_assert(outBoxes.size() == objects.size());\n  }\n};\n\ntemplate<typename ObjectList, typename VolumeList>\nstruct get_boxes_helper<ObjectList, VolumeList, int> {\n  void operator()(const ObjectList &objects, int, int, VolumeList &outBoxes)\n  {\n    outBoxes.reserve(objects.size());\n    for(int i = 0; i < (int)objects.size(); ++i)\n      outBoxes.push_back(bounding_box(objects[i]));\n  }\n};\n\n} // end namespace internal\n\n\n/** \\class KdBVH\n *  \\brief A simple bounding volume hierarchy based on AlignedBox\n *\n *  \\param _Scalar The underlying scalar type of the bounding boxes\n *  \\param _Dim The dimension of the space in which the hierarchy lives\n *  \\param _Object The object type that lives in the hierarchy.  It must have value semantics.  Either bounding_box(_Object) must\n *                 be defined and return an AlignedBox<_Scalar, _Dim> or bounding boxes must be provided to the tree initializer.\n *\n *  This class provides a simple (as opposed to optimized) implementation of a bounding volume hierarchy analogous to a Kd-tree.\n *  Given a sequence of objects, it computes their bounding boxes, constructs a Kd-tree of their centers\n *  and builds a BVH with the structure of that Kd-tree.  When the elements of the tree are too expensive to be copied around,\n *  it is useful for _Object to be a pointer.\n */\ntemplate<typename _Scalar, int _Dim, typename _Object> class KdBVH\n{\npublic:\n  enum { Dim = _Dim };\n  typedef _Object Object;\n  typedef std::vector<Object, aligned_allocator<Object> > ObjectList;\n  typedef _Scalar Scalar;\n  //typedef AlignedBox<Scalar, Dim> Volume;\n  typedef mcl::BoundingBox<Scalar, Dim> Volume;\n  typedef std::vector<Volume, Eigen::aligned_allocator<Volume> > VolumeList;\n  typedef int Index;\n  typedef const int *VolumeIterator; //the iterators are just pointers into the tree's vectors\n  typedef const Object *ObjectIterator;\n\n  KdBVH() {}\n\n  /** Given an iterator range over \\a Object references, constructs the BVH.  Requires that bounding_box(Object) return a Volume. */\n  template<typename Iter> KdBVH(Iter begin, Iter end) { init(begin, end, 0, 0); } //int is recognized by init as not being an iterator type\n\n  /** Given an iterator range over \\a Object references and an iterator range over their bounding boxes, constructs the BVH */\n  template<typename OIter, typename BIter> KdBVH(OIter begin, OIter end, BIter boxBegin, BIter boxEnd) { init(begin, end, boxBegin, boxEnd); }\n\n  /** Given an iterator range over \\a Object references, constructs the BVH, overwriting whatever is in there currently.\n    * Requires that bounding_box(Object) return a Volume. */\n  template<typename Iter> void init(Iter begin, Iter end) { init(begin, end, 0, 0); }\n\n  /** Given an iterator range over \\a Object references and an iterator range over their bounding boxes,\n    * constructs the BVH, overwriting whatever is in there currently. */\n  template<typename OIter, typename BIter> void init(OIter begin, OIter end, BIter boxBegin, BIter boxEnd)\n  {\n    objects.clear();\n    boxes.clear();\n    children.clear();\n\n    objects.insert(objects.end(), begin, end);\n    int n = static_cast<int>(objects.size());\n\n    if(n < 2)\n      return; //if we have at most one object, we don't need any internal nodes\n\n    VolumeList objBoxes;\n    VIPairList objCenters;\n\n    //compute the bounding boxes depending on BIter type\n    internal::get_boxes_helper<ObjectList, VolumeList, BIter>()(objects, boxBegin, boxEnd, objBoxes);\n\n    objCenters.reserve(n);\n    boxes.reserve(n - 1);\n    children.reserve(2 * n - 2);\n\n    for(int i = 0; i < n; ++i)\n      objCenters.push_back(VIPair(objBoxes[i].center(), i));\n\n    build(objCenters, 0, n, objBoxes, 0); //the recursive part of the algorithm\n\n    ObjectList tmp(n);\n    tmp.swap(objects);\n    for(int i = 0; i < n; ++i)\n      objects[i] = tmp[objCenters[i].second];\n  }\n\n  /** \\returns the index of the root of the hierarchy */\n  inline Index getRootIndex() const { return (int)boxes.size() - 1; }\n\n  /** Given an \\a index of a node, on exit, \\a outVBegin and \\a outVEnd range over the indices of the volume children of the node\n    * and \\a outOBegin and \\a outOEnd range over the object children of the node */\n  EIGEN_STRONG_INLINE void getChildren(Index index, VolumeIterator &outVBegin, VolumeIterator &outVEnd,\n                                       ObjectIterator &outOBegin, ObjectIterator &outOEnd) const\n  { //inlining this function should open lots of optimization opportunities to the compiler\n    if(index < 0) {\n      outVBegin = outVEnd;\n      if(!objects.empty())\n        outOBegin = &(objects[0]);\n      outOEnd = outOBegin + objects.size(); //output all objects--necessary when the tree has only one object\n      return;\n    }\n\n    int numBoxes = static_cast<int>(boxes.size());\n\n    int idx = index * 2;\n    if(children[idx + 1] < numBoxes) { //second index is always bigger\n      outVBegin = &(children[idx]);\n      outVEnd = outVBegin + 2;\n      outOBegin = outOEnd;\n    }\n    else if(children[idx] >= numBoxes) { //if both children are objects\n      outVBegin = outVEnd;\n      outOBegin = &(objects[children[idx] - numBoxes]);\n      outOEnd = outOBegin + 2;\n    } else { //if the first child is a volume and the second is an object\n      outVBegin = &(children[idx]);\n      outVEnd = outVBegin + 1;\n      outOBegin = &(objects[children[idx + 1] - numBoxes]);\n      outOEnd = outOBegin + 1;\n    }\n  }\n\n  /** \\returns the bounding box of the node at \\a index */\n  inline const Volume &getVolume(Index index) const\n  {\n    return boxes[index];\n  }\n\nprivate:\n  typedef internal::vector_int_pair<Scalar, Dim> VIPair;\n  typedef std::vector<VIPair, aligned_allocator<VIPair> > VIPairList;\n  typedef Matrix<Scalar, Dim, 1> VectorType;\n  struct VectorComparator //compares vectors, or, more specificall, VIPairs along a particular dimension\n  {\n    VectorComparator(int inDim) : dim(inDim) {}\n    inline bool operator()(const VIPair &v1, const VIPair &v2) const { return v1.first[dim] < v2.first[dim]; }\n    int dim;\n  };\n\n  //Build the part of the tree between objects[from] and objects[to] (not including objects[to]).\n  //This routine partitions the objCenters in [from, to) along the dimension dim, recursively constructs\n  //the two halves, and adds their parent node.  TODO: a cache-friendlier layout\n  void build(VIPairList &objCenters, int from, int to, const VolumeList &objBoxes, int dim)\n  {\n    eigen_assert(to - from > 1);\n    if(to - from == 2) {\n      boxes.push_back(objBoxes[objCenters[from].second].merged(objBoxes[objCenters[from + 1].second]));\n      children.push_back(from + (int)objects.size() - 1); //there are objects.size() - 1 tree nodes\n      children.push_back(from + (int)objects.size());\n    }\n    else if(to - from == 3) {\n      int mid = from + 2;\n      std::nth_element(objCenters.begin() + from, objCenters.begin() + mid,\n                        objCenters.begin() + to, VectorComparator(dim)); //partition\n      build(objCenters, from, mid, objBoxes, (dim + 1) % Dim);\n      int idx1 = (int)boxes.size() - 1;\n      boxes.push_back(boxes[idx1].merged(objBoxes[objCenters[mid].second]));\n      children.push_back(idx1);\n      children.push_back(mid + (int)objects.size() - 1);\n    }\n    else {\n      int mid = from + (to - from) / 2;\n      nth_element(objCenters.begin() + from, objCenters.begin() + mid,\n                  objCenters.begin() + to, VectorComparator(dim)); //partition\n      build(objCenters, from, mid, objBoxes, (dim + 1) % Dim);\n      int idx1 = (int)boxes.size() - 1;\n      build(objCenters, mid, to, objBoxes, (dim + 1) % Dim);\n      int idx2 = (int)boxes.size() - 1;\n      boxes.push_back(boxes[idx1].merged(boxes[idx2]));\n      children.push_back(idx1);\n      children.push_back(idx2);\n    }\n  }\n\n  std::vector<int> children; //children of x are children[2x] and children[2x+1], indices bigger than boxes.size() index into objects.\n  VolumeList boxes;\n  ObjectList objects;\n};\n\n} // end namespace Eigen\n\n#endif //KDBVH_H_INCLUDED\n", "meta": {"hexsha": "c69afc8fd4478fcffc88b372d1130060383bf67a", "size": 9331, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/MCL/ccd_internal/KdBVH.hpp", "max_stars_repo_name": "mattoverby/mclccd", "max_stars_repo_head_hexsha": "2137e4edee822c62c4aa5485cb83d7f8191c950c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/MCL/ccd_internal/KdBVH.hpp", "max_issues_repo_name": "mattoverby/mclccd", "max_issues_repo_head_hexsha": "2137e4edee822c62c4aa5485cb83d7f8191c950c", "max_issues_repo_licenses": ["MIT"], "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/MCL/ccd_internal/KdBVH.hpp", "max_forks_repo_name": "mattoverby/mclccd", "max_forks_repo_head_hexsha": "2137e4edee822c62c4aa5485cb83d7f8191c950c", "max_forks_repo_licenses": ["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.2198275862, "max_line_length": 142, "alphanum_fraction": 0.6913514093, "num_tokens": 2428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.29839804855571744}}
{"text": "#ifndef GRAPHS_H_\n#define GRAPHS_H_\n\n#include <cstddef>\n#include <vector>\n#include <Eigen/Sparse>\n#include \"multi_array.hpp\"\n\nnamespace graphs {\n\ntypedef std::size_t NodeID;\ntypedef std::size_t Index;\n\ntemplate<typename TReal=void>\nstruct EdgeTail {\n\n  EdgeTail() {\n    source = 0;\n    weight = 1;\n  }\n\n  EdgeTail(NodeID source_node, TReal source_weight) : \n      source(source_node), weight(source_weight) {}\n\n  NodeID source;\n  TReal weight;\n};\n\ntemplate<>\nstruct EdgeTail<void> {\n\n  EdgeTail() {\n    source = 0;\n  }\n\n  EdgeTail(NodeID source_node) : \n      source(source_node) {}\n\n  NodeID source;\n};\n\ntemplate<typename TReal=void>\nclass PredecessorGraph {\n  public:\n    typedef std::size_t NodeID;\n    typedef std::size_t Index;\n\n    /*\n     * When building from an edge list it is assumed nodes are labelled\n     * contiguously starting from 0 to num_nodes-1\n     */\n    PredecessorGraph() : PredecessorGraph(0) {\n    }\n\n    PredecessorGraph(NodeID num_nodes)\n        : num_nodes_(num_nodes) {\n      graph_.resize(num_nodes);\n      num_edges_ = 0;\n      for (NodeID iii = 0; iii < num_nodes; ++iii) {\n        graph_[iii].resize(0);\n      }\n    }\n\n    PredecessorGraph(const std::vector< std::vector<EdgeTail<TReal>> >& graph) : graph_(graph) {\n      num_nodes_ = graph_.size();\n      num_edges_ = CalcNumEdges();\n    }\n\n    PredecessorGraph(const PredecessorGraph<TReal>& other) : graph_(other.graph_),\n        num_nodes_(other.num_nodes_), num_edges_(other.num_edges_) {}\n\n    PredecessorGraph(PredecessorGraph<TReal>&& other) : graph_(std::move(other.graph_)),\n        num_nodes_(std::move(other.num_nodes_)), \n        num_edges_(std::move(other.num_edges_)) {}\n\n    PredecessorGraph<TReal>& operator=(const PredecessorGraph<TReal>& other) {\n      graph_ = other.graph_;\n      num_nodes_ = other.num_nodes_;\n      num_edges_ = other.num_edges_;\n      return *this;\n    }\n\n    PredecessorGraph<TReal>& operator=(PredecessorGraph<TReal>&& other) {\n      graph_ = std::move(other.graph_);\n      num_nodes_ = std::move(other.num_nodes_);\n      num_edges_ = std::move(other.num_edges_);\n      return *this;\n    }\n\n    std::size_t CalcNumEdges() const {\n      std::size_t sum = 0;\n      for (NodeID iii = 0; iii < graph_.size(); iii++) {\n        sum += graph_[iii].size();\n      }\n\n      return sum;\n    }\n\n    std::size_t NumEdges() const {\n      return num_edges_;\n    }\n\n    std::size_t NumNodes() const {\n      return num_nodes_;\n    }\n\n    const std::vector<EdgeTail<TReal>>& Predecessors(NodeID node) const {\n      return graph_[node];\n    }\n\n    void AddEdge(NodeID source, NodeID target, TReal weight=1) {\n      // It is assumed the Node should exist, so new nodes are added\n      // up to the NodeID of the source or target\n      if (source >= num_nodes_) {\n        std::size_t num_new_nodes = source - num_nodes_ + 1;\n        for (Index iii = 0; iii < num_new_nodes; ++iii) {\n          graph_.push_back(std::vector<EdgeTail<TReal>>(0));\n          ++num_nodes_;\n        }\n      }\n\n      if (target >= num_nodes_) {\n        std::size_t num_new_nodes = target - num_nodes_ + 1;\n        for (Index iii = 0; iii < num_new_nodes; ++iii) {\n          graph_.push_back(std::vector<EdgeTail<TReal>>(0));\n          ++num_nodes_;\n        }\n      }\n\n      graph_[target].push_back(EdgeTail<TReal>(source, weight));\n      ++num_edges_;\n    }\n\n  protected:\n    std::vector< std::vector<EdgeTail<TReal>> > graph_;\n    std::size_t num_nodes_;\n    std::size_t num_edges_;\n};\n\ntemplate<>\nclass PredecessorGraph<void> {\n  public:\n    typedef std::size_t NodeID;\n    typedef std::size_t Index;\n\n    /*\n     * When building from an edge list it is assumed nodes are labelled\n     * contiguously starting from 0 to num_nodes-1\n     */\n    PredecessorGraph() : PredecessorGraph(0) {\n    }\n\n    PredecessorGraph(NodeID num_nodes)\n        : num_nodes_(num_nodes) {\n      graph_.resize(num_nodes);\n      num_edges_ = 0;\n      for (NodeID iii = 0; iii < num_nodes; ++iii) {\n        graph_[iii].resize(0);\n      }\n    }\n\n    PredecessorGraph(const std::vector< std::vector<EdgeTail<>> >& graph) : graph_(graph) {\n      num_nodes_ = graph_.size();\n      num_edges_ = CalcNumEdges();\n    }\n\n    PredecessorGraph(const PredecessorGraph& other) : graph_(other.graph_),\n        num_nodes_(other.num_nodes_), num_edges_(other.num_edges_) {}\n\n    PredecessorGraph(PredecessorGraph&& other) : graph_(std::move(other.graph_)),\n        num_nodes_(std::move(other.num_nodes_)), \n        num_edges_(std::move(other.num_edges_)) {}\n\n    PredecessorGraph& operator=(const PredecessorGraph& other) {\n      graph_ = other.graph_;\n      num_nodes_ = other.num_nodes_;\n      num_edges_ = other.num_edges_;\n      return *this;\n    }\n\n    PredecessorGraph& operator=(PredecessorGraph&& other) {\n      graph_ = std::move(other.graph_);\n      num_nodes_ = std::move(other.num_nodes_);\n      num_edges_ = std::move(other.num_edges_);\n      return *this;\n    }\n\n    std::size_t CalcNumEdges() const {\n      std::size_t sum = 0;\n      for (NodeID iii = 0; iii < graph_.size(); iii++) {\n        sum += graph_[iii].size();\n      }\n\n      return sum;\n    }\n\n    std::size_t NumEdges() const {\n      return num_edges_;\n    }\n\n    std::size_t NumNodes() const {\n      return num_nodes_;\n    }\n\n    const std::vector<EdgeTail<>>& Predecessors(NodeID node) const {\n      return graph_[node];\n    }\n\n    // Automatically resizes graph if new nodes are introduced\n    void AddEdge(NodeID source, NodeID target) {\n      // It is assumed the Node should exist, so new nodes are added\n      // up to the NodeID of the source or target\n      if (source >= num_nodes_) {\n        std::size_t num_new_nodes = source - num_nodes_ + 1;\n        for (Index iii = 0; iii < num_new_nodes; ++iii) {\n          graph_.push_back(std::vector<EdgeTail<>>(0));\n          ++num_nodes_;\n        }\n      }\n\n      if (target >= num_nodes_) {\n        std::size_t num_new_nodes = target - num_nodes_ + 1;\n        for (Index iii = 0; iii < num_new_nodes; ++iii) {\n          graph_.push_back(std::vector<EdgeTail<>>(0));\n          ++num_nodes_;\n        }\n      }\n\n      graph_[target].push_back(EdgeTail<>(source));\n      ++num_edges_;\n    }\n\n  protected:\n    std::vector< std::vector<EdgeTail<>> > graph_;\n    std::size_t num_nodes_;\n    std::size_t num_edges_;\n};\n\n/*\n * edge list may exclude end nodes if they aren't connected, so it is\n * insufficient to just pass a node list.\n * First dimension is NumEdges, second dimension is [source, target]\n * If there are weights then pass weight array (must be same size as edges)\n */\n\ntemplate<typename Integer, template<typename, Index> class multi>\nPredecessorGraph<> ConvertEdgeListToPredecessorGraph(const multi<Integer, 2>& edge_list) {\n  PredecessorGraph<> graph = PredecessorGraph<>();\n  const multi_array::ArrayView<Integer, 2> edge_view = edge_list.accessor();\n  for (Index iii = 0; iii < edge_view.extent(0); ++iii) {\n    graph.AddEdge(edge_view[iii][0], edge_view[iii][1]);\n  }\n\n  return graph;\n}\n\ntemplate<typename Integer, typename TReal, template<typename, Index> class multi>\nPredecessorGraph<TReal> ConvertEdgeListToPredecessorGraph(const multi<Integer, 2>& edge_list,\n    const multi<TReal, 1>& weights) {\n  PredecessorGraph<TReal> graph = PredecessorGraph<TReal>();\n  const multi_array::ArrayView<Integer, 2> edge_view = edge_list.accessor();\n  const multi_array::ArrayView<TReal, 1> weight_view = weights.accessor();\n  for (Index iii = 0; iii < edge_view.extent(0); ++iii) {\n    graph.AddEdge(edge_view[iii][0], edge_view[iii][1], weight_view[iii]);\n  }\n\n  return graph;\n}\n\n/*\n * Converts an edge list into a sparse matrix. The tail_size, is the number\n * of nodes that act as the source of the links, and head_size is the number\n * of nodes that act as the sink of the links. For a standard graph this is\n * just the total number of nodes in the graph, else if the graph is\n * bipartite, then one will be larger than the other.\n * For edge list, the order of the list should be row-major\n * with shape Ex2 with major axis as the edge with (tail, head) so that\n * X[edge#][0]=tail, X[edge#][1]=head\n *\n * Because Eigen uses Fortran's column major format, the ordering will be\n * reversed in order to preserve the proper direction of the links in the\n * sparse matrix.\n *\n * The resulting sparse matrix shape is: Head x Tail\n * Where Tail == # cols, and Head == # rows\n */\ntemplate<typename TReal, template<typename, Index> class multi, typename Integer>\nEigen::SparseMatrix<TReal> ConvertEdgeListToSparseMatrix(const multi<Integer, 2>& edge_list,\n                                                         const int num_tail_nodes,\n                                                         const int num_head_nodes) {\n\n  const auto edge_view = edge_list.accessor();\n  std::vector<Eigen::Triplet<TReal>> matrix_elements(edge_view.extent(0));\n  for (std::size_t i = 0; i < edge_view.extent(0); ++i) {\n    matrix_elements[i] = Eigen::Triplet<TReal>(static_cast<int>(edge_view[i][1]),\n                                               static_cast<int>(edge_view[i][0]), 1);\n  }\n  Eigen::SparseMatrix<TReal> graph(num_head_nodes, num_tail_nodes);\n  graph.setFromTriplets(matrix_elements.begin(), matrix_elements.end());\n\n  return graph;\n};\n\ntemplate<typename TReal, template<typename, Index> class MultiArray2D,\n         template<typename, Index> class MultiArray1D, typename Integer>\nEigen::SparseMatrix<TReal> ConvertEdgeListToSparseMatrix(const MultiArray2D<Integer, 2>& edge_list,\n                                                         const int num_tail_nodes,\n                                                         const int num_head_nodes,\n                                                         const MultiArray1D<TReal, 1>& weights) {\n\n  const auto edge_view = edge_list.accessor();\n  const auto weight_view = weights.accessor();\n  std::vector<Eigen::Triplet<TReal>> matrix_elements(edge_view.extent(0));\n  for (std::size_t i = 0; i < edge_view.extent(0); ++i) {\n    matrix_elements[i] = Eigen::Triplet<TReal>(static_cast<int>(edge_view[i][1]),\n                                               static_cast<int>(edge_view[i][0]),\n                                               weight_view[i]);\n  }\n  Eigen::SparseMatrix<TReal> graph(num_head_nodes, num_tail_nodes);\n  graph.setFromTriplets(matrix_elements.begin(), matrix_elements.end());\n\n  return graph;\n};\n\n} // End graphs namespace\n\n#endif /* GRAPHS_H_ */", "meta": {"hexsha": "33df301278db8e2f24dc087374cbc513cfec5939", "size": 10395, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "alectrnn/common/graphs.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/common/graphs.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/common/graphs.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": 31.7889908257, "max_line_length": 99, "alphanum_fraction": 0.6354016354, "num_tokens": 2641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.29839804190599606}}
{"text": "//=======================================================================\r\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\r\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek\r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n//=======================================================================\r\n#include <boost/config.hpp>\r\n#include <iostream>\r\n#include <fstream>\r\n#include <string>\r\n#include <algorithm>\r\n#include <map>\r\n#include <boost/pending/stringtok.hpp>\r\n#include <boost/utility.hpp>\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/visitors.hpp>\r\n#include <boost/graph/breadth_first_search.hpp>\r\n#include <boost/graph/depth_first_search.hpp>\r\n\r\n\r\ntemplate <class Distance>\r\nclass calc_distance_visitor : public boost::bfs_visitor<>\r\n{\r\npublic:\r\n  calc_distance_visitor(Distance d) : distance(d) { }\r\n\r\n  template <class Graph>\r\n  void tree_edge(typename boost::graph_traits<Graph>::edge_descriptor e,\r\n                 Graph& g)\r\n  {\r\n    typename boost::graph_traits<Graph>::vertex_descriptor u, v;\r\n    u = boost::source(e, g);\r\n    v = boost::target(e, g);\r\n    distance[v] = distance[u] + 1;\r\n  }\r\nprivate:\r\n  Distance distance;\r\n};\r\n\r\n\r\ntemplate <class VertexNameMap, class DistanceMap>\r\nclass print_tree_visitor : public boost::dfs_visitor<>\r\n{\r\npublic:\r\n  print_tree_visitor(VertexNameMap n, DistanceMap d) : name(n), distance(d) { }\r\n  template <class Graph>\r\n  void \r\n  discover_vertex(typename boost::graph_traits<Graph>::vertex_descriptor v,\r\n            Graph&)\r\n  {\r\n    typedef typename boost::property_traits<DistanceMap>::value_type Dist;\r\n    // indentation based on depth\r\n    for (Dist i = 0; i < distance[v]; ++i)\r\n      std::cout << \"  \";\r\n    std::cout << name[v] << std::endl;\r\n  }\r\n\r\n  template <class Graph>\r\n  void tree_edge(typename boost::graph_traits<Graph>::edge_descriptor e,\r\n                 Graph& g)\r\n  {\r\n    distance[boost::target(e, g)] = distance[boost::source(e, g)] + 1;\r\n  }  \r\n\r\nprivate:\r\n  VertexNameMap name;\r\n  DistanceMap distance;\r\n};\r\n\r\nint\r\nmain()\r\n{\r\n  using namespace boost;\r\n\r\n  std::ifstream datafile(\"./boost_web.dat\");\r\n  if (!datafile) {\r\n    std::cerr << \"No ./boost_web.dat file\" << std::endl;\r\n    return -1;\r\n  }\r\n\r\n  //===========================================================================\r\n  // Declare the graph type and object, and some property maps.\r\n\r\n  typedef adjacency_list<vecS, vecS, directedS, \r\n    property<vertex_name_t, std::string, \r\n      property<vertex_color_t, default_color_type> >,\r\n    property<edge_name_t, std::string, property<edge_weight_t, int> >\r\n  > Graph;\r\n\r\n  typedef graph_traits<Graph> Traits;\r\n  typedef Traits::vertex_descriptor Vertex;\r\n  typedef Traits::edge_descriptor Edge;\r\n\r\n  typedef std::map<std::string, Vertex> NameVertexMap;\r\n  NameVertexMap name2vertex;\r\n  Graph g;\r\n\r\n  typedef property_map<Graph, vertex_name_t>::type NameMap;\r\n  NameMap node_name  = get(vertex_name, g);\r\n  property_map<Graph, edge_name_t>::type link_name = get(edge_name, g);\r\n\r\n  //===========================================================================\r\n  // Read the data file and construct the graph.\r\n  \r\n  std::string line;\r\n  while (std::getline(datafile,line)) {\r\n\r\n    std::list<std::string> line_toks;\r\n    boost::stringtok(line_toks, line, \"|\");\r\n\r\n    NameVertexMap::iterator pos; \r\n    bool inserted;\r\n    Vertex u, v;\r\n\r\n    std::list<std::string>::iterator i = line_toks.begin();\r\n\r\n    boost::tie(pos, inserted) = name2vertex.insert(std::make_pair(*i, Vertex()));\r\n    if (inserted) {\r\n      u = add_vertex(g);\r\n      put(node_name, u, *i);\r\n      pos->second = u;\r\n    } else\r\n      u = pos->second;\r\n    ++i;\r\n\r\n    std::string hyperlink_name = *i++;\r\n      \r\n    boost::tie(pos, inserted) = name2vertex.insert(std::make_pair(*i, Vertex()));\r\n    if (inserted) {\r\n      v = add_vertex(g);\r\n      put(node_name, v, *i);\r\n      pos->second = v;\r\n    } else\r\n      v = pos->second;\r\n\r\n    Edge e;\r\n    boost::tie(e, inserted) = add_edge(u, v, g);\r\n    if (inserted) {\r\n      put(link_name, e, hyperlink_name);\r\n    }\r\n  }\r\n\r\n  //===========================================================================\r\n  // Calculate the diameter of the graph.\r\n\r\n  typedef Traits::vertices_size_type size_type;\r\n  typedef std::vector<size_type> IntVector;\r\n  // Create N x N matrix for storing the shortest distances\r\n  // between each vertex. Initialize all distances to zero.\r\n  std::vector<IntVector> d_matrix(num_vertices(g),\r\n                                  IntVector(num_vertices(g), 0));\r\n\r\n  size_type i;\r\n  for (i = 0; i < num_vertices(g); ++i) {\r\n    calc_distance_visitor<size_type*> vis(&d_matrix[i][0]);\r\n    Traits::vertex_descriptor src = vertices(g).first[i];\r\n    breadth_first_search(g, src, boost::visitor(vis));\r\n  }\r\n\r\n  size_type diameter = 0;\r\n  BOOST_USING_STD_MAX();\r\n  for (i = 0; i < num_vertices(g); ++i)\r\n    diameter = max BOOST_PREVENT_MACRO_SUBSTITUTION(diameter, *std::max_element(d_matrix[i].begin(), \r\n                                                    d_matrix[i].end()));\r\n  \r\n  std::cout << \"The diameter of the boost web-site graph is \" << diameter\r\n            << std::endl << std::endl;\r\n\r\n  std::cout << \"Number of clicks from the home page: \" << std::endl;\r\n  Traits::vertex_iterator vi, vi_end;\r\n  for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n    std::cout << d_matrix[0][*vi] << \"\\t\" << node_name[*vi] << std::endl;\r\n  std::cout << std::endl;\r\n  \r\n  //===========================================================================\r\n  // Print out the breadth-first search tree starting at the home page\r\n\r\n  // Create storage for a mapping from vertices to their parents\r\n  std::vector<Traits::vertex_descriptor> parent(num_vertices(g));\r\n  for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n    parent[*vi] = *vi;\r\n\r\n  // Do a BFS starting at the home page, recording the parent of each\r\n  // vertex (where parent is with respect to the search tree).\r\n  Traits::vertex_descriptor src = vertices(g).first[0];\r\n  breadth_first_search\r\n    (g, src, \r\n     boost::visitor(make_bfs_visitor(record_predecessors(&parent[0],\r\n                                                         on_tree_edge()))));\r\n\r\n  // Add all the search tree edges into a new graph\r\n  Graph search_tree(num_vertices(g));\r\n  boost::tie(vi, vi_end) = vertices(g);\r\n  ++vi;\r\n  for (; vi != vi_end; ++vi)\r\n    add_edge(parent[*vi], *vi, search_tree);\r\n\r\n  std::cout << \"The breadth-first search tree:\" << std::endl;\r\n\r\n  // Print out the search tree. We use DFS because it visits\r\n  // the tree nodes in the order that we want to print out:\r\n  // a directory-structure like format.\r\n  std::vector<size_type> dfs_distances(num_vertices(g), 0);\r\n  print_tree_visitor<NameMap, size_type*>\r\n    tree_printer(node_name, &dfs_distances[0]);\r\n  for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n    get(vertex_color, g)[*vi] = white_color;\r\n  depth_first_visit(search_tree, src, tree_printer, get(vertex_color, g));\r\n  \r\n  return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "4f56c3702aa9266253c3c34a7155b47031cd23c6", "size": 7157, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/boost_web_graph.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/graph/example/boost_web_graph.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/graph/example/boost_web_graph.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 33.4439252336, "max_line_length": 102, "alphanum_fraction": 0.5949420148, "num_tokens": 1737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.29827247364548753}}
{"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 <Eigen/Geometry>\n#include <unsupported/Eigen/AutoDiff>\n#include <visualization_msgs/Marker.h>\n#include <arc_utilities/eigen_helpers.hpp>\n#include <arc_utilities/voxel_grid.hpp>\n#include <arc_utilities/pretty_print.hpp>\n#include <sdf_tools/SDF.h>\n\n#ifndef SDF_HPP\n#define SDF_HPP\n\nnamespace sdf_tools\n{\nusing VoxelGrid::GRID_INDEX;\n\nclass SignedDistanceField : public VoxelGrid::VoxelGrid<float>\n{\nprotected:\n\n  std::string frame_;\n  bool locked_;\n\n  /*\n   * You *MUST* provide valid indices to this function, hence why it is\n   * protected (there are safe wrappers available - use them!)\n   */\n  void FollowGradientsToLocalExtremaUnsafe(\n      VoxelGrid<Eigen::Vector3d>& watershed_map,\n      const int64_t x_index,\n      const int64_t y_index,\n      const int64_t z_index) const;\n\n  bool GradientIsEffectiveFlat(const Eigen::Vector3d& gradient) const;\n\n  GRID_INDEX GetNextFromGradient(const GRID_INDEX& index,\n                                 const Eigen::Vector3d& gradient) const;\n\npublic:\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  inline SignedDistanceField(const std::string& frame,\n                             double resolution,\n                             double x_size,\n                             double y_size,\n                             double z_size,\n                             float OOB_value)\n    : VoxelGrid::VoxelGrid<float>(resolution,\n                                  x_size, y_size, z_size,\n                                  OOB_value),\n      frame_(frame), locked_(false) {}\n\n  inline SignedDistanceField(const Eigen::Isometry3d& origin_transform,\n                             const std::string& frame,\n                             double resolution,\n                             double x_size,\n                             double y_size,\n                             double z_size,\n                             float OOB_value)\n    : VoxelGrid::VoxelGrid<float>(origin_transform, resolution,\n                                  x_size, y_size, z_size,\n                                  OOB_value),\n      frame_(frame), locked_(false) {}\n\n  inline SignedDistanceField(const std::string& frame,\n                             double resolution,\n                             int64_t x_cells,\n                             int64_t y_cells,\n                             int64_t z_cells,\n                             float OOB_value)\n    : VoxelGrid::VoxelGrid<float>(resolution,\n                                  x_cells, y_cells, z_cells,\n                                  OOB_value),\n      frame_(frame), locked_(false) {}\n\n  inline SignedDistanceField(const Eigen::Isometry3d& origin_transform,\n                             const std::string& frame,\n                             double resolution,\n                             int64_t x_cells,\n                             int64_t y_cells,\n                             int64_t z_cells,\n                             float OOB_value)\n    : VoxelGrid::VoxelGrid<float>(origin_transform, resolution,\n                                  x_cells, y_cells, z_cells,\n                                  OOB_value),\n      frame_(frame), locked_(false) {}\n\n  inline SignedDistanceField()\n    : VoxelGrid::VoxelGrid<float>(), frame_(\"\"), locked_(false) {}\n\n  virtual VoxelGrid<float>* Clone() const\n  {\n    return new SignedDistanceField(\n          static_cast<const SignedDistanceField&>(*this));\n  }\n\n  inline bool IsLocked() const\n  {\n      return locked_;\n  }\n\n  inline void Lock()\n  {\n      locked_ = true;\n  }\n\n  inline void Unlock()\n  {\n      locked_ = false;\n  }\n\n  virtual uint64_t SerializeSelf(\n      std::vector<uint8_t>& buffer,\n      const std::function<uint64_t(\n        const float&, std::vector<uint8_t>&)>& value_serializer\n      =arc_helpers::SerializeFixedSizePOD<float>) const;\n\n  virtual uint64_t DeserializeSelf(\n      const std::vector<uint8_t>& buffer, const uint64_t current,\n      const std::function<std::pair<float, uint64_t>(\n        const std::vector<uint8_t>&, const uint64_t)>& value_deserializer\n      =arc_helpers::DeserializeFixedSizePOD<float>);\n\n  /*\n   * Mutable access and setter functions MUST be used carefully!\n   * If you arbitrarily change SDF values, it is not a proper SDF any more!\n   *\n   * Use of these functions can be prevented by calling\n   * SignedDistanceField::Lock() on the SDF\n   */\n\n  virtual std::pair<float&, bool> GetMutable3d(\n      const Eigen::Vector3d& location)\n  {\n    const GRID_INDEX index = LocationToGridIndex3d(location);\n    if (IndexInBounds(index))\n    {\n      return GetMutable(index);\n    }\n    else\n    {\n      return std::pair<float&, bool>(oob_value_, false);\n    }\n  }\n\n  virtual std::pair<float&, bool> GetMutable4d(\n      const Eigen::Vector4d& location)\n  {\n    const GRID_INDEX index = LocationToGridIndex4d(location);\n    if (IndexInBounds(index))\n    {\n      return GetMutable(index);\n    }\n    else\n    {\n      return std::pair<float&, bool>(oob_value_, false);\n    }\n  }\n\n  virtual std::pair<float&, bool> GetMutable(const double x,\n                                             const double y,\n                                             const double z)\n  {\n    const Eigen::Vector4d location(x, y, z, 1.0);\n    return GetMutable4d(location);\n  }\n\n  virtual std::pair<float&, bool> GetMutable(const GRID_INDEX& index)\n  {\n    if (IndexInBounds(index) && !locked_)\n    {\n      return std::pair<float&, bool>(\n            AccessIndex(GetDataIndex(index)), true);\n    }\n    else\n    {\n      return std::pair<float&, bool>(oob_value_, false);\n    }\n  }\n\n  virtual std::pair<float&, bool> GetMutable(const int64_t x_index,\n                                             const int64_t y_index,\n                                             const int64_t z_index)\n  {\n    if (IndexInBounds(x_index, y_index, z_index) && !locked_)\n    {\n      return std::pair<float&, bool>(\n            AccessIndex(GetDataIndex(x_index, y_index, z_index)), true);\n    }\n    else\n    {\n      return std::pair<float&, bool>(oob_value_, false);\n    }\n  }\n\n  virtual bool SetValue3d(const Eigen::Vector3d& location,\n                          const float& value)\n  {\n    const GRID_INDEX index = LocationToGridIndex3d(location);\n    if (IndexInBounds(index))\n    {\n      return SetValue(index, value);\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n  virtual bool SetValue4d(const Eigen::Vector4d& location,\n                          const float& value)\n  {\n    const GRID_INDEX index = LocationToGridIndex4d(location);\n    if (IndexInBounds(index))\n    {\n      return SetValue(index, value);\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n  virtual bool SetValue(const double x,\n                        const double y,\n                        const double z,\n                        const float& value)\n  {\n    const Eigen::Vector4d location(x, y, z, 1.0);\n    return SetValue4d(location, value);\n  }\n\n  virtual bool SetValue(const GRID_INDEX& index,\n                        const float& value)\n  {\n    if (IndexInBounds(index) && !locked_)\n    {\n      AccessIndex(GetDataIndex(index)) = value;\n      return true;\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n  virtual bool SetValue(const int64_t x_index,\n                        const int64_t y_index,\n                        const int64_t z_index,\n                        const float& value)\n  {\n    if (IndexInBounds(x_index, y_index, z_index) && !locked_)\n    {\n      AccessIndex(GetDataIndex(x_index, y_index, z_index)) = value;\n      return true;\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n  virtual bool SetValue3d(const Eigen::Vector3d& location,\n                          float&& value)\n  {\n    const GRID_INDEX index = LocationToGridIndex3d(location);\n    if (IndexInBounds(index))\n    {\n      return SetValue(index, value);\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n  virtual bool SetValue4d(const Eigen::Vector4d& location,\n                          float&& value)\n  {\n    const GRID_INDEX index = LocationToGridIndex4d(location);\n    if (IndexInBounds(index))\n    {\n      return SetValue(index, value);\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n  virtual bool SetValue(const double x,\n                        const double y,\n                        const double z,\n                        float&& value)\n  {\n    const Eigen::Vector4d location(x, y, z, 1.0);\n    return SetValue4d(location, value);\n  }\n\n  virtual bool SetValue(const GRID_INDEX& index,\n                        float&& value)\n  {\n    if (IndexInBounds(index) && !locked_)\n    {\n      AccessIndex(GetDataIndex(index)) = value;\n      return true;\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n  virtual bool SetValue(const int64_t x_index,\n                        const int64_t y_index,\n                        const int64_t z_index,\n                        float&& value)\n  {\n    if (IndexInBounds(x_index, y_index, z_index) && !locked_)\n    {\n      AccessIndex(GetDataIndex(x_index, y_index, z_index)) = value;\n      return true;\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n  inline double GetResolution() const { return GetCellSizes().x(); }\n\n  inline std::string GetFrame() const\n  {\n    return frame_;\n  }\n\n  inline std::vector<double> GetGradient(\n      const double x, const double y, const double z,\n      const bool enable_edge_gradients=false) const\n  {\n    return GetGradient4d(Eigen::Vector4d(x, y, z, 1.0), enable_edge_gradients);\n  }\n\n  inline std::vector<double> GetGradient3d(\n      const Eigen::Vector3d& location,\n      const bool enable_edge_gradients=false) const\n  {\n    const GRID_INDEX index = LocationToGridIndex3d(location);\n    if (IndexInBounds(index))\n    {\n      return GetGradient(index, enable_edge_gradients);\n    }\n    else\n    {\n      return std::vector<double>();\n    }\n  }\n\n  inline std::vector<double> GetGradient4d(\n      const Eigen::Vector4d& location,\n      const bool enable_edge_gradients=false) const\n  {\n    const GRID_INDEX index = LocationToGridIndex4d(location);\n    if (IndexInBounds(index))\n    {\n      return GetGradient(index, enable_edge_gradients);\n    }\n    else\n    {\n      return std::vector<double>();\n    }\n  }\n\n  inline std::vector<double> GetGradient(\n      const GRID_INDEX& index,\n      const bool enable_edge_gradients=false) const\n  {\n    return GetGradient(index.x, index.y, index.z, enable_edge_gradients);\n  }\n\n  inline std::vector<double> GetGradient(\n      const int64_t x_index, const int64_t y_index, const int64_t z_index,\n      const bool enable_edge_gradients=false) const\n  {\n    const std::vector<double> grid_aligned_gradient\n        = GetGridAlignedGradient(x_index, y_index, z_index,\n                                 enable_edge_gradients);\n    if (grid_aligned_gradient.size() == 3)\n    {\n      const Eigen::Quaterniond grid_rotation(origin_transform_.rotation());\n      // Derived from EigenHelpers::RotateVector, but without extra copies\n      const Eigen::Quaterniond temp(0.0,\n                                    grid_aligned_gradient[0],\n                                    grid_aligned_gradient[1],\n                                    grid_aligned_gradient[2]);\n      const Eigen::Quaterniond result\n          = grid_rotation * (temp * grid_rotation.inverse());\n      return std::vector<double>{result.x(),\n                                 result.y(),\n                                 result.z()};\n    }\n    else\n    {\n      return std::vector<double>();\n    }\n  }\n\n  inline std::vector<double> GetGridAlignedGradient(\n      const int64_t x_index, const int64_t y_index, const int64_t z_index,\n      const bool enable_edge_gradients=false) const\n  {\n    // Make sure the index is inside bounds\n    if (IndexInBounds(x_index, y_index, z_index))\n    {\n      // See if the index we're trying to query is one cell in from the edge\n      if ((x_index > 0) && (y_index > 0) && (z_index > 0)\n          && (x_index < (GetNumXCells() - 1))\n          && (y_index < (GetNumYCells() - 1))\n          && (z_index < (GetNumZCells() - 1)))\n      {\n        const double inv_twice_resolution = 1.0 / (2.0 * GetResolution());\n        const double gx = (GetImmutable(x_index + 1, y_index, z_index).first\n                           - GetImmutable(x_index - 1, y_index, z_index).first)\n                          * inv_twice_resolution;\n        const double gy = (GetImmutable(x_index, y_index + 1, z_index).first\n                           - GetImmutable(x_index, y_index - 1, z_index).first)\n                          * inv_twice_resolution;\n        const double gz = (GetImmutable(x_index, y_index, z_index + 1).first\n                           - GetImmutable(x_index, y_index, z_index - 1).first)\n                          * inv_twice_resolution;\n        return std::vector<double>{gx, gy, gz};\n      }\n      // If we're on the edge, handle it specially\n      // TODO: we actually need to handle corners even more carefully,\n      // since if the SDF is build with a virtual border, these cells will\n      // get zero gradient from this approach!\n      else if (enable_edge_gradients)\n      {\n        // Get the \"best\" indices we can use\n        const int64_t low_x_index = std::max((int64_t)0, x_index - 1);\n        const int64_t high_x_index = std::min(GetNumXCells() - 1, x_index + 1);\n        const int64_t low_y_index = std::max((int64_t)0, y_index - 1);\n        const int64_t high_y_index = std::min(GetNumYCells() - 1, y_index + 1);\n        const int64_t low_z_index = std::max((int64_t)0, z_index - 1);\n        const int64_t high_z_index = std::min(GetNumZCells() - 1, z_index + 1);\n        // Compute the axis increments\n        const double x_increment\n            = (high_x_index - low_x_index) * GetResolution();\n        const double y_increment\n            = (high_y_index - low_y_index) * GetResolution();\n        const double z_increment\n            = (high_z_index - low_z_index) * GetResolution();\n        // Compute the gradients for each axis - by default these are zero\n        double gx = 0.0;\n        double gy = 0.0;\n        double gz = 0.0;\n        // Only if the increments are non-zero do we compute the axis gradient\n        if (x_increment > 0.0)\n        {\n          const double inv_x_increment = 1.0 / x_increment;\n          const double high_x_value\n              = GetImmutable(high_x_index, y_index, z_index).first;\n          const double low_x_value\n              = GetImmutable(low_x_index, y_index, z_index).first;\n          // Compute the gradient\n          gx = (high_x_value - low_x_value) * inv_x_increment;\n        }\n        if (y_increment > 0.0)\n        {\n          const double inv_y_increment = 1.0 / y_increment;\n          const double high_y_value\n              = GetImmutable(x_index, high_y_index, z_index).first;\n          const double low_y_value\n              = GetImmutable(x_index, low_y_index, z_index).first;\n          // Compute the gradient\n          gy = (high_y_value - low_y_value) * inv_y_increment;\n        }\n        if (z_increment > 0.0)\n        {\n          const double inv_z_increment = 1.0 / z_increment;\n          const double high_z_value\n              = GetImmutable(x_index, y_index, high_z_index).first;\n          const double low_z_value\n              = GetImmutable(x_index, y_index, low_z_index).first;\n          // Compute the gradient\n          gz = (high_z_value - low_z_value) * inv_z_increment;\n        }\n        // Assemble and return the computed gradient\n        return std::vector<double>{gx, gy, gz};\n      }\n      // Edge gradients disabled, return no gradient\n      else\n      {\n        return std::vector<double>();\n      }\n    }\n    // If we're out of bounds, return no gradient\n    else\n    {\n      return std::vector<double>();\n    }\n  }\n\n  inline std::vector<double> GetSmoothGradient3d(\n      const Eigen::Vector3d& location,\n      const double nominal_window_size) const\n  {\n    return GetSmoothGradient(location.x(), location.y(), location.z(),\n                             nominal_window_size);\n  }\n\n  inline std::vector<double> GetSmoothGradient4d(\n      const Eigen::Vector4d& location,\n      const double nominal_window_size) const\n  {\n    return GetSmoothGradient(location(0), location(1), location(2),\n                             nominal_window_size);\n  }\n\n  inline std::vector<double> GetSmoothGradient(\n      const double x, const double y, const double z,\n      const double nominal_window_size) const\n  {\n    const double ideal_window_size = std::abs(nominal_window_size);\n    if (LocationInBounds(x, y, z))\n    {\n      const double min_x = x - ideal_window_size;\n      const double max_x = x + ideal_window_size;\n      const double min_y = y - ideal_window_size;\n      const double max_y = y + ideal_window_size;\n      const double min_z = z - ideal_window_size;\n      const double max_z = z + ideal_window_size;\n      // Retrieve distance estimates\n      const std::pair<double, bool> point_distance = EstimateDistance(x, y, z);\n      const std::pair<double, bool> mx_distance = EstimateDistance(min_x, y, z);\n      const std::pair<double, bool> px_distance = EstimateDistance(max_x, y, z);\n      const std::pair<double, bool> my_distance = EstimateDistance(x, min_y, z);\n      const std::pair<double, bool> py_distance = EstimateDistance(x, max_y, z);\n      const std::pair<double, bool> mz_distance = EstimateDistance(x, y, min_z);\n      const std::pair<double, bool> pz_distance = EstimateDistance(x, y, max_z);\n      // Compute gradient for each axis\n      const double gx = ComputeAxisSmoothGradient(point_distance,\n                                                  mx_distance,\n                                                  px_distance,\n                                                  x, min_x, max_x);\n      const double gy = ComputeAxisSmoothGradient(point_distance,\n                                                  my_distance,\n                                                  py_distance,\n                                                  y, min_y, max_y);\n      const double gz = ComputeAxisSmoothGradient(point_distance,\n                                                  mz_distance,\n                                                  pz_distance,\n                                                  z, min_z, max_z);\n      return std::vector<double>{gx, gy, gz};\n    }\n    else\n    {\n      return std::vector<double>();\n    }\n  }\n\n  inline std::vector<double> GetSmoothGradient(\n      const GRID_INDEX& index, const double nominal_window_size) const\n  {\n    return GetSmoothGradient4d(GridIndexToLocation(index), nominal_window_size);\n  }\n\n  inline std::vector<double> GetSmoothGradient(\n      const int64_t x_index, const int64_t y_index, const int64_t z_index,\n      const double nominal_window_size) const\n  {\n    return GetSmoothGradient4d(\n          GridIndexToLocation(x_index, y_index, z_index), nominal_window_size);\n  }\n\n  inline std::vector<double> GetAutoDiffGradient3d(\n      const Eigen::Vector3d& location) const\n  {\n    return GetAutoDiffGradient(location.x(), location.y(), location.z());\n  }\n\n  inline std::vector<double> GetAutoDiffGradient4d(\n      const Eigen::Vector4d& location) const\n  {\n    return GetAutoDiffGradient(location(0), location(1), location(2));\n  }\n\n  // TODO: this does not work if you query at cell centers!\n  inline std::vector<double> GetAutoDiffGradient(\n      const double x, const double y, const double z) const\n  {\n    const GRID_INDEX index = LocationToGridIndex(x, y, z);\n    if (IndexInBounds(index))\n    {\n      // Use with AutoDiffScalar\n      typedef Eigen::AutoDiffScalar<Eigen::Vector4d> AScalar;\n      typedef Eigen::Matrix<AScalar, 4, 1> APosition;\n      APosition Alocation;\n      Alocation(0) = x;\n      Alocation(1) = y;\n      Alocation(2) = z;\n      Alocation(3) = 1.0;\n      Alocation(0).derivatives() = Eigen::Vector4d::Unit(0);\n      Alocation(1).derivatives() = Eigen::Vector4d::Unit(1);\n      Alocation(2).derivatives() = Eigen::Vector4d::Unit(2);\n      Alocation(3).derivatives() = Eigen::Vector4d::Unit(3);\n      AScalar Adist = EstimateDistanceInterpolateFromNeighbors<AScalar>(\n                        Alocation, index.x, index.y, index.z);\n      return std::vector<double>{\n        Adist.derivatives()(0), Adist.derivatives()(1), Adist.derivatives()(2)};\n    }\n    else\n    {\n      return std::vector<double>();\n    }\n  }\n\n  inline std::vector<double> GetAutoDiffGradient(const GRID_INDEX& index) const\n  {\n    return GetAutoDiffGradient4d(GridIndexToLocation(index));\n  }\n\n  inline std::vector<double> GetAutoDiffGradient(\n      const int64_t x_index, const int64_t y_index, const int64_t z_index) const\n  {\n    return GetAutoDiffGradient4d(\n          GridIndexToLocation(x_index, y_index, z_index));\n  }\n\nprotected:\n\n  inline double ComputeAxisSmoothGradient(\n      const std::pair<double, bool>& query_point_distance_estimate,\n      const std::pair<double, bool>& minus_axis_distance_estimate,\n      const std::pair<double, bool>& plus_axis_distance_estimate,\n      const double query_point_axis_value,\n      const double minus_point_axis_value,\n      const double plus_point_axis_value) const\n  {\n    if (query_point_distance_estimate.second\n        && minus_axis_distance_estimate.second\n        && plus_axis_distance_estimate.second)\n    {\n      const double window_size = plus_point_axis_value\n                                 - minus_point_axis_value;\n      const double distance_delta = plus_axis_distance_estimate.first\n                                    - minus_axis_distance_estimate.first;\n      return distance_delta / window_size;\n    }\n    else if (query_point_distance_estimate.second\n             && minus_axis_distance_estimate.second)\n    {\n      const double window_size = query_point_axis_value\n                                 - minus_point_axis_value;\n      const double distance_delta = query_point_distance_estimate.first\n                                    - minus_axis_distance_estimate.first;\n      return distance_delta / window_size;\n    }\n    else if (query_point_distance_estimate.second\n             && plus_axis_distance_estimate.second)\n    {\n      const double window_size = plus_point_axis_value\n                                 - query_point_axis_value;\n      const double distance_delta = plus_axis_distance_estimate.first\n                                    - query_point_distance_estimate.first;\n      return distance_delta / window_size;\n    }\n    else\n    {\n      throw std::runtime_error(\n            \"Window size for GetSmoothGradient is too large for SDF\");\n    }\n  }\n\n  template<typename T>\n  inline T BilinearInterpolate(const double low_d1,\n                               const double high_d1,\n                               const double low_d2,\n                               const double high_d2,\n                               const T query_d1,\n                               const T query_d2,\n                               const double l1l2_val,\n                               const double l1h2_val,\n                               const double h1l2_val,\n                               const double h1h2_val) const\n  {\n    Eigen::Matrix<T, 1, 2> d1_offsets;\n    d1_offsets(0, 0) = high_d1 - query_d1;\n    d1_offsets(0, 1) = query_d1 - low_d1;\n    Eigen::Matrix<T, 2, 2> values;\n    values(0, 0) = l1l2_val;\n    values(0, 1) = l1h2_val;\n    values(1, 0) = h1l2_val;\n    values(1, 1) = h1h2_val;\n    Eigen::Matrix<T, 2, 1> d2_offsets;\n    d2_offsets(0, 0) = high_d2 - query_d2;\n    d2_offsets(1, 0) = query_d2 - low_d2;\n    const T multiplier = 1.0 / ((high_d1 - low_d1) * (high_d2 - low_d2));\n    const T bilinear_interpolated\n        = multiplier * d1_offsets * values * d2_offsets;\n    return bilinear_interpolated;\n  }\n\n  template<typename T>\n  inline T BilinearInterpolateDistanceXY(\n      const Eigen::Vector4d& corner_location,\n      const Eigen::Matrix<T, 4, 1>& query_location,\n      const double mxmy_dist, const double mxpy_dist,\n      const double pxmy_dist, const double pxpy_dist) const\n  {\n    return BilinearInterpolate(corner_location(0),\n                               corner_location(0) + GetResolution(),\n                               corner_location(1),\n                               corner_location(1) + GetResolution(),\n                               query_location(0),\n                               query_location(1),\n                               mxmy_dist, mxpy_dist,\n                               pxmy_dist, pxpy_dist);\n  }\n\n  template<typename T>\n  inline T TrilinearInterpolateDistance(\n      const Eigen::Vector4d& corner_location,\n      const Eigen::Matrix<T, 4, 1>& query_location,\n      const double mxmymz_dist, const double mxmypz_dist,\n      const double mxpymz_dist, const double mxpypz_dist,\n      const double pxmymz_dist, const double pxmypz_dist,\n      const double pxpymz_dist, const double pxpypz_dist) const\n  {\n    // Do bilinear interpolation in the lower XY plane\n    const T mz_bilinear_interpolated\n        = BilinearInterpolateDistanceXY(corner_location, query_location,\n                                        mxmymz_dist, mxpymz_dist,\n                                        pxmymz_dist, pxpymz_dist);\n    // Do bilinear interpolation in the upper XY plane\n    const T pz_bilinear_interpolated\n        = BilinearInterpolateDistanceXY(corner_location, query_location,\n                                        mxmypz_dist, mxpypz_dist,\n                                        pxmypz_dist, pxpypz_dist);\n    // Perform linear interpolation/extrapolation between lower and upper planes\n    const double inv_resolution = 1.0 / GetResolution();\n    const T distance_delta\n        = pz_bilinear_interpolated - mz_bilinear_interpolated;\n    const T distance_slope = distance_delta * inv_resolution;\n    const T query_z_delta = query_location(2) - T(corner_location(2));\n    return mz_bilinear_interpolated + (query_z_delta * distance_slope);\n  }\n\n  inline double GetCorrectedCenterDistance(const int64_t x_idx,\n                                           const int64_t y_idx,\n                                           const int64_t z_idx) const\n  {\n    const std::pair<const float&, bool> query\n        = GetImmutable(x_idx, y_idx, z_idx);\n    if (query.second)\n    {\n      const double nominal_sdf_distance = (double)query.first;\n      const double cell_center_distance_offset = GetResolution() * 0.5;\n      if (nominal_sdf_distance >= 0.0)\n      {\n        return nominal_sdf_distance - cell_center_distance_offset;\n      }\n      else\n      {\n        return nominal_sdf_distance + cell_center_distance_offset;\n      }\n    }\n    else\n    {\n        throw std::invalid_argument(\"Index out of bounds\");\n    }\n  }\n\n  template<typename T>\n  std::pair<int64_t, int64_t> GetAxisInterpolationIndices(\n      const int64_t initial_index,\n      const int64_t axis_size,\n      const T axis_offset) const\n  {\n    int64_t lower = initial_index;\n    int64_t upper = initial_index;\n    if (axis_offset >= 0.0)\n    {\n      upper = initial_index + 1;\n      if (upper >= axis_size)\n      {\n        upper = initial_index;\n        lower = initial_index -1;\n        if (lower < 0)\n        {\n          lower = initial_index;\n        }\n      }\n    }\n    else\n    {\n      lower = initial_index - 1;\n      if (lower < 0)\n      {\n        upper = initial_index + 1;\n        lower = initial_index;\n        if (upper >= axis_size)\n        {\n          upper = initial_index;\n        }\n      }\n    }\n    return std::make_pair(lower, upper);\n  }\n\n  template<typename T>\n  inline T EstimateDistanceInterpolateFromNeighbors(\n      const Eigen::Matrix<T, 4, 1>& query_location,\n      const int64_t x_idx, const int64_t y_idx, const int64_t z_idx) const\n  {\n    // Get the query location in grid frame\n    const Eigen::Matrix<T, 4, 1> grid_frame_query_location\n        = GetInverseOriginTransform() * query_location;\n    // Switch between all the possible options of where we are\n    const Eigen::Vector4d cell_center_location\n        = GridIndexToLocationGridFrame(x_idx, y_idx, z_idx);\n    const Eigen::Matrix<T, 4, 1> query_offset\n        = grid_frame_query_location - cell_center_location.cast<T>();\n    // Catch the easiest case\n//    if ((query_offset(0) == 0.0)\n//        && (query_offset(1) == 0.0)\n//        && (query_offset(2) == 0.0))\n//    {\n//      return GetCorrectedCenterDistance(x_idx, y_idx, z_idx);\n//    }\n    // Find the best-matching 8 surrounding cell centers\n    const std::pair<int64_t, int64_t> x_axis_indices\n        = GetAxisInterpolationIndices(x_idx, GetNumXCells(), query_offset(0));\n    const std::pair<int64_t, int64_t> y_axis_indices\n        = GetAxisInterpolationIndices(y_idx, GetNumYCells(), query_offset(1));\n    const std::pair<int64_t, int64_t> z_axis_indices\n        = GetAxisInterpolationIndices(z_idx, GetNumZCells(), query_offset(2));\n    const Eigen::Vector4d lower_corner_location\n        = GridIndexToLocationGridFrame(x_axis_indices.first,\n                                       y_axis_indices.first,\n                                       z_axis_indices.first);\n    const double mxmymz_distance\n        = GetCorrectedCenterDistance(x_axis_indices.first,\n                                     y_axis_indices.first,\n                                     z_axis_indices.first);\n    const double mxmypz_distance\n        = GetCorrectedCenterDistance(x_axis_indices.first,\n                                     y_axis_indices.first,\n                                     z_axis_indices.second);\n    const double mxpymz_distance\n        = GetCorrectedCenterDistance(x_axis_indices.first,\n                                     y_axis_indices.second,\n                                     z_axis_indices.first);\n    const double mxpypz_distance\n        = GetCorrectedCenterDistance(x_axis_indices.first,\n                                     y_axis_indices.second,\n                                     z_axis_indices.second);\n    const double pxmymz_distance\n        = GetCorrectedCenterDistance(x_axis_indices.second,\n                                     y_axis_indices.first,\n                                     z_axis_indices.first);\n    const double pxmypz_distance\n        = GetCorrectedCenterDistance(x_axis_indices.second,\n                                     y_axis_indices.first,\n                                     z_axis_indices.second);\n    const double pxpymz_distance\n        = GetCorrectedCenterDistance(x_axis_indices.second,\n                                     y_axis_indices.second,\n                                     z_axis_indices.first);\n    const double pxpypz_distance\n        = GetCorrectedCenterDistance(x_axis_indices.second,\n                                     y_axis_indices.second,\n                                     z_axis_indices.second);\n    return TrilinearInterpolateDistance(lower_corner_location,\n                                        grid_frame_query_location,\n                                        mxmymz_distance, mxmypz_distance,\n                                        mxpymz_distance, mxpypz_distance,\n                                        pxmymz_distance, pxmypz_distance,\n                                        pxpymz_distance, pxpypz_distance);\n  }\n\npublic:\n\n  inline std::pair<double, bool> EstimateDistance(const double x,\n                                                  const double y,\n                                                  const double z) const\n  {\n      return EstimateDistance4d(Eigen::Vector4d(x, y, z, 1.0));\n  }\n\n  inline std::pair<double, bool> EstimateDistance3d(\n      const Eigen::Vector3d& location) const\n  {\n    const GRID_INDEX index = LocationToGridIndex3d(location);\n    if (IndexInBounds(index))\n    {\n      return std::make_pair(\n            EstimateDistanceInterpolateFromNeighbors<double>(\n              Eigen::Vector4d(location.x(), location.y(), location.z(), 1.0),\n              index.x, index.y, index.z),\n            true);\n    }\n    else\n    {\n      return std::make_pair((double)GetOOBValue(), false);\n    }\n  }\n\n  inline std::pair<double, bool> EstimateDistance4d(\n      const Eigen::Vector4d& location) const\n  {\n    const GRID_INDEX index = LocationToGridIndex4d(location);\n    if (IndexInBounds(index))\n    {\n      return std::make_pair(EstimateDistanceInterpolateFromNeighbors<double>(\n                              location, index.x, index.y, index.z),\n                            true);\n    }\n    else\n    {\n      return std::make_pair((double)GetOOBValue(), false);\n    }\n  }\n\n  inline Eigen::Vector3d ProjectOutOfCollision(\n      const double x, const double y, const double z,\n      const double stepsize_multiplier = 1.0 / 10.0) const\n  {\n    const Eigen::Vector4d result\n        = ProjectOutOfCollision4d(Eigen::Vector4d(x, y, z, 1.0),\n                                  stepsize_multiplier);\n    return result.head<3>();\n  }\n\n  inline Eigen::Vector3d ProjectOutOfCollision3d(\n      const Eigen::Vector3d& location,\n      const double stepsize_multiplier = 1.0 / 10.0) const\n  {\n    return ProjectOutOfCollision(location.x(), location.y(), location.z(),\n                                 stepsize_multiplier);\n  }\n\n  inline Eigen::Vector4d ProjectOutOfCollision4d(\n      const Eigen::Vector4d& location,\n      const double stepsize_multiplier = 1.0 / 10.0) const\n  {\n    return ProjectOutOfCollisionToMinimumDistance4d(location, 0.0,\n                                                    stepsize_multiplier);\n  }\n\n  inline Eigen::Vector3d ProjectOutOfCollisionToMinimumDistance(\n      const double x, const double y, const double z,\n      const double minimum_distance,\n      const double stepsize_multiplier = 1.0 / 10.0) const\n  {\n    return ProjectOutOfCollisionToMinimumDistance4d(\n          Eigen::Vector4d(x, y, z, 1.0),\n          minimum_distance, stepsize_multiplier).head<3>();\n  }\n\n  inline Eigen::Vector3d ProjectOutOfCollisionToMinimumDistance3d(\n      const Eigen::Vector3d& location, const double minimum_distance,\n      const double stepsize_multiplier = 1.0 / 10.0) const\n  {\n    return ProjectOutOfCollisionToMinimumDistance(\n          location.x(), location.y(), location.z(),\n          minimum_distance, stepsize_multiplier);\n  }\n\n  inline Eigen::Vector4d ProjectOutOfCollisionToMinimumDistance4d(\n      const Eigen::Vector4d& location,\n      const double minimum_distance,\n      const double stepsize_multiplier = 1.0 / 10.0) const\n  {\n    // To avoid potential problems with alignment, we need to pass location\n    // by reference, so we make a local copy here that we can change.\n    // See https://eigen.tuxfamily.org/dox/group__TopicPassingByValue.html\n    Eigen::Vector4d mutable_location = location;\n    // If we are in bounds, start the projection process,\n    // otherwise return the location unchanged\n    if (LocationInBounds4d(mutable_location))\n    {\n      // Add a small collision margin to account for rounding and similar\n      const double minimum_distance_with_margin\n          = minimum_distance + GetResolution() * stepsize_multiplier * 1e-3;\n      const double max_stepsize = GetResolution() * stepsize_multiplier;\n      const bool enable_edge_gradients = true;\n      double sdf_dist = EstimateDistance4d(mutable_location).first;\n      while (sdf_dist <= minimum_distance)\n      {\n        const std::vector<double> gradient\n            = GetGradient4d(mutable_location, enable_edge_gradients);\n        if (gradient.size() == 3)\n        {\n          const Eigen::Vector4d grad_vector(\n                gradient[0], gradient[1], gradient[2], 0.0);\n          if (grad_vector.norm() > GetResolution() * 0.25) // Sanity check\n          {\n            // Don't step any farther than is needed\n            const double step_distance\n                = std::min(max_stepsize,\n                           minimum_distance_with_margin - sdf_dist);\n            mutable_location += grad_vector.normalized() * step_distance;\n            sdf_dist = EstimateDistance4d(mutable_location).first;\n          }\n          else\n          {\n            throw std::runtime_error(\"Encountered flat gradient - stuck\");\n          }\n        }\n        else\n        {\n          throw std::runtime_error(\"Failed to compute gradient - out of SDF?\");\n        }\n      }\n    }\n    return mutable_location;\n  }\n\n  static void SaveToFile(const SignedDistanceField& sdf,\n                         const std::string& filepath,\n                         const bool compress);\n\n  static SignedDistanceField LoadFromFile(const std::string& filepath);\n\n  static sdf_tools::SDF GetMessageRepresentation(\n      const SignedDistanceField& sdf);\n\n  static SignedDistanceField LoadFromMessageRepresentation(\n      const sdf_tools::SDF& message);\n\n  visualization_msgs::Marker ExportForDisplay(const float alpha = 0.01f) const;\n\n  visualization_msgs::Marker ExportForDisplayCollisionOnly(\n      const float alpha = 0.01f) const;\n\n  /*\n   * The following function can be *VERY EXPENSIVE* to compute, since it\n   * performs gradient ascent/descent across the SDF\n   */\n  VoxelGrid<Eigen::Vector3d> ComputeLocalExtremaMap() const;\n};\n}\n\n#endif // SDF_HPP\n", "meta": {"hexsha": "81080f28e2cb3d3afea9fbe8b7bf7fb89d51682e", "size": 36955, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sdf_tools/sdf.hpp", "max_stars_repo_name": "ToyotaResearchInstitute/sdf_tools", "max_stars_repo_head_hexsha": "781e4d5187c10b8235fcbd3fd6a5498c1fffa7aa", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/sdf_tools/sdf.hpp", "max_issues_repo_name": "ToyotaResearchInstitute/sdf_tools", "max_issues_repo_head_hexsha": "781e4d5187c10b8235fcbd3fd6a5498c1fffa7aa", "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/sdf_tools/sdf.hpp", "max_forks_repo_name": "ToyotaResearchInstitute/sdf_tools", "max_forks_repo_head_hexsha": "781e4d5187c10b8235fcbd3fd6a5498c1fffa7aa", "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.0949667616, "max_line_length": 80, "alphanum_fraction": 0.5953727506, "num_tokens": 8361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.5, "lm_q1q2_score": 0.29821657313231276}}
{"text": "#ifndef ALEPH_PERSISTENCE_DIAGRAMS_DISTANCES_BOTTLENECK_HH__\n#define ALEPH_PERSISTENCE_DIAGRAMS_DISTANCES_BOTTLENECK_HH__\n\n#include <aleph/geometry/distances/Infinity.hh>\n\n#include <aleph/persistenceDiagrams/PersistenceDiagram.hh>\n#include <aleph/persistenceDiagrams/distances/detail/Orthogonal.hh>\n\n#include <boost/iterator/counting_iterator.hpp>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/max_cardinality_matching.hpp>\n\nnamespace aleph\n{\n\nnamespace distances\n{\n\nnamespace detail\n{\n\ntemplate <class T> struct Edge\n{\n  std::size_t source;\n  std::size_t target;\n\n  T weight;\n\n  Edge( std::size_t s, std::size_t t, T w )\n    : source( s )\n    , target( t )\n    , weight( w )\n  {\n  }\n\n  bool operator<( const Edge& other ) const\n  {\n    return weight < other.weight;\n  }\n};\n\ntemplate <class T> struct CheckMatchingCardinality\n{\n  using GraphType          = boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS>;\n  using MatchingVectorType = std::vector<boost::graph_traits<GraphType>::vertex_descriptor>;\n\n  CheckMatchingCardinality( std::size_t size, typename std::vector<Edge<T> >::const_iterator begin )\n    : _maximumSize( size )\n    , _last( begin )\n    , _graph( 2 * size )\n    , _mates( 2 * size )\n  {\n    boost::add_edge( begin->source, begin->target, _graph );\n  }\n\n  bool operator()( typename std::vector<Edge<T> >::const_iterator /* it1 */, typename std::vector<Edge<T> >::const_iterator it2 )\n  {\n    // The new edge lies beyond the edges that are already known, so the\n    // edges between the last edge and the new iterator position need to\n    // be added.\n    if( it2 > _last )\n    {\n      do\n      {\n        ++_last;\n        boost::add_edge( _last->source, _last->target, _graph );\n      }\n      while( _last != it2 );\n    }\n\n    // The new edge lies behind the edges that are already known, so the\n    // surplus edges need to be removed.\n    else\n    {\n      do\n      {\n        boost::remove_edge( _last->source, _last->target, _graph );\n        --_last;\n      }\n      while( _last != it2 );\n    }\n\n    boost::edmonds_maximum_cardinality_matching( _graph,\n                                                 &_mates[0] );\n\n    // Look out for _perfect matchings_ in the bipartite graph. Any other\n    // maximum cardinality matching does not qualify for the Bottleneck\n    // distance.\n    return boost::matching_size( _graph, &_mates[0] ) == _maximumSize;\n  }\n\n  std::size_t _maximumSize;\n\n  typename std::vector<Edge<T> >::const_iterator _last;\n\n  GraphType          _graph; // Input data\n  MatchingVectorType _mates; // Edges of the matching\n};\n\n} // namespace detail\n\n/**\n  Calculates the Bottleneck distance between two persistence diagrams.\n  The algorithm used for this involves checking a (complete) bipartite\n  graph for perfect matchings.\n\n  A brief description of the algoritmh is given in\n\n    Computational Topology\n    Herbert Edelsbrunner and John Harer\n\n  on page 191.\n\n  The implementation has been inspired by Dmitriy Morozov's \"Dionysus\"\n  framework.\n\n  @param D1 First persistence diagram\n  @param D2 Second persistence diagram\n\n  @returns Bottleneck distance between the two persistence diagrams\n*/\n\n\ntemplate <\n  class DataType,\n  class Distance = aleph::geometry::distances::InfinityDistance<DataType>\n> DataType bottleneckDistance( const PersistenceDiagram<DataType>& D1,\n                               const PersistenceDiagram<DataType>& D2 )\n{\n  auto n           = D1.size();\n  auto m           = D2.size();\n  auto maximumSize = n + m;\n\n  using SizeType = decltype(n);\n  using Edge     = detail::Edge<DataType>;\n\n  std::vector<Edge> edges;\n\n  // Diagonal edges ----------------------------------------------------\n\n  for( SizeType i = n; i < maximumSize; i++ )\n    for( SizeType j = maximumSize + i; j < 2 * maximumSize; j++ )\n      edges.push_back( Edge( static_cast<std::size_t>(i), static_cast<std::size_t>(j), DataType() ) );\n\n  SizeType i = 0;\n\n  // Edges between regular points --------------------------------------\n\n  Distance distance;\n\n  for( auto it1 = D1.begin(); it1 != D1.end(); ++it1 )\n  {\n    auto j = maximumSize;\n\n    for( auto it2 = D2.begin(); it2 != D2.end(); ++it2 )\n    {\n      auto weight = distance( *it1, *it2 );\n\n      edges.push_back( Edge( static_cast<std::size_t>(i), static_cast<std::size_t>(j),\n                             weight ) );\n\n      ++j;\n    }\n\n    ++i;\n  }\n\n  // Edges between points and their projections ------------------------\n\n  i = 0;\n\n  for( auto it1 = D1.begin(); it1 != D1.end(); ++it1 )\n  {\n    edges.push_back( Edge( static_cast<std::size_t>(i), static_cast<std::size_t>(maximumSize + m + i),\n                           aleph::distances::detail::orthogonalDistance<Distance>( *it1 ) ) );\n\n    ++i;\n  }\n\n  i = maximumSize;\n\n  for( auto it2 = D2.begin(); it2 != D2.end(); ++it2 )\n  {\n    edges.push_back( Edge( static_cast<std::size_t>(n + i - maximumSize), static_cast<std::size_t>(i),\n                           aleph::distances::detail::orthogonalDistance<Distance>( *it2 ) ) );\n  }\n\n  // Identify matchings ------------------------------------------------\n\n  std::sort( edges.begin(), edges.end() );\n\n  // Perform binary search over edge sets. Starting from the empty graph, use\n  // more and more edges to find out the first graph that permits a maximum\n  // cardinality matching.\n\n  using EdgeIteratorType     = typename std::vector<Edge>::const_iterator;\n  using CountingIteratorType = boost::counting_iterator<EdgeIteratorType>;\n\n  auto itEdge = std::upper_bound( CountingIteratorType( edges.begin() ),\n                                  CountingIteratorType( edges.end() ),\n                                  edges.begin(),\n                                  detail::CheckMatchingCardinality<DataType>( maximumSize, edges.begin() ) );\n\n  return (*itEdge)->weight;\n}\n\n} // namespace distances\n\n} // namespace aleph\n\n#endif\n", "meta": {"hexsha": "69deeccfa49c30ccb8f34ff9222a08f63c28e09d", "size": 5855, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/aleph/persistenceDiagrams/distances/Bottleneck.hh", "max_stars_repo_name": "eudoxos/Aleph", "max_stars_repo_head_hexsha": "874882c33a0e8429c74e567eb01525613fee0616", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 56.0, "max_stars_repo_stars_event_min_datetime": "2019-04-24T22:11:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T11:37:47.000Z", "max_issues_repo_path": "include/aleph/persistenceDiagrams/distances/Bottleneck.hh", "max_issues_repo_name": "eudoxos/Aleph", "max_issues_repo_head_hexsha": "874882c33a0e8429c74e567eb01525613fee0616", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2016-11-30T09:37:13.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-30T21:43:39.000Z", "max_forks_repo_path": "include/aleph/persistenceDiagrams/distances/Bottleneck.hh", "max_forks_repo_name": "eudoxos/Aleph", "max_forks_repo_head_hexsha": "874882c33a0e8429c74e567eb01525613fee0616", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-05-02T11:54:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-10T14:05:40.000Z", "avg_line_length": 27.4882629108, "max_line_length": 129, "alphanum_fraction": 0.6227156277, "num_tokens": 1462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2982165731323127}}
{"text": "#include \"geom/Vector2D.hpp\"\n#include \"geom/Transform.hpp\"\n#include \"geom/BoundingBox.hpp\"\n#include \"geom/Math.hpp\"\n#include \"geom/CollisionCheck.hpp\"\n\n#include <boost/python.hpp>\n\n\nvoid export_geom()\n{\n    namespace bp = boost::python;\n    namespace ag = avs::geom;\n\n    // Make from avsimpy.geometrics import ... work\n    bp::object utilModule(bp::handle<>(bp::borrowed(PyImport_AddModule(\"avsimpy.geometrics\"))));\n    // Make from avsimpy import geometrics work\n    bp::scope().attr(\"geometrics\") = utilModule;\n    bp::scope util_scope = utilModule;\n\n\n    bp::class_<ag::Vector2D>(\"Vector2D\")\n        .def(bp::init<const float, const float>((bp::arg(\"x\")=0.0f, bp::arg(\"y\")=0.0f)))\n        .def(bp::init<const ag::Vector2D>((bp::arg(\"vector\"))))\n        .def_readwrite(\"x\", &ag::Vector2D::x)\n        .def_readwrite(\"y\", &ag::Vector2D::y)\n        .def(\"get_length\", &ag::Vector2D::get_length)\n        .def(\"get_unit_vector\", &ag::Vector2D::get_unit_vector)\n        .def(\"__eq__\", &ag::Vector2D::operator==)\n        .def(\"__ne__\", &ag::Vector2D::operator!=)\n        .def(bp::self += bp::self)\n        .def(bp::self + bp::self)\n        .def(bp::self -= bp::self)\n        .def(bp::self - bp::self)\n        .def(bp::self *= double())\n        .def(bp::self * double())\n        .def(double() * bp::self)\n        .def(bp::self /= double())\n        .def(bp::self / double())\n        .def(double() / bp::self)\n        .def(bp::self_ns::str(bp::self_ns::self))\n    ;\n\n    bp::class_<ag::Transform>(\"Transform\")\n        .def(bp::init<const ag::Vector2D, const float>(\n            (bp::arg(\"location\")=ag::Vector2D(), bp::arg(\"rotation\")=0.0f)))\n        .def(bp::init<const ag::Transform&>((bp::arg(\"transform\"))))\n        .def_readwrite(\"location\", &ag::Transform::location)\n        .def_readwrite(\"rotation\", &ag::Transform::rotation)\n        .def(\"get_forward_vector\", &ag::Transform::get_forward_vector)\n        .def(\"calculate_distance\", &ag::Transform::calculate_distance)\n        .def(\"__eq__\", &ag::Transform::operator==)\n        .def(\"__ne__\", &ag::Transform::operator!=)\n        .def(bp::self_ns::str(bp::self_ns::self))\n    ;\n\n    bp::class_<ag::BoundingBox>(\"BoundingBox\")\n        .def(bp::init<const ag::Vector2D, const ag::Vector2D>(\n            (bp::arg(\"location\")=ag::Vector2D(), bp::arg(\"extent\")=ag::Vector2D())))\n        .def(bp::init<const float, const float, const float, const float>(\n            (bp::arg(\"x\")=0.0f, bp::arg(\"y\")=0.0f, bp::arg(\"extent_x\")=1.0f, bp::arg(\"extent_y\")=1.0f)))\n        .def(bp::init<const ag::BoundingBox&>((bp::arg(\"bounding_box\"))))\n        .def_readwrite(\"location\", &ag::BoundingBox::center)\n        .def_readwrite(\"extent\", &ag::BoundingBox::extent)\n        .def(\"contains\", &ag::BoundingBox::contains, bp::arg(\"point\"))\n        .def(\"intersects\", &ag::BoundingBox::intersects, bp::arg(\"bounding_box\"))\n        .def(\"__eq__\", &ag::BoundingBox::operator==)\n        .def(\"__ne__\", &ag::BoundingBox::operator!=)\n        .def(bp::self_ns::str(bp::self_ns::self))\n    ;\n\n    bp::class_<ag::Math>(\"math\")\n        .def(\"to_radian\", &ag::Math::to_radian, bp::arg(\"deg\"))\n        .def(\"to_degree\", &ag::Math::to_degree, bp::arg(\"rad\"))\n        .def(\"dot_product\", &ag::Math::dot_product, (bp::arg(\"vector_A\"), bp::arg(\"vector_B\")))\n        .def(\"calculate_distance\", &ag::Math::calculate_distance, (bp::arg(\"vector_A\"), bp::arg(\"vector_B\")))\n        .def(\"calculate_angle\", &ag::Math::calculate_angle, (bp::arg(\"vector_A\"), bp::arg(\"vector_B\")))\n        .def(\"get_forward_vector\", &ag::Math::get_forward_vector, bp::arg(\"deg\"))\n        .def(\"rotate_vector_on_origin\", &ag::Math::rotate_vector_on_origin, (bp::arg(\"vector\"), bp::arg(\"deg\")))\n        .def(\"rotate_vector_on_point\", &ag::Math::rotate_vector_on_point, (bp::arg(\"vector\"), bp::arg(\"deg\"), bp::arg(\"point\")))\n    ;\n\n    bp::class_<ag::CollisionChecker>(\"CollisionChecker\")\n        .def(\"check_collision\", &ag::CollisionChecker::check_collision, (bp::arg(\"entity_A\"), bp::arg(\"entity_B\")))\n        .def(bp::self_ns::str(bp::self_ns::self))\n    ;\n\n}\n", "meta": {"hexsha": "4359634b9ebcfd4c58bc67018e3de2fe2a2f2585", "size": 4047, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PythonAPI/Geom.cpp", "max_stars_repo_name": "50sven/avsim", "max_stars_repo_head_hexsha": "bfd29c8f0fe10a4f279310ded9b97aee6fab8819", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PythonAPI/Geom.cpp", "max_issues_repo_name": "50sven/avsim", "max_issues_repo_head_hexsha": "bfd29c8f0fe10a4f279310ded9b97aee6fab8819", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PythonAPI/Geom.cpp", "max_forks_repo_name": "50sven/avsim", "max_forks_repo_head_hexsha": "bfd29c8f0fe10a4f279310ded9b97aee6fab8819", "max_forks_repo_licenses": ["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.4719101124, "max_line_length": 128, "alphanum_fraction": 0.5972325179, "num_tokens": 1184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.5, "lm_q1q2_score": 0.29821656595887436}}
{"text": "//------------------------------------------------------------------------------\n// © 2021. Triad National Security, LLC. All rights reserved.  This\n// program was produced under U.S. Government contract 89233218CNA000001\n// for Los Alamos National Laboratory (LANL), which is operated by Triad\n// National Security, LLC for the U.S.  Department of Energy/National\n// Nuclear Security Administration. All rights in the program are\n// reserved by Triad National Security, LLC, and the U.S. Department of\n// Energy/National Nuclear Security Administration. The Government is\n// granted for itself and others acting on its behalf a nonexclusive,\n// paid-up, irrevocable worldwide license in this material to reproduce,\n// prepare derivative works, distribute copies to the public, perform\n// publicly and display publicly, and to permit others to do so.\n//------------------------------------------------------------------------------\n\n#ifndef _SINGULARITY_EOS_CLOSURE_MIXED_CELL_MODELS_\n#define _SINGULARITY_EOS_CLOSURE_MIXED_CELL_MODELS_\n\n#include <ports-of-call/portability.hpp>\n#include <singularity-eos/eos/eos.hpp>\n\n#include <cmath>\n\n#ifdef SINGULARITY_USE_KOKKOSKERNELS\n#include <KokkosBatched_ApplyQ_Decl.hpp>\n#include <KokkosBatched_QR_Decl.hpp>\n#include <KokkosBatched_Trsv_Decl.hpp>\n#else\n#include <Eigen/Dense>\n#endif // SINGULARITY_USE_KOKKOSKERNELS\n\nnamespace singularity {\n\n/*\n  This is the PTE code based on FLAG's matrix form in their mixgas treatment\n  I have modified it to include a line search which improves robustness and\n  quality of non-converged solutions, at the likely cost of speed (due to\n  additional EOS calls).\n  It is templated on nmat and takes an array of Indexers to the EOSs,\n  Volume (total volume of materials to be equilibrated), total SIE,\n  and an array of masses of each component as inputs, and returns component\n  volumes and energies (SIEs) as output.\n\n  EOSIndexer must have an operator[](int) that returns an EOS. e.g., EOS*\n  RealIndexer must have an operator[](int) that returns a Real. e.g., Real*\n  ConstRealIndexer is as RealIndexer, but assumed const type.\n  LambdaIndexer must have an operator[](int) that returns a Real*. e.g., Real**\n*/\n// Version templated on nmat\n// niter version produces histogram\ntemplate <int nmat, typename EOSIndexer, typename RealIndexer, typename ConstRealIndexer,\n          typename LambdaIndexer>\nPORTABLE_INLINE_FUNCTION bool pte_closure_flag_with_line(\n    EOSIndexer &&eoss, const Real Volume, const Real TotalSIE,\n    ConstRealIndexer &&ComponentMasses, RealIndexer &&ComponentVolumes,\n    RealIndexer &&ComponentEnergies, LambdaIndexer &&lambdas, int &niter);\ntemplate <int nmat, typename EOSIndexer, typename RealIndexer, typename ConstRealIndexer,\n          typename LambdaIndexer>\nPORTABLE_INLINE_FUNCTION bool\npte_closure_flag_with_line(EOSIndexer &&eoss, const Real Volume, const Real TotalSIE,\n                           ConstRealIndexer &&ComponentMasses,\n                           RealIndexer &&ComponentVolumes,\n                           RealIndexer &&ComponentEnergies, LambdaIndexer &&lambdas) {\n  int niter;\n  return pte_closure_flag_with_line(eoss, Volume, TotalSIE, ComponentMasses,\n                                    ComponentVolumes, ComponentEnergies, lambdas, niter);\n}\n// Version with nmat available at runtime\ntemplate <typename EOSIndexer, typename RealIndexer, typename ConstRealIndexer,\n          typename LambdaIndexer>\nPORTABLE_INLINE_FUNCTION bool\npte_closure_flag(int nmat, EOSIndexer &&eoss, const Real Volume, const Real TotalSIE,\n                 ConstRealIndexer &&ComponentMasses, RealIndexer &&ComponentVolumes,\n                 RealIndexer &&ComponentEnergies, LambdaIndexer &&lambdas, int &niter);\ntemplate <typename EOSIndexer, typename RealIndexer, typename ConstRealIndexer,\n          typename LambdaIndexer>\nPORTABLE_INLINE_FUNCTION bool\npte_closure_flag(int nmat, EOSIndexer &&eoss, const Real Volume, const Real TotalSIE,\n                 ConstRealIndexer &&ComponentMasses, RealIndexer &&ComponentVolumes,\n                 RealIndexer &&ComponentEnergies, LambdaIndexer &&lambdas) {\n  int niter;\n  return pte_closure_flag(nmat, eoss, Volume, TotalSIE, ComponentMasses, ComponentVolumes,\n                          ComponentEnergies, lambdas, niter);\n}\n// Pointer-only version with offset for EOS indexing\nPORTABLE_INLINE_FUNCTION bool\npte_closure_flag_offset(int nmat, EOS *eoss, const Real Volume, const Real TotalSIE,\n                        int const *const ComponentMats, const Real *ComponentMasses,\n                        Real *ComponentVolumes, Real *ComponentEnergies, Real **lambdas,\n                        int &niter);\nPORTABLE_INLINE_FUNCTION bool\npte_closure_flag_offset(int nmat, EOS *eoss, const Real Volume, const Real TotalSIE,\n                        int const *const ComponentMats, const Real *ComponentMasses,\n                        Real *ComponentVolumes, Real *ComponentEnergies, Real **lambdas) {\n  int niter;\n  return pte_closure_flag_offset(nmat, eoss, Volume, TotalSIE, ComponentMats,\n                                 ComponentMasses, ComponentVolumes, ComponentEnergies,\n                                 lambdas, niter);\n}\n/*\n  This solver was developed by Josh Dolence, and is guaranteed to\n  return a state where energies and volume fractions add up to the\n  total energy and 1 respectively, even if the solve fails.\n\n  EOSIndexer must have an operator[](int) that returns an EOS. e.g., EOS*\n  RealIndexer must have an operator[](int) that returns a Real. e.g., Real*\n  LambdaIndexer must have an operator[](int) that returns a Real*. e.g., Real**\n*/\n// Version templated on nmat.\ntemplate <int nmat, typename EOSIndexer, typename RealIndexer, typename LambdaIndexer>\nPORTABLE_INLINE_FUNCTION bool pte_closure_josh(EOSIndexer &&eos, const Real vfrac_tot,\n                                               const Real sie_tot, RealIndexer &&rho,\n                                               RealIndexer &&vfrac, RealIndexer &&sie,\n                                               RealIndexer &&temp, RealIndexer &&press,\n                                               LambdaIndexer &&lambda, int &niter);\ntemplate <int nmat, typename EOSIndexer, typename RealIndexer, typename LambdaIndexer>\nPORTABLE_INLINE_FUNCTION bool\npte_closure_josh(EOSIndexer &&eos, const Real vfrac_tot, const Real sie_tot,\n                 RealIndexer &&rho, RealIndexer &&vfrac, RealIndexer &&sie,\n                 RealIndexer &&temp, RealIndexer &&press, LambdaIndexer &&lambda) {\n  int niter;\n  return pte_closure_josh(eos, vfrac_tot, sie_tot, rho, vfrac, sie, temp, press, lambda,\n                          niter);\n}\n// Version with nmat available at runtime.\ntemplate <typename EOSIndexer, typename RealIndexer, typename LambdaIndexer>\nPORTABLE_INLINE_FUNCTION bool\npte_closure_josh(int nmat, EOSIndexer &&eoss, const Real vfrac_tot, const Real sie_tot,\n                 RealIndexer &&rho, RealIndexer &&vfrac, RealIndexer &&sie,\n                 RealIndexer &&temp, RealIndexer &&press, LambdaIndexer &&lambdas,\n                 int &niter);\ntemplate <typename EOSIndexer, typename RealIndexer, typename LambdaIndexer>\nPORTABLE_INLINE_FUNCTION bool\npte_closure_josh(int nmat, EOSIndexer &&eoss, const Real vfrac_tot, const Real sie_tot,\n                 RealIndexer &&rho, RealIndexer &&vfrac, RealIndexer &&sie,\n                 RealIndexer &&temp, RealIndexer &&press, LambdaIndexer &&lambdas) {\n  int niter;\n  return pte_closure_josh(nmat, eoss, vfrac_tot, sie_tot, rho, vfrac, sie, temp, press,\n                          lambdas, niter);\n}\n// Pointer-only version with offset for EOS indexing\nPORTABLE_INLINE_FUNCTION bool\npte_closure_josh_offset(int nmat, EOS *eoss, const Real vfrac_tot, const Real sie_tot,\n                        int const *const Mats, Real *rho, Real *vfrac, Real *sie,\n                        Real *temp, Real *press, Real **lambdas, int &niter);\nPORTABLE_INLINE_FUNCTION bool\npte_closure_josh_offset(int nmat, EOS *eoss, const Real vfrac_tot, const Real sie_tot,\n                        int const *const Mats, Real *rho, Real *vfrac, Real *sie,\n                        Real *temp, Real *press, Real **lambdas) {\n  int niter;\n  return pte_closure_josh_offset(nmat, eoss, vfrac_tot, sie_tot, Mats, rho, vfrac, sie,\n                                 temp, press, lambdas, niter);\n}\n\n/*\n    This is a formulation of the PTE closure equations which tries to minimize\n    differences between T and P/T.  Since T (should be) positive definite, this\n    should be well-founded.  In mixtures of ideal gasses, this should be linear\n    (so for hot plasmas, this should be linear-ish).\n    Equations 1-nmat will be:\n    T1-T0 = 0, T2-T1=0, [...], Tnmat-Tnmatm1=0, sum(Ei) = Etot\n    and Equations nmat+1-2*nmat will be:\n    P1/T1-P0/T0 = 0, P2/T2-P1/T1 = 0 [...], Sum(volumes)=Volume\n\n    EOSIndexer must have an operator[](int) that returns an EOS. e.g., EOS*\n    RealIndexer must have an operator[](int) that returns a Real. e.g., Real*\n    ConstRealIndexer is as RealIndexer, but assumed const type.\n    LambdaIndexer must have an operator[](int) that returns a Real*. e.g., Real**\n*/\ntemplate <typename EOSIndexer, typename RealIndexer, typename ConstRealIndexer,\n          typename LambdaIndexer>\nPORTABLE_INLINE_FUNCTION bool\npte_closure_ideal(int nmat, EOSIndexer &&eoss, const Real Volume, const Real TotalSIE,\n                  ConstRealIndexer &&ComponentMasses, RealIndexer &&ComponentVolumes,\n                  RealIndexer &&ComponentEnergies, LambdaIndexer &&lambdas, int &niter);\ntemplate <typename EOSIndexer, typename RealIndexer, typename ConstRealIndexer,\n          typename LambdaIndexer>\nPORTABLE_INLINE_FUNCTION bool\npte_closure_ideal(int nmat, EOSIndexer &&eoss, const Real Volume, const Real TotalSIE,\n                  ConstRealIndexer &&ComponentMasses, RealIndexer &&ComponentVolumes,\n                  RealIndexer &&ComponentEnergies, LambdaIndexer &&lambdas) {\n  int niter;\n  return pte_closure_ideal(nmat, eoss, Volume, TotalSIE, ComponentMasses,\n                           ComponentVolumes, ComponentEnergies, lambdas, niter);\n}\n\n// ======================================================================\n// Implementation details below\n// ======================================================================\n\nnamespace mix_params {\nconstexpr Real derivative_eps = 3.0e-6;\nconstexpr Real pte_rel_tolerance_p = 1.e-4;\nconstexpr Real pte_rel_tolerance_t = 1.e-4;\nconstexpr Real pte_abs_tolerance_p = 0.0;\nconstexpr Real pte_abs_tolerance_t = 0.0;\nconstexpr int pte_max_iter_per_mat = 16;\nconstexpr Real line_search_alpha = 1.e-4;\nconstexpr int line_search_max_iter = 3;\nconstexpr Real line_search_fac = 0.05;\n} // namespace mix_params\n\nnamespace mix_impl {\ntemplate <typename T,\n          typename = typename std::enable_if<std::is_floating_point<T>::value>::type>\nconstexpr bool isfinite(const T &a) {\n  return (a == a) && ((a == 0) || (a != 2 * a));\n}\n\nconstexpr Real square(const Real x) { return x * x; }\n\nPORTABLE_INLINE_FUNCTION\nbool check_nans(Real const *const a, const int n, const bool verbose = false) {\n  bool retval = true;\n  for (int i = 0; i < n; ++i)\n    if (!isfinite(a[i])) {\n      retval = false;\n#ifndef KOKKOS_ENABLE_CUDA\n      if (verbose) {\n        printf(\"bad val in element %i/%i\\n\", i, n);\n      }\n#endif // KOKKOS_ENABLE_CUDA\n    }\n  return retval;\n}\n\ntemplate <int n>\nPORTABLE_INLINE_FUNCTION bool solve_Ax_b(Real *a, Real *b) {\n#ifdef SINGULARITY_USE_KOKKOSKERNELS\n#ifndef PORTABILITY_STRATEGY_KOKKOS\n#error \"Kokkos Kernels requires Kokkos.\"\n#endif\n  Real t_[n], w_[n];\n  // aliases for kokkos views\n  using Unmgd = Kokkos::MemoryTraits<Kokkos::Unmanaged>;\n  using Lrgt = Kokkos::LayoutRight;\n  using vec_t = Kokkos::View<Real *, Unmgd>;\n  // aliases for QR solve template params\n  using QR_alg = KokkosBatched::Algo::QR::Unblocked;\n  using Lft = KokkosBatched::Side::Left;\n  using Trs = KokkosBatched::Trans::Transpose;\n  using nTrs = KokkosBatched::Trans::NoTranspose;\n  using ApQ_alg = KokkosBatched::Algo::ApplyQ::Unblocked;\n  using UP = KokkosBatched::Uplo::Upper;\n  using NonU = KokkosBatched::Diag::NonUnit;\n  using Tr_alg = KokkosBatched::Algo::Trsv::Unblocked;\n  // aliases for solver structs ('invoke' member of the struct is the\n  // actual function call)\n  using QR_factor = KokkosBatched::SerialQR<QR_alg>;\n  using ApplyQ_transpose = KokkosBatched::SerialApplyQ<Lft, Trs, ApQ_alg>;\n  using InvertR = KokkosBatched::SerialTrsv<UP, nTrs, NonU, Tr_alg>;\n  // view of matrix\n  Kokkos::View<Real **, Lrgt, Unmgd> A(a, n, n);\n  // view of RHS\n  vec_t B(b, n);\n  // view of reflectors\n  vec_t t(t_, n);\n  // view of workspace\n  vec_t w(w_, n);\n  // QR factor A, A x = B -> Q R x = B\n  // store result in A and t\n  QR_factor::invoke(A, t, w);\n  // Apply Q^T from the left to both sides\n  // Q^T Q R x = Q^T B -> R x = Q^T B\n  // store result of Q^T B in B\n  ApplyQ_transpose::invoke(A, t, B, w);\n  // Apply R^-1 from the left to both sides\n  // R^-1 R x = R^-1 Q^T B -> x = R^-1 Q^T B\n  // store solution vector x in B\n  InvertR::invoke(1.0, A, B);\n#else\n#ifdef PORTABILITY_STRATEGY_KOKKOS\n#error \"Eigen should not be used with Kokkos.\"\n#endif\n  // Eigen VERSION\n  Eigen::Map<Eigen::Matrix<Real, n, n, Eigen::RowMajor>> A(a);\n  Eigen::Map<Eigen::Matrix<Real, n, 1>> B(b);\n  Eigen::Matrix<Real, n, 1> X;\n  X = A.lu().solve(B);\n  B = X;\n#endif // SINGULARITY_USE_KOKKOSKERNELS\n  bool retval = check_nans(b, n);\n  return retval;\n}\n\ntemplate <int nmat, typename EOSIndexer, typename RealIndexer, typename ConstRealIndexer,\n          typename LambdaIndexer, typename OFFSETTER>\nPORTABLE_INLINE_FUNCTION bool\npte_closure_flag_with_line_impl(EOSIndexer &&eoss, const Real Volume, const Real TotalSIE,\n                                ConstRealIndexer &&ComponentMasses,\n                                RealIndexer &&ComponentVolumes,\n                                RealIndexer &&ComponentEnergies, LambdaIndexer &&lambdas,\n                                const OFFSETTER ofst, int &iter) {\n  using namespace mix_params;\n\n  Real TotalMass = 0.0, Vsum = 0.0, Esum = 0.0;\n  Real Densities[nmat], Pressures[nmat], Temperatures[nmat], dpdr[nmat];\n  Real dpde[nmat], dtdr[nmat], dtde[nmat], b[2 * nmat], A[4 * nmat * nmat];\n  Real rtemp[nmat], sietemp[nmat];\n  // First, normalize the energies and volumes.\n  // This may or may not be close to reality since SIE isn't strictly positive.\n  for (int i = 0; i < nmat; ++i)\n    TotalMass += ComponentMasses[i];\n  bool iszero = true;\n  for (int i = 0; i < nmat; ++i)\n    iszero &= ComponentVolumes[i] <= 1.0e-16;\n  if (iszero)\n    for (int i = 0; i < nmat; ++i)\n      ComponentVolumes[i] = Volume * ComponentMasses[i] / TotalMass;\n  for (int i = 0; i < nmat; ++i)\n    Vsum += ComponentVolumes[i];\n  for (int i = 0; i < nmat; ++i)\n    ComponentVolumes[i] *=\n        Volume / Vsum; // Are compilers smart enough to calculate this RHS once?\n  for (int i = 0; i < nmat; ++i)\n    Esum += ComponentEnergies[i] * ComponentMasses[i];\n  if (std::abs(Esum) <\n      0.0001) { // Then we punt and just distribute based on mass fractions\n    for (int i = 0; i < nmat; ++i)\n      ComponentEnergies[i] = TotalSIE * TotalMass / ComponentMasses[i];\n  } else { // Otherwise, we scale\n    for (int i = 0; i < nmat; ++i)\n      ComponentEnergies[i] *= (TotalSIE * TotalMass / Esum);\n  }\n\n  // This is the main loop\n  constexpr const int pte_max_iter = nmat * pte_max_iter_per_mat;\n  for (iter = 0; iter < pte_max_iter; ++iter) {\n    // Call the EOSs\n    for (int mat = 0; mat < nmat; ++mat) {\n      Densities[mat] = ComponentMasses[mat] / ComponentVolumes[mat];\n      eoss[ofst(mat)].PTofRE(Densities[mat], ComponentEnergies[mat], lambdas[mat],\n                             Pressures[mat], Temperatures[mat], dpdr[mat], dpde[mat],\n                             dtdr[mat], dtde[mat]);\n    }\n    // Now, zero the matrix and vector\n    for (int i = 0; i < 2 * nmat * 2 * nmat; ++i)\n      A[i] = 0.0;\n    for (int i = 0; i < 2 * nmat; ++i)\n      b[i] = 0.0;\n    // print_matrix(2*nmat,2*nmat,A);\n    // print_vector(2*nmat,b);\n    Real vsum = 0.0;\n    Real esum = 0.0;\n    Real err = 0.0;\n    // build matrix and vector\n    for (int n = 0; n < nmat - 1; ++n) {\n      const int i = n + nmat;\n      // First, do the energy side\n      A[n * 2 * nmat + n] = dtde[n];\n      A[n * 2 * nmat + n + 1] = -dtde[n + 1];\n      A[n * 2 * nmat + i] = dtdr[n];\n      A[n * 2 * nmat + i + 1] = -dtdr[n + 1];\n      A[(nmat - 1) * 2 * nmat + n] = ComponentMasses[n];\n      b[n] = Temperatures[n + 1] - Temperatures[n];\n      esum += ComponentMasses[n] * ComponentEnergies[n];\n      // Now the density half\n      A[i * 2 * nmat + n] = dpde[n];\n      A[i * 2 * nmat + n + 1] = -dpde[n + 1];\n      A[i * 2 * nmat + i] = dpdr[n];\n      A[i * 2 * nmat + i + 1] = -dpdr[n + 1];\n      A[(2 * nmat - 1) * 2 * nmat + i] = ComponentMasses[n] / square(Densities[n]);\n      b[i] = Pressures[n + 1] - Pressures[n];\n      vsum += ComponentMasses[n] / Densities[n];\n    }\n    A[(nmat - 1) * 2 * nmat + nmat - 1] = ComponentMasses[nmat - 1];\n    esum += ComponentMasses[nmat - 1] * ComponentEnergies[nmat - 1];\n    b[nmat - 1] = TotalSIE * TotalMass - esum; // esum - TotalSIE*TotalMass;\n    A[4 * nmat * nmat - 1] = ComponentMasses[nmat - 1] / square(Densities[nmat - 1]);\n    vsum += ComponentMasses[nmat - 1] / Densities[nmat - 1];\n    b[2 * nmat - 1] = vsum - Volume;\n    for (int i = 0; i < 2 * nmat; ++i)\n      err += square(b[i]);\n    err *= 0.5;\n    if (!solve_Ax_b<2 * nmat>(A, b)) {\n      // do something to crash out?  Tell folks what happened?\n#ifndef KOKKOS_ENABLE_CUDA\n      printf(\"Crashing out on iteration %i\\n\", iter);\n#endif // KOKKOS_ENABLE_CUDA\n      break;\n    }\n    // LINE SEARCH\n\n    // Now, get overall scaling limit\n    Real scale = 1.0;\n    for (int m = 0; m < nmat; ++m) {\n      Real rt = Densities[m] + scale * b[m + nmat];\n      if (rt < 0.0) {\n        scale = -0.9 * Densities[m] / b[m + nmat];\n      }\n      const Real dt = (dtdr[m] * b[m + nmat] + dtde[m] * b[m]);\n      const Real tt = Temperatures[m] + scale * dt;\n      if (tt < 0.0) scale = -0.9 * Temperatures[m] / dt;\n    }\n    // Now apply the overall pre-scaling\n    for (int i = 0; i < 2 * nmat; ++i)\n      b[i] *= scale;\n    // Line search\n    Real gradfdx = -2.0 * scale * err;\n    scale = 1.0;\n    Real err_old = err;\n    int line_iter = 0;\n    Real err_p, err_t;\n    do {\n      for (int m = 0; m < nmat; ++m) {\n        rtemp[m] = Densities[m] + scale * b[m + nmat];\n        sietemp[m] = ComponentEnergies[m] + scale * b[m];\n        Temperatures[m] = eoss[ofst(m)].TemperatureFromDensityInternalEnergy(\n            rtemp[m], sietemp[m], lambdas[m]);\n        if (eoss[ofst(m)].PreferredInput() ==\n            (thermalqs::density | thermalqs::specific_internal_energy)) {\n          Pressures[m] = eoss[ofst(m)].PressureFromDensityInternalEnergy(\n              rtemp[m], sietemp[m], lambdas[m]);\n        } else if (eoss[ofst(m)].PreferredInput() ==\n                   (thermalqs::density | thermalqs::temperature)) {\n          Pressures[m] = eoss[ofst(m)].PressureFromDensityTemperature(\n              rtemp[m], Temperatures[m], lambdas[m]);\n        }\n      }\n      err_p = 0.0;\n      err_t = 0.0;\n      for (int n = 0; n < nmat - 1; ++n) {\n        err_p += square(Pressures[n + 1] - Pressures[n]);\n        err_t += square(Temperatures[n + 1] - Temperatures[n]);\n      }\n      err = 0.5 * (err_p + err_t);\n      line_iter++;\n      if (line_iter > line_search_max_iter ||\n          err < err_old + line_search_alpha * scale * gradfdx)\n        break;\n      scale *= line_search_fac;\n    } while (true);\n\n    // END LINE SEARCH\n\n    Real mean_p = 0, mean_t = 0;\n\n    for (int i = 0; i < 2 * nmat; ++i)\n      b[i] *= scale;\n    for (int n = 0; n < nmat; ++n) {\n      const int i = nmat + n;\n      ComponentEnergies[n] += b[n];\n      Densities[n] += b[i];\n      ComponentVolumes[n] = ComponentMasses[n] / Densities[n];\n      mean_p += ComponentVolumes[n] * Pressures[n];\n      mean_t += ComponentMasses[n] * Temperatures[n];\n    }\n    mean_p /= Volume;\n    mean_t /= TotalMass;\n    err_p = std::sqrt(err_p);\n    err_t = std::sqrt(err_t);\n    bool converged_p =\n        (err_p < pte_rel_tolerance_p * std::abs(mean_p) || err_p < pte_abs_tolerance_p);\n    bool converged_t =\n        (err_t < pte_rel_tolerance_t * std::abs(mean_t) || err_t < pte_abs_tolerance_t);\n    if (converged_p && converged_t) {\n      return true; // FIXME\n    }\n  }\n  return false; // FIXME\n}\n\n// RealIndexer types may be different because some might be arrays and\n// some might be pointers.\ntemplate <int nmat, typename T1, typename T2, typename T3>\nPORTABLE_INLINE_FUNCTION static void pte_residual(const Real utot, T1 &&vfrac, Real *u,\n                                                  T2 &&temp, T3 &&press, Real *residual) {\n  Real vsum = 0.0;\n  Real esum = 0.0;\n  for (int m = 0; m < nmat; ++m) {\n    vsum += vfrac[m];\n    esum += u[m];\n  }\n  residual[0] = 1.0 - vsum;\n  residual[1] = utot - esum;\n  for (int m = 0; m < nmat - 1; ++m) {\n    residual[2 + m] = press[m + 1] - press[m];\n    residual[1 + nmat + m] = temp[m + 1] - temp[m];\n  }\n}\n\ntemplate <int nmat, typename EOSIndexer, typename RealIndexer, typename LambdaIndexer,\n          typename OFFSETTER>\nPORTABLE_INLINE_FUNCTION bool\npte_closure_josh_impl(EOSIndexer &&eos, const Real vfrac_tot, const Real sie_tot,\n                      RealIndexer &&rho, RealIndexer &&vfrac, RealIndexer &&sie,\n                      RealIndexer &&temp, RealIndexer &&press, LambdaIndexer &&lambda,\n                      const OFFSETTER ofst, int &niter) {\n  using namespace mix_params;\n  const Real ilog2 = 1.0 / std::log(2.0);\n  Real vsum = 0.0;\n  // Normalize vfrac\n  for (int m = 0; m < nmat; ++m)\n    vsum += vfrac[m];\n  for (int m = 0; m < nmat; ++m)\n    vfrac[m] /= vsum;\n  Real rhobar[nmat]; // This is a fixed quantity: the average density of\n                     // material m averaged over the full PTE volume\n  for (int m = 0; m < nmat; ++m)\n    rhobar[m] = rho[m] * vfrac[m];\n  Real rho_total = 0.0;\n  for (int m = 0; m < nmat; ++m)\n    rho_total += rhobar[m];\n  // Renormalize energies as well\n  Real utot = rho_total * sie_tot;\n  Real u[nmat];\n  Real esum = 0.0;\n  for (int m = 0; m < nmat; ++m)\n    u[m] = sie[m] * rhobar[m];\n  for (int m = 0; m < nmat; ++m)\n    esum += u[m];\n  for (int m = 0; m < nmat; ++m)\n    u[m] *= utot / esum;\n  Real jacobian[4 * nmat * nmat];\n  Real dx[2 * nmat];\n  Real residual[2 * nmat];\n  Real Cache[nmat][MAX_NUM_LAMBDAS];\n  // Real* Cache[nmat];\n  // for (int m {0}; m < nmat; ++m) Cache[m] = nullptr;\n  Real vtemp[nmat], rtemp[nmat], utemp[nmat];\n\n  Real dpde[nmat], dtde[nmat], dpdv[nmat], dtdv[nmat];\n\n  // set some options and make the initial EOS calls\n  enum class EosPreference { RhoT, Rhoe };\n  EosPreference eos_choice[nmat];\n  for (int m = 0; m < nmat; m++) {\n    temp[m] = eos[ofst(m)].TemperatureFromDensityInternalEnergy(rho[m], sie[m], Cache[m]);\n    if (eos[ofst(m)].PreferredInput() ==\n        (thermalqs::density | thermalqs::specific_internal_energy)) {\n      eos_choice[m] = EosPreference::Rhoe;\n      press[m] = eos[ofst(m)].PressureFromDensityInternalEnergy(rho[m], sie[m], Cache[m]);\n    } else if (eos[ofst(m)].PreferredInput() ==\n               (thermalqs::density | thermalqs::temperature)) {\n      eos_choice[m] = EosPreference::RhoT;\n      press[m] = eos[ofst(m)].PressureFromDensityTemperature(rho[m], temp[m], Cache[m]);\n    }\n  }\n\n  bool converged_p = false;\n  bool converged_t = false;\n  bool converged = true;\n  niter = 0;\n  constexpr const int pte_max_iter = nmat * pte_max_iter_per_mat;\n  for (niter = 0; niter < pte_max_iter; ++niter) {\n    for (int m = 0; m < nmat; m++) {\n      //////////////////////////////\n      // perturb volume fractions\n      //////////////////////////////\n      const Real deriv_mult = vfrac[m] > 0.01 ? vfrac[m] : 0.01;\n      const Real ldv = std::log(derivative_eps * deriv_mult) * ilog2;\n      Real dv = std::pow(2.0, std::round(ldv));\n      dv *= (vfrac[m] < 0.5 ? 1.0 : -1.0);\n      const Real vf_pert = vfrac[m] + dv;\n      const Real rho_pert = rhobar[m] / vf_pert;\n\n      Real p_pert;\n      Real t_pert =\n          eos[ofst(m)].TemperatureFromDensityInternalEnergy(rho_pert, sie[m], Cache[m]);\n      switch (eos_choice[m]) {\n      case EosPreference::Rhoe:\n        p_pert =\n            eos[ofst(m)].PressureFromDensityInternalEnergy(rho_pert, sie[m], Cache[m]);\n        break;\n      case EosPreference::RhoT:\n        p_pert = eos[ofst(m)].PressureFromDensityTemperature(rho_pert, t_pert, Cache[m]);\n        break;\n      }\n      dpdv[m] = (p_pert - press[m]) / dv;\n      dtdv[m] = (t_pert - temp[m]) / dv;\n      //////////////////////////////\n      // perturb energies\n      //////////////////////////////\n      Real lde = std::log(derivative_eps * std::abs(u[m])) * ilog2;\n      const Real de = std::pow(2.0, std::round(lde));\n      Real e_pert = (u[m] + de) / rhobar[m];\n\n      t_pert =\n          eos[ofst(m)].TemperatureFromDensityInternalEnergy(rho[m], e_pert, Cache[m]);\n      switch (eos_choice[m]) {\n      case EosPreference::Rhoe:\n        p_pert = eos[ofst(m)].PressureFromDensityInternalEnergy(rho[m], e_pert, Cache[m]);\n        break;\n      case EosPreference::RhoT:\n        p_pert = eos[ofst(m)].PressureFromDensityTemperature(rho[m], t_pert, Cache[m]);\n        break;\n      }\n      dpde[m] = (p_pert - press[m]) / de;\n      dtde[m] = (t_pert - temp[m]) / de;\n      if (std::abs(dtde[m]) < 1.e-16) { // must be on the cold curve\n        dtde[m] = derivative_eps;\n        ;\n      }\n    }\n    // Fill in the residual\n    pte_residual<nmat>(utot, vfrac, u, temp, press, residual);\n    Real err = 0;\n    for (int i = 0; i < 2 * nmat; ++i)\n      err += residual[i] * residual[i];\n    err *= 0.5;\n    // Fill in the Jacobian\n    for (int i = 0; i < 4 * nmat * nmat; ++i)\n      jacobian[i] = 0.0;\n    for (int m = 0; m < nmat; ++m) {\n      jacobian[m] = 1.0;\n      jacobian[2 * nmat + nmat + m] = 1.0;\n    }\n    jacobian[2 * 2 * nmat] = dpdv[0];\n    jacobian[nmat * 2 * nmat + nmat - 1] = -dpdv[nmat - 1];\n    jacobian[(nmat + 1) * 2 * nmat] = dtdv[0];\n    jacobian[(2 * nmat - 1) * 2 * nmat + nmat - 1] = -dtdv[nmat - 1];\n    jacobian[2 * 2 * nmat + nmat] = dpde[0];\n    jacobian[nmat * 2 * nmat + 2 * nmat - 1] = -dpde[nmat - 1];\n    jacobian[(nmat + 1) * 2 * nmat + nmat] = dtde[0];\n    jacobian[(2 * nmat - 1) * 2 * nmat + 2 * nmat - 1] = -dtde[nmat - 1];\n    for (int m = 1; m < nmat - 1; ++m) {\n      jacobian[(1 + m) * 2 * nmat + m] = -dpdv[m];\n      jacobian[(2 + m) * 2 * nmat + m] = dpdv[m];\n      jacobian[(nmat + m) * 2 * nmat + m] = -dtdv[m];\n      jacobian[(nmat + m + 1) * 2 * nmat + m] = dtdv[m];\n      jacobian[(1 + m) * 2 * nmat + nmat + m] = -dpde[m];\n      jacobian[(2 + m) * 2 * nmat + nmat + m] = dpde[m];\n      jacobian[(nmat + m) * 2 * nmat + nmat + m] = -dtde[m];\n      jacobian[(nmat + m + 1) * 2 * nmat + nmat + m] = dtde[m];\n    }\n    for (int i = 0; i < 2 * nmat; ++i)\n      dx[i] = residual[i];\n    if (!solve_Ax_b<2 * nmat>(jacobian, dx)) {\n      // do something to crash out?  Tell folks what happened?\n#ifndef KOKKOS_ENABLE_CUDA\n      printf(\"crashing out at iteration: %i\\n\", niter);\n#endif // KOKKOS_ENABLE_CUDA\n      converged = false;\n      // std::cout << \"Crashing out on iteration \"<< niter << std::endl;\n      break;\n    }\n    // Now, get overall scaling limit\n    Real scale = 1.0;\n    for (int m = 0; m < nmat; ++m) {\n      Real vt = vfrac[m] + scale * dx[m];\n      if (vt < 0.0) {\n        scale = -0.1 * vfrac[m] / dx[m];\n      } else if (vt > 1.0) {\n        scale = 0.1 * (1.0 - vfrac[m]) / dx[m];\n      }\n      // maybe the below is dangerous??\n      // const Real dt = (dtdv[m] * dx[m] + dtde[m] * dx[m + nmat]);\n      // const Real tt = temp[m] + scale * dt;\n      // if (tt < 0.0)\n      //  scale = -0.1 * temp[m] / dt;\n    }\n    // Now apply the overall scaling\n    for (int i = 0; i < 2 * nmat; ++i)\n      dx[i] *= scale;\n    // Line search\n    Real gradfdx = -2.0 * scale * err;\n    scale = 1.0;\n    Real err_old = err;\n    int line_iter = 0;\n    do {\n      for (int m = 0; m < nmat; ++m) {\n        vtemp[m] = vfrac[m] + scale * dx[m];\n        rtemp[m] = rhobar[m] / vtemp[m];\n        utemp[m] = u[m] + scale * dx[nmat + m];\n        sie[m] = utemp[m] / rhobar[m];\n        temp[m] =\n            eos[ofst(m)].TemperatureFromDensityInternalEnergy(rtemp[m], sie[m], Cache[m]);\n        switch (eos_choice[m]) {\n        case EosPreference::Rhoe:\n          press[m] =\n              eos[ofst(m)].PressureFromDensityInternalEnergy(rtemp[m], sie[m], Cache[m]);\n          break;\n        case EosPreference::RhoT:\n          press[m] =\n              eos[ofst(m)].PressureFromDensityTemperature(rtemp[m], temp[m], Cache[m]);\n          break;\n        }\n      }\n      pte_residual<nmat>(utot, vtemp, utemp, temp, press, residual);\n      Real err = 0;\n      for (int i = 0; i < 2 * nmat; ++i)\n        err += residual[i] * residual[i];\n      err *= 0.5;\n      line_iter++;\n      if (line_iter > line_search_max_iter ||\n          err < err_old + line_search_alpha * scale * gradfdx)\n        break;\n      scale *= 0.5;\n    } while (true);\n\n    // Update values\n    for (int m = 0; m < nmat; ++m) {\n      vfrac[m] = vtemp[m];\n      rho[m] = rhobar[m] / vfrac[m];\n      u[m] = utemp[m];\n      sie[m] = u[m] / rhobar[m];\n    }\n    // Calculate errors\n    Real mean_p = vfrac[0] * press[0];\n    Real mean_t = rhobar[0] * temp[0];\n    Real error_p = 0.0;\n    Real error_t = 0.0;\n    for (int m = 1; m < nmat; ++m) {\n      mean_p += vfrac[m] * press[m];\n      mean_t += rhobar[m] * temp[m];\n      error_p += residual[m + 1] * residual[m + 1];\n      error_t += residual[m + nmat] * residual[m + nmat];\n    }\n    mean_t /= rho_total;\n    error_p = std::sqrt(error_p);\n    error_t = std::sqrt(error_t);\n    // Check for convergence\n    converged_p = (error_p < pte_rel_tolerance_p * std::abs(mean_p) ||\n                   error_p < pte_abs_tolerance_p);\n    converged_t =\n        (error_t < pte_rel_tolerance_t * mean_t || error_t < pte_abs_tolerance_t);\n    converged = (converged_p && converged_t);\n    if (converged) break;\n    // niter++;\n  } // while (niter < pte_max_iter && !converged);\n  for (int m = 0; m < nmat; ++m)\n    vfrac[m] *= vfrac_tot;\n  return converged;\n}\n\nstruct NullPtrIndexer {\n  PORTABLE_INLINE_FUNCTION Real *operator[](const int i) { return nullptr; }\n};\n\n} // namespace mix_impl\n\ntemplate <int nmat, typename EOSIndexer, typename RealIndexer, typename ConstRealIndexer,\n          typename LambdaIndexer>\nPORTABLE_INLINE_FUNCTION bool pte_closure_flag_with_line(\n    EOSIndexer &&eoss, const Real Volume, const Real TotalSIE,\n    ConstRealIndexer &&ComponentMasses, RealIndexer &&ComponentVolumes,\n    RealIndexer &&ComponentEnergies, LambdaIndexer &&lambdas, int &niter) {\n  using namespace mix_impl;\n  return pte_closure_flag_with_line_impl<nmat>(\n      eoss, Volume, TotalSIE, ComponentMasses, ComponentVolumes, ComponentEnergies,\n      lambdas, [](const int m) { return m; }, niter);\n}\n\ntemplate <int nmat>\nPORTABLE_INLINE_FUNCTION bool\npte_closure_flag_with_line_offset(EOS *eoss, const Real Volume, const Real TotalSIE,\n                                  int const *const ComponentMats,\n                                  const Real *ComponentMasses, Real *ComponentVolumes,\n                                  Real *ComponentEnergies, Real **lambdas, int &niter) {\n  using namespace mix_impl;\n  if (lambdas == nullptr) {\n    NullPtrIndexer lambda_indexer;\n    return pte_closure_flag_with_line_impl<nmat>(\n        eoss, Volume, TotalSIE, ComponentMasses, ComponentVolumes, ComponentEnergies,\n        lambda_indexer, [&ComponentMats](const int m) { return ComponentMats[m]; },\n        niter);\n  }\n  return pte_closure_flag_with_line_impl<nmat>(\n      eoss, Volume, TotalSIE, ComponentMasses, ComponentVolumes, ComponentEnergies,\n      lambdas, [&ComponentMats](const int m) { return ComponentMats[m]; }, niter);\n}\n\ntemplate <int nmat, typename EOSIndexer, typename RealIndexer, typename LambdaIndexer>\nPORTABLE_INLINE_FUNCTION bool pte_closure_josh(EOSIndexer &&eos, const Real vfrac_tot,\n                                               const Real sie_tot, RealIndexer &&rho,\n                                               RealIndexer &&vfrac, RealIndexer &&sie,\n                                               RealIndexer &&temp, RealIndexer &&press,\n                                               LambdaIndexer &&lambda, int &niter) {\n  using namespace mix_impl;\n  return pte_closure_josh_impl<nmat>(\n      eos, vfrac_tot, sie_tot, rho, vfrac, sie, temp, press, lambda,\n      [&](const int m) { return m; }, niter);\n}\n\ntemplate <int nmat>\nPORTABLE_INLINE_FUNCTION bool\npte_closure_josh_offset(EOS *eos, const Real vfrac_tot, const Real sie_tot,\n                        int const *const Mats, Real *rho, Real *vfrac, Real *sie,\n                        Real *temp, Real *press, Real **lambda, int &niter) {\n  using namespace mix_impl;\n  if (lambda == nullptr) {\n    NullPtrIndexer lambda_indexer;\n    return pte_closure_josh_impl<nmat>(\n        eos, vfrac_tot, sie_tot, rho, vfrac, sie, temp, press, lambda_indexer,\n        [&](const int m) { return m; }, niter);\n  }\n  return pte_closure_josh_impl<nmat>(\n      eos, vfrac_tot, sie_tot, rho, vfrac, sie, temp, press, lambda,\n      [&Mats](const int m) { return Mats[m]; }, niter);\n}\n\ntemplate <int nmat, typename EOSIndexer, typename RealIndexer, typename ConstRealIndexer,\n          typename LambdaIndexer>\nPORTABLE_INLINE_FUNCTION bool\npte_closure_ideal(EOSIndexer &&eoss, const Real Volume, const Real TotalSIE,\n                  ConstRealIndexer &&ComponentMasses, RealIndexer &&ComponentVolumes,\n                  RealIndexer &&ComponentEnergies, LambdaIndexer &&lambdas, int &iter) {\n  using namespace mix_params;\n  using namespace mix_impl;\n  Real TotalMass = 0.0, Vsum = 0.0, Esum = 0.0;\n  Real Densities[nmat], Pressures[nmat], Temperatures[nmat], dpdr[nmat], dpde[nmat],\n      dtdr[nmat], dtde[nmat], dtpdv[nmat], dtpde[nmat], dtdv[nmat], b[2 * nmat],\n      A[4 * nmat * nmat], rtemp[nmat], sietemp[nmat];\n  // First, normalize the energies and volumes.\n  // This may or may not be close to reality since SIE isn't strictly positive.\n  for (int i = 0; i < nmat; ++i)\n    TotalMass += ComponentMasses[i];\n  bool iszero = false;\n  for (int i = 0; i < nmat; ++i)\n    iszero &= ComponentVolumes[i] <= 1.0e-16;\n  if (iszero)\n    for (int i = 0; i < nmat; ++i)\n      ComponentVolumes[i] = Volume * ComponentMasses[i] / TotalMass;\n  for (int i = 0; i < nmat; ++i)\n    Vsum += ComponentVolumes[i];\n  for (int i = 0; i < nmat; ++i)\n    ComponentVolumes[i] *=\n        Volume / Vsum; // Are compilers smart enough to calculate this RHS once?\n  for (int i = 0; i < nmat; ++i)\n    Esum += ComponentEnergies[i] * ComponentMasses[i];\n  if (std::abs(Esum) <\n      0.0001) { // Then we punt and just distribute based on mass fractions\n    for (int i = 0; i < nmat; ++i)\n      ComponentEnergies[i] = TotalSIE * TotalMass / ComponentMasses[i];\n  } else { // Otherwise, we scale\n    for (int i = 0; i < nmat; ++i)\n      ComponentEnergies[i] *= (TotalSIE * TotalMass / Esum);\n  }\n\n  // This is the main loop\n  constexpr const int pte_max_iter = nmat * pte_max_iter_per_mat;\n  for (iter = 0; iter < pte_max_iter; ++iter) {\n    // Call the EOSs\n    for (int mat = 0; mat < nmat; ++mat) {\n      Densities[mat] = ComponentMasses[mat] / ComponentVolumes[mat];\n      eoss[mat].PTofRE(Densities[mat], ComponentEnergies[mat], lambdas[mat],\n                       Pressures[mat], Temperatures[mat], dpdr[mat], dpde[mat], dtdr[mat],\n                       dtde[mat]);\n      // NOTE: here we are re-using this space for d(P/T)/dr and /de using the\n      // chain rule If it is deemed useful, we can output this quantity from the\n      // EOS call instead\n      dtpdv[mat] = -(dtdr[mat] - Temperatures[mat] / Pressures[mat] * dpdr[mat]) /\n                   Pressures[mat] * square(Densities[mat]);\n      dtpde[mat] =\n          (dtde[mat] - Temperatures[mat] / Pressures[mat] * dpde[mat]) / Pressures[mat];\n      dtdv[mat] = -dtdr[mat] * square(Densities[mat]);\n    }\n    // Now, zero the matrix and vector\n    for (int i = 0; i < 2 * nmat * 2 * nmat; ++i)\n      A[i] = 0.0;\n    for (int i = 0; i < 2 * nmat; ++i)\n      b[i] = 0.0;\n    Real vsum = 0.0;\n    Real esum = 0.0;\n    Real err = 0.0;\n    // build matrix and vector\n    for (int n = 0; n < nmat - 1; ++n) {\n      const int i = n + nmat;\n      // First, do the energy side\n      A[n * 2 * nmat + n] = dtde[n];\n      A[n * 2 * nmat + n + 1] = -dtde[n + 1];\n      A[n * 2 * nmat + i] = dtdv[n];\n      A[n * 2 * nmat + i + 1] = -dtdv[n + 1];\n      A[(nmat - 1) * 2 * nmat + n] = ComponentMasses[n];\n      b[n] = Temperatures[n + 1] - Temperatures[n];\n      // Now the density half\n      A[i * 2 * nmat + n] = dtpde[n];\n      A[i * 2 * nmat + n + 1] = -dtpde[n + 1];\n      A[i * 2 * nmat + i] = dtpdv[n];\n      A[i * 2 * nmat + i + 1] = -dtpdv[n + 1];\n      A[(2 * nmat - 1) * 2 * nmat + i] = 1;\n      b[i] = Pressures[n + 1] / Temperatures[n + 1] - Pressures[n] / Temperatures[n];\n      vsum += ComponentMasses[n] / Densities[n];\n      esum += ComponentMasses[n] * ComponentEnergies[n];\n    }\n    A[(nmat - 1) * 2 * nmat + nmat - 1] = ComponentMasses[nmat - 1];\n    b[nmat - 1] = esum - TotalMass * TotalSIE;\n    A[4 * nmat * nmat - 1] = 1.0;\n    vsum += ComponentMasses[nmat - 1] / Densities[nmat - 1];\n    b[2 * nmat - 1] = vsum - Volume;\n    for (int i = 0; i < 2 * nmat; ++i)\n      err += square(b[i]);\n    err *= 0.5;\n    // Solve the thing\n    if (!solve_Ax_b<2 * nmat>(A, b)) {\n      // do something to crash out?  Tell folks what happened?\n      break;\n    }\n\n    // LINE SEARCH\n\n    // Now, get overall scaling limit\n    Real scale = 1.0;\n    for (int m = 0; m < nmat; ++m) {\n      Real rt = ComponentMasses[m] / (ComponentVolumes[m] + scale * b[m + nmat]);\n      if (rt < 0.0) {\n        scale = -0.9 * ComponentVolumes[m] / b[m + nmat];\n      }\n      const Real dt = (dtdv[m] * b[m + nmat] + dtde[m] * b[m]);\n      const Real tt = Temperatures[m] + scale * dt;\n      if (tt < 0.0) scale = -0.9 * Temperatures[m] / dt;\n    }\n    // Now apply the overall pre-scaling\n    for (int i = 0; i < 2 * nmat; ++i)\n      b[i] *= scale;\n    // Line search\n    Real gradfdx = -2.0 * scale * err;\n    scale = 1.0;\n    Real err_old = err;\n    int line_iter = 0;\n    Real err_p, err_t;\n    do {\n      for (int m = 0; m < nmat; ++m) {\n        rtemp[m] = ComponentMasses[m] / (ComponentVolumes[m] + scale * b[m + nmat]);\n        sietemp[m] = ComponentEnergies[m] + scale * b[m];\n        Temperatures[m] = eoss[m].TemperatureFromDensityInternalEnergy(\n            rtemp[m], sietemp[m], lambdas[m]);\n        if (eoss[m].PreferredInput() ==\n            (thermalqs::density | thermalqs::specific_internal_energy)) {\n          Pressures[m] =\n              eoss[m].PressureFromDensityInternalEnergy(rtemp[m], sietemp[m], lambdas[m]);\n        } else if (eoss[m].PreferredInput() ==\n                   (thermalqs::density | thermalqs::temperature)) {\n          Pressures[m] = eoss[m].PressureFromDensityTemperature(rtemp[m], Temperatures[m],\n                                                                lambdas[m]);\n        }\n      }\n      err_p = 0.0;\n      err_t = 0.0;\n      for (int n = 0; n < nmat - 1; ++n) {\n        err_p += square(Pressures[n + 1] - Pressures[n]);\n        err_t += square(Temperatures[n + 1] - Temperatures[n]);\n      }\n      err = 0.5 * (err_p + err_t);\n      line_iter++;\n      if (line_iter > line_search_max_iter ||\n          err < err_old + line_search_alpha * scale * gradfdx)\n        break;\n      scale *= line_search_fac;\n    } while (true);\n\n    // END LINE SEARCH\n\n    Real mean_p = 0, mean_t = 0;\n\n    for (int i = 0; i < 2 * nmat; ++i)\n      b[i] *= scale;\n    for (int n = 0; n < nmat; ++n) {\n      const int i = nmat + n;\n      ComponentEnergies[n] += b[n];\n      ComponentVolumes[n] += b[i];\n      Densities[n] = ComponentMasses[n] / ComponentVolumes[n];\n      mean_p += ComponentVolumes[n] * Pressures[n];\n      mean_t += ComponentMasses[n] * Temperatures[n];\n    }\n    mean_p /= Volume;\n    mean_t /= TotalMass;\n    err_p = std::sqrt(err_p);\n    err_t = std::sqrt(err_t);\n    bool converged_p =\n        (err_p < pte_rel_tolerance_p * std::abs(mean_p) || err_p < pte_abs_tolerance_p);\n    bool converged_t =\n        (err_t < pte_rel_tolerance_t * std::abs(mean_t) || err_t < pte_abs_tolerance_t);\n    if (converged_p && converged_t) {\n      return true; // FIXME\n    }\n  }\n  return false; // FIXME\n}\n\n// TODO(JMM): The case statement below to switch between templated\n// versions of these functions is still extremely gross and I hate it.\n// Can we replace with a malloc+free? And if so, what's the\n// consequences of that?\ntemplate <typename EOSIndexer, typename RealIndexer, typename ConstRealIndexer,\n          typename LambdaIndexer>\nPORTABLE_INLINE_FUNCTION bool\npte_closure_flag(int nmat, EOSIndexer &&eoss, const Real Volume, const Real TotalSIE,\n                 ConstRealIndexer &&ComponentMasses, RealIndexer &&ComponentVolumes,\n                 RealIndexer &&ComponentEnergies, LambdaIndexer &&lambdas, int &niter) {\n  switch (nmat) {\n  case 1:\n    return true; // (or should we call the EOS actually?)\n  case 2:\n    return pte_closure_flag_with_line<2>(eoss, Volume, TotalSIE, ComponentMasses,\n                                         ComponentVolumes, ComponentEnergies, lambdas,\n                                         niter);\n    break;\n  case 3:\n    return pte_closure_flag_with_line<3>(eoss, Volume, TotalSIE, ComponentMasses,\n                                         ComponentVolumes, ComponentEnergies, lambdas,\n                                         niter);\n    break;\n  case 4:\n    return pte_closure_flag_with_line<4>(eoss, Volume, TotalSIE, ComponentMasses,\n                                         ComponentVolumes, ComponentEnergies, lambdas,\n                                         niter);\n    break;\n  case 5:\n    return pte_closure_flag_with_line<5>(eoss, Volume, TotalSIE, ComponentMasses,\n                                         ComponentVolumes, ComponentEnergies, lambdas,\n                                         niter);\n    break;\n  case 6:\n    return pte_closure_flag_with_line<6>(eoss, Volume, TotalSIE, ComponentMasses,\n                                         ComponentVolumes, ComponentEnergies, lambdas,\n                                         niter);\n    break;\n  case 7:\n    return pte_closure_flag_with_line<7>(eoss, Volume, TotalSIE, ComponentMasses,\n                                         ComponentVolumes, ComponentEnergies, lambdas,\n                                         niter);\n    break;\n  case 8:\n    return pte_closure_flag_with_line<8>(eoss, Volume, TotalSIE, ComponentMasses,\n                                         ComponentVolumes, ComponentEnergies, lambdas,\n                                         niter);\n    break;\n  }\n  return false;\n}\nPORTABLE_INLINE_FUNCTION\nbool pte_closure_flag_offset(int nmat, EOS *eoss, const Real Volume, const Real TotalSIE,\n                             int const *const ComponentMats, const Real *ComponentMasses,\n                             Real *ComponentVolumes, Real *ComponentEnergies,\n                             Real **lambdas, int &niter) {\n  switch (nmat) {\n  case 1:\n    return true; // (or should we call the EOS actually?)\n  case 2:\n    return pte_closure_flag_with_line_offset<2>(eoss, Volume, TotalSIE, ComponentMats,\n                                                ComponentMasses, ComponentVolumes,\n                                                ComponentEnergies, lambdas, niter);\n    break;\n  case 3:\n    return pte_closure_flag_with_line_offset<3>(eoss, Volume, TotalSIE, ComponentMats,\n                                                ComponentMasses, ComponentVolumes,\n                                                ComponentEnergies, lambdas, niter);\n    break;\n  case 4:\n    return pte_closure_flag_with_line_offset<4>(eoss, Volume, TotalSIE, ComponentMats,\n                                                ComponentMasses, ComponentVolumes,\n                                                ComponentEnergies, lambdas, niter);\n    break;\n  case 5:\n    return pte_closure_flag_with_line_offset<5>(eoss, Volume, TotalSIE, ComponentMats,\n                                                ComponentMasses, ComponentVolumes,\n                                                ComponentEnergies, lambdas, niter);\n    break;\n  case 6:\n    return pte_closure_flag_with_line_offset<6>(eoss, Volume, TotalSIE, ComponentMats,\n                                                ComponentMasses, ComponentVolumes,\n                                                ComponentEnergies, lambdas, niter);\n    break;\n  case 7:\n    return pte_closure_flag_with_line_offset<7>(eoss, Volume, TotalSIE, ComponentMats,\n                                                ComponentMasses, ComponentVolumes,\n                                                ComponentEnergies, lambdas, niter);\n    break;\n  case 8:\n    return pte_closure_flag_with_line_offset<8>(eoss, Volume, TotalSIE, ComponentMats,\n                                                ComponentMasses, ComponentVolumes,\n                                                ComponentEnergies, lambdas, niter);\n    break;\n  }\n  return false;\n}\ntemplate <typename EOSIndexer, typename RealIndexer, typename LambdaIndexer>\nPORTABLE_INLINE_FUNCTION bool\npte_closure_josh(int nmat, EOSIndexer &&eoss, const Real vfrac_tot, const Real sie_tot,\n                 RealIndexer &&rho, RealIndexer &&vfrac, RealIndexer &&sie,\n                 RealIndexer &&temp, RealIndexer &&press, LambdaIndexer &&lambdas,\n                 int &niter) {\n  switch (nmat) {\n  case 1:\n    return true; // (or should we call the EOS actually?)\n  case 2:\n    return pte_closure_josh<2>(eoss, vfrac_tot, sie_tot, rho, vfrac, sie, temp, press,\n                               lambdas, niter);\n    break;\n  case 3:\n    return pte_closure_josh<3>(eoss, vfrac_tot, sie_tot, rho, vfrac, sie, temp, press,\n                               lambdas, niter);\n    break;\n  case 4:\n    return pte_closure_josh<4>(eoss, vfrac_tot, sie_tot, rho, vfrac, sie, temp, press,\n                               lambdas, niter);\n    break;\n  case 5:\n    return pte_closure_josh<5>(eoss, vfrac_tot, sie_tot, rho, vfrac, sie, temp, press,\n                               lambdas, niter);\n    break;\n  case 6:\n    return pte_closure_josh<6>(eoss, vfrac_tot, sie_tot, rho, vfrac, sie, temp, press,\n                               lambdas, niter);\n    break;\n  case 7:\n    return pte_closure_josh<7>(eoss, vfrac_tot, sie_tot, rho, vfrac, sie, temp, press,\n                               lambdas, niter);\n    break;\n  case 8:\n    return pte_closure_josh<8>(eoss, vfrac_tot, sie_tot, rho, vfrac, sie, temp, press,\n                               lambdas, niter);\n    break;\n  }\n  return false;\n}\nPORTABLE_INLINE_FUNCTION bool\npte_closure_josh_offset(int nmat, EOS *eoss, const Real vfrac_tot, const Real sie_tot,\n                        int const *const Mats, Real *rho, Real *vfrac, Real *sie,\n                        Real *temp, Real *press, Real **lambdas, int &niter) {\n  switch (nmat) {\n  case 1:\n    return true; // (or should we call the EOS actually?)\n  case 2:\n    return pte_closure_josh_offset<2>(eoss, vfrac_tot, sie_tot, Mats, rho, vfrac, sie,\n                                      temp, press, lambdas, niter);\n    break;\n  case 3:\n    return pte_closure_josh_offset<3>(eoss, vfrac_tot, sie_tot, Mats, rho, vfrac, sie,\n                                      temp, press, lambdas, niter);\n    break;\n  case 4:\n    return pte_closure_josh_offset<4>(eoss, vfrac_tot, sie_tot, Mats, rho, vfrac, sie,\n                                      temp, press, lambdas, niter);\n    break;\n  case 5:\n    return pte_closure_josh_offset<5>(eoss, vfrac_tot, sie_tot, Mats, rho, vfrac, sie,\n                                      temp, press, lambdas, niter);\n    break;\n  case 6:\n    return pte_closure_josh_offset<6>(eoss, vfrac_tot, sie_tot, Mats, rho, vfrac, sie,\n                                      temp, press, lambdas, niter);\n    break;\n  case 7:\n    return pte_closure_josh_offset<7>(eoss, vfrac_tot, sie_tot, Mats, rho, vfrac, sie,\n                                      temp, press, lambdas, niter);\n    break;\n  case 8:\n    return pte_closure_josh_offset<8>(eoss, vfrac_tot, sie_tot, Mats, rho, vfrac, sie,\n                                      temp, press, lambdas, niter);\n    break;\n  }\n  return false;\n}\ntemplate <typename EOSIndexer, typename RealIndexer, typename ConstRealIndexer,\n          typename LambdaIndexer>\nPORTABLE_INLINE_FUNCTION bool\npte_closure_ideal(int nmat, EOSIndexer &&eoss, const Real Volume, const Real TotalSIE,\n                  ConstRealIndexer &&ComponentMasses, RealIndexer &&ComponentVolumes,\n                  RealIndexer &&ComponentEnergies, LambdaIndexer &&lambdas, int &niter) {\n  switch (nmat) {\n  case 1:\n    return true; // (or should we call the EOS actually?)\n  case 2:\n    return pte_closure_ideal<2>(eoss, Volume, TotalSIE, ComponentMasses, ComponentVolumes,\n                                ComponentEnergies, lambdas, niter);\n    break;\n  case 3:\n    return pte_closure_ideal<3>(eoss, Volume, TotalSIE, ComponentMasses, ComponentVolumes,\n                                ComponentEnergies, lambdas, niter);\n    break;\n  case 4:\n    return pte_closure_ideal<4>(eoss, Volume, TotalSIE, ComponentMasses, ComponentVolumes,\n                                ComponentEnergies, lambdas, niter);\n    break;\n  case 5:\n    return pte_closure_ideal<5>(eoss, Volume, TotalSIE, ComponentMasses, ComponentVolumes,\n                                ComponentEnergies, lambdas, niter);\n    break;\n  case 6:\n    return pte_closure_ideal<6>(eoss, Volume, TotalSIE, ComponentMasses, ComponentVolumes,\n                                ComponentEnergies, lambdas, niter);\n    break;\n  case 7:\n    return pte_closure_ideal<7>(eoss, Volume, TotalSIE, ComponentMasses, ComponentVolumes,\n                                ComponentEnergies, lambdas, niter);\n    break;\n  case 8:\n    return pte_closure_ideal<8>(eoss, Volume, TotalSIE, ComponentMasses, ComponentVolumes,\n                                ComponentEnergies, lambdas, niter);\n    break;\n  }\n  return false;\n}\n} // namespace singularity\n\n#endif // _SINGULARITY_EOS_CLOSURE_MIXED_CELL_MODELS_\n", "meta": {"hexsha": "919bc4313f5445fce7a0d9bd17456050bac63fdb", "size": 50322, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "singularity-eos/closure/mixed_cell_models.hpp", "max_stars_repo_name": "lanl/singularity-eos", "max_stars_repo_head_hexsha": "c35669b93a492903ad4ce7a15211bd42b7c88d37", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-14T15:08:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T16:32:19.000Z", "max_issues_repo_path": "singularity-eos/closure/mixed_cell_models.hpp", "max_issues_repo_name": "lanl/singularity-eos", "max_issues_repo_head_hexsha": "c35669b93a492903ad4ce7a15211bd42b7c88d37", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 70.0, "max_issues_repo_issues_event_min_datetime": "2021-04-15T23:08:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T17:43:18.000Z", "max_forks_repo_path": "singularity-eos/closure/mixed_cell_models.hpp", "max_forks_repo_name": "lanl/singularity-eos", "max_forks_repo_head_hexsha": "c35669b93a492903ad4ce7a15211bd42b7c88d37", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-21T16:59:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-17T20:52:38.000Z", "avg_line_length": 42.3585858586, "max_line_length": 90, "alphanum_fraction": 0.5969754779, "num_tokens": 14633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2981974454435981}}
{"text": "#ifndef FSTCLASSIFIERKNN_H\n#define FSTCLASSIFIERKNN_H\n\n/*!======================================================================\n   Feature Selection Toolbox 3 source code\n   ---------------------------------------\n\t\n   \\file    classifier_knn.hpp\n   \\brief   Implements k-Nearest Neighbor classifier\n   \\author  Petr Somol (somol@utia.cas.cz) with collaborators, see Contacts at http://fst.utia.cz\n   \\date    March 2011\n   \\version 3.1.0.beta\n   \\note    FST3 was developed using gcc 4.3 and requires\n   \\note    \\li Boost library (http://www.boost.org/, tested with versions 1.33.1 and 1.44),\n   \\note    \\li (\\e optionally) LibSVM (http://www.csie.ntu.edu.tw/~cjlin/libsvm/, \n                tested with version 3.00)\n   \\note    Note that LibSVM is required for SVM related tools only,\n            as demonstrated in demo12t.cpp, demo23.cpp, demo25t.cpp, demo32t.cpp, etc.\n\n*/ /* \n=========================================================================\nCopyright:\n  * FST3 software (with exception of any externally linked libraries) \n    is copyrighted by Institute of Information Theory and Automation (UTIA), \n    Academy of Sciences of the Czech Republic.\n  * FST3 source codes as presented here do not contain code of third parties. \n    FST3 may need linkage to external libraries to exploit its functionality\n    in full. For details on obtaining and possible usage restrictions \n    of external libraries follow their original sources (referenced from\n    FST3 documentation wherever applicable).\n  * FST3 software is available free of charge for non-commercial use. \n    Please address all inquires concerning possible commercial use \n    of FST3, or if in doubt, to FST3 maintainer (see http://fst.utia.cz)\n  * Derivative works based on FST3 are permitted as long as they remain\n    non-commercial only.\n  * Re-distribution of FST3 software is not allowed without explicit\n    consent of the copyright holder.\nDisclaimer of Warranty:\n  * FST3 software is presented \"as is\", without warranty of any kind, \n    either expressed or implied, including, but not limited to, the implied \n    warranties of merchantability and fitness for a particular purpose. \n    The entire risk as to the quality and performance of the program \n    is with you. Should the program prove defective, you assume the cost \n    of all necessary servicing, repair or correction.\nLimitation of Liability:\n  * The copyright holder will in no event be liable to you for damages, \n    including any general, special, incidental or consequential damages \n    arising out of the use or inability to use the code (including but not \n    limited to loss of data or data being rendered inaccurate or losses \n    sustained by you or third parties or a failure of the program to operate \n    with any other programs).\n========================================================================== */\n\n#include <boost/smart_ptr.hpp>\n#include <iostream>\n#include <cmath>\n#include <list>\n#include \"classifier.hpp\"\n#include \"error.hpp\"\n#include \"global.hpp\"\n\n/*============== Template parameter type naming conventions ==============\n--------- Numeric types: -------------------------------------------------\nDATATYPE - data sample values - usually real numbers (but may be integers\n          in text processing etc.)\nREALTYPE - must be real numbers - for representing intermediate results of \n          calculations like mean, covariance etc.\nIDXTYPE - index values for enumeration of data samples - (nonnegative) integers, \n          extent depends on numbers of samples in data\nDIMTYPE - index values for enumeration of features (dimensions), or classes (not \n          class sizes) - (nonnegative) integers, usually lower extent than IDXTYPE, \n          but be aware of expressions like _classes*_features*_features ! \n          in linearized representations of feature matrices for all classes\nBINTYPE - feature selection marker type - represents ca. <10 different feature \n          states (selected, deselected, sel./desel. temporarily 1st nested loop, 2nd...)\nRETURNTYPE - criterion value: real value, but may be extended in future to support \n          multiple values \n--------- Class types: ---------------------------------------------------\nSUBSET       - class of class type Subset \nCLASSIFIER   - class implementing interface defined in abstract class Classifier \nEVALUATOR    - class implementing interface defined in abstract class Sequential_Step \nDISTANCE     - class implementing interface defined in abstract class Distance \nDATAACCESSOR - class implementing interface defined in abstract class Data_Accessor \nINTERVALCONTAINER - class of class type TIntervaller \nCONTAINER    - STL container of class type TInterval  \n========================================================================== */\n\nnamespace FST {\n\n//! Implements k-Nearest Neighbor classifier\ntemplate<class RETURNTYPE, typename DATATYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR, class DISTANCE>\nclass Classifier_kNN : public Classifier<RETURNTYPE,DIMTYPE,SUBSET,DATAACCESSOR> { \npublic:\n\ttypedef Classifier<RETURNTYPE,DIMTYPE,SUBSET,DATAACCESSOR> parent;\n\ttypedef boost::shared_ptr<DATAACCESSOR> PDataAccessor;\n\ttypedef boost::shared_ptr<SUBSET> PSubset;\n\ttypedef typename DATAACCESSOR::PPattern PPattern;\n\tClassifier_kNN() {set_k(1); _nns_max_size=1; notify(\"Classifier_kNN constructor.\");}\n\tvirtual ~Classifier_kNN() {notify(\"Classifier_kNN destructor.\");}\n\n\tvoid set_k(const DIMTYPE k) {assert(k>0); _k=k; _nns_max_size=_k;} // NOTE: _nns_max_size may be set larger to help avoiding ties\n\tDIMTYPE get_k() const {return _k;}\n\n\tvirtual bool classify(DIMTYPE &cls, const PPattern &pattern);  // classifies pattern, returns the respective class index\n\tvirtual bool train(const PDataAccessor da, const PSubset sub); // with kNN there is actually no training. This just stores pointer to training data to be later accessed from test()\n\tvirtual bool test(RETURNTYPE &result, const PDataAccessor da); // estimates accuracy using designated test data\n\t\n\tClassifier_kNN* clone() const;\n\tClassifier_kNN* sharing_clone() const {throw fst_error(\"Classifier_kNN::sharing_clone() not supported, use Classifier_kNN::clone() instead.\");}\n\tClassifier_kNN* stateless_clone() const {throw fst_error(\"Classifier_kNN::stateless_clone() not supported, use Classifier_kNN::clone() instead.\");}\n\t\n\tvirtual std::ostream& print(std::ostream& os) const;\nprivate:\n\tClassifier_kNN(const Classifier_kNN& cknn); // copy-constructor \nprotected:\n\t// NOTE: for given k it is better to keep ((k-1)*NoOfClasses+1) nearest neighbours to prevent ties (provided enough neighbours exist)\n\t// NOTE: equal neighbour distances to different classes are not handled extra\n\t\n\t//! Holds information on distance and data-class membership of neighbors processed in Classifier_kNN\n\tclass Neighbour{\n\tpublic:\n\t\tNeighbour() {}\n\t\tNeighbour(const RETURNTYPE value, const DIMTYPE cls) {_value=value; _cls=cls;}\n\t\tNeighbour(const Neighbour& nei) {_value=nei._value; _cls=nei._cls;}\t//!< copy constructor\n\t\tRETURNTYPE _value; \n\t\tDIMTYPE _cls;\n\t};\n\tDIMTYPE _k;\n\tDIMTYPE _k_enough;\n\tDIMTYPE _nns_max_size;\n\tvoid sort_in(const RETURNTYPE value, const DIMTYPE cls);\n\tDIMTYPE get_most_freq_cls();\n\ttypename std::list<Neighbour>::iterator iter;\n\tstd::list<Neighbour> _nns; // implemented descending ... the closest neighbour is the last\n\tstd::vector<DIMTYPE> cls_freqs;\n\t\n\tboost::scoped_ptr<DISTANCE> _distance;\n\tPDataAccessor _da_train; // with kNN there is actually no training. This is meant to store pointer to training data to be later accessed from test()\n};\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR, class DISTANCE>\nClassifier_kNN<RETURNTYPE,DATATYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR,DISTANCE>::Classifier_kNN(const Classifier_kNN& cknn) :\n\t_k(cknn._k),\n\t_k_enough(cknn._k_enough),\n\t_nns_max_size(cknn._nns_max_size),\n\t_nns(cknn._nns),\n\tcls_freqs(cknn.cls_freqs)\n{\n\tnotify(\"Classifier_kNN constructor.\");\n\tif(cknn._distance) _distance.reset(cknn._distance->clone());\n}\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR, class DISTANCE>\nClassifier_kNN<RETURNTYPE,DATATYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR,DISTANCE>* Classifier_kNN<RETURNTYPE,DATATYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR,DISTANCE>::clone() const\n{\n\tClassifier_kNN<RETURNTYPE,DATATYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR,DISTANCE> *clone=new Classifier_kNN<RETURNTYPE,DATATYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR,DISTANCE>(*this);\n\tclone->set_cloned();\n\treturn clone;\n}\n\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR, class DISTANCE>\nbool Classifier_kNN<RETURNTYPE,DATATYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR,DISTANCE>::train(const PDataAccessor da, const PSubset sub)\n{\n\tassert(da);\n\tassert(sub);\n\tif(!_distance || _distance->get_n()<sub->get_n_raw()) _distance.reset(new DISTANCE(sub->get_n_raw()));\n\t_distance->narrow_to(sub);\n\t_da_train=da;\n\treturn true;\n}\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR, class DISTANCE>\nbool Classifier_kNN<RETURNTYPE,DATATYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR,DISTANCE>::classify(DIMTYPE &cls, const PPattern &pattern)\n{\n\t// NOTE: uses da_train_loop=0 \n\t// NOTE: da and _da_train may point to the same instance -> be careful with setClass() etc.\n\tassert(_da_train);\n\tassert(_distance);\n\tassert(_distance->get_n()==_da_train->getNoOfFeatures());\n\tassert(_distance->get_d()>0);\n\ttypename DATAACCESSOR::PPattern p2;\n\tIDXTYPE s2,i2;\n\tbool b;\n\tDIMTYPE _feats=_da_train->getNoOfFeatures();\n\tRETURNTYPE val;\n\t\n\tconst DIMTYPE da_train_loop=0; // to avoid mixup of get*Block() loops of different types be careful when calling classify() from a different loop\n\t\n\tcls_freqs.resize(_da_train->getNoOfClasses());\n\t_nns_max_size=(_k-1)*_da_train->getNoOfClasses()+1; // to help avoiding ties\n\t_k_enough=DIMTYPE(floor(0.5*(RETURNTYPE)_k)+1); \n\t\n\t_nns.clear();\n\tfor(DIMTYPE c_train=0;c_train<_da_train->getNoOfClasses();c_train++)\n\t{\n\t\t_da_train->setClass(c_train);\n\t\tfor(b=_da_train->getFirstBlock(TRAIN,p2,s2,da_train_loop);b==true;b=_da_train->getNextBlock(TRAIN,p2,s2,da_train_loop)) for(i2=0;i2<s2;i2++)\n\t\t{\n\t\t\t// p2[i2*_feats] is the beginning of the current pattern\n\t\t\tval=_distance->distance(pattern,&p2[i2*_feats]);\n\t\t\tsort_in(val,c_train);\n\t\t}\n\t}\n\tcls=get_most_freq_cls();\n\n\treturn true;\n}\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR, class DISTANCE>\nbool Classifier_kNN<RETURNTYPE,DATATYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR,DISTANCE>::test(RETURNTYPE &result, const PDataAccessor da)\n{\n\t// NOTE: da and _da_train may point to the same instance -> be careful with setClass() etc.\n\tassert(da);\n\tassert(_da_train);\n\tassert(_distance);\n\tassert(da->getNoOfFeatures()==_da_train->getNoOfFeatures());\n\tassert(_distance->get_n()==_da_train->getNoOfFeatures());\n\ttypename DATAACCESSOR::PPattern p1;\n\tIDXTYPE s1,i1;\n\tbool b;\n\tIDXTYPE count=0, correct=0;\n\tDIMTYPE _feats=da->getNoOfFeatures();\n\tDIMTYPE clstmp;\n\t\n\tconst DIMTYPE da_test_loop=1; // to avoid mixup of get*Block() loops of different types (must not! be 0, see classify())\n\t\n\tcls_freqs.resize(_da_train->getNoOfClasses());\n\t_nns_max_size=(_k-1)*_da_train->getNoOfClasses()+1; // to help avoiding ties\n\t_k_enough=DIMTYPE(floor(0.5*(RETURNTYPE)_k)+1); \n\t\n\tfor(DIMTYPE c_test=0;c_test<da->getNoOfClasses();c_test++)\n\t{\n\t\tda->setClass(c_test);\n\t\tfor(b=da->getFirstBlock(TEST,p1,s1,da_test_loop);b==true;b=da->getNextBlock(TEST,p1,s1,da_test_loop)) {\n\t\t\tfor(i1=0;i1<s1;i1++)\n\t\t\t{\n\t\t\t\tif(!classify(clstmp,&p1[i1*_feats])) return false; // \\note classify() internally uses block loop index 0\n\t\t\t\tif(clstmp==c_test) ++correct;\n\t\t\t\t++count;\n\t\t\t}\n\t\t\tda->setClass(c_test); // necessary for the case of da pointing to the same object as _da_train\n\t\t}\n\t}\n\tif(count==0) return false;\n\tresult = (RETURNTYPE)correct/(RETURNTYPE)count;\n\treturn true;\n}\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR, class DISTANCE>\nvoid Classifier_kNN<RETURNTYPE,DATATYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR,DISTANCE>::sort_in(const RETURNTYPE value, const DIMTYPE cls)\n{\n\titer=_nns.begin();\n\twhile(iter!=_nns.end() && value < (*iter)._value) iter++;\n\tif(_nns.size()<_nns_max_size || iter!=_nns.begin()) {\n\t\tNeighbour tmp(value,cls);\n\t\t_nns.insert(iter,tmp);\n\t\t// NOTE: ? consider: if(as below && first value!= second value) _nns.pop_front() .. to prevent loosing tie info\n\t\tif(_nns.size()>_nns_max_size) _nns.pop_front();\n\t}\n}\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR, class DISTANCE>\nDIMTYPE Classifier_kNN<RETURNTYPE,DATATYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR,DISTANCE>::get_most_freq_cls()\n{ // NOTE: destructs contents of _nns !\n\tassert(_da_train);\n\tDIMTYPE i,c,c_max,max=0;\n\tfor(i=0;i<_da_train->getNoOfClasses();i++) cls_freqs[i]=0;\n\twhile(_nns.size()>0) {\n\t\tc=(_nns.back()._cls);\n\t\tif(++cls_freqs[c]==_k_enough) return c;\n\t\tif(cls_freqs[c]>max) {max=cls_freqs[c]; c_max=c;}\n\t\t_nns.pop_back();\n\t}\n\tif(max>0) return c_max;\n\telse return _da_train->getNoOfClasses(); // wrong class\n}\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR, class DISTANCE>\nstd::ostream& Classifier_kNN<RETURNTYPE,DATATYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR,DISTANCE>::print(std::ostream& os) const \n{\n\tos << \"Clasifier_kNN(k=\" << _k << \")\";\n\tif(_distance) os << *_distance;\n\treturn os;\n}\n\n} // namespace\n#endif // FSTCLASSIFIERKNN_H ///:~\n", "meta": {"hexsha": "14395a7c478d6f66dbedf7444ffc061a2fbd3fa8", "size": 13749, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "extern/FST3lib/_src_criteria/classifier_knn.hpp", "max_stars_repo_name": "boussaffawalid/FeatureSelection", "max_stars_repo_head_hexsha": "9768a044c0c0dc2c4a2dc0f6e65413d19e92766c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-07-07T20:18:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-23T06:46:02.000Z", "max_issues_repo_path": "extern/FST3lib/_src_criteria/classifier_knn.hpp", "max_issues_repo_name": "boussaffawalid/FeatureSelection", "max_issues_repo_head_hexsha": "9768a044c0c0dc2c4a2dc0f6e65413d19e92766c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T08:35:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-10T08:57:35.000Z", "max_forks_repo_path": "extern/FST3lib/_src_criteria/classifier_knn.hpp", "max_forks_repo_name": "boussaffawalid/FeatureSelection", "max_forks_repo_head_hexsha": "9768a044c0c0dc2c4a2dc0f6e65413d19e92766c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-04-13T13:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-02-26T08:18:47.000Z", "avg_line_length": 47.5743944637, "max_line_length": 181, "alphanum_fraction": 0.7288530075, "num_tokens": 3624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.29803816461509924}}
{"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 *      Gentry, A., Smyth, D., and Oliver, W. . The Mark IV Supersonic-Hypersonic Arbitrary Body\n *        Program, Volume II - Program Formulation, Douglas Aircraft Aircraft Company, 1973.\n *\n */\n\n#include <string>\n\n#include <boost/bind.hpp>\n#include <functional>\n#include <boost/lambda/lambda.hpp>\n#include <boost/make_shared.hpp>\n#include <boost/pointer_cast.hpp>\n#include <memory>\n\n#include <Eigen/Geometry>\n\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n\n#include \"Tudat/Astrodynamics/Aerodynamics/aerodynamics.h\"\n#include \"Tudat/Astrodynamics/Aerodynamics/hypersonicLocalInclinationAnalysis.h\"\n#include \"Tudat/Mathematics/GeometricShapes/compositeSurfaceGeometry.h\"\n#include \"Tudat/Mathematics/GeometricShapes/surfaceGeometry.h\"\n#include \"Tudat/InputOutput/basicInputOutput.h\"\n\nnamespace tudat\n{\nnamespace aerodynamics\n{\n\nusing Eigen::Vector6d;\nusing mathematical_constants::PI;\n\nusing namespace geometric_shapes;\n\n//! Returns default values of mach number for use in HypersonicLocalInclinationAnalysis.\nstd::vector< double > getDefaultHypersonicLocalInclinationMachPoints(\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\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\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 HypersonicLocalInclinationAnalysis.\nstd::vector< double > getDefaultHypersonicLocalInclinationAngleOfAttackPoints( )\n{\n    std::vector< double > angleOfAttackPoints;\n\n    // Set number of data points and allocate memory.\n    angleOfAttackPoints.resize( 11 );\n\n    // Set default values, 0 to 40 degrees, with steps of 5 degrees.\n    for ( int i = 0; i < 11; i++ )\n    {\n        angleOfAttackPoints[ i ] =\n                ( static_cast< double >( i ) * 5.0 * PI / 180.0 );\n    }\n    return angleOfAttackPoints;\n}\n\n//! Returns default values of angle of sideslip for use in HypersonicLocalInclinationAnalysis.\nstd::vector< double > getDefaultHypersonicLocalInclinationAngleOfSideslipPoints( )\n{\n    std::vector< double > angleOfSideslipPoints;\n\n    // Set number of data points and allocate memory.\n    angleOfSideslipPoints.resize( 2 );\n\n    // Set default values, 0 and 1 degrees.\n    angleOfSideslipPoints[ 0 ] = 0.0;\n    angleOfSideslipPoints[ 1 ] = 1.0 * PI / 180.0;\n\n    return angleOfSideslipPoints;\n}\n\n//! Function that saves the vehicle mesh data used for a HypersonicLocalInclinationAnalysis to a file\nvoid saveVehicleMeshToFile(\n        const std::shared_ptr< HypersonicLocalInclinationAnalysis > localInclinationAnalysis,\n        const std::string directory,\n        const std::string filePrefix )\n{\n    std::vector< boost::multi_array< Eigen::Vector3d, 2 > > meshPoints =\n            localInclinationAnalysis->getMeshPoints( );\n    std::vector< boost::multi_array< Eigen::Vector3d, 2 > > meshSurfaceNormals =\n            localInclinationAnalysis->getPanelSurfaceNormals( );\n\n\n//    boost::array< int, 3 > independentVariables;\n//    independentVariables[ 0 ] = 0;\n//    independentVariables[ 1 ] = 6;\n//    independentVariables[ 2 ] = 0;\n\n//    std::vector< std::vector< std::vector< double > > > pressureCoefficients =\n//            localInclinationAnalysis->getPressureCoefficientList( independentVariables );\n\n    int counter = 0;\n    std::map< int, Eigen::Vector3d > meshPointsList;\n    std::map< int, Eigen::Vector3d > surfaceNormalsList;\n//    std::map< int, Eigen::Vector1d > pressureCoefficientsList;\n\n    for( unsigned int i = 0; i < meshPoints.size( ); i++ )\n    {\n        for( unsigned int j = 0; j < meshPoints.at( i ).shape( )[ 0 ] - 1; j++ )\n        {\n            for( unsigned int k = 0; k < meshPoints.at( i ).shape( )[ 1 ] - 1; k++ )\n            {\n                meshPointsList[ counter ] = meshPoints[ i ][ j ][ k ];\n                surfaceNormalsList[ counter ] = meshSurfaceNormals[ i ][ j ][ k ];\n//                pressureCoefficientsList[ counter ] = ( Eigen::Vector1d( ) << pressureCoefficients[ i ][ j ][ k ] ).finished( );\n                counter++;\n            }\n        }\n    }\n\n    input_output::writeDataMapToTextFile(\n                meshPointsList, filePrefix + \"ShapeFile.dat\", directory );\n    input_output::writeDataMapToTextFile(\n                surfaceNormalsList, filePrefix + \"SurfaceNormalFile.dat\", directory );\n\n//    input_output::writeDataMapToTextFile(\n//                pressureCoefficientsList, filePrefix + \"pressureCoefficientFile.dat\", directory );\n}\n\n\n//! Default constructor.\nHypersonicLocalInclinationAnalysis::HypersonicLocalInclinationAnalysis(\n        const std::vector< std::vector< double > >& dataPointsOfIndependentVariables,\n        const std::shared_ptr< SurfaceGeometry > inputVehicleSurface,\n        const std::vector< int >& numberOfLines,\n        const std::vector< int >& numberOfPoints,\n        const std::vector< bool >& invertOrders,\n        const std::vector< std::vector< int > >& selectedMethods,\n        const double referenceArea,\n        const double referenceLength,\n        const Eigen::Vector3d& momentReferencePoint,\n        const bool savePressureCoefficients )\n    : AerodynamicCoefficientGenerator< 3, 6 >(\n          dataPointsOfIndependentVariables, referenceLength, referenceArea, referenceLength,\n          momentReferencePoint, { mach_number_dependent, angle_of_attack_dependent, angle_of_sideslip_dependent },true, false ),\n      stagnationPressureCoefficient( 2.0 ),\n      ratioOfSpecificHeats( 1.4 ),\n      selectedMethods_( selectedMethods ),\n      savePressureCoefficients_( savePressureCoefficients )\n{\n    // Set geometry if it is a single surface.\n    if ( std::dynamic_pointer_cast< SingleSurfaceGeometry > ( inputVehicleSurface ) !=\n         std::shared_ptr< SingleSurfaceGeometry >( ) )\n    {\n        // Set number of geometries and allocate memory.\n        vehicleParts_.resize( 1 );\n\n        vehicleParts_[ 0 ] = std::make_shared< LawgsPartGeometry >( );\n        vehicleParts_[ 0 ]->setReversalOperator( invertOrders[ 0 ] );\n\n        // If part is not already a LaWGS part, convert it.\n        if ( std::dynamic_pointer_cast< LawgsPartGeometry >\n             ( inputVehicleSurface ) ==\n             std::shared_ptr< LawgsPartGeometry >( ) )\n        {\n            // Convert geometry to LaWGS surface mesh and set in vehicleParts_ list.\n            vehicleParts_[ 0 ]->setMesh(\n                        std::dynamic_pointer_cast< SingleSurfaceGeometry > ( inputVehicleSurface ),\n                        numberOfLines[ 0 ], numberOfPoints[ 0 ] );\n        }\n\n        // Else, set geometry directly.\n        else\n        {\n            vehicleParts_[ 0 ] = std::dynamic_pointer_cast< LawgsPartGeometry >\n                    ( inputVehicleSurface );\n        }\n    }\n\n    // Set geometry if it is a composite surface.\n    else if ( std::dynamic_pointer_cast< CompositeSurfaceGeometry >( inputVehicleSurface ) !=\n              std::shared_ptr< CompositeSurfaceGeometry >( ) )\n    {\n        // Dynamic cast to composite surface geometry for further processing.\n        std::shared_ptr< CompositeSurfaceGeometry > compositeSurfaceGeometry_ =\n                std::dynamic_pointer_cast< CompositeSurfaceGeometry >( inputVehicleSurface );\n\n        // Set number of geometries and allocate memory.\n        int numberOfVehicleParts =\n                compositeSurfaceGeometry_->getNumberOfSingleSurfaceGeometries( );\n        vehicleParts_.resize( numberOfVehicleParts );\n\n        // Iterate through all parts and set them in vehicleParts_ list.\n        for ( int i = 0; i < numberOfVehicleParts; i++ )\n        {\n            // If part is not already a LaWGS part, convert it.\n            if ( std::dynamic_pointer_cast< LawgsPartGeometry >\n                 ( compositeSurfaceGeometry_->getSingleSurfaceGeometry( i ) ) ==\n                 std::shared_ptr< LawgsPartGeometry >( ) )\n            {\n                vehicleParts_[ i ] = std::make_shared< LawgsPartGeometry >( );\n                vehicleParts_[ i ]->setReversalOperator( invertOrders[ i ] );\n\n                // Convert geometry to LaWGS and set in list.\n                vehicleParts_[ i ]->setMesh(\n                            compositeSurfaceGeometry_->getSingleSurfaceGeometry( i ),\n                            numberOfLines[ i ], numberOfPoints[ i ] );\n            }\n\n            // Else, set geometry directly.\n            else\n            {\n                vehicleParts_[ i ] = std::dynamic_pointer_cast< LawgsPartGeometry >(\n                            compositeSurfaceGeometry_->getSingleSurfaceGeometry( i ) );\n            }\n        }\n    }\n\n    // Allocate memory for panel inclinations and pressureCoefficient_.\n    inclination_.resize( vehicleParts_.size( ) );\n    pressureCoefficient_.resize( vehicleParts_.size( ) );\n    for ( unsigned int i = 0 ; i < vehicleParts_.size( ); i++ )\n    {\n        inclination_[ i ].resize( vehicleParts_[ i ]->getNumberOfLines( ) );\n        pressureCoefficient_[ i ].resize( vehicleParts_[ i ]->getNumberOfLines( ) );\n        for ( int j = 0 ; j < vehicleParts_[ i ]->getNumberOfLines( ) ; j++ )\n        {\n            inclination_[ i ][ j ].resize( vehicleParts_[ i ]->getNumberOfPoints( ) );\n            pressureCoefficient_[ i ][ j ].resize( vehicleParts_[ i ]->getNumberOfPoints( ) );\n        }\n    }\n\n    boost::array< int, 3 > numberOfPointsPerIndependentVariables;\n    for( int i = 0; i < 3; i++ )\n    {\n        numberOfPointsPerIndependentVariables[ i ] =\n                dataPointsOfIndependentVariables_[ i ].size( );\n    }\n\n    isCoefficientGenerated_.resize( numberOfPointsPerIndependentVariables );\n\n    std::fill( isCoefficientGenerated_.origin( ),\n               isCoefficientGenerated_.origin( ) + isCoefficientGenerated_.num_elements( ), 0 );\n\n    generateCoefficients( );\n    createInterpolator( );\n}\n\n//! Get aerodynamic coefficients.\nVector6d HypersonicLocalInclinationAnalysis::getAerodynamicCoefficientsDataPoint(\n        const boost::array< int, 3 > independentVariables )\n{\n    if( isCoefficientGenerated_( independentVariables ) == 0 )\n    {\n        determineVehicleCoefficients( independentVariables );\n    }\n\n    // Return requested coefficients.\n    return aerodynamicCoefficients_( independentVariables );\n}\n\n//! Generate aerodynamic database.\nvoid HypersonicLocalInclinationAnalysis::generateCoefficients( )\n{\n    // Allocate variable to pass to coefficient determination for independent\n    // variable indices.\n    boost::array< int, 3 > independentVariableIndices;\n\n    // Iterate over all combinations of independent variables.\n    for ( unsigned int i = 0 ; i < dataPointsOfIndependentVariables_[ 0 ].size( ) ; i++ )\n    {\n        independentVariableIndices[ 0 ] = i;\n        for ( unsigned  int j = 0 ; j < dataPointsOfIndependentVariables_[\n              1 ].size( ) ; j++ )\n        {\n            independentVariableIndices[ 1 ] = j;\n            for ( unsigned  int k = 0 ; k < dataPointsOfIndependentVariables_[\n                  2 ].size( ) ; k++ )\n            {\n                independentVariableIndices[ 2 ] = k;\n\n                determineVehicleCoefficients( independentVariableIndices );\n            }\n        }\n    }\n}\n\n//! Generate aerodynamic coefficients at a single set of independent variables.\nvoid HypersonicLocalInclinationAnalysis::determineVehicleCoefficients(\n        const boost::array< int, 3 > independentVariableIndices )\n{\n    // Declare coefficients vector and initialize to zeros.\n    Vector6d coefficients = Vector6d::Zero( );\n\n    // Loop over all vehicle parts, calculate aerodynamic coefficients and add\n    // to aerodynamicCoefficients_.\n    for ( unsigned int i = 0 ; i < vehicleParts_.size( ) ; i++ )\n    {\n        coefficients += determinePartCoefficients( i, independentVariableIndices );\n    }\n\n    if( savePressureCoefficients_ )\n    {\n        pressureCoefficientList_[ independentVariableIndices ] = pressureCoefficient_;\n    }\n\n    aerodynamicCoefficients_( independentVariableIndices ) = coefficients;\n    isCoefficientGenerated_( independentVariableIndices ) = 1;\n}\n\n//! Determine aerodynamic coefficients of a single vehicle part.\nVector6d HypersonicLocalInclinationAnalysis::determinePartCoefficients(\n        const int partNumber, const boost::array< int, 3 > independentVariableIndices )\n{\n    // Declare and determine angles of attack and sideslip for analysis.\n    double angleOfAttack =  dataPointsOfIndependentVariables_[ 1 ]\n            [ independentVariableIndices[ 1 ] ];\n\n    double angleOfSideslip =  dataPointsOfIndependentVariables_[ 2 ]\n            [ independentVariableIndices[ 2 ] ];\n\n    // Declare partCoefficient vector.\n    Vector6d partCoefficients = Vector6d::Zero( );\n\n    // Check whether the inclinations of the vehicle part have already been computed.\n    if ( previouslyComputedInclinations_.count( std::pair< double, double >(\n                                                    angleOfAttack, angleOfSideslip ) ) == 0 )\n    {\n        // Determine panel inclinations for part.\n        determineInclinations( angleOfAttack, angleOfSideslip );\n\n        // Add panel inclinations to container\n        previouslyComputedInclinations_[ std::pair< double, double >(\n                    angleOfAttack, angleOfSideslip ) ] = inclination_;\n    }\n\n    else\n    {\n        // Fetch inclinations from container\n        inclination_ = previouslyComputedInclinations_[ std::pair< double, double >(\n                    angleOfAttack, angleOfSideslip ) ];\n    }\n\n    // Set pressureCoefficient_ array for given independent variables.\n    determinePressureCoefficients( partNumber, independentVariableIndices );\n\n    // Calculate force coefficients from pressure coefficients.\n    partCoefficients.segment( 0, 3 ) = calculateForceCoefficients( partNumber );\n\n    // Calculate moment coefficients from pressure coefficients.\n    partCoefficients.segment( 3, 3 ) = calculateMomentCoefficients( partNumber );\n\n    return partCoefficients;\n}\n\n//! Determine the pressure coefficients on a single vehicle part.\nvoid HypersonicLocalInclinationAnalysis::determinePressureCoefficients(\n        const int partNumber, const boost::array< int, 3 > independentVariableIndices )\n{\n    // Retrieve Mach number.\n    double machNumber = dataPointsOfIndependentVariables_[ 0 ]\n            [ independentVariableIndices[ 0 ] ];\n\n    // Determine stagnation point pressure coefficients. Value is computed once\n    // here to prevent its calculation in inner loop.\n    stagnationPressureCoefficient = computeStagnationPressure(\n                machNumber, ratioOfSpecificHeats );\n\n    updateCompressionPressures( machNumber, partNumber );\n    updateExpansionPressures( machNumber, partNumber );\n}\n\n//! Determine force coefficients from pressure coefficients.\nEigen::Vector3d HypersonicLocalInclinationAnalysis::calculateForceCoefficients(\n        const int partNumber )\n{\n    // Declare force coefficient vector and intialize to zeros.\n    Eigen::Vector3d forceCoefficients = Eigen::Vector3d::Zero( );\n\n    // Loop over all panels and add pressures, scaled by panel area, to force\n    // coefficients.\n    for ( int i = 0 ; i < vehicleParts_[ partNumber ]->getNumberOfLines( ) - 1 ; i++ )\n    {\n        for ( int j = 0 ; j < vehicleParts_[ partNumber ]->getNumberOfPoints( ) - 1 ; j++)\n        {\n            forceCoefficients -=\n                    pressureCoefficient_[ partNumber ][ i ][ j ] *\n                    vehicleParts_[ partNumber ]->getPanelArea( i, j ) *\n                    vehicleParts_[ partNumber ]->getPanelSurfaceNormal( i, j );\n        }\n    }\n\n    // Normalize result by reference area.\n    forceCoefficients /= referenceArea_;\n\n    return forceCoefficients;\n}\n\n//! Determine moment coefficients from pressure coefficients.\nEigen::Vector3d HypersonicLocalInclinationAnalysis::calculateMomentCoefficients(\n        const int partNumber )\n{\n    // Declare moment coefficient vector and intialize to zeros.\n    Eigen::Vector3d momentCoefficients = Eigen::Vector3d::Zero( );\n\n    // Declare moment arm for panel moment determination.\n    Eigen::Vector3d referenceDistance;\n\n    // Loop over all panels and add moments due pressures.\n    for ( int i = 0 ; i < vehicleParts_[ partNumber ]->getNumberOfLines( ) - 1 ; i++ )\n    {\n        for ( int j = 0 ; j < vehicleParts_[ partNumber ]->getNumberOfPoints( ) - 1 ; j++ )\n        {\n            // Determine moment arm for given panel centroid.\n            referenceDistance = ( vehicleParts_[ partNumber ]->getPanelCentroid( i, j ) -\n                                  momentReferencePoint_ );\n\n            momentCoefficients -=\n                    pressureCoefficient_[ partNumber ][ i ][ j ] *\n                    vehicleParts_[ partNumber ]->getPanelArea( i, j ) *\n                    ( referenceDistance.cross( vehicleParts_[ partNumber ]->\n                                               getPanelSurfaceNormal( i, j ) ) );\n        }\n    }\n\n    // Scale result by reference length and area.\n    momentCoefficients /= ( referenceLength_ * referenceArea_ );\n\n    return momentCoefficients;\n}\n\n//! Determines the inclination angle of panels on a single part.\nvoid HypersonicLocalInclinationAnalysis::determineInclinations( const double angleOfAttack,\n                                                                const double angleOfSideslip )\n{\n    // Declare free-stream velocity vector.\n    Eigen::Vector3d freestreamVelocityDirection;\n\n    // Set freestream velocity vector in body frame.\n    double freestreamVelocityDirectionX = cos( angleOfAttack )* cos( angleOfSideslip );\n    double freestreamVelocityDirectionY = sin( angleOfSideslip );\n    double freestreamVelocityDirectionZ = sin( angleOfAttack ) * cos( angleOfSideslip );\n    freestreamVelocityDirection( 0 ) = freestreamVelocityDirectionX;\n    freestreamVelocityDirection( 1 ) = freestreamVelocityDirectionY;\n    freestreamVelocityDirection( 2 ) = freestreamVelocityDirectionZ;\n\n    // Declare cosine of inclination angle.\n    double cosineOfInclination;\n\n    // Loop over all panels of given vehicle part and set inclination angles.\n    for( unsigned int k = 0; k < vehicleParts_.size( ); k++ )\n    {\n        for ( int i = 0 ; i < vehicleParts_[ k ]->getNumberOfLines( ) - 1 ; i++ )\n        {\n            for ( int j = 0 ; j < vehicleParts_[ k ]->getNumberOfPoints( ) - 1 ; j++ )\n            {\n\n                // Determine cosine of inclination angle from inner product between\n                // surface normal and free-stream direction.\n                cosineOfInclination = vehicleParts_[ k ]->\n                        getPanelSurfaceNormal( i, j ).\n                        dot( freestreamVelocityDirection );\n\n                // Set inclination angle.\n                inclination_[ k ][ i ][ j ] = PI / 2.0 - acos( cosineOfInclination );\n            }\n        }\n    }\n}\n\n//! Determine compression pressure coefficients on all parts.\nvoid HypersonicLocalInclinationAnalysis::updateCompressionPressures( const double machNumber,\n                                                                     const int partNumber )\n{\n    int method = selectedMethods_[ 0 ][ partNumber ];\n\n    std::function< double( double ) > pressureFunction;\n\n    // Switch to analyze part using correct method.\n    switch( method )\n    {\n    case 0:\n        pressureFunction =\n                std::bind( aerodynamics::computeNewtonianPressureCoefficient, std::placeholders::_1 );\n        break;\n\n    case 1:\n        pressureFunction =\n                std::bind( aerodynamics::computeModifiedNewtonianPressureCoefficient, std::placeholders::_1,\n                           stagnationPressureCoefficient );\n        break;\n\n    case 2:\n        // Method currently disabled.\n        break;\n\n    case 3:\n        // Method currently disabled.\n        break;\n\n    case 4:\n        pressureFunction =\n                std::bind( aerodynamics::computeEmpiricalTangentWedgePressureCoefficient, std::placeholders::_1,\n                           machNumber );\n        break;\n\n    case 5:\n        pressureFunction =\n                std::bind( aerodynamics::computeEmpiricalTangentConePressureCoefficient, std::placeholders::_1,\n                           machNumber );\n        break;\n\n    case 6:\n        pressureFunction =\n                std::bind( aerodynamics::computeModifiedDahlemBuckPressureCoefficient, std::placeholders::_1,\n                           machNumber );\n        break;\n\n    case 7:\n        pressureFunction =\n                std::bind( aerodynamics::computeVanDykeUnifiedPressureCoefficient, std::placeholders::_1,\n                           machNumber, ratioOfSpecificHeats, 1 );\n        break;\n\n    case 8:\n        pressureFunction =\n                std::bind( aerodynamics::computeSmythDeltaWingPressureCoefficient, std::placeholders::_1,\n                           machNumber );\n        break;\n\n    case 9:\n        pressureFunction =\n                std::bind( aerodynamics::computeHankeyFlatSurfacePressureCoefficient, std::placeholders::_1,\n                           machNumber );\n        break;\n\n    default:\n        break;\n    }\n\n    for ( int i = 0 ; i < vehicleParts_[ partNumber ]->getNumberOfLines( ) - 1; i++ )\n    {\n        for ( int j = 0 ; j < vehicleParts_[ partNumber ]->getNumberOfPoints( ) - 1 ; j++ )\n        {\n            if ( inclination_[ partNumber ][ i ][ j ] > 0 )\n            {\n                // If panel inclination is positive, calculate pressure coefficient.\n                pressureCoefficient_[ partNumber ][ i ][ j ] =\n                        pressureFunction( inclination_[ partNumber ][ i ][ j ] );\n            }\n        }\n    }\n}\n\n//! Determines expansion pressure coefficients on all parts.\nvoid HypersonicLocalInclinationAnalysis::updateExpansionPressures( const double machNumber,\n                                                                   const int partNumber )\n{\n    // Get analysis method of part to analyze.\n    int method = selectedMethods_[ 1 ][ partNumber ];\n\n    if ( method == 0 || method == 1 || method == 4 )\n    {\n        std::function< double( ) > pressureFunction;\n        switch( method )\n        {\n        case 0:\n            pressureFunction = std::bind( &aerodynamics::computeVacuumPressureCoefficient,\n                                          machNumber, ratioOfSpecificHeats );\n            break;\n\n        case 1:\n            pressureFunction = [ ]( ){ return 0.0; };\n            break;\n\n        case 4:\n            pressureFunction = std::bind( &aerodynamics::computeHighMachBasePressure,\n                                          machNumber );\n            break;\n\n        }\n\n        // Iterate over all panels on part.\n        for ( int i = 0 ; i < vehicleParts_[ partNumber ]->getNumberOfLines( ) - 1 ; i++ )\n        {\n            for ( int j = 0 ; j < vehicleParts_[ partNumber ]->getNumberOfPoints( ) - 1 ; j++ )\n            {\n                if ( inclination_[ partNumber ][ i ][ j ] <= 0 )\n                {\n                    // If panel inclination is negative, calculate pressure using\n                    // Van Dyke unified method.\n                    pressureCoefficient_[ partNumber ][ i ][ j ] =\n                            pressureFunction( );\n                }\n            }\n        }\n    }\n\n    else if( method == 3 || method == 5 || method == 6 )\n    {\n\n        std::function< double( double ) > pressureFunction;\n\n        // Declare local variable.\n        double freestreamPrandtlMeyerFunction;\n\n        // Switch to analyze part using correct method.\n        switch( method )\n        {\n        case 3:\n            // Calculate freestream Prandtl-Meyer function.\n            freestreamPrandtlMeyerFunction = aerodynamics::computePrandtlMeyerFunction(\n                        machNumber, ratioOfSpecificHeats );\n            pressureFunction =\n                    std::bind( &aerodynamics::computePrandtlMeyerFreestreamPressureCoefficient,\n                               std::placeholders::_1, machNumber, ratioOfSpecificHeats,\n                               freestreamPrandtlMeyerFunction );\n            break;\n\n        case 5:\n            pressureFunction =\n                    std::bind( &aerodynamics::computePrandtlMeyerFreestreamPressureCoefficient,\n                               std::placeholders::_1, machNumber, ratioOfSpecificHeats, -1 );\n            break;\n\n        case 6:\n            pressureFunction = std::bind( &aerodynamics::computeAcmEmpiricalPressureCoefficient,\n                                          std::placeholders::_1, machNumber );\n            break;\n        }\n\n        // Iterate over all panels on part.\n        for ( int i = 0 ; i < vehicleParts_[ partNumber ]->getNumberOfLines( ) - 1 ; i++ )\n        {\n            for ( int j = 0 ; j < vehicleParts_[ partNumber ]->getNumberOfPoints( ) - 1 ; j++ )\n            {\n                if ( inclination_[ partNumber ][ i ][ j ] <= 0 )\n                {\n                    // If panel inclination is negative, calculate pressure using\n                    // Van Dyke unified method.\n                    pressureCoefficient_[ partNumber ][ i ][ j ] =\n                            pressureFunction( inclination_[ partNumber ][ i ][ j ] );\n                }\n            }\n        }\n    }\n\n    else\n    {\n        std::string errorMessage = \"Error, expansion local inclination method number \"\n                + std::to_string( method ) + \" not recognized\";\n        throw std::runtime_error( errorMessage );\n    }\n}\n\n} // namespace aerodynamics\n} // namespace tudat\n", "meta": {"hexsha": "d12ee7a8e7ad4c2d60296cb1e5ac820f3697e543", "size": 26598, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Aerodynamics/hypersonicLocalInclinationAnalysis.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/hypersonicLocalInclinationAnalysis.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/hypersonicLocalInclinationAnalysis.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": 38.2705035971, "max_line_length": 130, "alphanum_fraction": 0.6214377021, "num_tokens": 5984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.29800205420655446}}
{"text": "/*\n   For more information, please see: http://software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2020 Scientific Computing and Imaging Institute,\n   University of Utah.\n\n   Permission is hereby granted, free of charge, to any person obtaining a\n   copy of this software and associated documentation files (the \"Software\"),\n   to deal in the Software without restriction, including without limitation\n   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n   and/or sell copies of the Software, and to permit persons to whom the\n   Software is furnished to do so, subject to the following conditions:\n\n   The above copyright notice and this permission notice shall be included\n   in all copies or substantial portions of the Software.\n\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n   DEALINGS IN THE SOFTWARE.\n\n\t Author: \t\t\t\t\t\t\tJaume Coll-Font\n\t Last Modification:\t\tSeptember 6 2017\n*/\n\n\n#include <boost/bind.hpp>\n#include <boost/lexical_cast.hpp>\n\n// Tikhonov specific headers\n#include <Core/Algorithms/Legacy/Inverse/TikhonovAlgoAbstractBase.h>\n#include <Core/Algorithms/Legacy/Inverse/TikhonovImpl.h>\n#include <Core/Algorithms/Legacy/Inverse/SolveInverseProblemWithStandardTikhonovImpl.h>\n#include <Core/Algorithms/Legacy/Inverse/SolveInverseProblemWithTikhonovSVD_impl.h>\n#include <Core/Algorithms/Legacy/Inverse/SolveInverseProblemWithTSVD_impl.h>\n\n// Datatypes\n#include <Core/Datatypes/Matrix.h>\n#include <Core/Datatypes/DenseMatrix.h>\n#include <Core/Datatypes/DenseColumnMatrix.h>\n#include <Core/Datatypes/SparseRowMatrix.h>\n#include <Core/Datatypes/MatrixTypeConversions.h>\n#include <Core/Math/MiscMath.h>\n#include <unsupported/Eigen/Splines>\n\n// SCIRun structural\n#include <Core/Algorithms/Base/AlgorithmPreconditions.h>\n#include <Core/Algorithms/Base/AlgorithmVariableNames.h>\n#include <Core/Logging/LoggerInterface.h>\n#include <Core/Logging/Log.h>\n#include <Core/Utils/Exception.h>\n\nusing namespace SCIRun;\nusing namespace SCIRun::Core;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Logging;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core::Algorithms::Inverse;\n\n// shared inputs\nconst AlgorithmInputName TikhonovAlgoAbstractBase::ForwardMatrix(\"ForwardMatrix\");\nconst AlgorithmInputName TikhonovAlgoAbstractBase::MeasuredPotentials(\"MeasuredPotentials\");\nconst AlgorithmInputName TikhonovAlgoAbstractBase::WeightingInSourceSpace(\"WeightingInSourceSpace\");\nconst AlgorithmInputName TikhonovAlgoAbstractBase::WeightingInSensorSpace(\"WeightingInSensorSpace\");\n\n// Inputs specific from the Tikhonov SVD module\nconst AlgorithmInputName TikhonovAlgoAbstractBase::matrixU(\"matrixU\");\nconst AlgorithmInputName TikhonovAlgoAbstractBase::singularValues(\"singularValues\");\nconst AlgorithmInputName TikhonovAlgoAbstractBase::matrixV(\"matrixV\");\n\n// outputs\nconst AlgorithmOutputName TikhonovAlgoAbstractBase::InverseSolution(\"InverseSolution\");\nconst AlgorithmOutputName TikhonovAlgoAbstractBase::RegularizationParameter(\"RegularizationParameter\");\nconst AlgorithmOutputName TikhonovAlgoAbstractBase::LambdaArray(\"LambdaArray\");\nconst AlgorithmOutputName TikhonovAlgoAbstractBase::Lambda_Index(\"Lambda_Index\");\nconst AlgorithmOutputName TikhonovAlgoAbstractBase::RegInverse(\"RegInverse\");\n\nALGORITHM_PARAMETER_DEF( Inverse, TikhonovImplementation);\nALGORITHM_PARAMETER_DEF( Inverse, RegularizationMethod);\nALGORITHM_PARAMETER_DEF( Inverse, regularizationChoice);\nALGORITHM_PARAMETER_DEF( Inverse, LambdaFromDirectEntry);\nALGORITHM_PARAMETER_DEF( Inverse, LambdaMin);\nALGORITHM_PARAMETER_DEF( Inverse, LambdaMax);\nALGORITHM_PARAMETER_DEF( Inverse, LambdaNum);\nALGORITHM_PARAMETER_DEF( Inverse, LambdaResolution);\nALGORITHM_PARAMETER_DEF( Inverse, LambdaSliderValue);\n//ALGORITHM_PARAMETER_DEF( Inverse, LambdaCorner);\n//ALGORITHM_PARAMETER_DEF( Inverse, LCurveText);\nALGORITHM_PARAMETER_DEF( Inverse, regularizationSolutionSubcase);\nALGORITHM_PARAMETER_DEF( Inverse, regularizationResidualSubcase);\n\nTikhonovAlgoAbstractBase::TikhonovAlgoAbstractBase()\n{\n\taddParameter(Parameters::TikhonovImplementation, std::string(\"NoMethodSelected\") );\n\taddOption(Parameters::RegularizationMethod, \"lcurve\", \"single|slider|lcurve\");\n\taddParameter(Parameters::regularizationChoice, 0);\n\taddParameter(Parameters::LambdaFromDirectEntry,1e-6);\n\taddParameter(Parameters::LambdaMin,1e-6);\n\taddParameter(Parameters::LambdaMax,1);\n\taddParameter(Parameters::LambdaNum,200);\n\taddParameter(Parameters::LambdaResolution,1e-6);\n\taddParameter(Parameters::LambdaSliderValue,0);\n\taddParameter(Parameters::regularizationSolutionSubcase,solution_constrained);\n\taddParameter(Parameters::regularizationResidualSubcase,residual_constrained);\n}\n\n////// CHECK IF INPUT MATRICES HAVE THE CORRECT SIZE\nbool TikhonovAlgoAbstractBase::checkInputMatrixSizes( const AlgorithmInput & input) const\n{\n\tauto forwardMatrix_ = input.get<Matrix>(ForwardMatrix);\n\tauto measuredData_ = input.get<Matrix>(MeasuredPotentials);\n\tauto sourceWeighting_ = input.get<Matrix>(WeightingInSourceSpace);\n\tauto sensorWeighting_ = input.get<Matrix>(WeightingInSensorSpace);\n\n  const int M = forwardMatrix_->nrows();\n  const int N = forwardMatrix_->ncols();\n\n  // check that rows of fwd matrix equal number of measurements\n  if ( M != measuredData_->nrows() )\n  {\n  \tTHROW_ALGORITHM_INPUT_ERROR(\"Input matrix dimensions must agree.\");\n  \treturn false;\n  }\n\n  // check source regularization matrix sizes\n  if (sourceWeighting_)\n  {\n    if( get(Parameters::regularizationSolutionSubcase).toInt()==solution_constrained )\n    {\n      // check that the matrix is of appropriate size (equal number of rows as columns in fwd matrix)\n      if ( N != sourceWeighting_->ncols() )\n      {\n    \t\tTHROW_ALGORITHM_INPUT_ERROR(\"Solution Regularization Matrix must have the same number of rows as columns in the Forward Matrix !\");\n    \t\treturn false;\n      }\n    }\n    // otherwise, if the source regularization is provided as the squared version (RR^T)\n    else if ( get(Parameters::regularizationSolutionSubcase).toInt()==solution_constrained_squared )\n    {\n      // check that the matrix is of appropriate size and squared (equal number of rows as columns in fwd matrix)\n      if ( ( N != sourceWeighting_->nrows() ) || ( N != sourceWeighting_->ncols() ) )\n      {\n        THROW_ALGORITHM_INPUT_ERROR(\"The squared solution Regularization Matrix must have the same number of rows and columns and must be equal to the number of columns in the Forward Matrix !\");\n\t      return false;\n      }\n    }\n  }\n\n  // check measurement regularization matrix sizes\n  if (sensorWeighting_)\n  {\n    if (get(Parameters::regularizationResidualSubcase).toInt() == residual_constrained)\n    {\n      // check that the matrix is of appropriate size (equal number of rows as rows in fwd matrix)\n      if(M != sensorWeighting_->ncols())\n      {\n        THROW_ALGORITHM_INPUT_ERROR(\"Data Residual Weighting Matrix must have the same number of rows as the Forward Matrix !\");\n        return false;\n      }\n    }\n    // otherwise if the source covariance matrix is provided in squared form\n    else if  ( get(Parameters::regularizationResidualSubcase).toInt() == residual_constrained_squared )\n    {\n      // check that the matrix is of appropriate size and squared (equal number of rows as rows in fwd matrix)\n      if( (M != sensorWeighting_->nrows()) || (M != sensorWeighting_->ncols()) )\n      {\n        THROW_ALGORITHM_INPUT_ERROR(\"Squared data Residual Weighting Matrix must have the same number of rows and columns as number of rows in the Forward Matrix !\");\n        return false;\n      }\n    }\n  }\n  return true;\n}\n\nAlgorithmOutput TikhonovAlgoAbstractBase::run(const AlgorithmInput & input) const\n{\n\tauto forwardMatrix = castMatrix::toDense(input.get<Matrix>(TikhonovAlgoAbstractBase::ForwardMatrix));\n\tauto measuredData = castMatrix::toDense(input.get<Matrix>(TikhonovAlgoAbstractBase::MeasuredPotentials));\n\tauto sourceWeighting = castMatrix::toDense(input.get<Matrix>(TikhonovAlgoAbstractBase::WeightingInSourceSpace));\n\tauto sensorWeighting = castMatrix::toDense(input.get<Matrix>(TikhonovAlgoAbstractBase::WeightingInSensorSpace));\n\n\tauto RegularizationMethod_gotten = getOption(Parameters::RegularizationMethod);\n\tauto implOption = get(Parameters::TikhonovImplementation).toString();\n\n\t// check input MATRICES\n\tcheckInputMatrixSizes( input );\n\n\t// Determine specific Tikhonov Implementation\n\tstd::shared_ptr<TikhonovImpl> algoImpl;\n\tif (implOption == \"standardTikhonov\")\n  {\n\t\tint regularizationChoice = get(Parameters::regularizationChoice).toInt();\n\t\tint regularizationSolutionSubcase = get(Parameters::regularizationSolutionSubcase).toInt();\n\t\tint regularizationResidualSubcase = get(Parameters::regularizationResidualSubcase).toInt();\n\n\t\talgoImpl = std::make_shared<SolveInverseProblemWithStandardTikhonovImpl>( *forwardMatrix, *measuredData, *sourceWeighting, *sensorWeighting,\n      regularizationChoice, regularizationSolutionSubcase, regularizationResidualSubcase);\n\t}\n\telse if (implOption == \"TikhonovSVD\")\n  {\n\t\t// get TikhonovSVD special inputs\n\t\tauto matrixU = castMatrix::toDense(input.get<Matrix>(TikhonovAlgoAbstractBase::matrixU));\n\t\tauto singularValues = castMatrix::toDense(input.get<Matrix>(TikhonovAlgoAbstractBase::singularValues));\n\t\tauto matrixV = castMatrix::toDense(input.get<Matrix>(TikhonovAlgoAbstractBase::matrixV));\n\n\t\t// If there is a missing matrix from the precomputed SVD input\n\t\tif (!matrixU || !singularValues || !matrixV)\n\t\t\talgoImpl = std::make_shared<SolveInverseProblemWithTikhonovSVD_impl>(*forwardMatrix, *measuredData, *sourceWeighting, *sensorWeighting);\n\t\telse\n\t\t\talgoImpl = std::make_shared<SolveInverseProblemWithTikhonovSVD_impl>(*forwardMatrix, *measuredData, *sourceWeighting, *sensorWeighting, *matrixU, *singularValues, *matrixV);\n\t}\n\telse if (implOption == \"TSVD\")\n  {\n\t\t// get TikhonovSVD special inputs\n\t\tauto matrixU = castMatrix::toDense(input.get<Matrix>(TikhonovAlgoAbstractBase::matrixU));\n\t\tauto singularValues = castMatrix::toDense(input.get<Matrix>(TikhonovAlgoAbstractBase::singularValues));\n\t\tauto matrixV = castMatrix::toDense(input.get<Matrix>(TikhonovAlgoAbstractBase::matrixV));\n\n\t\t// If there is a missing matrix from the precomputed SVD input\n\t\tif (!matrixU || !singularValues || !matrixV)\n\t\t\talgoImpl = std::make_shared<SolveInverseProblemWithTSVD_impl>(*forwardMatrix, *measuredData, *sourceWeighting, *sensorWeighting);\n\t\telse\n\t\t\talgoImpl = std::make_shared<SolveInverseProblemWithTSVD_impl>(*forwardMatrix, *measuredData, *sourceWeighting, *sensorWeighting, *matrixU, *singularValues, *matrixV);\n\t}\n\telse\n  {\n\t\tTHROW_ALGORITHM_PROCESSING_ERROR(\"Not a valid Tikhonov Implementation selection\");\n\t}\n\n  double lambda = 0;\n  int lambda_index = 0;\n  AlgorithmOutput output;\n  DenseMatrixHandle lambdamatrix;\n  //Get Regularization parameter(s) : Lambda\n  if ((RegularizationMethod_gotten == \"single\") || (RegularizationMethod_gotten == \"slider\"))\n  {\n    if (RegularizationMethod_gotten == \"single\")\n    {\n      // Use single fixed lambda value, entered in UI\n      lambda = get(Parameters::LambdaFromDirectEntry).toDouble();\n    }\n    else if (RegularizationMethod_gotten == \"slider\")\n    {\n      // Use single fixed lambda value, select via slider\n      lambda = get(Parameters::LambdaSliderValue).toDouble();\n    }\n    lambdamatrix.reset(new DenseMatrix(1,1,lambda));\n  }\n  else if (RegularizationMethod_gotten == \"lcurve\")\n  {\n    lambda = computeLcurve( *algoImpl, input,  lambdamatrix, lambda_index);\n  }\n\telse\n\t{\n\t\tTHROW_ALGORITHM_PROCESSING_ERROR(\"Lambda selection was never set\");\n\t}\n\n  // compute final inverse solution\n\tauto solution = algoImpl->computeInverseSolution(lambda, true);\n\n\t// Set outputs\n\n\toutput[InverseSolution] = boost::make_shared<DenseMatrix>(solution);\n\toutput[RegularizationParameter] = boost::make_shared<DenseMatrix>(1, 1, lambda);\n  output[LambdaArray] = lambdamatrix;\n  output[Lambda_Index]= boost::make_shared<DenseMatrix>(1, 1, lambda_index);\n\n\treturn output;\n}\n\ndouble TikhonovAlgoAbstractBase::computeLcurve( const SCIRun::Core::Algorithms::Inverse::TikhonovImpl& algoImpl, const AlgorithmInput & input , DenseMatrixHandle& lambdamatrix, int& lambda_index) const\n{\n\t// get inputs\n\tauto forwardMatrix = input.get<Matrix>(TikhonovAlgoAbstractBase::ForwardMatrix);\n\tauto measuredData = input.get<Matrix>(TikhonovAlgoAbstractBase::MeasuredPotentials);\n\tauto sourceWeighting = input.get<Matrix>(TikhonovAlgoAbstractBase::WeightingInSourceSpace);\n\tauto sensorWeighting = input.get<Matrix>(TikhonovAlgoAbstractBase::WeightingInSensorSpace);\n  // define the step size of the lambda vector to be computed  (distance between min and max divided by number of desired lambdas in log scale)\n  const int nLambda = get(Parameters::LambdaNum).toInt();\n\tconst double lambdaMin = get(Parameters::LambdaMin).toDouble();\n\tconst double lambdaMax = get(Parameters::LambdaMax).toDouble();\n\tdouble lambda = 0;\n\n\t// prealocate vector of lambdas and eta and rho\n  std::vector<double> rho(nLambda, 0.0);\n  std::vector<double> eta(nLambda, 0.0);\n\n  lambdamatrix.reset(new DenseMatrix(nLambda,3,0.0));\n\n  auto lambdaArray = algoImpl.computeLambdaArray( lambdaMin, lambdaMax, nLambda );\n\n  DenseMatrix CAx, Rx;\n  DenseMatrix solution;\n\n  lambdaArray[0] = lambdaMin;\n\n  // for all lambdas\n  for (int j = 0; j < nLambda; j++)\n  {\n    solution = algoImpl.computeInverseSolution( lambdaArray[j], false);\n    lambdamatrix->put(j,0,lambdaArray[j]);\n\n    // if using source regularization matrix, apply it to compute Rx (for the eta computations)\n    if (sourceWeighting)\n    {\n      if (solution.nrows() == sourceWeighting->ncols()) // check that regularization matrix and solution match sizes\n      {\n        auto sw = castMatrix::toDense(sourceWeighting);\n        Rx = (*sw) * solution;\n      }\n      else\n      {\n        BOOST_THROW_EXCEPTION(AlgorithmProcessingException() << ErrorMessage(\" Solution weighting matrix unexpectedly does not fit to compute the weighted solution norm. \"));\n      }\n    }\n    else\n      Rx = solution;\n\n    auto forward = castMatrix::toDense(forwardMatrix);\n    auto Ax = (*forward) * solution;\n    auto measured = castMatrix::toDense(measuredData);\n    auto residualSolution = Ax - (*measured);\n\n    // if using source regularization matrix, apply it to compute Rx (for the eta computations)\n    if (sensorWeighting)\n    {\n      auto sw = castMatrix::toDense(sensorWeighting);\n      CAx = (*sw) * residualSolution;\n    }\n    else\n      CAx = residualSolution;\n\n    // compute rho and eta. Using Frobenious norm when using matrices\n    rho[j] = CAx.norm();\n    eta[j] = Rx.norm();\n    lambdamatrix->put(j,1,rho[j]);\n    lambdamatrix->put(j,2,eta[j]);\n  }\n\n  // Find corner in L-curve\n  lambda = FindCorner( rho, eta, lambdaArray, nLambda,lambda_index);\n\n\tLOG_DEBUG(\"Lambda: {}\", lambda);\n  // TODO: update GUI\n\n  return lambda;\n}\n\n///// Find Corner, find the maximal curvature which corresponds to the L-curve corner\ndouble TikhonovAlgoAbstractBase::FindCorner( const std::vector<double>& rho, const std::vector<double>& eta, const std::vector<double>& lambdaArray, const int nLambda, int& lambda_index )\n{\n\n\tDenseColumnMatrix lrho(nLambda);\n\tDenseColumnMatrix leta(nLambda);\n\n\tfor (int i = 0; i < nLambda; i++)\n\t{\n\t\tlrho[i] = std::log10(rho[i]);\n\t\tleta[i] = std::log10(eta[i]);\n\t}\n\n\t// create L-curve\n\tDenseMatrix Gamma( 2, lrho.nrows());\n\tGamma.row(0) = lrho;\n\tGamma.row(1) = leta;//DenseColumnMatrix::LinSpaced(lrho.nrows(),0,1);\n\n\t// fit spline and compute curvature\n\tDenseColumnMatrix kappa = TikhonovAlgoAbstractBase::InterpolateCurvatureWithSplines( Gamma );\n\n\t// select maximum curvature\n\tkappa.maxCoeff(&lambda_index);\n\n  \treturn lambdaArray[lambda_index];\n}\n\nSCIRun::Core::Datatypes::DenseColumnMatrix TikhonovAlgoAbstractBase::InterpolateCurvatureWithSplines( SCIRun::Core::Datatypes::DenseMatrix& samplePoints)\n{\n\n\t// prealoate\n\tint numSamples = samplePoints.ncols();\n\tDenseColumnMatrix kappa = DenseMatrix::Zero( numSamples, 1 );\n\n\t// typedefs needed for the spline\n\ttypedef Eigen::Spline<double,2> Spline2d;\n\ttypedef Spline2d::KnotVectorType KnotVectorType;\n\ttypedef Spline2d::ControlPointVectorType ControlPointVectorType;\n\n\t// fit cubic spline to data points\n\tControlPointVectorType points = samplePoints;\n\tconst Spline2d spline = Eigen::SplineFitting<Spline2d>::Interpolate(points,3);\n\n\t// determine position of samples along the spline curve\n\tKnotVectorType chord_lengths; // knot parameters\n\tEigen::ChordLengths(points, chord_lengths);\n\n\tfor (int i=0; i < numSamples; i++)\n\t{\n\t\t// compute derivatives up to 2nd order\n\t\tauto dpt = spline.derivatives( chord_lengths(i), 2);\n\n\t\t// compute curvature as:\n\t\t//\t\t\tabs( ( ddrho*ddeta - ddrho*deta ) /  sqrt(  ( deta^2 + drho^2  )^2)  )\n\t\tkappa[i] = std::abs( (dpt(0,2) * dpt(1,2) - dpt(0,2) * dpt(1,1)) /  //compute curvature\n\t                       std::sqrt( std::pow(dpt(1,1)*dpt(1,1)+dpt(0,1)*dpt(0,1) , 3.0)) );\n\n\n\t}\n\n\t// return curvature for all points on the Lcurve\n\treturn kappa;\n}\n", "meta": {"hexsha": "607fd7dabb927354aa721eea4e7e3bb17c97ed1d", "size": 17356, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Algorithms/Legacy/Inverse/TikhonovAlgoAbstractBase.cc", "max_stars_repo_name": "Haydelj/SCIRun", "max_stars_repo_head_hexsha": "f7ee04d85349b946224dbff183438663e54b9413", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Core/Algorithms/Legacy/Inverse/TikhonovAlgoAbstractBase.cc", "max_issues_repo_name": "Haydelj/SCIRun", "max_issues_repo_head_hexsha": "f7ee04d85349b946224dbff183438663e54b9413", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Core/Algorithms/Legacy/Inverse/TikhonovAlgoAbstractBase.cc", "max_forks_repo_name": "Haydelj/SCIRun", "max_forks_repo_head_hexsha": "f7ee04d85349b946224dbff183438663e54b9413", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6211031175, "max_line_length": 201, "alphanum_fraction": 0.757605439, "num_tokens": 4426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.29793811256464686}}
{"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\n// 素因数分解\nstd::unordered_map<long long, int> factor(long long n) {\n\tstd::unordered_map<long long, int> factors;\n\t{\n\t\tint i = 0;\n\t\twhile(n % 2 == 0) {\n\t\t\tn /= 2;\n\t\t\ti++;\n\t\t}\n\t\tif(i != 0) {\n\t\t\tfactors[2] = static_cast<long long>(i);\n\t\t}\n\t}\n\tfor(long long i = 3; i * i <= n; i += 2) {\n\t\tint j = 0;\n\t\twhile(n % i == 0) {\n\t\t\tn /= i;\n\t\t\tj++;\n\t\t}\n\t\tif(j != 0) {\n\t\t\tfactors[i] = j;\n\t\t}\n\t}\n\tif(n != 1) {\n\t\tfactors[n] = 1;\n\t}\n\treturn factors;\n}\n\nint main() {\n\tll n;\n\tcin >> n;\n\n\tunordered_map<ll, int> factors;\n\tRANGE(i, 1, n + 1) {\n\t\tauto f = factor(i);\n\t\tEACH(e, f) {\n\t\t\tif(factors[e.first] != 0) {\n\t\t\t\tchmax(factors[e.first], e.second);\n\t\t\t} else {\n\t\t\t\tfactors[e.first] = e.second;\n\t\t\t}\n\t\t}\n\t}\n\n\tll product = 1;\n\tEACH(e, factors) {\n\t\tREP(i, e.second) { product *= e.first; }\n\t}\n\tproduct += 1;\n\n\tcout << product << endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "4f7205c59c0943666bd46f80b2c000cc70cf9b78", "size": 3429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/ARC110/A.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/ARC110/A.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/ARC110/A.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.9085365854, "max_line_length": 76, "alphanum_fraction": 0.6179644211, "num_tokens": 1120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2979363072926219}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_EXPM1_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_EXPM1_HPP_INCLUDED\n#include <boost/simd/function/std.hpp>\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/function/is_nan.hpp>\n#endif\n#include <boost/simd/arch/common/detail/generic/expm1_kernel.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/logeps.hpp>\n#include <boost/simd/detail/constant/maxlog.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/function/std.hpp>\n#include <boost/simd/function/is_greater.hpp>\n#include <boost/simd/function/is_less.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/simd/detail/dispatch/meta/scalar_of.hpp>\n#include <boost/config.hpp>\n#include <cmath>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD ( expm1_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (A0 a0) const BOOST_NOEXCEPT\n    {\n      using sA0 = bd::scalar_of_t<A0>;\n    #ifndef BOOST_SIMD_NO_INVALIDS\n      if(is_nan(a0)) return Nan<A0>();\n    #endif\n      if((a0 < Logeps<A0>())) return Mone<A0>();\n      if((a0 > Maxlog<A0>())) return  Inf<A0>();\n      return detail::expm1_kernel<A0, sA0>::expm1(a0);\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( expm1_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::std_tag\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const std_tag &, A0 a0) const BOOST_NOEXCEPT\n    {\n      return std::expm1(a0);\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "4722d52ff4a4a290e86c995ae2e2433bbc9f9752", "size": 2281, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/expm1.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/arch/common/scalar/function/expm1.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/scalar/function/expm1.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 33.0579710145, "max_line_length": 100, "alphanum_fraction": 0.5808855765, "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2978326219727093}}
{"text": "//---------------------------------//\n//  This file is part of MuJoCo    //\n//  Written by Emo Todorov         //\n//  Copyright (C) 2017 Roboti LLC  //\n//---------------------------------//\n\n\n#include \"mujoco.h\"\n#include <stdlib.h>\n#include <stdio.h>\n#include <string>\n#include <chrono>\n#include <math.h> \n#include <time.h>\n#include <Eigen/Geometry>\n\nusing namespace std;\nusing namespace Eigen;\n//-------------------------------- macro variables --------------------------------------\n\n// model selection: PENDULUM CARTPOLE CART2POLE CART3POLE SWIMMER3 SWIMMER6 FISH\n#define FISH\n#define CTRL_LIMITTED false\n#define STATE_LINEAR false\n#define LOCAL true\n#define PI 3.141592653\n\n//-------------------------------- global variables -------------------------------------\n\n// user customized parameters\n#if defined(SWIMMER6)\nconst mjtNum t_step = 0.006;\nconst mjtNum cal_step = 0.006;\nconst mjtNum ptb_coef = 0.005;\nconst int step_max = 1500;\nconst int32_t roll_max = 1400;\nconst char* mname = \"swimmer6.xml\";\nconst int ctrl_num = 5;\nconst int NS = 16;\nmjtNum state_nominal[step_max + 1][NS] = { 0 };\n#elif defined(SWIMMER3)\nconst mjtNum t_step = 0.005;//0.01\nconst mjtNum cal_step = 0.005;\nconst mjtNum ptb_coef = 0.008;\nconst int step_max = 1600;//800\nconst int32_t roll_max = 1200;\nconst char* mname = \"swimmer3.xml\";\nconst int ctrl_num = 2;\nconst int NS = 10;\nmjtNum state_nominal[step_max + 1][NS] = { 0 };\n#elif defined(FISH)\nconst mjtNum t_step = 0.001;\nconst mjtNum cal_step = 0.001;\nconst mjtNum ptb_coef = 0.005;\nconst int step_max = 7000;//16000\nconst int roll_max = 1600;\nconst char* mname = \"fish.xml\";\nconst int ctrl_num = 5;\nconst int NS = 26;\nmjtNum state_nominal[step_max + 1][NS] = { 0.0, 0.0, 0, 0, 0, 0, 1, 0, 0 };\n#elif defined(CART2POLE)\nconst mjtNum t_step = 0.05;\nconst int32_t roll_max = 20000; //2w\nconst char* mname = \"cart2pole.xml\";\nconst int step_max = 120;\nconst int ctrl_num = 1;\nconst int NS = 6;\nmjtNum ptb_coef = 0.04;\nmjtNum state_nominal[step_max + 1][NS] = { 0 };\n#elif defined(CART7POLE)\nconst mjtNum t_step = 0.1;\nconst mjtNum ptb_coef = 1;\nconst int step_max = 100;\nconst int32_t roll_max = 20000;\nconst char* mname = \"cart7pole.xml\";\nconst int ctrl_num = 1;\nconst int NS = 16;\nmjtNum state_nominal[step_max + 1][NS] = { 0 };\n#elif defined(CART3POLE)\nconst mjtNum t_step = 0.05;\nconst mjtNum ptb_coef = 0;\nconst int step_max = 140;\nconst int32_t roll_max = 20000;\nconst char* mname = \"cart3pole.xml\";\nconst int ctrl_num = 1;\nconst int NS = 8;\nmjtNum state_nominal[step_max + 1][NS] = { 0 };\n#elif defined(ACROBOT)\nconst mjtNum t_step = 0.01;\nconst mjtNum ptb_coef = 0.02;\nconst int step_max = 700;\nconst int32_t roll_max = 20000;\nconst char* mname = \"acrobot.xml\";\nconst int ctrl_num = 1;\nconst int NS = 4;\nmjtNum state_nominal[step_max + 1][NS] = { -PI, 0, 0, 0 };\n#elif defined(PENDULUM)\nconst mjtNum t_step = 0.1;\nconst mjtNum cal_step = 0.1;\nmjtNum ptb_coef = 0.005;\nconst int step_max = 30;\nconst int32_t roll_max = 500;\nconst char* mname = \"pendulum.xml\";\nconst int ctrl_num = 1;\nconst int NS = 2;\nmjtNum state_nominal[step_max + 1][NS] = { PI, 0.0 };\n#elif defined(CARTPOLE)\nconst mjtNum t_step = 0.1;\nconst mjtNum cal_step = 0.1;\nmjtNum ptb_coef = 0.003;\nconst int step_max = 30;\nconst int32_t roll_max = 600;\nconst char* mname = \"cartpole.xml\";\nconst int ctrl_num = 1;\nconst int NS = 4;\nmjtNum state_nominal[step_max + 1][NS] = { 0, 0, 0, 0.0 };\n#endif\n\n// model\nmjModel* m = 0;\nmjData* d = 0;\nchar lastfile[1000] = \"\";\nchar error[1000];\nstatic int tri_num = 0;\nstatic int32_t trial = 0;\nstatic int index = 0;\nstatic bool cal_flag = true;\nconst long N = NS + ctrl_num;\nconst int n_check = 1;\nmjtNum sysiderr = 0;\nmjtNum delta_x1[12 + ctrl_num] = { 0 };\nmjtNum delta_x2[12] = { 0 };\nmjtNum mat[step_max][12][12 + ctrl_num] = { 0 };\n//mjtNum sum[step_max][NS][NS + ctrl_num] = { 0 };\n//mjtNum dx[step_max + 1][NS];\n//mjtNum delta_xc[step_max + 1][NS + ctrl_num] = { 0 };\n//mjtNum delta_xcs[step_max][NS] = { 0 };\nmjtNum res[NS + ctrl_num][NS + ctrl_num], res6[NS + ctrl_num][NS + ctrl_num], res7[NS][NS + ctrl_num];\nmjtNum ctrl_nominal[step_max * ctrl_num] = { 0 };\nmjtNum ulim = 0;\nint stepite = (int)(t_step / cal_step);\nchar ctrl_buff[20];\nchar para_buff[20];\nchar glstr[10];\nchar *str3, *str;\nFILE *fp, *fp1, *fop, *fop1, *fop2;\nchar mfilename[30];\nchar kfilename[30];\nchar dfilename[30];\n#if LOCAL == false\nchar mfilepre[17] = \"../../../model/\";\nchar kfilepre[17] = \"../../../doc/\";\nchar dfilepre[17] = \"../../../data/\";\n#else \nchar mfilepre[15] = \"\";\nchar kfilepre[15] = \"\";\nchar dfilepre[15] = \"\";\n#endif\n\n// timer\ndouble gettm(void)\n{\n    static chrono::system_clock::time_point _start = chrono::system_clock::now();\n    chrono::duration<double> elapsed = chrono::system_clock::now() - _start;\n    return elapsed.count();\n}\n\n// deallocate and print message\nint finish(const char* msg = 0, mjModel* m = 0, mjData* d = 0)\n{\n    // deallocated everything\n    if( d )\n        mj_deleteData(d);\n    if( m )\n        mj_deleteModel(m);\n    mj_deactivate();\n\n    // print message\n    if( msg )\n        printf(\"%s\\n\", msg);\n\n    return 0;\n}\n\n/* Calculate Determinant of the Matrix */\nmjtNum determinant(mjtNum fh[N][N], mjtNum r)\n{\n\tint z, j, i;\n\tmjtNum m = 1, k, det = 1.0;\n\tint rr = (int)r;\n\tmjtNum a[N][N];\n\n\tfor (i = 0; i < rr; i++)\n\t{\n\t\tfor (j = 0; j < r; j++)\n\t\t{\n\t\t\ta[i][j] = fh[i][j];\n\t\t}\n\t}\n\n\tfor (z = 0; z<rr - 1; z++)\n\t\tfor (i = z; i<rr - 1; i++)\n\t\t{\n\t\t\tif (a[z][z] == 0)\n\t\t\t{\n\t\t\t\t\n\t\t\t\tfor (j = 0; j<rr; j++)\n\t\t\t\t{\n\t\t\t\t\ta[z][j] = a[z][j] + a[i + 1][j];\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (a[z][z] != 0) {\n\t\t\t\tk = -a[i + 1][z] / a[z][z];\n\t\t\t\tfor (j = z; j<rr; j++)a[i + 1][j] = k * a[z][j] + a[i + 1][j];\n\t\t\t}\n\t\t}\n\t\n\tfor (z = 0; z<rr; z++)\n\t{\n\t\tdet = det * (a[z][z]);\n\t}\n\treturn (det);\n}\n\n/* Find transpose of matrix */\nvoid transpose(mjtNum num[N][N], mjtNum fac[N][N], mjtNum r)\n{\n\tint i, j, rr = (int)r;\n\tmjtNum b[N][N], d;\n\n\tfor (i = 0; i < rr; i++)\n\t{\n\t\tfor (j = 0; j < r; j++)\n\t\t{\n\t\t\tb[i][j] = fac[j][i];\n\t\t}\n\t}\n\td = determinant(num, r);\n\tfor (i = 0; i < rr; i++)\n\t{\n\t\tfor (j = 0; j < r; j++)\n\t\t{\n\t\t\tres[i][j] = b[i][j] / d;\n\t\t}\n\t}\n}\n\n/* Inverse */\nvoid cofactor(mjtNum num[N][N], mjtNum f)\n{\n\tmjtNum b[N][N] = { 0 }, fac[N][N];\n\tint p, q, m, n, i, j;\n\tint ff = (int)f;\n\n\tfor (q = 0; q < ff; q++)\n\t{\n\t\tfor (p = 0; p < ff; p++)\n\t\t{\n\t\t\tm = 0;\n\t\t\tn = 0;\n\t\t\tfor (i = 0; i < ff; i++)\n\t\t\t{\n\t\t\t\tfor (j = 0; j < ff; j++)\n\t\t\t\t{\n\t\t\t\t\tif (i != q && j != p)\n\t\t\t\t\t{\n\t\t\t\t\t\tb[m][n] = num[i][j];\n\t\t\t\t\t\tif (n < (f - 2)) n++;\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tn = 0;\n\t\t\t\t\t\t\tm++;\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\tfac[q][p] = pow(mjtNum(-1), q + p) * determinant(b, ff - 1);\n\t\t}\n\t}\n\ttranspose(num, fac, ff);\n}\n\n// w x y z to roll pitch yaw\nvoid quat2smpl(double *res, double *quat)\n{\n\tdouble b0, b1, b2, b3;\n\n\tb0 = *quat;\n\tb1 = *(quat + 1);\n\tb2 = *(quat + 2);\n\tb3 = *(quat + 3);\n\n\tQuaterniond q = Eigen::Quaterniond(b0, b1, b2, b3); // w x y z\n\tauto r = q.toRotationMatrix().eulerAngles(0, 1, 2);\n\n\t*res = r[0];\n\t*(res + 1) = r[1];\n\t*(res + 2) = r[2];\n}\n\n// roll pitch yaw to w x y z\nvoid smpl2quat(double *res, double *smpl)\n{\n\tdouble rx, ry, rz; // roll pitch yaw\n\n\trx = *smpl;\n\try = *(smpl + 1);\n\trz = *(smpl + 2);\n\n\tif (rx > PI) rx = PI - rx;\n\n\tQuaterniond q = AngleAxisd(rx, Vector3d::UnitX())\n\t\t* AngleAxisd(ry, Vector3d::UnitY())\n\t\t* AngleAxisd(rz, Vector3d::UnitZ());\n\n\tEigen::Vector4d b = q.coeffs(); // x y z w\n\n\t*res = b[3];\n\t*(res + 1) = b[0];\n\t*(res + 2) = b[1];\n\t*(res + 3) = b[2];\n}\n\ndouble gaussrand()\n{\n\tstatic double U, V;\n\tstatic int phase = 0;\n\tdouble Z;\n\n\tif (phase == 0)\n\t{\n\t\tU = rand() / (RAND_MAX + 1.0);\n\t\tV = rand() / (RAND_MAX + 1.0);\n\t\tif (U == 0) U = 0.00001;\n\t\tZ = sqrt(-2.0 * log(U)) * sin(2.0 * PI * V);\n\t}\n\telse\n\t{\n\t\tZ = sqrt(-2.0 * log(U)) * cos(2.0 * PI * V);\n\t}\n\tphase = 1 - phase;\n\treturn Z;\n}\n\nvoid get_nominal(mjModel* m, mjData* d)\n{\n\tstatic int index = 0, i, y;\n\tmjtNum temp[4];\n#if STATE_LINEAR == true\n\tstatic int step_max = 1;\n#endif\n\n\tmju_zero(d->qpos, m->nq);\n\tmju_zero(d->qvel, m->nv);\n\tfor (y = 0; y < NS/2; y++)\n\t{\n\t\td->qpos[y] = state_nominal[index][2 * y];\n\t}\n\tfor (y = 0; y < m->nv; y++)\n\t{\n\t\td->qvel[y] = state_nominal[index][2 * y + 1];\n\t}\n\tfor (y = 0; y < ctrl_num; y++)\n\t{\n\t\td->ctrl[y] = ctrl_nominal[index * ctrl_num + y];\n\t}\n\n\tquat2smpl(temp, &(d->qpos[3]));\n\tfor (int k = 0; k < 3; k++)state_nominal[index][2 * k + 6] = temp[k];\n\n\t//for (int k = 0; k < 3; k++)state_nominal[index][2 * k + 6] = d->qpos[k + 4];\n\n\twhile (index < step_max)\n\t{\n\t\tfor (i = 0; i < stepite; i++) mj_step(m, d);\n\n\t\tindex++;\n\t\tfor (y = 0; y < 3; y++)\n\t\t{\n\t\t\tstate_nominal[index][2 * y] = d->qpos[y];\n\t\t}\n\n\t\tquat2smpl(temp, &(d->qpos[3]));\n\t\tfor (int k = 0; k < 3; k++)state_nominal[index][2 * k + 6] = temp[k];\n\n\t\t//for (int k = 0; k < 3; k++)state_nominal[index][2 * k + 6] = d->qpos[k+4];\n\n\t\tfor (y = 7; y < m->nq; y++)\n\t\t{\n\t\t\tstate_nominal[index][2 * (y-1)] = d->qpos[y];\n\t\t}\n\t\tfor (y = 0; y < m->nv; y++)\n\t\t{\n\t\t\tstate_nominal[index][2 * y + 1] = d->qvel[y];\n\t\t}\n\t\tfor (y = 0; y < ctrl_num; y++)\n\t\t{\n\t\t\td->ctrl[y] = ctrl_nominal[index * ctrl_num + y];\n\t\t}\n\t}\n}\n\nvoid sysidcheck(mjModel* m, mjData* d)\n{\n\tstatic int index = 0;\n\tstatic mjtNum t_init;\n\tconst int step_max = 1500;\n\tint i, j, k;\n\tmjtNum dx[n_check][step_max][12];\n\tmjtNum delta_xc[n_check][step_max][12 + ctrl_num] = { 0 };\n\tmjtNum delta_xcs[n_check][step_max][12] = { 0 };\n\tmjtNum temp[4];\n\n\tfor (i = 0; i < 17; i++)\n\t{\n\t\tfor (j = 0; j < n_check; j++)\n\t\t{\n\t\t\tfor (k = 0; k < step_max; k++) delta_xc[j][k][i] = 0.005 * ulim * gaussrand();\n\t\t}\n\t}\n\tfor (i = 0; i < n_check; i++)\n\t{\n\t\tfor (j = 0; j < step_max; j++) mju_mulMatVec(dx[i][j], *mat[j], delta_xc[i][j], 12, 12 + ctrl_num);\n\t}\n\n\tfor (i = 0; i < n_check; i++)\n\t{\n\t\tindex = 0;\n\t\tt_init = d->time;\n\t\tfor (j = 0; j < 3; j++)\n\t\t{\n\t\t\td->qpos[j] = delta_xc[i][index][2 * j] + state_nominal[index][2 * j];\n\t\t}\n\n\t\t//for (k = 0; k < 3; k++) d->qpos[k+4] = delta_xc[i][index][2 * k + 6] + state_nominal[index][2 * k + 6];\n\t\t//d->qpos[3] = sqrt(1 - d->qpos[4] * d->qpos[4] - d->qpos[5] * d->qpos[5] - d->qpos[6] * d->qpos[6]);\n\n\t\tfor (k = 0; k < 3; k++) temp[k] = delta_xc[i][index][2 * k + 6] + state_nominal[index][2 * k + 6];\n\t\tsmpl2quat(&(d->qpos[3]), temp);\n\n\t\tfor (j = 7; j < m->nq; j++)\n\t\t{\n\t\t\td->qpos[j] = state_nominal[index][2 * (j-1)];\n\t\t}\n\t\t//d->qpos[9] = delta_xc[i][index][12] + state_nominal[index][16];\n\t\tfor (j = 0; j < 6; j++)\n\t\t{\n\t\t\td->qvel[j] = delta_xc[i][index][2 * j + 1] + state_nominal[index][2 * j + 1];\n\t\t}\n\t\tfor (j = 6; j < m->nv; j++)\n\t\t{\n\t\t\td->qvel[j] = state_nominal[index][2 * j + 1];\n\t\t}\n\t\t//d->qvel[8] = delta_xc[i][index][13] + state_nominal[index][17];\n\t\tfor (k = 0; k < ctrl_num; k++)\n\t\t{\n\t\t\td->ctrl[k] = delta_xc[i][index][k + 12] + ctrl_nominal[index * ctrl_num + k];\n\t\t}\n\t\twhile (index < step_max - 1)\n\t\t{\n\t\t\tif (d->time - t_init < t_step - 0.00001)\n\t\t\t{\n\t\t\t\tmj_step(m, d);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfor (int y = 0; y < 3; y++)\n\t\t\t\t{\n\t\t\t\t\tdelta_xcs[i][index][2 * y] = d->qpos[y] - state_nominal[index + 1][2 * y];\n\t\t\t\t}\n\n\t\t\t\tquat2smpl(temp, &(d->qpos[3]));\n\t\t\t\tfor (int k = 0; k < 3; k++) delta_xcs[i][index][2 * k + 6] = temp[k] - state_nominal[index][2 * k + 6];\n\n\t\t\t\t//for (int k = 0; k < 3; k++) delta_xcs[i][index][2 * k + 6] = d->qpos[k+4] - state_nominal[index][2 * k + 6];\n\n\t\t\t\t//delta_xcs[i][index][12] = d->qpos[9] - state_nominal[index + 1][16];\n\t\t\t\tfor (int y = 0; y < 6; y++)\n\t\t\t\t{\n\t\t\t\t\tdelta_xcs[i][index][2 * y + 1] = d->qvel[y] - state_nominal[index + 1][2 * y + 1];\n\t\t\t\t}\n\t\t\t\t//delta_xcs[i][index][13] = d->qvel[8] - state_nominal[index + 1][17];\n\n\t\t\t\tindex++;\n\t\t\t\tt_init = d->time;\n\n\t\t\t\tfor (int y = 0; y < 3; y++)\n\t\t\t\t{\n\t\t\t\t\td->qpos[y] = delta_xc[i][index][2 * y] + state_nominal[index][2 * y];\n\t\t\t\t}\n\n\t\t\t\t//for (int k = 0; k < 3; k++) d->qpos[k+4] = delta_xc[i][index][2 * k + 6] + state_nominal[index][2 * k + 6];\n\t\t\t\t//d->qpos[3] = sqrt(1 - d->qpos[4] * d->qpos[4] - d->qpos[5] * d->qpos[5] - d->qpos[6] * d->qpos[6]);\n\n\t\t\t\tfor (int k = 0; k < 3; k++) temp[k] = delta_xc[i][index][2 * k + 6] + state_nominal[index][2 * k + 6];\n\t\t\t\tsmpl2quat(&(d->qpos[3]), temp);\n\n\t\t\t\tfor (j = 7; j < m->nq; j++)\n\t\t\t\t{\n\t\t\t\t\td->qpos[j] = state_nominal[index][2 * (j - 1)];\n\t\t\t\t}\n\t\t\t\t//d->qpos[9] = delta_xc[i][index][12] + state_nominal[index][16];\n\t\t\t\tfor (int y = 0; y < 6; y++)\n\t\t\t\t{\n\t\t\t\t\td->qvel[y] = delta_xc[i][index][2 * y + 1] + state_nominal[index][2 * y + 1];\n\t\t\t\t}\n\t\t\t\tfor (int y = 6; y < m->nv; y++)\n\t\t\t\t{\n\t\t\t\t\td->qvel[y] = state_nominal[index][2 * y + 1];\n\t\t\t\t}\n\t\t\t\t//d->qvel[8] = delta_xc[i][index][13] + state_nominal[index][17];\n\t\t\t\tfor (int ci = 0; ci < ctrl_num; ci++)\n\t\t\t\t{\n\t\t\t\t\td->ctrl[ci] = delta_xc[i][index][ci + 12] + ctrl_nominal[index * ctrl_num + ci];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (int t = 0; t < 12; t++)\n\t\t{\n\t\t\tfor (int h = 0; h < step_max; h++)\n\t\t\t{\n\t\t\t\tif (delta_xcs[i][h][t] != 0) sysiderr += fabs((dx[i][h][t] - delta_xcs[i][h][t]) / delta_xcs[i][h][t]);\n\t\t\t}\n\t\t}\n\t}\n\tsysiderr = sysiderr / (1.0*n_check*step_max*12);\n}\n\nvoid check(mjModel* m, mjData* d)\n{\n//\tstatic int index = 0, h, u, y;\n//#if STATE_LINEAR == true\n//\tstatic int step_max = 1;\n//#endif\n//\n//\tfor (u = 0; u < NS + ctrl_num; u++)\n//\t{\n//\t\tfor (h = 0; h < step_max; h++) delta_xc[h][u] = ptb_coef * ulim * gaussrand();\n//\t}\n//\tfor (h = 0; h < step_max; h++)\n//\t{\n//\t\tmju_mulMatVec(dx[h + 1], *mat[h], delta_xc[h], NS, NS + ctrl_num);\n//\t}\n//\twhile (index < step_max)\n//\t{\n//\t\tfor (y = 0; y < m->nq; y++)\n//\t\t{\n//\t\t\td->qpos[y] = delta_xc[index][2 * y] + state_nominal[index][2 * y];\n//\t\t}\n//\t\tfor (y = 0; y < m->nv; y++)\n//\t\t{\n//\t\t\td->qvel[y] = delta_xc[index][2 * y + 1] + state_nominal[index][2 * y + 1];\n//\t\t}\n//\t\tfor (h = 0; h < ctrl_num; h++)\n//\t\t{\n//\t\t\td->ctrl[h] = ctrl_nominal[index * ctrl_num + h] + delta_xc[index][h + NS];\n//\t\t}\n//\n//\t\tfor (h = 0; h < stepite; h++) mj_step(m, d);\n//\n//\t\tfor (y = 0; y < m->nq; y++)\n//\t\t{\n//\t\t\tdelta_xcs[index][2 * y] = d->qpos[y] - state_nominal[index + 1][2 * y];\n//\t\t}\n//\t\tfor (y = 0; y < m->nv; y++)\n//\t\t{\n//\t\t\tdelta_xcs[index][2 * y + 1] = d->qvel[y] - state_nominal[index + 1][2 * y + 1];\n//\t\t}\n//\t\tindex++;\n//\t}\n}\n\nvoid setcontrol(mjModel* m, mjData* d)\n{\n\tmjtNum temp[4];\n\tstatic int index = 0, i, y;\n#if STATE_LINEAR == true\n\tstatic int step_max = 1;\n#endif\n\n\twhile (index < step_max)\n\t{\n\t\tfor (y = 0; y < 3; y++)\n\t\t{\n\t\t\tdelta_x1[2 * y] = ptb_coef * ulim * gaussrand();\n\t\t\td->qpos[y] = delta_x1[2 * y] + state_nominal[index][2 * y];\n\t\t}\n\t\tfor (int k = 0; k < 3; k++) {\n\t\t\tdelta_x1[2 * k + 6] = ptb_coef * ulim * gaussrand();\n\n\t\t\t//d->qpos[k+4] = delta_x1[2 * k + 6] + state_nominal[index][2 * k + 6];\n\n\t\t\ttemp[k] = delta_x1[2 * k + 6] + state_nominal[index][2 * k + 6];\n\t\t}\n\t\t//d->qpos[3] = sqrt(1 - d->qpos[4] * d->qpos[4] - d->qpos[5] * d->qpos[5] - d->qpos[6] * d->qpos[6]);\n\t\t\n\t\tsmpl2quat(&(d->qpos[3]), temp);\n\t\tfor (int j = 7; j < m->nq; j++)\n\t\t{\n\t\t\td->qpos[j] = state_nominal[index][2 * (j - 1)];\n\t\t}\n\t\t//delta_x1[12] = ptb_coef * ulim * gaussrand();\n\t\t//d->qpos[9] = delta_x1[12] + state_nominal[index][16];\n\t\tfor (y = 0; y < 6; y++)\n\t\t{\n\t\t\tdelta_x1[2 * y + 1] = ptb_coef * ulim * gaussrand();\n\t\t\td->qvel[y] = delta_x1[2 * y + 1]+state_nominal[index][2 * y + 1];\n\t\t}\n\t\tfor (y = 6; y < m->nv; y++)\n\t\t{\n\t\t\td->qvel[y] = state_nominal[index][2 * y + 1];\n\t\t}\n\t\t//delta_x1[13] = ptb_coef * ulim * gaussrand();\n\t\t//d->qvel[8] = delta_x1[13] + state_nominal[index][17];\n\t\tfor (i = 0; i < ctrl_num; i++)\n\t\t{\n\t\t\tdelta_x1[i + 12] = ptb_coef * ulim * gaussrand();\n\t\t\td->ctrl[i] = ctrl_nominal[index * ctrl_num + i] + delta_x1[i + 12];\n\t\t}\n\n\t\tfor (i = 0; i < stepite; i++) mj_step(m, d);\n\n\t\tfor (int y = 0; y < 3; y++)\n\t\t{\n\t\t\tdelta_x2[2 * y] = d->qpos[y] - state_nominal[index + 1][2 * y];\n\t\t}\n\n\t\tquat2smpl(temp, &(d->qpos[3]));\n\t\tfor (int k = 0; k < 3; k++) delta_x2[2 * k + 6] = temp[k] - state_nominal[index][2 * k + 6];\n\t\t\n\t\t//for (int k = 0; k < 3; k++) delta_x2[2 * k + 6] = d->qpos[k+4] - state_nominal[index][2 * k + 6];\n\n\t\t//delta_x2[12] = d->qpos[9] - state_nominal[index + 1][16];\n\t\tfor (int y = 0; y < 6; y++)\n\t\t{\n\t\t\tdelta_x2[2 * y + 1] = d->qvel[y] - state_nominal[index + 1][2 * y + 1];\n\t\t}\n\t\t//delta_x2[13] = d->qvel[8] - state_nominal[index + 1][17];\n\t\t// iteration method\n\t\tfor (y = 0; y < 12; y++)\n\t\t{\n\t\t\tfor (i = 0; i < 17; i++)\n\t\t\t{\n\t\t\t\tmat[index][y][i] = mat[index][y][i] * (1 - 1 / (trial + 1.0)) + delta_x2[y] * delta_x1[i] / ((trial + 1.0) * ptb_coef * ptb_coef * ulim * ulim);\n\t\t\t}\n\t\t}\n\n\t\tif (index == 0)\n\t\t{\n\t\t\tstr3 = glstr;\n\t\t\tsprintf(str3, \"%3.3f\", mat[index][0][1]);\n\t\t\tfwrite(str3, 5, 1, fop);\n\t\t\tfputs(\" \", fop);\n\t\t}\n\t\tindex++;\n\t}\n\tindex = 0;\n\ttrial++;\n}\n\n// main function\nint main(int argc, const char** argv)\n{\n    // activate MuJoCo Pro license (this must be *your* activation key)\n\tstrcpy(kfilename, kfilepre);\n\tstrcat(kfilename, \"mjkeysmall.txt\");\n    mj_activate(kfilename);\n\n    // get filename, determine file type\n    std::string filename(mname);\n    bool binary = (filename.find(\".mjb\")!=std::string::npos);\n\tstrcpy(mfilename, mfilepre);\n\tstrcat(mfilename, mname);\n\n    // load model\n    char error[1000] = \"Could not load binary model\";\n    if( binary )\n        m = mj_loadModel(mfilename, 0);\n    else\n        m = mj_loadXML(mfilename, 0, error, 1000);\n    if( !m )\n        return finish(error);\n\n    // make data\n    d = mj_makeData(m);\n    if( !d )\n        return finish(\"Could not allocate mjData\", m);\n\n\tif (STATE_LINEAR == true)\n\t{\n\t\t#if defined(CART2POLE)||defined(CART3POLE)||defined(CART7POLE)\n\t\t\t\tstate_nominal[0][2] = PI;\n\t\t#elif defined(PENDULUM)\n\t\t\t\tstate_nominal[0][0] = 0;\n\t\t#elif defined(CARTPOLE)\n\t\t\t\tstate_nominal[0][2] = -PI;\n\t\t#elif defined(ACROBOT)\n\t\t\t\tstate_nominal[0][0] = 0;\n\t\t\t\tstate_nominal[0][2] = -2 * PI;\n\t\t#endif\n\t}\n\n\tsrand((unsigned)time(NULL));\n\tstrcpy(dfilename, dfilepre);\n\tstrcat(dfilename, \"converge.txt\");\n\tif ((fop = fopen(dfilename, \"wt+\")) == NULL) {\n\t\treturn 0;\n\t}\n\tstrcpy(dfilename, dfilepre);\n\tstrcat(dfilename, \"result.txt\");\n\tif ((fp = fopen(dfilename, \"r\")) != NULL)\n\t{\n\t\tfscanf(fp, \"%s\", ctrl_buff);\n\t\tif (ctrl_buff[0] == 'C') {\n\t\t\tfor (int i = 0; i < step_max * ctrl_num; i++)\n\t\t\t{\n\t\t\t\tfscanf(fp, \"%s\", ctrl_buff);\n\t\t\t\tctrl_nominal[i] = atof(ctrl_buff);\n\t\t\t\tif (fabs(ctrl_nominal[i]) > ulim) ulim = fabs(ctrl_nominal[i]);\n\n\t\t\t\t#if CTRL_LIMITTED == true\n\t\t\t\t\tif (ctrl_nominal[i] > m->actuator_ctrlrange[1]) ctrl_nominal[i] = m->actuator_ctrlrange[1];\n\t\t\t\t\telse if (ctrl_nominal[i] < m->actuator_ctrlrange[0]) ctrl_nominal[i] = m->actuator_ctrlrange[0];\n\t\t\t\t#endif\n\t\t\t\t#if STATE_LINEAR == true\n\t\t\t\t\tctrl_nominal[i] = 0;\n\t\t\t\t#endif\n\t\t\t}\n\t\t\tfclose(fp); \n\t\t}\n\t}\n\n    // time simulation\n    int steps = 0, contacts = 0, constraints = 0;\n    double printfraction = 0.1;\n    printf(\"\\nSimulation \");\n    double start = gettm();\n\tget_nominal(m, d);\n\twhile (trial < roll_max)\n    {\n\t\tsetcontrol(m, d);\n\n        // accumulate statistics\n        steps = steps + stepite;\n        contacts += d->ncon;\n        constraints += d->nefc;\n\n        // print '.' every 10% of duration\n        if( trial >= roll_max*printfraction )\n        {\n            printf(\".\");\n            printfraction += 0.1;\n        }\n    }\n    double end = gettm();\n\n    // print results\n    printf(\"\\n Simulation time      : %.2f s\\n\", end-start);\n    printf(\" Time per step        : %.3f ms\\n\", 1000.0*(end-start)/mjMAX(1,steps));\n    printf(\" Contacts per step    : %d\\n\", contacts/mjMAX(1,steps));\n    printf(\" Constraints per step : %d\\n\", constraints/mjMAX(1,steps));\n    printf(\" Degrees of freedom   : %d\\n\\n\", m->nv);\n\n\tsysidcheck(m, d);\n\n\t// print result\n\t#if STATE_LINEAR == true\n\t\tstrcpy(dfilename, dfilepre);\n\t\tstrcat(dfilename, \"linearization_top.txt\");\n\t\tif ((fop2 = fopen(dfilename, \"wt+\")) != NULL)\n\t\t{\n\t\t\tstr3 = glstr;\n\t\t\tfor (int t = 0; t < 1; t++)\n\t\t\t{\n\t\t\t\tfor (int h = 0; h < NS; h++)\n\t\t\t\t{\n\t\t\t\t\tfor (int d = 0; d < NS + ctrl_num; d++)\n\t\t\t\t\t{\n\t\t\t\t\t\tsprintf(str3, \"%4.8f\", mat[t][h][d]);\n\t\t\t\t\t\tfwrite(str3, 10, 1, fop2);\n\t\t\t\t\t\tfputs(\" \", fop2);\n\t\t\t\t\t}\n\t\t\t\t\tfputs(\"\\n\", fop2);\n\t\t\t\t}\n\t\t\t\tfputs(\"\\n\", fop2);\n\t\t\t}\n\n\t\t\t// for result checking\n\t\t\tfor (int t = 0; t < NS; t++)\n\t\t\t{\n\t\t\t\tfor (int h = 1; h <= 1; h++)\n\t\t\t\t{\n\t\t\t\t\tsprintf(str3, \"%2.4f\", dx[h][t]);\n\t\t\t\t\tfwrite(str3, 6, 1, fop2);\n\t\t\t\t\tfputs(\" \", fop2);\n\t\t\t\t}\n\t\t\t\tfputs(\"\\n\", fop2);\n\t\t\t\tfor (int d = 0; d < 1; d++)\n\t\t\t\t{\n\t\t\t\t\tsprintf(str3, \"%2.4f\", delta_xcs[d][t]);\n\t\t\t\t\tfwrite(str3, 6, 1, fop2);\n\t\t\t\t\tfputs(\" \", fop2);\n\t\t\t\t}\n\t\t\t\tfputs(\"\\n\", fop2);\n\t\t\t\tfputs(\"\\n\", fop2);\n\t\t\t}\n\t\t\tfputs(\"\\nptb_coef: \", fop2);\n\t\t\tsprintf(str3, \"%2.4f\\n\", ptb_coef);\n\t\t\tfwrite(str3, 6, 1, fop2);\n\t\t\tfclose(fop2);\n\t\t}\n\t#else\n\t\tstrcpy(dfilename, dfilepre);\n\t\tstrcat(dfilename, \"lnr.txt\");\n\t\tif ((fop2 = fopen(dfilename, \"wt+\")) != NULL)\n\t\t{\n\t\t\tstr3 = glstr;\n\t\t\tfor (int t = 0; t < step_max; t++)\n\t\t\t{\n\t\t\t\tfor (int h = 0; h < 12; h++)\n\t\t\t\t{\n\t\t\t\t\tfor (int d = 0; d < 12 + ctrl_num; d++)\n\t\t\t\t\t{\n\t\t\t\t\t\tsprintf(str3, \"%4.8f\", mat[t][h][d]);\n\t\t\t\t\t\tfwrite(str3, 10, 1, fop2);\n\t\t\t\t\t\tfputs(\" \", fop2);\n\t\t\t\t\t}\n\t\t\t\t\tfputs(\"\\n\", fop2);\n\t\t\t\t}\n\t\t\t\tfputs(\"\\n\", fop2);\n\t\t\t}\n\n\t\t\t//// for result checking\n\t\t\t//for (int t = 0; t < NS; t++)\n\t\t\t//{\n\t\t\t//\tfor (int h = 1; h <= step_max; h++)\n\t\t\t//\t{\n\t\t\t//\t\tsprintf(str3, \"%2.4f\", dx[h][t]);\n\t\t\t//\t\tfwrite(str3, 6, 1, fop2);\n\t\t\t//\t\tfputs(\" \", fop2);\n\t\t\t//\t}\n\t\t\t//\tfputs(\"\\n\", fop2);\n\t\t\t//\tfor (int d = 0; d < step_max; d++)\n\t\t\t//\t{\n\t\t\t//\t\tsprintf(str3, \"%2.4f\", delta_xcs[d][t]);\n\t\t\t//\t\tfwrite(str3, 6, 1, fop2);\n\t\t\t//\t\tfputs(\" \", fop2);\n\t\t\t//\t}\n\t\t\t//\tfputs(\"\\n\", fop2);\n\t\t\t//\tfputs(\"\\n\", fop2);\n\t\t\t//}\n\t\t\tfputs(\"sysiderr: \", fop2);\n\t\t\tsprintf(str3, \"%2.4f\\n\", sysiderr);\n\t\t\tfwrite(str3, 6, 1, fop2);\n\t\t\tfputs(\"\\nptb_coef: \", fop2);\n\t\t\tsprintf(str3, \"%2.4f\\n\", ptb_coef);\n\t\t\tfwrite(str3, 6, 1, fop2);\n\n\t\t\tfclose(fop2);\n\t\t}\n\n\t\t//// state output\n\t\t//strcpy(dfilename, dfilepre);\n\t\t//strcat(dfilename, \"states.txt\");\n\t\t//if ((fp1 = fopen(dfilename, \"at+\")) != NULL)\n\t\t//{\n\t\t//\tstr3 = glstr;\n\t\t//\tfor (int h = 0; h < NS; h++)\n\t\t//\t{\n\t\t//\t\tfor (int d = 1; d < step_max; d++)\n\t\t//\t\t{\n\t\t//\t\t\tsprintf(str3, \"%4.8f\", state_nominal[d][h]);\n\t\t//\t\t\tfwrite(str3, 10, 1, fp1);\n\t\t//\t\t\tfputs(\" \", fp1);\n\t\t//\t\t}\n\t\t//\t\tfputs(\"\\n\", fp1);\n\t\t//\t}\n\t\t//\tfclose(fp1);\n\t\t//}\n\t#endif\n\t// hold cmd\n\tsystem(\"pause\");\n    // finalize\n    return finish(0, m, d);\n}\n", "meta": {"hexsha": "33a8989545d8682ef6985fb31caf4b404c7c9277", "size": 21980, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "backup/some old code and slides/sample/sysidpartial.cpp", "max_stars_repo_name": "rwang0417/d2c_mujoco200", "max_stars_repo_head_hexsha": "84609fbb14dc38dadf35193d0c7c4431e6f22913", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-02-24T00:15:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-02T03:20:46.000Z", "max_issues_repo_path": "backup/some old code and slides/sample/sysidpartial.cpp", "max_issues_repo_name": "rwang0417/d2c_mujoco200", "max_issues_repo_head_hexsha": "84609fbb14dc38dadf35193d0c7c4431e6f22913", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "backup/some old code and slides/sample/sysidpartial.cpp", "max_forks_repo_name": "rwang0417/d2c_mujoco200", "max_forks_repo_head_hexsha": "84609fbb14dc38dadf35193d0c7c4431e6f22913", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-08-05T20:21:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-02T03:20:49.000Z", "avg_line_length": 24.8642533937, "max_line_length": 148, "alphanum_fraction": 0.5339854413, "num_tokens": 8831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2978326155932026}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation>\n// Copyright (c) 2020-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// @file This module implements two binding commitment schemes used in the Groth16\n// aggregation.\n// The first one is a commitment scheme that commits to a single vector $a$ of\n// length n in the second base group $G_1$ (for example):\n// * it requires a structured SRS $v_1$ of the form $(h,h^u,h^{u^2}, ...\n// ,g^{h^{n-1}})$ with $h \\in G_2$ being a random generator of $G_2$ and $u$ a\n// random scalar (coming from a power of tau ceremony for example)\n// * it requires a second structured SRS $v_2$ of the form $(h,h^v,h^{v^2},\n// ...$ with $v$ being a random scalar different than u (coming from another\n// power of tau ceremony for example)\n// The Commitment is a tuple $(\\prod_{i=0}^{n-1} e(a_i,v_{1,i}),\n// \\prod_{i=0}^{n-1} e(a_i,v_{2,i}))$\n//\n// The second one takes two vectors $a \\in G_1^n$ and $b \\in G_2^n$ and commits\n// to them using a similar approach as above. It requires an additional SRS\n// though:\n// * $v_1$ and $v_2$ stay the same\n// * An additional tuple $w_1 = (g^{u^n},g^{u^{n+1}},...g^{u^{2n-1}})$ and $w_2 =\n// (g^{v^n},g^{v^{n+1},...,g^{v^{2n-1}})$ where $g$ is a random generator of\n// $G_1$\n// The commitment scheme returns a tuple:\n// * $\\prod_{i=0}^{n-1} e(a_i,v_{1,i})e(w_{1,i},b_i)$\n// * $\\prod_{i=0}^{n-1} e(a_i,v_{2,i})e(w_{2,i},b_i)$\n//\n// The second commitment scheme enables to save some KZG verification in the\n// verifier of the Groth16 verification protocol since we pack two vectors in\n// one commitment.\n\n#ifndef CRYPTO3_R1CS_GG_PPZKSNARK_AGGREGATE_IPP2_COMMITMENT_HPP\n#define CRYPTO3_R1CS_GG_PPZKSNARK_AGGREGATE_IPP2_COMMITMENT_HPP\n\n#include <tuple>\n#include <vector>\n#include <type_traits>\n\n#include <boost/assert.hpp>\n#include <boost/iterator/zip_iterator.hpp>\n#include <boost/accumulators/accumulators.hpp>\n\n#include <nil/crypto3/algebra/type_traits.hpp>\n\n#include <nil/crypto3/algebra/algorithms/pair.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace zk {\n            namespace snark {\n                /// Both commitment outputs a pair of $F_q^k$ element.\n                template<typename CurveType>\n                using r1cs_gg_ppzksnark_ipp2_commitment_output =\n                    std::pair<typename CurveType::gt_type::value_type, typename CurveType::gt_type::value_type>;\n\n                /// Key is a generic commitment key that is instantiated with g and h as basis,\n                /// and a and b as powers.\n                template<typename GroupType>\n                struct r1cs_gg_ppzksnark_ipp2_commitment_key {\n                    typedef GroupType group_type;\n                    typedef typename group_type::curve_type curve_type;\n                    typedef typename curve_type::scalar_field_type field_type;\n\n                    typedef typename group_type::value_type group_value_type;\n                    typedef typename field_type::value_type field_value_type;\n\n                    /// Exponent is a\n                    std::vector<group_value_type> a;\n                    /// Exponent is b\n                    std::vector<group_value_type> b;\n\n                    /// Returns true if commitment keys have the exact required length.\n                    /// It is necessary for the IPP scheme to work that commitment\n                    /// key have the exact same number of arguments as the number of proofs to\n                    /// aggregate.\n                    inline bool has_correct_len(std::size_t n) const {\n                        return a.size() == n && n == b.size();\n                    }\n\n                    /// Returns both vectors scaled by the given vector entrywise.\n                    /// In other words, it returns $\\{v_i^{s_i}\\}$\n                    template<\n                        typename InputIterator,\n                        typename ValueType = typename std::iterator_traits<InputIterator>::value_type,\n                        typename std::enable_if<std::is_same<field_value_type, ValueType>::value, bool>::type = true>\n                    r1cs_gg_ppzksnark_ipp2_commitment_key<group_type> scale(InputIterator s_first,\n                                                                            InputIterator s_last) const {\n                        BOOST_ASSERT(has_correct_len(std::distance(s_first, s_last)));\n\n                        r1cs_gg_ppzksnark_ipp2_commitment_key<group_type> result;\n                        std::for_each(boost::make_zip_iterator(boost::make_tuple(s_first, a.begin(), b.begin())),\n                                      boost::make_zip_iterator(boost::make_tuple(s_last, a.end(), b.end())),\n                                      [&](const boost::tuple<const field_value_type &, const group_value_type &,\n                                                             const group_value_type &> &t) {\n                                          result.a.emplace_back(t.template get<1>() * t.template get<0>());\n                                          result.b.emplace_back(t.template get<2>() * t.template get<0>());\n                                      });\n\n                        return result;\n                    }\n\n                    /// Returns the left and right commitment key part. It makes copy.\n                    std::pair<r1cs_gg_ppzksnark_ipp2_commitment_key<group_type>,\n                              r1cs_gg_ppzksnark_ipp2_commitment_key<group_type>>\n                        split(std::size_t at) const {\n                        BOOST_ASSERT(a.size() == b.size());\n                        BOOST_ASSERT(at > 0 && at < a.size());\n\n                        r1cs_gg_ppzksnark_ipp2_commitment_key<group_type> result_l;\n                        r1cs_gg_ppzksnark_ipp2_commitment_key<group_type> result_r;\n\n                        auto a_it = a.begin();\n                        auto b_it = b.begin();\n                        while (a_it != a.begin() + at && b_it != b.begin() + at) {\n                            result_l.a.emplace_back(*a_it);\n                            result_l.b.emplace_back(*b_it);\n                            ++a_it;\n                            ++b_it;\n                        }\n                        while (a_it != a.end() && b_it != b.end()) {\n                            result_r.a.emplace_back(*a_it);\n                            result_r.b.emplace_back(*b_it);\n                            ++a_it;\n                            ++b_it;\n                        }\n\n                        return std::make_pair(result_l, result_r);\n                    }\n\n                    /// Takes a left and right commitment key and returns a commitment\n                    /// key $left \\circ right^{scale} = (left_i*right_i^{scale} ...)$. This is\n                    /// required step during GIPA recursion.\n                    r1cs_gg_ppzksnark_ipp2_commitment_key<group_type>\n                        compress(const r1cs_gg_ppzksnark_ipp2_commitment_key<group_type> &right,\n                                 const field_value_type &scale) const {\n                        BOOST_ASSERT(a.size() == right.a.size());\n                        BOOST_ASSERT(b.size() == right.b.size());\n                        BOOST_ASSERT(a.size() == b.size());\n\n                        r1cs_gg_ppzksnark_ipp2_commitment_key<group_type> result;\n\n                        std::for_each(\n                            boost::make_zip_iterator(\n                                boost::make_tuple(a.begin(), b.begin(), right.a.begin(), right.b.begin())),\n                            boost::make_zip_iterator(boost::make_tuple(a.end(), b.end(), right.a.end(), right.b.end())),\n                            [&](const boost::tuple<const group_value_type &, const group_value_type &,\n                                                   const group_value_type &, const group_value_type &> &t) {\n                                result.a.emplace_back(t.template get<0>() + t.template get<2>() * scale);\n                                result.b.emplace_back(t.template get<1>() + t.template get<3>() * scale);\n                            });\n\n                        return result;\n                    }\n\n                    /// Returns the first values in the vector of v1 and v2 (respectively\n                    /// w1 and w2). When commitment key is of size one, it's a proxy to get the\n                    /// final values.\n                    std::pair<group_value_type, group_value_type> first() const {\n                        return std::make_pair(a.front(), b.front());\n                    }\n                };\n\n                /// Commitment key used by the \"single\" commitment on G1 values as\n                /// well as in the \"pair\" commitment.\n                /// It contains $\\{h^a^i\\}_{i=1}^n$ and $\\{h^b^i\\}_{i=1}^n$\n                template<typename CurveType>\n                using r1cs_gg_ppzksnark_ipp2_vkey = r1cs_gg_ppzksnark_ipp2_commitment_key<typename CurveType::g2_type>;\n\n                /// Commitment key used by the \"pair\" commitment. Note the sequence of\n                /// powers starts at $n$ already.\n                /// It contains $\\{g^{a^{n+i}}\\}_{i=1}^n$ and $\\{g^{b^{n+i}}\\}_{i=1}^n$\n                template<typename CurveType>\n                using r1cs_gg_ppzksnark_ipp2_wkey = r1cs_gg_ppzksnark_ipp2_commitment_key<typename CurveType::g1_type>;\n\n                template<typename CurveType>\n                struct r1cs_gg_ppzksnark_ipp2_commitment {\n                    typedef CurveType curve_type;\n                    typedef typename curve_type::pairing pairing;\n\n                    typedef r1cs_gg_ppzksnark_ipp2_wkey<CurveType> wkey_type;\n                    typedef r1cs_gg_ppzksnark_ipp2_vkey<CurveType> vkey_type;\n\n                    typedef typename wkey_type::group_value_type g1_value_type;\n                    typedef typename vkey_type::group_value_type g2_value_type;\n                    typedef typename curve_type::gt_type::value_type gt_value_type;\n\n                    typedef r1cs_gg_ppzksnark_ipp2_commitment_output<CurveType> output_type;\n\n                    /// Commits to a tuple of G1 vector and G2 vector in the following way:\n                    /// $T = \\prod_{i=0}^n e(A_i, v_{1,i})e(B_i,w_{1,i})$\n                    /// $U = \\prod_{i=0}^n e(A_i, v_{2,i})e(B_i,w_{2,i})$\n                    /// Output is $(T,U)$\n                    template<typename InputG1Iterator, typename InputG2Iterator,\n                             typename ValueType1 = typename std::iterator_traits<InputG1Iterator>::value_type,\n                             typename ValueType2 = typename std::iterator_traits<InputG2Iterator>::value_type,\n                             typename std::enable_if<std::is_same<g1_value_type, ValueType1>::value, bool>::type = true,\n                             typename std::enable_if<std::is_same<g2_value_type, ValueType2>::value, bool>::type = true>\n                    static output_type pair(const vkey_type &vkey, const wkey_type &wkey, InputG1Iterator a_first,\n                                            InputG1Iterator a_last, InputG2Iterator b_first, InputG2Iterator b_last) {\n                        BOOST_ASSERT(vkey.has_correct_len(std::distance(a_first, a_last)));\n                        BOOST_ASSERT(wkey.has_correct_len(std::distance(b_first, b_last)));\n                        BOOST_ASSERT(std::distance(a_first, a_last) == std::distance(b_first, b_last));\n\n                        // (A * v)\n                        gt_value_type t1 = gt_value_type::one();\n                        std::for_each(boost::make_zip_iterator(boost::make_tuple(a_first, vkey.a.begin())),\n                                      boost::make_zip_iterator(boost::make_tuple(a_last, vkey.a.end())),\n                                      [&](const boost::tuple<const g1_value_type &, const g2_value_type &> &t) {\n                                          t1 = t1 * algebra::pair<curve_type>(t.template get<0>(), t.template get<1>());\n                                      });\n\n                        // (B * v)\n                        gt_value_type t2 = gt_value_type::one();\n                        std::for_each(boost::make_zip_iterator(boost::make_tuple(wkey.a.begin(), b_first)),\n                                      boost::make_zip_iterator(boost::make_tuple(wkey.a.end(), b_last)),\n                                      [&](const boost::tuple<const g1_value_type &, const g2_value_type &> &t) {\n                                          t2 = t2 * algebra::pair<curve_type>(t.template get<0>(), t.template get<1>());\n                                      });\n\n                        gt_value_type u1 = gt_value_type::one();\n                        std::for_each(boost::make_zip_iterator(boost::make_tuple(a_first, vkey.b.begin())),\n                                      boost::make_zip_iterator(boost::make_tuple(a_last, vkey.b.end())),\n                                      [&](const boost::tuple<const g1_value_type &, const g2_value_type &> &t) {\n                                          u1 = u1 * algebra::pair<curve_type>(t.template get<0>(), t.template get<1>());\n                                      });\n\n                        gt_value_type u2 = gt_value_type::one();\n                        std::for_each(boost::make_zip_iterator(boost::make_tuple(wkey.b.begin(), b_first)),\n                                      boost::make_zip_iterator(boost::make_tuple(wkey.b.end(), b_last)),\n                                      [&](const boost::tuple<const g1_value_type &, const g2_value_type &> &t) {\n                                          u2 = u2 * algebra::pair<curve_type>(t.template get<0>(), t.template get<1>());\n                                      });\n\n                        // (A * v)(w * B)\n                        return std::make_pair(algebra::final_exponentiation<curve_type>(t1 * t2),\n                                              algebra::final_exponentiation<curve_type>(u1 * u2));\n                    }\n\n                    /// Commits to a single vector of G1 elements in the following way:\n                    /// $T = \\prod_{i=0}^n e(A_i, v_{1,i})$\n                    /// $U = \\prod_{i=0}^n e(A_i, v_{2,i})$\n                    /// Output is $(T,U)$\n                    template<typename InputG1Iterator,\n                             typename ValueType1 = typename std::iterator_traits<InputG1Iterator>::value_type,\n                             typename std::enable_if<std::is_same<g1_value_type, ValueType1>::value, bool>::type = true>\n                    static output_type single(const vkey_type &vkey, InputG1Iterator a_first, InputG1Iterator a_last) {\n                        BOOST_ASSERT(vkey.has_correct_len(std::distance(a_first, a_last)));\n\n                        gt_value_type t1 = gt_value_type::one();\n                        std::for_each(boost::make_zip_iterator(boost::make_tuple(a_first, vkey.a.begin())),\n                                      boost::make_zip_iterator(boost::make_tuple(a_last, vkey.a.end())),\n                                      [&](const boost::tuple<const g1_value_type &, const g2_value_type &> &t) {\n                                          t1 = t1 * algebra::pair<curve_type>(t.template get<0>(), t.template get<1>());\n                                      });\n\n                        gt_value_type u1 = gt_value_type::one();\n                        std::for_each(boost::make_zip_iterator(boost::make_tuple(a_first, vkey.b.begin())),\n                                      boost::make_zip_iterator(boost::make_tuple(a_last, vkey.b.end())),\n                                      [&](const boost::tuple<const g1_value_type &, const g2_value_type &> &t) {\n                                          u1 = u1 * algebra::pair<curve_type>(t.template get<0>(), t.template get<1>());\n                                      });\n\n                        return std::make_pair(algebra::final_exponentiation<curve_type>(t1),\n                                              algebra::final_exponentiation<curve_type>(u1));\n                    }\n                };\n            }    // namespace snark\n        }        // namespace zk\n    }            // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_R1CS_GG_PPZKSNARK_AGGREGATE_IPP2_COMMITMENT_HPP\n", "meta": {"hexsha": "e990c68d81032ab84bd2cf01cb1d3606640b68d3", "size": 17578, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "snark-logic/libs-source/zk/include/nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/ipp2/commitment.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/zk/include/nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/ipp2/commitment.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/zk/include/nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/ipp2/commitment.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": 59.586440678, "max_line_length": 120, "alphanum_fraction": 0.5289566504, "num_tokens": 3784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2977955234533018}}
{"text": "// ---------------------------------------------------------------------\n//\n// Copyright (c) 2018 - 2021 by the IBAMR developers\n// All rights reserved.\n//\n// This file is part of IBAMR.\n//\n// IBAMR is free software and is distributed under the 3-clause BSD\n// license. The full text of the license can be found in the file\n// COPYRIGHT at the top level directory of IBAMR.\n//\n// ---------------------------------------------------------------------\n\n/////////////////////////////// INCLUDES /////////////////////////////////////\n\n#include \"ibtk/FECache.h\"\n#include \"ibtk/QuadratureCache.h\"\n#include \"ibtk/libmesh_utilities.h\"\n\n#include \"tbox/Utilities.h\"\n\n#if LIBMESH_VERSION_LESS_THAN(1, 2, 0)\n#include \"libmesh/mesh_tools.h\"\n#else\n#include \"libmesh/bounding_box.h\"\n#endif\n#include \"libmesh/dof_map.h\"\n#include \"libmesh/elem.h\"\n#include \"libmesh/enum_elem_type.h\"\n#include \"libmesh/enum_order.h\"\n#include \"libmesh/enum_quadrature_type.h\"\n#include \"libmesh/explicit_system.h\"\n#include \"libmesh/fem_context.h\"\n#include \"libmesh/id_types.h\"\n#include \"libmesh/libmesh_config.h\"\n#include \"libmesh/mesh_base.h\"\n#include \"libmesh/node.h\"\n#include \"libmesh/numeric_vector.h\"\n#include \"libmesh/parallel.h\"\n#include \"libmesh/petsc_vector.h\"\n#include \"libmesh/point.h\"\n#include \"libmesh/quadrature.h\"\n#include \"libmesh/system.h\"\n#include \"libmesh/type_vector.h\"\n#include \"libmesh/variant_filter_iterator.h\"\n\n#include <petscsys.h>\n\nIBTK_DISABLE_EXTRA_WARNINGS\n#include <boost/multi_array.hpp>\nIBTK_ENABLE_EXTRA_WARNINGS\n\n#include <mpi.h>\n\n#include <algorithm>\n#include <cmath>\n#include <fstream>\n#include <limits>\n#include <memory>\n#include <sstream>\n#include <string>\n#include <tuple>\n#include <vector>\n\n/////////////////////////////// NAMESPACE ////////////////////////////////////\n\nnamespace IBTK\n{\n/////////////////////////////// STATIC ///////////////////////////////////////\n\n/////////////////////////////// PUBLIC ///////////////////////////////////////\nvoid\nsetup_system_vectors(libMesh::EquationSystems* equation_systems,\n                     const std::vector<std::string>& system_names,\n                     const std::vector<std::string>& vector_names,\n                     const bool from_restart)\n{\n    for (const std::string& system_name : system_names)\n    {\n        TBOX_ASSERT(equation_systems->has_system(system_name));\n        libMesh::System& system = equation_systems->get_system(system_name);\n        for (const std::string& vector_name : vector_names)\n        {\n            setup_system_vector(system, vector_name, from_restart);\n            if (vector_name == \"RHS Vector\")\n            {\n                auto* explicit_system = dynamic_cast<libMesh::ExplicitSystem*>(&system);\n                if (!explicit_system)\n                {\n                    TBOX_ERROR(\n                        \"You are attempting to add a RHS vector to a libMesh system that does not have one (i.e., it \"\n                        \"does not inherit from ExplicitSystem).\");\n                }\n                else\n                {\n                    explicit_system->rhs = &system.get_vector(\"RHS Vector\");\n                }\n            }\n        }\n    }\n}\n\nvoid\nsetup_system_vector(libMesh::System& system, const std::string& vector_name, const bool from_restart)\n{\n    std::unique_ptr<libMesh::NumericVector<double> > clone_vector;\n    if (from_restart)\n    {\n        libMesh::NumericVector<double>* current = system.request_vector(vector_name);\n        if (current != nullptr)\n        {\n            clone_vector = current->clone();\n        }\n    }\n    system.remove_vector(vector_name);\n    system.add_vector(vector_name, /*projections*/ true, /*type*/ libMesh::GHOSTED);\n\n    if (clone_vector != nullptr)\n    {\n        const auto& parallel_vector = dynamic_cast<const libMesh::PetscVector<double>&>(*clone_vector);\n        auto& ghosted_vector = dynamic_cast<libMesh::PetscVector<double>&>(system.get_vector(vector_name));\n        TBOX_ASSERT(parallel_vector.size() == ghosted_vector.size());\n        TBOX_ASSERT(parallel_vector.local_size() == ghosted_vector.local_size());\n        ghosted_vector = parallel_vector;\n        ghosted_vector.close();\n    }\n}\n\nvoid\napply_transposed_constraint_matrix(const libMesh::DofMap& dof_map, libMesh::PetscVector<double>& rhs)\n{\n    std::vector<libMesh::dof_id_type> dofs;\n    std::vector<double> values_to_add;\n    // loop over constraints and do the action of C^T b\n    for (auto it = dof_map.constraint_rows_begin(); it != dof_map.constraint_rows_end(); ++it)\n    {\n        const std::pair<libMesh::dof_id_type, libMesh::DofConstraintRow>& constraint = *it;\n        const libMesh::dof_id_type constrained_dof = constraint.first;\n        // only resolve constraints if the DoF is locally owned\n        if (dof_map.first_dof() <= constrained_dof && constrained_dof < dof_map.end_dof())\n        {\n            for (const std::pair<const libMesh::dof_id_type, double>& pair : constraint.second)\n            {\n                dofs.push_back(pair.first);\n                values_to_add.push_back(pair.second * rhs(constrained_dof));\n            }\n        }\n    }\n\n    // If we use ghosted RHSs then we cannot use VecSetValues because we are\n    // using a replacement for VecStash. Hence do some somewhat ugly\n    // transformations in that case to sum into ghost regions:\n    if (rhs.type() == libMesh::GHOSTED)\n    {\n        // Calling operator() above puts the vector in read-only mode, which\n        // has to be restored before we can write to it\n        rhs.restore_array();\n        // At this point rhs contains the full set of ghost data (which we\n        // needed for constraint resolution). However, we now want to reuse\n        // the ghost region to sum the values from constraint resolution onto\n        // their owning processes. Hence we must clear the ghost data and then\n        // do another parallel reduction.\n        const PetscInt local_size_without_ghosts = rhs.local_size();\n        Vec loc_vec = nullptr;\n        // we also need the size of the ghost region, which is surprisingly\n        // difficult to get\n        int ierr = VecGhostGetLocalForm(rhs.vec(), &loc_vec);\n        IBTK_CHKERRQ(ierr);\n        PetscInt local_size_with_ghosts = -1;\n        ierr = VecGetSize(loc_vec, &local_size_with_ghosts);\n        IBTK_CHKERRQ(ierr);\n        ierr = VecGhostRestoreLocalForm(rhs.vec(), &loc_vec);\n        IBTK_CHKERRQ(ierr);\n\n        double* const vec_array = rhs.get_array();\n        std::fill(vec_array + local_size_without_ghosts, vec_array + local_size_with_ghosts, 0.0);\n        for (std::size_t i = 0; i < dofs.size(); ++i)\n        {\n            const PetscInt index = rhs.map_global_to_local_index(dofs[i]);\n            vec_array[index] += values_to_add[i];\n        }\n        rhs.restore_array();\n    }\n    else\n    {\n        rhs.add_vector(values_to_add.data(), dofs);\n    }\n}\n\nquadrature_key_type\ngetQuadratureKey(const libMesh::QuadratureType quad_type,\n                 libMesh::Order order,\n                 const bool use_adaptive_quadrature,\n                 const double point_density,\n                 const bool allow_rules_with_negative_weights,\n                 const libMesh::Elem* const elem,\n                 const boost::multi_array<double, 2>& X_node,\n                 const double dx_min)\n{\n    const libMesh::ElemType elem_type = elem->type();\n#ifndef NDEBUG\n    TBOX_ASSERT(elem->p_level() == 0); // higher levels are not implemented\n#endif\n    if (use_adaptive_quadrature)\n    {\n        const double hmax = get_max_edge_length(elem, X_node);\n        int npts = int(std::ceil(point_density * hmax / dx_min));\n        if (npts < 3)\n        {\n            if (elem->default_order() == libMesh::FIRST)\n                npts = 2;\n            else\n                npts = 3;\n        }\n        switch (quad_type)\n        {\n        case libMesh::QGAUSS:\n            order = static_cast<libMesh::Order>(std::min(2 * npts - 1, static_cast<int>(libMesh::FORTYTHIRD)));\n            break;\n        case libMesh::QGRID:\n            order = static_cast<libMesh::Order>(npts);\n            break;\n        default:\n            TBOX_ERROR(\"IBTK::getQuadratureKey():\\n\"\n                       << \"  adaptive quadrature rules are available only for quad_type = QGAUSS \"\n                          \"or QGRID\\n\");\n        }\n    }\n\n    return std::make_tuple(elem_type, quad_type, order, allow_rules_with_negative_weights);\n}\n\nvoid\nwrite_elem_partitioning(const std::string& file_name, const libMesh::System& position_system)\n{\n    const int current_rank = position_system.comm().rank();\n    const unsigned int position_system_n = position_system.number();\n    const libMesh::NumericVector<double>& local_position = *position_system.solution.get();\n    const libMesh::MeshBase& mesh = position_system.get_mesh();\n    const unsigned int spacedim = mesh.spatial_dimension();\n    // TODO: there is something wrong with the way we set up the ghost data in\n    // the position vectors: not all locally owned nodes are, in fact, locally\n    // available. Get around this by localizing first. Since all processes\n    // write to the same file this isn't the worst bottleneck in this\n    // function, anyway.\n    std::vector<double> position(local_position.size());\n    local_position.localize(position);\n    std::stringstream current_processor_output;\n\n    const auto end_elem = mesh.local_elements_end();\n    for (auto elem = mesh.local_elements_begin(); elem != end_elem; ++elem)\n    {\n        const unsigned int n_nodes = (*elem)->n_nodes();\n        libMesh::Point center;\n        // TODO: this is a bit crude: if we use isoparametric elements (e.g.,\n        // Tri6) then this is not a very accurate representation of the center\n        // of the element. We should replace this with something more accurate.\n        for (unsigned int node_n = 0; node_n < n_nodes; ++node_n)\n        {\n            const libMesh::Node& node = (*elem)->node_ref(node_n);\n            TBOX_ASSERT(node.n_vars(position_system_n) == spacedim);\n            for (unsigned int d = 0; d < spacedim; ++d)\n            {\n                center(d) += position[node.dof_number(position_system_n, d, 0)];\n            }\n        }\n        center *= 1.0 / n_nodes;\n\n        for (unsigned int d = 0; d < spacedim; ++d)\n        {\n            current_processor_output << center(d) << ',';\n        }\n        if (spacedim == 2)\n        {\n            current_processor_output << 0.0 << ',';\n        }\n        current_processor_output << current_rank << '\\n';\n    }\n\n    // clear the file before we append to it\n    if (current_rank == 0)\n    {\n        std::remove(file_name.c_str());\n    }\n    const int n_processes = position_system.comm().size();\n    for (int rank = 0; rank < n_processes; ++rank)\n    {\n        if (rank == current_rank)\n        {\n            std::ofstream out(file_name, std::ios_base::app);\n            if (rank == 0)\n            {\n                out << \"x,y,z,r\\n\";\n            }\n            out << current_processor_output.rdbuf();\n        }\n        position_system.comm().barrier();\n    }\n}\n\nvoid\nwrite_node_partitioning(const std::string& file_name, const libMesh::System& position_system)\n{\n    const int current_rank = position_system.comm().rank();\n    const unsigned int position_system_n = position_system.number();\n    const libMesh::NumericVector<double>& local_position = *position_system.solution.get();\n    const libMesh::MeshBase& mesh = position_system.get_mesh();\n    const unsigned int spacedim = mesh.spatial_dimension();\n\n    // TODO: there is something wrong with the way we set up the ghost data in\n    // the position vectors: not all locally owned nodes are, in fact,\n    // locally available. Get around this by localizing first. Since all\n    // processes write to the same file this isn't the worst bottleneck in\n    // this function, anyway.\n    std::vector<double> position(local_position.size());\n    local_position.localize(position);\n    std::stringstream current_processor_output;\n\n    const auto end_node = mesh.local_nodes_end();\n    for (auto node_it = mesh.local_nodes_begin(); node_it != end_node; ++node_it)\n    {\n        const libMesh::Node* const node = *node_it;\n        if (node->n_vars(position_system_n))\n        {\n            TBOX_ASSERT(node->n_vars(position_system_n) == spacedim);\n            for (unsigned int d = 0; d < spacedim; ++d)\n            {\n                current_processor_output << position[node->dof_number(position_system_n, d, 0)] << ',';\n            }\n            if (spacedim == 2)\n            {\n                current_processor_output << 0.0 << ',';\n            }\n            current_processor_output << current_rank << '\\n';\n        }\n    }\n\n    // clear the file before we append to it\n    if (current_rank == 0)\n    {\n        std::remove(file_name.c_str());\n    }\n    const int n_processes = position_system.comm().size();\n    for (int rank = 0; rank < n_processes; ++rank)\n    {\n        if (rank == current_rank)\n        {\n            std::ofstream out(file_name, std::ios_base::app);\n            if (rank == 0)\n            {\n                out << \"x,y,z,r\\n\";\n            }\n            out << current_processor_output.rdbuf();\n        }\n        position_system.comm().barrier();\n    }\n}\n\nstd::vector<libMeshWrappers::BoundingBox>\nget_local_element_bounding_boxes(const libMesh::MeshBase& mesh,\n                                 const libMesh::System& X_system,\n                                 const libMesh::QuadratureType quad_type,\n                                 const libMesh::Order quad_order,\n                                 const bool use_adaptive_quadrature,\n                                 const double point_density,\n                                 bool allow_rules_with_negative_weights,\n                                 const double patch_dx_min)\n{\n    const unsigned int dim = mesh.mesh_dimension();\n    const unsigned int spacedim = mesh.spatial_dimension();\n    TBOX_ASSERT(spacedim == NDIM);\n    const unsigned int X_sys_num = X_system.number();\n    auto X_ghost_vec_ptr = X_system.current_local_solution->zero_clone();\n    auto& X_ghost_vec = dynamic_cast<libMesh::PetscVector<double>&>(*X_ghost_vec_ptr);\n    X_ghost_vec = *X_system.solution;\n\n    std::vector<libMeshWrappers::BoundingBox> bboxes;\n\n    std::vector<std::vector<libMesh::dof_id_type> > dof_indices(NDIM);\n    boost::multi_array<double, 2> X_node;\n    QuadratureCache quad_cache(dim);\n    FECache fe_cache(dim, X_system.get_dof_map().variable_type(0), update_phi);\n    using quad_key_type = quadrature_key_type;\n    const auto el_begin = mesh.local_elements_begin();\n    const auto el_end = mesh.local_elements_end();\n    for (auto el_it = el_begin; el_it != el_end; ++el_it)\n    {\n        // 0. Set up bounding box\n        bboxes.emplace_back();\n        auto& box = bboxes.back();\n        libMesh::Point& lower_bound = box.first;\n        libMesh::Point& upper_bound = box.second;\n        for (unsigned int d = 0; d < LIBMESH_DIM; ++d)\n        {\n            lower_bound(d) = std::numeric_limits<double>::max();\n            upper_bound(d) = -std::numeric_limits<double>::max();\n        }\n\n        // As mentioned in the documentation of this function we do not set up\n        // bounding boxes for inactive elements\n        if (!(*el_it)->active()) continue;\n\n        // 1. extract node locations\n        const libMesh::Elem* const elem = *el_it;\n        const unsigned int n_nodes = elem->n_nodes();\n        for (unsigned int d = 0; d < NDIM; ++d) dof_indices[d].clear();\n\n        for (unsigned int k = 0; k < n_nodes; ++k)\n        {\n            const libMesh::Node* const node = elem->node_ptr(k);\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                TBOX_ASSERT(node->n_dofs(X_sys_num, d) == 1);\n                dof_indices[d].push_back(node->dof_number(X_sys_num, d, 0));\n            }\n        }\n        get_values_for_interpolation(X_node, X_ghost_vec, dof_indices);\n\n        // 2. compute mapped quadrature points in the deformed configuration\n        const quad_key_type key = getQuadratureKey(quad_type,\n                                                   quad_order,\n                                                   use_adaptive_quadrature,\n                                                   point_density,\n                                                   allow_rules_with_negative_weights,\n                                                   elem,\n                                                   X_node,\n                                                   patch_dx_min);\n        libMesh::QBase& quadrature = quad_cache[key];\n        libMesh::FEBase& fe = fe_cache(key, elem);\n        const std::vector<std::vector<double> >& phi_X = fe.get_phi();\n        const std::vector<libMesh::Point>& q_points = quadrature.get_points();\n        for (unsigned int qp = 0; qp < q_points.size(); ++qp)\n        {\n            libMesh::Point mapped_point;\n            for (unsigned int k = 0; k < n_nodes; ++k)\n            {\n                for (unsigned int d = 0; d < NDIM; ++d)\n                {\n                    mapped_point(d) += phi_X[k][qp] * X_node[k][d];\n                }\n            }\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                lower_bound(d) = std::min(lower_bound(d), mapped_point(d));\n                upper_bound(d) = std::max(upper_bound(d), mapped_point(d));\n            }\n\n            // fill extra dimension with 0.0, which is libMesh's convention\n            for (unsigned int d = NDIM; d < LIBMESH_DIM; ++d)\n            {\n                lower_bound(d) = 0.0;\n                upper_bound(d) = 0.0;\n            }\n        }\n    }\n\n    return bboxes;\n} // get_local_element_bounding_boxes\n\nstd::vector<libMeshWrappers::BoundingBox>\nget_local_element_bounding_boxes(const libMesh::MeshBase& mesh, const libMesh::System& X_system)\n{\n    const unsigned int spacedim = mesh.spatial_dimension();\n    TBOX_ASSERT(spacedim == NDIM);\n    const unsigned int X_sys_num = X_system.number();\n    auto X_ghost_vec_ptr = X_system.current_local_solution->zero_clone();\n    auto& X_ghost_vec = dynamic_cast<libMesh::PetscVector<double>&>(*X_ghost_vec_ptr);\n    X_ghost_vec = *X_system.solution;\n\n    std::vector<libMeshWrappers::BoundingBox> bboxes;\n    bboxes.reserve(mesh.n_local_elem());\n\n    std::vector<libMesh::dof_id_type> dof_indices;\n    std::vector<double> X_node;\n    const auto el_begin = mesh.local_elements_begin();\n    const auto el_end = mesh.local_elements_end();\n    for (auto el_it = el_begin; el_it != el_end; ++el_it)\n    {\n        const libMesh::Elem* const elem = *el_it;\n        const unsigned int n_nodes = elem->n_nodes();\n        bboxes.emplace_back();\n        auto& box = bboxes.back();\n        libMesh::Point& lower_bound = box.first;\n        libMesh::Point& upper_bound = box.second;\n        for (unsigned int d = 0; d < LIBMESH_DIM; ++d)\n        {\n            lower_bound(d) = std::numeric_limits<double>::max();\n            upper_bound(d) = -std::numeric_limits<double>::max();\n        }\n\n        // As mentioned in the documentation of this function we do not set up\n        // bounding boxes for inactive elements\n        if (!(*el_it)->active()) continue;\n\n        dof_indices.clear();\n        for (unsigned int k = 0; k < n_nodes; ++k)\n        {\n            const libMesh::Node* const node = elem->node_ptr(k);\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                TBOX_ASSERT(node->n_dofs(X_sys_num, d) == 1);\n                dof_indices.push_back(node->dof_number(X_sys_num, d, 0));\n            }\n        }\n\n        X_node.resize(dof_indices.size());\n        X_ghost_vec.get(dof_indices, X_node.data());\n        for (unsigned int k = 0; k < n_nodes; ++k)\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                const double& X = X_node[k * NDIM + d];\n                lower_bound(d) = std::min(lower_bound(d), X);\n                upper_bound(d) = std::max(upper_bound(d), X);\n            }\n        }\n\n        // fill extra dimension with 0.0, which is libMesh's convention\n        for (unsigned int d = NDIM; d < LIBMESH_DIM; ++d)\n        {\n            lower_bound(d) = 0.0;\n            upper_bound(d) = 0.0;\n        }\n    }\n\n    return bboxes;\n} // get_local_element_bounding_boxes\n\nstd::vector<libMeshWrappers::BoundingBox>\nget_global_element_bounding_boxes(const libMesh::MeshBase& mesh,\n                                  const std::vector<libMeshWrappers::BoundingBox>& local_bboxes)\n{\n    const std::size_t n_elem = mesh.n_elem();\n    std::vector<double> flattened_bboxes(2 * LIBMESH_DIM * n_elem);\n    std::size_t elem_n = 0;\n    const auto el_begin = mesh.local_elements_begin();\n    const auto el_end = mesh.local_elements_end();\n    for (auto el_it = el_begin; el_it != el_end; ++el_it)\n    {\n        const auto id = (*el_it)->id();\n        TBOX_ASSERT((2 * id + 2) * LIBMESH_DIM - 1 < flattened_bboxes.size());\n        for (unsigned int d = 0; d < LIBMESH_DIM; ++d)\n        {\n            flattened_bboxes[2 * id * LIBMESH_DIM + d] = local_bboxes[elem_n].first(d);\n            flattened_bboxes[(2 * id + 1) * LIBMESH_DIM + d] = local_bboxes[elem_n].second(d);\n        }\n        ++elem_n;\n    }\n    const int ierr = MPI_Allreduce(\n        MPI_IN_PLACE, flattened_bboxes.data(), flattened_bboxes.size(), MPI_DOUBLE, MPI_SUM, mesh.comm().get());\n    TBOX_ASSERT(ierr == 0);\n\n    std::vector<libMeshWrappers::BoundingBox> global_bboxes(n_elem);\n    for (unsigned int e = 0; e < n_elem; ++e)\n    {\n        for (unsigned int d = 0; d < LIBMESH_DIM; ++d)\n        {\n            global_bboxes[e].first(d) = flattened_bboxes[2 * e * LIBMESH_DIM + d];\n            global_bboxes[e].second(d) = flattened_bboxes[(2 * e + 1) * LIBMESH_DIM + d];\n        }\n    }\n    return global_bboxes;\n} // get_local_element_bounding_boxes\n\nstd::vector<libMeshWrappers::BoundingBox>\nget_global_element_bounding_boxes(const libMesh::MeshBase& mesh, const libMesh::System& X_system)\n{\n    static_assert(NDIM <= LIBMESH_DIM,\n                  \"NDIM should be no more than LIBMESH_DIM for this function to \"\n                  \"work correctly.\");\n    return get_global_element_bounding_boxes(mesh, get_local_element_bounding_boxes(mesh, X_system));\n} // get_global_element_bounding_boxes\n//////////////////////////////////////////////////////////////////////////////\n\n} // namespace IBTK\n\n//////////////////////////////////////////////////////////////////////////////\n", "meta": {"hexsha": "c2f315c391f7acdfa2f04a56498f514ced2c2e54", "size": 22405, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ibtk/src/utilities/libmesh_utilities.cpp", "max_stars_repo_name": "akashdhruv/IBAMR", "max_stars_repo_head_hexsha": "a2b47946d795fb5a40c181b43e44a6ec387585a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 264.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T12:11:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T13:10:37.000Z", "max_issues_repo_path": "ibtk/src/utilities/libmesh_utilities.cpp", "max_issues_repo_name": "akashdhruv/IBAMR", "max_issues_repo_head_hexsha": "a2b47946d795fb5a40c181b43e44a6ec387585a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1057.0, "max_issues_repo_issues_event_min_datetime": "2015-04-27T04:27:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:14:59.000Z", "max_forks_repo_path": "ibtk/src/utilities/libmesh_utilities.cpp", "max_forks_repo_name": "drwells/IBAMR", "max_forks_repo_head_hexsha": "0ceda3873405a35da4888c99e7d2b24d132f9071", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 126.0, "max_forks_repo_forks_event_min_datetime": "2015-02-13T15:36:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T21:59:50.000Z", "avg_line_length": 38.7629757785, "max_line_length": 118, "alphanum_fraction": 0.5887971435, "num_tokens": 5200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.29776811152754035}}
{"text": "// $Id$\n/*\n * This is an extensive modification by Greg Landrum of\n * pieces from several files in the vflib-2.0 distribution\n *\n * The initial version of the modifications was completed\n *   in April 2009.\n *\n * the original author of the vflib files is:\n *    Author: P. Foggia\n *  http://amalfi.dis.unina.it/graph/db/vflib-2.0/doc/vflib.html\n *\n */\n#include <boost/graph/adjacency_list.hpp>\n#include <vector>\n#include <algorithm>\n#include <cstring>\n\n#ifndef __BGL_VF2_SUB_STATE_H__\n#define __BGL_VF2_SUB_STATE_H__\n\nnamespace boost{\n  namespace detail {\n    typedef unsigned short node_id;\n    const node_id NULL_NODE=0xFFFF;\n    struct NodeInfo {\n      node_id id;\n      node_id in;\n      node_id out;\n    };\n\n    /**\n     * The ordering by in/out degree\n     */\n    static bool nodeInfoComp1(const NodeInfo &a, const NodeInfo &b) {\n      if(a.out < b.out) return true;\n      if(a.out > b.out) return false;\n      if(a.in < b.in) return true;\n      if(a.in > b.in) return false;\n      return false;\n    }\n\n    /**\n     * The ordering by frequency/valence.\n     * The frequency is in the out field, the valence in `in'.\n     */\n    static int nodeInfoComp2(const NodeInfo &a, const NodeInfo &b) {\n      if (!a.in && b.in ) return 1;\n      if (a.in && !b.in) return -1;\n      if (a.out < b.out) return -1;\n      if (a.out > b.out) return 1;\n      if( a.in < b.in ) return -1;\n      if (a.in > b.in) return 1;\n      return 0;\n    }\n\n    template <class Graph,class VertexDescr,class EdgeDescr> \n    VertexDescr getOtherIdx(const Graph &g,const EdgeDescr &edge,const VertexDescr &vertex) {\n      VertexDescr tmp=boost::source(edge,g);\n      if(tmp==vertex){\n        tmp=boost::target(edge,g);\n      }\n      return tmp;\n    }\n  \n    /*----------------------------------------------------\n     * Sorts the nodes of a graphs, returning a \n     * heap-allocated vector (using new) with the node ids\n     * in the proper orders.\n     * The sorting criterion takes into account:\n     *    1 - The number of nodes with the same in/out \n     *        degree.\n     *    2 - The valence of the nodes.\n     * The nodes at the beginning of the vector are\n     * the most singular, from which the matching should\n     * start.\n     *--------------------------------------------------*/\n    template <class Graph>\n    node_id* SortNodesByFrequency(const Graph *g) {\n      std::vector<NodeInfo> vect;\n      vect.reserve(boost::num_vertices(*g));\n      typename Graph::vertex_iterator bNode,eNode;\n      boost::tie(bNode,eNode) = boost::vertices(*g);\n      while(bNode!=eNode){\n        NodeInfo t;\n        t.id=vect.size();\n        t.in=boost::out_degree(*bNode,*g);// <- assuming undirected graph\n        t.out=boost::out_degree(*bNode,*g); \n        vect.push_back(t);\n        ++bNode;\n      }\n      std::sort(vect.begin(),vect.end(),nodeInfoComp1);\n    \n      unsigned int run=1;\n      for(unsigned int i=0; i<vect.size(); i+=run){\n        for(run=1; i+run<vect.size() && \n              vect[i+run].in==vect[i].in && \n              vect[i+run].out==vect[i].out;\n            ++run) \n          ;\n        for(unsigned int j=0; j<run; ++j) {\n          vect[i+j].in += vect[i+j].out;\n          vect[i+j].out=run;\n        }\n      }\n      std::sort(vect.begin(),vect.end(),nodeInfoComp2);\n    \n      node_id *nodes=new node_id[vect.size()];\n      for(unsigned int i=0; i<vect.size(); ++i){\n        nodes[i]=vect[i].id;\n      }\n    \n      return nodes;\n    }\n\n    /*----------------------------------------------------------\n     * class VF2SubState\n     * A representation of the SSS current state\n     ---------------------------------------------------------*/\n    template <class Graph,class VertexCompatible,class EdgeCompatible,class MatchChecking >\n    class VF2SubState\n    { \n    private:\n      Graph *g1, *g2;\n      VertexCompatible &vc;\n      EdgeCompatible &ec;\n      MatchChecking &mc;\n      unsigned int n1, n2;\n\n      unsigned int core_len, orig_core_len;\n      unsigned int added_node1;\n      unsigned int t1both_len, t2both_len;\n      unsigned int t1in_len, t1out_len; \n      unsigned int t2in_len, t2out_len; // Core nodes are also counted by these...\n      node_id *core_1;\n      node_id *core_2;\n      node_id *in_1;\n      node_id *in_2;\n      node_id *out_1;\n      node_id *out_2;\n\n      node_id *order;\n\n      long *share_count;\n      int *vs_compared;\n    \n    public:\n      VF2SubState(Graph *ag1, Graph *ag2,\n                  VertexCompatible &avc,\n                  EdgeCompatible &aec,\n                  MatchChecking &amc,\n                  bool sortNodes=false) : g1(ag1), g2(ag2), vc(avc), ec(aec), mc(amc),\n                                          n1(num_vertices(*ag1)),n2(num_vertices(*ag2)) {\n        if (sortNodes){\n          order = SortNodesByFrequency(ag1);\n        } else {\n          order = NULL;\n        }\n\n        core_len=orig_core_len=0;\n        t1both_len=t1in_len=t1out_len=0;\n        t2both_len=t2in_len=t2out_len=0;\n\n        added_node1=NULL_NODE;\n\n        core_1=new node_id[n1];\n        core_2=new node_id[n2];\n        in_1=new node_id[n1];\n        in_2=new node_id[n2];\n        out_1=new node_id[n1];\n        out_2=new node_id[n2];\n        share_count = new long;\n\n        for(unsigned int i=0; i<n1; i++){\n          core_1[i]=NULL_NODE;\n          in_1[i]=0;\n          out_1[i]=0;\n        }\n        for(unsigned int i=0; i<n2; i++){\n          core_2[i]=NULL_NODE;\n          in_2[i]=0;\n          out_2[i]=0;\n        }\n        vs_compared=0;\n        //vs_compared = new int[n1*n2];\n        //memset((void *)vs_compared,0,n1*n2*sizeof(int));\n        \n        //es_compared = new std::map<unsigned int,bool>();\n        *share_count = 1;\n      };\n\n      VF2SubState(const VF2SubState &state) :\n        g1(state.g1), g2(state.g2), vc(state.vc), ec(state.ec), mc(state.mc),\n        n1(state.n1),n2(state.n2), order(state.order),vs_compared(state.vs_compared)\n        //es_compared(state.es_compared)\n      {\n\n        core_len=orig_core_len=state.core_len;\n        t1in_len=state.t1in_len;\n        t1out_len=state.t1out_len;\n        t1both_len=state.t1both_len;\n        t2in_len=state.t2in_len;\n        t2out_len=state.t2out_len;\n        t2both_len=state.t2both_len;\n\n        added_node1=NULL_NODE;\n\n        core_1=state.core_1;\n        core_2=state.core_2;\n        in_1=state.in_1;\n        in_2=state.in_2;\n        out_1=state.out_1;\n        out_2=state.out_2;\n        share_count=state.share_count;\n\n        ++(*share_count);\n      };\n\n      ~VF2SubState(){\n        if (-- *share_count == 0) {\n          delete [] core_1;\n          delete [] core_2;\n          delete [] in_1;\n          delete [] out_1;\n          delete [] in_2;\n          delete [] out_2;\n          delete share_count;\n          delete [] order;\n          //delete [] vs_compared;\n          //delete es_compared;\n        }\n      }; \n\n      bool IsGoal() { return core_len==n1 ; };\n      bool MatchChecks(const node_id c1[],const node_id c2[]){\n        return mc(c1,c2);\n      };\n      bool IsDead() { return n1>n2  || \n          t1both_len>t2both_len ||\n          t1out_len>t2out_len ||\n          t1in_len>t2in_len;\n      };\n      unsigned int CoreLen() { return core_len; }\n      Graph *GetGraph1() { return g1; }\n      Graph *GetGraph2() { return g2; }\n\n      bool NextPair(node_id *pn1, node_id *pn2,\n                    node_id prev_n1=NULL_NODE, node_id prev_n2=NULL_NODE){\n        if (prev_n1==NULL_NODE)\n          prev_n1=0;\n        if (prev_n2==NULL_NODE)\n          prev_n2=0;\n        else\n          prev_n2++;\n\n#if 0\n    std::cerr<<\" **** np: \"<< prev_n1<<\",\"<<prev_n2<<std::endl;\n    std::cerr<<\"in_1 \";\n    for(unsigned int i=0;i<n1;++i){\n      std::cerr<<\"(\"<<in_1[i]<<\",\"<<out_1[i]<<\"), \";\n    } \n    std::cerr<<std::endl;\n    std::cerr<<\"in_2 \";\n    for(unsigned int i=0;i<n2;++i){\n      std::cerr<<\"(\"<<in_2[i]<<\",\"<<out_2[i]<<\"), \";\n    } \n    std::cerr<<std::endl;\n#endif\n        if (t1both_len>core_len && t2both_len>core_len) {\n          while (prev_n1<n1 &&\n                 (core_1[prev_n1]!=NULL_NODE || out_1[prev_n1]==0\n                  || in_1[prev_n1]==0) ) {\n            prev_n1++;    \n            prev_n2=0;\n          }\n        }\n        else if (t1out_len>core_len && t2out_len>core_len) {\n          while (prev_n1<n1 &&\n                 (core_1[prev_n1]!=NULL_NODE || out_1[prev_n1]==0) ){\n            prev_n1++;    \n            prev_n2=0;\n          }\n        }\n        else if (t1in_len>core_len && t2in_len>core_len) {\n          while (prev_n1<n1 &&\n                 (core_1[prev_n1]!=NULL_NODE || in_1[prev_n1]==0) ) {\n            prev_n1++;    \n            prev_n2=0;\n          }\n        }\n        else if (prev_n1==0 && order!=NULL) {\n          unsigned int i=0;\n          while (i<n1 && core_1[prev_n1=order[i]] != NULL_NODE)\n            i++;\n          if (i==n1)\n            prev_n1=n1;\n        }\n        else {\n          while (prev_n1<n1 && core_1[prev_n1]!=NULL_NODE ){\n            prev_n1++;    \n            prev_n2=0;\n          }\n        }\n\n        if (t1both_len>core_len && t2both_len>core_len) {\n          while (prev_n2<n2 &&\n                 (core_2[prev_n2]!=NULL_NODE || out_2[prev_n2]==0\n                  || in_2[prev_n2]==0) ) {\n            prev_n2++;    \n          }\n        }\n        else if (t1out_len>core_len && t2out_len>core_len) {\n          while (prev_n2<n2 &&\n                 (core_2[prev_n2]!=NULL_NODE || out_2[prev_n2]==0) ) {\n            prev_n2++;    \n          }\n        }\n        else if (t1in_len>core_len && t2in_len>core_len) {\n          while (prev_n2<n2 &&\n                 (core_2[prev_n2]!=NULL_NODE || in_2[prev_n2]==0) ) {\n            prev_n2++;    \n          }\n        }\n        else {\n          while (prev_n2<n2 && core_2[prev_n2]!=NULL_NODE ){\n            prev_n2++;    \n          }\n        }\n        //std::cerr<<\" \"<< prev_n1<<\"<\"<<n1<<\" \"<<prev_n2<<\"<\"<<n2;\n        if (prev_n1<n1 && prev_n2<n2) {\n          *pn1=prev_n1;\n          *pn2=prev_n2;\n          //std::cerr<<\"  Found\"<<std::endl;\n          return true;\n        }\n        //std::cerr<<\"  nope\"<< std::endl;\n        return false;\n      };\n      bool IsFeasiblePair(node_id node1, node_id node2){\n        assert(node1 < n1);\n        assert(node2 < n2);\n        assert(core_1[node1] == NULL_NODE);\n        assert(core_2[node2] == NULL_NODE);\n\n        //std::cerr<<\"  ifp:\"<<node1<<\"-\"<<node2<<\" \"<<vs_compared->size()<<std::endl;\n        // int &isCompat=vs_compared[node1*n2+node2];\n        // if(isCompat==0){\n        //   isCompat=vc(node1,node2)?1:-1;\n        // }\n        // if( isCompat<0 ){\n        //   //std::cerr<<\"  short1\"<<std::endl;\n        //   return false;\n        // }\n        if(!vc(node1,node2)) return false;\n\n        unsigned int other1, other2;\n        unsigned int termout1 = 0, termout2 = 0, termin1 = 0, termin2 = 0;\n        unsigned int new1 = 0, new2 = 0;\n\n        // Check the out edges of node1\n        typename Graph::out_edge_iterator bNbrs,eNbrs;\n        boost::tie(bNbrs,eNbrs) = boost::out_edges(node1,*g1);\n        while(bNbrs!=eNbrs){\n          other1=getOtherIdx(*g1,*bNbrs,node1);\n          if (core_1[other1] != NULL_NODE) {\n            other2 = core_1[other1];\n            typename Graph::edge_descriptor oEdge;\n            bool found;\n            boost::tie(oEdge,found) = boost::edge(node2,other2,*g2);\n            if(!found || !ec(*bNbrs,oEdge) ){\n              //std::cerr<<\"  short2\"<<std::endl;\n              return false;\n            }\n          } else {\n            if (in_1[other1]) ++termin1;\n            if (out_1[other1]) ++termout1;\n            if (!in_1[other1] && !out_1[other1]) ++new1;\n          }\n          ++bNbrs;\n        }\n\n        // Check the out edges of node2\n        boost::tie(bNbrs,eNbrs) = boost::out_edges(node2,*g2);\n        while(bNbrs!=eNbrs){\n          other2=getOtherIdx(*g2,*bNbrs,node2);\n          if (core_2[other2] != NULL_NODE) {\n            // do nothing\n          } else {\n            if (in_2[other2]) ++termin2;\n            if (out_2[other2]) ++termout2;\n            if (!in_2[other2] && !out_2[other2]) ++new2;\n          }\n          ++bNbrs;\n        }\n        //std::cerr<<(termin1 <= termin2 && termout1 <= termout2 && (termin1+termout1+new1)<=(termin2+termout2+new2))<<std::endl;\n\n        return termin1 <= termin2 && termout1 <= termout2 && (termin1+termout1+new1)<=(termin2+termout2+new2);\n      };\n      void AddPair(node_id node1, node_id node2){\n        assert(node1 < n1);\n        assert(node2 < n2);\n        assert(core_len < n1);\n        assert(core_len < n2);\n\n        ++core_len;\n        added_node1 = node1;\n\n        if (!in_1[node1]) {\n          in_1[node1] = core_len;\n          ++t1in_len;\n          if (out_1[node1]) ++t1both_len;\n        }\n        if (!out_1[node1]) {\n          out_1[node1] = core_len;\n          ++t1out_len;\n          if (in_1[node1]) ++t1both_len;\n        }\n\n        if (!in_2[node2]) {\n          in_2[node2] = core_len;\n          ++t2in_len;\n          if (out_2[node2]) ++t2both_len;\n        }\n        if (!out_2[node2]) {\n          out_2[node2] = core_len;\n          ++t2out_len;\n          if (in_2[node2]) ++t2both_len;\n        }\n\n        core_1[node1] = node2;\n        core_2[node2] = node1;\n\n        typename Graph::out_edge_iterator bNbrs,eNbrs;\n        // FIX: this is explicitly ignoring directionality\n        boost::tie(bNbrs,eNbrs) = boost::out_edges(node1,*g1);\n        while(bNbrs!=eNbrs){\n          unsigned int other = getOtherIdx(*g1,*bNbrs,node1);\n          if (!in_1[other]) {\n            in_1[other] = core_len;\n            ++t1in_len;\n            if (out_1[other])  ++t1both_len;\n          }\n          if (!out_1[other]) {\n            out_1[other] = core_len;\n            ++t1out_len;\n            if (in_1[other])  ++t1both_len;\n          }\n          ++bNbrs;\n        }\n\n        // FIX: this is explicitly ignoring directionality\n        boost::tie(bNbrs,eNbrs) = boost::out_edges(node2,*g2);\n        while(bNbrs!=eNbrs){\n          unsigned int other = getOtherIdx(*g2,*bNbrs,node2);\n          if (!in_2[other]) {\n            in_2[other] = core_len;\n            ++t2in_len;\n            if (out_2[other]) ++t2both_len;\n          }\n          if (!out_2[other]) {\n            out_2[other] = core_len;\n            ++t2out_len;\n            if (in_2[other]) ++t2both_len;\n          }\n          ++bNbrs;\n        }\n      };\n      void GetCoreSet(node_id c1[], node_id c2[]){\n        unsigned int i, j;\n        for (i = 0, j = 0; i < n1; ++i){\n          if (core_1[i] != NULL_NODE) {\n            c1[j] = i;\n            c2[j] = core_1[i];\n            ++j;\n          }\n        }\n    \n      };\n      VF2SubState *Clone(){\n        return new VF2SubState(*this);\n      };\n      void BackTrack(){\n        assert(core_len - orig_core_len <= 1);\n        assert(added_node1 != NULL_NODE);\n\n        if (orig_core_len < core_len) {\n\n          if (in_1[added_node1] == core_len) in_1[added_node1] = 0;\n          if (out_1[added_node1] == core_len)  out_1[added_node1] = 0;\n\n          typename Graph::out_edge_iterator bNbrs,eNbrs;\n          boost::tie(bNbrs,eNbrs) = boost::out_edges(added_node1,*g1);\n          while(bNbrs!=eNbrs){\n            unsigned int other = getOtherIdx(*g1,*bNbrs,added_node1);\n            if (out_1[other] == core_len) out_1[other] = 0;\n            if (in_1[other] == core_len) in_1[other] = 0;\n            ++bNbrs;\n          }\n\n          unsigned int node2 = core_1[added_node1];\n          if (in_2[node2] == core_len) in_2[node2] = 0;\n          if (out_2[node2] == core_len) out_2[node2] = 0;\n\n          boost::tie(bNbrs,eNbrs) = boost::out_edges(node2,*g2);\n          while(bNbrs!=eNbrs){\n            unsigned int other = getOtherIdx(*g2,*bNbrs,node2);\n            if (out_2[other] == core_len) out_2[other] = 0;\n            if (in_2[other] == core_len) in_2[other] = 0;\n            ++bNbrs;\n          }\n\n          core_1[added_node1] = NULL_NODE;\n          core_2[node2] = NULL_NODE;\n\n          core_len = orig_core_len;\n          added_node1 = NULL_NODE;\n        }\n      };\n    };\n\n    /*-------------------------------------------------------------\n     * static bool match(pn, c1, c2, s)\n     * Finds a matching between two graphs, if it exists, starting\n     * from state s.\n     * Returns true a match has been found.\n     * *pn is assigned the numbero of matched nodes, and\n     * c1 and c2 will contain the ids of the corresponding nodes \n     * in the two graphs.\n     ------------------------------------------------------------*/\n    template <class SubState>\n    bool match(int *pn, node_id c1[], node_id c2[], SubState &s)\n    {\n      if (s.IsGoal() ) { \n        s.GetCoreSet(c1, c2);\n        if(s.MatchChecks(c1,c2)) {\n          *pn=s.CoreLen();\n          return true;\n        }\n      }\n\n      if (s.IsDead())\n        return false;\n      //std::cerr<<\"  > match: \"<<*pn<<\" \"<<&s<<std::endl;\n      node_id n1=NULL_NODE, n2=NULL_NODE;\n      bool found=false;\n      while (!found && s.NextPair(&n1, &n2, n1, n2)) {\n        //std::cerr<<\"           \"<<n1<<\",\"<<n2<<std::endl;\n        if (s.IsFeasiblePair(n1, n2)){\n          SubState *s1=s.Clone();\n          s1->AddPair(n1, n2);\n          found=match(pn, c1, c2, *s1);\n          s1->BackTrack();\n          delete s1;\n        }\n      }\n      //std::cerr<<\"  < returning: \"<<found<<\" \"<<*pn<<\" \"<<&s<<std::endl;\n      return found;\n    }\n\n    /*-------------------------------------------------------------\n     * static bool match(c1, c2, vis, usr_data, pcount)\n     * Visits all the matchings between two graphs,  starting\n     * from state s.\n     * Returns true if the caller must stop the visit.\n     * Stops when there are no more matches\n     *\n     ------------------------------------------------------------*/\n    template <class SubState,class DoubleBackInsertionSequence>\n    bool match(node_id c1[], node_id c2[], SubState &s, DoubleBackInsertionSequence &res,\n               unsigned int max_results) {\n      if (s.IsGoal()){\n        s.GetCoreSet(c1, c2);\n        if(s.MatchChecks(c1,c2)) {\n          typename DoubleBackInsertionSequence::value_type newSeq;\n          for(unsigned int i=0;i<s.CoreLen();++i){\n            newSeq.push_back(std::pair<int,int>(c1[i],c2[i]));\n          }\n          res.push_back(newSeq);\n          if(res.size()>=max_results) return true;\n        }\n        return false;\n      }\n\n      if (s.IsDead())\n        return false;\n\n      node_id n1=NULL_NODE, n2=NULL_NODE;\n      while (s.NextPair(&n1, &n2, n1, n2)) {\n        if (s.IsFeasiblePair(n1, n2)){\n          SubState *s1=s.Clone();\n          s1->AddPair(n1, n2);\n          if (match(c1, c2, *s1,res,max_results)){\n            s1->BackTrack(); \n            delete s1;\n            return true;\n          }\n          else {\n            s1->BackTrack(); \n            delete s1;\n          }\n        }\n      }\n      return false;\n    }\n  }; //end of namespace detail\n\n  template <  class Graph\n              , class VertexLabeling    // binary predicate\n              , class EdgeLabeling      // binary predicate\n              , class MatchChecking      // binary predicate\n              , class BackInsertionSequence   // contains std::pair<vertex_descriptor,vertex_descriptor>\n              >\n  bool vf2(const Graph &g1,const Graph &g2,\n           VertexLabeling& vertex_labeling,\n           EdgeLabeling& edge_labeling,\n           MatchChecking& match_checking,\n           BackInsertionSequence& F){\n    detail::VF2SubState<const Graph,VertexLabeling,EdgeLabeling,MatchChecking> s0(&g1,&g2,vertex_labeling,\n                                                                                  edge_labeling,match_checking,false);\n    detail::node_id *ni1 = new detail::node_id[num_vertices(g1)];\n    detail::node_id *ni2 = new detail::node_id[num_vertices(g2)];\n    int n=0;\n    \n    F.clear();\n    F.resize(0);\n    if(match(&n,ni1,ni2,s0)){\n      for(unsigned int i=0;i<num_vertices(g1);i++){\n        F.push_back(std::pair<int,int>(ni1[i],ni2[i]));\n      }\n    }\n    delete [] ni1;\n    delete [] ni2;\n    \n    return !F.empty();\n  };\n  template <  class Graph\n              , class VertexLabeling    // binary predicate\n              , class EdgeLabeling      // binary predicate\n              , class MatchChecking      // binary predicate\n              , class DoubleBackInsertionSequence   // contains a back insertion sequence\n              >\n  bool vf2_all(const Graph& g1, const Graph& g2,\n               VertexLabeling& vertex_labeling,\n               EdgeLabeling& edge_labeling,\n               MatchChecking& match_checking,\n               DoubleBackInsertionSequence& F,\n               unsigned int max_results=1000) {\n    detail::VF2SubState<const Graph,VertexLabeling,EdgeLabeling,MatchChecking> s0(&g1,&g2,vertex_labeling,\n                                                                                  edge_labeling,match_checking,false);\n    detail::node_id *ni1 = new detail::node_id[num_vertices(g1)];\n    detail::node_id *ni2 = new detail::node_id[num_vertices(g2)];\n    \n    F.clear();\n    F.resize(0);\n\n    match(ni1,ni2,s0,F,max_results);\n\n    delete [] ni1;\n    delete [] ni2;\n    \n    return !F.empty();\n  };\n} // end of namespace boost\n#endif\n\n", "meta": {"hexsha": "31b7663d8f7101dc8b94f982f94ef8577fc5c2ff", "size": 21107, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modified_rdkit/Code/GraphMol/Substruct/vf2.hpp", "max_stars_repo_name": "hjuinj/RDKit_mETKDG", "max_stars_repo_head_hexsha": "b270e765caa61d289e9e33595d4264b156f9062e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-03-30T04:00:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-31T01:32:13.000Z", "max_issues_repo_path": "modified_rdkit/Code/GraphMol/Substruct/vf2.hpp", "max_issues_repo_name": "hjuinj/RDKit_mETKDG", "max_issues_repo_head_hexsha": "b270e765caa61d289e9e33595d4264b156f9062e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-23T17:31:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-26T06:52:47.000Z", "max_forks_repo_path": "modified_rdkit/Code/GraphMol/Substruct/vf2.hpp", "max_forks_repo_name": "hjuinj/RDKit_mETKDG", "max_forks_repo_head_hexsha": "b270e765caa61d289e9e33595d4264b156f9062e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-03-30T04:00:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-25T23:11:52.000Z", "avg_line_length": 31.6921921922, "max_line_length": 129, "alphanum_fraction": 0.5114417018, "num_tokens": 6010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.29776811152754035}}
{"text": "// Ultra fast anagram generator\n\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <codecvt>\n#include <fstream>\n#include <ios>\n#include <iostream>\n#include <limits>\n#include <locale>\n#include <numeric>\n#include <optional>\n#include <sstream>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include <boost/functional/hash.hpp>\n#include <boost/program_options.hpp>\n\n#include <unicode/stringoptions.h>\n#include <unicode/uchar.h>\n#include <unicode/unistr.h>\n#include <unicode/ustream.h>\n#include <unicode/utypes.h>\n\nusing std::bitset;\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::forward;\nusing std::ifstream;\nusing std::ios;\nusing std::nullopt;\nusing std::optional;\nusing std::ostream;\nusing std::ostringstream;\nusing std::pair;\nusing std::string;\nusing std::tie;\nusing std::unordered_map;\nusing std::vector;\n\nusing boost::hash_range;\nusing icu::UnicodeString;\n\ntypedef unsigned __int128 bigint;\n\nnamespace po = boost::program_options;\n\n// total maximum of letters in input\nconstexpr int MAX_LETTERS = 128;\n\ntypedef uint8_t CharIdx;\nconstexpr int MAX_CHARIDX = std::numeric_limits<CharIdx>::max();\n\n// first 168 primes\nconstexpr int PRIMES[] = {\n    2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,\n    73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,\n    157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233,\n    239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,\n    331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419,\n    421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,\n    509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607,\n    613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,\n    709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811,\n    821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,\n    919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997\n};\n\n// If the given function returns false, terminate.\ntemplate <typename Fn>\nbool forAllAlpha(const UnicodeString &s, Fn &&f) {\n    for (int j = 0, je = s.length(); j<je; j++) {\n        UChar c = s[j];\n        if (u_isUAlphabetic(c)) {\n            if (!f(c))\n                return false;\n        }\n    }\n    return true;\n}\n\n// We map the characters in the input to integers starting from 0 (and\n// that must fit in CharIdx).\ntypedef unordered_map<UChar, int> CharMap;\n\nstatic size_t hash_bigint(const bigint &m) {\n    // Let's decide the lowest bits are good enough, even though it's\n    // guaranteed we have count(most_common_letter) trailing zero\n    // bits.\n    return static_cast<size_t>(m);\n}\n\n// A multiset of characters.\n//\n// The allowable characters are passed in the CharMap, which maps\n// unicode characters to integers starting from 0.\n//\n// To facilitate the required multiset operations, namely subtraction\n// and subset testing, we map a multiset to an integer (which may not\n// fit in a fixed size integer type)\n//\n//    product(nth_prime(i)**char_count(i)).\n//\n// Now,\n//\n// * x is a subset of y iff x.num % y.num == 0\n// * x-y maps to integer division.\n//\n// The order of characters is chosen such that the most common\n// characters in the input map to smallest primes, which results in\n// smallest numbers.\nclass CharBag {\npublic:\n    static optional<CharBag> fromUString(const UnicodeString &str, const CharMap &charmap);\n    static optional<CharBag> fromLowerUString(const UnicodeString &str, const CharMap &charmap);\n    static optional<CharBag> fromNativeString(const string &str, const CharMap &charmap) {\n        return fromUString(UnicodeString(str.c_str()), charmap);\n    }\n    const bigint &num() const { return m_num; }\n    const int size() const { return m_size; }\n    size_t hash() const { return m_hash; }\n\n    bool empty() const { return m_size == 0; }\n\n    bool isSubsetOf(const CharBag &other) const {\n        auto cs_opt = other-*this;\n        return (bool)cs_opt;\n    }\n\n    optional<CharBag> operator-(const CharBag &rhs) const;\n    bool operator==(const CharBag &rhs) const;\nprivate:\n    CharBag(bigint num, int size) :\n        m_num(num), m_size(size), m_hash(compute_hash(m_size, m_num)) {}\n\n    static size_t compute_hash(const int &size, const bigint &num) {\n        // As a hack to find words faster, we want longer words to map\n        // to smaller hashes. Do this by mapping negated size to the\n        // high bits of the hash.\n        constexpr int bits = std::numeric_limits<size_t>::digits;\n        size_t hi = (~static_cast<size_t>(size)) << (bits-7);\n        size_t lo = hash_bigint(num) & ((size_t(1) << (bits-7)) - 1);\n        return hi | lo;\n    }\n\n    bigint m_num;\n    int m_size;\n    size_t m_hash;\n};\n\nnamespace std {\n  template <> struct hash<CharBag> {\n    size_t operator()(const CharBag &cs) const {\n        return cs.hash();\n    }\n  };\n}\n\nbool CharBag::operator==(const CharBag &rhs) const {\n    return m_hash == rhs.m_hash && m_num == rhs.m_num;\n}\n\noptional<CharBag> CharBag::operator-(const CharBag &rhs) const {\n    if (rhs.m_size > m_size)\n        return nullopt;\n\n    if (m_size == rhs.m_size && m_num == rhs.m_num)\n        return CharBag{bigint(1), 0};\n\n    // if (!mpz_divisible_p(m_num.get_mpz_t(), rhs.m_num.get_mpz_t()))\n    //  return nullopt;\n    if (m_num % rhs.m_num != 0)\n        return nullopt;\n\n    return CharBag{m_num/rhs.m_num, m_size-rhs.m_size};\n}\n\noptional<CharBag> CharBag::fromLowerUString(const UnicodeString &str, const CharMap &charmap) {\n    bigint n(1);\n    int size = 0;\n\n    static_assert(sizeof(PRIMES)/sizeof(PRIMES[0]) >= MAX_LETTERS);\n\n    if (forAllAlpha(str, [&n, &size, &charmap](UChar c) {\n            auto it = charmap.find(c);\n            if (it == charmap.end())\n                return false;\n            int idx = it->second;\n            assert(idx < MAX_LETTERS);\n            n *= PRIMES[idx];\n            ++size;\n            return true;\n            })) {\n        return CharBag(n, size);\n    } else\n        return nullopt;\n}\n\noptional<CharBag> CharBag::fromUString(const UnicodeString &str_, const CharMap &charmap) {\n    UnicodeString str(str_);\n    str.toLower();\n    return fromLowerUString(str, charmap);\n}\n\n// [[maybe_unused]]\n// static ostream &operator<<(ostream &os, const CharBag &cs) {\n//     return os << \"CharBag{\" << cs.size() << \", \" << cs.num() << \"}\";\n// }\n\n// [[maybe_unused]]\n// static ostream &operator<<(ostream &os, const optional<CharBag> &cs) {\n//     if (cs)\n//      os << *cs;\n//     else\n//      os << \"nil\";\n//     return os;\n// }\n\n// from https://stackoverflow.com/questions/17074324/\ntemplate <typename T>\nvoid apply_permutation_in_place(std::vector<T>& vec,\n                                const std::vector<std::size_t>& p) {\n    std::vector<bool> done(vec.size());\n    for (std::size_t i = 0; i < vec.size(); ++i) {\n        if (done[i])\n            continue;\n        done[i] = true;\n        std::size_t prev_j = i;\n        std::size_t j = p[i];\n        while (i != j) {\n            std::swap(vec[prev_j], vec[j]);\n            done[j] = true;\n            prev_j = j;\n            j = p[j];\n        }\n    }\n}\n\nstatic vector<char> slurp(const string &fileName) {\n    ifstream ifs(fileName.c_str(), ios::binary | ios::ate);\n\n    ifstream::pos_type size = ifs.tellg();\n    ifs.seekg(0, ios::beg);\n\n    vector<char> bytes(size);\n    ifs.read(bytes.data(), size);\n\n    return bytes;\n}\n\n// The dictionary words are sorted by length (number of alphabetic\n// characters). This is important, it's used in\n// forAllAnagrams_iter_last().\nstatic pair<vector<vector<string>>, vector<CharBag>> loadDictionary(\n    const string &fname, const CharBag &cset, const CharMap &cmap) {\n    const auto raw_contents = slurp(fname);\n    UnicodeString contents = UnicodeString(raw_contents.data(), raw_contents.size());\n    contents.toLower();\n    size_t contents_len = contents.length();\n\n    vector<vector<string>> words;\n    vector<CharBag> charbags;\n    unordered_map<CharBag, size_t> charbag_map;\n\n    size_t count = 0;\n\n    size_t line_start = 0;\n    while (true) {\n        auto newline = contents.indexOf(UChar('\\n'), line_start);\n\n        size_t endpos;\n        if (newline == -1)\n            endpos = contents_len;\n        else\n            endpos = newline;\n\n        auto str_len = endpos - line_start;\n        auto line = contents.tempSubString(line_start, str_len);\n        if (str_len > 0) {\n            optional<CharBag> cs = CharBag::fromLowerUString(line, cmap);\n            if (cs && cset - *cs) {\n                if (cs->empty())\n                    continue;\n                ++count;\n\n                ostringstream line_sstream;\n                line_sstream << line;\n\n                auto it = charbag_map.find(*cs);\n                if (it == charbag_map.end()) {\n                    words.emplace_back(vector<string>{{line_sstream.str()}});\n                    charbags.emplace_back(*cs);\n                    charbag_map[*cs] = words.size()-1;\n                } else\n                    words[it->second].emplace_back(line_sstream.str());\n            }\n        }\n        if (newline == -1)\n            break;\n        else\n            line_start = newline+1;\n    }\n\n    // Sort the words by charbag hash.\n\n    vector<size_t> hash_sort_order(charbags.size());\n    std::iota(hash_sort_order.begin(), hash_sort_order.end(), 0);\n\n    std::sort(hash_sort_order.begin(), hash_sort_order.end(),\n              [&charbags](int a, int b) { return charbags[a].hash() < charbags[b].hash(); });\n\n    apply_permutation_in_place(words, hash_sort_order);\n    apply_permutation_in_place(charbags, hash_sort_order);\n\n    //cerr << \"Loaded \" << count << \" dictionary words, \" << words.size() << \" distinct.\" << endl;\n    return {words, charbags};\n}\n\ntemplate <typename Fn>\nvoid forAllAnagrams_iter_last(const vector<CharBag> &dict_charbags,\n                              const vector<int> &possible_charbags,\n                              const CharBag &charbag, Fn &&f,\n                              vector<size_t> &words, size_t start_idx) {\n    size_t required_hash = charbag.hash();\n\n    auto compare_charbags = [&dict_charbags, required_hash](const int a, const int b) {\n        size_t a_hash, b_hash;\n\n        // FIXME how to do this properly? This is really ugly.\n        if (a == -1)\n            a_hash = required_hash;\n        else\n            a_hash = dict_charbags[a].hash();\n        if (b == -1)\n            b_hash = required_hash;\n        else\n            b_hash = dict_charbags[b].hash();\n\n        return a_hash < b_hash;\n    };\n\n    {\n        auto it = std::lower_bound(possible_charbags.begin() + start_idx,\n                                   possible_charbags.end(), -1, compare_charbags);\n\n        for (auto ie = possible_charbags.end();\n             it != ie && dict_charbags[*it].hash() == required_hash; ++it)\n            if (charbag == dict_charbags[*it]) {\n                words.emplace_back(*it);\n                f(words);\n                words.pop_back();\n                // There's at most one hit, and we found one.\n                return;\n            }\n    }\n}\n\ntemplate <typename Fn>\nvoid forAllAnagrams_iter(const vector<CharBag> &dict_charbags,\n                         const vector<int> &old_possible_charbags,\n                         const CharBag &charbag, Fn &&f,\n                         vector<size_t> &words, size_t start_idx, int curr_len, int max_len) {\n    if (curr_len+1 >= max_len) {\n        forAllAnagrams_iter_last(dict_charbags, old_possible_charbags, charbag, f,\n                                 words, start_idx);\n        return;\n    }\n    vector<int> possible_charbags;\n    for (int i = start_idx, ie = old_possible_charbags.size(); i<ie; i++)\n        if (dict_charbags[old_possible_charbags[i]].isSubsetOf(charbag))\n            possible_charbags.emplace_back(old_possible_charbags[i]);\n\n    for (int i = 0, ie = possible_charbags.size(); i<ie; i++) {\n        auto cs = (charbag - dict_charbags[possible_charbags[i]]).value();\n        words.emplace_back(possible_charbags[i]);\n        if (cs.empty())\n            f(words);\n        else\n            forAllAnagrams_iter(dict_charbags, possible_charbags,\n                                cs, forward<Fn>(f), words, i, curr_len+1, max_len);\n        words.pop_back();\n    }\n}\n\ntemplate <typename Fn>\nvoid forAllAnagrams(const vector<CharBag> &dict_charbags, const CharBag &charbag,\n                    int max_len, Fn &&f) {\n    vector<size_t> words;\n    vector<int> possible_charbags(dict_charbags.size());\n    std::iota(possible_charbags.begin(), possible_charbags.end(), 0);\n    forAllAnagrams_iter(dict_charbags, possible_charbags,\n                        charbag, forward<Fn>(f), words, 0, 0, max_len);\n}\n\n// The words vector contains vectors of anagram-equivalent words.\n// Output all possible combinations of them.\nstatic void outputWords(ostream &stream, const vector<size_t> &word_idxs,\n                        const vector<vector<string>> &words) {\n    int size = word_idxs.size();\n    vector<size_t> idxs(size);\n\n    while (true) {\n        stream << words[word_idxs[0]][idxs[0]];\n        for (int i = 1; i<size; i++)\n            stream << \" \" << words[word_idxs[i]][idxs[i]];\n        stream << endl;\n\n        // increment\n        int curr = size-1;\n        while (curr >= 0 && ++idxs[curr] == words[word_idxs[curr]].size()) {\n            idxs[curr] = 0;\n            curr--;\n        }\n        if (curr < 0)\n            break;\n    }\n}\n\nstatic void usage(char * const *argv, po::options_description &visible) {\n    cout << \"Usage: \" << argv[0] << \" [options] sentence\" << endl;\n    cout << visible << endl;\n    exit(0);\n}\n\nstatic po::variables_map parse_args(int argc, char * const *argv) {\n    bool help = false;\n\n    po::options_description visible(\"Allowed options\"), cmdline_opt;\n    visible.add_options()\n        (\"help,h\", po::bool_switch(&help)->default_value(false), \"show this help\")\n        (\"dict,d\", po::value<string>()->default_value(\"words.txt\"),\n         \"dictionary (word list) to use\")\n        (\"len,l\", po::value<int>()->default_value(3), \"maximum anagram length in words\")\n        (\"remove,r\", po::value<string>()->default_value(\"\"),\n         \"remove characters from input (find anagrams containing given string)\");\n\n    po::options_description hidden;\n    hidden.add_options()\n        (\"sentence\", po::value<string>()->required(), \"sentence\");\n\n    cmdline_opt.add(visible).add(hidden);\n\n    po::positional_options_description p;\n    p.add(\"sentence\", 1);\n\n    po::variables_map vm;\n    try {\n        po::store(po::command_line_parser(argc, argv).options(cmdline_opt).positional(p).run(), vm);\n        po::notify(vm);\n    } catch (po::error &) {\n        help = true;\n    }\n\n    if (help)\n        usage(argv, visible);\n\n    return vm;\n}\n\nCharMap generateCharMap(const UnicodeString &input) {\n    CharMap charmap;\n\n    unordered_map<UChar, int> char_counts;\n\n    forAllAlpha(input, [&char_counts](UChar c) {\n            ++char_counts[c];\n            return true;\n        });\n\n    if (char_counts.size() > MAX_LETTERS) {\n        cerr << \"Error: More than \" << MAX_CHARIDX+1\n             << \" different characters in input.\" << endl;\n        exit(1);\n    }\n\n    vector<pair<int, UChar>> charmap_with_counts;\n    for (const auto &it : char_counts)\n        charmap_with_counts.emplace_back(-it.second, it.first);\n\n    std::sort(charmap_with_counts.begin(), charmap_with_counts.end());\n\n    int i = 0;\n    for (const auto &p : charmap_with_counts)\n        charmap[p.second] = i++;\n\n    return charmap;\n}\n\nint main(int argc, char **argv) {\n    std::locale::global(std::locale(\"\"));\n\n    auto vm = parse_args(argc, argv);\n\n    UnicodeString input = UnicodeString(vm[\"sentence\"].as<string>().c_str()).toLower();\n    UnicodeString remove = UnicodeString(vm[\"remove\"].as<string>().c_str()).toLower();\n\n    CharMap charmap;\n    vector<UChar> reverse_charmap;\n\n    charmap = generateCharMap(input);\n\n    auto input_charbag = CharBag::fromUString(input, charmap).value();\n    auto remove_charbag_opt = CharBag::fromUString(remove, charmap);\n\n    if (remove_charbag_opt == nullopt || !remove_charbag_opt.value().isSubsetOf(input_charbag)) {\n        cerr << \"Error: characters for substring \\\"\" << remove\n                << \"\\\" not found in string \\\"\" << input\n                << \"\\\"!\" << endl;\n        exit(2);\n    }\n\n    auto stripped_input_charbag = (input_charbag - remove_charbag_opt.value()).value();\n\n    vector<vector<string>> dict_words;\n    vector<CharBag> dict_charbags;\n    tie(dict_words, dict_charbags) = loadDictionary(\n        vm[\"dict\"].as<string>(), stripped_input_charbag, charmap);\n\n    forAllAnagrams(dict_charbags, stripped_input_charbag, vm[\"len\"].as<int>(),\n                   [&dict_words](const vector<size_t> &word_idxs) {\n            assert(!word_idxs.empty());\n            outputWords(cout, word_idxs, dict_words);\n        });\n}\n", "meta": {"hexsha": "db39208d34b773f3a3083f99c022fad7b6a0a47c", "size": 16963, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ufag.cpp", "max_stars_repo_name": "sliedes/ufag", "max_stars_repo_head_hexsha": "055040477ac5d8419e35e8a66966287ddd4d527b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ufag.cpp", "max_issues_repo_name": "sliedes/ufag", "max_issues_repo_head_hexsha": "055040477ac5d8419e35e8a66966287ddd4d527b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-12-19T21:42:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-06T08:41:52.000Z", "max_forks_repo_path": "ufag.cpp", "max_forks_repo_name": "sliedes/ufag", "max_forks_repo_head_hexsha": "055040477ac5d8419e35e8a66966287ddd4d527b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-12-19T21:18:30.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-19T21:18:30.000Z", "avg_line_length": 31.945386064, "max_line_length": 100, "alphanum_fraction": 0.6039615634, "num_tokens": 4506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.29775822432305726}}
{"text": "// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*-\n//   Learn more about Rcpp at:\n//\n//   http://www.rcpp.org/\n//   http://adv-r.had.co.nz/Rcpp.html\n//   http://gallery.rcpp.org/\n//\n\n// we only include RcppArmadillo.h which pulls Rcpp.h in for us\n#include \"RcppArmadillo.h\"\nusing namespace Rcpp;\n\n// via the depends attribute we tell Rcpp to create hooks for\n// RcppArmadillo so that the build process will know what to do\n//\n// [[Rcpp::depends(RcppArmadillo)]]\n// [[Rcpp::depends(BH)]]\n\n// one include file from Boost to access the digamma function\n#include <boost/math/special_functions/digamma.hpp>\n\n\n/*----------------------------------------------------------------------------*/\n// SlalomModel class definition and module //\n\n//' SlalomModel C++ class\n//'\n//' @description\n//' A C++ class for SlalomModel models.\n//'\n//' @param Y_init matrix of expression values\n//' @param pi_init G x K matrix with each entry being the prior\n//' probability for a gene g being active for factor k.\n//' @param X_init matrix of initial factor states (N x K)\n//' @param W_init G x K matrix of initial weights\n//' @param prior_alpha numeric vector of length two giving prior values\n//' for the gamma hyperparameters of the precisions\n//' @param prior_epsilon numeric vector of length two giving prior values\n//' for the gamma hyperparameters of the residual variances\n//'\n//' @return\n//' an object of the SlalomModel class\n//'\n//' @useDynLib slalom, .registration=TRUE, .fixes=\"Rcpp_\"\n//' @importFrom Rcpp evalCpp\n//' @exportClass Rcpp_SlalomModel\n//' @name SlalomModel\n//' @aliases SlalomModel\nclass SlalomModel {\n    // base class for slalom holding models\npublic:\n    // declare necessary variables for alpha\n    double alpha_pa;\n    double alpha_pb;\n    arma::vec alpha_a;\n    arma::vec alpha_b;\n    arma::vec alpha_E1;\n    arma::vec alpha_lnE1;\n    // declare necessary variables for epsilon\n    double epsilon_pa;\n    double epsilon_pb;\n    arma::vec epsilon_a;\n    arma::vec epsilon_b;\n    arma::vec epsilon_E1;\n    arma::vec epsilon_lnE1;\n    arma::vec epsilon_diagSigmaS;\n    // declare necessary variables for X\n    arma::mat X_E1;\n    arma::mat X_diagSigmaS;\n    arma::mat X_init;\n    // declare necessary variables for W\n    arma::mat W_E1;\n    arma::mat W_sigma2;\n    arma::mat W_E2diag;\n    arma::mat W_gamma0;\n    arma::mat W_gamma1;\n    // declare necessary variables for Z\n    arma::mat Z_E1;\n    // declare other variables\n    arma::mat I;\n    arma::mat Pi_a;\n    arma::mat Pi_b;\n    arma::mat Pi_pa;\n    arma::mat Pi_E1;\n    arma::mat Y;\n    arma::mat pseudo_Y;\n    arma::vec YY;\n    arma::mat Known;\n    int K;\n    int N;\n    int G;\n    int nAnnotated;\n    int nHidden;\n    int nKnown;\n    int nIterations;\n    int minIterations;\n    int iterationCount;\n    double tolerance;\n    bool forceIterations;\n    bool shuffle;\n    bool converged;\n    double nScale;\n    std::vector< std::string > noiseModel;\n    double onF;\n    arma::vec nOn;\n    arma::vec iUnannotatedDense;\n    arma::vec iUnannotatedSparse;\n    arma::uvec doUpdate;\n    arma::uvec pretrain_order;\n    bool dropFactors;\n    bool learnPi;\n    // names\n    Rcpp::StringVector termNames;\n    Rcpp::StringVector cellNames;\n    Rcpp::StringVector geneNames;\n    // methods\n    void train(void);\n    void update(void);\n    void updateEpsilon(void);\n    void updateAlpha(const int);\n    void updateX(const int);\n    void updateW(const int);\n    void updatePi(const int);\n    // constructor\n    SlalomModel() {}\n    SlalomModel(arma::mat Y_init, arma::mat pi_init, arma::mat X_init,\n                arma::mat W_init, arma::vec prior_alpha, arma::vec prior_epsilon) :\n        Y(Y_init), Pi_E1(pi_init), I(pi_init), W_gamma0(pi_init), X_E1(X_init),\n        W_E1(W_init) {\n        K = pi_init.n_cols;\n        N = Y_init.n_rows;\n        G = Y_init.n_cols;\n        nScale = 100.0;\n        // initialise squared column sums\n        YY = arma::zeros(G);\n        for (int g=0; g < G; g++) {\n            YY(g) = arma::accu(Y.col(g) % Y.col(g));\n        }\n        // initialise alpha variables\n        alpha_pa = prior_alpha[0];\n        alpha_pb = prior_alpha[1];\n        alpha_a = arma::ones(K) * alpha_pa;\n        alpha_b = arma::ones(K) * alpha_pb;\n        alpha_E1 = alpha_b / alpha_a;\n        alpha_lnE1 = arma::ones(K);\n        for (int i = 0; i < K; i++) {\n            alpha_lnE1(i) = boost::math::digamma(alpha_a(i));\n        }\n        alpha_lnE1 = alpha_lnE1 - arma::log(alpha_b);\n        // initialise epsilon variables\n        epsilon_pa = prior_epsilon[0];\n        epsilon_pb = prior_epsilon[1];\n        epsilon_a = arma::ones(G) * epsilon_pa;\n        epsilon_b = arma::ones(G) * epsilon_pb;\n        epsilon_E1 = epsilon_b / epsilon_a;\n        epsilon_lnE1 = arma::ones(G);\n        for (int i = 0; i < G; i++) {\n            epsilon_lnE1(i) = boost::math::digamma(epsilon_a(i));\n        }\n        epsilon_lnE1 = epsilon_lnE1 - arma::log(epsilon_b);\n        epsilon_diagSigmaS = arma::zeros(G);\n        // initialise X variables\n        X_diagSigmaS = arma::ones(N, K);\n        // initialise W variables\n        W_gamma1 = 1.0 - W_gamma0;\n        W_sigma2 = arma::ones(G, K);\n        W_E2diag = arma::zeros(G, K);\n        // initialise iterations\n        converged = false;\n        iterationCount = 0;\n        tolerance = 1e-08;\n        learnPi = true;\n        doUpdate = arma::ones<arma::uvec>(K);\n        minIterations = 1;\n        nIterations = 1;\n    }\n};\n\n\n/*----------------------------------------------------------------------------*/\n// SlalomModel class train method\n\n// train method\nvoid SlalomModel::train(void) {\n    /*\n     Iterate updates of weights (with spike-and-slab prior), ARD parameters, factors, annd noise parameters.\n\n     No arguments, but utilises the following parameters defined in the object:\n     nIterations          (int): Number of iterations.\n     forceIterations     (bool): Force the model to update `nIteration` times.\n     tolerance          (float): Tolerance to monitor convergence of reconstruction error\n     minIterations        (int): Minimum number of iterations the model should perform.\n     */\n    arma::umat Ion = (this->W_gamma0 > .5);\n    arma::mat Zr = this->X_E1 * (this->W_E1.t() % Ion.t());\n    arma::mat Zd = this->Z_E1 - Zr;\n    arma::rowvec error(1);\n    arma::rowvec error_old(1);\n    error.fill(arma::mean(arma::mean((arma::abs(Zd)))));\n    double meanerr = arma::mean(error);\n    // mean absolute error\n    error_old.fill(100);\n    this->converged = false;\n    // iterate model to train it\n    this->iterationCount = 0;\n    for (int iter = 0; iter <= this->nIterations; iter++) {\n        // t = time.time();\n        this->update();\n        this->iterationCount++;\n        if (iter % 100 == 0) {\n            Rcout << \"iteration \" << iter << std::endl;\n        }\n        if (iter % 50 == 0) {\n            error_old = error;\n            Zr = this->X_E1 * this->W_E1.t();\n            Zd = this->Z_E1 - Zr;\n            error.fill(arma::mean(arma::mean((arma::abs(Zd)))));\n            // mean absolute error\n            this->converged = arma::approx_equal(error_old, error, \"absdiff\",\n                                           this->tolerance);\n            double meanerr = arma::mean(error);\n        }\n        if ( this->converged && !(this->forceIterations) &&\n             (iter > this->minIterations) ) {\n            Rcout << \"Model converged after \" << iter << \" iterations.\" << std::endl;\n            break;\n        }\n        // this->Z_E1 = this->X_E1 * this->W_E1.t();\n    }\n    if (!converged) {\n        Rcout << \"Model not converged after \" <<  this->nIterations << \" iterations.\" << std::endl;\n    }\n}\n\n\n/*----------------------------------------------------------------------------*/\n// SlalomModel class update methods //\n\n// wrapper around R's RNG such that we get a uniform distribution over\n// [0,n) as required by the STL algorithm\ninline int randWrapper(const int n) { return floor(unif_rand() * n); }\n\nvoid SlalomModel::update(void) {\n    /*\n     Do one update of weights (with spike-and-slab prior), ARD parameters, factors, annd noise parameters.\n\n     */\n    this->epsilon_diagSigmaS = arma::zeros(this->K);\n    // arma::umat Ion = (this->W_gamma0 > .5);\n    // check above: set parameter to zero with every update?\n    arma::uvec kRange;\n    if (this->iterationCount == 1) {\n        kRange = this->pretrain_order;\n    } else {\n        kRange = arma::regspace<arma::uvec>(0,  (this->K - 1));\n    }\n    if (this->shuffle == true && this->iterationCount > 1) {\n        arma::uvec kunfix = arma::regspace<arma::uvec>(this->nKnown,\n                                                       (this->K - 1));\n        std::random_shuffle(kunfix.begin(), kunfix.end(), randWrapper);\n        for (int i = 0; i < (this->K - this->nKnown); ++i) {\n            int ii = i + this->nKnown;\n            kRange(ii) = kunfix(i);\n        }\n    }\n    // switch factors off such that they can't be turned back on\n    // Regular iterator, non-C++11\n    for (int m = 0; m < this->K; m++) {\n        int k = kRange[m];\n        if (this->doUpdate[k]) {\n            if (this->dropFactors == false || this->iterationCount < 10 ||\n                (this->alpha_E1[k] / arma::var(this->X_E1.col(k))) < 1e10) {\n                this->updateW(k);\n                if (this->learnPi) {\n                    if (arma::any((this->iUnannotatedSparse - 1) == k)) {\n                        this->updatePi(k);\n                    }\n                }\n                this->updateAlpha(k);\n                this->updateX(k);\n            } else {\n                this->doUpdate[k] = 0;\n                Rcout << \"Switched off factor \" << k << std::endl;\n            }\n        }\n    }\n    // const char noise_gauss = \"gauss\";\n    // if (std::strcmp(this->noiseModel, noise_gauss) == 0) {\n    //     // this->updateEpsilon();\n    // };\n    this->updateEpsilon();\n}\n\n\nvoid SlalomModel::updateW(const int k) {\n    // update the factor weights\n    // define logPi values\n    arma::vec logPi;\n    int Muse = arma::accu(this->doUpdate);\n    if (k < this->nKnown || arma::any((this->iUnannotatedSparse - 1) == k) ||\n        arma::any((this->iUnannotatedDense - 1) == k)) {\n        logPi = arma::log(this->Pi_E1.col(k) / (1.0 - this->Pi_E1.col(k)));\n        // careful of divide-by-zero errors here\n    } else if (this->nScale > 0 && this->nScale < this->N) {\n        logPi = arma::log(this->Pi_E1.col(k) / (1.0 - this->Pi_E1.col(k)));\n        // careful of divide-by-zero errors here\n        arma::uvec isOFF_ = arma::find(this->Pi_E1.col(k) < 0.5);\n        arma::uvec kvec(1);\n        kvec(0) = k;\n        logPi(isOFF_) = ((this->N / this->nScale) *\n            arma::log(this->Pi_E1(isOFF_, kvec) /\n                (1 - this->Pi_E1(isOFF_, kvec))));\n        // careful of divide-by-zero errors here\n        arma::uvec isON_ = arma::find(this->Pi_E1.col(k) > 0.5);\n        if (this->onF > 1.0) {\n            logPi(isON_) = this->onF * arma::log(\n                this->Pi_E1(isON_, kvec) / (1 - this->Pi_E1(isON_, kvec)));\n        }\n    } else {\n        logPi = arma::log(this->Pi_E1.col(k) / (1 - this->Pi_E1.col(k)));\n    }\n    arma::vec sigma2Sigmaw;\n    sigma2Sigmaw = (1.0 / this->epsilon_E1) * this->alpha_E1(k);\n    arma::uvec set1 = arma::regspace<arma::uvec>(0, 1, k - 1);    // zero-indexing\n    arma::uvec set2 = arma::regspace<arma::uvec>(k + 1, 1, this->K - 1);\n    arma::uvec setMinus = arma::join_cols(set1, set2);\n    arma::uvec idx = arma::find(this->doUpdate(setMinus) == 1);\n    setMinus = setMinus(idx);\n\n    arma::vec SmTSk = arma::sum(\n        (arma::repmat(this->X_E1.col(k), 1, Muse - 1) %\n             this->X_E1.cols(setMinus)), 0).t();\n    double tmp = arma::as_scalar(this->X_E1.col(k).t() * this->X_E1.col(k));\n    double SmTSm = (tmp + arma::sum(this->X_diagSigmaS.col(k)));\n\n    arma::vec b;\n    arma::vec diff;\n    b = (this->W_gamma0.cols(setMinus) % this->W_E1.cols(setMinus)) * SmTSk;\n    diff = (this->X_E1.col(k).t() * this->Z_E1).t() - b;\n    arma::vec diff2 = diff % diff;\n    arma::vec SmTSmSig = SmTSm + sigma2Sigmaw; // same as Py\n\n    // update gamma and W\n    arma::vec u_qm = (logPi + 0.5 * arma::log(sigma2Sigmaw) - 0.5 *\n        arma::log(SmTSmSig) + (0.5 * this->epsilon_E1) %\n        (diff2 / SmTSmSig));\n    this->W_gamma0.col(k) = 1.0 / (1 + arma::exp(-u_qm));\n    this->W_gamma1.col(k) = 1.0 - this->W_gamma0.col(k);\n    this->W_E1.col(k) = (diff / SmTSmSig);\n    this->W_sigma2.col(k) = (1.0 / this->epsilon_E1) / SmTSmSig;\n    this->W_E2diag.col(k) = ((this->W_E1.col(k) % this->W_E1.col(k)) +\n        this->W_sigma2.col(k));\n}\n\n\nvoid SlalomModel::updatePi(const int k) {\n    // update Pi in a SlalomModel class object\n    this->Pi_a.col(k) = this->Pi_pa.col(k) + arma::accu(this->W_gamma0.col(k));\n    this->Pi_b.col(k) = (this->Pi_pa.col(k) + this->G -\n        arma::accu(this->W_gamma0.col(k)));\n    this->Pi_E1.col(k) = this->Pi_a.col(k) / this->Pi_a.col(k) +\n        this->Pi_b.col(k);\n}\n\nvoid SlalomModel::updateAlpha(const int k) {\n    // pdate alpha in a SlalomModel class object - precisions\n    double Ewdwd = arma::accu(this->W_gamma0.col(k) % this->W_E2diag.col(k));\n    // elementwise mult.\n    this->alpha_a(k) = this->alpha_pa + 0.5 * Ewdwd;\n    this->alpha_b(k) = this->alpha_pb + arma::accu(this->W_gamma0.col(k)) / 2.0;\n    this->alpha_E1(k) = this->alpha_b(k) / this->alpha_a(k);\n}\n\n\nvoid SlalomModel::updateX(const int k) {\n    // update the factor states\n    arma::uvec set1 = arma::regspace<arma::uvec>(0, 1, k - 1);\n    arma::uvec set2 = arma::regspace<arma::uvec>(k + 1, 1, this->K - 1);\n    arma::uvec setMinus = arma::join_cols(set1, set2);\n    arma::uvec idx = arma::find(this->doUpdate(setMinus) == 1);\n    setMinus = setMinus(idx);\n\n    arma::vec SW_sigma;\n    arma::vec SW2_sigma;\n\n    SW2_sigma = ((this->W_gamma0.col(k) % this->W_E2diag.col(k)) %\n                     this->epsilon_E1);\n    double alphaSm = arma::sum(SW2_sigma);\n\n    for (int i = 0; i < this->N; i++) {\n        this->X_diagSigmaS(i, k) = 1.0 / (1.0 + alphaSm);\n    }\n\n    if (k >= this->nKnown) {\n        SW_sigma = (this->W_gamma0.col(k) %\n                        this->W_E1.col(k)) % this->epsilon_E1;     // Gx1 vec\n        arma::mat b0 = (this->X_E1.cols(setMinus) *\n            (this->W_gamma0.cols(setMinus) % this->W_E1.cols(setMinus)).t());  // NxG mat.\n        arma::vec b = b0 * SW_sigma;    // NxG x Gx1 -> Nx1 vec\n        arma::vec barmuX = (this->Z_E1 * SW_sigma) - b;\n        // update X\n        this->X_E1.col(k) = barmuX / (1.0 + alphaSm);\n        // keep diagSigmaS\n        this->epsilon_diagSigmaS(k) = arma::accu(this->X_diagSigmaS.col(k));\n    }\n}\n\n\nvoid SlalomModel::updateEpsilon(void) {\n    // update Epsilon (vectorised) - noise parameters\n    arma::uvec update_cols = arma::find(this->doUpdate == 1);\n    arma::mat SW_sigma = (this->W_gamma0.cols(update_cols) %\n                              this->W_E1.cols(update_cols));  // elementwise mult.; GxK mat\n    arma::mat SW2_sigma = (this->W_gamma0.cols(update_cols) %\n                               this->W_E2diag.cols(update_cols));  // elementwise mult.; GxK mat\n    arma::mat muSTmuS = (this->X_E1.cols(update_cols).t() *\n        this->X_E1.cols(update_cols));     // KxK matrix\n    arma::mat newmat = this->Z_E1.t() * this->X_E1.cols(update_cols);\n    arma::vec t1 = arma::sum(SW_sigma % newmat, 1);  // K length vec\n    arma::vec t2 = arma::sum(SW2_sigma % arma::repmat(muSTmuS.diag().t() +\n        this->epsilon_diagSigmaS(update_cols).t(), this->G, 1), 1);\n    // set diagonals to zeros in muSTmuS for next calculation\n    muSTmuS.diag().zeros();\n    arma::vec t3 = arma::sum((SW_sigma * muSTmuS) % SW_sigma, 1);\n    this->epsilon_E1 = 1.0 / ((0.5 * (this->YY  + (-2 * t1  + t2 + t3))) /\n        (0.5 * this->N));\n    this->epsilon_a.fill(0.5 * this->N + this->epsilon_pa);\n    this->epsilon_b = this->epsilon_pb + 0.5 * (this->YY + (-2 * t1 + t2 + t3));\n    for (int i = 0; i < this->epsilon_E1.n_elem; i++) {\n        if (this->epsilon_E1(i) > 1e6) {\n            this->epsilon_E1(i) = 1e6;\n        }\n    }\n}\n\n\n\n/*----------------------------------------------------------------------------*/\n// SlalomModel Rcpp module\n\n// Define a module to make the C++ class available to R\nRCPP_MODULE(SlalomModel) {\n    using namespace Rcpp;\n\n    class_<SlalomModel>(\"SlalomModel\")\n        // expose the default constructor\n        .constructor()\n        .constructor<arma::mat, arma::mat, arma::mat, arma::mat, arma::vec,\n        arma::vec>()\n        //\n        // fields\n        .field(\"K\", &SlalomModel::K)\n        .field(\"N\", &SlalomModel::N)\n        .field(\"G\", &SlalomModel::G)\n        .field(\"nScale\", &SlalomModel::nScale)\n        .field(\"nAnnotated\", &SlalomModel::nAnnotated)\n        .field(\"nHidden\", &SlalomModel::nHidden)\n        .field(\"nKnown\", &SlalomModel::nKnown)\n        .field(\"nIterations\", &SlalomModel::nIterations)\n        .field(\"minIterations\", &SlalomModel::minIterations)\n        .field(\"iterationCount\", &SlalomModel::iterationCount)\n        .field(\"forceIterations\", &SlalomModel::forceIterations)\n        .field(\"tolerance\", &SlalomModel::tolerance)\n        .field(\"shuffle\", &SlalomModel::shuffle)\n        .field(\"converged\", &SlalomModel::converged)\n        .field(\"noiseModel\", &SlalomModel::noiseModel)\n        .field(\"onF\", &SlalomModel::onF)\n        // alpha\n        .field(\"alpha_pa\", &SlalomModel::alpha_pa)\n        .field(\"alpha_pb\", &SlalomModel::alpha_pb)\n        .field(\"alpha_a\", &SlalomModel::alpha_a)\n        .field(\"alpha_b\", &SlalomModel::alpha_b)\n        .field(\"alpha_E1\", &SlalomModel::alpha_E1)\n        .field(\"alpha_lnE1\", &SlalomModel::alpha_lnE1)\n        // epsilon\n        .field(\"epsilon_pa\", &SlalomModel::epsilon_pa)\n        .field(\"epsilon_pb\", &SlalomModel::epsilon_pb)\n        .field(\"epsilon_a\", &SlalomModel::epsilon_a)\n        .field(\"epsilon_b\", &SlalomModel::epsilon_b)\n        .field(\"epsilon_E1\", &SlalomModel::epsilon_E1)\n        .field(\"epsilon_lnE1\", &SlalomModel::epsilon_lnE1)\n        .field(\"epsilon_diagSigmaS\", &SlalomModel::epsilon_diagSigmaS)\n        // X\n        .field(\"X_E1\", &SlalomModel::X_E1)\n        .field(\"X_diagSigmaS\", &SlalomModel::X_diagSigmaS)\n        .field(\"X_init\", &SlalomModel::X_init)\n        // W\n        .field(\"W_E1\", &SlalomModel::W_E1)\n        .field(\"W_sigma2\", &SlalomModel::W_sigma2)\n        .field(\"W_E2diag\", &SlalomModel::W_E2diag)\n        .field(\"W_gamma0\", &SlalomModel::W_gamma0)\n        .field(\"W_gamma1\", &SlalomModel::W_gamma1)\n        // Z\n        .field(\"Z_E1\", &SlalomModel::Z_E1)\n        // Pi\n        .field(\"Pi_a\", &SlalomModel::Pi_a)\n        .field(\"Pi_pa\", &SlalomModel::Pi_pa)\n        .field(\"Pi_b\", &SlalomModel::Pi_b)\n        .field(\"Pi_E1\", &SlalomModel::Pi_E1)\n        .field(\"I\", &SlalomModel::I)\n        // other variables\n        .field(\"Known\", &SlalomModel::Known)\n        .field(\"Y\", &SlalomModel::Y)\n        .field(\"pseudo_Y\", &SlalomModel::pseudo_Y)\n        .field(\"YY\", &SlalomModel::YY)\n        .field(\"iUnannotatedDense\", &SlalomModel::iUnannotatedDense)\n        .field(\"iUnannotatedSparse\", &SlalomModel::iUnannotatedSparse)\n        .field(\"nOn\", &SlalomModel::nOn)\n        .field(\"doUpdate\", &SlalomModel::doUpdate)\n        .field(\"pretrain_order\", &SlalomModel::pretrain_order)\n        .field(\"learnPi\", &SlalomModel::learnPi)\n        .field(\"dropFactors\", &SlalomModel::dropFactors)\n        // names\n        .field(\"termNames\", &SlalomModel::termNames)\n        .field(\"cellNames\", &SlalomModel::cellNames)\n        .field(\"geneNames\", &SlalomModel::geneNames)\n        // methods\n        .method(\"train\", &SlalomModel::train , \"Train the SlalomModel\")\n        .method(\"update\", &SlalomModel::update , \"Update the SlalomModel\")\n        .method(\"updateW\", &SlalomModel::updateW , \"Update W\")\n        .method(\"updateX\", &SlalomModel::updateX , \"Update X\")\n        .method(\"updatePi\", &SlalomModel::updatePi , \"Update Pi\")\n        .method(\"updateEpsilon\", &SlalomModel::updateEpsilon , \"Update Epsilon\")\n        .method(\"updateAlpha\", &SlalomModel::updateAlpha , \"Update alpha\")\n        ;\n}\n", "meta": {"hexsha": "2888e174e1542ffc8a2f2914597f4a482b5be968", "size": 20064, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "R_package/src/slalom-classes.cpp", "max_stars_repo_name": "dburkhardt/slalom", "max_stars_repo_head_hexsha": "547a56316e5c3ccc63e592eb907dc53b00212466", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2017-10-30T13:58:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-14T17:07:46.000Z", "max_issues_repo_path": "R_package/src/slalom-classes.cpp", "max_issues_repo_name": "dburkhardt/slalom", "max_issues_repo_head_hexsha": "547a56316e5c3ccc63e592eb907dc53b00212466", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-11-11T04:49:01.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-24T13:24:50.000Z", "max_forks_repo_path": "R_package/src/slalom-classes.cpp", "max_forks_repo_name": "dburkhardt/slalom", "max_forks_repo_head_hexsha": "547a56316e5c3ccc63e592eb907dc53b00212466", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-01-09T12:19:31.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-26T17:01:57.000Z", "avg_line_length": 38.0721062619, "max_line_length": 108, "alphanum_fraction": 0.5750099681, "num_tokens": 5926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2977582243230572}}
{"text": "#ifndef TCM_BLAS_WRAPPER_HPP\n#define TCM_BLAS_WRAPPER_HPP\n\n#include <type_traits>\n#include <complex>\n#include <cassert>\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <detail/config.hpp>\n#include <detail/utils.hpp>\n#include <detail/iterator.hpp>\n\n\n///////////////////////////////////////////////////////////////////////////////\n/// \\file blas_wrapper.hpp\n/// \\brief Defines template versions of some BLAS routines.\n///////////////////////////////////////////////////////////////////////////////\n\n\n\n#define REGISTER_BLAS(general_f, s_f, d_f, c_f, z_f)                           \\\n\tnamespace {                                                                \\\n\t\ttemplate<class... Args>                                                \\\n        __attribute__((always_inline))                                         \\\n\t\tinline                                                                 \\\n\t\tauto general_f##_impl( utils::Type2Type<float>                         \\\n\t\t                     , Args&&... args) noexcept                        \\\n\t\t{ return s_f(std::forward<Args>(args)...); }                           \\\n\t\t                                                                       \\\n\t\ttemplate<class... Args>                                                \\\n        __attribute__((always_inline))                                         \\\n\t\tinline                                                                 \\\n\t\tauto general_f##_impl( utils::Type2Type<double>                        \\\n\t\t                     , Args&&... args) noexcept                        \\\n\t\t{ return d_f(std::forward<Args>(args)...); }                           \\\n\t\t                                                                       \\\n\t\ttemplate<class... Args>                                                \\\n        __attribute__((always_inline))                                         \\\n\t\tinline                                                                 \\\n\t\tauto general_f##_impl( utils::Type2Type<std::complex<float>>           \\\n\t\t                     , Args&&... args) noexcept                        \\\n\t\t{ return c_f(std::forward<Args>(args)...); }                           \\\n\t\t                                                                       \\\n\t\ttemplate<class... Args>                                                \\\n        __attribute__((always_inline))                                         \\\n\t\tinline                                                                 \\\n\t\tauto general_f##_impl( utils::Type2Type<std::complex<double>>          \\\n\t\t                     , Args&&... args) noexcept                        \\\n\t\t{ return z_f(std::forward<Args>(args)...); }                           \\\n\t}                                                                          \\\n                                                                               \\\n\ttemplate<class T, class... Args>                                           \\\n\t__attribute__((always_inline))                                             \\\n\tinline                                                                     \\\n\tauto general_f(Args&&... args) noexcept                                    \\\n\t{ return general_f##_impl( utils::Type2Type<T>{}                           \\\n\t                         , std::forward<Args>(args)...);                   \\\n\t}   \n\n\n\n\n\n\n\nnamespace tcm {\n\nnamespace import {\n\n\nenum class Operator : char {None = 'N', T = 'T', H = 'C'};\n\n\n\n#ifdef USING_INTEL_MKL\n\tusing blas_int = long long int;\n#else\n#\tifdef USING_ATLAS\n\t\tusing blas_int = int;\n#\telse\n#\t\terror \"Need BLAS\"\n#\tendif\n#endif\n\n\n\n// ============================================================================\n//                                DOT PRODUCT                                  \n// ============================================================================\n\n\nextern \"C\" {\n\nfloat sdot_\n( blas_int const* N\n, float const* X, blas_int const* INCX\n, float const* Y, blas_int const* INCY );\n\ndouble ddot_\n( blas_int const* N\n, double const* X, blas_int const* INCX\n, double const* Y, blas_int const* INCY );\n\nstd::complex<float> cdotc_\n( blas_int const* N\n, std::complex<float> const* X, blas_int const* INCX\n, std::complex<float> const* Y, blas_int const* INCY );\n\nstd::complex<double> zdotc_\n( blas_int const* N\n, std::complex<double> const* X, blas_int const* inc_X\n, std::complex<double> const* Y, blas_int const* inc_Y );\n\n} // extern \"C\"\n\nREGISTER_BLAS(dotc, sdot_, ddot_, cdotc_, zdotc_)\n\n\ntemplate< class _T\n        , class = std::enable_if_t\n                  <   std::is_same<_T, float>() \n                   or std::is_same<_T, double>()\n                   or std::is_same<_T, std::complex<float>>()\n                   or std::is_same<_T, std::complex<double>>()\n                  >\n        >\ninline\nauto dot( std::size_t const n\n        , _T const* X, blas_int const INCX\n        , _T const* Y, blas_int const INCY\n        ) -> _T\n{\n\tif(n == 0) return _T{0.0};\n\n\tassert(X != nullptr and INCX != 0);\n\tassert(Y != nullptr and INCY != 0);\n\t/*\n\tutils::assert_valid( const_blas_iterator<_T>{X           , INCX}\n\t                   , const_blas_iterator<_T>{X + n * INCX, INCX} );\n\tutils::assert_valid( const_blas_iterator<_T>{Y           , INCY}\n\t                   , const_blas_iterator<_T>{Y + n * INCY, INCY} );\n\t*/\n\n\tauto const N = boost::numeric_cast<blas_int>(n);\t\n\tauto const result = dotc<_T>(&N, X, &INCX, Y, &INCY);\n\n\tutils::assert_valid(result);\n\treturn result;\n}\n\n\n\n// ============================================================================\n//                                   AXPY                                      \n// ============================================================================\n\nextern \"C\" {\n\nvoid saxpy_\n( blas_int const* N, float const* A\n, float const* X, blas_int const* INCX\n, float      * Y, blas_int const* INCY );\n\nvoid daxpy_\n( blas_int const* N, double const* A\n, double const* X, blas_int const* INCX\n, double      * Y, blas_int const* INCY );\n\nvoid caxpy_\n( blas_int const* N, std::complex<float> const* A\n, std::complex<float> const* X, blas_int const* INCX\n, std::complex<float>      * Y, blas_int const* INCY );\n\nvoid zaxpy_\n( blas_int const* N, std::complex<double> const* A\n, std::complex<double> const* X, blas_int const* INCX\n, std::complex<double>      * Y, blas_int const* INCY );\n\n} // extern \"C\"\n\nREGISTER_BLAS(axpy, saxpy_, daxpy_, caxpy_, zaxpy_)\n\ntemplate< class _T\n        , class = std::enable_if_t\n                  <   std::is_same<_T, float>() \n                   or std::is_same<_T, double>()\n                   or std::is_same<_T, std::complex<float>>()\n                   or std::is_same<_T, std::complex<double>>()\n                  >\n        >\ninline\nauto axpy( std::size_t const n, _T const a\n         , _T const* X, blas_int const INCX\n         , _T      * Y, blas_int const INCY ) -> void\n{\n\tif(n == 0) return;\n\n\tassert(X != nullptr and INCX != 0);\n\tassert(Y != nullptr and INCY != 0);\n\t/*\n\tassert_valid( const_blas_iterator<_T>{X           , INCX}\n\t            , const_blas_iterator<_T>{X + n * INCX, INCX} );\n\tassert_valid( const_blas_iterator<_T>{Y           , INCY}\n\t            , const_blas_iterator<_T>{Y + n * INCY, INCY} );\n\t*/\n\tauto const N = boost::numeric_cast<blas_int>(n);\t\n\t\n\taxpy<_T>(&N, &a, X, &INCX, Y, &INCY);\n\n\t/*\n\tassert_valid( const_blas_iterator<_T>{Y           , INCY}\n\t            , const_blas_iterator<_T>{Y + n * INCY, INCY} );\n\t*/\n}\n\n\n\n\n\n\n// ============================================================================\n//                         MATRIX-VECTOR MULTIPLICATION                        \n// ============================================================================\n\nextern \"C\" {\n\nvoid sgemv_\n( char const* TRANSA\n, blas_int const* M, blas_int const* N\n, float const* ALPHA, float const* A, blas_int const* LDA\n, float const* X, blas_int const* INCX\n, float const* BETA, float* Y, blas_int const* INCY );\n\nvoid dgemv_\n( char const* TRANSA\n, blas_int const* M, blas_int const* N\n, double const* ALPHA, double const* A, blas_int const* LDA\n, double const* X, blas_int const* INCX\n, double const* BETA, double* Y, blas_int const* INCY );\n\nvoid cgemv_\n( char const* TRANSA\n, blas_int const* M, blas_int const* N\n, std::complex<float> const* ALPHA\n, std::complex<float> const* A, blas_int const* LDA\n, std::complex<float> const* X, blas_int const* INCX\n, std::complex<float> const* BETA\n, std::complex<float>* Y, blas_int const* INCY );\n\nvoid zgemv_\n( char const* TRANSA\n, blas_int const* M, blas_int const* N\n, std::complex<double> const* ALPHA\n, std::complex<double> const* A, blas_int const* LDA\n, std::complex<double> const* X, blas_int const* INCX\n, std::complex<double> const* BETA\n, std::complex<double>* Y, blas_int const* INCY );\n\n} // extern \"C\"\n\nREGISTER_BLAS(gemv, sgemv_, dgemv_, cgemv_, zgemv_)\n\n\ntemplate< class _T\n        , class = std::enable_if_t\n                  <   std::is_same<_T, float>() \n                   or std::is_same<_T, double>()\n                   or std::is_same<_T, std::complex<float>>()\n                   or std::is_same<_T, std::complex<double>>()\n                  >\n        >\nauto gemv( Operator const op_A\n         , std::size_t const m, std::size_t const n\n         , _T const ALPHA, _T const* A, blas_int const LDA\n         , _T const* X, blas_int const INCX\n         , _T const BETA, _T* Y, blas_int const INCY ) -> void\n{\n\tif(n == 0 or m == 0) return;\n\n\tassert(A != nullptr and LDA  != 0);\n\tassert(X != nullptr and INCX != 0);\n\tassert(Y != nullptr and INCY != 0);\n\t/*\n\tutils::assert_valid(A, A + LDA * n);\n\tutils::assert_valid\n\t\t( const_blas_iterator<_T>{X, INCX}\n\t\t, const_blas_iterator<_T>{ X + (op_A == Operator::None ? n : m) * INCX\n\t\t                         , INCX }\n\t\t);\n\tutils::assert_valid\n\t\t( const_blas_iterator<_T>{Y, INCY}\n\t\t, const_blas_iterator<_T>{ Y + (op_A == Operator::None ? m : n) * INCY\n\t\t                         , INCY }\n\t\t);\n\t*/\n\n\tauto const TRANS = static_cast<char>(op_A);\n\tauto const M     = boost::numeric_cast<blas_int>(m);\n\tauto const N     = boost::numeric_cast<blas_int>(n);\n\n\tassert(LDA >= M);\n\n\tgemv<_T>( &TRANS, &M, &N\n\t        , &ALPHA, A, &LDA, X, &INCX\n\t        , &BETA, Y, &INCY );\n\n\t/*\n\tutils::assert_valid\n\t\t( const_blas_iterator<_T>{Y, INCY}\n\t\t, const_blas_iterator<_T>{ Y + (op_A == Operator::None ? m : n) * INCY\n\t\t                         , INCY }\n\t\t);\n\t*/\n}\n\n\n\n\n// ============================================================================\n//                           MATRIX-MATRIX MULTIPLICATION                      \n// ============================================================================\n\nextern \"C\" {\n\nvoid sgemm_\n( char const* TRANSA, char const* TRANSB\n, blas_int const* M, blas_int const* N, blas_int const* K\n, float const* ALPHA\n, float const* A, blas_int const* LDA\n, float const* B, blas_int const* LDB\n, float const* BETA\n, float* C, blas_int const* LDC );\n\nvoid dgemm_\n( char const* TRANSA, char const* TRANSB\n, blas_int const* M, blas_int const* N, blas_int const* K\n, double const* ALPHA\n, double const* A, blas_int const* LDA\n, double const* B, blas_int const* LDB\n, double const* BETA\n, double* C, blas_int const* LDC );\n\nvoid cgemm_\n( char const* TRANSA, char const* TRANSB\n, blas_int const* M, blas_int const* N, blas_int const* K\n, std::complex<float> const* ALPHA\n, std::complex<float> const* A, blas_int const* LDA\n, std::complex<float> const* B, blas_int const* LDB\n, std::complex<float> const* BETA\n, std::complex<float>* C, blas_int const* LDC );\n\nvoid zgemm_\n( char const* TRANSA, char const* TRANSB\n, blas_int const* M, blas_int const* N, blas_int const* K\n, std::complex<double> const* ALPHA\n, std::complex<double> const* A, blas_int const* LDA\n, std::complex<double> const* B, blas_int const* LDB\n, std::complex<double> const* BETA\n, std::complex<double>* C, blas_int const* LDC );\n\n} // extern \"C\"\n\nREGISTER_BLAS(gemm, sgemm_, dgemm_, cgemm_, zgemm_)\n\ntemplate< class _T\n        , class = std::enable_if_t\n                  <   std::is_same<_T, float>() \n                   or std::is_same<_T, double>()\n                   or std::is_same<_T, std::complex<float>>()\n                   or std::is_same<_T, std::complex<double>>()\n                  >\n        >\ninline\nauto gemm( Operator const op_A, Operator const op_B\n         , std::size_t const m, std::size_t const n, std::size_t const k\n         , _T const ALPHA, _T const* A, blas_int const LDA\n         , _T const* B, blas_int const LDB\n         , _T const BETA, _T* C, blas_int const LDC ) -> void\n{\n\tif(m == 0 or n == 0 or k == 0) return;\n\n\tassert(A != nullptr and LDA != 0);\n\tassert(B != nullptr and LDB != 0);\n\tassert(C != nullptr and LDC != 0);\n\t/*\n\tutils::assert_valid(A, A + LDA * (op_A == Operator::None ? k : m));\n\tutils::assert_valid(B, B + LDB * (op_B == Operator::None ? n : k));\n\tutils::assert_valid(C, C + LDC * n);\n\t*/\n\n\tauto const M      = boost::numeric_cast<blas_int>(m);\n\tauto const N      = boost::numeric_cast<blas_int>(n);\n\tauto const K      = boost::numeric_cast<blas_int>(k);\n\tauto const TRANSA = static_cast<char>(op_A);\n\tauto const TRANSB = static_cast<char>(op_B);\n\n\tassert( LDA >= (op_A == Operator::None ? M : K) );\n\tassert( LDB >= (op_B == Operator::None ? K : N) );\n\tassert( LDC >= M );\n\n\tgemm<_T>( &TRANSA, &TRANSB, &M, &N, &K\n\t        , &ALPHA, A, &LDA, B, &LDB\n\t        , &BETA, C, &LDC );\n\n\t/*\n\tutils::assert_valid(C, C + LDC * n);\n\t*/\n}\n\n\n\n} // namespace import\n\n} // namespace tcm\n\n\n\n\n\n\n\n\n#endif // TCM_BLAS_WRAPPER_HPP\n", "meta": {"hexsha": "b5a4498f197ee6ba48e92b80bb4124afb07f88a7", "size": 13454, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/detail/blas_wrapper.hpp", "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": "include/detail/blas_wrapper.hpp", "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": "include/detail/blas_wrapper.hpp", "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": 31.6564705882, "max_line_length": 80, "alphanum_fraction": 0.487661662, "num_tokens": 3389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2977582181353824}}
{"text": "#include <cstdio>\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include <map>\n#include <cfloat>\n\n// Boost\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n\n// Eigen\n#include <Eigen/Dense>\n#include <unsupported/Eigen/CXX11/Tensor>\n\n// HDF5\n#include <H5Cpp.h>\n\n// OpenMP\n#include <omp.h>\n\n// Point-triangle distance and ray-triangle intersection.\n#include \"triangle_point/poitri.h\"\n#include \"triangle_ray/raytri.h\"\n#include \"box_triangle/aabb_triangle_overlap.h\"\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(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 Compute triangle box intersection.\n * \\param[in] min defining voxel\n * \\param[in] max defining voxel\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 Eigen::Vector3f &min, Eigen::Vector3f &max, const Eigen::Vector3f &v1, const Eigen::Vector3f &v2, const Eigen::Vector3f &v3) {\n  float half_size[3] = {\n    (max(0) - min(0))/2.,\n    (max(1) - min(1))/2.,\n    (max(2) - min(2))/2.\n  };\n\n  float center[3] = {\n    max(0) - half_size[0],\n    max(1) - half_size[1],\n    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 Specifies the voxelization mode, i.e. which point of a voxel to use for SDF computation. */\nenum VoxelizationMode {\n  CENTER = 0,\n  CORNER = 1\n};\n\n/** \\brief Just encapsulating vertices and faces. */\nclass Mesh {\npublic:\n  /** \\brief Empty constructor. */\n  Mesh() {\n\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   */\n  static bool from_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 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->num_vertices() << \" \" << this->num_faces() << \" 0\" << std::endl;\n\n    for (unsigned int v = 0; v < this->num_vertices(); 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->num_faces(); 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\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 SDF.\n   * \\param[out] sdf volume to fill with sdf values\n   */\n  void voxelize_sdf(Eigen::Tensor<float, 3, Eigen::RowMajor>& sdf, const VoxelizationMode &mode) {\n\n    int height = sdf.dimension(0);\n    int width = sdf.dimension(1);\n    int depth = sdf.dimension(2);\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\n        sdf(h, w, d) = FLT_MAX;\n\n        // the box corresponding to this voxel\n        Eigen::Vector3f min(w, h, d);\n        Eigen::Vector3f max(w + 1, h + 1, d + 1);\n\n        Eigen::Vector3f center(w + 0.5f, h + 0.5f, d + 0.5f);\n        if (mode == VoxelizationMode::CORNER) {\n          center = Eigen::Vector3f(w, h, d);\n        }\n\n        // count number of intersections.\n        int num_intersect = 0;\n        for (unsigned int f = 0; f < this->num_faces(); ++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(h, w, d)) {\n            sdf(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(h, w, d) *= -1;\n        }\n      }\n    }\n  }\n\n  /** \\brief Voxelize the given mesh into an occupancy grid.\n   * \\param[out] occ volume to fill\n   */\n  void voxelize_occ(Eigen::Tensor<int, 3, Eigen::RowMajor>& occ, const VoxelizationMode &mode) {\n\n    int height = occ.dimension(0);\n    int width = occ.dimension(1);\n    int depth = occ.dimension(2);\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\n        Eigen::Vector3f min(w, h, d);\n        Eigen::Vector3f max(w + 1, h + 1, d + 1);\n\n        for (unsigned int f = 0; f < this->num_faces(); ++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          bool overlap = triangle_box_intersection(min, max, v1, v2, v3);\n          if (overlap) {\n            occ(h, w, d) = 1;\n            break;\n          }\n        }\n      }\n    }\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 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 */\ntemplate<int RANK>\nbool write_float_hdf5(const std::string filepath, Eigen::Tensor<float, RANK, Eigen::RowMajor>& tensor) {\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 = RANK;\n    hsize_t dimsf[rank];\n    for (int i = 0; i < rank; i++) {\n      dimsf[i] = tensor.dimension(i);\n\n    }\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*>(tensor.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 */\ntemplate<int RANK>\nbool write_int_hdf5(const std::string filepath, Eigen::Tensor<int, RANK, Eigen::RowMajor>& tensor) {\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 = RANK;\n    hsize_t dimsf[rank];\n    for (int i = 0; i < rank; i++) {\n      dimsf[i] = tensor.dimension(i);\n\n    }\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*>(tensor.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 boost::filesystem::path directory, std::map<int, boost::filesystem::path>& files, const std::string extension = \".off\") {\n\n  files.clear();\n  boost::filesystem::directory_iterator end;\n\n  for (boost::filesystem::directory_iterator it(directory); 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, boost::filesystem::path>(number, it->path()));\n    }\n  }\n}\n\n/** \\brief Main entrance point of the script.\n * Expects one parameter, the path to the corresponding config file in config/.\n */\nint main(int argc, char** argv) {\n  boost::program_options::options_description desc(\"Allowed options\");\n  desc.add_options()\n      (\"help\", \"produce help message\")\n      (\"mode\", boost::program_options::value<std::string>()->default_value(\"occ\"), \"operation mode, 'occ' or 'sdf'\")\n      (\"input\", boost::program_options::value<std::string>(), \"input, either single OFF file or directory containing OFF files where the names correspond to integers (zero padding allowed) and are consecutively numbered starting with zero\")\n      (\"height\", boost::program_options::value<int>()->default_value(32), \"height of volume, corresponding to y-axis (=up)\")\n      (\"width\", boost::program_options::value<int>()->default_value(32), \"width of volume, corresponding to x-axis (=right\")\n      (\"depth\", boost::program_options::value<int>()->default_value(32), \"depth of volume, corresponding to z-axis (=forward)\")\n      (\"center\", boost::program_options::bool_switch()->default_value(false), \"by default, the top-left-front corner is used for SDF computation; if instead the voxel centers should be used, set this flag\")\n      (\"output\", boost::program_options::value<std::string>(), \"output file, will be a HDF5 file containing either a N x C x height x width x depth tensor or a C x height x width x depth tensor, where N is the number of files and C=2 the number of channels, N is discarded if only a single file is processed; should have the .h5 extension\");\n\n  boost::program_options::positional_options_description positionals;\n  positionals.add(\"mode\", 1);\n  positionals.add(\"input\", 1);\n  positionals.add(\"output\", 1);\n\n  boost::program_options::variables_map parameters;\n  boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(desc).positional(positionals).run(), parameters);\n  boost::program_options::notify(parameters);\n\n  if (parameters.find(\"help\") != parameters.end()) {\n    std::cout << desc << std::endl;\n    return 0;\n  }\n\n  std::string mode = parameters[\"mode\"].as<std::string>();\n  if (mode == \"occ\") {\n    std::cout << \"Voxelizing occupancy grids.\" << std::endl;\n  }\n  else if (mode == \"sdf\") {\n    std::cout << \"Voxelizing SDFs.\" << std::endl;\n  }\n  else {\n    std::cout << \"Invalid mode, choose from occ or sdf.\" << std::endl;\n    return 1;\n  }\n\n  boost::filesystem::path input(parameters[\"input\"].as<std::string>());\n  if (!boost::filesystem::is_directory(input) && !boost::filesystem::is_regular_file(input)) {\n    std::cout << \"Input is neither directory nor file.\" << std::endl;\n    return 1;\n  }\n\n  boost::filesystem::path output(parameters[\"output\"].as<std::string>());\n  if (boost::filesystem::is_regular_file(output)) {\n    std::cout << \"Output file already exists; overwriting.\" << std::endl;\n  }\n\n  VoxelizationMode voxelization_mode;\n  if (parameters[\"center\"].as<bool>()) {\n    voxelization_mode = VoxelizationMode::CENTER;\n    std::cout << \"Using the top-left-front voxel corner for voxelization.\" << std::endl;\n  }\n  else {\n    voxelization_mode = VoxelizationMode::CORNER;\n    std::cout << \"Using the voxel center for voxelization.\" << std::endl;\n  }\n\n  int height = parameters[\"height\"].as<int>();\n  int width = parameters[\"width\"].as<int>();\n  int depth = parameters[\"depth\"].as<int>();\n\n  std::cout << \"Voxelizing into \" << height << \" x \" << width << \" x \" << depth << \" (height x width x depth).\" << std::endl;\n\n  if (boost::filesystem::is_regular_file(input)) {\n    Mesh mesh;\n    bool success = Mesh::from_off(input.string(), mesh);\n\n    if (!success) {\n      std::cout << \"Could not read \" << input << \".\" << std::endl;\n      return 1;\n    }\n\n    std::cout << \"Read \" << input << \".\" << std::endl;\n\n    if (mode == \"sdf\") {\n      Eigen::Tensor<float, 3, Eigen::RowMajor> tensor(height, width, depth);\n\n      mesh.voxelize_sdf(tensor, voxelization_mode);\n      std::cout << \"Voxelized \" << input << \".\" << std::endl;\n\n      bool success = write_float_hdf5<3>(output.string(), tensor);\n\n      if (!success) {\n        std::cout << \"Could not write \" << output << \".\" << std::endl;\n        return 1;\n      }\n    }\n    if (mode == \"occ\") {\n      Eigen::Tensor<int, 3, Eigen::RowMajor> tensor(height, width, depth);\n      tensor.setZero();\n\n      mesh.voxelize_occ(tensor, voxelization_mode);\n      std::cout << \"Voxelized \" << input << \".\" << std::endl;\n\n      bool success = write_int_hdf5<3>(output.string(), tensor);\n\n      if (!success) {\n        std::cout << \"Could not write \" << output << \".\" << std::endl;\n        return 1;\n      }\n    }\n\n    std::cout << \"Wrote \" << output << \".\" << std::endl;\n    std::cout << \"The output is a \" << height << \" x \" << width << \" x \" << depth << \" tensor.\" << std::endl;\n  }\n  else {\n    std::map<int, boost::filesystem::path> input_files;\n    read_directory(input, input_files);\n\n    if (input_files.size() <= 0) {\n      std::cout << \"Could not find any OFF files in the input directory.\" << std::endl;\n      return 1;\n    }\n\n    std::cout << \"Read \" << input_files.size() << \" files.\" << std::endl;\n\n    if (mode == \"sdf\") {\n      Eigen::Tensor<float, 4, Eigen::RowMajor> tensor(input_files.size(), height, width, depth);\n\n      int i = 0;\n      for (std::map<int, boost::filesystem::path>::iterator it = input_files.begin(); it != input_files.end(); it++) {\n        Mesh mesh;\n        bool success = Mesh::from_off(it->second.string(), mesh);\n\n        if (!success) {\n          std::cout << \"Could not read \" << it->second << \".\" << std::endl;\n          return 1;\n        }\n\n        Eigen::Tensor<float, 3, Eigen::RowMajor> slice(height, width, depth);\n        mesh.voxelize_sdf(slice, voxelization_mode);\n        tensor.chip(i, 0) = slice;\n        std::cout << \"Voxelized \" << it->second << \" (\" << (i + 1) << \" of \" << input_files.size() << \").\" << std::endl;\n\n        i++;\n      }\n\n      bool success = write_float_hdf5<4>(output.string(), tensor);\n\n      if (!success) {\n        std::cout << \"Could not write \" << output << \".\" << std::endl;\n        return 1;\n      }\n    }\n    if (mode == \"occ\") {\n      Eigen::Tensor<int, 4, Eigen::RowMajor> tensor(input_files.size(), height, width, depth);\n      tensor.setZero();\n\n      int i = 0;\n      for (std::map<int, boost::filesystem::path>::iterator it = input_files.begin(); it != input_files.end(); it++) {\n        Mesh mesh;\n        bool success = Mesh::from_off(it->second.string(), mesh);\n\n        if (!success) {\n          std::cout << \"Could not read \" << it->second << \".\" << std::endl;\n          return 1;\n        }\n\n        Eigen::Tensor<int, 3, Eigen::RowMajor> slice(height, width, depth);\n        slice.setZero();\n\n        mesh.voxelize_occ(slice, voxelization_mode);\n        tensor.chip(i, 0) = slice;\n        std::cout << \"Voxelized \" << it->second << \" (\" << (i + 1) << \" of \" << input_files.size() << \").\" << std::endl;\n\n        i++;\n      }\n\n      bool success = write_int_hdf5<4>(output.string(), tensor);\n\n      if (!success) {\n        std::cout << \"Could not write \" << output << \".\" << std::endl;\n        return 1;\n      }\n    }\n\n    std::cout << \"Wrote \" << output << \".\" << std::endl;\n    std::cout << \"The output is a \" << input_files.size() << \" x \" << height << \" x \" << width << \" x \" << depth << \" tensor.\" << std::endl;\n  }\n\n  return 0;\n}", "meta": {"hexsha": "cd5a9f67bb4d34302687e63c2b33356fd1fd0151", "size": 22925, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "FairyPig/mesh-voxelization", "max_stars_repo_head_hexsha": "5f597c421cb04857f0959725627b02c1949d31ad", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-08-02T12:20:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T08:43:48.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "FairyPig/mesh-voxelization", "max_issues_repo_head_hexsha": "5f597c421cb04857f0959725627b02c1949d31ad", "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": "main.cpp", "max_forks_repo_name": "FairyPig/mesh-voxelization", "max_forks_repo_head_hexsha": "5f597c421cb04857f0959725627b02c1949d31ad", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-08-02T12:20:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-07T08:43:52.000Z", "avg_line_length": 29.811443433, "max_line_length": 341, "alphanum_fraction": 0.6026608506, "num_tokens": 6366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.29774974864482723}}
{"text": "/*********************************************************************************\n *  OKVIS - Open Keyframe-based Visual-Inertial SLAM\n *  Copyright (c) 2015, Autonomous Systems Lab / ETH Zurich\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 *   * Neither the name of Autonomous Systems Lab / ETH Zurich nor the names of\n *     its 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 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 *  Created on: Jan 7, 2014\n *      Author: Stefan Leutenegger (s.leutenegger@imperial.ac.uk)\n *********************************************************************************/\n\n/**\n * @file odeHybrid.hpp\n * @brief Runge Kutta based IMU forward and backward propagation with an extended IMU model.\n * developed from ode.hpp in okvis.\n * @author Jianzhu Huai\n */\n\n#ifndef INCLUDE_SWIFT_VIO_ODE_HYBRID_HPP_\n#define INCLUDE_SWIFT_VIO_ODE_HYBRID_HPP_\n\n#include <swift_vio/imu/ImuErrorModel.h>\n\n#include <Eigen/Core>\n\n#include <okvis/FrameTypedefs.hpp>\n#include <okvis/Measurements.hpp>\n#include <okvis/Variables.hpp>\n#include <okvis/assert_macros.hpp>\n#include <okvis/kinematics/Transformation.hpp>\n#include <okvis/kinematics/operators.hpp>\n\nnamespace swift_vio {\nnamespace ode {\nconst int kNavErrorStateDim = 9;\n// Note this function assume that the W frame has z axis along the negative gravity.\n// This fact is used in computing velocity in the W frame.\n__inline__ void evaluateContinuousTimeOde(\n    const Eigen::Vector3d& gyr, const Eigen::Vector3d& acc, double g,\n    const Eigen::Vector3d& p_WS_W, const Eigen::Quaterniond& q_WS,\n    const okvis::SpeedAndBiases& sb,\n    const ImuErrorModel<double>& iem, Eigen::Vector3d& p_WS_W_dot,\n    Eigen::Vector4d& q_WS_dot, okvis::SpeedAndBiases& sb_dot,\n    Eigen::MatrixXd* F_c_ptr = 0) {\n  Eigen::Vector3d omega_S;\n  Eigen::Vector3d acc_S;\n  iem.estimate(gyr, acc, &omega_S, &acc_S);\n\n  // nonlinear states\n  // start with the pose\n  p_WS_W_dot = sb.head<3>();\n\n  // now the quaternion\n  Eigen::Vector4d dq;\n  q_WS_dot.head<3>() = 0.5 * omega_S;\n  q_WS_dot[3] = 0.0;\n  Eigen::Matrix3d C_WS = q_WS.toRotationMatrix();\n\n  // the rest is straightforward\n  // consider Earth's radius. Model the Earth as a sphere, since we neither\n  // know the position nor yaw (except if coupled with GPS and magnetometer).\n  Eigen::Vector3d G =\n      -p_WS_W - Eigen::Vector3d(0, 0, 6371009);  // vector to Earth center\n  sb_dot.head<3>() = (C_WS * acc_S + g * G.normalized());  // s\n  // biases\n  sb_dot.tail<6>().setZero();\n\n  // linearized system:\n  if (F_c_ptr) {\n    F_c_ptr->setZero();\n    F_c_ptr->block<3, 3>(0, 6) = Eigen::Matrix3d::Identity();\n    //    F_c_ptr->block<3, 3>(3, 9) -= C_WS;\n    F_c_ptr->block<3, 3>(6, 3) -= okvis::kinematics::crossMx(C_WS * acc_S);\n    //    F_c_ptr->block<3, 3>(6, 12) -= C_WS;\n    Eigen::Matrix<double, 9, 6> N = Eigen::Matrix<double, 9, 6>::Zero();\n    N.block<3, 3>(3, 0) = C_WS;\n    N.block<3, 3>(6, 3) = C_WS;\n    int colsF = F_c_ptr->cols();\n    Eigen::Matrix<double, 6, 6 + 27> dwaB_dbgbaSTS;\n    iem.dwa_B_dbgbaSTS(omega_S, acc_S, dwaB_dbgbaSTS);\n    F_c_ptr->block(0, 9, 9, colsF - 9) = N * dwaB_dbgbaSTS.rightCols(colsF - 9);\n  }\n}\n\n// p_WS_W, q_WS, sb are states at k\n/* * covariance error states $\\Delta y = \\Delta[\\mathbf{p}_{WS}^W,\n\\Delta\\mathbf{\\alpha}, \\Delta\\mathbf{v}_S^W,\n * \\Delta\\mathbf{b_g}, \\Delta\\mathbf{b_a}, \\Delta\\mathbf{Tg}, \\Delta\\mathbf{Ts},\n\\Delta\\mathbf{Ta}]$\n * $\\tilde{R}_s^w=(I-[\\delta\\alpha^w]_\\times)R_s^w$\n * this DEFINITION OF ROTATION ERROR is the same in Mingyang Li's later\npublications, okvis, and huai ION GNSS+ 2015 $y = [\\mathbf{p}_{WS}^W,\n\\mathbf{q}_S^W, \\mathbf{v}_S^W, \\mathbf{b_g}, \\mathbf{b_a}]$ $u =\n[\\mathbf{\\omega}_{WS}^S,\\mathbf{a}^S]$ $h = t_{n+1}-t_n$\n$\\mathbf{p}_{WS}^W \\oplus = \\mathbf{p}_{WS}^W +$\n$\\mathbf{v}_{WS}^W \\oplus = \\mathbf{v}_{WS}^W +$\n$\\mathbf{q}_{S}^W \\oplus \\mathbf{\\omega}_{WS}^S h/2 =\n\\mathbf{q}_{S}^W\\begin{bmatrix}\ncos(\\mathbf{\\omega}_{WS}^S h/2) \\\\\nsin(\\mathbf{\\omega}_{WS}^S\nh/2)\\frac{\\mathbf{\\omega}_{WS}^S/2}{\\vert\\mathbf{\\omega}_{WS}^S/2\\vert}\n\\end{bmatrix}$\n\n$k_1 = f(t_n,y_n,u_n)$\n$k_2 = f(t_n+h/2,y_n\\oplus k_1 h/2 ,(u_n +u_{n+1})/2)$\n$k_3 = f(t_n+h/2,y_n\\oplus k_2 h/2 ,(u_n +u_{n+1})/2)$\n$k_4 = f(t_n+h,y_n\\oplus k_3 h , u_{n+1})$\n$y_{n+1}=y_n\\oplus\\left(h(k_1 +2k_2 +2k_3 +k_4)/6 \\right )$\nCaution: provide both F_tot_ptr(e.g., identity) and P_ptr(e.g., zero matrix) if\ncovariance is to be computed\n*/\n__inline__ void integrateOneStep_RungeKutta(\n    const Eigen::Vector3d& gyr_0, const Eigen::Vector3d& acc_0,\n    const Eigen::Vector3d& gyr_1, const Eigen::Vector3d& acc_1, double g,\n    double sigma_g_c, double sigma_a_c, double sigma_gw_c, double sigma_aw_c,\n    double dt, Eigen::Vector3d& p_WS_W, Eigen::Quaterniond& q_WS,\n    okvis::SpeedAndBiases& sb, const ImuErrorModel<double>& iem,\n    Eigen::MatrixXd* P_ptr = 0,\n    Eigen::MatrixXd* F_tot_ptr = 0) {\n  Eigen::Vector3d k1_p_WS_W_dot;\n  Eigen::Vector4d k1_q_WS_dot;\n\n  okvis::SpeedAndBiases k1_sb_dot;\n  int covRows = 0;\n  Eigen::MatrixXd k1_F_c;\n  Eigen::MatrixXd k2_F_c;\n  Eigen::MatrixXd k3_F_c;\n  Eigen::MatrixXd k4_F_c;\n  Eigen::MatrixXd* k1_F_c_ptr = nullptr;\n  Eigen::MatrixXd* k2_F_c_ptr = nullptr;\n  Eigen::MatrixXd* k3_F_c_ptr = nullptr;\n  Eigen::MatrixXd* k4_F_c_ptr = nullptr;\n  if (P_ptr || F_tot_ptr) {\n      covRows = P_ptr ? P_ptr->rows() : F_tot_ptr->rows();\n      k1_F_c.resize(covRows, covRows);\n      k2_F_c.resize(covRows, covRows);\n      k3_F_c.resize(covRows, covRows);\n      k4_F_c.resize(covRows, covRows);\n      k1_F_c_ptr = &k1_F_c;\n      k2_F_c_ptr = &k2_F_c;\n      k3_F_c_ptr = &k3_F_c;\n      k4_F_c_ptr = &k4_F_c;\n  }\n\n  evaluateContinuousTimeOde(gyr_0, acc_0, g, p_WS_W, q_WS, sb, iem,\n                            k1_p_WS_W_dot, k1_q_WS_dot, k1_sb_dot, k1_F_c_ptr);\n\n  Eigen::Vector3d p_WS_W1 = p_WS_W;\n  Eigen::Quaterniond q_WS1 = q_WS;\n  okvis::SpeedAndBiases sb1 = sb;\n  // state propagation:\n  p_WS_W1 += k1_p_WS_W_dot * 0.5 * dt;\n  Eigen::Quaterniond dq;\n  double theta_half = k1_q_WS_dot.head<3>().norm() * 0.5 * dt;\n  double sinc_theta_half = okvis::kinematics::sinc(theta_half);\n  double cos_theta_half = cos(theta_half);\n  dq.vec() = sinc_theta_half * k1_q_WS_dot.head<3>() * 0.5 * dt;\n  dq.w() = cos_theta_half;\n  q_WS1 = q_WS * dq;\n  sb1 += k1_sb_dot * 0.5 * dt;\n\n  Eigen::Vector3d k2_p_WS_W_dot;\n  Eigen::Vector4d k2_q_WS_dot;\n  okvis::SpeedAndBiases k2_sb_dot;\n  evaluateContinuousTimeOde(0.5 * (gyr_0 + gyr_1), 0.5 * (acc_0 + acc_1), g,\n                            p_WS_W1, q_WS1, sb1, iem, k2_p_WS_W_dot,\n                            k2_q_WS_dot, k2_sb_dot, k2_F_c_ptr);\n\n  Eigen::Vector3d p_WS_W2 = p_WS_W;\n  Eigen::Quaterniond q_WS2 = q_WS;\n  okvis::SpeedAndBiases sb2 = sb;\n  // state propagation:\n  p_WS_W2 += k2_p_WS_W_dot * 0.5 * dt;\n  theta_half = k2_q_WS_dot.head<3>().norm() * 0.5 * dt;\n  sinc_theta_half = okvis::kinematics::sinc(theta_half);\n  cos_theta_half = cos(theta_half);\n  dq.vec() = sinc_theta_half * k2_q_WS_dot.head<3>() * 0.5 * dt;\n  dq.w() = cos_theta_half;\n  // std::cout<<dq.transpose()<<std::endl;\n  q_WS2 = q_WS2 * dq;\n  sb2 += k1_sb_dot * 0.5 * dt;\n\n  Eigen::Vector3d k3_p_WS_W_dot;\n  Eigen::Vector4d k3_q_WS_dot;\n  okvis::SpeedAndBiases k3_sb_dot;\n  evaluateContinuousTimeOde(0.5 * (gyr_0 + gyr_1), 0.5 * (acc_0 + acc_1), g,\n                            p_WS_W2, q_WS2, sb2, iem, k3_p_WS_W_dot,\n                            k3_q_WS_dot, k3_sb_dot, k3_F_c_ptr);\n\n  Eigen::Vector3d p_WS_W3 = p_WS_W;\n  Eigen::Quaterniond q_WS3 = q_WS;\n  okvis::SpeedAndBiases sb3 = sb;\n  // state propagation:\n  p_WS_W3 += k3_p_WS_W_dot * dt;\n  theta_half = k3_q_WS_dot.head<3>().norm() * dt;\n  sinc_theta_half = okvis::kinematics::sinc(theta_half);\n  cos_theta_half = cos(theta_half);\n  dq.vec() = sinc_theta_half * k3_q_WS_dot.head<3>() * dt;\n  dq.w() = cos_theta_half;\n  // std::cout<<dq.transpose()<<std::endl;\n  q_WS3 = q_WS3 * dq;\n  sb3 += k3_sb_dot * dt;\n\n  Eigen::Vector3d k4_p_WS_W_dot;\n  Eigen::Vector4d k4_q_WS_dot;\n  okvis::SpeedAndBiases k4_sb_dot;\n  evaluateContinuousTimeOde(gyr_1, acc_1, g, p_WS_W3, q_WS3, sb3, iem,\n                            k4_p_WS_W_dot, k4_q_WS_dot, k4_sb_dot, k4_F_c_ptr);\n\n  // now assemble\n  p_WS_W +=\n      (k1_p_WS_W_dot + 2 * (k2_p_WS_W_dot + k3_p_WS_W_dot) + k4_p_WS_W_dot) *\n      dt / 6.0;\n  Eigen::Vector3d theta_half_vec =\n      (k1_q_WS_dot.head<3>() +\n       2 * (k2_q_WS_dot.head<3>() + k3_q_WS_dot.head<3>()) +\n       k4_q_WS_dot.head<3>()) *\n      dt / 6.0;\n  theta_half = theta_half_vec.norm();\n  sinc_theta_half = okvis::kinematics::sinc(theta_half);\n  cos_theta_half = cos(theta_half);\n  dq.vec() = sinc_theta_half * theta_half_vec;\n  dq.w() = cos_theta_half;\n  q_WS = q_WS * dq;\n  sb += (k1_sb_dot + 2 * (k2_sb_dot + k3_sb_dot) + k4_sb_dot) * dt / 6.0;\n\n  q_WS.normalize();  // do not accumulate errors!\n\n  if (F_tot_ptr) {\n    // compute state transition matrix, note $\\frac{d\\Phi(t, t_0)}{dt}=\n    // F(t)\\Phi(t, t_0)$\n    Eigen::MatrixXd& F_tot = *F_tot_ptr;\n    const Eigen::MatrixXd& J1 = k1_F_c;\n    const Eigen::MatrixXd J2 =\n        k2_F_c * (Eigen::MatrixXd::Identity(covRows, covRows) + 0.5 * dt * J1);\n    const Eigen::MatrixXd J3 =\n        k3_F_c * (Eigen::MatrixXd::Identity(covRows, covRows) + 0.5 * dt * J2);\n    const Eigen::MatrixXd J4 =\n        k4_F_c * (Eigen::MatrixXd::Identity(covRows, covRows) + dt * J3);\n    Eigen::MatrixXd F = Eigen::MatrixXd::Identity(covRows, covRows) +\n                        dt * (J1 + 2 * (J2 + J3) + J4) / 6.0;\n    F_tot =\n        (F * F_tot)\n            .eval();  // F is $\\Phi(t_k, t_{k-1})$, F_tot is $\\Phi(t_k, t_{0})$\n\n    if (P_ptr) {\n      Eigen::MatrixXd& cov = *P_ptr;\n      cov = F * (cov * F.transpose()).eval();\n\n      // add process noise\n      const double Q_g = sigma_g_c * sigma_g_c * dt;\n      const double Q_a = sigma_a_c * sigma_a_c * dt;\n      const double Q_gw = sigma_gw_c * sigma_gw_c * dt;\n      const double Q_aw = sigma_aw_c * sigma_aw_c * dt;\n      cov(3, 3) += Q_g;\n      cov(4, 4) += Q_g;\n      cov(5, 5) += Q_g;\n      cov(6, 6) += Q_a;\n      cov(7, 7) += Q_a;\n      cov(8, 8) += Q_a;\n      cov(9, 9) += Q_gw;\n      cov(10, 10) += Q_gw;\n      cov(11, 11) += Q_gw;\n      cov(12, 12) += Q_aw;\n      cov(13, 13) += Q_aw;\n      cov(14, 14) += Q_aw;\n\n      // force symmetric\n      // huai: this may help keep cov positive semi-definite after propagation\n      cov = 0.5 * cov + 0.5 * cov.transpose().eval();\n    }\n  }\n}\n\n/* p_WS_W, q_WS, sb are states at k+1, dt= t(k+1) -t(k)\n$y = [\\mathbf{p}_{WS}^W, \\mathbf{q}_S^W, \\mathbf{v}_S^W, \\mathbf{b_g},\n\\mathbf{b_a}]$ $u = [\\mathbf{\\omega}_{WS}^S,\\mathbf{a}^S]$ $h = t_{n}-t_{n+1}$\n$\\mathbf{p}_{WS}^W \\oplus = \\mathbf{p}_{WS}^W +$\n$\\mathbf{v}_{WS}^W \\oplus = \\mathbf{v}_{WS}^W +$\n$\\mathbf{q}_{S}^W \\oplus \\mathbf{\\omega}_{WS}^S h/2 =\n\\mathbf{q}_{S}^W\\begin{bmatrix}\ncos(\\mathbf{\\omega}_{WS}^S h/2) \\\\\nsin(\\mathbf{\\omega}_{WS}^S\nh/2)\\frac{\\mathbf{\\omega}_{WS}^S/2}{\\vert\\mathbf{\\omega}_{WS}^S/2\\vert}\n\\end{bmatrix}$\n\n$k_1 = f(t_{n+1},y_{n+1},u_{n+1})$\n$k_2 = f(t_{n+1}+h/2,y_{n+1}\\oplus k_1 h/2 ,(u_n +u_{n+1})/2)$\n$k_3 = f(t_{n+1}+h/2,y_{n+1}\\oplus k_2 h/2 ,(u_n +u_{n+1})/2)$\n$k_4 = f(t_n,y_{n+1}\\oplus k_3 h , u_{n})$\n$y_{n}=y_{n+1}\\oplus\\left(h(k_1 +2k_2 +2k_3 +k_4)/6 \\right )$\n*/\n__inline__ void integrateOneStepBackward_RungeKutta(\n    const Eigen::Vector3d& gyr_0, const Eigen::Vector3d& acc_0,\n    const Eigen::Vector3d& gyr_1, const Eigen::Vector3d& acc_1, double g,\n    double sigma_g_c, double sigma_a_c, double sigma_gw_c, double sigma_aw_c,\n    double dt, Eigen::Vector3d& p_WS_W, Eigen::Quaterniond& q_WS,\n    okvis::SpeedAndBiases& sb, const ImuErrorModel<double>& iem,\n    Eigen::MatrixXd* P_ptr = 0,\n    Eigen::MatrixXd* F_tot_ptr = 0) {\n  Eigen::Vector3d k1_p_WS_W_dot;\n  Eigen::Vector4d k1_q_WS_dot;\n  okvis::SpeedAndBiases k1_sb_dot;\n\n  int covRows = 0;\n  Eigen::MatrixXd k1_F_c;\n  Eigen::MatrixXd k2_F_c;\n  Eigen::MatrixXd k3_F_c;\n  Eigen::MatrixXd k4_F_c;\n  Eigen::MatrixXd* k1_F_c_ptr = nullptr;\n  Eigen::MatrixXd* k2_F_c_ptr = nullptr;\n  Eigen::MatrixXd* k3_F_c_ptr = nullptr;\n  Eigen::MatrixXd* k4_F_c_ptr = nullptr;\n  if (P_ptr || F_tot_ptr) {\n      covRows = P_ptr ? P_ptr->rows() : F_tot_ptr->rows();\n      k1_F_c.resize(covRows, covRows);\n      k2_F_c.resize(covRows, covRows);\n      k3_F_c.resize(covRows, covRows);\n      k4_F_c.resize(covRows, covRows);\n      k1_F_c_ptr = &k1_F_c;\n      k2_F_c_ptr = &k2_F_c;\n      k3_F_c_ptr = &k3_F_c;\n      k4_F_c_ptr = &k4_F_c;\n  }\n\n  evaluateContinuousTimeOde(gyr_1, acc_1, g, p_WS_W, q_WS, sb, iem,\n                            k1_p_WS_W_dot, k1_q_WS_dot, k1_sb_dot, k1_F_c_ptr);\n\n  Eigen::Vector3d p_WS_W1 = p_WS_W;\n  Eigen::Quaterniond q_WS1 = q_WS;\n  okvis::SpeedAndBiases sb1 = sb;\n  // state propagation:\n  p_WS_W1 -= k1_p_WS_W_dot * 0.5 * dt;\n  Eigen::Quaterniond dq;\n  double theta_half = -k1_q_WS_dot.head<3>().norm() * 0.5 * dt;\n  double sinc_theta_half = okvis::kinematics::sinc(theta_half);\n  double cos_theta_half = cos(theta_half);\n  dq.vec() = -sinc_theta_half * k1_q_WS_dot.head<3>() * 0.5 * dt;\n  dq.w() = cos_theta_half;\n  q_WS1 = q_WS * dq;\n  sb1 -= k1_sb_dot * 0.5 * dt;\n\n  Eigen::Vector3d k2_p_WS_W_dot;\n  Eigen::Vector4d k2_q_WS_dot;\n  okvis::SpeedAndBiases k2_sb_dot;\n  evaluateContinuousTimeOde(0.5 * (gyr_0 + gyr_1), 0.5 * (acc_0 + acc_1), g,\n                            p_WS_W1, q_WS1, sb1, iem, k2_p_WS_W_dot,\n                            k2_q_WS_dot, k2_sb_dot, k2_F_c_ptr);\n\n  Eigen::Vector3d p_WS_W2 = p_WS_W;\n  Eigen::Quaterniond q_WS2 = q_WS;\n  okvis::SpeedAndBiases sb2 = sb;\n  // state propagation:\n  p_WS_W2 -= k2_p_WS_W_dot * 0.5 * dt;\n  theta_half = -k2_q_WS_dot.head<3>().norm() * 0.5 * dt;\n  sinc_theta_half = okvis::kinematics::sinc(theta_half);\n  cos_theta_half = cos(theta_half);\n  dq.vec() = -sinc_theta_half * k2_q_WS_dot.head<3>() * 0.5 * dt;\n  dq.w() = cos_theta_half;\n  // std::cout<<dq.transpose()<<std::endl;\n  q_WS2 = q_WS2 * dq;\n  sb2 -= k1_sb_dot * 0.5 * dt;\n\n  Eigen::Vector3d k3_p_WS_W_dot;\n  Eigen::Vector4d k3_q_WS_dot;\n  okvis::SpeedAndBiases k3_sb_dot;\n  evaluateContinuousTimeOde(0.5 * (gyr_0 + gyr_1), 0.5 * (acc_0 + acc_1), g,\n                            p_WS_W2, q_WS2, sb2, iem, k3_p_WS_W_dot,\n                            k3_q_WS_dot, k3_sb_dot, k3_F_c_ptr);\n\n  Eigen::Vector3d p_WS_W3 = p_WS_W;\n  Eigen::Quaterniond q_WS3 = q_WS;\n  okvis::SpeedAndBiases sb3 = sb;\n  // state propagation:\n  p_WS_W3 -= k3_p_WS_W_dot * dt;\n  theta_half = -k3_q_WS_dot.head<3>().norm() * dt;\n  sinc_theta_half = okvis::kinematics::sinc(theta_half);\n  cos_theta_half = cos(theta_half);\n  dq.vec() = -sinc_theta_half * k3_q_WS_dot.head<3>() * dt;\n  dq.w() = cos_theta_half;\n  // std::cout<<dq.transpose()<<std::endl;\n  q_WS3 = q_WS3 * dq;\n  sb3 -= k3_sb_dot * dt;\n\n  Eigen::Vector3d k4_p_WS_W_dot;\n  Eigen::Vector4d k4_q_WS_dot;\n  okvis::SpeedAndBiases k4_sb_dot;\n  evaluateContinuousTimeOde(gyr_0, acc_0, g, p_WS_W3, q_WS3, sb3, iem,\n                            k4_p_WS_W_dot, k4_q_WS_dot, k4_sb_dot, k4_F_c_ptr);\n\n  // now assemble\n  p_WS_W -=\n      (k1_p_WS_W_dot + 2 * (k2_p_WS_W_dot + k3_p_WS_W_dot) + k4_p_WS_W_dot) *\n      dt / 6.0;\n  Eigen::Vector3d theta_half_vec =\n      -(k1_q_WS_dot.head<3>() +\n        2 * (k2_q_WS_dot.head<3>() + k3_q_WS_dot.head<3>()) +\n        k4_q_WS_dot.head<3>()) *\n      dt / 6.0;\n  theta_half = theta_half_vec.norm();\n  sinc_theta_half = okvis::kinematics::sinc(theta_half);\n  cos_theta_half = cos(theta_half);\n  dq.vec() = sinc_theta_half * theta_half_vec;\n  dq.w() = cos_theta_half;\n  q_WS = q_WS * dq;\n  sb -= (k1_sb_dot + 2 * (k2_sb_dot + k3_sb_dot) + k4_sb_dot) * dt / 6.0;\n\n  q_WS.normalize();  // do not accumulate errors!\n\n  if (F_tot_ptr) {\n    assert(false);  // the following section is not well perused and tested\n    // compute state transition matrix, note $\\frac{d\\Phi(t, t_0)}{dt}=\n    // F(t)\\Phi(t, t_0)$\n    Eigen::MatrixXd& F_tot = *F_tot_ptr;\n    const Eigen::MatrixXd& J1 = k1_F_c;\n    const Eigen::MatrixXd J2 =\n        k2_F_c * (Eigen::MatrixXd::Identity(covRows, covRows) - 0.5 * dt * J1);\n    const Eigen::MatrixXd J3 =\n        k3_F_c * (Eigen::MatrixXd::Identity(covRows, covRows) - 0.5 * dt * J2);\n    const Eigen::MatrixXd J4 =\n        k4_F_c * (Eigen::MatrixXd::Identity(covRows, covRows) - dt * J3);\n    Eigen::MatrixXd F = Eigen::MatrixXd::Identity(covRows, covRows) -\n                        dt * (J1 + 2 * (J2 + J3) + J4) / 6.0;\n    F_tot = (F * F_tot).eval();\n\n    if (P_ptr) {\n      Eigen::MatrixXd& cov = *P_ptr;\n      cov = F * (cov * F.transpose()).eval();\n\n      // add process noise\n      const double Q_g = sigma_g_c * sigma_g_c * dt;\n      const double Q_a = sigma_a_c * sigma_a_c * dt;\n      const double Q_gw = sigma_gw_c * sigma_gw_c * dt;\n      const double Q_aw = sigma_aw_c * sigma_aw_c * dt;\n      cov(3, 3) += Q_g;\n      cov(4, 4) += Q_g;\n      cov(5, 5) += Q_g;\n      cov(6, 6) += Q_a;\n      cov(7, 7) += Q_a;\n      cov(8, 8) += Q_a;\n      cov(9, 9) += Q_gw;\n      cov(10, 10) += Q_gw;\n      cov(11, 11) += Q_gw;\n      cov(12, 12) += Q_aw;\n      cov(13, 13) += Q_aw;\n      cov(14, 14) += Q_aw;\n\n      // force symmetric - TODO: is this really needed here?\n      // cov = 0.5 * cov + 0.5 * cov.transpose().eval();\n    }\n  }\n}\n}  // namespace ode\n}  // namespace swift_vio\n\n#endif // INCLUDE_SWIFT_VIO_ODE_HYBRID_HPP_\n", "meta": {"hexsha": "dc023c8a1398700bf39bbe48d1b67a3a14d967e3", "size": 18519, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "okvis_ceres/include/swift_vio/imu/odeHybrid.hpp", "max_stars_repo_name": "wbl1997/okvis", "max_stars_repo_head_hexsha": "65e30d6ab25380d65c96c665485148e2ab55e93e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-26T15:31:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T15:31:53.000Z", "max_issues_repo_path": "okvis_ceres/include/swift_vio/imu/odeHybrid.hpp", "max_issues_repo_name": "wbl1997/okvis", "max_issues_repo_head_hexsha": "65e30d6ab25380d65c96c665485148e2ab55e93e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "okvis_ceres/include/swift_vio/imu/odeHybrid.hpp", "max_forks_repo_name": "wbl1997/okvis", "max_forks_repo_head_hexsha": "65e30d6ab25380d65c96c665485148e2ab55e93e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-08-01T16:49:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T09:00:03.000Z", "avg_line_length": 38.7426778243, "max_line_length": 92, "alphanum_fraction": 0.6389113883, "num_tokens": 6576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.49609382947091957, "lm_q1q2_score": 0.29774974154926315}}
{"text": "/*\n *  sinker.cpp\n *  pybg\n *\n *  Created by BART MOSLEY on 8/12/12.\n *  Copyright 2012 BG Research LLC. All rights reserved.\n *\n */\n\n\n#include <bg/bondgeek.hpp>\n\n#include <iostream>\n\n#include <boost/timer.hpp>\n\nusing namespace std;\nusing namespace QuantLib;\nusing namespace bondgeek;\n\n\n#if defined(QL_ENABLE_SESSIONS)\nnamespace QuantLib {\n    Integer sessionId() { return 0; }\n}\n#endif\n\nvoid showCashFlows(Bond &bnd)\n{\n    Leg fixedLeg = bnd.cashflows();\n    \n    cout << endl << \"Fixed Leg: \" << endl;\n    Leg::iterator fxIt;\n    Date cfDate;\n    double cfAmt;\n    for (fxIt=fixedLeg.begin(); fxIt < fixedLeg.end(); fxIt++) \n    {\n        cfDate = (*fxIt)->date();\n        cfAmt = (*fxIt)->amount();\n        cout << cfDate << \" | \" << cfAmt << endl;\n    }\n    \n}\n\nvoid showAssetSwapCashFlows(AssetSwap &aswap)\n{\n    Leg fixedLeg = aswap.bondLeg();\n    Leg floatLeg = aswap.floatingLeg();\n    \n    Date cfDate;\n    double cfAmt;\n    \n    cout << endl << \"Fixed Leg: \" << endl;\n    Leg::iterator fxIt;\n    for (fxIt=fixedLeg.begin(); fxIt < fixedLeg.end(); fxIt++) \n    {\n        cfDate = (*fxIt)->date();\n        cfAmt = (*fxIt)->amount();\n        cout << cfDate << \" | \" << cfAmt << endl;\n    }\n    cout << endl << \"Floating Leg: \" << endl;\n    Leg::iterator flIt;\n    for (flIt=floatLeg.begin(); flIt < floatLeg.end(); flIt++) \n    {\n        cfDate = (*flIt)->date();\n        cfAmt = (*flIt)->amount();\n        cout << cfDate << \" | \" << cfAmt << endl;\n    }\n    \n}\n\nvoid showRedemptions(Bond &bnd)\n{\n    Leg fixedLeg = bnd.redemptions();\n    \n    cout << endl << \"Redemptions: \" << endl;\n    Leg::iterator fxIt;\n    Date cfDate;\n    double cfAmt;\n    for (fxIt=fixedLeg.begin(); fxIt < fixedLeg.end(); fxIt++) \n    {\n        cfDate = (*fxIt)->date();\n        cfAmt = (*fxIt)->amount();\n        cout << cfDate << \" | \" << cfAmt << endl;\n    }\n    \n}\n\nvoid showNotionals(Bond &bnd)\n{\n    std::vector<Real> bnd_notionals = bnd.notionals();\n    \n    cout << endl << \"Notionals: \" << endl;\n    std::vector<Real>::iterator it;\n    int notional_count = 0;\n    for (it=bnd_notionals.begin(); it < bnd_notionals.end(); it++) {\n        notional_count++;\n        cout << notional_count << \": \" << *it << endl;\n    }\n    \n}\n\n\nint main (int argc, char * const argv[]) \n{\n    \n    Date today = Date(16,October,2007);\n    Settings::instance().evaluationDate() = today;\n\n    cout << endl << \"Today: \" << today << endl;\n    cout << \"Price with a bg curve \" << endl;\n    string depotenors[] = {\"1W\", \"1M\", \"3M\", \"6M\", \"9M\"};\n    double depospots[] = {0.0018400, 0.0023050, 0.0041825,\n                          0.0070765, 0.0086780};\n    string swaptenors[] = {\"2y\", \"3y\", \"5y\", \"10Y\", \n                           \"15Y\", \"20Y\", \"30Y\"};\n    double swapspots[] = {.0040100, 0.0042600, 0.0077300, 0.0106595, \n                          0.0211555, 0.02310205, 0.0247007};\n    \n    cout << \"Test with new curve \" << endl;\n    RateHelperCurve usdLiborCurve = RateHelperCurve(USDLiborCurve(\"3M\"));\n    usdLiborCurve.update(depotenors, \n                         depospots, \n                         5,\n                         swaptenors,                                                                      \n                         swapspots,\n                         7,\n                         today);\n    \n    boost::shared_ptr<PricingEngine> discEngine = \\\n    createPriceEngine<DiscountingBondEngine>(\n                                             usdLiborCurve.discountingTermStructure()\n                                             );\n    \n    // set up the callable bond\n    Real coupon = .06;\n    Date maturity(15, September,2012);\n    Date maturity1(15, September, 2011);\n    Date maturity0(15, September, 2010);\n    \n    Date dated(16,September,2004);\n    \n    Natural settlementDays = 3;  // Bloomberg OAS1 settle is Oct 19, 2007\n    Frequency frequency = Semiannual;\n    \n    Calendar bondCalendar = UnitedStates(UnitedStates::GovernmentBond);\n    DayCounter bondDayCounter = ActualActual(ActualActual::Bond);\n    \n    Real faceAmount = 100.0; // Notional amount\n    Real redemption = 100.0; // Amount paid on redemption\n    \n    BusinessDayConvention accrualConvention = Unadjusted;\n    BusinessDayConvention paymentConvention = Unadjusted;\n    \n    cout << endl << endl\n    << \"Generic Bond\"\n    << endl;\n    SinkingFundBond bnd(coupon,\n                        maturity,\n                        std::vector<Real>(1, faceAmount),\n                        Annual,\n                        dated,\n                        bondCalendar,\n                        settlementDays,\n                        bondDayCounter,\n                        frequency,\n                        redemption,\n                        faceAmount,\n                        accrualConvention,\n                        paymentConvention\n                        );\n    \n    showCashFlows(bnd);\n\n    cout << \"\\n\\none year shorter\" << endl;\n    SinkingFundBond bnd0(coupon,\n                         maturity0,\n                         std::vector<Real>(1, faceAmount),\n                         Annual,\n                         dated,\n                         bondCalendar,\n                         settlementDays,\n                         bondDayCounter,\n                         frequency,\n                         redemption,\n                         faceAmount,\n                         accrualConvention,\n                         paymentConvention\n                         );\n    \n    showCashFlows(bnd0);\n    \n    cout << \"\\n\\ntwo years shorter\" << endl;\n    SinkingFundBond bnd1(coupon,\n                         maturity1,\n                         std::vector<Real>(1, faceAmount),\n                         Annual,\n                         dated,\n                         bondCalendar,\n                         settlementDays,\n                         bondDayCounter,\n                         frequency,\n                         redemption,\n                         faceAmount,\n                         accrualConvention,\n                         paymentConvention\n                         );\n    showCashFlows(bnd1);\n\n    /* Sinkfing fund amortization:\n     \n     notionals start at par on the dated date and end at zero on maturity.\n     redemptions are the prices redemption prices (pct of par, e.g. 101.)\n\n     */\n    \n    double sf_sch[] = {\n        40000, 40000, 40000, 40000, 40000, 40000,\n        40000, 40000, 40000, 40000, 40000, 40000,\n        40000\n    };\n    int sf_num = 3;\n    Frequency sf_freq = Annual;\n    \n    std::vector<double> sf_bal;\n    sf_bal.assign(sf_sch, sf_sch+sf_num);\n    \n    Real rval = 100.;\n         \n    cout << endl << endl\n    << \"Amortizing Generic Bond \"\n    << endl;\n    SinkingFundBond bnd2(coupon,\n                         maturity,\n                         sf_bal,\n                         sf_freq,\n                         dated,\n                         bondCalendar,\n                         settlementDays,\n                         bondDayCounter,\n                         frequency,\n                         rval,\n                         faceAmount,\n                         accrualConvention,\n                         paymentConvention\n                         ); \n    \n    // show the results\n    showCashFlows(bnd2);\n    \n    bnd0.setPricingEngine(discEngine);\n    bnd1.setPricingEngine(discEngine);\n    bnd.setPricingEngine(discEngine);\n    bnd2.setPricingEngine(discEngine);\n    \n    double prc0 = bnd0.cleanPrice();\n    double prc1 = bnd1.cleanPrice();\n    double prc = bnd.cleanPrice();\n    double prc2 = bnd2.cleanPrice();\n    \n    cout << endl << \"Pricing component bonds\" << endl \n    << \"priced0: \" << prc0 << endl \n    << \"priced1: \" << prc1 << endl \n    << \"priced: \" << prc << endl\n    << \"avg price: \" << (prc0+prc1+prc)/3. << endl\n    << endl \n    << \"priced sinking fund bond: \" << prc2 << endl;\n    cout << \"cf yield: \" << bnd.toYield(prc2) << endl;\n    \n    return 0;\n}\n\n", "meta": {"hexsha": "e11c562986893a1296ed9cc46b6ce2b72bf55155", "size": 7900, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/sinker.cpp", "max_stars_repo_name": "bondgeek/pybg", "max_stars_repo_head_hexsha": "046a25074b78409c6d29302177aeac581ade90d1", "max_stars_repo_licenses": ["Unlicense", "MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-03-14T05:39:15.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-14T05:39:15.000Z", "max_issues_repo_path": "examples/sinker.cpp", "max_issues_repo_name": "bondgeek/pybg", "max_issues_repo_head_hexsha": "046a25074b78409c6d29302177aeac581ade90d1", "max_issues_repo_licenses": ["Unlicense", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/sinker.cpp", "max_forks_repo_name": "bondgeek/pybg", "max_forks_repo_head_hexsha": "046a25074b78409c6d29302177aeac581ade90d1", "max_forks_repo_licenses": ["Unlicense", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9377289377, "max_line_length": 106, "alphanum_fraction": 0.4856962025, "num_tokens": 1933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.2977497415492631}}
{"text": "\n/*\n * Prover.cpp\n *\n *  Created on: 26.10.2010\n *      Author: stephaniebayer\n */\n\n#include \"Prover.h\"\n\n#include<vector>\n#include \"Cipher_elg.h\"\n#include \"G_q.h\"\n#include \"Mod_p.h\"\n#include \"Functions.h\"\n#include \"ElGammal.h\"\n#include \"func_pro.h\"\n#include \"fft.h\"\n#include<fstream>\n\n#include <time.h>\n#include <NTL/ZZ.h>\nNTL_CLIENT\n\nextern G_q H;\nextern ElGammal El;\n\nProver::Prover() {\n\t// TODO Auto-generated constructor stub\n\n}\n\nProver::Prover(vector<vector<Cipher_elg>* >* Cin, vector<vector<ZZ>* >* Rin, vector<vector<vector<long>* >* >* piin, vector<long> num, ZZ genq){\n\n\t// set the dimensions of the row and columns according to the user input\n\tm = num[1]; //number of rows\n\tn = num[2]; //number of columns\n\tC = Cin; //sets the reencrypted cipertexts to the input\n\tR = Rin; //sets the random elements to the input\n\tpi = piin; // sets the permutation to the input\n\n\n\tfft *fft_new = new fft;\n\t//o is a root of unity\n\to = fft_new->r_o_u(genq, m, H.get_ord());\n\n\n\tA = new vector<vector<ZZ>* >(m);\n\tfunc_pro::set_A(A,pi, m, n);\n\n\t//Allocate the storage needed for the vectors\n\tchal_x6 = new vector<ZZ>(2*m); //x6, x6^2, ... challenges from round 6\n\tchal_y6 = new vector<ZZ>(n); //y6, y6^2, ... challenges form round 6\n\tchal_x8 = new vector<ZZ>(2*m +1); //x8, x8^2, ... challenges from round 8\n\n\t//Allocate the storage needed for the vectors\n\tc_A = new vector<Mod_p>(m+1); //commitments to the rows in A\n\tr_A = new vector<ZZ>(m+1); //random elements used for the commitments\n\n\tD = new vector<vector<ZZ>* >(m+1); //vector containing in the first row random values and in all others y*A(ij) + B(ij)-z\n\tD_h = new vector<vector<ZZ>* >(m); //Vector of the Hadamare products of the rows in D\n\tD_s = new vector<vector<ZZ>* >(m+1); //Shifted rows of D_h\n\td = new vector<ZZ>(n); //containing random elements to proof product of D_hm\n\tDelta = new vector<ZZ>(n); //containing random elements to proof product of D_hm\n\td_h = new vector<ZZ>(n); // vector containing the last row of D-h\n\n\tr_D_h = new vector<ZZ>(m);//random elements for commitments to D_h\n\tc_D_h = new vector<Mod_p>(m+2);//commitments to the rows in D_h\n\n\tB = new vector<vector<ZZ>* >(m);//matrix of permuted exponents, exponents are x2^i, i=1, ..N\n\tB_0 = new vector<ZZ>(n); //vector containing random exponents\n\tr_B = new vector<ZZ>(m); //random elements used to commit to T\n\tc_B = new vector<Mod_p>(m); //vector of commitments to rows in T\n\ta = new vector<ZZ>(2*m); //elements used for reencryption in round 5\n\tr_a = new vector<ZZ>(2*m); //random elements to commit to elements in a\n\tc_a = new vector<Mod_p>(2*m); //commitments to elements a\n\tE = new vector<Cipher_elg>(2*m); //\n\trho_a = new vector<ZZ>(2*m); //\n\n\tDl = new vector<ZZ>(2*m+1); //bilinear_map(Y_pi, U, chal_t)\n\tr_Dl = new vector<ZZ>(2*m+1); //random elements to commit to the C_ls\n\tc_Dl = new vector<Mod_p>(2*m +1); //commitments to the C_ls\n\n\td_bar = new vector<ZZ>(n);// chal_x8*D_h(m-1) +d\n\tDelta_bar = new vector<ZZ>(n);//chal_x8*d_h+Delta\n\tD_h_bar = new vector<ZZ>(n);//sum over the rows in D_h\n\n\tB_bar  = new vector<ZZ>(n); // sum over the rows in T multiplied by chal^i\n\n\tA_bar = new vector<ZZ>(n); //sum over the rows in Y times the challenges\n\tD_s_bar = new vector<ZZ>(n); // sum over the rows in U times thes challenges\n\n}\n//Destructor deletes all pointers and frees the storage\nProver::~Prover() {\n\tdelete chal_x6;\n\tdelete chal_y6;\n\tdelete chal_x8;\n\tdelete c_A;\n\tdelete r_A;\n\n\tFunctions::delete_vector(D);\n\tFunctions::delete_vector(D_h);\n\tFunctions::delete_vector(D_s);\n\tdelete d;\n\tdelete Delta;\n\tdelete d_h;\n\n\tdelete r_D_h;\n\tdelete c_D_h;\n\tFunctions::delete_vector(B);\n\tdelete B_0;\n\tdelete r_B;\n\tdelete c_B;\n\tdelete a;\n\tdelete r_a;\n\tdelete c_a;\n\tdelete rho_a;\n\tdelete Dl;\n\tdelete r_Dl;\n\tdelete c_Dl;\n\n\tdelete D_h_bar;\n\tdelete d_bar;\n\tdelete Delta_bar;\n\tdelete B_bar;\n\tdelete A_bar;\n\tdelete D_s_bar;\n}\n\n\n\n//round_1 picks random elements and commits to the rows of Y\nstring Prover::round_1(){\n\tlong i;\n\tstring name;\n\ttime_t rawtime;\n\ttime ( &rawtime );\n\n\t//calculates commitments to rows of Y\n\tname = \"example.txt\";\n\tofstream ost;\n\tost.open(name.c_str(),ios::app);\n\tost<<\"commitments to A and random values \"<<endl;\n\tost.close();\n\tFunctions::commit(A,r_A, c_A);\n\n\t//write commitments in the file name\n\tname = \"round_1 \";\n\tname = name + ctime(&rawtime);\n\tost.open(name.c_str());\n\tfor (i=0; i<m; i++){\n\t\tost << c_A->at(i)<< \" \";\n\t}\n\treturn name;\n\n}\n\n//round_3, permuted the exponents in s,  picks random elements and commits to values\nstring Prover::round_3(string in_name){\n\tlong i;\n\tZZ x2;\n\tvector<vector<ZZ>* >* chal_x2 = new vector<vector<ZZ>* >(m);\n\n\tstring name;\n\ttime_t rawtime;\n\ttime ( &rawtime );\n\n\t//reads in values of s\n\tifstream ist(in_name.c_str());\n\tif(!ist) cout<<\"Can't open \"<< in_name;\n\tist >> x2;\n\tname = \"example.txt\";\n\tofstream ost;\n\tost.open(name.c_str(),ios::app);\n\tost<<\"x ist \"<<x2<<endl;\n\t//creates a matrix with entries x2,..., x2^N\n\tfunc_pro::set_x2(chal_x2,x2, m,n);\n\n\t//permutes chal_x2 according pi to create B\n\tfunc_pro::set_B(B, chal_x2, pi);\n\n\t//commits to the rows in B\n\tost<<\"commitment to B \"<<endl;\n\tFunctions::commit(B,r_B,c_B);\n\tost.close();\n\n\tname = \"round_3 \";\n\tname = name + ctime(&rawtime);\n\n\t//write data in the file name\n\t ost.open(name.c_str());\n\tfor (i=0; i<m;i++){\n\t\tost << c_B->at(i) <<\" \";\n\t}\n\n\tFunctions::delete_vector(chal_x2);\n\treturn name;\n}\n\n//round_5a calculates Y_pi and the commitments to the vectors alpha, W\nvoid Prover::round_5a(){\n\tlong i;\n\tZZ temp, t; //temporary variables\n\tvector<ZZ>* r = new vector<ZZ>(n);\n\tvector<ZZ>* v_z = new vector<ZZ>(n); //row containing the challenge alpha\n\tZZ ord = H.get_ord();\n\ttime_t rawtime;\n\ttime ( &rawtime );\n\n\t//calculate for each value in the first m rows in D: y* A_ij + A_ij -z\n\tfunc_pro::set_D(D, A,B, chal_z4, chal_y4);\n\n\t//Set the matrix D_h as the Hadamard product of the rows in D\n\tfunc_pro::set_D_h(D_h, D);\n\n\tfor( i=0; i<n;i++){\n\t\tv_z->at(i) = chal_z4; //fills the vector z with the challenge z\n\t\tNegateMod(r->at(i),to_ZZ(1),ord);\n\t}\n\n\t//Sets the additional row in D to contain -1\n\tstring name = \"example.txt\";\n\tofstream ost;\n\tost.open(name.c_str(),ios::app);\n\tost<<\"Last row in D ist -1 \"<<endl;\n\tD->at(m) = r;\n\t//random number to commit to last row in A\n\tost<<\"r_A to commit to last row in A ist \"<<0<<endl;\n\tr_A->at(m) = 0;\n\n\t//calculate commitment to\n\tost<<\"commitment  to vector z\"<<endl;\n\tFunctions::commit(v_z, r_z, c_z);\n\t//calculate commitment to the rows in D_h\n\tost<<\"Commitments to Hadamard product over D \"<<endl;\n\tFunctions::commit(D_h,r_D_h,c_D_h);\n\n\tdelete v_z;\n}\n\nvoid Prover::round_5b(){\n\n\t//picks random values to set B0 and commits to it\n\tfunc_pro::commit_B0(B_0, r_B0, c_B0);\n\t//picks random values to set A and commits to them;\n\tfunc_pro::commit_a(a, r_a, c_a);\n\n}\n\nvoid Prover::round_5c(){\n\tvector<Cipher_elg>*  e = 0;\n\tdouble tstart, tstop, ttime;\n\n\t//calculates the value R_t as sum(T(ij)*r(ij));\n\tfunc_pro::set_Rb(B,R,R_b);\n\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\n\t\te= calculate_e();\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\tttime= tstop-tstart;\n\t//cout << \"To calculate the di's took \" << ttime << \" second(s).\" << endl;\n\n\tcalculate_E(e);\n\tdelete e;\n}\n\nstring Prover::round_5(string in_name ){\n\tlong i;\n\tstring name;\n\ttime_t rawtime;\n\ttime ( &rawtime );\n\n\t//reads the values out of the file\n\tifstream ist(in_name.c_str());\n\tif(!ist) cout<<\"Can't open \"<< in_name;\n\tist>> chal_z4;\n\tist >> chal_y4;\n\n\t name = \"example.txt\";\n\tofstream ost;\n\tost.open(name.c_str(),ios::app);\n\tost<<\"z \"<<chal_z4<<\" y \"<<chal_y4<<endl;\n\tost.close();\n\tround_5a();\n\tround_5b();\n\tround_5c();\n\t//Set name of the output file and open stream\n\tname = \"round_5 \";\n\tname = name + ctime(&rawtime);\n\n\n\tost.open(name.c_str());\n\n\t//writes the commitments in the file\n\tost<<  c_z<< \"\\n\";\n\tfor (i = 0; i<m ; i++){\n\t\tost << c_D_h ->at(i)<< \" \";\n\t}\n\tost << c_B0<< \"\\n \";\n\tfor (i = 0; i<2*m ; i++){\n\t\tost << c_a ->at(i)<< \" \";\n\t}\n\tost << \"\\n\";\n\tfor (i = 0; i<2*m ; i++){\n\t\tost << E ->at(i)<< \" \";\n\t}\n\n\tdelete E;\n\treturn name;\n}\n\nvoid Prover::round_7a(){\n\t//Set the rows in D_s as D_s(i) = chal_t_1^i+1*D_h(i) for i<m-1 and D_s(m-1) = sum(chal_x6^i+1 * D_s(i+1) and set last row of D_s to random values and also D(0)\n\n\tstring name = \"example.txt\";\n\tofstream ost;\n\tost.open(name.c_str(),ios::app);\n\tost<<\"matrix D_s = chal_t_1^i+1*D_h(i) for i<m-1 and D_s(m-1) = sum(chal_x6^i+1 * D_s(i+1) \"<<endl;\n\tfunc_pro::set_D_s(D_s,D_h,D,chal_x6,r_Dl_bar);\n\n\t//calculate the values Dls as Dl(l) = sum(D(i)*D_s->at(i)*chal_y6) for j=n+i-l and commits to the values\n\tfunc_pro::commit_Dl(c_Dl,Dl, r_Dl, D, D_s, chal_y6, o);\n\n\t//commitments to D(0) and D_s(m)\n\tost<<\"commitment to D(0) and D_s(m) \"<<endl;\n\tFunctions::commit(D->at(0),r_D0,c_D0);\n\tFunctions::commit(D_s->at(m), r_Dm, c_Dm);\n\n\t//commitments to prove that the product over the elements in D_h->at(m) is the desired product of n *y + x2n -z\n\tost<<\"commitment to d \"<<endl;\n\tfunc_pro::commit_d(d,r_d,c_d);\n\tfunc_pro::commit_Delta(Delta, d, r_Delta, c_Delta);\n\tfunc_pro::commit_d_h(D_h,d_h,d,Delta, r_d_h, c_d_h);\n}\n\nvoid Prover::round_7b(){\n\t//calculate B_bar = sum(chal_x6^i B(i)), opening to prove knowledge of B\n\tfunc_pro::calculate_B_bar(B_0, B,chal_x6, B_bar );\n\n\t//calculate r_B_bar= sum(chal_x6^i r_B(i)), opening to prove knowledge of B\n\tfunc_pro::calculate_r_B_bar(r_B, chal_x6,r_B0, r_B_bar );\n\n\t//calculate a_bar = sum(chal_x6 ^i a(i)), opening to prove reencryption\n\tfunc_pro::calculate_a_bar(a, chal_x6, a_bar);\n\n\t//calculate r_a_bar= sum(chal_x6 ^i r_a(i)), opening to prove reencryption\n\tfunc_pro::calculate_r_a_bar(r_a, chal_x6, r_a_bar);\n\n\t//calculate rho_a_bar = sum(chal_x6 ^i rho_a(i)), opening to prove reencryption\n\tfunc_pro::calculate_rho_a_bar(rho_a, chal_x6, rho_bar);\n}\n\nstring Prover::round_7(string in_name){\n\tlong i;\n\tlong l=2*m;\n\tstring name;\n\ttime_t rawtime;\n\ttime ( &rawtime );\n\t//reads the values out of the file\n\tifstream ist(in_name.c_str());\n\tif(!ist) cout<<\"Can't open \"<< in_name;\n\t//reads the vector t_1 and t\n\tfor(i=0; i<l; i++){\n\t\tist>>chal_x6->at(i);\n\t}\n\tfor (i = 0; i<n; i++){\n\t\tist >> chal_y6->at(i);\n\t}\n\n\tround_7a();\n\tround_7b();\n\n\n\t//Set name of the output file and open stream\n\tname = \"round_7 \";\n\tname = name + ctime(&rawtime);\n\n\n\tofstream ost(name.c_str());\n\tfor (i = 0; i<=l ; i++){\n\t\tost << c_Dl ->at(i)<< \" \";\n\t}\n\tost << \"\\n\";\n\tost<<c_D0<<\"\\n\";\n\tost <<c_Dm<<\"\\n\";\n\tost<<c_d<<\"\\n\";\n\tost<<c_Delta<<\"\\n\";\n\tost<<c_d_h<<\"\\n\";\n\tfor (i = 0; i<n; i++){\n\t\tost << B_bar->at(i)<<\" \";\n\t}\n\tost <<\"\\n\";\n\n\tost<< r_B_bar;\n\tost <<\"\\n\";\n\n\tost<< a_bar;\n\tost <<\"\\n\";\n\n\tost<< r_a_bar;\n\tost <<\"\\n\";\n\n\tost<< rho_bar;\n\n\treturn name;\n}\n\nvoid Prover::round_9a(){\n\n\t//Calculate D_h_bar = sum(chal^i*D_h(row(i)))\n\tfunc_pro::calculate_D_h_bar(D_h_bar,D_h,chal_x8);\n\n\t//calculate r_Dh_bar = sum(chal^i*r_Dh_bar(i)), opening to prove correctness of D_h\n\tfunc_pro::calculate_r_Dh_bar(r_D_h, chal_x8, r_Dh_bar);\n\n\t//calculate d_bar, r_d_bar, Delta_bar, r_Delta_bar, openings to prove product over elements in D_h->at(m-1)\n\tfunc_pro::calculate_dbar_rdbar(D_h, chal_x8, d_bar,d,r_D_h, r_d, r_d_bar);\n\tfunc_pro::calculate_Deltabar_rDeltabar(d_h, chal_x8, Delta_bar, Delta, r_d_h, r_Delta, r_Delta_bar);\n}\n\nvoid  Prover::round_9b(){\n\t//A_bar and r_A_bar, openings to prove permutation in D\n\tfunc_pro::calculate_A_bar(D, A_bar, chal_x8);\n\tfunc_pro::calculate_r_A_bar(r_D0, r_A, r_B, chal_x8, r_z, chal_y4, r_A_bar);\n\n\t//D_s_bar and r_Ds_bar, openings to prove correctness of D_s\n\tfunc_pro::calculate_D_s_bar(D_s, D_s_bar, chal_x8);\n\tfunc_pro::calculate_r_Ds_bar(r_D_h, chal_x6, chal_x8, r_Ds_bar, r_Dm);\n\n\t//sum of the random values used to commit to the Dl's, to prover correctness of them\n\tfunc_pro::calculate_r_Dl_bar(r_Dl, chal_x8, r_Dl_bar);\n}\n\nstring Prover::round_9(string in_name){\n\tlong i;\n\tstring name;\n\ttime_t rawtime;\n\ttime ( &rawtime );\n\n\t//reads the values out of the file\n\tifstream ist(in_name.c_str());\n\tif(!ist) cout<<\"Can't open \"<< in_name;\n\t//reads the vector e\n\tfor (i = 0; i<(signed) chal_x8->size(); i++){\n\t\tist >> chal_x8->at(i);\n\t}\n\n\tname = \"example.txt\";\n\tofstream ost;\n\tost.open(name.c_str(),ios::app);\n\n\tost<<\"chal_x8 \"<< chal_x8->at(0)<<endl;\n\tost.close();\n\n\tround_9a();\n\tround_9b();\n\n\t//Set name of the output file and open stream\n\tname = \"round_9 \";\n\tname = name + ctime(&rawtime);\n\n\tost.open(name.c_str());\n\n\tfor (i = 0; i<n; i++){\n\t\tost << D_h_bar->at(i)<<\" \";\n\t}\n\tost <<\"\\n\";\n\tost<< r_Dh_bar;\n\tost <<\"\\n\";\n\n\tfor(i=0; i<n;i++){\n\t\tost<<d_bar->at(i)<<\" \";\n\t}\n\tost<<\"\\n\";\n\tost<< r_d_bar <<\"\\n\";\n\n\tfor(i=0; i<n; i++){\n\t\tost<<Delta_bar->at(i)<<\" \";\n\t}\n\tost<<\"\\n\";\n\tost<<r_Delta_bar <<\"\\n\";\n\n\tfor (i = 0; i<n; i++){\n\t\tost << A_bar->at(i)<<\" \";\n\t}\n\tost<<\"\\n\";\n\tost<<r_A_bar<<\"\\n\";\n\tfor(i=0; i<n; i++){\n\t\tost<<D_s_bar->at(i)<<\" \";\n\t}\n\tost<<\"\\n\";\n\tost<<r_Ds_bar<<\"\\n\";\n\tost<<r_Dl_bar<<\"\\n\";\n\n\treturn name;\n}\n\n\nCipher_elg Prover::calculate_e_1(long pos){\n\tlong i;\n\tCipher_elg temp, temp_1;\n\n\tCipher_elg::expo(temp, C->at(pos)->at(0), B_0->at(0));\n\tfor (i = 1; i<n; i++){\n\t\tCipher_elg::expo(temp_1, C->at(pos)->at(i), B_0->at(i));\n\t\tCipher_elg::mult(temp,temp, temp_1);\n\t}\n\n\treturn temp;\n}\n\nCipher_elg Prover::calculate_e_2(long k){\n\tlong i,j,l;\n\tCipher_elg temp, temp_1;\n\tZZ mod = H.get_mod();\n\n\ttemp=Cipher_elg(1,1,mod);\n\tfor (i = 1; i<=m; i++){\n\t\tl = k-m+i;\n\t\tif((l>0) & (l<=m)){\n\t\t\tfor(j = 0; j<n;j++){\n\t\t\t\tCipher_elg::expo(temp_1,C->at(i-1)->at(j), B->at(l-1)->at(j));\n\t\t\t\tCipher_elg::mult(temp,temp,temp_1);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn temp;\n}\n\nvector<Cipher_elg>* Prover::calculate_e(){\n\tlong k,l;\n\tCipher_elg temp, temp_1;\n\tvector<Cipher_elg>* e = new vector<Cipher_elg>(2*m);\n\n\tstring name = \"example.txt\";\n\tofstream ost;\n\tost.open(name.c_str(),ios::app);\n\tost<<\"calculate the product of the diagonlas, values E \"<<endl;\n\te->at(0)= calculate_e_1(m-1);\n\tost<<e->at(0)<<\" \";\n\n\tl=m-1;\n\tfor (k =1; k<=l; k++){\n\t\ttemp_1 = calculate_e_1(m-k-1);\n\t\ttemp = calculate_e_2(k);\n\t\tCipher_elg::mult(temp,temp,temp_1);\n\t\te->at(k) = temp;\n\t\tost<<e->at(k)<<\" \";\n\t}\n\tl=2*m-1;\n\tfor (k = m; k<=l; k++){\n\t\te->at(k) = calculate_e_2(k);\n\t\tost<<e->at(k)<<\" \";\n\t}\n\tost<<endl;\n\treturn e;\n}\n\nvoid Prover::calculate_E(vector<Cipher_elg>* e){\n\tlong i,l;\n\tMod_p t;\n\tMod_p gen = H.get_gen();\n\tZZ ord = H.get_ord();\n\tl=2*m;\n\tstring name = \"example.txt\";\n\tofstream ost;\n\tost.open(name.c_str(),ios::app);\n\tost<<\"reencrypt values in e, pick random rho \"<<endl;\n\tfor (i = 0; i<l; i++){\n\t\trho_a->at(i)= RandomBnd(ord);\n\t\tost<<rho_a->at(i)<<\" \";\n\t}\n\tost<<endl;\n\tNegateMod(rho_a->at(m),R_b,ord);\n\tost<<\"rho(m) = -R_b  m\"<<rho_a->at(m)<<\" \"<<m<<endl;\n\tost<<\"t=g^a encrypt(t, rho)e \"<<endl;\n\tfor (i = 0; i<l; i++){\n\t\t t = gen.expo(a->at(i));\n\t\t E->at(i) = El.encrypt(t,rho_a->at(i))*e->at(i);\n\t\t ost<<t<<\" \"<<E->at(i)<<endl;\n\t}\n}\n", "meta": {"hexsha": "911a7b9998043a493fbed5f691c35cbb6e661d15", "size": 14606, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Prover.cpp", "max_stars_repo_name": "3for/verifiable-shuffle", "max_stars_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-01-11T14:06:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T08:28:26.000Z", "max_issues_repo_path": "src/Prover.cpp", "max_issues_repo_name": "3for/verifiable-shuffle", "max_issues_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "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/Prover.cpp", "max_forks_repo_name": "3for/verifiable-shuffle", "max_forks_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-13T06:11:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-03T15:21:49.000Z", "avg_line_length": 24.9675213675, "max_line_length": 161, "alphanum_fraction": 0.6466520608, "num_tokens": 5051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.29768934369348266}}
{"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 <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/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/ocl_config.hpp\"\n#include \"heom/ode.hpp\"\n#include \"heom/population_dynamics_config.hpp\"\n#include \"heom/population_dynamics_solver.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\t// parse config files\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::population_dynamics_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\theom::instance heom_instance(heom_config, heom::sites_to_states_mode_t::identity, complete_graph);\n\t\theom_instance.set_hierarchy_top(heom_config.population_dynamics_rho_init().data());\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// create a solver from configuration and instance\n\t\tconst ocl::nd_range ocl_nd_range {\n\t\t\t\t{}, // offset\n\t\t        {1, static_cast<std::uint64_t>(heom_instance.matrices())}, // global size\n\t\t        {1, 1} // local size\n\t\t\t};\n\n\t\tsolver_t solver(ocl_config, ocl_nd_range, heom_config, heom_instance);\n\t\tstd::cout << \"-------------------- OpenCL Runtime Configuration ----------\" << std::endl;\n\t\tsolver.write_ocl_runtime_config(std::cout);\n\t\tstd::cout << \"------------------------------------------------------------\" << std::endl;\n\n\t\t// with create_hierarchy_mask we create mask corresponding to configured filtering strategy, then update solver\n\t\t// NOTE: .data() returns pointer to mask_t array\n\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\tsolver.update_hierarchy_mask(hierarchy_mask.data());\n\n\t\tstd::cout << \"-------------------- Hierarchy Mask Counter ----------------\" << std::endl;\n\t\theom::write_hierarchy_mask_stats(hierarchy_mask, std::cout);\n\t\tstd::cout << \"------------------------------------------------------------\" << std::endl;\n\n\t\t// setup output\n\t\theom::observer_list observer_list = heom::make_file_observer_list(heom_config, complete_graph, solver);\n\t\tobserver_list.observe(0.0);\n\n\t\t// run the solver, print output every n steps\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\tfor (int_t i = 0; i < iterations; ++i) {\n\t\t\t// propagate\n\t\t\tsolver.step_forward(steps_per_iteration);\n\n\t\t\t// after propagation, we are at:\n\t\t\tconst auto current_step = (i + 1) * steps_per_iteration;\n\t\t\tconst real_t current_time = current_step * heom_config.solver_step_size();\n\n\t\t\t// observe\n//\t\t\tsolver.get_top_result(result_buffer_top);\n\t\t\tobserver_list.observe(current_time);\n\n\t\t\t// update status\n\t\t\theom::write_progress(current_step - 1, total_steps, \"Calculation population dynamics: \", std::cout);\n\t\t}\n\n\t\t// output benchmark results\n\t\tstd::cout << \"-------------------- Solver Runtime Summary ----------------\" << std::endl;\n\t\tsolver.write_runtime_summary(std::cout);\n\t\tstd::cout << \"------------------------------------------------------------\" << std::endl;\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.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.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\") % (solver.ocl_helper().allocated_byte_max() / 1024.0 / 1024.0)\n\t\t          << \" (\"\n\t\t\t      << boost::format(\"count: %6i\") % solver.ocl_helper().allocations_max()\n\t\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 << \"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": "a97b75ee03828749c0236eb9f474215f928a3451", "size": 6130, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dm-heom/src/app_population_dynamics.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_population_dynamics.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_population_dynamics.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.1007194245, "max_line_length": 187, "alphanum_fraction": 0.6425774878, "num_tokens": 1544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2976840574842258}}
{"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 \"rcbdd_synthesis.hpp\"\n#include \"synthesis_utils_p.hpp\"\n\n#include <fstream>\n\n#include <boost/range/algorithm.hpp>\n#include <boost/range/algorithm_ext/push_back.hpp>\n\n#include <core/utils/terminal.hpp>\n#include <core/utils/timer.hpp>\n#include <reversible/functions/add_circuit.hpp>\n#include <reversible/functions/add_gates.hpp>\n#include <reversible/functions/pattern_to_circuit.hpp>\n#include <reversible/io/print_circuit.hpp>\n#include <classical/optimization/optimization.hpp>\n\n#define timer timer_class\n#include <boost/progress.hpp>\n#undef timer\n\n#include <cuddInt.h>\n\nnamespace cirkit\n{\n\nenum Direction {\n  ChangeLeft = 0,\n  ChangeRight\n};\n\nint Cudd_bddPickOneCubeForRCBDD( DdManager * ddm, DdNode * node, char * repr)\n{\n  DdNode *N, *T, *E;\n  DdNode *one, *bzero;\n  char   dir;\n  int    i;\n\n  if ( repr == nullptr || node == nullptr ) return 0;\n\n  /* The constant 0 function has no on-set cubes. */\n  one = DD_ONE(ddm);\n  bzero = Cudd_Not(one);\n  if (node == bzero) return 0;\n\n  for ( i = 0; i < ddm->size; i++ ) repr[i] = 2;\n\n  for (;;)\n  {\n    if ( node == one ) break;\n\n    N = Cudd_Regular(node);\n\n    T = cuddT(N); E = cuddE(N);\n    if ( Cudd_IsComplement( node ) )\n    {\n\t    T = Cudd_Not(T); E = Cudd_Not(E);\n    }\n    if ( T == bzero )\n    {\n\t    repr[N->index] = 0;\n\t    node = E;\n    }\n    else if ( E == bzero )\n    {\n\t    repr[N->index] = 1;\n\t    node = T;\n    }\n    else\n    {\n      if ( N->index % 3 == 1 )\n      {\n        repr[N->index] = repr[N->index - 1];\n        node = repr[N->index] ? T : E;\n      }\n      else\n      {\n        dir = (char) ((Cudd_Random( ddm ) & 0x2000) >> 13);\n        repr[N->index] = dir;\n        node = dir ? T : E;\n      }\n    }\n  }\n  return 1;\n}\n\nint pick_one_cube_for_rcbdd( BDD node, char * repr )\n{\n  return Cudd_bddPickOneCubeForRCBDD( node.manager(), node.getNode(), repr );\n}\n\nstruct rcbdd_synthesis_manager\n{\n  rcbdd_synthesis_manager( const rcbdd& _cf, circuit& _circ )\n    : cf( _cf ),\n      circ( _circ ),\n      insert_position( 0u )\n  {\n    f = _cf.chi();\n\n    circ.set_lines( _cf.num_vars() );\n\n    std::vector<std::string> inputs( _cf.num_vars(), _cf.constant_value() ? \"1\" : \"0\" );\n    boost::copy( cf.input_labels(), inputs.end() - _cf.num_inputs() );\n    circ.set_inputs( inputs );\n\n    std::vector<std::string> outputs( _cf.num_vars(), \"-\" );\n    boost::copy( cf.output_labels(), outputs.begin() );\n    circ.set_outputs( outputs );\n\n    std::vector<constant> constants( _cf.num_vars(), constant() );\n    std::fill( constants.begin(), constants.end() - _cf.num_inputs(), _cf.constant_value() );\n    circ.set_constants( constants );\n\n    std::vector<bool> garbage( _cf.num_vars(), true );\n    std::fill( garbage.begin(), garbage.begin() + _cf.num_outputs(), false );\n    circ.set_garbage( garbage );\n\n    node_count += f.nodeCount();\n  }\n\n  void set_var(unsigned v)\n  {\n    _var = v;\n\n    left_f = cf.manager().bddZero();\n    right_f = cf.manager().bddZero();\n  }\n\n  void compute_cofactors()\n  {\n    n  = cf.cofactor(f, _var, false, false);\n    pp = cf.cofactor(f, _var, true,  false);\n    np = cf.cofactor(f, _var, false, true);\n    p  = cf.cofactor(f, _var, true,  true);\n\n    nx  = cf.remove_ys(n);\n    ppx = cf.remove_ys(pp);\n    npx = cf.remove_ys(np);\n    px  = cf.remove_ys(p);\n\n    ny  = cf.remove_xs(n);\n    ppy = cf.remove_xs(pp);\n    npy = cf.remove_xs(np);\n    py  = cf.remove_xs(p);\n  }\n\n  void apply_gates(const BDD& lf, const BDD& rf)\n  {\n    left_f ^= lf;\n    right_f ^= rf;\n\n    BDD gate_left = cf.create_from_gate(_var, lf);\n    BDD gate_right = cf.create_from_gate(_var, cf.move_ys_to_xs(rf));\n    f = cf.compose(cf.compose(gate_left, f), gate_right);\n    node_count += f.nodeCount();\n  }\n\n  void only_left_gate_shortcut()\n  {\n    BDD chi_prime = f;\n\n    // Copy y_var to x_var\n    chi_prime = chi_prime.ExistAbstract(cf.x(_var)) & cf.x(_var).Xnor(cf.y(_var));\n\n    // Check whether chi' is reversible\n    if (mpz_class(chi_prime.CountMinterm(2u * cf.num_vars())) == pow2(cf.num_vars())\n        && cf.remove_ys(chi_prime) == cf.manager().bddOne()\n        && cf.remove_xs(chi_prime) == cf.manager().bddOne())\n    {\n      BDD lf = cf.remove_ys(!f & chi_prime).ExistAbstract(cf.x(_var));\n      apply_gates(lf, cf.manager().bddZero());\n    }\n  }\n\n  void resolve_one_cycles()\n  {\n    // Via F_n\n    compute_cofactors();\n\n    //BDD lf = (!nx & ppx) ^ (!px & npx);\n    BDD lf = ppx & npx;\n\n    apply_gates(lf, cf.manager().bddZero());\n\n    compute_cofactors();\n\n    BDD rf = ppy & npy;\n\n    apply_gates(cf.manager().bddZero(), rf);\n\n    // // Via F_p\n    // compute_cofactors();\n\n    // lf = !px & npx;\n    // rf = !py & ppy;\n\n    // apply_gates(lf, rf);\n  }\n\n  void resolve_two_cycles()\n  {\n    // Via F_p\n    compute_cofactors();\n\n    BDD _f = ppy & p & npx;\n    BDD lf = cf.remove_ys(_f);\n    BDD rf = cf.remove_xs(_f);\n\n    apply_gates(lf, rf);\n\n    // Via F_n\n    compute_cofactors();\n\n    _f = npy & n & ppx;\n    lf = cf.remove_ys(_f);\n    rf = cf.remove_xs(_f);\n\n    apply_gates(lf, rf);\n  }\n\n\n  void cycle_step()\n  {\n    compute_cofactors();\n\n    std::vector<BDD> variables;\n    boost::push_back(variables, cf.xs());\n    boost::push_back(variables, cf.ys());\n\n    // Pick an arbitrary cube from pp\n    BDD cube;\n\n    if ( pp != cf.manager().bddZero() )\n    {\n      cube = pp.PickOneMinterm(variables);\n    }\n    else\n    {\n      cube = ( !cf.remove_xs( f ) & !cf.remove_ys( f ) & cf.x( _var) & !cf.y( _var ) ).PickOneMinterm( variables );\n      f |= cube;\n    }\n    char change = ChangeLeft;\n\n    BDD lf = cf.manager().bddZero();\n    BDD rf = cf.manager().bddZero();\n    BDD cube_part;\n    char *scube = new char[3u * cf.num_vars()];\n\n    ++access;\n\n    do\n    {\n      if (change == ChangeLeft)\n      {\n        // Update left gate\n        cube_part = cf.remove_ys(cube).ExistAbstract(cf.x(_var));\n        lf |= cube_part;\n        //change = CHANGE_RIGHT;\n        cube = !cf.x(_var) & cube_part & f;\n      }\n      else\n      {\n        cube_part = cf.remove_xs(cube).ExistAbstract(cf.y(_var));\n        rf |= cube_part;\n        //change = CHANGE_LEFT;\n        cube = cf.y(_var) & cube_part & f;\n      }\n\n      /* Cube is not part of the function? */\n      if (cube == cf.manager().bddZero())\n      {\n        BDD unused_outputs = !cf.remove_xs(f);\n        BDD unused_inputs = !cf.remove_ys(f);\n\n        BDD icube, ocube;\n\n        if (change == ChangeLeft)\n        {\n          icube = !cf.x(_var) & cube_part;\n\n          ocube = cf.manager().bddOne();\n          if ((unused_outputs & cf.y(_var)) != cf.manager().bddZero())\n          {\n            (unused_outputs & cf.y(_var)).PickOneCube(scube);\n          }\n          else\n          {\n            unused_outputs.PickOneCube(scube);\n          }\n          for (unsigned i = 0u; i < cf.num_vars(); ++i)\n          {\n            ocube &= (scube[3u * i + 1u] == 1) ? cf.y(i) : !cf.y(i);\n          }\n        }\n        else\n        {\n          ocube = cf.y(_var) & cube_part;\n\n          icube = cf.manager().bddOne();\n          if ((unused_inputs & !cf.x(_var)) != cf.manager().bddZero())\n          {\n            (unused_inputs & !cf.x(_var)).PickOneCube(scube);\n          }\n          else\n          {\n            unused_inputs.PickOneCube(scube);\n          }\n          for (unsigned i = 0u; i < cf.num_vars(); ++i)\n          {\n            icube &= (scube[3u * i] == 1) ? cf.x(i) : !cf.x(i);\n          }\n        }\n\n        cube = icube & ocube;\n        f |= cube;\n\n        compute_cofactors();\n      }\n\n      change = ((char)1u - change);\n      ++access;\n    } while ( ( cube & ( pp | np ) ) == cf.manager().bddZero() );\n\n    /* Cleanup */\n    delete[] scube;\n\n    apply_gates(lf, rf);\n  }\n\n  void resolve_k_cycles()\n  {\n    while (cf.cofactor(f, _var, true, false) != cf.manager().bddZero() || cf.cofactor(f, _var, false, true) != cf.manager().bddZero())\n    {\n      compute_cofactors();\n\n      /* special case #P' is 0 and #N' is not zero, then swap */\n      if ( pp == cf.manager().bddZero() && np != cf.manager().bddZero() )\n      {\n        apply_gates( cf.manager().bddOne(), cf.manager().bddOne() );\n      }\n\n      if ( false /*verbose*/ )\n      {\n        std::cout << \"#N: \" << cf.cofactor( f, _var, false, false ).CountMinterm( 2u * cf.num_vars() ) << \" \"\n                  << \"#P': \" << cf.cofactor( f, _var, true, false ).CountMinterm( 2u * cf.num_vars() ) << \" \"\n                  << \"#N': \" << cf.cofactor( f, _var, false, true ).CountMinterm( 2u * cf.num_vars() ) << \" \"\n                  << \"#P: \" << cf.cofactor( f, _var, true, true ).CountMinterm( 2u * cf.num_vars() ) << std::endl;\n      }\n\n      cycle_step();\n    }\n  }\n\n  typedef std::tuple<\n    bool,                                                   // p1[_var] value\n    std::function<BDD(rcbdd_synthesis_manager*)>,           // compute fc\n    unsigned,                                               // scube offset\n    std::function<BDD(rcbdd_synthesis_manager*, BDD, BDD)>, // update f\n    std::function<void(circuit&, const circuit&)>           // update circ\n    > resolve_cycles_configuration_t;\n\n  /* DISABLE FOR NOW\n  resolve_cycles_configuration_t resolve_x = std::make_tuple(\n    true,\n    []( rcbdd_synthesis_manager* manager ) {\n      BDD fc = manager->ppx & manager->cf.move_xs_to_tmp( manager->npx );\n      for ( unsigned j = 0u; j < manager->_var; ++j )\n      {\n        fc &= ( manager->cf.x( j ).Xnor( manager->cf.z( j ) ) );\n      }\n      return fc;\n    },\n    0u,\n    []( rcbdd_synthesis_manager* manager, BDD gcirc, BDD f ) { return manager->cf.compose( gcirc, f ); },\n    []( circuit& circ, const circuit& c ) { append_circuit( circ, c ); } );\n\n  resolve_cycles_configuration_t resolve_y = std::make_tuple(\n    false,\n    []( rcbdd_synthesis_manager* manager ) {\n      BDD fc = manager->ppy & manager->cf.move_ys_to_tmp( manager->npy );\n      for ( unsigned j = 0u; j < manager->_var; ++j )\n      {\n        fc &= ( manager->cf.y( j ).Xnor( manager->cf.z( j ) ) );\n      }\n      return fc;\n    },\n    1u,\n    []( rcbdd_synthesis_manager* manager, BDD gcirc, BDD f ) { return manager->cf.compose( f, gcirc ); },\n    []( circuit& circ, const circuit& c ) { prepend_circuit( circ, c ); } );\n  */\n\n  void resolve_cycles_with_transpositions( const resolve_cycles_configuration_t& configuration )\n  {\n    if ( false /*verbose*/ )\n    {\n      std::cout << boost::format( \"[i] resolve cycles for var %d\" ) % _var << std::endl;\n    }\n\n    while ( cf.cofactor( f, _var, true, false ) != cf.manager().bddZero() ||\n            cf.cofactor( f, _var, false, true ) != cf.manager().bddZero() )\n    {\n      compute_cofactors();\n\n      /* Extract two cubes and save them into bitset */\n      boost::dynamic_bitset<> p1( cf.num_vars() ), p2( cf.num_vars() );\n\n      p1[_var] =  std::get<0>( configuration );\n      p2[_var] = !std::get<0>( configuration );\n\n      char *scube = new char[3u * cf.num_vars()];\n\n      BDD fc = std::get<1>( configuration )( this );\n\n      if ( !smart_pickcube )\n      {\n        fc.PickOneCube( scube );\n      }\n      else\n      {\n        pick_one_cube_for_rcbdd( fc, scube );\n      }\n\n      for ( unsigned i = 0u; i < cf.num_vars(); ++i )\n      {\n        if ( i == _var ) continue;\n        p1[i] = scube[3u * i + std::get<2>( configuration )];\n        p2[i] = scube[3u * i + 2u];\n      }\n\n      delete[] scube;\n\n      /* Create circuit for p1 and p2 */\n      if ( verbose )\n      {\n        //std::cout << \"[i] realize transposition (\" << p1 << \" \" << p2 << \")\" << std::endl;\n      }\n      circuit c( cf.num_vars() );\n      pattern_to_circuit( c, p1, p2 );\n      if ( verbose )\n      {\n        //std::cout << \"[i] result: \" << std::endl << c;\n      }\n\n      /* Apply circuit to f */\n      BDD gcirc = cf.create_from_circuit( c );\n      f = std::get<3>( configuration )( this, gcirc, f );\n      std::get<4>( configuration )( circ, c );\n    }\n  }\n\n  void add_toffoli_gate( const cube_t& cube, unsigned offset )\n  {\n    gate::control_container controls;\n    for ( unsigned i = 0u; i < cf.num_vars(); ++i )\n    {\n      if ( cube.second[3u * i + offset] )\n      {\n        controls += make_var( i, cube.first[3u * i + offset] );\n      }\n    }\n\n    insert_toffoli( circ, insert_position, controls, _var );\n    insert_position++;\n  }\n\n  void create_toffoli_gates_with_exorcism(const BDD& gate, unsigned var, unsigned offset, bool add_gates_to_circuit = true)\n  {\n    if (gate == cf.manager().bddZero()) return;\n\n    if ( genesop )\n    {\n      std::ofstream esopout;\n      esopout.open( boost::str( boost::format( \"/tmp/%s_%d_%d.pla\" ) % name % var % offset ) );\n      esopout << \".i \" << cf.num_vars() << std::endl;\n      esopout << \".o \" << 1 << std::endl;\n\n      int *cube;\n      CUDD_VALUE_TYPE value;\n      DdGen *gen;\n\n      Cudd_ForeachCube(gate.manager(), gate.getNode(), gen, cube, value)\n      {\n        char v;\n\n        for (unsigned i = 0u; i < cf.num_vars(); ++i)\n        {\n          v = cube[3u * i + offset];\n          if (v != 2)\n          {\n            esopout << ((v == 0) ? \"0\" : \"1\");\n          }\n          else\n          {\n            esopout << \"-\";\n          }\n        }\n\n        esopout << \" 1\" << std::endl;\n      }\n\n      esopout << \".e\" << std::endl;\n      esopout.close();\n    }\n\n    if ( create_gates )\n    {\n      if ( add_gates_to_circuit )\n      {\n        esopmin.settings()->set( \"on_cube\", cube_function_t( [this, &offset]( const cube_t& c ) { add_toffoli_gate( c, offset ); } ) );\n      }\n      else\n      {\n        esopmin.settings()->set( \"on_cube\", cube_function_t( [this, &offset]( const cube_t& c ) {} ) );\n      }\n      esopmin.settings()->set( \"verify\", false );\n      esopmin( gate.manager(), gate.getNode() );\n\n      if ( add_gates_to_circuit && offset == 1u )\n      {\n        insert_position -= esopmin.statistics()->get<unsigned>( \"cube_count\" );\n      }\n\n      total_toffoli_gates += esopmin.statistics()->get<unsigned>( \"cube_count\" );\n      total_control_lines += esopmin.statistics()->get<unsigned>( \"literal_count\" );\n    }\n\n    /*\n    system(\"exorcism /tmp/test.esop\");\n\n    // Get number of gates\n    total_toffoli_gates += boost::lexical_cast<unsigned long long>(execute_and_return_output(\"cat /tmp/test.esop | grep -v -e \\\"^[#\\\\.]\\\" | wc -l\"));\n    total_control_lines += boost::lexical_cast<unsigned long long>(execute_and_return_output(\"cat /tmp/test.esop | grep -v -e \\\"^[#\\\\.]\\\" | awk '{print $1}' | tr '\\\\n' ' ' | sed -e \\\"s/[^01]//g\\\" | wc -c\"));\n\n    // Get gates\n    using boost::format;\n    using boost::str;\n\n    std::ifstream is;\n    is.open(\"/tmp/test.esop\");\n\n    std::string line;\n    while (std::getline(is, line)) {\n      boost::trim(line);\n      if (line.empty()) continue;\n\n      if (line[0] == '0' || line[0] == '1' || line[0] == '-') {\n        std::string negate, vars;\n        unsigned c = 0u;\n        for (unsigned i = 0u; i < mgr.num_vars(); ++i) {\n          if (line[i] == '0') {\n            negate += str(format(\"t1 x%d\\n\") % i);\n          }\n          if (line[i] == '0' || line[i] == '1') {\n            vars += str(format(\" x%d\") % i);\n            ++c;\n          }\n        }\n        std::string _gate = str(format(\"%st%d%s x%d\\n%s\") % negate % (c + 1u) % vars % _var % negate);\n        if (offset == 0u) {\n          real_l += _gate;\n        } else {\n          real_r = _gate + real_r;\n        }\n      }\n    }\n    is.close();\n    */\n  }\n\n  void default_synthesis()\n  {\n    null_stream ns;\n    std::ostream null_out( &ns );\n    boost::progress_display show_progress( cf.num_vars(), progress ? std::cout : null_out );\n\n    for (unsigned var = 0; var < cf.num_vars(); ++var)\n    {\n      ++show_progress;\n      set_var(var);\n\n      if ( synthesis_method == ResolveCycles )\n      {\n        only_left_gate_shortcut();\n        resolve_one_cycles();\n        resolve_two_cycles();\n        resolve_k_cycles();\n\n        if ( false /*verbose*/ )\n        {\n          std::cout << \"Target: \" << _var << std::endl << \" - left control function:\" << std::endl;\n          left_f.PrintMinterm();\n          std::cout << \" - right control function:\" << std::endl;\n          right_f.PrintMinterm();\n        }\n\n        create_toffoli_gates_with_exorcism(left_f, var, 0u);\n        create_toffoli_gates_with_exorcism(right_f, var, 1u);\n      }\n      else if ( synthesis_method == TranspositionsX )\n      {\n        //resolve_cycles_with_transpositions( resolve_x );\n      }\n      else if ( synthesis_method == TranspositionsY )\n      {\n        //resolve_cycles_with_transpositions( resolve_y );\n      }\n    }\n  }\n\n  void heuristic_swap() //Get chi\n  {\n    std::vector<unsigned> list_lines;\n    for (unsigned var = 0; var < cf.num_vars(); ++var)\n    {\n      list_lines.push_back(var);\n    }\n\n    BDD lf_c, lr_c;\n\n    while (!list_lines.empty())\n    {\n      unsigned min_cost = UINT_MAX;\n      unsigned best_line = 0u;\n\n      for (unsigned i = 0u; i < list_lines.size(); ++i)\n      {\n        BDD oldchi = f; //make a copy of chi\n        unsigned old_control_lines = total_control_lines;\n        unsigned old_toffoli_gates = total_toffoli_gates;\n        if ( false /*verbose*/ )\n        {\n          std::cout << \"[I] - total_toffoli_gates\" << total_toffoli_gates << std::endl;\n        }\n        set_var(list_lines[i]);\n\n        if ( false /*verbose*/ )\n        {\n          std::cout << \"[I] set_var(var): \" << _var << std::endl;\n        }\n        only_left_gate_shortcut();\n        resolve_one_cycles();\n        resolve_two_cycles();\n        resolve_k_cycles();\n\n        if ( false /*verbose*/ )\n        {\n          std::cout << \"Target: \" << _var << std::endl << \" - left control function:\" << std::endl;\n          left_f.PrintMinterm();\n          std::cout << \"[I] - right control function:\" << std::endl;\n          right_f.PrintMinterm();\n        }\n\n        create_toffoli_gates_with_exorcism( left_f, list_lines[i], 0u, false );\n        create_toffoli_gates_with_exorcism( right_f, list_lines[i], 1u, false );\n\n\n        // Determine cost and save in new_cost\n        unsigned new_cost = total_toffoli_gates - old_toffoli_gates;\n\n        if ( false /*verbose*/ )\n        {\n          std::cout << \"[I] h1: Lines:    \" << cf.num_vars() << std::endl;\n          std::cout << \"[I] h1: Gates:    \" << new_cost << std::endl;\n          std::cout << \"[I] Controls:     \" << total_control_lines << std::endl;\n        }\n\n        if (new_cost < min_cost)\n        {\n          best_line = list_lines[i];\n          min_cost = new_cost;\n          if ( false /*verbose*/ )\n          {\n            std::cout << \"[I] Min cost: \" << min_cost << std::endl;\n          }\n        }\n\n        f = oldchi;\n        total_toffoli_gates = old_toffoli_gates;\n        total_control_lines = old_control_lines;\n      }\n\n      set_var(best_line);\n      // Synthesis with best_line\n      only_left_gate_shortcut();\n      resolve_one_cycles();\n      resolve_two_cycles();\n      resolve_k_cycles();\n\n      create_toffoli_gates_with_exorcism(left_f, best_line, 0u);\n      create_toffoli_gates_with_exorcism(right_f, best_line, 1u);\n\n      list_lines.erase(std::remove(list_lines.begin(),list_lines.end(),best_line));\n\n      if ( false /*verbose*/ )\n      {\n        std::cout << \"[I] Best Line: \" << best_line << std::endl;\n      }\n    }\n  }\n\n  void heuristic_hamming()\n  {\n    std::vector<unsigned> list_lines;\n    for (unsigned var = 0; var < cf.num_vars(); ++var)\n    {\n      list_lines.push_back(var);\n    }\n\n    BDD lf_c, lr_c;\n\n    while (!list_lines.empty())\n    {\n      double min_cost = DBL_MAX;\n      unsigned best_line = 0u;\n\n      for (unsigned i = 0u; i < list_lines.size(); ++i)\n      {\n        // Determine costs and save in new_cost\n        double new_cost = cf.cofactor(f, list_lines[i], false, true).CountMinterm(2 * cf.num_vars());\n\n\n        if (new_cost < min_cost)\n        {\n          best_line = list_lines[i];\n          min_cost = new_cost;\n          if ( false /*verbose*/ )\n          {\n            std::cout << \"[I] Min cost: \" << min_cost << std::endl;\n          }\n        }\n      }\n\n      set_var(best_line);\n      // Synthesis with best_line\n      only_left_gate_shortcut();\n      resolve_one_cycles();\n      resolve_two_cycles();\n      resolve_k_cycles();\n\n      create_toffoli_gates_with_exorcism(left_f, best_line, 0u);\n      create_toffoli_gates_with_exorcism(right_f, best_line, 1u);\n\n      list_lines.erase(std::remove(list_lines.begin(),list_lines.end(),best_line));\n\n      if ( false /*verbose*/ )\n      {\n        std::cout << \"[I] Best Line: \" << best_line << std::endl;\n      }\n    }\n  }\n\n  const rcbdd& cf;\n  circuit& circ;\n\n  bool verbose;\n  bool progress;\n  std::string name;\n  bool genesop;\n  dd_based_esop_optimization_func esopmin;\n  bool create_gates;\n  bool smart_pickcube;\n  SynthesisMethod synthesis_method;\n\n  BDD f;\n  BDD left_f, right_f;\n  unsigned _var;\n  unsigned insert_position;\n  BDD n, pp, np, p;\n  BDD nx, ppx, npx, px;\n  BDD ny,  ppy, npy, py;\n  unsigned total_control_lines = 0u, total_toffoli_gates = 0u;\n  unsigned long long access = 0ull;\n  std::vector<int> node_count;\n};\n\nbool rcbdd_synthesis( circuit& circ, const rcbdd& cf, properties::ptr settings, properties::ptr statistics )\n{\n  /* Settings */\n  auto verbose          = get( settings, \"verbose\",          false                             );\n  auto progress         = get( settings, \"progress\",         false                             );\n  auto name             = get( settings, \"name\",             std::string( \"test\" )             );\n  auto genesop          = get( settings, \"genesop\",          false                             );\n  auto esopmin          = get( settings, \"esopmin\",          dd_based_esop_optimization_func() );\n  auto create_gates     = get( settings, \"create_gates\",     true                              );\n  /* 0: default, 1: swap, 2: hamming */\n  auto mode             = get( settings, \"mode\",             0u                                );\n  auto synthesis_method = get( settings, \"synthesis_method\", ResolveCycles                     );\n  auto smart_pickcube   = get( settings, \"smart_pickcube\",   true                              );\n\n  /* Timing */\n  properties_timer t( statistics );\n\n  rcbdd_synthesis_manager mgr( cf, circ );\n  mgr.verbose          = verbose;\n  mgr.progress         = progress;\n  mgr.name             = name;\n  mgr.genesop          = genesop;\n  mgr.esopmin          = esopmin;\n  mgr.create_gates     = create_gates;\n  mgr.synthesis_method = synthesis_method;\n  mgr.smart_pickcube   = smart_pickcube;\n  switch ( mode )\n  {\n  case 1u:\n    mgr.heuristic_swap();\n    break;\n  case 2u:\n    mgr.heuristic_hamming();\n    break;\n  default:\n    mgr.default_synthesis();\n  };\n\n  if ( statistics )\n  {\n    statistics->set( \"access\", mgr.access );\n    statistics->set( \"node_count\", mgr.node_count );\n  }\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": "0913429dd0cc68e705efe55ac0184ac3d30de586", "size": 23955, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/rcbdd_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/rcbdd_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/rcbdd_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": 27.9848130841, "max_line_length": 207, "alphanum_fraction": 0.5536213734, "num_tokens": 6730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2976840574842257}}
{"text": "/*\n * Copyright (c) 2008-2009 Radu Bogdan Rusu <rusu -=- cs.tum.edu>\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 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 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 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 * $Id: sac_model_sphere.cpp 21050 2009-08-07 21:24:30Z jfaustwg $\n *\n */\n\n/** \\author Radu Bogdan Rusu */\n\n#include <point_cloud_mapping/sample_consensus/sac_model_sphere.h>\n#include <point_cloud_mapping/geometry/nearest.h>\n#include <Eigen/LU>\n\n#include <cminpack.h>\n\nnamespace sample_consensus\n{\n  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n  /** \\brief Get 4 random points (3 non-collinear) as data samples and return them as point indices.\n    * \\param iterations the internal number of iterations used by SAC methods\n    * \\param samples the resultant model samples\n    * \\note assumes unique points!\n    * \\note Two different points could be enough in theory, to infere some sort of a center and a radius,\n    *       but in practice, we might end up with a lot of points which are just 'close' to one another.\n    *       Therefore we have two options:\n    *       a) use normal information (good but I wouldn't rely on it in extremely noisy point clouds, no matter what)\n    *       b) get two more points and uniquely identify a sphere in space (3 unique points define a circle)\n    */\n  void\n    SACModelSphere::getSamples (int &iterations, std::vector<int> &samples)\n  {\n    samples.resize (4);\n    double trand = indices_.size () / (RAND_MAX + 1.0);\n\n    // Get a random number between 1 and max_indices\n    int idx = (int)(rand () * trand);\n    // Get the index\n    samples[0] = indices_.at (idx);\n\n    // Get a second point which is different than the first\n    do\n    {\n      idx = (int)(rand () * trand);\n      samples[1] = indices_.at (idx);\n      iterations++;\n    } while (samples[1] == samples[0]);\n    iterations--;\n\n    double Dx1, Dy1, Dz1, Dx2, Dy2, Dz2, Dy1Dy2;\n    // Compute the segment values (in 3d) between XY\n    Dx1 = cloud_->points[samples[1]].x - cloud_->points[samples[0]].x;\n    Dy1 = cloud_->points[samples[1]].y - cloud_->points[samples[0]].y;\n    Dz1 = cloud_->points[samples[1]].z - cloud_->points[samples[0]].z;\n\n    int iter = 0;\n    do\n    {\n      // Get the third point, different from the first two\n      do\n      {\n        idx = (int)(rand () * trand);\n        samples[2] = indices_.at (idx);\n        iterations++;\n      } while ( (samples[2] == samples[1]) || (samples[2] == samples[0]) );\n      iterations--;\n\n      // Compute the segment values (in 3d) between XZ\n      Dx2 = cloud_->points[samples[2]].x - cloud_->points[samples[0]].x;\n      Dy2 = cloud_->points[samples[2]].y - cloud_->points[samples[0]].y;\n      Dz2 = cloud_->points[samples[2]].z - cloud_->points[samples[0]].z;\n\n      Dy1Dy2 = Dy1 / Dy2;\n      iter++;\n\n      if (iter > MAX_ITERATIONS_COLLINEAR )\n      {\n        ROS_WARN (\"[SACModelSphere::getSamples] WARNING: Could not select 3 non collinear points in %d iterations!\", MAX_ITERATIONS_COLLINEAR);\n        break;\n      }\n      iterations++;\n    }\n    // Use Zoli's method for collinearity check\n    while (((Dx1 / Dx2) == Dy1Dy2) && (Dy1Dy2 == (Dz1 / Dz2)));\n    iterations--;\n\n    // Need to improve this: we need 4 points, 3 non-collinear always, and the 4th should not be in the same plane as the other 3\n    // otherwise we can encounter degenerate cases\n    do\n    {\n      samples[3] = (int)(rand () * trand);\n      iterations++;\n    } while ( (samples[3] == samples[2]) || (samples[3] == samples[1]) || (samples[3] == samples[0]) );\n    iterations--;\n\n    return;\n  }\n\n  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n  /** \\brief Select all the points which respect the given model coefficients as inliers.\n    * \\param model_coefficients the coefficients of a sphere model that we need to compute distances to\n    * \\param threshold a maximum admissible distance threshold for determining the inliers from the outliers\n    * \\param inliers the resultant model inliers\n    * \\note: To get the refined inliers of a model, use:\n    * ANNpoint refined_coeff = refitModel (...); selectWithinDistance (refined_coeff, threshold);\n    */\n  void\n    SACModelSphere::selectWithinDistance (const std::vector<double> &model_coefficients, double threshold, std::vector<int> &inliers)\n  {\n    int nr_p = 0;\n    inliers.resize (indices_.size ());\n\n    // Iterate through the 3d points and calculate the distances from them to the sphere\n    for (unsigned int i = 0; i < indices_.size (); i++)\n    {\n      // Calculate the distance from the point to the sphere as the difference between\n      //dist(point,sphere_origin) and sphere_radius\n      if (fabs (sqrt (\n                      ( cloud_->points.at (indices_[i]).x - model_coefficients.at (0) ) *\n                      ( cloud_->points.at (indices_[i]).x - model_coefficients.at (0) ) +\n\n                      ( cloud_->points.at (indices_[i]).y - model_coefficients.at (1) ) *\n                      ( cloud_->points.at (indices_[i]).y - model_coefficients.at (1) ) +\n\n                      ( cloud_->points.at (indices_[i]).z - model_coefficients.at (2) ) *\n                      ( cloud_->points.at (indices_[i]).z - model_coefficients.at (2) )\n                     ) - model_coefficients.at (3)) < threshold)\n      {\n        // Returns the indices of the points whose distances are smaller than the threshold\n        inliers[nr_p] = indices_[i];\n        nr_p++;\n      }\n    }\n    inliers.resize (nr_p);\n    return;\n  }\n\n  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n  /** \\brief Compute all distances from the cloud data to a given sphere model.\n    * \\param model_coefficients the coefficients of a sphere model that we need to compute distances to\n    * \\param distances the resultant estimated distances\n    */\n  void\n    SACModelSphere::getDistancesToModel (const std::vector<double> &model_coefficients, std::vector<double> &distances)\n  {\n      distances.resize (indices_.size ());\n\n    // Iterate through the 3d points and calculate the distances from them to the sphere\n    for (unsigned int i = 0; i < indices_.size (); i++)\n      // Calculate the distance from the point to the sphere as the difference between\n      //dist(point,sphere_origin) and sphere_radius\n      distances[i] = fabs (sqrt (\n                                 ( cloud_->points.at (indices_[i]).x - model_coefficients.at (0) ) *\n                                 ( cloud_->points.at (indices_[i]).x - model_coefficients.at (0) ) +\n\n                                 ( cloud_->points.at (indices_[i]).y - model_coefficients.at (1) ) *\n                                 ( cloud_->points.at (indices_[i]).y - model_coefficients.at (1) ) +\n\n                                 ( cloud_->points.at (indices_[i]).z - model_coefficients.at (2) ) *\n                                 ( cloud_->points.at (indices_[i]).z - model_coefficients.at (2) )\n                                ) - model_coefficients.at (3));\n    return;\n  }\n\n  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n  /** \\brief Create a new point cloud with inliers projected onto the sphere model.\n    * \\param inliers the data inliers that we want to project on the sphere model\n    * \\param model_coefficients the coefficients of a sphere model\n    * \\param projected_points the resultant projected points\n    * \\todo implement this.\n    */\n  void\n    SACModelSphere::projectPoints (const std::vector<int> &inliers, const std::vector<double> &model_coefficients,\n                                   sensor_msgs::PointCloud &projected_points)\n  {\n    std::cerr << \"[SACModelSphere::projecPoints] Not implemented yet.\" << std::endl;\n    projected_points = *cloud_;\n  }\n\n  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n  /** \\brief Project inliers (in place) onto the given sphere model.\n    * \\param inliers the data inliers that we want to project on the sphere model\n    * \\param model_coefficients the coefficients of a sphere model\n    * \\todo implement this.\n    */\n  void\n    SACModelSphere::projectPointsInPlace (const std::vector<int> &inliers, const std::vector<double> &model_coefficients)\n  {\n    std::cerr << \"[SACModelSphere::projecPointsInPlace] Not implemented yet.\" << std::endl;\n  }\n\n  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n  /** \\brief Check whether the given index samples can form a valid sphere model, compute the model coefficients from\n    * these samples and store them internally in model_coefficients_. The sphere coefficients are: x, y, z, R.\n    * \\param samples the point indices found as possible good candidates for creating a valid model\n    */\n  bool\n    SACModelSphere::computeModelCoefficients (const std::vector<int> &samples)\n  {\n    model_coefficients_.resize (4);\n\n    Eigen::Matrix4d temp;\n    for (int i = 0; i < 4; i++)\n    {\n      temp (i, 0) = cloud_->points.at (samples.at (i)).x;\n      temp (i, 1) = cloud_->points.at (samples.at (i)).y;\n      temp (i, 2) = cloud_->points.at (samples.at (i)).z;\n      temp (i, 3) = 1;\n    }\n    double m11 = temp.determinant ();\n    if (m11 == 0)\n      return (false);             // the points don't define a sphere!\n\n    for (int i = 0; i < 4; i++)\n      temp (i, 0) = (cloud_->points.at (samples.at (i)).x) * (cloud_->points.at (samples.at (i)).x) +\n                    (cloud_->points.at (samples.at (i)).y) * (cloud_->points.at (samples.at (i)).y) +\n                    (cloud_->points.at (samples.at (i)).z) * (cloud_->points.at (samples.at (i)).z);\n    double m12 = temp.determinant ();\n\n    for (int i = 0; i < 4; i++)\n    {\n      temp (i, 1) = temp (i, 0);\n      temp (i, 0) = cloud_->points.at (samples.at (i)).x;\n    }\n    double m13 = temp.determinant ();\n\n    for (int i = 0; i < 4; i++)\n    {\n      temp (i, 2) = temp (i, 1);\n      temp (i, 1) = cloud_->points.at (samples.at (i)).y;\n    }\n    double m14 = temp.determinant ();\n\n    for (int i = 0; i < 4; i++)\n    {\n      temp (i, 0) = temp (i, 2);\n      temp (i, 1) = cloud_->points.at (samples.at (i)).x;\n      temp (i, 2) = cloud_->points.at (samples.at (i)).y;\n      temp (i, 3) = cloud_->points.at (samples.at (i)).z;\n    }\n    double m15 = temp.determinant ();\n\n    // Center (x , y, z)\n    model_coefficients_[0] = 0.5 * m12 / m11;\n    model_coefficients_[1] = 0.5 * m13 / m11;\n    model_coefficients_[2] = 0.5 * m14 / m11;\n    // Radius\n    model_coefficients_[3] = sqrt (\n                                   model_coefficients_[0] * model_coefficients_[0] +\n                                   model_coefficients_[1] * model_coefficients_[1] +\n                                   model_coefficients_[2] * model_coefficients_[2] - m15 / m11);\n\n    return (true);\n  }\n\n  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n  /** \\brief Recompute the sphere coefficients using the given inlier set and return them to the user.\n    * @note: these are the coefficients of the sphere model after refinement (eg. after SVD)\n    * \\param inliers the data inliers found as supporting the model\n    * \\param refit_coefficients the resultant recomputed coefficients after non-linear optimization\n    */\n  void\n    SACModelSphere::refitModel (const std::vector<int> &inliers, std::vector<double> &refit_coefficients)\n  {\n    if (inliers.size () == 0)\n    {\n      ROS_ERROR (\"[SACModelSphere::RefitModel] Cannot re-fit 0 inliers!\");\n      refit_coefficients = model_coefficients_;\n      return;\n    }\n    if (model_coefficients_.size () == 0)\n    {\n      ROS_WARN (\"[SACModelSphere::RefitModel] Initial model coefficients have not been estimated yet - proceeding without an initial solution!\");\n      best_inliers_ = indices_;\n    }\n\n    tmp_inliers_ = &inliers;\n    \n    int m = inliers.size ();\n\n    double *fvec = new double[m];\n\n    int n = 4;      // 4 unknowns\n    int iwa[n];\n\n    int lwa = m * n + 5 * n + m;\n    double *wa = new double[lwa];\n\n    // Set the initial solution\n    double x[4] = {0.0, 0.0, 0.0, 0.0};\n    if ((int)model_coefficients_.size () == n)\n      for (int d = 0; d < n; d++)\n        x[d] = model_coefficients_.at (d);\n\n    // Set tol to the square root of the machine. Unless high solutions are required, these are the recommended settings.\n    double tol = sqrt (dpmpar (1));\n\n    // Optimize using forward-difference approximation LM\n    int info = lmdif1 (&sample_consensus::SACModelSphere::functionToOptimize, this, m, n, x, fvec, tol, iwa, wa, lwa);\n\n    // Compute the L2 norm of the residuals\n    ROS_DEBUG (\"LM solver finished with exit code %i, having a residual norm of %g. \\nInitial solution: %g %g %g %g \\nFinal solution: %g %g %g %g\",\n               info, enorm (m, fvec), model_coefficients_.at (0), model_coefficients_.at (1), model_coefficients_.at (2), model_coefficients_.at (3),\n               x[0], x[1], x[2], x[3]);\n\n    refit_coefficients.resize (n);\n    for (int d = 0; d < n; d++)\n      refit_coefficients[d] = x[d];\n\n    free (wa); free (fvec);\n  }\n\n  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////(\n  /** \\brief Cost function to be minimized\n    * \\param p a pointer to our data structure array\n    * \\param m the number of functions\n    * \\param n the number of variables\n    * \\param x a pointer to the variables array\n    * \\param fvec a pointer to the resultant functions evaluations\n    * \\param iflag set to -1 inside the function to terminate execution\n    */\n  int\n    SACModelSphere::functionToOptimize (void *p, int m, int n, const double *x, double *fvec, int iflag)\n  {\n    SACModelSphere *model = (SACModelSphere*)p;\n\n    for (int i = 0; i < m; i ++)\n    {\n      // Compute the difference between the center of the sphere and the datapoint X_i\n      double xt = model->cloud_->points[model->tmp_inliers_->at (i)].x - x[0];\n      double yt = model->cloud_->points[model->tmp_inliers_->at (i)].y - x[1];\n      double zt = model->cloud_->points[model->tmp_inliers_->at (i)].z - x[2];\n\n      // g = sqrt ((x-a)^2 + (y-b)^2 + (z-c)^2) - R\n      fvec[i] = sqrt (xt * xt + yt * yt + zt * zt) - x[3];\n    }\n    return (0);\n  }\n\n  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n  /** \\brief Verify whether a subset of indices verifies the internal sphere model coefficients.\n    * \\param indices the data indices that need to be tested against the sphere model\n    * \\param threshold a maximum admissible distance threshold for determining the inliers from the outliers\n    */\n  bool\n    SACModelSphere::doSamplesVerifyModel (const std::set<int> &indices, double threshold)\n  {\n    for (std::set<int>::iterator it = indices.begin (); it != indices.end (); ++it)\n      // Calculate the distance from the point to the sphere as the difference between\n      //dist(point,sphere_origin) and sphere_radius\n      if (fabs (sqrt (\n                      ( cloud_->points.at (*it).x - model_coefficients_.at (0) ) *\n                      ( cloud_->points.at (*it).x - model_coefficients_.at (0) ) +\n\n                      ( cloud_->points.at (*it).y - model_coefficients_.at (1) ) *\n                      ( cloud_->points.at (*it).y - model_coefficients_.at (1) ) +\n\n                      ( cloud_->points.at (*it).z - model_coefficients_.at (2) ) *\n                      ( cloud_->points.at (*it).z - model_coefficients_.at (2) )\n                     ) - model_coefficients_.at (3)) > threshold)\n        return (false);\n\n    return (true);\n  }\n}\n", "meta": {"hexsha": "a6a2845e0df27006d1351509668831f1987fbe0c", "size": 17029, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "11_learning_materials/stanford_self_driving_car/perception/point_cloud_mapping/src/sample_consensus/sac_model_sphere.cpp", "max_stars_repo_name": "EatAllBugs/autonomous_learning", "max_stars_repo_head_hexsha": "02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-09-01T14:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T08:49:57.000Z", "max_issues_repo_path": "11_learning_materials/stanford_self_driving_car/perception/point_cloud_mapping/src/sample_consensus/sac_model_sphere.cpp", "max_issues_repo_name": "yinflight/autonomous_learning", "max_issues_repo_head_hexsha": "02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "11_learning_materials/stanford_self_driving_car/perception/point_cloud_mapping/src/sample_consensus/sac_model_sphere.cpp", "max_forks_repo_name": "yinflight/autonomous_learning", "max_forks_repo_head_hexsha": "02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-10-10T00:58:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T13:16:09.000Z", "avg_line_length": 43.8891752577, "max_line_length": 149, "alphanum_fraction": 0.5851782254, "num_tokens": 4284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2976840509151863}}
{"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\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\nnamespace SphericalHarmonics {\n    PS::F64 CoefficientY00 = 0.5 * sqrt(1.0 / M_PI);\n    PS::F64 CoefficientY10 = 0.5 * sqrt(3.0 / M_PI);\n    PS::F64 CoefficientY11 = 0.5 * sqrt(1.5 / M_PI);\n    PS::F64 CoefficientY20 = sqrt( 5. / (16. * M_PI));\n    PS::F64 CoefficientY22 = sqrt(15. / (32. * M_PI));\n\n    bool    FirstTime         = true;\n    PS::F64 MinimumRadius     = 1e+08;\n    PS::F64 MaximumRadius     = 1e+11;\n    PS::S64 NumberOfBinPerDex = 10;\n\n    PS::S64 NumberOfBin = 0;\n    const PS::S64 MaximumNumberOfBin = 64;\n    static PS::F64 m00re[MaximumNumberOfBin];\n    static PS::F64 m10re[MaximumNumberOfBin];\n    static PS::F64 m11re[MaximumNumberOfBin];\n    static PS::F64 m11im[MaximumNumberOfBin];\n    static PS::F64 m20re[MaximumNumberOfBin];\n    static PS::F64 m22re[MaximumNumberOfBin];\n    static PS::F64 m22im[MaximumNumberOfBin];\n    static PS::S64 nptcl[MaximumNumberOfBin];\n    static PS::F64 m00re_g[MaximumNumberOfBin];\n    static PS::F64 m10re_g[MaximumNumberOfBin];\n    static PS::F64 m11re_g[MaximumNumberOfBin];\n    static PS::F64 m11im_g[MaximumNumberOfBin];\n    static PS::F64 m20re_g[MaximumNumberOfBin];\n    static PS::F64 m22re_g[MaximumNumberOfBin];\n    static PS::F64 m22im_g[MaximumNumberOfBin];\n    static PS::S64 nptcl_g[MaximumNumberOfBin];\n\n    void initialize() {\n        FirstTime = false;\n        PS::F64 temp = log10(MaximumRadius / MinimumRadius) * NumberOfBinPerDex;\n        NumberOfBin = (temp - (PS::S64)temp == 0.) ? (PS::S64)temp : (PS::S64)(temp + 1.);\n        assert(NumberOfBin <= MaximumNumberOfBin);\n        for(PS::S64 i = 0; i < NumberOfBin; i++) {\n            m00re[i] = 0.;\n            m10re[i] = 0.;\n            m11re[i] = 0.;\n            m11im[i] = 0.;\n            m20re[i] = 0.;\n            m22re[i] = 0.;\n            m22im[i] = 0.;\n            nptcl[i] = 0;\n            m00re_g[i] = 0.;\n            m10re_g[i] = 0.;\n            m11re_g[i] = 0.;\n            m11im_g[i] = 0.;\n            nptcl_g[i] = 0.;\n        }\n    }\n\n    void reinitialize() {\n        for(PS::S64 i = 0; i < NumberOfBin; i++) {\n            m00re[i] = 0.;\n            m10re[i] = 0.;\n            m11re[i] = 0.;\n            m11im[i] = 0.;\n            m20re[i] = 0.;\n            m22re[i] = 0.;\n            m22im[i] = 0.;\n            nptcl[i] = 0;\n            m00re_g[i] = 0.;\n            m10re_g[i] = 0.;\n            m11re_g[i] = 0.;\n            m11im_g[i] = 0.;\n            nptcl_g[i] = 0.;\n        }\n    }\n\n    template <class Tsph>\n    inline void addParticle(Tsph & isph) {\n        PS::F64 r2 = isph.pos * isph.pos;\n        if(r2 >= MaximumRadius * MaximumRadius) {\n            return;\n        }\n        PS::F64 r1 = sqrt(r2);\n        PS::S64 ibin = PS::S64(log10(r1 / MinimumRadius) * NumberOfBinPerDex);\n        assert(ibin < NumberOfBin);\n\n        PS::F64 cr = sqrt(isph.pos[0] * isph.pos[0] + isph.pos[1] * isph.pos[1]);\n        PS::F64 prinv = 1. / r1;\n        PS::F64 crinv = 1. / cr;\n        PS::F64 costheta = isph.pos[2] * prinv;\n        PS::F64 sintheta = cr          * prinv;\n        PS::F64 cosphi   = isph.pos[0] * crinv;\n        PS::F64 sinphi   = isph.pos[1] * crinv;\n\n        PS::F64 costheta_sq   = costheta * costheta;\n        PS::F64 sintheta_sq   = sintheta * sintheta;\n        PS::F64 cosphi_2times = cosphi * cosphi - sinphi * sinphi;\n        PS::F64 sinphi_2times = 2. * sinphi * cosphi;\n\n        m00re[ibin] += isph.mass * CoefficientY00;\n        m10re[ibin] += isph.mass * CoefficientY10 * costheta;\n        m11re[ibin] += isph.mass * CoefficientY11 * sintheta * cosphi;\n        m11im[ibin] += isph.mass * CoefficientY11 * sintheta * sinphi;\n        m20re[ibin] += isph.mass * CoefficientY20 * (3. * costheta_sq - 1.);\n        m22re[ibin] += isph.mass * CoefficientY22 * sintheta_sq * cosphi_2times;\n        m22im[ibin] += isph.mass * CoefficientY22 * sintheta_sq * sinphi_2times;\n        nptcl[ibin] += 1;\n    }\n\n    void reduce() {\n        PS::S64 ierr = 0;\n        ierr = MPI_Allreduce(m00re, m00re_g, NumberOfBin, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n        ierr = MPI_Allreduce(m10re, m10re_g, NumberOfBin, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n        ierr = MPI_Allreduce(m11re, m11re_g, NumberOfBin, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n        ierr = MPI_Allreduce(m11im, m11im_g, NumberOfBin, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n        ierr = MPI_Allreduce(m20re, m20re_g, NumberOfBin, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n        ierr = MPI_Allreduce(m22re, m22re_g, NumberOfBin, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n        ierr = MPI_Allreduce(m22im, m22im_g, NumberOfBin, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n        ierr = MPI_Allreduce(nptcl, nptcl_g, NumberOfBin, MPI_LONG_LONG, MPI_SUM, MPI_COMM_WORLD);\n    }\n\n    void output(FILE * fp) {\n        for(PS::S64 i = 0; i < NumberOfBin; i++) {\n            PS::F64 r = (i == 0) ? (0.5 * MinimumRadius)\n                : (MinimumRadius * pow(10., (i - 0.5) / NumberOfBinPerDex));\n            fprintf(fp, \"%+e %+e %+e %+e %+e %+e %+e %+e %8d\\n\",\n                    r,\n                    m00re_g[i], m10re_g[i], m11re_g[i], m11im_g[i],\n                    m20re_g[i], m22re_g[i], m22im_g[i],\n                    nptcl_g[i]);\n        }\n    }\n\n};\n\ntemplate <class Tsph>\nvoid calcDensityCenter(Tsph  & sph,\n                       PS::F64vec & xdens_g,\n                       PS::F64vec & vdens_g,\n                       PS::F64vec & adens_g) {\n    PS::F64    tdens = 0.;\n    PS::F64vec xdens = 0.;\n    PS::F64vec vdens = 0.;\n    PS::F64vec adens = 0.;\n\n    for(PS::S64 i = 0; i < sph.getNumberOfParticleLocal(); i++) {\n        if(sph[i].istar == 1) {\n            continue;\n        }\n        tdens += sph[i].dens;\n        xdens += sph[i].dens * sph[i].pos;\n        vdens += sph[i].dens * sph[i].vel;\n        adens += sph[i].dens * sph[i].acc;\n    }\n\n    PS::F64    tdens_g = PS::Comm::getSum(tdens);\n    xdens_g = PS::Comm::getSum(xdens);\n    vdens_g = PS::Comm::getSum(vdens);\n    adens_g = PS::Comm::getSum(adens);\n\n    xdens_g = xdens_g / tdens_g;\n    vdens_g = vdens_g / tdens_g;\n    adens_g = adens_g / tdens_g;\n\n    return;\n}\n\ntemplate <class Tsph>\nvoid expandInSphericalHarmonics(char * ofile,\n                                Tsph  & sph) {\n    PS::F64vec xdens = 0.;\n    PS::F64vec vdens = 0.;\n    PS::F64vec adens = 0.;\n    calcDensityCenter(sph, xdens, vdens, adens);\n    for(PS::S64 i = 0; i < sph.getNumberOfParticleLocal(); i++) {\n        sph[i].pos -= xdens;\n        sph[i].vel -= vdens;\n        sph[i].acc -= adens;\n    }\n\n    if(SphericalHarmonics::FirstTime) {\n        SphericalHarmonics::initialize();\n    } else {\n        SphericalHarmonics::reinitialize();\n    }\n\n    for(PS::S64 i = 0; i < sph.getNumberOfParticleLocal(); i++) {\n        SphericalHarmonics::addParticle(sph[i]);\n    }\n\n    SphericalHarmonics::reduce();\n\n    if(PS::Comm::getRank() == 0) {\n        FILE * fp = fopen(ofile, \"w\");\n        SphericalHarmonics::output(fp);\n        fclose(fp);\n    }\n\n}\n\nint main(int argc, char ** argv) {\n    PS::Initialize(argc, argv);\n\n    PS::ParticleSystem<SPHAnalysis> sph;\n    sph.initialize();\n    sph.createParticle(0);\n    sph.setNumberOfParticleLocal(0);\n\n    char idir[1024], odir[1024];\n    PS::S64 ibgn, iend, dsnp;\n    FILE * fp = fopen(argv[1], \"r\");\n    fscanf(fp, \"%s\", idir);\n    fscanf(fp, \"%s\", odir);\n    fscanf(fp, \"%lld%lld%lld\", &ibgn, &iend, &dsnp);\n    fclose(fp);\n\n    for(PS::S64 itime = ibgn; itime <= iend; itime += dsnp) {        \n        char tfile[1024];\n        FILE *fp = NULL;\n        PS::S64 tdir = 0;\n        for(PS::S64 iidir = 0; iidir < 100; iidir++) {\n            sprintf(tfile, \"%s/t%02d/sph_t%04d_p%06d_i%06d.dat\", idir, iidir, itime,\n                    PS::Comm::getNumberOfProc(), 0);\n            fp = fopen(tfile, \"r\");\n            if(fp != NULL) {\n                tdir = iidir;\n                break;\n            }\n        }\n        if(fp == NULL) {\n            if(PS::Comm::getRank() == 0) {\n                fprintf(stderr, \"Not found %s\\n\", tfile);\n            }\n            continue;\n        }\n        fclose(fp);\n\n        char sfile[1024];\n        sprintf(sfile, \"%s/t%02d/sph_t%04d\", idir, tdir, itime);\n        sph.readParticleAscii(sfile, \"%s_p%06d_i%06d.dat\");\n\n        char ofile[1024];\n        sprintf(ofile, \"%s/harmonics_t%04d.dat\", odir, itime);\n        expandInSphericalHarmonics(ofile, sph);\n    }\n\n    PS::Finalize();\n\n    return 0;\n}\n", "meta": {"hexsha": "9a6d6b29284909262935349252a09e187b81b26a", "size": 10514, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/expandInSphericalHarmonics/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": "code/expandInSphericalHarmonics/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": "code/expandInSphericalHarmonics/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": 34.2475570033, "max_line_length": 98, "alphanum_fraction": 0.5348107286, "num_tokens": 3504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.661922862511608, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.29746325899654646}}
{"text": "#ifndef _REGEVPROOFS_HPP_\n#define _REGEVPROOFS_HPP_\n/* regevProofs.hpp - Proofs of correct behavior for Regev encryption\n * \n * Copyright (C) 2021, LWE-PVSS\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\n * 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\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n **/\n#include <vector>\n#include <iostream>\n#include <stdexcept>\n#include <cmath>\n\n#include <NTL/mat_ZZ.h>\n\n#include \"utils.hpp\"\n#include \"regevEnc.hpp\"\n#include \"ternaryMatrix.hpp\"\n#include \"merlin.hpp\"\n#include \"pedersen.hpp\"\n#include \"shamir.hpp\"\n#include \"bulletproof.hpp\"\n#include \"utils.hpp\"\n\n//#define DEBUGGING\n\nnamespace REGEVENC {\nusing CRV25519::Point, DLPROOFS::PedersenContext, TOOLS::SharingParams,\n    DLPROOFS::MerlinBPctx, DLPROOFS::LinConstraint, DLPROOFS::QuadConstraint;\n// NOTE: REGEVENC::Scalar is not the same as CRV25519::Scalar\n\n\ninline constexpr int PAD_SIZE=4; // add 4 scalars to pad to a specific sum-of-squares\n\n// We break the decryption error vector into subvectors, each with this many scalars\n#if 1 //ifndef DEBUGGING\ninline constexpr int JLDIM = 256;  // Target dimension of Johnson–Lindenstrauss\ninline constexpr int SQRT_JL =16;\ninline constexpr int LINYDIM=128;  // Target dimension in approximate l-infty proofs\n#else\ninline constexpr int JLDIM = 16;\ninline constexpr int SQRT_JL =4;\ninline constexpr int LINYDIM =8;\n#endif\n\n// More functionality for a Merlin-context wrapper\nstruct MerlinRegev: public MerlinBPctx {\n    MerlinRegev() = default;\n    explicit MerlinRegev(const merlin_transcript& m): MerlinBPctx(m) {}\n    explicit MerlinRegev(const std::string& st): MerlinBPctx(st) {}\n\n    void processVector(const ALGEBRA::SVector& v,\n                       unsigned char* label=nullptr, size_t llen=0) {\n        if (v.length()==0) return;\n        unsigned char buf[ALGEBRA::bytesPerScalar()];\n        ALGEBRA::scalarBytes(buf, v[0], sizeof(buf));\n        merlin_transcript_commit_bytes(&mctx,label,llen,buf,sizeof(buf));\n        for (size_t i=1; i<v.length(); i++) {\n            ALGEBRA::scalarBytes(buf, v[i], sizeof(buf));\n            merlin_transcript_commit_bytes(&mctx,nullptr,0,buf,sizeof(buf));\n        }\n    }\n    void processVector(const ALGEBRA::EVector& v,\n                       unsigned char* label=nullptr, size_t llen=0) {\n        if (v.length()==0) return;\n        unsigned char buf[ALGEBRA::bytesPerScalar()*ALGEBRA::scalarsPerElement()];\n        ALGEBRA::elementBytes(buf, v[0], sizeof(buf));\n        merlin_transcript_commit_bytes(&mctx,label,llen,buf,sizeof(buf));\n        for (size_t i=1; i<v.length(); i++) {\n            ALGEBRA::elementBytes(buf, v[i], sizeof(buf));\n            merlin_transcript_commit_bytes(&mctx,nullptr,0,buf,sizeof(buf));\n        }\n    }\n    void processMatrix(const ALGEBRA::SMatrix& M,\n                       unsigned char* label=nullptr, size_t llen=0) {\n        if (M.NumRows()<1)\n            return;\n        processVector(M[0],label,llen);\n        for (size_t i=1; i<M.NumRows(); i++) {\n            processVector(M[i]);\n        }\n    }\n    void processMatrix(const ALGEBRA::EMatrix& M,\n                       unsigned char* label=nullptr, size_t llen=0) {\n        if (M.NumRows()<1)\n            return;\n        processVector(M[0],label,llen);\n        for (size_t i=1; i<M.NumRows(); i++) {\n            processVector(M[i]);\n        }\n    }\n    // a challenge n-by-m trenary matrix\n    void newTernaryMatrix(const std::string& label,\n                          ALGEBRA::TernaryMatrix& R, size_t n=0, size_t m=0) {\n        if (n<=0) n = R.NumRows();\n        if (m<=0) m = R.NumCols();\n        if (n==0 || m==0) return; // nothing to do\n        size_t bufSize = (n*m +3)/4; // two bits per element\n        unsigned char buf[bufSize];\n        merlin_transcript_challenge_bytes(&mctx,\n            (const unsigned char*)label.data(),label.size(),buf,sizeof(buf));\n        R.setFromBytes(buf, n, m);\n    }\n    void newTernaryEMatrix(const std::string& label,\n                          ALGEBRA::TernaryEMatrix& R, size_t n=0, size_t m=0) {\n        if (n<=0) n = R.NumRows();\n        if (m<=0) m = R.NumCols();\n        if (n==0 || m==0) return; // nothing to do\n        size_t bufSize = ALGEBRA::scalarsPerElement()*((n*m +3)/4); // two bits per element\n        unsigned char buf[bufSize];\n        merlin_transcript_challenge_bytes(&mctx,\n            (const unsigned char*)label.data(),label.size(),buf,sizeof(buf));\n        R.setFromBytes(buf, n, m);\n    }\n    ALGEBRA::Scalar newScalar(const std::string& label) {\n        unsigned char buf[ALGEBRA::bytesPerScalar()];\n        merlin_transcript_challenge_bytes(&mctx,\n            (const unsigned char*)label.data(),label.size(),buf,sizeof(buf));\n        ALGEBRA::Scalar s;\n        ALGEBRA::scalarFromBytes(s, buf, sizeof(buf));\n        return s;\n    }\n    ALGEBRA::Element newElement(const std::string& label) {\n        int bufSize = ALGEBRA::bytesPerScalar()*ALGEBRA::scalarsPerElement();\n        unsigned char buf[bufSize];\n        merlin_transcript_challenge_bytes(&mctx,\n            (const unsigned char*)label.data(),label.size(),buf,sizeof(buf));\n        ALGEBRA::Element e;\n        ALGEBRA::elementFromBytes(e, buf, bufSize);\n        return e;\n    }\n};\n\n// A stucture for holding all the public data that both the prover and\n// the verifier knows. The prover will fill in the commitments, both\n// can use them to derive the various challenges in the proof prootcols.\nstruct VerifierData {\n    // The global public key, and utility objects for Pedersen commitments\n    // and for \"Merlin Transcripts\" (to derive challenges in Fiat-Shamir)\n    GlobalKey *gk;        // global Regev key\n    PedersenContext *ped; // Pedersen commitment context\n    MerlinRegev *mer;     // Merlin transcript context\n    SharingParams *sp;    // parameters of Shamir sharing\n\n    // Size bounds for the various compressed (JL) vectors\n    ALGEBRA::BigInt B_dNoise; // compressed decryption noise\n    ALGEBRA::BigInt B_sk;     // compressed secret-key\n    ALGEBRA::BigInt B_r;      // comressed encryption randomness\n    ALGEBRA::BigInt B_eNoise1;// compressed small encryption noise\n    ALGEBRA::BigInt B_eNoise2;// compressed large encryption noise\n    ALGEBRA::BigInt B_kNoise; // compressed keygen noise\n    ALGEBRA::BigInt B_smallness;// Used in the approximate smallness protocol\n    int smlnsBits;  // The bitsize of B_smallness above\n    ALGEBRA::BigInt radix; // the radix used to split large integers into digits\n\n    std::vector<Point> Gs, Hs; // lists of generators\n\n    // For most vectors, we have the vector itself (e.g., sk2), the\n    // compressed vector (e.g., sk2Comp) and the padding that the prover\n    // computes to pad the compressed vector to some pre-determined size\n    // (e.g., sk2Pad). The ones without compression and padding are\n    // sk1,pt1,pt2,y. For the noise vectors we only need the indexes\n    // of the compressed vector and padding, not the original vector\n    // (since there is no Pedersen commitment to that vector).\n\n    // indexes into the generator list\n    int pt1Idx, sk1Idx, dCompHiIdx, dPadHiIdx, dCompLoIdx, dPadLoIdx, // dec\n        pt2Idx, rIdx, rCompIdx, rPadIdx, eComp1HiIdx, ePad1HiIdx, eComp1LoIdx,\n        ePad1LoIdx, eComp2HiIdx, ePad2HiIdx, eComp2LoIdx, ePad2LoIdx,  // enc\n        sk2Idx, sk2CompIdx, sk2PadIdx,\n        kCompHiIdx, kPadHiIdx, kCompLoIdx, kPadLoIdx,               // keygen\n        yIdx, wIdx;                        // smallness proof and aggregation\n\n    // Commitments to different variables. The quadratic equations require\n    // a double-commitment with respect to both the G and H generators,\n    // while the linear constraints only need commitment wrt the Gs.\n\n    Point pt1Com, sk1Com, dCompHiCom, dPadHiCom, dCompLoCom, dPadLoCom,// dec\n        pt2Com, rCom, rCompCom, rPadCom, eComp1HiCom, ePad1HiCom, eComp1LoCom,\n        ePad1LoCom, eComp2HiCom, ePad2HiCom, eComp2LoCom, ePad2LoCom,  // enc\n        sk2Com, sk2CompCom, sk2PadCom,\n        kCompHiCom, kPadHiCom, kCompLoCom, kPadLoCom,               // keygen\n        yCom, wCom;                        // smallness proof and aggregation\n\n    // A list of all the linear and quadratic constraints\n    std::vector<DLPROOFS::LinConstraint> linConstr;\n    std::vector<DLPROOFS::QuadConstraint> normConstr;\n\n    // pointers into the above vectors of constraints\n    static constexpr int dLinIdx=0,   // dec\n        eLin1Idx=GlobalKey::ell,\n        eLin2Idx=2*GlobalKey::ell,\n        rLinIdx=3*GlobalKey::ell,     // enc\n        kLinIdx=4*GlobalKey::ell,\n        sk2LinIdx=5*GlobalKey::ell,   // keygen,\n        smlnsLinIdx=6*GlobalKey::ell, // smallness\n        reShrLinIdx=7*GlobalKey::ell; // resharing\n    static constexpr int dHiQuadIdx=0, dLoQuadIdx=1, rQuadIdx=2,\n        e1HiQuadIdx=3, e1LoQuadIdx=4, e2HiQuadIdx=5, e2LoQuadIdx=6,\n        sk2QuadIdx=7, kHiQuadIdx=8, kLoQuadIdx=9;\n\n    ALGEBRA::EVector z; // the masked vector z from the proof of smallness\n\n    // Set the indexes to their default values\n    void setIndexes();\n    void computeGenerators();\n\n    // Reset when preparing for a new proof at the prover's site\n    void prepareForNextProof() {\n        std::swap(sk1Idx,sk2Idx);\n        sk1Com = sk2Com; // copy commitment to the previous sk wrt the Gs\n\n        // zero out all the commitments and constraints\n        pt1Com= dCompHiCom= dPadHiCom= dCompLoCom= dPadLoCom= pt2Com= // dec\n        rCom= rCompCom= rPadCom= eComp1HiCom= ePad1HiCom= eComp1LoCom=\n        ePad1LoCom= eComp2HiCom= ePad2HiCom= eComp2LoCom= ePad2LoCom= // enc\n        sk2Com= sk2CompCom= sk2PadCom=\n        kCompHiCom= kPadHiCom= kCompLoCom= kPadLoCom=              // keygen\n        yCom= wCom = Point::identity();\n\n        // empty the constraints w/o invalidating the pointers to them\n        DLPROOFS::LinConstraint emptyLin;\n        for (auto& lc : linConstr) lc = emptyLin;\n        DLPROOFS::QuadConstraint emptyQuad;\n        for (auto& qc : normConstr) qc = emptyQuad;\n    }\n\n    VerifierData() = default;\n    VerifierData(GlobalKey& gk, PedersenContext& ped, MerlinRegev& mer,\n                 const SharingParams& sp);\n};\n\n// For each commitment in the VerifierData, the ProverData must hold\n// the corresponding opening: the randomness r and the witness values\nstruct ProverData {\n    VerifierData *vd;\n\n    // commitment randomness\n    CRV25519::Scalar pt1Rnd, sk1Rnd,\n        dCompHiRnd, dPadHiRnd, dCompLoRnd, dPadLoRnd,                  // dec\n        pt2Rnd, rRnd, rCompRnd, rPadRnd, eComp1HiRnd, ePad1HiRnd, eComp1LoRnd,\n        ePad1LoRnd, eComp2HiRnd, ePad2HiRnd, eComp2LoRnd, ePad2LoRnd,  // enc\n        sk2Rnd, sk2CompRnd, sk2PadRnd,\n        kCompHiRnd, kPadHiRnd, kCompLoRnd, kPadLoRnd,               // keygen\n        yRnd, wRnd;                    // smallness proof and aggregation\n\n    // The compressed vectors, concatenated\n    ALGEBRA::EVector compressed;\n\n    // The witnesses for the linear and quadratic constraints\n\n    DLPROOFS::PtxtVec linWitness;\n    DLPROOFS::PtxtVec quadWitnessG, quadWitnessH;\n\n    // Reset when preparing for a new proof at the prover's site\n    void prepareForNextProof() {\n        vd->prepareForNextProof(); // reset the public data\n        sk1Rnd = sk2Rnd; // randomness of commitment to secret key wrt Gs\n    }\n\n    ProverData() = default;    \n    ProverData(VerifierData& verData): vd(&verData) {\n        compressed.SetLength(10*(JLDIM+PAD_SIZE)/ALGEBRA::scalarsPerElement());\n   }\n};\n\n// Proof of decryption. We assume that the ProverData,VerifierData are\n// already initialized, and that ProverData contains sk1 and VerifierData\n// contains a commitment to it.\nvoid proveDecryption(ProverData& pd, \n    const ALGEBRA::EMatrix& ctMat, const ALGEBRA::EVector& ctVec,\n    const ALGEBRA::SVector& ptxt, const ALGEBRA::EVector& skey,\n    const ALGEBRA::EVector& noise);\n\nvoid verifyDecryption(VerifierData& vd, // vd has all the commitments\n        const ALGEBRA::EMatrix& ctMat, const ALGEBRA::EVector& ctVec);\n\n// Proof of encryption\nvoid proveEncryption(ProverData& pd,\n        const ALGEBRA::EVector& ct1, const ALGEBRA::EVector& ct2, \n        const ALGEBRA::SVector& ptxt, const ALGEBRA::EVector& rnd,\n        const ALGEBRA::EVector& noise1,const ALGEBRA::EVector& noise2);\n\nvoid verifyEncryption(VerifierData& vd,\n        const ALGEBRA::EVector& ct1, const ALGEBRA::EVector& ct2);\n\n// Proof of key-generation. pkNum is index of the pkey in the GlobalKey\nvoid proveKeyGen(ProverData& pd, int pkNum,\n        const ALGEBRA::EVector& sk, const ALGEBRA::EVector& noise);\n\nvoid verifyKeyGen(VerifierData& vd, int pkNum);\n\n// Proof of correct re-sharing. It is assumed that pt1, pt2\n// are already initialized in the ps structure\nvoid proveReShare(ProverData& pd, const ALGEBRA::SVector& lagrange,\n        const ALGEBRA::SVector& pt1, const ALGEBRA::SVector& pt2);\nvoid verifyReShare(VerifierData& vd, const ALGEBRA::SVector& lagrange);\n    // TOOLS::EvalSet from shamir.hpp describes the reconstruction set\n\n// Proof of approximate smallness (of all except the compressed vectors)\nvoid proveSmallness(ProverData& pd);\nvoid verifySmallness(VerifierData& vd);\n\nstruct ReadyToVerify {\n    // The linear and quadratic constraints and commitments\n    DLPROOFS::LinConstraint linCnstr;\n    Point linCom;\n    DLPROOFS::QuadConstraint quadCnstr;\n    Point quadCom;\n\n    // The offset used for the G, H witnesses in the quadratic proof\n    DLPROOFS::PtxtVec deltaG, deltaH;\n\n    // temporary variables used in aggregating the proofs\n    std::vector<CRV25519::Scalar> rVec, uVec;\n    DLPROOFS::PtxtVec as, bs;\n\n    // Flattened versions of the statements and generators\n    std::vector<Point> linGs;\n    std::vector<CRV25519::Scalar> linStmnt;\n\n    std::vector<Point> quadGs;\n    std::vector<Point> quadHs;\n    std::vector<CRV25519::Scalar> offstG;\n    std::vector<CRV25519::Scalar> offstH;\n\n    void aggregateVerifier1(VerifierData& vd);\n    void aggregateVerifier2(VerifierData& vd);\n\n    void flattenLinVer(VerifierData& vd);\n    void flattenQuadVer(VerifierData& vd);\n};\nstruct ReadyToProve : public ReadyToVerify {\n    // Randomness used for linCom and quadCom\n    CRV25519::Scalar lComRnd, qComRnd;\n\n    // Flattened versions of the witnesses\n    std::vector<CRV25519::Scalar> linWtns;\n    std::vector<CRV25519::Scalar> quadWtnsG, quadWtnsH;\n\n    void aggregateProver(ProverData& pd);\n    void flattenLinPrv(ProverData& pd);\n    void flattenQuadPrv(ProverData& pd);\n};\n\n\n/****** utility functions *******/\n\n// Compute the vector (1,x,x^2,...,x^{len-1})\nvoid powerVector(ALGEBRA::SVector& vec, const ALGEBRA::Scalar& x, int len);\nvoid powerVector(ALGEBRA::EVector& vec, const ALGEBRA::Element& x, int len);\nvoid powerVector(std::vector<CRV25519::Scalar>& vec, const CRV25519::Scalar& x, int len);\n\n// Commit to a slice of the vector\nPoint commit(const ALGEBRA::SVector& v, size_t genIdx,\n             const std::vector<Point>& Gs, CRV25519::Scalar& r,\n             int fromIdx=0, int toIdx=-1);\nPoint commit(const ALGEBRA::EVector& v, size_t genIdx,\n             const std::vector<Point>& Gs, CRV25519::Scalar& r,\n             int fromIdx=0, int toIdx=-1);\n// commit to the same xes wrt both Gs and Hs\nPoint commit2(const ALGEBRA::EVector& v, size_t genIdx,\n             const std::vector<Point>& Gs, const std::vector<Point>& Hs,\n             CRV25519::Scalar& r, int fromIdx=0, int toIdx=-1);\n\n// Add to v four integers a,b,c,d such that the result\n// (v | a,b,c,d) has norm exactly equal to the bound\nvoid pad2exactNorm(const ALGEBRA::SVector& v,\n         ALGEBRA::SVector& padding, const ALGEBRA::BigInt& bound);\nvoid pad2exactNorm(const ALGEBRA::EVector& v,\n        ALGEBRA::EVector& padding, const ALGEBRA::BigInt& bound);\nvoid pad2exactNorm(const ALGEBRA::Element* v, size_t len,\n        ALGEBRA::Element* padSpace, const ALGEBRA::BigInt& bound);\n\n// The expand functions below assume that GF(p^ell) is represented\n// modulo X^ell +1.\n\n// Expand a constraint a*x with a in GF(p^ell) to e constrints over scalars,\n// namely store in 'constrs' ell constraints in ell variables, representing\n// the ell-by-ell scalar matrix for multiply-by-a. The variables in these\n// constraints are indexed by idx,idx+1,... For example, the constraints\n// for the 1st row has coeffs: idx->a.freeTerm, idx+1 -> a.coeffOf(X),...\nvoid expandConstraints(LinConstraint* constrs, int idx, const ALGEBRA::Element& a);\n\n// Expand each of the constraints v[i]*x with successive indexes\nvoid expandConstraints(LinConstraint* constrs, int idx,\n                       const ALGEBRA::EVector& v, int from=0, int to=-1);\n\n// This function is for the case where the secret variables are from Z_p,\n// namely we have the constraint <x,v>=b over GF(p^ell), but x is over Z_p.\nvoid makeConstraints(LinConstraint* constrs, int idx,\n                     const ALGEBRA::EVector& v, int from=0, int to=-1);\n\n// This function sets the equalsTo field for the ell constraints\n// corresponding to the ell scalars representing the element e\nvoid setEqsTo(LinConstraint* constrs, const ALGEBRA::Element& e);\n\nbool checkQuadCommit(DLPROOFS::QuadConstraint& c,\n    const Point& com, const Point& padCom, const CRV25519::Scalar& rnd,\n    const CRV25519::Scalar& padRnd, DLPROOFS::PtxtVec& witness, PedersenContext* ped);\nbool checkLinCommit(DLPROOFS::PtxtVec& pv,\n    const Point& com, const CRV25519::Scalar& rnd,\n    DLPROOFS::PtxtVec& witness, PedersenContext* ped);\n\n} // end of namespace REGEVENC\n#endif // ifndef _REGEVPROOFS_HPP_\n", "meta": {"hexsha": "ac5c9d36a7b7fe49bae11dc4cc611dfd76bdcff0", "size": 18332, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/regevProofs.hpp", "max_stars_repo_name": "shaih/cpp-lwevss", "max_stars_repo_head_hexsha": "250516eb4270a87383cad40df498da4523242ee8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2022-01-24T21:19:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T23:07:39.000Z", "max_issues_repo_path": "include/regevProofs.hpp", "max_issues_repo_name": "shaih/cpp-lwevss", "max_issues_repo_head_hexsha": "250516eb4270a87383cad40df498da4523242ee8", "max_issues_repo_licenses": ["MIT"], "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/regevProofs.hpp", "max_forks_repo_name": "shaih/cpp-lwevss", "max_forks_repo_head_hexsha": "250516eb4270a87383cad40df498da4523242ee8", "max_forks_repo_licenses": ["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.2358490566, "max_line_length": 91, "alphanum_fraction": 0.6829587606, "num_tokens": 5221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.29746244384854564}}
{"text": "// Copyright 2020 the Autoware Foundation\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#ifndef NDT__UTILS_HPP_\n#define NDT__UTILS_HPP_\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <geometry_msgs/msg/transform.hpp>\n#include <point_cloud_msg_wrapper/point_cloud_msg_wrapper.hpp>\n#include <helper_functions/float_comparisons.hpp>\n#include <geometry_msgs/msg/pose.hpp>\n#include <Eigen/Eigenvalues>\n#include <algorithm>\n#include <limits>\n#include <tuple>\n\nnamespace autoware\n{\nnamespace localization\n{\nnamespace ndt\n{\n\nstruct PointWithCovariances\n{\n  double x;\n  double y;\n  double z;\n  double icov_xx;\n  double icov_xy;\n  double icov_xz;\n  double icov_yy;\n  double icov_yz;\n  double icov_zz;\n  friend bool operator==(const PointWithCovariances & p1, const PointWithCovariances & p2)\n  {\n    constexpr auto eps = std::numeric_limits<double>::epsilon();\n    return common::helper_functions::comparisons::rel_eq(p1.x, p2.x, eps) &&\n           common::helper_functions::comparisons::rel_eq(p1.y, p2.y, eps) &&\n           common::helper_functions::comparisons::rel_eq(p1.z, p2.z, eps) &&\n           common::helper_functions::comparisons::rel_eq(p1.icov_xx, p2.icov_xx, eps) &&\n           common::helper_functions::comparisons::rel_eq(p1.icov_xy, p2.icov_xy, eps) &&\n           common::helper_functions::comparisons::rel_eq(p1.icov_xz, p2.icov_xz, eps) &&\n           common::helper_functions::comparisons::rel_eq(p1.icov_yy, p2.icov_yy, eps) &&\n           common::helper_functions::comparisons::rel_eq(p1.icov_yz, p2.icov_yz, eps) &&\n           common::helper_functions::comparisons::rel_eq(p1.icov_zz, p2.icov_zz, eps);\n  }\n};\nLIDAR_UTILS__DEFINE_FIELD_GENERATOR_FOR_MEMBER(icov_xx);\nLIDAR_UTILS__DEFINE_FIELD_GENERATOR_FOR_MEMBER(icov_xy);\nLIDAR_UTILS__DEFINE_FIELD_GENERATOR_FOR_MEMBER(icov_xz);\nLIDAR_UTILS__DEFINE_FIELD_GENERATOR_FOR_MEMBER(icov_yy);\nLIDAR_UTILS__DEFINE_FIELD_GENERATOR_FOR_MEMBER(icov_yz);\nLIDAR_UTILS__DEFINE_FIELD_GENERATOR_FOR_MEMBER(icov_zz);\n\nusing PointWithCovariancesFieldGenerators = std::tuple<\n  point_cloud_msg_wrapper::field_x_generator,\n  point_cloud_msg_wrapper::field_y_generator,\n  point_cloud_msg_wrapper::field_z_generator,\n  field_icov_xx_generator,\n  field_icov_xy_generator,\n  field_icov_xz_generator,\n  field_icov_yy_generator,\n  field_icov_yz_generator,\n  field_icov_zz_generator>;\n\nusing NdtMapCloudModifier =\n  point_cloud_msg_wrapper::PointCloud2Modifier<PointWithCovariances,\n    PointWithCovariancesFieldGenerators>;\n\nusing NdtMapCloudView =\n  point_cloud_msg_wrapper::PointCloud2View<PointWithCovariances,\n    PointWithCovariancesFieldGenerators>;\n\n/// This function will check if the covariance is valid based on its eigenvalues. If the covariance\n/// is valid, eigen values smaller than a fraction of the biggest eigen value will be capped to the\n/// threshold. Covariance then will be reconstructed from the modified set of eigen values and\n/// vectors. This should result in increased numerical stability as stated in [Magnusson 2009].\n/// If the covariance is invalid, it will not be updated and false will be returned.\n/// \\tparam Derived Deduced Eigen Matrix type.\n/// \\param covariance [in, out] Covariance matrix to get stabilized.\n/// \\param scaling_factor [in] The ratio between the max. eigen value and the minimum\n/// allowed eigenvalue. Default value is 0.01 as suggested in [Magnusson 2009], page 60.\n/// \\return True if the covariance matrix is valid.\ntemplate<typename Derived>\nbool try_stabilize_covariance(\n  Eigen::MatrixBase<Derived> & covariance,\n  typename Derived::PlainMatrix::Scalar scaling_factor = 0.1)\n{\n  using CovMatrixT = typename Derived::PlainMatrix;\n  using ScalarT = typename CovMatrixT::Scalar;\n  using IndexT = typename CovMatrixT::Index;\n  using SolverT = Eigen::SelfAdjointEigenSolver<CovMatrixT>;\n  using VectorT = typename SolverT::RealVectorType;\n\n  Eigen::SelfAdjointEigenSolver<CovMatrixT> solver(covariance);\n  if (solver.info() != Eigen::Success) {return false;}\n\n  VectorT eigen_values = solver.eigenvalues();  // Sorted in increasing order.\n  const auto min_eigen_value = eigen_values[0];\n  const auto max_eigen_value = eigen_values[eigen_values.size() - IndexT{1U}];\n  const auto stabilized_min_eigen_value = scaling_factor * max_eigen_value;\n  if (stabilized_min_eigen_value < std::numeric_limits<ScalarT>::epsilon()) {return false;}\n  if (min_eigen_value > scaling_factor * max_eigen_value) {return true;}  // Already stable.\n  for (auto i = IndexT{0U}; i < eigen_values.size(); ++i) {\n    eigen_values[i] = std::max(eigen_values[i], stabilized_min_eigen_value);\n  }\n  covariance =\n    solver.eigenvectors() * eigen_values.asDiagonal() * solver.eigenvectors().transpose();\n  return true;\n}\n\ntemplate<typename T>\nusing EigenPose = Eigen::Matrix<T, 6U, 1U>;\ntemplate<typename T>\nusing EigenTransform = Eigen::Transform<T, 3, Eigen::Affine, Eigen::ColMajor>;\nusing RosTransform = geometry_msgs::msg::Transform;\nusing RosPose = geometry_msgs::msg::Pose;\nnamespace transform_adapters\n{\n/// Template function to convert a 6D pose to a transformation matrix.\n/// This function should be specialized and implemented for the supported types.\n/// \\tparam PoseT Pose type.\n/// \\tparam TransformT Transform type.\n/// \\param[in] pose pose to convert\n/// \\param[out] transform resulting transform\ntemplate<typename PoseT, typename TransformT>\nvoid pose_to_transform(const PoseT & pose, TransformT & transform);\n\n/// Template function to convert a 6D pose to a transformation matrix.\n/// This function should be specialized and implemented for the supported types.\n/// \\tparam PoseT Pose type.\n/// \\tparam TransformT Transform type.\n/// \\param[in] transform resulting transform\n/// \\param[out] pose pose to convert\ntemplate<typename PoseT, typename TransformT>\nvoid transform_to_pose(const TransformT & transform, PoseT & pose);\n\n\ntemplate<typename T>\nvoid pose_to_transform(\n  const EigenPose<T> & pose,\n  EigenTransform<T> & transform)\n{\n  static_assert(std::is_floating_point<T>::value, \"Eigen transform should use floating points\");\n  transform.setIdentity();\n  transform.translation() = pose.head(3);\n  transform.rotate(Eigen::AngleAxis<T>(pose(3), Eigen::Vector3d::UnitX()));\n  transform.rotate(Eigen::AngleAxis<T>(pose(4), Eigen::Vector3d::UnitY()));\n  transform.rotate(Eigen::AngleAxis<T>(pose(5), Eigen::Vector3d::UnitZ()));\n}\n\n/// Specialization to convert from the eigen pose to the ros transform type.\n/// \\tparam T Eigen scalar type\ntemplate<typename T>\nvoid pose_to_transform(\n  const EigenPose<T> & pose,\n  RosTransform & transform)\n{\n  static_assert(std::is_floating_point<T>::value, \"Eigen pose should use floating points\");\n  Eigen::Quaternion<T> eig_rot{Eigen::Quaternion<T>{}.setIdentity()};\n  eig_rot.setIdentity();\n  eig_rot =\n    Eigen::AngleAxis<T>(pose(3), Eigen::Matrix<T, 3, 1>::UnitX()) *\n    Eigen::AngleAxis<T>(pose(4), Eigen::Matrix<T, 3, 1>::UnitY()) *\n    Eigen::AngleAxis<T>(pose(5), Eigen::Matrix<T, 3, 1>::UnitZ());\n\n  decltype(RosTransform::translation) trans;\n  decltype(RosTransform::rotation) rot;\n\n  trans.set__x(pose(0)).set__y(pose(1)).set__z(pose(2));\n  transform.set__translation(trans);\n\n  rot.set__x(eig_rot.x()).\n  set__y(eig_rot.y()).\n  set__z(eig_rot.z()).\n  set__w(eig_rot.w());\n  transform.set__rotation(rot);\n}\n\n/// Specialization to convert from the eigen pose to the ros pose type.\n/// `pose_to_transform` template is used as conversion to `RosPose`\n/// is identical to conversion to `RosTransform`\n/// \\tparam T Eigen scalar type\ntemplate<typename T>\nvoid pose_to_transform(\n  const EigenPose<T> & pose,\n  RosPose & ros_pose)\n{\n  static_assert(std::is_floating_point<T>::value, \"Eigen pose should use floating points\");\n  Eigen::Quaternion<T> eig_rot{Eigen::Quaternion<T>{}.setIdentity()};\n  eig_rot =\n    Eigen::AngleAxis<T>(pose(3), Eigen::Matrix<T, 3, 1>::UnitX()) *\n    Eigen::AngleAxis<T>(pose(4), Eigen::Matrix<T, 3, 1>::UnitY()) *\n    Eigen::AngleAxis<T>(pose(5), Eigen::Matrix<T, 3, 1>::UnitZ());\n\n  decltype(RosPose::position) trans;\n  decltype(RosTransform::rotation) rot;\n\n  trans.set__x(pose(0)).set__y(pose(1)).set__z(pose(2));\n  ros_pose.set__position(trans);\n\n  rot.set__x(eig_rot.x()).\n  set__y(eig_rot.y()).\n  set__z(eig_rot.z()).\n  set__w(eig_rot.w());\n  ros_pose.set__orientation(rot);\n}\n\n/// Specialization to convert from the ros pose type to an eigen one.\n/// \\tparam T Eigen scalar type\ntemplate<typename T>\nvoid transform_to_pose(const RosTransform & transform, EigenPose<T> & pose)\n{\n  static_assert(std::is_floating_point<T>::value, \"Eigen pose should use floating points\");\n  const auto & ros_rot = transform.rotation;\n  const auto & ros_trans = transform.translation;\n  Eigen::Quaternion<T> eig_rot{ros_rot.w, ros_rot.x, ros_rot.y, ros_rot.z};\n  pose(0) = ros_trans.x;\n  pose(1) = ros_trans.y;\n  pose(2) = ros_trans.z;\n\n  const auto rot = eig_rot.matrix().eulerAngles(0, 1, 2);\n  pose(3) = rot(0);\n  pose(4) = rot(1);\n  pose(5) = rot(2);\n}\n\n/// Specialization to convert from the ros pose type to an eigen one.\n/// `transform_to_pose` template is used as conversion from `RosPose`\n/// is identical to conversion from `RosTransform`\n/// \\tparam T Eigen scalar type\ntemplate<typename T>\nvoid transform_to_pose(const RosPose & ros_pose, EigenPose<T> & pose)\n{\n  static_assert(std::is_floating_point<T>::value, \"Eigen pose should use floating points\");\n  const auto & ros_rot = ros_pose.orientation;\n  const auto & ros_trans = ros_pose.position;\n  Eigen::Quaternion<T> eig_rot{ros_rot.w, ros_rot.x, ros_rot.y, ros_rot.z};\n  pose(0) = ros_trans.x;\n  pose(1) = ros_trans.y;\n  pose(2) = ros_trans.z;\n\n  const auto rot = eig_rot.matrix().eulerAngles(0, 1, 2);\n  pose(3) = rot(0);\n  pose(4) = rot(1);\n  pose(5) = rot(2);\n}\n\n}  // namespace transform_adapters\n}  // namespace ndt\n}  // namespace localization\n}  // namespace autoware\n\n#endif  // NDT__UTILS_HPP_\n", "meta": {"hexsha": "43237b78d21b985246ad114e5dfcbac81b6e9cf8", "size": 10396, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/localization/ndt/include/ndt/utils.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/localization/ndt/include/ndt/utils.hpp", "max_issues_repo_name": "ruvus/auto", "max_issues_repo_head_hexsha": "25ae62d6e575cae40212356eed43ec3e76e9a13e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-23T16:45:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-03T16:59:40.000Z", "max_forks_repo_path": "src/localization/ndt/include/ndt/utils.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": 38.5037037037, "max_line_length": 99, "alphanum_fraction": 0.7408618699, "num_tokens": 2774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.29731081156278744}}
{"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#include \"Utils/Bonds/BondDetector.h\"\n\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\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 AngstromPositions& wrapper,\n  const AtomIndex v,\n  const std::vector<AtomIndex>& site\n) {\n  const auto& positions = wrapper.positions;\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.row(siteAtom);\n  }\n  siteCentroid /= siteSize;\n\n  if(siteSize == 2) {\n    const double frontAngle = Cartesian::angle(\n      positions.row(v),\n      siteCentroid,\n      positions.row(site.front())\n    );\n    const double backAngle = Cartesian::angle(\n      positions.row(v),\n      siteCentroid,\n      positions.row(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.row(v).transpose();\n\n  Utils::PositionCollection hapticAtoms(siteSize, 3);\n  for(unsigned i = 0; i < siteSize; ++i) {\n    hapticAtoms.row(i) = positions.row(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 AngstromPositions& angstromPositions,\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 auto& positions = angstromPositions.positions;\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.row(j);\n    }\n    sitePositions.col(i) = averagePosition / sites[i].size();\n  }\n  sitePositions.col(S) = positions.row(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 AngstromPositions& 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 = countComponents();\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 = countComponents();\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  const unsigned N = map.size();\n  for(unsigned i = 0; i < N; ++i) {\n    const 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\nunsigned ComponentMap::countComponents() const {\n  assert(!map.empty());\n  return *std::max_element(\n    std::begin(map),\n    std::end(map)\n  ) + 1;\n}\n\nstd::vector<AngstromPositions> ComponentMap::apply(\n  const AngstromPositions& positions\n) const {\n  const unsigned nComponents = countComponents();\n  std::vector<unsigned> componentSizes(nComponents, 0);\n  for(unsigned i : map) {\n    componentSizes.at(i) += 1;\n  }\n\n  /* Allocate the component position objects */\n  std::vector<AngstromPositions> collections = Temple::map(\n    componentSizes,\n    [](const unsigned size) { return AngstromPositions(size); }\n  );\n  std::vector<unsigned> collectionSizeCount(nComponents, 0);\n\n  const unsigned N = map.size();\n  for(unsigned i = 0; i < N; ++i) {\n    const unsigned moleculeIndex = map.at(i);\n    AngstromPositions& componentPositions = collections.at(moleculeIndex);\n    unsigned& collectionSize = collectionSizeCount.at(moleculeIndex);\n    componentPositions.positions.row(collectionSize) = positions.positions.row(i);\n    ++collectionSize;\n  }\n\n  return collections;\n}\n\nstd::vector<PeriodicBoundaryDuplicates> ComponentMap::apply(\n  const std::unordered_set<unsigned>& uninterestingAtoms,\n  const std::unordered_map<unsigned, unsigned>& ghostAtomMap\n) const {\n  const unsigned nComponents = countComponents();\n  std::vector<PeriodicBoundaryDuplicates> containers(nComponents);\n\n  std::vector<unsigned long> indicesInComponent (nComponents, 0);\n  const unsigned N = size();\n  for(unsigned i = 0; i < N; ++i) {\n    const unsigned component = map.at(i);\n    unsigned long& indexInComponent = indicesInComponent.at(component);\n    PeriodicBoundaryDuplicates& componentContainers = containers.at(component);\n\n    if(uninterestingAtoms.count(i) > 0) {\n      componentContainers.uninterestingAtoms.insert(indexInComponent);\n    }\n\n    const auto ghostAtomMapIter = ghostAtomMap.find(i);\n    if(ghostAtomMapIter != std::end(ghostAtomMap)) {\n      auto transformedMappedIndex = apply(ghostAtomMapIter->second);\n      assert(transformedMappedIndex.component == component);\n      componentContainers.ghostAtomMap.emplace(\n        indexInComponent,\n        transformedMappedIndex.atomIndex\n      );\n    }\n\n    ++indexInComponent;\n  }\n\n  return containers;\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  AngstromPositions positions;\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  /* Must keep a map of atom collection index to precursor index and new\n   * 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    const 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-8) {\n      parts.nZeroLengthPositions += 1;\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  // Split angstrom atom positions and store in precursors\n  auto splitPositions = parts.componentMap.apply(angstromWrapper);\n  for(unsigned i = 0; i < numComponents; ++i) {\n    parts.precursors.at(i).positions = std::move(splitPositions.at(i));\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  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        precursor.positions,\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    Utils::BondDetector::detectBonds(elements, angstromWrapper.getBohr()),\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    Utils::BondDetector::detectBonds(atomCollection),\n    discretization,\n    stereopermutatorThreshold\n  );\n}\n\n/* Periodic variation of molecule instantiation */\nMoleculesResult molecules(\n  const Utils::AtomCollection& atoms,\n  const Utils::BondOrderCollection& periodicBonds,\n  const std::unordered_set<unsigned>& uninterestingAtoms,\n  const std::unordered_map<unsigned, unsigned>& ghostAtomMap,\n  const BondDiscretizationOption discretization,\n  const boost::optional<double>& stereopermutatorThreshold\n) {\n  const AngstromPositions angstroms {atoms.getPositions(), LengthUnit::Bohr};\n\n  Parts parts = construeParts(\n    atoms.getElements(),\n    angstroms,\n    periodicBonds,\n    discretization,\n    stereopermutatorThreshold\n  );\n\n  // Refuse to deal with missing coordinates\n  if(parts.nZeroLengthPositions > 1) {\n    throw std::runtime_error(\"Found multiple coordinates of length zero. Please provide atom positions!\");\n  }\n\n  const auto periodicContainers = parts.componentMap.apply(uninterestingAtoms, ghostAtomMap);\n\n  MoleculesResult result;\n  result.molecules.reserve(parts.precursors.size());\n  const unsigned N = parts.precursors.size();\n  for(unsigned i = 0; i < N; ++i) {\n    auto& precursor = parts.precursors.at(i);\n    result.molecules.emplace_back(\n      Graph {std::move(precursor.graph)},\n      precursor.positions,\n      precursor.bondStereopermutatorCandidatesOptional,\n      periodicContainers.at(i)\n    );\n  }\n\n  // Copy the component map, removing ghost atoms\n  if(ghostAtomMap.empty()) {\n    result.componentMap = std::move(parts.componentMap);\n  } else {\n    for(unsigned i = 0; i < parts.componentMap.size(); ++i) {\n      if(ghostAtomMap.count(i) > 0) {\n        break;\n      }\n\n      result.componentMap.map.push_back(parts.componentMap.map.at(i));\n    }\n  }\n\n  return result;\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.positions, 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.positions, 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.positions.positions.row(v)\n            - part.positions.positions.row(site.front())\n          ).norm();\n          const double backDistance = (\n            part.positions.positions.row(v)\n            - part.positions.positions.row(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.positions,\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": "1ab1ac821acac1fc9fa818862e6a45f27678c104", "size": 27511, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Molassembler/Interpret.cpp", "max_stars_repo_name": "qcscine/molassembler", "max_stars_repo_head_hexsha": "3b72168477b2d1dee55812517e49d9c3285c50ba", "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/Interpret.cpp", "max_issues_repo_name": "qcscine/molassembler", "max_issues_repo_head_hexsha": "3b72168477b2d1dee55812517e49d9c3285c50ba", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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": "qcscine/molassembler", "max_forks_repo_head_hexsha": "3b72168477b2d1dee55812517e49d9c3285c50ba", "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": 30.5338512764, "max_line_length": 106, "alphanum_fraction": 0.6801279488, "num_tokens": 6500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7431679972357831, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2971272163201459}}
{"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\n\nint verifyProof(r1cs_ppzksnark_verification_key<default_r1cs_ppzksnark_pp> verificationKey_in, string proofFileName)\n{\n  boost::optional<libsnark::r1cs_ppzksnark_proof<libff::alt_bn128_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  bit_vector h_startBalance_bv;\n  bit_vector h_endBalance_bv;\n  bit_vector h_incoming_bv[noIncomingPayments];\n  bit_vector h_outgoing_bv[noOutgoingPayments];\n  vector<vector<unsigned long int>> values = fillValuesFromfile(\"publicInputParameters_multi\");\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  \n  for (counter = 0; counter < noIncomingPayments; counter++)\n  {\n    h_incoming_bv[counter] = int_list_to_bits_local(values[counter+2], 8);\n  }\n  for (counter = 0; counter < noOutgoingPayments; counter++)\n  {\n    h_outgoing_bv[counter] = int_list_to_bits_local(values[counter+2+noIncomingPayments], 8);\n  }\n\n  cout << \"proof read ... starting verification\" << endl;\n  // Verify the proof\n  bool isVerified = verify_payment_multi_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!!\" << endl;\n    return 0;\n  } else {\n    cout << \"Proof was not verified!!\" << 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_multi\");\n  stringstream verificationKeyFromFile;\n  if (fileIn) {\n     verificationKeyFromFile << fileIn.rdbuf();\n     fileIn.close();\n  }\n  verificationKeyFromFile >> verificationKey_in;\n\n  string proofName = \"proof_multi_\";\n  string proofNameWithId = proofName + argv[1];\n  return verifyProof(verificationKey_in, proofNameWithId);\n}\n\n\n", "meta": {"hexsha": "63b035235b847bea5ed142e51ed91858a2522485", "size": 2474, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/payment_multi_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_multi_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_multi_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": 29.1058823529, "max_line_length": 144, "alphanum_fraction": 0.7409054163, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.29712130790785707}}
{"text": "/**\n * \\file   common.hh\n * \\brief  Headers needed in all headers.\n */\n#ifndef CJ_COMMON_HH_\n#define CJ_COMMON_HH_\n\n#include <algorithm>\n#include <functional>\n#include <complex>\n#include <utility>\n#include <string>\n#include <random>\n#include <iterator>\n#include <type_traits>\n#include <array>\n#include <vector>\n#include <set>\n#include <map>\n#include <unordered_set>\n#include <unordered_map>\n#include <initializer_list>\n#include <memory>\n#include <cmath>\n#include <variant>\n#include <optional>\n#include <boost/container/flat_set.hpp>\n#include <boost/container/flat_map.hpp>\n#include <boost/lexical_cast.hpp>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n#define CONJUNCTION\n#define CONJUNCTION_MAX     0\n#define CONJUNCTION_MIN     0\n#define CONJUNCTION_REV     0\n#define CONJUNCTION_VERSION \"0.0.0\"\n\n#if defined(__GNUC__) // Clang also defines __GNUC__\n# define cj_likely(x)       (__builtin_expect((x), 1))\n# define cj_unlikely(x)     (__builtin_expect((x), 0))\n#else\n# define cj_likely(x)       (x)\n# define cj_unlikely(x)     (x)\n#endif\n\nnamespace cj {\n\n  // Aliases:\n\n  using string = std::string;\n\n  template<typename T>\n  using vector = std::vector<T>;\n\n  template<typename Key0, typename Key1>\n  using pair = std::pair<Key0, Key1>;\n\n  template<typename Key, typename Compare = std::less<Key>>\n  using flat_set = boost::container::flat_set<Key, Compare>;\n\n  template<typename Key, typename Value, typename Compare = std::less<Key>>\n  using flat_map = boost::container::flat_map<Key, Value, Compare>;\n\n  template<typename Key, typename Compare = std::less<Key>>\n  using flat_multiset = boost::container::flat_multiset<Key, Compare>;\n\n  template<typename Key, typename Value, typename Compare = std::less<Key>>\n  using flat_multimap = boost::container::flat_multimap<Key, Value, Compare>;\n\n  template<typename Key, typename Compare = std::less<Key>>\n  using ordered_set = std::set<Key, Compare>;\n\n  template<typename Key, typename Value, typename Compare = std::less<Key>>\n  using ordered_map = std::map<Key, Value, Compare>;\n\n  template<typename Key, typename Compare = std::less<Key>>\n  using ordered_multiset = std::multiset<Key, Compare>;\n\n  template<typename Key, typename Value, typename Compare = std::less<Key>>\n  using ordered_multimap = std::multimap<Key, Value, Compare>;\n\n  template<typename Key>\n  using unordered_set = std::unordered_set<Key>;\n\n  template<typename Key, typename Value>\n  using unordered_map = std::unordered_map<Key, Value>;\n\n  template<typename Key>\n  using unordered_multiset = std::unordered_multiset<Key>;\n\n  template<typename Key, typename Value>\n  using unordered_multimap = std::unordered_multimap<Key, Value>;\n\n  // Eigen's vectors and matrices. Aliases for matrices and vectors based on the 's', 'c', 'd', 'z'\n  // convention established by BLAS:\n\n  template<typename T>\n  using array = Eigen::Array<T, Eigen::Dynamic, 1>;\n\n  template<typename T>\n  using sparse_matrix = Eigen::SparseMatrix<T>;\n\n  template<typename T>\n  using matrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n\n  template<typename T>\n  using colvec = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\n  template<typename T>\n  using rowvec = Eigen::Matrix<T, 1, Eigen::Dynamic>;\n\n  // Aliases for matrices/vectors based on BLAS' convention: 's' = float, 'd' = double,\n  // 'c' = complex<float>, 'z': complex<double>.\n\n  using smatrix = matrix<float>;\n  using scolvec = colvec<float>;\n  using srowvec = rowvec<float>;\n\n  using dmatrix = matrix<double>;\n  using dcolvec = colvec<double>;\n  using drowvec = rowvec<double>;\n\n  using cmatrix = matrix<std::complex<float>>;\n  using ccolvec = colvec<std::complex<float>>;\n  using crowvec = rowvec<std::complex<float>>;\n\n  using zmatrix = matrix<std::complex<double>>;\n  using zcolvec = colvec<std::complex<double>>;\n  using zrowvec = rowvec<std::complex<double>>;\n\n  // Helpers to build eigen objects:\n\n  /**\n   * \\brief Builds an array with an initializer list.\n   */\n  template<typename T>\n  constexpr auto make_array(std::initializer_list<T> const& xs) noexcept -> array<T> {\n    auto a = array<T>(xs.size());\n    auto i = 0u;\n    for (auto const& x : xs) {\n      a(i++) = x;\n    }\n    return a;\n  }\n\n  /**\n   * \\brief Builds a column vector with an initializer list.\n   */\n  template<typename T>\n  constexpr auto make_colvec(std::initializer_list<T> const& xs) noexcept -> colvec<T> {\n    auto v = colvec<T>(xs.size());\n    auto i = 0u;\n    for (auto const& x : xs) {\n      v(i++) = x;\n    }\n    return v;\n  }\n\n  /**\n   * \\brief Builds a row vector with an initializer list.\n   */\n  template<typename T>\n  constexpr auto make_rowvec(std::initializer_list<T> const& xs) noexcept -> rowvec<T> {\n    auto v = rowvec<T>(xs.size());\n    auto i = 0u;\n    for (auto const& x : xs) {\n      v(i++) = x;\n    }\n    return v;\n  }\n\n  /**\n   * \\brief Builds a matrix with an initializer list.\n   */\n  template<typename T>\n  constexpr auto make_matrix(std::initializer_list<std::initializer_list<T>> const& xs) noexcept -> matrix<T> {\n    auto const nrows = xs.size();\n    if (nrows == 0) {\n      return matrix<T>(0, 0);\n    }\n    auto const ncols = xs.begin()->size();\n    auto m = matrix<T>(nrows, ncols);\n    auto r = 0u;\n    for (auto const& row : xs) {\n      auto c = 0u;\n      for (auto const& value : row) {\n        m(r, c++) = value;\n      }\n      ++r;\n    }\n    return m;\n  }\n\n  // Math constants:\n\n  /**\n   * \\brief Natural logarithm of 2.\n   */\n  template<typename T>\n  constexpr T ln2 = T(0.6931471805599453094172321214581765680755L);\n\n  /**\n   * \\brief Square root of 2.\n   */\n  template<typename T>\n  constexpr T sqrt2 = T(1.4142135623730950488016887242096980785696L);\n\n  /**\n   * \\brief Pi. You may have heard about it.\n   */\n  template<typename T>\n  constexpr T pi = T(3.1415926535897932384626433832795028841971L);\n\n  /**\n   * \\brief Euler's number.\n   */\n  template<typename T>\n  constexpr T euler = T(2.7182818284590452353602874713526624977572L);\n\n  /**\n   * \\brief The golden ratio.\n   */\n  template<typename T>\n  constexpr T golden = T(1.6180339887498948482045868343656381177203L);\n\n  // Helpers:\n\n  /**\n   * \\brief Get nth element using std::advance.\n   */\n  template<typename Container>\n  inline auto get(Container const& c, size_t n) -> typename Container::value_type const& {\n    auto it = c.begin();\n    std::advance(it, n);\n    return *it;\n  }\n\n  /**\n   * \\brief Whether a container contains a given element.\n   */\n  template<typename Container>\n  inline auto contains(Container const& c, typename Container::value_type const& elem) -> bool {\n    return c.find(elem) != c.end();\n  }\n\n  /**\n   * \\brief Checks if left <= x <= right.\n   */\n  template<typename T>\n  constexpr auto within_eq(T left, T x, T right) noexcept -> bool {\n    return left <= x && x <= right;\n  }\n\n  /**\n   * \\brief Checks if left < x < right.\n   */\n  template<typename T>\n  constexpr auto within(T left, T x, T right) noexcept -> bool {\n    return left < x && x < right;\n  }\n\n  /**\n   * \\brief Hashes T and combine with a seed. A version of boost's hash_combine using std::hash.\n   */\n  template<typename T>\n  constexpr auto std_hash_combine(size_t& seed, T const& t) noexcept -> void {\n    seed ^= std::hash<T>{}(t) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n  }\n\n  /**\n   * \\brief Hashes a range and combine with a seed. A version of boost's hash_range using std::hash.\n   */\n  template<typename It>\n  constexpr auto std_hash_range(size_t& seed, It fst, It lst) noexcept -> void {\n    for (; fst != lst; ++fst) {\n      using value_type = typename std::iterator_traits<It>::value_type;\n      seed ^= std::hash<value_type>{}(*fst) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n    }\n  }\n\n  template<typename It>\n  constexpr auto std_hash_pair_range(size_t& seed, It fst, It lst) noexcept -> void {\n    for (; fst != lst; ++fst) {\n      std_hash_range(seed, fst->first);\n      std_hash_range(seed, fst->second);\n    }\n  }\n\n} /* end namespace cj */\n\n#endif\n", "meta": {"hexsha": "e33931758d1e07a69aac083dcf80a07c932710b3", "size": 7890, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/cj/common.hh", "max_stars_repo_name": "PhDP/ConjunctionAI", "max_stars_repo_head_hexsha": "542bfe9bd8bb18b438bec48552f4f5099fef4c2e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-02T08:36:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-26T17:16:15.000Z", "max_issues_repo_path": "include/cj/common.hh", "max_issues_repo_name": "PhDP/ConjunctionAI", "max_issues_repo_head_hexsha": "542bfe9bd8bb18b438bec48552f4f5099fef4c2e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/cj/common.hh", "max_forks_repo_name": "PhDP/ConjunctionAI", "max_forks_repo_head_hexsha": "542bfe9bd8bb18b438bec48552f4f5099fef4c2e", "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.9283276451, "max_line_length": 111, "alphanum_fraction": 0.6598225602, "num_tokens": 2122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.29712130790785707}}
{"text": "//\n// Created by joonho on 10.06.19.\n//\n\n#ifndef OLD_RAI_IK_HPP\n#define OLD_RAI_IK_HPP\n\n#include <Eigen/Core>\n#include <Eigen/StdVector>\n\nclass InverseKinematics {\n\n public:\n  InverseKinematics() {\n\n    std::cout << \"Launched the IK constructor!\" << std::endl;\n\n    ///Hard code all the shits\n    PositionBaseToHipInBaseFrame.resize(4);\n    positionHipToThighInHipFrame.resize(4);\n    positionThighToShankInThighFrame.resize(4);\n    positionShankToFootInShankFrame.resize(4);\n    PositionBaseToHAACenterInBaseFrame.resize(4);\n\n    PositionBaseToHipInBaseFrame[0] << 0.277, 0.116, 0.0;\n    PositionBaseToHipInBaseFrame[1] << 0.277, -0.116, 0.0;\n    PositionBaseToHipInBaseFrame[2] << -0.277, 0.116, 0.0;\n    PositionBaseToHipInBaseFrame[3] << -0.277, -0.116, 0.0;\n\n    positionHipToThighInHipFrame[0] << 0.0635, 0.055, 0.0;\n    positionHipToThighInHipFrame[1] << 0.0635, -0.055, 0.0;\n    positionHipToThighInHipFrame[2] << -0.0635, 0.055, 0.0;\n    positionHipToThighInHipFrame[3] << -0.0635, -0.055, 0.0;\n\n    positionThighToShankInThighFrame[0] << 0.0, 0.12205, -0.25;\n    positionThighToShankInThighFrame[1] << 0.0, -0.12205, -0.25;\n    positionThighToShankInThighFrame[2] << 0.0, 0.12205, -0.25;\n    positionThighToShankInThighFrame[3] << 0.0, -0.12205, -0.25;\n\n    positionShankToFootInShankFrame[0] << 0.1, -0.02, -0.298;\n    positionShankToFootInShankFrame[1] << 0.1, 0.02, -0.298;\n    positionShankToFootInShankFrame[2] << -0.1, -0.02, -0.298;\n    positionShankToFootInShankFrame[3] << -0.1, 0.02, -0.298;\n\n    for (size_t i = 0; i < 4; i++) {\n      PositionBaseToHAACenterInBaseFrame[i] = PositionBaseToHipInBaseFrame[i];\n      PositionBaseToHAACenterInBaseFrame[i][0] += positionHipToThighInHipFrame[i][0];\n      d_[i] = positionHipToThighInHipFrame[i][1];\n      d_[i] += positionThighToShankInThighFrame[i][1];\n      d_[i] += positionShankToFootInShankFrame[i][1];\n    }\n\n    a1_squared_ = positionThighToShankInThighFrame[0][0] * positionThighToShankInThighFrame[0][0]\n        + positionThighToShankInThighFrame[0][2] * positionThighToShankInThighFrame[0][2];\n    a2_squared_ = positionShankToFootInShankFrame[0][0] * positionShankToFootInShankFrame[0][0]\n        + positionShankToFootInShankFrame[0][2] * positionShankToFootInShankFrame[0][2];\n\n    minReach_SP = std::abs(sqrt(a1_squared_) - sqrt(a2_squared_)) + 0.1;\n    maxReach_SP = sqrt(a1_squared_) + sqrt(a2_squared_) - 0.05;\n\n    minReach = std::sqrt(d_[0] * d_[0] + minReach_SP * minReach_SP);\n    maxReach = sqrt(d_[0] * d_[0] + maxReach_SP * maxReach_SP);\n\n    KFEOffset_ = atan2(0.1, 0.298);\n  }\n\n  ~InverseKinematics() = default;\n\n  bool solveIK(\n      Eigen::Vector3d &legJoints,\n      const Eigen::Vector3d &positionBaseToFootInBaseFrame,\n      size_t limb) {\n\n    Eigen::Vector3d\n        positionHipToFootInBaseFrame = positionBaseToFootInBaseFrame - PositionBaseToHAACenterInBaseFrame[limb];\n\n    const double d = d_[limb];\n    const double dSquared = d * d;\n\n    ///Rescaling target\n\n    double reach = positionHipToFootInBaseFrame.norm();\n    double positionYzSquared = positionHipToFootInBaseFrame.tail(2).squaredNorm();\n    if (reach > maxReach) {\n      positionHipToFootInBaseFrame /= reach;\n      positionHipToFootInBaseFrame *= maxReach;\n      positionYzSquared = positionHipToFootInBaseFrame.tail(2).squaredNorm();\n    }\n\n    if (positionYzSquared < minReach * minReach) {\n      positionHipToFootInBaseFrame[1] = d;\n      positionHipToFootInBaseFrame[2] = 0.0;\n      positionYzSquared = d * d;\n\n      double reach_SP = std::abs(positionHipToFootInBaseFrame[0]);\n\n      if (reach_SP > maxReach_SP) {\n        positionHipToFootInBaseFrame[0] /= reach_SP;\n        positionHipToFootInBaseFrame[0] *= maxReach_SP;\n      } else if (reach_SP < minReach_SP) {\n        positionHipToFootInBaseFrame[0] /= reach_SP;\n        positionHipToFootInBaseFrame[0] *= minReach_SP;\n      }\n\n    }\n\n    double rSquared = positionYzSquared - dSquared;\n    const double r = std::sqrt(rSquared);\n    const double delta = std::atan2(positionHipToFootInBaseFrame.y(),\n                                    -positionHipToFootInBaseFrame.z());\n    const double beta = std::atan2(r, d);\n    const double qHAA = beta + delta - M_PI_2;\n    legJoints[0] = qHAA;\n\n    const double l_squared = (rSquared + positionHipToFootInBaseFrame[0] * positionHipToFootInBaseFrame[0]);\n    const double phi1 = std::acos((a1_squared_ + l_squared - a2_squared_) * 0.5 / sqrt(a1_squared_ * l_squared));\n    const double phi2 = std::acos((a2_squared_ + l_squared - a1_squared_) * 0.5 / sqrt(a2_squared_ * l_squared));\n\n    double qKFE = phi1 + phi2 - KFEOffset_;\n\n    if (limb < 2) {\n      qKFE *= -1.0;\n    }\n    legJoints[2] = qKFE;\n\n    double theta_prime = atan2(positionHipToFootInBaseFrame[0], r);\n    double qHFE = phi1 - theta_prime;\n\n    if (limb > 1) {\n      qHFE = -phi1 - theta_prime;\n    }\n    legJoints[1] = qHFE;\n    return true;\n  }\n\n  double d_[4];\n\n  double a1_squared_;\n  double a2_squared_;\n  double KFEOffset_;\n  double minReach;\n  double maxReach;\n  double minReach_SP;\n  double maxReach_SP;\n\n  std::vector<Eigen::Vector3d> positionHipToThighInHipFrame;\n  std::vector<Eigen::Vector3d> positionThighToShankInThighFrame;\n  std::vector<Eigen::Vector3d> positionShankToFootInShankFrame;\n  std::vector<Eigen::Vector3d> PositionBaseToHipInBaseFrame;\n  std::vector<Eigen::Vector3d> PositionBaseToHAACenterInBaseFrame;\n\n};\n\n#endif //OLD_RAI_IK_HPP\n", "meta": {"hexsha": "934d008438e9bfc48253bec8fb885e6fb0e2a30e", "size": 5393, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cerberus_anymal_control/include/cerberus_anymal_control/utils/IK.hpp", "max_stars_repo_name": "heuristicus/cerberus_anymal_locomotion", "max_stars_repo_head_hexsha": "75f53e9a0ea267f62657bd90b9db95a884cd5ccb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2020-04-21T11:37:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T15:30:20.000Z", "max_issues_repo_path": "cerberus_anymal_control/include/cerberus_anymal_control/utils/IK.hpp", "max_issues_repo_name": "heuristicus/cerberus_anymal_locomotion", "max_issues_repo_head_hexsha": "75f53e9a0ea267f62657bd90b9db95a884cd5ccb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-04-22T13:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-12T17:20:18.000Z", "max_forks_repo_path": "cerberus_anymal_control/include/cerberus_anymal_control/utils/IK.hpp", "max_forks_repo_name": "heuristicus/cerberus_anymal_locomotion", "max_forks_repo_head_hexsha": "75f53e9a0ea267f62657bd90b9db95a884cd5ccb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-04-03T07:50:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T12:02:11.000Z", "avg_line_length": 34.7935483871, "max_line_length": 113, "alphanum_fraction": 0.6905247543, "num_tokens": 1840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.3665897363221598, "lm_q1q2_score": 0.29711324606783374}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2002-2012 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#ifndef ALGORITHM_3_ERROR_ESTIMATOR_EE\n#define ALGORITHM_3_ERROR_ESTIMATOR_EE\n\n#include <algorithm>\n#include <iostream>\n#include <utility>\n#include <vector>\n\n#include <boost/timer/timer.hpp>\n#include <boost/fusion/include/at_c.hpp>\n\n#include \"algorithm/newton_bridge.hh\"\n#include \"algorithm/adaptationStrategy.hh\"\n#include \"algorithm/errorDistribution.hh\"\n#include \"linalg/jacobiPreconditioner.hh\"\n#include \"fem/forEach.hh\"\n#include \"fem/hierarchicErrorEstimator.hh\"\n#include \"fem/variables.hh\"\n#include \"utilities/enums.hh\"\n#include \"errorEstimationTraits.hh\"\n#include \"lagrangeLinearization.hh\"\n\n// forward declarations\nnamespace Dune\n{\n  struct InverseOperatorResult;\n  template <class,int> class FieldVector;\n}\n\nnamespace Kaskade\n{\n  struct Dummy{};\n\n  template <template <class,class,class,bool> class Functional, class VariableSetDescription, class ExtensionVariableSetDescription, class ExtensionSpace,\n  class NormFunctional, template <class> class RefinementStrategy = Adaptivity::ErrorEquilibration, bool lump=false, int components=1, class ReferenceSolution = Dummy, class ReferenceOperator=Dummy>\n  class YetAnotherHBErrorEstimator : public ErrorEstimatorBase<VariableSetDescription,typename ErrorDistribution<NormFunctional,ExtensionVariableSetDescription>::AnsatzVars::VariableSet,ExtensionSpace,RefinementStrategy>\n  {\n    template <class AnsatzVars, class TestVars, class OriginVars> using EstimatorFunctional = Functional<AnsatzVars,TestVars,OriginVars,false>;\n    template <class AnsatzVars, class TestVars, class OriginVars> using LumpedFunctional = Functional<AnsatzVars,TestVars,OriginVars,lump>;\n    typedef ErrorEstimationTraits<EstimatorFunctional,VariableSetDescription,ExtensionVariableSetDescription> Traits;\n    typedef ErrorEstimationTraits<LumpedFunctional,VariableSetDescription,ExtensionVariableSetDescription> LumpedTraits;\n    typedef ErrorEstimatorBase<VariableSetDescription,typename ErrorDistribution<NormFunctional,ExtensionVariableSetDescription>::AnsatzVars::VariableSet,ExtensionSpace,RefinementStrategy> Base;\n    using Base::squaredError;\n    using Base::mde;\n    using Base::errorDistribution;\n    using Base::extensionSpace;\n  public:\n    // assemblers\n\n    typedef typename Traits::Scalar Scalar;\n    typedef typename VariableSetDescription::Grid Grid;\n    static constexpr int dim = VariableSetDescription::Grid::dimension;\n\n    typedef typename ExtensionVariableSetDescription::GridView::template Codim<0>::Iterator CellIterator;\n    typedef typename ExtensionVariableSetDescription::GridView::template Codim<0>::Entity Cell;\n    typedef ErrorDistribution<NormFunctional,ExtensionVariableSetDescription> EnergyError;\n    typedef typename EnergyError::AnsatzVars::VariableSet ErrorRepresentation;\n\n\n    YetAnotherHBErrorEstimator(NormFunctional& normFunctional_, VariableSetDescription& variableSetDescription_, ExtensionVariableSetDescription& extensionVariableSetDescription_,\n        ExtensionSpace& extensionSpace_, Scalar fraction=0.7, bool verbose_=false)\n    : Base(extensionSpace_,fraction,verbose), normFunctional(normFunctional_), variableSetDescription(variableSetDescription_), extensionVariableSetDescription(extensionVariableSetDescription_),\n      squaredFraction(fraction*fraction), verbose(verbose_)\n      {\n        ass_EE.reset(new typename LumpedTraits::Assembler_EE(extensionVariableSetDescription.spaces));\n        ass_HE.reset(new typename Traits::Assembler_HE(variableSetDescription.spaces));\n        ass_EH.reset(new typename Traits::Assembler_EH(extensionVariableSetDescription.spaces));\n        ass_HH.reset(new typename Traits::Assembler_HH(variableSetDescription.spaces));\n      }\n\n    virtual ~YetAnotherHBErrorEstimator(){}\n\n    void operator()(AbstractLinearization const& lin, AbstractFunctionSpaceElement const& x_, AbstractFunctionSpaceElement const& dx_, int step, AbstractFunctionSpaceElement const&)\n    {\n      boost::timer::cpu_timer overallTimer;\n      using boost::fusion::at_c;\n      if(verbose) std::cout << \"ERROR ESTIMATOR: Start.\" << std::endl;\n      Bridge::Vector<typename Traits::VarSet> const& xl = dynamic_cast<const Bridge::Vector<typename Traits::VarSet>&>(x_);\n      computeError(xl.get());\n      Bridge::Vector<typename Traits::ExtensionVarSet> xe(extensionVariableSetDescription);\n      boost::timer::cpu_timer atimer;\n      assembleAt(xl,xe);\n      if(verbose) std::cout << \"ERROR ESTIMATOR: assembly time: \" << boost::timer::format(atimer.elapsed())  << std::endl;\n      Bridge::Vector<typename Traits::VarSet> const& dxl = dynamic_cast<const Bridge::Vector<typename Traits::VarSet>&>(dx_);\n\n      /***************************************************************************************/\n      // state equation -> DLY\n      typename Traits::A_HH a_HH(*ass_HH,false);\n      typename Traits::A_HE a_HE(*ass_HE,false);\n      typename LumpedTraits::A_EE a_EE(*ass_EE,false);\n      typename Traits::B_HH b_HH(*ass_HH,false);\n      typename Traits::B_HE b_HE(*ass_HE,false);\n      typename Traits::B_EH b_EH(*ass_EH,false);\n      typename LumpedTraits::B_EE b_EE(*ass_EE,false);\n\n      typename Traits::ExtensionVectorP rhsPE(ass_EE->template rhs<Traits::adjointId,Traits::adjointId+1>());\n      rhsPE *= -1.0;\n      typename Traits::VectorY dy(at_c<Traits::stateId>(dxl.get().data).coefficients()), solYH = dy; solYH *= 0;\n      typename Traits::VectorU du(at_c<Traits::controlId>(dxl.get().data).coefficients());\n      typename Traits::ExtensionVectorY solYE(Traits::ExtensionVectorY_Initializer::init(extensionVariableSetDescription));\n\n      b_HE.applyscaleadd(-1.0,du,rhsPE);\n      a_HE.applyscaleadd(-1.0,dy,rhsPE);\n\n      JacobiPreconditionerForTriplets<Scalar,typename LumpedTraits::ExtensionVectorY,typename LumpedTraits::ExtensionVectorP> jacobi(a_EE);\n      jacobi.apply(solYE,rhsPE);\n\n\n      // error in adjoint equation\n      typename Traits::Lyy_HH lyy_HH(*ass_HH,false);\n      typename Traits::Lyy_HE lyy_HE(*ass_HE,false);\n      typename Traits::Lyy_EH lyy_EH(*ass_EH,false);\n      typename LumpedTraits::Lyy_EE lyy_EE(*ass_EE,false);\n      TransposedOperator<typename Traits::A_HE> at_EH(a_HE);//(*ass_EH,false);\n\n      typename Traits::VectorY rhsYH(ass_HH->template rhs<Traits::stateId,Traits::stateId+1>());\n      rhsYH *= -1.0;\n      typename Traits::ExtensionVectorY rhsYE(ass_EE->template rhs<Traits::stateId, Traits::stateId+1>());\n      rhsYE *= -1.0;\n\n      lyy_HH.applyscaleadd(-1.0,dy,rhsYH);\n      lyy_HE.applyscaleadd(-1.0,dy,rhsYE);\n      lyy_EH.applyscaleadd(-1.0,solYE,rhsYH);\n      lyy_EE.applyscaleadd(-1.0,solYE,rhsYE);\n\n      typename Traits::ExtensionVectorP solPE(Traits::ExtensionVectorP_Initializer::init(extensionVariableSetDescription));\n      typename Traits::VectorP solPH(Traits::VectorP_Initializer::init(variableSetDescription));\n\n      jacobi.apply(solPE,rhsYE);\n      at_EH.applyscaleadd(-1.0,solPE,rhsYH);\n\n      boost::timer::cpu_timer mgTimer;\n      MultiGridSolver<Grid,components>( a_HH, boost::fusion::at_c<0>(ass_HH->spaces())->gridManager().grid(),\n                                        typename MultiGridSolver<Grid,components>::Parameter(mgSteps,mgSmoothingSteps,relativeAccuracy), true ).apply(at_c<0>(solPH.data),\n                                                                                                                                                at_c<0>(rhsYH.data));\n      std::cout << \"mg: \" << boost::timer::format(mgTimer.elapsed()) << std::endl;\n\n      // variational equality\n      TransposedOperator<typename Traits::B_HH> bt_HH(b_HH);\n      TransposedOperator<typename Traits::B_EH> bt_HE(b_EH);\n      TransposedOperator<typename Traits::B_HE> bt_EH(b_HE);\n      TransposedOperator<typename LumpedTraits::B_EE> bt_EE(b_EE);\n      typename Traits::Luu_HH luu_HH(*ass_HH,false);\n      typename Traits::Luu_EH luu_EH(*ass_EH,false);\n      typename Traits::Luu_HE luu_HE(*ass_HE,false);\n      typename LumpedTraits::Luu_EE luu_EE(*ass_EE,false);\n\n      typename Traits::VectorU rhsUH(ass_HH->template rhs<Traits::controlId,Traits::controlId+1>());\n      rhsUH *= -1;\n      typename Traits::ExtensionVectorU rhsUE(ass_EE->template rhs<Traits::controlId,Traits::controlId+1>());\n      rhsUE *= -1;\n\n      luu_HH.applyscaleadd(-1.0,du,rhsUH);\n      luu_HE.applyscaleadd(-1.0,du,rhsUE);\n\n      bt_HH.applyscaleadd(-1.0,solPH,rhsUH);\n      bt_HE.applyscaleadd(-1.0,solPH,rhsUE);\n      bt_EH.applyscaleadd(-1.0,solPE,rhsUH);\n      bt_EE.applyscaleadd(-1.0,solPE,rhsUE);\n\n      typename Traits::VectorU solUH(Traits::VectorU_Initializer::init(variableSetDescription));\n      typename Traits::ExtensionVectorU solUE(Traits::ExtensionVectorU_Initializer::init(extensionVariableSetDescription));\n\n      JacobiPreconditionerForTriplets<Scalar,typename LumpedTraits::ExtensionVectorU,typename LumpedTraits::ExtensionVectorU>(luu_EE).apply(solUE,rhsUE);\n      luu_EH.applyscaleadd(-1.0,solUE,rhsUH);\n      boost::timer::cpu_timer chebTimer;\n      ChebyshevPreconditioner<typename Traits::Luu_HH> cheb(luu_HH,chebySteps);\n      cheb.initForMassMatrix_TetrahedralQ1Elements();\n      cheb.apply(solUH,rhsUH);\n      std::cout << \"cheb: \" << boost::timer::format(chebTimer.elapsed()) << std::endl;\n\n      typename ExtensionVariableSetDescription::VariableSet errorEstimate_E(extensionVariableSetDescription);\n      typename VariableSetDescription::VariableSet errorEstimate_H(variableSetDescription);\n      solYH *= 0.0; // DLY in state equation -> no error transport into space of linear finite elements\n      at_c<Traits::stateId>(errorEstimate_H.data) = at_c<0>(solYH.data);\n      at_c<Traits::controlId>(errorEstimate_H.data) = at_c<0>(solUH.data);\n      at_c<Traits::stateId>(errorEstimate_E.data) = at_c<0>(solYE.data);\n      at_c<Traits::controlId>(errorEstimate_E.data) = at_c<0>(solUE.data);\n//      std::string savefilename = createFileName(\"estimate_E\",\".vtu\",false);\n//      std::cout << \"Error estimator: writing estimates\" << std::endl;\n//      writeVTKFile(extensionVariableSetDescription.gridView,errorEstimate_E,savefilename,IoOptions(),2);\n//      std::cout << \"Error estimator: writing lower order estimates\" << std::endl;\n//      writeVTKFile(variableSetDescription.gridView,errorEstimate_H,savefilename,IoOptions(),1);\n      /***************************************************************************************/\n      // Transfer error indicators to cells.\n      auto const& is = extensionSpace.gridManager().grid().leafIndexSet();\n      errorDistribution.clear();\n      errorDistribution.resize(is.size(0),std::make_pair(0.0,0));\n\n      EnergyError energyError(normFunctional,xl.get(),errorEstimate_H,errorEstimate_E);\n      energyError.considerStateVariable(true);\n      energyError.considerControlVariable(true);\n      energyError.considerAdjointVariable(false);\n      typedef VariationalFunctionalAssembler<LinearizationAt<EnergyError> > EnergyErrorAssembler;\n      EnergyErrorAssembler eeAssembler(extensionSpace.gridManager(), energyError.getSpaces());\n\n      eeAssembler.assemble(linearization(energyError,xl.get()), EnergyErrorAssembler::RHS);\n      typename EnergyError::ErrorVector distError( eeAssembler.rhs() );\n      mde.reset(new ErrorRepresentation(energyError.getVariableSetDescription()) );\n      *mde = distError;\n\n//      if(verbose)\n//      {\n//        std::string name = \"errorDistribution_\";\n//        name += std::to_string(step);\n//        writeVTKFile(mde->descriptions.gridView,*mde,name);\n//      }\n\n      CellIterator cend = extensionVariableSetDescription.gridView.template end<0>();\n      for (CellIterator ci=extensionVariableSetDescription.gridView.template begin<0>(); ci!=cend; ++ci)\n        errorDistribution[is.index(*ci)] = std::make_pair( fabs(boost::fusion::at_c<0>(mde->data).value(*ci,Dune::FieldVector<Scalar,dim>(0.3))) , is.index(*ci));\n\n      squaredError = std::accumulate(errorDistribution.begin(), errorDistribution.end(), 0.0, ErrorEstimator_Detail::add);\n\n      if(verbose) std::cout << \"overall error estimation time: \" << boost::timer::format(overallTimer.elapsed()) << std::endl;\n    }\n\n    template <typename... Args>\n    void initFunctionals(const Args&... args)\n    {\n      F_HH.reset(new typename Traits::Functional_HH(args...));\n      F_HE.reset(new typename Traits::Functional_HE(args...));\n    }\n    \n    template <typename... Args>\n    void initExtensionFunctionals(const Args&... args)\n    {\n      F_EH.reset(new typename Traits::Functional_EH(args...));\n      F_EE.reset(new typename LumpedTraits::Functional_EE(args...));\n    }\n\n    void setReference(ReferenceOperator const& Aref, ReferenceSolution const& ref, typename Traits::Vector& refcv)\n    {\n      referenceSolution = &ref;\n      referenceOperator = &Aref;\n      referenceCoeffVec = &refcv;\n    }\n\n    void computeError(typename Traits::VarSet const& x)\n    {\n      if(referenceSolution == nullptr) return;\n      ReferenceSolution tmp(*referenceSolution);\n      interpolateGloballyFromFunctor<PlainAverage>(boost::fusion::at_c<0>(tmp.data),[&x](Cell const& cell, Dune::FieldVector<Scalar,dim> const& xLocal)\n      {\n        return boost::fusion::at_c<0>(x.data).value(cell.geometry().global(xLocal));\n      });\n\n      interpolateGloballyFromFunctor<PlainAverage>(boost::fusion::at_c<1>(tmp.data),[&x](Cell const& cell, Dune::FieldVector<Scalar,dim> const& xLocal)\n      {\n        return boost::fusion::at_c<1>(x.data).value(cell.geometry().global(xLocal));\n      });\n//      interpolateGloballyWeak<PlainAverage>(boost::fusion::at_c<2>(tmp.data),boost::fusion::at_c<2>(x.data));\n      tmp -= *referenceSolution;\n\n      boost::fusion::at_c<0>(referenceCoeffVec->data) = boost::fusion::at_c<0>(tmp.data).coefficients();\n      boost::fusion::at_c<1>(referenceCoeffVec->data) = boost::fusion::at_c<1>(tmp.data).coefficients();\n      // boost::fusion::at_c<2>(referenceCoeffVec->data) = boost::fusion::at_c<2>(tmp.data).coefficients();\n\n      auto tmp2 = *referenceCoeffVec;\n      referenceOperator->apply(*referenceCoeffVec,tmp2);\n      std::cout << \"REAL ERROR: \" << (*referenceCoeffVec)*tmp2 << std::endl;\n    }\n\n  private:\n    void assembleAt(const Bridge::Vector<typename Traits::VarSet>& xl, const Bridge::Vector<typename Traits::ExtensionVarSet>& xe)\n    {\n      ass_HH->assemble(linearization(*F_HH,xl.get()));\n      ass_HE->assemble(linearization(*F_HE,xl.get()));\n      ass_EH->assemble(linearization(*F_EH,xe.get()));\n      ass_EE->assemble(linearization(*F_EE,xe.get()));\n    }\n\n    std::unique_ptr<typename Traits::Functional_HH> F_HH;\n    std::unique_ptr<typename Traits::Functional_HE> F_HE;\n    std::unique_ptr<typename Traits::Functional_EH> F_EH;\n    std::unique_ptr<typename LumpedTraits::Functional_EE> F_EE;\n    std::unique_ptr<typename Traits::Assembler_HH> ass_HH;\n    //typename Traits::Assembler_HH* ass_HH;\n    std::unique_ptr<typename Traits::Assembler_HE> ass_HE;\n    std::unique_ptr<typename Traits::Assembler_EH> ass_EH;\n    std::unique_ptr<typename LumpedTraits::Assembler_EE> ass_EE;\n    NormFunctional& normFunctional;\n    VariableSetDescription& variableSetDescription;\n    ExtensionVariableSetDescription& extensionVariableSetDescription;\n    Scalar squaredFraction;\n    bool verbose;\n    size_t chebySteps = 30, mgSteps = 25, mgSmoothingSteps = 20;\n    Scalar relativeAccuracy = 1e-3;\n    ReferenceSolution const* referenceSolution = nullptr;\n    ReferenceOperator const* referenceOperator = nullptr;\n    typename Traits::Vector* referenceCoeffVec = nullptr;\n    //std::function<Scalar(typename Traits::VarSet)> compareError;\n  };\n\n  template <template <class,class,class,bool> class Functional, class VariableSetDescription, class ExtensionVariableSetDescription, class ExtensionSpace,\n  class NormFunctional, template <class> class RefinementStrategy = Adaptivity::ErrorEquilibration, bool lump=false, int components=1>\n  class YetAnotherHBErrorEstimator_Elasticity : public ErrorEstimatorBase<VariableSetDescription,typename ErrorDistribution<NormFunctional,ExtensionVariableSetDescription>::AnsatzVars::VariableSet,ExtensionSpace,RefinementStrategy>\n  {\n    template <class AnsatzVars, class TestVars, class OriginVars> using EstimatorFunctional = Functional<AnsatzVars,TestVars,OriginVars,false>;\n    template <class AnsatzVars, class TestVars, class OriginVars> using LumpedFunctional = Functional<AnsatzVars,TestVars,OriginVars,lump>;\n    typedef ErrorEstimationTraits<EstimatorFunctional,VariableSetDescription,ExtensionVariableSetDescription> Traits;\n    typedef ErrorEstimationTraits<LumpedFunctional,VariableSetDescription,ExtensionVariableSetDescription> LumpedTraits;\n    typedef ErrorEstimatorBase<VariableSetDescription,typename ErrorDistribution<NormFunctional,ExtensionVariableSetDescription>::AnsatzVars::VariableSet,ExtensionSpace,RefinementStrategy> Base;\n    using Base::squaredError;\n    using Base::mde;\n    using Base::errorDistribution;\n    using Base::extensionSpace;\n  public:\n    // assemblers\n\n    typedef typename Traits::Scalar Scalar;\n    typedef typename VariableSetDescription::Grid Grid;\n    static constexpr int dim = VariableSetDescription::Grid::dimension;\n\n    typedef typename ExtensionVariableSetDescription::GridView::template Codim<0>::Iterator CellIterator;\n    typedef typename ExtensionVariableSetDescription::GridView::template Codim<0>::Entity Cell;\n    typedef ErrorDistribution<NormFunctional,ExtensionVariableSetDescription> EnergyError;\n    typedef typename EnergyError::AnsatzVars::VariableSet ErrorRepresentation;\n\n\n    YetAnotherHBErrorEstimator_Elasticity(NormFunctional& normFunctional_, VariableSetDescription& variableSetDescription_, ExtensionVariableSetDescription& extensionVariableSetDescription_,\n        ExtensionSpace& extensionSpace_, Scalar fraction=0.7, bool verbose_=false)\n    : Base(extensionSpace_,fraction,verbose), normFunctional(normFunctional_), variableSetDescription(variableSetDescription_), extensionVariableSetDescription(extensionVariableSetDescription_),\n      squaredFraction(fraction*fraction), verbose(verbose_)\n      {\n        ass_EE.reset(new typename LumpedTraits::Assembler_EE(extensionVariableSetDescription.spaces));\n        ass_HE.reset(new typename Traits::Assembler_HE(variableSetDescription.spaces));\n        ass_EH.reset(new typename Traits::Assembler_EH(extensionVariableSetDescription.spaces));\n        ass_HH.reset(new typename Traits::Assembler_HH(variableSetDescription.spaces));\n      }\n\n    virtual ~YetAnotherHBErrorEstimator_Elasticity(){}\n\n    void operator()(AbstractLinearization const& lin, AbstractFunctionSpaceElement const& x_, AbstractFunctionSpaceElement const& dx_, int step, AbstractFunctionSpaceElement const&)\n    {\n      boost::timer::cpu_timer overallTimer;\n      using boost::fusion::at_c;\n      if(verbose) std::cout << \"ERROR ESTIMATOR: Start.\" << std::endl;\n      Bridge::Vector<typename Traits::VarSet> const& xl = dynamic_cast<const Bridge::Vector<typename Traits::VarSet>&>(x_);\n      Bridge::Vector<typename Traits::ExtensionVarSet> xe(extensionVariableSetDescription);\n      boost::timer::cpu_timer atimer;\n      assembleAt(xl,xe);\n      if(verbose) std::cout << \"ERROR ESTIMATOR: assembly time: \" << boost::timer::format(atimer.elapsed())  << std::endl;\n      Bridge::Vector<typename Traits::VarSet> const& dxl = dynamic_cast<const Bridge::Vector<typename Traits::VarSet>&>(dx_);\n\n      /***************************************************************************************/\n      // state equation -> DLY\n      typename Traits::A_HH a_HH(*ass_HH,false);\n      typename Traits::A_HE a_HE(*ass_HE,false);\n      typename LumpedTraits::A_EE a_EE(*ass_EE,false);\n      typename Traits::B_HH b_HH(*ass_HH,false);\n      typename Traits::B_HE b_HE(*ass_HE,false);\n      typename Traits::B_EH b_EH(*ass_EH,false);\n      typename LumpedTraits::B_EE b_EE(*ass_EE,false);\n\n      typename Traits::ExtensionVectorP rhsPE(ass_EE->template rhs<Traits::adjointId,Traits::adjointId+1>());\n      rhsPE *= -1.0;\n      typename Traits::VectorY dy(at_c<Traits::stateId>(dxl.get().data).coefficients()), solYH = dy; solYH *= 0;\n      typename Traits::VectorU du(at_c<Traits::controlId>(dxl.get().data).coefficients());\n      typename Traits::ExtensionVectorY solYE(Traits::ExtensionVectorY_Initializer::init(extensionVariableSetDescription));\n\n      b_HE.applyscaleadd(-1.0,du,rhsPE);\n      a_HE.applyscaleadd(-1.0,dy,rhsPE);\n\n      JacobiPreconditionerForTriplets<Scalar,typename LumpedTraits::ExtensionVectorY,typename LumpedTraits::ExtensionVectorP> jacobi(a_EE);\n      jacobi.apply(solYE,rhsPE);\n\n\n      // error in adjoint equation\n      typename Traits::Lyy_HH lyy_HH(*ass_HH,false);\n      typename Traits::Lyy_HE lyy_HE(*ass_HE,false);\n      typename Traits::Lyy_EH lyy_EH(*ass_EH,false);\n      typename LumpedTraits::Lyy_EE lyy_EE(*ass_EE,false);\n      typename Traits::Luy_HH luy_HH(*ass_HH,false);\n      typename Traits::Luy_HE luy_HE(*ass_HE,false);\n      typename Traits::Luy_EH luy_EH(*ass_EH,false);\n      typename LumpedTraits::Luy_EE luy_EE(*ass_EE,false);\n      TransposedOperator<typename Traits::Luy_HH> lyu_HH(luy_HH);\n      TransposedOperator<typename Traits::Luy_EH> lyu_HE(luy_EH);\n//      typename Traits::Lyu_HH lyu_HH(*ass_HH,false);\n//      typename Traits::Lyu_HE lyu_HE(*ass_HE,false);\n      TransposedOperator<typename Traits::A_HE> at_EH(a_HE);//(*ass_EH,false);\n\n      typename Traits::VectorY rhsYH(ass_HH->template rhs<Traits::stateId,Traits::stateId+1>());\n      rhsYH *= -1.0;\n      typename Traits::ExtensionVectorY rhsYE(ass_EE->template rhs<Traits::stateId, Traits::stateId+1>());\n      rhsYE *= -1.0;\n\n      lyy_HH.applyscaleadd(-1.0,dy,rhsYH);\n      lyy_HE.applyscaleadd(-1.0,dy,rhsYE);\n      lyy_EH.applyscaleadd(-1.0,solYE,rhsYH);\n      lyy_EE.applyscaleadd(-1.0,solYE,rhsYE);\n      lyu_HH.applyscaleadd(-1.0,du,rhsYH);\n      lyu_HE.applyscaleadd(-1.0,du,rhsYE);\n\n      typename Traits::ExtensionVectorP solPE(Traits::ExtensionVectorP_Initializer::init(extensionVariableSetDescription));\n      typename Traits::VectorP solPH(Traits::VectorP_Initializer::init(variableSetDescription));\n\n      jacobi.apply(solPE,rhsYE);\n      at_EH.applyscaleadd(-1.0,solPE,rhsYH);\n\n      boost::timer::cpu_timer mgTimer;\n      MultiGridSolver<Grid,components>( a_HH, boost::fusion::at_c<0>(ass_HH->spaces())->gridManager().grid(),\n                                        typename MultiGridSolver<Grid,components>::Parameter(mgSteps,mgSmoothingSteps,relativeAccuracy), true ).apply(at_c<0>(solPH.data),\n                                                                                                                                                at_c<0>(rhsYH.data));\n      std::cout << \"mg: \" << boost::timer::format(mgTimer.elapsed()) << std::endl;\n\n\n      // variational equality\n      TransposedOperator<typename Traits::B_HH> bt_HH(b_HH);\n      TransposedOperator<typename Traits::B_EH> bt_HE(b_EH);\n      TransposedOperator<typename Traits::B_HE> bt_EH(b_HE);\n      TransposedOperator<typename LumpedTraits::B_EE> bt_EE(b_EE);\n      typename Traits::Luu_HH luu_HH(*ass_HH,false);\n      typename Traits::Luu_EH luu_EH(*ass_EH,false);\n      typename Traits::Luu_HE luu_HE(*ass_HE,false);\n      typename LumpedTraits::Luu_EE luu_EE(*ass_EE,false);\n\n      typename Traits::VectorU rhsUH(ass_HH->template rhs<Traits::controlId,Traits::controlId+1>());\n      rhsUH *= -1;\n      typename Traits::ExtensionVectorU rhsUE(ass_EE->template rhs<Traits::controlId,Traits::controlId+1>());\n      rhsUE *= -1;\n\n      luu_HH.applyscaleadd(-1.0,du,rhsUH);\n      luu_HE.applyscaleadd(-1.0,du,rhsUE);\n\n      bt_HH.applyscaleadd(-1.0,solPH,rhsUH);\n      bt_HE.applyscaleadd(-1.0,solPH,rhsUE);\n      bt_EH.applyscaleadd(-1.0,solPE,rhsUH);\n      bt_EE.applyscaleadd(-1.0,solPE,rhsUE);\n\n      luy_HH.applyscaleadd(-1.0,dy,rhsUH);\n      luy_HE.applyscaleadd(-1.0,dy,rhsUE);\n      luy_EH.applyscaleadd(-1.0,solYE,rhsUH);\n      luy_EE.applyscaleadd(-1.0,solYE,rhsUE);\n\n      typename Traits::VectorU solUH(Traits::VectorU_Initializer::init(variableSetDescription));\n      typename Traits::ExtensionVectorU solUE(Traits::ExtensionVectorU_Initializer::init(extensionVariableSetDescription));\n\n      JacobiPreconditionerForTriplets<Scalar,typename LumpedTraits::ExtensionVectorU,typename LumpedTraits::ExtensionVectorU>(luu_EE).apply(solUE,rhsUE);\n      luu_EH.applyscaleadd(-1.0,solUE,rhsUH);\n      boost::timer::cpu_timer chebTimer;\n      ChebyshevPreconditioner<typename Traits::Luu_HH> cheb(luu_HH,chebySteps);\n      cheb.initForMassMatrix_TetrahedralQ1Elements();\n      cheb.apply(solUH,rhsUH);\n      std::cout << \"cheb: \" << boost::timer::format(chebTimer.elapsed()) << std::endl;\n\n      typename ExtensionVariableSetDescription::VariableSet errorEstimate_E(extensionVariableSetDescription);\n      typename VariableSetDescription::VariableSet errorEstimate_H(variableSetDescription);\n      solYH *= 0.0; // DLY in state equation -> no error transport into space of linear finite elements\n      at_c<Traits::stateId>(errorEstimate_H.data) = at_c<0>(solYH.data);\n      at_c<Traits::controlId>(errorEstimate_H.data) = at_c<0>(solUH.data);\n      at_c<Traits::stateId>(errorEstimate_E.data) = at_c<0>(solYE.data);\n      at_c<Traits::controlId>(errorEstimate_E.data) = at_c<0>(solUE.data);\n//      std::string savefilename = createFileName(\"estimate_E\",\".vtu\",false);\n//      std::cout << \"Error estimator: writing estimates\" << std::endl;\n//      writeVTKFile(extensionVariableSetDescription.gridView,errorEstimate_E,savefilename,IoOptions(),2);\n//      std::cout << \"Error estimator: writing lower order estimates\" << std::endl;\n//      writeVTKFile(variableSetDescription.gridView,errorEstimate_H,savefilename,IoOptions(),1);\n      /***************************************************************************************/\n      // Transfer error indicators to cells.\n      auto const& is = extensionSpace.gridManager().grid().leafIndexSet();\n      errorDistribution.clear();\n      errorDistribution.resize(is.size(0),std::make_pair(0.0,0));\n\n      EnergyError energyError(normFunctional,xl.get(),errorEstimate_H,errorEstimate_E);\n      energyError.considerStateVariable(true);\n      energyError.considerControlVariable(true);\n      energyError.considerAdjointVariable(false);\n      typedef VariationalFunctionalAssembler<LinearizationAt<EnergyError> > EnergyErrorAssembler;\n      EnergyErrorAssembler eeAssembler(extensionSpace.gridManager(), energyError.getSpaces());\n\n      eeAssembler.assemble(linearization(energyError,xl.get()), EnergyErrorAssembler::RHS);\n      typename EnergyError::ErrorVector distError( eeAssembler.rhs() );\n      mde.reset(new ErrorRepresentation(energyError.getVariableSetDescription()) );\n      *mde = distError;\n\n//      if(verbose)\n//      {\n//        std::string name = \"errorDistribution_\";\n//        name += std::to_string(step);\n//        writeVTKFile(mde->descriptions.gridView,*mde,name);\n//      }\n\n      CellIterator cend = extensionVariableSetDescription.gridView.template end<0>();\n      for (CellIterator ci=extensionVariableSetDescription.gridView.template begin<0>(); ci!=cend; ++ci)\n        errorDistribution[is.index(*ci)] = std::make_pair( fabs(boost::fusion::at_c<0>(mde->data).value(*ci,Dune::FieldVector<Scalar,dim>(0.3))) , is.index(*ci));\n\n      squaredError = std::accumulate(errorDistribution.begin(), errorDistribution.end(), 0.0, ErrorEstimator_Detail::add);\n\n      if(verbose) std::cout << \"overall error estimation time: \" << boost::timer::format(overallTimer.elapsed()) << std::endl;\n    }\n\n    template <typename... Args>\n    void initFunctionals(const Args&... args)\n    {\n      F_HH.reset(new typename Traits::Functional_HH(args...));\n      F_HE.reset(new typename Traits::Functional_HE(args...));\n    }\n\n        template <typename... Args>\n    void initExtensionFunctionals(const Args&... args)\n    {\n      F_EH.reset(new typename Traits::Functional_EH(args...));\n      F_EE.reset(new typename LumpedTraits::Functional_EE(args...));\n    }\n\n  private:\n    void assembleAt(const Bridge::Vector<typename Traits::VarSet>& xl, const Bridge::Vector<typename Traits::ExtensionVarSet>& xe)\n    {\n      ass_HH->assemble(linearization(*F_HH,xl.get()));\n      ass_HE->assemble(linearization(*F_HE,xl.get()));\n      ass_EH->assemble(linearization(*F_EH,xe.get()));\n      ass_EE->assemble(linearization(*F_EE,xe.get()));\n    }\n\n    std::unique_ptr<typename Traits::Functional_HH> F_HH;\n    std::unique_ptr<typename Traits::Functional_HE> F_HE;\n    std::unique_ptr<typename Traits::Functional_EH> F_EH;\n    std::unique_ptr<typename LumpedTraits::Functional_EE> F_EE;\n    std::unique_ptr<typename Traits::Assembler_HH> ass_HH;\n    //typename Traits::Assembler_HH* ass_HH;\n    std::unique_ptr<typename Traits::Assembler_HE> ass_HE;\n    std::unique_ptr<typename Traits::Assembler_EH> ass_EH;\n    std::unique_ptr<typename LumpedTraits::Assembler_EE> ass_EE;\n    NormFunctional& normFunctional;\n    VariableSetDescription& variableSetDescription;\n    ExtensionVariableSetDescription& extensionVariableSetDescription;\n    Scalar squaredFraction;\n    bool verbose;\n    size_t chebySteps = 30, mgSteps = 25, mgSmoothingSteps = 20;\n    Scalar relativeAccuracy = 1e-3;\n  };\n}\n\n#endif\n", "meta": {"hexsha": "7588a01282b0e0c1a1cfd738ee29cc7b43ad07bd", "size": 29961, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/algorithm/errorEstimator_efficient.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/algorithm/errorEstimator_efficient.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/algorithm/errorEstimator_efficient.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 54.5737704918, "max_line_length": 231, "alphanum_fraction": 0.7029805414, "num_tokens": 7462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.29699859004258317}}
{"text": "#include \"AffineTreeVisitor.h\"\n#include <boost/lexical_cast.hpp>\n#include \"TreeInfixPrinter.h\"\n#include <exception>\n#include \"Backend.h\"\n#include \"Logger.h\"\n#include \"kv/affine.hpp\"\n\nusing namespace std;\nusing namespace hydla::symbolic_expression;\nusing namespace boost;\n\n#define HYDLA_LOGGER_NODE_VALUE \\\n  ;\n//  HYDLA_LOGGER_DEBUG(\"node: \", node->get_node_type_name(), \", expr: \", get_infix_string(node), \", current_val: \", current_val_)\n\n#define HYDLA_LOGGER_NODE_VISIT \\\n  ;\n//  HYDLA_LOGGER_DEBUG(\"visit node: \", node->get_node_type_name(), \", expr: \", get_infix_string(node))\n\n\nnamespace hydla {\nnamespace interval {\n\n/// share constants to take advantage of dependency\nitvd AffineTreeVisitor::pi = kv::constants<kv::interval<double> >::pi();\nitvd AffineTreeVisitor::e = kv::constants<kv::interval<double> >::e();\n\nclass ApproximateException:public std::runtime_error{\npublic:\n  ApproximateException(const std::string& msg):\n    std::runtime_error(\"error occurred in approximation: \" + msg){}\n};\n\nAffineTreeVisitor::AffineTreeVisitor(parameter_idx_map_t &map, variable_map_t &vm):parameter_idx_map_(&map), variable_map(vm)\n{}\n\nAffineTreeVisitor::AffineTreeVisitor(variable_map_t &vm): variable_map(vm), pm_external(true)\n{\n  parameter_idx_map_ = new parameter_idx_map_t();\n  pm_external = true;\n}\n\n\n\nAffineTreeVisitor::~AffineTreeVisitor()\n{\n  if(pm_external)delete parameter_idx_map_;\n}\n\nvoid AffineTreeVisitor::set_current_time(itvd itv)\n{\n  ++time_idx;\n  current_time = itv;\n}\n\nAffineMixedValue AffineTreeVisitor::approximate(const node_sptr &node)\n{\n  differential_count = 0;\n  accept(node);\n  return current_val_;\n}\n\nvoid AffineTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::Plus> node)\n{\n  HYDLA_LOGGER_NODE_VISIT;\n  accept(node->get_lhs());\n  AffineMixedValue lhs = current_val_;\n  accept(node->get_rhs());\n  AffineMixedValue rhs = current_val_;\n  current_val_ = lhs + rhs;\n  HYDLA_LOGGER_NODE_VALUE;\n  return;\n}\n\nvoid AffineTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::Subtract> node)\n{\n  HYDLA_LOGGER_NODE_VISIT;\n  accept(node->get_lhs());\n  AffineMixedValue lhs = current_val_;\n  accept(node->get_rhs());\n  AffineMixedValue rhs = current_val_;\n  current_val_ = lhs - rhs;\n  HYDLA_LOGGER_NODE_VALUE;\n  return;\n}\n\nvoid AffineTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::Times> node)\n{\n  HYDLA_LOGGER_NODE_VISIT;\n  accept(node->get_lhs());\n  AffineMixedValue lhs = current_val_;\n  accept(node->get_rhs());\n  AffineMixedValue rhs = current_val_;\n  current_val_ = lhs * rhs;\n  HYDLA_LOGGER_NODE_VALUE;\n  return;\n}\n\nvoid AffineTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::Divide> node)\n{\n  HYDLA_LOGGER_NODE_VISIT;\n  accept(node->get_lhs());\n  AffineMixedValue lhs = current_val_;\n  accept(node->get_rhs());\n  AffineMixedValue rhs = current_val_;\n  current_val_ = lhs / rhs;\n  HYDLA_LOGGER_NODE_VALUE;\n  return;\n}\n\nvoid AffineTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::Power> node)\n{\n  HYDLA_LOGGER_NODE_VISIT;\n  accept(node->get_lhs());\n  AffineMixedValue lhs = current_val_;  \n  // TODO: 文字列以外で判定する\n  std::string rhs_str = get_infix_string(node->get_rhs());\n  if(rhs_str == \"1/2\")\n  {\n    if(lhs.type == INTEGER)current_val_ = sqrt(itvd(lhs.integer));\n    else if(lhs.type == INTERVAL)current_val_ = AffineMixedValue(sqrt(lhs.interval));\n    else current_val_ = sqrt(lhs.affine_value);\n  }\n  else if(rhs_str == \"(-1)/2\" || rhs_str == \"-1/2\")\n  {\n    if(lhs.type == INTEGER)current_val_ = 1/sqrt(itvd(lhs.integer));\n    else if(lhs.type == INTERVAL)current_val_ = 1/sqrt(lhs.interval);\n    else current_val_ = 1/sqrt(lhs.affine_value);\n  }\n  else if(rhs_str == \"2\" && lhs.type == AFFINE)\n  {\n    current_val_ = square(lhs.affine_value);\n  }\n  else\n  {\n    accept(node->get_rhs());\n    AffineMixedValue rhs = current_val_;\n    current_val_ = lhs ^ rhs;\n  }\n  HYDLA_LOGGER_NODE_VALUE;\n}\n\nvoid AffineTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::Negative> node)\n{\n  HYDLA_LOGGER_NODE_VISIT;\n  accept(node->get_child());\n  current_val_ = -current_val_;\n  HYDLA_LOGGER_NODE_VALUE;\n  return;\n}\n\nvoid AffineTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::Positive> node)\n{\n  HYDLA_LOGGER_NODE_VISIT;\n  accept(node->get_child());\n  HYDLA_LOGGER_NODE_VALUE;\n  return;\n}\n\nvoid AffineTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::Pi> node)\n{\n  current_val_.interval = pi;\n  current_val_.type = INTERVAL;\n}\n\nvoid AffineTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::E> node)\n{\n  current_val_ = AffineMixedValue(e);\n}\n\nvoid AffineTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::Number> node)\n{\n  HYDLA_LOGGER_NODE_VISIT;\n  std::string number_str = node->get_number();\n\n  // try translation to int\n  try{\n    int integer = lexical_cast<int>(number_str);\n    current_val_ = AffineMixedValue(integer);\n    HYDLA_LOGGER_NODE_VALUE;\n    return;\n  }catch(const bad_lexical_cast &){\n  }\n\n  //try approximation as double with upper rounding\n  kv::interval<double> itv = kv::interval<double>(number_str);\n  current_val_ = AffineMixedValue(itv);\n  HYDLA_LOGGER_NODE_VALUE;\n}\n\nvoid AffineTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::Float> node)\n{\n  HYDLA_LOGGER_NODE_VISIT;\n  current_val_ = AffineMixedValue(itvd(node->get_number()));\n  HYDLA_LOGGER_NODE_VALUE;\n}\n\nvoid AffineTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::Function> node)\n{\n  HYDLA_LOGGER_NODE_VISIT;\n  std::string name = node->get_name();\n  if(name == \"log\")\n  {\n    if(node->get_arguments_size() != 1)invalid_node(*node);\n    accept(node->get_argument(0) );\n    if(current_val_.type == INTEGER)current_val_.interval = log(itvd(current_val_.integer));\n    else if(current_val_.type == INTERVAL)current_val_.interval = log(current_val_.interval);\n    else current_val_.affine_value = log(current_val_.affine_value);\n  }\n  else if(name == \"sin\")\n  {\n    if(node->get_arguments_size() != 1)invalid_node(*node);\n    accept(node->get_argument(0) );\n    if(current_val_.type == INTEGER)current_val_.interval = sin(itvd(current_val_.integer));\n    if(current_val_.type == INTERVAL)current_val_.interval = sin(current_val_.interval);\n    else current_val_.affine_value = sin(current_val_.affine_value);\n  }\n  else if(name == \"cos\")\n  {\n    if(node->get_arguments_size() != 1)invalid_node(*node);\n    accept(node->get_argument(0) );\n    if(current_val_.type == INTEGER)current_val_.interval = cos(itvd(current_val_.integer));\n    if(current_val_.type == INTERVAL)current_val_.interval = cos(current_val_.interval);\n    else current_val_.affine_value = cos(current_val_.affine_value);\n  }\n  else if(name == \"sinh\")\n  {\n    if(node->get_arguments_size() != 1)invalid_node(*node);\n    accept(node->get_argument(0) );\n    if(current_val_.type == INTEGER)current_val_.interval = sinh(itvd(current_val_.integer));\n    if(current_val_.type == INTERVAL)current_val_.interval = sinh(current_val_.interval);\n    else current_val_.affine_value = sinh(current_val_.affine_value);\n  }\n  else if(name == \"cosh\")\n  {\n    if(node->get_arguments_size() != 1)invalid_node(*node);\n    accept(node->get_argument(0) );\n    if(current_val_.type == INTEGER)current_val_.interval = cosh(itvd(current_val_.integer));\n    if(current_val_.type == INTERVAL)current_val_.interval = cosh(current_val_.interval);\n    else current_val_.affine_value = cosh(current_val_.affine_value);\n  }\n  else\n  {\n    invalid_node(*node);\n  }\n  HYDLA_LOGGER_NODE_VALUE;\n}\n\nvoid AffineTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::Parameter> node)\n{\n  HYDLA_LOGGER_NODE_VISIT;\n  current_val_ = affine_t();\n  parameter_t param(node->get_name(),\n                    node->get_differential_count(),\n                    node->get_phase_id());\n  parameter_idx_map_t::left_iterator it = parameter_idx_map_->left.find(param);\n  int idx;\n  if(it == parameter_idx_map_->left.end())\n  {\n    idx = ++affine_t::maxnum();\n    parameter_idx_map_->insert(\n      parameter_idx_t(param, affine_t::maxnum()));\n  }\n  else\n  {\n    idx = it->second;\n  }\n  current_val_.affine_value.a.resize(idx + 1);\n  current_val_.affine_value.a(idx) = 1;\n  current_val_.affine_value.er = 0;\n  HYDLA_LOGGER_NODE_VALUE;\n  return;\n}\n\n\n\nvoid AffineTreeVisitor::visit(boost::shared_ptr<symbolic_expression::Variable> node)\n{\n  HYDLA_LOGGER_NODE_VISIT;\n  simulator::Variable variable(node->get_name(), differential_count);\n  if(variable_map.find(variable) == variable_map.end())throw ApproximateException(\"unknown variable: \" + variable.get_string() );\n  if(!variable_map[variable].unique())throw ApproximateException(\"the value of a variable must be unique: \"+ variable.get_string());\n  accept(variable_map[variable].get_unique_value().get_node());\n  HYDLA_LOGGER_NODE_VALUE;\n  return;\n}\n\n\nvoid AffineTreeVisitor::visit(boost::shared_ptr<Differential> node)\n{\n  HYDLA_LOGGER_NODE_VISIT;\n  differential_count++;\n  // TODO: 変数以外の微分値は扱えないので、その判定もしたい。\n  accept(node->get_child());\n  differential_count--;\n  return;\n}\n\nvoid AffineTreeVisitor::visit(boost::shared_ptr<SymbolicT> node)\n{\n  HYDLA_LOGGER_NODE_VISIT;\n  current_val_ = AffineMixedValue(affine_t());\n  parameter_t param(\"t\",\n                    -1,\n                    time_idx);\n  parameter_idx_map_t::left_iterator it = parameter_idx_map_->left.find(param);\n  int idx;\n  if(it == parameter_idx_map_->left.end())\n  {\n    idx = ++affine_t::maxnum();\n    parameter_idx_map_->insert(\n      parameter_idx_t(param, affine_t::maxnum()));\n  }\n  else\n  {\n    idx = it->second;\n  }\n  current_val_.affine_value = affine_t(current_time);\n  HYDLA_LOGGER_NODE_VALUE;\n  return;\n}\n\nvoid AffineTreeVisitor::invalid_node(symbolic_expression::Node& node)\n{\n  throw ApproximateException(\"invalid node: \" + node.get_string());\n}\n\n\n#define DEFINE_INVALID_NODE(NODE_NAME)                           \\\nvoid AffineTreeVisitor::visit(boost::shared_ptr<NODE_NAME> node) \\\n{                                                                \\\n  HYDLA_LOGGER_DEBUG(\"\");                                        \\\n  invalid_node(*node);                                           \\\n}\n\nDEFINE_INVALID_NODE(ConstraintDefinition)\nDEFINE_INVALID_NODE(ProgramDefinition)\nDEFINE_INVALID_NODE(ConstraintCaller)\nDEFINE_INVALID_NODE(ProgramCaller)\nDEFINE_INVALID_NODE(Constraint)\nDEFINE_INVALID_NODE(Ask)\nDEFINE_INVALID_NODE(Tell)\n\nDEFINE_INVALID_NODE(Equal)\nDEFINE_INVALID_NODE(UnEqual)\n\nDEFINE_INVALID_NODE(Less)\nDEFINE_INVALID_NODE(LessEqual)\n\nDEFINE_INVALID_NODE(Greater)\nDEFINE_INVALID_NODE(GreaterEqual)\n\nDEFINE_INVALID_NODE(LogicalAnd)\nDEFINE_INVALID_NODE(LogicalOr)\n\nDEFINE_INVALID_NODE(Weaker)\nDEFINE_INVALID_NODE(Parallel)\n\nDEFINE_INVALID_NODE(Always)\n\nDEFINE_INVALID_NODE(Previous)\n\nDEFINE_INVALID_NODE(Print)\nDEFINE_INVALID_NODE(PrintPP)\nDEFINE_INVALID_NODE(PrintIP)\nDEFINE_INVALID_NODE(Scan)\nDEFINE_INVALID_NODE(Exit)\nDEFINE_INVALID_NODE(Abort)\nDEFINE_INVALID_NODE(SVtimer)\n\nDEFINE_INVALID_NODE(Not)\n\nDEFINE_INVALID_NODE(UnsupportedFunction)\n\nDEFINE_INVALID_NODE(ImaginaryUnit)\nDEFINE_INVALID_NODE(Infinity)\nDEFINE_INVALID_NODE(True)\nDEFINE_INVALID_NODE(False)\n\nDEFINE_INVALID_NODE(ProgramList)\nDEFINE_INVALID_NODE(ConditionalProgramList)\nDEFINE_INVALID_NODE(ExpressionList)\nDEFINE_INVALID_NODE(ConditionalExpressionList)\nDEFINE_INVALID_NODE(EachElement)\nDEFINE_INVALID_NODE(DifferentVariable)\nDEFINE_INVALID_NODE(ExpressionListElement)\nDEFINE_INVALID_NODE(ExpressionListCaller)\nDEFINE_INVALID_NODE(ExpressionListDefinition)\nDEFINE_INVALID_NODE(ProgramListElement)\nDEFINE_INVALID_NODE(ProgramListCaller)\nDEFINE_INVALID_NODE(ProgramListDefinition)\nDEFINE_INVALID_NODE(Range)\nDEFINE_INVALID_NODE(Union)\nDEFINE_INVALID_NODE(Intersection)\nDEFINE_INVALID_NODE(SumOfList)\nDEFINE_INVALID_NODE(MulOfList)\nDEFINE_INVALID_NODE(SizeOfList)\n\n}\n}\n", "meta": {"hexsha": "35669d3bd5517e5f596028d5126bf94760d4b240", "size": 11764, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/interval/AffineTreeVisitor.cpp", "max_stars_repo_name": "takafumihoriuchi/HyLaGI", "max_stars_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T07:11:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-15T07:11:09.000Z", "max_issues_repo_path": "src/interval/AffineTreeVisitor.cpp", "max_issues_repo_name": "takafumihoriuchi/HyLaGI", "max_issues_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/interval/AffineTreeVisitor.cpp", "max_forks_repo_name": "takafumihoriuchi/HyLaGI", "max_forks_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.263681592, "max_line_length": 132, "alphanum_fraction": 0.7428595716, "num_tokens": 3009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2969507565805076}}
{"text": "#ifndef STAN_OPTIMIZATION_BFGS_HPP\n#define STAN_OPTIMIZATION_BFGS_HPP\n\n#include <stan/math/prim/mat.hpp>\n#include <stan/model/log_prob_propto.hpp>\n#include <stan/model/log_prob_grad.hpp>\n#include <stan/optimization/bfgs_linesearch.hpp>\n#include <stan/optimization/bfgs_update.hpp>\n#include <stan/optimization/lbfgs_update.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <algorithm>\n#include <cmath>\n#include <cstdlib>\n#include <limits>\n#include <string>\n#include <vector>\n\nnamespace stan {\n  namespace optimization {\n    typedef enum {\n      TERM_SUCCESS = 0,\n      TERM_ABSX = 10,\n      TERM_ABSF = 20,\n      TERM_RELF = 21,\n      TERM_ABSGRAD = 30,\n      TERM_RELGRAD = 31,\n      TERM_MAXIT = 40,\n      TERM_LSFAIL = -1\n    } TerminationCondition;\n\n    template<typename Scalar = double>\n    class ConvergenceOptions {\n    public:\n      ConvergenceOptions() {\n        maxIts = 10000;\n        fScale = 1.0;\n\n        tolAbsX = 1e-8;\n        tolAbsF = 1e-12;\n        tolAbsGrad = 1e-8;\n\n        tolRelF = 1e+4;\n        tolRelGrad = 1e+3;\n      }\n      size_t maxIts;\n      Scalar tolAbsX;\n      Scalar tolAbsF;\n      Scalar tolRelF;\n      Scalar fScale;\n      Scalar tolAbsGrad;\n      Scalar tolRelGrad;\n    };\n\n    template<typename Scalar = double>\n    class LSOptions {\n    public:\n      LSOptions() {\n        c1 = 1e-4;\n        c2 = 0.9;\n        alpha0 = 1e-3;\n        minAlpha = 1e-12;\n        maxLSIts = 20;\n        maxLSRestarts = 10;\n      }\n      Scalar c1;\n      Scalar c2;\n      Scalar alpha0;\n      Scalar minAlpha;\n      Scalar maxLSIts;\n      Scalar maxLSRestarts;\n    };\n    template<typename FunctorType, typename QNUpdateType,\n             typename Scalar = double, int DimAtCompile = Eigen::Dynamic>\n    class BFGSMinimizer {\n    public:\n      typedef Eigen::Matrix<Scalar, DimAtCompile, 1> VectorT;\n      typedef Eigen::Matrix<Scalar, DimAtCompile, DimAtCompile> HessianT;\n\n    protected:\n      FunctorType &_func;\n      VectorT _gk, _gk_1, _xk_1, _xk, _pk, _pk_1;\n      Scalar _fk, _fk_1, _alphak_1;\n      Scalar _alpha, _alpha0;\n      size_t _itNum;\n      std::string _note;\n      QNUpdateType _qn;\n\n    public:\n      LSOptions<Scalar> _ls_opts;\n      ConvergenceOptions<Scalar> _conv_opts;\n\n      QNUpdateType &get_qnupdate() { return _qn; }\n      const QNUpdateType &get_qnupdate() const { return _qn; }\n\n      const Scalar &curr_f() const { return _fk; }\n      const VectorT &curr_x() const { return _xk; }\n      const VectorT &curr_g() const { return _gk; }\n      const VectorT &curr_p() const { return _pk; }\n\n      const Scalar &prev_f() const { return _fk_1; }\n      const VectorT &prev_x() const { return _xk_1; }\n      const VectorT &prev_g() const { return _gk_1; }\n      const VectorT &prev_p() const { return _pk_1; }\n      Scalar prev_step_size() const { return _pk_1.norm()*_alphak_1; }\n\n      inline Scalar rel_grad_norm() const {\n        return -_pk.dot(_gk) / std::max(std::fabs(_fk), _conv_opts.fScale);\n      }\n      inline Scalar rel_obj_decrease() const {\n        return std::fabs(_fk_1 - _fk) / std::max(std::fabs(_fk_1),\n                                                 std::max(std::fabs(_fk),\n                                                          _conv_opts.fScale));\n      }\n\n      const Scalar &alpha0() const { return _alpha0; }\n      const Scalar &alpha() const { return _alpha; }\n      const size_t iter_num() const { return _itNum; }\n\n      const std::string &note() const { return _note; }\n\n      std::string get_code_string(int retCode) {\n        switch (retCode) {\n          case TERM_SUCCESS:\n            return std::string(\"Successful step completed\");\n          case TERM_ABSF:\n            return std::string(\"Convergence detected: absolute change \"\n                               \"in objective function was below tolerance\");\n          case TERM_RELF:\n            return std::string(\"Convergence detected: relative change \"\n                               \"in objective function was below tolerance\");\n          case TERM_ABSGRAD:\n            return std::string(\"Convergence detected: \"\n                               \"gradient norm is below tolerance\");\n          case TERM_RELGRAD:\n            return std::string(\"Convergence detected: relative \"\n                               \"gradient magnitude is below tolerance\");\n          case TERM_ABSX:\n            return std::string(\"Convergence detected: \"\n                               \"absolute parameter change was below tolerance\");\n          case TERM_MAXIT:\n            return std::string(\"Maximum number of iterations hit, \"\n                               \"may not be at an optima\");\n          case TERM_LSFAIL:\n            return std::string(\"Line search failed to achieve a sufficient \"\n                               \"decrease, no more progress can be made\");\n          default:\n            return std::string(\"Unknown termination code\");\n        }\n      }\n\n      explicit BFGSMinimizer(FunctorType &f) : _func(f) { }\n\n      void initialize(const VectorT &x0) {\n        int ret;\n        _xk = x0;\n        ret = _func(_xk, _fk, _gk);\n        if (ret) {\n          throw std::runtime_error(\"Error evaluating initial BFGS point.\");\n        }\n        _pk = -_gk;\n\n        _itNum = 0;\n        _note = \"\";\n      }\n\n      int step() {\n        Scalar gradNorm, stepNorm;\n        VectorT sk, yk;\n        int retCode(0);\n        int resetB(0);\n\n        _itNum++;\n\n        if (_itNum == 1) {\n          resetB = 1;\n          _note = \"\";\n        } else {\n          resetB = 0;\n          _note = \"\";\n        }\n\n        while (true) {\n          if (resetB) {\n            // Reset the Hessian approximation\n            _pk.noalias() = -_gk;\n          }\n\n          // Get an initial guess for the step size (alpha)\n          if (_itNum > 1 && resetB != 2) {\n            // use cubic interpolation based on the previous step\n            _alpha0 = _alpha = std::min(1.0,\n                                        1.01*CubicInterp(_gk_1.dot(_pk_1),\n                                                         _alphak_1,\n                                                         _fk - _fk_1,\n                                                         _gk.dot(_pk_1),\n                                                         _ls_opts.minAlpha,\n                                                         1.0));\n          } else {\n            // On the first step (or, after a reset) use the default step size\n            _alpha0 = _alpha = _ls_opts.alpha0;\n          }\n\n          // Perform the line search.  If successful, the results are in the\n          // variables: _xk_1, _fk_1 and _gk_1.\n          retCode = WolfeLineSearch(_func, _alpha, _xk_1, _fk_1, _gk_1,\n                                    _pk, _xk, _fk, _gk,\n                                    _ls_opts.c1, _ls_opts.c2,\n                                    _ls_opts.minAlpha,\n                                    _ls_opts.maxLSIts,\n                                    _ls_opts.maxLSRestarts);\n          if (retCode) {\n            // Line search failed...\n            if (resetB) {\n              // did a Hessian reset and it still failed,\n              // and nothing left to try\n              retCode = TERM_LSFAIL;\n              return retCode;\n            } else {\n              // try resetting the Hessian approximation\n              resetB = 2;\n              _note += \"LS failed, Hessian reset\";\n              continue;\n            }\n          } else {\n            break;\n          }\n        }\n\n        // Swap things so that k is the most recent iterate\n        std::swap(_fk, _fk_1);\n        _xk.swap(_xk_1);\n        _gk.swap(_gk_1);\n        _pk.swap(_pk_1);\n\n        sk.noalias() = _xk - _xk_1;\n        yk.noalias() = _gk - _gk_1;\n\n        gradNorm = _gk.norm();\n        stepNorm = sk.norm();\n\n        // Update QN approximation\n        if (resetB) {\n          // If the QN approximation was reset, automatically scale it\n          // and update the step-size accordingly\n          Scalar B0fact = _qn.update(yk, sk, true);\n          _pk_1 /= B0fact;\n          _alphak_1 = _alpha*B0fact;\n        } else {\n          _qn.update(yk, sk);\n          _alphak_1 = _alpha;\n        }\n        // Compute search direction for next step\n        _qn.search_direction(_pk, _gk);\n\n        // Check for convergence\n        if (std::fabs(_fk_1 - _fk) < _conv_opts.tolAbsF) {\n          // Objective function improvement wasn't sufficient\n          retCode = TERM_ABSF;\n        } else if (gradNorm < _conv_opts.tolAbsGrad) {\n          retCode = TERM_ABSGRAD;  // Gradient norm was below threshold\n        } else if (stepNorm < _conv_opts.tolAbsX) {\n          retCode = TERM_ABSX;  // Change in x was too small\n        } else if (_itNum >= _conv_opts.maxIts) {\n          retCode = TERM_MAXIT;  // Max number of iterations hit\n        } else if (rel_obj_decrease()\n                 < _conv_opts.tolRelF\n                 * std::numeric_limits<Scalar>::epsilon()) {\n          // Relative improvement in objective function wasn't sufficient\n          retCode = TERM_RELF;\n        } else if (rel_grad_norm()\n                   < _conv_opts.tolRelGrad\n                   * std::numeric_limits<Scalar>::epsilon()) {\n          // Relative gradient norm was below threshold\n          retCode = TERM_RELGRAD;\n        } else {\n          // Step was successful more progress to be made\n          retCode = TERM_SUCCESS;\n        }\n\n        return retCode;\n      }\n\n      int minimize(VectorT &x0) {\n        int retcode;\n        initialize(x0);\n        while (!(retcode = step()))\n          continue;\n        x0 = _xk;\n        return retcode;\n      }\n    };\n\n    template <class M>\n    class ModelAdaptor {\n    private:\n      M& _model;\n      std::vector<int> _params_i;\n      std::ostream* _msgs;\n      std::vector<double> _x, _g;\n      size_t _fevals;\n\n    public:\n      ModelAdaptor(M& model,\n                   const std::vector<int>& params_i,\n                   std::ostream* msgs)\n      : _model(model), _params_i(params_i), _msgs(msgs), _fevals(0) {}\n\n      size_t fevals() const { return _fevals; }\n      int operator()(const Eigen::Matrix<double, Eigen::Dynamic, 1> &x,\n                     double &f) {\n        using Eigen::Matrix;\n        using Eigen::Dynamic;\n        using stan::math::index_type;\n        using stan::model::log_prob_propto;\n        typedef typename index_type<Matrix<double, Dynamic, 1> >::type idx_t;\n\n        _x.resize(x.size());\n        for (idx_t i = 0; i < x.size(); i++)\n          _x[i] = x[i];\n\n        try {\n          f = - log_prob_propto<false>(_model, _x, _params_i, _msgs);\n        } catch (const std::exception& e) {\n          if (_msgs)\n            (*_msgs) << e.what() << std::endl;\n          return 1;\n        }\n\n        if (boost::math::isfinite(f)) {\n          return 0;\n        } else {\n          if (_msgs)\n            *_msgs << \"Error evaluating model log probability: \"\n                      \"Non-finite function evaluation.\" << std::endl;\n          return 2;\n        }\n      }\n      int operator()(const Eigen::Matrix<double, Eigen::Dynamic, 1> &x,\n                     double &f,\n                     Eigen::Matrix<double, Eigen::Dynamic, 1> &g) {\n        using Eigen::Matrix;\n        using Eigen::Dynamic;\n        using stan::math::index_type;\n        using stan::model::log_prob_grad;\n        typedef typename index_type<Matrix<double, Dynamic, 1> >::type idx_t;\n\n        _x.resize(x.size());\n        for (idx_t i = 0; i < x.size(); i++)\n          _x[i] = x[i];\n\n        _fevals++;\n\n        try {\n          f = - log_prob_grad<true, false>(_model, _x, _params_i, _g, _msgs);\n        } catch (const std::exception& e) {\n          if (_msgs)\n            (*_msgs) << e.what() << std::endl;\n          return 1;\n        }\n\n        g.resize(_g.size());\n        for (size_t i = 0; i < _g.size(); i++) {\n          if (!boost::math::isfinite(_g[i])) {\n            if (_msgs)\n              *_msgs << \"Error evaluating model log probability: \"\n                                 \"Non-finite gradient.\" << std::endl;\n            return 3;\n          }\n          g[i] = -_g[i];\n        }\n\n        if (boost::math::isfinite(f)) {\n          return 0;\n        } else {\n          if (_msgs)\n            *_msgs << \"Error evaluating model log probability: \"\n                   << \"Non-finite function evaluation.\"\n                   << std::endl;\n          return 2;\n        }\n      }\n      int df(const Eigen::Matrix<double, Eigen::Dynamic, 1> &x,\n             Eigen::Matrix<double, Eigen:: Dynamic, 1> &g) {\n        double f;\n        return (*this)(x, f, g);\n      }\n    };\n\n    template<typename M, typename QNUpdateType, typename Scalar = double,\n             int DimAtCompile = Eigen::Dynamic>\n    class BFGSLineSearch\n      : public BFGSMinimizer<ModelAdaptor<M>, QNUpdateType,\n                             Scalar, DimAtCompile> {\n    private:\n      ModelAdaptor<M> _adaptor;\n\n    public:\n      typedef BFGSMinimizer<ModelAdaptor<M>, QNUpdateType, Scalar, DimAtCompile>\n      BFGSBase;\n      typedef typename BFGSBase::VectorT vector_t;\n      typedef typename stan::math::index_type<vector_t>::type idx_t;\n\n      BFGSLineSearch(M& model,\n                     const std::vector<double>& params_r,\n                     const std::vector<int>& params_i,\n                     std::ostream* msgs = 0)\n        : BFGSBase(_adaptor),\n          _adaptor(model, params_i, msgs) {\n        initialize(params_r);\n      }\n\n      void initialize(const std::vector<double>& params_r) {\n        Eigen::Matrix<double, Eigen::Dynamic, 1> x;\n        x.resize(params_r.size());\n        for (size_t i = 0; i < params_r.size(); i++)\n          x[i] = params_r[i];\n        BFGSBase::initialize(x);\n      }\n\n      size_t grad_evals() { return _adaptor.fevals(); }\n      double logp() { return -(this->curr_f()); }\n      double grad_norm() { return this->curr_g().norm(); }\n      void grad(std::vector<double>& g) {\n        const vector_t &cg(this->curr_g());\n        g.resize(cg.size());\n        for (idx_t i = 0; i < cg.size(); i++)\n          g[i] = -cg[i];\n      }\n      void params_r(std::vector<double>& x) {\n        const vector_t &cx(this->curr_x());\n        x.resize(cx.size());\n        for (idx_t i = 0; i < cx.size(); i++)\n          x[i] = cx[i];\n      }\n    };\n\n  }\n\n}\n\n#endif\n", "meta": {"hexsha": "e47af499bff499c5c16b9b146719afe569ea4c83", "size": 14246, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/optimization/bfgs.hpp", "max_stars_repo_name": "drezap/stan", "max_stars_repo_head_hexsha": "9b319ed125e2a7d14d0c9c246d2f462dad668537", "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/stan/optimization/bfgs.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/optimization/bfgs.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": 32.2307692308, "max_line_length": 80, "alphanum_fraction": 0.5195142496, "num_tokens": 3575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2969368009092318}}
{"text": "/**\n *****************************************************************************\n * @author     This file is part of libsnark, developed by SCIPR Lab\n *             and contributors (see AUTHORS).\n * @copyright  MIT license (see LICENSE file)\n *****************************************************************************/\n#include <fstream>\n#include <iostream>\n#ifndef MINDEPS\n#include <boost/program_options.hpp>\n#endif\n\n#include \"common/default_types/tinyram_ppzksnark_pp.hpp\"\n#include \"zk_proof_systems/ppzksnark/ram_ppzksnark/ram_ppzksnark.hpp\"\n#include \"relations/ram_computations/rams/tinyram/tinyram_params.hpp\"\n\n#ifndef MINDEPS\nnamespace po = boost::program_options;\n\nbool process_verifier_command_line(const int argc, const char** argv,\n                                   std::string &processed_assembly_fn,\n                                   std::string &verification_key_fn,\n                                   std::string &primary_input_fn,\n                                   std::string &proof_fn,\n                                   std::string &verification_result_fn)\n{\n    try\n    {\n        po::options_description desc(\"Usage\");\n        desc.add_options()\n            (\"help\", \"print this help message\")\n            (\"processed_assembly\", po::value<std::string>(&processed_assembly_fn)->required())\n            (\"verification_key\", po::value<std::string>(&verification_key_fn)->required())\n            (\"primary_input\", po::value<std::string>(&primary_input_fn)->required())\n            (\"proof\", po::value<std::string>(&proof_fn)->required())\n            (\"verification_result\", po::value<std::string>(&verification_result_fn)->required());\n\n        po::variables_map vm;\n        po::store(po::parse_command_line(argc, argv, desc), vm);\n\n        if (vm.count(\"help\"))\n        {\n            std::cout << desc << \"\\n\";\n            return false;\n        }\n\n        po::notify(vm);\n    }\n    catch(std::exception& e)\n    {\n        std::cerr << \"Error: \" << e.what() << \"\\n\";\n        return false;\n    }\n\n    return true;\n}\n#endif\n\nusing namespace libsnark;\n\nint main(int argc, const char * argv[])\n{\n    default_tinyram_ppzksnark_pp::init_public_params();\n\n#ifdef MINDEPS\n    std::string processed_assembly_fn = \"processed.txt\";\n    std::string verification_key_fn = \"verification_key.txt\";\n    std::string proof_fn = \"proof.txt\";\n    std::string primary_input_fn = \"primary_input.txt\";\n    std::string verification_result_fn = \"verification_result.txt\";\n#else\n    std::string processed_assembly_fn;\n    std::string verification_key_fn;\n    std::string proof_fn;\n    std::string primary_input_fn;\n    std::string verification_result_fn;\n\n    if (!process_verifier_command_line(argc, argv, processed_assembly_fn, verification_key_fn, primary_input_fn, proof_fn, verification_result_fn))\n    {\n        return 1;\n    }\n#endif\n    start_profiling();\n\n    ram_ppzksnark_verification_key<default_tinyram_ppzksnark_pp> vk;\n    std::ifstream vk_file(verification_key_fn);\n    vk_file >> vk;\n    vk_file.close();\n\n    std::ifstream processed(processed_assembly_fn);\n    tinyram_program program = load_preprocessed_program(vk.ap, processed);\n\n    std::ifstream f_primary_input(primary_input_fn);\n    tinyram_input_tape primary_input = load_tape(f_primary_input);\n\n    std::ifstream proof_file(proof_fn);\n    ram_ppzksnark_proof<default_tinyram_ppzksnark_pp> pi;\n    proof_file >> pi;\n    proof_file.close();\n\n    const ram_boot_trace<default_tinyram_ppzksnark_pp> boot_trace = tinyram_boot_trace_from_program_and_input(vk.ap, vk.primary_input_size_bound, program, primary_input);\n    const bool bit = ram_ppzksnark_verifier<default_tinyram_ppzksnark_pp>(vk, boot_trace, pi);\n\n    printf(\"================================================================================\\n\");\n    printf(\"The verification result is: %s\\n\", (bit ? \"PASS\" : \"FAIL\"));\n    printf(\"================================================================================\\n\");\n    std::ofstream vr_file(verification_result_fn);\n    vr_file << bit << \"\\n\";\n    vr_file.close();\n}\n", "meta": {"hexsha": "33e411cd85eea9023f0800ddfa960a8741706d28", "size": 4053, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/zk_proof_systems/ppzksnark/ram_ppzksnark/examples/demo_ram_ppzksnark_verifier.cpp", "max_stars_repo_name": "ThisIsNotOfficialCodeItsJustForks/libsnark", "max_stars_repo_head_hexsha": "6c23407a73ecc8d7648772886f2cd500cd8560a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2017-03-12T17:10:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T14:42:25.000Z", "max_issues_repo_path": "src/zk_proof_systems/ppzksnark/ram_ppzksnark/examples/demo_ram_ppzksnark_verifier.cpp", "max_issues_repo_name": "ThisIsNotOfficialCodeItsJustForks/libsnark", "max_issues_repo_head_hexsha": "6c23407a73ecc8d7648772886f2cd500cd8560a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/zk_proof_systems/ppzksnark/ram_ppzksnark/examples/demo_ram_ppzksnark_verifier.cpp", "max_forks_repo_name": "ThisIsNotOfficialCodeItsJustForks/libsnark", "max_forks_repo_head_hexsha": "6c23407a73ecc8d7648772886f2cd500cd8560a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2017-06-26T20:20:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T14:42:18.000Z", "avg_line_length": 36.5135135135, "max_line_length": 170, "alphanum_fraction": 0.6089316556, "num_tokens": 886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.63341027751814, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2969368009092318}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2020-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_RELATE_GEOGRAPHIC_HPP\n#define BOOST_GEOMETRY_STRATEGIES_RELATE_GEOGRAPHIC_HPP\n\n\n// TEMP - move to strategy\n#include <boost/geometry/strategies/agnostic/point_in_box_by_side.hpp>\n#include <boost/geometry/strategies/cartesian/box_in_box.hpp>\n#include <boost/geometry/strategies/geographic/intersection.hpp>\n#include <boost/geometry/strategies/geographic/point_in_poly_winding.hpp>\n#include <boost/geometry/strategies/spherical/point_in_point.hpp>\n#include <boost/geometry/strategies/spherical/disjoint_box_box.hpp>\n\n#include <boost/geometry/strategies/envelope/geographic.hpp>\n#include <boost/geometry/strategies/relate/services.hpp>\n#include <boost/geometry/strategies/detail.hpp>\n\n#include <boost/geometry/strategy/geographic/area.hpp>\n#include <boost/geometry/strategy/geographic/area_box.hpp>\n\n#include <boost/geometry/util/type_traits.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategies { namespace relate\n{\n\ntemplate\n<\n    typename FormulaPolicy = strategy::andoyer,\n    typename Spheroid = srs::spheroid<double>,\n    typename CalculationType = void\n>\nclass geographic\n    : public strategies::envelope::geographic<FormulaPolicy, Spheroid, CalculationType>\n{\n    using base_t = strategies::envelope::geographic<FormulaPolicy, Spheroid, CalculationType>;\n\npublic:\n    geographic() = default;\n\n    explicit geographic(Spheroid const& spheroid)\n        : base_t(spheroid)\n    {}\n\n    // area\n\n    template <typename Geometry>\n    auto area(Geometry const&,\n              std::enable_if_t<! util::is_box<Geometry>::value> * = nullptr) const\n    {\n        return strategy::area::geographic\n            <\n                FormulaPolicy,\n                strategy::default_order<FormulaPolicy>::value,\n                Spheroid, CalculationType\n            >(base_t::m_spheroid);\n    }\n\n    template <typename Geometry>\n    auto area(Geometry const&,\n              std::enable_if_t<util::is_box<Geometry>::value> * = nullptr) const\n    {\n        return strategy::area::geographic_box\n            <\n                Spheroid, CalculationType\n            >(base_t::m_spheroid);\n    }\n\n    // covered_by\n\n    template <typename Geometry1, typename Geometry2>\n    static auto covered_by(Geometry1 const&, Geometry2 const&,\n                           std::enable_if_t\n                                <\n                                    util::is_pointlike<Geometry1>::value\n                                 && util::is_box<Geometry2>::value\n                                > * = nullptr)\n    {\n        return strategy::covered_by::spherical_point_box();\n    }\n\n    template <typename Geometry1, typename Geometry2>\n    static auto covered_by(Geometry1 const&, Geometry2 const&,\n                           std::enable_if_t\n                            <\n                                util::is_box<Geometry1>::value\n                             && util::is_box<Geometry2>::value\n                            > * = nullptr)\n    {\n        return strategy::covered_by::spherical_box_box();\n    }\n\n    // disjoint\n\n    template <typename Geometry1, typename Geometry2>\n    static auto disjoint(Geometry1 const&, Geometry2 const&,\n                         std::enable_if_t\n                            <\n                                util::is_box<Geometry1>::value\n                             && util::is_box<Geometry2>::value\n                            > * = nullptr)\n    {\n        return strategy::disjoint::spherical_box_box();\n    }\n\n    template <typename Geometry1, typename Geometry2>\n    auto disjoint(Geometry1 const&, Geometry2 const&,\n                  std::enable_if_t\n                    <\n                        util::is_segment<Geometry1>::value\n                        && util::is_box<Geometry2>::value\n                    > * = nullptr) const\n    {\n        // NOTE: Inconsistent name\n        // The only disjoint(Seg, Box) strategy that takes CalculationType.\n        return strategy::disjoint::segment_box_geographic\n            <\n                FormulaPolicy, Spheroid, CalculationType\n            >(base_t::m_spheroid);\n    }\n\n    // relate\n\n    template <typename Geometry1, typename Geometry2>\n    static auto relate(Geometry1 const&, Geometry2 const&,\n                       std::enable_if_t\n                            <\n                                util::is_pointlike<Geometry1>::value\n                             && util::is_pointlike<Geometry2>::value\n                            > * = nullptr)\n    {\n        return strategy::within::spherical_point_point();\n    }\n\n    template <typename Geometry1, typename Geometry2>\n    auto relate(Geometry1 const&, Geometry2 const&,\n                std::enable_if_t\n                    <\n                        util::is_pointlike<Geometry1>::value\n                        && ( util::is_linear<Geometry2>::value\n                        || util::is_polygonal<Geometry2>::value )\n                    > * = nullptr) const\n    {\n        return strategy::within::geographic_winding\n                <\n                    void, void, FormulaPolicy, Spheroid, CalculationType\n                >(base_t::m_spheroid);\n    }\n\n    //template <typename Geometry1, typename Geometry2>\n    auto relate(/*Geometry1 const&, Geometry2 const&,\n                std::enable_if_t\n                    <\n                        ( util::is_linear<Geometry1>::value\n                        || util::is_polygonal<Geometry1>::value )\n                        && ( util::is_linear<Geometry2>::value\n                        || util::is_polygonal<Geometry2>::value )\n                    > * = nullptr*/) const\n    {\n        return strategy::intersection::geographic_segments\n            <\n                FormulaPolicy,\n                strategy::default_order<FormulaPolicy>::value,\n                Spheroid, CalculationType\n            >(base_t::m_spheroid);\n    }\n\n    // side\n\n    auto side() const\n    {\n        return strategy::side::geographic\n            <\n                FormulaPolicy, Spheroid, CalculationType\n            >(base_t::m_spheroid);\n    }\n\n    // within\n\n    template <typename Geometry1, typename Geometry2>\n    static auto within(Geometry1 const&, Geometry2 const&,\n                       std::enable_if_t\n                            <\n                                util::is_pointlike<Geometry1>::value\n                                && util::is_box<Geometry2>::value\n                            > * = nullptr)\n    {\n        return strategy::within::spherical_point_box();\n    }\n\n    template <typename Geometry1, typename Geometry2>\n    static auto within(Geometry1 const&, Geometry2 const&,\n                       std::enable_if_t\n                            <\n                                util::is_box<Geometry1>::value\n                             && util::is_box<Geometry2>::value\n                            > * = nullptr)\n    {\n        return strategy::within::spherical_box_box();\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::relate::geographic<>;\n};\n\n\ntemplate <typename FormulaPolicy, typename Spheroid, typename CalculationType>\nstruct strategy_converter<strategy::disjoint::segment_box_geographic<FormulaPolicy, Spheroid, CalculationType>>\n{\n    static auto get(strategy::disjoint::segment_box_geographic<FormulaPolicy, Spheroid, CalculationType> const& s)\n    {\n        return strategies::relate::geographic\n            <\n                FormulaPolicy,\n                Spheroid,\n                CalculationType\n            >(s.model());\n    }\n};\n\ntemplate <typename P1, typename P2, typename FormulaPolicy, typename Spheroid, typename CalculationType>\nstruct strategy_converter<strategy::within::geographic_winding<P1, P2, FormulaPolicy, Spheroid, CalculationType>>\n{\n    static auto get(strategy::within::geographic_winding<P1, P2, FormulaPolicy, Spheroid, CalculationType> const& s)\n    {\n        return strategies::relate::geographic\n            <\n                FormulaPolicy,\n                Spheroid,\n                CalculationType\n            >(s.model());\n    }\n};\n\ntemplate <typename FormulaPolicy, std::size_t SeriesOrder, typename Spheroid, typename CalculationType>\nstruct strategy_converter<strategy::intersection::geographic_segments<FormulaPolicy, SeriesOrder, Spheroid, CalculationType>>\n{\n    struct altered_strategy\n        : strategies::relate::geographic<FormulaPolicy, Spheroid, CalculationType>\n    {\n        typedef strategies::relate::geographic<FormulaPolicy, Spheroid, CalculationType> base_t;\n\n        explicit altered_strategy(Spheroid const& spheroid)\n            : base_t(spheroid)\n        {}\n\n        template <typename Geometry>\n        auto area(Geometry const&) const\n        {\n            return strategy::area::geographic\n                <\n                    FormulaPolicy, SeriesOrder, Spheroid, CalculationType\n                >(base_t::m_spheroid);\n        }\n\n        using base_t::relate;\n\n        auto relate(/*...*/) const\n        {\n            return strategy::intersection::geographic_segments\n                <\n                    FormulaPolicy, SeriesOrder, Spheroid, CalculationType\n                >(base_t::m_spheroid);\n        }\n    };\n\n    static auto get(strategy::intersection::geographic_segments<FormulaPolicy, SeriesOrder, Spheroid, CalculationType> const& s)\n    {\n        return altered_strategy(s.model());\n    }\n};\n\ntemplate <typename FormulaPolicy, typename Spheroid, typename CalculationType>\nstruct strategy_converter<strategy::within::geographic_point_box_by_side<FormulaPolicy, Spheroid, CalculationType>>\n{\n    struct altered_strategy\n        : strategies::relate::geographic<FormulaPolicy, Spheroid, CalculationType>\n    {\n        altered_strategy(Spheroid const& spheroid)\n            : strategies::relate::geographic<FormulaPolicy, Spheroid, CalculationType>(spheroid)\n        {}\n\n        template <typename Geometry1, typename Geometry2>\n        auto covered_by(Geometry1 const&, Geometry2 const&,\n                        std::enable_if_t\n                            <\n                                util::is_pointlike<Geometry1>::value\n                                && util::is_box<Geometry2>::value\n                            > * = nullptr) const\n        {\n            return strategy::covered_by::geographic_point_box_by_side\n                <\n                    FormulaPolicy, Spheroid, CalculationType\n                >(this->model());\n        }\n\n        template <typename Geometry1, typename Geometry2>\n        auto within(Geometry1 const&, Geometry2 const&,\n                    std::enable_if_t\n                        <\n                            util::is_pointlike<Geometry1>::value\n                            && util::is_box<Geometry2>::value\n                        > * = nullptr) const\n        {\n            return strategy::within::geographic_point_box_by_side\n                <\n                    FormulaPolicy, Spheroid, CalculationType\n                >(this->model());\n        }\n    };\n\n    static auto get(strategy::covered_by::geographic_point_box_by_side<FormulaPolicy, Spheroid, CalculationType> const& s)\n    {\n        return altered_strategy(s.model());\n    }\n\n    static auto get(strategy::within::geographic_point_box_by_side<FormulaPolicy, Spheroid, CalculationType> const& s)\n    {\n        return altered_strategy(s.model());\n    }\n};\n\ntemplate <typename CalculationType>\nstruct strategy_converter<strategy::covered_by::geographic_point_box_by_side<CalculationType>>\n    : strategy_converter<strategy::within::geographic_point_box_by_side<CalculationType>>\n{};\n\n\n} // namespace services\n\n}} // namespace strategies::relate\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_RELATE_GEOGRAPHIC_HPP\n", "meta": {"hexsha": "4f556e953b564c0eb1874da1256a0a4b1ba5564e", "size": 12041, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/boost/geometry/strategies/relate/geographic.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/strategies/relate/geographic.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/strategies/relate/geographic.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": 34.0141242938, "max_line_length": 128, "alphanum_fraction": 0.5921435097, "num_tokens": 2522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.296936794421029}}
{"text": "// MIT License\n//\n// Copyright (c) 2021 Oliver Schick\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 MPO19_CLUSTERING_22072020\n#define MPO19_CLUSTERING_22072020\n\n#include <mpo19/typedefs.hpp>\n#include <mpo19/cluster.hpp>\n#include <boost/range/algorithm.hpp>\n\nnamespace mpo19{\ntemplate<typename Linkage>\nstruct hierarchical_clustering : public Linkage {\n\n    using dendrogram_t  = std::vector<cluster>;\n\n    using Linkage::Linkage;\n\n    dendrogram_t operator()(size_t t)\n    {\n        using std::swap;\n\n        size_t n = Linkage::get_input_size();\n\n        assert(t < n && \"t must be strictly smaller than n\");\n\n        dendrogram_t dendrogram;\n\n        //Initialize dendrogram\n        for(index_t i = 0; i != index_t(n); ++i) {\n            dendrogram.emplace_back(cluster::leaf_t(i));\n        }\n\n        for(size_t l = 0; l < n - t; ++l) {\n            //get indices of clusters to be merged\n            auto p = get_merge_indices();\n\n            size_t i = std::get<0>(p);\n            size_t j = std::get<1>(p);\n\n            assert(i < j && \"By convention i should be smaller than j\");\n            assert(0 <= i && i < n && \"i should be between 0 and n\");\n            assert(0 <= j && j < n && \"j should be between 0 and n\");\n\n            //merge the two clusters at position i and j\n            merge(dendrogram[i], dendrogram[j], l + 1);\n        }\n        \n        assert(dendrogram.size() == n && \"dendrogram should be of size n here\");\n        //Erase all clusters that only refer to other clusters through a pointer\n        dendrogram.erase(\n        boost::remove_if(dendrogram, [](cluster const& c) {\n            return !c.is_cluster();\n        })\n        , dendrogram.end());\n        \n        assert(dendrogram.size() == t && \"dendrogram should be of size t here\");\n\n        return dendrogram;\n    }\n    \n    dendrogram_t partial_evaluation(size_t t, dendrogram_t dendrogram = dendrogram_t{})\n    {\n        using std::swap;\n        using boost::range::count_if;\n\n        size_t n = Linkage::get_input_size();\n\n        assert(t < n && \"t must be strictly smaller than n\");\n\n        size_t start;\n        if(dendrogram.empty()) {\n            //Initialize dendrogram\n            for(index_t i = 0; i != index_t(n); ++i) {\n                dendrogram.emplace_back(cluster::leaf_t(i));\n            }\n            start = 0;\n        }\n        else {\n            assert(dendrogram.size() == n);\n            start = n - count_if(dendrogram, [](cluster const& c){\n                return c.is_cluster();\n            });\n        }\n\n        for(size_t l = start; l < n - t; ++l) {\n            //get indices of clusters to be merged\n            auto p = get_merge_indices();\n\n            size_t i = std::get<0>(p);\n            size_t j = std::get<1>(p);\n\n            assert(i < j && \"By convention i should be smaller than j\");\n            assert(0 <= i && i < n && \"i should be between 0 and n\");\n            assert(0 <= j && j < n && \"j should be between 0 and n\");\n\n            //merge the two clusters at position i and j\n            merge(dendrogram[i], dendrogram[j], l + 1);\n        }\n\n        assert(dendrogram.size() == n && \"dendrogram should be of size n here\");\n\n        return dendrogram;\n    }\n\nprivate:\n    using Linkage::get_merge_indices;\n};\n\n}\n#endif //MPO19_CLUSTERING_22072020\n", "meta": {"hexsha": "586570473b60afd9b7b923c7f6c550aac09e05f0", "size": 4327, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "hc_protocols/include/mpo19/clustering.hpp", "max_stars_repo_name": "encryptogroup/SoK_ppClustering", "max_stars_repo_head_hexsha": "6b008a09bfe3f3b8074e24059ac3e2aa6b87f227", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-18T08:09:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T05:41:24.000Z", "max_issues_repo_path": "hc_protocols/include/mpo19/clustering.hpp", "max_issues_repo_name": "encryptogroup/SoK_ppClustering", "max_issues_repo_head_hexsha": "6b008a09bfe3f3b8074e24059ac3e2aa6b87f227", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hc_protocols/include/mpo19/clustering.hpp", "max_forks_repo_name": "encryptogroup/SoK_ppClustering", "max_forks_repo_head_hexsha": "6b008a09bfe3f3b8074e24059ac3e2aa6b87f227", "max_forks_repo_licenses": ["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.0305343511, "max_line_length": 87, "alphanum_fraction": 0.6031892766, "num_tokens": 1038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.2968040682220356}}
{"text": "// Copyright 2018 Hans Dembinski\r\n//\r\n// Distributed under the Boost Software License, version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_HISTOGRAM_ACCUMULATORS_SUM_HPP\r\n#define BOOST_HISTOGRAM_ACCUMULATORS_SUM_HPP\r\n\r\n#include <boost/histogram/fwd.hpp>\r\n#include <cmath>\r\n#include <type_traits>\r\n\r\nnamespace boost {\r\nnamespace histogram {\r\nnamespace accumulators {\r\n\r\n/**\r\n  Uses Neumaier algorithm to compute accurate sums.\r\n\r\n  The algorithm uses memory for two floats and is three to\r\n  five times slower compared to a simple floating point\r\n  number used to accumulate a sum, but the relative error\r\n  of the sum is at the level of the machine precision,\r\n  independent of the number of samples.\r\n\r\n  A. Neumaier, Zeitschrift fuer Angewandte Mathematik\r\n  und Mechanik 54 (1974) 39-51.\r\n*/\r\ntemplate <typename RealType>\r\nclass sum {\r\npublic:\r\n  sum() = default;\r\n\r\n  /// Initialize sum to value\r\n  explicit sum(const RealType& value) noexcept : large_(value) {}\r\n\r\n  /// Set sum to value\r\n  sum& operator=(const RealType& value) noexcept {\r\n    large_ = value;\r\n    small_ = 0;\r\n    return *this;\r\n  }\r\n\r\n  /// Increment sum by one\r\n  sum& operator++() { return operator+=(1); }\r\n\r\n  /// Increment sum by value\r\n  sum& operator+=(const RealType& value) {\r\n    auto temp = large_ + value; // prevent optimization\r\n    if (std::abs(large_) >= std::abs(value))\r\n      small_ += (large_ - temp) + value;\r\n    else\r\n      small_ += (value - temp) + large_;\r\n    large_ = temp;\r\n    return *this;\r\n  }\r\n\r\n  /// Scale by value\r\n  sum& operator*=(const RealType& value) {\r\n    large_ *= value;\r\n    small_ *= value;\r\n    return *this;\r\n  }\r\n\r\n  template <class T>\r\n  bool operator==(const sum<T>& rhs) const noexcept {\r\n    return large_ == rhs.large_ && small_ == rhs.small_;\r\n  }\r\n\r\n  template <class T>\r\n  bool operator!=(const T& rhs) const noexcept {\r\n    return !operator==(rhs);\r\n  }\r\n\r\n  /// Return large part of the sum.\r\n  const RealType& large() const { return large_; }\r\n\r\n  /// Return small part of the sum.\r\n  const RealType& small() const { return small_; }\r\n\r\n  // allow implicit conversion to RealType\r\n  operator RealType() const { return large_ + small_; }\r\n\r\n  template <class Archive>\r\n  void serialize(Archive&, unsigned /* version */);\r\n\r\nprivate:\r\n  RealType large_ = RealType();\r\n  RealType small_ = RealType();\r\n};\r\n\r\n} // namespace accumulators\r\n} // namespace histogram\r\n} // namespace boost\r\n\r\n#ifndef BOOST_HISTOGRAM_DOXYGEN_INVOKED\r\nnamespace std {\r\ntemplate <class T, class U>\r\nstruct common_type<boost::histogram::accumulators::sum<T>,\r\n                   boost::histogram::accumulators::sum<U>> {\r\n  using type = boost::histogram::accumulators::sum<common_type_t<T, U>>;\r\n};\r\n} // namespace std\r\n#endif\r\n\r\n#endif\r\n", "meta": {"hexsha": "67c767cf7216f01290423f996ce015906fc09d8c", "size": 2819, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dep/win/include/boost/histogram/accumulators/sum.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/histogram/accumulators/sum.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/histogram/accumulators/sum.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": 26.1018518519, "max_line_length": 73, "alphanum_fraction": 0.6598084427, "num_tokens": 706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.2967681312105448}}
{"text": "/*\n * Copyright Nick Thompson, 2020\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_MATH_INTERPOLATORS_QUINTIC_HERMITE_HPP\n#define BOOST_MATH_INTERPOLATORS_QUINTIC_HERMITE_HPP\n#include <algorithm>\n#include <stdexcept>\n#include <memory>\n#include <boost/math/interpolators/detail/quintic_hermite_detail.hpp>\n\nnamespace boost {\nnamespace math {\nnamespace interpolators {\n\ntemplate<class RandomAccessContainer>\nclass quintic_hermite {\npublic:\n    using Real = typename RandomAccessContainer::value_type;\n    quintic_hermite(RandomAccessContainer && x, RandomAccessContainer && y, RandomAccessContainer && dydx, RandomAccessContainer && d2ydx2)\n     : impl_(std::make_shared<detail::quintic_hermite_detail<RandomAccessContainer>>(std::move(x), std::move(y), std::move(dydx), std::move(d2ydx2)))\n    {}\n\n    Real operator()(Real x) const\n    {\n        return impl_->operator()(x);\n    }\n\n    Real prime(Real x) const\n    {\n        return impl_->prime(x);\n    }\n\n    Real double_prime(Real x) const\n    {\n        return impl_->double_prime(x);\n    }\n\n    friend std::ostream& operator<<(std::ostream & os, const quintic_hermite & m)\n    {\n        os << *m.impl_;\n        return os;\n    }\n\n    void push_back(Real x, Real y, Real dydx, Real d2ydx2)\n    {\n        impl_->push_back(x, y, dydx, d2ydx2);\n    }\n\n    int64_t bytes() const\n    {\n        return impl_->bytes() + sizeof(impl_);\n    }\n\n    std::pair<Real, Real> domain() const\n    {\n        return impl_->domain();\n    }\n\nprivate:\n    std::shared_ptr<detail::quintic_hermite_detail<RandomAccessContainer>> impl_;\n};\n\ntemplate<class RandomAccessContainer>\nclass cardinal_quintic_hermite {\npublic:\n    using Real = typename RandomAccessContainer::value_type;\n    cardinal_quintic_hermite(RandomAccessContainer && y, RandomAccessContainer && dydx, RandomAccessContainer && d2ydx2, Real x0, Real dx)\n     : impl_(std::make_shared<detail::cardinal_quintic_hermite_detail<RandomAccessContainer>>(std::move(y), std::move(dydx), std::move(d2ydx2), x0, dx))\n    {}\n\n    inline Real operator()(Real x) const {\n        return impl_->operator()(x);\n    }\n\n    inline Real prime(Real x) const {\n        return impl_->prime(x);\n    }\n\n    inline Real double_prime(Real x) const\n    {\n        return impl_->double_prime(x);\n    }\n\n    int64_t bytes() const\n    {\n        return impl_->bytes() + sizeof(impl_);\n    }\n\n    std::pair<Real, Real> domain() const\n    {\n        return impl_->domain();\n    }\n\nprivate:\n    std::shared_ptr<detail::cardinal_quintic_hermite_detail<RandomAccessContainer>> impl_;\n};\n\ntemplate<class RandomAccessContainer>\nclass cardinal_quintic_hermite_aos {\npublic:\n    using Point = typename RandomAccessContainer::value_type;\n    using Real = typename Point::value_type;\n    cardinal_quintic_hermite_aos(RandomAccessContainer && data, Real x0, Real dx)\n     : impl_(std::make_shared<detail::cardinal_quintic_hermite_detail_aos<RandomAccessContainer>>(std::move(data), x0, dx))\n    {}\n\n    inline Real operator()(Real x) const\n    {\n        return impl_->operator()(x);\n    }\n\n    inline Real prime(Real x) const\n    {\n        return impl_->prime(x);\n    }\n\n    inline Real double_prime(Real x) const\n    {\n        return impl_->double_prime(x);\n    }\n\n    int64_t bytes() const\n    {\n        return impl_->bytes() + sizeof(impl_);\n    }\n\n    std::pair<Real, Real> domain() const\n    {\n        return impl_->domain();\n    }\nprivate:\n    std::shared_ptr<detail::cardinal_quintic_hermite_detail_aos<RandomAccessContainer>> impl_;\n};\n\n}\n}\n}\n#endif\n", "meta": {"hexsha": "c0ba067de2411502a47af16fa1db58081985aaca", "size": 3664, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/interpolators/quintic_hermite.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": 310.0, "max_stars_repo_stars_event_min_datetime": "2017-02-02T09:14:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T06:50:11.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/interpolators/quintic_hermite.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": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/interpolators/quintic_hermite.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": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 25.6223776224, "max_line_length": 152, "alphanum_fraction": 0.6754912664, "num_tokens": 956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.2967681312105448}}
{"text": "#ifndef LOOKUP_TABLE_HH__\n#define LOOKUP_TABLE_HH__\n\n#include <vector>\n\n#include <boost/math/distributions/chi_squared.hpp>\n\nclass LookupTable\n{\npublic:\n\n  /** Creates a new lookup table for the given marginals */\n  LookupTable( unsigned n, unsigned n1 );\n\n  /**\n     Returns the minimum attainable $p$-value of a given marginal\n     value.\n  */\n\n  long double operator[]( unsigned rs ) const noexcept\n  {\n    return _values[rs];\n  }\n\n  // Attributes --------------------------------------------------------\n\n  unsigned n()  const noexcept { return _n;  }\n  unsigned n1() const noexcept { return _n1; }\n\nprivate:\n  unsigned _n  = 0;\n  unsigned _n1 = 0;\n\n  /** Shared distribution for calculating $p$-values */\n  static boost::math::chi_squared_distribution<long double> _chi2;\n\n  /** Maps marginals to $p$-values */\n  std::vector<long double> _values;\n};\n\n#endif\n", "meta": {"hexsha": "901e6b438d651b5b5a09cf4c39aa933b2f646616", "size": 863, "ext": "hh", "lang": "C++", "max_stars_repo_path": "code/cpp/include/LookupTable.hh", "max_stars_repo_name": "vishalbelsare/S3M", "max_stars_repo_head_hexsha": "2df2257da9ab80b2b89251fd47676d04f2675532", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 52.0, "max_stars_repo_stars_event_min_datetime": "2018-07-05T14:43:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T04:26:42.000Z", "max_issues_repo_path": "code/cpp/include/LookupTable.hh", "max_issues_repo_name": "vishalbelsare/S3M", "max_issues_repo_head_hexsha": "2df2257da9ab80b2b89251fd47676d04f2675532", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-06-12T13:59:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-27T08:21:50.000Z", "max_forks_repo_path": "code/cpp/include/LookupTable.hh", "max_forks_repo_name": "vishalbelsare/S3M", "max_forks_repo_head_hexsha": "2df2257da9ab80b2b89251fd47676d04f2675532", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-07-25T16:55:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-29T06:25:15.000Z", "avg_line_length": 20.5476190476, "max_line_length": 72, "alphanum_fraction": 0.6419466976, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.2967681312105448}}
{"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 \"write_numpy.hpp\"\n\n#include <fstream>\n\n#include <boost/algorithm/string/join.hpp>\n#include <boost/format.hpp>\n\n#include <reversible/pauli_tags.hpp>\n#include <reversible/target_tags.hpp>\n\nnamespace cirkit\n{\n\n/******************************************************************************\n * Types                                                                      *\n ******************************************************************************/\n\n/******************************************************************************\n * Private functions                                                          *\n ******************************************************************************/\n\nstd::string identity_padding( const std::string& matrix, unsigned from, unsigned to, unsigned lines )\n{\n  std::vector<std::string> gates;\n\n  if ( from > 0u )\n  {\n    gates.push_back( boost::str( boost::format( \"np.identity(%d)\" ) % ( 1 << from ) ) );\n  }\n\n  gates.push_back( matrix );\n\n  if ( to + 1u < lines )\n  {\n    gates.push_back( boost::str( boost::format( \"np.identity(%d)\" ) % ( 1 << ( lines - to - 1u ) ) ) );\n  }\n\n  switch ( gates.size() )\n  {\n  case 1u:\n    return gates.front();\n\n  case 2u:\n    return boost::str( boost::format( \"np.kron(%s, %s)\" ) % gates[0u] % gates[1u] );\n\n  default:\n    return boost::str( boost::format( \"nkron(%s)\" ) % boost::join( gates, \", \" ) );\n  }\n}\n\n/******************************************************************************\n * Public functions                                                           *\n ******************************************************************************/\n\nvoid write_numpy( const circuit& circ, std::ostream& os )\n{\n  const auto n = circ.lines();\n\n  os << \"#!/usr/bin/env python3\" << std::endl << std::endl;\n  os << \"import numpy as np\" << std::endl;\n  os << \"from functools import reduce\" << std::endl << std::endl;\n\n  os << \"X = np.array([[0, 1], [1, 0]])\" << std::endl;\n  os << \"H = 1 / np.sqrt(2) * np.array([[1, 1], [1, -1]])\" << std::endl;\n  os << \"T = np.array([[1, 0], [0, np.exp(1j * np.pi / 4)]])\" << std::endl;\n  os << \"Tdag = np.array([[1, 0], [0, -np.exp(1j * np.pi / 4)]])\" << std::endl;\n  os << \"zc = np.array([[1, 0], [0, 0]])\" << std::endl;\n  os << \"oc = np.array([[0, 0], [0, 1]])\" << std::endl;\n  os << std::endl;\n\n  os << \"def nkron(*args):\" << std::endl;\n  os << \"  return reduce(np.kron, args)\" << std::endl;\n  os << std::endl;\n\n  os << \"gates = []\" << std::endl << std::endl;\n\n  for ( const auto& g : circ )\n  {\n    const auto target = g.targets().front();\n\n    if ( is_toffoli( g ) && g.controls().size() == 1u && g.controls().front().polarity() )\n    {\n      const auto control = g.controls().front().line();\n\n      if ( control < target )\n      {\n        const auto act = target - control;\n        const auto gate = boost::str( boost::format( \"np.kron(zc, np.identity(%d)) + nkron(oc, np.identity(%d), X)\" ) % ( 1 << act ) % ( 1 << ( act - 1 ) ) );\n        os << boost::format( \"gates.append(%s)\" ) % identity_padding( gate, control, target, n ) << std::endl;\n      }\n      else\n      {\n        const auto act = control - target;\n        const auto gate = boost::str( boost::format( \"np.kron(np.identity(%d), zc) + nkron(X, np.identity(%d), oc)\" ) % ( 1 << act ) % ( 1 << ( act - 1 ) ) );\n        os << boost::format( \"gates.append(%s)\" ) % identity_padding( gate, target, control, n ) << std::endl;\n      }\n    }\n    else if ( is_hadamard( g ) )\n    {\n      os << boost::format( \"gates.append(%s)\" ) % identity_padding( \"H\", target, target, n ) << std::endl;\n    }\n    else if ( is_pauli( g ) )\n    {\n      const auto pauli = boost::any_cast<pauli_tag>( g.type() );\n      switch ( pauli.axis )\n      {\n      case pauli_axis::Z:\n        if ( pauli.root == 4u )\n        {\n          os << boost::format( \"gates.append(%s)\" ) % identity_padding( pauli.adjoint ? \"Tdag\" : \"T\", target, target, n ) << std::endl;\n        }\n        else\n        {\n          os << \"# unsupported gate\" << std::endl;\n        }\n        break;\n      default:\n        os << \"# unsupported gate\" << std::endl;\n        break;\n      }\n    }\n    else\n    {\n      os << \"# unsupported gate\" << std::endl;\n    }\n  }\n\n  os << std::endl;\n  os << \"circuit = reduce(np.dot, reversed(gates))\" << std::endl;\n  os << \"print(np.round(circuit))\" << std::endl;\n}\n\nvoid write_numpy( const circuit& circ, const std::string& filename )\n{\n  std::ofstream os( filename.c_str(), std::ofstream::out );\n\n  write_numpy( circ, os );\n\n  os.close();\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": "6159bf8743af926545dfa3ab8137c459341c5cc0", "size": 5835, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "addons/cirkit-addon-reversible/src/reversible/io/write_numpy.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/io/write_numpy.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/io/write_numpy.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": 33.3428571429, "max_line_length": 158, "alphanum_fraction": 0.5189374464, "num_tokens": 1533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5039061705290806, "lm_q1q2_score": 0.2967448667514172}}
{"text": "/* Copyright (c) 2012, Julian Straub <jstraub@csail.mit.edu>\n * Licensed under the MIT license. See LICENSE.txt or \n * http://www.opensource.org/licenses/mit-license.php */\n\n#pragma once\n\n#include \"hdp_base.hpp\"\n#include \"hdp_var_base.hpp\"\n\n#include \"random.hpp\"\n#include \"baseMeasure.hpp\"\n#include \"probabilityHelpers.hpp\"\n\n#include <stddef.h>\n#include <stdint.h>\n#include <typeinfo>\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/beta.hpp>\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n\n/*\n * this one assumes that the number of words per document is \n * smaller than the dictionary size\n *\n * http://en.wikipedia.org/wiki/Virtual_inheritance\n */\ntemplate <class U>\nclass HDP_var: public HDP<U>, public virtual HDP_var_base\n{\n  public:\n\n    HDP_var(const BaseMeasure<U>& base, double alpha, double omega)\n      : HDP_var_base(0,0,0), HDP<U>(base, alpha, omega)\n    {};\n\n    ~HDP_var()\n    {};\n\n    // interface mainly for python\n    uint32_t addDoc(const Mat<U>& x_i)\n    {\n      uint32_t x_ind = HDP<U>::addDoc(x_i);\n      // TODO: potentially slow\n      // add the index of the added x_i\n      mInd2Proc.resize(mInd2Proc.n_elem+1);\n      mInd2Proc[mInd2Proc.n_elem-1] = x_ind;\n      return x_ind;\n    };\n\n    /* \n     * Initializes the corpus level parameters mA and mLambda according \n     * to Blei's Stochastic Variational paper\n     *\n     * @param D is the assumed number of documents for init\n     */\n    void initCorpusParams(uint32_t Nw, uint32_t K, uint32_t T, uint32_t D)\n    {\n\n      mT = T;\n      mK = K;\n      mNw = Nw;\n\n      mA.ones(K,2);\n      mA.col(1) *= HDP<U>::mOmega; \n\n      // initialize lambda\n      HDP<U>::mLambda.init(HDP<U>::mH0,K); // initialize the priors of the topics from the base measure.\n    \n//      HDP<U>::mLambda.zeros(K,Nw);\n//      GammaRnd gammaRnd(1.0, 1.0);\n//      for (uint32_t k=0; k<K; ++k){\n//        for (uint32_t w=0; w<Nw; ++w) HDP<U>::mLambda(k,w) = gammaRnd.draw();\n//        HDP<U>::mLambda.row(k) += ((Dir*)(&mH0))->mAlphas;\n//      }\n    };\n\n    /* From: Online Variational Inference for the HDP\n     * method for \"one shot\" computation without storing data in this class\n     *  Nw: number of different words\n     *  kappa=0.9: forgetting rate\n     *  uint32_t T=10; // truncation on document level\n     *  uint32_t K=100; // truncation on corpus level\n     *  S = batch size\n     */\n    void densityEst(const vector<Mat<U> >& x, uint32_t Nw, \n        double kappa, uint32_t K, uint32_t T, uint32_t S)\n    {\n      cout<<\"densityEstimate with: K=\"<<K<<\"; T=\"<<T<<\"; kappa=\"<<kappa<<\"; Nw=\"<<Nw<<\"; S=\"<<S<<endl;\n\n      HDP<U>::mX = x;\n      uint32_t D=HDP<U>::mX.size();\n      cout<<\"D=\"<<D<<endl;\n      cout<<\"mX[0].shape= \"<<HDP<U>::mX[0].n_rows<<\"x\"<<HDP<U>::mX[0].n_cols<<endl;\n\n      mInd2Proc = linspace<Row<uint32_t> >(0,D-1,D);\n\n      mT = T;\n      mK = K;\n      mNw = Nw;\n\n      initCorpusParams(mNw,mK,mT,D);\n      cout<<\"Init of corpus params done\"<<endl;\n      Row<uint32_t> ind = updateEst_batch(mInd2Proc,mZeta,mPhi,mGamma,mA,HDP<U>::mLambda,mPerp,HDP<U>::mOmega,kappa,S,true);\n//      cout<<\"mPhi -> D=\"<<mPhi.size()<<endl;\n//      cout<<\"mPhi -> D=\"<<HDP_var_base::mPhi.size()<<endl;\n//      cout<<\"mPerp=\"<<mPerp.t()<<endl;\n\n      Mat<double> pi(D,T);\n      Mat<double> sigPi(D,T+1);\n      Mat<uint32_t> c(D,T);\n      getDocTopics(pi,sigPi,c);\n//      cout<<\"c:\"<<c<<endl;\n\n      mInd2Proc.set_size(0); // all processed\n\n    };\n\n    /*\n     * compute density estimate based on data previously fed into the class using addDoc\n     */\n    bool densityEst(uint32_t Nw, double kappa, uint32_t K, uint32_t T, uint32_t S)\n    {\n      if(HDP<U>::mX.size() > 0)\n      {\n        densityEst(HDP<U>::mX,Nw,kappa,K,T,S);\n        //TODO: return p_d(x)\n        return true;\n      }else{\n        return false;\n      }\n    };\n\n\n    /* \n     * updated the estimate using newly added docs in mX\n     * \"newly added\": the ones that are indicated in mInd2Proc\n     */\n    bool updateEst_batch(double kappa, uint32_t S)\n    {\n      uint32_t Db=mInd2Proc.n_elem;\n      if (Db >0){  \n        cout<<\"updatedEstimate with: K=\"<<mK<<\"; T=\"<<mT<<\"; kappa=\"<<kappa<<\"; Nw=\"<<mNw<<\"; S=\"<<S<<endl;\n        vector<Mat<double> > zeta; // will get resized accordingly inside updateEst_batch\n        vector<Mat<double> > phi;\n        vector<Mat<double> > gamma;\n        Col<double> perp;\n\n        Row<uint32_t> ind = updateEst_batch(mInd2Proc,zeta,phi,gamma,mA,HDP<U>::mLambda,perp,HDP<U>::mOmega,kappa,S);\n\n        mZeta.resize(mZeta.size()+Db);\n        mPhi.resize(mPhi.size()+Db);\n        mGamma.resize(mGamma.size()+Db);\n        mPerp.resize(mPerp.n_elem+Db);\n        mPerp.rows(mPerp.n_elem-Db,mPerp.n_elem-1) = perp;\n        for (uint32_t i=0; i<ind.n_elem; ++i){\n          mZeta[ind[i]] = zeta[i];\n          mPhi[ind[i]] = phi[i];\n          mGamma[ind[i]] = gamma[i];\n        }\n\n        mInd2Proc.set_size(0); // all processed\n\n        return true;\n      }else{\n        cout<<\"add more documents before starting to process\"<<endl;\n      }\n      return false;\n    };\n\n    /*\n     * after an initial densitiy estimate has been made using densityEst()\n     * can use this to update the estimate with information from additional x \n     */\n    bool  updateEst(const Mat<U>& x, double kappa)\n    {\n      if (HDP<U>::mX.size() > 0 && HDP<U>::mX.size() == mPhi.size()) { // this should indicate that there exists an estimate already\n        uint32_t N = x.n_cols;\n        uint32_t T = mT; \n        uint32_t K = mK;\n        HDP<U>::mX.push_back(x);\n        mZeta.push_back(Mat<double>(T,K));\n        mPhi.push_back(Mat<double>(N,T));\n        //    mZeta.set_size(T,K);\n        //    mPhi.set_size(N,T);\n        mGamma.push_back(Mat<double>(T,2));\n        uint32_t d = HDP<U>::mX.size()-1;\n        mPerp.resize(d+1);\n\n\n        if(updateEst(HDP<U>::mX[d],mZeta[d],mPhi[d],mGamma[d],mA,HDP<U>::mLambda,HDP<U>::mOmega,d,kappa))\n        {\n          mPerp[d] = 0.0;\n          for (uint32_t i=0; i < HDP<U>::mX_ho.size(); ++i)\n          {    \n            Row<double> logP=logP_w(HDP<U>::mX[d],mPhi[d], mZeta[d], mGamma[d], HDP<U>::mLambda);\n            mPerp[d] += HDP<U>::perplexity(HDP<U>::mX_ho[i], logP);\n            //mPerp[d] += perplexity(mX_ho[i], mZeta[d], mPhi[d], mGamma[d], HDP<U>::mLambda);\n          }\n          mPerp[d] /= double(HDP<U>::mX_ho.size());\n          cout<<\"Perplexity=\"<<mPerp[d]<<endl;\n          return true; \n        }else{\n          return false;\n        } \n      }else{\n        return false;\n      }\n    };\n\n    /*\n     *\n     */\n    bool updateEst(const Mat<U>& x, Mat<double>& zeta, Mat<double>& phi, Mat<double>& gamma, Mat<double>& a, DistriContainer<U>& lambda, double omega, uint32_t d, double kappa)\n    {\n      uint32_t D = d+1; // assume that doc d is appended to the end  \n//      uint32_t Nw = lambda.n_cols;\n      uint32_t T = zeta.n_rows;\n      uint32_t K = zeta.n_cols;\n\n      Mat<double> eLogBeta(mK,x.n_cols); //TODO\n      Col<double> digam_lamb_sum(mK);\n\n      compElogBeta(eLogBeta,  lambda, x);\n\n      Col<double> eLogSig_a(K);\n      compElogSig(eLogSig_a, a);\n\n      //    cout<<\"---------------- Document \"<<d<<\" N=\"<<N<<\" -------------------\"<<endl;\n      initZeta(zeta,eLogBeta);\n      initPhi(phi,zeta,eLogBeta);\n\n      if(!is_finite(zeta))\n      {\n        cout<<\"updateEst::a=\"<<size(a)<<endl<<a;\n        cout<<\"updateEst::lambda=\"<<lambda[0]->asRow();\n        cout<<\"updateEst::x=\"<<size(x)<<endl<<x;\n        cout<<\"zeta_init=\"<<zeta<<endl;\n        cout<<\"phi_init=\"<<phi<<endl;\n        cout<<\"eLogBeta=\"<<eLogBeta<<endl;\n        exit(0);\n      }\n\n      // ------------------------ doc level updates --------------------\n      bool converged = false;\n      Col<double> eLogSig_gam(T);\n      Mat<double> gamma_prev(T,2);\n      gamma_prev.ones();\n\n      uint32_t o=0;\n      while(!converged){\n        //      cout<<\"-------------- Iterating local params #\"<<o<<\" -------------------------\"<<endl;\n        updateGamma(gamma,phi);\n\n        if (!is_finite(gamma)){\n          cout<<\"gamma=\"<<gamma;\n          cout<<\"phi=\"<<phi;\n          exit(1);\n        }\n\n\n        compElogSig(eLogSig_gam,gamma); // precompute \n\n        updateZeta(zeta,phi,eLogSig_a,eLogBeta);\n        updatePhi(phi,zeta,eLogSig_gam,eLogBeta);\n\n        converged = (accu(gamma_prev != gamma))==0 || o>60 ;\n        gamma_prev = gamma;\n        ++o;\n\n        if(!is_finite(zeta))\n        {\n          cout<<\"o=\"<<o<<endl;\n          cout<<\"zeta=\"<<zeta.row(0)<<\" |.|=\"<<sum(exp(zeta.row(0)))<<endl;\n          cout<<\"phi=\"<<phi.row(0)<<\" |.|=\"<<sum(exp(phi.row(0)))<<endl;\n          exit(0);\n        }\n      }\n\n      //    cout<<\" --------------------- natural gradients --------------------------- \"<<endl;\n      //    cout<<\"\\tD=\"<<D<<\" omega=\"<<omega<<endl;\n      DistriContainer<U> d_lambda(HDP<U>::mH0,K);\n      Mat<double> d_a(K,2); \n      computeNaturalGradients(d_lambda, d_a, zeta, phi, omega, D, x);\n\n      cout<<\"update::d_lambda:\"<<d_lambda.toMat().rows(0,5);\n      cout<<\"update::lambda:\"<<lambda.toMat().rows(0,5);\n\n      //    cout<<\" ------------------- global parameter updates: ---------------\"<<endl;\n      double ro = exp(-kappa*log(1+double(d+1)));\n      //    cout<<\"\\tro=\"<<ro<<endl;\n      for (uint32_t k=0; k<mK; ++k)\n        lambda[k]->fromRow( (1.0-ro)*lambda[k]->asRow() + ro* d_lambda[k]->asRow());\n\n      //lambda = (1.0-ro)*lambda + ro*d_lambda;\n      a = (1.0-ro)*a+ ro*d_a;\n      return true;\n    };\n\n\n    /*\n     * Updates the estimate using mini batches\n     * @param ind_x indices of docs to process within docs mX. !these are assumed to be in order!\n     * @param sameIndAsX == true -> zeta,phi,gamma have same indices as x (ind_x). This typically happens for the initial batch update. Setting this to true eliminates the need of reordering the results afterwords to match the indices of the docs x.\n     * @return the randomly shuffled indices to show how the data was processed -> this allows association of zetas, phis and gammas with docs in mX\n     */\n    Row<uint32_t> updateEst_batch(const Row<uint32_t>& ind_x, vector<Mat<double> >& zeta, vector<Mat<double> >& phi, vector<Mat<double> >& gamma, Mat<double>& a, DistriContainer<U>& lambda, Col<double>& perp, double omega, double kappa, uint32_t S, bool sameIndAsX=false)\n    {\n      uint32_t d_0 = min(ind_x); // thats the doc number that we start with -> needed for ro computation; assumes that all indices in mX prior to d_0 have already been processed.\n      uint32_t D= max(ind_x)+1; // D is the maximal index of docs that we are processing +1\n\n      Row<uint32_t> ind = shuffle(ind_x,1);\n//        cout<<\"ind_x: \"<<ind_x.cols(0,S)<<endl;\n//        cout<<\"ind  : \"<<ind.cols(0,S)<<endl;\n\n      zeta.resize(ind.n_elem,Mat<double>(mT,mK));\n      phi.resize(ind.n_elem);\n      gamma.resize(ind.n_elem,Mat<double>(mT,2));\n      perp.zeros(ind.n_elem);\n\n      for (uint32_t dd=0; dd<ind.n_elem; dd += S)\n      {\n        DistriContainer<U> db_lambda(HDP<U>::mH0,mK);\n\n        Mat<double> db_a(mK,2); \n        db_a.zeros();\n\n        Col<double> eLogSig_a(mK);\n        compElogSig(eLogSig_a, a);\n\n#pragma omp parallel for schedule(dynamic) \n        for (uint32_t db=dd; db<min(dd+S,ind.n_elem); db++)\n        {\n          uint32_t d=ind[db];  \n          const Mat<U>& x_d = HDP<U>::mX[d];\n          uint32_t dout=sameIndAsX?d:db;\n          uint32_t N=x_d.n_cols;\n          //      cout<<\"---------------- Document \"<<d<<\" N=\"<<N<<\" -------------------\"<<endl;\n\n          cout<<\"-- db=\"<<db<<\" d=\"<<d<<\" N=\"<<N<<endl;\n\n          Mat<double> eLogBeta(mK,x_d.n_cols);\n          Col<double> digam_lamb_sum(mK);\n          compElogBeta(eLogBeta, lambda, x_d);\n\n          //Mat<double> zeta(T,K);\n          phi[dout].resize(N,mT);\n          initZeta(zeta[dout],eLogBeta);\n          initPhi(phi[dout],zeta[dout],eLogBeta);\n\n//            cout<<\"zeta_init=\"<<zeta[dout]<<endl;\n//            cout<<\"phi_init=\"<<phi[dout]<<endl;\n//            cout<<\"eLogBeta=\"<<eLogBeta<<endl;\n//            if(!is_finite(zeta[dout]))\n//              exit(0);\n\n          //cout<<\" ------------------------ doc level updates --------------------\"<<endl;\n          //Mat<double> gamma(T,2);\n          Col<double> eLogSig_gam(mT);\n          Mat<double> gamma_prev(mT,2);\n          gamma_prev.ones();\n          gamma_prev.col(1) += HDP<U>::mAlpha;\n          bool converged = false;\n          uint32_t o=0;\n          while(!converged){\n//            cout<<\"-------------- Iterating local params #\"<<o<<\" -------------------------\"<<endl;\n            updateGamma(gamma[dout],phi[dout]);\n\n            if (!is_finite(gamma[dout])){\n              cout<<\"gamma=\"<<gamma[dout];\n              cout<<\"phi=\"<<phi[dout];\n              exit(1);\n            }\n\n            compElogSig(eLogSig_gam,gamma[dout]); // precompute \n\n            updateZeta(zeta[dout],phi[dout],eLogSig_a,eLogBeta);\n            updatePhi(phi[dout],zeta[dout],eLogSig_gam,eLogBeta);\n\n            converged = (accu(gamma_prev != gamma[dout]))==0 || o>30 ;\n            gamma_prev = gamma[dout];\n            ++o;\n\n//            cout<<\"o=\"<<o<<endl;\n//            cout<<\"zeta=\"<<zeta[dout].row(0)<<\" |.|=\"<<sum(zeta[dout].row(0))<<endl;\n//            cout<<\"phi=\"<<phi[dout].row(0)<<\" |.|=\"<<sum(phi[dout].row(0))<<endl;\n//            if(!is_finite(zeta[dout]))\n//              exit(0);\n          }\n\n          DistriContainer<U> d_lambda(HDP<U>::mH0,mK); // batch updates\n          Mat<double> d_a(mK,2); \n//          cout<<\" --------------------- natural gradients dout=\"<< dout<<\" dd=\"<< dd<<\" --------------------------- \"<<endl;\n          computeNaturalGradients(d_lambda, d_a, zeta[dout], phi[dout], HDP<U>::mOmega, D, x_d);\n#pragma omp critical\n          {\n            cout<<\"update_batch::d_lambda:\"<<endl<<d_lambda.toMat().rows(0,5);\n            for (uint32_t k=0; k<d_lambda.size(); ++k){\n              db_lambda[k]->fromRow(db_lambda[k]->asRow() + d_lambda[k]->asRow());\n            }\n            db_a += d_a;\n          }\n        }\n        //for (uint32_t k=0; k<K; ++k)\n        //  cout<<\"delta lambda_\"<<k<<\" min=\"<<min(d_lambda.row(k))<<\" max=\"<< max(d_lambda.row(k))<<\" #greater 0.1=\"<<sum(d_lambda.row(k)>0.1)<<endl;\n        // ----------------------- update global params -----------------------\n        uint32_t t=dd+d_0; // d_0 is the timestep of the the first index to process; dd is the index in the current batch\n        uint32_t bS = min(S,ind.n_elem-dd); // necessary for the last batch, which migth not form a complete batch\n        //TODO: what is the time dd? d_0 needed?\n        double ro = exp(-kappa*log(1+double(t)+double(bS)/2.0)); // as \"time\" use the middle of the batch \n//        cout<<\" -- global parameter updates t=\"<<t<<\" bS=\"<<bS<<\" ro=\"<<ro<<endl;\n//        cout<<\"d_a=\"<<db_a<<endl;\n        \n\n//        cout<<\"dLambda\"<<endl;\n//        for (uint32_t k=0; k<10; ++k)\n//          cout<<db_lambda[k]->asRow();\n//        \n//        cout<<\"Before\"<<endl;\n//        for (uint32_t k=0; k<10; ++k)\n//          cout<<lambda[k]->asRow();\n\n        cout<<\"update_batch::db_lambda:\"<<endl<<db_lambda.toMat().rows(0,5);\n        for (uint32_t k=0; k<db_lambda.size(); ++k)\n          lambda[k]->fromRow((1.0-ro)*lambda[k]->asRow() + (ro/S)*db_lambda[k]->asRow()); //TODO: doies this make sense for NIW prior???\n        cout<<\"update_batch::lambda(after):\"<<endl<<lambda.toMat().rows(0,5);\n\n//        cout<<\"After\"<<endl;\n//        for (uint32_t k=0; k<10; ++k)\n//          cout<<lambda[k]->asRow();\n\n\n        //lambda = (1.0-ro)*lambda + (ro/S)*db_lambda;\n        a = (1.0-ro)*a + (ro/S)*db_a;\n        cout<<\"update_batch::lambda:\"<<lambda.toMat().rows(0,5);\n\n        perp[dd+bS/2] = 0.0;\n        if (HDP<U>::mX_te.size() > 0) {\n          cout<<\"computing \"<<HDP<U>::mX_te.size()<<\" perplexities\"<<endl;\n#pragma omp parallel for schedule(dynamic) \n          for (uint32_t i=0; i < HDP<U>::mX_te.size(); ++i)\n          {\n            //cout<<\"mX_te: \"<< mX_te[i].n_rows << \"x\"<< mX_te[i].n_cols<<endl;\n            //cout<<\"mX_ho: \"<< mX_ho[i].n_rows << \"x\"<< mX_ho[i].n_cols<<endl;\n            //TODO: these subfunctions work on the member variables!!! dont do that...\n            double perp_i =  perplexity(HDP<U>::mX_te[i],HDP<U>::mX_ho[i],dd+bS/2+1,ro); //perplexity(mX_ho[i], mZeta[d], mPhi[d], mGamma[d], lambda);\n            //cout<<\"perp_\"<<i<<\"=\"<<perp_i<<endl;\n#pragma omp critical\n            {\n              perp[dd+bS/2] += perp_i;\n            }\n          }\n          perp[dd+bS/2] /= double(HDP<U>::mX_te.size());\n          cout<<\"Perplexity=\"<<perp[dd+bS/2]<<endl;\n        }\n      }\n      cout<<\"perp=\"<<perp.t()<<endl;\n      return ind;\n    };\n\n\n    // compute the perplexity of a given document split into x_test (to find a topic model for the doc) and x_ho (to evaluate the perplexity)\n    double perplexity(const Mat<U>& x_te, const Mat<U>& x_ho, uint32_t d, double kappa=0.75)\n    {\n      if (HDP<U>::mX.size() > 0 && HDP<U>::mX.size() == mPhi.size()) { // this should indicate that there exists a estimate already\n       \n        uint32_t N = x_te.n_cols;\n        uint32_t T = mT; \n        uint32_t K = mK; \n\n        Mat<double> zeta(T,K);\n        Mat<double> phi(N,T);\n        Mat<double> gamma(T,2);\n        //uint32_t d = mX.size()-1;\n\n        Mat<double> a(mA);// DONE: make deep copy here!\n\n        DistriContainer<U> lambda(HDP<U>::mLambda);\n        double omega = HDP<U>::mOmega;\n\n\n        cout<<\"perplexity::lambda:\"<<lambda.toMat().rows(0,5);\n        cout<<\"perplexity::mLambda:\"<<HDP<U>::mLambda.toMat().rows(0,5);\n\n        cout<<\"updating copied model with x\"<<endl;\n        updateEst(x_te,zeta,phi,gamma,a,lambda,omega,d,kappa);\n//        cout<<\" lambda.shape=\"<<lambda.size()<<endl;\n        cout<<\"computing perplexity under updated model\"<<endl;\n        //TODO: compute probabilities then use that to compute perplexity\n\n        cout<<\"x_te: \"<<size(x_te);\n        Mixture<U> mix = docMixture(phi, zeta, gamma, lambda);\n        return HDP<U>::perplexity(x_ho, mix);\n        //return perplexity(x_ho, zeta, phi, gamma, lambda);\n      }else{\n        return 1.0/0.0;\n      }\n    };\n\n    Mixture<U> docMixture(uint32_t d) const {\n      return docMixture(mPhi[d],mZeta[d],mGamma[d],HDP<U>::mLambda);\n    };\n    Mixture<U> docMixture(const Mat<double>& phi, const Mat<double>& zeta, const Mat<double>& gamma, const DistriContainer<U>& lambda) const\n    {\n      Col<double> pi;\n      Col<double> sigPi;\n      Col<uint32_t> c;\n      getDocTopics(pi,sigPi,c,gamma,zeta);\n      //cout<<\"getDocTopics done\"<<endl;\n      //cout<<\"c=\"<<c.t()<<size(c);\n      Col<uint32_t> z(mNw);\n      getWordTopics(z, phi);\n      //cout<<\"getWordTopics done\"<<endl;\n      //cout<<\"z=\"<<z.t()<<size(z);\n\n      DistriContainer<U> beta;\n      HDP<U>::getCorpTopics(beta,lambda);\n//      cout<<\"getCorpTopics done\"<<endl;\n      //cout<<\"beta:\\t\"<<size(beta);\n\n      Col<uint32_t> c_u = unique(c);\n      Row<double> ps(c_u.n_elem); // proportions in  the mixture\n      DistriContainer<U> beta_d(c_u.n_elem);\n      for (uint32_t i=0; i< c_u.n_elem; ++i){\n        beta_d[i] = beta[c_u(i)]->getCopy();\n        ps[i] = sum(sigPi.elem(find(c == c_u(i) )));\n      }\n//      cout<<\"Mixture done\"<<endl;\n      return Mixture<U>(beta_d,ps);\n    };\n\n    /* Probability distribution over the words in document d\n     *\n     * TODO: so is that here not some MAP or ML estimate?!\n     */\n    Row<double> logP_w(uint32_t d) const {\n//      cout<<\"mX.size=\"<<mX.size()<<endl;\n      return logP_w(HDP<U>::mX[d],mPhi[d],mZeta[d],mGamma[d],HDP<U>::mLambda);\n    };\n    /* \n     * log probability using the samples x (not using sufficient statistics -> x is just a list of words)\n     */\n    Row<double> logP_w(const Mat<U>& x, const Mat<double>& phi, const Mat<double>& zeta, const Mat<double>& gamma, const DistriContainer<U>& lambda) const\n    { \n      Row<double> p(x.n_cols);\n      p.zeros();\n//      cout<<\"x:\\t\"<<size(x);\n//      cout<<\"phi:\\t\"<<size(phi);\n//      cout<<\"zeta:\\t\"<<size(zeta);\n//      cout<<\"gamma:\\t\"<<size(gamma);\n//      cout<<\"lambda:\\t\"<<size(lambda);\n\n      Col<double> pi;\n      Col<double> sigPi;\n      Col<uint32_t> c;\n      getDocTopics(pi,sigPi,c,gamma,zeta);\n      //cout<<\"getDocTopics done\"<<endl;\n      //cout<<\"c=\"<<c.t()<<size(c);\n      Col<uint32_t> z(mNw);\n      getWordTopics(z, phi);\n      //cout<<\"getWordTopics done\"<<endl;\n      //cout<<\"z=\"<<z.t()<<size(z);\n\n      DistriContainer<U> beta;\n      HDP<U>::getCorpTopics(beta,lambda);\n      //cout<<\"getCorpTopics done\"<<endl;\n      //cout<<\"beta:\\t\"<<size(beta);\n\n      for (uint32_t i=0; i<x.n_cols; ++i){\n        //cout<<\"z_\"<<i<<\"=\"<<z[i]<<endl;\n        p[i] = beta[c[z[i]]]->logP(x.col(i));// logCat(x[i], beta.row( c[ z[i] ]));\n        //cout<<\"p_\"<<x[i]<<\"=\"<<p[x[i]]<<endl;\n      }\n//      for (uint32_t w=0; w<mNw; ++w)\n//        p[w] = p[w]==0.0?-1e10:p[w];\n\n      //cout<<\"p=\"<<p<<endl;\n      return p;\n    };\n\n  protected:\n\n    Row<uint32_t> mInd2Proc; // indices of docs that have not been processed\n\n  private:\n\n    /*\n     * precompute necessary digamma function values, because these are slowing the whole algorithm down\n     * all the update methods for zeta and phi need these values very often! I can precumpute these once after updating the global parameters (and hence lambda)\n     */\n    void compElogBeta(Mat<double>& eLogBeta, const DistriContainer<U>& lambda, const Mat<U>& x_d) const \n    { \n      eLogBeta.zeros(mK,x_d.n_cols);\n\n      Col<double> digam_lamb_sum(mK);\n    //  Mat<uint32_t> x_u = unique(x_d); // cannot do this trick anymore since x_d are continuous for the NIW base measure\n//      cout<<\"x_d=\"<<x_d<<endl;\n//      cout<<\"x_u=\"<<x_u<<endl;\n \n      for (uint32_t i = 0; i < x_d.n_cols ; i++) {\n        for (uint32_t k = 0; k < mK; k++) {\n           eLogBeta(k,i) = lambda[k]->Elog(x_d.col(i)); // E[log beta] computation in paper\n        }\n      }\n//      for (uint32_t k = 0; k < mK; k++) {\n//        digam_lamb_sum(k) = digamma(sum(lambda.row(k)));\n//      }\n//      for (uint32_t i = 0; i < x_u.n_elem ; i++) {\n//        for (uint32_t k = 0; k < mK; k++) {\n//           eLogBeta(k,x_u(i)) = digamma(lambda(k,x_u(i))) - digam_lamb_sum(k);\n//        }\n//      }\n    }\n\n    void compElogSig(Col<double>& eLogSig, const Mat<double>& a) const\n    {\n      for (uint32_t k=0; k<a.n_rows; ++k){\n        eLogSig(k) = digamma(a(k,0)) - digamma(a(k,0) + a(k,1));\n        for (uint32_t l=0; l<k; ++l)\n          eLogSig(k) += digamma(a(l,1)) - digamma(a(l,0) + a(l,1));\n      }\n    }\n\n    void initZeta(Mat<double>& zeta, const Mat<double>& eLogBeta)\n    {\n      uint32_t N = eLogBeta.n_cols; // x_d.n_cols;\n      uint32_t T = zeta.n_rows;\n      uint32_t K = zeta.n_cols;\n      //cerr<<\"\\tinit zeta\"<<endl;\n      for (uint32_t i=0; i<T; ++i) {\n        for (uint32_t k=0; k<K; ++k) {\n          zeta(i,k)=0.0;\n          for (uint32_t n=0; n<N; ++n) {\n            //if(i==0 && k==0) cout<<zeta(i,k)<<\" -> \";\n            zeta(i,k) += eLogBeta(k,n); //ElogBeta(lambda, k, x_d(n));\n          }\n        }\n        normalizeLogDistribution(zeta.row(i));\n        //cout<<\" normalized=\"<<zeta(0,0)<<endl;\n      }\n      //cerr<<\"zeta>\"<<endl<<zeta<<\"<zeta\"<<endl;\n      //cerr<<\"normalization check:\"<<endl<<sum(zeta,1).t()<<endl; // sum over rows\n    };\n\n    void initPhi(Mat<double>& phi, const Mat<double>& zeta, const Mat<double>& eLogBeta)\n    {\n      uint32_t N = phi.n_rows; // x_d.n_cols;\n      uint32_t T = zeta.n_rows;\n      uint32_t K = zeta.n_cols;\n      //cout<<\"\\tinit phi\"<<endl;\n      for (uint32_t n=0; n<N; ++n){\n        for (uint32_t i=0; i<T; ++i) {\n          phi(n,i)=0.0;\n          for (uint32_t k=0; k<K; ++k) {\n            phi(n,i)+=zeta(i,k)* eLogBeta(k,n); // ElogBeta(lambda, k, x_d(n));\n          }\n        }\n        normalizeLogDistribution(phi.row(n));\n      }\n      //cerr<<\"phi>\"<<endl<<phi<<\"<phi\"<<endl;\n    };\n\n    void updateGamma(Mat<double>& gamma, const Mat<double>& phi)\n    {\n      uint32_t N = phi.n_rows;\n      uint32_t T = phi.n_cols;\n\n      gamma.ones();\n      gamma.col(1) *= HDP<U>::mAlpha;\n      for (uint32_t i=0; i<T; ++i) \n      {\n        for (uint32_t n=0; n<N; ++n){\n          gamma(i,0) += phi(n,i);\n          for (uint32_t j=i+1; j<T; ++j) {\n            gamma(i,1) += phi(n,j);\n          }\n        }\n      }\n      //cout<<gamma.t()<<endl;\n    };\n\n    void updateZeta(Mat<double>& zeta, const Mat<double>& phi, const Col<double>& eLogSig_a, const Mat<double>& eLogBeta)\n    {\n//      assert(x_d.n_rows == 1);\n\n      uint32_t N = phi.n_rows; // x_d.n_cols;\n      uint32_t T = zeta.n_rows;\n      uint32_t K = zeta.n_cols;\n\n      for (uint32_t i=0; i<T; ++i){\n        //zeta(i,k)=0.0;\n        for (uint32_t k=0; k<K; ++k) {\n          zeta(i,k) = eLogSig_a(k); //ElogSigma(a,k);\n          //cout<<zeta(i,k)<<endl;\n          for (uint32_t n=0; n<N; ++n){\n            zeta(i,k) += phi(n,i)* eLogBeta(k,n); //ElogBeta(lambda,k,x_d(n));\n          }\n        }\n        normalizeLogDistribution(zeta.row(i));\n      }\n    }\n\n\n    void updatePhi(Mat<double>& phi, const Mat<double>& zeta, const Col<double>& eLogSig_gam, const Mat<double>& eLogBeta)\n    {\n//      assert(x_d.n_rows == 1);\n\n      uint32_t N = phi.n_rows; // x_d.n_cols;\n      uint32_t T = zeta.n_rows;\n      uint32_t K = zeta.n_cols;\n\n      for (uint32_t n=0; n<N; ++n){\n        //phi(n,i)=0.0;\n        for (uint32_t i=0; i<T; ++i) {\n          phi(n,i) = eLogSig_gam(i); //ElogSigma(gamma,i);\n          for (uint32_t k=0; k<K; ++k) {\n            phi(n,i) += zeta(i,k)* eLogBeta(k,n); //ElogBeta(lambda,k,x_d(n)) ;\n          }\n        }\n        normalizeLogDistribution(phi.row(n));\n      }\n    }\n\n    void computeNaturalGradients(DistriContainer<U>& d_lambda, Mat<double>& d_a, const Mat<double>& zeta, const Mat<double>&  phi, double omega, uint32_t D, const Mat<U>& x_d)\n    {\n//      uint32_t N = x_d.n_cols;\n//      uint32_t Nw = d_lambda.n_cols;\n      uint32_t T = zeta.n_rows;\n      uint32_t K = zeta.n_cols;\n\n//      d_lambda.init(HDP<U>::mH0,mK);\n\n//      d_lambda.zeros();\n      d_a.zeros();\n      for (uint32_t k=0; k<K; ++k) \n      { // for all K corpus level topics\n//        cout<<zeta.col(k).t()<<endl;\n//        cout<<phi;\n        d_lambda[k]->posteriorHDP_var(zeta.col(k),phi,D,x_d);\n\n//        for (uint32_t i=0; i<T; ++i) \n//        {\n//          Row<double> _lambda(Nw); _lambda.zeros();\n//          for (uint32_t n=0; n<N; ++n){\n//            _lambda(x_d(n)) += phi(n,i);\n//          }\n//          d_lambda.row(k) += zeta(i,k) * _lambda;\n//        }\n//        d_lambda.row(k) = D*d_lambda.row(k);\n//        //cout<<\"lambda-nu=\"<<d_lambda[k].t()<<endl;\n//        d_lambda.row(k) += ((Dir*)(&mH0))->mAlphas;\n//        //cout<<\"lambda=\"<<d_lambda[k].t()<<endl;\n\n        for (uint32_t i=0; i<T; ++i) \n        {\n          d_a(k,0) += zeta(i,k);\n          for (uint32_t l=k+1; l<K; ++l) {\n            d_a(k,1) += zeta(i,l);\n          }\n        }\n        d_a(k,0) = D*d_a(k,0)+1.0;\n        d_a(k,1) = D*d_a(k,1)+omega;\n      }\n    }\n\n\n    //bool normalizeLogDistribution(Row<double>& r)\n    bool normalizeLogDistribution(arma::subview_row<double> r) const\n    {\n      // known as the log sum exp trick!\n//      cout<<\" r=\"<<r<<endl;\n      double maxR = as_scalar(max(r));\n//      cout<<\"  maxR=\"<<maxR<<endl;\n//      cout<<\"  exp(r-maxR)=\"<<exp(r-maxR)<<endl;\n     \n      r -= maxR + log(sum(exp(r-maxR)));\n      r=exp(r);\n\n//      cout<<\" r=\"<<r<<endl;\n      return true;\n\n\n//      double minR = as_scalar(min(r));\n//      cout<<\" minR=\"<<minR<<endl;\n//      if(minR > -100.0) {\n//        cout<<\" logDenom=\"<<sum(exp(r),1)<<endl;\n//        double denom = as_scalar(sum(exp(r),1));\n//        cout<<\" logDenom=\"<<denom<<endl;\n//        r -= log(denom); // avoid division by 0\n//        cout<<\" r - logDenom=\"<<r<<endl;\n//        r = exp(r);\n//        r /= sum(r);\n//        cout<<\" exp(r - logDenom)=\"<<r<<endl;\n//        return true;\n//      }else{ // cannot compute this -> set the smallest r to 1.0 and the rest to 0\n//        double maxR = as_scalar(max(r));\n//        cout<<\"maxR=\"<<maxR<<\" <-\" <<arma::max(r) <<endl;\n//        uint32_t kMax=as_scalar(find(r==maxR,1));\n//        cout<<\"maxR=\"<<maxR<<\" kMax=\"<<kMax<<\" <-\" <<arma::max(r) <<endl;\n//        r.zeros();\n//        r(kMax)=1.0;\n//        cout<<\" r =\"<<r<<endl;\n//        return false;\n//      }\n    }\n\n};\n\n", "meta": {"hexsha": "e7ecb1d609e06b6a93c6423920ae493cd9dc3271", "size": 28299, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hdp_var.hpp", "max_stars_repo_name": "jstraub/bnp", "max_stars_repo_head_hexsha": "11cd28b49e9cf1db96f349181aff57a17672b6a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T01:18:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-16T20:16:54.000Z", "max_issues_repo_path": "include/hdp_var.hpp", "max_issues_repo_name": "jstraub/bnp", "max_issues_repo_head_hexsha": "11cd28b49e9cf1db96f349181aff57a17672b6a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-07-12T12:58:14.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-12T12:58:14.000Z", "max_forks_repo_path": "include/hdp_var.hpp", "max_forks_repo_name": "jstraub/bnp", "max_forks_repo_head_hexsha": "11cd28b49e9cf1db96f349181aff57a17672b6a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-07-22T05:37:10.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-26T07:11:34.000Z", "avg_line_length": 34.8081180812, "max_line_length": 271, "alphanum_fraction": 0.532598325, "num_tokens": 8571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.29674485947994605}}
{"text": "///=======================================================================\n// Copyright 2015-2020 Clemson University\n// Authors: Bradley S. Meyer\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 RANK_SPANNING_BRANCHINGS_HPP\n#define RANK_SPANNING_BRANCHINGS_HPP\n\n/*\n * Rank spanning branchings\n *         Camerini et al Algorithm\n *\n * Requirement:\n *      directed graph with single root vertex\n */\n\n#include <vector>\n#include <limits>\n\n#include <boost/concept_check.hpp>\n#include <boost/config.hpp>\n#include <boost/foreach.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/filtered_graph.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/heap/fibonacci_heap.hpp>\n#include <boost/pending/disjoint_sets.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/optional.hpp>\n#include <boost/unordered_set.hpp>\n\nusing namespace boost;\n\nnamespace rsb {\n\n  namespace detail {\n\n    typedef adjacency_list < vecS, vecS, bidirectionalS,\n      no_property, no_property > BranchingGraph;\n\n    typedef graph_traits<BranchingGraph>::vertex_descriptor BranchingVertex;\n\n    // Structure to store edges and compare them by weight.\n\n    template <typename Edge, typename WeightMap, typename Compare>\n    struct EdgeNode\n    {\n      Edge                                                            edge;\n      typename property_traits<WeightMap>::value_type                 weight;\n      Compare                                                         compare;\n      EdgeNode(){}\n      EdgeNode(\n        const Edge& e,\n        const typename property_traits<WeightMap>::value_type & w,\n        Compare c ) :\n        edge( e ), weight( w ), compare( c ) {}\n      bool operator<( EdgeNode const & rhs ) const\n      { return compare( weight, rhs.weight ); }\n    };\n\n    // Insert edges from graph into queue, taking into account constraints.\n\n    template <typename Graph, typename Edge, typename WeightMap,\n              typename Compare, typename MergablePriorityQueueMap>\n    bool\n    insert_edges\n    (\n      const Graph& g,\n      WeightMap& weight_map,\n      Compare& comp,\n      MergablePriorityQueueMap& in_edges,\n      const unordered_set<Edge>& include_edges,\n      const unordered_set<Edge>& exclude_edges\n    )\n    {\n      typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n      unordered_set<Vertex> include_vertices, in_set, out_set;\n      typename unordered_set<Vertex>::iterator it;\n\n      // Insert vertices in sets to check for spanning branching.\n\n      BGL_FORALL_VERTICES_T( v, g, Graph )\n      {\n        in_set.insert( v );\n        out_set.insert( v );\n      }\n\n      // Insert edges that must be present and note the invertex.  Remove\n      // vertices from relevant sets.\n\n      BOOST_FOREACH( const Edge& e, include_edges )\n      {\n        include_vertices.insert( target( e, g ) );\n        in_edges[target( e, g )].push(\n          EdgeNode<Edge,WeightMap,Compare>( e, get( weight_map, e ), comp )\n        );\n        it = in_set.find( target( e, g ) );\n        if( it != in_set.end() ) { in_set.erase( it ); }\n        it = out_set.find( source( e, g ) );\n        if( it != out_set.end() ) { out_set.erase( it ); }\n      }\n        \n      // Insert edges, but not edges to be excluded or into vertices that\n      // already have in edges.  Remove vertices from relevant sets.\n\n      BOOST_FOREACH( const Edge &e, edges(g) )\n      {\n        if(\n          include_vertices.find( target(e, g) ) == include_vertices.end()\n          &&\n          exclude_edges.find( e ) == exclude_edges.end()\n        )\n        {\n          if( source(e, g) != target(e, g) )\n          {\n            in_edges[target(e,g)].push(\n              EdgeNode<Edge,WeightMap,Compare>( e, get( weight_map, e ), comp )\n            );\n            it = in_set.find( target( e, g ) );\n            if( it != in_set.end() ) { in_set.erase( it ); }\n            it = out_set.find( source( e, g ) );\n            if( it != out_set.end() ) { out_set.erase( it ); }\n          }\n        }\n      }\n\n      // Check for correct number of roots.\n      //\n      if( in_set.size() != 1 )\n        return false;   // Zero roots or more than one root.\n      else if( out_set.find( *in_set.begin() ) != out_set.end() )\n        return false;   // Root is isolated.\n      else\n        return true;\n\n    }\n\n    // Retrieve the path back from leaf to root in cycle branching.\n\n    void\n    find_back_path(\n      BranchingGraph& cycle_branching,\n      std::vector<BranchingVertex>& bv\n    )\n    {\n\n      BGL_FORALL_INEDGES( bv[0], e, cycle_branching, BranchingGraph )\n      {\n        bv.insert( bv.begin(), source( e, cycle_branching ) );\n        find_back_path( cycle_branching, bv );\n      }\n\n    }\n\n    // Expand cycles.\n\n    template <typename Graph, typename Edge, typename IndexMap,\n              typename WeightMap, typename Compare>\n    void\n    expand(\n      const Graph& g,\n      IndexMap& v_id,\n      BranchingGraph& cycle_branching,\n      unordered_set<BranchingVertex>& root_set,\n      std::vector<EdgeNode< Edge, WeightMap, Compare> >& beta\n    )\n    {\n\n      BOOST_FOREACH( BranchingVertex v, root_set )\n      {\n        if(\n          in_degree( v, cycle_branching ) == 0 &&\n          out_degree( v, cycle_branching ) != 0\n        )\n        {\n          std::vector<BranchingVertex> bv;\n          bv.push_back( v_id[target( beta[v].edge, g )] );\n          find_back_path( cycle_branching, bv );\n          for( std::size_t i = 0; i < bv.size() - 1; i++ )\n          {\n            beta[bv[i+1]] = beta[bv[i]];\n            clear_vertex( bv[i], cycle_branching );\n          }\n        }\n      }\n\n      // Remove isolated vertices.\n\n      std::vector<BranchingVertex> vertices_to_remove_from_set;\n\n      BOOST_FOREACH( BranchingVertex v, root_set )\n      {\n        if(\n           in_degree( v, cycle_branching ) == 0 &&\n           out_degree( v, cycle_branching ) == 0\n        )\n        {\n          vertices_to_remove_from_set.push_back( v );\n        }\n      }\n\n      BOOST_FOREACH( BranchingVertex v, vertices_to_remove_from_set )\n      {\n        root_set.erase( v );\n      }\n\n    }\n\n    // Camerini et al. BEST routine.\n\n    template <typename EdgeNodeType, typename MergablePriorityQueue,\n              typename Graph, typename Edge, typename IndexMap,\n              typename WeightMap, typename Rank, typename Pred,\n              typename Compare>\n    void\n    best_spanning_branching( const Graph& g, \n                             unordered_set<Edge>& branching,\n                             IndexMap& v_id,\n                             WeightMap& weight_map,\n                             Compare& comp,\n                             Rank rank,\n                             Pred pred1,\n                             Pred pred2,\n                             unordered_set<Edge>& include_edges,\n                             unordered_set<Edge>& exclude_edges\n                           )\n    {\n\n      // Define types.\n\n      typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n      typedef typename graph_traits<Graph>::vertices_size_type vertex_idx_t;\n\n      typedef std::map<Vertex, EdgeNodeType> exit_map_t;\n\n      // Create various objects.  Note in particular the two disjoint\n      // sets.  The set of weakly connected components is used to determine\n      // cycles.  The set of strongly connected components is used to\n      // represent supervertices (condensed cycles).\n\n      unordered_set<Vertex> unvisited_vertex_set;\n\n      Vertex root_vertex;\n\n      BranchingGraph cycle_branching;\n\n      vertex_idx_t n = num_vertices(g);\n\n      std::map<Vertex, MergablePriorityQueue> in_edges;\n\n      // Create disjoint sets.  The set of weakly connected components is\n      // used to determine cycles.  The set of strongly connected components\n      // is used to represent supervertices (condensed cycles).\n\n      disjoint_sets<Rank, Pred>\n        weak_cc( rank, pred1 ), strong_cc( rank, pred2 );\n\n      if(\n        !insert_edges(\n          g,\n          weight_map,\n          comp,\n          in_edges,\n          include_edges,\n          exclude_edges\n        )\n      ) return;\n\n      std::vector<EdgeNodeType> beta( 2 * n );\n\n      std::map<Vertex, vertex_idx_t> parent;\n\n      BGL_FORALL_VERTICES_T( v, g, Graph )\n      {\n        weak_cc.make_set( v );\n        strong_cc.make_set( v );\n        parent[v]  = v_id[v];\n        add_vertex( cycle_branching );\n        unvisited_vertex_set.insert( v );\n      }\n\n      while( !unvisited_vertex_set.empty() )\n      {\n\n        typename unordered_set<Vertex>::iterator it =\n          unvisited_vertex_set.begin(); \n\n        if( in_edges[*it].empty() )\n        {\n          root_vertex = *it;\n\t  unvisited_vertex_set.erase( it );\n        }\n        else\n        {\n\n\t  EdgeNodeType critical_edge_node = in_edges[*it].top();\n\n\t  beta[parent[*it]] = critical_edge_node;\n\n          // Done with this vertex.\n\n\t  unvisited_vertex_set.erase( it );\n\n          // Check for cycle and, if present, condense.\n\n\t  if(\n\t    weak_cc.find_set( source( critical_edge_node.edge, g ) ) !=\n\t    weak_cc.find_set( target( critical_edge_node.edge, g ) )\n\t  )\n\t  {\n\t    weak_cc.union_set(\n              source( critical_edge_node.edge, g ),\n              target( critical_edge_node.edge, g )\n\t    );\n\t  }\n\t  else\n\t  {\n\t    BranchingVertex v_new = add_vertex( cycle_branching );\n\n\t    EdgeNodeType least_costly_edge_node = critical_edge_node; \n\n\t    boost::unordered_set<Vertex> cycle_vertex_set;\n\n\t    for(\n              Vertex v = source( critical_edge_node.edge, g );\n\t      cycle_vertex_set.find( strong_cc.find_set( v ) ) ==\n                cycle_vertex_set.end();\n\t      v = source( beta[parent[strong_cc.find_set( v )]].edge, g )\n\t    )\n\t    {\n              Vertex u = strong_cc.find_set( v );\n\t      cycle_vertex_set.insert( u );\n\t      add_edge( v_new, parent[u], cycle_branching ); \n              if(\n                comp( beta[parent[u]].weight, least_costly_edge_node.weight )\n              )\n              {\n\t\tleast_costly_edge_node = beta[parent[u]];\n              }\n\t    }\n\n            Vertex new_repr = *cycle_vertex_set.begin();\n\n\t    BOOST_FOREACH( Vertex u, cycle_vertex_set )\n\t    {\n              strong_cc.link( u, new_repr );\n              new_repr = strong_cc.find_set( new_repr );\n            }\n\n\t    BOOST_FOREACH( Vertex v, cycle_vertex_set )\n\t    {\n              exit_map_t v_exit;\n              BOOST_FOREACH( EdgeNodeType en, in_edges[v] )\n              {\n                if( strong_cc.find_set( source( en.edge, g ) ) != new_repr )\n                {\n                  en.weight += least_costly_edge_node.weight -\n                      beta[parent[v]].weight;\n                  Vertex u = strong_cc.find_set( source( en.edge, g ) );\n                  if( v_exit.find(u) != v_exit.end() )\n                  {\n                    if( comp( v_exit[u].weight, en.weight ) )\n                    {\n                      v_exit[u] = en;\n                    }\n                  }\n                  else\n                  {\n                    v_exit[u] = en;\n                  }\n                }\n\t      }\n              MergablePriorityQueue tmp_queue;\n              BOOST_FOREACH( typename exit_map_t::value_type& t, v_exit )\n              {\n                tmp_queue.push( t.second );\n              }\n              in_edges[v].swap( tmp_queue );\n\t    }\n                 \n\t    BOOST_FOREACH( Vertex v, cycle_vertex_set )\n\t    {\n              if( v != new_repr ) in_edges[new_repr].merge( in_edges[v] );\n            }\n\n\t    unvisited_vertex_set.insert( new_repr );\n\n            parent[new_repr] = v_new;\n\n\t  }\n\n        }\n\n      }\n\n      // Create a set containing possible roots of the cycle branching.\n      // In each cycle expansion, remove isolated vertices of the\n      // cycle branching to avoid considering them in subsequent cycle\n      // expansions.\n\n      unordered_set<BranchingVertex> root_set;\n\n      BGL_FORALL_VERTICES( u, cycle_branching, BranchingGraph )\n      {\n        root_set.insert( u );\n      }\n\n      while( !root_set.empty() )\n      {\n        expand( g, v_id, cycle_branching, root_set, beta );\n      }\n\n      BGL_FORALL_VERTICES_T( v, g, Graph )\n      {\n        if( v != root_vertex )\n        {\n          branching.insert( beta[v_id[v]].edge );\n        }\n      }\n\n    }\n\n    // Depth-first visitor to set up pre-order and post-order maps.\n\n    template<typename OrderMap>\n    class dfs_order_visitor:public default_dfs_visitor\n    {\n\n      public:\n\tdfs_order_visitor(\n\t  OrderMap& pr,\n\t  OrderMap& po\n\t) :  m_pr( pr ), m_po( po ) { td = 0; tf = 0; }\n\n\ttemplate<typename Vertex, typename Graph>\n\tvoid discover_vertex(const Vertex u, const Graph & g)\n\t{\n\t  m_pr[u] = td++;\n\t}\n\n\ttemplate <typename Vertex, typename Graph>\n\tvoid finish_vertex(const Vertex u, const Graph & g)\n\t{\n\t  m_po[u] = tf++;\n\t}\n\n\tOrderMap& m_pr;\n\tOrderMap& m_po;\n\n      private:\n\tstd::size_t td;\n\tstd::size_t tf;\n\n    };\n\n    // The ancestor checker.  A vertex u is a proper ancestor of\n    // vertex v (in the parent branching) if pr[u] < pr[v] and po[u] > po[v].\n\n    template<typename OrderMap>\n    struct ancestor_checker\n    {\n      OrderMap& m_pr;\n      OrderMap& m_po;\n      ancestor_checker( OrderMap& pr, OrderMap& po ) :\n\tm_pr( pr ), m_po( po ) {}\n\n      template<typename Vertex>\n      bool operator()( const Vertex& v1, const Vertex& v2 ) const\n      { return ( m_pr[v1] < m_pr[v2] && m_po[v1] > m_po[v2] ); }\n    };\n\n    // Create a new branching from an input edge set.\n\n    template<typename Graph, typename Edge, typename IndexMap>\n    BranchingGraph\n    create_branching_graph_from_edge_set(\n      Graph& g,\n      IndexMap& v_id,\n      const unordered_set<Edge>& branching\n    )\n    {\n\n      BranchingGraph new_branching;\n\n      for( size_t i = 0; i < num_vertices( g ); i++ )\n      {\n        add_vertex( new_branching );\n      }\n\n      BOOST_FOREACH( const Edge& e, branching )\n      {\n        add_edge(\n          v_id[source( e, g )], v_id[target( e, g )], new_branching\n        );\n      }\n\n      return new_branching;\n\n    }\n\n    // Camerini et al. SEEK routine.  Find the in edge that, when removed,\n    //  gives the next best branching for a vertex and the weight difference.\n\n    template <typename Graph, typename Edge, typename IndexMap,\n              typename MergablePriorityQueue, typename EdgeNodeType,\n              typename Compare, typename OrderMap, typename OptionalWeight>\n    void\n    seek_next_edge_weight_diff(\n      Graph& g,\n      MergablePriorityQueue& in_edges,\n      IndexMap& v_id,\n      ancestor_checker<OrderMap>& is_ancestor,\n      const unordered_set<Edge>& branching,\n      EdgeNodeType& b,\n      Compare& comp,\n      Edge& return_edge,\n      OptionalWeight& delta\n    )\n    {\n\n      if( branching.find( b.edge ) != branching.end() )\n      {\n        for(\n          typename MergablePriorityQueue::ordered_iterator ei =\n            in_edges.ordered_begin();\n          ei != in_edges.ordered_end();\n          ei++\n        )\n        {\n          if( (*ei).edge != b.edge )\n          {\n            if(\n              !is_ancestor(\n                v_id[target( b.edge, g )],\n                v_id[source( (*ei).edge, g )]\n              )\n            )\n            {\n              if( !delta || comp( b.weight - (*ei).weight, delta.get() ) )\n              {\n                delta = b.weight - (*ei).weight;\n                return_edge = b.edge;\n                break;\n              }\n            }\n          }\n        }\n      }\n    }\n\n    // Camerini et al. NEXT routine.  Find the edge that, when removed,\n    // gives the next best branching and the resulting weight difference.\n\n    template <typename EdgeNodeType, typename MergablePriorityQueue,\n              typename Graph, typename Edge, typename IndexMap,\n              typename WeightMap, typename Rank, typename Pred,\n              typename Compare>\n    boost::optional<\n      std::pair<Edge, typename property_traits<WeightMap>::value_type>\n    >\n    next_spanning_branching( const Graph& g, \n                             const unordered_set<Edge>& branching,\n                             IndexMap& v_id,\n                             WeightMap& weight_map,\n                             Compare& comp,\n                             Rank rank,\n                             Pred pred1,\n                             Pred pred2,\n                             unordered_set<Edge>& include_edges,\n                             unordered_set<Edge>& exclude_edges\n                           )\n    {\n\n      typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n\n      typedef std::map<Vertex, EdgeNodeType> exit_map_t;\n\n      typedef typename property_traits<WeightMap>::value_type weight_t;\n\n      Edge return_edge;\n\n      boost::optional<weight_t> delta;\n\n      EdgeNodeType b;\n\n      // Create various objects.\n\n      boost::optional<\n        std::pair<Edge, typename property_traits<WeightMap>::value_type>\n      > next_edge_and_weight_delta;\n\n      unordered_set<Vertex> unvisited_vertex_set;\n\n      std::map<Vertex, MergablePriorityQueue> in_edges;\n\n      std::map<Vertex, EdgeNodeType> max_e;\n\n      // Create disjoint sets.  The set of weakly connected components is\n      // used to determine cycles.  The set of strongly connected components\n      // is used to represent supervertices (condensed cycles).\n\n      disjoint_sets<Rank, Pred>\n        weak_cc( rank, pred1 ), strong_cc( rank, pred2 );\n\n      // Create a branching graph to check whether a vertex is an ancestor of\n      // another vertex in the branching.\n\n      BranchingGraph ancestor_branching =\n        create_branching_graph_from_edge_set( g, v_id, branching );\n\n      // Insert edges.\n\n      if(\n        !insert_edges(\n          g,\n          weight_map,\n          comp,\n          in_edges,\n          include_edges,\n          exclude_edges\n        )\n      )\n      {\n        return next_edge_and_weight_delta;\n      }\n\n      // Initialize data structures and find start vertex for depth\n      // first search.\n\n      BranchingVertex start_vertex;\n\n      BGL_FORALL_VERTICES_T( v, g, Graph )\n      {\n        weak_cc.make_set( v );\n        strong_cc.make_set( v );\n        unvisited_vertex_set.insert( v );\n        if( in_edges[v].empty() ) { start_vertex = v_id[v]; }\n      }\n\n      // Create the ancestor checker from ancestor_branching.\n\n      typedef std::map<BranchingVertex, std::size_t> OrderMap;\n\n      OrderMap pr;\n      OrderMap po;\n\n      dfs_order_visitor<OrderMap> vis(pr, po);\n\n      depth_first_search(\n        ancestor_branching, visitor(vis).root_vertex( start_vertex )\n      );\n\n      ancestor_checker<OrderMap> is_ancestor(pr, po);\n\n      // Main loop.\n\n      while( !unvisited_vertex_set.empty() )\n      {\n\n        typename unordered_set<Vertex>::iterator it =\n          unvisited_vertex_set.begin(); \n\n        if( in_edges[*it].empty() )\n        {\n\t  unvisited_vertex_set.erase( it );\n        }\n        else\n        {\n\n          // Get largest in edge with ties solved in favor of edges in\n          // input branching.\n\n          for(\n            typename MergablePriorityQueue::ordered_iterator ei =\n              in_edges[*it].ordered_begin();\n            ei != in_edges[*it].ordered_end();\n            ei++\n          )\n          {\n            if( comp( (*ei).weight, in_edges[*it].top().weight ) )\n              break;\n            b = *ei;\n            if( branching.find( b.edge ) != branching.end() )\n              break;\n          }\n\n\t  max_e[*it] = b;\n\n          // Seek next edge weight difference.\n\n          seek_next_edge_weight_diff(\n            g, in_edges[*it], v_id, is_ancestor, branching, b, comp,\n            return_edge, delta\n          );\n\n          // Done with this vertex.\n\n\t  unvisited_vertex_set.erase( it );\n\n          // Check for cycle and, if present, condense.\n\n\t  if(\n\t    weak_cc.find_set( source( b.edge, g ) ) !=\n\t    weak_cc.find_set( target( b.edge, g ) )\n\t  )\n\t  {\n\t    weak_cc.union_set( source( b.edge, g ), target( b.edge, g ) );\n\t  }\n\t  else\n\t  {\n\n\t    EdgeNodeType least_costly_edge_node = b; \n\n\t    boost::unordered_set<Vertex> cycle_vertex_set;\n\n\t    for(\n              Vertex v = source( b.edge, g );\n\t      cycle_vertex_set.find( strong_cc.find_set( v ) ) ==\n                cycle_vertex_set.end();\n\t      v = source( max_e[strong_cc.find_set( v )].edge, g )\n\t    )\n\t    {\n              Vertex u = strong_cc.find_set( v );\n\t      cycle_vertex_set.insert( u );\n\t      if( comp( max_e[u].weight, least_costly_edge_node.weight ) )\n              {\n\t\tleast_costly_edge_node = max_e[u];\n              }\n\t    }\n\n            Vertex new_repr = *cycle_vertex_set.begin();\n\n\t    BOOST_FOREACH( Vertex v, cycle_vertex_set )\n\t    {\n              strong_cc.link( v, new_repr );\n              new_repr = strong_cc.find_set( new_repr );\n            }\n\n            // Adjust arc weights and remove parallel arcs.  Keep the\n            // the largest weight in arc and the largest viable alternative\n            // arc from each source outside the cycle.  Make sure that\n            // an arc from the branching is among the added edges, if present.\n\n\t    BOOST_FOREACH( Vertex v, cycle_vertex_set )\n\t    {\n              std::vector<exit_map_t> v_exit(3);\n              BOOST_FOREACH( EdgeNodeType en, in_edges[v] )\n              {\n                if( strong_cc.find_set( source( en.edge, g ) ) != new_repr )\n                {\n                  en.weight += least_costly_edge_node.weight - max_e[v].weight;\n                  Vertex u = strong_cc.find_set( source( en.edge, g ) );\n                  if( branching.find( en.edge ) != branching.end() )\n                  {\n                    v_exit[0][u] = en;\n                  }\n                  else\n                  {\n                    if( v_exit[1].find(u) != v_exit[1].end() )\n                    {\n                      if( comp( v_exit[1][u].weight, en.weight ) )\n                      {\n                        if(\n                          !is_ancestor(\n                             v_id[target( v_exit[1][u].edge, g )],\n                             v_id[source( v_exit[1][u].edge, g )]\n                          )\n                        )\n                        {\n                          v_exit[2][u] = v_exit[1][u];\n                        }\n                        v_exit[1][u] = en;\n                      }\n                      else if(\n                        v_exit[2].find(u) == v_exit[2].end() ||\n                        comp( v_exit[2][u].weight, en.weight )\n                      )\n                      {\n                        if(\n                          !is_ancestor(\n                            v_id[target( en.edge, g )],\n                            v_id[source( en.edge, g )]\n                          )\n                        )\n                        {\n                          v_exit[2][u] = en;\n                        }\n                      }\n                    }\n                    else\n                    {\n                      v_exit[1][u] = en;\n                    }\n                  }\n                }\n\t      }\n              MergablePriorityQueue tmp_queue;\n              BOOST_FOREACH( exit_map_t& exit_map, v_exit )\n              {\n                BOOST_FOREACH( typename exit_map_t::value_type& t, exit_map )\n                {\n                  tmp_queue.push( t.second );\n                }\n              }\n              in_edges[v].swap( tmp_queue );\n\t    }\n                 \n\t    BOOST_FOREACH( Vertex v, cycle_vertex_set )\n\t    {\n              if( v != new_repr ) in_edges[new_repr].merge( in_edges[v] );\n            }\n\n\t    unvisited_vertex_set.insert( new_repr );\n\n\t  }\n\n        }\n\n      }\n\n      if( delta )\n      {\n        next_edge_and_weight_delta = std::make_pair( return_edge, delta.get() );\n      }\n\n      return next_edge_and_weight_delta;\n\n    }\n\n    // Class to filter graph.\n\n    template<typename EdgeSet>\n    class branching_filter\n    {\n\n      public:\n        branching_filter(){}\n        branching_filter( const EdgeSet * _es ) : p_es( _es ){}\n\n        template <typename Edge>\n        bool operator()( const Edge& e ) const\n        {\n          if( p_es->find( e ) != p_es->end() )\n            return true;\n          else\n            return false;\n        }\n\n     private:\n       const EdgeSet * p_es;\n\n    };\n\n    // Structure to store branchings and compare them by weight.\n\n    template<typename Edge, typename WeightMap, typename Compare>\n    struct BranchingEntry\n    {\n      Edge                                                        edge;\n      typename property_traits<WeightMap>::value_type             weight;\n      Compare                                                     compare;\n      unordered_set<Edge>                                         branching;\n      unordered_set<Edge>                                         include_edges;\n      unordered_set<Edge>                                         exclude_edges;\n      BranchingEntry(){}\n      BranchingEntry(\n\tconst typename property_traits<WeightMap>::value_type& w,\n\tconst Edge& e,\n\tCompare& comp,\n\tconst unordered_set<Edge>& b,\n\tconst unordered_set<Edge>& include,\n\tconst unordered_set<Edge>& exclude\n      ) :\n\t  edge( e ), weight( w ), compare( comp ),\n\t  branching( b ), include_edges( include ),\n\t  exclude_edges( exclude ){}\n      bool operator<( BranchingEntry const & rhs ) const\n      { return compare( weight, rhs.weight ); }\n    };\n\n    // Compute the weight of a branching.\n\n    template<typename WeightMap, typename Edge>\n    typename property_traits<WeightMap>::value_type\n    compute_branching_weight(\n      WeightMap& w,\n      const unordered_set<Edge>& branching\n    )\n    {\n\n       typedef typename property_traits<WeightMap>::value_type weight_t;\n\n       boost::optional<weight_t> weight;\n\n       BOOST_FOREACH( const Edge& e, branching )\n       {\n         \n         if( !weight )\n         {\n           weight = get( w, e );\n         }\n         else\n         {\n\t   weight = weight.get() + get( w, e );\n         }\n       }\n\n       return weight.get();\n\n    }\n\n    // Routine implementation.\n     \n    template <template<class...> class PriorityQueue,\n              typename Graph, typename BranchingProcessor, typename IndexMap,\n              typename WeightMap, typename Compare,\n              typename Rank, typename Parent>\n    void \n    rank_spanning_branchings_impl( const Graph& g,\n\t\t\t           BranchingProcessor bp,\n                                   IndexMap v_id,\n                                   WeightMap w,\n\t\t\t           Compare comp,\n                                   Rank rank,\n                                   Parent pred1,\n                                   Parent pred2\n\t\t\t         )\n    {\n\n      typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n      typedef typename graph_traits<Graph>::edge_descriptor Edge;\n\n      typedef typename property_traits<WeightMap>::value_type weight_t;\n\n      typedef BranchingEntry<Edge, WeightMap, Compare> branching_entry_t;\n\n      typedef EdgeNode<Edge, WeightMap, Compare> edge_node_t;\n\n      typedef PriorityQueue<branching_entry_t> branching_queue_t;\n\n      typedef PriorityQueue<edge_node_t> edge_node_queue_t;\n\n      BOOST_CONCEPT_ASSERT(( VertexAndEdgeListGraphConcept<Graph> ));\n\n      BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<IndexMap, Vertex> ));\n      BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<WeightMap, Edge> ));\n\n      BOOST_CONCEPT_ASSERT(( heap::PriorityQueue<branching_queue_t> ));\n      BOOST_CONCEPT_ASSERT(( heap::MergablePriorityQueue<edge_node_queue_t> ));\n\n      unordered_set<Edge> best_branching, empty_set;\n\n      boost::optional<std::pair<Edge, weight_t> > next_edge_and_weight_delta;\n\n      Edge e;\n\n      branching_queue_t branching_queue;\n\n      best_spanning_branching<edge_node_t, edge_node_queue_t>\n                             ( g,\n                               best_branching,\n                               v_id,\n                               w,\n                               comp,\n                               rank,\n                               pred1,\n                               pred2,\n                               empty_set,\n                               empty_set\n                             );\n\n      branching_filter<unordered_set<Edge> > filter1( &best_branching );\n      filtered_graph<Graph, branching_filter<unordered_set<Edge> > >\n        fg1( g, filter1 );\n\n      if( !bp( fg1 ) ) return;\n\n      next_edge_and_weight_delta =\n        next_spanning_branching<edge_node_t, edge_node_queue_t>\n                              ( g,\n                                 best_branching,\n                                  v_id,\n                                  w,\n                                  comp,\n                                  rank,\n                                  pred1,\n                                  pred2,\n                                  empty_set,\n                                  empty_set\n                               );\n\n      if( next_edge_and_weight_delta )\n      {\n\tbranching_queue.push(\n          branching_entry_t(\n\t    compute_branching_weight( w, best_branching ) -\n              (next_edge_and_weight_delta.get()).second,\n\t    (next_edge_and_weight_delta.get()).first,\n\t    comp,\n\t    best_branching,\n\t    empty_set,\n\t    empty_set\n\t  )\n\t);\n      }\n      else\n      {\n\treturn;\n      }\n\n      while( !branching_queue.empty() )\n      {\n\n\tunordered_set<Edge> branching;\n\n\tbranching_entry_t P = branching_queue.top();\n\n\tbranching_queue.pop();\n\n\tunordered_set<Edge> include_edges = P.include_edges;\n\n\tunordered_set<Edge> exclude_edges = P.exclude_edges;\n\n\tinclude_edges.insert( P.edge );\n\n\texclude_edges.insert( P.edge );\n\n\tbest_spanning_branching<edge_node_t, edge_node_queue_t>\n                              ( g,\n                                 branching,\n                                 v_id,\n                                 w,\n                                 comp,\n                                 rank,\n                                 pred1,\n                                 pred2,\n                                 P.include_edges,\n                                 exclude_edges\n                               );\n\n        branching_filter<unordered_set<Edge> > filter( &branching );\n        filtered_graph<Graph, branching_filter<unordered_set<Edge> > >\n          fg( g, filter );\n\n        if( !bp( fg ) ) return;\n\n\tnext_edge_and_weight_delta =\n\t  next_spanning_branching<edge_node_t, edge_node_queue_t>\n                                ( g,\n                                   P.branching,\n                                   v_id,\n                                   w,\n                                   comp,\n                                   rank,\n                                   pred1,\n                                   pred2,\n                                   include_edges,\n                                   P.exclude_edges\n                                 );\n\n\tif( next_edge_and_weight_delta )\n\t{\n\t  branching_queue.push(\n            branching_entry_t(\n\t      compute_branching_weight( w, P.branching ) -\n                (next_edge_and_weight_delta.get()).second,\n\t      (next_edge_and_weight_delta.get()).first,\n\t      comp,\n\t      P.branching,\n\t      include_edges,\n\t      P.exclude_edges\n\t    )\n\t  );\n\t}\n\n\tnext_edge_and_weight_delta =\n\t  next_spanning_branching<edge_node_t, edge_node_queue_t>\n                                ( g,\n                                   branching,\n                                   v_id,\n                                   w,\n                                   comp,\n                                   rank,\n                                   pred1,\n                                   pred2,\n                                   P.include_edges,\n                                   exclude_edges\n                                 );\n\n\tif( next_edge_and_weight_delta )\n\t{\n\t  branching_queue.push(\n            branching_entry_t(\n\t      P.weight - (next_edge_and_weight_delta.get()).second,\n\t      (next_edge_and_weight_delta.get()).first,\n\t      comp,\n\t      branching,\n\t      P.include_edges,\n\t      exclude_edges\n\t    )\n\t  );\n\t}\n\n      }\n\n    }\n\n    template <template<class...> class PriorityQueue,\n              typename Graph, typename BranchingProcessor, typename IndexMap,\n              typename WeightMap, typename Compare>\n    void \n    rank_spanning_branchings_dispatch2( const Graph& g,\n                                        BranchingProcessor bp,\n                                        IndexMap id_map,\n                                        WeightMap weight_map,\n                                        Compare compare\n                                      )\n    {\n\n      typename graph_traits<Graph>::vertices_size_type n = num_vertices(g);\n\n      if( num_vertices( g ) == 0 ) return; // Nothing to do.\n\n      typedef typename graph_traits<Graph>::vertices_size_type vertex_idx_t;\n      typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n\n      // Set up rank and parent for disjoint sets.\n      \n      std::vector<vertex_idx_t> rank( n );\n\n      std::vector<Vertex> pred1( n ), pred2( n );\n\n      rank_spanning_branchings_impl<PriorityQueue>(\n        g,\n        bp,\n        id_map,\n        weight_map,\n        compare,\n        make_iterator_property_map( rank.begin(), id_map, rank[0] ),\n        make_iterator_property_map( pred1.begin(), id_map, pred1[0] ),\n        make_iterator_property_map( pred2.begin(), id_map, pred2[0])\n      );\n\n    }\n\n    template <template<class...> class PriorityQueue,\n              typename Graph, typename BranchingProcessor, typename Compare,\n              typename P, typename T, typename R>\n    void rank_spanning_branchings_dispatch1(\n      const Graph& g,\n      BranchingProcessor bp,\n      Compare compare,\n      const bgl_named_params<P, T, R>& params\n    )\n    {\n\n      detail::rank_spanning_branchings_dispatch2<PriorityQueue>(\n        g,\n        bp,\n        choose_param(\n          get_param( params, vertex_index_t()), get( vertex_index, g )\n        ),\n        choose_param(\n          get_param( params, edge_weight_t()), get( edge_weight, g )\n        ),\n        compare\n      );\n\n    }\n \n    template <template<class...> class PriorityQueue,\n              typename Graph, typename BranchingProcessor,\n              typename P, typename T, typename R>\n    void rank_spanning_branchings_dispatch1(\n      const Graph& g,\n      BranchingProcessor bp,\n      param_not_found,\n      const bgl_named_params<P, T, R>& params\n    )\n    {\n\n      typedef\n        typename\n        property_traits<\n          typename property_map<Graph, edge_weight_t>::const_type\n        >::value_type weight_t;\n \n      BOOST_CONCEPT_ASSERT(( ComparableConcept<weight_t> ));\n\n      detail::rank_spanning_branchings_dispatch2<PriorityQueue>(\n        g,\n        bp,\n        choose_param(\n          get_param( params, vertex_index_t()), get( vertex_index, g )\n        ),\n        choose_param(\n          get_param( params, edge_weight_t()), get( edge_weight, g )\n        ),\n        std::less<weight_t>()\n      );\n\n    }\n \n  } // namespace detail \n\n  template <template<class...> class PriorityQueue = heap::fibonacci_heap,\n            typename Graph, typename BranchingProcessor,\n            typename P, typename T, typename R>\n  void \n  inline rank_spanning_branchings(\n    const Graph& g,\n    BranchingProcessor bp,\n    const bgl_named_params<P, T, R>& params\n  )\n  {\n\n    detail::rank_spanning_branchings_dispatch1<PriorityQueue>(\n      g,\n      bp,\n      get_param( params, distance_compare_t() ),\n      params\n    );\n \n  }\n\n  template <template<class...> class PriorityQueue = heap::fibonacci_heap,\n            typename Graph, typename BranchingProcessor>\n  void \n  inline rank_spanning_branchings( const Graph& g,\n                            BranchingProcessor bp\n                          )\n  {\n\n    bgl_named_params<int,int> params(0);\n    rank_spanning_branchings<PriorityQueue>( g, bp, params );\n\n  }\n\n} // namespace rsb\n\n#endif // RANK_SPANNING_BRANCHINGS_HPP\n", "meta": {"hexsha": "4a34c1af48ac632a6a65417ab610d99aecff54f5", "size": 36220, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rank_spanning_branchings.hpp", "max_stars_repo_name": "mbradle/rank_spanning_branchings", "max_stars_repo_head_hexsha": "86aa045beebe0e5f273f0ee1bce5e91ca4f4f079", "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/rank_spanning_branchings.hpp", "max_issues_repo_name": "mbradle/rank_spanning_branchings", "max_issues_repo_head_hexsha": "86aa045beebe0e5f273f0ee1bce5e91ca4f4f079", "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/rank_spanning_branchings.hpp", "max_forks_repo_name": "mbradle/rank_spanning_branchings", "max_forks_repo_head_hexsha": "86aa045beebe0e5f273f0ee1bce5e91ca4f4f079", "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.0457097033, "max_line_length": 80, "alphanum_fraction": 0.5291275538, "num_tokens": 7620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.29674485947994605}}
{"text": "#pragma once\n\n#include <map>\n\n#include <cvode/cvode.h>               /* prototypes for CVODE 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 <sundials/sundials_types.h>   /* defs. of realtype, sunindextype      */\n\n//#include <Eigen/Core>\n//#include <Eigen/Dense>\n\n#include <autodiff/forward/real.hpp>\n#include <autodiff/forward/real/eigen.hpp>\n#include \"types.hh\"\n//#define Ith(v,i)    NV_Ith_S(v,i-1)         /* Ith numbers components 1..NEQ */\n//#define IJth(A,i,j) SM_ELEMENT_D(A,i-1,j-1) /* IJth numbers rows,cols 1..NEQ */\n\nusing namespace types;\n\n\nnamespace cvode_wrapper\n{\n\nstd::map<std::string_view, int> cv_lmm = {{\"BDF\", CV_BDF}, {\"ADAMS\", CV_ADAMS}};\n\n\nstruct cv_options\n{\n    // Integrator settings\n    std::string step_method = \"BDF\";\n    double      rtol        = 1.0E-4;   // relative tolerance\n    double      atol        = 1.0E-14;   // absolute tolerance\n    int         max_steps   = 500;      // max number of steps between outputs\n    int         max_order   = 5;        // max order of linear multistep\n    double      t0          = 0.0;      // inital time\n    double      tf          = 1.0;      // final time\n    double      step_min    = 0.0;      // minimum step size\n    double      step_max    = 0.0;      // maximum step size (0 -> no max size)\n\n    // Linear solver and preconditioner settings\n    double      epslin      = 1.0E-6;    // linear solver tolerance factor\n\n    // output options\n    int         output_lvl  = 0;\n};\n\nstatic int check_retval(void *returnvalue, const char *funcname, int opt)\n{\n  int *retval;\n\n  /* Check if SUNDIALS function returned NULL pointer - no memory allocated */\n  if (opt == 0 && returnvalue == NULL) {\n    fmt::print(stderr, \"\\nSUNDIALS_ERROR: {} failed - returned NULL pointer\\n\\n\",\n\t    funcname);\n    return(1); }\n\n  /* Check if retval < 0 */\n  else if (opt == 1) {\n    retval = (int *) returnvalue;\n    if (*retval < 0) {\n      fmt::print(stderr, \"\\nSUNDIALS_ERROR: {} failed with retval = %d\\n\\n\",\n\t      funcname, *retval);\n      return(1); }}\n\n  /* Check if function returned NULL pointer - no memory allocated */\n  else if (opt == 2 && returnvalue == NULL) {\n    fmt::print(stderr, \"\\nMEMORY_ERROR: {} failed - returned NULL pointer\\n\\n\",\n\t    funcname);\n    return(1); }\n\n  return(0);\n}\n\n/* compare the solution at the final time 4e10s to a reference solution computed\n   using a relative tolerance of 1e-8 and absoltue tolerance of 1e-14 */\nstatic int check_ans(N_Vector y, realtype t, realtype rtol, N_Vector atol)\n{\n  int      passfail=0;        /* answer pass (0) or fail (1) retval */\n  N_Vector ref;               /* reference solution vector        */\n  N_Vector ewt;               /* error weight vector              */\n  realtype err;               /* wrms error                       */\n  realtype ONE=RCONST(1.0);\n  realtype ZERO=RCONST(0.0);\n\n  /* create reference solution and error weight vectors */\n  ref = N_VClone(y);\n  ewt = N_VClone(y);\n\n  /* set the reference solution data */\n  NV_Ith_S(ref,0) = RCONST(5.2083495894337328e-08);\n  NV_Ith_S(ref,1) = RCONST(2.0833399429795671e-13);\n  NV_Ith_S(ref,2) = RCONST(9.9999994791629776e-01);\n\n  /* compute the error weight vector, loosen atol */\n  N_VAbs(ref, ewt);\n  N_VLinearSum(rtol, ewt, RCONST(10.0), atol, ewt);\n  if (N_VMin(ewt) <= ZERO) {\n    fmt::print(stderr, \"\\nSUNDIALS_ERROR: check_ans failed - ewt <= 0\\n\\n\");\n    return(-1);\n  }\n  fmt::print(stdout, \"\\n{} {} {}\\n\", NV_Ith_S(ewt,0),NV_Ith_S(ewt,1),NV_Ith_S(ewt,2));\n  N_VInv(ewt, ewt);\n\n  /* compute the solution error */\n  N_VLinearSum(ONE, y, -ONE, ref, ref);\n  err = N_VWrmsNorm(ref, ewt);\n\n\n  /* is the solution within the tolerances? */\n  passfail = (err < ONE) ? 0 : 1;\n\n  if (passfail) {\n    fmt::print(stdout, \"\\nSUNDIALS_WARNING: check_ans error={}\\n\\n\", err);\n  }\n\n  /* Free vectors */\n  N_VDestroy(ref);\n  N_VDestroy(ewt);\n\n\n  return(passfail);\n}\n\ntemplate<class System>\nstruct cvode_stepper\n{\n    // options\n    cv_options options;\n\n    // cvode context pointer\n    void *cvode_mem;\n\n    size_t N;           // system size\n    N_Vector cv_y, abst;     // ongoing solution\n    SUNMatrix A;        //\n    SUNLinearSolver LS;\n\n    cvode_stepper(cv_options opts) : options(std::move(opts)), cvode_mem(nullptr)\n    {\n\n    }\n\n    ~cvode_stepper()\n    {\n        CVodeFree(&cvode_mem);\n        N_VDestroy(cv_y); N_VDestroy(abst);\n        SUNLinSolFree(LS);\n        SUNMatDestroy(A);\n    }\n\n    auto copy_nvect(const N_Vector a, vector_t& b)\n    {\n        for(int i = 0; i < N; ++i)\n        {\n            b(i) = NV_Ith_S(a, i);\n        }\n    }\n\n    auto initialize(vector_t& y0)\n    {\n        // set system size\n        N = y0.rows();\n\n        // allocate solution vector\n        //y = N_VNew_Serial(N);\n\n        //cv_y = N_VMake_Serial(N, static_cast<Eigen::VectorXd>(y0).data());\n        cv_y = N_VMake_Serial(N, y0.data());\n        //cv_y = N_VNew_Serial(N);\n\n        // fill solution vector\n        //copy_evect(y0, cv_y);\n\n        // linear solver data\n        // TODO: implement sparse\n        A = SUNDenseMatrix(N, N);\n        LS = SUNLinSol_Dense(cv_y, A);\n\n        // init a new cvode context\n        cvode_mem = CVodeCreate(cv_lmm[options.step_method]);\n        // init integrator memory\n\n        CVodeInit(cvode_mem, [](realtype t, N_Vector y, N_Vector ydot, void* user_data)\n            {\n                System* sys = static_cast<System*>(user_data);\n                vector_map_t yref(NV_DATA_S(y), NV_LENGTH_S(y));\n                vector_map_t fref(NV_DATA_S(ydot), NV_LENGTH_S(ydot));\n\n                fref = sys->f(yref, t);\n\n                return 0;\n\n            },\n        options.t0, cv_y);\n        // set max step attempts\n        CVodeSetMaxNumSteps(cvode_mem, options.max_steps);\n        // set max/min step sizes\n        CVodeSetMinStep(cvode_mem, options.step_min);\n        CVodeSetMaxStep(cvode_mem, options.step_max);\n        // set max order\n        CVodeSetMaxOrd(cvode_mem, options.max_order);\n        // set tolarances\n        // TODO: allow vector tolerance\n        abst = N_VNew_Serial(N);\n        NV_Ith_S(abst, 0) = 1.0E-8; NV_Ith_S(abst, 1) = 1.0E-14; NV_Ith_S(abst, 2) = 1.0E-6;\n        CVodeSVtolerances(cvode_mem, options.rtol, abst);\n        //CVodeSStolerances(cvode_mem, options.rtol, options.atol);\n        // set linear solver\n        CVodeSetLinearSolver(cvode_mem, LS, A);\n        // set jacobin\n        CVodeSetJacFn(cvode_mem, [](realtype t, N_Vector y, N_Vector fy, SUNMatrix J,\n            void *user_data, N_Vector tmp1, N_Vector tmp2, N_Vector tmp3)\n            {\n                System* sys = static_cast<System*>(user_data);\n\n                vector_map_t yref(NV_DATA_S(y), NV_LENGTH_S(y));\n                matrix_map_t Jref(SM_DATA_D(J), SM_ROWS_D(J), SM_COLUMNS_D(J));\n\n                Jref = sys->J(yref, t);\n                return 0;\n            }\n        );\n\n\n    }\n\n    auto print_sol(double sol_time)\n    {\n        fmt::print(\"At t = {} y = {} {} {}\\n\", sol_time, NV_Ith_S(cv_y,0), NV_Ith_S(cv_y,1),NV_Ith_S(cv_y,2));\n    }\n\n    auto step()\n    {\n\n    }\n\n    auto check_retval(void *returnvalue, const char *funcname, int opt)\n    {\n        int *retval;\n\n        /* Check if SUNDIALS function returned NULL pointer - no memory allocated */\n        if (opt == 0 && returnvalue == NULL) {\n            fmt::print(stderr, \"\\nSUNDIALS_ERROR: {} failed - returned NULL pointer\\n\\n\",\n                funcname);\n            return(1); }\n\n        /* Check if retval < 0 */\n        else if (opt == 1) {\n            retval = (int *) returnvalue;\n            if (*retval < 0) {\n            fmt::print(stderr, \"\\nSUNDIALS_ERROR: {} failed with retval = %d\\n\\n\",\n                funcname, *retval);\n            return(1); }}\n\n        /* Check if function returned NULL pointer - no memory allocated */\n        else if (opt == 2 && returnvalue == NULL) {\n            fmt::print(stderr, \"\\nMEMORY_ERROR: {} failed - returned NULL pointer\\n\\n\",\n                funcname);\n            return(1); }\n\n        return(0);\n    }\n    auto letsgo()\n    {\n        auto iout = 0;\n        auto tout = 0.4;\n        double sol_time;\n        while(1)\n        {\n            auto rstep = CVode(cvode_mem, tout, cv_y, &sol_time, CV_NORMAL);\n            print_sol(sol_time);\n            if (check_retval(&rstep, \"CVode\", 1)) break;\n            if (rstep == CV_SUCCESS) {\n                iout++;\n                tout *= 10.0;\n            }\n        if (iout == 12) break;\n        }\n        check_ans(cv_y,sol_time,options.rtol,abst);\n    }\n\n};\n\n}", "meta": {"hexsha": "d7ac417369d3df409c6b5bc95ab5dc1392a8a96e", "size": 8705, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/cvode_wrapper.hh", "max_stars_repo_name": "cmauney/sundials_eigen", "max_stars_repo_head_hexsha": "88a2b8c894da3ed144dfab95cc4e5988e8b7f167", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cvode_wrapper.hh", "max_issues_repo_name": "cmauney/sundials_eigen", "max_issues_repo_head_hexsha": "88a2b8c894da3ed144dfab95cc4e5988e8b7f167", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cvode_wrapper.hh", "max_forks_repo_name": "cmauney/sundials_eigen", "max_forks_repo_head_hexsha": "88a2b8c894da3ed144dfab95cc4e5988e8b7f167", "max_forks_repo_licenses": ["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.4370629371, "max_line_length": 110, "alphanum_fraction": 0.5702469845, "num_tokens": 2491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.29674485947994605}}
{"text": "//==============================================================================\n//         Copyright 2014 - Jean-Thierry Lapresté\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   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_FACTORIZATIONS_SCHUR_HPP_INCLUDED\n#define NT2_LINALG_FUNCTIONS_FACTORIZATIONS_SCHUR_HPP_INCLUDED\n\n\n#include <nt2/include/functions/schur.hpp>\n#include <boost/dispatch/attributes.hpp>\n#include <nt2/core/container/table/table.hpp>\n#include <nt2/include/functions/geesx.hpp>\n#include <nt2/include/functions/geesx_no_w.hpp>\n#include <nt2/include/functions/geesx1.hpp>\n#include <nt2/include/functions/geesxw.hpp>\n#include <nt2/include/functions/height.hpp>\n#include <nt2/include/functions/isreal.hpp>\n#include <nt2/include/functions/of_size.hpp>\n#include <nt2/include/functions/real.hpp>\n#include <nt2/include/functions/resize.hpp>\n#include <nt2/include/functions/tie.hpp>\n#include <nt2/include/functions/issquare.hpp>\n#include <nt2/sdk/meta/as_real.hpp>\n#include <nt2/sdk/complex/meta/is_complex.hpp>\n#include <nt2/linalg/options.hpp>\n#include <nt2/linalg/details/utility/lapack_verify.hpp>\n#include <nt2/core/container/dsl/as_terminal.hpp>\n#include <nt2/core/utility/assign_swap.hpp>\n#include <boost/assert.hpp>\n#include <boost/mpl/bool.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/dispatch/meta/strip.hpp>\n\nnamespace nt2 { namespace ext\n{\n  //============================================================================\n  //SCHUR Scalar\n  //============================================================================\n  BOOST_DISPATCH_IMPLEMENT  ( schur_, tag::cpu_\n                            , (A0)\n                            , (scalar_<unspecified_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE result_type operator()(const A0& a0) const\n    {\n      return a0;\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( schur_, tag::cpu_\n                            , (A0)(A1)\n                            , (scalar_<unspecified_<A0> >)\n                              (unspecified_<A1>)\n                            )\n  {\n    typedef A0                                                      otype_t;\n    typedef typename nt2::meta::as_real<A0>::type                   rtype_t;\n    typedef typename meta::strip<A1>::type                            opt_t;\n    typedef typename boost::mpl::if_ < boost::is_same< opt_t, nt2::policy<ext::real_> >\n                              , rtype_t\n                              , otype_t\n                              >::type                           result_type;\n\n    BOOST_FORCEINLINE result_type operator()(const A0& a0, const A1&) const\n    {\n      return eval(a0, opt_t());\n    }\n  private :\n    template < class T >\n    BOOST_FORCEINLINE result_type eval( const A0& a0, const T& ) const\n    {\n      return a0;\n    }\n\n    BOOST_FORCEINLINE result_type eval( const A0& a0, nt2::policy<ext::real_> const & ) const\n    {\n      BOOST_ASSERT_MSG(isreal(a0),\n                       \"all input matrix elements are to be real to support\"\n                       \"'real_' option with complex type input\");\n      return real(a0);\n    }\n\n  };\n\n\n  //============================================================================\n  //SCHUR\n  //============================================================================\n  BOOST_DISPATCH_IMPLEMENT  ( schur_, tag::cpu_\n                            , (A0)(N0)(A1)(N1)\n                            , ((node_<A0, nt2::tag::schur_\n                                    , N0, nt2::container::domain\n                                      >\n                              ))\n                              ((node_<A1, nt2::tag::tie_\n                                    , N1, nt2::container::domain\n                                     >\n                              ))\n                            )\n  {\n    typedef void  result_type;\n    typedef typename boost::proto::result_of::child_c<A0&,0>::value_type child0;\n    typedef typename child0::value_type                                  type_t;\n    typedef typename nt2::meta::as_complex<type_t>::type                ctype_t;\n    typedef typename nt2::meta::as_real<type_t>::type                   rtype_t;\n    typedef rtype_t T;\n    typedef nt2::memory::container<tag::table_,  type_t, nt2::_2D>   o_semantic;\n    typedef nt2::memory::container<tag::table_, rtype_t, nt2::_2D>   r_semantic;\n    typedef nt2::memory::container<tag::table_, ctype_t, nt2::_2D>   c_semantic;\n\n    BOOST_FORCEINLINE result_type operator()( A0& a0, A1& a1 ) const\n    {\n      BOOST_ASSERT_MSG(issquare(boost::proto::child_c<0>(a0)),\"first input must be square\");\n      eval(a0, a1, N0(), N1());\n    }\n  private:\n    //==========================================================================\n    /// INTERNAL ONLY - T = SCHUR(A)\n    // returns the schur matrix\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<1> const&\n              , boost::mpl::long_<1> const&\n              ) const\n    {\n      NT2_AS_TERMINAL_INOUT(o_semantic, a, boost::proto::child_c<0>(a0), boost::proto::child_c<0>(a1));\n      NT2_LAPACK_VERIFY(nt2::geesx(boost::proto::value(a), type_t(0)));\n      boost::proto::child_c<0>(a1) = a;\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - T = SCHUR(A, cmplx_/real_)\n    // returns T in its real or complex form or only the eigenvalues\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<2> const&\n              , boost::mpl::long_<1> const&\n              ) const\n    {\n       eval1_2(a0, a1,\n               boost::proto::value(boost::proto::child_c<1>(a0)));\n    }\n\n\n    //==========================================================================\n    /// INTERNAL ONLY\n    BOOST_FORCEINLINE\n    void eval1_2 ( A0& a0, A1& a1\n                 , nt2::policy<ext::real_>\n                 ) const\n    {\n      BOOST_ASSERT_MSG(isreal(boost::proto::child_c<0>(a0)),\n                       \"all input matrix elements are to be real to support\"\n                       \"'real_' option with complex type input\");\n      NT2_AS_TERMINAL_INOUT(r_semantic, t\n                           , real(boost::proto::child_c<0>(a0))\n                           , boost::proto::child_c<0>(a1));\n      // Here one cannot be sure that boost::proto::child_c<0>(a1) is real typed\n      // as the 'real'schur decomposition can be put in a complex table\n      // so we cannot pass it to geesx that needs a real table\n      NT2_LAPACK_VERIFY(nt2::geesx(boost::proto::value(t), rtype_t(0)));\n      assign_swap(boost::proto::child_c<0>(a1), t);\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY\n    BOOST_FORCEINLINE\n    void eval1_2 ( A0& a0, A1& a1\n                 , nt2::policy<ext::eigs_>\n                 ) const\n    {\n      nt2::container::table<type_t> work;\n      NT2_AS_TERMINAL_INOUT(o_semantic, t\n                           , boost::proto::child_c<0>(a0), work);\n      NT2_AS_TERMINAL_OUT  (c_semantic, w\n                           , boost::proto::child_c<0>(a1));\n      NT2_LAPACK_VERIFY( nt2::geesxw(boost::proto::value(t),\n                                     boost::proto::value(w)));\n      w.resize(of_size(height(t), 1));\n      assign_swap(boost::proto::child_c<0>(a1), w);\n   }\n\n    //==========================================================================\n    /// INTERNAL ONLY\n    BOOST_FORCEINLINE\n    void eval1_2 ( A0& a0, A1& a1\n                 , nt2::policy<ext::cmplx_>\n                 ) const\n    {\n      typedef typename meta::is_complex<type_t>::type is_cmplx_t;\n      eval1_2c(a0, a1, is_cmplx_t());\n    }\n\n    BOOST_FORCEINLINE\n    void eval1_2c ( A0& a0, A1& a1\n                 , boost::mpl::false_\n                 ) const\n    {\n      // Here boost::proto::child_c<0>(a0) is real and geesx has to receive a complex table\n      NT2_AS_TERMINAL_INOUT(c_semantic, t, boost::proto::child_c<0>(a0), boost::proto::child_c<0>(a1));\n      NT2_LAPACK_VERIFY(nt2::geesx(boost::proto::value(t), ctype_t(0)));\n      assign_swap(boost::proto::child_c<0>(a1), t);\n    }\n\n    BOOST_FORCEINLINE\n    void eval1_2c ( A0& a0, A1& a1\n                 , boost::mpl::true_\n                 ) const\n    {\n      // Here  boost::proto::child_c<0>(a0) is complex\n      NT2_AS_TERMINAL_INOUT(c_semantic, t\n                           , boost::proto::child_c<0>(a0), boost::proto::child_c<0>(a1));\n      NT2_LAPACK_VERIFY(nt2::geesx(boost::proto::value(t), ctype_t(0)));\n      assign_swap(boost::proto::child_c<0>(a1), t);\n     }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [U, T]= SCHUR(A)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<1> const&\n              , boost::mpl::long_<2> const&\n              ) const\n    {\n      NT2_AS_TERMINAL_INOUT(o_semantic, t\n                           , boost::proto::child_c<0>(a0), boost::proto::child_c<1>(a1));\n      NT2_AS_TERMINAL_OUT  (o_semantic, u\n                           , boost::proto::child_c<0>(a1));\n      size_t n = height(t);\n      u.resize(of_size(n, n));\n      NT2_LAPACK_VERIFY(nt2::geesx_no_w( boost::proto::value(t)\n                                       , boost::proto::value(u)\n                                   ));\n      assign_swap(boost::proto::child_c<0>(a1), u);\n      assign_swap(boost::proto::child_c<1>(a1), t);\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [T, U]= SCHUR(A, sort_/cmplx_/real_ )\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<2> const&\n              , boost::mpl::long_<2> const&\n              ) const\n    {\n      eval2_2( a0, a1\n             , boost::proto::value(boost::proto::child_c<1>(a0)));\n\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY\n    BOOST_FORCEINLINE\n    void eval2_2 ( A0& a0, A1& a1\n                 , nt2::policy<ext::real_>\n                 ) const\n    {\n      BOOST_ASSERT_MSG(isreal(boost::proto::child_c<0>(a0)),\n                       \"all input matrix elements are to be real to support \"\n                       \"'real_' option with complex type input\");\n      NT2_AS_TERMINAL_INOUT(r_semantic, t\n                           , real(boost::proto::child_c<0>(a0)), boost::proto::child_c<1>(a1));\n      NT2_AS_TERMINAL_OUT  (r_semantic, u\n                           , boost::proto::child_c<0>(a1));\n      size_t n = height(t);\n      u.resize(of_size(n, n));\n      NT2_LAPACK_VERIFY(nt2::geesx_no_w( boost::proto::value(t)\n                                       , boost::proto::value(u)\n                                   ));\n      assign_swap(boost::proto::child_c<0>(a1), u);\n      assign_swap(boost::proto::child_c<1>(a1), t);\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY\n    BOOST_FORCEINLINE\n    void eval2_2 ( A0& a0, A1& a1\n                 , nt2::policy<ext::cmplx_>\n                 ) const\n    {\n      NT2_AS_TERMINAL_INOUT(c_semantic, t\n                           , boost::proto::child_c<0>(a0), boost::proto::child_c<1>(a1));\n      NT2_AS_TERMINAL_OUT  (c_semantic, u\n                           , boost::proto::child_c<0>(a1));\n      size_t n = nt2::height(t);\n      u.resize(of_size(n, n));\n      NT2_LAPACK_VERIFY(nt2::geesx_no_w( boost::proto::value(t)\n                                       , boost::proto::value(u)\n                                   ));\n      assign_swap(boost::proto::child_c<0>(a1), u);\n      assign_swap(boost::proto::child_c<1>(a1), t);\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [U, T, W]= SCHUR(A)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<1> const&\n              , boost::mpl::long_<3> const&\n              ) const\n    {\n      NT2_AS_TERMINAL_INOUT(o_semantic, t\n                           , boost::proto::child_c<0>(a0), boost::proto::child_c<1>(a1));\n      NT2_AS_TERMINAL_OUT  (o_semantic, u\n                           , boost::proto::child_c<0>(a1));\n      NT2_AS_TERMINAL_OUT  (c_semantic, w\n                           , boost::proto::child_c<2>(a1));\n      size_t n =   height(t);\n      u.resize(of_size(n, n));\n      w.resize(of_size(n, 1));\n      NT2_LAPACK_VERIFY(nt2::geesx( boost::proto::value(t)\n                                  , boost::proto::value(w)\n                                  , boost::proto::value(u)\n                              ));\n      assign_swap(boost::proto::child_c<0>(a1), u);\n      assign_swap(boost::proto::child_c<1>(a1), t);\n      assign_swap(boost::proto::child_c<2>(a1), w);\n\n    }\n    //==========================================================================\n    /// INTERNAL ONLY - [U, T, W]= SCHUR(A, real_/complex_)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<2> const&\n              , boost::mpl::long_<3> const&\n              ) const\n    {\n      eval3_2(a0, a1,\n              boost::proto::value(boost::proto::child_c<1>(a0)));\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY\n    BOOST_FORCEINLINE\n    void eval3_2 ( A0& a0, A1& a1\n                 , nt2::policy<ext::cmplx_>\n                 ) const\n    {\n      NT2_AS_TERMINAL_INOUT(c_semantic, t\n                           , boost::proto::child_c<0>(a0), boost::proto::child_c<1>(a1));\n      NT2_AS_TERMINAL_OUT  (c_semantic, u\n                           , boost::proto::child_c<0>(a1));\n      NT2_AS_TERMINAL_OUT  (c_semantic, w\n                           , boost::proto::child_c<2>(a1));\n      size_t n = nt2::height(t);\n      u.resize(of_size(n, n));\n      w.resize(of_size(n, 1));\n      NT2_LAPACK_VERIFY(nt2::geesx( boost::proto::value(t)\n                                  , boost::proto::value(w)\n                                  , boost::proto::value(u)\n                                  ));\n      assign_swap(boost::proto::child_c<0>(a1), u);\n      assign_swap(boost::proto::child_c<1>(a1), t);\n      assign_swap(boost::proto::child_c<2>(a1), w);\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY\n    BOOST_FORCEINLINE\n    void eval3_2 ( A0& a0, A1& a1\n                 , nt2::policy<ext::real_>\n                 ) const\n    {\n      BOOST_ASSERT_MSG(isreal(boost::proto::child_c<0>(a0)),\n                       \"all input matrix elements are to be real to support \"\n                       \"'real_' option with complex type input\");\n      NT2_AS_TERMINAL_INOUT(r_semantic, t\n                           , real(boost::proto::child_c<0>(a0)), boost::proto::child_c<1>(a1));\n      NT2_AS_TERMINAL_OUT  (r_semantic, u\n                           , boost::proto::child_c<0>(a1));\n      NT2_AS_TERMINAL_OUT  (c_semantic, w\n                           , boost::proto::child_c<2>(a1));\n      size_t n = nt2::height(t);\n      u.resize(of_size(n, n));\n      w.resize(of_size(n, 1));\n      NT2_LAPACK_VERIFY(nt2::geesx( boost::proto::value(t)\n                                  , boost::proto::value(w)\n                                  , boost::proto::value(u)\n                                  ));\n      assign_swap(boost::proto::child_c<0>(a1), u);\n      assign_swap(boost::proto::child_c<1>(a1), t);\n      assign_swap(boost::proto::child_c<2>(a1), w);\n    }\n  };\n\n\n} }\n\n#endif\n\n\n", "meta": {"hexsha": "fa989187291d8f89aad7f2df4ccad5c2434095fc", "size": 15887, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/functions/factorizations/schur.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/factorizations/schur.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/factorizations/schur.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": 39.7175, "max_line_length": 103, "alphanum_fraction": 0.4759866558, "num_tokens": 3972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2967118357622337}}
{"text": "// ########################## OPEN3D ORIGINAL WORK ############################\n// ----------------------------------------------------------------------------\n// -                        Open3D: www.open3d.org                            -\n// ----------------------------------------------------------------------------\n// The MIT License (MIT)\n//\n// Copyright (c) 2018 www.open3d.org\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\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n// ----------------------------------------------------------------------------\n//\n//\n//\n// ########################## PROCARE MODIFIED WORK ############################\n// Mofifications: block of codes specified by /*kimeguida*/\n// -----------------------------------------------------------------------------\n// <                                  ProCare                                  >\n// -----------------------------------------------------------------------------\n// The MIT License (MIT)\n//\n// Copyright (c) 2020 Merveille Eguida\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\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n\n\n#include \"Feature.h\"\n\n#include <Eigen/Dense>\n#include <Core/Utility/Console.h>\n#include <Core/Geometry/PointCloud.h>\n#include <Core/Geometry/KDTreeFlann.h>\n\nnamespace open3d {\n\nnamespace {\n\nEigen::Vector4d ComputePairFeatures(const Eigen::Vector3d &p1,\n                                    const Eigen::Vector3d &n1,\n                                    const Eigen::Vector3d &p2,\n                                    const Eigen::Vector3d &n2) {\n    Eigen::Vector4d result;\n    Eigen::Vector3d dp2p1 = p2 - p1;\n    result(3) = dp2p1.norm();\n    if (result(3) == 0.0) {\n        return Eigen::Vector4d::Zero();\n    }\n    auto n1_copy = n1;\n    auto n2_copy = n2;\n    double angle1 = n1_copy.dot(dp2p1) / result(3);\n    double angle2 = n2_copy.dot(dp2p1) / result(3);\n    if (acos(fabs(angle1)) > acos(fabs(angle2))) {\n        n1_copy = n2;\n        n2_copy = n1;\n        dp2p1 *= -1.0;\n        result(2) = -angle2;\n    } else {\n        result(2) = angle1;\n    }\n    auto v = dp2p1.cross(n1_copy);\n    double v_norm = v.norm();\n    if (v_norm == 0.0) {\n        return Eigen::Vector4d::Zero();\n    }\n    v /= v_norm;\n    auto w = n1_copy.cross(v);\n    result(1) = v.dot(n2_copy);\n    result(0) = atan2(w.dot(n2_copy), n1_copy.dot(n2_copy));\n    return result;\n}\n\nstd::shared_ptr<Feature> ComputeSPFHFeature(\n        const PointCloud &input,\n        const KDTreeFlann &kdtree,\n        const KDTreeSearchParam &search_param) {\n    auto feature = std::make_shared<Feature>();\n    feature->Resize(33, (int)input.points_.size());\n#ifdef _OPENMP\n#pragma omp parallel for schedule(static)\n#endif\n    for (int i = 0; i < (int)input.points_.size(); i++) {\n        const auto &point = input.points_[i];\n        const auto &normal = input.normals_[i];\n        std::vector<int> indices;\n        std::vector<double> distance2;\n        if (kdtree.Search(point, search_param, indices, distance2) > 1) {\n            // only compute SPFH feature when a point has neighbors\n            double hist_incr = 100.0 / (double)(indices.size() - 1);\n            for (size_t k = 1; k < indices.size(); k++) {\n                // skip the point itself, compute histogram\n                auto pf = ComputePairFeatures(point, normal,\n                                              input.points_[indices[k]],\n                                              input.normals_[indices[k]]);\n                int h_index = (int)(floor(11 * (pf(0) + M_PI) / (2.0 * M_PI)));\n                if (h_index < 0) h_index = 0;\n                if (h_index >= 11) h_index = 10;\n                feature->data_(h_index, i) += hist_incr;\n                h_index = (int)(floor(11 * (pf(1) + 1.0) * 0.5));\n                if (h_index < 0) h_index = 0;\n                if (h_index >= 11) h_index = 10;\n                feature->data_(h_index + 11, i) += hist_incr;\n                h_index = (int)(floor(11 * (pf(2) + 1.0) * 0.5));\n                if (h_index < 0) h_index = 0;\n                if (h_index >= 11) h_index = 10;\n                feature->data_(h_index + 22, i) += hist_incr;\n            }\n        }\n    }\n    return feature;\n}\n\n/*kimeguida*/\nstd::shared_ptr<Feature> ComputeCSPFHFeature(\n        const PointCloud &input,\n        const KDTreeFlann &kdtree,\n        const KDTreeSearchParam &search_param) {\n    auto feature = std::make_shared<Feature>();\n    feature->Resize(41, (int)input.points_.size());\n#ifdef _OPENMP\n#pragma omp parallel for schedule(static)\n#endif\n    for (int i = 0; i < (int)input.points_.size(); i++) {\n        const auto &point = input.points_[i];\n        const auto &normal = input.normals_[i];\n        std::vector<int> indices;\n        std::vector<double> distance2;\n        if (kdtree.Search(point, search_param, indices, distance2) > 1) {\n            // only compute CSPFH feature when a point has neighbors\n            double hist_incr = 100.0 / (double)(indices.size() - 1);\n            for (size_t k = 1; k < indices.size(); k++) {\n                // skip the point itself, compute histogram\n                auto pf = ComputePairFeatures(point, normal,\n                                              input.points_[indices[k]],\n                                              input.normals_[indices[k]]);\n                int h_index = (int)(floor(11 * (pf(0) + M_PI) / (2.0 * M_PI)));\n                if (h_index < 0) h_index = 0;\n                if (h_index >= 11) h_index = 10;\n                feature->data_(h_index, i) += hist_incr;\n                h_index = (int)(floor(11 * (pf(1) + 1.0) * 0.5));\n                if (h_index < 0) h_index = 0;\n                if (h_index >= 11) h_index = 10;\n                feature->data_(h_index + 11, i) += hist_incr;\n                h_index = (int)(floor(11 * (pf(2) + 1.0) * 0.5));\n                if (h_index < 0) h_index = 0;\n                if (h_index >= 11) h_index = 10;\n                feature->data_(h_index + 22, i) += hist_incr;\n            }\n\n            double c_hist_incr = 100.0 / (double)(indices.size());\n            const char *CA_c = \"16741671\";\n            const char *CZ_c = \"4646984\";\n            const char *O_c = \"15219528\";\n            const char *OD1_c = \"0\";\n            const char *OG_c = \"8204959\";\n            const char *N_c = \"30894\";\n            const char *NZ_c = \"15231913\";\n            const char *DU_c = \"7566712\";\n\n            Eigen::Vector3d CA_rgb = ASCIIPCDColorToRGB(CA_c, 'F', 4);\n            Eigen::Vector3d CZ_rgb = ASCIIPCDColorToRGB(CZ_c, 'F', 4);\n            Eigen::Vector3d O_rgb = ASCIIPCDColorToRGB(O_c, 'F', 4);\n            Eigen::Vector3d OD1_rgb = ASCIIPCDColorToRGB(OD1_c, 'F', 4);\n            Eigen::Vector3d OG_rgb = ASCIIPCDColorToRGB(OG_c, 'F', 4);\n            Eigen::Vector3d N_rgb = ASCIIPCDColorToRGB(N_c, 'F', 4);\n            Eigen::Vector3d NZ_rgb = ASCIIPCDColorToRGB(NZ_c, 'F', 4);\n            Eigen::Vector3d DU_rgb = ASCIIPCDColorToRGB(DU_c, 'F', 4);\n\n            for (size_t k = 0; k < indices.size(); k++) {\n                // include the point itself, compute histogram\n                if (input.colors_[indices[k]] == CA_rgb) {\n                    int c_h_index = 33;\n                    feature->data_(c_h_index, i) += c_hist_incr;\n                }\n                if (input.colors_[indices[k]] == CZ_rgb) {\n                    int c_h_index = 34;\n                    feature->data_(c_h_index, i) += c_hist_incr;\n                }\n                if (input.colors_[indices[k]] == O_rgb) {\n                    int c_h_index = 35;\n                    feature->data_(c_h_index, i) += c_hist_incr;\n                }\n                if (input.colors_[indices[k]] == OD1_rgb) {\n                    int c_h_index = 36;\n                    feature->data_(c_h_index, i) += c_hist_incr;\n                }\n                if (input.colors_[indices[k]] == OG_rgb) {\n                    int c_h_index = 37;\n                    feature->data_(c_h_index, i) += c_hist_incr;\n                }\n                if (input.colors_[indices[k]] == N_rgb) {\n                    int c_h_index = 38;\n                    feature->data_(c_h_index, i) += c_hist_incr;\n                }\n                if (input.colors_[indices[k]] == NZ_rgb) {\n                    int c_h_index = 39;\n                    feature->data_(c_h_index, i) += c_hist_incr;\n                }\n                if (input.colors_[indices[k]] == DU_rgb) {\n                    int c_h_index = 40;\n                    feature->data_(c_h_index, i) += c_hist_incr;\n                }\n            }\n        }\n    }\n    return feature;\n}\n/*kimeguida*/\n\n}  // unnamed namespace\n\nstd::shared_ptr<Feature> ComputeFPFHFeature(\n        const PointCloud &input,\n        const KDTreeSearchParam &search_param /* = KDTreeSearchParamKNN()*/) {\n    auto feature = std::make_shared<Feature>();\n    feature->Resize(33, (int)input.points_.size());\n    if (input.HasNormals() == false) {\n        PrintDebug(\n                \"[ComputeFPFHFeature] Failed because input point cloud has no \"\n                \"normal.\\n\");\n        return feature;\n    }\n    KDTreeFlann kdtree(input);\n    auto spfh = ComputeSPFHFeature(input, kdtree, search_param);\n#ifdef _OPENMP\n#pragma omp parallel for schedule(static)\n#endif\n    for (int i = 0; i < (int)input.points_.size(); i++) {\n        const auto &point = input.points_[i];\n        std::vector<int> indices;\n        std::vector<double> distance2;\n        if (kdtree.Search(point, search_param, indices, distance2) > 1) {\n            double sum[3] = {0.0, 0.0, 0.0};\n            for (size_t k = 1; k < indices.size(); k++) {\n                // skip the point itself\n                double dist = distance2[k];\n                if (dist == 0.0) continue;\n                for (int j = 0; j < 33; j++) {\n                    double val = spfh->data_(j, indices[k]) / dist;\n                    sum[j / 11] += val;\n                    feature->data_(j, i) += val;\n                }\n            }\n            for (int j = 0; j < 3; j++)\n                if (sum[j] != 0.0) sum[j] = 100.0 / sum[j];\n            for (int j = 0; j < 33; j++) {\n                feature->data_(j, i) *= sum[j / 11];\n                // The commented line is the fpfh function in the paper.\n                // But according to PCL implementation, it is skipped.\n                // Our initial test shows that the full fpfh function in the\n                // paper seems to be better than PCL implementation. Further\n                // test required.\n                feature->data_(j, i) += spfh->data_(j, i);\n            }\n        }\n    }\n    return feature;\n}\n\n/*kimeguida*/\nEigen::Vector3d ASCIIPCDColorToRGB(const char *color_ptr,\n                                   const char type,\n                                   const int size) {\n    if ((size == 4) && (type == 'F')) {\n        std::uint8_t c_data[4] = {0, 0, 0, 0};\n        char *end;\n        std::float_t c_value = std::strtof(color_ptr, &end);\n        memcpy(c_data, &c_value, 4);\n        return Eigen::Vector3d((double)c_data[2] / 255.0,\n                               (double)c_data[1] / 255.0,\n                               (double)c_data[0] / 255.0);\n    } else {\n        return Eigen::Vector3d::Zero();\n    }\n}\n\nstd::shared_ptr<Feature> ComputeCFPFHFeature(\n        const PointCloud &input,\n        const KDTreeSearchParam\n                &search_param /* = geometry::KDTreeSearchParamKNN()*/) {\n    auto feature = std::make_shared<Feature>();\n    feature->Resize(41, (int)input.points_.size());\n    if (input.HasNormals() == false) {\n        PrintDebug(\n                \"[ComputeCFPFHFeature] Failed because input point cloud has no \"\n                \"normal.\\n\");\n        return feature;\n    }\n    if (input.HasColors() == false) {\n        PrintDebug(\n                \"[ComputeCFPFHFeature] Failed because input point cloud has no \"\n                \"color.\\n\");\n        return feature;\n    }\n    KDTreeFlann kdtree(input);\n    auto cspfh = ComputeCSPFHFeature(input, kdtree, search_param);\n#ifdef _OPENMP\n#pragma omp parallel for schedule(static)\n#endif\n    for (int i = 0; i < (int)input.points_.size(); i++) {\n        const auto &point = input.points_[i];\n        std::vector<int> indices;\n        std::vector<double> distance2;\n        if (kdtree.Search(point, search_param, indices, distance2) > 1) {\n            double sum[3] = {0.0, 0.0, 0.0};\n            double c_sum = 0;\n            for (size_t k = 1; k < indices.size(); k++) {\n                // skip the point itself\n                double dist = distance2[k];\n                if (dist == 0.0) continue;\n                for (int j = 0; j < 33; j++) {\n                    double val = cspfh->data_(j, indices[k]) / dist;\n                    sum[j / 11] += val;\n                    feature->data_(j, i) += val;\n                }\n                for (int j = 33; j < 41; j++) {\n                    double val = cspfh->data_(j, indices[k]) / dist;\n                    c_sum += val;\n                    feature->data_(j, i) += val;\n                }\n            }\n            for (int j = 0; j < 3; j++)\n                if (sum[j] != 0.0) sum[j] = 100.0 / sum[j];\n            for (int j = 0; j < 33; j++) {\n                feature->data_(j, i) *= sum[j / 11];\n                // The commented line is the fpfh function in the paper.\n                // But according to PCL implementation, it is skipped.\n                // Our initial test shows that the full fpfh function in the\n                // paper seems to be better than PCL implementation. Further\n                // test required.\n                feature->data_(j, i) += cspfh->data_(j, i);\n            }\n\n            if (c_sum != 0.0) c_sum = 100.0 / c_sum;\n\n            for (int j = 33; j < 41; j++) {\n                feature->data_(j, i) *= c_sum;\n                feature->data_(j, i) += cspfh->data_(j, i);\n            }\n        }\n    }\n    return feature;\n}\n/*kimeguida*/\n}  // namespace open3d\n", "meta": {"hexsha": "9d0649b36eb86b914685bd6cff9a897e79cb8ae6", "size": 15884, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "open3d_sources/src/Core/Registration/Feature.cpp", "max_stars_repo_name": "kimeguida/ProCare", "max_stars_repo_head_hexsha": "574a066a1eb787683b4e7d1042703151fa216afc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2020-07-07T01:05:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T09:31:47.000Z", "max_issues_repo_path": "open3d_sources/src/Core/Registration/Feature.cpp", "max_issues_repo_name": "dominiquesydow/ProCare", "max_issues_repo_head_hexsha": "f01487c07a5b5de9b7aca2cba7f6315fc7275bc7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-01T00:43:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T17:53:02.000Z", "max_forks_repo_path": "open3d_sources/src/Core/Registration/Feature.cpp", "max_forks_repo_name": "dominiquesydow/ProCare", "max_forks_repo_head_hexsha": "f01487c07a5b5de9b7aca2cba7f6315fc7275bc7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-07-07T02:14:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T10:09:10.000Z", "avg_line_length": 42.2446808511, "max_line_length": 80, "alphanum_fraction": 0.5165575422, "num_tokens": 4038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.2966962745201913}}
{"text": "#pragma once\n\n// deal.II includes\n#include <deal.II/base/exceptions.h>\n#include <deal.II/base/parameter_handler.h>\n#include <deal.II/dofs/dof_renumbering.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_in.h>\n#include <deal.II/grid/grid_tools.h>\n#include <deal.II/grid/tria_boundary_lib.h>\n#include <deal.II/lac/sparsity_pattern.h>\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/vector_tools.h>\n#include <yaml-cpp/yaml.h>\n#include <cctype>\n// own includes\n#include \"grid_handler_base.hpp\"\n\nnamespace boltzmann {\n// ----------------------------------------------------------------------\n\n/**\n * @brief takes into account *all* ajdacent vertices\n *        when constructing the domain decomposition with METIS\n *        for *periodic* boundary conditions.\n *\n */\ntemplate <int dim>\nclass GridHandlerPeriodic : public GridHandlerBase<dim>\n{\n private:\n  typedef GridHandlerBase<dim> base_type;\n\n public:\n  GridHandlerPeriodic();\n  void init_square(int nref, int nprocs = 1);\n  void init(dealii::ParameterHandler& param_handler, int nprocs = 1);\n  void init(YAML::Node& config, int nprocs = 1);\n\n private:\n  void make_graph();\n\n private:\n  void load_msh(std::string fname);\n  bool is_initialized;\n  dealii::SparsityPattern graph;\n  using base_type::triangulation_;\n  using base_type::dofhandler_;\n};\n\n// ----------------------------------------------------------------------\ntemplate <int dim>\nGridHandlerPeriodic<dim>::GridHandlerPeriodic()\n    : GridHandlerBase<dim>()\n    , is_initialized(false)\n{\n  static_assert(dim == 2, \"dim must be 2, 3d code is not implemented\");\n}\n\n// ----------------------------------------------------------------------\ntemplate <int dim>\nvoid\nGridHandlerPeriodic<dim>::init(dealii::ParameterHandler& param_handler, int nprocs)\n{\n  int n_refine = param_handler.get_integer(\"refine phys\");\n  std::string mesh = param_handler.get(\"mesh\");\n  if (!mesh.compare(\"\")) {\n    this->init_square(n_refine, nprocs);\n  } else {\n    throw std::runtime_error(\n        \"Grids for periodic boundary conditions should be generated and not loaded from file!\");\n    // load mesh grom file\n    this->load_msh(mesh);\n    this->dofhandler_.distribute_dofs(this->fe);\n    if (nprocs > 1) {\n      dealii::GridTools::partition_triangulation(nprocs, triangulation_);\n      dealii::DoFRenumbering::subdomain_wise(dofhandler_);\n    } else {\n      dealii::DoFRenumbering::boost::Cuthill_McKee(dofhandler_);\n    }\n    is_initialized = true;\n  }\n}\n\n// ----------------------------------------------------------------------\ntemplate <int dim>\nvoid\nGridHandlerPeriodic<dim>::init(YAML::Node& config, int nprocs)\n{\n  if (!config[\"Mesh\"][\"file\"]) {\n    int n_refine = config[\"Mesh\"][\"nref\"].as<int>();\n    this->init_square(n_refine, nprocs);\n  } else {\n    throw std::runtime_error(\n        \"Grids for periodic boundary conditions should be generated and not loaded from file!\");\n    std::string mesh = config[\"Mesh\"][\"file\"].as<std::string>();\n    // load mesh grom file\n    this->load_msh(mesh);\n    this->dofhandler_.distribute_dofs(this->fe);\n    if (nprocs > 1) {\n      dealii::GridTools::partition_triangulation(nprocs, triangulation_);\n      dealii::DoFRenumbering::boost::Cuthill_McKee(dofhandler_);\n      dealii::DoFRenumbering::subdomain_wise(dofhandler_);\n    } else {\n      dealii::DoFRenumbering::boost::Cuthill_McKee(dofhandler_);\n    }\n  }\n  is_initialized = true;\n}\n\n// ----------------------------------------------------------------------\ntemplate <int dim>\nvoid\nGridHandlerPeriodic<dim>::init_square(int nref, int nprocs)\n{\n  AssertThrow(!is_initialized, dealii::ExcMessage(\"Attempt to initialize GridHandler twice\"));\n  bool colorize = true;\n  dealii::GridGenerator::hyper_cube(triangulation_, 0, 1, colorize);\n  triangulation_.refine_global(nref);\n  dofhandler_.distribute_dofs(this->fe);\n  if (nprocs > 1) {\n    this->make_graph();\n    dealii::GridTools::partition_triangulation(nprocs, graph, triangulation_);\n    dealii::DoFRenumbering::boost::Cuthill_McKee(dofhandler_);\n    dealii::DoFRenumbering::subdomain_wise(dofhandler_);\n  } else {\n    dealii::DoFRenumbering::boost::Cuthill_McKee(dofhandler_);\n  }\n  is_initialized = true;\n}\n\n// ----------------------------------------------------------------------\ntemplate <int dim>\nvoid\nGridHandlerPeriodic<dim>::make_graph()\n{\n  typedef long int lint;\n  lint FUZZY = 1e6;\n  typedef typename dealii::Triangulation<dim>::cell_iterator cell_t;\n  //  typedef std::pair<cell_t, int> cell_face_pair_t;\n  typedef std::map<lint, int> map_t;\n  map_t hmap;\n  map_t vmap;\n  int nfaces = 4;\n  dealii::DynamicSparsityPattern csp(triangulation_.n_active_cells());\n  for (auto cell = triangulation_.begin_active(); cell != triangulation_.end(); ++cell) {\n    for (int i = 0; i < nfaces; ++i) {\n      auto neighbor = cell->neighbor(i);\n      if (neighbor != triangulation_.end()) {\n        csp.add(neighbor->index(), cell->index());\n        csp.add(cell->index(), neighbor->index());\n      }\n    }\n    if (cell->at_boundary()) {\n      // vertical faces\n      for (int f : {0, 1}) {\n        if (cell->face(f)->at_boundary()) {\n          auto center = cell->face(f)->center();\n          // find horizontal neighbor\n          auto it = vmap.find(lint(FUZZY * center[1]));\n          if (it != vmap.end()) {\n            // element found\n            int index_other = it->second;\n            csp.add(cell->index(), index_other);\n            csp.add(index_other, cell->index());\n            vmap.erase(it);\n          } else {\n            vmap.insert(it, std::make_pair(lint(center[1] * FUZZY), cell->index()));\n          }\n        }\n      }\n      // horizontal faces\n      for (int f : {2, 3}) {\n        if (cell->face(f)->at_boundary()) {\n          auto center = cell->face(f)->center();\n          // find horizontal neighbor\n          auto it = hmap.find(lint(FUZZY * center[0]));\n          if (it != hmap.end()) {\n            // element found\n            int index_other = it->second;\n            csp.add(cell->index(), index_other);\n            csp.add(index_other, cell->index());\n            hmap.erase(it);\n          } else {\n            hmap.insert(it, std::make_pair(lint(center[0] * FUZZY), cell->index()));\n          }\n        }\n      }\n    }\n  }\n  // no single boundary faces\n  AssertThrow(hmap.empty(), dealii::ExcMessage(\"unpaired horizontal face\"));\n  AssertThrow(vmap.empty(), dealii::ExcMessage(\"unpaired vertical face\"));\n  //  graph.reinit(triangulation_.n_active_cells());\n  csp.compress();\n  graph.copy_from(csp);\n}\n\n// ------------------------------------------------------------------------\ntemplate <int dim>\nvoid\nGridHandlerPeriodic<dim>::load_msh(std::string fname)\n{\n  dealii::GridIn<2> gridin;\n  gridin.attach_triangulation(triangulation_);\n  std::ifstream f(fname);\n  gridin.read_msh(f);\n  std::cout << \"Number of active cells: \" << triangulation_.n_active_cells() << std::endl;\n  std::cout << \"Total number of cells: \" << triangulation_.n_cells() << std::endl;\n}\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "826f72e96d789eca11d659e93bf9b884462d5bcf", "size": 7005, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/grid/grid_handler_periodic.hpp", "max_stars_repo_name": "simonpintarelli/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/grid/grid_handler_periodic.hpp", "max_issues_repo_name": "simonpintarelli/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/grid/grid_handler_periodic.hpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8873239437, "max_line_length": 96, "alphanum_fraction": 0.6111349036, "num_tokens": 1786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.2966962745201913}}
{"text": "#pragma once\n\n#include <cstdlib>\n#include <utility>\n#include <tuple>\n#include <numeric>\n\n#include <boost/unordered_map.hpp>\n#include \"types.hh\"\n#include \"zone.hh\"\n\n/*!\n  @brief Generate a zone automaton from a timed automaton\n  @tparam NVar the number of variable in TA\n\n  TA to ZA adds states with BFS. Initial configuration is the initial states of ZA. The ZA contain only the states reachable from initial states.\n */\ntemplate <int NVar>\nvoid ta2za (const TimedAutomaton<NVar> &TA,ZoneAutomaton &ZA, Zone initialZone = Zone::zero(NVar + 1))\n{\n  auto initialStates = TA.initialStates;\n  if (!ZA.abstractedStates.empty()) {\n    for (auto it = initialStates.begin(); it != initialStates.end();) {\n      if (std::find(ZA.abstractedStates.begin(), ZA.abstractedStates.end(),std::pair<ZAState,Zone>{TAState(*it),initialZone}) != ZA.abstractedStates.end()) {\n        it = initialStates.erase(it);\n      } else {\n        it++;\n      }\n    }\n  }\n  if (initialStates.empty()) {\n    return;    \n  }\n\n  ZA.numOfVariables = NVar;\n  //! number of states of ZA\n  const State numOfStatesInitial = ZA.abstractedStates.size();\n  State numOfStates = numOfStatesInitial;\n  if (NVar > 0) {\n    initialZone.M = Bounds{*std::max_element(TA.max_constraints.begin(), TA.max_constraints.end()), true};\n  } else {\n    initialZone.M = Bounds(0, true);\n  }\n\n  // make initial state\n  numOfStates += initialStates.size();\n  ZA.edges.resize(numOfStates);\n  const State numOfInitialStatesInitial = ZA.initialStates.size();\n  ZA.initialStates.resize (numOfStates);\n  iota (ZA.initialStates.begin() + numOfInitialStatesInitial, ZA.initialStates.end(),numOfStatesInitial);\n\n  ZA.abstractedStates.reserve (numOfStates);\n  for (const auto &conf : initialStates ) {\n    ZA.abstractedStates.push_back (std::make_pair(conf,initialZone));\n  }\n\n  /*!\n    @brief Current configuration of BFS\n    \n    A configuration consistes of a tuple ((conf,\\alpha),conf,alpha). Remark (conf,\\alpha) is not a pair but just a number representing a state of RA.\n   */\n  std::vector<std::tuple<RAState,TAState,Zone> > nextConf;\n  nextConf.resize (initialStates.size());\n  for (std::size_t i = 0; i < nextConf.size();i++) {\n    nextConf[i] = std::make_tuple(i + numOfStatesInitial, \n                                  ZA.abstractedStates[i+numOfStatesInitial].first,\n                                  ZA.abstractedStates[i+numOfStatesInitial].second);\n  }\n  \n  /*! \n    @brief translater from TAState and Region to its corresponding state in RA.\n\n    The type is like this.\n    (TAState,Zone) -> RAState\n  */\n  while (!nextConf.empty ()) {\n    std::vector<std::tuple<RAState,TAState, Zone> > currentConf = nextConf;\n    nextConf.clear();\n    for (const auto &conf : currentConf) {\n      Zone nowZone = std::get<2>(conf);\n      nowZone.elapse();\n      for (const auto &edge : TA.edges.at(std::get<1>(conf))) {\n        Zone nextZone = nowZone;\n        \n        for (const auto &delta : edge.guard) {\n          switch (delta.odr) {\n          case Constraint::Order::lt:\n            nextZone.tighten(delta.x,-1,{delta.c, false});\n            break;\n          case Constraint::Order::le:\n            nextZone.tighten(delta.x,-1,{delta.c, true});\n            break;\n          case Constraint::Order::gt:\n            nextZone.tighten(-1,delta.x,{-delta.c, false});\n            break;\n          case Constraint::Order::ge:\n            nextZone.tighten(-1,delta.x,{-delta.c, true});\n            break;\n          }\n        }\n\n        if (nextZone.isSatisfiable()) {\n          for (auto x : edge.resetVars) {\n            nextZone.reset(x);\n          }\n          nextZone.abstractize();\n          nextZone.canonize();\n          // nextRegion state is new\n          const auto targetStateInZA = ZA.zones_in_za.find(std::make_pair(edge.target, nextZone.toTuple()));\n\n          // targetRegionState is already added\n          if (targetStateInZA != ZA.zones_in_za.end()) {\n            const NFA::Edge newEdge = {std::get<0>(conf),targetStateInZA->second,edge.c};\n            ZA.edges[std::get<0>(conf)].push_back (newEdge);\n            ZoneAutomaton::TAEdge taEdge = {edge.source, edge.target, edge.c, edge.resetVars, edge.guard};\n            ZA.edgeMap[newEdge.toTuple()] = taEdge;\n            \n          } else {\n            const NFA::Edge newEdge = {std::get<0>(conf),static_cast<State>(numOfStates),edge.c};\n            ZA.edges[std::get<0>(conf)].push_back (newEdge);\n            ZoneAutomaton::TAEdge taEdge = {edge.source, edge.target, edge.c, edge.resetVars, edge.guard};\n            ZA.edgeMap[newEdge.toTuple()] = taEdge;\n            \n            if (binary_search (TA.acceptingStates.begin(), \n                               TA.acceptingStates.end (),edge.target)) {\n              ZA.acceptingStates.push_back (numOfStates);\n            }\n            ZA.zones_in_za[std::make_pair(edge.target, nextZone.toTuple())] = numOfStates;\n            ZA.abstractedStates.push_back (std::make_pair (edge.target,nextZone));\n            nextConf.push_back (std::make_tuple (numOfStates,edge.target, nextZone));\n            numOfStates++;\n            ZA.edges.resize(numOfStates);\n          }\n        }\n      }\n    }\n  }\n}\n", "meta": {"hexsha": "36b03c20b3d459364b829f3de4da5ca1e362ff74", "size": 5149, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/ta2za.hh", "max_stars_repo_name": "MasWag/timed-pattern-matching", "max_stars_repo_head_hexsha": "325d03d2447bdc3b28c391a94f920d708581ad35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ta2za.hh", "max_issues_repo_name": "MasWag/timed-pattern-matching", "max_issues_repo_head_hexsha": "325d03d2447bdc3b28c391a94f920d708581ad35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ta2za.hh", "max_forks_repo_name": "MasWag/timed-pattern-matching", "max_forks_repo_head_hexsha": "325d03d2447bdc3b28c391a94f920d708581ad35", "max_forks_repo_licenses": ["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.0431654676, "max_line_length": 157, "alphanum_fraction": 0.615653525, "num_tokens": 1300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.296651450865509}}
{"text": "#include <kazen/bsdf.h>\n#include <kazen/mesh.h>\n#include <kazen/frame.h>\n#include <kazen/warp.h>\n#include <kazen/texture.h>\n#include <kazen/mircofacet.h>\n#include <kazen/proplist.h>\n#include <Eigen/Geometry> // cross()\n#include <OpenImageIO/texture.h>\n#include <OpenImageIO/ustring.h>\n#include <filesystem/resolver.h>\n\n\nNAMESPACE_BEGIN(kazen)\n\n/**\n * \\brief Diffuse / Lambertian BRDF model\n */\nclass Diffuse : public BSDF {\npublic:\n    Diffuse(const PropertyList &propList) {\n        m_albedo = propList.getColor(\"albedo\", Color3f(0.5f));\n    }\n\n    /// Evaluate the BRDF model\n    Color3f eval(const BSDFQueryRecord &bRec) const {\n        /* This is a smooth BRDF -- return zero if the measure\n           is wrong, or when queried for illumination on the backside */\n        if (bRec.measure != ESolidAngle\n            || Frame::cosTheta(bRec.wi) <= 0\n            || Frame::cosTheta(bRec.wo) <= 0)\n            return Color3f(0.0f);\n\n        /* The BRDF is simply the albedo / pi */\n        return m_albedo * INV_PI * Frame::cosTheta(bRec.wo);\n    }\n\n    /// Compute the density of \\ref sample() wrt. solid angles\n    float pdf(const BSDFQueryRecord &bRec) const {\n        /* This is a smooth BRDF -- return zero if the measure\n           is wrong, or when queried for illumination on the backside */\n        if (bRec.measure != ESolidAngle\n            || Frame::cosTheta(bRec.wi) <= 0\n            || Frame::cosTheta(bRec.wo) <= 0)\n            return 0.0f;\n\n\n        /* Importance sampling density wrt. solid angles:\n           cos(theta) / pi.\n\n           Note that the directions in 'bRec' are in local coordinates,\n           so Frame::cosTheta() actually just returns the 'z' component.\n        */\n        return INV_PI * Frame::cosTheta(bRec.wo);\n    }\n\n    /// Draw a a sample from the BRDF model\n    Color3f sample(BSDFQueryRecord &bRec, const Point2f &sample) const {\n        if (Frame::cosTheta(bRec.wi) <= 0)\n            return Color3f(0.0f);\n\n        bRec.measure = ESolidAngle;\n\n        /* Warp a uniformly distributed sample on [0,1]^2\n           to a direction on a cosine-weighted hemisphere */\n        bRec.wo = Warp::squareToCosineHemisphere(sample);\n\n        /* Relative index of refraction: no change */\n        bRec.eta = 1.0f;\n\n        /* eval() / pdf() * cos(theta) = albedo. There\n           is no need to call these functions. */\n        return m_albedo;\n    }\n\n    bool isDiffuse() const {\n        return true;\n    }\n\n    /// Return a human-readable summary\n    std::string toString() const {\n        return fmt::format(\n            \"Diffuse[\\n\"\n            \"  albedo = {}\\n\"\n            \"]\", m_albedo.toString());\n    }\n\n    EClassType getClassType() const { return EBSDF; }\nprivate:\n    Color3f m_albedo;\n};\n\n\n/**\n * \\brief Dielectric / Ideal dielectric BSDF\n */\nclass Dielectric : public BSDF {\npublic:\n    Dielectric(const PropertyList &propList) {\n        /* Interior IOR (default: BK7 borosilicate optical glass) */\n        m_intIOR = propList.getFloat(\"intIOR\", 1.5046f);\n\n        /* Exterior IOR (default: air) */\n        m_extIOR = propList.getFloat(\"extIOR\", 1.000277f);\n    }\n\n    Color3f eval(const BSDFQueryRecord &) const {\n        /* Discrete BRDFs always evaluate to zero in kazen */\n        return Color3f(0.0f);\n    }\n\n    float pdf(const BSDFQueryRecord &) const {\n        /* Discrete BRDFs always evaluate to zero in kazen */\n        return 1.0f;\n    }\n\n    Color3f sample(BSDFQueryRecord &bRec, const Point2f &sample) const {\n        bRec.measure = EDiscrete;\n\n        auto cosThetaI = Frame::cosTheta(bRec.wi);\n        auto fresnelTerm = fresnel(cosThetaI, m_extIOR, m_intIOR);\n\n        if (sample.x() < fresnelTerm) {\n            /* Reflect wo = -wi + 2*dot(wi, n)*n. In this case is much simpler:\n            https://www.pbr-book.org/3ed-2018/Reflection_Models/Specular_Reflection_and_Transmission*/\n            bRec.wo = Vector3f(-bRec.wi.x(), -bRec.wi.y(), bRec.wi.z());\n            bRec.eta = 1.f;\n            return Color3f(1.0f);\n        } else {\n            auto n = Vector3f(0.0f, 0.0f, 1.0f);\n            auto factor = m_intIOR / m_extIOR;\n            /* inside out */\n            if (Frame::cosTheta(bRec.wi) < 0.f) {\n                factor = m_extIOR / m_intIOR;\n                n.z() = -1.0f;\n            }\n            bRec.wo = refract(-bRec.wi, n, factor);\n            bRec.eta = m_intIOR / m_extIOR;\n            return Color3f(1.0f);\n        }   \n    }\n\n    std::string toString() const {\n        return fmt::format(\n            \"Dielectric[\\n\"\n            \"  intIOR = {},\\n\"\n            \"  extIOR = {}\\n\"\n            \"]\",\n            m_intIOR, m_extIOR);\n    }\nprivate:\n    float m_intIOR, m_extIOR;\n};\n\n\n/**\n * \\brief Mirror / Ideal mirror BRDF\n */\nclass Mirror : public BSDF {\npublic:\n    Mirror(const PropertyList &) { }\n\n    Color3f eval(const BSDFQueryRecord &) const {\n        /* Discrete BRDFs always evaluate to zero in kazen */\n        return Color3f(0.0f);\n    }\n\n    float pdf(const BSDFQueryRecord &) const {\n        /* Discrete BRDFs always evaluate to zero in kazen */\n        return 1.0f;\n    }\n\n    Color3f sample(BSDFQueryRecord &bRec, const Point2f &) const {\n        if (Frame::cosTheta(bRec.wi) <= 0) \n            return Color3f(0.0f);\n\n        // Reflection in local coordinates\n        bRec.wo = Vector3f(\n            -bRec.wi.x(),\n            -bRec.wi.y(),\n             bRec.wi.z()\n        );\n        bRec.measure = EDiscrete;\n\n        /* Relative index of refraction: no change */\n        bRec.eta = 1.0f;\n\n        return Color3f(1.0f);\n    }\n\n    std::string toString() const {\n        return \"Mirror[]\";\n    }\n};\n\n\n/**\n * \\brief Diffuse / Lambertian BRDF model with texture as albedo\n */\nclass Lambertian : public BSDF {\npublic:\n    Lambertian(const PropertyList &propList) { }\n\n    ~Lambertian() {\n        if(!m_albedo) delete m_albedo;\n    }\n\n    Color3f eval(const BSDFQueryRecord &bRec) const override {\n        /* This is a smooth BRDF -- return zero if the measure\n           is wrong, or when queried for illumination on the backside */\n        if (bRec.measure != ESolidAngle\n            || Frame::cosTheta(bRec.wi) <= 0\n            || Frame::cosTheta(bRec.wo) <= 0)\n            return Color3f(0.0f);\n\n        /* The BRDF is simply the albedo / pi */\n        return m_albedo->eval(bRec.uv) * INV_PI * Frame::cosTheta(bRec.wo);\n    }\n\n    float pdf(const BSDFQueryRecord &bRec) const override {\n        /* This is a smooth BRDF -- return zero if the measure\n           is wrong, or when queried for illumination on the backside */\n        if (bRec.measure != ESolidAngle\n            || Frame::cosTheta(bRec.wi) <= 0\n            || Frame::cosTheta(bRec.wo) <= 0)\n            return 0.0f;\n\n\n        /* Importance sampling density wrt. solid angles:\n           cos(theta) / pi.\n\n           Note that the directions in 'bRec' are in local coordinates,\n           so Frame::cosTheta() actually just returns the 'z' component.\n        */\n        return INV_PI * Frame::cosTheta(bRec.wo);       \n    }\n\n    Color3f sample(BSDFQueryRecord &bRec, const Point2f &sample) const override {\n        if (Frame::cosTheta(bRec.wi) <= 0)\n            return Color3f(0.0f);\n\n        bRec.measure = ESolidAngle;\n\n        /* Warp a uniformly distributed sample on [0,1]^2\n           to a direction on a cosine-weighted hemisphere */\n        bRec.wo = Warp::squareToCosineHemisphere(sample);\n\n        /* Relative index of refraction: no change */\n        bRec.eta = 1.0f;\n\n        /* eval() / pdf() * cos(theta) = albedo. There\n           is no need to call these functions. */\n        return m_albedo->eval(bRec.uv);\n    }\n\n    void addChild(Object *obj) override {\n        switch (obj->getClassType()) {\n            case ETexture:\n                m_albedo = static_cast<Texture<Color3f>*>(obj);\n                break;\n            default:\n                throw Exception(\"addChild is not supported other than albedi maps\");\n        }\n    }\n\n    EClassType getClassType() const { return EBSDF; }\n\n    std::string toString() const {\n        return fmt::format(\"Lambertian[]\");\n    }    \n\nprivate:\n    Texture<Color3f>* m_albedo=nullptr;\n};\n\n\n\n/// normal map (normal switch)\nclass NormalMap : public BSDF {\npublic:\n    NormalMap(const PropertyList &propList) { }\n\n    ~NormalMap() {\n        if(!m_normalMap) delete m_normalMap;\n        if(!m_nested) delete m_nested;\n    }\n\n    Color3f eval(const BSDFQueryRecord &bRec) const override {\n        const Intersection &its = bRec.its;\n        Color3f rgb = m_normalMap->eval(its.uv);\n        Vector3f n(2*rgb.r()-1, 2*rgb.g()-1, 2*rgb.b()-1);\n\n\t\tif (Frame::cosTheta(bRec.wi) > 0 && Frame::cosTheta(bRec.wo) > 0 && n.dot(bRec.wi) <= 0)\n            return m_nested->eval(bRec);\n\n        Intersection perturbed(its);\n        perturbed.shFrame = getFrame(its, n.normalized(), bRec.wi);\n        \n        BSDFQueryRecord perturbedQuery(\n            perturbed.toLocal(its.toWorld(bRec.wi)),\n            perturbed.toLocal(its.toWorld(bRec.wo)), bRec.measure);\n        \n\t\tif (Frame::cosTheta(bRec.wo) * Frame::cosTheta(perturbedQuery.wo) <= 0)\n\t\t\treturn Color3f(0.0f);\n\n        perturbedQuery.uv = bRec.uv;\n        perturbedQuery.measure = bRec.measure;\n        perturbedQuery.eta = bRec.eta;\n        return m_nested->eval(perturbedQuery);\n    }\n\n    float pdf(const BSDFQueryRecord &bRec) const override {\n        const Intersection &its = bRec.its;\n        Color3f rgb = m_normalMap->eval(its.uv);\n        Vector3f n(2*rgb.r()-1, 2*rgb.g()-1, 2*rgb.b()-1);\n\n\t\tif (Frame::cosTheta(bRec.wi) > 0 && Frame::cosTheta(bRec.wo) > 0 && n.dot(bRec.wi) <= 0)\n            return m_nested->pdf(bRec); \n\n        Intersection perturbed(its);\n        perturbed.shFrame = getFrame(its, n.normalized(), bRec.wi);\n        \n        BSDFQueryRecord perturbedQuery(\n            perturbed.toLocal(its.toWorld(bRec.wi)),\n            perturbed.toLocal(its.toWorld(bRec.wo)), bRec.measure);\n        \n\t\tif (Frame::cosTheta(bRec.wo) * Frame::cosTheta(perturbedQuery.wo) <= 0)\n\t\t\treturn 0.0f;\n        \n        perturbedQuery.uv = bRec.uv;\n        perturbedQuery.measure = bRec.measure;\n        perturbedQuery.eta = bRec.eta;\n        return m_nested->pdf(perturbedQuery);        \n    }\n\n    Color3f sample(BSDFQueryRecord &bRec, const Point2f &sample) const override {\n        const Intersection &its = bRec.its;\n        Color3f rgb = m_normalMap->eval(its.uv);\n        Vector3f n(2*rgb.r()-1, 2*rgb.g()-1, 2*rgb.b()-1);\n    \n\t\tif (Frame::cosTheta(bRec.wi) > 0 && n.dot(bRec.wi) <= 0) {\n\t\t\tbRec.eta = 1.0f;\n\t\t\treturn m_nested->sample(bRec, sample);\n\t\t}\n\n\t\tIntersection perturbed(its);\n\t\tperturbed.shFrame = getFrame(its, n.normalized(), bRec.wi);\n        \n        BSDFQueryRecord perturbedQuery(perturbed.toLocal(its.toWorld(bRec.wi)));\n        perturbedQuery.uv = its.uv;\n        perturbedQuery.measure = bRec.measure;\n        perturbedQuery.eta = bRec.eta;\n        Color3f result = m_nested->sample(perturbedQuery, sample);\n        if (!result.isZero()) {\n            bRec.wo = its.toLocal(perturbed.toWorld(perturbedQuery.wo));\n\t\t\tbRec.eta = perturbedQuery.eta;\n\t\t\tif (Frame::cosTheta(bRec.wo) * Frame::cosTheta(perturbedQuery.wo) <= 0)\n\t\t\t\treturn Color3f(0.0f);\n        }\n        return result;\n    }\n\n    // https://arxiv.org/abs/1705.01263\n    Frame getFrame(const Intersection &its, Vector3f n, Vector3f wi) const {\n\n        // 1. Naive implementation\n        Frame result;\n        result.n = its.shFrame.toWorld(n).normalized();\n        result.s = (its.dpdu - result.n * result.n.dot(its.dpdu)).normalized();\n        result.t = result.n.cross(result.s).normalized();       \n\n        return result;\n\n        // 2. Normalmap switch (Iray way)\n        // Frame result;\n\t\t// Vector3f r = 2.0f * n.dot(wi) * n - wi;\n\t\t// if (Frame::cosTheta(r) <= 0) {\n\t\t// \t// pull up normal (see p. 46 https://arxiv.org/abs/1705.01263)\n\t\t// \tr = (r - r.dot(wi) * 1.01f * wi).normalized();\n\t\t// \tn = (wi + r).normalized();\n\t\t// }\n\n\t\t// Frame frame = its.shFrame;\n\t\t// result.n = frame.toWorld(n).normalized();\n\t\t// result.s = (its.dpdu - result.n * result.n.dot(its.dpdu)).normalized();\n\t\t// result.t = result.n.cross(result.s).normalized();\n\n\t\t// return result;\n    }\n\n    void addChild(Object *obj) override {\n        switch (obj->getClassType()) {\n            case ETexture:\n                m_normalMap = static_cast<Texture<Color3f>*>(obj);\n                break;\n            case EBSDF:\n                m_nested = static_cast<BSDF*>(obj);\n                break;\n            default:\n                throw Exception(\"addChild is not supported other than normal maps and nested BSDF\");\n        }\n    }\n\n    EClassType getClassType() const { return EBSDF; }\n\n    std::string toString() const {\n        return fmt::format(\"NormalMap[]\");\n    }    \n\nprivate:\n    Texture<Color3f>* m_normalMap=nullptr;\n    BSDF* m_nested = nullptr;\n};\n\n\n// // Eric Heitz's 2017 - Microfacet-based Normal Mapping for Robust Monte Carlo Path Tracing\n// class NormalMapMicrofacet : public BSDF {\n// public:\n//     NormalMapMicrofacet(const PropertyList &propList) {\n//         m_albedo = propList.getColor(\"albedo\", Color3f(0.5f));\n\n//     }\n\n//     ~NormalMapMicrofacet() {\n//         if(!m_normalMap) delete m_normalMap;\n//         if(!m_nested) delete m_nested;\n//     }\n\n//     static float pdot(Vector3f a, Vector3f b) {\n//         return std::max(0.f, a.dot(b));\n//     }\n\n//     static Vector3f wt(Vector3f wp) {\n//         return Vector3f(-wp.x(), -wp.y(), 0.f).normalized();\n//     }\n\n//     static float G1(Vector3f wp, Vector3f w) {\n//         return std::min(1.f, std::max(0.f, Frame::cosTheta(w)) * std::max(0.f, Frame::cosTheta(wp))\n//             / (pdot(w, wp) + pdot(w, wt(wp)) * Frame::sinTheta(wp))\n//         );\n//     }\n\n//     static float lambda_p(Vector3f wp, Vector3f wi) {\n//         float i_dot_p = pdot(wp, wi);\n//         return i_dot_p / (i_dot_p + pdot(wt(wp), wi) * Frame::sinTheta(wp));\n//     }\n\n// \tColor3f eval(const BSDFQueryRecord &bRec) const {\n// \t\tif (Frame::cosTheta(bRec.wi) <= 0 || Frame::cosTheta(bRec.wo) <= 0)\n// \t\t\treturn Color3f(0.0f);\n\n// \t\tVector3f wp;\n//         Color3f rgb = m_normalMap->eval(bRec.its.uv);\n//         wp = Vector3f(2*rgb.r()-1, 2*rgb.g()-1, 2*rgb.b()-1).normalized();\n\n// \t\tif (Frame::cosTheta(wp) <= 0 || (std::abs(wp.x()) < 1e-6 && std::abs(wp.y()) < 1e-6))\n// \t\t\treturn m_nested->eval(bRec);\n\n// \t\tFrame frame_wp(bRec.its.toWorld(wp));\n// \t\tIntersection perturbed_wp(bRec.its);\n// \t\tperturbed_wp.geoFrame = frame_wp;\n// \t\tperturbed_wp.shFrame = frame_wp;\n// \t\tperturbed_wp.wi = perturbed_wp.toLocal(bRec.its.toWorld(bRec.wi));\n\n// \t\tVector3f wo_wp = perturbed_wp.toLocal(bRec.its.toWorld(bRec.wo));\n// \t\tVector3f wt_ = bRec.its.toWorld(wt(wp));\n// \t\tVector3f wo = bRec.its.toWorld(bRec.wo);\n// \t\tVector3f wi = bRec.its.toWorld(bRec.wi);\n// \t\tVector3f wo_reflected = (wo - 2.0f * wo.dot(wt_) * wt_).normalized();\n// \t\tfloat notShadowedWpMirror = 1.f - G1(wp, bRec.its.toLocal(wo_reflected));\n// \t\two_reflected = perturbed_wp.toLocal(wo_reflected);\n// \t\tfloat shadowing = G1(wp, bRec.wo);\n\n// \t\tColor3f value(0.f);\n\n// \t\tfloat lambda_p_ = lambda_p(wp, bRec.wi);\n\n// \t\t// i -> p -> o\n// \t\tBSDFQueryRecord evalSingleP(perturbed_wp, perturbed_wp.wi, wo_wp);\n// \t\tvalue += m_nested->eval(evalSingleP) * (lambda_p_ * shadowing);\n\n// \t\t// i -> p -> t -> o\n// \t\tif (wo.dot(wt_) > 0) {\n// \t\t\tBSDFQueryRecord evalDoubleP(perturbed_wp, perturbed_wp.wi, wo_reflected);\n// \t\t\tvalue += m_nested->eval(evalDoubleP) * (lambda_p_ * notShadowedWpMirror * shadowing);\n// \t\t}\n\n// \t\t// i -> t -> p -> o\n// \t\tif (wi.dot(wt_) > 0) {\n// \t\t\tVector3f wi_reflected = (wi - 2.0f * wi.dot(wt_) * wt_).normalized();\n// \t\t\tBSDFQueryRecord evalDoubleT(perturbed_wp, perturbed_wp.toLocal(wi_reflected), wo_wp);\n// \t\t\tvalue += m_nested->eval(evalDoubleT) * ((1.f - lambda_p_) * shadowing);\n// \t\t}\n\n// \t\treturn value;\n//     }\n\n// \tfloat pdf(const BSDFQueryRecord &bRec) const {\n// \t\tif (Frame::cosTheta(bRec.wi) <= 0 || Frame::cosTheta(bRec.wo) <= 0)\n// \t\t\treturn 0.0f;\n\n// \t\tVector3f wp;\n//         Color3f rgb = m_normalMap->eval(bRec.its.uv);\n//         wp = Vector3f(2*rgb.r()-1, 2*rgb.g()-1, 2*rgb.b()-1).normalized();\n\n// \t\tif (Frame::cosTheta(wp) <= 0 || (std::abs(wp.x()) < 1e-6 && std::abs(wp.y()) < 1e-6)) {\n// \t\t\treturn m_nested->pdf(bRec);\n// \t\t}\n\n// \t\tfloat probability_wp = lambda_p(wp, bRec.wi);\n// \t\tFrame frameWp(bRec.its.toWorld(wp));\n// \t\tIntersection perturbed_wp(bRec.its);\n// \t\tperturbed_wp.geoFrame = frameWp;\n// \t\tperturbed_wp.shFrame = frameWp;\n// \t\tVector3f wi = bRec.its.toWorld(bRec.wi);\n// \t\tVector3f wo = bRec.its.toWorld(bRec.wo);\n// \t\tVector3f wt_ = bRec.its.toWorld(wt(wp));\n// \t\tfloat pdf = 0.f;\n// \t\tif (probability_wp > 0.f) {\n// \t\t\tBSDFQueryRecord queryWp(perturbed_wp, perturbed_wp.toLocal(wi), perturbed_wp.toLocal(wo));\n// \t\t\tpdf += probability_wp * m_nested->pdf(queryWp) * G1(wp, bRec.wo);\n\n// \t\t\tif (wo.dot(wt_) > 1e-6) {\n// \t\t\t\tVector3f woReflected = (wo - 2.0f * wo.dot(wt_) * wt_).normalized();\n// \t\t\t\tBSDFQueryRecord queryWpt(perturbed_wp, perturbed_wp.toLocal(wi), perturbed_wp.toLocal(woReflected));\n// \t\t\t\tpdf += probability_wp * m_nested->pdf(queryWpt)\n// \t\t\t\t\t* (1.f - G1(wp, bRec.its.toLocal(woReflected)));\n// \t\t\t}\n// \t\t}\n\n// \t\tif (probability_wp < 1.f && wi.dot(wt_) > 1e-6) {\n// \t\t\tVector3f wiReflected = (wi - 2.0f * wi.dot(wt_) * wt_).normalized();\n// \t\t\tBSDFQueryRecord queryWtp(perturbed_wp, perturbed_wp.toLocal(wiReflected), perturbed_wp.toLocal(wo));\n// \t\t\tpdf += (1.f - probability_wp) * m_nested->pdf(queryWtp);\n// \t\t}\n\n// \t\treturn pdf;\n// \t}    \n\n// \tColor3f sample(BSDFQueryRecord &bRec, const Point2f &sample) const {\n// \t\tif (Frame::cosTheta(bRec.wi) <= 0)\n// \t\t\treturn Color3f(0.0f);\n\n// \t\tbRec.eta = 1.0f;\n\n// \t\tVector3f wp;\n//         Color3f rgb = m_normalMap->eval(bRec.its.uv);\n//         wp = Vector3f(2*rgb.r()-1, 2*rgb.g()-1, 2*rgb.b()-1).normalized();\n\n// \t\tif (Frame::cosTheta(wp) <= 0 || (std::abs(wp.x()) < 1e-6 && std::abs(wp.y()) < 1e-6)) {\n// \t\t\treturn m_nested->sample(bRec, sample);\n// \t\t}\n\n// \t\tFrame frame_wp(bRec.its.toWorld(wp));\n// \t\tIntersection perturbed_wp(bRec.its);\n// \t\tperturbed_wp.geoFrame = frame_wp;\n// \t\tperturbed_wp.shFrame = frame_wp;\n\n// \t\tVector3f wt_ = bRec.its.toWorld(wt(wp));\n\n// \t\tVector3f wr = -bRec.its.toWorld(bRec.wi);\n// \t\tColor3f energy(1.f);\n// \t\tif (sample.x() < lambda_p(wp, bRec.wi)) {\n// \t\t\t// sample on wp\n// \t\t\tperturbed_wp.wi = -perturbed_wp.toLocal(wr);\n// \t\t\tBSDFQueryRecord query_wp(perturbed_wp, Vector3f(1.f));\n// \t\t\tenergy *= m_nested->sample(query_wp, sample);\n// \t\t\t// did sampling fail?\n// \t\t\tif (energy.isZero()) return energy;\n// \t\t\twr = perturbed_wp.toWorld(query_wp.wo);\n// \t\t\tfloat G1_ = G1(wp, bRec.its.toLocal(wr));\n\n// \t\t\t// is the sampled direction shadowed?\n// \t\t\tif (sample.x() > G1_) {\n// \t\t\t\t// reflect on wt\n// \t\t\t\twr = (wr + 2.0f * wt_.dot(-wr) * wt_).normalized();\n// \t\t\t\tenergy *= G1(wp, bRec.its.toLocal(wr));\n// \t\t\t}\n// \t\t} else {\n// \t\t\t// do one reflection if we start at wt\n// \t\t\twr = (wr + 2.0f * wt_.dot(-wr) * wt_).normalized();\n// \t\t\t// sample on wp\n// \t\t\tperturbed_wp.wi = -perturbed_wp.toLocal(wr);\n// \t\t\tBSDFQueryRecord query_wp(perturbed_wp, NULL);\n// \t\t\tenergy *= m_nested->sample(query_wp, sample);\n// \t\t\t// did sampling fail?\n// \t\t\tif (energy.isZero()) return energy;\n// \t\t\twr = perturbed_wp.toWorld(query_wp.wo);\n// \t\t\tenergy *= G1(wp, bRec.its.toLocal(wr));\n// \t\t}\n// \t\tbRec.wo = bRec.its.toLocal(wr);\n// \t\tif (Frame::cosTheta(bRec.wo) <= 0.f) return Color3f(0.f);\n// \t\treturn energy;\n// \t}\n\n//     void addChild(Object *obj) override {\n//         switch (obj->getClassType()) {\n//             case ETexture:\n//                 m_normalMap = static_cast<Texture<Color3f>*>(obj);\n//                 break;\n//             case EBSDF:\n//                 m_nested = static_cast<BSDF*>(obj);\n//                 // m_albedo = Color3f(0.f, 1.0f, 0.f); // this line is for debugging\n//                 m_albedo = m_nested->getColor();\n//                 break;\n//             default:\n//                 throw Exception(\"addChild is not supported other than normal maps and nested BSDF\");\n//         }\n//     }\n\n//     EClassType getClassType() const { return EBSDF; }\n\n//     std::string toString() const {\n//         return fmt::format(\"NormalMapMircofacet[]\");\n//     } \n\n// private:\n//     Color3f m_albedo;\n//     Texture<Color3f>* m_normalMap = nullptr;\n//     BSDF* m_nested = nullptr;\n    \n// };\n\n\nclass GGX : public BSDF {\npublic:\n    GGX(const PropertyList &propList) { \n        m_roughness = propList.getFloat(\"roughness\", 0.5f);\n        m_anisotropy = propList.getFloat(\"anisotropy\", 0.f);\n    }\n\n    ~GGX() {\n        if(!m_albedo) delete m_albedo;\n    }\n\n    Color3f eval(const BSDFQueryRecord &bRec) const {\n        if (Frame::cosTheta(bRec.wi) <= 0 || Frame::cosTheta(bRec.wo) <= 0)\n            return Color3f(0.0f);        \n        Color3f F;\n        Color3f albedo = m_albedo->eval(bRec.uv);\n        return evaluateGGXSmithBRDF(bRec.wi, bRec.wo, albedo, m_roughness, m_anisotropy, F) * Frame::cosTheta(bRec.wo);\n    }\n\n    float pdf(const BSDFQueryRecord &bRec) const {\n        if (Frame::cosTheta(bRec.wi) <= 0 || Frame::cosTheta(bRec.wo) <= 0) \n            return 0.0f;\n        \n        auto H = (bRec.wi + bRec.wo).normalized();\n        auto alpha = roughnessToAlpha(m_roughness, m_anisotropy);\n        auto denom = 4.0f * bRec.wi.dot(H);\n        return computeGGXSmithPDF(bRec.wi, H, alpha) / denom;\n    }\n\n    Color3f sample(BSDFQueryRecord &bRec, const Point2f &sample) const {\n        if (Frame::cosTheta(bRec.wi) <= 0)\n            return Color3f(0.0f);\n        Color3f albedo = m_albedo->eval(bRec.uv);            \n        Color3f color = sampleGGXSmithBRDF(bRec.wi, albedo, m_roughness, m_anisotropy, sample, bRec.wo, bRec.pdf);\n        \n        if (Frame::cosTheta(bRec.wo) <= 0)\n            return Color3f(0.0f);\n\n        return color * Frame::cosTheta(bRec.wo) / bRec.pdf;\n\n    }\n\n    void addChild(Object *obj) override {\n        switch (obj->getClassType()) {\n            case ETexture:\n                m_albedo = static_cast<Texture<Color3f>*>(obj);\n                break;\n            default:\n                throw Exception(\"addChild is not supported other than albedi maps\");\n        }\n    }\n\n    std::string toString() const {\n        return \"GGX[]\";\n    }\n\nprivate:\n    Texture<Color3f>* m_albedo=nullptr;\n    float m_roughness;\n    float m_anisotropy;\n};\n\n\nclass RoughConductor : public BSDF {\npublic:\n    RoughConductor(const PropertyList &propList) {\n        /* RMS surface roughness */\n        auto roughness = propList.getFloat(\"alpha\", 0.1f);\n        // Specify a minimum alpha value, as the GGX NDF does not support a zero alpha.\n        float MIN_ALPHA = 0.001f;\n        // Square the roughness value and combine with anisotropy to produce X and Y alpha values.\n        m_alpha = std::max(MIN_ALPHA, sqr(roughness));\n        \n        /* Eta and K (default: gold) */\n        std::string material = propList.getString(\"material\",\"Au\");\n        if (material == \"Au\") {\n            m_eta = Color3f(0.1431189557f, 0.3749570432f, 1.4424785571f);\n            m_k = Color3f(3.9831604247f, 2.3857207478f, 1.6032152899f);\n        } else if (material == \"Cu\") {\n            m_eta = Color3f(0.2004376970f, 0.9240334304f, 1.1022119527f);\n            m_k = Color3f(3.9129485033f, 2.4528477015f, 2.1421879552f);\n        } else if (material == \"Cr\") {\n            m_eta = Color3f(4.3696828663f, 2.9167024892f, 1.6547005413f);\n            m_k = Color3f(5.2064337956f, 4.2313645277f, 3.7549467933f);\n        }\n    }\n\n    /// Evaluate the fresnel for conductor\n    Color3f fresnelCond(float cosThetaI, Color3f eta, Color3f k) const {\n        Color3f tmp_f = pow(eta,2) + pow(k,2);\n        Color3f tmp = tmp_f * pow(cosThetaI,2);\n        Color3f Rparl2 = (tmp - (2.f * eta * cosThetaI) + 1) /\n                    (tmp + (2.f * eta * cosThetaI) + 1);\n        Color3f Rperp2 = (tmp_f - (2.f * eta * cosThetaI) + pow(cosThetaI,2)) /\n                    (tmp_f + (2.f * eta * cosThetaI) + pow(cosThetaI,2));\n        return (Rparl2 + Rperp2) / 2.0f;\n    }\n\n    /// Evaluate the microfacet normal distribution D\n    float evalBeckmann(const Normal3f &m) const {\n        float temp = Frame::tanTheta(m) / m_alpha,\n              ct = Frame::cosTheta(m), ct2 = ct*ct;\n\n        return std::exp(-temp*temp) \n            / (M_PI * m_alpha * m_alpha * ct2 * ct2);\n    }\n\n    /// Evaluate Smith's shadowing-masking function G1 \n    float smithBeckmannG1(const Vector3f &v, const Normal3f &m) const {\n        float tanTheta = Frame::tanTheta(v);\n\n        /* Perpendicular incidence -- no shadowing/masking */\n        if (tanTheta == 0.0f)\n            return 1.0f;\n\n        /* Can't see the back side from the front and vice versa */\n        if (m.dot(v) * Frame::cosTheta(v) <= 0)\n            return 0.0f;\n\n        float a = 1.0f / (m_alpha * tanTheta);\n        if (a >= 1.6f)\n            return 1.0f;\n        float a2 = a * a;\n\n        /* Use a fast and accurate (<0.35% rel. error) rational\n           approximation to the shadowing-masking function */\n        return (3.535f * a + 2.181f * a2) \n             / (1.0f + 2.276f * a + 2.577f * a2);\n    }\n\n    /// Evaluate the BRDF for the given pair of directions\n    virtual Color3f eval(const BSDFQueryRecord &bRec) const override {\n        if (Frame::cosTheta(bRec.wi) <= 0 || Frame::cosTheta(bRec.wo) <= 0)\n            return Color3f(0.0f);          \n        Vector3f wh = (bRec.wi + bRec.wo).normalized();\n        \n        Color3f F = fresnelCond(wh.dot(bRec.wo), m_eta, m_k);\n        float D = evalBeckmann(wh);\n        float G = smithBeckmannG1(bRec.wi, wh) * smithBeckmannG1(bRec.wo,wh);\n        \n        return D * F * G / (4.f * Frame::cosTheta(bRec.wi));\n    }\n\n    /// Evaluate the sampling density of \\ref sample() wrt. solid angles\n    virtual float pdf(const BSDFQueryRecord &bRec) const override {\n        if (Frame::cosTheta(bRec.wi) <= 0 || Frame::cosTheta(bRec.wo) <= 0) \n            return 0.0f;      \n        Vector3f wh = (bRec.wi + bRec.wo).normalized();\n        float D = evalBeckmann(wh);\n        float Jh = 1.f / (4.f * wh.dot(bRec.wo));\n        return D * Frame::cosTheta(wh) * Jh;\n    }\n\n    /// Sample the BRDF\n    virtual Color3f sample(BSDFQueryRecord &bRec, const Point2f &_sample) const override {\n        if (Frame::cosTheta(bRec.wi) <= 0)\n            return Color3f(0.0f);\n        \n        Point2f sample = _sample;\n        Vector3f wh = Warp::squareToBeckmann(sample, m_alpha);\n        bRec.wo = reflect(bRec.wi, wh).normalized();\n        if (Frame::cosTheta(bRec.wo) <= 0)\n            return Color3f(0.0f);\n\n        return eval(bRec) / pdf(bRec);\n    }\n\n    virtual std::string toString() const override {\n        return fmt::format(\n            \"RoughConductor[\\n\"\n            \"  alpha = %f,\\n\"\n            \"  intIOR = %f,\\n\"\n            \"  extIOR = %f,\\n\"\n            \"]\",\n            m_alpha,\n            m_eta,\n            m_k\n        );\n    }\nprivate:\n    float m_alpha;\n    Color3f m_eta, m_k;\n};\n\n\nclass RoughPlastic : public BSDF {\npublic:\n    RoughPlastic(const PropertyList &propList) {\n        /* RMS surface roughness */\n        auto roughness = propList.getFloat(\"alpha\", 0.1f);\n        // Specify a minimum alpha value, as the GGX NDF does not support a zero alpha.\n        float MIN_ALPHA = 0.001f;\n        // Square the roughness value and combine with anisotropy to produce X and Y alpha values.\n        m_alpha = std::max(MIN_ALPHA, sqr(roughness));\n\n        /* Interior IOR (default: BK7 borosilicate optical glass) */\n        m_intIOR = propList.getFloat(\"intIOR\", 1.5046f);\n\n        /* Exterior IOR (default: air) */\n        m_extIOR = propList.getFloat(\"extIOR\", 1.000277f);\n\n        /* Albedo of the diffuse base material (a.k.a \"kd\") */\n        m_kd = propList.getColor(\"kd\", Color3f(0.5f));\n\n        /* To ensure energy conservation, we must scale the \n           specular component by 1-kd. \n           While that is not a particularly realistic model of what \n           happens in reality, this will greatly simplify the \n           implementation. Please see the course staff if you're \n           interested in implementing a more realistic version \n           of this BRDF. */\n        m_ks = 1 - m_kd.maxCoeff();\n    }\n\n    /// Evaluate the microfacet normal distribution D\n    float evalBeckmann(const Normal3f &m) const {\n        float temp = Frame::tanTheta(m) / m_alpha,\n              ct = Frame::cosTheta(m), ct2 = ct*ct;\n\n        return std::exp(-temp*temp) \n            / (M_PI * m_alpha * m_alpha * ct2 * ct2);\n    }\n\n    /// Evaluate Smith's shadowing-masking function G1 \n    float smithBeckmannG1(const Vector3f &v, const Normal3f &m) const {\n        float tanTheta = Frame::tanTheta(v);\n\n        /* Perpendicular inci\t\treturn 0.0f;\n         * dence -- no shadowing/masking */\n        if (tanTheta == 0.0f)\n            return 1.0f;\n\n        /* Can't see the back side from the front and vice versa */\n        if (m.dot(v) * Frame::cosTheta(v) <= 0)\n            return 0.0f;\n\n        float a = 1.0f / (m_alpha * tanTheta);\n        if (a >= 1.6f)\n            return 1.0f;\n        float a2 = a * a;\n\n        /* Use a fast and accurate (<0.35% rel. error) rational\n           approximation to the shadowing-masking function */\n        return (3.535f * a + 2.181f * a2) \n             / (1.0f + 2.276f * a + 2.577f * a2);\n    }\n\n    /// Evaluate the BRDF for the given pair of directions\n    virtual Color3f eval(const BSDFQueryRecord &bRec) const override {\n        if (Frame::cosTheta(bRec.wi) <= 0 || Frame::cosTheta(bRec.wo) <= 0)\n            return Color3f(0.0f); \t\t\n        \n        Vector3f wh = (bRec.wi + bRec.wo).normalized();\n\t\tfloat D = evalBeckmann(wh);\n\t\tfloat F = fresnel((wh.dot(bRec.wo)), m_extIOR, m_intIOR);\n\t\tfloat G = (smithBeckmannG1(bRec.wo, wh) * smithBeckmannG1(bRec.wi, wh));\n\n\t\treturn m_kd * INV_PI * Frame::cosTheta(bRec.wo) + m_ks * (D * F * G) \n\t\t\t/ (4.f * Frame::cosTheta(bRec.wi));\n\n    }\n\n    /// Evaluate the sampling density of \\ref sample() wrt. solid angles\n    virtual float pdf(const BSDFQueryRecord &bRec) const override {\n\t    if (Frame::cosTheta(bRec.wi) <= 0 || Frame::cosTheta(bRec.wo) <= 0)\n            return 0.0f; \n\n        Vector3f wh = (bRec.wi + bRec.wo).normalized();\n\t\tfloat D = evalBeckmann(wh);\n\t\tfloat Jh = 1.f / (4.f * abs(wh.dot(bRec.wo)));\n\n\t\treturn m_ks * D * Frame::cosTheta(wh) * Jh + (1- m_ks) * Frame::cosTheta(bRec.wo) * INV_PI;\n\t\t// return m_ks * Warp::squareToBeckmannPdf(wh, m_alpha) * Jh + (1 - m_ks) * Warp::squareToCosineHemispherePdf(bRec.wo);\n\t}\n\n    /// Sample the BRDF\n    virtual Color3f sample(BSDFQueryRecord &bRec, const Point2f &_sample) const override {\n\t\tif (Frame::cosTheta(bRec.wi) <= 0)\n\t\t\treturn Color3f(0.0f);\n\n\t\tif (_sample.x() < m_ks) {\n\t\t\tPoint2f sample(_sample.x() / m_ks, _sample.y());\n\t\t\tVector3f wh = Warp::squareToBeckmann(sample, m_alpha);\n\t\t\tbRec.wo = ((2.f * wh.dot(bRec.wi) * wh) - bRec.wi).normalized();\n\t\t} else {\n\t\t\tPoint2f sample((_sample.x() - m_ks) / (1 - m_ks), _sample.y());\n\t\t\tbRec.wo = Warp::squareToCosineHemisphere(sample);\n\t\t}\n\n\t\tif (Frame::cosTheta(bRec.wo) <= 0)\n\t\t\treturn Color3f(0.0f);\n\n\t\t// return eval(bRec) / pdf(bRec) * Frame::cosTheta(bRec.wo);\n\t\treturn eval(bRec) / pdf(bRec);\n\t}\n\n    virtual std::string toString() const override {\n        return fmt::format(\n            \"RoughPlastic[\\n\"\n            \"  alpha = %f,\\n\"\n            \"  intIOR = %f,\\n\"\n            \"  extIOR = %f,\\n\"\n            \"  kd = %s,\\n\"\n            \"  ks = %f\\n\"\n            \"]\",\n            m_alpha,\n            m_intIOR,\n            m_extIOR,\n            m_kd.toString(),\n            m_ks\n        );\n    }\nprivate:\n    float m_alpha;\n    float m_intIOR, m_extIOR;\n    float m_ks;\n    Color3f m_kd;\n};\n\n/// TODO: Rough Dielectric\n\n\n/// kazen innercircle standard surface (kiss)\n/* References:\n* [1] [Physically Based Shading at Disney] https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf\n* [2] [Extending the Disney BRDF to a BSDF with Integrated Subsurface Scattering] https://blog.selfshadow.com/publications/s2015-shading-course/burley/s2015_pbs_disney_bsdf_notes.pdf\n* [3] [Simon Kallweit's project report] http://simon-kallweit.me/rendercompo2015/report/\n* [4] [Microfacet Models for Refraction through Rough Surfaces] https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf\n* [5] [Understanding the Masking-Shadowing Function in Microfacet-Based BRDFs] https://jcgt.org/published/0003/02/03/paper.pdf\n* [6] [Sampling the GGX Distribution of Visible Normals] https://jcgt.org/published/0007/04/01/paper.pdf\n*/\nclass KazenStandardSurface : public BSDF {\npublic:\n    KazenStandardSurface(const PropertyList &proplist) {\n        m_anisotropy = proplist.getFloat(\"anisotropy\", 0.0f);\n        m_specular = proplist.getFloat(\"specular\", 0.5f);\n        m_specularTint = proplist.getFloat(\"specularTint\", 0.5f); \n        m_clearcoat = proplist.getFloat(\"clearcoat\", 0.0f);\n        m_clearcoatRoughness = proplist.getFloat(\"clearcoatRoughness\", 0.5f);               \n        m_sheen = proplist.getFloat(\"sheen\", 0.0f);\n        m_sheenTint = proplist.getFloat(\"sheenTint\", 0.5);\n    }\n\n    ~KazenStandardSurface() {\n        if(!m_baseColor) delete m_baseColor;\n        if(!m_metallic) delete m_metallic;\n        if(!m_roughness) delete m_roughness;\n    }\n\n    float schlickWeight(float x) const {\n        x = math::clamp(1.f - x, 0.f, 1.f);\n        auto x2 = x * x;\n        return x2 * x2 * x;\n    }\n\n    Color3f lerp(const Color3f& c1, const Color3f& c2, float t) const {\n        return (1.f - t) * c1 + t * c2;\n    }\n\n    float ior(float specular) const {\n        return 2.f/(1.f - std::sqrt(0.08*specular)) - 1.f;\n    };\n\n    Color3f eval(const BSDFQueryRecord &bRec) const {\n        /* This is a smooth BRDF -- return zero if the measure\n           is wrong, or when queried for illumination on the backside */\n        if (Frame::cosTheta(bRec.wi) <= 0 || Frame::cosTheta(bRec.wo) <= 0)\n            return Color3f(0.0f);\n\n        Vector3f V = bRec.wi;\n        Vector3f L = bRec.wo;\n        Vector3f H = (V + L).normalized();\n\n        // color \n        Color3f Cdlin = m_baseColor->eval(bRec.uv);\n        auto metallic = m_metallic->eval(bRec.uv).r(); // TODO: single channel?\n        auto roughness = m_roughness->eval(bRec.uv).r();\n        float Cdlum = Cdlin.getLuminance();\n        Color3f Ctint = Cdlum > 0.f ? Cdlin/Cdlum : Color3f(1.f);\n\t\tColor3f Ctintmix = 0.08f * m_specular * lerp(Color3f(1.f), Ctint, m_specularTint);\n\t\tColor3f Cspec0 = lerp(Ctintmix, Cdlin, metallic);\n\n        // diffuse\n        float FL = schlickWeight(L.z());\n        float FV = schlickWeight(V.z());\n        float FH = schlickWeight(L.dot(H));\n\n        float cosThetaD = V.dot(H);\n        float FD90 = 0.5f * 2 * roughness * cosThetaD * cosThetaD;\n\n        float Lambert = (1.f - 0.5f*FL) * (1.f - 0.5f*FV);\n        float RR = 2.f * roughness * cosThetaD * cosThetaD;\n        float retro_reflection = RR * (FL + FV + FL * FV * (RR - 1.f));\n\n        // sheen\n        Color3f Csheen = lerp(Color3f(1.f), Ctint, m_sheenTint);\n        Color3f Fsheen = FH * m_sheen * Csheen;\n\n        // specular\n        Color3f F;\n        Color3f specTerm = evaluateGGXSmithBRDF(V, L, Cspec0, roughness, m_anisotropy, F);         \n\n        // clearcoat(ior = 1.5 -> F0 = 0.04)\n        float clearcoatRoughness = math::lerp(m_clearcoatRoughness, .01f, .3f);\n        Color3f clearcoatTerm = 0.25f * m_clearcoat * evaluateGGXSmithBRDF(V, L, 0.04f, clearcoatRoughness, m_anisotropy, F);       \n\n        return ((1.f-metallic)*(Cdlin * INV_PI * (Lambert + retro_reflection) +  Fsheen) +\n                (specTerm + clearcoatTerm))* Frame::cosTheta(bRec.wo);\n\n    }\n\n    float pdf(const BSDFQueryRecord &bRec) const override {\n        /* This is a smooth BRDF -- return zero if the measure\n           is wrong, or when queried for illumination on the backside */\n        if (Frame::cosTheta(bRec.wi) <= 0 || Frame::cosTheta(bRec.wo) <= 0)\n            return 0.0f;\n\n        // weight: reference - http://simon-kallweit.me/rendercompo2015/report/\n        auto metallic = m_metallic->eval(bRec.uv).r();\n        float diffuse = (1.f - metallic) * 0.5f;\n        // float diffuse =  m_baseColor->eval(bRec.uv).maxCoeff();\n        float GTR2 = 1.f / (1.f + m_clearcoat);\n\n        auto H = (bRec.wi + bRec.wo).normalized();\n        auto jacobian = 4.0f * bRec.wi.dot(H);\n        \n        // specular \n        auto roughness = m_roughness->eval(bRec.uv).r();\n        auto alpha = roughnessToAlpha(roughness, m_anisotropy);\n        auto specPdf = computeGGXSmithPDF(bRec.wi, H, alpha) / jacobian;\n\n        // clearcoat\n        auto coatalpha = roughnessToAlpha(math::lerp(m_clearcoatRoughness, .01f, .3f), 0.f);\n        float clearcoatPdf = computeGGXSmithPDF(bRec.wi, H, coatalpha) / jacobian;\n\n        return diffuse * INV_PI * Frame::cosTheta(bRec.wo) +\n                (1.f-diffuse) * (GTR2*specPdf + (1.f-GTR2)*clearcoatPdf);  \n    }\n\n    Color3f sample(BSDFQueryRecord &bRec, const Point2f &_sample) const override {\n        if (Frame::cosTheta(bRec.wi) <= 0)\n            return Color3f(0.0f);\n\n        bRec.measure = ESolidAngle;\n        /* Relative index of refraction: no change */\n        bRec.eta = 1.0f;\n\n        auto metallic = m_metallic->eval(bRec.uv).r();\n        float diffuse = (1.f - metallic) * 0.5f;\n        // float diffuse = m_baseColor->eval(bRec.uv).maxCoeff();\n\n\t\tif (_sample.x() < diffuse) {\n            auto sample = Point2f(_sample.x()/diffuse, _sample.y());\n            bRec.wo = Warp::squareToCosineHemisphere(sample);\n\t\t} else {\n\t\t\tauto sample = Point2f((_sample.x()-diffuse) / (1.f-diffuse), _sample.y());\n            float GTR2 = 1.f / (1.f + m_clearcoat);\n            \n            Vector3f H;\n            Point2f sample1;\n            bool flip = bRec.wi.z() <= 0.f;\n            if (sample.x() < GTR2) {\n                sample1 = Point2f(sample.x() / GTR2, sample.y());\n                auto roughness = m_roughness->eval(bRec.uv).r();\n                Vector2f alpha = roughnessToAlpha(roughness, m_anisotropy);\n                H = sampleGGXSmithVNDF(flip ? -bRec.wi : bRec.wi, alpha, sample1);\n            } else {\n                sample1 = Point2f((sample.x()-GTR2) / (1.f-GTR2), sample.y());\n                Vector2f alpha = roughnessToAlpha(math::lerp(m_clearcoatRoughness, 0.01f, .3f), 0.f);\n                H = sampleGGXSmithVNDF(flip ? -bRec.wi : bRec.wi, alpha, sample1);\n            }\n            H = flip ? -H : H;\n            // Reflect the view direction across the microfacet normal to get the sample direction.\n            bRec.wo = reflect(bRec.wi, H).normalized();\n\t\t}\n\n        auto invalid = [&]() {\n            return std::isnan(bRec.wo.x()) || std::isnan(bRec.wo.y()) || std::isnan(bRec.wo.z());\n        };\n\n        if (Frame::cosTheta(bRec.wo) <= 0 || pdf(bRec) <= Epsilon || invalid())\n            return Color3f(0.f);\n\n\t\t// return eval(bRec) / pdf(bRec) * Frame::cosTheta(bRec.wo);\n        return eval(bRec) / pdf(bRec);\n    }\n\n    void addChild(Object *obj) override {\n        switch (obj->getClassType()) {\n            case ETexture:\n                if( obj->getId() == \"baseColor\" ) {\n                    if (m_baseColor)\n                        throw Exception(\"There is already an baseColor defined!\");\n                    m_baseColor = static_cast<Texture<Color3f> *>(obj);\n                }\n                else if ( obj->getId() == \"metallic\" ) {\n                    if (m_metallic)\n                        throw Exception(\"There is already an metallic defined!\");\n                    m_metallic = static_cast<Texture<Color3f> *>(obj);\n                }  \n                else if ( obj->getId() == \"roughness\" ) {\n                    if (m_roughness)\n                        throw Exception(\"There is already an roughness defined!\");\n                    m_roughness = static_cast<Texture<Color3f> *>(obj);\n                }       \n                break;\n            default:\n                throw Exception(\"addChild is not supported other than baseColor maps\");\n        }\n    }\n\n    std::string toString() const {\n        return fmt::format(\n            \"KazenStandardSurface\"\n        );\n    }\n\nprivate:\n    Texture<Color3f>* m_baseColor=nullptr;\n    Texture<Color3f>* m_roughness=nullptr;\n    Texture<Color3f>* m_metallic=nullptr;\n    float m_anisotropy;\n    float m_specular;\n    float m_specularTint;\n    float m_sheen;\n    float m_sheenTint;\n    float m_clearcoat;\n    float m_clearcoatRoughness;\n};\n\n\nKAZEN_REGISTER_CLASS(Diffuse, \"diffuse\");\nKAZEN_REGISTER_CLASS(Dielectric, \"dielectric\");\nKAZEN_REGISTER_CLASS(Mirror, \"mirror\");\nKAZEN_REGISTER_CLASS(Lambertian, \"lambertian\");\nKAZEN_REGISTER_CLASS(NormalMap, \"normalmap\");\n// KAZEN_REGISTER_CLASS(NormalMapMicrofacet, \"normalmap_mircofacet\");\nKAZEN_REGISTER_CLASS(GGX, \"ggx\");\nKAZEN_REGISTER_CLASS(RoughConductor, \"roughconductor\");\nKAZEN_REGISTER_CLASS(RoughPlastic, \"roughplastic\");\n// KAZEN_REGISTER_CLASS(RoughDieletric, \"roughdieletric\");\nKAZEN_REGISTER_CLASS(KazenStandardSurface, \"kazenstandard\");\nNAMESPACE_END(kazen)\n", "meta": {"hexsha": "eb2d8abd19dbc618eb654b552d81a4615d618c18", "size": 41039, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/kazen/bsdf.cpp", "max_stars_repo_name": "ZhongLingXiao/nano-kazen", "max_stars_repo_head_hexsha": "0f4311b6cfe1d964af4e49263e8cc9b089d53e2e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-17T01:57:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T01:57:59.000Z", "max_issues_repo_path": "src/kazen/bsdf.cpp", "max_issues_repo_name": "ZhongLingXiao/nano-kazen", "max_issues_repo_head_hexsha": "0f4311b6cfe1d964af4e49263e8cc9b089d53e2e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-15T06:37:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T10:44:45.000Z", "max_forks_repo_path": "src/kazen/bsdf.cpp", "max_forks_repo_name": "ZhongLingXiao/nano-kazen", "max_forks_repo_head_hexsha": "0f4311b6cfe1d964af4e49263e8cc9b089d53e2e", "max_forks_repo_licenses": ["BSD-3-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.136130137, "max_line_length": 182, "alphanum_fraction": 0.5856867857, "num_tokens": 12418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2966514508655089}}
{"text": "#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <ctime>\n#include <cstdio>\n#include <experimental/filesystem>\n\n#include <Eigen/Eigen>\n#include <opencv2/core/eigen.hpp>\n#include <opengv2/utility/utility.hpp>\n#include <opengv2/sensor/PinholeCamera.hpp>\n\n#include <opencv2/core.hpp>\n#include <opencv2/core/utility.hpp>\n#include <opencv2/imgproc.hpp>\n#include <opencv2/calib3d.hpp>\n#include <opencv2/imgcodecs.hpp>\n#include <opencv2/videoio.hpp>\n#include <opencv2/highgui.hpp>\n\nusing namespace cv;\nusing namespace std;\nusing namespace opengv2;\nusing namespace std::experimental;\n\nstatic void help() {\n    cout << \"This is a camera calibration sample.\" << endl\n         << \"Usage: camera_calibration [configuration_file -- default ./default.xml]\" << endl\n         << \"Near the sample file you'll find the configuration file, which has detailed help of \"\n            \"how to edit it.  It may be any OpenCV supported file format XML/YAML.\" << endl;\n}\n\nclass Settings {\npublic:\n    Settings() : goodInput(false) {}\n\n    enum Pattern {\n        NOT_EXISTING, CHESSBOARD, CIRCLES_GRID, ASYMMETRIC_CIRCLES_GRID\n    };\n    enum InputType {\n        INVALID, CAMERA, VIDEO_FILE, IMAGE_LIST\n    };\n\n    void write(FileStorage &fs) const                        //Write serialization for this class\n    {\n        fs << \"{\"\n           << \"BoardSize_Width\" << boardSize.width\n           << \"BoardSize_Height\" << boardSize.height\n           << \"Square_Size\" << squareSize\n           << \"Calibrate_Pattern\" << patternToUse\n           << \"Calibrate_NrOfFrameToUse\" << nrFrames\n           << \"Calibrate_FixAspectRatio\" << aspectRatio\n           << \"Calibrate_AssumeZeroTangentialDistortion\" << calibZeroTangentDist\n           << \"Calibrate_FixPrincipalPointAtTheCenter\" << calibFixPrincipalPoint\n\n           << \"Write_DetectedFeaturePoints\" << writePoints\n           << \"Write_extrinsicParameters\" << writeExtrinsics\n           << \"Write_outputFileName\" << outputFileName\n\n           << \"Show_UndistortedImage\" << showUndistorsed\n\n           << \"Input_FlipAroundHorizontalAxis\" << flipVertical\n           << \"Input_Delay\" << delay\n           << \"Input\" << input\n           << \"}\";\n    }\n\n    void read(const FileNode &node)                          //Read serialization for this class\n    {\n        node[\"BoardSize_Width\"] >> boardSize.width;\n        node[\"BoardSize_Height\"] >> boardSize.height;\n        node[\"Calibrate_Pattern\"] >> patternToUse;\n        node[\"Square_Size\"] >> squareSize;\n        //node[\"Calibrate_NrOfFrameToUse\"] >> nrFrames;\n        node[\"Calibrate_FixAspectRatio\"] >> aspectRatio;\n        node[\"Write_DetectedFeaturePoints\"] >> writePoints;\n        node[\"Write_extrinsicParameters\"] >> writeExtrinsics;\n        //node[\"Write_outputFileName\"] >> outputFileName;\n        node[\"Calibrate_AssumeZeroTangentialDistortion\"] >> calibZeroTangentDist;\n        node[\"Calibrate_FixPrincipalPointAtTheCenter\"] >> calibFixPrincipalPoint;\n        node[\"Calibrate_UseFisheyeModel\"] >> useFisheye;\n        node[\"Input_FlipAroundHorizontalAxis\"] >> flipVertical;\n        node[\"Show_UndistortedImage\"] >> showUndistorsed;\n        node[\"Input\"] >> input;\n        node[\"Input_Delay\"] >> delay;\n        node[\"Fix_K1\"] >> fixK1;\n        node[\"Fix_K2\"] >> fixK2;\n        node[\"Fix_K3\"] >> fixK3;\n        node[\"Fix_K4\"] >> fixK4;\n        node[\"Fix_K5\"] >> fixK5;\n\n        node[\"camera_matrix\"] >> eventCameraMatrix;\n        node[\"distortion_coefficients\"] >> eventDistCoeffs;\n\n        validate();\n    }\n\n    void validate() {\n        goodInput = true;\n        if (boardSize.width <= 0 || boardSize.height <= 0) {\n            cerr << \"Invalid Board size: \" << boardSize.width << \" \" << boardSize.height << endl;\n            goodInput = false;\n        }\n        if (squareSize <= 10e-6) {\n            cerr << \"Invalid square size \" << squareSize << endl;\n            goodInput = false;\n        }\n        /*if (nrFrames <= 0) {\n            cerr << \"Invalid number of frames \" << nrFrames << endl;\n            goodInput = false;\n        }*/\n\n        if (input.empty())      // Check for valid input\n            inputType = INVALID;\n        else {\n            if (input[0] >= '0' && input[0] <= '9') {\n                stringstream ss(input);\n                ss >> cameraID;\n                inputType = CAMERA;\n            } else {\n                if (isListOfImages(input) && readStringList(input, imageList)) {\n                    inputType = IMAGE_LIST;\n                    //nrFrames = (nrFrames < (int) imageList.size()) ? nrFrames : (int) imageList.size();\n                    nrFrames = imageList.size();\n                } else\n                    inputType = VIDEO_FILE;\n            }\n            if (inputType == CAMERA)\n                inputCapture.open(cameraID);\n            if (inputType == VIDEO_FILE)\n                inputCapture.open(input);\n            if (inputType != IMAGE_LIST && !inputCapture.isOpened())\n                inputType = INVALID;\n        }\n        if (inputType == INVALID) {\n            cerr << \" Input does not exist: \" << input;\n            goodInput = false;\n        }\n\n        flag = 0;\n        if (calibFixPrincipalPoint) flag |= CALIB_FIX_PRINCIPAL_POINT;\n        if (calibZeroTangentDist) flag |= CALIB_ZERO_TANGENT_DIST;\n        if (aspectRatio) flag |= CALIB_FIX_ASPECT_RATIO;\n        if (fixK1) flag |= CALIB_FIX_K1;\n        if (fixK2) flag |= CALIB_FIX_K2;\n        if (fixK3) flag |= CALIB_FIX_K3;\n        if (fixK4) flag |= CALIB_FIX_K4;\n        if (fixK5) flag |= CALIB_FIX_K5;\n\n        if (useFisheye) {\n            // the fisheye model has its own enum, so overwrite the flags\n            flag = fisheye::CALIB_FIX_SKEW | fisheye::CALIB_RECOMPUTE_EXTRINSIC;\n            if (fixK1) flag |= fisheye::CALIB_FIX_K1;\n            if (fixK2) flag |= fisheye::CALIB_FIX_K2;\n            if (fixK3) flag |= fisheye::CALIB_FIX_K3;\n            if (fixK4) flag |= fisheye::CALIB_FIX_K4;\n            if (calibFixPrincipalPoint) flag |= fisheye::CALIB_FIX_PRINCIPAL_POINT;\n        }\n\n        calibrationPattern = NOT_EXISTING;\n        if (!patternToUse.compare(\"CHESSBOARD\")) calibrationPattern = CHESSBOARD;\n        if (!patternToUse.compare(\"CIRCLES_GRID\")) calibrationPattern = CIRCLES_GRID;\n        if (!patternToUse.compare(\"ASYMMETRIC_CIRCLES_GRID\")) calibrationPattern = ASYMMETRIC_CIRCLES_GRID;\n        if (calibrationPattern == NOT_EXISTING) {\n            cerr << \" Camera calibration mode does not exist: \" << patternToUse << endl;\n            goodInput = false;\n        }\n        atImageList = 0;\n\n    }\n\n    Mat nextImage(double &timestamp) {\n        Mat result;\n        if (inputCapture.isOpened()) {\n            Mat view0;\n            inputCapture >> view0;\n            view0.copyTo(result);\n        } else if (atImageList < imageList.size()) {\n            size_t lastIndex = imageList[atImageList].find_last_of(\".\");\n            std::size_t beginIndex = imageList[atImageList].find_last_of(\"/\");\n            string rawName = imageList[atImageList].substr(beginIndex + 1, lastIndex - beginIndex - 1);\n            long long tmp = std::stoll(rawName);\n            timestamp = ((tmp - startTime_) * 1e-6);\n            result = imread(imageList[atImageList++], IMREAD_COLOR);\n        }\n\n        return result;\n    }\n\n    static bool readStringList(const string &path, vector<string> &l) {\n        l.clear();\n        /*FileStorage fs(filename, FileStorage::READ);\n        if (!fs.isOpened())\n            return false;\n        FileNode n = fs.getFirstTopLevelNode();\n        if (n.type() != FileNode::SEQ)\n            return false;\n        FileNodeIterator it = n.begin(), it_end = n.end();\n        for (; it != it_end; ++it)\n            l.push_back((string) *it);*/\n        set<filesystem::path> sorted_by_name;\n        for (const auto &entry : filesystem::directory_iterator(path)) {\n            sorted_by_name.insert(entry.path());\n        }\n\n        std::move(sorted_by_name.begin(), sorted_by_name.end(), std::back_inserter(l));\n\n        return true;\n    }\n\n    static bool isListOfImages(const string &filename) {\n        /*string s(filename);\n        // Look for file extension\n        if (s.find(\".xml\") == string::npos && s.find(\".yaml\") == string::npos && s.find(\".yml\") == string::npos)\n            return false;\n        else\n            return true;*/\n        return true;\n    }\n\npublic:\n    Size boardSize;              // The size of the board -> Number of items by width and height\n    Pattern calibrationPattern;  // One of the Chessboard, circles, or asymmetric circle pattern\n    float squareSize;            // The size of a square in your defined unit (point, millimeter,etc).\n    int nrFrames;                // The number of frames to use from the input for calibration\n    float aspectRatio;           // The aspect ratio\n    int delay;                   // In case of a video input\n    bool writePoints;            // Write detected feature points\n    bool writeExtrinsics;        // Write extrinsic parameters\n    bool calibZeroTangentDist;   // Assume zero tangential distortion\n    bool calibFixPrincipalPoint; // Fix the principal point at the center\n    bool flipVertical;           // Flip the captured images around the horizontal axis\n    string outputFileName;       // The name of the file where to write\n    bool showUndistorsed;        // Show undistorted images after calibration\n    string input;                // The input ->\n    bool useFisheye;             // use fisheye camera model for calibration\n    bool fixK1;                  // fix K1 distortion coefficient\n    bool fixK2;                  // fix K2 distortion coefficient\n    bool fixK3;                  // fix K3 distortion coefficient\n    bool fixK4;                  // fix K4 distortion coefficient\n    bool fixK5;                  // fix K5 distortion coefficient\n\n    Mat eventCameraMatrix, eventDistCoeffs;\n\n    int cameraID;\n    vector<string> imageList;\n    size_t atImageList;\n    long long startTime_;\n    VideoCapture inputCapture;\n    InputType inputType;\n    bool goodInput;\n    int flag;\n\nprivate:\n    string patternToUse;\n\n\n};\n\nstatic inline void read(const FileNode &node, Settings &x, const Settings &default_value = Settings()) {\n    if (node.empty())\n        x = default_value;\n    else\n        x.read(node);\n}\n\nenum {\n    DETECTION = 0, CAPTURING = 1, CALIBRATED = 2\n};\n\nbool runCalibrationAndSave(Settings &s, Size imageSize, Mat &cameraMatrix, Mat &distCoeffs,\n                           vector<vector<Point2f>> imagePoints, vector<Mat> &rvecs, vector<Mat> &tvecs,\n                           const vector<double> &timestampSet);\n\nstatic void compareResult(Settings &s, Size &imageSize, Mat &cameraMatrix, Mat &distCoeffs,\n                          const vector<vector<Point2f>> &imagePoints, vector<Mat> &rvecs, vector<Mat> &tvecs,\n                          const Mat &eventCameraMatrix, const Mat &eventDistCoeffs);\n\nint main(int argc, char *argv[]) {\n    help();\n\n    if (argc != 4) {\n        cerr << endl\n             << \"Usage: ./opencv_camera_calibration settingFilePath SavePath baseTime\"\n             << endl;\n        return 1;\n    }\n\n    //! [file_read]\n    Settings s;\n    const string inputSettingsFile = argv[1];\n    FileStorage fs(inputSettingsFile, FileStorage::READ); // Read the settings\n    if (!fs.isOpened()) {\n        cout << \"Could not open the configuration file: \\\"\" << inputSettingsFile << \"\\\"\" << endl;\n        return -1;\n    }\n    fs[\"Settings\"] >> s;\n    fs.release();                                         // close Settings file\n    //! [file_read]\n\n    //FileStorage fout(\"settings.yml\", FileStorage::WRITE); // write config as YAML\n    //fout << \"Settings\" << s;\n\n    s.outputFileName = std::string(argv[2]);\n    s.startTime_ = std::stoll(argv[3]);\n    auto lastIndex = s.outputFileName.find_last_of('/');\n    string imageFolder = s.outputFileName.substr(0, lastIndex) + \"/cvImage/\";\n    experimental::filesystem::remove_all(imageFolder);\n    experimental::filesystem::create_directories(imageFolder);\n\n    if (!s.goodInput) {\n        cout << \"Invalid input detected. Application stopping. \" << endl;\n        return -1;\n    }\n\n    vector<vector<Point2f>> imagePoints;\n    Mat cameraMatrix, distCoeffs;\n    Size imageSize;\n    int mode = s.inputType == Settings::IMAGE_LIST ? CAPTURING : DETECTION;\n    clock_t prevTimestamp = 0;\n    const Scalar RED(0, 0, 255), GREEN(0, 255, 0);\n    const char ESC_KEY = 27;\n\n    vector<Mat> rvecs, tvecs;\n    vector<double> timestampSet;\n\n    int counter = 0;\n\n    //! [get_input]\n    for (;;) {\n        Mat view;\n        bool blinkOutput = false;\n\n        double timestamp;\n        view = s.nextImage(timestamp);\n        counter++;\n\n        //-----  If no more image, or got enough, then stop calibration and show result -------------\n        if (mode == CAPTURING && (imagePoints.size() >= (size_t) s.nrFrames || counter >= s.imageList.size())) {\n            if (runCalibrationAndSave(s, imageSize, cameraMatrix, distCoeffs, imagePoints, rvecs, tvecs, timestampSet))\n                mode = CALIBRATED;\n            else\n                mode = DETECTION;\n        }\n        if (view.empty())          // If there are no more images stop the loop\n        {\n            // if calibration threshold was not reached yet, calibrate now\n            if (mode != CALIBRATED && !imagePoints.empty())\n                runCalibrationAndSave(s, imageSize, cameraMatrix, distCoeffs, imagePoints, rvecs, tvecs, timestampSet);\n            break;\n        }\n        //! [get_input]\n\n        imageSize = view.size();  // Format input image.\n        if (s.flipVertical) flip(view, view, 0);\n\n        //! [find_pattern]\n        vector<Point2f> pointBuf;\n\n        bool found;\n\n        int chessBoardFlags = CALIB_CB_ADAPTIVE_THRESH | CALIB_CB_NORMALIZE_IMAGE;\n\n        if (!s.useFisheye) {\n            // fast check erroneously fails with high distortions like fisheye\n            chessBoardFlags |= CALIB_CB_FAST_CHECK;\n        }\n\n        switch (s.calibrationPattern) // Find feature points on the input format\n        {\n            case Settings::CHESSBOARD:\n                found = findChessboardCorners(view, s.boardSize, pointBuf, chessBoardFlags);\n                break;\n            case Settings::CIRCLES_GRID:\n                found = findCirclesGrid(view, s.boardSize, pointBuf);\n                break;\n            case Settings::ASYMMETRIC_CIRCLES_GRID:\n                found = findCirclesGrid(view, s.boardSize, pointBuf, CALIB_CB_ASYMMETRIC_GRID);\n                break;\n            default:\n                found = false;\n                break;\n        }\n        //! [find_pattern]\n        //! [pattern_found]\n        if (found)                // If done with success,\n        {\n            // improve the found corners' coordinate accuracy for chessboard\n            if (s.calibrationPattern == Settings::CHESSBOARD) {\n                Mat viewGray;\n                cvtColor(view, viewGray, COLOR_BGR2GRAY);\n                cornerSubPix(viewGray, pointBuf, Size(11, 11),\n                             Size(-1, -1), TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 30, 0.1));\n            }\n\n            if (mode == CAPTURING &&  // For camera only take new samples after delay time\n                (!s.inputCapture.isOpened() || clock() - prevTimestamp > s.delay * 1e-3 * CLOCKS_PER_SEC)) {\n                imagePoints.push_back(pointBuf);\n                timestampSet.push_back(timestamp);\n                prevTimestamp = clock();\n                blinkOutput = s.inputCapture.isOpened();\n            }\n\n            // Draw the corners.\n            drawChessboardCorners(view, s.boardSize, Mat(pointBuf), found);\n        }\n        //! [pattern_found]\n\n        // output image\n        cv::imwrite(imageFolder + std::to_string(timestamp) + \"_cv.png\", view);\n\n        //----------------------------- Output Text ------------------------------------------------\n        //! [output_text]\n        string msg = (mode == CAPTURING) ? \"100/100\" :\n                     mode == CALIBRATED ? \"Calibrated\" : \"Press 'g' to start\";\n        int baseLine = 0;\n        Size textSize = getTextSize(msg, 1, 1, 1, &baseLine);\n        Point textOrigin(view.cols - 2 * textSize.width - 10, view.rows - 2 * baseLine - 10);\n\n        if (mode == CAPTURING) {\n            if (s.showUndistorsed)\n                msg = format(\"%d/%d Undist\", (int) imagePoints.size(), s.nrFrames);\n            else\n                msg = format(\"%d/%d\", (int) imagePoints.size(), s.nrFrames);\n        }\n\n        putText(view, msg, textOrigin, 1, 1, mode == CALIBRATED ? GREEN : RED);\n\n        if (blinkOutput)\n            bitwise_not(view, view);\n        //! [output_text]\n        //------------------------- Video capture  output  undistorted ------------------------------\n        //! [output_undistorted]\n        if (mode == CALIBRATED && s.showUndistorsed) {\n            Mat temp = view.clone();\n            if (s.useFisheye)\n                cv::fisheye::undistortImage(temp, view, cameraMatrix, distCoeffs);\n            else\n                undistort(temp, view, cameraMatrix, distCoeffs);\n        }\n        //! [output_undistorted]\n        //------------------------------ Show image and check for input commands -------------------\n        //! [await_input]\n        imshow(\"Image View\", view);\n        char key = (char) waitKey(s.inputCapture.isOpened() ? 50 : s.delay);\n\n        if (key == ESC_KEY)\n            break;\n\n        if (key == 'u' && mode == CALIBRATED)\n            s.showUndistorsed = !s.showUndistorsed;\n\n        if (s.inputCapture.isOpened() && key == 'g') {\n            mode = CAPTURING;\n            imagePoints.clear();\n        }\n        //! [await_input]\n    }\n\n    // -----------------------Show the undistorted image for the image list ------------------------\n    //! [show_results]\n    if (s.inputType == Settings::IMAGE_LIST && s.showUndistorsed) {\n        /*compareResult(s, imageSize, cameraMatrix, distCoeffs, imagePoints, rvecs, tvecs, s.eventCameraMatrix,\n                      s.eventDistCoeffs);*/\n    }\n    //! [show_results]\n\n    return 0;\n}\n\n//! [compute_errors]\nstatic double computeReprojectionErrors(const vector<vector<Point3f> > &objectPoints,\n                                        const vector<vector<Point2f> > &imagePoints,\n                                        const vector<Mat> &rvecs, const vector<Mat> &tvecs,\n                                        const Mat &cameraMatrix, const Mat &distCoeffs,\n                                        vector<float> &perViewErrors, bool fisheye) {\n    vector<Point2f> imagePoints2;\n    size_t totalPoints = 0;\n    double totalErr = 0, err;\n    perViewErrors.resize(objectPoints.size());\n\n    for (size_t i = 0; i < objectPoints.size(); ++i) {\n        if (fisheye) {\n            fisheye::projectPoints(objectPoints[i], imagePoints2, rvecs[i], tvecs[i], cameraMatrix,\n                                   distCoeffs);\n        } else {\n            projectPoints(objectPoints[i], rvecs[i], tvecs[i], cameraMatrix, distCoeffs, imagePoints2);\n        }\n        err = norm(imagePoints[i], imagePoints2, NORM_L2);\n\n        size_t n = objectPoints[i].size();\n        perViewErrors[i] = (float) std::sqrt(err * err / n);\n        totalErr += err * err;\n        totalPoints += n;\n    }\n\n    return std::sqrt(totalErr / totalPoints);\n}\n\nstatic void computeBackProjectionErrors(const vector<vector<Point3f> > &objectPoints,\n                                        const vector<vector<Point2f> > &imagePoints,\n                                        const vector<Mat> &rvecs, const vector<Mat> &tvecs,\n                                        const Mat &cameraMatrix, const Mat &distCoeffs,\n                                        vector<vector<float>> &errors, bool fisheye, bool inversePoly) {\n    errors.resize(objectPoints.size());\n\n    Eigen::Matrix3f invK;\n    cv2eigen(cameraMatrix.inv(), invK);\n    Eigen::VectorXf inverseRadialPoly;\n    cv2eigen(distCoeffs, inverseRadialPoly);\n    for (size_t i = 0; i < objectPoints.size(); ++i) {\n        cv::Mat cvRsw;\n        cv::Rodrigues(rvecs[i], cvRsw);\n        Eigen::Matrix3f Rsw;\n        Eigen::Vector3f tsw;\n        cv::cv2eigen(cvRsw, Rsw);\n        cv::cv2eigen(tvecs[i], tsw);\n        Eigen::Matrix3f Rws = Rsw.transpose();\n        Eigen::Vector3f tws = -Rws * tsw;\n\n        vector<Point3f> objectPoints2;\n        objectPoints2.reserve(objectPoints[i].size());\n        if (inversePoly) {\n            for (const auto &p: imagePoints[i]) {\n                Eigen::Vector3f Xc;\n                Xc = invK * Eigen::Vector3f(p.x, p.y, 1);\n                Xc /= Xc[2];\n\n                Eigen::VectorXf r_coeff(inverseRadialPoly.size());\n                r_coeff[0] = Xc[0] * Xc[0] + Xc[1] * Xc[1];\n                for (int k = 1; k < inverseRadialPoly.size(); ++k) {\n                    r_coeff[k] = r_coeff[k - 1] * r_coeff[0];\n                }\n                Xc[0] *= 1 + r_coeff.transpose() * inverseRadialPoly;\n                Xc[1] *= 1 + r_coeff.transpose() * inverseRadialPoly;\n\n                double depth = -tws[2] / (Rws.row(2).dot(Xc));\n                Xc *= depth;\n\n                Eigen::Vector3f Xw = Rws * Xc + tws;\n                objectPoints2.emplace_back(Xw[0], Xw[1], Xw[2]);\n            }\n        } else {\n            std::vector<cv::Point2f> dst;\n            if (fisheye) {\n                fisheye::undistortPoints(imagePoints[i], dst, cameraMatrix, distCoeffs);\n            } else {\n                undistortPoints(imagePoints[i], dst, cameraMatrix, distCoeffs);\n            }\n\n            for (const auto &p: dst) {\n                Eigen::Vector3f Xc(p.x, p.y, 1);\n\n                double depth = -tws[2] / (Rws.row(2).dot(Xc));\n                Xc *= depth;\n\n                Eigen::Vector3f Xw = Rws * Xc + tws;\n                objectPoints2.emplace_back(Xw[0], Xw[1], Xw[2]);\n            }\n        }\n\n        errors[i].resize(objectPoints2.size());\n        for (int k = 0; k < objectPoints2.size(); ++k) {\n            errors[i][k] = norm(objectPoints[i][k] - objectPoints2[k]);\n        }\n    }\n}\n\n//! [compute_errors]\n//! [board_corners]\nstatic void calcBoardCornerPositions(Size boardSize, float squareSize, vector<Point3f> &corners,\n                                     Settings::Pattern patternType /*= Settings::CHESSBOARD*/) {\n    corners.clear();\n\n    switch (patternType) {\n        case Settings::CHESSBOARD:\n        case Settings::CIRCLES_GRID:\n            for (int i = 0; i < boardSize.height; ++i)\n                for (int j = 0; j < boardSize.width; ++j)\n                    corners.push_back(Point3f(j * squareSize, i * squareSize, 0));\n            break;\n\n        case Settings::ASYMMETRIC_CIRCLES_GRID:\n            for (int i = 0; i < boardSize.height; i++)\n                for (int j = 0; j < boardSize.width; j++)\n                    corners.push_back(Point3f((2 * j + i % 2) * squareSize, i * squareSize, 0));\n            break;\n        default:\n            break;\n    }\n}\n\ndouble evaluateStraightness(const vectorofEigenMatrix<Eigen::Vector3d> &centers, int height, int width,\n                            bool isAsymmetric) {\n    std::vector<std::vector<int>> lineSet;\n\n    // each row\n    for (int i = 0; i < height; ++i) {\n        lineSet.emplace_back();\n        for (int j = 0; j < width; ++j) {\n            lineSet.back().push_back(i * width + j);\n        }\n    }\n\n    if (isAsymmetric) {\n        // each col\n        for (int j = 0; j < width; ++j) {\n            lineSet.emplace_back();\n            for (int i = 0; i < height; i += 2) {\n                lineSet.back().push_back(i * width + j);\n            }\n            lineSet.emplace_back();\n            for (int i = 1; i < height; i += 2) {\n                lineSet.back().push_back(i * width + j);\n            }\n        }\n    } else {\n        // each col\n        for (int j = 0; j < width; ++j) {\n            lineSet.emplace_back();\n            for (int i = 0; i < height; i++) {\n                lineSet.back().push_back(i * width + j);\n            }\n        }\n    }\n\n    double err = 0;\n    for (const auto &pointIdSet: lineSet) {\n        Eigen::MatrixXd A(pointIdSet.size(), 3);\n        for (int i = 0; i < pointIdSet.size(); ++i) {\n            A.row(i) = centers[pointIdSet[i]].transpose();\n        }\n\n        Eigen::JacobiSVD svd(A, Eigen::ComputeThinV);\n        Eigen::Vector3d line = svd.matrixV().col(2);\n\n        double sum = 0;\n        for (const auto &pointId: pointIdSet) {\n            sum += std::abs(line.transpose() * centers[pointId]);\n        }\n        sum /= pointIdSet.size();\n\n        err += sum;\n    }\n    err /= lineSet.size();\n\n    return err;\n}\n\nstatic void compareResult(Settings &s, Size &imageSize, Mat &cameraMatrix, Mat &distCoeffs,\n                          const vector<vector<Point2f>> &imagePoints, vector<Mat> &rvecs, vector<Mat> &tvecs,\n                          const Mat &eventCameraMatrix, const Mat &eventDistCoeffs) {\n    vector<vector<Point3f>> objectPoints(1);\n    calcBoardCornerPositions(s.boardSize, s.squareSize, objectPoints[0], s.calibrationPattern);\n    objectPoints.resize(imagePoints.size(), objectPoints[0]);\n\n    std::vector<float> cvErr;\n    std::vector<float> splineErr;\n    vector<vector<float>> errors;\n    computeBackProjectionErrors(objectPoints, imagePoints, rvecs, tvecs, cameraMatrix,\n                                distCoeffs, errors, s.useFisheye, false);\n    for (auto &&v : errors) {\n        std::move(v.begin(), v.end(), std::back_inserter(cvErr));\n    }\n    computeBackProjectionErrors(objectPoints, imagePoints, rvecs, tvecs, eventCameraMatrix,\n                                eventDistCoeffs, errors, s.useFisheye, true);\n    for (auto &&v : errors) {\n        std::move(v.begin(), v.end(), std::back_inserter(splineErr));\n    }\n\n    float cvMean, cvSdtdev, splineMean, splineSdtdev;\n    fitNormal(cvErr, cvMean, cvSdtdev);\n    fitNormal(splineErr, splineMean, splineSdtdev);\n\n    std::cout << \"OpenCV back-projection error (mean, stddev): \" << cvMean << \" \" << cvSdtdev << std::endl;\n    std::cout << \"Ours back-projection error (mean, stddev): \" << splineMean << \" \" << splineSdtdev << std::endl;\n\n    /*** evaluateStraightness ***/\n    // ours\n    Eigen::VectorXd inverseRadialPoly;\n    Eigen::Matrix3d K;\n    Eigen::Vector2d cs(imageSize.width, imageSize.height);\n    cv2eigen(eventDistCoeffs, inverseRadialPoly);\n    cv2eigen(eventCameraMatrix, K);\n    auto camera = make_shared<PinholeCamera>(cs, K);\n    camera->inverseRadialPoly() = inverseRadialPoly;\n\n    // cv\n    Eigen::VectorXd distortion;\n    cv2eigen(distCoeffs, distortion);\n    cv2eigen(cameraMatrix, K);\n    auto cvCamera = make_shared<PinholeCamera>(cs, K, distortion);\n\n    // evaluateStraightness\n    std::vector<float> ourErrSet, cvErrSet;\n    for (const auto &imagePointSet: imagePoints) {\n        opengv2::vectorofEigenMatrix <Eigen::Vector3d> normalizedCenters, cv_normalizedCenters;\n        for (const auto &imagePoint: imagePointSet) {\n            Eigen::Vector2d p(imagePoint.x, imagePoint.y);\n            Eigen::Vector3d pc;\n            pc.block<2, 1>(0, 0) = camera->undistortPoint(p);\n            pc[2] = 1;\n            normalizedCenters.push_back(pc);\n\n            Eigen::Vector3d cv_pc;\n            cv_pc.block<2, 1>(0, 0) = cvCamera->undistortPoint(p);\n            cv_pc[2] = 1;\n            cv_normalizedCenters.push_back(cv_pc);\n        }\n        ourErrSet.push_back(evaluateStraightness(normalizedCenters, s.boardSize.height, s.boardSize.width,\n                                                 s.calibrationPattern == Settings::ASYMMETRIC_CIRCLES_GRID));\n        cvErrSet.push_back(evaluateStraightness(cv_normalizedCenters, s.boardSize.height, s.boardSize.width,\n                                                s.calibrationPattern == Settings::ASYMMETRIC_CIRCLES_GRID));\n    }\n    fitNormal(cvErrSet, cvMean, cvSdtdev);\n    fitNormal(ourErrSet, splineMean, splineSdtdev);\n\n    std::cout << \"OpenCV undistortion straightness error (mean, stddev): \" << cvMean << \" \" << cvSdtdev << std::endl;\n    std::cout << \"Ours undistortion straightness error (mean, stddev): \" << splineMean << \" \" << splineSdtdev\n              << std::endl;\n\n    /*** show undistorted images ***/\n    Mat view, rview, map1, map2;\n    if (s.useFisheye) {\n        Mat newCamMat;\n        fisheye::estimateNewCameraMatrixForUndistortRectify(cameraMatrix, distCoeffs, imageSize,\n                                                            Matx33d::eye(), newCamMat, 1);\n        fisheye::initUndistortRectifyMap(cameraMatrix, distCoeffs, Matx33d::eye(), newCamMat, imageSize,\n                                         CV_32FC1, map1, map2);\n    } else {\n        initUndistortRectifyMap(\n                cameraMatrix, distCoeffs, Mat(),\n                getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0), imageSize,\n                CV_32FC1, map1, map2);\n    }\n\n    cv::namedWindow(\"Debug_undistorted\");\n    cv::namedWindow(\"Debug_undistorted_cv\");\n    for (size_t i = 0; i < s.imageList.size(); i++) {\n        view = imread(s.imageList[i], IMREAD_COLOR);\n        if (view.empty())\n            continue;\n        remap(view, rview, map1, map2, INTER_LINEAR);\n        cv::Mat ourView = camera->undistortImage(view);\n        imshow(\"Debug_undistorted_cv\", rview);\n        imshow(\"Debug_undistorted\", ourView);\n        waitKey(10);\n    }\n}\n\n//! [board_corners]\nstatic bool runCalibration(Settings &s, Size &imageSize, Mat &cameraMatrix, Mat &distCoeffs,\n                           vector<vector<Point2f> > imagePoints, vector<Mat> &rvecs, vector<Mat> &tvecs,\n                           vector<float> &reprojErrs, double &totalAvgErr) {\n    //! [fixed_aspect]\n    cameraMatrix = Mat::eye(3, 3, CV_64F);\n    if (s.flag & CALIB_FIX_ASPECT_RATIO)\n        cameraMatrix.at<double>(0, 0) = s.aspectRatio;\n    //! [fixed_aspect]\n    if (s.useFisheye) {\n        distCoeffs = Mat::zeros(4, 1, CV_64F);\n    } else {\n        distCoeffs = Mat::zeros(8, 1, CV_64F);\n    }\n\n    vector<vector<Point3f> > objectPoints(1);\n    calcBoardCornerPositions(s.boardSize, s.squareSize, objectPoints[0], s.calibrationPattern);\n\n    objectPoints.resize(imagePoints.size(), objectPoints[0]);\n\n    //Find intrinsic and extrinsic camera parameters\n    double rms;\n\n    if (s.useFisheye) {\n        Mat _rvecs, _tvecs;\n        rms = fisheye::calibrate(objectPoints, imagePoints, imageSize, cameraMatrix, distCoeffs, _rvecs,\n                                 _tvecs, s.flag);\n\n        rvecs.reserve(_rvecs.rows);\n        tvecs.reserve(_tvecs.rows);\n        for (int i = 0; i < int(objectPoints.size()); i++) {\n            rvecs.push_back(_rvecs.row(i));\n            tvecs.push_back(_tvecs.row(i));\n        }\n    } else {\n        rms = calibrateCamera(objectPoints, imagePoints, imageSize, cameraMatrix, distCoeffs, rvecs, tvecs,\n                              s.flag | CALIB_USE_LU);\n    }\n\n    cout << \"Re-projection error reported by calibrateCamera: \" << rms << endl;\n\n    bool ok = checkRange(cameraMatrix) && checkRange(distCoeffs);\n\n    totalAvgErr = computeReprojectionErrors(objectPoints, imagePoints, rvecs, tvecs, cameraMatrix,\n                                            distCoeffs, reprojErrs, s.useFisheye);\n\n    return ok;\n}\n\n// Print camera parameters to the output file\nstatic void saveCameraParams(Settings &s, Size &imageSize, Mat &cameraMatrix, Mat &distCoeffs,\n                             const vector<Mat> &rvecs, const vector<Mat> &tvecs,\n                             const vector<float> &reprojErrs, const vector<vector<Point2f> > &imagePoints,\n                             double totalAvgErr, const vector<double> &timestampSet) {\n    FileStorage fs(s.outputFileName, FileStorage::WRITE);\n\n    time_t tm;\n    time(&tm);\n    struct tm *t2 = localtime(&tm);\n    char buf[1024];\n    strftime(buf, sizeof(buf), \"%c\", t2);\n\n    fs << \"calibration_time\" << buf;\n\n    if (!rvecs.empty() || !reprojErrs.empty())\n        fs << \"nr_of_frames\" << (int) std::max(rvecs.size(), reprojErrs.size());\n    fs << \"image_width\" << imageSize.width;\n    fs << \"image_height\" << imageSize.height;\n    fs << \"board_width\" << s.boardSize.width;\n    fs << \"board_height\" << s.boardSize.height;\n    fs << \"square_size\" << s.squareSize;\n\n    if (s.flag & CALIB_FIX_ASPECT_RATIO)\n        fs << \"fix_aspect_ratio\" << s.aspectRatio;\n\n    if (s.flag) {\n        std::stringstream flagsStringStream;\n        if (s.useFisheye) {\n            flagsStringStream << \"flags:\"\n                              << (s.flag & fisheye::CALIB_FIX_SKEW ? \" +fix_skew\" : \"\")\n                              << (s.flag & fisheye::CALIB_FIX_K1 ? \" +fix_k1\" : \"\")\n                              << (s.flag & fisheye::CALIB_FIX_K2 ? \" +fix_k2\" : \"\")\n                              << (s.flag & fisheye::CALIB_FIX_K3 ? \" +fix_k3\" : \"\")\n                              << (s.flag & fisheye::CALIB_FIX_K4 ? \" +fix_k4\" : \"\")\n                              << (s.flag & fisheye::CALIB_RECOMPUTE_EXTRINSIC ? \" +recompute_extrinsic\" : \"\");\n        } else {\n            flagsStringStream << \"flags:\"\n                              << (s.flag & CALIB_USE_INTRINSIC_GUESS ? \" +use_intrinsic_guess\" : \"\")\n                              << (s.flag & CALIB_FIX_ASPECT_RATIO ? \" +fix_aspectRatio\" : \"\")\n                              << (s.flag & CALIB_FIX_PRINCIPAL_POINT ? \" +fix_principal_point\" : \"\")\n                              << (s.flag & CALIB_ZERO_TANGENT_DIST ? \" +zero_tangent_dist\" : \"\")\n                              << (s.flag & CALIB_FIX_K1 ? \" +fix_k1\" : \"\")\n                              << (s.flag & CALIB_FIX_K2 ? \" +fix_k2\" : \"\")\n                              << (s.flag & CALIB_FIX_K3 ? \" +fix_k3\" : \"\")\n                              << (s.flag & CALIB_FIX_K4 ? \" +fix_k4\" : \"\")\n                              << (s.flag & CALIB_FIX_K5 ? \" +fix_k5\" : \"\");\n        }\n        fs.writeComment(flagsStringStream.str());\n    }\n\n    fs << \"flags\" << s.flag;\n\n    fs << \"fisheye_model\" << s.useFisheye;\n\n    fs << \"camera_matrix\" << cameraMatrix;\n    fs << \"distortion_coefficients\" << distCoeffs;\n\n    fs << \"avg_reprojection_error\" << totalAvgErr;\n    if (s.writeExtrinsics && !reprojErrs.empty())\n        fs << \"per_view_reprojection_errors\" << Mat(reprojErrs);\n\n    if (s.writeExtrinsics && !rvecs.empty() && !tvecs.empty()) {\n        CV_Assert(rvecs[0].type() == tvecs[0].type());\n        Mat bigmat((int) rvecs.size(), 6, CV_MAKETYPE(rvecs[0].type(), 1));\n        bool needReshapeR = rvecs[0].depth() != 1 ? true : false;\n        bool needReshapeT = tvecs[0].depth() != 1 ? true : false;\n\n        std::ofstream f;\n        auto lastIndex = s.outputFileName.find_last_of('/');\n        f.open(s.outputFileName.substr(0, lastIndex) + \"/TrajectoryByCV.txt\");\n        f << std::fixed;\n        for (size_t i = 0; i < rvecs.size(); i++) {\n            Mat r = bigmat(Range(int(i), int(i + 1)), Range(0, 3));\n            Mat t = bigmat(Range(int(i), int(i + 1)), Range(3, 6));\n\n            if (needReshapeR)\n                rvecs[i].reshape(1, 1).copyTo(r);\n            else {\n                //*.t() is MatExpr (not Mat) so we can use assignment operator\n                CV_Assert(rvecs[i].rows == 3 && rvecs[i].cols == 1);\n                r = rvecs[i].t();\n            }\n\n            if (needReshapeT)\n                tvecs[i].reshape(1, 1).copyTo(t);\n            else {\n                CV_Assert(tvecs[i].rows == 3 && tvecs[i].cols == 1);\n                t = tvecs[i].t();\n            }\n\n            cv::Mat cvRcw;\n            cv::Rodrigues(rvecs[i], cvRcw);\n            Eigen::Matrix3d Rcw;\n            Eigen::Vector3d tcw;\n            cv::cv2eigen(cvRcw, Rcw);\n            cv::cv2eigen(tvecs[i], tcw);\n            Eigen::Quaterniond Qwc(Rcw.transpose());\n            Qwc.normalize();\n            Eigen::Vector3d twc = -(Qwc * tcw);\n\n            //timestamp tx ty tz qx qy qz qw\n            f << std::setprecision(10) << timestampSet[i] << \" \" << twc[0] << \" \" << twc[1] << \" \"\n              << twc[2] << \" \" << Qwc.x() << \" \" << Qwc.y() << \" \" << Qwc.z() << \" \" << Qwc.w() << std::endl;\n        }\n        //fs.writeComment(\"a set of 6-tuples (rotation vector + translation vector) for each view\");\n        //fs << \"extrinsic_parameters\" << bigmat;\n        f.close();\n    }\n\n    if (s.writePoints && !imagePoints.empty()) {\n        Mat imagePtMat((int) imagePoints.size(), (int) imagePoints[0].size(), CV_32FC2);\n        for (size_t i = 0; i < imagePoints.size(); i++) {\n            Mat r = imagePtMat.row(int(i)).reshape(2, imagePtMat.cols);\n            Mat imgpti(imagePoints[i]);\n            imgpti.copyTo(r);\n        }\n        fs << \"image_points\" << imagePtMat;\n    }\n}\n\n//! [run_and_save]\nbool runCalibrationAndSave(Settings &s, Size imageSize, Mat &cameraMatrix, Mat &distCoeffs,\n                           vector<vector<Point2f>> imagePoints, vector<Mat> &rvecs, vector<Mat> &tvecs,\n                           const vector<double> &timestampSet) {\n    vector<float> reprojErrs;\n    double totalAvgErr = 0;\n\n    bool ok = runCalibration(s, imageSize, cameraMatrix, distCoeffs, imagePoints, rvecs, tvecs, reprojErrs,\n                             totalAvgErr);\n    cout << (ok ? \"Calibration succeeded\" : \"Calibration failed\")\n         << \". avg re projection error = \" << totalAvgErr << endl;\n\n    if (ok)\n        saveCameraParams(s, imageSize, cameraMatrix, distCoeffs, rvecs, tvecs, reprojErrs, imagePoints,\n                         totalAvgErr, timestampSet);\n    return ok;\n}\n//! [run_and_save]\n", "meta": {"hexsha": "b43d4c4f61b3b8f5ca31130047eb52ca7dca5c38", "size": 37390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/camera_calibration/cv_calib/app/camera_calibration.cpp", "max_stars_repo_name": "MobilePerceptionLab/EventCameraCalibration", "max_stars_repo_head_hexsha": "debd774ac989674b500caf27641b7ad4e94681e9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2021-08-06T03:21:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T03:40:54.000Z", "max_issues_repo_path": "modules/camera_calibration/cv_calib/app/camera_calibration.cpp", "max_issues_repo_name": "MobilePerceptionLab/EventCameraCalibration", "max_issues_repo_head_hexsha": "debd774ac989674b500caf27641b7ad4e94681e9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-02-25T02:55:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T15:18:45.000Z", "max_forks_repo_path": "modules/camera_calibration/cv_calib/app/camera_calibration.cpp", "max_forks_repo_name": "MobilePerceptionLab/EventCameraCalibration", "max_forks_repo_head_hexsha": "debd774ac989674b500caf27641b7ad4e94681e9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-08-11T12:29:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T03:41:01.000Z", "avg_line_length": 39.7765957447, "max_line_length": 119, "alphanum_fraction": 0.5594276545, "num_tokens": 9466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583270090337582, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.2965885406064663}}
{"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 <boost/mpl/bool.hpp>\n#include <boost/mpl/and.hpp>\n#include <boost/mpl/or.hpp> \n#include <boost/static_assert.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/linear_algebra/identity.hpp>\n\nusing namespace std; \n\ntemplate <typename T, typename U, typename Assign>\nstruct lazy_assign\n{\n    typedef Assign  assign_type;\n\n    lazy_assign(T& first, const U& second) : first(first), second(second) {} \n\n    T&       first;\n    const U& second;\n\n};\n\ntemplate <typename T, typename U, typename Assign>\nvoid inline evaluate_lazy(lazy_assign<T, U, Assign>& lazy)\n{\n    Assign::first_update(lazy.first, lazy.second);\n}\n\n\ntemplate <typename T>\nstruct is_lazy : boost::mpl::false_ {};\n\ntemplate <typename T, typename U, typename Assign>\nstruct is_lazy<lazy_assign<T, U, Assign> > : boost::mpl::true_ {};\n\n\ntemplate <typename T>\nstruct lazy_t\n{\n    lazy_t(T& data) : data(data) {}\n\n    template <typename U>\n    lazy_assign<T, U, mtl::assign::assign_sum> operator=(const U& other) \n    { return lazy_assign<T, U, mtl::assign::assign_sum>(data, other); }\n\n    template <typename U>\n    lazy_assign<T, U, mtl::assign::plus_sum> operator+=(const U& other) \n    { return lazy_assign<T, U, mtl::assign::plus_sum>(data, other); }\n\n    template <typename U>\n    lazy_assign<T, U, mtl::assign::minus_sum> operator-=(const U& other) \n    { return lazy_assign<T, U, mtl::assign::minus_sum>(data, other); }\n\n    T& data;\n};\n\ntemplate <typename T>\ninline lazy_t<T> lazy(T& x) \n{ return lazy_t<T>(x); }\n\ntemplate <typename T>\ninline lazy_t<const T> lazy(const T& x) \n{ return lazy_t<const T>(x); }\n\ntemplate <typename T>\nstruct is_vector_reduction : boost::mpl::false_ {};\n\ntemplate <unsigned long Unroll, typename Vector1, typename Vector2, typename ConjOpt>\nstruct is_vector_reduction<mtl::dot_class<Unroll, Vector1, Vector2, ConjOpt> >\n  : boost::mpl::true_ {};\n\n#if 0\ntemplate <unsigned long Unroll, typename Vector>\nstruct is_vector_reduction<mtl::unary_dot_class<Unroll, Vector> >\n  : boost::mpl::true_ {};\n#endif\n\ntemplate<typename Vector, typename Functor>\nstruct is_vector_reduction<mtl::lazy_reduction<Vector, Functor> >\n  : boost::mpl::true_ {};\n\ntemplate <typename T>\nstruct index_evaluatable : boost::mpl::false_ {};\n\ntemplate <typename T, typename U, typename Assign>\nstruct index_evaluatable<lazy_assign<T, U, Assign> >\n  : boost::mpl::or_<\n      boost::mpl::and_<mtl::traits::is_vector<T>, mtl::traits::is_scalar<U> >,\n      boost::mpl::and_<mtl::traits::is_vector<T>, mtl::traits::is_vector<U> >,\n      boost::mpl::and_<mtl::traits::is_scalar<T>, is_vector_reduction<U> >\n    >\n{};\n\ntemplate <typename V1, typename Matrix, typename V2, typename Assign>\nstruct index_evaluatable<lazy_assign<V1, mtl::mat_cvec_times_expr<Matrix, V2>, Assign> >\n  : mtl::traits::is_row_major<Matrix> {};\n\n// Strided traversal would be more expensive than saving from mixed reduction\n//  : boost::mpl::or_<mtl::traits::is_row_major<Matrix>, mtl::traits::is_dense<Matrix> > {}; \n\ntemplate <typename T> struct evaluator_type {};\n\ntemplate <typename T, typename U, typename Assign>\nstruct evaluator_type<lazy_assign<T, U, Assign> >\n  : boost::lazy_enable_if<mtl::traits::is_vector<T>,\n\t\t\t  boost::mpl::if_<mtl::traits::is_vector<U>,\n\t\t\t\t\t  mtl::vec_vec_aop_expr<T, U, Assign>, \n\t\t\t\t\t  mtl::vec_scal_aop_expr<T, U, Assign>\n\t\t\t\t\t  >\n\t\t\t  >\n{};\n\ntemplate <typename T, typename U, typename Assign>\ntypename boost::enable_if<boost::mpl::and_<mtl::traits::is_vector<T>, mtl::traits::is_vector<U> >, \n\t\t\t  mtl::vec_vec_aop_expr<T, U, Assign> >::type\ninline index_evaluator(lazy_assign<T, U, Assign>& lazy)\n{\n    return mtl::vec_vec_aop_expr<T, U, Assign>(lazy.first, lazy.second, true);\n}\n\n\ntemplate <typename T, typename U, typename Assign>\ntypename boost::enable_if<boost::mpl::and_<mtl::traits::is_vector<T>, mtl::traits::is_scalar<U> >, \n\t\t\t  mtl::vec_scal_aop_expr<T, U, Assign> >::type\ninline index_evaluator(lazy_assign<T, U, Assign>& lazy)\n{\n    return mtl::vec_scal_aop_expr<T, U, Assign>(lazy.first, lazy.second, true);\n}\n\n#if 0\ntemplate <typename Scalar, typename Vector, typename Assign>\nstruct unary_dot_index_evaluator\n{\n    unary_dot_index_evaluator(Scalar& scalar, const Vector& v) \n      : scalar(scalar), v(v) \n    { \n\ttmp[0]= tmp[1]= tmp[2]= tmp[3]= Scalar(0); \n    }\n\n    ~unary_dot_index_evaluator() \n    { \n\tScalar s(tmp[0] + tmp[1] + tmp[2] + tmp[3]);\n\tAssign::apply(scalar, s); \n    }\n    \n    void operator() (std::size_t i) { mtl::two_norm_functor::update(tmp[0], v[i]); }\n    void operator[] (std::size_t i) { (*this)(i); }\n    \n    template <unsigned Offset>\n    void at(std::size_t i) \n    { mtl::two_norm_functor::update(tmp[Offset], v[i+Offset]); }\n\n    Scalar&        scalar;\n    Scalar         tmp[4];\n    const Vector&  v;\n};\n\ntemplate <typename Scalar, typename Vector, typename Assign>\ninline std::size_t size(const unary_dot_index_evaluator<Scalar, Vector, Assign>& eval)\n{ return size(eval.v); }\n#endif\n\n\ntemplate <typename Scalar, typename Vector, typename Functor, typename Assign>\nstruct reduction_index_evaluator\n{\n    reduction_index_evaluator(Scalar& scalar, const Vector& v) \n      : scalar(scalar), v(v) \n    {\n\tFunctor::init(tmp[0]);\n\ttmp[1]= tmp[2]= tmp[3]= tmp[0];\n    }\n\n    ~reduction_index_evaluator() \n    { \n\tFunctor::finish(tmp[0], tmp[1]);\n\tFunctor::finish(tmp[2], tmp[3]);\n\tFunctor::finish(tmp[0], tmp[2]);\n\tAssign::apply(scalar, Functor::post_reduction(tmp[0])); // compute sqrt or such if necessary\n    }\n\n    template <unsigned Offset>\n    void at(std::size_t i) \n    { \n\tFunctor::update(tmp[Offset], v[i+Offset]); \n    }\n\n    void operator[] (std::size_t i) { at<0>(i); }\n    void operator() (std::size_t i) { at<0>(i); }    \n\n    Scalar&        scalar;\n    Scalar         tmp[4];\n    const Vector&  v;\n};\n\ntemplate <typename Scalar, typename Vector, typename Functor, typename Assign>\ninline std::size_t size(const reduction_index_evaluator<Scalar, Vector, Functor, Assign>& eval)\n{ return size(eval.v); }\n\n\n\ntemplate <typename Scalar, typename Vector, typename Functor, typename Assign>\nreduction_index_evaluator<Scalar, Vector, Functor, Assign>\ninline index_evaluator(lazy_assign<Scalar, mtl::lazy_reduction<Vector, Functor>, Assign>& lazy)\n{\n    return reduction_index_evaluator<Scalar, Vector, Functor, Assign>(lazy.first, lazy.second.v);\n}\n\n\ntemplate <typename Scalar, typename Vector1, typename Vector2, typename ConjOpt, typename Assign>\nstruct dot_index_evaluator\n{\n    dot_index_evaluator(Scalar& scalar, const Vector1& v1, const Vector2& v2) \n      : scalar(scalar), v1(v1), v2(v2) \n    { \n\ttmp[0]= tmp[1]= tmp[2]= tmp[3]= Scalar(0); \n    }\n\n    ~dot_index_evaluator() \n    { \n\tScalar s(tmp[0] + tmp[1] + tmp[2] + tmp[3]);\n\tAssign::apply(scalar, s); \n    }\n    \n    void operator() (std::size_t i) { tmp[0]+= ConjOpt()(v1[i]) * v2[i]; }\n    void operator[] (std::size_t i) { (*this)(i); }\n\n    template <unsigned Offset>\n    void at(std::size_t i) \n    { tmp[Offset]+= ConjOpt()(v1[i+Offset]) * v2[i+Offset]; }\n\n    Scalar&        scalar;\n    Scalar         tmp[4];\n    const Vector1& v1;\n    const Vector2& v2;\n};\n\ntemplate <typename Scalar, typename Vector1, typename Vector2, typename ConjOpt, typename Assign>\ninline std::size_t size(const dot_index_evaluator<Scalar, Vector1, Vector2, ConjOpt, Assign>& eval)\n{ \n    return size(eval.v1);\n}\n\n\ntemplate <typename Scalar, unsigned long Unroll, typename Vector1, \n\t  typename Vector2, typename ConjOpt, typename Assign>\ndot_index_evaluator<Scalar, Vector1, Vector2, ConjOpt, Assign>\ninline index_evaluator(lazy_assign<Scalar, mtl::dot_class<Unroll, Vector1, Vector2, ConjOpt>, Assign>& lazy)\n{\n    return dot_index_evaluator<Scalar, Vector1, Vector2, ConjOpt, Assign>(lazy.first, lazy.second.v1, lazy.second.v2);\n}\n\ntemplate <typename VectorOut, typename Matrix, typename VectorIn, typename Assign>\nstruct row_mat_cvec_index_evaluator\n{\n    BOOST_STATIC_ASSERT((mtl::traits::is_row_major<Matrix>::value));\n    typedef typename mtl::Collection<VectorOut>::value_type        value_type;\n    typedef typename mtl::Collection<Matrix>::size_type            size_type; \n\n    row_mat_cvec_index_evaluator(VectorOut& w, const Matrix& A, const VectorIn& v) : w(w), A(A), v(v) {}\n\n    template <unsigned Offset>\n    void at(size_type i, mtl::tag::sparse)\n    {\n\tvalue_type tmp(math::zero(w[i+Offset]));\n\tconst size_type cj0= A.ref_major()[i+Offset], cj1= A.ref_major()[i+Offset+1];\n\tfor (size_type j= cj0; j != cj1; ++j)\n\t    tmp+= A.data[j] * v[A.ref_minor()[j]];\n\tAssign::first_update(w[i+Offset], tmp);\n    }\n\n    template <unsigned Offset>\n    void at(size_type i, mtl::tag::dense)\n    {\n\tvalue_type tmp(math::zero(w[i+Offset]));\n\tfor (size_type j= 0; j < num_cols(A); j++) \n\t    tmp+= A[i][j] * v[j];\n\tAssign::first_update(w[i+Offset], tmp);\n    }\n\n    template <unsigned Offset>\n    void at(size_type i)\n    { \n\tat<Offset>(i, typename mtl::traits::category<Matrix>::type());\n    }\n\n    void operator()(size_type i) { at<0>(i); }\n    void operator[](size_type i) { at<0>(i); }\n\n    VectorOut&      w;\n    const Matrix&   A;\n    const VectorIn& v;\n};\n\ntemplate <typename VectorOut, typename Matrix, typename VectorIn, typename Assign>\ninline std::size_t size(const row_mat_cvec_index_evaluator<VectorOut, Matrix, VectorIn, Assign>& eval)\n{\n    return size(eval.w);\n}\n\ntemplate <typename VectorOut, typename Matrix, typename VectorIn, typename Assign>\nrow_mat_cvec_index_evaluator<VectorOut, Matrix, VectorIn, Assign>\ninline index_evaluator(lazy_assign<VectorOut, mtl::mat_cvec_times_expr<Matrix, VectorIn>, Assign>& lazy)\n{\n    return row_mat_cvec_index_evaluator<VectorOut, Matrix, VectorIn, Assign>(lazy.first, lazy.second.first, lazy.second.second);\n}\n\ntemplate <typename T, typename U> struct fused_expr;\ntemplate <typename T, typename U> void inline evaluate_lazy(fused_expr<T, U>& expr);\n\n\ntemplate <typename T, typename U>\nstruct fused_expr\n{\n    template <typename TT, typename UU, typename Assign>\n    void check(lazy_assign<TT, UU, Assign>& )\n    {\n\tbool vec_scal= boost::mpl::and_<mtl::traits::is_vector<TT>, mtl::traits::is_scalar<UU> >::value;\n\tbool vec_vec= boost::mpl::and_<mtl::traits::is_vector<TT>, mtl::traits::is_vector<UU> >::value;\n\tbool scal_red= boost::mpl::and_<mtl::traits::is_scalar<TT>, is_vector_reduction<UU> >::value;\n\t\n\tbool ia= boost::mpl::or_<\n\t    boost::mpl::and_<mtl::traits::is_vector<TT>, mtl::traits::is_scalar<UU> >,\n\t    boost::mpl::and_<mtl::traits::is_vector<TT>, mtl::traits::is_vector<UU> >,\n\t    boost::mpl::and_<mtl::traits::is_scalar<TT>, is_vector_reduction<UU> >\n\t    >::value;\n    }\n\n\n    fused_expr(T& first, U& second) : first(first), second(second) \n    {\n\t// check(first); check(second);\n\t//index_evaluatable<T> it= \"\";\n\t//index_evaluatable<U> iu= \"\";\n    }\n \n    ~fused_expr() { eval(index_evaluatable<T>(), index_evaluatable<U>()); }\n\n    template <typename TT, typename UU>\n    void eval_loop(TT first_eval, UU second_eval)\n    {\t\n\tMTL_DEBUG_THROW_IF(/*mtl::*/  size(first_eval) != /*mtl::*/  size(second_eval), mtl::incompatible_size());\t\n\n#ifdef MTL_LAZY_LOOP_WO_UNROLL\n\tfor (std::size_t i= 0, s= size(first_eval); i < s; i++) {\n\t    first_eval(i); second_eval(i);\n\t}\t\n#else\n\tstd::size_t s= size(first_eval), sb= s >> 2 << 2;\n\n\tfor (std::size_t i= 0; i < sb; i+= 4) {\n\t    first_eval.template at<0>(i); second_eval.template at<0>(i);\n\t    first_eval.template at<1>(i); second_eval.template at<1>(i);\n\t    first_eval.template at<2>(i); second_eval.template at<2>(i);\n\t    first_eval.template at<3>(i); second_eval.template at<3>(i);\n\t}\n\n\tfor (std::size_t i= sb; i < s; i++) {\n\t    first_eval(i); second_eval(i);\n\t}\n#endif\n    }\n\n    void eval(boost::mpl::true_, boost::mpl::true_)\n    {\n\tcout << \"Now I really fuse!\\n\";\n\teval_loop(index_evaluator(first), index_evaluator(second)); \n    }\n\n    template <bool B1, bool B2>\n    void eval(boost::mpl::bool_<B1>, boost::mpl::bool_<B2>)\n    { evaluate_lazy(first); evaluate_lazy(second); }\n\n    T& first;\n    U& second;\n};\n\ntemplate <typename T, typename U>\nstruct is_lazy<fused_expr<T, U> > \n  : boost::mpl::and_<is_lazy<T>, is_lazy<U> > \n{};\n\ntemplate <typename T, typename U>\nstruct index_evaluatable<fused_expr<T, U> > \n  : boost::mpl::and_<index_evaluatable<T>, index_evaluatable<U> > \n{};\n\ntemplate <typename T, typename U>\nvoid inline evaluate_lazy(fused_expr<T, U>& expr) \n{ evaluate_lazy(expr.first); evaluate_lazy(expr.second); }\n\n\ntemplate <typename T, typename U>\nstruct fused_index_evaluator\n{\n    fused_index_evaluator(T& first, U& second) \n      : first(index_evaluator(first)), second(index_evaluator(second)) {}\n\n    template <unsigned Offset>\n    void at(std::size_t i) \n    { first.at<Offset>(i); second.at<Offset>(i); }\n\n    void operator() (std::size_t i) { at<0>(i); }\n    void operator[] (std::size_t i) { at<0>(i); }\n\n    typename evaluator_type<T>::type first;\n    typename evaluator_type<U>::type second;\n};\n\ntemplate <typename T, typename U>\ninline size_t size(const fused_index_evaluator<T, U>& expr) { return size(expr.first); }\n\ntemplate <typename T, typename U>\nstruct evaluator_type<fused_expr<T, U> >\n{\n    typedef fused_index_evaluator<T, U> type;\n};\n\ntemplate <typename T, typename U>\ninline fused_index_evaluator<T, U> index_evaluator(fused_expr<T, U>& expr)\n{  return fused_index_evaluator<T, U>(expr.first, expr.second); }\n\n\ntemplate <typename T, typename U>\ntypename boost::enable_if<boost::mpl::and_<is_lazy<T>, is_lazy<U> >, fused_expr<T, U> >::type\noperator||(const T& x, const U& y)\n{\n    return fused_expr<T, U>(const_cast<T&>(x), const_cast<U&>(y));\n}\n\ntemplate <typename T, typename U>\ntypename boost::enable_if<boost::mpl::and_<is_lazy<T>, is_lazy<U> >, fused_expr<T, U> >::type\nfuse(const T& x, const U& y)\n{\n    return fused_expr<T, U>(const_cast<T&>(x), const_cast<U&>(y));\n}\n\n\nint main(int, char**) \n{\n    double                d, rho, alpha= 7.8, beta, gamma;\n    const double          cd= 2.6;\n    std::complex<double>  z;\n\n    mtl::dense_vector<double> v(6, 1.0), w(6), r(6, 6.0), q(6, 2.0), x(6);\n    mtl::dense2D<double>      A(6, 6);\n    A= 2.0;\n    mtl::compressed2D<double>      B(6, 6);\n    B= 2.0;\n\n    (lazy(w)= A * v) || (lazy(d) = lazy_dot(w, v));\n    // fuse(lazy(w)= A * v, lazy(d) = lazy_dot(w, v));\n    // d= with_reduction(lazy(w)= A * v, lazy_dot(w, v));\n    cout << \"w = \" << w << \", d (12?)= \" << d << \"\\n\";\n\n    (lazy(w)= B * v) || (lazy(d) = lazy_dot(w, v));\n    // fuse(lazy(w)= A * v, lazy(d) = lazy_dot(w, v));\n    // d= with_reduction(lazy(w)= A * v, lazy_dot(w, v));\n    cout << \"w = \" << w << \", d (12?)= \" << d << \"\\n\";\n\n    (lazy(r)-= alpha * q) || (lazy(rho)= lazy_unary_dot(r)); \n    //fuse( lazy(r)-= alpha * q, lazy(rho)= lazy_unary_dot(r) ); \n    // lazy(r)-= alpha * q, lazy(rho)= lazy_unary_dot(r);\n    cout << \"r = \" << r << \", rho (552.96?) = \" << rho << \"\\n\";\n\n    (lazy(x)= 7.0) || (lazy(beta)= lazy_unary_dot(x)); \n    cout << \"x = \" << x << \", beta (294?) = \" << beta << \"\\n\";\n    \n    (lazy(x)= 7.0) || (lazy(beta)= lazy_one_norm(x)); \n    cout << \"x = \" << x << \", beta (42?) = \" << beta << \"\\n\";\n    \n    (lazy(x)= 7.0) || (lazy(beta)= lazy_two_norm(x)); \n    cout << \"x = \" << x << \", beta (17.1464?) = \" << beta << \"\\n\";\n    \n    (lazy(x)= 7.0) || (lazy(beta)= lazy_infinity_norm(x)); \n    cout << \"x = \" << x << \", beta (7?) = \" << beta << \"\\n\";\n    \n    (lazy(x)= 7.0) || (lazy(beta)= lazy_sum(x)); \n    cout << \"x = \" << x << \", beta (42?) = \" << beta << \"\\n\";\n    \n    (lazy(x)= 7.0) || (lazy(beta)= lazy_product(x)); \n    cout << \"x = \" << x << \", beta (117649?) = \" << beta << \"\\n\";\n    \n    (lazy(x)= 2.0) || (lazy(gamma)= lazy_dot(r, x)); \n    cout << \"x = \" << x << \", gamma (-115.2?) = \" << gamma << \"\\n\";\n    \n    (lazy(r)= alpha * q) || (lazy(rho)= lazy_dot(r, q)); \n    cout << \"r = \" << r << \", rho (187.2?) = \" << rho << \"\\n\";\n\n    (lazy(r)= alpha * q) || (lazy(v)= 8.6 * q) || (lazy(x)= 2.2 * q); \n    //fuse( lazy(r)-= alpha * q, lazy(rho)= lazy_unary_dot(r) ); \n    // lazy(r)-= alpha * q, lazy(rho)= lazy_unary_dot(r);\n    cout << \"r = \" << r << \", v (17.2?) = \" << v << \"\\n\";\n\n\n    \n\n\n    return 0;\n}\n", "meta": {"hexsha": "47c5d218694c493749fbf3e91af75f92caddbca4", "size": 16530, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/experimental/lazy_assign.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/experimental/lazy_assign.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/experimental/lazy_assign.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": 32.1595330739, "max_line_length": 128, "alphanum_fraction": 0.6441016334, "num_tokens": 4937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.296588532798547}}
{"text": "//\n//  Copyright (c) 2000-2002\n//  Joerg Walter, Mathias Koch\n//\n//  Permission to use, copy, modify, distribute and sell this software\n//  and its documentation for any purpose is hereby granted without fee,\n//  provided that the above copyright notice appear in all copies and\n//  that both that copyright notice and this permission notice appear\n//  in supporting documentation.  The authors make no representations\n//  about the suitability of this software for any purpose.\n//  It is provided \"as is\" without express or implied warranty.\n//\n//  The authors gratefully acknowledge the support of\n//  GeNeSys mbH & Co. KG in producing this work.\n//\n\n#ifndef BOOST_UBLAS_TRAITS_H\n#define BOOST_UBLAS_TRAITS_H\n\n#include <algorithm>\n#include <iterator>\n#include <complex>\n#include <cmath>\n\n#include <boost/numeric/ublas/iterator.hpp>\n#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) && !defined(BOOST_NO_SFINAE)\n#include <boost/numeric/ublas/returntype_deduction.hpp>\n#endif\n\nnamespace boost { namespace numeric { namespace ublas {\n\n    template<class T>\n    struct type_traits {\n        typedef type_traits<T> self_type;\n        typedef T value_type;\n        typedef const T &const_reference;\n        typedef T &reference;\n\n        /*\n         * Don't define unknown properties\n         * \n        typedef T real_type;\n        typedef T precision_type;\n\n        BOOST_STATIC_CONSTANT (unsigned, plus_complexity = 0);\n        BOOST_STATIC_CONSTANT (unsigned, multiplies_complexity = 0);\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type real (const_reference) {\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type imag (const_reference) {\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type conj (const_reference) {\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type abs (const_reference) {\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type sqrt (const_reference) {\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_1 (const_reference t) {\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_2 (const_reference t) {\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_inf (const_reference t) {\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        bool equals (const_reference t1, const_reference t2) {\n        }\n        */\n        // Dummy definition for compilers that error if undefined even though it is never used\n#ifdef BOOST_NO_SFINAE\n        typedef void real_type;\n        typedef void precision_type;\n#endif\n    };\n\n    template<>\n    struct type_traits<float> {\n        typedef type_traits<float> self_type;\n        typedef float value_type;\n        typedef const value_type &const_reference;\n        typedef value_type &reference;\n        typedef value_type real_type;\n        typedef double precision_type;\n\n        BOOST_STATIC_CONSTANT (unsigned, plus_complexity = 1);\n        BOOST_STATIC_CONSTANT (unsigned, multiplies_complexity = 1);\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type real (const_reference t) {\n                return t;\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type imag (const_reference /*t*/) {\n                return 0;\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type conj (const_reference t) {\n                return t;\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type abs (const_reference t) {\n#if defined (BOOST_NO_STDC_NAMESPACE) || defined (BOOST_UBLAS_CMATH_BAD_STD)\n            return ::fabsf (t);\n#else\n            return std::abs (t);\n#endif\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type sqrt (const_reference t) {\n#if defined (BOOST_NO_STDC_NAMESPACE) || defined (BOOST_UBLAS_CMATH_BAD_STD)\n            return ::sqrtf (t);\n#else\n            return std::sqrt (t);\n#endif\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_1 (const_reference t) {\n            return self_type::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_2 (const_reference t) {\n            return self_type::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_inf (const_reference t) {\n            return self_type::abs (t);\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        bool equals (const_reference t1, const_reference t2) {\n            return self_type::norm_inf (t1 - t2) < BOOST_UBLAS_TYPE_CHECK_EPSILON *\n                   (std::max) ((std::max) (self_type::norm_inf (t1),\n                                       self_type::norm_inf (t2)),\n                             BOOST_UBLAS_TYPE_CHECK_MIN);\n        }\n    };\n    template<>\n    struct type_traits<double> {\n        typedef type_traits<double> self_type;\n        typedef double value_type;\n        typedef const value_type &const_reference;\n        typedef value_type &reference;\n        typedef value_type real_type;\n#ifndef BOOST_UBLAS_NO_LONG_DOUBLE\n        typedef long double precision_type;\n#else\n        typedef value_type precision_type;\n#endif\n\n        BOOST_STATIC_CONSTANT (unsigned, plus_complexity = 1);\n        BOOST_STATIC_CONSTANT (unsigned, multiplies_complexity = 1);\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type real (const_reference t) {\n                return t;\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type imag (const_reference /*t*/) {\n                return 0;\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type conj (const_reference t) {\n                return t;\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type abs (const_reference t) {\n#if defined (BOOST_NO_STDC_NAMESPACE) || defined (BOOST_UBLAS_CMATH_BAD_STD)\n            return ::fabs (t);\n#else\n            return std::abs (t);\n#endif\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type sqrt (const_reference t) {\n#if defined (BOOST_NO_STDC_NAMESPACE) || defined (BOOST_UBLAS_CMATH_BAD_STD)\n            return ::sqrt (t);\n#else\n            return std::sqrt (t);\n#endif\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_1 (const_reference t) {\n            return self_type::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_2 (const_reference t) {\n            return self_type::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_inf (const_reference t) {\n            return self_type::abs (t);\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        bool equals (const_reference t1, const_reference t2) {\n            return self_type::norm_inf (t1 - t2) < BOOST_UBLAS_TYPE_CHECK_EPSILON *\n                   (std::max) ((std::max) (self_type::norm_inf (t1),\n                                       self_type::norm_inf (t2)),\n                             BOOST_UBLAS_TYPE_CHECK_MIN);\n        }\n    };\n#ifndef BOOST_UBLAS_NO_LONG_DOUBLE\n    template<>\n    struct type_traits<long double> {\n        typedef type_traits<long double> self_type;\n        typedef long double value_type;\n        typedef const value_type &const_reference;\n        typedef value_type &reference;\n        typedef value_type real_type;\n        typedef value_type precision_type;\n\n        BOOST_STATIC_CONSTANT (unsigned, plus_complexity = 1);\n        BOOST_STATIC_CONSTANT (unsigned, multiplies_complexity = 1);\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type real (const_reference t) {\n                return t;\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type imag (const_reference /*t*/) {\n                return 0;\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type conj (const_reference t) {\n                return t;\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type abs (const_reference t) {\n#if defined (BOOST_NO_STDC_NAMESPACE) || defined (BOOST_UBLAS_CMATH_BAD_STD)\n            return ::fabsl (t);\n#else\n            return std::abs (t);\n#endif\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type sqrt (const_reference t) {\n#if defined (BOOST_NO_STDC_NAMESPACE) || defined (BOOST_UBLAS_CMATH_BAD_STD)\n            return ::sqrtl (t);\n#else\n            return std::sqrt (t);\n#endif\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_1 (const_reference t) {\n            return self_type::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_2 (const_reference t) {\n            return self_type::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_inf (const_reference t) {\n            return self_type::abs (t);\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        bool equals (const_reference t1, const_reference t2) {\n            return self_type::norm_inf (t1 - t2) < BOOST_UBLAS_TYPE_CHECK_EPSILON *\n                   (std::max) ((std::max) (self_type::norm_inf (t1),\n                                       self_type::norm_inf (t2)),\n                             BOOST_UBLAS_TYPE_CHECK_MIN);\n        }\n    };\n#endif\n\n    template<>\n    struct type_traits<std::complex<float> > {\n        typedef type_traits<std::complex<float> > self_type;\n        typedef std::complex<float> value_type;\n        typedef const value_type &const_reference;\n        typedef value_type &reference;\n        typedef float real_type;\n        typedef std::complex<double> precision_type;\n\n        BOOST_STATIC_CONSTANT (unsigned, plus_complexity = 2);\n        BOOST_STATIC_CONSTANT (unsigned, multiplies_complexity = 6);\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type real (const_reference t) {\n                return std::real (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type imag (const_reference t) {\n                return std::imag (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type conj (const_reference t) {\n                return std::conj (t);\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type abs (const_reference t) {\n                return std::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type sqrt (const_reference t) {\n                return std::sqrt (t);\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_1 (const_reference t) {\n            return type_traits<real_type>::abs (self_type::real (t)) +\n                   type_traits<real_type>::abs (self_type::imag (t));\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_2 (const_reference t) {\n            return self_type::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_inf (const_reference t) {\n            return (std::max) (type_traits<real_type>::abs (self_type::real (t)),\n                             type_traits<real_type>::abs (self_type::imag (t)));\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        bool equals (const_reference t1, const_reference t2) {\n            return self_type::norm_inf (t1 - t2) < BOOST_UBLAS_TYPE_CHECK_EPSILON *\n                   (std::max) ((std::max) (self_type::norm_inf (t1),\n                                       self_type::norm_inf (t2)),\n                             BOOST_UBLAS_TYPE_CHECK_MIN);\n        }\n    };\n    template<>\n    struct type_traits<std::complex<double> > {\n        typedef type_traits<std::complex<double> > self_type;\n        typedef std::complex<double> value_type;\n        typedef const value_type &const_reference;\n        typedef value_type &reference;\n        typedef double real_type;\n#ifndef BOOST_UBLAS_NO_LONG_DOUBLE\n        typedef std::complex<long double> precision_type;\n#else\n        typedef value_type precision_type;\n#endif\n\n        BOOST_STATIC_CONSTANT (unsigned, plus_complexity = 2);\n        BOOST_STATIC_CONSTANT (unsigned, multiplies_complexity = 6);\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type real (const_reference t) {\n                return std::real (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type imag (const_reference t) {\n                return std::imag (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type conj (const_reference t) {\n                return std::conj (t);\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type abs (const_reference t) {\n                return std::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type sqrt (const_reference t) {\n                return std::sqrt (t);\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_1 (const_reference t) {\n            return type_traits<real_type>::abs (self_type::real (t)) +\n                   type_traits<real_type>::abs (self_type::imag (t));\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_2 (const_reference t) {\n            return self_type::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_inf (const_reference t) {\n            return (std::max) (type_traits<real_type>::abs (self_type::real (t)),\n                             type_traits<real_type>::abs (self_type::imag (t)));\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        bool equals (const_reference t1, const_reference t2) {\n            return self_type::norm_inf (t1 - t2) < BOOST_UBLAS_TYPE_CHECK_EPSILON *\n                   (std::max) ((std::max) (self_type::norm_inf (t1),\n                                       self_type::norm_inf (t2)),\n                             BOOST_UBLAS_TYPE_CHECK_MIN);\n        }\n    };\n#ifndef BOOST_UBLAS_NO_LONG_DOUBLE\n    template<>\n    struct type_traits<std::complex<long double> > {\n        typedef type_traits<std::complex<long double> > self_type;\n        typedef std::complex<long double> value_type;\n        typedef const value_type &const_reference;\n        typedef value_type &reference;\n        typedef long double real_type;\n        typedef value_type precision_type;\n\n        BOOST_STATIC_CONSTANT (unsigned, plus_complexity = 2);\n        BOOST_STATIC_CONSTANT (unsigned, multiplies_complexity = 6);\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type real (const_reference t) {\n                return std::real (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type imag (const_reference t) {\n                return std::imag (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type conj (const_reference t) {\n                return std::conj (t);\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type abs (const_reference t) {\n                return std::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type sqrt (const_reference t) {\n                return std::sqrt (t);\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_1 (const_reference t) {\n            return type_traits<real_type>::abs (self_type::real (t)) +\n                   type_traits<real_type>::abs (self_type::imag (t));\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_2 (const_reference t) {\n            return self_type::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_inf (const_reference t) {\n            return (std::max) (type_traits<real_type>::abs (self_type::real (t)),\n                             type_traits<real_type>::abs (self_type::imag (t)));\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        bool equals (const_reference t1, const_reference t2) {\n            return self_type::norm_inf (t1 - t2) < BOOST_UBLAS_TYPE_CHECK_EPSILON *\n                   (std::max) ((std::max) (self_type::norm_inf (t1),\n                                       self_type::norm_inf (t2)),\n                             BOOST_UBLAS_TYPE_CHECK_MIN);\n        }\n    };\n#endif\n\n#ifdef BOOST_UBLAS_USE_INTERVAL\n    template<>\n    struct type_traits<boost::numeric::interval<float> > {\n        typedef type_traits<boost::numeric::interval<float> > self_type;\n        typedef boost::numeric::interval<float> value_type;\n        typedef const value_type &const_reference;\n        typedef value_type &reference;\n        typedef value_type real_type;\n        typedef boost::numeric::interval<double> precision_type;\n\n        BOOST_STATIC_CONSTANT (unsigned, plus_complexity = 1);\n        BOOST_STATIC_CONSTANT (unsigned, multiplies_complexity = 1);\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type real (const_reference t) {\n                return t;\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type imag (const_reference t) {\n                return 0;\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type conj (const_reference t) {\n                return t;\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type abs (const_reference t) {\n            return boost::numeric::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type sqrt (const_reference t) {\n            return boost::numeric::sqrt (t);\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_1 (const_reference t) {\n            return self_type::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_2 (const_reference t) {\n            return self_type::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_inf (const_reference t) {\n            return self_type::abs (t);\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        bool equals (const_reference t1, const_reference t2) {\n            return self_type::norm_inf (t1 - t2) < BOOST_UBLAS_TYPE_CHECK_EPSILON *\n                   (std::max) ((std::max) (self_type::norm_inf (t1),\n                                       self_type::norm_inf (t2)),\n                             BOOST_UBLAS_TYPE_CHECK_MIN);\n        }\n    };\n    template<>\n    struct type_traits<boost::numeric::interval<double> > {\n        typedef type_traits<boost::numeric::interval<double> > self_type;\n        typedef boost::numeric::interval<double> value_type;\n        typedef const value_type &const_reference;\n        typedef value_type &reference;\n        typedef value_type real_type;\n#ifndef BOOST_UBLAS_NO_LONG_DOUBLE\n        typedef boost::numeric::interval<long double> precision_type;\n#else\n        typedef value_type precision_type;\n#endif\n\n        BOOST_STATIC_CONSTANT (unsigned, plus_complexity = 1);\n        BOOST_STATIC_CONSTANT (unsigned, multiplies_complexity = 1);\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type real (const_reference t) {\n                return t;\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type imag (const_reference t) {\n                return 0;\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type conj (const_reference t) {\n                return t;\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type abs (const_reference t) {\n            return boost::numeric::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type sqrt (const_reference t) {\n            return boost::numeric::sqrt (t);\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_1 (const_reference t) {\n            return self_type::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_2 (const_reference t) {\n            return self_type::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_inf (const_reference t) {\n            return self_type::abs (t);\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        bool equals (const_reference t1, const_reference t2) {\n            return self_type::norm_inf (t1 - t2) < BOOST_UBLAS_TYPE_CHECK_EPSILON *\n                   (std::max) ((std::max) (self_type::norm_inf (t1),\n                                       self_type::norm_inf (t2)),\n                             BOOST_UBLAS_TYPE_CHECK_MIN);\n        }\n    };\n#ifndef BOOST_UBLAS_NO_LONG_DOUBLE\n    template<>\n    struct type_traits<boost::numeric::interval<long double> > {\n        typedef type_traits<boost::numeric::interval<long double> > self_type;\n        typedef boost::numeric::interval<long double> value_type;\n        typedef const value_type &const_reference;\n        typedef value_type &reference;\n        typedef value_type real_type;\n        typedef value_type precision_type;\n\n        BOOST_STATIC_CONSTANT (unsigned, plus_complexity = 1);\n        BOOST_STATIC_CONSTANT (unsigned, multiplies_complexity = 1);\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type real (const_reference t) {\n                return t;\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type imag (const_reference t) {\n                return 0;\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type conj (const_reference t) {\n                return t;\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type abs (const_reference t) {\n            return boost::numeric::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type sqrt (const_reference t) {\n            return boost::numeric::sqrt (t);\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_1 (const_reference t) {\n            return self_type::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_2 (const_reference t) {\n            return self_type::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_inf (const_reference t) {\n            return self_type::abs (t);\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        bool equals (const_reference t1, const_reference t2) {\n            return self_type::norm_inf (t1 - t2) < BOOST_UBLAS_TYPE_CHECK_EPSILON *\n                   (std::max) ((std::max) (self_type::norm_inf (t1),\n                                       self_type::norm_inf (t2)),\n                             BOOST_UBLAS_TYPE_CHECK_MIN);\n        }\n    };\n#endif\n\n#ifdef BOOST_UBLAS_USE_BOOST_COMPLEX\n    template<>\n    struct type_traits<boost::complex<boost::numeric::interval<float> > > {\n        typedef type_traits<boost::complex<boost::numeric::interval<float> > > self_type;\n        typedef boost::complex<boost::numeric::interval<float> > value_type;\n        typedef const value_type &const_reference;\n        typedef value_type &reference;\n        typedef boost::numeric::interval<float> real_type;\n        typedef boost::complex<boost::numeric::interval<double> > precision_type;\n\n        BOOST_STATIC_CONSTANT (unsigned, plus_complexity = 2);\n        BOOST_STATIC_CONSTANT (unsigned, multiplies_complexity = 6);\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type real (const_reference t) {\n                return std::real (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type imag (const_reference t) {\n                return std::imag (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type conj (const_reference t) {\n                return std::conj (t);\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type abs (const_reference t) {\n                return boost::numeric::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type sqrt (const_reference t) {\n                return boost::numeric::sqrt (t);\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_1 (const_reference t) {\n            return type_traits<real_type>::abs (self_type::real (t)) +\n                   type_traits<real_type>::abs (self_type::imag (t));\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_2 (const_reference t) {\n            return self_type::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_inf (const_reference t) {\n            return (std::max) (type_traits<real_type>::abs (self_type::real (t)),\n                             type_traits<real_type>::abs (self_type::imag (t)));\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        bool equals (const_reference t1, const_reference t2) {\n            return self_type::norm_inf (t1 - t2) < BOOST_UBLAS_TYPE_CHECK_EPSILON *\n                   (std::max) ((std::max) (self_type::norm_inf (t1),\n                                       self_type::norm_inf (t2)),\n                             BOOST_UBLAS_TYPE_CHECK_MIN);\n        }\n    };\n    template<>\n    struct type_traits<boost::complex<boost::numeric::interval<double> > {\n        typedef type_traits<boost::complex<boost::numeric::interval<double> > self_type;\n        typedef boost::complex<boost::numeric::interval<double> > value_type;\n        typedef const value_type &const_reference;\n        typedef value_type &reference;\n        typedef boost::numeric::interval<double> real_type;\n#ifndef BOOST_UBLAS_NO_LONG_DOUBLE\n        typedef boost::complex<boost::numeric::interval<long double> > precision_type;\n#else\n        typedef value_type precision_type;\n#endif\n\n        BOOST_STATIC_CONSTANT (unsigned, plus_complexity = 2);\n        BOOST_STATIC_CONSTANT (unsigned, multiplies_complexity = 6);\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type real (const_reference t) {\n                return std::real (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type imag (const_reference t) {\n                return std::imag (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type conj (const_reference t) {\n                return std::conj (t);\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type abs (const_reference t) {\n                return boost::numeric::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type sqrt (const_reference t) {\n                return boost::numeric::sqrt (t);\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_1 (const_reference t) {\n            return type_traits<real_type>::abs (self_type::real (t)) +\n                   type_traits<real_type>::abs (self_type::imag (t));\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_2 (const_reference t) {\n            return self_type::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_inf (const_reference t) {\n            return (std::max) (type_traits<real_type>::abs (self_type::real (t)),\n                             type_traits<real_type>::abs (self_type::imag (t)));\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        bool equals (const_reference t1, const_reference t2) {\n            return self_type::norm_inf (t1 - t2) < BOOST_UBLAS_TYPE_CHECK_EPSILON *\n                   (std::max) ((std::max) (self_type::norm_inf (t1),\n                                       self_type::norm_inf (t2)),\n                             BOOST_UBLAS_TYPE_CHECK_MIN);\n        }\n    };\n#ifndef BOOST_UBLAS_NO_LONG_DOUBLE\n    template<>\n    struct type_traits<boost::complex<boost::numeric::interval<long double> > > {\n        typedef type_traits<boost::complex<boost::numeric::interval<long double> > > self_type;\n        typedef boost::complex<boost::numeric::interval<long double> > value_type;\n        typedef const value_type &const_reference;\n        typedef value_type &reference;\n        typedef boost::numeric::interval<long double> real_type;\n        typedef value_type precision_type;\n\n        BOOST_STATIC_CONSTANT (unsigned, plus_complexity = 2);\n        BOOST_STATIC_CONSTANT (unsigned, multiplies_complexity = 6);\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type real (const_reference t) {\n                return std::real (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type imag (const_reference t) {\n                return std::imag (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type conj (const_reference t) {\n                return std::conj (t);\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type abs (const_reference t) {\n                return boost::numeric::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        value_type sqrt (const_reference t) {\n                return boost::numeric::sqrt (t);\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_1 (const_reference t) {\n            return type_traits<real_type>::abs (self_type::real (t)) +\n                   type_traits<real_type>::abs (self_type::imag (t));\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_2 (const_reference t) {\n            return self_type::abs (t);\n        }\n        static\n        BOOST_UBLAS_INLINE\n        real_type norm_inf (const_reference t) {\n            return (std::max) (type_traits<real_type>::abs (self_type::real (t)),\n                             type_traits<real_type>::abs (self_type::imag (t)));\n        }\n\n        static\n        BOOST_UBLAS_INLINE\n        bool equals (const_reference t1, const_reference t2) {\n            return self_type::norm_inf (t1 - t2) < BOOST_UBLAS_TYPE_CHECK_EPSILON *\n                   (std::max) ((std::max) (self_type::norm_inf (t1),\n                                       self_type::norm_inf (t2)),\n                             BOOST_UBLAS_TYPE_CHECK_MIN);\n        }\n    };\n#endif\n#endif\n#endif\n\n\n\n#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) && !defined(BOOST_NO_SFINAE)\n    // Use Joel de Guzman's return type deduction\n    // uBLAS assumes a common return type for all binary arithmetic operators\n    template<class X, class Y>\n    struct promote_traits {\n        typedef type_deduction_detail::base_result_of<X, Y> base_type;\n        static typename base_type::x_type x;\n        static typename base_type::y_type y;\n        BOOST_STATIC_CONSTANT(int,\n            size = sizeof(\n                type_deduction_detail::test<\n                    typename base_type::x_type\n                  , typename base_type::y_type\n                >(x + y)     // Use x+y to stand of all the arithmetic actions\n            ));\n\n        BOOST_STATIC_CONSTANT(int, index = (size / sizeof(char)) - 1);\n        typedef typename mpl::at_c<\n            typename base_type::types, index>::type id;\n        typedef typename id::type promote_type;\n    };\n    template<class X, class Y>\n    struct promote_type_multiplies {\n        typedef type_deduction_detail::base_result_of<X, Y> base_type;\n        static typename base_type::x_type x;\n        static typename base_type::y_type y;\n        BOOST_STATIC_CONSTANT(int,\n            size = sizeof(\n                type_deduction_detail::test<\n                    typename base_type::x_type\n                  , typename base_type::y_type\n                >(x * y)     // Specifically the * arithmetic actions\n            ));\n\n        BOOST_STATIC_CONSTANT(int, index = (size / sizeof(char)) - 1);\n        typedef typename mpl::at_c<\n            typename base_type::types, index>::type id;\n        typedef typename id::type promote_type;\n    };\n\n\n#else\n    template<class T1, class T2>\n    struct promote_traits {\n        // Default promotion will badly fail, if the types are different.\n        // Thanks to Kresimir Fresl for spotting this.\n        BOOST_STATIC_ASSERT ((boost::is_same<T1, T2>::value));\n        typedef T1 promote_type;\n    };\n\n    template<>\n    struct promote_traits<float, double> {\n        typedef double promote_type;\n    };\n    template<>\n    struct promote_traits<double, float> {\n        typedef double promote_type;\n    };\n#ifndef BOOST_UBLAS_NO_LONG_DOUBLE\n    template<>\n    struct promote_traits<float, long double> {\n        typedef long double promote_type;\n    };\n    template<>\n    struct promote_traits<long double, float> {\n        typedef long double promote_type;\n    };\n    template<>\n    struct promote_traits<double, long double> {\n        typedef long double promote_type;\n    };\n    template<>\n    struct promote_traits<long double, double> {\n        typedef long double promote_type;\n    };\n#endif\n\n    template<>\n    struct promote_traits<float, std::complex<float> > {\n        typedef std::complex<float> promote_type;\n    };\n    template<>\n    struct promote_traits<std::complex<float>, float> {\n        typedef std::complex<float> promote_type;\n    };\n    template<>\n    struct promote_traits<float, std::complex<double> > {\n        typedef std::complex<double> promote_type;\n    };\n    template<>\n    struct promote_traits<std::complex<double>, float> {\n        typedef std::complex<double> promote_type;\n    };\n#ifndef BOOST_UBLAS_NO_LONG_DOUBLE\n    template<>\n    struct promote_traits<float, std::complex<long double> > {\n        typedef std::complex<long double> promote_type;\n    };\n    template<>\n    struct promote_traits<std::complex<long double>, float> {\n        typedef std::complex<long double> promote_type;\n    };\n#endif\n\n    template<>\n    struct promote_traits<double, std::complex<float> > {\n        // Here we'd better go the conservative way.\n        // typedef std::complex<float> promote_type;\n        typedef std::complex<double> promote_type;\n    };\n    template<>\n    struct promote_traits<std::complex<float>, double> {\n        // Here we'd better go the conservative way.\n        // typedef std::complex<float> promote_type;\n        typedef std::complex<double> promote_type;\n    };\n    template<>\n    struct promote_traits<double, std::complex<double> > {\n        typedef std::complex<double> promote_type;\n    };\n    template<>\n    struct promote_traits<std::complex<double>, double> {\n        typedef std::complex<double> promote_type;\n    };\n#ifndef BOOST_UBLAS_NO_LONG_DOUBLE\n    template<>\n    struct promote_traits<double, std::complex<long double> > {\n        typedef std::complex<long double> promote_type;\n    };\n    template<>\n    struct promote_traits<std::complex<long double>, double> {\n        typedef std::complex<long double> promote_type;\n    };\n#endif\n\n#ifndef BOOST_UBLAS_NO_LONG_DOUBLE\n    template<>\n    struct promote_traits<long double, std::complex<float> > {\n        // Here we'd better go the conservative way.\n        // typedef std::complex<float> promote_type;\n        typedef std::complex<long double> promote_type;\n    };\n    template<>\n    struct promote_traits<std::complex<float>, long double> {\n        // Here we'd better go the conservative way.\n        // typedef std::complex<float> promote_type;\n        typedef std::complex<long double> promote_type;\n    };\n    template<>\n    struct promote_traits<long double, std::complex<double> > {\n        // Here we'd better go the conservative way.\n        // typedef std::complex<double> promote_type;\n        typedef std::complex<long double> promote_type;\n    };\n    template<>\n    struct promote_traits<std::complex<double>, long double> {\n        // Here we'd better go the conservative way.\n        // typedef std::complex<double> promote_type;\n        typedef std::complex<long double> promote_type;\n    };\n    template<>\n    struct promote_traits<long double, std::complex<long double> > {\n        typedef std::complex<long double> promote_type;\n    };\n    template<>\n    struct promote_traits<std::complex<long double>, long double> {\n        typedef std::complex<long double> promote_type;\n    };\n#endif\n\n    template<>\n    struct promote_traits<std::complex<float>, std::complex<double> > {\n        typedef std::complex<double> promote_type;\n    };\n    template<>\n    struct promote_traits<std::complex<double>, std::complex<float> > {\n        typedef std::complex<double> promote_type;\n    };\n#ifndef BOOST_UBLAS_NO_LONG_DOUBLE\n    template<>\n    struct promote_traits<std::complex<float>, std::complex<long double> > {\n        typedef std::complex<long double> promote_type;\n    };\n    template<>\n    struct promote_traits<std::complex<long double>, std::complex<float> > {\n        typedef std::complex<long double> promote_type;\n    };\n    template<>\n    struct promote_traits<std::complex<double>, std::complex<long double> > {\n        typedef std::complex<long double> promote_type;\n    };\n    template<>\n    struct promote_traits<std::complex<long double>, std::complex<double> > {\n        typedef std::complex<long double> promote_type;\n    };\n#endif\n\n#ifdef BOOST_UBLAS_USE_INTERVAL\n    template<>\n    struct promote_traits<boost::numeric::interval<float>, boost::numeric::interval<double> > {\n        typedef boost::numeric::interval<double> promote_type;\n    };\n    template<>\n    struct promote_traits<boost::numeric::interval<double>, boost::numeric::interval<float> > {\n        typedef boost::numeric::interval<double> promote_type;\n    };\n#ifndef BOOST_UBLAS_NO_LONG_DOUBLE\n    template<>\n    struct promote_traits<boost::numeric::interval<float>, boost::numeric::interval<long double> > {\n        typedef boost::numeric::interval<long double> promote_type;\n    };\n    template<>\n    struct promote_traits<boost::numeric::interval<long double>, boost::numeric::interval<float> > {\n        typedef boost::numeric::interval<long double> promote_type;\n    };\n    template<>\n    struct promote_traits<boost::numeric::interval<double>, boost::numeric::interval<long double> > {\n        typedef boost::numeric::interval<long double> promote_type;\n    };\n    template<>\n    struct promote_traits<boost::numeric::interval<long double>, boost::numeric::interval<double> > {\n        typedef boost::numeric::interval<long double> promote_type;\n    };\n#endif\n\n#ifdef BOOST_UBLAS_USE_BOOST_COMPLEX\n    template<>\n    struct promote_traits<boost::numeric::interval<float>, boost::complex<boost::numeric::interval<float> > > {\n        typedef boost::complex<boost::numeric::interval<float> > promote_type;\n    };\n    template<>\n    struct promote_traits<boost::complex<boost::numeric::interval<float> >, boost::numeric::interval<float> > {\n        typedef boost::complex<boost::numeric::interval<float> > promote_type;\n    };\n    template<>\n    struct promote_traits<boost::numeric::interval<float>, boost::complex<boost::numeric::interval<double> > > {\n        typedef boost::complex<boost::numeric::interval<double> > promote_type;\n    };\n    template<>\n    struct promote_traits<boost::complex<boost::numeric::interval<double> >, boost::numeric::interval<float> > {\n        typedef boost::complex<boost::numeric::interval<double> > promote_type;\n    };\n#ifndef BOOST_UBLAS_NO_LONG_DOUBLE\n    template<>\n    struct promote_traits<boost::numeric::interval<float>, boost::complex<boost::numeric::interval<long double> > > {\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\n    };\n    template<>\n    struct promote_traits<boost::complex<boost::numeric::interval<long double> >, boost::numeric::interval<float> > {\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\n    };\n#endif\n\n    template<>\n    struct promote_traits<boost::numeric::interval<double>, boost::complex<boost::numeric::interval<float> > > {\n        // Here we'd better go the conservative way.\n        // typedef boost::complex<boost::numeric::interval<float> > promote_type;\n        typedef boost::complex<boost::numeric::interval<double> > promote_type;\n    };\n    template<>\n    struct promote_traits<boost::complex<boost::numeric::interval<float> >, boost::numeric::interval<double> > {\n        // Here we'd better go the conservative way.\n        // typedef boost::complex<boost::numeric::interval<float> > promote_type;\n        typedef boost::complex<boost::numeric::interval<double> > promote_type;\n    };\n    template<>\n    struct promote_traits<boost::numeric::interval<double>, boost::complex<boost::numeric::interval<double> > > {\n        typedef boost::complex<boost::numeric::interval<double> > promote_type;\n    };\n    template<>\n    struct promote_traits<boost::complex<boost::numeric::interval<double> >, boost::numeric::interval<double> > {\n        typedef boost::complex<boost::numeric::interval<double> > promote_type;\n    };\n#ifndef BOOST_UBLAS_NO_LONG_DOUBLE\n    template<>\n    struct promote_traits<boost::numeric::interval<double>, boost::complex<boost::numeric::interval<long double> > > {\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\n    };\n    template<>\n    struct promote_traits<boost::complex<boost::numeric::interval<long double> >, boost::numeric::interval<double> > {\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\n    };\n#endif\n\n#ifndef BOOST_UBLAS_NO_LONG_DOUBLE\n    template<>\n    struct promote_traits<boost::numeric::interval<long double>, boost::complex<boost::numeric::interval<float> > > {\n        // Here we'd better go the conservative way.\n        // typedef boost::complex<boost::numeric::interval<float> > promote_type;\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\n    };\n    template<>\n    struct promote_traits<boost::complex<boost::numeric::interval<float> >, boost::numeric::interval<long double> > {\n        // Here we'd better go the conservative way.\n        // typedef boost::complex<boost::numeric::interval<float> > promote_type;\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\n    };\n    template<>\n    struct promote_traits<boost::numeric::interval<long double>, boost::complex<boost::numeric::interval<double> > > {\n        // Here we'd better go the conservative way.\n        // typedef boost::complex<boost::numeric::interval<double> > promote_type;\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\n    };\n    template<>\n    struct promote_traits<boost::complex<boost::numeric::interval<double> >, boost::numeric::interval<long double> > {\n        // Here we'd better go the conservative way.\n        // typedef boost::complex<boost::numeric::interval<double> > promote_type;\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\n    };\n    template<>\n    struct promote_traits<boost::numeric::interval<long double>, boost::complex<boost::numeric::interval<long double> > > {\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\n    };\n    template<>\n    struct promote_traits<boost::complex<boost::numeric::interval<long double> >, boost::numeric::interval<long double> > {\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\n    };\n#endif\n\n    template<>\n    struct promote_traits<boost::complex<boost::numeric::interval<float> >, boost::complex<boost::numeric::interval<double> > > {\n        typedef boost::complex<boost::numeric::interval<double> > promote_type;\n    };\n    template<>\n    struct promote_traits<boost::complex<boost::numeric::interval<double> >, boost::complex<boost::numeric::interval<float> > > {\n        typedef boost::complex<boost::numeric::interval<double> > promote_type;\n    };\n#ifndef BOOST_UBLAS_NO_LONG_DOUBLE\n    template<>\n    struct promote_traits<boost::complex<boost::numeric::interval<float> >, boost::complex<boost::numeric::interval<long double> > > {\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\n    };\n    template<>\n    struct promote_traits<boost::complex<boost::numeric::interval<long double> >, boost::complex<boost::numeric::interval<float> > > {\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\n    };\n    template<>\n    struct promote_traits<boost::complex<boost::numeric::interval<double> >, boost::complex<boost::numeric::interval<long double> > > {\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\n    };\n    template<>\n    struct promote_traits<boost::complex<boost::numeric::interval<long double> >, boost::complex<boost::numeric::interval<double> > > {\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\n    };\n#endif\n#endif\n#endif\n#endif\n\n    struct unknown_storage_tag {};\n    struct sparse_proxy_tag: public unknown_storage_tag {};\n    struct sparse_tag: public sparse_proxy_tag {};\n    struct packed_proxy_tag: public sparse_proxy_tag {};\n    struct packed_tag: public packed_proxy_tag {};\n    struct dense_proxy_tag: public packed_proxy_tag {};\n    struct dense_tag: public dense_proxy_tag {};\n\n    template<class S1, class S2>\n    struct storage_restrict_traits {\n        typedef S1 storage_category;\n    };\n\n    template<>\n    struct storage_restrict_traits<sparse_tag, dense_proxy_tag> {\n        typedef sparse_proxy_tag storage_category;\n    };\n    template<>\n    struct storage_restrict_traits<sparse_tag, packed_proxy_tag> {\n        typedef sparse_proxy_tag storage_category;\n    };\n    template<>\n    struct storage_restrict_traits<sparse_tag, sparse_proxy_tag> {\n        typedef sparse_proxy_tag storage_category;\n    };\n\n    template<>\n    struct storage_restrict_traits<packed_tag, dense_proxy_tag> {\n        typedef packed_proxy_tag storage_category;\n    };\n    template<>\n    struct storage_restrict_traits<packed_tag, packed_proxy_tag> {\n        typedef packed_proxy_tag storage_category;\n    };\n    template<>\n    struct storage_restrict_traits<packed_tag, sparse_proxy_tag> {\n        typedef sparse_proxy_tag storage_category;\n    };\n\n    template<>\n    struct storage_restrict_traits<packed_proxy_tag, sparse_proxy_tag> {\n        typedef sparse_proxy_tag storage_category;\n    };\n\n    template<>\n    struct storage_restrict_traits<dense_tag, dense_proxy_tag> {\n        typedef dense_proxy_tag storage_category;\n    };\n    template<>\n    struct storage_restrict_traits<dense_tag, packed_proxy_tag> {\n        typedef packed_proxy_tag storage_category;\n    };\n    template<>\n    struct storage_restrict_traits<dense_tag, sparse_proxy_tag> {\n        typedef sparse_proxy_tag storage_category;\n    };\n\n    template<>\n    struct storage_restrict_traits<dense_proxy_tag, packed_proxy_tag> {\n        typedef packed_proxy_tag storage_category;\n    };\n    template<>\n    struct storage_restrict_traits<dense_proxy_tag, sparse_proxy_tag> {\n        typedef sparse_proxy_tag storage_category;\n    };\n\n    struct sparse_bidirectional_iterator_tag : public std::bidirectional_iterator_tag {};\n    struct packed_random_access_iterator_tag : public std::random_access_iterator_tag {};\n    struct dense_random_access_iterator_tag : public packed_random_access_iterator_tag {};\n\n    // Thanks to Kresimir Fresl for convincing Comeau with iterator_base_traits ;-)\n    template<class IC>\n    struct iterator_base_traits {};\n\n    template<>\n    struct iterator_base_traits<std::forward_iterator_tag> {\n        template<class I, class T>\n        struct iterator_base {\n            typedef forward_iterator_base<std::forward_iterator_tag, I, T> type;\n        };\n    };\n\n    template<>\n    struct iterator_base_traits<std::bidirectional_iterator_tag> {\n        template<class I, class T>\n        struct iterator_base {\n            typedef bidirectional_iterator_base<std::bidirectional_iterator_tag, I, T> type;\n        };\n    };\n    template<>\n    struct iterator_base_traits<sparse_bidirectional_iterator_tag> {\n        template<class I, class T>\n        struct iterator_base {\n            typedef bidirectional_iterator_base<sparse_bidirectional_iterator_tag, I, T> type;\n        };\n    };\n\n    template<>\n    struct iterator_base_traits<std::random_access_iterator_tag> {\n        template<class I, class T>\n        struct iterator_base {\n            typedef random_access_iterator_base<std::random_access_iterator_tag, I, T> type;\n        };\n    };\n    template<>\n    struct iterator_base_traits<packed_random_access_iterator_tag> {\n        template<class I, class T>\n        struct iterator_base {\n            typedef random_access_iterator_base<packed_random_access_iterator_tag, I, T> type;\n        };\n    };\n    template<>\n    struct iterator_base_traits<dense_random_access_iterator_tag> {\n        template<class I, class T>\n        struct iterator_base {\n            typedef random_access_iterator_base<dense_random_access_iterator_tag, I, T> type;\n        };\n    };\n\n    template<class I1, class I2>\n    struct iterator_restrict_traits {\n        typedef I1 iterator_category;\n    };\n\n    template<>\n    struct iterator_restrict_traits<packed_random_access_iterator_tag, sparse_bidirectional_iterator_tag> {\n        typedef sparse_bidirectional_iterator_tag iterator_category;\n    };\n    template<>\n    struct iterator_restrict_traits<sparse_bidirectional_iterator_tag, packed_random_access_iterator_tag> {\n        typedef sparse_bidirectional_iterator_tag iterator_category;\n    };\n\n    template<>\n    struct iterator_restrict_traits<dense_random_access_iterator_tag, sparse_bidirectional_iterator_tag> {\n        typedef sparse_bidirectional_iterator_tag iterator_category;\n    };\n    template<>\n    struct iterator_restrict_traits<sparse_bidirectional_iterator_tag, dense_random_access_iterator_tag> {\n        typedef sparse_bidirectional_iterator_tag iterator_category;\n    };\n\n    template<>\n    struct iterator_restrict_traits<dense_random_access_iterator_tag, packed_random_access_iterator_tag> {\n        typedef packed_random_access_iterator_tag iterator_category;\n    };\n    template<>\n    struct iterator_restrict_traits<packed_random_access_iterator_tag, dense_random_access_iterator_tag> {\n        typedef packed_random_access_iterator_tag iterator_category;\n    };\n\n    template<class I>\n    BOOST_UBLAS_INLINE\n    void increment (I &it, const I &it_end, BOOST_UBLAS_TYPENAME I::difference_type compare, packed_random_access_iterator_tag) {\n        it += (std::min) (compare, it_end - it);\n    }\n    template<class I>\n    BOOST_UBLAS_INLINE\n    void increment (I &it, const I &/* it_end */, BOOST_UBLAS_TYPENAME I::difference_type /* compare */, sparse_bidirectional_iterator_tag) {\n        ++ it;\n    }\n    template<class I>\n    BOOST_UBLAS_INLINE\n    void increment (I &it, const I &it_end, BOOST_UBLAS_TYPENAME I::difference_type compare) {\n        increment (it, it_end, compare, BOOST_UBLAS_TYPENAME I::iterator_category ());\n    }\n\n    template<class I>\n    BOOST_UBLAS_INLINE\n    void increment (I &it, const I &it_end) {\n#if BOOST_UBLAS_TYPE_CHECK\n        I cit (it);\n        while (cit != it_end) {\n            BOOST_UBLAS_CHECK (*cit == BOOST_UBLAS_TYPENAME I::value_type (0), internal_logic ());\n            ++ cit;\n        }\n#endif\n        it = it_end;\n    }\n\n}}}\n\n#endif\n", "meta": {"hexsha": "f9cb0cea83391f26bae45645a2a5d3949313a0ae", "size": 50339, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/numeric/ublas/traits.hpp", "max_stars_repo_name": "Imperator-Knoedel/Sunset", "max_stars_repo_head_hexsha": "19c95f4844586b96341f3474b58e0dacaae485b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-05T18:36:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-05T18:36:14.000Z", "max_issues_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/numeric/ublas/traits.hpp", "max_issues_repo_name": "Imperator-Knoedel/Sunset", "max_issues_repo_head_hexsha": "19c95f4844586b96341f3474b58e0dacaae485b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/numeric/ublas/traits.hpp", "max_forks_repo_name": "Imperator-Knoedel/Sunset", "max_forks_repo_head_hexsha": "19c95f4844586b96341f3474b58e0dacaae485b9", "max_forks_repo_licenses": ["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.3610921502, "max_line_length": 141, "alphanum_fraction": 0.6232940662, "num_tokens": 10952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.296588532798547}}
{"text": "// Copyright (c) Jeremy Siek 2001\n// Copyright (c) Douglas Gregor 2004\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// NOTE: this final is generated by libs/graph/doc/biconnected_components.w\n\n#ifndef BOOST_GRAPH_BICONNECTED_COMPONENTS_HPP\n#define BOOST_GRAPH_BICONNECTED_COMPONENTS_HPP\n\n#include <stack>\n#include <vector>\n#include <algorithm> // for std::min and std::max\n#include <boost/config.hpp>\n#include <boost/limits.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/property_map.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/graph/graph_utility.hpp>\n\nnamespace boost\n{\n  namespace detail\n  {\n    template<typename ComponentMap, typename DiscoverTimeMap,\n             typename LowPointMap, typename PredecessorMap,\n             typename OutputIterator, typename Stack>\n    struct biconnected_components_visitor : public dfs_visitor<>\n    {\n      biconnected_components_visitor\n        (ComponentMap comp, std::size_t& c, DiscoverTimeMap dtm,\n         std::size_t& dfs_time, LowPointMap lowpt, PredecessorMap pred,\n         OutputIterator out, Stack& S)\n          : comp(comp), c(c), dtm(dtm), dfs_time(dfs_time), lowpt(lowpt),\n            pred(pred), out(out), S(S) { }\n\n      template <typename Vertex, typename Graph>\n      void start_vertex(const Vertex& u, Graph&)\n      {\n        put(pred, u, u);\n      }\n\n      template <typename Vertex, typename Graph>\n      void discover_vertex(const Vertex& u, Graph&)\n      {\n        put(dtm, u, ++dfs_time);\n        put(lowpt, u, get(dtm, u));\n      }\n\n      template <typename Edge, typename Graph>\n      void tree_edge(const Edge& e, Graph& g)\n      {\n        S.push(e);\n        put(pred, target(e, g), source(e, g));\n      }\n\n      template <typename Edge, typename Graph>\n      void back_edge(const Edge& e, Graph& g)\n      {\n        BOOST_USING_STD_MIN();\n\n        if ( target(e, g) != get(pred, source(e, g)) ) {\n          S.push(e);\n          put(lowpt, source(e, g),\n              min BOOST_PREVENT_MACRO_SUBSTITUTION(get(lowpt, source(e, g)),\n                                                   get(dtm, target(e, g))));\n        }\n      }\n\n      template <typename Vertex, typename Graph>\n      void finish_vertex(const Vertex& u, Graph& g)\n      {\n        BOOST_USING_STD_MIN();\n        Vertex parent = get(pred, u);\n        bool is_art_point = false;\n        if ( get(dtm, parent) > get(dtm, u) ) {\n          parent = get(pred, parent);\n          is_art_point = true;\n        }\n\n        if ( parent == u ) { // at top\n          if ( get(dtm, u) + 1 == get(dtm, get(pred, u)) )\n            is_art_point = false;\n        } else {\n          put(lowpt, parent,\n              min BOOST_PREVENT_MACRO_SUBSTITUTION(get(lowpt, parent),\n                                                   get(lowpt, u)));\n\n          if (get(lowpt, u) >= get(dtm, parent)) {\n            if ( get(dtm, parent) > get(dtm, get(pred, parent)) ) {\n              put(pred, u, get(pred, parent));\n              put(pred, parent, u);\n            }\n\n            while ( get(dtm, source(S.top(), g)) >= get(dtm, u) ) {\n              put(comp, S.top(), c);\n              S.pop();\n            }\n            put(comp, S.top(), c);\n              S.pop();\n            ++c;\n            if ( S.empty() ) {\n              put(pred, u, parent);\n              put(pred, parent, u);\n            }\n          }\n        }\n        if ( is_art_point )\n          *out++ = u;\n      }\n\n      ComponentMap comp;\n      std::size_t& c;\n      DiscoverTimeMap dtm;\n      std::size_t& dfs_time;\n      LowPointMap lowpt;\n      PredecessorMap pred;\n      OutputIterator out;\n      Stack& S;\n    };\n  } // namespace detail\n\n  template<typename Graph, typename ComponentMap, typename OutputIterator,\n           typename DiscoverTimeMap, typename LowPointMap,\n           typename PredecessorMap, typename VertexIndexMap>\n  std::pair<std::size_t, OutputIterator>\n  biconnected_components(const Graph & g, ComponentMap comp,\n                         OutputIterator out, DiscoverTimeMap discover_time,\n                         LowPointMap lowpt, PredecessorMap pred,\n                         VertexIndexMap index_map)\n  {\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\n    typedef typename graph_traits<Graph>::edge_descriptor edge_t;\n    function_requires<VertexListGraphConcept<Graph> >();\n    function_requires<IncidenceGraphConcept<Graph> >();\n    function_requires<WritablePropertyMapConcept<ComponentMap, edge_t> >();\n    function_requires<ReadWritePropertyMapConcept<DiscoverTimeMap,\n                                                  vertex_t> >();\n    function_requires<ReadWritePropertyMapConcept<LowPointMap, vertex_t > >();\n    function_requires<ReadWritePropertyMapConcept<PredecessorMap,\n                                                  vertex_t> >();\n\n    std::size_t num_components = 0;\n    std::size_t dfs_time = 0;\n    std::stack < edge_t > S;\n\n    detail::biconnected_components_visitor<ComponentMap, DiscoverTimeMap,\n        LowPointMap, PredecessorMap, OutputIterator, std::stack<edge_t> >\n      vis(comp, num_components, discover_time, dfs_time, lowpt, pred, out, S);\n\n    depth_first_search(g, visitor(vis).vertex_index_map(index_map));\n\n    return std::pair<std::size_t, OutputIterator>(num_components, vis.out);\n  }\n\n  template<typename Graph, typename ComponentMap, typename OutputIterator,\n           typename DiscoverTimeMap, typename LowPointMap, \n           typename VertexIndexMap>\n  std::pair<std::size_t, OutputIterator>\n  biconnected_components(const Graph & g, ComponentMap comp,\n                         OutputIterator out, DiscoverTimeMap discover_time,\n                         LowPointMap lowpt, VertexIndexMap index_map)\n  {\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\n    std::vector<vertex_t> pred(num_vertices(g));\n    vertex_t vert = graph_traits<Graph>::null_vertex();\n    return biconnected_components\n             (g, comp, out, discover_time, lowpt,\n              make_iterator_property_map(pred.begin(), index_map, vert),\n              index_map);\n  }\n\n  template<typename Graph, typename ComponentMap, typename OutputIterator,\n           typename VertexIndexMap>\n  std::pair<std::size_t, OutputIterator>\n  biconnected_components(const Graph& g, ComponentMap comp, OutputIterator out,\n                         VertexIndexMap index_map)\n  {\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\n    typedef typename graph_traits<Graph>::vertices_size_type\n      vertices_size_type;\n\n    std::vector<vertices_size_type> discover_time(num_vertices(g));\n    std::vector<vertices_size_type> lowpt(num_vertices(g));\n\n    vertices_size_type vst(0);\n\n    return biconnected_components\n             (g, comp, out,\n              make_iterator_property_map(discover_time.begin(), index_map, vst),\n              make_iterator_property_map(lowpt.begin(), index_map, vst),\n              index_map);\n  }\n\n  template < typename Graph, typename ComponentMap, typename OutputIterator>\n  std::pair<std::size_t, OutputIterator>\n  biconnected_components(const Graph& g, ComponentMap comp, OutputIterator out)\n  {\n    return biconnected_components(g, comp, out, get(vertex_index, g));\n  }\n\n  namespace graph_detail {\n    struct dummy_output_iterator\n    {\n      typedef std::output_iterator_tag iterator_category;\n      typedef void value_type;\n      typedef void pointer;\n      typedef void difference_type;\n\n      struct reference {\n        template<typename T>\n        reference& operator=(const T&) { return *this; }\n      };\n\n      reference operator*() const { return reference(); }\n      dummy_output_iterator& operator++() { return *this; }\n      dummy_output_iterator operator++(int) { return *this; }\n    };\n  } // end namespace graph_detail\n\n  template <typename Graph, typename ComponentMap>\n  std::size_t\n  biconnected_components(const Graph& g, ComponentMap comp)\n  {\n    return biconnected_components(g, comp,\n                                  graph_detail::dummy_output_iterator()).first;\n  }\n\n  template<typename Graph, typename OutputIterator, typename VertexIndexMap>\n  OutputIterator\n  articulation_points(const Graph& g, OutputIterator out, \n                      VertexIndexMap index_map)\n  {\n    return biconnected_components(g, dummy_property_map(), out, \n                                  index_map).second;\n  }\n\n  template<typename Graph, typename OutputIterator>\n  OutputIterator\n  articulation_points(const Graph& g, OutputIterator out)\n  {\n    return biconnected_components(g, dummy_property_map(), out, \n                                  get(vertex_index, g)).second;\n  }\n\n}                               // namespace boost\n\n#endif  /* BOOST_GRAPH_BICONNECTED_COMPONENTS_HPP */\n", "meta": {"hexsha": "6baf586ce4da4f0e3ea56e660d220a8e048579dd", "size": 8880, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "applications/physbam/physbam-lib/External_Libraries/Archives/boost/boost/graph/biconnected_components.hpp", "max_stars_repo_name": "schinmayee/nimbus", "max_stars_repo_head_hexsha": "170cd15e24a7a88243a6ea80aabadc0fc0e6e177", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2017-07-03T19:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T02:53:56.000Z", "max_issues_repo_path": "applications/physbam/physbam-lib/External_Libraries/Archives/boost/boost/graph/biconnected_components.hpp", "max_issues_repo_name": "schinmayee/nimbus", "max_issues_repo_head_hexsha": "170cd15e24a7a88243a6ea80aabadc0fc0e6e177", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/physbam/physbam-lib/External_Libraries/Archives/boost/boost/graph/biconnected_components.hpp", "max_forks_repo_name": "schinmayee/nimbus", "max_forks_repo_head_hexsha": "170cd15e24a7a88243a6ea80aabadc0fc0e6e177", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-09-17T02:05:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-31T00:12:01.000Z", "avg_line_length": 35.2380952381, "max_line_length": 80, "alphanum_fraction": 0.6265765766, "num_tokens": 2006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.296588532798547}}
{"text": "/* FILE: common.cc\n *\n * Common code for doubledouble.cc and alt_doubledouble.cc.\n *\n * NOTICE: Please see the file ../../LICENSE\n *\n */\n\n#include <assert.h>\n#include \"xpcommon.h\"\n\n#if XP_USE_FLOAT_TYPE == XP_MPFR_TYPE\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/math/special_functions/sign.hpp>\nusing boost::math::isfinite;\nusing boost::math::signbit;\n#endif\n\n/* End includes */\n\n////////////////////////////////////////////////////////////////////////\n/// Start value safe block (associative floating point optimization\n/// disallowed).\n////////////////////////////////////////////////////////////////////////\n\n////////////////////////////////////////////////////////////////////////\n// Extended value support (infinities, NaNs):\n//\n// The are a host of various isnan, isinf, isfinite, which are\n// non-standard and broken in various ingenious ways on different\n// compilers with different compiler options.  But mostly what is\n// needed in this source file is a check on whether or not a given\n// value is finite.  The following test appears pretty robust:\n#if XP_USE_FLOAT_TYPE == XP_MPFR_TYPE\n// MPFR type doesn't support volatile qualifier, so\n// use standard C++11 library routines\nOC_BOOL Xp_IsFinite(XP_DDFLOAT_TYPE tx)\n{ return isfinite(tx); }\nOC_BOOL Xp_IsPosInf(XP_DDFLOAT_TYPE tx)\n{ return (tx == XP_INFINITY); }\nOC_BOOL Xp_IsNegInf(XP_DDFLOAT_TYPE tx)\n{ return (tx == -XP_INFINITY); }\n\n#else // !XP_USE_FLOAT_TYPE == XP_MPFR_TYPE\n\nOC_BOOL Xp_IsFinite(XP_DDFLOAT_TYPE tx)\n{\n  volatile XP_DDFLOAT_TYPE x = tx;\n  return (-XP_DDFLOAT_MAX<=x && x<=XP_DDFLOAT_MAX);\n}\nOC_BOOL Xp_IsPosInf(XP_DDFLOAT_TYPE tx)\n{ // Depending on compiler flags, differentiating Infs from NaNs is\n  // difficult.  The following is a best try:\n  volatile XP_DDFLOAT_TYPE x = tx;\n  if(x == XP_INFINITY && !(x == -XP_INFINITY)) return 1;\n  return 0;\n  /// A more robust though probably slower alternative would be\n  /// return (memcmp(&x,&XP_INFINITY,sizeof(x))==0);\n}\nOC_BOOL Xp_IsNegInf(XP_DDFLOAT_TYPE tx)\n{ // Depending on compiler flags, differentiating Infs from NaNs is\n  // difficult.  The following is a best try:\n  volatile XP_DDFLOAT_TYPE x = tx;\n  if(x == -XP_INFINITY && !(x == XP_INFINITY)) return 1;\n  return 0;\n  /// A more robust though probably slower alternative would be\n  ///    XP_DDFLOAT_TYPE chk = -XP_INFINITY;\n  ///    return (memcmp(&x,&chk,sizeof(x))==0);\n}\n#endif // XP_USE_FLOAT_TYPE == XP_MPFR_TYPE\n\nOC_BOOL Xp_IsNaN(XP_DDFLOAT_TYPE x)\n{\n  if(Xp_IsFinite(x) || Xp_IsPosInf(x) || Xp_IsNegInf(x)) {\n    return 0;\n  }\n  return 1;\n}\n\n// Some compilers (e.g. g++ 5.3.1) will take code like this\n//\n//    if(x==0.0) {\n//       signbit = Xp_SignBit(x)\n//    }\n//\n// and replace it with\n//\n//    if(x==0.0) {\n//       signbit = Xp_SignBit(0.0)\n//    }\n//\n// which is a broken optimization if one wants to distinguish between x\n// being +0.0 and -0.0.  A workaround is to use a non-inlined subroutine\n// call to make the magnitude check, e.g.\n//\n//    if(Xp_IsZero(x)) {\n//       signbit = Xp_SignBit(0.0)\n//    }\n//\n// (Here if(fabs(x)==0.0) might also work, depending on how much the\n// compiler knows about fabs().)  The Xp_AreEqual routine handles\n// similar issues for comparisons between two values.\n//\n// These routines also take care of NaN handling problems.\nOC_BOOL Xp_IsZero(XP_DDFLOAT_TYPE x)\n{\n  return (Xp_IsFinite(x) && 0.0 == x);\n}\nOC_BOOL Xp_AreEqual(XP_DDFLOAT_TYPE x,XP_DDFLOAT_TYPE y)\n{\n  if(Xp_IsNaN(x) || Xp_IsNaN(y)) return 0;\n  return (x == y);\n}\n\n// The Xp_SignBit routines return 1 if x is negative, 0 if positive\n// (same as std::signbit spec).\n#if XP_USE_FLOAT_TYPE == XP_MPFR_TYPE\nOC_BOOL Xp_SignBit(XP_DDFLOAT_TYPE x)\n{ return boost::math::signbit(x); }\n#else // !XP_USE_FLOAT_TYPE == XP_MPFR_TYPE\nOC_BOOL Xp_SignBit(OC_REAL4 x)\n{\n  union BITS {\n    OC_REAL4 f;\n    OC_UINT4 u;\n  };\n  BITS a = {1.0};\n  BITS b = {-1.0};\n  BITS c = { x };\n  if((a.u ^ b.u) & c.u) return 1;\n  return 0;\n}\nOC_BOOL Xp_SignBit(OC_REAL8 x)\n{\n  union BITS {\n    OC_REAL8 f;\n    OC_UINT8 u;\n  };\n  BITS a = {1.0};\n  BITS b = {-1.0};\n  BITS c = { x };\n  if((a.u ^ b.u) & c.u) return 1;\n  return 0;\n}\nOC_BOOL Xp_SignBit(long double x)\n{ // This code could be sped up considerably, in particular\n  // by determining a priori the one bit where 1.0 and -1.0\n  // differ, and then checking just that one bit.\n  assert(sizeof(long double) % sizeof(unsigned int) == 0);\n  static const long double af =  1.0;\n  static const long double bf = -1.0;\n  unsigned int const * a = reinterpret_cast<unsigned int const *>(&af);\n  unsigned int const * b = reinterpret_cast<unsigned int const *>(&bf);\n  unsigned int const * c = reinterpret_cast<unsigned int const *>(&x);\n  for(size_t i=0; i*sizeof(unsigned int)<sizeof(long double); ++i) {\n    if((a[i] ^ b[i]) & c[i]) return 1;\n  }\n  return 0;\n}\n#endif // XP_USE_FLOAT_TYPE == XP_MPFR_TYPE\n\n\n////////////////////////////////////////////////////////////////////////\n/// End value safe block\n////////////////////////////////////////////////////////////////////////\n\nint HexFloatWidth()\n{\n  return (XP_DDFLOAT_MANTISSA_PRECISION+6)/4\n    + 6 + (XP_DDFLOAT_HUGE_EXP<3000 ? 4 : 5);\n}\n\nstd::string HexFloatFormat(XP_DDFLOAT_TYPE value)\n{\n  char buf[256+XP_DDFLOAT_MANTISSA_PRECISION/4];\n  if(!Xp_IsFinite(value)) { // Use %g to decide how to print the value\n    snprintf(buf,sizeof(buf),\"%g\",static_cast<double>(value));\n    char* cptr=buf;\n    while(*cptr != '\\0') {\n      *cptr = static_cast<char>(tolower(*cptr));\n      ++cptr;\n    }\n    std::string str = buf;\n    if(str.find(\"inf\")== std::string::npos) {\n      str = \"NaN\";\n    } else {\n      if(str[0]=='-') {\n        str = \"-Inf\";\n      } else {\n        str = \"Inf\";\n      }\n    }\n    return str;\n  }\n\n  char* cptr = buf;\n  XP_DDFLOAT_TYPE mantissa;\n  int exp;\n  mantissa = XP_FREXP(value,&exp);\n  if(!Xp_SignBit(value)) { // Xp_SignBit detects signed zero\n    *(cptr++) = ' ';  // Leave sign space\n  } else {\n    *(cptr++) = '-';\n    mantissa *= -1;\n  }\n\n  // Write \"0x\" prefix to mantissa string, and leading \"1.\"\n  *(cptr++) = '0';  *(cptr++) = 'x';\n  if(mantissa == 0.0) {\n    *(cptr++) = '0';\n  } else {\n    *(cptr++) = '1';\n    mantissa = 2*mantissa - 1.0;\n    exp -= 1;\n  }\n  *(cptr++) = '.';\n\n  // Write mantissa as hex digits\n  for(int offset=1; offset<XP_DDFLOAT_MANTISSA_PRECISION; offset+=4) {\n    mantissa *= 16;\n    XP_DDFLOAT_TYPE fval = floor(mantissa);\n    int ival = static_cast<int>(fval); // i.e., floor(mantissa)\n    /// MPFR library has some trouble taking int() on temporary.\n    if(ival<10) *(cptr++) = static_cast<char>('0' + ival);\n    else        *(cptr++) = static_cast<char>('A' + ival - 10);\n    mantissa -= ival;\n  }\n\n  if(XP_DDFLOAT_HUGE_EXP<3000) {\n    snprintf(cptr,sizeof(buf)-(cptr-buf),\"p%+05d\",exp);\n  } else {\n    snprintf(cptr,sizeof(buf)-(cptr-buf),\"p%+06d\",exp);\n  }\n  return std::string(buf);\n}\n\nXP_DDFLOAT_TYPE ReadOneHexFloat(const char* buf,const char*& remainder)\n{\n  const int MAXSTOP = 16384; // Maximum buf size; fallback stop\n  const char* CSTOP = buf + MAXSTOP;\n  // Skip to data start; data has form 0x*, Inf, or NaN\n  const char* cptr = strpbrk(buf,\"0iInN\");\n  if(cptr == 0) { // No data\n    remainder = 0;\n    return 0.0;\n  }\n  // Check sign\n  XP_DDFLOAT_TYPE valsign = 1.0;\n  if( cptr - buf > 0 && *(cptr-1) == '-') {\n    valsign = -1.0;\n  }\n\n  // Check for special values\n  if(tolower(cptr[0])=='i' && tolower(cptr[1])=='n'\n     && tolower(cptr[2])=='f') { // Infinity\n    remainder = cptr+3;\n    return valsign*XP_INFINITY;\n  }\n  if(tolower(cptr[0])=='n' && tolower(cptr[1])=='a'\n     && tolower(cptr[2])=='n') { // NaN\n    remainder = cptr+3;\n    return XP_NAN;\n  }\n\n  // Otherwise, cptr should be pointing at a standard hexfloat.\n  // First, convert string up to \".\"  Should be at most one digit.\n  // (Moreover, that digit is suppose to be \"1\".)\n  char* endptr;\n  XP_DDFLOAT_TYPE val = XP_DDFLOAT_TYPE(strtol(cptr+2,&endptr,16));\n  if(*endptr != '.') {\n    std::string msg = \"Bad input to ReadOneHexFloat: \" + std::string(buf);\n    throw msg;\n  }\n  cptr = endptr+1;\n  XP_DDFLOAT_TYPE scale = 1.0/16.0;\n  while(*cptr != 'p' && *cptr != '\\0' && cptr != CSTOP) {\n    int ival = *cptr - '0';\n    if(ival>9) {\n      ival -= ('A' - '0');\n      if(ival>5) ival -= ('a'-'A');\n      ival += 10;\n    }\n    val += XP_DDFLOAT_TYPE(ival)*scale;\n    scale *= 1.0/16.0;\n    // One alternative is to parse from back to front using a Horner\n    // type algorithm to scale and sum values.\n    ++cptr;\n  }\n  if(*cptr == 'p' || *cptr == 'P') {\n    // Read exponent\n    int iexp = strtol(cptr+1,&endptr,10);\n    // Many implementations of ldexp misbehave in underflow\n    // situations, by either flushing to zero or not rounding\n    // properly.  This is not a critical path, so just brute-force it:\n    if(iexp>0) {\n      for(int i=0;i<iexp;++i) val *= 2;\n    } else if(iexp<0) {\n      for(int i=0;i>iexp;--i) val *= 0.5;\n    }\n    cptr = endptr;\n  }\n\n  remainder = cptr;\n  return valsign*val;\n}\n\n\nint HexBinaryFloatWidth()\n{\n  return (XP_DDFLOAT_MANTISSA_PRECISION+3)/4\n    + 6 + (XP_DDFLOAT_HUGE_EXP<3000 ? 3 : 4);\n}\n\nstd::string HexBinaryFloatFormat(XP_DDFLOAT_TYPE value)\n{\n  char buf[256+XP_DDFLOAT_MANTISSA_PRECISION/4];\n\n  if(!Xp_IsFinite(value)) { // Use %g to decide how to print the value\n    snprintf(buf,sizeof(buf),\"%g\",static_cast<double>(value));\n    char* cptr=buf;\n    while(*cptr != '\\0') {\n      *cptr = static_cast<char>(tolower(*cptr));\n      ++cptr;\n    }\n    std::string str = buf;\n    if(str.find(\"inf\")== std::string::npos) {\n      str = \"NaN\";\n    } else {\n      if(str[0]=='-') {\n        str = \"-Inf\";\n      } else {\n        str = \"Inf\";\n      }\n    }\n    return str;\n  }\n\n  char* cptr = buf;\n  XP_DDFLOAT_TYPE mantissa;\n  int exp;\n  mantissa = XP_FREXP(value,&exp);\n  if(!Xp_SignBit(value)) { // Xp_SignBit detects signed zero\n    *(cptr++) = ' ';  // Leave sign space\n  } else {\n    *(cptr++) = '-';\n    mantissa *= -1;\n  }\n\n  // Write \"0x\" prefix to mantissa string\n  *(cptr++) = '0';\n  *(cptr++) = 'x';\n\n  // Lead shift; if precision is not divisible by 4, then write\n  // \"left-over\" bits (which won't fill a full hex digit) first.\n#if XP_DDFLOAT_MANTISSA_PRECISION%4 != 0\n    mantissa *= pow(XP_DDFLOAT_TYPE(2.0),XP_DDFLOAT_MANTISSA_PRECISION%4);\n    exp -= XP_DDFLOAT_MANTISSA_PRECISION%4;\n#else\n    mantissa *= 16;\n    exp -= 4;\n#endif\n\n  // Write mantissa as hex digits\n  for(int offset=0; 4*offset<XP_DDFLOAT_MANTISSA_PRECISION; ++offset) {\n    XP_DDFLOAT_TYPE fval = floor(mantissa);\n    int ival = static_cast<int>(fval); // i.e., floor(mantissa)\n    /// MPFR library has some trouble taking int() on temporary.\n    if(ival<10) *(cptr++) = static_cast<char>('0' + ival);\n    else        *(cptr++) = static_cast<char>('A' + ival - 10);\n    mantissa -= ival;\n    mantissa *= 16;\n    exp -= 4;\n  }\n\n  exp += 4;\n  if(XP_DDFLOAT_HUGE_EXP<3000) {\n    snprintf(cptr,sizeof(buf)-(cptr-buf),\"xb%+04d\",exp);\n  } else {\n    snprintf(cptr,sizeof(buf)-(cptr-buf),\"xb%+05d\",exp);\n  }\n  return std::string(buf);\n}\n\n\nXP_DDFLOAT_TYPE ScanHexBinFloat(const char* cptr)\n{ // Support for HexHex-Float and HexBin-Float formats, which have form\n  //\n  //    smmm...mmmxseee         (HexHex-Float)\n  //    smmm...mmmxbseee        (HexBin-Float)\n  //\n  // where s is an optional mantisa sign (+ or -), mmm...mmm is an\n  // arbitrary length run of hexadecimal digits (0-9, a-f, A-F), followed\n  // by a literal 'x' (or 'X') or 'xb' (or 'XB') indicating the base of\n  // the exponent (16 or 2, respectively), followed by an optional\n  // exponent sign, and then a run of decimal digits representing the\n  // power of 16 or 2.  Examples of the HexHex-Float format:\n  //\n  //     5a0x3\n  //\n  // is the decimal number (5*16^2 + 10*16) * 16^3 = 1440 * 4096 = 5898240.\n  // and\n  //      120Fx-7\n  //\n  // is the decimal number (1*16^3 + 2*16^2 + 15) * 16^-7 = 4623/268435456\n  //                                      = 0.0000172220170497894287109375\n  //\n  // Examples of the HexBin-format:\n  //\n  //     5a0xb3\n  //\n  // is the decimal number (5*16^2 + 10*16) * 2^3 = 1440 * 8 = 11520.\n  // and\n  //      120Fxb-7\n  //\n  // is the decimal number (1*16^3 + 2*16^2 + 15) * 2^-7 = 4623/128\n  //                                                     = 36.1171875\n  //\n  // Note: C99 and C++11 specify a different hexfloat format, represented\n  // by the format specifier %a.  See the ScanC99HexFloat routine for\n  // details.\n\n  // Safer to work with unsigned chars\n  const unsigned char* ptr = (const unsigned char*)cptr;\n\n  // Skip leading junk\n  unsigned char ch;\n  while((ch=*ptr) != 0x0 && ch!='+' && ch!='-' &&\n        !(('0'<=ch && ch<='9')                                  \\\n          || ('a'<=ch && ch<='f') || ('A'<=ch && ch<='F'))) {\n    ++ptr;\n  }\n  // Set sign on mantissa\n  int sign = 1;\n  if(ch=='-') {\n    sign = -1;\n    ch = *(++ptr);\n  } else if(ch=='+') {\n    ch = *(++ptr);\n  }\n\n  // Skip leading \"0x\", if any\n  if(ch == '0') {\n    ch = *(++ptr);\n    if(ch == 'x' || ch == 'X') {\n      ch = *(++ptr);\n    }\n  }\n\n  // Read mantissa\n  XP_DDFLOAT_TYPE value = 0.0;\n  while(ch != 0x0) {\n    unsigned int digit;\n    if(ch=='-') {\n      sign = -1;\n    } else if(ch=='+') {\n      sign = 1;\n    } else {\n      if('0'<=ch && ch<='9') {\n        digit = static_cast<unsigned int>(ch - '0');\n      } else if('a'<=ch && ch<='f') {\n        digit = static_cast<unsigned int>(ch - 'a' + 10);\n      } else if('A'<=ch && ch<='F') {\n        digit = static_cast<unsigned int>(ch - 'A' + 10);\n      } else { // Bad value\n        break;\n      }\n      value = 16*value + digit;\n    }\n    ch=*(++ptr);\n  }\n\n  // Exponent\n  int exponent=0;\n  double base=16.;\n  if(ch=='x' || ch=='X') {\n    ch=*(++ptr);\n    if(ch=='b' || ch=='B') {\n      base=2.;\n      ++ptr;\n    }\n    exponent = atoi((const char*)(ptr));\n  }\n  if(base == 16) {\n    exponent *= 4;\n  }\n\n  // Put it all together.  Break exponent up as necessary to protect\n  // against under/overflow.  This code also in ScanC99HexFloat().\n  while(exponent > XP_DDFLOAT_HUGE_EXP-1) {\n    value *= pow(XP_DDFLOAT_TYPE(2),XP_DDFLOAT_TYPE(XP_DDFLOAT_HUGE_EXP-1));\n    exponent -= XP_DDFLOAT_HUGE_EXP-1;\n  }\n  while(exponent < XP_DDFLOAT_TINY_EXP+1) {\n    value *= pow(XP_DDFLOAT_TYPE(2),XP_DDFLOAT_TYPE(XP_DDFLOAT_TINY_EXP+1));\n    exponent -= XP_DDFLOAT_TINY_EXP+1;\n  }\n  value *= pow(XP_DDFLOAT_TYPE(2),XP_DDFLOAT_TYPE(exponent));\n\n  return sign*value;\n}\n\nXP_DDFLOAT_TYPE ScanC99HexFloat(const char* cptr)\n{ // The format for the C99/C++11 hexfloat format is\n  //    sOx1.mmm...mmmpseee         (hexfloat)\n  // where s is an optional mantisa sign (+ or -), 0x is a literal\n  // identifier indicating a hexadecimal value, 1. is the first part of\n  // the normalized hexadecimal floating point value. mmm...mmm is an\n  // arbitrary length run of hexadecimal digits (0-9, a-f, A-F),\n  // followed by a literal 'p' (or 'P') indicating the start of the\n  // base-2 exponent, then an optional exponent sign, and then a run of\n  // decimal digits representing the power of 2.  Examples of the C99\n  // hexfloat format:\n  //\n  //     0x1.68p13\n  //\n  // is the decimal number (1+6/16+8/16^2) * 2^13 = (360/256) * 2^13\n  // = 360 * 2^5= 11520, and\n  //\n  //    -0x1.20Fp+5\n  //\n  // is the decimal number -(1*16^3 + 2*16^2 + 15) * 2^(5-12)\n  // = -4623/128 = -36.1171875\n  //\n  // This is very similar to the HexBin format above, the difference\n  // being the location of the hex point in the mantissa---this\n  // shifts the exponent and re-jiggers the binary-to-hex grouping\n  // in the mantissa.\n\n  // Safer to work with unsigned chars\n  const unsigned char* ptr = (const unsigned char*)cptr;\n\n  // Skip leading junk\n  unsigned char ch;\n  while((ch=*ptr) != 0x0 && ch!='+' && ch!='-' &&\n        !(('0'<=ch && ch<='9')                                  \\\n          || ('a'<=ch && ch<='f') || ('A'<=ch && ch<='F'))) {\n    ++ptr;\n  }\n  // Set sign on mantissa\n  int sign = 1;\n  if(ch=='-') {\n    sign = -1;\n    ch = *(++ptr);\n  } else if(ch=='+') {\n    ch = *(++ptr);\n  }\n\n  // Skip leading \"0x\", if any\n  if(ch == '0') {\n    ch = *(++ptr);\n    if(ch == 'x' || ch == 'X') {\n      ch = *(++ptr);\n    }\n  }\n\n  // Next two characters should be \"1.\" or \"0.\", the latter only on\n  // zero input.\n  if(ch == '0') {\n    // Optimization bugs will sometimes drop sign on sign*0.0, so use\n    // copysign instead.\n#if XP_HAVE_COPYSIGN\n    return copysign(static_cast<XP_DDFLOAT_TYPE>(0.0),\n                    static_cast<XP_DDFLOAT_TYPE>(sign));\n#else\n    return sign*static_cast<XP_DDFLOAT_TYPE>(0.0);\n#endif\n  }\n  if(ch != '1' || *(++ptr) != '.') {\n    std::string errmsg\n      = \"Error in ScanC99HexFloat; Invalid C99 hexfloat string: \";\n    errmsg += cptr;\n    throw errmsg;\n  }\n\n  // Read mantissa\n  XP_DDFLOAT_TYPE value = 1.0;\n  int exponent = 0;\n  while( (ch = *(++ptr)) != 0x0) {\n    unsigned int digit;\n    if('0'<=ch && ch<='9') {\n      digit = static_cast<unsigned int>(ch - '0');\n    } else if('a'<=ch && ch<='f') {\n      digit = static_cast<unsigned int>(ch - 'a' + 10);\n    } else if('A'<=ch && ch<='F') {\n      digit = static_cast<unsigned int>(ch - 'A' + 10);\n    } else { // Bad value\n      break;\n    }\n    value = 16*value + digit;\n    exponent -= 4;\n  }\n\n  // Exponent (base is 2)\n  if(ch=='p' || ch=='P') {\n    exponent += atoi((const char*)(++ptr));\n  }\n\n  // Put it all together.  Break exponent up as necessary to protect\n  // against under/overflow.  This code also in ScanHexBinFloat().\n  while(exponent > XP_DDFLOAT_HUGE_EXP-1) {\n    value *= pow(XP_DDFLOAT_TYPE(2),XP_DDFLOAT_TYPE(XP_DDFLOAT_HUGE_EXP-1));\n    exponent -= XP_DDFLOAT_HUGE_EXP-1;\n  }\n  while(exponent < XP_DDFLOAT_TINY_EXP+1) {\n    value *= pow(XP_DDFLOAT_TYPE(2),XP_DDFLOAT_TYPE(XP_DDFLOAT_TINY_EXP+1));\n    exponent -= XP_DDFLOAT_TINY_EXP+1;\n  }\n  value *= pow(XP_DDFLOAT_TYPE(2),XP_DDFLOAT_TYPE(exponent));\n\n  return sign*value;\n}\n\nXP_DDFLOAT_TYPE ScanFloat(const char* cptr)\n{\n  // If string contains an p or P, then calls ScanC99HexFloat.\n  // If string contains an x or X, then calls ScanHexBinFloat.\n  // Otherwise uses strtold()\n  // Note: Check for 'p' first since C99HexFloat also contains\n  //       an 'x' in the '0x' prefix.\n  XP_DDFLOAT_TYPE value;\n  // First check for infinities and NaNs.\n  const char* special = strstr(cptr,\"Inf\");\n  if(special) {\n    XP_DDFLOAT_TYPE value_sign = 1;\n    if(special>cptr && *(special-1) == '-') {\n      value_sign = -1;\n    }\n    return value_sign*XP_INFINITY;\n  }\n  if(strstr(cptr,\"NaN\")) {\n    return XP_NAN;\n  }\n\n  // Else, determine string format and process accordingly.\n  if(strchr(cptr,'p') || strchr(cptr,'P')) {\n    // Assume C99 hex-float\n    value = ScanC99HexFloat(cptr);\n  } else if(strchr(cptr,'x') || strchr(cptr,'X')) {\n    // Assume hexhex-float\n    value = ScanHexBinFloat(cptr);\n  } else {\n    // Assume decimal float\n    value = static_cast<XP_DDFLOAT_TYPE>(strtold(cptr,0));\n  }\n\n  return value;\n}\n", "meta": {"hexsha": "63305016ac420b241247cac7e6595fb018d86d49", "size": 18856, "ext": "cc", "lang": "C++", "max_stars_repo_path": "oommf/pkg/xp/xpcommon.cc", "max_stars_repo_name": "fangohr/oommf", "max_stars_repo_head_hexsha": "67fa0d69eadbbb9eef320babd07910f6d7b4e089", "max_stars_repo_licenses": ["TCL"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2016-04-29T10:11:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T08:48:39.000Z", "max_issues_repo_path": "oommf/pkg/xp/xpcommon.cc", "max_issues_repo_name": "fangohr/oommf", "max_issues_repo_head_hexsha": "67fa0d69eadbbb9eef320babd07910f6d7b4e089", "max_issues_repo_licenses": ["TCL"], "max_issues_count": 29.0, "max_issues_repo_issues_event_min_datetime": "2017-11-01T20:00:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-05T12:22:50.000Z", "max_forks_repo_path": "oommf/pkg/xp/xpcommon.cc", "max_forks_repo_name": "fangohr/oommf", "max_forks_repo_head_hexsha": "67fa0d69eadbbb9eef320babd07910f6d7b4e089", "max_forks_repo_licenses": ["TCL"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-10-17T19:41:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-12T08:32:37.000Z", "avg_line_length": 29.0987654321, "max_line_length": 76, "alphanum_fraction": 0.5894675435, "num_tokens": 6062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.29658853279854697}}
{"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#include \"SiconosConfig.h\"\n#include <boost/numeric/bindings/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/bindings/trans.hpp>\n#include <boost/numeric/bindings/blas/level2.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/std/vector.hpp>\n\n// Note Franck : sounds useless. It seems it's defined in bindings\n// (to be checked, especially on windows)\n\n// #define BIND_FORTRAN_LOWERCASE_UNDERSCORE\nnamespace siconosBindings = boost::numeric::bindings;\n\n// for ublas::axpy_prod, ...\n#include <boost/numeric/ublas/operation.hpp>\n\n// for matrix stuff like value_type\n//#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n\n#include \"SiconosVector.hpp\"\n#include \"SimpleMatrix.hpp\"\n#include \"BlockMatrixIterators.hpp\"\n#include \"BlockMatrix.hpp\"\n#include \"SiconosAlgebra.hpp\"\n\nusing namespace Siconos;\n\n// ========== Products matrix - vector //\n\n// Computation of y = A*x\n//\n// Two specific functions are used to handle all the cases where x or y are blocks.\n// All of their blocks can also be blocks. Then we use:\n// - private_prod to \"slice\" A when y is block, ie according to its rows.\n// - private_addprod to \"slice\" A when x is block, and to sum over the columns of blocks to compute y = sum subA x[i].\n\n// The following function is private and used inside prod(...) public functions.\n// It is required to deal with block vectors of blocks ( of blocks ...).\n// It computes res = subA*x +res, subA being a submatrix of A (rows from startRow to startRow+sizeY and columns between startCol and startCol+sizeX).\n// If x is a block vector, it call the present function for all blocks.\nconst SiconosVector prod(const SiconosMatrix& A, const SiconosVector& x)\n{\n  // To compute y = A * x\n  assert(!(A.isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n  if (A.size(1) != x.size())\n    SiconosMatrixException::selfThrow(\"prod(matrix,vector) error: inconsistent sizes.\");\n\n  unsigned int numA = A.num();\n  unsigned int numX = x.num();\n\n  if (numA == 0) // if A is block ...\n    SiconosMatrixException::selfThrow(\"prod(matrix,vector) error: not yet implemented for block matrix.\");\n\n  if (numA == 6) // A = 0\n    return (DenseVect)(ublas::zero_vector<double>(x.size()));\n\n  else if (numA == 7) // A = Identity\n    return x;\n\n  else\n  {\n    if (numX == 1)\n    {\n      if (numA == 1)\n        return (DenseVect)(prod(*A.dense(), *x.dense()));\n      else if (numA == 2)\n        return (DenseVect)(prod(*A.triang(), *x.dense()));\n      else if (numA == 3)\n        return (DenseVect)(prod(*A.sym(), *x.dense()));\n      else if (numA == 4)\n        return (DenseVect)(prod(*A.sparse(), *x.dense()));\n      else // if(numA==5)\n        return (DenseVect)(prod(*A.banded(), *x.dense()));\n    }\n    else //if(numX == 4)\n    {\n      if (numA == 1)\n        return (DenseVect)(prod(*A.dense(), *x.sparse()));\n      else if (numA == 2)\n        return (DenseVect)(prod(*A.triang(), *x.sparse()));\n      else if (numA == 3)\n        return (DenseVect)(prod(*A.sym(), *x.sparse()));\n      else if (numA == 4)\n        return (DenseVect)(prod(*A.sparse(), *x.sparse()));\n      else // if(numA==5)\n        return (DenseVect)(prod(*A.banded(), *x.sparse()));\n    }\n  }\n}\n\n\nvoid prod(double a, const SiconosMatrix& A, const SiconosVector& x, SiconosVector& y, bool init)\n{\n  // To compute y = a*A * x in an \"optimized\" way (in comparison with y = prod(A,x) )\n  // or y += a*A*x if init = false.\n  assert(!(A.isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n  if (A.size(1) != x.size())\n    SiconosMatrixException::selfThrow(\"prod(A,x,y) error: inconsistent sizes between A and x.\");\n\n  if (A.size(0) != y.size())\n    SiconosMatrixException::selfThrow(\"prod(A,x,y) error: inconsistent sizes between A and y.\");\n\n  unsigned int numA = A.num();\n  unsigned int numX = x.num();\n  unsigned int numY = y.num();\n\n  if (numA == 0) // If A is Block\n    SiconosMatrixException::selfThrow(\"prod(A,x,y) error: not yet implemented for block matrices.\");\n\n  if (numA == 6) // A = 0\n  {\n    if (init)\n      y.zero();\n    //else nothing\n  }\n\n  else if (numA == 7) // A = identity\n  {\n    scal(a, x, y, init);\n  }\n\n  else // A is not 0 or identity\n  {\n\n    // === First case: y is not a block vector ===\n    {\n      {\n        if (init)\n        {\n          if (&x != &y) // if no common memory between x and y.\n          {\n            if (numX == 1)\n            {\n              if (numY != 1)\n                SiconosMatrixException::selfThrow(\"prod(A,x,y) error: y (output) must be a dense vector.\");\n\n              if (numA == 1)\n                noalias(*y.dense()) = a * ublas::prod(*A.dense(), *x.dense());\n              else if (numA == 2)\n                noalias(*y.dense()) = a * ublas::prod(*A.triang(), *x.dense());\n              else if (numA == 3)\n                noalias(*y.dense()) = a * ublas::prod(*A.sym(), *x.dense());\n              else if (numA == 4)\n                noalias(*y.dense()) = a * ublas::prod(*A.sparse(), *x.dense());\n              else //if(numA==5)\n                noalias(*y.dense()) = a * ublas::prod(*A.banded(), *x.dense());\n            }\n            else //if(numX == 4)\n            {\n              if (numY != 1 && numA != 4)\n                SiconosMatrixException::selfThrow(\"prod(A,x,y) error: y (output) must be a dense vector.\");\n\n              if (numA == 1)\n                noalias(*y.dense()) = a * ublas::prod(*A.dense(), *x.sparse());\n              else if (numA == 2)\n                noalias(*y.dense()) = a * ublas::prod(*A.triang(), *x.sparse());\n              else if (numA == 3)\n                noalias(*y.dense()) = a * ublas::prod(*A.sym(), *x.sparse());\n              else if (numA == 4)\n              {\n                if (numY == 1)\n                  noalias(*y.dense()) = a * ublas::prod(*A.sparse(), *x.sparse());\n                else\n                  noalias(*y.sparse()) = a * ublas::prod(*A.sparse(), *x.sparse());\n              }\n              else //if(numA==5)\n                noalias(*y.dense()) = a * ublas::prod(*A.banded(), *x.sparse());\n            }\n          }\n          else // if x and y are the same object => alias\n          {\n            if (numX == 1)\n            {\n              if (numA == 1)\n                *y.dense() = a * ublas::prod(*A.dense(), *x.dense());\n              else if (numA == 2)\n                *y.dense() = a * ublas::prod(*A.triang(), *x.dense());\n              else if (numA == 3)\n                *y.dense() = a * ublas::prod(*A.sym(), *x.dense());\n              else if (numA == 4)\n                *y.dense() = a * ublas::prod(*A.sparse(), *x.dense());\n              else //if(numA==5)\n                *y.dense() = a * ublas::prod(*A.banded(), *x.dense());\n            }\n            else //if(numX == 4)\n            {\n              if (numA == 1)\n                *y.sparse() = a * ublas::prod(*A.dense(), *x.sparse());\n              else if (numA == 2)\n                *y.sparse() = a * ublas::prod(*A.triang(), *x.sparse());\n              else if (numA == 3)\n                *y.sparse() = a * ublas::prod(*A.sym(), *x.sparse());\n              else if (numA == 4)\n                *y.sparse() = a * ublas::prod(*A.sparse(), *x.sparse());\n              else //if(numA==5)\n                *y.sparse() = a * ublas::prod(*A.banded(), *x.sparse());\n            }\n          }\n        }\n        else // += case\n        {\n          if (&x != &y) // if no common memory between x and y.\n          {\n            if (numX == 1)\n            {\n              if (numY != 1)\n                SiconosMatrixException::selfThrow(\"prod(A,x,y) error: y (output) must be a dense vector.\");\n\n              if (numA == 1)\n                noalias(*y.dense()) += a * ublas::prod(*A.dense(), *x.dense());\n              else if (numA == 2)\n                noalias(*y.dense()) += a * ublas::prod(*A.triang(), *x.dense());\n              else if (numA == 3)\n                noalias(*y.dense()) += a * ublas::prod(*A.sym(), *x.dense());\n              else if (numA == 4)\n                noalias(*y.dense()) += a * ublas::prod(*A.sparse(), *x.dense());\n              else //if(numA==5)\n                noalias(*y.dense()) += a * ublas::prod(*A.banded(), *x.dense());\n            }\n            else //if(numX == 4)\n            {\n              if (numY != 1 && numA != 4)\n                SiconosMatrixException::selfThrow(\"prod(A,x,y) error: y (output) must be a dense vector.\");\n\n              if (numA == 1)\n                noalias(*y.dense()) += a * ublas::prod(*A.dense(), *x.sparse());\n              else if (numA == 2)\n                noalias(*y.dense()) += a * ublas::prod(*A.triang(), *x.sparse());\n              else if (numA == 3)\n                noalias(*y.dense()) += a * ublas::prod(*A.sym(), *x.sparse());\n              else if (numA == 4)\n              {\n                if (numY == 1)\n                  noalias(*y.dense()) += a * ublas::prod(*A.sparse(), *x.sparse());\n                else\n                  noalias(*y.sparse()) += a * ublas::prod(*A.sparse(), *x.sparse());\n              }\n              else //if(numA==5)\n                noalias(*y.dense()) += a * ublas::prod(*A.banded(), *x.sparse());\n            }\n          }\n          else // if x and y are the same object => alias\n          {\n            if (numX == 1)\n            {\n              if (numA == 1)\n                *y.dense() += a * ublas::prod(*A.dense(), *x.dense());\n              else if (numA == 2)\n                *y.dense() += a * ublas::prod(*A.triang(), *x.dense());\n              else if (numA == 3)\n                *y.dense() += a * ublas::prod(*A.sym(), *x.dense());\n              else if (numA == 4)\n                *y.dense() += a * ublas::prod(*A.sparse(), *x.dense());\n              else //if(numA==5)\n                *y.dense() += a * ublas::prod(*A.banded(), *x.dense());\n            }\n            else //if(numX == 4)\n            {\n              if (numA == 1)\n                *y.sparse() += a * ublas::prod(*A.dense(), *x.sparse());\n              else if (numA == 2)\n                *y.sparse() += a * ublas::prod(*A.triang(), *x.sparse());\n              else if (numA == 3)\n                *y.sparse() += a * ublas::prod(*A.sym(), *x.sparse());\n              else if (numA == 4)\n                *y.sparse() += a * ublas::prod(*A.sparse(), *x.sparse());\n              else //if(numA==5)\n                *y.sparse() += a * ublas::prod(*A.banded(), *x.sparse());\n            }\n          }\n        }\n      }\n    }\n  }\n}\n\nvoid prod(const SiconosVector& x, const SiconosMatrix& A, SiconosVector& y, bool init)\n{\n  // To compute y = trans(A) * x in an \"optimized\" way, if init = true\n  // (or y = trans(A) * x + y if init = false\n  assert(!(A.isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n  if (A.size(0) != x.size())\n    SiconosMatrixException::selfThrow(\"prod(x,A,y) error: inconsistent sizes between A and x.\");\n\n  if (A.size(1) != y.size())\n    SiconosMatrixException::selfThrow(\"prod(x,A,y) error: inconsistent sizes between A and y.\");\n\n  unsigned int numA = A.num();\n  unsigned int numX = x.num();\n  unsigned int numY = y.num();\n\n  if (numA == 0) // If A is Block\n    SiconosMatrixException::selfThrow(\"prod(x,A,y) error: not yet implemented for block matrices.\");\n\n  if (numA == 6) // A = 0\n  {\n    if (init)\n      y.zero();\n    // else nothing\n  }\n\n  else if (numA == 7) // A = identity\n  {\n    if (!init)\n      y += x;\n    else\n    {\n      if (&x != &y) y = x ; // if x and y do not share memory (ie are different objects)\n      // else nothing\n    }\n  }\n\n  else // A is not 0 or identity\n  {\n    {\n      if (init)\n      {\n\n        if (&x != &y) // if no common memory between x and y.\n        {\n          if (numX == 1)\n          {\n            if (numY != 1)\n              SiconosMatrixException::selfThrow(\"prod(x,A,y) error: y (output) must be a dense vector.\");\n\n            if (numA == 1)\n              noalias(*y.dense()) = ublas::prod(trans(*A.dense()), *x.dense());\n            else if (numA == 2)\n              noalias(*y.dense()) = ublas::prod(trans(*A.triang()), *x.dense());\n            else if (numA == 3)\n              noalias(*y.dense()) = ublas::prod(trans(*A.sym()), *x.dense());\n            else if (numA == 4)\n              noalias(*y.dense()) = ublas::prod(trans(*A.sparse()), *x.dense());\n            else //if(numA==5)\n              noalias(*y.dense()) = ublas::prod(trans(*A.banded()), *x.dense());\n          }\n          else //if(numX == 4)\n          {\n            if (numY != 1 && numA != 4)\n              SiconosMatrixException::selfThrow(\"prod(x,A,y) error: y (output) must be a dense vector.\");\n\n            if (numA == 1)\n              noalias(*y.dense()) = ublas::prod(trans(*A.dense()), *x.sparse());\n            else if (numA == 2)\n              noalias(*y.dense()) = ublas::prod(trans(*A.triang()), *x.sparse());\n            else if (numA == 3)\n              noalias(*y.dense()) = ublas::prod(trans(*A.sym()), *x.sparse());\n            else if (numA == 4)\n            {\n              if (numY == 1)\n                noalias(*y.dense()) = ublas::prod(trans(*A.sparse()), *x.sparse());\n              else\n                noalias(*y.sparse()) = ublas::prod(trans(*A.sparse()), *x.sparse());\n            }\n            else //if(numA==5)\n              noalias(*y.dense()) = ublas::prod(trans(*A.banded()), *x.sparse());\n          }\n        }\n        else // if x and y are the same object => alias\n        {\n          if (numX == 1)\n          {\n            if (numA == 1)\n              *y.dense() = ublas::prod(trans(*A.dense()), *x.dense());\n            else if (numA == 2)\n              *y.dense() = ublas::prod(trans(*A.triang()), *x.dense());\n            else if (numA == 3)\n              *y.dense() = ublas::prod(trans(*A.sym()), *x.dense());\n            else if (numA == 4)\n              *y.dense() = ublas::prod(trans(*A.sparse()), *x.dense());\n            else //if(numA==5)\n              *y.dense() = ublas::prod(trans(*A.banded()), *x.dense());\n          }\n          else //if(numX == 4)\n          {\n            if (numA == 1)\n              *y.sparse() = ublas::prod(trans(*A.dense()), *x.sparse());\n            else if (numA == 2)\n              *y.sparse() = ublas::prod(trans(*A.triang()), *x.sparse());\n            else if (numA == 3)\n              *y.sparse() = ublas::prod(trans(*A.sym()), *x.sparse());\n            else if (numA == 4)\n              *y.sparse() = ublas::prod(trans(*A.sparse()), *x.sparse());\n            else //if(numA==5)\n              *y.sparse() = ublas::prod(trans(*A.banded()), *x.sparse());\n          }\n        }\n      }\n      else // += case\n      {\n\n        if (&x != &y) // if no common memory between x and y.\n        {\n          if (numX == 1)\n          {\n            if (numY != 1)\n              SiconosMatrixException::selfThrow(\"prod(x,A,y) error: y (output) must be a dense vector.\");\n\n            if (numA == 1)\n              noalias(*y.dense()) += ublas::prod(trans(*A.dense()), *x.dense());\n            else if (numA == 2)\n              noalias(*y.dense()) += ublas::prod(trans(*A.triang()), *x.dense());\n            else if (numA == 3)\n              noalias(*y.dense()) += ublas::prod(trans(*A.sym()), *x.dense());\n            else if (numA == 4)\n              noalias(*y.dense()) += ublas::prod(trans(*A.sparse()), *x.dense());\n            else //if(numA==5)\n              noalias(*y.dense()) += ublas::prod(trans(*A.banded()), *x.dense());\n          }\n          else //if(numX == 4)\n          {\n            if (numY != 1 && numA != 4)\n              SiconosMatrixException::selfThrow(\"prod(x,A,y) error: y (output) must be a dense vector.\");\n\n            if (numA == 1)\n              noalias(*y.dense()) += ublas::prod(trans(*A.dense()), *x.sparse());\n            else if (numA == 2)\n              noalias(*y.dense()) += ublas::prod(trans(*A.triang()), *x.sparse());\n            else if (numA == 3)\n              noalias(*y.dense()) += ublas::prod(trans(*A.sym()), *x.sparse());\n            else if (numA == 4)\n            {\n              if (numY == 1)\n                noalias(*y.dense()) += ublas::prod(trans(*A.sparse()), *x.sparse());\n              else\n                noalias(*y.sparse()) += ublas::prod(trans(*A.sparse()), *x.sparse());\n            }\n            else //if(numA==5)\n              noalias(*y.dense()) += ublas::prod(trans(*A.banded()), *x.sparse());\n          }\n        }\n        else // if x and y are the same object => alias\n        {\n          if (numX == 1)\n          {\n            if (numA == 1)\n              *y.dense() += ublas::prod(trans(*A.dense()), *x.dense());\n            else if (numA == 2)\n              *y.dense() += ublas::prod(trans(*A.triang()), *x.dense());\n            else if (numA == 3)\n              *y.dense() += ublas::prod(trans(*A.sym()), *x.dense());\n            else if (numA == 4)\n              *y.dense() += ublas::prod(trans(*A.sparse()), *x.dense());\n            else //if(numA==5)\n              *y.dense() += ublas::prod(trans(*A.banded()), *x.dense());\n          }\n          else //if(numX == 4)\n          {\n            if (numA == 1)\n              *y.sparse() += ublas::prod(trans(*A.dense()), *x.sparse());\n            else if (numA == 2)\n              *y.sparse() += ublas::prod(trans(*A.triang()), *x.sparse());\n            else if (numA == 3)\n              *y.sparse() += ublas::prod(trans(*A.sym()), *x.sparse());\n            else if (numA == 4)\n              *y.sparse() += ublas::prod(trans(*A.sparse()), *x.sparse());\n            else //if(numA==5)\n              *y.sparse() += ublas::prod(trans(*A.banded()), *x.sparse());\n          }\n        }\n      }\n    }\n  }\n}\n\nvoid prod(const SiconosMatrix& A, const SiconosVector& x, SiconosVector& y, bool init)\n{\n  // To compute y = A * x in an \"optimized\" way (in comparison with y = prod(A,x) )\n  // or y += A*x if init = false.\n  assert(!(A.isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n  if (A.size(1) != x.size())\n    SiconosMatrixException::selfThrow(\"prod(A,x,y) error: inconsistent sizes between A and x.\");\n\n  if (A.size(0) != y.size())\n    SiconosMatrixException::selfThrow(\"prod(A,x,y) error: inconsistent sizes between A and y.\");\n\n  unsigned int numA = A.num();\n  unsigned int numX = x.num();\n  unsigned int numY = y.num();\n\n  if (numA == 0) // If A is Block\n    SiconosMatrixException::selfThrow(\"prod(A,x,y) error: not yet implemented for block matrices.\");\n\n  if (numA == 6) // A = 0\n  {\n    if (init)\n      y.zero();\n    //else nothing\n  }\n\n  else if (numA == 7) // A = identity\n  {\n    if (!init)\n      y += x;\n    else\n    {\n      if (&x != &y) y = x ; // if x and y do not share memory (ie are different objects)\n      // else nothing\n    }\n  }\n\n  else // A is not 0 or identity\n  {\n\n    // === First case: y is not a block vector ===\n    if (init)\n    {\n      if (&x != &y) // if no common memory between x and y.\n      {\n        if (numX == 1)\n        {\n          if (numY != 1)\n            SiconosMatrixException::selfThrow(\"prod(A,x,y) error: y (output) must be a dense vector.\");\n\n          assert(y.dense() != x.dense());\n\n          if (numA == 1)\n            noalias(*y.dense()) = ublas::prod(*A.dense(), *x.dense());\n          else if (numA == 2)\n            noalias(*y.dense()) = ublas::prod(*A.triang(), *x.dense());\n          else if (numA == 3)\n            noalias(*y.dense()) = ublas::prod(*A.sym(), *x.dense());\n          else if (numA == 4)\n            noalias(*y.dense()) = ublas::prod(*A.sparse(), *x.dense());\n          else //if(numA==5)\n            noalias(*y.dense()) = ublas::prod(*A.banded(), *x.dense());\n        }\n        else //if(numX == 4)\n        {\n          if (numY != 1 && numA != 4)\n            SiconosMatrixException::selfThrow(\"prod(A,x,y) error: y (output) must be a dense vector.\");\n\n          if (numA == 1)\n            noalias(*y.dense()) = ublas::prod(*A.dense(), *x.sparse());\n          else if (numA == 2)\n            noalias(*y.dense()) = ublas::prod(*A.triang(), *x.sparse());\n          else if (numA == 3)\n            noalias(*y.dense()) = ublas::prod(*A.sym(), *x.sparse());\n          else if (numA == 4)\n          {\n            if (numY == 1)\n              noalias(*y.dense()) = ublas::prod(*A.sparse(), *x.sparse());\n            else\n              noalias(*y.sparse()) = ublas::prod(*A.sparse(), *x.sparse());\n          }\n          else //if(numA==5)\n            noalias(*y.dense()) = ublas::prod(*A.banded(), *x.sparse());\n        }\n      }\n      else // if x and y are the same object => alias\n      {\n        if (numX == 1)\n        {\n          if (numA == 1)\n            *y.dense() = ublas::prod(*A.dense(), *x.dense());\n          else if (numA == 2)\n            *y.dense() = ublas::prod(*A.triang(), *x.dense());\n          else if (numA == 3)\n            *y.dense() = ublas::prod(*A.sym(), *x.dense());\n          else if (numA == 4)\n            *y.dense() = ublas::prod(*A.sparse(), *x.dense());\n          else //if(numA==5)\n            *y.dense() = ublas::prod(*A.banded(), *x.dense());\n        }\n        else //if(numX == 4)\n        {\n          if (numA == 1)\n            *y.sparse() = ublas::prod(*A.dense(), *x.sparse());\n          else if (numA == 2)\n            *y.sparse() = ublas::prod(*A.triang(), *x.sparse());\n          else if (numA == 3)\n            *y.sparse() = ublas::prod(*A.sym(), *x.sparse());\n          else if (numA == 4)\n            *y.sparse() = ublas::prod(*A.sparse(), *x.sparse());\n          else //if(numA==5)\n            *y.sparse() = ublas::prod(*A.banded(), *x.sparse());\n        }\n      }\n    }\n    else // += case\n    {\n      if (&x != &y) // if no common memory between x and y.\n      {\n        if (numX == 1)\n        {\n          if (numY != 1)\n            SiconosMatrixException::selfThrow(\"prod(A,x,y) error: y (output) must be a dense vector.\");\n\n          if (numA == 1)\n            noalias(*y.dense()) += ublas::prod(*A.dense(), *x.dense());\n          else if (numA == 2)\n            noalias(*y.dense()) += ublas::prod(*A.triang(), *x.dense());\n          else if (numA == 3)\n            noalias(*y.dense()) += ublas::prod(*A.sym(), *x.dense());\n          else if (numA == 4)\n            noalias(*y.dense()) += ublas::prod(*A.sparse(), *x.dense());\n          else //if(numA==5)\n            noalias(*y.dense()) += ublas::prod(*A.banded(), *x.dense());\n        }\n        else //if(numX == 4)\n        {\n          if (numY != 1 && numA != 4)\n            SiconosMatrixException::selfThrow(\"prod(A,x,y) error: y (output) must be a dense vector.\");\n\n          if (numA == 1)\n            noalias(*y.dense()) += ublas::prod(*A.dense(), *x.sparse());\n          else if (numA == 2)\n            noalias(*y.dense()) += ublas::prod(*A.triang(), *x.sparse());\n          else if (numA == 3)\n            noalias(*y.dense()) += ublas::prod(*A.sym(), *x.sparse());\n          else if (numA == 4)\n          {\n            if (numY == 1)\n              noalias(*y.dense()) += ublas::prod(*A.sparse(), *x.sparse());\n            else\n              noalias(*y.sparse()) += ublas::prod(*A.sparse(), *x.sparse());\n          }\n          else //if(numA==5)\n            noalias(*y.dense()) += ublas::prod(*A.banded(), *x.sparse());\n        }\n      }\n      else // if x and y are the same object => alias\n      {\n        if (numX == 1)\n        {\n          if (numA == 1)\n            *y.dense() += ublas::prod(*A.dense(), *x.dense());\n          else if (numA == 2)\n            *y.dense() += ublas::prod(*A.triang(), *x.dense());\n          else if (numA == 3)\n            *y.dense() += ublas::prod(*A.sym(), *x.dense());\n          else if (numA == 4)\n            *y.dense() += ublas::prod(*A.sparse(), *x.dense());\n          else //if(numA==5)\n            *y.dense() += ublas::prod(*A.banded(), *x.dense());\n        }\n        else //if(numX == 4)\n        {\n          if (numA == 1)\n            *y.sparse() += ublas::prod(*A.dense(), *x.sparse());\n          else if (numA == 2)\n            *y.sparse() += ublas::prod(*A.triang(), *x.sparse());\n          else if (numA == 3)\n            *y.sparse() += ublas::prod(*A.sym(), *x.sparse());\n          else if (numA == 4)\n            *y.sparse() += ublas::prod(*A.sparse(), *x.sparse());\n          else //if(numA==5)\n            *y.sparse() += ublas::prod(*A.banded(), *x.sparse());\n        }\n      }\n    }\n  }\n}\n\n\nvoid axpy_prod(const SiconosMatrix& A, const SiconosVector& x, SiconosVector& y, bool init)\n{\n  // To compute y = A * x ( init = true) or y += A * x (init = false) using ublas::axpy_prod\n  assert(!(A.isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n  if (A.size(1) != x.size())\n    SiconosMatrixException::selfThrow(\"prod(A,x,y) error: inconsistent sizes between A and x.\");\n\n  if (A.size(0) != y.size())\n    SiconosMatrixException::selfThrow(\"prod(A,x,y) error: inconsistent sizes between A and y.\");\n\n  unsigned int numA = A.num();\n  unsigned int numX = x.num();\n  unsigned int numY = y.num();\n\n  if (numA == 0) // If A is Block\n    SiconosMatrixException::selfThrow(\"axpy_prod(A,x,y) error: not yet implemented for block matrices.\");\n\n  if (numA == 6) // A = 0\n  {\n    if (init) y.zero(); // else nothing ...\n  }\n\n  else if (numA == 7) // A = identity\n  {\n    if (!init) y += x;\n    else\n    {\n      if (&x != &y)\n        y = x ; // if x and y do not share memory (ie are different objects)\n    }\n    // else nothing\n  }\n\n  else // A is not 0 or identity\n  {\n    {\n      {\n        if (&x != &y) // if no common memory between x and y.\n        {\n          if (numX == 1)\n          {\n            if (numY != 1)\n              SiconosMatrixException::selfThrow(\"prod(A,x,y) error: y (output) must be a dense vector.\");\n\n            if (numA == 1)\n              ublas::axpy_prod(*A.dense(), *x.dense(), *y.dense(), init);\n            else if (numA == 2)\n              ublas::axpy_prod(*A.triang(), *x.dense(), *y.dense(), init);\n            else if (numA == 3)\n              ublas::axpy_prod(*A.sym(), *x.dense(), *y.dense(), init);\n            else if (numA == 4)\n              ublas::axpy_prod(*A.sparse(), *x.dense(), *y.dense(), init);\n            else //if(numA==5)\n              ublas::axpy_prod(*A.banded(), *x.dense(), *y.dense(), init);\n          }\n          else //if(numX == 4)\n          {\n            if (numY != 1 && numA != 4)\n              SiconosMatrixException::selfThrow(\"axpy_prod(A,x,y) error: y (output) must be a dense vector.\");\n\n            if (numA == 1)\n              ublas::axpy_prod(*A.dense(), *x.sparse(), *y.dense(), init);\n            else if (numA == 2)\n              ublas::axpy_prod(*A.triang(), *x.sparse(), *y.dense(), init);\n            else if (numA == 3)\n              ublas::axpy_prod(*A.sym(), *x.sparse(), *y.dense(), init);\n            else if (numA == 4)\n            {\n              if (numY == 1)\n                ublas::axpy_prod(*A.sparse(), *x.sparse(), *y.dense(), init);\n              else\n                ublas::axpy_prod(*A.sparse(), *x.sparse(), *y.sparse(), init);\n            }\n            else //if(numA==5)\n              ublas::axpy_prod(*A.banded(), *x.sparse(), *y.dense(), init);\n          }\n        }\n        else // if x and y are the same object => alias\n        {\n          if (numX == 1)\n          {\n            if (numA == 1)\n              ublas::axpy_prod(*A.dense(), *x.dense(), *x.dense(), init);\n            else if (numA == 2)\n              ublas::axpy_prod(*A.triang(), *x.dense(), *x.dense(), init);\n            else if (numA == 3)\n              ublas::axpy_prod(*A.sym(), *x.dense(), *x.dense(), init);\n            else if (numA == 4)\n              ublas::axpy_prod(*A.sparse(), *x.dense(), *x.dense(), init);\n            else //if(numA==5)\n              ublas::axpy_prod(*A.banded(), *x.dense(), *x.dense(), init);\n          }\n          else //if(numX == 4)\n          {\n            if (numA == 1)\n              ublas::axpy_prod(*A.dense(), *x.sparse(), *x.sparse(), init);\n            else if (numA == 2)\n              ublas::axpy_prod(*A.triang(), *x.sparse(), *x.sparse(), init);\n            else if (numA == 3)\n              ublas::axpy_prod(*A.sym(), *x.sparse(), *x.sparse(), init);\n            else if (numA == 4)\n              ublas::axpy_prod(*A.sparse(), *x.sparse(), *x.sparse(), init);\n            else //if(numA==5)\n              ublas::axpy_prod(*A.banded(), *x.sparse(), *x.sparse(), init);\n          }\n        }\n      }\n    }\n  }\n}\n\nvoid gemvtranspose(double a, const SiconosMatrix& A, const SiconosVector& x, double b, SiconosVector& y)\n{\n  if (A.isBlock())\n    SiconosMatrixException::selfThrow(\"gemv(...) not yet implemented for block vectors or matrices.\");\n  assert(!(A.isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n  unsigned int numA = A.num();\n  unsigned int numX = x.num();\n  unsigned int numY = y.num();\n  if (numA != 1 || numX != 1 || numY != 1)\n    SiconosMatrixException::selfThrow(\"gemv(...) failed: reserved to dense matrices or vectors.\");\n\n  siconosBindings::blas::gemv(a, siconosBindings::trans(*A.dense()), *x.dense(), b, *y.dense());\n}\n\nvoid gemv(double a, const SiconosMatrix& A, const SiconosVector& x, double b, SiconosVector& y)\n{\n  if (A.isBlock())\n    SiconosMatrixException::selfThrow(\"gemv(...) not yet implemented for block vectors or matrices.\");\n  assert(!(A.isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n  unsigned int numA = A.num();\n  unsigned int numX = x.num();\n  unsigned int numY = y.num();\n  if (numA != 1 || numX != 1 || numY != 1)\n    SiconosMatrixException::selfThrow(\"gemv(...) failed: reserved to dense matrices or vectors.\");\n\n  siconosBindings::blas::gemv(a, *A.dense(), *x.dense(), b, *y.dense());\n}\n", "meta": {"hexsha": "9867c33b0670784e00c83f39b0229b6f196e0397", "size": 30183, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixBLAS2.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/utils/SiconosAlgebra/SimpleMatrixBLAS2.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/utils/SiconosAlgebra/SimpleMatrixBLAS2.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": 36.7637028015, "max_line_length": 149, "alphanum_fraction": 0.4782162144, "num_tokens": 8577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.2964600627612183}}
{"text": "#pragma once\n/**\n * @file kdtree.hpp\n * @author Thomas Grandits\n * @brief Header of the KD-Tree implementation (CPU & GPU)\n * @version 0.1\n * @date 2020-12-16\n * \n * @copyright Copyright (c) 2020\n * \n */\n\n#include <iostream>     // std::cout\n#include <iterator>     // std::back_inserter\n#include <vector>       // std::vector\n#include <algorithm>    // std::copy\n#include <array>\n#include <assert.h>     /* assert */\n#include <cmath>\n#include <tuple>\n#include <numeric>\n#include <functional>\n#include \"nndistance.hpp\"\n\n#include <Eigen/Dense>\n\n//https://stackoverflow.com/questions/32014839/how-to-use-a-cuda-class-header-file-in-both-cpp-and-cuda-modules\n#ifdef __CUDACC__\n#define CUDA_HOSTDEV __host__ __device__\n#else\n#define CUDA_HOSTDEV\n#endif\n\ntypedef uint8_t dim_t;\ntypedef uint32_t point_i_t;\ntypedef uint32_t point_i_knn_t;\ntypedef point_i_t tree_ind_t;\ntypedef int level_t;\ntypedef uint8_t slot_t;\n\ntemplate <typename T, dim_t dims>\nusing Vec = Eigen::Matrix<T, dims, 1>;\n\n/**\n * @brief PingPongBuffer consisting of two actual buffers that can be easily accessed and swapped\n * \n * @tparam T Type of the PingPongBuffer\n */\ntemplate <typename T>\nstruct PingPongBuffer\n{\n    //std::array<T*, 2> buffers;\n    T* buffers[2];\n    slot_t current_slot = 0;\n\n    CUDA_HOSTDEV PingPongBuffer(){}\n    CUDA_HOSTDEV PingPongBuffer(T* ping, T* pong){buffers[0] = ping; buffers[1] = pong;}\n\n    CUDA_HOSTDEV inline T* getCurrentSlot() { return buffers[current_slot]; }\n    CUDA_HOSTDEV inline slot_t getCurrentSlotInd() const { return current_slot; }\n    CUDA_HOSTDEV inline T* getPongSlot() { return buffers[(current_slot + 1) % 2]; }\n    CUDA_HOSTDEV inline void increment()  { current_slot = (current_slot + 1) % 2; }\n    CUDA_HOSTDEV inline T* getCurrentSlotAndIncrement() { T* buf = getCurrentSlot();  increment(); return buf;}\n};\n\n/**\n * @brief Computes the total number of nodes necessary for a KD-Tree with the given levels\n * \n * @tparam T Type of the levels\n * @param levels Number of levels of the tree\n * @return T Number of total nodes of the tree\n */\ntemplate <typename T>\ninline T compTotalNrNodes(const T levels)\n{\n    std::vector<T> range(levels);\n    std::iota(range.begin(), range.end(), 0);\n\n    return std::accumulate(range.begin(), range.end(), 0, [](const T accum, const T cur_level){return accum + std::pow<T>(2, cur_level);});\n}\n\n/**\n * @brief Computes the total number of leaves necessary for a KD-Tree with the given levels\n * \n * @tparam T Type of the levels\n * @param levels Number of levels of the tree\n * @return CUDA_HOSTDEV T Number of total leaves of the tree\n */\ntemplate <typename T>\nCUDA_HOSTDEV inline T compTotalNrLeaves(const T levels)\n{\n    return std::pow<T>(2, levels);\n}\n\n/**\n * @brief Enum to tag which nodes have been visited when traversing the tree\n * \n */\nenum NodeTag : unsigned char\n{\n    uncharted = 0,\n    //visited = 1,\n    left_visited = 1,\n    right_visited = 2,\n    left_right_visited = left_visited | right_visited\n};\n\n/**\n * @brief Enum to specify in which direction an algorithm should continue traversing the tree\n * \n */\nenum NodeDirection : unsigned char\n{\n    up = 0,\n    left = 1,\n    right = 2,\n    finished = 3\n};\n\n/**\n * @brief Specifies data associated to each leaf of the tree\n * \n * @tparam T Type of the leaf\n * @tparam dims Dimensionality of the contained points\n */\ntemplate <typename T, dim_t dims>\nstruct PartitionLeaf\n{\n    std::array<T, dims>* data;\n    point_i_t nr_points;\n    point_i_t offset;\n\n    PartitionLeaf(std::array<T, dims>* data_, const point_i_t nr_points_, const point_i_t offset_) \n    : data(data_), nr_points(nr_points_), offset(offset_){}\n\n    PartitionLeaf(){}\n};\n\n/**\n * @brief Partition info present at each node, denoting the split-axis and the median used for the partitioning \n * \n * @tparam T Type of the median\n */\ntemplate <typename T>\nstruct Partition //: PartitionAligned<T>\n{\n    dim_t axis_split;\n    T median;\n\n    Partition(const dim_t axis_split_, const T median_) : axis_split(axis_split_), median(median_){}\n    Partition(){}\n};\n\ntemplate <typename T>\nusing tree_visit_f = std::function<NodeDirection(const Partition<T>&, const NodeTag, const tree_ind_t, const level_t)>;\n\n/**\n * @brief Contains all partition info associated with a KD-Tree:\n *        All partitions, all leaves, levels of the tree and the underyling structured points, as well as the shuffled indices are all managed here.\n * \n * @tparam T Type of the structured points and all underlying data\n * @tparam dims Dimensionality of the points\n * @tparam delete_partitions If true, deletes all associated partition data once the tree is destructed\n */\ntemplate <typename T, dim_t dims, bool delete_partitions = true>\nstruct PartitionInfo\n{\n    Partition<T>* partitions;\n    PartitionLeaf<T, dims>* leaves;\n    level_t levels;\n    std::array<T, dims>* structured_points = NULL;\n    point_i_t* shuffled_inds = NULL;\n    const point_i_t nr_points = 0;\n    const tree_ind_t nr_partitions, nr_leaves;\n\n    PartitionInfo(std::vector<Partition<T>>&& parts, std::vector<PartitionLeaf<T, dims>>&& leaves_, point_i_t* shuffled_inds_, const point_i_t nr_points_);\n    \n    PartitionInfo(PartitionInfo&& to_move) : partitions(std::move(to_move.partitions)), leaves(std::move(to_move.leaves)), levels(to_move.levels), \n        structured_points(to_move.structured_points), shuffled_inds(to_move.shuffled_inds), nr_points(to_move.nr_points), \n        nr_partitions(to_move.nr_partitions), nr_leaves(to_move.nr_leaves)\n    { \n        to_move.partitions = NULL;\n        to_move.leaves = NULL;\n        to_move.structured_points = NULL;\n        to_move.shuffled_inds = NULL;\n    }\n\n    PartitionInfo(const PartitionInfo<T, dims>& to_copy) : partitions(to_copy.partitions), leaves(to_copy.leaves), levels(to_copy.levels), \n        structured_points(to_copy.structured_points), shuffled_inds(to_copy.shuffled_inds), nr_points(to_copy.nr_points), \n        nr_partitions(to_copy.nr_partitions), nr_leaves(to_copy.nr_leaves)\n    {\n        if(delete_partitions)\n            throw std::runtime_error(\"Copies are not meant to do this here\");\n    }\n\n    CUDA_HOSTDEV ~PartitionInfo()\n    {\n        if(delete_partitions)\n        {\n            delete partitions;\n            delete leaves;\n        }\n    }\n};\n\ntemplate <typename T, dim_t dims>\nusing PartitionInfoDevice = PartitionInfo<T, dims, false>;\n\n/**\n * @brief Helper class to effectively traverse the KD-tree without any recursions. \n * \n * @tparam T Type of the points\n * @tparam dims Dimensionality of the points\n */\ntemplate <typename T, dim_t dims>\nclass TreeTraversal\n{\n//protected:\npublic:\n    PartitionInfo<T, dims>* partition_info = NULL;\n\n    NodeTag* visited_info; \n    tree_ind_t current_lin_ind;\n    level_t current_level;   \n    point_i_t nr_nodes;\n\npublic:\n\n    /**\n     * @brief Resets all positions and tags, effectively reinitializing the object without the need to destruct it.\n     * \n     * @return CUDA_HOSTDEV \n     */\n    CUDA_HOSTDEV void resetPositionAndTags()\n    {\n        std::fill(visited_info, visited_info + nr_nodes, NodeTag::uncharted);\n        current_lin_ind = current_level = 0;\n    }\n\n    TreeTraversal(PartitionInfo<T, dims>* partition_info_) : partition_info(partition_info_), nr_nodes(partition_info_->nr_partitions)\n    {\n        //visited_info = std::move(std::vector<NodeTag>(compTotalNrNodes(partition_info->levels), NodeTag::uncharted));\n        visited_info = new NodeTag[nr_nodes];\n        std::fill(visited_info, visited_info + nr_nodes, NodeTag::uncharted);\n        resetPositionAndTags();\n    }\n\n    CUDA_HOSTDEV TreeTraversal(){}\n\n    CUDA_HOSTDEV TreeTraversal(PartitionInfoDevice<T, dims>* partition_info_) : \n    //TODO: This could cause serious problems down the road!!!\n    partition_info(reinterpret_cast<PartitionInfo<T, dims>*>(partition_info_)),\n    //partition_info_d(partition_info_), \n    nr_nodes(partition_info_->nr_partitions)\n    {\n        //visited_info = std::move(std::vector<NodeTag>(compTotalNrNodes(partition_info->levels), NodeTag::uncharted));\n        visited_info = new NodeTag[nr_nodes];\n        std::fill(visited_info, visited_info + nr_nodes, NodeTag::uncharted);\n        current_lin_ind = current_level = 0;\n    }\n\n    CUDA_HOSTDEV ~TreeTraversal()\n    {\n        delete visited_info;\n    }\n\n    template <typename T_ind>\n    static T_ind compParentInd(const T_ind lin_ind) { return (lin_ind - 1)/2; }\n\n    template <typename T_ind>\n    static T_ind compLeftChildInd(const T_ind lin_ind) { return lin_ind * 2 + 1; }\n\n    template <typename T_ind>\n    static T_ind compRightChildInd(const T_ind lin_ind) { return lin_ind * 2 + 2; }\n\n    template <typename T_ind>\n    static T_ind compLevel(T_ind lin_ind) \n    { \n        if(lin_ind == 0)\n            return 1;\n\n        T_ind level = 0; \n        while((lin_ind = compParentInd(lin_ind)) != 0)\n            level++;\n\n        return level + 2;\n    }\n\n    template <typename T_ind, typename T_ind2>\n    static inline T_ind compLeftLeafInd(const T_ind lin_ind, const T_ind2 nr_partitions) { return compLeftChildInd(lin_ind) - nr_partitions; }\n\n    template <typename T_ind, typename T_ind2>\n    static inline T_ind compRightLeafInd(const T_ind lin_ind, const T_ind2 nr_partitions) { return compLeftLeafInd(lin_ind, nr_partitions) + 1; }\n\n    template <typename T_ind>\n    static inline T_ind compLeftLeafInd(const T_ind lin_ind) { return compLeftLeafInd(lin_ind, compTotalNrNodes(compLevel(lin_ind))); }\n\n    template <typename T_ind>\n    static inline T_ind compRightLeafInd(const T_ind lin_ind) { return compLeftLeafInd(lin_ind) + 1; }\n\n    CUDA_HOSTDEV inline tree_ind_t compLeftLeafInd(){ return compLeftLeafInd(current_lin_ind); }\n    CUDA_HOSTDEV inline tree_ind_t compRighLeafInd(){ return compRightLeafInd(current_lin_ind); }\n    CUDA_HOSTDEV inline level_t getTotalLevels() const {return partition_info->levels;}\n    CUDA_HOSTDEV inline tree_ind_t getCurrentLinearIndex() const {return current_lin_ind;}\n    CUDA_HOSTDEV inline level_t getCurrentLevel() const {return current_level;}\n    CUDA_HOSTDEV inline NodeTag getCurrentTag() const {return visited_info[current_lin_ind];}\n    CUDA_HOSTDEV //Partition<T>& getCurrentPartition() {return partition_info->partitions[current_lin_ind];}\n    CUDA_HOSTDEV inline const Partition<T>& getCurrentConstPartition() const {return partition_info->partitions[current_lin_ind];}\n    CUDA_HOSTDEV inline void moveToParent(){ assert(current_level != 0 && current_lin_ind != 0); current_lin_ind = compParentInd(current_lin_ind); current_level -= 1; }\n    CUDA_HOSTDEV inline void moveToLeftChild(){ assert(current_level < partition_info->levels);  current_lin_ind = compLeftChildInd(current_lin_ind); current_level += 1; }\n    CUDA_HOSTDEV inline void moveToRightChild(){ assert(current_level < partition_info->levels);  current_lin_ind = compRightChildInd(current_lin_ind); current_level += 1; }\n    CUDA_HOSTDEV inline bool isLeafParent() const { return current_level == partition_info->levels-1; }\n    CUDA_HOSTDEV inline const PartitionLeaf<T, dims>& getLeftLeaf() const{ assert(isLeafParent()); return partition_info->leaves[compLeftLeafInd(current_lin_ind, partition_info->nr_partitions)]; }\n    CUDA_HOSTDEV inline const PartitionLeaf<T, dims>& getRightLeaf() const{ assert(isLeafParent()); return partition_info->leaves[compRightLeafInd(current_lin_ind, partition_info->nr_partitions)]; }\n    CUDA_HOSTDEV inline void setCurrentNodeTag(const NodeTag new_tag){ visited_info[current_lin_ind] = new_tag; }\n\n    static_assert(NodeTag::left_right_visited == 3 && NodeTag::uncharted == 0, \"The binary computation does not work without these values\");\n    CUDA_HOSTDEV inline NodeTag moveTagToBinaryPosition(const NodeTag tag) const \n    { \n        const unsigned char bit_idx  = current_lin_ind % 4;\n        return static_cast<NodeTag>(tag << (bit_idx*2));\n    }\n    CUDA_HOSTDEV inline NodeTag getBinaryIndMask() const { return moveTagToBinaryPosition(NodeTag::left_right_visited);}\n    CUDA_HOSTDEV inline NodeTag getCurrentTagBinary() const \n    {\n        const auto byte_idx = current_lin_ind / 4;\n        const unsigned char bit_idx  = current_lin_ind % 4;\n        const unsigned char byte_data = visited_info[byte_idx];\n        const unsigned char binary_bitmask = NodeTag::left_right_visited << (bit_idx*2);\n        const unsigned char data = ( (byte_data & binary_bitmask) >> (bit_idx*2)) & NodeTag::left_right_visited;\n\n        return static_cast<NodeTag>(data);\n    }\n    CUDA_HOSTDEV inline void setCurrentNodeTagBinary(const NodeTag new_bits)\n    { \n        const auto byte_idx = current_lin_ind / 4;\n        const NodeTag old_byte = visited_info[byte_idx];\n        const NodeTag modified_mask = moveTagToBinaryPosition(NodeTag::left_right_visited); //getBinaryIndMask();\n        const NodeTag unmodified_mask = static_cast<NodeTag>(~modified_mask);\n        const unsigned char bit_idx  = current_lin_ind % 4;\n        visited_info[byte_idx] = static_cast<NodeTag>((unmodified_mask & old_byte) | (moveTagToBinaryPosition(new_bits) & modified_mask));\n    }\n\n    /**\n     * @brief Traverses the tree with which the object was constructed and calls a function at each node.\n     * \n     * @param direction_f Function to call at each node. This function will receive the current node along with some positional information.\n     *                    The function has to return a direction in which the tree should be further traversed. Finished when the function \n     *                    returns NodeDirection::finished.\n     * @return CUDA_HOSTDEV \n     */\n    CUDA_HOSTDEV void traverseTree(const tree_visit_f<T>& direction_f)\n    {\n        NodeDirection next_dir;\n        while((next_dir = direction_f(getCurrentConstPartition(), getCurrentTag(), current_lin_ind, current_level)) \n                        != NodeDirection::finished)\n        {\n            switch(next_dir)\n            {\n                case NodeDirection::up:\n                    moveToParent(); break;\n                case NodeDirection::left:\n                    moveToLeftChild(); break;\n                case NodeDirection::right:\n                    moveToRightChild(); break;\n            }\n        }\n    }\n};\n\n/**\n * @brief Computes the median along given axis for the ordered points\n * \n * @tparam T Type of the points\n * @tparam dims Dimensionality of the points\n * @param points_ordered Points for which the median should be computed. Note that the points are required to be ordered\n *                       in the respective dimension. This should be ensured after the tree was already constructed.\n * @param nr_points Number of points present in the array\n * @param current_axis Axis for which the median should be computed\n * @return T The median\n */\ntemplate <typename T, dim_t dims>\ninline T compMedian(const std::array<T, dims>* points_ordered, const point_i_t nr_points, const dim_t current_axis)\n{\n    assert(nr_points > 1);\n    const point_i_t half_ind = nr_points / 2;\n    if(nr_points % 2 == 1)\n        return points_ordered[half_ind][current_axis];\n    else\n        return 0.5 * (points_ordered[half_ind][current_axis] + points_ordered[half_ind-1][current_axis]);\n}\n\n/**\n * @brief Creates the KD-Tree's partitions using a recursive algorithms\n * \n * @tparam T Type of the points\n * @tparam dims Dimensionality of the points\n * @param partitions Vector of already generated (possibly empty) partitions, which will be initialized\n * @param leaves Empty vector of leaves that will be generated when creating the KD-tree\n * @param lin_ind Current node index (initially 0)\n * @param structured_points Pointer to the array of underlying ordered points\n * @param shuffled_inds Pointer to the array of underlying indices of the ordered points\n * @param nr_points Number of total points\n * @param levels Levels of the final KD-Tree\n * @param current_axis Current dimension in which we will split (initially 0)\n * @param arr_offset Current recursive offset of in the structured points array (initially 0)\n */\ntemplate <typename T, dim_t dims>\nvoid createPartitionRecursive(\n                                std::vector<Partition<T>>& partitions,\n                                std::vector<PartitionLeaf<T, dims>>& leaves,\n                                const tree_ind_t lin_ind,\n                                std::array<T, dims>* structured_points, \n                                point_i_t* shuffled_inds, const point_i_t nr_points,\n                                const int levels, const dim_t current_axis, const point_i_t arr_offset)\n{\n    typedef TreeTraversal<T, dims> tree_t;\n    if(nr_points == 0)\n        throw std::runtime_error(\"Error: Ran out of points while building KD-Tree. Either you required too many levels, or you used a lot of coplanar points\");\n\n\n    //Track global indices\n    std::vector<point_i_t> idx(nr_points);\n    std::iota(idx.begin(), idx.end(), 0);\n    std::sort(idx.begin(), idx.end(), \n    [current_axis, &structured_points](const point_i_t lhs, const point_i_t rhs)\n    { return structured_points[lhs][current_axis] < structured_points[rhs][current_axis]; });\n\n    //Reorder in the original\n    //Work on copy and then copy back\n    std::vector<std::array<T, dims>> structured_points_copy;\n    std::vector<point_i_t> shuffle_copy(shuffled_inds, shuffled_inds + nr_points);\n    for(size_t elem_i = 0; elem_i < nr_points; elem_i++)\n        shuffled_inds[elem_i] = shuffle_copy[idx[elem_i]];\n\n    \n    std::sort(structured_points, structured_points + nr_points, \n    [current_axis](const std::array<T, dims>& lhs, const std::array<T, dims>& rhs){return lhs[current_axis] < rhs[current_axis];});\n\n    const T median = compMedian<T, dims>(structured_points, nr_points, current_axis);\n\n    std::array<T, dims>* points_lower = structured_points; \n    std::array<T, dims>* points_higher = structured_points + nr_points/2;\n    const point_i_t nr_points_lower = nr_points/2;\n    const point_i_t nr_points_higher = nr_points - nr_points_lower; //TODO: For duplicates, this may cause alterations...\n\n    assert((nr_points - nr_points_lower) > 0);\n\n    if(levels == 0)\n    {        \n        assert(tree_t::compLeftLeafInd(lin_ind) == leaves.size());\n        leaves.push_back(std::move(PartitionLeaf<T, dims>(points_lower, nr_points_lower, arr_offset)));\n\n        assert(tree_t::compRightLeafInd(lin_ind) == leaves.size());\n        leaves.push_back(std::move(PartitionLeaf<T, dims>(points_higher, nr_points_higher, arr_offset + nr_points_lower)));\n        partitions[lin_ind] = std::move(Partition<T>(current_axis, median));\n    }\n    else\n    {\n        createPartitionRecursive<T, dims>(\n            partitions, leaves, TreeTraversal<T, dims>::compLeftChildInd(lin_ind),\n            points_lower, shuffled_inds, nr_points_lower, levels-1, \n                (current_axis + 1) % dims, arr_offset);\n        createPartitionRecursive<T, dims>(\n            partitions, leaves, TreeTraversal<T, dims>::compRightChildInd(lin_ind),\n            points_higher, shuffled_inds + nr_points_lower, nr_points_higher, levels-1, \n                (current_axis + 1) % dims, arr_offset + nr_points_lower);\n        \n        Partition<T> partition(current_axis, median);\n        partitions[lin_ind] = std::move(partition);\n    }\n}\n\n/**\n * @brief Recursively generates a KD-Tree using \\ref createPartitionRecursive 'createPartitionRecursive'\n * \n * @tparam T Type of the points\n * @tparam dims Dimensionality of the points\n * @param points_flat Array of points\n * @param nr_points Number of points\n * @param levels KD-Tree levels\n * @return PartitionInfo<T, dims> The PartitionInfo containing the information regarding the KD-Tree\n */\ntemplate <typename T, dim_t dims>\nPartitionInfo<T, dims> createKDTree(const T* points_flat, \n                                        const point_i_t nr_points, const int levels)\n{\n    assert(levels >= 1);\n    std::vector<PartitionLeaf<T, dims>> leaves; //(compTotalNrLeaves(levels));\n    std::vector<Partition<T>> partitions(compTotalNrNodes(levels), Partition<T>(-1, -1));\n\n    point_i_t* orig_inds = new point_i_t[nr_points];\n    std::iota(orig_inds, orig_inds + nr_points, 0); //Initializing\n    //std::cout << \"Creating main partition: \" << nr_points << \", \" << levels << std::endl;\n    const std::array<T, dims>* points = reinterpret_cast<const std::array<T, dims>*>(points_flat);\n    //std::vector<std::array<T, dims>> structured_points(points, points + nr_points);\n    std::array<T, dims>* structured_points = new std::array<T, dims>[nr_points];\n    std::copy(points, points + nr_points, structured_points);\n    createPartitionRecursive<T, dims>(partitions, leaves, 0,\n                                        structured_points,\n                                        orig_inds, nr_points, levels-1, 0, 0);\n    //partitions[0] = new MainPartition<T, dims>(std::move(partitions[0]));\n    /*MainPartition<T, dims> main_partition = MainPartition<T, dims>(std::move(\n                        ),\n                                        structured_points, orig_inds, nr_points, levels);*/\n\n    //Sanity checks\n    #ifndef NDEBUG\n    point_i_t offset = 0;\n    for(int i = 0; i < leaves.size(); i++)\n    {\n        assert(leaves[i].offset == offset);\n        offset += leaves[i].nr_points;\n    }\n    for(int i = 1; i < leaves.size(); i++)\n    {\n        assert((leaves[i-1].data + leaves[i-1].nr_points) == leaves[i].data);\n    }\n    #endif\n\n    assert(leaves.size() == compTotalNrLeaves(levels));\n\n    return std::move(PartitionInfo<T, dims>(std::move(partitions), std::move(leaves), /*structured_points,*/ orig_inds, nr_points)); //std::move(main_partition);\n}\n\n/**\n * @brief Computes the difference between two points (lhs - rhs)\n * \n * @tparam T Type of the points\n * @tparam T_calc Type of the resulting difference\n * @tparam dims Dimensionality of the points\n * @param lhs Array of points\n * @param rhs Array of points\n * @return std::array<T_calc, dims> The difference between the lhs and rhs\n */\ntemplate\n<typename T, typename T_calc, dim_t dims>\ninline CUDA_HOSTDEV std::array<T_calc, dims> compDiff(const std::array<T, dims>& lhs, const std::array<T, dims>& rhs)\n{\n    std::array<T_calc, dims> diffs;\n\n    for(dim_t dim_i = 0; dim_i < dims; dim_i++)\n    {\n        diffs[dim_i] = static_cast<T_calc>(lhs[dim_i]) - static_cast<T_calc>(rhs[dim_i]);\n    }\n\n    return std::move(diffs);\n}\n\n/**\n * @brief Computes the sum of squared elem\n * \n * @tparam T Type of the array\n * @tparam dims Number of points\n * @param x Array of values\n * @return T sum(x^2)\n */\ntemplate\n<typename T, dim_t dims>\ninline CUDA_HOSTDEV T compQuadrSum(const std::array<T, dims>& x)\n{\n    return std::accumulate(x.begin(), x.end(), 0., [](const T accum, const T elem){return accum + elem*elem;});\n}\n\n/**\n * @brief Computes the element-wise quadratic euclidean distance between lhs and rhs, i.e. ||lhs_i - rhs_i||\n * \n * @tparam T Type of the array\n * @tparam T_calc Type of the calculation\n * @tparam dims Dimensionality of the points\n * @param lhs Left-hand-side of the calculation\n * @param lhs Right-hand-side of the calculation\n * @return T_calc ||lhs_i - rhs_i||\n */\ntemplate\n<typename T, typename T_calc, dim_t dims>\ninline CUDA_HOSTDEV T_calc compQuadrDist(const std::array<T, dims>& lhs, const std::array<T, dims>& rhs)\n{\n    std::array<T_calc, dims> diffs = compDiff<T, T_calc, dims>(lhs, rhs);\n    return compQuadrSum<T_calc, dims>(diffs);\n}\n\n/**\n * @brief Computes the distance to the projected point onto the median of the current dimension. This is used to see if we need to further\n *        traverse the tree or already found the KNNs, which is true in case the projection is farther away than\n *        the distance to the current KNN most far away.\n * \n * @tparam T Type of the array\n * @tparam dims Dimensionality of the points\n * @param point Original point for which to search the KNN\n * @param point_proj The original point, already projected on possible multiple previous dimensions. Note that in the simplest case\n *                   this is equal to point.\n * @param Partition<T> Node information of the current axis/dimension split that we want to compute the projection in\n * @return T Resulting distance of the current projection\n */\ntemplate\n<typename T, dim_t dims>\ninline CUDA_HOSTDEV T projectionDist(const std::array<T, dims>& point, const std::array<T, dims>& point_proj, const Partition<T>& partition)\n{\n    std::array<T, dims> proj_vec = compDiff<T, T, dims>(point_proj, point);\n    const dim_t current_axis = partition.axis_split;\n    proj_vec[current_axis] += partition.median - point_proj[current_axis];\n    return compQuadrSum<T, dims>(proj_vec);\n}\n\n/**\n * @brief See \\ref projectionDist 'projectionDist'\n */\ntemplate\n<typename T, dim_t dims>\ninline CUDA_HOSTDEV T projectionDist(const Vec<T, dims>& point, const Vec<T, dims>& point_proj, const Partition<T>& partition)\n{\n    Vec<T, dims> proj_vec = (point_proj - point);\n    const dim_t current_axis = partition.axis_split;\n    proj_vec[current_axis] += partition.median - point_proj[current_axis];\n    return proj_vec.squaredNorm();\n}\n\n/**\n * @brief Checks if we need to compute the distances to any of the points in the partition. Achieved by using \\ref projectionDist 'projectionDist'.\n */\ntemplate\n<typename T, typename T_calc, dim_t dims>\ninline CUDA_HOSTDEV bool partitionNecessary(const std::array<T, dims>& point, const std::array<T, dims>& point_proj, \n                                const Partition<T>& partition, const T current_worst_dist)\n{\n    const auto proj_dist = projectionDist<T, dims>(point, point_proj, partition);\n    return proj_dist < current_worst_dist;\n}\n\n/**\n * @brief See \\ref partitionNecessary 'partitionNecessary'.\n */\ntemplate\n<typename T, typename T_calc, dim_t dims>\ninline CUDA_HOSTDEV bool partitionNecessary(const Vec<T, dims>& point, const Vec<T, dims>& point_proj, \n                                const Partition<T>& partition, const T current_worst_dist)\n{\n    const auto proj_dist = projectionDist<T, dims>(point, point_proj, partition);\n    return proj_dist < current_worst_dist;\n}\n\n/**\n * @brief Computes the quadratic distances between point to all points in partition_leaf and updates the current knn, marked by best_dists and best_idx. \n * \n * @param point Query point for which the KNN should be calculated\n * @param partition_leaf Partition for which all quadratic distances should be computed\n * @param best_dists Quadr. distances to the currently assumed KNNs (starts with infinity). Has a length of K\n * @param best_idx Indices of the currently assumed KNNs (starts with -1). Has a length of K\n * @param nr_nns_searches How many nearest neighbors will be searched (=K)\n *         \n */\ntemplate\n<typename T, typename T_calc, dim_t dims>\nvoid compQuadrDistLeafPartition(const std::array<T, dims>& point, const PartitionLeaf<T, dims>& partition_leaf,\n                                    T* best_dists, point_i_knn_t* best_idx,\n\t\t\t\t\t\t\t\t\tconst point_i_knn_t nr_nns_searches)\n{\n\tconst std::array<T, dims>* partition_data = partition_leaf.data;\n    const point_i_t partition_size = partition_leaf.nr_points;\n\tconst point_i_t partition_offset = partition_leaf.offset;\n    for(point_i_t ref_i = 0; ref_i < partition_size; ref_i++)\n    {\n        const T_calc dist = compQuadrDist<T, T_calc, dims>(point, partition_data[ref_i]);\n        const auto insertion_idx = knnInsertionDynamic<T_calc>(dist, best_dists, nr_nns_searches);\n        if(insertion_idx < nr_nns_searches)\n        {\n            const auto best_dists_end = best_dists + nr_nns_searches;\n            const auto best_idx_end = best_idx + nr_nns_searches;\n            assert(best_dists + insertion_idx < best_dists_end);\n            assert(best_idx + insertion_idx < best_idx_end);\n            //Shift elements to the right\n            //std::cout << k << \", \" << d << \"insert into \" << insertion_idx << std::endl;\n            //std::move_backward(best_dists + insertion_idx, best_dists +  nr_nns_searches - 1, best_dists.end());\n            //std::move_backward(best_idx.begin() + insertion_idx, best_idx.end() - 1, best_idx.end());\n            moveBackward(best_dists + insertion_idx, best_dists_end - 1, best_dists_end);\n            moveBackward(best_idx + insertion_idx, best_idx_end - 1, best_idx_end);\n            best_dists[insertion_idx] = dist;\n            best_idx[insertion_idx] = ref_i + partition_offset;\n        }\n    }    \n}\n\n\n/**\n * @brief See \\ref compQuadrDistLeafPartition 'compQuadrDistLeafPartition'.\n */\ntemplate\n<typename T, typename T_calc, dim_t dims>\nCUDA_HOSTDEV void compQuadrDistLeafPartition(const Vec<T, dims>& point, const PartitionLeaf<T, dims>& partition_leaf,\n                                    T* best_dists, point_i_knn_t* best_idx,\n\t\t\t\t\t\t\t\t\tconst point_i_knn_t nr_nns_searches)\n{\n    //printf(\"compQuadrDistLeafPartition: %x, \", partition_leaf.data);\n    //printf(\"%d, \", partition_leaf.nr_points);\n    //printf(\"%d\\n\", partition_leaf.offset);\n\tconst Vec<T, dims>* partition_data = reinterpret_cast<Vec<T, dims>*>(partition_leaf.data);\n    const point_i_t partition_size = partition_leaf.nr_points;\n\tconst point_i_t partition_offset = partition_leaf.offset;\n    for(point_i_t ref_i = 0; ref_i < partition_size; ref_i++)\n    {\n        const T_calc dist = (point - partition_data[ref_i]).squaredNorm();\n        const auto insertion_idx = knnInsertionDynamic<T_calc>(dist, best_dists, nr_nns_searches);\n        if(insertion_idx < nr_nns_searches)\n        {\n            const auto best_dists_end = best_dists + nr_nns_searches;\n            const auto best_idx_end = best_idx + nr_nns_searches;\n            assert(best_dists + insertion_idx < best_dists_end);\n            assert(best_idx + insertion_idx < best_idx_end);\n            //Shift elements to the right\n            //std::cout << k << \", \" << d << \"insert into \" << insertion_idx << std::endl;\n            //std::move_backward(best_dists + insertion_idx, best_dists +  nr_nns_searches - 1, best_dists.end());\n            //std::move_backward(best_idx.begin() + insertion_idx, best_idx.end() - 1, best_idx.end());\n            moveBackward(best_dists + insertion_idx, best_dists_end - 1, best_dists_end);\n            moveBackward(best_idx + insertion_idx, best_idx_end - 1, best_idx_end);\n            best_dists[insertion_idx] = dist;\n            best_idx[insertion_idx] = ref_i + partition_offset;\n        }\n    }    \n}\n\n/**\n * @brief See \\ref compQuadrDistLeafPartition 'compQuadrDistLeafPartition'.\n */\ntemplate\n<typename T, typename T_calc, dim_t dims>\nvoid compQuadrDistPartition(const std::array<T, dims>& point, const PartitionLeaf<T, dims>& partition_leaf,\n                                    std::vector<T>& best_dists, std::vector<point_i_knn_t>& best_idx,\n\t\t\t\t\t\t\t\t\tconst point_i_knn_t nr_nns_searches);\n\n/**\n * @brief Recursively traverses the node and calls compQuadrDistLeafPartition on the leaves.\n */\ntemplate\n<typename T, typename T_calc, dim_t dims>\nvoid compQuadrDistNode(const std::array<T, dims>& point, const Partition<T>& partition,\n                                    std::vector<T>& best_dists, std::vector<point_i_knn_t>& best_idx,\n                                    const int current_level, const std::array<T, dims>& point_proj, const point_i_knn_t nr_nns_searches);\n\n/**\n * @brief Computes the KNN on the KD-Tree defined by partition_info. Iteratively calls compQuadrDistNode on the main node for each point in points_query.\n *        The resulting quadr. distances and indices of the KNNs will be stored in dist [M, K] in a C-ordering fashion.\n */\ntemplate\n<typename T, typename T_calc, dim_t dims>\nvoid KDTreeKNNSearch(PartitionInfo<T, dims>& partition_info,\n                    const point_i_t nr_query, \n                    const std::array<T, dims>* points_query, T * dist, point_i_knn_t* idx, const point_i_knn_t nr_nns_searches);\n\n", "meta": {"hexsha": "f1a97194a54960d2f257f729d2c9e7c46b9d24dc", "size": 31727, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/kdtree.hpp", "max_stars_repo_name": "thomgrand/tf_kdtree", "max_stars_repo_head_hexsha": "e6474f5aeb7d80f6c65a9af0e307c1d4bf912942", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-05-08T22:43:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T00:57:41.000Z", "max_issues_repo_path": "src/kdtree.hpp", "max_issues_repo_name": "thomgrand/tf_kdtree", "max_issues_repo_head_hexsha": "e6474f5aeb7d80f6c65a9af0e307c1d4bf912942", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kdtree.hpp", "max_forks_repo_name": "thomgrand/tf_kdtree", "max_forks_repo_head_hexsha": "e6474f5aeb7d80f6c65a9af0e307c1d4bf912942", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-15T21:15:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T14:45:24.000Z", "avg_line_length": 42.3026666667, "max_line_length": 198, "alphanum_fraction": 0.6924701358, "num_tokens": 7654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.2964449579727892}}
{"text": "/* main.cpp - a \"main\" file, just a debugging tool\n * \n * Copyright (C) 2021, LWE-PVSS\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\n * 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\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n **/\n \n// This file is just a convenience, a handy tool that lets us run\n// small porgrams without having to use the awkward ctest syntax.\n#include <cassert>\n#include <cmath>\n#include <random>\n#include <chrono>\n#include <string>\n#include <sys/time.h>\n#include <sys/resource.h>\nusing namespace std;\n\n#include <NTL/version.h>\n#include \"regevEnc.hpp\"\n#include \"regevProofs.hpp\"\n\nusing namespace ALGEBRA;\nusing namespace REGEVENC;\n\nint main(int argc, char** argv) {\n    // std::cout << \"- Found GMP version \"<<__GNU_MP__ <<std::endl;\n    // std::cout << \"- Found NTL version \"<<NTL_VERSION <<std::endl;\n    // std::cout << \"- Found Sodium version \"<<SODIUM_VERSION_STRING<<std::endl;\n\n    int nParties = 512;\n    if (argc > 1) {\n        nParties = std::stoi(argv[1]);\n    }\n    if (nParties < 32 || nParties > 4096)\n        nParties = 512;\n    std::cout << \"nParties=\"<<nParties << std::endl;\n\n    // The dimensions of the the CRX is k-by-m, but note that this is a\n    // matrix over GF(p^2) so the lattice dimensions we get is twice that\n    KeyParams kp(nParties);\n    // kp.k=64;\n    GlobalKey gpk(\"testContext\", kp);\n    std::cout <<\"{ kay:\"<<gpk.kay<<\", enn:\"<<gpk.enn\n      <<\", sigmaEnc1:\"<<gpk.sigmaEnc1<<\", sigmaEnc2:\"<<gpk.sigmaEnc2<<\" }\\n\";\n\n    TernaryEMatrix::init();\n    MerlinRegev mer;\n    PedersenContext ped;\n    SharingParams ssp(interval(1,gpk.enn+1), gpk.tee);\n    VerifierData vd(gpk, ped, mer, ssp);\n    ProverData pd(vd);\n\n    // Generate/verify the proofs by the second party (idx=1)\n    int partyIdx = 1;\n\n    // Key generation for all the parties\n    std::vector<ALGEBRA::EVector> kgNoise(gpk.enn);\n    std::vector<ALGEBRA::EVector> sk(gpk.enn);\n    std::vector<ALGEBRA::EVector> pk(gpk.enn);\n    auto start = chrono::steady_clock::now();\n    crsTicks = 0;\n    for (int i=0; i<gpk.enn; i++) {\n        std::tie(sk[i],pk[i]) = gpk.genKeys(&kgNoise[i]);\n        gpk.addPK(pk[i]);\n    }\n    gpk.setKeyHash();\n    auto end = chrono::steady_clock::now();\n    auto ticks = chrono::duration_cast<chrono::milliseconds>(end - start).count();\n    std::cout <<gpk.enn<<\" keyGens in \"<<ticks<<\" milliseconds, avg=\"<<(ticks/double(gpk.enn))\n        << \" (\"<< (crsTicks/double(gpk.enn)) << \" for s x A)\\n\";\n\n    // encryption\n    std::vector<ALGEBRA::SVector> ptxt1(gpk.enn);\n    std::vector<GlobalKey::CtxtPair> ctxt1(gpk.enn);\n    // secret sharing of a random value , the secret itself is sshr[0]\n    ALGEBRA::SVector sshr;\n    ssp.randomSharing(sshr);\n    for (int i=0; i<gpk.enn; i++) {\n        resize(ptxt1[i], gpk.enn);\n        for (int j=0; j<gpk.enn; j++) ptxt1[i][j] = sshr[i+1];\n    }\n    start = chrono::steady_clock::now();\n    crsTicks = 0;\n    for (int i=0; i<gpk.enn; i++) {\n        ctxt1[i] = gpk.encrypt(ptxt1[i]);\n    }\n    end = chrono::steady_clock::now();\n    ticks = chrono::duration_cast<chrono::milliseconds>(end - start).count();\n    std::cout <<gpk.enn<<\" encryptions in \"<<ticks<<\" milliseconds, avg=\"<<(ticks/double(gpk.enn)) \n        << \" (\"<< (crsTicks/double(gpk.enn)) << \" for A x r)\\n\";\n\n    // decryption at party #1\n    ALGEBRA::SVector ptxt2;    resize(ptxt2, gpk.tee);\n    ALGEBRA::EVector decNoise; resize(decNoise, gpk.tee);\n    start = chrono::steady_clock::now();\n    for (int i=0; i<gpk.tee; i++) { // decrypt 2nd entry in i'th ctxt\n        ptxt2[i] = gpk.decrypt(sk[partyIdx], partyIdx, ctxt1[i], &(decNoise[i]));\n    }\n    end = chrono::steady_clock::now();\n    ticks = chrono::duration_cast<chrono::milliseconds>(end - start).count();\n    std::cout << gpk.tee << \" decryptions in \"<<ticks<< \" milliseconds, avg=\"\n        << (ticks/double(gpk.tee)) << std::endl;\n\n    for (int i=0; i<gpk.tee; i++) { // decrypt 2nd entry in i'th ctxt\n        if (ptxt2[i] != ptxt1[i][partyIdx])\n            std::cout << \"decryption error in \"<<i<<\"th ciphertext\\n\";\n    }\n\n    // re-encryption at party #1\n    ALGEBRA::SVector ptxt3;\n    resize(ptxt3, gpk.enn);\n    for (int j=0; j<gpk.enn; j++) ptxt3[j] = sshr[j+1];\n    ALGEBRA::EVector encRnd;\n    REGEVENC::GlobalKey::CtxtPair eNoise;\n    auto ctxt2 = gpk.encrypt(ptxt3, encRnd, eNoise);\n\n    // Copy the first t ciphertexts into a k x t matrix and another t-vector\n    EMatrix ctxtMat;\n    resize(ctxtMat, gpk.kay, gpk.tee);\n    EVector ctxtVec;\n    resize(ctxtVec, gpk.tee);\n    for (int i=0; i<gpk.tee; i++) {\n        for (int j=0; j<gpk.kay; j++)\n            ctxtMat[j][i] = ctxt1[i].first[j];\n        ctxtVec[i] = ctxt1[i].second[partyIdx];\n    }\n\n    // prepare for proof, commit to the secret key\n    DLPROOFS::Point::counter = 0;\n    DLPROOFS::Point::timer = 0;\n    int origSize = sk[partyIdx].length(); \n   \n    vd.sk1Com = commit(sk[partyIdx], vd.sk1Idx, vd.Gs, pd.sk1Rnd);\n\n    start = chrono::steady_clock::now();\n    SVector lagrange = vd.sp->lagrangeCoeffs(interval(1,gpk.tee+1));\n\n    crsTicks = 0;\n    proveDecryption(pd, ctxtMat, ctxtVec, ptxt2, sk[partyIdx], decNoise);\n    proveEncryption(pd, ctxt2.first, ctxt2.second, ptxt3, encRnd, eNoise.first, eNoise.second);\n    proveKeyGen(pd, partyIdx, sk[partyIdx], kgNoise[partyIdx]);\n    proveReShare(pd, lagrange, ptxt2, ptxt3);\n    proveSmallness(pd);\n\n    end = chrono::steady_clock::now();\n    ticks = chrono::duration_cast<chrono::milliseconds>(end - start).count();\n    std::cout << \"preparing to prove and committing in \"<<ticks<< \" milliseconds, \"\n        << DLPROOFS::Point::counter << \" exponentiations in \"\n        << ((500+DLPROOFS::Point::timer)/1000) << \" milliseconds\"\n        << \" (\"<< crsTicks << \" for xR x A)\\n\";\n\n    // aggregate the constraints and flatten everything before proving\n    DLPROOFS::Point::counter = 0;\n    DLPROOFS::Point::timer = 0;\n    std::cout<<\"aggregting constraints\\n\";\n    start = chrono::steady_clock::now();\n    ReadyToProve rtp;\n    rtp.aggregateProver(pd);\n\n    // Make copies of the Merlin transcripts and specialize them\n    // for the final constraints before proving/verifying them\n    auto merLin = *vd.mer;\n    merLin.processConstraint(\"linear\", rtp.linCnstr);\n\n    auto merQuad = *vd.mer;\n    merQuad.processConstraint(\"quadratic\", rtp.quadCnstr);\n\n    // Flatten the statements, this relases the memory of the constraints\n    // (hence the Merlin processing above must be done before doing this).\n    std::cout<<\"flatenning constraints\\n\";\n    rtp.flattenLinPrv(pd);\n    rtp.flattenQuadPrv(pd);\n\n    ReadyToVerify rtv = rtp; // a copy without the secret variables\n\n    // prove and verify the linear statement\n    auto merLinVer = merLin; // another copy for verification\n    DLPROOFS::LinPfTranscript pfL(\"Linear\");\n    pfL.C = rtp.linCom;\n\n    end = chrono::steady_clock::now();\n    ticks = chrono::duration_cast<chrono::milliseconds>(end - start).count();\n    std::cout << \"aggregating constaints in \"<<ticks<< \" milliseconds, \"\n        << DLPROOFS::Point::counter << \" exponentiations in \"\n        << ((500+DLPROOFS::Point::timer)/1000) << \" milliseconds\\n\";\n\n    // The actual proof\n    DLPROOFS::Point::counter = 0;\n    DLPROOFS::Point::timer = 0;\n    start = chrono::steady_clock::now();\n    DLPROOFS::proveLinear(pfL, rtp.lComRnd, merLin, rtp.linWtns.data(),\n            rtp.linStmnt.data(), rtp.linGs.data(), rtp.linGs.size());\n    end = chrono::steady_clock::now();\n    ticks = chrono::duration_cast<chrono::milliseconds>(end - start).count();\n    std::cout << \"proving linear in \"<<ticks<< \" milliseconds, \"\n        << DLPROOFS::Point::counter << \" exponentiations in \"\n        << ((500+DLPROOFS::Point::timer)/1000) << \" milliseconds\\n\";\n\n    DLPROOFS::Point::counter = 0;\n    DLPROOFS::Point::timer = 0;\n    start = chrono::steady_clock::now();\n    if (!DLPROOFS::verifyLinear(pfL, rtv.linStmnt.data(), rtv.linGs.data(),\n                      rtv.linGs.size(), rtv.linCnstr.equalsTo, merLinVer))\n        std::cout << \"failed linear verification\\n\";\n    end = chrono::steady_clock::now();\n    ticks = chrono::duration_cast<chrono::milliseconds>(end - start).count();\n    std::cout << \"verifying linear in \"<<ticks<< \" milliseconds, \"\n        << DLPROOFS::Point::counter << \" exponentiations in \"\n        << ((500+DLPROOFS::Point::timer)/1000) << \" milliseconds\\n\";\n\n    // prove and verify the quadratic statement\n    DLPROOFS::Point::counter = 0;\n    DLPROOFS::Point::timer = 0;\n    auto merQuadVer = merQuad; // another copy for verification\n    DLPROOFS::QuadPfTranscript pfQ(\"Quadratic\");\n    pfQ.C = rtp.quadCom;\n     // The actual proof\n    start = chrono::steady_clock::now();\n    DLPROOFS::proveQuadratic(pfQ, rtp.qComRnd, merQuad, rtp.quadGs.data(),\n                rtp.quadWtnsG.data(), rtp.quadHs.data(), rtp.quadWtnsH.data(),\n                rtp.quadGs.size());\n    end = chrono::steady_clock::now();\n    ticks = chrono::duration_cast<chrono::milliseconds>(end - start).count();\n    std::cout << \"proving quadratic in \"<<ticks<< \" milliseconds, \"\n        << DLPROOFS::Point::counter << \" exponentiations in \"\n        << ((500+DLPROOFS::Point::timer)/1000) << \" milliseconds\\n\";\n\n    // The actual verification\n    DLPROOFS::Point::counter = 0;\n    DLPROOFS::Point::timer = 0;\n    start = chrono::steady_clock::now();\n    if (!DLPROOFS::verifyQuadratic(pfQ, rtv.quadGs.data(), rtv.quadHs.data(),\n                        rtp.quadGs.size(), rtv.quadCnstr.equalsTo, merQuadVer,\n                        rtv.offstG.data(), rtv.offstH.data()))\n        std::cout << \"failed quadratic verification\\n\";\n    end = chrono::steady_clock::now();\n    ticks = chrono::duration_cast<chrono::milliseconds>(end - start).count();\n    std::cout << \"verifying quadratic in \"<<ticks<< \" milliseconds, \"\n        << DLPROOFS::Point::counter << \" exponentiations in \"\n        << ((500+DLPROOFS::Point::timer)/1000) << \" milliseconds\\n\";\n\n    struct rusage ru;\n    getrusage(RUSAGE_SELF, &ru);\n    std::cout << \" max mem: \" << ru.ru_maxrss << \" kilobytes\\n\";\n\n    return 0;\n}\n\n#if 0\n#include <vector>\n#include <iostream>\n#include \"bulletproof.hpp\"\n\nint main(int, char**) {\n    constexpr size_t pfSize = 13;\n\n    // build a constraint: sum_i ai*bi = b = \\sum_bi^2\n    DLPROOFS::LinConstraint cnstrL;\n    for (size_t i=0; i<pfSize; i++) {\n        CRV25519::Scalar& x = cnstrL.terms[i+1].setInteger(i+1);\n        cnstrL.equalsTo += x * x;\n    }\n    DLPROOFS::PtxtVec& xes = cnstrL.terms;\n    DLPROOFS::LinPfTranscript pfL = proveLinear(\"blah\", cnstrL, xes);\n    std::cout << \"linear: \"<<verifyLinear(cnstrL, pfL) <<std::endl;\n\n    DLPROOFS::QuadConstraint cnstrQ;\n    for (auto& x : xes) {\n        cnstrQ.indexes.insert(cnstrQ.indexes.end(), x.first);\n        cnstrQ.equalsTo += x.second * x.second;\n    }    \n    DLPROOFS::PtxtVec& ys = cnstrL.terms;\n    DLPROOFS::QuadPfTranscript pfQ = proveQuadratic(\"blah\", cnstrQ, xes, ys);\n    std::cout << \"quadratic: \"<<verifyQuadratic(cnstrQ, pfQ) <<std::endl;\n\n    std::set<size_t> indexes;\n    for (auto& elem: xes) // elem = {idx:scalar}\n        indexes.insert(indexes.end(), elem.first);\n\n    auto [normSq, prNS] = DLPROOFS::proveNormSquared(\"blah\", xes);\n    std::cout << \"norm: \"<<verifyNormSquared(indexes,normSq,prNS)<<std::endl;\n\n    return 0;\n}\n#endif\n", "meta": {"hexsha": "17812cf83f4c7b3e611655409b1612d6b4158d81", "size": 12177, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "shaih/cpp-lwevss", "max_stars_repo_head_hexsha": "250516eb4270a87383cad40df498da4523242ee8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2022-01-24T21:19:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T23:07:39.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "shaih/cpp-lwevss", "max_issues_repo_head_hexsha": "250516eb4270a87383cad40df498da4523242ee8", "max_issues_repo_licenses": ["MIT"], "max_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": "shaih/cpp-lwevss", "max_forks_repo_head_hexsha": "250516eb4270a87383cad40df498da4523242ee8", "max_forks_repo_licenses": ["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.0559210526, "max_line_length": 99, "alphanum_fraction": 0.6372669787, "num_tokens": 3625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2963332999770349}}
{"text": "// Copyright András Vukics 2006–2020. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt)\n#include \"ModeCorrelations.h\"\n\n#include \"LazyDensityOperator.h\"\n#include \"Structure.h\"\n\n#include <boost/range/algorithm/copy.hpp>\n\nusing namespace boost;\n\n\nModeCorrelations::ModeCorrelations()\n  : EA_Base(\"ModeCorrelations\",{\"<a number operator>\",\"VAR(a number operator)\",\"real(<a>)\",\"imag(\\\")\",\"<X^2>-<X>^2\",\"<Y^2>-<Y>^2\",\"<(XY+YX)/2>-<X><Y>\",\n                                \"<b number operator>\",\"VAR(b number operator)\",\"real(<b>)\",\"imag(\\\")\",\"<Q^2>-<Q>^2\",\"<P^2>-<P>^2\",\"<(QP+PQ)/2>-<Q><P>\",\n                                \"<XQ>-<X><Q>\",\"<XP>-<X><P>\",\"<YQ>-<Y><Q>\",\"<YP>-<Y><P>\"}\n           ),\n    averagedMode_()\n{\n}\n\n\nnamespace {\n\n#include \"details_BinaryHelper.h\"\n\n}\n\n\nconst ModeCorrelations::Averages\nModeCorrelations::average_v(structure::NoTime, const LazyDensityOperator& matrix) const\n{\n  using quantumdata::partialTrace;\n\n  auto averages(initializedAverages());\n\n  {\n    auto fun=[&](const auto& psiS){return averagedMode_.average(0,psiS);};\n    \n    const Averages \n      a0{partialTrace<V0>(matrix,fun)},\n      a1{partialTrace<V1>(matrix,fun)};\n\n    copy(a1,copy(a0,averages.begin()));\n  }\n\n  for (int n=0; n<int(matrix.getDimension(0)); n++) for (int m=1; m<int(matrix.getDimension(1)); m++) {\n      if(n<int(matrix.getDimension(0))-1) {\n        dcomp temp=sqrt(m*(n+1))*matrix(n,m)(n+1,m-1);\n        averages(14)+=real(temp);\n        averages(15)+=imag(temp);\n      }\n      if(n>0) {\n        dcomp temp=sqrt(m*n)*matrix(n,m)(n-1,m-1);\n        averages(16)+=real(temp);\n        averages(17)+=imag(temp);\n      }\n    }\n\n  return averages;\n\n}\n\n\nvoid\nModeCorrelations::process_v(Averages& averages) const\n{\n  {\n    Averages ranged(averages(blitz::Range(0, 6)));\n    averagedMode_.process(ranged);\n  }\n  {\n    Averages ranged(averages(blitz::Range(7,13)));\n    averagedMode_.process(ranged);\n  }\n\n  double \n    xAvr=sqrt(2)*averages( 2),\n    yAvr=sqrt(2)*averages( 3),\n    qAvr=sqrt(2)*averages( 9),\n    pAvr=sqrt(2)*averages(10);\n\n  double\n    xq= averages(14)+averages(16)-xAvr*qAvr,\n    xp= averages(15)+averages(17)-xAvr*pAvr,\n    yq=-averages(15)+averages(17)-yAvr*qAvr,\n    yp= averages(14)-averages(16)-yAvr*pAvr;\n\n  averages(14)=xq;\n  averages(15)=xp;\n  averages(16)=yq;\n  averages(17)=yp;\n\n}\n", "meta": {"hexsha": "a34caa7b2c181b8a873a13afb632d48af982f00f", "size": 2348, "ext": "cc", "lang": "C++", "max_stars_repo_path": "CPPQEDelements/interactions/ModeCorrelations.cc", "max_stars_repo_name": "bartoszek/cppqed", "max_stars_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "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": "CPPQEDelements/interactions/ModeCorrelations.cc", "max_issues_repo_name": "bartoszek/cppqed", "max_issues_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "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": "CPPQEDelements/interactions/ModeCorrelations.cc", "max_forks_repo_name": "bartoszek/cppqed", "max_forks_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9787234043, "max_line_length": 151, "alphanum_fraction": 0.6056218058, "num_tokens": 768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.29626562686036534}}
{"text": "/* Copyright (c) 2021, the adamantine authors.\n *\n * This file is subject to the Modified BSD License and may not be distributed\n * without copyright and license information. Please refer to the file LICENSE\n * for the text and further information on this license.\n */\n\n#include <DataAssimilator.hh>\n\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/lac/linear_operator_tools.h>\n\n#include <execution>\n\nnamespace adamantine\n{\n\nDataAssimilator::DataAssimilator(boost::property_tree::ptree const &database)\n{\n  // Set the solver parameters from the input database\n  // PropertyTreeInput data_assimilation.solver.max_number_of_temp_vectors\n  if (boost::optional<unsigned int> max_num_temp_vectors =\n          database.get_optional<unsigned int>(\n              \"solver.max_number_of_temp_vectors\"))\n    _additional_data.max_n_tmp_vectors = *max_num_temp_vectors;\n\n  // PropertyTreeInput data_assimilation.solver.max_iterations\n  if (boost::optional<unsigned int> max_iterations =\n          database.get_optional<unsigned int>(\"solver.max_iterations\"))\n    _solver_control.set_max_steps(*max_iterations);\n\n  // PropertyTreeInput data_assimilation.solver.convergence_tolerance\n  if (boost::optional<double> tolerance =\n          database.get_optional<double>(\"solver.convergence_tolerance\"))\n    _solver_control.set_tolerance(*tolerance);\n}\n\nvoid DataAssimilator::update_ensemble(\n    std::vector<dealii::LA::distributed::Vector<double>> &sim_data,\n    std::vector<double> const &expt_data, dealii::SparseMatrix<double> &R)\n{\n  // Set some constants\n  _num_ensemble_members = sim_data.size();\n  if (sim_data.size() > 0)\n  {\n    _sim_size = sim_data[0].size();\n  }\n  else\n  {\n    _sim_size = 0;\n  }\n  _expt_size = expt_data.size();\n\n  // Get the perturbed innovation, ( y+u - Hx )\n  std::vector<dealii::Vector<double>> perturbed_innovation(\n      _num_ensemble_members);\n  for (unsigned int member = 0; member < _num_ensemble_members; ++member)\n  {\n    perturbed_innovation[member].reinit(_expt_size);\n    fill_noise_vector(perturbed_innovation[member], R);\n    dealii::Vector<double> temporary = calc_Hx(sim_data[member]);\n    for (unsigned int i = 0; i < _expt_size; ++i)\n    {\n      perturbed_innovation[member][i] += expt_data[i] - temporary[i];\n    }\n  }\n\n  // Apply the Kalman filter to the perturbed innovation, K ( y+u - Hx )\n  std::vector<dealii::LA::distributed::Vector<double>> forecast_shift =\n      apply_kalman_gain(sim_data, R, perturbed_innovation);\n\n  // Update the ensemble, x = x + K ( y+u - Hx )\n  for (unsigned int member = 0; member < _num_ensemble_members; ++member)\n  {\n    sim_data[member] += forecast_shift[member];\n  }\n}\n\nstd::vector<dealii::LA::distributed::Vector<double>>\nDataAssimilator::apply_kalman_gain(\n    std::vector<dealii::LA::distributed::Vector<double>> &vec_ensemble,\n    dealii::SparseMatrix<double> &R,\n    std::vector<dealii::Vector<double>> &perturbed_innovation)\n{\n  /*\n   * Currently this function uses GMRES to apply the inverse of HPH^T+R in the\n   * Kalman gain calculation for each ensemble member individually. Depending on\n   * the size of the datasets, the number of ensembles, and other factors doing\n   * a direct solve of (HPH^T+R)^-1 once and then applying to the perturbed\n   * innovation from each ensemble member might be more efficient.\n   */\n\n  dealii::SparsityPattern pattern_H(_expt_size, _sim_size, _expt_size);\n  dealii::SparseMatrix<double> H = calc_H(pattern_H);\n\n  dealii::FullMatrix<double> P = calc_sample_covariance_dense(vec_ensemble);\n\n  const auto op_H = dealii::linear_operator(H);\n  const auto op_P = dealii::linear_operator(P);\n  const auto op_R = dealii::linear_operator(R);\n\n  const auto op_HPH_plus_R =\n      op_H * op_P * dealii::transpose_operator(op_H) + op_R;\n\n  std::vector<dealii::LA::distributed::Vector<double>> output(\n      _num_ensemble_members,\n      dealii::LA::distributed::Vector<double>(_sim_size));\n\n  // Create non-member versions of these for use in the lambda function\n  auto solver_control = _solver_control;\n  auto additional_data = _additional_data;\n  auto sim_size = _sim_size;\n\n  // Apply the Kalman gain to the perturbed innovation for the ensemble members\n  // in parallel\n  std::transform(\n      std::execution::par, perturbed_innovation.begin(),\n      perturbed_innovation.end(), output.begin(),\n      [&](dealii::Vector<double> entry) {\n        dealii::SolverGMRES<dealii::Vector<double>> HPH_plus_R_inv_solver(\n            solver_control, additional_data);\n\n        auto op_HPH_plus_R_inv =\n            dealii::inverse_operator(op_HPH_plus_R, HPH_plus_R_inv_solver);\n\n        const auto op_K =\n            op_P * dealii::transpose_operator(op_H) * op_HPH_plus_R_inv;\n\n        // Apply the Kalman gain to each innovation vector\n        dealii::Vector<double> temporary = op_K * entry;\n\n        // Copy into a distributed vector, this is the only place where the\n        // mismatch matters, using dealii::Vector for the experimental data\n        // and dealii::LA::distributed::Vector for the simulation data.\n        dealii::LA::distributed::Vector<double> output_member(sim_size);\n        for (unsigned int i = 0; i < sim_size; ++i)\n        {\n          output_member(i) = temporary(i);\n        }\n\n        return output_member;\n      });\n\n  return output;\n}\n\ndealii::SparseMatrix<double>\nDataAssimilator::calc_H(dealii::SparsityPattern &pattern) const\n{\n  int num_expt_dof_map_entries = _expt_to_dof_mapping.first.size();\n\n  for (auto i = 0; i < num_expt_dof_map_entries; ++i)\n  {\n    auto sim_index = _expt_to_dof_mapping.second[i];\n    auto expt_index = _expt_to_dof_mapping.first[i];\n    pattern.add(expt_index, sim_index);\n  }\n\n  pattern.compress();\n\n  dealii::SparseMatrix<double> H(pattern);\n\n  for (auto i = 0; i < num_expt_dof_map_entries; ++i)\n  {\n    auto sim_index = _expt_to_dof_mapping.second[i];\n    auto expt_index = _expt_to_dof_mapping.first[i];\n    H.add(expt_index, sim_index, 1.0);\n  }\n\n  return H;\n}\n\ntemplate <int dim>\nvoid DataAssimilator::update_dof_mapping(\n    dealii::DoFHandler<dim> const &dof_handler,\n    std::pair<std::vector<int>, std::vector<int>> const &indices_and_offsets)\n{\n  std::map<dealii::types::global_dof_index, dealii::Point<dim>> indices_points;\n  dealii::DoFTools::map_dofs_to_support_points(\n      dealii::StaticMappingQ1<dim>::mapping, dof_handler, indices_points);\n  // Change the format to the one used by ArborX\n  std::vector<dealii::types::global_dof_index> dof_indices(\n      indices_points.size());\n  unsigned int pos = 0;\n  for (auto map_it = indices_points.begin(); map_it != indices_points.end();\n       ++map_it, ++pos)\n  {\n    dof_indices[pos] = map_it->first;\n  }\n\n  _expt_to_dof_mapping.first.resize(indices_and_offsets.first.size());\n  _expt_to_dof_mapping.second.resize(indices_and_offsets.first.size());\n\n  for (unsigned int i = 0; i < _expt_size; ++i)\n  {\n    for (int j = indices_and_offsets.second[i];\n         j < indices_and_offsets.second[i + 1]; ++j)\n    {\n      _expt_to_dof_mapping.first[j] = i;\n      _expt_to_dof_mapping.second[j] =\n          dof_indices[indices_and_offsets.first[j]];\n    }\n  }\n}\n\ndealii::Vector<double> DataAssimilator::calc_Hx(\n    const dealii::LA::distributed::Vector<double> &sim_ensemble_member) const\n{\n  int num_expt_dof_map_entries = _expt_to_dof_mapping.first.size();\n\n  dealii::Vector<double> out_vec(_expt_size);\n\n  // Loop through the observation map to get the observation indices\n  for (auto i = 0; i < num_expt_dof_map_entries; ++i)\n  {\n    auto sim_index = _expt_to_dof_mapping.second[i];\n    auto expt_index = _expt_to_dof_mapping.first[i];\n    out_vec(expt_index) = sim_ensemble_member(sim_index);\n  }\n\n  return out_vec;\n}\n\nvoid DataAssimilator::fill_noise_vector(dealii::Vector<double> &vec,\n                                        dealii::SparseMatrix<double> &R)\n{\n  auto vector_size = vec.size();\n\n  // Do Cholesky decomposition\n  dealii::FullMatrix<double> L(vector_size);\n  dealii::FullMatrix<double> R_full(vector_size);\n  R_full.copy_from(R);\n  L.cholesky(R_full);\n\n  // Get a vector of normally distributed values\n  dealii::Vector<double> uncorrelated_noise_vector(vector_size);\n\n  for (unsigned int i = 0; i < vector_size; ++i)\n  {\n    uncorrelated_noise_vector(i) = _normal_dist_generator(_prng);\n  }\n\n  L.vmult(vec, uncorrelated_noise_vector);\n}\n\ntemplate <typename VectorType>\ndealii::FullMatrix<double> DataAssimilator::calc_sample_covariance_dense(\n    std::vector<VectorType> vec_ensemble) const\n{\n  unsigned int num_ensemble_members = vec_ensemble.size();\n  unsigned int vec_size = 0;\n  if (vec_ensemble.size() > 0)\n  {\n    vec_size = vec_ensemble[0].size();\n  }\n\n  // Calculate the mean\n  dealii::Vector<double> mean(vec_size);\n  for (unsigned int i = 0; i < vec_size; ++i)\n  {\n    double sum = 0.0;\n    for (unsigned int sample = 0; sample < num_ensemble_members; ++sample)\n    {\n      sum += vec_ensemble[sample][i];\n    }\n    mean[i] = sum / num_ensemble_members;\n  }\n\n  // Calculate the anomaly\n  dealii::FullMatrix<double> anomaly(vec_size, num_ensemble_members);\n  for (unsigned int member = 0; member < num_ensemble_members; ++member)\n  {\n    for (unsigned int i = 0; i < vec_size; ++i)\n    {\n      anomaly(i, member) = (vec_ensemble[member][i] - mean[i]) /\n                           std::sqrt(num_ensemble_members - 1.0);\n    }\n  }\n\n  dealii::FullMatrix<double> cov(vec_size);\n  anomaly.mTmult(cov, anomaly);\n\n  return cov;\n}\n\n// Explicit instantiation\ntemplate void DataAssimilator::update_dof_mapping<2>(\n    dealii::DoFHandler<2> const &dof_handler,\n    std::pair<std::vector<int>, std::vector<int>> const &indices_and_offsets);\ntemplate void DataAssimilator::update_dof_mapping<3>(\n    dealii::DoFHandler<3> const &dof_handler,\n    std::pair<std::vector<int>, std::vector<int>> const &indices_and_offsets);\ntemplate dealii::FullMatrix<double>\nDataAssimilator::calc_sample_covariance_dense<dealii::Vector<double>>(\n    std::vector<dealii::Vector<double>> vec_ensemble) const;\ntemplate dealii::FullMatrix<double>\nDataAssimilator::calc_sample_covariance_dense<\n    dealii::LA::distributed::Vector<double>>(\n    std::vector<dealii::LA::distributed::Vector<double>> vec_ensemble) const;\n\n} // namespace adamantine\n", "meta": {"hexsha": "4c573b2b036e976efaacc977cb6d81aa960ce58b", "size": 10163, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/DataAssimilator.cc", "max_stars_repo_name": "Rombur/adamantine", "max_stars_repo_head_hexsha": "45dd37397680fad1eaa64dbb311724c4f727a675", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-09-03T02:08:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-03T01:26:41.000Z", "max_issues_repo_path": "source/DataAssimilator.cc", "max_issues_repo_name": "Rombur/adamantine", "max_issues_repo_head_hexsha": "45dd37397680fad1eaa64dbb311724c4f727a675", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 74.0, "max_issues_repo_issues_event_min_datetime": "2016-08-31T18:10:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T01:51:44.000Z", "max_forks_repo_path": "source/DataAssimilator.cc", "max_forks_repo_name": "Rombur/adamantine", "max_forks_repo_head_hexsha": "45dd37397680fad1eaa64dbb311724c4f727a675", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-11-12T15:43:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-19T02:58:56.000Z", "avg_line_length": 33.6523178808, "max_line_length": 80, "alphanum_fraction": 0.7074682672, "num_tokens": 2709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.29626561919677047}}
{"text": "/**************************************************************\n * \n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the 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,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n * \n *************************************************************/\n\n\n\n// MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_basegfx.hxx\"\n#include <osl/diagnose.h>\n\n#include <basegfx/curve/b2dcubicbezier.hxx>\n\n#include <basegfx/tools/debugplotter.hxx>\n#include <boost/bind.hpp>\n\n\nnamespace basegfx\n{\n    namespace\n    {\n        void outputHeader( const ::rtl::OString& rTitle,\n                           ::std::ostream* \t\t pStm )\n        {\n            // output gnuplot setup\n            if( pStm )\n            {\n                *pStm << \"#!/usr/bin/gnuplot -persist\" << ::std::endl <<\n                    \"#\" << ::std::endl <<\n                    \"# automatically generated by basegfx, don't change!\" << ::std::endl <<\n                    \"#\" << ::std::endl <<\n                    \"#   --- \" << rTitle.getStr() << \" ---\" << ::std::endl <<\n                    \"#\" << ::std::endl <<\n                    \"set parametric\" << ::std::endl <<\n                    \"# set terminal postscript eps enhanced color \" << ::std::endl <<\n                    \"# set output \\\"plot.eps\\\"\" << ::std::endl <<\n                    // This function plots a cubic bezier curve. P,q,r,s\n                    // are the control point elements of the corresponding\n                    // output coordinate component (i.e. x components for\n                    // the x plot, and y components for the y plot)\n                    \"cubicBezier(p,q,r,s,t) = p*(1-t)**3+q*3*(1-t)**2*t+r*3*(1-t)*t**2+s*t**3\" << ::std::endl <<\n                    // This function plots the derivative of a cubic\n                    // bezier curve. P,q,r,s are the control point\n                    // components of the _original_ curve\n                    \"cubicBezDerivative(p,q,r,s,t) = 3*(q-p)*(1-t)**2+6*(r-q)*(1-t)*t+3*(s-r)*t**2\" << ::std::endl <<\n                    // Plot a line's component of a line between a and b\n                    // (where a and b should be the corresponding\n                    // components of the line's start and end point,\n                    // respectively)\n                    \"line(p,q,r) = p*(1-t)+q*t\" << ::std::endl <<\n                    // Plot a line's x component of a line in implicit\n                    // form ax + by + c = 0\n                    \"implicitLineX(a,b,c,t) = a*-c + t*-b\" << ::std::endl <<\t\t\t\t\t\t\t\t\t \n                    // Plot a line's y component of a line in implicit\n                    // form ax + by + c = 0\n                    \"implicitLineY(a,b,c,t) = b*-c + t*a\" << ::std::endl <<\t\t\t\t\t\t\t\t\t \t \n                    \"pointmarkx(c,t) = c-0.03*t\" << ::std::endl <<\t\t\t\t\t\t\t\t\t\t // hack for displaying single points in parametric form\n                    \"pointmarky(c,t) = c+0.03*t\" << ::std::endl <<\t\t\t\t\t\t\t\t\t\t // hack for displaying single points in parametric form\n                    \"# end of setup\" << ::std::endl;\n            }\n            else\n            {\n                OSL_TRACE( \"#!/usr/bin/gnuplot -persist\\n\",\n                           \"#\\n\",\n                           \"# automatically generated by basegfx, don't change!\\n\",\n                           \"#\\n\",\n                           \"#   --- %s ---\\n\",\n                           \"#\\n\",\n                           \"set parametric\\n\",\n                           // This function plots a cubic bezier curve. P,q,r,s\n                           // are the control point elements of the corresponding\n                           // output coordinate component (i.e. x components for\n                           // the x plot, and y components for the y plot)\n                           \"cubicBezier(p,q,r,s,t) = p*(1-t)**3+q*3*(1-t)**2*t+r*3*(1-t)*t**2+s*t**3\\n\",\n                           // This function plots the derivative of a cubic\n                           // bezier curve. P,q,r,s are the control point\n                           // components of the _original_ curve\n                           \"cubicBezDerivative(p,q,r,s,t) = 3*(q-p)*(1-t)**2+6*(r-q)*(1-t)*t+3*(s-r)*t**2\\n\",\n                           // Plot a line's component of a line between a and b\n                           // (where a and b should be the corresponding\n                           // components of the line's start and end point,\n                           // respectively)\n                           \"line(p,q,r) = p*(1-t)+q*t\\n\",\n                           // Plot a line's x component of a line in implicit\n                           // form ax + by + c = 0\n                           \"implicitLineX(a,b,c,t) = a*-c + t*-b\\n\",\t\t\t\t\t\t\t\t\t \n                           // Plot a line's y component of a line in implicit\n                           // form ax + by + c = 0\n                           \"implicitLineY(a,b,c,t) = b*-c + t*a\\n\",\t\t\t\t\t\t\t\t\t \t \n                           \"pointmarkx(c,t) = c-0.03*t\\n\",\t\t\t\t\t\t\t\t\t\t // hack for displaying single points in parametric form\n                           \"pointmarky(c,t) = c+0.03*t\\n\",\t\t\t\t\t\t\t\t\t\t // hack for displaying single points in parametric form\n                           \"# end of setup\\n\",\n                           rTitle.getStr() );\n            }\n        }\n\n        class Writer\n        {\n        public:\n            Writer( ::std::ostream* pStm ) :\n                mpStream( pStm )\n            {\n            }\n            \n            void outputPoint( const ::std::pair< B2DPoint, ::rtl::OString >& rElem )\n            {\n                if( mpStream )\n                    *mpStream << \" \" << rElem.first.getX() << \"\\t\" << rElem.first.getY() << ::std::endl;\n                else\n                    OSL_TRACE( \" %f\\t%f\\n\", rElem.first.getX(), rElem.first.getY() );\n            }\n            \n            void outputVector( const ::std::pair< B2DVector, ::rtl::OString >& rElem )\n            {\n                if( mpStream )\n                    *mpStream << \" \" << rElem.first.getX() << \"\\t\" << rElem.first.getY() << ::std::endl << ::std::endl;\n                else\n                    OSL_TRACE( \" %f\\t%f\\n\\n\", rElem.first.getX(), rElem.first.getY() );\n            }\n            \n            void outputRect( const ::std::pair< B2DRange, ::rtl::OString >& rElem )\n            {\n                const double nX0( rElem.first.getMinX() );\n                const double nY0( rElem.first.getMinY() );\n                const double nX1( rElem.first.getMaxX() );\n                const double nY1( rElem.first.getMaxY() );\n                \n                if( mpStream )\n                    *mpStream << \" \" \n                              << nX0 << \"\\t\" << nY0 << \"\\t\"\n                              << nX1 << \"\\t\" << nY0 << \"\\t\"\n                              << nX1 << \"\\t\" << nY1 << \"\\t\"\n                              << nX0 << \"\\t\" << nY1 << \"\\t\"\n                              << nX0 << \"\\t\" << nY0 << ::std::endl << ::std::endl;\n\n                else\n                    OSL_TRACE( \" %f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\n\\n\", \n                               nX0, nY0,\n                               nX1, nY0,\n                               nX1, nY1,\n                               nX0, nY1,\n                               nX0, nY0 );\n            }\n\n        private:\n            ::std::ostream* \tmpStream;            \n        };\n    }\n\n    DebugPlotter::DebugPlotter( const sal_Char* pTitle ) :\n        maTitle( pTitle ),\n        maPoints(),\n        maVectors(),\n        maRanges(),\n        maPolygons(),\n        mpOutputStream(NULL)\n    {\n    }\n\n    DebugPlotter::DebugPlotter( const sal_Char* pTitle,\n                                ::std::ostream& rOutputStream ) :\n        maTitle( pTitle ),\n        maPoints(),\n        maVectors(),\n        maRanges(),\n        maPolygons(),\n        mpOutputStream(&rOutputStream)\n    {\n    }\n\n    DebugPlotter::~DebugPlotter()\n    {\n        const bool bHavePoints( !maPoints.empty() );\n        const bool bHaveVectors( !maVectors.empty() );\n        const bool bHaveRanges( !maRanges.empty() );\n        const bool bHavePolygons( !maPolygons.empty() );\n\n        if( bHavePoints ||\n            bHaveVectors ||\n            bHaveRanges ||\n            bHavePolygons )\n        {\n            outputHeader( maTitle, mpOutputStream );\n            \n            print( \"\\n\\n# parametric primitive output\\n\"\n                   \"plot [t=0:1] \\\\\\n\" );\n\n            // output plot declarations for used entities\n            bool bNeedColon( false );\n            if( bHavePoints )\n            {\n                print( \" '-' using ($1):($2) title \\\"Points\\\" with points\" );\n                bNeedColon = true;\n            }\n            if( bHaveVectors )\n            {\n                if( bNeedColon )\n                    print( \", \\\\\\n\" );\n\n                print( \" '-' using ($1):($2) title \\\"Vectors\\\" with lp\" );\n                bNeedColon = true;\n            }\n            if( bHaveRanges )\n            {\n                if( bNeedColon )\n                    print( \", \\\\\\n\" );\n\n                print( \" '-' using ($1):($2) title \\\"Ranges\\\" with lines\" );\n                bNeedColon = true;\n            }\n            if( bHavePolygons )\n            {\n                const ::std::size_t nSize( maPolygons.size() );\n                for( ::std::size_t i=0; i<nSize; ++i )\n                {\n                    if( maPolygons.at(i).first.areControlPointsUsed() )\n                    {\n                        const B2DPolygon& rCurrPoly( maPolygons.at(i).first );\n                        \n                        const sal_uInt32 nCount( rCurrPoly.count() );\n                        for( sal_uInt32 k=0; k<nCount; ++k )\n                        {\n                            if( bNeedColon )\n                                print( \", \\\\\\n\" );\n\n                            const B2DPoint& rP0( rCurrPoly.getB2DPoint(k) );\n                            const B2DPoint& rP1( rCurrPoly.getNextControlPoint(k) );\n                            const B2DPoint& rP2( rCurrPoly.getPrevControlPoint((k + 1) % nCount) );\n                            const B2DPoint& rP3( k+1<nCount ? rCurrPoly.getB2DPoint(k+1) : rCurrPoly.getB2DPoint(k) );\n\n                            if( mpOutputStream )\n                                *mpOutputStream << \"  cubicBezier(\" \n                                                << rP0.getX() << \",\"\n                                    << rP1.getX() << \",\"\n                                    << rP2.getX() << \",\"\n                                    << rP3.getX() << \",t), \\\\\\n   cubicBezier(\"\n                                    << rP0.getY() << \",\"\n                                    << rP1.getY() << \",\"\n                                    << rP2.getY() << \",\"\n                                    << rP3.getY() << \",t)\";\n                            else\n                                OSL_TRACE( \"  cubicBezier(%f,%f,%f,%f,t), \\\\\\n\"\n                                           \"   cubicBezier(%f,%f,%f,%f,t)\",\n                                           rP0.getX(),\n                                           rP1.getX(),\n                                           rP2.getX(),\n                                           rP3.getX(),\n                                           rP0.getY(),\n                                           rP1.getY(),\n                                           rP2.getY(),\n                                           rP3.getY() );\n\n                            bNeedColon = true;\n                        }\n                    }\n                    else\n                    {\n                        if( bNeedColon )\n                            print( \", \\\\\\n\" );\n                        \n                        if( mpOutputStream )\n                            *mpOutputStream << \" '-' using ($1):($2) title \\\"Polygon \"\n                                            << maPolygons.at(i).second.getStr() << \"\\\" with lp\";\n                        else\n                            OSL_TRACE( \" '-' using ($1):($2) title \\\"Polygon %s\\\" with lp\",\n                                       maPolygons.at(i).second.getStr() );\n\n                        bNeedColon = true;\n                    }\n                }\n            }\n\n            if( bHavePoints )\n            {\n                Writer aWriter( mpOutputStream );\n\n                ::std::for_each( maPoints.begin(),\n                                 maPoints.end(),\n                                 ::boost::bind( &Writer::outputPoint,\n                                                ::boost::ref( aWriter ),\n                                                _1 ) );\n                print( \"e\\n\" );\n            }\n\n            if( bHaveVectors )\n            {\n                Writer aWriter( mpOutputStream );\n\n                ::std::for_each( maVectors.begin(),\n                                 maVectors.end(),\n                                 ::boost::bind( &Writer::outputVector,\n                                                ::boost::ref( aWriter ),\n                                                _1 ) );\n                print( \"e\\n\" );\n            }\n\n            if( bHaveRanges )\n            {\n                Writer aWriter( mpOutputStream );\n\n                ::std::for_each( maRanges.begin(),\n                                 maRanges.end(),\n                                 ::boost::bind( &Writer::outputRect,\n                                                ::boost::ref( aWriter ),\n                                                _1 ) );\n                print( \"e\\n\" );\n            }\n\n            if( bHavePolygons )\n            {\n                const ::std::size_t nSize( maPolygons.size() );\n                for( ::std::size_t i=0; i<nSize; ++i )\n                {\n                    if( !maPolygons.at(i).first.areControlPointsUsed() )\n                    {\n                        const B2DPolygon& rCurrPoly( maPolygons.at(i).first );\n\n                        const sal_uInt32 nCount( rCurrPoly.count() );\n                        for( sal_uInt32 k=0; k<nCount; ++k )\n                        {\n                            const B2DPoint& rP( rCurrPoly.getB2DPoint(k) );\n\n                            if( mpOutputStream )\n                                *mpOutputStream << \" \" << rP.getX() << \",\" << rP.getY();\n                            else\n                                OSL_TRACE( \" %f,%f\",\n                                           rP.getX(),\n                                           rP.getX() );\n                        }\n\n                        print( \"\\ne\\n\" );\n                    }\n                }\n            }\n        }\n    }\n\n    void DebugPlotter::plot( const B2DPoint& rPoint,\n                             const sal_Char* pTitle )\n    {\n        maPoints.push_back( ::std::make_pair( rPoint,\n                                              ::rtl::OString( pTitle ) ) );\n    }\n\n    void DebugPlotter::plot( const B2DVector&\trVec,\n                             const sal_Char* \tpTitle )\n    {\n        maVectors.push_back( ::std::make_pair( rVec,\n                                               ::rtl::OString( pTitle ) ) );\n    }\n\n    void DebugPlotter::plot( const B2DCubicBezier&\trBezier,\n                             const sal_Char* \t\tpTitle )\n    {\n        B2DPolygon aPoly;\n        aPoly.append(rBezier.getStartPoint());\n\t\taPoly.appendBezierSegment(rBezier.getControlPointA(), rBezier.getControlPointB(), rBezier.getEndPoint());\n        maPolygons.push_back( ::std::make_pair( aPoly,\n                                                ::rtl::OString( pTitle ) ) );\n    }\n\n    void DebugPlotter::plot( const B2DRange& rRange,\n                             const sal_Char* pTitle )\n    {\n        maRanges.push_back( ::std::make_pair( rRange,\n                                              ::rtl::OString( pTitle ) ) );\n    }\n\n    void DebugPlotter::plot( const B2DPolygon&\trPoly,\n                             const sal_Char* \tpTitle )\n    {\n        maPolygons.push_back( ::std::make_pair( rPoly,\n                                                ::rtl::OString( pTitle ) ) );\n    }\n\n    void DebugPlotter::plot( const B2DPolyPolygon&\trPoly,\n                             const sal_Char* \t\tpTitle )\n    {\n        const ::rtl::OString aTitle( pTitle );\n        const sal_uInt32 nCount( rPoly.count() );\n        for( sal_uInt32 i=0; i<nCount; ++i )\n            maPolygons.push_back( ::std::make_pair( rPoly.getB2DPolygon( i ),\n                                                    aTitle ) );\n    }\n\n    void DebugPlotter::print( const sal_Char* pStr )\n    {\n        if( mpOutputStream )\n            *mpOutputStream << pStr;\n        else\n            OSL_TRACE( pStr );\n    }\n}\n", "meta": {"hexsha": "e22908e897b37d1bf4730ffaa5f44dc3419516a5", "size": 17333, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "main/basegfx/source/tools/debugplotter.cxx", "max_stars_repo_name": "Grosskopf/openoffice", "max_stars_repo_head_hexsha": "93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 679.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T06:34:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T01:06:03.000Z", "max_issues_repo_path": "main/basegfx/source/tools/debugplotter.cxx", "max_issues_repo_name": "Grosskopf/openoffice", "max_issues_repo_head_hexsha": "93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 102.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T08:51:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T12:13:49.000Z", "max_forks_repo_path": "main/basegfx/source/tools/debugplotter.cxx", "max_forks_repo_name": "Grosskopf/openoffice", "max_forks_repo_head_hexsha": "93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 331.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T11:40:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T04:07:51.000Z", "avg_line_length": 42.2756097561, "max_line_length": 132, "alphanum_fraction": 0.389430566, "num_tokens": 3720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.29626561919677047}}
{"text": "#ifndef SPECIAL_HPP\n#define SPECIAL_HPP\n\n#include <boost/shared_ptr.hpp>\n#include \"../workspace.hpp\"\n#include <cmath>\n#include <memory>\n\nnamespace dqmc {\n    namespace la {\n\n#ifdef USE_DD       \n\tinline void copy_to_dd(pmat_t& in, dd_mat& out) {\n\t    for (int c = 0; c < in.cols(); ++c) {\n\t\tfor (int r = 0; r < in.rows(); ++r) {\n\t\t    out(r, c) = ddouble(in(r, c));\n\t\t}\n\t    }\n\t}\n\t\n\tinline void copy_to_dd(pvec_t& in, dd_vec& out) {\n\t    for (int c = 0; c < in.size(); ++c) {\n\t\tout(c) = ddouble(in(c));\n\t    }\n\t}\n\n\n\tinline void copy_from_dd(dd_mat& in, pmat_t& out) {\n\t    for (int c = 0; c < in.cols(); ++c) {\n\t\tfor (int r = 0; r < in.rows(); ++r) {\t\t    \n\t\t    out(r, c) = to_double(in(r, c));\n\t\t}\n\t    }\n\t}\n\n\n\tinline void copy_from_dd(dd_vec& in, pvec_t& out) {\n\t    for (int c = 0; c < in.rows(); ++c) {\n\t\tout(c) = to_double(in(c));\n\t    }\n\t}\n\n\n\tinline void dd_normalize(dd_vec&__restrict__ v) {\n\t    dd_real norm = 0;\n\n\t    for (int i = 0; i < v.rows() * v.cols(); ++i) {\n\t\tif ((v(i) * v(i)).isnan()) {\n\t\t    std::cout << v(i) << \" squared is nan\" << std::endl;\n\t\t    throw std::runtime_error(\"error\");\n\t\t}\n\t\tnorm += v(i) * v(i);\n\t    }\n\n\t    v /= sqrt(norm);\n\t}\n\n\t\n\tinline void dd_dot(dd_vec&__restrict__ v1, dd_vec&__restrict__ v2,\n\t\t\t   dd_real&__restrict__ result) {\n\t    result = dd_real(0, 0);\n\n\t    for (int i = 0; i < v1.rows() * v1.cols(); ++i) {\n\t\tif ((v1(i) * v2(i)).isnan()) {\n\t\t    std::cout << v1(i) << \" times \" << v2(i) << \" is nan\" << std::endl;\n\t\t    throw std::runtime_error(\"error\");\n\t\t}\n\t\tresult += v1(i) * v2(i);\n\t    }\n\t}\n\n\n\tinline void dd_from_col(int c, const dd_mat& in, dd_vec& out) {\n\t    for (int r = 0; r < in.rows(); ++r) {\n\t\tout(r) = in(r, c);\n\t    }\n\t}\n\n\n\tinline void dd_to_col(int c, const dd_vec& in, dd_mat& out) {\n\t    for (int r = 0; r < in.rows(); ++r) {\n\t\tout(r, c) = in(r);\n\t    }\n\t}\n\n\n\tinline void dd_from_row(int r, const dd_mat& in, dd_vec& out) {\n\t    for (int c = 0; c < in.cols(); ++c) {\n\t\tout(c) = in(r, c);\n\t    }\n\t}\n\n\n\tinline void dd_to_row(int r, const dd_vec& in, dd_mat& out) {\n\t    for (int c = 0; c < out.cols(); ++c) {\n\t\tout(r, c) = in(c);\n\t    }\n\t}\n\n\n\tinline void dd_thin_col_to_invertible(dd_mat& in, dd_mat& temp, dd_mat& out,\n\t\t\t\t\t      dd_vec& t_vec_1, dd_vec& t_vec_2) {\n\t    using namespace std;\n\t    \n\t    for (int c = 0; c < in.cols(); ++c) {\n\t\tfor (int r = 0; r < in.rows(); ++r) {\n\t\t    temp(r, c) = in(r,c);\n\t\t    out(r, c) = in(r, c);\n\t\t}\n\t    }\n\t    \n\t    for (int c = in.cols(); c < out.cols(); ++c) {\n\t\tfor (int r = 0; r < in.rows(); ++r) {\n\t\t    temp(r, c) = ddrand();// / dd_real::_max;\n\t\t}\n\t    }\n\n\t    // cout << \"Randomized full col\" << endl;\n\t    // dqmc::la::print_matrix(temp.rows(), temp.cols(), temp);\n\t    // Gram-Schmidt orthogonalization\n\t    dd_real projection;\n\n\t    for (int iter = 0; iter < 5; ++iter) {\n\t\t// cout << \"First iteration\" << endl;\n\t\t\n\t\tfor (int c = in.cols(); c < out.cols(); ++c) {\n\t\t    // cout << \"from_col\" << endl;\n\t\t    dd_from_col(c, temp, t_vec_1);\n\n\t\t    for (int c2 = 0; c2 < c; ++c2) {\n\t\t\t// cout << \"c2\" << endl;\n\t\t\tdd_from_col(c2, out, t_vec_2);\n\t\t\t// cout << \"dd_dot\" << endl;\n\t\t\tdd_dot(t_vec_1, t_vec_2, projection);\n\t\t\t// cout << projection << endl;\n\t\t\tt_vec_1 -= projection * t_vec_2;\n\t\t    }\n\t\t    \n\t\t    dd_normalize(t_vec_1);\n\t\t    dd_to_col(c, t_vec_1, out);\n\t\t}\n\t\ttemp = out;\n\t    }\n\t    // dqmc::la::print_matrix(out.rows(), out.cols(), out);\n\t}\n\n\n\tinline void dd_thin_row_to_invertible(dd_mat& in, dd_mat& temp, dd_mat& out,\n\t\t\t\t\t      dd_vec& t_vec_1, dd_vec& t_vec_2) {\n\t    using namespace std;\n\t    \n\t    for (int c = 0; c < in.cols(); ++c) {\n\t\tfor (int r = 0; r < in.rows(); ++r) {\n\t\t    temp(r, c) = in(r,c);\n\t\t    out(r, c) = in(r, c);\n\t\t}\n\t    }\n\t    \n\t    for (int c = in.rows(); c < out.rows(); ++c) {\n\t\tfor (int r = 0; r < in.cols(); ++r) {\n\t\t    temp(r, c) = ddrand();// / dd_real::_max;\n\t\t    if (isnan(temp(r, c))) {\n\t\t\tcout << \"Random nan???\" << endl;\n\t\t\tthrow std::runtime_error(\"no\");\n\t\t    }\n\t\t}\n\t    }\n\n\t    dd_real projection;\n\n\t    for (int iter = 0; iter < 5; ++iter) {\n\t\tfor (int r = in.rows(); r < out.rows(); ++r) {\n\t\t    dd_from_row(r, temp, t_vec_1);\n\t\t    \n\t\t    for (int r2 = 0; r2 < r; ++r2) {\n\t\t\tdd_from_row(r2, out, t_vec_2);\n\t\t\tdd_dot(t_vec_1, t_vec_2, projection);\n\t\t\tt_vec_1 -= projection * t_vec_2;\n\t\t    }\n\t\t    \n\t\t    dd_normalize(t_vec_1);\n\t\t    dd_to_row(r, t_vec_1, out);\n\t\t}\n\t\ttemp = out;\n\t    }\n\t}\n#endif\n\t\n\tinline void randomize(pmat_t& M) {\n\t    for (int r = 0; r < M.rows(); r++) {\n\t\tfor ( int c = 0; c < M.cols(); c++) {\n\t\t    M(r, c) = (std::rand() % RAND_MAX)/double(RAND_MAX);\n\t\t}\n\t    }\n\t    std::srand (std::rand());\n\t}\n\n\n\tinline void normalize(pvec_t&__restrict__ v) {\n\t    pdouble_t norm = 0;\n\n\t    for (int i = 0; i < v.size(); ++i) {\n\t\tnorm += v(i) * v(i);\n\t    }\n\n\t    for (int i = 0; i < v.size(); ++i) {\n\t\tv(i) /= sqrt(norm);\n\t    }\n\t}\n\n\tinline void random_with_inverse(pmat_t&__restrict__ in,\n\t\t\t\t\tpmat_t&__restrict__ in_inv) {\n\t    throw std::runtime_error(\"Broken\");\n\t    // for (int c = 0; c < in.cols(); ++c) {\n\t    // \tfor (int r = 0; r < in.rows(); ++r) {\n\t    // \t    in(r, c) = (std::rand() % RAND_MAX)/double(RAND_MAX);\n\t    // \t}\n\t    // }\n\n\t    // pmat_t U = in;\n\t    // pmat_t T = in;\n\t    // pvec_t D(in.rows());\n\t    // pmat_t U_inv = in;\n\t    // pmat_t T_inv = in;\n\n\t    // decompose_dgejsv_nt(in, U, D, T);\n\t    // matrix_transpose(U, T_inv);\n\t    // matrix_transpose(T, U_inv);\n\t    // thin_inv_sandwich(U_inv, D, T_inv, in_inv);\n\t}\n\n\t\n\tinline void random_orthogonal(pmat_t&__restrict__ in, boost::shared_ptr<dqmc::workspace> ws) {\n\t    for (int c = 0; c < in.cols(); ++c) {\n\t\tfor (int r = 0; r < in.rows(); ++r) {\n\t\t    in(r, c) = (std::rand() % RAND_MAX)/double(RAND_MAX);\n\t\t}\n\t    }\n\t    pdouble_t projection, inner_prod;\n\n\t    pvec_t vec_1(in.rows());\n\t    pvec_t vec_2(in.rows());\n\t    pvec_t vec_3(in.rows());\n\n\t    for(int c = 0; c < in.cols(); ++c) {\n\t\tcol(c, in, vec_1);\n\t\tnormalize(vec_1);\n\t\tto_col(c, in, vec_1);\n\t\tdot(vec_1, vec_1, projection);\n\t\t// std::cout << \"Projection of \" << c << \" - \" << projection << std::endl;\n\t    }\n\t    // gram-Schmidt orthogonalization\n\n\t    for (int iter = 0; iter < 5; ++iter) {\n\t\tpmat_t mat_1 = in;\n\t\tfor(int c = 0; c < in.cols(); ++c) {\n\t\t    col(c, in, vec_1);\n\t\t    dot(vec_1, vec_1, projection);\n\t\t    // std::cout << \"Before Projection of \" << c << \" - \" << projection << std::endl;\n\t\t}\n\n\t\tfor (int i = 1; i < in.rows(); ++i) {\n\t\t    col(i, mat_1, vec_2);\n\t\t    col(i, mat_1, vec_3);\n\n\t\t    for (int j = 0; j < i; ++j) {\n\t\t\tcol(j, mat_1, vec_1);\n\t\t\t\n\t\t\tdot(vec_1, vec_3, projection);\n\t\t\tdot(vec_1, vec_1, inner_prod);\n\t\t\tvec_2 -= projection/inner_prod * vec_1;\t\t\t\n\t\t    }\n\t\t    normalize(vec_2);\n\t\t    to_col(i, mat_1, vec_2);\t\t    \n\t\t}\n\t\tin = mat_1;\n\t\t// std::cout << \"Done with iter \" << iter << std::endl;\n\t\t// for(int c = 0; c < in.cols(); ++c) {\n\t\t//     col(c, in, vec_1);\n\t\t//     dot(vec_1, vec_1, projection);\n\t\t//     std::cout << \"Projection of \" << c << \" - \" << projection << std::endl;\n\t\t// }\n\n\t    }\t    \n\t    // for(int c = 0; c < in.cols(); ++c) {\n\t    // \tcol(c, in, vec_1);\n\t    // \tdot(vec_1, vec_1, projection);\n\t    // \tstd::cout << \"Projection of \" << c << \" - \" << projection << std::endl;\n\t    // }\n\t}\n\t\n\n\tinline void tiny_to_invertible(const pmat_t&__restrict__ in, const pmat_t& trans, pmat_t&__restrict__ out) {\t   \n\t    // out.zeros();\n\t    out.block(0, 0, in.rows(), in.cols()) = in;\n\t    out.block(in.rows(), in.cols(), trans.rows(), trans.cols()) = trans;\n\t}\n\n\n\tinline void tiny_plus_random(const pmat_t&__restrict__ in, pmat_t& out) {\t   \n\t    // out.zeros();\n\t    out.block(0, 0, in.rows(), in.cols()) = in;\n\t    out.block(in.rows(), in.cols(), out.rows() - in.rows(), out.cols() - in.cols()).setRandom();\n\t}\n\n\n\tinline void thin_col_plus_random(const pmat_t&__restrict__ in, pmat_t&__restrict__ out) {\n\t    out.block(0, 0, in.rows(), in.cols()) = in;\n\t    out.block(0, in.cols(), out.rows(), out.cols() - in.cols()).setRandom();\n\t}\n\t\n\tinline void thin_col_to_invertible(const pmat_t&__restrict__ in, pmat_t&__restrict__ out) {\n\t    using namespace std;\n\t    out.block(0, 0, in.rows(), in.cols()) = in;\n\t    out.block(0, in.cols(), out.rows(), out.cols() - in.cols()).setRandom();\n\n\t    // Gram-Schmidt orthogonalization\n\t    pdouble_t projection;\n\n\t    for (int iter = 0; iter < 2; ++iter) {\n\t\tfor (int c = in.cols(); c < out.cols(); ++c) {\n\t\t    for (int c2 = 0; c2 < c; ++c2) {\n\t\t\tprojection = out.col(c).transpose() * out.col(c2);\n\t\t\tout.col(c) -= projection * out.col(c2);\n\t\t    }\t\t    \n\t\t    out.col(c).normalize();\t\t    \n\t\t}\n\t    }\n\t}\n\n\t\n\tinline void thin_col_to_invertible_old(const pmat_t&__restrict__ in, pmat_t&__restrict__ out, \n\t\t\t\t\t       dqmc::workspace& ws) {\n\t    using namespace std;\n\t    // out.zeros();\n\t    for (int c = 0; c < in.cols(); ++c) {\n\t\tfor (int r = 0; r < in.rows(); ++r) {\n\t\t    ws.la_mat_1(r, c) = in(r,c);\n\t\t    out(r, c) = in(r, c);\n\t\t}\n\t    }\n\t    // return;\n\n\t    for (int c = in.cols(); c < out.cols(); ++c) {\n\t\tfor (int r = 0; r < in.rows(); ++r) {\n\t\t    ws.la_mat_1(r, c) = (std::rand() % RAND_MAX)/double(RAND_MAX);\n\t\t    // for (int o = 0; o < in.rows()*in.cols(); o++) {\n\t\t    // \tif (!(fabs(in((r * in.rows() + c * in.cols() + o) % in.rows(), \n\t\t    // \t\t      (r * in.cols() + c * in.rows() + o) % in.cols())) == 0)) {\n\t\t    // \t    ws.la_mat_1(r, c) = fabs(in((r * in.rows() + c * in.cols() + o) % in.rows(), \n\t\t    // \t\t\t\t\t (r * in.cols() + c * in.rows() + o) % in.cols()));\n\t\t    // \t    break;\n\t\t    // \t}\n\t\t    // }\n\t\t    // ws.la_mat_1(r, c) = 0.;\n\n\t\t    if (r == c) {\n\t\t\tif (ws.la_mat_1(r, c) == 0) { ws.la_mat_1(r, c) = 1.;\t}\n\t\t\tws.la_mat_1(r, c) *= -1;\n\t\t    }\n\t\t}\n\t    }\n\t    // Gram-Schmidt orthogonalization\n\t    pdouble_t projection;\n\n\t    for (int iter = 0; iter < 5; ++iter) {\n\t\tfor (int c = in.cols(); c < out.cols(); ++c) {\n\t\t    //col(c, ws.la_mat_1, ws.la_vec_1);\n\t\t    ws.la_vec_1 = ws.la_mat_1.col(c);\n\t\t    \n\t\t    for (int c2 = 0; c2 < c; ++c2) {\n\t\t\t// col(c2, out, ws.la_vec_2);\n\t\t\tws.la_vec_2 = out.col(c2);\n\t\t\t// dot(ws.la_vec_1, ws.la_vec_2, projection);\n\t\t\tprojection = ws.la_vec_1.transpose() * ws.la_vec_2;\n\t\t\tws.la_vec_1 -= projection * ws.la_vec_2;\n\t\t    }\t\t    \n\t\t    // normalize(ws.la_vec_1);\n\t\t    ws.la_vec_1.normalize();\n\t\t    // to_col(c, out, ws.la_vec_1);\n\t\t    out.col(c) = ws.la_vec_1;\n\t\t}\n\t\tws.la_mat_1 = out;\n\t    }\n\t}\n\n\n\tinline void thin_row_plus_random(const pmat_t&__restrict__ in,\n\t\t\t\t\t pmat_t&__restrict__ out) {\n\t    out.block(0, 0, in.rows(), in.cols()) = in;\n\t    out.block(in.rows(), 0, out.rows() - in.rows(), in.cols()).setRandom();\n\t}\n\n\tinline void thin_row_to_invertible(const pmat_t&__restrict__ in,\n\t\t\t\t\t   pmat_t&__restrict__ out) {\n\t    out.block(0, 0, in.rows(), in.cols()) = in;\n\t    out.block(in.rows(), 0, out.rows() - in.rows(), in.cols()).setRandom();\n\t    \n\t    // Gram-Schmidt orthogonalization\n\t    pdouble_t projection;\n\n\t    for (int iter = 0; iter < 2; ++iter) {\n\t\tfor (int r = in.rows(); r < out.rows(); ++r) {\n\t\t    for (int r2 = 0; r2 < r; ++r2) {\n\t\t\tprojection = out.row(r) * out.row(r2).transpose();\n\t\t\tout.row(r) -= projection * out.row(r2);\n\t\t    }\n\t\t    out.row(r).normalize();\n\t\t}\n\t    }\n\t}\n\n\n\tinline void thin_row_to_invertible_old(const pmat_t&__restrict__ in,\n\t\t\t\t\t       pmat_t&__restrict__ out, \n\t\t\t\t\t       dqmc::workspace& ws) {\n\t    // out.zeros();\n\t    for (int c = 0; c < in.cols(); ++c) {\n\t\tfor (int r = 0; r < in.rows(); ++r) {\n\t\t    ws.la_mat_1(r, c) = in(r,c);\n\t\t    out(r, c) = in(r, c);\n\t\t}\n\t    }\n\t    // return;\n\t    \n\t    for (int c = 0; c < out.cols(); ++c) {\n\t\tfor (int r = in.rows(); r < out.rows(); ++r) {\n\t\t    ws.la_mat_1(r, c) = (std::rand() % RAND_MAX)/double(RAND_MAX);\n\t\t    if (r == c) {\n\t\t\tif (ws.la_mat_1(r, c) == 0) { ws.la_mat_1(r, c) = 1.;\t}\n\t\t\tws.la_mat_1(r, c) *= -1;\n\t\t    }\n\t\t}\n\t    }\n\t\t\n\n\t    // Gram-Schmidt orthogonalization\n\t    pdouble_t projection;\n\t    vec temp = ws.la_mat_1.row(0);\n\n\t    for (int iter = 0; iter < 5; ++iter) {\n\t\tfor (int r = in.rows(); r < out.rows(); ++r) {\n\t\t    row(r, ws.la_mat_1, ws.la_vec_1);\n\t\t    // temp = ws.la_mat_1.row(r);\n\t\t    for (int r2 = 0; r2 < r; ++r2) {\n\t\t\t// projection = ws.la_mat_1.row(r) * out.row(r2).transpose();\n\t\t\trow(r2, out, ws.la_vec_2);\n\t\t\tdot(ws.la_vec_1, ws.la_vec_2, projection);\n\t\t\tws.la_vec_1 -= projection * ws.la_vec_2;\n\t\t\t// ws.la_mat_1.row(r) -= projection * out.row(r2);\n\t\t    }\n\t\t    \n\t\t    // ws.la_mat_1.row(r) /= sqrt(ws.la_mat_1.row(r) * ws.la_mat_1.row(r).transpose());\n\t\t    // ws.la_mat_1.row(r).normalize();\n\t\t    normalize(ws.la_vec_1);\n\t\t    to_row(r, out, ws.la_vec_1);\n\t\t}\n\t\tws.la_mat_1 = out;\n\t    }\n\t}\n\n\n\tinline pdouble_t trace(pmat_t& M) {\n\t    pdouble_t tr = 0.;\n\t    for (int i = 0; i < M.rows(); i++) {\n\t\ttr += M(i, i);\n\t    }\n\t    return tr;\n\t}\n\n\tinline void split_vec_sqrt(pvec_t&__restrict__ in, pvec_t&__restrict__ out) {\n\t    for (int i = 0; i < in.size(); ++i) {\n\t\tout(i) = sqrt(in(i));\n\t    }\n\t}\n\n\tinline bool all_below_eps(const pmat_t&__restrict M) {\n\t    for (int c = 0; c < M.cols(); ++c) {\n\t\tfor (int r = 0; r < M.rows(); ++r) {\n\t\t    if (fabs(M(r, c)) > 1e-14) { return false; }\n\t\t}\n\t    }\n\t    return true;\n\t}\n\n\tinline void sum(const pvec_t&__restrict__ v, double& sum) {\n\t    sum = 0;\n\t    for (int i = 0; i < v.size(); ++i) {\n\t\tsum += v(i);\n\t    }}\n\t    \n    }\t\t    \n}\n#endif\n", "meta": {"hexsha": "737b830a4ead8f01ff9c6545a4297b0af34b1c8b", "size": 13239, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libdqmc/la/special.hpp", "max_stars_repo_name": "pebroecker/DQMC", "max_stars_repo_head_hexsha": "c4a96cb20347ef722b6ae68c415233d464c89e93", "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": "libdqmc/la/special.hpp", "max_issues_repo_name": "pebroecker/DQMC", "max_issues_repo_head_hexsha": "c4a96cb20347ef722b6ae68c415233d464c89e93", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libdqmc/la/special.hpp", "max_forks_repo_name": "pebroecker/DQMC", "max_forks_repo_head_hexsha": "c4a96cb20347ef722b6ae68c415233d464c89e93", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7454545455, "max_line_length": 113, "alphanum_fraction": 0.5145403731, "num_tokens": 4689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961013, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.29626561919677036}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   DataGen_FreeGasElasticScatteringKernelFactor.cpp\n//! \\author Alex Robinson\n//! \\brief  Free gas elastic scattering gkq_set factor def.\n//!\n//---------------------------------------------------------------------------//\n\n// Std Lib Includes\n#include <iostream>\n#include <limits>\n\n// Boost Includes\n#include <boost/math/special_functions/bessel.hpp>\n\n// FRENSIE Includes\n#include \"DataGen_FreeGasElasticScatteringKernelFactor.hpp\"\n#include \"Utility_PhysicalConstants.hpp\"\n#include \"MonteCarlo_KinematicHelpers.hpp\"\n#include \"Utility_ComparisonPolicy.hpp\"\n#include \"Utility_DesignByContract.hpp\"\n\nnamespace DataGen{\n\n// Initialize static member data\ndouble FreeGasElasticScatteringKernelFactor::neutron_kinetic_energy_multiplier=\n  0.5*Utility::PhysicalConstants::neutron_rest_mass_energy/\n  (Utility::PhysicalConstants::speed_of_light*\n   Utility::PhysicalConstants::speed_of_light);\n\ndouble FreeGasElasticScatteringKernelFactor::min_exp_arg =\n  log(std::numeric_limits<double>::min());\n\n// Constructor\nFreeGasElasticScatteringKernelFactor::FreeGasElasticScatteringKernelFactor(\n\t  const std::shared_ptr<Utility::UnivariateDistribution>&\n\t  zero_temp_elastic_cross_section,\n          const std::shared_ptr<MonteCarlo::NuclearScatteringAngularDistribution>&\n\t  cm_scattering_distribution,\n\t  const double A,\n\t  const double kT,\n\t  const double alpha,\n\t  const double beta,\n\t  const double E )\n  : d_gkq_set( 1e-6 ),\n    d_zero_temp_elastic_cross_section( zero_temp_elastic_cross_section ),\n    d_cm_scattering_distribution( cm_scattering_distribution ),\n    d_A( A ),\n    d_kT( kT ),\n    d_alpha( alpha ),\n    d_beta( beta ),\n    d_E( E )\n{\n  // Make sure the distributions are valid\n  testPrecondition( zero_temp_elastic_cross_section.use_count() > 0 );\n  testPrecondition( cm_scattering_distribution.use_count() > 0 );\n  // Make sure the values are valid\n  testPrecondition( A > 0.0 );\n  testPrecondition( kT > 0.0 );\n  testPrecondition( E > 0.0 );\n  testPrecondition( beta >= MonteCarlo::calculateBetaMin( E, d_kT ) );\n  remember( double alpha_min = MonteCarlo::calculateAlphaMin(E,beta,A,kT) );\n  testPrecondition( alpha >= alpha_min );\n  remember( double alpha_max = MonteCarlo::calculateAlphaMax(E,beta,d_A,d_kT) );\n  testPrecondition( alpha <= alpha_max );\n\n  calculateCachedValues();\n}\n\n// Set the alpha, beta, and energy values\nvoid FreeGasElasticScatteringKernelFactor::setIndependentVariables(\n\t\t\t\t\t\t\t    const double alpha,\n\t\t\t\t\t\t\t    const double beta,\n\t\t\t\t\t\t\t    const double E )\n{\n  // Make sure the values are valid\n  testPrecondition( E > 0.0 );\n  testPrecondition( beta >= -E/d_kT );\n  remember( double alpha_min_arg = sqrt(E)-sqrt(E+beta*d_kT) );\n  remember( double alpha_min = alpha_min_arg*alpha_min_arg/(d_A*d_kT) );\n  testPrecondition( alpha >= alpha_min );\n  remember( double alpha_max_arg = sqrt(E)+sqrt(E+beta*d_kT) );\n  remember( double alpha_max = alpha_max_arg*alpha_max_arg/(d_A*d_kT) );\n  testPrecondition( alpha <= alpha_max );\n\n  d_alpha = alpha;\n  d_beta = beta;\n  d_E = E;\n\n  calculateCachedValues();\n}\n\n// Evaluate the factor at a desired value of the center-of-mass angle cosine\ndouble FreeGasElasticScatteringKernelFactor::operator()(\n\t\t\t\t\t\t     const double mu_cm ) const\n{\n  // Make sure the cm angle is valid\n  testPrecondition( mu_cm >= -1.0 );\n  testPrecondition( mu_cm <= 1.0 );\n\n  // The function goes to zero at mu_cm = 1.0\n  if( mu_cm == 1.0 )\n    return 0.0;\n  else\n  {\n    double relative_velocity = d_relative_velocity_mult/sqrt(1.0-mu_cm);\n    double relative_energy =\n      neutron_kinetic_energy_multiplier*relative_velocity*\n      relative_velocity;\n\n    double term_1 =\n      d_zero_temp_elastic_cross_section->evaluate( relative_energy )*\n      d_cm_scattering_distribution->evaluatePDF( d_E, mu_cm )/\n      ((1.0-mu_cm)*(1.0-mu_cm));\n\n    double exp_arg = d_exponential_arg_mult/(1-mu_cm) +\n      d_exponential_arg_const;\n\n    double bessel_arg = d_bessel_arg_mult*\n      sqrt((1.0+mu_cm)/(1.0-mu_cm));\n\n    double term_2;\n\n    try{\n      if( exp_arg > min_exp_arg )\n      {\n\tterm_2 = boost::math::cyl_bessel_i( 0, bessel_arg, Policy() )*\n\t  exp( exp_arg );\n      }\n      else // Use extended precision\n      {\n\tBoostLongDouble exp_arg_long = exp_arg;\n\tBoostLongDouble term_2_long =\n\t  boost::math::cyl_bessel_i( 0, bessel_arg, Policy() )*\n\t  exp( exp_arg_long );\n\n\tterm_2 = term_2_long.convert_to<double>();\n      }\n    }\n    // If the bessel argument is large use the asymptotic form of the function\n    catch( std::exception& exception )\n    {\n      term_2 = exp( bessel_arg + exp_arg )/\n\tsqrt( 2*Utility::PhysicalConstants::pi*bessel_arg );\n    }\n\n    // Make sure the return value is valid\n    testPostcondition(!Utility::QuantityTraits<double>::isnaninf(term_1*term_2));\n\n    return term_1*term_2;\n  }\n}\n\n// Get the integrated value\ndouble FreeGasElasticScatteringKernelFactor::getIntegratedValue(\n\t\t\t\t\t\t double& error_estimate ) const\n{\n  double integrated_value, lower_limit, upper_limit;\n\n  this->findLimits( lower_limit, upper_limit );\n\n  d_gkq_set.integrateAdaptively<15>( *this,\n\t\t\t\t    lower_limit,\n\t\t\t\t    upper_limit,\n\t\t\t\t    integrated_value,\n\t\t\t\t    error_estimate );\n\n  // Make sure the value is valid\n  testPostcondition( !Utility::QuantityTraits<double>::isnaninf( integrated_value ) );\n\n  return integrated_value;\n}\n\n// Calculate the cached values\nvoid FreeGasElasticScatteringKernelFactor::calculateCachedValues()\n{\n  d_energy_ratio = d_E/d_kT;\n\n  d_exponential_arg_mult = -(d_A+1)*(d_A+1)*d_alpha/2.0;\n\n  d_exponential_arg_const = -d_A*d_energy_ratio;\n\n  double bessel_arg_mult_arg =\n    4.0*d_A*d_alpha*d_energy_ratio -\n    (d_beta - d_A*d_alpha)*(d_beta - d_A*d_alpha);\n\n  // When alpha ~ alpha_min, alpha ~ alpha_max or beta ~ beta_min,\n  // a very small negative argument is possible due to roundoff - set it to 0\n  if( bessel_arg_mult_arg < 0.0 )\n    bessel_arg_mult_arg = 0.0;\n\n  d_bessel_arg_mult = (d_A+1)/2.0*sqrt(bessel_arg_mult_arg);\n\n  d_relative_velocity_mult = (d_A+1)/d_A*\n    sqrt(d_A*d_kT*d_alpha*Utility::PhysicalConstants::speed_of_light*\n\t Utility::PhysicalConstants::speed_of_light/\n\t Utility::PhysicalConstants::neutron_rest_mass_energy);\n}\n\n// Find limits to integrate over\nvoid FreeGasElasticScatteringKernelFactor::findLimits(\n\t\t\t\t\t\t    double& lower_limit,\n\t\t\t\t\t\t    double& upper_limit ) const\n{\n  // find an independent value where the function is non-zero\n  std::list<double> search_grid;\n\n  double arg1 = 4*d_A*d_alpha*d_E/d_kT -\n    (d_beta - d_A*d_alpha)*(d_beta - d_A*d_alpha);\n  double arg2 = (d_A + 1)*(d_A + 1)*d_alpha*d_alpha;\n\n  double estimated_peak_mu_cm = (arg1 - arg2)/(arg1 + arg2);\n\n\n  double estimated_peak_exp_arg = d_exponential_arg_const +\n    d_exponential_arg_mult/(1-estimated_peak_mu_cm) +\n    d_bessel_arg_mult*\n    sqrt((1.0+estimated_peak_mu_cm)/(1.0-estimated_peak_mu_cm));\n\n  // Check if the integrand can be expected to return non-zero values\n  if( estimated_peak_exp_arg > min_exp_arg )\n  {\n    search_grid.push_back( std::max( estimated_peak_mu_cm - 1e-6,\n\t\t\t\t     -1.0 ) );\n    search_grid.push_back( std::min( estimated_peak_mu_cm + 1e-6,\n\t\t\t\t     1.0 ) );\n\n    double center_value =\n      this->findCMScatteringAngleCosineWithNonZeroFunctionValue( search_grid );\n\n    // binary search to find closer lower and upper limits\n    double tol = 1e-15;\n\n    double lower_bound = -1.0;\n    double upper_bound = center_value;\n    double new_bound;\n\n    while( Utility::RelativeErrorComparisonPolicy::calculateRelativeError(upper_bound, lower_bound ) > tol  )\n    {\n      new_bound = (upper_bound + lower_bound)/2;\n\n      if( (*this)( new_bound ) == 0.0 )\n\tlower_bound = new_bound;\n      else\n\tupper_bound = new_bound;\n    }\n\n    // set the lower integration limit\n    lower_limit = lower_bound;\n\n    lower_bound = center_value;\n    upper_bound = 1.0;\n\n    while( Utility::RelativeErrorComparisonPolicy::calculateRelativeError(upper_bound, lower_bound) > tol )\n    {\n      new_bound = (upper_bound + lower_bound)/2;\n\n      if( (*this)( new_bound ) == 0.0 )\n\tupper_bound = new_bound;\n      else\n\tlower_bound = new_bound;\n    }\n\n    // set the upper integration limit\n    upper_limit = upper_bound;\n  }\n  else // integrand will always return zero\n  {\n    upper_limit = 0.0;\n    lower_limit = 0.0;\n  }\n}\n\n// Find a CM scattering angle cosine where the function is non-zero\ndouble FreeGasElasticScatteringKernelFactor::findCMScatteringAngleCosineWithNonZeroFunctionValue(\n\t\t\t\t\t std::list<double>& grid_points ) const\n{\n  std::list<double>::iterator first_grid_point = grid_points.begin();\n  std::list<double>::iterator second_grid_point = first_grid_point;\n  ++second_grid_point;\n\n  double cm_center_value;\n\n  // Find if any center points have non-zero function values\n  while( second_grid_point != grid_points.end() )\n  {\n    cm_center_value = (*first_grid_point + *second_grid_point)/2;\n\n    if( (*this)( cm_center_value ) > 0.0 )\n      return cm_center_value;\n\n    first_grid_point = grid_points.insert( second_grid_point,\n\t\t\t\t\t   cm_center_value );\n    ++first_grid_point;\n    ++second_grid_point;\n  }\n\n  return findCMScatteringAngleCosineWithNonZeroFunctionValue( grid_points );\n}\n\n} // end DataGen namespace\n\n//---------------------------------------------------------------------------//\n// end DataGen_FreeGasElasticScatteringKernelFactor.cpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "927115359ff7cfb56f7b64c7c52876a924415fc6", "size": 9454, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/data_gen/free_gas_sab/src/DataGen_FreeGasElasticScatteringKernelFactor.cpp", "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/data_gen/free_gas_sab/src/DataGen_FreeGasElasticScatteringKernelFactor.cpp", "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/data_gen/free_gas_sab/src/DataGen_FreeGasElasticScatteringKernelFactor.cpp", "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": 30.8954248366, "max_line_length": 109, "alphanum_fraction": 0.6938861857, "num_tokens": 2452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.29622434909692763}}
{"text": "#include \"multi_body_icp.h\"\n\n#include \"vox_grid.h\"\n#include \"frames.h\"\n#include \"model.h\"\n#include \"focal_grid.h\"\n\n#include <boost/thread/thread.hpp>\n#include <boost/make_shared.hpp>\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 <thread>\n#include <algorithm>\n#include <dirent.h>\n#include <armadillo>\n#include <nlopt.h>\n#include <pcl/console/parse.h>\n#include <pcl/common/transforms.h>\n#include <pcl/PCLPointCloud2.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/io/vtk_lib_io.h>\n#include <pcl/kdtree/kdtree_flann.h>\n#include <pcl/features/normal_3d.h>\n#include <pcl/surface/gp3.h>\n#include <pcl/registration/icp.h>\n#include <Eigen/Core>\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n#include <pcl/point_representation.h>\n#include <pcl/common/time.h>\n#include <pcl/console/print.h>\n#include <pcl/features/normal_3d_omp.h>\n#include <pcl/features/fpfh_omp.h>\n#include <pcl/filters/filter.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/registration/icp.h>\n#include <pcl/registration/sample_consensus_prerejective.h>\n#include <pcl/segmentation/sac_segmentation.h>\n#include <pcl/registration/icp_nl.h>\n#include <pcl/registration/transforms.h>\n\nusing namespace std;\n\n// Types\ntypedef pcl::PointXYZ PointT;\ntypedef pcl::PointNormal PointNT;\ntypedef pcl::PointCloud<PointT> PointCloud;\ntypedef pcl::PointCloud<PointNT> PointCloudT;\ntypedef pcl::FPFHSignature33 FeatureT;\ntypedef pcl::FPFHEstimationOMP<PointNT,PointNT,FeatureT> FeatureEstimationT;\ntypedef pcl::PointCloud<FeatureT> FeatureCloudT;\n\n// Define a new point representation for < x, y, z, curvature >\nclass MyPointRepresentation : public pcl::PointRepresentation <PointNT>\n{\n  using pcl::PointRepresentation<PointNT>::nr_dimensions_;\npublic:\n  MyPointRepresentation ()\n  {\n    // Define the number of dimensions\n    nr_dimensions_ = 4;\n  }\n\n  // Override the copyToFloatArray method to define our feature vector\n  virtual void copyToFloatArray (const PointNT &p, float * out) const\n  {\n    // < x, y, z, curvature >\n    out[0] = p.x;\n    out[1] = p.y;\n    out[2] = p.z;\n    out[3] = p.curvature;\n  }\n};\n\nMultiBodyICP::MultiBodyICP() {\n  // empty\n}\n\n/*\nvector<arma::Mat<double>> MultiBodyICP::SingleFrameICP(frames &frame_in, model &mod) {\n\n  vector<arma::Mat<double>> M_align_vec;\n\n  arma::Mat<double> body_pcl = frame_in.pcl_init_single_frame[0];\n  arma::Mat<double> wing_L_pcl = frame_in.pcl_init_single_frame[1];\n  arma::Mat<double> wing_R_pcl = frame_in.pcl_init_single_frame[2];\n\n  arma::Mat<double> M_body_init = frame_in.M_init_single_frame[0];\n  arma::Mat<double> M_wing_L_init = frame_in.M_init_single_frame[1];\n  arma::Mat<double> M_wing_R_init = frame_in.M_init_single_frame[2];\n\n  // Calculate transformation matrices for all initial orientations:\n\n  // body:\n\n  arma::Mat<double> M_thorax_init = MultiBodyICP::CalculateMeshTransform(mod, M_body_init, 0);\n  arma::Mat<double> M_head_init = MultiBodyICP::CalculateMeshTransform(mod, M_thorax_init, 1);\n  arma::Mat<double> M_abdomen_init = MultiBodyICP::CalculateMeshTransform(mod, M_thorax_init, 2);\n\n  pcl::PointCloud<pcl::PointXYZ> thorax_src_pcl = MultiBodyICP::GetModelSRCPointCloud(mod, M_thorax_init, 0);\n  PointCloudT thorax_src = MultiBodyICP::TransferPointXYZ2PointNT(thorax_src_pcl);\n  pcl::PointCloud<pcl::PointXYZ> head_src_pcl = MultiBodyICP::GetModelSRCPointCloud(mod, M_head_init, 1);\n  PointCloudT head_src = MultiBodyICP::TransferPointXYZ2PointNT(head_src_pcl);\n  pcl::PointCloud<pcl::PointXYZ> abdomen_src_pcl = MultiBodyICP::GetModelSRCPointCloud(mod, M_abdomen_init, 2);\n  PointCloudT abdomen_src = MultiBodyICP::TransferPointXYZ2PointNT(abdomen_src_pcl);\n\n  pcl::PointCloud<pcl::PointXYZ> body_dest_pcl = MultiBodyICP::Convert_Mat_2_PCL_XYZ(body_pcl);\n  PointCloudT body_dest = MultiBodyICP::TransferPointXYZ2PointNT(body_dest_pcl);\n\n  // Perform ICP on thorax\n  //tuple<arma::Mat<double>,double> icp_result_thorax = MultiBodyICP::ICP_on_single_segment(body_dest_pcl, thorax_src_pcl);\n  //tuple<arma::Mat<double>,double> icp_result_head = MultiBodyICP::ICP_on_single_segment(body_dest_pcl, head_src_pcl);\n  //tuple<arma::Mat<double>,double> icp_result_abdomen = MultiBodyICP::ICP_on_single_segment(body_dest_pcl, abdomen_src_pcl);\n  tuple<arma::Mat<double>,double> icp_result_thorax = MultiBodyICP::RobustPoseEstimation(body_dest, thorax_src);\n  tuple<arma::Mat<double>,double> icp_result_head = MultiBodyICP::RobustPoseEstimation(body_dest, head_src);\n  tuple<arma::Mat<double>,double> icp_result_abdomen = MultiBodyICP::RobustPoseEstimation(body_dest, abdomen_src);\n\n  M_align_vec.push_back(get<0>(icp_result_thorax));\n  M_align_vec.push_back(get<0>(icp_result_head));\n  M_align_vec.push_back(get<0>(icp_result_abdomen));\n\n  \n  // left wing:\n\n  arma::Mat<double> M_wing_L1_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_L_init.submat(0,0,3,3), 3);\n  arma::Mat<double> M_wing_L2_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_L_init.submat(0,4,3,7), 3);\n  arma::Mat<double> M_wing_L3_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_L_init.submat(0,8,3,11), 3);\n  arma::Mat<double> M_wing_L4_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_L_init.submat(0,12,3,15), 3);\n\n  pcl::PointCloud<pcl::PointXYZ> wing_L1_src_pcl = MultiBodyICP::GetModelSRCPointCloud(mod, M_wing_L1_init, 3);\n  PointCloudT wing_L1_src = MultiBodyICP::TransferPointXYZ2PointNT(wing_L1_src_pcl);\n  pcl::PointCloud<pcl::PointXYZ> wing_L2_src_pcl = MultiBodyICP::GetModelSRCPointCloud(mod, M_wing_L2_init, 3);\n  PointCloudT wing_L2_src = MultiBodyICP::TransferPointXYZ2PointNT(wing_L2_src_pcl);\n  pcl::PointCloud<pcl::PointXYZ> wing_L3_src_pcl = MultiBodyICP::GetModelSRCPointCloud(mod, M_wing_L3_init, 3);\n  PointCloudT wing_L3_src = MultiBodyICP::TransferPointXYZ2PointNT(wing_L3_src_pcl);\n  pcl::PointCloud<pcl::PointXYZ> wing_L4_src_pcl = MultiBodyICP::GetModelSRCPointCloud(mod, M_wing_L4_init, 3);\n  PointCloudT wing_L4_src = MultiBodyICP::TransferPointXYZ2PointNT(wing_L4_src_pcl);\n\n  pcl::PointCloud<pcl::PointXYZ> wing_L_dest_pcl = MultiBodyICP::Convert_Mat_2_PCL_XYZ(wing_L_pcl);\n  PointCloudT wing_L_dest = MultiBodyICP::TransferPointXYZ2PointNT(wing_L_dest_pcl);\n\n  // Perform ICP on the left wing:\n\n  //tuple<arma::Mat<double>,double> icp_result_wing_L1 = MultiBodyICP::ICP_on_single_segment(wing_L_dest_pcl, wing_L1_src_pcl);\n  //tuple<arma::Mat<double>,double> icp_result_wing_L2 = MultiBodyICP::ICP_on_single_segment(wing_L_dest_pcl, wing_L2_src_pcl);\n  //tuple<arma::Mat<double>,double> icp_result_wing_L3 = MultiBodyICP::ICP_on_single_segment(wing_L_dest_pcl, wing_L3_src_pcl);\n  //tuple<arma::Mat<double>,double> icp_result_wing_L4 = MultiBodyICP::ICP_on_single_segment(wing_L_dest_pcl, wing_L4_src_pcl);\n  tuple<arma::Mat<double>,double> icp_result_wing_L1 = MultiBodyICP::RobustPoseEstimation(wing_L_dest, wing_L1_src);\n  tuple<arma::Mat<double>,double> icp_result_wing_L2 = MultiBodyICP::RobustPoseEstimation(wing_L_dest, wing_L2_src);\n  tuple<arma::Mat<double>,double> icp_result_wing_L3 = MultiBodyICP::RobustPoseEstimation(wing_L_dest, wing_L3_src);\n  tuple<arma::Mat<double>,double> icp_result_wing_L4 = MultiBodyICP::RobustPoseEstimation(wing_L_dest, wing_L4_src);\n\n  arma::Col<double> score_vec_L = {get<1>(icp_result_wing_L1),get<1>(icp_result_wing_L2),get<1>(icp_result_wing_L3),get<1>(icp_result_wing_L4)};\n\n  if (score_vec_L.index_max()==0) {\n    M_align_vec.push_back(get<0>(icp_result_wing_L1));\n  }\n  else if (score_vec_L.index_max()==1) {\n    M_align_vec.push_back(get<0>(icp_result_wing_L2));\n  }\n  else if (score_vec_L.index_max()==2) {\n    M_align_vec.push_back(get<0>(icp_result_wing_L3));\n  }\n  else if (score_vec_L.index_max()==3) {\n    M_align_vec.push_back(get<0>(icp_result_wing_L4));\n  }\n  else {\n    arma::Mat<double> zero_mat(4,4);\n    zero_mat.zeros();\n    M_align_vec.push_back(zero_mat);\n  }\n\n  \n  // right wing:\n\n  arma::Mat<double> M_wing_R1_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_R_init.submat(0,0,3,3), 4);\n  arma::Mat<double> M_wing_R2_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_R_init.submat(0,4,3,7), 4);\n  arma::Mat<double> M_wing_R3_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_R_init.submat(0,8,3,11), 4);\n  arma::Mat<double> M_wing_R4_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_R_init.submat(0,12,3,15), 4);\n\n  pcl::PointCloud<pcl::PointXYZ> wing_R1_src_pcl = MultiBodyICP::GetModelSRCPointCloud(mod, M_wing_R1_init, 4);\n  PointCloudT wing_R1_src = MultiBodyICP::TransferPointXYZ2PointNT(wing_R1_src_pcl);\n  pcl::PointCloud<pcl::PointXYZ> wing_R2_src_pcl = MultiBodyICP::GetModelSRCPointCloud(mod, M_wing_R2_init, 4);\n  PointCloudT wing_R2_src = MultiBodyICP::TransferPointXYZ2PointNT(wing_R2_src_pcl);\n  pcl::PointCloud<pcl::PointXYZ> wing_R3_src_pcl = MultiBodyICP::GetModelSRCPointCloud(mod, M_wing_R3_init, 4);\n  PointCloudT wing_R3_src = MultiBodyICP::TransferPointXYZ2PointNT(wing_R3_src_pcl);\n  pcl::PointCloud<pcl::PointXYZ> wing_R4_src_pcl = MultiBodyICP::GetModelSRCPointCloud(mod, M_wing_R4_init, 4);\n  PointCloudT wing_R4_src = MultiBodyICP::TransferPointXYZ2PointNT(wing_R4_src_pcl);\n\n  pcl::PointCloud<pcl::PointXYZ> wing_R_dest_pcl = MultiBodyICP::Convert_Mat_2_PCL_XYZ(wing_R_pcl);\n  PointCloudT wing_R_dest = MultiBodyICP::TransferPointXYZ2PointNT(wing_R_dest_pcl);\n\n  // Perform ICP on the right wing:\n\n  //tuple<arma::Mat<double>,double> icp_result_wing_R1 = MultiBodyICP::ICP_on_single_segment(wing_R_dest_pcl, wing_R1_src_pcl);\n  //tuple<arma::Mat<double>,double> icp_result_wing_R2 = MultiBodyICP::ICP_on_single_segment(wing_R_dest_pcl, wing_R2_src_pcl);\n  //tuple<arma::Mat<double>,double> icp_result_wing_R3 = MultiBodyICP::ICP_on_single_segment(wing_R_dest_pcl, wing_R3_src_pcl);\n  //tuple<arma::Mat<double>,double> icp_result_wing_R4 = MultiBodyICP::ICP_on_single_segment(wing_R_dest_pcl, wing_R4_src_pcl);\n  tuple<arma::Mat<double>,double> icp_result_wing_R1 = MultiBodyICP::RobustPoseEstimation(wing_R_dest, wing_R1_src);\n  tuple<arma::Mat<double>,double> icp_result_wing_R2 = MultiBodyICP::RobustPoseEstimation(wing_R_dest, wing_R2_src);\n  tuple<arma::Mat<double>,double> icp_result_wing_R3 = MultiBodyICP::RobustPoseEstimation(wing_R_dest, wing_R3_src);\n  tuple<arma::Mat<double>,double> icp_result_wing_R4 = MultiBodyICP::RobustPoseEstimation(wing_R_dest, wing_R4_src);\n\n  arma::Col<double> score_vec_R = {get<1>(icp_result_wing_R1),get<1>(icp_result_wing_R2),get<1>(icp_result_wing_R3),get<1>(icp_result_wing_R4)};\n\n  if (score_vec_R.index_max()==0) {\n    M_align_vec.push_back(get<0>(icp_result_wing_R1));\n  }\n  else if (score_vec_R.index_max()==1) {\n    M_align_vec.push_back(get<0>(icp_result_wing_R2));\n  }\n  else if (score_vec_R.index_max()==2) {\n    M_align_vec.push_back(get<0>(icp_result_wing_R3));\n  }\n  else if (score_vec_R.index_max()==3) {\n    M_align_vec.push_back(get<0>(icp_result_wing_R4));\n  }\n  else {\n    arma::Mat<double> zero_mat(4,4);\n    zero_mat.zeros();\n    M_align_vec.push_back(zero_mat);\n  }\n\n  return M_align_vec;\n}\n*/\n\npcl::PointCloud<pcl::PointXYZ> MultiBodyICP::GetModelSRCPointCloud(model &mod, arma::Mat<double> M_init, int seg_ind) {\n\n  pcl::PolygonMesh part_mesh = mod.parts[seg_ind];\n\n  // Scale the part:\n\n  double part_scale = mod.scale[seg_ind];\n\n  arma::Mat<double> M_part = {{M_init(0,0)*part_scale, M_init(0,1)*part_scale, M_init(0,2)*part_scale, M_init(0,3)},\n    {M_init(1,0)*part_scale, M_init(1,1)*part_scale, M_init(1,2)*part_scale, M_init(1,3)},\n    {M_init(2,0)*part_scale, M_init(2,1)*part_scale, M_init(2,2)*part_scale, M_init(2,3)},\n    {0.0, 0.0, 0.0, 1.0}};\n\n  // Transform the mesh:\n\n  pcl::PolygonMesh trans_mesh = MultiBodyICP::TransformMesh(part_mesh, M_part);\n\n  // Get Pointcloud of the mesh:\n\n  pcl::PointCloud<pcl::PointXYZ> pcl_out = MultiBodyICP::GetPointCloudFromMesh(trans_mesh);\n\n  return pcl_out;\n}\n\narma::Mat<double> MultiBodyICP::CalculateMeshTransform(model &mod, arma::Mat<double> M_init, int seg_ind) {\n\n  arma::Mat<double> R_init = M_init.submat(0,0,2,2);\n  arma::Col<double> T_init = {M_init(0,3), M_init(1,3), M_init(2,3)};\n\n  double seg_scale = mod.scale[seg_ind];\n\n  arma::Col<double> bbox_config = mod.bounding_box_config[seg_ind];\n  arma::Mat<double> M_bbox = MultiBodyICP::GetM(bbox_config);\n  arma::Mat<double> R_bbox = M_bbox.submat(0,0,2,2);\n  arma::Col<double> T_bbox = {M_bbox(0,3)*seg_scale, M_bbox(1,3)*seg_scale, M_bbox(2,3)*seg_scale};\n\n  arma::Mat<double> R_out = R_init*R_bbox;\n  arma::Col<double> T_out = R_init*T_bbox+T_init;\n  arma::Mat<double> M_out = {{R_out(0,0), R_out(0,1), R_out(0,2), T_out(0)},\n    {R_out(1,0), R_out(1,1), R_out(1,2), T_out(1)},\n    {R_out(2,0), R_out(2,1), R_out(2,2), T_out(2)},\n    {0.0, 0.0, 0.0, 1.0}};\n  mod.M_vec.push_back(M_out);\n\n  return M_out;\n}\n\ntuple<arma::Mat<double>,double> MultiBodyICP::RobustPoseEstimation(PointCloudT &dest_pcl, PointCloudT &src_pcl) {\n\n  int max_iter = 50000;\n  double leaf_size = 0.10;\n  double search_radius = 0.25;\n  int N_samples = 3;\n  int N_features = 5;\n\n  // Pointclouds:\n  PointCloudT::Ptr src (new PointCloudT);\n  PointCloudT::Ptr src_aligned (new PointCloudT);\n  PointCloudT::Ptr dest (new PointCloudT);\n  FeatureCloudT::Ptr src_features (new FeatureCloudT);\n  FeatureCloudT::Ptr dest_features (new FeatureCloudT);\n\n  *src = src_pcl;\n  *dest = dest_pcl;\n\n  // Downsampling:\n  pcl::VoxelGrid<PointNT> grid;\n  grid.setLeafSize (leaf_size, leaf_size, leaf_size);\n  grid.setInputCloud (src);\n  grid.filter (*src);\n  grid.setInputCloud (dest);\n  grid.filter (*dest);\n\n  // Estimate normals:\n  pcl::NormalEstimationOMP<PointNT,PointNT> nest;\n  nest.setRadiusSearch (search_radius);\n  nest.setInputCloud (src);\n  nest.compute (*src);\n  nest.setInputCloud (dest);\n  nest.compute (*dest);\n\n  // Estimate features:\n  FeatureEstimationT fest;\n  fest.setRadiusSearch (search_radius);\n  fest.setInputCloud (src);\n  fest.setInputNormals (src);\n  fest.compute (*src_features);\n  fest.setInputCloud (dest);\n  fest.setInputNormals (dest);\n  fest.compute (*dest_features);\n\n  // Perform alignment:\n  pcl::SampleConsensusPrerejective<PointNT,PointNT,FeatureT> align;\n  align.setInputSource (src);\n  align.setSourceFeatures (src_features);\n  align.setInputTarget (dest);\n  align.setTargetFeatures (dest_features);\n  align.setMaximumIterations (max_iter); // Number of RANSAC iterations\n  align.setNumberOfSamples (N_samples); // Number of points to sample for generating/prejecting a pose\n  align.setCorrespondenceRandomness (N_features); // Number of nearest features to use\n  align.setSimilarityThreshold (0.5f); // Polygonal edge length similarity threshold\n  align.setMaxCorrespondenceDistance (5.0f * leaf_size); // Inlier threshold\n  align.setInlierFraction (0.1f); // Required inlier fraction ofr accepting a pose hypothesis\n\n  {\n    pcl::ScopeTime t(\"Alignment\");\n    align.align (*src_aligned);\n  }\n\n  arma::Mat<double> M_out(4,4);\n  double score;\n\n  if (align.hasConverged ()) {\n\n    Eigen::Matrix4f transformation = align.getFinalTransformation ();\n\n    M_out(0,0) = transformation(0,0);\n    M_out(0,1) = transformation(0,1);\n    M_out(0,2) = transformation(0,2);\n    M_out(0,3) = transformation(0,3);\n    M_out(1,0) = transformation(1,0);\n    M_out(1,1) = transformation(1,1);\n    M_out(1,2) = transformation(1,2);\n    M_out(1,3) = transformation(1,3);\n    M_out(2,0) = transformation(2,0);\n    M_out(2,1) = transformation(2,1);\n    M_out(2,2) = transformation(2,2);\n    M_out(2,3) = transformation(2,3);\n    M_out(3,0) = transformation(3,0);\n    M_out(3,1) = transformation(3,1);\n    M_out(3,2) = transformation(3,2);\n    M_out(3,3) = transformation(3,3);\n\n    score = 1.0;\n\n    cout << \"transformation matrix\" << endl;\n    cout << M_out << endl;\n    cout << \"inliers\" << endl;\n    cout << align.getInliers().size() << endl;\n    cout << \"\" << endl;\n\n  }\n  else {\n    cout << \"aligned failed\" << endl;\n  }\n\n  return make_tuple(M_out,score);\n}\n\ntuple<arma::Mat<double>,double> MultiBodyICP::ICP_on_single_segment(pcl::PointCloud<pcl::PointXYZ> &dest_pcl, pcl::PointCloud<pcl::PointXYZ> &src_pcl) {\n\n  pcl::PointCloud<pcl::PointXYZ>::Ptr dest_cloud (new pcl::PointCloud<pcl::PointXYZ>);\n  pcl::PointCloud<pcl::PointXYZ>::Ptr src_cloud (new pcl::PointCloud<pcl::PointXYZ>);\n\n  *dest_cloud = dest_pcl;\n  *src_cloud = src_pcl;\n\n  pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp;\n  icp.setInputCloud(src_cloud);\n  icp.setInputTarget(dest_cloud);\n\n  pcl::PointCloud<pcl::PointXYZ> Final;\n  icp.align(Final);\n\n  int icp_converged = icp.hasConverged();\n  double icp_score = icp.getFitnessScore();\n  Eigen::Matrix4f M_final = icp.getFinalTransformation();\n\n  cout << \"has converged:\" << icp_converged << \" score: \" << icp_score << endl;\n  cout << M_final << endl;\n\n  arma::Mat<double> M_out(4,4);\n\n  M_out(0,0) = M_final(0,0);\n  M_out(0,1) = M_final(0,1);\n  M_out(0,2) = M_final(0,2);\n  M_out(0,3) = M_final(0,3);\n  M_out(1,0) = M_final(1,0);\n  M_out(1,1) = M_final(1,1);\n  M_out(1,2) = M_final(1,2);\n  M_out(1,3) = M_final(1,3);\n  M_out(2,0) = M_final(2,0);\n  M_out(2,1) = M_final(2,1);\n  M_out(2,2) = M_final(2,2);\n  M_out(2,3) = M_final(2,3);\n  M_out(3,0) = M_final(3,0);\n  M_out(3,1) = M_final(3,1);\n  M_out(3,2) = M_final(3,2);\n  M_out(3,3) = M_final(3,3);\n\n  return make_tuple(M_out,icp_score);\n\n}\n\nvector<arma::Mat<int>> MultiBodyICP::ReturnProjectedImages(frames &frame_in, model &mod, vox_grid &vox, FocalGrid &fcg) {\n\n  // Compute initial orientation matrices:\n\n  arma::Mat<double> M_body_init = frame_in.M_init_single_frame[0];\n  arma::Mat<double> M_wing_L_init = frame_in.M_init_single_frame[1];\n  arma::Mat<double> M_wing_R_init = frame_in.M_init_single_frame[2];\n\n  // body:\n  arma::Mat<double> M_thorax_init  = MultiBodyICP::CalculateMeshTransform(mod, M_body_init, 0);\n  arma::Mat<double> M_head_init    = MultiBodyICP::CalculateMeshTransform(mod, M_thorax_init, 1);\n  arma::Mat<double> M_abdomen_init = MultiBodyICP::CalculateMeshTransform(mod, M_thorax_init, 2);\n\n  // left wing:\n  arma::Mat<double> M_wing_L1_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_L_init.submat(0,0,3,3), 3);\n\n  // right wing:\n  arma::Mat<double> M_wing_R1_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_R_init.submat(0,0,3,3), 4);\n\n  // Project the model segments from 3d to 2d and back to 3d:\n\n  vector<arma::Col<int>> mdl_pcl_thorax  = MultiBodyICP::GetProjectedImages(mod, vox, fcg, M_thorax_init, 0, 10);\n  vector<arma::Col<int>> mdl_pcl_head    = MultiBodyICP::GetProjectedImages(mod, vox, fcg, M_head_init, 1, 10);\n  vector<arma::Col<int>> mdl_pcl_abdomen = MultiBodyICP::GetProjectedImages(mod, vox, fcg, M_abdomen_init, 2, 10);\n  vector<arma::Col<int>> mdl_pcl_wing_L1 = MultiBodyICP::GetProjectedImages(mod, vox, fcg, M_wing_L1_init, 3, 3);\n  vector<arma::Col<int>> mdl_pcl_wing_R1 = MultiBodyICP::GetProjectedImages(mod, vox, fcg, M_wing_R1_init, 4, 3);\n\n  vector<arma::Mat<int>> proj_frames;\n\n  int N_frames = mdl_pcl_thorax.size();\n\n  for (int i=0; i<N_frames; i++) {\n\n    arma::Col<int> frame = mdl_pcl_thorax[i]+mdl_pcl_head[i]+mdl_pcl_abdomen[i]+mdl_pcl_wing_L1[i]+mdl_pcl_wing_R1[i];\n\n    int N_row = get<0>(frame_in.image_size[i]);\n    int N_col = get<1>(frame_in.image_size[i]);\n\n    arma::Mat<int> frame_mat(N_row,N_col);\n\n    for (int j=0; j<N_col; j++) {\n      for (int k=0; k<N_row; k++) {\n        if (frame(k*N_col+j)>10) {\n          frame_mat(k,j) = 10;\n        }\n        else {\n          frame_mat(k,j) = frame(k*N_col+j);\n        }\n      }\n    }\n\n    proj_frames.push_back(frame_mat);\n\n  }\n\n  return proj_frames;\n}\n\nvector<arma::Col<int>> MultiBodyICP::GetProjectedImages(model &mod, vox_grid &vox, FocalGrid &fcg, arma::Mat<double> M_init, int seg_ind, int int_val) {\n\n  vector<arma::Mat<double>> proj_images;\n\n  pcl::PointCloud<pcl::PointXYZ> seg_pcl = MultiBodyICP::GetModelSRCPointCloud(mod, M_init, seg_ind);\n\n  vector<tuple<double,double,double,int>> seg_pcl_vec = MultiBodyICP::Convert_PCL_XYZ_2_Vec(seg_pcl, int_val);\n\n  vector<arma::Col<int>> proj_frames = fcg.ProjectCloud2Image(seg_pcl_vec);\n\n  return proj_frames;\n}\n\narma::Mat<double> MultiBodyICP::ReturnSRCPCL(frames &frame_in, model &mod, vox_grid &vox, FocalGrid &fcg) {\n\n  // Compute initial orientation matrices:\n\n  arma::Mat<double> M_body_init   = frame_in.M_init_single_frame[0];\n  arma::Mat<double> M_wing_L_init = frame_in.M_init_single_frame[1];\n  arma::Mat<double> M_wing_R_init = frame_in.M_init_single_frame[2];\n\n  // body:\n  arma::Mat<double> M_thorax_init  = MultiBodyICP::CalculateMeshTransform(mod, M_body_init, 0);\n  arma::Mat<double> M_head_init    = MultiBodyICP::CalculateMeshTransform(mod, M_thorax_init, 1);\n  arma::Mat<double> M_abdomen_init = MultiBodyICP::CalculateMeshTransform(mod, M_thorax_init, 2);\n\n  // left wing:\n  arma::Mat<double> M_wing_L1_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_L_init.submat(0,0,3,3), 3);\n  arma::Mat<double> M_wing_L2_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_L_init.submat(0,4,3,7), 3);\n  arma::Mat<double> M_wing_L3_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_L_init.submat(0,8,3,11), 3);\n  arma::Mat<double> M_wing_L4_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_L_init.submat(0,12,3,15), 3);\n\n  // right wing:\n  arma::Mat<double> M_wing_R1_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_R_init.submat(0,0,3,3), 4);\n  arma::Mat<double> M_wing_R2_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_R_init.submat(0,4,3,7), 4);\n  arma::Mat<double> M_wing_R3_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_R_init.submat(0,8,3,11), 4);\n  arma::Mat<double> M_wing_R4_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_R_init.submat(0,12,3,15), 4);\n\n  // Project the model segments from 3d to 2d and back to 3d:\n\n  arma::Mat<double> mdl_pcl_thorax  = MultiBodyICP::GetProjectedModelPCL(mod, vox, fcg, M_thorax_init,  0, 1);\n  arma::Mat<double> mdl_pcl_head    = MultiBodyICP::GetProjectedModelPCL(mod, vox, fcg, M_head_init,    1, 1);\n  arma::Mat<double> mdl_pcl_abdomen = MultiBodyICP::GetProjectedModelPCL(mod, vox, fcg, M_abdomen_init, 2, 1);\n  arma::Mat<double> mdl_pcl_wing_L1 = MultiBodyICP::GetProjectedModelPCL(mod, vox, fcg, M_wing_L1_init, 3, 1);\n  arma::Mat<double> mdl_pcl_wing_L2 = MultiBodyICP::GetProjectedModelPCL(mod, vox, fcg, M_wing_L2_init, 3, 1);\n  arma::Mat<double> mdl_pcl_wing_L3 = MultiBodyICP::GetProjectedModelPCL(mod, vox, fcg, M_wing_L3_init, 3, 1);\n  arma::Mat<double> mdl_pcl_wing_L4 = MultiBodyICP::GetProjectedModelPCL(mod, vox, fcg, M_wing_L4_init, 3, 1);\n  arma::Mat<double> mdl_pcl_wing_R1 = MultiBodyICP::GetProjectedModelPCL(mod, vox, fcg, M_wing_R1_init, 4, 1);\n  arma::Mat<double> mdl_pcl_wing_R2 = MultiBodyICP::GetProjectedModelPCL(mod, vox, fcg, M_wing_R2_init, 4, 1);\n  arma::Mat<double> mdl_pcl_wing_R3 = MultiBodyICP::GetProjectedModelPCL(mod, vox, fcg, M_wing_R3_init, 4, 1);\n  arma::Mat<double> mdl_pcl_wing_R4 = MultiBodyICP::GetProjectedModelPCL(mod, vox, fcg, M_wing_R4_init, 4, 1);\n\n  arma::Mat<double> pcl_mat_out = mdl_pcl_thorax;\n  pcl_mat_out = arma::join_rows(pcl_mat_out,mdl_pcl_head);\n  pcl_mat_out = arma::join_rows(pcl_mat_out,mdl_pcl_abdomen);\n  pcl_mat_out = arma::join_rows(pcl_mat_out,mdl_pcl_wing_L1);\n  pcl_mat_out = arma::join_rows(pcl_mat_out,mdl_pcl_wing_L2);\n  pcl_mat_out = arma::join_rows(pcl_mat_out,mdl_pcl_wing_L3);\n  pcl_mat_out = arma::join_rows(pcl_mat_out,mdl_pcl_wing_L4);\n  pcl_mat_out = arma::join_rows(pcl_mat_out,mdl_pcl_wing_R1);\n  pcl_mat_out = arma::join_rows(pcl_mat_out,mdl_pcl_wing_R2);\n  pcl_mat_out = arma::join_rows(pcl_mat_out,mdl_pcl_wing_R3);\n  pcl_mat_out = arma::join_rows(pcl_mat_out,mdl_pcl_wing_R4);\n\n  return pcl_mat_out;\n}\n\narma::Mat<double> MultiBodyICP::SingleFrameICP(frames &frame_in, model &mod, vox_grid &vox, FocalGrid &fcg) {\n\n  clock_t start;\n  double duration;\n\n  start = clock();\n\n  arma::Mat<double> body_pcl = frame_in.pcl_init_single_frame[0];\n  arma::Mat<double> M_body_init   = frame_in.M_init_single_frame[0];\n\n  arma::Mat<double> M_thorax_init  = MultiBodyICP::CalculateMeshTransform(mod, M_body_init, 0);\n  arma::Mat<double> M_head_init    = MultiBodyICP::CalculateMeshTransform(mod, M_thorax_init, 1);\n  arma::Mat<double> M_abdomen_init = MultiBodyICP::CalculateMeshTransform(mod, M_thorax_init, 2);\n\n  tuple<arma::Mat<double>,arma::Mat<double>,double> thorax_icp_results  = MultiBodyICP::ICPAlgorithm(mod, vox, fcg, body_pcl, M_thorax_init,  0, 1);\n  tuple<arma::Mat<double>,arma::Mat<double>,double> head_icp_results    = MultiBodyICP::ICPAlgorithm(mod, vox, fcg, body_pcl, M_head_init,  1, 3);\n  tuple<arma::Mat<double>,arma::Mat<double>,double> abdomen_icp_results = MultiBodyICP::ICPAlgorithm(mod, vox, fcg, body_pcl, M_abdomen_init,  2, 5);\n\n  arma::Mat<double> pcl_mat_out = get<0>(thorax_icp_results);\n  pcl_mat_out = arma::join_rows(pcl_mat_out,get<0>(head_icp_results));\n  pcl_mat_out = arma::join_rows(pcl_mat_out,get<0>(abdomen_icp_results));\n\n  duration = (clock()-start)/ (double) CLOCKS_PER_SEC;\n\n  cout << \"ICP took\" << endl;\n  cout << duration << endl;\n\n  return pcl_mat_out;\n\n}\n\n\n/*\narma::Mat<double> MultiBodyICP::SingleFrameICP(frames &frame_in, model &mod, vox_grid &vox, FocalGrid &fcg) {\n\n  // Compute initial orientation matrices:\n\n  arma::Mat<double> body_pcl = frame_in.pcl_init_single_frame[0];\n  arma::Mat<double> wing_L_pcl = frame_in.pcl_init_single_frame[1];\n  arma::Mat<double> wing_R_pcl = frame_in.pcl_init_single_frame[2];\n\n  arma::Mat<double> M_body_init   = frame_in.M_init_single_frame[0];\n  arma::Mat<double> M_wing_L_init = frame_in.M_init_single_frame[1];\n  arma::Mat<double> M_wing_R_init = frame_in.M_init_single_frame[2];\n\n  // body:\n  arma::Mat<double> M_thorax_init  = MultiBodyICP::CalculateMeshTransform(mod, M_body_init, 0);\n  arma::Mat<double> M_head_init    = MultiBodyICP::CalculateMeshTransform(mod, M_thorax_init, 1);\n  arma::Mat<double> M_abdomen_init = MultiBodyICP::CalculateMeshTransform(mod, M_thorax_init, 2);\n\n  // left wing:\n  arma::Mat<double> M_wing_L1_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_L_init.submat(0,0,3,3), 3);\n  arma::Mat<double> M_wing_L2_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_L_init.submat(0,4,3,7), 3);\n  arma::Mat<double> M_wing_L3_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_L_init.submat(0,8,3,11), 3);\n  arma::Mat<double> M_wing_L4_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_L_init.submat(0,12,3,15), 3);\n\n  // right wing:\n  arma::Mat<double> M_wing_R1_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_R_init.submat(0,0,3,3), 4);\n  arma::Mat<double> M_wing_R2_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_R_init.submat(0,4,3,7), 4);\n  arma::Mat<double> M_wing_R3_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_R_init.submat(0,8,3,11), 4);\n  arma::Mat<double> M_wing_R4_init = MultiBodyICP::CalculateMeshTransform(mod, M_wing_R_init.submat(0,12,3,15), 4);\n\n  // Project the model segments from 3d to 2d and back to 3d:\n\n  arma::Mat<double> mdl_pcl_thorax  = MultiBodyICP::GetProjectedModelPCL(mod, vox, fcg, M_thorax_init,  0, 1);\n  arma::Mat<double> mdl_pcl_head    = MultiBodyICP::GetProjectedModelPCL(mod, vox, fcg, M_head_init,    1, 1);\n  arma::Mat<double> mdl_pcl_abdomen = MultiBodyICP::GetProjectedModelPCL(mod, vox, fcg, M_abdomen_init, 2, 1);\n  arma::Mat<double> mdl_pcl_wing_L1 = MultiBodyICP::GetProjectedModelPCL(mod, vox, fcg, M_wing_L1_init, 3, 2);\n  arma::Mat<double> mdl_pcl_wing_L2 = MultiBodyICP::GetProjectedModelPCL(mod, vox, fcg, M_wing_L2_init, 3, 2);\n  arma::Mat<double> mdl_pcl_wing_L3 = MultiBodyICP::GetProjectedModelPCL(mod, vox, fcg, M_wing_L3_init, 3, 2);\n  arma::Mat<double> mdl_pcl_wing_L4 = MultiBodyICP::GetProjectedModelPCL(mod, vox, fcg, M_wing_L4_init, 3, 2);\n  arma::Mat<double> mdl_pcl_wing_R1 = MultiBodyICP::GetProjectedModelPCL(mod, vox, fcg, M_wing_R1_init, 4, 3);\n  arma::Mat<double> mdl_pcl_wing_R2 = MultiBodyICP::GetProjectedModelPCL(mod, vox, fcg, M_wing_R2_init, 4, 3);\n  arma::Mat<double> mdl_pcl_wing_R3 = MultiBodyICP::GetProjectedModelPCL(mod, vox, fcg, M_wing_R3_init, 4, 3);\n  arma::Mat<double> mdl_pcl_wing_R4 = MultiBodyICP::GetProjectedModelPCL(mod, vox, fcg, M_wing_R4_init, 4, 3);\n\n\n  // Perform ICP:\n  tuple<arma::Mat<double>,arma::Mat<double>,double> thorax_icp_results  = MultiBodyICP::ICPAlgorithm(mod, vox, fcg, body_pcl, mdl_pcl_thorax,  M_thorax_init,  0, 1);\n  tuple<arma::Mat<double>,arma::Mat<double>,double> head_icp_results    = MultiBodyICP::ICPAlgorithm(mod, vox, fcg, body_pcl, mdl_pcl_head,     M_head_init,    1, 2);\n  tuple<arma::Mat<double>,arma::Mat<double>,double> abdomen_icp_results = MultiBodyICP::ICPAlgorithm(mod, vox, fcg, body_pcl, mdl_pcl_abdomen, M_abdomen_init, 2, 3);\n  tuple<arma::Mat<double>,arma::Mat<double>,double> wing_L1_icp_results = MultiBodyICP::ICPAlgorithm(mod, vox, fcg, wing_L_pcl, mdl_pcl_wing_L1, M_wing_L1_init, 3, 5);\n  tuple<arma::Mat<double>,arma::Mat<double>,double> wing_L2_icp_results = MultiBodyICP::ICPAlgorithm(mod, vox, fcg, wing_L_pcl, mdl_pcl_wing_L2, M_wing_L2_init, 3, 5);\n  tuple<arma::Mat<double>,arma::Mat<double>,double> wing_L3_icp_results = MultiBodyICP::ICPAlgorithm(mod, vox, fcg, wing_L_pcl, mdl_pcl_wing_L3, M_wing_L1_init, 3, 5);\n  tuple<arma::Mat<double>,arma::Mat<double>,double> wing_L4_icp_results = MultiBodyICP::ICPAlgorithm(mod, vox, fcg, wing_L_pcl, mdl_pcl_wing_L4, M_wing_L2_init, 3, 5);\n  tuple<arma::Mat<double>,arma::Mat<double>,double> wing_R1_icp_results = MultiBodyICP::ICPAlgorithm(mod, vox, fcg, wing_R_pcl, mdl_pcl_wing_R1, M_wing_R1_init, 4, 10);\n  tuple<arma::Mat<double>,arma::Mat<double>,double> wing_R2_icp_results = MultiBodyICP::ICPAlgorithm(mod, vox, fcg, wing_R_pcl, mdl_pcl_wing_R2, M_wing_R2_init, 4, 10);\n  tuple<arma::Mat<double>,arma::Mat<double>,double> wing_R3_icp_results = MultiBodyICP::ICPAlgorithm(mod, vox, fcg, wing_R_pcl, mdl_pcl_wing_R3, M_wing_R1_init, 4, 10);\n  tuple<arma::Mat<double>,arma::Mat<double>,double> wing_R4_icp_results = MultiBodyICP::ICPAlgorithm(mod, vox, fcg, wing_R_pcl, mdl_pcl_wing_R4, M_wing_R2_init, 4, 10);\n\n  // Find best fit:\n  arma::Mat<double> pcl_mat_out = get<0>(thorax_icp_results);\n  pcl_mat_out = arma::join_rows(pcl_mat_out,get<0>(head_icp_results));\n  pcl_mat_out = arma::join_rows(pcl_mat_out,get<0>(abdomen_icp_results));\n\n  arma::Row<double> score_vec_L = {get<2>(wing_L1_icp_results), get<2>(wing_L2_icp_results),get<2>(wing_L3_icp_results), get<2>(wing_L4_icp_results)};\n  arma::Row<double> score_vec_R = {get<2>(wing_R1_icp_results), get<2>(wing_R2_icp_results),get<2>(wing_R3_icp_results), get<2>(wing_R4_icp_results)};\n\n  if (score_vec_L.index_min()==0) {\n    pcl_mat_out = arma::join_rows(pcl_mat_out,get<0>(wing_L1_icp_results));\n  }\n  else if (score_vec_L.index_min()==1) {\n    pcl_mat_out = arma::join_rows(pcl_mat_out,get<0>(wing_L2_icp_results));\n  }\n  else if (score_vec_L.index_min()==2) {\n    pcl_mat_out = arma::join_rows(pcl_mat_out,get<0>(wing_L3_icp_results));\n  }\n  else if (score_vec_L.index_min()==3) {\n    pcl_mat_out = arma::join_rows(pcl_mat_out,get<0>(wing_L4_icp_results));\n  }\n\n  if (score_vec_R.index_min()==0) {\n    pcl_mat_out = arma::join_rows(pcl_mat_out,get<0>(wing_R1_icp_results));\n  }\n  else if (score_vec_R.index_min()==1) {\n    pcl_mat_out = arma::join_rows(pcl_mat_out,get<0>(wing_R2_icp_results));\n  }\n  else if (score_vec_R.index_min()==2) {\n    pcl_mat_out = arma::join_rows(pcl_mat_out,get<0>(wing_R3_icp_results));\n  }\n  else if (score_vec_R.index_min()==3) {\n    pcl_mat_out = arma::join_rows(pcl_mat_out,get<0>(wing_R4_icp_results));\n  }\n\n  return pcl_mat_out;\n}\n*/\n\n//tuple<arma::Mat<double>,double> MultiBodyICP::PairAlign(arma::Mat<double> &dest_pcl, arma::Mat<double> &src_pcl) {\ntuple<arma::Mat<double>,double> MultiBodyICP::PairAlign(arma::Mat<double> &dest_pcl, model &mod, arma::Mat<double> M_init, int seg_ind) {\n\n  //PointCloud cloud_src = MultiBodyICP::Convert_Mat_2_PCL_XYZ(src_pcl);\n  //PointCloud cloud_tgt = MultiBodyICP::Convert_Mat_2_PCL_XYZ(dest_pcl);\n\n  PointCloud cloud_src = MultiBodyICP::GetModelSRCPointCloud(mod, M_init, seg_ind);\n  PointCloud cloud_tgt = MultiBodyICP::Convert_Mat_2_PCL_XYZ(dest_pcl);\n\n  PointCloud::Ptr src (new PointCloud);\n  PointCloud::Ptr tgt (new PointCloud);\n\n  PointCloud::Ptr cloud_src2 (new PointCloud);\n  PointCloud::Ptr cloud_tgt2 (new PointCloud);\n\n  *cloud_src2 = cloud_src;\n  *cloud_tgt2 = cloud_tgt;\n\n  pcl::VoxelGrid<PointT> grid;\n\n  grid.setLeafSize (0.06, 0.06, 0.06);\n  grid.setInputCloud (cloud_src2);\n  grid.filter (*src);\n\n  grid.setInputCloud (cloud_tgt2);\n  grid.filter (*tgt);\n\n  pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp;\n  //pcl::IterativeClosestPointNonLinear<pcl::PointXYZ, pcl::PointXYZ> icp;\n\n  icp.setMaxCorrespondenceDistance(0.2);\n  icp.setMaximumIterations(50);\n  icp.setTransformationEpsilon(0.001);\n  //icp.setEuclideanFitnessEpsilon(1);\n  icp.setRANSACIterations(50);\n  icp.setRANSACOutlierRejectionThreshold(0.06);\n\n  icp.setInputCloud(src);\n  icp.setInputTarget(tgt);\n\n  pcl::PointCloud<pcl::PointXYZ> Final;\n\n  icp.align(Final);\n\n  double score = icp.getFitnessScore();\n\n    // Get the transformation from target to source\n  //targetToSource = Ti.inverse();\n\n  Eigen::Matrix4f Ti = Eigen::Matrix4f::Identity ();\n\n  Ti = icp.getFinalTransformation();\n\n  arma::Mat<double> M_transform(4,4);\n\n  M_transform(0,0) = Ti(0,0);\n  M_transform(0,1) = Ti(0,1);\n  M_transform(0,2) = Ti(0,2);\n  M_transform(0,3) = Ti(0,3);\n  M_transform(1,0) = Ti(1,0);\n  M_transform(1,1) = Ti(1,1);\n  M_transform(1,2) = Ti(1,2);\n  M_transform(1,3) = Ti(1,3);\n  M_transform(2,0) = Ti(2,0);\n  M_transform(2,1) = Ti(2,1);\n  M_transform(2,2) = Ti(2,2);\n  M_transform(2,3) = Ti(2,3);\n  M_transform(3,0) = 0.0;\n  M_transform(3,1) = 0.0;\n  M_transform(3,2) = 0.0;\n  M_transform(3,3) = 1.0;\n\n  return make_tuple(M_transform,score);\n\n}\n\n/*\n//tuple<arma::Mat<double>,double> MultiBodyICP::PairAlign(arma::Mat<double> &dest_pcl, arma::Mat<double> &src_pcl) {\ntuple<arma::Mat<double>,double> MultiBodyICP::PairAlign(arma::Mat<double> &dest_pcl, model &mod, arma::Mat<double> M_init, int seg_ind) {\n\n  //PointCloud cloud_src = MultiBodyICP::Convert_Mat_2_PCL_XYZ(src_pcl);\n  PointCloud cloud_src = MultiBodyICP::GetModelSRCPointCloud(mod, M_init, seg_ind);\n  PointCloud cloud_tgt = MultiBodyICP::Convert_Mat_2_PCL_XYZ(dest_pcl);\n\n  PointCloud::Ptr src (new PointCloud);\n  PointCloud::Ptr tgt (new PointCloud);\n\n  PointCloud::Ptr cloud_src2 (new PointCloud);\n  PointCloud::Ptr cloud_tgt2 (new PointCloud);\n\n  *cloud_src2 = cloud_src;\n  *cloud_tgt2 = cloud_tgt;\n\n  //*src = cloud_src;\n  //*tgt = cloud_tgt;\n\n  pcl::VoxelGrid<PointT> grid;\n\n  grid.setLeafSize (0.06, 0.06, 0.06);\n  grid.setInputCloud (cloud_src2);\n  grid.filter (*src);\n\n  grid.setInputCloud (cloud_tgt2);\n  grid.filter (*tgt);\n\n  // Compute surface normals and curvature\n  PointCloudT::Ptr points_with_normals_src (new PointCloudT);\n  PointCloudT::Ptr points_with_normals_tgt (new PointCloudT);\n\n  //pcl::NormalEstimation<PointT, PointNT> norm_est;\n  pcl::NormalEstimationOMP<PointT, PointNT> norm_est;\n  pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ> ());\n  norm_est.setSearchMethod (tree);\n  norm_est.setKSearch (30);\n    \n  norm_est.setInputCloud (src);\n  norm_est.compute (*points_with_normals_src);\n  pcl::copyPointCloud (*src, *points_with_normals_src);\n\n  norm_est.setInputCloud (tgt);\n  norm_est.compute (*points_with_normals_tgt);\n  pcl::copyPointCloud (*tgt, *points_with_normals_tgt);\n\n  // Instantiate our custom point representation (defined above) ...\n  MyPointRepresentation point_representation;\n  // ... and weight the 'curvature' dimension so that it is balanced against x, y, and z\n  float alpha[4] = {1.0, 1.0, 1.0, 1.0};\n  point_representation.setRescaleValues (alpha);\n\n  // Align\n  pcl::IterativeClosestPointNonLinear<PointNT, PointNT> reg;\n  reg.setTransformationEpsilon (0.001);\n  //reg.setEuclideanFitnessEpsilon(1e-2);\n  // Set the maximum distance between two correspondences (src<->tgt) to 10cm\n  // Note: adjust this based on the size of your datasets\n  reg.setMaxCorrespondenceDistance (0.2);\n  // Set the point representation\n  reg.setPointRepresentation (boost::make_shared<const MyPointRepresentation> (point_representation));\n\n  reg.setInputSource (points_with_normals_src);\n  reg.setInputTarget (points_with_normals_tgt);\n\n  // Run the same optimization in a loop and visualize the results\n  Eigen::Matrix4f Ti = Eigen::Matrix4f::Identity (), prev, targetToSource;\n  PointCloudT::Ptr reg_result = points_with_normals_src;\n  reg.setMaximumIterations (30);\n\n  double score = 1.0;\n\n  clock_t start;\n  double duration;\n\n  start = clock();\n\n  for (int i = 0; i < 30; ++i) {\n    // save cloud for visualization purpose\n    points_with_normals_src = reg_result;\n\n    // Estimate\n    reg.setInputSource (points_with_normals_src);\n    reg.align (*reg_result);\n\n    //accumulate transformation between each Iteration\n    Ti = reg.getFinalTransformation () * Ti;\n\n    //if the difference between this transformation and the previous one\n    //is smaller than the threshold, refine the process by reducing\n    //the maximal correspondence distance\n    if (fabs ((reg.getLastIncrementalTransformation () - prev).sum ()) < reg.getTransformationEpsilon ())\n      reg.setMaxCorrespondenceDistance (reg.getMaxCorrespondenceDistance () - 0.001);\n    \n    prev = reg.getLastIncrementalTransformation ();\n\n    score = reg.getFitnessScore();\n  }\n\n  duration = (clock()-start)/ (double) CLOCKS_PER_SEC;\n\n  cout << \"iteration time\" << endl;\n  cout << duration << endl;\n\n  // Get the transformation from target to source\n  //targetToSource = Ti.inverse();\n\n  arma::Mat<double> M_transform(4,4);\n\n  M_transform(0,0) = Ti(0,0);\n  M_transform(0,1) = Ti(0,1);\n  M_transform(0,2) = Ti(0,2);\n  M_transform(0,3) = Ti(0,3);\n  M_transform(1,0) = Ti(1,0);\n  M_transform(1,1) = Ti(1,1);\n  M_transform(1,2) = Ti(1,2);\n  M_transform(1,3) = Ti(1,3);\n  M_transform(2,0) = Ti(2,0);\n  M_transform(2,1) = Ti(2,1);\n  M_transform(2,2) = Ti(2,2);\n  M_transform(2,3) = Ti(2,3);\n  M_transform(3,0) = 0.0;\n  M_transform(3,1) = 0.0;\n  M_transform(3,2) = 0.0;\n  M_transform(3,3) = 1.0;\n\n  return make_tuple(M_transform,score);\n}\n\n/*\ntuple<arma::Mat<double>,arma::Mat<double>,double> MultiBodyICP::ICPAlgorithm(model &mod, vox_grid &vox, FocalGrid &fcg, arma::Mat<double> &dest_pcl, arma::Mat<double> M_init, int seg_ind, int int_val) {\n\n  arma::Mat<double> src_pcl_i;\n\n  PointCloud cloud_src;\n  PointCloud cloud_tgt;\n\n  PointCloud::Ptr src (new PointCloud);\n  PointCloud::Ptr tgt (new PointCloud);\n\n  // Non-linear closest point:\n\n  pcl::IterativeClosestPointNonLinear<pcl::PointXYZ, pcl::PointXYZ> icp;\n\n  icp.setMaxCorrespondenceDistance(0.3);\n  icp.setMaximumIterations(30);\n  icp.setTransformationEpsilon(0.001);\n  icp.setEuclideanFitnessEpsilon(1);\n  icp.setRANSACIterations(30);\n  icp.setRANSACOutlierRejectionThreshold(0.04);\n\n  // Set target:\n  cloud_tgt = MultiBodyICP::Convert_Mat_2_PCL_XYZ(dest_pcl);\n  *tgt = cloud_tgt;\n  icp.setInputTarget(tgt);\n\n  // Iteration parameters:\n  int max_iter = 10;\n  double prev_score = 1e6;\n  int i = 0;\n\n  // Output parameters:\n  arma::Mat<double> M_out;\n  double score = 1.0;\n  pcl::PointCloud<pcl::PointXYZ> Final;\n  Eigen::Matrix4f Ti = Eigen::Matrix4f::Identity ();\n  arma::Mat<double> M_delta(4,4);\n  arma::Mat<double> M_update;\n  arma::Mat<double> src_pcl_out;\n  M_update = M_init;\n\n  while ((i < max_iter) && ((score/prev_score)<1.02)) {\n\n    // Set src:\n    src_pcl_i = MultiBodyICP::GetProjectedModelPCL(mod,vox,fcg,M_update,seg_ind,int_val);\n    cloud_src = MultiBodyICP::Convert_Mat_2_PCL_XYZ(src_pcl_i);\n    *src = cloud_src;\n    icp.setInputCloud(src);\n\n    // Align:\n    icp.align(Final);\n\n    score = icp.getFitnessScore();\n\n    Ti = icp.getFinalTransformation();\n\n    M_delta(0,0) = Ti(0,0);\n    M_delta(0,1) = Ti(0,1);\n    M_delta(0,2) = Ti(0,2);\n    M_delta(0,3) = Ti(0,3);\n    M_delta(1,0) = Ti(1,0);\n    M_delta(1,1) = Ti(1,1);\n    M_delta(1,2) = Ti(1,2);\n    M_delta(1,3) = Ti(1,3);\n    M_delta(2,0) = Ti(2,0);\n    M_delta(2,1) = Ti(2,1);\n    M_delta(2,2) = Ti(2,2);\n    M_delta(2,3) = Ti(2,3);\n    M_delta(3,0) = 0.0;\n    M_delta(3,1) = 0.0;\n    M_delta(3,2) = 0.0;\n    M_delta(3,3) = 1.0;\n\n    M_update = M_delta*M_update;\n\n    if ((score/prev_score)<1.02) {\n      src_pcl_out = src_pcl_i;\n      M_out = M_update;\n      prev_score = score;\n    }\n    else {\n      i = max_iter;\n    }\n\n    i++;\n  }\n\n  return make_tuple(src_pcl_out,M_out,score);\n}\n*/\n\n\ntuple<arma::Mat<double>,arma::Mat<double>,double> MultiBodyICP::ICPAlgorithm(model &mod, vox_grid &vox, FocalGrid &fcg, arma::Mat<double> &dest_pcl, arma::Mat<double> M_init, int seg_ind, int int_val) {\n\n  arma::Mat<double> M_update;\n  M_update = M_init;\n\n  tuple<arma::Mat<double>,double> pair_update = MultiBodyICP::PairAlign(dest_pcl, mod, M_init, seg_ind);\n\n  double score = get<1>(pair_update);\n\n  cout << \"score\" << endl;\n  cout << score << endl;\n\n  arma::Mat<double> M_delta = get<0>(pair_update);\n\n  cout << M_delta << endl;\n\n  M_update.submat(0,0,2,2) = M_delta.submat(0,0,2,2)*M_update.submat(0,0,2,2);\n  M_update(0,3) = M_update(0,3)+M_delta(0,3);\n  M_update(1,3) = M_update(1,3)+M_delta(1,3);\n  M_update(2,3) = M_update(2,3)+M_delta(2,3);\n\n  arma::Mat<double> src_pcl_out = MultiBodyICP::GetProjectedModelPCL(mod,vox,fcg,M_update,seg_ind,int_val);\n\n  return make_tuple(src_pcl_out,M_update,score);\n}\n\n/*\ntuple<arma::Mat<double>,arma::Mat<double>,double> MultiBodyICP::ICPAlgorithm(model &mod, vox_grid &vox, FocalGrid &fcg, arma::Mat<double> &dest_pcl, arma::Mat<double> M_init, int seg_ind, int int_val) {\n\n  double score = 1.0;\n  arma::Mat<double> src_pcl_i;\n  arma::Mat<double> src_pcl_out;\n  arma::Mat<double> M_update;\n  M_update = M_init;\n  arma::Mat<double> M_out;\n  M_out.eye(4,4);\n\n  int max_iter = 30;\n  double prev_score = 1e6;\n  int i = 0;\n\n  //for (int i=0; i<20; i++) {\n  while ((i < max_iter) && ((score/prev_score)<1.05)) {\n\n    cout << \"iteration\" << endl;\n    cout << i << endl;\n\n    src_pcl_i = MultiBodyICP::GetProjectedModelPCL(mod,vox,fcg,M_update,seg_ind,int_val);\n\n    tuple<arma::Mat<double>,double> pair_update = MultiBodyICP::PairAlign(dest_pcl, src_pcl_i);\n\n    //score = get<1>(pair_update);\n    score = get<1>(pair_update);\n    cout << \"score\" << endl;\n    cout << score << endl;\n\n    arma::Mat<double> M_delta = get<0>(pair_update);\n\n    M_update.submat(0,0,2,2) = M_update.submat(0,0,2,2)*M_delta.submat(0,0,2,2);\n    M_update(0,3) = M_update(0,3)+M_delta(0,3);\n    M_update(1,3) = M_update(1,3)+M_delta(1,3);\n    M_update(2,3) = M_update(2,3)+M_delta(2,3);\n\n    if ((score/prev_score)<1.05) {\n\n      M_out = M_update;\n      src_pcl_out = src_pcl_i;\n      prev_score = score;\n\n    }\n    else {\n      i = max_iter;\n    }\n\n    i++;\n  }\n\n  return make_tuple(src_pcl_out,M_out,score);\n}\n*/\n\ndouble MultiBodyICP::ProjectedModelScore(model &mod, vox_grid &vox, FocalGrid &fcg, arma::Mat<double> &dest_pcl, arma::Mat<double> M_init, int seg_ind, int int_val) {\n\n  pcl::PointCloud<pcl::PointXYZ> seg_pcl = MultiBodyICP::GetModelSRCPointCloud(mod, M_init, seg_ind);\n\n  vector<tuple<double,double,double,int>> seg_pcl_vec = MultiBodyICP::Convert_PCL_XYZ_2_Vec(seg_pcl, int_val);\n\n  vector<tuple<double,double,double,int>> dest_pcl_vec = MultiBodyICP::Convert_Mat_2_PCL_Vec(dest_pcl, int_val);\n\n  vector<arma::Col<int>> proj_mdl_frames = fcg.ProjectCloud2Image(seg_pcl_vec);\n\n  vector<arma::Col<int>> proj_dest_frames = fcg.ProjectCloud2Image(dest_pcl_vec);\n\n  int N_views = proj_mdl_frames.size();\n\n  double score = 0.0;\n\n  for (int i=0; i<N_views; i++) {\n\n    arma::Col<int> frame_diff = arma::abs(proj_dest_frames[i]-proj_mdl_frames[i]);\n\n    score += (1.0*arma::sum(frame_diff))/(1.0*arma::sum(proj_dest_frames[i]));\n\n  }\n\n  return score;\n\n}\n\narma::Mat<double> MultiBodyICP::GetProjectedModelPCL(model &mod, vox_grid &vox, FocalGrid &fcg, arma::Mat<double> M_init, int seg_ind, int int_val) {\n\n  // Project model pointcloud to 2d images:\n\n  pcl::PointCloud<pcl::PointXYZ> seg_pcl = MultiBodyICP::GetModelSRCPointCloud(mod, M_init, seg_ind);\n\n  vector<tuple<double,double,double,int>> seg_pcl_vec = MultiBodyICP::Convert_PCL_XYZ_2_Vec(seg_pcl, int_val);\n\n  vector<arma::Col<int>> proj_mdl_frames = fcg.ProjectCloud2Image(seg_pcl_vec);\n\n  // Project 2d images to pointcloud:\n\n  vector<tuple<int,double,double,double,double,double,double>> proj_pcl = fcg.ProjectImage2Cloud(proj_mdl_frames, vox);\n\n  arma::Mat<double> pcl_out = MultiBodyICP::Convert_PCL_Vec_2_Mat(proj_pcl);\n\n  return pcl_out;\n}\n\npcl::PolygonMesh MultiBodyICP::TransformMesh(pcl::PolygonMesh mesh_in, arma::Mat<double> transform_mat) {\n\n  pcl::PCLHeader header = mesh_in.header;\n\n  pcl::PCLPointCloud2 cloud2_in = mesh_in.cloud;\n\n  vector<pcl::Vertices> polygons = mesh_in.polygons;\n\n  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_in (new pcl::PointCloud<pcl::PointXYZ>);\n  pcl::fromPCLPointCloud2(cloud2_in, *cloud_in);\n\n  // Construct the transformation matrix\n\n  Eigen::Matrix4f trans_mat = Eigen::Matrix4f::Identity();\n\n  trans_mat(0,0) = transform_mat(0,0);\n  trans_mat(0,1) = transform_mat(0,1);\n  trans_mat(0,2) = transform_mat(0,2);\n  trans_mat(0,3) = transform_mat(0,3);\n  trans_mat(1,0) = transform_mat(1,0);\n  trans_mat(1,1) = transform_mat(1,1);\n  trans_mat(1,2) = transform_mat(1,2);\n  trans_mat(1,3) = transform_mat(1,3);\n  trans_mat(2,0) = transform_mat(2,0);\n  trans_mat(2,1) = transform_mat(2,1);\n  trans_mat(2,2) = transform_mat(2,2);\n  trans_mat(2,3) = transform_mat(2,3);\n\n  // Transform the pointcloud\n\n  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_out (new pcl::PointCloud<pcl::PointXYZ>);\n\n  pcl::transformPointCloud(*cloud_in, *cloud_out, trans_mat);\n\n  pcl::PCLPointCloud2::Ptr cloud2_out (new pcl::PCLPointCloud2);\n\n  pcl::toPCLPointCloud2(*cloud_out,*cloud2_out);\n\n  pcl::PolygonMesh mesh_out;\n\n  mesh_out.header = header;\n  mesh_out.polygons = polygons;\n  mesh_out.cloud = *cloud2_out;\n\n  return mesh_out;\n\n}\n\npcl::PointCloud<pcl::PointXYZ> MultiBodyICP::GetPointCloudFromMesh(pcl::PolygonMesh mesh_in) {\n\n  pcl::PointCloud<pcl::PointXYZ> cloud_out;\n\n  pcl::PCLPointCloud2 cloud2_in = mesh_in.cloud;\n\n  pcl::fromPCLPointCloud2(cloud2_in, cloud_out);\n\n  return cloud_out;\n}\n\narma::Mat<double> MultiBodyICP::MultiplyMat(arma::Mat<double> M_a, arma::Mat<double> M_b) {\n\n  arma::Mat<double> mult_mat;\n\n  mult_mat.zeros(4,4);\n\n  mult_mat.submat(0,0,2,2) = M_a.submat(0,0,2,2)*M_b.submat(0,0,2,2);\n\n  mult_mat.submat(0,0,2,0) = M_a.submat(0,0,2,2)*M_b.submat(0,0,2,0)+M_a.submat(0,0,2,0);\n\n  //mult_mat(0,3) = M_a(0,3)+M_b(0,3);\n  //mult_mat(1,3) = M_a(1,3)+M_b(1,3);\n  //mult_mat(2,3) = M_a(2,3)+M_b(2,3);\n\n  mult_mat(3,3) = 1.0;\n\n  return mult_mat;\n\n}\n\narma::Mat<double> MultiBodyICP::TransformMat(arma::Col<double> q_in, double scale) {\n\n  arma::Mat<double> start_mat;\n\n  start_mat.zeros(4,4);\n\n  start_mat(0,0) = (2.0*pow(q_in(0),2)-1.0+2.0*pow(q_in(1),2));\n  start_mat(0,1) = (2.0*q_in(1)*q_in(2)+2.0*q_in(0)*q_in(3));\n  start_mat(0,2) = (2.0*q_in(1)*q_in(3)-2.0*q_in(0)*q_in(2));\n  start_mat(0,3) = scale*(q_in(4));\n  start_mat(1,0) = (2.0*q_in(1)*q_in(2)-2.0*q_in(0)*q_in(3));\n  start_mat(1,1) = (2.0*pow(q_in(0),2)-1.0+2.0*pow(q_in(2),2));\n  start_mat(1,2) = (2.0*q_in(2)*q_in(3)+2.0*q_in(0)*q_in(1));\n  start_mat(1,3) = scale*(q_in(5));\n  start_mat(2,0) = (2.0*q_in(1)*q_in(3)+2.0*q_in(0)*q_in(2));\n  start_mat(2,1) = (2.0*q_in(2)*q_in(3)-2.0*q_in(0)*q_in(1));\n  start_mat(2,2) = (2.0*pow(q_in(0),2)-1.0+2.0*pow(q_in(3),2));\n  start_mat(2,3) = scale*(q_in(6));\n  start_mat(3,3) = 1.0;\n\n  return start_mat;\n\n}\n\narma::Mat<double> MultiBodyICP::Convert_PCL_Vec_2_Mat(vector<tuple<int,double,double,double,double,double,double>> pcl_in) {\n\n  int N_points = pcl_in.size();\n\n  arma::Mat<double> pcl_out(7,N_points);\n\n  for (int i=0; i<N_points; i++) {\n\n    pcl_out(0,i) = (double) get<0>(pcl_in[i]);\n    pcl_out(1,i) = get<1>(pcl_in[i]);\n    pcl_out(2,i) = get<2>(pcl_in[i]);\n    pcl_out(3,i) = get<3>(pcl_in[i]);\n    pcl_out(4,i) = get<4>(pcl_in[i]);\n    pcl_out(5,i) = get<5>(pcl_in[i]);\n    pcl_out(6,i) = get<6>(pcl_in[i]);\n\n  }\n\n  return pcl_out;\n}\n\nvector<tuple<double,double,double,int>> MultiBodyICP::Convert_PCL_XYZ_2_Vec(pcl::PointCloud<pcl::PointXYZ> pcl_in, int ind) {\n\n  vector<tuple<double,double,double,int>> pcl_out;\n\n  for (int i=0; i<pcl_in.points.size(); i++) {\n\n    pcl_out.push_back(make_tuple(pcl_in.points[i].x,pcl_in.points[i].y,pcl_in.points[i].z,ind));\n\n  }\n\n  return pcl_out;\n}\n\nvector<tuple<double,double,double,int>> MultiBodyICP::Convert_Mat_2_PCL_Vec(arma::Mat<double> &pcl_in, int ind) {\n\n  vector<tuple<double,double,double,int>> pcl_out;\n\n  for (int i=0; i<pcl_in.n_cols; i++) {\n\n    pcl_out.push_back(make_tuple(pcl_in(1,i),pcl_in(2,i),pcl_in(3,i),ind));\n\n  }\n\n  return pcl_out;\n}\n\npcl::PointCloud<pcl::PointXYZ> MultiBodyICP::Convert_Mat_2_PCL_XYZ(arma::Mat<double> pcl_mat) {\n\n  // Convert an armadillo matrix to a PointCloud vector\n\n  pcl::PointCloud<pcl::PointXYZ> pcl_vec;\n\n  int N_points = pcl_mat.n_cols;\n\n  for (int i=0; i<N_points; i++) {\n\n    pcl::PointXYZ point;\n    point.x = pcl_mat(1,i);\n    point.y = pcl_mat(2,i);\n    point.z = pcl_mat(3,i);\n\n    pcl_vec.push_back(point);\n\n  }\n\n  return pcl_vec;\n\n}\n\narma::Mat<double> MultiBodyICP::GetM(arma::Col<double> state_in) {\n\n  arma::Col<double> q_vec = {state_in(0),state_in(1),state_in(2),state_in(3)};\n  q_vec = q_vec/sqrt(pow(q_vec(0),2)+pow(q_vec(1),2)+pow(q_vec(2),2)+pow(q_vec(3),2));\n\n  double q0 = q_vec(0);\n  double q1 = q_vec(1);\n  double q2 = q_vec(2);\n  double q3 = q_vec(3);\n  double tx = state_in(4);\n  double ty = state_in(5);\n  double tz = state_in(6);\n\n  arma::Mat<double> M = {{2.0*pow(q0,2.0)-1.0+2.0*pow(q1,2.0), 2.0*q1*q2-2.0*q0*q3, 2.0*q1*q3+2.0*q0*q2, tx},\n    {2.0*q1*q2+2.0*q0*q3, 2.0*pow(q0,2.0)-1.0+2.0*pow(q2,2.0), 2.0*q2*q3-2.0*q0*q1, ty},\n    {2.0*q1*q3-2.0*q0*q2, 2.0*q2*q3+2.0*q0*q1, 2.0*pow(q0,2.0)-1.0+2.0*pow(q3,2.0), tz},\n    {0.0, 0.0, 0.0, 1.0}};\n\n  return M;\n\n}\n\nPointCloudT MultiBodyICP::TransferPointXYZ2PointNT(pcl::PointCloud<pcl::PointXYZ> pcl_in) {\n\n  PointCloudT pcl_out;\n\n  for (int i=0; i<pcl_in.points.size(); i++) {\n\n    PointNT point_out;\n\n    point_out.x = pcl_in.points[i].x;\n    point_out.y = pcl_in.points[i].y;\n    point_out.z = pcl_in.points[i].z;\n    point_out.normal_x = 1.0;\n    point_out.normal_y = 0.0;\n    point_out.normal_z = 0.0;\n\n    pcl_out.push_back(point_out);\n\n  }\n  return pcl_out;\n}\n\narma::Mat<double> MultiBodyICP::TransferPointCloudT2Mat(PointCloudT pcl_in, int int_val) {\n\n  int N_points = pcl_in.points.size();\n\n  arma::Mat<double> pcl_out(7,N_points);\n\n  for (int i=0; i<N_points; i++) {\n    pcl_out(0,i) = (double) int_val;\n    pcl_out(1,i) = pcl_in.points[i].x;\n    pcl_out(2,i) = pcl_in.points[i].y;\n    pcl_out(3,i) = pcl_in.points[i].z;\n    pcl_out(4,i) = 1.0;\n    pcl_out(5,i) = 0.0;\n    pcl_out(6,i) = 0.0;\n  }\n\n  return pcl_out;\n}\n\n", "meta": {"hexsha": "33285153ee173d27ef5665ee7f2813ff443bc16d", "size": 50748, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FlyTrackApp/multi_body_icp.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/multi_body_icp.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/multi_body_icp.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": 37.8152011923, "max_line_length": 202, "alphanum_fraction": 0.7204618901, "num_tokens": 17004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.29614125174964995}}
{"text": "/* \n * Type and constant definitions\n * Copyright (C) 2019  Robin Scheibler\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 * You should have received a copy of the MIT License along with this program. If\n * not, see <https://opensource.org/licenses/MIT>.\n */\n\n/* This file contains type and constants definitions */\n#ifndef __COMMON_HPP__\n#define __COMMON_HPP__\n\n#include <iostream>\n#include <Eigen/Dense>\n\nextern float libroom_eps;  // epsilon is the precision for floating point computations. It is defined in libroom.cpp\n\ntemplate<size_t D>\nusing Vectorf = Eigen::Matrix<float, D, 1>;\n\nusing MatrixXf = Eigen::MatrixXf;\ntypedef Eigen::Matrix<bool, Eigen::Dynamic, Eigen::Dynamic> MatrixXb;\ntypedef Eigen::Matrix<bool, Eigen::Dynamic, 1> VectorXb;\n\n/* The 'entry' type is simply defined as an array of 2 floats.\n * It represents an entry that is logged by the microphone\n * during the ray_tracing execution.\n * The first one of those float will be the travel time of a ray reaching\n * the microphone. The second one will be the energy of this ray.*/\n\nstruct Hit\n{\n  float distance = 0.f;\n  Eigen::ArrayXf transmitted;  // vector of transmitted energy over frequency bands\n\n  Hit(int _nfreq)\n  {\n    transmitted.resize(_nfreq);\n    transmitted.setOnes();\n  };\n  Hit(const float _d, const Eigen::ArrayXf &_t)\n    : distance(_d), transmitted(_t) {}\n};\n\ntypedef std::vector<std::list<Hit>> HitLog;\n\nsize_t get_new_size(size_t val, size_t cur_size)\n{\n  size_t new_size = cur_size;\n  while (val >= new_size)\n    new_size *= 2;\n  return new_size;\n}\n\nclass Histogram2D\n{\n  size_t rows, cols;\n  Eigen::ArrayXXf array;\n  Eigen::ArrayXXi counts;\n\n  public:\n    Histogram2D() {}  // empty constructor\n    Histogram2D(int _r, int _c) : rows(_r), cols(_c)\n    {\n      init(rows, cols);\n    }\n\n    void init(int rows, int cols)\n    {\n      array.resize(rows, cols);\n      array.setZero();\n      counts.resize(rows, cols);\n      counts.setZero();\n    }\n\n    void reset()\n    {\n      array.setZero();\n      counts.setZero();\n    }\n\n    void resize_rows(int new_rows)\n    {\n      auto old_rows = array.rows();\n      // this will resize the array while preserving the content\n      array.conservativeResize(new_rows, Eigen::NoChange);\n      counts.conservativeResize(new_rows, Eigen::NoChange);\n      // We need to initialize the new elements\n      if (new_rows > old_rows)\n      {\n        array.bottomRows(new_rows - old_rows).setZero();\n        counts.bottomRows(new_rows - old_rows).setZero();\n      }\n    }\n\n    void resize_cols(int new_cols)\n    {\n      auto old_cols = array.cols();\n      // this will resize the array while preserving the content\n      array.conservativeResize(Eigen::NoChange, new_cols);\n      counts.conservativeResize(Eigen::NoChange, new_cols);\n      // We need to initialize the new elements\n      if (new_cols > old_cols)\n      {\n        array.rightCols(new_cols - old_cols).setZero();\n        counts.rightCols(new_cols - old_cols).setZero();\n      }\n    }\n\n    void log(Eigen::Index row, Eigen::Index col, float val)\n    {\n      if (row >= array.rows())\n        resize_rows(get_new_size(row, array.rows()));\n\n      if (col >= array.cols())\n        resize_cols(get_new_size(col, array.cols()));\n\n      array.coeffRef(row, col) += val;\n      counts.coeffRef(row, col)++;\n    }\n\n    void log_col(Eigen::Index col, const Eigen::ArrayXf &val)\n    {\n      if (col >= array.cols())\n        resize_cols(get_new_size(col, array.cols()));\n\n      array.col(col) += val;\n      counts.col(col) += 1;\n    }\n\n    void log_row(Eigen::Index row, const Eigen::ArrayXf &val)\n    {\n      if (row >= array.rows())\n        resize_rows(get_new_size(row, array.rows()));\n\n      array.row(row) += val;\n      counts.row(row) += 1;\n    }\n\n    float bin(Eigen::Index row, Eigen::Index col) const\n    {\n      if (counts.coeff(row, col) != 0)\n        return array.coeff(row, col) / counts.coeff(row, col);\n      else\n        return 0.f;\n    }\n\n    Eigen::ArrayXXf get_hist() const\n    {\n      return array;\n    }\n};\n\n#endif // __COMMON_HPP__\n", "meta": {"hexsha": "b1a1170060f9e4899d9ba645f2ca0958e5bcf69e", "size": 5058, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pyroomacoustics/libroom_src/common.hpp", "max_stars_repo_name": "HemaZ/pyroomacoustics", "max_stars_repo_head_hexsha": "c401f829c71ff03a947f68f9b6b2f48346ae84b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-04T07:34:02.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-04T07:34:02.000Z", "max_issues_repo_path": "pyroomacoustics/libroom_src/common.hpp", "max_issues_repo_name": "HemaZ/pyroomacoustics", "max_issues_repo_head_hexsha": "c401f829c71ff03a947f68f9b6b2f48346ae84b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyroomacoustics/libroom_src/common.hpp", "max_forks_repo_name": "HemaZ/pyroomacoustics", "max_forks_repo_head_hexsha": "c401f829c71ff03a947f68f9b6b2f48346ae84b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-07T09:46:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-07T09:46:58.000Z", "avg_line_length": 29.2369942197, "max_line_length": 116, "alphanum_fraction": 0.6690391459, "num_tokens": 1230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.29614124488999993}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2014-2021, Oracle and/or its affiliates.\n\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// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_DISTANCE_SEGMENT_TO_SEGMENT_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_DISTANCE_SEGMENT_TO_SEGMENT_HPP\n\n#include <algorithm>\n#include <iterator>\n\n#include <boost/core/addressof.hpp>\n\n#include <boost/geometry/algorithms/assign.hpp>\n#include <boost/geometry/algorithms/detail/distance/is_comparable.hpp>\n#include <boost/geometry/algorithms/detail/distance/strategy_utils.hpp>\n#include <boost/geometry/algorithms/dispatch/distance.hpp>\n#include <boost/geometry/algorithms/intersects.hpp>\n\n#include <boost/geometry/core/point_type.hpp>\n#include <boost/geometry/core/tags.hpp>\n\n#include <boost/geometry/strategies/distance.hpp>\n#include <boost/geometry/strategies/tags.hpp>\n\n#include <boost/geometry/util/condition.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace distance\n{\n\n\n\n// compute segment-segment distance\ntemplate<typename Segment1, typename Segment2, typename Strategies>\nclass segment_to_segment\n{\n    typedef distance::strategy_t<Segment1, Segment2, Strategies> strategy_type;\n\npublic:\n    typedef distance::return_t<Segment1, Segment2, Strategies> return_type;\n\n    static inline return_type apply(Segment1 const& segment1, Segment2 const& segment2,\n                                    Strategies const& strategies)\n    {\n        if (geometry::intersects(segment1, segment2, strategies))\n        {\n            return 0;\n        }\n\n        typename point_type<Segment1>::type p[2];\n        detail::assign_point_from_index<0>(segment1, p[0]);\n        detail::assign_point_from_index<1>(segment1, p[1]);\n\n        typename point_type<Segment2>::type q[2];\n        detail::assign_point_from_index<0>(segment2, q[0]);\n        detail::assign_point_from_index<1>(segment2, q[1]);\n\n        strategy_type const strategy = strategies.distance(segment1, segment2);\n\n        auto const cstrategy = strategy::distance::services::get_comparable\n                                <\n                                    strategy_type\n                                >::apply(strategy);\n\n        distance::creturn_t<Segment1, Segment2, Strategies> d[4];\n        d[0] = cstrategy.apply(q[0], p[0], p[1]);\n        d[1] = cstrategy.apply(q[1], p[0], p[1]);\n        d[2] = cstrategy.apply(p[0], q[0], q[1]);\n        d[3] = cstrategy.apply(p[1], q[0], q[1]);\n\n        std::size_t imin = std::distance(boost::addressof(d[0]),\n                                         std::min_element(d, d + 4));\n\n        if (BOOST_GEOMETRY_CONDITION(is_comparable<strategy_type>::value))\n        {\n            return d[imin];\n        }\n\n        switch (imin)\n        {\n        case 0:\n            return strategy.apply(q[0], p[0], p[1]);\n        case 1:\n            return strategy.apply(q[1], p[0], p[1]);\n        case 2:\n            return strategy.apply(p[0], q[0], q[1]);\n        default:\n            return strategy.apply(p[1], q[0], q[1]);\n        }\n    }\n};\n\n\n\n\n}} // namespace detail::distance\n#endif // DOXYGEN_NO_DETAIL\n\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\n\n\n// segment-segment\ntemplate <typename Segment1, typename Segment2, typename Strategy>\nstruct distance\n    <\n        Segment1, Segment2, Strategy, segment_tag, segment_tag,\n        strategy_tag_distance_point_segment, false\n    >\n    : detail::distance::segment_to_segment<Segment1, Segment2, Strategy>\n{};\n\n\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_DISTANCE_SEGMENT_TO_SEGMENT_HPP\n", "meta": {"hexsha": "9cbececdb7f1a535219f53df2759ce978b3917ba", "size": 3882, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/algorithms/detail/distance/segment_to_segment.hpp", "max_stars_repo_name": "pranavgo/RRT", "max_stars_repo_head_hexsha": "87148c3ddb91600f4e74f00ffa8af14b54689aa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "boost/geometry/algorithms/detail/distance/segment_to_segment.hpp", "max_issues_repo_name": "pranavgo/RRT", "max_issues_repo_head_hexsha": "87148c3ddb91600f4e74f00ffa8af14b54689aa4", "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": "boost/geometry/algorithms/detail/distance/segment_to_segment.hpp", "max_forks_repo_name": "pranavgo/RRT", "max_forks_repo_head_hexsha": "87148c3ddb91600f4e74f00ffa8af14b54689aa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 28.3357664234, "max_line_length": 87, "alphanum_fraction": 0.6651210716, "num_tokens": 912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2961412448899999}}
{"text": "/* Copyright (c) 2019, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``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 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\n * 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 <boost/multiprecision/cpp_int.hpp>\n\n#include \"numeric.hpp\"\n\nusing namespace boost::multiprecision;\n\n//------------------------------------\n//           Miscellaneous\n//------------------------------------\n\n// Returns the smallest factor of an integer and the quotient after\n// division with the smallest factor.\nvoid SmallestFactor(uint64_t n, uint64_t& factor, uint64_t& residue)\n{\n  for (uint64_t i = 2; i < n; i++)\n  {\n    if (n % i == 0)\n    {\n      factor = i;\n      residue = n / i;\n      return;\n    }\n  }\n  factor = n;\n  residue = 1;\n}\n\n// Helper function to get close-to-square layouts of arrays\n// containing a given number of nodes.\nvoid GetTiling(uint64_t num_elems, uint64_t& height, uint64_t& width)\n{\n  std::vector<uint64_t> factors;\n  uint64_t residue = num_elems;\n  uint64_t cur_factor;\n  while (residue > 1)\n  {\n    SmallestFactor(residue, cur_factor, residue);\n    factors.push_back(cur_factor);\n  }\n\n  height = 1;\n  width = 1;\n  for (uint64_t i = 0; i < factors.size(); i++)\n  {\n    if (i % 2 == 0)\n      height *= factors[i];\n    else\n      width *= factors[i];\n  }\n\n  if (height > width)\n  {\n    uint64_t temp = height;\n    height = width;\n    width = temp;\n  }\n}\n\ndouble LinearInterpolate(double x,\n                         double x0, double x1,\n                         double q0, double q1)\n{\n  double slope = (x0 == x1) ? 0 : (q1 - q0) / double(x1 - x0);\n  return q0 + slope * (x - x0);\n}\n\ndouble BilinearInterpolate(double x, double y,\n                           double x0, double x1,\n                           double y0, double y1,\n                           double q00, double q01, double q10, double q11)\n{\n  // Linear interpolate along x dimension.\n  double qx0 = LinearInterpolate(x, x0, x1, q00, q10);\n  double qx1 = LinearInterpolate(x, x0, x1, q01, q11);\n\n  // Linear interpolate along y dimension.\n  return LinearInterpolate(y, y0, y1, qx0, qx1);\n}\n", "meta": {"hexsha": "e2df21ff4b058bab09ca1adac78a01b54619e40c", "size": 3460, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/util/numeric.cpp", "max_stars_repo_name": "tanvisharma/timeloop", "max_stars_repo_head_hexsha": "bd6985e6a4faa6d6383e5c2ae9bca4830a752ad2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T22:25:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T13:42:51.000Z", "max_issues_repo_path": "src/util/numeric.cpp", "max_issues_repo_name": "tanvisharma/timeloop", "max_issues_repo_head_hexsha": "bd6985e6a4faa6d6383e5c2ae9bca4830a752ad2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/util/numeric.cpp", "max_forks_repo_name": "tanvisharma/timeloop", "max_forks_repo_head_hexsha": "bd6985e6a4faa6d6383e5c2ae9bca4830a752ad2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-22T19:33:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T19:33:19.000Z", "avg_line_length": 32.641509434, "max_line_length": 74, "alphanum_fraction": 0.6598265896, "num_tokens": 837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.569852651414157, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.2960506027805881}}
{"text": "// Copyright Nick Thompson, 2019\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_INTERPOLATORS_CARDINAL_QUINTIC_B_SPLINE_HPP\n#define BOOST_MATH_INTERPOLATORS_CARDINAL_QUINTIC_B_SPLINE_HPP\n#include <memory>\n#include <limits>\n#include <boost/math/interpolators/detail/cardinal_quintic_b_spline_detail.hpp>\n\n\nnamespace boost{ namespace math{ namespace interpolators {\n\ntemplate <class Real>\nclass cardinal_quintic_b_spline\n{\npublic:\n    // If you don't know the value of the derivative at the endpoints, leave them as nans and the routine will estimate them.\n    // y[0] = y(a), y[n - 1] = y(b), step_size = (b - a)/(n -1).\n    cardinal_quintic_b_spline(const Real* const y,\n                                size_t n,\n                                Real t0 /* initial time, left endpoint */,\n                                Real h  /*spacing, stepsize*/,\n                                std::pair<Real, Real> left_endpoint_derivatives = {std::numeric_limits<Real>::quiet_NaN(), std::numeric_limits<Real>::quiet_NaN()},\n                                std::pair<Real, Real> right_endpoint_derivatives = {std::numeric_limits<Real>::quiet_NaN(), std::numeric_limits<Real>::quiet_NaN()})\n     : impl_(std::make_shared<detail::cardinal_quintic_b_spline_detail<Real>>(y, n, t0, h, left_endpoint_derivatives, right_endpoint_derivatives))\n    {}\n\n    // Oh the bizarre error messages if we template this on a RandomAccessContainer:\n    cardinal_quintic_b_spline(std::vector<Real> const & y,\n                                Real t0 /* initial time, left endpoint */,\n                                Real h  /*spacing, stepsize*/,\n                                std::pair<Real, Real> left_endpoint_derivatives = {std::numeric_limits<Real>::quiet_NaN(), std::numeric_limits<Real>::quiet_NaN()},\n                                std::pair<Real, Real> right_endpoint_derivatives = {std::numeric_limits<Real>::quiet_NaN(), std::numeric_limits<Real>::quiet_NaN()})\n     : impl_(std::make_shared<detail::cardinal_quintic_b_spline_detail<Real>>(y.data(), y.size(), t0, h, left_endpoint_derivatives, right_endpoint_derivatives))\n    {}\n\n\n    Real operator()(Real t) const {\n        return impl_->operator()(t);\n    }\n\n    Real prime(Real t) const {\n       return impl_->prime(t);\n    }\n\n    Real double_prime(Real t) const {\n        return impl_->double_prime(t);\n    }\n\n    Real t_max() const {\n        return impl_->t_max();\n    }\n\nprivate:\n    std::shared_ptr<detail::cardinal_quintic_b_spline_detail<Real>> impl_;\n};\n\n}}}\n#endif\n", "meta": {"hexsha": "3d72865d933a0171d878dd83f268f524effa82e8", "size": 2675, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/interpolators/cardinal_quintic_b_spline.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": 597.0, "max_stars_repo_stars_event_min_datetime": "2018-07-17T10:59:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:59:36.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/interpolators/cardinal_quintic_b_spline.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": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/interpolators/cardinal_quintic_b_spline.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": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 42.4603174603, "max_line_length": 164, "alphanum_fraction": 0.6471028037, "num_tokens": 628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2959585528883825}}
{"text": "#include \"modules/neuralNetwork/layer/activation/activation.hpp\"\n#include \"modules/neuralNetwork/neuralNetwork.hpp\"\n\n#ifdef _KORALI_USE_CUDNN\n  #include \"auxiliar/cudaUtils.hpp\"\n#endif\n\n#ifdef _KORALI_USE_ONEDNN\n  #include \"auxiliar/dnnUtils.hpp\"\nusing namespace dnnl;\n#endif\n\n#include <Eigen/Dense>\nusing namespace Eigen;\n\nnamespace korali\n{\nnamespace neuralNetwork\n{\nnamespace layer\n{\n;\n\nvoid Activation::initialize()\n{\n  // The node count for this layer should be the same as the previous layer\n  _outputChannels = _prevLayer->_outputChannels;\n\n  // Checking Layer size\n  if (_outputChannels == 0) KORALI_LOG_ERROR(\"Node count for layer (%lu) should be larger than zero.\\n\", _index);\n\n  // Checking position\n  if (_index == 0) KORALI_LOG_ERROR(\"Activation layers cannot be the starting layer of the NN\\n\");\n  if (_index == _nn->_layers.size() - 1) KORALI_LOG_ERROR(\"Activation layers cannot be the last layer of the NN\\n\");\n}\n\nvoid Activation::createForwardPipeline()\n{\n  // Calling base layer function\n  Layer::createForwardPipeline();\n\n#ifdef _KORALI_USE_ONEDNN\n  if (_nn->_engine == \"OneDNN\")\n  {\n    // If it is an element-wise operation, create an element-wise primitive\n    if (_function.rfind(\"Elementwise\", 0) == 0)\n    {\n      if (_function == \"Elementwise/Clip\") _activationAlgorithm = algorithm::eltwise_clip;\n      if (_function == \"Elementwise/Linear\") _activationAlgorithm = algorithm::eltwise_linear;\n      if (_function == \"Elementwise/Log\") _activationAlgorithm = algorithm::eltwise_log;\n      if (_function == \"Elementwise/Logistic\") _activationAlgorithm = algorithm::eltwise_logistic;\n      if (_function == \"Elementwise/ReLU\") _activationAlgorithm = algorithm::eltwise_relu;\n      if (_function == \"Elementwise/SoftReLU\") _activationAlgorithm = algorithm::eltwise_soft_relu;\n      if (_function == \"Elementwise/SoftSign\") KORALI_LOG_ERROR(\"ONEDNN does not support activation functions of type 'Elementwise/SoftSign'.\");\n      if (_function == \"Elementwise/Tanh\") _activationAlgorithm = algorithm::eltwise_tanh;\n\n      // Creating descriptor\n      auto activationDesc = eltwise_forward::desc(\n        _propKind,\n        _activationAlgorithm,\n        _prevLayer->_outputMem[0].get_desc(),\n        _alpha,\n        _beta);\n\n      // Create primitive descriptor.\n      _forwardEltwiseActivationPrimitiveDesc = eltwise_forward::primitive_desc(activationDesc, _nn->_dnnlEngine);\n\n      // Create the primitive.\n      _forwardActivationPrimitive = eltwise_forward(_forwardEltwiseActivationPrimitiveDesc);\n    }\n\n    // Check other possible types of activation functions\n    if (_function == \"Softmax\")\n    {\n      // Creating descriptor\n      const int axis = 1;\n      auto activationDesc = softmax_forward::desc(_propKind, _prevLayer->_outputMem[0].get_desc(), axis);\n\n      // Create primitive descriptor.\n      _forwardSoftmaxActivationPrimitiveDesc = softmax_forward::primitive_desc(activationDesc, _nn->_dnnlEngine);\n\n      // Create the primitive.\n      _forwardActivationPrimitive = softmax_forward(_forwardSoftmaxActivationPrimitiveDesc);\n    }\n  }\n#endif\n\n#ifdef _KORALI_USE_CUDNN\n  if (_nn->_engine == \"CuDNN\")\n  {\n    cudnnErrCheck(cudnnCreateActivationDescriptor(&_activationDesc));\n    cudnnActivationMode_t activationMode;\n\n    if (_function == \"Elementwise/Clip\") activationMode = CUDNN_ACTIVATION_CLIPPED_RELU;\n    if (_function == \"Elementwise/Linear\") activationMode = CUDNN_ACTIVATION_IDENTITY;\n    if (_function == \"Elementwise/Log\") KORALI_LOG_ERROR(\"Activation function not supported: %s.\\n\", _function.c_str());\n    if (_function == \"Elementwise/Logistic\") activationMode = CUDNN_ACTIVATION_SIGMOID;\n    if (_function == \"Elementwise/ReLU\") activationMode = CUDNN_ACTIVATION_RELU;\n    if (_function == \"Elementwise/SoftReLU\") KORALI_LOG_ERROR(\"CUDNN does not support activation functions of type 'Elementwise/SoftSign'.\");\n    if (_function == \"Elementwise/SoftSign\") KORALI_LOG_ERROR(\"CUDNN does not support activation functions of type 'Elementwise/SoftSign'.\");\n    if (_function == \"Elementwise/Tanh\") activationMode = CUDNN_ACTIVATION_TANH;\n    if (_function == \"Softmax\") activationMode = CUDNN_ACTIVATION_IDENTITY;\n\n    if (cudnnSetActivationDescriptor(_activationDesc, activationMode, CUDNN_PROPAGATE_NAN, _alpha) != CUDNN_STATUS_SUCCESS) KORALI_LOG_ERROR(\"Error creating activation algorithm\\n\");\n  }\n#endif\n}\n\nvoid Activation::createBackwardPipeline()\n{\n  // Calling base layer function\n  Layer::createBackwardPipeline();\n\n// Creating backward propagation primitives for activation functions\n#ifdef _KORALI_USE_ONEDNN\n  if (_nn->_engine == \"OneDNN\")\n  {\n    // If it is an element-wise operation, create an element-wise backward primitive\n    if (_function.rfind(\"Elementwise\", 0) == 0)\n    {\n      // Creating descriptor\n      auto activationDesc = eltwise_backward::desc(_activationAlgorithm, _prevLayer->_outputMem[0].get_desc(), _outputMem[0].get_desc(), _alpha, _beta);\n\n      // Create primitive descriptor.\n      auto backwardActivationPrimitiveDesc = eltwise_backward::primitive_desc(activationDesc, _nn->_dnnlEngine, _forwardEltwiseActivationPrimitiveDesc);\n\n      // Create the primitive.\n      _backwardActivationPrimitive = eltwise_backward(backwardActivationPrimitiveDesc);\n    }\n\n    // Check other possible types of activation functions\n    if (_function == \"Softmax\")\n    {\n      // Creating descriptor\n      const int axis = 1;\n      auto activationDesc = softmax_backward::desc(_prevLayer->_outputMem[0].get_desc(), _outputMem[0].get_desc(), axis);\n\n      // Create primitive descriptor.\n      auto backwardActivationPrimitiveDesc = softmax_backward::primitive_desc(activationDesc, _nn->_dnnlEngine, _forwardSoftmaxActivationPrimitiveDesc);\n\n      // Create the primitive.\n      _backwardActivationPrimitive = softmax_backward(backwardActivationPrimitiveDesc);\n    }\n  }\n#endif\n}\n\nvoid Activation::forwardData(const size_t t)\n{\n  size_t N = _batchSize;\n  size_t OC = _outputChannels;\n\n  if (_nn->_engine == \"Korali\")\n  {\n    if (_function == \"Elementwise/Clip\")\n    {\n      for (size_t i = 0; i < N * OC; i++)\n      {\n        if (_prevLayer->_outputValues[i] < _alpha)\n          _outputValues[i] = _alpha;\n        else if (_prevLayer->_outputValues[i] > _beta)\n          _outputValues[i] = _beta;\n        else\n          _outputValues[i] = _prevLayer->_outputValues[i];\n      }\n    }\n    if (_function == \"Elementwise/Linear\")\n    {\n      for (size_t i = 0; i < N * OC; i++)\n        _outputValues[i] = _prevLayer->_outputValues[i] * _alpha + _beta;\n    }\n    if (_function == \"Elementwise/Log\")\n    {\n      for (size_t i = 0; i < N * OC; i++)\n        _outputValues[i] = std::log(_prevLayer->_outputValues[i]);\n    }\n    if (_function == \"Elementwise/ReLU\")\n    {\n      for (size_t i = 0; i < N * OC; i++)\n        if (_prevLayer->_outputValues[i] > 0.0f)\n          _outputValues[i] = _prevLayer->_outputValues[i];\n        else\n          _outputValues[i] = _prevLayer->_outputValues[i] * _alpha;\n    }\n    if (_function == \"Elementwise/SoftReLU\")\n    {\n      for (size_t i = 0; i < N * OC; i++)\n        _outputValues[i] = std::log(1.0f + std::exp(_prevLayer->_outputValues[i]));\n    }\n\n    if (_function == \"Elementwise/Tanh\")\n    {\n      for (size_t i = 0; i < N * OC; i++)\n        _outputValues[i] = std::tanh(_prevLayer->_outputValues[i]);\n    }\n    if (_function == \"Elementwise/Logistic\")\n    {\n      for (size_t i = 0; i < N * OC; i++)\n        _outputValues[i] = 1.0f / (1.0f + std::exp(-_prevLayer->_outputValues[i]));\n    }\n    if (_function == \"Elementwise/SoftSign\")\n    {\n      for (size_t i = 0; i < N * OC; i++)\n        _outputValues[i] = _prevLayer->_outputValues[i] / (1.0f + std::abs(_prevLayer->_outputValues[i]));\n    }\n    if (_function == \"Softmax\")\n    {\n      for (size_t i = 0; i < N; i++)\n      {\n        float LSE = logSumExp(&_prevLayer->_outputValues[i * OC], OC);\n        for (size_t j = 0; j < OC; j++)\n          _outputValues[i * OC + j] = std::exp(_prevLayer->_outputValues[i * OC + j] - LSE);\n      }\n    }\n  }\n\n#ifdef _KORALI_USE_ONEDNN\n  if (_nn->_engine == \"OneDNN\")\n  {\n    // Primitive arguments.\n    _forwardActivationArgs[DNNL_ARG_SRC] = _prevLayer->_outputMem[t];\n    _forwardActivationArgs[DNNL_ARG_DST] = _outputMem[t];\n\n    _forwardActivationPrimitive.execute(_nn->_dnnlStream, _forwardActivationArgs);\n  }\n#endif\n\n#ifdef _KORALI_USE_CUDNN\n  if (_nn->_engine == \"CuDNN\")\n  {\n    if (_function == \"Elementwise/Linear\")\n    {\n      cudaErrCheck(cudaMemcpy(\n        _outputTensor[t],\n        _prevLayer->_outputTensor[t],\n        N * OC * sizeof(float),\n        cudaMemcpyDeviceToDevice));\n    }\n    else if (_function == \"Softmax\")\n    {\n      cudnnErrCheck(cudnnSoftmaxForward(\n        _nn->_cuDNNHandle,\n        CUDNN_SOFTMAX_LOG,\n        CUDNN_SOFTMAX_MODE_CHANNEL,\n        &_alpha,\n        _prevLayer->_outputTensorDesc,\n        _prevLayer->_outputTensor[t],\n        &_beta,\n        _outputTensorDesc,\n        _outputTensor[t]));\n    }\n    else\n    {\n      cudnnErrCheck(cudnnActivationForward(\n        _nn->_cuDNNHandle,\n        _activationDesc,\n        &_alpha,\n        _prevLayer->_outputTensorDesc,\n        _prevLayer->_outputTensor[t],\n        &_beta,\n        _outputTensorDesc,\n        _outputTensor[t]));\n    }\n  }\n#endif\n}\n\nvoid Activation::backwardData(const size_t t)\n{\n  size_t N = _batchSize;\n  size_t OC = _outputChannels;\n\n  if (_nn->_mode == \"Inference\")\n    KORALI_LOG_ERROR(\"Requesting Layer backward data propagation but NN was configured for inference only.\\n\");\n\n  if (_nn->_engine == \"Korali\")\n  {\n    if (_function == \"Elementwise/Linear\")\n      for (size_t i = 0; i < N * OC; i++)\n        _prevLayer->_outputGradient[i] = _outputGradient[i] * _alpha;\n\n    if (_function == \"Elementwise/Log\")\n      for (size_t i = 0; i < N * OC; i++)\n        _prevLayer->_outputGradient[i] = _outputGradient[i] / _prevLayer->_outputValues[i];\n\n    if (_function == \"Elementwise/ReLU\")\n    {\n      for (size_t i = 0; i < N * OC; i++)\n        if (_prevLayer->_outputValues[i] > 0.0f)\n        {\n          _prevLayer->_outputGradient[i] = _outputGradient[i];\n        }\n        else\n        {\n          _prevLayer->_outputGradient[i] = _outputGradient[i] * _alpha;\n        }\n    }\n    if (_function == \"Elementwise/SoftReLU\")\n      for (size_t i = 0; i < N * OC; i++)\n      {\n        const float expOutVal = std::exp(_outputValues[i]);\n        _prevLayer->_outputGradient[i] = _outputGradient[i] * (expOutVal - 1.0f) / expOutVal;\n      }\n\n    if (_function == \"Elementwise/Tanh\")\n      for (size_t i = 0; i < N * OC; i++)\n        _prevLayer->_outputGradient[i] = _outputGradient[i] * (1.0f - _outputValues[i] * _outputValues[i]);\n\n    if (_function == \"Elementwise/Logistic\")\n      for (size_t i = 0; i < N * OC; i++)\n        _prevLayer->_outputGradient[i] = _outputGradient[i] * _outputValues[i] * (1.0f - _outputValues[i]);\n\n    if (_function == \"Elementwise/SoftSign\")\n      for (size_t i = 0; i < N * OC; i++)\n        _prevLayer->_outputGradient[i] = _outputGradient[i] / ((1.0f + std::abs(_outputValues[i])) * (1.0f + std::abs(_outputValues[i])));\n\n    if (_function == \"Softmax\")\n      for (size_t i = 0; i < N * OC; i++)\n        _prevLayer->_outputGradient[i] = _outputGradient[i] * _outputValues[i] * (1.0f - _outputValues[i]);\n  }\n\n#ifdef _KORALI_USE_ONEDNN\n  if (_nn->_engine == \"OneDNN\")\n  {\n    // Primitive arguments.\n    _backwardActivationArgs[DNNL_ARG_DIFF_DST] = _outputGradientMem[t];             // Input\n    _backwardActivationArgs[DNNL_ARG_SRC] = _prevLayer->_outputMem[t];              // Input\n    _backwardActivationArgs[DNNL_ARG_DIFF_SRC] = _prevLayer->_outputGradientMem[t]; // Output\n    if (_function == \"Softmax\") _backwardActivationArgs[DNNL_ARG_DST] = _outputMem[t];\n\n    _backwardActivationPrimitive.execute(_nn->_dnnlStream, _backwardActivationArgs);\n  }\n#endif\n\n#ifdef _KORALI_USE_CUDNN\n  if (_nn->_engine == \"CuDNN\")\n  {\n    if (_function == \"Elementwise/Linear\")\n    {\n      cudaErrCheck(cudaMemcpy(\n        _prevLayer->_outputGradientTensor[t],\n        _outputGradientTensor[t],\n        N * OC * sizeof(float),\n        cudaMemcpyDeviceToDevice));\n    }\n    else if (_function == \"Softmax\")\n    {\n      cudnnErrCheck(cudnnSoftmaxBackward(\n        _nn->_cuDNNHandle,\n        CUDNN_SOFTMAX_LOG,\n        CUDNN_SOFTMAX_MODE_CHANNEL,\n        &_alpha,\n        _outputTensorDesc,\n        _outputTensor[t],\n        _outputTensorDesc,\n        _outputGradientTensor[t],\n        &_beta,\n        _prevLayer->_outputTensorDesc,\n        _prevLayer->_outputGradientTensor[t]));\n    }\n    else\n    {\n      cudnnErrCheck(cudnnActivationBackward(\n        _nn->_cuDNNHandle,\n        _activationDesc,\n        &_alpha,\n        _outputTensorDesc,\n        _outputTensor[t],\n        _outputTensorDesc,\n        _outputGradientTensor[t],\n        _prevLayer->_outputTensorDesc,\n        _prevLayer->_outputTensor[t],\n        &_beta,\n        _prevLayer->_outputTensorDesc,\n        _prevLayer->_outputGradientTensor[t]));\n    }\n  }\n#endif\n}\n\nvoid Activation::setConfiguration(knlohmann::json& js) \n{\n if (isDefined(js, \"Results\"))  eraseValue(js, \"Results\");\n\n if (isDefined(js, \"Function\"))\n {\n try { _function = js[\"Function\"].get<std::string>();\n} catch (const std::exception& e)\n { KORALI_LOG_ERROR(\" + Object: [ activation ] \\n + Key:    ['Function']\\n%s\", e.what()); } \n{\n bool validOption = false; \n if (_function == \"Elementwise/Clip\") validOption = true; \n if (_function == \"Elementwise/Linear\") validOption = true; \n if (_function == \"Elementwise/Log\") validOption = true; \n if (_function == \"Elementwise/Logistic\") validOption = true; \n if (_function == \"Elementwise/ReLU\") validOption = true; \n if (_function == \"Elementwise/SoftReLU\") validOption = true; \n if (_function == \"Elementwise/SoftSign\") validOption = true; \n if (_function == \"Elementwise/Tanh\") validOption = true; \n if (_function == \"Softmax\") validOption = true; \n if (validOption == false) KORALI_LOG_ERROR(\" + Unrecognized value (%s) provided for mandatory setting: ['Function'] required by activation.\\n\", _function.c_str()); \n}\n   eraseValue(js, \"Function\");\n }\n  else   KORALI_LOG_ERROR(\" + No value provided for mandatory setting: ['Function'] required by activation.\\n\"); \n\n if (isDefined(js, \"Alpha\"))\n {\n try { _alpha = js[\"Alpha\"].get<float>();\n} catch (const std::exception& e)\n { KORALI_LOG_ERROR(\" + Object: [ activation ] \\n + Key:    ['Alpha']\\n%s\", e.what()); } \n   eraseValue(js, \"Alpha\");\n }\n  else   KORALI_LOG_ERROR(\" + No value provided for mandatory setting: ['Alpha'] required by activation.\\n\"); \n\n if (isDefined(js, \"Beta\"))\n {\n try { _beta = js[\"Beta\"].get<float>();\n} catch (const std::exception& e)\n { KORALI_LOG_ERROR(\" + Object: [ activation ] \\n + Key:    ['Beta']\\n%s\", e.what()); } \n   eraseValue(js, \"Beta\");\n }\n  else   KORALI_LOG_ERROR(\" + No value provided for mandatory setting: ['Beta'] required by activation.\\n\"); \n\n Layer::setConfiguration(js);\n _type = \"layer/activation\";\n if(isDefined(js, \"Type\")) eraseValue(js, \"Type\");\n if(isEmpty(js) == false) KORALI_LOG_ERROR(\" + Unrecognized settings for Korali module: activation: \\n%s\\n\", js.dump(2).c_str());\n} \n\nvoid Activation::getConfiguration(knlohmann::json& js) \n{\n\n js[\"Type\"] = _type;\n   js[\"Function\"] = _function;\n   js[\"Alpha\"] = _alpha;\n   js[\"Beta\"] = _beta;\n Layer::getConfiguration(js);\n} \n\nvoid Activation::applyModuleDefaults(knlohmann::json& js) \n{\n\n std::string defaultString = \"{\\\"Alpha\\\": 1.0, \\\"Beta\\\": 0.0}\";\n knlohmann::json defaultJs = knlohmann::json::parse(defaultString);\n mergeJson(js, defaultJs); \n Layer::applyModuleDefaults(js);\n} \n\nvoid Activation::applyVariableDefaults() \n{\n\n Layer::applyVariableDefaults();\n} \n\n;\n\n} //layer\n} //neuralNetwork\n} //korali\n;\n", "meta": {"hexsha": "bac654b5eaf9f2b1081bf542d0263996389a46e3", "size": 15671, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/modules/neuralNetwork/layer/activation/activation.cpp", "max_stars_repo_name": "JonathanLehner/korali", "max_stars_repo_head_hexsha": "90f97d8e2fed2311f988f39cfe014f23ba7dd6cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 43.0, "max_stars_repo_stars_event_min_datetime": "2018-07-26T07:20:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T10:23:12.000Z", "max_issues_repo_path": "source/modules/neuralNetwork/layer/activation/activation.cpp", "max_issues_repo_name": "JonathanLehner/korali", "max_issues_repo_head_hexsha": "90f97d8e2fed2311f988f39cfe014f23ba7dd6cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 212.0, "max_issues_repo_issues_event_min_datetime": "2018-09-21T10:44:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T14:33:05.000Z", "max_forks_repo_path": "source/modules/neuralNetwork/layer/activation/activation.cpp", "max_forks_repo_name": "JonathanLehner/korali", "max_forks_repo_head_hexsha": "90f97d8e2fed2311f988f39cfe014f23ba7dd6cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2018-07-25T15:00:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T14:19:46.000Z", "avg_line_length": 33.9199134199, "max_line_length": 182, "alphanum_fraction": 0.6609661158, "num_tokens": 4268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.4726834766204329, "lm_q1q2_score": 0.2959585528883825}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2019 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_DETAIL_ENDIAN_SHIFT_HPP\n#define CRYPTO3_DETAIL_ENDIAN_SHIFT_HPP\n\n#include <boost/assert.hpp>\n\n#include <nil/crypto3/detail/stream_endian.hpp>\n#include <nil/crypto3/detail/basic_functions.hpp>\n#include <nil/crypto3/detail/unbounded_shift.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace detail {\n\n            template<typename Endianness, std::size_t WordBits>\n            struct endian_shift;\n\n            template<int UnitBits, std::size_t WordBits>\n            struct endian_shift<stream_endian::big_unit_big_bit<UnitBits>, WordBits>\n                : public basic_functions<WordBits> {\n\n                constexpr static const std::size_t word_bits = basic_functions<WordBits>::word_bits;\n                typedef typename basic_functions<WordBits>::word_type word_type;\n\n                static word_type &to_msb(word_type &w, std::size_t shift) {\n                    // shift to most significant bits according to endianness\n                    w = unbounded_shl(w, shift);\n                    return w;\n                }\n            };\n\n            template<int UnitBits, std::size_t WordBits>\n            struct endian_shift<stream_endian::little_unit_big_bit<UnitBits>, WordBits>\n                : public basic_functions<WordBits> {\n\n                constexpr static const std::size_t word_bits = basic_functions<WordBits>::word_bits;\n                typedef typename basic_functions<WordBits>::word_type word_type;\n\n                static word_type &to_msb(word_type &w, std::size_t shift) {\n                    // shift to most significant bits according to endianness\n                    std::size_t shift_rem = shift % UnitBits;\n                    std::size_t shift_unit_bits = shift - shift_rem;\n\n                    std::size_t sz[2] = {UnitBits - shift_rem, shift_rem};\n                    word_type masks[2];\n                    masks[0] = unbounded_shl(low_bits<word_bits>(~word_type(), sz[0]), shift_unit_bits);\n                    masks[1] =\n                        unbounded_shl(low_bits<word_bits>(~word_type(), sz[1]), shift_unit_bits + UnitBits + sz[0]);\n                    std::size_t bits_left = word_bits - shift;\n\n                    word_type w_combined = 0;\n                    int ind = 0;\n\n                    while (bits_left) {\n                        w_combined |= (!ind ? unbounded_shl(w & masks[0], shift_rem) :\n                                              unbounded_shr(w & masks[1], UnitBits + sz[0]));\n                        bits_left -= sz[ind];\n                        masks[ind] = unbounded_shl(masks[ind], UnitBits);\n                        ind = 1 - ind;\n                    }\n\n                    w = unbounded_shr(w_combined, shift_unit_bits);\n                    return w;\n                }\n            };\n\n            template<int UnitBits, std::size_t WordBits>\n            struct endian_shift<stream_endian::big_unit_little_bit<UnitBits>, WordBits>\n                : public basic_functions<WordBits> {\n\n                constexpr static const std::size_t word_bits = basic_functions<WordBits>::word_bits;\n                typedef typename basic_functions<WordBits>::word_type word_type;\n\n                static word_type &to_msb(word_type &w, std::size_t shift) {\n                    // shift to most significant bits according to endianness\n                    std::size_t shift_rem = shift % UnitBits;\n                    std::size_t shift_unit_bits = shift - shift_rem;\n\n                    std::size_t sz[2] = {UnitBits - shift_rem, shift_rem};\n                    word_type masks[2] = {\n                        unbounded_shr(high_bits<word_bits>(~word_type(), sz[0]), shift_unit_bits),\n                        unbounded_shr(high_bits<word_bits>(~word_type(), sz[1]), shift_unit_bits + UnitBits + sz[0])};\n\n                    std::size_t bits_left = word_bits - shift;\n                    word_type w_combined = 0;\n                    int ind = 0;\n\n                    while (bits_left) {\n                        w_combined |= (!ind ? unbounded_shr(w & masks[0], shift_rem) :\n                                              unbounded_shl(w & masks[1], UnitBits + sz[0]));\n                        bits_left -= sz[ind];\n                        masks[ind] = unbounded_shr(masks[ind], UnitBits);\n                        ind = 1 - ind;\n                    }\n\n                    w = unbounded_shl(w_combined, shift_unit_bits);\n                    return w;\n                }\n            };\n\n            template<int UnitBits, std::size_t WordBits>\n            struct endian_shift<stream_endian::little_unit_little_bit<UnitBits>, WordBits>\n                : public basic_functions<WordBits> {\n\n                constexpr static const std::size_t word_bits = basic_functions<WordBits>::word_bits;\n                typedef typename basic_functions<WordBits>::word_type word_type;\n\n                static word_type &to_msb(word_type &w, std::size_t shift) {\n\n                    // shift to most significant bits according to endianness\n                    w = unbounded_shr(w, shift);\n                    return w;\n                }\n            };\n        }    // namespace detail\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_DETAIL_ENDIAN_SHIFT_HPP\n", "meta": {"hexsha": "6d6fd12fd23f4f56d8f21ad252c118fa82b43fa2", "size": 6636, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/detail/endian_shift.hpp", "max_stars_repo_name": "NilFoundation/crypto3-modes", "max_stars_repo_head_hexsha": "f21ae3185dcd37ccef31523e40ec0203c201da36", "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/detail/endian_shift.hpp", "max_issues_repo_name": "tonlabs/crypto3-block", "max_issues_repo_head_hexsha": "d7eede022f6130797d28bc39eb312bff9afebf07", "max_issues_repo_licenses": ["MIT"], "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/detail/endian_shift.hpp", "max_forks_repo_name": "tonlabs/crypto3-block", "max_forks_repo_head_hexsha": "d7eede022f6130797d28bc39eb312bff9afebf07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-06-04T07:42:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T21:05:07.000Z", "avg_line_length": 46.0833333333, "max_line_length": 118, "alphanum_fraction": 0.5708257987, "num_tokens": 1351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175139669998, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2958879811793677}}
{"text": "/*\n * Copyright 2014-2017 Jouni Roivas\n */\n\n#include \"blieng/point.h\"\n#include \"blieng.h\"\n\n#include <boost/format.hpp>\n#include <math.h>\n\n#include <string>\n\nusing blieng::Point;\n\nPoint::~Point()\n{\n    x = 0;\n    y = 0;\n}\n\nstd::string Point::toString() const\n{\n    return (boost::format(\"%f,%f\") % x % y).str();\n}\n\nbool Point::operator==(const Point &other) const\n{\n    return (x == other.x && y == other.y);\n}\n\nbool Point::operator!=(const Point &other) const\n{\n    return (x != other.x || y != other.y);\n}\n\nPoint Point::operator+(const Point &other)\n{\n    Point res(x + other.x, y + other.y);\n    return res;\n}\n\nPoint Point::operator-(const Point &other)\n{\n    Point res(x - other.x, y - other.y);\n    return res;\n}\n\nPoint &Point::operator+=(const Point &other)\n{\n    x += other.x;\n    y += other.y;\n    return *this;\n}\n\nPoint &Point::operator-=(const Point &other)\n{\n    x -= other.x;\n    y -= other.y;\n    return *this;\n}\n\nvoid Point::update(Point another)\n{\n    x = another.x;\n    y = another.y;\n}\n\nPoint Point::semiPoint(Point target, double pos) const\n{\n    if (pos < 0) return *this;\n    if (pos >= 1.0) return target;\n\n    double nposx = target.x - x;\n    double nposy = target.y - y;\n\n    nposx *= pos;\n    nposy *= pos;\n\n    nposx += x;\n    nposy += y;\n\n    return Point(nposx, nposy);\n}\n\nPoint Point::traverse(Point target, double now, double time) const\n{\n    // Travel to another point, in specific time, specify now as current time\n    if (now <= 0) return *this;\n    if (now > time) return target;\n\n    double nposx, nposy;\n    nposx = target.x - x;\n    nposy = target.y - y;\n    nposx = (nposx * now / time) + x;\n    nposy = (nposy * now / time) + y;\n\n    return Point(nposx, nposy);\n}\n\ndouble Point::length(Point another)\n{\n    double dx = x - another.x;\n    double dy = y - another.y;\n    if (dx < 0) dx *= -1;\n    if (dy < 0) dy *= -1;\n\n    // return sqrt(dx*dx + dy*dy);\n    return dx+dy;\n}\n\ndouble Point::lengthGeo(Point another)\n{\n    double dlat = (x - another.x) * blieng::PI / 180.0;\n    double dlon = (y - another.y) * blieng::PI / 180.0;\n\n    double a = sin(dlat / 2) * sin(dlat / 2) +\n        cos(another.x * blieng::PI / 180.0) * cos(x * blieng::PI / 180.0) *\n        sin(dlon / 2) * sin(dlon / 2);\n    double c = 2 * atan2(sqrt(a), sqrt(1 - a));\n    double d = blieng::RADIUS * c;\n\n    // Meters\n    return d;\n}\n\nPoint Point::geoToMeters()\n{\n    double latF = 2 * blieng::RADIUS * blieng::PI / 360.0;\n    double lngF = latF * cos(x * blieng::PI / 180.0);\n\n    return Point(x * latF, y * lngF);\n}\n\nblieng::Complex Point::toComplex() const\n{\n    return Complex(x, y);\n}\n", "meta": {"hexsha": "39d5b822acbd4f9f9d9d49e78e4d336b1fe29300", "size": 2598, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "blieng/point.cpp", "max_stars_repo_name": "jroivas/blieng", "max_stars_repo_head_hexsha": "e1d67bab927f91d820232578b10768212da36821", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "blieng/point.cpp", "max_issues_repo_name": "jroivas/blieng", "max_issues_repo_head_hexsha": "e1d67bab927f91d820232578b10768212da36821", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "blieng/point.cpp", "max_forks_repo_name": "jroivas/blieng", "max_forks_repo_head_hexsha": "e1d67bab927f91d820232578b10768212da36821", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8260869565, "max_line_length": 77, "alphanum_fraction": 0.5739030023, "num_tokens": 844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2958867964364101}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-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_BLOCK_BASIC_SHACAL_HPP\n#define CRYPTO3_BLOCK_BASIC_SHACAL_HPP\n\n#include <boost/crypto3/block/detail/shacal/shacal_policy.hpp>\n#include <boost/crypto3/block/detail/shacal/shacal1_policy.hpp>\n\n#include <boost/static_assert.hpp>\n\n#ifdef CRYPTO3_BLOCK_SHOW_PROGRESS\n#include <cstdio>\n#endif\n\nnamespace boost {\n    namespace crypto3 {\n        namespace block {\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             * The algorithms for SHA(-0) and SHA-1 are identical apart from the\n             * key scheduling, so encapsulate that as a class that takes an\n             * already-prepared schedule.  (Constructor is protected to help keep\n             * people from accidentally giving it just a key in a schedule.)\n             */\n            class basic_shacal {\n            protected:\n                typedef detail::shacal_policy policy_type;\n\n            public:\n                constexpr static const std::size_t word_bits = policy_type::word_bits;\n                typedef 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 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 policy_type::block_type block_type;\n\n                constexpr static const std::size_t rounds = policy_type::rounds;\n                typedef policy_type::schedule_type schedule_type;\n\n            protected:\n                basic_shacal(const schedule_type &s) : schedule(s) {\n                }\n\n                virtual ~basic_shacal() {\n                    schedule.fill(0);\n                }\n\n            public:\n                inline block_type encrypt(const block_type &plaintext) const {\n                    return encrypt_block(schedule, plaintext);\n                }\n\n                inline block_type decrypt(const block_type &ciphertext) const {\n                    return decrypt_block(schedule, ciphertext);\n                }\n\n            private:\n                schedule_type schedule;\n\n                inline static block_type encrypt_block(const schedule_type &schedule, const block_type &plaintext) {\n\n#ifdef CRYPTO3_BLOCK_SHOW_PROGRESS\n                    for (unsigned t = 0; t < block_words; ++t) {\n                        std::printf(word_bits == 32 ? \"H[%d] = %.8x\\n\" : \"H[%d] = %.16lx\\n\", t, plaintext[t]);\n                    }\n#endif\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\n                    // Encipher block\n#ifdef CRYPTO3_BLOCK_NO_OPTIMIZATION\n\n                    for (unsigned t = 0; t < rounds; ++t) {\n                        word_type T = policy_type::rotl<5>(a) + policy_type::f(t, b, c, d) + e +\n                                      policy_type::constants[t] + round_constants_words[t];\n\n                        e = d;\n                        d = c;\n                        c = policy_type::rotl<30>(b);\n                        b = a;\n                        a = T;\n\n#ifdef CRYPTO3_BLOCK_SHOW_PROGRESS\n                        printf(word_bits == 32 ? \"t = %2d: %.8x %.8x %.8x %.8x %.8x\\n\" :\n                                                 \"t = %2d: %.16lx %.16lx %.16lx %.16lx %.16lx\\n\",\n                               t, a, b, c, d, e);\n#endif\n                    }\n\n#else    // CRYPTO3_BLOCK_NO_OPTIMIZATION\n\n#ifdef CRYPTO3_BLOCK_SHOW_PROGRESS\n#define CRYPTO3_BLOCK_SHACAL1_TRANSFORM_PROGRESS                                                                      \\\n    printf(word_bits == 32 ? \"t = %2d: %.8x %.8x %.8x %.8x %.8x\\n\" : \"t = %2d: %.16lx %.16lx %.16lx %.16lx %.16lx\\n\", \\\n           t, a, b, c, d, e);\n#else\n#define CRYPTO3_BLOCK_SHACAL1_TRANSFORM_PROGRESS\n#endif\n\n#define CRYPTO3_BLOCK_SHACAL1_TRANSFORM                                                                               \\\n    word_type T = policy_type::rotl<5>(a) + policy_type::f(t, b, c, d) + e + policy_type::constants[t] + schedule[t]; \\\n    e = d;                                                                                                            \\\n    d = c;                                                                                                            \\\n    c = policy_type::rotl<30>(b);                                                                                     \\\n    b = a;                                                                                                            \\\n    a = T;                                                                                                            \\\n    CRYPTO3_BLOCK_SHACAL1_TRANSFORM_PROGRESS\n\n                    BOOST_STATIC_ASSERT(rounds == 80);\n                    BOOST_STATIC_ASSERT(rounds % block_words == 0);\n                    for (unsigned t = 0; t < 20;) {\n                        for (int n = block_words; n--; ++t) {\n                            CRYPTO3_BLOCK_SHACAL1_TRANSFORM\n                        }\n                    }\n                    for (unsigned t = 20; t < 40;) {\n                        for (int n = block_words; n--; ++t) {\n                            CRYPTO3_BLOCK_SHACAL1_TRANSFORM\n                        }\n                    }\n                    for (unsigned t = 40; t < 60;) {\n                        for (int n = block_words; n--; ++t) {\n                            CRYPTO3_BLOCK_SHACAL1_TRANSFORM\n                        }\n                    }\n                    for (unsigned t = 60; t < 80;) {\n                        for (int n = block_words; n--; ++t) {\n                            CRYPTO3_BLOCK_SHACAL1_TRANSFORM\n                        }\n                    }\n\n#endif\n\n                    return {{a, b, c, d, e}};\n                }\n\n                inline static block_type decrypt_block(const schedule_type &schedule, const block_type &ciphertext) {\n\n#ifdef CRYPTO3_BLOCK_SHOW_PROGRESS\n                    for (unsigned t = 0; t < block_words; ++t) {\n                        std::printf(word_bits == 32 ? \"H[%d] = %.8x\\n\" : \"H[%d] = %.16lx\\n\", t, ciphertext[t]);\n                    }\n#endif\n\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];\n\n                    // Decipher block\n                    for (unsigned t = rounds; t--;) {\n                        word_type T = a;\n\n                        a = b;\n                        b = policy_type::rotr<30>(c);\n                        c = d;\n                        d = e;\n                        e = T - policy_type::rotl<5>(a) - policy_type::f(t, b, c, d) - policy_type::constants[t] -\n                            schedule[t];\n\n#ifdef CRYPTO3_BLOCK_SHOW_PROGRESS\n                        std::printf(word_bits == 32 ? \"t = %2d: %.8x %.8x %.8x %.8x %.8x\\n\" :\n                                                      \"t = %2d: %.16lx %.16lx %.16lx %.16lx %.16lx\\n\",\n                                    t, a, b, c, d, e);\n#endif\n                    }\n\n                    return {{a, b, c, d, e}};\n                }\n            };\n        }    // namespace block\n    }        // namespace crypto3\n}    // namespace boost\n\n#endif    // CRYPTO3_BLOCK_CIPHERS_BASIC_SHACAL_HPP\n", "meta": {"hexsha": "ee5a4e69aab91644bbdedb35ddb2aedbd9913fd4", "size": 8376, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/crypto3/block/basic_shacal.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/block/basic_shacal.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/block/basic_shacal.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": 42.303030303, "max_line_length": 119, "alphanum_fraction": 0.4400668577, "num_tokens": 1728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2956025556559639}}
{"text": "/* Copyright (c) 2020 C. Pattison\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 * 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 * 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 OWNER 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\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#pragma once\n#include <cassert>\n#include <algorithm>\n#include <utility>\n#include <complex>\n#include <random>\n#include <exception>\n#include <cmath>\n\n#include <Eigen/Dense>\n#include \"syk_types.hpp\"\n#include \"pauli.hpp\"\n#include \"util.hpp\"\n\n/** Generation for SYK Hamiltonians\n */\n\nnamespace syk {\nusing namespace std::complex_literals;\n\n/** Utility class for construction Majorana fermion representations\n */\nstruct FermionRep : PauliRep {\nprotected:\n    int num_fermions_;\n\npublic:\n\n    FermionRep(int num_fermions) : PauliRep(num_fermions/2), num_fermions_(num_fermions) {\n        if(!(num_fermions > 0 && num_fermions % 2 == 0)) { throw std::runtime_error(\"Number of fermions must be positive and even\"); }\n    }\n\n    Pauli get_pauli_factor(int a, int qubit_index) {\n        assert(0 <= a && a < num_fermions_);\n        assert(0 <= qubit_index && qubit_index < num_qubits_);\n        if (a/2 == qubit_index) { return (a%2 == 1) ? PauliY() : PauliX(); }\n        if (a/2 < qubit_index)  { return PauliI(); }\n        if (a/2 > qubit_index)  { return PauliZ(); }\n        \n        assert(false);\n        return PauliI();\n    }\n\n    /** Four body interaction terms\n     */\n    PauliString four_fermion(int a, int b, int c, int d) {\n        PauliString pstring;\n        for(int qubit_index = 0; qubit_index < num_qubits_; ++qubit_index) {\n            pstring[qubit_index] =\n                  get_pauli_factor(a, qubit_index)\n                * get_pauli_factor(b, qubit_index)\n                * get_pauli_factor(c, qubit_index)\n                * get_pauli_factor(d, qubit_index);\n        }\n        return pstring;\n    }\n\n    /** Returns the parity operator (gamma_*) for the Clifford algebra repp\n     */\n    PauliString gamma_star() const {\n        PauliString pstring;\n        pstring.fill(PauliZ());\n        return pstring;\n    }\n};\n\n/** Return all numbers of even hamming weight below size\n */\nstd::vector<std::uint64_t> hamming_weight(std::uint64_t size, bool odd = false) {\n\n    std::vector<std::uint64_t> idx;\n    idx.reserve(size/2);\n    for (std::uint64_t i = 0; i < size; ++i) {\n        if (static_cast<bool>(__builtin_popcount(i) % 2) == odd) {\n            idx.push_back(i);\n        }\n    }\n\n    return idx;\n}\n\n/** Generate an SYK Hamiltonian\n * Returns only a single parity sector\n */\ntemplate<typename rng_type>\n__attribute__((optimize(\"fast-math\")))\nMatrixType syk_hamiltonian(rng_type* rng, int N, double J) {\n    auto hilbert_space_size = (1 << (N+1)/2);\n    auto repp = FermionRep(N);\n\n    auto distr = std::normal_distribution<double>(0, J/std::pow(static_cast<double>(N), 1.5));\n\n    std::vector<FermionRep::Term> interactions;\n    interactions.reserve(N*N*N);\n    for(int i = 0; i < N; ++i) {\n        for(int j = 0; j < i; ++j) {\n            for(int k = 0; k < j; ++k) {\n                for(int l = 0; l < k; ++l) {\n                    interactions.push_back(FermionRep::Term { repp.four_fermion(i, j, k, l), distr(*rng)} );\n                }\n            }\n        }\n    }\n\n    // The parity projection (1 + gamma_*) removes all rows/columns with odd hamming weight\n    auto even_weight = hamming_weight(hilbert_space_size);\n    auto hamiltonian = repp.get_hamiltonian(interactions, even_weight);\n\n    return hamiltonian;\n}\n\n/** Returns a lambda for computing the spectral form factor at some time\n */\nauto spectral_form_factor(const std::vector<double>& eigenvals) {\n    return [=](std::complex<double> beta) -> double {\n        auto z_part = util::transform_reduce(eigenvals.cbegin(), eigenvals.cend(), 0.0i,\n            std::plus<>(), [=](auto a) { return std::exp(a * beta); });\n        return std::real(z_part * std::conj(z_part));\n    };\n}\n\n/** Vector of doubles to Eigen::VectorXd\n */\nauto to_eigen_vector(const std::vector<double>& vals) {\n    Eigen::Matrix<MatrixType::Scalar, Eigen::Dynamic, 1> vec(vals.size());\n    std::copy(vals.begin(), vals.end(), vec.data());\n    return vec;\n}\n}\n", "meta": {"hexsha": "25ac71ef2ccbf9753e0de0a7ae6a2c657b91dac0", "size": 5276, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/syk.hpp", "max_stars_repo_name": "ChrisPattison/SYK", "max_stars_repo_head_hexsha": "f62b1e9519daf804409790d01316749d010c0db2", "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/syk.hpp", "max_issues_repo_name": "ChrisPattison/SYK", "max_issues_repo_head_hexsha": "f62b1e9519daf804409790d01316749d010c0db2", "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/syk.hpp", "max_forks_repo_name": "ChrisPattison/SYK", "max_forks_repo_head_hexsha": "f62b1e9519daf804409790d01316749d010c0db2", "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.2597402597, "max_line_length": 134, "alphanum_fraction": 0.6550416983, "num_tokens": 1349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.2955366064820453}}
{"text": "// Copyright 2015-2020 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\n/// @file\n///\n/// Definitions of geometry_2d.hpp\n\n#include <geometry_2d.hpp>\n#include <io_utils.hpp>\n#include <boost/property_tree/xml_parser.hpp>\n#include <utilities.hpp>\n\nnamespace alma {\n\nEigen::MatrixXd geometry_2d::bounding_box(polygon& p) {\n    Eigen::Matrix2d limits;\n    Eigen::MatrixXd points;\n    std::size_t cols = 0;\n    boost::geometry::for_each_point(p, [&cols](point& i) { cols++; });\n    points.resize(2, cols);\n    cols = 0;\n    boost::geometry::for_each_point(p, [&cols, &points](point& i) {\n        points(0, cols) = boost::geometry::get<0>(i);\n        points(1, cols) = boost::geometry::get<1>(i);\n        cols++;\n    });\n    // Xmin\n    limits(0, 0) = points.row(0).minCoeff();\n    // Xmax\n    limits(1, 0) = points.row(0).maxCoeff();\n    // Ymin\n    limits(0, 1) = points.row(1).minCoeff();\n    // Ymax\n    limits(1, 1) = points.row(1).maxCoeff();\n\n    return limits;\n}\n\nvoid geometry_2d::get_sides(Eigen::MatrixXd& vertices_) {\n    if (vertices_.rows() != 2) {\n        throw alma::input_error(\"Error in provided vertices,\"\n                                \" bad dimension\\n\");\n    }\n    for (auto i = 0; i < vertices_.cols(); i++) {\n        Eigen::Vector2d p1 = vertices_.col(i);\n        for (auto j = i; j < vertices_.cols(); j++) {\n            Eigen::Vector2d p2 = vertices_.col(j);\n            /// If same point pass\n            if ((p1 - p2).norm() < 1.0e-6)\n                continue;\n            segment s({p1(0), p1(1)}, {p2(0), p2(1)});\n            point sc;\n            /// Looking for midpoint\n            boost::geometry::centroid(s, sc);\n            /// To prevent numerical issues about boder\n            /// we slightly displace the point\n            /// away from hull center\n            Eigen::Vector2d ncsc;\n            ncsc << sc.get<0>() - this->center(0),\n                sc.get<1>() - this->center(1);\n\n            if (ncsc.norm() == 0.) {\n                continue;\n            }\n\n            double nc = 1. / ncsc.norm();\n            /// Normalize and multiply by the eps\n            ncsc(0) *= 1.0e-4 * nc;\n            ncsc(1) *= 1.0e-4 * nc;\n            point fp(ncsc(0) + sc.get<0>(), ncsc(1) + sc.get<1>());\n\n            bool valid_segment = boost::geometry::covered_by(fp, this->hull);\n            /// If valid segment\n            if (!valid_segment) {\n                geom2d_border b;\n                b.p1 = p1;\n                b.p2 = p2;\n                b.nd = (p2 - p1);\n                // Build it to point outside\n                Eigen::Vector2d np_t;\n                np_t << b.nd(1), -b.nd(0);\n                if (np_t.dot(ncsc) < 0.) {\n                    np_t *= -1;\n                }\n                b.np = np_t / np_t.norm();\n\n                auto pa = (p1 - 1.0e-6 * b.nd).eval();\n                auto pb = (p2 + 1.0e-6 * b.nd).eval();\n\n                segment sf({pa(0), pa(1)}, {pb(0), pb(1)});\n\n                b.sb = s;\n                b.sbl = sf;\n\n                if (std::find_if(borders.begin(),\n                                 borders.end(),\n                                 [&b](const geom2d_border& a) -> bool {\n                                     if ((a.np - b.np).norm() < 1.0e-6)\n                                         return true;\n                                     return false;\n                                 }) == borders.end()) {\n                    borders.push_back(b);\n                }\n\n                if (borders.size() >\n                    static_cast<std::size_t>(vertices_.cols())) {\n                    throw alma::geometry_error(\"To much borders\");\n                }\n            }\n        }\n    }\n}\n\n\ngeometry_2d::geometry_2d(Eigen::MatrixXd& vertices_) {\n    //     if (vertices_.cols()!=3) {\n    //         std::cerr << \"Error in vertices, we are only accepting\n    //         triangles\\n\"; exit(EXIT_FAILURE);\n    //     }\n\n\n    polygon poly;\n\n    for (auto i = 0; i < vertices_.cols(); i++) {\n        double x = vertices_(0, i);\n        double y = vertices_(1, i);\n        boost::geometry::append(poly, boost::make_tuple(x, y));\n    }\n    /// Creating convex hull\n    boost::geometry::convex_hull(poly, this->hull);\n    /// Calculating centroid\n    point c;\n    boost::geometry::centroid(this->hull, c);\n    this->center << c.get<0>(), c.get<1>();\n    /// Calculating area\n    this->area = boost::geometry::area(this->hull);\n    /// Geting borders\n    get_sides(vertices_);\n    /// Getting bounding_box\n    this->bbox = bounding_box(this->hull);\n}\n\nbool geometry_2d::inside(Eigen::Vector2d& point2check) const {\n    point p(point2check(0), point2check(1));\n    return boost::geometry::covered_by(p, this->hull);\n}\n\nstd::tuple<double, Eigen::Vector2d, std::vector<int>>\ngeometry_2d::get_inter_side(Eigen::Vector2d& r0,\n                            Eigen::Vector2d& v,\n                            double dt) {\n    point p0(r0(0), r0(1));\n    point pf(r0(0) + dt * v(0), r0(1) + dt * v(1));\n    segment s(p0, pf);\n\n    double time = 1.0e+7;\n    Eigen::Vector2d rf;\n    int border_id = 0;\n    std::vector<int> bids;\n    bool already_there = true;\n\n    for (auto& b : borders) {\n        /// To rule out already there stuff\n        if (boost::geometry::intersects(s, b.sbl) and\n            !boost::geometry::covered_by(p0, b.sbl)) {\n            if (b.np.dot(v) > 0.) {\n                std::vector<point> rinter;\n                boost::geometry::intersection(s, b.sbl, rinter);\n\n                double newtime =\n                    std::max({(std::abs(v(0)) < 1.0e-6)\n                                  ? -1\n                                  : (rinter[0].get<0>() - r0(0)) / v(0),\n                              (std::abs(v(1)) < 1.0e-6)\n                                  ? -1\n                                  : (rinter[0].get<1>() - r0(1)) / v(1)});\n\n                /// Corner case\n                if (newtime == time) {\n                    bids.push_back(border_id);\n                }\n\n\n                if (newtime < time) {\n                    bids.clear();\n                    rf(0) = rinter[0].get<0>();\n                    rf(1) = rinter[0].get<1>();\n                    time = newtime;\n                    already_there = false;\n                    bids.push_back(border_id);\n                }\n            }\n        }\n\n        border_id++;\n    }\n\n    /// In the case already there and going outside\n    /// of box\n    if (already_there) {\n        point p0p(r0(0) - 1.0e-6 * v(0), r0(1) - 1.0e-6 * v(1));\n        segment sp(p0p, pf);\n\n        border_id = 0;\n\n        for (auto& b : borders) {\n            /// To rule out already there stuff\n            if (boost::geometry::intersects(sp, b.sbl)) {\n                if (b.np.dot(v) > 0.) {\n                    std::vector<point> rinter;\n                    boost::geometry::intersection(sp, b.sbl, rinter);\n\n                    double newtime =\n                        std::max({(std::abs(v(0)) < 1.0e-6)\n                                      ? -1.0e+8\n                                      : (rinter[0].get<0>() - r0(0)) / v(0),\n                                  (std::abs(v(1)) < 1.0e-6)\n                                      ? -1.0e+8\n                                      : (rinter[0].get<1>() - r0(1)) / v(1)});\n\n                    /// Corner case\n                    if (newtime == time) {\n                        bids.push_back(border_id);\n                    }\n\n\n                    if (std::abs(newtime) < time) {\n                        bids.clear();\n                        rf(0) = rinter[0].get<0>();\n                        rf(1) = rinter[0].get<1>();\n                        time = newtime;\n                        bids.push_back(border_id);\n                    }\n                }\n            }\n\n            border_id++;\n        }\n\n        if (time > 1.0e+6) {\n            //             std::cout << \"Error in get_inter_side\\n\";\n            //             std::cout << time << '\\t' << dt << std::endl;\n            //             std::cout << \"v\\n\" << v << std::endl;\n            //             std::cout << \"r0\\n\" << r0 << std::endl;\n            //             for (auto &b : borders) {\n            //                 std::cout << \"nb\\n\"<< b.np << std::endl;\n            //                 std::cout << std::boolalpha <<\n            //                 boost::geometry::intersects(sp, b.sbl) << '\\t'\n            //                 << boost::geometry::intersects(s, b.sbl) << '\\t'\n            //                 << boost::geometry::covered_by(pf,b.sb) << '\\t'\n            //                 << boost::geometry::covered_by(p0,b.sb) <<\n            //                 std::endl;\n            //             }\n            //             std::cout << \"box_id: \" << this->get_id() <<\n            //             std::endl;\n            // \t    Eigen::Vector2d rf_ = r0+dt*v;\n            //             std::cout << std::boolalpha <<\n            //                 this->inside(r0) << '\\t'  << std::endl;\n            //             std::cout << \"rf:\\n\" << rf_ << std::endl <<\n            //             std::boolalpha <<\n            //                 this->inside(rf_) << '\\t' << std::endl;\n            throw alma::geometry_error(\"Error to huge time\");\n        }\n    }\n\n    /// This is to clean out some numerical noise\n    /// from geometric library\n    if (alma::almost_equal(time, 0.))\n        time = 0.;\n\n    if (time < 0.) {\n        std::cout << \"Error in get_inter_side\\n\";\n        std::cout << time << std::endl;\n        std::cout << \"v\\n\" << v << std::endl;\n        std::cout << \"r0\\n\" << r0 << std::endl;\n        std::cout << \"rf\\n\" << rf << std::endl;\n        throw alma::geometry_error(\"Bad time\");\n    }\n\n    return std::make_tuple(time, rf, bids);\n}\n\nvoid geometry_2d::calculate_contacts(std::vector<geometry_2d>& system) {\n    /// First get real contacts\n    for (auto& element : system) {\n        if (element.id == this->id)\n            continue;\n        if (boost::geometry::intersects(this->hull, element.hull)) {\n            std::vector<point> pinter;\n            /// This gives the 2 points of the segment\n            boost::geometry::intersection(this->hull, element.hull, pinter);\n\n            /// Border object\n            geom2d_border cb;\n\n            /// If point contact\n            if (pinter.size() == 1) {\n                cb.p1(0) = pinter[0].get<0>();\n                cb.p1(1) = pinter[0].get<1>();\n                cb.p2(0) = pinter[0].get<0>();\n                cb.p2(1) = pinter[0].get<1>();\n\n                cb.nd = Eigen::Vector2d::Zero();\n                cb.sb = segment(pinter[0], pinter[0]);\n                cb.np = cb.p1 - this->get_center();\n                cb.np /= cb.np.norm();\n\n                contacts.emplace(\n                    std::make_pair(element.id, std::vector<geom2d_border>{cb}));\n                continue;\n            }\n\n            cb.p1(0) = pinter[0].get<0>();\n            cb.p1(1) = pinter[0].get<1>();\n            cb.p2(0) = pinter[1].get<0>();\n            cb.p2(1) = pinter[1].get<1>();\n\n            if ((cb.p2 - cb.p1).norm() < 1.0e-6) {\n                cb.p1(0) = pinter[0].get<0>();\n                cb.p1(1) = pinter[0].get<1>();\n                cb.p2(0) = pinter[1].get<0>();\n                cb.p2(1) = pinter[1].get<1>();\n\n                cb.nd = Eigen::Vector2d::Zero();\n                cb.sb = segment(pinter[0], pinter[1]);\n                cb.np = cb.p1 - this->get_center();\n                cb.np /= cb.np.norm();\n\n                contacts.emplace(\n                    std::make_pair(element.id, std::vector<geom2d_border>{}));\n                continue;\n            }\n\n            /// Get director vector of segment\n            cb.nd = (cb.p2 - cb.p1); //\n                                     //(cb.p2 - cb.p1).norm();\n            /// Get perpendicular vector pointing outside\n            segment s(pinter[0], pinter[1]);\n            point sc;\n            /// Looking for midpoint\n            boost::geometry::centroid(s, sc);\n            /// To prevent numerical issues about boder\n            /// we slightly displace the point\n            /// away from hull center\n            Eigen::Vector2d ncsc;\n            ncsc << sc.get<0>() - this->center(0),\n                sc.get<1>() - this->center(1);\n            Eigen::Vector2d np_t;\n            np_t << cb.nd(1), -cb.nd(0);\n            if (np_t.dot(ncsc) < 0.) {\n                np_t *= -1;\n            }\n            cb.np = np_t / np_t.norm();\n            cb.sb = s;\n\n            auto pa = (cb.p1 - 1.0e-6 * cb.nd / cb.nd.norm()).eval();\n            auto pb = (cb.p2 + 1.0e-6 * cb.nd / cb.nd.norm()).eval();\n            segment sf({pa(0), pa(1)}, {pb(0), pb(1)});\n            cb.sbl = sf;\n\n            contacts.emplace(\n                std::make_pair(element.id, std::vector<geom2d_border>{cb}));\n        }\n    }\n\n    if (contacts.size() == 0 and system.size() > 1) {\n        throw alma::geometry_error(\"There are unconnected boxes\");\n    }\n}\n\n\n/// Helper function definitions\n///@param[in] r point to check if tri-or-higher\n///         intersection\n///@param[in] gs vector containing the geometry\nstd::pair<bool, std::vector<std::size_t>> in_corner3(\n    Eigen::Vector2d& r,\n    std::vector<geometry_2d>& gs) {\n    std::size_t ic = 0;\n    std::vector<std::size_t> ids;\n    ids.reserve(gs.size());\n    boost::tuple<double, double> p(r(0), r(1));\n    for (auto& g : gs) {\n        if (boost::geometry::covered_by(p, g.get_poly())) {\n            ids.push_back(g.get_id());\n            ic++;\n        }\n    }\n\n    if (ic > 2) {\n        return std::make_pair(true, ids);\n    }\n    return std::make_pair(false, ids);\n}\n\nstd::vector<alma::geometry_2d> read_geometry_XML(std::string xmlfname) {\n    // Vector containing geometry\n    std::vector<alma::geometry_2d> geometries;\n\n\n    // Create empty property tree object\n    boost::property_tree::ptree tree;\n\n    // Parse XML input file into the tree\n    boost::property_tree::read_xml(xmlfname, tree);\n\n\n    for (const auto& v : tree.get_child(\"Geometry\")) {\n        if (v.first == \"number_of_boxes\") {\n            std::size_t ngeometries =\n                alma::parseXMLfield<std::size_t>(v, \"Ngeom\");\n            geometries.reserve(ngeometries);\n        }\n        /// Iterate throught boxes\n        if (v.first == \"Box\") {\n            auto box_tree = v.second;\n            std::string matname;\n            Eigen::MatrixXd vertices;\n            double Teq = -1.;\n            bool periodic = false;\n            std::size_t box2translate;\n            Eigen::Vector2d translation;\n            bool reservoir = false;\n            double theta = 0.;\n            double Treal = -1.;\n\n            for (auto it = box_tree.begin(); it != box_tree.end(); it++) {\n                /// Parsing name\n                if (it->first == \"MaterialID\")\n                    matname = alma::parseXMLfield<std::string>(*it, \"name\");\n                // Parsing vertices:\n                if (it->first == \"Vertices\") {\n                    int rows, cols;\n                    rows = alma::parseXMLfield<int>(*it, \"dim\");\n                    cols = alma::parseXMLfield<int>(*it, \"npoints\");\n                    vertices.resize(rows, cols);\n\n                    std::stringstream datass(\n                        (box_tree).get<std::string>(\"Vertices\"));\n\n                    for (auto i = 0; i < rows * cols; i++) {\n                        datass >> vertices.data()[i];\n                    }\n                }\n                /// Equilibrium temperature\n                if (it->first == \"initCnd\") {\n                    Teq = alma::parseXMLfield<double>(*it, \"Teq\");\n                    if (alma::probeXMLfield<double>(*it, \"Tinit\")) {\n                        Treal = alma::parseXMLfield<double>(*it, \"Tinit\");\n                    }\n                    else {\n                        Treal = Teq;\n                    }\n                }\n                /// Parsing periodic:\n                if (it->first == \"Translate_to\") {\n                    box2translate = alma::parseXMLfield<std::size_t>(*it, \"id\");\n\n                    periodic = true;\n\n                    std::stringstream datass(\n                        (box_tree).get<std::string>(\"Translate_to\"));\n\n                    datass >> translation(0) >> translation(1);\n                }\n                /// Reservoir\n                if (it->first == \"Reservoir\")\n                    reservoir = true;\n                /// Parsing angle:\n                if (it->first == \"theta\")\n                    theta = alma::parseXMLfield<double>(*it, \"angle\");\n            }\n\n            /// Set properties\n            alma::geometry_2d g(vertices);\n            if (periodic) {\n                g.periodic = true;\n                g.translation = translation;\n                g.box2translate = box2translate;\n            }\n            if (reservoir)\n                g.reservoir = true;\n\n            g.Teq = Teq;\n            g.Treal = Treal;\n            g.material = matname;\n            g.theta = theta;\n            g.rotmat.setZero();\n            /// Obtain rotation matrix\n            if (theta == 0.) {\n                g.rotmat = Eigen::Matrix2d::Identity();\n            }\n            else {\n                g.rotmat(0, 0) = std::cos(theta);\n                g.rotmat(1, 1) = std::cos(theta);\n                g.rotmat(0, 1) = -std::sin(theta);\n                g.rotmat(1, 0) = std::sin(theta);\n            }\n            geometries.push_back(g);\n        }\n    }\n\n    /// Assing ids\n    assign_geom_ids(geometries);\n    /// Calculate contacts\n    for (auto& g : geometries)\n        g.calculate_contacts(geometries);\n\n    return geometries;\n}\n\nEigen::MatrixXd calculate_gradientT(std::vector<alma::geometry_2d>& sys) {\n    Eigen::MatrixXd gradients(3, sys.size());\n    gradients.setZero();\n\n\n    for (auto& s : sys) {\n        if (s.reservoir or s.periodic)\n            continue;\n        /// Get data for gradient\n        /// calculation\n        double T0 = s.Teq;\n        auto id0 = s.get_id();\n        Eigen::Vector2d c0 = s.get_center();\n\n        auto& contacts = s.get_contacts();\n\n        std::size_t csize = 0;\n        for (auto& [c, b] : contacts) {\n            if (!sys[c].reservoir and !sys[c].periodic)\n                csize++;\n        }\n\n\n        /// We want to solve:\n        /// f(r0+hi) - f(r0) = h_i * gradf\n        /// dfi = hi*gradf\n        /// gradf = MPinv(hi)*dfi\n        /// where MPinv is the Moore–Penrose inverse\n        Eigen::VectorXd dfi(csize);\n        Eigen::MatrixXd hi(csize, 2);\n\n        int ci = 0;\n        for (auto& [c, b] : contacts) {\n            if (sys[c].reservoir or sys[c].periodic)\n                continue;\n            dfi(ci) = sys[c].Teq - T0;\n            Eigen::Vector2d hi_ = sys[c].get_center() - c0;\n            hi.row(ci) = hi_;\n            ci++;\n        }\n\n        /// The actual MPinv is not used\n        Eigen::CompleteOrthogonalDecomposition<Eigen::MatrixXd> cqr(hi);\n\n        /// But we solve the minimum-norm solution gradT\n        /// to a least squares problem\n        Eigen::Vector2d gradT = cqr.solve(dfi);\n\n        gradients(0, id0) = gradT(0);\n        gradients(1, id0) = gradT(1);\n    }\n    return gradients;\n}\n\n\n}; // namespace alma\n", "meta": {"hexsha": "0d9e5233e04f1ecced49277f5e73f6e1e6a31396", "size": 19639, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometry_2d.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/geometry_2d.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/geometry_2d.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": 33.8603448276, "max_line_length": 80, "alphanum_fraction": 0.4495646418, "num_tokens": 5022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2955366064820453}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020-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_PUBKEY_BLS_HPP\n#define CRYPTO3_PUBKEY_BLS_HPP\n\n#include <map>\n#include <vector>\n#include <iterator>\n#include <type_traits>\n#include <utility>\n#include <functional>\n\n#include <boost/assert.hpp>\n#include <boost/concept_check.hpp>\n\n#include <boost/range/concepts.hpp>\n\n#include <boost/mpl/vector.hpp>\n\n#include <nil/crypto3/detail/stream_endian.hpp>\n\n#include <nil/crypto3/algebra/curves/bls12.hpp>\n#include <nil/crypto3/algebra/pairing/bls12.hpp>\n\n#include <nil/crypto3/hash/sha2.hpp>\n\n#include <nil/crypto3/pubkey/detail/bls/bls_basic_policy.hpp>\n#include <nil/crypto3/pubkey/detail/bls/bls_basic_functions.hpp>\n#include <nil/crypto3/pubkey/keys/private_key.hpp>\n#include <nil/crypto3/pubkey/operations/aggregate_op.hpp>\n#include <nil/crypto3/pubkey/operations/aggregate_verify_op.hpp>\n#include <nil/crypto3/pubkey/operations/aggregate_verify_single_msg_op.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace pubkey {\n            /*!\n             * @brief Basic BLS Scheme\n             * @tparam SignatureVersion\n             * @tparam BlsParams\n             * @see https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-bls-signature-04#section-3.1\n             */\n            template<typename SignatureVersion>\n            struct bls_basic_scheme {\n                typedef SignatureVersion signature_version;\n                typedef typename signature_version::basic_functions basic_functions;\n\n                typedef typename basic_functions::private_key_type private_key_type;\n                typedef typename basic_functions::public_key_type public_key_type;\n                typedef typename basic_functions::signature_type signature_type;\n\n                typedef typename basic_functions::internal_accumulator_type internal_accumulator_type;\n                typedef typename basic_functions::internal_aggregation_accumulator_type\n                    internal_aggregation_accumulator_type;\n\n                static inline public_key_type generate_public_key(const private_key_type &privkey) {\n                    return basic_functions::privkey_to_pubkey(privkey);\n                }\n\n                static inline void init_accumulator(internal_accumulator_type &acc, const private_key_type &privkey) {\n                }\n\n                static inline void init_accumulator(internal_accumulator_type &acc, const public_key_type &pubkey) {\n                }\n\n                template<typename InputRange>\n                static inline void update(internal_accumulator_type &acc, const InputRange &range) {\n                    basic_functions::update(acc, range);\n                }\n\n                template<typename InputIterator>\n                static inline void update(internal_accumulator_type &acc, InputIterator first, InputIterator last) {\n                    basic_functions::update(acc, first, last);\n                }\n\n                static inline signature_type sign(internal_accumulator_type &acc, const private_key_type &privkey) {\n                    return basic_functions::sign(acc, privkey);\n                }\n\n                static inline bool verify(internal_accumulator_type &acc, const public_key_type &pubkey,\n                                          const signature_type &sig) {\n                    return basic_functions::verify(acc, pubkey, sig);\n                }\n\n                template<typename SignatureRange>\n                static inline void update_aggregate(signature_type &acc, const SignatureRange &signatures) {\n                    basic_functions::aggregate(acc, signatures);\n                }\n\n                template<typename SignatureIterator>\n                static inline void update_aggregate(signature_type &acc, SignatureIterator sig_first,\n                                                    SignatureIterator sig_last) {\n                    basic_functions::aggregate(acc, sig_first, sig_last);\n                }\n\n                static inline bool aggregate_verify(internal_aggregation_accumulator_type &acc,\n                                                    const signature_type &signature) {\n                    // TODO: add check - If any two input messages are equal, return INVALID.\n                    return basic_functions::aggregate_verify(acc, signature);\n                }\n            };\n\n            /*!\n             * @brief\n             * @tparam SignatureVersion\n             * @tparam BlsParams\n             * @see https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-bls-signature-04#section-3.2\n             */\n            template<typename SignatureVersion>\n            struct bls_aug_scheme {\n                typedef SignatureVersion signature_version;\n                typedef typename signature_version::basic_functions basic_functions;\n\n                typedef typename basic_functions::private_key_type private_key_type;\n                typedef typename basic_functions::public_key_type public_key_type;\n                typedef typename basic_functions::signature_type signature_type;\n\n                typedef typename basic_functions::internal_accumulator_type internal_accumulator_type;\n                typedef typename basic_functions::internal_aggregation_accumulator_type\n                    internal_aggregation_accumulator_type;\n\n                static inline public_key_type generate_public_key(const private_key_type &privkey) {\n                    return basic_functions::privkey_to_pubkey(privkey);\n                }\n\n                static inline void init_accumulator(internal_accumulator_type &acc, const private_key_type &privkey) {\n                    init_accumulator(acc, generate_public_key(privkey));\n                }\n\n                static inline void init_accumulator(internal_accumulator_type &acc, const public_key_type &pubkey) {\n                    basic_functions::update(acc, basic_functions::point_to_pubkey(pubkey));\n                }\n\n                template<typename InputRange>\n                static inline void update(internal_accumulator_type &acc, const InputRange &range) {\n                    basic_functions::update(acc, range);\n                }\n\n                template<typename InputIterator>\n                static inline void update(internal_accumulator_type &acc, InputIterator first, InputIterator last) {\n                    basic_functions::update(acc, first, last);\n                }\n\n                static inline signature_type sign(internal_accumulator_type &acc, const private_key_type &privkey) {\n                    return basic_functions::sign(acc, privkey);\n                }\n\n                static inline bool verify(internal_accumulator_type &acc, const public_key_type &pubkey,\n                                          const signature_type &sig) {\n                    return basic_functions::verify(acc, pubkey, sig);\n                }\n\n                template<typename SignatureRange>\n                static inline void update_aggregate(signature_type &acc, const SignatureRange &signatures) {\n                    basic_functions::aggregate(acc, signatures);\n                }\n\n                template<typename SignatureIterator>\n                static inline void update_aggregate(signature_type &acc, SignatureIterator sig_first,\n                                                    SignatureIterator sig_last) {\n                    basic_functions::aggregate(acc, sig_first, sig_last);\n                }\n\n                static inline bool aggregate_verify(internal_aggregation_accumulator_type &acc,\n                                                    const signature_type &signature) {\n                    return basic_functions::aggregate_verify(acc, signature);\n                }\n            };\n\n            /*!\n             * @brief Proof of possession BLS Scheme\n             * @tparam SignatureVersion\n             * @tparam BlsParams\n             * @see https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-bls-signature-04#section-3.3\n             */\n            template<typename SignatureVersion>\n            struct bls_pop_scheme {\n                typedef SignatureVersion signature_version;\n                typedef typename signature_version::basic_functions basic_functions;\n\n                typedef typename basic_functions::private_key_type private_key_type;\n                typedef typename basic_functions::public_key_type public_key_type;\n                typedef typename basic_functions::signature_type signature_type;\n\n                typedef typename basic_functions::internal_accumulator_type internal_accumulator_type;\n                typedef typename basic_functions::internal_aggregation_accumulator_type\n                    internal_aggregation_accumulator_type;\n                typedef typename basic_functions::internal_fast_aggregation_accumulator_type\n                    internal_fast_aggregation_accumulator_type;\n\n                static inline public_key_type generate_public_key(const private_key_type &privkey) {\n                    return basic_functions::privkey_to_pubkey(privkey);\n                }\n\n                static inline void init_accumulator(internal_accumulator_type &acc, const private_key_type &privkey) {\n                }\n\n                static inline void init_accumulator(internal_accumulator_type &acc, const public_key_type &pubkey) {\n                }\n\n                template<typename InputRange>\n                static inline void update(internal_accumulator_type &acc, const InputRange &range) {\n                    basic_functions::update(acc, range);\n                }\n\n                template<typename InputIterator>\n                static inline void update(internal_accumulator_type &acc, InputIterator first, InputIterator last) {\n                    basic_functions::update(acc, first, last);\n                }\n\n                static inline signature_type sign(internal_accumulator_type &acc, const private_key_type &privkey) {\n                    return basic_functions::sign(acc, privkey);\n                }\n\n                static inline bool verify(internal_accumulator_type &acc, const public_key_type &pubkey,\n                                          const signature_type &sig) {\n                    return basic_functions::verify(acc, pubkey, sig);\n                }\n\n                template<typename SignatureRange>\n                static inline void update_aggregate(signature_type &acc, const SignatureRange &signatures) {\n                    basic_functions::aggregate(acc, signatures);\n                }\n\n                template<typename SignatureIterator>\n                static inline void update_aggregate(signature_type &acc, SignatureIterator sig_first,\n                                                    SignatureIterator sig_last) {\n                    basic_functions::aggregate(acc, sig_first, sig_last);\n                }\n\n                static inline bool aggregate_verify(internal_aggregation_accumulator_type &acc,\n                                                    const signature_type &signature) {\n                    return basic_functions::aggregate_verify(acc, signature);\n                }\n\n                static inline bool aggregate_verify(internal_fast_aggregation_accumulator_type &acc,\n                                                    const signature_type &signature) {\n                    return basic_functions::aggregate_verify(acc, signature);\n                }\n\n                static inline signature_type pop_prove(const private_key_type &privkey) {\n                    return basic_functions::pop_prove(privkey);\n                }\n\n                static inline bool pop_verify(const public_key_type &pubkey, const signature_type &proof) {\n                    return basic_functions::pop_verify(pubkey, proof);\n                }\n            };\n\n            //\n            // Minimal-signature-size\n            // Random oracle version of hash-to-point\n            //\n            template<typename PublicParams, typename CurveType = algebra::curves::bls12_381>\n            struct bls_mss_ro_version {\n                typedef detail::bls_mss_ro_policy<PublicParams, CurveType> policy_type;\n                typedef detail::bls_basic_functions<policy_type> basic_functions;\n            };\n\n            //\n            // Minimal-pubkey-size\n            // Random oracle version of hash-to-point\n            //\n            template<typename PublicParams, typename CurveType = algebra::curves::bls12_381>\n            struct bls_mps_ro_version {\n                typedef detail::bls_mps_ro_policy<PublicParams, CurveType> policy_type;\n                typedef detail::bls_basic_functions<policy_type> basic_functions;\n            };\n\n            template<hashes::UniformityCount _uniformity_count = hashes::UniformityCount::uniform_count,\n                     hashes::ExpandMsgVariant _expand_msg_variant = hashes::ExpandMsgVariant::rfc_xmd>\n            struct bls_default_public_params {\n                constexpr static hashes::UniformityCount uniformity_count = _uniformity_count;\n                constexpr static hashes::ExpandMsgVariant expand_msg_variant = _expand_msg_variant;\n\n                // \"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_\"\n                typedef std::array<std::uint8_t, 43> dst_type;\n                static constexpr dst_type dst = {0x42, 0x4c, 0x53, 0x5f, 0x53, 0x49, 0x47, 0x5f, 0x42, 0x4c, 0x53,\n                                                 0x31, 0x32, 0x33, 0x38, 0x31, 0x47, 0x32, 0x5f, 0x58, 0x4d, 0x44,\n                                                 0x3a, 0x53, 0x48, 0x41, 0x2d, 0x32, 0x35, 0x36, 0x5f, 0x53, 0x53,\n                                                 0x57, 0x55, 0x5f, 0x52, 0x4f, 0x5f, 0x4e, 0x55, 0x4c, 0x5f};\n            };\n\n            template<hashes::UniformityCount _uniformity_count = hashes::UniformityCount::uniform_count,\n                     hashes::ExpandMsgVariant _expand_msg_variant = hashes::ExpandMsgVariant::rfc_xmd>\n            struct bls_pop_prove_default_public_params {\n                constexpr static hashes::UniformityCount uniformity_count = _uniformity_count;\n                constexpr static hashes::ExpandMsgVariant expand_msg_variant = _expand_msg_variant;\n\n                typedef std::vector<std::uint8_t> dst_type;\n                static inline dst_type dst = []() {\n                    const std::string _dst_str = \"BLS_POP_BLS12381G1_XMD:SHA-256_SSWU_RO_POP_\";\n                    const std::vector<std::uint8_t> _dst(_dst_str.begin(), _dst_str.end());\n                    return _dst;\n                }();\n            };\n\n            template<hashes::UniformityCount _uniformity_count = hashes::UniformityCount::uniform_count,\n                     hashes::ExpandMsgVariant _expand_msg_variant = hashes::ExpandMsgVariant::rfc_xmd>\n            struct bls_pop_sign_default_public_params {\n                constexpr static hashes::UniformityCount uniformity_count = _uniformity_count;\n                constexpr static hashes::ExpandMsgVariant expand_msg_variant = _expand_msg_variant;\n\n                typedef std::vector<std::uint8_t> dst_type;\n                static inline dst_type dst = []() {\n                    const std::string _dst_str = \"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_\";\n                    const std::vector<std::uint8_t> _dst(_dst_str.begin(), _dst_str.end());\n                    return _dst;\n                }();\n            };\n\n            template<typename PublicParams = bls_default_public_params<>,\n                     template<typename, typename> class BlsVersion = bls_mss_ro_version,\n                     template<typename> class BlsScheme = bls_basic_scheme,\n                     typename CurveType = algebra::curves::bls12_381>\n            struct bls {\n                typedef bls<PublicParams, BlsVersion, BlsScheme, CurveType> self_type;\n                typedef BlsVersion<PublicParams, CurveType> bls_version_type;\n                typedef BlsScheme<bls_version_type> bls_scheme_type;\n\n                typedef public_key<self_type> public_key_type;\n                typedef private_key<self_type> private_key_type;\n                typedef aggregate_op<self_type> aggregate_op_policy;\n                typedef aggregate_verify_op<self_type> aggregate_verify_op_policy;\n            };\n\n            template<typename PublicParams, template<typename, typename> class BlsVersion,\n                     template<typename> class BlsScheme, typename CurveType>\n            struct public_key<bls<PublicParams, BlsVersion, BlsScheme, CurveType>> {\n                typedef bls<PublicParams, BlsVersion, BlsScheme, CurveType> scheme_type;\n                typedef typename scheme_type::bls_scheme_type bls_scheme_type;\n\n                typedef typename bls_scheme_type::private_key_type private_key_type;\n                typedef typename bls_scheme_type::public_key_type public_key_type;\n                typedef typename bls_scheme_type::signature_type signature_type;\n\n                typedef typename public_key_type::group_type public_key_group_type;\n                typedef typename signature_type::group_type signature_group_type;\n\n                typedef typename bls_scheme_type::internal_accumulator_type internal_accumulator_type;\n\n                typedef public_key_type key_type;\n\n                public_key() = delete;\n                public_key(const key_type &pubkey) : pubkey(pubkey) {\n                }\n\n                inline void init_accumulator(internal_accumulator_type &acc) const {\n                    bls_scheme_type::init_accumulator(acc, pubkey);\n                }\n\n                template<typename InputRange>\n                static inline void update(internal_accumulator_type &acc, const InputRange &range) {\n                    bls_scheme_type::update(acc, range);\n                }\n\n                template<typename InputIterator>\n                static inline void update(internal_accumulator_type &acc, InputIterator first, InputIterator last) {\n                    bls_scheme_type::update(acc, first, last);\n                }\n\n                inline bool verify(internal_accumulator_type &acc, const signature_type &sig) const {\n                    return bls_scheme_type::verify(acc, pubkey, sig);\n                }\n\n                inline public_key_type public_key_data() const {\n                    return pubkey;\n                }\n\n                // TODO: refactor pop\n                template<typename FakeAccumulator>\n                inline bool pop_verify(FakeAccumulator, const signature_type &proof) const {\n                    return bls_scheme_type::pop_verify(pubkey, proof);\n                }\n\n                // FIXME: copy pubkey between equivalent public keys is a bottleneck\n                // TODO: support using of the same pubkey even if scheme policy differs in public params and scheme type\n                template<typename ToPublicParams, template<typename> class ToBlsScheme>\n                operator public_key<bls<ToPublicParams, BlsVersion, ToBlsScheme, CurveType>>() const {\n                    return public_key<bls<ToPublicParams, BlsVersion, BlsScheme, CurveType>>(pubkey);\n                }\n\n            protected:\n                public_key_type pubkey;\n            };\n\n            template<typename PublicParams, template<typename, typename> class BlsVersion,\n                     template<typename> class BlsScheme, typename CurveType>\n            struct private_key<bls<PublicParams, BlsVersion, BlsScheme, CurveType>>\n                : public public_key<bls<PublicParams, BlsVersion, BlsScheme, CurveType>> {\n                typedef bls<PublicParams, BlsVersion, BlsScheme, CurveType> scheme_type;\n                typedef typename scheme_type::bls_scheme_type bls_scheme_type;\n                typedef public_key<scheme_type> base_type;\n\n                typedef typename base_type::private_key_type private_key_type;\n                typedef typename base_type::public_key_type public_key_type;\n                typedef typename base_type::signature_type signature_type;\n\n                typedef typename bls_scheme_type::internal_accumulator_type internal_accumulator_type;\n\n                typedef private_key_type key_type;\n\n                private_key() = delete;\n                private_key(const key_type &privkey) :\n                    privkey(privkey), base_type(bls_scheme_type::generate_public_key(privkey)) {\n                }\n\n                inline void init_accumulator(internal_accumulator_type &acc) const {\n                    bls_scheme_type::init_accumulator(acc, privkey);\n                }\n\n                template<typename InputRange>\n                static inline void update(internal_accumulator_type &acc, const InputRange &range) {\n                    bls_scheme_type::update(acc, range);\n                }\n\n                template<typename InputIterator>\n                static inline void update(internal_accumulator_type &acc, InputIterator first, InputIterator last) {\n                    bls_scheme_type::update(acc, first, last);\n                }\n\n                inline signature_type sign(internal_accumulator_type &acc) const {\n                    return bls_scheme_type::sign(acc, privkey);\n                }\n\n                inline signature_type pop_prove() const {\n                    return bls_scheme_type::pop_prove(privkey);\n                }\n\n                // FIXME: copy privkey between equivalent private keys is a bottleneck\n                // TODO: support using of the same privkey even if scheme policy differs in public params and scheme\n                //  type\n                template<typename ToPublicParams, template<typename> class ToBlsScheme>\n                operator private_key<bls<ToPublicParams, BlsVersion, ToBlsScheme, CurveType>>() const {\n                    return private_key<bls<ToPublicParams, BlsVersion, BlsScheme, CurveType>>(privkey);\n                }\n\n            protected:\n                private_key_type privkey;\n            };\n\n            template<typename PublicParams, template<typename, typename> class BlsVersion,\n                     template<typename> class BlsScheme, typename CurveType>\n            struct aggregate_op<bls<PublicParams, BlsVersion, BlsScheme, CurveType>> {\n                typedef bls<PublicParams, BlsVersion, BlsScheme, CurveType> scheme_type;\n                typedef typename scheme_type::bls_scheme_type bls_scheme_type;\n\n                typedef typename bls_scheme_type::private_key_type private_key_type;\n                typedef typename bls_scheme_type::public_key_type public_key_type;\n                typedef typename bls_scheme_type::signature_type signature_type;\n\n                typedef signature_type internal_accumulator_type;\n                typedef signature_type result_type;\n\n                static inline void init_accumulator(internal_accumulator_type &acc) {\n                    acc = signature_type::zero();\n                }\n\n                template<typename InputRange>\n                static inline void update(internal_accumulator_type &acc, const InputRange &range) {\n                    bls_scheme_type::update_aggregate(acc, range);\n                }\n\n                template<typename InputIterator>\n                static inline void update(internal_accumulator_type &acc, InputIterator first, InputIterator last) {\n                    bls_scheme_type::update_aggregate(acc, first, last);\n                }\n\n                static inline result_type process(internal_accumulator_type &acc) {\n                    return acc;\n                }\n            };\n\n            template<typename PublicParams, template<typename, typename> class BlsVersion,\n                     template<typename> class BlsScheme, typename CurveType>\n            struct aggregate_verify_op<bls<PublicParams, BlsVersion, BlsScheme, CurveType>> {\n                typedef bls<PublicParams, BlsVersion, BlsScheme, CurveType> scheme_type;\n                typedef typename scheme_type::bls_scheme_type bls_scheme_type;\n                typedef public_key<scheme_type> scheme_public_key_type;\n\n                typedef typename bls_scheme_type::private_key_type private_key_type;\n                typedef typename bls_scheme_type::public_key_type public_key_type;\n                typedef typename bls_scheme_type::signature_type signature_type;\n\n                typedef typename bls_scheme_type::internal_accumulator_type _internal_accumulator_type;\n                typedef typename bls_scheme_type::internal_aggregation_accumulator_type\n                    _internal_aggregation_accumulator_type;\n                typedef _internal_aggregation_accumulator_type internal_accumulator_type;\n                typedef bool result_type;\n\n                static inline void init_accumulator(internal_accumulator_type &acc) {\n                }\n\n                template<typename InputIterator>\n                static inline void update(internal_accumulator_type &acc, const scheme_public_key_type &scheme_pubkey,\n                                          InputIterator first, InputIterator last) {\n                    auto index = get_public_key_index(acc, scheme_pubkey);\n                    bls_scheme_type::update(acc.second[index], first, last);\n                }\n\n                template<typename InputRange>\n                static inline void update(internal_accumulator_type &acc, const scheme_public_key_type &scheme_pubkey,\n                                          const InputRange &range) {\n                    auto index = get_public_key_index(acc, scheme_pubkey);\n                    bls_scheme_type::update(acc.second[index], range);\n                }\n\n                static inline result_type process(internal_accumulator_type &acc, const signature_type &sig) {\n                    return bls_scheme_type::aggregate_verify(acc, sig);\n                }\n\n            private:\n                static inline std::size_t get_public_key_index(internal_accumulator_type &acc,\n                                                               const scheme_public_key_type &scheme_pubkey) {\n                    assert(std::distance(std::cbegin(acc.first), std::cend(acc.first)) ==\n                           std::distance(std::cbegin(acc.second), std::cend(acc.second)));\n\n                    auto found_pos_it =\n                        std::find(std::cbegin(acc.first), std::cend(acc.first), scheme_pubkey.public_key_data());\n\n                    if (std::cend(acc.first) == found_pos_it) {\n                        acc.first.push_back(scheme_pubkey.public_key_data());\n                        acc.second.push_back(_internal_accumulator_type());\n                        bls_scheme_type::init_accumulator(acc.second.back(), acc.first.back());\n                        return std::size(acc.first) - 1;\n                    }\n\n                    return std::distance(std::cbegin(acc.first), found_pos_it);\n                }\n            };\n\n            template<typename PublicParams, template<typename, typename> class BlsVersion, typename CurveType>\n            struct aggregate_verify_single_msg_op<bls<PublicParams, BlsVersion, bls_pop_scheme, CurveType>> {\n                typedef bls<PublicParams, BlsVersion, bls_pop_scheme, CurveType> scheme_type;\n                typedef typename scheme_type::bls_scheme_type bls_scheme_type;\n                typedef public_key<scheme_type> scheme_public_key_type;\n\n                typedef typename bls_scheme_type::private_key_type private_key_type;\n                typedef typename bls_scheme_type::public_key_type public_key_type;\n                typedef typename bls_scheme_type::signature_type signature_type;\n\n                typedef typename bls_scheme_type::internal_accumulator_type _internal_accumulator_type;\n                typedef typename bls_scheme_type::internal_fast_aggregation_accumulator_type\n                    _internal_fast_aggregation_accumulator_type;\n                typedef _internal_fast_aggregation_accumulator_type internal_accumulator_type;\n                typedef bool result_type;\n\n                static inline void init_accumulator(internal_accumulator_type &acc) {\n                }\n\n                template<typename InputIterator>\n                static inline typename std::enable_if<!std::is_convertible<\n                    typename std::iterator_traits<InputIterator>::value_type, scheme_public_key_type>::value>::type\n                    update(internal_accumulator_type &acc, InputIterator first, InputIterator last) {\n                    bls_scheme_type::update(acc.second, first, last);\n                }\n\n                template<typename InputRange>\n                static inline typename std::enable_if<\n                    !std::is_convertible<typename std::iterator_traits<typename InputRange::iterator>::value_type,\n                                         scheme_public_key_type>::value>::type\n                    update(internal_accumulator_type &acc, const InputRange &range) {\n                    bls_scheme_type::update(acc.second, range);\n                }\n\n                template<typename InputIterator>\n                static inline typename std::enable_if<std::is_convertible<\n                    typename std::iterator_traits<InputIterator>::value_type, scheme_public_key_type>::value>::type\n                    update(internal_accumulator_type &acc, InputIterator first, InputIterator last) {\n                    for (auto iter = first; iter != last; ++iter) {\n                        update(acc, *iter);\n                    }\n                }\n\n                template<typename InputRange>\n                static inline typename std::enable_if<\n                    std::is_convertible<typename std::iterator_traits<typename InputRange::iterator>::value_type,\n                                        scheme_public_key_type>::value>::type\n                    update(internal_accumulator_type &acc, const InputRange &range) {\n                    for (const auto &scheme_pubkey : range) {\n                        update(acc, scheme_pubkey);\n                    }\n                }\n\n                static inline void update(internal_accumulator_type &acc, const scheme_public_key_type &scheme_pubkey) {\n                    auto found_pos_it =\n                        std::find(std::cbegin(acc.first), std::cend(acc.first), scheme_pubkey.public_key_data());\n                    if (std::cend(acc.first) == found_pos_it) {\n                        acc.first.push_back(scheme_pubkey.public_key_data());\n                    }\n                }\n\n                static inline result_type process(internal_accumulator_type &acc, const signature_type &sig) {\n                    return bls_scheme_type::aggregate_verify(acc, sig);\n                }\n            };\n        }    // namespace pubkey\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_PUBKEY_BLS_HPP\n", "meta": {"hexsha": "213dba6fe3c4fba69eade7cbdf1e97f21a2d94f8", "size": 32166, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/pubkey/bls.hpp", "max_stars_repo_name": "NilFoundation/pubkey", "max_stars_repo_head_hexsha": "3b146d6ed14e127be57895a08846c9e1eea4eade", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-23T02:25:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T02:25:55.000Z", "max_issues_repo_path": "include/nil/crypto3/pubkey/bls.hpp", "max_issues_repo_name": "NilFoundation/pubkey", "max_issues_repo_head_hexsha": "3b146d6ed14e127be57895a08846c9e1eea4eade", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2020-10-10T00:23:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-20T21:03:41.000Z", "max_forks_repo_path": "include/nil/crypto3/pubkey/bls.hpp", "max_forks_repo_name": "NilFoundation/pubkey", "max_forks_repo_head_hexsha": "3b146d6ed14e127be57895a08846c9e1eea4eade", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-13T21:40:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T21:39:35.000Z", "avg_line_length": 51.4656, "max_line_length": 120, "alphanum_fraction": 0.6122924827, "num_tokens": 5948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.705785040214066, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.29551001500710844}}
{"text": "#include <algorithm>\n#include <cstdint>\n#include <iostream>\n#include <stdexcept>\n#include <string>\n\n\n#ifndef CPPDEBUG /* Ubuntu's Boost does not provide binaries compatible with libstdc++'s debug mode so we just reduce functionality here */\n#include <boost/program_options.hpp>\n#endif\n\n#include \"libiop/algebra/fields/gf64.hpp\"\n#include \"libiop/algebra/fields/gf128.hpp\"\n#include \"libiop/algebra/fields/gf192.hpp\"\n#include \"libiop/algebra/fields/gf256.hpp\"\n#include \"libiop/algebra/fields/utils.hpp\"\n\n\n#include \"boost_profile.cpp\"\n#include \"libiop/snark/aurora_snark.hpp\"\n#include \"libiop/bcs/bcs_common.hpp\"\n#include \"libiop/protocols/aurora_iop.hpp\"\n#include \"libiop/protocols/ldt/fri/argument_size_optimizer.hpp\"\n#include \"libiop/relations/examples/r1cs_examples.hpp\"\n#include <libff/algebra/curves/edwards/edwards_pp.hpp>\n#include <libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp>\n\n#ifndef CPPDEBUG\nbool process_prover_command_line(const int argc, const char** argv,\n                                 options &options, bool heuristic_fri_soundness, bool optimize_localization)\n{\n    namespace po = boost::program_options;\n\n    try\n    {\n\n        po::options_description desc = gen_options(options);\n        desc.add_options()\n             (\"optimize_localization\", po::value<bool>(&optimize_localization)->default_value(false))\n             (\"heuristic_fri_soundness\", po::value<bool>(&heuristic_fri_soundness)->default_value(true));\n\n        po::variables_map vm;\n        po::store(po::parse_command_line(argc, argv, desc), vm);\n\n        if (vm.count(\"help\"))\n        {\n            std::cout << desc << \"\\n\";\n            return false;\n        }\n\n        po::notify(vm);\n        options.hash_enum = static_cast<libiop::bcs_hash_type>(options.hash_enum_val);\n    }\n    catch(std::exception& e)\n    {\n        std::cerr << \"Error: \" << e.what() << \"\\n\";\n        return false;\n    }\n\n    return true;\n}\n#endif\n\nusing namespace libiop;\n\ntemplate<typename FieldT, typename hash_type>\nvoid print_argument_size(\n    aurora_snark_parameters<FieldT, hash_type> params,\n    const r1cs_constraint_system<FieldT> &constraint_system,\n    aurora_snark_argument<FieldT, hash_type> argument)\n{\n    /* We go through registration on the verifier to know what the domains look like */\n    bcs_verifier<FieldT, hash_type> verifier(params.bcs_params_, argument);\n    aurora_iop<FieldT> full_protocol(verifier, constraint_system, params.iop_params_);\n    full_protocol.register_interactions();\n    verifier.seal_interaction_registrations();\n    full_protocol.register_queries();\n    verifier.seal_query_registrations();\n    const bool holographic = false;\n    print_detailed_transcript_data<FieldT, hash_type>(\n        holographic,\n        argument,\n        params.bcs_params_,\n        verifier);\n}\n\ntemplate<typename FieldT, typename hash_type>\nvoid instrument_aurora_snark(options &options, \n                            LDT_reducer_soundness_type ldt_reducer_soundness_type,\n                            FRI_soundness_type fri_soundness_type, \n                            bool &optimize_localization)\n\n{\n    // TODO: Unhard code this\n    const size_t RS_extra_dimensions = 3 + (options.make_zk ? 0 : 2);\n    const size_t fri_localization_parameter = 2;\n    field_subset_type domain_type = affine_subspace_type;\n    if (options.is_multiplicative) {\n        domain_type = multiplicative_coset_type;\n    }\n\n    for (std::size_t log_n = options.log_n_min; log_n <= options.log_n_max; ++log_n)\n    {\n        print_separator();\n\n        const std::size_t n = 1ul << log_n;\n        /* k+1 needs to be a power of 2 (proof system artifact) so we just fix it to 15 here */\n        const std::size_t k = 15;\n        const std::size_t m = n - 1;\n        r1cs_example<FieldT> example = generate_r1cs_example<FieldT>(n, k, m);\n\n        aurora_snark_parameters<FieldT, hash_type> parameters(\n            options.security_level,\n            ldt_reducer_soundness_type,\n            fri_soundness_type,\n            options.hash_enum,\n            fri_localization_parameter,\n            RS_extra_dimensions,\n            options.make_zk,\n            domain_type,\n            example.constraint_system_.num_constraints(),\n            example.constraint_system_.num_variables());\n\n        std::vector<std::size_t> localization_parameter_array;\n        if (optimize_localization)\n        {\n            const size_t codeword_domain_dim = parameters.iop_params_.codeword_domain_dim();\n            size_t num_query_sets = parameters.iop_params_.FRI_params_.query_repetitions();\n            size_t interactive_repetitions =\n                parameters.iop_params_.FRI_params_.interactive_repetitions() *\n                parameters.iop_params_.LDT_reducer_params_.num_output_LDT_instances();\n            const size_t max_tested_degree_bound =\n                parameters.iop_params_.encoded_aurora_params_.max_tested_degree_bound();\n            const size_t hash_size = (parameters.bcs_params_.security_parameter + 3) / 4;\n            std::vector<size_t> oracle_locality_vector = parameters.iop_params_.locality_vector();\n            // if (parameters.iop_params_.make_zk())\n            // {\n            //     /* Handle the zk leaves for the SNARK. TODO: Where should this go? */\n            //     oracle_locality_vector[0] += 1;\n            // }\n            localization_parameter_array =\n                compute_argument_size_optimal_localization_parameters<FieldT>(\n                    oracle_locality_vector, codeword_domain_dim,\n                    num_query_sets, interactive_repetitions,\n                    max_tested_degree_bound, hash_size);\n\n            parameters.reset_fri_localization_parameters(localization_parameter_array);\n        }\n\n        enter_block(\"Check satisfiability of R1CS example\");\n        const bool is_satisfied = example.constraint_system_.is_satisfied(\n            example.primary_input_, example.auxiliary_input_);\n        assert(is_satisfied);\n        leave_block(\"Check satisfiability of R1CS example\");\n        printf(\"\\n\");\n        print_indent(); printf(\"* R1CS number of constraints: %zu\\n\", example.constraint_system_.num_constraints());\n        print_indent(); printf(\"* R1CS number of variables: %zu\\n\", example.constraint_system_.num_variables());\n        print_indent(); printf(\"* R1CS number of variables for primary input: %zu\\n\", example.primary_input_.size());\n        print_indent(); printf(\"* R1CS number of variables for auxiliary input: %zu\\n\", example.auxiliary_input_.size());\n        print_indent(); printf(\"* R1CS size of constraint system (bytes): %zu\\n\", example.constraint_system_.size_in_bytes());\n        print_indent(); printf(\"* R1CS size of primary input (bytes): %zu\\n\", example.primary_input_.size() * sizeof(FieldT));\n        print_indent(); printf(\"* R1CS size of auxiliary input (bytes): %zu\\n\", example.auxiliary_input_.size() * sizeof(FieldT));\n        printf(\"\\n\");\n        const aurora_snark_argument<FieldT, hash_type> proof = aurora_snark_prover<FieldT, hash_type>(\n            example.constraint_system_,\n            example.primary_input_,\n            example.auxiliary_input_,\n            parameters);\n\n        print_argument_size(parameters, example.constraint_system_, proof);\n\n        const bool bit = aurora_snark_verifier<FieldT, hash_type>(\n            example.constraint_system_,\n            example.primary_input_,\n            proof,\n            parameters);\n\n        printf(\"\\n\\n\");\n\n        print_indent(); printf(\"* Verifier satisfied: %s\\n\", bit ? \"true\" : \"false\");\n    }\n}\n\nint main(int argc, const char * argv[])\n{\n    /* Set up R1CS */\n\n    options default_vals;\n\n    bool optimize_localization = false;\n    bool heuristic_fri_soundness = true;\n\n#ifdef CPPDEBUG\n    /* set reasonable defaults */\n    if (argc > 1)\n    {\n        printf(\"There is no argument parsing in CPPDEBUG mode.\");\n        exit(1);\n    }\n    libiop::UNUSED(argv);\n\n#else\n    if (!process_prover_command_line(argc, argv, default_vals, heuristic_fri_soundness, optimize_localization))\n    {\n        return 1;\n    }\n#endif\n    /** TODO: eventually get a string from program options, and then have a from string methods in protocols */\n    LDT_reducer_soundness_type ldt_reducer_soundness_type = LDT_reducer_soundness_type::proven;\n    if (default_vals.heuristic_ldt_reducer_soundness)\n    {\n        ldt_reducer_soundness_type = LDT_reducer_soundness_type::optimistic_heuristic;\n    }\n    FRI_soundness_type fri_soundness_type = FRI_soundness_type::proven;\n    if (heuristic_fri_soundness) {\n        fri_soundness_type = FRI_soundness_type::heuristic;\n    }\n    start_profiling();\n\n    printf(\"Selected parameters:\\n\");\n    printf(\"- log_n_min = %zu\\n\", default_vals.log_n_min);\n    printf(\"- log_n_max = %zu\\n\", default_vals.log_n_max);\n    printf(\"- security_level = %zu\\n\", default_vals.security_level);\n    printf(\"- LDT_reducer_soundness_type = %s\\n\", LDT_reducer_soundness_type_to_string(ldt_reducer_soundness_type));\n    printf(\"- FRI_soundness_type = %s\\n\", FRI_soundness_type_to_string(fri_soundness_type));\n    printf(\"- is_multiplicative = %s\\n\", default_vals.is_multiplicative ? \"true\" : \"false\");\n    printf(\"- field_size = %zu\\n\", default_vals.field_size);\n    printf(\"- make_zk = %s\\n\", default_vals.make_zk ? \"true\" : \"false\");\n    printf(\"- hash_enum = %s\\n\", bcs_hash_type_names[default_vals.hash_enum]);\n\n    if (default_vals.is_multiplicative) {\n        switch (default_vals.field_size) {\n            case 181:\n                edwards_pp::init_public_params();\n                instrument_aurora_snark<edwards_Fr, binary_hash_digest>(\n                    default_vals, ldt_reducer_soundness_type,\n                    fri_soundness_type, optimize_localization);\n                break;\n            case 256:\n                libff::alt_bn128_pp::init_public_params();\n                \n                if (default_vals.hash_enum == libiop::blake2b_type)\n                {\n                    instrument_aurora_snark<libff::alt_bn128_Fr, binary_hash_digest>(\n                        default_vals, ldt_reducer_soundness_type,\n                        fri_soundness_type, optimize_localization);\n                }\n                else\n                {\n                    instrument_aurora_snark<libff::alt_bn128_Fr, libff::alt_bn128_Fr>(\n                        default_vals, ldt_reducer_soundness_type, \n                        fri_soundness_type, optimize_localization);\n                }\n                break;\n            default:\n                throw std::invalid_argument(\"Field size not supported.\");\n        }\n\n    } else {\n        switch (default_vals.field_size)\n        {\n            case 64:\n                instrument_aurora_snark<gf64, binary_hash_digest>(\n                    default_vals, ldt_reducer_soundness_type, fri_soundness_type, optimize_localization);\n                break;\n            case 128:\n                instrument_aurora_snark<gf128, binary_hash_digest>(\n                    default_vals, ldt_reducer_soundness_type, fri_soundness_type, optimize_localization);\n                break;\n            case 192:\n                instrument_aurora_snark<gf192, binary_hash_digest>(\n                    default_vals, ldt_reducer_soundness_type, fri_soundness_type, optimize_localization);\n                break;\n            case 256:\n                instrument_aurora_snark<gf256, binary_hash_digest>(\n                    default_vals, ldt_reducer_soundness_type, fri_soundness_type, optimize_localization);\n                break;\n            default:\n                throw std::invalid_argument(\"Field size not supported.\");\n        }\n    }\n}\n", "meta": {"hexsha": "09177441d974896ea9ea87a843f31b407d3faef3", "size": 11601, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libiop/profiling/instrument_aurora_snark.cpp", "max_stars_repo_name": "pwang00/libiop", "max_stars_repo_head_hexsha": "640a627f0e844caf88ac66cc2ab16f1ef3ea3283", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libiop/profiling/instrument_aurora_snark.cpp", "max_issues_repo_name": "pwang00/libiop", "max_issues_repo_head_hexsha": "640a627f0e844caf88ac66cc2ab16f1ef3ea3283", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libiop/profiling/instrument_aurora_snark.cpp", "max_forks_repo_name": "pwang00/libiop", "max_forks_repo_head_hexsha": "640a627f0e844caf88ac66cc2ab16f1ef3ea3283", "max_forks_repo_licenses": ["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.9929328622, "max_line_length": 139, "alphanum_fraction": 0.6554607361, "num_tokens": 2592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.29543822851566076}}
{"text": "#include \"astroutils.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <unistd.h>\n#include <math.h>\n#include \"libwcs/wcs.h\"\n#include \"libwcs/fitsfile.h\"\n#include \"libwcs/wcscat.h\"\n#include \"libwcs/lwcs.h\"\n\n#include <iostream>\n#include <vector>\n#include <string>\n\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/classification.hpp>\n#include <boost/algorithm/string.hpp>\nusing namespace boost::algorithm;\n\n\nextern void setsys();\n\nAstroUtils::AstroUtils()\n{\n}\n\nvoid AstroUtils::GetCenterCoords(std::string file, double *coords)\n{\n    WorldCoor *wc = AstroUtils().GetWCSFITS((char*) file.c_str(), 1);\n    AstroUtils().xy2sky(file, wc->nxpix/2.0, wc->nypix/2.0, coords, WCS_GALACTIC);\n    wcsfree(wc);\n}\n\n/// values = [dl, db]\nvoid AstroUtils::GetRectSize(std::string file, double *values)\n{\n    WorldCoor *wc = AstroUtils().GetWCSFITS((char*) file.c_str(), 1);\n    double sky_coords[2], delta[2];\n    AstroUtils().xy2sky(file, 0, 0, sky_coords, WCS_GALACTIC);\n\n    /* dl */\n    AstroUtils().xy2sky(file, wc->nxpix, 0, delta, WCS_GALACTIC);\n    values[0] = abs(delta[0] - sky_coords[0]);\n\n    /* db */\n    AstroUtils().xy2sky(file, 0, wc->nypix, delta, WCS_GALACTIC);\n    values[1] = abs(delta[1] - sky_coords[1]);\n\n    wcsfree(wc);\n}\n\ndouble AstroUtils::GetRadiusSize(std::string file)\n{\n    double rect[2];\n    AstroUtils().GetRectSize(file, rect);\n    double radius = fmax(rect[0], rect[1]) / 2.0;\n    return radius;\n}\n\nvoid AstroUtils::GetBounds(std::string file, double *top, double *bottom, double *right, double *left)\n{\n    double tl[2], br[2];\n    WorldCoor *wc = AstroUtils().GetWCSFITS((char*) file.c_str(), 1);\n    AstroUtils().xy2sky(file, 0, wc->nypix, tl, WCS_GALACTIC);\n    AstroUtils().xy2sky(file, wc->nxpix, 0, br, WCS_GALACTIC);\n    *top = tl[1];\n    *left = tl[0];\n    *bottom = br[1];\n    *right = br[0];\n    wcsfree(wc);\n}\n\nbool AstroUtils::CheckOverlap(std::string f1, std::string f2, bool full)\n{\n    if (full) {\n        // Full overlap\n        return CheckFullOverlap(f1, f2) || CheckFullOverlap(f2, f1);\n    } else {\n        // Check partial overlap\n        double T1, B1, R1, L1;\n        AstroUtils().GetBounds(f1, &T1, &B1, &R1, &L1);\n\n        double T2, B2, R2, L2;\n        AstroUtils().GetBounds(f2, &T2, &B2, &R2, &L2);\n\n        return L1 > R2 && R1 < L2 && T1 > B2 && B1 < T2;\n    }\n}\n\nbool AstroUtils::CheckFullOverlap(std::string f1, std::string f2)\n{\n    double T1, B1, R1, L1;\n    AstroUtils().GetBounds(f1, &T1, &B1, &R1, &L1);\n\n    double T2, B2, R2, L2;\n    AstroUtils().GetBounds(f2, &T2, &B2, &R2, &L2);\n\n    // returns true if f2 is completely inside f1\n    return R2 > R1 && L2 < L1 && T2 < T1 && B2 > B1;\n}\n\ndouble AstroUtils::arcsecPixel(std::string file)\n{\n    char *fn = new char[file.length() + 1];\n    strcpy(fn, file.c_str());\n\n    struct WorldCoor *wcs;\n    char *header;\n    double cra, cdec, dra, ddec, secpix;\n    int wp, hp;\n    int sysout = 0;\n    double eqout = 0.0;\n\n    header = GetFITShead(fn, 0);\n    wcs = GetFITSWCS(fn, header, 0, &cra, &cdec, &dra, &ddec, &secpix, &wp, &hp, &sysout, &eqout);\n    wcsfree(wcs);\n\n    return secpix;\n}\n\nvoid AstroUtils::xy2sky(std::string map, float x, float y, double* coord, int wcs_type)\n{\n    struct WorldCoor *wcs;\n    char *fn = new char[map.length() + 1];\n    static char coorsys[16];\n    char wcstring[64];\n    char lstr = 64;\n    *coorsys = 0;\n\n    strcpy(fn, map.c_str());\n    wcs = GetWCSFITS(fn, 0);\n    wcs->sysout = wcs_type;\n    // force the set of wcs in degree\n    setwcsdeg(wcs,1);\n\n    if (wcs_type == WCS_GALACTIC)\n    {\n        wcs->eqout = 2000.0;\n    }\n\n    if (pix2wcst(wcs, x, y, wcstring, lstr))\n    {\n        std::string str(wcstring);\n        std::vector<std::string> tokens;\n        trim(str);\n        split(tokens, str, is_any_of(\" \"), boost::token_compress_on);\n        coord[0] = atof(tokens[0].c_str());\n        coord[1] = atof(tokens[1].c_str());\n    }\n\n    delete [] fn;\n    wcsfree(wcs);\n}\n\nint AstroUtils::getSysOut(std::string file)\n{\n    char *fn = new char[file.length() + 1];\n    strcpy(fn, file.c_str());\n\n    struct WorldCoor *wcs;\n    char *header;\n    double cra, cdec, dra, ddec, secpix;\n    int wp, hp;\n    int sysout = 0;\n    double eqout = 0.0;\n\n    header = GetFITShead(fn, 0);\n    wcs = GetFITSWCS(fn, header, 1, &cra, &cdec, &dra, &ddec, &secpix, &wp, &hp, &sysout, &eqout);\n    wcsfree(wcs);\n\n    delete [] fn;\n\n    return sysout;\n}\n\nvoid AstroUtils::getRotationAngle(std::string file)\n{\n    char *fn = new char[file.length() + 1];\n    strcpy(fn, file.c_str());\n\n    struct WorldCoor *wcs;\n    char *header;\n    double cra, cdec, dra, ddec, secpix;\n    int wp, hp;\n    int sysout = 0;\n    double eqout = 0.0;\n\n    header = GetFITShead(fn, 0);\n    wcs = GetFITSWCS(fn, header, 1, &cra, &cdec, &dra, &ddec, &secpix, &wp, &hp, &sysout, &eqout);\n    wcsoutinit(wcs, (char*) \"GALACTIC\");\n\n    int off;\n    double xc, xn, xe, yc, yn, ye;\n\n    /* If image is one-dimensional, leave rotation angle alone */\n    if (wcs->nxpix < 1.5 || wcs->nypix < 1.5) {\n        wcs->imrot = wcs->rot;\n        wcs->pa_north = wcs->rot + 90.0;\n        wcs->pa_east = wcs->rot + 180.0;\n        return;\n    }\n\n    /* Do not try anything if image is LINEAR (not Cartesian projection) */\n    if (wcs->syswcs == WCS_LINEAR)\n        return;\n\n    wcs->xinc = fabs (wcs->xinc);\n    wcs->yinc = fabs (wcs->yinc);\n\n    /* Compute position angles of North and East in image */\n    xc = wcs->xrefpix;\n    yc = wcs->yrefpix;\n    pix2wcs (wcs, xc, yc, &cra, &cdec);\n    if (wcs->coorflip) {\n        wcs2pix (wcs, cra+wcs->yinc, cdec, &xe, &ye, &off);\n        wcs2pix (wcs, cra, cdec+wcs->xinc, &xn, &yn, &off);\n    }\n    else {\n        wcs2pix (wcs, cra+wcs->xinc, cdec, &xe, &ye, &off);\n        wcs2pix (wcs, cra, cdec+wcs->yinc, &xn, &yn, &off);\n    }\n    wcs->pa_north = raddeg (atan2 (yn-yc, xn-xc));\n    if (wcs->pa_north < -90.0)\n        wcs->pa_north = wcs->pa_north + 360.0;\n    wcs->pa_east = raddeg (atan2 (ye-yc, xe-xc));\n    if (wcs->pa_east < -90.0)\n        wcs->pa_east = wcs->pa_east + 360.0;\n\n    /* Compute image rotation angle from North */\n    if (wcs->pa_north < -90.0)\n        wcs->imrot = 270.0 + wcs->pa_north;\n    else\n        wcs->imrot = wcs->pa_north - 90.0;\n\n    /* Compute CROTA */\n    if (wcs->coorflip) {\n        wcs->rot = wcs->imrot + 90.0;\n        if (wcs->rot < 0.0)\n            wcs->rot = wcs->rot + 360.0;\n    }\n    else\n        wcs->rot = wcs->imrot;\n    if (wcs->rot < 0.0)\n        wcs->rot = wcs->rot + 360.0;\n    if (wcs->rot >= 360.0)\n        wcs->rot = wcs->rot - 360.0;\n\n    /* Set image mirror flag based on axis orientation */\n    wcs->imflip = 0;\n    if (wcs->pa_east - wcs->pa_north < -80.0 &&\n            wcs->pa_east - wcs->pa_north > -100.0)\n        wcs->imflip = 1;\n    if (wcs->pa_east - wcs->pa_north < 280.0 &&\n            wcs->pa_east - wcs->pa_north > 260.0)\n        wcs->imflip = 1;\n    if (wcs->pa_north - wcs->pa_east > 80.0 &&\n            wcs->pa_north - wcs->pa_east < 100.0)\n        wcs->imflip = 1;\n    if (wcs->coorflip) {\n        if (wcs->imflip)\n            wcs->yinc = -wcs->yinc;\n    }\n    else {\n        if (!wcs->imflip)\n            wcs->xinc = -wcs->xinc;\n    }\n\n    delete [] fn;\n    wcsfree(wcs);\n}\n\nbool AstroUtils::sky2xy(std::string map, double ra, double dec, double* coord)\n{\n    char *fn = new char[map.length() + 1];\n    strcpy(fn, map.c_str());\n\n    struct WorldCoor *wcs;\n    char *header;\n    double cra, cdec, dra, ddec, secpix;\n    int wp, hp;\n    int sysout = 0;\n    double eqout = 0.0;\n    double x, y;\n    int sysin;\n    char csys[16];\n    double eqin = 0.0;\n    int offscale;\n\n    header = GetFITShead(fn, 0);\n    wcs = GetFITSWCS(fn, header, 0, &cra, &cdec, &dra, &ddec, &secpix, &wp, &hp, &sysout, &eqout);\n\n    if (wcs->prjcode < 0)\n        strcpy (csys, \"PIXEL\");\n    else if (wcs->prjcode < 2)\n        strcpy (csys, \"LINEAR\");\n    else\n        strcpy (csys, wcs->radecsys);\n\n    sysin = wcscsys (csys);\n    eqin = wcsceq (csys);\n\n    if (wcs->syswcs > 0 && wcs->syswcs != 6 && wcs->syswcs != 10)\n        wcscon (sysin, wcs->syswcs, eqin, eqout, &ra, &dec, wcs->epoch);\n\n    wcsc2pix (wcs, ra, dec, csys, &x, &y, &offscale);\n\n    coord[0] = x;\n    coord[1] = y;\n    coord[2] = secpix;\n\n    delete [] fn;\n    delete [] header;\n    wcsfree(wcs);\n\n    return true;\n}\n\nstatic double secpix0 = PSCALE;\t\t/* Set image scale--override header */\nstatic int usecdelt = 0;\t\t    /* Use CDELT if 1, else CD matrix */\nstatic int hp0 = 0;\t\t\t        /* Initial height of image */\nstatic int wp0 = 0;\t\t\t        /* Initial width of image */\nstatic double ra0 = -99.0;\t\t    /* Initial center RA in degrees */\nstatic double dec0 = -99.0;\t\t    /* Initial center Dec in degrees */\nstatic int comsys = WCS_J2000;\t\t/* Command line center coordinte system */\nstatic int ptype0 = -1;\t\t\t    /* Projection type to fit */\nstatic int  nctype = 28;\t\t    /* Number of possible projections */\nstatic char ctypes[32][4];\t\t    /* 3-letter codes for projections */\nstatic double xref0 = -99999.0;\t\t/* Reference pixel X coordinate */\nstatic double yref0 = -99999.0;\t\t/* Reference pixel Y coordinate */\nstatic double secpix2 = PSCALE;\t\t/* Set image scale 2--override header */\nstatic double *cd0 = NULL;\t\t    /* Set CD matrix--override header */\nstatic double rot0 = 361.0;\t\t    /* Initial image rotation */\nstatic char *dateobs0 = NULL;\t\t/* Initial DATE-OBS value in FITS date format */\n\nWorldCoor* AstroUtils::GetFITSWCS(char *filename, char\t*header, int verbose, double *cra, double *cdec,double\t*dra, double *ddec, double *secpix, int *wp,int\t*hp,int\t*sysout ,double\t*eqout)\n{\n    int naxes;\n    double eq1, x, y;\n    double ra1, dec1, dx, dy;\n    double xmin, xmax, ymin, ymax, ra2, dec2, ra3, dec3, ra4, dec4;\n    double dra0, dra1, dra2, dra3, dra4;\n    struct WorldCoor *wcs;\n    char rstr[64], dstr[64], cstr[16];\n\n    /* Initialize WCS structure from possibly revised FITS header */\n    wcs = ChangeFITSWCS (filename, header, verbose);\n    if (wcs == NULL) {\n        return (NULL);\n    }\n    *hp = (int) wcs->nypix;\n    *wp = (int) wcs->nxpix;\n\n    /* If incomplete WCS in header, drop out */\n    if (nowcs (wcs)) {\n        setwcsfile (filename);\n        /* wcserr(); */\n        if (verbose)\n            fprintf (stderr,\"Insufficient information for initial WCS\\n\");\n        return (NULL);\n    }\n\n    /* If in linear coordinates, do not print as sexigesimal */\n    if (wcs->sysout < 1 || wcs->sysout == 6 || wcs->sysout == 10)\n        wcs->degout = 1;\n\n    /* Set flag to get appropriate equinox for catalog search */\n    if (!*sysout)\n        *sysout = wcs->syswcs;\n    if (*eqout == 0.0)\n        *eqout = wcs->equinox;\n    eq1 = wcs->equinox;\n    if (wcs->coorflip) {\n        ra1 = wcs->crval[1];\n        dec1 = wcs->crval[0];\n    }\n    else {\n        ra1 = wcs->crval[0];\n        dec1 = wcs->crval[1];\n    }\n\n    /* Print reference pixel position and value */\n    if (verbose && (eq1 != *eqout || wcs->syswcs != *sysout)) {\n        if (wcs->degout) {\n            deg2str (rstr, 32, ra1, 6);\n            deg2str (dstr, 32, dec1, 6);\n        }\n        else {\n            ra2str (rstr, 32, ra1, 3);\n            dec2str (dstr, 32, dec1, 2);\n        }\n        wcscstr (cstr, wcs->syswcs, wcs->equinox, wcs->epoch);\n        fprintf (stderr,\"Reference pixel (%.2f,%.2f) %s %s %s\\n\",\n                 wcs->xrefpix, wcs->yrefpix, rstr, dstr, cstr);\n    }\n\n    /* Get coordinates of corners for size for catalog searching */\n    dx = wcs->nxpix;\n    dy = wcs->nypix;\n    xmin = 0.5;\n    ymin = 0.5;\n    xmax = 0.5 + dx;\n    ymax = 0.5 + dy;\n    pix2wcs (wcs, xmin, ymin, &ra1, &dec1);\n    pix2wcs (wcs, xmin, ymax, &ra2, &dec2);\n    pix2wcs (wcs, xmax, ymin, &ra3, &dec3);\n    pix2wcs (wcs, xmax, ymax, &ra4, &dec4);\n\n    /* Convert search corners to output coordinate system and equinox */\n    if (wcs->syswcs > 0 && wcs->syswcs != 6 && wcs->syswcs != 10) {\n        wcscon (wcs->syswcs,*sysout,wcs->equinox,*eqout,&ra1,&dec1,wcs->epoch);\n        wcscon (wcs->syswcs,*sysout,wcs->equinox,*eqout,&ra2,&dec2,wcs->epoch);\n        wcscon (wcs->syswcs,*sysout,wcs->equinox,*eqout,&ra3,&dec3,wcs->epoch);\n        wcscon (wcs->syswcs,*sysout,wcs->equinox,*eqout,&ra4,&dec4,wcs->epoch);\n    }\n\n    /* Find center and convert to output coordinate system and equinox */\n    x = 0.5 + (dx * 0.5);\n    y = 0.5 + (dy * 0.5);\n    pix2wcs (wcs, x, y, cra, cdec);\n    if (wcs->syswcs > 0 && wcs->syswcs != 6 && wcs->syswcs != 10)\n        wcscon (wcs->syswcs,*sysout,wcs->equinox,*eqout,cra,cdec,wcs->epoch);\n\n    /* Find maximum half-width in declination */\n    *ddec = fabs (dec1 - *cdec);\n    if (fabs (dec2 - *cdec) > *ddec)\n        *ddec = fabs (dec2 - *cdec);\n    if (fabs (dec3 - *cdec) > *ddec)\n        *ddec = fabs (dec3 - *cdec);\n    if (fabs (dec4 - *cdec) > *ddec)\n        *ddec = fabs (dec4 - *cdec);\n\n    /* Find maximum half-width in right ascension */\n    dra0 = (dx / dy) * (*ddec / cos (*cdec));\n    dra1 = ra1 - *cra;\n    dra2 = ra2 - *cra;\n    if (*cra < 0 && *cra + dra0 > 0.0) {\n        dra1 = -(dra1 - 360.0);\n        dra2 = -(dra2 - 360.0);\n    }\n    if (dra1 > 180.0)\n        dra1 = dra1 - 360.0;\n    else if (dra1 < -180.0)\n        dra1 = dra1 + 360.0;\n    else if (dra1 < 0.0)\n        dra1 = -dra1;\n    if (dra2 > 180.0)\n        dra2 = dra2 - 360.0;\n    else if (dra2 < -180.0)\n        dra2 = dra2 + 360.0;\n    else if (dra2 < 0.0)\n        dra2 = -dra2;\n    dra3 = *cra - ra3;\n    dra4 = *cra - ra4;\n    if (*cra > 0 && *cra - dra0 < 0.0) {\n        dra3 = dra3 + 360.0;\n        dra4 = dra4 + 360.0;\n    }\n    if (dra3 > 180.0)\n        dra3 = dra3 - 360.0;\n    else if (dra3 < -180.0)\n        dra3 = dra3 + 360.0;\n    else if (dra3 < 0.0)\n        dra3 = -dra3;\n    if (dra4 > 180.0)\n        dra4 = dra4 - 360.0;\n    else if (dra4 < -180.0)\n        dra4 = dra4 + 360.0;\n    else if (dra4 < 0.0)\n        dra4 = -dra4;\n    *dra = dra1;\n    if (dra2 > *dra)\n        *dra = dra2;\n    if (dra3 > *dra)\n        *dra = dra3;\n    if (dra4 > *dra)\n        *dra = dra4;\n\n    /* wcssize (wcs, cra, cdec, dra, ddec); */\n\n    /* Set reference pixel to center of image if it has not been set */\n    if (wcs->xref == -999.0 && wcs->yref == -999.0) {\n        wcs->xref = *cra;\n        wcs->cel.ref[0] = *cra;\n        wcs->crval[0] = *cra;\n        wcs->yref = *cdec;\n        wcs->cel.ref[1] = *cdec;\n        wcs->crval[1] = *cdec;\n        ra1 = *cra;\n        dec1 = *cdec;\n        if (wcs->xrefpix == 0.0 && wcs->yrefpix == 0.0) {\n            wcs->xrefpix = 0.5 + (double) wcs->nxpix * 0.5;\n            wcs->yrefpix = 0.5 + (double) wcs->nypix * 0.5;\n        }\n        wcs->xinc = *dra * 2.0 / (double) wcs->nxpix;\n        wcs->yinc = *ddec * 2.0 / (double) wcs->nypix;\n        /* hchange (header,\"PLTRAH\",\"PLT0RAH\");\n    wcs->plate_fit = 0; */\n    }\n\n    /* Convert center to desired coordinate system */\n    else if (wcs->syswcs != *sysout && wcs->equinox != *eqout) {\n        wcscon (wcs->syswcs, *sysout, wcs->equinox, *eqout, &ra1, &dec1, wcs->epoch);\n        if (wcs->coorflip) {\n            wcs->yref = ra1;\n            wcs->xref = dec1;\n        }\n        else {\n            wcs->xref = ra1;\n            wcs->yref = dec1;\n        }\n    }\n\n    /* Compute plate scale to return if it was not set on the command line */\n    if (secpix0 <= 0.0) {\n        pix2wcs (wcs, wcs->xrefpix-0.5, wcs->yrefpix, &ra1, &dec1);\n        pix2wcs (wcs, wcs->xrefpix+0.5, wcs->yrefpix, &ra2, &dec2);\n        *secpix = 3600.0 * wcsdist (ra1, dec1, ra2, dec2);\n    }\n\n    wcs->crval[0] = wcs->xref;\n    wcs->crval[1] = wcs->yref;\n    if (wcs->coorflip) {\n        wcs->cel.ref[0] = wcs->crval[1];\n        wcs->cel.ref[1] = wcs->crval[0];\n    }\n    else {\n        wcs->cel.ref[0] = wcs->crval[0];\n        wcs->cel.ref[1] = wcs->crval[1];\n    }\n\n    if (wcs->syswcs > 0 && wcs->syswcs != 6 && wcs->syswcs != 10) {\n        wcs->cel.flag = 0;\n        wcs->wcsl.flag = 0;\n    }\n    else {\n        wcs->lin.flag = LINSET;\n        wcs->wcsl.flag = WCSSET;\n    }\n\n    wcs->equinox = *eqout;\n    wcs->syswcs = *sysout;\n    wcs->sysout = *sysout;\n    wcs->eqout = *eqout;\n    wcs->sysin = *sysout;\n    wcs->eqin = *eqout;\n    wcscstr (cstr,*sysout,*eqout,wcs->epoch);\n    strcpy (wcs->radecsys, cstr);\n    strcpy (wcs->radecout, cstr);\n    strcpy (wcs->radecin, cstr);\n    wcsininit (wcs, wcs->radecsys);\n    wcsoutinit (wcs, wcs->radecsys);\n\n    naxes = wcs->naxis;\n    if (naxes < 1 || naxes > 9) {\n        naxes = wcs->naxes;\n        wcs->naxis = naxes;\n    }\n\n    if (usecdelt) {\n        hputnr8 (header, \"CDELT1\", 9, wcs->xinc);\n        if (naxes > 1) {\n            hputnr8 (header, \"CDELT2\", 9, wcs->yinc);\n            hputnr8 (header, \"CROTA2\", 9, wcs->rot);\n        }\n        hdel (header, \"CD1_1\");\n        hdel (header, \"CD1_2\");\n        hdel (header, \"CD2_1\");\n        hdel (header, \"CD2_2\");\n    }\n    else {\n        hputnr8 (header, \"CD1_1\", 9, wcs->cd[0]);\n        if (naxes > 1) {\n            hputnr8 (header, \"CD1_2\", 9, wcs->cd[1]);\n            hputnr8 (header, \"CD2_1\", 9, wcs->cd[2]);\n            hputnr8 (header, \"CD2_2\", 9, wcs->cd[3]);\n        }\n    }\n\n    /* Print reference pixel position and value */\n    if (verbose) {\n        if (wcs->degout) {\n            deg2str (rstr, 32, ra1, 6);\n            deg2str (dstr, 32, dec1, 6);\n        }\n        else {\n            ra2str (rstr, 32, ra1, 3);\n            dec2str (dstr, 32, dec1, 2);\n        }\n        wcscstr (cstr,*sysout,*eqout,wcs->epoch);\n        fprintf (stderr,\"Reference pixel (%.2f,%.2f) %s %s %s\\n\",\n                 wcs->xrefpix, wcs->yrefpix, rstr, dstr, cstr);\n    }\n\n    /* Image size for catalog search */\n    if (verbose) {\n        if (wcs->degout) {\n            deg2str (rstr, 32, *cra, 6);\n            deg2str (dstr, 32, *cdec, 6);\n        }\n        else {\n            ra2str (rstr, 32, *cra, 3);\n            dec2str (dstr, 32, *cdec, 2);\n        }\n        wcscstr (cstr, *sysout, *eqout, wcs->epoch);\n        fprintf (stderr,\"Search at %s %s %s\", rstr, dstr, cstr);\n        if (wcs->degout) {\n            deg2str (rstr, 32, *dra, 6);\n            deg2str (dstr, 32, *ddec, 6);\n        }\n        else {\n            ra2str (rstr, 32, *dra, 3);\n            dec2str (dstr, 32, *ddec, 2);\n        }\n        fprintf (stderr,\" +- %s %s\\n\", rstr, dstr);\n        fprintf (stderr,\"Image width=%d height=%d, %g arcsec/pixel\\n\",\n                 *wp, *hp, *secpix);\n    }\n\n    return (wcs);\n}\n\nWorldCoor* AstroUtils::ChangeFITSWCS(char *filename, char* header, int verbose)\n{\n    int nax, i, hp, wp;\n    double xref, yref, degpix, secpix;\n    struct WorldCoor *wcs;\n    char temp[16];\n    char *cwcs;\n\n    /* Set the world coordinate system from the image header */\n    if (strlen (filename) > 0)\n    {\n        cwcs = strchr (filename, '%');\n        if (cwcs != NULL)\n            cwcs++;\n    }\n\n    if (!strncmp (header, \"END\", 3)) {\n        cwcs = NULL;\n        for (i = 0; i < 2880; i++)\n            header[i] = (char) 32;\n        hputl (header, \"SIMPLE\", 1);\n        hputi4 (header, \"BITPIX\", 0);\n        hputi4 (header, \"NAXIS\", 2);\n        hputi4 (header, \"NAXIS1\", 1);\n        hputi4 (header, \"NAXIS2\", 1);\n    }\n\n    /* Set image dimensions */\n    nax = 0;\n    if (hp0 > 0 || wp0 > 0) {\n        hp = hp0;\n        wp = wp0;\n        if (hp > 0 && wp > 0)\n            nax = 2;\n        else\n            nax = 1;\n        hputi4 (header, \"NAXIS\", nax);\n        hputi4 (header, \"NAXIS1\", wp);\n        hputi4 (header, \"NAXIS2\", hp);\n    }\n    else if (hgeti4 (header,\"NAXIS\",&nax) < 1 || nax < 1) {\n        if (hgeti4 (header, \"WCSAXES\", &nax) < 1)\n            return (NULL);\n        else {\n            if (hgeti4 (header, \"IMAGEW\", &wp) < 1)\n                return (NULL);\n            if (hgeti4 (header, \"IMAGEH\", &wp) < 1)\n                return (NULL);\n        }\n    }\n    else {\n        if (hgeti4 (header,\"NAXIS1\",&wp) < 1)\n            return (NULL);\n        if (hgeti4 (header,\"NAXIS2\",&hp) < 1)\n            return (NULL);\n    }\n\n    /* Set plate center from command line, if it is there */\n    if (ra0 > -99.0 && dec0 > -99.0) {\n        hputnr8 (header, \"CRVAL1\" ,8,ra0);\n        hputnr8 (header, \"CRVAL2\" ,8,dec0);\n        hputra (header, \"RA\", ra0);\n        hputdec (header, \"DEC\", dec0);\n        if (comsys == WCS_B1950) {\n            hputi4 (header, \"EPOCH\", 1950);\n            hputi4 (header, \"EQUINOX\", 1950);\n            hputs (header, \"RADECSYS\", \"FK4\");\n        }\n        else {\n            hputi4 (header, \"EPOCH\", 2000);\n            hputi4 (header, \"EQUINOX\", 2000);\n            if (comsys == WCS_GALACTIC)\n                hputs (header, \"RADECSYS\", \"GALACTIC\");\n            else if (comsys == WCS_ECLIPTIC)\n                hputs (header, \"RADECSYS\", \"ECLIPTIC\");\n            else if (comsys == WCS_ICRS)\n                hputs (header, \"RADECSYS\", \"ICRS\");\n            else\n                hputs (header, \"RADECSYS\", \"FK5\");\n        }\n        if (hgetr8 (header, \"SECPIX\", &secpix)) {\n            degpix = secpix / 3600.0;\n            hputnr8 (header, \"CDELT1\", 8, -degpix);\n            hputnr8 (header, \"CDELT2\", 8, degpix);\n            hdel (header, \"CD1_1\");\n            hdel (header, \"CD1_2\");\n            hdel (header, \"CD2_1\");\n            hdel (header, \"CD2_2\");\n        }\n    }\n    if (ptype0 > -1 && ptype0 < nctype) {\n        strcpy (temp,\"RA---\");\n        strcat (temp, ctypes[ptype0]);\n        hputs (header, \"CTYPE1\", temp);\n        strcpy (temp,\"DEC--\");\n        strcat (temp, ctypes[ptype0]);\n        hputs (header, \"CTYPE2\", temp);\n    }\n\n    /* Set reference pixel from command line, if it is there */\n    if (xref0 > -99999.0 && yref0 > -99999.0) {\n        hputr8 (header, \"CRPIX1\", xref0);\n        hputr8 (header, \"CRPIX2\", yref0);\n    }\n    else if (hgetr8 (header, \"CRPIX1\", &xref) < 1) {\n        xref = 0.5 + (double) wp / 2.0;\n        yref = 0.5 + (double) hp / 2.0;\n        hputnr8 (header, \"CRPIX1\", 3, xref);\n        hputnr8 (header, \"CRPIX2\", 3, yref);\n    }\n\n    /* Set plate scale from command line, if it is there */\n    if (secpix0 != 0.0 || cd0 != NULL) {\n        if (secpix2 != 0.0) {\n            secpix = 0.5 * (secpix0 + secpix2);\n            hputnr8 (header, \"SECPIX1\", 5, secpix0);\n            hputnr8 (header, \"SECPIX2\", 5, secpix2);\n            degpix = -secpix0 / 3600.0;\n            hputnr8 (header, \"CDELT1\", 8, degpix);\n            degpix = secpix2 / 3600.0;\n            hputnr8 (header, \"CDELT2\", 8, degpix);\n            hdel (header, \"CD1_1\");\n            hdel (header, \"CD1_2\");\n            hdel (header, \"CD2_1\");\n            hdel (header, \"CD2_2\");\n        }\n        else if (secpix0 != 0.0) {\n            secpix = secpix0;\n            hputnr8 (header, \"SECPIX\", 5, secpix);\n            degpix = secpix / 3600.0;\n            hputnr8 (header, \"CDELT1\", 8, -degpix);\n            hputnr8 (header, \"CDELT2\", 8, degpix);\n            hdel (header, \"CD1_1\");\n            hdel (header, \"CD1_2\");\n            hdel (header, \"CD2_1\");\n            hdel (header, \"CD2_2\");\n        }\n        else {\n            hputr8 (header, \"CD1_1\", cd0[0]);\n            hputr8 (header, \"CD1_2\", cd0[1]);\n            hputr8 (header, \"CD2_1\", cd0[2]);\n            hputr8 (header, \"CD2_2\", cd0[3]);\n            hdel (header, \"CDELT1\");\n            hdel (header, \"CDELT2\");\n            hdel (header, \"CROTA1\");\n            hdel (header, \"CROTA2\");\n        }\n        if (!ksearch (header,\"CRVAL1\")) {\n            hgetra (header, \"RA\", &ra0);\n            hgetdec (header, \"DEC\", &dec0);\n            hputnr8 (header, \"CRVAL1\", 8, ra0);\n            hputnr8 (header, \"CRVAL2\", 8, dec0);\n        }\n        if (!ksearch (header,\"CRPIX1\")) {\n            xref = (double) wp / 2.0;\n            yref = (double) hp / 2.0;\n            hputnr8 (header, \"CRPIX1\", 3, xref);\n            hputnr8 (header, \"CRPIX2\", 3, yref);\n        }\n        if (!ksearch (header,\"CTYPE1\")) {\n            if (comsys == WCS_GALACTIC) {\n                hputs (header, \"CTYPE1\", \"GLON-TAN\");\n                hputs (header, \"CTYPE2\", \"GLAT-TAN\");\n            }\n            else {\n                hputs (header, \"CTYPE1\", \"RA---TAN\");\n                hputs (header, \"CTYPE2\", \"DEC--TAN\");\n            }\n        }\n    }\n\n    /* Set rotation angle from command line, if it is there */\n    if (rot0 < 361.0) {\n        hputnr8 (header, \"CROTA1\", 5, rot0);\n        hputnr8 (header, \"CROTA2\", 5, rot0);\n    }\n\n    /* Set observation date for epoch, if it is there */\n    if (dateobs0 != NULL)\n        hputs (header, \"DATE-OBS\", dateobs0);\n\n    /* Initialize WCS structure from FITS header */\n    wcs = wcsinitn (header, cwcs);\n\n    /* If incomplete WCS in header, drop out */\n    if (nowcs (wcs)) {\n        setwcsfile (filename);\n        /* wcserr(); */\n        if (verbose)\n            fprintf (stderr,\"Insufficient information for initial WCS\\n\");\n        return (NULL);\n    }\n    return (wcs);\n}\n\nWorldCoor * AstroUtils::GetWCSFITS(char *filename, int verbose)\n{\n    char *header;\t\t    /* FITS header */\n    struct WorldCoor *wcs;\t/* World coordinate system structure */\n    char *cwcs;\t\t\t    /* Multiple wcs string (name or character) */\n\n    /* Read the FITS or IRAF image file header */\n    header = GetFITShead (filename, verbose);\n    if (header == NULL)\n        return (NULL);\n\n    verbose=true;\n\n    /* Set the world coordinate system from the image header */\n    cwcs = strchr (filename, '%');\n    if (cwcs != NULL)\n        cwcs++;\n    wcs = wcsinitn (header, cwcs);\n    if (wcs == NULL) {\n        setwcsfile (filename);\n        if (verbose)\n            wcserr ();\n    }\n    free (header);\n\n    return (wcs);\n}\n\nchar * AstroUtils::GetFITShead(char * filename, int verbose)\n{\n    char *header;\t\t/* FITS header */\n    int lhead;\t\t\t/* Maximum number of bytes in FITS header */\n    char *irafheader;   /* IRAF image header */\n    int nbiraf, nbfits;\n\n    /* Open IRAF image if .imh extension is present */\n    if (isiraf (filename)) {\n        if ((irafheader = irafrhead (filename, &nbiraf)) != NULL) {\n            if ((header = iraf2fits (filename, irafheader, nbiraf, &lhead)) == NULL) {\n                if (verbose)\n                    fprintf (stderr, \"Cannot translate IRAF header %s\\n\",filename);\n                free (irafheader);\n                irafheader = NULL;\n                return (NULL);\n            }\n            free (irafheader);\n            irafheader = NULL;\n        }\n        else {\n            if (verbose)\n                fprintf (stderr, \"Cannot read IRAF header file %s\\n\", filename);\n            return (NULL);\n        }\n    }\n    else if (istiff (filename) || isgif (filename) || isjpeg (filename)) {\n        if ((header = fitsrtail (filename, &lhead, &nbfits)) == NULL) {\n            if (verbose)\n                fprintf (stderr, \"TIFF file %s has no appended header\\n\", filename);\n            return (NULL);\n        }\n    }\n\n    /* Open FITS file if .imh extension is not present */\n    else {\n        if ((header = fitsrhead (filename, &lhead, &nbfits)) == NULL) {\n            if (verbose)\n                /* fprintf (stderr, \"Cannot read FITS file %s\\n\", filename); */\n                fitserr ();\n            return (NULL);\n        }\n    }\n\n    return (header);\n}\n", "meta": {"hexsha": "d939fd53ae64468ea91612419bca463952f765d7", "size": 27091, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/src/astroutils.cpp", "max_stars_repo_name": "scigeliu/ViaLacteaVisualAnalytics", "max_stars_repo_head_hexsha": "2ac79301ceaaab0415ec7105b8267552262c7650", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-15T15:15:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T15:15:50.000Z", "max_issues_repo_path": "Code/src/astroutils.cpp", "max_issues_repo_name": "scigeliu/ViaLacteaVisualAnalytics", "max_issues_repo_head_hexsha": "2ac79301ceaaab0415ec7105b8267552262c7650", "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": "Code/src/astroutils.cpp", "max_forks_repo_name": "scigeliu/ViaLacteaVisualAnalytics", "max_forks_repo_head_hexsha": "2ac79301ceaaab0415ec7105b8267552262c7650", "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.269273743, "max_line_length": 189, "alphanum_fraction": 0.5219076446, "num_tokens": 9306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2954263550278007}}
{"text": "//\n//  Copyright (c) 2000-2002\n//  Joerg Walter, Mathias Koch\n//\n//  Permission to use, copy, modify, distribute and sell this software\n//  and its documentation for any purpose is hereby granted without fee,\n//  provided that the above copyright notice appear in all copies and\n//  that both that copyright notice and this permission notice appear\n//  in supporting documentation.  The authors make no representations\n//  about the suitability of this software for any purpose.\n//  It is provided \"as is\" without express or implied warranty.\n//\n//  The authors gratefully acknowledge the support of\n//  GeNeSys mbH & Co. KG in producing this work.\n//\n\n#ifndef _BOOST_UBLAS_OPERATION_SPARSE_\n#define _BOOST_UBLAS_OPERATION_SPARSE_\n\n#include <boost/numeric/ublas/traits.hpp>\n\n// These scaled additions were borrowed from MTL unashamedly.\n// But Alexei Novakov had a lot of ideas to improve these. Thanks.\n\nnamespace boost { namespace numeric { namespace ublas {\n\n    template<class M, class E1, class E2, class TRI>\n    BOOST_UBLAS_INLINE\n    M &\n    sparse_prod (const matrix_expression<E1> &e1,\n                 const matrix_expression<E2> &e2,\n                 M &m, TRI,\n                 row_major_tag) {\n        typedef M matrix_type;\n        typedef TRI triangular_restriction;\n        typedef const E1 expression1_type;\n        typedef const E2 expression2_type;\n        typedef typename M::size_type size_type;\n        typedef typename M::value_type value_type;\n\n        // ISSUE why is there a dense vector here?\n        vector<value_type> temporary (e2 ().size2 ());\n        temporary.clear ();\n#if BOOST_UBLAS_TYPE_CHECK\n        matrix<value_type, row_major> cm (m.size1 (), m.size2 ());\n        typedef typename type_traits<value_type>::real_type real_type;\n        real_type merrorbound (norm_1 (m) + norm_1 (e1) * norm_1 (e2));\n        indexing_matrix_assign<scalar_assign> (cm, prod (e1, e2), row_major_tag ());\n#endif\n        typename expression1_type::const_iterator1 it1 (e1 ().begin1 ());\n        typename expression1_type::const_iterator1 it1_end (e1 ().end1 ());\n        while (it1 != it1_end) {\n            size_type jb (temporary.size ());\n            size_type je (0);\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n            typename expression1_type::const_iterator2 it2 (it1.begin ());\n            typename expression1_type::const_iterator2 it2_end (it1.end ());\n#else\n            typename expression1_type::const_iterator2 it2 (boost::numeric::ublas::begin (it1, iterator1_tag ()));\n            typename expression1_type::const_iterator2 it2_end (boost::numeric::ublas::end (it1, iterator1_tag ()));\n#endif\n            while (it2 != it2_end) {\n                // temporary.plus_assign (*it2 * row (e2 (), it2.index2 ()));\n                matrix_row<expression2_type> mr (e2 (), it2.index2 ());\n                typename matrix_row<expression2_type>::const_iterator itr (mr.begin ());\n                typename matrix_row<expression2_type>::const_iterator itr_end (mr.end ());\n                while (itr != itr_end) {\n                    size_type j (itr.index ());\n                    temporary (j) += *it2 * *itr;\n                    jb = (std::min) (jb, j);\n                    je = (std::max) (je, j);\n                    ++ itr;\n                }\n                ++ it2;\n            }\n            for (size_type j = jb; j < je + 1; ++ j) {\n                if (temporary (j) != value_type/*zero*/()) {\n                    // FIXME we'll need to extend the container interface!\n                    // m.push_back (it1.index1 (), j, temporary (j));\n                    // FIXME What to do with adaptors?\n                    // m.insert (it1.index1 (), j, temporary (j));\n                    if (triangular_restriction::other (it1.index1 (), j))\n                        m (it1.index1 (), j) = temporary (j);\n                    temporary (j) = value_type/*zero*/();\n                }\n            }\n            ++ it1;\n        }\n#if BOOST_UBLAS_TYPE_CHECK\n        BOOST_UBLAS_CHECK (norm_1 (m - cm) <= 2 * std::numeric_limits<real_type>::epsilon () * merrorbound, internal_logic ());\n#endif\n        return m;\n    }\n\n    template<class M, class E1, class E2, class TRI>\n    BOOST_UBLAS_INLINE\n    M &\n    sparse_prod (const matrix_expression<E1> &e1,\n                 const matrix_expression<E2> &e2,\n                 M &m, TRI,\n                 column_major_tag) {\n        typedef M matrix_type;\n        typedef TRI triangular_restriction;\n        typedef const E1 expression1_type;\n        typedef const E2 expression2_type;\n        typedef typename M::size_type size_type;\n        typedef typename M::value_type value_type;\n\n        // ISSUE why is there a dense vector here?\n        vector<value_type> temporary (e1 ().size1 ());\n        temporary.clear ();\n#if BOOST_UBLAS_TYPE_CHECK\n        matrix<value_type, column_major> cm (m.size1 (), m.size2 ());\n        typedef typename type_traits<value_type>::real_type real_type;\n        real_type merrorbound (norm_1 (m) + norm_1 (e1) * norm_1 (e2));\n        indexing_matrix_assign<scalar_assign> (cm, prod (e1, e2), column_major_tag ());\n#endif\n        typename expression2_type::const_iterator2 it2 (e2 ().begin2 ());\n        typename expression2_type::const_iterator2 it2_end (e2 ().end2 ());\n        while (it2 != it2_end) {\n            size_type ib (temporary.size ());\n            size_type ie (0);\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n            typename expression2_type::const_iterator1 it1 (it2.begin ());\n            typename expression2_type::const_iterator1 it1_end (it2.end ());\n#else\n            typename expression2_type::const_iterator1 it1 (boost::numeric::ublas::begin (it2, iterator2_tag ()));\n            typename expression2_type::const_iterator1 it1_end (boost::numeric::ublas::end (it2, iterator2_tag ()));\n#endif\n            while (it1 != it1_end) {\n                // column (m, it2.index2 ()).plus_assign (*it1 * column (e1 (), it1.index1 ()));\n                matrix_column<expression1_type> mc (e1 (), it1.index1 ());\n                typename matrix_column<expression1_type>::const_iterator itc (mc.begin ());\n                typename matrix_column<expression1_type>::const_iterator itc_end (mc.end ());\n                while (itc != itc_end) {\n                    size_type i (itc.index ());\n                    temporary (i) += *it1 * *itc;\n                    ib = (std::min) (ib, i);\n                    ie = (std::max) (ie, i);\n                    ++ itc;\n                }\n                ++ it1;\n            }\n            for (size_type i = ib; i < ie + 1; ++ i) {\n                if (temporary (i) != value_type/*zero*/()) {\n                    // FIXME we'll need to extend the container interface!\n                    // m.push_back (i, it2.index2 (), temporary (i));\n                    // FIXME What to do with adaptors?\n                    // m.insert (i, it2.index2 (), temporary (i));\n                    if (triangular_restriction::other (i, it2.index2 ()))\n                        m (i, it2.index2 ()) = temporary (i);\n                    temporary (i) = value_type/*zero*/();\n                }\n            }\n            ++ it2;\n        }\n#if BOOST_UBLAS_TYPE_CHECK\n        BOOST_UBLAS_CHECK (norm_1 (m - cm) <= 2 * std::numeric_limits<real_type>::epsilon () * merrorbound, internal_logic ());\n#endif\n        return m;\n    }\n\n    // Dispatcher\n    template<class M, class E1, class E2, class TRI>\n    BOOST_UBLAS_INLINE\n    M &\n    sparse_prod (const matrix_expression<E1> &e1,\n                 const matrix_expression<E2> &e2,\n                 M &m, TRI, bool init = true) {\n        typedef typename M::value_type value_type;\n        typedef TRI triangular_restriction;\n        typedef typename M::orientation_category orientation_category;\n\n        if (init)\n            m.assign (zero_matrix<value_type> (e1 ().size1 (), e2 ().size2 ()));\n        return sparse_prod (e1, e2, m, triangular_restriction (), orientation_category ());\n    }\n    template<class M, class E1, class E2, class TRI>\n    BOOST_UBLAS_INLINE\n    M\n    sparse_prod (const matrix_expression<E1> &e1,\n                 const matrix_expression<E2> &e2,\n                 TRI) {\n        typedef M matrix_type;\n        typedef TRI triangular_restriction;\n\n        matrix_type m (e1 ().size1 (), e2 ().size2 ());\n        // FIXME needed for c_matrix?!\n        // return sparse_prod (e1, e2, m, triangular_restriction (), false);\n        return sparse_prod (e1, e2, m, triangular_restriction (), true);\n    }\n    template<class M, class E1, class E2>\n    BOOST_UBLAS_INLINE\n    M &\n    sparse_prod (const matrix_expression<E1> &e1,\n                 const matrix_expression<E2> &e2,\n                 M &m, bool init = true) {\n        typedef typename M::value_type value_type;\n        typedef typename M::orientation_category orientation_category;\n\n        if (init)\n            m.assign (zero_matrix<value_type> (e1 ().size1 (), e2 ().size2 ()));\n        return sparse_prod (e1, e2, m, full (), orientation_category ());\n    }\n    template<class M, class E1, class E2>\n    BOOST_UBLAS_INLINE\n    M\n    sparse_prod (const matrix_expression<E1> &e1,\n                 const matrix_expression<E2> &e2) {\n        typedef M matrix_type;\n\n        matrix_type m (e1 ().size1 (), e2 ().size2 ());\n        // FIXME needed for c_matrix?!\n        // return sparse_prod (e1, e2, m, full (), false);\n        return sparse_prod (e1, e2, m, full (), true);\n    }\n\n}}}\n\n#endif\n", "meta": {"hexsha": "8210a21f8c0289fb692fd8e8576b96245b4b5f35", "size": 9453, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "applications/physbam/physbam-lib/External_Libraries/Archives/boost/boost/numeric/ublas/operation_sparse.hpp", "max_stars_repo_name": "schinmayee/nimbus", "max_stars_repo_head_hexsha": "170cd15e24a7a88243a6ea80aabadc0fc0e6e177", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2017-07-03T19:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T02:53:56.000Z", "max_issues_repo_path": "applications/physbam/physbam-lib/External_Libraries/Archives/boost/boost/numeric/ublas/operation_sparse.hpp", "max_issues_repo_name": "schinmayee/nimbus", "max_issues_repo_head_hexsha": "170cd15e24a7a88243a6ea80aabadc0fc0e6e177", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/physbam/physbam-lib/External_Libraries/Archives/boost/boost/numeric/ublas/operation_sparse.hpp", "max_forks_repo_name": "schinmayee/nimbus", "max_forks_repo_head_hexsha": "170cd15e24a7a88243a6ea80aabadc0fc0e6e177", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-09-17T02:05:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-31T00:12:01.000Z", "avg_line_length": 42.7737556561, "max_line_length": 127, "alphanum_fraction": 0.5832011002, "num_tokens": 2292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.4921881357207955, "lm_q1q2_score": 0.2954055825859017}}
{"text": "// Copyright 2016 Robert Maier, Technical University Munich\n#include \"dvo.hpp\"\n\n#include <iostream>\n#include <sstream>\n#include <string>\n\n#include <Eigen/Cholesky>\n#include <sophus/se3.hpp>\n\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/highgui/highgui.hpp>\n\n\nDVO::DVO() :\n    numPyramidLevels_(2),\n    useWeights_(true),\n    numIterations_(500),\n    algo_(LevenbergMarquardt)\n    //algo_(GaussNewton)\n{\n}\n\n\nDVO::~DVO()\n{\n    for (int i = 0; i < numPyramidLevels_; ++i)\n    {\n        delete[] J_[i];\n        delete[] residuals_[i];\n        delete[] weights_[i];\n    }\n}\n\n\nvoid DVO::init(int w, int h, const Eigen::Matrix3f &K)\n{\n    // pyramid level size\n    int wDown = w;\n    int hDown = h;\n    int n = wDown*hDown;\n    sizePyramid_.push_back(cv::Size(wDown, hDown));\n\n    // gradients\n    cv::Mat gradX = cv::Mat::zeros(h, w, CV_32FC1);\n    gradX_.push_back(gradX);\n    cv::Mat gradY = cv::Mat::zeros(h, w, CV_32FC1);\n    gradY_.push_back(gradY);\n\n    // Jacobian\n    float* J = new float[n*6];\n    J_.push_back(J);\n    // residuals\n    float* residuals = new float[n];\n    residuals_.push_back(residuals);\n    // per-residual weights\n    float* weights = new float[n];\n    weights_.push_back(weights);\n\n    // camera matrix\n    kPyramid_.push_back(K);\n\n    for (int i = 1; i < numPyramidLevels_; ++i)\n    {\n        // pyramid level size\n        wDown = wDown / 2;\n        hDown = hDown / 2;\n        int n = wDown*hDown;\n        sizePyramid_.push_back(cv::Size(wDown, hDown));\n\n        // gradients\n        cv::Mat gradXdown = cv::Mat::zeros(hDown, wDown, CV_32FC1);\n        gradX_.push_back(gradXdown);\n        cv::Mat gradYdown = cv::Mat::zeros(hDown, wDown, CV_32FC1);\n        gradY_.push_back(gradYdown);\n\n        // Jacobian\n        float* J = new float[n*6];\n        J_.push_back(J);\n        // residuals\n        float* residuals = new float[n];\n        residuals_.push_back(residuals);\n        // per-residual weights\n        float* weights = new float[n];\n        weights_.push_back(weights);\n\n        // downsample camera matrix\n        Eigen::Matrix3f kDown = kPyramid_[i-1];\n        kDown(0, 2) += 0.5f;\n        kDown(1, 2) += 0.5f;\n        kDown.topLeftCorner(2, 3) = kDown.topLeftCorner(2, 3) * 0.5f;\n        kDown(0, 2) -= 0.5f;\n        kDown(1, 2) -= 0.5f;\n        kPyramid_.push_back(kDown);\n        //std::cout << \"Camera matrix (level \" << i << \"): \" << kDown << std::endl;\n    }\n}\n\n\nvoid DVO::convertSE3ToTf(const Vec6f &xi, Eigen::Matrix3f &rot, Eigen::Vector3f &t)\n{\n    // rotation\n    Sophus::SE3f se3 = Sophus::SE3f::exp(xi);\n    Eigen::Matrix4f mat = se3.matrix();\n    rot = mat.topLeftCorner(3, 3);\n    t = mat.topRightCorner(3, 1);\n}\n\n\nvoid DVO::convertSE3ToTf(const Vec6f &xi, Eigen::Matrix4f &pose)\n{\n    Sophus::SE3f se3 = Sophus::SE3f::exp(xi);\n    pose = se3.matrix();\n}\n\n\nvoid DVO::convertTfToSE3(const Eigen::Matrix3f &rot, const Eigen::Vector3f &t, Vec6f &xi)\n{\n    Sophus::SE3f se3(rot, t);\n    xi = Sophus::SE3f::log(se3);\n}\n\n\nvoid DVO::convertTfToSE3(const Eigen::Matrix4f &pose, Vec6f &xi)\n{\n    Eigen::Matrix3f rot = pose.topLeftCorner(3, 3);\n    Eigen::Vector3f t = pose.topRightCorner(3, 1);\n    convertTfToSE3(rot, t, xi);\n}\n\n\ncv::Mat DVO::downsampleGray(const cv::Mat &gray)\n{\n    const float* ptrIn = (const float*)gray.data;\n    int w = gray.cols;\n    int h = gray.rows;\n    int wDown = w/2;\n    int hDown = h/2;\n\n    cv::Mat grayDown = cv::Mat::zeros(hDown, wDown, gray.type());\n    float* ptrOut = (float*)grayDown.data;\n    for (size_t y = 0; y < hDown; ++y)\n    {\n        for (size_t x = 0; x < wDown; ++x)\n        {\n            float sum = 0.0f;\n            sum += ptrIn[2*y * w + 2*x] * 0.25f;\n            sum += ptrIn[2*y * w + 2*x+1] * 0.25f;\n            sum += ptrIn[(2*y+1) * w + 2*x] * 0.25f;\n            sum += ptrIn[(2*y+1) * w + 2*x+1] * 0.25f;\n            ptrOut[y*wDown + x] = sum;\n        }\n    }\n\n    return grayDown;\n}\n\n\ncv::Mat DVO::downsampleDepth(const cv::Mat &depth)\n{\n    const float* ptrIn = (const float*)depth.data;\n    int w = depth.cols;\n    int h = depth.rows;\n    int wDown = w/2;\n    int hDown = h/2;\n\n    // downscaling by averaging the inverse depth\n    cv::Mat depthDown = cv::Mat::zeros(hDown, wDown, depth.type());\n    float* ptrOut = (float*)depthDown.data;\n    for (size_t y = 0; y < hDown; ++y)\n    {\n        for (size_t x = 0; x < wDown; ++x)\n        {\n            float d0 = ptrIn[2*y * w + 2*x];\n            float d1 = ptrIn[2*y * w + 2*x+1];\n            float d2 = ptrIn[(2*y+1) * w + 2*x];\n            float d3 = ptrIn[(2*y+1) * w + 2*x+1];\n\n            int cnt = 0;\n            float sum = 0.0f;\n            if (d0 != 0.0f)\n            {\n                sum += 1.0f / d0;\n                ++cnt;\n            }\n            if (d1 != 0.0f)\n            {\n                sum += 1.0f / d1;\n                ++cnt;\n            }\n            if (d2 != 0.0f)\n            {\n                sum += 1.0f / d2;\n                ++cnt;\n            }\n            if (d3 != 0.0f)\n            {\n                sum += 1.0f / d3;\n                ++cnt;\n            }\n\n            if (cnt > 0)\n            {\n                float dInv = sum / float(cnt);\n                if (dInv != 0.0f)\n                    ptrOut[y*wDown + x] = 1.0f / dInv;\n            }\n        }\n    }\n\n    return depthDown;\n}\n\n\nvoid DVO::computeGradient(const cv::Mat &gray, cv::Mat &gradient, int direction)\n{\n    int dirX = 1;\n    int dirY = 0;\n    if (direction == 1)\n    {\n        dirX = 0;\n        dirY = 1;\n    }\n\n    // compute gradient manually using finite differences\n    int w = gray.cols;\n    int h = gray.rows;\n    const float* ptrIn = (const float*)gray.data;\n    gradient.setTo(0);\n    float* ptrOut = (float*)gradient.data;\n\n    int yStart = dirY;\n    int yEnd = h - dirY;\n    int xStart = dirX;\n    int xEnd = w - dirX;\n    for (size_t y = yStart; y < yEnd; ++y)\n    {\n        for (size_t x = xStart; x < xEnd; ++x)\n        {\n            float v0;\n            float v1;\n            if (direction == 1)\n            {\n                // y-direction\n                v0 = ptrIn[(y-1)*w + x];\n                v1 = ptrIn[(y+1)*w + x];\n            }\n            else\n            {\n                // x-direction\n                v0 = ptrIn[y*w + (x-1)];\n                v1 = ptrIn[y*w + (x+1)];\n            }\n            ptrOut[y*w + x] = 0.5f * (v1 - v0);\n        }\n    }\n}\n\n\nfloat DVO::interpolate(const float* ptrImgIntensity, float x, float y, int w, int h)\n{\n    float valCur = std::numeric_limits<float>::quiet_NaN();\n\n#if 0\n    // direct lookup, no interpolation\n    int x0 = static_cast<int>(x + 0.5f);\n    int y0 = static_cast<int>(y + 0.5f);\n    if (x0 >= 0 && x0 < w && y0 >= 0 && y0 < h)\n        valCur = ptrImgIntensity[y0*w + x0];\n#else\n    //bilinear interpolation\n    int x0 = static_cast<int>(x);\n    int y0 = static_cast<int>(y);\n    int x1 = x0 + 1;\n    int y1 = y0 + 1;\n\n    float x1_weight = x - static_cast<float>(x0);\n    float y1_weight = y - static_cast<float>(y0);\n    float x0_weight = 1.0f - x1_weight;\n    float y0_weight = 1.0f - y1_weight;\n\n    if (x0 < 0 || x0 >= w)\n        x0_weight = 0.0f;\n    if (x1 < 0 || x1 >= w)\n        x1_weight = 0.0f;\n    if (y0 < 0 || y0 >= h)\n        y0_weight = 0.0f;\n    if (y1 < 0 || y1 >= h)\n        y1_weight = 0.0f;\n    float w00 = x0_weight * y0_weight;\n    float w10 = x1_weight * y0_weight;\n    float w01 = x0_weight * y1_weight;\n    float w11 = x1_weight * y1_weight;\n\n    float sumWeights = w00 + w10 + w01 + w11;\n    float sum = 0.0f;\n    if (w00 > 0.0f)\n        sum += ptrImgIntensity[y0*w + x0] * w00;\n    if (w01 > 0.0f)\n        sum += ptrImgIntensity[y1*w + x0] * w01;\n    if (w10 > 0.0f)\n        sum += ptrImgIntensity[y0*w + x1] * w10;\n    if (w11 > 0.0f)\n        sum += ptrImgIntensity[y1*w + x1] * w11;\n\n    if (sumWeights > 0.0f)\n        valCur = sum / sumWeights;\n#endif\n\n    return valCur;\n}\n\n\nfloat DVO::calculateError(const float* residuals, int n)\n{\n    float error = 0.0f;\n    int numValid = 0;\n    for (int i = 0; i < n; ++i)\n    {\n        if (residuals[i] != 0.0f)\n        {\n            error += residuals[i] * residuals[i];\n            ++numValid;\n        }\n    }\n    if (numValid > 0)\n        error = error / static_cast<float>(numValid);\n    return error;\n}\n\n\nvoid DVO::calculateErrorImage(const float* residuals, int w, int h, cv::Mat &errorImage)\n{\n    cv::Mat imgResiduals = cv::Mat::zeros(h, w, CV_32FC1);\n    float* ptrResiduals = (float*)imgResiduals.data;\n\n    // fill residuals image\n    for (size_t y = 0; y < h; ++y)\n    {\n        for (size_t x = 0; x < w; ++x)\n        {\n            size_t off = y*w + x;\n            if (residuals[off] != 0.0f)\n                ptrResiduals[off] = residuals[off];\n        }\n    }\n\n    imgResiduals.convertTo(errorImage, CV_8SC1, 127.0);\n}\n\n\nvoid DVO::calculateError(const cv::Mat &grayRef, const cv::Mat &depthRef,\n                         const cv::Mat &grayCur, const cv::Mat &depthCur,\n                         const Eigen::VectorXf &xi, const Eigen::Matrix3f &K,\n                         float* residuals)\n{\n    // create residual image\n    int w = grayRef.cols;\n    int h = grayRef.rows;\n\n    // camera intrinsics\n    float fx = K(0, 0);\n    float fy = K(1, 1);\n    float cx = K(0, 2);\n    float cy = K(1, 2);\n    float fxInv = 1.0f / fx;\n    float fyInv = 1.0f / fy;\n\n    // convert SE3 to rotation matrix and translation vector\n    Eigen::Matrix3f rotMat;\n    Eigen::Vector3f t;\n    convertSE3ToTf(xi, rotMat, t);\n\n    const float* ptrGrayRef = (const float*)grayRef.data;\n    const float* ptrDepthRef = (const float*)depthRef.data;\n    const float* ptrGrayCur = (const float*)grayCur.data;\n    const float* ptrDepthCur = (const float*)depthCur.data;\n\n    for (size_t y = 0; y < h; ++y)\n    {\n        for (size_t x = 0; x < w; ++x)\n        {\n            size_t off = y*w + x;\n            float residual = 0.0f;\n\n            // project 2d point back into 3d using its depth\n            float dRef = ptrDepthRef[y*w + x];\n            if (dRef > 0.0)\n            {\n                float x0 = (static_cast<float>(x) - cx) * fxInv;\n                float y0 = (static_cast<float>(y) - cy) * fyInv;\n                float scale = 1.0f;\n                //scale = std::sqrt(x0*x0 + y0*y0 + 1.0f);\n                dRef = dRef * scale;\n                x0 = x0 * dRef;\n                y0 = y0 * dRef;\n\n                // transform reference 3d point into current frame\n                // reference 3d point\n                Eigen::Vector3f pt3Ref(x0, y0, dRef);\n                Eigen::Vector3f pt3Cur = rotMat * pt3Ref + t;\n                if (pt3Cur[2] > 0.0f)\n                {\n                    // project 3d point to 2d\n                    Eigen::Vector3f pt2CurH = K * pt3Cur;\n                    float ptZinv = 1.0f / pt2CurH[2];\n                    float px = pt2CurH[0] * ptZinv;\n                    float py = pt2CurH[1] * ptZinv;\n\n                    // interpolate residual\n                    float valCur = interpolate(ptrGrayCur, px, py, w, h);\n                    if (!std::isnan(valCur))\n                    {\n                        float valRef = ptrGrayRef[off];\n                        float valDiff = valRef - valCur;\n                        residual = valDiff;\n                    }\n                }\n            }\n            residuals[off] = residual;\n        }\n    }\n}\n\n\nvoid DVO::calculateMeanStdDev(const float* residuals, float &mean, float &stdDev, int n)\n{\n    float meanVal = 0.0f;\n    for (int i = 0; i < n; ++i)\n        meanVal += residuals[i];\n    mean = meanVal / static_cast<float>(n);\n\n    float variance = 0.0f;\n    for (int i = 0; i < n; ++i)\n        variance += (residuals[i] - mean) * (residuals[i] - mean);\n    stdDev = std::sqrt(variance);\n}\n\n\nvoid DVO::computeWeights(const float* residuals, float* weights, int n)\n{\n#if 0\n    // no weighting\n    for (int i = 0; i < n; ++i)\n        weights[i] = 1.0f;\n#if 0\n    // squared residuals\n    for (int i = 0; i < n; ++i)\n        residuals[i] = residuals[i] * residuals[i];\n    return;\n#endif\n#endif\n\n    // compute mean and standard deviation\n    float mean, stdDev;\n    calculateMeanStdDev(residuals, mean, stdDev, n);\n\n    // compute robust Huber weights\n    \n    float k = 1.345f * stdDev;\n    //float k = 0.15f * stdDev;\n    for (int i = 0; i < n; ++i)\n    {\n        float w;\n        if (std::abs(residuals[i]) <= k)\n            w = 1.0f;\n        else\n            w = k / std::abs(residuals[i]);\n        weights[i] = w;\n    }\n    /*\n    #if 0\n    // compute Tukey weights\n    float k = 4.6851f * stdDev;\n    for (int i = 0; i<n; i++)\n    {\n        float w;\n        if (std::abs(residuals[i]) <= k)\n            w = std::pow((1.0f-residuals[i]*residuals[i] / (k*k)),2);\n        else\n            w = 0.0f;\n        weights[i] = w;\n    }\n    \n    // compute Cauchy weights\n    float k = 1.35f * stdDev;\n    for (int i = 0; i<n; i++)\n    {\n        float w;       \n        w = 1.0f/(1+(residuals[i]*residuals[i] / (k*k)));        \n        weights[i] = w;\n    }\n    */\n    \n}\n\n\nvoid DVO::applyWeights(const float* weights, float* residuals, int n)\n{\n    for (size_t i = 0; i < n; ++i)\n    {\n        // weight residual\n        residuals[i] = residuals[i] * weights[i];\n    }\n}\n\n\nvoid DVO::deriveNumeric(const cv::Mat &grayRef, const cv::Mat &depthRef,\n                                  const cv::Mat &grayCur, const cv::Mat &depthCur,\n                                  const Eigen::VectorXf &xi, const Eigen::Matrix3f &K,\n                                  float* residuals, float* J)\n{\n    float epsilon = 1e-6;\n    float scale = 1.0f / epsilon;\n\n    int w = grayRef.cols;\n    int h = grayRef.rows;\n    int n = w*h;\n\n    // calculate per-pixel residuals\n    calculateError(grayRef, depthRef, grayCur, depthCur, xi, K, residuals);\n\n    // create and fill Jacobian column by column\n    float* residualsInc = new float[n];\n    for (int j = 0; j < 6; ++j)\n    {\n        Eigen::VectorXf unitVec = Eigen::VectorXf::Zero(6);\n        unitVec[j] = epsilon;\n\n        // left-multiplicative increment on SE3\n        Eigen::VectorXf xiEps = Sophus::SE3f::log(Sophus::SE3f::exp(unitVec) * Sophus::SE3f::exp(xi));\n\n        calculateError(grayRef, depthRef, grayCur, depthCur, xiEps, K, residualsInc);\n        for (int i = 0; i < n; ++i)\n            J[i*6 + j] = (residualsInc[i] - residuals[i]) * scale;\n    }\n    delete[] residualsInc;\n}\n\n\nvoid DVO::compute_JtR(const float* J, const float* residuals, Vec6f &b, int validRows)\n{\n    int n = 6;\n    int m = validRows;\n\n    // compute b = Jt*r\n    for (int j = 0; j < n; ++j)\n    {\n        float val = 0.0f;\n        for (int i = 0; i < m; ++i)\n            val += J[i*6 + j] * residuals[i];\n        b[j] = val;\n    }\n}\n\n\nvoid DVO::compute_JtJ(const float* J, Mat6f &A, const float* weights, int validRows, bool useWeights)\n{\n    int n = 6;\n    int m = validRows;\n\n    // compute A = Jt*J\n    for (int k = 0; k < n; ++k)\n    {\n        for (int j = 0; j < n; ++j)\n        {\n            float val = 0.0f;\n            for (int i = 0; i < m; ++i)\n            {\n                float valSqr = J[i*6 + j] * J[i*6 + k];\n                if (useWeights)\n                    valSqr *= weights[i];\n                val += valSqr;\n            }\n            A(k, j) = val;\n        }\n    }\n}\n\n\nvoid DVO::deriveAnalytic(const cv::Mat &grayRef, const cv::Mat &depthRef,\n                   const cv::Mat &grayCur, const cv::Mat &depthCur,\n                   const cv::Mat &gradX, const cv::Mat &gradY,\n                   const Eigen::VectorXf &xi, const Eigen::Matrix3f &K,\n                   float* residuals, float* J)\n{\n    // reference input images\n    int w = grayRef.cols;\n    int h = grayRef.rows;\n    int n = w*h;\n    const float* ptrDepthRef = (const float*)depthRef.data;\n\n    // camera intrinsics\n    float fx = K(0, 0);\n    float fy = K(1, 1);\n    float cx = K(0, 2);\n    float cy = K(1, 2);\n    float fxInv = 1.0f / fx;\n    float fyInv = 1.0f / fy;\n\n    // convert SE3 to rotation matrix and translation vector\n    Eigen::Matrix3f rotMat;\n    Eigen::Vector3f t;\n    convertSE3ToTf(xi, rotMat, t);\n\n    // calculate per-pixel residuals\n    calculateError(grayRef, depthRef, grayCur, depthCur, xi, K, residuals);\n\n    // reference gradient images\n    const float* ptrGradX = (const float*)gradX.data;\n    const float* ptrGradY = (const float*)gradY.data;\n\n    // create and fill Jacobian row by row\n    float residualRowJ[6];\n    for (size_t y = 0; y < h; ++y)\n    {\n        for (size_t x = 0; x < w; ++x)\n        {\n            size_t off = y*w + x;\n\n            // project 2d point back into 3d using its depth\n            float dRef = ptrDepthRef[y*w + x];\n            if (dRef > 0.0f)\n            {\n                float x0 = (static_cast<float>(x) - cx) * fxInv;\n                float y0 = (static_cast<float>(y) - cy) * fyInv;\n                float scale = 1.0f;\n                //scale = std::sqrt(x0*x0 + y0*y0 + 1.0);\n                dRef = dRef * scale;\n                x0 = x0 * dRef;\n                y0 = y0 * dRef;\n\n                // transform reference 3d point into current frame\n                // reference 3d point\n                Eigen::Vector3f pt3Ref(x0, y0, dRef);\n                Eigen::Vector3f pt3 = rotMat * pt3Ref + t;\n                if (pt3[2] > 0.0f)\n                {\n                    // project 3d point to 2d\n                    Eigen::Vector3f pt2CurH = K * pt3;\n                    float ptZinv = 1.0f / pt2CurH[2];\n                    float px = pt2CurH[0] * ptZinv;\n                    float py = pt2CurH[1] * ptZinv;\n\n                    // compute interpolated image gradient\n                    float dX = interpolate(ptrGradX, px, py, w, h);\n                    float dY = interpolate(ptrGradY, px, py, w, h);\n                    if (!std::isnan(dX) && !std::isnan(dY))\n                    {\n                        dX = fx * dX;\n                        dY = fy * dY;\n                        float pt3Zinv = 1.0f / pt3[2];\n\n                        // shorter computation\n                        residualRowJ[0] = dX * pt3Zinv;\n                        residualRowJ[1] = dY * pt3Zinv;\n                        residualRowJ[2] = - (dX * pt3[0] + dY * pt3[1]) * pt3Zinv * pt3Zinv;\n                        residualRowJ[3] = - (dX * pt3[0] * pt3[1]) * pt3Zinv * pt3Zinv - dY * (1 + (pt3[1] * pt3Zinv) * (pt3[1] * pt3Zinv));\n                        residualRowJ[4] = + dX * (1.0 + (pt3[0] * pt3Zinv) * (pt3[0] * pt3Zinv)) + (dY * pt3[0] * pt3[1]) * pt3Zinv * pt3Zinv;\n                        residualRowJ[5] = (- dX * pt3[1] + dY * pt3[0]) * pt3Zinv;\n                    }\n                }\n            }\n\n            // set 1x6 Jacobian row for current residual\n            // invert Jacobian according to kerl2012msc.pdf (necessary?)\n            for (int j = 0; j < 6; ++j)\n                J[off*6 + j] = - residualRowJ[j];\n        }\n    }\n}\n\n\nvoid DVO::buildPyramid(const cv::Mat &depth, const cv::Mat &gray, std::vector<cv::Mat> &depthPyramid, std::vector<cv::Mat> &grayPyramid)\n{\n    grayPyramid.push_back(gray);\n    depthPyramid.push_back(depth);\n\n    for (int i = 1; i < numPyramidLevels_; ++i)\n    {\n        // downsample grayscale image\n        cv::Mat grayDown = downsampleGray(grayPyramid[i-1]);\n        grayPyramid.push_back(grayDown);\n\n        // downsample depth image\n        cv::Mat depthDown = downsampleDepth(depthPyramid[i-1]);\n        depthPyramid.push_back(depthDown);\n    }\n}\n\n\nvoid DVO::align(const cv::Mat &depthRef, const cv::Mat &grayRef, const cv::Mat &depthCur, const cv::Mat &grayCur, Eigen::Matrix4f &pose)\n{\n    // downsampling\n    std::vector<cv::Mat> grayRefPyramid;\n    std::vector<cv::Mat> depthRefPyramid;\n    buildPyramid(depthRef, grayRef, depthRefPyramid, grayRefPyramid);\n\n    std::vector<cv::Mat> grayCurPyramid;\n    std::vector<cv::Mat> depthCurPyramid;\n    buildPyramid(depthCur, grayCur, depthCurPyramid, grayCurPyramid);\n\n    align(depthRefPyramid, grayRefPyramid, depthCurPyramid, grayCurPyramid, pose);\n}\n\n\nvoid DVO::align(const std::vector<cv::Mat> &depthRefPyramid, const std::vector<cv::Mat> &grayRefPyramid,\n                const std::vector<cv::Mat> &depthCurPyramid, const std::vector<cv::Mat> &grayCurPyramid,\n                Eigen::Matrix4f &pose)\n{\n    Vec6f xi;\n    convertTfToSE3(pose, xi);\n\n    Vec6f lastXi = Vec6f::Zero();\n\n    int maxLevel = numPyramidLevels_-1;\n    int minLevel = 1;\n    float initGradDescStepSize = 1e-3f;\n    float gradDescStepSize = initGradDescStepSize;\n\n    Mat6f A;\n    Mat6f diagMatA = Mat6f::Identity();\n    Vec6f delta;\n\n    for (int lvl = maxLevel; lvl >= minLevel; --lvl)\n    {\n        float lambda = 0.1f;\n\n        int w = sizePyramid_[lvl].width;\n        int h = sizePyramid_[lvl].height;\n        int n = w*h;\n\n        cv::Mat grayRef = grayRefPyramid[lvl];\n        cv::Mat depthRef = depthRefPyramid[lvl];\n        cv::Mat grayCur = grayCurPyramid[lvl];\n        cv::Mat depthCur = depthCurPyramid[lvl];\n        Eigen::Matrix3f kLevel = kPyramid_[lvl];\n        //std::cout << \"level \" << level << \" (size \" << depthRef.cols << \"x\" << depthRef.rows << \")\" << std::endl;\n\n        // compute gradient images\n        computeGradient(grayCur, gradX_[lvl], 0);\n        computeGradient(grayCur, gradY_[lvl], 1);\n\n        float errorLast = std::numeric_limits<float>::max();\n        for (int itr = 0; itr < numIterations_; ++itr)\n        {\n            // compute residuals and Jacobian\n#if 0\n            deriveNumeric(grayRef, depthRef, grayCur, depthCur, xi, kLevel, residuals_[lvl], J_[lvl]);\n#else\n            deriveAnalytic(grayRef, depthRef, grayCur, depthCur, gradX_[lvl], gradY_[lvl], xi, kLevel, residuals_[lvl], J_[lvl]);\n#endif\n\n#if 0\n            // compute and show error image\n            cv::Mat errorImage;\n            calculateErrorImage(residuals_[level], grayRef.cols, grayRef.rows, errorImage);\n            std::stringstream ss;\n            ss << dataFolder << \"residuals_\" << level << \"_\";\n            ss << std::setw(2) << std::setfill('0') << itr << \".png\";\n            cv::imwrite(ss.str(), errorImage);\n            cv::imshow(\"error\", errorImage);\n            cv::waitKey(100);\n#endif\n\n            // calculate error\n            float error = calculateError(residuals_[lvl], n);\n\n            if (useWeights_)\n            {\n                // compute robust weights\n                computeWeights(residuals_[lvl], weights_[lvl], n);\n                // apply robust weights\n                applyWeights(weights_[lvl], residuals_[lvl], n);\n            }\n\n            // compute update\n            Vec6f b;\n            compute_JtR(J_[lvl], residuals_[lvl], b, n);\n\n            if (algo_ == GradientDescent)\n            {\n                // Gradient Descent\n                delta = -gradDescStepSize * b * (1.0f / b.norm());\n            }\n            else if (algo_ == GaussNewton)\n            {\n                // Gauss-Newton algorithm\n                compute_JtJ(J_[lvl], A, weights_[lvl], n, useWeights_);\n                // solve using Cholesky LDLT decomposition\n                delta = -(A.ldlt().solve(b));\n            }\n            else if (algo_ == LevenbergMarquardt)\n            {\n                // Levenberg-Marquardt algorithm\n                compute_JtJ(J_[lvl], A, weights_[lvl], n, useWeights_);\n                diagMatA.diagonal() = lambda * A.diagonal();\n                delta = -((A + diagMatA).ldlt().solve(b));\n            }\n\n            // apply update: left-multiplicative increment on SE3\n            lastXi = xi;\n            xi = Sophus::SE3f::log(Sophus::SE3f::exp(delta) * Sophus::SE3f::exp(xi));\n#if 0\n            std::cout << \"delta = \" << delta.transpose() << \" size = \" << delta.rows() << \" x \" << delta.cols() << std::endl;\n            std::cout << \"xi = \" << xi.transpose() << std::endl;\n#endif\n\n            // compute error again\n            error = calculateError(residuals_[lvl], n);\n\n            if (algo_ == LevenbergMarquardt)\n            {\n                if (error >= errorLast)\n                {\n                    lambda = lambda * 5.0f;\n                    xi = lastXi;\n\n                    if (lambda > 5.0f)\n                        break;\n                }\n                else\n                {\n                    lambda = lambda / 1.5f;\n                }\n            }\n            else if (algo_ == GaussNewton)\n            {\n                // break if no improvement (0.99 or 0.995)\n                if (error / errorLast > 0.995f)\n                    break;\n            }\n            else if (algo_ == GradientDescent)\n            {\n                if (error >= errorLast)\n                {\n                    gradDescStepSize = gradDescStepSize * 0.5f;\n                    if (gradDescStepSize <= initGradDescStepSize * 0.01f)\n                        gradDescStepSize = initGradDescStepSize * 0.01f;\n                    xi = lastXi;\n                }\n                else\n                {\n                    gradDescStepSize = gradDescStepSize * 2.0f;\n                    if (gradDescStepSize >= initGradDescStepSize * 100.0f)\n                        gradDescStepSize = initGradDescStepSize * 100.0f;\n\n                    // break if no improvement (0.99 or 0.995)\n                    if (error / errorLast > 0.995f)\n                        break;\n                }\n            }\n\n            errorLast = error;\n        }\n    }\n\n    // store to output pose\n    convertSE3ToTf(xi, pose);\n}\n", "meta": {"hexsha": "78f10d35c1b8859e328d9ff5e33b824186afe622", "size": 25296, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DVO/src/dvo.cpp", "max_stars_repo_name": "Sangluisme/MultiviewLightEnhancedDepthSR", "max_stars_repo_head_hexsha": "cf1bebaed3ccff25de8e7439772f1bb4e03d7fd3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-10-13T11:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T04:41:59.000Z", "max_issues_repo_path": "DVO/src/dvo.cpp", "max_issues_repo_name": "Sangluisme/MultiviewLightEnhancedDepthSR", "max_issues_repo_head_hexsha": "cf1bebaed3ccff25de8e7439772f1bb4e03d7fd3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DVO/src/dvo.cpp", "max_forks_repo_name": "Sangluisme/MultiviewLightEnhancedDepthSR", "max_forks_repo_head_hexsha": "cf1bebaed3ccff25de8e7439772f1bb4e03d7fd3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-10-19T11:57:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-10T01:45:16.000Z", "avg_line_length": 29.3797909408, "max_line_length": 142, "alphanum_fraction": 0.5022928526, "num_tokens": 7644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.29534387851028215}}
{"text": "/* Copyright (c) 2016, the Cap 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 <cap/mp_values.h>\n#include <cap/energy_storage_device.h>\n#include <deal.II/base/types.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <iostream>\n\nnamespace cap\n{\n\n// reads database for finite element model and write database for equivalent\n// circuit model\nvoid compute_equivalent_circuit(\n    boost::property_tree::ptree const &input_database,\n    boost::property_tree::ptree &output_database)\n{\n  // TODO: of course we could clear the database or just overwrite but for\n  // now let's just throw an exception if it is not empty\n  if (!output_database.empty())\n    throw std::runtime_error(\"output_database was not empty...\");\n\n  auto to_meters = [](double const &cm)\n  {\n    return 0.01 * cm;\n  };\n  auto to_square_meters = [](double const &cm2)\n  {\n    return 0.0001 * cm2;\n  };\n\n  double const cross_sectional_area =\n      to_square_meters(input_database.get<double>(\"geometry.geometric_area\"));\n  // clang-format off\n  double const electrode_width = to_meters(input_database.get<double>(\"geometry.anode_electrode_thickness\"));\n  double const separator_width = to_meters(input_database.get<double>(\"geometry.separator_thickness\"      ));\n  double const collector_width = to_meters(input_database.get<double>(\"geometry.anode_collector_thickness\"));\n  // clang-format on\n\n  // getting the material parameters values\n  std::shared_ptr<boost::property_tree::ptree> material_properties_database =\n      std::make_shared<boost::property_tree::ptree>(\n          input_database.get_child(\"material_properties\"));\n  MPValuesParameters<2> mp_values_params(material_properties_database);\n  std::shared_ptr<boost::property_tree::ptree> geometry_database =\n      std::make_shared<boost::property_tree::ptree>(\n          input_database.get_child(\"geometry\"));\n  // build dummy cell iterator and set its material id. Because we use a dummy\n  // triangulation, we can use MPI_COMM_WORLD.\n  std::shared_ptr<dealii::distributed::Triangulation<2>> triangulation(\n      new dealii::distributed::Triangulation<2>(MPI_COMM_WORLD));\n  dealii::GridGenerator::hyper_cube(*triangulation);\n  dealii::FE_Q<2> fe(1);\n  dealii::DoFHandler<2> dof_handler(*triangulation);\n  dof_handler.distribute_dofs(fe);\n  mp_values_params.geometry = std::make_shared<Geometry<2>>(\n      triangulation,\n      std::make_shared<std::unordered_map<\n          std::string, std::set<dealii::types::material_id>>>(\n          std::initializer_list<std::pair<\n              std::string const, std::set<dealii::types::material_id>>>{\n              {\"anode\", std::set<dealii::types::material_id>{1}},\n              {\"separator\", std::set<dealii::types::material_id>{2}},\n              {\"cathode\", std::set<dealii::types::material_id>{3}},\n              {\"collector\", std::set<dealii::types::material_id>{4, 5}}}),\n      std::make_shared<std::unordered_map<\n          std::string, std::set<dealii::types::material_id>>>(\n          std::initializer_list<std::pair<\n              std::string const, std::set<dealii::types::boundary_id>>>{\n              {\"anode\", std::set<dealii::types::boundary_id>{1}},\n              {\"cathode\", std::set<dealii::types::boundary_id>{2}}}));\n\n  std::shared_ptr<MPValues<2>> mp_values =\n      std::make_shared<SuperCapacitorMPValues<2>>(mp_values_params);\n  dealii::DoFHandler<2>::active_cell_iterator cell = dof_handler.begin_active();\n  dealii::FEValues<2> fe_values(fe, dealii::QGauss<2>(1),\n                                dealii::update_default);\n  fe_values.reinit(cell);\n  // electrode\n  cell->set_material_id(1); // <- matches the anode material_id in the\n                            //    initializer list\n  std::vector<double> electrode_solid_electrical_conductivity_values(1);\n  std::vector<double> electrode_liquid_electrical_conductivity_values(1);\n  mp_values->get_values(\"solid_electrical_conductivity\", fe_values,\n                        electrode_solid_electrical_conductivity_values);\n  mp_values->get_values(\"liquid_electrical_conductivity\", fe_values,\n                        electrode_liquid_electrical_conductivity_values);\n  double const electrode_resistivity =\n      (1.0 / electrode_solid_electrical_conductivity_values[0] +\n       1.0 / electrode_liquid_electrical_conductivity_values[0] +\n       1.0 / (electrode_solid_electrical_conductivity_values[0] +\n              electrode_liquid_electrical_conductivity_values[0])) /\n      3.0;\n  double const electrode_resistance =\n      electrode_resistivity * electrode_width / cross_sectional_area;\n  std::vector<double> electrode_specific_capacitance_values(1);\n  mp_values->get_values(\"specific_capacitance\", fe_values,\n                        electrode_specific_capacitance_values);\n  double const electrode_capacitance =\n      electrode_specific_capacitance_values[0] * electrode_width *\n      cross_sectional_area;\n  std::vector<double> electrode_exchange_current_density_values(1);\n  mp_values->get_values(\"faradaic_reaction_coefficient\", fe_values,\n                        electrode_exchange_current_density_values);\n  double const electrode_leakage_resistance =\n      1.0 / (electrode_exchange_current_density_values[0] * electrode_width *\n             cross_sectional_area);\n  std::cout << \"ELECTRODE\\n\";\n  std::cout << \"    specific_capacitance=\"\n            << electrode_specific_capacitance_values[0] << \"\\n\";\n  std::cout << \"    solid_electrical_conductivity=\"\n            << electrode_solid_electrical_conductivity_values[0] << \"\\n\";\n  std::cout << \"    liquid_electrical_conductivity=\"\n            << electrode_liquid_electrical_conductivity_values[0] << \"\\n\";\n  std::cout << \"    exchange_current_density=\"\n            << electrode_exchange_current_density_values[0] << \"\\n\";\n  std::cout << \"    width=\" << electrode_width << \"\\n\";\n  std::cout << \"    cross_sectional_area=\" << cross_sectional_area << \"\\n\";\n  // separator\n  cell->set_material_id(2); // <- matches the separator material_id in the\n                            //    initializer list\n  std::vector<double> separator_liquid_electrical_conductivity_values(1);\n  mp_values->get_values(\"liquid_electrical_conductivity\", fe_values,\n                        separator_liquid_electrical_conductivity_values);\n  double const separator_resistivity =\n      1.0 / separator_liquid_electrical_conductivity_values[0];\n  double const separator_resistance =\n      separator_resistivity * separator_width / cross_sectional_area;\n  std::cout << \"SEPARATOR\\n\";\n  std::cout << \"    liquid_electrical_conductivity=\"\n            << separator_liquid_electrical_conductivity_values[0] << \"\\n\";\n  std::cout << \"    width=\" << separator_width << \"\\n\";\n  std::cout << \"    cross_sectional_area=\" << cross_sectional_area << \"\\n\";\n  // collector\n  cell->set_material_id(4); // <- matches the collector  material_id in the\n                            //    initializer list\n  std::vector<double> collector_solid_electrical_conductivity_values(1);\n  mp_values->get_values(\"solid_electrical_conductivity\", fe_values,\n                        collector_solid_electrical_conductivity_values);\n  double const collector_resistivity =\n      1.0 / collector_solid_electrical_conductivity_values[0];\n  double const collector_resistance =\n      collector_resistivity * collector_width / cross_sectional_area;\n  std::cout << \"COLLECTOR\\n\";\n  std::cout << \"    solid_electrical_conductivity=\"\n            << collector_solid_electrical_conductivity_values[0] << \"\\n\";\n  std::cout << \"    width=\" << collector_width << \"\\n\";\n  std::cout << \"    cross_sectional_area=\" << cross_sectional_area << \"\\n\";\n\n  std::cout << \"electrode_capacitance=\" << electrode_capacitance << \"\\n\";\n  std::cout << \"electrode_resistance=\" << electrode_resistance << \"\\n\";\n  std::cout << \"electrode_leakage_resistance=\" << electrode_leakage_resistance\n            << \"\\n\";\n  std::cout << \"separator_resistance=\" << separator_resistance << \"\\n\";\n  std::cout << \"collector_resistance=\" << collector_resistance << \"\\n\";\n\n  // compute the effective resistance and capacitance\n  double const sandwich_capacitance = electrode_capacitance / 2.0;\n  double const sandwich_resistance = 2.0 * electrode_resistance +\n                                     separator_resistance +\n                                     2.0 * collector_resistance;\n  double const sandwich_leakage_resistance = 2.0 * electrode_leakage_resistance;\n  std::cout << \"sandwich_capacitance=\" << sandwich_capacitance << \"\\n\";\n  std::cout << \"sandwich_resistance=\" << sandwich_resistance << \"\\n\";\n  std::cout << \"sandwich_leakage_resistance=\" << sandwich_leakage_resistance\n            << \"\\n\";\n\n  output_database.put(\"capacitance\", sandwich_capacitance);\n  output_database.put(\"series_resistance\", sandwich_resistance);\n  output_database.put(\"parallel_resistance\", sandwich_leakage_resistance);\n  if (std::isfinite(sandwich_leakage_resistance))\n    output_database.put(\"type\", \"ParallelRC\");\n  else\n    output_database.put(\"type\", \"SeriesRC\");\n}\n\nclass EquivalentCircuitBuilder : public EnergyStorageDeviceBuilder\n{\npublic:\n  EquivalentCircuitBuilder()\n  {\n    register_energy_storage_device(\"EquivalentCircuit\", this);\n  }\n  std::unique_ptr<EnergyStorageDevice>\n  build(boost::property_tree::ptree const &ptree,\n        boost::mpi::communicator const &comm) override\n  {\n    boost::property_tree::ptree other;\n    compute_equivalent_circuit(ptree, other);\n    return EnergyStorageDevice::build(other, comm);\n  }\n} global_EquivalentCircuitBuilder;\n\n} // end namespace cap\n", "meta": {"hexsha": "22977a678c67aef260f755ea0191def134bd16f0", "size": 9775, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/source/deal.II/equivalent_circuit.cc", "max_stars_repo_name": "iiscsahoo/EnergyData", "max_stars_repo_head_hexsha": "6230145b5df6b126eab11aea58a5cfaa11ad5ba1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2016-05-15T11:42:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T19:33:04.000Z", "max_issues_repo_path": "cpp/source/deal.II/equivalent_circuit.cc", "max_issues_repo_name": "iiscsahoo/EnergyData", "max_issues_repo_head_hexsha": "6230145b5df6b126eab11aea58a5cfaa11ad5ba1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 198.0, "max_issues_repo_issues_event_min_datetime": "2016-01-27T16:46:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-11T06:31:37.000Z", "max_forks_repo_path": "cpp/source/deal.II/equivalent_circuit.cc", "max_forks_repo_name": "iiscsahoo/EnergyData", "max_forks_repo_head_hexsha": "6230145b5df6b126eab11aea58a5cfaa11ad5ba1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-01-27T15:17:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T02:06:50.000Z", "avg_line_length": 48.1527093596, "max_line_length": 109, "alphanum_fraction": 0.7023017903, "num_tokens": 2395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2953438721840835}}
{"text": "#ifndef CONTEXT_HELIB_F2_HPP\n#define CONTEXT_HELIB_F2_HPP\n\n#include <NTL/BasicThreadPool.h>\n#include <chrono>\n#include <type_traits>\n#include <unordered_map>\n#include <complex>\n#include <cmath>\n#include \"bits.hpp\"\nNTL_CLIENT\n\n#include \"circuit.hpp\"\n#include \"context.hpp\"\n\n#include \"Ctxt.h\"\n#include \"EncryptedArray.h\"\n#include \"FHE.h\"\n\n#include \"binaryArith.h\"\n#include \"binaryCompare.h\"\n#include \"intraSlot.h\"\n\nnamespace SHEEP {\n\ntemplate <typename PlaintextT, typename CiphertextT>\nclass ContextHElib : public Context<PlaintextT, CiphertextT> {\n public:\n  typedef PlaintextT Plaintext;\n  typedef CiphertextT Ciphertext;\n  // typedef std::vector<PlaintextT> Ciphertext;\n  // typedef PlaintextT CiphertextEl;\n\n  /// constructors\n  ContextHElib(long p,               // plaintext modulus\n               long param_set = 0,   // parameter set, from 0 (tiny) to 4 (huge)\n               long bootstrapl = 1,  // bootstrap or not?\n               long hamming_weight = 128)\n      :  // Hamming weight of secret key\n\n        m_p(p),\n        m_param_set(param_set),\n        m_bootstrapl(bootstrapl),\n        m_w(hamming_weight) {\n    /// BITWIDTH(bool) is 8, so need to deal with this by hand...\n    //// (better to specialize class?)\n    if (std::is_same<Plaintext, bool>::value)\n      m_bitwidth = 1;\n    else\n      m_bitwidth = BITWIDTH(Plaintext);\n\n    ////  populate the map that will allow us to set parameters via an input\n    ///file (or string)\n\n    this->m_param_name_map.insert({\"BaseParamSet\", m_param_set});\n    this->m_param_name_map.insert({\"HammingWeight\", m_w});\n    this->m_param_name_map.insert({\"Bootstrap\", m_bootstrapl});\n    this->m_param_name_map.insert({\"m\", m_m});\n    this->m_param_name_map.insert({\"phim\", m_phim});\n    this->m_param_name_map.insert({\"d\", m_d});\n    this->m_param_name_map.insert({\"m1\", m_m1});\n    this->m_param_name_map.insert({\"m2\", m_m2});\n    this->m_param_name_map.insert({\"m3\", m_m3});\n    this->m_param_name_map.insert({\"g1\", m_g1});\n    this->m_param_name_map.insert({\"g2\", m_g2});\n    this->m_param_name_map.insert({\"g3\", m_g3});\n    this->m_param_name_map.insert({\"ord1\", m_ord1});\n    this->m_param_name_map.insert({\"ord2\", m_ord2});\n    this->m_param_name_map.insert({\"ord3\", m_ord3});\n    this->m_param_name_map.insert({\"c\", m_c});\n    this->m_param_name_map.insert({\"BitsPerLevel\", m_B});\n    this->m_param_name_map.insert({\"Levels\", m_L});\n    /// sizes of objects in bytes.  Assign values when they are constructed.\n    this->m_ciphertext_size = 0;\n    this->m_public_key_size = 0;\n    this->m_private_key_size = 0;\n\n    /// configure\n    configure();\n  }\n\n  void configure() {\n    m_bootstrap = (bool)m_bootstrapl;\n    /// Set all the other parameters.\n\n    long mValues[][15] = {\n        // { p, phi(m),   m,   d, m1, m2, m3,    g1,   g2,   g3, ord1,ord2,ord3,\n        // B,c}\n        {2, 48, 105, 12, 3, 35, 0, 71, 76, 0, 2, 2, 0, 25, 2},\n        {2, 600, 1023, 10, 11, 93, 0, 838, 584, 0, 10, 6, 0, 25, 2},\n        {2, 2304, 4641, 24, 7, 3, 221, 3979, 3095, 3760, 6, 2, -8, 25, 3},\n        {2, 15004, 15709, 22, 23, 683, 0, 4099, 13663, 0, 22, 31, 0, 25, 3},\n        {2, 27000, 32767, 15, 31, 7, 151, 11628, 28087, 25824, 30, 6, -10, 28,\n         4}};\n\n    long* vals = mValues[m_param_set];\n    //// if parameters were not set explicitly in a parameters file, take the\n    ///value from /  the mValues array.  (But if they were set explicitly, use\n    ///that value!)\n\n    if (!this->override_param(\"m\")) m_m = vals[2];\n    if (!this->override_param(\"phi(m)\")) m_phim = vals[1];\n    if (!this->override_param(\"d\")) m_d = vals[3];\n    if (!this->override_param(\"m1\")) m_m1 = vals[4];\n    if (!this->override_param(\"m2\")) m_m2 = vals[5];\n    if (!this->override_param(\"m3\")) m_m3 = vals[6];\n    if (!this->override_param(\"g1\")) m_g1 = vals[7];\n    if (!this->override_param(\"g2\")) m_g2 = vals[8];\n    if (!this->override_param(\"g3\")) m_g3 = vals[9];\n    if (!this->override_param(\"ord1\")) m_ord1 = vals[10];\n    if (!this->override_param(\"ord2\")) m_ord2 = vals[11];\n    if (!this->override_param(\"ord3\")) m_ord3 = vals[12];\n    if (!this->override_param(\"B\")) m_B = vals[13];\n    if (!this->override_param(\"c\")) m_c = vals[14];\n\n    NTL::Vec<long> mvec;\n    append(mvec, m_m1);\n    if (m_m2 > 1) append(mvec, m_m2);\n    if (m_m3 > 1) append(mvec, m_m3);\n\n    std::vector<long> gens;\n    gens.push_back(m_g1);\n    if (m_g2 > 1) gens.push_back(m_g2);\n    if (m_g3 > 1) gens.push_back(m_g3);\n\n    std::vector<long> ords;\n    ords.push_back(m_ord1);\n    if (abs(m_ord2) > 1) ords.push_back(m_ord2);\n    if (abs(m_ord3) > 1) ords.push_back(m_ord3);\n\n    /// number of levels  (copied from HElib's Test_binaryCompare)\n    if (!this->override_param(\"Levels\")) {\n      if (m_bootstrap)\n        m_L = 30;\n      else\n        m_L = 3 + NTL::NumBits(m_bitwidth + 2);\n    }\n    /// initialize HElib context\n    m_helib_context = new FHEcontext(m_m, m_p, 1, gens, ords);\n    m_helib_context->bitsPerLevel = m_B;\n    /// modify context, add primes to modulus chain\n    buildModChain(*m_helib_context, m_L, m_c, 8);\n\n    if (m_bootstrap) {\n      m_helib_context->makeBootstrappable(mvec, /*t=*/0,\n                                          /*flag=*/false, /*cacheType=DCRT*/ 2);\n    }\n\n    // unpack slot encoding\n    buildUnpackSlotEncoding(m_unpackSlotEncoding, *(m_helib_context->ea));\n\n    /// create secret key structure\n    m_secretKey = new FHESecKey(*m_helib_context);\n\n    m_publicKey = m_secretKey;  //// points to the same place\n\n    /// generate a secret key\n    m_secretKey->GenSecKey(m_w);  /// Hamming weight of 128\n\n    addSome1DMatrices(*m_secretKey);\n    addFrbMatrices(*m_secretKey);\n\n    /// how big are keys?\n    this->m_private_key_size = sizeof(*m_secretKey);\n    this->m_public_key_size = sizeof(*m_publicKey);\n\n    if (m_bootstrap) m_secretKey->genRecryptData();\n\n    m_ea = new EncryptedArray(*m_helib_context);\n\n    this->m_nslots = m_ea->size();\n  };\n\n  // destructor\n  virtual ~ContextHElib() {\n    /// delete everything we new-ed in the constructor\n    if (m_ea != NULL) delete m_ea;\n    if (m_secretKey != NULL) delete m_secretKey;\n    if (m_helib_context != NULL) delete m_helib_context;\n  };\n\n  virtual Ciphertext encrypt(std::vector<Plaintext> pt) = 0;\n  virtual std::vector<Plaintext> decrypt(Ciphertext pt) = 0;\n\n protected:\n  long m_param_set;  // which set of parameters to use (0 to 4).\n  long m_p;          //  modulus of plaintext\n  long m_B;          // number of bits per level\n  long m_L;          // maximum number of homomorphic levels\n  long m_w;          // Hamming weight of secret key\n  long m_c;          // number of columns in key-switching matrix\n\n  long m_m;\n  long m_phim;\n  long m_d;\n  long m_m1;\n  long m_m2;\n  long m_m3;\n  long m_g1;\n  long m_g2;\n  long m_g3;\n  long m_ord1;\n  long m_ord2;\n  long m_ord3;\n  EncryptedArray* m_ea;\n  FHESecKey* m_secretKey;\n  const FHEPubKey* m_publicKey;\n  FHEcontext* m_helib_context;\n  int m_bitwidth;\n  std::vector<zzX> m_unpackSlotEncoding;\n  bool m_bootstrap;\n  long m_bootstrapl;  /// long version of the bootstrap flag to allow it to be\n                      /// settable from param_name_map\n\n};  //// end of ContextHElib class definition.\n\n////////////////////////////////////////////////////////////////////////////////////\n///  ContextHElib_F2 -  use p=2, do everything with arrays of Ciphertext,\n///  and binary operations for add, multiply, compare etc.\ntemplate <typename PlaintextT>\nclass ContextHElib_F2 : public ContextHElib<PlaintextT, NTL::Vec<Ctxt> > {\n public:\n  typedef PlaintextT Plaintext;\n  typedef NTL::Vec<Ctxt> Ciphertext;\n\n  ContextHElib_F2(\n      long param_set = 0,         // parameter set, from 0 (tiny) to 4 (huge)\n      bool bootstrap = true,      // bootstrap or not?\n      long hamming_weight = 128)  // Hamming weight of secret key\n      : ContextHElib<Plaintext, Ciphertext>(2, param_set, bootstrap,\n                                            hamming_weight) {\n    /// this is not nice, but for Compare, it helps to know if we are dealing\n    /// with signed or unsigned inputs\n    m_signed_plaintext = (std::is_same<Plaintext, int8_t>::value ||\n                          std::is_same<Plaintext, int16_t>::value ||\n                          std::is_same<Plaintext, int32_t>::value);\n\n    m_bool_plaintext = std::is_same<Plaintext, bool>::value;\n  }\n\n  Ciphertext encrypt(std::vector<Plaintext> pt) {\n    if (pt.size() > this->m_nslots) {\n      throw std::runtime_error(\n          \"The number of slots is greater than the number of SIMD operations \"\n          \"that can be done at a time\");\n    }\n\n    Ctxt mu(*(this->m_publicKey), (long)this->m_nslots);\n    Ciphertext ct;\n\n    resize(ct, this->m_bitwidth, mu);\n\n    for (int j = 0; j < this->m_bitwidth; j++) {\n      vector<ZZX> sliced_pt = vector<ZZX>(this->m_nslots);\n\n      // sliced_pt[i] is the jth bit of input i\n      for (int i = 0; i < pt.size(); i++) {\n        sliced_pt[i] = ZZX((pt[i] >> j) & 1);\n      }\n\n      this->m_ea->encrypt(ct[j], *(this->m_publicKey), sliced_pt);\n    }\n    return ct;\n  }\n\n  std::vector<Plaintext> decrypt(Ciphertext ct) {\n    std::vector<long> ct_decrypt = std::vector<long>(this->m_nslots);\n    std::vector<Plaintext> pt_transformed =\n        std::vector<Plaintext>(this->m_nslots);\n\n    decryptBinaryNums(ct_decrypt, CtPtrs_VecCt(ct), *(this->m_secretKey),\n                      *(this->m_ea));\n\n    for (int i = 0; i < this->m_nslots; i++) {\n      pt_transformed[i] = ct_decrypt[i] % int(pow(2, this->m_bitwidth));\n    }\n    return pt_transformed;\n  }\n\n\n  std::string encrypt_and_serialize(std::vector<PlaintextT> pt) {\n    Ciphertext ct = encrypt(pt);\n    std::stringstream ss;\n    for (int i=0; i< this->m_bitwidth; ++i) {\n      ss << ct[i];\n    }\n    std::string ctstring = ss.str();\n    return ctstring;\n  };\n\n  Ciphertext Negate(Ciphertext a) {\n    /// bootstrapping method copied from HElib's Test_binaryCompare\n    if (this->m_bootstrap) {\n      for (int i = 0; i < this->m_bitwidth; ++i) {\n        a[i].modDownToLevel(5);\n      }\n    }\n\n    /// Two's complement negation - negate all bits then add one\n    Ciphertext output;\n\n    for (int i = 0; i < this->m_bitwidth; ++i) {\n      Ctxt abit = a[i];\n      abit.addConstant(to_ZZX(1L));\n      output.append(abit);\n    }\n\n    if (this->m_bitwidth == 1)\n      return output;  // for a bool, we are already done..\n\n    /// for integers, need to add 1.\n    std::vector<Plaintext> one;\n    for (int i = 0; i < this->m_nslots; i++) {\n      one.push_back(1);\n    }\n\n    Ciphertext one_enc = encrypt(one);\n    Ciphertext output_final = Add(output, one_enc);\n\n    return output_final;\n  }\n\n  Ciphertext Maximum(Ciphertext a, Ciphertext b) {\n    /// \"Maximum\" i.e. \"OR\" only valid for bool inputs.  If not, call the\n    /// base-class function (which will throw a GateNotImplemented error).\n    if (!this->m_bool_plaintext) Context<Plaintext, Ciphertext>::Maximum(a, b);\n    /// OR(a,b) = XOR( XOR(a,b), AND(a,b))\n    Ciphertext output;\n\n    Ctxt a1 = a[0];\n    Ctxt a2 = a[0];\n    a1 += b[0];  // XOR(a,b)\n    a2 *= b[0];  // AND(a,b)\n    a1 += a2;    // XOR the previous two lines\n    output.append(a1);\n    return output;\n  }\n\n  Ciphertext Compare_unsigned(Ciphertext a, Ciphertext b) {\n    Ctxt mu(*(this->m_publicKey));\n    Ctxt ni(*(this->m_publicKey));\n    Ciphertext cmax, cmin;\n    CtPtrs_VecCt wMin(cmin), wMax(cmax);  /// wrappers around output vectors\n    compareTwoNumbers(wMax, wMin, mu, ni, CtPtrs_VecCt(a), CtPtrs_VecCt(b),\n                      &(this->m_unpackSlotEncoding));\n    /// mu is now a Ctxt which is the encryption of 1 if a>b and 0 otherwise.\n    /// but we need to put it into NTL::Vec<Ctxt> as that is our new\n    /// \"Ciphertext\" type.\n    Ciphertext output;\n    output.append(mu);\n    return output;\n  }\n\n  Ciphertext Compare_signed(Ciphertext a, Ciphertext b) {\n    //// subtract a-b and look at sign-bit\n    Ciphertext b_minus_a = Subtract(b, a);\n    Ciphertext output;\n\n    Ctxt sign_bit =\n        b_minus_a[this->m_bitwidth - 1];  /// is sign-bit set?  if yes, b\n    output.append(sign_bit);\n    return output;\n  }\n\n  Ciphertext Compare(Ciphertext a, Ciphertext b) {\n    if (this->m_bootstrap) {\n      for (int i = 0; i < this->m_bitwidth; ++i) {\n        a[i].modDownToLevel(5);\n        b[i].modDownToLevel(5);\n      }\n    }\n    if (this->m_signed_plaintext)\n      return Compare_signed(a, b);\n    else\n      return Compare_unsigned(a, b);\n  }\n\n  Ciphertext Subtract(Ciphertext a, Ciphertext b) {\n    if (this->m_bitwidth == 1)\n      return Add(a, b);  //// for bools, add and subtract are the same\n\n    if (this->m_bootstrap) {\n      for (int i = 0; i < this->m_bitwidth; ++i) {\n        a[i].modDownToLevel(5);\n      }\n    }\n\n    Ciphertext output;\n    Ciphertext b_neg = Negate(b);\n    CtPtrs_VecCt wout(output);\n    addTwoNumbers(wout, CtPtrs_VecCt(a), CtPtrs_VecCt(b_neg), this->m_bitwidth,\n                  &(this->m_unpackSlotEncoding));\n    return output;\n  }\n\n  Ciphertext Add(Ciphertext a, Ciphertext b) {\n    if (this->m_bootstrap) {\n      for (int i = 0; i < this->m_bitwidth; ++i) {\n        a[i].modDownToLevel(5);\n      }\n    }\n\n    Ciphertext sum;\n    CtPtrs_VecCt wsum(sum);\n\n    addTwoNumbers(wsum, CtPtrs_VecCt(a), CtPtrs_VecCt(b), this->m_bitwidth,\n                  &(this->m_unpackSlotEncoding));\n\n    return sum;\n  }\n\n  Ciphertext Multiply(Ciphertext a, Ciphertext b) {\n    if (this->m_bootstrap) {\n      for (int i = 0; i < this->m_bitwidth; ++i) {\n        a[i].modDownToLevel(5);\n      }\n    }\n\n    Ciphertext product;\n    CtPtrs_VecCt wprod(product);\n\n    multTwoNumbers(wprod, CtPtrs_VecCt(a), CtPtrs_VecCt(b), false,\n                   this->m_bitwidth, &(this->m_unpackSlotEncoding));\n\n    return product;\n  }\n\n  Ciphertext Select(Ciphertext s, Ciphertext a, Ciphertext b) {\n    if (this->m_bootstrap) {\n      for (int i = 0; i < this->m_bitwidth; ++i) {\n        a[i].modDownToLevel(5);\n        b[i].modDownToLevel(5);\n      }\n    }\n    /// s is 0 or 1\n    /// for each bit of a,b,output, do output = s*a + (1-s)*b\n    Ciphertext output;\n\n    for (int i = 0; i < this->m_bitwidth; ++i) {\n      Ctxt sbit = s[0];\n      Ctxt abit = a[i];\n      Ctxt bbit = b[i];\n      abit *= sbit;\n      sbit.addConstant(to_ZZX(-1L));\n      sbit.multByConstant(to_ZZX(-1L));\n      sbit *= bbit;\n      abit += sbit;\n      output.append(abit);\n    }\n    return output;\n  }\n\n  Ciphertext Rotate(Ciphertext a, long n) {\n    /// Cyclically rotate the linear array by n positions\n    if (n > this->m_nslots) {\n      throw std::runtime_error(\"Error in Rotate: cannot rotate by more than nslots positions\");\n    }\n    Ciphertext result;\n    if (n > 0) n = n - this->m_ninputs;\n    /// loop over all bits\n    for (int j = 0; j < this->m_bitwidth; j++) {\n      Ctxt result_bit(a[j]);\n      this->m_ea->rotate(result_bit, n);\n      result.append(result_bit);\n    }\n    return result;\n\n  }\n\n private:\n  bool m_signed_plaintext;\n  bool m_bool_plaintext;\n\n};  /// end of class definition\n\n// (dummy) specializations for double and complex<double>\ntemplate <>\nclass ContextHElib_F2<double> : public Context<double, NTL::Vec<Ctxt> > {\n public:\n  typedef double Plaintext;\n  typedef NTL::Vec<Ctxt>  Ciphertext;\n\n  ContextHElib_F2() {\n    throw InputTypeNotSupported();\n  }\n  Ciphertext encrypt(std::vector<Plaintext> pt) {\n    throw InputTypeNotSupported();\n  }\n  std::vector<Plaintext> decrypt(Ciphertext ct) {\n    throw InputTypeNotSupported();\n  }\n};\n\ntemplate <>\nclass ContextHElib_F2<std::complex<double> >: public Context<std::complex<double>, NTL::Vec<Ctxt> > {\n public:\n  typedef std::complex<double> Plaintext;\n  typedef NTL::Vec<Ctxt>  Ciphertext;\n\n  ContextHElib_F2() {\n    throw InputTypeNotSupported();\n  }\n  Ciphertext encrypt(std::vector<Plaintext> pt) {\n    throw InputTypeNotSupported();\n  }\n  std::vector<Plaintext> decrypt(Ciphertext ct) {\n    throw InputTypeNotSupported();\n  }\n};\n\n\n////////////////////////////////////////////////////////////////////////////\n//// ContextHElib_Fp  - use integer plaintext space, e.g. p=65537\n\ntemplate <typename PlaintextT>\nclass ContextHElib_Fp : public ContextHElib<PlaintextT, Ctxt> {\n public:\n  typedef PlaintextT Plaintext;\n  typedef Ctxt Ciphertext;\n\n  ContextHElib_Fp(\n      long p = 65537,             // plaintext modulus\n      long param_set = 0,         // parameter set, from 0 (tiny) to 4 (huge)\n      bool bootstrap = false,     // bootstrap or not?\n      long hamming_weight = 128)  // Hamming weight of secret key\n      : ContextHElib<Plaintext, Ciphertext>(p, param_set, bootstrap,\n                                            hamming_weight) {\n    this->m_ninputs = 0;\n    this->m_param_name_map.insert({\"p\", this->m_p});\n  }\n\n  Ciphertext encrypt(std::vector<Plaintext> pt) {\n    std::vector<long> ptvec;\n\n    int pt_len = pt.size();\n\n    // Check whether the input is too long to be encrypted in one go\n    if (pt_len > this->m_nslots) {\n      throw std::runtime_error(\n          \"The number of slots is greater than the number of SIMD operations \"\n          \"that can be done at a time\");\n    }\n    // convert plaintext input into a vector of longs\n    for (int i = 0; i < this->m_nslots; i++) {\n      ptvec.push_back(pt[i % pt_len]);\n    }\n\n    // encrypt vector of longs\n    Ciphertext ct(*(this->m_publicKey));\n\n    this->m_ea->encrypt(ct, *(this->m_publicKey), ptvec);\n    this->m_ciphertext_size = sizeof(ct);\n\n    return ct;\n  }\n\n  std::vector<Plaintext> decrypt(Ciphertext ct) {\n    std::vector<Plaintext> result;\n    std::vector<long> pt;\n\n    long pt_transformed;\n\n    this->m_ea->decrypt(ct, *(this->m_secretKey), pt);\n\n    for (int i = 0; i < pt.size(); i++) {\n      // convention - treat this as a negative number\n      if ((pt[i]) > this->m_p / 2)\n        pt_transformed = pt[i] - this->m_p;\n      else\n        pt_transformed = pt[i];\n\n      result.push_back(pt_transformed % int(pow(2, this->m_bitwidth)));\n    }\n\n    return result;\n  }\n\n  std::string encrypt_and_serialize(std::vector<PlaintextT> pt) {\n    Ciphertext ct = encrypt(pt);\n    std::stringstream ss;\n    ss << ct;\n    std::string ctstring = ss.str();\n    return ctstring;\n  };\n\n  Ciphertext Add(Ciphertext a, Ciphertext b) {\n    a += b;\n    return a;\n  }\n\n  Ciphertext Subtract(Ciphertext a, Ciphertext b) {\n    a -= b;\n    return a;\n  }\n\n  Ciphertext Multiply(Ciphertext a, Ciphertext b) {\n    a *= b;\n    return a;\n  }\n\n  Ciphertext Negate(Ciphertext a) {\n    if (this->m_bitwidth == 1)  /// special case for binary\n      a.addConstant(to_ZZX(1L));\n    else\n      a.multByConstant(to_ZZX(-1L));\n\n    return a;\n  }\n\n  Ciphertext MultByConstant(Ciphertext a, long b) {\n    a.multByConstant(to_ZZX(b));\n    return a;\n  }\n\n  Ciphertext AddConstant(Ciphertext a, long b) {\n    a.addConstant(to_ZZX(b));\n\n    return a;\n  }\n\n  Ciphertext Select(Ciphertext s, Ciphertext a, Ciphertext b) {\n    /// s is 0 or 1\n    /// output is s*a + (1-s)*b\n    Ciphertext sa = Multiply(s, a);\n    Ciphertext one_minus_s = MultByConstant(AddConstant(s, -1L), -1L);\n    Ciphertext one_minus_s_times_b = Multiply(one_minus_s, b);\n    return Add(sa, one_minus_s_times_b);\n  }\n\n  Ciphertext Rotate(Ciphertext a, long n) {\n    /// Cyclically rotate the linear array by n positions\n    if (n > this->m_nslots) {\n      throw std::runtime_error(\"Error in Rotate: cannot rotate by more than nslots positions\");\n    }\n    //to rotate right, we actually rotate left\n    // by (ninputs - n) positions\n    if (n > 0) n = n - this->m_ninputs;\n\n    Ciphertext result(a);\n    this->m_ea->rotate(result, n);\n\n    return result;\n  }\n\n};  /// end of class definition\n\n// (dummy) specializations for double and complex<double>\ntemplate <>\nclass ContextHElib_Fp<double> : public Context<double, Ctxt > {\n public:\n  typedef double Plaintext;\n  typedef Ctxt  Ciphertext;\n\n  ContextHElib_Fp() {\n    throw InputTypeNotSupported();\n  }\n  Ciphertext encrypt(std::vector<Plaintext> pt) {\n    throw InputTypeNotSupported();\n  }\n  std::vector<Plaintext> decrypt(Ciphertext ct) {\n    throw InputTypeNotSupported();\n  }\n};\n\ntemplate <>\nclass ContextHElib_Fp<std::complex<double> >: public Context<std::complex<double>, Ctxt > {\n public:\n  typedef std::complex<double> Plaintext;\n  typedef Ctxt  Ciphertext;\n\n  ContextHElib_Fp() {\n    throw InputTypeNotSupported();\n  }\n  Ciphertext encrypt(std::vector<Plaintext> pt) {\n    throw InputTypeNotSupported();\n  }\n  std::vector<Plaintext> decrypt(Ciphertext ct) {\n    throw InputTypeNotSupported();\n  }\n};\n\n\n}  // namespace SHEEP\n\n#endif  // CONTEXT_HELIB_HPP\n", "meta": {"hexsha": "b477dde52731c0b8a48e6e6f25dc0a860a519a86", "size": 20441, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "backend/include/context-helib.hpp", "max_stars_repo_name": "vkurilin/SHEEP", "max_stars_repo_head_hexsha": "2ccaef32c16efcf5dbc8eefd1dc243bed4ac2fbb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40.0, "max_stars_repo_stars_event_min_datetime": "2018-12-03T13:01:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T13:04:12.000Z", "max_issues_repo_path": "backend/include/context-helib.hpp", "max_issues_repo_name": "vkurilin/SHEEP", "max_issues_repo_head_hexsha": "2ccaef32c16efcf5dbc8eefd1dc243bed4ac2fbb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 63.0, "max_issues_repo_issues_event_min_datetime": "2018-09-11T14:13:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-14T16:12:39.000Z", "max_forks_repo_path": "backend/include/context-helib.hpp", "max_forks_repo_name": "vkurilin/SHEEP", "max_forks_repo_head_hexsha": "2ccaef32c16efcf5dbc8eefd1dc243bed4ac2fbb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-07-10T14:48:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T09:12:11.000Z", "avg_line_length": 29.7973760933, "max_line_length": 101, "alphanum_fraction": 0.6201262169, "num_tokens": 6095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.29523430967234743}}
{"text": "#include <cstdlib>\n#include <sstream>\n#include <string>\n\n#include <boost/program_options.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/algorithm/string.hpp>\n\n#include \"cell.hpp\"\n\n\nusing namespace std;\n\n\ntypedef map<pair<int, int>, int> pcn;   // copy number at a position\n\nint use_grandparent;\n\n// Read posterior distributions of parameters from file\n// parameter1\tparameter2\tdistance\tweights\nvoid read_params_posterior(string fname, vector<double>& param1, vector<double>& param2, vector<double>& param3, vector<double>& weights, int verbose = 0){\n   ifstream fin(fname);\n   string line;\n   // int i = 0;\n   while (getline(fin, line)) {\n       // i++;\n       // cout << \"line \" << i << endl;\n       // skip comment lines\n       if(!isdigit(line.c_str()[0])){\n           continue;\n       }\n       // Split line into tab-separated parts\n       vector<string> parts;\n       // parameter1\tparameter2\tdistance\tweights\n       boost::split(parts, line, boost::is_any_of(\"\\t\"));\n       // cout << parts.size() << \"\\t\" << parts[0] << \"\\t\" << parts[1] << \"\\t\" << parts[2] << endl;\n\n       param1.push_back(stod(parts[0]));\n       param2.push_back(stod(parts[1]));\n       if(parts.size()>4){\n           param3.push_back(stod(parts[2]));    // birth rates\n           weights.push_back(stod(parts[4]));\n       }else{\n           weights.push_back(stod(parts[3]));\n       }\n   }\n   fin.close();\n\n   // Test reading input\n   if(verbose > 0){\n       cout << \"Reading file \" << fname << endl;\n       cout << param1.size() << \"\\t\" << param2.size() << \"\\t\" << param3.size() << \"\\t\" << weights.size() << \"\\n\";\n   }\n   // for(int i = 0; i < param1.size(); i++){\n   //     cout << param1[i] << \"\\t\" << param2[i] << \"\\t\" << weights[i] << \"\\n\";\n   // }\n}\n\n\nvoid get_params_file(string dir_param, vector<string>& filenames, int verbose = 0){\n    for (boost::filesystem::directory_iterator itr(dir_param); itr!=boost::filesystem::directory_iterator(); ++itr)\n    {\n        string fname = itr->path().filename().string();\n        // cout << itr->path().filename() << ' '; // display filename only\n        // if (is_regular_file(itr->status())) cout << \" [\" << file_size(itr->path()) << ']';\n        // cout << '\\n';\n        std::string prefix = \"smc-\";\n        if(fname.compare(0, prefix.size(), prefix) == 0){\n            filenames.push_back(itr->path().string());\n        }\n    }\n    if(verbose > 0){\n        cout << \"Parameter files: \" << endl;\n        for(int i = 0; i < filenames.size(); i++){\n            cout << filenames[i] << endl;\n        }\n        cout << endl;\n    }\n}\n\n\n// Simulate the growth of one cell into a single organoid (clone)\nClone run_sim(double birth_rate, double death_rate, int Nend, double arm_prob, double chr_prob, double multi_prob, int skip, int only_mut, unsigned long rseed, string outdir, int genotype_diff = 0, double chr_weight = 1.0, int chr_sel=0, int use_ablen=0, string suffix=\"\", string prefix=\"\", int model = 0, string fitness_vals=\"\", int num_subclone = 0, double tmin = 0, double tmax = 0, double min_clone_freq = 0, double max_clone_freq = 0, int num_clonal_mutation = 0, string file_cmut = \"\", int verbose = 0){\n    Clone clone;\n\n    double lambda = birth_rate - death_rate;\n    double tend = log(Nend)/(lambda);\n\n    double mutation_rate = arm_prob + chr_prob + multi_prob;\n\n    vector<double> fitness;\n    if(fitness_vals!=\"\"){\n        stringstream ss(fitness_vals);\n        int num;   ss >> num;\n        for(int i = 0; i < num; i++){\n            double d1;\n            ss >> d1;\n            fitness.push_back(d1);\n        }\n    }\n\n    vector<double> time_occur;\n\n    if(verbose > 0){\n        cout << \"\\nSimulating tumor growth\" << endl;\n        cout << \"Random seed: \" << rseed << endl;\n        cout << \"Model of evolution: \" << model << endl;\n        cout << \"Initial Net growth rate: \" << lambda << endl;\n        if(fitness_vals != \"\"){\n          cout << \"Fitness values: \" << fitness_vals << endl;\n        }\n        cout << \"Mutation rate: \" << mutation_rate << endl;\n        cout << \"\\tChr-level CNA rate: \" << chr_prob << endl;\n        cout << \"\\tArm-level CNA rate: \" << arm_prob << endl;\n        cout << \"\\tMultipolar spindle (hopeful monster) rate: \" << multi_prob << endl;\n        cout << \"\\tEffective mutation rate (μ/β): \" << mutation_rate/((birth_rate - death_rate)/birth_rate) << endl;\n        cout << \"Estimated simulation finish time (tumor doublings): \" << tend << endl;\n    }\n\n    if(tmax > tend){\n        tmax = tend;\n    }\n\n    if(mutation_rate > 0){\n        if(verbose == 1) cout << \"\\nSimulating CIN\" << endl;\n        clone.grow_with_cnv(num_subclone, num_clonal_mutation, model, fitness, time_occur, Nend, birth_rate, death_rate, mutation_rate, arm_prob, chr_prob, multi_prob, genotype_diff, chr_weight, chr_sel, file_cmut, verbose);\n    }\n    else{\n        clone.grow(num_subclone, num_clonal_mutation, fitness, time_occur, Nend, birth_rate, death_rate, mutation_rate, verbose);\n    }\n\n    // not output anything when simulating bulk samples\n    if(verbose < 0) return clone;\n\n    if(verbose > 0){\n        const char* path = outdir.c_str();\n        boost::filesystem::path dir(path);\n        if(boost::filesystem::create_directory(dir))\n        {\n            if(verbose == 1) cerr << \"Directory Created: \" << outdir <<endl;\n        }\n        if(suffix == \"\"){\n            string sep = \"-\";\n            suffix = sep + to_string(num_subclone) + sep + to_string(Nend) + sep + to_string(int(birth_rate*10)) + sep + to_string(int(death_rate*10)) + sep + to_string(int(mutation_rate)) + sep + to_string(num_clonal_mutation) + sep + prefix + sep + to_string(int(tmin)) + sep + to_string(int(rseed));\n        }\n        string outfile = \"\";\n\n        // outfile = outdir + \"curr_vaf\" + suffix;\n        // cout << \"Computing VAF\" << endl;\n        // map<int, double> mut_freq = clone.get_allele_freq();\n        // clone.print_map(mut_freq, outfile);\n\n        outfile = outdir + \"summary\" + suffix;\n        cout << \"Printing summary\" << endl;\n        clone.print_summary(outfile);\n\n        outfile = outdir + \"end_cells_cn\" + suffix + \".txt\";\n        clone.print_obs_cn(clone.curr_cells, outfile, verbose);\n\n        // outfile = outdir + \"end_cells_cn\" + suffix + \"_rvec.txt\";\n        // clone.write_avg_reciprocal_cn(clone.curr_cells, outfile, false);\n\n        // // The proportion of chr-level and arm-level (p,q) events for each chromosome\n        // outfile = outdir + \"end_cells_cn\" + suffix + \"_prop.txt\";\n        // clone.write_prop(clone.curr_cells, outfile);\n        //\n        // outfile = outdir + \"end_cells_cn\" + suffix + \"_cnvec.txt\";\n        // clone.write_avg_cn(clone.curr_cells, outfile);\n        //\n        // outfile = outdir + \"end_cells_cn\" + suffix + \"_uvec.txt\";\n        // clone.write_avg_uniq_cn(clone.curr_cells, outfile);\n        //\n        // outfile = outdir + \"end_cells_cn\" + suffix + \"_avec.txt\";\n        // clone.write_aggregated_uniq_cn(clone.curr_cells, outfile);\n        //\n        // outfile = outdir + \"end_cells_cn\" + suffix + \"_lvec.txt\";\n        // clone.write_relative_reciprocal_cn(clone.curr_cells, outfile, false);\n\n        // Output total number of de novo events in the population\n        // outfile = outdir + \"summary_stats\" + suffix + \".txt\";\n        // clone.write_summary_stats(sum_stats, outfile);\n\n        if(verbose > 1){\n            cout << \"Printing out informaton of all cells in a tumor clone\" << endl;\n            // cout << \"file name\" << outfile << endl;\n            clone.print_lineage(clone.cells, outdir, suffix);\n\n            outfile = outdir + \"all_cells_tree\" + suffix + \".nwk\";\n            clone.write_newick(clone.cells, outfile);\n\n            outfile = outdir + \"all_cells_tree\" + suffix + \".txt\";\n            clone.write_tree(clone.cells, outfile);\n        }\n    }\n\n    // vector<double> sum_stats;\n    cout.precision(9);\n    vector<int> avg_cn(2, 0);\n    clone.get_avg_reciprocal_cn(clone.curr_cells, avg_cn, false);\n    for(int i = 0; i < avg_cn.size(); i++){\n        double ac = (double) avg_cn[i] / clone.curr_cells.size();\n        // sum_stats.push_back(ac);\n        cout << ac << \"\\t\";\n    }\n\n    if(use_ablen == 1){     // Output all the tree lenghts\n        if(fitness_vals != \"\"){\n            vector<double> blens;\n            clone.get_treelen_vec(blens, clone.cells, skip);\n            cout << blens[0];\n            for(int i = 1; i < blens.size(); i++){\n                cout << \"\\t\" << blens[i];\n            }\n            cout << \"\\t\";\n        }\n    }else{\n        // Output half tree length (cell lineage tree is symmetrical)\n        double tlen = clone.get_treelen(clone.cells, skip);\n        // sum_stats.push_back(tlen);\n        // cout << tlen << endl;\n        cout << tlen << \"\\t\";\n\n        // Output branch length ratios of parent and daughter cells of current cell\n        if(verbose > 1) cout << \"\\ngetting branch length ratios\" << endl;\n        vector<double> ratios;\n        clone.get_treelen_ratios(ratios, clone.cells, skip, only_mut, use_grandparent, verbose);\n        double avg_ratio = 0;\n        for(auto r : ratios){\n         if(verbose > 1)  cout << r << endl;\n          avg_ratio += r;\n        }\n        if(ratios.size() > 0){\n          avg_ratio = avg_ratio / ratios.size();\n        }\n        cout << avg_ratio << \"\\t\";\n\n        // Output half the sum length of branches after immediate CNAs (seem not working well)\n        // double elen = clone.get_elen(clone.cells, skip);\n        // cout << elen << \"\\t\";\n    }\n\n    int ndenovo = 0;\n    pcn clone_cnp;      // Group CNPs by arms\n    pcn clone_cnc;\n    for(auto cell : clone.curr_cells) {\n        cell.set_obs_cn();\n        for(auto cp : cell.obs_cn_profile){\n            pair<int, int> pos = cp.first;\n            if(cp.second != 0){\n                ndenovo++;\n\n                if(pos.second==0){  // divide whole chromosome to two arms\n                    pair<int, int> pos1(pos.first, 1);\n                    clone_cnp[pos1] += abs(cp.second);\n                    clone_cnc[pos1] += 1;\n                    pair<int, int> pos2(pos.first, 2);\n                    clone_cnp[pos2] += abs(cp.second);\n                    clone_cnc[pos2] += 1;\n                }else{\n                    clone_cnp[pos] += abs(cp.second);\n                    clone_cnc[pos]++;\n                }\n            }\n        }\n    }\n    int naler_pos_l1sample = 0;\n    double sum_avg_cn = 0;\n    map<int, int> nalter_chr;   // count the number of altered position for each chromosome (at most 2)\n    for(auto cp : clone_cnp){\n        pair<int, int> pos = cp.first;\n        assert(pos.second!=0);\n        nalter_chr[pos.first]++;\n        if(clone_cnp[pos] > 1) naler_pos_l1sample += 1;\n        // double avg_cn = (double) clone_cnp[pos] / clone_cnc[pos];     // taking average over altered cells\n        double avg_cn = (double) clone_cnp[pos] / clone.curr_cells.size();     // taking average over all cells in an organoid\n        sum_avg_cn += abs(avg_cn);\n    }\n\n    int nalter = 0;\n    for(auto nc : nalter_chr){\n        assert(nc.second <= 2);\n        nalter += nc.second;\n    }\n\n    // double prop_alter = (double) nalter / (NUM_CHR * 2);\n    // Output summary statistics\n    // cout << prop_alter << endl;\n    cout << nalter << \"\\t\" << sum_avg_cn  << \"\\t\" << ndenovo << \"\\t\" << naler_pos_l1sample << endl;\n\n    return clone;\n\n}\n\n\n\n// set bulk parameters for one run according to random choice\nvoid set_bulk_params_random(vector<double>& params,  double min_birth_rate, double max_birth_rate, double min_arm_prob, double max_arm_prob, double min_chr_prob, double max_chr_prob, double min_mut_rate, double max_mut_rate, double avg_mut_rate, double max_multi_prob) {\n    // double mut_rate = runiform(r, min_mut_rate, max_mut_rate);\n    double mut_rate_init = gsl_ran_exponential(r, avg_mut_rate);\n    double mut_rate = mut_rate_init > max_mut_rate? max_mut_rate : mut_rate_init;\n\n    // // select arm_prob since chr_prob is biased towards small values in real data sets\n    // double max_arm_rate = mut_rate < max_arm_prob? mut_rate : max_arm_prob;\n    // double min_arm_rate = max_arm_rate < min_arm_prob? max_arm_rate : min_arm_prob;\n    // arm_prob = runiform(r, min_arm_rate, max_arm_rate);\n    // // chr_prob = runiform(r, min_chr_prob, max_arm_prob);\n    // double chr_prob_init = mut_rate - arm_prob;\n    // chr_prob = chr_prob_init > max_chr_prob? max_chr_prob:chr_prob_init;\n\n    // select chr_prob since chr_prob is often less than arm_prob in real data sets\n    double max_chr_rate = mut_rate < max_chr_prob? mut_rate : max_chr_prob;\n    double min_chr_rate = max_chr_rate < min_chr_prob? max_chr_rate : min_chr_prob;\n    double chr_prob = runiform(r, min_chr_rate, max_chr_rate);\n    // chr_prob = runiform(r, min_chr_prob, max_arm_prob);\n    double arm_prob_init = mut_rate - chr_prob;\n    double arm_prob = arm_prob_init > max_arm_prob? max_arm_prob : arm_prob_init;\n\n    double multi_prob = 0;\n    if(max_multi_prob > 0){\n        double multi_prob = runiform(r, 0, max_multi_prob);\n    }\n\n    mut_rate = chr_prob + arm_prob + multi_prob;\n    double birth_rate = runiform(r, min_birth_rate, max_birth_rate);\n\n    params.push_back(chr_prob);\n    params.push_back(arm_prob);\n    params.push_back(multi_prob);\n    params.push_back(mut_rate);\n    params.push_back(birth_rate);\n}\n\n\n// set bulk parameters for one run according to weighted choice from posterior distributions\nvoid set_bulk_params(vector<double>& params, const vector<string>& filenames,  double min_birth_rate, double max_birth_rate, double max_multi_prob, int verbose = 0){\n    // randomly pick up a dataset to choose parameters from\n    int i = runiform(r, 0, filenames.size());\n\n    string fname = filenames[i];\n    vector<double> param1;\n    vector<double> param2;\n    vector<double> param3;\n    vector<double> weights;\n    read_params_posterior(fname, param1, param2, param3, weights, verbose);\n\n    double* arr_weights = &weights[0];\n    gsl_ran_discrete_t*  dis = gsl_ran_discrete_preproc(weights.size(), arr_weights);\n    int sel = gsl_ran_discrete(r, dis);\n\n    double chr_prob, arm_prob, mut_rate, birth_rate, multi_prob = 0;\n    chr_prob = param1[sel];\n    arm_prob = param2[sel];\n\n    if(param3.size() > 0){\n        birth_rate = param3[sel];\n    }else{\n        birth_rate = runiform(r, min_birth_rate, max_birth_rate);\n    }\n    assert(birth_rate > 0);\n\n    // Multipolar rate:\n    // 1/24=0.0417  divisions in 20190409_1\n    // 1/23=0.0435  divisions in 20181127\n    // 1/18=0.0556  divisions in 20200403\n    if(max_multi_prob > 0){\n        // multi_prob = runiform(r, 0, max_multi_prob);\n        if(fname.find(\"20190409_1\")!=std::string::npos){\n            multi_prob = gsl_ran_exponential(r, 0.0417);\n        }else if(fname.find(\"20181127\")!=std::string::npos){\n            multi_prob = gsl_ran_exponential(r, 0.0435);\n        }else if(fname.find(\"20200403\")!=std::string::npos){\n            multi_prob = gsl_ran_exponential(r, 0.0556);\n        }else{\n            multi_prob = 0;\n        }\n    }\n\n    // Used for printing\n    mut_rate = chr_prob + arm_prob + multi_prob;\n\n    params.push_back(chr_prob);\n    params.push_back(arm_prob);\n    params.push_back(multi_prob);\n    params.push_back(mut_rate);\n    params.push_back(birth_rate);\n\n    if(verbose > 0)\n        cout << \"Selected parameters: \" << chr_prob << \"\\t\" << arm_prob << \"\\t\" << multi_prob << \"\\t\" << mut_rate << \"\\t\" << birth_rate << endl;\n}\n\n\n// set single organoid parameters for one run according to weighted choice from posterior distributions\nvoid set_organoid_params(vector<double>& params, string filename, double& birth_rate, int verbose = 0){\n    vector<double> param1;\n    vector<double> param2;\n    vector<double> param3;\n    vector<double> weights;\n    read_params_posterior(filename, param1, param2, param3, weights, verbose);\n\n    double* arr_weights = &weights[0];\n    gsl_ran_discrete_t*  dis = gsl_ran_discrete_preproc(weights.size(), arr_weights);\n    int sel = gsl_ran_discrete(r, dis);\n\n    double chr_prob, arm_prob;\n    chr_prob = param1[sel];\n    arm_prob = param2[sel];\n\n    if(param3.size() > 0){\n        birth_rate = param3[sel];\n    }\n    assert(birth_rate > 0);\n\n    // mut_rate = chr_prob + arm_prob + multi_prob;\n\n    params.push_back(chr_prob);\n    params.push_back(arm_prob);\n    // params.push_back(mut_rate);\n    params.push_back(birth_rate);\n\n    if(verbose > 0)\n        cout << \"Selected parameters: \" << chr_prob << \"\\t\" << arm_prob << \"\\t\" << birth_rate << endl;\n}\n\n\nvoid get_bulk_stat(pcn& bulk_cnp, pcn& bulk_cnc, int nsample, int ndenovo, int verbose = 0){\n    // Take the average of each bulk sample to get the CN profiles of all bulk samples\n    double sum_avg_cn = 0;\n    // double total_cn = 0;\n    map<int, int> nalter_chr;   // count the number of altered position for each chromosome (at most 2)\n    int naler_pos_l1sample = 0;    // count the number of  altered position for each chromosome which appear in more than one samples\n    // cout << \"Bulk CNPs: \" << endl;\n    assert(bulk_cnp.size() <= 2 * NUM_CHR);\n    for(auto cp : bulk_cnp){\n        pair<int, int> pos = cp.first;\n        assert(pos.second!=0);\n        nalter_chr[pos.first]++;\n        if(bulk_cnc[pos]>1) naler_pos_l1sample++;\n        // double avg_cn = (double) bulk_cnp[pos] / bulk_cnc[pos];     // taking average over all samples\n        double avg_cn = (double) bulk_cnp[pos] / nsample;     // taking average over all samples\n        // if(verbose>0) cout << pos.first + 1 << \"\\t\" << pos.second << \"\\t\" << cp.second << \"\\t\" << avg_cn << \"\\t\" << bulk_cnc[pos] << endl;\n        sum_avg_cn += abs(avg_cn);\n        // total_cn += cp.second;\n    }\n\n    int nalter_bulk = 0;\n    for(auto nc : nalter_chr){\n        assert(nc.second <= 2);\n        nalter_bulk += nc.second;\n    }\n\n    // Compute the proportion of altered positions\n    if(verbose>0){\n        cout << \"Number of CNP in bulk sample is \" << bulk_cnp.size() << endl;\n        cout << \"Number of altered CNP by arm in bulk sample is \" << nalter_bulk << endl;\n    }\n    // double prop_alter = (double) nalter_bulk / (NUM_CHR * 2);\n    cout << nalter_bulk << \"\\t\" << sum_avg_cn << \"\\t\" << ndenovo  << \"\\t\" << naler_pos_l1sample << endl;\n}\n\n\nvoid sim_bulk(int nsample, double min_birth_rate, double max_birth_rate, double death_rate, int min_ncell, int max_ncell, double min_arm_prob, double max_arm_prob, double min_chr_prob, double max_chr_prob, double min_mut_rate, double max_mut_rate, double avg_mut_rate, double max_multi_prob, int skip, int only_mut, unsigned long rseed, string dir_param, string outdir, int genotype_diff = 0, double chr_weight = 1.0, int chr_sel=0, int use_ablen=0, string suffix=\"\", string prefix=\"\", int model = 0, string fitness_vals=\"\", int num_subclone = 0, double tmin = 0, double tmax = 0, double min_clone_freq = 0, double max_clone_freq = 0, int num_clonal_mutation = 0, string file_cmut = \"\", int verbose = 0){\n    pcn bulk_cnp;   // used to compute the average of bulk CNPs\n    pcn bulk_cnc;\n    int ndenovo = 0;\n    // support for moving iostreams was added to GCC 5.1 (not work on cs cluster with default gcc)\n    string outfile = outdir + \"bulk_cn\" + suffix + \".txt\";\n    string outfile_rate = outdir + \"bulk_rate\" + suffix + \".txt\";\n    // ofstream fcn(\" \"), fcn_rate(\" \");\n    ofstream fcn(outfile);\n    ofstream fcn_rate(outfile_rate);\n    vector<string> filenames;\n\n    get_params_file(dir_param, filenames, verbose);\n\n    // Suppress all the output when verbose = -1\n    // if(verbose >= 0){\n        // fcn = ofstream(outfile);\n        // // Output the parameters used for each simulation for double checking\n        // fcn_rate = ofstream(outfile_rate);\n    // }\n\n    string orig_suffix = suffix;\n    double avg_bulk_birth_rate = 0, avg_bulk_mut_rate = 0, avg_bulk_chr_rate = 0, avg_bulk_arm_rate = 0, avg_bulk_mp_rate = 0;\n    double avg_bulk_ncell = 0, avg_bulk_num_mut = 0, avg_bulk_first_mut_time = 0, bulk_first_mut_count = 0;\n\n    for(int i = 0; i < nsample; i++){\n        int ncell = runiform(r, min_ncell, max_ncell);\n\n        vector<double> params;\n        // set_bulk_params_random(params, min_birth_rate, max_birth_rate, min_arm_prob, max_arm_prob, min_chr_prob, max_chr_prob, min_mut_rate, max_mut_rate, avg_mut_rate, max_multi_prob);\n        set_bulk_params(params, filenames, min_birth_rate, max_birth_rate, max_multi_prob, verbose);\n\n        double chr_prob = params[0];\n        double arm_prob = params[1];\n        double multi_prob = params[2];\n        double mut_rate = params[3];\n        double birth_rate = params[4];\n\n        avg_bulk_birth_rate += birth_rate;\n        avg_bulk_mut_rate += mut_rate;\n        avg_bulk_chr_rate += chr_prob;\n        avg_bulk_arm_rate += arm_prob;\n        avg_bulk_mp_rate += multi_prob;\n\n        if(verbose>0){\n            cout << \"Simulating bulk sample \" << i+1 << \" with \" << ncell << \" cells\" << endl;\n            cout << \"\\tBirth rate: \" << birth_rate << endl;\n            cout << \"\\tMutation rate: \" << mut_rate << endl;\n            cout << \"\\tChr-level CNA rate: \" << chr_prob << endl;\n            cout << \"\\tArm-level CNA rate: \" << arm_prob << endl;\n            cout << \"\\tMultipolar spindle (hopeful monster) rate: \" << multi_prob << endl;\n            // cout << \"\\tDeath rate: \" << death_rate << endl;\n            // cout << \"\\tEffective mutation rate (μ/β): \" << cell.mutation_rate / ((cell.birth_rate-cell.death_rate)/cell.birth_rate) << endl;\n        }\n        suffix = orig_suffix + \"_bulk\" + to_string(i+1);\n        Clone s1 = run_sim(birth_rate, death_rate, ncell, arm_prob, chr_prob, multi_prob, skip, only_mut, rseed + i, outdir, genotype_diff, chr_weight, chr_sel, use_ablen, suffix, prefix, model, fitness_vals, num_subclone, tmin, tmax, min_clone_freq, max_clone_freq, num_clonal_mutation, file_cmut, verbose);\n\n        avg_bulk_ncell += ncell;\n        avg_bulk_num_mut += s1.num_novel_mutation;\n        avg_bulk_first_mut_time += s1.time_first_mut;\n        if(s1.time_first_mut==1) bulk_first_mut_count += 1;\n        if(verbose >= 0)\n            fcn_rate << ncell << \"\\t\" << s1.num_novel_mutation << \"\\t\" << s1.time_first_mut << \"\\t\" << birth_rate << \"\\t\" << mut_rate << \"\\t\" << chr_prob << \"\\t\" << arm_prob << \"\\t\" << multi_prob << endl;\n\n\n        // by default, C++ creates an empty map with value for unknown key being 0\n        pcn s1_cnp_split;\n        pcn s1_cnc_split;\n        pcn s1_cnp_merged;\n        pcn s1_cnc_merged;\n\n        // Use s1_cnp_split to merge events on one chromosome across cells in the organoid\n        for(auto cell : s1.curr_cells) {\n            cell.set_obs_cn();\n            for(auto cp : cell.obs_cn_profile){\n                pair<int, int> pos = cp.first;\n                if(cp.second != 0){\n                    if(pos.second==0){  // divide whole chromosome to two arms\n                        pair<int, int> pos1(pos.first, 1);\n                        s1_cnp_split[pos1] += cp.second;\n                        s1_cnc_split[pos1] += 1;\n\n                        pair<int, int> pos2(pos.first, 2);\n                        s1_cnp_split[pos2] += cp.second;\n                        s1_cnc_split[pos2] += 1;\n                    }else{\n                        s1_cnp_split[pos] += cp.second;\n                        s1_cnc_split[pos] += 1;\n                    }\n                }\n            }\n        }\n        assert(s1_cnp_split.size() <= 2 * NUM_CHR);\n\n        // Take the average of each organoid sample to get the CN profiles of a bulk sample\n        for(auto cp : s1_cnp_split){\n            pair<int, int> pos = cp.first;\n            assert(pos.second != 0);\n            // double acn = (double) s1_cnp_split[pos] / s1_cnc_split[pos];\n            double acn = (double) s1_cnp_split[pos] / ncell;        // The detected CN should be based on total number of cells\n            // int racn = int(acn);\n            // if(round_cn==1)\n            int racn = round(acn);\n            // if(i==0){\n            //     cout << i + 1 << \"\\t\" << pos.first + 1 << \"\\t\" << pos.second << \"\\t\" << s1_cnp_split[pos] << \"\\t\" << s1_cnc_split[pos] << \"\\t\" << acn << \"\\t\" << racn << endl;\n            // }\n            if(racn == 0) continue;\n\n            // chr-level event on one chr has been recorded\n            pair<int, int> pos_chr(pos.first, 0);\n            if(s1_cnp_merged.find(pos_chr) != s1_cnp_merged.end()){\n                continue;\n            }\n\n            pair<int, int> pos2;\n            if(pos.second==1){\n                pos2 = make_pair(pos.first, 2);\n            }else{\n                assert(pos.second==2);\n                pos2= make_pair(pos.first, 1);\n            }\n            if(s1_cnp_split.find(pos2) != s1_cnp_split.end()){\n                double acn2 = (double) s1_cnp_split[pos2] / s1_cnc_split[pos2];\n                // int racn2 = int(acn2);\n                // if(round_cn==1){\n                int racn2 = round(acn2);\n                // }\n                if(racn == racn2){\n                    s1_cnp_merged[pos_chr] = racn;\n                    bulk_cnp[pos] += abs(racn);\n                    bulk_cnc[pos] += 1;\n                    bulk_cnp[pos2] += abs(racn);\n                    bulk_cnc[pos2] += 1;\n                    continue;\n                }\n            }\n            s1_cnp_merged[pos] = racn;\n            bulk_cnp[pos] += abs(racn);\n            bulk_cnc[pos] += 1;\n        }\n\n        int nalt = 0;\n        for(auto cp : s1_cnp_merged){\n            pair<int, int> pos = cp.first;\n            int rmcn = s1_cnp_merged[pos];\n            if(rmcn == 0) continue;\n            nalt++;\n            // Output the CN of each bulk sample\n            if(verbose >= 0)\n                fcn << i + 1 << \"\\t\" << pos.first + 1 << \"\\t\" << pos.second << \"\\t\" << rmcn << endl;\n        }\n\n        ndenovo += nalt;\n\n        if(verbose>0) cout << \"Number of altered CNP in sample \" << i+1 << \" is \" << nalt << endl;\n    }  // Simulate a bulk sample with nsample bulk organoid data\n\n    cout << avg_bulk_ncell / nsample << \"\\t\" << avg_bulk_num_mut / nsample << \"\\t\" << avg_bulk_first_mut_time / nsample << \"\\t\" << bulk_first_mut_count << \"\\t\" << avg_bulk_birth_rate / nsample << \"\\t\" << avg_bulk_mut_rate / nsample << \"\\t\" << avg_bulk_chr_rate / nsample << \"\\t\" << avg_bulk_arm_rate / nsample << \"\\t\" << avg_bulk_mp_rate / nsample << endl;\n\n    get_bulk_stat(bulk_cnp, bulk_cnc, nsample, ndenovo, verbose);\n\n    // if(verbose >= 0){\n        fcn.close();\n        fcn_rate.close();\n    // }\n}\n\n\n// TODO: pass parameters\nint main(int argc, char const *argv[]) {\n    Clone clone;\n\n    int mode;\n    int nsample;\n    int min_ncell, max_ncell;\n    double min_mut_rate, max_mut_rate, avg_mut_rate;\n    double min_arm_prob, max_arm_prob;\n    double min_chr_prob, max_chr_prob;\n    double max_multi_prob;\n    double min_birth_rate, max_birth_rate;\n    string dir_param;\n\n    int Nend;\n    double birth_rate, death_rate;\n    double mutation_rate, arm_prob, chr_prob, multi_prob;\n    int multi_nchr;\n    string file_param;\n\n    int model;\n    string fitness_vals;\n    int num_subclone;\n    double tmin, tmax;\n    // Mutation rate per division per genome\n    double min_clone_freq, max_clone_freq;\n    int num_clonal_mutation;\n\n    int chr_sel; // level of selection\n    int genotype_diff;\n    double chr_weight;\n    int use_ablen;\n    int skip; // number of cells to skip when computing division time\n    int only_mut;  // only consider branch ratios when new mutation is introduced\n    string outdir, prefix, suffix; // output\n\n    unsigned long seed;\n\n    string tree_file, file_cmut;\n\n    int verbose;\n\n    namespace po = boost::program_options;\n\n    po::options_description generic(\"Generic options\");\n    generic.add_options()\n      (\"version,v\", \"print version string\")\n      (\"help,h\", \"produce help message\")\n      ;\n\n    po::options_description required(\"Required parameters\");\n    required.add_options()\n      (\"odir,o\", po::value<string>(&outdir)->required()->default_value(\"./\"), \"output directory\")\n       ;\n\n    po::options_description optional(\"Optional parameters\");\n    optional.add_options()\n      (\"mode\", po::value<int>(&mode)->default_value(0), \"mode of simulation. 0: single cell data; 1: bulk data\")\n\n      (\"birth_rate\", po::value<double>(&birth_rate)->default_value(1), \"birth rate\")\n      (\"death_rate\", po::value<double>(&death_rate)->default_value(0), \"death rate\")\n      (\"Nend,e\", po::value<int>(&Nend)->default_value(100), \"size of final cell populations\")\n\n      (\"nsample\", po::value<int>(&nsample)->default_value(100), \"number of bulk samples\")\n      (\"min_ncell\", po::value<int>(&min_ncell)->default_value(100), \"minimum number of cells in a bulk sample\")\n      (\"max_ncell\", po::value<int>(&max_ncell)->default_value(100), \"maximum number of cells in a bulk sample\")\n      (\"min_mut_rate\", po::value<double>(&min_mut_rate)->default_value(0.02), \"minimum CNA rate\")\n      (\"max_mut_rate\", po::value<double>(&max_mut_rate)->default_value(0.2), \"maximum CNA rate\")\n      (\"avg_mut_rate\", po::value<double>(&avg_mut_rate)->default_value(0.1), \"average CNA rate\")\n      (\"min_chr_prob\", po::value<double>(&min_chr_prob)->default_value(0.01), \"minimum chr-level CNA rate\")\n      (\"max_chr_prob\", po::value<double>(&max_chr_prob)->default_value(0.2), \"maximum chr-level CNA rate\")\n      (\"min_arm_prob\", po::value<double>(&min_arm_prob)->default_value(0.02), \"minimum arm-level CNA rate\")\n      (\"max_arm_prob\", po::value<double>(&max_arm_prob)->default_value(0.2), \"maximum arm-level CNA rate\")\n      (\"max_multi_prob\", po::value<double>(&max_multi_prob)->default_value(0.06), \"maximum multiple simultaneous chr-level CNA rate (hopeful monster)\")\n      (\"min_birth_rate\", po::value<double>(&min_birth_rate)->default_value(0.2), \"minimum cell division rate\")\n      (\"max_birth_rate\", po::value<double>(&max_birth_rate)->default_value(0.5), \"maximum cell division rate\")\n      (\"dir_param\", po::value<string>(&dir_param)->default_value(\"\"), \"directory containing posterior distributions of inferred parameters\")\n\n      (\"model\", po::value<int>(&model)->default_value(0), \"model of evolution. 0: neutral; 1: gradual; 2: punctuated; 3: positive\")\n      (\"fitness_vals\", po::value<string>(&fitness_vals)->default_value(\"\"), \"fitness values of mutatants\")\n      (\"chr_sel\", po::value<int>(&chr_sel)->default_value(0), \"level of selection. 0: selection on all CNAs; 1: selection on chr-level CNAs\")\n      (\"genotype_diff\", po::value<int>(&genotype_diff)->default_value(0), \"whether or not to use genotype difference (L1 distance) in simulating selection. 0: no; 1: yes\")\n      (\"chr_weight\", po::value<double>(&chr_weight)->default_value(1.0), \"relative fitness of chr-level CNAs\")\n\n      (\"use_ablen\", po::value<int>(&use_ablen)->default_value(0), \"tree summary statistics. 0: half tree length; 1: vector of all branch lengths\")\n\n      (\"num_subclone,n\", po::value<int>(&num_subclone)->default_value(0), \"number of subclones to simulate\")\n      (\"min_clone_freq\", po::value<double>(&min_clone_freq)->default_value(0), \"the minimal frequency of a subclone\")\n      (\"max_clone_freq\", po::value<double>(&max_clone_freq)->default_value(0), \"the maximal frequency of a subclone\")\n      (\"tmin\", po::value<double>(&tmin)->default_value(0), \"the earliest time that a subclone occurs\")\n      (\"tmax\", po::value<double>(&tmax)->default_value(0), \"the latest time that a subclone occurs\")\n\n      (\"num_clonal_mutation\", po::value<int>(&num_clonal_mutation)->default_value(0), \"number of clonal mutations\")\n      (\"file_cmut\", po::value<string>(&file_cmut)->default_value(\"\"), \"the TSV file which contains clonal CNVs, with three columns (chr, arm, cn)\")\n\n      (\"arm_prob, a\", po::value<double>(&arm_prob)->default_value(0.5), \"arm-level CNA rate per cell division\")\n      (\"chr_prob, c\", po::value<double>(&chr_prob)->default_value(0.5), \"chr-level CNA rate per cell division\")\n      (\"multi_prob, m\", po::value<double>(&multi_prob)->default_value(0), \"multiple simultaneous chr-level CNA rate per cell division\")\n      (\"multi_nchr\", po::value<int>(&multi_nchr)->default_value(16), \"number of chromosomes affected by multipolar division\")\n      (\"file_param\", po::value<string>(&file_param)->default_value(\"\"), \"the file containing posterior distributions of inferred parameters\")\n\n      (\"prefix,p\", po::value<string>(&prefix)->default_value(\"run1\"), \"prefix of output file (it will be sim-data-N if not specified\")\n      (\"suffix,s\", po::value<string>(&suffix)->default_value(\"\"), \"suffix of output file\")\n      (\"skip\", po::value<int>(&skip)->default_value(3), \"number of cells to skip when computing division time\")\n      (\"only_mut\", po::value<int>(&only_mut)->default_value(0), \"when to consider branch ratios (1: only when there are mutations introduced to the node)\")\n      (\"use_grandparent\", po::value<int>(&use_grandparent)->default_value(1), \"whether to check grandparent when computing branch ratios\")\n\n      (\"seed\", po::value<unsigned long>(&seed)->default_value(0), \"seed used for generating random numbers\")\n      (\"verbose\", po::value<int>(&verbose)->default_value(0), \"verbose level (0: default, 1: print information of final cells; 2: print information of all cells)\")\n      ;\n\n    po::options_description cmdline_options;\n    cmdline_options.add(generic).add(required).add(optional);\n    po::variables_map vm;\n\n    try {\n        po::store(po::command_line_parser(argc, argv).options(cmdline_options).run(), vm);\n        if(vm.count(\"help\")){\n            cout << cmdline_options << endl;\n            return 1;\n        }\n        if(vm.count(\"version\")){\n            cout << \"sim_cin [version 0.1], a program to simulate copy number variations along a cell division tree\" << endl;\n            return 1;\n        }\n        po::notify(vm);\n    }\n    catch (const exception& e) {\n          cerr << e.what() << endl;\n          return 1;\n    }\n\n\n    unsigned long rseed = setup_rng(seed);\n\n    if(mode == 0){\n        if(file_param!=\"\"){\n            vector<double> params;\n            set_organoid_params(params, file_param, birth_rate, verbose);\n\n            chr_prob = params[0];\n            arm_prob = params[1];\n            birth_rate = params[2];\n        }\n        run_sim(birth_rate, death_rate, Nend, arm_prob, chr_prob, multi_prob, skip, only_mut, rseed, outdir, genotype_diff, chr_weight, chr_sel, use_ablen, suffix, prefix, model, fitness_vals, num_subclone, tmin, tmax, min_clone_freq, max_clone_freq, num_clonal_mutation, file_cmut, verbose);\n    }else{\n        sim_bulk(nsample, min_birth_rate, max_birth_rate, death_rate, min_ncell, max_ncell, min_arm_prob, max_arm_prob, min_chr_prob, max_chr_prob, min_mut_rate, max_mut_rate, avg_mut_rate, max_multi_prob, skip, only_mut, rseed, dir_param, outdir, genotype_diff, chr_weight, chr_sel, use_ablen, suffix, prefix, model, fitness_vals, num_subclone, tmin, tmax, min_clone_freq, max_clone_freq, num_clonal_mutation, file_cmut, verbose);\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "0181a8db2a6eddb2fe6e834a3a4c6dd3945261a9", "size": 34790, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/sim_cin.cpp", "max_stars_repo_name": "ucl-cssb/CIN_PDO", "max_stars_repo_head_hexsha": "57b06e5aa24797015fc08e25e1163f74b6459d8a", "max_stars_repo_licenses": ["MIT"], "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/sim_cin.cpp", "max_issues_repo_name": "ucl-cssb/CIN_PDO", "max_issues_repo_head_hexsha": "57b06e5aa24797015fc08e25e1163f74b6459d8a", "max_issues_repo_licenses": ["MIT"], "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/sim_cin.cpp", "max_forks_repo_name": "ucl-cssb/CIN_PDO", "max_forks_repo_head_hexsha": "57b06e5aa24797015fc08e25e1163f74b6459d8a", "max_forks_repo_licenses": ["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.6025641026, "max_line_length": 704, "alphanum_fraction": 0.6148031043, "num_tokens": 9053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2951926061713521}}
{"text": "/*! \\file Peridigm_EnergyReleaseDamageModel.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//////////////////////////////////////////////////////////////////////////////////////    \n// Routine developed for Peridigm by\n// DLR Composite Structures and Adaptive Systems\n//                                __/|__\n//                                /_/_/_/  \n//            www.dlr.de/fa/en      |/ DLR\n//////////////////////////////////////////////////////////////////////////////////////    \n// Questions?\n// Christian Willberg  christian.willberg@dlr.de\n// Martin Raedel       martin.raedel@dlr.de\n// https://github.com/PeriDoX/\n//////////////////////////////////////////////////////////////////////////////////////   \n//@HEADER\n\n#include \"Peridigm_EnergyReleaseDamageModel.hpp\"\n#include \"Peridigm_Field.hpp\"\n#include \"material_utilities.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::EnergyReleaseDamageModel::EnergyReleaseDamageModel(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_damageModelFieldId(-1),\nm_planeStrain(false),\nm_planeStress(false),\nm_onlyTension(false),\nm_rot(false),\nm_Thickness(-1),\nm_OMEGA(PeridigmNS::InfluenceFunction::self().getInfluenceFunction()) {\n\tm_rot = false;\n    if (params.isParameter(\"Rot Sym\")) {\n\t\tm_rot = true;\t\n\t\tmaxRad = params.get<double>(\"Rot Sym\");\n\t}\n    if (params.isParameter(\"Critical Energy\")) {\n        m_criticalEnergyTension = params.get<double>(\"Critical Energy Tension\");\n        m_criticalEnergyCompression = params.get<double>(\"Critical Energy Compression\");\n        m_criticalEnergyShear = params.get<double>(\"Critical Energy Shear\");\n          \n    } else {\n        if (params.isParameter(\"Critical Energy Tension\"))\n            m_criticalEnergyTension = params.get<double>(\"Critical Energy Tension\");\n        else\n            m_criticalEnergyTension = -1.0;\n        if (params.isParameter(\"Critical Energy Compression\"))\n            m_criticalEnergyCompression = params.get<double>(\"Critical Energy Compression\");\n        else\n            m_criticalEnergyCompression = -1.0;\n        if (params.isParameter(\"Critical Energy Shear\"))\n            m_criticalEnergyShear = params.get<double>(\"Critical Energy Shear\");\n        else\n            m_criticalEnergyShear = -1.0; \n        m_type = 1;\n        if (params.isParameter(\"Energy Criterion\")) {\n            if (params.get<bool>(\"Energy Criterion\") == true)\n                m_type = 1;\n            }\n            \n        if (params.isParameter(\"Power Law\")) {\n            if (params.get<bool>(\"Power Law\") == true)\n                m_type = 2;\n            }\n            \n        if (params.isParameter(\"Separated\")) {\n            if (params.get<bool>(\"Separated\") == true)\n                m_type = 3;\n            }\n\n    }\n    if(params.isParameter(\"Plane Stress\")){\n        m_planeStress = params.get<bool>(\"Plane Stress\");\n        m_Thickness = params.get<double>(\"Thickness\");\n    }\n    if(params.isParameter(\"Plane Strain\")){\n        m_planeStrain = params.get<bool>(\"Plane Strain\");\n        m_Thickness = params.get<double>(\"Thickness\");\n    }\n    m_pi = 3.14159;\n    m_onlyTension = false;\n    if(params.isParameter(\"Only Tension\")){\n        m_onlyTension = params.get<bool>(\"Only Tension\");\n       \n    }\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(\"Model_Coordinates\");\n    m_coordinatesFieldId = fieldManager.getFieldId(\"Coordinates\");\n    m_volumeFieldId = fieldManager.getFieldId(PeridigmNS::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(PeridigmNS::PeridigmField::ELEMENT, PeridigmNS::PeridigmField::SCALAR, PeridigmNS::PeridigmField::TWO_STEP, \"Damage\");\n    m_bondDamageFieldId = fieldManager.getFieldId(PeridigmNS::PeridigmField::BOND, PeridigmNS::PeridigmField::SCALAR, PeridigmNS::PeridigmField::TWO_STEP, \"Bond_Damage\");\n    m_horizonFieldId = fieldManager.getFieldId(PeridigmNS::PeridigmField::ELEMENT, PeridigmNS::PeridigmField::SCALAR, PeridigmNS::PeridigmField::CONSTANT, \"Horizon\");\n    m_damageModelFieldId = fieldManager.getFieldId(PeridigmNS::PeridigmField::NODE, PeridigmNS::PeridigmField::VECTOR, PeridigmNS::PeridigmField::TWO_STEP, \"Damage_Model_Data\");\n    if(m_applyThermalStrains)\n        m_deltaTemperatureFieldId      = fieldManager.getFieldId(PeridigmField::NODE,    PeridigmField::SCALAR,      PeridigmField::TWO_STEP, \"Temperature_Change\");\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_damageModelFieldId);\n    m_fieldIds.push_back(m_bondDamageFieldId);\n    m_fieldIds.push_back(m_horizonFieldId);\n\n}\n\nPeridigmNS::EnergyReleaseDamageModel::~EnergyReleaseDamageModel() {\n}\n\nvoid\nPeridigmNS::EnergyReleaseDamageModel::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\tdataManager.getData(m_damageModelFieldId, 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::EnergyReleaseDamageModel::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;\n    double *cellVolume, *weightedVolume, *damageModel;\n    double criticalEnergyTension(-1.0), criticalEnergyCompression(-1.0), criticalEnergyShear(-1.0);\n    // for temperature dependencies easy to extent\n    double *deltaTemperature = NULL;\n    if(m_applyThermalStrains)\n        dataManager.getData(m_deltaTemperatureFieldId, PeridigmField::STEP_NP1)->ExtractView(&deltaTemperature);\n    double m_alpha = 0;\n\n    dataManager.getData(m_damageFieldId, PeridigmField::STEP_NP1)->ExtractView(&damage);\n    dataManager.getData(m_modelCoordinatesFieldId, PeridigmField::STEP_NONE)->ExtractView(&x);\n    dataManager.getData(m_coordinatesFieldId, PeridigmField::STEP_NP1)->ExtractView(&y);\n    dataManager.getData(m_weightedVolumeFieldId, PeridigmField::STEP_NONE)->ExtractView(&weightedVolume);\n    dataManager.getData(m_volumeFieldId, PeridigmField::STEP_NONE)->ExtractView(&cellVolume);\n    //////////////////////////////////////////////////////////////\n    // transfer of data is done in ComputeDilation --> PeridigmElastic.cpp\n    //////////////////////////////////////////////////////////////\n    dataManager.getData(m_damageModelFieldId, PeridigmField::STEP_NP1)->ExtractView(&damageModel);\n    dataManager.getData(m_horizonFieldId, PeridigmField::STEP_NONE)->ExtractView(&horizon);\n    ////////////////////////////////////\n    ////////////////////////////////////\n    // transfer of data is done in ComputeDilation --> PeridigmMaterial.cpp\n    dataManager.getData(m_bondDamageFieldId, PeridigmField::STEP_NP1)->ExtractView(&bondDamageNP1);\n    \n\n    ////////////////////////////////////////////////////\n    double trialDamage(0.0);\n    int neighborhoodListIndex(0), bondIndex(0);\n    int nodeId, numNeighbors, neighborID, iID, iNID;\n    double totalDamage, totalVol;\n    double alphaP1 = 0.0, alphaP2 = 0.0, gammaP1 = 0.0, gammaP2 = 0.0, kappaP1 = 0.0, kappaP2 = 0.0;\n    double nodeInitialX[3], nodeCurrentX[3], relativeExtension(0.0);\n    double bondEnergyIsotropic(0.0), bondEnergyDeviatoric(0.0);\n    double omegaP1, omegaP2;\n    double critDev, critIso, critComp;\n    double degradationFactor = 1.0; // Optional parameter if bond should be degradated and not fully destroyed instantaneously \n    double avgHorizon, quadhorizon;\n    double eiP1, eiP2, tiP1, tiP2;\n    double edP1, edP2, tdP1, tdP2;\n    double dilatationP1, dilatationP2;\n    double BulkModP1, BulkModP2;\n    double ShearModP1, ShearModP2;\n    double bondEnergy;\n    \n    //double thickness;\n    //---------------------------\n    // INITIALIZE PROCESS STEP t\n    //---------------------------\n    \n    if (m_criticalEnergyTension > 0.0)\n        criticalEnergyTension = m_criticalEnergyTension;\n    if (m_criticalEnergyCompression > 0.0)\n        criticalEnergyCompression = m_criticalEnergyCompression;\n    if (m_criticalEnergyShear > 0.0)\n        criticalEnergyShear = m_criticalEnergyShear;\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    //temperatur ist in peridigm_ElasticMaterial gegeben\n    for (iID = 0; iID < numOwnedPoints; ++iID) {\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        dilatationP1 = damageModel[3*nodeId];\n        BulkModP1    = damageModel[3*nodeId+1];     // weightedVolume is already included in the variable --> Perdigm_Elastic.cpp;\n        ShearModP1   = damageModel[3*nodeId+2]; // weightedVolume is already included in --> Perdigm_Elastic.cpp;\n        \n        if (m_planeStress==false and m_planeStrain==false){\n          //  c = 3 * K * (*theta) / weightedVol;\n            // kappa = c / (*theta) / gamma / 3 (?) (above eq (7) lammiCJ\n            kappaP1 = 9.0 * BulkModP1;\n            gammaP1 = 1.0;\n            alphaP1 = 15.0 * ShearModP1;\n        }\n        if (m_planeStress==true and m_planeStrain==false){\n            alphaP1 = 8.0 * ShearModP1;\n            kappaP1 = 3.0 * BulkModP1;\n            gammaP1 = 4.0 * ShearModP1 / (3.0 * BulkModP1 + 4.0 * ShearModP1);\n            alphaP1 = 8.0 * ShearModP1;\n        }\n        if (m_planeStrain==true and m_planeStress==false){\n           // c = (12.0*K-4.0*MU) / 9.0 * (*theta) / weightedVol;\n            // kappa = c / (*theta) / gamma / 3 (?) (above eq (7) lammiCJ\n            //kappa = 3*(12.0*K-4.0*MU) / 18.0 * (*theta) / weightedVol;\n            \n            gammaP1 = 2.0/3.0;\n            kappaP1 = 6.0*BulkModP1 - 2.0*ShearModP1;\n            alphaP1 = 8.0*ShearModP1;\n        }\n        for (iNID = 0; iNID < numNeighbors; ++iNID) {\n            \n            trialDamage = 0.0;\n            neighborID = neighborhoodList[neighborhoodListIndex++];\n            \n            double zeta = \n            distance(nodeInitialX[0], nodeInitialX[1], nodeInitialX[2],\n                 x[neighborID*3], x[neighborID*3+1], x[neighborID*3+2]);\n\n            double dY = \n            distance(nodeCurrentX[0], nodeCurrentX[1], nodeCurrentX[2],\n                 y[neighborID*3], y[neighborID*3+1], y[neighborID*3+2]);\n \n            relativeExtension = (dY - zeta)/zeta;    \n             // the direction switches between both bonds. This results in a switch of the forces\n             // as well. Therefore, all forces and bond deformations are normalized.\n            double eP = dY - zeta;\n            if(deltaTemperature)\n              eP -= 0.5 * m_alpha*(deltaTemperature[nodeId] + deltaTemperature[neighborID])*zeta;\n            \n            \n            // the average horizon is taken, if multiple horizons are used\n            dilatationP2 = damageModel[3*neighborID];\n            BulkModP2    = damageModel[3*neighborID+1]; // weightedVolume is already included in the variable --> Perdigm_Elastic.cpp;\n            ShearModP2   = damageModel[3*neighborID+2]; // weightedVolume is already included in --> Perdigm_Elastic.cpp;\n\t\t\t\n            \n            \n            \n            if (m_planeStress){\n              //  c = 4.0*K*MU/(3.0*K+4.0*MU) * (*theta) / weightedVol;\n                // kappa = c / (*theta) / gamma / 3 (?) (above eq (7) lammiCJ\n                kappaP2 = 3.0 * BulkModP2;\n                gammaP2 = 4.0 * ShearModP2 / (3.0 * BulkModP2 + 4.0 * ShearModP2);\n                alphaP2 = 8.0 * ShearModP2;\n            }\n            if (m_planeStrain){\n               // c = (12.0*K-4.0*MU) / 9.0 * (*theta) / weightedVol;\n                // kappa = c / (*theta) / gamma / 3 (?) (above eq (7) lammiCJ\n                //kappa = 3*(12.0*K-4.0*MU) / 18.0 * (*theta) / weightedVol;\n                \n                gammaP2 = 2.0/3.0;\n                kappaP2 =(12.0*BulkModP2 - 4.0*ShearModP2) / 3.0 / gammaP2;\n                alphaP2 = 8.0 * ShearModP2;\n                \n            }\n            if (m_planeStress==false and m_planeStrain==false){\n              //  c = 3 * K * (*theta) / weightedVol;\n                // kappa = c / (*theta) / gamma / 3 (?) (above eq (7) lammiCJ\n                kappaP2 = 9.0 * BulkModP2;\n                gammaP2 = 1.0;\n                alphaP2 = 15.0 * ShearModP2 ;\n            }\n\n            omegaP1 = MATERIAL_EVALUATION::scalarInfluenceFunction(zeta, horizon[nodeId]); \n            omegaP2 = MATERIAL_EVALUATION::scalarInfluenceFunction(zeta, horizon[neighborID]); \n            avgHorizon = 0.5*(horizon[nodeId]+horizon[neighborID]);\n            \n            if(m_planeStrain or m_planeStress){ // m_Thickness is in the volume included (tbd to guarantee this)\n            //factor = 16.0 / 5.0 / weightedVol * sqrt(M_PI / 3.0 * pow(horizon,5)); // Simplified with Mathematica\n                quadhorizon =  3.0 /(m_Thickness * pow(horizon[neighborID],3) );\n\t\t\t\tif (m_rot){\n\t\t\t\t\tdouble rad = nodeInitialX[0]*nodeInitialX[0]/maxRad/maxRad;\n\t\t\t\t\t//if (rad == 0) rad = 1e-10;\n\t\t\t\t\tquadhorizon = quadhorizon*(1+rad);\n\t\t\t\t}\n            }\n            else {\n                //yieldValue = 25.0 * yieldStress * yieldStress / 8 / M_PI / pow(horizon,5);\n                //factor = sqrt(75.0 / 4 / M_PI / pow(horizon,5));        // equation (51) MitchelJA_2011; 1/2 is not needed \n                //factor = 15.0 / weightedVol * sqrt(4.0 / 75.0 * M_PI * pow(horizon,5));        // equation (51) MitchelJA_2011; 1/2 is not needed \n                \n                quadhorizon =  8.0 /( m_pi * pow(avgHorizon, 4) );\n            }\n            \n\n\n            eiP1 = gammaP1 * dilatationP1 * zeta / 3.0;\n            eiP2 = gammaP2 * dilatationP2 * zeta / 3.0;\n            tiP1 = kappaP1*eiP1;\n            tiP2 = kappaP2*eiP2;\n            \n\t\t\t\n            edP1 = eP - eiP1;\n            edP2 = eP - eiP2;\n            tdP1 = omegaP1*alphaP1*edP1;\n            tdP2 = omegaP2*alphaP2*edP2;\n \n            bondEnergyIsotropic  = (1.0 - bondDamageNP1[bondIndex])*(sqrt(tiP1*eiP1*tiP1*eiP1) + sqrt(tiP2*eiP2*tiP2*eiP2)); \n            bondEnergyDeviatoric = (1.0 - bondDamageNP1[bondIndex])*(sqrt(tdP1*edP1*tdP1*edP1) + sqrt(tdP2*edP2*tdP2*edP2));\n\n            critIso = 0.0;\n            if (relativeExtension>0&&criticalEnergyTension != -1.0){\n               critIso = (bondEnergyIsotropic/(criticalEnergyTension*quadhorizon));\n            }\n            critDev = 0.0;\n            \n            if (criticalEnergyShear != -1.0){\n               critDev = (bondEnergyDeviatoric/(criticalEnergyShear*quadhorizon));\n            }\n            critComp = 0.0;\n            if (relativeExtension < 0.0 && criticalEnergyCompression != -1.0){\n                critComp = (bondEnergyIsotropic/(criticalEnergyCompression*quadhorizon));\n                critIso = 0.0;\n            }\n            if (m_type == 1){ // Energy Criterion by Foster et al.(2009) Journal for Multiscale Computational Engineering;\n                bondEnergy = abs(abs(tdP1+tiP1) + abs(tdP2 + tiP2))*eP;\n                \n                //bondEnergy = abs(damageModel[3*nodeId]-damageModel[3*neighborID])*zeta / *m;\n                \n                critIso = bondEnergy/(criticalEnergyTension*quadhorizon);\n                \n                if (m_criticalEnergyTension > 0.0 && critIso > 1.0 ) {\n\t\t\t\t\t//std::cout<<BulkModP1<< \" \"<< weightedVolume[nodeId]<<\" \"<< ShearModP1<< \" \"<< ShearModP2<<\" \"<< BulkModP2<<std::endl;\n                    trialDamage = bondDamageNP1[bondIndex] + degradationFactor;\n                } \n            }\n            \n            if (m_type == 2){// Power Law\n    \n                if (m_criticalEnergyTension > 0.0 &&critIso*critIso + critDev*critDev + critComp*critComp > 1.0) {\n                   trialDamage = bondDamageNP1[bondIndex] + degradationFactor;\n                }\n            }\n            //std::cout<< m_type<< \" \"<< std::endl;\n            if (m_type == 3){ // Separated\n                if (m_criticalEnergyTension > 0.0  &&critIso > 1.0) {\n                   trialDamage = bondDamageNP1[bondIndex] + degradationFactor;\n                }\n                if (criticalEnergyShear > 0.0 && critDev > 1.0) {\n                   trialDamage = bondDamageNP1[bondIndex] + degradationFactor;\n                   \n                } \n                if (m_criticalEnergyCompression > 0.0  && critComp > 1.0) {\n                   trialDamage = bondDamageNP1[bondIndex] + degradationFactor;\n                }\n            }\n            if (m_onlyTension == true){\n                if (relativeExtension<0)trialDamage = 0;\n            }\n                    \n\n            if (trialDamage > bondDamageNP1[bondIndex]) {\n               if (trialDamage>1)trialDamage = 1;\n                            bondDamageNP1[bondIndex] = trialDamage;\n                    }    \n\n            bondIndex += 1;\n\n            }\n\n        }\n    \n\n    //  Update the element damage (percent of bonds broken)\n\n    neighborhoodListIndex = 0;\n    bondIndex = 0;\n    for (iID = 0; iID < numOwnedPoints; ++iID) {\n        nodeId = ownedIDs[iID];\n        numNeighbors = neighborhoodList[neighborhoodListIndex++];\n        //neighborhoodListIndex += numNeighbors;\n        damageModel[3*nodeId] = 0.0;\n        damageModel[3*nodeId+1] = 0.0;\n        damageModel[3*nodeId+2] = 0.0;\n        totalDamage = 0.0;\n        totalVol = 0.0;\n        for (iNID = 0; iNID < numNeighbors; ++iNID) {\n            \n            neighborID = neighborhoodList[neighborhoodListIndex++];\n            // must be zero to avoid synchronization errors\n            damageModel[3*neighborID] = 0.0;\n            damageModel[3*neighborID+1] = 0.0;\n            damageModel[3*neighborID+2] = 0.0;\n            \n            totalDamage += bondDamageNP1[bondIndex]*weightedVolume[nodeId];\n            totalVol += weightedVolume[nodeId];\n            bondIndex += 1;\n        }\n        if (numNeighbors > 0)\n            totalDamage /= (totalVol);\n        else\n            totalDamage = 0.0;\n        damage[nodeId] = totalDamage;\n    }\n}\n\n\n", "meta": {"hexsha": "957380dd53e96c3ce2f438bbb4af81ed74a855de", "size": 22257, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Peridigm/Code/Anisotropic_Material/damage/Peridigm_EnergyReleaseDamageModel.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_EnergyReleaseDamageModel.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_EnergyReleaseDamageModel.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": 44.2485089463, "max_line_length": 177, "alphanum_fraction": 0.6006649593, "num_tokens": 5938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2951926061713521}}
{"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#ifndef MTL_SET_TO_0_INCLUDE\n#define MTL_SET_TO_0_INCLUDE\n\n#include <algorithm>\n#include <cassert>\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/utility/enable_if.hpp>\n#include <boost/numeric/mtl/utility/ashape.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/utility/category.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\nnamespace mtl {\n\n    // Forward declarations\n    namespace matrix { \n\ttemplate <typename Coll> \n\ttypename mtl::traits::enable_if_matrix<Coll>::type \n\tset_to_zero(Coll& collection); \n    }\n    namespace vector { \n\ttemplate <typename Coll> \n\ttypename mtl::traits::enable_if_vector<Coll>::type\n\tset_to_zero(Coll& collection); \n    }\n\n    namespace impl {\n\n\ttemplate <typename Coll>\n\tvoid set_to_zero(Coll& collection, tag::vector_ref, ashape::scal)\n\t{\n\t    using math::zero;\n\t    typename Collection<Coll>::value_type  ref, my_zero(zero(ref));\n\t    for (typename Collection<Coll>::size_type i= 0; i < size(collection); ++i)\n\t\tcollection[i]= my_zero;\n\t}\n\n\ttemplate <typename Coll>\n\tvoid set_to_zero(Coll& collection, tag::contiguous_dense, ashape::scal)\n\t{\n\t    using math::zero;\n\t    typename Collection<Coll>::value_type  ref, my_zero(zero(ref));\n\n\t    std::fill(collection.elements(), collection.elements()+collection.used_memory(), my_zero);\n\t}\n\n\ttemplate <typename Coll>\n\tvoid set_to_zero(Coll& collection, tag::std_vector, ashape::scal)\n\t{\n\t    using math::zero;\n\t    typename Collection<Coll>::value_type  ref, my_zero(zero(ref));\n\n\t    std::fill(collection.begin(), collection.end(), my_zero);\n\t}\n\n\ttemplate <typename Matrix>\n\tvoid set_to_zero(Matrix& matrix, tag::morton_dense, ashape::scal)\n\t{\n\t    using math::zero;\n\t    typename Collection<Matrix>::value_type  ref, my_zero(zero(ref));\n\t    // maybe faster to do it straight\n\t    // if performance problems we'll take care of the holes\n\t    // std::cout << \"set_to_zero: used_memory = \" << matrix.used_memory() << \"\\n\";\n\t    std::fill(matrix.elements(), matrix.elements() + matrix.used_memory(), my_zero);\n\n#if 0\n\t    for (int i= 0; i < matrix.num_rows(); i++)\n\t      for (int j= 0; j < matrix.num_cols(); j++)\n\t\tmatrix[i][j]= my_zero;\n#endif\n\t}\t\n\n\t// For nested collection, we must consider the dimensions of the elements\n\t// (Morton-order is included in contiguous_dense)\n\ttemplate <typename Coll>\n\tvoid set_to_zero(Coll& collection, tag::contiguous_dense, ashape::nonscal)\n\t{\n\t    for (typename Collection<Coll>::size_type i= 0; i < collection.used_memory(); ++i)\n\t\tset_to_zero(collection.value_n(i));\n\t}\n\n\n\t// Is approbriate for all sparse matrices and vectors (including collections as value_type)\n\ttemplate <typename Coll>\n\tvoid set_to_zero(Coll& collection, tag::sparse, ashape::universe)\n\t{\n\t    collection.make_empty();\n\t}\n\t\n\t// Special treatment for multi_vector\n\ttemplate <typename Coll>\n\tvoid set_to_zero(Coll& collection, tag::multi_vector, ashape::universe)\n\t{\n\t    using mtl::vector::set_to_zero;\n\t    for (typename Collection<Coll>::size_type i= 0; i < num_cols(collection); ++i)\n\t\tset_to_zero(collection.vector(i));\n\t}\t\n\t\n\ttemplate <typename Coll>\n\tbool has_strided_data(const Coll&) \n\t{ return false; }\n\n\ttemplate <typename Value, typename Parameter>\n\tbool has_strided_data(const matrix::dense2D<Value, Parameter>& A)\n\t{ return A.has_strided_data(); }\n\n\t\n\ttemplate <typename Matrix>\n\tvoid naive_set_to_zero(Matrix& A, tag::matrix, tag::dense)\n\t{\n\t    using math::zero;\n\t    typename Collection<Matrix>::value_type  ref, my_zero(zero(ref));\n\n\t    for (unsigned i= 0; i < num_rows(A); i++)\n\t\tfor (unsigned j= 0; j < num_cols(A); j++)\n\t\t    A[i][j]= my_zero;\n\t}\n\n\ttemplate <typename Matrix>\n\tvoid naive_set_to_zero(Matrix&, tag::matrix, tag::sparse)\n\t{\n\t    assert(true); // must not be called\n\t}\n\n    }\n\n\nnamespace matrix {\n\n    /// Sets all values of a collection to 0\n    /// More spefically the defined multiplicative identity element\n    template <typename Coll>\n    typename mtl::traits::enable_if_matrix<Coll>::type\n    set_to_zero(Coll& collection)\n    {\n\tusing mtl::traits::category;\n\tvampir_trace<3031> tracer;\n\ttypedef typename Collection<Coll>::value_type value_type;\n\tif (mtl::impl::has_strided_data(collection))\n\t    mtl::impl::naive_set_to_zero(collection, typename category<Coll>::type(), typename category<Coll>::type());\n\telse\n\t    mtl::impl::set_to_zero(collection, typename category<Coll>::type(),typename ashape::ashape<value_type>::type()); // 2. ashape ???\n    }   \n}\n\nnamespace vector {\n\n    /// Sets all values of a collection to 0\n    /// More spefically the defined multiplicative identity element\n    template <typename Coll>\n    typename mtl::traits::enable_if_vector<Coll>::type\n    set_to_zero(Coll& collection)\n    {\n\tusing mtl::traits::category;\n\tvampir_trace<2029> tracer;\n\ttypedef typename Collection<Coll>::value_type value_type;\n\tmtl::impl::set_to_zero(collection, typename category<Coll>::type(),typename ashape::ashape<value_type>::type());\n    }\n\n}\n\n} // namespace mtl\n\n#endif // MTL_SET_TO_0_INCLUDE\n", "meta": {"hexsha": "0ae79e6631083857a130086fc6a0a1a5adcd7a86", "size": 5545, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/operation/set_to_zero.hpp", "max_stars_repo_name": "spraetor/amdis2", "max_stars_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T16:44:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T07:26:27.000Z", "max_issues_repo_path": "lib/mtl4/boost/numeric/mtl/operation/set_to_zero.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/mtl4/boost/numeric/mtl/operation/set_to_zero.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9776536313, "max_line_length": 134, "alphanum_fraction": 0.7067628494, "num_tokens": 1427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.2951926061713521}}
{"text": "/*******************************************************************************\n * This file is part of KaHyPar.\n *\n * Copyright (C) 2019 Sebastian Schlag <sebastian.schlag@kit.edu>\n *\n * KaHyPar 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 * KaHyPar 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 KaHyPar.  If not, see <http://www.gnu.org/licenses/>.\n *\n******************************************************************************/\n\n#include <boost/algorithm/string/predicate.hpp>\n\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <string>\n\n#include \"kahypar/definitions.h\"\n#include \"kahypar/io/hypergraph_io.h\"\n#include \"kahypar/io/partitioning_output.h\"\n#include \"kahypar/macros.h\"\n#include \"kahypar/partition/context.h\"\n#include \"kahypar/partition/metrics.h\"\n#include \"tools/mtx_to_hgr_conversion.h\"\n\nusing namespace kahypar;\nusing mtxconversion::Matrix;\n\nstatic inline double imb(const Hypergraph& hypergraph, const PartitionID k) {\n  HypernodeWeight max_weight = hypergraph.partWeight(0);\n  for (PartitionID i = 1; i != k; ++i) {\n    max_weight = std::max(max_weight, hypergraph.partWeight(i));\n  }\n  return static_cast<double>(max_weight) /\n         ceil(static_cast<double>(hypergraph.totalWeight()) / k) - 1.0;\n}\n\nstatic inline Hypergraph createHypergraphFromMtx(const std::string& filename,\n                                                  const PartitionID num_parts) {\n  // we use the row-net model\n  Matrix matrix = mtxconversion::readMatrix(filename);\n  HypernodeID num_hypernodes = matrix.info.num_columns;\n  HyperedgeID num_hyperedges = matrix.info.num_rows;\n  HyperedgeIndexVector index_vector;\n  HyperedgeVector edge_vector;\n\n  index_vector.push_back(edge_vector.size());\n  for (const auto& hyperedge : matrix.data.entries) {\n    if (hyperedge.size() != 0) {\n      for (const auto& pin : hyperedge) {\n        edge_vector.push_back(pin);\n      }\n      index_vector.push_back(edge_vector.size());\n    }\n  }\n  ALWAYS_ASSERT(matrix.info.object == mtxconversion::MatrixObjectType::WEIGHTED_MATRIX\n                || matrix.data.weights.empty(), \"Weights not allowed\");\n  return Hypergraph(num_hypernodes, num_hyperedges, index_vector, edge_vector,\n                    num_parts, HyperedgeWeightVector{ }, matrix.data.weights);\n}\n\nint main(int argc, char* argv[]) {\n  if (argc != 2 && argc != 3) {\n    std::cout << \"No .hgr file specified\" << std::endl;\n    std::cout << \"Usage: EvaluateMondriaanPartiton <.hgr/.mtx> <partition file>\" << std::endl;\n    exit(0);\n  }\n  const std::string hypergraph_filename(argv[1]);\n  Hypergraph hypergraph;\n  if (boost::algorithm::ends_with(hypergraph_filename, \".mtx\")) {\n    hypergraph = createHypergraphFromMtx(hypergraph_filename, 2);\n  } else {\n    hypergraph = io::createHypergraphFromFile(hypergraph_filename, 2);\n  }\n\n  PartitionID max_part = 1;\n  std::vector<PartitionID> partition(hypergraph.initialNumNodes(), -1);\n  if (argc == 3) {\n    const std::string partition_filename(argv[2]);\n    std::cout << \"Reading partition file: \" << partition_filename << std::endl;\n    std::ifstream file(partition_filename);\n    if (file) {\n      HypernodeID vertex = -1;\n      PartitionID part = -1;\n      // header\n      file >> vertex >> max_part;\n      ALWAYS_ASSERT(vertex == hypergraph.initialNumNodes());\n      while (file >> vertex >> part) {\n        // one-based\n        partition[vertex - 1] = part - 1;\n      }\n      file.close();\n    } else {\n      std::cerr << \"Error: File not found: \" << std::endl;\n    }\n    ALWAYS_ASSERT(std::none_of(std::begin(partition), std::end(partition),\n                               [](PartitionID i) {\n      return i == -1;\n    }));\n  }\n\n  if (partition.size() != 0 && partition.size() != hypergraph.initialNumNodes()) {\n    std::cout << \"partition file has incorrect size. Exiting.\" << std::endl;\n    exit(-1);\n  }\n\n  LOG << V(max_part);\n  hypergraph.changeK(max_part);\n\n  for (size_t index = 0; index < partition.size(); ++index) {\n    hypergraph.setNodePart(index, partition[index]);\n  }\n\n  Context context;\n  context.partition.k = max_part;\n\n  for (PartitionID i = 0; i < context.partition.k; ++i) {\n    LOG << i << V(hypergraph.partSize(i)) << V(hypergraph.partWeight(i));\n  }\n\n  std::cout << \"***********************\" << hypergraph.k()\n            << \"-way Partition Result************************\" << std::endl;\n  std::cout << \"cut=\" << metrics::hyperedgeCut(hypergraph) << std::endl;\n  std::cout << \"soed=\" << metrics::soed(hypergraph) << std::endl;\n  std::cout << \"km1= \" << metrics::km1(hypergraph) << std::endl;\n  std::cout << \"absorption= \" << metrics::absorption(hypergraph) << std::endl;\n  std::cout << \"imbalance= \" << imb(hypergraph, context.partition.k)\n            << std::endl;\n\n  std::cout << \"RESULT\"\n            << \" graph=\" << hypergraph_filename.substr(hypergraph_filename.find_last_of('/') + 1)\n            << \" k=\" << context.partition.k\n            << \" imbalance=\" << imb(hypergraph, context.partition.k)\n            << \" cut=\" << metrics::hyperedgeCut(hypergraph)\n            << \" soed=\" << metrics::soed(hypergraph)\n            << \" km1=\" << metrics::km1(hypergraph) << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "105ec3f4eaadd59add2f10dac4494081a0d55584", "size": 5597, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/kahypar/tools/evaluate_mondriaan_partition.cc", "max_stars_repo_name": "sjkelly/LSOracle", "max_stars_repo_head_hexsha": "21688c5d542740dfc8577349fa615ee655acd92c", "max_stars_repo_licenses": ["MIT"], "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/kahypar/tools/evaluate_mondriaan_partition.cc", "max_issues_repo_name": "sjkelly/LSOracle", "max_issues_repo_head_hexsha": "21688c5d542740dfc8577349fa615ee655acd92c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-26T22:09:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-26T22:09:49.000Z", "max_forks_repo_path": "lib/kahypar/tools/evaluate_mondriaan_partition.cc", "max_forks_repo_name": "sjkelly/LSOracle", "max_forks_repo_head_hexsha": "21688c5d542740dfc8577349fa615ee655acd92c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-26T14:46:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-09T11:32:09.000Z", "avg_line_length": 37.3133333333, "max_line_length": 97, "alphanum_fraction": 0.6287296766, "num_tokens": 1392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2949061911095047}}
{"text": "#pragma once\n\n#include <iostream>\n\n#include <Eigen/Geometry>\n\n#include <ipc/utils/eigen_ext.hpp>\n#include <ipc/utils/logger.hpp>\n\nnamespace ipc {\n\ntemplate <typename DerivedP, typename DerivedE0, typename DerivedE1>\nPointEdgeDistanceType point_edge_distance_type(\n    const Eigen::MatrixBase<DerivedP>& p,\n    const Eigen::MatrixBase<DerivedE0>& e0,\n    const Eigen::MatrixBase<DerivedE1>& e1)\n{\n    assert(p.size() == 2 || p.size() == 3);\n    assert(e0.size() == 2 || e0.size() == 3);\n    assert(e1.size() == 2 || e1.size() == 3);\n\n    const auto e = e1 - e0;\n    const auto e_length_sqr = e.squaredNorm();\n    if (e_length_sqr == 0) {\n        IPC_LOG(warn(\"Degenerate edge in point_edge_distance_type!\"));\n        return PointEdgeDistanceType::P_E0; // WARNING: use arbitrary end-point\n    }\n    auto ratio = e.dot(p - e0) / e_length_sqr;\n    if (ratio < 0) {\n        return PointEdgeDistanceType::P_E0; // PP (p-e0)\n    } else if (ratio > 1) {\n        return PointEdgeDistanceType::P_E1; // PP (p-e1)\n    } else {\n        return PointEdgeDistanceType::P_E; // PE\n    }\n}\n\ntemplate <\n    typename DerivedP,\n    typename DerivedT0,\n    typename DerivedT1,\n    typename DerivedT2>\nPointTriangleDistanceType point_triangle_distance_type(\n    const Eigen::MatrixBase<DerivedP>& p,\n    const Eigen::MatrixBase<DerivedT0>& t0,\n    const Eigen::MatrixBase<DerivedT1>& t1,\n    const Eigen::MatrixBase<DerivedT2>& t2)\n{\n    typedef typename DerivedP::Scalar T;\n\n    assert(p.size() == 3);\n    assert(t0.size() == 3);\n    assert(t1.size() == 3);\n    assert(t2.size() == 3);\n\n    Eigen::Matrix<T, 2, 3> basis;\n    basis.row(0) = t1 - t0;\n    basis.row(1) = t2 - t0;\n\n    auto normal = cross(basis.row(0), basis.row(1));\n\n    Eigen::Matrix<T, 2, 3> param;\n\n    basis.row(1) = cross(basis.row(0), normal);\n    param.col(0) =\n        (basis * basis.transpose()).ldlt().solve(basis * Vector3<T>(p - t0));\n    if (param(0, 0) > 0.0 && param(0, 0) < 1.0 && param(1, 0) >= 0.0) {\n        return PointTriangleDistanceType::P_E0; // edge 0 is the closest\n    } else {\n        basis.row(0) = t2 - t1;\n        basis.row(1) = cross(basis.row(0), normal);\n        param.col(1) = (basis * basis.transpose())\n                           .ldlt()\n                           .solve(basis * Vector3<T>(p - t1));\n        if (param(0, 1) > 0.0 && param(0, 1) < 1.0 && param(1, 1) >= 0.0) {\n            return PointTriangleDistanceType::P_E1; // edge 1 is the closest\n        } else {\n            basis.row(0) = t0 - t2;\n\n            basis.row(1) = cross(basis.row(0), normal);\n            param.col(2) = (basis * basis.transpose())\n                               .ldlt()\n                               .solve(basis * Vector3<T>(p - t2));\n            if (param(0, 2) > 0.0 && param(0, 2) < 1.0 && param(1, 2) >= 0.0) {\n                return PointTriangleDistanceType::P_E2; // edge 2 is the closest\n            } else {\n                if (param(0, 0) <= 0.0 && param(0, 2) >= 1.0) {\n                    // vertex 0 is the closest\n                    return PointTriangleDistanceType::P_T0;\n                } else if (param(0, 1) <= 0.0 && param(0, 0) >= 1.0) {\n                    // vertex 1 is the closest\n                    return PointTriangleDistanceType::P_T1;\n                } else if (param(0, 2) <= 0.0 && param(0, 1) >= 1.0) {\n                    // vertex 2 is the closest\n                    return PointTriangleDistanceType::P_T2;\n                } else {\n                    return PointTriangleDistanceType::P_T;\n                }\n            }\n        }\n    }\n}\n\n// A more robust implementation of http://geomalgorithms.com/a07-_distance.html\ntemplate <\n    typename DerivedEA0,\n    typename DerivedEA1,\n    typename DerivedEB0,\n    typename DerivedEB1>\nEdgeEdgeDistanceType edge_edge_distance_type(\n    const Eigen::MatrixBase<DerivedEA0>& ea0,\n    const Eigen::MatrixBase<DerivedEA1>& ea1,\n    const Eigen::MatrixBase<DerivedEB0>& eb0,\n    const Eigen::MatrixBase<DerivedEB1>& eb1)\n{\n    assert(ea0.size() == 3);\n    assert(ea1.size() == 3);\n    assert(eb0.size() == 3);\n    assert(eb1.size() == 3);\n\n    auto u = ea1 - ea0;\n    auto v = eb1 - eb0;\n    auto w = ea0 - eb0;\n\n    auto a = u.squaredNorm(); // always >= 0\n    auto b = u.dot(v);\n    auto c = v.squaredNorm(); // always >= 0\n    auto d = u.dot(w);\n    auto e = v.dot(w);\n    auto D = a * c - b * b; // always >= 0\n    auto tD = D;            // tc = tN / tD, default tD = D >= 0\n\n    EdgeEdgeDistanceType defaultCase = EdgeEdgeDistanceType::EA_EB;\n\n    // compute the line parameters of the two closest points\n    auto sN = (b * e - c * d);\n    decltype(sN) tN;\n    if (sN <= 0.0) { // sc < 0 => the s=0 edge is visible\n        tN = e;\n        tD = c;\n        defaultCase = EdgeEdgeDistanceType::EA0_EB;\n    } else if (sN >= D) { // sc > 1  => the s=1 edge is visible\n        tN = e + b;\n        tD = c;\n        defaultCase = EdgeEdgeDistanceType::EA1_EB;\n    } else {\n        tN = (a * e - b * d);\n        if (tN > 0.0 && tN < tD\n            && (cross(u, v).squaredNorm() < 1.0e-20 * a * c)) {\n            // avoid nearly parallel EE\n            if (sN < D / 2) {\n                tN = e;\n                tD = c;\n                defaultCase = EdgeEdgeDistanceType::EA0_EB;\n            } else {\n                tN = e + b;\n                tD = c;\n                defaultCase = EdgeEdgeDistanceType::EA1_EB;\n            }\n        }\n        // else defaultCase stays EdgeEdgeDistanceType::EA_EB\n    }\n\n    if (tN <= 0.0) { // tc < 0 => the t=0 edge is visible\n        // recompute sc for this edge\n        if (-d <= 0.0) {\n            return EdgeEdgeDistanceType::EA0_EB0;\n        } else if (-d >= a) {\n            return EdgeEdgeDistanceType::EA1_EB0;\n        } else {\n            return EdgeEdgeDistanceType::EA_EB0;\n        }\n    } else if (tN >= tD) { // tc > 1  => the t=1 edge is visible\n        // recompute sc for this edge\n        if ((-d + b) <= 0.0) {\n            return EdgeEdgeDistanceType::EA0_EB1;\n        } else if ((-d + b) >= a) {\n            return EdgeEdgeDistanceType::EA1_EB1;\n        } else {\n            return EdgeEdgeDistanceType::EA_EB1;\n        }\n    }\n\n    return defaultCase;\n}\n\n} // namespace ipc\n", "meta": {"hexsha": "4a2cf12724cfb87cd04c443177169bad975cf7cf", "size": 6177, "ext": "tpp", "lang": "C++", "max_stars_repo_path": "src/distance/distance_type.tpp", "max_stars_repo_name": "ipc-sim/ipc-toolk", "max_stars_repo_head_hexsha": "81873d0288810e30166d871419da4104329860e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2020-08-04T21:08:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T02:24:31.000Z", "max_issues_repo_path": "src/distance/distance_type.tpp", "max_issues_repo_name": "dbelgrod/ipc-toolkit", "max_issues_repo_head_hexsha": "0b7ca9b5f867db63bd68dd02ce54a9d00b0fc337", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-10-12T05:54:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T18:39:30.000Z", "max_forks_repo_path": "src/distance/distance_type.tpp", "max_forks_repo_name": "dbelgrod/ipc-toolkit", "max_forks_repo_head_hexsha": "0b7ca9b5f867db63bd68dd02ce54a9d00b0fc337", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-11-26T12:47:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T04:55:49.000Z", "avg_line_length": 32.8563829787, "max_line_length": 80, "alphanum_fraction": 0.5300307593, "num_tokens": 1887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499941, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.29490619110950467}}
{"text": "\n//把kitti的groundtru格式类型的pose(时间戳 4X3的转移矩阵[去掉了0 0 0 1]) 转化为 Tum数据集类型的数据( 'timestamp tx ty tz qx qy qz qw' )\n//在转化的过程中经过一个对pose进行的一个变换transpose*pose*transposeInv 保存 , 详情见 int loadKittiPoses(const string &  file_name, vector<Eigen::Matrix4d> & poses, Eigen::Matrix4d &transpose);\n\n\n#include <iostream>\n#include <iomanip> //要用到格式控制符\n#include <fstream>\n#include <boost/program_options.hpp>\n\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <Eigen/Geometry>\n#include <Eigen/Core>\n#include <boost/format.hpp>  // for formating strings\n\n\n#include <vector>\n#include <string>\n\n#include <sstream>\n#include <boost/filesystem.hpp>\n#include <algorithm>\n#include <iterator>\n#include <math.h>\n\n\n\n\nusing namespace std;\n\n\nint loadKittiPoses(const string & file_name, vector<Eigen::Matrix4d> &poses) ;\nint loadKittiPoses(const string &  file_name, vector<Eigen::Matrix4d> & poses, Eigen::Matrix4d &transpose);\nint loadKittiTimes( const string & file_name,  vector<double> & timestamps);\nint convert(  vector<Eigen::Matrix4d> & poses,  vector<double> & timestamps,  const string & filename);\n\n\nint main( int argc, char** argv )\n{\n\n    if (argc != 4)\n    {\n        //example: ./project    kitti类型的pose.txt   kitti时间戳文件夹   要输出的文件名\n        cerr << endl << \"Usage: ./project    kittiPoseXX.txt     kittiTimeXX.txt    tumOutxx.txt \" << endl;\n        return 1;\n    }\n\n    string kittipath =  std::string(argv[1]);\n    string kittTimepath =  std::string(argv[2]);\n    string tumFileName = std::string(argv[3]);\n    cout << kittipath << endl;\n    cout << kittTimepath << endl;\n    cout << tumFileName << endl;\n\n    vector<Eigen::Matrix4d> poses;         // 相机位姿\n    vector<double>  timestamps;// 时间戳\n\n\n     Eigen::Matrix4d T_rectC2_to_rectC0;\n     T_rectC2_to_rectC0 << 1.0000, 0.0000,   -0.0000,   -0.0595,\n             0.0000,    1.0000,    0.0000,    0.0015,\n             -0.0000,   -0.0000,    1.0000,   -0.0038,\n             0,         0,         0,    1.0000; //00-02\n\n//     T_rectC2_to_rectC0 << 1.0000, 0.0000,   -0.0000,   -0.0596,\n//             0.0000,    1.0000,    0.0000,    0.0006,\n//             -0.0000,   -0.0000,    1.0000,   -0.0027,\n//             0,         0,         0,    1.0000; //03\n\n//     T_rectC2_to_rectC0 << 1.0000, 0.0000,   -0.0000,   -0.0602,\n//             0.0000,    1.0000,    0.0000,    0.0021,\n//             -0.0000,   -0.0000,    1.0000,   -0.0062,\n//             0,         0,         0,    1.0000;//04-10\n\n    //load  poses\n    if (loadKittiPoses(kittipath,  poses, T_rectC2_to_rectC0) == 0 )\n    {\n        cerr << \"cannot find pose file\" << endl;\n        return 0;\n    }\n    //load  poses\n    if (loadKittiTimes(kittTimepath,  timestamps) == 0 )\n    {\n        cerr << \"cannot find time file\" << endl;\n        return 0;\n    }\n\n    if ( convert( poses, timestamps, tumFileName) == 0)\n    {\n        cerr << \"convert failed!!!\" << endl;\n        return 0;\n    }\n\n\n    cout << \"It is done!------------------------------------------------\" << endl;\n\n\n\n    return 1;\n}\n\n\n\n\nint loadKittiPoses(const string &  file_name, vector<Eigen::Matrix4d> & poses)\n{\n    FILE *fp = fopen(file_name.c_str(), \"r\");\n    if (!fp)\n        return  0;\n    while (!feof(fp)) {\n        double P[3] [4];\n        if (fscanf(fp, \"%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf\",\n                   &P[0][0], &P[0][1], &P[0][2], &P[0][3],\n                   &P[1][0], &P[1][1], &P[1][2], &P[1][3],\n                   &P[2][0], &P[2][1], &P[2][2], &P[2][3] ) == 12) {\n            Eigen::Matrix4d T;\n            T << P[0][0], P[0][1], P[0][2], P[0][3],\n            P[1][0], P[1][1], P[1][2], P[1][3],\n            P[2][0], P[2][1], P[2][2], P[2][3],\n            0, 0, 0, 1;\n            poses.push_back(T);\n        }\n    }\n    fclose(fp);\n    return 1;\n\n}\n\n//保存transpose*T*transposeInv到poses\nint loadKittiPoses(const string &  file_name, vector<Eigen::Matrix4d> & poses, Eigen::Matrix4d &transpose)\n{\n Eigen::Matrix4d transposeInv=transpose.inverse();\n\tcout<<\"transpose: \"<<transpose<<endl;\ncout<<\"transposeInv: \"<<transposeInv<<endl;\n    FILE *fp = fopen(file_name.c_str(), \"r\");\n    if (!fp)\n        return  0;\n    while (!feof(fp)) {\n        double P[3] [4];\n        if (fscanf(fp, \"%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf\",\n                   &P[0][0], &P[0][1], &P[0][2], &P[0][3],\n                   &P[1][0], &P[1][1], &P[1][2], &P[1][3],\n                   &P[2][0], &P[2][1], &P[2][2], &P[2][3] ) == 12) {\n            Eigen::Matrix4d T;\n            T << P[0][0], P[0][1], P[0][2], P[0][3],\n            P[1][0], P[1][1], P[1][2], P[1][3],\n            P[2][0], P[2][1], P[2][2], P[2][3],\n            0, 0, 0, 1;\n            poses.push_back(transpose*T*transposeInv);\n        }\n    }\n    fclose(fp);\n    return 1;\n\n}\n\nint loadKittiTimes( const string & file_name,  vector<double> & timestamps)\n{\n    FILE *fp = fopen(file_name.c_str(), \"r\");\n    if (!fp)\n        return  0;\n    while (!feof(fp)) {\n        double timestamp;\n        if (fscanf(fp, \"%lf \", &timestamp ) == 1) {\n            timestamps.push_back(timestamp);\n        }\n    }\n    fclose(fp);\n    return 1;\n\n}\n\n\nint convert(  vector<Eigen::Matrix4d> & poses,  vector<double> & timestamps,  const string & filename)\n{\n    cout << endl << \"Saving camera pose to \" << filename << \" ...\" << endl;\n    ofstream fileout;\n    fileout.open(filename.c_str(),std::ios::out);\n    fileout << \"#Format: timestamp tx ty tz qx qy qz qw\" << endl ;\n\n    vector<double>::iterator itTimestamp = timestamps.begin();\n    if (poses.size() != timestamps.size())\n    {\n        cerr << \"!!!-----------poses.size() != timestamps.size()----------!!!\" << endl;\n        //return 0;\n    }\n\n\n//NOTE 这里以pose的size()为准\n    for (vector<Eigen::Matrix4d>::iterator it = poses.begin(); it != poses.end(); it++, itTimestamp++)\n    {\n        Eigen::Matrix4d tmpPose = *it;\n        Eigen::Matrix3d tmpRotationMatrix = tmpPose.block(0, 0, 3, 3);\n        Eigen::Quaterniond q = Eigen::Quaterniond ( tmpRotationMatrix ); //// 请注意四元数 的顺序是(x,y,z,w), w 为实部，前三者为虚部\n        //cout<< q.x() << \" \" << q.y() << \" \" << q.z() << \" \" << q.w() << endl;\n        fileout << setprecision(6) << *itTimestamp << \" \" <<  setprecision(9) <<  tmpPose(0, 3) << \" \" << tmpPose(1, 3) << \" \" << tmpPose(2, 3) << \" \" << q.x() << \" \" << q.y() << \" \" << q.z() << \" \" << q.w() << endl;\n\n\n    }\n\n    fileout.close();\n    cout << endl << \"trajectory saved!\" << endl;\n    return 1;\n\n}\n", "meta": {"hexsha": "c02aea7e9b48c7bfb3c9831e3f4a89ae0adbe67d", "size": 6398, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "convert/kitti2Tum/convert2.cpp", "max_stars_repo_name": "jiexuan/evaluation_tools", "max_stars_repo_head_hexsha": "d8cab5cea2c859ef6067aaedc8cf11be102ad7f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-05-13T10:20:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T03:40:47.000Z", "max_issues_repo_path": "convert/kitti2Tum/convert2.cpp", "max_issues_repo_name": "michaelczhou/evaluation_tools", "max_issues_repo_head_hexsha": "1ef3f6d65869990eb35b6e69106a77e0baf2c0b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "convert/kitti2Tum/convert2.cpp", "max_forks_repo_name": "michaelczhou/evaluation_tools", "max_forks_repo_head_hexsha": "1ef3f6d65869990eb35b6e69106a77e0baf2c0b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-04-24T02:33:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-13T08:33:38.000Z", "avg_line_length": 30.7596153846, "max_line_length": 216, "alphanum_fraction": 0.5198499531, "num_tokens": 2228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.29490619110950467}}
{"text": "/*\nCompute probability & bayesian evidence that a Pfam or TIGR protein domain is near \ntheir respective average tri-nucleotide or amino acid distribution.\n\nConversely, the same quantities an be computed for domains consistently far from the mean.\n*/\n#include <iostream>\n#include <string>\n#include <algorithm>\n#include <boost/program_options.hpp>\n#include \"./task/domain_probability_task.cpp\"\n#include \"./task/context.cpp\"\n\nusing namespace std;\nnamespace po = boost::program_options;\n\nint main(int ac, char* av[]) {\n\ttry {\n\t\tpo::options_description desc(\n\t\t\t\"Compute probability & bayesian evidence that a Pfam or TIGR \"\n            \"protein domain is near (or far) from their respective \"\n            \"average tri-nucleotide or amino acid distribution\"\n\t\t);\n\t\tdesc.add_options()\n            (\n            \t\"help,h\", \n            \t\"Print help message\"\n            )\n            (\n                \"kind,k\", \n                po::value<string>()->default_value(\"\"), \n                \"One of \\\"tri-nucleotide\\\" or \\\"amino-acid\\\"\"\n            )\n            (\n                \"query,q\", \n                po::value<string>()->default_value(\"\"), \n                \"Protein domain source = Pfam or TIGR (case insensitive)\"\n            )\n            (\n                \"tail,d\", \n                po::value<string>()->default_value(\"left\"), \n                \"Tail of the distribution of distances to tri-nucleotide mean on which to focus: \"\n                \"left (closest to min distance 0) or right (closest to max distance 1)\"\n            )\n            (\n            \t\"n_threads,t\", \n            \tpo::value<int>()->default_value(4),\n            \t\"Number of threads to use.\"\n            )\n            (\n                \"config_file,c\", \n                po::value<string>()->default_value(\"\"),\n                \"Use JSON config file instead of command line parameters\"\n            )\n        ;\n\n        po::variables_map vm;\n        po::store(po::parse_command_line(ac, av, desc), vm);\n        po::notify(vm);\n\n        if (vm.count(\"help\")) {\n            cerr << desc << endl;\n            return 0;\n        }\n\n        string config_file_path = vm[\"config_file\"].as<string>();\n        if (!config_file_path.empty()) {\n            cerr << \"Using config file: \" << config_file_path << endl;\n            DomainProbabilityContext ctx = parse_domain_probability_context(config_file_path);\n            compute_domain_probabilities(ctx);\n\n        } else {\n            string kind = vm[\"kind\"].as<string>();\n            if (kind == \"tri-nucleotide\" || kind == \"amino-acid\") {\n                cerr << \"Kind: \" << kind << endl;\n            } else if (kind.empty()) {\n                cerr << \"Error: parameter \\\"kind\\\" not set.\";\n                cerr << \" See --help for usage.\" << endl;\n                return 1;\n            } else {\n                cerr << \"Error: unknown value for parameter \\\"kind\\\": \\\"\" << kind;\n                cerr << \"\\\". See --help for usage.\" << endl;\n                return 1;\n            }\n\n            auto query = vm[\"query\"].as<string>();\n            transform(query.begin(), query.end(), query.begin(), ::tolower);\n\n            cerr << \"Query: \" << query << endl;\n            if (query != \"pfam\" && query != \"tigr\") {\n                cerr << \"Error: --query must be one of pfam, tigr\" << endl;\n                cerr << desc << endl;\n                return 1;\n            }\n\n            auto tail = vm[\"tail\"].as<string>();\n            transform(tail.begin(), tail.end(), tail.begin(), ::tolower);\n            cerr << \"Tail: \" << tail << endl;\n            if (tail != \"left\" && tail != \"right\") {\n                cerr << \"Error: --tail must be one of left, right\" << endl;\n                cerr << desc << endl;\n                return 1;\n            }\n\n            const int n_threads = vm[\"n_threads\"].as<int>();\n            cerr << \"Threads: \" << n_threads << endl;\n\n            DomainProbabilityContext ctx = get_context_from_parameters(\n                kind,\n                query,\n                tail,\n                n_threads\n            );\n            compute_domain_probabilities(ctx);\n        }\n\t}\n\tcatch (exception& e) {\n\t\tcerr << \"Exception raised: \" << e.what() << endl;\n\t\treturn 1;\n\t}\n\tcatch (...) {\n\t\tcerr << \"Unknown exception raised\" << endl;\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n", "meta": {"hexsha": "b5f946e73ca44673b0e41f626cc00e8390e827ba", "size": 4291, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/domain_probability.cpp", "max_stars_repo_name": "srom/nbias", "max_stars_repo_head_hexsha": "be8cf8dd623038dcf08d38ed3d19f635ee2dbeae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/domain_probability.cpp", "max_issues_repo_name": "srom/nbias", "max_issues_repo_head_hexsha": "be8cf8dd623038dcf08d38ed3d19f635ee2dbeae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/domain_probability.cpp", "max_forks_repo_name": "srom/nbias", "max_forks_repo_head_hexsha": "be8cf8dd623038dcf08d38ed3d19f635ee2dbeae", "max_forks_repo_licenses": ["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.7874015748, "max_line_length": 98, "alphanum_fraction": 0.4977860639, "num_tokens": 930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040617, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.2948981698994849}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2019 Tinko Bartels, Berlin, Germany.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_EXTENSIONS_TRIANGULATION_GEOMETRIES_TRIANGULATION_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_TRIANGULATION_GEOMETRIES_TRIANGULATION_HPP\n\n#include <vector>\n\n#include <boost/range.hpp>\n#include <boost/iterator/iterator_facade.hpp>\n#include <boost/iterator/iterator_categories.hpp>\n#include <boost/iterator/indirect_iterator.hpp>\n\n#include <boost/geometry/strategies/cartesian/side_by_triangle.hpp>\n#include <boost/geometry/core/point_type.hpp>\n#include <boost/geometry/views/detail/points_view.hpp>\n#include <boost/geometry/algorithms/assign.hpp>\n#include <boost/geometry/geometries/concepts/point_concept.hpp>\n\nnamespace boost { namespace geometry\n{\ntemplate<typename Triangulation>\nstruct face_range_type {};\n\ntemplate<typename Triangulation>\ntypename face_range_type<Triangulation>::type\n    face_range(Triangulation const& t);\n\ntemplate<typename Triangulation>\nstruct triangulation_face {};\n\nnamespace model\n{\n\ntemplate\n<\n    typename Point,\n    bool ClockWise = true,\n    template<typename, typename> class VertexContainer = std::vector,\n    template<typename, typename> class FaceContainer = std::vector,\n    template<typename> class VertexAllocator = std::allocator,\n    template<typename> class FaceAllocator = std::allocator\n>\nclass triangulation;\n\ntemplate<typename Triangulation>\nstruct vertex_ref\n{\n    typename Triangulation::point_type m_p;\n    typename Triangulation::face_iterator m_f;\n};\n\ntemplate<typename Triangulation>\nstruct face_ref\n{\n    typedef typename Triangulation::point_type point_type;\n    typedef typename Triangulation::vertex_iterator vertex_iterator;\n    typedef typename Triangulation::face_iterator face_iterator;\n    typedef std::array<vertex_iterator, 3> vertex_container;\n    vertex_container m_v;\n    std::array<face_iterator, 3> m_f;\n    std::array<unsigned short, 3> m_o;\npublic:\n    typedef boost::indirect_iterator<typename vertex_container::const_iterator>\n        const_iterator;\n    typedef boost::indirect_iterator<typename vertex_container::iterator>\n        iterator;\n\n    const_iterator begin() const { return const_iterator(m_v.begin()); }\n    const_iterator end() const { return const_iterator(m_v.end()); }\n};\n\ntemplate\n<\n    typename Value,\n    template<typename, typename> class Container,\n    template<typename> class Allocator\n>\nstruct reserve_if_vector{\n    static void apply(Container<Value, Allocator<Value>>& c, std::size_t n) {}\n};\n\ntemplate<typename Value, template<typename> class Allocator>\nstruct reserve_if_vector<Value, std::vector, Allocator>{\n    static void apply(std::vector<Value, Allocator<Value>>& c,\n                      std::size_t n) { c.reserve(n);}\n};\n\ntemplate\n<\n    typename Point,\n    bool ClockWise,\n    template<typename, typename> class VertexContainer,\n    template<typename, typename> class FaceContainer,\n    template<typename> class VertexAllocator,\n    template<typename> class FaceAllocator\n>\nclass triangulation\n{\nprivate:\n    BOOST_CONCEPT_ASSERT( (concepts::Point<Point>) );\npublic:\n    typedef Point point_type;\n    typedef face_ref<triangulation> face_type;\n    typedef vertex_ref<triangulation> vertex_type;\n    typedef unsigned short face_vertex_index;\n    typedef VertexContainer<vertex_type, VertexAllocator<vertex_type>>\n        vertex_container;\n    typedef FaceContainer<face_type, FaceAllocator<face_type>> face_container;\n    typedef typename face_container::iterator face_iterator;\n    typedef typename face_container::const_iterator const_face_iterator;\n    typedef typename vertex_container::iterator vertex_iterator;\n    typedef typename vertex_container::const_iterator const_vertex_iterator;\n    typedef typename coordinate_type<Point>::type coordinate_type;\n    typedef typename model::segment<Point> segment_type;\n\n    static const order_selector point_order =\n        ClockWise ? clockwise : counterclockwise;\n    struct halfedge_index\n    {\n        halfedge_index(face_iterator f, face_vertex_index v):m_f(f), m_v(v) {}\n        face_iterator m_f;\n        face_vertex_index m_v;\n    };\n\n    struct fulledge_index\n    {\n        fulledge_index(face_iterator f1,\n                       face_vertex_index v1,\n                       face_iterator f2,\n                       face_vertex_index v2)\n            : m_f1(f1),\n              m_f2(f2),\n              m_v1(v1),\n              m_v2(v2) {}\n        fulledge_index(halfedge_index e)\n            : m_f1(e.m_f),\n              m_f2(e.m_f->m_f[ e.m_v ]),\n              m_v1(e.m_v),\n              m_v2(e.m_f->m_o[ e.m_v ]) {}\n        face_iterator m_f1, m_f2;\n        face_vertex_index m_v1, m_v2;\n    };\n\n    static face_iterator invalid() { return face_iterator(); }\n    triangulation(std::size_t points = 3)\n    {\n        reserve_if_vector<vertex_type, VertexContainer, VertexAllocator>::\n            apply(m_vertices, points);\n        reserve_if_vector<face_type, FaceContainer, FaceAllocator>::\n            apply(m_faces, 2 * points - 5);\n    }\n\n    triangulation(std::size_t points, std::size_t faces)\n    {\n        reserve_if_vector<vertex_type, VertexContainer, VertexAllocator>::\n            apply(m_vertices, points);\n        reserve_if_vector<face_type, FaceContainer, FaceAllocator>::\n            apply(m_faces, faces);\n    }\n\n    template <typename InputIt>\n    triangulation(InputIt begin, InputIt end)\n    {\n        m_vertices.assign(begin, end);\n        reserve_if_vector<face_type, FaceContainer, FaceAllocator>\n            ::apply(m_faces, 2 * m_vertices.size() - 5);\n    }\n\n    typename vertex_container::iterator vertices_begin()\n    {\n        return m_vertices.begin();\n    }\n\n    typename vertex_container::const_iterator vertices_begin() const\n    {\n        return m_vertices.cbegin();\n    }\n\n    typename vertex_container::iterator vertices_end()\n    {\n        return m_vertices.end();\n    }\n\n    typename vertex_container::const_iterator vertices_end() const\n    {\n        return m_vertices.cend();\n    }\n\n    vertex_iterator add_vertex(const Point& p)\n    {\n        return m_vertices.insert(m_vertices.end(), vertex_type{p, invalid()});\n    }\n\n    face_container const& face_range() const\n    {\n        return m_faces;\n    }\n\n    vertex_container const& vertex_range() const\n    {\n        return m_vertices;\n    }\n\n    typename face_container::const_iterator faces_cbegin() const\n    {\n        return m_faces.cbegin();\n    }\n\n    typename face_container::iterator faces_begin()\n    {\n        return m_faces.begin();\n    }\n\n    typename face_container::const_iterator faces_cend() const\n    {\n        return m_faces.cend();\n    }\n\n    typename face_container::iterator faces_end()\n    {\n        return m_faces.end();\n    }\n\n    template <typename InputIt>\n    void assign_vertices(InputIt begin, InputIt end)\n    {\n        m_vertices.assign(begin, end);\n        m_faces.reserve(2 * m_vertices.size() - 5);\n    }\n\n    static Point const& face_vertex(face_iterator f, face_vertex_index v)\n    {\n        return f -> m_v[ v ] -> m_p;\n    }\n\n    static segment_type face_segment(halfedge_index e)\n    {\n        return segment_type(\n            face_vertex(e.m_f, (e.m_v == 2 ? 0 : e.m_v + 1)),\n            face_vertex(e.m_f, (e.m_v == 0 ? 2 : e.m_v - 1)) );\n    }\n\n    static Point& vertex(vertex_iterator v)\n    {\n        return v -> m_p;\n    }\n\n    static face_iterator neighbour(face_iterator f, unsigned short v)\n    {\n        return f -> m_f[ v ];\n    }\n\n    static const_face_iterator neighbour(const_face_iterator f,\n                                         unsigned short v)\n    {\n        return f -> m_f[ v ];\n    }\n\n    static face_vertex_index opposite(face_iterator f, unsigned short v)\n    {\n        return f -> m_o[ v ];\n    }\n\n    static halfedge_index opposite(halfedge_index const& e)\n    {\n        return halfedge_index{ e.m_f -> m_f[ e.m_v ], e.m_f -> m_o[ e.m_v ] };\n    }\n\n    static halfedge_index next(halfedge_index const& e)\n    {\n        return halfedge_index{\n            e.m_f,\n            static_cast<unsigned short>(e.m_v == 2 ? 0 : e.m_v + 1) };\n    }\n\n    static halfedge_index prev(halfedge_index const& e)\n    {\n        return halfedge_index{\n            e.m_f,\n            static_cast<unsigned short>(e.m_v == 0 ? 2 : e.m_v - 1)};\n    }\n\n    vertex_iterator boundary_vertex() const\n    {\n        return m_boundary_vertex;\n    }\n\n    static vertex_iterator boundary_next(vertex_iterator v)\n    {\n        face_iterator fi = v -> m_f;\n        if(fi -> m_v[ 0 ] == v )\n            return fi -> m_v[ 1 ];\n        else if(fi -> m_v[ 1 ] == v)\n            return fi -> m_v[ 2 ];\n        else\n            return fi -> m_v[ 0 ];\n    }\n\n    vertex_iterator boundary_prev(vertex_iterator v) const\n    {\n        face_iterator fi = v -> m_f;\n        unsigned short vi;\n        if(fi -> m_v[ 0 ] == v) vi = 0;\n        else if(fi -> m_v[ 1 ] == v) vi = 1;\n        else vi = 2;\n        if(m_faces.size() == 1)\n            return vi == 0 ? fi -> m_v[ 2 ] : fi -> m_v[ vi - 1 ];\n        halfedge_index e = next(halfedge_index{fi, vi});\n        while( opposite(e).m_f != invalid() )\n        {\n            e = prev(opposite(e));\n        }\n        return e.m_f -> m_v[ e.m_v == 2 ? 0 : e.m_v + 1 ];\n    }\n\n    void clear()\n    {\n        m_vertices.clear();\n        m_faces.clear();\n    }\n\n    std::size_t vertices() const\n    {\n        return m_vertices.size();\n    }\n\n    std::size_t faces() const\n    {\n        return m_faces.size();\n    }\n\n    static void flip(const halfedge_index& e)\n    {\n        face_iterator fi1 = e.m_f;\n        face_type& f1 = *fi1;\n        face_iterator fi2 = f1.m_f[ e.m_v ];\n        face_type& f2 = *fi2;\n        unsigned short const& v1 = e.m_v;\n        unsigned short const v2 = f1.m_o[ v1 ];\n\n        if( f1.m_v[ v1 == 0 ? 2 : v1 - 1 ] -> m_f == fi1 )\n            f1.m_v[ v1 == 0 ? 2 : v1 - 1 ] -> m_f = fi2;\n        if( f2.m_v[ v2 == 0 ? 2 : v2 - 1  ]-> m_f == fi2)\n            f2.m_v[ v2 == 0 ? 2 : v2 - 1  ]-> m_f = fi1;\n        f1.m_v[ v1 == 0 ? 2 : v1 - 1 ] = f2.m_v[ v2 ];\n        f2.m_v[ v2 == 0 ? 2 : v2 - 1 ] = f1.m_v[ v1 ];\n\n        f1.m_f[v1] = f2.m_f[ v2 == 2 ? 0 : v2 + 1 ];\n        f1.m_o[v1] = f2.m_o[ v2 == 2 ? 0 : v2 + 1 ];\n        if(f1.m_f[v1] != invalid()) {\n            f1.m_f[v1] -> m_f[ f2.m_o[ v2 == 2 ? 0 : v2 + 1 ] ] = fi1;\n            f1.m_f[v1] -> m_o[ f2.m_o[ v2 == 2 ? 0 : v2 + 1 ] ] = v1;\n        }\n        f2.m_f[v2] = f1.m_f[ v1 == 2 ? 0 : v1 + 1 ];\n        f2.m_o[v2] = f1.m_o[ v1 == 2 ? 0 : v1 + 1 ];\n        if(f2.m_f[v2] != invalid()) {\n            f2.m_f[v2] -> m_f[ f1.m_o[ v1 == 2 ? 0 : v1 + 1 ] ] = fi2;\n            f2.m_f[v2] -> m_o[ f1.m_o[ v1 == 2 ? 0 : v1 + 1 ] ] = v2;\n        }\n        f1.m_f[ v1 == 2 ? 0 : v1 + 1 ] = fi2;\n        f1.m_o[ v1 == 2 ? 0 : v1 + 1 ] = v2 == 2 ? 0 : v2 + 1;\n        f2.m_f[ v2 == 2 ? 0 : v2 + 1 ] = fi1;\n        f2.m_o[ v2 == 2 ? 0 : v2 + 1 ] = v1 == 2 ? 0 : v1 + 1;\n    }\n\n    face_iterator add_face_on_boundary(halfedge_index e, vertex_iterator v)\n    {\n        const face_iterator f = e.m_f;\n        const face_vertex_index adj = e.m_v;\n        f -> m_o[adj] = 0;\n        m_boundary_vertex = v;\n        face_iterator pos = m_faces.insert(m_faces.end(),\n            face_type{ {{v, f->m_v[ adj == 0 ? 2 : adj - 1 ],\n                         f->m_v[ adj == 2 ? 0 : adj + 1 ] }},\n                {{f, invalid(), invalid()}},\n                {{adj, 4, 4}}});\n        f -> m_f[adj] = pos;\n        v -> m_f = pos;\n        m_faces.back().m_v[ 2 ]->m_f = pos;\n        return pos;\n    }\n\n    fulledge_index next_around_vertex(fulledge_index e)\n    {\n        if(e.m_f2 == invalid()) {\n            face_vertex_index left_vi = (e.m_v1 == 0 ? 2 : e.m_v1 - 1);\n            vertex_iterator left_v = e.m_f1->m_v[ left_vi ];\n            face_iterator next_f = left_v->m_f;\n            face_vertex_index next_vi =\n                (next_f->m_v[ 0 ] == left_v) ? 2 :\n                ((next_f->m_v[ 1 ] == left_v) ? 0 : 1);\n            return fulledge_index(invalid(), 4, next_f, next_vi);\n        } else {\n            return fulledge_index(halfedge_index(e.m_f2,\n                                                 e.m_v2 == 0 ? 2 : e.m_v2 - 1));\n        }\n    }\n\n    static fulledge_index begin_vertex_edge(vertex_iterator vi)\n    {\n        face_iterator first_f = vi -> m_f;\n        face_vertex_index next_vi =\n            (first_f->m_v[ 0 ] == vi) ? 2 :\n            ((first_f->m_v[ 1 ] == vi) ? 0 : 1);\n        return fulledge_index(invalid(), 4, first_f, next_vi);\n    }\n\n    face_iterator add_isolated_face(vertex_iterator v1,\n                                    vertex_iterator v2,\n                                    vertex_iterator v3)\n    {\n        m_boundary_vertex = v1;\n        face_iterator pos = m_faces.insert( m_faces.end(),\n            face_type{\n                {{ v1, v2, v3 }},\n                {{ invalid(), invalid(), invalid() }},\n                {{4, 4, 4}} } );\n        v1 -> m_f = v2 -> m_f = v3 -> m_f = pos;\n        return pos;\n    }\n\n    static halfedge_index face_edge(face_iterator f, face_vertex_index v = 0)\n    {\n        return halfedge_index{f, v};\n    }\n\n    static void connect(halfedge_index e1, halfedge_index e2)\n    {\n        face_iterator f1 = e1.m_f;\n        face_iterator f2 = e2.m_f;\n        unsigned short& v1 = e1.m_v;\n        unsigned short& v2 = e2.m_v;\n        f1 -> m_f[ v1 ] = f2;\n        f1 -> m_o[ v1 ] = v2;\n        f2 -> m_f[ v2 ] = f1;\n        f2 -> m_o[ v2 ] = v1;\n        if(f1 -> m_v[ (v1 == 2 ? 0 : v1 + 1) ] -> m_f == f1) {\n            f1 -> m_v[ (v1 == 2 ? 0 : v1 + 1) ] -> m_f = f2;\n        }\n        if(f2 -> m_v[ (v2 == 2 ? 0 : v2 + 1) ] -> m_f == f2) {\n            f2 -> m_v[ (v2 == 2 ? 0 : v2 + 1) ] -> m_f = f1;\n        }\n    }\n\n    bool valid() const\n    {\n        bool valid = true;\n        for(const_face_iterator fi = m_faces.begin();\n            fi != m_faces.end();\n            ++fi)\n        {\n            face_type const& f = *fi;\n            for(unsigned short v = 0 ; v < 3 ; ++v)\n            {\n                if(f.m_f[ v ] == invalid())\n                    continue;\n                face_vertex_index const& o = f.m_o[ v ];\n                valid = valid && (f.m_f[ v ]->m_o[ o ] == v);\n                if(!valid) {\n                    return false;\n                }\n                valid = valid && (f.m_f[ v ]->m_f[ o ] == fi);\n                if(!valid) {\n                    return false;\n                }\n                valid = valid\n                    && (f.m_v[ (v + 1) % 3 ] == f.m_f[ v ]->m_v[ (o + 2) % 3 ])\n                    && (f.m_v[ (v + 2) % 3 ] == f.m_f[ v ]->m_v[ (o + 1) % 3 ]);\n                if(!valid) {\n                    return false;\n                }\n                if(f.m_o[v] == 4) {\n                    unsigned short next = (v + 1) % 3;\n                    valid = valid && f.m_v[ next ]->m_f == fi;\n                    if(!valid) {\n                        return false;\n                    }\n\n                }\n            }\n        }\n        for(const_vertex_iterator vi = m_vertices.cbegin();\n            vi != m_vertices.cend();\n            ++vi)\n        {\n            vertex_type const& v = *vi;\n            if(v.m_f == invalid()) continue;\n\n            bool found = false;\n            for(face_vertex_index vj = 0; vj < 3 ; ++vj)\n            {\n                found = found || (v.m_f -> m_v[ vj ] == vi);\n            }\n            valid = valid && found;\n            if(!valid) {\n                return false;\n            }\n        }\n        return valid;\n    }\nprivate:\n    vertex_container m_vertices;\n    face_container m_faces;\n    vertex_iterator m_boundary_vertex;\n};\n\ntemplate< typename Point >\nstruct edge_ref\n{\n    typename triangulation<Point>::halfedge_index m_e;\n    triangulation<Point>& m_t;\n};\n\ntemplate< typename Point >\nusing triangulation_face_range = typename triangulation<Point>::face_container;\n\ntemplate< typename Point >\nusing triangulation_vertex_range =\n    typename triangulation<Point>::vertex_container;\n\n} // namespace model\n\n#ifndef DOXYGEN_NO_TRAITS_SPECIALIZATIONS\nnamespace traits\n{\n\ntemplate<typename Triangulation>\nstruct tag< model::vertex_ref<Triangulation> >\n{ typedef point_tag type; };\n\ntemplate<typename Triangulation>\nstruct coordinate_type< model::vertex_ref<Triangulation> >\n{\n    typedef typename coordinate_type<typename Triangulation::point_type>\n        ::type type;\n};\n\ntemplate<typename Triangulation>\nstruct dimension< model::vertex_ref<Triangulation> > : boost::mpl::int_<2> {};\n\ntemplate<typename Triangulation>\nstruct coordinate_system< model::vertex_ref<Triangulation> >\n{\n    typedef typename coordinate_system<typename Triangulation::point_type>\n        ::type type;\n};\n\ntemplate<typename Triangulation, std::size_t Dimension>\nstruct access<model::vertex_ref<Triangulation>, Dimension>\n{\n    static typename coordinate_type<typename Triangulation::point_type>::type\n        get(model::vertex_ref<Triangulation> const& p)\n    {\n        return boost::geometry::get<Dimension>(p.m_p);\n    }\n};\n\ntemplate<typename Point> struct tag< model::edge_ref<Point> >\n{ typedef segment_tag type; };\n\ntemplate<typename Point> struct point_type< model::edge_ref<Point> >\n{ typedef Point type; };\n\ntemplate<typename Point, std::size_t Dimension>\nstruct indexed_access<model::edge_ref<Point>, 0, Dimension>\n{\n    static typename coordinate_type<Point>::type\n        get(model::edge_ref<Point> const& p)\n    {\n        return get<Dimension>(\n            p.m_t.face_vertex(p.m_e.m_f, (p.m_e.m_v == 2 ? 0 : p.m_e.m_v + 1))\n        );\n    }\n};\n\ntemplate<typename Point, std::size_t Dimension>\nstruct indexed_access<model::edge_ref<Point>, 1, Dimension>\n{\n    static typename coordinate_type<Point>::type\n        get(model::edge_ref<Point> const& p)\n    {\n        return get<Dimension>(\n            p.m_t.face_vertex(p.m_e.m_f, (p.m_e.m_v == 0 ? 2 : p.m_e.m_v - 1)));\n    }\n};\n\ntemplate<typename Triangulation>\nstruct tag<model::face_ref<Triangulation>>\n{ typedef ring_tag type; };\n\ntemplate<typename Triangulation>\nstruct point_order<model::face_ref<Triangulation>>\n{ static const order_selector value = Triangulation::point_order; };\n\ntemplate<typename Triangulation>\nstruct closure<model::face_ref<Triangulation>>\n{ static const closure_selector value = open; };\n\n} // namespace traits\n#endif // DOXYGEN_NO_TRAITS_SPECIALIZATIONS\n\ntemplate<typename Point>\nstruct face_range_type<model::triangulation<Point>> {\n    typedef typename model::triangulation_face_range<Point> type;\n};\n\ntemplate\n<\n    typename Point,\n    bool ClockWise,\n    template<typename, typename> class VertexContainer,\n    template<typename, typename> class FaceContainer,\n    template<typename> class VertexAllocator,\n    template<typename> class FaceAllocator\n>\ninline typename model::triangulation\n<\n    Point,\n    ClockWise,\n    VertexContainer,\n    FaceContainer,\n    VertexAllocator,\n    FaceAllocator\n>::vertex_container const& vertex_range(\n    model::triangulation<Point, ClockWise, VertexContainer, FaceContainer,\n        VertexAllocator, FaceAllocator> const& t)\n{ return t.vertex_range(); }\n\ntemplate\n<\n    typename Point,\n    bool ClockWise,\n    template<typename, typename> class VertexContainer,\n    template<typename, typename> class FaceContainer,\n    template<typename> class VertexAllocator,\n    template<typename> class FaceAllocator\n>\ninline typename model::triangulation\n<\n    Point,\n    ClockWise,\n    VertexContainer,\n    FaceContainer,\n    VertexAllocator,\n    FaceAllocator\n>::face_container const& face_range(\n    model::triangulation<Point, ClockWise, VertexContainer, FaceContainer,\n        VertexAllocator, FaceAllocator> const& t)\n{ return t.face_range(); }\n\ntemplate\n<\n    typename Point,\n    bool ClockWise,\n    template<typename, typename> class VertexContainer,\n    template<typename, typename> class FaceContainer,\n    template<typename> class VertexAllocator,\n    template<typename> class FaceAllocator,\n    typename FaceIterator,\n    typename OutputIterator\n>\ninline void face_adjacent_range(\n    model::triangulation<Point, ClockWise, VertexContainer, FaceContainer,\n        VertexAllocator, FaceAllocator>& t,\n    FaceIterator fi,\n    OutputIterator out)\n{\n    typedef typename model::triangulation<Point, ClockWise, VertexContainer,\n        FaceContainer, VertexAllocator, FaceAllocator > triangulation;\n    typedef typename triangulation::face_iterator face_iterator;\n    face_iterator const invalid = t.invalid();\n    if(fi -> m_f[ 0 ] != invalid ) *out++ = fi->m_f[ 0 ];\n    if(fi -> m_f[ 1 ] != invalid ) *out++ = fi->m_f[ 1 ];\n    if(fi -> m_f[ 2 ] != invalid ) *out++ = fi->m_f[ 2 ];\n}\n\ntemplate\n<\n    typename Point,\n    bool ClockWise,\n    template<typename, typename> class VertexContainer,\n    template<typename, typename> class FaceContainer,\n    template<typename> class VertexAllocator,\n    template<typename> class FaceAllocator,\n    typename FaceIterator,\n    typename OutputIterator\n>\ninline void face_incident_faces(\n    model::triangulation<Point, ClockWise, VertexContainer, FaceContainer,\n        VertexAllocator, FaceAllocator> & t,\n    FaceIterator fi,\n    OutputIterator out)\n{\n    typedef typename model::triangulation<Point, ClockWise, VertexContainer,\n        FaceContainer, VertexAllocator, FaceAllocator> triangulation;\n    typedef typename triangulation::face_iterator face_iterator;\n    typedef typename triangulation::vertex_iterator vertex_iterator;\n    typedef typename triangulation::face_vertex_index face_vertex_index;\n    typedef typename triangulation::face_type face_type;\n    face_iterator const invalid = t.invalid();\n    for(face_vertex_index i = 0; i < 3; ++i)\n    {\n        face_iterator n = fi -> m_f[i];\n        face_iterator m = fi -> m_f[i == 2 ? 0 : i + 1];\n        face_iterator f_prev = fi;\n        face_vertex_index v_prev = i;\n        if(n != invalid) {\n            f_prev = n;\n            v_prev = fi -> m_o[i];\n            v_prev = (v_prev == 0 ? 2 : v_prev - 1);\n        }\n        while(true)\n        {\n            face_iterator next = f_prev -> m_f[v_prev];\n            if(next == invalid) {\n                face_vertex_index j = (i == 2 ? 0 : i + 1);\n                face_iterator m = fi -> m_f[j];\n                if(m == invalid) break;\n                face_vertex_index prev_vertex_index = (i == 0 ? 2 : i - 1 );\n                vertex_iterator const& prev_vertex_it =\n                    fi->m_v[ prev_vertex_index ];\n                face_type& first = *prev_vertex_it->m_f;\n                *out++ = prev_vertex_it->m_f;\n                f_prev = next = prev_vertex_it->m_f;\n                if(first.m_v[0] == prev_vertex_it) v_prev = 1;\n                else if(first.m_v[1] == prev_vertex_it) v_prev = 2;\n                else v_prev = 0;\n                continue;\n            } else {\n                if(&(*next) == &(*fi)) break;\n                *out++ = next;\n                v_prev = f_prev -> m_o[v_prev];\n                v_prev = (v_prev == 0 ? 2 : v_prev - 1);\n                f_prev = next;\n            }\n        }\n    }\n}\n\ntemplate\n<\n    typename Point,\n    bool ClockWise,\n    template<typename, typename> class VertexContainer,\n    template<typename, typename> class FaceContainer,\n    template<typename> class VertexAllocator,\n    template<typename> class FaceAllocator,\n    typename OutputIterator\n>\ninline void vertex_incident_faces(\n    model::triangulation<Point, ClockWise, VertexContainer, FaceContainer,\n        VertexAllocator, FaceAllocator> & t,\n    typename model::triangulation<Point, ClockWise, VertexContainer,\n        FaceContainer, VertexAllocator, FaceAllocator>::vertex_iterator vi,\n    OutputIterator out)\n{\n    typedef typename model::triangulation<Point, ClockWise, VertexContainer,\n        FaceContainer, VertexAllocator, FaceAllocator> triangulation;\n    typedef typename triangulation::face_iterator face_iterator;\n    typedef typename triangulation::fulledge_index fulledge_index;\n    fulledge_index e = t.begin_vertex_edge(vi);\n    face_iterator first_face = e.m_f2;\n    *out++ = first_face;\n    while(true) {\n        e = t.next_around_vertex(e);\n        if(e.m_f2 == t.invalid() || e.m_f2 == first_face) break;\n        *out++ = e.m_f2;\n    }\n}\n\ntemplate\n<\n    typename Point,\n    bool ClockWise,\n    template<typename, typename> class VertexContainer,\n    template<typename, typename> class FaceContainer,\n    template<typename> class VertexAllocator,\n    template<typename> class FaceAllocator,\n    typename OutputIterator\n>\ninline void vertex_incident_vertices(\n    model::triangulation<Point, ClockWise, VertexContainer, FaceContainer,\n        VertexAllocator, FaceAllocator> & t,\n    typename model::triangulation<Point, ClockWise, VertexContainer,\n        FaceContainer, VertexAllocator, FaceAllocator>::vertex_iterator vi,\n    OutputIterator out)\n{\n    typedef model::triangulation<Point, ClockWise, VertexContainer,\n        FaceContainer, VertexAllocator, FaceAllocator> triangulation_type;\n    typedef typename triangulation_type::face_iterator face_iterator;\n    typedef typename triangulation_type::fulledge_index fulledge_index;\n    fulledge_index e = t.begin_vertex_edge(vi);\n    face_iterator first_face = e.m_f2;\n    *out++ = e.m_f2 -> m_v[ e.m_v2 == 0 ? 2 : e.m_v2 - 1 ];\n    while(true) {\n        e = t.next_around_vertex(e);\n        if(e.m_f2 == t.invalid() || e.m_f2 == first_face) break;\n        *out++ = e.m_f2 -> m_v[ e.m_v2 == 0 ? 2 : e.m_v2 - 1 ];\n    }\n}\n\n} // namespace geometry\n\n} // namespace boost\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_TRIANGULATION_GEOMETRIES_TRIANGULATION_HPP\n", "meta": {"hexsha": "f8b3c96639799da0fecb7d8a93aea9ba90c364d5", "size": 25670, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/extensions/triangulation/geometries/triangulation.hpp", "max_stars_repo_name": "BoostGSoC19/geometry", "max_stars_repo_head_hexsha": "bad1b9c5a2f4f458284a912a848a25e73c28014b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-31T19:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-31T19:33:37.000Z", "max_issues_repo_path": "include/boost/geometry/extensions/triangulation/geometries/triangulation.hpp", "max_issues_repo_name": "BoostGSoC19/geometry", "max_issues_repo_head_hexsha": "bad1b9c5a2f4f458284a912a848a25e73c28014b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/geometry/extensions/triangulation/geometries/triangulation.hpp", "max_forks_repo_name": "BoostGSoC19/geometry", "max_forks_repo_head_hexsha": "bad1b9c5a2f4f458284a912a848a25e73c28014b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-11-20T12:45:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-29T04:54:35.000Z", "avg_line_length": 31.5744157442, "max_line_length": 80, "alphanum_fraction": 0.6079080639, "num_tokens": 6567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2948981631986741}}
{"text": "#include \"CALPHADFreeEnergyFunctionsTernary.h\"\n#include \"CALPHADConcSolverTernary.h\"\n#include \"CALPHADEqConcSolverTernary.h\"\n#include \"CALPHADFunctions.h\"\n#include \"CALPHADTieLineConcSolverTernary.h\"\n#include \"PhysicalConstants.h\"\n#include \"datatypes.h\"\n#include \"functions.h\"\n#include \"well_functions.h\"\n\n#include <boost/property_tree/json_parser.hpp>\n\n#include <cmath>\n#include <iomanip>\n#include <string>\n\nnamespace pt = boost::property_tree;\n\nnamespace Thermo4PFM\n{\n\nvoid readLmixTernaryParameters(\n    pt::ptree& Lmix_db, CalphadDataType LmixABC[3][2])\n{\n    // L0\n    {\n        auto child = Lmix_db.get_child_optional(\"L0\");\n        if (child)\n        {\n            int i = 0;\n            for (pt::ptree::value_type& v : Lmix_db.get_child(\"L0\"))\n            {\n                LmixABC[0][i] = v.second.get_value<CalphadDataType>();\n                i++;\n            }\n        }\n    }\n    // L1\n    {\n        auto child = Lmix_db.get_child_optional(\"L1\");\n        if (child)\n        {\n            int i = 0;\n            for (pt::ptree::value_type& v : Lmix_db.get_child(\"L1\"))\n            {\n                LmixABC[1][i] = v.second.get_value<CalphadDataType>();\n                i++;\n            }\n        }\n    }\n    // L2\n    {\n        auto child = Lmix_db.get_child_optional(\"L2\");\n        if (child)\n        {\n            int i = 0;\n            for (pt::ptree::value_type& v : Lmix_db.get_child(\"L2\"))\n            {\n                LmixABC[2][i] = v.second.get_value<CalphadDataType>();\n                i++;\n            }\n        }\n    }\n}\n\nCALPHADFreeEnergyFunctionsTernary::CALPHADFreeEnergyFunctionsTernary(\n    pt::ptree& calphad_db, boost::optional<pt::ptree&> newton_db,\n    const EnergyInterpolationType energy_interp_func_type,\n    const ConcInterpolationType conc_interp_func_type)\n    : energy_interp_func_type_(energy_interp_func_type),\n      conc_interp_func_type_(conc_interp_func_type),\n      newton_tol_(1.e-8),\n      newton_alpha_(1.),\n      newton_maxits_(20),\n      newton_verbose_(false)\n\n{\n    std::string fenergy_diag_filename(\"energy.vtk\");\n    fenergy_diag_filename_ = new char[fenergy_diag_filename.length() + 1];\n    strcpy(fenergy_diag_filename_, fenergy_diag_filename.c_str());\n\n    readParameters(calphad_db);\n\n    if (newton_db) readNewtonparameters(newton_db.get());\n}\n\n//=======================================================================\n\nvoid CALPHADFreeEnergyFunctionsTernary::readNewtonparameters(\n    pt::ptree& newton_db)\n{\n    newton_tol_     = newton_db.get<double>(\"tol\", newton_tol_);\n    newton_alpha_   = newton_db.get<double>(\"alpha\", newton_alpha_);\n    newton_maxits_  = newton_db.get<int>(\"max_its\", newton_maxits_);\n    newton_verbose_ = newton_db.get<bool>(\"verbose\", newton_verbose_);\n}\n\n//=======================================================================\n\nvoid CALPHADFreeEnergyFunctionsTernary::readParameters(pt::ptree& calphad_db)\n{\n    pt::ptree& species0_db = calphad_db.get_child(\"SpeciesA\");\n    std::string name       = species0_db.get<std::string>(\"name\", \"unknown\");\n    std::string dbnameL(\"PhaseL\");\n    g_species_phaseL_[0].initialize(name, species0_db.get_child(dbnameL));\n    std::string dbnameA(\"PhaseA\");\n    g_species_phaseA_[0].initialize(name, species0_db.get_child(dbnameA));\n\n    pt::ptree& speciesB_db = calphad_db.get_child(\"SpeciesB\");\n    name                   = speciesB_db.get<std::string>(\"name\", \"unknown\");\n    g_species_phaseL_[1].initialize(name, speciesB_db.get_child(dbnameL));\n    g_species_phaseA_[1].initialize(name, speciesB_db.get_child(dbnameA));\n\n    pt::ptree& speciesC_db = calphad_db.get_child(\"SpeciesC\");\n    name                   = speciesC_db.get<std::string>(\"name\", \"unknown\");\n    g_species_phaseL_[2].initialize(name, speciesC_db.get_child(dbnameL));\n    g_species_phaseA_[2].initialize(name, speciesC_db.get_child(dbnameA));\n\n    // read Lmix coefficients\n\n    // AB\n    {\n        pt::ptree& Lmix0_db = calphad_db.get_child(\"LmixABPhaseL\");\n        readLmixBinary(Lmix0_db, LmixABPhaseL_);\n\n        pt::ptree& Lmix1_db = calphad_db.get_child(\"LmixABPhaseA\");\n        readLmixBinary(Lmix1_db, LmixABPhaseA_);\n    }\n\n    // AC\n    {\n        pt::ptree& Lmix0_db = calphad_db.get_child(\"LmixACPhaseL\");\n        readLmixBinary(Lmix0_db, LmixACPhaseL_);\n\n        pt::ptree& Lmix1_db = calphad_db.get_child(\"LmixACPhaseA\");\n        readLmixBinary(Lmix1_db, LmixACPhaseA_);\n    }\n\n    // BC\n    {\n        pt::ptree& Lmix0_db = calphad_db.get_child(\"LmixBCPhaseL\");\n        readLmixBinary(Lmix0_db, LmixBCPhaseL_);\n\n        pt::ptree& Lmix1_db = calphad_db.get_child(\"LmixBCPhaseA\");\n        readLmixBinary(Lmix1_db, LmixBCPhaseA_);\n    }\n\n    // ABC\n    {\n        // default values\n        LmixABCPhaseL_[0][0] = 0.0;\n        LmixABCPhaseL_[0][1] = 0.0;\n        LmixABCPhaseL_[1][0] = 0.0;\n        LmixABCPhaseL_[1][1] = 0.0;\n        LmixABCPhaseL_[2][0] = 0.0;\n        LmixABCPhaseL_[2][1] = 0.0;\n\n        std::string dbnamemixL(\"LmixABCPhaseL\");\n        if (calphad_db.get_child_optional(dbnamemixL))\n        {\n            pt::ptree& Lmix0_db = calphad_db.get_child(dbnamemixL);\n            readLmixTernaryParameters(Lmix0_db, LmixABCPhaseL_);\n        }\n\n        assert(LmixABCPhaseL_[0][0] == LmixABCPhaseL_[0][0]);\n        assert(LmixABCPhaseL_[0][1] == LmixABCPhaseL_[0][1]);\n        assert(LmixABCPhaseL_[1][0] == LmixABCPhaseL_[1][0]);\n        assert(LmixABCPhaseL_[1][1] == LmixABCPhaseL_[1][1]);\n        assert(LmixABCPhaseL_[2][0] == LmixABCPhaseL_[2][0]);\n        assert(LmixABCPhaseL_[2][1] == LmixABCPhaseL_[2][1]);\n\n        std::string dbnamemixA(\"LmixABCPhaseA\");\n        // default values\n        LmixABCPhaseA_[0][0] = 0.0;\n        LmixABCPhaseA_[0][1] = 0.0;\n        LmixABCPhaseA_[1][0] = 0.0;\n        LmixABCPhaseA_[1][1] = 0.0;\n        LmixABCPhaseA_[2][0] = 0.0;\n        LmixABCPhaseA_[2][1] = 0.0;\n        if (calphad_db.get_child_optional(dbnamemixA))\n        {\n            pt::ptree& Lmix1_db = calphad_db.get_child(dbnamemixA);\n            readLmixTernaryParameters(Lmix1_db, LmixABCPhaseA_);\n        }\n\n        assert(LmixABCPhaseA_[0][0] == LmixABCPhaseA_[0][0]);\n        assert(LmixABCPhaseA_[0][1] == LmixABCPhaseA_[0][1]);\n        assert(LmixABCPhaseA_[1][0] == LmixABCPhaseA_[1][0]);\n        assert(LmixABCPhaseA_[1][1] == LmixABCPhaseA_[1][1]);\n        assert(LmixABCPhaseA_[2][0] == LmixABCPhaseA_[2][0]);\n        assert(LmixABCPhaseA_[2][1] == LmixABCPhaseA_[2][1]);\n    }\n\n    // print database just read\n    // std::clog << \"CALPHAD database...\" << std::endl;\n    // pt::write_json(std::clog, calphad_db);\n}\n\n//-----------------------------------------------------------------------\n\n#ifdef HAVE_OPENMP_OFFLOAD\n#pragma omp declare target\n#endif\n\ndouble CALPHADFreeEnergyFunctionsTernary::computeFreeEnergy(\n    const double temperature, const double* conc, const PhaseIndex pi,\n    const bool gp)\n{\n    const double conc0 = conc[0];\n    const double conc1 = conc[1];\n\n    CalphadDataType lAB[4]\n        = { lmix0ABPhase(pi, temperature), lmix1ABPhase(pi, temperature),\n              lmix2ABPhase(pi, temperature), lmix3ABPhase(pi, temperature) };\n    CalphadDataType lAC[4]\n        = { lmix0ACPhase(pi, temperature), lmix1ACPhase(pi, temperature),\n              lmix2ACPhase(pi, temperature), lmix3ACPhase(pi, temperature) };\n    CalphadDataType lBC[4]\n        = { lmix0BCPhase(pi, temperature), lmix1BCPhase(pi, temperature),\n              lmix2BCPhase(pi, temperature), lmix3BCPhase(pi, temperature) };\n\n    CalphadDataType lABC[3] = { lmix0ABCPhase(pi, temperature),\n        lmix1ABCPhase(pi, temperature), lmix2ABCPhase(pi, temperature) };\n\n    CALPHADSpeciesPhaseGibbsEnergy* g_species;\n\n    switch (pi)\n    {\n        case PhaseIndex::phaseL:\n            g_species = &g_species_phaseL_[0];\n            break;\n        case PhaseIndex::phaseA:\n            g_species = &g_species_phaseA_[0];\n            break;\n        default:\n            //            std::cout << \"CALPHADFreeEnergyFunctionsTernary::\"\n            //                         \"computeFreeEnergy(), undefined phase!!!\"\n            //                      << std::endl;\n            // abort();\n            return 0.;\n    }\n\n    double conc2 = 1. - conc0 - conc1;\n    double fe    = conc0 * g_species[0].fenergy(temperature)\n                + conc1 * g_species[1].fenergy(temperature)\n                + conc2 * g_species[2].fenergy(temperature)\n                + CALPHADcomputeFMixTernary(lAB, lAC, lBC, lABC, conc0, conc1)\n                + CALPHADcomputeFIdealMixTernary(\n                      gas_constant_R_JpKpmol * temperature, conc0, conc1);\n\n    // subtract -mu*c to get grand potential\n    if (gp)\n    {\n        double deriv[2];\n        computeDerivFreeEnergy(temperature, conc, pi, deriv);\n        fe -= deriv[0] * conc0;\n        fe -= deriv[1] * conc1;\n    }\n\n    return fe;\n}\n\n//=======================================================================\n\nvoid CALPHADFreeEnergyFunctionsTernary::computeDerivFreeEnergy(\n    const double temperature, const double* const conc, const PhaseIndex pi,\n    double* deriv)\n{\n    CalphadDataType lAB[4]\n        = { lmix0ABPhase(pi, temperature), lmix1ABPhase(pi, temperature),\n              lmix2ABPhase(pi, temperature), lmix3ABPhase(pi, temperature) };\n    CalphadDataType lAC[4]\n        = { lmix0ACPhase(pi, temperature), lmix1ACPhase(pi, temperature),\n              lmix2ACPhase(pi, temperature), lmix3ACPhase(pi, temperature) };\n    CalphadDataType lBC[4]\n        = { lmix0BCPhase(pi, temperature), lmix1BCPhase(pi, temperature),\n              lmix2BCPhase(pi, temperature), lmix3BCPhase(pi, temperature) };\n\n    CalphadDataType lABC[3] = { lmix0ABCPhase(pi, temperature),\n        lmix1ABCPhase(pi, temperature), lmix2ABCPhase(pi, temperature) };\n\n    CALPHADSpeciesPhaseGibbsEnergy* g_species;\n\n    switch (pi)\n    {\n        case PhaseIndex::phaseL:\n            g_species = &g_species_phaseL_[0];\n            break;\n        case PhaseIndex::phaseA:\n            g_species = &g_species_phaseA_[0];\n            break;\n        default:\n            //            std::cout << \"CALPHADFreeEnergyFunctionsTernary::\"\n            //                         \"computeFreeEnergy(), undefined phase!!!\"\n            //                      << std::endl;\n            // abort();\n            return;\n    }\n\n    CALPHADcomputeFMix_derivTernary(\n        lAB, lAC, lBC, lABC, conc[0], conc[1], deriv);\n\n    deriv[0] += g_species[0].fenergy(temperature);\n    deriv[0] -= g_species[2].fenergy(temperature);\n\n    deriv[1] += g_species[1].fenergy(temperature);\n    deriv[1] -= g_species[2].fenergy(temperature);\n\n    double tmp[2];\n    CALPHADcomputeFIdealMix_derivTernary(\n        gas_constant_R_JpKpmol * temperature, conc[0], conc[1], tmp);\n    deriv[0] += tmp[0];\n    deriv[1] += tmp[1];\n}\n\n//=======================================================================\n\nvoid CALPHADFreeEnergyFunctionsTernary::computeSecondDerivativeFreeEnergy(\n    const double temp, const double* const conc, const PhaseIndex pi,\n    double* d2fdc2)\n{\n    // assert(conc[0] >= 0.);\n    // assert(conc[0] <= 1.);\n    // assert(conc[1] >= 0.);\n    // assert(conc[1] <= 1.);\n\n    CalphadDataType lAB[4]  = { lmix0ABPhase(pi, temp), lmix1ABPhase(pi, temp),\n        lmix2ABPhase(pi, temp), lmix3ABPhase(pi, temp) };\n    CalphadDataType lAC[4]  = { lmix0ACPhase(pi, temp), lmix1ACPhase(pi, temp),\n        lmix2ACPhase(pi, temp), lmix3ACPhase(pi, temp) };\n    CalphadDataType lBC[4]  = { lmix0BCPhase(pi, temp), lmix1BCPhase(pi, temp),\n        lmix2BCPhase(pi, temp), lmix3BCPhase(pi, temp) };\n    CalphadDataType lABC[3] = { lmix0ABCPhase(pi, temp),\n        lmix1ABCPhase(pi, temp), lmix2ABCPhase(pi, temp) };\n    const double rt         = gas_constant_R_JpKpmol * temp;\n\n    double deriv1[4];\n    CALPHADcomputeFIdealMix_deriv2Ternary(rt, conc[0], conc[1], &deriv1[0]);\n\n    double deriv2[4];\n    CALPHADcomputeFMix_deriv2Ternary(\n        lAB, lAC, lBC, lABC, conc[0], conc[1], &deriv2[0]);\n\n    d2fdc2[0] = deriv1[0] + deriv2[0];\n    d2fdc2[1] = deriv1[1] + deriv2[1];\n    d2fdc2[2] = deriv1[2] + deriv2[2];\n    d2fdc2[3] = deriv1[3] + deriv2[3];\n}\n\n//=======================================================================\n\nvoid CALPHADFreeEnergyFunctionsTernary::computeTdependentParameters(\n    const double temperature, CalphadDataType* L_AB_L, CalphadDataType* L_AC_L,\n    CalphadDataType* L_BC_L, CalphadDataType* L_ABC_L, CalphadDataType* L_AB_S,\n    CalphadDataType* L_AC_S, CalphadDataType* L_BC_S, CalphadDataType* L_ABC_S,\n    CalphadDataType* fA, CalphadDataType* fB, CalphadDataType* fC)\n{\n    fA[0] = g_species_phaseL_[0].fenergy(temperature);\n    fB[0] = g_species_phaseL_[1].fenergy(temperature);\n    fC[0] = g_species_phaseL_[2].fenergy(temperature);\n\n    fA[1] = g_species_phaseA_[0].fenergy(temperature);\n    fB[1] = g_species_phaseA_[1].fenergy(temperature);\n    fC[1] = g_species_phaseA_[2].fenergy(temperature);\n\n    L_AB_L[0]  = lmix0ABPhaseL(temperature);\n    L_AB_L[1]  = lmix1ABPhaseL(temperature);\n    L_AB_L[2]  = lmix2ABPhaseL(temperature);\n    L_AB_L[3]  = lmix3ABPhaseL(temperature);\n    L_AC_L[0]  = lmix0ACPhaseL(temperature);\n    L_AC_L[1]  = lmix1ACPhaseL(temperature);\n    L_AC_L[2]  = lmix2ACPhaseL(temperature);\n    L_AC_L[3]  = lmix3ACPhaseL(temperature);\n    L_BC_L[0]  = lmix0BCPhaseL(temperature);\n    L_BC_L[1]  = lmix1BCPhaseL(temperature);\n    L_BC_L[2]  = lmix2BCPhaseL(temperature);\n    L_BC_L[3]  = lmix3BCPhaseL(temperature);\n    L_ABC_L[0] = lmix0ABCPhaseL(temperature);\n    L_ABC_L[1] = lmix1ABCPhaseL(temperature);\n    L_ABC_L[2] = lmix2ABCPhaseL(temperature);\n\n    L_AB_S[0]  = lmix0ABPhaseA(temperature);\n    L_AB_S[1]  = lmix1ABPhaseA(temperature);\n    L_AB_S[2]  = lmix2ABPhaseA(temperature);\n    L_AB_S[3]  = lmix3ABPhaseA(temperature);\n    L_AC_S[0]  = lmix0ACPhaseA(temperature);\n    L_AC_S[1]  = lmix1ACPhaseA(temperature);\n    L_AC_S[2]  = lmix2ACPhaseA(temperature);\n    L_AC_S[3]  = lmix3ACPhaseA(temperature);\n    L_BC_S[0]  = lmix0BCPhaseA(temperature);\n    L_BC_S[1]  = lmix1BCPhaseA(temperature);\n    L_BC_S[2]  = lmix2BCPhaseA(temperature);\n    L_BC_S[3]  = lmix3BCPhaseA(temperature);\n    L_ABC_S[0] = lmix0ABCPhaseA(temperature);\n    L_ABC_S[1] = lmix1ABCPhaseA(temperature);\n    L_ABC_S[2] = lmix2ABCPhaseA(temperature);\n\n    // assert(L_ABC_L[0] == L_ABC_L[0]);\n    // assert(fC[0] == fC[0]);\n}\n\n//=======================================================================\n\n// compute equilibrium concentrations in various phases for given temperature\nbool CALPHADFreeEnergyFunctionsTernary::computeCeqT(\n    const double temperature, double* ceq, const int maxits, const bool verbose)\n{\n    // if (verbose)\n    //    std::cout << \"CALPHADFreeEnergyFunctionsTernary::computeCeqT()\"\n    //              << std::endl;\n    // assert(temperature > 0.);\n\n    CalphadDataType L_AB_L[4];\n    CalphadDataType L_AC_L[4];\n    CalphadDataType L_BC_L[4];\n\n    CalphadDataType L_ABC_L[3];\n\n    CalphadDataType L_AB_S[4];\n    CalphadDataType L_AC_S[4];\n    CalphadDataType L_BC_S[4];\n\n    CalphadDataType L_ABC_S[3];\n\n    CalphadDataType fA[2];\n    CalphadDataType fB[2];\n    CalphadDataType fC[2];\n\n    computeTdependentParameters(temperature, L_AB_L, L_AC_L, L_BC_L, L_ABC_L,\n        L_AB_S, L_AC_S, L_BC_S, L_ABC_S, fA, fB, fC);\n\n    double RTinv = 1.0 / (gas_constant_R_JpKpmol * temperature);\n\n    CALPHADEqConcSolverTernary eq_solver;\n    eq_solver.setup(RTinv, L_AB_L, L_AC_L, L_BC_L, L_AB_S, L_AC_S, L_BC_S,\n        L_ABC_L, L_ABC_S, fA, fB, fC);\n    int ret = eq_solver.ComputeConcentration(ceq, newton_tol_, maxits);\n#ifndef HAVE_OPENMP_OFFLOAD\n    if (ret >= 0)\n    {\n        if (verbose)\n        {\n            std::cout << \"CALPHAD, c0 phase0=\" << ceq[0] << std::endl;\n            std::cout << \"CALPHAD, c1 phase0=\" << ceq[1] << std::endl;\n            std::cout << \"CALPHAD, c0 phase1=\" << ceq[2] << std::endl;\n            std::cout << \"CALPHAD, c1 phase1=\" << ceq[3] << std::endl;\n        }\n    }\n    else\n    {\n        std::cout << \"CALPHADFreeEnergyFunctionsTernary, WARNING: ceq \"\n                     \"computation did not converge\"\n                  << std::endl;\n    }\n#endif\n    return (ret >= 0);\n}\n\n//=======================================================================\n\nbool CALPHADFreeEnergyFunctionsTernary::computeTieLine(const double temperature,\n    const double c0, const double c1, double* ceq, const int maxits,\n    const bool verbose)\n{\n    CalphadDataType L_AB_L[4];\n    CalphadDataType L_AC_L[4];\n    CalphadDataType L_BC_L[4];\n\n    CalphadDataType L_ABC_L[3];\n\n    CalphadDataType L_AB_S[4];\n    CalphadDataType L_AC_S[4];\n    CalphadDataType L_BC_S[4];\n\n    CalphadDataType L_ABC_S[3];\n\n    CalphadDataType fA[2];\n    CalphadDataType fB[2];\n    CalphadDataType fC[2];\n\n    computeTdependentParameters(temperature, L_AB_L, L_AC_L, L_BC_L, L_ABC_L,\n        L_AB_S, L_AC_S, L_BC_S, L_ABC_S, fA, fB, fC);\n\n    double RTinv = 1.0 / (gas_constant_R_JpKpmol * temperature);\n\n    CALPHADTieLineConcSolverTernary eq_solver;\n    eq_solver.setup(c0, c1, RTinv, L_AB_L, L_AC_L, L_BC_L, L_AB_S, L_AC_S,\n        L_BC_S, L_ABC_L, L_ABC_S, fA, fB, fC);\n    int ret = eq_solver.ComputeConcentration(ceq, newton_tol_, newton_maxits_);\n#ifndef HAVE_OPENMP_OFFLOAD\n    if (ret >= 0)\n    {\n        if (verbose)\n        {\n            std::cout << \"CALPHAD, c0 phase0=\" << ceq[0] << std::endl;\n            std::cout << \"CALPHAD, c1 phase0=\" << ceq[1] << std::endl;\n            std::cout << \"CALPHAD, c0 phase1=\" << ceq[2] << std::endl;\n            std::cout << \"CALPHAD, c1 phase1=\" << ceq[3] << std::endl;\n        }\n    }\n    else\n    {\n        std::cout << \"CALPHADFreeEnergyFunctionsTernary, WARNING: ceq \"\n                     \"computation did not converge\"\n                  << std::endl;\n    }\n#endif\n    return (ret >= 0);\n}\n\n//=======================================================================\n\nvoid CALPHADFreeEnergyFunctionsTernary::computePhasesFreeEnergies(\n    const double temperature, const double* const hphi, const double conc0,\n    const double conc1, double& fl, double& fa)\n{\n    // std::cout<<\"CALPHADFreeEnergyFunctionsTernary::computePhasesFreeEnergies()\"<<endl;\n\n    double cauxilliary[4] = { conc0, conc1, conc0, conc1 };\n\n    CalphadDataType L_AB_L[4];\n    CalphadDataType L_AC_L[4];\n    CalphadDataType L_BC_L[4];\n\n    CalphadDataType L_ABC_L[3];\n\n    CalphadDataType L_AB_S[4];\n    CalphadDataType L_AC_S[4];\n    CalphadDataType L_BC_S[4];\n\n    CalphadDataType L_ABC_S[3];\n\n    CalphadDataType fA[2];\n    CalphadDataType fB[2];\n    CalphadDataType fC[2];\n\n    computeTdependentParameters(temperature, L_AB_L, L_AC_L, L_BC_L, L_ABC_L,\n        L_AB_S, L_AC_S, L_BC_S, L_ABC_S, fA, fB, fC);\n\n    double RTinv = 1.0 / (gas_constant_R_JpKpmol * temperature);\n    CALPHADConcSolverTernary solver;\n    solver.setup(conc0, conc1, hphi[0], RTinv, L_AB_L, L_AC_L, L_BC_L, L_AB_S,\n        L_AC_S, L_BC_S, L_ABC_L, L_ABC_S, fA, fB, fC);\n    int ret\n        = solver.ComputeConcentration(cauxilliary, newton_tol_, newton_maxits_);\n#ifndef HAVE_OPENMP_OFFLOAD\n    if (ret < 0)\n    {\n        std::cerr << \"ERROR in \"\n                     \"CALPHADFreeEnergyFunctionsTernary::\"\n                     \"computePhasesFreeEnergies() \"\n                     \"---\"\n                  << \"conc0=\" << conc0 << \", conc1=\" << conc1\n                  << \", hphi=\" << hphi[0] << std::endl;\n        abort();\n    }\n\n    assert(conc0 >= 0.);\n#endif\n    double concl[2] = { cauxilliary[0], cauxilliary[1] };\n    fl = computeFreeEnergy(temperature, &concl[0], PhaseIndex::phaseL, false);\n\n    double conca[2] = { cauxilliary[2], cauxilliary[3] };\n    fa = computeFreeEnergy(temperature, &conca[0], PhaseIndex::phaseA, false);\n}\n\n//-----------------------------------------------------------------------\n// output: x\nint CALPHADFreeEnergyFunctionsTernary::computePhaseConcentrations(\n    const double temperature, const double* const conc, const double* const phi,\n    double* x)\n{\n    // assert(conc[0] == conc[0]);\n    // assert(conc[1] == conc[1]);\n    // assert(x[0] >= 0.);\n    // assert(x[1] >= 0.);\n    // assert(x[0] <= 1.);\n    // assert(x[1] <= 1.);\n\n    const double conc0 = conc[0];\n    const double conc1 = conc[1];\n\n    const double RTinv = 1.0 / (gas_constant_R_JpKpmol * temperature);\n\n    CalphadDataType L_AB_L[4];\n    CalphadDataType L_AC_L[4];\n    CalphadDataType L_BC_L[4];\n\n    CalphadDataType L_ABC_L[3];\n\n    CalphadDataType L_AB_S[4];\n    CalphadDataType L_AC_S[4];\n    CalphadDataType L_BC_S[4];\n\n    CalphadDataType L_ABC_S[3];\n\n    CalphadDataType fA[2];\n    CalphadDataType fB[2];\n    CalphadDataType fC[2];\n\n    computeTdependentParameters(temperature, L_AB_L, L_AC_L, L_BC_L, L_ABC_L,\n        L_AB_S, L_AC_S, L_BC_S, L_ABC_S, fA, fB, fC);\n    // assert(fC[0] == fC[0]);\n\n    const double hphi = interp_func(conc_interp_func_type_, phi[0]);\n\n    // conc could be outside of [0.,1.] in a trial step\n    double c0 = conc0 >= 0. ? conc0 : 0.;\n    c0        = c0 <= 1. ? c0 : 1.;\n    double c1 = conc1 >= 0. ? conc1 : 0.;\n    c1        = c1 <= 1. ? c1 : 1.;\n\n    CALPHADConcSolverTernary solver;\n    solver.setup(c0, c1, hphi, RTinv, L_AB_L, L_AC_L, L_BC_L, L_AB_S, L_AC_S,\n        L_BC_S, L_ABC_L, L_ABC_S, fA, fB, fC);\n    int ret = solver.ComputeConcentration(x, newton_tol_, newton_maxits_);\n#ifndef HAVE_OPENMP_OFFLOAD\n    if (ret == -1)\n    {\n        std::cerr << \"ERROR, \"\n                     \"CALPHADFreeEnergyFunctionsTernary::\"\n                     \"computePhaseConcentrations() \"\n                     \"failed for conc0=\"\n                  << conc0 << \", conc1=\" << conc1 << \", hphi=\" << hphi\n                  << std::endl;\n    }\n#endif\n    return ret;\n}\n\n#ifdef HAVE_OPENMP_OFFLOAD\n#pragma omp end declare target\n#endif\n\n//-----------------------------------------------------------------------\n\nvoid CALPHADFreeEnergyFunctionsTernary::energyVsPhiAndC(\n    const double temperature, const double* const ceq, const bool found_ceq,\n    const double phi_well_scale, const int npts_phi, const int npts_c)\n{\n    std::clog << \"CALPHADFreeEnergyFunctionsTernary::energyVsPhiAndC()...\"\n              << std::endl;\n\n    const double* const ceqL = &ceq[0];\n    const double* const ceqS = &ceq[2];\n    // std::clog<<\"Input:\n    // \"<<ceq[0]<<\",\"<<ceq[1]<<\",\"<<ceq[2]<<\",\"<<ceq[3]<<endl;\n\n    double slopec = 0.;\n    double fc0    = 0.;\n    double fc1    = 0.;\n    if (found_ceq)\n    {\n        // compute slope of f between equilibrium concentrations\n        // to add slopec*conc to energy later on\n\n        fc0    = computeFreeEnergy(temperature, &ceqL[0], PhaseIndex::phaseL);\n        fc1    = computeFreeEnergy(temperature, &ceqS[0], PhaseIndex::phaseA);\n        slopec = -(fc1 - fc0) / (ceqL[1] - ceqL[0]);\n    }\n    std::clog << std::setprecision(8) << \"fc0: \" << fc0 << \"...\"\n              << \", fc1: \" << fc1 << \"...\" << std::endl;\n    std::clog << \"CALPHADFreeEnergyFunctionsTernary: Use slope: \" << slopec\n              << \"...\" << std::endl;\n\n    {\n        // reset cmin, cmax, deltac\n        double c0min = std::min(ceqL[0], ceqS[0]);\n        double c0max = std::max(ceqL[0], ceqS[0]);\n\n        double dc0     = c0max - c0min;\n        c0min          = std::max(0.25 * c0min, c0min - 0.25 * dc0);\n        c0max          = std::min(1. - 0.25 * (1. - c0max), c0max + 0.25 * dc0);\n        c0max          = std::max(c0max, c0min + dc0);\n        double deltac0 = (c0max - c0min) / (npts_c - 1);\n\n        double c1min = std::min(ceqL[1], ceqS[1]);\n        double c1max = std::max(ceqL[1], ceqS[1]);\n\n        double dc1     = c1max - c1min;\n        c1min          = std::max(0.25 * c1min, c1min - 0.25 * dc1);\n        c1max          = std::min(1. - 0.25 * (1. - c1max), c1max + 0.25 * dc1);\n        c1max          = std::max(c1max, c1min + dc1);\n        double deltac1 = (c1max - c1min) / (npts_c - 1);\n\n        std::clog << \"Range for c0: \" << c0min << \" to \" << c0max << std::endl;\n        std::clog << \"Range for c1: \" << c1min << \" to \" << c1max << std::endl;\n\n        std::ofstream tfile(fenergy_diag_filename_, std::ios::out);\n\n        printEnergyVsPhiHeader(temperature, npts_phi, npts_c, npts_c, c0min,\n            c0max, c1min, c1max, tfile);\n\n        for (int i0 = 0; i0 < npts_c; i0++)\n        {\n            int i1    = (1. - c0min - deltac0 * i0 - c1min) / deltac1;\n            int i1max = i1 < npts_c ? i1 : npts_c;\n            for (int i1 = 0; i1 < i1max; i1++)\n            {\n                double c[2] = { c0min + deltac0 * i0, c1min + deltac1 * i1 };\n                printEnergyVsPhi(\n                    c, temperature, phi_well_scale, npts_phi, tfile);\n            }\n        }\n    }\n}\n\n// Print out free energy as a function of phase\n// for given composition and temperature\n// File format: ASCII VTK, readble with Visit\nvoid CALPHADFreeEnergyFunctionsTernary::printEnergyVsPhiHeader(\n    const double temperature, const int nphi, const int nc0, const int nc1,\n    const double c0min, const double c0max, const double c1min,\n    const double c1max, std::ostream& os) const\n{\n    os << \"# vtk DataFile Version 2.0\" << std::endl;\n    os << \"Free energy [J/mol] at T=\" << temperature << std::endl;\n    os << \"ASCII\" << std::endl;\n    os << \"DATASET STRUCTURED_POINTS\" << std::endl;\n\n    os << \"DIMENSIONS   \" << nphi << \" \" << nc0 << \" \" << nc1 << std::endl;\n    double asp_ratio_c0 = (nc0 > 1) ? (c0max - c0min) / (nc0 - 1) : 1.;\n    double asp_ratio_c1 = (nc1 > 1) ? (c1max - c1min) / (nc1 - 1) : 1.;\n    os << \"ASPECT_RATIO \" << 1. / (nphi - 1) << \" \" << asp_ratio_c0 << \" \"\n       << asp_ratio_c1 << std::endl;\n    os << \"ORIGIN        0. \" << c0min << \" \" << c1min << std::endl;\n    os << \"POINT_DATA   \" << nphi * nc0 * nc1 << std::endl;\n    os << \"SCALARS energy float 1\" << std::endl;\n    os << \"LOOKUP_TABLE default\" << std::endl;\n}\n\n//=======================================================================\n\nvoid CALPHADFreeEnergyFunctionsTernary::printEnergyVsPhi(const double* conc,\n    const double temperature, const double phi_well_scale, const int npts,\n    std::ostream& os)\n{\n    // std::cout << \"CALPHADFreeEnergyFunctionsTernary::printEnergyVsPhi()...\"\n    // << std::endl;\n    const double dphi = 1.0 / (double)(npts - 1);\n\n    // os << \"# phi     f(phi)     for c=\" << conc\n    //           << \" and T=\" << temperature << std::endl;\n    for (int i = 0; i < npts; i++)\n    {\n        const double phi = i * dphi;\n\n        double e       = fchem(&phi, conc, temperature);\n        const double w = phi_well_scale * well_func(phi);\n\n        os << e + w << std::endl;\n    }\n    // os << std::endl;\n}\n\n//=======================================================================\n// compute free energy in [J/mol]\ndouble CALPHADFreeEnergyFunctionsTernary::fchem(\n    const double* const phi, const double* const conc, const double temperature)\n{\n    const double conc0 = conc[0];\n    const double conc1 = conc[1];\n\n    const double hcphi = interp_func(conc_interp_func_type_, phi[0]);\n\n    const double tol = 1.e-8;\n    double fl        = 0.;\n    double fa        = 0.;\n    if ((phi[0] > tol) & (phi[0] < 1. - tol))\n    {\n        computePhasesFreeEnergies(temperature, &hcphi, conc0, conc1, fl, fa);\n    }\n    else\n    {\n        // don't solve for phases concentrations, just compute energy\n        // in either phase\n        double conc[2] = { conc0, conc1 };\n        if (phi[0] <= tol)\n        {\n            fl = computeFreeEnergy(temperature, &conc[0], PhaseIndex::phaseL);\n        }\n        else\n        {\n            fa = computeFreeEnergy(temperature, &conc[0], PhaseIndex::phaseA);\n        }\n    }\n\n    const double hfphi = interp_func(energy_interp_func_type_, phi[0]);\n\n    return (1.0 - hfphi) * fl + hfphi * fa;\n}\n\n//=======================================================================\n\nvoid CALPHADFreeEnergyFunctionsTernary::printEnergyVsComposition(\n    const double temperature, std::ostream& os, const int npts)\n{\n    const double dc = 1.0 / (double)(npts - 1);\n\n    std::string name1(\"Fl\");\n    name1 += g_species_phaseL_[0].name();\n    name1 += g_species_phaseL_[2].name();\n    os << \"#\" << name1 << std::endl;\n    os << \"#phi=0, c1=0, temperature=\" << temperature << std::endl;\n    for (int i = 0; i < npts; i++)\n    {\n        double conc[2];\n        conc[0] = i * dc;\n        conc[1] = 0.;\n\n        const double phi = 0.;\n\n        double e = fchem(&phi, conc, temperature);\n        os << conc[0] << \"\\t\" << e << std::endl;\n    }\n    os << std::endl;\n\n    std::string name2(\"Fs\");\n    name2 += g_species_phaseA_[0].name();\n    name2 += g_species_phaseA_[2].name();\n    os << \"#\" << name2 << std::endl;\n    os << \"#phi=1, c1=0, temperature=\" << temperature << std::endl;\n    for (int i = 0; i < npts; i++)\n    {\n        double conc[2];\n        conc[0] = i * dc;\n        conc[1] = 0.;\n\n        const double phi = 1.;\n\n        double e = fchem(&phi, conc, temperature);\n        os << conc[0] << \"\\t\" << e << std::endl;\n    }\n    os << std::endl;\n\n    std::string name3(\"Fl\");\n    name3 += g_species_phaseL_[1].name();\n    name3 += g_species_phaseL_[2].name();\n    os << \"#\" << name3 << std::endl;\n    os << \"#phi=0, c0=0, temperature=\" << temperature << std::endl;\n    for (int i = 0; i < npts; i++)\n    {\n        double conc[2];\n        conc[0] = 0.;\n        conc[1] = i * dc;\n\n        const double phi = 0.;\n\n        double e = fchem(&phi, conc, temperature);\n        os << conc[1] << \"\\t\" << e << std::endl;\n    }\n    os << std::endl;\n\n    std::string name4(\"Fs\");\n    name4 += g_species_phaseA_[1].name();\n    name4 += g_species_phaseA_[2].name();\n    os << \"#\" << name4 << std::endl;\n    os << \"#phi=1, c0=0, temperature=\" << temperature << std::endl;\n    for (int i = 0; i < npts; i++)\n    {\n        double conc[2];\n        conc[0] = 0.;\n        conc[1] = i * dc;\n\n        const double phi = 1.;\n\n        double e = fchem(&phi, conc, temperature);\n        os << conc[1] << \"\\t\" << e << std::endl;\n    }\n    os << std::endl;\n\n    std::string name5(\"Fl\");\n    name5 += g_species_phaseL_[0].name();\n    name5 += g_species_phaseL_[1].name();\n    os << \"#\" << name5 << std::endl;\n    os << \"#phi=0, temperature=\" << temperature << std::endl;\n    for (int i = 0; i < npts; i++)\n    {\n        double conc[2];\n        conc[0] = i * dc;\n        conc[1] = 1. - i * dc;\n\n        const double phi = 0.;\n\n        double e = fchem(&phi, conc, temperature);\n        os << conc[0] << \"\\t\" << e << std::endl;\n    }\n    os << std::endl;\n\n    std::string name6(\"Fs\");\n    name6 += g_species_phaseA_[0].name();\n    name6 += g_species_phaseA_[1].name();\n    os << \"#\" << name6 << std::endl;\n    os << \"#phi=1, temperature=\" << temperature << std::endl;\n    for (int i = 0; i < npts; i++)\n    {\n        double conc[2];\n        conc[0] = i * dc;\n        conc[1] = 1. - i * dc;\n\n        const double phi = 1.;\n\n        double e = fchem(&phi, conc, temperature);\n        os << conc[0] << \"\\t\" << e << std::endl;\n    }\n    os << std::endl;\n}\n\nvoid CALPHADFreeEnergyFunctionsTernary::preRunDiagnostics(\n    const double T0, const double T1)\n{\n    std::ofstream os1(\"FlC0vsT.dat\", std::ios::out);\n    os1 << \"#Species 0, Phase L\" << std::endl;\n    g_species_phaseL_[0].plotFofT(os1, T0, T1);\n\n    std::ofstream os2(\"FlC1vsT.dat\", std::ios::out);\n    os2 << \"#Species 1, Phase L\" << std::endl;\n    g_species_phaseL_[1].plotFofT(os2, T0, T1);\n\n    std::ofstream os3(\"FlC2vsT.dat\", std::ios::out);\n    os3 << \"#Species 2, Phase L\" << std::endl;\n    g_species_phaseL_[2].plotFofT(os3, T0, T1);\n\n    std::ofstream os4(\"FsC0vsT.dat\", std::ios::out);\n    os4 << \"#Species 0, Phase A\" << std::endl;\n    g_species_phaseA_[0].plotFofT(os4, T0, T1);\n\n    std::ofstream os5(\"FsC1vsT.dat\", std::ios::out);\n    os5 << \"#Species 1, Phase A\" << std::endl;\n    g_species_phaseA_[1].plotFofT(os5, T0, T1);\n\n    std::ofstream os6(\"FsC2vsT.dat\", std::ios::out);\n    os6 << \"#Species 2, Phase A\" << std::endl;\n    g_species_phaseA_[2].plotFofT(os6, T0, T1);\n}\n}\n", "meta": {"hexsha": "4f90dcad80296f3f690fe28b07644fae71cd591a", "size": 31794, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/CALPHADFreeEnergyFunctionsTernary.cc", "max_stars_repo_name": "stvdwtt/Thermo4PFM", "max_stars_repo_head_hexsha": "5308b7c58c4b67ed98d2bd50469226b7d89da2b8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2022-01-21T17:39:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T21:00:24.000Z", "max_issues_repo_path": "src/CALPHADFreeEnergyFunctionsTernary.cc", "max_issues_repo_name": "stvdwtt/Thermo4PFM", "max_issues_repo_head_hexsha": "5308b7c58c4b67ed98d2bd50469226b7d89da2b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-21T16:51:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T16:51:52.000Z", "max_forks_repo_path": "src/CALPHADFreeEnergyFunctionsTernary.cc", "max_forks_repo_name": "stvdwtt/Thermo4PFM", "max_forks_repo_head_hexsha": "5308b7c58c4b67ed98d2bd50469226b7d89da2b8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-12-13T14:29:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T18:12:51.000Z", "avg_line_length": 33.931696905, "max_line_length": 89, "alphanum_fraction": 0.5780650437, "num_tokens": 9943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2948981631986741}}
{"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 \"graph_augment.hh\"\n#include <boost/graph/stoer_wagner_min_cut.hpp>\n\nusing namespace std;\nusing namespace boost;\nusing namespace graph_tool;\n\nstruct get_min_cut\n{\n    template <class Graph, class EdgeWeight, class PartMap>\n    void operator()(Graph& g, EdgeWeight eweight, PartMap part_map, double& mc) const\n    {\n        try\n        {\n            mc = stoer_wagner_min_cut(g, eweight, parity_map(part_map));\n        }\n        catch (bad_graph&)\n        {\n            throw ValueException(\"Graph has less than 2 vertices.\");\n        }\n    }\n\n};\n\ndouble min_cut(GraphInterface& gi, boost::any weight, boost::any part_map)\n{\n    double mc = 0;\n\n    typedef ConstantPropertyMap<size_t,GraphInterface::edge_t> cweight_t;\n\n    if (weight.empty())\n        weight = cweight_t(1);\n\n    typedef boost::mpl::push_back<writable_edge_scalar_properties, cweight_t>::type\n        weight_maps;\n\n    run_action<graph_tool::detail::never_directed>()\n        (gi, std::bind(get_min_cut(),  placeholders::_1,  placeholders::_2,\n                       placeholders::_3, std::ref(mc)),\n         weight_maps(), writable_vertex_scalar_properties())(weight, part_map);\n    return mc;\n}\n\nstruct do_get_residual_graph\n{\n    template <class Graph, class CapacityMap, class ResidualMap,\n              class AugmentedMap>\n    void operator()(Graph& g, CapacityMap capacity, ResidualMap res,\n                    AugmentedMap augmented) const\n    {\n        residual_graph(g, capacity, res, augmented);\n    }\n};\n\nvoid get_residual_graph(GraphInterface& gi, boost::any capacity,\n                        boost::any res, boost::any oaugment)\n{\n    typedef property_map_type::apply<uint8_t,\n                                     GraphInterface::edge_index_map_t>::type\n        emap_t;\n    emap_t augment = boost::any_cast<emap_t>(oaugment);\n    run_action<>()\n        (gi, std::bind(do_get_residual_graph(), placeholders::_1,\n                       placeholders::_2, placeholders::_3, augment),\n         edge_scalar_properties(), edge_scalar_properties())(capacity, res);\n}\n", "meta": {"hexsha": "400e3019ef2e072a62700ae429436cf6ba3e70f2", "size": 2918, "ext": "cc", "lang": "C++", "max_stars_repo_path": "graph-tool/src/graph/flow/graph_minimum_cut.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/flow/graph_minimum_cut.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/flow/graph_minimum_cut.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.1590909091, "max_line_length": 85, "alphanum_fraction": 0.6751199452, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2948981631986741}}
{"text": "// ---------------------------------------------------------------------\n//\n// Copyright (c) 2017 - 2019 by the IBAMR developers\n// All rights reserved.\n//\n// This file is part of IBAMR.\n//\n// IBAMR is free software and is distributed under the 3-clause BSD\n// license. The full text of the license can be found in the file\n// COPYRIGHT at the top level directory of IBAMR.\n//\n// ---------------------------------------------------------------------\n\n// Config files\n#include <IBAMR_config.h>\n#include <IBTK_config.h>\n\n#include <SAMRAI_config.h>\n\n// Headers for basic PETSc functions\n#include <petscsys.h>\n\n// Headers for basic SAMRAI objects\n#include <BergerRigoutsos.h>\n#include <CartesianGridGeometry.h>\n#include <LoadBalancer.h>\n#include <StandardTagAndInitialize.h>\n#include <VariableDatabase.h>\n\n// Headers for application-specific algorithm/data structure objects\n#include <ibamr/CIBMethod.h>\n#include <ibamr/CIBMobilitySolver.h>\n#include <ibamr/CIBSaddlePointSolver.h>\n#include <ibamr/CIBStaggeredStokesSolver.h>\n#include <ibamr/DirectMobilitySolver.h>\n#include <ibamr/IBExplicitHierarchyIntegrator.h>\n#include <ibamr/IBHydrodynamicForceEvaluator.h>\n#include <ibamr/IBStandardForceGen.h>\n#include <ibamr/IBStandardInitializer.h>\n#include <ibamr/INSStaggeredHierarchyIntegrator.h>\n#include <ibamr/INSStaggeredPressureBcCoef.h>\n#include <ibamr/KrylovMobilitySolver.h>\n#include <ibamr/app_namespaces.h>\n\n#include <ibtk/AppInitializer.h>\n#include <ibtk/LData.h>\n#include <ibtk/LDataManager.h>\n#include <ibtk/muParserCartGridFunction.h>\n#include <ibtk/muParserRobinBcCoefs.h>\n\n#include <boost/multi_array.hpp>\n\n//////////////////////////////////////////////////////////////////////////////\n\n// Center of mass velocity\nvoid\nConstrainedCOMOuterVel(double /*data_time*/, IBTK::Vector3d& U_com, IBTK::Vector3d& W_com, void* /*ctx*/)\n{\n    U_com.setZero();\n    W_com.setZero();\n    U_com[0] = 1.0;\n    U_com[1] = 2.0;\n    W_com[1] = 5.0;\n\n    return;\n} // ConstrainedCOMOuterVel\n\n// Center of mass velocity\nvoid\nConstrainedCOMInnerVel(double /*data_time*/, IBTK::Vector3d& U_com, IBTK::Vector3d& W_com, void* /*ctx*/)\n{\n    U_com.setZero();\n    W_com.setZero();\n    return;\n} // ConstrainedCOMInnerVel\n\nvoid\nConstrainedNodalVel(Vec /*U_k*/, const RigidDOFVector& /*U*/, const IBTK::Vector3d& /*X_com*/, void* /*ctx*/)\n{\n    // intentionally left blank.\n    return;\n} // ConstrainedNodalVel\n\n// These forces on the structure are computed when the \"above\" velocities are prescribed on them.\nvoid\nNetExternalForceTorqueOuter(double /*data_time*/, IBTK::Vector3d& F_ext, IBTK::Vector3d& T_ext, void* /*ctx*/)\n{\n    F_ext << 100.916, 1351.74, 0.000916801;\n    T_ext << -2.23858e-09, 58206.1, -1.12567e-09;\n\n    return;\n} // NetExternalForceTorqueOuter\n\nvoid\nNetExternalForceTorqueInner(double /*data_time*/, IBTK::Vector3d& F_ext, IBTK::Vector3d& T_ext, void* /*ctx*/)\n{\n    F_ext << -116.762, -201.82, -0.00128781;\n    T_ext << 1.46423e-09, -1393.33, 9.03505e-10;\n\n    return;\n} // NetExternalForceTorqueInner\n\n// Function prototypes\nvoid output_data(Pointer<PatchHierarchy<NDIM> > patch_hierarchy,\n                 LDataManager* l_data_manager,\n                 const int iteration_num,\n                 const double loop_time,\n                 const string& data_dump_dirname);\n\n/*******************************************************************************\n * For each run, the input filename and restart information (if needed) must   *\n * be given on the command line.  For non-restarted case, command line is:     *\n *                                                                             *\n *    executable <input file name>                                             *\n *                                                                             *\n * For restarted run, command line is:                                         *\n *                                                                             *\n *    executable <input file name> <restart directory> <restart number>        *\n *                                                                             *\n *******************************************************************************/\nint\nmain(int argc, char* argv[])\n{\n    // Initialize PETSc, MPI, and SAMRAI.\n    PetscInitialize(&argc, &argv, NULL, NULL);\n    SAMRAI_MPI::setCommunicator(PETSC_COMM_WORLD);\n    SAMRAI_MPI::setCallAbortInSerialInsteadOfExit();\n    SAMRAIManager::startup();\n    SAMRAIManager::setMaxNumberPatchDataEntries(2054);\n\n    { // cleanup dynamically allocated objects prior to shutdown\n\n        // Parse command line options, set some standard options from the input\n        // file, initialize the restart database (if this is a restarted run),\n        // and enable file logging.\n        Pointer<AppInitializer> app_initializer = new AppInitializer(argc, argv, \"CIB.log\");\n        Pointer<Database> input_db = app_initializer->getInputDatabase();\n\n        // Read default Petsc options\n        if (input_db->keyExists(\"petsc_options_file\"))\n        {\n            std::string petsc_options_file = input_db->getString(\"petsc_options_file\");\n            PetscOptionsInsertFile(PETSC_COMM_WORLD, NULL, petsc_options_file.c_str(), PETSC_TRUE);\n        }\n\n        // Get various standard options set in the input file.\n        const bool dump_viz_data = app_initializer->dumpVizData();\n        const int viz_dump_interval = app_initializer->getVizDumpInterval();\n        const bool uses_visit = dump_viz_data && !app_initializer->getVisItDataWriter().isNull();\n\n        const bool dump_restart_data = app_initializer->dumpRestartData();\n        const int restart_dump_interval = app_initializer->getRestartDumpInterval();\n        const string restart_dump_dirname = app_initializer->getRestartDumpDirectory();\n\n        const bool dump_postproc_data = app_initializer->dumpPostProcessingData();\n        const int postproc_data_dump_interval = app_initializer->getPostProcessingDataDumpInterval();\n        const string postproc_data_dump_dirname = app_initializer->getPostProcessingDataDumpDirectory();\n        if (dump_postproc_data && (postproc_data_dump_interval > 0) && !postproc_data_dump_dirname.empty())\n        {\n            Utilities::recursiveMkdir(postproc_data_dump_dirname);\n        }\n\n        const bool dump_timer_data = app_initializer->dumpTimerData();\n        const int timer_dump_interval = app_initializer->getTimerDumpInterval();\n\n        // Create major algorithm and data objects that comprise the\n        // application.  These objects are configured from the input database\n        // and, if this is a restarted run, from the restart database.\n\n        // INS integrator\n        Pointer<INSStaggeredHierarchyIntegrator> navier_stokes_integrator = new INSStaggeredHierarchyIntegrator(\n            \"INSStaggeredHierarchyIntegrator\",\n            app_initializer->getComponentDatabase(\"INSStaggeredHierarchyIntegrator\"));\n\n        // CIB method\n        const unsigned int num_structures = input_db->getIntegerWithDefault(\"num_structures\", 1);\n        Pointer<CIBMethod> ib_method_ops =\n            new CIBMethod(\"CIBMethod\", app_initializer->getComponentDatabase(\"CIBMethod\"), num_structures);\n\n        // Krylov solver for INS integrator that solves for [u,p,U,L]\n        Pointer<CIBStaggeredStokesSolver> CIBSolver =\n            new CIBStaggeredStokesSolver(\"CIBStaggeredStokesSolver\",\n                                         input_db->getDatabase(\"CIBStaggeredStokesSolver\"),\n                                         navier_stokes_integrator,\n                                         ib_method_ops,\n                                         \"SP_\");\n\n        // Register the Krylov solver with INS integrator\n        navier_stokes_integrator->setStokesSolver(CIBSolver);\n\n        Pointer<IBHierarchyIntegrator> time_integrator =\n            new IBExplicitHierarchyIntegrator(\"IBHierarchyIntegrator\",\n                                              app_initializer->getComponentDatabase(\"IBHierarchyIntegrator\"),\n                                              ib_method_ops,\n                                              navier_stokes_integrator);\n        Pointer<CartesianGridGeometry<NDIM> > grid_geometry = new CartesianGridGeometry<NDIM>(\n            \"CartesianGeometry\", app_initializer->getComponentDatabase(\"CartesianGeometry\"));\n        Pointer<PatchHierarchy<NDIM> > patch_hierarchy = new PatchHierarchy<NDIM>(\"PatchHierarchy\", grid_geometry);\n        Pointer<StandardTagAndInitialize<NDIM> > error_detector =\n            new StandardTagAndInitialize<NDIM>(\"StandardTagAndInitialize\",\n                                               time_integrator,\n                                               app_initializer->getComponentDatabase(\"StandardTagAndInitialize\"));\n        Pointer<BergerRigoutsos<NDIM> > box_generator = new BergerRigoutsos<NDIM>();\n        Pointer<LoadBalancer<NDIM> > load_balancer =\n            new LoadBalancer<NDIM>(\"LoadBalancer\", app_initializer->getComponentDatabase(\"LoadBalancer\"));\n        Pointer<GriddingAlgorithm<NDIM> > gridding_algorithm =\n            new GriddingAlgorithm<NDIM>(\"GriddingAlgorithm\",\n                                        app_initializer->getComponentDatabase(\"GriddingAlgorithm\"),\n                                        error_detector,\n                                        box_generator,\n                                        load_balancer);\n        // Configure the IB solver.\n        Pointer<IBStandardInitializer> ib_initializer = new IBStandardInitializer(\n            \"IBStandardInitializer\", app_initializer->getComponentDatabase(\"IBStandardInitializer\"));\n        ib_method_ops->registerLInitStrategy(ib_initializer);\n\n        // Specify structure kinematics\n        FreeRigidDOFVector outer_free_dofs, inner_free_dofs;\n\n        // Make some DOFs prescribed and some free.\n        outer_free_dofs << 0, 0, 1, 1, 1, 1;\n        inner_free_dofs << 1, 1, 0, 1, 1, 0;\n        ib_method_ops->setSolveRigidBodyVelocity(0, outer_free_dofs);\n        ib_method_ops->setSolveRigidBodyVelocity(1, inner_free_dofs);\n\n        ib_method_ops->registerConstrainedVelocityFunction(NULL, &ConstrainedCOMOuterVel, NULL, 0);\n        ib_method_ops->registerConstrainedVelocityFunction(NULL, &ConstrainedCOMInnerVel, NULL, 1);\n\n        ib_method_ops->registerExternalForceTorqueFunction(&NetExternalForceTorqueOuter, NULL, 0);\n        ib_method_ops->registerExternalForceTorqueFunction(&NetExternalForceTorqueInner, NULL, 1);\n\n        // Create initial condition specification objects.\n        Pointer<CartGridFunction> u_init = new muParserCartGridFunction(\n            \"u_init\", app_initializer->getComponentDatabase(\"VelocityInitialConditions\"), grid_geometry);\n        navier_stokes_integrator->registerVelocityInitialConditions(u_init);\n        Pointer<CartGridFunction> p_init = new muParserCartGridFunction(\n            \"p_init\", app_initializer->getComponentDatabase(\"PressureInitialConditions\"), grid_geometry);\n        navier_stokes_integrator->registerPressureInitialConditions(p_init);\n\n        // Set up visualization plot file writers.\n        Pointer<VisItDataWriter<NDIM> > visit_data_writer = app_initializer->getVisItDataWriter();\n        Pointer<LSiloDataWriter> silo_data_writer = app_initializer->getLSiloDataWriter();\n        if (uses_visit)\n        {\n            ib_initializer->registerLSiloDataWriter(silo_data_writer);\n            ib_method_ops->registerLSiloDataWriter(silo_data_writer);\n            ib_method_ops->registerVisItDataWriter(visit_data_writer);\n            time_integrator->registerVisItDataWriter(visit_data_writer);\n        }\n\n        // Create boundary condition specification objects (when necessary).\n        const IntVector<NDIM>& periodic_shift = grid_geometry->getPeriodicShift();\n        vector<RobinBcCoefStrategy<NDIM>*> u_bc_coefs(NDIM);\n        if (periodic_shift.min() > 0)\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                u_bc_coefs[d] = NULL;\n            }\n        }\n        else\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                const std::string bc_coefs_name = \"u_bc_coefs_\" + std::to_string(d);\n\n                const std::string bc_coefs_db_name = \"VelocityBcCoefs_\" + std::to_string(d);\n\n                Pointer<Database> bc_coefs_db = app_initializer->getComponentDatabase(bc_coefs_db_name);\n                u_bc_coefs[d] = new muParserRobinBcCoefs(bc_coefs_name, bc_coefs_db, grid_geometry);\n            }\n            navier_stokes_integrator->registerPhysicalBoundaryConditions(u_bc_coefs);\n        }\n\n        // Initialize hierarchy configuration and data on all patches.\n        time_integrator->initializePatchHierarchy(patch_hierarchy, gridding_algorithm);\n\n        // Set physical boundary operator used in spreading.\n        ib_method_ops->setVelocityPhysBdryOp(time_integrator->getVelocityPhysBdryOp());\n\n        // Register mobility matrices (if needed)\n        std::string mobility_solver_type = input_db->getString(\"MOBILITY_SOLVER_TYPE\");\n        if (mobility_solver_type == \"DIRECT\")\n        {\n            std::string mat_name1 = \"struct-1\";\n            std::string mat_name2 = \"struct-2\";\n            std::vector<std::vector<unsigned> > struct_ids1;\n            std::vector<std::vector<unsigned> > struct_ids2;\n            std::vector<unsigned> prototype_structs1;\n            std::vector<unsigned> prototype_structs2;\n\n            // Dense matrix\n            prototype_structs1.push_back(0);\n            prototype_structs2.push_back(1);\n\n            struct_ids1.push_back(prototype_structs1);\n            struct_ids2.push_back(prototype_structs2);\n\n            DirectMobilitySolver* direct_solvers = NULL;\n            CIBSolver->getSaddlePointSolver()->getCIBMobilitySolver()->getMobilitySolvers(NULL, &direct_solvers, NULL);\n\n            direct_solvers->registerMobilityMat(\n                mat_name1, prototype_structs1, EMPIRICAL, std::make_pair(LAPACK_SVD, LAPACK_SVD), 0);\n            direct_solvers->registerStructIDsWithMobilityMat(mat_name1, struct_ids1);\n\n            int next_proc = 0;\n            if (SAMRAI_MPI::getNodes() > 1) next_proc = 1;\n            direct_solvers->registerMobilityMat(\n                mat_name2, prototype_structs2, EMPIRICAL, std::make_pair(LAPACK_SVD, LAPACK_SVD), next_proc);\n            direct_solvers->registerStructIDsWithMobilityMat(mat_name2, struct_ids2);\n        }\n        navier_stokes_integrator->setStokesSolverNeedsInit();\n\n        // Set up the hydro force objects\n        double rho_fluid = input_db->getDouble(\"RHO\");\n        double mu_fluid = input_db->getDouble(\"MU\");\n        double start_time = time_integrator->getIntegratorTime();\n        Pointer<IBHydrodynamicForceEvaluator> hydro_force =\n            new IBHydrodynamicForceEvaluator(\"IBHydrodynamicForce\", rho_fluid, mu_fluid, start_time, true);\n\n        // Get the initial box position and velocity from input\n        const string init_hydro_force_box_out_db_name = \"InitHydroForceBox_0\";\n        IBTK::Vector3d box_X_lower_out, box_X_upper_out, box_init_vel_out;\n\n        input_db->getDatabase(init_hydro_force_box_out_db_name)\n            ->getDoubleArray(\"lower_left_corner\", &box_X_lower_out[0], 3);\n        input_db->getDatabase(init_hydro_force_box_out_db_name)\n            ->getDoubleArray(\"upper_right_corner\", &box_X_upper_out[0], 3);\n        input_db->getDatabase(init_hydro_force_box_out_db_name)\n            ->getDoubleArray(\"init_velocity\", &box_init_vel_out[0], 3);\n\n        const string init_hydro_force_box_in_db_name = \"InitHydroForceBox_1\";\n        IBTK::Vector3d box_X_lower_in, box_X_upper_in, box_init_vel_in;\n\n        input_db->getDatabase(init_hydro_force_box_out_db_name)\n            ->getDoubleArray(\"lower_left_corner\", &box_X_lower_in[0], 3);\n        input_db->getDatabase(init_hydro_force_box_out_db_name)\n            ->getDoubleArray(\"upper_right_corner\", &box_X_upper_in[0], 3);\n        input_db->getDatabase(init_hydro_force_box_out_db_name)\n            ->getDoubleArray(\"init_velocity\", &box_init_vel_in[0], 3);\n\n        // Register the control volumes\n        hydro_force->registerStructure(box_X_lower_out, box_X_upper_out, patch_hierarchy, box_init_vel_out, 0);\n        hydro_force->registerStructure(box_X_lower_in, box_X_upper_in, patch_hierarchy, box_init_vel_in, 1);\n\n        // Set up optional visualization of select boxes\n        hydro_force->registerStructurePlotData(visit_data_writer, patch_hierarchy, 0);\n        hydro_force->registerStructurePlotData(visit_data_writer, patch_hierarchy, 1);\n\n        // Set the origin of the torque evaluation\n        IBTK::Vector3d torque_origin_out, torque_origin_in;\n        input_db->getDatabase(init_hydro_force_box_out_db_name)\n            ->getDoubleArray(\"torque_origin\", &torque_origin_out[0], 3);\n        input_db->getDatabase(init_hydro_force_box_out_db_name)\n            ->getDoubleArray(\"torque_origin\", &torque_origin_in[0], 3);\n\n        hydro_force->setTorqueOrigin(torque_origin_out, 0);\n        hydro_force->setTorqueOrigin(torque_origin_in, 1);\n\n        // Deallocate initialization objects.\n        app_initializer.setNull();\n\n        // Print the input database contents to the log file.\n        plog << \"Input database:\\n\";\n        input_db->printClassData(plog);\n\n        // Get velocity and pressure variables from integrator\n        VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();\n\n        const Pointer<Variable<NDIM> > u_var = navier_stokes_integrator->getVelocityVariable();\n        const Pointer<VariableContext> u_ctx = navier_stokes_integrator->getCurrentContext();\n        const int u_idx = var_db->mapVariableAndContextToIndex(u_var, u_ctx);\n\n        const Pointer<Variable<NDIM> > p_var = navier_stokes_integrator->getPressureVariable();\n        const Pointer<VariableContext> p_ctx = navier_stokes_integrator->getCurrentContext();\n        const int p_idx = var_db->mapVariableAndContextToIndex(p_var, p_ctx);\n\n        // Write out initial visualization data.\n        int iteration_num = time_integrator->getIntegratorStep();\n        double loop_time = time_integrator->getIntegratorTime();\n\n        if (dump_viz_data && uses_visit)\n        {\n            pout << \"\\n\\nWriting visualization files...\\n\\n\";\n            time_integrator->setupPlotData();\n            visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time);\n            silo_data_writer->writePlotData(iteration_num, loop_time);\n        }\n        if (dump_postproc_data)\n        {\n            output_data(patch_hierarchy,\n                        ib_method_ops->getLDataManager(),\n                        iteration_num,\n                        loop_time,\n                        postproc_data_dump_dirname);\n        }\n\n        // Main time step loop.\n        double loop_time_end = time_integrator->getEndTime();\n        double current_time, new_time;\n        double dt = 0.0;\n\n        while (!MathUtilities<double>::equalEps(loop_time, loop_time_end) && time_integrator->stepsRemaining())\n        {\n            iteration_num = time_integrator->getIntegratorStep();\n            loop_time = time_integrator->getIntegratorTime();\n            current_time = loop_time;\n\n            pout << \"\\n\";\n            pout << \"+++++++++++++++++++++++++++++++++++++++++++++++++++\\n\";\n            pout << \"At beginning of timestep # \" << iteration_num << \"\\n\";\n            pout << \"Simulation time is \" << loop_time << \"\\n\";\n\n            dt = time_integrator->getMaximumTimeStepSize();\n            loop_time += dt;\n            new_time = loop_time;\n\n            pout << \"Advancing hierarchy by timestep size dt = \" << dt << \"\\n\";\n\n            if (time_integrator->atRegridPoint()) navier_stokes_integrator->setStokesSolverNeedsInit();\n            if (ib_method_ops->flagRegrid())\n            {\n                time_integrator->regridHierarchy();\n                navier_stokes_integrator->setStokesSolverNeedsInit();\n            }\n\n            // Update the location of the box for time n + 1\n            hydro_force->updateStructureDomain(IBTK::Vector3d::Zero(), dt, patch_hierarchy, 0);\n            hydro_force->updateStructureDomain(IBTK::Vector3d::Zero(), dt, patch_hierarchy, 1);\n\n            // Compute the momentum of u^n in box n+1 on the newest hierarchy\n            hydro_force->computeLaggedMomentumIntegral(\n                u_idx, patch_hierarchy, navier_stokes_integrator->getVelocityBoundaryConditions());\n\n            // Advance the hierarchy\n            time_integrator->advanceHierarchy(dt);\n\n            pout << \"\\n\\nNet rigid force and torque on structure 0 is : \\n\"\n                 << ib_method_ops->getNetRigidGeneralizedForce(0) << \"\\n\\n\";\n            pout << \"\\n\\nNet rigid force and torque on structure 1 is : \\n\"\n                 << ib_method_ops->getNetRigidGeneralizedForce(1) << \"\\n\\n\";\n\n            RDV U;\n            ib_method_ops->getNewRigidBodyVelocity(0, U);\n            pout << \"\\n\\nRigid body velocity of structure 0 is : \\n\" << U << \"\\n\\n\";\n            ib_method_ops->getNewRigidBodyVelocity(1, U);\n            pout << \"\\n\\nRigid body velocity of structure 1 is : \\n\" << U << \"\\n\\n\";\n\n            pout << \"\\n\";\n            pout << \"At end       of timestep # \" << iteration_num << \"\\n\";\n            pout << \"Simulation time is \" << loop_time << \"\\n\";\n            pout << \"+++++++++++++++++++++++++++++++++++++++++++++++++++\\n\";\n            pout << \"\\n\";\n\n            // Set the linear and angular momentum of the spheres (zero in Stokes flow)\n            IBTK::Vector3d Sphere_mom;\n            IBTK::Vector3d Sphere_ang_mom;\n            Sphere_mom.setZero();\n            Sphere_ang_mom.setZero();\n\n            // Store the new momenta of the sphere\n            hydro_force->updateStructureMomentum(Sphere_mom, Sphere_ang_mom, 0);\n            hydro_force->updateStructureMomentum(Sphere_mom, Sphere_ang_mom, 1);\n\n            // Evaluate hydrodynamic force on the sphere.\n            hydro_force->computeHydrodynamicForce(u_idx,\n                                                  p_idx,\n                                                  /*f_idx*/ -1,\n                                                  patch_hierarchy,\n                                                  dt,\n                                                  navier_stokes_integrator->getVelocityBoundaryConditions(),\n                                                  navier_stokes_integrator->getPressureBoundaryConditions());\n            // Post processing call for writing data\n            hydro_force->postprocessIntegrateData(current_time, new_time);\n\n            // Update optional visualization of select boxes\n            hydro_force->updateStructurePlotData(patch_hierarchy, 0);\n            hydro_force->updateStructurePlotData(patch_hierarchy, 1);\n\n            // At specified intervals, write visualization and restart files,\n            // print out timer data, and store hierarchy data for post\n            // processing.\n            iteration_num += 1;\n            const bool last_step = !time_integrator->stepsRemaining();\n            if (dump_viz_data && uses_visit && (iteration_num % viz_dump_interval == 0 || last_step))\n            {\n                pout << \"\\nWriting visualization files...\\n\\n\";\n                time_integrator->setupPlotData();\n                visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time);\n                silo_data_writer->writePlotData(iteration_num, loop_time);\n            }\n            if (dump_restart_data && (iteration_num % restart_dump_interval == 0 || last_step))\n            {\n                pout << \"\\nWriting restart files...\\n\\n\";\n                RestartManager::getManager()->writeRestartFile(restart_dump_dirname, iteration_num);\n            }\n            if (dump_timer_data && (iteration_num % timer_dump_interval == 0 || last_step))\n            {\n                pout << \"\\nWriting timer data...\\n\\n\";\n                TimerManager::getManager()->print(plog);\n            }\n            if (dump_postproc_data && (iteration_num % postproc_data_dump_interval == 0 || last_step))\n            {\n                output_data(patch_hierarchy,\n                            ib_method_ops->getLDataManager(),\n                            iteration_num,\n                            loop_time,\n                            postproc_data_dump_dirname);\n            }\n        }\n\n        // Cleanup boundary condition specification objects (when necessary).\n        for (unsigned int d = 0; d < NDIM; ++d) delete u_bc_coefs[d];\n\n    } // cleanup dynamically allocated objects prior to shutdown\n\n    SAMRAIManager::shutdown();\n    PetscFinalize();\n} // main\n\nvoid\noutput_data(Pointer<PatchHierarchy<NDIM> > /*patch_hierarchy*/,\n            LDataManager* /*l_data_manager*/,\n            const int iteration_num,\n            const double loop_time,\n            const string& /*data_dump_dirname*/)\n{\n    plog << \"writing hierarchy data at iteration \" << iteration_num << \" to disk\" << endl;\n    plog << \"simulation time is \" << loop_time << endl;\n\n    return;\n} // output_data\n", "meta": {"hexsha": "f6f9b468417ae823ef046e2ffce29e6d1c9dd754", "size": 25049, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/CIB/ex1/example.cpp", "max_stars_repo_name": "syam-s/IBAMR", "max_stars_repo_head_hexsha": "b6502f2f818835961d103fd2a2827d9336e68640", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-03T12:29:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-15T06:54:20.000Z", "max_issues_repo_path": "examples/CIB/ex1/example.cpp", "max_issues_repo_name": "syam-s/IBAMR", "max_issues_repo_head_hexsha": "b6502f2f818835961d103fd2a2827d9336e68640", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/CIB/ex1/example.cpp", "max_forks_repo_name": "syam-s/IBAMR", "max_forks_repo_head_hexsha": "b6502f2f818835961d103fd2a2827d9336e68640", "max_forks_repo_licenses": ["BSD-3-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.9962476548, "max_line_length": 119, "alphanum_fraction": 0.6284083197, "num_tokens": 5541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.2948898862989504}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n#include \"Mesh.h\"\n#include <cellogram/State.h>\n#include <cellogram/delaunay.h>\n#include <cellogram/load_points.h>\n#include <cellogram/convex_hull.h>\n#include <cellogram/delaunay.h>\n#include <cellogram/tri2hex.h>\n#include <cellogram/voronoi.h>\n#include <cellogram/vertex_degree.h>\n#include <cellogram/laplace_energy.h>\n#include <points_untangler/points_untangler.h>\n#include <igl/list_to_matrix.h>\n#include <igl/bounding_box.h>\n#include <igl/opengl/glfw/Viewer.h>\n#include <Eigen/Sparse>\n#include <fstream>\n////////////////////////////////////////////////////////////////////////////////\n\nnamespace cellogram {\n\n\tnamespace\n\t{\n\t\ttemplate<typename T>\n\t\tvoid removeRow(T& matrix, unsigned int rowToRemove)\n\t\t{\n\t\t\tunsigned int numRows = matrix.rows() - 1;\n\t\t\tunsigned int numCols = matrix.cols();\n\n\t\t\tif (rowToRemove < numRows)\n\t\t\t\tmatrix.block(rowToRemove, 0, numRows - rowToRemove, numCols) = matrix.bottomRows(numRows - rowToRemove);\n\n\t\t\tmatrix.conservativeResize(numRows, numCols);\n\t\t}\n\n\t\tvoid replaceTriangles(const Eigen::MatrixXi tNew, const Eigen::MatrixXi &to_remove, Eigen::MatrixXi &triangles)\n\t\t{\n\t\t\tstd::vector<int> removeIdx(to_remove.data(), to_remove.data() + to_remove.rows() * to_remove.cols());\n\t\t\tstd::sort(removeIdx.begin(), removeIdx.end());\n\t\t\t// remove all the triangles that connect to the internal of ROI\n\t\t\tfor (int i = removeIdx.size() - 1; i >= 0; i--)\n\t\t\t{\n\t\t\t\tremoveRow(triangles, removeIdx[i]);\n\t\t\t}\n\n\t\t\t//std::cout << tNew << \"\\n\\n\" << std::endl;\n\n\t\t\t// add new rows at the end of triangles\n\t\t\tEigen::MatrixXi tmp = triangles;\n\t\t\ttriangles.resize(triangles.rows() + tNew.rows(), triangles.cols());\n\n\t\t\ttriangles << tmp, tNew;\n\t\t}\n\n\t\ttemplate<typename Matrix>\n\t\tbool load_data(const std::string & path, Matrix & data_matrix)\n\t\t{\n\t\t\ttypedef typename Matrix::Scalar Scalar;\n\t\t\tstd::fstream file;\n\t\t\tfile.open(path);\n\n\t\t\tif (!file.good())\n\t\t\t{\n\t\t\t\tstd::cerr << \"Failed to open file : \" << path << std::endl;\n\t\t\t\tfile.close();\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tstd::string s;\n\t\t\tstd::vector<std::vector<Scalar>> matrix;\n\n\t\t\twhile (getline(file, s))\n\t\t\t{\n\t\t\t\tstd::stringstream input(s);\n\t\t\t\tdouble temp;\n\t\t\t\tmatrix.emplace_back();\n\n\t\t\t\tauto &currentLine = matrix.back();\n\n\t\t\t\twhile (input >> temp)\n\t\t\t\t\tcurrentLine.push_back(temp);\n\t\t\t}\n\n\t\t\tif (!igl::list_to_matrix(matrix, data_matrix))\n\t\t\t{\n\t\t\t\tstd::cerr << \"list to matrix error\" << std::endl;\n\t\t\t\tfile.close();\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\t}\n\n\n\tbool Mesh::load(const nlohmann::json &data)\n\t{\n\t\tparams = {};\n\t\tdetected.resize(0, 0); // detected (unmoved) point positions\n\t\tmoved.resize(0, 0); // manually moved\n\t\tpoints.resize(0, 0); // relaxed point positions\n\t\ttriangles.resize(0, 0); // triangular mesh\n\t\tadj.clear(); // adjaceny list of triangluar mesh\n\t\tvertex_to_tri.clear();\n\t\tboundary.resize(0); // list of vertices on the boundary\n\t\tvertex_status_fixed.resize(0);\n\n\t\tread_json_mat(data[\"detected\"], detected);\n\t\tread_json_mat(data[\"points\"], points);\n\t\tread_json_mat(data[\"moved\"], moved);\n\t\tread_json_mat(data[\"triangles\"], triangles);\n\n\t\tparams.load(data[\"params\"]);\n\n\t\tsolved_vertex.resize(points.rows(), 1);\n\t\tsolved_vertex.setConstant(false);\n\n\t\tadjacency_list(triangles, adj);\n\t\tgenerate_vertex_to_tri();\n\n\t\tvertex_status_fixed.resize(points.rows(), 1);\n\t\tvertex_status_fixed.setZero();\n\n\t\treturn true;\n\t}\n\n\n\t// bool Mesh::load(const std::string & path)\n\t// {\n\t// \tif (path.empty()) { return false; }\n\t// \t// clear previous\n\t// \tparams = {};\n\t// \tdetected.resize(0, 0); // detected (unmoved) point positions\n\t// \tmoved.resize(0, 0); // manually moved\n\t// \tpoints.resize(0, 0); // relaxed point positions\n\t// \ttriangles.resize(0, 0); // triangular mesh\n\t// \tadj.clear(); // adjaceny list of triangluar mesh\n\t// \tvertex_to_tri.clear();\n\t// \tboundary.resize(0); // list of vertices on the boundary\n\t// \tvertex_status_fixed.resize(0);\n\n\t// \t// Load data\n\t// \tload_data(path + \"/cellogram/detected.vert\", detected);\n\t// \tload_data(path + \"/cellogram/points.vert\", points);\n\t// \tload_data(path + \"/cellogram/moved.vert\", moved);\n\t// \tload_data(path + \"/cellogram/mesh.tri\", triangles);\n\n\t// \t// change when moved is also saved\n\t// \t//moved = detected;\n\n\t// \tparams.load(path + \"/cellogram/params.json\");\n\n\t// \tsolved_vertex.resize(points.rows(), 1);\n\t// \tsolved_vertex.setConstant(false);\n\n\t// \tadjacency_list(triangles, adj);\n\t// \tgenerate_vertex_to_tri();\n\n\t// \tvertex_status_fixed.resize(points.rows(), 1);\n\t// \tvertex_status_fixed.setZero();\n\n\t// \treturn true;\n\t// }\n\n\tvoid Mesh::relax_with_lloyd(const int lloyd_iterations, const Eigen::MatrixXd &hull_vertices,const Eigen::MatrixXi &hull_faces, const bool fix_regular_regions)\n\t{\n\t\t//reset the state\n\t\t//points = detected;\n\t\tpoints = moved;\n\t\tcompute_triangulation();\n\n\t\tEigen::VectorXi fixed_V;\n\t\tif (fix_regular_regions)\n\t\t{\n\t\t\tEigen::VectorXd energy;\n\t\t\tlaplace_energy(moved, triangles, energy);\n\t\t\t// Determine whether each vertex passes the criterium for bad mesh\n\t\t\tdouble avg = energy.mean();\n\n\t\t\t// Find the degree of each vertex\n\t\t\tEigen::VectorXi degree;\n\t\t\tvertex_degree(degree);\n\n\t\t\tEigen::Matrix<bool, 1, Eigen::Dynamic> low_energy(moved.rows());\n\t\t\tlow_energy.setConstant(false);\n\t\t\tint count = 0;\n\t\t\tfor (int i = 0; i < moved.rows(); i++)\n\t\t\t{\n\t\t\t\tif (energy(i) < 0.6*avg && degree(i) == 6)\n\t\t\t\t{\n\t\t\t\t\tlow_energy(i) = true;\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int i = 0; i < boundary.size(); i++)\n\t\t\t{\n\t\t\t\tlow_energy(boundary(i)) = true;\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\tfixed_V.resize(low_energy.size());\n\t\t\tcount = 0;\n\t\t\tfor (int i = 0; i < low_energy.size(); i++)\n\t\t\t{\n\t\t\t\tif (low_energy(i))\n\t\t\t\t{\n\t\t\t\t\tfixed_V(count) = i;\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t\t//check if the vertices were manually moved\n\t\t\t\telse if((moved.row(i) - detected.row(i)).squaredNorm() > 1.)\n\t\t\t\t{\n\t\t\t\t\tfixed_V(count) = i;\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfixed_V.conservativeResize(count);\n\t\t}\n\t\telse\n\t\t\tfixed_V = boundary;\n\n\t\tlloyd_relaxation(points, fixed_V, lloyd_iterations, hull_vertices, hull_faces);\n\t\tcompute_triangulation();\n\t}\n\n\tvoid Mesh::vertex_degree(Eigen::VectorXi & degree)\n\t{\n\t\tcellogram::vertex_degree(triangles, degree);\n\t}\n\n\tvoid Mesh::detect_vertices(const Eigen::MatrixXd &V, const DetectionParams &params)\n\t{\n\t\tdetected.resize(0, 0); // detected (unmoved) point positions\n\t\tpoints.resize(0, 0); // relaxed point positions\n\t\ttriangles.resize(0, 0); // triangular mesh\n\t\tadj.clear(); // adjaceny list of triangluar mesh\n\t\tvertex_to_tri.clear();\n\t\tboundary.resize(0); // list of vertices on the boundary\n\n\t\tif (V.size() == 0)\n\t\t\treturn;\n\n\t\tthis->params = params;\n\t\tdetected = V;\n\n\t\tmoved = detected;\n\t\tpoints = detected;\n\t\tvertex_status_fixed.resize(points.rows(), 1);\n\t\tvertex_status_fixed.setZero();\n\t\tsolved_vertex.resize(points.rows(), 1);\n\t\tsolved_vertex.setConstant(false);\n\n\n\t\tif (V.rows() < 3)\n\t\t\treturn;\n\n\t\t//loose_convex_hull(moved, boundary, 6); moved to compute_triangulation\n\t\tcompute_triangulation();\n\n\t\t// automatically load params if available\n\n\t}\n\n\tvoid Mesh::delete_vertex(const int index, bool recompute_triangulation)\n\t{\n\t\t// Delete vertex\n\t\tremoveRow(detected, index);\n\t\tremoveRow(moved, index);\n\t\tremoveRow(solved_vertex, index);\n\t\tremoveRow(vertex_status_fixed, index);\n\n\t\t// Delete entry in params\n\t\tif (params.A.size() > 0)\n\t\t{\n\t\t\tparams.remove_index(index);\n\t\t}\n\n\t\tfor (int i = 0; i < boundary.size(); ++i)\n\t\t{\n\t\t\tif (boundary(i) > index)\n\t\t\t\t--boundary(i);\n\t\t}\n\t\tfor (int i = 0; i < added_by_untangler.size(); ++i)\n\t\t{\n\t\t\tif (added_by_untangler(i) == index){\n\t\t\t\tremoveRow(added_by_untangler, index);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tfor (int i = 0; i < added_by_untangler.size(); ++i)\n\t\t{\n\t\t\tif (added_by_untangler(i) > index)\n\t\t\t\t--added_by_untangler(i);\n\t\t}\n\t\tif (recompute_triangulation)\n\t\t{\n\t\t\treset();\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// delete from points\n\t\t\tremoveRow(points, index);\n\n\t\t\t// delete triangles\n\t\t\tstd::vector<int> ind;\n\t\t\tind = vertex_to_tri[index];\n\t\t\tstd::sort(ind.begin(), ind.end());\n\n\t\t\tfor (int i = ind.size()-1; i >= 0; i--)\n\t\t\t{\n\t\t\t\tremoveRow(triangles,ind[i]);\n\t\t\t}\n\t\t\t// lower index of values higher than index\n\t\t\tfor (int i = 0; i < triangles.rows(); i++)\n\t\t\t{\n\t\t\t\tfor (int j = 0; j < triangles.cols(); j++)\n\t\t\t\t{\n\t\t\t\t\tif (triangles(i, j) > index)\n\t\t\t\t\t\ttriangles(i, j) = triangles(i, j) - 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tadjacency_list(triangles, adj);\n\t\t\tgenerate_vertex_to_tri();\n\t\t}\n\t}\n\n\tvoid Mesh::add_vertex(Eigen::Vector3d & new_point, bool must_reset)\n\t{\n\t\t// Check if vertex already exists\n\t\tEigen::MatrixXd tmp = detected.rowwise() - new_point.transpose();\n\t\tEigen::MatrixXd d = tmp.rowwise().norm();\n\t\tif (d.minCoeff() == 0)\n\t\t{\n\t\t\t// point is a duplicate\n\t\t\treturn;\n\t\t}\n\n\t\t// Add vertex\n\t\t{\n\t\t\tEigen::MatrixXd tmp(detected.rows() + 1, detected.cols());\n\t\t\ttmp.block(0, 0, detected.rows(), detected.cols()) = detected;\n\t\t\ttmp.row(detected.rows()) = new_point.transpose();\n\t\t\tdetected = tmp;\n\t\t}\n\t\t// Add vertex to moved\n\t\t{\n\t\t\tEigen::MatrixXd tmp(moved.rows() + 1, moved.cols());\n\t\t\ttmp.block(0, 0, moved.rows(), moved.cols()) = moved;\n\t\t\ttmp.row(moved.rows()) = new_point.transpose();\n\t\t\tmoved = tmp;\n\t\t}\n\t\t// Add new entry to solved_vertex\n\t\tEigen::Matrix<bool, Eigen::Dynamic,1> tmp_bool;\n\t\ttmp_bool.resize(solved_vertex.rows()+1);\n\t\ttmp_bool.block(0, 0, solved_vertex.rows(), solved_vertex.cols()) = solved_vertex;\n\t\ttmp_bool(solved_vertex.rows()) = false;\n\t\tsolved_vertex = tmp_bool;\n\n\t\t// Add new entry to vertex_status_fixed\n\t\tEigen::MatrixXi tmp_i;\n\t\ttmp_i.resize(vertex_status_fixed.rows() + 1, vertex_status_fixed.cols());\n\t\ttmp_i.block(0, 0, vertex_status_fixed.rows(), vertex_status_fixed.cols()) = vertex_status_fixed;\n\t\ttmp_i(vertex_status_fixed.rows()) = 0;\n\t\tvertex_status_fixed = tmp_i;\n\n\t\t// Add zero row to params\n\t\tparams.push_back_const(0);\n\n\t\tif(must_reset)\n\t\t\treset();\n\t}\n\n\tvoid Mesh::local_update(Eigen::VectorXi &local2global, const int global_to_remove, Eigen::MatrixXi & new_triangles)\n\t{\n\t\t//decide if to remove is local or global (better local)\n\t\t//remove vertex to_remove from points detected params (ie fix the existing method) delete_vertex(local2global(local_to_remove), false); and update triangulation and the local2global important\n\t\tdelete_vertex(global_to_remove, false);\n\t\tEigen::MatrixXi tGlobal = Eigen::MatrixXi(new_triangles.rows(), 3);\n\t\tfor (int i = 0; i < new_triangles.rows(); i++)\n\t\t{\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tconst int gindex = local2global(new_triangles(i, j));\n\t\t\t\tassert(gindex != global_to_remove);\n\t\t\t\ttGlobal(i, j) = gindex -(gindex >= global_to_remove ? 1 : 0);\n\t\t\t}\n\n\t\t}\n\n\t\tEigen::MatrixXi tmp = triangles;\n\t\ttriangles.resize(triangles.rows() + tGlobal.rows(), triangles.cols());\n\n\t\ttriangles << tmp, tGlobal;\n\n\t\tadjacency_list(triangles, adj);\n\t\tgenerate_vertex_to_tri();\n\t}\n\n\tvoid Mesh::update_triangles_from_split(const Eigen::VectorXi & t_ind_old, const  Eigen::MatrixXi & t1, const Eigen::MatrixXi & t2)\n\t{\n\t\t// first remove all the old triangles\n\t\tfor (int i = t_ind_old.size()-1; i >= 0; i--)\n\t\t{\n\t\t\tremoveRow(triangles, t_ind_old(i));\n\t\t}\n\n\t\tint nT = triangles.rows();\n\n\t\t// append the new triangles and return their indices in triangle\n\t\tint index = triangles.rows();\n\n\t\ttriangles.conservativeResize(triangles.rows() + t1.rows() + t2.rows(), 3);\n\t\tif (t1.size() > 0)\n\t\t{\n\t\t\ttriangles.block(index, 0, t1.rows(), 3) = t1;\n\t\t\tindex += t1.rows();\n\t\t}\n\t\tif (t2.size() > 0)\n\t\t{\n\t\t\ttriangles.block(index, 0, t2.rows(), 3) = t2;\n\t\t\tindex += t2.rows();\n\t\t}\n\t\tassert(index == triangles.rows());\n\t\tadjacency_list(triangles, adj);\n\t\tgenerate_vertex_to_tri();\n\t}\n\n\tvoid Mesh::mark_vertex_as_solved(const Eigen::VectorXi & region_interior)\n\t{\n\t\tfor (int i = 0; i < region_interior.size(); i++)\n\t\t{\n\t\t\tsolved_vertex(region_interior(i)) = true;\n\t\t}\n\t}\n\n\tvoid Mesh::get_physical_bounding_box(double scaling, Eigen::Vector2d & min, Eigen::Vector2d & max) const\n\t{\n\t\tEigen::RowVector3d maxVal = points.colwise().maxCoeff();\n\t\tEigen::RowVector3d minVal = points.colwise().minCoeff();\n\n\t\tmax = maxVal.block<1,2>(0, 0)*scaling;\n\t\tmin = minVal.block<1,2>(0, 0)*scaling;\n\n\t\t// std::cout << \"max:\\n\" << max << \"\\n\\nmin:\\n\" << min << std::endl;\n\t}\n\n\tvoid Mesh::get_background_mesh(double scaling, Eigen::MatrixXd &V, Eigen::MatrixXi &F, Eigen::VectorXd &S, double padding) const {\n\t\tEigen::MatrixXd BV;\n\t\tEigen::MatrixXi BF;\n\t\tV = points.leftCols<2>();\n\t\tigl::bounding_box(V, padding / scaling, BV, BF);\n\t\tassert(BV.rows() == 4);\n\n\t\tV.resize(points.rows() + BV.rows(), 2);\n\t\tV.topRows(points.rows()) = points.leftCols<2>();\n\t\tV.bottomRows(BV.rows()) = BV;\n\n\t\tdelaunay_triangulation(V, F);\n\t\tV *= scaling;\n\n\t\tS.resize(V.rows());\n\t\tS.head(points.rows()) = (detected - points).rowwise().norm() * scaling;\n\t\tS.tail(BV.rows()).setZero();\n\t}\n\n\tvoid Mesh::local_update(Eigen::VectorXi & local2global, Eigen::MatrixXd & new_points, Eigen::MatrixXi & new_triangles, Eigen::VectorXi & old_triangles)\n\t{\n\t\tfor (int i = 0; i < local2global.size(); i++)\n\t\t{\n\t\t\tconst int global_index = local2global(i);\n\t\t\tpoints.row(global_index) = new_points.row(i);\n\n\t\t}\n\n\t\tEigen::MatrixXi tGlobal = Eigen::MatrixXi(new_triangles.rows(), 3);\n\t\tfor (int i = 0; i < new_triangles.rows(); i++)\n\t\t{\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\ttGlobal(i, j) = local2global(new_triangles(i, j));\n\t\t\t}\n\n\t\t}\n\n\t\treplaceTriangles(tGlobal, old_triangles, triangles);\n\n\t\tadjacency_list(triangles, adj);\n\t\tgenerate_vertex_to_tri();\n\t}\n\n\tvoid Mesh::final_relax(const Eigen::VectorXi & expanded_boundary)\n\t{\n\t\tint n = points.rows();\n\t\t////Find vertices that have lower connectivity than 6\n\n\t\tEigen::VectorXi neighCount;\n\t\tvertex_degree(neighCount);\n\n\t\t// Determine fixed vertices based on connectivity and bounding box\n\t\tEigen::VectorXi indFixed = Eigen::VectorXi::Zero(n);\n\n\t\tfor (size_t i = 0; i < n; i++)\n\t\t{\n\t\t\tif (neighCount(i) != 6)\n\t\t\t{\n\t\t\t\tindFixed(i) = 1;\n\t\t\t}\n\t\t}\n\n\t\t// fix vertices on the boundary and the ones connected to the boundary\n\t\tfor (size_t i = 0; i < expanded_boundary.rows(); i++)\n\t\t{\n\t\t\tindFixed(expanded_boundary(i)) = 1;\n\t\t}\n\n\t\t//////PLEASE USE ME\n\t\t//igl::opengl::glfw::Viewer viewer;\n\n\t\t//viewer.data().set_mesh(points, triangles);\n\t\t//Eigen::MatrixXd cc(n, 3);\n\t\t//for (int i = 0; i < indFixed.rows(); ++i) {\n\t\t//\tif(indFixed(i) == 1)\n\t\t//\t\tcc.row(i) = Eigen::RowVector3d(1, 0, 0);\n\t\t//\telse\n\t\t//\t\tcc.row(i) = Eigen::RowVector3d(0, 0, 0);\n\t\t//}\n\t\t//viewer.data().set_points(points, cc);\n\t\t//viewer.data().point_size = float(8);\n\t\t//viewer.core.set_rotation_type(igl::opengl::ViewerCore::RotationType::ROTATION_TYPE_NO_ROTATION);\n\t\t//viewer.core.orthographic = true;\n\t\t//viewer.core.is_animating = true;\n\t\t//viewer.launch();\n\n\n\t\t// Rearrange coordinates and triangle indices to have free vertices first...\n\t\t//MatrixXd xRearranged = MatrixXd::Zero(n, 1);\n\t\tEigen::SparseVector<double> xRearranged(n);\n\t\tEigen::SparseVector<double> yRearranged(n);\n\t\tEigen::VectorXi indicesMapping = Eigen::VectorXi::Zero(n);\n\t\tEigen::MatrixXi trianglesRearranged = Eigen::MatrixXi::Zero(triangles.rows(), 3);\n\n\n\t\tint c = 0;\n\t\tfor (size_t i = 0; i < n; i++)\n\t\t{\n\t\t\tif (indFixed(i) == 0)\n\t\t\t{\n\t\t\t\tindicesMapping(i) = c;\n\t\t\t\txRearranged.fill(c) = points(i, 0);\n\t\t\t\tyRearranged.fill(c) = points(i, 1);\n\n\t\t\t\tc++;\n\t\t\t}\n\t\t}\n\t\tint nFree = c;\n\n\t\t// and then the fixed vertices\n\t\tfor (size_t i = 0; i < n; i++)\n\t\t{\n\t\t\tif (indFixed(i) == 1)\n\t\t\t{\n\t\t\t\tindicesMapping(i) = c;\n\t\t\t\txRearranged.fill(c) = points(i, 0);\n\t\t\t\tyRearranged.fill(c) = points(i, 1);\n\n\t\t\t\tc++;\n\t\t\t}\n\t\t}\n\n\t\t// rearrange triangles such that it is congruent with the newly arranged coordinates\n\t\tfor (size_t j = 0; j < triangles.rows(); j++)\n\t\t{\n\t\t\tfor (size_t k = 0; k < 3; k++)\n\t\t\t{\n\t\t\t\ttrianglesRearranged(j, k) = indicesMapping(triangles(j, k));\n\t\t\t}\n\t\t}\n\n\t\t// Generate Laplacian\n\t\tEigen::VectorXd diag = Eigen::VectorXd::Zero(n);\n\t\tEigen::SparseMatrix<double> L(n, n);\n\t\ttypedef Eigen::Triplet<int> Trip;\n\t\tstd::vector< Trip > tripletList;\n\t\ttripletList.reserve(n * 7);\n\n\t\tfor (size_t i = 0; i < trianglesRearranged.rows(); i++)\n\t\t{\n\t\t\tfor (size_t j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\ttripletList.push_back(Trip(trianglesRearranged(i, j), trianglesRearranged(i, (j + 1) % 3), -1));\n\t\t\t\ttripletList.push_back(Trip(trianglesRearranged(i, (j + 1) % 3), trianglesRearranged(i, j), -1));\n\t\t\t\tdiag(trianglesRearranged(i, j))++;\n\t\t\t}\n\t\t}\n\n\t\tfor (size_t i = 0; i < diag.rows(); i++)\n\t\t{\n\t\t\ttripletList.push_back(Trip(i, i, diag(i)));\n\t\t}\n\n\t\tL.setFromTriplets(tripletList.begin(), tripletList.end());\n\n\t\t// Force all non-zeros to be one\n\t\tfor (int k = 0; k<L.outerSize(); ++k)\n\t\t{\n\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(L, k); it; ++it)\n\t\t\t{\n\t\t\t\tif (it.value() < 0)\n\t\t\t\t{\n\t\t\t\t\tL.coeffRef(it.row(), it.col()) = -1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Solve for xNew and yNew\n\t\tEigen::SparseMatrix<double>  Li = L.block(0, 0, nFree, nFree);\n\t\tEigen::SparseMatrix<double>  Lb = L.block(0, nFree, nFree, L.rows() - nFree);\n\n\t\t//SparseMatrix<int>  Lii = Li.inverse();\n\t\tEigen::SimplicialLDLT<Eigen::SparseMatrix<double> > solver;\n\t\tsolver.compute(Li);\n\t\tif (solver.info() != Eigen::Success) {\n\t\t\t// decomposition failed\n\t\t\treturn;\n\t\t}\n\n\t\tEigen::SparseVector<double> xB(L.rows() - nFree);\n\t\tEigen::SparseVector<double> yB(L.rows() - nFree);\n\t\tfor (size_t i = 0; i < L.rows() - nFree; i++)\n\t\t{\n\t\t\txB.fill(i) = xRearranged.coeffRef(nFree + i);\n\t\t\tyB.fill(i) = yRearranged.coeffRef(nFree + i);\n\t\t}\n\t\tEigen::SparseVector<double> tmp = -Lb * xB;\n\n\t\tEigen::VectorXd xNew = solver.solve(Eigen::VectorXd(tmp));\n\n\t\ttmp = -Lb * yB;\n\t\tEigen::VectorXd yNew = solver.solve(Eigen::VectorXd(tmp));\n\n\t\t// Overwrite the free vertices of xRearranged and yRearranged\n\t\tfor (size_t i = 0; i < nFree; i++)\n\t\t{\n\t\t\txRearranged.coeffRef(i) = xNew(i);\n\t\t\tyRearranged.coeffRef(i) = yNew(i);\n\t\t}\n\n\t\t// use indices mapping to overwrite \"points\" with the newly calculated coordinates\n\t\tfor (size_t i = 0; i < indicesMapping.rows(); i++)\n\t\t{\n\t\t\tpoints(i,0) = xRearranged.coeffRef(indicesMapping(i));\n\t\t\tpoints(i,1) = yRearranged.coeffRef(indicesMapping(i));\n\t\t}\n\t}\n\n\tvoid Mesh::generate_vertex_to_tri()\n\t{\n\t\tvertex_to_tri.clear();\n\t\tvertex_to_tri.resize(points.rows());\n\n\t\tfor (int f = 0; f < triangles.rows(); ++f) {\n\t\t\tfor (int lv = 0; lv < triangles.cols(); ++lv)\n\t\t\t{\n\t\t\t\tconst int v_index = triangles(f, lv);\n\t\t\t\tvertex_to_tri[v_index].push_back(f);\n\t\t\t}\n\t\t}\n\t}\n\n\tbool Mesh::untangle()\n\t{\n\t\tbool has_changed_points = false;\n\t\ttriangles.resize(0, 0); // triangular mesh\n\t\tadj.clear(); // adjaceny list of triangluar mesh\n\t\tvertex_to_tri.clear();\n\n\t\tadded_by_untangler.resize(0);\n\t\tdeleted_by_untangler.resize(0, 0);\n\n\t\tEigen::MatrixXd newPts;\n\t\tstd::vector<int> dropped;\n\t\t// std::cout<<points<<std::endl;\n\t\tcellogram::PointsUntangler::pointsUntangler(moved, triangles, dropped, newPts);\n\t\t// assert(moved.rows() - dropped.size() + newPts.rows() == triangles.maxCoeff() - 1);\n\n\t\tif (newPts.rows() > 0 || !dropped.empty())\n\t\t{\n\t\t\thas_changed_points = true;\n\t\t}\n\n\t\tint old_size = added_by_untangler.size();\n\t\tadded_by_untangler.conservativeResize(old_size + newPts.rows());\n\n\t\tfor (int i = 0; i < newPts.rows(); ++i) {\n\n\t\t\tEigen::Vector3d tmp; tmp.setZero();\n\t\t\tfor (int j = 0; j < newPts.cols(); ++j)\n\t\t\t\ttmp(j) = newPts(i, j);\n\n\t\t\tadded_by_untangler(old_size + i) = detected.rows();\n\t\t\tadd_vertex(tmp, false);\n\t\t}\n\t\tpoints = moved;\n\n\t\tsolved_vertex.setConstant(false);\n\t\tvertex_status_fixed.setZero();\n\n\t\t//Now mesh is valid, but it has to many points....\n\t\tgenerate_vertex_to_tri();\n\n\t\told_size = deleted_by_untangler.size();\n\t\tdeleted_by_untangler.conservativeResize(old_size + dropped.size(), moved.cols());\n\t\tstd::sort(dropped.begin(), dropped.end());\n\n\n\t\tfor (int i = dropped.size() - 1; i >= 0; i--)\n\t\t{\n\t\t\tconst int gid = dropped[i];\n\t\t\tdeleted_by_untangler.row(old_size++) = moved.row(gid);\n\t\t\tdelete_vertex(gid, false);\n\t\t}\n\n\t\tassert(triangles.maxCoeff() < points.rows());\n\t\tassert(triangles.minCoeff() >= 0);\n\n\t\tadjacency_list(triangles, adj);\n\t\tgenerate_vertex_to_tri();\n\n\t\treturn has_changed_points;\n\t}\n\n\tvoid Mesh::clear()\n\t{\n\t\tdetected.resize(0, 0); // detected (unmoved) point positions\n\t\tmoved.resize(0, 0); // relaxed point positions\n\t\tpoints.resize(0, 0); // relaxed point positions\n\t\ttriangles.resize(0, 0); // triangular mesh\n\t\tadj.clear(); // adjaceny list of triangluar mesh\n\t\tvertex_to_tri.clear();\n\t\tboundary.resize(0); // list of vertices on the boundary\n\n\t\tsolved_vertex.resize(0);\n\t\tvertex_status_fixed.resize(0);\n\t\tadded_by_untangler.resize(0);\n\t\tdeleted_by_untangler.resize(0, 0);\n\n\t\tparams.clear();\n\t}\n\n\n\tvoid Mesh::save(nlohmann::json &data)\n\t{\n\t\tdata[\"detected\"] = json::object();\n\t\twrite_json_mat(detected, data[\"detected\"]);\n\n\t\tdata[\"moved\"] = json::object();\n\t\twrite_json_mat(moved, data[\"moved\"]);\n\n\t\tdata[\"points\"] = json::object();\n\t\twrite_json_mat(points, data[\"points\"]);\n\n\t\tdata[\"displacement\"] = json::object();\n\t\twrite_json_mat((detected-points).eval(), data[\"displacement\"]);\n\n\t\tdata[\"triangles\"] = json::object();\n\t\twrite_json_mat(triangles, data[\"triangles\"]);\n\n\t\tdata[\"boundary\"] = json::object();\n\t\twrite_json_mat(boundary, data[\"boundary\"]);\n\n\t\tdata[\"params\"] = json::object();\n\n\t\tparams.save(data[\"params\"]);\n\t}\n\n\t// void Mesh::save(const std::string & path)\n\t// {\n\t// \t{\n\t// \t\tstd::ofstream out(path + \"/detected.vert\");\n\t// \t\tout << detected << std::endl;\n\t// \t\tout.close();\n\t// \t}\n\n\t// \t{\n\t// \t\tstd::ofstream out(path + \"/moved.vert\");\n\t// \t\tout << moved << std::endl;\n\t// \t\tout.close();\n\t// \t}\n\n\t// \t{\n\t// \t\tstd::ofstream out(path + \"/points.vert\");\n\t// \t\tout << points << std::endl;\n\t// \t\tout.close();\n\t// \t}\n\n\t// \t{\n\t// \t\tstd::ofstream out(path + \"/displacement.txt\");\n\t// \t\tout << (points-detected) << std::endl;\n\t// \t\tout.close();\n\t// \t}\n\n\t// \t{\n\t// \t\tstd::ofstream out(path + \"/mesh.tri\");\n\t// \t\tout << triangles << std::endl;\n\t// \t\tout.close();\n\t// \t}\n\n\t// \t{\n\t// \t\tstd::ofstream out(path + \"/boundary.txt\");\n\t// \t\tout << boundary << std::endl;\n\t// \t\tout.close();\n\t// \t}\n\n\t// \tparams.save(path);\n\t// }\n\n\tvoid Mesh::reset()\n\t{\n\t\t//points = detected;\n\t\tpoints = moved;\n\t\tsolved_vertex.setConstant(false);\n\n\t\t//recompute boundary\n\n\t\t//compute_triangulation();\n\t}\n\n\tvoid Mesh::compute_triangulation()\n\t{\n\t\tif (points.size() == 0)\n\t\t\treturn;\n\t\t// delaunay_triangulation(points, triangles);\n\n\t\tloose_convex_hull(moved, boundary, 6);\n\t\tconstrained_delaunay_triangulation(points, boundary, triangles);\n\n\t\t// Calculate the graph adjancency\n\t\tadjacency_list(triangles, adj);\n\t\tgenerate_vertex_to_tri();\n\n\t}\n\n}// namespace cellogram\n\n\n", "meta": {"hexsha": "0e24116ca4abce69207f83e910e8a5d190a63211", "size": 22258, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cellogram/Mesh.cpp", "max_stars_repo_name": "cellogram/cellogram", "max_stars_repo_head_hexsha": "d378e9b87e56b879b2fb352b08b0fed714481968", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-09-25T15:04:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-20T08:17:44.000Z", "max_issues_repo_path": "src/cellogram/Mesh.cpp", "max_issues_repo_name": "cellogram/cellogram", "max_issues_repo_head_hexsha": "d378e9b87e56b879b2fb352b08b0fed714481968", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cellogram/Mesh.cpp", "max_forks_repo_name": "cellogram/cellogram", "max_forks_repo_head_hexsha": "d378e9b87e56b879b2fb352b08b0fed714481968", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-14T01:36:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-11T20:27:57.000Z", "avg_line_length": 26.3096926714, "max_line_length": 193, "alphanum_fraction": 0.6427351963, "num_tokens": 6845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.5039061705290806, "lm_q1q2_score": 0.29483608927796157}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   Utility_Measurement.hpp\n//! \\author Alex Robinson\n//! \\brief  The measurement class declaration. This object is based of of the\n//!         measurement class in the boost::units examples\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef UTILITY_MEASUREMENT_HPP\n#define UTILITY_MEASUREMENT_HPP\n\n// Boost Includes\n#include <boost/units/config.hpp>\n#include <boost/units/operators.hpp>\n#include <boost/typeof/typeof.hpp>\n\n// Trilinos Includes\n#include <Teuchos_ScalarTraits.hpp>\n\n// FRENSIE Includes\n#include \"Utility_PrintableObject.hpp\"\n#include \"Utility_ContractException.hpp\"\n\nnamespace Utility{\n\n/*! The measurement class\n *\n * This class wraps is meant to be used as any typical scalar type\n * (e.g. double). It is designed to keep track of and propagate the\n * uncertainty of a value (like one would with a measured quantity).\n */\ntemplate<typename T>\nclass Measurement : public PrintableObject\n{\n\nprivate:\n\n  // The scalar traits typedef\n  typedef Teuchos::ScalarTraits<T> ST;\n  \npublic:\n\n  //! The typedef for this type\n  typedef Measurement<T> ThisType;\n  \n  //! The typedef for the value type\n  typedef T ValueType;\n\n  //! Constructor\n  Measurement( const ValueType& value = ValueType(),\n\t       const ValueType& uncertainty = ValueType() );\n\n  //! Copy constructor\n  Measurement( const ThisType& other_measurement );\n\n  //! Destructor\n  ~Measurement()\n  { /* ... */ }\n\n  //! Print method\n  void print( std::ostream& os ) const;\n\n  //! Return the value of the measurement\n  const ValueType& getValue() const;\n\n  //! Return the uncertainty of the measurement\n  const ValueType& getUncertainty() const;\n\n  //! Return the relative uncertainty of the measurement\n  const ValueType getRelativeUncertainty() const;\n\n  //! Return the lower bound of the measurement\n  const ValueType getLowerBound() const;\n  \n  //! Return the upper bound of the measurement\n  const ValueType getUpperBound() const;\n\n  //! Implicit conversion to value type\n  operator ValueType() const;\n\n  //! In-place addition operator\n  ThisType& operator+=( const ValueType& value );\n\n  //! In-place addition operator\n  ThisType& operator+=( const ThisType& other_measurement );\n\n  //! In-place subtraction operator\n  ThisType& operator-=( const ValueType& value );\n\n  //! In-place subtraction operator\n  ThisType& operator-=( const ThisType& other_measurement );\n\n  //! In-place multiplication operator\n  ThisType& operator*=( const ValueType& value );\n\n  //! In-place multiplication operator\n  ThisType& operator*=( const ThisType& other_measurement );\n\n  //! In-place division operator\n  ThisType& operator/=( const ValueType& value );\n\n  //! In-place division operator\n  ThisType& operator/=( const ThisType& other_measurement );\n\nprivate:\n\n  // The measurement value\n  ValueType d_value;\n\n  // The measurement uncertainty\n  ValueType d_uncertainty;\n};\n\n//! Addition operator\ntemplate<typename T>\ninline Measurement<T> operator+( T lhs, const Measurement<T>& rhs )\n{\n  // Make sure nested conditions are met\n  testNestedConditionsBegin(1);\n  \n  return (Measurement<T>( lhs, T(0) ) += rhs);\n  \n  testNestedConditionsEnd(1);\n}\n\n//! Addition operator\ntemplate<typename T>\ninline Measurement<T> operator+( const Measurement<T>& lhs, T rhs )\n{\n  // Make sure nested conditions are met\n  testNestedConditionsBegin(1);\n  \n  return (Measurement<T>( lhs ) += Measurement<T>( rhs, T(0) ));\n\n  testNestedConditionsEnd(1);\n}\n\n//! Addition operator\ntemplate<typename T>\ninline Measurement<T> operator+( const Measurement<T>& lhs, \n\t\t\t\t const Measurement<T>& rhs )\n{\n  // Make sure nested conditions are met\n  testNestedConditionsBegin(1);\n  \n  return (Measurement<T>( lhs ) += rhs );\n\n  testNestedConditionsEnd(1);\n}\n\n//! Subtraction operator\ntemplate<typename T>\ninline Measurement<T> operator-( T lhs, const Measurement<T>& rhs )\n{\n  // Make sure nested conditions are met\n  testNestedConditionsBegin(1);\n  \n  return (Measurement<T>( lhs, T(0) ) -= rhs);\n\n  testNestedConditionsEnd(1);\n}\n\n//! Subtraction operator\ntemplate<typename T>\ninline Measurement<T> operator-( const Measurement<T>& lhs, T rhs )\n{\n  // Make sure nested conditions are met\n  testNestedConditionsBegin(1);\n  \n  return (Measurement<T>( lhs ) -= Measurement<T>( rhs, T(0) ));\n\n  testNestedConditionsEnd(1);\n}\n\n//! Subtraction operator\ntemplate<typename T>\ninline Measurement<T> operator-( const Measurement<T>& lhs, \n\t\t\t\t const Measurement<T>& rhs )\n{\n  // Make sure nested conditions are met\n  testNestedConditionsBegin(1);\n  \n  return (Measurement<T>( lhs ) -= rhs );\n\n  testNestedConditionsEnd(1);\n}\n\n//! Multiplication operator\ntemplate<typename T>\ninline Measurement<T> operator*( T lhs, const Measurement<T>& rhs )\n{\n  // Make sure nested conditions are met\n  testNestedConditionsBegin(1);\n  \n  return (Measurement<T>( lhs, T(0) ) *= rhs);\n\n  testNestedConditionsEnd(1);\n}\n\n//! Multiplication operator\ntemplate<typename T>\ninline Measurement<T> operator*( const Measurement<T>& lhs, T rhs )\n{\n  // Make sure nested conditions are met\n  testNestedConditionsBegin(1);\n  \n  return (Measurement<T>( lhs ) *= Measurement<T>( rhs, T(0) ));\n\n  testNestedConditionsEnd(1);\n}\n\n//! Multiplication operator\ntemplate<typename T>\ninline Measurement<T> operator*( const Measurement<T>& lhs, \n\t\t\t\t const Measurement<T>& rhs )\n{\n  // Make sure nested conditions are met\n  testNestedConditionsBegin(1);\n  \n  return (Measurement<T>( lhs ) *= rhs );\n\n  testNestedConditionsEnd(1);\n}\n\n//! Division operator\ntemplate<typename T>\ninline Measurement<T> operator/( T lhs, const Measurement<T>& rhs )\n{\n  // Make sure nested conditions are met\n  testNestedConditionsBegin(1);\n  \n  // Make sure nested conditions are met\n  return (Measurement<T>( lhs, T(0) ) /= rhs);\n\n  testNestedConditionsEnd(1);\n}\n\n//! Division operator\ntemplate<typename T>\ninline Measurement<T> operator/( const Measurement<T>& lhs, T rhs )\n{\n  // Make sure nested conditions are met\n  testNestedConditionsBegin(1);\n  \n  return (Measurement<T>( lhs ) /= Measurement<T>( rhs, T(0) ));\n  \n  testNestedConditionsEnd(1);\n}\n\n//! Division operator\ntemplate<typename T>\ninline Measurement<T> operator/( const Measurement<T>& lhs, \n\t\t\t\t const Measurement<T>& rhs )\n{\n  // Make sure nested conditions are met\n  testNestedConditionsBegin(1);\n  \n  return (Measurement<T>( lhs ) /= rhs );\n\n  testNestedConditionsEnd(1);\n}\n\n//! Overload of sqrt for a measurement\ntemplate<typename T>\ninline Measurement<T> sqrt( const Measurement<T>& x )\n{\n  // Make sure the measurement is valid\n  testPrecondition( x.getValue() >= 0.0 );\n  \n  const T new_value = std::sqrt( x.getValue() );\n\n  const T propagated_uncertainty = 0.5*(new_value/x.getValue())*\n    x.getUncertainty();\n\n  // Make sure reasonable values have been calculated\n  testPostcondition( !Teuchos::ScalarTraits<T>::isnaninf( new_value ) );\n  testPostcondition( !Teuchos::ScalarTraits<T>::isnaninf( \n\t\t\t\t\t\t    propagated_uncertainty ) );\n\n  return Measurement<T>( new_value, propagated_uncertainty );\n}\n\n//! Overload of pow for a measurement\ntemplate<typename T, typename ExponentType>\ninline Measurement<T> pow( const Measurement<T>& x, \n\t\t\t   const ExponentType exponent )\n{\n  const T new_value = std::pow( x.getValue(), exponent );\n\n  const T propagated_uncertainty = fabs(exponent*(new_value/x.getValue()))*\n    x.getUncertainty();\n\n  // Make sure reasonable values have been calculated\n  testPostcondition( !Teuchos::ScalarTraits<T>::isnaninf( new_value ) );\n  testPostcondition( !Teuchos::ScalarTraits<T>::isnaninf( \n\t\t\t\t\t\t    propagated_uncertainty ) );\n  testPostcondition( propagated_uncertainty >= 0.0 );\n\n  return Measurement<T>( new_value, propagated_uncertainty );\n}\n\n} // end Utility namespace\n\n\nnamespace boost{\n\nnamespace units{\n\n//! Specialization of the boost::units::power_typeof_helper\ntemplate<typename Y, long N, long D>\nstruct power_typeof_helper<Utility::Measurement<Y>,static_rational<N,D> >\n{\n  typedef Utility::Measurement<typename power_typeof_helper<Y,static_rational<N,D> >::type> type;\n  \n  static type value( const Utility::Measurement<Y>& x)\n  {\n    const static_rational<N,D> rational;\n\n    const Y rational_power = Y(rational.numerator())/Y(rational.denominator());\n    \n    return Utility::pow( x, rational_power );\n  }\n};\n\n//! Specialization of the boost::units::root_typeof_helper\ntemplate<typename Y, long N, long D>\nstruct root_typeof_helper<Utility::Measurement<Y>,static_rational<N,D> >\n{\n  typedef Utility::Measurement<typename root_typeof_helper<Y,static_rational<N,D> >::type> type;\n\n  static type value( const Utility::Measurement<Y>& x )\n  {\n    const static_rational<N,D> rational;\n\n    // Compute D/N instead of N/D since we're interested in the root\n    const Y rational_power = Y(rational.denominator())/Y(rational.numerator());\n\n    return Utility::pow( x, rational_power );\n  }\n};\n\n} // end units namespace\n\n} // end boost namespace\n\nnamespace Teuchos{\n\n//! Partial specialization of Teuchos::ScalarTraits for the Measurement class\ntemplate<typename T>\nstruct ScalarTraits<Utility::Measurement<T> >\n{\n  typedef Utility::Measurement<T> Measurement;\n  typedef T magnitudeType;\n  typedef typename Teuchos::ScalarTraits<T>::halfPrecision halfPrecision;\n  typedef typename Teuchos::ScalarTraits<T>::doublePrecision doublePrecision;\n  \n  static const bool isComplex = Teuchos::ScalarTraits<T>::isComplex;\n  static const bool isOrdinal = Teuchos::ScalarTraits<T>::isOrdinal;\n  static const bool isComparable = Teuchos::ScalarTraits<T>::isComparable;\n  static const bool hasMachineParameters = Teuchos::ScalarTraits<T>::hasMachineParameters;\n\n  static inline magnitudeType eps() { return ScalarTraits<magnitudeType>::eps(); }\n  static inline magnitudeType sfmin() { return ScalarTraits<magnitudeType>::sfmin(); }\n  static inline magnitudeType base() { return ScalarTraits<magnitudeType>::base(); }\n  static inline magnitudeType prec() { return ScalarTraits<magnitudeType>::prec(); }\n  static inline magnitudeType t() { return ScalarTraits<magnitudeType>::t(); }\n  static inline magnitudeType rnd() { return ScalarTraits<magnitudeType>::rnd(); }\n  static inline magnitudeType emin() { return ScalarTraits<magnitudeType>::emin(); }\n  static inline magnitudeType rmin() { return ScalarTraits<magnitudeType>::rmin(); }\n  static inline magnitudeType emax() { return ScalarTraits<magnitudeType>::emax(); }\n  static inline magnitudeType rmax() { return ScalarTraits<magnitudeType>::rmax(); }\n  static inline magnitudeType magnitude(Measurement a) { return ScalarTraits<magnitudeType>::magnitude( a.getValue() ); }\n  static inline Measurement zero() { return Measurement( ScalarTraits<magnitudeType>::zero(), 0.0 ); }\n  static inline Measurement one() { return Measurement( ScalarTraits<magnitudeType>::zero(), 1.0 ); }\n  static inline Measurement conjugate(Measurement a){ return Measurement( ScalarTraits<magnitudeType>::conjugate(a.getValue()), ScalarTraits<magnitudeType>::conjugate(a.getUncertainty()) ); }\n  static inline Measurement real(Measurement a){ return Measurement( ScalarTraits<magnitudeType>::real(a.getValue()), ScalarTraits<magnitudeType>::real(a.getUncertainty()) ); }\n  static inline Measurement imag(Measurement a){ return Measurement( ScalarTraits<magnitudeType>::imag(a.getValue()), ScalarTraits<magnitudeType>::imag(a.getUncertainty()) ); }\n  static inline Measurement nan() { return Measurement( ScalarTraits<magnitudeType>::nan(), ScalarTraits<magnitudeType>::nan() ); }\n  static inline bool isnaninf(Measurement a){ return ScalarTraits<magnitudeType>::isnaninf(a.getValue()) || ScalarTraits<magnitudeType>::isnaninf(a.getUncertainty()); }\n  static inline void seedrandom(unsigned int s) { ScalarTraits<magnitudeType>::seedrandom(s); }\n  static inline Measurement random() { return Measurement( ScalarTraits<magnitudeType>::random(), 0.0 ); }\n  static inline std::string name() { return std::string(\"Measurement<\")+std::string(ScalarTraits<magnitudeType>::name())+std::string(\">\"); }\n  static inline Measurement squareroot(Measurement a) { return Utility::sqrt(a); }\n  static inline Measurement pow(Measurement a, Measurement b) { return Utility::pow( a, b.getValue() ); }\n\n};\n\n} // end Teuchos namespace\n\n// Register the Measurement class with boost typeof for auto-like type\n// deduction when used with the boost::units library\n#if BOOST_UNITS_HAS_BOOST_TYPEOF\n\nBOOST_TYPEOF_REGISTER_TEMPLATE(Utility::Measurement, 1)\n\n#endif // end BOOST_UNITS_HAS_BOOST_TYPEOF\n\n//---------------------------------------------------------------------------//\n// Template Includes\n//---------------------------------------------------------------------------//\n\n#include \"Utility_Measurement_def.hpp\"\n\n//---------------------------------------------------------------------------//\n\n#endif // end UTILITY_MEASUREMENT_HPP\n\n//---------------------------------------------------------------------------//\n// end Utility_Measurement.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "0afb5cf0b93d741a5fc9006a69257006ef471105", "size": 13025, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/utility/core/src/Utility_Measurement.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/utility/core/src/Utility_Measurement.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/utility/core/src/Utility_Measurement.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": 31.6140776699, "max_line_length": 191, "alphanum_fraction": 0.6978886756, "num_tokens": 2867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.2948360819866952}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2002-2016 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#ifndef LINEARSPACE_HH\n#define LINEARSPACE_HH\n\n#include <cmath>\n#include <type_traits>\n\n#include <boost/version.hpp>\n#include <boost/fusion/algorithm.hpp>\n#include <boost/fusion/sequence.hpp>\n\n#include \"linalg/crsutil.hh\"\n\nnamespace Kaskade\n{\n  /// \\internal \n  // forward declaration\n  template <class> class VariableSet;\n\n  namespace LinearSpace_Detail\n  {\n\n    template <class Space0, class Space2, int id> struct Copy;\n\n    template <class Space, int id, class VSDescriptions>\n    struct Copy<VariableSet<VSDescriptions>,Space,id>\n    {\n      static void apply(const VariableSet<VSDescriptions>& from, Space& to)\n      {\n        boost::fusion::at_c<id>(to.data) = boost::fusion::at_c<id>(from.data).coefficients();\n        Copy<VariableSet<VSDescriptions>,Space,id-1>::apply(from,to);\n      }\n    };\n\n    template <class Space, class VSDescriptions>\n    struct Copy<VariableSet<VSDescriptions>,Space,0>\n    {\n      static void apply(const VariableSet<VSDescriptions>& from, Space& to)\n      {\n        boost::fusion::at_c<0>(to.data) = boost::fusion::at_c<0>(from.data).coefficients();\n      }\n    };\n  }\n  /// \\endinternal \n\n  /**\n   * \\ingroup linalgbasic \n   * \\brief A product space of linear spaces. \n   * \n   * Access to the components of the product space is provided by the the boost::fusion\n   * sequence data:\n   * \\code\n   * LinearProductSpace<double,boost::fusion::vector<Dune::FieldVector<double,2>,Dune::FieldVector<double,3>>> x;\n   * Dune::FieldVector<double,3>& comp1 = boost::fusion::at_c<1>(x.data);\n   * \\endcode\n   * \n   * Arithmetic operations are delegated componentwise to the heterogeneous subspaces.\n   * \n   *\n   * \\tparam Scalar the scalar field type of the linear space\n   * \\tparam Seq a boost::fusion sequence type defining the variables of the cartesian product\n   */\n  template <class Scalar_, class Seq>\n  class LinearProductSpace\n  {\n  private:\n    typedef LinearProductSpace<Scalar_,Seq> Self;\n\n    // forward declarations (definitions at end of file)\n    struct Add;\n    struct Sub;\n    struct Assign;\n    struct ScalarMult;\n    struct Axpy;\n    struct ScalarProduct;\n    struct ScalarProductHack;\n    template <typename> struct ReadBlock;\n    template <typename> struct WriteBlock;\n\n  public:\n    /// scalar type\n    typedef Scalar_ Scalar;\n    typedef Scalar field_type;\n    \n    /// boost::fusion::vector of element vectors.\n    typedef Seq Sequence;\n    typedef Seq Functions;\n\n\n    // use with care: default constructed subvectors may not be properly initialized (e.g. size?)\n    // LinearProductSpace() {}\n    LinearProductSpace() = delete;\n\n    /// Copy constructor\n    LinearProductSpace(LinearProductSpace<Scalar,Sequence> const& y): data(y.data) {}\n\n    /// Copy from VariableSet\n    template <class VSDescriptions>\n    explicit LinearProductSpace(const VariableSet<VSDescriptions>& y)\n    {\n      *this = y;\n    }\n\n    /// Constructor with explicit data\n    template <class S>\n    explicit LinearProductSpace(S const& init): data(init)\n    {}\n\n    template <typename... Args>\n    explicit LinearProductSpace(boost::fusion::transform_view<Args...> const& data_) : data(data_)\n    {\n      applyUnaryOp(Assign(0));\n    }\n\n    /**\n     *\\brief Number of scalar degrees of freedom.\n     * This computes the total number of degrees of freedom, i.e. the sum of the dimensions of \n     * the components.\n     */\n    size_t dim() const\n    {\n      return boost::fusion::accumulate(data,0,[](auto dim, auto const& v) { return dim+v.dim(); });\n    }\n\n\n    /// Assignment from the same type\n    Self& operator=(Self const& y) { if (this!=&y) data = y.data; return *this; }\n\n    /// Assignment from a different (hopefully compatible) type\n    template <class VSDescriptions>\n    Self& operator=(VariableSet<VSDescriptions> const& y)\n    {\n      using namespace boost::fusion;\n      static_assert(result_of::size<Sequence>::type::value == VSDescriptions::noOfVariables,\"Numbers of variables do not match.\");\n      LinearSpace_Detail::Copy<VariableSet<VSDescriptions>,LinearProductSpace,\n                               result_of::size<typename VSDescriptions::RepresentationData>::type::value-1>::apply(y,*this);\n      return *this;\n    } // need not check for self assignment here\n\n    /// Assignment from a different (hopefully compatible) type\n    template <class OtherSeq>\n    Self& operator=(LinearProductSpace<Scalar,OtherSeq> const& y) \n    { \n      using namespace boost::fusion;\n      static_assert(result_of::size<Sequence>::type::value == result_of::size<OtherSeq>::type::value, \"Numbers of variables do not match.\");\n      data = y.data;\n      return *this; \n    } // need not check for self assignment here\n\n    /// Assignment from a (hopefully compatible) FunctionSpaceElement\n    template <class FunctionSpace, int m>\n    Self& operator=(FunctionSpaceElement<FunctionSpace,m> const& fse) \n    { \n      data = fse.coefficients(); \n      return *this; \n    }\n\n    /// Assignment to constant scalar\n    Self& operator=(Scalar a) \n    { \n      return applyUnaryOp(Assign(a));\n    }\n    \n    /// Assignment from a (hopefully compatible) boost::fusion iterator range \n    template <class First, class Last>\n    Self& operator=(boost::fusion::iterator_range<First,Last> range)\n    {\n      static_assert(boost::fusion::result_of::size<Sequence>::type::value == boost::fusion::result_of::distance<First,Last>::type::value,\n                    \"Numbers of variables do not match.\");\n      data = range;\n      return *this;\n    }\n    \n    //\n    \n    /// Scaling\n    Self& operator*=(Scalar a) { return applyUnaryOp(ScalarMult(a)); }\n\n    /// In place addition\n    template <class SequenceY>\n    Self& operator+=(LinearProductSpace<Scalar,SequenceY> const& y) {\n      return applyBinaryOp(Add(),y); }\n\n    /// In place subtraction\n    Self& operator-=(Self const& y) { return applyBinaryOp(Sub(),y); }\n\n    /// this <- this + a*y\n    Self& axpy(Scalar a, Self const& y) { return applyBinaryOp(Axpy(a),y); }\n\n    /// Scalar product\n    field_type operator*(Self const& y) const {\n      // For some unknown reason, this does not work... (will work in more recent fusion version).\n      // return boost::fusion::accumulate(boost::fusion::zip(data,y.data),0,ScalarProduct());\n      // We therefore use the following ugly hack workaround\n      using namespace boost::fusion;\n      zip_view<vector<Sequence const&,Sequence const&> > zipped(vector<Sequence const&,Sequence const&>(data,y.data));\n      ScalarProductHack sp;\n      for_each(zipped,sp);\n      return sp.s;\n    }\n    \n    /// Scalar product\n    field_type dot(Self const& y) const { return *this * y; } \n\n    /**\n     * \\brief DEPRECATED use vectorFromSequence instead\n     * \n     * Reads the coefficients sequentially from an input iterator. \n     * The InIterator's value type must be convertible to field_type.\n     */\n    template <class InIterator>\n    void read(InIterator i) \n    { \n      vectorFromSequence(*this,i);\n    }\n\n    /**\n     * \\brief Reads the coefficients of the subrange [rbegin,rend[ sequentially from an input iterator. \n     * The InIterator's value type must be convertible to field_type.\n     */\n    template <class InIterator>\n    void read(int rbegin, int rend, InIterator i) { boost::fusion::for_each(data,ReadBlock<InIterator>(rbegin,rend,i)); }\n\n    /**\n     * \\brief DEPRECATED use vectorToSequence instead\n     * \n     * Writes the coefficients sequentially to an output iterator (flattening).\n     * The field_type must be convertible to the OutIterator's value type.\n     */\n    template <class OutIterator>\n    void write(OutIterator i) const \n    { \n      vectorToSequence(*this,i);\n    }\n\n    /**\n     * \\brief Writes the coefficients of the subrange [rbegin,rend[ sequentially to an output iterator. \n     * The InIterator's value type must be convertible to field_type.\n     */\n    template <class DataOutIter>\n    void write(int rbegin, int rend, DataOutIter i) const\n    {\n      boost::fusion::for_each(data,WriteBlock<DataOutIter>(rbegin,rend,i));\n    }\n\n    /// Euclidean Norm\n    double two_norm() const { return std::sqrt((*this)*(*this)); }\n    \n    /// Data\n    Sequence data;\n\n  private:\n\n    // applies a binary operator to the elements of a pair\n    template <class BinaryOp>\n    struct PairOp\n    {\n      PairOp(BinaryOp const& op_): op(op_) {}\n\n      template <class Pair> void operator()(Pair p) const {\n        op(boost::fusion::at_c<0>(p),boost::fusion::at_c<1>(p));\n      }\n\n    private:\n      BinaryOp const& op;\n    };\n\n    template <class UnaryOp>\n    Self& applyUnaryOp(UnaryOp const& op) {\n      boost::fusion::for_each(data,op);\n      return *this;\n    }\n\n    template <class BinaryOp, class SpaceY>\n    Self& applyBinaryOp(BinaryOp const& op, SpaceY const& y) {\n      using namespace boost::fusion;\n      typedef typename SpaceY::Sequence SequenceY;\n      zip_view<vector<Sequence&,SequenceY const&> > zipped(vector<Sequence&,SequenceY const&>(data,y.data));\n      for_each(zipped,PairOp<BinaryOp>(op));\n      return *this;\n    }\n\n    struct Add { template <class T, class S> void operator()(T& a, S const& b) const { a += b; } };\n    struct Sub { template <class T> void operator()(T& a, T const& b) const { a -= b; } };\n    struct Assign {\n      Assign(Scalar s_): s(s_) {}\n      template <class T> void operator()(T& a) const { a = s; }\n    private: Scalar s;\n    };\n\n\n    struct ScalarMult {\n      ScalarMult(Scalar s_): s(s_) {}\n      template <class Element> void operator()(Element& e) const { e *= s; }\n    private: Scalar s;\n    };\n\n    struct Axpy\n    {\n      Axpy(Scalar s_): s(s_) {}\n      template <class T> void operator()(T& a, T const& b) const {\n\n        // Funny runtime error could only be avoided by this funny code.\n        // Probably a compiler bug.\n        // assert(a.size()==b.size());\n        std::cout << \"\";\n\n\n        a.axpy(s,b);\n      }\n\n    private: Scalar s;\n    };\n\n    struct ScalarProduct\n    {\n      template <class T> struct result {};\n\n      template <class Pair, class T> struct result<ScalarProduct(Pair,T)> { typedef field_type type; };\n      template <class Pair>\n      field_type operator()(Pair const& pair, field_type res) const {\n        using namespace boost::fusion;\n\n        return res ;//+ at_c<0>(pair)*at_c<1>(pair);\n      }\n    };\n\n    // Ugly hack -- see above\n    struct ScalarProductHack\n    {\n      ScalarProductHack(): s(0) {}\n      template <class Pair> void operator()(Pair const& p) const { s += boost::fusion::at_c<0>(p) * boost::fusion::at_c<1>(p); }\n      mutable field_type s;\n    };\n\n    template <class DataOutIter>\n    struct WriteBlock\n    {\n\n\n      WriteBlock(int& rbegin_, int& rend_, DataOutIter& out_): rbegin(rbegin_), rend(rend_), out(out_) {}\n      template <class VectorBlock> void operator()(VectorBlock const& v) const\n      {\n        if (rbegin<=0 && rend>0)\n          vectorToSequence(v,out);\n        --rbegin;\n        --rend;\n      }\n    private:\n      int& rbegin;\n      int& rend;\n      DataOutIter& out;\n\n    };\n\n    template <class DataInIter>\n    struct ReadBlock\n    {\n      ReadBlock(int& rbegin_, int& rend_, DataInIter& in_): rbegin(rbegin_), rend(rend_), in(in_) {}\n      \n      template <class VectorBlock> void operator()(VectorBlock& v) const\n      {\n        if (rbegin<=0 && rend>0)\n          vectorFromSequence(v,in);\n        --rbegin;\n        --rend;\n      }\n    private:\n      int& rbegin;\n      int& rend;\n      DataInIter& in;\n\n    };\n\n  };\n  \n  /**\n   * \\ingroup linalgbasic\n   * \\brief Provides access to the m-th component of a product space.\n   * \n   * This simplifies the access to individual components of a product space, e.g., a variable set of finite\n   * element functions. Instead of \n   * \\code\n   * boost::fusion::at_c<m>(x.data)\n   * \\endcode\n   * one can write\n   * \\code\n   * component<m>(x)\n   * \\endcode\n   * \n   * \\tparam m the index of the component (nonnegative)\n   * \\tparam Scalar a scalar type\n   * \\tparam Sequence a boost::fusion sequence type\n   * \n   * \\return a reference to the m-th component\n   * \n   * \\relates LinearProductSpace\n   */\n  template <int m, class Scalar, class Sequence>\n  typename boost::fusion::result_of::at_c<Sequence const,m>::type component(LinearProductSpace<Scalar,Sequence> const& x) { return boost::fusion::at_c<m>(x.data); }\n\n  template <int m, class Scalar, class Sequence>\n  typename boost::fusion::result_of::at_c<Sequence,m>::type component(LinearProductSpace<Scalar,Sequence>& x) { return boost::fusion::at_c<m>(x.data); }\n  \n\n  /**\n   * \\ingroup linalgbasic\n   * \\brief writes the coefficients of a vector to a flat scalar sequence\n   * \\related LinearProductSpace<Scalar,Seq>\n   */\n  template <class Scalar, class Seq, class OutIter>\n  OutIter vectorToSequence(LinearProductSpace<Scalar,Seq> const& v, OutIter i)\n  {\n    boost::fusion::for_each(v.data,[&](auto& x) { i = vectorToSequence(x,i); }); \n    return i;\n  }\n  \n  /**\n   * \\ingroup linalgbasic\n   * \\brief reads the coefficients of a vector from a flat scalar sequence\n   * \\related LinearProductSpace<Scalar,Seq>\n   */\n  template <class Scalar, class Seq, class InIter>\n  InIter vectorFromSequence(LinearProductSpace<Scalar,Seq>& v, InIter i)\n  {\n    boost::fusion::for_each(v.data,[&](auto& x) { i = vectorFromSequence(x,i); }); \n    return i;\n  }\n  \n} // end of namespace Kaskade\n\n\n#endif\n", "meta": {"hexsha": "b1231ef72f40eb7eb61718bbf6dc3f98841f1390", "size": 14159, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/fem/linearspace.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/fem/linearspace.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/fem/linearspace.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 31.8179775281, "max_line_length": 164, "alphanum_fraction": 0.6175577371, "num_tokens": 3542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.2946826900294997}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// BSD 3-Clause License\n//\n// Copyright (C) 2019-2020, LAAS-CNRS, New York University, Max Planck Gesellschaft,\n//                          University of Edinburgh\n// Copyright note valid unless otherwise stated in individual files.\n// All rights reserved.\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef CROCODDYL_CORE_NUMDIFF_STATE_HPP_\n#define CROCODDYL_CORE_NUMDIFF_STATE_HPP_\n\n#include <boost/make_shared.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include \"crocoddyl/core/fwd.hpp\"\n#include \"crocoddyl/core/state-base.hpp\"\n\nnamespace crocoddyl {\n\ntemplate <typename _Scalar>\nclass StateNumDiffTpl : public StateAbstractTpl<_Scalar> {\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  typedef _Scalar Scalar;\n  typedef MathBaseTpl<Scalar> MathBase;\n  typedef StateAbstractTpl<_Scalar> Base;\n  typedef typename MathBase::VectorXs VectorXs;\n  typedef typename MathBase::MatrixXs MatrixXs;\n\n  explicit StateNumDiffTpl(boost::shared_ptr<Base> state);\n  virtual ~StateNumDiffTpl();\n\n  virtual VectorXs zero() const;\n  virtual VectorXs rand() const;\n  virtual void diff(const Eigen::Ref<const VectorXs>& x0, const Eigen::Ref<const VectorXs>& x1,\n                    Eigen::Ref<VectorXs> dxout) const;\n  virtual void integrate(const Eigen::Ref<const VectorXs>& x, const Eigen::Ref<const VectorXs>& dx,\n                         Eigen::Ref<VectorXs> xout) const;\n  /**\n   * @brief This computes the Jacobian of the diff method by finite\n   * differentiation:\n   * \\f{equation}{\n   *    Jfirst[:,k] = diff(int(x_1, dx_dist), x_2) - diff(x_1, x_2)/disturbance\n   * \\f}\n   * and\n   * \\f{equation}{\n   *    Jsecond[:,k] = diff(x_1, int(x_2, dx_dist)) - diff(x_1, x_2)/disturbance\n   * \\f}\n   *\n   * @param Jfirst\n   * @param Jsecond\n   * @param firstsecond\n   */\n  virtual void Jdiff(const Eigen::Ref<const VectorXs>& x0, const Eigen::Ref<const VectorXs>& x1,\n                     Eigen::Ref<MatrixXs> Jfirst, Eigen::Ref<MatrixXs> Jsecond, Jcomponent firstsecond = both) const;\n  /**\n   * @brief This computes the Jacobian of the integrate method by finite\n   * differentiation:\n   * \\f{equation}{\n   *    Jfirst[:,k] = diff( int(x, d_x), int( int(x, dx_dist), dx) )/disturbance\n   * \\f}\n   * and\n   * \\f{equation}{\n   *    Jsecond[:,k] = diff( int(x, d_x), int( x, dx + dx_dist) )/disturbance\n   * \\f}\n   *\n   * @param Jfirst\n   * @param Jsecond\n   * @param firstsecond\n   */\n  virtual void Jintegrate(const Eigen::Ref<const VectorXs>& x, const Eigen::Ref<const VectorXs>& dx,\n                          Eigen::Ref<MatrixXs> Jfirst, Eigen::Ref<MatrixXs> Jsecond,\n                          const Jcomponent firstsecond = both, const AssignmentOp op = setto) const;\n\n  virtual void JintegrateTransport(const Eigen::Ref<const VectorXs>& x, const Eigen::Ref<const VectorXs>& dx,\n                                   Eigen::Ref<MatrixXs> Jin, const Jcomponent firstsecond = both) const;\n\n  const Scalar& get_disturbance() const;\n  void set_disturbance(const Scalar& disturbance);\n\n private:\n  /**\n   * @brief This is the state we need to compute the numerical differentiation\n   * from.\n   */\n  boost::shared_ptr<Base> state_;\n  /**\n   * @brief This the increment used in the finite differentiation and integration.\n   */\n  Scalar disturbance_;\n\n protected:\n  using Base::has_limits_;\n  using Base::lb_;\n  using Base::ndx_;\n  using Base::nq_;\n  using Base::nv_;\n  using Base::nx_;\n  using Base::ub_;\n};\n\n}  // namespace crocoddyl\n\n/* --- Details -------------------------------------------------------------- */\n/* --- Details -------------------------------------------------------------- */\n/* --- Details -------------------------------------------------------------- */\n#include \"crocoddyl/core/numdiff/state.hxx\"\n\n#endif  // CROCODDYL_CORE_NUMDIFF_STATE_HPP_\n", "meta": {"hexsha": "4424f4219c714bd8a7fd885135692af2a54e33e3", "size": 3860, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crocoddyl/core/numdiff/state.hpp", "max_stars_repo_name": "pFernbach/crocoddyl", "max_stars_repo_head_hexsha": "cbf81a329e3abaf4ce1b4a8fab1431f93cd9a5c8", "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/crocoddyl/core/numdiff/state.hpp", "max_issues_repo_name": "pFernbach/crocoddyl", "max_issues_repo_head_hexsha": "cbf81a329e3abaf4ce1b4a8fab1431f93cd9a5c8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/crocoddyl/core/numdiff/state.hpp", "max_forks_repo_name": "pFernbach/crocoddyl", "max_forks_repo_head_hexsha": "cbf81a329e3abaf4ce1b4a8fab1431f93cd9a5c8", "max_forks_repo_licenses": ["BSD-3-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.4642857143, "max_line_length": 117, "alphanum_fraction": 0.6075129534, "num_tokens": 984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.2946826900294997}}
{"text": "/*!\n@file\nForward declares `boost::hana::Group`.\n\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_HANA_FWD_GROUP_HPP\n#define BOOST_HANA_FWD_GROUP_HPP\n\n#include <boost/hana/detail/std/forward.hpp>\n#include <boost/hana/fwd/core/datatype.hpp>\n#include <boost/hana/fwd/core/operators.hpp>\n\n\nnamespace boost { namespace hana {\n    //! @ingroup group-concepts\n    //! The `Group` concept represents `Monoid`s where all objects have\n    //! an inverse w.r.t. the `Monoid`'s binary operation.\n    //!\n    //! A [Group][1] is an algebraic structure built on top of a `Monoid`\n    //! which adds the ability to invert the action of the `Monoid`'s binary\n    //! operation on any element of the set. Specifically, a `Group` is a\n    //! `Monoid` `(S, +)` such that every element `s` in `S` has an inverse\n    //! (say `s'`) which is such that\n    //! @code\n    //!     s + s' == s' + s == identity of the Monoid\n    //! @endcode\n    //!\n    //! There are many examples of `Group`s, one of which would be the\n    //! additive `Monoid` on integers, where the inverse of any integer\n    //! `n` is the integer `-n`. The method names used here refer to\n    //! exactly this model.\n    //!\n    //!\n    //! Superclass\n    //! ----------\n    //! `Monoid`\n    //!\n    //!\n    //! Laws\n    //! ----\n    //! For all objects `x` of a `Group` `G`, the following laws must be\n    //! satisfied:\n    //! @code\n    //!     plus(x, negate(x)) == zero<G>() // right inverse\n    //!     plus(negate(x), x) == zero<G>() // left inverse\n    //! @endcode\n    //!\n    //!\n    //! Minimal complete definitions\n    //! ----------------------------\n    //! 1. `minus`\\n\n    //! When `minus` is specified, the `negate` method is defaulted by setting\n    //! @code\n    //!     negate(x) = minus(zero<G>(), x)\n    //! @endcode\n    //!\n    //! 2. `negate`\\n\n    //! When `negate` is specified, the `minus` method is defaulted by setting\n    //! @code\n    //!     minus(x, y) = plus(x, negate(y))\n    //! @endcode\n    //!\n    //!\n    //! Provided models\n    //! ---------------\n    //! 1. For non-boolean arithmetic data types\\n\n    //! A data type `T` is arithmetic if `std::is_arithmetic<T>::%value` is\n    //! true. For a non-boolean arithmetic data type `T`, a model of `Group`\n    //! is automatically defined by setting\n    //! @code\n    //!     minus(x, y) = (x - y)\n    //!     negate(x) = -x\n    //! @endcode\n    //!\n    //! @note\n    //! The rationale for not providing a Group model for `bool` is the same\n    //! as for not providing a `Monoid` model.\n    //!\n    //!\n    //! Operators\n    //! ---------\n    //! For convenience, the following operators are provided as an\n    //! equivalent way of calling the corresponding method:\n    //! @code\n    //!     binary -  ->  minus\n    //!     unary -   ->  negate\n    //! @endcode\n    //!\n    //!\n    //! Structure-preserving functions\n    //! ------------------------------\n    //! Let `A` and `B` be two `Group`s. A function `f : A -> B` is said to\n    //! be a [Group morphism][2] if it preserves the group structure between\n    //! `A` and `B`. Rigorously, for all objects `x, y` of data type `A`,\n    //! @code\n    //!     f(plus(x, y)) == plus(f(x), f(y))\n    //! @endcode\n    //! Because of the `Group` structure, it is easy to prove that the\n    //! following will then also be satisfied:\n    //! @code\n    //!     f(negate(x)) == negate(f(x))\n    //!     f(zero<A>()) == zero<B>()\n    //! @endcode\n    //! Functions with these properties interact nicely with `Group`s, which\n    //! is why they are given such a special treatment.\n    //!\n    //!\n    //! [1]: http://en.wikipedia.org/wiki/Group_(mathematics)\n    //! [2]: http://en.wikipedia.org/wiki/Group_homomorphism\n    struct Group { };\n\n    //! Subtract two elements of a group.\n    //! @relates Group\n    //!\n    //! Specifically, this performs the `Monoid` operation on the first\n    //! argument and on the inverse of the second argument, thus being\n    //! equivalent to:\n    //! @code\n    //!     minus(x, y) == plus(x, negate(y))\n    //! @endcode\n    //!\n    //!\n    //! Cross-type version of the method\n    //! --------------------------------\n    //! The `minus` method is \"overloaded\" to handle distinct data types\n    //! with certain properties. Specifically, `minus` is defined for\n    //! _distinct_ data types `A` and `B` such that\n    //! 1. `A` and `B` share a common data type `C`, as determined by the\n    //!    `common` metafunction\n    //! 2. `A`, `B` and `C` are all `Group`s when taken individually\n    //! 3. `to<C> : A -> B` and `to<C> : B -> C` are `Group`-embeddings, as\n    //!    determined by the `is_embedding` metafunction.\n    //!\n    //! The definition of `minus` for data types satisfying the above\n    //! properties is obtained by setting\n    //! @code\n    //!     minus(x, y) = minus(to<C>(x), to<C>(y))\n    //! @endcode\n    //!\n    //!\n    //! Example\n    //! -------\n    //! @snippet example/group.cpp minus\n#ifdef BOOST_HANA_DOXYGEN_INVOKED\n    constexpr auto minus = [](auto&& x, auto&& y) -> decltype(auto) {\n        return tag-dispatched;\n    };\n#else\n    template <typename T, typename U, typename = void>\n    struct minus_impl;\n\n    struct _minus {\n        template <typename X, typename Y>\n        constexpr decltype(auto) operator()(X&& x, Y&& y) const {\n            return minus_impl<\n                typename datatype<X>::type, typename datatype<Y>::type\n            >::apply(\n                detail::std::forward<X>(x),\n                detail::std::forward<Y>(y)\n            );\n        }\n    };\n\n    constexpr _minus minus{};\n#endif\n\n    //! Return the inverse of an element of a group.\n    //! @relates Group\n    //!\n    //!\n    //! Example\n    //! -------\n    //! @snippet example/group.cpp negate\n#ifdef BOOST_HANA_DOXYGEN_INVOKED\n    constexpr auto negate = [](auto&& x) -> decltype(auto) {\n        return tag-dispatched;\n    };\n#else\n    template <typename G, typename = void>\n    struct negate_impl;\n\n    struct _negate {\n        template <typename X>\n        constexpr decltype(auto) operator()(X&& x) const {\n            return negate_impl<typename datatype<X>::type>::apply(\n                detail::std::forward<X>(x)\n            );\n        }\n    };\n\n    constexpr _negate negate{};\n#endif\n\n    template <>\n    struct operators::of<Group>\n        : decltype(minus), decltype(negate)\n    { };\n}} // end namespace boost::hana\n\n#endif // !BOOST_HANA_FWD_GROUP_HPP\n", "meta": {"hexsha": "39fa8234a1aa3bbec7407b98a6ee8de9f616f34b", "size": 6542, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/hana/fwd/group.hpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/hana/fwd/group.hpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/hana/fwd/group.hpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.912195122, "max_line_length": 78, "alphanum_fraction": 0.5556404769, "num_tokens": 1715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.2946826900294997}}
{"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 ored/configuration/yieldcurveconfig.hpp\n    \\brief Yield curve configuration classes\n    \\ingroup configuration\n*/\n\n#pragma once\n\n#include <boost/none.hpp>\n#include <boost/optional.hpp>\n#include <boost/shared_ptr.hpp>\n#include <map>\n#include <ored/configuration/curveconfig.hpp>\n#include <ored/utilities/xmlutils.hpp>\n#include <ql/patterns/visitor.hpp>\n#include <ql/types.hpp>\n#include <set>\n\nnamespace ore {\nnamespace data {\nusing std::string;\nusing std::vector;\nusing std::set;\nusing std::pair;\nusing std::map;\nusing boost::optional;\nusing ore::data::XMLNode;\nusing QuantLib::AcyclicVisitor;\nusing QuantLib::Real;\n\n//! Base class for yield curve segments.\n/*!\n  \\ingroup configuration\n*/\nclass YieldCurveSegment : public XMLSerializable {\npublic:\n    //! supported segment types\n    enum class Type {\n        Zero,\n        ZeroSpread,\n        Discount,\n        Deposit,\n        FRA,\n        Future,\n        OIS,\n        Swap,\n        AverageOIS,\n        TenorBasis,\n        TenorBasisTwo,\n        BMABasis,\n        FXForward,\n        CrossCcyBasis,\n        CrossCcyFixFloat,\n        DiscountRatio\n    };\n    //! Default destructor\n    virtual ~YieldCurveSegment() {}\n\n    //! \\name Serialisation\n    //@{\n    virtual void fromXML(XMLNode* node) = 0;\n    virtual XMLNode* toXML(XMLDocument& doc) = 0;\n    //@}\n\n    //! \\name Inspectors\n    //@{\n    Type type() const { return type_; }\n    // TODO: why typeID?\n    const string& typeID() const { return typeID_; }\n    const string& conventionsID() const { return conventionsID_; }\n    const vector<pair<string, bool>>& quotes() const { return quotes_; }\n    //@}\n\n    //! \\name Visitability\n    //@{\n    virtual void accept(AcyclicVisitor&);\n    //@}\n\nprotected:\n    //! \\name Constructors\n    //@{\n    //! Default constructor\n    YieldCurveSegment() {}\n    //! Detailed constructor - assumes all quotes are mandatory\n    YieldCurveSegment(const string& typeID, const string& conventionsID, const vector<string>& quotes);\n    //@}\n\n    //! Quote and optional flag pair\n    vector<pair<string, bool>> quotes_;\n\n    //! Utility to build a quote, optional flag defaults to false\n    pair<string, bool> quote(const string& name, bool opt = false) { return make_pair(name, opt); }\n\n    //! Utility method to read quotes from XML\n    void loadQuotesFromXML(XMLNode* node);\n    //! Utility method to write quotes to XML\n    XMLNode* writeQuotesToXML(XMLDocument& doc);\n\nprivate:\n    // TODO: why type and typeID?\n    Type type_;\n    string typeID_;\n    string conventionsID_;\n};\n\n//! Direct yield curve segment\n/*!\n  A direct yield curve segment is used when the segments is entirely defined by\n  a set of quotes that are passed to the constructor.\n\n  \\ingroup configuration\n*/\nclass DirectYieldCurveSegment : public YieldCurveSegment {\npublic:\n    //! \\name Constructors/Destructors\n    //@{\n    //! Default constructor\n    DirectYieldCurveSegment() {}\n    //! Detailed constructor\n    DirectYieldCurveSegment(const string& typeID, const string& conventionsID, const vector<string>& quotes);\n    //! Default destructor\n    virtual ~DirectYieldCurveSegment() {}\n    //@}\n\n    //! \\name Serialisation\n    //@{\n    virtual void fromXML(XMLNode* node);\n    virtual XMLNode* toXML(XMLDocument& doc);\n    //@}\n\n    //! \\name Visitability\n    //@{\n    virtual void accept(AcyclicVisitor&);\n    //@}\n};\n\n//! Simple yield curve segment\n/*!\n  A simple yield curve segment is used when the curve segment is determined by\n  a set of quotes and a projection curve.\n\n  \\ingroup configuration\n*/\nclass SimpleYieldCurveSegment : public YieldCurveSegment {\npublic:\n    //! \\name Constructors/Destructors\n    //@{\n    //! Default constructor\n    SimpleYieldCurveSegment() {}\n    //! Detailed constructor\n    SimpleYieldCurveSegment(const string& typeID, const string& conventionsID, const vector<string>& quotes,\n                            const string& projectionCurveID = string());\n    //! Default destructor\n    virtual ~SimpleYieldCurveSegment() {}\n    //@}\n\n    //! \\name Serialisation\n    //@{\n    virtual void fromXML(XMLNode* node);\n    virtual XMLNode* toXML(XMLDocument& doc);\n    //@}\n\n    //! \\name Inspectors\n    //@{\n    const string& projectionCurveID() const { return projectionCurveID_; }\n    //@}\n\n    //! \\name Visitability\n    //@{\n    virtual void accept(AcyclicVisitor&);\n    //@}\n\nprivate:\n    string projectionCurveID_;\n};\n\n//! Avergae OIS yield curve segment\n/*!\n  The average OIS yield curve segment is used e.g. for USD OIS curve building where\n  the curve segment is determined by  a set of composite quotes and a projection curve.\n  The composite quote is  represented here as a pair of quote strings, a tenor basis spread\n  and an interest rate swap quote.\n\n  \\ingroup configuration\n*/\nclass AverageOISYieldCurveSegment : public YieldCurveSegment {\npublic:\n    //! \\name Constructors/Destructors\n    //@{\n    //! Default constructor\n    AverageOISYieldCurveSegment() {}\n    //! Detailec constructor\n    AverageOISYieldCurveSegment(const string& typeID, const string& conventionsID, const vector<string>& quotes,\n                                const string& projectionCurveID);\n    //! Default destructor\n    virtual ~AverageOISYieldCurveSegment() {}\n    //@}\n\n    //! \\name Serialisation\n    //@{\n    virtual void fromXML(XMLNode* node);\n    virtual XMLNode* toXML(XMLDocument& doc);\n    //@}\n\n    //! \\name Inspectors\n    //@{\n    const string& projectionCurveID() const { return projectionCurveID_; }\n    //@}\n\n    //! \\name Visitability\n    //@{\n    virtual void accept(AcyclicVisitor&);\n    //@}\n\nprivate:\n    string projectionCurveID_;\n};\n\n//! Tenor Basis yield curve segment\n/*!\n  Yield curve building from tenor basis swap quotes requires a set of tenor\n  basis spread quotes and the projection curve for either the shorter or the longer tenor\n  which acts as the reference curve.\n\n  \\ingroup configuration\n*/\nclass TenorBasisYieldCurveSegment : public YieldCurveSegment {\npublic:\n    //! \\name Constructors/Destructors\n    //@{\n    //! Default constructor\n    TenorBasisYieldCurveSegment() {}\n    //! Detailed constructor\n    TenorBasisYieldCurveSegment(const string& typeID, const string& conventionsID, const vector<string>& quotes,\n                                const string& shortProjectionCurveID, const string& longProjectionCurveID);\n    //! Default destructor\n    virtual ~TenorBasisYieldCurveSegment() {}\n    //@}\n\n    //!\\name Serialisation\n    //@{\n    virtual void fromXML(XMLNode* node);\n    virtual XMLNode* toXML(XMLDocument& doc);\n    //@}\n\n    //! \\name Inspectors\n    //@{\n    const string& shortProjectionCurveID() const { return shortProjectionCurveID_; }\n    const string& longProjectionCurveID() const { return longProjectionCurveID_; }\n    //@}\n\n    //! \\name Visitability\n    //@{\n    virtual void accept(AcyclicVisitor&);\n    //@}\n\nprivate:\n    string shortProjectionCurveID_;\n    string longProjectionCurveID_;\n};\n\n//! Cross Currency yield curve segment\n/*!\n  Cross currency basis spread adjusted discount curves for 'domestic' currency cash flows\n  are built using this segment type which requires cross currency basis spreads quotes,\n  the spot FX quote ID and at least the 'foreign' discount curve ID.\n  Projection curves for both currencies can be provided as well for consistency with\n  tenor basis in each currency.\n\n  \\ingroup configuration\n*/\nclass CrossCcyYieldCurveSegment : public YieldCurveSegment {\npublic:\n    //! \\name Constructors/Destructors\n    //@{\n    //! Default constructor\n    CrossCcyYieldCurveSegment() {}\n    //! Detailed constructor\n    CrossCcyYieldCurveSegment(const string& typeID, const string& conventionsID, const vector<string>& quotes,\n                              const string& spotRateID, const string& foreignDiscountCurveID,\n                              const string& domesticProjectionCurveID = string(),\n                              const string& foreignProjectionCurveID = string());\n    //! Default destructor\n    virtual ~CrossCcyYieldCurveSegment() {}\n    //@}\n\n    //! \\name Serialisation\n    //@{\n    virtual void fromXML(XMLNode* node);\n    virtual XMLNode* toXML(XMLDocument& doc);\n    //@}\n\n    //! \\name Inspectors\n    //@{\n    const string& spotRateID() const { return spotRateID_; }\n    const string& foreignDiscountCurveID() const { return foreignDiscountCurveID_; }\n    const string& domesticProjectionCurveID() const { return domesticProjectionCurveID_; }\n    const string& foreignProjectionCurveID() const { return foreignProjectionCurveID_; }\n    //@}\n\n    //! \\name Visitability\n    //@{\n    virtual void accept(AcyclicVisitor&);\n    //@}\n\nprivate:\n    string spotRateID_;\n    string foreignDiscountCurveID_;\n    string domesticProjectionCurveID_;\n    string foreignProjectionCurveID_;\n};\n\n//! Zero Spreaded yield curve segment\n/*!\n  A zero spreaded segment is used to build a yield curve from zero spread quotes and\n  a reference yield curve.\n\n  \\ingroup configuration\n*/\nclass ZeroSpreadedYieldCurveSegment : public YieldCurveSegment {\npublic:\n    //! \\name Constructors/Destructors\n    //@{\n    //! Default constructor\n    ZeroSpreadedYieldCurveSegment() {}\n    //! Detailed constructor\n    ZeroSpreadedYieldCurveSegment(const string& typeID, const string& conventionsID, const vector<string>& quotes,\n                                  const string& referenceCurveID);\n    //! Default destructor\n    virtual ~ZeroSpreadedYieldCurveSegment() {}\n    //@}\n\n    //! \\name Serialisation\n    //@{\n    virtual void fromXML(XMLNode* node);\n    virtual XMLNode* toXML(XMLDocument& doc);\n    //@}\n\n    //! \\name Inspectors\n    //@{\n    const string& referenceCurveID() const { return referenceCurveID_; }\n    //@}\n\n    //! \\name Visitability\n    //@{\n    virtual void accept(AcyclicVisitor&);\n    //@}\n\nprivate:\n    string referenceCurveID_;\n};\n\n//! Discount ratio yield curve segment\n/*! Used to configure a QuantExt::DiscountRatioModifiedCurve.\n\n    \\ingroup configuration\n*/\nclass DiscountRatioYieldCurveSegment : public YieldCurveSegment {\npublic:\n    //! \\name Constructors/Destructors\n    //@{\n    //! Default constructor\n    DiscountRatioYieldCurveSegment() {}\n    //! Detailed constructor\n    DiscountRatioYieldCurveSegment(const std::string& typeId, const std::string& baseCurveId,\n                                   const std::string& baseCurveCurrency, const std::string& numeratorCurveId,\n                                   const std::string& numeratorCurveCurrency, const std::string& denominatorCurveId,\n                                   const std::string& denominatorCurveCurrency);\n    //@}\n\n    //! \\name Serialisation\n    //@{\n    virtual void fromXML(XMLNode* node);\n    virtual XMLNode* toXML(XMLDocument& doc);\n    //@}\n\n    //! \\name Inspectors\n    //@{\n    const string& baseCurveId() const { return baseCurveId_; }\n    const string& baseCurveCurrency() const { return baseCurveCurrency_; }\n    const string& numeratorCurveId() const { return numeratorCurveId_; }\n    const string& numeratorCurveCurrency() const { return numeratorCurveCurrency_; }\n    const string& denominatorCurveId() const { return denominatorCurveId_; }\n    const string& denominatorCurveCurrency() const { return denominatorCurveCurrency_; }\n    //@}\n\n    //! \\name Visitability\n    //@{\n    void accept(QuantLib::AcyclicVisitor& v);\n    //@}\n\nprivate:\n    std::string baseCurveId_;\n    std::string baseCurveCurrency_;\n    std::string numeratorCurveId_;\n    std::string numeratorCurveCurrency_;\n    std::string denominatorCurveId_;\n    std::string denominatorCurveCurrency_;\n};\n\n//! Yield Curve configuration\n/*!\n  Wrapper class containing all yield curve segments needed to build a yield curve.\n\n  \\ingroup configuration\n */\nclass YieldCurveConfig : public CurveConfig {\npublic:\n    //! \\name Constructors/Destructurs\n    //@{\n    //! Default constructor\n    YieldCurveConfig() {}\n    //! Detailed constructor\n    YieldCurveConfig(const string& curveID, const string& curveDescription, const string& currency,\n                     const string& discountCurveID, const vector<boost::shared_ptr<YieldCurveSegment>>& curveSegments,\n                     const string& interpolationVariable = \"Discount\", const string& interpolationMethod = \"LogLinear\",\n                     const string& zeroDayCounter = \"A365\", bool extrapolation = true, Real tolerance = 1.0e-12);\n    //! Default destructor\n    virtual ~YieldCurveConfig() {}\n    //@}\n\n    //! \\name Serilalisation\n    //@{\n    virtual void fromXML(XMLNode* node) override;\n    virtual XMLNode* toXML(XMLDocument& doc) override;\n    //@}\n\n    //! \\name Inspectors\n    //@{\n    const string& currency() const { return currency_; }\n    const string& discountCurveID() const { return discountCurveID_; }\n    const vector<boost::shared_ptr<YieldCurveSegment>>& curveSegments() const { return curveSegments_; }\n    const string& interpolationVariable() const { return interpolationVariable_; }\n    const string& interpolationMethod() const { return interpolationMethod_; }\n    const string& zeroDayCounter() const { return zeroDayCounter_; }\n    bool extrapolation() const { return extrapolation_; }\n    Real tolerance() const { return tolerance_; }\n    const set<string>& requiredYieldCurveIDs() const { return requiredYieldCurveIDs_; }\n    //@}\n\n    //! \\name Setters\n    //@{\n    string& interpolationVariable() { return interpolationVariable_; }\n    string& interpolationMethod() { return interpolationMethod_; }\n    string& zeroDayCounter() { return zeroDayCounter_; }\n    bool& extrapolation() { return extrapolation_; }\n    Real& tolerance() { return tolerance_; }\n    //@}\n\n    const vector<string>& quotes() override;\n\nprivate:\n    void populateRequiredYieldCurveIDs();\n\n    // Mandatory members\n    string currency_;\n    string discountCurveID_;\n    vector<boost::shared_ptr<YieldCurveSegment>> curveSegments_;\n    set<string> requiredYieldCurveIDs_;\n\n    // Optional members\n    string interpolationVariable_;\n    string interpolationMethod_;\n    string zeroDayCounter_;\n    bool extrapolation_;\n    Real tolerance_;\n};\n\n// Map form curveID to YieldCurveConfig\nusing YieldCurveConfigMap = std::map<string, boost::shared_ptr<YieldCurveConfig>>;\n} // namespace data\n} // namespace ore\n", "meta": {"hexsha": "f74dd0c46281019abea779b52b0fb77739a6e4b0", "size": 14946, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "OREData/ored/configuration/yieldcurveconfig.hpp", "max_stars_repo_name": "paul-giltinan/Engine", "max_stars_repo_head_hexsha": "49b6e142905ca2cce93c2ae46e9ac69380d9f7a1", "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": "OREData/ored/configuration/yieldcurveconfig.hpp", "max_issues_repo_name": "paul-giltinan/Engine", "max_issues_repo_head_hexsha": "49b6e142905ca2cce93c2ae46e9ac69380d9f7a1", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/configuration/yieldcurveconfig.hpp", "max_forks_repo_name": "paul-giltinan/Engine", "max_forks_repo_head_hexsha": "49b6e142905ca2cce93c2ae46e9ac69380d9f7a1", "max_forks_repo_licenses": ["BSD-3-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.5020408163, "max_line_length": 119, "alphanum_fraction": 0.6826575672, "num_tokens": 3326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.2945399160675766}}
{"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: Tobias Leibner\n\n#ifndef DUNE_STUFF_LA_CONTAINER_VECTOR_INTERFACE_HH\n#define DUNE_STUFF_LA_CONTAINER_VECTOR_INTERFACE_HH\n\n#include <cmath>\n#include <limits>\n#include <iostream>\n#include <vector>\n#include <complex>\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <dune/common/ftraits.hh>\n\n#include <dune/stuff/common/crtp.hh>\n#include <dune/stuff/common/exceptions.hh>\n#include <dune/stuff/common/float_cmp.hh>\n#include <dune/stuff/common/type_utils.hh>\n#include <dune/stuff/common/vector.hh>\n#include <dune/stuff/common/math.hh>\n\n#include \"container-interface.hh\"\n#include \"vector-interface-internal.hh\"\n\nnamespace Dune {\nnamespace Stuff {\nnamespace LA {\n\n/**\n *  \\brief  Contains tags mostly needed for python bindings.\n */\nnamespace Tags {\n\nclass VectorInterface\n{\n};\n\n} // namespace Tags\n\ntemplate <class Traits, class ScalarImp = typename Traits::ScalarType>\nclass VectorInterface : public ContainerInterface<Traits, ScalarImp>, public Tags::VectorInterface\n{\npublic:\n  typedef typename Traits::derived_type derived_type;\n  typedef typename Dune::FieldTraits<ScalarImp>::field_type ScalarType;\n  typedef typename Dune::FieldTraits<ScalarImp>::real_type RealType;\n\n  typedef internal::VectorInputIterator<Traits, ScalarType> const_iterator;\n  typedef internal::VectorOutputIterator<Traits, ScalarType> iterator;\n\n  static_assert(std::is_same<ScalarType, typename Traits::ScalarType>::value, \"\");\n\n  virtual ~VectorInterface() {}\n\n  /// \\name Have to be implemented by a derived class in addition to the ones required by ContainerInterface!\n  /// \\{\n\n  /**\n   * \\brief   The size of the vector.\n   * \\return  The size of the vector.\n   */\n  inline size_t size() const\n  {\n    CHECK_CRTP(this->as_imp().size());\n    return this->as_imp().size();\n  }\n\n  /**\n   * \\brief Add a scalar to the iith entry.\n   */\n  inline void add_to_entry(const size_t ii, const ScalarType& value)\n  {\n    CHECK_AND_CALL_CRTP(this->as_imp().add_to_entry(ii, value));\n  }\n\n  /**\n   * \\brief Set the iith entry to given scalar.\n   */\n  inline void set_entry(const size_t ii, const ScalarType& value)\n  {\n    CHECK_AND_CALL_CRTP(this->as_imp().set_entry(ii, value));\n  }\n\n  /**\n   * \\brief Get the iith entry.\n   * \\todo  Default implement using get_entry_ref!\n   */\n  inline ScalarType get_entry(const size_t ii) const\n  {\n    CHECK_CRTP(this->as_imp().get_entry(ii));\n    return this->as_imp().get_entry(ii);\n  }\n\n  inline ScalarType& get_entry_ref(const size_t ii)\n  {\n    CHECK_CRTP(this->as_imp().get_entry_ref(ii));\n    return this->as_imp().get_entry_ref(ii);\n  }\n\n  inline const ScalarType& get_entry_ref(const size_t ii) const\n  {\n    CHECK_CRTP(this->as_imp().get_entry_ref(ii));\n    return this->as_imp().get_entry_ref(ii);\n  }\n\n  /// \\}\n  /// \\name Provided by the interface for convenience!\n  /// \\note Those marked as virtual may be implemented more efficiently in a derived class!\n  /// \\{\n\n  virtual void set_all(const ScalarType& val)\n  {\n    for (auto& element : *this)\n      element = val;\n  }\n\n  virtual bool valid() const\n  {\n    for (const auto& val : *this) {\n      if (Common::isnan(val) || Common::isinf(val))\n        return false;\n    }\n    return true;\n  } // ... valid()\n\n  /**\n   * \\brief Get writable reference to the iith entry.\n   */\n  inline ScalarType& operator[](const size_t ii) { return get_entry_ref(ii); }\n\n  /**\n   * \\brief Get read-only reference to the iith entry.\n   */\n  inline const ScalarType& operator[](const size_t ii) const { return get_entry_ref(ii); }\n\n  /**\n   * \\brief   The dimension of the vector.\n   * \\return  The dimension of the vector.\n   * \\see     size()\n   */\n  inline size_t dim() const { return size(); }\n\n  virtual ScalarType mean() const\n  {\n    ScalarType ret = 0.0;\n    for (const auto& element : *this)\n      ret += element;\n    ret /= size();\n    return ret;\n  } // ... mean()\n\n  /**\n   *  \\brief  The maximum absolute value of the vector.\n   *  \\return A pair of the lowest index at which the maximum is attained and the absolute maximum value.\n   *  \\note   If you override this method please use exceptions instead of assertions (for the python bindings).\n   */\n  virtual std::pair<size_t, RealType> amax() const\n  {\n    auto result = std::make_pair(size_t(0), RealType(0));\n    for (size_t ii = 0; ii < size(); ++ii) {\n      const auto value = std::abs(get_entry_ref(ii));\n      if (value > result.second) {\n        result.first  = ii;\n        result.second = value;\n      }\n    }\n    return result;\n  } // ... amax(...)\n\n  /**\n   *  \\brief  Check vectors for equality.\n   *          Equality of two vectors is defined as in Dune::FloatCmp componentwise.\n   *  \\param  other   A vector of same dimension to compare with.\n   *  \\param  epsilon See Dune::FloatCmp.\n   *  \\return Truth value of the comparison.\n   *  \\see    Dune::Stuff::Common::FloatCmp\n   *  \\note   If you override this method please use exceptions instead of assertions (for the python bindings).\n   */\n  virtual bool\n      almost_equal(const derived_type& other,\n                   const ScalarType epsilon = Stuff::Common::FloatCmp::DefaultEpsilon<ScalarType>::value()) const\n  {\n    if (other.size() != size())\n      DUNE_THROW(Exceptions::shapes_do_not_match,\n                 \"The size of other (\" << other.size() << \") does not match the size of this (\" << size() << \")!\");\n    return Stuff::Common::FloatCmp::eq(this->as_imp(), other, epsilon);\n  } // ... almost_equal(...)\n\n  /**\n   *  \\brief  Check vectors for equality (variant for arbitrary derived combinations).\n   *          Equality of two vectors is defined as in Dune::FloatCmp componentwise.\n   *  \\param  other   A vector of same dimension to compare with.\n   *  \\param  epsilon See Dune::FloatCmp.\n   *  \\return Truth value of the comparison.\n   *  \\see    Dune::Stuff::Common::FloatCmp\n   */\n  template <class T>\n  bool almost_equal(const VectorInterface<T>& other,\n                    const ScalarType epsilon = Stuff::Common::FloatCmp::DefaultEpsilon<ScalarType>::value()) const\n  {\n    if (other.size() != size())\n      DUNE_THROW(Exceptions::shapes_do_not_match,\n                 \"The size of other (\" << other.size() << \") does not match the size of this (\" << size() << \")!\");\n    return Stuff::Common::FloatCmp::eq(this->as_imp(), other.as_imp(), epsilon);\n  } // ... almost_equal(...)\n\n  /**\n   *  \\brief  Computes the scalar products between two vectors.\n   *  \\param  other The second factor.\n   *  \\return The scalar product.\n   *  \\note   If you override this method please use exceptions instead of assertions (for the python bindings).\n   */\n  virtual ScalarType dot(const derived_type& other) const\n  {\n    if (other.size() != size())\n      DUNE_THROW(Exceptions::shapes_do_not_match,\n                 \"The size of other (\" << other.size() << \") does not match the size of this (\" << size() << \")!\");\n    ScalarType result = 0;\n    for (size_t ii = 0; ii < size(); ++ii)\n      result += std::conj(get_entry_ref(ii)) * other.get_entry_ref(ii);\n    return result;\n  } // ... dot(...)\n\n  /**\n   *  \\brief  The l1-norm of the vector.\n   *  \\return The l1-norm of the vector.\n   *  \\note   If you override this method please use exceptions instead of assertions (for the python bindings).\n   */\n  virtual RealType l1_norm() const\n  {\n    RealType result = 0;\n    for (size_t ii = 0; ii < size(); ++ii)\n      result += std::abs(get_entry_ref(ii));\n    return result;\n  } // ... l1_norm(...)\n\n  /**\n   *  \\brief  The l2-norm of the vector.\n   *  \\return The l2-norm of the vector.\n   *  \\note   If you override this method please use exceptions instead of assertions (for the python bindings).\n   */\n  virtual RealType l2_norm() const\n  {\n    return std::sqrt(std::abs(dot(this->as_imp(*this)))); // std::abs is only needed for the right return type:\n    // v.dot(v) should always be a ScalarType with zero imaginary part\n  }\n\n  /**\n   *  \\brief  The l-infintiy-norm of the vector.\n   *  \\return The l-infintiy-norm of the vector.\n   *  \\note   If you override this method please use exceptions instead of assertions (for the python bindings).\n   */\n  virtual RealType sup_norm() const { return amax().second; }\n\n  virtual ScalarType standard_deviation() const\n  {\n    const ScalarType mu = mean();\n    ScalarType sigma = 0.0;\n    for (const auto& x_i : *this)\n      sigma += std::pow(x_i - mu, 2);\n    sigma /= size();\n    return std::sqrt(sigma);\n  } // ... standard_deviation(...)\n\n  /**\n   *  \\brief  Adds two vectors.\n   *  \\param  other   The right summand.\n   *  \\param  result  Vector to write the result of this + other to\n   *  \\note   If you override this method please use exceptions instead of assertions (for the python bindings).\n   *  \\note   If you are looking for the old (now deprecated) add() method, \\see add_to_entry().\n   */\n  virtual void add(const derived_type& other, derived_type& result) const\n  {\n    if (other.size() != size())\n      DUNE_THROW(Exceptions::shapes_do_not_match,\n                 \"The size of other (\" << other.size() << \") does not match the size of this (\" << size() << \")!\");\n    if (result.size() != size())\n      DUNE_THROW(Exceptions::shapes_do_not_match,\n                 \"The size of result (\" << result.size() << \") does not match the size of this (\" << size() << \")!\");\n    for (size_t ii = 0; ii < size(); ++ii)\n      result.set_entry(ii, get_entry_ref(ii) + other.get_entry_ref(ii));\n  } // ... add(...)\n\n  /**\n   *  \\brief  Adds two vectors.\n   *  \\param  other The right summand.\n   *  \\return The sum of this and other.\n   *  \\note   If you override this method please use exceptions instead of assertions (for the python bindings).\n   *  \\note   If you are looking for the old (now deprecated) add() method, \\see add_to_entry().\n   */\n  virtual derived_type add(const derived_type& other) const\n  {\n    derived_type result = this->copy();\n    result.iadd(other);\n    return result;\n  } // ... add(...)\n\n  /**\n   *  \\brief  Inplace variant of add().\n   *  \\param  other The right summand.\n   *  \\note   If you override this method please use exceptions instead of assertions (for the python bindings).\n   */\n  virtual void iadd(const derived_type& other)\n  {\n    if (other.size() != size())\n      DUNE_THROW(Exceptions::shapes_do_not_match,\n                 \"The size of other (\" << other.size() << \") does not match the size of this (\" << size() << \")!\");\n    for (size_t ii = 0; ii < size(); ++ii)\n      set_entry(ii, get_entry_ref(ii) + other.get_entry_ref(ii));\n  } // ... iadd(...)\n\n  /**\n   *  \\brief  Subtracts two vectors.\n   *  \\param  other   The subtrahend.\n   *  \\param  result  The vectror to write the difference between this and other to.\n   *  \\note   If you override this method please use exceptions instead of assertions (for the python bindings).\n   */\n  virtual void sub(const derived_type& other, derived_type& result) const\n  {\n    if (other.size() != size())\n      DUNE_THROW(Exceptions::shapes_do_not_match,\n                 \"The size of other (\" << other.size() << \") does not match the size of this (\" << size() << \")!\");\n    if (result.size() != size())\n      DUNE_THROW(Exceptions::shapes_do_not_match,\n                 \"The size of result (\" << result.size() << \") does not match the size of this (\" << size() << \")!\");\n    for (size_t ii = 0; ii < size(); ++ii)\n      result.set_entry(ii, get_entry_ref(ii) - other.get_entry_ref(ii));\n  } // ... sub(...)\n\n  /**\n   *  \\brief  Subtracts two vectors.\n   *  \\param  other The subtrahend.\n   *  \\return The difference between this and other.\n   *  \\note   If you override this method please use exceptions instead of assertions (for the python bindings).\n   */\n  virtual derived_type sub(const derived_type& other) const\n  {\n    derived_type result = this->copy();\n    result.isub(other);\n    return result;\n  } // ... sub(...)\n\n  /**\n   *  \\brief  Inplace variant of sub().\n   *  \\param  other The subtrahend.\n   *  \\note   If you override this method please use exceptions instead of assertions (for the python bindings).\n   */\n  virtual void isub(const derived_type& other)\n  {\n    if (other.size() != size())\n      DUNE_THROW(Exceptions::shapes_do_not_match,\n                 \"The size of other (\" << other.size() << \") does not match the size of this (\" << size() << \")!\");\n    for (size_t ii = 0; ii < size(); ++ii)\n      set_entry(ii, get_entry_ref(ii) - other.get_entry_ref(ii));\n  } // ... isub(...)\n\n  /**\n   *  \\brief  Multiplies every component of this by a scalar.\n   *  \\param  alpha The scalar.\n   *  \\return The scaled copy of this.\n   */\n  virtual derived_type operator*(const ScalarType& alpha)\n  {\n    derived_type ret = this->copy();\n    ret *= alpha;\n    return ret;\n  } // ... operator*() ...\n\n  /**\n   *  \\brief  Computes the scalar products between this and another vector.\n   *  \\param  other The second factor.\n   *  \\return The scalar product.\n   *  \\see dot()\n   */\n  virtual ScalarType operator*(const derived_type& other) { return dot(other); }\n\n  /**\n   *  \\brief  Adds another vector to this, in-place variant.\n   *  \\param  other The second summand.\n   *  \\return The sum of this and other.\n   */\n  virtual derived_type& operator+=(const derived_type& other)\n  {\n    iadd(other);\n    return this->as_imp(*this);\n  }\n\n  /**\n   *  \\brief  Subtracts another vector from this, in-place variant.\n   *  \\param  other The subtrahend.\n   *  \\return The difference between this and other.\n   */\n  virtual derived_type& operator-=(const derived_type& other)\n  {\n    isub(other);\n    return this->as_imp(*this);\n  }\n\n  /**\n   *  \\brief  Adds two vectors.\n   *  \\param  other The second summand.\n   *  \\return The sum of the two vectors.\n   */\n  virtual derived_type operator+(const derived_type& other) const { return add(other); }\n\n  /**\n   *  \\brief  Substracts two vectors.\n   *  \\param  other The subtrahend\n   *  \\return The difference.\n   */\n  virtual derived_type operator-(const derived_type& other) const { return sub(other); }\n\n  virtual derived_type& operator+=(const ScalarType& scalar)\n  {\n    for (auto& element : *this)\n      element += scalar;\n    return this->as_imp(*this);\n  }\n\n  virtual derived_type& operator-=(const ScalarType& scalar)\n  {\n    for (auto& element : *this)\n      element -= scalar;\n    return this->as_imp(*this);\n  }\n\n  virtual derived_type& operator/=(const ScalarType& scalar)\n  {\n    for (auto& element : *this)\n      element /= scalar;\n    return this->as_imp(*this);\n  }\n\n  /**\n   *  \\brief  Check vectors for equality (componentwise) using almost_equal()\n   *  \\param  other   A vector of same dimension to compare with.\n   *  \\return Truth value of the comparison.\n   *  \\see    almost_equal()\n   */\n  virtual bool operator==(const derived_type& other) const { return almost_equal(other); }\n\n  /**\n   *  \\brief  Check vectors for inequality using !almost_equal()\n   *  \\param  other   A vector of same dimension to compare with.\n   *  \\return Truth value of the comparison.\n   */\n  virtual bool operator!=(const derived_type& other) const { return !(this->operator==(other)); }\n\n  /// \\}\n  /// \\name Necesarry for the python bindings.\n  /// \\{\n\n  /**\n   * \\brief Variant of dim() needed for the python bindings.\n   * \\see   dim()\n   */\n  inline DUNE_STUFF_SSIZE_T pb_dim() const\n  {\n    try {\n      return boost::numeric_cast<DUNE_STUFF_SSIZE_T>(dim());\n    } catch (boost::bad_numeric_cast& ee) {\n      DUNE_THROW(Exceptions::external_error,\n                 \"There was an error in boost converting '\" << dim() << \"' to '\"\n                                                            << Common::Typename<ScalarType>::value()\n                                                            << \"': \"\n                                                            << ee.what());\n    }\n  } // ... pb_dim(...)\n\n  /**\n   * \\brief Variant of add_to_entry() needed for the python bindings.\n   * \\see   add_to_entry()\n   */\n  inline void pb_add_to_entry(const DUNE_STUFF_SSIZE_T ii, const ScalarType& value)\n  {\n    try {\n      add_to_entry(boost::numeric_cast<size_t>(ii), value);\n    } catch (boost::bad_numeric_cast& ee) {\n      DUNE_THROW(Exceptions::external_error,\n                 \"There was an error in boost converting '\" << ii << \"' to '\" << Common::Typename<size_t>::value()\n                                                            << \"': \"\n                                                            << ee.what());\n    }\n  } // ... pb_add_to_entry(...)\n\n  /**\n   * \\brief Variant of set_entry() needed for the python bindings.\n   * \\see   set_entry()\n   */\n  inline void pb_set_entry(const DUNE_STUFF_SSIZE_T ii, const ScalarType& value)\n  {\n    try {\n      set_entry(boost::numeric_cast<size_t>(ii), value);\n    } catch (boost::bad_numeric_cast& ee) {\n      DUNE_THROW(Exceptions::external_error,\n                 \"There was an error in boost converting '\" << ii << \"' to '\" << Common::Typename<size_t>::value()\n                                                            << \"': \"\n                                                            << ee.what());\n    }\n  } // ... pb_set_entry(...)\n\n  /**\n   * \\brief Variant of get_entry() needed for the python bindings.\n   * \\see   get_entry()\n   */\n  inline ScalarType pb_get_entry(const DUNE_STUFF_SSIZE_T ii)\n  {\n    try {\n      return get_entry(boost::numeric_cast<size_t>(ii));\n    } catch (boost::bad_numeric_cast& ee) {\n      DUNE_THROW(Exceptions::external_error,\n                 \"There was an error in boost converting '\" << ii << \"' to '\" << Common::Typename<size_t>::value()\n                                                            << \"': \"\n                                                            << ee.what());\n    }\n  } // ... pb_get_entry(...)\n\n  /**\n   * \\brief Variant of amax() needed for the python bindings.\n   * \\see   amax()\n   */\n  std::vector<RealType> pb_amax() const\n  {\n    const auto max = amax();\n    try {\n      return {boost::numeric_cast<RealType>(max.first), max.second};\n    } catch (boost::bad_numeric_cast& ee) {\n      DUNE_THROW(Exceptions::external_error,\n                 \"There was an error in boost converting '\" << max.first << \"' to '\"\n                                                            << Common::Typename<RealType>::value()\n                                                            << \"': \"\n                                                            << ee.what());\n    }\n  } // ... pb_amax(...)\n\n  std::vector<ScalarType> components(const std::vector<DUNE_STUFF_SSIZE_T>& component_indices) const\n  {\n    if (component_indices.size() > dim())\n      DUNE_THROW(Exceptions::index_out_of_range,\n                 \"size of component_indices (\" << component_indices.size() << \") is larger than the dim of this (\"\n                                               << dim()\n                                               << \")!\");\n    std::vector<ScalarType> values(component_indices.size(), ScalarType(0));\n    try {\n      for (size_t ii = 0; ii < component_indices.size(); ++ii) {\n        const size_t component = boost::numeric_cast<size_t>(component_indices[ii]);\n        if (component >= dim())\n          DUNE_THROW(Exceptions::index_out_of_range,\n                     \"component_indices[\" << ii << \"] is too large for this (\" << dim() << \")!\");\n        values[ii] = get_entry(component);\n      }\n    } catch (boost::bad_numeric_cast& ee) {\n      DUNE_THROW(Exceptions::external_error, \"There was an error in boost during a numeric_cast: \" << ee.what());\n    }\n    return values;\n  } // components(...)\n\n  /// \\}\n\n  iterator begin() { return iterator(*this); }\n\n  const_iterator begin() const { return const_iterator(*this); }\n\n  iterator end() { return iterator(*this, true); }\n\n  const_iterator end() const { return const_iterator(*this, true); }\n\n  operator std::vector<ScalarType>() const\n  {\n    std::vector<ScalarType> ret(dim());\n    for (size_t ii = 0; ii < dim(); ++ii)\n      ret[ii] = this->operator[](ii);\n    return ret;\n  }\n\nprivate:\n  template <class T, class S>\n  friend std::ostream& operator<<(std::ostream& /*out*/, const VectorInterface<T, S>& /*vector*/);\n}; // class VectorInterface\n\nnamespace internal {\n\ntemplate <class V>\nstruct is_vector_helper\n{\n  DSC_has_typedef_initialize_once(Traits) DSC_has_typedef_initialize_once(ScalarType)\n\n      static const bool is_candidate = DSC_has_typedef(Traits)<V>::value && DSC_has_typedef(ScalarType)<V>::value;\n}; // class is_vector_helper\n\n} // namespace internal\n\ntemplate <class V, bool candidate = internal::is_vector_helper<V>::is_candidate>\nstruct is_vector : public std::is_base_of<VectorInterface<typename V::Traits, typename V::ScalarType>, V>\n{\n};\n\ntemplate <class V>\nstruct is_vector<V, false> : public std::false_type\n{\n};\n\nnamespace internal {\n\ntemplate <class VectorImp>\nstruct VectorAbstractionBase\n{\n  static const bool is_vector = LA::is_vector<VectorImp>::value;\n\n  static const bool has_static_size = false;\n\n  static const size_t static_size = std::numeric_limits<size_t>::max();\n\n  typedef typename std::conditional<is_vector, VectorImp, void>::type VectorType;\n  typedef typename std::conditional<is_vector, typename VectorImp::ScalarType, void>::type ScalarType;\n  typedef typename std::conditional<is_vector, typename VectorImp::RealType, void>::type RealType;\n  typedef ScalarType S;\n  typedef RealType R;\n\n  static inline typename std::enable_if<is_vector, VectorType>::type create(const size_t sz) { return VectorType(sz); }\n\n  static inline typename std::enable_if<is_vector, VectorType>::type create(const size_t sz, const ScalarType& val)\n  {\n    return VectorType(sz, val);\n  }\n}; // struct VectorAbstractionBase\n\n} // namespace internal\n\ntemplate <class T, class S>\nstd::ostream& operator<<(std::ostream& out, const VectorInterface<T, S>& vector)\n{\n  out << \"[\";\n  const size_t sz = vector.size();\n  if (sz > 0) {\n    out << vector[0];\n    for (size_t ii = 1; ii < sz; ++ii)\n      out << \"\\n \" << vector[ii];\n  } else\n    out << \" \";\n  out << \"]\";\n  return out;\n} // ... operator<<(...)\n\n} // namespace LA\n} // namespace Stuff\n} // namespace Dune\n\n#endif // DUNE_STUFF_LA_CONTAINER_VECTOR_INTERFACE_HH\n", "meta": {"hexsha": "f0b84534efbda913141b26f0eaddf7527ca5c1ad", "size": 22254, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/stuff/la/container/vector-interface.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/la/container/vector-interface.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/la/container/vector-interface.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": 33.9237804878, "max_line_length": 119, "alphanum_fraction": 0.6183158084, "num_tokens": 5538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.29453990824588383}}
{"text": "// Copyright (c) 2008-2017 Emil Dotchevski and Reverge Studios, Inc.\n\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_QVM_F622919DE18B1FDAB0CA992B9729D49\n#define BOOST_QVM_F622919DE18B1FDAB0CA992B9729D49\n\n// This file was generated by a program. Do not edit manually.\n\n#include <boost/qvm/deduce_scalar.hpp>\n#include <boost/qvm/deduce_vec.hpp>\n#include <boost/qvm/error.hpp>\n#include <boost/qvm/gen/vec_assign2.hpp>\n#include <boost/qvm/math.hpp>\n#include <boost/qvm/static_assert.hpp>\n#include <boost/qvm/throw_exception.hpp>\n\nnamespace boost {\nnamespace qvm {\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename lazy_enable_if_c<vec_traits<A>::dim == 2 &&\n                                  vec_traits<B>::dim == 2,\n                              deduce_vec2<A, B, 2>>::type\n    operator+(A const &a, B const &b) {\n  typedef typename deduce_vec2<A, B, 2>::type R;\n  BOOST_QVM_STATIC_ASSERT(vec_traits<R>::dim == 2);\n  R r;\n  vec_traits<R>::template write_element<0>(r) =\n      vec_traits<A>::template read_element<0>(a) +\n      vec_traits<B>::template read_element<0>(b);\n  vec_traits<R>::template write_element<1>(r) =\n      vec_traits<A>::template read_element<1>(a) +\n      vec_traits<B>::template read_element<1>(b);\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator+;\n}\n\nnamespace qvm_detail {\ntemplate <int D> struct plus_vv_defined;\n\ntemplate <> struct plus_vv_defined<2> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename lazy_enable_if_c<vec_traits<A>::dim == 2 &&\n                                  vec_traits<B>::dim == 2,\n                              deduce_vec2<A, B, 2>>::type\n    operator-(A const &a, B const &b) {\n  typedef typename deduce_vec2<A, B, 2>::type R;\n  BOOST_QVM_STATIC_ASSERT(vec_traits<R>::dim == 2);\n  R r;\n  vec_traits<R>::template write_element<0>(r) =\n      vec_traits<A>::template read_element<0>(a) -\n      vec_traits<B>::template read_element<0>(b);\n  vec_traits<R>::template write_element<1>(r) =\n      vec_traits<A>::template read_element<1>(a) -\n      vec_traits<B>::template read_element<1>(b);\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator-;\n}\n\nnamespace qvm_detail {\ntemplate <int D> struct minus_vv_defined;\n\ntemplate <> struct minus_vv_defined<2> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<vec_traits<A>::dim == 2 && vec_traits<B>::dim == 2,\n                         A &>::type\n    operator+=(A &a, B const &b) {\n  vec_traits<A>::template write_element<0>(a) +=\n      vec_traits<B>::template read_element<0>(b);\n  vec_traits<A>::template write_element<1>(a) +=\n      vec_traits<B>::template read_element<1>(b);\n  return a;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator+=;\n}\n\nnamespace qvm_detail {\ntemplate <int D> struct plus_eq_vv_defined;\n\ntemplate <> struct plus_eq_vv_defined<2> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<vec_traits<A>::dim == 2 && vec_traits<B>::dim == 2,\n                         A &>::type\n    operator-=(A &a, B const &b) {\n  vec_traits<A>::template write_element<0>(a) -=\n      vec_traits<B>::template read_element<0>(b);\n  vec_traits<A>::template write_element<1>(a) -=\n      vec_traits<B>::template read_element<1>(b);\n  return a;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator-=;\n}\n\nnamespace qvm_detail {\ntemplate <int D> struct minus_eq_vv_defined;\n\ntemplate <> struct minus_eq_vv_defined<2> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename lazy_enable_if_c<vec_traits<A>::dim == 2 && is_scalar<B>::value,\n                              deduce_vec<A>>::type\n    operator*(A const &a, B b) {\n  typedef typename deduce_vec<A>::type R;\n  R r;\n  vec_traits<R>::template write_element<0>(r) =\n      vec_traits<A>::template read_element<0>(a) * b;\n  vec_traits<R>::template write_element<1>(r) =\n      vec_traits<A>::template read_element<1>(a) * b;\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator*;\n}\n\nnamespace qvm_detail {\ntemplate <int D> struct mul_vs_defined;\n\ntemplate <> struct mul_vs_defined<2> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename lazy_enable_if_c<is_scalar<A>::value && vec_traits<B>::dim == 2,\n                              deduce_vec<B>>::type\n    operator*(A a, B const &b) {\n  typedef typename deduce_vec<B>::type R;\n  R r;\n  vec_traits<R>::template write_element<0>(r) =\n      a * vec_traits<B>::template read_element<0>(b);\n  vec_traits<R>::template write_element<1>(r) =\n      a * vec_traits<B>::template read_element<1>(b);\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator*;\n}\n\nnamespace qvm_detail {\ntemplate <int D> struct mul_sv_defined;\n\ntemplate <> struct mul_sv_defined<2> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<vec_traits<A>::dim == 2 && is_scalar<B>::value,\n                         A &>::type\n    operator*=(A &a, B b) {\n  vec_traits<A>::template write_element<0>(a) *= b;\n  vec_traits<A>::template write_element<1>(a) *= b;\n  return a;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator*=;\n}\n\nnamespace qvm_detail {\ntemplate <int D> struct mul_eq_vs_defined;\n\ntemplate <> struct mul_eq_vs_defined<2> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename lazy_enable_if_c<vec_traits<A>::dim == 2 && is_scalar<B>::value,\n                              deduce_vec<A>>::type\n    operator/(A const &a, B b) {\n  typedef typename deduce_vec<A>::type R;\n  R r;\n  vec_traits<R>::template write_element<0>(r) =\n      vec_traits<A>::template read_element<0>(a) / b;\n  vec_traits<R>::template write_element<1>(r) =\n      vec_traits<A>::template read_element<1>(a) / b;\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator/;\n}\n\nnamespace qvm_detail {\ntemplate <int D> struct div_vs_defined;\n\ntemplate <> struct div_vs_defined<2> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<vec_traits<A>::dim == 2 && is_scalar<B>::value,\n                         A &>::type\n    operator/=(A &a, B b) {\n  vec_traits<A>::template write_element<0>(a) /= b;\n  vec_traits<A>::template write_element<1>(a) /= b;\n  return a;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator/=;\n}\n\nnamespace qvm_detail {\ntemplate <int D> struct div_eq_vs_defined;\n\ntemplate <> struct div_eq_vs_defined<2> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class R, class A>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<is_vec<A>::value && vec_traits<R>::dim == 2 &&\n                             vec_traits<A>::dim == 2,\n                         R>::type\n    convert_to(A const &a) {\n  R r;\n  vec_traits<R>::template write_element<0>(r) =\n      vec_traits<A>::template read_element<0>(a);\n  vec_traits<R>::template write_element<1>(r) =\n      vec_traits<A>::template read_element<1>(a);\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::convert_to;\n}\n\nnamespace qvm_detail {\ntemplate <int D> struct convert_to_v_defined;\n\ntemplate <> struct convert_to_v_defined<2> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<vec_traits<A>::dim == 2 && vec_traits<B>::dim == 2,\n                         bool>::type\n    operator==(A const &a, B const &b) {\n  return vec_traits<A>::template read_element<0>(a) ==\n             vec_traits<B>::template read_element<0>(b) &&\n         vec_traits<A>::template read_element<1>(a) ==\n             vec_traits<B>::template read_element<1>(b);\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator==;\n}\n\nnamespace qvm_detail {\ntemplate <int D> struct eq_vv_defined;\n\ntemplate <> struct eq_vv_defined<2> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<vec_traits<A>::dim == 2 && vec_traits<B>::dim == 2,\n                         bool>::type\n    operator!=(A const &a, B const &b) {\n  return !(vec_traits<A>::template read_element<0>(a) ==\n           vec_traits<B>::template read_element<0>(b)) ||\n         !(vec_traits<A>::template read_element<1>(a) ==\n           vec_traits<B>::template read_element<1>(b));\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator!=;\n}\n\nnamespace qvm_detail {\ntemplate <int D> struct neq_vv_defined;\n\ntemplate <> struct neq_vv_defined<2> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS\n    typename lazy_enable_if_c<vec_traits<A>::dim == 2, deduce_vec<A>>::type\n    operator-(A const &a) {\n  typedef typename deduce_vec<A>::type R;\n  R r;\n  vec_traits<R>::template write_element<0>(r) =\n      -vec_traits<A>::template read_element<0>(a);\n  vec_traits<R>::template write_element<1>(r) =\n      -vec_traits<A>::template read_element<1>(a);\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator-;\n}\n\nnamespace qvm_detail {\ntemplate <int D> struct minus_v_defined;\n\ntemplate <> struct minus_v_defined<2> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<is_vec<A>::value && vec_traits<A>::dim == 2,\n                         typename vec_traits<A>::scalar_type>::type\n    mag(A const &a) {\n  typedef typename vec_traits<A>::scalar_type T;\n  T const a0 = vec_traits<A>::template read_element<0>(a);\n  T const a1 = vec_traits<A>::template read_element<1>(a);\n  T const m2 = a0 * a0 + a1 * a1;\n  T const mag = sqrt<T>(m2);\n  return mag;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::mag;\n}\n\nnamespace qvm_detail {\ntemplate <int D> struct mag_v_defined;\n\ntemplate <> struct mag_v_defined<2> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<is_vec<A>::value && vec_traits<A>::dim == 2,\n                         typename vec_traits<A>::scalar_type>::type\n    mag_sqr(A const &a) {\n  typedef typename vec_traits<A>::scalar_type T;\n  T const a0 = vec_traits<A>::template read_element<0>(a);\n  T const a1 = vec_traits<A>::template read_element<1>(a);\n  T const m2 = a0 * a0 + a1 * a1;\n  return m2;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::mag_sqr;\n}\n\nnamespace qvm_detail {\ntemplate <int D> struct mag_sqr_v_defined;\n\ntemplate <> struct mag_sqr_v_defined<2> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS\n    typename lazy_enable_if_c<vec_traits<A>::dim == 2, deduce_vec<A>>::type\n    normalized(A const &a) {\n  typedef typename vec_traits<A>::scalar_type T;\n  T const a0 = vec_traits<A>::template read_element<0>(a);\n  T const a1 = vec_traits<A>::template read_element<1>(a);\n  T const m2 = a0 * a0 + a1 * a1;\n  if (m2 == scalar_traits<typename vec_traits<A>::scalar_type>::value(0))\n    BOOST_QVM_THROW_EXCEPTION(zero_magnitude_error());\n  T const rm = scalar_traits<T>::value(1) / sqrt<T>(m2);\n  typedef typename deduce_vec<A>::type R;\n  R r;\n  vec_traits<R>::template write_element<0>(r) = a0 * rm;\n  vec_traits<R>::template write_element<1>(r) = a1 * rm;\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::normalized;\n}\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<vec_traits<A>::dim == 2, void>::type\n    normalize(A &a) {\n  typedef typename vec_traits<A>::scalar_type T;\n  T const a0 = vec_traits<A>::template read_element<0>(a);\n  T const a1 = vec_traits<A>::template read_element<1>(a);\n  T const m2 = a0 * a0 + a1 * a1;\n  if (m2 == scalar_traits<typename vec_traits<A>::scalar_type>::value(0))\n    BOOST_QVM_THROW_EXCEPTION(zero_magnitude_error());\n  T const rm = scalar_traits<T>::value(1) / sqrt<T>(m2);\n  vec_traits<A>::template write_element<0>(a) *= rm;\n  vec_traits<A>::template write_element<1>(a) *= rm;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::normalize;\n}\n\nnamespace qvm_detail {\ntemplate <int D> struct normalize_v_defined;\n\ntemplate <> struct normalize_v_defined<2> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c<\n    vec_traits<A>::dim == 2 && vec_traits<B>::dim == 2,\n    deduce_scalar<typename vec_traits<A>::scalar_type,\n                  typename vec_traits<B>::scalar_type>>::type\ndot(A const &a, B const &b) {\n  typedef typename vec_traits<A>::scalar_type Ta;\n  typedef typename vec_traits<B>::scalar_type Tb;\n  typedef typename deduce_scalar<Ta, Tb>::type Tr;\n  Ta const a0 = vec_traits<A>::template read_element<0>(a);\n  Ta const a1 = vec_traits<A>::template read_element<1>(a);\n  Tb const b0 = vec_traits<B>::template read_element<0>(b);\n  Tb const b1 = vec_traits<B>::template read_element<1>(b);\n  Tr const dot = a0 * b0 + a1 * b1;\n  return dot;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::dot;\n}\n\nnamespace qvm_detail {\ntemplate <int D> struct dot_vv_defined;\n\ntemplate <> struct dot_vv_defined<2> { static bool const value = true; };\n} // namespace qvm_detail\n\n} // namespace qvm\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "643cb321372cf51ec20a43d984012c554f4ee53a", "size": 13556, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/boost_1_72_0/boost/qvm/gen/vec_operations2.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/qvm/gen/vec_operations2.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/qvm/gen/vec_operations2.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": 30.4629213483, "max_line_length": 79, "alphanum_fraction": 0.6732074358, "num_tokens": 3760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.29453990042419115}}
{"text": "// PythonStuff.cpp\r\n// Copyright 2011, Dan Heeks\r\n// This program is released under the BSD license. See the file COPYING for details.\r\n\r\n#include \"PythonStuff.h\"\r\n\r\n#include \"Area.h\"\r\n#include \"Point.h\"\r\n#include \"AreaDxf.h\"\r\n#include \"geometry.h\"\r\n#include \"Tris.h\"\r\n#include \"HeeksGeomDxf.h\"\r\n#include \"Box.h\"\r\n#include \"Mesh.h\"\r\n\r\n#define HAVE_ACOSH\r\n#define HAVE_ASINH\r\n#define HAVE_ATANH\r\n#define HAVE_LOG1P\r\n\r\n#if _DEBUG\r\n#undef _DEBUG\r\n#include <Python.h>\r\n#define _DEBUG\r\n#else\r\n#include <Python.h>\r\n#endif\r\n\r\n#ifdef __GNUG__\r\n#pragma implementation\r\n#endif\r\n\r\n#include <boost/progress.hpp>\r\n#include <boost/timer.hpp>\r\n#include <boost/foreach.hpp>\r\n#include <boost/python.hpp>\r\n#include <boost/python/module.hpp>\r\n#include <boost/python/class.hpp>\r\n#include <boost/python/wrapper.hpp>\r\n#include <boost/python/call.hpp>\r\n\r\n#include \"clipper.hpp\"\r\nusing namespace ClipperLib;\r\n\r\n\r\nnamespace bp = boost::python;\r\n\r\nboost::python::list getVertices(const CCurve& curve) {\r\n\tboost::python::list vlist;\r\n\tBOOST_FOREACH(const CVertex& vertex, curve.m_vertices) {\r\n\t\tvlist.append(vertex);\r\n    }\r\n\treturn vlist;\r\n}\r\n\r\nboost::python::list getCurves(const CArea& area) {\r\n\tboost::python::list clist;\r\n\tBOOST_FOREACH(const CCurve& curve, area.m_curves) {\r\n\t\tclist.append(curve);\r\n    }\r\n\treturn clist;\r\n}\r\n\r\nboost::python::tuple transformed_point(const Matrix &matrix, double x, double y, double z)\r\n{\r\n\tPoint3d p(x,y,z);\r\n\tp = p.Transformed(matrix);\r\n\r\n\treturn bp::make_tuple(p.x,p.y,p.z);\r\n}\r\n\r\nvoid MatrixRotate(Matrix &matrix, double angle)\r\n{\r\n\tmatrix.Rotate(angle, 3);\r\n}\r\n\r\nvoid MatrixRotateAxis(Matrix &matrix, double angle, const Point3d& axis)\r\n{\r\n\tmatrix.Rotate(angle, axis);\r\n}\r\n\r\nvoid Point3dTransform(Point3d &p, const Matrix &matrix)\r\n{\r\n\tp = p.Transformed(matrix);\r\n}\r\n\r\nboost::python::tuple ArbitraryAxes(const Point3d& p)\r\n{\r\n\tPoint3d x, y;\r\n\tp.arbitrary_axes(x, y);\r\n\treturn bp::make_tuple(x, y);\r\n}\r\n\r\nboost::python::object PlaneIntofPlane(const Plane &plane1, const Plane &plane2)\r\n{\r\n\tLine line;\r\n\tbool result = plane1.Intof(plane2, line);\r\n\r\n\tif (result)\r\n\t{\r\n\t\treturn boost::python::object(line);\r\n\t}\r\n\telse\r\n\t\treturn boost::python::object();\r\n}\r\n\r\nvoid LineTransform(Line &line, const Matrix &matrix)\r\n{\r\n\tline.p0 = line.p0.Transformed(matrix);\r\n\tline.v = line.v.Transformed(matrix);\r\n}\r\n\r\nstatic void print_curve(const CCurve& c)\r\n{\r\n\tunsigned int nvertices = (unsigned int)(c.m_vertices.size());\r\n\twprintf(L\"number of vertices = %d\\n\", nvertices);\r\n\tint i = 0;\r\n\tfor(std::list<CVertex>::const_iterator It = c.m_vertices.begin(); It != c.m_vertices.end(); It++, i++)\r\n\t{\r\n\t\tconst CVertex& vertex = *It;\r\n\t\twprintf(L\"vertex %d type = %d, x = %g, y = %g\", i+1, vertex.m_type, vertex.m_p.x / CArea::m_units, vertex.m_p.y / CArea::m_units);\r\n\t\tif(vertex.m_type)wprintf(L\", xc = %g, yc = %g\", vertex.m_c.x / CArea::m_units, vertex.m_c.y / CArea::m_units);\r\n\t\twprintf(L\"\\n\");\r\n\t}\r\n}\r\n\r\nstatic void print_area(const CArea &a)\r\n{\r\n\tfor(std::list<CCurve>::const_iterator It = a.m_curves.begin(); It != a.m_curves.end(); It++)\r\n\t{\r\n\t\tconst CCurve& curve = *It;\r\n\t\tprint_curve(curve);\r\n\t}\r\n}\r\n\r\nstatic unsigned int num_vertices(const CCurve& curve)\r\n{\r\n\treturn (unsigned int)(curve.m_vertices.size());\r\n}\r\n\r\nstatic CVertex FirstVertex(const CCurve& curve)\r\n{\r\n\treturn curve.m_vertices.front();\r\n}\r\n\r\nstatic CVertex LastVertex(const CCurve& curve)\r\n{\r\n\treturn curve.m_vertices.back();\r\n}\r\n\r\nstatic void set_units(double units)\r\n{\r\n\tCArea::m_units = units;\r\n}\r\n\r\nstatic double get_units()\r\n{\r\n\treturn CArea::m_units;\r\n}\r\n\r\nstatic CArea AreaFromDxf(const char* filepath)\r\n{\r\n\tCArea area;\r\n\tAreaDxfRead dxf(&area, filepath);\r\n\tdxf.DoRead();\r\n\treturn area;\r\n}\r\n\r\nstatic void append_point(CCurve& c, const Point& p)\r\n{\r\n\tc.m_vertices.push_back(CVertex(p));\r\n}\r\n\r\nstatic boost::python::tuple nearest_point_to_curve(CCurve& c1, const CCurve& c2)\r\n{\r\n\tdouble dist = 0.0;\r\n\tPoint p = c1.NearestPoint(c2, &dist);\r\n\r\n\treturn bp::make_tuple(p, dist);\r\n}\r\n\r\n\r\nstatic boost::python::tuple SpanNearestPoint(Span& s1, Span& s2)\r\n{\r\n\tdouble dist = 0.0;\r\n\tPoint p = s1.NearestPoint(s2, &dist);\r\n\r\n\treturn bp::make_tuple(p, dist);\r\n}\r\n\r\nstatic bool SpanOn(Span& s, Point& p)\r\n{\r\n\treturn s.On(p, NULL);\r\n}\r\n\r\nboost::python::list MakePocketToolpath(const CArea& a, double tool_radius, double extra_offset, double stepover, bool from_center, bool use_zig_zag, double zig_angle)\r\n{\r\n\tstd::list<CCurve> toolpath;\r\n\r\n\tCAreaPocketParams params(tool_radius, extra_offset, stepover, from_center, use_zig_zag ? ZigZagPocketMode : SpiralPocketMode, zig_angle);\r\n\ta.SplitAndMakePocketToolpath(toolpath, params);\r\n\r\n\tboost::python::list clist;\r\n\tBOOST_FOREACH(const CCurve& c, toolpath) {\r\n\t\tclist.append(c);\r\n    }\r\n\treturn clist;\r\n}\r\n\r\nboost::python::list SplitArea(const CArea& a)\r\n{\r\n\tstd::list<CArea> areas;\r\n\ta.Split(areas);\r\n\r\n\tboost::python::list alist;\r\n\tBOOST_FOREACH(const CArea& a, areas) {\r\n\t\talist.append(a);\r\n    }\r\n\treturn alist;\r\n}\r\n\r\nvoid dxfArea(CArea& area, const char* str)\r\n{\r\n\tarea = CArea();\r\n}\r\n\r\nboost::python::list getCurveSpans(const CCurve& c)\r\n{\r\n\tboost::python::list span_list;\r\n\tconst Point *prev_p = NULL;\r\n\r\n\tfor(std::list<CVertex>::const_iterator VIt = c.m_vertices.begin(); VIt != c.m_vertices.end(); VIt++)\r\n\t{\r\n\t\tconst CVertex& vertex = *VIt;\r\n\r\n\t\tif(prev_p)\r\n\t\t{\r\n\t\t\tspan_list.append(Span(*prev_p, vertex));\r\n\t\t}\r\n\t\tprev_p = &(vertex.m_p);\r\n\t}\r\n\r\n\treturn span_list;\r\n}\r\n\r\nSpan getFirstCurveSpan(const CCurve& c)\r\n{\r\n\tif(c.m_vertices.size() < 2)return Span();\r\n\r\n\tstd::list<CVertex>::const_iterator VIt = c.m_vertices.begin();\r\n\tconst Point &p = (*VIt).m_p;\r\n\tVIt++;\r\n\treturn Span(p, *VIt, true);\r\n}\r\n\r\nSpan getLastCurveSpan(const CCurve& c)\r\n{\r\n\tif(c.m_vertices.size() < 2)return Span();\r\n\r\n\tstd::list<CVertex>::const_reverse_iterator VIt = c.m_vertices.rbegin();\r\n\tconst CVertex &v = (*VIt);\r\n\tVIt++;\r\n\r\n\treturn Span((*VIt).m_p, v, c.m_vertices.size() == 2);\r\n}\r\n\r\nbp::tuple TangentialArc(const Point &p0, const Point &p1, const Point &v0)\r\n{\r\n  Point c;\r\n  int dir;\r\n  tangential_arc(p0, p1, v0, c, dir);\r\n\r\n  return bp::make_tuple(c, dir);\r\n}\r\n\r\nboost::python::list spanIntersect(const Span& span1, const Span& span2) {\r\n\tboost::python::list plist;\r\n\tstd::list<Point> pts;\r\n\tspan1.Intersect(span2, pts);\r\n\tBOOST_FOREACH(const Point& p, pts) {\r\n\t\tplist.append(p);\r\n    }\r\n\treturn plist;\r\n}\r\n\r\n//Matrix(boost::python::list &l){}\r\n\r\n\r\nboost::shared_ptr<Matrix> matrix3point_constructor(const Point3d& o, const Point3d& x, const Point3d& y) {\r\n\treturn boost::shared_ptr<Matrix>(new Matrix(o, Point3d(x.x, x.y, x.z), Point3d(y.x, y.y, y.z)));\r\n}\r\n\r\nboost::shared_ptr<Matrix> matrix_constructor(const boost::python::list& lst) {\r\n\tdouble m[16] = {1,0,0,0,0,1,0,0, 0,0,1,0, 0,0,0,1};\r\n\r\n  boost::python::ssize_t n = boost::python::len(lst);\r\n  int j = 0;\r\n  for(boost::python::ssize_t i=0;i<n;i++) {\r\n    boost::python::object elem = lst[i];\r\n\tm[j] = boost::python::extract<double>(elem.attr(\"__float__\")());\r\n\tj++;\r\n\tif(j>=16)break;\r\n  }\r\n\r\n  return boost::shared_ptr<Matrix>( new Matrix(m) );\r\n}\r\n\r\nboost::shared_ptr<Plane> plane_constructor(const Point3d& p, const Point3d& v) {\r\n\treturn boost::shared_ptr<Plane>(new Plane(p, Point3d(v.x, v.y, v.z)));\r\n}\r\n\r\n\r\nboost::python::list InsideCurves(const CArea& a, const CCurve& curve) {\r\n\tboost::python::list plist;\r\n\r\n\tstd::list<CCurve> curves_inside;\r\n\ta.InsideCurves(curve, curves_inside);\r\n\tBOOST_FOREACH(const CCurve& c, curves_inside) {\r\n\t\tplist.append(c);\r\n    }\r\n\treturn plist;\r\n}\r\n\r\nboost::python::list CurveIntersections(const CCurve& c1, const CCurve& c2) {\r\n\tboost::python::list plist;\r\n\r\n\tstd::list<Point> pts;\r\n\tc1.CurveIntersections(c2, pts);\r\n\tBOOST_FOREACH(const Point& p, pts) {\r\n\t\tplist.append(p);\r\n    }\r\n\treturn plist;\r\n}\r\n\r\nCBox2D CurveGetBox(const CCurve &c)\r\n{\r\n\tCBox2D box;\r\n\tc.GetBox(box);\r\n\treturn box;\r\n}\r\n\r\nPoint3d CBoxCenter(const CBox& box)\r\n{\r\n\tdouble x[3];\r\n\tbox.Centre(x);\r\n\treturn Point3d(x);\r\n}\r\n\r\nboost::python::list AreaIntersections(const CArea& a, const CCurve& c2) {\r\n\tboost::python::list plist;\r\n\r\n\tstd::list<Point> pts;\r\n\ta.CurveIntersections(c2, pts);\r\n\tBOOST_FOREACH(const Point& p, pts) {\r\n\t\tplist.append(p);\r\n    }\r\n\treturn plist;\r\n}\r\n\r\nboost::python::list CTrisGetMachiningAreas(const CTris& tris)\r\n{\r\n\tboost::python::list plist;\r\n\tstd::list<CMachiningArea> areas;\r\n\ttris.GetMachiningAreas(areas);\r\n\tBOOST_FOREACH(CMachiningArea& a, areas) {\r\n\t\tplist.append(a);\r\n\t}\r\n\treturn plist;\r\n}\r\n\r\nbool SplitAtZ(double z, CTris& new_tris);\r\n\r\nboost::python::object CTrisSplitAtZ(CTris& tris, double z)\r\n{\r\n\tCTris new_tris;\r\n\tif (tris.SplitAtZ(z, new_tris))\r\n\t{\r\n\t\treturn boost::python::object(new_tris);\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn boost::python::object(); // None\r\n\t}\r\n}\r\n\r\n\r\nboost::python::object LineIntersectPlane(const Line& line, const Plane& plane)\r\n{\r\n\tPoint3d intof;\r\n\tdouble t;\r\n\tif (plane.Intof(line, intof, t))\r\n\t{\r\n\t\treturn boost::python::object(intof);\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn boost::python::object(); // None\r\n\t}\r\n}\r\n\r\nvoid CTrisAddTriangle(CTris& tris, const Point3d& p0, const Point3d& p1, const Point3d& p2)\r\n{\r\n\tfloat x[9] = { (float)p0.x, (float)p0.y, (float)p0.z, (float)p1.x, (float)p1.y, (float)p1.z, (float)p2.x, (float)p2.y, (float)p2.z };\r\n\ttris.AddTri(x);\r\n}\r\n\r\nCMesh* CTrisGetMesh(const CTris& tris)\r\n{\r\n\treturn new CMesh(tris);\r\n}\r\n\r\nboost::python::list GetTrianglesAsCurveList(const CTris& tris)\r\n{\r\n\tboost::python::list clist;\r\n\tfor (std::list<CTri>::const_iterator It = tris.m_tris.begin(); It != tris.m_tris.end(); It++)\r\n\t{\r\n\t\tconst CTri& tri = *It;\r\n\t\tCCurve c;\r\n\t\tc.append(Point(tri.x[0][0], tri.x[0][1]));\r\n\t\tc.append(Point(tri.x[1][0], tri.x[1][1]));\r\n\t\tc.append(Point(tri.x[2][0], tri.x[2][1]));\r\n\t\tc.append(Point(tri.x[0][0], tri.x[0][1]));\r\n\t\tclist.append(c);\r\n\t}\r\n\treturn clist;\r\n}\r\n\r\nboost::python::list CTrisGetTriangles(const CTris& tris)\r\n{\r\n\tboost::python::list clist;\r\n\tfor (std::list<CTri>::const_iterator It = tris.m_tris.begin(); It != tris.m_tris.end(); It++)\r\n\t{\r\n\t\tconst CTri& tri = *It;\r\n\t\tclist.append(bp::make_tuple(bp::make_tuple(tri.x[0][0], tri.x[0][1], tri.x[0][2]), bp::make_tuple(tri.x[1][0], tri.x[1][1], tri.x[1][2]), bp::make_tuple(tri.x[2][0], tri.x[2][1], tri.x[2][2])));\r\n\t}\r\n\treturn clist;\r\n}\r\n\r\nboost::python::tuple MeshGetFaces(const CMesh& mesh)\r\n{\r\n\tboost::python::list vlist;\r\n\tboost::python::list flist;\r\n\r\n\tint next_vertex_index = 0;\r\n\tstd::map<const CMeshVertex*, int> vertex_map;\r\n\tfor (std::list<CMeshFace*>::const_iterator It = mesh.m_faces.begin(); It != mesh.m_faces.end(); It++)\r\n\t{\r\n\t\tconst CMeshFace* face = *It;\r\n\r\n\t\tboost::python::list ilist;\r\n\r\n\t\tunsigned int size = face->m_vertices.size();\r\n\t\tfor (unsigned int i = 0; i < size; i++)\r\n\t\t{\r\n\t\t\tconst CMeshVertex* v = face->m_vertices[i];\r\n\t\t\tstd::map<const CMeshVertex*, int>::const_iterator FindIt = vertex_map.find(v);\r\n\t\t\tint index = -1;\r\n\t\t\tif (FindIt == vertex_map.end()){\r\n\t\t\t\tindex = next_vertex_index;\r\n\t\t\t\tvertex_map.insert(std::make_pair(v, next_vertex_index));\r\n\t\t\t\tvlist.append(boost::python::make_tuple(v->m_x[0], v->m_x[1], v->m_x[2]));\r\n\t\t\t\tnext_vertex_index++;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tindex = FindIt->second;\r\n\t\t\t}\r\n\t\t\tilist.append(index);\r\n\t\t}\r\n\r\n\t\tflist.append(ilist);\r\n\t}\r\n\r\n\treturn boost::python::make_tuple(vlist, flist);\r\n}\r\n\r\ndouble AreaGetArea(const CArea& a)\r\n{\r\n\treturn a.GetArea();\r\n}\r\n\r\nCBox2D AreaGetBox(const CArea& a)\r\n{\r\n\tCBox2D box;\r\n\ta.GetBox(box);\r\n\treturn box;\r\n}\r\n\r\nboost::python::list AreaGetTrianglesList(const CArea& a)\r\n{\r\n\tstd::list<CTris> tri_list;\r\n\ta.GetTriangles(tri_list);\r\n\tboost::python::list python_list;\r\n\tfor (std::list<CTris>::const_iterator It = tri_list.begin(); It != tri_list.end(); It++)\r\n\t{\r\n\t\tconst CTris& tris = *It;\r\n\t\tpython_list.append(tris);\r\n\t}\r\n\treturn python_list;\r\n}\r\n\r\nextern int oct_ele_count;\r\nint get_oct_ele_count()\r\n{\r\n\treturn oct_ele_count;\r\n}\r\n\r\nstatic void set_tolerance(double tolerance)\r\n{\r\n\tTOLERANCE = tolerance;\r\n}\r\n\r\nstatic double get_tolerance()\r\n{\r\n\treturn TOLERANCE;\r\n}\r\n\r\nstatic void set_accuracy(double accuracy)\r\n{\r\n\tCArea::m_accuracy = accuracy;\r\n}\r\n\r\nstatic double get_accuracy()\r\n{\r\n\treturn CArea::m_accuracy;\r\n}\r\n\r\nstatic void set_fitarcs(bool fitarcs)\r\n{\r\n\tCArea::m_fit_arcs = fitarcs;\r\n}\r\n\r\nstatic bool get_fitarcs()\r\n{\r\n\treturn CArea::m_fit_arcs;\r\n}\r\n\r\nCBox CTrisGetBox(const CTris& solid)\r\n{\r\n\tCBox box;\r\n\tsolid.GetBox(box);\r\n\treturn box;\r\n}\r\n\r\nsize_t CTrisNumTris(const CTris& solid)\r\n{\r\n\treturn solid.m_tris.size();\r\n}\r\n\r\nvoid CTrisProject(const CTris& solid, const CArea& area, const std::string& dxf_file_path)\r\n{\r\n\tstd::list<Line> lines;\r\n\tsolid.Project(area, lines);\r\n\r\n\t// write dxf file\r\n\tCDxfWrite dxf_writer(dxf_file_path.c_str());\r\n\t// add the spans transformed back to the input span's plane\r\n\tfor (std::list<Line>::iterator It = lines.begin(); It != lines.end(); It++)\r\n\t{\r\n\t\tLine& line = *It;\r\n\t\tPoint3d e = line.p0 + line.v;\r\n\t\tdxf_writer.WriteLine(line.p0.getBuffer(), e.getBuffer(), \"0\");\r\n\t}\r\n}\r\n\r\nstatic std::string Point__str__(const Point& self) {\r\n\tstd::ostringstream ss;\r\n\tss << self;\r\n\treturn ss.str();\r\n}\r\n\r\nstatic std::string Point3d__str__(const Point3d& self) {\r\n\tstd::ostringstream ss;\r\n\tss << self;\r\n\treturn ss.str();\r\n}\r\n\r\nstatic std::string Circle__str__(const Circle& self) {\r\n\tstd::ostringstream ss;\r\n\tss << self;\r\n\treturn ss.str();\r\n}\r\n\r\nstatic std::string CVertex__str__(const CVertex& self) {\r\n\tstd::ostringstream ss;\r\n\tss << self;\r\n\treturn ss.str();\r\n}\r\n\r\nstatic std::string Span__str__(const Span& self) {\r\n\tstd::ostringstream ss;\r\n\tss << self;\r\n\treturn ss.str();\r\n}\r\n\r\nstatic std::string Curve__str__(const CCurve& self) {\r\n\tstd::ostringstream ss;\r\n\tss << self;\r\n\treturn ss.str();\r\n}\r\n\r\nstatic std::string CBox__str__(const CBox& self) {\r\n\tstd::ostringstream ss;\r\n\tss << self;\r\n\treturn ss.str();\r\n}\r\n\r\nstatic std::string Area__str__(const CArea& self) {\r\n\tstd::ostringstream ss;\r\n\tss << self;\r\n\treturn ss.str();\r\n}\r\n\r\nstatic std::string Matrix__str__(const Matrix& self) {\r\n\tstd::ostringstream ss;\r\n\tss << self;\r\n\treturn ss.str();\r\n}\r\n\r\nboost::python::object CurveIsACircle(const CCurve& curve, double tol)\r\n{\r\n\tCircle circle;\r\n\tif (curve.IsACircle(circle, tol))\r\n\t{\r\n\t\treturn boost::python::object(circle);\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn boost::python::object(); // None\r\n\t}\r\n}\r\n\r\nBOOST_PYTHON_MODULE(geom) {\r\n\r\n\tbp::docstring_options local_docstring_options(true, true, false); // This will enable user-defined docstrings and python signatures, while disabling the C++ signatures\r\n\r\n\tbp::class_<Point>(\"Point\", \"Point((float)x, (float)y)\\n\\n2D Point\\nCan also be used as a vector\"\r\n\t\t\"\\nTo make a vector from p1 to p2, use v = p2 - p1\"\r\n\t\t\"\\nUse p1 * p2 for dot product\"\r\n\t\t\"\\nUse p1 ^ p2 for cross product\"\r\n\t\t\"\\nUse ~p to return a vector at 90 degrees to the left of p\")\r\n\t\t.def(bp::init<double, double>())\r\n\t\t.def(bp::init<Point>())\r\n\t\t.def(bp::other<double>() * bp::self)\r\n\t\t.def(bp::self * bp::other<double>())\r\n\t\t.def(bp::self / bp::other<double>())\r\n\t\t.def(bp::self * bp::other<Point>())\r\n\t\t.def(bp::self - bp::other<Point>())\r\n\t\t.def(bp::self + bp::other<Point>())\r\n\t\t.def(bp::self ^ bp::other<Point>())\r\n\t\t.def(bp::self == bp::other<Point>())\r\n\t\t.def(bp::self != bp::other<Point>())\r\n\t\t.def(-bp::self)\r\n\t\t.def(~bp::self)\r\n\t\t.def(\"Dist\", &Point::dist, bp::args(\"p2\"), \"returns the distance between this point and p2\")\r\n\t\t.def(\"Length\", &Point::length, \"returns the length of the vector\")\r\n\t\t.def(\"Normalize\", &Point::normalize, \"makes the vector into a unit vector\\nthis will leave a (0, 0) vector as it is\\nreturns the (float)length before operation\")\r\n\t\t.def(\"Rotate\", static_cast<void (Point::*)(double, double)>(&Point::Rotate), bp::args(\"cosa, sina\"), \"rotates the vector about (0,0) given cosine and sine of the angle\")\r\n\t\t.def(\"Rotate\", static_cast<void (Point::*)(double)>(&Point::Rotate), bp::args(\"angle\"), \"rotates the vector about (0,0) by given angle ( in radians )\")\r\n\t\t.def(\"Transform\", &Point::Transform, bp::args(\"m\"), \"transforms the point by the matrix\")\r\n\t\t.def_readwrite(\"x\", &Point::x, \"the x value of the point\")\r\n\t\t.def_readwrite(\"y\", &Point::y, \"the y value of the point\")\r\n\t\t.def(\"__str__\", Point__str__);\r\n\t;\r\n\r\n\tbp::class_<CVertex>(\"Vertex\", \"Vertex((int)type, (Point)p, (Point)c) make a new Vertex with type, end point and center point; type 0 = line, 1 = ccw arc, -1 = cw arc\"\r\n\t\t\"Vertex((Point)p) make a Vertex with end point\")\r\n\t\t.def(bp::init<CVertex>())\r\n\t\t.def(bp::init<int, Point, Point>())\r\n\t\t.def(bp::init<Point>())\r\n\t\t.def(bp::init<int, Point, Point, int>())\r\n\t\t.def_readwrite(\"type\", &CVertex::m_type, \"0 - line, 1 - ccw arc, -1 - cw arc\")\r\n\t\t.def_readwrite(\"p\", &CVertex::m_p, \"the end point of the span\")\r\n\t\t.def_readwrite(\"c\", &CVertex::m_c, \"the center point of the span, for arcs\")\r\n\t\t.def_readwrite(\"user_data\", &CVertex::m_user_data)\r\n\t\t.def(\"__str__\", CVertex__str__);\r\n\t;\r\n\r\n\tbp::class_<Span>(\"Span\", \"Span((Point)p, (Vertex)v, (bool)start_span\\n\\nA Span has start Point and a Vertex\\nThese re not stored in a Curve ( Curve stores a list of Vertex objects )\\nYou can use curve.GetSpans() to get a list of these from a curve\")\r\n\t\t.def(bp::init<Span>())\r\n\t\t.def(bp::init<Point, CVertex, bool>())\r\n\t\t.def(\"NearestPoint\", static_cast<Point(Span::*)(const Point& p)const>(&Span::NearestPoint), bp::args(\"p\"), \"returns the nearest point on this span to the given point\")\r\n\t\t.def(\"NearestPoint\", &SpanNearestPoint, bp::args(\"s2\"), \"returns tuple (nearest point on this span to span s2, distance of that point to s2)\")\r\n\t\t.def(\"GetBox\", &Span::GetBox, \"returns the box that fits round the span\")\r\n\t\t.def(\"IncludedAngle\", &Span::IncludedAngle, \"returns the included angle of the arc in radians, + for ccw, - for cw\")\r\n\t\t.def(\"GetArea\", &Span::GetArea, \"returns the area under the span to the X axis\")\r\n\t\t.def(\"On\", &SpanOn, bp::args(\"p\"), \"returns True if point lies on span, else False\")\r\n\t\t.def(\"MidPerim\", &Span::MidPerim, bp::args(\"param\"), \"returns the point which is the given fraction ( of the span ) along the span\")\r\n\t\t.def(\"MidParam\", &Span::MidParam, bp::args(\"perim\"), \"returns the point, which is the given distance along the span\")\r\n\t\t.def(\"Length\", &Span::Length, bp::args(\"p\"), \"returns the length of the span\")\r\n\t\t.def(\"GetVector\", &Span::GetVector, \"returns the tangential vector ( the vector pointing in the direction of travel )\\nat the given fraction along the span\")\r\n\t\t.def(\"Intersect\", &spanIntersect, bp::args(\"s2\"), \"returns a list of intersection points between this span and s2\\nordered along this span\")\r\n\t\t.def(\"GetRadius\", &Span::GetRadius, \"returns the radius of the arc, or 0.0 if it's a line\")\r\n\t\t.def_readwrite(\"p\", &Span::m_p, \"the start point of this span\")\r\n\t\t.def_readwrite(\"v\", &Span::m_v, \"the Vertex describing the span type, end and center\")\r\n\t\t.def(\"__str__\", Span__str__);\r\n\t;\r\n\r\n\tbp::class_<CCurve>(\"Curve\", \"Curve()\\n\\ndefined by a list of Vertex objects\\nif you want a closed curve, you need to add a point at the end that is at the same place as the start point\") \r\n        .def(bp::init<CCurve>())\r\n        .def(\"GetVertices\", &getVertices, \"returns the list of Vertex objects\")\r\n\t\t.def(\"Append\", &CCurve::append, bp::args(\"v\"), \"adds a Vertex to the list of vertices\")\r\n\t\t.def(\"Append\", &append_point, bp::args(\"p\"), \"adds a Point to the list of vertices ( makes a Vertex from it )\")\r\n        .def(\"Text\", &print_curve, \"for debugging, prints a text definition of the Curve\")\r\n\t\t.def(\"NearestPoint\", static_cast< Point(CCurve::*)(const Point& p)const >(&CCurve::NearestPoint), bp::args(\"p\"), \"returns the nearest point on the curve to the given point\")\r\n\t\t.def(\"NearestPoint\", &nearest_point_to_curve, bp::args(\"c2\"), \"returns the nearest point on the curve to the given curve, c2, and returns the distance of it to this curve\")\r\n\t\t.def(\"Reverse\", &CCurve::Reverse, \"reverses this curve\")\r\n\t\t.def(\"NumVertices\", &num_vertices, \"returns the number of vertices; quicker than getting the list of vertices\")\r\n\t\t.def(\"FirstVertex\", &FirstVertex, \"returns the first vertex\")\r\n\t\t.def(\"LastVertex\", &LastVertex, \"returns the last vertex\")\r\n\t\t.def(\"GetArea\", &CCurve::GetArea, \"returns the area enclosed by the curve\")\r\n\t\t.def(\"IsClockwise\", &CCurve::IsClockwise, \"returns True if this curve is closed and clockwise, else False\")\r\n\t\t.def(\"IsClosed\", &CCurve::IsClosed, \"returns True if this curve is closed, else False\")\r\n\t\t.def(\"ChangeStart\", &CCurve::ChangeStart, bp::args(\"p\"), \"changes the start of this curve, keeps it closed if it was closed\")\r\n\t\t.def(\"ChangeEnd\", &CCurve::ChangeEnd, bp::args(\"p\"), \"changes the end point of this curve, doesn't keep closed kurves closed\")\r\n\t\t.def(\"Offset\", &CCurve::Offset, bp::args(\"leftwards_value\"), \"offsets the curve by given amount to the left, keeps closed curves closed\")\r\n\t\t.def(\"OffsetForward\", &CCurve::OffsetForward, bp::args(\"forwards_value\", \"refit_arcs\"), \"for drag-knife compensation\")\r\n        .def(\"GetSpans\",&getCurveSpans, \"returns a list of Span objects\")\r\n        .def(\"GetFirstSpan\",&getFirstCurveSpan, \"returns a Span for the start of the curve\")\r\n        .def(\"GetLastSpan\",&getLastCurveSpan, \"returns a Span for the end of the curve\")\r\n\t\t.def(\"Break\", &CCurve::Break, bp::args(\"p\"), \"inserts a Point at given point\")\r\n        .def(\"Perim\",&CCurve::Perim, \"returns the length of the curve ( its perimeter )\")\r\n\t\t.def(\"PerimToPoint\", &CCurve::PerimToPoint, bp::args(\"perim\"), \"returns the Point at the given distance around the Curve\")\r\n\t\t.def(\"PointToPerim\", &CCurve::PointToPerim, bp::args(\"p\"), \"returns the distance around the Curve at the given Point\")\r\n\t\t.def(\"FitArcs\",&CCurve::FitArcs, \"replaces little lines with arcs where possible\")\r\n        .def(\"UnFitArcs\",&CCurve::UnFitArcs, \"replaces arcs with lots of little lines\")\r\n\t\t.def(\"Intersections\", &CurveIntersections, bp::args(\"c2\"), \"returns a list of all the intersections between this Curve and the given Curve\\nordered along this Curve\")\r\n\t\t.def(\"GetBox\", &CurveGetBox, \"returns the box that fits round the curve\")\r\n\t\t.def(\"Transform\", &CCurve::Transform, bp::args(\"m\"), \"transforms the curve by the matrix\\na curve is only 2D though, so don't rotate in 3D\")\r\n\t\t.def(\"IsACircle\", CurveIsACircle, bp::args(\"tol\"), \"returns True if all the spans are arcs of the same direction and fit the same circle\\n to given tolerance\")\r\n\t\t.def(\"__str__\", Curve__str__);\r\n\t;\r\n\r\n\tbp::class_<CBox2D>(\"Box\", \"Box((Point)minxy, (Point)maxxy)\\n\\na 2D box used for returning the extents of a Span or Curve\") \r\n        .def(bp::init<CBox2D>())\r\n\t\t.def(bp::init<const Point&, const Point&>())\r\n\t\t.def(\"MinX\", &CBox2D::MinX, \"returns the minimum x value\")\r\n\t\t.def(\"MaxX\", &CBox2D::MaxX, \"returns the maximum x value\")\r\n\t\t.def(\"MinY\", &CBox2D::MinY, \"returns the minimum y value\")\r\n\t\t.def(\"MaxY\", &CBox2D::MaxY, \"returns the maximum y value\")\r\n\t\t.def(\"Width\", &CBox2D::Width, \"returns the width of the box in the X axis\")\r\n\t\t.def(\"Height\", &CBox2D::Height, \"returns the height of the box in the Y axis\")\r\n\t\t.def(\"InsertPoint\", static_cast< void(CBox2D::*)(const Point&) >(&CBox2D::Insert), bp::args(\"p\"), \"makes the box bigger to include the given point\")\r\n\t\t.def(\"InsertBox\", static_cast< void(CBox2D::*)(const CBox2D&) >(&CBox2D::Insert), bp::args(\"b2\"), \"makes the box bigger to include the given box\")\r\n\t\t.def_readwrite(\"minxy\", &CBox2D::m_minxy, \"the X, Y coordinate of the bottom left of the box\")\r\n\t\t.def_readwrite(\"maxxy\", &CBox2D::m_maxxy, \"the X, Y coordinate of the top right of the box\")\r\n\t\t.def_readwrite(\"valid\", &CBox2D::m_valid, \"if False, the box is empty and all the other values are invalid\")\r\n\t\t;\r\n\r\n\tbp::class_<CBox>(\"Box3D\", \"Box3D((float)minx, (float)miny, (float)minz, (float)maxx, (float)maxy, (float)maxz)\\n\\na 3D box used for returning the extents of a Solid\")\r\n\t\t.def(bp::init<CBox>())\r\n\t\t.def(bp::init<double, double, double, double, double, double>())\r\n\t\t.def(\"MinX\", &CBox::MinX, \"returns the minimum x value\")\r\n\t\t.def(\"MaxX\", &CBox::MaxX, \"returns the maximum x value\")\r\n\t\t.def(\"MinY\", &CBox::MinY, \"returns the minimum y value\")\r\n\t\t.def(\"MaxY\", &CBox::MaxY, \"returns the maximum y value\")\r\n\t\t.def(\"MinZ\", &CBox::MinZ, \"returns the minimum z value\")\r\n\t\t.def(\"MaxZ\", &CBox::MaxZ, \"returns the maximum z value\")\r\n\t\t.def(\"InsertBox\", static_cast< void (CBox::*)(const CBox&) >(&CBox::Insert), bp::args(\"b2\"), \"makes the box bigger to include the given box\")\r\n\t\t.def(\"InsertPoint\", static_cast< void (CBox::*)(double, double, double) >(&CBox::Insert), bp::args(\"p\"), \"makes the box bigger to include the given point\")\r\n\t\t.def(\"Center\", &CBoxCenter, \"returns the Point3D at the mid X,Y,Z\")\r\n\t\t.def(\"Radius\", &CBox::Radius, \"returns the radius of a sphere that would enclose the box exactly if centres at Center()\")\r\n\t\t.def_readwrite(\"valid\", &CBox::m_valid, \"if False, the box is empty and all the other values are invalid\")\r\n\t\t.def(\"Width\", &CBox::Width, \"returns the width of the box in the X axis\")\r\n\t\t.def(\"Height\", &CBox::Height, \"returns the height of the box in the Y axis\")\r\n\t\t.def(\"Depth\", &CBox::Depth, \"returns the depth of the box in the Z axis\")\r\n\t\t.def(\"__str__\", CBox__str__);\r\n\t;\r\n\r\n\tbp::class_<CArea>(\"Area\", \"Area()\\n\\n a list of Curve objects that can represent an area with optional islands\")\r\n        .def(bp::init<CArea>())///function Area///makes an new empty Area///return Area\r\n        .def(\"GetCurves\", &getCurves, \"returns the list of Curve objects\")\r\n\t\t.def(\"Append\", &CArea::append, bp::args(\"c\"), \"adds a curve to the area\\nyou must add outside curves first, followed by island curves\\nyou must make sure your outside curves are anti-clockwise and island curves clockwise\\nor use Reorder function\")\r\n\t\t.def(\"Subtract\", &CArea::Subtract, bp::args(\"a2\"), \"cuts a2 away from this area\")\r\n\t\t.def(\"Intersect\", &CArea::Intersect, bp::args(\"a2\"), \"leaves the area that is common to both this area and a2\")\r\n\t\t.def(\"Union\", &CArea::Union, bp::args(\"a2\"), \"joins a2 to this area\")\r\n\t\t.def(\"Offset\", &CArea::Offset, bp::args(\"inwards_value\"), \"offset the area inwards by the value\\nuse a negative value to offset outwards\\nthis can change the number of curves of the area\\nwhen you offset too far inwards there will be no curves left\")\r\n\t\t.def(\"Thicken\", &CArea::Thicken, bp::args(\"value\"), \"offset the thin curves outwards by the value to make sausages\")\r\n        .def(\"FitArcs\",&CArea::FitArcs, \"replaces little lines with arcs where possible. to tolerance set by set_accuracy\")\r\n        .def(\"Text\", &print_area, \"for debugging, prints a text definition of the Area\")\r\n\t\t.def(\"NumCurves\", &CArea::num_curves, \"returns the number of curves in this area\")\r\n\t\t.def(\"NearestPoint\", &CArea::NearestPoint, bp::args(\"p\"), \"returns the nearest point on this area's curves to the given point\")\r\n\t\t.def(\"GetBox\", &AreaGetBox, \"returns the (Box)box that fits round the area\")\r\n\t\t.def(\"Reorder\", &CArea::Reorder, \"This reorders and reverses the curves where necessary\")\r\n\t\t.def(\"Split\", &SplitArea, \"splits up the area, where it has multiple outside curves and makes a list of separate areas\\nif no splitting occurs the list contains a copy of this area\")\r\n\t\t.def(\"InsideCurves\", &InsideCurves, bp::args(\"c\"), \"chops up the given curve with this area\\nreturns a list of new curves which are the sections inside the area\")\r\n\t\t.def(\"Thicken\", &CArea::Thicken, bp::args(\"radius\"), \"replaces the area with united obrounds with given radius around each span\")\r\n\t\t.def(\"Intersections\", &AreaIntersections, bp::args(\"c\"), \"returns a list of intersection points with this area and the given curve\\nordered along the given curve\")\r\n\t\t.def(\"GetArea\", &AreaGetArea, \"returns the (float)area enclosed by the area\")\r\n\t\t.def(\"WriteDxf\", static_cast< void(*)(const CArea& area, const std::string& dxf_file_path) >(&WriteDxfFile), bp::args(\"filepath\"), \"writes a dxf file with this area in\")\r\n\t\t.def(\"Swept\", &CArea::Swept, bp::args(\"v\"), \"returns an area that is this area swept along the given vector\")\r\n\t\t.def(\"Transform\", &CArea::Transform, bp::args(\"m\"), \"transforms this area by the matrix\\nan area is only 2D though, so don't rotate in 3D\")\r\n\t\t.def(\"GetTrianglesList\", &AreaGetTrianglesList, \"returns a list of Stl objects with triangles that fill each separate area\")\r\n\t\t.def(\"__str__\", Area__str__);\r\n\t;\r\n\r\n\tbp::class_<Matrix > (\"Matrix\", \"Matrix((Point)o, (Point)x_vector, (Point)y_vector)\\nMatrix([list of 16 floats])\\n\\ndefines a 4x4 transformation matrix\")\r\n        .def(bp::init<Matrix>())\r\n\t\t.def(\"__init__\", bp::make_constructor(&matrix3point_constructor))\r\n\t\t.def(\"__init__\", bp::make_constructor(&matrix_constructor))\r\n\t\t.def(\"TransformedPoint\", &transformed_point, bp::args(\"x\", \"y\", \"z\"), \"transforms a 3D point by the matrix given x, y, z values\\nreturns x, y, z\")\r\n\t\t.def(\"Multiply\", &Matrix::Multiply, bp::args(\"m2\"), \"transforms this matrix by the given one\")\r\n\t\t.def(\"Inverse\", &Matrix::Inverse, \"returns a Matrix which is the inverse of this matrix\\nthe matrix which reverts the effect of this matrix\")\r\n\t\t.def(\"Rotate\", &MatrixRotate, bp::args(\"angle\"), \"rotates this matrix by the given angle in radians around the z axis anti-clockwise\")\r\n\t\t.def(\"RotateAxis\", &MatrixRotateAxis, bp::args(\"angle\", \"axis\"), \"rotates this matrix by the given angle in radians around the given axis anti-clockwise\\nwhen looking backwards along the given vector\")\r\n\t\t.def(\"Translate\", static_cast< void (Matrix::*)(const Point3d&) >(&Matrix::Translate), bp::args(\"shift\"), \"translates this matrix by the given shift vector\")\r\n\t\t.def(\"Scale\", static_cast< void (Matrix::*)(double) >(&Matrix::Scale), bp::args(\"value\"), \"scales the vector uniformly about 0, 0, 0 by the given scale factor\")\r\n\t\t.def(\"Scale3\", static_cast< void (Matrix::*)(double, double, double) >(&Matrix::Scale), bp::args(\"x\", \"y\", \"z\"), \"scales the vector differentially about 0, 0, 0 by the given scale factors\")\r\n\t\t.def(\"__str__\", Matrix__str__);\r\n\t;\r\n\r\n\tbp::class_<Point3d>(\"Point3D\", \"Point((float)x, (float)y, (float)z)\\n\\n3D Point\\nCan also be used as a vector\"\r\n\t\t\"\\nTo make a vector from p1 to p2, use v = p2 - p1\"\r\n\t\t\"\\nUse p1 * p2 for dot product\"\r\n\t\t\"\\nUse p1 ^ p2 for cross product\")\r\n\t\t.def(bp::init<Point3d>())\r\n\t\t.def(bp::init<double, double, double>())\r\n\t\t.def(\"Transform\", &Point3dTransform, bp::args(\"m\"), \"transforms the point by the matrix\")\r\n\t\t.def(\"Transformed\", &Point3d::Transformed, bp::args(\"m\"), \"returns a Point3D transformed by the matrix\")\r\n\t\t.def_readwrite(\"x\", &Point3d::x, \"the x value of the point\")\r\n\t\t.def_readwrite(\"y\", &Point3d::y, \"the y value of the point\")\r\n\t\t.def_readwrite(\"z\", &Point3d::z, \"the z value of the point\")\r\n\t\t.def(bp::self * bp::other<double>())\r\n\t\t.def(bp::self / bp::other<double>())\r\n\t\t.def(bp::self * bp::other<Point3d>())\r\n\t\t.def(bp::self - bp::other<Point3d>())\r\n\t\t.def(bp::self + bp::other<Point3d>())\r\n\t\t.def(bp::self ^ bp::other<Point3d>())\r\n\t\t.def(bp::self == bp::other<Point3d>())\r\n\t\t.def(bp::self != bp::other<Point3d>())\r\n\t\t.def(-bp::self)\r\n\t\t.def(\"Normalized\", &Point3d::Normalized, \"returns a vector which is this vector scaled to a unit vector\\nfor a (0, 0, 0) vector, this will return Point3D(0, 0, 0)\")\r\n\t\t.def(\"Dist\", &Point3d::Dist, bp::args(\"p2\"), \"returns the distance between this point and p2\")\r\n\t\t.def(\"Length\", &Point3d::magnitude, \"returns the length of the vector\")\r\n\t\t.def(\"ArbitraryAxes\", &ArbitraryAxes, \"returns a tuple of (x_axis, y_axis) unit vectors, which have the same relationship to this vector\\nas x-axis and y-axis have to z-axis\")\r\n\t\t.def(\"__str__\", Point3d__str__);\r\n\t;\r\n\r\n\tbp::class_<Plane>(\"Plane\", \"Plane((Point)point_on_plane, (Point)normal_vector)\\n\\nAn infinite plane\")\r\n\t\t.def(bp::init<Plane>())\r\n\t\t.def(\"__init__\", bp::make_constructor(&plane_constructor))\r\n\t\t.def(\"Intof\", &PlaneIntofPlane, bp::args(\"pl2\"), \"if the two planes intersect this returns the Line of intersection, else returns None\")\r\n\t\t.def_readwrite(\"normal\", &Plane::normal, \"unit vector normal to plane\")\r\n\t\t.def_readwrite(\"d\", &Plane::d, \"distance of plane to origin\\nuse normal * (-d) to get a point on the plane\")\r\n\t\t;\r\n\r\n\tbp::class_<Line>(\"Line\", \"Line((Point3D)p1, (Point3D)p2) - an infinite line through p1 and p2\")\r\n\t\t.def(bp::init<Line>())\r\n\t\t.def(bp::init<const Point3d &, const Point3d &>())\r\n\t\t.def(\"Transform\", &LineTransform, bp::args(\"m\"), \"transforms this Line by the matrix\")\r\n\t\t.def_readwrite(\"p\", &Line::p0, \"the point on the line\")\r\n\t\t.def_readwrite(\"v\", &Line::v, \"the vector along the line\")\r\n\t\t.def(\"IntersectPlane\", &LineIntersectPlane, bp::args(\"pl\"), \"returns the intersection (Point3D)point of this line with given plane, if intersection exists\\nelse returns None\")\r\n\t\t;\r\n\r\n\tbp::class_<Circle>(\"Circle\", \"Circle((Point)center, (float)radius - circle with given center point and radius\"\r\n\t\t\"\\nCircle((Point)point_on_circle, (Point)center) - circle with given point on circle and center point\"\r\n\t\t\"\\nCircle((Point)p1, (Point)p2, (Point)p3) - circle through 3 points\")\r\n\t\t.def(bp::init<Circle>())\r\n\t\t.def(bp::init<const Point&, double>())\r\n\t\t.def(bp::init<const Point&, const Point&>())\r\n\t\t.def(bp::init<const Point&, const Point&, const Point&>())\r\n\t\t.def(\"Transform\", &LineTransform, bp::args(\"m\"), \"transforms this Circle by the matrix\")\r\n\t\t.def_readwrite(\"c\", &Circle::pc, \"center point of the circle\")\r\n\t\t.def_readwrite(\"radius\", &Circle::radius, \"radius of the circle\")\r\n\t\t.def(\"__str__\", Circle__str__);\r\n\t;\r\n\r\n\tbp::class_<CTris>(\"Stl\", \"Stl() - empty collection of triangles\\nStl(file_path) - collection of triangles read in from an .stl file\")\r\n\t\t.def(bp::init<CTris>())\r\n\t\t.def(bp::init<const std::wstring&>())\r\n\t\t.def(\"MakeSection\", &CTris::MakeSection, bp::args(\"s\", \"e\", \"dxf_file_path\"), \"makes a dxf file with a drawing of the section through this solid/nusing the given line to cut it\")\r\n\t\t.def(\"WriteStl\", &CTris::WriteStl, bp::args(\"stl_file_path\"), \"writes an stl file for this solid\")\r\n\t\t.def(\"BooleanCut\", &CTris::BooleanCut, bp::return_value_policy<bp::manage_new_object>(), bp::args(\"stl2\"), \"returns a new Stl object which is this Stl cut by the given Stl\")\r\n\t\t.def(\"BooleanUnion\", &CTris::BooleanUnion, bp::return_value_policy<bp::manage_new_object>(), bp::args(\"stl2\"), \"returns a new Stl object which is this Stl united with the given Stl\")\r\n\t\t.def(\"BooleanCommon\", &CTris::BooleanCommon, bp::return_value_policy<bp::manage_new_object>(), bp::args(\"stl2\"), \"returns a new Stl object which is common volume between this Stl and the given Stl\")\r\n\t\t.def(\"SplitTriangles\", &CTris::SplitTriangles, bp::arg(\"s2\"), \"intersects this Stl with the given Stl\")\r\n\t\t.def(\"Shadow\", &CTris::Shadow2Mat, bp::args(\"m\", \"just_up_allowed\"), \"returns an Area representing the shadow of this Stl object\\nif just_up_allowed is true, then ignore downward facing triangles\")\r\n\t\t.def(\"Project\", &CTrisProject, bp::args(\"area\", \"dxf_file_path\"), \"writes a dxf file with the given Area projected down onto the Stl object\")\r\n\t\t.def(\"Transform\", &CTris::Transform, bp::args(\"m\"), \"transforms this Stl by the matrix\")\r\n\t\t.def(\"GetBox\", &CTrisGetBox, \"returns the (Box3D)box that fits round the area\")\r\n\t\t.def(\"NumTris\", &CTrisNumTris, \"returns the number of triangles in this Stl\")\r\n\t\t.def(\"GetMachiningAreas\", &CTrisGetMachiningAreas, \"joins up triangles of the same FaceFlatType and returns a list of MachiningArea objects\")\r\n\t\t.def(\"SplitAtZ\", &CTrisSplitAtZ, \"split at z height, returns new Stl object, for triangles above z, or None if split not done\")\r\n\t\t.def(\"Add\", &CTrisAddTriangle, bp::args(\"p1\", \"p2\", \"p3\"), \"Add a triangles given 3 Point3D objects\")\r\n\t\t.def(\"GetFlattenedSurface\", &CTris::GetFlattenedSurface, bp::return_value_policy<bp::manage_new_object>(), \"returns a new Stl with all the triangles unfolded into a flat shape\")\r\n\t\t.def(\"GetTrianglesAsCurveList\", &GetTrianglesAsCurveList, \"returns a list of Curve objects, each one being a closed triangle\")\r\n\t\t.def(\"GetMesh\", &CTrisGetMesh, bp::return_value_policy<bp::manage_new_object>(), \"returns a mesh\")\r\n\t\t.def(\"GetTriangles\", &CTrisGetTriangles, \"returns the list of tuples of tuples\")\r\n\r\n\t\t.def(bp::self += bp::other<CTris>())\r\n\t\t;\r\n\r\n\tbp::class_<CMesh>(\"Mesh\", \"Mesh(() - mesh of triangles\")\r\n\t\t.def(bp::init<CMesh>())\r\n\t\t.def(\"GetFaces\", &MeshGetFaces, \"a tuple with a list of vertices and a list of faces with vertex indexes\")\r\n\t\t;\r\n\r\n\tbp::enum_<FaceFlatType>(\"FaceFlatType\", \"face type for MachiningArea\")\r\n\t\t.value(\"Flat\", FaceFlatTypeFlat)\r\n\t\t.value(\"UpButNotFlat\", FaceFlatTypeUpButNotFlat)\r\n\t\t.value(\"Down\", FaceFlatTypeDown)\r\n\t\t;\r\n\r\n\tbp::class_<CMachiningArea>(\"MachiningArea\", \"MachiningArea() - empty MachiningArea\\n\\nUse Stl.GetMachiningAreas() to get a list of these from an Stl\")\r\n\t\t.def(bp::init<CMachiningArea>())\r\n\t\t.def_readwrite(\"area\", &CMachiningArea::m_area, \"Area - 2D area of all the similar triangles joined together\")\r\n\t\t.def_readwrite(\"top\", &CMachiningArea::m_top, \"z height of the top of the machining area\")\r\n\t\t.def_readwrite(\"bottom\", &CMachiningArea::m_bottom, \"z height of the bottom of the machining area\")\r\n\t\t.def_readwrite(\"face_type\", &CMachiningArea::m_face_type, \"see FaceFlatType\")\r\n\t;\r\n\r\n    bp::def(\"set_units\", set_units, \"function called set_units\", bp::args(\"units\"));\r\n    bp::def(\"get_units\", get_units);\r\n    bp::def(\"AreaFromDxf\", AreaFromDxf, bp::args(\"filepath\"), \"returns an Area created from a dxf file\");\r\n\tbp::def(\"TangentialArc\", TangentialArc, bp::args(\"p1\", \"p2\", \"v\"), \"given start point, end point and start vector\\nreturns the center point and span type\");\r\n\tbp::def(\"oct_ele_count\", get_oct_ele_count, \"just for debugging\");\r\n\tbp::def(\"set_tolerance\", set_tolerance, \"set the tolerance used for various geometry things like comparing tow points\");\r\n\tbp::def(\"get_tolerance\", get_tolerance, \"get the tolerance used for various geometry things like comparing tow points\");\r\n\tbp::def(\"set_accuracy\", set_accuracy, \"set the tolerance used for fitting arcs\");\r\n\tbp::def(\"get_accuracy\", get_accuracy, \"get the tolerance used for fitting arcs\");\r\n\tbp::def(\"set_fitarcs\", set_fitarcs, \"set to True if Area.FitArcs() is to be called automatically for boolean Area operations and Offset\");\r\n\tbp::def(\"get_fitarcs\", get_fitarcs, \"see set_fitarcs for description\");\r\n}\r\n", "meta": {"hexsha": "d6a1b30c65287f67f3e0914c7cf904a0656fae07", "size": 37856, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Geom/PythonStuff.cpp", "max_stars_repo_name": "danheeks/PyCAD", "max_stars_repo_head_hexsha": "711543aaa88c88a82d909f329b6ee36a9b96ae79", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2018-07-30T17:38:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T10:35:38.000Z", "max_issues_repo_path": "Geom/PythonStuff.cpp", "max_issues_repo_name": "danheeks/PyCAD", "max_issues_repo_head_hexsha": "711543aaa88c88a82d909f329b6ee36a9b96ae79", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-06-11T10:29:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-11T15:42:00.000Z", "max_forks_repo_path": "Geom/PythonStuff.cpp", "max_forks_repo_name": "danheeks/PyCAD", "max_forks_repo_head_hexsha": "711543aaa88c88a82d909f329b6ee36a9b96ae79", "max_forks_repo_licenses": ["BSD-3-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.9254054054, "max_line_length": 253, "alphanum_fraction": 0.6769336433, "num_tokens": 11041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.29453990001582064}}
{"text": "\n#include \"octotiger/unitiger/hydro_impl/flux_kernel_interface.hpp\"\n\n#include <aligned_buffer_util.hpp>\n#include <boost/container/vector.hpp>    // to get non-specialized vector<bool>\n#include <buffer_manager.hpp>\n\n\nboost::container::vector<bool> create_masks() {\n    constexpr int length = INX + 2;\n    constexpr int length_short = INX + 1;\n    boost::container::vector<bool> masks(NDIM * length * length * length);\n    constexpr size_t dim_offset = length * length * length;\n    const cell_geometry<3, 8> geo;\n    for (int dim = 0; dim < NDIM; dim++) {\n        std::array<int, NDIM> ubs = {length_short, length_short, length_short};\n        for (int dimension = 0; dimension < NDIM; dimension++) {\n            ubs[dimension] = geo.xloc()[geo.face_pts()[dim][0]][dimension] == -1 ? (length) : (length_short);\n        }\n        for (size_t ix = 0; ix < length; ix++) {\n            for (size_t iy = 0; iy < length; iy++) {\n                for (size_t iz = 0; iz < length; iz++) {\n                    const size_t index = ix * length * length + iy * length + iz + dim_offset * dim;\n                    if (ix > 0 && iy > 0 && iz > 0 && ix < ubs[0] && iy < ubs[1] && iz < ubs[2])\n                        masks[index] = true;\n                    else\n                        masks[index] = false;\n                }\n            }\n        }\n    }\n    return masks;\n}\n\n#ifdef __x86_64__ // currently only works on x86\n#ifdef OCTOTIGER_HAVE_VC\n#pragma GCC push_options\n#pragma GCC optimize(\"unroll-loops\")\n\n#include <Vc/Vc>\n#include <Vc/common/mask.h>\n#include <Vc/vector.h>\n\nusing vc_type = Vc::Vector<double, Vc::VectorAbi::Avx>;\nusing mask_type = vc_type::mask_type;\nusing index_type = Vc::Vector<int, Vc::VectorAbi::Avx>;\n\n// helpers for using vectortype specialization functions\ntemplate <>\ninline void select_wrapper<vc_type, mask_type>(\n    vc_type& target, const mask_type cond, const vc_type& tmp1, const vc_type& tmp2) {\n    target = tmp2;\n    Vc::where(cond, target) = tmp1;\n}\n\ntemplate <>\ninline vc_type max_wrapper<vc_type>(const vc_type& tmp1, const vc_type& tmp2) {\n    return Vc::max(tmp1, tmp2);\n}\ntemplate <>\ninline vc_type min_wrapper<vc_type>(const vc_type& tmp1, const vc_type& tmp2) {\n    return Vc::min(tmp1, tmp2);\n}\ntemplate <>\ninline vc_type sqrt_wrapper<vc_type>(const vc_type& tmp1) {\n    return Vc::sqrt(tmp1);\n}\n/// Awful workaround for missing Vc::pow\ntemplate <>\ninline vc_type pow_wrapper<vc_type>(const vc_type& tmp1, const double& tmp2) {\n    // TODO(daissgr) is this accurate enough?\n    return Vc::exp(static_cast<vc_type>(tmp2) * Vc::log(tmp1));\n\n    // vc_type ret = 0.0;\n    // for (auto vec_i = 0; vec_i < vc_type::size(); vec_i++) {\n    // ret[vec_i] = std::pow(tmp1[vec_i], tmp2);\n    //}\n    // return ret;\n}\ntemplate <>\ninline vc_type asinh_wrapper<vc_type>(const vc_type& tmp1) {\n    // not implemented \n    //return Vc::asinh(tmp1);\n\n    vc_type ret = 0.0;\n    for (auto vec_i = 0; vec_i < vc_type::size(); vec_i++) {\n      ret[vec_i] = std::asinh(tmp1[vec_i]);\n    }\n    return ret;\n}\ntemplate <>\ninline bool skippable<mask_type>(const mask_type& tmp1) {\n    return Vc::none_of(tmp1);\n}\ntemplate <>\ninline vc_type load_value<vc_type>(const double* __restrict__ data, const size_t index) {\n    return vc_type(data + index);\n}\n\ntimestep_t flux_cpu_kernel(const hydro::recon_type<NDIM>& Q, hydro::flux_type& F, hydro::x_type& X,\n    safe_real omega, const size_t nf_) {\n    // input Q, X\n    // output F\n\n    timestep_t ts;\n    ts.a = 0.0;\n\n    // bunch of small helpers\n    static const cell_geometry<3, 8> geo;\n    static constexpr auto faces = geo.face_pts();\n    static constexpr auto weights = geo.face_weight();\n    static constexpr auto xloc = geo.xloc();\n    double p, v, v0, c;\n    const auto A_ = physics<NDIM>::A_;\n    const auto B_ = physics<NDIM>::B_;\n    double current_amax = 0.0;\n    size_t current_max_index = 0;\n    size_t current_d = 0;\n    size_t current_dim = 0;\n\n    const double dx = X[0][geo.H_DNX] - X[0][0];\n\n    std::vector<vc_type> UR(nf_), UL(nf_), this_flux(nf_);\n    std::array<vc_type, NDIM> x;\n    std::array<vc_type, NDIM> vg;\n\n    for (int dim = 0; dim < NDIM; dim++) {\n        const auto indices = geo.get_indexes(3, geo.face_pts()[dim][0]);\n\n        std::array<int, NDIM> lbs = {3, 3, 3};\n        std::array<int, NDIM> ubs = {geo.H_NX - 3, geo.H_NX - 3, geo.H_NX - 3};\n        for (int dimension = 0; dimension < NDIM; dimension++) {\n            ubs[dimension] = geo.xloc()[geo.face_pts()[dim][0]][dimension] == -1 ?\n                (geo.H_NX - 3 + 1) :\n                (geo.H_NX - 3);\n            lbs[dimension] = geo.xloc()[geo.face_pts()[dim][0]][dimension] == +1 ? (3 - 1) : 3;\n        }\n\n        // zero-initialize F\n        for (int f = 0; f < nf_; f++) {\n#pragma ivdep\n            for (const auto& i : indices) {\n                F[dim][f][i] = 0.0;\n            }\n        }\n\n        for (int fi = 0; fi < geo.NFACEDIR; fi++) {    // 9\n            vc_type ap = 0.0, am = 0.0;                // final am ap for this i\n            safe_real this_amax = 0.0;\n            const auto d = faces[dim][fi];\n            const auto flipped_dim = geo.flip_dim(d, dim);\n            // std::cout << dim << \" flipped: \" << flipped_dim << \" d: \" << d << std::endl;\n            const vc_type zindices = vc_type::IndexesFromZero();\n            for (size_t ix = lbs[0]; ix < ubs[0]; ix++) {\n                for (size_t iy = lbs[1]; iy < ubs[1]; iy++) {\n                    for (size_t iz = lbs[2]; iz < geo.H_NX; iz += vc_type::size()) {\n                        const int border = ubs[2] - iz;\n                        const mask_type mask = (zindices < border);\n                        if (Vc::none_of(mask))\n                            continue;\n                        const size_t i = ix * geo.H_NX * geo.H_NX + iy * geo.H_NX + iz;\n                        vc_type this_ap = 0.0, this_am = 0.0;    // tmps\n\n                        for (int f = 0; f < nf_; f++) {\n                            UR[f] = vc_type(((Q[f][d]).data()) + i);\n                            UL[f] = vc_type(((Q[f][flipped_dim]).data()) + i - geo.H_DN[dim]);\n                            Vc::where(!mask, UR[f]) = 1.0;\n                            Vc::where(!mask, UL[f]) = 1.0;\n                        }\n                        for (int dim = 0; dim < NDIM; dim++) {\n                            x[dim] = vc_type(X[dim].data() + i) + vc_type(0.5 * xloc[d][dim] * dx);\n                        }\n                        vg[0] =\n                            -omega * (vc_type(X[1].data() + i) + vc_type(0.5 * xloc[d][1] * dx));\n                        vg[1] =\n                            +omega * (vc_type(X[0].data() + i) + vc_type(0.5 * xloc[d][0] * dx));\n                        vg[2] = 0.0;\n                        inner_flux_loop<vc_type>(omega, nf_, A_, B_, UR.data(), UL.data(),\n                            this_flux.data(), x.data(), vg.data(), this_ap, this_am, dim, d, dx,\n                            physics<NDIM>::fgamma_, physics<NDIM>::de_switch_1);\n                        Vc::where(!mask, this_ap) = 0.0;\n                        Vc::where(!mask, this_am) = 0.0;\n                        am = min_wrapper(am, this_am);\n                        ap = max_wrapper(ap, this_ap);\n                        vc_type tmp_amax = max_wrapper(ap, (-am));\n\n                        for (auto vec_i = 0; vec_i < vc_type::size(); vec_i++) {\n                            if (tmp_amax[vec_i] > current_amax) {\n                                current_amax = tmp_amax[vec_i];\n                                current_max_index = i + vec_i;\n                                current_d = d;\n                                current_dim = dim;\n                            }\n                        }\n                        for (int f = 0; f < nf_; f++) {\n                            // mask not required\n                            // Vc::where(!mask, this_flux[f]) = 0.0;\n                            // field update from flux\n                            const vc_type final_f =\n                                vc_type(F[dim][f].data() + i) + weights[fi] * this_flux[f];\n                            final_f.store(F[dim][f].data() + i);\n                        }\n                    }    // end z\n                }        // end y\n            }            // end x\n        }                // end dirs\n    }                    // end dim\n    static thread_local std::vector<double> URs(nf_), ULs(nf_);\n    // std::cout << \"current amax: \" << current_amax << std::endl;\n    // std::cin.get();\n    ts.a = current_amax;\n    ts.x = X[0][current_max_index];\n    ts.y = X[1][current_max_index];\n    ts.z = X[2][current_max_index];\n    const auto flipped_dim = geo.flip_dim(current_d, current_dim);\n    for (int f = 0; f < nf_; f++) {\n        URs[f] = Q[f][current_d][current_max_index];\n        ULs[f] = Q[f][flipped_dim][current_max_index - geo.H_DN[current_dim]];\n    }\n    ts.ul = URs;\n    ts.ur = ULs;\n    ts.dim = current_dim;\n    return ts;\n}\n\n/*timestep_t flux_unified_cpu_kernel(const hydro::recon_type<NDIM>& Q, hydro::flux_type& F,\n    hydro::x_type& X, safe_real omega, const size_t nf_) {\n    // input Q, X\n    // output F\n    // SAGIV: This is the last function that contains explicitly the number 15 as the number of fields (10 physical fields in 3D + 5 specie fields).\n    // I did not changed this function because it is not being called anyway. Maybe we can remove this function.\n\n    timestep_t ts;\n    ts.a = 0.0;\n    // Convert\n    std::vector<double, recycler::aggressive_recycle_std<double>> combined_q(\n        15 * 27 * 10 * 10 * 10 + 32);\n    auto it = combined_q.begin();\n    for (auto face = 0; face < 15; face++) {\n        for (auto d = 0; d < 27; d++) {\n            auto start_offset = 2 * 14 * 14 + 2 * 14 + 2;\n            for (auto ix = 2; ix < 2 + INX + 2; ix++) {\n                for (auto iy = 2; iy < 2 + INX + 2; iy++) {\n                    it = std::copy(Q[face][d].begin() + start_offset,\n                        Q[face][d].begin() + start_offset + 10, it);\n                    start_offset += 14;\n                }\n                start_offset += (2 + 2) * 14;\n            }\n        }\n    }\n    std::vector<double, recycler::aggressive_recycle_std<double>> combined_x(\n        NDIM * 1000 + 32);\n    auto it_x = combined_x.begin();\n    for (size_t dim = 0; dim < NDIM; dim++) {\n        auto start_offset = 2 * 14 * 14 + 2 * 14 + 2;\n        for (auto ix = 2; ix < 2 + INX + 2; ix++) {\n            for (auto iy = 2; iy < 2 + INX + 2; iy++) {\n                it_x = std::copy(\n                    X[dim].begin() + start_offset, X[dim].begin() + start_offset + 10, it_x);\n                start_offset += 14;\n            }\n            start_offset += (2 + 2) * 14;\n        }\n    }\n\n    std::vector<double, recycler::aggressive_recycle_std<double>> combined_f(\n        NDIM * 15 * 1000 + 32);\n    // bunch of tmp containers\n\n    // bunch of small helpers\n    static const cell_geometry<3, 8> geo;\n    static constexpr auto faces = geo.face_pts();\n    static constexpr auto weights = geo.face_weight();\n    static constexpr auto xloc = geo.xloc();\n    double p, v, v0, c;\n    const auto A_ = physics<NDIM>::A_;\n    const auto B_ = physics<NDIM>::B_;\n    double current_amax = 0.0;\n    size_t current_max_index = 0;\n    size_t current_d = 0;\n    size_t current_dim = 0;\n\n    const double dx = X[0][geo.H_DNX] - X[0][0];\n\n    std::vector<vc_type> this_flux(nf_);\n    std::array<vc_type, NDIM> x;\n    std::array<vc_type, NDIM> vg;\n\n    // TODO(daissgr) why is this only working with static?\n    static const auto masks_container = create_masks();\n    static const bool* masks = masks_container.data();\n\n    constexpr size_t dim_offset = 1000;\n    constexpr size_t face_offset = 27 * 1000;\n    constexpr int compressedH_DN[3] = {100, 10, 1};\n    for (int dim = 0; dim < NDIM; dim++) {\n        // zero-initialize F\n        for (int f = 0; f < nf_; f++) {\n            auto it = combined_f.begin() + dim * 15 * 1000 + f * 1000 + 111;\n            std::fill(it, it + 889, 0.0);\n        }\n        //auto it = combined_f.begin() + dim * 15 * 1000;\n        //std::fill(it, it + 15000, 0.0);\n\n        for (int fi = 0; fi < geo.NFACEDIR; fi++) {    // 9\n            vc_type ap = 0.0, am = 0.0;\n            safe_real this_amax = 0.0;\n            const auto d = faces[dim][fi];\n            const auto flipped_dim = geo.flip_dim(d, dim);\n\n            for (size_t index = 111; index < 10 * 100; index += vc_type::size()) {\n                const vc_type::mask_type mask(masks + index + dim * dim_offset);\n\n                if (Vc::none_of(mask))\n                    continue;\n                vc_type this_ap = 0.0, this_am = 0.0;    // tmps\n\n                for (int dim = 0; dim < NDIM; dim++) {\n                    x[dim] = vc_type(combined_x.data() + dim * 1000 + index) +\n                        vc_type(0.5 * xloc[d][dim] * dx);\n                }\n                vg[0] = -omega *\n                    (vc_type(combined_x.data() + 1000 + index) + vc_type(0.5 * xloc[d][1] * dx));\n                vg[1] =\n                    +omega * (vc_type(combined_x.data() + index) + vc_type(0.5 * xloc[d][0] * dx));\n                vg[2] = 0.0;\n                inner_flux_loop2<vc_type>(omega, nf_, A_, B_, combined_q.data(), this_flux.data(),\n                    x.data(), vg.data(), this_ap, this_am, dim, d, dx, physics<NDIM>::fgamma_,\n                    physics<NDIM>::de_switch_1, dim_offset * d + index,\n                    dim_offset * flipped_dim + index - compressedH_DN[dim], face_offset);\n\n                Vc::where(!mask, this_ap) = 0.0;\n                Vc::where(!mask, this_am) = 0.0;\n                am = min_wrapper(am, this_am);\n                ap = max_wrapper(ap, this_ap);\n                vc_type tmp_amax = max_wrapper(ap, (-am));\n\n                for (auto vec_i = 0; vec_i < vc_type::size(); vec_i++) {\n                    if (tmp_amax[vec_i] > current_amax) {\n                        current_amax = tmp_amax[vec_i];\n                        current_max_index = index + vec_i;\n                        current_d = d;\n                        current_dim = dim;\n                    }\n                }\n                for (int f = 0; f < nf_; f++) {\n                    //Vc::where(!mask, this_flux[f]) = 0.0;\n                    const vc_type final_f =\n                        vc_type(combined_f.data() + dim * 15 * 1000 + f * 1000 + index) +\n                        weights[fi] * this_flux[f];\n                    final_f.store(combined_f.data() + dim * 15 * 1000 + f * 1000 + index);\n                }\n            }\n        }    // end dirs\n    }        // end dim\n\n    // convert f\n    for (size_t dim = 0; dim < NDIM; dim++) {\n        for (auto face = 0; face < 15; face++) {\n            auto face_offse_f = dim * 15 * 1000 + face * 1000;\n            auto start_offset = 2 * 14 * 14 + 2 * 14 + 2;\n            auto compressed_offset = 0;\n            for (auto ix = 2; ix < 2 + INX + 2; ix++) {\n                for (auto iy = 2; iy < 2 + INX + 2; iy++) {\n                    std::copy(combined_f.begin() + face_offse_f + compressed_offset,\n                        combined_f.begin() + face_offse_f + compressed_offset + 10,\n                        F[dim][face].data() + start_offset);\n                    compressed_offset += 10;\n                    start_offset += 14;\n                }\n                start_offset += (2 + 2) * 14;\n            }\n        }\n    }\n    std::vector<double> URs(nf_), ULs(nf_);\n    ts.a = current_amax;\n    ts.x = combined_x[current_max_index];\n    ts.y = combined_x[current_max_index + 1000];\n    ts.z = combined_x[current_max_index + 2000];\n    const auto flipped_dim = geo.flip_dim(current_d, current_dim);\n    for (int f = 0; f < nf_; f++) {\n        URs[f] = combined_q[current_max_index + f * face_offset + dim_offset * current_d];\n        ULs[f] = combined_q[current_max_index - compressedH_DN[current_dim] + f * face_offset +\n            dim_offset * flipped_dim];\n    }\n    ts.ul = std::move(ULs);\n    ts.ur = std::move(URs);\n    ts.dim = current_dim;\n    return ts;\n}*/\n#pragma GCC pop_options\n#endif\n#endif\n", "meta": {"hexsha": "32ff398e6b89af3220e4eadec44cb1704ddfc9f6", "size": 16076, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/unitiger/hydro_impl/flux_cpu_kernel.cpp", "max_stars_repo_name": "srinivasyadav18/octotiger", "max_stars_repo_head_hexsha": "4d93c50fe345a081b7985ecb4cb698d16c121565", "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/unitiger/hydro_impl/flux_cpu_kernel.cpp", "max_issues_repo_name": "srinivasyadav18/octotiger", "max_issues_repo_head_hexsha": "4d93c50fe345a081b7985ecb4cb698d16c121565", "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/unitiger/hydro_impl/flux_cpu_kernel.cpp", "max_forks_repo_name": "srinivasyadav18/octotiger", "max_forks_repo_head_hexsha": "4d93c50fe345a081b7985ecb4cb698d16c121565", "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.6987341772, "max_line_length": 148, "alphanum_fraction": 0.5036078627, "num_tokens": 4545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778403, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.29447342690786027}}
{"text": "// ----------------------------------------------------------------------------\n// -                        Open3D: www.open3d.org                            -\n// ----------------------------------------------------------------------------\n// The MIT License (MIT)\n//\n// Copyright (c) 2018 www.open3d.org\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\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n// ----------------------------------------------------------------------------\n\n#include \"TransformationEstimation.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n#include <Eigen/Dense>\n#include <Open3D/Geometry/PointCloud.h>\n#include <Open3D/Utility/Eigen.h>\n#include <iostream>\n\nnamespace Eigen { \n \n#ifndef EIGEN_PARSED_BY_DOXYGEN\n\n    // These helpers are required since it allows to use mixed types as parameters\n    // for the Umeyama. The problem with mixed parameters is that the return type\n    // cannot trivially be deduced when float and double types are mixed.\n    namespace internal {\n\n        // Compile time return type deduction for different MatrixBase types.\n        // Different means here different alignment and parameters but the same underlying\n        // real scalar type.\n        template<typename MatrixType, typename OtherMatrixType>\n            struct umeyama_transform_matrix_type2\n            {\n                enum {\n                    MinRowsAtCompileTime = EIGEN_SIZE_MIN_PREFER_DYNAMIC(MatrixType::RowsAtCompileTime, OtherMatrixType::RowsAtCompileTime),\n\n                    // When possible we want to choose some small fixed size value since the result\n                    // is likely to fit on the stack. So here, EIGEN_SIZE_MIN_PREFER_DYNAMIC is not what we want.\n                    HomogeneousDimension = int(MinRowsAtCompileTime) == Dynamic ? Dynamic : int(MinRowsAtCompileTime)+1\n                };\n\n                typedef Matrix<typename traits<MatrixType>::Scalar,\n                        HomogeneousDimension,\n                        HomogeneousDimension,\n                        AutoAlign | (traits<MatrixType>::Flags & RowMajorBit ? RowMajor : ColMajor),\n                        HomogeneousDimension,\n                        HomogeneousDimension\n                            > type;\n            };\n\n    }\n\n#endif\n\n    // Similar to the original Eigen::Umeyama  https://eigen.tuxfamily.org/dox/Umeyama_8h_source.html\n    template <typename Derived, typename OtherDerived>\n    Eigen::Matrix4d umeyama_constrained(const Eigen::MatrixXd& _src, const Eigen::MatrixXd& _dst, bool with_scaling = true) {\n        typedef typename Eigen::internal::umeyama_transform_matrix_type2<Derived, OtherDerived>::type TransformationMatrixType;\n        typedef typename Eigen::internal::traits<TransformationMatrixType>::Scalar Scalar;\n        typedef typename Eigen::NumTraits<Scalar>::Real RealScalar;\n\n        enum { Dimension = EIGEN_SIZE_MIN_PREFER_DYNAMIC(Derived::RowsAtCompileTime, OtherDerived::RowsAtCompileTime) };\n\n        typedef Eigen::Matrix<Scalar, Dimension, 1> VectorType;\n        typedef Eigen::Matrix<Scalar, Dimension, Dimension> MatrixType;\n        typedef typename Eigen::internal::plain_matrix_type_row_major<Derived>::type RowMajorMatrixType;\n\n        const Index m = _src.rows(); // dimension\n        const Index n = _src.cols(); // number of measurements\n\n        Eigen::MatrixXd src(m, n);\n        src << _src.topRows(2), Eigen::MatrixXd::Zero(1, n);\n        Eigen::MatrixXd dst(m, n);\n        dst << _dst.topRows(2), Eigen::MatrixXd::Zero(1, n);\n\n        // required for demeaning ...\n        const RealScalar one_over_n = RealScalar(1) / static_cast<RealScalar>(n);\n\n        // computation of mean\n        const VectorType src_mean = src.rowwise().sum() * one_over_n;\n        const VectorType dst_mean = dst.rowwise().sum() * one_over_n;\n\n        // demeaning of src and dst points\n        const RowMajorMatrixType src_demean = src.colwise() - src_mean;\n        const RowMajorMatrixType dst_demean = dst.colwise() - dst_mean;\n\n        // Eq. (36)-(37)\n        const Scalar src_var = src_demean.rowwise().squaredNorm().sum() * one_over_n;\n\n        // Eq. (38)\n        const MatrixType sigma = one_over_n * dst_demean * src_demean.transpose();\n\n        Eigen::JacobiSVD<MatrixType> svd(sigma, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n        // Initialize the resulting transformation with an identity matrix...\n        TransformationMatrixType Rt = TransformationMatrixType::Identity(m+1,m+1);\n\n        // Eq. (39)\n        VectorType S = VectorType::Ones(m);\n\n        if  ( svd.matrixU().determinant() * svd.matrixV().determinant() < 0 ) {\n            // S(m-1) = -1;\n            Rt.col(m).head(m) = dst_mean-src_mean;\n            return Rt;\n        }\n\n        // Eq. (40) and (43)\n        Rt.block(0,0,m,m).noalias() = svd.matrixU() * S.asDiagonal() * svd.matrixV().transpose();\n\n        if (with_scaling)\n        {\n            // Eq. (42)\n            const Scalar c = Scalar(1)/src_var * svd.singularValues().dot(S);\n\n            // Eq. (41)\n            Rt.col(m).head(m) = dst_mean;\n            Rt.col(m).head(m).noalias() -= c*Rt.topLeftCorner(m,m)*src_mean;\n            Rt.block(0,0,m,m) *= c;\n        }\n        else\n        {\n            Rt.col(m).head(m) = dst_mean;\n            Rt.col(m).head(m).noalias() -= Rt.topLeftCorner(m,m)*src_mean;\n        }\n        return Rt;\n    }\n}\n\nnamespace open3d {\nnamespace registration {\n\ndouble TransformationEstimationPointToPoint::ComputeRMSE(\n        const geometry::PointCloud &source,\n        const geometry::PointCloud &target,\n        const CorrespondenceSet &corres) const {\n    if (corres.empty()) return 0.0;\n    double err = 0.0;\n    for (const auto &c : corres) {\n        err += (source.points_[c[0]] - target.points_[c[1]]).squaredNorm();\n    }\n    return std::sqrt(err / (double)corres.size());\n}\n\nEigen::Matrix4d TransformationEstimationPointToPoint::ComputeTransformation(\n        const geometry::PointCloud &source,\n        const geometry::PointCloud &target,\n        const CorrespondenceSet &corres) const {\n    if (corres.empty()) return Eigen::Matrix4d::Identity();\n    Eigen::MatrixXd source_mat(3, corres.size());\n    Eigen::MatrixXd target_mat(3, corres.size());\n    for (size_t i = 0; i < corres.size(); i++) {\n        source_mat.block<3, 1>(0, i) = source.points_[corres[i][0]];\n        target_mat.block<3, 1>(0, i) = target.points_[corres[i][1]];\n    }\n    if (with_constraint_) {\n        return Eigen::umeyama_constrained<Eigen::MatrixXd, Eigen::MatrixXd>(source_mat, target_mat, with_scaling_);\n    }\n    else {\n        return Eigen::umeyama(source_mat, target_mat, with_scaling_);\n    }\n}\n\ndouble TransformationEstimationPointToPlane::ComputeRMSE(\n        const geometry::PointCloud &source,\n        const geometry::PointCloud &target,\n        const CorrespondenceSet &corres) const {\n    if (corres.empty() || target.HasNormals() == false) return 0.0;\n    double err = 0.0, r;\n    for (const auto &c : corres) {\n        r = (source.points_[c[0]] - target.points_[c[1]])\n                    .dot(target.normals_[c[1]]);\n        err += r * r;\n    }\n    return std::sqrt(err / (double)corres.size());\n}\n\nEigen::Matrix4d TransformationEstimationPointToPlane::ComputeTransformation(\n        const geometry::PointCloud &source,\n        const geometry::PointCloud &target,\n        const CorrespondenceSet &corres) const {\n    if (corres.empty() || target.HasNormals() == false)\n        return Eigen::Matrix4d::Identity();\n\n    auto compute_jacobian_and_residual = [&](int i, Eigen::Vector6d &J_r,\n                                             double &r) {\n        const Eigen::Vector3d &vs = source.points_[corres[i][0]];\n        const Eigen::Vector3d &vt = target.points_[corres[i][1]];\n        const Eigen::Vector3d &nt = target.normals_[corres[i][1]];\n        r = (vs - vt).dot(nt);\n        J_r.block<3, 1>(0, 0) = vs.cross(nt);\n        J_r.block<3, 1>(3, 0) = nt;\n    };\n\n    Eigen::Matrix6d JTJ;\n    Eigen::Vector6d JTr;\n    double r2;\n    std::tie(JTJ, JTr, r2) =\n            utility::ComputeJTJandJTr<Eigen::Matrix6d, Eigen::Vector6d>(\n                    compute_jacobian_and_residual, (int)corres.size());\n\n    bool is_success;\n    Eigen::Matrix4d extrinsic;\n    std::tie(is_success, extrinsic) =\n            utility::SolveJacobianSystemAndObtainExtrinsicMatrix(JTJ, JTr);\n\n    return is_success ? extrinsic : Eigen::Matrix4d::Identity();\n}\n\n}  // namespace registration\n}  // namespace open3d\n", "meta": {"hexsha": "26df434dcbcebe824ec31c6e51c2b5ccd5ae0c28", "size": 9458, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Open3D/Registration/TransformationEstimation.cpp", "max_stars_repo_name": "grossjohannes/Open3D", "max_stars_repo_head_hexsha": "423490c92095352fd412048d005e04ae4f15308a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Open3D/Registration/TransformationEstimation.cpp", "max_issues_repo_name": "grossjohannes/Open3D", "max_issues_repo_head_hexsha": "423490c92095352fd412048d005e04ae4f15308a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Open3D/Registration/TransformationEstimation.cpp", "max_forks_repo_name": "grossjohannes/Open3D", "max_forks_repo_head_hexsha": "423490c92095352fd412048d005e04ae4f15308a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-16T10:09:32.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-16T10:09:32.000Z", "avg_line_length": 41.1217391304, "max_line_length": 140, "alphanum_fraction": 0.6246563756, "num_tokens": 2230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.294473420473483}}
{"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_TRIGONOMETRIC_CONSTANTS_PIO_4LO_HPP_INCLUDED\n#define NT2_TRIGONOMETRIC_CONSTANTS_PIO_4LO_HPP_INCLUDED\n\n#include <nt2/include/functor.hpp>\n#include <boost/simd/constant/hierarchy.hpp>\n#include <boost/simd/constant/register.hpp>\n\nnamespace nt2\n{\n  namespace tag\n  {\n   /*!\n     @brief Pio_4lo generic tag\n\n     Represents the Pio_4lo constant in generic contexts.\n\n     @par Models:\n        Hierarchy\n   **/\n    BOOST_SIMD_CONSTANT_REGISTER( Pio_4lo, double\n                                , 0, 0xb2bbbd2eUL\n                                , 0x3c81a62633145c07ULL\n                                )\n  }\n  namespace ext\n  {\n   template<class Site, class... Ts>\n   BOOST_FORCEINLINE generic_dispatcher<tag::Pio_4lo, Site> dispatching_Pio_4lo(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)\n   {\n     return generic_dispatcher<tag::Pio_4lo, Site>();\n   }\n   template<class... Args>\n   struct impl_Pio_4lo;\n  }\n  /*!\n    This constant is such that, for pairs of types (Tup, T)\n    (namely (float,  double) and (double, long double)) the sum:\n\n    abs(Tup(Pio_4lo<T>())+Tup(Pio_4<T>())-Pio_4<Tup>())  is  lesser than\n    a few Eps<Tup>().\n\n    This is used to improve accurracy when computing sums of the kind\n    Pio_4 + x with x small,  by replacing them by Pio_4 + (Pio_4lo+x)\n\n    @par Semantic:\n\n    For type T0:\n\n    @code\n    T r = Pio_4lo<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    if T is double\n      r = 3.061616997868383e-17\n    else if T is float\n      r = -2.1855694e-08\n    @endcode\n\n    @return a value of type T0\n  **/\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(tag::Pio_4lo, Pio_4lo);\n}\n\n#endif\n\n", "meta": {"hexsha": "f501478e3f25d97ca491bb11b45273fb20c0f47a", "size": 2174, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/pio_4lo.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/pio_4lo.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/trigonometric/include/nt2/trigonometric/constants/pio_4lo.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2337662338, "max_line_length": 170, "alphanum_fraction": 0.5850965961, "num_tokens": 611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2944445725990201}}
{"text": "/* Author: Chih-Che Chueh, University of Victoria, 2010 */\n/*         Wolfgang Bangerth, Texas A&M University, 2010 */\n\n/*    $Id: step-43.cc 27661 2012-11-21 14:38:52Z bangerth $       */\n/*                                                                */\n/*    Copyright (C) 2010-2012 by Chih-Che Chueh and the deal.II authors */\n/*                                                                */\n/*    This file is subject to QPL and may not be  distributed     */\n/*    without copyright and license information. Please refer     */\n/*    to the file deal.II/doc/license.html for the  text  and     */\n/*    further information on this license.                        */\n\n\n// @sect3{Include files}\n\n// The first step, as always, is to include the functionality of a number of\n// deal.II and C++ header files.\n//\n// The list includes some header files that provide vector, matrix, and\n// preconditioner classes that implement interfaces to the respective Trilinos\n// classes; some more information on these may be found in step-31.\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/utilities.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/tensor_function.h>\n#include <deal.II/base/std_cxx1x/shared_ptr.h>\n\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/solver_gmres.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/block_sparsity_pattern.h>\n#include <deal.II/lac/constraint_matrix.h>\n\n#include <deal.II/grid/tria.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/grid_tools.h>\n\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_renumbering.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_system.h>\n#include <deal.II/fe/fe_values.h>\n\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/solution_transfer.h>\n\n#include <deal.II/lac/trilinos_sparse_matrix.h>\n#include <deal.II/lac/trilinos_block_sparse_matrix.h>\n#include <deal.II/lac/trilinos_vector.h>\n#include <deal.II/lac/trilinos_block_vector.h>\n#include <deal.II/lac/trilinos_precondition.h>\n\n#include <fstream>\n#include <sstream>\n\n\n// At the end of this top-matter, we open a namespace for the current project\n// into which all the following material will go, and then import all deal.II\n// names into this namespace:\nnamespace Step43\n{\n  using namespace dealii;\n\n\n  // @sect3{Pressure right hand side, pressure boundary values and saturation initial value classes}\n\n  // The following part is taken directly from step-21 so there is no need to\n  // repeat the descriptions found there.\n  template <int dim>\n  class PressureRightHandSide : public Function<dim>\n  {\n  public:\n    PressureRightHandSide () : Function<dim>(1) {}\n\n    virtual double value (const Point<dim>   &p,\n                          const unsigned int  component = 0) const;\n  };\n\n\n\n  template <int dim>\n  double\n  PressureRightHandSide<dim>::value (const Point<dim>  & /*p*/,\n                                     const unsigned int /*component*/) const\n  {\n    return 0;\n  }\n\n\n  template <int dim>\n  class PressureBoundaryValues : public Function<dim>\n  {\n  public:\n    PressureBoundaryValues () : Function<dim>(1) {}\n\n    virtual double value (const Point<dim>   &p,\n                          const unsigned int  component = 0) const;\n  };\n\n\n  template <int dim>\n  double\n  PressureBoundaryValues<dim>::value (const Point<dim> &p,\n                                      const unsigned int /*component*/) const\n  {\n    return 1-p[0];\n  }\n\n\n  template <int dim>\n  class SaturationBoundaryValues : public Function<dim>\n  {\n  public:\n    SaturationBoundaryValues () : Function<dim>(1) {}\n\n    virtual double value (const Point<dim>   &p,\n                          const unsigned int  component = 0) const;\n  };\n\n\n\n  template <int dim>\n  double\n  SaturationBoundaryValues<dim>::value (const Point<dim> &p,\n                                        const unsigned int /*component*/) const\n  {\n    if (p[0] == 0)\n      return 1;\n    else\n      return 0;\n  }\n\n\n  template <int dim>\n  class SaturationInitialValues : public Function<dim>\n  {\n  public:\n    SaturationInitialValues () : Function<dim>(1) {}\n\n    virtual double value (const Point<dim>   &p,\n                          const unsigned int  component = 0) const;\n\n    virtual void vector_value (const Point<dim> &p,\n                               Vector<double>   &value) const;\n  };\n\n\n  template <int dim>\n  double\n  SaturationInitialValues<dim>::value (const Point<dim>  & /*p*/,\n                                       const unsigned int /*component*/) const\n  {\n    return 0.2;\n  }\n\n\n  template <int dim>\n  void\n  SaturationInitialValues<dim>::vector_value (const Point<dim> &p,\n                                              Vector<double>   &values) const\n  {\n    for (unsigned int c=0; c<this->n_components; ++c)\n      values(c) = SaturationInitialValues<dim>::value (p,c);\n  }\n\n\n  // @sect3{Permeability models}\n\n  // In this tutorial, we still use the two permeability models previously\n  // used in step-21 so we again refrain from commenting in detail about them.\n  namespace SingleCurvingCrack\n  {\n    template <int dim>\n    class KInverse : public TensorFunction<2,dim>\n    {\n    public:\n      KInverse ()\n        :\n        TensorFunction<2,dim> ()\n      {}\n\n      virtual void value_list (const std::vector<Point<dim> > &points,\n                               std::vector<Tensor<2,dim> >    &values) const;\n    };\n\n\n    template <int dim>\n    void\n    KInverse<dim>::value_list (const std::vector<Point<dim> > &points,\n                               std::vector<Tensor<2,dim> >    &values) const\n    {\n      Assert (points.size() == values.size(),\n              ExcDimensionMismatch (points.size(), values.size()));\n\n      for (unsigned int p=0; p<points.size(); ++p)\n        {\n          values[p].clear ();\n\n          const double distance_to_flowline\n            = std::fabs(points[p][1]-0.5-0.1*std::sin(10*points[p][0]));\n\n          const double permeability = std::max(std::exp(-(distance_to_flowline*\n                                                          distance_to_flowline)\n                                                        / (0.1 * 0.1)),\n                                               0.01);\n\n          for (unsigned int d=0; d<dim; ++d)\n            values[p][d][d] = 1./permeability;\n        }\n    }\n  }\n\n\n  namespace RandomMedium\n  {\n    template <int dim>\n    class KInverse : public TensorFunction<2,dim>\n    {\n    public:\n      KInverse ()\n        :\n        TensorFunction<2,dim> ()\n      {}\n\n      virtual void value_list (const std::vector<Point<dim> > &points,\n                               std::vector<Tensor<2,dim> >    &values) const;\n\n    private:\n      static std::vector<Point<dim> > centers;\n\n      static std::vector<Point<dim> > get_centers ();\n    };\n\n\n\n    template <int dim>\n    std::vector<Point<dim> >\n    KInverse<dim>::centers = KInverse<dim>::get_centers();\n\n\n    template <int dim>\n    std::vector<Point<dim> >\n    KInverse<dim>::get_centers ()\n    {\n      const unsigned int N = (dim == 2 ?\n                              40 :\n                              (dim == 3 ?\n                               100 :\n                               throw ExcNotImplemented()));\n\n      std::vector<Point<dim> > centers_list (N);\n      for (unsigned int i=0; i<N; ++i)\n        for (unsigned int d=0; d<dim; ++d)\n          centers_list[i][d] = static_cast<double>(rand())/RAND_MAX;\n\n      return centers_list;\n    }\n\n\n\n    template <int dim>\n    void\n    KInverse<dim>::value_list (const std::vector<Point<dim> > &points,\n                               std::vector<Tensor<2,dim> >    &values) const\n    {\n      Assert (points.size() == values.size(),\n              ExcDimensionMismatch (points.size(), values.size()));\n\n      for (unsigned int p=0; p<points.size(); ++p)\n        {\n          values[p].clear ();\n\n          double permeability = 0;\n          for (unsigned int i=0; i<centers.size(); ++i)\n            permeability += std::exp(-(points[p]-centers[i]).square()\n                                     / (0.05 * 0.05));\n\n          const double normalized_permeability\n            = std::min (std::max(permeability, 0.01), 4.);\n\n          for (unsigned int d=0; d<dim; ++d)\n            values[p][d][d] = 1./normalized_permeability;\n        }\n    }\n  }\n\n\n  // @sect3{Physical quantities}\n\n  // The implementations of all the physical quantities such as total mobility\n  // $\\lambda_t$ and fractional flow of water $F$ are taken from step-21 so\n  // again we don't have do any comment about them. Compared to step-21 we\n  // have added checks that the saturation passed to these functions is in\n  // fact within the physically valid range. Furthermore, given that the\n  // wetting phase moves at speed $\\mathbf u F'(S)$ it is clear that $F'(S)$\n  // must be greater or equal to zero, so we assert that as well to make sure\n  // that our calculations to get at the formula for the derivative made\n  // sense.\n  double mobility_inverse (const double S,\n                           const double viscosity)\n  {\n    return 1.0 / (1.0/viscosity * S * S + (1-S) * (1-S));\n  }\n\n\n  double fractional_flow (const double S,\n                          const double viscosity)\n  {\n    Assert ((S >= 0) && (S<=1),\n            ExcMessage (\"Saturation is outside its physically valid range.\"));\n\n    return S*S / ( S * S + viscosity * (1-S) * (1-S));\n  }\n\n\n  double fractional_flow_derivative (const double S,\n                                     const double viscosity)\n  {\n    Assert ((S >= 0) && (S<=1),\n            ExcMessage (\"Saturation is outside its physically valid range.\"));\n\n    const double temp = ( S * S + viscosity * (1-S) * (1-S) );\n\n    const double numerator   =  2.0 * S * temp\n                                -\n                                S * S *\n                                ( 2.0 * S - 2.0 * viscosity * (1-S) );\n    const double denominator =  std::pow(temp, 2.0);\n\n    const double F_prime = numerator / denominator;\n\n    Assert (F_prime >= 0, ExcInternalError());\n\n    return F_prime;\n  }\n\n\n  // @sect3{Helper classes for solvers and preconditioners}\n\n  // In this first part we define a number of classes that we need in the\n  // construction of linear solvers and preconditioners. This part is\n  // essentially the same as that used in step-31. The only difference is that\n  // the original variable name stokes_matrix is replaced by another name\n  // darcy_matrix to match our problem.\n  namespace LinearSolvers\n  {\n    template <class Matrix, class Preconditioner>\n    class InverseMatrix : public Subscriptor\n    {\n    public:\n      InverseMatrix (const Matrix         &m,\n                     const Preconditioner &preconditioner);\n\n\n      template <typename VectorType>\n      void vmult (VectorType       &dst,\n                  const VectorType &src) const;\n\n    private:\n      const SmartPointer<const Matrix> matrix;\n      const Preconditioner &preconditioner;\n    };\n\n\n    template <class Matrix, class Preconditioner>\n    InverseMatrix<Matrix,Preconditioner>::\n    InverseMatrix (const Matrix &m,\n                   const Preconditioner &preconditioner)\n      :\n      matrix (&m),\n      preconditioner (preconditioner)\n    {}\n\n\n\n    template <class Matrix, class Preconditioner>\n    template <typename VectorType>\n    void\n    InverseMatrix<Matrix,Preconditioner>::\n    vmult (VectorType       &dst,\n           const VectorType &src) const\n    {\n      SolverControl solver_control (src.size(), 1e-7*src.l2_norm());\n      SolverCG<VectorType> cg (solver_control);\n\n      dst = 0;\n\n      try\n        {\n          cg.solve (*matrix, dst, src, preconditioner);\n        }\n      catch (std::exception &e)\n        {\n          Assert (false, ExcMessage(e.what()));\n        }\n    }\n\n    template <class PreconditionerA, class PreconditionerMp>\n    class BlockSchurPreconditioner : public Subscriptor\n    {\n    public:\n      BlockSchurPreconditioner (\n        const TrilinosWrappers::BlockSparseMatrix     &S,\n        const InverseMatrix<TrilinosWrappers::SparseMatrix,\n        PreconditionerMp>         &Mpinv,\n        const PreconditionerA                         &Apreconditioner);\n\n      void vmult (TrilinosWrappers::BlockVector       &dst,\n                  const TrilinosWrappers::BlockVector &src) const;\n\n    private:\n      const SmartPointer<const TrilinosWrappers::BlockSparseMatrix> darcy_matrix;\n      const SmartPointer<const InverseMatrix<TrilinosWrappers::SparseMatrix,\n            PreconditionerMp > > m_inverse;\n      const PreconditionerA &a_preconditioner;\n\n      mutable TrilinosWrappers::Vector tmp;\n    };\n\n\n\n    template <class PreconditionerA, class PreconditionerMp>\n    BlockSchurPreconditioner<PreconditionerA, PreconditionerMp>::\n    BlockSchurPreconditioner(const TrilinosWrappers::BlockSparseMatrix &S,\n                             const InverseMatrix<TrilinosWrappers::SparseMatrix,\n                             PreconditionerMp>      &Mpinv,\n                             const PreconditionerA                      &Apreconditioner)\n      :\n      darcy_matrix            (&S),\n      m_inverse               (&Mpinv),\n      a_preconditioner        (Apreconditioner),\n      tmp                     (darcy_matrix->block(1,1).m())\n    {}\n\n\n    template <class PreconditionerA, class PreconditionerMp>\n    void BlockSchurPreconditioner<PreconditionerA, PreconditionerMp>::vmult (\n      TrilinosWrappers::BlockVector       &dst,\n      const TrilinosWrappers::BlockVector &src) const\n    {\n      a_preconditioner.vmult (dst.block(0), src.block(0));\n      darcy_matrix->block(1,0).residual(tmp, dst.block(0), src.block(1));\n      tmp *= -1;\n      m_inverse->vmult (dst.block(1), tmp);\n    }\n  }\n\n\n  // @sect3{The TwoPhaseFlowProblem class}\n\n  // The definition of the class that defines the top-level logic of solving\n  // the time-dependent advection-dominated two-phase flow problem (or\n  // Buckley-Leverett problem [Buckley 1942]) is mainly based on tutorial\n  // programs step-21 and step-33, and in particular on step-31 where we have\n  // used basically the same general structure as done here. As in step-31,\n  // the key routines to look for in the implementation below are the\n  // <code>run()</code> and <code>solve()</code> functions.\n  //\n  // The main difference to step-31 is that, since adaptive operator splitting\n  // is considered, we need a couple more member variables to hold the last\n  // two computed Darcy (velocity/pressure) solutions in addition to the\n  // current one (which is either computed directly, or extrapolated from the\n  // previous two), and we need to remember the last two times we computed the\n  // Darcy solution. We also need a helper function that figures out whether\n  // we do indeed need to recompute the Darcy solution.\n  //\n  // Unlike step-31, this step uses one more ConstraintMatrix object called\n  // darcy_preconditioner_constraints. This constraint object is used only for\n  // assembling the matrix for the Darcy preconditioner and includes hanging\n  // node constrants as well as Dirichlet boundary value constraints for the\n  // pressure variable. We need this because we are building a Laplace matrix\n  // for the pressure as an approximation of the Schur complement) which is\n  // only positive definite if boundary conditions are applied.\n  //\n  // The collection of member functions and variables thus declared in this\n  // class is then rather similar to those in step-31:\n  template <int dim>\n  class TwoPhaseFlowProblem\n  {\n  public:\n    TwoPhaseFlowProblem (const unsigned int degree);\n    void run ();\n\n  private:\n    void setup_dofs ();\n    void assemble_darcy_preconditioner ();\n    void build_darcy_preconditioner ();\n    void assemble_darcy_system ();\n    void assemble_saturation_system ();\n    void assemble_saturation_matrix ();\n    void assemble_saturation_rhs ();\n    void assemble_saturation_rhs_cell_term (const FEValues<dim>             &saturation_fe_values,\n                                            const FEValues<dim>             &darcy_fe_values,\n                                            const double                     global_max_u_F_prime,\n                                            const double                     global_S_variation,\n                                            const std::vector<unsigned int> &local_dof_indices);\n    void assemble_saturation_rhs_boundary_term (const FEFaceValues<dim>             &saturation_fe_face_values,\n                                                const FEFaceValues<dim>             &darcy_fe_face_values,\n                                                const std::vector<unsigned int>     &local_dof_indices);\n    void solve ();\n    void refine_mesh (const unsigned int              min_grid_level,\n                      const unsigned int              max_grid_level);\n    void output_results () const;\n\n    // We follow with a number of helper functions that are used in a variety\n    // of places throughout the program:\n    double                   get_max_u_F_prime () const;\n    std::pair<double,double> get_extrapolated_saturation_range () const;\n    bool                     determine_whether_to_solve_for_pressure_and_velocity () const;\n    void                     project_back_saturation ();\n    double                   compute_viscosity (const std::vector<double>          &old_saturation,\n                                                const std::vector<double>          &old_old_saturation,\n                                                const std::vector<Tensor<1,dim> > &old_saturation_grads,\n                                                const std::vector<Tensor<1,dim> > &old_old_saturation_grads,\n                                                const std::vector<Vector<double> > &present_darcy_values,\n                                                const double                        global_max_u_F_prime,\n                                                const double                        global_S_variation,\n                                                const double                        cell_diameter) const;\n\n\n    // This all is followed by the member variables, most of which are similar\n    // to the ones in step-31, with the exception of the ones that pertain to\n    // the macro time stepping for the velocity/pressure system:\n    Triangulation<dim>                   triangulation;\n    double                               global_Omega_diameter;\n\n    const unsigned int degree;\n\n    const unsigned int                   darcy_degree;\n    FESystem<dim>                        darcy_fe;\n    DoFHandler<dim>                      darcy_dof_handler;\n    ConstraintMatrix                     darcy_constraints;\n\n    ConstraintMatrix                     darcy_preconditioner_constraints;\n\n    TrilinosWrappers::BlockSparseMatrix  darcy_matrix;\n    TrilinosWrappers::BlockSparseMatrix  darcy_preconditioner_matrix;\n\n    TrilinosWrappers::BlockVector        darcy_solution;\n    TrilinosWrappers::BlockVector        darcy_rhs;\n\n    TrilinosWrappers::BlockVector        last_computed_darcy_solution;\n    TrilinosWrappers::BlockVector        second_last_computed_darcy_solution;\n\n\n    const unsigned int                   saturation_degree;\n    FE_Q<dim>                            saturation_fe;\n    DoFHandler<dim>                      saturation_dof_handler;\n    ConstraintMatrix                     saturation_constraints;\n\n    TrilinosWrappers::SparseMatrix       saturation_matrix;\n\n\n    TrilinosWrappers::Vector             saturation_solution;\n    TrilinosWrappers::Vector             old_saturation_solution;\n    TrilinosWrappers::Vector             old_old_saturation_solution;\n    TrilinosWrappers::Vector             saturation_rhs;\n\n    TrilinosWrappers::Vector             saturation_matching_last_computed_darcy_solution;\n\n    const double                         saturation_refinement_threshold;\n\n    double                               time;\n    const double                         end_time;\n\n    double                               current_macro_time_step;\n    double                               old_macro_time_step;\n\n    double                               time_step;\n    double                               old_time_step;\n    unsigned int                         timestep_number;\n\n    const double                         viscosity;\n    const double                         porosity;\n    const double                         AOS_threshold;\n\n    std_cxx1x::shared_ptr<TrilinosWrappers::PreconditionIC> Amg_preconditioner;\n    std_cxx1x::shared_ptr<TrilinosWrappers::PreconditionIC> Mp_preconditioner;\n\n    bool                                rebuild_saturation_matrix;\n\n    // At the very end we declare a variable that denotes the material\n    // model. Compared to step-21, we do this here as a member variable since\n    // we will want to use it in a variety of places and so having a central\n    // place where such a variable is declared will make it simpler to replace\n    // one class by another (e.g. replace RandomMedium::KInverse by\n    // SingleCurvingCrack::KInverse).\n    const RandomMedium::KInverse<dim>   k_inverse;\n  };\n\n\n  // @sect3{TwoPhaseFlowProblem<dim>::TwoPhaseFlowProblem}\n\n  // The constructor of this class is an extension of the constructors in\n  // step-21 and step-31. We need to add the various variables that concern\n  // the saturation. As discussed in the introduction, we are going to use\n  // $Q_2 \\times Q_1$ (Taylor-Hood) elements again for the Darcy system, an\n  // element combination that fulfills the Ladyzhenskaya-Babuska-Brezzi (LBB)\n  // conditions [Brezzi and Fortin 1991, Chen 2005], and $Q_1$ elements for\n  // the saturation. However, by using variables that store the polynomial\n  // degree of the Darcy and temperature finite elements, it is easy to\n  // consistently modify the degree of the elements as well as all quadrature\n  // formulas used on them downstream. Moreover, we initialize the time\n  // stepping variables related to operator splitting as well as the option\n  // for matrix assembly and preconditioning:\n  template <int dim>\n  TwoPhaseFlowProblem<dim>::TwoPhaseFlowProblem (const unsigned int degree)\n    :\n    triangulation (Triangulation<dim>::maximum_smoothing),\n\n    degree (degree),\n    darcy_degree (degree),\n    darcy_fe (FE_Q<dim>(darcy_degree+1), dim,\n              FE_Q<dim>(darcy_degree), 1),\n    darcy_dof_handler (triangulation),\n\n    saturation_degree (degree+1),\n    saturation_fe (saturation_degree),\n    saturation_dof_handler (triangulation),\n\n    saturation_refinement_threshold (0.5),\n\n    time (0),\n    end_time (10),\n\n    current_macro_time_step (0),\n    old_macro_time_step (0),\n\n    time_step (0),\n    old_time_step (0),\n    viscosity (0.2),\n    porosity (1.0),\n    AOS_threshold (3.0),\n\n    rebuild_saturation_matrix (true)\n  {}\n\n\n  // @sect3{TwoPhaseFlowProblem<dim>::setup_dofs}\n\n  // This is the function that sets up the DoFHandler objects we have here\n  // (one for the Darcy part and one for the saturation part) as well as set\n  // to the right sizes the various objects required for the linear algebra in\n  // this program. Its basic operations are similar to what step-31 did.\n  //\n  // The body of the function first enumerates all degrees of freedom for the\n  // Darcy and saturation systems. For the Darcy part, degrees of freedom are\n  // then sorted to ensure that velocities precede pressure DoFs so that we\n  // can partition the Darcy matrix into a $2 \\times 2$ matrix.\n  //\n  // Then, we need to incorporate hanging node constraints and Dirichlet\n  // boundary value constraints into darcy_preconditioner_constraints.  The\n  // boundary condition constraints are only set on the pressure component\n  // since the Schur complement preconditioner that corresponds to the porous\n  // media flow operator in non-mixed form, $-\\nabla \\cdot [\\mathbf K\n  // \\lambda_t(S)]\\nabla$, acts only on the pressure variable. Therefore, we\n  // use a component_mask that filters out the velocity component, so that the\n  // condensation is performed on pressure degrees of freedom only.\n  //\n  // After having done so, we count the number of degrees of freedom in the\n  // various blocks. This information is then used to create the sparsity\n  // pattern for the Darcy and saturation system matrices as well as the\n  // preconditioner matrix from which we build the Darcy preconditioner. As in\n  // step-31, we choose to create the pattern not as in the first few tutorial\n  // programs, but by using the blocked version of\n  // CompressedSimpleSparsityPattern. The reason for doing this is mainly\n  // memory, that is, the SparsityPattern class would consume too much memory\n  // when used in three spatial dimensions as we intend to do for this\n  // program. So, for this, we follow the same way as step-31 did and we don't\n  // have to repeat descriptions again for the rest of the member function.\n  template <int dim>\n  void TwoPhaseFlowProblem<dim>::setup_dofs ()\n  {\n    std::vector<unsigned int> darcy_block_component (dim+1,0);\n    darcy_block_component[dim] = 1;\n    {\n      darcy_dof_handler.distribute_dofs (darcy_fe);\n      DoFRenumbering::Cuthill_McKee (darcy_dof_handler);\n      DoFRenumbering::component_wise (darcy_dof_handler, darcy_block_component);\n\n      darcy_constraints.clear ();\n      DoFTools::make_hanging_node_constraints (darcy_dof_handler, darcy_constraints);\n      darcy_constraints.close ();\n    }\n    {\n      saturation_dof_handler.distribute_dofs (saturation_fe);\n\n      saturation_constraints.clear ();\n      DoFTools::make_hanging_node_constraints (saturation_dof_handler, saturation_constraints);\n      saturation_constraints.close ();\n    }\n    {\n      darcy_preconditioner_constraints.clear ();\n\n      FEValuesExtractors::Scalar pressure(dim);\n\n      DoFTools::make_hanging_node_constraints (darcy_dof_handler, darcy_preconditioner_constraints);\n      DoFTools::make_zero_boundary_constraints (darcy_dof_handler, darcy_preconditioner_constraints,\n                                                darcy_fe.component_mask(pressure));\n\n      darcy_preconditioner_constraints.close ();\n    }\n\n\n    std::vector<unsigned int> darcy_dofs_per_block (2);\n    DoFTools::count_dofs_per_block (darcy_dof_handler, darcy_dofs_per_block, darcy_block_component);\n    const unsigned int n_u = darcy_dofs_per_block[0],\n                       n_p = darcy_dofs_per_block[1],\n                       n_s = saturation_dof_handler.n_dofs();\n\n    std::cout << \"Number of active cells: \"\n              << triangulation.n_active_cells()\n              << \" (on \"\n              << triangulation.n_levels()\n              << \" levels)\"\n              << std::endl\n              << \"Number of degrees of freedom: \"\n              << n_u + n_p + n_s\n              << \" (\" << n_u << '+' << n_p << '+'<< n_s <<')'\n              << std::endl\n              << std::endl;\n\n    {\n      darcy_matrix.clear ();\n\n      BlockCompressedSimpleSparsityPattern csp (2,2);\n\n      csp.block(0,0).reinit (n_u, n_u);\n      csp.block(0,1).reinit (n_u, n_p);\n      csp.block(1,0).reinit (n_p, n_u);\n      csp.block(1,1).reinit (n_p, n_p);\n\n      csp.collect_sizes ();\n\n      Table<2,DoFTools::Coupling> coupling (dim+1, dim+1);\n\n      for (unsigned int c=0; c<dim+1; ++c)\n        for (unsigned int d=0; d<dim+1; ++d)\n          if (! ((c==dim) && (d==dim)))\n            coupling[c][d] = DoFTools::always;\n          else\n            coupling[c][d] = DoFTools::none;\n\n\n      DoFTools::make_sparsity_pattern (darcy_dof_handler, coupling, csp,\n                                       darcy_constraints, false);\n\n      darcy_matrix.reinit (csp);\n    }\n\n    {\n      Amg_preconditioner.reset ();\n      Mp_preconditioner.reset ();\n      darcy_preconditioner_matrix.clear ();\n\n      BlockCompressedSimpleSparsityPattern csp (2,2);\n\n      csp.block(0,0).reinit (n_u, n_u);\n      csp.block(0,1).reinit (n_u, n_p);\n      csp.block(1,0).reinit (n_p, n_u);\n      csp.block(1,1).reinit (n_p, n_p);\n\n      csp.collect_sizes ();\n\n      Table<2,DoFTools::Coupling> coupling (dim+1, dim+1);\n      for (unsigned int c=0; c<dim+1; ++c)\n        for (unsigned int d=0; d<dim+1; ++d)\n          if (c == d)\n            coupling[c][d] = DoFTools::always;\n          else\n            coupling[c][d] = DoFTools::none;\n\n      DoFTools::make_sparsity_pattern (darcy_dof_handler, coupling, csp,\n                                       darcy_constraints, false);\n\n      darcy_preconditioner_matrix.reinit (csp);\n    }\n\n\n    {\n      saturation_matrix.clear ();\n\n      CompressedSimpleSparsityPattern csp (n_s, n_s);\n\n      DoFTools::make_sparsity_pattern (saturation_dof_handler, csp,\n                                       saturation_constraints, false);\n\n\n      saturation_matrix.reinit (csp);\n    }\n\n    darcy_solution.reinit (2);\n    darcy_solution.block(0).reinit (n_u);\n    darcy_solution.block(1).reinit (n_p);\n    darcy_solution.collect_sizes ();\n\n    last_computed_darcy_solution.reinit (2);\n    last_computed_darcy_solution.block(0).reinit (n_u);\n    last_computed_darcy_solution.block(1).reinit (n_p);\n    last_computed_darcy_solution.collect_sizes ();\n\n    second_last_computed_darcy_solution.reinit (2);\n    second_last_computed_darcy_solution.block(0).reinit (n_u);\n    second_last_computed_darcy_solution.block(1).reinit (n_p);\n    second_last_computed_darcy_solution.collect_sizes ();\n\n    darcy_rhs.reinit (2);\n    darcy_rhs.block(0).reinit (n_u);\n    darcy_rhs.block(1).reinit (n_p);\n    darcy_rhs.collect_sizes ();\n\n    saturation_solution.reinit (n_s);\n    old_saturation_solution.reinit (n_s);\n    old_old_saturation_solution.reinit (n_s);\n\n    saturation_matching_last_computed_darcy_solution.reinit (n_s);\n\n    saturation_rhs.reinit (n_s);\n  }\n\n\n  // @sect3{Assembling matrices and preconditioners}\n\n  // The next few functions are devoted to setting up the various system and\n  // preconditioner matrices and right hand sides that we have to deal with in\n  // this program.\n\n  // @sect4{TwoPhaseFlowProblem<dim>::assemble_darcy_preconditioner}\n\n  // This function assembles the matrix we use for preconditioning the Darcy\n  // system. What we need are a vector mass matrix weighted by\n  // $\\left(\\mathbf{K} \\lambda_t\\right)^{-1}$ on the velocity components and a\n  // mass matrix weighted by $\\left(\\mathbf{K} \\lambda_t\\right)$ on the\n  // pressure component. We start by generating a quadrature object of\n  // appropriate order, the FEValues object that can give values and gradients\n  // at the quadrature points (together with quadrature weights). Next we\n  // create data structures for the cell matrix and the relation between local\n  // and global DoFs. The vectors phi_u and grad_phi_p are going to hold the\n  // values of the basis functions in order to faster build up the local\n  // matrices, as was already done in step-22. Before we start the loop over\n  // all active cells, we have to specify which components are pressure and\n  // which are velocity.\n  //\n  // The creation of the local matrix is rather simple. There are only a term\n  // weighted by $\\left(\\mathbf{K} \\lambda_t\\right)^{-1}$ (on the velocity)\n  // and a Laplace matrix weighted by $\\left(\\mathbf{K} \\lambda_t\\right)$ to\n  // be generated, so the creation of the local matrix is done in essentially\n  // two lines. Since the material model functions at the top of this file\n  // only provide the inverses of the permeability and mobility, we have to\n  // compute $\\mathbf K$ and $\\lambda_t$ by hand from the given values, once\n  // per quadrature point.\n  //\n  // Once the local matrix is ready (loop over rows and columns in the local\n  // matrix on each quadrature point), we get the local DoF indices and write\n  // the local information into the global matrix. We do this by directly\n  // applying the constraints (i.e. darcy_preconditioner_constraints) that\n  // takes care of hanging node and zero Dirichlet boundary condition\n  // constraints. By doing so, we don't have to do that afterwards, and we\n  // later don't have to use ConstraintMatrix::condense and\n  // MatrixTools::apply_boundary_values, both functions that would need to\n  // modify matrix and vector entries and so are difficult to write for the\n  // Trilinos classes where we don't immediately have access to individual\n  // memory locations.\n  template <int dim>\n  void\n  TwoPhaseFlowProblem<dim>::assemble_darcy_preconditioner ()\n  {\n    std::cout << \"   Rebuilding darcy preconditioner...\" << std::endl;\n\n    darcy_preconditioner_matrix = 0;\n\n    const QGauss<dim> quadrature_formula(darcy_degree+2);\n    FEValues<dim>     darcy_fe_values (darcy_fe, quadrature_formula,\n                                       update_JxW_values |\n                                       update_values |\n                                       update_gradients |\n                                       update_quadrature_points);\n    FEValues<dim> saturation_fe_values (saturation_fe, quadrature_formula,\n                                        update_values);\n\n    const unsigned int   dofs_per_cell   = darcy_fe.dofs_per_cell;\n    const unsigned int   n_q_points      = quadrature_formula.size();\n\n    std::vector<Tensor<2,dim> >       k_inverse_values (n_q_points);\n\n    std::vector<double>               old_saturation_values (n_q_points);\n\n    FullMatrix<double>                local_matrix (dofs_per_cell, dofs_per_cell);\n    std::vector<unsigned int>         local_dof_indices (dofs_per_cell);\n\n    std::vector<Tensor<1,dim> > phi_u   (dofs_per_cell);\n    std::vector<Tensor<1,dim> > grad_phi_p (dofs_per_cell);\n\n    const FEValuesExtractors::Vector velocities (0);\n    const FEValuesExtractors::Scalar pressure (dim);\n\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = darcy_dof_handler.begin_active(),\n    endc = darcy_dof_handler.end();\n    typename DoFHandler<dim>::active_cell_iterator\n    saturation_cell = saturation_dof_handler.begin_active();\n\n    for (; cell!=endc; ++cell, ++saturation_cell)\n      {\n        darcy_fe_values.reinit (cell);\n        saturation_fe_values.reinit (saturation_cell);\n\n        local_matrix = 0;\n\n        saturation_fe_values.get_function_values (old_saturation_solution, old_saturation_values);\n\n        k_inverse.value_list (darcy_fe_values.get_quadrature_points(),\n                              k_inverse_values);\n\n        for (unsigned int q=0; q<n_q_points; ++q)\n          {\n            const double old_s = old_saturation_values[q];\n\n            const double        inverse_mobility = mobility_inverse(old_s,viscosity);\n            const double        mobility         = 1.0 / inverse_mobility;\n            const Tensor<2,dim> permeability     = invert(k_inverse_values[q]);\n\n            for (unsigned int k=0; k<dofs_per_cell; ++k)\n              {\n                phi_u[k]       = darcy_fe_values[velocities].value (k,q);\n                grad_phi_p[k]  = darcy_fe_values[pressure].gradient (k,q);\n              }\n\n            for (unsigned int i=0; i<dofs_per_cell; ++i)\n              for (unsigned int j=0; j<dofs_per_cell; ++j)\n                {\n                  local_matrix(i,j) += (k_inverse_values[q] * inverse_mobility *\n                                        phi_u[i] * phi_u[j]\n                                        +\n                                        permeability * mobility *\n                                        grad_phi_p[i] * grad_phi_p[j])\n                                       * darcy_fe_values.JxW(q);\n                }\n          }\n\n        cell->get_dof_indices (local_dof_indices);\n        darcy_preconditioner_constraints.distribute_local_to_global (local_matrix,\n            local_dof_indices,\n            darcy_preconditioner_matrix);\n      }\n  }\n\n\n  // @sect4{TwoPhaseFlowProblem<dim>::build_darcy_preconditioner}\n\n  // After calling the above functions to assemble the preconditioner matrix,\n  // this function generates the inner preconditioners that are going to be\n  // used for the Schur complement block preconditioner. The preconditioners\n  // need to be regenerated at every saturation time step since they depend on\n  // the saturation $S$ that varies with time.\n  //\n  // In here, we set up the preconditioner for the velocity-velocity matrix\n  // $\\mathbf{M}^{\\mathbf{u}}$ and the Schur complement $\\mathbf{S}$. As\n  // explained in the introduction, we are going to use an IC preconditioner\n  // based on the vector matrix $\\mathbf{M}^{\\mathbf{u}}$ and another based on\n  // the scalar Laplace matrix $\\tilde{\\mathbf{S}}^p$ (which is spectrally\n  // close to the Schur complement of the Darcy matrix). Usually, the\n  // TrilinosWrappers::PreconditionIC class can be seen as a good black-box\n  // preconditioner which does not need any special knowledge of the matrix\n  // structure and/or the operator that's behind it.\n  template <int dim>\n  void\n  TwoPhaseFlowProblem<dim>::build_darcy_preconditioner ()\n  {\n    assemble_darcy_preconditioner ();\n\n    Amg_preconditioner = std_cxx1x::shared_ptr<TrilinosWrappers::PreconditionIC>\n                         (new TrilinosWrappers::PreconditionIC());\n    Amg_preconditioner->initialize(darcy_preconditioner_matrix.block(0,0));\n\n    Mp_preconditioner = std_cxx1x::shared_ptr<TrilinosWrappers::PreconditionIC>\n                        (new TrilinosWrappers::PreconditionIC());\n    Mp_preconditioner->initialize(darcy_preconditioner_matrix.block(1,1));\n\n  }\n\n\n  // @sect4{TwoPhaseFlowProblem<dim>::assemble_darcy_system}\n\n  // This is the function that assembles the linear system for the Darcy\n  // system.\n  //\n  // Regarding the technical details of implementation, the procedures are\n  // similar to those in step-22 and step-31. We reset matrix and vector,\n  // create a quadrature formula on the cells, and then create the respective\n  // FEValues object.\n  //\n  // There is one thing that needs to be commented: since we have a separate\n  // finite element and DoFHandler for the saturation, we need to generate a\n  // second FEValues object for the proper evaluation of the saturation\n  // solution. This isn't too complicated to realize here: just use the\n  // saturation structures and set an update flag for the basis function\n  // values which we need for evaluation of the saturation solution. The only\n  // important part to remember here is that the same quadrature formula is\n  // used for both FEValues objects to ensure that we get matching information\n  // when we loop over the quadrature points of the two objects.\n  //\n  // The declarations proceed with some shortcuts for array sizes, the\n  // creation of the local matrix, right hand side as well as the vector for\n  // the indices of the local dofs compared to the global system.\n  template <int dim>\n  void TwoPhaseFlowProblem<dim>::assemble_darcy_system ()\n  {\n    darcy_matrix = 0;\n    darcy_rhs    = 0;\n\n    QGauss<dim>   quadrature_formula(darcy_degree+2);\n    QGauss<dim-1> face_quadrature_formula(darcy_degree+2);\n\n    FEValues<dim> darcy_fe_values (darcy_fe, quadrature_formula,\n                                   update_values    | update_gradients |\n                                   update_quadrature_points  | update_JxW_values);\n\n    FEValues<dim> saturation_fe_values (saturation_fe, quadrature_formula,\n                                        update_values);\n\n    FEFaceValues<dim> darcy_fe_face_values (darcy_fe, face_quadrature_formula,\n                                            update_values    | update_normal_vectors |\n                                            update_quadrature_points  | update_JxW_values);\n\n    const unsigned int   dofs_per_cell   = darcy_fe.dofs_per_cell;\n\n    const unsigned int   n_q_points      = quadrature_formula.size();\n    const unsigned int   n_face_q_points = face_quadrature_formula.size();\n\n    FullMatrix<double>   local_matrix (dofs_per_cell, dofs_per_cell);\n    Vector<double>       local_rhs (dofs_per_cell);\n\n    std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\n    const PressureRightHandSide<dim>  pressure_right_hand_side;\n    const PressureBoundaryValues<dim> pressure_boundary_values;\n\n    std::vector<double>               pressure_rhs_values (n_q_points);\n    std::vector<double>               boundary_values (n_face_q_points);\n    std::vector<Tensor<2,dim> >       k_inverse_values (n_q_points);\n\n    // Next we need a vector that will contain the values of the saturation\n    // solution at the previous time level at the quadrature points to\n    // assemble the saturation dependent coefficients in the Darcy equations.\n    //\n    // The set of vectors we create next hold the evaluations of the basis\n    // functions as well as their gradients that will be used for creating the\n    // matrices. Putting these into their own arrays rather than asking the\n    // FEValues object for this information each time it is needed is an\n    // optimization to accelerate the assembly process, see step-22 for\n    // details.\n    //\n    // The last two declarations are used to extract the individual blocks\n    // (velocity, pressure, saturation) from the total FE system.\n    std::vector<double>               old_saturation_values (n_q_points);\n\n    std::vector<Tensor<1,dim> >       phi_u (dofs_per_cell);\n    std::vector<double>               div_phi_u (dofs_per_cell);\n    std::vector<double>               phi_p (dofs_per_cell);\n\n    const FEValuesExtractors::Vector  velocities (0);\n    const FEValuesExtractors::Scalar  pressure (dim);\n\n    // Now start the loop over all cells in the problem. We are working on two\n    // different DoFHandlers for this assembly routine, so we must have two\n    // different cell iterators for the two objects in use. This might seem a\n    // bit peculiar, but since both the Darcy system and the saturation system\n    // use the same grid we can assume that the two iterators run in sync over\n    // the cells of the two DoFHandler objects.\n    //\n    // The first statements within the loop are again all very familiar, doing\n    // the update of the finite element data as specified by the update flags,\n    // zeroing out the local arrays and getting the values of the old solution\n    // at the quadrature points.  At this point we also have to get the values\n    // of the saturation function of the previous time step at the quadrature\n    // points. To this end, we can use the FEValues::get_function_values\n    // (previously already used in step-9, step-14 and step-15), a function\n    // that takes a solution vector and returns a list of function values at\n    // the quadrature points of the present cell. In fact, it returns the\n    // complete vector-valued solution at each quadrature point, i.e. not only\n    // the saturation but also the velocities and pressure.\n    //\n    // Then we are ready to loop over the quadrature points on the cell to do\n    // the integration. The formula for this follows in a straightforward way\n    // from what has been discussed in the introduction.\n    //\n    // Once this is done, we start the loop over the rows and columns of the\n    // local matrix and feed the matrix with the relevant products.\n    //\n    // The last step in the loop over all cells is to enter the local\n    // contributions into the global matrix and vector structures to the\n    // positions specified in local_dof_indices. Again, we let the\n    // ConstraintMatrix class do the insertion of the cell matrix elements to\n    // the global matrix, which already condenses the hanging node\n    // constraints.\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = darcy_dof_handler.begin_active(),\n    endc = darcy_dof_handler.end();\n    typename DoFHandler<dim>::active_cell_iterator\n    saturation_cell = saturation_dof_handler.begin_active();\n\n    for (; cell!=endc; ++cell, ++saturation_cell)\n      {\n        darcy_fe_values.reinit (cell);\n        saturation_fe_values.reinit (saturation_cell);\n\n        local_matrix = 0;\n        local_rhs = 0;\n\n        saturation_fe_values.get_function_values (old_saturation_solution, old_saturation_values);\n\n        pressure_right_hand_side.value_list (darcy_fe_values.get_quadrature_points(),\n                                             pressure_rhs_values);\n        k_inverse.value_list (darcy_fe_values.get_quadrature_points(),\n                              k_inverse_values);\n\n        for (unsigned int q=0; q<n_q_points; ++q)\n          {\n            for (unsigned int k=0; k<dofs_per_cell; ++k)\n              {\n                phi_u[k]     = darcy_fe_values[velocities].value (k,q);\n                div_phi_u[k] = darcy_fe_values[velocities].divergence (k,q);\n                phi_p[k]     = darcy_fe_values[pressure].value (k,q);\n              }\n            for (unsigned int i=0; i<dofs_per_cell; ++i)\n              {\n                const double old_s = old_saturation_values[q];\n                for (unsigned int j=0; j<=i; ++j)\n                  {\n                    local_matrix(i,j) += (phi_u[i] * k_inverse_values[q] *\n                                          mobility_inverse(old_s,viscosity) * phi_u[j]\n                                          - div_phi_u[i] * phi_p[j]\n                                          - phi_p[i] * div_phi_u[j])\n                                         * darcy_fe_values.JxW(q);\n                  }\n\n                local_rhs(i) += (-phi_p[i] * pressure_rhs_values[q])*\n                                darcy_fe_values.JxW(q);\n              }\n          }\n\n        for (unsigned int face_no=0;\n             face_no<GeometryInfo<dim>::faces_per_cell;\n             ++face_no)\n          if (cell->at_boundary(face_no))\n            {\n              darcy_fe_face_values.reinit (cell, face_no);\n\n              pressure_boundary_values\n              .value_list (darcy_fe_face_values.get_quadrature_points(),\n                           boundary_values);\n\n              for (unsigned int q=0; q<n_face_q_points; ++q)\n                for (unsigned int i=0; i<dofs_per_cell; ++i)\n                  {\n                    const Tensor<1,dim>\n                    phi_i_u = darcy_fe_face_values[velocities].value (i, q);\n\n                    local_rhs(i) += -(phi_i_u *\n                                      darcy_fe_face_values.normal_vector(q) *\n                                      boundary_values[q] *\n                                      darcy_fe_face_values.JxW(q));\n                  }\n            }\n\n        for (unsigned int i=0; i<dofs_per_cell; ++i)\n          for (unsigned int j=i+1; j<dofs_per_cell; ++j)\n            local_matrix(i,j) = local_matrix(j,i);\n\n        cell->get_dof_indices (local_dof_indices);\n\n        darcy_constraints.distribute_local_to_global (local_matrix,\n                                                      local_rhs,\n                                                      local_dof_indices,\n                                                      darcy_matrix,\n                                                      darcy_rhs);\n\n      }\n  }\n\n\n  // @sect4{TwoPhaseFlowProblem<dim>::assemble_saturation_system}\n\n  // This function is to assemble the linear system for the saturation\n  // transport equation. It calls, if necessary, two other member functions:\n  // assemble_saturation_matrix() and assemble_saturation_rhs(). The former\n  // function then assembles the saturation matrix that only needs to be\n  // changed occasionally. On the other hand, the latter function that\n  // assembles the right hand side must be called at every saturation time\n  // step.\n  template <int dim>\n  void TwoPhaseFlowProblem<dim>::assemble_saturation_system ()\n  {\n    if (rebuild_saturation_matrix == true)\n      {\n        saturation_matrix = 0;\n        assemble_saturation_matrix ();\n      }\n\n    saturation_rhs = 0;\n    assemble_saturation_rhs ();\n  }\n\n\n\n  // @sect4{TwoPhaseFlowProblem<dim>::assemble_saturation_matrix}\n\n  // This function is easily understood since it only forms a simple mass\n  // matrix for the left hand side of the saturation linear system by basis\n  // functions phi_i_s and phi_j_s only. Finally, as usual, we enter the local\n  // contribution into the global matrix by specifying the position in\n  // local_dof_indices. This is done by letting the ConstraintMatrix class do\n  // the insertion of the cell matrix elements to the global matrix, which\n  // already condenses the hanging node constraints.\n  template <int dim>\n  void TwoPhaseFlowProblem<dim>::assemble_saturation_matrix ()\n  {\n    QGauss<dim> quadrature_formula(saturation_degree+2);\n\n    FEValues<dim> saturation_fe_values (saturation_fe, quadrature_formula,\n                                        update_values | update_JxW_values);\n\n    const unsigned int dofs_per_cell = saturation_fe.dofs_per_cell;\n\n    const unsigned int n_q_points = quadrature_formula.size();\n\n    FullMatrix<double>   local_matrix (dofs_per_cell, dofs_per_cell);\n    Vector<double>       local_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 = saturation_dof_handler.begin_active(),\n    endc = saturation_dof_handler.end();\n    for (; cell!=endc; ++cell)\n      {\n        saturation_fe_values.reinit (cell);\n        local_matrix = 0;\n        local_rhs    = 0;\n\n        for (unsigned int q=0; q<n_q_points; ++q)\n          for (unsigned int i=0; i<dofs_per_cell; ++i)\n            {\n              const double phi_i_s = saturation_fe_values.shape_value (i,q);\n              for (unsigned int j=0; j<dofs_per_cell; ++j)\n                {\n                  const double phi_j_s = saturation_fe_values.shape_value (j,q);\n                  local_matrix(i,j) += porosity * phi_i_s * phi_j_s * saturation_fe_values.JxW(q);\n                }\n            }\n        cell->get_dof_indices (local_dof_indices);\n\n        saturation_constraints.distribute_local_to_global (local_matrix,\n                                                           local_dof_indices,\n                                                           saturation_matrix);\n\n      }\n  }\n\n\n\n  // @sect4{TwoPhaseFlowProblem<dim>::assemble_saturation_rhs}\n\n  // This function is to assemble the right hand side of the saturation\n  // transport equation. Before going about it, we have to create two FEValues\n  // objects for the Darcy and saturation systems respectively and, in\n  // addition, two FEFaceValues objects for the two systems because we have a\n  // boundary integral term in the weak form of saturation equation. For the\n  // FEFaceValues object of the saturation system, we also require normal\n  // vectors, which we request using the update_normal_vectors flag.\n  //\n  // Next, before looping over all the cells, we have to compute some\n  // parameters (e.g. global_u_infty, global_S_variation, and\n  // global_Omega_diameter) that the artificial viscosity $\\nu$ needs. This is\n  // largely the same as was done in step-31, so you may see there for more\n  // information.\n  //\n  // The real works starts with the loop over all the saturation and Darcy\n  // cells to put the local contributions into the global vector. In this\n  // loop, in order to simplify the implementation, we split some of the work\n  // into two helper functions: assemble_saturation_rhs_cell_term and\n  // assemble_saturation_rhs_boundary_term.  We note that we insert cell or\n  // boundary contributions into the global vector in the two functions rather\n  // than in this present function.\n  template <int dim>\n  void TwoPhaseFlowProblem<dim>::assemble_saturation_rhs ()\n  {\n    QGauss<dim>   quadrature_formula(saturation_degree+2);\n    QGauss<dim-1> face_quadrature_formula(saturation_degree+2);\n\n    FEValues<dim> saturation_fe_values                   (saturation_fe, quadrature_formula,\n                                                          update_values    | update_gradients |\n                                                          update_quadrature_points  | update_JxW_values);\n    FEValues<dim> darcy_fe_values                        (darcy_fe, quadrature_formula,\n                                                          update_values);\n    FEFaceValues<dim> saturation_fe_face_values          (saturation_fe, face_quadrature_formula,\n                                                          update_values    | update_normal_vectors |\n                                                          update_quadrature_points  | update_JxW_values);\n    FEFaceValues<dim> darcy_fe_face_values               (darcy_fe, face_quadrature_formula,\n                                                          update_values);\n    FEFaceValues<dim> saturation_fe_face_values_neighbor (saturation_fe, face_quadrature_formula,\n                                                          update_values);\n\n    const unsigned int dofs_per_cell = saturation_dof_handler.get_fe().dofs_per_cell;\n    std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\n    const double                   global_max_u_F_prime = get_max_u_F_prime ();\n    const std::pair<double,double> global_S_range       = get_extrapolated_saturation_range ();\n    const double                   global_S_variation   = global_S_range.second - global_S_range.first;\n\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = saturation_dof_handler.begin_active(),\n    endc = saturation_dof_handler.end();\n    typename DoFHandler<dim>::active_cell_iterator\n    darcy_cell = darcy_dof_handler.begin_active();\n    for (; cell!=endc; ++cell, ++darcy_cell)\n      {\n        saturation_fe_values.reinit (cell);\n        darcy_fe_values.reinit (darcy_cell);\n\n        cell->get_dof_indices (local_dof_indices);\n\n        assemble_saturation_rhs_cell_term (saturation_fe_values,\n                                           darcy_fe_values,\n                                           global_max_u_F_prime,\n                                           global_S_variation,\n                                           local_dof_indices);\n\n        for (unsigned int face_no=0; face_no<GeometryInfo<dim>::faces_per_cell;\n             ++face_no)\n          if (cell->at_boundary(face_no))\n            {\n              darcy_fe_face_values.reinit (darcy_cell, face_no);\n              saturation_fe_face_values.reinit (cell, face_no);\n              assemble_saturation_rhs_boundary_term (saturation_fe_face_values,\n                                                     darcy_fe_face_values,\n                                                     local_dof_indices);\n            }\n      }\n  }\n\n\n\n  // @sect4{TwoPhaseFlowProblem<dim>::assemble_saturation_rhs_cell_term}\n\n  // This function takes care of integrating the cell terms of the right hand\n  // side of the saturation equation, and then assembling it into the global\n  // right hand side vector. Given the discussion in the introduction, the\n  // form of these contributions is clear. The only tricky part is getting the\n  // artificial viscosity and all that is necessary to compute it. The first\n  // half of the function is devoted to this task.\n  //\n  // The last part of the function is copying the local contributions into the\n  // global vector with position specified in local_dof_indices.\n  template <int dim>\n  void\n  TwoPhaseFlowProblem<dim>::\n  assemble_saturation_rhs_cell_term (const FEValues<dim>             &saturation_fe_values,\n                                     const FEValues<dim>             &darcy_fe_values,\n                                     const double                     global_max_u_F_prime,\n                                     const double                     global_S_variation,\n                                     const std::vector<unsigned int> &local_dof_indices)\n  {\n    const unsigned int dofs_per_cell = saturation_fe_values.dofs_per_cell;\n    const unsigned int n_q_points    = saturation_fe_values.n_quadrature_points;\n\n    std::vector<double>          old_saturation_solution_values(n_q_points);\n    std::vector<double>          old_old_saturation_solution_values(n_q_points);\n    std::vector<Tensor<1,dim> >  old_grad_saturation_solution_values(n_q_points);\n    std::vector<Tensor<1,dim> >  old_old_grad_saturation_solution_values(n_q_points);\n    std::vector<Vector<double> > present_darcy_solution_values(n_q_points, Vector<double>(dim+1));\n\n    saturation_fe_values.get_function_values (old_saturation_solution, old_saturation_solution_values);\n    saturation_fe_values.get_function_values (old_old_saturation_solution, old_old_saturation_solution_values);\n    saturation_fe_values.get_function_grads (old_saturation_solution, old_grad_saturation_solution_values);\n    saturation_fe_values.get_function_grads (old_old_saturation_solution, old_old_grad_saturation_solution_values);\n    darcy_fe_values.get_function_values (darcy_solution, present_darcy_solution_values);\n\n    const double nu\n      = compute_viscosity (old_saturation_solution_values,\n                           old_old_saturation_solution_values,\n                           old_grad_saturation_solution_values,\n                           old_old_grad_saturation_solution_values,\n                           present_darcy_solution_values,\n                           global_max_u_F_prime,\n                           global_S_variation,\n                           saturation_fe_values.get_cell()->diameter());\n\n    Vector<double> local_rhs (dofs_per_cell);\n\n    for (unsigned int q=0; q<n_q_points; ++q)\n      for (unsigned int i=0; i<dofs_per_cell; ++i)\n        {\n          const double old_s = old_saturation_solution_values[q];\n          Tensor<1,dim> present_u;\n          for (unsigned int d=0; d<dim; ++d)\n            present_u[d] = present_darcy_solution_values[q](d);\n\n          const double        phi_i_s      = saturation_fe_values.shape_value (i, q);\n          const Tensor<1,dim> grad_phi_i_s = saturation_fe_values.shape_grad (i, q);\n\n          local_rhs(i) += (time_step *\n                           fractional_flow(old_s,viscosity) *\n                           present_u *\n                           grad_phi_i_s\n                           -\n                           time_step *\n                           nu *\n                           old_grad_saturation_solution_values[q] * grad_phi_i_s\n                           +\n                           porosity * old_s * phi_i_s)\n                          *\n                          saturation_fe_values.JxW(q);\n        }\n\n    saturation_constraints.distribute_local_to_global (local_rhs,\n                                                       local_dof_indices,\n                                                       saturation_rhs);\n  }\n\n\n  // @sect4{TwoPhaseFlowProblem<dim>::assemble_saturation_rhs_boundary_term}\n\n  // The next function is responsible for the boundary integral terms in the\n  // right hand side form of the saturation equation.  For these, we have to\n  // compute the upwinding flux on the global boundary faces, i.e. we impose\n  // Dirichlet boundary conditions weakly only on inflow parts of the global\n  // boundary. As before, this has been described in step-21 so we refrain\n  // from giving more descriptions about that.\n  template <int dim>\n  void\n  TwoPhaseFlowProblem<dim>::\n  assemble_saturation_rhs_boundary_term (const FEFaceValues<dim>             &saturation_fe_face_values,\n                                         const FEFaceValues<dim>             &darcy_fe_face_values,\n                                         const std::vector<unsigned int>     &local_dof_indices)\n  {\n    const unsigned int dofs_per_cell      = saturation_fe_face_values.dofs_per_cell;\n    const unsigned int n_face_q_points    = saturation_fe_face_values.n_quadrature_points;\n\n    Vector<double> local_rhs (dofs_per_cell);\n\n    std::vector<double>          old_saturation_solution_values_face(n_face_q_points);\n    std::vector<Vector<double> > present_darcy_solution_values_face(n_face_q_points,\n        Vector<double>(dim+1));\n    std::vector<double>          neighbor_saturation (n_face_q_points);\n\n    saturation_fe_face_values.get_function_values (old_saturation_solution,\n                                                   old_saturation_solution_values_face);\n    darcy_fe_face_values.get_function_values (darcy_solution,\n                                              present_darcy_solution_values_face);\n\n    SaturationBoundaryValues<dim> saturation_boundary_values;\n    saturation_boundary_values\n    .value_list (saturation_fe_face_values.get_quadrature_points(),\n                 neighbor_saturation);\n\n    for (unsigned int q=0; q<n_face_q_points; ++q)\n      {\n        Tensor<1,dim> present_u_face;\n        for (unsigned int d=0; d<dim; ++d)\n          present_u_face[d] = present_darcy_solution_values_face[q](d);\n\n        const double normal_flux = present_u_face *\n                                   saturation_fe_face_values.normal_vector(q);\n\n        const bool is_outflow_q_point = (normal_flux >= 0);\n\n        for (unsigned int i=0; i<dofs_per_cell; ++i)\n          local_rhs(i) -= time_step *\n                          normal_flux *\n                          fractional_flow((is_outflow_q_point == true\n                                           ?\n                                           old_saturation_solution_values_face[q]\n                                           :\n                                           neighbor_saturation[q]),\n                                          viscosity) *\n                          saturation_fe_face_values.shape_value (i,q) *\n                          saturation_fe_face_values.JxW(q);\n      }\n    saturation_constraints.distribute_local_to_global (local_rhs,\n                                                       local_dof_indices,\n                                                       saturation_rhs);\n  }\n\n\n  // @sect3{TwoPhaseFlowProblem<dim>::solve}\n\n  // This function implements the operator splitting algorithm, i.e. in each\n  // time step it either re-computes the solution of the Darcy system or\n  // extrapolates velocity/pressure from previous time steps, then determines\n  // the size of the time step, and then updates the saturation variable. The\n  // implementation largely follows similar code in step-31. It is, next to\n  // the run() function, the central one in this program.\n  //\n  // At the beginning of the function, we ask whether to solve the\n  // pressure-velocity part by evaluating the posteriori criterion (see the\n  // following function). If necessary, we will solve the pressure-velocity\n  // part using the GMRES solver with the Schur complement block\n  // preconditioner as is described in the introduction.\n  template <int dim>\n  void TwoPhaseFlowProblem<dim>::solve ()\n  {\n    const bool\n    solve_for_pressure_and_velocity = determine_whether_to_solve_for_pressure_and_velocity ();\n\n    if (solve_for_pressure_and_velocity == true)\n      {\n        std::cout << \"   Solving Darcy (pressure-velocity) system...\" << std::endl;\n\n        assemble_darcy_system ();\n        build_darcy_preconditioner ();\n\n        {\n          const LinearSolvers::InverseMatrix<TrilinosWrappers::SparseMatrix,\n                TrilinosWrappers::PreconditionIC>\n                mp_inverse (darcy_preconditioner_matrix.block(1,1), *Mp_preconditioner);\n\n          const LinearSolvers::BlockSchurPreconditioner<TrilinosWrappers::PreconditionIC,\n                TrilinosWrappers::PreconditionIC>\n                preconditioner (darcy_matrix, mp_inverse, *Amg_preconditioner);\n\n          SolverControl solver_control (darcy_matrix.m(),\n                                        1e-16*darcy_rhs.l2_norm());\n\n          SolverGMRES<TrilinosWrappers::BlockVector>\n          gmres (solver_control,\n                 SolverGMRES<TrilinosWrappers::BlockVector >::AdditionalData(100));\n\n          for (unsigned int i=0; i<darcy_solution.size(); ++i)\n            if (darcy_constraints.is_constrained(i))\n              darcy_solution(i) = 0;\n\n          gmres.solve(darcy_matrix, darcy_solution, darcy_rhs, preconditioner);\n\n          darcy_constraints.distribute (darcy_solution);\n\n          std::cout << \"        ...\"\n                    << solver_control.last_step()\n                    << \" GMRES iterations.\"\n                    << std::endl;\n        }\n\n        {\n          second_last_computed_darcy_solution              = last_computed_darcy_solution;\n          last_computed_darcy_solution                     = darcy_solution;\n\n          saturation_matching_last_computed_darcy_solution = saturation_solution;\n        }\n      }\n    // On the other hand, if we have decided that we don't want to compute the\n    // solution of the Darcy system for the current time step, then we need to\n    // simply extrapolate the previous two Darcy solutions to the same time as\n    // we would have computed the velocity/pressure at. We do a simple linear\n    // extrapolation, i.e. given the current length $dt$ of the macro time\n    // step from the time when we last computed the Darcy solution to now\n    // (given by <code>current_macro_time_step</code>), and $DT$ the length of\n    // the last macro time step (given by <code>old_macro_time_step</code>),\n    // then we get $u^\\ast = u_p + dt \\frac{u_p-u_{pp}}{DT} = (1+dt/DT)u_p -\n    // dt/DT u_{pp}$, where $u_p$ and $u_{pp}$ are the last two computed Darcy\n    // solutions. We can implement this formula using just two lines of code.\n    //\n    // Note that the algorithm here only works if we have at least two\n    // previously computed Darcy solutions from which we can extrapolate to\n    // the current time, and this is ensured by requiring re-computation of\n    // the Darcy solution for the first 2 time steps.\n    else\n      {\n        darcy_solution = last_computed_darcy_solution;\n        darcy_solution.sadd (1 + current_macro_time_step / old_macro_time_step,\n                             -current_macro_time_step / old_macro_time_step,\n                             second_last_computed_darcy_solution);\n      }\n\n\n    // With the so computed velocity vector, compute the optimal time step\n    // based on the CFL criterion discussed in the introduction...\n    {\n      old_time_step = time_step;\n\n      const double max_u_F_prime = get_max_u_F_prime();\n      if (max_u_F_prime > 0)\n        time_step = porosity *\n                    GridTools::minimal_cell_diameter(triangulation) /\n                    saturation_degree /\n                    max_u_F_prime / 50;\n      else\n        time_step = end_time - time;\n    }\n\n\n\n    // ...and then also update the length of the macro time steps we use while\n    // we're dealing with time step sizes. In particular, this involves: (i)\n    // If we have just recomputed the Darcy solution, then the length of the\n    // previous macro time step is now fixed and the length of the current\n    // macro time step is, up to now, simply the length of the current (micro)\n    // time step. (ii) If we have not recomputed the Darcy solution, then the\n    // length of the current macro time step has just grown by\n    // <code>time_step</code>.\n    if (solve_for_pressure_and_velocity == true)\n      {\n        old_macro_time_step     = current_macro_time_step;\n        current_macro_time_step = time_step;\n      }\n    else\n      current_macro_time_step += time_step;\n\n    // The last step in this function is to recompute the saturation solution\n    // based on the velocity field we've just obtained. This naturally happens\n    // in every time step, and we don't skip any of these computations. At the\n    // end of computing the saturation, we project back into the allowed\n    // interval $[0,1]$ to make sure our solution remains physical.\n    {\n      std::cout << \"   Solving saturation transport equation...\" << std::endl;\n\n      assemble_saturation_system ();\n\n      SolverControl solver_control (saturation_matrix.m(),\n                                    1e-16*saturation_rhs.l2_norm());\n      SolverCG<TrilinosWrappers::Vector> cg (solver_control);\n\n      TrilinosWrappers::PreconditionIC preconditioner;\n      preconditioner.initialize (saturation_matrix);\n\n      cg.solve (saturation_matrix, saturation_solution,\n                saturation_rhs, preconditioner);\n\n      saturation_constraints.distribute (saturation_solution);\n      project_back_saturation ();\n\n      std::cout << \"        ...\"\n                << solver_control.last_step()\n                << \" CG iterations.\"\n                << std::endl;\n    }\n  }\n\n\n  // @sect3{TwoPhaseFlowProblem<dim>::refine_mesh}\n\n  // The next function does the refinement and coarsening of the mesh. It does\n  // its work in three blocks: (i) Compute refinement indicators by looking at\n  // the gradient of a solution vector extrapolated linearly from the previous\n  // two using the respective sizes of the time step (or taking the only\n  // solution we have if this is the first time step). (ii) Flagging those\n  // cells for refinement and coarsening where the gradient is larger or\n  // smaller than a certain threshold, preserving minimal and maximal levels\n  // of mesh refinement. (iii) Transferring the solution from the old to the\n  // new mesh. None of this is particularly difficult.\n  template <int dim>\n  void\n  TwoPhaseFlowProblem<dim>::\n  refine_mesh (const unsigned int              min_grid_level,\n               const unsigned int              max_grid_level)\n  {\n    Vector<double> refinement_indicators (triangulation.n_active_cells());\n    {\n      const QMidpoint<dim> quadrature_formula;\n      FEValues<dim> fe_values (saturation_fe, quadrature_formula, update_gradients);\n      std::vector<Tensor<1,dim> > grad_saturation (1);\n\n      TrilinosWrappers::Vector extrapolated_saturation_solution (saturation_solution);\n      if (timestep_number != 0)\n        extrapolated_saturation_solution.sadd ((1. + time_step/old_time_step),\n                                               time_step/old_time_step, old_saturation_solution);\n\n      typename DoFHandler<dim>::active_cell_iterator\n      cell = saturation_dof_handler.begin_active(),\n      endc = saturation_dof_handler.end();\n      for (unsigned int cell_no=0; cell!=endc; ++cell, ++cell_no)\n        {\n          fe_values.reinit(cell);\n          fe_values.get_function_grads (extrapolated_saturation_solution,\n                                        grad_saturation);\n\n          refinement_indicators(cell_no) = grad_saturation[0].norm();\n        }\n    }\n\n    {\n      typename DoFHandler<dim>::active_cell_iterator\n      cell = saturation_dof_handler.begin_active(),\n      endc = saturation_dof_handler.end();\n\n      for (unsigned int cell_no=0; cell!=endc; ++cell, ++cell_no)\n        {\n          cell->clear_coarsen_flag();\n          cell->clear_refine_flag();\n\n          if ((static_cast<unsigned int>(cell->level()) < max_grid_level) &&\n              (std::fabs(refinement_indicators(cell_no)) > saturation_refinement_threshold))\n            cell->set_refine_flag();\n          else if ((static_cast<unsigned int>(cell->level()) > min_grid_level) &&\n                   (std::fabs(refinement_indicators(cell_no)) < 0.5 * saturation_refinement_threshold))\n            cell->set_coarsen_flag();\n        }\n    }\n\n    triangulation.prepare_coarsening_and_refinement ();\n\n    {\n      std::vector<TrilinosWrappers::Vector> x_saturation (3);\n      x_saturation[0] = saturation_solution;\n      x_saturation[1] = old_saturation_solution;\n      x_saturation[2] = saturation_matching_last_computed_darcy_solution;\n\n      std::vector<TrilinosWrappers::BlockVector> x_darcy (2);\n      x_darcy[0] = last_computed_darcy_solution;\n      x_darcy[1] = second_last_computed_darcy_solution;\n\n      SolutionTransfer<dim,TrilinosWrappers::Vector> saturation_soltrans(saturation_dof_handler);\n\n      SolutionTransfer<dim,TrilinosWrappers::BlockVector> darcy_soltrans(darcy_dof_handler);\n\n\n      triangulation.prepare_coarsening_and_refinement();\n      saturation_soltrans.prepare_for_coarsening_and_refinement(x_saturation);\n\n      darcy_soltrans.prepare_for_coarsening_and_refinement(x_darcy);\n\n      triangulation.execute_coarsening_and_refinement ();\n      setup_dofs ();\n\n      std::vector<TrilinosWrappers::Vector> tmp_saturation (3);\n      tmp_saturation[0].reinit (saturation_solution);\n      tmp_saturation[1].reinit (saturation_solution);\n      tmp_saturation[2].reinit (saturation_solution);\n      saturation_soltrans.interpolate(x_saturation, tmp_saturation);\n\n      saturation_solution = tmp_saturation[0];\n      old_saturation_solution = tmp_saturation[1];\n      saturation_matching_last_computed_darcy_solution = tmp_saturation[2];\n\n      std::vector<TrilinosWrappers::BlockVector> tmp_darcy (2);\n      tmp_darcy[0].reinit (darcy_solution);\n      tmp_darcy[1].reinit (darcy_solution);\n      darcy_soltrans.interpolate(x_darcy, tmp_darcy);\n\n      last_computed_darcy_solution        = tmp_darcy[0];\n      second_last_computed_darcy_solution = tmp_darcy[1];\n\n      rebuild_saturation_matrix    = true;\n    }\n  }\n\n\n\n  // @sect3{TwoPhaseFlowProblem<dim>::output_results}\n\n  // This function generates graphical output. It is in essence a copy of the\n  // implementation in step-31.\n  template <int dim>\n  void TwoPhaseFlowProblem<dim>::output_results ()  const\n  {\n    const FESystem<dim> joint_fe (darcy_fe, 1,\n                                  saturation_fe, 1);\n    DoFHandler<dim> joint_dof_handler (triangulation);\n    joint_dof_handler.distribute_dofs (joint_fe);\n    Assert (joint_dof_handler.n_dofs() ==\n            darcy_dof_handler.n_dofs() + saturation_dof_handler.n_dofs(),\n            ExcInternalError());\n\n    Vector<double> joint_solution (joint_dof_handler.n_dofs());\n\n    {\n      std::vector<unsigned int> local_joint_dof_indices (joint_fe.dofs_per_cell);\n      std::vector<unsigned int> local_darcy_dof_indices (darcy_fe.dofs_per_cell);\n      std::vector<unsigned int> local_saturation_dof_indices (saturation_fe.dofs_per_cell);\n\n      typename DoFHandler<dim>::active_cell_iterator\n      joint_cell      = joint_dof_handler.begin_active(),\n      joint_endc      = joint_dof_handler.end(),\n      darcy_cell      = darcy_dof_handler.begin_active(),\n      saturation_cell = saturation_dof_handler.begin_active();\n\n      for (; joint_cell!=joint_endc; ++joint_cell, ++darcy_cell, ++saturation_cell)\n        {\n          joint_cell->get_dof_indices (local_joint_dof_indices);\n          darcy_cell->get_dof_indices (local_darcy_dof_indices);\n          saturation_cell->get_dof_indices (local_saturation_dof_indices);\n\n          for (unsigned int i=0; i<joint_fe.dofs_per_cell; ++i)\n            if (joint_fe.system_to_base_index(i).first.first == 0)\n              {\n                Assert (joint_fe.system_to_base_index(i).second\n                        <\n                        local_darcy_dof_indices.size(),\n                        ExcInternalError());\n                joint_solution(local_joint_dof_indices[i])\n                  = darcy_solution(local_darcy_dof_indices[joint_fe.system_to_base_index(i).second]);\n              }\n            else\n              {\n                Assert (joint_fe.system_to_base_index(i).first.first == 1,\n                        ExcInternalError());\n                Assert (joint_fe.system_to_base_index(i).second\n                        <\n                        local_darcy_dof_indices.size(),\n                        ExcInternalError());\n                joint_solution(local_joint_dof_indices[i])\n                  = saturation_solution(local_saturation_dof_indices[joint_fe.system_to_base_index(i).second]);\n              }\n\n        }\n    }\n    std::vector<std::string> joint_solution_names (dim, \"velocity\");\n    joint_solution_names.push_back (\"pressure\");\n    joint_solution_names.push_back (\"saturation\");\n\n    std::vector<DataComponentInterpretation::DataComponentInterpretation>\n    data_component_interpretation\n    (dim, DataComponentInterpretation::component_is_part_of_vector);\n    data_component_interpretation\n    .push_back (DataComponentInterpretation::component_is_scalar);\n    data_component_interpretation\n    .push_back (DataComponentInterpretation::component_is_scalar);\n\n    DataOut<dim> data_out;\n\n    data_out.attach_dof_handler (joint_dof_handler);\n    data_out.add_data_vector (joint_solution, joint_solution_names,\n                              DataOut<dim>::type_dof_data,\n                              data_component_interpretation);\n\n    data_out.build_patches ();\n\n    std::string filename = \"solution-\" +\n                           Utilities::int_to_string (timestep_number, 5) + \".vtu\";\n    std::ofstream output (filename.c_str());\n    data_out.write_vtu (output);\n  }\n\n\n\n  // @sect3{Tool functions}\n\n  // @sect4{TwoPhaseFlowProblem<dim>::determine_whether_to_solve_for_pressure_and_velocity}\n\n  // This function implements the a posteriori criterion for adaptive operator\n  // splitting. The function is relatively straightforward given the way we\n  // have implemented other functions above and given the formula for the\n  // criterion derived in the paper.\n  //\n  // If one decides that one wants the original IMPES method in which the\n  // Darcy equation is solved in every time step, then this can be achieved by\n  // setting the threshold value <code>AOS_threshold</code> (with a default of\n  // $5.0$) to zero, thereby forcing the function to always return true.\n  //\n  // Finally, note that the function returns true unconditionally for the\n  // first two time steps to ensure that we have always solved the Darcy\n  // system at least twice when skipping its solution, thereby allowing us to\n  // extrapolate the velocity from the last two solutions in\n  // <code>solve()</code>.\n  template <int dim>\n  bool\n  TwoPhaseFlowProblem<dim>::determine_whether_to_solve_for_pressure_and_velocity () const\n  {\n    if (timestep_number <= 2)\n      return true;\n\n    const QGauss<dim>  quadrature_formula(saturation_degree+2);\n    const unsigned int n_q_points = quadrature_formula.size();\n\n    FEValues<dim> fe_values (saturation_fe, quadrature_formula,\n                             update_values | update_quadrature_points);\n\n    std::vector<double> old_saturation_after_solving_pressure (n_q_points);\n    std::vector<double> present_saturation (n_q_points);\n\n    std::vector<Tensor<2,dim> > k_inverse_values (n_q_points);\n\n    double max_global_aop_indicator = 0.0;\n\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = saturation_dof_handler.begin_active(),\n    endc = saturation_dof_handler.end();\n    for (; cell!=endc; ++cell)\n      {\n        double max_local_mobility_reciprocal_difference = 0.0;\n        double max_local_permeability_inverse_l1_norm = 0.0;\n\n        fe_values.reinit(cell);\n        fe_values.get_function_values (saturation_matching_last_computed_darcy_solution,\n                                       old_saturation_after_solving_pressure);\n        fe_values.get_function_values (saturation_solution,\n                                       present_saturation);\n\n        k_inverse.value_list (fe_values.get_quadrature_points(),\n                              k_inverse_values);\n\n        for (unsigned int q=0; q<n_q_points; ++q)\n          {\n            const double mobility_reciprocal_difference\n              = std::fabs(mobility_inverse(present_saturation[q],viscosity)\n                          -\n                          mobility_inverse(old_saturation_after_solving_pressure[q],viscosity));\n\n            max_local_mobility_reciprocal_difference = std::max(max_local_mobility_reciprocal_difference,\n                                                                mobility_reciprocal_difference);\n\n            max_local_permeability_inverse_l1_norm = std::max(max_local_permeability_inverse_l1_norm,\n                                                              l1_norm(k_inverse_values[q]));\n          }\n\n        max_global_aop_indicator = std::max(max_global_aop_indicator,\n                                            (max_local_mobility_reciprocal_difference *\n                                             max_local_permeability_inverse_l1_norm));\n      }\n\n    return (max_global_aop_indicator > AOS_threshold);\n  }\n\n\n\n  // @sect4{TwoPhaseFlowProblem<dim>::project_back_saturation}\n\n  // The next function simply makes sure that the saturation values always\n  // remain within the physically reasonable range of $[0,1]$. While the\n  // continuous equations guarantee that this is so, the discrete equations\n  // don't. However, if we allow the discrete solution to escape this range we\n  // get into trouble because terms like $F(S)$ and $F'(S)$ will produce\n  // unreasonable results (e.g. $F'(S)<0$ for $S<0$, which would imply that\n  // the wetting fluid phase flows <i>against</i> the direction of the bulk\n  // fluid velocity)). Consequently, at the end of each time step, we simply\n  // project the saturation field back into the physically reasonable region.\n  template <int dim>\n  void\n  TwoPhaseFlowProblem<dim>::project_back_saturation ()\n  {\n    for (unsigned int i=0; i<saturation_solution.size(); ++i)\n      if (saturation_solution(i) < 0.2)\n        saturation_solution(i) = 0.2;\n      else if (saturation_solution(i) > 1)\n        saturation_solution(i) = 1;\n  }\n\n\n\n  // @sect4{TwoPhaseFlowProblem<dim>::get_max_u_F_prime}\n  //\n  // Another simpler helper function: Compute the maximum of the total\n  // velocity times the derivative of the fraction flow function, i.e.,\n  // compute $\\|\\mathbf{u} F'(S)\\|_{L_\\infty(\\Omega)}$. This term is used in\n  // both the computation of the time step as well as in normalizing the\n  // entropy-residual term in the artificial viscosity.\n  template <int dim>\n  double\n  TwoPhaseFlowProblem<dim>::get_max_u_F_prime () const\n  {\n    const QGauss<dim>  quadrature_formula(darcy_degree+2);\n    const unsigned int n_q_points = quadrature_formula.size();\n\n    FEValues<dim> darcy_fe_values (darcy_fe, quadrature_formula,\n                                   update_values);\n    FEValues<dim> saturation_fe_values (saturation_fe, quadrature_formula,\n                                        update_values);\n\n    std::vector<Vector<double> > darcy_solution_values(n_q_points,\n                                                       Vector<double>(dim+1));\n    std::vector<double>          saturation_values (n_q_points);\n\n    double max_velocity_times_dF_dS = 0;\n\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = darcy_dof_handler.begin_active(),\n    endc = darcy_dof_handler.end();\n    typename DoFHandler<dim>::active_cell_iterator\n    saturation_cell = saturation_dof_handler.begin_active();\n    for (; cell!=endc; ++cell, ++saturation_cell)\n      {\n        darcy_fe_values.reinit (cell);\n        saturation_fe_values.reinit (saturation_cell);\n\n        darcy_fe_values.get_function_values (darcy_solution, darcy_solution_values);\n        saturation_fe_values.get_function_values (old_saturation_solution, saturation_values);\n\n        for (unsigned int q=0; q<n_q_points; ++q)\n          {\n            Tensor<1,dim> velocity;\n            for (unsigned int i=0; i<dim; ++i)\n              velocity[i] = darcy_solution_values[q](i);\n\n            const double dF_dS = fractional_flow_derivative(saturation_values[q],viscosity);\n\n            max_velocity_times_dF_dS = std::max (max_velocity_times_dF_dS,\n                                                 velocity.norm() * dF_dS);\n          }\n      }\n\n    return max_velocity_times_dF_dS;\n  }\n\n\n  // @sect4{TwoPhaseFlowProblem<dim>::get_extrapolated_saturation_range}\n  //\n  // For computing the stabilization term, we need to know the range of the\n  // saturation variable. Unlike in step-31, this range is trivially bounded\n  // by the interval $[0,1]$ but we can do a bit better by looping over a\n  // collection of quadrature points and seeing what the values are there. If\n  // we can, i.e., if there are at least two timesteps around, we can even\n  // take the values extrapolated to the next time step.\n  //\n  // As before, the function is taken with minimal modifications from step-31.\n  template <int dim>\n  std::pair<double,double>\n  TwoPhaseFlowProblem<dim>::get_extrapolated_saturation_range () const\n  {\n    const QGauss<dim>  quadrature_formula(saturation_degree+2);\n    const unsigned int n_q_points = quadrature_formula.size();\n\n    FEValues<dim> fe_values (saturation_fe, quadrature_formula,\n                             update_values);\n    std::vector<double> old_saturation_values(n_q_points);\n    std::vector<double> old_old_saturation_values(n_q_points);\n\n    if (timestep_number != 0)\n      {\n        double min_saturation = std::numeric_limits<double>::max(),\n               max_saturation = -std::numeric_limits<double>::max();\n\n        typename DoFHandler<dim>::active_cell_iterator\n        cell = saturation_dof_handler.begin_active(),\n        endc = saturation_dof_handler.end();\n        for (; cell!=endc; ++cell)\n          {\n            fe_values.reinit (cell);\n            fe_values.get_function_values (old_saturation_solution,\n                                           old_saturation_values);\n            fe_values.get_function_values (old_old_saturation_solution,\n                                           old_old_saturation_values);\n\n            for (unsigned int q=0; q<n_q_points; ++q)\n              {\n                const double saturation =\n                  (1. + time_step/old_time_step) * old_saturation_values[q]-\n                  time_step/old_time_step * old_old_saturation_values[q];\n\n                min_saturation = std::min (min_saturation, saturation);\n                max_saturation = std::max (max_saturation, saturation);\n              }\n          }\n\n        return std::make_pair(min_saturation, max_saturation);\n      }\n    else\n      {\n        double min_saturation = std::numeric_limits<double>::max(),\n               max_saturation = -std::numeric_limits<double>::max();\n\n        typename DoFHandler<dim>::active_cell_iterator\n        cell = saturation_dof_handler.begin_active(),\n        endc = saturation_dof_handler.end();\n        for (; cell!=endc; ++cell)\n          {\n            fe_values.reinit (cell);\n            fe_values.get_function_values (old_saturation_solution,\n                                           old_saturation_values);\n\n            for (unsigned int q=0; q<n_q_points; ++q)\n              {\n                const double saturation = old_saturation_values[q];\n\n                min_saturation = std::min (min_saturation, saturation);\n                max_saturation = std::max (max_saturation, saturation);\n              }\n          }\n\n        return std::make_pair(min_saturation, max_saturation);\n      }\n  }\n\n\n\n  // @sect4{TwoPhaseFlowProblem<dim>::compute_viscosity}\n  //\n  // The final tool function is used to compute the artificial viscosity on a\n  // given cell. This isn't particularly complicated if you have the formula\n  // for it in front of you, and looking at the implementation in step-31. The\n  // major difference to that tutorial program is that the velocity here is\n  // not simply $\\mathbf u$ but $\\mathbf u F'(S)$ and some of the formulas\n  // need to be adjusted accordingly.\n  template <int dim>\n  double\n  TwoPhaseFlowProblem<dim>::\n  compute_viscosity (const std::vector<double>          &old_saturation,\n                     const std::vector<double>          &old_old_saturation,\n                     const std::vector<Tensor<1,dim> > &old_saturation_grads,\n                     const std::vector<Tensor<1,dim> > &old_old_saturation_grads,\n                     const std::vector<Vector<double> > &present_darcy_values,\n                     const double                        global_max_u_F_prime,\n                     const double                        global_S_variation,\n                     const double                        cell_diameter) const\n  {\n    const double beta = .4 * dim;\n    const double alpha = 1;\n\n    if (global_max_u_F_prime == 0)\n      return 5e-3 * cell_diameter;\n\n    const unsigned int n_q_points = old_saturation.size();\n\n    double max_residual = 0;\n    double max_velocity_times_dF_dS = 0;\n\n    const bool use_dF_dS = true;\n\n    for (unsigned int q=0; q < n_q_points; ++q)\n      {\n        Tensor<1,dim> u;\n        for (unsigned int d=0; d<dim; ++d)\n          u[d] = present_darcy_values[q](d);\n\n        const double dS_dt = porosity * (old_saturation[q] - old_old_saturation[q])\n                             / old_time_step;\n\n        const double dF_dS = fractional_flow_derivative ((old_saturation[q] + old_old_saturation[q]) / 2.0,viscosity);\n\n        const double u_grad_S = u * dF_dS *\n                                (old_saturation_grads[q] + old_old_saturation_grads[q]) / 2.0;\n\n        const double residual\n          = std::abs((dS_dt + u_grad_S) *\n                     std::pow((old_saturation[q]+old_old_saturation[q]) / 2,\n                              alpha-1.));\n\n        max_residual = std::max (residual,        max_residual);\n        max_velocity_times_dF_dS = std::max (std::sqrt (u*u) *\n                                             (use_dF_dS\n                                              ?\n                                              std::max(dF_dS, 1.)\n                                              :\n                                              1),\n                                             max_velocity_times_dF_dS);\n      }\n\n    const double c_R = 1.0;\n    const double global_scaling = c_R * porosity * (global_max_u_F_prime) * global_S_variation /\n                                  std::pow(global_Omega_diameter, alpha - 2.);\n\n//    return (beta * (max_velocity_times_dF_dS) * cell_diameter);\n\n    return (beta *\n            (max_velocity_times_dF_dS) *\n            std::min (cell_diameter,\n                      std::pow(cell_diameter,alpha) *\n                      max_residual / global_scaling));\n  }\n\n\n  // @sect3{TwoPhaseFlowProblem<dim>::run}\n\n  // This function is, besides <code>solve()</code>, the primary function of\n  // this program as it controls the time iteration as well as when the\n  // solution is written into output files and when to do mesh refinement.\n  //\n  // With the exception of the startup code that loops back to the beginning\n  // of the function through the <code>goto start_time_iteration</code> label,\n  // everything should be relatively straightforward. In any case, it mimicks\n  // the corresponding function in step-31.\n  template <int dim>\n  void TwoPhaseFlowProblem<dim>::run ()\n  {\n    const unsigned int initial_refinement     = (dim == 2 ? 5 : 2);\n    const unsigned int n_pre_refinement_steps = (dim == 2 ? 3 : 2);\n\n\n    GridGenerator::hyper_cube (triangulation, 0, 1);\n    triangulation.refine_global (initial_refinement);\n    global_Omega_diameter = GridTools::diameter (triangulation);\n\n    setup_dofs ();\n\n    unsigned int pre_refinement_step = 0;\n\nstart_time_iteration:\n\n    VectorTools::project (saturation_dof_handler,\n                          saturation_constraints,\n                          QGauss<dim>(saturation_degree+2),\n                          SaturationInitialValues<dim>(),\n                          old_saturation_solution);\n\n    timestep_number = 0;\n    time_step = old_time_step = 0;\n    current_macro_time_step = old_macro_time_step = 0;\n\n    time = 0;\n\n    do\n      {\n        std::cout << \"Timestep \" << timestep_number\n                  << \":  t=\" << time\n                  << \", dt=\" << time_step\n                  << std::endl;\n\n        solve ();\n\n        std::cout << std::endl;\n\n        if (timestep_number % 200 == 0)\n          output_results ();\n\n        if (timestep_number % 25 == 0)\n          refine_mesh (initial_refinement,\n                       initial_refinement + n_pre_refinement_steps);\n\n        if ((timestep_number == 0) &&\n            (pre_refinement_step < n_pre_refinement_steps))\n          {\n            ++pre_refinement_step;\n            goto start_time_iteration;\n          }\n\n        time += time_step;\n        ++timestep_number;\n\n        old_old_saturation_solution = old_saturation_solution;\n        old_saturation_solution = saturation_solution;\n      }\n    while (time <= end_time);\n  }\n}\n\n\n\n// @sect3{The <code>main()</code> function}\n//\n// The main function looks almost the same as in all other programs. In\n// particular, it is essentially the same as in step-31 where we also explain\n// the need to initialize the MPI subsystem.\nint main (int argc, char *argv[])\n{\n  try\n    {\n      using namespace dealii;\n      using namespace Step43;\n\n      deallog.depth_console (0);\n\n      Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv);\n\n      TwoPhaseFlowProblem<2> two_phase_flow_problem(1);\n      two_phase_flow_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": "7c0d0a8b36b476e8da70a1fde2a0ea5389751c54", "size": 93352, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-43/step-43.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-43/step-43.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-43/step-43.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": 40.9438596491, "max_line_length": 118, "alphanum_fraction": 0.6287706744, "num_tokens": 20895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.2944150573125936}}
{"text": "// (C) Copyright 2007-2009 Andrew Sutton\n//\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0 (See accompanying file\n// LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GRAPH_DEGREE_CENTRALITY_HPP\n#define BOOST_GRAPH_DEGREE_CENTRALITY_HPP\n\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/concept/assert.hpp>\n\nnamespace boost {\n\ntemplate <typename Graph>\nstruct degree_centrality_measure\n{\n    typedef typename graph_traits<Graph>::degree_size_type degree_type;\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_type;\n};\n\ntemplate <typename Graph>\nstruct influence_measure\n    : public degree_centrality_measure<Graph>\n{\n    typedef degree_centrality_measure<Graph> base_type;\n    typedef typename base_type::degree_type degree_type;\n    typedef typename base_type::vertex_type vertex_type;\n\n    inline degree_type operator ()(vertex_type v, const Graph& g)\n    {\n        BOOST_CONCEPT_ASSERT(( IncidenceGraphConcept<Graph> ));\n        return out_degree(v, g);\n    }\n};\n\ntemplate <typename Graph>\ninline influence_measure<Graph>\nmeasure_influence(const Graph&)\n{ return influence_measure<Graph>(); }\n\n\ntemplate <typename Graph>\nstruct prestige_measure\n    : public degree_centrality_measure<Graph>\n{\n    typedef degree_centrality_measure<Graph> base_type;\n    typedef typename base_type::degree_type degree_type;\n    typedef typename base_type::vertex_type vertex_type;\n\n    inline degree_type operator ()(vertex_type v, const Graph& g)\n    {\n        BOOST_CONCEPT_ASSERT(( BidirectionalGraphConcept<Graph> ));\n        return in_degree(v, g);\n    }\n};\n\ntemplate <typename Graph>\ninline prestige_measure<Graph>\nmeasure_prestige(const Graph&)\n{ return prestige_measure<Graph>(); }\n\n\ntemplate <typename Graph, typename Vertex, typename Measure>\ninline typename Measure::degree_type\ndegree_centrality(const Graph& g, Vertex v, Measure measure)\n{\n    BOOST_CONCEPT_ASSERT(( DegreeMeasureConcept<Measure, Graph> ));\n    return measure(v, g);\n}\n\ntemplate <typename Graph, typename Vertex>\ninline typename graph_traits<Graph>::degree_size_type\ndegree_centrality(const Graph& g, Vertex v)\n{\n    return degree_centrality(g, v, measure_influence(g));\n}\n\n\n// These are alias functions, intended to provide a more expressive interface.\n\ntemplate <typename Graph, typename Vertex>\ninline typename graph_traits<Graph>::degree_size_type\ninfluence(const Graph& g, Vertex v)\n{ return degree_centrality(g, v, measure_influence(g)); }\n\n\ntemplate <typename Graph, typename Vertex>\ninline typename graph_traits<Graph>::degree_size_type\nprestige(const Graph& g, Vertex v)\n{ return degree_centrality(g, v, measure_prestige(g)); }\n\n\ntemplate <typename Graph, typename CentralityMap, typename Measure>\ninline void\nall_degree_centralities(const Graph& g, CentralityMap cent, Measure measure)\n{\n    BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<Graph> ));\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n    typedef typename graph_traits<Graph>::vertex_iterator VertexIterator;\n    BOOST_CONCEPT_ASSERT(( WritablePropertyMapConcept<CentralityMap,Vertex> ));\n    typedef typename property_traits<CentralityMap>::value_type Centrality;\n\n    VertexIterator i, end;\n    for(boost::tie(i, end) = vertices(g); i != end; ++i) {\n        Centrality c = degree_centrality(g, *i, measure);\n        put(cent, *i, c);\n    }\n}\n\ntemplate <typename Graph, typename CentralityMap>\ninline void all_degree_centralities(const Graph& g, CentralityMap cent)\n{ all_degree_centralities(g, cent, measure_influence(g)); }\n\n// More helper functions for computing influence and prestige.\n// I hate the names of these functions, but influence and prestige\n// don't pluralize too well.\n\ntemplate <typename Graph, typename CentralityMap>\ninline void all_influence_values(const Graph& g, CentralityMap cent)\n{ all_degree_centralities(g, cent, measure_influence(g)); }\n\ntemplate <typename Graph, typename CentralityMap>\ninline void all_prestige_values(const Graph& g, CentralityMap cent)\n{ all_degree_centralities(g, cent, measure_prestige(g)); }\n\n} /* namespace boost */\n\n#endif\n\n\n", "meta": {"hexsha": "f6cc7a22f4e9114af91e9d92d3125ec28b143185", "size": 4136, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/graph/degree_centrality.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/graph/degree_centrality.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/graph/degree_centrality.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": 31.3333333333, "max_line_length": 79, "alphanum_fraction": 0.7688588008, "num_tokens": 947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.2944150495618929}}
{"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 <boost/shared_ptr.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n#include <Eigen/Dense>\n#include <math.h>\n#include <iostream>\n\n#include \"tudat/astro/ephemerides/approximatePlanetPositions.h\"\n#include \"tudat/astro/LowThrustTrajectories/simsFlanagan.h\"\n#include \"tudat/astro/LowThrustTrajectories/simsFlanaganModel.h\"\n#include \"tudat/astro/LowThrustTrajectories/simsFlanaganOptimisationSetup.h\"\n#include \"tudat/astro/LowThrustTrajectories/ShapeBasedMethods/hodographicShaping.h\"\n#include \"tudat/astro/LowThrustTrajectories/ShapeBasedMethods/baseFunctionsHodographicShaping.h\"\n#include \"tudat/astro/LowThrustTrajectories/ShapeBasedMethods/compositeFunctionHodographicShaping.h\"\n#include \"tudat/astro/LowThrustTrajectories/ShapeBasedMethods/createBaseFunctionHodographicShaping.h\"\n#include \"pagmo/algorithms/de1220.hpp\"\n#include \"Problems/applicationOutput.h\"\n#include \"tudat/astro/basic_astro/celestialBodyConstants.h\"\n\nint main( )\n{\n    using namespace tudat;\n    using namespace tudat::input_output;\n    using namespace tudat::simulation_setup;\n    using namespace tudat::shape_based_methods;\n    using namespace tudat::low_thrust_trajectories;\n    using namespace shape_based_methods;\n\n\n    spice_interface::loadStandardSpiceKernels( );\n\n\n    double julianDate = 9264.5 * physical_constants::JULIAN_DAY;\n    double timeOfFlight = 1000.0 * physical_constants::JULIAN_DAY;\n    int numberOfRevolutions = 2;\n\n    // Ephemeris departure body.\n    ephemerides::EphemerisPointer pointerToDepartureBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions>(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::earthMoonBarycenter );\n\n    // Ephemeris arrival body.\n    ephemerides::EphemerisPointer pointerToArrivalBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::mars );\n\n    // Retrieve cartesian state at departure and arrival.\n    Eigen::Vector6d cartesianStateDepartureBody = pointerToDepartureBodyEphemeris->getCartesianState( julianDate );\n    Eigen::Vector6d cartesianStateArrivalBody = pointerToArrivalBodyEphemeris->getCartesianState( julianDate + timeOfFlight );\n\n    double maximumThrust = 5.0;\n    double specificImpulse = 3000.0;\n    double mass = 2800.0;\n    int numberSegments = 500;\n\n\n    std::string bodyToPropagate = \"Borzi\";\n    std::string centralBody = \"Sun\";\n\n\n    // Create central, departure and arrival bodies.\n    std::vector< std::string > bodiesToCreate;\n    bodiesToCreate.push_back( \"Sun\" );\n\n    std::map< std::string, std::shared_ptr< simulation_setup::BodySettings > > bodySettings =\n            simulation_setup::getDefaultBodySettings( bodiesToCreate );\n\n    std::string frameOrigin = \"SSB\";\n    std::string frameOrientation = \"ECLIPJ2000\";\n\n\n    // Define central body ephemeris settings.\n    bodySettings[ centralBody ]->ephemerisSettings = std::make_shared< simulation_setup::ConstantEphemerisSettings >(\n                ( Eigen::Vector6d( ) << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ).finished( ), frameOrigin, frameOrientation );\n\n    bodySettings[ centralBody ]->ephemerisSettings->resetFrameOrientation( frameOrientation );\n    bodySettings[ centralBody ]->rotationModelSettings->resetOriginalFrame( frameOrientation );\n\n\n    // Create system of bodies.\n    simulation_setup::SystemOfBodies bodies = createBodies( bodySettings );\n\n    bodies[ bodyToPropagate ] = std::make_shared< simulation_setup::Body >( );\n    bodies.at( bodyToPropagate )->setEphemeris( std::make_shared< ephemerides::TabulatedCartesianEphemeris< > >(\n                                                         std::shared_ptr< interpolators::OneDimensionalInterpolator\n                                                         < double, Eigen::Vector6d > >( ), frameOrigin, frameOrientation ) );\n\n\n    setGlobalFrameBodyEphemerides( bodies, frameOrigin, frameOrientation );\n\n    // Set vehicle mass.\n    bodies[ bodyToPropagate ]->setConstantBodyMass( mass );\n\n\n\n    double frequency = 2.0 * mathematical_constants::PI / timeOfFlight;\n    double scaleFactor = 1.0 / timeOfFlight;\n\n\n    // Initialize free coefficients vector for radial velocity function.\n    Eigen::VectorXd freeCoefficientsRadialVelocityFunction = Eigen::VectorXd::Zero( 0 );\n\n    // Initialize free coefficients vector for normal velocity function.\n    Eigen::VectorXd freeCoefficientsNormalVelocityFunction = Eigen::VectorXd::Zero( 0 );\n\n    // Initialize free coefficients vector for axial velocity function.\n    Eigen::VectorXd freeCoefficientsAxialVelocityFunction = Eigen::VectorXd::Zero( 0 );\n\n    // Get recommended base functions for the radial velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstRadialVelocityBaseFunctionSettings =\n            std::make_shared< BaseFunctionHodographicShapingSettings >( );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondRadialVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdRadialVelocityBaseFunctionSettings =\n            std::make_shared< TrigonometricFunctionHodographicShapingSettings >( frequency );\n\n    // Create components of the radial velocity composite function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > radialVelocityFunctionComponents;\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( constant, firstRadialVelocityBaseFunctionSettings ) );\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, secondRadialVelocityBaseFunctionSettings ) );\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( cosine, thirdRadialVelocityBaseFunctionSettings ) );\n\n    // Create base function settings for the components of the normal velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstNormalVelocityBaseFunctionSettings =\n            std::make_shared< BaseFunctionHodographicShapingSettings >( );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondNormalVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdNormalVelocityBaseFunctionSettings =\n            std::make_shared< TrigonometricFunctionHodographicShapingSettings >( frequency );\n\n    // Get recommended base functions for normal velocity composition function.\n    std::vector< std::shared_ptr< shape_based_methods::BaseFunctionHodographicShaping > > normalVelocityFunctionComponents;\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( constant, firstNormalVelocityBaseFunctionSettings ) );\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, secondNormalVelocityBaseFunctionSettings ) );\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( cosine, thirdNormalVelocityBaseFunctionSettings ) );\n\n    // Create base function settings for the components of the axial velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstAxialVelocityBaseFunctionSettings =\n            std::make_shared< TrigonometricFunctionHodographicShapingSettings >( ( numberOfRevolutions + 0.5 ) * frequency );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondAxialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >\n            ( 3.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdAxialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >(\n                3.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );\n\n    // Get recommended base functions for axial velocity composition function.\n    std::vector< std::shared_ptr< shape_based_methods::BaseFunctionHodographicShaping > > axialVelocityFunctionComponents;\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( cosine, firstAxialVelocityBaseFunctionSettings ) );\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerCosine, secondAxialVelocityBaseFunctionSettings ) );\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerSine, thirdAxialVelocityBaseFunctionSettings ) );\n\n\n    // Create hodographic-shaping object with defined velocity functions and boundary conditions.\n    std::shared_ptr< shape_based_methods::HodographicShaping > hodographicShaping =\n            std::make_shared< shape_based_methods::HodographicShaping >(\n                cartesianStateDepartureBody, cartesianStateArrivalBody, timeOfFlight, numberOfRevolutions,\n                bodies, bodyToPropagate, centralBody, radialVelocityFunctionComponents, normalVelocityFunctionComponents,\n                axialVelocityFunctionComponents, freeCoefficientsRadialVelocityFunction, freeCoefficientsNormalVelocityFunction,\n                freeCoefficientsAxialVelocityFunction );\n\n\n\n\n    // Save results\n    int numberOfSteps = 10000;\n    double stepSize = timeOfFlight / static_cast< double >( numberOfSteps );\n\n    // Define specific impulse function.\n    std::function< double( const double ) > specificImpulseFunction = [ = ]( const double time )\n    {\n        return specificImpulse;\n    };\n\n    // Define integrator settings.\n    std::shared_ptr< numerical_integrators::IntegratorSettings< double > > integratorSettings =\n            std::make_shared< numerical_integrators::IntegratorSettings< double > > ( numerical_integrators::rungeKutta4, 0.0, stepSize );\n\n    std::vector< double > epochsToSaveResults;\n    for ( int i = 0 ; i <= numberOfSteps ; i++ )\n    {\n        epochsToSaveResults.push_back( i * stepSize );\n    }\n\n    std::map< double, Eigen::Vector6d > hodographicShapingTrajectory;\n    std::map< double, Eigen::VectorXd > hodographicShapingMassProfile;\n    std::map< double, Eigen::VectorXd > hodographicShapingThrustProfile;\n    std::map< double, Eigen::VectorXd > hodographicShapingThrustAcceleration;\n    hodographicShaping->getTrajectory( epochsToSaveResults, hodographicShapingTrajectory );\n    hodographicShaping->getMassProfile( epochsToSaveResults, hodographicShapingMassProfile, specificImpulseFunction, integratorSettings );\n    hodographicShaping->getThrustProfile( epochsToSaveResults, hodographicShapingThrustProfile, specificImpulseFunction, integratorSettings );\n    hodographicShaping->getThrustAccelerationProfile( epochsToSaveResults, hodographicShapingThrustAcceleration,\n                                                      specificImpulseFunction, integratorSettings );\n\n\n\n\n    bodies[ bodyToPropagate ]->setConstantBodyMass( mass );\n\n    std::shared_ptr< ShapeBasedMethod > shapeBased = std::dynamic_pointer_cast< ShapeBasedMethod >( hodographicShaping );\n\n    std::function< Eigen::Vector3d( const double ) > initialGuessThrustFromShaping =\n            getInitialGuessFunctionFromShaping( shapeBased, numberSegments, timeOfFlight, specificImpulseFunction, integratorSettings );\n\n    std::vector< double > initialGuessVector = convertToSimsFlanaganThrustModel( initialGuessThrustFromShaping, maximumThrust,\n                                                                                 timeOfFlight, ( numberSegments + 1 ) / 2, numberSegments / 2 );\n\n    std::map< double, Eigen::Vector3d > initialGuessThrustProfile;\n    std::map< double, Eigen::Vector3d > initialGuessThrustAccelerationProfile;\n    std::map< double, Eigen::Vector1d > initialGuessMassProfile;\n\n    for ( unsigned int i = 0 ; i < epochsToSaveResults.size( ) ; i++ )\n    {\n        double currentTime = epochsToSaveResults[ i ];\n        initialGuessThrustProfile[ currentTime ] =  initialGuessThrustFromShaping( currentTime );\n\n        if ( i == 0 )\n        {\n            initialGuessMassProfile[ currentTime ] = ( Eigen::Vector1d( ) << mass ).finished( );\n        }\n        else\n        {\n            initialGuessMassProfile[ currentTime ] = ( Eigen::Vector1d( ) << initialGuessMassProfile[ epochsToSaveResults[ i - 1 ] ][ 0 ]\n                    - initialGuessThrustProfile[ currentTime ].norm( ) /\n                    ( specificImpulse * physical_constants::SEA_LEVEL_GRAVITATIONAL_ACCELERATION ) * stepSize ).finished( );\n        }\n\n        initialGuessThrustAccelerationProfile[ currentTime ] = initialGuessThrustProfile[ currentTime ] / initialGuessMassProfile[ currentTime ][ 0 ];\n\n    }\n\n\n    bodies[ bodyToPropagate ]->setConstantBodyMass( mass );\n\n    // Define optimisation algorithm.\n    algorithm optimisationAlgorithm{ pagmo::de1220() };\n\n    std::shared_ptr< OptimisationSettings > optimisationSettings = std::make_shared< OptimisationSettings >(\n                optimisationAlgorithm, 10, 1024, 1.0e-6, std::make_pair( initialGuessVector, 0.3 ) );\n\n    SimsFlanagan simsFlanagan = SimsFlanagan(\n                cartesianStateDepartureBody, cartesianStateArrivalBody, maximumThrust, specificImpulseFunction, numberSegments,\n                timeOfFlight, bodies, bodyToPropagate, centralBody, optimisationSettings );\n\n\n    std::map< double, Eigen::Vector6d > SimsFlanaganTrajectory;\n    std::map< double, Eigen::VectorXd > SimsFlanaganMassProfile;\n    std::map< double, Eigen::VectorXd > SimsFlanaganThrustProfile;\n    std::map< double, Eigen::VectorXd > SimsFlanaganThrustAcceleration;\n    simsFlanagan.getTrajectory( epochsToSaveResults, SimsFlanaganTrajectory );\n    simsFlanagan.getMassProfile( epochsToSaveResults, SimsFlanaganMassProfile, specificImpulseFunction, integratorSettings );\n    simsFlanagan.getThrustProfile( epochsToSaveResults, SimsFlanaganThrustProfile, specificImpulseFunction, integratorSettings );\n    simsFlanagan.getThrustAccelerationProfile( epochsToSaveResults, SimsFlanaganThrustAcceleration, specificImpulseFunction, integratorSettings );\n\n\n    input_output::writeDataMapToTextFile( hodographicShapingTrajectory,\n                                          \"hodographicShapingTrajectory.dat\",\n                                          tudat_pagmo_applications::getOutputPath( ),\n                                          \"\",\n                                          std::numeric_limits< double >::digits10,\n                                          std::numeric_limits< double >::digits10,\n                                          \",\" );\n\n    input_output::writeDataMapToTextFile( hodographicShapingMassProfile,\n                                          \"hodographicShapingMassProfile.dat\",\n                                          tudat_pagmo_applications::getOutputPath( ),\n                                          \"\",\n                                          std::numeric_limits< double >::digits10,\n                                          std::numeric_limits< double >::digits10,\n                                          \",\" );\n\n    input_output::writeDataMapToTextFile( hodographicShapingThrustProfile,\n                                          \"hodographicShapingThrustProfile.dat\",\n                                          tudat_pagmo_applications::getOutputPath( ),\n                                          \"\",\n                                          std::numeric_limits< double >::digits10,\n                                          std::numeric_limits< double >::digits10,\n                                          \",\" );\n\n    input_output::writeDataMapToTextFile( hodographicShapingThrustAcceleration,\n                                          \"hodographicShapingThrustAcceleration.dat\",\n                                          tudat_pagmo_applications::getOutputPath( ),\n                                          \"\",\n                                          std::numeric_limits< double >::digits10,\n                                          std::numeric_limits< double >::digits10,\n                                          \",\" );\n\n    input_output::writeDataMapToTextFile( SimsFlanaganTrajectory,\n                                          \"SimsFlanaganTrajectory.dat\",\n                                          tudat_pagmo_applications::getOutputPath( ),\n                                          \"\",\n                                          std::numeric_limits< double >::digits10,\n                                          std::numeric_limits< double >::digits10,\n                                          \",\" );\n\n    input_output::writeDataMapToTextFile( SimsFlanaganMassProfile,\n                                          \"SimsFlanaganMassProfile.dat\",\n                                          tudat_pagmo_applications::getOutputPath( ),\n                                          \"\",\n                                          std::numeric_limits< double >::digits10,\n                                          std::numeric_limits< double >::digits10,\n                                          \",\" );\n\n    input_output::writeDataMapToTextFile( SimsFlanaganThrustProfile,\n                                          \"SimsFlanaganThrustProfile.dat\",\n                                          tudat_pagmo_applications::getOutputPath( ),\n                                          \"\",\n                                          std::numeric_limits< double >::digits10,\n                                          std::numeric_limits< double >::digits10,\n                                          \",\" );\n\n    input_output::writeDataMapToTextFile( SimsFlanaganThrustAcceleration,\n                                          \"SimsFlanaganThrustAcceleration.dat\",\n                                          tudat_pagmo_applications::getOutputPath( ),\n                                          \"\",\n                                          std::numeric_limits< double >::digits10,\n                                          std::numeric_limits< double >::digits10,\n                                          \",\" );\n\n    input_output::writeDataMapToTextFile( initialGuessThrustProfile,\n                                          \"initialGuessThrustProfile.dat\",\n                                          tudat_pagmo_applications::getOutputPath( ),\n                                          \"\",\n                                          std::numeric_limits< double >::digits10,\n                                          std::numeric_limits< double >::digits10,\n                                          \",\" );\n\n    input_output::writeDataMapToTextFile( initialGuessThrustAccelerationProfile,\n                                          \"initialGuessThrustAccelerationProfile.dat\",\n                                          tudat_pagmo_applications::getOutputPath( ),\n                                          \"\",\n                                          std::numeric_limits< double >::digits10,\n                                          std::numeric_limits< double >::digits10,\n                                          \",\" );\n\n    input_output::writeDataMapToTextFile( initialGuessMassProfile,\n                                          \"initialGuessMassProfile.dat\",\n                                          tudat_pagmo_applications::getOutputPath( ),\n                                          \"\",\n                                          std::numeric_limits< double >::digits10,\n                                          std::numeric_limits< double >::digits10,\n                                          \",\" );\n\n\n    std::cout << \"DELTAV SIMS FLANAGAN: \" << simsFlanagan.computeDeltaV( ) << \"\\n\\n\";\n    std::cout << \"DELTAV SHAPE BASED: \" << hodographicShaping->computeDeltaV( ) << \"\\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": "91b04f632eae6e13366fb16c8f1c08bd6c783663", "size": 20649, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/pagmo/simsFlanaganTrajectoryExample.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/pagmo/simsFlanaganTrajectoryExample.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/pagmo/simsFlanaganTrajectoryExample.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": 55.6576819407, "max_line_length": 150, "alphanum_fraction": 0.6517022616, "num_tokens": 4238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7431680199891789, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.29434519491062444}}
{"text": "/*------------------------------------------------------------------------------\n* preceph.c : precise ephemeris and clock functions\n*\n*          Copyright (C) 2007-2013 by T.TAKASU, All rights reserved.\n*\n* references :\n*     [1] S.Hilla, The Extended Standard Product 3 Orbit Format (SP3-c),\n*         12 February, 2007\n*     [2] J.Ray, W.Gurtner, RINEX Extensions to Handle Clock Information,\n*         27 August, 1998\n*     [3] D.D.McCarthy, IERS Technical Note 21, IERS Conventions 1996, July 1996\n*     [4] D.A.Vallado, Fundamentals of Astrodynamics and Applications 2nd ed,\n*         Space Technology Library, 2004\n*-----------------------------------------------------------------------------*/\n\n#include <unordered_map>\n#include <iostream>\n#include <string>\n#include <array>\n#include <map>\n#include <ctype.h>\n\nusing std::string;\nusing std::array;\nusing std::map;\n\n#include <boost/log/trivial.hpp>\n\n\n#include \"eigenIncluder.hpp\"\n#include \"streamTrace.hpp\"\n#include \"navigation.hpp\"\n#include \"constants.h\"\n#include \"station.hpp\"\n#include \"algebra.hpp\"\n#include \"gTime.hpp\"\n#include \"common.hpp\"\n#include \"tides.hpp\"\n#include \"enums.h\"\n\nmap<string, map<E_Sys, array<double, 3>>> stationRBiasMap;\n\n//     double rbias[2][3]\t\t= {}; /* receiver dcb (0:p1-p2, 1:p1-c1, 2:p2-c2) (m) */\n\t\n#define NMAX        10              /* order of polynomial interpolation */\n#define MAXDTE      900.0           /* max time difference to ephem time (s) */\n#define EXTERR_CLK  1E-3            /* extrapolation error for clock (m/s) */\n#define EXTERR_EPH  5E-7            /* extrapolation error for ephem (m/s^2) */\n\n/* read satellite antenna parameters -------------------------------------------\n* read satellite antenna parameters\n* args   : char   *file       I   antenna parameter file\n*          gtime_t time       I   time\n*          nav_t  *nav        IO  navigation data\n* return : status (1:ok,0:error)\n* notes  : only support antex format for the antenna parameter file\n*-----------------------------------------------------------------------------*/\n/*extern int readsap(char *file, gtime_t time, nav_t *nav)\n{\n\tpcvs_t pcvs={0};\n\tpcv_t pcv0={0},*pcv;\n\tint i;\n\n\ttrace(3,\"readsap : file=%s time=%s\\n\",file,time.to_string(0).c_str());\n\n\tif (!readpcv(file,&pcvs)) return 0;\n\n\tfor (i=0;i<MAXSAT;i++) {\n\t\tpcv=searchpcv(i+1,\"\",time,&pcvs);\n\t\tnav->pcvs[i]=pcv?*pcv:pcv0;\n\t}\n\tfree(pcvs.pcv);\n\treturn 1;\n}*/\n/* read dcb parameters file --------------------------------------------------*/\nint readdcb(string file, nav_t *nav)\n{\n\t//todo aaron, use maps for these rather than arrays,\n\tFILE *fp;\n\tdouble cbias;\n\tchar buff[256],str1[32],str2[32]=\"\";\n\tint type=0;\n\tSatSys Sat;\n//     trace(3,\"readdcbf: file=%s\\n\",file);\n\n\tif (!(fp=fopen(file.c_str(), \"r\")))\n\t{\n//         trace(2,\"dcb parameters file open error: %s\\n\",file);\n\t\treturn 0;\n\t}\n\twhile (fgets(buff,sizeof(buff),fp))\n\t{\n\t\tif      (strstr(buff,\"DIFFERENTIAL (P1-P2) CODE BIASES\"))\ttype=1;\n\t\telse if (strstr(buff,\"DIFFERENTIAL (P1-C1) CODE BIASES\"))\ttype=2;\n\t\telse if (strstr(buff,\"DIFFERENTIAL (P2-C2) CODE BIASES\"))\ttype=3;\n\n\t\tif\t(!type\n\t\t\t||sscanf(buff,\"%s %s\",str1,str2) < 1)\n\t\t\tcontinue;\n\n\t\tif ((cbias = str2num(buff,26,9)) == 0)\n\t\t\tcontinue;\n\n\t\tif  ( !strcmp(str1,\"G\")\n\t\t\t||!strcmp(str1,\"R\"))\n\t\t{\n\t\t\tE_Sys sys;\n\t\t\tif (str1[0] == 'G')\t\tsys = E_Sys::GPS;\n\t\t\tif (str1[0] == 'R')\t\tsys = E_Sys::GLO;\n\t\t\t\n\t\t\tauto& rbias = stationRBiasMap[str2][sys];\n\t\t\t\n\t\t\t/* receiver dcb */\n\t\t\trbias[type-1] = cbias * 1E-9 * CLIGHT; /* ns -> m */ //todo aaron, this looks like it had issues to begin with\n\t\t\n\t\t}\n\t\telse if (Sat = SatSys(str1), Sat)\n\t\t{\n\t\t\t/* satellite dcb */\n\t\t\tif (type == 1)\t\tnav->satNavMap[Sat].cBias_P1_P2\t\t= cbias * 1E-9 * CLIGHT; /* ns -> m */\n\t\t\tif (type == 2)\t\tnav->satNavMap[Sat].cBiasMap[F1]\t= cbias * 1E-9 * CLIGHT; /* ns -> m */\n\t\t\tif (type == 3)\t\tnav->satNavMap[Sat].cBiasMap[F2]\t= cbias * 1E-9 * CLIGHT; /* ns -> m */\n\t\t}\n\t}\n\tfclose(fp);\n\n\treturn 1;\n}\n\n/* add satellite fcb ---------------------------------------------------------*/\n// int addfcb(nav_t *nav, gtime_t ts, gtime_t te, int sat,\n// \t\t\t\tconst double *bias, const double *std)\t//todo aaron, is this broken?\n// {\n//     fcbd_t *nav_fcb;\n//     int i,j;\n//\n//     if (nav->nf>0&&fabs(timediff(ts,nav->fcb[nav->nf-1].ts))<=1e-3) {\n//         for (i=0;i<3;i++) {\n//             nav->fcb[nav->nf-1].bias[sat-1][i]=bias[i];\n//             nav->fcb[nav->nf-1].std [sat-1][i]=std [i];\n//         }\n//         return 1;\n//     }\n//     if (nav->nf>=nav->nfmax) {\n//         nav->nfmax=nav->nfmax<=0?2048:nav->nfmax*2;\n//         if (!(nav_fcb=(fcbd_t *)realloc(nav->fcb,sizeof(fcbd_t)*nav->nfmax))) {\n//             free(nav->fcb); nav->nf=nav->nfmax=0;\n//             return 0;\n//         }\n//         nav->fcb=nav_fcb;\n//     }\n//     for (i=0;i<MAXSAT;i++) for (j=0;j<3;j++) {\n//         nav->fcb[nav->nf].bias[i][j]=nav->fcb[nav->nf].std[i][j]=0.0;\n//     }\n//     for (i=0;i<3;i++) {\n//         nav->fcb[nav->nf].bias[sat-1][i]=bias[i];\n//         nav->fcb[nav->nf].std [sat-1][i]=std [i];\n//     }\n//     nav->fcb[nav->nf  ].ts=ts;\n//     nav->fcb[nav->nf++].te=te;\n// \treturn 1;\n// }\n/* read satellite fcb file ---------------------------------------------------*/\n// int readfcbf(const char *file, nav_t *nav)\n// {\n// \tFILE *fp;\n// \tgtime_t ts,te;\n// \tdouble ep1[6],ep2[6],bias[3]={0},std[3]={0};\n// \tchar buff[1024],str[32],*p;\n// \tint sat;\n// \n// //     trace(3,\"readfcbf: file=%s\\n\",file);\n// \n// \tif (!(fp=fopen(file,\"r\"))) {\n// //         trace(2,\"fcb parameters file open error: %s\\n\",file);\n// \t\treturn 0;\n// \t}\n// \twhile (fgets(buff,sizeof(buff),fp)) {\n// \t\tif ((p=strchr(buff,'#'))) *p='\\0';\n// \t\tif (sscanf(buff,\"%lf/%lf/%lf %lf:%lf:%lf %lf/%lf/%lf %lf:%lf:%lf %s\"\n// \t\t\t\t\"%lf %lf %lf %lf %lf %lf\",ep1,ep1+1,ep1+2,ep1+3,ep1+4,ep1+5,\n// \t\t\t\tep2,ep2+1,ep2+2,ep2+3,ep2+4,ep2+5,str,bias,std,bias+1,std+1,\n// \t\t\t\tbias+2,std+2)<17) continue;\n// \t\tif (!(sat=SatSys(str))) continue;\n// \t\tts=epoch2time(ep1);\n// \t\tte=epoch2time(ep2);\n// \t\tif (!addfcb(nav,ts,te,sat,bias,std)) return 0;\n// \t}\n// \tfclose(fp);\n// \treturn 1;\n// }\n/* compare satellite fcb -----------------------------------------------------*/\n// bool cmpfcb(fcbd_t&p1, fcbd_t&p2)\n// {\n// \tfcbd_t *q1=&p1,*q2=&p2;\n// \tdouble tt=timediff(q1->ts,q2->ts);\n// \treturn tt<-1E-3?-1:(tt>1E-3?1:0);\n// }\n/* read satellite fcb data -----------------------------------------------------\n* read satellite fractional cycle bias (dcb) parameters\n* args   : char   *file       I   fcb parameters file (wild-card * expanded)\n*          nav_t  *nav        IO  navigation data\n* return : status (1:ok,0:error)\n* notes  : fcb data appended to navigation data\n*-----------------------------------------------------------------------------*/\n// int readfcb(string& file, nav_t *nav)\n// {\n// \treadfcbf(file.c_str(), nav);\n// // \tnav->fcbList.sort(cmpfcb);\n// \treturn 1;\n// }\n\n/* polynomial interpolation by Neville's algorithm ---------------------------*/\ndouble interppol(const double *x, double *y, int n)\n{\n\tfor (int j=1; j < n;\t\tj++)\n\tfor (int i=0; i < n - j;\ti++)\n\t{\n\t\ty[i] = (x[i+j] * y[i] - x[i] * y[i+1]) / (x[i+j] - x[i]);\n\t}\n\n\treturn y[0];\n}\n\n/* satellite position by precise ephemeris -----------------------------------*/\nint pephpos(\n\tGTime time,\n\tSatSys Sat,\n\tnav_t& nav,\n\tdouble *rs,\n\tdouble *dts,\n\tdouble *vare,\n\tdouble *varc)\n{\n\tdouble t[NMAX+1],p[3][NMAX+1],c[2],s[3];\n\n\tchar id[4];\n\tSat.getId(id);\n//     trace(4,\"pephpos : time=%s sat=%s\\n\",time.to_string(3).c_str(),id);\n\n\trs[0]\t= 0;\n\trs[1]\t= 0;\n\trs[2]\t= 0;\n\t*dts\t= 0;\n\n\tPephList pephList = nav.pephMap[Sat];\n\n\tif\t( (pephList.size()\t\t\t\t\t\t\t< NMAX + 1)\n\t\t||(timediff(time, pephList.begin()->first)\t< -MAXDTE)\n\t\t||(timediff(time, pephList.rbegin()->first)\t> +MAXDTE))\n\t{\n//         trace(3,\"no prec ephem %s sat=%s\\n\",time.to_string(0).c_str(),id);\n\t\treturn 0;\n\t}\n\n// \t//search for the ephemeris in the list\n\n\tauto peph_it = pephList.lower_bound(time);\n\tif (peph_it == pephList.end())\n\t{\n\t\tpeph_it--;\n\t}\n\n\tauto middle0 = peph_it;\n\n\t//go forward a few steps to make sure we're far from the end of the list.\n\tfor (int i = 0; i < NMAX/2; i++)\n\t{\n\t\tpeph_it++;\n\t\tif (peph_it == pephList.end())\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t//go backward a few steps to make sure we're far from the beginning of the list\n\tfor (int i = 0; i <= NMAX; i++)\t//todo aaron, needs +1 to go back an extra step due to end()?\n\t{\n\t\tpeph_it--;\n\t\tif (peph_it == pephList.begin())\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tauto begin = peph_it;\n\n\t//get interpolation parameters and check all ephemerides have values.\n\tpeph_it = begin;\n\tfor (int i = 0; i <= NMAX; i++, peph_it++)\n\t{\n\t\tPeph& peph = peph_it->second;\n\t\tif (peph.Pos.norm() <= 0)\n\t\t{\n//             trace(3,\"prec ephem outage %s sat=%s\\n\",time.to_string(0).c_str(), id);\n\t\t\treturn 0;\n\t\t}\n\n\t\tt[i] = timediff(peph.time, time);\n\t\tauto& pos = peph.Pos;\n#if 0\n\t\tp[0][i]=pos[0];\n\t\tp[1][i]=pos[1];\n#else\n\t\t/* correciton for earh rotation ver.2.4.0 */\n\t\tdouble sinl = sin(OMGE * t[i]);\n\t\tdouble cosl = cos(OMGE * t[i]);\n\t\tp[0][i] = cosl * pos[0] - sinl * pos[1];\n\t\tp[1][i] = sinl * pos[0] + cosl * pos[1];\n#endif\n\t\tp[2][i] = pos[2];\n\t}\n\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\trs[i] = interppol(t, p[i], NMAX + 1);\n\t}\n\tdouble std = 0;\n\tif (vare)\n\t{\n\t\tfor (int i = 0; i < 3; i++)\n\t\t\ts[i] = middle0->second.PosStd[i];\n\t\tstd = norm(s, 3);\n\n\t\t/* extrapolation error for orbit */\n\t\tif      (t[0   ] > 0) std += EXTERR_EPH * SQR(t[0   ]) / 2;\t\t//todo aaron, needs straigtening as below?\n\t\telse if (t[NMAX] < 0) std += EXTERR_EPH * SQR(t[NMAX]) / 2;\n\n\t\t*vare = SQR(std);\n\t}\n\n\t/* linear interpolation for clock */\n\tauto middle1 = middle0;\n\tif (middle0 != pephList.begin())\n\t{\n\t\tmiddle0--;\n\t}\n\tt[0] = timediff(time, middle0->second.time);\n\tt[1] = timediff(time, middle1->second.time);\n\tc[0] = middle0->second.Clk;\n\tc[1] = middle1->second.Clk;\n\n\tif \t\t(t[0] <= 0)\n\t{\n\t\t*dts = c[0];\n\n\t\tif (*dts != 0)\n\t\t\tstd = middle0->second.ClkStd * CLIGHT\t+ EXTERR_CLK * fabs(t[0]);\n\t}\n\telse if (t[1] >= 0)\n\t{\n\t\t*dts = c[1];\n\n\t\tif (*dts != 0)\n\t\t\tstd = middle1->second.ClkStd * CLIGHT\t+ EXTERR_CLK * fabs(t[1]);\n\t}\n\telse if ( c[0] != 0\n\t\t\t&&c[1] != 0)\n\t{\n\t\t*dts = (c[1] * t[0] - c[0] * t[1]) / (t[0] - t[1]);\n\n\t\tdouble inv0 = 1 / middle0->second.ClkStd * CLIGHT + EXTERR_CLK * fabs(t[0]);\n\t\tdouble inv1 = 1 / middle1->second.ClkStd * CLIGHT + EXTERR_CLK * fabs(t[1]);\n\t\tstd\t\t\t= 1 / (inv0 + inv1);\n\t}\n\telse\n\t{\n\t\t*dts = 0;\n\t}\n\tif (varc)\n\t\t*varc=SQR(std);\n\treturn 1;\n}\n\n/* satellite clock by precise clock ------------------------------------------*/\nint pephclk(GTime time, string id, nav_t& nav, double *dtSat, double *varc)\n{\n//     BOOST_LOG_TRIVIAL(debug)\n// \t<< \"pephclk : time=\" << time.to_string(3)\n// \t<< \" id=\" << id;\n\n\tPclkList pclkList = nav.pclkMap[id];\n\n\tif\t( (pclkList.size()\t\t\t\t\t\t\t< 2)\n\t\t||(timediff(time, pclkList.front().\ttime)\t< -MAXDTE)\n\t\t||(timediff(time, pclkList.back().\ttime)\t> +MAXDTE))\n\t{\n\t\tBOOST_LOG_TRIVIAL(debug)\n\t\t<< \"no prec clock \" << time.to_string(0)\n\t\t<< \" id=\" << id;\n\n\t\treturn -1;\t//non zero for pass, negative for no result\n\t}\n\n\t//search for the ephemeris in the list\n\tauto pclk_it = pclkList.begin();\n\twhile (pclk_it->time < time)\n\t{\n\t\tpclk_it++;\n\t\tif (pclk_it == pclkList.end())\n\t\t{\n\t\t\tpclk_it--;\n\t\t\tbreak;\n\t\t}\n\t}\n\tauto middle1 = pclk_it;\n\tauto middle0 = middle1;\n\tif (middle0 != pclkList.begin())\n\t{\n\t\tmiddle0--;\n\t}\n\n\t/* linear interpolation for clock */\n\tdouble t[2];\n\tdouble c[2];\n\tt[0] = timediff(time, middle0->time);\n\tt[1] = timediff(time, middle1->time);\n\tc[0] = middle0->clk;\n\tc[1] = middle1->clk;\n\n\tdouble std = 0;\n\n\tif\t\t(t[0] <= 0)\n\t{\n\t\t*dtSat = c[0];\n\n\t\tif (*dtSat == 0)\n\t\t\treturn 0;\n\n\t\tstd\t= middle0->std * CLIGHT\t+ EXTERR_CLK * fabs(t[0]);\n\t}\n\telse if (t[1] >= 0)\n\t{\n\t\t*dtSat = c[1];\n\n\t\tif (*dtSat == 0)\n\t\t\treturn 0;\n\n\t\tstd\t= middle1->std * CLIGHT\t+ EXTERR_CLK * fabs(t[1]);\n\t}\n\telse if\t( c[0] != 0\n\t\t\t&&c[1] != 0)\n\t{\n\t\t*dtSat = (c[1] * t[0] - c[0] * t[1]) / (t[0] - t[1]);\n\n\t\tdouble inv0 = 1 / middle0->std * CLIGHT + EXTERR_CLK * fabs(t[0]);\n\t\tdouble inv1 = 1 / middle1->std * CLIGHT + EXTERR_CLK * fabs(t[1]);\n\t\tstd\t\t\t= 1 / (inv0 + inv1);\n\t}\n\telse\n\t{\n\t\tBOOST_LOG_TRIVIAL(debug)\n\t\t<< \"prec clock outage \" << time.to_string(0)\n\t\t<< \" sat=\" << id;\n\n\t\treturn 0;\n\t}\n\n\tif (varc)\n\t\t*varc = SQR(std);\n\n\treturn 1;\n}\n/* satellite antenna phase center offset ---------------------------------------\n* compute satellite antenna phase center offset in ecef\n* args   : gtime_t time       I   time (gpst)\n*          double *rs         I   satellite position and velocity (ecef)\n*                                 {x,y,z,vx,vy,vz} (m|m/s)\n*          int    sat         I   satellite number\n*          nav_t  *nav        I   navigation data\n*          double *dant       I   satellite antenna phase center offset (ecef)\n*                                 {dx,dy,dz} (m) (iono-free LC value)\n* return : none\n*-----------------------------------------------------------------------------*/\nvoid satantoff(\n\tTrace&\t\ttrace,\n\tGTime\t\ttime,\n\tVector3d&\trs,\n\tSatSys& \tSat,\n\tSatNav*\t\tsatNav_ptr,\n\tVector3d&\tdant,\n\tPcoMapType*\tpcoMap_ptr)\n{\n\tauto&\tlam = satNav_ptr->lamMap;\n\tdouble gmst,erpv[5]={0};\n\tE_FType j = F1;\n\tE_FType k = F2;\n\ttracepde(4,trace, \"satantoff: time=%s sat=%2d\\n\",time.to_string(3).c_str() ,Sat);\n\n\t/* sun position in ecef */\n\tVector3d rsun;\n\tsunmoonpos(gpst2utc(time),erpv,rsun.data(),NULL,&gmst);\n\n\t/* unit vectors of satellite fixed coordinates */\n\tVector3d r = -rs;\n\tVector3d ez = r.normalized();\n\tr = rsun - rs;\n\tVector3d es = r.normalized();\n\tr = ez.cross(es);\n\tVector3d ey = r.normalized();\n\tVector3d ex = ey.cross(ez);\n\n\n\tint sys = Sat.sys;\n\tif \t( sys == E_Sys::GAL\n\t\t||sys == E_Sys::SBS)\n\t{\n\t\tk = F5;\n\t}\n\n\tif \t( lam[j] == 0\n\t\t||lam[k] == 0)\n\t{\n\t\treturn;\n\t}\n\n\tdouble gamma\t= SQR(lam[k]) / SQR(lam[j]);\t\t//todo aaron, can use obs2lc?\n\tdouble C1\t\t= gamma\t/ (gamma - 1);\n\tdouble C2\t\t= -1\t/ (gamma - 1);\n\n\tif (pcoMap_ptr == nullptr)\n\t{\n\t\treturn;\n\t}\n\tauto& pcoMap = *pcoMap_ptr;\n\n\t/* iono-free LC */\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\t/* ENU to NEU */\n\t\tVector3d pcoJ;\n\t\tVector3d pcoK;\n\t\tif (pcoMap.find(j) == pcoMap.end())\t\tpcoJ = Vector3d::Zero();\n\t\telse\t\t\t\t\t\t\t\t\tpcoJ = pcoMap[j];\n\t\tif (pcoMap.find(k) == pcoMap.end())\t\tpcoK = Vector3d::Zero();\n\t\telse\t\t\t\t\t\t\t\t\tpcoK = pcoMap[k];\n\t\tdouble dant1\t= pcoJ[1] * ex(i)\n\t\t\t\t\t\t+ pcoJ[0] * ey(i)\n\t\t\t\t\t\t+ pcoJ[2] * ez(i);\t//todo aaron, matrix\n\t\tdouble dant2\t= pcoK[1] * ex(i)\n\t\t\t\t\t\t+ pcoK[0] * ey(i)\n\t\t\t\t\t\t+ pcoK[2] * ez(i);\n\n\t\tdant(i)\t= C1 * dant1\n\t\t\t\t+ C2 * dant2;\n\t}\n}\n\n/* satellite position/clock by precise ephemeris/clock -------------------------\n* compute satellite position/clock with precise ephemeris/clock\n* args   : gtime_t time       I   time (gpst)\n*          int    sat         I   satellite number\n*          nav_t  *nav        I   navigation data\n*          int    opt         I   sat postion option\n*                                 (0: center of mass, 1: antenna phase center)\n*          double *rs         O   sat position and velocity (ecef)\n*                                 {x,y,z,vx,vy,vz} (m|m/s)\n*          double *dts        O   sat clock {bias,drift} (s|s/s)\n*          double *var        IO  sat position and clock error variance (m)\n*                                 (NULL: no output)\n* return : status (1:ok,0:error or data outage)\n* notes  : clock includes relativistic correction but does not contain code bias\n*          before calling the function, nav->peph, nav->ne, nav->pclk and\n*          nav->nc must be set by calling readsp3(), readrnx() or readrnxt()\n*          if precise clocks are not set, clocks in sp3 are used instead\n*-----------------------------------------------------------------------------*/\nint peph2pos(\n\tTrace&\t\ttrace,\n\tGTime\t\ttime,\n\tSatSys&\t\tSat,\n\tnav_t& \t\tnav,\n\tint\t\t\topt,\n\tObs&\t\tobs,\n\tPcoMapType*\tpcoMap_ptr)\n{\n\tVector3d dAnt\t= Vector3d::Zero();\n\tVector3d rst\t= Vector3d::Zero();\n\n\tdouble dtss1 = 0,dtss2 = 0,dtst,vare=0,varc=0,tt=1E-3;\n\n\ttracepde(4,trace, \"peph2pos: time=%s sat=%2d opt=%d\\n\", time.to_string(3).c_str(), Sat, opt);\n\n\t/* satellite position and clock bias */\n\tif \t( !pephpos(time, Sat, nav, obs.rSat.data(),\t&dtss1,\t&vare,\t&varc)\n\t\t||!pephclk(time, Sat, nav, \t\t\t\t\t&dtss2,\t\t\t&varc))\n\t{\n\t\treturn 0;\n\t}\n\n\tif (dtss2 != 0)\n\t{\n\t\tdouble delta = dtss1 - dtss2;\n\t\tdtss1 = dtss2;\n\t}\n\n\ttime = timeadd(time,tt);\n\n\tif \t( !pephpos(time, Sat, nav, rst.data(),\t\t&dtst,\tNULL,\tNULL)\n\t\t||!pephclk(time, Sat, nav, \t\t\t\t\t&dtst,\t\t\tNULL))\n\t\treturn 0;\n\n\t/* satellite antenna offset correction */\n\tif (opt)\n\t{\n\t\tsatantoff(trace, time, obs.rSat, Sat, &nav.satNavMap[Sat], dAnt, pcoMap_ptr);\n\t}\n\n\tobs.satVel = (rst - obs.rSat) / tt;\n\tobs.rSat += dAnt;\n\n\t/* relativistic effect correction */\n\tif (dtss1 != 0)\n\t{\n\t\tdouble deltaDt = dtst-dtss1;\n\t\tdouble relativisticAdj = 2 * obs.rSat.dot(obs.satVel) / CLIGHT / CLIGHT;\n\t\tobs.dtSat[0] = dtss1 - relativisticAdj;\n\t\tobs.dtSat[1] = deltaDt / tt;\n\t}\n\telse\n\t{\n\t\t/* no precise clock */\n\t\tobs.dtSat[0] = 0;\n\t\tobs.dtSat[1] = 0;\n\t}\n\n\tobs.var = vare + varc;\n\n// \tobs.svh = 1;\n\treturn 1;\n}\n\n", "meta": {"hexsha": "5ff43076b3f6bb6e976e97bf269b920747fb4fc8", "size": 16856, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/rtklib/preceph.cpp", "max_stars_repo_name": "RodrigoNaves/ginan-bitbucket-update-tests", "max_stars_repo_head_hexsha": "4bd5cc0a9dd0e94b1c2d8b35385e128404009b0c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 73.0, "max_stars_repo_stars_event_min_datetime": "2021-07-08T23:35:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:17:58.000Z", "max_issues_repo_path": "src/cpp/rtklib/preceph.cpp", "max_issues_repo_name": "RodrigoNaves/ginan-bitbucket-update-tests", "max_issues_repo_head_hexsha": "4bd5cc0a9dd0e94b1c2d8b35385e128404009b0c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2021-09-27T14:27:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T23:50:02.000Z", "max_forks_repo_path": "src/cpp/rtklib/preceph.cpp", "max_forks_repo_name": "RodrigoNaves/ginan-bitbucket-update-tests", "max_forks_repo_head_hexsha": "4bd5cc0a9dd0e94b1c2d8b35385e128404009b0c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 39.0, "max_forks_repo_forks_event_min_datetime": "2021-07-12T05:42:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:15:34.000Z", "avg_line_length": 26.6708860759, "max_line_length": 113, "alphanum_fraction": 0.5365448505, "num_tokens": 5939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947155710234, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.2943048615275117}}
{"text": "#include \"Assembler.hpp\"\n\n// std c++ headers\n#include <algorithm>\n#include <vector>\n\n// MTL4 includes\n#include <boost/numeric/mtl/mtl.hpp>\n\n// AMDiS includes\n#include \"DOFVector.hpp\"\n#include \"Element.hpp\"\n#include \"ElInfo.hpp\"\n#include \"Operator.hpp\"\n#include \"QPsiPhi.hpp\"\n\nnamespace AMDiS\n{\n  Assembler::Assembler(not_null<Operator*> op,\n                       not_null<const FiniteElemSpace*> row,\n\t\t\t\tconst FiniteElemSpace*  col)\n    : operat(op),\n      rowFeSpace(row),\n      colFeSpace(col ? col : row.get()),\n      nRow(rowFeSpace->getBasisFcts()->getNumber()),\n      nCol(colFeSpace->getBasisFcts()->getNumber()),\n      remember(true),\n      rememberElMat(false),\n      rememberElVec(false),\n      elementMatrix(nRow, nCol),\n      elementVector(nRow),\n      tmpMat(nRow, nCol),\n      lastMatEl(NULL),\n      lastVecEl(NULL),\n      lastTraverseId(-1)\n  {}\n\n\n  void Assembler::calculateElementMatrix(const ElInfo* elInfo,\n                                         ElementMatrix& userMat,\n                                         double factor)\n  {\n    if (remember && (factor != 1.0 || operat->getUhOld()))\n      rememberElMat = true;\n\n    Element* el = elInfo->getElement();\n\n    if (el != lastMatEl || !operat->isOptimized())\n    {\n      initElement(elInfo);\n\n      if (rememberElMat)\n        set_to_zero(elementMatrix);\n\n      lastMatEl = el;\n    }\n    else\n    {\n      // Only possible in single mesh case when one operator\n      // is used more than twice?\n      if (rememberElMat)\n      {\n        if (&userMat != &elementMatrix)\n          userMat += factor * elementMatrix;\n        return;\n      }\n    }\n\n    ElementMatrix& mat = rememberElMat ? elementMatrix : userMat;\n\n    if (secondOrderAssembler)\n      secondOrderAssembler->calculateElementMatrix(elInfo, mat);\n    if (firstOrderAssemblerGrdPsi)\n      firstOrderAssemblerGrdPsi->calculateElementMatrix(elInfo, mat);\n    if (firstOrderAssemblerGrdPhi)\n      firstOrderAssemblerGrdPhi->calculateElementMatrix(elInfo, mat);\n    if (zeroOrderAssembler)\n      zeroOrderAssembler->calculateElementMatrix(elInfo, mat);\n\n    if (rememberElMat && &userMat != &elementMatrix)\n      userMat += factor * elementMatrix;\n  }\n\n\n  void Assembler::calculateElementVector(const ElInfo* elInfo,\n                                         DenseVector<double>& userVec,\n                                         double factor)\n  {\n    if (remember && factor != 1.0)\n      rememberElVec = true;\n\n    Element* el = elInfo->getElement();\n\n    if ((el != lastMatEl && el != lastVecEl) || !operat->isOptimized())\n      initElement(elInfo);\n\n    if (el != lastVecEl || !operat->isOptimized())\n    {\n      if (rememberElVec)\n        set_to_zero(elementVector);\n\n      lastVecEl = el;\n    }\n    else\n    {\n      // Only possible in single mesh case when one operator\n      // is used more than twice at dof vector?\n      if (rememberElVec)\n      {\n        userVec += factor * elementVector;\n        return;\n      }\n    }\n\n    DenseVector<double>& vec = rememberElVec ? elementVector : userVec;\n\n    if (operat->getUhOld() && remember)\n    {\n      matVecAssemble(elInfo, vec);\n      if (rememberElVec)\n        userVec += factor * elementVector;\n\n      return;\n    }\n\n    if (firstOrderAssemblerGrdPsi)\n      firstOrderAssemblerGrdPsi->calculateElementVector(elInfo, vec);\n    if (zeroOrderAssembler)\n      zeroOrderAssembler->calculateElementVector(elInfo, vec);\n\n    if (rememberElVec)\n      userVec += factor * elementVector;\n  }\n\n\n  void Assembler::matVecAssemble(const ElInfo* elInfo, DenseVector<double>& vec)\n  {\n\n    Element* el = elInfo->getElement();\n    DenseVector<double> uhOldLoc(operat->getUhOld()->getFeSpace() == rowFeSpace ?\n                                 nRow : nCol);\n    operat->getUhOld()->getLocalVector(el, uhOldLoc);\n\n    if (el != lastMatEl)\n    {\n      set_to_zero(elementMatrix);\n      calculateElementMatrix(elInfo, elementMatrix);\n    }\n\n\n    vec += elementMatrix * uhOldLoc;\n  }\n\n\n  void Assembler::initElement(const ElInfo* smallElInfo,\n                              const ElInfo* largeElInfo,\n                              Quadrature* quad)\n  {\n    if (secondOrderAssembler)\n      secondOrderAssembler->initElement(smallElInfo, largeElInfo, quad);\n    if (firstOrderAssemblerGrdPsi)\n      firstOrderAssemblerGrdPsi->initElement(smallElInfo, largeElInfo, quad);\n    if (firstOrderAssemblerGrdPhi)\n      firstOrderAssemblerGrdPhi->initElement(smallElInfo, largeElInfo, quad);\n    if (zeroOrderAssembler)\n      zeroOrderAssembler->initElement(smallElInfo, largeElInfo, quad);\n  }\n\n\n  void Assembler::checkQuadratures()\n  {\n    if (secondOrderAssembler)\n    {\n      // create quadrature\n      if (!secondOrderAssembler->getQuadrature())\n      {\n        int dim = rowFeSpace->getMesh()->getDim();\n        int degree = operat->getQuadratureDegree(2);\n        Quadrature* quadrature = Quadrature::provideQuadrature(dim, degree);\n        secondOrderAssembler->setQuadrature(quadrature);\n      }\n    }\n    if (firstOrderAssemblerGrdPsi)\n    {\n      // create quadrature\n      if (!firstOrderAssemblerGrdPsi->getQuadrature())\n      {\n        int dim = rowFeSpace->getMesh()->getDim();\n        int degree = operat->getQuadratureDegree(1, GRD_PSI);\n        Quadrature* quadrature = Quadrature::provideQuadrature(dim, degree);\n        firstOrderAssemblerGrdPsi->setQuadrature(quadrature);\n      }\n    }\n    if (firstOrderAssemblerGrdPhi)\n    {\n      // create quadrature\n      if (!firstOrderAssemblerGrdPhi->getQuadrature())\n      {\n        int dim = rowFeSpace->getMesh()->getDim();\n        int degree = operat->getQuadratureDegree(1, GRD_PHI);\n        Quadrature* quadrature = Quadrature::provideQuadrature(dim, degree);\n        firstOrderAssemblerGrdPhi->setQuadrature(quadrature);\n      }\n    }\n    if (zeroOrderAssembler)\n    {\n      // create quadrature\n      if (!zeroOrderAssembler->getQuadrature())\n      {\n        int dim = rowFeSpace->getMesh()->getDim();\n        int degree = operat->getQuadratureDegree(0);\n        Quadrature* quadrature = Quadrature::provideQuadrature(dim, degree);\n        zeroOrderAssembler->setQuadrature(quadrature);\n      }\n    }\n  }\n\n\n  void Assembler::finishAssembling()\n  {\n    lastVecEl = NULL;\n    lastMatEl = NULL;\n  }\n\n\n  OptimizedAssembler::OptimizedAssembler(Operator*  op,\n                                         Quadrature* quad2,\n                                         Quadrature* quad1GrdPsi,\n                                         Quadrature* quad1GrdPhi,\n                                         Quadrature* quad0,\n                                         const FiniteElemSpace* rowFeSpace,\n                                         const FiniteElemSpace* colFeSpace)\n    : Assembler(op, rowFeSpace, colFeSpace)\n  {\n    bool opt = (rowFeSpace->getBasisFcts() == colFeSpace->getBasisFcts());\n\n    // create sub assemblers\n    secondOrderAssembler =\n      SecondOrderAssembler::getSubAssembler(op, this, quad2, opt);\n    firstOrderAssemblerGrdPsi =\n      FirstOrderAssembler::getSubAssembler(op, this, quad1GrdPsi, GRD_PSI, opt);\n    firstOrderAssemblerGrdPhi =\n      FirstOrderAssembler::getSubAssembler(op, this, quad1GrdPhi, GRD_PHI, opt);\n    zeroOrderAssembler =\n      ZeroOrderAssembler::getSubAssembler(op, this, quad0, opt);\n\n    checkQuadratures();\n  }\n\n\n  StandardAssembler::StandardAssembler(Operator* op,\n                                       Quadrature* quad2,\n                                       Quadrature* quad1GrdPsi,\n                                       Quadrature* quad1GrdPhi,\n                                       Quadrature* quad0,\n                                       const FiniteElemSpace* rowFeSpace,\n                                       const FiniteElemSpace* colFeSpace)\n    : Assembler(op, rowFeSpace, colFeSpace)\n  {\n    remember = false;\n\n    // create sub assemblers\n    secondOrderAssembler =\n      SecondOrderAssembler::getSubAssembler(op, this, quad2, false);\n    firstOrderAssemblerGrdPsi =\n      FirstOrderAssembler::getSubAssembler(op, this, quad1GrdPsi, GRD_PSI, false);\n    firstOrderAssemblerGrdPhi =\n      FirstOrderAssembler::getSubAssembler(op, this, quad1GrdPhi, GRD_PHI, false);\n    zeroOrderAssembler =\n      ZeroOrderAssembler::getSubAssembler(op, this, quad0, false);\n\n    checkQuadratures();\n  }\n\n} // end namespace AMDiS\n", "meta": {"hexsha": "16d469019796014b41220783ea84b031038368ba", "size": 8291, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Assembler.cpp", "max_stars_repo_name": "spraetor/amdis2", "max_stars_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T16:44:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T07:26:27.000Z", "max_issues_repo_path": "src/Assembler.cpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Assembler.cpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0398550725, "max_line_length": 82, "alphanum_fraction": 0.6124713545, "num_tokens": 2013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2942546202574461}}
{"text": "//\n// Copyright 2016 Pixar\n//\n// Licensed under the Apache License, Version 2.0 (the \"Apache License\")\n// with the following modification; you may not use this file except in\n// compliance with the Apache License and the following modification to it:\n// Section 6. Trademarks. is deleted and replaced with:\n//\n// 6. Trademarks. This License does not grant permission to use the trade\n//    names, trademarks, service marks, or product names of the Licensor\n//    and its affiliates, except as required to comply with Section 4(c) of\n//    the License and to reproduce the content of the NOTICE file.\n//\n// You may obtain a copy of the Apache 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 Apache License with the above modification is\n// distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n// KIND, either express or implied. See the Apache License for the specific\n// language governing permissions and limitations under the Apache License.\n//\n\n#include \"pxr/pxr.h\"\n#include \"pxr/base/gf/ray.h\"\n#include \"pxr/base/gf/line.h\"\n#include \"pxr/base/gf/lineSeg.h\"\n#include \"pxr/base/gf/plane.h\"\n#include \"pxr/base/gf/range3d.h\"\n\n#include \"pxr/base/tf/pyUtils.h\"\n#include \"pxr/base/tf/wrapTypeHelpers.h\"\n\n#include <boost/python/class.hpp>\n#include <boost/python/def.hpp>\n#include <boost/python/copy_const_reference.hpp>\n#include <boost/python/operators.hpp>\n#include <boost/python/return_arg.hpp>\n#include <boost/python/tuple.hpp>\n\n#include <string>\n\nusing namespace boost::python;\n\nusing std::string;\n\nPXR_NAMESPACE_USING_DIRECTIVE\n\nnamespace {\n\nstatic void\nSetStartPointHelper( GfRay &self, const GfVec3d &startPoint ) {\n    self.SetPointAndDirection( startPoint, self.GetDirection() );\n}\n\nstatic void\nSetDirectionHelper( GfRay &self, const GfVec3d &direction ) {\n    self.SetPointAndDirection( self.GetStartPoint(), direction );\n}\n\nstatic tuple\nFindClosestPointHelper( const GfRay &self, const GfVec3d &point ) {\n    double rayDist;\n    GfVec3d result = self.FindClosestPoint( point, &rayDist );\n    return make_tuple( result, rayDist );\n}\n\nstatic tuple\nFindClosestPointsHelper1( const GfRay &l1, const GfLine &l2 )\n{\n    GfVec3d p1(0), p2(0);\n    double t1 = 0.0, t2 = 0.0;\n    bool result = GfFindClosestPoints( l1, l2, &p1, &p2, &t1, &t2 );\n    return make_tuple( result, p1, p2, t1, t2 );\n}\n\nstatic tuple\nFindClosestPointsHelper2( const GfRay &l1, const GfLineSeg &l2 )\n{\n    GfVec3d p1(0), p2(0);\n    double t1 = 0.0, t2 = 0.0;\n    bool result = GfFindClosestPoints( l1, l2, &p1, &p2, &t1, &t2 );\n    return make_tuple( result, p1, p2, t1, t2 );\n}\n\nstatic tuple\nIntersectHelper1( const GfRay &self, const GfVec3d &p0,\n                  const GfVec3d &p1, const GfVec3d &p2 )\n{\n    double dist = 0;\n    GfVec3d barycentricCoords(0);\n    bool frontFacing = false;\n    bool result =\n        self.Intersect( p0, p1, p2, &dist, &barycentricCoords, &frontFacing );\n    return make_tuple( result, dist, barycentricCoords, frontFacing );\n}\n\nstatic tuple\nIntersectHelper2( const GfRay &self, const GfPlane &plane )\n{\n    double dist = 0;\n    bool frontFacing = false;\n    bool result = self.Intersect( plane, &dist, &frontFacing );\n    return make_tuple( result, dist, frontFacing );\n}\n\nstatic tuple\nIntersectHelper3( const GfRay &self, const GfRange3d &box )\n{\n    double enterDist = 0, exitDist = 0;\n    bool result = self.Intersect( box, &enterDist, &exitDist );\n    return make_tuple( result, enterDist, exitDist );\n}\n\nstatic tuple\nIntersectHelper4( const GfRay &self, const GfVec3d& center, double radius )\n{\n    double enterDist = 0, exitDist = 0;\n    bool result = self.Intersect( center, radius, &enterDist, &exitDist );\n    return make_tuple( result, enterDist, exitDist );\n}\n\nstatic tuple\nIntersectHelper5(const GfRay &self, \n                 const GfVec3d &origin, \n                 const GfVec3d &axis,\n                 double radius)\n{\n    double enter = 0, exit = 0;\n    bool result = self.Intersect(origin, axis, radius, &enter, &exit);\n    return make_tuple(result, enter, exit);\n}\n\nstatic tuple\nIntersectHelper6(const GfRay &self, \n                 const GfVec3d &origin, \n                 const GfVec3d &axis,\n                 double radius,\n                 double height)\n{\n    double enter = 0, exit = 0;\n    bool result = self.Intersect(origin, axis, radius, height, &enter, &exit);\n    return make_tuple(result, enter, exit);\n}\n\nstatic string _Repr(GfRay const &self) {\n    return TF_PY_REPR_PREFIX + \"Ray(\" + TfPyRepr(self.GetStartPoint()) + \", \" +\n        TfPyRepr(self.GetDirection()) + \")\";\n}\n\n} // anonymous namespace \n\nvoid wrapRay()\n{    \n    typedef GfRay This;\n\n    def(\"FindClosestPoints\", FindClosestPointsHelper1, \n        \"FindClosestPoints( r1, l2 ) -> tuple<intersects=bool, \"\n        \"p1 = GfVec3d, p2 = GfVec3d, t1 = double, t2 = double>\\n\"\n        \"\\n\"\n        \"r1 : GfRay\\n\"\n        \"l2 : GfLine\\n\"\n        \"\\n\"\n        \"Computes the closest points between a ray and a line,\\n\"\n        \"returning a tuple. The first item in the tuple is true if \"\n        \"they intersect. The two points are returned in p1 and p2.\\n\"\n        \"The parametric distance of each point on the ray and line is\\n\"\n        \"returned in t1 and t2.\\n\"\n        \"----------------------------------------------------------------------\"\n        );\n    def(\"FindClosestPoints\", FindClosestPointsHelper2, \n        \"FindClosestPoints( r1, s2 ) -> tuple<intersects = bool, \"\n        \"p1 = GfVec3d, p2 = GfVec3d, t1 = double, t2 = double>\\n\"\n        \"\\n\"\n        \"r1 : GfRay\\n\"\n        \"s2 : GfLineSeg\\n\"\n        \"\\n\"\n        \"Computes the closest points between a ray and a line segment,\\n\"\n        \"returning a tuple. The first item in the tuple is true if \"\n        \"they intersect. The two points are returned in p1 and p2.\\n\"\n        \"The parametric distance of each point on the ray and line\\n\"\n        \"segment is returned in t1 and t2.\\n\"\n        \"----------------------------------------------------------------------\"\n        );\n\n    class_<This>(\"Ray\", \"\", init<>())\n        .def(init< const GfVec3d &, const GfVec3d & >())\n\n        .def(TfTypePythonClass())\n\n        .def(\"SetPointAndDirection\",\n             &This::SetPointAndDirection, return_self<>())\n        .def(\"SetEnds\", &This::SetEnds, return_self<>())\n\n        .add_property( \"startPoint\", make_function\n                       (&This::GetStartPoint,\n                        return_value_policy<copy_const_reference>()),\n                       SetStartPointHelper )\n        .add_property( \"direction\", make_function\n                       (&This::GetDirection,\n                        return_value_policy<copy_const_reference>()),\n                       SetDirectionHelper )\n\n        .def(\"GetPoint\", &This::GetPoint )\n\n        .def(\"FindClosestPoint\", FindClosestPointHelper)\n\n        .def(\"Transform\", &This::Transform, return_self<>())\n        \n        .def(\"Intersect\", IntersectHelper1,\n             \"Intersect( p0, p1, p2 ) -> tuple<intersects = bool, dist =\\n\"\n             \"float, barycentric = GfVec3d, frontFacing = bool>\\n\"\n             \"\\n\"\n             \"Intersects the ray with the triangle formed by points p0,\\n\"\n             \"p1, and p2.  The first item in the tuple is true if the ray\\n\"\n             \"intersects the triangle. dist is the the parametric\\n\"\n             \"distance to the intersection point, the barycentric\\n\"\n             \"coordinates of the intersection point, and the front-facing\\n\"\n             \"flag. The barycentric coordinates are defined with respect\\n\"\n             \"to the three vertices taken in order.  The front-facing\\n\"\n             \"flag is True if the intersection hit the side of the\\n\"\n             \"triangle that is formed when the vertices are ordered\\n\"\n             \"counter-clockwise (right-hand rule).\\n\"\n             \"\\n\"\n             \"Barycentric coordinates are defined to sum to 1 and satisfy\\n\"\n             \"this relationsip:\\n\"\n             \"\\n\"\n             \"    intersectionPoint = (barycentricCoords[0] * p0 +\\n\"\n             \"                         barycentricCoords[1] * p1 +\\n\"\n             \"                         barycentricCoords[2] * p2);\\n\"\n             \"----------------------------------------------------------------------\"\n            )\n        .def( \"Intersect\", IntersectHelper2,\n              \"Intersect( plane ) -> tuple<intersects = bool, dist = float,\\n\"\n              \"frontFacing = bool>\\n\"\n              \"\\n\"\n              \"Intersects the ray with the Gf.Plane.  The first item in\\n\"\n              \"the returned tuple is true if the ray intersects the plane.\\n\"\n              \"dist is the parametric distance to the intersection point\\n\"\n              \"and frontfacing is true if the intersection is on the side\\n\"\n              \"of the plane toward which the plane's normal points.\\n\"\n             \"----------------------------------------------------------------------\"\n            )\n        .def( \"Intersect\", IntersectHelper3,\n              \"Intersect( range3d ) -> tuple<intersects = bool, enterDist\\n\"\n              \"= float, exitDist = float>\\n\"\n              //\\n\"\n              \"Intersects the plane with an axis-aligned box in a\\n\"\n              \"Gf.Range3d.  intersects is true if the ray intersects it at\\n\"\n              \"all within bounds. If there is an intersection then enterDist\\n\"\n              \"and exitDist will be the parametric distances to the two\\n\"\n              \"intersection points.\\n\"\n              \"----------------------------------------------------------------------\"\n            )\n        .def( \"Intersect\", IntersectHelper4,\n              \"Intersect( center, radius ) -> tuple<intersects = bool,\\n\"\n              \"enterDist = float, exitDist = float>\\n\"\n              \"\\n\"\n              \"Intersects the plane with an sphere. intersects is true if\\n\"\n              \"the ray intersects it at all within the sphere. If there is\\n\"\n              \"an intersection then enterDist and exitDist will be the\\n\"\n              \"parametric distances to the two intersection points.\\n\"\n              \"----------------------------------------------------------------------\"\n            )\n        .def( \"Intersect\", IntersectHelper5,\n              \"Intersect( origin, axis, radius ) -> tuple<intersects = bool,\\n\"\n              \"enterDist = float, exitDist = float>\\n\"\n              \"\\n\"\n              \"Intersects the plane with an infinite cylinder. intersects\\n\"\n              \"is true if the ray intersects it at all within the\\n\"\n              \"sphere. If there is an intersection then enterDist and\\n\"\n              \"exitDist will be the parametric distances to the two\\n\"\n              \"intersection points.\\n\"\n              \"----------------------------------------------------------------------\"\n            )\n        .def( \"Intersect\", IntersectHelper6,\n              \"Intersect( origin, axis, radius, height ) -> \\n\"\n              \"tuple<intersects = bool, enterDist = float, exitDist = float>\\n\"\n              \"\\n\"\n              \"Intersects the plane with an cylinder. intersects\\n\"\n              \"is true if the ray intersects it at all within the\\n\"\n              \"sphere. If there is an intersection then enterDist and\\n\"\n              \"exitDist will be the parametric distances to the two\\n\"\n              \"intersection points.\\n\"\n              \"----------------------------------------------------------------------\"\n            )\n\n        .def( str(self) )\n        .def( self == self )\n        .def( self != self )\n\n        .def(\"__repr__\", _Repr)\n\n        ;\n    \n}\n", "meta": {"hexsha": "25cf5ad84e4bbd184a222417c5a22137c9b5b63c", "size": 11604, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pxr/base/lib/gf/wrapRay.cpp", "max_stars_repo_name": "YuqiaoZhang/USD", "max_stars_repo_head_hexsha": "bf3a21e6e049486441440ebf8c0387db2538d096", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 88.0, "max_stars_repo_stars_event_min_datetime": "2018-07-13T01:22:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T22:15:27.000Z", "max_issues_repo_path": "pxr/base/lib/gf/wrapRay.cpp", "max_issues_repo_name": "YuqiaoZhang/USD", "max_issues_repo_head_hexsha": "bf3a21e6e049486441440ebf8c0387db2538d096", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-14T23:57:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-14T23:57:51.000Z", "max_forks_repo_path": "pxr/base/lib/gf/wrapRay.cpp", "max_forks_repo_name": "YuqiaoZhang/USD", "max_forks_repo_head_hexsha": "bf3a21e6e049486441440ebf8c0387db2538d096", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2018-06-06T03:39:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-28T23:02:42.000Z", "avg_line_length": 38.9395973154, "max_line_length": 86, "alphanum_fraction": 0.5776456394, "num_tokens": 2908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2942546202574461}}
{"text": "/* pcmsolver_copyright_start */\n/*\n *     PCMSolver, an API for the Polarizable Continuum Model\n *     Copyright (C) 2013-2016 Roberto Di Remigio, Luca Frediani and contributors\n *     \n *     This file is part of PCMSolver.\n *     \n *     PCMSolver is free software: you can redistribute it and/or modify\n *     it under the terms of the GNU Lesser General Public License as published by\n *     the Free Software Foundation, either version 3 of the License, or\n *     (at your option) any later version.\n *     \n *     PCMSolver is distributed in the hope that it will be useful,\n *     but WITHOUT ANY WARRANTY; without even the implied warranty of\n *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *     GNU Lesser General Public License for more details.\n *     \n *     You should have received a copy of the GNU Lesser General Public License\n *     along with PCMSolver.  If not, see <http://www.gnu.org/licenses/>.\n *     \n *     For information on the complete list of contributors to the\n *     PCMSolver API, see: <http://pcmsolver.readthedocs.io/>\n */\n/* pcmsolver_copyright_end */\n\n#ifndef IGREENSFUNCTION_HPP\n#define IGREENSFUNCTION_HPP\n\n#include <iosfwd>\n#include <vector>\n\n#include \"Config.hpp\"\n\n#include <Eigen/Core>\n\nclass Element;\n\n#include \"dielectric_profile/ProfileTypes.hpp\"\n\n/*! \\file IGreensFunction.hpp\n *  \\class IGreensFunction\n *  \\brief Interface for Green's function classes\n *  \\author Luca Frediani and Roberto Di Remigio\n *  \\date 2012-2015\n *\n *  The Non-Virtual Interface (NVI) idiom is used. Notice also that some of the return\n *  types are in some cases \"auto\", meaning that we will let the compiler deduce\n *  them.\n */\n\n/*! \\typedef KernelS\n *  \\brief functor handle to the kernelS method\n */\ntypedef pcm::function<double(const Eigen::Vector3d &, const Eigen::Vector3d &)> KernelS;\n\n/*! \\typedef KernelD\n *  \\brief functor handle to the kernelD method\n */\ntypedef pcm::function<double(const Eigen::Vector3d &, const Eigen::Vector3d &, const Eigen::Vector3d &)> KernelD;\n\nclass IGreensFunction\n{\n  public:\n    virtual ~IGreensFunction() {}\n    /*! Returns value of the kernel of the \\f$\\mathcal{S}\\f$ integral operator, i.e. the value of the\n     *  Greens's function for the pair of points p1, p2: \\f$ G(\\mathbf{p}_1, \\mathbf{p}_2)\\f$\n     *  \\param[in] p1 first point\n     *  \\param[in] p2 second point\n     */\n    double kernelS(const Eigen::Vector3d & p1, const Eigen::Vector3d &p2) const {\n      return kernelS_impl(p1, p2);\n    }\n    /*! Returns value of the kernel of the \\f$\\mathcal{D}\\f$ integral operator for the pair of points p1, p2:\n     *  \\f$ [\\boldsymbol{\\varepsilon}\\nabla_{\\mathbf{p_2}}G(\\mathbf{p}_1, \\mathbf{p}_2)]\\cdot \\mathbf{n}_{\\mathbf{p}_2}\\f$\n     *  To obtain the kernel of the \\f$\\mathcal{D}^\\dagger\\f$ operator call this methods with \\f$\\mathbf{p}_1\\f$\n     *  and \\f$\\mathbf{p}_2\\f$ exchanged and with \\f$\\mathbf{n}_{\\mathbf{p}_2} = \\mathbf{n}_{\\mathbf{p}_1}\\f$\n     *  \\param[in] direction the direction\n     *  \\param[in]        p1 first point\n     *  \\param[in]        p2 second point\n     */\n    double kernelD(const Eigen::Vector3d & direction, const Eigen::Vector3d & p1, const Eigen::Vector3d & p2) const {\n      return kernelD_impl(direction, p1, p2);\n    }\n\n    KernelS exportKernelS() const {\n      return exportKernelS_impl();\n    }\n    KernelD exportKernelD() const {\n      return exportKernelD_impl();\n    }\n\n    /*! Whether the Green's function describes a uniform environment */\n    virtual bool uniform() const = 0;\n    /*! Returns a dielectric permittivity profile */\n    virtual Permittivity permittivity() const = 0;\n\n    /*! Calculates the matrix representation of the S operator\n     *  \\param[in] e list of finite elements\n     */\n    virtual Eigen::MatrixXd singleLayer(const std::vector<Element> & e) const = 0;\n    /*! Calculates the matrix representation of the D operator\n     *  \\param[in] e list of finite elements\n     */\n    virtual Eigen::MatrixXd doubleLayer(const std::vector<Element> & e) const = 0;\n\n    friend std::ostream & operator<<(std::ostream & os, IGreensFunction & gf) {\n      return gf.printObject(os);\n    }\n  protected:\n    /*! Returns value of the kernel of the \\f$\\mathcal{S}\\f$ integral operator, i.e. the value of the\n     *  Greens's function for the pair of points p1, p2: \\f$ G(\\mathbf{p}_1, \\mathbf{p}_2)\\f$\n     *  \\param[in] p1 first point\n     *  \\param[in] p2 second point\n     */\n    virtual double kernelS_impl(const Eigen::Vector3d & p1, const Eigen::Vector3d &p2) const = 0;\n    /*! Returns value of the kernel of the \\f$\\mathcal{D}\\f$ integral operator for the pair of points p1, p2:\n     *  \\f$ [\\boldsymbol{\\varepsilon}\\nabla_{\\mathbf{p_2}}G(\\mathbf{p}_1, \\mathbf{p}_2)]\\cdot \\mathbf{n}_{\\mathbf{p}_2}\\f$\n     *  To obtain the kernel of the \\f$\\mathcal{D}^\\dagger\\f$ operator call this methods with \\f$\\mathbf{p}_1\\f$\n     *  and \\f$\\mathbf{p}_2\\f$ exchanged and with \\f$\\mathbf{n}_{\\mathbf{p}_2} = \\mathbf{n}_{\\mathbf{p}_1}\\f$\n     *  \\param[in] direction the direction\n     *  \\param[in]        p1 first point\n     *  \\param[in]        p2 second point\n     */\n    virtual double kernelD_impl(const Eigen::Vector3d & direction,\n        const Eigen::Vector3d & p1, const Eigen::Vector3d & p2) const = 0;\n    virtual KernelS exportKernelS_impl() const = 0;\n    virtual KernelD exportKernelD_impl() const = 0;\n    virtual std::ostream & printObject(std::ostream & os) = 0;\n};\n\n#endif // IGREENSFUNCTION_HPP\n", "meta": {"hexsha": "55d8df56ff3894571236b13d1409f460b23c67ed", "size": 5460, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/PCMSolver/PCMSolver-source/src/green/IGreensFunction.hpp", "max_stars_repo_name": "robertodr/externalize", "max_stars_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-02-15T22:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-15T22:16:34.000Z", "max_issues_repo_path": "external/PCMSolver/PCMSolver-source/src/green/IGreensFunction.hpp", "max_issues_repo_name": "robertodr/externalize", "max_issues_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/PCMSolver/PCMSolver-source/src/green/IGreensFunction.hpp", "max_forks_repo_name": "robertodr/externalize", "max_forks_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3636363636, "max_line_length": 122, "alphanum_fraction": 0.6679487179, "num_tokens": 1580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.5234203489363239, "lm_q1q2_score": 0.294254612578485}}
{"text": "#ifndef FLOW_H_\n#define FLOW_H_\n#include <Eigen/Core>\n#include <list>\n#include <map>\n#include <vector>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/boykov_kolmogorov_max_flow.hpp>\n#include <boost/graph/edmonds_karp_max_flow.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n\nusing namespace boost;\nusing namespace Eigen;\n\ntypedef int EdgeWeightType;\n\n// clang-format off\ntypedef adjacency_list_traits < vecS, vecS, directedS > Traits;\ntypedef adjacency_list < vecS, vecS, directedS,\n    property < vertex_name_t, std::string,\n    property < vertex_index_t, long,\n    property < vertex_color_t, boost::default_color_type,\n    property < vertex_distance_t, long,\n    property < vertex_predecessor_t, Traits::edge_descriptor > > > > >,\n\n    property < edge_capacity_t, EdgeWeightType,\n    property < edge_residual_capacity_t, EdgeWeightType,\n    property < edge_reverse_t, Traits::edge_descriptor > > > > Graph;\n// clang-format on\n\nvoid AddEdge(Traits::vertex_descriptor& v1, Traits::vertex_descriptor& v2,\n             property_map<Graph, edge_reverse_t>::type& rev, const double capacity, Graph& g);\n\nvoid AddDirectEdge(Traits::vertex_descriptor& v1, Traits::vertex_descriptor& v2,\n                   property_map<Graph, edge_reverse_t>::type& rev, const int capacity,\n                   const int inv_capacity, Graph& g, Traits::edge_descriptor& e1,\n                   Traits::edge_descriptor& e2);\n\nclass MaxFlowHelper {\n   public:\n    MaxFlowHelper() {}\n    virtual ~MaxFlowHelper(){};\n    virtual void resize(int n, int m) = 0;\n    virtual int compute() = 0;\n    virtual void AddEdge(int x, int y, int c, int rc, int v) = 0;\n    virtual void Apply(std::vector<Vector2i>& edge_diff) = 0;\n};\n\nclass BoykovMaxFlowHelper : public MaxFlowHelper {\n   public:\n    BoykovMaxFlowHelper() {\n        rev = get(edge_reverse, g);\n        num = 0;\n    }\n    int num;\n    void resize(int n, int m) {\n        vertex_descriptors.resize(n);\n        for (int i = 0; i < n; ++i) {\n            vertex_descriptors[i] = add_vertex(g);\n        }\n        num = n;\n    }\n    int compute() {\n        EdgeWeightType flow =\n            boykov_kolmogorov_max_flow(g, vertex_descriptors.front(), vertex_descriptors.back());\n        return flow;\n    }\n    void AddEdge(int x, int y, int c, int rc, int v) {\n        Traits::edge_descriptor e1, e2;\n        AddDirectEdge(vertex_descriptors[x], vertex_descriptors[y], rev, c, rc, g, e1, e2);\n        if (v != -1) {\n            edge_to_variables[e1] = std::make_pair(v, -1);\n            edge_to_variables[e2] = std::make_pair(v, 1);\n        }\n    }\n    void Apply(std::vector<Vector2i>& edge_diff) {\n        property_map<Graph, edge_capacity_t>::type capacity = get(edge_capacity, g);\n        property_map<Graph, edge_residual_capacity_t>::type residual_capacity =\n            get(edge_residual_capacity, g);\n\n        graph_traits<Graph>::vertex_iterator u_iter, u_end;\n        graph_traits<Graph>::out_edge_iterator ei, e_end;\n        for (tie(u_iter, u_end) = vertices(g); u_iter != u_end; ++u_iter)\n            for (tie(ei, e_end) = out_edges(*u_iter, g); ei != e_end; ++ei)\n                if (capacity[*ei] > 0) {\n                    int flow = (capacity[*ei] - residual_capacity[*ei]);\n                    if (flow > 0) {\n                        auto it = edge_to_variables.find(*ei);\n                        if (it != edge_to_variables.end()) {\n                            edge_diff[it->second.first / 2][it->second.first % 2] +=\n                                it->second.second * flow;\n                        }\n                        /*\n                        int64_t key = (int64_t)*u_iter * num + target(*ei, g);\n                        auto q = edge_to_variable[key];\n                        edge_diff[q.first / 2][q.first % 2] += q.second * flow;\n                        if (abs(edge_diff[q.first/2][q.first%2]) > 2) {\n                            printf(\"Edge %d %d\\n\", *u_iter, target(*ei, g));\n                            printf(\"Apply error 1: %d %d %d\\n\",\n                                   edge_diff[q.first / 2][q.first % 2],\n                                   q.second, flow);\n                            printf(\"capacity %d\\n\", capacity[*ei]);\n                            exit(0);\n                        }\n                         */\n                    }\n                }\n    }\n    Graph g;\n    property_map<Graph, edge_reverse_t>::type rev;\n    std::vector<Traits::vertex_descriptor> vertex_descriptors;\n    std::map<Traits::edge_descriptor, std::pair<int, int>> edge_to_variables;\n};\n\nint flow(std::vector<std::map<int, std::pair<int, int>>>& graph);\n\ninline void AddEdge(Traits::vertex_descriptor& v1, Traits::vertex_descriptor& v2,\n                    property_map<Graph, edge_reverse_t>::type& rev, const double capacity,\n                    Graph& g) {\n    Traits::edge_descriptor e1 = add_edge(v1, v2, g).first;\n    Traits::edge_descriptor e2 = add_edge(v2, v1, g).first;\n    put(edge_capacity, g, e1, capacity);\n    put(edge_capacity, g, e2, capacity);\n\n    rev[e1] = e2;\n    rev[e2] = e1;\n}\n\ninline void AddDirectEdge(Traits::vertex_descriptor& v1, Traits::vertex_descriptor& v2,\n                          property_map<Graph, edge_reverse_t>::type& rev, const int capacity,\n                          const int inv_capacity, Graph& g, Traits::edge_descriptor& e1,\n                          Traits::edge_descriptor& e2) {\n    e1 = add_edge(v1, v2, g).first;\n    e2 = add_edge(v2, v1, g).first;\n    put(edge_capacity, g, e1, capacity);\n    put(edge_capacity, g, e2, inv_capacity);\n\n    rev[e1] = e2;\n    rev[e2] = e1;\n}\n\nclass ECMaxFlowHelper : public MaxFlowHelper {\n   public:\n    struct FlowInfo {\n        int id;\n        int capacity, flow;\n        int v, d;\n        FlowInfo* rev;\n    };\n    struct SearchInfo {\n        SearchInfo(int _id, int _prev_id, FlowInfo* _info)\n            : id(_id), prev_id(_prev_id), info(_info) {}\n        int id;\n        int prev_id;\n        FlowInfo* info;\n    };\n    ECMaxFlowHelper() { num = 0; }\n    int num;\n    std::vector<FlowInfo*> variable_to_edge;\n    void resize(int n, int m) {\n        graph.resize(n);\n        variable_to_edge.resize(m, 0);\n        num = n;\n    }\n    void AddEdge(int x, int y, int c, int rc, int v) {\n        FlowInfo flow;\n        flow.id = y;\n        flow.capacity = c;\n        flow.flow = 0;\n        flow.v = v;\n        flow.d = -1;\n        graph[x].push_back(flow);\n        auto& f1 = graph[x].back();\n        flow.id = x;\n        flow.capacity = rc;\n        flow.flow = 0;\n        flow.v = v;\n        flow.d = 1;\n        graph[y].push_back(flow);\n        auto& f2 = graph[y].back();\n        f2.rev = &f1;\n        f1.rev = &f2;\n    }\n\n    void ApplyFlow(int v1, int v2, int flow) {\n        for (auto& it : graph[v1]) {\n            if (it.id == v2) {\n                it.flow += flow;\n                break;\n            }\n        }\n    }\n    int compute() {\n        int total_flow = 0;\n        int count = 0;\n        while (true) {\n            count += 1;\n            std::vector<int> vhash(num, 0);\n            std::vector<SearchInfo> q;\n            q.push_back(SearchInfo(0, -1, 0));\n            vhash[0] = 1;\n            int q_front = 0;\n            bool found = false;\n            while (q_front < q.size()) {\n                int vert = q[q_front].id;\n                for (auto& l : graph[vert]) {\n                    if (vhash[l.id] || l.capacity <= l.flow) continue;\n                    q.push_back(SearchInfo(l.id, q_front, &l));\n                    vhash[l.id] = 1;\n                    if (l.id == num - 1) {\n                        found = true;\n                        break;\n                    }\n                }\n                if (found) break;\n                q_front += 1;\n            }\n            if (q_front == q.size()) break;\n            int loc = q.size() - 1;\n            while (q[loc].prev_id != -1) {\n                q[loc].info->flow += 1;\n                q[loc].info->rev->flow -= 1;\n                loc = q[loc].prev_id;\n                //                int prev_v = q[loc].id;\n                //                ApplyFlow(prev_v, current_v, 1);\n                //                ApplyFlow(current_v, prev_v, -1);\n            }\n            total_flow += 1;\n        }\n        return total_flow;\n    }\n    void Apply(std::vector<Vector2i>& edge_diff) {\n        for (int i = 0; i < graph.size(); ++i) {\n            for (auto& flow : graph[i]) {\n                if (flow.flow > 0 && flow.v != -1) {\n                    if (flow.flow > 0) {\n                        edge_diff[flow.v / 2][flow.v % 2] += flow.d * flow.flow;\n                        if (abs(edge_diff[flow.v / 2][flow.v % 2]) > 2) {\n                        }\n                    }\n                }\n            }\n        }\n    }\n    std::vector<std::list<FlowInfo>> graph;\n};\n#endif\n", "meta": {"hexsha": "f8a4291fb9967d8ddbf9ccc65c45cc9afcb4bf26", "size": 8813, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "data/QuadriFlow/src/flow.hpp", "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/QuadriFlow/src/flow.hpp", "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/QuadriFlow/src/flow.hpp", "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": 35.3935742972, "max_line_length": 97, "alphanum_fraction": 0.514580733, "num_tokens": 2239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.29422624734834735}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2021 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n\n\n#include \"Lagrangian2d1DR.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 DEBUG_NOCOLOR\n// #define DEBUG_STDOUT\n// #define DEBUG_MESSAGES\n#include \"siconos_debug.h\"\n\n\nvoid Lagrangian2d1DR::initialize(Interaction& inter)\n{\n  LagrangianR::initialize(inter);\n  //proj_with_q  _jachqProj.reset(new SimpleMatrix(_jachq->size(0),_jachq->size(1)));\n\n  if((inter.getSizeOfDS() !=3) and (inter.getSizeOfDS() !=6))\n  {\n    THROW_EXCEPTION(\"Lagrangian2d1DR::initialize(Interaction& inter). The size of ds must of size 3\");\n  }\n  unsigned int qSize = 3 * (inter.getSizeOfDS() / 3);\n  _jachq.reset(new SimpleMatrix(1, qSize));\n}\n\nvoid Lagrangian2d1DR::computeJachq(const BlockVector& q, BlockVector& z)\n{\n  DEBUG_BEGIN(\"Lagrangian2d1DR::computeJachq(Interaction& inter, SP::BlockVector q0 \\n\");\n\n  double Nx = _Nc->getValue(0);\n  double Ny = _Nc->getValue(1);\n  double Px = _Pc1->getValue(0);\n  double Py = _Pc1->getValue(1);\n  double G1x = q.getValue(0);\n  double G1y = q.getValue(1);\n\n  _jachq->setValue(0,0,Nx);\n  _jachq->setValue(0,1,Ny);\n  _jachq->setValue(0,2,(G1y-Py)*Nx - (G1x-Px)*Ny);\n\n\n  if(q.size() ==6)\n  {\n    DEBUG_PRINT(\"take into account second ds\\n\");\n    double G2x = q.getValue(3);\n    double G2y = q.getValue(4);\n\n    _jachq->setValue(0,3,-Nx);\n    _jachq->setValue(0,4,-Ny);\n    _jachq->setValue(0,5,- ((G2y-Py)*Nx - (G2x-Px)*Ny));\n  }\n  DEBUG_EXPR(_jachq->display(););\n  DEBUG_END(\"Lagrangian2d1DR::computeJachq(Interaction& inter, SP::BlockVector q0) \\n\");\n\n}\n\ndouble Lagrangian2d1DR::distance() const\n{\n  DEBUG_BEGIN(\"Lagrangian2d1DR::distance(...)\\n\")\n  SiconosVector dpc(*_Pc2 - *_Pc1);\n  DEBUG_END(\"Lagrangian2d1DR::distance(...)\\n\")\n  return dpc.norm2() * (inner_prod(*_Nc, dpc) >= 0 ? -1 : 1);\n\n}\n\nvoid Lagrangian2d1DR::computeh(const BlockVector& q, BlockVector& z, SiconosVector& y)\n{\n  DEBUG_BEGIN(\"Lagrangian2d1DR::computeh(...)\\n\");\n  DEBUG_EXPR(q.display());\n\n  LagrangianScleronomousR::computeh(q, z, y);\n  y.setValue(0, distance());\n  DEBUG_EXPR(y.display(););\n  DEBUG_EXPR(display(););\n  DEBUG_END(\"Lagrangian2d1DR::computeh(...)\\n\")\n}\nvoid Lagrangian2d1DR::display() const\n{\n  LagrangianR::display();\n\n  std::cout << \" _Pc1 :\" << std::endl;\n  if(_Pc1)\n    _Pc1->display();\n  else\n    std::cout << \" nullptr :\" << std::endl;\n\n  std::cout << \" _Pc2 :\" << std::endl;\n  if(_Pc2)\n    _Pc2->display();\n  else\n    std::cout << \" nullptr :\" << std::endl;\n\n  std::cout << \" _Nc :\" << std::endl;\n  if(_Nc)\n    _Nc->display();\n  else\n    std::cout << \" nullptr :\" << std::endl;\n  std::cout << \" _relNc :\" << std::endl;\n  if(_relNc)\n    _relNc->display();\n  else\n    std::cout << \" nullptr :\" << std::endl;\n\n}\n", "meta": {"hexsha": "e4d9a7fb13578942cfb3ab1f52b1159f35d9dd35", "size": 3443, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/modelingTools/Lagrangian2d1DR.cpp", "max_stars_repo_name": "siconos/siconos", "max_stars_repo_head_hexsha": "db65b1b2ae7b3efa5b5b8e0ebcac43034ac2f195", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "kernel/src/modelingTools/Lagrangian2d1DR.cpp", "max_issues_repo_name": "siconos/siconos", "max_issues_repo_head_hexsha": "db65b1b2ae7b3efa5b5b8e0ebcac43034ac2f195", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "kernel/src/modelingTools/Lagrangian2d1DR.cpp", "max_forks_repo_name": "siconos/siconos", "max_forks_repo_head_hexsha": "db65b1b2ae7b3efa5b5b8e0ebcac43034ac2f195", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 27.544, "max_line_length": 102, "alphanum_fraction": 0.6703456288, "num_tokens": 1127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2942262407273221}}
{"text": "// Copyright 2020 Tier IV, 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#include <bits/stdc++.h>\n#include <tf2/LinearMath/Matrix3x3.h>\n#include <tf2/LinearMath/Quaternion.h>\n#include <tf2/utils.h>\n#include <tf2_geometry_msgs/tf2_geometry_msgs.h>\n#define EIGEN_MPL2_ONLY\n#include \"multi_object_tracker/tracker/model/unknown_tracker.hpp\"\n#include \"multi_object_tracker/utils/utils.hpp\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <autoware_utils/autoware_utils.hpp>\n\nUnknownTracker::UnknownTracker(\n  const rclcpp::Time & time, const autoware_auto_perception_msgs::msg::DetectedObject & object)\n: Tracker(time, object.classification),\n  logger_(rclcpp::get_logger(\"UnknownTracker\")),\n  last_update_time_(time),\n  z_(object.kinematics.pose_with_covariance.pose.position.z)\n{\n  object_ = object;\n\n  // initialize params\n  ekf_params_.use_measurement_covariance = false;\n  float q_stddev_x = 0.0;                              // [m/s]\n  float q_stddev_y = 0.0;                              // [m/s]\n  float q_stddev_vx = autoware_utils::kmph2mps(0.1);   // [m/(s*s)]\n  float q_stddev_vy = autoware_utils::kmph2mps(0.1);   // [m/(s*s)]\n  float r_stddev_x = 0.4;                              // [m]\n  float r_stddev_y = 0.4;                              // [m]\n  float p0_stddev_x = 1.0;                             // [m/s]\n  float p0_stddev_y = 1.0;                             // [m/s]\n  float p0_stddev_vx = autoware_utils::kmph2mps(0.1);  // [m/(s*s)]\n  float p0_stddev_vy = autoware_utils::kmph2mps(0.1);  // [m/(s*s)]\n  ekf_params_.q_cov_x = std::pow(q_stddev_x, 2.0);\n  ekf_params_.q_cov_y = std::pow(q_stddev_y, 2.0);\n  ekf_params_.q_cov_vx = std::pow(q_stddev_vx, 2.0);\n  ekf_params_.q_cov_vy = std::pow(q_stddev_vy, 2.0);\n  ekf_params_.r_cov_x = std::pow(r_stddev_x, 2.0);\n  ekf_params_.r_cov_y = std::pow(r_stddev_y, 2.0);\n  ekf_params_.p0_cov_x = std::pow(p0_stddev_x, 2.0);\n  ekf_params_.p0_cov_y = std::pow(p0_stddev_y, 2.0);\n  ekf_params_.p0_cov_vx = std::pow(p0_stddev_vx, 2.0);\n  ekf_params_.p0_cov_vy = std::pow(p0_stddev_vy, 2.0);\n  max_vx_ = autoware_utils::kmph2mps(5);  // [m/s]\n  max_vy_ = autoware_utils::kmph2mps(5);  // [m/s]\n\n  // initialize X matrix\n  Eigen::MatrixXd X(ekf_params_.dim_x, 1);\n  X(IDX::X) = object.kinematics.pose_with_covariance.pose.position.x;\n  X(IDX::Y) = object.kinematics.pose_with_covariance.pose.position.y;\n  if (object.kinematics.has_twist) {\n    X(IDX::VX) = object.kinematics.twist_with_covariance.twist.linear.x;\n    X(IDX::VY) = object.kinematics.twist_with_covariance.twist.linear.y;\n  } else {\n    X(IDX::VX) = 0.0;\n    X(IDX::VY) = 0.0;\n  }\n\n  // initialize P matrix\n  Eigen::MatrixXd P = Eigen::MatrixXd::Zero(ekf_params_.dim_x, ekf_params_.dim_x);\n  if (\n    !ekf_params_.use_measurement_covariance ||\n    object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::X_X] == 0.0 ||\n    object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::Y_Y] == 0.0) {\n    // Rotate the covariance matrix according to the vehicle yaw\n    // because p0_cov_x and y are in the vehicle coordinate system.\n    P(IDX::X, IDX::X) = ekf_params_.p0_cov_x;\n    P(IDX::X, IDX::Y) = 0.0;\n    P(IDX::Y, IDX::Y) = ekf_params_.p0_cov_y;\n    P(IDX::Y, IDX::X) = P(IDX::X, IDX::Y);\n    P(IDX::VX, IDX::VX) = ekf_params_.p0_cov_vx;\n    P(IDX::VY, IDX::VY) = ekf_params_.p0_cov_vy;\n  } else {\n    P(IDX::X, IDX::X) = object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::X_X];\n    P(IDX::X, IDX::Y) = object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::X_Y];\n    P(IDX::Y, IDX::Y) = object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::Y_Y];\n    P(IDX::Y, IDX::X) = object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::Y_X];\n    if (object.kinematics.has_twist_covariance) {\n      P(IDX::VX, IDX::VX) =\n        object.kinematics.twist_with_covariance.covariance[utils::MSG_COV_IDX::X_X];\n      P(IDX::VY, IDX::VY) =\n        object.kinematics.twist_with_covariance.covariance[utils::MSG_COV_IDX::Y_Y];\n    } else {\n      P(IDX::VX, IDX::VX) = ekf_params_.p0_cov_vx;\n      P(IDX::VY, IDX::VY) = ekf_params_.p0_cov_vy;\n    }\n  }\n\n  ekf_.init(X, P);\n}\n\nbool UnknownTracker::predict(const rclcpp::Time & time)\n{\n  const double dt = (time - last_update_time_).seconds();\n  bool ret = predict(dt, ekf_);\n  if (ret) {\n    last_update_time_ = time;\n  }\n  return ret;\n}\n\nbool UnknownTracker::predict(const double dt, KalmanFilter & ekf) const\n{\n  /*  == Nonlinear model ==\n   *\n   * x_{k+1}   = x_k + vx_k * dt\n   * y_{k+1}   = y_k + vx_k * dt\n   * vx_{k+1}  = vx_k\n   * vy_{k+1}  = vy_k\n   *\n   */\n\n  /*  == Linearized model ==\n   *\n   * A = [ 1, 0, dt,  0]\n   *     [ 0, 1,  0, dt]\n   *     [ 0, 0,  1,  0]\n   *     [ 0, 0,  0,  1]\n   */\n\n  // X t\n  Eigen::MatrixXd X_t(ekf_params_.dim_x, 1);  // predicted state\n  ekf.getX(X_t);\n\n  // X t+1\n  Eigen::MatrixXd X_next_t(ekf_params_.dim_x, 1);  // predicted state\n  X_next_t(IDX::X) = X_t(IDX::X) + X_t(IDX::VX) * dt;\n  X_next_t(IDX::Y) = X_t(IDX::Y) + X_t(IDX::VY) * dt;\n  X_next_t(IDX::VX) = X_t(IDX::VX);\n  X_next_t(IDX::VY) = X_t(IDX::VY);\n\n  // A\n  Eigen::MatrixXd A = Eigen::MatrixXd::Identity(ekf_params_.dim_x, ekf_params_.dim_x);\n  A(IDX::X, IDX::VX) = dt;\n  A(IDX::Y, IDX::VY) = dt;\n\n  // Q\n  Eigen::MatrixXd Q = Eigen::MatrixXd::Zero(ekf_params_.dim_x, ekf_params_.dim_x);\n  // Rotate the covariance matrix according to the vehicle yaw\n  // because q_cov_x and y are in the vehicle coordinate system.\n  Q(IDX::X, IDX::X) = ekf_params_.q_cov_x * dt * dt;\n  Q(IDX::X, IDX::Y) = 0.0;\n  Q(IDX::Y, IDX::Y) = ekf_params_.q_cov_y * dt * dt;\n  Q(IDX::Y, IDX::X) = Q(IDX::X, IDX::Y);\n  Q(IDX::VX, IDX::VX) = ekf_params_.q_cov_vx * dt * dt;\n  Q(IDX::VY, IDX::VY) = ekf_params_.q_cov_vy * dt * dt;\n  Eigen::MatrixXd B = Eigen::MatrixXd::Zero(ekf_params_.dim_x, ekf_params_.dim_x);\n  Eigen::MatrixXd u = Eigen::MatrixXd::Zero(ekf_params_.dim_x, 1);\n\n  if (!ekf.predict(X_next_t, A, Q)) {\n    RCLCPP_WARN(logger_, \"Pedestrian : Cannot predict\");\n  }\n\n  return true;\n}\n\nbool UnknownTracker::measureWithPose(\n  const autoware_auto_perception_msgs::msg::DetectedObject & object)\n{\n  constexpr int dim_y = 2;  // pos x, pos y depending on Pose output\n\n  /* Set measurement matrix */\n  Eigen::MatrixXd Y(dim_y, 1);\n  Y << object.kinematics.pose_with_covariance.pose.position.x,\n    object.kinematics.pose_with_covariance.pose.position.y;\n\n  /* Set measurement matrix */\n  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(dim_y, ekf_params_.dim_x);\n  C(0, IDX::X) = 1.0;  // for pos x\n  C(1, IDX::Y) = 1.0;  // for pos y\n\n  /* Set measurement noise covariance */\n  Eigen::MatrixXd R = Eigen::MatrixXd::Zero(dim_y, dim_y);\n  if (\n    !ekf_params_.use_measurement_covariance ||\n    object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::X_X] == 0.0 ||\n    object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::Y_Y] == 0.0) {\n    R(0, 0) = ekf_params_.r_cov_x;  // x - x\n    R(0, 1) = 0.0;                  // x - y\n    R(1, 1) = ekf_params_.r_cov_y;  // y - y\n    R(1, 0) = R(0, 1);              // y - x\n  } else {\n    R(0, 0) = object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::X_X];\n    R(0, 1) = object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::X_Y];\n    R(1, 0) = object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::Y_X];\n    R(1, 1) = object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::Y_Y];\n  }\n  if (!ekf_.update(Y, C, R)) {\n    RCLCPP_WARN(logger_, \"Pedestrian : Cannot update\");\n  }\n\n  // limit vx, vy\n  {\n    Eigen::MatrixXd X_t(ekf_params_.dim_x, 1);\n    Eigen::MatrixXd P_t(ekf_params_.dim_x, ekf_params_.dim_x);\n    ekf_.getX(X_t);\n    ekf_.getP(P_t);\n    if (!(-max_vx_ <= X_t(IDX::VX) && X_t(IDX::VX) <= max_vx_)) {\n      X_t(IDX::VX) = X_t(IDX::VX) < 0 ? -max_vx_ : max_vx_;\n    }\n    if (!(-max_vy_ <= X_t(IDX::VY) && X_t(IDX::VY) <= max_vy_)) {\n      X_t(IDX::VY) = X_t(IDX::VY) < 0 ? -max_vy_ : max_vy_;\n    }\n    ekf_.init(X_t, P_t);\n  }\n\n  // position z\n  constexpr float gain = 0.9;\n  z_ = gain * z_ + (1.0 - gain) * object.kinematics.pose_with_covariance.pose.position.z;\n\n  return true;\n}\n\nbool UnknownTracker::measure(\n  const autoware_auto_perception_msgs::msg::DetectedObject & object, const rclcpp::Time & time)\n{\n  object_ = object;\n\n  if (0.01 /*10msec*/ < std::fabs((time - last_update_time_).seconds())) {\n    RCLCPP_WARN(\n      logger_,\n      \"Pedestrian : There is a large gap between predicted time and measurement time. (%f)\",\n      (time - last_update_time_).seconds());\n  }\n\n  measureWithPose(object);\n\n  return true;\n}\n\nbool UnknownTracker::getTrackedObject(\n  const rclcpp::Time & time, autoware_auto_perception_msgs::msg::TrackedObject & object) const\n{\n  object = utils::toTrackedObject(object_);\n  object.object_id = getUUID();\n  object.classification = getClassification();\n\n  // predict kinematics\n  KalmanFilter tmp_ekf_for_no_update = ekf_;\n  const double dt = (time - last_update_time_).seconds();\n  if (0.001 /*1msec*/ < dt) {\n    predict(dt, tmp_ekf_for_no_update);\n  }\n  Eigen::MatrixXd X_t(ekf_params_.dim_x, 1);                // predicted state\n  Eigen::MatrixXd P(ekf_params_.dim_x, ekf_params_.dim_x);  // predicted state\n  tmp_ekf_for_no_update.getX(X_t);\n  tmp_ekf_for_no_update.getP(P);\n\n  // position\n  object.kinematics.pose_with_covariance.pose.position.x = X_t(IDX::X);\n  object.kinematics.pose_with_covariance.pose.position.y = X_t(IDX::Y);\n  object.kinematics.pose_with_covariance.pose.position.z = z_;\n  // position covariance\n  constexpr double z_cov = 0.1 * 0.1;    // TODO(yukkysaito) Currently tentative\n  constexpr double r_cov = 0.1 * 0.1;    // TODO(yukkysaito) Currently tentative\n  constexpr double p_cov = 0.1 * 0.1;    // TODO(yukkysaito) Currently tentative\n  constexpr double yaw_cov = 0.1 * 0.1;  // TODO(yukkysaito) Currently tentative\n  object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::X_X] = P(IDX::X, IDX::X);\n  object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::X_Y] = P(IDX::X, IDX::Y);\n  object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::Y_X] = P(IDX::Y, IDX::X);\n  object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::Y_Y] = P(IDX::Y, IDX::Y);\n  object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::Z_Z] = z_cov;\n  object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::ROLL_ROLL] = r_cov;\n  object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::PITCH_PITCH] = p_cov;\n  object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::YAW_YAW] = yaw_cov;\n\n  // twist\n  object.kinematics.twist_with_covariance.twist.linear.x = X_t(IDX::VX);\n  object.kinematics.twist_with_covariance.twist.linear.y = X_t(IDX::VY);\n  // twist covariance\n  constexpr double vz_cov = 0.1 * 0.1;  // TODO(yukkysaito) Currently tentative\n  constexpr double wx_cov = 0.1 * 0.1;  // TODO(yukkysaito) Currently tentative\n  constexpr double wy_cov = 0.1 * 0.1;  // TODO(yukkysaito) Currently tentative\n  constexpr double wz_cov = 0.1 * 0.1;  // TODO(yukkysaito) Currently tentative\n  object.kinematics.twist_with_covariance.covariance[utils::MSG_COV_IDX::X_X] = P(IDX::VX, IDX::VX);\n  object.kinematics.twist_with_covariance.covariance[utils::MSG_COV_IDX::Y_Y] = P(IDX::VY, IDX::VY);\n  object.kinematics.twist_with_covariance.covariance[utils::MSG_COV_IDX::Z_Z] = vz_cov;\n  object.kinematics.twist_with_covariance.covariance[utils::MSG_COV_IDX::ROLL_ROLL] = wx_cov;\n  object.kinematics.twist_with_covariance.covariance[utils::MSG_COV_IDX::PITCH_PITCH] = wy_cov;\n  object.kinematics.twist_with_covariance.covariance[utils::MSG_COV_IDX::YAW_YAW] = wz_cov;\n\n  return true;\n}\n", "meta": {"hexsha": "ebc484b84ef76e740c23a47f7447194e9e44c58b", "size": 12248, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "perception/object_recognition/tracking/multi_object_tracker/src/tracker/model/unknown_tracker.cpp", "max_stars_repo_name": "taikitanaka3/AutowareArchitectureProposal.iv", "max_stars_repo_head_hexsha": "0d47ea532118c98458516a8c83fbdab3d27c6231", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2020-09-25T08:52:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-05T02:39:31.000Z", "max_issues_repo_path": "perception/object_recognition/tracking/multi_object_tracker/src/tracker/model/unknown_tracker.cpp", "max_issues_repo_name": "taikitanaka3/AutowareArchitectureProposal.iv", "max_issues_repo_head_hexsha": "0d47ea532118c98458516a8c83fbdab3d27c6231", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2021-12-13T04:28:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T13:53:15.000Z", "max_forks_repo_path": "perception/object_recognition/tracking/multi_object_tracker/src/tracker/model/unknown_tracker.cpp", "max_forks_repo_name": "taikitanaka3/AutowareArchitectureProposal.iv", "max_forks_repo_head_hexsha": "0d47ea532118c98458516a8c83fbdab3d27c6231", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2020-09-27T05:27:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-08T03:14:25.000Z", "avg_line_length": 40.9632107023, "max_line_length": 100, "alphanum_fraction": 0.677743305, "num_tokens": 4187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.29417122025525994}}
{"text": "/*  \n*   Copyright 2019 Simon Raschke\n*\n*   Licensed under the Apache License, Version 2.0 (the \"License\");\n*   you may not use this file except in compliance with the License.\n*   You may obtain a copy of the License at\n*\n*       http://www.apache.org/licenses/LICENSE-2.0\n*\n*   Unless required by applicable law or agreed to in writing, software\n*   distributed under the License is distributed on an \"AS IS\" BASIS,\n*   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n*   See the License for the specific language governing permissions and\n*   limitations under the License.\n*/\n\n\n#pragma once\n\n#include \"common/definitions.hpp\"\n#include \"common/component.hpp\"\n\n#if __has_include(<eigen3/Eigen/Geometry>)\n    #include <eigen3/Eigen/Geometry>\n#elif __has_include(<Eigen/Geometry>)\n    #include <Eigen/Geometry>\n#else\n    #pragma error \"no eigen include\"\n#endif\n#include <cmath>\n#include <memory>\n#include <exception>\n\n\n\nnamespace ves \n{\n    struct Bounding; \n    struct CoordinatesBounding; \n    struct OrientationBounding; \n}\n\n\n\nstruct ves::Bounding\n{\nprotected:\n    Bounding() = default;\n\npublic:\n    std::unique_ptr<Eigen::Matrix<REAL,3,1>> origin {nullptr};\n\n    virtual ~Bounding() = default;\n    virtual bool isAllowed(const decltype(origin)::element_type&) = 0;\n    virtual void forcefullyShift(const Eigen::Matrix<REAL,3,1>&) = 0;\n};\n\n\n\nstruct ves::OrientationBounding\n    : public Bounding\n{\n    REAL value = TWOPI;\n\n    inline virtual bool isAllowed(const decltype(origin)::element_type& compare) override\n    {\n        if(!origin)\n        {\n            origin = std::make_unique<decltype(origin)::element_type>(compare);\n            return true;\n        }\n        else\n        {\n            return (std::acos(compare.normalized().dot(origin->normalized())) < value); \n            const bool allowed = (std::acos(compare.normalized().dot(origin->normalized())) < value); \n            if(allowed)\n            {\n                origin = std::make_unique<decltype(origin)::element_type>(compare);\n            }\n            return allowed;\n        }\n    };\n\n    virtual void forcefullyShift(const Eigen::Matrix<REAL,3,1>& s) override\n    {\n        if(origin)\n            origin->operator+=(s);\n    }\n};\n\n\n\nstruct ves::CoordinatesBounding\n    : public Bounding\n{\n    inline virtual bool isAllowed(const decltype(origin)::element_type& compare) override\n    {\n        if(!origin)\n        {\n            bool allowed = false;\n            if(bounding_box)\n            {\n                allowed = bounding_box->contains(compare);\n            }\n            else if(sphere_bounds)\n            {\n                const auto offset = (compare - (*origin)).norm();\n                allowed = offset >= sphere_bounds->first && offset <= sphere_bounds->second;\n            }\n            else if(!bounding_box && !sphere_bounds)\n            {\n                allowed = true;\n            }\n            else\n            {\n                vesCRITICAL(__PRETTY_FUNCTION__ << \" bad decision\");\n                allowed = false;\n            }\n            \n            if(allowed)\n                origin = std::make_unique<decltype(origin)::element_type>(compare);\n            \n            return allowed;\n        }\n        else\n        {\n            if(bounding_box)\n            {\n                return bounding_box->contains(compare);\n            }\n            else if(sphere_bounds)\n            {\n                const auto offset = (compare - (*origin)).norm();\n                return offset >= sphere_bounds->first && offset <= sphere_bounds->second;\n            }\n            else if(!bounding_box && !sphere_bounds)\n            {\n                return true;\n            }\n            else\n            {\n                vesCRITICAL(__PRETTY_FUNCTION__ << \" bad decision\");\n                return false;\n            }\n        }\n    };\n\n\n\n    inline void setBoundingSphere(const REAL from, const REAL to)\n    {\n        sphere_bounds = std::make_unique<std::pair<REAL,REAL>>(std::make_pair(from,to));\n        bounding_box.reset(nullptr);\n    };\n\n\n\n    inline void setBoundingBox(Eigen::AlignedBox<REAL,3>&& _box)\n    {\n        bounding_box = std::make_unique<Eigen::AlignedBox<REAL,3>>(std::move(_box));\n        sphere_bounds.reset(nullptr);\n    };\n\n\n\n    virtual void forcefullyShift(const Eigen::Matrix<REAL,3,1>& s) override\n    {\n        if(origin)\n            origin->operator+=(s);\n        if(bounding_box)\n            bounding_box->translate(s);\n    }\n\n\n\n    inline bool isBoxBound() const { return static_cast<bool>(bounding_box); };\n    inline bool isSphereBound() const { return static_cast<bool>(sphere_bounds); };\n\n    inline auto getBoundingBox() const { return *bounding_box; };\n    inline auto getSphereBounds() const { return *sphere_bounds; };\n\n\nprotected:\n    std::unique_ptr<Eigen::AlignedBox<REAL,3>> bounding_box = {nullptr};\n    std::unique_ptr<std::pair<REAL,REAL>> sphere_bounds = {nullptr};\n};", "meta": {"hexsha": "79ba4294d006b9a0c0f336c8637c79bdc081e870", "size": 4930, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/particles/boundings.hpp", "max_stars_repo_name": "simonraschke/vesicle2", "max_stars_repo_head_hexsha": "14aa0b2c7a7f587a861c67ba736e2047faecc0e0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T15:27:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-15T15:27:28.000Z", "max_issues_repo_path": "src/particles/boundings.hpp", "max_issues_repo_name": "simonraschke/vesicle2", "max_issues_repo_head_hexsha": "14aa0b2c7a7f587a861c67ba736e2047faecc0e0", "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/particles/boundings.hpp", "max_forks_repo_name": "simonraschke/vesicle2", "max_forks_repo_head_hexsha": "14aa0b2c7a7f587a861c67ba736e2047faecc0e0", "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.5053763441, "max_line_length": 102, "alphanum_fraction": 0.584178499, "num_tokens": 1057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2941471637608456}}
{"text": "//\n// Created by Zhongshi Jiang on 4/11/17.\n//\n\n#include <Eigen/Core>\n#include <Eigen/StdVector>\n#include \"tetrahedron_tetrahedron_adjacency.h\"\n#include \"tetrahedron_tuple.h\"\n#include \"retain_tetrahedral_adjacency.h\"\n#include \"edge_removal.h\"\n\n#include <iostream>\n#include <tuple>\n#include <set>\n#include <algorithm>\n#include <map>\n#include <list>\n#include <iterator>\nnamespace igl {\nnamespace dev {\n\nstruct face_removal_neighbor_test {\n  template<typename DerivedT, typename DerivedTT,\n           typename DerivedTTif, typename DerivedTTie>\n  std::tuple<double, double, std::list<int>, std::list<std::tuple<int, int>>>\n  recurse(int ti, int fi, int ei, bool ai,\n          std::vector<DerivedT> &T,\n          std::vector<DerivedTT> &TT,\n          std::vector<DerivedTTif> &TTif,\n          std::vector<DerivedTTie> &TTie,\n          int a, int b,\n          const std::function<double(int, int,\n                                     int, int)> &tet_quality,\n          const std::function<bool(int, int,\n                                   int, int)> &orient3D) {\n    using namespace igl::dev;\n\n    auto u = tet_tuple_get_vert(ti, fi, ei, ai, T, TT, TTif, TTie);\n    auto w = tet_tuple_get_vert(ti, fi, ei, !ai, T, TT, TTif, TTie);\n\n    auto q_uw = tet_quality(a, b, u, w);\n\n    // revolve around the edge : count one-ring tet and decide non-boundary.\n    bool flag = true;\n    int revolving_face_num = 0;\n    std::tuple<int, int, int> other_sandwiched_face;\n    int f = fi, t = ti, e = ei;\n    do {\n      // swtch t/f\n      if (tet_tuple_is_on_boundary(t, f, e, true, T, TT, TTif, TTie)) {\n        flag = false;\n        break;\n      }\n      std::tie(t, f, e) = std::make_tuple(TT[t][f], TTif[t][f],\n                                          TTie[t](f, e));\n      f = igl::dev::tetrahedron_local_FF(f, (e + 2) % 3);\n\n      revolving_face_num++;\n      if (revolving_face_num == 2) {\n        other_sandwiched_face = std::make_tuple(t, f, e);\n      }\n      if (revolving_face_num > 4) {\n        flag = false;\n        break;\n      }\n    } while (t != ti);\n\n    if(revolving_face_num != 4) flag = false;\n\n    if (flag) {\n      std::tie(t, f, e) = other_sandwiched_face;\n      int v = tet_tuple_get_vert(t, f, (e + 2) % 3, true, T, TT, TTif, TTie);\n\n      auto j_uv = orient3D(a, b, u, v);\n      auto j_vw = orient3D(a, b, v, w);\n      auto j_wu = orient3D(a, b, w, u);\n\n      double o_uv, n_uv, o_vw, n_vw;\n\n      std::list<int> h_uv, h_vw;\n      std::list<std::tuple<int, int>> dt_uv, dt_vw;\n      if ((int) j_uv + (int) j_vw + (int) j_wu >= 2) {\n        std::tie(o_uv, n_uv, h_uv, dt_uv) =\n            recurse(t, f, (e + 1) % 3, false,\n                    T, TT, TTif, TTie,\n                    a, b, tet_quality, orient3D);\n        std::tie(o_vw, n_vw, h_vw, dt_vw) =\n            recurse(t, f, (e + 2) % 3, false,\n                    T, TT, TTif, TTie,\n                    a, b, tet_quality, orient3D);\n\n        auto q_old = (std::min)({tet_quality(a, u, v, w), tet_quality(u, v, w,\n                                                                    b),\n                               o_uv, o_vw});\n        auto q_new = (std::min)(n_uv, n_vw);\n\n        if (q_new > q_old || q_new > q_uw) {\n//        one_ring_of_removal.insert(current_pos, v);\n          h_uv.push_back(v);\n          h_uv.splice(h_uv.end(), h_vw);\n          dt_uv.emplace_back(t, f);\n          dt_uv.splice(dt_uv.end(), dt_vw);\n          return std::make_tuple(q_old, q_new, h_uv, dt_uv);\n        }\n      }\n    }\n\n    return std::make_tuple(INFINITY, q_uw, std::list<int>(),\n                           std::list<std::tuple<int, int>>());\n  };\n};\n\ntemplate<typename DerivedT, typename DerivedTT,\n         typename DerivedTTif, typename DerivedTTie>\nbool tet_tuple_multi_face_removal(int ti,\n                                  int fi,\n                                  int ei,\n                                  bool ai,\n                                  std::function<double(int, int,\n                                                       int, int)> tet_quality,\n                                  std::function<bool(int, int,\n                                                     int, int)> orient3D,\n                                  std::vector<DerivedT> &T,\n                                  std::vector<DerivedTT> &TT,\n                                  std::vector<DerivedTTif> &TTif,\n                                  std::vector<DerivedTTie> &TTie,\n                                  std::vector<int> &new_tets_id) {\n\n  if (igl::dev::tet_tuple_is_on_boundary(ti, fi, ei, ai,\n                                         T, TT, TTif, TTie))\n    return false;\n\n  int apex_a, apex_b;\n  double q_old = tet_quality(T[ti](0), T[ti](1), T[ti](2), T[ti](3));\n  double q_new = INFINITY;\n  {\n    // get apex_a: switch f/e/v\n    auto t = ti, f = fi, e = ei;\n    auto a = true;\n    igl::dev::tet_tuple_switch_face(t, f, e, a, T, TT, TTif, TTie);\n    igl::dev::tet_tuple_switch_edge(t, f, e, a, T, TT, TTif, TTie);\n    apex_a = igl::dev::tet_tuple_get_vert(t, f, e, !a,\n                                          T, TT, TTif, TTie);\n  }\n  {\n    auto t = ti, f = fi, e = ei;\n    auto a = true;\n    igl::dev::tet_tuple_switch_tet(t, f, e, a, T, TT, TTif, TTie);\n    igl::dev::tet_tuple_switch_face(t, f, e, a, T, TT, TTif, TTie);\n    igl::dev::tet_tuple_switch_edge(t, f, e, a, T, TT, TTif, TTie);\n    apex_b = igl::dev::tet_tuple_get_vert(t, f, e, !a,\n                                          T, TT, TTif, TTie);\n    q_old = (std::min)(q_old, tet_quality(T[t](0), T[t](1), T[t](2), T[t](3)));\n  }\n\n  assert(q_old > 0);\n\n  face_removal_neighbor_test neighbor_test;\n  std::list<int> polygon;\n  std::list<std::tuple<int, int>> delete_faces{std::make_tuple(ti, fi)};;\n  for (auto e:{0, 1, 2}) {\n    std::list<int> added_points;\n    decltype(delete_faces) local_del_faces;\n    double local_q_old, local_q_new;\n    polygon.push_back(igl::dev::tet_tuple_get_vert(ti, fi, e, ai,\n                                                   T, TT, TTif, TTie));\n    std::tie(local_q_old, local_q_new, added_points, local_del_faces) =\n        neighbor_test.recurse(ti, fi, e, ai, T, TT, TTif, TTie, apex_a, apex_b,\n                              tet_quality, orient3D);\n\n    q_old = (std::min)(q_old, local_q_old);\n    q_new = (std::min)(q_new, local_q_new);\n    polygon.splice(polygon.end(), added_points);\n    delete_faces.splice(delete_faces.end(), local_del_faces);\n  }\n  if (q_new <= q_old)\n    return false;\n  if (q_new < 0) {\n//    std::cout<<\"Warning q_new < 0 in Multiface removal\"<<std::endl;\n    return false;\n  }\n  // delete those sandwiched between a/b\n  std::set<int> delete_tets;\n  std::set<int> influence_id;\n  for (auto tf:delete_faces) {\n    int t, f;\n    std::tie(t, f) = tf;\n    delete_tets.insert(t);\n    delete_tets.insert(TT[t][f]);\n  }\n\n  for (auto t:delete_tets)\n    for (auto f:{0, 1, 2, 3}) influence_id.insert(TT[t][f]);\n  influence_id.erase(-1);\n\n  std::vector<Eigen::RowVector4i> new_tets;\n  auto p = std::rbegin(polygon);\n  auto q = std::next(p);\n  for (; q != std::rend(polygon); ++p, ++q) {\n    new_tets.emplace_back(apex_a, apex_b, *p, *q);\n  }\n  if (!new_tets.empty())\n    new_tets.emplace_back(apex_a, apex_b, *p, *std::rbegin(polygon));\n\n  std::set<int> surround_id;\n  std::set_difference(influence_id.begin(), influence_id.end(),\n                      delete_tets.begin(), delete_tets.end(),\n                      std::inserter(surround_id, surround_id.begin()));\n\n\n  // additional procedure for the recomputation of new tets.\n  // is actually reusable for retain_tet_adj. But not much.\n  new_tets_id.clear();\n  new_tets_id.insert(new_tets_id.end(), delete_tets.begin(), delete_tets.end());\n  for (int i = 0, loop_num = new_tets.size() - delete_tets.size(); i < loop_num;\n       i++)\n    new_tets_id.push_back(i + T.size());\n  if (delete_tets.size() > new_tets.size()) new_tets_id.resize(new_tets.size());\n\n#ifndef NDEBUG\n  {\n    double qq = INFINITY;\n    for (auto r:new_tets) {\n      double new_qq = tet_quality(r[0], r[1], r[2], r[3]);\n      if (qq > new_qq)\n        qq = new_qq;\n    }\n    assert(qq == q_new);\n  }\n  assert(q_new > 0);\n\n#endif\n  retain_tetrahedral_adjacency(delete_tets, surround_id, new_tets, T, TT, TTif,\n                               TTie);\n#ifndef NDEBUG\n  {\n    double qq = INFINITY;\n    for (auto i:new_tets_id) {\n      auto r = T[i];\n      double new_qq = tet_quality(r[0], r[1], r[2], r[3]);\n      if (qq > new_qq)\n        qq = new_qq;\n    }\n    assert(qq == q_new);\n  }\n#endif\n  return true;\n};\n\ntemplate<typename DerivedT, typename DerivedTT,\n         typename DerivedTTif, typename DerivedTTie>\nbool tet_tuple_multi_face_removal_force(int ti,\n                                        int fi,\n                                        int ei,\n                                        bool ai,\n                                        std::function<double(int,\n                                                             int,\n                                                             int,\n                                                             int)> tet_quality,\n                                        std::function<bool(int, int,\n                                                           int, int)> orient3D,\n                                        std::vector<DerivedT> &T,\n                                        std::vector<DerivedTT> &TT,\n                                        std::vector<DerivedTTif> &TTif,\n                                        std::vector<DerivedTTie> &TTie) {\n\n  if (igl::dev::tet_tuple_is_on_boundary(ti, fi, ei, ai,\n                                         T, TT, TTif, TTie))\n    return false;\n\n  int apex_a, apex_b;\n  double q_old = tet_quality(T[ti](0), T[ti](1), T[ti](2), T[ti](3));\n  double q_new = INFINITY;\n  {\n    // get apex_a: switch f/e/v\n    auto t = ti, f = fi, e = ei;\n    auto a = true;\n    igl::dev::tet_tuple_switch_face(t, f, e, a, T, TT, TTif, TTie);\n    igl::dev::tet_tuple_switch_edge(t, f, e, a, T, TT, TTif, TTie);\n    apex_a = igl::dev::tet_tuple_get_vert(t, f, e, !a,\n                                          T, TT, TTif, TTie);\n  }\n  {\n    auto t = ti, f = fi, e = ei;\n    auto a = true;\n    igl::dev::tet_tuple_switch_tet(t, f, e, a, T, TT, TTif, TTie);\n    igl::dev::tet_tuple_switch_face(t, f, e, a, T, TT, TTif, TTie);\n    igl::dev::tet_tuple_switch_edge(t, f, e, a, T, TT, TTif, TTie);\n    apex_b = igl::dev::tet_tuple_get_vert(t, f, e, !a,\n                                          T, TT, TTif, TTie);\n    q_old = (std::min)(q_old, tet_quality(T[t](0), T[t](1), T[t](2), T[t](3)));\n  }\n\n  assert(q_old > 0);\n\n  face_removal_neighbor_test neighbor_test;\n  std::list<int> polygon;\n  std::list<std::tuple<int, int>> delete_faces{std::make_tuple(ti, fi)};;\n  for (auto e:{0, 1, 2}) {\n    std::list<int> added_points;\n    decltype(delete_faces) local_del_faces;\n    double local_q_old, local_q_new;\n    polygon.push_back(igl::dev::tet_tuple_get_vert(ti, fi, e, ai,\n                                                   T, TT, TTif, TTie));\n    std::tie(local_q_old, local_q_new, added_points, local_del_faces) =\n        neighbor_test.recurse(ti, fi, e, ai, T, TT, TTif, TTie, apex_a, apex_b,\n                              tet_quality, orient3D);\n\n    q_old = (std::min)(q_old, local_q_old);\n    q_new = (std::min)(q_new, local_q_new);\n    polygon.splice(polygon.end(), added_points);\n    delete_faces.splice(delete_faces.end(), local_del_faces);\n  }\n  // delete those sandwiched between a/b\n  std::set<int> delete_tets;\n  std::set<int> influence_id;\n  for (auto tf:delete_faces) {\n    int t, f;\n    std::tie(t, f) = tf;\n    delete_tets.insert(t);\n    delete_tets.insert(TT[t][f]);\n  }\n\n  for (auto t:delete_tets)\n    for (auto f:{0, 1, 2, 3}) influence_id.insert(TT[t][f]);\n  influence_id.erase(-1);\n\n  std::vector<Eigen::RowVector4i> new_tets;\n  auto p = std::rbegin(polygon);\n  auto q = std::next(p);\n  for (; q != std::rend(polygon); ++p, ++q) {\n    new_tets.emplace_back(apex_a, apex_b, *p, *q);\n  }\n  if (!new_tets.empty())\n    new_tets.emplace_back(apex_a, apex_b, *p, *std::rbegin(polygon));\n\n  std::set<int> surround_id;\n  std::set_difference(influence_id.begin(), influence_id.end(),\n                      delete_tets.begin(), delete_tets.end(),\n                      std::inserter(surround_id, surround_id.begin()));\n\n\n#ifndef NDEBUG\n  {\n    double qq = INFINITY;\n    for (auto r:new_tets) {\n      double new_qq = tet_quality(r[0], r[1], r[2], r[3]);\n      if (qq > new_qq)\n        qq = new_qq;\n    }\n    assert(qq == q_new);\n  }\n  assert(q_new >= 0);\n\n#endif\n  retain_tetrahedral_adjacency(delete_tets, surround_id, new_tets, T, TT, TTif,\n                               TTie);\n  return true;\n};\n\n}\n}\n\n#ifdef IGL_STATIC_LIBRARY\ntemplate bool igl::dev::tet_tuple_multi_face_removal<Eigen::Matrix<int, 1, 4,\n                                                                   1, 1, 4>,\n                                                     Eigen::Matrix<int,\n                                                                   1,\n                                                                   4,\n                                                                   1,\n                                                                   1,\n                                                                   4>,\n                                                     Eigen::Matrix<int,\n                                                                   1,\n                                                                   4,\n                                                                   1,\n                                                                   1,\n                                                                   4>,\n                                                     Eigen::Matrix<int,\n                                                                   4,\n                                                                   3,\n                                                                   0,\n                                                                   4,\n                                                                   3> >(int,\n                                                                        int,\n                                                                        int,\n                                                                        bool,\n                                                                        std::function<\n                                                                            double(\n                                                                                int,\n                                                                                int,\n                                                                                int,\n                                                                                int)>,\n                                                                        std::function<\n                                                                            bool(\n                                                                                int,\n                                                                                int,\n                                                                                int,\n                                                                                int)>,\n                                                                        std::vector<\n                                                                            Eigen::Matrix<\n                                                                                int,\n                                                                                1,\n                                                                                4,\n                                                                                1,\n                                                                                1,\n                                                                                4>,\n                                                                            std::allocator<\n                                                                                Eigen::Matrix<\n                                                                                    int,\n                                                                                    1,\n                                                                                    4,\n                                                                                    1,\n                                                                                    1,\n                                                                                    4> > > &,\n                                                                        std::vector<\n                                                                            Eigen::Matrix<\n                                                                                int,\n                                                                                1,\n                                                                                4,\n                                                                                1,\n                                                                                1,\n                                                                                4>,\n                                                                            std::allocator<\n                                                                                Eigen::Matrix<\n                                                                                    int,\n                                                                                    1,\n                                                                                    4,\n                                                                                    1,\n                                                                                    1,\n                                                                                    4> > > &,\n                                                                        std::vector<\n                                                                            Eigen::Matrix<\n                                                                                int,\n                                                                                1,\n                                                                                4,\n                                                                                1,\n                                                                                1,\n                                                                                4>,\n                                                                            std::allocator<\n                                                                                Eigen::Matrix<\n                                                                                    int,\n                                                                                    1,\n                                                                                    4,\n                                                                                    1,\n                                                                                    1,\n                                                                                    4> > > &,\n                                                                        std::vector<\n                                                                            Eigen::Matrix<\n                                                                                int,\n                                                                                4,\n                                                                                3,\n                                                                                0,\n                                                                                4,\n                                                                                3>,\n                                                                            std::allocator<\n                                                                                Eigen::Matrix<\n                                                                                    int,\n                                                                                    4,\n                                                                                    3,\n                                                                                    0,\n                                                                                    4,\n                                                                                    3> > > &,\n                                                                        std::vector<\n                                                                            int,\n                                                                            std::allocator<\n                                                                                int> > &);\n\ntemplate bool igl::dev::tet_tuple_multi_face_removal_force<Eigen::Matrix<int,\n                                                                         1,\n                                                                         4,\n                                                                         1,\n                                                                         1,\n                                                                         4>,\n                                                           Eigen::Matrix<int,\n                                                                         1,\n                                                                         4,\n                                                                         1,\n                                                                         1,\n                                                                         4>,\n                                                           Eigen::Matrix<int,\n                                                                         1,\n                                                                         4,\n                                                                         1,\n                                                                         1,\n                                                                         4>,\n                                                           Eigen::Matrix<int,\n                                                                         4,\n                                                                         3,\n                                                                         0,\n                                                                         4,\n                                                                         3> >(\n    int,\n    int,\n    int,\n    bool,\n    std::function<double(int, int, int, int)>,\n    std::function<bool(int, int, int, int)>,\n    std::vector<Eigen::Matrix<int, 1, 4, 1, 1, 4>,\n                     std::allocator<Eigen::Matrix<int,\n                                                       1,\n                                                       4,\n                                                       1,\n                                                       1,\n                                                       4> > > &,\n    std::vector<Eigen::Matrix<int, 1, 4, 1, 1, 4>,\n                     std::allocator<Eigen::Matrix<int,\n                                                       1,\n                                                       4,\n                                                       1,\n                                                       1,\n                                                       4> > > &,\n    std::vector<Eigen::Matrix<int, 1, 4, 1, 1, 4>,\n                     std::allocator<Eigen::Matrix<int,\n                                                       1,\n                                                       4,\n                                                       1,\n                                                       1,\n                                                       4> > > &,\n    std::vector<Eigen::Matrix<int, 4, 3, 0, 4, 3>,\n                     std::allocator<Eigen::Matrix<int,\n                                                       4,\n                                                       3,\n                                                       0,\n                                                       4,\n                                                       3> > > &);\n\n#endif\n", "meta": {"hexsha": "54f0562b71e53434c5c92d76ad8f8ebe31a42bbf", "size": 24897, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/igl_dev/multi_face_removal.cpp", "max_stars_repo_name": "squarefk/Scaffold-Map", "max_stars_repo_head_hexsha": "6218cbc3ec5b83cb24c5bc65dd21e7b3a52dc76b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2018-04-04T19:50:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T00:56:10.000Z", "max_issues_repo_path": "src/igl_dev/multi_face_removal.cpp", "max_issues_repo_name": "squarefk/Scaffold-Map", "max_issues_repo_head_hexsha": "6218cbc3ec5b83cb24c5bc65dd21e7b3a52dc76b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2018-04-27T05:01:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-21T19:07:28.000Z", "max_forks_repo_path": "src/igl_dev/multi_face_removal.cpp", "max_forks_repo_name": "squarefk/Scaffold-Map", "max_forks_repo_head_hexsha": "6218cbc3ec5b83cb24c5bc65dd21e7b3a52dc76b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-04-05T10:50:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-10T14:26:09.000Z", "avg_line_length": 47.0642722117, "max_line_length": 94, "alphanum_fraction": 0.3040928626, "num_tokens": 4521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2941471585454427}}
{"text": "#pragma once\n\n#include <boost/container/static_vector.hpp>\n#include <iostream>\n#include <unordered_map>\n\n#include \"haar_basis.hpp\"\n#include \"linear_operator.hpp\"\n#include \"orthonormal_basis.hpp\"\n#include \"three_point_basis.hpp\"\nnamespace Time {\n\n/**\n *  Implementations of LinearOperator.\n */\ntemplate <typename I, typename BasisIn, typename BasisOut>\nSparseVector<BasisOut> LinearOperator<I, BasisIn, BasisOut>::MatVec(\n    const SparseVector<BasisIn> &vec) const {\n  SparseVector<BasisOut> result;\n  result.reserve(vec.size() * 2);\n\n  for (const auto [labda_in, coeff_in] : vec)\n    for (const auto [labda_out, coeff_out] : I::Column(labda_in))\n      result.emplace_back(labda_out, coeff_in * coeff_out);\n  result.Compress();\n  return result;\n}\n\ntemplate <typename I, typename BasisIn, typename BasisOut>\nSparseVector<BasisIn> LinearOperator<I, BasisIn, BasisOut>::RMatVec(\n    const SparseVector<BasisOut> &vec) const {\n  SparseVector<BasisIn> result;\n  result.reserve(vec.size() * 2);\n\n  for (const auto [labda_out, coeff_out] : vec)\n    for (const auto [labda_in, coeff_in] : I::Row(labda_out))\n      result.emplace_back(labda_in, coeff_out * coeff_in);\n  result.Compress();\n  return result;\n}\n\ntemplate <typename I, typename BasisIn, typename BasisOut>\nSparseVector<BasisOut> LinearOperator<I, BasisIn, BasisOut>::MatVec(\n    const SparseVector<BasisIn> &vec,\n    const SparseIndices<BasisOut> &indices_out) const {\n  if (vec.empty() || indices_out.empty()) return {};\n  assert(indices_out.IsUnique());\n  SparseVector<BasisOut> result;\n  result.reserve(indices_out.size());\n\n  vec.StoreInTree();\n  for (const auto labda_out : indices_out) {\n    double val = 0;\n    for (const auto [labda_in, coeff_in] : I::Row(labda_out))\n      if (labda_in->has_data())\n        val += coeff_in * (*labda_in->template data<double>());\n    result.emplace_back(labda_out, val);\n  }\n  vec.RemoveFromTree();\n  return result;\n}\n\ntemplate <typename I, typename BasisIn, typename BasisOut>\nSparseVector<BasisIn> LinearOperator<I, BasisIn, BasisOut>::RMatVec(\n    const SparseVector<BasisOut> &vec,\n    const SparseIndices<BasisIn> &indices_in) const {\n  if (vec.empty() || indices_in.empty()) return {};\n  assert(indices_in.IsUnique());\n  SparseVector<BasisIn> result;\n  result.reserve(indices_in.size());\n\n  vec.StoreInTree();\n  for (const auto labda_in : indices_in) {\n    double val = 0;\n    for (const auto [labda_out, coeff_out] : I::Column(labda_in))\n      if (labda_out->has_data())\n        val += coeff_out * (*labda_out->template data<double>());\n    result.emplace_back(labda_in, val);\n  }\n  vec.RemoveFromTree();\n  return result;\n}\n\ntemplate <typename I, typename BasisIn, typename BasisOut>\nSparseIndices<BasisOut> LinearOperator<I, BasisIn, BasisOut>::Range(\n    const SparseIndices<BasisIn> &ind) const {\n  SparseIndices<BasisOut> result;\n  result.reserve(ind.size() * 2);\n\n  for (const auto labda_in : ind)\n    for (const auto [labda_out, _] : I::Column(labda_in))\n      result.emplace_back(labda_out);\n  result.Compress();\n  return result;\n}\n\ntemplate <typename I, typename BasisIn, typename BasisOut>\nEigen::MatrixXd LinearOperator<I, BasisIn, BasisOut>::ToMatrix(\n    const SparseIndices<BasisIn> &indices_in,\n    const SparseIndices<BasisOut> &indices_out) const {\n  assert(indices_in.IsUnique() && indices_out.IsUnique());\n  std::unordered_map<BasisIn *, int> indices_in_map;\n  std::unordered_map<BasisOut *, int> indices_out_map;\n  Eigen::MatrixXd A =\n      Eigen::MatrixXd::Zero(indices_out.size(), indices_in.size());\n\n  for (int i = 0; i < indices_in.size(); ++i) {\n    assert(!indices_in_map.count(indices_in[i]));\n    indices_in_map[indices_in[i]] = i;\n  }\n  for (int i = 0; i < indices_out.size(); ++i) {\n    assert(!indices_out_map.count(indices_out[i]));\n    indices_out_map[indices_out[i]] = i;\n  }\n\n  // Create A.\n  for (int i = 0; i < indices_in.size(); ++i) {\n    SparseVector<BasisIn> vec{{{indices_in[i], 1.0}}};\n    auto op_vec = MatVec(vec);\n    for (auto [fn, coeff] : op_vec) {\n      A(indices_out_map[fn], i) = coeff;\n    }\n  }\n\n  return A;\n}\n\n/**\n *  Below implementations have various return types based. The aliases\n *  below are some handy containers with fixed memory size.\n */\ntemplate <typename Basis, size_t N>\nusing StaticSparseVector =\n    boost::container::static_vector<std::pair<Basis *, double>, N>;\ntemplate <typename Basis, size_t N>\nusing ArraySparseVector = std::array<std::pair<Basis *, double>, N>;\n\n/**\n *  Implementations of Prolongate.\n */\ntemplate <>\ninline auto Prolongate<ContLinearScalingFn>::Column(\n    ContLinearScalingFn *phi_in) {\n  StaticSparseVector<ContLinearScalingFn, 3> result;\n\n  auto [l, n] = phi_in->labda();\n  result.emplace_back(phi_in->RefineMiddle(), 1.0);\n  if (n > 0) result.emplace_back(phi_in->RefineLeft(), 0.5);\n  if (n < (1LL << l)) result.emplace_back(phi_in->RefineRight(), 0.5);\n  return result;\n}\n\ntemplate <>\ninline auto Prolongate<ContLinearScalingFn>::Row(ContLinearScalingFn *phi_in) {\n  StaticSparseVector<ContLinearScalingFn, 2> result;\n  const auto &parents = phi_in->parents();\n  if (parents.size() == 1)\n    result = {{{parents[0], 1.0}}};\n  else if (parents.size() == 2)\n    result = {{{parents[0], 0.5}, {parents[1], 0.5}}};\n  else\n    assert(false);\n  return result;\n}\n\ntemplate <>\ninline auto Prolongate<DiscLinearScalingFn>::Column(\n    DiscLinearScalingFn *phi_in) {\n  StaticSparseVector<DiscLinearScalingFn, 4> result;\n  auto [l, n] = phi_in->labda();\n  phi_in->Refine();\n  const auto &children = phi_in->children();\n  if (phi_in->pw_constant()) {\n    result.emplace_back(children[0], 1);\n    result.emplace_back(children[2], 1);\n  } else {\n    result.emplace_back(children[0], -sqrt(3) / 2);\n    result.emplace_back(children[1], 0.5);\n    result.emplace_back(children[2], sqrt(3) / 2);\n    result.emplace_back(children[3], 0.5);\n  }\n  return result;\n}\n\ntemplate <>\ninline auto Prolongate<DiscLinearScalingFn>::Row(DiscLinearScalingFn *phi_in) {\n  StaticSparseVector<DiscLinearScalingFn, 2> result;\n  auto [l, n] = phi_in->labda();\n  const auto &parents = phi_in->parents();\n  switch (n % 4) {\n    case 0:\n      result = {{{parents[0], 1.0}, {parents[1], -sqrt(3) / 2}}};\n      return result;\n    case 1:\n      result = {{{parents[1], 0.5}}};\n      return result;\n    case 2:\n      result = {{{parents[0], 1.0}, {parents[1], sqrt(3) / 2}}};\n      return result;\n    case 3:\n    default:\n      result = {{{parents[1], 0.5}}};\n      return result;\n  }\n}\n\n/**\n *  Implementations of the Mass operator.\n */\ntemplate <>\ninline auto MassOperator<ContLinearScalingFn, ContLinearScalingFn>::Column(\n    ContLinearScalingFn *phi_in) {\n  StaticSparseVector<ContLinearScalingFn, 3> result;\n\n  auto [l, n] = phi_in->labda();\n  double self_ip = 0;\n  if (n > 0) {\n    auto elem = phi_in->support()[0];\n    result.emplace_back(elem->RefineContLinear()[0], 1. / ((1LL << l) * 6.0));\n    self_ip += 1. / ((1LL << l) * 3.0);\n  }\n  if (n < (1LL << l)) {\n    auto elem = phi_in->support().back();\n    result.emplace_back(elem->RefineContLinear()[1], 1. / ((1LL << l) * 6.0));\n    self_ip += 1. / ((1LL << l) * 3.0);\n  }\n  result.emplace_back(phi_in, self_ip);\n  return result;\n}\n\ntemplate <>\ninline auto MassOperator<ContLinearScalingFn, ContLinearScalingFn>::Row(\n    ContLinearScalingFn *phi_out) {\n  // This MassOperator is symmetric.\n  return Column(phi_out);\n}\n\ntemplate <>\ninline auto MassOperator<DiscConstantScalingFn, DiscConstantScalingFn>::Column(\n    DiscConstantScalingFn *phi_in) {\n  return ArraySparseVector<DiscConstantScalingFn, 1>{\n      {{phi_in, 1. / (1LL << phi_in->level())}}};\n}\n\ntemplate <>\ninline auto MassOperator<DiscConstantScalingFn, DiscConstantScalingFn>::Row(\n    DiscConstantScalingFn *phi_out) {\n  // This MassOperator is symmetric.\n  return Column(phi_out);\n}\n\ntemplate <>\ninline auto MassOperator<DiscLinearScalingFn, DiscLinearScalingFn>::Column(\n    DiscLinearScalingFn *phi_in) {\n  return ArraySparseVector<DiscLinearScalingFn, 1>{\n      {{phi_in, 1. / (1LL << phi_in->level())}}};\n}\n\ntemplate <>\ninline auto MassOperator<DiscLinearScalingFn, DiscLinearScalingFn>::Row(\n    DiscLinearScalingFn *phi_out) {\n  // This MassOperator is symmetric.\n  return Column(phi_out);\n}\n\nnamespace Mass {\ninline auto ThreeInOrthoOut(ContLinearScalingFn *phi_in) {\n  StaticSparseVector<DiscLinearScalingFn, 4> result;\n\n  auto [l, n] = phi_in->labda();\n  const double s = 1. / (1LL << (l + 1));  // s = pow(2, -(l+1)).\n  if (n > 0) {\n    const auto &[pdl0, pdl1] = phi_in->support().front()->PhiDiscLinear();\n    assert(pdl0 != nullptr && pdl1 != nullptr);\n    result.emplace_back(pdl0, s);\n    result.emplace_back(pdl1, s / sqrt(3));\n  }\n  if (n < (1LL << l)) {\n    const auto &[pdl0, pdl1] = phi_in->support().back()->PhiDiscLinear();\n    assert(pdl0 != nullptr && pdl1 != nullptr);\n    result.emplace_back(pdl0, s);\n    result.emplace_back(pdl1, -s / sqrt(3));\n  }\n  return result;\n}\n\ninline auto OrthoInThreeOut(DiscLinearScalingFn *phi_in) {\n  ArraySparseVector<ContLinearScalingFn, 2> result;\n  auto [l, n] = phi_in->labda();\n  const auto &[pcl0, pcl1] = phi_in->support()[0]->RefineContLinear();\n  assert(pcl0 != nullptr && pcl1 != nullptr);\n  const double s = 1. / (1LL << (l + 1));  // s = pow(2, -(l+1)).\n  if (phi_in->pw_constant())\n    result = {{{pcl0, s}, {pcl1, s}}};\n  else\n    result = {{{pcl0, -s / sqrt(3)}, {pcl1, s / sqrt(3)}}};\n  return result;\n}\n};  // namespace Mass\n\ntemplate <>\ninline auto MassOperator<ContLinearScalingFn, DiscLinearScalingFn>::Column(\n    ContLinearScalingFn *phi_in) {\n  return Mass::ThreeInOrthoOut(phi_in);\n}\n\ntemplate <>\ninline auto MassOperator<ContLinearScalingFn, DiscLinearScalingFn>::Row(\n    DiscLinearScalingFn *phi_out) {\n  return Mass::OrthoInThreeOut(phi_out);\n}\n\ntemplate <>\ninline auto MassOperator<DiscLinearScalingFn, ContLinearScalingFn>::Column(\n    DiscLinearScalingFn *phi_in) {\n  return Mass::OrthoInThreeOut(phi_in);\n}\n\ntemplate <>\ninline auto MassOperator<DiscLinearScalingFn, ContLinearScalingFn>::Row(\n    ContLinearScalingFn *phi_out) {\n  return Mass::ThreeInOrthoOut(phi_out);\n}\n\ntemplate <>\ninline auto ZeroEvalOperator<ContLinearScalingFn, ContLinearScalingFn>::Column(\n    ContLinearScalingFn *phi_in) {\n  StaticSparseVector<ContLinearScalingFn, 1> result;\n  auto [l, n] = phi_in->labda();\n  if (n == 0) result = {{{phi_in, 1.0}}};\n  return result;\n}\n\ntemplate <>\ninline auto ZeroEvalOperator<ContLinearScalingFn, ContLinearScalingFn>::Row(\n    ContLinearScalingFn *phi_out) {\n  return Column(phi_out);\n}\n\ntemplate <>\ninline auto ZeroEvalOperator<DiscLinearScalingFn, DiscLinearScalingFn>::Column(\n    DiscLinearScalingFn *phi_in) {\n  StaticSparseVector<DiscLinearScalingFn, 2> result;\n  auto [l, n] = phi_in->labda();\n  if (n <= 1) {\n    const auto &[pdl0, pdl1] = phi_in->support().front()->PhiDiscLinear();\n    assert(pdl0 != nullptr && pdl1 != nullptr);\n    if (phi_in->pw_constant())\n      result = {{{pdl0, 1.0}, {pdl1, -sqrt(3)}}};\n    else\n      result = {{{pdl0, -sqrt(3)}, {pdl1, 3.0}}};\n  }\n  return result;\n}\n\ntemplate <>\ninline auto ZeroEvalOperator<DiscLinearScalingFn, DiscLinearScalingFn>::Row(\n    DiscLinearScalingFn *phi_out) {\n  return Column(phi_out);\n}\n\nnamespace ZeroEval {\ninline auto ThreeInOrthoOut(ContLinearScalingFn *phi_in) {\n  StaticSparseVector<DiscLinearScalingFn, 2> result;\n  auto [l, n] = phi_in->labda();\n  if (n == 0) {\n    const auto &[pdl0, pdl1] = phi_in->support().front()->PhiDiscLinear();\n    assert(pdl0 != nullptr && pdl1 != nullptr);\n    result = {{{pdl0, 1.0}, {pdl1, -sqrt(3)}}};\n  }\n  return result;\n}\n\ninline auto OrthoInThreeOut(DiscLinearScalingFn *phi_in) {\n  StaticSparseVector<ContLinearScalingFn, 1> result;\n  auto [l, n] = phi_in->labda();\n  if (n <= 1) {\n    const auto &pcl0 = phi_in->support().front()->RefineContLinear()[0];\n    assert(pcl0 != nullptr);\n    if (phi_in->pw_constant())\n      result = {{{pcl0, 1.0}}};\n    else\n      result = {{{pcl0, -sqrt(3)}}};\n  }\n  return result;\n}\n};  // namespace ZeroEval\n\ntemplate <>\ninline auto ZeroEvalOperator<ContLinearScalingFn, DiscLinearScalingFn>::Column(\n    ContLinearScalingFn *phi_in) {\n  return ZeroEval::ThreeInOrthoOut(phi_in);\n}\n\ntemplate <>\ninline auto ZeroEvalOperator<ContLinearScalingFn, DiscLinearScalingFn>::Row(\n    DiscLinearScalingFn *phi_out) {\n  return ZeroEval::OrthoInThreeOut(phi_out);\n}\n\ntemplate <>\ninline auto ZeroEvalOperator<DiscLinearScalingFn, ContLinearScalingFn>::Column(\n    DiscLinearScalingFn *phi_in) {\n  return ZeroEval::OrthoInThreeOut(phi_in);\n}\n\ntemplate <>\ninline auto ZeroEvalOperator<DiscLinearScalingFn, ContLinearScalingFn>::Row(\n    ContLinearScalingFn *phi_out) {\n  return ZeroEval::ThreeInOrthoOut(phi_out);\n}\n\nnamespace Transport {\ninline auto ThreeInOrthoOut(ContLinearScalingFn *phi_in) {\n  StaticSparseVector<DiscLinearScalingFn, 2> result;\n\n  auto [l, n] = phi_in->labda();\n  if (n > 0) {\n    const auto &pdl0 = phi_in->support().front()->PhiDiscLinear()[0];\n    assert(pdl0 != nullptr);\n    result.emplace_back(pdl0, 1.0);\n  }\n  if (n < (1LL << l)) {\n    const auto &pdl0 = phi_in->support().back()->PhiDiscLinear()[0];\n    assert(pdl0 != nullptr);\n    result.emplace_back(pdl0, -1.0);\n  }\n  return result;\n}\ninline auto OrthoInThreeOut(DiscLinearScalingFn *phi_in) {\n  StaticSparseVector<ContLinearScalingFn, 2> result;\n  auto [l, n] = phi_in->labda();\n  const auto &[pcl0, pcl1] = phi_in->support().front()->RefineContLinear();\n  assert(pcl0 != nullptr && pcl1 != nullptr);\n  if (phi_in->pw_constant()) result = {{{pcl0, -1.0}, {pcl1, 1.0}}};\n  return result;\n}\n}  // namespace Transport\n\ntemplate <>\ninline auto TransportOperator<ContLinearScalingFn, DiscLinearScalingFn>::Column(\n    ContLinearScalingFn *phi_in) {\n  return Transport::ThreeInOrthoOut(phi_in);\n}\n\ntemplate <>\ninline auto TransportOperator<ContLinearScalingFn, DiscLinearScalingFn>::Row(\n    DiscLinearScalingFn *phi_out) {\n  return Transport::OrthoInThreeOut(phi_out);\n}\n\ntemplate <>\ninline auto TransportOperator<DiscLinearScalingFn, ContLinearScalingFn>::Column(\n    DiscLinearScalingFn *phi_in) {\n  return Transport::OrthoInThreeOut(phi_in);\n}\n\ntemplate <>\ninline auto TransportOperator<DiscLinearScalingFn, ContLinearScalingFn>::Row(\n    ContLinearScalingFn *phi_out) {\n  return Transport::ThreeInOrthoOut(phi_out);\n}\n\n}  // namespace Time\n", "meta": {"hexsha": "e5135269cdd4f5ec5df2eb59524405dcde38739a", "size": 14251, "ext": "ipp", "lang": "C++", "max_stars_repo_path": "src/time/linear_operator.ipp", "max_stars_repo_name": "rvanvenetie/spacetime", "max_stars_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/time/linear_operator.ipp", "max_issues_repo_name": "rvanvenetie/spacetime", "max_issues_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/time/linear_operator.ipp", "max_forks_repo_name": "rvanvenetie/spacetime", "max_forks_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_forks_repo_licenses": ["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.647311828, "max_line_length": 80, "alphanum_fraction": 0.6876008701, "num_tokens": 4132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.2940586976544659}}
{"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:40:14\n\n#ifndef NSM_TWO_SCALE_susy_parameters_H\n#define NSM_TWO_SCALE_susy_parameters_H\n\n#include \"betafunction.hpp\"\n#include \"NSM_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 NSM_susy_parameters : public Beta_function {\npublic:\n   explicit NSM_susy_parameters(const NSM_input_parameters& input_ = NSM_input_parameters());\n   NSM_susy_parameters(double scale_, double loops_, double thresholds_, const NSM_input_parameters& input_, double g1_, double g2_, double g3_, double Lambda2_, double Lambda3_,\n   double Lambda1_, const Eigen::Matrix<double,3,3>& Yu_, const Eigen::Matrix<\n   double,3,3>& Yd_, const Eigen::Matrix<double,3,3>& Ye_\n);\n   virtual ~NSM_susy_parameters() {}\n   virtual Eigen::ArrayXd beta() const;\n   virtual Eigen::ArrayXd get() const;\n   virtual void print(std::ostream&) const;\n   virtual void set(const Eigen::ArrayXd&);\n   const NSM_input_parameters& get_input() const;\n   NSM_input_parameters& get_input();\n   void set_input_parameters(const NSM_input_parameters&);\n\n   NSM_susy_parameters calc_beta() const;\n   virtual void clear();\n\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_Lambda2(double Lambda2_) { Lambda2 = Lambda2_; }\n   void set_Lambda3(double Lambda3_) { Lambda3 = Lambda3_; }\n   void set_Lambda1(double Lambda1_) { Lambda1 = Lambda1_; }\n   void set_Yu(const Eigen::Matrix<double,3,3>& Yu_) { Yu = Yu_; }\n   void set_Yu(int i, int k, double value) { Yu(i,k) = value; }\n   void set_Yd(const Eigen::Matrix<double,3,3>& Yd_) { Yd = Yd_; }\n   void set_Yd(int i, int k, 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, double value) { Ye(i,k) = value; }\n\n   double get_g1() const { return g1; }\n   double get_g2() const { return g2; }\n   double get_g3() const { return g3; }\n   double get_Lambda2() const { return Lambda2; }\n   double get_Lambda3() const { return Lambda3; }\n   double get_Lambda1() const { return Lambda1; }\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   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\n\n\nprotected:\n   double g1;\n   double g2;\n   double g3;\n   double Lambda2;\n   double Lambda3;\n   double Lambda1;\n   Eigen::Matrix<double,3,3> Yu;\n   Eigen::Matrix<double,3,3> Yd;\n   Eigen::Matrix<double,3,3> Ye;\n\n   NSM_input_parameters input;\n\nprivate:\n   static const int numberOfParameters = 33;\n\n   struct Susy_traces {\n      double traceYdAdjYd;\n      double traceYeAdjYe;\n      double traceYuAdjYu;\n      double traceYdAdjYdYdAdjYd;\n      double traceYdAdjYuYuAdjYd;\n      double traceYeAdjYeYeAdjYe;\n      double traceYuAdjYuYuAdjYu;\n      double traceYdAdjYdYdAdjYdYdAdjYd;\n      double traceYdAdjYdYdAdjYuYuAdjYd;\n      double traceYdAdjYuYuAdjYdYdAdjYd;\n      double traceYdAdjYuYuAdjYuYuAdjYd;\n      double traceYeAdjYeYeAdjYeYeAdjYe;\n      double traceYuAdjYuYuAdjYuYuAdjYu;\n\n   };\n   void calc_susy_traces(Susy_traces&) const;\n\n   double calc_beta_g1_one_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_g1_two_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_g1_three_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_g2_one_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_g2_two_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_g2_three_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_g3_one_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_g3_two_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_g3_three_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_Lambda2_one_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_Lambda2_two_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_Lambda2_three_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_Lambda3_one_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_Lambda3_two_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_Lambda3_three_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_Lambda1_one_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_Lambda1_two_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_Lambda1_three_loop(const TRACE_STRUCT_TYPE&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Yu_one_loop(const TRACE_STRUCT_TYPE&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Yu_two_loop(const TRACE_STRUCT_TYPE&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Yu_three_loop(const TRACE_STRUCT_TYPE&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Yd_one_loop(const TRACE_STRUCT_TYPE&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Yd_two_loop(const TRACE_STRUCT_TYPE&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Yd_three_loop(const TRACE_STRUCT_TYPE&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Ye_one_loop(const TRACE_STRUCT_TYPE&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Ye_two_loop(const TRACE_STRUCT_TYPE&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Ye_three_loop(const TRACE_STRUCT_TYPE&) const;\n\n};\n\nstd::ostream& operator<<(std::ostream&, const NSM_susy_parameters&);\n\n#undef TRACE_STRUCT_TYPE\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "d781fc790d336e33966ca5cee8879a8c36ce1e6f", "size": 6428, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/NSM/NSM_two_scale_susy_parameters.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/NSM/NSM_two_scale_susy_parameters.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/NSM/NSM_two_scale_susy_parameters.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": 40.9426751592, "max_line_length": 178, "alphanum_fraction": 0.7324206596, "num_tokens": 1740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2939901141812518}}
{"text": "/*\n*  Template of a compute module\n*/\n\n#include <QApplication>\n\n#include <hxcore/HxMessage.h>\n#include <hxcore/internal/HxWorkArea.h>\n#include <hxfield/HxUniformScalarField3.h>\n\n#include \"CCPiXtekNoShiftReconstruction.h\"\n#include \"base_types.hpp\"\n#include \"mpi.hpp\"\n#include \"utils.hpp\"\n#include \"instruments.hpp\"\n#include \"algorithms.hpp\"\n#include \"cgls.hpp\"\n#include \"sirt.hpp\"\n#include \"mlem.hpp\"\n#include \"results.hpp\"\n#include \"voxels.hpp\"\n#include \"ui_messages.hpp\"\n#include <boost/multi_array.hpp>\n\nHX_INIT_CLASS(CCPiXtekNoShiftReconstruction, HxCompModule)\n\n\tCCPiXtekNoShiftReconstruction::CCPiXtekNoShiftReconstruction() :\nHxCompModule(HxUniformScalarField3::getClassTypeId()),\n\tportAction(this,\"action\",QApplication::translate(\"CCPiXtekNoShiftReconstruction\",\n\t\"Action\")),\n\talgorithm(this, \"algorithm\",\n\tQApplication::translate(\"CCPiXtekNoShiftReconstruction\",\n\t\"Reconstruction Algorithm\")),\n\titerations(this, \"number of iterations\",\n\tQApplication::translate(\"CCPiXtekNoShiftReconstruction\", \"Iterations\")),\n\tresolution(this, \"resolution\", QApplication::translate(\"CCPiXtekNoShiftReconstruction\", \"Pixels per Voxel\")),\n\tbeam_harden(this, \"beam harden\",\n\tQApplication::translate(\"CCPiXtekNoShiftReconstruction\", \"Beam Hardening\")),\n\tregularize(this, \"regularize\", QApplication::translate(\"CCPiXtekNoShiftReconstruction\", \"Regularization parameter\"))\n{\n\tportAction.setLabel(0,\"DoIt\");\n\talgorithm.setNum(5);\n\talgorithm.setLabel(0, \"CGLS\");\n\talgorithm.setLabel(1, \"SIRT\");\n\talgorithm.setLabel(2, \"MLEM\");\n\talgorithm.setLabel(3, \"CGLS/Tikhonov\");\n\talgorithm.setLabel(4, \"CGLS/TV reg\");\n\talgorithm.setValue(0);\n\titerations.setMinMax(5, 30);\n\titerations.setValue(20);\n\tresolution.setMinMax(1, 8);\n\tresolution.setValue(1);\n\tbeam_harden.setValue(false);\n\tregularize.setNum(1);\n\tregularize.setMinMax(0.00001, 0.2);\n\tregularize.setValue(0.01);\n\tregularize.hide();\n}\n\nCCPiXtekNoShiftReconstruction::~CCPiXtekNoShiftReconstruction()\n{\n}\n\nvoid CCPiXtekNoShiftReconstruction::compute()\n{\n\t// Check whether the action port button was clicked\n  if (!portAction.wasHit()) {\n    if (algorithm.isNew()) {\n      if (algorithm.getValue() < 3)\n\tregularize.hide();\n      else\n\tregularize.show();\n    }\n    return;\n  }\n\tccpi_recon::do_progress = false;\n\tccpi_recon::messages = theMsg;\n\tccpi_recon::progress = theWorkArea;\n\tHxUniformScalarField3* field = (HxUniformScalarField3*) portData.getSource();\n\t// Check whether the input port is connected\n\tif (field == 0)\n\t{\n\t\ttheMsg->stream()<<\"Is not connected to uniform scalar field source\"<<std::endl;\n\t\treturn;\n\t}\n\tfloat *angles = new float[field->lattice().getDims()[2]];\n\tint result = field->parameters.findReal(\"Angles\", field->lattice().getDims()[2], angles);\n\t//Check the Rotation Angle\n\tif (result!=1)\n\t{\n\t\ttheMsg->stream()<<\"Angles parameter not found in input data\"<<result<<std::endl;\n\t\treturn;\n\t}\n\t// Todo - check of optional shifts\n\tfloat *pixel_size = new float[2];\n\tresult = field->parameters.findReal(\"DetectorPixelSize\", 2,pixel_size);\n\tif(result!=1)\n\t{\n\t\ttheMsg->stream()<<\"DetectorPixelSize parameter not found in input data\"<<result<<std::endl;\n\t\treturn;\n\t}\n\tdouble srcToObject;\n\tresult = field->parameters.findReal(\"SourceToObject\", srcToObject);\n\tif(result!=1)\n\t{\n\t\ttheMsg->stream()<<\"SourceToObject parameter not found in input data\"<<std::endl;\n\t\treturn;\n\t}\n\tdouble srcToDetector;\n\tresult = field->parameters.findReal(\"SourceToDetector\", srcToDetector);\n\tif(result!=1)\n\t{\n\t\ttheMsg->stream()<<\"SourceToDetector parameter not found in input data\"<<std::endl;\n\t\treturn;\n\t}\n\n\t// Todo - check that its a float field?\n\trun_reconstruction();\n\n\t// end progress area\n\tif (ccpi_recon::do_progress) {\n\t\ttheWorkArea->stopWorking();\n\t\ttheWorkArea->undivide();\n\t}\n}\n\nvoid CCPiXtekNoShiftReconstruction::run_reconstruction()\n{\n\tHxUniformScalarField3 *field = (HxUniformScalarField3 *) portData.getSource();\n\tMcDim3l fdims = field->lattice().getDims();\n\tboost::multi_array_ref<float, 3>\n\t\tpixels_ref((float *)field->lattice().dataPtr(),\n\t\tboost::extents[fdims[0]][fdims[1]][fdims[2]],\n\t\tboost::fortran_storage_order());\n\n\t//Convert pixels to correct order\n\tpixel_3d pixels(boost::extents[fdims[2]][fdims[1]][fdims[0]]);\n\tfor (int i = 0; i < fdims[2]; i++)\n\t\tfor (int j = 0; j < fdims[1]; j++)\n\t\t\tfor (int k = 0; k < fdims[0]; k++)\n\t\t\t\tpixels[i][j][k] = pixels_ref[k][j][i];\n\n\tfloat *angles_float = new float[field->lattice().getDims()[2]];\n\tfield->parameters.findReal(\"Angles\", field->lattice().getDims()[2], angles_float);\n\tfloat *pixel_size = new float[2];\n\tfield->parameters.findReal(\"DetectorPixelSize\", 2,pixel_size);\n\tdouble srcToObject;\n\tfield->parameters.findReal(\"SourceToObject\", srcToObject);\n\tdouble srcToDetector;\n\tfield->parameters.findReal(\"SourceToDetector\", srcToDetector);\n\tdouble MaskRadius;\n\tfield->parameters.findReal(\"MaskRadius\", MaskRadius);\n\tboost::multi_array_ref<float, 1> angles(angles_float,\n\t\t\t\t\t\tboost::extents[fdims[2]]);\n\n\treal h_size = pixel_size[0];\n\treal v_size = pixel_size[1];\n\n\treal source_x = - srcToObject;\n\treal detector_x = srcToDetector + source_x;\n\n\tint pixels_per_voxel = resolution.getValue();\n\tint niterations = iterations.getValue();\n\tbool beam_hardening = beam_harden.getValue();\n\tfloat reg_param = regularize.getValue();\n\n\tCCPi::instrument *instrument = new CCPi::Nikon_XTek();\n\n\tCCPi::reconstruction_alg *recon_algorithm = 0;\n\tswitch (algorithm.getValue()) {\n\tcase 0:\n\t\t//if (blocking_factor > 0 and instrument->supports_blocks())\n\t\t//  recon_algorithm = new CCPi::cgls_2d(niterations, pixels_per_voxel);\n\t\trecon_algorithm = new CCPi::cgls_3d(niterations);\n\t\tbreak;\n\tcase 1:\n\t\trecon_algorithm = new CCPi::sirt(niterations);\n\t\tbreak;\n\tcase 2:\n\t\trecon_algorithm = new CCPi::mlem(niterations);\n\t\tbreak;\n\tcase 3:\n\t  recon_algorithm = new CCPi::cgls_tikhonov(niterations, reg_param);\n\t\tbreak;\n\tcase 4:\n\t  recon_algorithm = new CCPi::cgls_tv_reg(niterations, reg_param);\n\t\tbreak;\n\t}\n\n\tmachine::initialise(0);\n\t// instrument setup from pixels/angles will probably copy\n\tboost::multi_array<float, 1> h_offsets(boost::extents[1]);\n\tboost::multi_array<float, 1> v_offsets(boost::extents[1]);\n\treal vox_origin[3];\n\treal vox_size[3];\n\tvoxel_data *voxels = reconstruct(instrument, recon_algorithm, pixels,\n\t\t\t\t\t angles, h_offsets, v_offsets,\n\t\t\t\t\t pixels_per_voxel, source_x, detector_x,\n\t\t\t\t\t h_size, v_size, MaskRadius,\n\t\t\t\t\t beam_hardening, vox_origin, vox_size,\n\t\t\t\t\t false, false);\n\ttheMsg->stream() << \"completed the reconstruction: \" << voxels<< std::endl;\n\n\tmachine::exit();\n\tdelete recon_algorithm;\n\tdelete instrument;\n\tif (voxels != 0) {\n\t\tint dims[3];\n\n\t\tdims[0] = voxels->shape()[0];\n\t\tdims[1] = voxels->shape()[1];\n\t\tdims[2] = voxels->shape()[2];\n\t\tHxUniformScalarField3* output =\n\t\t\tnew HxUniformScalarField3(dims, McPrimType::MC_FLOAT);\n\t\tfor (int i = 0; i < dims[0]; i++)\n\t\t\tfor (int j = 0; j < dims[1]; j++)\n\t\t\t\tfor (int k = 0; k < dims[2]; k++)\n\t\t\t\t\toutput->set(i, j, k, (*voxels)[i][j][k]);\n\t\tdelete voxels;\n\t\tHxUniformCoord3 *coords =(HxUniformCoord3 *) output->lattice().coords();\n\t\tMcBox3f bx = coords->getBoundingBox();\n\t\tbx[0] = vox_origin[0];\n\t\tbx[1] = vox_origin[0] + float(dims[0]) * vox_size[0];\n\t\tbx[2] = vox_origin[1];\n\t\tbx[3] = vox_origin[1] + float(dims[1]) * vox_size[1];\n\t\tbx[4] = vox_origin[2];\n\t\tbx[5] = vox_origin[2] + float(dims[2]) * vox_size[2];\n\t\t// publish reconstruction\n\t\tsetResult(output); \n\t}\n}\n", "meta": {"hexsha": "8098880973724ae6d1e5e3d1e4f45b45982e5ab7", "size": 7319, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Wrappers/Avizo/src/CCPiReconstruction/CCPiXtekNoShiftReconstruction.cpp", "max_stars_repo_name": "vais-ral/CCPi-Reconstruction", "max_stars_repo_head_hexsha": "6c9f5eb9af308981b6d1c910dc1a38e8f6e83acd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-11-09T11:58:32.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T11:58:32.000Z", "max_issues_repo_path": "Wrappers/Avizo/src/CCPiReconstruction/CCPiXtekNoShiftReconstruction.cpp", "max_issues_repo_name": "vais-ral/CCPi-Reconstruction", "max_issues_repo_head_hexsha": "6c9f5eb9af308981b6d1c910dc1a38e8f6e83acd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2018-05-22T12:58:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-15T14:54:04.000Z", "max_forks_repo_path": "Wrappers/Avizo/src/CCPiReconstruction/CCPiXtekNoShiftReconstruction.cpp", "max_forks_repo_name": "vais-ral/CCPi-Reconstruction", "max_forks_repo_head_hexsha": "6c9f5eb9af308981b6d1c910dc1a38e8f6e83acd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-01-11T12:04:53.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-11T12:04:53.000Z", "avg_line_length": 31.5474137931, "max_line_length": 117, "alphanum_fraction": 0.7151250171, "num_tokens": 2105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.29389388148268325}}
{"text": "// Copyright (c) 2020, Oracle and/or its affiliates.\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, version 2.0,\n// as published by the Free Software Foundation.\n//\n// This program is also distributed with certain software (including\n// but not limited to OpenSSL) that is licensed under separate terms,\n// as designated in a particular file or component or in included license\n// documentation.  The authors of MySQL hereby grant you an additional\n// permission to link the program and your derivative works with the\n// separately licensed software that they have included with MySQL.\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, version 2.0, 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA.\n\n/// @file\n///\n/// This file implements the discrete Hausdorff distance functor and function.\n\n#include <cmath>  // std::isfinite\n\n#include <boost/geometry.hpp>\n#include \"my_inttypes.h\"                            // MYF\n#include \"my_sys.h\"                                 // my_error\n#include \"mysqld_error.h\"                           // Error codes\n#include \"sql/dd/types/spatial_reference_system.h\"  // dd::Spatial_reference_system\n#include \"sql/gis/gc_utils.h\"\n#include \"sql/gis/geometries.h\"\n#include \"sql/gis/geometries_traits.h\"\n#include \"sql/gis/hausdorff_distance.h\"\n#include \"sql/gis/hausdorff_distance_functor.h\"\n#include \"sql/sql_exception_handler.h\"  // handle_gis_exception\n\nnamespace bg = boost::geometry;\nnamespace bgs = boost::geometry::srs;\nnamespace bgsd = boost::geometry::strategy::distance;\n\nnamespace gis {\n\nHausdorff_distance::Hausdorff_distance(double major, double minor)\n    : m_geographic_strategy(\n          new bgsd::geographic<boost::geometry::strategy::andoyer,\n                               bgs::spheroid<double>>(\n              bgs::spheroid<double>(major, minor))) {}\n\ndouble Hausdorff_distance::operator()(const Geometry *g1,\n                                      const Geometry *g2) const {\n  return apply(*this, g1, g2);\n}\n\ndouble Hausdorff_distance::eval(const Geometry *g1, const Geometry *g2) const {\n  throw not_implemented_exception::for_non_projected(*g1, *g2);\n}\n\ndouble Hausdorff_distance::eval(const Cartesian_point *g1,\n                                const Cartesian_multipoint *g2) const {\n  return bg::discrete_hausdorff_distance(*g1, *g2);\n}\n\ndouble Hausdorff_distance::eval(const Cartesian_multipoint *g1,\n                                const Cartesian_point *g2) const {\n  return bg::discrete_hausdorff_distance(*g2, *g1);\n}\n\ndouble Hausdorff_distance::eval(const Cartesian_linestring *g1,\n                                const Cartesian_linestring *g2) const {\n  return bg::discrete_hausdorff_distance(*g1, *g2);\n}\n\ndouble Hausdorff_distance::eval(const Cartesian_multipoint *g1,\n                                const Cartesian_multipoint *g2) const {\n  return bg::discrete_hausdorff_distance(*g1, *g2);\n}\n\ndouble Hausdorff_distance::eval(const Cartesian_linestring *g1,\n                                const Cartesian_multilinestring *g2) const {\n  return bg::discrete_hausdorff_distance(*g1, *g2);\n}\n\ndouble Hausdorff_distance::eval(const Cartesian_multilinestring *g1,\n                                const Cartesian_linestring *g2) const {\n  return bg::discrete_hausdorff_distance(*g2, *g1);\n}\n\ndouble Hausdorff_distance::eval(const Cartesian_multilinestring *g1,\n                                const Cartesian_multilinestring *g2) const {\n  return bg::discrete_hausdorff_distance(*g1, *g2);\n}\n\ndouble Hausdorff_distance::eval(const Geographic_point *g1,\n                                const Geographic_multipoint *g2) const {\n  return bg::discrete_hausdorff_distance(*g1, *g2, *m_geographic_strategy);\n}\n\ndouble Hausdorff_distance::eval(const Geographic_multipoint *g1,\n                                const Geographic_point *g2) const {\n  return bg::discrete_hausdorff_distance(*g2, *g1, *m_geographic_strategy);\n}\n\ndouble Hausdorff_distance::eval(const Geographic_linestring *g1,\n                                const Geographic_linestring *g2) const {\n  return bg::discrete_hausdorff_distance(*g1, *g2, *m_geographic_strategy);\n}\n\ndouble Hausdorff_distance::eval(const Geographic_multipoint *g1,\n                                const Geographic_multipoint *g2) const {\n  return bg::discrete_hausdorff_distance(*g1, *g2, *m_geographic_strategy);\n}\n\ndouble Hausdorff_distance::eval(const Geographic_linestring *g1,\n                                const Geographic_multilinestring *g2) const {\n  return bg::discrete_hausdorff_distance(*g1, *g2, *m_geographic_strategy);\n}\n\ndouble Hausdorff_distance::eval(const Geographic_multilinestring *g1,\n                                const Geographic_linestring *g2) const {\n  return bg::discrete_hausdorff_distance(*g2, *g1, *m_geographic_strategy);\n}\n\ndouble Hausdorff_distance::eval(const Geographic_multilinestring *g1,\n                                const Geographic_multilinestring *g2) const {\n  return bg::discrete_hausdorff_distance(*g1, *g2, *m_geographic_strategy);\n}\n\n/////////////////////////////////////////////////////////////////////////////\n\nbool hausdorff_distance(const dd::Spatial_reference_system *srs,\n                        const Geometry *g1, const Geometry *g2,\n                        const char *func_name, double *hausdorff_distance,\n                        bool *is_null) noexcept {\n  try {\n    DBUG_ASSERT(g1->coordinate_system() == g2->coordinate_system());\n    DBUG_ASSERT(srs == nullptr ||\n                ((srs->is_cartesian() &&\n                  g1->coordinate_system() == Coordinate_system::kCartesian) ||\n                 (srs->is_geographic() &&\n                  g1->coordinate_system() == Coordinate_system::kGeographic)));\n\n    if ((*is_null = (g1->is_empty() || g2->is_empty()))) return false;\n\n    Hausdorff_distance hd(srs ? srs->semi_major_axis() : 0.0,\n                          srs ? srs->semi_minor_axis() : 0.0);\n    *hausdorff_distance = hd(g1, g2);\n  } catch (...) {\n    handle_gis_exception(func_name);\n    return true;\n  }\n\n  if (!std::isfinite(*hausdorff_distance) || *hausdorff_distance < 0.0) {\n    my_error(ER_DATA_OUT_OF_RANGE, MYF(0), \"Hausdorff_distance\", func_name);\n    return true;\n  }\n\n  return false;\n}\n\n}  // namespace gis\n", "meta": {"hexsha": "04578dede66b3b87591e9abadc2849ed9fde56d2", "size": 6644, "ext": "cc", "lang": "C++", "max_stars_repo_path": "mysql-server/sql/gis/hausdorff_distance.cc", "max_stars_repo_name": "silenc3502/MYSQL-Arch-Doc-Summary", "max_stars_repo_head_hexsha": "fcc6bb65f72a385b9f56debc9b2c00cee5914bae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mysql-server/sql/gis/hausdorff_distance.cc", "max_issues_repo_name": "silenc3502/MYSQL-Arch-Doc-Summary", "max_issues_repo_head_hexsha": "fcc6bb65f72a385b9f56debc9b2c00cee5914bae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mysql-server/sql/gis/hausdorff_distance.cc", "max_forks_repo_name": "silenc3502/MYSQL-Arch-Doc-Summary", "max_forks_repo_head_hexsha": "fcc6bb65f72a385b9f56debc9b2c00cee5914bae", "max_forks_repo_licenses": ["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.2666666667, "max_line_length": 83, "alphanum_fraction": 0.6640577965, "num_tokens": 1625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.29389388148268325}}
{"text": "#ifndef CELL_HPP\n#define CELL_HPP\n\n#include \"vector\"\n#include \"array\"\n#include \"iostream\"\n\n\n#include <Eigen/Dense>\n#include \"mpi.h\"\n\nusing namespace Eigen;\n\n/// 4x1 vector FIXME multiple definitions of the same type also in pic.cpp\ntypedef Array<double, 4, 1> vec4;\n// typedef Array<double, 3, 1> vec3;\n\n/// Full 4x4 GR vector\ntypedef Array<double, 4, 4> mat4;\n\n// Define cell types for different boundary conditions\n#define NORMAL_CELL 0               ///< Cell in a normal state\n#define METAL_BOUNDARY_X_CELL 1     ///< Cell with a conducting X boundary\n#define METAL_BOUNDARY_Y_CELL 2     ///< Cell with a conducting Y boundary\n\n\n// Enumarete particle populations\nenum Population\n{\n    ELECTRONS, ///< Electron particle population\n    POSITRONS,  ///< positron particle population\n    N_POPULATIONS\n};\n\n\n\n/// Modular Cell class for mpiGrid\n/**\nCell class to handle MPI communications\n*/\n\nclass Cell\n{\npublic:\n        \n\n    /// current number of electrons inside the Cell\n\t// unsigned int number_of_electrons = 0;\n    \n    /// current number of positrons inside the Cell\n\t// unsigned int number_of_positrons = 0;\n\n    std::array<uint64_t , Population::N_POPULATIONS> particles_in_population;\n\n    uint64_t& number_of(Population particle_population)\n    {\n        return particles_in_population[particle_population];\n    };\n\n    /// Particle 6D phase space populations\n    ///@{\n\t/// 6D phase space coordinates of electrons in this cell\n\tstd::vector<std::array<double, 6> > electrons;\n    \n\t/// 6D phase space coordinates of positrons in this cell\n\tstd::vector<std::array<double, 6> > positrons;\n    ///@}\n\n\n    /// Particle population switcher TODO fix/check performance\n    std::vector<std::array<double, 6> >& particles(Population particle_population)\n    {\n        switch(particle_population) {\n            case Population::ELECTRONS:\n                return this->electrons;\n                break; \n            case Population::POSITRONS:\n                return this->positrons;\n                break; \n            default:\n                    std::cerr << __FILE__ << \":\" << __LINE__\n                    << \" Invalid population switch: \" << particle_population\n                    << std::endl;\n                abort();\n                break;\n        }\n    };\n\n\n\n    /// 4-current vector containing (rho, Jx, Jy, Jz)\n    vec4 J;\n\n    /// standard 3-vector for currents & field vectors at Yee lattice staggeration\n    /**\n        XXX Here we use 3+1 formalism which is more easily\n        expressed via E and B, not F tensor\n    */\n    Vector3d JY, BY, EY;\n\n\n    /* Yee staggered field tensor \n        note that E and B elements are defined in different locations\n        due to the staggering\n     mat4 FY = mat4::Zero();\n    */\n\n\n    // Yee lattice/mesh stuff array\n    /*\n        0 - charge density rho\n        DONE 1 2 3    - current vector on nodal points Jx, Jy, Jz\n        DONE 4 5 6    - current vector on Yee lattice  JxY, JyY, JzY\n        7 8 9    - E field on Yee lattice ExY, EyY, EzY\n        10 11 12 - B field on Yee lattice BxY, ByY, BzY\n\n        13 14 15 - E field on nodal lattice Ex, Ey, Ez\n        16 17 18 - B field on nodal lattice Bx, By, Bz\n    std::array<double, 19> field = {{0.0, \n                                     0.0, 0.0, 0.0,\n                                     0.0, 0.0, 0.0,\n                                     0.0, 0.0, 0.0,\n                                     0.0, 0.0, 0.0,\n                                     0.0, 0.0, 0.0,\n                                     0.0, 0.0, 0.0}};\n    */\n\n\n    /// incoming currents from other processes\n    /**  3x3x3 cube with four-vector elements = 108 values */\n    std::array<double, 108> incoming_currents;\n\n\n\n    /** @name Auxiliary functions \n     *  auxiliary functions to help disentangle lattice values\n     *\n     *  note how we always give normal and const definition\n     *  this makes sure the variable pointed to by the returned \n     *  pointer & won't be alterable and that the method does not \n     *  alter the variable pointed to by the given pointer. (phew!)\n    */\n\n    /*\n    ///@{\n    /// overload array operator for object\n    double& operator [](const std::size_t i){return this->field[i];}\n    const double& operator [](const std::size_t i) const {return this->field[i];}\n\n    /// charge density\n    double& rho(){ return this->field[0]; }\n    const double& rho() const { return this->field[0]; }\n\n    /// nodal current x\n    double& Jx(){ return this->field[1]; }\n    const double& Jx() const { return this->field[1]; }\n\n    /// nodal current y\n    double& Jy(){ return this->field[2]; }\n    const double& Jy() const { return this->field[2]; }\n\n    /// nodal current z\n    double& Jz(){ return this->field[3]; }\n    const double& Jz() const { return this->field[3]; }\n\n    /// Yee currents x\n    double& JxY(){ return this->field[4]; }\n    const double& JxY() const { return this->field[4]; }\n\n    /// Yee currents y\n    double& JyY(){ return this->field[5]; }\n    const double& JyY() const { return this->field[5]; }\n\n    /// Yee currents z\n    double& JzY(){ return this->field[6]; }\n    const double& JzY() const { return this->field[6]; }\n\n    /// Yee E x\n    double& ExY(){ return this->field[7]; }\n    const double& ExY() const { return this->field[7]; }\n\n    /// Yee E y\n    double& EyY(){ return this->field[8]; }\n    const double& EyY() const { return this->field[8]; }\n\n    /// Yee E z\n    double& EzY(){ return this->field[9]; }\n    const double& EzY() const { return this->field[9]; }\n\n    /// Yee B x\n    double& BxY(){ return this->field[10]; }\n    const double& BxY() const { return this->field[10]; }\n\n    /// Yee B y\n    double& ByY(){ return this->field[11]; }\n    const double& ByY() const { return this->field[11]; }\n\n    /// Yee B z\n    double& BzY(){ return this->field[12]; }\n    const double& BzY() const { return this->field[12]; }\n\n    /// nodal E field vector x\n    double& Ex(){ return this->field[13]; }\n    const double& Ex() const { return this->field[13]; }\n\n    /// nodal E field vector y\n    double& Ey(){ return this->field[14]; }\n    const double& Ey() const { return this->field[14]; }\n\n    /// nodal E field vector z\n    double& Ez(){ return this->field[15]; }\n    const double& Ez() const { return this->field[15]; }\n\n\n    /// nodal B x\n    double& Bx(){ return this->field[16]; }\n    const double& Bx() const { return this->field[16]; }\n\n    /// nodal B y\n    double& By(){ return this->field[17]; }\n    const double& By() const { return this->field[17]; }\n\n    /// nodal B z\n    double& Bz(){ return this->field[18]; }\n    const double& Bz() const { return this->field[18]; }\n    ///@}\n    */\n\n\n    /// Cell type XXX: use me!\n    double cell_type = 0;\n\n    /// list of remote neighbors\n    std::array<uint64_t, 27> \n        remote_neighbor_list = {{0, 0, 0, 0, 0, 0, 0, 0, 0,\n                                 0, 0, 0, 0, 0, 0, 0, 0, 0,\n                                 0, 0, 0, 0, 0, 0, 0, 0, 0\n                                }};\n\n    /// transfer switch \n\t/**\n     Defines what is transferred over MPI\n\t*/\n\tstatic int transfer_mode;\n\n    // Enumarete data types\n    enum {\n        INIT,                 /// < data related to initialization\n        NUMBER_OF_ELECTRONS,  /// < Number of electrons to expect\n        NUMBER_OF_POSITRONS,  /// < Number of positrons to expect\n        ELECTRONS,            /// < 6D electron phase phases\n        POSITRONS,            /// < 6D positron phase phases\n        FIELDS,               /// < data of EM fields\n\t\tREMOTE_NEIGHBOR_LIST, /// < List of remote neighbors sending to me\n\t\tINCOMING_CURRENTS,    /// < data of incoming currents\n        CURRENT,              /// < current four vector\n        YEE_CURRENT,          /// < staggered current four vector\n        YEE_B,                /// < Staggered B field\n        YEE_E,                /// < Staggered E field\n\t\tTYPE                  /// < Cell type\n    };\n\n\n    /// handle the MPI calls depending on cell state\n\tstd::tuple<void*, int, MPI_Datatype> get_mpi_datatype();\n\n\n\t/// reserves space for electron phase space data coming over MPI\n    /// TODO make ambigious of population\n    void resize_population(Population particle_population)\n    {\n        switch(particle_population) {\n            case Population::ELECTRONS:\n                this->electrons.resize(this->number_of(Population::ELECTRONS));\n                break; \n            case Population::POSITRONS:\n                this->positrons.resize(this->number_of(Population::POSITRONS));\n                break; \n            default:\n                    std::cerr << __FILE__ << \":\" << __LINE__\n                    << \" Invalid population switch: \" << particle_population\n                    << std::endl;\n                abort();\n                break;\n        }\n    };\n\n\n\n\n};\n\n\n\n\n\n#endif\n\n", "meta": {"hexsha": "adab2fa507284f265205ed7394cd865c6698dfd5", "size": 8792, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "prototypes/cpp-pic/cell.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/cell.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/cell.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": 29.4046822742, "max_line_length": 82, "alphanum_fraction": 0.5642629663, "num_tokens": 2363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2938938814826832}}
{"text": "#include \"anomaly.h\"\n#include \"../util.h\"\n\n#include <boost/exception/all.hpp>\n\nnamespace Akumuli {\nnamespace QP {\n\nstatic AnomalyDetector::FcastMethod parse_anomaly_detector_type(boost::property_tree::ptree const& ptree) {\n    bool approx = ptree.get<bool>(\"approx\");\n    std::string name = ptree.get<std::string>(\"method\");\n    AnomalyDetector::FcastMethod method;\n    if (name == \"ewma\" || name == \"exp-smoothing\") {\n        method = approx ? AnomalyDetector::EWMA_SKETCH : AnomalyDetector::EWMA;\n    } else if (name == \"sma\" || name == \"simple-moving-average\") {\n        method = approx ? AnomalyDetector::SMA_SKETCH : AnomalyDetector::SMA;\n    } else if (name == \"double-exp-smoothing\") {\n        method = approx ? AnomalyDetector::DOUBLE_EXP_SMOOTHING_SKETCH : AnomalyDetector::DOUBLE_EXP_SMOOTHING;\n    } else if (name == \"holt-winters\") {\n        method = approx ? AnomalyDetector::HOLT_WINTERS_SKETCH : AnomalyDetector::HOLT_WINTERS;\n    } else {\n        QueryParserError err(\"Unknown forecasting method\");\n        BOOST_THROW_EXCEPTION(err);\n    }\n    return method;\n}\n\nstatic void validate_sketch_params(boost::property_tree::ptree const& ptree) {\n    uint32_t bits = ptree.get<uint32_t>(\"bits\", 8);\n    uint32_t hashes = ptree.get<uint32_t>(\"hashes\", 1);\n    // bits should be in range\n    if (bits < 8 || bits > 16) {\n        QueryParserError err(\"Anomaly detector parameter `bits` out of range\");\n        BOOST_THROW_EXCEPTION(err);\n    }\n    // hashes should be in range and odd\n    if (hashes % 2 == 0) {\n        QueryParserError err(\"Anomaly detector parameter `hashes` should be odd\");\n        BOOST_THROW_EXCEPTION(err);\n    }\n    if (hashes == 0 || hashes > 9) {\n        QueryParserError err(\"Anomaly detector parameter `hashes` out of range\");\n        BOOST_THROW_EXCEPTION(err);\n    }\n}\n\nstatic void validate_all_params(std::vector<std::string> required, boost::property_tree::ptree const& ptree) {\n    for (auto name: required) {\n        auto o = ptree.get_optional<std::string>(name);\n        if (!o) {\n            std::string err_msg = \"Parameter \" + name + \" should be set\";\n            QueryParserError err(err_msg.c_str());\n            BOOST_THROW_EXCEPTION(err);\n        }\n    }\n}\n\nstatic void validate_anomaly_detector_params(boost::property_tree::ptree const& ptree) {\n    auto type = parse_anomaly_detector_type(ptree);\n    switch(type) {\n    case AnomalyDetector::SMA_SKETCH:\n        validate_sketch_params(ptree);\n    case AnomalyDetector::SMA:\n        validate_all_params({\"period\"}, ptree);\n        break;\n\n    case AnomalyDetector::EWMA_SKETCH:\n        validate_sketch_params(ptree);\n    case AnomalyDetector::EWMA:\n        validate_all_params({\"alpha\"}, ptree);\n        break;\n\n    case AnomalyDetector::DOUBLE_EXP_SMOOTHING_SKETCH:\n        validate_sketch_params(ptree);\n    case AnomalyDetector::DOUBLE_EXP_SMOOTHING:\n        validate_all_params({\"alpha\", \"gamma\"}, ptree);\n        break;\n\n    case AnomalyDetector::HOLT_WINTERS_SKETCH:\n        validate_sketch_params(ptree);\n    case AnomalyDetector::HOLT_WINTERS:\n        validate_all_params({\"alpha\", \"beta\", \"gamma\", \"period\"}, ptree);\n        break;\n    }\n}\n\nstatic void validate_coef(double value, double range_begin, double range_end, const char* err_msg) {\n    if (value >= range_begin && value <= range_end) {\n        return;\n    }\n    QueryParserError err(err_msg);\n    BOOST_THROW_EXCEPTION(err);\n}\n\nAnomalyDetector::AnomalyDetector(boost::property_tree::ptree const& ptree, std::shared_ptr<Node> next)\n    : next_(next)\n{\n    validate_anomaly_detector_params(ptree);\n    double threshold = ptree.get<double>(\"threshold\");\n    uint32_t bits = ptree.get<uint32_t>(\"bits\", 10u);\n    uint32_t nhashes = ptree.get<uint32_t>(\"hashes\", 3u);\n    AnomalyDetector::FcastMethod method = parse_anomaly_detector_type(ptree);\n    double alpha = ptree.get<double>(\"alpha\", 0.0);\n    double beta = ptree.get<double>(\"beta\", 0.0);\n    double gamma = ptree.get<double>(\"gamma\", 0.0);\n    int period = ptree.get<int>(\"period\", 0);\n    validate_coef(alpha, 0.0, 1.0, \"`alpha` should be in [0, 1] range\");\n    validate_coef(beta,  0.0, 1.0, \"`beta` should be in [0, 1] range\");\n    validate_coef(gamma, 0.0, 1.0, \"`gamma` should be in [0, 1] range\");\n\n    switch(method) {\n    case SMA:\n        detector_ = AnomalyDetectorUtil::create_precise_sma(threshold, period);\n        break;\n    case SMA_SKETCH:\n        detector_ = AnomalyDetectorUtil::create_approx_sma(nhashes, 1 << bits, threshold, period);\n        break;\n    case EWMA:\n        detector_ = AnomalyDetectorUtil::create_precise_ewma(threshold, alpha);\n        break;\n    case EWMA_SKETCH:\n        detector_ = AnomalyDetectorUtil::create_approx_ewma(nhashes, 1 << bits, threshold, alpha);\n        break;\n    case DOUBLE_EXP_SMOOTHING:\n        detector_ = AnomalyDetectorUtil::create_precise_double_exp_smoothing(threshold, alpha, gamma);\n        break;\n    case DOUBLE_EXP_SMOOTHING_SKETCH:\n        detector_ = AnomalyDetectorUtil::create_approx_double_exp_smoothing(nhashes, 1 << bits, threshold, alpha, gamma);\n        break;\n    case HOLT_WINTERS:\n        detector_ = AnomalyDetectorUtil::create_precise_holt_winters(threshold, alpha, beta, gamma, period);\n        break;\n    case HOLT_WINTERS_SKETCH:\n        detector_ = AnomalyDetectorUtil::create_approx_holt_winters(nhashes, 1 << bits, threshold, alpha, beta, gamma, period);\n        break;\n    default:\n        AKU_PANIC(\"AnomalyDetector building error\");\n    }\n}\n\nAnomalyDetector::AnomalyDetector(\n        uint32_t nhashes,\n        uint32_t bits,\n        double   threshold,\n        double   alpha,\n        double   beta,\n        double   gamma,\n        int      period,\n        FcastMethod method,\n        std::shared_ptr<Node> next)\n    : next_(next)\n{\n    try {\n        switch(method) {\n        case SMA:\n            detector_ = AnomalyDetectorUtil::create_precise_sma(threshold, period);\n            break;\n        case SMA_SKETCH:\n            detector_ = AnomalyDetectorUtil::create_approx_sma(nhashes, 1 << bits, threshold, period);\n            break;\n        case EWMA:\n            detector_ = AnomalyDetectorUtil::create_precise_ewma(threshold, alpha);\n            break;\n        case EWMA_SKETCH:\n            detector_ = AnomalyDetectorUtil::create_approx_ewma(nhashes, 1 << bits, threshold, alpha);\n            break;\n        case DOUBLE_EXP_SMOOTHING:\n            detector_ = AnomalyDetectorUtil::create_precise_double_exp_smoothing(threshold, alpha, gamma);\n            break;\n        case DOUBLE_EXP_SMOOTHING_SKETCH:\n            detector_ = AnomalyDetectorUtil::create_approx_double_exp_smoothing(nhashes, 1 << bits, threshold, alpha, gamma);\n            break;\n        case HOLT_WINTERS:\n            detector_ = AnomalyDetectorUtil::create_precise_holt_winters(threshold, alpha, beta, gamma, period);\n            break;\n        case HOLT_WINTERS_SKETCH:\n            detector_ = AnomalyDetectorUtil::create_approx_holt_winters(nhashes, 1 << bits, threshold, alpha, beta, gamma, period);\n            break;\n        default:\n            std::logic_error err(\"AnomalyDetector building error\");  // invalid use of the constructor\n            BOOST_THROW_EXCEPTION(err);\n        }\n    } catch (...) {\n        // std::cout << boost::current_exception_diagnostic_information() << std::endl;\n        throw;\n    }\n}\n\nvoid AnomalyDetector::complete() {\n    next_->complete();\n}\n\nbool AnomalyDetector::put(const aku_Sample &sample) {\n    if (sample.payload.type == aku_PData::EMPTY) {\n        detector_->move_sliding_window();\n        return next_->put(sample);\n    } else if (sample.payload.type & aku_PData::FLOAT_BIT) {\n        detector_->add(sample.paramid, sample.payload.float64);\n        if (detector_->is_anomaly_candidate(sample.paramid)) {\n            aku_Sample anomaly = sample;\n            anomaly.payload.type |= aku_PData::URGENT;\n            return next_->put(anomaly);\n        }\n    }\n    // Ignore BLOBs\n    return true;\n}\n\nvoid AnomalyDetector::set_error(aku_Status status) {\n    next_->set_error(status);\n}\n\nint AnomalyDetector::get_requirements() const {\n    return TERMINAL|GROUP_BY_REQUIRED;\n}\n\n//! Register anomaly detector for use in queries\nstatic QueryParserToken<AnomalyDetector> detector_token(\"anomaly-detector\");\n\n}}  // namespace\n\n", "meta": {"hexsha": "0ee72046caa2e00b2df9941d90a24326423f0f75", "size": 8264, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libakumuli/query_processing/anomaly.cpp", "max_stars_repo_name": "vladon/Akumuli", "max_stars_repo_head_hexsha": "c45672a23b929ccb3a5743cc5e9aae980c160eb0", "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": "libakumuli/query_processing/anomaly.cpp", "max_issues_repo_name": "vladon/Akumuli", "max_issues_repo_head_hexsha": "c45672a23b929ccb3a5743cc5e9aae980c160eb0", "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": "libakumuli/query_processing/anomaly.cpp", "max_forks_repo_name": "vladon/Akumuli", "max_forks_repo_head_hexsha": "c45672a23b929ccb3a5743cc5e9aae980c160eb0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-22T07:11:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-22T07:11:13.000Z", "avg_line_length": 37.2252252252, "max_line_length": 131, "alphanum_fraction": 0.6603339787, "num_tokens": 2073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.29382738363008015}}
{"text": "/***\n *  $Id$\n **\n *  File: performance_indicators_diss.hpp\n *  Created: May 9, 2012\n *\n *  Author: Olga Wodo, Baskar Ganapathysubramanian\n *  Copyright (c) 2012 Olga Wodo, Baskar Ganapathysubramanian\n *  See accompanying LICENSE.\n *\n *  This file is part of GraSPI.\n */\n\n#ifndef PERFORMANCE_INDICATORS_DISS_HPP\n#define PERFORMANCE_INDICATORS_DISS_HPP\n\n#include <climits>\n#include <sstream>\n\n#include \"graspi_types.hpp\"\n#include \"graph_dijkstra.hpp\"\n#include \"graspi_predicates.hpp\"\n#include <boost/graph/filtered_graph.hpp>\n\n\nnamespace graspi {\n\n    /// structure used to estimate the contribution of electron donor to exciton dissociation\n    struct foo_w_diss{\n        double A1; ///< coefficient to define the exciton diffusion weighting function\n        double B1; ///< coefficient to define the exciton diffusion weighting function\n        double C1; ///< coefficient to define the exciton diffusion weighting function\n        foo_w_diss(){ A1=6.265; B1=-23.0; C1=17.17; }\n        double operator()(double d)const{\n            return A1*exp(-((d-B1)/C1)*((d-B1)/C1));\n        }\n    };\n\n    /// Function to count number of vertices within predefined distance to target vertices\n    ///\n    /// @param d is the vector of distances\n    /// @param Ld is the predefined distance to be checked against\n    /// return the total number of vertices within the Ld distance to the targeted meta-vertex\n    inline int\n    identify_n_vertices_within_distance( const std::vector<float>& d,\n                                        double Ld){\n        int n_Ld = 0;\n        for(unsigned int i = 0; i < d.size(); i++){\n            if( (d[i] < Ld) && (d[i] > 0) ) n_Ld++;\n        }\n        return n_Ld;\n    }\n\n    /// Function to compute the weighted sum of electron-donor contributing to exciton dissociation located with Ld distance to the interface\n    ///\n    /// @param d is the vector of distances\n    /// @param Ld is the predefined distance to be checked against\n    /// return the weigthed sum over all vertices within the Ld distance to the targeted meta-vertex\n    inline double\n    identify_weighted_vertices_within_distance( const std::vector<float>& d,\n                                               double Ld){\n        double wn_Ld = 0;\n        foo_w_diss wfoo;\n\n        for(unsigned int i = 0; i < d.size(); i++){\n            double d_i = d[i];\n            double wd_i = wfoo(d_i);\n            if( (d_i < Ld) && (d_i > 0) ) wn_Ld+= wd_i;\n        }\n        return wn_Ld;\n    }\n\n    /// Function to compute the weighted fraction of electron-donor contributing to exciton dissociation located with Ld distance to the interface\n    ///\n    /// @param d is the vector of distances\n    /// @param Ld is the predefined distance to be checked against\n    /// return the pair of values required to compute the weigthed fraction\n    /// the pair consists of weigthed sum of contribution\n    /// and the total number of vertices within the Ld distance to the targeted meta-vertex (here GREEN)\n    inline std::pair<int,double>\n    identify_n_weighted_vertices_within_distance( const std::vector<float>& d,\n                                                 double Ld){\n        double wn_Ld = 0;\n        int n_Ld = 0;\n        foo_w_diss wfoo;\n\n        for(unsigned int i = 0; i < d.size(); i++){\n            double d_i = d[i];\n            double wd_i = wfoo(d_i);\n            if( (d_i < Ld) && (d_i > 0) ){\n                wn_Ld+= wd_i;\n                n_Ld++;\n            }\n        }\n        return std::pair<int,double>(n_Ld,wn_Ld);\n    }\n\n\n    /// This function computes two descriptors related to exciton dissociation\n    ///\n    /// @param G is the input graph\n    /// @param d_g is the structure storing basic informations about the graph dimensionality\n    /// @param C is the vector storing the labels/colors of vertices in the graph G\n    /// @param W is the map storing the weights of the edges\n    /// @param vCC is the vector storing indices of the connected components (CC) of each vector in the graph\n    /// @param CC is the vector of CC,\n    /// @param Ld is the exciton diffusion length\n    /// @param filename_ColorToGreen is the filename where all distances from GREEN to BLACK vertices will be outputted\n    /// @param filename_WColorToGreen is the filename where all weighted distances from GREEN to BLACK vertices will be outputed\n    /// @param color is the color code for vertices that will be analyzed (default value is BLACK)\n    /// @param green is the color code for targeted meta-vertex (default value is GREEN)\n    /// @return the pair of fractions: the weighted fraction of vertices and the fraction of vertices within Ld distance to the targeted meta-vertex\n    inline std::pair<double,double>\n    wf_diss(\n            graph_t* G, const dim_g_t& d_g, const vertex_colors_t& C,\n            const edge_weights_t& W, const vertex_ccs_t& vCC,\n            const ccs_t& CC,\n            double Ld,\n            const std::string& filename_ColorToGreen,\n            const std::string& filename_WColorToGreen,\n            COLOR color = BLACK,\n            COLOR green = GREEN\n            ){\n        int n_color = 0;\n        int n_color_Ld = 0;\n        double wn_color_Ld = 0;\n\n        connect_color_green pred(*G,C,color,green);\n        unsigned int n = boost::num_vertices(*G);\n        vertex_t int_id = d_g.id(green);\n        std::vector<float> d(n);\n\n        determine_shortest_distances( G, W, int_id, pred, d);\n\n        foo_w_diss wfoo;\n        std::ostringstream oss_out_d;\n        std::ostringstream oss_out_wd;\n        for (unsigned int i = 0; i < d.size(); i++) {\n            unsigned int c = C[i];\n            if (c == color) n_color++;\n            if ( ( c == color )\n                && ( fabs(d[i]) < std::numeric_limits<float>::max() )\n                ) {\n                double d_i = d[i];\n                oss_out_d  << d_i       << std::endl;\n                oss_out_wd << d_i << \" \" << wfoo(d_i) << std::endl;\n            }\n        }\n        std::ofstream f_out(filename_ColorToGreen.c_str());\n        std::string buffer = oss_out_d.str();\n        int size = oss_out_d.str().size();\n        f_out.write (buffer.c_str(),size);\n        f_out.close();\n        f_out.open(filename_WColorToGreen.c_str());\n        buffer = oss_out_wd.str();\n        size = oss_out_wd.str().size();\n        f_out.write (buffer.c_str(),size);\n        f_out.close();\n\n        std::pair<int,double> pLd\n        = identify_n_weighted_vertices_within_distance(d,Ld);\n        n_color_Ld = pLd.first;\n        wn_color_Ld = pLd.second;\n\n#ifdef DEBUG\n        std::cout << \"[DEBUG] Number of \" << color << \"vertices: \"\n        << n_color << std::endl\n        << \"[DEBUG] Number of \" << color << \"vertices in \"\n        << Ld << \" distance to green: \"\n        << n_color_Ld << std::endl;\n#endif\n\n        return std::pair<double, double>(\n                                         (double)wn_color_Ld/n_color,\n                                         (double)n_color_Ld/n_color\n                                         );\n    }\n\n\n      /// Function to compute the descriptors related to exciton dissociation\n      ///\n      /// @cond\n      /// @fn std::pair<double,double> wf_diss( graph_t* G, const dim_g_t& d_g, const vertex_colors_t& C, const edge_weights_t& W, const vertex_ccs_t& vCC, const ccs_t& CC, double Ld, COLOR color = BLACK, COLOR green = GREEN )\n      /// This function computes two descriptors related to exciton dissociation\n      /// @param G is the input graph\n      /// @param d_g is the structure storing basic informations about the graph dimensionality\n      /// @param C is the vector storing the labels/colors of vertices in the graph G\n      /// @param W is the map storing the weights of the edges\n      /// @param vCC is the vector storing indices of the connected components (CC) of each vector in the graph\n      /// @param CC is the vector of CC,\n      /// @param Ld is the exciton diffusion length\n      /// @param color is the color code for vertices that will be analyzed (default value is BLACK)\n      /// @param green is the color code for targeted meta-vertex (default value is GREEN)\n      /// @return the pair of fractions: the weighted fraction of vertices and the fraction of vertices within Ld distance to the targeted meta-vertex\n    inline std::pair<double,double> wf_diss(\n            graph_t* G, const dim_g_t& d_g, const vertex_colors_t& C,\n            const edge_weights_t& W, const vertex_ccs_t& vCC,\n            const ccs_t& CC,\n            double Ld,\n            COLOR color = BLACK,\n            COLOR green = GREEN\n            ){\n        int n_color = 0;\n        int n_color_Ld = 0;\n        double wn_color_Ld = 0;\n\n        connect_color_green pred(*G,C,color,green);\n        unsigned int n = boost::num_vertices(*G);\n        vertex_t int_id = d_g.id(green);\n        std::vector<float> d(n);\n\n        determine_shortest_distances( G, W, int_id, pred, d);\n\n        foo_w_diss wfoo;\n        for (unsigned int i = 0; i < d.size(); i++) {\n            unsigned int c = C[i];\n            if (c == color) n_color++;\n        }\n\n        std::pair<int,double> pLd\n        = identify_n_weighted_vertices_within_distance(d,Ld);\n        n_color_Ld = pLd.first;\n        wn_color_Ld = pLd.second;\n\n        return std::pair<double, double>(\n                                         (double)wn_color_Ld/n_color,\n                                         (double)n_color_Ld/n_color\n                                         );\n    }\n    /// @endcond\n\n\n\n}\n#endif\n", "meta": {"hexsha": "2533b6aabbcdf39019ec9cd72541b08344f7fa64", "size": 9483, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/performance_indicators_diss.hpp", "max_stars_repo_name": "owodolab/graspi", "max_stars_repo_head_hexsha": "4319cad2d5490903998094cdee85f039f70a4ff6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-11-24T15:07:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T00:22:14.000Z", "max_issues_repo_path": "src/performance_indicators_diss.hpp", "max_issues_repo_name": "owodolab/graspi", "max_issues_repo_head_hexsha": "4319cad2d5490903998094cdee85f039f70a4ff6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-21T21:33:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-08T16:17:12.000Z", "max_forks_repo_path": "src/performance_indicators_diss.hpp", "max_forks_repo_name": "owodolab/graspi", "max_forks_repo_head_hexsha": "4319cad2d5490903998094cdee85f039f70a4ff6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-11-19T22:18:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T11:13:22.000Z", "avg_line_length": 40.1822033898, "max_line_length": 226, "alphanum_fraction": 0.5978066013, "num_tokens": 2296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.29375600231069454}}
{"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 FIXED_POINT_ITERATOR_H\n#define FIXED_POINT_ITERATOR_H\n\n#include <iostream>\n#include <limits>\n#include <string>\n#include <utility>\n#include <Eigen/Core>\n#include <gsl/gsl_sys.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_multiroots.h>\n\n#include \"logger.hpp\"\n#include \"wrappers.hpp\"\n#include \"error.hpp\"\n#include \"ewsb_solver.hpp\"\n#include \"gsl_utils.hpp\"\n#include \"gsl_vector.hpp\"\n\nnamespace flexiblesusy {\n\nnamespace fixed_point_iterator {\n\nclass Convergence_tester_absolute {\npublic:\n   explicit Convergence_tester_absolute(double precision_ = 1.0e-2)\n      : precision(precision_)\n   {}\n\n   std::string name() const { return \"Convergence_tester_absolute\"; }\n\n   /**\n    * Test whether the absolute value of the residual, defined by\n    * \\f$|a-b| = \\sqrt{\\sum_i (a_i - b_i)^2}\\f$,\n    * is less than the set precision.\n    *\n    * @param a GSL vector\n    * @param b GSL vector\n    * @return GSL error code (GSL_SUCCESS or GSL_CONTINUE)\n    */\n   int operator()(const GSL_vector& a, const GSL_vector& b) const {\n      if (a.size() != b.size()) throw SetupError(\"Error: vectors have different size.\");\n\n      const auto dimension = a.size();\n      double residual = 0.;\n\n      if (precision < 0.)\n         GSL_ERROR(\"absolute tolerance is negative\", GSL_EBADTOL);\n\n      for (std::size_t i = 0; i < dimension; ++i)\n         residual += Sqr(a[i] - b[i]);\n\n      residual = Sqrt(residual);\n\n      return (residual < precision ? GSL_SUCCESS : GSL_CONTINUE);\n   }\n\nprivate:\n   double precision;                 ///< precision goal\n};\n\nclass Convergence_tester_relative {\npublic:\n   explicit Convergence_tester_relative(double precision_ = 1.0e-2)\n      : precision(precision_)\n   {}\n\n   std::string name() const { return \"Convergence_tester_relative\"; }\n\n   /**\n    * Test whether the relative difference is less than the set\n    * precision. The relative difference test used here is carried out\n    * by applying \\a MaxRelDiff to each element of the vector.\n    *\n    * @param a GSL vector\n    * @param b GSL vector\n    * @return GSL error code (GSL_SUCCESS or GSL_CONTINUE)\n    */\n   int operator()(const GSL_vector& a, const GSL_vector& b) const {\n      if (a.size() != b.size()) throw SetupError(\"Error: vectors have different size.\");\n\n      const auto dimension = a.size();\n      double rel_diff = 0.;\n\n      if (precision < 0.)\n         GSL_ERROR(\"relative tolerance is negative\", GSL_EBADTOL);\n\n      for (std::size_t i = 0; i < dimension; ++i) {\n         rel_diff = MaxRelDiff(a[i], b[i]);\n\n         if (rel_diff > precision)\n            return GSL_CONTINUE;\n      }\n\n      return GSL_SUCCESS;\n   }\n\nprivate:\n   double precision;                 ///< precision goal\n};\n\ntemplate <std::size_t dimension>\nclass Convergence_tester_tadpole {\npublic:\n   using Vector_t = Eigen::Matrix<double,dimension,1>;\n   using Function_t = std::function<Vector_t(const Vector_t&)>;\n\n   Convergence_tester_tadpole(double precision_,\n                              const Function_t& tadpole_function_)\n      : precision(precision_)\n      , tadpole_function(tadpole_function_)\n   {}\n\n   std::string name() const { return \"Convergence_tester_tadpole\"; }\n\n   /**\n    * Test whether the relative difference is less than the set\n    * precision. The relative difference test used here is carried out\n    * by applying \\a MaxRelDiff to each element of the vector. If the\n    * relative difference is below the precision, it is tested whether\n    * the tadpoles are below the precision. If the tadpoles are larger\n    * than the precision, GSL_CONTINUE is returned.\n    *\n    * @param a GSL vector\n    * @param b GSL vector\n    * @return GSL error code (GSL_SUCCESS or GSL_CONTINUE)\n    */\n   int operator()(const GSL_vector& a, const GSL_vector& b) const {\n      if (a.size() != b.size()) throw SetupError(\"Error: vectors have different size.\");\n\n      if (precision < 0.)\n         GSL_ERROR(\"relative tolerance is negative\", GSL_EBADTOL);\n\n      const double max_rel_diff =\n         MaxRelDiff(to_eigen_vector(a), to_eigen_vector(b));\n\n      if (max_rel_diff > precision)\n         return GSL_CONTINUE;\n\n      static const double eps = 10*std::pow(10., -std::numeric_limits<double>::digits10);\n\n      if (max_rel_diff < eps)\n         return GSL_SUCCESS;\n\n      return check_tadpoles(a);\n   }\n\nprivate:\n   double precision;                 ///< precision goal\n   const Function_t tadpole_function; ///< function to calculate tadpole\n\n   int check_tadpoles(const GSL_vector& x) const {\n      const GSL_vector t(to_GSL_vector(tadpole_function(to_eigen_vector(x))));\n      return gsl_multiroot_test_residual(t.raw(), precision);\n   }\n};\n\n} // namespace fixed_point_iterator\n\n/**\n * @class Fixed_point_iterator\n * @brief Does fixed point iteration\n * @author Dylan Harries, Alexander Voigt\n * @tparam dimension dimension of function\n * @tparam Convergence_tester function for relative comparison\n *    of subsequent iteration steps\n *\n * The user has to provide the function (of which a fixed point should\n * be found) of the type \\a Function_t. This function gets as\n * arguments a Eigen vector of length \\a dimension and returns a\n * vector with the next point.\n *\n * @note The standard relative convergence criterion\n * \\f$\\text{MaxRelDiff}(x_{n+1}, x_{n}) < \\text{precision}\\f$ is not\n * very good: The iteration might converge slowly.  This means, that\n * subsequent steps are very close to each other, but \\f$x_n\\f$ might\n * not be close to the true fixed point.\n *\n * @todo implement check for no progress towards solution\n */\ntemplate <std::size_t dimension, class Convergence_tester = fixed_point_iterator::Convergence_tester_relative>\nclass Fixed_point_iterator : public EWSB_solver {\npublic:\n   using Vector_t = Eigen::Matrix<double,dimension,1>;\n   using Function_t = std::function<Vector_t(const Vector_t&)>;\n\n   Fixed_point_iterator() = default;\n   template <typename F>\n   Fixed_point_iterator(F&&, std::size_t, const Convergence_tester&);\n   virtual ~Fixed_point_iterator() = default;\n\n   template <typename F>\n   void set_function(F&& f) { function = std::forward<F>(f); }\n   void set_max_iterations(std::size_t n) { max_iterations = n; }\n   int find_fixed_point(const Eigen::VectorXd&);\n\n   // EWSB_solver interface methods\n   virtual std::string name() const override { return \"Fixed_point_iterator<\" + convergence_tester.name() + \">\"; }\n   virtual int solve(const Eigen::VectorXd&) override;\n   virtual Eigen::VectorXd get_solution() const override;\n\nprivate:\n   std::size_t max_iterations{100};         ///< maximum number of iterations\n   GSL_vector xn{dimension};                ///< current iteration point\n   GSL_vector fixed_point{dimension};       ///< vector of fixed point estimate\n   Function_t function{nullptr};            ///< function defining fixed point\n   Convergence_tester convergence_tester{}; ///< convergence tester\n\n   int fixed_point_iterator_iterate();\n   void print_state(std::size_t) const;\n   static int gsl_function(const gsl_vector*, void*, gsl_vector*);\n};\n\n/**\n * Constructor\n *\n * @param function_ pointer to the function to find fixed point for\n * @param max_iterations_ maximum number of iterations\n * @param convergence_tester_ convergence tester\n */\ntemplate <std::size_t dimension, class Convergence_tester>\ntemplate <typename F>\nFixed_point_iterator<dimension,Convergence_tester>::Fixed_point_iterator(\n   F&& function_,\n   std::size_t max_iterations_,\n   const Convergence_tester& convergence_tester_\n)\n   : max_iterations(max_iterations_)\n   , function(std::forward<F>(function_))\n   , convergence_tester(convergence_tester_)\n{\n}\n\n/**\n * Start the iteration\n *\n * @param start starting point\n *\n * @return GSL error code (GSL_SUCCESS if fixed point found)\n */\ntemplate <std::size_t dimension, class Convergence_tester>\nint Fixed_point_iterator<dimension,Convergence_tester>::find_fixed_point(\n   const Eigen::VectorXd& start\n)\n{\n   if (!function)\n      throw SetupError(\"Fixed_point_iterator: function not callable\");\n\n   int status;\n   std::size_t iter = 0;\n\n#ifndef ENABLE_DEBUG\n   gsl_set_error_handler_off();\n#endif\n\n   fixed_point = xn = to_GSL_vector(start);\n\n#ifdef ENABLE_VERBOSE\n   print_state(iter);\n#endif\n\n   do {\n      iter++;\n      status = fixed_point_iterator_iterate();\n\n#ifdef ENABLE_VERBOSE\n      print_state(iter);\n#endif\n\n      if (status)   // check if iterator has problems\n         break;\n\n      status = convergence_tester(fixed_point, xn);\n\n   } while (status == GSL_CONTINUE && iter < max_iterations);\n\n   VERBOSE_MSG(\"\\t\\t\\tFixed_point_iterator status = \"\n               << gsl_strerror(status));\n\n   return status;\n}\n\n/**\n * Perform a single step of the fixed point iteration\n *\n * @return GSL error code\n */\ntemplate <std::size_t dimension, class Convergence_tester>\nint Fixed_point_iterator<dimension,Convergence_tester>::fixed_point_iterator_iterate()\n{\n   xn = fixed_point;\n\n   void* parameters = &function;\n\n   int status = gsl_function(xn.raw(), parameters, fixed_point.raw());\n\n   if (status != GSL_SUCCESS)\n      return GSL_EBADFUNC;\n\n   // For safety, include a check for nans or infs here (which\n   // should be sufficient for now)\n   if (!is_finite(fixed_point))\n      GSL_ERROR(\"update point is not finite\", GSL_EBADFUNC);\n\n   return GSL_SUCCESS;\n}\n\n/**\n * Print state of the fixed point iterator\n *\n * @param iteration iteration number\n */\ntemplate <std::size_t dimension, class Convergence_tester>\nvoid Fixed_point_iterator<dimension,Convergence_tester>::print_state(std::size_t iteration) const\n{\n   VERBOSE_MSG(\"\\t\\t\\tIteration n = \" << iteration\n               << \": x_{n} = \" << xn\n               << \", x_{n+1} = \" << fixed_point);\n}\n\ntemplate <std::size_t dimension, class Convergence_tester>\nint Fixed_point_iterator<dimension,Convergence_tester>::gsl_function(const gsl_vector* x, void* params, gsl_vector* f)\n{\n   if (!is_finite(x)) {\n      gsl_vector_set_all(f, std::numeric_limits<double>::max());\n      return GSL_EDOM;\n   }\n\n   Function_t* fun = static_cast<Function_t*>(params);\n   int status = GSL_SUCCESS;\n   const Vector_t arg(to_eigen_vector(x));\n   auto result = arg;\n\n   try {\n      result = (*fun)(arg);\n      status = GSL_SUCCESS;\n   } catch (const flexiblesusy::Error&) {\n      status = GSL_EDOM;\n   }\n\n   copy(result, f);\n\n   return status;\n}\n\ntemplate <std::size_t dimension, class Convergence_tester>\nint Fixed_point_iterator<dimension,Convergence_tester>::solve(const Eigen::VectorXd& start)\n{\n   return (find_fixed_point(start) == GSL_SUCCESS ?\n           EWSB_solver::SUCCESS : EWSB_solver::FAIL);\n}\n\ntemplate <std::size_t dimension, class Convergence_tester>\nEigen::VectorXd Fixed_point_iterator<dimension,Convergence_tester>::get_solution() const\n{\n   return to_eigen_vector(fixed_point);\n}\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "4e01ce54f5262f4993527c25382aaa743e00622a", "size": 11610, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/src/fixed_point_iterator.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/fixed_point_iterator.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/fixed_point_iterator.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": 30.4724409449, "max_line_length": 118, "alphanum_fraction": 0.6873385013, "num_tokens": 2751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.29375599550629505}}
{"text": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the 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,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\n * @file mlp_igd.cpp\n *\n * @brief Multilayer Perceptron functions\n *\n *//* ----------------------------------------------------------------------- */\n#include <boost/lexical_cast.hpp>\n\n#include <dbconnector/dbconnector.hpp>\n#include <modules/shared/HandleTraits.hpp>\n\n#include \"mlp_igd.hpp\"\n\n#include \"task/mlp.hpp\"\n#include \"task/l2.hpp\"\n#include \"algo/igd.hpp\"\n#include \"algo/loss.hpp\"\n\n#include \"type/tuple.hpp\"\n#include \"type/model.hpp\"\n#include \"type/state.hpp\"\n\nnamespace madlib {\n\nnamespace modules {\n\nnamespace convex {\n\n// These 2 classes contain public static methods that can be called\ntypedef IGD<MLPIGDState<MutableArrayHandle<double> >, MLPIGDState<ArrayHandle<double> >,\n        MLP<MLPModel<MutableArrayHandle<double> >, MLPTuple > > MLPIGDAlgorithm;\n\ntypedef IGD<MLPMiniBatchState<MutableArrayHandle<double> >, MLPMiniBatchState<ArrayHandle<double> >,\n        MLP<MLPModel<MutableArrayHandle<double> >, MiniBatchTuple > > MLPMiniBatchAlgorithm;\n\ntypedef Loss<MLPIGDState<MutableArrayHandle<double> >, MLPIGDState<ArrayHandle<double> >,\n        MLP<MLPModel<MutableArrayHandle<double> >, MLPTuple > > MLPLossAlgorithm;\n\ntypedef MLP<MLPModel<MutableArrayHandle<double> >,MLPTuple> MLPTask;\n\ntypedef MLPModel<MutableArrayHandle<double> > MLPModelType;\n\n/**\n * @brief Perform the multilayer perceptron transition step\n *\n * Called for each tuple.\n */\nAnyType\nmlp_igd_transition::run(AnyType &args) {\n    // For the first tuple: args[0] is nothing more than a marker that\n    // indicates that we should do some initial operations.\n    // For other tuples: args[0] holds the computation state until last tuple\n    MLPIGDState<MutableArrayHandle<double> > state = args[0];\n\n    // initilize the state if first tuple\n    if (state.algo.numRows == 0) {\n        if (!args[3].isNull()) {\n            MLPIGDState<ArrayHandle<double> > previousState = args[3];\n\n            state.allocate(*this, previousState.task.numberOfStages,\n                           previousState.task.numbersOfUnits);\n            state = previousState;\n        } else {\n            // configuration parameters and initialization\n            // this is run only once (first iteration, first tuple)\n            ArrayHandle<double> numbersOfUnits = args[4].getAs<ArrayHandle<double> >();\n            uint16_t numberOfStages = static_cast<uint16_t>(numbersOfUnits.size() - 1);\n\n            state.allocate(*this, numberOfStages,\n                           reinterpret_cast<const double *>(numbersOfUnits.ptr()));\n            state.task.stepsize = args[5].getAs<double>();\n            state.task.model.activation = static_cast<double>(args[6].getAs<int>());\n            state.task.model.is_classification = static_cast<double>(args[7].getAs<int>());\n            // args[8] is for weighting the input row, which is populated later.\n            state.task.lambda = args[10].getAs<double>();\n            MLPTask::lambda = state.task.lambda;\n            state.task.model.momentum = args[11].getAs<double>();\n            state.task.model.is_nesterov = static_cast<double>(args[12].getAs<bool>());\n            if (!args[9].isNull()){\n                // initial coefficients are provided\n                MappedColumnVector warm_start_coeff = args[9].getAs<MappedColumnVector>();\n\n                // copy warm start into the task model\n                // state.reset() ensures algo.incrModel is copied from task.model\n                Index layer_start = 0;\n                for (size_t k = 0; k < numberOfStages; ++k){\n                    for (Index j=0; j < state.task.model.u[k].cols(); ++j){\n                        for (Index i=0; i < state.task.model.u[k].rows(); ++i){\n                            state.task.model.u[k](i, j) = warm_start_coeff(\n                                layer_start + j * state.task.model.u[k].rows() + i);\n                        }\n                    }\n                    layer_start = state.task.model.u[k].rows() * state.task.model.u[k].cols();\n                }\n            } else {\n                // initialize the model with appropriate coefficients\n                state.task.model.initialize(\n                    numberOfStages,\n                    reinterpret_cast<const double *>(numbersOfUnits.ptr()));\n            }\n        }\n        // resetting in either case\n        state.reset();\n    }\n\n    MLPTuple tuple;\n    try {\n        tuple.indVar = args[1].getAs<MappedColumnVector>();;\n        tuple.depVar = args[2].getAs<MappedColumnVector>();\n    } catch (const ArrayWithNullException &e) {\n        return args[0];\n    }\n\n    tuple.weight = args[8].getAs<double>();\n    MLPIGDAlgorithm::transition(state, tuple);\n    // Use the model from the previous iteration to compute the loss (note that\n    // it is stored in Task's state, and the Algo's state holds the model from\n    // the current iteration.\n    MLPLossAlgorithm::transition(state, tuple);\n    state.algo.numRows ++;\n\n    return state;\n}\n\n/**\n * @brief Perform the perliminary aggregation function: Merge transition states\n */\nAnyType\nmlp_igd_merge::run(AnyType &args) {\n    MLPIGDState<MutableArrayHandle<double> > stateLeft = args[0];\n    MLPIGDState<ArrayHandle<double> > stateRight = args[1];\n\n    if (stateLeft.algo.numRows == 0) { return stateRight; }\n    else if (stateRight.algo.numRows == 0) { return stateLeft; }\n\n    MLPIGDAlgorithm::merge(stateLeft, stateRight);\n    MLPLossAlgorithm::merge(stateLeft, stateRight);\n\n    // The following numRows update cannot be put above, because the model\n    // averaging depends on their original values\n    stateLeft.algo.numRows += stateRight.algo.numRows;\n\n    return stateLeft;\n}\n/**\n * @brief Perform the multilayer perceptron final step\n */\nAnyType\nmlp_igd_final::run(AnyType &args) {\n    // We request a mutable object. Depending on the backend, this might perform\n    // a deep copy.\n    MLPIGDState<MutableArrayHandle<double> > state = args[0];\n\n    if (state.algo.numRows == 0) { return Null(); }\n\n    L2<MLPModelType>::lambda = state.task.lambda;\n    state.algo.loss = state.algo.loss/static_cast<double>(state.algo.numRows);\n    state.algo.loss += L2<MLPModelType>::loss(state.task.model);\n    MLPIGDAlgorithm::final(state);\n    return state;\n}\n\n/**\n * @brief Perform the multilayer perceptron minibatch transition step\n *\n * Called for each tuple.\n */\nAnyType\nmlp_minibatch_transition::run(AnyType &args) {\n    // For the first tuple: args[0] is nothing more than a marker that\n    // indicates that we should do some initial operations.\n    // For other tuples: args[0] holds the computation state until last tuple\n    MLPMiniBatchState<MutableArrayHandle<double> > state = args[0];\n\n    // initilize the state if first tuple\n    if (state.numRows == 0) {\n        if (!args[3].isNull()) {\n            MLPMiniBatchState<ArrayHandle<double> > previousState = args[3];\n            state.allocate(*this, previousState.numberOfStages,\n                           previousState.numbersOfUnits);\n            state = previousState;\n        } else {\n            // configuration parameters\n            ArrayHandle<double> numbersOfUnits = args[4].getAs<ArrayHandle<double> >();\n            uint16_t numberOfStages = static_cast<uint16_t>(numbersOfUnits.size() - 1);\n            state.allocate(*this, numberOfStages,\n                           reinterpret_cast<const double *>(numbersOfUnits.ptr()));\n            state.stepsize = args[5].getAs<double>();\n            state.model.activation = static_cast<double>(args[6].getAs<int>());\n            state.model.is_classification = static_cast<double>(args[7].getAs<int>());\n            // args[8] is for weighting the input row, which is populated later.\n            state.model.momentum = args[13].getAs<double>();\n            state.model.is_nesterov = static_cast<double>(args[14].getAs<bool>());\n            if (!args[9].isNull()){\n                // initial coefficients are provided copy warm start into the model\n                MappedColumnVector warm_start_coeff = args[9].getAs<MappedColumnVector>();\n                Index layer_start = 0;\n                for (size_t k = 0; k < numberOfStages; ++k){\n                    for (Index j=0; j < state.model.u[k].cols(); ++j){\n                        for (Index i=0; i < state.model.u[k].rows(); ++i){\n                            state.model.u[k](i, j) = warm_start_coeff(\n                                layer_start + j * state.model.u[k].rows() + i);\n                        }\n                    }\n                    layer_start = state.model.u[k].rows() * state.model.u[k].cols();\n                }\n            } else {\n                // initialize the model with appropriate coefficients\n                state.model.initialize(\n                    numberOfStages,\n                    reinterpret_cast<const double *>(numbersOfUnits.ptr()));\n            }\n\n            state.lambda = args[10].getAs<double>();\n            MLPTask::lambda = state.lambda;\n            state.batchSize = static_cast<uint16_t>(args[11].getAs<int>());\n            state.nEpochs = static_cast<uint16_t>(args[12].getAs<int>());\n        }\n        // resetting in either case\n        state.reset();\n    }\n\n    MiniBatchTuple tuple;\n    try {\n        // Ideally there should be no NULLs in the pre-processed input data,\n        // but keep it in a try block in case the user has modified the\n        // pre-processed data in any way.\n        // The matrices are by default read as column-major. We will have to\n        // transpose it to get back the matrix like how it is in the database.\n        tuple.indVar = trans(args[1].getAs<MappedMatrix>());\n        tuple.depVar = trans(args[2].getAs<MappedMatrix>());\n    } catch (const ArrayWithNullException &e) {\n        return args[0];\n    }\n\n    tuple.weight = args[8].getAs<double>();\n\n    /*\n        Note that the IGD version uses the model in Task (model from the\n        previous iteration) to compute the loss.\n        Minibatch uses the model from Algo (the model based on current\n        iteration) to compute the loss. The difference in loss based on one\n        iteration is not too much, hence doing so here. We therefore don't\n        need to maintain another copy of the model (from previous iteration)\n        in the state. The model for the current iteration, and the loss are\n        both computed in one function now.\n    */\n    MLPMiniBatchAlgorithm::transitionInMiniBatch(state, tuple);\n    state.numRows += tuple.indVar.rows();\n    return state;\n}\n/**\n * @brief Perform the perliminary aggregation function: Merge transition states\n */\nAnyType\nmlp_minibatch_merge::run(AnyType &args) {\n    MLPMiniBatchState<MutableArrayHandle<double> > stateLeft = args[0];\n    MLPMiniBatchState<ArrayHandle<double> > stateRight = args[1];\n\n    if (stateLeft.numRows == 0) { return stateRight; }\n    else if (stateRight.numRows == 0) { return stateLeft; }\n\n    MLPMiniBatchAlgorithm::mergeInPlace(stateLeft, stateRight);\n\n    // The following numRows update, cannot be put above, because the model\n    // averaging depends on their original values\n    stateLeft.numRows += stateRight.numRows;\n    stateLeft.loss += stateRight.loss;\n\n    return stateLeft;\n}\n\n/**\n * @brief Perform the multilayer perceptron final step\n */\nAnyType\nmlp_minibatch_final::run(AnyType &args) {\n    // We request a mutable object. Depending on the backend, this might perform\n    // a deep copy.\n    MLPMiniBatchState<MutableArrayHandle<double> > state = args[0];\n    // Aggregates that haven't seen any data just return Null.\n    if (state.numRows == 0) { return Null(); }\n\n    L2<MLPModelType>::lambda = state.lambda;\n    state.loss = state.loss/static_cast<double>(state.numRows);\n    state.loss += L2<MLPModelType>::loss(state.model);\n    return state;\n}\n\n/**\n * @brief Return the difference in RMSE between two states\n */\nAnyType\ninternal_mlp_igd_distance::run(AnyType &args) {\n    MLPIGDState<ArrayHandle<double> > stateLeft = args[0];\n    MLPIGDState<ArrayHandle<double> > stateRight = args[1];\n    return std::abs(stateLeft.algo.loss - stateRight.algo.loss);\n}\n\n\nAnyType\ninternal_mlp_minibatch_distance::run(AnyType &args) {\n    MLPMiniBatchState<ArrayHandle<double> > stateLeft = args[0];\n    MLPMiniBatchState<ArrayHandle<double> > stateRight = args[1];\n\n    return std::abs(stateLeft.loss - stateRight.loss);\n}\n\n/**\n * @brief Return the coefficients and diagnostic statistics of the state\n */\nAnyType\ninternal_mlp_igd_result::run(AnyType &args) {\n    MLPIGDState<ArrayHandle<double> > state = args[0];\n    HandleTraits<ArrayHandle<double> >::ColumnVectorTransparentHandleMap\n        flattenU;\n    flattenU.rebind(&state.task.model.u[0](0, 0),\n                    state.task.model.coeffArraySize(state.task.numberOfStages,\n                                               state.task.numbersOfUnits));\n    AnyType tuple;\n    tuple << flattenU\n          << static_cast<double>(state.algo.loss);;\n    return tuple;\n}\n\n/**\n * @brief Return the coefficients and diagnostic statistics of the state\n */\nAnyType\ninternal_mlp_minibatch_result::run(AnyType &args) {\n    MLPMiniBatchState<ArrayHandle<double> > state = args[0];\n    HandleTraits<ArrayHandle<double> >::ColumnVectorTransparentHandleMap flattenU;\n    flattenU.rebind(&state.model.u[0](0, 0),\n                    state.model.coeffArraySize(state.numberOfStages,\n                                          state.numbersOfUnits));\n    AnyType tuple;\n    tuple << flattenU\n          << static_cast<double>(state.loss);\n    return tuple;\n}\n\nAnyType\ninternal_predict_mlp::run(AnyType &args) {\n    MLPModel<MutableArrayHandle<double> > model;\n    ColumnVector indVar;\n    int is_response = args[5].getAs<int>();\n    MappedColumnVector x_means = args[6].getAs<MappedColumnVector>();\n    MappedColumnVector x_stds = args[7].getAs<MappedColumnVector>();\n    MappedColumnVector coeff = args[0].getAs<MappedColumnVector>();\n    MappedColumnVector layerSizes = args[4].getAs<MappedColumnVector>();\n    // Input layer doesn't count\n    uint16_t numberOfStages = static_cast<uint16_t>(layerSizes.size() - 1);\n    double is_classification = args[2].getAs<double>();\n    double activation = args[3].getAs<double>();\n    int is_dep_var_array_for_classification = args[8].getAs<int>();\n    bool is_classification_response = is_classification && is_response;\n\n    // The model rebind function is called by both predict and train functions.\n    // Since we have to use the same function, we are passing a dummy value for\n    // activation, momentum and nesterov because predict does not care\n    // about the actual values for these params.\n    const double dummy_value = static_cast<double>(-1);\n    model.rebind(&is_classification, &activation, &dummy_value, &dummy_value, &coeff.data()[0],\n                 numberOfStages, &layerSizes.data()[0]);\n    try {\n        indVar = (args[1].getAs<MappedColumnVector>()-x_means).cwiseQuotient(x_stds);\n    } catch (const ArrayWithNullException &e) {\n        return args[0];\n    }\n    ColumnVector prediction = MLPTask::predict(model, indVar, is_classification_response,\n                                               is_dep_var_array_for_classification);\n    return prediction;\n}\n\n\n} // namespace convex\n\n} // namespace modules\n\n} // namespace madlib\n\n", "meta": {"hexsha": "0fb17b338f3adcb754487e63c1c53f20d54cf9b6", "size": 15973, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/modules/convex/mlp_igd.cpp", "max_stars_repo_name": "kinow/madlib", "max_stars_repo_head_hexsha": "d00f09166fbb06c8a6ac9a3eb6d75fc20cc6fef8", "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/convex/mlp_igd.cpp", "max_issues_repo_name": "kinow/madlib", "max_issues_repo_head_hexsha": "d00f09166fbb06c8a6ac9a3eb6d75fc20cc6fef8", "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/convex/mlp_igd.cpp", "max_forks_repo_name": "kinow/madlib", "max_forks_repo_head_hexsha": "d00f09166fbb06c8a6ac9a3eb6d75fc20cc6fef8", "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.0325814536, "max_line_length": 100, "alphanum_fraction": 0.6462780943, "num_tokens": 3691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2936222174100474}}
{"text": "// Copyright (c) 2021 Rubens AMARO\n// Distributed under the MIT License.\n#include <algorithm>\n#include <chrono>\n#include <cmath>\n#include <fstream>\n#include <experimental/filesystem>\n// strings and c-strings\n#include <iostream>\n#include <cstring>\n#include <string>\n// input file\n#include \"json.hpp\"\n// mkdir for Linux\n#include <sys/stat.h>\n// mkdir for Windows\n#if defined(_WIN32) || defined(WIN32) || defined(__MINGW32__) || defined(__BORLANDC__)\n#include <direct.h>\n#endif\n#include <sys/time.h>\n#include \"MpsParticle.h\"\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Eigen/IterativeLinearSolvers>\n#include <Eigen/LU>\n\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n\nusing namespace std;\n\n// Constructor declaration\nMpsParticle::MpsParticle()\n{\n}\n// Destructor declaration\nMpsParticle::~MpsParticle()\n{\n}\n\n// Return time\ndouble MpsParticle::getTime() {\n\tstruct timeval tv;\n\tgettimeofday(&tv, NULL);\n\treturn ((double)(tv.tv_sec) + (double)(tv.tv_usec) * 1.0e-6);\n}\n\nvoid MpsParticle::displayInfo(const int intervalIter) {\n\tif(numOfIterations%intervalIter == 0) {\n\t\ttimerEnd = getTime();\n\t\tint seconds, hours, minutes;\n\t\tseconds = int(timerEnd - timerStart);\n\t\t//seconds = int(timer_end - timer_sta);\n\t\tminutes = seconds / 60;\n\t\thours = minutes / 60;\n\t\tprintf(\"Iteration: %5dth Time: %lfsec Num. Particles: %d Max Velocity: %lfm/s Courant: %lf\", \n\t\t\tnumOfIterations, timeCurrent, numParticles, velMax, CFLcurrent);\n\t\tif(fluidType == viscType::NON_NEWTONIAN) {\n\t\t\tprintf(\" CFLvisc: %lf\", CFLvisc);\n\t\t}\n\t\tif(mpsType == calcPressType::IMPLICIT_PND || mpsType == calcPressType::IMPLICIT_PND_DIVU){\n\t\t\tprintf(\" Solver iterations: %3d Estimated error: %.2e\", solverIter, solverError);\n\t\t}\n\t\tprintf(\" RunTime: %02dh%02dm%02dsec\\n\", int(hours), int(minutes%60), int(seconds%60));\n\t}\n}\n\n// Initialize elements of the class\nvoid MpsParticle::init() {\n\t// Read and allocate memory for data\n\treadInputFile();\n\t// Write header of output txt files (force and pressure)\n\t// part->writeHeaderTxtFiles(); (NOT WORKING !!!)\n\t// Allocation of buckets\n\tallocateBuckets();\n\t// Setting parameters\n\tsetParameters();\n\t// Set Periodic Boundary Condition of the bucket\n\tsetBucketBC();\n\t// Update particle ID's in buckets\n\tupdateBuckets();\n\t// Verify if particle is out of domain\n\tcheckParticleOutDomain();\n}\n\n// Update variables at 0th step\nvoid MpsParticle::stepZero() {\n\n\t// Initial PND\n\tsetInitialPndNumberOfNeigh();\n\tif(wallType == boundaryWallType::POLYGON) {\n\t\t// Contribution to mean PND due polygon wall\n\t\tmeanWallPnd();\n\t}\n\t// Mean of PND\n\tmeanPnd();\n\t// Mean fluid neighbor PND\n\tmeanNeighFluidPnd();\n\t// Update type of particle\n\tif(freeSurfType == calcBCType::PND_ARC) {\n\t\t// Compute fluid particles normal vector\n\t\tcalcNormalParticles();\n\t\tif(wallType == boundaryWallType::POLYGON) {\n\t\t\t// Contribution to normal vector due polygon wall\n\t\t\tcalcWallNormalParticles();\n\t\t}\n\t}\n\tupdateParticleBC();\n\t// Compute pressure\n\tif(mpsType == calcPressType::EXPLICIT) {\n\t\tcalcPressEMPS();\n\t}\n\telse if(mpsType == calcPressType::WEAKLY) {\n\t\tcalcPressWCMPS();\n\t}\n\telse if(mpsType == calcPressType::IMPLICIT_PND)\n\t{\n\t\tsolvePressurePoissonPnd();\n\t}\n\telse if(mpsType == calcPressType::IMPLICIT_PND_DIVU)\n\t{\n\t\tcalcVelDivergence();\n\t\tif(wallType == boundaryWallType::POLYGON) {\n\t\t\tif(slipCondition == slipBC::FREE_SLIP) {\n\t\t\t\tcalcWallSlipVelDivergence(); // Free-Slip condition\n\t\t\t}\n\t\t\telse if(slipCondition == slipBC::NO_SLIP) {\n\t\t\t\tcalcWallNoSlipVelDivergence(); // No-Slip condition\n\t\t\t}\n\t\t}\n\t\tsolvePressurePoissonPndDivU();\n\t}\n\t// Write header for vtu files\n\twritePvd();\n\t// Delete all files inside the simulation folder\n\tdeleteDirectoryFiles();\n\t// Write VTK file of buckets\n\twriteBuckets();\n}\n\n// Return the square distance between thwo particles \"i\" and \"j\"\nvoid MpsParticle::sqrDistBetweenParticles(const int j, \n\tconst double rxi, const double ryi, const double rzi,\n\tdouble &rx, double &ry, double &rz, double &rij2) {\n\trx = pos[j*3  ] - rxi;\n\try = pos[j*3+1] - ryi;\n\trz = pos[j*3+2] - rzi;\n\n\trij2 = rx*rx+ry*ry+rz*rz;\n}\n// Return the square distance between thwo particles \"i\" and \"j\" considering Periodic BC\nvoid MpsParticle::sqrDistBetweenParticles(const int j, \n\tconst double rxi, const double ryi, const double rzi,\n\tdouble &rx, double &ry, double &rz, double &rij2, \n\tconst double plx, const double ply, const double plz) {\n\n\trx = (pos[j*3  ] + plx) - rxi;\n\try = (pos[j*3+1] + ply) - ryi;\n\trz = (pos[j*3+2] + plz) - rzi;\n\n\trij2 = rx*rx+ry*ry+rz*rz;\n}\n\n// Get Periodic lenghts\nvoid MpsParticle::getPeriodicLengths(const int jb, double &perlx, double &perly, \n\tdouble &perlz) {\n\tint bPBC = bucketPeriodicBC[jb];\n\tperlx = bPBC*periodicLength[0];\n\tperly = bPBC*periodicLength[1];\n\tperlz = bPBC*periodicLength[2];\n}\n\n// Return the bucket coordinates for particle \"i\"\nvoid MpsParticle::bucketCoordinates(int &bx, int &by, int &bz,\n\tconst double rxi, const double ryi, const double rzi) {\n\tbx = (int)((rxi - domainMinX)*invBucketSide + 1.0e-8);\n\tby = (int)((ryi - domainMinY)*invBucketSide + 1.0e-8);\n\tbz = (int)((rzi - domainMinZ)*invBucketSide + 1.0e-8);\n}\n\n// Weight function\ndouble MpsParticle::weight(const double dst, const double re, const int wijType) {\n\tswitch (wijType) {\n\t\tcase 0:\n\t\t\treturn re/dst - 1.0;\n\t\tcase 1:\n\t\t\treturn re/dst + dst/re - 2.0;\n\t\tcase 2:\n\t\t\treturn re/dst - dst/re;\n\t\tcase 3:\n\t\t\treturn (1.0-dst/re)*(1.0-dst/re)*(1.0-dst/re);\n\t\tcase 4:\n\t\t\treturn (1.0-dst/re)*(1.0-dst/re);\n\t\tdefault:\n\t\t\treturn re/dst - 1.0;\n\t}\n}\n\n// Weight function for gradient\ndouble MpsParticle::weightGradient(const double dst, const double re, const int wijType) {\n\tswitch (wijType) {\n\t\tcase 0:\n\t\t\treturn re/dst - 1.0;\n\t\tcase 1:\n\t\t\treturn re/dst + dst/re - 2.0;\n\t\tcase 2:\n\t\t\treturn re/dst - dst/re;\n\t\tcase 3:\n\t\t\treturn (1.0-dst/re)*(1.0-dst/re)*(1.0-dst/re);\n\t\tcase 4:\n\t\t\treturn (1.0-dst/re)*(1.0-dst/re);\n\t\tdefault:\n\t\t\treturn re/dst - 1.0;\n\t}\n}\n\n// Derivate of weight function\ndouble MpsParticle::delWeight(const double dst, const double re, const int wijType) {\n\tswitch (wijType) {\n\t\tcase 0:\n\t\t\treturn -re/(dst*dst);\n\t\tcase 1:\n\t\t\treturn -re/(dst*dst) + 1.0/re;\n\t\tcase 2:\n\t\t\treturn -re/(dst*dst) - 1.0/re;\n\t\tcase 3:\n\t\t\treturn -3.0/re*(1.0-dst/re)*(1.0-dst/re);\n\t\tcase 4:\n\t\t\treturn -2.0/re*(1.0-dst/re);\n\t\tdefault:\n\t\t\treturn -re/(dst*dst);\n\t}\n}\n\n////////////////////////////////////////////////////////////\n// Functions called only at the initial instant (t=0)\n////////////////////////////////////////////////////////////\n\n// Read input data from file .json to class MpsParticle\nvoid MpsParticle::readInputFile() {\n\n\t// Runtime start\n\ttimerStart = getTime();\n\n\tchar json_folder[] = \"input/\";\n\tchar json_file_char [1000];\n\tchar json_path_char [1000];\n\tbool readOK = false;\n\n\tprintf(\"   ____       ___                    ____    ____       \t\t\t\t\t\t\t\\n\");\n\tprintf(\"  /\\\\  _`\\\\    /\\\\_ \\\\           /'\\\\_/`\\\\/\\\\  _`\\\\ /\\\\  _`\\\\     \t\t\t\t\\n\");\n\tprintf(\"  \\\\ \\\\ \\\\L\\\\ \\\\__\\\\//\\\\ \\\\   __  __/\\\\      \\\\ \\\\ \\\\L\\\\ \\\\ \\\\,\\\\L\\\\_\\\\   \t\t\\n\");\n\tprintf(\"   \\\\ \\\\ ,__/ __`\\\\ \\\\ \\\\ /\\\\ \\\\/\\\\ \\\\ \\\\ \\\\__\\\\ \\\\ \\\\ ,__/\\\\/_\\\\__ \\\\   \t\t\t\\n\");\n\tprintf(\"    \\\\ \\\\ \\\\/\\\\ \\\\L\\\\ \\\\_\\\\ \\\\\\\\ \\\\ \\\\_\\\\ \\\\ \\\\ \\\\_/\\\\ \\\\ \\\\ \\\\/   /\\\\ \\\\L\\\\ \\\\ \t\\n\");\n\tprintf(\"     \\\\ \\\\_\\\\ \\\\____/\\\\____\\\\/`____ \\\\ \\\\_\\\\\\\\ \\\\_\\\\ \\\\_\\\\   \\\\ `\\\\____\\\\ \t\t\\n\");\n\tprintf(\"      \\\\/_/\\\\/___/\\\\/____/`/___/> \\\\/_/ \\\\/_/\\\\/_/    \\\\/_____/\t\t\t\t\t\\n\");\n\tprintf(\"                          /\\\\___/                        \t\t\t\t\t\t\t\\n\");\n\tprintf(\"                          \\\\/__/                         \t\t\t\t\t\t\t\\n\");\n\n\tprintf(\" ____________________________________________________________ \\n\");\n\tprintf(\"|                                                            |\\n\");\n\tprintf(\"|                      E-MPS/WC-MPS/MPS                      |\\n\");\n\tprintf(\"|         Explicit/Weakly-compressible/Semi-implicit         |\\n\");\n\tprintf(\"|                Moving Particle Simulation                  |\\n\");\n\tprintf(\"|                                                            |\\n\");\n\tprintf(\"|               University of Sao Paulo - Brazil             |\\n\");\n\tprintf(\"|                                                            |\\n\");\n\tprintf(\"|  by Rubens Augusto Amaro Junior                            |\\n\");\n\tprintf(\"|____________________________________________________________|\\n\\n\");\n\n\twhile (readOK == false)\n\t{\n\t\tprintf(\"Enter the name of the MPS input file:\\n\");\n\t\tscanf(\"%s\", json_file_char);\n\t\tprintf(\"\\n\");\n\n\t\t// char *json_file_char = new char[json_file.length()+1];\n\t\t// strcpy (json_file_char, json_file.c_str());\n\t\t// json_file_char now contains a c-string copy of json_file\n\t\tstrcat(json_file_char, \".json\");\n\t\tsnprintf(json_path_char, 1000, \"%s%s\", json_folder, json_file_char);\n\n\t\t//tries to read the input json file\n\t\tjs = fopen(json_path_char, \"r\");\n\t\tif (js == NULL) {\n\t\t\tprintf(\"Error reading the input file %s. Try again.\\n\", json_path_char);\n\t\t}\n\t\telse {\n\t\t\treadOK = true;\n\t\t}\n\t}\n\t\n\t//printf(\"Input file: %s\\n\", json_file_char);\n\tprintf(\"Reading JSON File... \");\n\n\tusing json = nlohmann::json;\n\t// read a JSON file\n\tifstream ifs(json_path_char);\n\t//json je;\n\t//ifs >> je;\n\t\n\t//json je = json::parse(ifs);\n\t// Set parameter ignore_comments to true in the parse function to ignore // or /* */ comments. \n\t// Comments will then be treated as whitespace.\n\t// If skip_comments is set to true, the comments are skipped during parsing\n\tjson je = json::parse(ifs,\n\t\t\t\t\t/* callback */ nullptr,\n\t\t\t\t\t/* allow exceptions */ true,\n\t\t\t\t\t/* skip_comments */ true);\n\n\t// Access the values\n\t// Types of simulations and output\n\twallType = je.at(\"flags\").value(\"wall_type\", 1);\n\tfemOn = je.at(\"flags\").value(\"fem_MESH\", false);\n\tforcedOn = je.at(\"flags\").value(\"forced_MESH\", false);\n\tvtuType = je.at(\"flags\").at(\"output_VTU\").value(\"type\", 0);\n\tfreeSurfWall = je.at(\"flags\").at(\"output_VTU\").value(\"only_freeSurface\", false);\n\toutputPnd = je.at(\"flags\").at(\"output_VTU\").value(\"pnd\", false);\n\toutputNeigh = je.at(\"flags\").at(\"output_VTU\").value(\"neigh\", false);\n\toutputDeviation = je.at(\"flags\").at(\"output_VTU\").value(\"deviation\", false);\n\toutputConcentration = je.at(\"flags\").at(\"output_VTU\").value(\"concentration\", false);\n\toutputAuxiliar = je.at(\"flags\").at(\"output_VTU\").value(\"auxiliar\", false);\n\toutputNonNewtonian = je.at(\"flags\").at(\"output_VTU\").value(\"non_newtonian\", false);\n\ttxtPress = je.at(\"flags\").at(\"output_TXT\").value(\"press\", false);\n\ttxtForce = je.at(\"flags\").at(\"output_TXT\").value(\"force\", false);\n\t// Paths of input and output files/folders\n\tgridFilename = je.at(\"pathNames\").value(\"particle_grid_file\", \"oops\");\n\tmeshRigidFilename = je.at(\"pathNames\").value(\"mesh_rigid_file\", \"oops\");\n\tmeshDeformableFilename = je.at(\"pathNames\").value(\"mesh_deformable_file\", \"oops\");\n\tmeshForcedFilename = je.at(\"pathNames\").value(\"mesh_forced_file\", \"oops\");\n\tvtuOutputFoldername = je.at(\"pathNames\").value(\"vtu_output_folder\", \"oops\");\n\tforceTxtFilename = je.at(\"pathNames\").value(\"forceTxt_file\", \"oops\");\n\tpressTxtFilename = je.at(\"pathNames\").value(\"pressTxt_file\", \"oops\");\n\t// Geometry dimension limits\n\tdomainMinX = je.at(\"domain\").at(\"min\").value(\"x\", 0.0);\n\tdomainMinY = je.at(\"domain\").at(\"min\").value(\"y\", 0.0);\n\tdomainMinZ = je.at(\"domain\").at(\"min\").value(\"z\", 0.0);\n\tdomainMaxX = je.at(\"domain\").at(\"max\").value(\"x\", 0.0);\n\tdomainMaxY = je.at(\"domain\").at(\"max\").value(\"y\", 0.0);\n\tdomainMaxZ = je.at(\"domain\").at(\"max\").value(\"z\", 0.0);\n\t// Domain Boundary Condition\n\tdomainTypeBC = je.at(\"domain\").at(\"boundary\").value(\"type\", 0);\n\tnumBC = 1;\n\tlimitTypeBC = je.at(\"domain\").at(\"boundary\").value(\"limit\", 0);\n\tperiodicDirectionX = je.at(\"domain\").at(\"boundary\").at(\"direction\").value(\"x\", false);\n\tperiodicDirectionY = je.at(\"domain\").at(\"boundary\").at(\"direction\").value(\"y\", false);\n\tperiodicDirectionZ = je.at(\"domain\").at(\"boundary\").at(\"direction\").value(\"z\", false);\n\t\n\t// Physical parameters\n\tdensityFluid = je.at(\"physical\").value(\"fluid_density\", 1000.0);\n\tdensityWall = je.at(\"physical\").value(\"wall_density\", 1000.0);\n\tKNM_VS1 = je.at(\"physical\").value(\"kinematic_visc\", 0.000001);\n\tgravityX = je.at(\"physical\").at(\"gravity\").value(\"x\", 0.0);\n\tgravityY = je.at(\"physical\").at(\"gravity\").value(\"y\", 0.0);\n\tgravityZ = je.at(\"physical\").at(\"gravity\").value(\"z\", -9.81);\n\t// Rheological parameters\n\tKNM_VS2 = je.at(\"physical\").at(\"rheological\").value(\"kinematic_visc_phase_2\", 0.000001);\n\tDNS_FL1 = je.at(\"physical\").at(\"rheological\").value(\"fluid_density_phase_1\", 1000.0);\n\tDNS_FL2 = je.at(\"physical\").at(\"rheological\").value(\"fluid_density_phase_2\", 1540.0);\n\tDNS_SDT = je.at(\"physical\").at(\"rheological\").value(\"sediment_density\", 1540.0);\n\tfluidType = je.at(\"physical\").at(\"rheological\").value(\"fluid_type\", 0);\n\tN = je.at(\"physical\").at(\"rheological\").value(\"power_law_index\", 1.2);\n\tMEU0 = je.at(\"physical\").at(\"rheological\").value(\"consistency_index\", 0.03);\n\tPHI_1 = je.at(\"physical\").at(\"rheological\").at(\"phi\").value(\"lower\", 0.541);\n\tPHI_WAL = je.at(\"physical\").at(\"rheological\").at(\"phi\").value(\"wall\", 0.541);\n\tPHI_BED = je.at(\"physical\").at(\"rheological\").at(\"phi\").value(\"bed\", 0.541);\n\tPHI_2 = je.at(\"physical\").at(\"rheological\").at(\"phi\").value(\"second\", 0.6);\n\tcohes = je.at(\"physical\").at(\"rheological\").value(\"cohes_coeff\", 0.0);\n\tFraction_method = je.at(\"physical\").at(\"rheological\").value(\"fraction_method\", 2);\n\t//visc_max = je.at(\"physical\").at(\"rheological\").value(\"visc_max\", 20);\n\tDG = je.at(\"physical\").at(\"rheological\").value(\"grain_size\", 0.0035);\n\tI0 = je.at(\"physical\").at(\"rheological\").value(\"I0\", 0.75);\n\tmm = je.at(\"physical\").at(\"rheological\").value(\"mm\", 100.0);\n\tstress_calc_method = je.at(\"physical\").at(\"rheological\").value(\"stress_calc_method\", 1);\n\tvisc_itr_num = je.at(\"physical\").at(\"rheological\").at(\"viscosity\").value(\"iter_num\", 1);\n\tvisc_error = je.at(\"physical\").at(\"rheological\").at(\"viscosity\").value(\"error\", 0.0);\n\tvisc_ave = je.at(\"physical\").at(\"rheological\").at(\"viscosity\").value(\"average\", 0.0);\n\tCd = je.at(\"physical\").at(\"rheological\").value(\"drag_coeff\", 0.47);\n\tVF_min = je.at(\"physical\").at(\"rheological\").at(\"volume_fraction\").value(\"min\", 0.25);\n\tVF_max = je.at(\"physical\").at(\"rheological\").at(\"volume_fraction\").value(\"max\", 0.65);\n\t// Numerical parameters\n\tdim = je.at(\"numerical\").value(\"dimension\", 3.0);\n\tpartDist = je.at(\"numerical\").value(\"particle_dist\", 0.01);\n\ttimeStep = je.at(\"numerical\").value(\"time_step\", 0.0005);\n\ttimeSimulation = je.at(\"numerical\").value(\"final_time\", 1.0);\n\titerOutput = je.at(\"numerical\").value(\"iter_output\", 80);\n\tcflNumber = je.at(\"numerical\").value(\"CFL_number\", 0.2);\n\tweightType = je.at(\"numerical\").value(\"weight_type\", 0);\n\tslipCondition = je.at(\"numerical\").value(\"slip_condition\", 0);\n\treS = je.at(\"numerical\").at(\"effective_radius\").value(\"small\", 2.1);\n\treL = je.at(\"numerical\").at(\"effective_radius\").value(\"large\", 2.1);\n\tgradientType = je.at(\"numerical\").at(\"gradient\").value(\"type\", 3);\n\tgradientCorrection = je.at(\"numerical\").at(\"gradient\").value(\"correction\", false);\n\trelaxPress = je.at(\"numerical\").at(\"gradient\").value(\"relax_fact\", 1.0);\n\tmpsType = je.at(\"numerical\").value(\"mps_type\", 1);\n\tsoundSpeed = je.at(\"numerical\").at(\"explicit_mps\").at(\"equation_state\").value(\"speed_sound\", 15.0);\n\tgamma = je.at(\"numerical\").at(\"explicit_mps\").at(\"equation_state\").value(\"gamma\", 7.0);\n\tsolverType = je.at(\"numerical\").at(\"semi_implicit_mps\").value(\"solver_type\", 0);\n\talphaCompressibility = je.at(\"numerical\").at(\"semi_implicit_mps\").at(\"weak_compressibility\").value(\"alpha\", 0.000001);\n\trelaxPND = je.at(\"numerical\").at(\"semi_implicit_mps\").at(\"source_term\").value(\"relax_pnd\", 0.001);\n\tshiftingType = je.at(\"numerical\").at(\"particle_shifting\").value(\"type\", 2);\n\tdri = je.at(\"numerical\").at(\"particle_shifting\").value(\"DRI\", 0.01);\n\tcoefA = je.at(\"numerical\").at(\"particle_shifting\").value(\"coef_A\", 2.0);\n\tmachNumber = je.at(\"numerical\").at(\"particle_shifting\").value(\"mach_number\", 0.1);\n\tVEL_A = je.at(\"numerical\").at(\"particle_shifting\").value(\"adj_vel_A\", 0.1);\n\tpndType = je.at(\"numerical\").at(\"pnd\").value(\"type\", 0);\n\tdiffusiveCoef = je.at(\"numerical\").at(\"pnd\").value(\"diffusive_coeff\", 0.35);\n\trepulsiveForceType = je.at(\"numerical\").at(\"wall_repulsive_force\").value(\"type\", 2);\n\treRepulsiveForce = je.at(\"numerical\").at(\"wall_repulsive_force\").value(\"re\", 0.5);\n\texpectMaxVelocity = je.at(\"numerical\").at(\"wall_repulsive_force\").value(\"maxVel\", 6.0);\n\trepForceCoefMitsume = je.at(\"numerical\").at(\"wall_repulsive_force\").at(\"coefficient\").value(\"Mitsume\", 40000000.0);\n\trepForceCoefLennardJones = je.at(\"numerical\").at(\"wall_repulsive_force\").at(\"coefficient\").value(\"Lennard-Jones\", 2.0);\n\trepForceCoefMonaghanKajtar = je.at(\"numerical\").at(\"wall_repulsive_force\").at(\"coefficient\").value(\"Monaghan-Kajtar\", 1.0);\n\tEPS_RE = je.at(\"numerical\").at(\"wall_repulsive_force\").value(\"eps_re\", 0.01);\n\tfreeSurfType = je.at(\"numerical\").at(\"free_surface_threshold\").value(\"type\", 0);\n\tpndThreshold = je.at(\"numerical\").at(\"free_surface_threshold\").value(\"pnd\", 0.98);\n\tneighThreshold = je.at(\"numerical\").at(\"free_surface_threshold\").value(\"neigh\", 0.85);\n\tnpcdThreshold = je.at(\"numerical\").at(\"free_surface_threshold\").value(\"NPCD\", 0.20);\n\tthetaThreshold = je.at(\"numerical\").at(\"free_surface_threshold\").value(\"ARC\", 45.0);\n\tnormThreshold = je.at(\"numerical\").at(\"free_surface_threshold\").value(\"normal\", 0.1);\n\tcollisionType = je.at(\"numerical\").at(\"particle_collision\").value(\"type\", 0);\n\tcollisionRatio = je.at(\"numerical\").at(\"particle_collision\").value(\"ratio\", 0.20);\n\tdistLimitRatio = je.at(\"numerical\").at(\"particle_collision\").value(\"dist_limit_ratio\", 0.85);\n\tlambdaCollision = je.at(\"numerical\").at(\"particle_collision\").value(\"lambda\", 0.20);\n\tghost = je.at(\"numerical\").at(\"particle_type\").value(\"ghost\", -1);\n\tfluid = je.at(\"numerical\").at(\"particle_type\").value(\"fluid\",  0);\n\twall = je.at(\"numerical\").at(\"particle_type\").value(\"wall\",   2);\n\tdummyWall = je.at(\"numerical\").at(\"particle_type\").value(\"dummyWall\",   3);\n\tsurface = je.at(\"numerical\").at(\"boundary_type\").value(\"free_surface\", 1);\n\tinner = je.at(\"numerical\").at(\"boundary_type\").value(\"inner\", 0);\n\tother = je.at(\"numerical\").at(\"boundary_type\").value(\"other\", -1);\n\tnumPartTypes = 3;\n\n\tprintf(\"OK\\n\");\n\n\tprintf(\"Reading GRID File... \");\n\treadMpsParticleFile(gridFilename);\n\tprintf(\"OK\\n\");\n\n\t// Extend domain\n\tdomainMinX = domainMinX - partDist*3.0;\n\tdomainMinY = domainMinY - partDist*3.0;\n\tdomainMinZ = domainMinZ - partDist*3.0;\n\tdomainMaxX = domainMaxX + partDist*3.0;\n\tdomainMaxY = domainMaxY + partDist*3.0;\n\tdomainMaxZ = domainMaxZ + partDist*3.0;\n\tif((int)dim == 2) {\t\n\t\tdomainMinZ = 0.0;\n\t\tdomainMaxZ = 0.0;\n\t}\n\n\t// Number of meshs\n\tnumOfRigidMesh = 0;\tnumOfDeformableMesh = 0;\tnumOfForcedMesh = 0;\n\tif(wallType == 1) numOfRigidMesh = 1;\n\tif(femOn == true) numOfDeformableMesh = 1;\n\tif(forcedOn == true) numOfForcedMesh = 1;\n\tnumOfMeshs = numOfRigidMesh + numOfDeformableMesh + numOfForcedMesh;\n\n\t// // Print the values\n\t// cout << \"INPUT FILE .JSON\" << endl;\n\t// cout << \"Number of Meshs: \" << numOfMeshs << \" | \";\n\t// cout << \"WallType:\" << wallType << \" | \";\n\t// cout << \"GiraffeOn: \" << femOn << \" | \";\n\t// cout << \"forcedOn: \" << forcedOn << \" | \";\n\t// cout << \"vtuType: \" << vtuType << \" | \";\n\t// cout << \"freeSurfWall: \" << freeSurfWall << \" | \";\n\t// cout << \"outputPnd: \" << outputPnd << \" | \";\n\t// cout << \"outputNeigh: \" << outputNeigh << \" | \";\n\t// cout << \"outputDeviation: \" << outputDeviation << \" | \";\n\t// cout << \"outputConcentration: \" << outputConcentration << \" | \";\n\t// cout << \"outputAuxiliar: \" << outputAuxiliar << \" | \";\n\t// cout << \"outputNonNewtonian: \" << outputNonNewtonian << \" | \";\n\t// cout << \"txtPress: \" << txtPress << \" | \";\n\t// cout << \"txtForce: \" << txtForce << endl;\n\t// cout << \"gridFilename: \" << gridFilename << endl;\n\t// cout << \"meshRigidFilename: \" << meshRigidFilename << endl;\n\t// cout << \"meshDeformableFilename: \" << meshDeformableFilename << endl;\n\t// cout << \"meshForcedFilename: \" << meshForcedFilename << endl;\n\t// cout << \"vtuOutputFoldername: \" << vtuOutputFoldername << endl;\n\t// cout << \"forceTxtFilename: \" << forceTxtFilename << endl;\n\t// cout << \"pressTxtFilename: \" << pressTxtFilename << endl;\n\t// cout << \"domainMin: \" << domainMinX << \": \" << domainMinY << \": \" << domainMinZ << endl;\n\t// cout << \"domainMax: \" << domainMaxX << \": \" << domainMaxY << \": \" << domainMaxZ << endl;\n\t// cout << \"gravity: \" << gravityX << \": \" << gravityY << \": \" << gravityZ << endl;\n\t// cout << \"densityFluid: \" << densityFluid << \" | \";\n\t// cout << \"densityWall: \" << densityWall << \" | \";\n\t// cout << \"KNM_VS1-2: \" << KNM_VS1 << \": \" << KNM_VS2 << \" | \";\n\t// cout << \"DNS_FL1-2-DST: \" << DNS_FL1 << \": \" << DNS_FL2 << \": \" << DNS_SDT << endl;\n\t// cout << \"fluidType: \" << fluidType << \" | \";\n\t// cout << \"N: \" << N << \" | \";\n\t// cout << \"MEU0: \" << MEU0 << \" | \";\n\t// cout << \"PHI-FL-WAL-BED-2: \" << PHI_1 << \": \" << PHI_WAL << \": \" << PHI_BED << \": \" << PHI_2 << endl;\n\t// cout << \"cohes: \" << cohes << \" | \";\n\t// cout << \"Fraction_method: \" << Fraction_method << \" | \";\n\t// cout << \"DG: \" << DG << \" | \";\n\t// cout << \"I0: \" << I0 << \" | \";\n\t// cout << \"mm: \" << mm << \" | \";\n\t// cout << \"stress_calc_method: \" << stress_calc_method << \" | \";\n\t// cout << \"visc_itr_num-error-ave: \" << visc_itr_num << \": \" << visc_error << \": \" << visc_ave << endl;\n\t// cout << \"Cd: \" << Cd << \" | \";\n\t// cout << \"VFminmax: \" << VF_min << \": \" << VF_max << endl;\n\t// cout << \"dim: \" << dim << \" | \";\n\t// cout << \"lo: \" << partDist << \" | \";\n\t// cout << \"dt: \" << timeStep << \" | \";\n\t// cout << \"tf: \" << timeSimulation << \" | \";\n\t// cout << \"itO: \" << iterOutput << \" | \";\n\t// cout << \"CFL: \" << cflNumber << endl;\n\t// cout << \"mpsType: \" << mpsType << \" | \";\n\t// cout << \"weightType: \" << weightType << \" | \";\n\t// cout << \"slip: \" << slipCondition << \" | \";\n\t// cout << \"reSL: \" << reS << \": \" << reL << endl;\n\t// cout << \"gradientType: \" << gradientType << \" | \";\n\t// cout << \"gradientCorrection: \" << gradientCorrection << \" | \";\n\t// cout << \"relaxPress: \" << relaxPress << \" | \";\n\t// cout << \"soundSpeed: \" << soundSpeed << \" | \";\n\t// cout << \"solverType: \" << solverType << endl;\n\t// cout << \"alphaCompressibility: \" << alphaCompressibility << \" | \";\n\t// cout << \"relaxPND: \" << relaxPND << endl;\n\t// cout << \"shiftingType: \" << shiftingType << \" | \";\n\t// cout << \"dri: \" << dri << \" | \";\n\t// cout << \"coefA: \" << coefA << \" | \";\n\t// cout << \"machNumber: \" << machNumber << \" | \";\n\t// cout << \"VEL_A: \" << VEL_A << \" | \";\n\t// cout << \"pndType: \" << pndType << endl;\n\t// cout << \"diffusiveCoef: \" << diffusiveCoef << \" | \";\n\t// cout << \"repulsiveForceType: \" << repulsiveForceType << \" | \";\n\t// cout << \"reRepulsiveForce: \" << reRepulsiveForce << \" | \";\n\t// cout << \"expectMaxVelocity: \" << expectMaxVelocity << \" | \";\n\t// cout << \"repForceCoefMitsume\" << repForceCoefMitsume << \" | \";\n\t// cout << \"repForceCoefLennardJones: \" << repForceCoefLennardJones << \" | \";\n\t// cout << \"repForceCoefMonaghanKajtar: \" << repForceCoefMonaghanKajtar << endl;\n\t// cout << \"EPS_RE: \" << EPS_RE << \" | \";\n\t// cout << \"freeSurfType: \" << freeSurfType << \" | \";\n\t// cout << \"pndThreshold: \" << pndThreshold << \" | \";\n\t// cout << \"neighThreshold: \" << neighThreshold << \" | \";\n\t// cout << \"npcdThreshold: \" << npcdThreshold << \" | \";\n\t// cout << \"thetaThreshold: \" << thetaThreshold << \" | \";\n\t// cout << \"normThreshold: \" << normThreshold << \" | \";\n\t// cout << \"collisionType: \" << collisionType << \" | \";\n\t// cout << \"collisionRatio: \" << collisionRatio << \" | \";\n\t// cout << \"distLimitRatio: \" << distLimitRatio << \" | \";\n\t// cout << \"lambdaCollision: \" << lambdaCollision << endl;\n\t// cout << \"ghost: \" << ghost << \" | \";\n\t// cout << \"fluid: \" << fluid << \" | \";\n\t// cout << \"wall: \" << wall << \" | \";\n\t// cout << \"surface: \" << surface << \" | \";\n\t// cout << \"inner: \" << inner << \" | \";\n\t// cout << \"other: \" << other << \" | \";\n\t// cout << \"numParticles: \" << numPartTypes << endl;\n\t\t\n\t// // cout << endl;\n\t// Close .json file\n\tfclose(js);\n\n}\n\n// Read data from file .grid to class MpsParticle\nvoid MpsParticle::readMpsParticleFile(const std::string& grid_file) {\n\tchar *grid_file_char = new char[grid_file.length()+1];\n\tstrcpy (grid_file_char, grid_file.c_str());\n\t// grid_file_char now contains a c-string copy of grid_file\n\n\tfp = fopen(grid_file_char, \"r\");\n\tif(fp == NULL) perror (\"Error opening grid file\");\n\n\tint zeroZero;\n\tfscanf(fp,\"%d\",&zeroZero);\n\tfscanf(fp,\"%d\",&numParticles);\t\t\t\t\t\t\t\t\t// Read number of particles\n\tnumParticlesZero = numParticles;\n\t// printf(\"Number of particles: %d\\n\",numParticles);\n\n\t// Memory allocation\n\t// Scalars\n\tparticleType = (int*)malloc(sizeof(int)*numParticles);\t\t\t// Particle type\n\tparticleBC = (int*)malloc(sizeof(int)*numParticles);\t\t\t// BC particle type\n\tnumNeigh = (int*)malloc(sizeof(int)*numParticles);\t\t\t\t// Number of neighbors\n\n\tpress = (double*)malloc(sizeof(double)*numParticles);\t\t\t// Particle pressure\n\tpressAverage = (double*)malloc(sizeof(double)*numParticles);\t// Time averaged particle pressure\n\tpndi = (double*)malloc(sizeof(double)*numParticles);\t\t\t// PND\n\tpndki = (double*)malloc(sizeof(double)*numParticles);\t\t\t// PND step k\n\tpndski = (double*)malloc(sizeof(double)*numParticles);\t\t\t// Mean fluid neighbor PND step k\n\tpndSmall = (double*)malloc(sizeof(double)*numParticles);\t\t// PND small = sum(wij)\n\tnpcdDeviation2 = (double*)malloc(sizeof(double)*numParticles);\t// NPCD deviation modulus\n\tconcentration = (double*)malloc(sizeof(double)*numParticles);\t// Concentration\n\tvelDivergence = (double*)malloc(sizeof(double)*numParticles);\t// Divergence of velocity\n\tdiffusiveTerm = (double*)malloc(sizeof(double)*numParticles);\t// Diffusive term\n\t\n\tDns = (double*)malloc(sizeof(double)*numPartTypes);\t\t\t\t// Density\n\tinvDns = (double*)malloc(sizeof(double)*numPartTypes);\t\t\t// Inverse of Density\n\n\t// Vectors\n\tacc = (double*)malloc(sizeof(double)*numParticles*3);\t\t\t// Particle acceleration\n\taccStar = (double*)malloc(sizeof(double)*numParticles*3);\t\t// Particle acceleration due gravity and viscosity\n\tpos = (double*)malloc(sizeof(double)*numParticles*3);\t\t\t// Particle position\n\tvel = (double*)malloc(sizeof(double)*numParticles*3);\t\t\t// Particle velocity\n\tnpcdDeviation = (double*)malloc(sizeof(double)*numParticles*3);\t\t\t// NPCD deviation\n\tgradConcentration = (double*)malloc(sizeof(double)*numParticles*3);\t\t// Gradient of concentration\n\tcorrecMatrixRow1 = (double*)malloc(sizeof(double)*numParticles*3);\t\t// Correction matrix - Row 1\n\tcorrecMatrixRow2 = (double*)malloc(sizeof(double)*numParticles*3);\t\t// Correction matrix - Row 2\n\tcorrecMatrixRow3 = (double*)malloc(sizeof(double)*numParticles*3);\t\t// Correction matrix - Row 3\n\tnormal = (double*)malloc(sizeof(double)*numParticles*3);\t\t// Particle normal\n\tdvelCollision = (double*)malloc(sizeof(double)*numParticles*3);\t\t\t// Variation of velocity due collision\n\n\t// Polygons\n\t// Scalars\n\tnearMeshType = (int*)malloc(sizeof(int)*numParticles);\t\t\t\t// Type of mesh near particle\n\tparticleNearWall = (bool*)malloc(sizeof(bool)*numParticles);\t\t// Particle near polygon wall\n\tnumNeighWallContribution = (int*)malloc(sizeof(int)*numParticles);\t// Number of neighbors due wall\n\n\tpndWallContribution = (double*)malloc(sizeof(double)*numParticles);\t\t\t// PND wall\n\tdeviationDotPolygonNormal = (double*)malloc(sizeof(double)*numParticles);\t// Deviation vector X polygonal wall\n\tnumNeighborsSurfaceParticles = (double*)malloc(sizeof(double)*numParticles);// Number of free-surface particle neighbors\n\tdistParticleWall2 = (double*)malloc(sizeof(double)*numParticles);\t\t\t// Squared distance of particle to triangle mesh\n\t// Vectors\n\tparticleAtWallPos = (double*)malloc(sizeof(double)*numParticles*3);\t\t// Particle at wall coordinate\n\tmirrorParticlePos = (double*)malloc(sizeof(double)*numParticles*3);\t\t// Mirrored particle coordinate\n\twallParticleForce1 = (double*)malloc(sizeof(double)*numParticles*3);\t// Wall-Particle force\n\twallParticleForce2 = (double*)malloc(sizeof(double)*numParticles*3);\t// Wall-Particle force\n\tpolygonNormal = (double*)malloc(sizeof(double)*numParticles*3);\t\t// Polygon normal\n\t\n//\tPosk = (double*)malloc(sizeof(double)*numParticles*3);\t\t// Particle coordinates\n//\tVelk = (double*)malloc(sizeof(double)*numParticles*3);\t\t// Particle velocity\n//\tAcv = (double*)malloc(sizeof(double)*numParticles*3);\t\t// Part\n\n\t// Non-Newtonian\n\t// Scalars\n\tPTYPE = (int*)malloc(sizeof(int)*numParticles);\t\t\t\t// Type of fluid\n\n\tCv = (double*)malloc(sizeof(double)*numParticles);\t\t\t// Concentration\n\tII = (double*)malloc(sizeof(double)*numParticles);\t\t\t// Invariant\n\tMEU = (double*)malloc(sizeof(double)*numParticles);\t\t\t// Dynamic viscosity\n\tMEU_Y = (double*)malloc(sizeof(double)*numParticles);\t\t// Dynamic viscosity ??\n\tInertia = (double*)malloc(sizeof(double)*numParticles);\t\t//\n\tpnew = (double*)malloc(sizeof(double)*numParticles);\t\t// New pressure\n\tp_rheo_new = (double*)malloc(sizeof(double)*numParticles);\t//\n\tRHO = (double*)malloc(sizeof(double)*numParticles);\t\t\t// Fluid density\n\tp_smooth = (double*)malloc(sizeof(double)*numParticles);\t//\n\tVF = (double*)malloc(sizeof(double)*numParticles);\t\t\t//\n\tS12 = (double*)malloc(sizeof(double)*numParticles);\t\t\t//\n\tS13 = (double*)malloc(sizeof(double)*numParticles);\t\t\t//\n\tS23 = (double*)malloc(sizeof(double)*numParticles);\t\t\t//\n\tS11 = (double*)malloc(sizeof(double)*numParticles);\t\t\t//\n\tS22 = (double*)malloc(sizeof(double)*numParticles);\t\t\t//\n\tS33 = (double*)malloc(sizeof(double)*numParticles);\t\t\t//\n\n\t// FSI\n\t// Scalars\n\telementID = (int*)malloc(sizeof(int)*numParticles);\t\t\t// Element ID\n\t// Vectors\n\tforceWall = (double*)malloc(sizeof(double)*numParticles*3);\t// Force on wall\n\n\t// Solver PPE\n\tpressurePPE = Eigen::VectorXd::Zero(numParticles);\n\tsourceTerm = Eigen::VectorXd::Zero(numParticles);\n\n\t// Set values from .grid file\n\tfor(int i=0; i<numParticles; i++) {\n\t\tint a[2];\n\t\tdouble b[8];\n\n\t\t// Uncomment here to read .prof file\n\t\t//fscanf(fp,\" %d %d %lf %lf %lf %lf %lf %lf %lf %lf\",&a[0],&a[1],&b[0],&b[1],&b[2],&b[3],&b[4],&b[5],&b[6],&b[7]);\n\t\t// Uncomment here to read .grid file\n\t\ta[0] = 0;\n\t\tfscanf(fp,\"%d %lf %lf %lf %lf %lf %lf %lf %lf\",&a[1],&b[0],&b[1],&b[2],&b[3],&b[4],&b[5],&b[6],&b[7]);\n\t\tparticleType[i]=a[1];\n\t\tpos[i*3]=b[0];\tpos[i*3+1]=b[1];\tpos[i*3+2]=b[2];\n\t\tvel[i*3]=b[3];\tvel[i*3+1]=b[4];\tvel[i*3+2]=b[5];\n\t\t//\t|\t\t\t\t|\t\t\t\t\t|\n\t\t//\ti*3 = x\t\t\ti*3+1 = y\t\t\ti*3+2 = z\n\t\tpress[i]=b[6];\tpressAverage[i]=b[7];\n\n//\t\tprintf(\"X: %d %lf %lf %lf %lf %lf %lf %lf %lf\\n\",particleType[i],pos[3*i],pos[3*i+1],pos[3*i+2],vel[3*i],vel[3*i+1],vel[3*i+2],press[i],pressAverage[i]);\n//\t\tPosk[i*3]=b[0];\tPosk[i*3+1]=b[1];\tPosk[i*3+2]=b[2];\n//\t\tVelk[i*3]=b[3];\tVelk[i*3+1]=b[4];\tVelk[i*3+2]=b[5];\n\t}\n\t// Close .grid file\n\tfclose(fp);\n\t\n\t// Set vectors to zero\n\tfor(int i=0;i<numParticles*3;i++) {\n\t\tacc[i]=0.0;accStar[i]=0.0;npcdDeviation[i]=0.0;gradConcentration[i]=0.0;\n\t\tcorrecMatrixRow1[i]=0.0;correcMatrixRow2[i]=0.0;correcMatrixRow3[i]=0.0;normal[i]=0.0;dvelCollision[i]=0.0;//Acv[i]=0.0;\n\t\tparticleAtWallPos[i]=0.0;mirrorParticlePos[i]=0.0;wallParticleForce1[i]=0.0;wallParticleForce2[i]=0.0;polygonNormal[i]=0.0;\n\t\tforceWall[i]=0.0;\n\t}\n\n\t// Set scalars to zero or infinity(10e8)\n\tfor(int i=0; i<numParticles; i++) {\n\t\tparticleBC[i]=0;numNeigh[i]=0;numNeighWallContribution[i]=0;elementID[i]=0;\n\t\tparticleNearWall[i]=false;\n\t\tnearMeshType[i]=meshType::FIXED;\n\n\t\tpndi[i]=0.0;pndki[i]=0.0;pndski[i]=0.0;pndSmall[i]=0.0;npcdDeviation2[i]=0.0;concentration[i]=0.0;\n\t\tvelDivergence[i]=0.0;diffusiveTerm[i]=0.0;pndWallContribution[i]=0.0;deviationDotPolygonNormal[i]=0.0;\n\t\tnumNeighborsSurfaceParticles[i]=0.0;Cv[i]=0.0;II[i]=0.0;MEU_Y[i]=0.0;Inertia[i]=0.0;pnew[i]=0.0;\n\t\tp_rheo_new[i]=0.0;p_smooth[i]=0.0;VF[i]=0.0;S12[i]=0.0;S13[i]=0.0;S23[i]=0.0;S11[i]=0.0;S22[i]=0.0;S33[i]=0.0;\n\n\t\tdistParticleWall2[i]=10e8*partDist;\n\t}\n\t// Assign type and density\n\tfor(int i=0; i<numParticles; i++) {\n\t\t/*\n\t\t// Assign type and density\n\t\tif(pos[i*3+2] <= 0.3) {\n\t\t\tPTYPE[i]=2;\n\t\t\tRHO[i] = DNS_FL2;\n\t\t\t// CHANGED Only at the first time step\n\t\t\tMEU[i] = KNM_VS2 * DNS_FL2;\n\t\t}\n\t\telse {\n\t\t\tPTYPE[i]=1;\n\t\t\tRHO[i] = DNS_FL1;\n\t\t\t// CHANGED Only at the first time step\n\t\t\tMEU[i] = KNM_VS1 * DNS_FL1;\n\t\t}\n\t\t*/\n\n\t\tif(fluidType == viscType::NEWTONIAN) {\n\t\t\tRHO[i] = DNS_FL1;\n\t\t\tPTYPE[i] = 1;\n\t\t\tMEU[i] = KNM_VS1 * DNS_FL1;\n\t\t}\n\t\t// Multiphase simulations - Granular Fluid\n\t\tif(fluidType == viscType::NON_NEWTONIAN) {\n\t\t\t// Assign type and density\n\t\t\tif(particleType[i] == 1) {\n\t\t\t\tparticleType[i] = 0;\n\t\t\t\tPTYPE[i] = 2;\n\t\t\t\tRHO[i] = DNS_FL2;\n\t\t\t\t// CHANGED Only at the first time step\n\t\t\t\tMEU[i] = KNM_VS2 * DNS_FL2;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t//particleType[i] = 0;\n\t\t\t\tPTYPE[i] = 1;\n\t\t\t\tRHO[i] = DNS_FL1;\n\t\t\t\t// CHANGED Only at the first time step\n\t\t\t\tMEU[i] = KNM_VS1 * DNS_FL1;\n\t\t\t}\n\t\t}\n\t}\n}\n\n// Allocation of buckets\n// Murotani et al., 2015. Performance improvements of differential operators code for MPS method on GPU.\nvoid MpsParticle::allocateBuckets() {\n\treS = partDist*reS;\t\t\t\t\t\t\t\t// Influence radius small\n\treL = partDist*reL;\t\t\t\t\t\t\t\t// Influence radius large\n\treS2 = reS*reS;\t\t\t\t\t\t\t\t\t// Influence radius small to square\n\treL2 = reL*reL;\t\t\t\t\t\t\t\t\t// Influence radius large to square\n\tEPS_RE = EPS_RE*reS2/4.0;\n\treRepulsiveForce = partDist*reRepulsiveForce;\t// Influence radius for repulsive force\n\t// First guess of buckets values\n\tbucketSide = reL*(1.0+cflNumber);\t\t\t\t// Length of one bucket side\n\tinvBucketSide = 1.0/bucketSide;\n\tnumBucketsX = (int)((domainMaxX - domainMinX)*invBucketSide) + 3;\t\t// Number of buckets in the x direction in the analysis domain\n\tnumBucketsY = (int)((domainMaxY - domainMinY)*invBucketSide) + 3;\t\t// Number of buckets in the y direction in the analysis domain\n\tnumBucketsZ = (int)((domainMaxZ - domainMinZ)*invBucketSide) + 3;\t\t// Number of buckets in the z direction in the analysis domain\n\tif((int)dim == 2) {\tnumBucketsZ = 1; }\n\n\tbucketTypeBC = \t \t\t\t(int*)malloc(sizeof(int) * numBC);\t\t\t// Type of Domain Boundary Condition in Bucket\n\tperiodicDirection =\t \t\t(bool*)malloc(sizeof(bool) * numBC*3);\t\t// Periodic direction in domain (x, y, or z)\n\t//periodicLength = \t \t\t(double*)malloc(sizeof(double) * numBC*3);\t// Periodic length in x, y and z direction\n\tfor(int b=0; b<numBC; b++){\n\t\t// domainTypeBC == 0: None\n\t\t// domainTypeBC == 1: Periodic\n\t\tbucketTypeBC[b] = domainTypeBC;\n\t\tperiodicDirection[b*3  ] = periodicDirectionX;\n\t\tperiodicDirection[b*3+1] = periodicDirectionY;\n\t\tperiodicDirection[b*3+2] = periodicDirectionZ;\n\t}\n\tperiodicLength[0] = periodicLength[1] = periodicLength[2] = 0.0;\t\t// Periodic length in x, y and z direction\n\n\t// Compute domain limits and adjust the buckets values\n\tif(wallType == boundaryWallType::PARTICLE || domainTypeBC == 1) {\n\t\tcalcDomainLimits();\n\t\tinvBucketSide = 1.0/bucketSide;\n\t}\n\tnumBucketsXY = numBucketsX*numBucketsY;\n\tnumBucketsXYZ = numBucketsX*numBucketsY*numBucketsZ;\t\t\t\t\t// Number of buckets in analysis area\n\t\n\tstd::cout << std::endl << \"DomainMIN: \" << domainMinX << \" \" << domainMinY << \" \" << domainMinZ;\n\tstd::cout << std::endl << \"DomainMAX: \" << domainMaxX << \" \" << domainMaxY << \" \" << domainMaxZ;\n\tif(domainTypeBC == 1) {\n\t\tstd::cout << std::endl << \"PhysicMIN: \" << physDomMinX << \" \" << physDomMinY << \" \" << physDomMinZ;\n\t\tstd::cout << std::endl << \"PhysicMAX: \" << physDomMaxX << \" \" << physDomMaxY << \" \" << physDomMaxZ;\n\t}\n\tstd::cout << std::endl << \"Num Buckt: \" << numBucketsX << \" \" << numBucketsY << \" \" << numBucketsZ;\n\tstd::cout << std::endl << \"BucktSide: \" << bucketSide << \" 1/BucketSide: \" << invBucketSide;\n\tstd::cout << std::endl << \"PeriodicL: \" << periodicLength[0] << \" \" << periodicLength[1] << \" \" << periodicLength[2];\n\tstd::cout << std::endl;\n\n\tfirstParticleInBucket = \t(int*)malloc(sizeof(int) * numBucketsXYZ);\t// First particle number stored in the bucket\n\tlastParticleInBucket = \t\t(int*)malloc(sizeof(int) * numBucketsXYZ);\t// Last particle number stored in the bucket\n\tnextParticleInSameBucket  = (int*)malloc(sizeof(int) * numParticles);\t// Next particle number in the same bucket\n\tbucketPeriodicBC =\t \t\t(int*)malloc(sizeof(int) * numBucketsXYZ);\t// Periodic Boundary Condition of the bucket\n}\n\n// Set parameters\nvoid MpsParticle::setParameters() {\n\tpndSmallZero = pndLargeZero = pndGradientZero = lambdaZero = numNeighZero = 0.0;\n\tint lmin = ceil(reL/partDist) + 1;\n\tint lmax = ceil(reL/partDist) + 2;\n\tint flag2D = 0;\n\tint flag3D = 1;\n\tif((int)dim == 2) {\n\t\tflag2D = 1;\n\t\tflag3D = 0;\n\t}\n\tfor(int ix= -lmin; ix<lmax; ix++) {\n\tfor(int iy= -lmin; iy<lmax; iy++) {\n\tfor(int iz= -lmin*flag3D; iz<lmax*flag3D+flag2D; iz++) {\n\t\tdouble x = partDist* (double)ix;\n\t\tdouble y = partDist* (double)iy;\n\t\tdouble z = partDist* (double)iz;\n\t\tdouble dst2 = x*x+y*y+z*z;\n\t\tif(dst2 <= reL2) {\n\t\t\tif(dst2 <= 1.0e-8) continue; \t\t\t\t\t\t\t// equals to zero\n\t\t\tdouble dst = sqrt(dst2);\n\t\t\tpndLargeZero += weight(dst, reL, weightType);\t\t\t// Initial particle number density (large)\n\t\t\tlambdaZero += dst2 * weight(dst, reL, weightType);\n\t\t\tnumNeighZero += 1;\t\t\t\t\t\t\t\t\t\t// Initial number of neighbors\n\t\t\tif(dst2 <= reS2) {\n\t\t\t\tpndSmallZero += weight(dst, reS, weightType);\t\t// Initial particle number density (small)\n\t\t\t\tpndGradientZero += weightGradient(dst, reS, weightType);\t// Initial particle number density (gradient operator)\n\t\t\t}\n\t\t}\n\t}}}\n\tlambdaZero = lambdaZero/pndLargeZero;\t\t\t\t\t\t\t// Coefficient λ of Laplacian model\n\tcoeffViscosity = 2.0*KNM_VS1*dim/(pndLargeZero*lambdaZero);\t\t// Coefficient used to calculate viscosity term\n\tcoeffViscMultiphase = 2.0*dim/(pndLargeZero*lambdaZero);\t\t// Coefficient used to calculate viscosity term Multiphase\n\tcoeffPressEMPS = soundSpeed*soundSpeed/pndSmallZero;\t\t\t// Coefficient used to calculate pressure E-MPS\n\tcoeffPressGrad = -dim/pndGradientZero;\t\t\t\t\t\t\t// Coefficient used to calculate pressure gradient term\n\tcoeffPressWCMPS = soundSpeed*soundSpeed;\t\t\t\t\t\t// Coefficient used to calculate pressure WC-MPS\n\tcoeffShifting1 = dri*partDist/pndSmallZero;\t\t\t\t\t\t// Coefficient used to adjust velocity type 1\n\tcoeffShifting2 = coefA*partDist*partDist*cflNumber*machNumber;\t// Coefficient used to adjust velocity type 2\n\tcoeffPPE = 2.0*dim/(pndLargeZero*lambdaZero);\t\t\t\t\t// Coefficient used to PPE\n\tcoeffPPESource = relaxPND/(timeStep*timeStep*pndSmallZero);\t\t// Coefficient used to PPE source term\n\tDns[partType::FLUID]=densityFluid;\t\t\tDns[partType::WALL]=densityWall;\n\tinvDns[partType::FLUID]=1.0/densityFluid;\tinvDns[partType::WALL]=1.0/densityWall;\n\tinvPartDist = 1.0/partDist;\n\tdistCollisionLimit = partDist*distLimitRatio;\t\t\t\t\t// A distance that does not allow further access between particles\n\tdistCollisionLimit2 = distCollisionLimit*distCollisionLimit;\n\trestitutionCollision = 1.0 + collisionRatio;\n\tnumOfIterations = 0;\t\t\t\t\t\t\t\t\t\t\t// Number of iterations\n\tfileNumber = 0;\t\t\t\t\t\t\t\t\t\t\t\t\t// File number\n\ttimeCurrent = 0.0;\t\t\t\t\t\t\t\t\t\t\t\t// Simulation time\n\tvelMax = 0.0;\t\t\t\t\t\t\t\t\t\t\t\t\t// Maximum flow velocity\n\tCFLcurrent = cflNumber;\t\t\t\t\t\t\t\t\t\t\t// Current Courant number\n\tbetaPnd = pndThreshold*pndSmallZero;\t\t\t\t\t\t\t// Surface cte PND\n\tbetaNeigh = neighThreshold*numNeighZero;\t\t\t\t\t\t// Surface cte Neighbors\n\tdelta2 = npcdThreshold*npcdThreshold*partDist*partDist;\t\t\t// Surface cte NPCD \n\tthetaArc = thetaThreshold/180.0*3.14159265;\t\t\t\t\t\t// Surface cte theta ARC\n\thThreshold2 = 1.33*1.33*partDist*partDist;\t\t\t\t\t\t// Surface cte radius ARC\n\tdstThreshold2 = 2.0*hThreshold2;\t\t\t\t\t\t\t\t// Surface cte radius ARC\n\tnormThreshold2 = normThreshold*normThreshold;\t\t\t\t\t// Surface cte Normal\n\t\n\t//cout << \"lo: \" << partDist << \" m, dt: \" << timeStep << \" s, PND0Small: \" << pndSmallZero << \" PND0Large: \" << pndLargeZero << \" PND0Grad: \" << pndGradientZero << \" lambda: \" << lambdaZero << std::endl;\n\t//cout << \"bPnd: \" << betaPnd << \"betaNeigh: \" << betaNeigh << endl;\n}\n\n// Set initial PND and number of neighbors\nvoid MpsParticle::setInitialPndNumberOfNeigh() {\n#pragma omp parallel for schedule(dynamic,64)\n\tfor(int i=0; i<numParticles; i++) {\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\tdouble wSum = 0.0;\n\t\tnumNeigh[i] = 0;\n\t\tnpcdDeviation[i*3] = npcdDeviation[i*3+1] = npcdDeviation[i*3+2] = 0.0;\n\t\t\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reL2 && (dstij2 < dstimj2 || wallType == boundaryWallType::PARTICLE)) {\n\t\t\t\t\tif(j != i) {\n\t\t\t\t\t\tnumNeigh[i] += 1;\n\t\t\t\t\t\tif(dstij2 < reS2) {\n\t\t\t\t\t\t\tdouble dst = sqrt(dstij2);\n\t\t\t\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\t\t\t\tpndi[i] += wS;\n\t\t\t\t\t\t\t//dst = dst*invPartDist;\n\t\t\t\t\t\t\t//wS = weight(dst, reS*invPartDist, weightType);\n\t\t\t\t\t\t\t//npcdDeviation[i*3  ] += v0ij*wS*invPartDist;\n\t\t\t\t\t\t\t//npcdDeviation[i*3+1] += v1ij*wS*invPartDist;\n\t\t\t\t\t\t\t//npcdDeviation[i*3+2] += v2ij*wS*invPartDist;\n\t\t\t\t\t\t\tnpcdDeviation[i*3  ] += v0ij*wS;\n\t\t\t\t\t\t\tnpcdDeviation[i*3+1] += v1ij*wS;\n\t\t\t\t\t\t\tnpcdDeviation[i*3+2] += v2ij*wS;\n\t\t\t\t\t\t\twSum += wS;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\t\t// Add PND due wall polygon\n\t\tpndi[i] += pndWallContribution[i];\n\t\tif(particleType[i] == wall)\n\t\t\tpndi[i] = pndSmallZero;\n\t\tpndSmall[i] = pndi[i];\n\t\tpndki[i] = pndi[i];\n\t\t// Add Number of neighbors due wall polygon\n\t\tnumNeigh[i] += numNeighWallContribution[i];\n\n\t\tif(wSum > 1.0e-8) {\n\t\t\tnpcdDeviation[i*3  ] /= pndSmall[i];\n\t\t\tnpcdDeviation[i*3+1] /= pndSmall[i];\n\t\t\tnpcdDeviation[i*3+2] /= pndSmall[i];\n\t\t\t//npcdDeviation[i*3  ] /= wSum;\n\t\t\t//npcdDeviation[i*3+1] /= wSum;\n\t\t\t//npcdDeviation[i*3+2] /= wSum;\n\t\t}\n\n\t\tnpcdDeviation2[i] = npcdDeviation[i*3]*npcdDeviation[i*3] + npcdDeviation[i*3+1]*npcdDeviation[i*3+1] +\n\t\t\tnpcdDeviation[i*3+2]*npcdDeviation[i*3+2];\n\n\t\t//deviationDotPolygonNormal[i] = npcdDeviation[i*3]*polygonNormal[i*3]+npcdDeviation[i*3+1]*polygonNormal[i*3+1]+npcdDeviation[i*3+2]*polygonNormal[i*3+2];\n\t\tif(npcdDeviation[i*3]*polygonNormal[i*3]+npcdDeviation[i*3+1]*polygonNormal[i*3+1]+npcdDeviation[i*3+2]*polygonNormal[i*3+2] < 0.0)\n\t\t\tdeviationDotPolygonNormal[i] = 1;\n\t\telse\n\t\t\tdeviationDotPolygonNormal[i] = -1;\n\t}\n}\n\n// Compute domain limits\nvoid MpsParticle::calcDomainLimits()\n{\n\tdouble **limDom;\n\tlimDom = new double *[3];\n\tfor(int i=0; i<3; i++) limDom[i] = new double[3];\n\n\t// limitTypeBC = 0: Border particle positions\n\t// limitTypeBC = 1: Domain limits min and max\n\tif(limitTypeBC == 0) {\n\t\t// wall_type = 0: Use border particle positions to define all domain limits\n\t\t// wall_type = 1: Use border particle positions to define periodic domain limits\n\t\tlimDom[0][0] = limDom[0][1] = pos[0*3  ];\n\t\tlimDom[1][0] = limDom[1][1] = pos[0*3+1];\n\t\tlimDom[2][0] = limDom[2][1] = pos[0*3+2];\n\t\t\n\t\tfor(int i=0; i<numParticles; i++) {\n\t\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\t\tlimDom[0][0] = min(limDom[0][0], posXi);\n\t\t\tlimDom[0][1] = max(limDom[0][1], posXi);\n\t\t\tlimDom[1][0] = min(limDom[1][0], posYi);\n\t\t\tlimDom[1][1] = max(limDom[1][1], posYi);\n\t\t\tlimDom[2][0] = min(limDom[2][0], posZi);\n\t\t\tlimDom[2][1] = max(limDom[2][1], posZi);\n\t\t}\n\t\tint testdim = 0;\n\t\tif(limDom[0][0] != limDom[0][1])\n\t\t\ttestdim++;\n\t\tif(limDom[1][0] != limDom[1][1])\n\t\t\ttestdim++;\n\t\tif(limDom[2][0] != limDom[2][1])\n\t\t\ttestdim++;\n\t\tif(testdim != dim) {\n\t\t\tfprintf(stderr, \"\\n Dimensions in json [%d] and grid file [%d] do not match!\\n\\n\", int(dim), testdim);\n\t\t\texit(10);\n\t\t}\n\t}\n\telse {\n\t\t// Adopt min and max values from json to define domain limits\n\t\tlimDom[0][0] = domainMinX; limDom[0][1] = domainMaxX;\n\t\tlimDom[1][0] = domainMinY; limDom[1][1] = domainMaxY;\n\t\tlimDom[2][0] = domainMinZ; limDom[2][1] = domainMaxZ;\n\t}\n\n\t// domainTypeBC == 0: None\n\t// domainTypeBC == 1: Periodic\n\tif(domainTypeBC == 0 && wallType == boundaryWallType::PARTICLE) { // Whithout any special domain boundary condition\n\t\t\n\t\t// Shift half particle distance\n\t\tlimDom[0][0] -= 0.5*partDist;\tlimDom[0][1] += 0.5*partDist;\n\t\tlimDom[1][0] -= 0.5*partDist;\tlimDom[1][1] += 0.5*partDist;\n\t\tif(dim==3) {\n\t\t\tlimDom[2][0] -= 0.5*partDist;\tlimDom[2][1] += 0.5*partDist;\n\t\t}\n\t\t\n\t\tfor(int k=0; k<dim; k++) {\n\t\t\tlimDom[k][0] -= bucketSide;\n\t\t\tlimDom[k][1] += bucketSide;\n\t\t\tif(k == 0) {\n\t\t\t\tnumBucketsX = (long)((limDom[k][1]-limDom[k][0])/bucketSide+1);\n\t\t\t\tlimDom[k][1] = limDom[k][0] + numBucketsX*bucketSide; // Adjust the maximum limit o X\n\t\t\t}\n\t\t\telse if(k == 1) {\n\t\t\t\tnumBucketsY = (long)((limDom[k][1]-limDom[k][0])/bucketSide+1);\n\t\t\t\tlimDom[k][1] = limDom[k][0] + numBucketsY*bucketSide; // Adjust the maximum limit o Y\n\t\t\t}\n\t\t\telse if(k == 2) {\n\t\t\t\tnumBucketsZ = (long)((limDom[k][1]-limDom[k][0])/bucketSide+1);\n\t\t\t\tlimDom[k][1] = limDom[k][0] + numBucketsZ*bucketSide; // Adjust the maximum limit o Z\n\t\t\t}\n\t\t}\n\t}\n\telse if(domainTypeBC == 1) {\n\t\tfor(int b=0; b<numBC; b++) {\n\t\t\tif(bucketTypeBC[b] == domainBC::PERIODIC) {\n\t\t\t\tbool periodicX =  periodicDirection[b*3] && !periodicDirection[b*3+1] && !periodicDirection[b*3+2];\n\t\t\t\tbool periodicY = !periodicDirection[b*3] &&  periodicDirection[b*3+1] && !periodicDirection[b*3+2];\n\t\t\t\tbool periodicZ = !periodicDirection[b*3] && !periodicDirection[b*3+1] &&  periodicDirection[b*3+2];\n\t\t\t\t// Periodic in X\n\t\t\t\tif(periodicX) {\n\t\t\t\t\tperiodicLength[0] = limDom[0][1] - limDom[0][0] + partDist;\n\t\t\t\t\tlimDom[0][0] -= partDist*0.5;\n\t\t\t\t\tlimDom[0][1] += partDist*0.5;\n\t\t\t\t\t// Physical domain\n\t\t\t\t\tphysDomMinX = limDom[0][0];\n\t\t\t\t\tphysDomMaxX = limDom[0][1];\n\t\t\t\t\tnumBucketsX = (long)((limDom[0][1]-limDom[0][0])/bucketSide);\n\t\t\t\t\t// Adjust bucketSide to perfectly divide the domain without leftovers\n\t\t\t\t\tbucketSide = periodicLength[0]/(long)(periodicLength[0]/bucketSide);\n\t\t\t\t\t// Analysis domain is extended from the boundaries by one bucket width\n\t\t\t\t\tlimDom[0][0] -= bucketSide;\n\t\t\t\t\tlimDom[0][1] += bucketSide;\n\t\t\t\t\tnumBucketsX += 2;\n\t\t\t\t\t// Adjust limits of Y\n\t\t\t\t\tif(wallType == boundaryWallType::PARTICLE) {\n\t\t\t\t\t\tlimDom[1][0] -= bucketSide;\n\t\t\t\t\t\tlimDom[1][1] += bucketSide;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlimDom[1][0] = domainMinY - bucketSide;\n\t\t\t\t\t\tlimDom[1][1] = domainMaxY + bucketSide;\n\t\t\t\t\t}\n\t\t\t\t\t// Physical domain\n\t\t\t\t\tphysDomMinY = limDom[1][0];\n\t\t\t\t\tphysDomMaxY = limDom[1][1];\n\t\t\t\t\tnumBucketsY = (long)((limDom[1][1]-limDom[1][0])/bucketSide+1);\n\t\t\t\t\tlimDom[1][1] = limDom[1][0] + numBucketsY*bucketSide;\n\t\t\t\t\tif(dim == 3) {\n\t\t\t\t\t\t// Adjust limits of Z\n\t\t\t\t\t\tif(wallType == boundaryWallType::PARTICLE) {\n\t\t\t\t\t\t\tlimDom[2][0] -= bucketSide;\n\t\t\t\t\t\t\tlimDom[2][1] += bucketSide;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tlimDom[2][0] = domainMinZ - bucketSide;\n\t\t\t\t\t\t\tlimDom[2][1] = domainMaxZ + bucketSide;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Physical domain\n\t\t\t\t\t\tphysDomMinZ = limDom[2][0];\n\t\t\t\t\t\tphysDomMaxZ = limDom[2][1];\n\t\t\t\t\t\tnumBucketsZ = (long)((limDom[2][1]-limDom[2][0])/bucketSide+1);\n\t\t\t\t\t\tlimDom[2][1] = limDom[2][0] + numBucketsZ*bucketSide;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Periodic in Y\n\t\t\t\tif(periodicY) {\n\t\t\t\t\tperiodicLength[1] = limDom[1][1] - limDom[1][0] + partDist;\n\t\t\t\t\tlimDom[1][0] -= partDist*0.5;\n\t\t\t\t\tlimDom[1][1] += partDist*0.5;\n\t\t\t\t\t// Physical domain\n\t\t\t\t\tphysDomMinY = limDom[1][0];\n\t\t\t\t\tphysDomMaxY = limDom[1][1];\n\t\t\t\t\tnumBucketsY = (long)((limDom[1][1]-limDom[1][0])/bucketSide);\n\t\t\t\t\t// Adjust bucketSide to perfectly divide the domain without leftovers\n\t\t\t\t\tbucketSide = periodicLength[1]/(long)(periodicLength[1]/bucketSide);\n\t\t\t\t\t// Analysis domain is extended from the boundaries by one bucket width\n\t\t\t\t\tlimDom[1][0] -= bucketSide;\n\t\t\t\t\tlimDom[1][1] += bucketSide;\n\t\t\t\t\tnumBucketsY += 2;\n\t\t\t\t\t// Adjust limits of X\n\t\t\t\t\tif(wallType == boundaryWallType::PARTICLE) {\n\t\t\t\t\t\tlimDom[0][0] -= bucketSide;\n\t\t\t\t\t\tlimDom[0][1] += bucketSide;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlimDom[0][0] = domainMinX - bucketSide;\n\t\t\t\t\t\tlimDom[0][1] = domainMaxX + bucketSide;\n\t\t\t\t\t}\n\t\t\t\t\t// Physical domain\n\t\t\t\t\tphysDomMinX = limDom[0][0];\n\t\t\t\t\tphysDomMaxX = limDom[0][1];\n\t\t\t\t\tnumBucketsX = (long)((limDom[0][1]-limDom[0][0])/bucketSide+1);\n\t\t\t\t\tlimDom[0][1] = limDom[0][0] + numBucketsX*bucketSide;\n\t\t\t\t\tif(dim == 3) {\n\t\t\t\t\t\t// Adjust limits of Z\n\t\t\t\t\t\tif(wallType == boundaryWallType::PARTICLE) {\n\t\t\t\t\t\t\tlimDom[2][0] -= bucketSide;\n\t\t\t\t\t\t\tlimDom[2][1] += bucketSide;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tlimDom[2][0] = domainMinZ - bucketSide;\n\t\t\t\t\t\t\tlimDom[2][1] = domainMaxZ + bucketSide;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Physical domain\n\t\t\t\t\t\tphysDomMinZ = limDom[2][0];\n\t\t\t\t\t\tphysDomMaxZ = limDom[2][1];\n\t\t\t\t\t\tnumBucketsZ = (long)((limDom[2][1]-limDom[2][0])/bucketSide+1);\n\t\t\t\t\t\tlimDom[2][1] = limDom[2][0] + numBucketsZ*bucketSide;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Periodic in Z\n\t\t\t\tif(periodicZ) {\n\t\t\t\t\tperiodicLength[2] = limDom[2][1] - limDom[2][0] + partDist;\n\t\t\t\t\tlimDom[2][0] -= partDist*0.5;\n\t\t\t\t\tlimDom[2][1] += partDist*0.5;\n\t\t\t\t\t// Physical domain\n\t\t\t\t\tphysDomMinZ = limDom[2][0];\n\t\t\t\t\tphysDomMaxZ = limDom[2][1];\n\t\t\t\t\tnumBucketsZ = (long)((limDom[2][1]-limDom[2][0])/bucketSide);\n\t\t\t\t\t// Adjust bucketSide to perfectly divide the domain without leftovers\n\t\t\t\t\tbucketSide = periodicLength[2]/(long)(periodicLength[2]/bucketSide);\n\t\t\t\t\t// Analysis domain is extended from the boundaries by one bucket width\n\t\t\t\t\tlimDom[2][0] -= bucketSide;\n\t\t\t\t\tlimDom[2][1] += bucketSide;\n\t\t\t\t\tnumBucketsZ += 2;\n\t\t\t\t\t// Adjust limits of X\n\t\t\t\t\tif(wallType == boundaryWallType::PARTICLE) {\n\t\t\t\t\t\tlimDom[0][0] -= bucketSide;\n\t\t\t\t\t\tlimDom[0][1] += bucketSide;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlimDom[0][0] = domainMinX - bucketSide;\n\t\t\t\t\t\tlimDom[0][1] = domainMaxX + bucketSide;\n\t\t\t\t\t}\n\t\t\t\t\t// Physical domain\n\t\t\t\t\tphysDomMinX = limDom[0][0];\n\t\t\t\t\tphysDomMaxX = limDom[0][1];\n\t\t\t\t\tnumBucketsX = (long)((limDom[0][1]-limDom[0][0])/bucketSide+1);\n\t\t\t\t\tlimDom[0][1] = limDom[0][0] + numBucketsX*bucketSide;\n\t\t\t\t\t// Adjust limits of Y\n\t\t\t\t\tif(wallType == boundaryWallType::PARTICLE) {\n\t\t\t\t\t\tlimDom[1][0] -= bucketSide;\n\t\t\t\t\t\tlimDom[1][1] += bucketSide;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlimDom[1][0] = domainMinY - bucketSide;\n\t\t\t\t\t\tlimDom[1][1] = domainMaxY + bucketSide;\n\t\t\t\t\t}\n\t\t\t\t\t// Physical domain\n\t\t\t\t\tphysDomMinY = limDom[1][0];\n\t\t\t\t\tphysDomMaxY = limDom[1][1];\n\t\t\t\t\tnumBucketsY = (long)((limDom[1][1]-limDom[1][0])/bucketSide+1);\n\t\t\t\t\tlimDom[1][1] = limDom[1][0] + numBucketsY*bucketSide;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tstd::cout << std::endl << \"Periodic Domain Limits\";\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tdomainMinX = limDom[0][0];\tdomainMaxX = limDom[0][1];\n\tdomainMinY = limDom[1][0];\tdomainMaxY = limDom[1][1];\n\tdomainMinZ = limDom[2][0];\tdomainMaxZ = limDom[2][1];\n\n}\n\n// Set Periodic Boundary Condition of the bucket\nvoid MpsParticle::setBucketBC() {\n\tfor(int iz=0; iz<numBucketsZ; iz++) {\n\t\tfor(int iy=0; iy<numBucketsY; iy++) {\n\t\t\tfor(int ix=0; ix<numBucketsX; ix++) {\n\t\t\t\tint ib = iz*numBucketsXY + iy*numBucketsX + ix;\n\t\t\t\tbucketPeriodicBC[ib] = 0;\n\t\t\t\tfor(int b=0; b<numBC; b++) {\n\t\t\t\t\tif(bucketTypeBC[b] == domainBC::PERIODIC) {\n\t\t\t\t\t\t// Periodic in X\n\t\t\t\t\t\tif(periodicDirection[b*3]) {\n\t\t\t\t\t\t\tif(ix == 0) { // Left border of domain\n\t\t\t\t\t\t\t\tbucketPeriodicBC[ib] = -1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif(ix == numBucketsX-1) { // Right border of domain\n\t\t\t\t\t\t\t\tbucketPeriodicBC[ib] = 1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Periodic in Y\n\t\t\t\t\t\tif(periodicDirection[b*3+1]) {\n\t\t\t\t\t\t\tif(iy == 0) { // Bottom border of domain\n\t\t\t\t\t\t\t\tbucketPeriodicBC[ib] = -1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif(iy == numBucketsY-1) { // Top border of domain\n\t\t\t\t\t\t\t\tbucketPeriodicBC[ib] = 1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Periodic in Z\n\t\t\t\t\t\tif(periodicDirection[b*3+2]) {\n\t\t\t\t\t\t\tif(iz == 0) { // Back border of domain\n\t\t\t\t\t\t\t\tbucketPeriodicBC[ib] = -1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif(iz == numBucketsZ-1) { // Front border of domain\n\t\t\t\t\t\t\t\tbucketPeriodicBC[ib] = 1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t//std::cout << std::endl << \"ib: \" << ib << \" ix: \" << ix\n\t\t\t\t\t//<< \" iy: \" << iy << \" iz: \" << iz;\n\t\t\t\t\t//std::cout << \" bc: \" << bucketPeriodicBC[ib];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n////////////////////////////////////////////////////////////\n// Functions called during the simulation (main loop)\n////////////////////////////////////////////////////////////\n\n// Verify if particle is out of domain\nvoid MpsParticle::checkParticleOutDomain() {\n\n#pragma omp parallel for\n\tfor(int i=0; i<numParticles; i++) {\n\t\tfor(int b=0; b<numBC; b++) {\n\t\t\tif(bucketTypeBC[b] == domainBC::PERIODIC) {\n\t\t\t\t// Periodic in X\n\t\t\t\tif(periodicDirection[b*3]) {\n\t\t\t\t\tif(pos[i*3  ]>physDomMaxX) {\n\t\t\t\t\t\tpos[i*3  ] -= periodicLength[0];\n\t\t\t\t\t}\n\t\t\t\t\tif(pos[i*3  ]<physDomMinX) {\n\t\t\t\t\t\tpos[i*3  ] += periodicLength[0];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Periodic in Y\n\t\t\t\tif(periodicDirection[b*3+1]) {\n\t\t\t\t\tif(pos[i*3+1]>physDomMaxY) {\n\t\t\t\t\t\tpos[i*3+1] -= periodicLength[1];\n\t\t\t\t\t}\n\t\t\t\t\tif(pos[i*3+1]<physDomMinY) {\n\t\t\t\t\t\tpos[i*3+1] += periodicLength[1];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Periodic in Z\n\t\t\t\tif(periodicDirection[b*3+2]) {\n\t\t\t\t\tif(pos[i*3+2]>physDomMaxZ) {\n\t\t\t\t\t\tpos[i*3+2] -= periodicLength[2];\n\t\t\t\t\t}\n\t\t\t\t\tif(pos[i*3+2]<physDomMinZ) {\n\t\t\t\t\t\tpos[i*3+2] += periodicLength[2];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tint newNumParticles = numParticles;\n\tdouble limMinX = domainMinX;\n\tdouble limMaxX = domainMaxX;\n\tdouble limMinY = domainMinY;\n\tdouble limMaxY = domainMaxY;\n\tdouble limMinZ = domainMinZ;\n\tdouble limMaxZ = domainMaxZ;\n\t// limitTypeBC = 0: Border particle positions\n\t// limitTypeBC = 1: Domain limits min and max\n\t////if(limitTypeBC == 0)\n\t////{\n\t\tlimMinX += bucketSide; limMaxX -= bucketSide;\n\t\tlimMinY += bucketSide; limMaxY -= bucketSide;\n\t\tlimMinZ += bucketSide; limMaxZ -= bucketSide;\n\t////}\n\tfor(int i=0; i<numParticles; i++) {\n\t\tif(\tparticleType[i] == fluid && i < newNumParticles &&\n\t\t\t(pos[i*3  ]>limMaxX || pos[i*3  ]<limMinX ||\n\t\t\tpos[i*3+1]>limMaxY || pos[i*3+1]<limMinY ||\n\t\t\t(dim == 3 && (pos[i*3+2]>limMaxZ || pos[i*3+2]<limMinZ)))) {\n\t\t\t\n\t\t\t// ID of last particle\n\t\t\tint iLastParticle = newNumParticles - 1;\n\t\t\t// Move the data from \"Last Particle\" to i-th ghost particle\n\n\t\t\t// Scalars\n\t\t\tparticleType[i]=particleType[iLastParticle];\n\t\t\tparticleBC[i]=particleBC[iLastParticle];\n\t\t\tnumNeigh[i]=numNeigh[iLastParticle];\n\t\t\tpress[i]=press[iLastParticle];\n\t\t\tpressAverage[i]=pressAverage[iLastParticle];\n\t\t\tpndi[i]=pndi[iLastParticle];\n\t\t\tpndki[i]=pndki[iLastParticle];\n\t\t\tpndski[i]=pndski[iLastParticle];\n\t\t\tpndSmall[i]=pndSmall[iLastParticle];\n\t\t\tnpcdDeviation2[i]=npcdDeviation2[iLastParticle];\n\t\t\tconcentration[i]=concentration[iLastParticle];\n\t\t\tvelDivergence[i]=velDivergence[iLastParticle];\n\t\t\tdiffusiveTerm[i]=diffusiveTerm[iLastParticle];\n\t\t\tnearMeshType[i]=nearMeshType[iLastParticle];\n\t\t\tparticleNearWall[i]=particleNearWall[iLastParticle];\n\t\t\tnumNeighWallContribution[i]=numNeighWallContribution[iLastParticle];\n\t\t\tpndWallContribution[i]=pndWallContribution[iLastParticle];\n\t\t\tdeviationDotPolygonNormal[i]=deviationDotPolygonNormal[iLastParticle];\n\t\t\tnumNeighborsSurfaceParticles[i]=numNeighborsSurfaceParticles[iLastParticle];\n\t\t\tdistParticleWall2[i]=distParticleWall2[iLastParticle];\n\t\t\tPTYPE[i]=PTYPE[iLastParticle];\n\t\t\tCv[i]=Cv[iLastParticle];\n\t\t\tII[i]=II[iLastParticle];\n\t\t\tMEU[i]=MEU[iLastParticle];\n\t\t\tMEU_Y[i]=MEU_Y[iLastParticle];\n\t\t\tInertia[i]=Inertia[iLastParticle];\n\t\t\tpnew[i]=pnew[iLastParticle];\n\t\t\tp_rheo_new[i]=p_rheo_new[iLastParticle];\n\t\t\tRHO[i]=RHO[iLastParticle];\n\t\t\tp_smooth[i]=p_smooth[iLastParticle];\n\t\t\tVF[i]=VF[iLastParticle];\n\t\t\tS12[i]=S12[iLastParticle];\n\t\t\tS13[i]=S13[iLastParticle];\n\t\t\tS23[i]=S23[iLastParticle];\n\t\t\tS11[i]=S11[iLastParticle];\n\t\t\tS22[i]=S22[iLastParticle];\n\t\t\tS33[i]=S33[iLastParticle];\n\t\t\telementID[i]=elementID[iLastParticle];\n\n\t\t\tpressurePPE(i)=pressurePPE(iLastParticle);\n\t\t\tsourceTerm(i)=sourceTerm(iLastParticle);\n\t\t\t\n\t\t\t// Vectors\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tacc[i*3+j]=acc[iLastParticle*3+j];\n\t\t\t\taccStar[i*3+j]=accStar[iLastParticle*3+j];\n\t\t\t\tpos[i*3+j]=pos[iLastParticle*3+j];\n\t\t\t\tvel[i*3+j]=vel[iLastParticle*3+j];\n\t\t\t\tnpcdDeviation[i*3+j]=npcdDeviation[iLastParticle*3+j];\n\t\t\t\tgradConcentration[i*3+j]=gradConcentration[iLastParticle*3+j];\n\t\t\t\tcorrecMatrixRow1[i*3+j]=correcMatrixRow1[iLastParticle*3+j];\n\t\t\t\tcorrecMatrixRow2[i*3+j]=correcMatrixRow2[iLastParticle*3+j];\n\t\t\t\tcorrecMatrixRow3[i*3+j]=correcMatrixRow3[iLastParticle*3+j];\n\t\t\t\tnormal[i*3+j]=normal[iLastParticle*3+j];\n\t\t\t\tdvelCollision[i*3+j]=dvelCollision[iLastParticle*3+j];\n\t\t\t\tparticleAtWallPos[i*3+j]=particleAtWallPos[iLastParticle*3+j];\n\t\t\t\tmirrorParticlePos[i*3+j]=mirrorParticlePos[iLastParticle*3+j];\n\t\t\t\twallParticleForce1[i*3+j]=wallParticleForce1[iLastParticle*3+j];\n\t\t\t\twallParticleForce2[i*3+j]=wallParticleForce2[iLastParticle*3+j];\n\t\t\t\tpolygonNormal[i*3+j]=polygonNormal[iLastParticle*3+j];\n\t\t\t\tforceWall[i*3+j]=forceWall[iLastParticle*3+j];\n\t\t\t\t//Posk[i*3+j]=Posk[iLastParticle*3+j];\n\t\t\t\t//Velk[i*3+j]=Velk[iLastParticle*3+j];\n\t\t\t\t//Acv[i*3+j]=Acv[iLastParticle*3+j];\n\t\t\t}\n\n\t\t\t// Update some data of \"Last Particle\"\n\t\t\tparticleType[iLastParticle]=ghost;\n\t\t\tparticleBC[iLastParticle]=other;\n\t\t\tparticleNearWall[iLastParticle]=false;\n\t\t\tnearMeshType[iLastParticle]=meshType::FIXED;\n\t\t\tdistParticleWall2[iLastParticle]=10e8*partDist;\n\t\t\t// Set zero to velocity and press of lastParticle\n\t\t\tfor (int j = 0; j < 3; j++){\n\t\t\t\t//pos[iLastParticle*3+j]=0.0;\n\t\t\t\t//Posk[iLastParticle*3+j]=0.0;\n\t\t\t\tvel[iLastParticle*3+j] = 0.0;\n\t\t\t}\n\t\t\tpress[iLastParticle  ] = 0.0;\n\t\t\t// Set maximum position to lastParticle\n\t\t\tpos[iLastParticle*3  ] = domainMaxX - partDist;\n\t\t\tpos[iLastParticle*3+1] = domainMaxY - partDist;\n\t\t\tif (dim == 2)\n\t\t\t\tpos[iLastParticle*3+2] = 0.0;\n\t\t\telse\n\t\t\t\tpos[iLastParticle*3+2] = domainMaxZ - partDist;\n\t\t\t\n\t\t\t// Decrease number of particles\n\t\t\tnewNumParticles--;\n\t\t}\n\t\t// Update number of particles\n\t\tnumParticles = newNumParticles;\n\t}\n}\n\n// Copy data from periodic buckets to border buckets\nvoid MpsParticle::copyDataBetweenBuckets(const int b) {\n\tbool periodicX =  periodicDirection[b*3] && !periodicDirection[b*3+1] && !periodicDirection[b*3+2];\n\tbool periodicY = !periodicDirection[b*3] &&  periodicDirection[b*3+1] && !periodicDirection[b*3+2];\n\tbool periodicZ = !periodicDirection[b*3] && !periodicDirection[b*3+1] &&  periodicDirection[b*3+2];\n\t// Periodic in X\n\tif(periodicX) {\n\t\t//for(int iz=0; iz<numBucketsZ; iz++) {\n\t\t//\tfor(int iy=0; iy<numBucketsY; iy++) {\n\t\t//\t\tfor(int ix=0; ix<numBucketsX; ix+=numBucketsX-1) {\n\t\t//\t\t\tint ib = iz*numBucketsXY + iy*numBucketsX + ix;\n#pragma omp parallel for\n\t\tfor (int ib=0; ib<numBucketsXYZ; ib++) {\n\t\t\tif(bucketPeriodicBC[ib] == -1) {\n\t\t\t\tfirstParticleInBucket[ib] = firstParticleInBucket[ib+numBucketsX-2];\n\t\t\t\tlastParticleInBucket[ib] = lastParticleInBucket[ib+numBucketsX-2];\n\t\t\t}\n\t\t\tif(bucketPeriodicBC[ib] == 1) {\n\t\t\t\tfirstParticleInBucket[ib] = firstParticleInBucket[ib-numBucketsX+2];\n\t\t\t\tlastParticleInBucket[ib] = lastParticleInBucket[ib-numBucketsX+2];\n\t\t\t}\n\t\t}\n\t\t//}}}\n\t}\n\t// Periodic in Y\n\tif(periodicY) {\n\t\t//for(int ix=0; ix<numBucketsX; ix++) {\n\t\t//\tfor(int iz=0; iz<numBucketsZ; iz++) {\n\t\t//\t\tfor(int iy=0; iy<numBucketsY; iy+=numBucketsY-1) {\n\t\t//\t\t\tint ib = iz*numBucketsXY + iy*numBucketsX + ix;\n#pragma omp parallel for\n\t\tfor (int ib=0; ib<numBucketsXYZ; ib++) {\n\t\t\tif(bucketPeriodicBC[ib] == -1) {\n\t\t\t\tfirstParticleInBucket[ib] = firstParticleInBucket[ib+numBucketsX*(numBucketsY-2)];\n\t\t\t\tlastParticleInBucket[ib] = lastParticleInBucket[ib+numBucketsX*(numBucketsY-2)];\n\t\t\t}\n\t\t\tif(bucketPeriodicBC[ib] == 1) {\n\t\t\t\tfirstParticleInBucket[ib] = firstParticleInBucket[ib-numBucketsX*(numBucketsY-2)];\n\t\t\t\tlastParticleInBucket[ib] = lastParticleInBucket[ib-numBucketsX*(numBucketsY-2)];\n\t\t\t}\n\t\t}\n\t\t//}}}\n\t}\n\t// Periodic in Z\n\tif(periodicZ) {\n\t\t//for(int iy=0; iy<numBucketsY; iy++) {\n\t\t//\tfor(int ix=0; ix<numBucketsX; ix++) {\n\t\t//\t\tfor(int iz=0; iz<numBucketsZ; iz+=numBucketsZ-1) {\n\t\t//\t\t\tint ib = iz*numBucketsXY + iy*numBucketsX + ix;\n#pragma omp parallel for\n\t\tfor (int ib=0; ib<numBucketsXYZ; ib++) {\n\t\t\tif(bucketPeriodicBC[ib] == -1) {\n\t\t\t\tfirstParticleInBucket[ib] = firstParticleInBucket[ib+numBucketsXY*(numBucketsZ-2)];\n\t\t\t\tlastParticleInBucket[ib] = lastParticleInBucket[ib+numBucketsXY*(numBucketsZ-2)];\n\t\t\t}\n\t\t\tif(bucketPeriodicBC[ib] == 1) {\n\t\t\t\tfirstParticleInBucket[ib] = firstParticleInBucket[ib-numBucketsXY*(numBucketsZ-2)];\n\t\t\t\tlastParticleInBucket[ib] = lastParticleInBucket[ib-numBucketsXY*(numBucketsZ-2)];\n\t\t\t}\n\t\t}\n\t\t//}}}\n\t}\n}\n\n// Update particle ID's in buckets\nvoid MpsParticle::updateBuckets() {\n\tif((int)dim == 2) {\n#pragma omp parallel for\n\t\tfor(int i=0; i<numBucketsXY; i++) {\t\n\t\t\tfirstParticleInBucket[i] = -1;\n\t\t\tlastParticleInBucket[i] = -1;\n\t\t}\n#pragma omp parallel for\n\t\tfor(int i=0; i<numParticlesZero; i++) {\t\n\t\t\tnextParticleInSameBucket[i] = -1;\n\t\t}\n\t\tfor(int i=0; i<numParticles; i++) {\n\t\t\tif(particleType[i] == ghost) continue;\n\t\t\tint ix = (int)((pos[i*3  ] - domainMinX)*invBucketSide + 1.0e-8);\n\t\t\tint iy = (int)((pos[i*3+1] - domainMinY)*invBucketSide + 1.0e-8);\n\t\t\tint ib = iy*numBucketsX + ix;\n\t\t\tint j = lastParticleInBucket[ib];\n\t\t\tlastParticleInBucket[ib] = i;\n\t\t\tif(j == -1) {\tfirstParticleInBucket[ib] = i;\t}\n\t\t\telse \t\t{\tnextParticleInSameBucket[j] = i;}\n\t\t}\n\t}\n\telse {\n#pragma omp parallel for\n\t\tfor(int i=0; i<numBucketsXYZ; i++) {\n\t\t\tfirstParticleInBucket[i] = -1;\n\t\t\tlastParticleInBucket[i] = -1;\n\t\t}\n#pragma omp parallel for\n\t\tfor(int i=0; i<numParticlesZero; i++) {\n\t\t\tnextParticleInSameBucket[i] = -1;\n\t\t}\n\t\tfor(int i=0; i<numParticles; i++) {\n\t\t\tif(particleType[i] == ghost) continue;\n\t\t\tint ix = (int)((pos[i*3  ] - domainMinX)*invBucketSide);\n\t\t\tint iy = (int)((pos[i*3+1] - domainMinY)*invBucketSide);\n\t\t\tint iz = (int)((pos[i*3+2] - domainMinZ)*invBucketSide);\n\t\t\tint ib = iz*numBucketsXY + iy*numBucketsX + ix;\n\t\t\tint j = lastParticleInBucket[ib];\n\t\t\tlastParticleInBucket[ib] = i;\n\t\t\tif(j == -1) {\tfirstParticleInBucket[ib] = i;\t}\n\t\t\telse \t\t{\tnextParticleInSameBucket[j] = i;}\n\t\t}\n\t}\n\t// Copy data from periodic buckets to border buckets\n\tfor(int b=0; b<numBC; b++) {\n\t\tif(bucketTypeBC[b] == domainBC::PERIODIC) {\n\t\t\tcopyDataBetweenBuckets(b);\n\t\t}\n\t}\n}\n\n// Acceleration due Laplacian of velocity and gravity\nvoid MpsParticle::calcViscosityGravity() {\n#pragma omp parallel for schedule(dynamic,64)\n\tfor(int i=0; i<numParticles; i++) {\n//\t\tif(particleType[i] == fluid) {\n\t\tdouble meu_i = MEU[i];\n\t\tdouble accX = 0.0;\t\t\tdouble accY = 0.0;\t\t\tdouble accZ = 0.0;\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble velXi = vel[i*3  ];\tdouble velYi = vel[i*3+1];\tdouble velZi = vel[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reL2 && (dstij2 < dstimj2 || wallType == boundaryWallType::PARTICLE)) {\n\t\t\t\t\tif(j != i) {\n\t\t\t\t\t\tdouble dst = sqrt(dstij2);\n\t\t\t\t\t\tdouble wL = weight(dst, reL, weightType);\n\t\t\t\t\t\tdouble neu_ij;\n\t\t\t\t\t\tif ((meu_i + MEU[j]) > 1.0e-8)\n\t\t\t\t\t\t\tneu_ij = 2.0 * meu_i * MEU[j] / (meu_i + MEU[j]);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tneu_ij = 0.0;\n\t\t\t\t\t\tif(particleType[j] == wall) neu_ij = 2.0 * meu_i; // MEU[j] -> oo\n\t\t\t\t\t\t//neu_ij = KNM_VS2 * DNS_FL2;\n\t//\t\t\t\t\tif(PTYPE[i] == 1) neu_ij = neu_ij/DNS_FL1;\n\t//\t\t\t\t\telse neu_ij = neu_ij/DNS_FL2;\n\t\t\t\t\t\tneu_ij = neu_ij/RHO[i];\n\t\t\t\t\t\t//if((NEUt[i] + NEUt[j]) > 0) neu_ij = neu_ij + (2.0 * NEUt[i] * RHO[j] * NEUt[j] * RHO[j] / (NEUt[i] * RHO[i] + NEUt[j] * RHO[j])) / RHO[i];\n\t\t\t\t\t\t// Original\n\t//\t\t\t\t\taccX +=(vel[j*3  ]-velXi)*w;\n\t//\t\t\t\t\taccY +=(vel[j*3+1]-velYi)*w;\n\t//\t\t\t\t\taccZ +=(vel[j*3+2]-velZi)*w;\n\t\t\t\t\t\t// Modified\n\t\t\t\t\t\taccX +=(vel[j*3  ]-velXi)*wL*neu_ij;\n\t\t\t\t\t\taccY +=(vel[j*3+1]-velYi)*wL*neu_ij;\n\t\t\t\t\t\taccZ +=(vel[j*3+2]-velZi)*wL*neu_ij;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\t\t// Original\n//\t\tacc[i*3  ]=accX*coeffViscosity + gravityX;\n//\t\tacc[i*3+1]=accY*coeffViscosity + gravityY;\n//\t\tacc[i*3+2]=accZ*coeffViscosity + gravityZ;\n\t\t// Modified\n\t\t//if(timeCurrent > 0.3) {\n\t\t// coeffViscMultiphase = 2.0*dim/(pndLargeZero*lambdaZero);\n\t\tacc[i*3  ] = coeffViscMultiphase*accX + gravityX;\n\t\tacc[i*3+1] = coeffViscMultiphase*accY + gravityY;\n\t\tacc[i*3+2] = coeffViscMultiphase*accZ + gravityZ;\n\t\t//}\t\t\n\t\taccStar[i*3  ] = acc[i*3  ];\n\t\taccStar[i*3+1] = acc[i*3+1];\n\t\taccStar[i*3+2] = acc[i*3+2];\n\t}\n}\n\n// Prediction of pressure gradient\nvoid MpsParticle::predictionPressGradient() {\n#pragma omp parallel for schedule(dynamic,64)\n\tfor(int i=0; i<numParticles; i++){\n//\t\tif(particleType[i] == fluid) {\n\t\tdouble accX = 0.0;\t\t\tdouble accY = 0.0;\t\t\tdouble accZ = 0.0;\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\tdouble Pi = press[i];\t\t\tdouble ni = pndi[i];\t\tdouble pressMin = Pi;\n\t\t\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tif(gradientType == 0 || gradientType == 2) {\n\t\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\t\tint j = firstParticleInBucket[jb];\n\t\t\t\tif(j == -1) continue;\n\t\t\t\tdouble plx, ply, plz;\n\t\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\t\twhile(true) {\n\t\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\t\tif(dstij2 < reS2 && (dstij2 < dstimj2 || wallType == boundaryWallType::PARTICLE)) {\n\t\t\t\t\t\tif(j != i) {\n\t\t\t\t\t\t\tif(pressMin > press[j]) pressMin = press[j];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\t\tif(j == -1) break;\n\t\t\t\t}\n\t\t\t}}}\n\t\t}\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reS2 && (dstij2 < dstimj2 || wallType == boundaryWallType::PARTICLE)) {\n\t\t\t\t\tif(j != i) {\n\t\t\t\t\t\tdouble dst = sqrt(dstij2);\n\t\t\t\t\t\tdouble wS = weightGradient(dst, reS, weightType);\n\t\t\t\t\t\tif(gradientType == 0)\n\t\t\t\t\t\t\twS *= (press[j] - pressMin)/dstij2;\n\t\t\t\t\t\telse if(gradientType == 1)\n\t\t\t\t\t\t\twS *= (press[j] + Pi)/dstij2;\n\t\t\t\t\t\telse if(gradientType == 2)\n\t\t\t\t\t\t\twS *= (press[j] + Pi - 2.0*pressMin)/dstij2;\n\t\t\t\t\t\telse if(gradientType == 3) {\n\t\t\t\t\t\t\tdouble nj = pndi[j];\n\t\t\t\t\t\t\tif(ni > 1.0e-8 && nj > 1.0e-8)\n\t\t\t\t\t\t\t\twS *= (ni*press[j]/nj + nj*Pi/ni)/dstij2;\n\t\t\t\t\t\t}\n\t\t\t\t\t\taccX += v0ij*wS;\taccY += v1ij*wS;\taccZ += v2ij*wS;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\t\t// coeffPressGrad is a negative cte (-dim/noGrad)\n\t\t// Original\n//\t\tacc[i*3  ]+=(1.0-relaxPress)*accX*invDns[partType::FLUID]*coeffPressGrad;\n//\t\tacc[i*3+1]+=(1.0-relaxPress)*accY*invDns[partType::FLUID]*coeffPressGrad;\n//\t\tacc[i*3+2]+=(1.0-relaxPress)*accZ*invDns[partType::FLUID]*coeffPressGrad;\n\t\t// Modified\n\t\tacc[i*3  ]+=(1.0-relaxPress)*accX*coeffPressGrad/RHO[i];\n\t\tacc[i*3+1]+=(1.0-relaxPress)*accY*coeffPressGrad/RHO[i];\n\t\tacc[i*3+2]+=(1.0-relaxPress)*accZ*coeffPressGrad/RHO[i];\n\t}\n}\n\n// Prediction of pressure gradient (Polygon wall)\nvoid MpsParticle::predictionWallPressGradient() {\n\t// Maximum velocity is the minimum of the computed and expected maximum velocities\n\tdouble maxVelocity = min(velMax, expectMaxVelocity);\n\tdouble velMax2 = maxVelocity*maxVelocity;\n\t//int nPartNearMesh = partNearMesh.size();\n\t//printf(\" Mesh %d \\n\", nPartNearMesh);\n\t// Loop only for particles near mesh\n#pragma omp parallel for schedule(dynamic,64)\n\t//for(int im=0;im<nPartNearMesh;im++) {\n\t//int i = partNearMesh[im];\n\tfor(int i=0; i<numParticles; i++) {\n\t\t//particleNearWall[i]=true; // Only to show particles near polygon\n\t\tif(particleType[i] == fluid && particleNearWall[i] == true) {\n\t\t\tdouble accX = 0.0;\t\t\tdouble accY = 0.0;\t\t\tdouble accZ = 0.0;\n\t\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\t\tdouble Pi = press[i];\t\t\tdouble ni = pndi[i];\t\tdouble pressMin = Pi;\n\t\t\t\n\t\t\t// Wall gradient Mitsume`s model\n\t\t    double Rref_i[9], normaliw[3], normaliwSqrt;\n\t\t    // normal fluid-wall particle = 0.5*(normal fluid-mirror particle)\n\t\t    normaliw[0] = 0.5*(posXi - posMirrorXi); normaliw[1] = 0.5*(posYi - posMirrorYi); normaliw[2] = 0.5*(posZi - posMirrorZi);\n\t\t    normaliwSqrt = sqrt(normaliw[0]*normaliw[0] + normaliw[1]*normaliw[1] + normaliw[2]*normaliw[2]);\n\t\t    if(normaliwSqrt > 1.0e-8) {\n\t\t    \tnormaliw[0] = normaliw[0]/normaliwSqrt;\n\t\t    \tnormaliw[1] = normaliw[1]/normaliwSqrt;\n\t\t    \tnormaliw[2] = normaliw[2]/normaliwSqrt;\n\t\t    }\n\t\t    else {\n\t\t    \tnormaliw[0] = 0.0;\n\t\t    \tnormaliw[1] = 0.0;\n\t\t    \tnormaliw[2] = 0.0;\n\t\t    }\n\t\t    //  Transformation matrix Rref_i = I - 2.0*normal_iwall*normal_iwall\n\t\t    Rref_i[0] = 1.0 - 2.0*normaliw[0]*normaliw[0]; Rref_i[1] = 0.0 - 2.0*normaliw[0]*normaliw[1]; Rref_i[2] = 0.0 - 2.0*normaliw[0]*normaliw[2];\n\t\t\tRref_i[3] = 0.0 - 2.0*normaliw[1]*normaliw[0]; Rref_i[4] = 1.0 - 2.0*normaliw[1]*normaliw[1]; Rref_i[5] = 0.0 - 2.0*normaliw[1]*normaliw[2];\n\t\t\tRref_i[6] = 0.0 - 2.0*normaliw[2]*normaliw[0]; Rref_i[7] = 0.0 - 2.0*normaliw[2]*normaliw[1]; Rref_i[8] = 1.0 - 2.0*normaliw[2]*normaliw[2];\n\t\t\t// Taylor pressure Pj\n\t\t\tdouble Rai[3];\n\t\t\tRai[0] = Rref_i[0]*accStar[i*3] + Rref_i[1]*accStar[i*3+1] + Rref_i[2]*accStar[i*3+2];\n\t\t\tRai[1] = Rref_i[3]*accStar[i*3] + Rref_i[4]*accStar[i*3+1] + Rref_i[5]*accStar[i*3+2];\n\t\t\tRai[2] = Rref_i[6]*accStar[i*3] + Rref_i[7]*accStar[i*3+1] + Rref_i[8]*accStar[i*3+2];\n\n\t\t\tint ix, iy, iz;\n\t\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\t\tif(gradientType == 0 || gradientType == 2) {\n\t\t\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\t\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\t\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\t\t\tint j = firstParticleInBucket[jb];\n\t\t\t\t\tif(j == -1) continue;\n\t\t\t\t\tdouble plx, ply, plz;\n\t\t\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\t\t\twhile(true) {\n\t\t\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\t\t\tif(dstij2 < reS2 && dstij2 < dstimj2) {\n\t\t\t\t\t\tif(j != i) {\n\t\t\t\t\t\t\tif(pressMin > press[j]) pressMin = press[j];\n\t\t\t\t\t\t}}\n\t\t\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\t\t\tif(j == -1) break;\n\t\t\t\t\t}\n\t\t\t\t}}}\n\t\t\t}\n\t\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\t\tint j = firstParticleInBucket[jb];\n\t\t\t\tif(j == -1) continue;\n\t\t\t\tdouble plx, ply, plz;\n\t\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\t\twhile(true) {\n\t\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\t\n\t\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t\t// If j is inside the neighborhood of i and im (intersection) and \n\t\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\t\tif(dstij2 < reS2 && dstimj2 < reS2 && dstij2 < dstimj2) {\n\t\t\t\t\t\tif(j != i) {\n\n\t\t\t\t\t\t\tdouble dst = sqrt(dstimj2);\n\t\t\t\t\t\t\tdouble wS = weightGradient(dst, reS, weightType);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// Taylor pressure Pj\n\t\t\t\t\t\t\tdouble Pj;\n\t\t//\t\t\t\t\tPj = Pi + RHO[i]*(Rai[0]*v0 + Rai[1]*v1 + Rai[2]*v2);\n\t\t\t\t\t\t\tPj = press[j];\n\n\t\t\t\t\t\t\tif(gradientType == 0)\n\t\t\t\t\t\t\t\twS *= (Pj - pressMin)/dstimj2;//(press[j] - pressMin)/dstimj2;\n\t\t\t\t\t\t\telse if(gradientType == 1)\n\t\t\t\t\t\t\t\twS *= (Pj + Pi)/dstimj2;//(press[j] + Pi)/dstimj2;\n\t\t\t\t\t\t\telse if(gradientType == 2)\n\t\t\t\t\t\t\t\twS *= (Pj + Pi - 2.0*pressMin)/dstimj2;//(press[j] + Pi - 2.0*pressMin)/dstimj2;\n\t\t\t\t\t\t\telse if(gradientType == 3) {\n\t\t\t\t\t\t\t\tdouble nj = pndi[j];\n\t\t\t\t\t\t\t\tif(ni > 1.0e-8 && nj > 1.0e-8)\n\t\t\t\t\t\t\t\t\twS *= (ni*Pj/nj + nj*Pi/ni)/dstimj2;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\taccX += v0imj*wS;\taccY += v1imj*wS;\taccZ += v2imj*wS;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\t\tif(j == -1) break;\n\t\t\t\t}\n\t\t\t}}}\n\t\t\t// Add \"i\" contribution (\"i\" is a neighbor of \"mirror i\")\n\t\t\tdouble v0imi, v1imi, v2imi, dstimi2;\n\t\t\tsqrDistBetweenParticles(i, posMirrorXi, posMirrorYi, posMirrorZi, v0imi, v1imi, v2imi, dstimi2);\n\t\t  \t\n\t\t\tif(dstimi2 < reS2) {\n\t\t\t\tdouble dst = sqrt(dstimi2);\n\t\t\t\tdouble wS = weightGradient(dst, reS, weightType);\n\n\t\t\t\t// Taylor pressure Pj\n\t\t\t\tdouble Pj;\n\t//\t\t\tPj = Pi + RHO[i]*(Rai[0]*v0 + Rai[1]*v1 + Rai[2]*v2);\n\t\t\t\tPj = Pi;\n\n\t\t\t\tif(gradientType == 0)\n\t\t\t\t\twS *= (Pj - pressMin)/dstimi2;//(Pi - pressMin)/dstimi2\n\t\t\t\telse if(gradientType == 1)\n\t\t\t\t\twS *= (Pj + Pi)/dstimi2;//(Pi + Pi)/dstimi2\n\t\t\t\telse if(gradientType == 2)\n\t\t\t\t\twS *= (Pj + Pi - 2.0*pressMin)/dstimi2;//(Pi + Pi - 2.0*pressMin)/dstimi2\n\t\t\t\telse if(gradientType == 3) {\n\t\t\t\t\tdouble nj = pndi[i];\n\t\t\t\t\tif(ni > 1.0e-8 && nj > 1.0e-8)\n\t\t\t\t\t\twS *= (ni*Pj/nj + nj*Pi/ni)/dstimi2;\n\t\t\t\t}\n\t\t\t\taccX += v0imi*wS;\taccY += v1imi*wS;\taccZ += v2imi*wS;\n\t\t  \t}\n\n\t\t\t// Repulsive force\n\t\t\tdouble rpsForce[3];\n\t\t\trpsForce[0]=rpsForce[1]=rpsForce[2] = 0.0;\n\n\t\t\tif(repulsiveForceType == repForceType::HARADA) {\n\t\t\t\t// Parallel analysis system for free-surface flow using MPS method with explicitly represented polygon wall boundary model\n\t\t\t\t// https://doi.org/10.1007/s40571-019-00269-6\n\t\t\t\tif(normaliwSqrt < reRepulsiveForce && normaliwSqrt > 1.0e-8) {\n\t\t\t\t\tdouble wijRep = RHO[i]/(timeStep*timeStep)*(reRepulsiveForce-normaliwSqrt);\n\t\t\t\t\trpsForce[0] = - wijRep*normaliw[0];\n\t\t\t\t\trpsForce[1] = - wijRep*normaliw[1];\n\t\t\t\t\trpsForce[2] = - wijRep*normaliw[2];\n\t\t\t\t\t//if(i == 6) {\n\t\t\t\t\t\t//printf(\"x:%lf y:%lf z:%lf x:%lf y:%lf z:%lf\\n\", pos[i*3],pos[i*3+1],pos[i*3+2],mirrorParticlePos[i*3],mirrorParticlePos[i*3+1],mirrorParticlePos[i*3+2]);\n\t\t\t\t\t\t//printf(\"nx:%lf ny: %lf nz: %lf nN:%lf\\n\", normaliw[0],normaliw[1],normaliw[2],normaliwSqrt);\n\t\t\t\t\t\t//printf(\"Fx:%lf Fy:%lf Fz:%lf\\n\", rpsForce[0],rpsForce[1],rpsForce[2]);\n\t\t\t\t\t//}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(repulsiveForceType == repForceType::MITSUME) {\n\t\t\t\t// Explicitly represented polygon wall boundary model for the explicit MPS method\n\t\t\t\t// https://doi.org/10.1007/s40571-015-0037-8\n\t\t\t\tif(normaliwSqrt < reRepulsiveForce && normaliwSqrt > 1.0e-8) {\n\t\t\t\t\tdouble wijRep = repForceCoefMitsume*weightGradient(normaliwSqrt, reRepulsiveForce, weightType);\n\t\t\t\t\trpsForce[0] = - wijRep*normaliw[0];\n\t\t\t\t\trpsForce[1] = - wijRep*normaliw[1];\n\t\t\t\t\trpsForce[2] = - wijRep*normaliw[2];\n\t\t\t\t\t//if(i == 6) {\n\t\t\t\t\t\t//printf(\"x:%lf y:%lf z:%lf x:%lf y:%lf z:%lf\\n\", pos[i*3],pos[i*3+1],pos[i*3+2],mirrorParticlePos[i*3],mirrorParticlePos[i*3+1],mirrorParticlePos[i*3+2]);\n\t\t\t\t\t\t//printf(\"nx:%lf ny: %lf nz: %lf nN:%lf\\n\", normaliw[0],normaliw[1],normaliw[2],normaliwSqrt);\n\t\t\t\t\t\t//printf(\"Fx:%lf Fy:%lf Fz:%lf\\n\", rpsForce[0],rpsForce[1],rpsForce[2]);\n\t\t\t\t\t//}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(repulsiveForceType == repForceType::LENNARD_JONES) {\n\t\t\t\t// Simulating Free Surface Flows with SPH\n\t\t\t\t// https://doi.org/10.1006/jcph.1994.1034\n\t\t\t\tif(normaliwSqrt < reRepulsiveForce && normaliwSqrt > 1.0e-8) {\n\t\t\t\t\tdouble R1 = (reRepulsiveForce/normaliwSqrt)*(reRepulsiveForce/normaliwSqrt);\n\t\t\t\t\tdouble R2 = R1*R1;\n\t\t\t\t\tdouble wijRep = (repForceCoefLennardJones*velMax2/normaliwSqrt)*(R2-R1)*RHO[i];\n\t\t\t\t\trpsForce[0] = - wijRep*normaliw[0];\n\t\t\t\t\trpsForce[1] = - wijRep*normaliw[1];\n\t\t\t\t\trpsForce[2] = - wijRep*normaliw[2];\n\t\t\t\t}\n\t\t\t}\n\t\t  \telse {\n\t\t\t\t// SPH particle boundary forces for arbitrary boundaries \n\t\t\t\t// https://doi.org/10.1016/j.cpc.2009.05.008\n\t\t\t\tif(normaliwSqrt < reRepulsiveForce && normaliwSqrt > 1.0e-8) {\n\t\t\t\t\tdouble W1 = (1.0+3.0*0.5*normaliwSqrt/(reRepulsiveForce));\n\t\t\t\t\tdouble W2 = (1.0-normaliwSqrt/(reRepulsiveForce))*(1.0-normaliwSqrt/(reRepulsiveForce))*(1.0-normaliwSqrt/(reRepulsiveForce));\n\t\t\t\t\tdouble wijRep = (repForceCoefMonaghanKajtar*velMax2/(normaliwSqrt - 0.0*partDist))*(1.0/8.0)*(W1)*(W2)*RHO[i];\n\t\t\t\t\trpsForce[0] = - wijRep*normaliw[0];\n\t\t\t\t\trpsForce[1] = - wijRep*normaliw[1];\n\t\t\t\t\trpsForce[2] = - wijRep*normaliw[2];\n\t\t\t\t}\n\t\t  \t}\n\t\t\t// coeffPressGrad is a negative cte (-dim/noGrad)\n\t\t\t// Original\n\t//\t\tacc[i*3  ] += ((1.0-relaxPress)*(Rref_i[0]*accX + Rref_i[1]*accY + Rref_i[2]*accZ)*coeffPressGrad - rpsForce[0])*invDns[partType::FLUID];\n\t//\t\tacc[i*3+1] += ((1.0-relaxPress)*(Rref_i[3]*accX + Rref_i[4]*accY + Rref_i[5]*accZ)*coeffPressGrad - rpsForce[1])*invDns[partType::FLUID];\n\t//\t\tacc[i*3+2] += ((1.0-relaxPress)*(Rref_i[6]*accX + Rref_i[7]*accY + Rref_i[8]*accZ)*coeffPressGrad - rpsForce[2])*invDns[partType::FLUID];\n\t\t\t// Modified\n\t\t\tacc[i*3  ] += ((1.0-relaxPress)*(Rref_i[0]*accX + Rref_i[1]*accY + Rref_i[2]*accZ)*coeffPressGrad - rpsForce[0])/RHO[i];\n\t\t\tacc[i*3+1] += ((1.0-relaxPress)*(Rref_i[3]*accX + Rref_i[4]*accY + Rref_i[5]*accZ)*coeffPressGrad - rpsForce[1])/RHO[i];\n\t\t\tacc[i*3+2] += ((1.0-relaxPress)*(Rref_i[6]*accX + Rref_i[7]*accY + Rref_i[8]*accZ)*coeffPressGrad - rpsForce[2])/RHO[i];\n\n\t\t\t//Fwall[i*3  ] =  (Rref_i[0]*accX + Rref_i[1]*accY + Rref_i[2]*accZ)*invDns[partType::FLUID]*coeffPressGrad - rpsForce[0]*invDns[partType::FLUID];\n\t\t\t//Fwall[i*3+1] =  (Rref_i[3]*accX + Rref_i[4]*accY + Rref_i[5]*accZ)*invDns[partType::FLUID]*coeffPressGrad - rpsForce[1]*invDns[partType::FLUID];\n\t\t\t//Fwall[i*3+2] =  (Rref_i[6]*accX + Rref_i[7]*accY + Rref_i[8]*accZ)*invDns[partType::FLUID]*coeffPressGrad - rpsForce[2]*invDns[partType::FLUID];\n\t\t}\n\t}\n}\n\n// Update velocity and position\nvoid MpsParticle::updateVelocityPosition1st() {\n#pragma omp parallel for\n\tfor(int i=0; i<numParticles; i++) {\n\t\tif(particleType[i] == fluid) {\n\t\t\tvel[i*3  ] += acc[i*3  ]*timeStep;\tvel[i*3+1] += acc[i*3+1]*timeStep;\tvel[i*3+2] += acc[i*3+2]*timeStep;\n\t\t\t//if(particleType[i] == fluid) {\n\t\t\tpos[i*3  ] += vel[i*3  ]*timeStep;\tpos[i*3+1] += vel[i*3+1]*timeStep;\tpos[i*3+2] += vel[i*3+2]*timeStep;\n\t\t\t//}\n\t\t}\n\t\tacc[i*3]=acc[i*3+1]=acc[i*3+2]=0.0;\n\t\tdvelCollision[i*3]=dvelCollision[i*3+1]=dvelCollision[i*3+2]=0.0;\n\t\twallParticleForce1[i*3]=wallParticleForce1[i*3+1]=wallParticleForce1[i*3+2]=0.0;\n\t\twallParticleForce2[i*3]=wallParticleForce2[i*3+1]=wallParticleForce2[i*3+2]=0.0;\n\t\tnpcdDeviation[i*3]=npcdDeviation[i*3+1]=npcdDeviation[i*3+2]=0.0;\n\t\tnumNeighWallContribution[i]=0;\n\t\tparticleNearWall[i]=false;\n\t\t// Set squared distance of particle to triangle mesh to ~infinite\n\t\tdistParticleWall2[i] = 10e8*partDist;\n\t\tnumNeighborsSurfaceParticles[i]=0.0;\n\n\t\tif(wallType == boundaryWallType::POLYGON) {\n\t\t\t// Set mirrored particle to ~infinite if wall particles are used\n\t\t\tmirrorParticlePos[i*3  ] = 10e8*partDist; mirrorParticlePos[i*3+1] = 10e8*partDist; mirrorParticlePos[i*3+2] = 10e8*partDist;\n\t\t}\n\t}\n}\n\n// Check collisions between particles\n// Step-by-step improvement of MPS method in simulating violent free-surface motions and impact-loads\n// https://doi.org/10.1016/j.cma.2010.12.001\nvoid MpsParticle::checkParticleCollisions() {\n#pragma omp parallel for schedule(dynamic,64)\n\tfor(int i=0; i<numParticles; i++) {\n\t\tif(particleType[i] == fluid) {\n\t//\t\tdouble mi = Dns[partType::FLUID];\n\t\t\tdouble mi;\n\t\t\tif(PTYPE[i] == 1) mi = DNS_FL1;\n\t\t\telse mi = DNS_FL2;\n\t\t\tdouble posXi = pos[i*3  ];double posYi = pos[i*3+1];double posZi = pos[i*3+2];\n\t\t\tdouble velXi = vel[i*3  ];double velYi = vel[i*3+1];double velZi = vel[i*3+2];\n\t\t\tdouble dVelXi = 0.0;double dVelYi = 0.0;double dVelZi = 0.0;\n\t\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\t\t\n\t\t\tint ix, iy, iz;\n\t\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\t\tint j = firstParticleInBucket[jb];\n\t\t\t\tif(j == -1) continue;\n\t\t\t\tdouble plx, ply, plz;\n\t\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\t\twhile(true) {\n\t\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\t\n\t\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\t\tif(dstij2 < distCollisionLimit2 && (dstij2 < dstimj2 || wallType == boundaryWallType::PARTICLE)) {\n\t\t\t\t\t\tif(j != i) {\n\t\t\t\t\t\t\tdouble fDT = (velXi-vel[j*3  ])*v0ij+(velYi-vel[j*3+1])*v1ij+(velZi-vel[j*3+2])*v2ij;\n\t\t\t\t\t\t\tif(fDT > 0.0) {\n\t\t\t\t\t\t\t\tdouble mj;\n\t\t\t\t\t\t\t\tif(particleType[j]==fluid)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tif(PTYPE[j] == 1) mj = DNS_FL1;\n\t\t\t\t\t\t\t\t\telse mj = DNS_FL2;\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\tmj = Dns[partType::WALL];\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tfDT *= restitutionCollision*mj/(mi+mj)/dstij2;\n\t\t\t\t\t\t\t\tif(particleType[j]==fluid)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tdVelXi -= v0ij*fDT;\t\tdVelYi -= v1ij*fDT;\t\tdVelZi -= v2ij*fDT;\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\tdVelXi -= 2.0*v0ij*fDT;\tdVelYi -= 2.0*v1ij*fDT;\tdVelZi -= 2.0*v2ij*fDT;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\tdouble fDT = (vel[j*3  ]-velXi)*v0+(vel[j*3+1]-velYi)*v1+(vel[j*3+2]-velZi)*v2;\n\t\t\t\t\t\t\tdouble mj;\n\t\t\t\t\t\t\tif(particleType[j]==fluid)\n\t\t\t\t\t\t\t\tmj = Dns[partType::FLUID];\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tmj = Dns[partType::WALL];\n\t\t\t\t\t\t\tfDT *= restitutionCollision*mj/(mi+mj)/dst2;\n\t\t\t\t\t\t\tvelXi2 += v0*fDT;\t\tvecYi2 += v1*fDT;\t\tvecZi2 += v2*fDT;\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\tj = nextParticleInSameBucket[j];\n\t\t\t\t\tif(j == -1) break;\n\t\t\t\t}\n\t\t\t}}}\n\n\t\t\tdvelCollision[i*3  ]=dVelXi;\tdvelCollision[i*3+1]=dVelYi;\tdvelCollision[i*3+2]=dVelZi;\n\t\t\t//accStar[i*3  ]=vel[i*3  ]+dVelXi;\taccStar[i*3+1]=vel[i*3+1]+dVelYi;\taccStar[i*3+2]=vel[i*3+2]+dVelZi;\n\t\t}\n\t}\n#pragma omp parallel for\n\tfor(int i=0; i<numParticles; i++) {\n\t\tif(particleType[i] == fluid) {\n\t\t\t// CHANGED !!!\n\t\t\t//pos[i*3  ]+=(acc[i*3  ]-vel[i*3  ])*timeStep; pos[i*3+1]+=(acc[i*3+1]-vel[i*3+1])*timeStep; pos[i*3+2]+=(acc[i*3+2]-vel[i*3+2])*timeStep;\n\t\t\tvel[i*3  ]+=dvelCollision[i*3  ];\tvel[i*3+1]+=dvelCollision[i*3+1];\tvel[i*3+2]+=dvelCollision[i*3+2];\n\t\t\t\n\t\t\t//Velk[i*3  ]=vel[i*3  ];\tVelk[i*3+1]=vel[i*3+1];\tVelk[i*3+2]=vel[i*3+2];\n\t\t\t//pos[i*3  ]=Posk[i*3  ]+vel[i*3  ]*timeStep; pos[i*3+1]=Posk[i*3+1]+vel[i*3+1]*timeStep; pos[i*3+2]=Posk[i*3+2]+vel[i*3+2]*timeStep;\n\t\t}\n\t\tdvelCollision[i*3  ]=0.0;\tdvelCollision[i*3+1]=0.0;\tdvelCollision[i*3+2]=0.0;\n\t}\n}\n\n// Check collisions between particles (Dynamic Particle Collision)\n// Enhanced weakly-compressible MPS method for violent free-surface flows: Role of particle regularization techniques\n// https://doi.org/10.1016/j.jcp.2021.110202\nvoid MpsParticle::checkDynamicParticleCollisions() {\n\t\n\tdouble Wij5 = 0.5*0.5*0.5*0.5*3.0;\n\t//double Wij5 = 0.5*0.5;\n\tdouble pmax = 0.0;\n\tdouble gravityMod = sqrt(gravityX*gravityX + gravityY*gravityY + gravityZ*gravityZ);\n\t\n\t// Compute maximum pressure on the walls\n#pragma omp parallel\n{\n\tdouble local_pmax = 0.0;\n#pragma omp for\n\tfor(int i=0; i<numParticles; i++) {\n\t\tif(particleType[i] == wall) {\n\t\t\tlocal_pmax = max(local_pmax, press[i]);\n\t\t}\n\t}\n#pragma omp critical\n\t{\n\t\tif (local_pmax > pmax)\n\t\t\tpmax = local_pmax;\n\t}\n}\n\t// Compute collision and repulsive terms and the dynamic coefficients\n#pragma omp parallel for schedule(dynamic,64)\n\tfor(int i=0; i<numParticles; i++) {\n\t\tif(particleType[i] == fluid) {\n\t//\t\tdouble mi = Dns[partType::FLUID];\n\t\t\tdouble mi;\n\t\t\tif(PTYPE[i] == 1) mi = DNS_FL1;\n\t\t\telse mi = DNS_FL2;\n\n\t\t\tdouble posXi = pos[i*3  ];double posYi = pos[i*3+1];double posZi = pos[i*3+2];\n\t\t\tdouble velXi = vel[i*3  ];double velYi = vel[i*3+1];double velZi = vel[i*3+2];\n\t\t\tdouble dVelXi = 0.0;double dVelYi = 0.0;double dVelZi = 0.0;\n\t\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\n\t\t\tint ix, iy, iz;\n\t\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\t\tint j = firstParticleInBucket[jb];\n\t\t\t\tif(j == -1) continue;\n\t\t\t\tdouble plx, ply, plz;\n\t\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\t\twhile(true) {\n\t\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\t\n\t\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\t\tif(dstij2 < partDist*partDist && (dstij2 < dstimj2 || wallType == boundaryWallType::PARTICLE)) {\n\t\t\t\t\t\tif(j != i) {\n\t\t\t\t\t\t\tdouble mj;\n\t\t\t\t\t\t\tif(particleType[j]==fluid)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif(PTYPE[j] == 1) mj = DNS_FL1;\n\t\t\t\t\t\t\t\telse mj = DNS_FL2;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmj = Dns[partType::WALL];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tdouble dst = sqrt(dstij2);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// inter-particle distance\n\t\t\t\t\t\t\tdouble Wij = 0.0;\n\t\t\t\t\t\t\tif(dst > 1.0e-8 && dst < partDist)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tdouble w1 = 1.0 - dst*invPartDist;\n\t\t\t\t\t\t\t\tdouble w2 = 4.0*dst*invPartDist + 1.0;\n\t\t\t\t\t\t\t\tWij = w1*w1*w1*w1*w2;\n\t\t\t\t\t\t\t\t//Wij = w1*w1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tdouble chi = sqrt(Wij/Wij5);\n\t\t\t\t\t\t\tdouble kappa = 0.0;\n\t\t\t\t\t\t\tif(dst < 0.5*partDist)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkappa = 1.0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if(dst >= 0.5*partDist && dst < partDist)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkappa = chi;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tdouble fDT = (velXi-vel[j*3  ])*v0ij+(velYi-vel[j*3+1])*v1ij+(velZi-vel[j*3+2])*v2ij;\n\t\t\t\t\t\t\tif(fDT > 0.0) {\n\t\t\t\t\t\t\t\tfDT *= kappa*2.0*mj/(mi+mj)/dstij2;\n\t\t\t\t\t\t\t\t//fDT *= restitutionCollision*mj/(mi+mj)/dstij2;\n\t\t\t\t\t\t\t\tif(particleType[j]==fluid)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tdVelXi -= v0ij*fDT;\t\tdVelYi -= v1ij*fDT;\t\tdVelZi -= v2ij*fDT;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse //if(particleBC[i] == surface)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tdVelXi -= 2.0*v0ij*fDT;\t\tdVelYi -= 2.0*v1ij*fDT;\t\tdVelZi -= 2.0*v2ij*fDT;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t// Dynamic background pressure\n\t\t\t\t\t\t\t\tdouble pmax = 2.0/3.0*RHO[i]*gravityMod*0.2;\n\t\t\t\t\t\t\t\tdouble pmin = RHO[i]*gravityMod*partDist;\n\n\t\t\t\t\t\t\t\tdouble ptil = max(min(lambdaCollision*fabs(press[i]+press[j]), lambdaCollision*pmax), pmin);\n\t\t\t\t\t\t\t\tdouble pb = ptil*chi;\n\t\t\t\t\t\t\t\tdouble rep = timeStep/mi*chi*pb/dstij2;\n\t\t\t\t\t\t\t\tif(particleType[j]==fluid)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tdVelXi -= v0ij*rep;\t\tdVelYi -= v1ij*rep;\t\tdVelZi -= v2ij*rep;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse //if(particleBC[i] == surface)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tdVelXi -= 2.0*v0ij*rep;\t\tdVelYi -= 2.0*v1ij*rep;\t\tdVelZi -= 2.0*v2ij*rep;\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\tj = nextParticleInSameBucket[j];\n\t\t\t\t\tif(j == -1) break;\n\t\t\t\t}\n\t\t\t}}}\n\n\t\t\tdvelCollision[i*3  ]=dVelXi;\tdvelCollision[i*3+1]=dVelYi;\tdvelCollision[i*3+2]=dVelZi;\n\t\t}\n\t}\n\t// Update velocity and position\n#pragma omp parallel for\n\tfor(int i=0; i<numParticles; i++) {\n\t\tif(particleType[i] == fluid) {\n\t\t\t\n\t\t\tvel[i*3  ]+=dvelCollision[i*3  ];\tvel[i*3+1]+=dvelCollision[i*3+1];\tvel[i*3+2]+=dvelCollision[i*3+2];\n\t\t\tpos[i*3  ]+=dvelCollision[i*3  ]*timeStep; pos[i*3+1]+=dvelCollision[i*3+1]*timeStep; pos[i*3+2]+=dvelCollision[i*3+2]*timeStep;\n\t\t\t/*\n\t\t\tdouble drNew[3], drMod, drMin, duNew[3];\n\t\t\tduNew[0] = dvelCollision[i*3  ];\n\t\t\tduNew[1] = dvelCollision[i*3+1];\n\t\t\tduNew[2] = dvelCollision[i*3+2];\n\t\t\tdrNew[0] = dvelCollision[i*3  ]*timeStep;\n\t\t\tdrNew[1] = dvelCollision[i*3+1]*timeStep;\n\t\t\tdrNew[2] = dvelCollision[i*3+2]*timeStep;\n\t\t\tdrMod = (drNew[0]*drNew[0] + drNew[1]*drNew[1] + drNew[2]*drNew[2]);\n\t\t\tdrMin = min(0.1*partDist, drMod);\n\t\t\tif(drMin > 1.0e-8)\n\t\t\t{\n\t\t\t\tpos[i*3  ]+=drMin*drNew[0]/drMod;\n\t\t\t\tpos[i*3+1]+=drMin*drNew[1]/drMod;\n\t\t\t\tpos[i*3+2]+=drMin*drNew[2]/drMod;\n\t\t\t\tvel[i*3  ]+=drMin*duNew[0]/drMod;\n\t\t\t\tvel[i*3+1]+=drMin*duNew[1]/drMod;\n\t\t\t\tvel[i*3+2]+=drMin*duNew[2]/drMod;\n\t\t\t}\n\t\t\t*/\n\t\t}\n\t\tdvelCollision[i*3  ]=0.0;\tdvelCollision[i*3+1]=0.0;\tdvelCollision[i*3+2]=0.0;\n\t}\n}\n\n// Set force on wall to zero\n//void MpsParticle::WallZeroForce_omp(int nNodes, int nSolids, solid_fem * &solid) {\nvoid MpsParticle::setWallForceZero(const int nNodes, double *nodeforceX, double *nodeforceY, double *nodeforceZ) {\n#pragma omp parallel for\n\tfor(int i=0; i<numParticles; i++) {\n\t\tif(particleType[i] == fluid) {\n\t\t\tforceWall[i*3]=forceWall[i*3+1]=forceWall[i*3+2]=0.0;\n\t\t}\n\t}\n#pragma omp parallel for\n\tfor(int nn=0;nn<nNodes;nn++)\n\t\tnodeforceX[nn]=nodeforceY[nn]=nodeforceZ[nn]=0.0;\n/*\tfor(int ss=0; ss<nSolids; ss++) {\n//#pragma omp parallel for\n\t\tfor(int ns=0; ns<solid[ss].nNodes; ns++) {\n\t\t\tsolid[ss].node[ns].forceX = 0.0;\n\t\t\tsolid[ss].node[ns].forceY = 0.0;\n\t\t\tsolid[ss].node[ns].forceZ = 0.0;\n\t\t}}*/\n}\n\n// Free-surface particles. NPCD (Polygon wall)\nvoid MpsParticle::calcWallNPCD() {\n\t//int nPartNearMesh = partNearMesh.size();\n\t//printf(\" Mesh %d \\n\", nPartNearMesh);\n\t// Loop only for particles near mesh\n#pragma omp parallel for schedule(dynamic,64)\n\t//for(int im=0;im<nPartNearMesh;im++) {\n\t//int i = partNearMesh[im];\n\tfor(int i=0; i<numParticles; i++) {\n\t\tif(particleType[i] == fluid && particleNearWall[i] == true) {\n\t\t\tdouble npcdDeviationXi = 0.0;\tdouble npcdDeviationYi = 0.0;\tdouble npcdDeviationZi = 0.0;\n\t\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\t\t// Wall gradient Mitsume`s model\n\t\t\tdouble Rref_i[9], normaliw[3], normaliwSqrt;\n\t\t\t// normal fluid-wall particle = 0.5*(normal fluid-mirror particle)\n\t\t\tnormaliw[0] = 0.5*(posXi - posMirrorXi); normaliw[1] = 0.5*(posYi - posMirrorYi); normaliw[2] = 0.5*(posZi - posMirrorZi);\n\t\t\tnormaliwSqrt = sqrt(normaliw[0]*normaliw[0] + normaliw[1]*normaliw[1] + normaliw[2]*normaliw[2]);\n\n\t\t\tif(normaliwSqrt > 1.0e-8) {\n\t\t\t\tnormaliw[0] = normaliw[0]/normaliwSqrt;\n\t\t\t\tnormaliw[1] = normaliw[1]/normaliwSqrt;\n\t\t\t\tnormaliw[2] = normaliw[2]/normaliwSqrt;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tnormaliw[0] = 0;\n\t\t\t\tnormaliw[1] = 0;\n\t\t\t\tnormaliw[2] = 0;\n\t\t\t}\n\n\t\t    // Transformation matrix Rref_i = I - 2.0*normal_iwall*normal_iwall\n\t\t\tRref_i[0] = 1.0 - 2.0*normaliw[0]*normaliw[0]; Rref_i[1] = 0.0 - 2.0*normaliw[0]*normaliw[1]; Rref_i[2] = 0.0 - 2.0*normaliw[0]*normaliw[2];\n\t\t\tRref_i[3] = 0.0 - 2.0*normaliw[1]*normaliw[0]; Rref_i[4] = 1.0 - 2.0*normaliw[1]*normaliw[1]; Rref_i[5] = 0.0 - 2.0*normaliw[1]*normaliw[2];\n\t\t\tRref_i[6] = 0.0 - 2.0*normaliw[2]*normaliw[0]; Rref_i[7] = 0.0 - 2.0*normaliw[2]*normaliw[1]; Rref_i[8] = 1.0 - 2.0*normaliw[2]*normaliw[2];\n\n\t\t\tint ix, iy, iz;\n\t\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\t\tint j = firstParticleInBucket[jb];\n\t\t\t\tif(j == -1) continue;\n\t\t\t\tdouble plx, ply, plz;\n\t\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\t\twhile(true) {\n\t\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\t\n\t\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t\t// If j is inside the neighborhood of i and im (intersection) and \n\t\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\t\tif(dstij2 < reS2 && dstimj2 < reS2 && dstij2 < dstimj2) {\n\t\t\t\t\t\tif(j != i) {\n\t\t\t\t\t\t\tdouble dst = sqrt(dstimj2);\n\t\t\t\t\t\t\tdouble wS = weightGradient(dst, reS, weightType);\n\t\t\t\t\t\t\tnpcdDeviationXi += v0imj*wS;\n\t\t\t\t\t\t\tnpcdDeviationYi += v1imj*wS;\n\t\t\t\t\t\t\tnpcdDeviationZi += v2imj*wS;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\t\tif(j == -1) break;\n\t\t\t\t}\n\n\t\t\t}}}\n\t\t\t// Add \"i\" contribution (\"i\" is a neighbor of \"mirror i\")\n\t\t\tdouble v0imi, v1imi, v2imi, dstimi2;\n\t\t\tsqrDistBetweenParticles(i, posMirrorXi, posMirrorYi, posMirrorZi, v0imi, v1imi, v2imi, dstimi2);\n\t\t\t\n\t\t\tif(dstimi2 < reS2) {\n\t\t\t\tdouble dst = sqrt(dstimi2);\n\t\t\t\tdouble wS = weightGradient(dst, reS, weightType);\n\t\t\t\tnpcdDeviationXi += v0imi*wS;\n\t\t\t\tnpcdDeviationYi += v1imi*wS;\n\t\t\t\tnpcdDeviationZi += v2imi*wS;\n\t\t\t}\n\t\t\tnpcdDeviation[i*3  ] += Rref_i[0]*npcdDeviationXi + Rref_i[1]*npcdDeviationYi + Rref_i[2]*npcdDeviationZi;\n\t\t\tnpcdDeviation[i*3+1] += Rref_i[3]*npcdDeviationXi + Rref_i[4]*npcdDeviationYi + Rref_i[5]*npcdDeviationZi;\n\t\t\tnpcdDeviation[i*3+2] += Rref_i[6]*npcdDeviationXi + Rref_i[7]*npcdDeviationYi + Rref_i[8]*npcdDeviationZi;\n\t\t}\n\t}\n}\n\n// Compute PND, number of neighbors and NPCD\nvoid MpsParticle::calcPndnNeighNPCD() {\n#pragma omp parallel for schedule(dynamic,64)\n\tfor(int i=0; i<numParticles; i++) {\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\tdouble ni = 0.0; double wSum = 0.0;\n\t\tnumNeigh[i] = 0;\n\t\t// Add Number of neighbors due Wall polygon\n\t\tnumNeigh[i] += numNeighWallContribution[i];\n\t\t\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reL2 && (dstij2 < dstimj2 || wallType == boundaryWallType::PARTICLE)) {\n\t\t\t\t\tif(j != i) {\n\t\t\t\t\t\tnumNeigh[i] += 1;\n\t\t\t\t\t\t//double dst = sqrt(dst2);\n\t\t\t\t\t\t//double wL = weight(dst, reL*invPartDist, weightType);\n\t\t\t\t\t\t//npcdDeviation[i*3  ] += v0*wL*invPartDist;\n\t\t\t\t\t\t//npcdDeviation[i*3+1] += v1*wL*invPartDist;\n\t\t\t\t\t\t//npcdDeviation[i*3+2] += v2*wL*invPartDist;\n\t\t\t\t\t\t//wSum += wL;\n\t\t\t\t\t\tif(dstij2 < reS2) {\n\t\t\t\t\t\t\tdouble dst = sqrt(dstij2);\n\t\t\t\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\t\t\t\tni += wS;\n\t\t\t\t\t\t\t//dst = dst*invPartDist;\n\t\t\t\t\t\t\t//wS = weight(dst, reS*invPartDist, weightType);\n\t\t\t\t\t\t\t//npcdDeviation[i*3  ] += v0ij*wS*invPartDist;\n\t\t\t\t\t\t\t//npcdDeviation[i*3+1] += v1ij*wS*invPartDist;\n\t\t\t\t\t\t\t//npcdDeviation[i*3+2] += v2ij*wS*invPartDist;\n\t\t\t\t\t\t\tnpcdDeviation[i*3  ] += v0ij*wS;\n\t\t\t\t\t\t\tnpcdDeviation[i*3+1] += v1ij*wS;\n\t\t\t\t\t\t\tnpcdDeviation[i*3+2] += v2ij*wS;\n\t\t\t\t\t\t\twSum += wS;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\n//\t\tdouble mi;\n//\t\tif(PTYPE[i] == 1) mi = DNS_FL1;\n//\t\telse mi = DNS_FL2;\n\t\t//if(particleType[i]==fluid)\n\t\t//\tmi = Dns[partType::FLUID];\n\t\t//else\n\t\t//\tmi = Dns[partType::WALL];\n\n\t\tif(pndType == calcPNDType::SUM_WIJ || pndType == calcPNDType::MEAN_SUM_WIJ) {\n//\t\tif(pndType == calcPNDType::SUM_WIJ) {\n\t\t\t// PND at initial of step k\n\t\t\tpndki[i] = pndi[i];\n\t\t\t// New PND due particles and Wall polygon\n\t\t\tpndi[i] = ni + pndWallContribution[i];\n\t\t}\n\n//\t\tif(particleType[i] == wall) {\n\t\t\t// PND due particles and Wall polygon\n//\t\t\tpndi[i] = ni + pndWallContribution[i];\n//\t\t\tif(pndi[i] < pndSmallZero)\n//\t\t\t\tpndi[i] = pndSmallZero;\n\n//\t\t\t\tpndi[i] = pndSmallZero*pow((press[i]*gamma/(mi*coeffPressWCMPS)+1),gamma);\n//\t\t}\n\n\t\t// Add PND due Wall polygon\n\t\tpndSmall[i] = ni + pndWallContribution[i];\n\t\t// Prevent pndSmall[i] = 0\n//\t\tif(numNeigh[i]>1) {\n\t\tif(wSum > 1.0e-8) {\n\t\t\tnpcdDeviation[i*3  ] /= pndSmall[i];\n\t\t\tnpcdDeviation[i*3+1] /= pndSmall[i];\n\t\t\tnpcdDeviation[i*3+2] /= pndSmall[i];\n\t\t\t//npcdDeviation[i*3  ] /= wSum;\n\t\t\t//npcdDeviation[i*3+1] /= wSum;\n\t\t\t//npcdDeviation[i*3+2] /= wSum;\n\t\t}\n\n\t\tnpcdDeviation2[i] = npcdDeviation[i*3]*npcdDeviation[i*3]+npcdDeviation[i*3+1]*npcdDeviation[i*3+1]+npcdDeviation[i*3+2]*npcdDeviation[i*3+2];\n\n\t\t//deviationDotPolygonNormal[i] = npcdDeviation[i*3]*polygonNormal[i*3]+npcdDeviation[i*3+1]*polygonNormal[i*3+1]+npcdDeviation[i*3+2]*polygonNormal[i*3+2];\n\t\tif(npcdDeviation[i*3]*polygonNormal[i*3]+npcdDeviation[i*3+1]*polygonNormal[i*3+1]+npcdDeviation[i*3+2]*polygonNormal[i*3+2]< 0.0)\n\t\t\tdeviationDotPolygonNormal[i] = 1;\n\t\telse\n\t\t\tdeviationDotPolygonNormal[i] = -1;\n\t\t\n\t\t// First check based on particle number density\n//\t\tif(pndSmall[i] < pndThreshold*pndSmallZero)\n//\t\t\tparticleBC[i] = surface;\n//\t\telse\n//\t\t\tparticleBC[i] = inner;\n\n\t\t// Boundary particle verification based on relative distance and weight (NPCD)\n//\t\tif(particleBC[i] == surface) {\n//\t\t\tif(numNeigh[i] > 4 && npcdDeviation2[i] < delta2)\n//\t\t\t{\n//\t\t\t\tparticleBC[i] = inner;\n\t\t\t\t//printf(\" inner %d \\n\", i);\n//\t\t\t}\n//\t\t}\n\n//\t\tif(pndSmall[i] < pndThreshold*pndSmallZero && numNeigh[i] < neighThreshold*numNeighZero)\n//\t\t\tparticleBC[i] = surface;\n//\t\telse\n//\t\t\tparticleBC[i] = inner;\n\t}\n}\n\n// Diffusive term of density/PND (pndType = calcPNDType::DIFFUSIVE)\n// An enhanced weakly-compressible MPS method for free-surface flows\n// https://doi.org/10.1016/j.cma.2019.112771\nvoid MpsParticle::calcPndDiffusiveTerm() {\n\t// coeffViscMultiphase = 2.0*dim/(pndLargeZero*lambdaZero);\n\tdouble C1 = diffusiveCoef*timeStep*soundSpeed*soundSpeed*coeffViscMultiphase/(pndLargeZero);\n\tdouble C2 = diffusiveCoef*partDist*soundSpeed*coeffViscMultiphase/(pndLargeZero);\n#pragma omp parallel for schedule(dynamic,64)\n\tfor(int i=0; i<numParticles; i++) {\n//\tif(particleType[i] == fluid) {\n\t\tdouble Di = 0.0; double DivV = 0.0; double flagDi = 1.0; double pndAux = 0.0;\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble velXi = vel[i*3  ];\tdouble velYi = vel[i*3+1];\tdouble velZi = vel[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\tdouble MC[9];\n\t\tMC[0] = correcMatrixRow1[i*3];\tMC[1] = correcMatrixRow1[i*3+1];\tMC[2] = correcMatrixRow1[i*3+2];\n\t\tMC[3] = correcMatrixRow2[i*3];\tMC[4] = correcMatrixRow2[i*3+1];\tMC[5] = correcMatrixRow2[i*3+2];\n\t\tMC[6] = correcMatrixRow3[i*3];\tMC[7] = correcMatrixRow3[i*3+1];\tMC[8] = correcMatrixRow3[i*3+2];\n\n\t\tdouble ni = pndi[i];\n\t\tif(ni < 1.0e-8) continue;\n\t\tdouble Pi = press[i];\n\t\t\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reL2 && (dstij2 < dstimj2 || wallType == boundaryWallType::PARTICLE)) {\n\t\t\t\t\tif(j != i) {\n\t//\t\t\t\tif(j != i && particleType[j] == fluid) {\n\t\t\t\t\t\tdouble dst = sqrt(dstij2);\n\t\t\t\t\t\tdouble wL = weight(dst, reL, weightType);\n\t\t\t\t\t\tdouble nj = pndi[j];\n\t\t\t\t\t\tif(particleType[i] == fluid && particleType[j] == fluid) {\n\t\t\t\t\t\t//if(particleType[i] == inner) {\n\t//\t\t\t\t\tif(particleType[i] == fluid && particleType[j] == fluid && particleBC[i] == inner) {\n\t\t\t\t\t\t\t// coeffViscMultiphase = 2.0*dim/(pndLargeZero*lambdaZero);\n\t//\t\t\t\t\t\tdouble pgh = RHO[i]*(gravityX*v0+gravityY*v1+gravityZ*v2);\n\t//\t\t\t\t\t\tdouble CB = RHO[i]*soundSpeed*soundSpeed/gamma;\n\t//\t\t\t\t\t\tdouble nijH = pndSmallZero*(pow((pgh+1.0)/CB,1.0/gamma)-1.0);\n\t//\t\t\t\t\t\tdouble nijH = pndSmallZero*(pow((pgh)/CB+1.0,1.0/gamma)-1.0);\n\t//\n\t\t\t\t\t\t//\tpow( ( pgh + 1.0 ) / CB - 1.0 , 1.0  )\n\n\t\t\t\t\t\t\t//double CB = soundSpeed*soundSpeed*RHO[i];\n\t\t\t\t\t\t\t//double nijH = pndSmallZero*((PijH+1.0)/CB-1);\n\t//\t\t\t\t\t\tif(isnan(nijH) == 0)\n\t//\t\t\t\t\t\t\tDi += C1*(nj - ni - nijH)*wL;\n\t//\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t////////Di += C1*(nj - ni)*wL;\n\t\t\t\t\t\t\t//if(isnan(nijH) == 1)\n\t\t\t\t\t\t\t//if(i == 200)\n\t\t\t\t\t\t\t//\tprintf(\" pgh %e CB %e ni %e nj %e nijH %e res %e \\n\", pgh, CB, ni, nj, nijH, pndSmallZero*(pow((pgh+1)/CB,1/gamma)-1));\n\t\t\t\t\t\t\t// PND\n\t//\t\t\t\t\t\tDi += C1*(nj-ni)*wL;\n\t\t\t\t\t\t\t//Di += C2*(nj-ni)*wL;\n\t\t\t\t\t\t\t// Pressure\n\t\t\t\t\t\t\t// Delta Voronoi smoothed particle hydrodynamics, δ-VSPH\n\t\t\t\t\t\t\t// https://doi.org/10.1016/j.jcp.2019.109000\n\t\t\t\t\t\t\tdouble pgh = -2.0*(RHO[i]*RHO[j]/(RHO[i]+RHO[j]))*(gravityX*v0ij+gravityY*v1ij+gravityZ*v2ij);\n\t\t\t\t\t\t\tdouble Pj = press[j];\n\t\t\t\t\t\t\tDi += timeStep/RHO[i]*coeffViscMultiphase*(Pj-Pi-pgh)*wL;\n\t\t\t\t\t\t\t//Di += (partDist/soundSpeed)/RHO[i]*coeffViscMultiphase*(Pj-Pi+pgh)*wL;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//else\n\t\t\t\t\t\t//\tflagDi = 0.0;\n\t\t\t\t\t\tif(dstij2 < reS2) {\n\t\t\t\t\t\t\tdouble vijx = vel[j*3  ]-velXi;\n\t\t\t\t\t\t\tdouble vijy = vel[j*3+1]-velYi;\n\t\t\t\t\t\t\tdouble vijz = vel[j*3+2]-velZi;\n\t\t\t\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\t\t\t\t//if(ni > 1.0e-8)\n\t\t\t\t\t\t\t//{\n\t\t\t\t\t\t\t//\tDivV += (dim/pndSmallZero)*(nj/ni)*(vijx*v0ij+vijy*v1ij+vijz*v2ij)*wS/dstij2;\n\t\t\t\t\t\t\t//}\n\t\t\t\t\t\t\tif(gradientCorrection == false) {\n\t\t\t\t\t\t\t\tif(ni > 1.0e-8) {\n\t\t\t\t\t\t\t\t\tDivV += (dim/pndSmallZero)*(pndi[j]/ni)*(vijx*v0ij+vijy*v1ij+vijz*v2ij)*wS/dstij2;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tdouble v0ijC = (v0ij*MC[0] + v1ij*MC[1] + v2ij*MC[2]);\n\t\t\t\t\t\t\t\tdouble v1ijC = (v0ij*MC[3] + v1ij*MC[4] + v2ij*MC[5]);\n\t\t\t\t\t\t\t\tdouble v2ijC = (v0ij*MC[6] + v1ij*MC[7] + v2ij*MC[8]);\n\t\t\t\t\t\t\t\tDivV += (dim/pndSmallZero)*(vijx*v0ijC+vijy*v1ijC+vijz*v2ijC)*wS/dstij2;\n\t\t\t\t\t\t\t}\n\n\t//\t\t\t\t\t\tM1[0][0] += (dim/pndSmallZero)*(nj/ni)*(v0*vijx)*wS/dst2; M1[0][1] += (dim/pndSmallZero)*(nj/ni)*(v0*vijy)*wS/dst2; M1[0][2] += (dim/pndSmallZero)*(nj/ni)*(v0*vijz)*wS/dst2;\n\t//\t\t\t\t\t\tM1[1][0] += (dim/pndSmallZero)*(nj/ni)*(v1*vijx)*wS/dst2; M1[1][1] += (dim/pndSmallZero)*(nj/ni)*(v1*vijy)*wS/dst2; M1[1][2] += (dim/pndSmallZero)*(nj/ni)*(v1*vijz)*wS/dst2;\n\t//\t\t\t\t\t\tM1[2][0] += (dim/pndSmallZero)*(nj/ni)*(v2*vijx)*wS/dst2; M1[2][1] += (dim/pndSmallZero)*(nj/ni)*(v2*vijy)*wS/dst2; M1[2][2] += (dim/pndSmallZero)*(nj/ni)*(v2*vijz)*wS/dst2;\n\n\t//\t\t\t\t\t\tif(particleType[i] == wall)\n\t//\t\t\t\t\t\tif(particleType[i] == wall || particleBC[i] == surface)\n\t//\t\t\t\t\t\t\tpndAux += wS;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\n\n//\t\tDivV = \tcorrecMatrixRow1[i*3  ]*M1[0][0] + correcMatrixRow1[i*3+1]*M1[1][0] + correcMatrixRow1[i*3+2]*M1[2][0] +\n//\t\t\t\tcorrecMatrixRow2[i*3  ]*M1[0][1] + correcMatrixRow2[i*3+1]*M1[1][1] + correcMatrixRow2[i*3+2]*M1[2][1] +\n//\t\t\t\tcorrecMatrixRow3[i*3  ]*M1[0][2] + correcMatrixRow3[i*3+1]*M1[1][2] + correcMatrixRow3[i*3+2]*M1[2][2];\n\n\t\tacc[i*3] = pndi[i]*(1.0+timeStep*(-DivV+Di*flagDi));\n\n\n//\t\tif(isnan(DivV) || isnan(Di))\n//\t\t\tprintf(\" i %d \\n\", i);\n\t\tvelDivergence[i] = DivV;\n\t\tdiffusiveTerm[i] = Di;\n\n\t//acc[i*3] = pndi[i]*(1.0+timeStep*(-(1.0-diffusiveCoef)*DivV+Di*flagDi));\n\t//acc[i*3] = pndSmall[i]*(1.0+timeStep*(-DivV+Di*flagDi));\n\t//acc[i*3] =     pndSmallZero*(1.0+timeStep*(-DivV+Di*flagDi)); // Ruim\n//\t\tif(particleType[i] == wall)\n//\t\t{\n//\t\t\tif(pndAux < pndSmallZero)\n//\t\t\t\tpndAux = pndSmallZero;\n//\t\t\tacc[i*3] = pndAux;\n//\t\t}\n//\t\tif(particleBC[i] == surface)\n//\t\t{\n//\t\t\tacc[i*3] = pndAux;\n//\t\t}\n\t}\n//#pragma omp parallel for\n//\tfor(int i=0; i<numParticles; i++) {\n/////\tif(particleType[i] == fluid) {\n//\t\tpndi[i] = acc[i*3];\n//\t\tacc[i*3]=0.0;\n//\t}\n}\n\n// Diffusive term of density/PND (Polygon wall) - Free-slip (pndType = calcPNDType::DIFFUSIVE)\nvoid MpsParticle::calcWallSlipPndDiffusiveTerm() {\n\t//int nPartNearMesh = partNearMesh.size();\n\t//printf(\" Mesh %d \\n\", nPartNearMesh);\n\t// Loop only for particles near mesh\n#pragma omp parallel for schedule(dynamic,64)\n\t//for(int im=0;im<nPartNearMesh;im++) {\n\t//int i = partNearMesh[im];\n\tfor(int i=0; i<numParticles; i++) {\n\t\tdouble ni = pndi[i];\n\t\t//if(particleType[i] == fluid && ni > 1.0e-8) {\n\t\tif(particleType[i] == fluid && particleNearWall[i] == true && ni > 1.0e-8) {\n\t//\tif(particleType[i] == fluid) {\n\t\t\tdouble DivV = 0.0;\n\t\t\t//double Pi = press[i];\n\t\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\t\tdouble velXi = vel[i*3  ];\tdouble velYi = vel[i*3+1];\tdouble velZi = vel[i*3+2];\n\t\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t//\t\tdouble velXi = Velk[i*3  ];\tdouble velYi = Velk[i*3+1];\tdouble velZi = Velk[i*3+2\n\n\t\t\t// Transformation matrix Rref_i = I - 2.0*normal_iwall*normal_iwall\n\t\t\tdouble Rref_i[9], normaliw[3], normalMod2;\n\t\t\t// normal fluid-wall particle = 0.5*(normal fluid-mirror particle)\n\t\t\tnormaliw[0] = 0.5*(posXi - posMirrorXi); normaliw[1] = 0.5*(posYi - posMirrorYi); normaliw[2] = 0.5*(posZi - posMirrorZi);\n\t\t\tnormalMod2 = normaliw[0]*normaliw[0] + normaliw[1]*normaliw[1] + normaliw[2]*normaliw[2];\n\t\t\tif(normalMod2 > 1.0e-8) {\n\t\t\t\tdouble normalMod = sqrt(normalMod2);\n\t\t\t\tnormaliw[0] = normaliw[0]/normalMod;\n\t\t\t\tnormaliw[1] = normaliw[1]/normalMod;\n\t\t\t\tnormaliw[2] = normaliw[2]/normalMod;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tnormaliw[0] = 0;\n\t\t\t\tnormaliw[1] = 0;\n\t\t\t\tnormaliw[2] = 0;\n\t\t\t}\n\n\t\t    //  Transformation matrix Rref_i = I - 2.0*normal_iwall*normal_iwall\n\t\t    Rref_i[0] = 1.0 - 2.0*normaliw[0]*normaliw[0]; Rref_i[1] = 0.0 - 2.0*normaliw[0]*normaliw[1]; Rref_i[2] = 0.0 - 2.0*normaliw[0]*normaliw[2];\n\t\t\tRref_i[3] = 0.0 - 2.0*normaliw[1]*normaliw[0]; Rref_i[4] = 1.0 - 2.0*normaliw[1]*normaliw[1]; Rref_i[5] = 0.0 - 2.0*normaliw[1]*normaliw[2];\n\t\t\tRref_i[6] = 0.0 - 2.0*normaliw[2]*normaliw[0]; Rref_i[7] = 0.0 - 2.0*normaliw[2]*normaliw[1]; Rref_i[8] = 1.0 - 2.0*normaliw[2]*normaliw[2];\n\n\t\t\t// Mirror particle velocity vi' = Rref_i * vi\n\t      \tdouble velMirrorXi = (Rref_i[0]*velXi + Rref_i[1]*velYi + Rref_i[2]*velZi);\n\t\t\tdouble velMirrorYi = (Rref_i[3]*velXi + Rref_i[4]*velYi + Rref_i[5]*velZi);\n\t\t\tdouble velMirrorZi = (Rref_i[6]*velXi + Rref_i[7]*velYi + Rref_i[8]*velZi);\n\n\t\t\tint ix, iy, iz;\n\t\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\t\tint j = firstParticleInBucket[jb];\n\t\t\t\tif(j == -1) continue;\n\t\t\t\tdouble plx, ply, plz;\n\t\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\t\twhile(true) {\n\t\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\t\n\t\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t\t// If j is inside the neighborhood of i and im (intersection) and \n\t\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\t\tif(dstij2 < reS2 && dstimj2 < reS2 && dstij2 < dstimj2) {\n\t\t\t\t\t\tif(j != i) {\n\t\t\t\t\t\t\tdouble dst = sqrt(dstimj2);\n\t\t\t\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\t\t\t\tdouble vijx = vel[j*3  ]-velMirrorXi;\n\t\t\t\t\t\t\tdouble vijy = vel[j*3+1]-velMirrorYi;\n\t\t\t\t\t\t\tdouble vijz = vel[j*3+2]-velMirrorZi;\n\t\t\t\t\t\t\tDivV += (dim/pndSmallZero)*(pndi[j]/ni)*(vijx*v0imj+vijy*v1imj+vijz*v2imj)*wS/dstimj2;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\t\tif(j == -1) break;\n\t\t\t\t}\n\t\t\t}}}\n\n\t\t\t// Add \"i\" contribution (\"i\" is a neighbor of \"mirror i\")\n\t\t\tdouble v0imi, v1imi, v2imi, dstimi2;\n\t\t\tsqrDistBetweenParticles(i, posMirrorXi, posMirrorYi, posMirrorZi, v0imi, v1imi, v2imi, dstimi2);\n\t\t\t\n\t\t\tif(dstimi2 < reS2) {\n\t\t\t\tdouble dst = sqrt(dstimi2);\n\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\tdouble vijx = velXi-velMirrorXi;\n\t\t\t\tdouble vijy = velYi-velMirrorYi;\n\t\t\t\tdouble vijz = velZi-velMirrorZi;\n\t\t\t\tDivV += (dim/pndSmallZero)*(pndi[i]/ni)*(vijx*v0imi+vijy*v1imi+vijz*v2imi)*wS/dstimi2;\n\t\t  \t}\n\n\t\t\tacc[i*3] += -pndi[i]*timeStep*DivV;\n\t\t\t//acc[i*3] = pndSmallZero*(1.0+timeStep*(-DivV+Di*flagDi));\n\t\t}\n\t}\n//#pragma omp parallel for\n//\tfor(int i=0; i<numParticles; i++) {\n//\tif(particleType[i] == fluid) {\n//\t\tpndi[i] += acc[i*3];\n//\t\tacc[i*3]=0.0;\n//\t}}\n}\n\n// Diffusive term of density/PND (Polygon wall) - No-slip (pndType = calcPNDType::DIFFUSIVE)\nvoid MpsParticle::calcWallNoSlipPndDiffusiveTerm() {\n\t//int nPartNearMesh = partNearMesh.size();\n\t//printf(\" Mesh %d \\n\", nPartNearMesh);\n\t// Loop only for particles near mesh\n#pragma omp parallel for schedule(dynamic,64)\n\t//for(int im=0;im<nPartNearMesh;im++) {\n\t//int i = partNearMesh[im];\n\tfor(int i=0; i<numParticles; i++) {\n\t\tdouble ni = pndi[i];\n\t\t//if(particleType[i] == fluid && ni > 1.0e-8) {\n\t\tif(particleType[i] == fluid && particleNearWall[i] == true && ni > 1.0e-8) {\n\t//\tif(particleType[i] == fluid) {\n\t\t\tdouble DivV = 0.0;\n\t\t\t//double Pi = press[i];\n\t\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\t\tdouble velXi = vel[i*3  ];\tdouble velYi = vel[i*3+1];\tdouble velZi = vel[i*3+2];\n\t\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t//\t\tdouble velXi = Velk[i*3  ];\tdouble velYi = Velk[i*3+1];\tdouble velZi = Velk[i*3+2\n\n\t\t\t// Inverse matrix Rinv_i = - I\n\t\t\tdouble Rinv_i[9], Rref_i[9], normaliw[3], normalMod2;\n\t\t    // normal fluid-wall particle = 0.5*(normal fluid-mirror particle)\n\t\t    normaliw[0] = 0.5*(posXi - posMirrorXi); normaliw[1] = 0.5*(posYi - posMirrorYi); normaliw[2] = 0.5*(posZi - posMirrorZi);\n\t\t    normalMod2 = normaliw[0]*normaliw[0] + normaliw[1]*normaliw[1] + normaliw[2]*normaliw[2];\n\t\t    if(normalMod2 > 1.0e-8) {\n\t\t    \tdouble normalMod = sqrt(normalMod2);\n\t\t    \tnormaliw[0] = normaliw[0]/normalMod;\n\t\t    \tnormaliw[1] = normaliw[1]/normalMod;\n\t\t    \tnormaliw[2] = normaliw[2]/normalMod;\n\t\t    }\n\t\t    else {\n\t\t    \tnormaliw[0] = 0;\n\t\t    \tnormaliw[1] = 0;\n\t\t    \tnormaliw[2] = 0;\n\t\t    }\n\n\t\t    //  Inverse transformation matrix Rinv_i = - I\n\t\t    Rinv_i[0] = -1.0; Rinv_i[1] =  0.0; Rinv_i[2] =  0.0;\n\t\t\tRinv_i[3] =  0.0; Rinv_i[4] = -1.0; Rinv_i[5] =  0.0;\n\t\t\tRinv_i[6] =  0.0; Rinv_i[7] =  0.0; Rinv_i[8] = -1.0;\n\n\t\t    //  Transformation matrix Rref_i = I - 2.0*normal_iwall*normal_iwall\n\t\t    Rref_i[0] = 1.0 - 2.0*normaliw[0]*normaliw[0]; Rref_i[1] = 0.0 - 2.0*normaliw[0]*normaliw[1]; Rref_i[2] = 0.0 - 2.0*normaliw[0]*normaliw[2];\n\t\t\tRref_i[3] = 0.0 - 2.0*normaliw[1]*normaliw[0]; Rref_i[4] = 1.0 - 2.0*normaliw[1]*normaliw[1]; Rref_i[5] = 0.0 - 2.0*normaliw[1]*normaliw[2];\n\t\t\tRref_i[6] = 0.0 - 2.0*normaliw[2]*normaliw[0]; Rref_i[7] = 0.0 - 2.0*normaliw[2]*normaliw[1]; Rref_i[8] = 1.0 - 2.0*normaliw[2]*normaliw[2];\n\n\t\t\tdouble viwall[3], vtil[3];\n\t\t\t// Wall velocity (0 if fixed)\n\t\t\tviwall[0]=viwall[1]=viwall[2]=0.0;\n\n\t\t\tif(nearMeshType[i] == meshType::FORCED) {\n\t\t\t\tviwall[0] = velVWall[0];\n\t\t\t\tviwall[1] = velVWall[1];\n\t\t\t\tviwall[2] = velVWall[2];\n\t\t\t}\n\n\t\t\t// normal_iwall*v_iwall\n\t\t\tdouble dotnv = normaliw[0]*viwall[0] + normaliw[1]*viwall[1] + normaliw[2]*viwall[2];\n\t\t\t// vtil = vi - 2 {v_iwall - (normal_iwall*v_iwall)normal_iwall}\n\t\t\tvtil[0] = velXi - 2.0*(viwall[0] - dotnv*normaliw[0]);\n\t\t\tvtil[1] = velYi - 2.0*(viwall[1] - dotnv*normaliw[1]);\n\t\t\tvtil[2] = velZi - 2.0*(viwall[2] - dotnv*normaliw[2]);\n\t\t\t// Mirror particle velocity vi' = Rinv_i * [vi - 2 {v_iwall - (normal_iwall*v_iwall)normal_iwall}] \n\t      \tdouble velMirrorXi = (Rinv_i[0]*vtil[0] + Rinv_i[1]*vtil[1] + Rinv_i[2]*vtil[2]);\n\t\t\tdouble velMirrorYi = (Rinv_i[3]*vtil[0] + Rinv_i[4]*vtil[1] + Rinv_i[5]*vtil[2]);\n\t\t\tdouble velMirrorZi = (Rinv_i[6]*vtil[0] + Rinv_i[7]*vtil[1] + Rinv_i[8]*vtil[2]);\n\n\t\t\tint ix, iy, iz;\n\t\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\t\tint j = firstParticleInBucket[jb];\n\t\t\t\tif(j == -1) continue;\n\t\t\t\tdouble plx, ply, plz;\n\t\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\t\twhile(true) {\n\t\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\t\n\t\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t\t// If j is inside the neighborhood of i and im (intersection) and \n\t\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\t\tif(dstij2 < reS2 && dstimj2 < reS2 && dstij2 < dstimj2) {\n\t\t\t\t\t\tif(j != i) {\n\t\t\t\t\t\t\tdouble dst = sqrt(dstimj2);\n\t\t\t\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\t\t\t\tdouble vijx = -(vel[j*3  ]-velMirrorXi);\n\t\t\t\t\t\t\tdouble vijy = -(vel[j*3+1]-velMirrorYi);\n\t\t\t\t\t\t\tdouble vijz = -(vel[j*3+2]-velMirrorZi);\n\t\t\t\t\t\t\t// Refelected rij' = Rref_i * ri'j\n\t      \t\t\t\t\tdouble v0m = (Rref_i[0]*v0imj + Rref_i[1]*v1imj + Rref_i[2]*v2imj);\n\t\t\t\t\t\t\tdouble v1m = (Rref_i[3]*v0imj + Rref_i[4]*v1imj + Rref_i[5]*v2imj);\n\t\t\t\t\t\t\tdouble v2m = (Rref_i[6]*v0imj + Rref_i[7]*v1imj + Rref_i[8]*v2imj);\n\t\t\t\t\t\t\tDivV += (dim/pndSmallZero)*(pndi[j]/ni)*(vijx*v0m+vijy*v1m+vijz*v2m)*wS/dstimj2;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\t\tif(j == -1) break;\n\t\t\t\t\t}\n\t\t\t}}}\n\n\t\t\t// Add \"i\" contribution (\"i\" is a neighbor of \"mirror i\")\n\t\t\tdouble v0imi, v1imi, v2imi, dstimi2;\n\t\t\tsqrDistBetweenParticles(i, posMirrorXi, posMirrorYi, posMirrorZi, v0imi, v1imi, v2imi, dstimi2);\n\t\t\t\n\t\t\tif(dstimi2 < reS2) {\n\t\t\t\tdouble dst = sqrt(dstimi2);\n\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\tdouble vijx = -(velXi-velMirrorXi);\n\t\t\t\tdouble vijy = -(velYi-velMirrorYi);\n\t\t\t\tdouble vijz = -(velZi-velMirrorZi);\n\t\t\t\t// Refelected rij' = Rref_i * ri'j\n\t\t\t\tdouble v0m = (Rref_i[0]*v0imi + Rref_i[1]*v1imi + Rref_i[2]*v2imi);\n\t\t\t\tdouble v1m = (Rref_i[3]*v0imi + Rref_i[4]*v1imi + Rref_i[5]*v2imi);\n\t\t\t\tdouble v2m = (Rref_i[6]*v0imi + Rref_i[7]*v1imi + Rref_i[8]*v2imi);\n\t\t\t\tDivV += (dim/pndSmallZero)*(pndi[i]/ni)*(vijx*v0m+vijy*v1m+vijz*v2m)*wS/dstimi2;\n\t\t  \t}\n\n\t\t\tacc[i*3] += -pndi[i]*timeStep*DivV;\n\t\t\t//acc[i*3] = pndSmallZero*(1.0+timeStep*(-DivV+Di*flagDi));\n\t\t}\n\t}\n//#pragma omp parallel for\n//\tfor(int i=0; i<numParticles; i++) {\n//\tif(particleType[i] == fluid) {\n//\t\tpndi[i] += acc[i*3];\n//\t\tacc[i*3]=0.0;\n//\t}}\n}\n\n// Update PND (pndType = calcPNDType::DIFFUSIVE)\nvoid MpsParticle::updatePnd() {\n#pragma omp parallel for\n\tfor(int i=0; i<numParticles; i++) {\n\t//\t\tif(particleType[i] == fluid)\n\t\t\tpndi[i] = acc[i*3];\n//\t\telse\n//\t\t{\n//\t\t\tpndi[i] = acc[i*3];\n\t\t\t/*\n\t\t\tdouble mi;\n\t\t\tif(PTYPE[i] == 1) \n\t\t\t\tmi = DNS_FL1;\n\t\t\telse \n\t\t\t\tmi = DNS_FL2;\n\t\t\tif(mpsType == calcPressType::EXPLICIT)\n\t\t\t\tpndi[i] = pndSmallZero*(press[i]/(mi*coeffPressWCMPS)+1);\n\t\t\telse if(mpsType == calcPressType::WEAKLY)\n\t\t\t\tpndi[i] = pndSmallZero*pow(press[i]*gamma/(mi*coeffPressWCMPS)+1,gamma);\n\t\t\t\t*/\n//\t\t}\n\t\tacc[i*3]=0.0;\n\t}\n}\n\n// Mean PND at wall and dummy particles (pndType = calcPNDType::DIFFUSIVE)\nvoid MpsParticle::meanPndParticlesWallDummySurface() {\n#pragma omp parallel for schedule(dynamic,64)\n\tfor(int i=0; i<numParticles; i++) {\n//\tif(particleType[i] == wall) {\n\t\tif(particleType[i] == wall || particleBC[i] == surface) {\n//\tif(particleBC[i] == surface) {\n\t\t\tdouble PNDup = 0.0;\n\t\t\tdouble PNDdo = 0.0;\n\t\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\t\t\n\t\t\tint ix, iy, iz;\n\t\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\t\tint j = firstParticleInBucket[jb];\n\t\t\t\tif(j == -1) continue;\n\t\t\t\tdouble plx, ply, plz;\n\t\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\t\twhile(true) {\n\t\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\t\n\t\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\t\tif(dstij2 < reS2 && (dstij2 < dstimj2 || wallType == boundaryWallType::PARTICLE)) {\n\t\t\t\t\t\tif(j != i) {\n\t\t\t\t\t\t\tdouble dst = sqrt(dstij2);\n\t\t\t\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\t\t\t\tPNDup += pndi[j]*wS;\n\t\t\t\t\t\t\tPNDdo += wS;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\t\tif(j == -1) break;\n\t\t\t\t}\n\t\t\t}}}\n\t\t\tacc[i*3  ] = PNDup;\n\t\t\tacc[i*3+1] = PNDdo;\n\t\t\t//acc[i*3] = pndSmallZero*(1.0+timeStep*(-DivV+Di*flagDi));\n\t//\t}}}\n\t\t}\n\t}\n#pragma omp parallel for\n\tfor(int i=0; i<numParticles; i++) {\n//\tif(particleType[i] == wall) {\n\t\tif(particleType[i] == wall || particleBC[i] == surface) {\n//\tif(particleBC[i] == surface) {\n\t\t// Prevent PNDdo = 0\n//\t\tif(numNeigh[i] < 1)\n\t\t\tif(acc[i*3+1] < 1.0e-8)\n\t\t\t\tpndi[i] = acc[i*3];\n\t\t\telse\n\t\t\t\tpndi[i] = acc[i*3]/(acc[i*3+1]);\n//\t\t\tpndi[i] = acc[i*3]/(acc[i*3+1] + 0.01*reS2/4.0);\n\t\t}\n//\t}\n\t\tacc[i*3]=0.0;acc[i*3+1]=0.0;\n\t}\n}\n\n// Mean PND (Polygon wall) (pndType = calcPNDType::MEAN_SUM_WIJ)\nvoid MpsParticle::meanWallPnd() {\n\t//int nPartNearMesh = partNearMesh.size();\n\t//printf(\" Mesh %d \\n\", nPartNearMesh);\n\t// Loop only for particles near mesh\n#pragma omp parallel for schedule(dynamic,64)\n\t//for(int im=0;im<nPartNearMesh;im++) {\n\t//int i = partNearMesh[im];\n\tfor(int i=0; i<numParticles; i++) {\n//\tif(particleType[i] == fluid) {\n\t\tif(particleNearWall[i] == true) {\n\t\t\tdouble PNDup = 0.0;\n\t\t\tdouble PNDdo = 0.0;\n\t\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\n\t\t\tint ix, iy, iz;\n\t\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\t\tint j = firstParticleInBucket[jb];\n\t\t\t\tif(j == -1) continue;\n\t\t\t\tdouble plx, ply, plz;\n\t\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\t\twhile(true) {\n\t\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\t\n\t\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t\t// If j is inside the neighborhood of i and im (intersection) and \n\t\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\t\tif(dstij2 < reS2 && dstimj2 < reS2 && dstij2 < dstimj2) {\n\t\t\t\t\t\tif(j != i) {\n\t\t\t\t\t\t\tdouble dst = sqrt(dstimj2);\n\t\t\t\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\t\t\t\tPNDup += pndi[j]*wS;\n\t\t\t\t\t\t\tPNDdo += wS;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\t\tif(j == -1) break;\n\t\t\t\t}\n\n\t\t\t}}}\n\t\t\t// Add \"i\" contribution (\"i\" is a neighbor of \"mirror i\")\n\t\t\tdouble v0imi, v1imi, v2imi, dstimi2;\n\t\t\tsqrDistBetweenParticles(i, posMirrorXi, posMirrorYi, posMirrorZi, v0imi, v1imi, v2imi, dstimi2);\n\t\t\t\n\t\t\tif(dstimi2 < reS2) {\n\t\t\t\tdouble dst = sqrt(dstimi2);\n\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\tPNDup += pndi[i]*wS;\n\t\t\t\tPNDdo += wS;\n\t\t\t}\n\t\t\tacc[i*3  ] = PNDup;\n\t\t\tacc[i*3+1] = PNDdo;\n\t\t}\n\t}\n}\n\n// Mean PND (pndType = calcPNDType::MEAN_SUM_WIJ)\nvoid MpsParticle::meanPnd() {\n#pragma omp parallel for schedule(dynamic,64)\n\tfor(int i=0; i<numParticles; i++) {\n\t\tdouble PNDup = 0.0;\n\t\tdouble PNDdo = 0.0;\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\t\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reS2 && (dstij2 < dstimj2 || wallType == boundaryWallType::PARTICLE)) {\n\t\t\t\t\tif(j != i) {\n\t\t\t\t\t\tdouble dst = sqrt(dstij2);\n\t\t\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\t\t\tPNDup += pndi[j]*wS;\n\t\t\t\t\t\tPNDdo += wS;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\t\tacc[i*3  ] += PNDup;\n\t\tacc[i*3+1] += PNDdo;\n\t\t//acc[i*3] = pndSmallZero*(1.0+timeStep*(-DivV+Di*flagDi));\n\t}\n#pragma omp parallel for\nfor(int i=0; i<numParticles; i++) {\n//\tif(particleType[i] == fluid) {\n\t// Prevent PNDdo = 0\n\t\tif(numNeigh[i] < 1) {\n\t\t\tpndi[i] = acc[i*3];\n\t\t}\n\t\telse {\n\t\t\tpndi[i] = acc[i*3]/acc[i*3+1];\n\t\t}\n\t\tacc[i*3]=0.0;acc[i*3+1]=0.0;\n\t}\n}\n\n// Mean Fluid PND (pndType = calcPNDType::MEAN_SUM_WIJ) // CHANGED\nvoid MpsParticle::meanNeighFluidPnd() {\n#pragma omp parallel for schedule(dynamic,64)\n\tfor(int i=0; i<numParticles; i++) {\n\t\tdouble PNDup = 0.0;\n\t\tdouble PNDdo = 0.0;\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\t\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reS2 && (dstij2 < dstimj2 || wallType == boundaryWallType::PARTICLE)) {\n\t\t\t\t\tif(j != i && particleType[j] == fluid) {\n\t\t\t\t\t\tdouble dst = sqrt(dstij2);\n\t\t\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\t\t\tPNDup += pndki[j]*wS;\n\t\t\t\t\t\tPNDdo += wS;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\t\tif(PNDdo > 1.0e-8) {\n\t\t\tpndski[i] = PNDup/PNDdo;\n\t\t}\n\t\telse {\n\t\t\tpndski[i] = PNDup;\n\t\t}\n\t}\n}\n\n// Update type of particle\nvoid MpsParticle::updateParticleBC() {\n// Use #pragma omp parallel for schedule(dynamic,64) if there are \"for\" inside the main \"for\"\n//#pragma omp parallel for schedule(dynamic,64)\n#pragma omp parallel for\n\tfor(int i=0; i<numParticles; i++) {\n/*\n\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\tdouble ni = 0.0; double wSum = 0.0;\n\tnumNeigh[i] = 0;\n\t// Add Number of neighbors due Wall polygon\n\tnumNeigh[i] += numNeighWallContribution[i];\n\t\n\tint ix, iy, iz;\n\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\tint j = firstParticleInBucket[jb];\n\t\tif(j == -1) continue;\n\t\tdouble plx, ply, plz;\n\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\twhile(true) {\n\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\n\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t// If j is inside the neighborhood of i and \n\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\tif(dstij2 < reL2 && (dstij2 < dstimj2 || wallType == boundaryWallType::PARTICLE)) {\n\t\t\tif(j != i) {\n\t\t\t\tnumNeigh[i] += 1;\n\t\t\t\t//double dst = sqrt(dstij2);\n\t\t\t\t//double wL = weight(dst, reL*invPartDist, weightType);\n\t\t\t\t//npcdDeviation[i*3  ] += v0ij*wL*invPartDist;\n\t\t\t\t//npcdDeviation[i*3+1] += v1ij*wL*invPartDist;\n\t\t\t\t//npcdDeviation[i*3+2] += v2ij*wL*invPartDist;\n\t\t\t\t//wSum += wL;\n\t\t\t\tif(dstij2 < reS2) {\n\t\t\t\t\tdouble dst = sqrt(dstij2);\n\t\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\t\tni += wS;\n\t\t\t\t\tdst = dst*invPartDist;\n\t\t\t\t\twS = weight(dst, reS*invPartDist, weightType);;\n\t\t\t\t\tnpcdDeviation[i*3  ] += v0ij*wS*invPartDist;\n\t\t\t\t\tnpcdDeviation[i*3+1] += v1ij*wS*invPartDist;\n\t\t\t\t\tnpcdDeviation[i*3+2] += v2ij*wS*invPartDist;\n\t\t\t\t\twSum += wS;\n\t\t\t}}}\n\t\t\tj = nextParticleInSameBucket[j];\n\t\t\tif(j == -1) break;\n\t\t}\n\t}}}\n\n\tdouble mi;\n\tif(PTYPE[i] == 1) mi = DNS_FL1;\n\telse mi = DNS_FL2;\n\t//if(particleType[i]==fluid)\n\t//\tmi = Dns[partType::FLUID];\n\t//else\n\t//\tmi = Dns[partType::WALL];\n\n\tif(pndType == calcPNDType::SUM_WIJ || pndType == calcPNDType::MEAN_SUM_WIJ)\n//\t\tif(pndType == calcPNDType::SUM_WIJ)\n\t{\n\t\t// PND due particles and Wall polygon\n\t\tpndi[i] = ni + pndWallContribution[i];\n\t}\n\n//\t\tif(particleType[i] == wall) {\n\t\t// PND due particles and Wall polygon\n//\t\t\tpndi[i] = ni + pndWallContribution[i];\n//\t\t\tif(pndi[i] < pndSmallZero)\n//\t\t\t\tpndi[i] = pndSmallZero;\n\n//\t\t\t\tpndi[i] = pndSmallZero*pow((press[i]*gamma/(mi*coeffPressWCMPS)+1),gamma);\n//\t\t}\n\n\t// Add PND due Wall polygon\n\tpndSmall[i] = ni + pndWallContribution[i];\n\t// Prevent pndSmall[i] = 0\n//\t\tif(numNeigh[i] > 1) {\n\tif(wSum > 1.0e-8) {\n\t\t//npcdDeviation[i*3  ] /= pndSmall[i];\n\t\t//npcdDeviation[i*3+1] /= pndSmall[i];\n\t\t//npcdDeviation[i*3+2] /= pndSmall[i];\n\t\tnpcdDeviation[i*3  ] /= wSum;\n\t\tnpcdDeviation[i*3+1] /= wSum;\n\t\tnpcdDeviation[i*3+2] /= wSum;\n\t}\n\n\tnpcdDeviation2[i] = npcdDeviation[i*3]*npcdDeviation[i*3]+npcdDeviation[i*3+1]*npcdDeviation[i*3+1]+npcdDeviation[i*3+2]*npcdDeviation[i*3+2];\n\n\t//deviationDotPolygonNormal[i] = npcdDeviation[i*3]*polygonNormal[i*3]+npcdDeviation[i*3+1]*polygonNormal[i*3+1]+npcdDeviation[i*3+2]*polygonNormal[i*3+2];\n\tif(npcdDeviation[i*3]*polygonNormal[i*3]+npcdDeviation[i*3+1]*polygonNormal[i*3+1]+npcdDeviation[i*3+2]*polygonNormal[i*3+2] < 0.0)\n\t\tdeviationDotPolygonNormal[i] = 1;\n\telse\n\t\tdeviationDotPolygonNormal[i] = -1;\n\n\t// coeffPressWCMPS = soundSpeed*soundSpeed\n\tdouble pressure = 0.0;\n*/\t\t\n\t\tif(particleType[i] == dummyWall) {\n\t\t\tparticleBC[i] = other;\n\t\t\tcontinue;\n\t\t}\n\t\t// First check based on particle number density\n\t\tif(pndSmall[i] < betaPnd) {\n\t\t//if(pndi[i] < betaPnd) {\n\t\t\tparticleBC[i] = surface;\n\t\t}\n\t\telse {\n\t\t\tparticleBC[i] = inner;\n\t\t}\n\n\t\tif(freeSurfType == calcBCType::PND_NEIGH) {\n\t\t\tif(pndSmall[i] < betaPnd && numNeigh[i] < betaNeigh) {\n\t\t\t//if(pndi[i] < betaPnd && numNeigh[i] < betaNeigh) {\n\t\t\t\tparticleBC[i] = surface;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tparticleBC[i] = inner;\n\t\t\t}\n\t\t}\n\t\telse if(freeSurfType == calcBCType::PND_NPCD) {\n\t\t\t// Boundary particle verification based on relative distance and weight (NPCD)\n\t\t\t// 2016 - Fluid interface detection technique based on neighborhood particles \n\t\t\t// centroid deviation (NPCD) for particle methods\n\t\t\tif(particleBC[i] == surface) {\n\t\t\t\tif(numNeigh[i] > 4 && npcdDeviation2[i] < delta2) {\n\t\t\t\t\tparticleBC[i] = inner;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if(freeSurfType == calcBCType::PND_ARC) {\n\t\t\tdouble normalXi = normal[i*3  ];\tdouble normalYi = normal[i*3+1];\tdouble normalZi = normal[i*3+2];\n\t\t\tdouble norm2 = normalXi*normalXi + normalYi*normalYi + normalZi*normalZi;\n\t\t\t// 2017 - A multiphase MPS solver for modeling multi-fluid interaction with \n\t\t\t// free surface and its application in oil spill\n\t\t\t//if((pndSmall[i] >= betaPnd || numNeigh[i] >= betaNeigh) && norm2 <= normThreshold2) {\n\t\t\t/*if(pndSmall[i] >= betaPnd && numNeigh[i] >= betaNeigh && norm2 <= normThreshold2) {\n\t\t\t//if(pndSmall[i] >= betaPnd || numNeigh[i] >= betaNeigh) {\n\t\t\t*/\n\t\t\tif(pndi[i] >= betaPnd && numNeigh[i] >= betaNeigh && norm2 <= normThreshold2) {\n\t\t\t\tparticleBC[i] = inner;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\t\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\t\t\t//double normalXi = normal[i*3  ];\tdouble normalYi = normal[i*3+1];\tdouble normalZi = normal[i*3+2];\n\t\t\t\tif(norm2 > 1.0e-8) {\n\t\t\t\t\tdouble norm = sqrt(norm2);\n\t\t\t\t\tnormalXi /= norm;\tnormalYi /= norm;\tnormalZi /= norm;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tnormalXi = 0.0;\tnormalYi = 0.0;\tnormalZi = 0.0;\n\t\t\t\t}\n\t\t\t\t// Transformation matrix Rref_i = I - 2.0*normal_iwall*normal_iwall\n\t\t\t\tdouble Rref_i[9], normaliw[3], normalMod2;\n\t\t\t\t// normal fluid-wall particle = 0.5*(normal fluid-mirror particle)\n\t\t\t\tnormaliw[0] = 0.5*(posXi - posMirrorXi); normaliw[1] = 0.5*(posYi - posMirrorYi); normaliw[2] = 0.5*(posZi - posMirrorZi);\n\t\t\t\tnormalMod2 = normaliw[0]*normaliw[0] + normaliw[1]*normaliw[1] + normaliw[2]*normaliw[2];\n\t\t\t\tif(normalMod2 > 1.0e-8) {\n\t\t\t\t\tdouble normalMod = sqrt(normalMod2);\n\t\t\t\t\tnormaliw[0] /= normalMod; normaliw[1] /= normalMod; normaliw[2] /= normalMod;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tnormaliw[0] = 0.0; normaliw[1] = 0.0; normaliw[2] = 0;\n\t\t\t\t}\n\n\t\t\t\t// Transformation matrix Rref_i = I - 2.0*normal_iwall*normal_iwall\n\t\t\t\tRref_i[0] = 1.0 - 2.0*normaliw[0]*normaliw[0]; Rref_i[1] = 0.0 - 2.0*normaliw[0]*normaliw[1]; Rref_i[2] = 0.0 - 2.0*normaliw[0]*normaliw[2];\n\t\t\t\tRref_i[3] = 0.0 - 2.0*normaliw[1]*normaliw[0]; Rref_i[4] = 1.0 - 2.0*normaliw[1]*normaliw[1]; Rref_i[5] = 0.0 - 2.0*normaliw[1]*normaliw[2];\n\t\t\t\tRref_i[6] = 0.0 - 2.0*normaliw[2]*normaliw[0]; Rref_i[7] = 0.0 - 2.0*normaliw[2]*normaliw[1]; Rref_i[8] = 1.0 - 2.0*normaliw[2]*normaliw[2];\n\n\t\t\t\t// Normal mirror i\n\t\t\t\tdouble normalMirrorXi = Rref_i[0]*normalXi + Rref_i[1]*normalYi + Rref_i[2]*normalZi;\n\t\t\t\tdouble normalMirrorYi = Rref_i[3]*normalXi + Rref_i[4]*normalYi + Rref_i[5]*normalZi;\n\t\t\t\tdouble normalMirrorZi = Rref_i[6]*normalXi + Rref_i[7]*normalYi + Rref_i[8]*normalZi;\n\t\t\t\tdouble normMirror2 = normalMirrorXi*normalMirrorXi + normalMirrorYi*normalMirrorYi + normalMirrorZi*normalMirrorZi;\n\t\t\t\tif(normMirror2 > 1.0e-8) {\n\t\t\t\t\tdouble normMirror = sqrt(normMirror2);\n\t\t\t\t\tnormalMirrorXi /= normMirror;\tnormalMirrorYi /= normMirror;\tnormalMirrorZi /= normMirror;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tnormalMirrorXi = 0.0;\tnormalMirrorYi = 0.0;\tnormalMirrorZi = 0.0;\n\t\t\t\t}\n\n\t\t\t\tint ix, iy, iz;\n\t\t\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\t\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\t\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\t\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\t\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\t\t\tint j = firstParticleInBucket[jb];\n\t\t\t\t\tif(j == -1) continue;\n\t\t\t\t\tdouble plx, ply, plz;\n\t\t\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\t\t\twhile(true) {\n\t\t\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t\t\t// Real particle i and neighbor j\n\t\t\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\t\t\tif(dstij2 < reS2 && (dstij2 < dstimj2 || wallType == boundaryWallType::PARTICLE)) {\n\t\t\t\t\t\tif(j != i) {\n\t\t\t\t\t\t\tdouble v0inj, v1inj, v2inj, dstinj2;\n\t\t\t\t\t\t\tsqrDistBetweenParticles(j, posXi + partDist*normalXi, posYi + partDist*normalYi, \n\t\t\t\t\t\t\t\tposZi + partDist*normalZi, v0inj, v1inj, v2inj, dstinj2, plx, ply, plz);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tdouble rijn = v0ij*normalXi + v1ij*normalYi + v2ij*normalZi;\n\n\t\t\t\t\t\t\tdouble ang = acos(rijn/sqrt(dstij2));\n\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\tif (dstij2 >= dstThreshold2 && dstinj2 < hThreshold2) {\n\t\t\t\t\t\t\t\tparticleBC[i] = inner;\n\t\t\t\t\t\t\t\t//goto endloop;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (dstij2 < dstThreshold2 && ang < 3.14159265/4.0) {\n\t\t\t\t\t\t\t//else if (dstij2 < dstThreshold2 && rijn*rijn < dstij2*0.5) {\n\t\t\t\t\t\t\t\tparticleBC[i] = inner;\n\t\t\t\t\t\t\t\t//goto endloop;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tparticleBC[i] = surface;\n\t\t\t\t\t\t\t\tgoto endloop;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t*/\n\t\t\t\t\t\t\tif (dstij2 >= dstThreshold2 && dstinj2 < hThreshold2) {\n\t\t\t\t\t\t\t\tparticleBC[i] = inner;\n\t\t\t\t\t\t\t\tgoto endloop;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (dstij2 < dstThreshold2 && ang < thetaArc) {\n\t\t\t\t\t\t\t\tparticleBC[i] = inner;\n\t\t\t\t\t\t\t\tgoto endloop;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tparticleBC[i] = surface;\n\t\t\t\t\t\t\t}\n/*\n\t\t\t\t\t\t\t//if ((dstij2 < dstThreshold2 && ang < thetaArc) || (numNeigh[i] >= betaNeigh)) {\n\t\t\t\t\t\t\tif (ang < thetaArc && numNeigh[i] >= 4) {\n\t\t\t\t\t\t\t//else if (dstij2 < dstThreshold2 && rijn*rijn < dstij2*0.5) {\n\t\t\t\t\t\t\t\tparticleBC[i] = inner;\n\t\t\t\t\t\t\t\tgoto endloop;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tparticleBC[i] = surface;\n\t\t\t\t\t\t\t\t//goto endloop;\n\t\t\t\t\t\t\t}*/\n\t\t\t\t\t\t}}\n\n\t\t\t\t\t\tif(wallType == boundaryWallType::POLYGON){\n\t\t\t\t\t\t\t// Virtual particle i and real neighbor j\n\t\t\t\t\t\t\t// If j is inside the neighborhood of i and im (intersection) and \n\t\t\t\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\t\t\t\tif(dstij2 < reS2 && dstimj2 < reS2 && dstij2 < dstimj2) {\n\t\t\t\t\t\t\t\tif(j != i) {\n\t\t\t\t\t\t\t\t\tdouble v0imnj, v1imnj, v2imnj, dstimnj2;\n\t\t\t\t\t\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi + partDist*normalMirrorXi, posMirrorYi + partDist*normalMirrorYi, \n\t\t\t\t\t\t\t\t\t\tposMirrorZi + partDist*normalMirrorZi, v0imnj, v1imnj, v2imnj, dstimnj2, plx, ply, plz);\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tdouble rimjn = v0imj*normalMirrorXi + v1imj*normalMirrorYi + v2imj*normalMirrorZi;\n\n\t\t\t\t\t\t\t\t\tdouble angm = acos(rimjn/sqrt(dstimj2));\n\n\t\t\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t\t\tif (dstimj2 >= dstThreshold2 && dstimnj2 < hThreshold2) {\n\t\t\t\t\t\t\t\t\t\tparticleBC[i] = inner;\n\t\t\t\t\t\t\t\t\t\t//goto endloop;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t//else if (dstimj2 < dstThreshold2 && rimjn*rimjn < dstimj2*0.6675*0.6675) {\n\t\t\t\t\t\t\t\t\telse if (dstimj2 < dstThreshold2 && angm < thetaArc) {\n\t\t\t\t\t\t\t\t\t//else if (dstimj2 < dstThreshold2 && rimjn*rimjn < dstimj2*0.5) {\n\t\t\t\t\t\t\t\t\t\tparticleBC[i] = inner;\n\t\t\t\t\t\t\t\t\t\t//goto endloop;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\tparticleBC[i] = surface;\n\t\t\t\t\t\t\t\t\t\tgoto endloop;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t*/\n\n\t\t\t\t\t\t\t\t\tif (dstimj2 >= dstThreshold2 && dstimnj2 < hThreshold2) {\n\t\t\t\t\t\t\t\t\t\tparticleBC[i] = inner;\n\t\t\t\t\t\t\t\t\t\tgoto endloop;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if (dstimj2 < dstThreshold2 && angm < thetaArc) {\n\t\t\t\t\t\t\t\t\t\tparticleBC[i] = inner;\n\t\t\t\t\t\t\t\t\t\tgoto endloop;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\tparticleBC[i] = surface;\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\t//if ((dstimj2 < dstThreshold2 && angm < 3.14159265/4.0) || (numNeigh[i] >= betaNeigh)) {\n\t\t\t\t\t\t\t\t\tif (angm < thetaArc && numNeigh[i] >= 4) {\n\t\t\t\t\t\t\t\t\t\tparticleBC[i] = inner;\n\t\t\t\t\t\t\t\t\t\tgoto endloop;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\tparticleBC[i] = surface;\n\t\t\t\t\t\t\t\t\t\t//goto endloop;\n\t\t\t\t\t\t\t\t\t}*/\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\t\t\tif(j == -1) break;\n\t\t\t\t\t}\n\t\t\t\t}}}\n\n\t\t\t\tendloop: ;\n\t\t\t}\n\t\t}\n\t}\n}\n\n// Compute pressure EMPS (mpsType = calcPressType::EXPLICIT)\nvoid MpsParticle::calcPressEMPS() {\n// Use #pragma omp parallel for schedule(dynamic,64) if there are \"for\" inside the main \"for\"\n//#pragma omp parallel for schedule(dynamic,64)\n#pragma omp parallel for\n\tfor(int i=0; i<numParticles; i++) {\n\t\tdouble mi;\n\t\tif(PTYPE[i] == 1) mi = DNS_FL1;\n\t\telse mi = DNS_FL2;\n\t\t//if(particleType[i]==fluid)\n\t\t//\tmi = Dns[partType::FLUID];\n\t\t//else\n\t\t//\tmi = Dns[partType::WALL];\n\n\t\tdouble pressure = 0.0;\n\t\tif(particleBC[i] == inner) {\n\t\t\tpressure = (pndi[i] - pndSmallZero) * coeffPressEMPS * mi;\n\t\t}\n\n//\t\tif(pndSmall[i] < pndThreshold*pndSmallZero && numNeigh[i] < neighThreshold*numNeighZero)\n//\t\t\tparticleBC[i] = surface;\n//\t\telse\n//\t\t{\n//\t\t\tparticleBC[i] = inner;\n//\t\t\tpressure = (pndi[i] - pndSmallZero) * coeffPressEMPS * mi;\n//\t\t}\n//\t\tif(wallType == boundaryWallType::POLYGON) {\n//\t\t\tif(pndi[i] > pndThreshold*pndSmallZero) {\n//\t\t\t\tpressure = -mi*gravityZ*(0.3-posZi);\n//\t\t\t}\n//\t\t}\n//\t\telse if(wallType == boundaryWallType::PARTICLE) {\n//\t\t\tif(pndi[i] > pndThreshold*pndSmallZero || numNeigh[i] > neighThreshold*numNeighZero) {\n//\t\t\t\tpressure = -mi*gravityZ*(0.3-posZi);\n//\t\t\t}\n//\t\t}\n\n\t\tif(pressure < 0.0) {\n\t\t\tpressure = 0.0;\n\t\t}\n\t\tpress[i] = pressure;\n\t}\n}\n\n// Compute pressure WCMPS (mpsType = calcPressType::WEAKLY)\nvoid MpsParticle::calcPressWCMPS() {\n// Use #pragma omp parallel for schedule(dynamic,64) if there are \"for\" inside the main \"for\"\n//#pragma omp parallel for schedule(dynamic,64)\n#pragma omp parallel for\n\tfor(int i=0; i<numParticles; i++) {\n\t\tdouble mi;\n\t\tif(PTYPE[i] == 1) mi = DNS_FL1;\n\t\telse mi = DNS_FL2;\n\t\t//if(particleType[i]==fluid)\n\t\t//\tmi = Dns[partType::FLUID];\n\t\t//else\n\t\t//\tmi = Dns[partType::WALL];\n\n\t\tdouble pressure = 0.0;\n\t\tif(particleBC[i] == inner) {\n\t\t// if(particleBC[i] == inner && particleType[i] == fluid)\n\t\t\tpressure = (mi*coeffPressWCMPS/gamma)*(pow(pndi[i]/pndSmallZero,gamma)-1);\n\t\t}\n\t\n//\t\tif(pndSmall[i] < pndThreshold*pndSmallZero && numNeigh[i] < neighThreshold*numNeighZero)\n//\t\t\tparticleBC[i] = surface;\n//\t\telse\n//\t\t{\n//\t\t\tparticleBC[i] = inner;\n//\t\t\tpressure = (mi*coeffPressWCMPS/gamma)*(pow(pndi[i]/pndSmallZero,gamma)-1);\n\t\t//pressure = (ni - n0) * coeffPressEMPS * mi;\n\t\t//pressure = (pndi[i] - pndSmallZero) * coeffPressEMPS * mi;\n//\t\t}\n\t\n//\t\t\tif(wallType == boundaryWallType::POLYGON) {\n//\t\t\t\tif(pndi[i] > pndThreshold*pndSmallZero){\n//\t\t\t\t\tpressure = -mi*gravityZ*(0.20 - 0.5*partDist -posZi);\n//\t\t\t\t\tpressure = -mi*gravityZ*(0.18 - 0.5*partDist -posZi); // lat\n//\t\t\t\t}\n//\t\t\t}\n//\t\telse if(wallType == boundaryWallType::PARTICLE) \n//\t\t\t\tif(pndi[i] > pndThreshold*pndSmallZero || numNeigh[i] > neighThreshold*numNeighZero) {\n//\t\t\t\t\tpressure = -mi*gravityZ*(0.20 - 0.5*partDist -posZi);\n//\t\t\t\t\tpressure = -mi*gravityZ*(0.18 - 0.5*partDist -posZi); // lat\n//\t\t\t\t}\n//\t\t\t}\n\t\t\n\t\tif(pressure < 0.0) {\n\t\t\tpressure = 0.0;\n\t\t}\n\t\tpress[i] = pressure;\n\t}\n}\n\n// Solve linear system solver PPE (mpsType = calcPressType::IMPLICIT_PND)\n// Perform conjugate gradient method on symmetry matrix A to solve Ax=b\n// matA\t\t\tsymmetric (sparse) matrix\n// sourceTerm\tvector\nvoid MpsParticle::solvePressurePoissonPnd() {\n\n\tusing T = Eigen::Triplet<double>;\n\tdouble lap_r = reL*invPartDist;\n\tint n_size = (int)(pow(lap_r * 2, dim)); // maximum number of neighbors\n\tEigen::SparseMatrix<double> matA(numParticles, numParticles); // declares a column-major sparse matrix type of double\n\tsourceTerm.resize(numParticles); // Resizing a dynamic-size matrix\n\tsourceTerm.setZero(); // Right hand side-vector set to zero\n\tvector<T> coeffs(numParticles * n_size); // list of non-zeros coefficients\n\n// Use #pragma omp parallel for schedule(dynamic,64) if there are \"for\" inside the main \"for\"\n//#pragma omp parallel for schedule(dynamic,64)\n\tfor(int i=0; i<numParticles; i++) {\n\t\tif(particleBC[i] == other || particleBC[i] == surface) {\n\t\t\tcoeffs.push_back(T(i, i, 1.0));\n\t\t\tcontinue;\n\t\t}\n\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\tdouble ni = pndSmall[i];\n\t\tdouble sum = 0.0;\n\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reL2 && (dstij2 < dstimj2 || wallType == boundaryWallType::PARTICLE)) {\n\t\t\t\tif(j != i) {\n\t\t\t\t\tdouble dst = sqrt(dstij2);\n\t\t\t\t\tdouble wL = weight(dst, reL, weightType);\n\t\t\t\t\t// coeffPPE = 2.0*dim/(pndLargeZero*lambdaZero)\n\t\t\t\t\tdouble mat_ij = wL*coeffPPE;\n\t\t\t\t\tif (particleType[j] == dummyWall) {\n\t\t\t\t\t\tdouble pgh = RHO[j]*(v0ij*gravityX + v1ij*gravityY + v2ij*gravityZ)*wL;\n\t\t\t\t\t\tsourceTerm(i) -= coeffPPE*pgh;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tsum -= mat_ij;\n\t\t\t\t\t\tif (particleBC[j] == inner) {\n\t\t\t\t\t\t\tcoeffs.push_back(T(i, j, mat_ij));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}}\n\t\t\t\t\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\n\t\tdouble density;\n\t\tif(PTYPE[i] == 1) density = DNS_FL1;\n\t\telse density = DNS_FL2;\n\n\t\t// Increase diagonal\n\t\tsum -= alphaCompressibility*density/(timeStep*timeStep);\n\n\t\t//double Cdiag = 1.0;\n\t\t//double beta = 0.9;\n\t\t//double DI2 = Cdiag*beta*coeffPPE*relaxPND*pndWallContribution[i]*density;\n\t\t//sum -= DI2;\n\n\t\tcoeffs.push_back(T(i, i, sum));\n\n\t\t//coeffPPESource = relaxPND/(timeStep*timeStep*pndSmallZero)\n\t\tsourceTerm(i) = - coeffPPESource*density*(ni - pndSmallZero);\n\n\t\t// 2019 - Enhancement of stabilization of MPS to arbitrary geometries with a generic wall boundary condition\n\t\t//double pndc = 0.0;\n\t\t//if(ni > 0)\n\t\t//\tpndc = (ni - pndWallContribution[i])/ni;\n\t\t//sourceTerm(i) = pndc*((1.0-relaxPND)*(pndki[i] - ni) + relaxPND*(pndSmallZero - pndski[i]))*ddt/pndSmallZero;\n\t\t//sourceTerm(i) = - relaxPND*ddt*(pndski[i] - pndSmallZero)/pndSmallZero;\n\n\t\t//double riw[3], riwSqrt;\n\t\t// Normal fluid-wall particle = 0.5*(normal fluid-mirror particle)\n\t\t//riw[0] = 0.5*(posXi - posMirrorXi); riw[1] = 0.5*(posYi - posMirrorYi); riw[2] = 0.5*(posZi - posMirrorZi);\n\t\t//riwSqrt = sqrt(riw[0]*riw[0] + riw[1]*riw[1] + riw[2]*riw[2]);\n\t\t//double ST1 = - coeffPPESource*density*(ni - pndSmallZero);\n\t\t//double ST2 = 0.0;\n\t\t//if(riwSqrt < 0.5*partDist)\n\t\t//\tST2 = - Cdiag*(1.0-beta)*2.0*partDist/lambdaZero*(0.5*partDist - riwSqrt)/(timeStep*timeStep);\n\t\t//sourceTerm(i) = ST1 + ST2;\n\t}\n\n\t// Finished setup matrix\n\tmatA.setFromTriplets(coeffs.begin(), coeffs.end());\n\t// Solve PPE\n\tif(solverType == solvPressType::CG)\n\t\tsolveConjugateGradient(matA);\n\telse if (solverType == solvPressType::BICGSTAB)\n\t\tsolveBiConjugateGradientStabilized(matA);\n\t// Set zero to negative pressures\n\tsetZeroOnNegativePressure();\n}\n\n// Solve linear system solver PPE (mpsType = calcPressType::IMPLICIT_PND_DIVU)\nvoid MpsParticle::solvePressurePoissonPndDivU() {\n\n\tusing T = Eigen::Triplet<double>;\n\tdouble lap_r = reL*invPartDist;\n\tint n_size = (int)(pow(lap_r * 2, dim)); // maximum number of neighbors\n\tEigen::SparseMatrix<double> matA(numParticles, numParticles); // declares a column-major sparse matrix type of double\n\tsourceTerm.resize(numParticles); // Resizing a dynamic-size matrix\n\tsourceTerm.setZero(); // Right hand side-vector set to zero\n\tvector<T> coeffs(numParticles * n_size); // list of non-zeros coefficients\n\n// Use #pragma omp parallel for schedule(dynamic,64) if there are \"for\" inside the main \"for\"\n//#pragma omp parallel for schedule(dynamic,64)\n\tfor(int i=0; i<numParticles; i++) {\n\t\tif(particleBC[i] == other || particleBC[i] == surface) {\n\t\t\tcoeffs.push_back(T(i, i, 1.0));\n\t\t\tcontinue;\n\t\t}\n\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\tdouble ni = pndSmall[i];\n\t\tdouble sum = 0.0;\n\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reL2 && (dstij2 < dstimj2 || wallType == boundaryWallType::PARTICLE)) {\n\t\t\t\tif(j != i) {\n\t\t\t\t\tdouble dst = sqrt(dstij2);\n\t\t\t\t\tdouble wL = weight(dst, reL, weightType);\n\t\t\t\t\t// coeffPPE = 2.0*dim/(pndLargeZero*lambdaZero)\n\t\t\t\t\tdouble mat_ij = wL*coeffPPE;\n\t\t\t\t\tif (particleType[j] == dummyWall) {\n\t\t\t\t\t\tdouble pgh = RHO[j]*(v0ij*gravityX + v1ij*gravityY + v2ij*gravityZ)*wL;\n\t\t\t\t\t\tsourceTerm(i) -= coeffPPE*pgh;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tsum -= mat_ij;\n\t\t\t\t\t\tif (particleBC[j] == inner) {\n\t\t\t\t\t\t\tcoeffs.push_back(T(i, j, mat_ij));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}}\n\t\t\t\t\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\n\t\tdouble density;\n\t\tif(PTYPE[i] == 1) density = DNS_FL1;\n\t\telse density = DNS_FL2;\n\n\t\t// Increase diagonal\n\t\tsum -= alphaCompressibility*density/(timeStep*timeStep);\n\n\t\t//double Cdiag = 1.0;\n\t\t//double beta = 0.9;\n\t\t//double DI2 = Cdiag*beta*coeffPPE*relaxPND*pndWallContribution[i]*density;\n\t\t//sum -= DI2;\n\n\t\tcoeffs.push_back(T(i, i, sum));\n\n\t\t//coeffPPESource = relaxPND/(timeStep*timeStep*pndSmallZero)\n\t\t//sourceTerm(i) = - coeffPPESource*density*(ni - pndSmallZero) + (1.0-relaxPND)*density*velDivergence[i]/timeStep;\n\t\tsourceTerm(i) = - coeffPPESource*density*(pndki[i] - pndSmallZero) + (1.0-relaxPND)*density*velDivergence[i]/timeStep;\n\t\t//sourceTerm(i) = - 4.0*density*(ni - pndSmallZero)/(partDist*partDist*pndSmallZero) \n\t\t//\t\t\t\t+ 2.0*density*velDivergence[i]*invPartDist;\n\n\t\t// Sun et al., 2015. Modified MPS method for the 2D fluid structure interaction problem with free surface\n\t\t////double dtPhysical = partDist/20.0;\n\t\t//double dtPhysical = timeStep;\n\t\t//double a1 = fabs(ni - pndSmallZero)/pndSmallZero;\n\t\t//if ((pndSmallZero-ni)*velDivergence[i] > 1e-6)\n\t\t//{\n\t\t//\ta1 += dtPhysical*fabs(velDivergence[i]);\n\t\t//}\n\t\t////double a2 = fabs((ni - pndSmallZero)/pndSmallZero);\n\t\t//sourceTerm(i) = - a1*density/(dtPhysical*dtPhysical)*(ni - pndSmallZero)/pndSmallZero \n\t\t//\t+ density*velDivergence[i]/dtPhysical;\n\n\t\t// 2019 - Enhancement of stabilization of MPS to arbitrary geometries with a generic wall boundary condition\n\t\t//double pndc = 0.0;\n\t\t//if(ni > 0)\n\t\t//\tpndc = (ni - pndWallContribution[i])/ni;\n\t\t//sourceTerm(i) = pndc*((1.0-relaxPND)*(pndki[i] - ni) + relaxPND*(pndSmallZero - pndski[i]))*ddt/pndSmallZero;\n\t\t//sourceTerm(i) = - relaxPND*ddt*(pndski[i] - pndSmallZero)/pndSmallZero;\n\n\t\t//double riw[3], riwSqrt;\n\t\t// normal fluid-wall particle = 0.5*(normal fluid-mirror particle)\n\t\t//riw[0] = 0.5*(posXi - posMirrorXi); riw[1] = 0.5*(posYi - posMirrorYi); riw[2] = 0.5*(posZi - posMirrorZi);\n\t\t//riwSqrt = sqrt(riw[0]*riw[0] + riw[1]*riw[1] + riw[2]*riw[2]);\n\t\t//double ST1 = - coeffPPESource*density*(ni - pndSmallZero);\n\t\t//double ST2 = 0.0;\n\t\t//if(riwSqrt < 0.5*partDist)\n\t\t//\tST2 = - Cdiag*(1.0-beta)*2.0*partDist/lambdaZero*(0.5*partDist - riwSqrt)/(timeStep*timeStep);\n\t\t//sourceTerm(i) = ST1 + ST2;\n\t}\n\n\t// Finished setup matrix\n\tmatA.setFromTriplets(coeffs.begin(), coeffs.end());\n\t// Solve PPE\n\tif(solverType == solvPressType::CG)\n\t\tsolveConjugateGradient(matA);\n\telse if (solverType == solvPressType::BICGSTAB)\n\t\tsolveBiConjugateGradientStabilized(matA);\n\t// Set zero to negative pressures\n\tsetZeroOnNegativePressure();\n}\n\n// Solve linear system using Conjugate Gradient (solverType = solvPressType::CG)\nvoid MpsParticle::solveConjugateGradient(Eigen::SparseMatrix<double> p_mat) {\n\t//Eigen::ConjugateGradient<Eigen::SparseMatrix<double>> cg;\n\tEigen::ConjugateGradient<Eigen::SparseMatrix<double>, Eigen::Lower|Eigen::Upper> cg;\n\t//cg.setTolerance(1.0e-9);\n\tcg.compute(p_mat);\n\tif (cg.info() != Eigen::ComputationInfo::Success) {\n\t\tcerr << \"Error: Failed decompostion.\" << endl;\n\t}\n\t//pressurePPE = cg.solve(sourceTerm);\n\tpressurePPE = cg.solveWithGuess(sourceTerm,pressurePPE);\n\n#pragma omp parallel for\n\tfor(int i=0; i<numParticles; i++) {\n\t\tpress[i] = pressurePPE(i);\n\t}\n\n\tif (cg.info() != Eigen::ComputationInfo::Success) {\n\t\tcerr << \"Error: Failed solving.\" << endl;\n\t}\n\tsolverIter = cg.iterations();\n\tsolverError = cg.error();\n}\n\n// Solve linear system using Bi Conjugate Gradient Stabiçized (solverType = solvPressType::BICGSTAB)\nvoid MpsParticle::solveBiConjugateGradientStabilized(Eigen::SparseMatrix<double> p_mat) {\n\tEigen::BiCGSTAB<Eigen::SparseMatrix<double>> bicg;\n\t//bicg.setTolerance(1.0e-9);\n\tbicg.compute(p_mat);\n\tif (bicg.info() != Eigen::ComputationInfo::Success) {\n\t\tcerr << \"Error: Failed decompostion.\" << endl;\n\t}\n\n\tpressurePPE = bicg.solveWithGuess(sourceTerm,pressurePPE);\n\n#pragma omp parallel for\n\tfor(int i=0; i<numParticles; i++) {\n\t\tpress[i] = pressurePPE(i);\n\t}\n\n\tif (bicg.info() != Eigen::ComputationInfo::Success) {\n\t\tcerr << \"Error: Failed solving.\" << endl;\n\t}\n\tsolverIter = bicg.iterations();\n\tsolverError = bicg.error();\n}\n\n// Set negative pressure to zero\nvoid MpsParticle::setZeroOnNegativePressure(){\n#pragma omp parallel for\n\tfor(int i=0; i<numParticles; i++) {\n\t\tif (press[i] < 0) press[i] = 0.0;\n\t}\n}\n\n// Divergence of velocity\nvoid MpsParticle::calcVelDivergence() {\n#pragma omp parallel for schedule(dynamic,64)\n\tfor(int i=0; i<numParticles; i++) {\n\t\tvelDivergence[i] = 0.0;\n\t\tif(particleType[i] == fluid) {\n\t\tdouble DivV = 0.0;\n\t\tdouble ni = pndi[i];\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble velXi = vel[i*3  ];\tdouble velYi = vel[i*3+1];\tdouble velZi = vel[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\tdouble MC[9];\n\t\tMC[0] = correcMatrixRow1[i*3];\tMC[1] = correcMatrixRow1[i*3+1];\tMC[2] = correcMatrixRow1[i*3+2];\n\t\tMC[3] = correcMatrixRow2[i*3];\tMC[4] = correcMatrixRow2[i*3+1];\tMC[5] = correcMatrixRow2[i*3+2];\n\t\tMC[6] = correcMatrixRow3[i*3];\tMC[7] = correcMatrixRow3[i*3+1];\tMC[8] = correcMatrixRow3[i*3+2];\n\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reS2 && (dstij2 < dstimj2 || wallType == boundaryWallType::PARTICLE)) {\n\t\t\t\t\tif(j != i) {\n//\t\t\t\t\t\tif(particleType[i] == fluid && particleType[j] == fluid) {\n\t\t\t\t\t\t\tdouble vijx = vel[j*3  ]-velXi;\n\t\t\t\t\t\t\tdouble vijy = vel[j*3+1]-velYi;\n\t\t\t\t\t\t\tdouble vijz = vel[j*3+2]-velZi;\n\t\t\t\t\t\t\tdouble dst = sqrt(dstij2);\n\t\t\t\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif(gradientCorrection == false) {\n\t\t\t\t\t\t\t\tif(ni > 1.0e-8) {\n\t\t\t\t\t\t\t\t\tDivV += (dim/pndSmallZero)*(pndi[j]/ni)*(vijx*v0ij+vijy*v1ij+vijz*v2ij)*wS/dstij2;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tdouble v0ijC = (v0ij*MC[0] + v1ij*MC[1] + v2ij*MC[2]);\n\t\t\t\t\t\t\t\tdouble v1ijC = (v0ij*MC[3] + v1ij*MC[4] + v2ij*MC[5]);\n\t\t\t\t\t\t\t\tdouble v2ijC = (v0ij*MC[6] + v1ij*MC[7] + v2ij*MC[8]);\n\t\t\t\t\t\t\t\tDivV += (dim/pndSmallZero)*(vijx*v0ijC+vijy*v1ijC+vijz*v2ijC)*wS/dstij2;\n\t\t\t\t\t\t\t}\n//\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\t\t\n\t\tvelDivergence[i] = DivV;\n\t}\n\t}\n}\n\n// Divergence of velocity (Polygon wall) - Free-slip\nvoid MpsParticle::calcWallSlipVelDivergence() {\n\t//int nPartNearMesh = partNearMesh.size();\n\t//printf(\" Mesh %d \\n\", nPartNearMesh);\n\t// Loop only for particles near mesh\n#pragma omp parallel for schedule(dynamic,64)\n\t//for(int im=0;im<nPartNearMesh;im++) {\n\t//int i = partNearMesh[im];\n\tfor(int i=0; i<numParticles; i++) {\n//\tif(particleType[i] == fluid) {\n\t\tdouble ni = pndi[i];\n\t\tif(particleType[i] == fluid && particleNearWall[i] == true && ni > 1.0e-8) {\n\t\t\tdouble DivV = 0.0;\n\t\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\t\tdouble velXi = vel[i*3  ];\tdouble velYi = vel[i*3+1];\tdouble velZi = vel[i*3+2];\n\t\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\t\t\n\t\t\t// Transformation matrix Rref_i = I - 2.0*normal_iwall*normal_iwall\n\t\t\tdouble Rref_i[9], normaliw[3], normalMod2;\n\t\t\t// normal fluid-wall particle = 0.5*(normal fluid-mirror particle)\n\t\t\tnormaliw[0] = 0.5*(posXi - posMirrorXi); normaliw[1] = 0.5*(posYi - posMirrorYi); normaliw[2] = 0.5*(posZi - posMirrorZi);\n\t\t\tnormalMod2 = normaliw[0]*normaliw[0] + normaliw[1]*normaliw[1] + normaliw[2]*normaliw[2];\n\t\t\tif(normalMod2 > 1.0e-8) {\n\t\t\t\tdouble normalMod = sqrt(normalMod2);\n\t\t\t\tnormaliw[0] = normaliw[0]/normalMod;\n\t\t\t\tnormaliw[1] = normaliw[1]/normalMod;\n\t\t\t\tnormaliw[2] = normaliw[2]/normalMod;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tnormaliw[0] = 0;\n\t\t\t\tnormaliw[1] = 0;\n\t\t\t\tnormaliw[2] = 0;\n\t\t\t}\n\n\t\t\t//  Transformation matrix Rref_i = I - 2.0*normal_iwall*normal_iwall\n\t\t\tRref_i[0] = 1.0 - 2.0*normaliw[0]*normaliw[0]; Rref_i[1] = 0.0 - 2.0*normaliw[0]*normaliw[1]; Rref_i[2] = 0.0 - 2.0*normaliw[0]*normaliw[2];\n\t\t\tRref_i[3] = 0.0 - 2.0*normaliw[1]*normaliw[0]; Rref_i[4] = 1.0 - 2.0*normaliw[1]*normaliw[1]; Rref_i[5] = 0.0 - 2.0*normaliw[1]*normaliw[2];\n\t\t\tRref_i[6] = 0.0 - 2.0*normaliw[2]*normaliw[0]; Rref_i[7] = 0.0 - 2.0*normaliw[2]*normaliw[1]; Rref_i[8] = 1.0 - 2.0*normaliw[2]*normaliw[2];\n\n\t\t\t// Mirror particle velocity vi' = Rref_i * vi\n\t\t\tdouble velMirrorXi = (Rref_i[0]*velXi + Rref_i[1]*velYi + Rref_i[2]*velZi);\n\t\t\tdouble velMirrorYi = (Rref_i[3]*velXi + Rref_i[4]*velYi + Rref_i[5]*velZi);\n\t\t\tdouble velMirrorZi = (Rref_i[6]*velXi + Rref_i[7]*velYi + Rref_i[8]*velZi);\n\n\t\t\tint ix, iy, iz;\n\t\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\t\tint j = firstParticleInBucket[jb];\n\t\t\t\tif(j == -1) continue;\n\t\t\t\tdouble plx, ply, plz;\n\t\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\t\twhile(true) {\n\t\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\t\n\t\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t\t// If j is inside the neighborhood of i and im (intersection) and \n\t\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\t\tif(dstij2 < reS2 && dstimj2 < reS2 && dstij2 < dstimj2) {\n\t\t\t\t\t\tif(j != i) {\n\t\t\t\t\t\t\tdouble dst = sqrt(dstimj2);\n\t\t\t\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\t\t\t\tdouble vijx = vel[j*3  ]-velMirrorXi;\n\t\t\t\t\t\t\tdouble vijy = vel[j*3+1]-velMirrorYi;\n\t\t\t\t\t\t\tdouble vijz = vel[j*3+2]-velMirrorZi;\n\t\t\t\t\t\t\tDivV += (dim/pndSmallZero)*(pndi[j]/ni)*(vijx*v0imj+vijy*v1imj+vijz*v2imj)*wS/dstimj2;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\t\tif(j == -1) break;\n\t\t\t\t}\n\t\t\t}}}\n\n\t\t\t// Add \"i\" contribution (\"i\" is a neighbor of \"mirror i\")\n\t\t\tdouble v0imi, v1imi, v2imi, dstimi2;\n\t\t\tsqrDistBetweenParticles(i, posMirrorXi, posMirrorYi, posMirrorZi, v0imi, v1imi, v2imi, dstimi2);\n\t\t\t\n\t\t\tif(dstimi2 < reS2) {\n\t\t\t\tdouble dst = sqrt(dstimi2);\n\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\tdouble vijx = velXi-velMirrorXi;\n\t\t\t\tdouble vijy = velYi-velMirrorYi;\n\t\t\t\tdouble vijz = velZi-velMirrorZi;\n\t\t\t\tDivV += (dim/pndSmallZero)*(pndi[i]/ni)*(vijx*v0imi+vijy*v1imi+vijz*v2imi)*wS/dstimi2;\n\t\t\t}\n\n\t\t\tvelDivergence[i] += DivV;\n\t\t}\n\t}\n}\n\n\n// Divergence of velocity (Polygon wall) - No-slip\nvoid MpsParticle::calcWallNoSlipVelDivergence() {\n\t//int nPartNearMesh = partNearMesh.size();\n\t//printf(\" Mesh %d \\n\", nPartNearMesh);\n\t// Loop only for particles near mesh\n#pragma omp parallel for schedule(dynamic,64)\n\t//for(int im=0;im<nPartNearMesh;im++) {\n\t//int i = partNearMesh[im];\n\tfor(int i=0; i<numParticles; i++) {\n\t\tdouble ni = pndi[i];\n\t\t//if(particleType[i] == fluid && ni > 1.0e-8) {\n\t\tif(particleType[i] == fluid && particleNearWall[i] == true && ni > 1.0e-8) {\n\t//\tif(particleType[i] == fluid) {\n\t\t\tdouble DivV = 0.0;\n\t\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\t\tdouble velXi = vel[i*3  ];\tdouble velYi = vel[i*3+1];\tdouble velZi = vel[i*3+2];\n\t\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\n\t\t\t// Inverse matrix Rinv_i = - I\n\t\t\tdouble Rinv_i[9], Rref_i[9], normaliw[3], normalMod2;\n\t\t\t// normal fluid-wall particle = 0.5*(normal fluid-mirror particle)\n\t\t\tnormaliw[0] = 0.5*(posXi - posMirrorXi); normaliw[1] = 0.5*(posYi - posMirrorYi); normaliw[2] = 0.5*(posZi - posMirrorZi);\n\t\t\tnormalMod2 = normaliw[0]*normaliw[0] + normaliw[1]*normaliw[1] + normaliw[2]*normaliw[2];\n\t\t\tif(normalMod2 > 1.0e-8) {\n\t\t\t\tdouble normalMod = sqrt(normalMod2);\n\t\t\t\tnormaliw[0] = normaliw[0]/normalMod;\n\t\t\t\tnormaliw[1] = normaliw[1]/normalMod;\n\t\t\t\tnormaliw[2] = normaliw[2]/normalMod;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tnormaliw[0] = 0;\n\t\t\t\tnormaliw[1] = 0;\n\t\t\t\tnormaliw[2] = 0;\n\t\t\t}\n\n\t\t\t//  Inverse transformation matrix Rinv_i = - I\n\t\t\tRinv_i[0] = -1.0; Rinv_i[1] =  0.0; Rinv_i[2] =  0.0;\n\t\t\tRinv_i[3] =  0.0; Rinv_i[4] = -1.0; Rinv_i[5] =  0.0;\n\t\t\tRinv_i[6] =  0.0; Rinv_i[7] =  0.0; Rinv_i[8] = -1.0;\n\n\t\t\t//  Transformation matrix Rref_i = I - 2.0*normal_iwall*normal_iwall\n\t\t\tRref_i[0] = 1.0 - 2.0*normaliw[0]*normaliw[0]; Rref_i[1] = 0.0 - 2.0*normaliw[0]*normaliw[1]; Rref_i[2] = 0.0 - 2.0*normaliw[0]*normaliw[2];\n\t\t\tRref_i[3] = 0.0 - 2.0*normaliw[1]*normaliw[0]; Rref_i[4] = 1.0 - 2.0*normaliw[1]*normaliw[1]; Rref_i[5] = 0.0 - 2.0*normaliw[1]*normaliw[2];\n\t\t\tRref_i[6] = 0.0 - 2.0*normaliw[2]*normaliw[0]; Rref_i[7] = 0.0 - 2.0*normaliw[2]*normaliw[1]; Rref_i[8] = 1.0 - 2.0*normaliw[2]*normaliw[2];\n\n\t\t\tdouble viwall[3], vtil[3];\n\t\t\t// Wall velocity (0 if fixed)\n\t\t\tviwall[0]=viwall[1]=viwall[2]=0.0;\n\n\t\t\tif(nearMeshType[i] == meshType::FORCED) {\n\t\t\t\tviwall[0] = velVWall[0];\n\t\t\t\tviwall[1] = velVWall[1];\n\t\t\t\tviwall[2] = velVWall[2];\n\t\t\t}\n\n\t\t\t// normal_iwall*v_iwall\n\t\t\tdouble dotnv = normaliw[0]*viwall[0] + normaliw[1]*viwall[1] + normaliw[2]*viwall[2];\n\t\t\t// vtil = vi - 2 {v_iwall - (normal_iwall*v_iwall)normal_iwall}\n\t\t\tvtil[0] = velXi - 2.0*(viwall[0] - dotnv*normaliw[0]);\n\t\t\tvtil[1] = velYi - 2.0*(viwall[1] - dotnv*normaliw[1]);\n\t\t\tvtil[2] = velZi - 2.0*(viwall[2] - dotnv*normaliw[2]);\n\t\t\t// Mirror particle velocity vi' = Rinv_i * [vi - 2 {v_iwall - (normal_iwall*v_iwall)normal_iwall}] \n\t\t\tdouble velMirrorXi = (Rinv_i[0]*vtil[0] + Rinv_i[1]*vtil[1] + Rinv_i[2]*vtil[2]);\n\t\t\tdouble velMirrorYi = (Rinv_i[3]*vtil[0] + Rinv_i[4]*vtil[1] + Rinv_i[5]*vtil[2]);\n\t\t\tdouble velMirrorZi = (Rinv_i[6]*vtil[0] + Rinv_i[7]*vtil[1] + Rinv_i[8]*vtil[2]);\n\n\t\t\tint ix, iy, iz;\n\t\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\t\tint j = firstParticleInBucket[jb];\n\t\t\t\tif(j == -1) continue;\n\t\t\t\tdouble plx, ply, plz;\n\t\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\t\twhile(true) {\n\t\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\t\n\t\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t\t// If j is inside the neighborhood of i and im (intersection) and \n\t\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\t\tif(dstij2 < reS2 && dstimj2 < reS2 && dstij2 < dstimj2) {\n\t\t\t\t\t\tif(j != i) {\n\t\t\t\t\t\t\tdouble dst = sqrt(dstimj2);\n\t\t\t\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\t\t\t\tdouble vijx = -(vel[j*3  ]-velMirrorXi);\n\t\t\t\t\t\t\tdouble vijy = -(vel[j*3+1]-velMirrorYi);\n\t\t\t\t\t\t\tdouble vijz = -(vel[j*3+2]-velMirrorZi);\n\t\t\t\t\t\t\t// Refelected rij' = Rref_i * ri'j\n\t\t\t\t\t\t\tdouble v0m = (Rref_i[0]*v0imj + Rref_i[1]*v1imj + Rref_i[2]*v2imj);\n\t\t\t\t\t\t\tdouble v1m = (Rref_i[3]*v0imj + Rref_i[4]*v1imj + Rref_i[5]*v2imj);\n\t\t\t\t\t\t\tdouble v2m = (Rref_i[6]*v0imj + Rref_i[7]*v1imj + Rref_i[8]*v2imj);\n\t\t\t\t\t\t\tDivV += (dim/pndSmallZero)*(pndi[j]/ni)*(vijx*v0m+vijy*v1m+vijz*v2m)*wS/dstimj2;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\t\tif(j == -1) break;\n\t\t\t\t\t}\n\t\t\t}}}\n\n\t\t\t// Add \"i\" contribution (\"i\" is a neighbor of \"mirror i\")\n\t\t\tdouble v0imi, v1imi, v2imi, dstimi2;\n\t\t\tsqrDistBetweenParticles(i, posMirrorXi, posMirrorYi, posMirrorZi, v0imi, v1imi, v2imi, dstimi2);\n\t\t\t\n\t\t\tif(dstimi2 < reS2) {\n\t\t\t\tdouble dst = sqrt(dstimi2);\n\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\tdouble vijx = -(velXi-velMirrorXi);\n\t\t\t\tdouble vijy = -(velYi-velMirrorYi);\n\t\t\t\tdouble vijz = -(velZi-velMirrorZi);\n\t\t\t\t// Refelected rij' = Rref_i * ri'j\n\t\t\t\tdouble v0m = (Rref_i[0]*v0imi + Rref_i[1]*v1imi + Rref_i[2]*v2imi);\n\t\t\t\tdouble v1m = (Rref_i[3]*v0imi + Rref_i[4]*v1imi + Rref_i[5]*v2imi);\n\t\t\t\tdouble v2m = (Rref_i[6]*v0imi + Rref_i[7]*v1imi + Rref_i[8]*v2imi);\n\t\t\t\tDivV += (dim/pndSmallZero)*(pndi[i]/ni)*(vijx*v0m+vijy*v1m+vijz*v2m)*wS/dstimi2;\n\t\t\t}\n\n\t\t\tvelDivergence[i] += DivV;\n\t\t}\n\t}\n}\n\n\n// Extrapolate pressure to wall and dummy particles\nvoid MpsParticle::extrapolatePressParticlesWallDummy() {\n#pragma omp parallel for schedule(dynamic,64)\n\tfor(int i=0; i<numParticles; i++) {\n\t\tif(particleType[i] == dummyWall || (mpsType == calcPressType::WEAKLY && particleType[i] == wall)) {\n\t\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\t\tdouble ni = 0.0;\n\t\t\tdouble pressure = 0.0;\n\t\t\t\n\t\t\tint ix, iy, iz;\n\t\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\t\tint j = firstParticleInBucket[jb];\n\t\t\t\tif(j == -1) continue;\n\t\t\t\tdouble plx, ply, plz;\n\t\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\t\twhile(true) {\n\t\t\t\t\tdouble v0ij, v1ij, v2ij, dstij2;\n\t\t\t\t\t\n\t\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\n\t\t\t\t\tif(dstij2 < reS2) {\n\t//\t\t\t\tif(j != i) {\n\t\t\t\t\t\tif(j != i && particleType[j] == fluid) {\n\t\t\t\t\t\t\tdouble dst = sqrt(dstij2);\n\t\t\t\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\t\t\t\tni += wS;\n\t\t\t\t\t\t\tpressure += (press[j] - RHO[j]*(gravityX*v0ij+gravityY*v1ij+gravityZ*v2ij))*wS;\n\t\t\t\t\t\t\t//pressure += (press[j] + RHO[j]*(gravityX*v0ij+gravityY*v1ij+gravityZ*v2ij))*wS;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\t\tif(j == -1) break;\n\t\t\t\t}\n\t\t\t}}}\n\t\t\tif(pressure < 0.0)\n\t\t\t\tpressure = 0.0;\n\t\t\tif(ni > 0)\n\t\t\t\tpress[i] = pressure/ni;\n\t\t\telse\n\t\t\t\tpress[i] = pressure;\n\t\t}\n\t}\n}\n\n// Extrapolate pressure to inner particles near polygon walls\nvoid MpsParticle::extrapolatePressParticlesNearPolygonWall() {\n\t//int nPartNearMesh = partNearMesh.size();\n\t//printf(\" Mesh %d \\n\", nPartNearMesh);\n\t// Loop only for particles near mesh\n#pragma omp parallel for schedule(dynamic,64)\n\t//for(int im=0;im<nPartNearMesh;im++) {\n\t//int i = partNearMesh[im];\n\tfor(int i=0; i<numParticles; i++) {\n\t//if(particleType[i] == fluid && press[i] == 0 /*&& particleNearWall[i] == true*/) {\n\t\tif(particleType[i] == fluid && press[i] == 0 && particleNearWall[i] == true) {\n\t\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\t\tdouble pressure = 0.0;\n\t\t\tdouble sumWij = 0.0;\n\t\t\tint nTotal = 0;\n\t\t\tint nFree = 0;\n\t\t\t\n\t\t\tint ix, iy, iz;\n\t\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\t\tint j = firstParticleInBucket[jb];\n\t\t\t\tif(j == -1) continue;\n\t\t\t\tdouble plx, ply, plz;\n\t\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\t\twhile(true) {\n\t\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\t\n\t\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\t\tif(dstij2 < reS2 && dstij2 < dstimj2) {\n\t//\t\t\t\tif(dstij2 < 1.2*partDist) {\n\t\t\t\t\t\tif(j != i) {\n\t\t\t\t\t\t\tdouble dst = sqrt(dstij2);\n\t\t\t\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t//\t\t\t\t\tdouble wS = WEI_WEND(dst, 1.2*partDist);\n\t\t\t\t\t\t\tsumWij += wS;\n\t\t//\t\t\t\t\tpressure += press[j]*wS;\n\t\t\t\t\t\t\tpressure += (press[j] - RHO[j]*(gravityX*v0ij+gravityY*v1ij+gravityZ*v2ij))*wS;\n\t\t\t\t\t\t\tnTotal += 1;\n\t\t\t\t\t\t\tif(particleBC[j] == surface)\n\t\t\t\t\t\t\t\tnFree += 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\t\tif(j == -1) break;\n\t\t\t\t}\n\t\t\t}}}\n\t\t\t\n\t\t\tif(nTotal > 0)\n\t\t\t\tnumNeighborsSurfaceParticles[i] = double(nFree)/nTotal;\n\t\t\telse\n\t\t\t\tnumNeighborsSurfaceParticles[i] = 1.0;\n\n\t//\t\tif(numNeighborsSurfaceParticles[i]<=0.5){\n\t\t\tif(pressure > 0) {\n\t\t  \t\tif(sumWij > 1.0e-8)\n\t\t\t\t\tpress[i] = pressure/sumWij;\n\t\t\t\telse\n\t\t\t\t\tpress[i] = pressure;\n\t\t\t}\n\t//\t\t}\n\t\t}\n\t}\n}\n\n// Determinant of matrix\ndouble MpsParticle::detMatrix(double M11, double M12, double M13, double M21, double M22, double M23, double M31, double M32, double M33) {\n\treturn (M11*M22*M33 + M12*M23*M31 + M13*M21*M32)\n\t\t\t- (M13*M22*M31 + M12*M21*M33 + M11*M23*M32);\n}\n\n// Inverse of matrix\nint MpsParticle::inverseMatrix(int dim, double &M11, double &M12, double &M13, double &M21, double &M22, double &M23, double &M31, double &M32, double &M33) {\n\tdouble M[3][3], Maux[3][3];\n\n\tMaux[0][0] = M11;\tMaux[0][1] = M12;\tMaux[0][2] = M13;\n\tMaux[1][0] = M21;\tMaux[1][1] = M22;\tMaux[1][2] = M23;\n\tMaux[2][0] = M31;\tMaux[2][1] = M32;\tMaux[2][2] = M33;\n\n\tif(dim == 2) {\n\t\tMaux[0][2] = Maux[1][2] = Maux[2][0] = Maux[2][1] = 0.0;\n\t\tMaux[2][2] = 1.0;\n\t}\n\n\t// Convert matrix to identity\n\tfor(int i = 0; i < 3; i++)\n\tfor(int j = 0; j < 3; j++) {\n\t\tif(i == j) M[i][j] = 1.0;\n\t\telse M[i][j] = 0.0;\n\t}\n\n\tdouble detM = detMatrix(Maux[0][0], Maux[0][1], Maux[0][2],\n\t\t\t\t\t\t\tMaux[1][0], Maux[1][1], Maux[1][2],\n\t\t\t\t\t\t\tMaux[2][0], Maux[2][1], Maux[2][2]);\n\tif(detM <= 1.0e-8) {\n\t\tM11 = 1.0;\tM12 = 0.0;\tM13 = 0.0;\n\t\tM21 = 0.0;\tM22 = 1.0;\tM23 = 0.0;\n\t\tM31 = 0.0;\tM32 = 0.0;\tM33 = 1.0;\n\t\treturn 0;\n\t}\n\n\tfor(int k = 0; k < dim; k++) {\n\n\t\t/*if(fabs(Maux[k][k]) <= 1.0e-8) {\n\t\t\tM11 = 1.0;\tM12 = 0.0;\tM13 = 0.0;\n\t\t\tM21 = 0.0;\tM22 = 1.0;\tM23 = 0.0;\n\t\t\tM31 = 0.0;\tM32 = 0.0;\tM33 = 1.0;\n\t\t\treturn 0;\n\t\t}*/\n\n\t\tfor(int i = 0; i < dim; i++) {\n\t\t\tif(i == k) continue;\n\n\t\t\tdouble m = Maux[i][k]/Maux[k][k];\n\n\t\t\tfor(int j = 0; j < dim; j++) {\n\t\t\t\tMaux[i][j] -= m*Maux[k][j];\n\t\t\t\tM[i][j] -= m*M[k][j];\n\t\t\t}\n\t\t}\n\t}\n\n\tfor(int i = 0; i < dim; i++)\n\t\tfor(int j = 0; j < dim; j++)\n\t\t\tM[i][j] /= Maux[i][i];\n\n\tM11 = M[0][0];\tM12 = M[0][1];\tM13 = M[0][2];\n\tM21 = M[1][0];\tM22 = M[1][1];\tM23 = M[1][2];\n\tM31 = M[2][0];\tM32 = M[2][1];\tM33 = M[2][2];\n\n\treturn 1;\n}\n\n// Correction matrix\nvoid MpsParticle::correctionMatrix() {\n#pragma omp parallel for schedule(dynamic,64)\n\tfor(int i=0; i<numParticles; i++) {\n//\tif(particleType[i] == fluid) {\n\t\tcorrecMatrixRow1[i*3  ] = 0.0; correcMatrixRow1[i*3+1] = 0.0; correcMatrixRow1[i*3+2] = 0.0;\n\t\tcorrecMatrixRow2[i*3  ] = 0.0; correcMatrixRow2[i*3+1] = 0.0; correcMatrixRow2[i*3+2] = 0.0;\n\t\tcorrecMatrixRow3[i*3  ] = 0.0; correcMatrixRow3[i*3+1] = 0.0; correcMatrixRow3[i*3+2] = 0.0;\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\t\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reS2 && (dstij2 < dstimj2 || wallType == boundaryWallType::PARTICLE)) {\n\t\t\t\tif(j != i) {\n\t\t\t\t\tdouble dst = sqrt(dstij2);\n\t\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\t\tdouble invDstij2 = 1.0/dstij2;\n\t\t\t\t\tcorrecMatrixRow1[i*3  ] += wS*v0ij*v0ij*invDstij2;\tcorrecMatrixRow1[i*3+1] += wS*v0ij*v1ij*invDstij2;\tcorrecMatrixRow1[i*3+2] += wS*v0ij*v2ij*invDstij2;\n\t\t\t\t\tcorrecMatrixRow2[i*3  ] += wS*v1ij*v0ij*invDstij2;\tcorrecMatrixRow2[i*3+1] += wS*v1ij*v1ij*invDstij2;\tcorrecMatrixRow2[i*3+2] += wS*v1ij*v2ij*invDstij2;\n\t\t\t\t\tcorrecMatrixRow3[i*3  ] += wS*v2ij*v0ij*invDstij2;\tcorrecMatrixRow3[i*3+1] += wS*v2ij*v1ij*invDstij2;\tcorrecMatrixRow3[i*3+2] += wS*v2ij*v2ij*invDstij2;\n\t\t\t\t}}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\n\t\t// coeffPressGrad is a negative cte (-dim/noGrad)\n\t\tcorrecMatrixRow1[i*3  ] *= -coeffPressGrad;\tcorrecMatrixRow1[i*3+1] *= -coeffPressGrad;\tcorrecMatrixRow1[i*3+2] *= -coeffPressGrad;\n\t\tcorrecMatrixRow2[i*3  ] *= -coeffPressGrad;\tcorrecMatrixRow2[i*3+1] *= -coeffPressGrad;\tcorrecMatrixRow2[i*3+2] *= -coeffPressGrad;\n\t\tcorrecMatrixRow3[i*3  ] *= -coeffPressGrad;\tcorrecMatrixRow3[i*3+1] *= -coeffPressGrad;\tcorrecMatrixRow3[i*3+2] *= -coeffPressGrad;\n\n\t\t// Inverse of the matrix\n\t\tint rcv = inverseMatrix((int)(dim),\tcorrecMatrixRow1[i*3],correcMatrixRow1[i*3+1],correcMatrixRow1[i*3+2],\n\t\t\t\t\t\t\t\t\t\t\tcorrecMatrixRow2[i*3],correcMatrixRow2[i*3+1],correcMatrixRow2[i*3+2],\n\t\t\t\t\t\t\t\t\t\t\tcorrecMatrixRow3[i*3],correcMatrixRow3[i*3+1],correcMatrixRow3[i*3+2]);\n\n\t\tif(numNeigh[i] < 4) {\n\t\t\tcorrecMatrixRow1[i*3  ] = 1.0;\tcorrecMatrixRow1[i*3+1] = 0.0;\tcorrecMatrixRow1[i*3+2] = 0.0;\n\t\t\tcorrecMatrixRow2[i*3  ] = 0.0;\tcorrecMatrixRow2[i*3+1] = 1.0;\tcorrecMatrixRow2[i*3+2] = 0.0;\n\t\t\tcorrecMatrixRow3[i*3  ] = 0.0;\tcorrecMatrixRow3[i*3+1] = 0.0;\tcorrecMatrixRow3[i*3+2] = 1.0;\n\t\t}\n\n//\t\tif(i == 200) {\n//\t\t\tprintf(\"\\n X %e %e %e \", correcMatrixRow1[i*3  ], correcMatrixRow1[i*3+1], correcMatrixRow1[i*3+2]);\n//\t\t\tprintf(\"\\n Y %e %e %e \", correcMatrixRow2[i*3  ], correcMatrixRow2[i*3+1], correcMatrixRow2[i*3+2]);\n//\t\t\tprintf(\"\\n Z %e %e %e \\n\", correcMatrixRow3[i*3  ], correcMatrixRow3[i*3+1], correcMatrixRow3[i*3+2]);\n//\t\t}\n\t}\n}\n\n// Acceleration due to pressure gradient\nvoid MpsParticle::calcPressGradient() {\n#pragma omp parallel for schedule(dynamic,64)\n\tfor(int i=0; i<numParticles; i++) {\n//\tif(particleType[i] == fluid) {\n\t\tdouble accX = 0.0;\t\t\tdouble accY = 0.0;\t\t\tdouble accZ = 0.0;\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\tdouble pressMin = press[i];\n\t\tdouble Pi = press[i];\n\t\tdouble ni = pndi[i];\n\t\tdouble MC[9];\n\t\tMC[0] = correcMatrixRow1[i*3];\tMC[1] = correcMatrixRow1[i*3+1];\tMC[2] = correcMatrixRow1[i*3+2];\n\t\tMC[3] = correcMatrixRow2[i*3];\tMC[4] = correcMatrixRow2[i*3+1];\tMC[5] = correcMatrixRow2[i*3+2];\n\t\tMC[6] = correcMatrixRow3[i*3];\tMC[7] = correcMatrixRow3[i*3+1];\tMC[8] = correcMatrixRow3[i*3+2];\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tif(gradientType == 0 || gradientType == 2) {\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reS2 && (dstij2 < dstimj2 || wallType == boundaryWallType::PARTICLE)) {\n\t\t\t\tif(j != i) {\n\t\t\t\t\tif(pressMin > press[j]) pressMin = press[j];\n\t\t\t\t}}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}}\n\t\t\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reS2 && (dstij2 < dstimj2 || wallType == boundaryWallType::PARTICLE)) {\n\t\t\t\tif(j != i) {\n\t\t\t\t\tdouble dst = sqrt(dstij2);\n\t\t\t\t\tdouble wS = weightGradient(dst, reS, weightType);\n\t\t\t\t\tif(gradientType == 0)\n\t\t\t\t\t\twS *= (press[j] - pressMin)/dstij2;\n\t\t\t\t\telse if(gradientType == 1)\n\t\t\t\t\t\twS *= (press[j] + Pi)/dstij2;\n\t\t\t\t\telse if(gradientType == 2)\n\t\t\t\t\t\twS *= (press[j] + Pi - 2.0*pressMin)/dstij2;\n\t\t\t\t\telse if(gradientType == 3) {\n\t\t\t\t\t\tdouble nj = pndi[j];\n\t\t\t\t\t\tif(ni > 1.0e-8 && nj > 1.0e-8)\n\t\t\t\t\t\t\twS *= (ni*press[j]/nj + nj*Pi/ni)/dstij2;\n\t\t\t\t\t}\n\t\t\t\t\tif(gradientCorrection == false) {\n\t\t\t\t\t\taccX += v0ij*wS;\taccY += v1ij*wS;\taccZ += v2ij*wS;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\taccX += (v0ij*MC[0] + v1ij*MC[1] + v2ij*MC[2])*wS;\n\t\t\t\t\t\taccY += (v0ij*MC[3] + v1ij*MC[4] + v2ij*MC[5])*wS;\n\t\t\t\t\t\taccZ += (v0ij*MC[6] + v1ij*MC[7] + v2ij*MC[8])*wS;\n\t\t\t\t\t}\n\t\t\t\t}}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\t\t// coeffPressGrad is a negative cte (-dim/noGrad)\n\t\t// Original\n//\t\tacc[i*3  ]=relaxPress*accX*invDns[partType::FLUID]*coeffPressGrad;\n//\t\tacc[i*3+1]=relaxPress*accY*invDns[partType::FLUID]*coeffPressGrad;\n//\t\tacc[i*3+2]=relaxPress*accZ*invDns[partType::FLUID]*coeffPressGrad;\n\t\t// Modified\n\t\tacc[i*3  ]=relaxPress*accX*coeffPressGrad/RHO[i];\n\t\tacc[i*3+1]=relaxPress*accY*coeffPressGrad/RHO[i];\n\t\tacc[i*3+2]=relaxPress*accZ*coeffPressGrad/RHO[i];\n\t\t/*if(gradientCorrection == false) {\n\t\t\tacc[i*3  ]=relaxPress*accX*coeffPressGrad/RHO[i];\n\t\t\tacc[i*3+1]=relaxPress*accY*coeffPressGrad/RHO[i];\n\t\t\tacc[i*3+2]=relaxPress*accZ*coeffPressGrad/RHO[i];\n\t\t}\n\t\telse {\n\t\t//\tif(correcMatrixRow1[1*3] > 1.0) {\n\t\t//\t\tprintf(\"\\n X %e %e %e \", correcMatrixRow1[i*3  ], correcMatrixRow1[i*3+1], correcMatrixRow1[i*3+2]);\n\t\t//\t\tprintf(\"\\n Y %e %e %e \", correcMatrixRow2[i*3  ], correcMatrixRow2[i*3+1], correcMatrixRow2[i*3+2]);\n\t\t//\t\tprintf(\"\\n Z %e %e %e \\n\", correcMatrixRow3[i*3  ], correcMatrixRow3[i*3+1], correcMatrixRow3[i*3+2]);\n\t\t\t//}\n\t\t\tacc[i*3  ]=(relaxPress*coeffPressGrad/RHO[i])*(accX*correcMatrixRow1[i*3] + accY*correcMatrixRow1[i*3+1] + accZ*correcMatrixRow1[i*3+2]);\n\t\t\tacc[i*3+1]=(relaxPress*coeffPressGrad/RHO[i])*(accX*correcMatrixRow2[i*3] + accY*correcMatrixRow2[i*3+1] + accZ*correcMatrixRow2[i*3+2]);\n\t\t\tacc[i*3+2]=(relaxPress*coeffPressGrad/RHO[i])*(accX*correcMatrixRow3[i*3] + accY*correcMatrixRow3[i*3+1] + accZ*correcMatrixRow3[i*3+2]);\n\t\t}*/\n\t}\n}\n\n// Acceleration due to pressure gradient (Polygon wall)\nvoid MpsParticle::calcWallPressGradient() {\n\t//int nPartNearMesh = partNearMesh.size();\n\tdouble VolumeForce = pow(partDist,dim);\n\t// Maximum velocity is the minimum of the computed and expected maximum velocities\n\tdouble maxVelocity = min(velMax, expectMaxVelocity);\n\tdouble velMax2 = maxVelocity*maxVelocity;\n\t//printf(\" Mesh %d \\n\", nPartNearMesh);\n\t// Loop only for particles near mesh\n#pragma omp parallel for schedule(dynamic,64)\n\t//for(int im=0;im<nPartNearMesh;im++) {\n\t//int i = partNearMesh[im];\n\tfor(int i=0; i<numParticles; i++) {\n\n\t//particleNearWall[i]=true; // Only to show particles near polygon\n\t\n\t//if(particleType[i] == fluid) {\n\tif(particleType[i] == fluid && particleNearWall[i] == true) {\n\t\tdouble accX = 0.0;\t\t\tdouble accY = 0.0;\t\t\tdouble accZ = 0.0;\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\tdouble pressMin = press[i];\n\t\tdouble Pi = press[i];\n\t\tdouble ni = pndi[i];\n\t\t// Wall gradient Mitsume`s model\n\t\tdouble Rref_i[9], normaliw[3], normaliwSqrt;\n\t\t// normal fluid-wall particle = 0.5*(normal fluid-mirror particle)\n\t\tnormaliw[0] = 0.5*(posXi - posMirrorXi); normaliw[1] = 0.5*(posYi - posMirrorYi); normaliw[2] = 0.5*(posZi - posMirrorZi);\n\t\tnormaliwSqrt = sqrt(normaliw[0]*normaliw[0] + normaliw[1]*normaliw[1] + normaliw[2]*normaliw[2]);\n\n\t\tif(normaliwSqrt > 1.0e-8) {\n\t\t\tnormaliw[0] = normaliw[0]/normaliwSqrt;\n\t\t\tnormaliw[1] = normaliw[1]/normaliwSqrt;\n\t\t\tnormaliw[2] = normaliw[2]/normaliwSqrt;\n\t\t}\n\t\telse {\n\t\t\tnormaliw[0] = 0;\n\t\t\tnormaliw[1] = 0;\n\t\t\tnormaliw[2] = 0;\n\t\t}\n\n\t\t//  Transformation matrix Rref_i = I - 2.0*normal_iwall*normal_iwall\n\t\tRref_i[0] = 1.0 - 2.0*normaliw[0]*normaliw[0]; Rref_i[1] = 0.0 - 2.0*normaliw[0]*normaliw[1]; Rref_i[2] = 0.0 - 2.0*normaliw[0]*normaliw[2];\n\t\tRref_i[3] = 0.0 - 2.0*normaliw[1]*normaliw[0]; Rref_i[4] = 1.0 - 2.0*normaliw[1]*normaliw[1]; Rref_i[5] = 0.0 - 2.0*normaliw[1]*normaliw[2];\n\t\tRref_i[6] = 0.0 - 2.0*normaliw[2]*normaliw[0]; Rref_i[7] = 0.0 - 2.0*normaliw[2]*normaliw[1]; Rref_i[8] = 1.0 - 2.0*normaliw[2]*normaliw[2];\n\n\t\t// Taylor pressure Pj\n\t\tdouble Rai[3];\n\t\tRai[0] = Rref_i[0]*accStar[i*3] + Rref_i[1]*accStar[i*3+1] + Rref_i[2]*accStar[i*3+2];\n\t\tRai[1] = Rref_i[3]*accStar[i*3] + Rref_i[4]*accStar[i*3+1] + Rref_i[5]*accStar[i*3+2];\n\t\tRai[2] = Rref_i[6]*accStar[i*3] + Rref_i[7]*accStar[i*3+1] + Rref_i[8]*accStar[i*3+2];\n\n\t\t// if(i == 16107)\n\t\t// {\n\t\t// \tprintf(\"\\ni:%5d timeCurrent: %lf / Rref_i: \", i, timeCurrent);\n\t\t// \tfor(int rr=0; rr<9; rr++)\n\t\t// \t\tprintf(\"%lf \", Rref_i[rr]);\n\t\t// \tprintf(\"\\ni:%5d timeCurrent: %lf / Rai: \", i, timeCurrent);\n\t\t// \tfor(int rr=0; rr<3; rr++)\n\t\t// \t\tprintf(\"%lf \", Rai[rr]);\n\t\t// \tprintf(\"\\ni:%5d timeCurrent: %lf / ai: %lf, %lf, %lf\", i, timeCurrent, accStar[i*3], accStar[i*3+1], accStar[i*3+2]);\n\t\t\t\n\t\t// }\n\t\t\t\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tif(gradientType == 0 || gradientType == 2) {\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reS2 && dstij2 < dstimj2) {\n\t\t\t\tif(j != i) {\n\t\t\t\t\tif(pressMin > press[j]) pressMin = press[j];\n\t\t\t\t}}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}}\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and im (intersection) and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reS2 && dstimj2 < reS2 && dstij2 < dstimj2) {\n\t\t\t\tif(j != i) {\n\n\t\t\t\t\tdouble dst = sqrt(dstimj2);\n\t\t\t\t\tdouble wS = weightGradient(dst, reS, weightType);\n\n\t\t\t\t\t// Taylor pressure Pj\n\t\t\t\t\tdouble Pj = Pi + RHO[i]*(Rai[0]*v0imj + Rai[1]*v1imj + Rai[2]*v2imj);\n\t\t\t\t\tPj = press[j];\n\n\t\t\t\t\t// if(i == 16107)\n\t\t\t\t\t// \tprintf(\"\\ni:%5d j:%5d timeCurrent: %lf / Pj: %lf / Pi: %lf / Zj: %lf / Zi: %lf\", i, j, timeCurrent, Pj, Pi, pos[j*3+2], posMirrorZi);\n\n\t\t\t\t\tif(gradientType == 0)\n\t\t\t\t\t\twS *= (Pj - pressMin)/dstimj2;//(press[j] - pressMin)/dstimj2\n\t\t\t\t\telse if(gradientType == 1)\n\t\t\t\t\t\twS *= (Pj + Pi)/dstimj2;//(press[j] + press[i])/dstimj2\n\t\t\t\t\telse if(gradientType == 2)\n\t\t\t\t\t\twS *= (Pj + Pi - 2.0*pressMin)/dstimj2;//(press[j] + press[i] - 2.0*pressMin)/dstimj2\n\t\t\t\t\telse if(gradientType == 3) {\n\t\t\t\t\t\tdouble nj = pndi[j];\n\t\t\t\t\t\tif(ni > 1.0e-8 && nj > 1.0e-8)\n\t\t\t\t\t\t\twS *= (ni*Pj/nj + nj*Pi/ni)/dstimj2;\n\t\t\t\t\t}\n\t\t\t\t\taccX += v0imj*wS;\taccY += v1imj*wS;\taccZ += v2imj*wS;\n\t\t\t\t}}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\t\t// Add \"i\" contribution (\"i\" is a neighbor of \"mirror i\")\n\t\tdouble v0imi, v1imi, v2imi, dstimi2;\n\t\tsqrDistBetweenParticles(i, posMirrorXi, posMirrorYi, posMirrorZi, v0imi, v1imi, v2imi, dstimi2);\n\t  \t\n\t\tif(dstimi2 < reS2) {\n\n\t\t\tdouble dst = sqrt(dstimi2);\n\t\t\tdouble wS = weightGradient(dst, reS, weightType);\n\n\t\t\t// Taylor pressure Pj\n\t\t\tdouble Pj = Pi + RHO[i]*(Rai[0]*v0imi + Rai[1]*v1imi + Rai[2]*v2imi);\n\t\t\tPj = press[i];\n\n\t\t\t//if(i == 16107)\n\t\t\t//\tprintf(\"\\ni:%5d timeCurrent: %lf / Pj: %lf / Pi: %lf / Zj: %lf / Zi: %lf\", i, timeCurrent, Pj, Pi, posZi, posMirrorZi);\n\n\t\t\tif(gradientType == 0)\n\t\t\t\twS *= (Pj - pressMin)/dstimi2;//(press[i] - pressMin)/dstimi2\n\t\t\telse if(gradientType == 1)\n\t\t\t\twS *= (Pj + Pi)/dstimi2;//(press[i] + press[i])/dstimi2;\n\t\t\telse if(gradientType == 2)\n\t\t\t\twS *= (Pj + Pi - 2.0*pressMin)/dstimi2;//(press[i] + press[i] - 2.0*pressMin)/dstimi2;\n\t\t\telse if(gradientType == 3) {\n\t\t\t\tdouble nj = pndi[i];\n\t\t\t\tif(ni > 1.0e-8 && nj > 1.0e-8)\n\t\t\t\t\twS *= (ni*Pj/nj + nj*Pi/ni)/dstimi2;\n\t\t\t}\n\t\t\taccX += v0imi*wS;\taccY += v1imi*wS;\taccZ += v2imi*wS;\n\t  \t}\n\n\t\t// Repulsive force\n\t  \tdouble rpsForce[3];\n\t  \trpsForce[0]=rpsForce[1]=rpsForce[2] = 0.0;\n\n\t  \tif(repulsiveForceType == repForceType::HARADA) {\n\t\t\t// Parallel analysis system for free-surface flow using MPS method with explicitly represented polygon wall boundary model\n\t\t\t// https://doi.org/10.1007/s40571-019-00269-6\n\t\t\tif(normaliwSqrt < reRepulsiveForce && normaliwSqrt > 1.0e-8) {\n\t\t\t\tdouble wijRep = RHO[i]/(timeStep*timeStep)*(reRepulsiveForce-normaliwSqrt);\n\t\t\t\trpsForce[0] = - wijRep*normaliw[0];\n\t\t\t\trpsForce[1] = - wijRep*normaliw[1];\n\t\t\t\trpsForce[2] = - wijRep*normaliw[2];\n\t\t\t}\n\t\t}\n\t\telse if(repulsiveForceType == repForceType::MITSUME) {\n\t\t\t// Explicitly represented polygon wall boundary model for the explicit MPS method\n\t\t\t// https://doi.org/10.1007/s40571-015-0037-8\n\t\t\tif(normaliwSqrt < reRepulsiveForce && normaliwSqrt > 1.0e-8) {\n\t\t\t\tdouble wijRep = repForceCoefMitsume*weightGradient(normaliwSqrt, reRepulsiveForce, weightType);\n\t\t\t\trpsForce[0] = - wijRep*normaliw[0];\n\t\t\t\trpsForce[1] = - wijRep*normaliw[1];\n\t\t\t\trpsForce[2] = - wijRep*normaliw[2];\n\t\t\t}\n\t\t}\n\t\telse if(repulsiveForceType == repForceType::LENNARD_JONES) {\n\t\t\t// Simulating Free Surface Flows with SPH\n\t\t\t// https://doi.org/10.1006/jcph.1994.1034\n\t\t\tif(normaliwSqrt < reRepulsiveForce && normaliwSqrt > 1.0e-8) {\n\t\t\t\tdouble R1 = (reRepulsiveForce/normaliwSqrt)*(reRepulsiveForce/normaliwSqrt);\n\t\t\t\tdouble R2 = R1*R1;\n\t\t\t\tdouble wijRep = (repForceCoefLennardJones*velMax2/normaliwSqrt)*(R2-R1)*RHO[i];\n\t\t\t\trpsForce[0] = - wijRep*normaliw[0];\n\t\t\t\trpsForce[1] = - wijRep*normaliw[1];\n\t\t\t\trpsForce[2] = - wijRep*normaliw[2];\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t// SPH particle boundary forces for arbitrary boundaries \n\t\t\t// https://doi.org/10.1016/j.cpc.2009.05.008\n\t\t\tif(normaliwSqrt < reRepulsiveForce && normaliwSqrt > 1.0e-8) {\n\t\t\t\tdouble W1 = (1.0+3.0*0.5*normaliwSqrt/(reRepulsiveForce));\n\t\t\t\tdouble W2 = (1.0-normaliwSqrt/(reRepulsiveForce))*(1.0-normaliwSqrt/(reRepulsiveForce))*(1.0-normaliwSqrt/(reRepulsiveForce));\n\t\t\t\tdouble wijRep = (repForceCoefMonaghanKajtar*velMax2/(normaliwSqrt - 0.0*partDist))*(1.0/8.0)*(W1)*(W2)*RHO[i];\n\t\t\t\trpsForce[0] = - wijRep*normaliw[0];\n\t\t\t\trpsForce[1] = - wijRep*normaliw[1];\n\t\t\t\trpsForce[2] = - wijRep*normaliw[2];\n\t\t\t}\n\t  \t}\n\t\t// coeffPressGrad is a negative cte (-dim/noGrad)\n\t\t// Original\n//\t\tacc[i*3  ] += (relaxPress*(Rref_i[0]*accX + Rref_i[1]*accY + Rref_i[2]*accZ)*coeffPressGrad - rpsForce[0])*invDns[partType::FLUID];\n//\t\tacc[i*3+1] += (relaxPress*(Rref_i[3]*accX + Rref_i[4]*accY + Rref_i[5]*accZ)*coeffPressGrad - rpsForce[1])*invDns[partType::FLUID];\n//\t\tacc[i*3+2] += (relaxPress*(Rref_i[6]*accX + Rref_i[7]*accY + Rref_i[8]*accZ)*coeffPressGrad - rpsForce[2])*invDns[partType::FLUID];\n\t\t// Modified\n\t\tacc[i*3  ] += (relaxPress*(Rref_i[0]*accX + Rref_i[1]*accY + Rref_i[2]*accZ)*coeffPressGrad - rpsForce[0])/RHO[i];\n\t\tacc[i*3+1] += (relaxPress*(Rref_i[3]*accX + Rref_i[4]*accY + Rref_i[5]*accZ)*coeffPressGrad - rpsForce[1])/RHO[i];\n\t\tacc[i*3+2] += (relaxPress*(Rref_i[6]*accX + Rref_i[7]*accY + Rref_i[8]*accZ)*coeffPressGrad - rpsForce[2])/RHO[i];\n\n\t\t// FSI\n\t\t// Force on wall\n\t\tforceWall[i*3  ] += - (relaxPress*(Rref_i[0]*accX + Rref_i[1]*accY + Rref_i[2]*accZ)*coeffPressGrad - rpsForce[0])*VolumeForce;\n\t\tforceWall[i*3+1] += - (relaxPress*(Rref_i[3]*accX + Rref_i[4]*accY + Rref_i[5]*accZ)*coeffPressGrad - rpsForce[1])*VolumeForce;\n\t\tforceWall[i*3+2] += - (relaxPress*(Rref_i[6]*accX + Rref_i[7]*accY + Rref_i[8]*accZ)*coeffPressGrad - rpsForce[2])*VolumeForce;\n\t}}\n}\n\n// Calculation of the volume of fraction if phase II in the mixture\nvoid MpsParticle::calcVolumeFraction()\n{\n\tif(Fraction_method == 1) {   //Linear distribution\n#pragma omp parallel for schedule(dynamic,64)\n\t\tfor(int i=0; i<numParticles; i++) {\n\t\tif(particleType[i] == fluid) {\n\t\t\tdouble sum1 = 0.0, sum2 = 0.0;\n\t\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\t\t\n\t\t\tint ix, iy, iz;\n\t\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\t\tint j = firstParticleInBucket[jb];\n\t\t\t\tif(j == -1) continue;\n\t\t\t\tdouble plx, ply, plz;\n\t\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\t\twhile(true) {\n\t\t\t\t\tdouble v0ij, v1ij, v2ij, dstij2;\n\t\t\t\t\t\n\t\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t\t\n\t\t\t\t\tif(dstij2 < reS2) {\n\t\t\t\t\tif(j != i && particleType[j] == fluid) {\n\t\t\t\t\t\tsum1 += 1.0;\n\t\t\t\t\t\tif(PTYPE[j] >= 2) sum2 += 1.0;\n\t\t\t\t\t\t}}\n\t\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\t\tif(j == -1) break;\n\t\t\t\t}\n\t\t\t}}}\n\t\t\tif(sum1 < 1.0e-8)\n\t\t\t\tCv[i] = 0.0;\n\t\t\telse \n\t\t\t\tCv[i] = sum2/sum1;\n\t\t}}\n\t}\n\telse if(Fraction_method == 2) {   //Non linear :  Smoothed using the weight funtion\n#pragma omp parallel for schedule(dynamic,64)\n\t\tfor(int i=0; i<numParticles; i++) {\n\t\tif(particleType[i] == fluid) {\n\t\t\tdouble sum1 = 0.0, sum2 = 0.0;\n\t\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\t\t\n\t\t\tint ix, iy, iz;\n\t\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\t\tint j = firstParticleInBucket[jb];\n\t\t\t\tif(j == -1) continue;\n\t\t\t\tdouble plx, ply, plz;\n\t\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\t\twhile(true) {\n\t\t\t\t\tdouble v0ij, v1ij, v2ij, dstij2;\n\t\t\t\t\t\n\t\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\n\t\t\t\t\tif(dstij2 < reS2) {\n\t\t\t\t\tif(j != i && particleType[j] == fluid) {\n\t\t\t\t\t\tdouble dst = sqrt(dstij2);\n\t\t\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\t\t\tsum1 += wS;\n\t\t\t\t\t\tif(PTYPE[j] >= 2) sum2 += wS;\n\t\t\t\t\t\t}}\n\t\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\t\tif(j == -1) break;\n\t\t\t\t}\n\t\t\t}}}\n\t\t\tif(sum1 < 1.0e-8)\n\t\t\t\tCv[i] = 0.0;\n\t\t\telse \n\t\t\t\tCv[i] = sum2/sum1;\n\t\t}}\n\t}\n}\n\n// 2018 - Meshfree particle numerical modelling of sub-aerial and submerged landslides\n// Viscosity interaction values for \"real\" fluid particles\nvoid MpsParticle::calcViscosityInteractionVal() {\n\n\tdouble gravityMod = sqrt(gravityX*gravityX + gravityY*gravityY + gravityZ*gravityZ);\n\n\t//double  *S12, *S13, *S23, *S11, *S22, *S33, d, phi = 0.0, phi2 = 0.0, meu_0, normal_stress;//,grain_VF, *p_smooth;\n\tdouble d, phi = 0.0, phi2 = 0.0, meu_0, normal_stress;\n\tdouble **BL, **WL, **PS;\n\n\t// Changed !!!\n\t// Be carefull to assign all domain\n\tdouble Xmin, Xmax, Ymin, Ymax, Zmin; // Minimum and maximum of searching grid\n\t// dam1610\n//\tXmin = 0.0 - partDist*3.0; Xmax = 1.65 + partDist*3.0;\n//\tYmin = 0.0 - partDist*3.0; Ymax = 0.15 + partDist*3.0;\n\tZmin = 0.0 - partDist*3.0; //Zmax = 0.7 + partDist*30.0;\n\t// damErosion3D\n//\tXmin = 0.0 - partDist*3.0; Xmax = 2.00 + partDist*3.0;\n//\tYmin = 0.0 - partDist*3.0; Ymax = 0.10 + partDist*3.0;\n\t// damErosion2D\n\t//Xmin = 0.0 - partDist*3.0; Xmax = 2.00 + partDist*3.0;\n\t//Ymin = 0.0; Ymax = 0.00;\n\t// S1 2D\n//\tXmin = 0.0 - partDist*3.0; Xmax = 0.30 + partDist*3.0;\n//\tYmin = 0.0; Ymax = 0.00;\n\t// Subaquatic 0.016\n\tXmin = 0.0016 - partDist*3.0; Xmax = 0.9792 + partDist*3.0;\n\tYmin = 0.00; Ymax = 0.00;\n\t// Changed !!!\n\n\t// Search free-surface particles for each interval of aa = 2 particles in wall\n\tdouble aaL0 = 2.0*partDist;\n\tint kx_max = int( (Xmax - Xmin)/aaL0 ) + 1;\n\tint ky_max = int( (Ymax - Ymin)/aaL0 ) + 1;\n\n\tdouble Uxx, Uxy, Uxz, Uyx, Uyy, Uyz, Uzx, Uzy, Uzz;\n/*\n\tS11 = new double[numParticles + 1];\n\tS22 = new double[numParticles + 1];\n\tS33 = new double[numParticles + 1];\n\tS12 = new double[numParticles + 1];\n\tS13 = new double[numParticles + 1];\n\tS23 = new double[numParticles + 1];\n*/\n\t//p_smooth = new double[numParticles + 1];\n\tBL = new double*[kx_max + 1];  // bed level\n\tWL = new double*[kx_max + 1];  // water level\n\tPS = new double*[kx_max + 1];  // pressure sediment\n\n#pragma omp parallel for\n\tfor(int m = 1; m <= kx_max; m++) {\n\t\tBL[m] = new double[ky_max + 1];\n\t\tWL[m] = new double[ky_max + 1];\n\t\tPS[m] = new double[ky_max + 1];\n\t}\n\n\t// Determining the bed level\n\tif((int)dim == 2) {\n#pragma omp parallel for schedule(dynamic,64)\n\t\tfor(int kx = 1; kx <= kx_max; kx++) {\n\t\t\tfor(int ky = 1; ky <= ky_max; ky++) {\n\t\t\t\tBL[kx][ky] = Ymin;\n\t\t\t\tWL[kx][ky] = Ymin;\n\t\t\t\tPS[kx][ky] = 0.0;\n\t\t\t}\n\t\t}\n\t}\n\telse {\n#pragma omp parallel for schedule(dynamic,64)\n\t\tfor(int kx = 1; kx <= kx_max; kx++) {\n\t\t\tfor(int ky = 1; ky <= ky_max; ky++) {\n\t\t\t\tBL[kx][ky] = Zmin;\n\t\t\t\tWL[kx][ky] = Zmin;\n\t\t\t\tPS[kx][ky] = 0.0;\n\t\t\t}\n\t\t}\n\t}\n\n\n\tif((int)dim == 2) {\n#pragma omp parallel for\n\t\tfor(int i=0; i<numParticles; i++) {\n\t\t\tif(particleType[i] == fluid) {\n\t\t\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\n\t\t\t\n\t\t\t\tint kx = int( (posXi - Xmin)/aaL0 ) + 1;\n\t\t\t\tint ky = 1;\n\t\t\t\t//if(posYi > BL[kx][ky] && Cv[i] > 0.5) { BL[kx][ky] = posYi; PS[kx][ky] = pnew[i]; }\n\t\t\t\tif(posYi > BL[kx][ky] && Cv[i] > 0.5) { BL[kx][ky] = posYi; PS[kx][ky] = press[i]; }\n\t\t\t\tif(posYi > WL[kx][ky] && PTYPE[i] == 1) { WL[kx][ky] = posYi; }\n\t\t\t}\n\t\t}\n\t}\n\telse {\n#pragma omp parallel for\n\t\tfor(int i=0; i<numParticles; i++) {\n\t\t\tif(particleType[i] == fluid) {\n\t\t\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\t\t\n\t\t\t\tint kx = int( (posXi - Xmin)/aaL0 ) + 1;\n\t\t\t\tint ky = int( (posYi - Ymin)/aaL0 ) + 1;\n\t\t\t\t//if(posZi > BL[kx][ky] && Cv[i] > 0.5) { BL[kx][ky] = posZi; PS[kx][ky] = pnew[i]; }\n\t\t\t\tif(posZi > BL[kx][ky] && Cv[i] > 0.5) { BL[kx][ky] = posZi; PS[kx][ky] = press[i]; }\n\t\t\t\tif(posZi > WL[kx][ky] && PTYPE[i] == 1) { WL[kx][ky] = posZi; }\n\t\t\t}\n\t\t}\n\t}\n\n\t// Strain rate calculation\n#pragma omp parallel for schedule(dynamic,64)\n\tfor(int i=0; i<numParticles; i++) {\n\tif(particleType[i] == fluid) {\n\t\tdouble sum1 = 0.0, sum2 = 0.0, sum3 = 0.0, sum4 = 0.0, sum5 = 0.0, sum6 = 0.0, sum7 = 0.0, sum8 = 0.0, sum9 = 0.0, sum10 = 0.0;\n\t\tdouble sumWs = 0.0;\n//\t\tdouble accX = 0.0;\t\t\tdouble accY = 0.0;\t\t\tdouble accZ = 0.0;\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble velXi = vel[i*3  ];\tdouble velYi = vel[i*3+1];\tdouble velZi = vel[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\tdouble MC[9];\n\t\tMC[0] = correcMatrixRow1[i*3];\tMC[1] = correcMatrixRow1[i*3+1];\tMC[2] = correcMatrixRow1[i*3+2];\n\t\tMC[3] = correcMatrixRow2[i*3];\tMC[4] = correcMatrixRow2[i*3+1];\tMC[5] = correcMatrixRow2[i*3+2];\n\t\tMC[6] = correcMatrixRow3[i*3];\tMC[7] = correcMatrixRow3[i*3+1];\tMC[8] = correcMatrixRow3[i*3+2];\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reS2 && (dstij2 < dstimj2 || wallType == boundaryWallType::PARTICLE)) {\n\t\t\t\tif(j != i) {\n\t\t\t\t\tdouble dst = sqrt(dstij2);\n\t\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\t\tdouble vec_ijx = vel[j*3  ] - velXi;\t\n\t\t\t\t\tdouble vec_ijy = vel[j*3+1] - velYi;\t\n\t\t\t\t\tdouble vec_ijz = vel[j*3+2] - velZi;\n\t\t\t\t\tdouble invDstij2 = 1.0/dstij2;\n\n\t\t\t\t\tif(gradientCorrection == false) {\n\t\t\t\t\t\tsum1 += vec_ijx*v0ij*wS*invDstij2;\n\t\t\t\t\t\tsum2 += vec_ijx*v1ij*wS*invDstij2;\n\t\t\t\t\t\tsum3 += vec_ijx*v2ij*wS*invDstij2;\n\t\t\t\t\t\t\n\t\t\t\t\t\tsum4 += vec_ijy*v0ij*wS*invDstij2;\n\t\t\t\t\t\tsum5 += vec_ijy*v1ij*wS*invDstij2;\n\t\t\t\t\t\tsum6 += vec_ijy*v2ij*wS*invDstij2;\n\t\t\t\t\t\t\n\t\t\t\t\t\tsum7 += vec_ijz*v0ij*wS*invDstij2;\n\t\t\t\t\t\tsum8 += vec_ijz*v1ij*wS*invDstij2;\n\t\t\t\t\t\tsum9 += vec_ijz*v2ij*wS*invDstij2;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tdouble v0ijC = (v0ij*MC[0] + v1ij*MC[1] + v2ij*MC[2]);\n\t\t\t\t\t\tdouble v1ijC = (v0ij*MC[3] + v1ij*MC[4] + v2ij*MC[5]);\n\t\t\t\t\t\tdouble v2ijC = (v0ij*MC[6] + v1ij*MC[7] + v2ij*MC[8]);\n\t\t\t\t\t\tsum1 += vec_ijx*v0ijC*wS*invDstij2;\n\t\t\t\t\t\tsum2 += vec_ijx*v1ijC*wS*invDstij2;\n\t\t\t\t\t\tsum3 += vec_ijx*v2ijC*wS*invDstij2;\n\t\t\t\t\t\t\n\t\t\t\t\t\tsum4 += vec_ijy*v0ijC*wS*invDstij2;\n\t\t\t\t\t\tsum5 += vec_ijy*v1ijC*wS*invDstij2;\n\t\t\t\t\t\tsum6 += vec_ijy*v2ijC*wS*invDstij2;\n\t\t\t\t\t\t\n\t\t\t\t\t\tsum7 += vec_ijz*v0ijC*wS*invDstij2;\n\t\t\t\t\t\tsum8 += vec_ijz*v1ijC*wS*invDstij2;\n\t\t\t\t\t\tsum9 += vec_ijz*v2ijC*wS*invDstij2;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tsum10 += press[j]*wS;\n\t\t\t\t\tsumWs += wS;\n\t\t\t\t}}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\n\t\t// coeffPressGrad is a negative cte (-dim/pndGradientZero)\n\t\tUxx = -coeffPressGrad*sum1; Uxy = -coeffPressGrad*sum2; Uxz = -coeffPressGrad*sum3;\n\t\tUyx = -coeffPressGrad*sum4; Uyy = -coeffPressGrad*sum5; Uyz = -coeffPressGrad*sum6;\n\t\tUzx = -coeffPressGrad*sum7; Uzy = -coeffPressGrad*sum8; Uzz = -coeffPressGrad*sum9;\n\n\t\t/*if(gradientCorrection == true) {\n\t\t\tdouble Uaux[9];\n\t\t\tUaux[0] = Uxx*correcMatrixRow1[i*3] + Uyx*correcMatrixRow1[i*3+1] + Uzx*correcMatrixRow1[i*3+2];\n\t\t\tUaux[1] = Uxy*correcMatrixRow1[i*3] + Uyy*correcMatrixRow1[i*3+1] + Uzy*correcMatrixRow1[i*3+2];\n\t\t\tUaux[2] = Uxz*correcMatrixRow1[i*3] + Uyz*correcMatrixRow1[i*3+1] + Uzz*correcMatrixRow1[i*3+2];\n\t\t\tUaux[3] = Uxx*correcMatrixRow2[i*3] + Uyx*correcMatrixRow2[i*3+1] + Uzx*correcMatrixRow2[i*3+2];\n\t\t\tUaux[4] = Uxy*correcMatrixRow2[i*3] + Uyy*correcMatrixRow2[i*3+1] + Uzy*correcMatrixRow2[i*3+2];\n\t\t\tUaux[5] = Uxz*correcMatrixRow2[i*3] + Uyz*correcMatrixRow2[i*3+1] + Uzz*correcMatrixRow2[i*3+2];\n\t\t\tUaux[6] = Uxx*correcMatrixRow3[i*3] + Uyx*correcMatrixRow3[i*3+1] + Uzx*correcMatrixRow3[i*3+2];\n\t\t\tUaux[7] = Uxy*correcMatrixRow3[i*3] + Uyy*correcMatrixRow3[i*3+1] + Uzy*correcMatrixRow3[i*3+2];\n\t\t\tUaux[8] = Uxz*correcMatrixRow3[i*3] + Uyz*correcMatrixRow3[i*3+1] + Uzz*correcMatrixRow3[i*3+2];\n\n\t\t\tUxx = Uaux[0];\tUxy = Uaux[1];\tUxz = Uaux[2];\n\t\t\tUyx = Uaux[3];\tUyy = Uaux[4];\tUyz = Uaux[5];\n\t\t\tUzx = Uaux[6];\tUzy = Uaux[7];\tUzz = Uaux[8];\n\t\t}\n\t\t*/\n\t\tif(sumWs > 1.0e-8) {\n\t\t\tp_smooth[i] = sum10/sumWs;\n\t\t}\n\t\telse {\n\t\t\tp_smooth[i] = press[i];\n\t\t}\n\t\tif(p_smooth[i] < 1.0e-8) p_smooth[i] = 0.0;\n\n\t\tS11[i] = 0.5*(Uxx + Uxx);\n\t\tS12[i] = 0.5*(Uxy + Uyx);\n\t\tS13[i] = 0.5*(Uxz + Uzx);\n\t\tS22[i] = 0.5*(Uyy + Uyy);\n\t\tS23[i] = 0.5*(Uyz + Uzy);\n\t\tS33[i] = 0.5*(Uzz + Uzz);\n\n\t\t// Square of the second invariant of the strain-rate tensor = 0.5*tr(SS^2)\n\t\t//II[i] = 0.5*Uxx*Uxx + 0.5*Uyy*Uyy + 0.25*(Uxy + Uyx)*(Uxy + Uyx);\n\t\t//II[i] = 0.5*(S11[i]*S11[i] + S12[i]*S12[i] + S13[i]*S13[i] + S12[i]*S12[i] + S22[i]*S22[i] + S23[i]*S23[i] + S13[i]*S13[i] + S23[i]*S23[i] + S33[i]*S33[i]);\n\t\tII[i] = 0.5*(S11[i]*S11[i] + 2.0*S12[i]*S12[i] + 2.0*S13[i]*S13[i] + S22[i]*S22[i] + 2.0*S23[i]*S23[i] + S33[i]*S33[i]);\n//\t\tII[i] = - (S11[i]*S22[i] + S22[i]*S33[i] + S11[i]*S33[i] - S12[i]*S12[i] - S13[i]*S13[i] - S23[i]*S23[i]);\n//\t\tII[i] = sqrt(II[i]*II[i]);\n\t\tif(II[i] < 1.0e-8 || II[i]*0 != 0) II[i] = 0.0;\n\t\t//II=fabs(S11[i]*S22[i]-S12[i]*S12[i]);\n\t\t//std::cout << \" II: \" << II[i] << std::endl;\n\t}}\n\n\t// Newtonian viscosity\n\tif(fluidType == viscType::NEWTONIAN)\n\t{\n#pragma omp parallel for\n\t\tfor(int i=0; i<numParticles; i++) {\n\t\tif(particleType[i] == fluid) {\n\t\t\tif(PTYPE[i] <= 1)MEU[i] = KNM_VS1 * DNS_FL1;\n\t\t\tif(PTYPE[i] != 1)MEU[i] = KNM_VS2 * DNS_FL2;\n\t\t}}\n\n//\t\tif(TURB > 0)\n//\t\t{\n//\t\t\tNEUt[i] = Cs*DL*Cs*DL*2.0*sqrt(II[i]);\n\n//\t\t\tif(NEUt[i] * 0 != 0)  NEUt[i] = 0.0;\n//\t\t\tif(NEUt[i] > 1.0)     NEUt[i] = 1.0;\n//\t\t}\n\t}\n\n\tdouble mi_max = 0.0;\n\t// Granular Fluid\n\tif(fluidType == viscType::NON_NEWTONIAN)\n\t{\n\t// PROBLEMS TO USE OPENMP HERE. MAYBE THE ACCESS TO BL, WL\n//#pragma omp parallel for\n\t\tfor(int i=0; i<numParticles; i++) {\n\t\tif(particleType[i] == fluid) {\n\n//\t\t\tdouble accX = 0.0;\t\t\tdouble accY = 0.0;\t\t\tdouble accZ = 0.0;\n\t\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\t\tdouble velXi = vel[i*3  ];\tdouble velYi = vel[i*3+1];\tdouble velZi = vel[i*3+2];\n\t\t\tdouble vel2i = velXi*velXi + velYi*velYi + velZi*velZi;\n\n\t\t\tif(PTYPE[i] == 1) { // Newtonian fluid\n\t\t\t\t// Mojtaba\n\t\t\t\t//MEU[i] = KNM_VS1*DNS_FL1*(1 + 2.5*Cv[i]);\n\t\t\t\t//////////////\n\t\t\t\t// Original //\n\t\t\t\tMEU[i] = KNM_VS1*DNS_FL1;\n\t\t\t}\n\t\t\telse if(PTYPE[i] == 2) { // Non-Newtonian mixture\n\t\t\t\t//////////////\n\t\t\t\t// Original //\n\t\t\t\t// phi: internal friction angle\n\t\t\t\t// phi2: maximum friction angle\n\t\t\t\tphi = (Cv[i] - 0.25)*PHI_1/(1.0 - 0.25);\n\t\t\t\tphi2 = (Cv[i] - 0.25)*PHI_2/(1.0 - 0.25);\n\t\t\t\tif(Cv[i] <= 0.25) { phi = 1.0e-8; phi2 = 1.0e-8; } // phi close to zero\n\t\t\t\tif(PTYPE[i] <= 0) phi = PHI_BED; // ghost\n\n\t\t\t\t// normal stress calculation (mechanical pressure)\n\t\t\t\tp_rheo_new[i] = p_smooth[i];\n\n\t\t\t\tint kx = int( (posXi - Xmin)/aaL0 ) + 1;\n\t\t\t\t//int ky = int( (posYi - Ymin)/aaL0 ) + 1;\n\t\t\t\tint ky;\n\t\t\t\tif((int)dim == 2) {\n\t\t\t\t\tky = 1;\n\t\t\t\t\t// Effective pressure = total pressure (from EOS) - hydrostatic pressure\n\t\t\t\t\t//normal_stress = (BL[kx][ky] - posYi + partDist*0.5)*(DNS_FL2)*gravityMod;\t// normal_stress= Gama.H\n\t\t\t\t\t// SPH Simulation of Sediment Flushing Induced by a Rapid Water Flow\n\t\t\t\t\tnormal_stress = (BL[kx][ky] - posYi + partDist*0.5)*(DNS_FL2 - DNS_FL1)*gravityMod - vel2i*(DNS_FL2 - DNS_FL1)*0.5;\t// normal_stress= Gama.H, Eq. (8)\n\n//\t\t\t\t\tif(p_smooth[i] < (WL[kx][ky] - posYi)*DNS_FL1*gravityMod) p_smooth[i] = (WL[kx][ky] - posYi)*DNS_FL1*gravityMod;\n\t\t\t\t\t///if(timeCurrent <= 1.0) normal_stress = (1.0 - timeCurrent)*(p_smooth[i] - (WL[kx][ky] - posYi)*DNS_FL1*gravityMod) + timeCurrent*normal_stress;\n\n\t\t\t\t\tif(WL[kx][ky] < BL[kx][ky]) {\n\t\t\t\t\t\tnormal_stress = p_smooth[i];\t\t// Free-fall (dry granular material)\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t//normal_stress = p_smooth[i] - (WL[kx][ky] - posYi)*DNS_FL1*gravityMod;\n\t\t\t\t\t\t// A multiphase meshfree particle method for continuum-based modeling of dry and submerged granular flows\n\t\t\t\t\t\tnormal_stress = (p_smooth[i] - PS[kx][ky])*(DNS_FL2 - DNS_FL1)*VF[i]/RHO[i];\t// Grain inertia (submerged) Eq. (20)\n\n\t\t\t\t\t\tnormal_stress = p_smooth[i] - PS[kx][ky];\n//\t\t\t\t\t\tnormal_stress = p_smooth[i] - (WL[kx][ky] - posYi)*(DNS_FL1)*gravityMod;\t// Grain inertia (submerged)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tky = int( (posYi - Ymin)/aaL0 ) + 1;\n\t\t\t\t\t// Effective pressure = total pressure (from EOS) - hydrostatic pressure\n\t\t\t\t\t//normal_stress = (BL[kx][ky] - posZi + partDist*0.5)*(DNS_FL2)*gravityMod;\t// normal_stress= Gama.H\n\t\t\t\t\tnormal_stress = (BL[kx][ky] - posZi + partDist*0.5)*(DNS_FL2 - DNS_FL1)*gravityMod - vel2i*(DNS_FL2 - DNS_FL1)*0.5;\t// normal_stress= Gama.H\n\n\t\t\t\t\tif(p_smooth[i] - (WL[kx][ky] - posZi)*DNS_FL1*gravityMod < 1.0e-8) p_smooth[i] = (WL[kx][ky] - posZi)*DNS_FL1*gravityMod;\n\t\t\t\t\tif(timeCurrent <= 1.0) normal_stress = (1.0 - timeCurrent)*(p_smooth[i] - (WL[kx][ky] - posZi)*DNS_FL1*gravityMod) + timeCurrent*normal_stress;\n\n//\t\t\t\t\tnormal_stress = p_smooth[i] - (WL[kx][ky] - posZi)*DNS_FL1*gravityMod;\n\t\t\t\t}\n\n\t\t\t\t\n//\t\t\t\tnormal_stress = p_smooth[i];\n\t\t\t\t//normal_stress=normal_stress*0.61*1500/DNS_FL2;\n\t\t\t\tif(normal_stress < 1.0 || Cv[i] < 0.5) normal_stress = 1.0;\n\n\t\t\t\tp_rheo_new[i] = normal_stress;\n\n\t\t\t\tdouble modE = sqrt(II[i]);\n\n\t\t\t\t// Yield stress calculation (Text below Eq. (8))\n\t\t\t\tif(WL[kx][ky] < BL[kx][ky]) {\n\t\t\t\t\tInertia[i] = modE*DG/sqrt(normal_stress/DNS_SDT);\t\t// Free-fall (dry granular material)\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tInertia[i] = modE*DG/sqrt(normal_stress/(DNS_FL1*Cd));\t// Grain inertia (submerged)\n\t\t\t\t}\n\t\t\t\t//Inertia[i] = modE*(KNM_VS1*DNS_FL1)/normal_stress ;\t// Viscous regime\n\n//\t\t\t\tInertia[i] = 1.0;\n\t\t\t\t// VF_max VF_min\n\t\t\t\tVF[i] = VF_max - (VF_max - VF_min)*Inertia[i];\n\t\t\t\tif(VF[i] < VF_min) VF[i] = VF_min;\n\t\t\t\tRHO[i] = DNS_SDT*VF[i] + (1.0 - VF[i])*DNS_FL1;\n\t\t\t\tphi *= (VF[i]/VF_max);\n\n\t\t\t\tdouble yield_stress;\n\n\t\t\t\t// Drucker-Prager model\n\t\t\t\tdouble alpha_1 = 2.0*sqrt(3.0)*sin(phi)/(3.0 - sin(phi));\n\t\t\t\tdouble beta_1 = 2.0*sqrt(3.0)*cos(phi)/(3.0 - sin(phi));\n\t\t\t\t// Mohr-Coulomb model\n\t\t\t\t//double alpha_1 = sin(phi);\n\t\t\t\t//double beta_1 = cos(phi);\n\t\t\t\t//double alpha_1 = tan(phi);\n\t\t\t\t//double beta_1 = 1.0;\n\n\t\t\t\tyield_stress = cohes*beta_1 + normal_stress*alpha_1;\n\n\t\t\t\t//yield_stress = normal_stress*tan(phi);\n\n\t\t\t\tif(yield_stress < 1.0e-8) yield_stress = 0.0;\n\n\t\t\t\tdouble visc_max = (MEU0 + yield_stress*mm*0.5); // Below Eq. (5)\n\n\t\t\t\t// Pre-failure portion\n\t\t\t\t//if(modE > 1.0e-8) {\n\t\t\t\t//\tMEU_Y[i] = yield_stress*(1.0 - exp(-mm*modE))/(2.0*modE); // Eq. (5)\n\t\t\t\t//}\n\t\t\t\t//else {\n\t\t\t\t//\tMEU_Y[i] = visc_max;\n\t\t\t\t//}\n\n\n\t\t\t\tMEU_Y[i] = yield_stress/(2.0*sqrt(modE*modE + 1.0e-12));\n\n\t\t\t\t// H-B rheology\n\n\t\t\t\t//meu_0 = MEU0;\n\n//\t\t\t\tphi = PHI_1; phi2 = PHI_2;\n//\t\t\t\tif(Cv[i] <= 0.25) { phi = 1.0e-8; phi2 = 1.0e-8; } // phi close to zero\n\n\t\t\t\t// Non-linear Meu(I) rheology\n\t\t\t\tif(WL[kx][ky] < BL[kx][ky]) {\n//\t\t\t\t\tmeu_0 = 0.5*(tan(phi2) - tan(phi))*normal_stress*DG/(I0*sqrt(normal_stress/DNS_FL2) + modE*DG);\t\t\t//free fall\n\t\t\t\t\tmeu_0 = 0.5*(tan(phi2) - tan(phi))*normal_stress*DG/(I0*sqrt(normal_stress/DNS_FL2) + modE*DG)*modE/(sqrt(modE*modE + 1.0e-12));\n\t\t\t\t\t//meu_0 = (tan(phi) + (tan(phi2) - tan(phi))*modE*DG/(I0*sqrt(normal_stress/DNS_FL2) + modE*DG))*normal_stress/(sqrt(II[i] + 1.0e-12));\n\t\t\t\t}\n\t\t\t\telse {\n//\t\t\t\t\tmeu_0 = 0.5*(tan(phi2) - tan(phi))*normal_stress*DG/(I0*sqrt(normal_stress/(DNS_FL1*Cd)) + modE*DG);\t//grain inertia\n\t\t\t\t\tmeu_0 = 0.5*(tan(phi2) - tan(phi))*normal_stress*DG/(I0*sqrt(normal_stress/(DNS_FL1*Cd)) + modE*DG)*modE/(sqrt(modE*modE + 1.0e-12));\n\n\t\t\t\t\t//meu_0 = (tan(phi) + (tan(phi2) - tan(phi))*modE*DG/(I0*sqrt(normal_stress/DNS_FL1*Cd) + modE*DG))*normal_stress/(sqrt(II[i] + 1.0e-12));\n\t\t\t\t}\n\n\t\t\t   \t//meu_0 = 0.5*(tan(phi2) - tan(phi))*normal_stress*(KNM_VS1*DNS_FL1)/(I0*normal_stress + modE*(KNM_VS1*DNS_FL1));\t//viscous\n\t\t\t   \t\n\t\t\t   \t// Linear Meu(I) rheology\n\t\t\t   \t//meu_0 = 0.5*(tan(phi2) - tan(phi))*DG*sqrt(normal_stress*DNS_FL2)/I0;\t\t//free fall\n\t\t\t   \t//meu_0 = 0.5*(tan(phi2) - tan(phi))*DG*sqrt(normal_stress*DNS_FL1*Cd)/I0;\t//grain inertia\n\t\t\t   \t//meu_0 = 0.5*(tan(phi2) - tan(phi))*(KNM_VS1*DNS_FL1)/I0;\t\t\t\t\t//viscous\n\n\t\t\t\tif(modE <= 1.0e-8 || (meu_0*0) != 0) meu_0 = MEU0;\n\n\t\t\t\tvisc_max = (meu_0 + yield_stress*mm*0.5); // Below Eq. (5)\n\n\t\t\t\t//if(isnan(II[i]) || isinf(II[i])) {\n\t\t\t\t\t//std::cout << \" viscmax: \" << II[i] << std::endl;\n\t\t\t\t//\tassert(visc_max >= 0.0 || visc_max <= 0.0);\n\t\t\t\t//}\n\t\t\t\t\n\t\t\t\t// Herschel bulkley papanastasiou\n///\t\t\t\tMEU[i] = MEU_Y[i] + MEU0*pow(4.0*II[i], (N - 1.0)*0.5);\n\n\t\t\t\t// MEU_Y rheological model\n\t\t\t\tMEU[i] = MEU_Y[i] + meu_0;\n\t\t\t\t\n\t\t\t\t//if(II[i] <= 1.0e-8 || MEU[i] > visc_max) {\n\t\t\t\tif(II[i] <= 1.0e-8) {\n\t\t\t\t\t//std::cout << \" MEU>viscmax: \" << yield_stress*mm*0.5 << \" meu0: \" << meu_0 << \" II: \" << II[i] << std::endl;\n\t\t\t\t\tMEU[i] = visc_max;\n\t\t\t\t}\n\t\t\t\tif(PTYPE[i] <= 0) MEU[i] = MEU[i]*Cv[i] + DNS_FL1*KNM_VS1*(1.0 - Cv[i]); // ghost\n\n\t\t\t\t//if(MEU[i]/RHO[i] > maxVIS) maxVIS = MEU[i]/RHO[i];\n\t\t\t\tif(MEU[i] > mi_max) mi_max = MEU[i];\n\t\t\t}\n\t\t\t\n\t\t\tif(PTYPE[i] >= 2) {\n\t\t\t\tif(Cv[i] > 0.5) RHO[i] = DNS_FL2;\n\t\t\t\telse RHO[i] = Cv[i]*DNS_FL2 + (1.0 - Cv[i])*DNS_FL1;\n\t\t\t}\n\t\t}}\n\n\t\t//---------------------------------- Direct stress calculation method -----------------------------------------\n//\t\tif(stress_cal_method == 2)\n//\t\t{\n//\t\t\tfor(i = 1; i <= NUM; i++)\n//\t\t\t{\n//\t\t\t\tdouble sum1 = 0.0, sum2 = 0.0, sum3 = 0.0, sum4 = 0.0, sum5 = 0.0, sum6 = 0.0, sum7 = 0.0, sum8 = 0.0, sum9 = 0.0, sum10 = 0.0;\n//\t\t\t\tfor(l = 2; l <= neighb[i][1]; l++)\n//\t\t\t\t{\n//\t\t\t\t\tj = neighb[i][l];\n//\t\t\t\t\td = DIST(i, j);\n//\t\t\t\t\tif(i != j && d <= re)\n//\t\t\t\t\t{\n//\t\t\t\t\t\tw = W(d, KTYPE, 2);\n\n//\t\t\t\t\t\tdouble meuij = 2.0 * MEU[i] * MEU[j] / (MEU[i] + MEU[j]);\n//\t\t\t\t\t\tif((NEUt[i] + NEUt[j])>0) meuij = meuij + 2.0 * NEUt[i] * RHO[i] * NEUt[j] * RHO[j] / (NEUt[i] * RHO[i] + NEUt[j] * RHO[j]);\n\n//\t\t\t\t\t\tsum1 = sum1 + meuij * (x_vel[j] - x_vel[i])*DX(i, j)*w / d / d;\n//\t\t\t\t\t\tsum2 = sum2 + meuij * (x_vel[j] - x_vel[i])*DY(i, j)*w / d / d;\n//\t\t\t\t\t\tsum3 = sum3 + meuij * (x_vel[j] - x_vel[i])*DZ(i, j)*w / d / d;\n\n//\t\t\t\t\t\tsum4 = sum4 + meuij * (y_vel[j] - y_vel[i])*DX(i, j)*w / d / d;\n//\t\t\t\t\t\tsum5 = sum5 + meuij * (y_vel[j] - y_vel[i])*DY(i, j)*w / d / d;\n//\t\t\t\t\t\tsum6 = sum6 + meuij * (y_vel[j] - y_vel[i])*DZ(i, j)*w / d / d;\n\n//\t\t\t\t\t\tsum7 = sum7 + meuij * (z_vel[j] - z_vel[i])*DX(i, j)*w / d / d;\n//\t\t\t\t\t\tsum8 = sum8 + meuij * (z_vel[j] - z_vel[i])*DY(i, j)*w / d / d;\n//\t\t\t\t\t\tsum9 = sum9 + meuij * (z_vel[j] - z_vel[i])*DZ(i, j)*w / d / d;\n//\t\t\t\t\t}\n//\t\t\t\t}\n\n//\t\t\t\tTau_xx[i] = (dim / n0) * 2.0 * sum1;\n//\t\t\t\tTau_yy[i] = (dim / n0) * 2.0 * sum5;\n//\t\t\t\tTau_zz[i] = (dim / n0) * 2.0 * sum9;\n\n//\t\t\t\tTau_xy[i] = (dim / n0)*(sum2 + sum4);\n//\t\t\t\tTau_xz[i] = (dim / n0)*(sum3 + sum7);\n//\t\t\t\tTau_yz[i] = (dim / n0)*(sum6 + sum8);\n//\t\t\t}\n//\t\t}\n\n\t} // if(fluidType == viscType::NON_NEWTONIAN)\n\n\t//---------------------------------------------------------------\n\n//\tdelete[]S11; delete[]S12; delete[]S13; delete[]S22; delete[]S23; delete[]S33; delete[]BL; delete[]WL; delete[]PS; //delete[]p_smooth;\n//\tS11 = NULL; S12 = NULL; S13 = NULL; S22 = NULL; S23 = NULL; S33 = NULL; BL = NULL; WL = NULL; PS = NULL; //p_smooth = NULL;\n\n\tCFLvisc = timeStep*mi_max/((DNS_SDT*VF_max + (1.0 - VF_max)*DNS_FL1)*partDist*partDist);\n\n\tdelete[]BL; delete[]WL; delete[]PS;\n\tBL = NULL; WL = NULL; PS = NULL;\n}\n\n// Free-slip condition. Viscosity interaction values\nvoid MpsParticle::calcWallSlipViscosityInteractionVal() {\n\n\tdouble gravityMod = sqrt(gravityX*gravityX + gravityY*gravityY + gravityZ*gravityZ);\n\n\t//double  *S12, *S13, *S23, *S11, *S22, *S33, d, phi = 0.0, phi2 = 0.0, meu_0, normal_stress;//, grain_VF, *p_smooth;\n\tdouble d, phi = 0.0, phi2 = 0.0, meu_0, normal_stress;\n\tdouble **BL, **WL, **PS;\n\n\t// Changed !!!\n\t// Be carefull to assign all domain\n\tdouble Xmin, Xmax, Ymin, Ymax, Zmin; // Minimum and maximum of searching grid\n\t// dam1610\n//\tXmin = 0.0 - partDist*3.0; Xmax = 1.65 + partDist*3.0;\n//\tYmin = 0.0 - partDist*3.0; Ymax = 0.15 + partDist*3.0;\n\tZmin = 0.0 - partDist*3.0; //Zmax = 0.7 + partDist*30.0;\n\t// damErosion3D\n\tXmin = 0.0 - partDist*3.0; Xmax = 2.00 + partDist*3.0;\n\tYmin = 0.0 - partDist*3.0; Ymax = 0.10 + partDist*3.0;\n\t// Changed !!!\n\n\t// Search free-surface particles for each interval of aa = 2 particles in wall\n\tdouble aaL0 = 2.0*partDist;\n\tint kx_max = int( (Xmax - Xmin)/aaL0 ) + 1;\n\tint ky_max = int( (Ymax - Ymin)/aaL0 ) + 1;\n\n\tdouble Uxx, Uxy, Uxz, Uyx, Uyy, Uyz, Uzx, Uzy, Uzz;\n\tdouble aUxx, aUxy, aUxz, aUyx, aUyy, aUyz, aUzx, aUzy, aUzz;\n/*\n\tS11 = new double[numParticles + 1];\n\tS22 = new double[numParticles + 1];\n\tS33 = new double[numParticles + 1];\n\tS12 = new double[numParticles + 1];\n\tS13 = new double[numParticles + 1];\n\tS23 = new double[numParticles + 1];\n*/\n\t//p_smooth = new double[numParticles + 1];\n\tBL = new double*[kx_max + 1];  // bed level\n\tWL = new double*[kx_max + 1];  // water level\n\tPS = new double*[kx_max + 1];  // pressure sediment\n\n#pragma omp parallel for\n\tfor(int m = 1; m <= kx_max; m++)\n\t{\n\t\tBL[m] = new double[ky_max + 1];\n\t\tWL[m] = new double[ky_max + 1];\n\t\tPS[m] = new double[ky_max + 1];\n\t}\n\n\t// Determining the bed level\n#pragma omp parallel for schedule(dynamic,64)\n\tfor(int kx = 1; kx <= kx_max; kx++)\n\t{\n\t\tfor(int ky = 1; ky <= ky_max; ky++)\n\t\t{\n\t\t\tBL[kx][ky] = Zmin;\n\t\t\tWL[kx][ky] = Zmin;\n\t\t}\n\t}\n\n#pragma omp parallel for\n\tfor(int i=0; i<numParticles; i++) {\n\t\tif(particleType[i] == fluid) {\n\t\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\t\t\n\t\t\tint kx = int( (posXi - Xmin)/aaL0 ) + 1;\n\t\t\tint ky = int( (posYi - Ymin)/aaL0 ) + 1;\n\n\t\t\t//if(posZi>BL[kx][ky] && Cv[i]>0.5) { BL[kx][ky] = posZi; PS[kx][ky] = pnew[i]; }\n\t\t\tif(posZi>BL[kx][ky] && Cv[i]>0.5) { BL[kx][ky] = posZi; PS[kx][ky] = press[i]; }\n\t\t\tif(posZi>WL[kx][ky] && PTYPE[i] == 1) { WL[kx][ky] = posZi; }\n\t\t}\n\t}\n\n\t// Strain rate calculation\n\t//int nPartNearMesh = partNearMesh.size();\n\t//printf(\" Mesh %d \\n\", partNearMesh);\n\t// Loop only for particles near mesh\n#pragma omp parallel for schedule(dynamic,64)\n\t//for(int im=0;im<nPartNearMesh;im++) {\n\t//int i = partNearMesh[im];\n\tfor(int i=0; i<numParticles; i++) {\n\t//if(particleType[i] == fluid) {\n\tif(particleType[i] == fluid && particleNearWall[i] == true) {\n\t\tdouble sum1 = 0.0, sum2 = 0.0, sum3 = 0.0, sum4 = 0.0, sum5 = 0.0, sum6 = 0.0, sum7 = 0.0, sum8 = 0.0, sum9 = 0.0, sum10 = 0.0;\n\n//\t\tdouble accX = 0.0;\t\t\tdouble accY = 0.0;\t\t\tdouble accZ = 0.0;\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble velXi = vel[i*3  ];\tdouble velYi = vel[i*3+1];\tdouble velZi = vel[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n//\t\tdouble velXi = Velk[i*3  ];\tdouble velYi = Velk[i*3+1];\tdouble velZi = Velk[i*3+2\n\n\t\t// Transformation matrix Rref_i = I - 2.0*normal_iwall*normal_iwall\n\t\tdouble Rref_i[9], normaliw[3], normalMod2;\n\t\t// normal fluid-wall particle = 0.5*(normal fluid-mirror particle)\n\t\tnormaliw[0] = 0.5*(posXi - posMirrorXi); normaliw[1] = 0.5*(posYi - posMirrorYi); normaliw[2] = 0.5*(posZi - posMirrorZi);\n\t\tnormalMod2 = normaliw[0]*normaliw[0] + normaliw[1]*normaliw[1] + normaliw[2]*normaliw[2];\n\n\t\tif(normalMod2 > 1.0e-8) {\n\t\t\tdouble normalMod = sqrt(normalMod2);\n\t\t\tnormaliw[0] = normaliw[0]/normalMod;\n\t\t\tnormaliw[1] = normaliw[1]/normalMod;\n\t\t\tnormaliw[2] = normaliw[2]/normalMod;\n\t\t}\n\t\telse {\n\t\t\tnormaliw[0] = 0;\n\t\t\tnormaliw[1] = 0;\n\t\t\tnormaliw[2] = 0;\n\t\t}\n\n\t\t//  Transformation matrix R_i = I - 2.0*normal_iwall*normal_iwall\n\t\tRref_i[0] = 1.0 - 2.0*normaliw[0]*normaliw[0]; Rref_i[1] = 0.0 - 2.0*normaliw[0]*normaliw[1]; Rref_i[2] = 0.0 - 2.0*normaliw[0]*normaliw[2];\n\t\tRref_i[3] = 0.0 - 2.0*normaliw[1]*normaliw[0]; Rref_i[4] = 1.0 - 2.0*normaliw[1]*normaliw[1]; Rref_i[5] = 0.0 - 2.0*normaliw[1]*normaliw[2];\n\t\tRref_i[6] = 0.0 - 2.0*normaliw[2]*normaliw[0]; Rref_i[7] = 0.0 - 2.0*normaliw[2]*normaliw[1]; Rref_i[8] = 1.0 - 2.0*normaliw[2]*normaliw[2];\n\n\t\t// Mirror particle velocity vi' = Ri * vi\n\t\tdouble velMirrorXi = (Rref_i[0]*velXi + Rref_i[1]*velYi + Rref_i[2]*velZi);\n\t\tdouble velMirrorYi = (Rref_i[3]*velXi + Rref_i[4]*velYi + Rref_i[5]*velZi);\n\t\tdouble velMirrorZi = (Rref_i[6]*velXi + Rref_i[7]*velYi + Rref_i[8]*velZi);\n\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and im (intersection) and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reS2 && dstimj2 < reS2 && dstij2 < dstimj2) {\n\t\t\t\tif(j != i) {\n\t\t\t\t\tdouble dst = sqrt(dstimj2);\n\t\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\n\t\t\t\t\tdouble vec_mijx = vel[j*3  ]-velMirrorXi;\t\n\t\t\t\t\tdouble vec_mijy = vel[j*3+1]-velMirrorYi;\t\n\t\t\t\t\tdouble vec_mijz = vel[j*3+2]-velMirrorZi;\n\n\t\t\t\t\tsum1 += vec_mijx*v0imj*wS/dstimj2;\n\t\t\t\t\tsum2 += vec_mijx*v1imj*wS/dstimj2;\n\t\t\t\t\tsum3 += vec_mijx*v2imj*wS/dstimj2;\n\t\t\t\t\t\n\t\t\t\t\tsum4 += vec_mijy*v0imj*wS/dstimj2;\n\t\t\t\t\tsum5 += vec_mijy*v1imj*wS/dstimj2;\n\t\t\t\t\tsum6 += vec_mijy*v2imj*wS/dstimj2;\n\t\t\t\t\t\n\t\t\t\t\tsum7 += vec_mijz*v0imj*wS/dstimj2;\n\t\t\t\t\tsum8 += vec_mijz*v1imj*wS/dstimj2;\n\t\t\t\t\tsum9 += vec_mijz*v2imj*wS/dstimj2;\n\t\t\t\t\t\n\t\t\t\t\tsum10 += press[j]*wS;\n\t\t\t\t}}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\n\t\t// Rref_i * gradU\n\t\t// coeffPressGrad is a negative cte (-dim/pndGradientZero)\n\t\taUxx = -coeffPressGrad*(Rref_i[0]*sum1 + Rref_i[1]*sum4 + Rref_i[2]*sum7);\n\t\taUxy = -coeffPressGrad*(Rref_i[0]*sum2 + Rref_i[1]*sum5 + Rref_i[2]*sum8);\n\t\taUxz = -coeffPressGrad*(Rref_i[0]*sum3 + Rref_i[1]*sum6 + Rref_i[2]*sum9);\n\n\t\taUyx = -coeffPressGrad*(Rref_i[3]*sum1 + Rref_i[4]*sum4 + Rref_i[5]*sum7);\n\t\taUyy = -coeffPressGrad*(Rref_i[3]*sum2 + Rref_i[4]*sum5 + Rref_i[5]*sum8);\n\t\taUyz = -coeffPressGrad*(Rref_i[3]*sum3 + Rref_i[4]*sum6 + Rref_i[5]*sum9);\n\n\t\taUzx = -coeffPressGrad*(Rref_i[6]*sum1 + Rref_i[7]*sum4 + Rref_i[8]*sum7);\n\t\taUzy = -coeffPressGrad*(Rref_i[6]*sum2 + Rref_i[7]*sum5 + Rref_i[8]*sum8);\n\t\taUzz = -coeffPressGrad*(Rref_i[6]*sum3 + Rref_i[7]*sum6 + Rref_i[8]*sum9);\n\n\t\t// Rref_i * gradU * Rref_i\n\t\tUxx = aUxx*Rref_i[0] + aUxy*Rref_i[3] + aUxz*Rref_i[6];\n\t\tUxy = aUxx*Rref_i[1] + aUxy*Rref_i[4] + aUxz*Rref_i[7];\n\t\tUxz = aUxx*Rref_i[2] + aUxy*Rref_i[5] + aUxz*Rref_i[8];\n\n\t\tUyx = aUyx*Rref_i[0] + aUyy*Rref_i[3] + aUyz*Rref_i[6];\n\t\tUyy = aUyx*Rref_i[1] + aUyy*Rref_i[4] + aUyz*Rref_i[7];\n\t\tUyz = aUyx*Rref_i[2] + aUyy*Rref_i[5] + aUyz*Rref_i[8];\n\n\t\tUzx = aUzx*Rref_i[0] + aUzy*Rref_i[3] + aUzz*Rref_i[6];\n\t\tUzy = aUzx*Rref_i[1] + aUzy*Rref_i[4] + aUzz*Rref_i[7];\n\t\tUzz = aUzx*Rref_i[2] + aUzy*Rref_i[5] + aUzz*Rref_i[8];\n\n\t\t// Addition of smoothed pressure for particles near mesh\n\t\tp_smooth[i] += sum10/pndGradientZero;\n\t\tif(p_smooth[i] < 1.0e-8) p_smooth[i] = 0.0;\n\n\t\t// 0.5*(gradU + gradUt)\n\t\tS11[i] = 0.5*(Uxx + Uxx);\n\t\tS12[i] = 0.5*(Uxy + Uyx);\n\t\tS13[i] = 0.5*(Uxz + Uzx);\n\t\tS22[i] = 0.5*(Uyy + Uyy);\n\t\tS23[i] = 0.5*(Uyz + Uzy);\n\t\tS33[i] = 0.5*(Uzz + Uzz);\n\n\t\t//II[i] = 0.5*Uxx*Uxx + 0.5*Uyy*Uyy + 0.25*(Uxy + Uyx)*(Uxy + Uyx);\n\n\t\t// Addition of II for particles near mesh\n\t\t//II[i] += 0.5*(S11[i]*S11[i] + S12[i]*S12[i] + S13[i]*S13[i] + S12[i]*S12[i] + S22[i]*S22[i] + S23[i]*S23[i] + S13[i]*S13[i] + S23[i]*S23[i] + S33[i]*S33[i]);\n\t\tII[i] += 0.5*(S11[i]*S11[i] + 2.0*S12[i]*S12[i] + 2.0*S13[i]*S13[i] + S22[i]*S22[i] + 2.0*S23[i]*S23[i] + S33[i]*S33[i]);\n//\t\tII[i] = 0.5*(S11[i]*S11[i] + S12[i]*S12[i] + S13[i]*S13[i] + S12[i]*S12[i] + S22[i]*S22[i] + S23[i]*S23[i] + S13[i]*S13[i] + S23[i]*S23[i] + S33[i]*S33[i]);\n\t\t//II[i]= S11[i]*S22[i] +S22[i]*S33[i]+ S11[i]*S33[i] - S12[i]*S12[i] -S13[i]*S13[i]- S23[i]*S23[i] ;\n\t\tif(II[i] < 1.0e-8 || II[i]*0 != 0) II[i] = 0.0;\n\t\t//II=fabs(S11[i]*S22[i]-S12[i]*S12[i]);\n\t}}\n\t\n\t// Newtonian viscosity\n\tif(fluidType == viscType::NEWTONIAN)\n\t{\n\t// Loop only for particles near mesh\n#pragma omp parallel for\n\t\t//for(int im=0;im<nPartNearMesh;im++) {\n\t\t//int i = partNearMesh[im];\n\t\tfor(int i=0; i<numParticles; i++) {\n\t\t//if(particleType[i] == fluid) {\n\t\tif(particleType[i] == fluid && particleNearWall[i] == true) {\n\t\t\tif(PTYPE[i] <= 1)MEU[i] = KNM_VS1 * DNS_FL1;\n\t\t\tif(PTYPE[i] != 1)MEU[i] = KNM_VS2 * DNS_FL2;\n\t\t}}\n\n//\t\tif(TURB>0)\n//\t\t{\n//\t\t\tNEUt[i] = Cs*DL*Cs*DL*2.0*sqrt(II[i]);\n\n//\t\t\tif(NEUt[i] * 0 != 0)  NEUt[i] = 0.0;\n//\t\t\tif(NEUt[i]>1.0)     NEUt[i] = 1.0;\n//\t\t}\n\t}\n\n\t// Granular Fluid\n\tif(fluidType == viscType::NON_NEWTONIAN)\n\t{\n\t\t// PROBLEMS TO USE OPENMP HERE. MAYBE THE ACCESS TO BL, WL\n\t\t// Loop only for particles near mesh\n//#pragma omp parallel for\n\t\t//for(int im=0;im<nPartNearMesh;im++) {\n\t\t//int i = partNearMesh[im];\n\t\tfor(int i=0; i<numParticles; i++) {\n\t\t//if(particleType[i] == fluid) {\n\t\tif(particleType[i] == fluid && particleNearWall[i] == true) {\n//\t\t\tdouble accX = 0.0;\t\t\tdouble accY = 0.0;\t\t\tdouble accZ = 0.0;\n\t\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\t\tdouble velXi = vel[i*3  ];\tdouble velYi = vel[i*3+1];\tdouble velZi = vel[i*3+2];\n\t\t\tdouble vel2i = velXi*velXi + velYi*velYi + velZi*velZi;\n\n\t\t\tif(PTYPE[i] == 1) {\n\t\t\t\tMEU[i] = KNM_VS1 * DNS_FL1;\n\t\t\t}\n\t\t\telse if(PTYPE[i] == 2) {\n\t\t\t\tphi = (Cv[i] - 0.25)*PHI_1/(1.0 - 0.25);\n\t\t\t\tphi2 = (Cv[i] - 0.25)*PHI_2/(1.0 - 0.25);\n\t\t\t\tif(Cv[i] <= 0.25) { phi = 1.0e-8; phi2 = 1.0e-8; } // phi close to zero\n\t\t\t\tif(PTYPE[i] <= 0) phi = PHI_BED;\n\n\t\t\t\t// normal stress calculation (mehcanical pressure)\n\t\t\t\tp_rheo_new[i] = p_smooth[i];\n\n\t\t\t\tint kx = int( (posXi - Xmin)/aaL0 ) + 1;\n\t\t\t\tint ky = int( (posYi - Ymin)/aaL0 ) + 1;\n\n\t\t\t\t// Effective pressure = total pressure (from EOS) - hydrostatic pressure\n\t\t\t\t//normal_stress = (BL[kx][ky] - posZi + partDist*0.5)*(DNS_FL2)*gravityMod;\t// normal_stress= Gama.H\n\t\t\t\tnormal_stress = (BL[kx][ky] - posZi + partDist*0.5)*(DNS_FL2 - DNS_FL1)*gravityMod - vel2i*(DNS_FL2 - DNS_FL1)*0.5;\t// normal_stress= Gama.H\n\n\t\t\t\tif(p_smooth[i] < (WL[kx][ky] - posZi)*DNS_FL1*gravityMod) p_smooth[i] = (WL[kx][ky] - posZi)*DNS_FL1*gravityMod;\n\t\t\t\tif(timeCurrent <= 1.0) normal_stress = (1.0 - timeCurrent)*(p_smooth[i] - (WL[kx][ky] - posZi)*DNS_FL1*gravityMod) + timeCurrent*normal_stress;\n\n//\t\t\t\tnormal_stress = p_smooth[i] - (WL[kx][ky] - posZi)*DNS_FL1*gravityMod;\n//\t\t\t\tnormal_stress = p_smooth[i];\n\t\t\t\t//normal_stress=normal_stress*0.61*1500/DNS_FL2;\n\t\t\t\tif(normal_stress < 1.0 || Cv[i] < 0.5) normal_stress = 1.0;\n\n\t\t\t\tp_rheo_new[i] = normal_stress;\n\n\t\t\t\t// Yield stress calculation\n\t\t\t\t//Inertia[i] = sqrt(II[i])*DG/sqrt(normal_stress/DNS_SDT);\t\t// Free-fall (dry granular material)\n\t\t\t\tInertia[i] = sqrt(II[i])*DG/sqrt(normal_stress/(DNS_FL1*Cd));\t// Grain inertia (submerged)\n\t\t\t\t//Inertia[i] = sqrt(II[i])*(KNM_VS1*DNS_FL1)/normal_stress ;\t// Viscous regime\n\n\t\t\t\t// VF_max VF_min\n\t\t\t\tVF[i] = VF_max - (VF_max - VF_min)*Inertia[i];\n\t\t\t\tif(VF[i] < VF_min) VF[i] = VF_min;\n\t\t\t\tRHO[i] = DNS_SDT * VF[i] + (1.0-VF[i])*DNS_FL1;\n\t\t\t\tphi = phi * VF[i] / VF_max;\n\n\t\t\t\tdouble yield_stress = cohes * cos(phi) + normal_stress * sin(phi);\n\n\t\t\t\tif(yield_stress < 1.0e-8) yield_stress = 0.0;\n\n\t\t\t\tdouble visc_max = (yield_stress*mm*0.5 + MEU0);\n\n\t\t\t\tif(II[i] > 1.0e-8)\n\t\t\t\t\tMEU_Y[i] = yield_stress*(1.0 - exp(-mm*sqrt(II[i])))*0.5/sqrt(II[i]);\n\t\t\t\telse\n\t\t\t\t\tMEU_Y[i] = visc_max;\n\n\t\t\t\t// H-B rheology\n\n\t\t\t\t//meu_0 = MEU0;\n\n\t\t\t\t// Non-linear Meu(I) rheology\n\t\t\t\t//meu_0 = 0.5*(tan(phi2) - tan(phi))*normal_stress*DG/(I0*sqrt(normal_stress/DNS_FL2)+sqrt(II[i])*DG);\t\t\t//free fall\n\t\t\t\tmeu_0 = 0.5*(tan(phi2) - tan(phi))*normal_stress*DG/(I0*sqrt(normal_stress/(DNS_FL1*Cd))+sqrt(II[i])*DG);\t\t//grain inertia\n\t\t\t   \t//meu_0 = 0.5*(tan(phi2) - tan(phi))*normal_stress*(KNM_VS1*DNS_FL1)/(I0*normal_stress+sqrt(II[i])*(KNM_VS1*DNS_FL1));\t//viscous\n\t\t\t   \t\n\t\t\t   \t// Linear Meu(I) rheology\n\t\t\t   \t//meu_0 = 0.5*(tan(phi2) - tan(phi))*DG*sqrt(normal_stress*DNS_FL2)/I0;\t\t//free fall\n\t\t\t   \t//meu_0 = 0.5*(tan(phi2) - tan(phi))*DG*sqrt(normal_stress*DNS_FL1*Cd)/I0;\t//grain inertia\n\t\t\t   \t//meu_0 = 0.5*(tan(phi2) - tan(phi))*(KNM_VS1*DNS_FL1)/I0;\t\t\t\t\t//viscous\n\n\t\t\t\tif(II[i] <= 1.0e-8 || (meu_0*0) != 0) meu_0 = MEU0;\n\n\t\t\t\tvisc_max = (yield_stress*mm*0.5 + meu_0);\n\n\t\t\t\t// Herschel bulkley papanastasiou\n\t\t\t\tMEU[i] = MEU_Y[i] + MEU0*pow(4.0*II[i], (N - 1.0)*0.5);\n\n\t\t\t\t// MEU_Y rheological model\n\t\t\t\t//MEU[i] = MEU_Y[i] + meu_0;\n\t\t\t\t\n\t\t\t\tif(II[i] == 0 || MEU[i]>visc_max) MEU[i] = visc_max;\n\t\t\t\tif(PTYPE[i] <= 0) MEU[i] = MEU[i]*Cv[i] + DNS_FL1*KNM_VS1*(1.0 - Cv[i]);\n\t\t\t}\n\t\t\t\n\t\t\tif(PTYPE[i] >= 2) {\n\t\t\t\tif(Cv[i] > 0.5) RHO[i] = DNS_FL2;\n\t\t\t\telse RHO[i] = Cv[i]*DNS_FL2 + (1.0 - Cv[i])*DNS_FL1;\n\t\t\t}\n\t\t}}\n\n\t\t//---------------------------------- Direct stress calculation method -----------------------------------------\n//\t\tif(stress_cal_method == 2)\n//\t\t{\n//\t\t\tfor(i = 1; i <= NUM; i++)\n//\t\t\t{\n//\t\t\t\tdouble sum1 = 0.0, sum2 = 0.0, sum3 = 0.0, sum4 = 0.0, sum5 = 0.0, sum6 = 0.0, sum7 = 0.0, sum8 = 0.0, sum9 = 0.0, sum10 = 0.0;\n//\t\t\t\tfor(l = 2; l <= neighb[i][1]; l++)\n//\t\t\t\t{\n//\t\t\t\t\tj = neighb[i][l];\n//\t\t\t\t\td = DIST(i, j);\n//\t\t\t\t\tif(i != j && d <= re)\n//\t\t\t\t\t{\n//\t\t\t\t\t\tw = W(d, KTYPE, 2);\n\n//\t\t\t\t\t\tdouble meuij = 2.0 * MEU[i] * MEU[j] / (MEU[i] + MEU[j]);\n//\t\t\t\t\t\tif((NEUt[i] + NEUt[j])>0) meuij = meuij + 2.0 * NEUt[i] * RHO[i] * NEUt[j] * RHO[j] / (NEUt[i] * RHO[i] + NEUt[j] * RHO[j]);\n\n//\t\t\t\t\t\tsum1 = sum1 + meuij * (x_vel[j] - x_vel[i])*DX(i, j)*w / d / d;\n//\t\t\t\t\t\tsum2 = sum2 + meuij * (x_vel[j] - x_vel[i])*DY(i, j)*w / d / d;\n//\t\t\t\t\t\tsum3 = sum3 + meuij * (x_vel[j] - x_vel[i])*DZ(i, j)*w / d / d;\n\n//\t\t\t\t\t\tsum4 = sum4 + meuij * (y_vel[j] - y_vel[i])*DX(i, j)*w / d / d;\n//\t\t\t\t\t\tsum5 = sum5 + meuij * (y_vel[j] - y_vel[i])*DY(i, j)*w / d / d;\n//\t\t\t\t\t\tsum6 = sum6 + meuij * (y_vel[j] - y_vel[i])*DZ(i, j)*w / d / d;\n\n//\t\t\t\t\t\tsum7 = sum7 + meuij * (z_vel[j] - z_vel[i])*DX(i, j)*w / d / d;\n//\t\t\t\t\t\tsum8 = sum8 + meuij * (z_vel[j] - z_vel[i])*DY(i, j)*w / d / d;\n//\t\t\t\t\t\tsum9 = sum9 + meuij * (z_vel[j] - z_vel[i])*DZ(i, j)*w / d / d;\n//\t\t\t\t\t}\n//\t\t\t\t}\n\n//\t\t\t\tTau_xx[i] = (dim / n0) * 2.0 * sum1;\n//\t\t\t\tTau_yy[i] = (dim / n0) * 2.0 * sum5;\n//\t\t\t\tTau_zz[i] = (dim / n0) * 2.0 * sum9;\n\n//\t\t\t\tTau_xy[i] = (dim / n0)*(sum2 + sum4);\n//\t\t\t\tTau_xz[i] = (dim / n0)*(sum3 + sum7);\n//\t\t\t\tTau_yz[i] = (dim / n0)*(sum6 + sum8);\n//\t\t\t}\n//\t\t}\n\n\t} // if(fluidType == viscType::NON_NEWTONIAN)\n\n\t//---------------------------------------------------------------\n\n//\tdelete[]S11; delete[]S12; delete[]S13; delete[]S22; delete[]S23; delete[]S33; delete[]BL; delete[]WL; delete[]PS;// delete[]p_smooth;\n//\tS11 = NULL; S12 = NULL; S13 = NULL; S22 = NULL; S23 = NULL; S33 = NULL; BL = NULL; WL = NULL; PS = NULL;// p_smooth = NULL;\n\n\tdelete[]BL; delete[]WL; delete[]PS;\n\tBL = NULL; WL = NULL; PS = NULL;\n}\n\n// No-Slip condition. Viscosity interaction values\nvoid MpsParticle::calcWallNoSlipViscosityInteractionVal() {\n\n\tdouble gravityMod = sqrt(gravityX*gravityX + gravityY*gravityY + gravityZ*gravityZ);\n\n\t//double  *S12, *S13, *S23, *S11, *S22, *S33, d, phi = 0.0, phi2 = 0.0, meu_0, normal_stress;//, grain_VF, *p_smooth;\n\tdouble d, phi = 0.0, phi2 = 0.0, meu_0, normal_stress;\n\tdouble **BL, **WL, **PS;\n\n\t// Changed !!!\n\t// Be carefull to assign all domain\n\tdouble Xmin, Xmax, Ymin, Ymax, Zmin; // Minimum and maximum of searching grid\n\t// dam1610\n//\tXmin = 0.0 - partDist*3.0; Xmax = 1.65 + partDist*3.0;\n//\tYmin = 0.0 - partDist*3.0; Ymax = 0.15 + partDist*3.0;\n\tZmin = 0.0 - partDist*3.0; //Zmax = 0.7 + partDist*30.0;\n\t// damErosion3D\n\tXmin = 0.0 - partDist*3.0; Xmax = 2.00 + partDist*3.0;\n\tYmin = 0.0 - partDist*3.0; Ymax = 0.10 + partDist*3.0;\n\t// Changed !!!\n\n\t// Search free-surface particles for each interval of aa = 2 particles in wall\n\tdouble aaL0 = 2.0*partDist;\n\tint kx_max = int( (Xmax - Xmin)/aaL0 ) + 1;\n\tint ky_max = int( (Ymax - Ymin)/aaL0 ) + 1;\n\n\tdouble Uxx, Uxy, Uxz, Uyx, Uyy, Uyz, Uzx, Uzy, Uzz;\n/*\n\tS11 = new double[numParticles + 1];\n\tS22 = new double[numParticles + 1];\n\tS33 = new double[numParticles + 1];\n\tS12 = new double[numParticles + 1];\n\tS13 = new double[numParticles + 1];\n\tS23 = new double[numParticles + 1];\n*/\n\t//p_smooth = new double[numParticles + 1];\n\tBL = new double*[kx_max + 1];  // bed level\n\tWL = new double*[kx_max + 1];  // water level\n\tPS = new double*[kx_max + 1];  // pressure sediment\n\n#pragma omp parallel for\n\tfor(int m = 1; m <= kx_max; m++)\n\t{\n\t\tBL[m] = new double[ky_max + 1];\n\t\tWL[m] = new double[ky_max + 1];\n\t\tPS[m] = new double[ky_max + 1];\n\t}\n\n\t// Determining the bed level\n#pragma omp parallel for schedule(dynamic,64)\n\tfor(int kx = 1; kx <= kx_max; kx++)\n\t{\n\t\tfor(int ky = 1; ky <= ky_max; ky++)\n\t\t{\n\t\t\tBL[kx][ky] = Zmin;\n\t\t\tWL[kx][ky] = Zmin;\n\t\t}\n\t}\n\n#pragma omp parallel for\n\tfor(int i=0; i<numParticles; i++) {\n\t\tif(particleType[i] == fluid) {\n\t\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\t\n\t\t\tint kx = int( (posXi - Xmin)/aaL0 ) + 1;\n\t\t\tint ky = int( (posYi - Ymin)/aaL0 ) + 1;\n\n\t\t\t//if(posZi>BL[kx][ky] && Cv[i]>0.5) { BL[kx][ky] = posZi; PS[kx][ky] = pnew[i]; }\n\t\t\tif(posZi>BL[kx][ky] && Cv[i]>0.5) { BL[kx][ky] = posZi; PS[kx][ky] = press[i]; }\n\t\t\tif(posZi>WL[kx][ky] && PTYPE[i] == 1) { WL[kx][ky] = posZi; }\n\t\t}\n\t}\n\n\t// Strain rate calculation\n\t//int nPartNearMesh = partNearMesh.size();\n\t//printf(\" Mesh %d \\n\", partNearMesh);\n\t// Loop only for particles near mesh\n#pragma omp parallel for schedule(dynamic,64)\n\t//for(int im=0;im<nPartNearMesh;im++) {\n\t//int i = partNearMesh[im];\n\tfor(int i=0; i<numParticles; i++) {\n\t//if(particleType[i] == fluid) {\n\tif(particleType[i] == fluid && particleNearWall[i] == true) {\n\t\tdouble sum1 = 0.0, sum2 = 0.0, sum3 = 0.0, sum4 = 0.0, sum5 = 0.0, sum6 = 0.0, sum7 = 0.0, sum8 = 0.0, sum9 = 0.0, sum10 = 0.0;\n\n//\t\tdouble accX = 0.0;\t\t\tdouble accY = 0.0;\t\t\tdouble accZ = 0.0;\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble velXi = vel[i*3  ];\tdouble velYi = vel[i*3+1];\tdouble velZi = vel[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n//\t\tdouble velXi = Velk[i*3  ];\tdouble velYi = Velk[i*3+1];\tdouble velZi = Velk[i*3+2];\n\n\t\t// Transformation matrix R_i = I\n\t\tdouble Rref_i[9], Rinv_i[9], normaliw[3], normalMod2;\n\t    // normal fluid-wall particle = 0.5*(normal fluid-mirror particle)\n\t    normaliw[0] = 0.5*(posXi - posMirrorXi); normaliw[1] = 0.5*(posYi - posMirrorYi); normaliw[2] = 0.5*(posZi - posMirrorZi);\n\t    normalMod2 = normaliw[0]*normaliw[0] + normaliw[1]*normaliw[1] + normaliw[2]*normaliw[2];\n\n\t    if(normalMod2 > 1.0e-8) {\n\t    \tdouble normalMod = sqrt(normalMod2);\n\t    \tnormaliw[0] = normaliw[0]/normalMod;\n\t    \tnormaliw[1] = normaliw[1]/normalMod;\n\t    \tnormaliw[2] = normaliw[2]/normalMod;\n\t    }\n\t    else {\n\t    \tnormaliw[0] = 0;\n\t    \tnormaliw[1] = 0;\n\t    \tnormaliw[2] = 0;\n\t    }\n\n\t    //  Inverse transformation matrix Rinv_i = - I\n\t    Rinv_i[0] = -1.0; Rinv_i[1] =  0.0; Rinv_i[2] =  0.0;\n\t\tRinv_i[3] =  0.0; Rinv_i[4] = -1.0; Rinv_i[5] =  0.0;\n\t\tRinv_i[6] =  0.0; Rinv_i[7] =  0.0; Rinv_i[8] = -1.0;\n\n\t\t//  Transformation matrix Rref_i = I - 2.0*normal_iwall*normal_iwall\n\t    Rref_i[0] = 1.0 - 2.0*normaliw[0]*normaliw[0]; Rref_i[1] = 0.0 - 2.0*normaliw[0]*normaliw[1]; Rref_i[2] = 0.0 - 2.0*normaliw[0]*normaliw[2];\n\t\tRref_i[3] = 0.0 - 2.0*normaliw[1]*normaliw[0]; Rref_i[4] = 1.0 - 2.0*normaliw[1]*normaliw[1]; Rref_i[5] = 0.0 - 2.0*normaliw[1]*normaliw[2];\n\t\tRref_i[6] = 0.0 - 2.0*normaliw[2]*normaliw[0]; Rref_i[7] = 0.0 - 2.0*normaliw[2]*normaliw[1]; Rref_i[8] = 1.0 - 2.0*normaliw[2]*normaliw[2];\n\n\t\tdouble viwall[3], vtil[3];\n\t\t// Wall velocity (0 if fixed)\n\t\tviwall[0]=viwall[1]=viwall[2]=0.0;\n\n\t\tif(nearMeshType[i] == meshType::FORCED) {\n\t\t\tviwall[0] = velVWall[0];\n\t\t\tviwall[1] = velVWall[1];\n\t\t\tviwall[2] = velVWall[2];\n\t\t}\n\n\t\t// normal_iwall*v_iwall\n\t\tdouble dotnv = normaliw[0]*viwall[0] + normaliw[1]*viwall[1] + normaliw[2]*viwall[2];\n\t\t// vtil = vi - 2 {v_iwall - (normal_iwall*v_iwall)normal_iwall}\n\t\tvtil[0] = velXi - 2.0*(viwall[0] - dotnv*normaliw[0]);\n\t\tvtil[1] = velYi - 2.0*(viwall[1] - dotnv*normaliw[1]);\n\t\tvtil[2] = velZi - 2.0*(viwall[2] - dotnv*normaliw[2]);\n\t\t// Mirror particle velocity vi' = Ri_inv * [vi - 2 {v_iwall - (normal_iwall*v_iwall)normal_iwall}] \n      \tdouble velMirrorXi = (Rinv_i[0]*vtil[0] + Rinv_i[1]*vtil[1] + Rinv_i[2]*vtil[2]);\n\t\tdouble velMirrorYi = (Rinv_i[3]*vtil[0] + Rinv_i[4]*vtil[1] + Rinv_i[5]*vtil[2]);\n\t\tdouble velMirrorZi = (Rinv_i[6]*vtil[0] + Rinv_i[7]*vtil[1] + Rinv_i[8]*vtil[2]);\n\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and im (intersection) and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reS2 && dstimj2 < reS2 && dstij2 < dstimj2) {\n\t\t\t\tif(j != i) {\n\t\t\t\t\tdouble dst = sqrt(dstimj2);\n\t\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\n\t\t\t\t\tdouble vec_mijx = vel[j*3  ]-velMirrorXi;\t\n\t\t\t\t\tdouble vec_mijy = vel[j*3+1]-velMirrorYi;\t\n\t\t\t\t\tdouble vec_mijz = vel[j*3+2]-velMirrorZi;\n\n\t\t\t\t\tsum1 += vec_mijx*v0imj*wS/dstimj2;\n\t\t\t\t\tsum2 += vec_mijx*v1imj*wS/dstimj2;\n\t\t\t\t\tsum3 += vec_mijx*v2imj*wS/dstimj2;\n\t\t\t\t\t\n\t\t\t\t\tsum4 += vec_mijy*v0imj*wS/dstimj2;\n\t\t\t\t\tsum5 += vec_mijy*v1imj*wS/dstimj2;\n\t\t\t\t\tsum6 += vec_mijy*v2imj*wS/dstimj2;\n\t\t\t\t\t\n\t\t\t\t\tsum7 += vec_mijz*v0imj*wS/dstimj2;\n\t\t\t\t\tsum8 += vec_mijz*v1imj*wS/dstimj2;\n\t\t\t\t\tsum9 += vec_mijz*v2imj*wS/dstimj2;\n\t\t\t\t\t\n\t\t\t\t\tsum10 += press[j]*wS;\n\t\t\t\t}}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\n\t\t// Rinv_i * gradU * Rref_i = - gradU * Rref_i\n\t\t// coeffPressGrad is a negative cte (-dim/pndGradientZero)\n\t\tUxx = coeffPressGrad*(sum1*Rref_i[0] + sum2*Rref_i[3] + sum3*Rref_i[6]);\n\t\tUxy = coeffPressGrad*(sum1*Rref_i[1] + sum2*Rref_i[4] + sum3*Rref_i[7]);\n\t\tUxz = coeffPressGrad*(sum1*Rref_i[2] + sum2*Rref_i[5] + sum3*Rref_i[8]);\n\n\t\tUyx = coeffPressGrad*(sum4*Rref_i[0] + sum5*Rref_i[3] + sum6*Rref_i[6]);\n\t\tUyy = coeffPressGrad*(sum4*Rref_i[1] + sum5*Rref_i[4] + sum6*Rref_i[7]);\n\t\tUyz = coeffPressGrad*(sum4*Rref_i[2] + sum5*Rref_i[5] + sum6*Rref_i[8]);\n\n\t\tUzx = coeffPressGrad*(sum7*Rref_i[0] + sum8*Rref_i[3] + sum9*Rref_i[6]);\n\t\tUzy = coeffPressGrad*(sum7*Rref_i[1] + sum8*Rref_i[4] + sum9*Rref_i[7]);\n\t\tUzz = coeffPressGrad*(sum7*Rref_i[2] + sum8*Rref_i[5] + sum9*Rref_i[8]);\n\n\t\t// Addition of smoothed pressure for particles near mesh\n\t\tp_smooth[i] += sum10/pndGradientZero;\n\t\tif(p_smooth[i] < 1.0e-8) p_smooth[i] = 0.0;\n\n\t\t// - (Rref_i * gradU) - (Rref_i * gradU)t\n\t\tS11[i] = 0.5*(Uxx + Uxx);\n\t\tS12[i] = 0.5*(Uxy + Uyx);\n\t\tS13[i] = 0.5*(Uxz + Uzx);\n\t\tS22[i] = 0.5*(Uyy + Uyy);\n\t\tS23[i] = 0.5*(Uyz + Uzy);\n\t\tS33[i] = 0.5*(Uzz + Uzz);\n\n\t\t//II[i] = 0.5*Uxx*Uxx + 0.5*Uyy*Uyy + 0.25*(Uxy + Uyx)*(Uxy + Uyx);\n\t\t\n\t\t// Addition of II for particles near mesh\n\t\t//II[i] += 0.5*(S11[i]*S11[i] + S12[i]*S12[i] + S13[i]*S13[i] + S12[i]*S12[i] + S22[i]*S22[i] + S23[i]*S23[i] + S13[i]*S13[i] + S23[i]*S23[i] + S33[i]*S33[i]);\n\t\tII[i] += 0.5*(S11[i]*S11[i] + 2.0*S12[i]*S12[i] + 2.0*S13[i]*S13[i] + S22[i]*S22[i] + 2.0*S23[i]*S23[i] + S33[i]*S33[i]);\n//\t\tII[i] = 0.5*(S11[i]*S11[i] + S12[i]*S12[i] + S13[i]*S13[i] + S12[i]*S12[i] + S22[i]*S22[i] + S23[i]*S23[i] + S13[i]*S13[i] + S23[i]*S23[i] + S33[i]*S33[i]);\n\t\t//II[i]= S11[i]*S22[i] +S22[i]*S33[i]+ S11[i]*S33[i] - S12[i]*S12[i] -S13[i]*S13[i]- S23[i]*S23[i] ;\n\t\tif(II[i] < 1.0e-8 || II[i]*0 != 0) II[i] = 0.0;\n\t\t//II=fabs(S11[i]*S22[i]-S12[i]*S12[i]);\n\t}}\n\t\n\t// Newtonian viscosity\n\tif(fluidType == viscType::NEWTONIAN)\n\t{\n\t// Loop only for particles near mesh\n#pragma omp parallel for\n\t\t//for(int im=0;im<nPartNearMesh;im++) {\n\t\t//int i = partNearMesh[im];\n\t\tfor(int i=0; i<numParticles; i++) {\n\t\t//if(particleType[i] == fluid) {\n\t\tif(particleType[i] == fluid && particleNearWall[i] == true) {\n\t\t\tif(PTYPE[i] <= 1)MEU[i] = KNM_VS1 * DNS_FL1;\n\t\t\tif(PTYPE[i] != 1)MEU[i] = KNM_VS2 * DNS_FL2;\n\t\t}}\n\n//\t\tif(TURB>0)\n//\t\t{\n//\t\t\tNEUt[i] = Cs*DL*Cs*DL*2.0*sqrt(II[i]);\n\n//\t\t\tif(NEUt[i] * 0 != 0)  NEUt[i] = 0.0;\n//\t\t\tif(NEUt[i]>1.0)     NEUt[i] = 1.0;\n//\t\t}\n\t}\n\n\t// Granular Fluid\n\tif(fluidType == viscType::NON_NEWTONIAN)\n\t{\n\t\t// PROBLEMS TO USE OPENMP HERE. MAYBE THE ACCESS TO BL, WL\n\t\t// Loop only for particles near mesh\n//#pragma omp parallel for\n\t\t//for(int im=0;im<nPartNearMesh;im++) {\n\t\t//int i = partNearMesh[im];\n\t\tfor(int i=0; i<numParticles; i++) {\n\t\t//if(particleType[i] == fluid) {\n\t\tif(particleType[i] == fluid && particleNearWall[i] == true) {\n//\t\t\tdouble accX = 0.0;\t\t\tdouble accY = 0.0;\t\t\tdouble accZ = 0.0;\n\t\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\t\tdouble velXi = vel[i*3  ];\tdouble velYi = vel[i*3+1];\tdouble velZi = vel[i*3+2];\n\t\t\tdouble vel2i = velXi*velXi + velYi*velYi + velZi*velZi;\n\n\t\t\tif(PTYPE[i] == 1) \n\t\t\t\tMEU[i] = KNM_VS1 * DNS_FL1;\n\t\t\telse if(PTYPE[i] == 2) {\n\t\t\t\tphi = (Cv[i] - 0.25)*PHI_1/(1.0 - 0.25);\n\t\t\t\tphi2 = (Cv[i] - 0.25)*PHI_2/(1.0 - 0.25);\n\t\t\t\tif(Cv[i] <= 0.25) { phi = 1.0e-8; phi2 = 1.0e-8; } // phi close to zero\n\t\t\t\tif(PTYPE[i] <= 0) phi = PHI_BED;\n\n\t\t\t\t// normal stress calculation (mechanical pressure)\n\t\t\t\tp_rheo_new[i] = p_smooth[i];\n\n\t\t\t\tint kx = int( (posXi - Xmin)/aaL0 ) + 1;\n\t\t\t\tint ky = int( (posYi - Ymin)/aaL0 ) + 1;\n\n\t\t\t\t// Effective pressure = total pressure (from EOS) - hydrostatic pressure\n\t\t\t\t//normal_stress = (BL[kx][ky] - posZi + partDist*0.5)*(DNS_FL2)*gravityMod;\t// normal_stress= Gama.H\n\t\t\t\tnormal_stress = (BL[kx][ky] - posZi + partDist*0.5)*(DNS_FL2 - DNS_FL1)*gravityMod - vel2i*(DNS_FL2 - DNS_FL1)*0.5;\t// normal_stress= Gama.H\n\n\t\t\t\tif(p_smooth[i] < (WL[kx][ky] - posZi)*DNS_FL1*gravityMod) p_smooth[i] = (WL[kx][ky] - posZi)*DNS_FL1*gravityMod;\n\t\t\t\tif(timeCurrent <= 1.0) normal_stress = (1.0 - timeCurrent)*(p_smooth[i] - (WL[kx][ky] - posZi)*DNS_FL1*gravityMod) + timeCurrent*normal_stress;\n\n//\t\t\t\tnormal_stress = p_smooth[i] - (WL[kx][ky] - posZi)*DNS_FL1*gravityMod;\n//\t\t\t\tnormal_stress = p_smooth[i];\n\t\t\t\t//normal_stress=normal_stress*0.61*1500/DNS_FL2;\n\t\t\t\tif(normal_stress < 1.0 || Cv[i] < 0.5) normal_stress = 1.0;\n\n\t\t\t\tp_rheo_new[i] = normal_stress;\n\n\t\t\t\t// Yield stress calculation\n\t\t\t\t//Inertia[i] = sqrt(II[i])*DG/sqrt(normal_stress/DNS_SDT);\t\t// Free-fall (dry granular material)\n\t\t\t\tInertia[i] = sqrt(II[i])*DG/sqrt(normal_stress/(DNS_FL1*Cd));\t// Grain inertia (submerged)\n\t\t\t\t//Inertia[i] = sqrt(II[i])*(KNM_VS1*DNS_FL1)/normal_stress ;\t// Viscous regime\n\n\t\t\t\t// VF_max VF_min\n\t\t\t\tVF[i] = VF_max - (VF_max - VF_min)*Inertia[i];\n\t\t\t\tif(VF[i] < VF_min) VF[i] = VF_min;\n\t\t\t\tRHO[i] = DNS_SDT*VF[i] + (1.0-VF[i])*DNS_FL1;\n\t\t\t\tphi = phi*VF[i]/VF_max;\n\n\t\t\t\tdouble yield_stress = cohes*cos(phi) + normal_stress*sin(phi);\n\n\t\t\t\tif(yield_stress < 0.0) yield_stress = 0.0;\n\n\t\t\t\tdouble visc_max = (yield_stress*mm*0.5 + MEU0);\n\n\t\t\t\tif(II[i] > 1.0e-8)\n\t\t\t\t\tMEU_Y[i] = yield_stress*(1.0 - exp(-mm*sqrt(II[i])))*0.5/sqrt(II[i]);\n\t\t\t\telse\n\t\t\t\t\tMEU_Y[i] = visc_max;\n\n\t\t\t\t// H-B rheology\n\n\t\t\t\t//meu_0 = MEU0;\n\n\t\t\t\t// Non-linear Meu(I) rheology\n\t\t\t\t//meu_0 = 0.5*(tan(phi2) - tan(phi))*normal_stress*DG/(I0*sqrt(normal_stress/DNS_FL2)+sqrt(II[i])*DG);\t\t\t//free fall\n\t\t\t\tmeu_0 = 0.5*(tan(phi2) - tan(phi))*normal_stress*DG/(I0*sqrt(normal_stress/(DNS_FL1*Cd))+sqrt(II[i])*DG);\t\t//grain inertia\n\t\t\t   \t//meu_0 = 0.5*(tan(phi2) - tan(phi))*normal_stress*(KNM_VS1*DNS_FL1)/(I0*normal_stress+sqrt(II[i])*(KNM_VS1*DNS_FL1));\t//viscous\n\t\t\t   \t\n\t\t\t   \t// Linear Meu(I) rheology\n\t\t\t   \t//meu_0 = 0.5*(tan(phi2) - tan(phi))*DG*sqrt(normal_stress*DNS_FL2)/I0;\t\t//free fall\n\t\t\t   \t//meu_0 = 0.5*(tan(phi2) - tan(phi))*DG*sqrt(normal_stress*DNS_FL1*Cd)/I0;\t//grain inertia\n\t\t\t   \t//meu_0 = 0.5*(tan(phi2) - tan(phi))*(KNM_VS1*DNS_FL1)/I0;\t\t\t\t\t//viscous\n\n\t\t\t\tif(II[i] <= 1.0e-8 || (meu_0*0) != 0) meu_0 = MEU0;\n\n\t\t\t\tvisc_max = (yield_stress*mm*0.5 + meu_0);\n\n\t\t\t\t// Herschel bulkley papanastasiou\n\t\t\t\tMEU[i] = MEU_Y[i] + MEU0*pow(4.0*II[i], (N - 1.0)*0.5);\n\n\t\t\t\t// MEU_Y rheological model\n\t\t\t\t//MEU[i] = MEU_Y[i] + meu_0;\n\t\t\t\t\n\t\t\t\tif(II[i] == 0 || MEU[i]>visc_max) MEU[i] = visc_max;\n\t\t\t\tif(PTYPE[i] <= 0) MEU[i] = MEU[i]*Cv[i] + DNS_FL1*KNM_VS1*(1.0 - Cv[i]);\n\t\t\t}\n\t\t\t\n\t\t\tif(PTYPE[i] >= 2) {\n\t\t\t\tif(Cv[i] > 0.5) RHO[i] = DNS_FL2;\n\t\t\t\telse RHO[i] = Cv[i]*DNS_FL2 + (1.0 - Cv[i])*DNS_FL1;\n\t\t\t}\n\t\t}}\n\n\t\t//---------------------------------- Direct stress calculation method -----------------------------------------\n//\t\tif(stress_cal_method == 2)\n//\t\t{\n//\t\t\tfor(i = 1; i <= NUM; i++)\n//\t\t\t{\n//\t\t\t\tdouble sum1 = 0.0, sum2 = 0.0, sum3 = 0.0, sum4 = 0.0, sum5 = 0.0, sum6 = 0.0, sum7 = 0.0, sum8 = 0.0, sum9 = 0.0, sum10 = 0.0;\n//\t\t\t\tfor(l = 2; l <= neighb[i][1]; l++)\n//\t\t\t\t{\n//\t\t\t\t\tj = neighb[i][l];\n//\t\t\t\t\td = DIST(i, j);\n//\t\t\t\t\tif(i != j && d <= re)\n//\t\t\t\t\t{\n//\t\t\t\t\t\tw = W(d, KTYPE, 2);\n\n//\t\t\t\t\t\tdouble meuij = 2.0 * MEU[i] * MEU[j] / (MEU[i] + MEU[j]);\n//\t\t\t\t\t\tif((NEUt[i] + NEUt[j])>0) meuij = meuij + 2.0 * NEUt[i] * RHO[i] * NEUt[j] * RHO[j] / (NEUt[i] * RHO[i] + NEUt[j] * RHO[j]);\n\n//\t\t\t\t\t\tsum1 = sum1 + meuij * (x_vel[j] - x_vel[i])*DX(i, j)*w / d / d;\n//\t\t\t\t\t\tsum2 = sum2 + meuij * (x_vel[j] - x_vel[i])*DY(i, j)*w / d / d;\n//\t\t\t\t\t\tsum3 = sum3 + meuij * (x_vel[j] - x_vel[i])*DZ(i, j)*w / d / d;\n\n//\t\t\t\t\t\tsum4 = sum4 + meuij * (y_vel[j] - y_vel[i])*DX(i, j)*w / d / d;\n//\t\t\t\t\t\tsum5 = sum5 + meuij * (y_vel[j] - y_vel[i])*DY(i, j)*w / d / d;\n//\t\t\t\t\t\tsum6 = sum6 + meuij * (y_vel[j] - y_vel[i])*DZ(i, j)*w / d / d;\n\n//\t\t\t\t\t\tsum7 = sum7 + meuij * (z_vel[j] - z_vel[i])*DX(i, j)*w / d / d;\n//\t\t\t\t\t\tsum8 = sum8 + meuij * (z_vel[j] - z_vel[i])*DY(i, j)*w / d / d;\n//\t\t\t\t\t\tsum9 = sum9 + meuij * (z_vel[j] - z_vel[i])*DZ(i, j)*w / d / d;\n//\t\t\t\t\t}\n//\t\t\t\t}\n\n//\t\t\t\tTau_xx[i] = (dim / n0) * 2.0 * sum1;\n//\t\t\t\tTau_yy[i] = (dim / n0) * 2.0 * sum5;\n//\t\t\t\tTau_zz[i] = (dim / n0) * 2.0 * sum9;\n\n//\t\t\t\tTau_xy[i] = (dim / n0)*(sum2 + sum4);\n//\t\t\t\tTau_xz[i] = (dim / n0)*(sum3 + sum7);\n//\t\t\t\tTau_yz[i] = (dim / n0)*(sum6 + sum8);\n//\t\t\t}\n//\t\t}\n\n\t} // if(fluidType == viscType::NON_NEWTONIAN)\n\n\t//---------------------------------------------------------------\n\n//\tdelete[]S11; delete[]S12; delete[]S13; delete[]S22; delete[]S23; delete[]S33; delete[]BL; delete[]WL; delete[]PS; //delete[]p_smooth;\n//\tS11 = NULL; S12 = NULL; S13 = NULL; S22 = NULL; S23 = NULL; S33 = NULL; BL = NULL; WL = NULL; PS = NULL;// p_smooth = NULL;\n\t\n\tdelete[]BL; delete[]WL; delete[]PS;\n\tBL = NULL; WL = NULL; PS = NULL;\n}\n\n// Free-Slip condition. Add acceleration due laplacian of viscosity on wall (Polygon wall)\nvoid MpsParticle::calcWallSlipViscosity() {\n\t//int nPartNearMesh = partNearMesh.size();\n\tdouble VolumeForce = pow(partDist,dim);\n\t//printf(\" Mesh %d \\n\", nPartNearMesh);\n\t// Loop only for particles near mesh\n#pragma omp parallel for schedule(dynamic,64)\n\t//for(int im=0;im<nPartNearMesh;im++) {\n\t//int i = partNearMesh[im];\n\tfor(int i=0; i<numParticles; i++) {\n\t//if(particleType[i] == fluid) {\n\tif(particleType[i] == fluid && particleNearWall[i] == true) {\n\t\t\n\t\tdouble meu_i = MEU[i];\n\t\tdouble accX = 0.0;\t\t\tdouble accY = 0.0;\t\t\tdouble accZ = 0.0;\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble velXi = vel[i*3  ];\tdouble velYi = vel[i*3+1];\tdouble velZi = vel[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n//\t\tdouble velXi = Velk[i*3  ];\tdouble velYi = Velk[i*3+1];\tdouble velZi = Velk[i*3+2\n\n\t\t// Transformation matrix Rref_i = I - 2.0*normal_iwall*normal_iwall\n\t\tdouble Rref_i[9], normaliw[3], normalMod2;\n\t\t// Normal fluid-wall particle = 0.5*(normal fluid-mirror particle)\n\t\tnormaliw[0] = 0.5*(posXi - posMirrorXi); normaliw[1] = 0.5*(posYi - posMirrorYi); normaliw[2] = 0.5*(posZi - posMirrorZi);\n\t\tnormalMod2 = normaliw[0]*normaliw[0] + normaliw[1]*normaliw[1] + normaliw[2]*normaliw[2];\n\n\t\tif(normalMod2 > 1.0e-8) {\n\t\t\tdouble normalMod = sqrt(normalMod2);\n\t\t\tnormaliw[0] = normaliw[0]/normalMod;\n\t\t\tnormaliw[1] = normaliw[1]/normalMod;\n\t\t\tnormaliw[2] = normaliw[2]/normalMod;\n\t\t}\n\t\telse {\n\t\t\tnormaliw[0] = 0;\n\t\t\tnormaliw[1] = 0;\n\t\t\tnormaliw[2] = 0;\n\t\t}\n\n\t\t//  Transformation matrix Rref_i = I - 2.0*normal_iwall*normal_iwall\n\t\tRref_i[0] = 1.0 - 2.0*normaliw[0]*normaliw[0]; Rref_i[1] = 0.0 - 2.0*normaliw[0]*normaliw[1]; Rref_i[2] = 0.0 - 2.0*normaliw[0]*normaliw[2];\n\t\tRref_i[3] = 0.0 - 2.0*normaliw[1]*normaliw[0]; Rref_i[4] = 1.0 - 2.0*normaliw[1]*normaliw[1]; Rref_i[5] = 0.0 - 2.0*normaliw[1]*normaliw[2];\n\t\tRref_i[6] = 0.0 - 2.0*normaliw[2]*normaliw[0]; Rref_i[7] = 0.0 - 2.0*normaliw[2]*normaliw[1]; Rref_i[8] = 1.0 - 2.0*normaliw[2]*normaliw[2];\n\n\t\t// Mirror particle velocity vi' = Rref_i * vi\n\t\tdouble velMirrorXi = (Rref_i[0]*velXi + Rref_i[1]*velYi + Rref_i[2]*velZi);\n\t\tdouble velMirrorYi = (Rref_i[3]*velXi + Rref_i[4]*velYi + Rref_i[5]*velZi);\n\t\tdouble velMirrorZi = (Rref_i[6]*velXi + Rref_i[7]*velYi + Rref_i[8]*velZi);\n\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and im (intersection) and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reL2 && dstimj2 < reL2 && dstij2 < dstimj2) {\n\t\t\t\tif(j != i) {\n\t\t\t\t\tdouble dst = sqrt(dstimj2);\n\t\t\t\t\tdouble wL = weight(dst, reL, weightType);\n\t\t\t\t\tdouble neu_ij;\n\t\t\t\t\tif((meu_i + MEU[j]) > 1.0e-8)\n\t\t\t\t\t\tneu_ij = 2.0 * meu_i * MEU[j] / (meu_i + MEU[j]);\n\t\t\t\t\telse\n\t\t\t\t\t\tneu_ij = 0.0;\n\n//neu_ij = KNM_VS2 * DNS_FL2;\n\n\t\t\t\t\tif(PTYPE[i] == 1) neu_ij = neu_ij/DNS_FL1;\n\t\t\t\t\telse neu_ij = neu_ij/DNS_FL2;\n\n\t\t\t\t\t//if((NEUt[i] + NEUt[j])>0) neu_ij = neu_ij + (2.0 * NEUt[i] * RHO[j] * NEUt[j] * RHO[j] / (NEUt[i] * RHO[i] + NEUt[j] * RHO[j])) / RHO[i];\n\n\t\t\t\t\t// Original\n//\t\t\t\t\taccX +=(vel[j*3  ]-velMirrorXi)*w;\n//\t\t\t\t\taccY +=(vel[j*3+1]-velMirrorYi)*w;\n//\t\t\t\t\taccZ +=(vel[j*3+2]-velMirrorZi)*w;\n\t\t\t\t\t// Modified\n\t\t\t\t\taccX +=(vel[j*3  ]-velMirrorXi)*wL*neu_ij;\n\t\t\t\t\taccY +=(vel[j*3+1]-velMirrorYi)*wL*neu_ij;\n\t\t\t\t\taccZ +=(vel[j*3+2]-velMirrorZi)*wL*neu_ij;\n\n\t\t\t\t\t//accX +=(Velk[j*3  ]-velMirrorXi)*w;\n\t\t\t\t\t//accY +=(Velk[j*3+1]-velMirrorYi)*w;\n\t\t\t\t\t//accZ +=(Velk[j*3+2]-velMirrorZi)*w;\n\t\t\t\t}}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\n\t\t// Add \"i\" contribution (\"i\" is a neighbor of \"mirror i\")\n\t\tdouble v0imi, v1imi, v2imi, dstimi2;\n\t\tsqrDistBetweenParticles(i, posMirrorXi, posMirrorYi, posMirrorZi, v0imi, v1imi, v2imi, dstimi2);\n\t\t\n\t\tif(dstimi2 < reL2) {\n\t\t\tdouble dst = sqrt(dstimi2);\n\t\t\tdouble wL = weight(dst, reL, weightType);\n\t\t\tdouble neu_ij;\n\t\t\tif(meu_i > 1.0e-8)\n\t\t\t\tneu_ij = 2.0 * meu_i * meu_i / (meu_i + meu_i);\n\t\t\telse\n\t\t\t\tneu_ij = 0.0;\n\n//neu_ij = KNM_VS2 * DNS_FL2;\n\n\t\t\tif(PTYPE[i] == 1) neu_ij = neu_ij/DNS_FL1;\n\t\t\telse neu_ij = neu_ij/DNS_FL2;\n\n\t\t\t// Original\n//\t\t\taccX +=(velXi-velMirrorXi)*w;\n//\t\t\taccY +=(velYi-velMirrorYi)*w;\n//\t\t\taccZ +=(velZi-velMirrorZi)*w;\n\n\t\t\t// Modified\n\t\t\taccX +=(velXi-velMirrorXi)*wL*neu_ij;\n\t\t\taccY +=(velYi-velMirrorYi)*wL*neu_ij;\n\t\t\taccZ +=(velZi-velMirrorZi)*wL*neu_ij;\n\t\t}\n\n\t\t// Wall laplacian Mitsume`s model\n\t\t// Correction of velocity\n\t\t// Original\n//      acc[i*3  ] += (Rref_i[0]*accX + Rref_i[1]*accY + Rref_i[2]*accZ)*coeffViscosity;\n//\t\tacc[i*3+1] += (Rref_i[3]*accX + Rref_i[4]*accY + Rref_i[5]*accZ)*coeffViscosity;\n//\t\tacc[i*3+2] += (Rref_i[6]*accX + Rref_i[7]*accY + Rref_i[8]*accZ)*coeffViscosity;\n\n\t\t// coeffViscMultiphase = 2.0*dim/(pndLargeZero*lambdaZero);\n\t\t// Modified\n\t\tacc[i*3  ] += (Rref_i[0]*accX + Rref_i[1]*accY + Rref_i[2]*accZ)*coeffViscMultiphase;\n\t\tacc[i*3+1] += (Rref_i[3]*accX + Rref_i[4]*accY + Rref_i[5]*accZ)*coeffViscMultiphase;\n\t\tacc[i*3+2] += (Rref_i[6]*accX + Rref_i[7]*accY + Rref_i[8]*accZ)*coeffViscMultiphase;\n\n\t\t\n\t\t// FSI\n\t\t// Force on wall\n\t\tforceWall[i*3  ] += - (Rref_i[0]*accX + Rref_i[1]*accY + Rref_i[2]*accZ)*coeffViscMultiphase*VolumeForce*RHO[i];\n\t\tforceWall[i*3+1] += - (Rref_i[3]*accX + Rref_i[4]*accY + Rref_i[5]*accZ)*coeffViscMultiphase*VolumeForce*RHO[i];\n\t\tforceWall[i*3+2] += - (Rref_i[6]*accX + Rref_i[7]*accY + Rref_i[8]*accZ)*coeffViscMultiphase*VolumeForce*RHO[i];\n\t}}\n}\n\n// No-Slip condition. Add acceleration due laplacian of viscosity on wall (Polygon wall)\nvoid MpsParticle::calcWallNoSlipViscosity() {\n\t//int nPartNearMesh = partNearMesh.size();\n\tdouble VolumeForce = pow(partDist,dim);\n\t//printf(\" Mesh %d \\n\", partNearMesh);\n\t// Loop only for particles near mesh\n#pragma omp parallel for schedule(dynamic,64)\n\t//for(int im=0;im<nPartNearMesh;im++) {\n\t//int i = partNearMesh[im];\n\tfor(int i=0; i<numParticles; i++) {\n\t//if(particleType[i] == fluid) {\n\tif(particleType[i] == fluid && particleNearWall[i] == true) {\n\n\t\tdouble meu_i = MEU[i];\n\t\tdouble accX = 0.0;\t\t\tdouble accY = 0.0;\t\t\tdouble accZ = 0.0;\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble velXi = vel[i*3  ];\tdouble velYi = vel[i*3+1];\tdouble velZi = vel[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n//\t\tdouble velXi = Velk[i*3  ];\tdouble velYi = Velk[i*3+1];\tdouble velZi = Velk[i*3+2];\n\n\t\t// Inverse matrix Rinv_i = - I\n\t\tdouble Rinv_i[9], normaliw[3], normalMod2;\n\t\t// normal fluid-wall particle = 0.5*(normal fluid-mirror particle)\n\t\tnormaliw[0] = 0.5*(posXi - posMirrorXi); normaliw[1] = 0.5*(posYi - posMirrorYi); normaliw[2] = 0.5*(posZi - posMirrorZi);\n\t\tnormalMod2 = normaliw[0]*normaliw[0] + normaliw[1]*normaliw[1] + normaliw[2]*normaliw[2];\n\n\t\tif(normalMod2 > 1.0e-8) {\n\t\t\tdouble normalMod = sqrt(normalMod2);\n\t\t\tnormaliw[0] = normaliw[0]/normalMod;\n\t\t\tnormaliw[1] = normaliw[1]/normalMod;\n\t\t\tnormaliw[2] = normaliw[2]/normalMod;\n\t\t}\n\t\telse {\n\t\t\tnormaliw[0] = 0;\n\t\t\tnormaliw[1] = 0;\n\t\t\tnormaliw[2] = 0;\n\t\t}\n\n\t\t//  Inverse transformation matrix Rinv_i = - I\n\t\tRinv_i[0] = -1.0; Rinv_i[1] =  0.0; Rinv_i[2] =  0.0;\n\t\tRinv_i[3] =  0.0; Rinv_i[4] = -1.0; Rinv_i[5] =  0.0;\n\t\tRinv_i[6] =  0.0; Rinv_i[7] =  0.0; Rinv_i[8] = -1.0;\n\n\t\tdouble viwall[3], vtil[3];\n\t\t// Wall velocity (0 if fixed)\n\t\tviwall[0]=viwall[1]=viwall[2]=0.0;\n\n\t\tif(nearMeshType[i] == meshType::FORCED) {\n\t\t\tviwall[0] = velVWall[0];\n\t\t\tviwall[1] = velVWall[1];\n\t\t\tviwall[2] = velVWall[2];\n\t\t}\n\n\t\t// normal_iwall*v_iwall\n\t\tdouble dotnv = normaliw[0]*viwall[0] + normaliw[1]*viwall[1] + normaliw[2]*viwall[2];\n\t\t// vtil = vi - 2 {v_iwall - (normal_iwall*v_iwall)normal_iwall}\n\t\tvtil[0] = velXi - 2.0*(viwall[0] - dotnv*normaliw[0]);\n\t\tvtil[1] = velYi - 2.0*(viwall[1] - dotnv*normaliw[1]);\n\t\tvtil[2] = velZi - 2.0*(viwall[2] - dotnv*normaliw[2]);\n\t\t// Mirror particle velocity vi' = Rinv_i * [vi - 2 {v_iwall - (normal_iwall*v_iwall)normal_iwall}] \n\t\tdouble velMirrorXi = (Rinv_i[0]*vtil[0] + Rinv_i[1]*vtil[1] + Rinv_i[2]*vtil[2]);\n\t\tdouble velMirrorYi = (Rinv_i[3]*vtil[0] + Rinv_i[4]*vtil[1] + Rinv_i[5]*vtil[2]);\n\t\tdouble velMirrorZi = (Rinv_i[6]*vtil[0] + Rinv_i[7]*vtil[1] + Rinv_i[8]*vtil[2]);\n\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and im (intersection) and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reL2 && dstimj2 < reL2 && dstij2 < dstimj2) {\n\t\t\t\tif(j != i) {\n\t\t\t\t\tdouble dst = sqrt(dstimj2);\n\t\t\t\t\tdouble wL = weight(dst, reL, weightType);\n\t\t\t\t\tdouble neu_ij;\n\t\t\t\t\tif((meu_i + MEU[j]) > 1.0e-8)\n\t\t\t\t\t\tneu_ij = 2.0 * meu_i * MEU[j] / (meu_i + MEU[j]);\n\t\t\t\t\telse\n\t\t\t\t\t\tneu_ij = 0.0;\n\n//neu_ij = KNM_VS2 * DNS_FL2;\n\n\n\t\t\t\t\tif(PTYPE[i] == 1) neu_ij = neu_ij/DNS_FL1;\n\t\t\t\t\telse neu_ij = neu_ij/DNS_FL2;\n\t\t\t\t\t\n\t\t\t\t\t//if((NEUt[i] + NEUt[j])>0) neu_ij = neu_ij + (2.0 * NEUt[i] * RHO[j] * NEUt[j] * RHO[j] / (NEUt[i] * RHO[i] + NEUt[j] * RHO[j])) / RHO[i];\n\n\t\t\t\t\t// Original\n//\t\t\t\t\taccX +=(vel[j*3  ]-velMirrorXi)*w;\n//\t\t\t\t\taccY +=(vel[j*3+1]-velMirrorYi)*w;\n//\t\t\t\t\taccZ +=(vel[j*3+2]-velMirrorZi)*w;\n\t\t\t\t\t// Modified\n\t\t\t\t\taccX +=(vel[j*3  ]-velMirrorXi)*wL*neu_ij;\n\t\t\t\t\taccY +=(vel[j*3+1]-velMirrorYi)*wL*neu_ij;\n\t\t\t\t\taccZ +=(vel[j*3+2]-velMirrorZi)*wL*neu_ij;\n\t\t\t\t\t\n\t\t\t\t\t//accX +=(Velk[j*3  ]-velMirrorXi)*w;\n\t\t\t\t\t//accY +=(Velk[j*3+1]-velMirrorYi)*w;\n\t\t\t\t\t//accZ +=(Velk[j*3+2]-velMirrorZi)*w;\n\n\t\t\t\t\t//if(i==2817) {\n\t\t\t\t\t//\tFwall[i*3  ] += 1;//AA[0];\n\t\t\t\t\t//\tFwall[i*3+1] += 1;//AA[1];\n\t\t\t\t\t//\tFwall[i*3+2] += 1;//AA[2];\n\t\t\t\t\t//\tstd::cout << j << \" \" << Velk[j*3] << \" \" << Velk[j*3+1] << \" \" << Velk[j*3+2] << \" Pj \" << press[j] << std::endl;\n\t\t\t\t\t//}\n\t\t\t\t\t//accX += (Rinv_i[0]*(Velk[j*3  ]-velMirrorXi)+ Rinv_i[1]*(Velk[j*3+1]-velMirrorYi) + Rinv_i[2]*(Velk[j*3+2]-velMirrorZi))*w;\n\t\t\t\t\t//accY += (Rinv_i[3]*(Velk[j*3  ]-velMirrorXi)+ Rinv_i[4]*(Velk[j*3+1]-velMirrorYi) + Rinv_i[5]*(Velk[j*3+2]-velMirrorZi))*w;\n\t\t\t\t\t//accZ += (Rinv_i[6]*(Velk[j*3  ]-velMirrorXi)+ Rinv_i[7]*(Velk[j*3+1]-velMirrorYi) + Rinv_i[8]*(Velk[j*3+2]-velMirrorZi))*w;\n\t\t\t\t}}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\n\t\t// Add \"i\" contribution (\"i\" is a neighbor of \"mirror i\")\n\t\tdouble v0imi, v1imi, v2imi, dstimi2;\n\t\tsqrDistBetweenParticles(i, posMirrorXi, posMirrorYi, posMirrorZi, v0imi, v1imi, v2imi, dstimi2);\n\t\t\n\t\tif(dstimi2 < reL2) {\n\t\t\tdouble dst = sqrt(dstimi2);\n\t\t\tdouble wL = weight(dst, reL, weightType);\n\t\t\tdouble neu_ij;\n\t\t\tif(meu_i > 1.0e-8)\n\t\t\t\tneu_ij = 2.0 * meu_i * meu_i / (meu_i + meu_i);\n\t\t\telse\n\t\t\t\tneu_ij = 0.0;\n\n//neu_ij = KNM_VS2 * DNS_FL2;\n\n\t\t\tif(PTYPE[i] == 1) neu_ij = neu_ij/DNS_FL1;\n\t\t\telse neu_ij = neu_ij/DNS_FL2;\n\n\t\t\t// Original\n//\t\t\taccX +=(velXi-velMirrorXi)*w;\n//\t\t\taccY +=(velYi-velMirrorYi)*w;\n//\t\t\taccZ +=(velZi-velMirrorZi)*w;\n\n\t\t\t// Modified\n\t\t\taccX +=(velXi-velMirrorXi)*wL*neu_ij;\n\t\t\taccY +=(velYi-velMirrorYi)*wL*neu_ij;\n\t\t\taccZ +=(velZi-velMirrorZi)*wL*neu_ij;\n\n\t\t\t//accX += (Rinv_i[0]*(velXi-velMirrorXi)+ Rinv_i[1]*(velYi-velMirrorYi) + Rinv_i[2]*(velZi-velMirrorZi))*w;\n\t\t\t//accY += (Rinv_i[3]*(velXi-velMirrorXi)+ Rinv_i[4]*(velYi-velMirrorYi) + Rinv_i[5]*(velZi-velMirrorZi))*w;\n\t\t\t//accZ += (Rinv_i[6]*(velXi-velMirrorXi)+ Rinv_i[7]*(velYi-velMirrorYi) + Rinv_i[8]*(velZi-velMirrorZi))*w;\n\t\t}\n\n\t\t//if(i==6) {\n\t\t//\tprintf(\"Vx:%lf Vy:%lf Vz:%lf Vx:%lf Vy:%lf Vz:%lf\\n\",velXi,velMirrorXi,velYi,velMirrorYi,velZi,velMirrorZi);\n\t\t//\tprintf(\"Accx:%lf Bccy:%lf Bccz:%lf \\n\", acc[i*3],acc[i*3+1],acc[i*3+2]);\n\t\t\t//printf(\"Bccx:%lf Bccy:%lf Bccz:%lf \\n\", acc[i*3],acc[i*3+1],acc[i*3+2]);\n\t\t//}\n\t\t// Wall laplacian Mitsume`s model\n\t\t// Correction of velocity\n\t\t// coeffViscMultiphase = 2.0*dim/(pndLargeZero*lambdaZero);\n\t\t// Original\n//     \tacc[i*3  ] += (Rinv_i[0]*accX + Rinv_i[1]*accY + Rinv_i[2]*accZ)*coeffViscosity;\n//\t\tacc[i*3+1] += (Rinv_i[3]*accX + Rinv_i[4]*accY + Rinv_i[5]*accZ)*coeffViscosity;\n//\t\tacc[i*3+2] += (Rinv_i[6]*accX + Rinv_i[7]*accY + Rinv_i[8]*accZ)*coeffViscosity;\n\t\t// Modified\n\t\tacc[i*3  ] += (Rinv_i[0]*accX + Rinv_i[1]*accY + Rinv_i[2]*accZ)*coeffViscMultiphase;\n\t\tacc[i*3+1] += (Rinv_i[3]*accX + Rinv_i[4]*accY + Rinv_i[5]*accZ)*coeffViscMultiphase;\n\t\tacc[i*3+2] += (Rinv_i[6]*accX + Rinv_i[7]*accY + Rinv_i[8]*accZ)*coeffViscMultiphase;\n\t\t//Acv[i*3  ] = (Rinv_i[0]*accX + Rinv_i[1]*accY + Rinv_i[2]*accZ)*coeffViscosity;\n\t\t//Acv[i*3+1] = (Rinv_i[3]*accX + Rinv_i[4]*accY + Rinv_i[5]*accZ)*coeffViscosity;\n\t\t//Acv[i*3+2] = (Rinv_i[6]*accX + Rinv_i[7]*accY + Rinv_i[8]*accZ)*coeffViscosity;\n\n\t\t//double AA[3];\n\t\t\n\t\t//AA[0] = (Rinv_i[0]*accX + Rinv_i[1]*accY + Rinv_i[2]*accZ)*coeffViscosity;\n\t\t//AA[1] = (Rinv_i[3]*accX + Rinv_i[4]*accY + Rinv_i[5]*accZ)*coeffViscosity;\n\t\t//AA[2] = (Rinv_i[6]*accX + Rinv_i[7]*accY + Rinv_i[8]*accZ)*coeffViscosity;\n\n\t\t//wallParticleForce1[i*3  ] = AA[0];\n\t\t//wallParticleForce1[i*3+1] = AA[1];\n\t\t//wallParticleForce1[i*3+2] = AA[2];\n\n\t\t//if(i==2817) {\n\t\t\t//Fwall[i*3  ] = AA[0];\n\t\t\t//Fwall[i*3+1] = AA[1];\n\t\t\t//Fwall[i*3+2] = AA[2];\n\t\t\t//std::cout << \"t: \" << timeCurrent << std::endl;\n\t\t\t//std::cout << \"Fwall \" << AA[0] << \" \" << AA[1] << \" \" << AA[2] << std::endl;\n\t\t\t//std::cout << \"Veli \" << velXi << \" \" << velYi << \" \" << velZi << std::endl;\n\t\t\t//std::cout << \"Posmi \" << posMirrorXi << \" \" << posMirrorYi << \" \" << posMirrorZi << std::endl;\n\t\t\t//std::cout << \"pndi \" << pndi[i] << \" Pi \" << press[i] << std::endl;\n\t\t\t//printf(\"Accx:%lf Accy:%lf Accz:%lf \\n\", AA[0],AA[1],AA[2]);\n\t\t//}\n\t\t//if(i==6) {\n\t\t\t//printf(\"Accx:%lf Accy:%lf Accz:%lf \\n\", acc[i*3],acc[i*3+1],acc[i*3+2]);\n\t\t//\tprintf(\"Time:%e\\n\", timeCurrent);\n\t\t//\tprintf(\"Xi:%e %e %e Xm:%e %e %e\\n\", posXi,posYi,posZi,posMirrorXi,posMirrorYi,posMirrorZi);\n\t\t//\tprintf(\"Vi:%e %e %e Vm:%e %e %e\\n\", velXi,velYi,velZi,velMirrorXi,velMirrorYi,velMirrorZi);\n\t\t//\tprintf(\"acc:%e %e %e\\n\", AA[0],AA[1],AA[2]);\n\t\t//}\n\n\n\t\t// FSI\n\t\t// Force on wall\n\t\tforceWall[i*3  ] += - (Rinv_i[0]*accX + Rinv_i[1]*accY + Rinv_i[2]*accZ)*coeffViscMultiphase*VolumeForce*RHO[i];\n\t\tforceWall[i*3+1] += - (Rinv_i[3]*accX + Rinv_i[4]*accY + Rinv_i[5]*accZ)*coeffViscMultiphase*VolumeForce*RHO[i];\n\t\tforceWall[i*3+2] += - (Rinv_i[6]*accX + Rinv_i[7]*accY + Rinv_i[8]*accZ)*coeffViscMultiphase*VolumeForce*RHO[i];\n\t}}\n}\n\n// 3D triangle to xy plane\n// https://math.stackexchange.com/questions/856666/how-can-i-transform-a-3d-triangle-to-xy-plane\nvoid MpsParticle::transformMatrix(double *V1, double *V2, double *V3, double *RM) {\n\tdouble A[3],B[3],C[3],U[3],V[3],W[3];\n\t// Translate the vertex \"V1\" to origin 0,0,0\n\tfor(unsigned int i = 0; i < 3; i++) {\n\t\t//A[i] = V1[i] - V1[i];\n\t\tB[i] = V2[i] - V1[i];\n\t\tC[i] = V3[i] - V1[i];\n\t}\n\t// Define the vector U pointing from A to B, and normalise it.\n\tdouble normB = sqrt(B[0]*B[0]+B[1]*B[1]+B[2]*B[2]);\n\tif(normB > 1.0e-8) {\n\t\tfor(unsigned int i = 0; i < 3; i++)\n\t\t\tU[i] = B[i]/normB;\n\t}\n\telse {\n\t\tfor(unsigned int i = 0; i < 3; i++)\n\t\t\tU[i] = 0.0;\n\t}\n\t// Take the cross product which is at right angles to the triangle.\n\tW[0] = U[1] * C[2] - U[2] * C[1];\n\tW[1] = U[2] * C[0] - U[0] * C[2];\n\tW[2] = U[0] * C[1] - U[1] * C[0];\n\t// Normalise it to give the unit vector\n\tdouble normW = sqrt(W[0]*W[0]+W[1]*W[1]+W[2]*W[2]);\n\tif(normW > 1.0e-8) {\n\t\tfor(unsigned int i = 0; i < 3; i++)\n\t\t\tW[i] = W[i]/normW;\n\t}\n\telse {\n\t\tfor(unsigned int i = 0; i < 3; i++)\n\t\t\tW[i] = 0.0;\n\t}\n\t// Find the cross-product automatically a unit vector.\n\tV[0] = U[1] * W[2] - U[2] * W[1];\n\tV[1] = U[2] * W[0] - U[0] * W[2];\n\tV[2] = U[0] * W[1] - U[1] * W[0];\n\t// In coordinates corresponding to the basis {U, V, W }, the triangle lies. The rotation matrix that carries the usual\n\t// (1,0,0) to U, the usual (0,1,0) to V, and the usual (,0,0,1) to W has U, V and W as its columns.\n\t// You want the other direction, so take the inverse - which for a rotation matrix is just the transpose.\n\tfor(unsigned int i = 0; i < 3; i++) {\n\t\tRM[i  ] = U[i];\n\t\tRM[i+3] = V[i];\n\t\tRM[i+6] = W[i];\n\t}\n\n\t/*\n\t// Projection of P represented in triangle coordinate system 3D (X,Y,Z) -> 2D (U,V,W).\n\tproj_pn = RM*proj_p';\n\t// Square approximation support in triangle coordinate system 3D (X,Y,Z) -> 2D (U,V,W). Here, we assume the\n\t// value in W as 0.\n\tls = sqrt(re^2-p_pb^2);\n\tsquareSupport = [[-ls+proj_pn(1);ls+proj_pn(1);ls+proj_pn(1);-ls+proj_pn(1)],...\n\t[-ls+proj_pn(2);-ls+proj_pn(2);ls+proj_pn(2);ls+proj_pn(2)]];\n\t// Triangle represented in triangle coordinate system 3D\n\t// (X,Y,Z) -> 2D (U,V,W). Here we assume the value in W as 0\n\ttriangle2D = [[an(1);bn(1);cn(1)],[an(2);bn(2);cn(2)]];\n\t// Sutherland Hodgman clipping - 2D (U,V,W). Here, the value in W is assumed 0 for all points.\n\tclippedPolygon2D = sutherlandHodgman(triangle2D,squareSupport);\n\t*/\n}\n\n// 3D -> 2D\nvoid MpsParticle::transform3Dto2D(double *P1, double *RM) {\n\tdouble A[3];\n\t// Point represented in triangle coordinate system (U,V,W). The value in W is the same for all points (3D -> 2D).\n\t// Trasnpose of RM\n\tfor(unsigned int i = 0; i < 3; i++) {\n\t\tA[i] = RM[3*i]*P1[0]+RM[3*i+1]*P1[1]+RM[3*i+2]*P1[2];\n\t}\n\tfor(unsigned int i = 0; i < 3; i++) {\n\t\tP1[i] = A[i];\n\t}\n}\n\n// 2D -> 3D\nvoid MpsParticle::transform2Dto3D(double *P1, double *RM) {\n\tdouble A[3];\n\t// Point represented in coordinate system (X,Y,Z) (2D -> 3D).\n\tfor(unsigned int i = 0; i < 3; i++) {\n\t\tA[i] = RM[i]*P1[0]+RM[i+3]*P1[1]+RM[i+6]*P1[2];\n\t}\n\tfor(unsigned int i = 0; i < 3; i++) {\n\t\tP1[i] = A[i];\n\t}\n}\n\n// // Force on wall due fluid particles - FSI\n// void MpsParticle::forceParticlesToWall(mesh mesh, solid_fem * &solid) {\n// \t//int nPartNearMesh = partNearMesh.size();\n\n// \tdouble resForce_x, resForce_y, resForce_z, pForce_x, pForce_y, pForce_z;\n// \tdouble AreaForce = pow(partDist,dim-1.0);\n// \tresForce_x=0.0;\tresForce_y=0.0;\tresForce_z=0.0;\n// \tpForce_x=0.0;\tpForce_y=0.0;\tpForce_z=0.0;\n\n// \t//printf(\" Mesh %d \\n\", nPartNearMesh);\n// \t// Loop only for particles near mesh\n// #pragma omp parallel for reduction(+: resForce_x, resForce_y, resForce_z, pForce_x, pForce_y, pForce_z)\n// \t//for(int im=0;im<nPartNearMesh;im++) {\n// \t//int i = partNearMesh[im];\n// \tfor(int i=0; i<numParticles; i++) {\n\n// \t//if(particleType[i] == fluid && nearMeshType[i] == meshType::DEFORMABLE) {\n// \tif(particleType[i] == fluid && particleNearWall[i] == true && nearMeshType[i] == meshType::DEFORMABLE) {\n// \t\t//printf(\"\\n%5d th timeCurrent: %lf / ENTROU !!! i: %d\", numOfIterations, timeCurrent, i);\n\t\t\n// \t\tresForce_x += forceWall[i*3]; resForce_y += forceWall[i*3+1]; resForce_z += forceWall[i*3+2];\n\n// \t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n// \t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\n// \t\tdouble  normaliw[3], normalMod2;\n// \t\t// normal fluid-wall particle = 0.5*(normal fluid-mirror particle)\n// \t\tnormaliw[0] = 0.5*(posXi - posMirrorXi); normaliw[1] = 0.5*(posYi - posMirrorYi); normaliw[2] = 0.5*(posZi - posMirrorZi);\n// \t\tnormalMod2 = normaliw[0]*normaliw[0] + normaliw[1]*normaliw[1] + normaliw[2]*normaliw[2];\n\n// \t\t//if(i==16173)\n// \t\t//   \tprintf(\"\\ni:%5d th timeCurrent: %lf / ri: %lf %lf %lf / rim: %lf %lf %lf / N: %lf\", i, timeCurrent, posXi, posYi, posZi, posMirrorXi, posMirrorYi, posMirrorZi, normalMod2);\n\n// \t\tif(normalMod2 <= 0.26*partDist*partDist) {\n// \t\t\tif(normalMod2 > 1.0e-8) {\n// \t\t\t\tdouble normalMod = sqrt(normalMod2);\n// \t\t\t\tnormaliw[0] = normaliw[0]/normalMod;\n// \t\t\t\tnormaliw[1] = normaliw[1]/normalMod;\n// \t\t\t\tnormaliw[2] = normaliw[2]/normalMod;\n// \t\t}\n// \t\telse {\n// \t\t\tnormaliw[0] = 0;\n// \t\t\tnormaliw[1] = 0;\n// \t\t\tnormaliw[2] = 0;\n// \t\t}\n\n// \t\t\tpForce_x += press[i]*normaliw[0]*AreaForce; pForce_y += press[i]*normaliw[1]*AreaForce; pForce_z += press[i]*normaliw[2]*AreaForce;\n// \t\t}\n\n\n\n// \t\tdouble FWG[3], FWL[3];\t// Global and local force\n// \t\tdouble V1[3],V2[3],V3[3],PW[3],RM[9];\n\n// \t\t// Mesh element ID\n// \t\tint elemID = elementID[i];\n\n// \t\t// Triangle vertices\n// \t\tint node1 = elemNode1id[elemID];\n// \t\tint node2 = elemNode2id[elemID];\n// \t\tint node3 = elemNode3id[elemID];\n\n// \t\tint ss = 1;\n// //\t\tint node1 = solid[ss].element[elemID].node1ID;\n// //\t\tint node2 = solid[ss].element[elemID].node2ID;\n// //\t\tint node3 = solid[ss].element[elemID].node3ID;\n// /*\n// \t\tif(i==65)\n// \t\t{\n// \t\t\tstd::cout << \"NN: \" << node1 << \" X: \" << nodeX[node1] << \" Y: \" << nodeY[node1] << \" Z: \" << nodeZ[node1] << std::endl;\n// \t\t\tstd::cout << \"NN: \" << node2 << \" X: \" << nodeX[node2] << \" Y: \" << nodeY[node2] << \" Z: \" << nodeZ[node2] << std::endl;\n// \t\t\tstd::cout << \"NN: \" << node3 << \" X: \" << nodeX[node3] << \" Y: \" << nodeY[node3] << \" Z: \" << nodeZ[node3] << std::endl;\n// \t\t}\n// \t*/\n// \t\tV1[0] = nodeX[node1]; V1[1] = nodeY[node1]; V1[2] = nodeZ[node1];\n// \t\tV2[0] = nodeX[node2]; V2[1] = nodeY[node2]; V2[2] = nodeZ[node2];\n// \t\tV3[0] = nodeX[node3]; V3[1] = nodeY[node3]; V3[2] = nodeZ[node3];\n\n// //\t\tV1[0] = solid[ss].node[node1].x; V1[1] = solid[ss].node[node1].y; V1[2] = solid[ss].node[node1].z;\n// //\t\tV2[0] = solid[ss].node[node2].x; V2[1] = solid[ss].node[node2].y; V2[2] = solid[ss].node[node2].z;\n// //\t\tV3[0] = solid[ss].node[node3].x; V3[1] = solid[ss].node[node3].y; V3[2] = solid[ss].node[node3].z;\n// /*\n// \t\tif(i==65)\n// \t\t{\n// \t\t\tstd::cout << \"Elem: \" << elemID << \" N1: \" << node1 << \" N2: \" << node2 << \" N3: \" << node3 << std::endl;\n// \t\t\tstd::cout << \"N1 X: \" << V1[0] << \" Y: \" << V1[1] << \" Z: \" << V1[2] << std::endl;\n// \t\t\tstd::cout << \"N2 X: \" << V2[0] << \" Y: \" << V2[1] << \" Z: \" << V2[2] << std::endl;\n// \t\t\tstd::cout << \"N3 X: \" << V3[0] << \" Y: \" << V3[1] << \" Z: \" << V3[2] << std::endl;\n\t\t\t\n// \t\t}\n// */\n// \t\t// Transformation matrix\n// \t\ttransformMatrix(V1, V2, V3, RM);\n\n// \t\tif(i==65)\n// \t\t{\n// \t\t\tstd::cout << \"RM: \" << RM[0] << \" Y: \" << RM[1] << \" Z: \" << RM[2] << std::endl;\n// \t\t\tstd::cout << \"RM: \" << RM[3] << \" Y: \" << RM[4] << \" Z: \" << RM[5] << std::endl;\n// \t\t\tstd::cout << \"RM: \" << RM[6] << \" Y: \" << RM[7] << \" Z: \" << RM[8] << std::endl;\n\t\t\t\n// \t\t}\n\n// \t\t// Wall point\n// \t\tPW[0] = particleAtWallPos[i*3  ];\tPW[1] = particleAtWallPos[i*3+1];\tPW[2] = particleAtWallPos[i*3+2];\n// /*\n// \t\tif(i==65)\n// \t\t{\n// \t\t\tstd::cout << \"PW: \" << PW[0] << \" Y: \" << PW[1] << \" Z: \" << PW[2] << std::endl;\n// \t\t}\n// */\n// \t\tFWL[0] = forceWall[i*3]; FWL[1] = forceWall[i*3+1]; FWL[2] = forceWall[i*3+2];\n\n// \t\t// Arbitrary plane to XY plane\n// \t\ttransform3Dto2D(V1, RM);\n// \t\ttransform3Dto2D(V2, RM);\n// \t\ttransform3Dto2D(V3, RM);\n// \t\ttransform3Dto2D(PW, RM);\n// \t\ttransform3Dto2D(FWL, RM);\n// /*\n// \t\tif(i==65)\n// \t\t{\n// \t\t\tstd::cout << \"PW: \" << PW[0] << \" Y: \" << PW[1] << \" Z: \" << PW[2] << std::endl;\n// \t\t\tstd::cout << \"FWL: \" << FWL[0] << \" Y: \" << FWL[1] << \" Z: \" << FWL[2] << std::endl;\n// \t\t}\n// */\n// \t\t// Element area 0.5*[(x2*y3 - x3*y2) + (y2 - y3)*x1 + (x3 - x2)*y1]\n// \t\tdouble Ae = fabs(0.5*((V2[0]*V3[1] - V3[0]*V2[1]) + (V2[1] - V3[1])*V1[0] + (V3[0] - V2[0])*V1[1]));\n\n// \t\t// Shape functions\n// \t\t// N1 = Ar1/Ae, N2 = Ar2/Ae, N3 = Ar3/Ae\n// \t\t// Ar1 = 0.5*[(x2*y3 - x3*y2) + (y2 - y3)*x + (x3 - x2)*y]\n// \t\t// Ar2 = 0.5*[(x3*y1 - x1*y3) + (y3 - y1)*x + (x1 - x3)*y]\n// \t\t// Ar3 = 0.5*[(x1*y2 - x2*y1) + (y1 - y2)*x + (x2 - x1)*y] = 1 - Ar2 - Ar1\n// \t\tdouble Ar1 = fabs(0.5*((V2[0]*V3[1] - V3[0]*V2[1]) + (V2[1] - V3[1])*PW[0] + (V3[0] - V2[0])*PW[1]));\n// \t\tdouble Ar2 = fabs(0.5*((V3[0]*V1[1] - V1[0]*V3[1]) + (V3[1] - V1[1])*PW[0] + (V1[0] - V3[0])*PW[1]));\n// \t\tdouble Ar3 = Ae - Ar1 - Ar2;\n\n// /*\n// \t\tif(i==65)\n// \t\t{\n// \t\t\tstd::cout << \"Elem: \" << elemID << \" N1: \" << node1 << \" N2: \" << node2 << \" N3: \" << node3 << std::endl;\n// \t\t\tstd::cout << \"N1 X: \" << V1[0] << \" Y: \" << V1[1] << \" Z: \" << V1[2] << std::endl;\n// \t\t\tstd::cout << \"N2 X: \" << V2[0] << \" Y: \" << V2[1] << \" Z: \" << V2[2] << std::endl;\n// \t\t\tstd::cout << \"N3 X: \" << V3[0] << \" Y: \" << V3[1] << \" Z: \" << V3[2] << std::endl;\n// \t\t\tstd::cout << \"Ae: \" << Ae << \" Ar1: \" << Ar1 << \" Ar2: \" << Ar2 << \" Ar3: \" << Ar3 << std::endl;\n// \t\t\tstd::cout << \"t: \" << timeCurrent << \" fiX: \" << forceWall[i*3] << \" fiY: \" << forceWall[i*3+1] << \" fiZ: \" << forceWall[i*3+2] << std::endl;\n// \t\t}\n// */\n\t\t\n// \t\t// Nodal forces\n// \t\t// Node 1\n// \t\tFWG[0] = (Ar1/Ae)*FWL[0]; FWG[1] = (Ar1/Ae)*FWL[1]; FWG[2] = (Ar1/Ae)*FWL[2];\n// \t\t// XY plane to Arbitrary plane\n// \t\ttransform2Dto3D(FWG, RM);\n// \t\tnodeFx[node1] += FWG[0]; nodeFy[node1] += FWG[1]; nodeFz[node1] += FWG[2];\n// //\t\tsolid[ss].node[node1].forceX += FWG[0]; solid[ss].node[node1].forceY += FWG[1]; solid[ss].node[node1].forceZ += FWG[2];\n// /*\t\t\n// \t\tif(i==65)\n// \t\t{\n// \t\t\tstd::cout << \"t1: \" << timeCurrent << \" fWX: \" << FWG[0] << \" fWY: \" << FWG[1] << \" fWZ: \" << FWG[2] << std::endl;\n// \t\t}\n// */\n// \t\t// Node 2\n// \t\tFWG[0] = (Ar2/Ae)*FWL[0]; FWG[1] = (Ar2/Ae)*FWL[1]; FWG[2] = (Ar2/Ae)*FWL[2];\n// \t\t// XY plane to Arbitrary plane\n// \t\ttransform2Dto3D(FWG, RM);\n// \t\tnodeFx[node2] += FWG[0]; nodeFy[node2] += FWG[1]; nodeFz[node2] += FWG[2];\n// //\t\tsolid[ss].node[node2].forceX += FWG[0]; solid[ss].node[node2].forceY += FWG[1]; solid[ss].node[node2].forceZ += FWG[2];\n// /*\n// \t\tif(i==65)\n// \t\t{\n// \t\t\tstd::cout << \"t2: \" << timeCurrent << \" fWX: \" << FWG[0] << \" fWY: \" << FWG[1] << \" fWZ: \" << FWG[2] << std::endl;\n// \t\t}\n// */\n// \t\t// Node 3\n// \t\tFWG[0] = (Ar3/Ae)*FWL[0]; FWG[1] = (Ar3/Ae)*FWL[1]; FWG[2] = (Ar3/Ae)*FWL[2];\n// \t\t// XY plane to Arbitrary plane\n// \t\ttransform2Dto3D(FWG, RM);\n// \t\tnodeFx[node3] += FWG[0]; nodeFy[node3] += FWG[1]; nodeFz[node3] += FWG[2];\n// //\t\tsolid[ss].node[node3].forceX += FWG[0]; solid[ss].node[node3].forceY += FWG[1]; solid[ss].node[node3].forceZ += FWG[2];\n// /*\n// \t\tif(i==65)\n// \t\t{\n// \t\t\tstd::cout << \"t3: \" << timeCurrent << \" fWX: \" << FWG[0] << \" fWY: \" << FWG[1] << \" fWZ: \" << FWG[2] << std::endl;\n// \t\t}\n// \t\t*/\n// \t}}\n\n\n// \tif(numOfIterations%1 == 0) {\n// \t\tprintf(\"\\n%5d th timeCurrent: %lf / Fx: %lf / Fy: %lf / Fz: %lf\", numOfIterations, timeCurrent, resForce_x, resForce_y, resForce_z);\n// \t\tprintf(\"\\n%5d th timeCurrent: %lf / pFx: %lf / pFy: %lf / pFz: %lf\", numOfIterations, timeCurrent, pForce_x, pForce_y, pForce_z);\n// \t}\n\t\n// \t// Open the File to write\n// \tforceTxtFile = fopen(OUT_FORCE, \"a\");\n// \tif(forceTxtFile == NULL) perror (\"Error opening force txt file\");\n// \tfprintf(forceTxtFile,\"\\n%lf\\t%lf\\t%lf\\t%lf\",timeCurrent, resForce_x,resForce_y,resForce_z);\n// \t// Close force file\n// \tfclose(forceTxtFile);\n// }\n\n// Update velocity and positions\nvoid MpsParticle::updateVelocityPosition2nd() {\n\tvelMax = 0.0;\t\t\t\t\t\t// Maximum flow velocity\n\tdouble auxiliar[5] = {1.2, -3.3, 4.3, -0.3, 5.6};\n\n\t// https://stackoverflow.com/questions/39989473/use-openmp-in-c11-to-find-the-maximum-of-the-calculated-values\n#pragma omp parallel\n{\n\tdouble local_vMax = 0.0;\n#pragma omp for\n\tfor(int i=0; i<numParticles; i++) {\n\t\tif(particleType[i] == fluid) {\n\t\t\tvel[i*3  ]+=acc[i*3  ]*timeStep;\tvel[i*3+1]+=acc[i*3+1]*timeStep;\tvel[i*3+2]+=acc[i*3+2]*timeStep;\n\t\t\t//if(particleType[i] == fluid) {\n\t\t\tpos[i*3  ]+=acc[i*3  ]*timeStep*timeStep;\tpos[i*3+1]+=acc[i*3+1]*timeStep*timeStep;\tpos[i*3+2]+=acc[i*3+2]*timeStep*timeStep;\n\t\t\t//}\n\t\t\tacc[i*3]=acc[i*3+1]=acc[i*3+2]=0.0;\n\n\t\t\t//pos[i*3  ]=Posk[i*3 ]+vel[i*3  ]*timeStep;\tpos[i*3+1]=Posk[i*3+1]+vel[i*3+1]*timeStep;\tpos[i*3+2]=Posk[i*3+2]+vel[i*3+2]*timeStep;\n\t\t\t//Posk[i*3  ]=pos[i*3  ];\tPosk[i*3+1]=pos[i*3+1];\tPosk[i*3+2]=pos[i*3+2];\n\t\t\t//Velk[i*3  ]=vel[i*3  ];\tVelk[i*3+1]=vel[i*3+1];\tVelk[i*3+2]=vel[i*3+2];\n\n\t\t\t//wallParticleForce1[i*3  ]=acc[i*3  ];\twallParticleForce1[i*3+1]=acc[i*3+1];\twallParticleForce1[i*3+2]=acc[i*3+2];\n\t\t\t//wallParticleForce2[i*3  ]=Acv[i*3  ];\twallParticleForce2[i*3+1]=Acv[i*3+1];\twallParticleForce2[i*3+2]=Acv[i*3+2];\n\t\t\t//acc[i*3]=acc[i*3+1]=acc[i*3+2]=0.0;\n\t\t\t//Acv[i*3]=Acv[i*3+1]=Acv[i*3+2]=0.0;\n\n\t\t\tdouble vMod2 = vel[i*3  ]*vel[i*3  ] + vel[i*3+1]*vel[i*3+1] + vel[i*3+2]*vel[i*3+2];\n\t\t\tif(vMod2 > local_vMax*local_vMax)\n\t\t\t\tlocal_vMax = sqrt(vMod2);\n\t\t}\n\t}\n\n#pragma omp critical\n\t{\n\t\tif (local_vMax > velMax)\n\t\t\tvelMax = local_vMax;\n\t}\n}\n\tCFLcurrent = timeStep*velMax/partDist;\n}\n\n// Shifting technique\n// Improvements for accuracy and stability in a weakly-compressible particle method\n// https://www.sciencedirect.com/science/article/pii/S0045793016302250\nvoid MpsParticle::calcShifting() {\n#pragma omp parallel for schedule(dynamic,64)\n\tfor(int i=0; i<numParticles; i++) {\n\tif(particleType[i] == fluid) {\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble velXi = vel[i*3  ];\tdouble velYi = vel[i*3+1];\tdouble velZi = vel[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\tdouble duXi = 0.0;\tdouble duYi = 0.0;\tdouble duZi = 0.0;\n\t\t//double ni = 0.0;\n\t\t\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reS2 && (dstij2 < dstimj2 || wallType == boundaryWallType::PARTICLE)) {\n\t\t\t\tif(j != i) {\n\t\t\t\t\tdouble dst = sqrt(dstij2);\n\t\t\t\t\tdouble dw = delWeight(dst, reS, weightType);\n\t\t\t\t\tduXi += dw*(vel[j*3  ]-velXi);\n\t\t\t\t\tduYi += dw*(vel[j*3+1]-velYi);\n\t\t\t\t\tduZi += dw*(vel[j*3+2]-velZi);\n\t\t\t\t\t//double w = weight(dst, r, weightType);\n\t\t\t\t\t//ni += w;\n\t\t\t\t}}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\n//\t\tif(wallType == boundaryWallType::POLYGON) {\n//\t\t\tif(pndi[i] > pndThreshold*pndSmallZero)\n//\t\t}\n//\t\telse if(wallType == boundaryWallType::PARTICLE) \n//\t\t\tif(pndi[i] > pndThreshold*pndSmallZero || numNeigh[i] > neighThreshold*numNeighZero)\n//\t\t}\n//\t\tif(pndSmall[i] > pndThreshold*pndSmallZero || numNeigh[i] > neighThreshold*numNeighZero)\n\t\tif(particleBC[i] == inner) {\n\t\t\tvel[i*3  ] -= coeffShifting1*duXi;\n\t\t\tvel[i*3+1] -= coeffShifting1*duYi;\n\t\t\tvel[i*3+2] -= coeffShifting1*duZi;\n\t\t}\n\t\t// else {\n\t\t// \tdouble Inn[9], duAux[3];\n\t\t// \t// I - nxn\n\t\t// \tInn[0] = 1.0 - normal[i*3  ]*normal[i*3  ]; Inn[1] = 0.0 - normal[i*3  ]*normal[i*3+1]; Inn[2] = 0.0 - normal[i*3  ]*normal[i*3+2];\n\t\t// \tInn[3] = 0.0 - normal[i*3+1]*normal[i*3  ]; Inn[4] = 1.0 - normal[i*3+1]*normal[i*3+1]; Inn[5] = 0.0 - normal[i*3+1]*normal[i*3+2];\n\t\t// \tInn[6] = 0.0 - normal[i*3+2]*normal[i*3  ]; Inn[7] = 0.0 - normal[i*3+2]*normal[i*3+1]; Inn[8] = 1.0 - normal[i*3+2]*normal[i*3+2];\n\t\t// \t// (I - nxn)dr\n\t\t// \tduAux[0] = Inn[0]*duXi + Inn[1]*duYi + Inn[2]*duZi;\n\t\t// \tduAux[1] = Inn[3]*duXi + Inn[4]*duYi + Inn[5]*duZi;\n\t\t// \tduAux[2] = Inn[6]*duXi + Inn[7]*duYi + Inn[8]*duZi;\n\t\t// \tvel[i*3  ] -= coeffShifting1*duAux[0];\n\t\t// \tvel[i*3+1] -= coeffShifting1*duAux[1];\n\t\t// \tvel[i*3+2] -= coeffShifting1*duAux[2];\n\t\t// }\n\t}}\n}\n\n// normal vector on the fluid\n// An accurate and stable multiphase moving particle semi-implicit method based on a corrective matrix for all particle interaction models\n// https://onlinelibrary.wiley.com/doi/full/10.1002/nme.5844\nvoid MpsParticle::calcNormalParticles() {\n#pragma omp parallel for schedule(dynamic,64)\n\tfor(int i=0; i<numParticles; i++) {\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\tdouble dr_ix = 0.0;\tdouble dr_iy = 0.0;\tdouble dr_iz = 0.0;\n\t\t\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reS2 && (dstij2 < dstimj2 || wallType == boundaryWallType::PARTICLE)) {\n\t\t\t\tif(j != i) {\n\t\t\t\t\tdouble dst = sqrt(dstij2);\n\t\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\t\tdr_ix += v0ij*wS/dst;\n\t\t\t\t\tdr_iy += v1ij*wS/dst;\n\t\t\t\t\tdr_iz += v2ij*wS/dst;\n\t\t\t\t}}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\n\t\tnormal[i*3  ] = - dr_ix/pndSmallZero;\n\t\tnormal[i*3+1] = - dr_iy/pndSmallZero;\n\t\tnormal[i*3+2] = - dr_iz/pndSmallZero;\n\t\t\n\t\t/*\n\t\tif(wallType == boundaryWallType::PARTICLE)\n\t\t{\n\t\t\t// Normalize\n\t\t\tdouble norm2 = dr_ix*dr_ix + dr_iy*dr_iy + dr_iz*dr_iz;\n\t\t\tif(norm2 > 0.0) {\n\t\t\t\tdouble norm = sqrt(norm2);\n\t\t\t\tnormal[i*3  ] /= norm;\n\t\t\t\tnormal[i*3+1] /= norm;\n\t\t\t\tnormal[i*3+2] /= norm;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tnormal[i*3  ] = 0.0;\n\t\t\t\tnormal[i*3+1] = 0.0;\n\t\t\t\tnormal[i*3+2] = 0.0;\n\t\t\t}\n\t\t}\n\t\t*/\n\t}\n}\n\n// normal vector on the fluid (Polygon wall)\nvoid MpsParticle::calcWallNormalParticles() {\n\t//int nPartNearMesh = partNearMesh.size();\n\t//printf(\" Mesh %d \\n\", nPartNearMesh);\n\t// Loop only for particles near mesh\n#pragma omp parallel for schedule(dynamic,64)\n\t//for(int im=0;im<nPartNearMesh;im++) {\n\t//int i = partNearMesh[im];\n\tfor(int i=0; i<numParticles; i++) {\n\t//if(particleType[i] == fluid) {\n\tif(particleType[i] == fluid && particleNearWall[i] == true) {\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\tdouble dr_ix = 0.0;\tdouble dr_iy = 0.0;\tdouble dr_iz = 0.0;\n\t\t// Wall gradient Mitsume`s model\n\t\tdouble Rref_i[9], normaliw[3], normaliwSqrt;\n\t\t// normal fluid-wall particle = 0.5*(normal fluid-mirror particle)\n\t\tnormaliw[0] = 0.5*(posXi - posMirrorXi); normaliw[1] = 0.5*(posYi - posMirrorYi); normaliw[2] = 0.5*(posZi - posMirrorZi);\n\t\tnormaliwSqrt = sqrt(normaliw[0]*normaliw[0] + normaliw[1]*normaliw[1] + normaliw[2]*normaliw[2]);\n\n\t\tif(normaliwSqrt > 1.0e-8) {\n\t\t\tnormaliw[0] = normaliw[0]/normaliwSqrt;\n\t\t\tnormaliw[1] = normaliw[1]/normaliwSqrt;\n\t\t\tnormaliw[2] = normaliw[2]/normaliwSqrt;\n\t\t}\n\t\telse {\n\t\t\tnormaliw[0] = 0;\n\t\t\tnormaliw[1] = 0;\n\t\t\tnormaliw[2] = 0;\n\t\t}\n\n\t\t//  Transformation matrix Rref_i = I - 2.0*normal_iwall*normal_iwall\n\t\tRref_i[0] = 1.0 - 2.0*normaliw[0]*normaliw[0]; Rref_i[1] = 0.0 - 2.0*normaliw[0]*normaliw[1]; Rref_i[2] = 0.0 - 2.0*normaliw[0]*normaliw[2];\n\t\tRref_i[3] = 0.0 - 2.0*normaliw[1]*normaliw[0]; Rref_i[4] = 1.0 - 2.0*normaliw[1]*normaliw[1]; Rref_i[5] = 0.0 - 2.0*normaliw[1]*normaliw[2];\n\t\tRref_i[6] = 0.0 - 2.0*normaliw[2]*normaliw[0]; Rref_i[7] = 0.0 - 2.0*normaliw[2]*normaliw[1]; Rref_i[8] = 1.0 - 2.0*normaliw[2]*normaliw[2];\n\t\t\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and im (intersection) and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reS2 && dstimj2 < reS2 && dstij2 < dstimj2) {\n\t\t\t\tif(j != i) {\n\t\t\t\t\tdouble dst = sqrt(dstimj2);\n\t\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\t\tdr_ix += v0imj*wS/dst;\n\t\t\t\t\tdr_iy += v1imj*wS/dst;\n\t\t\t\t\tdr_iz += v2imj*wS/dst;\n\t\t\t\t}}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\n\t\t// Add \"i\" contribution (\"i\" is a neighbor of \"mirror i\")\n\t\tdouble v0imi, v1imi, v2imi, dstimi2;\n\t\tsqrDistBetweenParticles(i, posMirrorXi, posMirrorYi, posMirrorZi, v0imi, v1imi, v2imi, dstimi2);\n\t  \t\n\t\tif(dstimi2 < reS2) {\n\t\t\tdouble dst = sqrt(dstimi2);\n\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\tdr_ix += v0imi*wS/dst;\n\t\t\tdr_iy += v1imi*wS/dst;\n\t\t\tdr_iz += v2imi*wS/dst;\n\t\t}\n\n\t\tdouble drx = Rref_i[0]*dr_ix + Rref_i[1]*dr_iy + Rref_i[2]*dr_iz;\n\t\tdouble dry = Rref_i[3]*dr_ix + Rref_i[4]*dr_iy + Rref_i[5]*dr_iz;\n\t\tdouble drz = Rref_i[6]*dr_ix + Rref_i[7]*dr_iy + Rref_i[8]*dr_iz;\n\t\t\n\t\tnormal[i*3  ] += - drx/pndSmallZero;\n\t\tnormal[i*3+1] += - dry/pndSmallZero;\n\t\tnormal[i*3+2] += - drz/pndSmallZero;\n\n/*\n\t\t// Normalize\n\t\tdouble norm2 = normal[i*3  ]*normal[i*3  ] + normal[i*3+1]*normal[i*3+1] + normal[i*3+2]*normal[i*3+2];\n\t\tif(norm2 > 0.0) {\n\t\t\tdouble norm = sqrt(norm2);\n\t\t\tnormal[i*3  ] /= norm;\n\t\t\tnormal[i*3+1] /= norm;\n\t\t\tnormal[i*3+2] /= norm;\n\t\t}\n\t\telse {\n\t\t\tnormal[i*3  ] = 0.0;\n\t\t\tnormal[i*3+1] = 0.0;\n\t\t\tnormal[i*3+2] = 0.0;\n\t\t}\n*/\t\n\t}}\n}\n\n\n// Shifting technique (Polygon wall)\nvoid MpsParticle::calcWallShifting() {\n\t//int nPartNearMesh = partNearMesh.size();\n\t//printf(\" Mesh %d \\n\", nPartNearMesh);\n\t// Loop only for particles near mesh\n#pragma omp parallel for schedule(dynamic,64)\n\t//for(int im=0;im<nPartNearMesh;im++) {\n\t//int i = partNearMesh[im];\n\tfor(int i=0; i<numParticles; i++) {\n\t//if(particleType[i] == fluid) {\n\tif(particleType[i] == fluid && particleNearWall[i] == true) {\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\tdouble velXi = vel[i*3  ];\tdouble velYi = vel[i*3+1];\tdouble velZi = vel[i*3+2];\n\t\tdouble duXi = 0.0;\tdouble duYi = 0.0;\tdouble duZi = 0.0;\n\n\t\t// No-slip\n\n\t\t// Inverse matrix Rinv_i = - I\n\t\tdouble Rinv_i[9], normaliw[3], normalMod2;\n\t\t// normal fluid-wall particle = 0.5*(normal fluid-mirror particle)\n\t\tnormaliw[0] = 0.5*(posXi - posMirrorXi); normaliw[1] = 0.5*(posYi - posMirrorYi); normaliw[2] = 0.5*(posZi - posMirrorZi);\n\t\tnormalMod2 = normaliw[0]*normaliw[0] + normaliw[1]*normaliw[1] + normaliw[2]*normaliw[2];\n\n\t\tif(normalMod2 > 1.0e-8) {\n\t\t\tdouble normalMod = sqrt(normalMod2);\n\t\t\tnormaliw[0] = normaliw[0]/normalMod;\n\t\t\tnormaliw[1] = normaliw[1]/normalMod;\n\t\t\tnormaliw[2] = normaliw[2]/normalMod;\n\t\t}\n\t\telse {\n\t\t\tnormaliw[0] = 0;\n\t\t\tnormaliw[1] = 0;\n\t\t\tnormaliw[2] = 0;\n\t\t}\n\n\t\t// Inverse transformation matrix Rinv_i = - I\n\t\tRinv_i[0] = -1.0; Rinv_i[1] =  0.0; Rinv_i[2] =  0.0;\n\t\tRinv_i[3] =  0.0; Rinv_i[4] = -1.0; Rinv_i[5] =  0.0;\n\t\tRinv_i[6] =  0.0; Rinv_i[7] =  0.0; Rinv_i[8] = -1.0;\n\n\t\tdouble viwall[3], vtil[3];\n\t\t// Wall velocity (0 if fixed)\n\t\tviwall[0]=viwall[1]=viwall[2]=0.0;\n\n\t\tif(nearMeshType[i] == meshType::FORCED) {\n\t\t\tviwall[0] = velVWall[0];\n\t\t\tviwall[1] = velVWall[1];\n\t\t\tviwall[2] = velVWall[2];\n\t\t}\n\n\t\t// normal_iwall*v_iwall\n\t\tdouble dotnv = normaliw[0]*viwall[0] + normaliw[1]*viwall[1] + normaliw[2]*viwall[2];\n\t\t// vtil = vi - 2 {v_iwall - (normal_iwall*v_iwall)normal_iwall}\n\t\tvtil[0] = velXi - 2.0*(viwall[0] - dotnv*normaliw[0]);\n\t\tvtil[1] = velYi - 2.0*(viwall[1] - dotnv*normaliw[1]);\n\t\tvtil[2] = velZi - 2.0*(viwall[2] - dotnv*normaliw[2]);\n\t\t// Mirror particle velocity vi' = Rinv_i * [vi - 2 {v_iwall - (normal_iwall*v_iwall)normal_iwall}] \n\t\tdouble velMirrorXi = (Rinv_i[0]*vtil[0] + Rinv_i[1]*vtil[1] + Rinv_i[2]*vtil[2]);\n\t\tdouble velMirrorYi = (Rinv_i[3]*vtil[0] + Rinv_i[4]*vtil[1] + Rinv_i[5]*vtil[2]);\n\t\tdouble velMirrorZi = (Rinv_i[6]*vtil[0] + Rinv_i[7]*vtil[1] + Rinv_i[8]*vtil[2]);\n\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and im (intersection) and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reS2 && dstimj2 < reS2 && dstij2 < dstimj2) {\n\t\t\t\tif(j != i) {\n\t\t\t\t\tdouble dst = sqrt(dstimj2);\n\t\t\t\t\tdouble dw = delWeight(dst, reS, weightType);\n\t\t\t\t\tduXi += dw*(vel[j*3  ]-velMirrorXi);\n\t\t\t\t\tduYi += dw*(vel[j*3+1]-velMirrorYi);\n\t\t\t\t\tduZi += dw*(vel[j*3+2]-velMirrorZi);\n\t\t\t\t}}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\t\t// Add \"i\" contribution (\"i\" is a neighbor of \"mirror i\")\n\t\tdouble v0imi, v1imi, v2imi, dstimi2;\n\t\tsqrDistBetweenParticles(i, posMirrorXi, posMirrorYi, posMirrorZi, v0imi, v1imi, v2imi, dstimi2);\n\t  \t\n\t\tif(dstimi2 < reS2) {\n\t\t\tdouble dst = sqrt(dstimi2);\n\t\t\tdouble dw = delWeight(dst, reS, weightType);\n\t\t\tduXi += dw*(velXi-velMirrorXi);\n\t\t\tduYi += dw*(velYi-velMirrorYi);\n\t\t\tduZi += dw*(velZi-velMirrorZi);\n\t\t}\n\t\n//\t\tif(wallType == boundaryWallType::POLYGON) {\n//\t\t\tif(pndi[i] > pndThreshold*pndSmallZero)\n//\t\t}\n//\t\telse if(wallType == boundaryWallType::PARTICLE) \n//\t\t\tif(pndi[i] > pndThreshold*pndSmallZero || numNeigh[i] > neighThreshold*numNeighZero)\n//\t\t}\n//\t\tif(pndSmall[i] > pndThreshold*pndSmallZero || numNeigh[i] > neighThreshold*numNeighZero)\n\t\tif(particleBC[i] == inner) {\n\t\t\tdouble dux = Rinv_i[0]*duXi + Rinv_i[1]*duYi + Rinv_i[2]*duZi;\n\t\t\tdouble duy = Rinv_i[3]*duXi + Rinv_i[4]*duYi + Rinv_i[5]*duZi;\n\t\t\tdouble duz = Rinv_i[6]*duXi + Rinv_i[7]*duYi + Rinv_i[8]*duZi;\n\t\t\tvel[i*3  ] -= coeffShifting1*dux;\n\t\t\tvel[i*3+1] -= coeffShifting1*duy;\n\t\t\tvel[i*3+2] -= coeffShifting1*duz;\n\t\t}\n\t\t// else {\n\t\t// \tdouble Inn[9], duAux[3];\n\t\t// \t// I - nxn\n\t\t// \tInn[0] = 1.0 - normal[i*3  ]*normal[i*3  ]; Inn[1] = 0.0 - normal[i*3  ]*normal[i*3+1]; Inn[2] = 0.0 - normal[i*3  ]*normal[i*3+2];\n\t\t// \tInn[3] = 0.0 - normal[i*3+1]*normal[i*3  ]; Inn[4] = 1.0 - normal[i*3+1]*normal[i*3+1]; Inn[5] = 0.0 - normal[i*3+1]*normal[i*3+2];\n\t\t// \tInn[6] = 0.0 - normal[i*3+2]*normal[i*3  ]; Inn[7] = 0.0 - normal[i*3+2]*normal[i*3+1]; Inn[8] = 1.0 - normal[i*3+2]*normal[i*3+2];\n\t\t// \tdouble dux = Rinv_i[0]*duXi + Rinv_i[1]*duYi + Rinv_i[2]*duZi;\n\t\t//\tdouble duy = Rinv_i[3]*duXi + Rinv_i[4]*duYi + Rinv_i[5]*duZi;\n\t\t//\tdouble duz = Rinv_i[6]*duXi + Rinv_i[7]*duYi + Rinv_i[8]*duZi;\n\t\t// \t// (I - nxn)dr\n\t\t// \tduAux[0] = Inn[0]*dux + Inn[1]*duy + Inn[2]*duz;\n\t\t// \tduAux[1] = Inn[3]*dux + Inn[4]*duy + Inn[5]*duz;\n\t\t// \tduAux[2] = Inn[6]*dux + Inn[7]*duy + Inn[8]*duz;\n\t\t// \tvel[i*3  ] -= coeffShifting1*duAux[0];\n\t\t// \tvel[i*3+1] -= coeffShifting1*duAux[1];\n\t\t// \tvel[i*3+2] -= coeffShifting1*duAux[2];\n\t\t// }\n\t}}\n}\n\n// Concentration and Gradient of concentration\nvoid MpsParticle::calcConcAndConcGradient() {\n\t// Concentration\n#pragma omp parallel for schedule(dynamic,64)\n\tfor(int i=0; i<numParticles; i++) {\n\t\tconcentration[i] = 0.0;\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble velXi = vel[i*3  ];\tdouble velYi = vel[i*3+1];\tdouble velZi = vel[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\t\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reS2 && (dstij2 < dstimj2 || wallType == boundaryWallType::PARTICLE)) {\n\t\t\t\tif(j != i) {\n\t\t\t\t\tdouble dst = sqrt(dstij2);\n\t\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\t\tconcentration[i] += wS;\n\t\t\t\t}}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\n\t\t// Add PND due Wall polygon\n\t\tconcentration[i] += pndWallContribution[i];\n\n\t\tconcentration[i] /= pndSmallZero;\n\t}\n\t// Gradient of concentration\n#pragma omp parallel for schedule(dynamic,64)\n\tfor(int i=0; i<numParticles; i++) {\n\tif(particleType[i] == fluid) {\n\t\tgradConcentration[i*3  ] = 0.0;\tgradConcentration[i*3+1] = 0.0;\tgradConcentration[i*3+2] = 0.0;\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble velXi = vel[i*3  ];\tdouble velYi = vel[i*3+1];\tdouble velZi = vel[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\tdouble duXi = 0.0;\tdouble duYi = 0.0;\tdouble duZi = 0.0;\n\t\tdouble conc_i = concentration[i];\n\t\t\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reS2 && (dstij2 < dstimj2 || wallType == boundaryWallType::PARTICLE)) {\n\t\t\t\tif(j != i) {\n\t\t\t\t\tdouble dst = sqrt(dstij2);\n\t\t\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\t\t\tgradConcentration[i*3  ] += (conc_i + concentration[j])*v0ij*wS/dstij2;\n\t\t\t\t\tgradConcentration[i*3+1] += (conc_i + concentration[j])*v1ij*wS/dstij2;\n\t\t\t\t\tgradConcentration[i*3+2] += (conc_i + concentration[j])*v2ij*wS/dstij2;\n\t\t\t\t}}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\t\t//coeffPressGrad = -dim/pndGradientZero\n\t\tgradConcentration[3*i  ] *= -coeffPressGrad;\n\t\tgradConcentration[3*i+1] *= -coeffPressGrad;\n\t\tgradConcentration[3*i+2] *= -coeffPressGrad;\n\n//\t\tif(wallType == boundaryWallType::POLYGON) {\n//\t\t\tif(pndi[i] > pndThreshold*pndSmallZero)\n//\t\t}\n//\t\telse if(wallType == boundaryWallType::PARTICLE) \n//\t\t\tif(pndi[i] > pndThreshold*pndSmallZero || numNeigh[i] > neighThreshold*numNeighZero)\n//\t\t}\n//\t\tif(pndSmall[i] > pndThreshold*pndSmallZero || numNeigh[i] > neighThreshold*numNeighZero)\n\t\tif(particleBC[i] == inner) {\n\t\t\t// coeffShifting2 = coefA*partDist*partDist*cflNumber*machNumber;\t// Coefficient used to adjust velocity\n\t\t\tpos[i*3  ] -= coeffShifting2*gradConcentration[3*i  ];\n\t\t\tpos[i*3+1] -= coeffShifting2*gradConcentration[3*i+1];\n\t\t\tpos[i*3+2] -= coeffShifting2*gradConcentration[3*i+2];\n\t\t}\n\t\t/*\n\t\telse\n\t\t{\n\t\t\tdouble Inn[9], drAux[3];\n\t\t\t// I - nxn\n\t\t\tInn[0] = 1.0 - normal[i*3  ]*normal[i*3  ]; Inn[1] = 0.0 - normal[i*3  ]*normal[i*3+1]; Inn[2] = 0.0 - normal[i*3  ]*normal[i*3+2];\n\t\t\tInn[3] = 0.0 - normal[i*3+1]*normal[i*3  ]; Inn[4] = 1.0 - normal[i*3+1]*normal[i*3+1]; Inn[5] = 0.0 - normal[i*3+1]*normal[i*3+2];\n\t\t\tInn[6] = 0.0 - normal[i*3+2]*normal[i*3  ]; Inn[7] = 0.0 - normal[i*3+2]*normal[i*3+1]; Inn[8] = 1.0 - normal[i*3+2]*normal[i*3+2];\n\t\t\t// (I - nxn)dr\n\t\t\tdrAux[0] = Inn[0]*gradConcentration[3*i  ] + Inn[1]*gradConcentration[3*i+1] + Inn[2]*gradConcentration[3*i+2];\n\t\t\tdrAux[1] = Inn[3]*gradConcentration[3*i  ] + Inn[4]*gradConcentration[3*i+1] + Inn[5]*gradConcentration[3*i+2];\n\t\t\tdrAux[2] = Inn[6]*gradConcentration[3*i  ] + Inn[7]*gradConcentration[3*i+1] + Inn[8]*gradConcentration[3*i+2];\n\t\t\t// coeffShifting2 = coefA*partDist*partDist*cflNumber*machNumber;\t// Coefficient used to adjust Velocity\n\t\t\tpos[i*3  ] -= coeffShifting2*drAux[0];\n\t\t\tpos[i*3+1] -= coeffShifting2*drAux[1];\n\t\t\tpos[i*3+2] -= coeffShifting2*drAux[2];\n\t\t}\n\t\t*/\n\t\t// else {\n\t\t// \tdouble Inn[9], duAux[3];\n\t\t// \t// I - nxn\n\t\t// \tInn[0] = 1.0 - normal[i*3  ]*normal[i*3  ]; Inn[1] = 0.0 - normal[i*3  ]*normal[i*3+1]; Inn[2] = 0.0 - normal[i*3  ]*normal[i*3+2];\n\t\t// \tInn[3] = 0.0 - normal[i*3+1]*normal[i*3  ]; Inn[4] = 1.0 - normal[i*3+1]*normal[i*3+1]; Inn[5] = 0.0 - normal[i*3+1]*normal[i*3+2];\n\t\t// \tInn[6] = 0.0 - normal[i*3+2]*normal[i*3  ]; Inn[7] = 0.0 - normal[i*3+2]*normal[i*3+1]; Inn[8] = 1.0 - normal[i*3+2]*normal[i*3+2];\n\t\t// \t// (I - nxn)dr\n\t\t// \tduAux[0] = Inn[0]*duXi + Inn[1]*duYi + Inn[2]*duZi;\n\t\t// \tduAux[1] = Inn[3]*duXi + Inn[4]*duYi + Inn[5]*duZi;\n\t\t// \tduAux[2] = Inn[6]*duXi + Inn[7]*duYi + Inn[8]*duZi;\n\t\t// \tvel[i*3  ] -= coeffShifting1*duAux[0];\n\t\t// \tvel[i*3+1] -= coeffShifting1*duAux[1];\n\t\t// \tvel[i*3+2] -= coeffShifting1*duAux[2];\n\t\t// }\n\t}}\n}\n\n// Concentration and Gradient of concentration (Polygon wall)\nvoid MpsParticle::calcWallConcAndConcGradient() {\n\t// Gradient of concentration due Polygon wall\n\t//int nPartNearMesh = partNearMesh.size();\n\tdouble VolumeForce = pow(partDist,dim);\n\t//printf(\" Mesh %d \\n\", nPartNearMesh);\n\t// Loop only for particles near mesh\n#pragma omp parallel for schedule(dynamic,64)\n\t//for(int im=0;im<nPartNearMesh;im++) {\n\t//int i = partNearMesh[im];\n\tfor(int i=0; i<numParticles; i++) {\n\t//if(particleType[i] == fluid) {\n\tif(particleType[i] == fluid && particleNearWall[i] == true) {\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble velXi = vel[i*3  ];\tdouble velYi = vel[i*3+1];\tdouble velZi = vel[i*3+2];\n\t\tdouble posMirrorXi = mirrorParticlePos[i*3  ];\tdouble posMirrorYi = mirrorParticlePos[i*3+1];\tdouble posMirrorZi = mirrorParticlePos[i*3+2];\n\t\tdouble drX = 0.0;\t\t\tdouble drY = 0.0;\t\t\tdouble drZ = 0.0;\n\t\tdouble gradCiWallX = 0.0;\t\t\tdouble gradCiWallY = 0.0;\t\t\tdouble gradCiWallZ = 0.0;\n\t\tdouble ni = pndi[i];\n\t\tdouble conc_i = concentration[i];\n\n\t\t// Wall gradient Mitsume`s model\n\t\tdouble Rref_i[9], normaliw[3], normaliwSqrt;\n\t\t// normal fluid-wall particle = 0.5*(normal fluid-mirror particle)\n\t\tnormaliw[0] = 0.5*(posXi - posMirrorXi); normaliw[1] = 0.5*(posYi - posMirrorYi); normaliw[2] = 0.5*(posZi - posMirrorZi);\n\t\tnormaliwSqrt = sqrt(normaliw[0]*normaliw[0] + normaliw[1]*normaliw[1] + normaliw[2]*normaliw[2]);\n\n\t\tif(normaliwSqrt > 1.0e-8) {\n\t\t\tnormaliw[0] = normaliw[0]/normaliwSqrt;\n\t\t\tnormaliw[1] = normaliw[1]/normaliwSqrt;\n\t\t\tnormaliw[2] = normaliw[2]/normaliwSqrt;\n\t\t}\n\t\telse {\n\t\t\tnormaliw[0] = 0;\n\t\t\tnormaliw[1] = 0;\n\t\t\tnormaliw[2] = 0;\n\t\t}\n\n\t\t//  Transformation matrix Rref_i = I - 2.0*normal_iwall*normal_iwall\n\t\tRref_i[0] = 1.0 - 2.0*normaliw[0]*normaliw[0]; Rref_i[1] = 0.0 - 2.0*normaliw[0]*normaliw[1]; Rref_i[2] = 0.0 - 2.0*normaliw[0]*normaliw[2];\n\t\tRref_i[3] = 0.0 - 2.0*normaliw[1]*normaliw[0]; Rref_i[4] = 1.0 - 2.0*normaliw[1]*normaliw[1]; Rref_i[5] = 0.0 - 2.0*normaliw[1]*normaliw[2];\n\t\tRref_i[6] = 0.0 - 2.0*normaliw[2]*normaliw[0]; Rref_i[7] = 0.0 - 2.0*normaliw[2]*normaliw[1]; Rref_i[8] = 1.0 - 2.0*normaliw[2]*normaliw[2];\n\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, v0imj, v1imj, v2imj, dstij2, dstimj2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\t\t\t\t// Mirror particle square distance r_imj^2 = (Xj - Xim_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posMirrorXi, posMirrorYi, posMirrorZi, v0imj, v1imj, v2imj, dstimj2, plx, ply, plz);\n\n\t\t\t\t// If j is inside the neighborhood of i and im (intersection) and \n\t\t\t\t// is not at the same side of im (avoid real j in the virtual neihborhood)\n\t\t\t\tif(dstij2 < reS2 && dstimj2 < reS2 && dstij2 < dstimj2) {\n\t\t\t\tif(j != i) {\n\t\t\t\t\tdouble dst = sqrt(dstimj2);\n\t\t\t\t\tdouble wS = weightGradient(dst, reS, weightType);\n\n\t\t\t\t\tdrX += (conc_i + concentration[j])*v0imj*wS/dstimj2;\n\t\t\t\t\tdrY += (conc_i + concentration[j])*v1imj*wS/dstimj2;\n\t\t\t\t\tdrZ += (conc_i + concentration[j])*v2imj*wS/dstimj2;\n\t\t\t\t}}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\t\t// Add \"i\" contribution (\"i\" is a neighbor of \"mirror i\")\n\t\tdouble v0imi, v1imi, v2imi, dstimi2;\n\t\tsqrDistBetweenParticles(i, posMirrorXi, posMirrorYi, posMirrorZi, v0imi, v1imi, v2imi, dstimi2);\n\t\t\n\t\tif(dstimi2 < reS2) {\n\t\t\tdouble dst = sqrt(dstimi2);\n\t\t\tdouble wS = weightGradient(dst, reS, weightType);\n\n\t\t\tdrX += (conc_i + conc_i)*v0imi*wS/dstimi2;\n\t\t\tdrY += (conc_i + conc_i)*v1imi*wS/dstimi2;\n\t\t\tdrZ += (conc_i + conc_i)*v2imi*wS/dstimi2;\n\t\t}\n\n\t\t// coeffPressGrad is a negative cte (-dim/noGrad)\n\t\t// Original\n//\t\tacc[i*3  ] += (relaxPress*(Rref_i[0]*accX + Rref_i[1]*accY + Rref_i[2]*accZ)*coeffPressGrad - rpsForce[0])*invDns[partType::FLUID];\n//\t\tacc[i*3+1] += (relaxPress*(Rref_i[3]*accX + Rref_i[4]*accY + Rref_i[5]*accZ)*coeffPressGrad - rpsForce[1])*invDns[partType::FLUID];\n//\t\tacc[i*3+2] += (relaxPress*(Rref_i[6]*accX + Rref_i[7]*accY + Rref_i[8]*accZ)*coeffPressGrad - rpsForce[2])*invDns[partType::FLUID];\n\t\t// Modified\n\t\tgradCiWallX = -(Rref_i[0]*drX + Rref_i[1]*drY + Rref_i[2]*drZ)*coeffPressGrad;\n\t\tgradCiWallY = -(Rref_i[3]*drX + Rref_i[4]*drY + Rref_i[5]*drZ)*coeffPressGrad;\n\t\tgradCiWallZ = -(Rref_i[6]*drX + Rref_i[7]*drY + Rref_i[8]*drZ)*coeffPressGrad;\n\n\t\tgradConcentration[i*3  ] += gradCiWallX;\n\t\tgradConcentration[i*3+1] += gradCiWallY;\n\t\tgradConcentration[i*3+2] += gradCiWallZ;\n\n\t\tif(particleBC[i] == inner) {\n\t\t\t// coeffShifting2 = coefA*partDist*partDist*cflNumber*machNumber;\t// Coefficient used to adjust velocity\n\t\t\tpos[i*3  ] -= coeffShifting2*gradCiWallX;\n\t\t\tpos[i*3+1] -= coeffShifting2*gradCiWallY;\n\t\t\tpos[i*3+2] -= coeffShifting2*gradCiWallZ;\n\t\t}\n\t}}\n}\n\n// normal vector on the fluid\nvoid MpsParticle::calcNormalConcentration() {\n#pragma omp parallel for\n\tfor(int i=0; i<numParticles; i++) {\n\t\tdouble norm2GradCi = gradConcentration[3*i]*gradConcentration[3*i] + gradConcentration[3*i+1]*gradConcentration[3*i+1] + gradConcentration[3*i+2]*gradConcentration[3*i+2];\n\t\t\n\t\tif(norm2GradCi > 0.0) {\n\t\t\tdouble norm = sqrt(norm2GradCi);\n\t\t\tnormal[i*3  ] = -gradConcentration[i*3  ]/norm;\n\t\t\tnormal[i*3+1] = -gradConcentration[i*3+1]/norm;\n\t\t\tnormal[i*3+2] = -gradConcentration[i*3+2]/norm;\n\t\t}\n\t\telse {\n\t\t\tnormal[i*3  ] = 0.0;\n\t\t\tnormal[i*3+1] = 0.0;\n\t\t\tnormal[i*3+2] = 0.0;\n\t\t}\n\t}\n}\n\n// Update velocity at wall and dummy particles\nvoid MpsParticle::updateVelocityParticlesWallDummy() {\n\tdouble velWallx = 0.0;\n\tdouble velWally = 0.0;\n\tdouble velWallz = 0.0;\n#pragma omp parallel for schedule(dynamic,64)\n\tfor(int i=0; i<numParticles; i++) {\n\tif(particleType[i] == dummyWall) {\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\tdouble velXi = vel[i*3  ];\tdouble velYi = vel[i*3+1];\tdouble velZi = vel[i*3+2];\n\t\tdouble duXi = 0.0;\tdouble duYi = 0.0;\tdouble duZi = 0.0;\n\t\tdouble ni = 0.0;\n\t\t\n\t\tint ix, iy, iz;\n\t\tbucketCoordinates(ix, iy, iz, posXi, posYi, posZi);\n\t\tint minZ = (iz-1)*((int)(dim-2.0)); int maxZ = (iz+1)*((int)(dim-2.0));\n\t\tfor(int jz=minZ;jz<=maxZ;jz++) {\n\t\tfor(int jy=iy-1;jy<=iy+1;jy++) {\n\t\tfor(int jx=ix-1;jx<=ix+1;jx++) {\n\t\t\tint jb = jz*numBucketsXY + jy*numBucketsX + jx;\n\t\t\tint j = firstParticleInBucket[jb];\n\t\t\tif(j == -1) continue;\n\t\t\tdouble plx, ply, plz;\n\t\t\tgetPeriodicLengths(jb, plx, ply, plz);\n\t\t\twhile(true) {\n\t\t\t\tdouble v0ij, v1ij, v2ij, dstij2;\n\t\t\t\t\n\t\t\t\t// Particle square distance r_ij^2 = (Xj - Xi_temporary_position)^2\n\t\t\t\tsqrDistBetweenParticles(j, posXi, posYi, posZi, v0ij, v1ij, v2ij, dstij2, plx, ply, plz);\n\n\t\t\t\tif(dstij2 < reL2) {\n//\t\t\t\tif(j != i) {\n\t\t\t\tif(j != i && particleType[j] == fluid) {\n\t\t\t\t\tdouble dst = sqrt(dstij2);\n\t\t\t\t\tdouble wL = weight(dst, reL, weightType);\n\t\t\t\t\tni += wL;\n\t\t\t\t\tduXi += vel[j*3  ]*wL;\n\t\t\t\t\tduYi += vel[j*3+1]*wL;\n\t\t\t\t\tduZi += vel[j*3+2]*wL;\n\t\t\t\t}}\n\t\t\t\tj = nextParticleInSameBucket[j];\n\t\t\t\tif(j == -1) break;\n\t\t\t}\n\t\t}}}\n\t\tif(ni > 1.0e-8) {\n\t\t\tvel[i*3  ] = 2.0*velWallx - duXi/ni;\n\t\t\tvel[i*3+1] = 2.0*velWally - duYi/ni;\n\t\t\tvel[i*3+2] = 2.0*velWallz - duZi/ni;\n\t\t}\n\t\telse {\n\t\t\tvel[i*3  ] = 2.0*velWallx - duXi;\n\t\t\tvel[i*3+1] = 2.0*velWally - duYi;\n\t\t\tvel[i*3+2] = 2.0*velWallz - duZi;\n\t\t}\n\t}}\n}\n\n// Pressure sensors\nvoid MpsParticle::writePressSensors() {\n\n\tdouble P1, P2, P3, P4, posP1[3], posP2[3], posP3[3], posP4[3];\n\tdouble pndP1, pndP2, pndP3, pndP4, P1wij, P2wij, P3wij, P4wij;\n\tdouble riP1, riP2, riP3, riP4;\n\n\tdouble xPrs1Min, xPrs1Max, xPrs2Min, xPrs2Max;\n\tdouble yPrs1Min, yPrs1Max, yPrs2Min, yPrs2Max;\n\tdouble zPrs1min, zPrs2min, zPrs3min, zPrs4min;\n\tdouble zPrs1max, zPrs2max, zPrs3max, zPrs4max;\n\n\t// Pressure at sensor\n\tP1=P2=P3=P4=0.0;\n\t// PND for each sensor\n\tpndP1=pndP2=pndP3=pndP4=0.0;\n\t// Pressure * wij\n\tP1wij=P2wij=P3wij=P4wij=0.0;\n\t// Square distance between the fluid particle and the sensor\n\triP1=riP2=riP3=riP4=10.0e10;\n\n\t// Sensor limits\n\t// Dam 1610\n\t/*\n\txPrs1Min = 1.61 - 2.0*partDist; xPrs1Max = 1.61 + partDist;\n\tyPrs1Min = 0.075 - 2.0*partDist; yPrs1Max = 0.075 + 2.0*partDist;\n\tzPrs1min = 0.003 - partDist; zPrs2min = 0.015 - partDist; zPrs3min = 0.030 - partDist; zPrs4min = 0.080 - partDist;\n\tzPrs1max = 0.003 + partDist; zPrs2max = 0.015 + partDist; zPrs3max = 0.030 + partDist; zPrs4max = 0.080 + partDist;\n*/\n\t// Hydrostatic\n\txPrs1Min = 0.1 - 2.0*partDist; xPrs1Max = 0.1 + partDist; xPrs2Min = 0.0 - 2.0*partDist; xPrs2Max = 0.0 + partDist;\n\tyPrs1Min = 0.1 - 2.0*partDist; yPrs1Max = 0.1 + 2.0*partDist; yPrs2Min = 0.1 - 2.0*partDist; yPrs2Max = 0.1 + 2.0*partDist;\n\tzPrs1min = 0.0 - partDist; zPrs2min = 0.1 - partDist;\n\tzPrs1max = 0.0 + partDist; zPrs2max = 0.1 + partDist;\n\n\t// Sensor positions\n\t// Dam 1610\n\t/*\n\tposP1[0] = 1.61; posP1[1] = 0.075; posP1[2] = 0.003;\n\tposP2[0] = 1.61; posP2[1] = 0.075; posP2[2] = 0.015;\n\tposP3[0] = 1.61; posP3[1] = 0.075; posP3[2] = 0.030;\n\tposP4[0] = 1.61; posP4[1] = 0.075; posP4[2] = 0.080;\n*/\n\t// Hydrostatic\n\tposP1[0] = 0.1; posP1[1] = 0.1; posP1[2] = 0.0;\n\tposP2[0] = 0.0; posP2[1] = 0.1; posP2[2] = 0.1;\n\n#pragma omp parallel for reduction(+: pndP1, pndP2, pndP3, pndP4, P1wij, P2wij, P3wij, P4wij)\n\tfor(int i=0; i<numParticles; i++) {\n\t\tdouble posXi = pos[i*3  ];\tdouble posYi = pos[i*3+1];\tdouble posZi = pos[i*3+2];\n\t\t\n\t\t/*\n\t\t// Pressure at a specific particle close to the sensor\n\t\t// Dam 1610\n\t\tif(posXi >= xPrs1Min && posXi <= xPrs1Max && posYi >= yPrs1Min && posYi <= yPrs1Max) {\n\t\t\t// Sensor 1\n\t\t\tif(posZi >= zPrs1min && posZi <= zPrs1max) {\n\t\t\t\tif(press[i] > 0.0) {\n\t\t\t\t\tdouble v0 = posP1[0] - posXi;\n\t\t\t\t\tdouble v1 = posP1[1] - posYi;\n\t\t\t\t\tdouble v2 = posP1[2] - posZi;\n\t\t\t\t\tdouble dst2 = v0*v0+v1*v1+v2*v2;\n\t\t\t\t\t// Closest fluid particle\n\t\t\t\t\tif(dst2 < riP1) {\n\t\t\t\t\t\tP1 = press[i];\n\t\t\t\t\t\triP1 = dst2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Sensor 2\n\t\t\tif(posZi >= zPrs2min && posZi <= zPrs2max) {\n\t\t\t\tif(press[i] > 0.0) {\n\t\t\t\t\tdouble v0 = posP2[0] - posXi;\n\t\t\t\t\tdouble v1 = posP2[1] - posYi;\n\t\t\t\t\tdouble v2 = posP2[2] - posZi;\n\t\t\t\t\tdouble dst2 = v0*v0+v1*v1+v2*v2;\n\t\t\t\t\t// Closest fluid particle\n\t\t\t\t\tif(dst2 < riP2) {\n\t\t\t\t\t\tP2 = press[i];\n\t\t\t\t\t\triP2 = dst2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Sensor 3\n\t\t\tif(posZi >= zPrs3min && posZi <= zPrs3max) {\n\t\t\t\tif(press[i] > 0.0) {\n\t\t\t\t\tdouble v0 = posP3[0] - posXi;\n\t\t\t\t\tdouble v1 = posP3[1] - posYi;\n\t\t\t\t\tdouble v2 = posP3[2] - posZi;\n\t\t\t\t\tdouble dst2 = v0*v0+v1*v1+v2*v2;\n\t\t\t\t\t// Closest fluid particle\n\t\t\t\t\tif(dst2 < riP3) {\n\t\t\t\t\t\tP3 = press[i];\n\t\t\t\t\t\triP3 = dst2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Sensor 4\n\t\t\tif(posZi >= zPrs4min && posZi <= zPrs4max) {\n\t\t\t\tif(press[i] > 0.0) {\n\t\t\t\t\tdouble v0 = posP4[0] - posXi;\n\t\t\t\t\tdouble v1 = posP4[1] - posYi;\n\t\t\t\t\tdouble v2 = posP4[2] - posZi;\n\t\t\t\t\tdouble dst2 = v0*v0+v1*v1+v2*v2;\n\t\t\t\t\t// Closest fluid particle\n\t\t\t\t\tif(dst2 < riP4) {\n\t\t\t\t\t\tP4 = press[i];\n\t\t\t\t\t\triP4 = dst2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Weighted average pressure\n\t\tdouble v0 = posP1[0] - posXi;\n\t\tdouble v1 = posP1[1] - posYi;\n\t\tdouble v2 = posP1[2] - posZi;\n\t\tdouble dst2 = v0*v0+v1*v1+v2*v2;\n\t\tif(dst2 < reS2) {\n\t\t\tdouble dst = sqrt(dst2);\n\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\tif(press[i] > 0.0){\n\t\t\t\tpndP1 += wS;\n\t\t\t\tP1wij += press[i]*wS;\n\t\t\t}\n\t\t}\n\t\t\n\t\tv0 = posP2[0] - posXi;\n\t\tv1 = posP2[1] - posYi;\n\t\tv2 = posP2[2] - posZi;\n\t\tdst2 = v0*v0+v1*v1+v2*v2;\n\t\tif(dst2 < reS2) {\n\t\t\tdouble dst = sqrt(dst2);\n\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\tif(press[i] > 0.0){\n\t\t\t\tpndP2 += wS;\n\t\t\t\tP2wij += press[i]*wS;\n\t\t\t}\n\t\t}\n\t\t\n\t\tv0 = posP3[0] - posXi;\n\t\tv1 = posP3[1] - posYi;\n\t\tv2 = posP3[2] - posZi;\n\t\tdst2 = v0*v0+v1*v1+v2*v2;\n\t\tif(dst2 < reS2) {\n\t\t\tdouble dst = sqrt(dst2);\n\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\tif(press[i] > 0.0){\n\t\t\t\tpndP3 += wS;\n\t\t\t\tP3wij += press[i]*wS;\n\t\t\t}\n\t\t}\n\t\t\n\t\tv0 = posP4[0] - posXi;\n\t\tv1 = posP4[1] - posYi;\n\t\tv2 = posP4[2] - posZi;\n\t\tdst2 = v0*v0+v1*v1+v2*v2;\n\t\tif(dst2 < reS2) {\n\t\t\tdouble dst = sqrt(dst2);\n\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\tif(press[i] > 0.0){\n\t\t\t\tpndP4 += wS;\n\t\t\t\tP4wij += press[i]*wS;\n\t\t\t}\n\t\t}\n\t\t*/\n\t\t// Pressure at a specific particle close to the sensor\n\t\t// Hydrostatic\n\t\tif((posXi >= xPrs1Min && posXi <= xPrs1Max && posYi >= yPrs1Min && posYi <= yPrs1Max) || (posXi >= xPrs2Min && posXi <= xPrs2Max && posYi >= yPrs2Min && posYi <= yPrs2Max)) {\n\t\t\t// Sensor 1\n\t\t\tif(posZi >= zPrs1min && posZi <= zPrs1max) {\n\t\t\t\tif(press[i] > 0.0) {\n\t\t\t\t\tdouble v0 = posP1[0] - posXi;\n\t\t\t\t\tdouble v1 = posP1[1] - posYi;\n\t\t\t\t\tdouble v2 = posP1[2] - posZi;\n\t\t\t\t\tdouble dst2 = v0*v0+v1*v1+v2*v2;\n\t\t\t\t\t// Closest fluid particle\n\t\t\t\t\tif(dst2 < riP1) {\n\t\t\t\t\t\tP1 = press[i];\n\t\t\t\t\t\triP1 = dst2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Sensor 2\n\t\t\tif(posZi >= zPrs2min && posZi <= zPrs2max) {\n\t\t\t\tif(press[i] > 0.0) {\n\t\t\t\t\tdouble v0 = posP2[0] - posXi;\n\t\t\t\t\tdouble v1 = posP2[1] - posYi;\n\t\t\t\t\tdouble v2 = posP2[2] - posZi;\n\t\t\t\t\tdouble dst2 = v0*v0+v1*v1+v2*v2;\n\t\t\t\t\t// Closest fluid particle\n\t\t\t\t\tif(dst2 < riP2) {\n\t\t\t\t\t\tP2 = press[i];\n\t\t\t\t\t\triP2 = dst2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\t// Weighted average pressure\n\t\tdouble v0 = posP1[0] - posXi;\n\t\tdouble v1 = posP1[1] - posYi;\n\t\tdouble v2 = posP1[2] - posZi;\n\t\tdouble dst2 = v0*v0+v1*v1+v2*v2;\n\t\tif(dst2 < reS2) {\n\t\t\tdouble dst = sqrt(dst2);\n\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\tif(press[i] > 0.0){\n\t\t\t\tpndP1 += wS;\n\t\t\t\tP1wij += press[i]*wS;\n\t\t\t}\n\t\t}\n\t\t\n\t\tv0 = posP2[0] - posXi;\n\t\tv1 = posP2[1] - posYi;\n\t\tv2 = posP2[2] - posZi;\n\t\tdst2 = v0*v0+v1*v1+v2*v2;\n\t\tif(dst2 < reS2) {\n\t\t\tdouble dst = sqrt(dst2);\n\t\t\tdouble wS = weight(dst, reS, weightType);\n\t\t\tif(press[i] > 0.0){\n\t\t\t\tpndP2 += wS;\n\t\t\t\tP2wij += press[i]*wS;\n\t\t\t}\n\t\t}\n\n\t}\n\n\tchar *pressTxtFilenameChar = new char[pressTxtFilename.length()+1];\n\tstrcpy (pressTxtFilenameChar, pressTxtFilename.c_str());\n\t// pressTxtFilenameChar now contains a c-string copy of pressTxtFilename\n\n\t// Open the File to write\n\tpressTxtFile = fopen(pressTxtFilenameChar, \"a\");\n\tif(pressTxtFile == NULL) perror (\"Error opening press txt file\");\n\n\tdelete[] pressTxtFilenameChar;\n\tpressTxtFilenameChar = NULL;\n\t/*\n\t// dam 1610\n\tfprintf(pressTxtFile,\"\\n%lf\\t%lf\\t%lf\\t%lf\\t%lf\",timeCurrent, P1,P2,P3,P4);\n\tdouble Pmean;\n\t\n\tif(pndP1 > 0.0)\n\t\tPmean = P1wij/pndP1;\n\telse\n\t\tPmean = 0.0;\n\tfprintf(pressTxtFile,\"\\t%lf\",Pmean);\n\t\n\tif(pndP2 > 0.0)\n\t\tPmean = P2wij/pndP2;\n\telse\n\t\tPmean = 0.0;\n\tfprintf(pressTxtFile,\"\\t%lf\",Pmean);\n\t\n\tif(pndP3 > 0.0)\n\t\tPmean = P3wij/pndP3;\n\telse\n\t\tPmean = 0.0;\n\tfprintf(pressTxtFile,\"\\t%lf\",Pmean);\n\t\n\tif(pndP4 > 0.0)\n\t\tPmean = P4wij/pndP4;\n\telse\n\t\tPmean = 0.0;\n\tfprintf(pressTxtFile,\"\\t%lf\",Pmean);\n\t*/\n\n\t// Hydrostatic\n\tfprintf(pressTxtFile,\"\\n%lf\\t%lf\\t%lf\",timeCurrent, P1,P2);\n\tdouble Pmean;\n\t\n\tif(pndP1 > 0.0)\n\t\tPmean = P1wij/pndP1;\n\telse\n\t\tPmean = 0.0;\n\tfprintf(pressTxtFile,\"\\t%lf\",Pmean);\n\t\n\tif(pndP2 > 0.0)\n\t\tPmean = P2wij/pndP2;\n\telse\n\t\tPmean = 0.0;\n\tfprintf(pressTxtFile,\"\\t%lf\",Pmean);\n\t\n\n\t// Close press file\n\tfclose(pressTxtFile);\n\n}\n\nvoid MpsParticle::writeHeaderTxtFiles() {\n\tif(txtForce ==  true) {\n\t\tchar *forceTxtFilenameChar = new char[forceTxtFilename.length()+1];\n\t\tstrcpy (forceTxtFilenameChar, forceTxtFilename.c_str());\n\t\t// forceTxtFilenameChar now contains a c-string copy of forceTxtFilename\n\t\t\n\t\t// Open the File to write\n\t\tforceTxtFile = fopen(forceTxtFilenameChar, \"w\");\n\t\tif(forceTxtFile == NULL) perror (\"Error opening force txt file\");\n\t\tfprintf(forceTxtFile,\"Time(s)\\tForce(N) X\\tY\\tZ\");\n\t\t// Close force file\n\t\tfclose(forceTxtFile);\n\n\t\tdelete[] forceTxtFilenameChar;\n\t\tforceTxtFilenameChar = NULL;\n\t}\n\tif(txtPress ==  true) {\n\t\tchar *pressTxtFilenameChar = new char[pressTxtFilename.length()+1];\n\t\tstrcpy (pressTxtFilenameChar, pressTxtFilename.c_str());\n\t\t// pressTxtFilenameChar now contains a c-string copy of pressTxtFilename\n\n\t\t// Open the File to write\n\t\tpressTxtFile = fopen(pressTxtFilenameChar, \"w\");\n\t\tif(pressTxtFile == NULL) perror (\"Error opening press txt file\");\n\n\t\t// dam 1610\n\t\t// fprintf(pressTxtFile,\"Time(s)\\tP1(Pa)\\tP2(Pa)\\tP3(Pa)\\tP4(Pa)\\tPm1(Pa)\\tPm2(Pa)\\tPm3(Pa)\\tPm4(Pa)\");\n\n\t\t// Hydrostatic\n\t\tfprintf(pressTxtFile,\"Time(s)\\tP1(Pa)\\tP2(Pa)\\tPm1(Pa)\\tPm2(Pa)\");\n\n\t\t// Close press file\n\t\tfclose(pressTxtFile);\n\n\t\tdelete[] pressTxtFilenameChar;\n\t\tpressTxtFilenameChar = NULL;\n\t}\n}\n\n// Call functions to write output files\nvoid MpsParticle::writeOutputFiles() {\n\t// writeProfAscii();\n\t// Write particle data (VTU files)\n\tif(vtuType == 0) {\n\t\tif(freeSurfWall == true) {\n\t\t\twriteVtuAsciiFreeSurface();\n\t\t}\n\t\telse {\n\t\t\twriteVtuAscii();\n\t\t}\n\t}\n\telse {\n\t\tif(freeSurfWall == true) {\n\t\t\twriteVtuBinaryFreeSurface();\n\t\t}\n\t\telse {\n\t\t\twriteVtuBinary();\n\t\t}\n\t}\n}\n\n// Write data. Format .prof\nvoid MpsParticle::writeProfAscii()\n{\n\tchar output_filename[256];\n\tsprintf(output_filename, \"output%05d.prof\",fileNumber);\n\tfp = fopen(output_filename, \"w\");\n\tfprintf(fp,\"%d\\n\",numParticles);\n\tfor(int i=0; i<numParticles; i++)\n\t{\n\t\tint a[2];\n\t\tdouble b[9];\n\t\ta[0]=i;\ta[1]=particleType[i];\n\t\tb[0]=pos[i*3];\tb[1]=pos[i*3+1];\tb[2]=pos[i*3+2];\n\t\tb[3]=vel[i*3];\tb[4]=vel[i*3+1];\tb[5]=vel[i*3+2];\n\t\tb[6]=press[i];\t\tb[7]=pressAverage[i]/iterOutput;\n\t\tb[8]=pndi[i];\n\t\tfprintf(fp,\" %d %d %lf %lf %lf %lf %lf %lf %lf %lf %lf\\n\",a[0],a[1],b[0],b[1],b[2],b[3],b[4],b[5],b[6],b[7],b[8]);\n\t\tpressAverage[i]=0.0;\n\t}\n\t// Close .prof file\n\tfclose(fp);\n}\n\n// https://stackoverflow.com/questions/105252\n// https://stackoverflow.com/questions/10913666/error-writing-binary-vtk-files\n// https://stackoverflow.com/questions/55829282/write-vtk-file-in-binary-format\ntemplate <typename T> void MpsParticle::SwapEnd(T& var)\n{\n\tchar* varArray = reinterpret_cast<char*>(&var);\n\tfor(long i = 0; i < static_cast<long>(sizeof(var)/2); i++)\n\t\tswap(varArray[sizeof(var) - 1 - i],varArray[i]);\n}\n\n// Write data. Format .vtu (Paraview)\nvoid MpsParticle::writeVtuBinary()\n{\n\tchar output_filename[256];\n\tchar *output_folder_char = new char[vtuOutputFoldername.length()+1];\n\tstrcpy (output_folder_char, vtuOutputFoldername.c_str());\n\t// output_folder_char now contains a c-string copy of vtuOutputFoldername\n\n\t//char output_folder_char[vtuOutputFoldername.size() + 1];\n    //strcpy(output_folder_char, vtuOutputFoldername.c_str());    // or pass &vtuOutputFoldername[0]\n\n    //string aux_filename = path + \"/mesh\" + mesh_IDstr + \"_\" + numstr + \".stl\";\n\n\tsprintf(output_filename, \"%s/output%05d.vtu\",output_folder_char,fileNumber);\n\n\tdelete[] output_folder_char;\n\toutput_folder_char = NULL;\n\n\t// BINARY FILE\n\tofstream file;\n\tfile.open(output_filename, ios::out | ios::binary);\n\n\tint nParticles = numParticles;\n\n\t// Header\n\t//file << \"<?xml version='1.0' encoding='UTF-8'?>\" << endl;\n\tfile << \"<VTKFile type='UnstructuredGrid' version='1.0' byte_order='LittleEndian' header_type='UInt64'>\" << endl;\n\tfile << \"  <UnstructuredGrid>\" << endl;\n\tfile << \"    <Piece NumberOfPoints='\" << nParticles << \"' NumberOfCells='\" << nParticles << \"'>\" << endl;\n\t\n\t// Point data\n\tfile << \"      <PointData>\" << endl;\n\tfile << \"        <DataArray type='Float32' Name='Velocity' NumberOfComponents='3' format='binary'>\" << endl;\n\tfor(size_t i=0; i<numParticles; i++)\n\t{\n\t\t{\n\t\t\tfloat ptx = (float)vel[i*3  ];\n\t\t\tfloat pty = (float)vel[i*3+1];\n\t\t\tfloat ptz = (float)vel[i*3+2];\n\n\t\t\tSwapEnd(ptx);\n\t\t\tSwapEnd(pty);\n\t\t\tSwapEnd(ptz);\n\n\t\t\tfile.write(reinterpret_cast<char*>(&ptx), sizeof(float));\n\t\t\tfile.write(reinterpret_cast<char*>(&pty), sizeof(float));\n\t\t\tfile.write(reinterpret_cast<char*>(&ptz), sizeof(float));\n\t\t}\n\t}\n\tfile << endl << \"        </DataArray>\" << endl;\n\t\n\tfile << \"        <DataArray type='Float32' Name='PreSmallsure' format='binary'>\" << endl;\n\tfor(size_t i=0; i<numParticles; i++)\n\t{\n\t\t{\n\t\t\tfloat ptv = (float)press[i];\n\t\t\tSwapEnd(ptv);\n\t\t\tfile.write(reinterpret_cast<char*>(&ptv), sizeof(float));\n\t\t}\n\t}\n\tfile << endl << \"        </DataArray>\" << endl;\n\t\n\tfile << \"<        DataArray type='Int32' Name='BC' format='binary'>\" << endl;\n\tfor(size_t i=0; i<numParticles; i++)\n\t{\n\t\t{\n\t\t\tint32_t type = particleBC[i];\n\t\t\tint type_i = static_cast<int>(type);\n\t\t\tSwapEnd(type_i);\n\t\t\tfile.write(reinterpret_cast<char*>(&type_i), sizeof(int));\n\t\t}\n\t}\n\tfile << endl << \"        </DataArray>\" << endl;\n\n\tif(outputPnd) \n\t{\n\t\tfile << \"        <DataArray type='Float32' Name='pnd' format='binary'>\" << endl;\n\t\tfor(size_t i=0; i<numParticles; i++)\n\t\t{\n\t\t\t{\n\t\t\t\tfloat ptv = pndi[i];\n\t\t\t\tSwapEnd(ptv);\n\t\t\t\tfile.write(reinterpret_cast<char*>(&ptv), sizeof(float));\n\t\t\t}\n\t\t}\n\t\tfile << endl << \"        </DataArray>\" << endl;\n\t\t\n\t\tfile << \"        <DataArray type='Float32' Name='pndSmall' format='binary'>\" << endl;\n\t\tfor(size_t i=0; i<numParticles; i++)\n\t\t{\n\t\t\t{\n\t\t\t\tfloat ptv = pndSmall[i];\n\t\t\t\tSwapEnd(ptv);\n\t\t\t\tfile.write(reinterpret_cast<char*>(&ptv), sizeof(float));\n\t\t\t}\n\t\t}\n\t\tfile << endl << \"        </DataArray>\" << endl;\n\t}\n\n\tif(outputNeigh)\n\t{\n\t\tfile << \"        <DataArray type='Int32' Name='nNeigh' format='binary'>\" << endl;\n\t\tfor(size_t i=0; i<numParticles; i++)\n\t\t{\n\t\t\t{\n\t\t\t\tint32_t type = numNeigh[i];\n\t\t\t\tint type_i = static_cast<int>(type);\n\t\t\t\tSwapEnd(type_i);\n\t\t\t\tfile.write(reinterpret_cast<char*>(&type_i), sizeof(int));\n\t\t\t}\n\t\t}\n\t\tfile << endl << \"        </DataArray>\" << endl;\n\t}\n\n\tfile << \"      </PointData>\" << endl;\n\n\t// Cell data\n\tfile << \"      <CellData>\" << endl;\n\tfile << \"      </CellData>\" << endl;\n\n\t//Points\n\tfile << \"      <Points>\" << endl;\n\tfile << \"        <DataArray type='Float32' Name='Position' NumberOfComponents='3' format='binary'>\" << endl;\n\tfor(size_t i=0; i<numParticles; i++)\n\t{\n\t\t{\n\t\t\tfloat ptx = (float)pos[i*3  ];\n\t\t\tfloat pty = (float)pos[i*3+1];\n\t\t\tfloat ptz = (float)pos[i*3+2];\n\n\t\t\tSwapEnd(ptx);\n\t\t\tSwapEnd(pty);\n\t\t\tSwapEnd(ptz);\n\n\t\t\tfile.write(reinterpret_cast<char*>(&ptx), sizeof(float));\n\t\t\tfile.write(reinterpret_cast<char*>(&pty), sizeof(float));\n\t\t\tfile.write(reinterpret_cast<char*>(&ptz), sizeof(float));\n\t\t}\n\t}\n\tfile << endl <<\"        </DataArray>\" << endl;\n\tfile << \"      </Points>\" << endl;\n\n\t// Cells\n\tfile << \"      <Cells>\" << endl;\n\tfile << \"        <DataArray type='Int64' Name='connectivity' format='binary'>\" << endl;\n\tfor(size_t i=0, ii=0; i<numParticles; i++)\n\t{\n\t\t{\n\t\t\tint64_t type = ii;\n\t\t\tint type_i = static_cast<int>(type);\n\t\t\tSwapEnd(type_i);\n\t\t\tfile.write(reinterpret_cast<char*>(&type_i), sizeof(int));\n\t\t\tii++;\n\t\t}\n\t}\n\tfile << endl << \"        </DataArray>\" << endl;\n\t\n\tfile << \"        <DataArray type='Int64' Name='offsets' format='binary'>\" << endl;\n\tfor(size_t i=0, ii=0; i<numParticles; i++)\n\t{\n\t\t{\n\t\t\tint64_t type = ii+1;\n\t\t\tint type_i = static_cast<int>(type);\n\t\t\tSwapEnd(type_i);\n\t\t\tfile.write(reinterpret_cast<char*>(&type_i), sizeof(int));\n\t\t\tii++;\n\t\t}\n\t}\n\tfile << endl << \"        </DataArray>\" << endl;\n\n\tfile << \"        <DataArray type='UInt8' Name='types' format='binary'>\" << endl;\n\tfor(size_t i=0; i<numParticles; i++)\n\t{\n\t\t{\n\t\t\tuint8_t type = 1;\n\t\t\tint type_i = static_cast<int>(type);\n\t\t\tSwapEnd(type_i);\n\t\t\tfile.write(reinterpret_cast<char*>(&type_i), sizeof(int));\n\t\t}\n\t}\n\tfile << endl << \"        </DataArray>\" << endl;\n\tfile << \"      </Cells>\" << endl;\n\tfile << \"    </Piece>\" << endl;\n\tfile << \"  </UnstructuredGrid>\" << endl;\n\tfile << \"</VTKFile>\" << endl;\n\n\tfile.close();\n}\n\n// Write data. Format .vtu (Paraview). Print only free-surface particles\nvoid MpsParticle::writeVtuBinaryFreeSurface()\n{\n\n\tchar output_filename[256];\n\tchar *output_folder_char = new char[vtuOutputFoldername.length()+1];\n\tstrcpy (output_folder_char, vtuOutputFoldername.c_str());\n\t// output_folder_char now contains a c-string copy of vtuOutputFoldername\n\n\tsprintf(output_filename, \"%s/output%05d.vtu\",output_folder_char,fileNumber);\n\n\tdelete[] output_folder_char;\n\toutput_folder_char = NULL;\n\n\tint nParticles = 0;\n\n\tfor(int i=0; i<numParticles; i++)\n\t{\n\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t\tnParticles++;\n\t}\n\n\t// BINARY FILE\n\tofstream file;\n\tfile.open(output_filename, ios::out | ios::binary);\n\n\t// Header\n\t//file << \"<?xml version='1.0' encoding='UTF-8'?>\" << endl;\n\tfile << \"<VTKFile type='UnstructuredGrid' version='1.0' byte_order='LittleEndian' header_type='UInt64'>\" << endl;\n\tfile << \"  <UnstructuredGrid>\" << endl;\n\tfile << \"    <Piece NumberOfPoints='\" << nParticles << \"' NumberOfCells='\" << nParticles << \"'>\" << endl;\n\t\n\t// Point data\n\tfile << \"      <PointData>\" << endl;\n\tfile << \"        <DataArray type='Float32' Name='Velocity' NumberOfComponents='3' format='binary'>\" << endl;\n\tfor(size_t i=0; i<numParticles; i++)\n\t{\n\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t{\n\t\t\tfloat ptx = (float)vel[i*3  ];\n\t\t\tfloat pty = (float)vel[i*3+1];\n\t\t\tfloat ptz = (float)vel[i*3+2];\n\n\t\t\tSwapEnd(ptx);\n\t\t\tSwapEnd(pty);\n\t\t\tSwapEnd(ptz);\n\n\t\t\tfile.write(reinterpret_cast<char*>(&ptx), sizeof(float));\n\t\t\tfile.write(reinterpret_cast<char*>(&pty), sizeof(float));\n\t\t\tfile.write(reinterpret_cast<char*>(&ptz), sizeof(float));\n\t\t}\n\t}\n\tfile << endl << \"        </DataArray>\" << endl;\n\t\n\tfile << \"        <DataArray type='Float32' Name='PreSmallsure' format='binary'>\" << endl;\n\tfor(size_t i=0; i<numParticles; i++)\n\t{\n\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t{\n\t\t\tfloat ptv = (float)press[i];\n\t\t\tSwapEnd(ptv);\n\t\t\tfile.write(reinterpret_cast<char*>(&ptv), sizeof(float));\n\t\t}\n\t}\n\tfile << endl << \"        </DataArray>\" << endl;\n\t\n\tfile << \"<        DataArray type='Int32' Name='BC' format='binary'>\" << endl;\n\tfor(size_t i=0; i<numParticles; i++)\n\t{\n\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t{\n\t\t\tint32_t type = particleBC[i];\n\t\t\tint type_i = static_cast<int>(type);\n\t\t\tSwapEnd(type_i);\n\t\t\tfile.write(reinterpret_cast<char*>(&type_i), sizeof(int));\n\t\t}\n\t}\n\tfile << endl << \"        </DataArray>\" << endl;\n\n\tif(outputPnd)\n\t{\n\t\tfile << \"        <DataArray type='Float32' Name='pnd' format='binary'>\" << endl;\n\t\tfor(size_t i=0; i<numParticles; i++)\n\t\t{\n\t\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t\t{\n\t\t\t\tfloat ptv = pndi[i];\n\t\t\t\tSwapEnd(ptv);\n\t\t\t\tfile.write(reinterpret_cast<char*>(&ptv), sizeof(float));\n\t\t\t}\n\t\t}\n\t\tfile << endl << \"        </DataArray>\" << endl;\n\t\t\n\t\tfile << \"        <DataArray type='Float32' Name='pndSmall' format='binary'>\" << endl;\n\t\tfor(size_t i=0; i<numParticles; i++)\n\t\t{\n\t\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t\t{\n\t\t\t\tfloat ptv = pndSmall[i];\n\t\t\t\tSwapEnd(ptv);\n\t\t\t\tfile.write(reinterpret_cast<char*>(&ptv), sizeof(float));\n\t\t\t}\n\t\t}\n\t\tfile << endl << \"        </DataArray>\" << endl;\n\t\t\n\t}\n\n\tif(outputNeigh)\n\t{\n\t\tfile << \"        <DataArray type='Int32' Name='nNeigh' format='binary'>\" << endl;\n\t\tfor(size_t i=0; i<numParticles; i++)\n\t\t{\n\t\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t\t{\n\t\t\t\tint32_t type = numNeigh[i];\n\t\t\t\tint type_i = static_cast<int>(type);\n\t\t\t\tSwapEnd(type_i);\n\t\t\t\tfile.write(reinterpret_cast<char*>(&type_i), sizeof(int));\n\t\t\t}\n\t\t}\n\t\tfile << endl << \"        </DataArray>\" << endl;\n\t\t\n\t}\n\n\tfile << \"      </PointData>\" << endl;\n\n\t// Cell data\n\tfile << \"      <CellData>\" << endl;\n\tfile << \"      </CellData>\" << endl;\n\n\t//Points\n\tfile << \"      <Points>\" << endl;\n\tfile << \"        <DataArray type='Float32' Name='Position' NumberOfComponents='3' format='binary'>\" << endl;\n\tfor(size_t i=0; i<numParticles; i++)\n\t{\n\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t{\n\t\t\tfloat ptx = (float)pos[i*3  ];\n\t\t\tfloat pty = (float)pos[i*3+1];\n\t\t\tfloat ptz = (float)pos[i*3+2];\n\n\t\t\tSwapEnd(ptx);\n\t\t\tSwapEnd(pty);\n\t\t\tSwapEnd(ptz);\n\n\t\t\tfile.write(reinterpret_cast<char*>(&ptx), sizeof(float));\n\t\t\tfile.write(reinterpret_cast<char*>(&pty), sizeof(float));\n\t\t\tfile.write(reinterpret_cast<char*>(&ptz), sizeof(float));\n\t\t}\n\t}\n\tfile << endl <<\"        </DataArray>\" << endl;\n\tfile << \"      </Points>\" << endl;\n\n\t// Cells\n\tfile << \"      <Cells>\" << endl;\n\tfile << \"        <DataArray type='Int64' Name='connectivity' format='binary'>\" << endl;\n\tfor(size_t i=0, ii=0; i<numParticles; i++)\n\t{\n\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t{\n\t\t\tint64_t type = ii;\n\t\t\tint type_i = static_cast<int>(type);\n\t\t\tSwapEnd(type_i);\n\t\t\tfile.write(reinterpret_cast<char*>(&type_i), sizeof(int));\n\t\t\tii++;\n\t\t}\n\t}\n\tfile << endl << \"        </DataArray>\" << endl;\n\t\n\tfile << \"        <DataArray type='Int64' Name='offsets' format='binary'>\" << endl;\n\tfor(size_t i=0, ii=0; i<numParticles; i++)\n\t{\n\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t{\n\t\t\tint64_t type = ii+1;\n\t\t\tint type_i = static_cast<int>(type);\n\t\t\tSwapEnd(type_i);\n\t\t\tfile.write(reinterpret_cast<char*>(&type_i), sizeof(int));\n\t\t\tii++;\n\t\t}\n\t}\n\tfile << endl << \"        </DataArray>\" << endl;\n\n\tfile << \"        <DataArray type='UInt8' Name='types' format='binary'>\" << endl;\n\tfor(size_t i=0; i<numParticles; i++)\n\t{\n\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t{\n\t\t\tuint8_t type = 1;\n\t\t\tint type_i = static_cast<int>(type);\n\t\t\tSwapEnd(type_i);\n\t\t\tfile.write(reinterpret_cast<char*>(&type_i), sizeof(int));\n\t\t}\n\t}\n\tfile << endl << \"        </DataArray>\" << endl;\n\tfile << \"      </Cells>\" << endl;\n\tfile << \"    </Piece>\" << endl;\n\tfile << \"  </UnstructuredGrid>\" << endl;\n\tfile << \"</VTKFile>\" << endl;\n\n\tfile.close();\n}\n\n// Write data. Format .vtu (Paraview)\nvoid MpsParticle::writeVtuAscii()\n{\n\tchar output_filename[256];\n\tchar *output_folder_char = new char[vtuOutputFoldername.length()+1];\n\tstrcpy (output_folder_char, vtuOutputFoldername.c_str());\n\t// output_folder_char now contains a c-string copy of vtuOutputFoldername\n\n\tsprintf(output_filename, \"%s/output%05d.vtu\",output_folder_char,fileNumber);\n\n\tdelete[] output_folder_char;\n\toutput_folder_char = NULL;\n\n\tint nParticles = numParticles;\n\n\t// ASCII FILE\n\tfp = fopen(output_filename, \"w\");\n\n\t// Header\n\tfprintf(fp,\"<?xml version='1.0' encoding='UTF-8'?>\\n\");\n\tfprintf(fp,\"<VTKFile xmlns='VTK' byte_order='LittleEndian' version='0.1' type='UnstructuredGrid'>\\n\");\n\tfprintf(fp,\"  <UnstructuredGrid>\\n\");\n\tfprintf(fp,\"    <Piece NumberOfCells='%d' NumberOfPoints='%d'>\\n\",nParticles,nParticles);\n\n\t// Points\n\tfprintf(fp,\"      <Points>\\n\");\n\tfprintf(fp,\"        <DataArray type='Float32' Name='Position' NumberOfComponents='3' format='ascii'>\\n          \");\n\tfor(int i=0; i<numParticles; i++)\n\t{\n\t\tfprintf(fp,\"%lf %lf %lf \",pos[i*3],pos[i*3+1],pos[i*3+2]);\n\t}\n\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\tfprintf(fp,\"      </Points>\\n\");\n\n\t// Point data\n\tfprintf(fp,\"      <PointData>\\n\");\n\tfprintf(fp,\"        <DataArray type='Float32' Name='Velocity' NumberOfComponents='3' format='ascii'>\\n\");\n\tfor(int i=0; i<numParticles; i++)\n\t{\n\t\t//double val=sqrt(vel[i*3]*vel[i*3]+vel[i*3+1]*vel[i*3+1]+vel[i*3+2]*vel[i*3+2]);\n\t\tfprintf(fp,\"%f %f %f \",(float)vel[i*3],(float)vel[i*3+1],(float)vel[i*3+2]);\n\t}\n\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t//fprintf(fp,\"        <DataArray type='Float32' Name='preSmallsave' format='ascii'>\\n\");\n\t//for(int i=0; i<numParticles; i++) {\tfprintf(fp,\"%f \",(float)(pressAverage[i]/iterOutput));}\n\t//fprintf(fp,\"\\n        </DataArray>\\n\");\n\tfprintf(fp,\"        <DataArray type='Float32' Name='pressure' format='ascii'>\\n\");\n\tfor(int i=0; i<numParticles; i++)\n\t{\n\t\tfprintf(fp,\"%f \",(float)press[i]);\n\t}\n\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\tfprintf(fp,\"        <DataArray type='Int32' Name='BC' format='ascii'>\\n\");\n\tfor(int i=0; i<numParticles; i++)\n\t{\n\t\tfprintf(fp,\"%d \",particleBC[i]);\n\t}\n\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\n\tif(outputPnd)\n\t{\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='pnd' format='ascii'>\\n\");\n\t\tfor(int i=0; i<numParticles; i++)\n\t\t{\n\t\t\tfprintf(fp,\"%f \",(float)pndi[i]);\n\t\t}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='pndSmall' format='ascii'>\\n\");\n\t\tfor(int i=0; i<numParticles; i++)\n\t\t{\n\t\t\tfprintf(fp,\"%f \",(float)pndSmall[i]);\n\t\t}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n//\t\tfprintf(fp,\"        <DataArray type='Float32' Name='pndk' format='ascii'>\\n\");\n//\t\tfor(int i=0; i<numParticles; i++)\n//\t\t{\n//\t\t\tfprintf(fp,\"%f \",(float)pndki[i]);\n//\t\t}\n//\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n//\t\tfprintf(fp,\"        <DataArray type='Float32' Name='pndsk' format='ascii'>\\n\");\n//\t\tfor(int i=0; i<numParticles; i++)\n//\t\t{\n//\t\t\tfprintf(fp,\"%f \",(float)pndski[i]);\n//\t\t}\n//\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t}\n\tif(outputNeigh) {\n\t\tfprintf(fp,\"        <DataArray type='Int32' Name='nNeigh' format='ascii'>\\n\");\n\t\tfor(int i=0; i<numParticles; i++)\n\t\t{\n\t\t\tfprintf(fp,\"%d \",numNeigh[i]);\n\t\t}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t}\n\n\tif(outputDeviation)\n\t{\n//\t\tfprintf(fp,\"        <DataArray type='Float32' Name='devSquare' format='ascii'>\\n\");\n//\t\tfor(int i=0; i<numParticles; i++) {\tfprintf(fp,\"%f \",(float)npcdDeviation2[i]);}\n//\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='npcdDeviation' NumberOfComponents='3' format='ascii'>\\n\");\n\t\tfor(int i=0; i<numParticles; i++)\n\t\t{\n\t\t\tfprintf(fp,\"%f %f %f \",(float)npcdDeviation[i*3],(float)npcdDeviation[i*3+1],(float)npcdDeviation[i*3+2]);\n\t\t}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='polygonNormal' NumberOfComponents='3' format='ascii'>\\n\");\n\t\tfor(int i=0; i<numParticles; i++)\n\t\t{\n\t\t\tfprintf(fp,\"%f %f %f \",(float)polygonNormal[i*3],(float)polygonNormal[i*3+1],(float)polygonNormal[i*3+2]);\n\t\t}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n//\t\tfprintf(fp,\"        <DataArray type='Float32' Name='deviationDotPolygonNormal' format='ascii'>\\n\");\n//\t\tfor(int i=0; i<numParticles; i++) {\tfprintf(fp,\"%f \",(float)deviationDotPolygonNormal[i]);}\n//\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t}\n\n\tif(outputConcentration)\n\t{\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='concentration' format='ascii'>\\n\");\n\t\tfor(int i=0; i<numParticles; i++)\n\t\t{\n\t\t\tfprintf(fp,\"%f \",(float)concentration[i]);\n\t\t}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='GradCi' NumberOfComponents='3' format='ascii'>\\n\");\n\t\tfor(int i=0; i<numParticles; i++)\n\t\t{\n\t\t\tfprintf(fp,\"%f %f %f \",(float)gradConcentration[i*3],(float)gradConcentration[i*3+1],(float)gradConcentration[i*3+2]);\n\t\t}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t}\n\t\n//\tfprintf(fp,\"        <DataArray type='Float32' Name='wallParticleForce1' NumberOfComponents='3' format='ascii'>\\n\");\n//\tfor(int i=0; i<numParticles; i++) {\n//\t\tfprintf(fp,\"%f %f %f \",(float)wallParticleForce1[i*3],(float)wallParticleForce1[i*3+1],(float)wallParticleForce1[i*3+2]);\n//\t}\n//\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\n//\tfprintf(fp,\"        <DataArray type='Float32' Name='wallParticleForce2' NumberOfComponents='3' format='ascii'>\\n\");\n//\tfor(int i=0; i<numParticles; i++) {\n//\t\tfprintf(fp,\"%f %f %f \",(float)wallParticleForce2[i*3],(float)wallParticleForce2[i*3+1],(float)wallParticleForce2[i*3+2]);\n//\t}\n//\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\n//\tfprintf(fp,\"        <DataArray type='Float32' Name='Normal' NumberOfComponents='3' format='ascii'>\\n\");\n//\tfor(int i=0; i<numParticles; i++) {\n//\t\tfprintf(fp,\"%f %f %f \",(float)normal[i*3],(float)normal[i*3+1],(float)normal[i*3+2]);\n//\t}\n//\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\n\tif(outputNonNewtonian)\n\t{\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='RHO' format='ascii'>\\n\");\n\t\t\tfor(int i=0; i<numParticles; i++) {\tfprintf(fp,\"%f \",(float)RHO[i]);}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='ConcVol' format='ascii'>\\n\");\n\t\t\tfor(int i=0; i<numParticles; i++) {\tfprintf(fp,\"%f \",(float)Cv[i]);}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='MEU' format='ascii'>\\n\");\n\t\t\tfor(int i=0; i<numParticles; i++) {\tfprintf(fp,\"%f \",(float)MEU[i]);}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='MEUy' format='ascii'>\\n\");\n\t\t\tfor(int i=0; i<numParticles; i++) {\tfprintf(fp,\"%f \",(float)MEU_Y[i]);}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='II' format='ascii'>\\n\");\n\t\t\tfor(int i=0; i<numParticles; i++) {\tfprintf(fp,\"%f \",(float)II[i]);}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\tfprintf(fp,\"        <DataArray type='Int32' Name='PTYPE' format='ascii'>\\n\");\n\t\t\tfor(int i=0; i<numParticles; i++) {\tfprintf(fp,\"%d \",PTYPE[i]);}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='p_smooth' format='ascii'>\\n\");\n\t\t\tfor(int i=0; i<numParticles; i++) {\tfprintf(fp,\"%f \",(float)p_smooth[i]);}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='Inertia' format='ascii'>\\n\");\n\t\t\tfor(int i=0; i<numParticles; i++) {\tfprintf(fp,\"%f \",(float)Inertia[i]);}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='Normal_Stress' format='ascii'>\\n\");\n\t\t\tfor(int i=0; i<numParticles; i++) {\tfprintf(fp,\"%f \",(float)p_rheo_new[i]);}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='VF' format='ascii'>\\n\");\n\t\t\tfor(int i=0; i<numParticles; i++) {\tfprintf(fp,\"%f \",(float)VF[i]);}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t}\n\t\n\tif(outputAuxiliar)\n\t{\n\t\tfprintf(fp,\"        <DataArray type='Int32' Name='ParticleType' format='ascii'>\\n\");\n\t\tfor(int i=0; i<numParticles; i++) {\n\t\t\tfprintf(fp,\"%d \",particleType[i]);\n\t\t}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\n//\t\tfprintf(fp,\"        <DataArray type='Float32' Name='mirrorParticlePos' NumberOfComponents='3' format='ascii'>\\n\");\n//\t\tfor(int i=0; i<numParticles; i++) {\n//\t\t\tfprintf(fp,\"%f %f %f \",(float)mirrorParticlePos[i*3],(float)mirrorParticlePos[i*3+1],(float)mirrorParticlePos[i*3+2]);\n//\t\t}\n//\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\n//\t\tfprintf(fp,\"        <DataArray type='Int32' Name='NearWall' format='ascii'>\\n\");\n//\t\tfor(int i=0; i<numParticles; i++) {\n//\t\t\tfprintf(fp,\"%d \",particleNearWall[i]);\n//\t\t}\n//\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\n\t\t//fprintf(fp,\"        <DataArray type='Float32' Name='Fwall' NumberOfComponents='3' format='ascii'>\\n\");\n\t\t//for(int i=0; i<numParticles; i++) {\n\t\t//\tfprintf(fp,\"%f %f %f \",(float)Fwall[i*3],(float)Fwall[i*3+1],(float)Fwall[i*3+2]);\n\t\t//}\n\t\t//fprintf(fp,\"\\n        </DataArray>\\n\");\n//\t\tfprintf(fp,\"        <DataArray type='Float32' Name='Fwall' NumberOfComponents='3' format='ascii'>\\n\");\n//\t\tfor(int i=0; i<numParticles; i++) {\n//\t\t\tfprintf(fp,\"%f %f %f \",(float)forceWall[i*3],(float)forceWall[i*3+1],(float)forceWall[i*3+2]);\n//\t\t}\n//\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n//\t\tfprintf(fp,\"        <DataArray type='Float32' Name='DIV' format='ascii'>\\n\");\n//\t\tfor(int i=0; i<numParticles; i++) {\tfprintf(fp,\"%f \",(float)velDivergence[i]);}\n//\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n//\t\tfprintf(fp,\"        <DataArray type='Float32' Name='Di' format='ascii'>\\n\");\n//\t\tfor(int i=0; i<numParticles; i++) {\tfprintf(fp,\"%f \",(float)diffusiveTerm[i]);}\n//\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\n\t\tfprintf(fp,\"        <DataArray type='Int32' Name='nearMeshType' format='ascii'>\\n\");\n\t\tfor(int i=0; i<numParticles; i++)\n\t\t{\n\t\t\tfprintf(fp,\"%d \",nearMeshType[i]);\n\t\t}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\n\t\t//fprintf(fp,\"        <DataArray type='Float32' Name='numNeighborsSurfaceParticles' format='ascii'>\\n\");\n\t\t//for(int i=0; i<numParticles; i++) {fprintf(fp,\"%f \",(float)numNeighborsSurfaceParticles[i]);}\n\t\t//fprintf(fp,\"\\n        </DataArray>\\n\");\n\t}\n\n\tfprintf(fp,\"      </PointData>\\n\");\n\n\t// Cells\n\tfprintf(fp,\"      <Cells>\\n\");\n\tfprintf(fp,\"        <DataArray type='Int32' Name='connectivity' format='ascii'>\\n\");\n\tfor(int i=0, ii = 0; i<numParticles; i++)\n\t{\n\t\tfprintf(fp,\"%d \",ii);\n\t\tii++;\n\t}\n\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\tfprintf(fp,\"        <DataArray type='Int32' Name='offsets' format='ascii'>\\n\");\n\tfor(int i=0, ii=0; i<numParticles; i++)\n\t{\n\t\tfprintf(fp,\"%d \",ii+1);\n\t\tii++;\n\t}\n\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\tfprintf(fp,\"        <DataArray type='UInt8' Name='types' format='ascii'>\\n\");\n\tfor(int i=0; i<numParticles; i++)\n\t{\n\t\tfprintf(fp,\"1 \");\n\t}\n\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\tfprintf(fp,\"      </Cells>\\n\");\n\tfprintf(fp,\"    </Piece>\\n\");\n\tfprintf(fp,\"  </UnstructuredGrid>\\n\");\n\tfprintf(fp,\"</VTKFile>\\n\");\n\n\tfclose(fp);\n}\n\n// Write data. Format .vtu (Paraview). Print only free-surface particles\nvoid MpsParticle::writeVtuAsciiFreeSurface()\n{\n\tchar output_filename[256];\n\tchar *output_folder_char = new char[vtuOutputFoldername.length()+1];\n\tstrcpy (output_folder_char, vtuOutputFoldername.c_str());\n\t// output_folder_char now contains a c-string copy of vtuOutputFoldername\n\n\tsprintf(output_filename, \"%s/output%05d.vtu\",output_folder_char,fileNumber);\n\n\tdelete[] output_folder_char;\n\toutput_folder_char = NULL;\n\n\t// ASCII FILE\n\tfp = fopen(output_filename, \"w\");\n\n\tint nParticles = 0;\n\tfor(int i=0; i<numParticles; i++)\n\t{\n\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t\tnParticles++;\n\t}\n\n\t// Header\n\tfprintf(fp,\"<?xml version='1.0' encoding='UTF-8'?>\\n\");\n\tfprintf(fp,\"<VTKFile xmlns='VTK' byte_order='LittleEndian' version='0.1' type='UnstructuredGrid'>\\n\");\n\tfprintf(fp,\"  <UnstructuredGrid>\\n\");\n\tfprintf(fp,\"    <Piece NumberOfCells='%d' NumberOfPoints='%d'>\\n\",nParticles,nParticles);\n\n\t// Points\n\tfprintf(fp,\"      <Points>\\n\");\n\tfprintf(fp,\"        <DataArray type='Float32' Name='Position' NumberOfComponents='3' format='ascii'>\\n          \");\n\tfor(int i=0; i<numParticles; i++)\n\t{\n\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t{\n\t\t\tfprintf(fp,\"%lf %lf %lf \",pos[i*3],pos[i*3+1],pos[i*3+2]);\n\t\t}\n\t}\n\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\tfprintf(fp,\"      </Points>\\n\");\n\n\t// Point data\n\tfprintf(fp,\"      <PointData>\\n\");\n\tfprintf(fp,\"        <DataArray type='Float32' Name='Velocity' NumberOfComponents='3' format='ascii'>\\n\");\n\tfor(int i=0; i<numParticles; i++)\n\t{\n\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t\tfprintf(fp,\"%f %f %f \",(float)vel[i*3],(float)vel[i*3+1],(float)vel[i*3+2]);\n\t}\n\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t//fprintf(fp,\"        <DataArray type='Float32' Name='preSmallsave' format='ascii'>\\n\");\n\t//for(int i=0; i<numParticles; i++) {\tfprintf(fp,\"%f \",(float)(pressAverage[i]/iterOutput));}\n\t//fprintf(fp,\"\\n        </DataArray>\\n\");\n\tfprintf(fp,\"        <DataArray type='Float32' Name='pressure' format='ascii'>\\n\");\n\tfor(int i=0; i<numParticles; i++)\n\t{\n\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t\tfprintf(fp,\"%f \",(float)press[i]);\n\t}\n\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\tfprintf(fp,\"        <DataArray type='Int32' Name='BC' format='ascii'>\\n\");\n\tfor(int i=0; i<numParticles; i++)\n\t{\n\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t\tfprintf(fp,\"%d \",particleBC[i]);\n\t}\n\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\n\tif(outputPnd)\n\t{\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='pnd' format='ascii'>\\n\");\n\t\tfor(int i=0; i<numParticles; i++)\n\t\t{\n\t\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t\t\tfprintf(fp,\"%f \",(float)pndi[i]);\n\t\t}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='pndSmall' format='ascii'>\\n\");\n\t\tfor(int i=0; i<numParticles; i++)\n\t\t{\n\t\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t\t\tfprintf(fp,\"%f \",(float)pndSmall[i]);\n\t\t}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t}\n\n\tif(outputNeigh)\n\t{\n\t\tfprintf(fp,\"        <DataArray type='Int32' Name='nNeigh' format='ascii'>\\n\");\n\t\tfor(int i=0; i<numParticles; i++)\n\t\t{\n\t\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t\t\tfprintf(fp,\"%d \",numNeigh[i]);\n\t\t}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t}\n\n\tif(outputDeviation)\n\t{\n//\t\tfprintf(fp,\"        <DataArray type='Float32' Name='devSquare' format='ascii'>\\n\");\n//\t\tfor(int i=0; i<numParticles; i++) {\tfprintf(fp,\"%f \",(float)npcdDeviation2[i]);}\n//\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='npcdDeviation' NumberOfComponents='3' format='ascii'>\\n\");\n\t\tfor(int i=0; i<numParticles; i++)\n\t\t{\n\t\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t\t\tfprintf(fp,\"%f %f %f \",(float)npcdDeviation[i*3],(float)npcdDeviation[i*3+1],(float)npcdDeviation[i*3+2]);\n\t\t}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='polygonNormal' NumberOfComponents='3' format='ascii'>\\n\");\n\t\tfor(int i=0; i<numParticles; i++)\n\t\t{\n\t\t\tfprintf(fp,\"%f %f %f \",(float)polygonNormal[i*3],(float)polygonNormal[i*3+1],(float)polygonNormal[i*3+2]);\n\t\t}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n//\t\tfprintf(fp,\"        <DataArray type='Float32' Name='deviationDotPolygonNormal' format='ascii'>\\n\");\n//\t\tfor(int i=0; i<numParticles; i++) {\tfprintf(fp,\"%f \",(float)deviationDotPolygonNormal[i]);}\n//\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t}\n\n\tif(outputConcentration)\n\t{\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='concentration' format='ascii'>\\n\");\n\t\tfor(int i=0; i<numParticles; i++)\n\t\t{\n\t\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t\t\tfprintf(fp,\"%f \",(float)concentration[i]);\n\t\t}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='GradCi' NumberOfComponents='3' format='ascii'>\\n\");\n\t\tfor(int i=0; i<numParticles; i++)\n\t\t{\n\t\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t\t\tfprintf(fp,\"%f %f %f \",(float)gradConcentration[i*3],(float)gradConcentration[i*3+1],(float)gradConcentration[i*3+2]);\n\t\t}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t}\n\t\n//\tfprintf(fp,\"        <DataArray type='Float32' Name='wallParticleForce1' NumberOfComponents='3' format='ascii'>\\n\");\n//\tfor(int i=0; i<numParticles; i++) {\n//\t\tfprintf(fp,\"%f %f %f \",(float)wallParticleForce1[i*3],(float)wallParticleForce1[i*3+1],(float)wallParticleForce1[i*3+2]);\n//\t}\n//\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\n//\tfprintf(fp,\"        <DataArray type='Float32' Name='wallParticleForce2' NumberOfComponents='3' format='ascii'>\\n\");\n//\tfor(int i=0; i<numParticles; i++) {\n//\t\tfprintf(fp,\"%f %f %f \",(float)wallParticleForce2[i*3],(float)wallParticleForce2[i*3+1],(float)wallParticleForce2[i*3+2]);\n//\t}\n//\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\n\tif(outputNonNewtonian)\n\t{\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='RHO' format='ascii'>\\n\");\n\t\t\tfor(int i=0; i<numParticles; i++) {\n\t\t\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t\t\t\tfprintf(fp,\"%f \",(float)RHO[i]);\n\t\t\t}\n\t\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='ConcVol' format='ascii'>\\n\");\n\t\t\tfor(int i=0; i<numParticles; i++) {\n\t\t\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t\t\t\tfprintf(fp,\"%f \",(float)Cv[i]);\n\t\t\t}\n\t\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='MEU' format='ascii'>\\n\");\n\t\t\tfor(int i=0; i<numParticles; i++) {\n\t\t\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t\t\t\tfprintf(fp,\"%f \",(float)MEU[i]);\n\t\t\t}\n\t\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='MEUy' format='ascii'>\\n\");\n\t\t\tfor(int i=0; i<numParticles; i++) {\n\t\t\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t\t\t\tfprintf(fp,\"%f \",(float)MEU_Y[i]);\n\t\t\t}\n\t\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='II' format='ascii'>\\n\");\n\t\t\tfor(int i=0; i<numParticles; i++) {\n\t\t\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t\t\t\tfprintf(fp,\"%f \",(float)II[i]);\n\t\t\t}\n\t\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\tfprintf(fp,\"        <DataArray type='Int32' Name='PTYPE' format='ascii'>\\n\");\n\t\t\tfor(int i=0; i<numParticles; i++) {\n\t\t\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t\t\t\tfprintf(fp,\"%d \",PTYPE[i]);\n\t\t\t}\n\t\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t\tfprintf(fp,\"        <DataArray type='Float32' Name='p_smooth' format='ascii'>\\n\");\n\t\tfor(int i=0; i<numParticles; i++) {\n\t\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t\t\tfprintf(fp,\"%f \",(float)p_smooth[i]);\n\t\t}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\t}\n\t\n\tif(outputAuxiliar)\n\t{\n\n//\t\tfprintf(fp,\"        <DataArray type='Int32' Name='ParticleType' format='ascii'>\\n\");\n//\t\tfor(int i=0; i<numParticles; i++) {\n//\t\t\tif(particleBC[i] == surface || particleType[i] == wall)\n//\t\t\t\tfprintf(fp,\"%d \",particleType[i]);\n//\t\t}\n//\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\n//\t\tfprintf(fp,\"        <DataArray type='Float32' Name='mirrorParticlePos' NumberOfComponents='3' format='ascii'>\\n\");\n//\t\tfor(int i=0; i<numParticles; i++) {\n//\t\t\tif(particleBC[i] == surface || particleType[i] == wall)\n//\t\t\tfprintf(fp,\"%f %f %f \",(float)mirrorParticlePos[i*3],(float)mirrorParticlePos[i*3+1],(float)mirrorParticlePos[i*3+2]);\n//\t\t}\n//\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\n//\t\tfprintf(fp,\"        <DataArray type='Int32' Name='NearWall' format='ascii'>\\n\");\n//\t\tfor(int i=0; i<numParticles; i++) {\n//\t\t\tif(particleBC[i] == surface || particleType[i] == wall)\n//\t\t\t\tfprintf(fp,\"%d \",particleNearWall[i]);\n//\t\t}\n//\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\n\t\t//fprintf(fp,\"        <DataArray type='Float32' Name='Fwall' NumberOfComponents='3' format='ascii'>\\n\");\n\t\t//for(int i=0; i<numParticles; i++) {\n\t\t//\tfprintf(fp,\"%f %f %f \",(float)Fwall[i*3],(float)Fwall[i*3+1],(float)Fwall[i*3+2]);\n\t\t//}\n\t\t//fprintf(fp,\"\\n        </DataArray>\\n\");\n//\t\tfprintf(fp,\"        <DataArray type='Float32' Name='Fwall' NumberOfComponents='3' format='ascii'>\\n\");\n//\t\tfor(int i=0; i<numParticles; i++) {\n//\t\t\tfprintf(fp,\"%f %f %f \",(float)forceWall[i*3],(float)forceWall[i*3+1],(float)forceWall[i*3+2]);\n//\t\t}\n//\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n//\t\tfprintf(fp,\"        <DataArray type='Float32' Name='DIV' format='ascii'>\\n\");\n//\t\tfor(int i=0; i<numParticles; i++) {\tfprintf(fp,\"%f \",(float)velDivergence[i]);}\n//\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n//\t\tfprintf(fp,\"        <DataArray type='Float32' Name='Di' format='ascii'>\\n\");\n//\t\tfor(int i=0; i<numParticles; i++) {\tfprintf(fp,\"%f \",(float)diffusiveTerm[i]);}\n//\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\n\t\tfprintf(fp,\"        <DataArray type='Int32' Name='nearMeshType' format='ascii'>\\n\");\n\t\tfor(int i=0; i<numParticles; i++)\n\t\t{\n\t\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t\t\tfprintf(fp,\"%d \",nearMeshType[i]);\n\t\t}\n\t\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\n\t\t//fprintf(fp,\"        <DataArray type='Float32' Name='numNeighborsSurfaceParticles' format='ascii'>\\n\");\n\t\t//for(int i=0; i<numParticles; i++) {fprintf(fp,\"%f \",(float)numNeighborsSurfaceParticles[i]);}\n\t\t//fprintf(fp,\"\\n        </DataArray>\\n\");\n\t\n\t}\n\n\tfprintf(fp,\"      </PointData>\\n\");\n\n\t// Cells\n\tfprintf(fp,\"      <Cells>\\n\");\n\tfprintf(fp,\"        <DataArray type='Int32' Name='connectivity' format='ascii'>\\n\");\n\tfor(int i=0, ii = 0; i<numParticles; i++)\n\t{\n\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t{\n\t\t\tfprintf(fp,\"%d \",ii);\n\t\t\tii++;\n\t\t}\n\t}\n\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\tfprintf(fp,\"        <DataArray type='Int32' Name='offsets' format='ascii'>\\n\");\n\tfor(int i=0, ii=0; i<numParticles; i++)\n\t{\n\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t{\n\t\t\tfprintf(fp,\"%d \",ii+1);\n\t\t\tii++;\n\t\t}\n\t}\n\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\tfprintf(fp,\"        <DataArray type='UInt8' Name='types' format='ascii'>\\n\");\n\tfor(int i=0; i<numParticles; i++)\n\t{\n\t\tif(particleBC[i] == surface || particleType[i] == wall)\n\t\t{\n\t\t\tfprintf(fp,\"1 \");\n\t\t}\n\t}\n\tfprintf(fp,\"\\n        </DataArray>\\n\");\n\tfprintf(fp,\"      </Cells>\\n\");\n\tfprintf(fp,\"    </Piece>\\n\");\n\tfprintf(fp,\"  </UnstructuredGrid>\\n\");\n\tfprintf(fp,\"</VTKFile>\\n\");\n\n\tfclose(fp);\n}\n\n// Write header for vtu files\nvoid MpsParticle::writePvd()\n{\n\tchar pvd_filename[256];\n\tchar *output_folder_char = new char[vtuOutputFoldername.length()+1];\n\tstrcpy (output_folder_char, vtuOutputFoldername.c_str());\n\t// output_folder_char now contains a c-string copy of vtuOutputFoldername\n\n\tstring vtuOutputFoldername_copy;\n\tvtuOutputFoldername_copy = vtuOutputFoldername;\n\tsize_t found = vtuOutputFoldername_copy.find('/');\n\tif(found != std::string::npos)\n\t{\n\t\tvtuOutputFoldername_copy.erase(0,found+1);\n\t}\n\n\tint mkdirOK;\n\t// Creating a directory\n#if defined(_WIN32) || defined(WIN32) || defined(__MINGW32__) || defined(__BORLANDC__)\n\tmkdirOK = _mkdir(output_folder_char);\n#else\n\tmkdirOK = mkdir(output_folder_char, 0777);\n#endif\n\n\tif(mkdirOK == -1) {\n\t\tprintf(\"Unable to create OUTPUT directory or it has already been created!\\n\");\n\t}\n\telse {\n\t\tprintf(\"Directory created.\\n\");\n\t}\n\n\tsprintf(pvd_filename, \"%s.pvd\",output_folder_char);\n\n\tfp = fopen(pvd_filename, \"w\");\n\tint nIter = ceil(timeSimulation/timeStep);\n\n\t//fprintf(fp,\"<VTKFile type=\"\"Collection\"\" version=\"\"0.1\"\" byte_order=\"\"LittleEndian\"\">\\n\");\n\tfprintf(fp,\"<VTKFile type='Collection' version='0.1' byte_order='LittleEndian'>\\n\");\n\tfprintf(fp,\"  <Collection>\\n\");\n\tint j = 0;\n\tfor(int i=0;i<nIter;i++)\n\t{\n\t\tif(i % iterOutput == 0)\n\t\t{\n\t\t\tdouble timePrint = timeStep*i;\n \t\t\tfprintf(fp,\"    <DataSet timestep='%.6f' group='A' part='0' file='%s/output%05d.vtu'/>\\n\",timePrint,vtuOutputFoldername_copy.c_str(),j);\n \t\t\tj++;\n\t\t}\n\t}\n\tfprintf(fp,\"  </Collection>\\n\");\n \tfprintf(fp,\"</VTKFile>\\n\");\n\n\tfclose(fp);\n\n\tdelete[] output_folder_char;\n\toutput_folder_char = NULL;\n}\n\n// Delete all files inside the simulation folder\nvoid MpsParticle::deleteDirectoryFiles()\n{\n\tfor (const auto& entry : std::experimental::filesystem::directory_iterator(vtuOutputFoldername)) \n\t\tstd::experimental::filesystem::remove_all(entry.path());\n}\n\n// Write vtk file with initial bucktes\nvoid MpsParticle::writeBuckets() {\n\n\tchar output_filename[256];\n\tchar *output_folder_char = new char[vtuOutputFoldername.length()+1];\n\tstrcpy (output_folder_char, vtuOutputFoldername.c_str());\n\t// output_folder_char now contains a c-string copy of vtuOutputFoldername\n\n\tsprintf(output_filename, \"%s/buckets.vtk\",output_folder_char);\n\n\tdelete[] output_folder_char;\n\toutput_folder_char = NULL;\n\n\t// ASCII FILE\n\tfp = fopen(output_filename, \"w\");\n\n\tint nDimX = numBucketsX + 1;\n\tint nDimY = numBucketsY + 1;\n\tint nDimZ = numBucketsZ;\n\tif(dim==3) {\n\t\tnDimZ += 1;\n\t}\n\tdouble originX = domainMinX;\n\tdouble originY = domainMinY;\n\tdouble originZ = domainMinZ;\n\tint numCells = numBucketsXYZ;\n\t\n\tfprintf(fp,\"# vtk DataFile Version 3.0\\n\");\n\tfprintf(fp,\"Initial Buckets\\n\");\n\tfprintf(fp,\"ASCII\\n\");\n\tfprintf(fp,\"DATASET STRUCTURED_POINTS\\n\");\n\tfprintf(fp,\"DIMENSIONS %d %d %d\\n\", nDimX, nDimY, nDimZ);\n\tfprintf(fp,\"ORIGIN %lf %lf %lf\\n\", domainMinX, domainMinY, domainMinZ);\n\tfprintf(fp,\"SPACING %lf %lf %lf\\n\", bucketSide, bucketSide, bucketSide);\n\tfprintf(fp,\"CELL_DATA %d\\n\", numBucketsXYZ);\n\tfprintf(fp,\"SCALARS density int 1\\n\");\n\tfprintf(fp,\"LOOKUP_TABLE default\\n\");\n\tfor(int i=0; i<numBucketsXYZ; i++)\n\t{\n\t\tfprintf(fp,\"1 \");\n\t}\n\n\tfclose(fp);\n}\n", "meta": {"hexsha": "b95e990367eb299f96181c25c6f641ad295dd5ee", "size": 358058, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MpsParticle.cpp", "max_stars_repo_name": "rubensamarojr/polymps", "max_stars_repo_head_hexsha": "bae8ee68962ac2de44ab7b7e5a70f25926eccc72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MpsParticle.cpp", "max_issues_repo_name": "rubensamarojr/polymps", "max_issues_repo_head_hexsha": "bae8ee68962ac2de44ab7b7e5a70f25926eccc72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MpsParticle.cpp", "max_forks_repo_name": "rubensamarojr/polymps", "max_forks_repo_head_hexsha": "bae8ee68962ac2de44ab7b7e5a70f25926eccc72", "max_forks_repo_licenses": ["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.7444777445, "max_line_length": 205, "alphanum_fraction": 0.614048562, "num_tokens": 138393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.29360728207179854}}
{"text": "/**\n * \\file dcs/testbed/anglano2014_fc2q_application_manager.hpp\n *\n * \\brief Application manager based on the work by (Anglano et al., 2014)\n *\n * This class implements the FC2Q fuzzy controller proposed in [1].\n *\n * References:\n * -# C. Anglano, M. Canonico and M. Guazzone,\n *    \"FC2Q: Exploiting Fuzzy Control in Server Consolidation for Cloud Applications with SLA Constraints,\"\n *    Concurrency and Computation: Practice and Experience, 27:4491–4514, 2015.\n *    doi:10.1002/cpe.3410\n * .\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright 2014   Marco Guazzone (marco.guazzone@gmail.com)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef DCS_TESTBED_ANGLANO2014_FC2Q_APPLICATION_MANAGER_HPP\n#define DCS_TESTBED_ANGLANO2014_FC2Q_APPLICATION_MANAGER_HPP\n\n\n#include <boost/smart_ptr.hpp>\n#include <boost/timer/timer.hpp>\n#include <cmath>\n#include <cstddef>\n#include <dcs/assert.hpp>\n#include <dcs/debug.hpp>\n#include <dcs/exception.hpp>\n#include <dcs/logging.hpp>\n#include <dcs/math/function/clamp.hpp>\n#include <dcs/math/traits/float.hpp>\n#include <dcs/testbed/application_performance_category.hpp>\n#include <dcs/testbed/base_application_manager.hpp>\n//#include <dcs/testbed/data_estimators.hpp>\n#include <dcs/testbed/data_smoothers.hpp>\n#include <dcs/testbed/virtual_machine_performance_category.hpp>\n#include <fl/Headers.h>\n#include <fstream>\n#include <limits>\n#include <map>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\n\nnamespace dcs { namespace testbed {\n\n/**\n * \\brief Application manager based on the work by (Anglano et al., 2014)\n *\n * This class implements the FC2Q fuzzy controller proposed in [1].\n *\n * References:\n * -# C. Anglano, M. Canonico and M. Guazzone,\n *    \"FC2Q: Exploiting Fuzzy Control in Server Consolidation for Cloud Applications with SLA Constraints,\"\n *    Concurrency and Computation: Practice and Experience, 27:4491–4514, 2015.\n *    doi:10.1002/cpe.3410\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n */\ntemplate <typename TraitsT>\nclass anglano2014_fc2q_application_manager: public base_application_manager<TraitsT>\n{\n\tprivate: typedef base_application_manager<TraitsT> base_type;\n\tpublic: typedef typename base_type::traits_type traits_type;\n\tpublic: typedef typename traits_type::real_type real_type;\n\tprivate: typedef typename base_type::app_type app_type;\n\tprivate: typedef typename base_type::app_pointer app_pointer;\n\tprivate: typedef typename base_type::vm_identifier_type vm_identifier_type;\n\tprivate: typedef typename app_type::sensor_type sensor_type;\n\tprivate: typedef typename app_type::sensor_pointer sensor_pointer;\n\tprivate: typedef ::std::map<application_performance_category,sensor_pointer> out_sensor_map;\n\tprivate: typedef ::std::map<virtual_machine_performance_category,::std::map<vm_identifier_type,sensor_pointer> > in_sensor_map;\n\n\n\tprivate: static const std::size_t control_warmup_size;\n\tprivate: static const float resource_share_lb_scale_factor;\n\n\tprivate: static const ::std::string rgain_fuzzy_var_name;\n\tprivate: static const ::std::string cres_fuzzy_var_name;\n\tprivate: static const ::std::string deltac_fuzzy_var_name;\n\n\n\tpublic: anglano2014_fc2q_application_manager()\n\t: beta_(0.9),\n\t  p_fuzzy_eng_(new fl::Engine()),\n\t  ctl_count_(0),\n\t  ctl_skip_count_(0),\n\t  ctl_fail_count_(0)\n\t{\n\t\tinit();\n\t}\n\n\tpublic: void smoothing_factor(real_type value)\n\t{\n\t\tbeta_ = value;\n\t}\n\n\tpublic: real_type smoothing_factor() const\n\t{\n\t\treturn beta_;\n\t}\n\n\tpublic: void export_data_to(::std::string const& fname)\n\t{\n\t\tdat_fname_ = fname;\n\t}\n\n\tprivate: void init()\n\t{\n\t\tDCS_DEBUG_ASSERT( p_fuzzy_eng_ );\n\n\t\tfl::InputVariable* p_iv = 0;\n\n\t\tp_iv = new fl::InputVariable();\n\t\tp_iv->setEnabled(true);\n\t\tp_iv->setName(cres_fuzzy_var_name);\n\t\tp_iv->setRange(0.0, 1.0);\n\t\tp_iv->addTerm(new fl::Ramp(\"LOW\", 0.30, 0.00));\n\t\tp_iv->addTerm(new fl::Triangle(\"FINE\", 0.10, 0.25, 0.40));\n\t\tp_iv->addTerm(new fl::Ramp(\"HIGH\", 0.30, 1.00));\n\t\tp_fuzzy_eng_->addInputVariable(p_iv);\n\n\t\tp_iv = new fl::InputVariable();\n\t\tp_iv->setEnabled(true);\n\t\tp_iv->setName(rgain_fuzzy_var_name);\n\t\tp_iv->setRange(-1, 1);\n\t\tp_iv->addTerm(new fl::Ramp(\"LOW\", 0.20, -0.40));\n\t\tp_iv->addTerm(new fl::Triangle(\"FINE\", 0.10, 0.20, 0.30));\n\t\tp_iv->addTerm(new fl::Ramp(\"HIGH\", 0.30, 1.00));\n\t\tp_fuzzy_eng_->addInputVariable(p_iv);\n\n\t\tfl::OutputVariable* p_ov = 0;\n\t\tp_ov = new fl::OutputVariable();\n\t\tp_ov->setEnabled(true);\n\t\tp_ov->setName(deltac_fuzzy_var_name);\n\t\tp_ov->setRange(-1, 1);\n\t\t//p_ov->setLockValueInRange(true);\n\t\tp_ov->fuzzyOutput()->setAccumulation(new fl::AlgebraicSum());\n\t\tp_ov->setDefuzzifier(new fl::Centroid());\n\t\tp_ov->setDefaultValue(fl::nan);\n\t\tp_ov->setPreviousValue(false);\n\t\tp_ov->addTerm(new fl::Triangle(\"BDW\", -1.00, -0.55, -0.10));\n\t\tp_ov->addTerm(new fl::Triangle(\"DWN\", -0.20, -0.125, -0.05));\n\t\tp_ov->addTerm(new fl::Triangle(\"STY\", -0.10, 0.0, 0.10));\n\t\tp_ov->addTerm(new fl::Triangle(\"UP\", 0.05, 0.125, 0.20));\n\t\tp_ov->addTerm(new fl::Triangle(\"BUP\", 0.10, 0.55, 1.00));\n\t\tp_fuzzy_eng_->addOutputVariable(p_ov);\n\n\t\tfl::RuleBlock* p_rules = new fl::RuleBlock();\n\t\tp_rules->setEnabled(true);\n\t\tp_rules->setConjunction(new fl::Minimum());\n\t\tp_rules->setDisjunction(new fl::Maximum());\n\t\tp_rules->setImplication(new fl::AlgebraicProduct());\n\t\tp_rules->addRule(fl::Rule::parse(\"if \" + cres_fuzzy_var_name + \" is LOW and \" + rgain_fuzzy_var_name + \" is LOW then \" + deltac_fuzzy_var_name + \" is BUP\", p_fuzzy_eng_.get()));\n\t\tp_rules->addRule(fl::Rule::parse(\"if \" + cres_fuzzy_var_name + \" is LOW and \" + rgain_fuzzy_var_name + \" is FINE then \" + deltac_fuzzy_var_name + \" is UP\", p_fuzzy_eng_.get()));\n\t\tp_rules->addRule(fl::Rule::parse(\"if \" + cres_fuzzy_var_name + \" is LOW and \" + rgain_fuzzy_var_name + \" is HIGH then \" + deltac_fuzzy_var_name + \" is UP\", p_fuzzy_eng_.get()));\n\t\tp_rules->addRule(fl::Rule::parse(\"if \" + cres_fuzzy_var_name + \" is FINE and \" + rgain_fuzzy_var_name + \" is LOW then \" + deltac_fuzzy_var_name + \" is UP\", p_fuzzy_eng_.get()));\n\t\tp_rules->addRule(fl::Rule::parse(\"if \" + cres_fuzzy_var_name + \" is FINE and \" + rgain_fuzzy_var_name + \" is FINE then \" + deltac_fuzzy_var_name + \" is STY\", p_fuzzy_eng_.get()));\n\t\tp_rules->addRule(fl::Rule::parse(\"if \" + cres_fuzzy_var_name + \" is FINE and \" + rgain_fuzzy_var_name + \" is HIGH then \" + deltac_fuzzy_var_name + \" is DWN\", p_fuzzy_eng_.get()));\n\t\tp_rules->addRule(fl::Rule::parse(\"if \" + cres_fuzzy_var_name + \" is HIGH and \" + rgain_fuzzy_var_name + \" is LOW then \" + deltac_fuzzy_var_name + \" is STY\", p_fuzzy_eng_.get()));\n\t\tp_rules->addRule(fl::Rule::parse(\"if \" + cres_fuzzy_var_name + \" is HIGH and \" + rgain_fuzzy_var_name + \" is FINE then \" + deltac_fuzzy_var_name + \" is DWN\", p_fuzzy_eng_.get()));\n\t\tp_rules->addRule(fl::Rule::parse(\"if \" + cres_fuzzy_var_name + \" is HIGH and \" + rgain_fuzzy_var_name + \" is HIGH then \" + deltac_fuzzy_var_name + \" is BDW\", p_fuzzy_eng_.get()));\n\t\tp_fuzzy_eng_->addRuleBlock(p_rules);\n\t}\n\n\tprivate: void do_reset()\n\t{\n\t\ttypedef typename base_type::target_value_map::const_iterator target_iterator;\n\t\ttypedef typename app_type::vm_pointer vm_pointer;\n\n\t\tconst ::std::vector<vm_pointer> vms = this->app().vms();\n\t\tconst ::std::size_t nvms = this->app().num_vms();\n\n\t\t// Reset output sensors\n\t\tout_sensors_.clear();\n\t\tfor (target_iterator tgt_it = this->target_values().begin(),\n\t\t\t\t\t\t\t tgt_end_it = this->target_values().end();\n\t\t\t tgt_it != tgt_end_it;\n\t\t\t ++tgt_it)\n\t\t{\n\t\t\tconst application_performance_category cat = tgt_it->first;\n\n\t\t\tout_sensors_[cat] = this->app().sensor(cat);\n\t\t}\n\n\t\t// Reset input sensors\n\t\tin_sensors_.clear();\n\t\tfor (::std::size_t i = 0; i < nvms; ++i)\n\t\t{\n\t\t\tvm_pointer p_vm = vms[i];\n\n\t\t\tin_sensors_[cpu_util_virtual_machine_performance][p_vm->id()] = p_vm->sensor(cpu_util_virtual_machine_performance);\n\t\t\tin_sensors_[memory_util_virtual_machine_performance][p_vm->id()] = p_vm->sensor(memory_util_virtual_machine_performance);\n\t\t}\n\n\t\t// Reset counters\n\t\tctl_count_ = ctl_skip_count_\n\t\t\t\t   = ctl_fail_count_\n\t\t\t\t   = 0;\n\n\t\t// Reset fuzzy controller\n\t\tp_fuzzy_eng_->restart();\n\n\t\t// Reset resource utilization smoothers\n\t\tfor (::std::size_t i = 0; i < nvms; ++i)\n\t\t{\n\t\t\tthis->data_smoother(cpu_util_virtual_machine_performance, vms[i]->id(), ::boost::make_shared< testbed::brown_single_exponential_smoother<real_type> >(beta_));\n\t\t\tthis->data_smoother(memory_util_virtual_machine_performance, vms[i]->id(), ::boost::make_shared< testbed::brown_single_exponential_smoother<real_type> >(beta_));\n\t\t}\n\n\t\t// Reset output data file\n\t\tif (p_dat_ofs_ && p_dat_ofs_->is_open())\n\t\t{\n\t\t\tp_dat_ofs_->close();\n\t\t}\n\t\tp_dat_ofs_.reset();\n\t\tif (!dat_fname_.empty())\n\t\t{\n\t\t\tp_dat_ofs_ = ::boost::make_shared< ::std::ofstream >(dat_fname_.c_str());\n\t\t\tif (!p_dat_ofs_->good())\n\t\t\t{\n\t\t\t\t::std::ostringstream oss;\n\t\t\t\toss << \"Cannot open output data file '\" << dat_fname_ << \"'\";\n\n\t\t\t\tDCS_EXCEPTION_THROW(::std::runtime_error, oss.str());\n\t\t\t}\n\n\t\t\t*p_dat_ofs_ << \"\\\"ts\\\"\";\n\n\t\t\tfor (::std::size_t i = 0; i < nvms; ++i)\n\t\t\t{\n\t\t\t\t*p_dat_ofs_ << \",\\\"CPUCap_{\" << vms[i]->id() << \"}(k)\\\",\\\"CPUShare_{\" << vms[i]->id() << \"}(k)\\\"\";\n\t\t\t}\n\t\t\tfor (::std::size_t i = 0; i < nvms; ++i)\n\t\t\t{\n\t\t\t\t*p_dat_ofs_ << \",\\\"CPUShare_{\" << vms[i]->id() << \"}(k-1)\\\"\";\n\t\t\t}\n\t\t\tfor (::std::size_t i = 0; i < nvms; ++i)\n\t\t\t{\n\t\t\t\t*p_dat_ofs_ << \",\\\"CPUUtil_{\" << vms[i]->id() << \"}(k-1)\\\",\\\"MemUtil_{\" << vms[i]->id() << \"}(k-1)\\\"\";\n\t\t\t}\n\t\t\tfor (target_iterator tgt_it = this->target_values().begin(),\n\t\t\t\t\t\t\t \t tgt_end_it = this->target_values().end();\n\t\t\t\t tgt_it != tgt_end_it;\n\t\t\t\t ++tgt_it)\n\t\t\t{\n\t\t\t\tconst application_performance_category cat = tgt_it->first;\n\n\t\t\t\t*p_dat_ofs_ << \",\\\"ReferenceOutput_{\" << cat << \"}(k-1)\\\",\\\"MeasuredOutput_{\" << cat << \"}(k-1)\\\",\\\"RelativeOutputError_{\" << cat << \"}(k-1)\\\"\";\n\t\t\t}\n\t\t\tfor (::std::size_t i = 0; i < nvms; ++i)\n\t\t\t{\n\t\t\t\t*p_dat_ofs_ << \",\\\"Cres_{\" << vms[i]->id() << \"}(k-1)\\\"\";\n\t\t\t}\n\t\t\tfor (::std::size_t i = 0; i < nvms; ++i)\n\t\t\t{\n\t\t\t\t*p_dat_ofs_ << \",\\\"DeltaC_{\" << vms[i]->id() << \"}(k)\\\"\";\n\t\t\t}\n\t\t\t//NOTE: C(k) may differ from CPUShare(k) for several reasons:\n\t\t\t// - There is a latency in setting the new share (e.g., this is usually not the case of CPU but of other resources like the memory, whereby the new share is not immediately set but the memory is (de)allocated incrementally)\n\t\t\t// - There is another component between this controller and physical resources that may change the wanted share (e.g., if a physical resource is shared among different VMs, there can be a component that try to allocate the contented physical resource fairly).\n\t\t\tfor (std::size_t i = 0; i < nvms; ++i)\n\t\t\t{\n\t\t\t\t*p_dat_ofs_ << \",\\\"C_{\" << vms[i]->id() << \"}(k)\\\"\";\n\t\t\t}\n\t\t\t*p_dat_ofs_ << \",\\\"# Controls\\\",\\\"# Skip Controls\\\",\\\"# Fail Controls\\\"\";\n            *p_dat_ofs_ << \",\\\"Elapsed Time\\\"\";\n\t\t\t*p_dat_ofs_ << ::std::endl;\n\t\t}\n\t}\n\n\tprivate: void do_sample()\n\t{\n\t\ttypedef typename in_sensor_map::const_iterator in_sensor_iterator;\n\t\ttypedef typename out_sensor_map::const_iterator out_sensor_iterator;\n\t\ttypedef ::std::vector<typename sensor_type::observation_type> obs_container;\n\t\ttypedef typename obs_container::const_iterator obs_iterator;\n\n\t\tDCS_DEBUG_TRACE(\"(\" << this << \") BEGIN Do SAMPLE - Count: \" << ctl_count_ << \"/\" << ctl_skip_count_ << \"/\" << ctl_fail_count_);\n\n\t\t// Collect input values\n\t\tfor (in_sensor_iterator in_sens_it = in_sensors_.begin(),\n\t\t\t\t\t\t\t\tin_sens_end_it = in_sensors_.end();\n\t\t\t in_sens_it != in_sens_end_it;\n\t\t\t ++in_sens_it)\n\t\t{\n\t\t\tconst virtual_machine_performance_category cat = in_sens_it->first;\n\n\t\t\tfor (typename in_sensor_map::mapped_type::const_iterator vm_it = in_sens_it->second.begin(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t vm_end_it = in_sens_it->second.end();\n\t\t\t\t vm_it != vm_end_it;\n\t\t\t\t ++vm_it)\n\t\t\t{\n\t\t\t\tconst vm_identifier_type vm_id = vm_it->first;\n\t\t\t\tsensor_pointer p_sens = vm_it->second;\n\n\t\t\t\t// check: p_sens != null\n\t\t\t\tDCS_DEBUG_ASSERT( p_sens );\n\n\t\t\t\tp_sens->sense();\n\t\t\t\tif (p_sens->has_observations())\n\t\t\t\t{\n\t\t\t\t\tconst obs_container obs = p_sens->observations();\n\t\t\t\t\tconst obs_iterator end_it = obs.end();\n\t\t\t\t\tfor (obs_iterator it = obs.begin();\n\t\t\t\t\t\t it != end_it;\n\t\t\t\t\t\t ++it)\n\t\t\t\t\t{\n\t\t\t\t\t\t//this->data_estimator(cat, vm_id).collect(it->value());\n\t\t\t\t\t\tthis->data_smoother(cat, vm_id).smooth(it->value());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Collect output values\n\t\tfor (out_sensor_iterator out_sens_it = out_sensors_.begin(),\n\t\t\t\t\t\t\t\t out_sens_end_it = out_sensors_.end();\n\t\t\t out_sens_it != out_sens_end_it;\n\t\t\t ++out_sens_it)\n\t\t{\n\t\t\tconst application_performance_category cat = out_sens_it->first;\n\n\t\t\tsensor_pointer p_sens = out_sens_it->second;\n\n\t\t\t// check: p_sens != null\n\t\t\tDCS_DEBUG_ASSERT( p_sens );\n\n\t\t\tp_sens->sense();\n\t\t\tif (p_sens->has_observations())\n\t\t\t{\n\t\t\t\tconst obs_container obs = p_sens->observations();\n\t\t\t\tconst obs_iterator end_it = obs.end();\n\t\t\t\tfor (obs_iterator it = obs.begin();\n\t\t\t\t\t it != end_it;\n\t\t\t\t\t ++it)\n\t\t\t\t{\n\t\t\t\t\tthis->data_estimator(cat).collect(it->value());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tDCS_DEBUG_TRACE(\"(\" << this << \") END Do SAMPLE - Count: \" << ctl_count_ << \"/\" << ctl_skip_count_ << \"/\" << ctl_fail_count_);\n\t}\n\n\tprivate: void do_control()\n\t{\n\t\ttypedef typename base_type::target_value_map::const_iterator target_iterator;\n\t\ttypedef typename app_type::vm_pointer vm_pointer;\n\n\t\tDCS_DEBUG_TRACE(\"(\" << this << \") BEGIN Do CONTROL - Count: \" << ctl_count_ << \"/\" << ctl_skip_count_ << \"/\" << ctl_fail_count_);\n\n        boost::timer::cpu_timer cpu_timer;\n\n\t\t++ctl_count_;\n\n\t\tbool skip_ctl = false;\n\n\t\tstd::vector<real_type> old_shares;\n\t\tstd::vector<real_type> new_shares;\n\t\tstd::vector<real_type> deltacs;\n\t\tstd::vector<real_type> cress;\n\t\tstd::vector<real_type> cutils;\n\t\tstd::map<application_performance_category,real_type> rgains;\n\n\t\t::std::vector<vm_pointer> vms = this->app().vms();\n\t\tconst ::std::size_t nvms = vms.size();\n\n\t\tfor (::std::size_t i = 0; i < nvms; ++i)\n\t\t{\n\t\t\tconst virtual_machine_performance_category cat = cpu_util_virtual_machine_performance;\n\t\t\tconst vm_pointer p_vm = vms[i];\n\n//\t\t\tif (this->data_estimator(cat, vms[i]->id()).count() > 0)\n//\t\t\t{\n//\t\t\t\t//const real_type uh = this->data_estimator(cat, p_vm->id()).estimate();\n//\t\t\t\tconst real_type uh = this->data_smoother(cat, p_vm->id()).forecast(0);\n//\t\t\t\tconst real_type c = p_vm->cpu_share();\n//\n//\t\t\t\tcress[cat].push_back(c-uh);\n//\t\t\t}\n//\t\t\telse\n//\t\t\t{\n//\t\t\t\t// No observation collected during the last control interval\n//\t\t\t\tDCS_DEBUG_TRACE(\"No input observation collected during the last control interval -> Skip control\");\n//\t\t\t\tskip_ctl = true;\n//\t\t\t\tbreak;\n//\t\t\t}\n\t\t\tconst real_type uh = this->data_smoother(cat, p_vm->id()).forecast(0);\n\t\t\tconst real_type c = p_vm->cpu_share();\n\t\t\tconst real_type cres = c-uh;\n\n\t\t\tcress.push_back(cres);\n\t\t\told_shares.push_back(c);\n\t\t\tcutils.push_back(uh);\nDCS_DEBUG_TRACE(\"VM \" << p_vm->id() << \" - Performance Category: \" << cat << \" - Uhat(k): \" << uh << \" - C(k): \" << c << \" -> Cres(k+1): \" << cres << \" (Relative Cres(k+1): \" << cres/c << \")\");//XXX\n\t\t}\n\n\t\tif (!skip_ctl)\n\t\t{\n\t\t\tfor (target_iterator tgt_it = this->target_values().begin(),\n\t\t\t\t\t\t\t \t tgt_end_it = this->target_values().end();\n\t\t\t\t tgt_it != tgt_end_it;\n\t\t\t\t ++tgt_it)\n\t\t\t{\n\t\t\t\tconst application_performance_category cat(tgt_it->first);\n\n\t\t\t\t// Compute a summary statistics of collected observation\n\t\t\t\tif (this->data_estimator(cat).count() > 0)\n\t\t\t\t{\n\t\t\t\t\tconst real_type yh = this->data_estimator(cat).estimate();\n\t\t\t\t\tconst real_type yr = this->target_value(cat);\n\n\t\t\t\t\tswitch (cat)\n\t\t\t\t\t{\n\t\t\t\t\t\tcase response_time_application_performance:\n\t\t\t\t\t\t\trgains[cat] = (yr-yh)/yr;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase throughput_application_performance:\n\t\t\t\t\t\t\trgains[cat] = (yh-yr)/yr;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\nDCS_DEBUG_TRACE(\"APP Performance Category: \" << cat << \" - Yhat(k): \" << yh << \" - R: \" << yr << \" -> Rgain(k+1): \" << rgains.at(cat));//XXX\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// No observation collected during the last control interval\n\t\t\t\t\tDCS_DEBUG_TRACE(\"No output observation collected during the last control interval -> Skip control\");\n\t\t\t\t\tskip_ctl = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n#ifdef DCSXX_TESTBED_EXP_APP_MGR_RESET_ESTIMATION_EVERY_INTERVAL\n\t\t\t\tthis->data_estimator(cat).reset();\n#endif // DCSXX_TESTBED_EXP_APP_MGR_RESET_ESTIMATION_EVERY_INTERVAL\n\t\t\t}\n\t\t}\n\n\t\t// Skip control until we see enough observations.\n\t\t// This should give enough time to let the estimated performance metric\n\t\t// (e.g., 95th percentile of response time) stabilize\n\t\tif (ctl_count_ <= control_warmup_size)\n\t\t{\n\t\t\tskip_ctl = true;\n\t\t}\n\n        if (!skip_ctl)\n        {\n\t\t\t//FIXME: actually we only handle SISO systems\n\t\t\tDCS_ASSERT(rgains.size() == 1,\n\t\t\t\t\t   DCS_EXCEPTION_THROW(::std::runtime_error,\n\t\t\t\t\t   \"Only SISO system are currently managed\"));\n\n\t\t\t// Perform fuzzy control\n\t\t\tbool ok = false;\n\t\t\t//::std::vector<real_type> deltacs(nvms);\n\t\t\ttry\n\t\t\t{\n\t\t\t\tfor (::std::size_t i = 0; i < nvms; ++i)\n\t\t\t\t{\n\t\t\t\t\tconst real_type cres = cress[i];\n\t\t\t\t\tconst real_type cutil = cutils[i];\n\t\t\t\t\tconst real_type rgain = rgains.begin()->second;\n\t\t\t\t\tconst real_type old_share = old_shares[i];\n\t\t\t\t\tconst real_type deltac_lb = std::min(1.0, cutil*resource_share_lb_scale_factor)-old_share;\n\t\t\t\t\tconst real_type deltac_ub = std::max(0.0, 1-old_share);\n\n\t\t\t\t\tp_fuzzy_eng_->setInputValue(cres_fuzzy_var_name, cres/old_share);\n\t\t\t\t\tp_fuzzy_eng_->setInputValue(rgain_fuzzy_var_name, rgain);\n\t\t\t\t\t//p_fuzzy_eng_->getOutputVariable(deltac_fuzzy_var_name)->setMinimum(-cres);\n\t\t\t\t\t//p_fuzzy_eng_->getOutputVariable(deltac_fuzzy_var_name)->setMaximum(1-old_shares[i]);\n\n\t\t\t\t\tp_fuzzy_eng_->process();\n\n\t\t\t\t\tconst real_type fuzzy_deltac = p_fuzzy_eng_->getOutputValue(deltac_fuzzy_var_name);\n\n\t\t\t\t\treal_type deltac = fuzzy_deltac;\n\t\t\t\t\tdeltac = dcs::math::clamp(deltac, deltac_lb, deltac_ub);\n\n\t\t\t\t\tdeltacs.push_back(deltac);\nDCS_DEBUG_TRACE(\"VM \" << vms[i]->id() << \" -> DeltaC(k+1): \" << deltacs.at(i) << \" (computed: \" << fuzzy_deltac << \", lb: \" << deltac_lb << \", ub: \" << deltac_ub << \")\");//XXX\n\t\t\t\t}\n\n\t\t\t\tok = true;\n\t\t\t}\n\t\t\tcatch (fl::Exception const& fe)\n\t\t\t{\n\t\t\t\tDCS_DEBUG_TRACE( \"Caught exception: \" << fe.what() );\n\n\t\t\t\t::std::ostringstream oss;\n\t\t\t\toss << \"Unable to compute optimal control: \" << fe.what();\n\t\t\t\t::dcs::log_warn(DCS_LOGGING_AT, oss.str());\n\t\t\t}\n\t\t\tcatch (::std::exception const& e)\n\t\t\t{\n\t\t\t\tDCS_DEBUG_TRACE( \"Caught exception: \" << e.what() );\n\n\t\t\t\t::std::ostringstream oss;\n\t\t\t\toss << \"Unable to compute optimal control: \" << e.what();\n\t\t\t\t::dcs::log_warn(DCS_LOGGING_AT, oss.str());\n\t\t\t}\n\n\t\t\t// Apply fuzzy control results\n\t\t\tif (ok)\n\t\t\t{\n\t\t\t\tfor (::std::size_t i = 0; i < nvms; ++i)\n\t\t\t\t{\n\t\t\t\t\tvm_pointer p_vm = vms[i];\n\n\t\t\t\t\tconst real_type old_share = p_vm->cpu_share();\n\t\t\t\t\tconst real_type new_share = ::std::max(::std::min(old_share+deltacs[i], 1.0), 0.0);\n\n\t\t\t\t\tDCS_DEBUG_TRACE(\"VM '\" << p_vm->id() << \"' - old-share: \" << old_share << \" - new-share: \" << new_share);\n\n\t\t\t\t\tif (::std::isfinite(new_share) && !::dcs::math::float_traits<real_type>::essentially_equal(old_share, new_share))\n\t\t\t\t\t{\n\t\t\t\t\t\tp_vm->cpu_share(new_share);\nDCS_DEBUG_TRACE(\"VM \" << vms[i]->id() << \" -> C(k+1): \" << new_share);//XXX\n\n\t\t\t\t\t\tnew_shares.push_back(new_share);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\nDCS_DEBUG_TRACE(\"VM \" << vms[i]->id() << \" -> C(k+1) not set!\");//XXX\n\n\t\t\t\t\t\tnew_shares.push_back(old_share);\n\t\t\t\t\t}\n\t\t\t\t}\nDCS_DEBUG_TRACE(\"Control applied\");//XXX\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t++ctl_fail_count_;\n\n\t\t\t\t::std::ostringstream oss;\n\t\t\t\toss << \"Control not applied: failed to solve the control problem\";\n\t\t\t\t::dcs::log_warn(DCS_LOGGING_AT, oss.str());\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t++ctl_skip_count_;\n\t\t}\n\n        cpu_timer.stop();\n\n\t\t// Export to file\n\t\tif (p_dat_ofs_)\n\t\t{\n\t\t\tif (new_shares.size() == 0)\n\t\t\t{\n\t\t\t\tfor (::std::size_t i = 0; i < nvms; ++i)\n\t\t\t\t{\n\t\t\t\t\tconst vm_pointer p_vm = vms[i];\n\n\t\t\t\t\t// check: p_vm != null\n\t\t\t\t\tDCS_DEBUG_ASSERT( p_vm );\n\n\t\t\t\t\tnew_shares.push_back(p_vm->cpu_share());\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (old_shares.size() == 0)\n\t\t\t{\n\t\t\t\tfor (::std::size_t i = 0; i < nvms; ++i)\n\t\t\t\t{\n\t\t\t\t\tconst vm_pointer p_vm = vms[i];\n\n\t\t\t\t\t// check: p_vm != null\n\t\t\t\t\tDCS_DEBUG_ASSERT( p_vm );\n\n\t\t\t\t\told_shares.push_back(p_vm->cpu_share());\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (deltacs.size() == 0)\n\t\t\t{\n\t\t\t\tdeltacs.assign(nvms, std::numeric_limits<real_type>::quiet_NaN());\n\t\t\t}\n\t\t\tif (cress.size() == 0)\n\t\t\t{\n\t\t\t\tcress.assign(nvms, std::numeric_limits<real_type>::quiet_NaN());\n\t\t\t}\n\t\t\tif (rgains.size() == 0)\n\t\t\t{\n\t\t\t\tfor (target_iterator tgt_it = this->target_values().begin(),\n\t\t\t\t\t\t\t\t\t tgt_end_it = this->target_values().end();\n\t\t\t\ttgt_it != tgt_end_it;\n\t\t\t\t++tgt_it)\n\t\t\t\t{\n\t\t\t\t\tconst application_performance_category cat = tgt_it->first;\n\n\t\t\t\t\trgains[cat] = std::numeric_limits<real_type>::quiet_NaN();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t*p_dat_ofs_ << ::std::time(0) << \",\";\n\t\t\tfor (::std::size_t i = 0; i < nvms; ++i)\n\t\t\t{\n\t\t\t\tconst vm_pointer p_vm = vms[i];\n\n\t\t\t\t// check: p_vm != null\n\t\t\t\tDCS_DEBUG_ASSERT( p_vm );\n\n\t\t\t\tif (i != 0)\n\t\t\t\t{\n\t\t\t\t\t*p_dat_ofs_ << \",\";\n\t\t\t\t}\n\t\t\t\t*p_dat_ofs_ << p_vm->cpu_cap() << \",\" << p_vm->cpu_share();\n\t\t\t}\n\t\t\t*p_dat_ofs_ << \",\";\n            for (std::size_t i = 0; i < nvms; ++i)\n            {\n                if (i != 0)\n                {\n                    *p_dat_ofs_ << \",\";\n                }\n                *p_dat_ofs_ << old_shares[i];\n            }\n\t\t\t*p_dat_ofs_ << \",\";\n\t\t\tfor (::std::size_t i = 0; i < nvms; ++i)\n\t\t\t{\n\t\t\t\tconst vm_pointer p_vm = vms[i];\n\n\t\t\t\t// check: p_vm != null\n\t\t\t\tDCS_DEBUG_ASSERT( p_vm );\n\n\t\t\t\tif (i != 0)\n\t\t\t\t{\n\t\t\t\t\t*p_dat_ofs_ << \",\";\n\t\t\t\t}\n\t\t\t\t//*p_dat_ofs_ << this->data_smoother(cpu_util_virtual_machine_performance, p_vm->id()).forecast(0)\n\t\t\t\t//\t\t\t<< \",\" << this->data_smoother(memory_util_virtual_machine_performance, p_vm->id()).forecast(0);\n\t\t\t\t*p_dat_ofs_ << cutils[i]\n\t\t\t\t\t\t\t<< \",\" << this->data_smoother(memory_util_virtual_machine_performance, p_vm->id()).forecast(0);\n\t\t\t}\n\t\t\t*p_dat_ofs_ << \",\";\n\t\t\tfor (target_iterator tgt_it = this->target_values().begin(),\n\t\t\t\t\t\t\t\t tgt_end_it = this->target_values().end();\n\t\t\t\t tgt_it != tgt_end_it;\n\t\t\t\t ++tgt_it)\n\t\t\t{\n\t\t\t\tconst application_performance_category cat = tgt_it->first;\n\n\t\t\t\tif (tgt_it != this->target_values().begin())\n\t\t\t\t{\n\t\t\t\t\t*p_dat_ofs_ << \",\";\n\t\t\t\t}\n\t\t\t\tconst real_type yh = this->data_estimator(cat).estimate();\n\t\t\t\tconst real_type yr = tgt_it->second;\n\t\t\t\tconst real_type rgain = rgains.at(cat);\n\t\t\t\t*p_dat_ofs_ << yr << \",\" << yh << \",\" << rgain;\n\t\t\t}\n\t\t\tfor (::std::size_t i = 0; i < nvms; ++i)\n\t\t\t{\n\t\t\t\t*p_dat_ofs_ << \",\" << cress[i];\n\t\t\t}\n\t\t\tfor (std::size_t i = 0; i < nvms; ++i)\n\t\t\t{\n\t\t\t\t*p_dat_ofs_ << \",\" << deltacs[i];\n\t\t\t}\n\t\t\tfor (std::size_t i = 0; i < nvms; ++i)\n\t\t\t{\n\t\t\t\t*p_dat_ofs_ << \",\" << new_shares[i];\n\t\t\t}\n\t\t\t*p_dat_ofs_ << \",\" << ctl_count_ << \",\" << ctl_skip_count_ << \",\" << ctl_fail_count_;\n            *p_dat_ofs_ << \",\" << (cpu_timer.elapsed().user+cpu_timer.elapsed().system);\n\t\t\t*p_dat_ofs_ << ::std::endl;\n\t\t}\n\n\t\tDCS_DEBUG_TRACE(\"(\" << this << \") END Do CONTROL - Count: \" << ctl_count_ << \"/\" << ctl_skip_count_ << \"/\" << ctl_fail_count_);\n\t}\n\n\n\tprivate: real_type beta_; ///< The EWMA smoothing factor for resource utilizations\n\tprivate: ::boost::shared_ptr<fl::Engine> p_fuzzy_eng_; ///< The fuzzy control engine\n\tprivate: ::std::size_t ctl_count_; ///< Number of times control function has been invoked\n\tprivate: ::std::size_t ctl_skip_count_; ///< Number of times control has been skipped\n\tprivate: ::std::size_t ctl_fail_count_; ///< Number of times control has failed\n\tprivate: in_sensor_map in_sensors_;\n\tprivate: out_sensor_map out_sensors_;\n\tprivate: ::std::string dat_fname_;\n\tprivate: ::boost::shared_ptr< ::std::ofstream > p_dat_ofs_;\n}; // anglano2014_fc2q_application_manager\n\ntemplate <typename T>\nconst std::size_t anglano2014_fc2q_application_manager<T>::control_warmup_size = 5;\n\ntemplate <typename T>\nconst float anglano2014_fc2q_application_manager<T>::resource_share_lb_scale_factor = 1.1;\n\ntemplate <typename T>\nconst ::std::string anglano2014_fc2q_application_manager<T>::rgain_fuzzy_var_name = \"Rgain\";\n\ntemplate <typename T>\nconst ::std::string anglano2014_fc2q_application_manager<T>::cres_fuzzy_var_name = \"Cres\";\n\ntemplate <typename T>\nconst ::std::string anglano2014_fc2q_application_manager<T>::deltac_fuzzy_var_name = \"DeltaC\";\n\n}} // Namespace dcs::testbed\n\n#endif // DCS_TESTBED_ANGLANO2014_FC2Q_APPLICATION_MANAGER_HPP\n", "meta": {"hexsha": "287ab93739639f7d6026584d5b829fe663e4bcc3", "size": 24727, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/dcs/testbed/anglano2014_fc2q_application_manager.hpp", "max_stars_repo_name": "sguazt/dcsxx-testbed", "max_stars_repo_head_hexsha": "e7210f0c7f54256d5bf0c90297e0c4f9eaf82da0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inc/dcs/testbed/anglano2014_fc2q_application_manager.hpp", "max_issues_repo_name": "sguazt/dcsxx-testbed", "max_issues_repo_head_hexsha": "e7210f0c7f54256d5bf0c90297e0c4f9eaf82da0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/dcs/testbed/anglano2014_fc2q_application_manager.hpp", "max_forks_repo_name": "sguazt/dcsxx-testbed", "max_forks_repo_head_hexsha": "e7210f0c7f54256d5bf0c90297e0c4f9eaf82da0", "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.3908205841, "max_line_length": 262, "alphanum_fraction": 0.6553564929, "num_tokens": 7432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.293560766853691}}
{"text": "/*\n *\n * Copyright (c) Toon Knapen & Kresimir Fresl 2003\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 * KF acknowledges the support of the Faculty of Civil Engineering,\n * University of Zagreb, Croatia.\n *\n */\n\n#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_HESV_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_HESV_HPP\n\n#include <boost/numeric/bindings/traits/type_traits.hpp>\n#include <boost/numeric/bindings/traits/traits.hpp>\n#include <boost/numeric/bindings/lapack/lapack.h>\n#include <boost/numeric/bindings/lapack/ilaenv.hpp>\n#include <boost/numeric/bindings/traits/detail/array.hpp>\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n#  include <boost/static_assert.hpp>\n#  include <boost/type_traits/is_same.hpp>\n#endif\n\n#include <cassert>\n\n\nnamespace boost { namespace numeric { namespace bindings {\n\n  namespace lapack {\n\n    /////////////////////////////////////////////////////////////////////\n    //\n    // system of linear equations A * X = B\n    // with A Hermitian indefinite matrix\n    //\n    /////////////////////////////////////////////////////////////////////\n\n    namespace detail {\n\n      inline\n      integer_t hetrf_block (traits::complex_f,\n                       integer_t const ispec, char const ul, integer_t const n)\n      {\n        char ul2[2] = \"x\"; ul2[0] = ul;\n        return ilaenv (ispec, \"CHETRF\", ul2, n);\n      }\n      inline\n      integer_t hetrf_block (traits::complex_d,\n                       integer_t const ispec, char const ul, integer_t const n)\n      {\n        char ul2[2] = \"x\"; ul2[0] = ul;\n        return ilaenv (ispec, \"ZHETRF\", ul2, n);\n      }\n\n    }\n\n\n    template <typename HermA>\n    integer_t hetrf_block (char const q, char const ul, HermA const& a) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<HermA>::matrix_structure,\n        traits::general_t\n      >::value));\n#endif\n      assert (q == 'O' || q == 'M');\n      assert (ul == 'U' || ul == 'L');\n\n      integer_t n = traits::matrix_size1 (a);\n      assert (n == traits::matrix_size2 (a));\n\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<HermA>::value_type val_t;\n#else\n      typedef typename HermA::value_type val_t;\n#endif\n      integer_t ispec = (q == 'O' ? 1 : 2);\n      return detail::hetrf_block (val_t(), ispec, ul, n);\n    }\n\n    template <typename HermA>\n    integer_t hetrf_block (char const q, HermA const& a) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<HermA>::matrix_structure,\n        traits::hermitian_t\n      >::value));\n#endif\n      assert (q == 'O' || q == 'M');\n\n      char ul = traits::matrix_uplo_tag (a);\n      integer_t n = traits::matrix_size1 (a);\n      assert (n == traits::matrix_size2 (a));\n\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<HermA>::value_type val_t;\n#else\n      typedef typename HermA::value_type val_t;\n#endif\n      integer_t ispec = (q == 'O' ? 1 : 2);\n      return detail::hetrf_block (val_t(), ispec, ul, n);\n    }\n\n    template <typename HermA>\n    integer_t hetrf_work (char const q, char const ul, HermA const& a) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<HermA>::matrix_structure,\n        traits::general_t\n      >::value));\n#endif\n      assert (q == 'O' || q == 'M');\n      assert (ul == 'U' || ul == 'L');\n\n      integer_t n = traits::matrix_size1 (a);\n      assert (n == traits::matrix_size2 (a));\n\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<HermA>::value_type val_t;\n#else\n      typedef typename HermA::value_type val_t;\n#endif\n      integer_t lw = -13;\n      if (q == 'M')\n        lw = 1;\n      if (q == 'O')\n        lw = n * detail::hetrf_block (val_t(), 1, ul, n);\n      return lw;\n    }\n\n    template <typename HermA>\n    integer_t hetrf_work (char const q, HermA const& a) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<HermA>::matrix_structure,\n        traits::hermitian_t\n      >::value));\n#endif\n      assert (q == 'O' || q == 'M');\n\n      char ul = traits::matrix_uplo_tag (a);\n      integer_t n = traits::matrix_size1 (a);\n      assert (n == traits::matrix_size2 (a));\n\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<HermA>::value_type val_t;\n#else\n      typedef typename HermA::value_type val_t;\n#endif\n      integer_t lw = -13;\n      if (q == 'M')\n        lw = 1;\n      if (q == 'O')\n        lw = n * detail::hetrf_block (val_t(), 1, ul, n);\n      return lw;\n    }\n\n\n    template <typename HermA>\n    inline\n    integer_t hesv_work (char const q, char const ul, HermA const& a) {\n      return hetrf_work (q, ul, a);\n    }\n\n    template <typename HermA>\n    inline\n    integer_t hesv_work (char const q, HermA const& a) { return hetrf_work (q, a); }\n\n\n    /*\n     * hesv() computes the solution to a system of linear equations\n     * A * X = B, where A is an N-by-N Hermitian matrix and X and B\n     * are N-by-NRHS matrices.\n     *\n     * The diagonal pivoting method is used to factor A as\n     *   A = U * D * U^H,  if UPLO = 'U',\n     *   A = L * D * L^H,  if UPLO = 'L',\n     * where  U (or L) is a product of permutation and unit upper\n     * (lower) triangular matrices, and D is Hermitian and block\n     * diagonal with 1-by-1 and 2-by-2 diagonal blocks. The factored\n     * form of A is then used to solve the system of equations A * X = B.\n     */\n\n    namespace detail {\n\n      inline\n      void hesv (char const uplo, integer_t const n, integer_t const nrhs,\n                 traits::complex_f* a, integer_t const lda, integer_t* ipiv,\n                 traits::complex_f* b, integer_t const ldb,\n                 traits::complex_f* w, integer_t const lw, integer_t* info)\n      {\n        LAPACK_CHESV (&uplo, &n, &nrhs,\n                      traits::complex_ptr (a), &lda, ipiv,\n                      traits::complex_ptr (b), &ldb,\n                      traits::complex_ptr (w), &lw, info);\n      }\n\n      inline\n      void hesv (char const uplo, integer_t const n, integer_t const nrhs,\n                 traits::complex_d* a, integer_t const lda, integer_t* ipiv,\n                 traits::complex_d* b, integer_t const ldb,\n                 traits::complex_d* w, integer_t const lw, integer_t* info)\n      {\n        LAPACK_ZHESV (&uplo, &n, &nrhs,\n                      traits::complex_ptr (a), &lda, ipiv,\n                      traits::complex_ptr (b), &ldb,\n                      traits::complex_ptr (w), &lw, info);\n      }\n\n      template <typename HermA, typename MatrB, typename IVec, typename Work>\n      int hesv (char const ul, HermA& a, IVec& i, MatrB& b, Work& w) {\n\n        integer_t const n = traits::matrix_size1 (a);\n        assert (n == traits::matrix_size2 (a));\n        assert (n == traits::matrix_size1 (b));\n        assert (n == traits::vector_size (i));\n\n        integer_t info;\n        hesv (ul, n, traits::matrix_size2 (b),\n              traits::matrix_storage (a),\n              traits::leading_dimension (a),\n              traits::vector_storage (i),\n              traits::matrix_storage (b),\n              traits::leading_dimension (b),\n              traits::vector_storage (w),\n              traits::vector_size (w),\n              &info);\n        return info;\n      }\n\n    }\n\n    template <typename HermA, typename MatrB, typename IVec, typename Work>\n    int hesv (char const ul, HermA& a, IVec& i, MatrB& b, Work& w) {\n\n      assert (ul == 'U' || ul == 'L');\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<HermA>::matrix_structure,\n        traits::general_t\n      >::value));\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrB>::matrix_structure,\n        traits::general_t\n      >::value));\n#endif\n\n      integer_t const lw = traits::vector_size (w);\n      assert (lw >= 1);\n      return detail::hesv (ul, a, i, b, w);\n    }\n\n    template <typename HermA, typename MatrB, typename IVec, typename Work>\n    int hesv (HermA& a, IVec& i, MatrB& b, Work& w) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<HermA>::matrix_structure,\n        traits::hermitian_t\n      >::value));\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrB>::matrix_structure,\n        traits::general_t\n      >::value));\n#endif\n\n      integer_t const lw = traits::vector_size (w);\n      assert (lw >= 1);\n      char uplo = traits::matrix_uplo_tag (a);\n      return detail::hesv (uplo, a, i, b, w);\n    }\n\n    template <typename HermA, typename MatrB>\n    int hesv (char const ul, HermA& a, MatrB& b) {\n      // with 'internal' pivot and work vectors\n\n      assert (ul == 'U' || ul == 'L');\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<HermA>::matrix_structure,\n        traits::general_t\n      >::value));\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrB>::matrix_structure,\n        traits::general_t\n      >::value));\n#endif\n\n      integer_t const n = traits::matrix_size1 (a);\n      integer_t info = -101;\n      traits::detail::array<integer_t> i (n);\n\n      if (i.valid()) {\n        info = -102;\n        integer_t lw = hetrf_work ('O', ul, a);\n        assert (lw >= 1); // paranoia ?\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n        typedef typename traits::matrix_traits<HermA>::value_type val_t;\n#else\n        typedef typename HermA::value_type val_t;\n#endif\n        traits::detail::array<val_t> w (lw);\n        if (w.valid())\n          info = detail::hesv (ul, a, i, b, w);\n      }\n      return info;\n    }\n\n    template <typename HermA, typename MatrB>\n    int hesv (HermA& a, MatrB& b) {\n      // with 'internal' pivot and work vectors\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<HermA>::matrix_structure,\n        traits::hermitian_t\n      >::value));\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrB>::matrix_structure,\n        traits::general_t\n      >::value));\n#endif\n\n      integer_t const n = traits::matrix_size1 (a);\n      char uplo = traits::matrix_uplo_tag (a);\n      integer_t info = -101;\n      traits::detail::array<integer_t> i (n);\n\n      if (i.valid()) {\n        info = -102;\n        integer_t lw = hetrf_work ('O', a);\n        assert (lw >= 1); // paranoia ?\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n        typedef typename traits::matrix_traits<HermA>::value_type val_t;\n#else\n        typedef typename HermA::value_type val_t;\n#endif\n        traits::detail::array<val_t> w (lw);\n        w.resize (lw);\n        if (w.valid())\n          info = detail::hesv (uplo, a, i, b, w);\n      }\n      return info;\n    }\n\n\n    /*\n     * hetrf() computes the factorization of a Hermitian matrix A using\n     * the  Bunch-Kaufman diagonal pivoting method. The form of the\n     * factorization is\n     *    A = U * D * U^H  or  A = L * D * L^H\n     * where U (or L) is a product of permutation and unit upper (lower)\n     * triangular matrices, and D is Hermitian and block diagonal with\n     * 1-by-1 and 2-by-2 diagonal blocks.\n     */\n\n    namespace detail {\n\n      inline\n      void hetrf (char const uplo, integer_t const n,\n                  traits::complex_f* a, integer_t const lda, integer_t* ipiv,\n                  traits::complex_f* w, integer_t const lw, integer_t* info)\n      {\n        LAPACK_CHETRF (&uplo, &n,\n                       traits::complex_ptr (a), &lda, ipiv,\n                       traits::complex_ptr (w), &lw, info);\n      }\n\n      inline\n      void hetrf (char const uplo, integer_t const n,\n                  traits::complex_d* a, integer_t const lda, integer_t* ipiv,\n                  traits::complex_d* w, integer_t const lw, integer_t* info)\n      {\n        LAPACK_ZHETRF (&uplo, &n,\n                       traits::complex_ptr (a), &lda, ipiv,\n                       traits::complex_ptr (w), &lw, info);\n      }\n\n      template <typename HermA, typename IVec, typename Work>\n      int hetrf (char const ul, HermA& a, IVec& i, Work& w) {\n\n        integer_t const n = traits::matrix_size1 (a);\n        assert (n == traits::matrix_size2 (a));\n        assert (n == traits::vector_size (i));\n\n        integer_t info;\n        hetrf (ul, n, traits::matrix_storage (a),\n               traits::leading_dimension (a),\n               traits::vector_storage (i),\n               traits::vector_storage (w),\n               traits::vector_size (w),\n               &info);\n        return info;\n      }\n\n    }\n\n    template <typename HermA, typename IVec, typename Work>\n    int hetrf (char const ul, HermA& a, IVec& i, Work& w) {\n\n      assert (ul == 'U' || ul == 'L');\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<HermA>::matrix_structure,\n        traits::general_t\n      >::value));\n#endif\n\n      assert (traits::vector_size (w) >= 1);\n      return detail::hetrf (ul, a, i, w);\n    }\n\n    template <typename HermA, typename IVec, typename Work>\n    int hetrf (HermA& a, IVec& i, Work& w) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<HermA>::matrix_structure,\n        traits::hermitian_t\n      >::value));\n#endif\n\n      std::ptrdiff_t const lw = traits::vector_size (w);\n      assert (lw >= 1);\n      char uplo = traits::matrix_uplo_tag (a);\n      return detail::hetrf (uplo, a, i, w);\n    }\n\n    template <typename HermA, typename Ivec>\n    int hetrf (char const ul, HermA& a, Ivec& i) {\n      // with 'internal' work vector\n\n      assert (ul == 'U' || ul == 'L');\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<HermA>::matrix_structure,\n        traits::general_t\n      >::value));\n#endif\n\n      integer_t info = -101;\n      integer_t lw = hetrf_work ('O', ul, a);\n      assert (lw >= 1); // paranoia ?\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<HermA>::value_type val_t;\n#else\n      typedef typename HermA::value_type val_t;\n#endif\n      traits::detail::array<val_t> w (lw);\n      if (w.valid())\n        info = detail::hetrf (ul, a, i, w);\n      return info;\n    }\n\n    template <typename HermA, typename Ivec>\n    int hetrf (HermA& a, Ivec& i) {\n      // with 'internal' work vector\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<HermA>::matrix_structure,\n        traits::hermitian_t\n      >::value));\n#endif\n\n      char uplo = traits::matrix_uplo_tag (a);\n      integer_t info = -101;\n      integer_t lw = hetrf_work ('O', a);\n      assert (lw >= 1); // paranoia ?\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<HermA>::value_type val_t;\n#else\n      typedef typename HermA::value_type val_t;\n#endif\n      traits::detail::array<val_t> w (lw);\n      if (w.valid())\n        info = detail::hetrf (uplo, a, i, w);\n      return info;\n    }\n\n\n    /*\n     * hetrs() solves a system of linear equations A*X = B with\n     * a Hermitian matrix A using the factorization\n     *    A = U * D * U^H   or  A = L * D * L^H\n     * computed by hetrf().\n     */\n\n    namespace detail {\n\n      inline\n      void hetrs (char const uplo, integer_t const n, integer_t const nrhs,\n                  traits::complex_f const* a, integer_t const lda,\n                  integer_t const* ipiv,\n                  traits::complex_f* b, integer_t const ldb, integer_t* info)\n      {\n        LAPACK_CHETRS (&uplo, &n, &nrhs,\n                       traits::complex_ptr (a), &lda, ipiv,\n                       traits::complex_ptr (b), &ldb, info);\n      }\n\n      inline\n      void hetrs (char const uplo, integer_t const n, integer_t const nrhs,\n                  traits::complex_d const* a, integer_t const lda,\n                  integer_t const* ipiv,\n                  traits::complex_d* b, integer_t const ldb, integer_t* info)\n      {\n        LAPACK_ZHETRS (&uplo, &n, &nrhs,\n                       traits::complex_ptr (a), &lda, ipiv,\n                       traits::complex_ptr (b), &ldb, info);\n      }\n\n      template <typename HermA, typename MatrB, typename IVec>\n      int hetrs (char const ul, HermA const& a, IVec const& i, MatrB& b) {\n\n        integer_t const n = traits::matrix_size1 (a);\n        assert (n == traits::matrix_size2 (a));\n        assert (n == traits::matrix_size1 (b));\n        assert (n == traits::vector_size (i));\n\n        integer_t info;\n        hetrs (ul, n, traits::matrix_size2 (b),\n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n               traits::matrix_storage (a),\n#else\n               traits::matrix_storage_const (a),\n#endif\n               traits::leading_dimension (a),\n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n               traits::vector_storage (i),\n#else\n               traits::vector_storage_const (i),\n#endif\n               traits::matrix_storage (b),\n               traits::leading_dimension (b), &info);\n        return info;\n      }\n\n    }\n\n    template <typename HermA, typename MatrB, typename IVec>\n    inline\n    int hetrs (char const ul, HermA const& a, IVec const& i, MatrB& b) {\n\n      assert (ul == 'U' || ul == 'L');\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<HermA>::matrix_structure,\n        traits::general_t\n      >::value));\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrB>::matrix_structure,\n        traits::general_t\n      >::value));\n#endif\n\n      return detail::hetrs (ul, a, i, b);\n    }\n\n    template <typename HermA, typename MatrB, typename IVec>\n    inline\n    int hetrs (HermA const& a, IVec const& i, MatrB& b) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<HermA>::matrix_structure,\n        traits::hermitian_t\n      >::value));\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrB>::matrix_structure,\n        traits::general_t\n      >::value));\n#endif\n\n      char uplo = traits::matrix_uplo_tag (a);\n      return detail::hetrs (uplo, a, i, b);\n    }\n\n\n    // TO DO: hetri\n\n  }\n\n}}}\n\n#endif\n", "meta": {"hexsha": "9e87854a3e43ee5255af1f9c08451ed5a4fad49b", "size": 18927, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/lapack/hesv.hpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/lapack/hesv.hpp", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/lapack/hesv.hpp", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.545, "max_line_length": 84, "alphanum_fraction": 0.6018386432, "num_tokens": 4977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.29356075939409254}}
{"text": "/*********************************************************************\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2013, PAL Robotics, S.L.\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of the PAL Robotics 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 * Author: Luca Marchionni\n * Author: Bence Magyar\n * Author: Enrique Fernández\n * Author: Paul Mathieu\n */\n\n#include \"odometry.h\"\n\n#include <cmath>\n#include <boost/bind.hpp>\n\n#include <dynamic-graph/command-bind.h>\n#include <dynamic-graph/command-direct-getter.h>\n#include <dynamic-graph/command-direct-setter.h>\n#include <dynamic-graph/factory.h>\n\nnamespace dynamicgraph\n{\nnamespace details\n{\n  namespace bacc = boost::accumulators;\n\n  Odometry::Odometry(size_t velocity_rolling_window_size)\n  : x_(0.0)\n  , y_(0.0)\n  , heading_(0.0)\n  , linear_(0.0)\n  , angular_(0.0)\n  , wheelSeparation_(0.0)\n  , left_wheelRadius_(0.0)\n  , right_wheelRadius_(0.0)\n  , left_wheel_old_pos_(0.0)\n  , right_wheel_old_pos_(0.0)\n  , velocity_rolling_window_size_(velocity_rolling_window_size)\n  , linear_acc_(RollingWindow::window_size = velocity_rolling_window_size)\n  , angular_acc_(RollingWindow::window_size = velocity_rolling_window_size)\n  , integrate_fun_(boost::bind(&Odometry::integrateExact, this, _1, _2))\n  {\n  }\n\n  void Odometry::init()\n  {\n    // Reset accumulators:\n    resetAccumulators();\n  }\n\n  bool Odometry::update(double left_pos, double right_pos, double dt)\n  {\n    /// Get current wheel joint positions:\n    const double left_wheel_cur_pos  = left_pos  * left_wheelRadius_;\n    const double right_wheel_cur_pos = right_pos * right_wheelRadius_;\n\n    /// Estimate velocity of wheels using old and current position:\n    const double left_wheel_est_vel  = left_wheel_cur_pos  - left_wheel_old_pos_;\n    const double right_wheel_est_vel = right_wheel_cur_pos - right_wheel_old_pos_;\n\n    /// Update old position with current:\n    left_wheel_old_pos_  = left_wheel_cur_pos;\n    right_wheel_old_pos_ = right_wheel_cur_pos;\n\n    /// Compute linear and angular diff:\n    const double linear  = (right_wheel_est_vel + left_wheel_est_vel) * 0.5 ;\n    const double angular = (right_wheel_est_vel - left_wheel_est_vel) / wheelSeparation_;\n\n    /// Integrate odometry:\n    integrate_fun_(linear, angular);\n\n    /// We cannot estimate the speed with very small time intervals:\n    if (dt < 0.0001)\n      return false; // Interval too small to integrate with\n\n    /// Estimate speeds using a rolling mean to filter them out:\n    linear_acc_(linear/dt);\n    angular_acc_(angular/dt);\n\n    linear_ = bacc::rolling_mean(linear_acc_);\n    angular_ = bacc::rolling_mean(angular_acc_);\n\n    return true;\n  }\n\n  void Odometry::updateOpenLoop(double linear, double angular, double dt)\n  {\n    /// Save last linear and angular velocity:\n    linear_ = linear;\n    angular_ = angular;\n\n    /// Integrate odometry:\n    integrate_fun_(linear * dt, angular * dt);\n  }\n\n  void Odometry::setWheelParams(double wheelSeparation, double left_wheelRadius, double right_wheelRadius)\n  {\n    wheelSeparation_   = wheelSeparation;\n    left_wheelRadius_  = left_wheelRadius;\n    right_wheelRadius_ = right_wheelRadius;\n  }\n\n  void Odometry::setVelocityRollingWindowSize(size_t velocity_rolling_window_size)\n  {\n    velocity_rolling_window_size_ = velocity_rolling_window_size;\n\n    resetAccumulators();\n  }\n\n  void Odometry::integrateRungeKutta2(double linear, double angular)\n  {\n    const double direction = heading_ + angular * 0.5;\n\n    /// Runge-Kutta 2nd order integration:\n    x_       += linear * cos(direction);\n    y_       += linear * sin(direction);\n    heading_ += angular;\n  }\n\n  /**\n   * \\brief Other possible integration method provided by the class\n   * \\param linear\n   * \\param angular\n   */\n  void Odometry::integrateExact(double linear, double angular)\n  {\n    if (fabs(angular) < 1e-6)\n      integrateRungeKutta2(linear, angular);\n    else\n    {\n      /// Exact integration (should solve problems when angular is zero):\n      const double heading_old = heading_;\n      const double r = linear/angular;\n      heading_ += angular;\n      x_       +=  r * (sin(heading_) - sin(heading_old));\n      y_       += -r * (cos(heading_) - cos(heading_old));\n    }\n  }\n\n  void Odometry::resetAccumulators()\n  {\n    linear_acc_ = RollingMeanAcc(RollingWindow::window_size = velocity_rolling_window_size_);\n    angular_acc_ = RollingMeanAcc(RollingWindow::window_size = velocity_rolling_window_size_);\n  }\n\n} // namespace details\n\n  namespace bacc = boost::accumulators;\n\n  Odometry::Odometry(const std::string& name)\n  : Entity (name)\n  , wheelsPositionSIN (NULL, \"Odometry(\"+name+\")::input(vector)::wheelsPosition\")\n  , baseVelocityEstimationSOUT (boost::bind (&Odometry::computeVelocityEstimation, this, _1, _2),\n      wheelsPositionSIN, \"Odometry(\"+name+\")::output(vector)::baseVelocityEstimation\")\n  , baseVelocityFilteredEstimationSOUT (boost::bind (&Odometry::computeVelocityFilteredEstimation, this, _1, _2),\n      baseVelocityEstimationSOUT, \"Odometry(\"+name+\")::output(vector)::baseVelocityFilteredEstimation\")\n  , baseVelocitySIN (NULL, \"Odometry(\"+name+\")::input(vector)::baseVelocity\")\n  , baseConfigSOUT (boost::bind (&Odometry::computeBaseConfig, this, _1, _2),\n      baseVelocitySIN, \"Odometry(\"+name+\")::output(vector)::baseConfig\")\n  , basePoseSOUT (boost::bind (&Odometry::computeBasePose, this, _1, _2),\n      baseConfigSOUT, \"Odometry(\"+name+\")::output(matrixHomogeneous)::basePose\")\n\n  , dt_ (1.)\n  , x_(0.0)\n  , y_(0.0)\n  , heading_(0.0)\n  , wheelSeparationInv_(0.0)\n  , wheelRadii_(0.0, 0.0)\n  , wheelOldPos_ (0.0, 0.0)\n  , rollingWindowSize_ (10)\n  , linear_acc_(RollingWindow::window_size = rollingWindowSize_)\n  , angular_acc_(RollingWindow::window_size = rollingWindowSize_)\n  {\n    signalRegistration (\n        wheelsPositionSIN <<\n        baseVelocityEstimationSOUT <<\n        baseVelocityFilteredEstimationSOUT <<\n        baseVelocitySIN <<\n        baseConfigSOUT <<\n        basePoseSOUT);\n\n    // By default, use the velocity estimation\n    // (i.e. loop closed with wheel position sensors).\n    baseVelocitySIN.plug (&baseVelocityEstimationSOUT);\n\n    addCommand (\"setWheelParams\",\n        command::makeCommandVoid3 (*this, &Odometry::setWheelParams,\n          command::docCommandVoid3 (\"Sets the wheel parameters: radius and separation\",\n            \"double: Separation between left and right wheels [m]\",\n            \"double: Left wheel radius [m]\",\n            \"double: Right wheel radius [m]\"))\n        );\n    addCommand (\"setBasePose\",\n        command::makeCommandVoid3 (*this, &Odometry::setBasePose,\n          command::docCommandVoid3 (\"Set the base pose to integrate from.\",\n            \"double: x [m]\",\n            \"double: y [m]\",\n            \"double: heading [rad]\"))\n        );\n    addCommand (\"setPeriod\", command::makeDirectSetter (*this, &dt_,\n          \"Set period (only affects the velocity estimation and nothing else).\"));\n    addCommand (\"getPeriod\", command::makeDirectGetter (*this, &dt_,\n          \"the period\"));\n  }\n\n  Vector& Odometry::computeVelocityEstimation (Vector& vel, int time)\n  {\n    vel.resize(2);\n    const Vector& wheelCurAng = wheelsPositionSIN (time);\n\n    /// Get current wheel joint positions:\n    Eigen::Array2d wheelCurPos = wheelCurAng.array() * wheelRadii_;\n\n    /// Estimate velocity of wheels using old and current position:\n    Eigen::Array2d wheelEstVel = ( wheelCurPos - wheelOldPos_ ) / dt_;\n\n    /// Update old position with current:\n    wheelOldPos_ = wheelCurPos;\n\n    /// Compute linear and angular diff:\n    vel[0] = (wheelEstVel[1] + wheelEstVel[0]) * 0.5                ;\n    vel[1] = (wheelEstVel[1] - wheelEstVel[0]) * wheelSeparationInv_;\n\n    /// Estimate speeds using a rolling mean to filter them out:\n    linear_acc_ (vel[0]);\n    angular_acc_(vel[1]);\n\n    return vel;\n  }\n\n  Vector& Odometry::computeVelocityFilteredEstimation (Vector& vel, int time)\n  {\n    baseVelocityEstimationSOUT.recompute (time);\n\n    vel.resize(2);\n    vel[0] = bacc::rolling_mean(linear_acc_);\n    vel[1] = bacc::rolling_mean(angular_acc_);\n\n    return vel;\n  }\n\n  Vector& Odometry::computeBaseConfig (Vector& base, int time)\n  {\n    base.resize(3);\n    const Vector& vel = baseVelocitySIN (time);\n    integrateExact (vel[0] * dt_, vel[1] * dt_);\n\n    base << x_, y_, heading_;\n    return base;\n  }\n\n  sot::MatrixHomogeneous& Odometry::computeBasePose (sot::MatrixHomogeneous& M, int time)\n  {\n    const Vector& base = baseConfigSOUT (time);\n    M.setIdentity();\n    M.translation().head<2>() = base.head<2>();\n    double c = cos(base(2)), s = sin(base(2));\n    M.linear().topLeftCorner<2,2>() <<\n      c, -s,\n      s,  c;\n    return M;\n  }\n\n  void Odometry::setBasePose (const double& x, const double& y, const double& heading)\n  {\n    x_ = x;\n    y_ = y;\n    heading_ = heading;\n\n    resetAccumulators ();\n  }\n\n  void Odometry::setWheelParams(const double& wheelSeparation, const double& leftWheelRadius, const double& rightWheelRadius)\n  {\n    wheelSeparationInv_   = 1/wheelSeparation;\n    wheelRadii_  << leftWheelRadius, rightWheelRadius;\n  }\n\n  void Odometry::setVelocityRollingWindowSize(const size_t& rollingWindowSize)\n  {\n    rollingWindowSize_ = rollingWindowSize;\n    resetAccumulators ();\n  }\n\n  void Odometry::integrateRungeKutta2(double linear, double angular)\n  {\n    const double direction = heading_ + angular * 0.5;\n\n    /// Runge-Kutta 2nd order integration:\n    x_       += linear * cos(direction);\n    y_       += linear * sin(direction);\n    heading_ += angular;\n  }\n\n  /**\n   * \\brief Other possible integration method provided by the class\n   * \\param linear\n   * \\param angular\n   */\n  void Odometry::integrateExact(double linear, double angular)\n  {\n    if (fabs(angular) < 1e-6)\n      integrateRungeKutta2(linear, angular);\n    else\n    {\n      /// Exact integration (should solve problems when angular is zero):\n      const double heading_old = heading_;\n      const double r = linear/angular;\n      heading_ += angular;\n      x_       +=  r * (sin(heading_) - sin(heading_old));\n      y_       += -r * (cos(heading_) - cos(heading_old));\n    }\n  }\n\n  void Odometry::resetAccumulators()\n  {\n    linear_acc_  = RollingMeanAcc(RollingWindow::window_size = rollingWindowSize_);\n    angular_acc_ = RollingMeanAcc(RollingWindow::window_size = rollingWindowSize_);\n  }\n\n  DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN (Odometry, \"Odometry\");\n\n} // namespace diff_drive_controller\n", "meta": {"hexsha": "9708a3bb7fbab33ded6ae6b1e8ba2d5fd82e5621", "size": 11950, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/odometry.cpp", "max_stars_repo_name": "longhathuc/sot-tiago", "max_stars_repo_head_hexsha": "213ab140001396ee7d0c2be1bf96f1d93e42e22d", "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/odometry.cpp", "max_issues_repo_name": "longhathuc/sot-tiago", "max_issues_repo_head_hexsha": "213ab140001396ee7d0c2be1bf96f1d93e42e22d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2019-05-15T11:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-14T09:46:16.000Z", "max_forks_repo_path": "src/odometry.cpp", "max_forks_repo_name": "longhathuc/sot-tiago", "max_forks_repo_head_hexsha": "213ab140001396ee7d0c2be1bf96f1d93e42e22d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-03-30T16:56:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-30T09:15:01.000Z", "avg_line_length": 33.661971831, "max_line_length": 125, "alphanum_fraction": 0.6837656904, "num_tokens": 3023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.29355731834207466}}
{"text": "/* The Image Registration Toolkit (IRTK)\n *\n * Copyright 2008-2015 Imperial College London\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// MUST be included first due to nasty IRTK \"round\" macro\n#include <boost/random.hpp>\n\n#include <irtkPointSamples.h>\n\ntypedef boost::mt19937 RandomNumberGeneratorType;\n\n// =============================================================================\n// Construction/Destruction\n// =============================================================================\n\n// -----------------------------------------------------------------------------\nirtkPointSamples::irtkPointSamples(int n, int seed)\n:\n  irtkPointSet(n), _RandomNumberGenerator(new RandomNumberGeneratorType())\n{\n  RandomNumberGeneratorType &rng = *(RandomNumberGeneratorType*)_RandomNumberGenerator;\n  if (seed < 0) rng.seed(static_cast<unsigned int>(std::time(0)));\n  else          rng.seed(seed);\n}\n\n// -----------------------------------------------------------------------------\nirtkPointSamples::~irtkPointSamples()\n{\n  delete (RandomNumberGeneratorType*)_RandomNumberGenerator;\n}\n\n// =============================================================================\n// Uniform grid sampling\n// =============================================================================\n\n// -----------------------------------------------------------------------------\nvoid irtkPointSamples::SampleGrid(const irtkPoint &p1, const irtkPoint &p2,\n                                  int nx, int ny, int nz)\n{\n  SampleGrid(p1._x, p1._y, p1._z, p2._x, p2._y, p2._z, nx, ny, nz);\n}\n\n// -----------------------------------------------------------------------------\nvoid irtkPointSamples::SampleGrid(const irtkPoint &p1, const irtkPoint &p2,\n                                  double dx, double dy, double dz)\n{\n  SampleGrid(p1._x, p1._y, p1._z, p2._x, p2._y, p2._z, dx, dy, dz);\n}\n\n// -----------------------------------------------------------------------------\nvoid irtkPointSamples::SampleGrid(double x1, double y1, double z1,\n                                  double x2, double y2, double z2,\n                                  int    nx, int    ny, int    nz)\n{\n  if (x2 < x1) swap(x1, x2);\n  if (y2 < y1) swap(y1, y2);\n  if (z2 < z1) swap(z1, z2);\n  if (nx <= 0) nx = 1;\n  if (ny <= 0) ny = 1;\n  if (nz <= 0) nz = 1;\n  const double sx = x2 - x1;\n  const double sy = x2 - x1;\n  const double sz = x2 - x1;\n  const double dx = sx / nx;\n  const double dy = sy / ny;\n  const double dz = sz / nz;\n  Size(nx * ny * nz);\n  int n = 0;\n  for (int k = 0; k < nz; ++k)\n  for (int j = 0; j < ny; ++j)\n  for (int i = 0; i < nx; ++i, ++n) {\n    _data[n] = irtkPoint(x1 + i * dx, y1 + j * dy, z1 + k * dz);\n  }\n}\n\n// -----------------------------------------------------------------------------\nvoid irtkPointSamples::SampleGrid(double x1, double y1, double z1,\n                                  double x2, double y2, double z2,\n                                  double dx, double dy, double dz)\n{\n  if (x2 < x1) swap(x1, x2);\n  if (y2 < y1) swap(y1, y2);\n  if (z2 < z1) swap(z1, z2);\n  if (dx < 0) dx = .0;\n  if (dy < 0) dy = .0;\n  if (dz < 0) dz = .0;\n  const double sx = x2 - x1;\n  const double sy = x2 - x1;\n  const double sz = x2 - x1;\n  const int    nx = (dx > .0 ? round(sx / dx) : 1);\n  const int    ny = (dy > .0 ? round(sy / dy) : 1);\n  const int    nz = (dz > .0 ? round(sz / dz) : 1);\n  Size(nx * ny * nz);\n  int n = 0;\n  for (int k = 0; k < nz; ++k)\n  for (int j = 0; j < ny; ++j)\n  for (int i = 0; i < nx; ++i, ++n) {\n    _data[n] = irtkPoint(x1 + i * dx, y1 + j * dy, z1 + k * dz);\n  }\n}\n\n// =============================================================================\n// Uniform spherical distribution\n// =============================================================================\n\n// -----------------------------------------------------------------------------\nvoid irtkPointSamples::SampleSphere(double r)\n{\n  SampleSphere(.0, r);\n}\n\n// -----------------------------------------------------------------------------\nvoid irtkPointSamples::SampleSphere(double c, double r)\n{\n  SampleSphere(c, c, c, r, r, r);\n}\n\n// -----------------------------------------------------------------------------\nvoid irtkPointSamples::SampleSphere(const irtkPoint & c, double r)\n{\n  SampleSphere(c._x, c._y, c._z, r, r, r);\n}\n\n// -----------------------------------------------------------------------------\nvoid irtkPointSamples::SampleSphere(const irtkPoint & c, double rx, double ry, double rz)\n{\n  SampleSphere(c._x, c._y, c._z, rx, ry, rz);\n}\n\n// -----------------------------------------------------------------------------\nvoid irtkPointSamples::SampleSphere(double cx, double cy, double cz, double r)\n{\n  SampleSphere(cx, cy, cz, r, r, r);\n}\n\n// -----------------------------------------------------------------------------\nvoid irtkPointSamples::SampleSphere(double cx, double cy, double cz,\n                                    double rx, double ry, double rz)\n{\n  typedef boost::uniform_on_sphere<double>                                   Distribution;\n  typedef boost::variate_generator<RandomNumberGeneratorType&, Distribution> Generator;\n\n  RandomNumberGeneratorType &rng = *(RandomNumberGeneratorType*)_RandomNumberGenerator;\n\n  Distribution dist(3);\n  Generator next(rng, dist);\n\n  vector<double> p(3);\n  for (int i = 0; i < _n; ++i) {\n    p = next();\n    _data[i]._x = cx + rx * p[0];\n    _data[i]._y = cy + ry * p[1];\n    _data[i]._z = cz + rz * p[2];\n  }\n}\n\n// =============================================================================\n// Normal distribution\n// =============================================================================\n\n// -----------------------------------------------------------------------------\nvoid irtkPointSamples::SampleGaussian(double s)\n{\n  SampleGaussian(.0, s);\n}\n\n// -----------------------------------------------------------------------------\nvoid irtkPointSamples::SampleGaussian(double m, double s)\n{\n  SampleGaussian(m, m, m, s, s, s);\n}\n\n// -----------------------------------------------------------------------------\nvoid irtkPointSamples::SampleGaussian(const irtkPoint & m, double s)\n{\n  SampleGaussian(m._x, m._y, m._z, s, s, s);\n}\n\n// -----------------------------------------------------------------------------\nvoid irtkPointSamples::SampleGaussian(const irtkPoint & m, double sx, double sy, double sz)\n{\n  SampleGaussian(m._x, m._y, m._z, sx, sy, sz);\n}\n\n// -----------------------------------------------------------------------------\nvoid irtkPointSamples::SampleGaussian(double mx, double my, double mz, double s)\n{\n  SampleGaussian(mx, my, mz, s, s, s);\n}\n\n// -----------------------------------------------------------------------------\nvoid irtkPointSamples::SampleGaussian(double mx, double my, double mz,\n                                      double sx, double sy, double sz)\n{\n  typedef boost::normal_distribution<double>                                 Distribution;\n  typedef boost::variate_generator<RandomNumberGeneratorType&, Distribution> Generator;\n\n  RandomNumberGeneratorType &rng = *(RandomNumberGeneratorType*)_RandomNumberGenerator;\n\n  Distribution distx(mx, sx);\n  Distribution disty(my, sy);\n  Distribution distz(mz, sz);\n\n  Generator x(rng, distx);\n  Generator y(rng, disty);\n  Generator z(rng, distz);\n\n  for (int i = 0; i < _n; ++i) {\n    _data[i]._x = x();\n    _data[i]._y = y();\n    _data[i]._z = z();\n  }\n}\n", "meta": {"hexsha": "2716ae0420716e00f96ac93461e25ab58750d74e", "size": 7889, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Modules/Geometry/src/irtkPointSamples.cc", "max_stars_repo_name": "kevin-keraudren/IRTK", "max_stars_repo_head_hexsha": "ce329b7f58270b6c34665dcfe9a6e941649f3b94", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-10-04T19:32:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-02T07:37:30.000Z", "max_issues_repo_path": "Modules/Geometry/src/irtkPointSamples.cc", "max_issues_repo_name": "kevin-keraudren/IRTK", "max_issues_repo_head_hexsha": "ce329b7f58270b6c34665dcfe9a6e941649f3b94", "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/Geometry/src/irtkPointSamples.cc", "max_forks_repo_name": "kevin-keraudren/IRTK", "max_forks_repo_head_hexsha": "ce329b7f58270b6c34665dcfe9a6e941649f3b94", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-03-17T02:55:00.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-03T05:40:05.000Z", "avg_line_length": 34.907079646, "max_line_length": 91, "alphanum_fraction": 0.4543034605, "num_tokens": 1871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2935573183420746}}
{"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 NMSSM_TWOLOOPHIGGS_H\n#define NMSSM_TWOLOOPHIGGS_H\n\n#include <Eigen/Core>\n\n/**\n * @file nmssm_twoloophiggs.hpp\n * @brief function declarations for 2-loop NMSSM Higgs self-energies\n *        and tadpoles\n *\n * Notation:\n *\n * mt2    : squared DR-bar top mass in the NMSSM\n * mb2    : squared DR-bar bottom mass in the NMSSM\n * mtau2  : squared DR-bar tau mass in the NMSSM\n * mg     : DR-bar gluino mass in the NMSSM\n * mA2    : squared DR-bar CP-odd Higgs mass in the NMSSM\n * mst12  : squared DR-bar lightest stop mass\n * mst22  : squared DR-bar heaviest stop mass\n * msb12  : squared DR-bar lightest sbottom mass\n * msb22  : squared DR-bar heaviest sbottom mass\n * mstau12: squared DR-bar lightest stau mass\n * mstau22: squared DR-bar heaviest stau mass\n *\n * sxt    : sine of DR-bar stop mixing angle in the NMSSM\n * cxt    : cosine of DR-bar stop mixing angle in the NMSSM\n * sxb    : sine of DR-bar sbottom mixing angle in the NMSSM\n * cxb    : cosine of DR-bar sbottom mixing angle in the NMSSM\n * sintau : sine of DR-bar stau mixing angle in the NMSSM\n * costau : cosine of DR-bar stau mixing angle in the NMSSM\n *\n * gs     : DR-bar strong gauge coupling g3 in the NMSSM\n * mu     : DR-bar mu-parameter in the NMSSM (arXiv:0907.4682)\n * tanb   : DR-bar tan(beta) = vu/vd in the NMSSM\n * cotb   : DR-bar 1/tan(beta) in the NMSSM\n * vev2   : squared DR-bar vev^2 = (vu^2 + vd^2) in the NMSSM\n * lam    : DR-bar lambda in the NNMSSM\n * svev   : DR-bar singlet VEV = mu_eff / lam\n *\n * scheme : DR-bar scheme (0) or on-shell scheme (1)\n */\n\nnamespace flexiblesusy {\nnamespace nmssm_twoloophiggs {\n\nEigen::Matrix<double, 3, 1> tadpole_higgs_2loop_at_as_nmssm(\n   double mt2, double mg, double mst12, double mst22,\n   double sxt, double cxt, double scale2,\n   double mu, double tanb, double vev2, double gs, double svev);\n\nEigen::Matrix<double, 3, 1> tadpole_higgs_2loop_ab_as_nmssm(\n   double mb2, double mg, double msb12, double msb22,\n   double sxb, double cxb, double scale2,\n   double mu, double cotb, double vev2, double gs, double svev);\n\nEigen::Matrix<double, 3, 3> self_energy_higgs_2loop_at_as_nmssm(\n   double rmt, double mg, double mst12, double mst22,\n   double sxt, double cxt, double scale2, double tanb, double vev2,\n   double lam, double svev, double as, double mu);\n\nEigen::Matrix<double, 3, 3> self_energy_higgs_2loop_ab_as_nmssm(\n   double rmb, double mg, double msb12, double msb22,\n   double sxb, double cxb, double scale2, double cotb, double vev2,\n   double lam, double svev, double as, double mu);\n\nEigen::Matrix<double, 3, 3> self_energy_pseudoscalar_2loop_at_as_nmssm(\n   double rmt, double mg, double mst12, double mst22,\n   double sxt, double cxt, double scale2, double tanb, double vev2,\n   double lam, double svev, double as, double mu);\n\nEigen::Matrix<double, 3, 3> self_energy_pseudoscalar_2loop_ab_as_nmssm(\n   double rmb, double mg, double msb12, double msb22,\n   double sxb, double cxb, double scale2, double cotb, double vev2,\n   double lam, double svev, double as, double mu);\n\nEigen::Matrix<double, 3, 3> self_energy_higgs_2loop_at_as_nmssm_with_tadpoles(\n   double rmt, double mg, double mst12, double mst22,\n   double sxt, double cxt, double scale2, double tanb, double vev2,\n   double lam, double svev, double as);\n\nEigen::Matrix<double, 3, 3> self_energy_higgs_2loop_ab_as_nmssm_with_tadpoles(\n   double rmb, double mg, double msb12, double msb22,\n   double sxb, double cxb, double scale2, double cotb, double vev2,\n   double lam, double svev, double as);\n\nEigen::Matrix<double, 3, 3> self_energy_pseudoscalar_2loop_at_as_nmssm_with_tadpoles(\n   double rmt, double mg, double mst12, double mst22,\n   double sxt, double cxt, double scale2, double tanb, double vev2,\n   double lam, double svev, double as);\n\nEigen::Matrix<double, 3, 3> self_energy_pseudoscalar_2loop_ab_as_nmssm_with_tadpoles(\n   double rmb, double mg, double msb12, double msb22,\n   double sxb, double cxb, double scale2, double cotb, double vev2,\n   double lam, double svev, double as);\n\n} // namespace nmssm_twoloophiggs\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "5d8f93c797632ee75fce6752b6766f07f953bbed", "size": 4912, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/src/nmssm_twoloophiggs.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/nmssm_twoloophiggs.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/nmssm_twoloophiggs.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.6271186441, "max_line_length": 85, "alphanum_fraction": 0.7078583062, "num_tokens": 1507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.36296919862864746, "lm_q1q2_score": 0.2933035122967478}}
{"text": "/**\n * @file BayesianNetwork.hpp\n * @brief Implementation of the BayesianNetwork functions.\n * @author Ankit Srivastava <asrivast@gatech.edu>\n *\n * Copyright 2020 Georgia Institute of Technology\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n#ifndef DETAIL_BAYESIANNETWORK_HPP_\n#define DETAIL_BAYESIANNETWORK_HPP_\n\n#include \"utils/Logging.hpp\"\n\n#include <boost/graph/copy.hpp>\n#include <boost/graph/tiernan_all_cycles.hpp>\n\n\ntemplate <typename Var>\n/**\n  * @brief Helper class that implements the anti-parallel edge filter functionality.\n */\nclass BayesianNetwork<Var>::AntiParallelEdgeFilter {\npublic:\n  AntiParallelEdgeFilter(\n  ) : m_graph(nullptr)\n  {\n  }\n\n  AntiParallelEdgeFilter(\n    const GraphImpl& g\n  ) : m_graph(&g)\n  {\n  }\n\n  template <typename EdgeDescriptor>\n  bool\n  operator()(\n    const EdgeDescriptor& e\n  ) const\n  {\n    auto source = boost::source(e, *m_graph);\n    auto target = boost::target(e, *m_graph);\n    return !boost::edge(target, source, *m_graph).second;\n  }\n\nprivate:\n  const GraphImpl* m_graph;\n}; // class AntiParallelEdgeFilter\n\ntemplate <typename Var>\n/**\n * @brief Helper class for counting all the simple cycles that\n *        an edge is part of.\n */\nclass BayesianNetwork<Var>::EdgeCycleCounter {\npublic:\n  EdgeCycleCounter(\n    const Graph<BidirectionalAdjacencyList, VertexLabel, Var>& graph,\n    std::unordered_map<Edge, size_t, typename Edge::Hash>& counts\n  ) : m_graph(graph),\n      m_counts(counts)\n  {\n  }\n\n  template <typename Path, typename DirectedGraph>\n  void\n  cycle(\n    const Path& p,\n    const DirectedGraph& dg\n  )\n  {\n    using IndexMap = typename boost::property_map<DirectedGraph, boost::vertex_index_t>::const_type;\n    IndexMap indices = boost::get(boost::vertex_index, dg);\n    auto u = p.begin();\n    auto v = u+1;\n    while (v != p.end()) {\n      auto e = m_graph.getEdge(boost::get(indices, *u), boost::get(indices, *v));\n      if (m_counts.find(e) == m_counts.end()) {\n        m_counts[e] = 0;\n      }\n      m_counts[e] += 1;\n      ++u;\n      ++v;\n    }\n    v = p.begin();\n    auto e = m_graph.getEdge(boost::get(indices, *u), boost::get(indices, *v));\n    if (m_counts.find(e) == m_counts.end()) {\n      m_counts[e] = 0;\n    }\n    m_counts[e] += 1;\n  }\n\nprivate:\n  const Graph<BidirectionalAdjacencyList, VertexLabel, Var>& m_graph;\n  std::unordered_map<Edge, size_t, typename Edge::Hash>& m_counts;\n}; // class EdgeCycleCounter\n\ntemplate <typename Var>\n/**\n * @brief Constructs empty network with given labels as vertices.\n */\nBayesianNetwork<Var>::BayesianNetwork(\n  const std::vector<std::string>& varLabels\n) : Graph<BidirectionalAdjacencyList, VertexLabel, Var>(varLabels),\n    m_directed(this->filterAntiParallelEdges())\n{\n}\n\ntemplate <typename Var>\n/**\n * @brief Adds a directed or undirected edge between the vertices.\n */\nvoid\nBayesianNetwork<Var>::addEdge(\n  const Var source,\n  const Var target,\n  const bool undirected\n)\n{\n  this->addEdge(source, target);\n  if (undirected) {\n    this->addEdge(target, source);\n  }\n}\n\ntemplate <typename Var>\n/**\n * @brief Returns a filtered view of the current graph with the anti-parallel edges removed.\n */\ntypename BayesianNetwork<Var>::FilteredGraph\nBayesianNetwork<Var>::filterAntiParallelEdges(\n) const\n{\n  AntiParallelEdgeFilter bef(this->m_graph);\n  boost::filtered_graph<decltype(this->m_graph), AntiParallelEdgeFilter> fg(this->m_graph, bef);\n  return FilteredGraph(std::move(fg), this->m_idVertexMap);\n}\n\ntemplate <typename Var>\n/**\n * @brief Orients the edges of the network in accordance with v-structures.\n *\n * @param vStructures A tuple with all the discovered v-structures and the corresponding p-values.\n */\nvoid\nBayesianNetwork<Var>::applyVStructures(\n  std::vector<std::tuple<double, Var, Var, Var>>&& vStructures\n)\n{\n  // First sort the v-structures in the ascending order of the p-values\n  std::sort(vStructures.begin(), vStructures.end());\n  for (const auto& vs : vStructures) {\n    auto y = this->wrap(this->m_idVertexMap.at(std::get<1>(vs)));\n    auto x = this->wrap(this->m_idVertexMap.at(std::get<2>(vs)));\n    auto z = this->wrap(this->m_idVertexMap.at(std::get<3>(vs)));\n    // First check if the reverse edges still exist\n    if (!this->edgeExists(y, x) || !this->edgeExists(z, x)) {\n      LOG_MESSAGE(warning, \"* Could not apply v-structure %s -> %s <- %s (p-value = % g)\",\n                           y.property().label, x.property().label, z.property().label, std::get<0>(vs));\n      LOG_MESSAGE_IF(!this->edgeExists(y, x), debug, \"* %s - %s has already been oriented in the opposite direction\", y.property().label, x.property().label);\n      LOG_MESSAGE_IF(!this->edgeExists(z, x), debug, \"* %s - %s has already been oriented in the opposite direction\", x.property().label, z.property().label);\n      continue;\n    }\n    LOG_MESSAGE(info, \"+ Applying the v-structure %s -> %s <- %s (p-value = %g)\",\n                      y.property().label, x.property().label, z.property().label, std::get<0>(vs));\n    this->removeEdge(x, y);\n    this->removeEdge(x, z);\n  }\n}\n\ntemplate <typename Var>\n/**\n * @brief Function which checks if the network has directed cycles.\n */\nbool\nBayesianNetwork<Var>::hasDirectedCycles(\n) const\n{\n  return m_directed.hasCycles();\n}\n\ntemplate <typename Var>\n/**\n * @brief Counts the number of simple cycles that each edge is part of.\n */\nstd::unordered_map<typename BayesianNetwork<Var>::Edge, size_t, typename BayesianNetwork<Var>::Edge::Hash>\nBayesianNetwork<Var>::countEdgeCycles(\n) const\n{\n  // Copy the directed view of the graph to a directed graph\n  typename DirectedGraph<VertexLabel, Var>::Impl dg;\n  boost::copy_graph(*m_directed, dg);\n  // Record all the counts\n  std::unordered_map<Edge, size_t, typename Edge::Hash> counts;\n  EdgeCycleCounter ecc(*this, counts);\n  boost::tiernan_all_cycles(dg, ecc);\n  return counts;\n}\n\ntemplate <typename Var>\n/**\n * @brief Function which breaks directed cycles in the network by reversing\n *        the direction of the edge which is part of most cycles.\n */\nvoid\nBayesianNetwork<Var>::breakDirectedCycles(\n)\n{\n  Edge e;\n  auto maxCount = 0u;\n  for (const auto& cc : this->countEdgeCycles()) {\n    if (cc.second > maxCount) {\n      e = cc.first;\n      maxCount = cc.second;\n    }\n  }\n  if (maxCount > 0) {\n    auto source = *e.source();\n    auto target = *e.target();\n    // Reverse the edge\n    LOG_MESSAGE(info, \"* Reversing the direction of edge %s -> %s\", e.source().property().label, e.target().property().label);\n    this->removeEdge(source, target);\n    this->addEdge(target, source);\n  }\n}\n\ntemplate <typename Var>\n/**\n * @brief Function which orients an edge, if it doesn't create directed cycles.\n *\n * @param e The edge to be removed.\n *\n * @returns true if any changes were made, otherwise returns false.\n */\nbool\nBayesianNetwork<Var>::removeEdgeAcyclic(\n  Edge&& e\n)\n{\n  auto source = e.source();\n  auto target = e.target();\n  this->removeEdge(std::move(e));\n  if (m_directed.hasCycles(*source)) {\n    this->addEdge(source, target);\n    return false;\n  }\n  return true;\n}\n\ntemplate <typename Var>\n/**\n * @brief Function which checks if the undirected edge Y - Z can be\n *        oriented as Y -> Z to prevent new unshielded colliders.\n */\nbool\nBayesianNetwork<Var>::unshieldedColliderRule(\n  const Vertex& y,\n  const Vertex& z\n) const\n{\n  if (m_directed.wrap(*y).inDegree() == 0) {\n    return false;\n  }\n  bool potential = false;\n  // Examine all the edges incoming into Y for a potential X\n  for (const auto inY : m_directed.wrap(*y).inEdges()) {\n    auto x = inY.source();\n    // Check if an X exists such that no edge exists between X and Z\n    if (!(this->edgeExists(*z, *x) || this->edgeExists(*x, *z))) {\n      potential = true;\n      break;\n    }\n  }\n  return potential;\n}\n\ntemplate <typename Var>\n/**\n * @brief Function which checks if the undirected edge X - Z can be\n *        oriented as X -> Z to prevent directed cycles.\n */\nbool\nBayesianNetwork<Var>::acyclicityRule(\n  const Vertex& x,\n  const Vertex& z\n) const\n{\n  // Therefore, try to apply the rule by setting the source as Z and the target as X\n  bool orientEdge = false;\n  // Iterate over all the outgoing neighbors of X for a potential Y\n  for (const auto y : m_directed.wrap(*x).outNeighbors()) {\n    if (m_directed.edgeExists(*y, *z)) {\n      // Orient this edge as X -> Z\n      // ...as long as it does not create an immorality\n      orientEdge = true;\n      break;\n    }\n  }\n  bool immorality = false;\n  if (orientEdge) {\n    for (const auto inZ : m_directed.wrap(*z).inEdges()) {\n      auto w = inZ.source();\n      // Check if there is an edge between the source of another incoming edge into Z and X\n      if (!(this->edgeExists(*x, *w) || this->edgeExists(*w, *x))) {\n        // If no such edge exists, then the rule can not be applied because an immorality will be created\n        immorality = true;\n        break;\n      }\n    }\n  }\n  return (orientEdge && !immorality);\n}\n\ntemplate <typename Var>\n/**\n * @brief Function which checks if the undirected edge X - Z can be\n *        oriented as X -> Z by applying the hybrid rule.\n */\nbool\nBayesianNetwork<Var>::hybridRule(\n  const Vertex& x,\n  const Vertex& z\n) const\n{\n  auto countY = 0u;\n  // Iterate over all the incoming neighbors of Z for potential Y\n  for (const auto inZ : m_directed.wrap(*z).inEdges()) {\n    auto y = inZ.source();\n    // Check if an undirected edge exists between X and Y\n    if (this->edgeExists(*x, *y) && this->edgeExists(*y, *x)) {\n      ++countY;\n    }\n  }\n  // The rule can be applied only if at least two Ys were found\n  return (countY >= 2);\n}\n\ntemplate <typename Var>\n/**\n * @brief Top level function for orienting edges using Meek's rules.\n *\n * @returns true if any changes were made, otherwise returns false.\n */\nbool\nBayesianNetwork<Var>::applyMeekRules(\n)\n{\n  bool changed = false;\n  auto isCollider = [] (const Vertex& v) { return (v.inDegree() > v.outDegree()) &&\n                                                  (v.inDegree() - v.outDegree() > 1); };\n  // Iterate over all the undirected edges\n  for (auto e : this->antiParallelEdges()) {\n    // Check if the anti-parallel edge still exists\n    if (!e.hasAntiParallel()) {\n      continue;\n    }\n    // See if this direction of the anti-parallel edge can be removed\n    // Therefore, check if the rules can be applied to the reverse direction\n    auto source = e.source();\n    auto target = e.target();\n    if (isCollider(source) && isCollider(target)) {\n      LOG_MESSAGE_IF(*source < *target, info, \"* Fixing edge %s - %s because of conflicting v-structures\", source.property().label, target.property().label);\n      continue;\n    }\n    if (this->unshieldedColliderRule(target, source)) { // Apply Meek's Rule 1\n      if (this->removeEdgeAcyclic(std::move(e))) {\n        LOG_MESSAGE(info, \"* Directing edge %s -> %s (R1: unshielded colliders)\", target.property().label, source.property().label);\n        changed = true;\n      }\n    }\n    else if (this->acyclicityRule(target, source)) { // Apply Meek's Rule 2\n      if (this->removeEdgeAcyclic(std::move(e))) {\n        LOG_MESSAGE(info, \"* Directing edge %s -> %s (R2: acyclicity)\", target.property().label, source.property().label);\n        changed = true;\n      }\n    }\n    else if (this->hybridRule(target, source)) { // Apply Meek's Rule 3\n      if (this->removeEdgeAcyclic(std::move(e))) {\n        LOG_MESSAGE(info, \"* Directing edge %s -> %s (R3: hybrid)\", target.property().label, source.property().label);\n        changed = true;\n      }\n    }\n  }\n  return changed;\n}\n\ntemplate <typename Var>\n/**\n * @brief Top level function for writing the network in graphviz format.\n *\n * @param fileName Name of the file to which the network should be written.\n */\nvoid\nBayesianNetwork<Var>::writeGraphviz(\n  const std::string& fileName\n) const\n{\n  std::ofstream out(fileName);\n  // Check if there are any directed edges in the graph\n  // If not, write the graph as an undirected graph\n  auto directed = false;\n  for (const auto e : m_directed.edges()) {\n    std::ignore = e;\n    directed = true;\n    break;\n  }\n  out << (directed ? \"digraph\" : \"graph\") << \" {\" << std::endl;\n  for (const auto v : this->vertices()) {\n    out << \"  \";\n    out << boost::escape_dot_string(v.property().label);\n    out << \" ;\" << std::endl;\n  }\n  auto delimiter = directed ? \" -> \" : \" -- \";\n  for (const auto e : this->edges()) {\n    bool write = false;\n    if (directed && !this->edgeExists(e.target(), e.source())) {\n      out << \"  edge [dir=forward] \";\n      write = true;\n    }\n    else if (e.source() < e.target()) {\n      out << \"  edge [dir=none] \";\n      write = true;\n    }\n    if (write) {\n      out << boost::escape_dot_string(e.source().property().label);\n      out << delimiter;\n      out << boost::escape_dot_string(e.target().property().label);\n      out << \" ;\" << std::endl;\n    }\n  }\n  out << \"}\" << std::endl;\n}\n\n#endif // DETAIL_BAYESIANNETWORK_HPP\n", "meta": {"hexsha": "0fbb41b57676c5a216c7c78a9066f7b887d5376c", "size": 13364, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "detail/BayesianNetwork.hpp", "max_stars_repo_name": "NickCao/ramBLe", "max_stars_repo_head_hexsha": "21284debee87592eeb8ab903ef57bea337ba6698", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2020-04-22T16:01:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T02:35:42.000Z", "max_issues_repo_path": "detail/BayesianNetwork.hpp", "max_issues_repo_name": "NickCao/ramBLe", "max_issues_repo_head_hexsha": "21284debee87592eeb8ab903ef57bea337ba6698", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "detail/BayesianNetwork.hpp", "max_forks_repo_name": "NickCao/ramBLe", "max_forks_repo_head_hexsha": "21284debee87592eeb8ab903ef57bea337ba6698", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-07-11T04:48:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-13T12:59:54.000Z", "avg_line_length": 29.9641255605, "max_line_length": 158, "alphanum_fraction": 0.6539958096, "num_tokens": 3547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.29325900539281835}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   Utility_AtomicMassUnit.hpp\n//! \\author Alex Robinson\n//! \\brief  The atomic mass unit\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef UTILITY_ATOMIC_MASS_UNIT_HPP\n#define UTILITY_ATOMIC_MASS_UNIT_HPP\n\n// Boost Includes\n#include <boost/units/systems/si/mass.hpp>\n#include <boost/units/base_unit.hpp>\n#include <boost/units/conversion.hpp>\n\nnamespace Utility{\n\nnamespace Units{\n\n//! The atomic mass base unit\nstruct AtomicMassBaseUnit : public boost::units::base_unit<AtomicMassBaseUnit,boost::units::mass_dimension,4>\n{\n  static const char* name() { return \"atomic mass unit\"; }\n  static const char* symbol() { return \"amu\"; }\n};\n\n//! The atomic mass unit\ntypedef AtomicMassBaseUnit::unit_type AtomicMass;\n\nBOOST_UNITS_STATIC_CONSTANT( amu, AtomicMass );\n\n} // end Units namespace\n\n} // end Utility namespace\n\n// From codata 2014\nBOOST_UNITS_DEFINE_CONVERSION_FACTOR( Utility::Units::AtomicMassBaseUnit, boost::units::si::mass, double, 1.660539040e-27 );\nBOOST_UNITS_DEFINE_CONVERSION_FACTOR( boost::units::si::mass, Utility::Units::AtomicMassBaseUnit, double, 1.0/1.660539040e-27 );\n\nBOOST_UNITS_DEFAULT_CONVERSION( Utility::Units::AtomicMassBaseUnit, boost::units::si::mass );\n\n#endif // end UTILITY_ATOMIC_MASS_UNIT_HPP\n\n//---------------------------------------------------------------------------//\n// end Utility_AtomicMassUnit.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "8c0ca29d87598d6dd86aa3288cbabb65e4c998b2", "size": 1557, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/utility/core/src/Utility_AtomicMassUnit.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/core/src/Utility_AtomicMassUnit.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/core/src/Utility_AtomicMassUnit.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": 32.4375, "max_line_length": 128, "alphanum_fraction": 0.6095054592, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2932589980076071}}
{"text": "/**\n * \\file\n *\n * \\author Nicholas J. Curtis\n * \\date 04/29/2016\n *\n * \\brief Defines an interface for boost's runge_kutta_fehlberg78 solver\n *\n*/\n\n//wrapper code\n#include \"rk78_typedefs.hpp\"\n\n//boost includes\n#include <boost/numeric/odeint/integrate/integrate_adaptive.hpp>\nextern \"C\" {\n#include \"solver.h\"\n}\n\n#ifdef GENERATE_DOCS\nnamespace rk78 {\n#endif\n\nextern std::vector<state_type*> state_vectors;\nextern std::vector<rhs_eval*> evaluators;\nextern std::vector<controller> controllers;\n\nextern \"C\" void intDriver(const int, const double, const double, const double*, double*);\n\n#ifdef STIFFNESS_MEASURE\n    extern std::vector<double> max_stepsize;\n    controlled_step_result test_step(int index, const state_type& y, const double t, state_type& y_out, const double dt)\n    {\n        try\n        {\n            double t_copy = t;\n            double dt_copy = dt;\n            return controllers[index]->try_step(*evaluators[index], y, t_copy, y_out, dt_copy);\n        }\n        catch(...)\n        {\n            return fail;\n        }\n    }\n#endif\n\n/**\n * \\brief Integration driver for the CPU integrators\n * \\param[in]       NUM         the number of IVPs to solve\n * \\param[in]       t           the current IVP time\n * \\param[in]       t_end       the time to integrate the IVP to\n * \\param[in]       pr_global   the pressure value for the IVPs\n * \\param[in, out]  y_global    the state vectors\n *\n * The integration driver for the RK78 solver\n */\nvoid intDriver (const int NUM, const double t, const double t_end,\n                const double *pr_global, double *y_global)\n{\n    #ifdef STIFFNESS_MEASURE\n    max_stepsize.clear();\n    max_stepsize.resize(NUM, 0.0);\n    #endif\n\n\tint tid = 0;\n#ifdef STIFFNESS_MEASURE\n    #pragma omp parallel for shared(state_vectors, evaluators, controllers, max_stepsize) private(tid)\n#else\n\t#pragma omp parallel for shared(state_vectors, evaluators, controllers) private(tid)\n#endif\n    for (tid = 0; tid < NUM; ++tid) {\n    \tint index = omp_get_thread_num();\n\n        // local array with initial values\n        state_type& vec = *state_vectors[index];\n        evaluators[index]->set_state_var(pr_global[tid]);\n\n        // load local array with initial values from global array\n        for (int i = 0; i < NSP; i++)\n        {\n            vec[i] = y_global[tid + i * NUM];\n        }\n\n#ifndef STIFFNESS_MEASURE\n        integrate_adaptive(controllers[index],\n            *evaluators[index], vec, t, t_end, t_end - t);\n#else\n        double tol = 1e-15;\n        state_type y_copy(vec);\n        //do a binary search to find the maximum stepsize\n        double left_size = 1.0;\n        while (test_step(index, vec, t, y_copy, left_size) == success)\n        {\n            left_size *= 10.0;\n        }\n        double right_size = 1e-20;\n        while (test_step(index, vec, t, y_copy, right_size) == fail)\n        {\n            right_size /= 10.0;\n        }\n        double delta = 1.0;\n        double mid = 0;\n        while (delta > tol) {\n            mid = (left_size + right_size) / 2.0;\n            controlled_step_result result = test_step(index, vec, t, y_copy, mid);\n            if (result == fail) {\n                //mid becomes the new left\n                delta = fabs(left_size - mid) / left_size;\n                left_size = mid;\n            }\n            else{\n                delta = fabs(right_size - mid) / right_size;\n                right_size = mid;\n            }\n        }\n        max_stepsize[tid] = mid;\n#endif\n\n        // update global array with integrated values\n        for (int i = 0; i < NSP; i++)\n        {\n            y_global[tid + i * NUM] = vec[i];\n        }\n\n    }\n}\n\n#ifdef GENERATE_DOCS\n}\n#endif\n", "meta": {"hexsha": "8668b00072fad763adaaf363c947a81febcdf7b6", "size": 3663, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rk78/solver_rk78.cpp", "max_stars_repo_name": "arghdos/accelerInt", "max_stars_repo_head_hexsha": "d66b615d61438be3caa76fa178fb8a913bed77c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-01-04T12:40:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T12:35:45.000Z", "max_issues_repo_path": "rk78/solver_rk78.cpp", "max_issues_repo_name": "arghdos/accelerInt", "max_issues_repo_head_hexsha": "d66b615d61438be3caa76fa178fb8a913bed77c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2017-03-02T19:15:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-15T10:50:14.000Z", "max_forks_repo_path": "rk78/solver_rk78.cpp", "max_forks_repo_name": "arghdos/accelerInt", "max_forks_repo_head_hexsha": "d66b615d61438be3caa76fa178fb8a913bed77c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-06-01T01:38:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T13:57:17.000Z", "avg_line_length": 27.9618320611, "max_line_length": 120, "alphanum_fraction": 0.5921375921, "num_tokens": 929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160666, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2931383555553517}}
{"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_HAUSDORFF_DISTANCE\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(void)\n        {\n#ifdef ENABLE_PARALLEL_HAUSDORFF_DISTANCE\n        #if defined(_OPENMP)\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#else\n            return 1;\n#endif\n        }\n\n    public:\n\n        template<typename FirstDatatype, typename SecondDatatype, typename FirstAllocator=std::allocator<FirstDatatype>, typename SecondAllocator=std::allocator<SecondDatatype>>\n        static double ComputeDistance(const std::vector<FirstDatatype, FirstAllocator>& first_distribution, const std::vector<SecondDatatype, SecondAllocator>& second_distribution, const std::function<double(const FirstDatatype&, const SecondDatatype&)>& distance_fn)\n        {\n            // Compute the Hausdorff distance - the \"maximum minimum\" distance\n            std::vector<double> per_thread_storage(GetNumOMPThreads(), 0.0);\n#ifdef ENABLE_PARALLEL_HAUSDORFF_DISTANCE\n            #pragma omp parallel for\n#endif\n            for (size_t idx = 0; idx < first_distribution.size(); idx++)\n            {\n                const FirstDatatype& first = first_distribution[idx];\n                double minimum_distance = INFINITY;\n                for (size_t jdx = 0; jdx < second_distribution.size(); jdx++)\n                {\n                    const SecondDatatype& 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_HAUSDORFF_DISTANCE\n                #if defined(_OPENMP)\n                const size_t current_thread_id = (size_t)omp_get_thread_num();\n                #else\n                const size_t current_thread_id = 0;\n                #endif\n#else\n                const size_t current_thread_id = 0;\n#endif\n                if (minimum_distance > per_thread_storage[current_thread_id])\n                {\n                    per_thread_storage[current_thread_id] = minimum_distance;\n                }\n            }\n            double maximum_minimum_distance = 0.0;\n            for (size_t idx = 0; idx < per_thread_storage.size(); idx++)\n            {\n                const double temp_minimum_distance = per_thread_storage[idx];\n                if (temp_minimum_distance > maximum_minimum_distance)\n                {\n                    maximum_minimum_distance = temp_minimum_distance;\n                }\n            }\n            return maximum_minimum_distance;\n        }\n    };\n}\n#endif // SIMPLE_HAUSDORFF_DISTANCE_HPP\n", "meta": {"hexsha": "baf09a322f52d79c8e9f711785f2135185b63873", "size": 3292, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Modules/planning/FastPlanner/plan_env/ThirdParty/arc_utilities/include/arc_utilities/simple_hausdorff_distance.hpp", "max_stars_repo_name": "473867143/Prometheus", "max_stars_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1217.0, "max_stars_repo_stars_event_min_datetime": "2020-07-02T13:15:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:17:44.000Z", "max_issues_repo_path": "Modules/planning/FastPlanner/plan_env/ThirdParty/arc_utilities/include/arc_utilities/simple_hausdorff_distance.hpp", "max_issues_repo_name": "473867143/Prometheus", "max_issues_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 167.0, "max_issues_repo_issues_event_min_datetime": "2020-07-12T15:35:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:57:40.000Z", "max_forks_repo_path": "Modules/planning/FastPlanner/plan_env/ThirdParty/arc_utilities/include/arc_utilities/simple_hausdorff_distance.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": 34.2916666667, "max_line_length": 267, "alphanum_fraction": 0.6084447145, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.2931383555553517}}
{"text": "#ifndef INCLUDE_SWIFT_VIO_IMU_ERROR_MODELS_HPP_\n#define INCLUDE_SWIFT_VIO_IMU_ERROR_MODELS_HPP_\n\n// Generic methods specific to each IMU model is encapsulated in the following classes.\n// These models are to be used in constructing ceres::SizedCostFunction or\n// ceres::AutoDiffCostFunction. Both require constant parameter block sizes at compile time.\n// This is why we cannot use polymorphism for representing IMU models.\n\n// The model parameter data are kept in the ImuModel class which\n// is initialized and updated in the estimator.\n\n// The IMU input reference frame or sensor frame denoted by S is affixed to\n// the accelerometer triad, and its x-axis aligned to the accelerometer in the x direction.\n// Its origin is at the intersection of the three accelerometers.\n// Tts y-axis in the plane spanned by the two accelerometers at x and y\n// direction while being close to the accelerometer at y-direction.\n// The sensor rig body frame denoted by B is used to express the motion of the rig.\n// It varies depending on the IMU model.\n\n#include <vector>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <okvis/ModelSwitch.hpp>\n\nnamespace swift_vio {\nstatic const int kBgBaDim = 6; // bg ba\n\ntemplate <typename T>\nvoid vectorToLowerTriangularMatrix(const T* data, int startIndex, Eigen::Matrix<T, 3, 3>* mat33) {\n  (*mat33)(0, 0) = data[startIndex];\n  (*mat33)(0, 1) = 0;\n  (*mat33)(0, 2) = 0;\n  (*mat33)(1, 0) = data[startIndex + 1];\n  (*mat33)(1, 1) = data[startIndex + 2];\n  (*mat33)(1, 2) = 0;\n  (*mat33)(2, 0) = data[startIndex + 3];\n  (*mat33)(2, 1) = data[startIndex + 4];\n  (*mat33)(2, 2) = data[startIndex + 5];\n}\n\ntemplate <typename T>\nvoid vectorToMatrix(const T* data, int startIndex, Eigen::Matrix<T, 3, 3>* mat33) {\n  (*mat33)(0, 0) = data[startIndex];\n  (*mat33)(0, 1) = data[startIndex + 1];\n  (*mat33)(0, 2) = data[startIndex + 2];\n  (*mat33)(1, 0) = data[startIndex + 3];\n  (*mat33)(1, 1) = data[startIndex + 4];\n  (*mat33)(1, 2) = data[startIndex + 5];\n  (*mat33)(2, 0) = data[startIndex + 6];\n  (*mat33)(2, 1) = data[startIndex + 7];\n  (*mat33)(2, 2) = data[startIndex + 8];\n}\n\ntemplate <typename T>\nvoid invertLowerTriangularMatrix(const T* data, int startIndex, Eigen::Matrix<T, 3, 3>* mat33) {\n  //  syms a b c d e f positive\n  //  g = [a, 0, 0, b, c, 0, d, e, f]\n  //  [ a, 0, 0]\n  //  [ b, c, 0]\n  //  [ d, e, f]\n  //  inv(g)\n  //  [                 1/a,        0,   0]\n  //  [            -b/(a*c),      1/c,   0]\n  //  [ (b*e - c*d)/(a*c*f), -e/(c*f), 1/f]\n  (*mat33)(0, 0) = 1 / data[startIndex];\n  (*mat33)(0, 1) = 0;\n  (*mat33)(0, 2) = 0;\n  (*mat33)(1, 0) = - data[startIndex + 1] / (data[startIndex] * data[startIndex + 2]);\n  (*mat33)(1, 1) = 1 / data[startIndex + 2];\n  (*mat33)(1, 2) = 0;\n  (*mat33)(2, 0) = (data[startIndex + 1] * data[startIndex + 4] -\n      data[startIndex + 2] * data[startIndex + 3]) /\n      (data[startIndex] * data[startIndex + 2] * data[startIndex + 5]);\n  (*mat33)(2, 1) = - data[startIndex + 4] / (data[startIndex + 2] * data[startIndex + 5]);\n  (*mat33)(2, 2) = 1 / data[startIndex + 5];\n}\n\n/**\n * @brief The Imu_BG_BA class\n * The body frame is identical to the classic IMU sensor frame which has origin\n * at the accelerometer intersection, and x along x-accelrometer and y in the\n * plane spanned by the x- and y-accelerometer.\n * The accelerometer triad and the gyroscope triad are free of scaling error and misalignment.\n */\nclass Imu_BG_BA {\n public:\n  static const int kModelId = 0;\n  static const size_t kGlobalDim = kBgBaDim;\n  static const size_t kAugmentedDim = 0;\n\n  /**\n   * @brief getAugmentedDim\n   * @return dim of all the augmented params.\n   */\n  static inline int getAugmentedDim() { return kAugmentedDim; }\n  /**\n   * @brief getMinimalDim\n   * @return minimal dim of all the params.\n   */\n  static inline int getMinimalDim() { return kGlobalDim; }\n  /**\n   * @brief getAugmentedMinimalDim\n   * @return minimal dim of all augmented params.\n   */\n  static inline int getAugmentedMinimalDim() { return kAugmentedDim; }\n  /**\n   * get nominal values for augmented params.\n   */\n  template <typename T>\n  static Eigen::Matrix<T, kAugmentedDim, 1> getNominalAugmentedParams() {\n    return Eigen::Matrix<T, kAugmentedDim, 1>::Zero();\n  }\n  /**\n   * predict IMU measurement from values in the body frame.\n   * This function is used for testing purposes.\n   */\n  template <typename T>\n  static void\n  predict(const Eigen::Matrix<T, 3, 1> &bg, const Eigen::Matrix<T, 3, 1> &ba,\n          const Eigen::Matrix<T, Eigen::Dynamic, 1> & /*extraParams*/,\n          const Eigen::Matrix<T, 3, 1> &w_b, const Eigen::Matrix<T, 3, 1> &a_b,\n          Eigen::Matrix<T, 3, 1> *w, Eigen::Matrix<T, 3, 1> *a) {\n    *a = a_b + ba;\n    *w = w_b + bg;\n  }\n  /**\n   * correct IMU measurement to the body frame.\n   * This function is used by the ceres::CostFunction.\n   * @param[in] params bg ba and augmented Euclidean params.\n   * @param[in] q_gyro_i orientation from the accelerometer triad input reference frame,\n   *     i.e., the IMU sensor frame to the gyro triad input reference frame.\n   * @param[in] w, a angular velocity and linear acceleration measured by the IMU.\n   * @param[out] w_b, a_b angular velocity and linear acceleration in the body frame.\n   */\n  template <typename T>\n  static void\n  correct(const Eigen::Matrix<T, 3, 1> &bg, const Eigen::Matrix<T, 3, 1> &ba,\n          const Eigen::Matrix<T, Eigen::Dynamic, 1> & /*params*/,\n          const Eigen::Matrix<T, 3, 1> &w, const Eigen::Matrix<T, 3, 1> &a,\n          Eigen::Matrix<T, 3, 1> *w_b, Eigen::Matrix<T, 3, 1> *a_b) {\n    *a_b = a - ba;\n    *w_b = w - bg;\n  }\n\n  static Eigen::VectorXd computeAugmentedParamsError(\n      const Eigen::VectorXd& /*params*/) {\n      return Eigen::VectorXd(0);\n  }\n};\n\n/**\n * @brief The Imu_BG_BA_TG_TS_TA class\n * The body frame is the same as the IMU sensor frame which is\n * defined relative to an external sensor, e.g., the camera. Its \n * orientation is fixed to the nominal value of R_SC0 and its origin is at \n * the accelerometer intersection. Thus both accelerometer triad and \n * gyroscope triad need to account for scaling effect (3), misalignment (3),\n * relative orientation (4, minimal 3) to the body frame.\n * This model also considers the g-sensitivity (9) of the gyroscope triad.\n * In other words, the remaining misalignment between the orthogonal\n *  accelerometer input reference frame (A) and the C frame is\n * absorbed into T_a, the IMU accelerometer misalignment matrix.\n *\n * IMU model\n * w_m = T_g * w_B + T_s * a_B + b_w + n_w\n * a_m = T_a * a_B + b_a + n_a = S * M * R_AB * a_B + b_a + n_a\n *\n * The A frame has origin at the accelerometers intersection and x-axis aligned\n * with accelerometer x.\n */\nclass Imu_BG_BA_TG_TS_TA {\n public:\n  static const int kModelId = 1;\n  static const size_t kAugmentedDim = 27;\n  static const size_t kGlobalDim = kAugmentedDim + kBgBaDim;\n\n  static inline int getAugmentedDim() { return kAugmentedDim; }\n  static inline int getMinimalDim() { return kGlobalDim; }\n  static inline int getAugmentedMinimalDim() { return kAugmentedDim; }\n  template <typename T>\n  static Eigen::Matrix<T, kAugmentedDim, 1> getNominalAugmentedParams() {\n    Eigen::Matrix<T, 9, 1> eye;\n    eye << 1, 0, 0, 0, 1, 0, 0, 0, 1;\n    Eigen::Matrix<T, kAugmentedDim, 1> augmentedParams;\n    augmentedParams.template head<9>() = eye;\n    augmentedParams.template tail<9>() = eye;\n    return augmentedParams;\n  }\n\n  template <typename T>\n  static void\n  predict(const Eigen::Matrix<T, 3, 1> &bg, const Eigen::Matrix<T, 3, 1> &ba,\n          const Eigen::Matrix<T, Eigen::Dynamic, 1> &params,\n          const Eigen::Matrix<T, 3, 1> &w_b, const Eigen::Matrix<T, 3, 1> &a_b,\n          Eigen::Matrix<T, 3, 1> *w, Eigen::Matrix<T, 3, 1> *a) {\n    Eigen::Matrix<T, 3, 3> T_g;\n    vectorToMatrix<T>(params.data(), 0, &T_g);\n    Eigen::Matrix<T, 3, 3> T_s;\n    vectorToMatrix<T>(params.data(), 9, &T_s);\n    Eigen::Matrix<T, 3, 3> T_a;\n    vectorToMatrix<T>(params.data(), 18, &T_a);\n    *a = T_a * a_b + ba;\n    *w = T_g * w_b + T_s * a_b + bg;\n  }\n\n  template <typename T>\n  static void\n  correct(const Eigen::Matrix<T, 3, 1> &bg, const Eigen::Matrix<T, 3, 1> &ba,\n          const Eigen::Matrix<T, Eigen::Dynamic, 1> &params,\n          const Eigen::Matrix<T, 3, 1> &w, const Eigen::Matrix<T, 3, 1> &a,\n          Eigen::Matrix<T, 3, 1> *w_b, Eigen::Matrix<T, 3, 1> *a_b) {\n    Eigen::Matrix<T, 3, 3> T_g;\n    vectorToMatrix<T>(params.data(), 0, &T_g);\n    Eigen::Matrix<T, 3, 3> T_s;\n    vectorToMatrix<T>(params.data(), 9, &T_s);\n    Eigen::Matrix<T, 3, 3> T_a;\n    vectorToMatrix<T>(params.data(), 18, &T_a);\n    Eigen::Matrix<T, 3, 3> inv_T_g = T_g.inverse();\n    Eigen::Matrix<T, 3, 3> inv_T_a = T_a.inverse();\n    *a_b = inv_T_a * (a - ba);\n    *w_b = inv_T_g * (w - bg - T_s * (*a_b));\n  }\n\n  static Eigen::VectorXd computeAugmentedParamsError(\n      const Eigen::VectorXd& params) {\n      Eigen::VectorXd residual = params;\n      Eigen::Matrix<double, 9, 1> eye;\n      eye << 1, 0, 0, 0, 1, 0, 0, 0, 1;\n      residual.head<9>() -= eye;\n      residual.tail<9>() -= eye;\n      return residual;\n  }\n};\n\n/**\n * @brief The ScaledMisalignedImu class\n * The body frame is the same as the classic IMU sensor frame. So the gyroscope triad\n * needs to consider scaling effect(3), misalignment(3), and relative \n * orientation(4, minimal 3) to the IMU sensor frame, and g-sensitivity (9)\n * whereas the accelerometer triad needs to consider scaling effect (3) and\n * misalignment (3). The lever arm(size) effects are ignored.\n * Implemented according to \"Extending Kalibr\".\n */\nclass ScaledMisalignedImu {\n public:\n  static const int kModelId = 2;\n  static const size_t kSMDim = 6;\n  static const size_t kSensitivityDim = 9;\n  static const size_t kAugmentedDim = kSMDim + kSensitivityDim + kSMDim + 4;\n  static const size_t kGlobalDim = kAugmentedDim + kBgBaDim;\n  static inline int getAugmentedDim() { return kAugmentedDim; }\n  static inline int getMinimalDim() { return kGlobalDim - 1; }\n  static inline int getAugmentedMinimalDim() { return kAugmentedDim - 1; }\n  template <typename T>\n  static Eigen::Matrix<T, kAugmentedDim, 1> getNominalAugmentedParams() {\n    Eigen::Matrix<T, kAugmentedDim, 1> nominalValues = Eigen::Matrix<T, kAugmentedDim, 1>::Zero();\n    nominalValues[0] = T(1.0);\n    nominalValues[2] = T(1.0);\n    nominalValues[5] = T(1.0);\n    nominalValues[6 + 9] = T(1.0);\n    nominalValues[6 + 9 + 2] = T(1.0);\n    nominalValues[6 + 9 + 5] = T(1.0);\n    nominalValues[kAugmentedDim - 1] = T(1.0);  // quaternion in xyzw format for R_gyro_i.\n    return nominalValues;\n  }\n\n  /**\n   * nearly 1:1 implementation of\n   * https://github.com/ethz-asl/kalibr/blob/master/aslam_offline_calibration/kalibr/python/kalibr_imu_camera_calibration/IccSensors.py#L1033-L1049\n   * w_b angular velocity in body frame at time tk.\n   * w_dot_b angular acceleration in body frame at time tk.\n   * a_w linear acceleration at tk.\n   * r_b acceleration triad origin, i.e., the sensor frame origin, coordinates expressed in the body frame.\n   * params gyro bias, accelerometer bias, gyro Scaling*Misalignment, gyro g-sensitivity, accelerometer Scaling*Misalignment.\n   * C_gyro_i the relative orientation from the accelerometer triad frame, i.e., the IMU sensor frame to the gyro triad frame.\n   */\n  template <typename T>\n  static void predictAngularVelocity(\n      const Eigen::Matrix<T, 3, 1> &bg, const Eigen::Matrix<T, 3, 1> & /*ba*/,\n      const Eigen::Matrix<T, Eigen::Dynamic, 1> &params,\n      const Eigen::Quaternion<T> &q_w_b, const Eigen::Matrix<T, 3, 1> &w_b,\n      const Eigen::Matrix<T, 3, 1> &a_w, const Eigen::Matrix<T, 3, 1> &g_w,\n      Eigen::Matrix<T, 3, 1> *w) {\n    Eigen::Matrix<T, 3, 1> w_dot_b = Eigen::Matrix<T, 3, 1>::Zero();\n    Eigen::Matrix<T, 3, 3> C_b_w =\n        q_w_b.template toRotationMatrix().transpose();\n    Eigen::Matrix<T, 3, 1> r_b =\n        Eigen::Matrix<T, 3, 1>::Zero(); // Assume the 3 accelerometers are at\n                                        // the origin of the body frame.\n    Eigen::Matrix<T, 3, 1> a_b =\n        C_b_w * (a_w - g_w) + w_dot_b.cross(r_b) + w_b.cross(w_b.cross(r_b));\n\n    Eigen::Matrix<T, 3, 3> C_i_b =\n        Eigen::Matrix<T, 3, 3>::Identity(); // The IMU sensor frame coincides\n                                            // the accelerometer triad frame.\n    Eigen::Map<const Eigen::Quaternion<T>> q_gyro_i(params.data() +\n                                                    kAugmentedDim - 4);\n    Eigen::Matrix<T, 3, 3> C_gyro_i = q_gyro_i.template toRotationMatrix();\n    Eigen::Matrix<T, 3, 3> C_gyro_b = C_gyro_i * C_i_b;\n\n    Eigen::Matrix<T, 3, 3> M_gyro;\n    vectorToLowerTriangularMatrix<T>(params.data(), 0, &M_gyro);\n    Eigen::Matrix<T, 3, 3> M_accel_gyro;\n    vectorToMatrix<T>(params.data(), kSMDim, &M_accel_gyro);\n    *w = M_gyro * (C_gyro_b * w_b) + M_accel_gyro * (C_gyro_b * a_b) + bg;\n  }\n\n  /**\n   * nearly 1:1 implementation of\n   * https://github.com/ethz-asl/kalibr/blob/master/aslam_offline_calibration/kalibr/python/kalibr_imu_camera_calibration/IccSensors.py#L989-L1000\n   */\n  template <typename T>\n  static void predictLinearAcceleration(\n      const Eigen::Matrix<T, 3, 1> &/*bg*/, const Eigen::Matrix<T, 3, 1> &ba,\n      const Eigen::Matrix<T, Eigen::Dynamic, 1> &params,\n      const Eigen::Quaternion<T> &q_w_b, const Eigen::Matrix<T, 3, 1> &w_b,\n      const Eigen::Matrix<T, 3, 1> &a_w, const Eigen::Matrix<T, 3, 1> &g_w,\n      Eigen::Matrix<T, 3, 1> *a) {\n    Eigen::Matrix<T, 3, 1> w_dot_b = Eigen::Matrix<T, 3, 1>::Zero();\n    Eigen::Matrix<T, 3, 3> C_b_w =\n        q_w_b.template toRotationMatrix().transpose();\n\n    Eigen::Matrix<T, 3, 3> M_accel;\n    vectorToLowerTriangularMatrix<T>(params.data(), kSMDim + kSensitivityDim,\n                                     &M_accel);\n\n    Eigen::Matrix<T, 3, 1> r_b =\n        Eigen::Matrix<T, 3, 1>::Zero(); // Assume the 3 accelerometers are at\n                                        // the origin of the body frame.\n    Eigen::Matrix<T, 3, 1> a_b =\n        C_b_w * (a_w - g_w) + w_dot_b.cross(r_b) + w_b.cross(w_b.cross(r_b));\n\n    Eigen::Matrix<T, 3, 3> C_i_b =\n        Eigen::Matrix<T, 3, 3>::Identity(); // The IMU sensor frame coincides\n                                            // the accelerometer triad frame.\n    *a = M_accel * (C_i_b * a_b) + ba;\n  }\n\n  template <typename T>\n  static void\n  predict(const Eigen::Matrix<T, 3, 1> &bg, const Eigen::Matrix<T, 3, 1> &ba,\n          const Eigen::Matrix<T, Eigen::Dynamic, 1> &params,\n          const Eigen::Matrix<T, 3, 1> &w_b, const Eigen::Matrix<T, 3, 1> &a_b,\n          Eigen::Matrix<T, 3, 1> *w, Eigen::Matrix<T, 3, 1> *a) {\n    Eigen::Matrix<T, 3, 3> M_accel;\n    vectorToLowerTriangularMatrix<T>(params.data(), kSMDim + kSensitivityDim,\n                                     &M_accel);\n    Eigen::Matrix<T, 3, 3> C_i_b =\n        Eigen::Matrix<T, 3, 3>::Identity(); // The IMU sensor frame coincides\n                                            // the accelerometer triad frame.\n    *a = M_accel * (C_i_b * a_b) + ba;\n\n    Eigen::Map<const Eigen::Quaternion<T>> q_gyro_i(params.data() +\n                                                    kAugmentedDim - 4);\n    Eigen::Matrix<T, 3, 3> C_gyro_i = q_gyro_i.toRotationMatrix();\n    Eigen::Matrix<T, 3, 3> C_gyro_b = C_gyro_i * C_i_b;\n\n    Eigen::Matrix<T, 3, 3> M_gyro;\n    vectorToLowerTriangularMatrix<T>(params.data(), 0, &M_gyro);\n    Eigen::Matrix<T, 3, 3> M_accel_gyro;\n    vectorToMatrix<T>(params.data(), kSMDim, &M_accel_gyro);\n    *w = M_gyro * (C_gyro_b * w_b) + M_accel_gyro * (C_gyro_b * a_b) + bg;\n  }\n\n  template <typename T>\n  static void\n  correct(const Eigen::Matrix<T, 3, 1> &bg, const Eigen::Matrix<T, 3, 1> &ba,\n          const Eigen::Matrix<T, Eigen::Dynamic, 1> &params,\n          const Eigen::Matrix<T, 3, 1> &w, const Eigen::Matrix<T, 3, 1> &a,\n          Eigen::Matrix<T, 3, 1> *w_b, Eigen::Matrix<T, 3, 1> *a_b) {\n    Eigen::Matrix<T, 3, 3> M_accel_inv;\n    invertLowerTriangularMatrix<T>(params.data(), kSMDim + kSensitivityDim,\n                                   &M_accel_inv);\n    Eigen::Matrix<T, 3, 3> C_b_i =\n        Eigen::Matrix<T, 3, 3>::Identity(); // The IMU sensor frame coincides\n                                            // the accelerometer triad frame.\n    *a_b = C_b_i * M_accel_inv * (a - ba);\n\n    Eigen::Matrix<T, 3, 3> C_i_b = C_b_i.transpose();\n    Eigen::Map<const Eigen::Quaternion<T>> q_gyro_i(params.data() +\n                                                    kAugmentedDim - 4);\n    Eigen::Matrix<T, 3, 3> C_gyro_i = q_gyro_i.toRotationMatrix();\n    Eigen::Matrix<T, 3, 3> C_gyro_b = C_gyro_i * C_i_b;\n\n    Eigen::Matrix<T, 3, 3> M_gyro_inv;\n    invertLowerTriangularMatrix<T>(params.data(), 0, &M_gyro_inv);\n    Eigen::Matrix<T, 3, 3> M_accel_gyro;\n    vectorToMatrix<T>(params.data(), kSMDim, &M_accel_gyro);\n    *w_b = C_gyro_b.transpose() *\n           (M_gyro_inv * (w - bg - M_accel_gyro * (C_gyro_b * (*a_b))));\n  }\n\n  static Eigen::VectorXd\n  computeAugmentedParamsError(const Eigen::VectorXd &params) {\n    Eigen::VectorXd residual(getAugmentedMinimalDim());\n    Eigen::VectorXd nominalValues = getNominalAugmentedParams<double>();\n    constexpr int kAugmentedEuclideanDim = kAugmentedDim - 4;\n    Eigen::Map<const Eigen::Quaterniond> q_g_i(nominalValues.data() +\n                                               kAugmentedEuclideanDim);\n    residual.head<kAugmentedEuclideanDim>() =\n        params.head<kAugmentedEuclideanDim>() -\n        nominalValues.head<kAugmentedEuclideanDim>();\n    Eigen::Map<const Eigen::Quaterniond> q_g_i_hat(params.data() + kAugmentedEuclideanDim);\n    residual.tail<3>() = (q_g_i * q_g_i_hat.conjugate()).coeffs().head<3>() * 2;\n    return residual;\n  }\n};\n\n#ifndef IMU_ERROR_MODEL_CASES\n#define IMU_ERROR_MODEL_CASES                                                  \\\n  IMU_ERROR_MODEL_CASE(Imu_BG_BA)                                              \\\n  IMU_ERROR_MODEL_CASE(Imu_BG_BA_TG_TS_TA)                                     \\\n  IMU_ERROR_MODEL_CASE(ScaledMisalignedImu)\n#endif\n\ninline int ImuModelGetMinimalDim(int model_id) {\n  switch (model_id) {\n#define MODEL_CASES IMU_ERROR_MODEL_CASES\n#define IMU_ERROR_MODEL_CASE(ImuModel) \\\n  case ImuModel::kModelId:             \\\n    return ImuModel::getMinimalDim();\n\n    MODEL_SWITCH_CASES\n\n#undef IMU_ERROR_MODEL_CASE\n#undef MODEL_CASES\n  }\n  return 0;\n}\n\ninline int ImuModelGetAugmentedDim(int model_id) {\n  switch (model_id) {\n#define MODEL_CASES IMU_ERROR_MODEL_CASES\n#define IMU_ERROR_MODEL_CASE(ImuModel) \\\n  case ImuModel::kModelId:             \\\n    return ImuModel::getAugmentedDim();\n\n    MODEL_SWITCH_CASES\n\n#undef IMU_ERROR_MODEL_CASE\n#undef MODEL_CASES\n  }\n  return 0;\n}\n\ninline int ImuModelGetAugmentedMinimalDim(int model_id) {\n  switch (model_id) {\n#define MODEL_CASES IMU_ERROR_MODEL_CASES\n#define IMU_ERROR_MODEL_CASE(ImuModel) \\\n  case ImuModel::kModelId:             \\\n    return ImuModel::getAugmentedMinimalDim();\n\n    MODEL_SWITCH_CASES\n\n#undef IMU_ERROR_MODEL_CASE\n#undef MODEL_CASES\n  }\n  return 0;\n}\n\ninline void ImuModelToAugmentedDesiredStdevs(const int imu_model,\n                                             Eigen::VectorXd *stdevs) {\n  int index = 0;\n  switch (imu_model) {\n  case Imu_BG_BA_TG_TS_TA::kModelId:\n    stdevs->resize(27);\n    for (int i = 0; i < 9; ++i) {\n      (*stdevs)[i] = 4e-3;\n    }\n    index = 9;\n    for (int i = 0; i < 9; ++i) {\n      (*stdevs)[i + index] = 1e-3;\n    }\n    index += 9;\n    for (int i = 0; i < 9; ++i) {\n      (*stdevs)[i + index] = 5e-3;\n    }\n    break;\n  case ScaledMisalignedImu::kModelId:\n    stdevs->resize(24);\n    for (int i = 0; i < 6; ++i) {\n      (*stdevs)[i] = 4e-3;\n    }\n    index += 6;\n    for (int i = 0; i < 9; ++i) {\n      (*stdevs)[i + index] = 1e-3;\n    }\n    index += 9;\n    for (int i = 0; i < 6; ++i) {\n      (*stdevs)[i + index] = 5e-3;\n    }\n    index += 6;\n    for (int i = 0; i < 3; ++i) {\n      (*stdevs)[i + index] = 5e-3;\n    }\n    index += 3;\n    break;\n  case Imu_BG_BA::kModelId:\n  default:\n    stdevs->resize(0);\n    break;\n  }\n}\n\ninline void\nImuModelToMinimalAugmentedDimensionLabels(const int imu_model,\n                                          std::vector<std::string> *labels) {\n  std::vector<std::string> extraLabels;\n  switch (imu_model) {\n  case Imu_BG_BA_TG_TS_TA::kModelId:\n    extraLabels = {\"Tg_1\", \"Tg_2\", \"Tg_3\", \"Tg_4\", \"Tg_5\", \"Tg_6\", \"Tg_7\",\n                   \"Tg_8\", \"Tg_9\", \"Ts_1\", \"Ts_2\", \"Ts_3\", \"Ts_4\", \"Ts_5\",\n                   \"Ts_6\", \"Ts_7\", \"Ts_8\", \"Ts_9\", \"Ta_1\", \"Ta_2\", \"Ta_3\",\n                   \"Ta_4\", \"Ta_5\", \"Ta_6\", \"Ta_7\", \"Ta_8\", \"Ta_9\"};\n    break;\n  case ScaledMisalignedImu::kModelId:\n    extraLabels = {\"Mg_11\", \"Mg_21\",       \"Mg_22\",       \"Mg_31\",      \"Mg_32\",\n                   \"Mg_33\", \"A_11\",        \"A_12\",        \"A_13\",       \"A_21\",\n                   \"A_22\",  \"A_23\",        \"A_31\",        \"A_32\",       \"A_33\",\n                   \"Ma_11\", \"Ma_21\",       \"Ma_22\",       \"Ma_31\",      \"Ma_32\",\n                   \"Ma_33\", \"theta_g_a_x\", \"theta_g_a_y\", \"theta_g_a_z\"};\n    break;\n  case Imu_BG_BA::kModelId:\n  default:\n    break;\n  }\n  *labels = extraLabels;\n}\n\ninline void\nImuModelToAugmentedDimensionLabels(const int imu_model,\n                                   std::vector<std::string> *labels) {\n  std::vector<std::string> extraLabels;\n  switch (imu_model) {\n  case Imu_BG_BA_TG_TS_TA::kModelId:\n    extraLabels = {\"Tg_1\", \"Tg_2\", \"Tg_3\", \"Tg_4\", \"Tg_5\", \"Tg_6\", \"Tg_7\",\n                   \"Tg_8\", \"Tg_9\", \"Ts_1\", \"Ts_2\", \"Ts_3\", \"Ts_4\", \"Ts_5\",\n                   \"Ts_6\", \"Ts_7\", \"Ts_8\", \"Ts_9\", \"Ta_1\", \"Ta_2\", \"Ta_3\",\n                   \"Ta_4\", \"Ta_5\", \"Ta_6\", \"Ta_7\", \"Ta_8\", \"Ta_9\"};\n    break;\n  case ScaledMisalignedImu::kModelId:\n    extraLabels = {\"Mg_11\", \"Mg_21\",   \"Mg_22\",   \"Mg_31\",   \"Mg_32\",\n                   \"Mg_33\", \"A_11\",    \"A_12\",    \"A_13\",    \"A_21\",\n                   \"A_22\",  \"A_23\",    \"A_31\",    \"A_32\",    \"A_33\",\n                   \"Ma_11\", \"Ma_21\",   \"Ma_22\",   \"Ma_31\",   \"Ma_32\",\n                   \"Ma_33\", \"q_g_a_x\", \"q_g_a_y\", \"q_g_a_z\", \"q_g_a_w\"};\n    break;\n  case Imu_BG_BA::kModelId:\n  default:\n    break;\n  }\n  *labels = extraLabels;\n}\n\ninline void ImuModelToDimensionLabels(const int imu_model,\n                                      std::vector<std::string> *labels) {\n  *labels = {\"b_g_x[rad/s]\", \"b_g_y\", \"b_g_z\",\n             \"b_a_x[m/s^2]\", \"b_a_y\", \"b_a_z\"};\n  std::vector<std::string> extraLabels;\n  ImuModelToAugmentedDimensionLabels(imu_model, &extraLabels);\n  labels->insert(labels->end(), extraLabels.begin(), extraLabels.end());\n}\n\ninline int ImuModelNameToId(std::string imu_error_model_descrip) {\n  std::transform(imu_error_model_descrip.begin(), imu_error_model_descrip.end(),\n                 imu_error_model_descrip.begin(),\n                 [](unsigned char c) { return std::toupper(c); });\n  if (imu_error_model_descrip.compare(\"SCALEDMISALIGNED\") == 0) {\n    return ScaledMisalignedImu::kModelId;\n  } else if (imu_error_model_descrip.compare(\"BG_BA_TG_TS_TA\") == 0) {\n    return Imu_BG_BA_TG_TS_TA::kModelId;\n  } else if (imu_error_model_descrip.compare(\"BG_BA\") == 0) {\n    return Imu_BG_BA::kModelId;\n  } else {\n    return Imu_BG_BA_TG_TS_TA::kModelId;\n  }\n}\n\ninline Eigen::Matrix<double, Eigen::Dynamic, 1> ImuModelNominalAugmentedParams(int model_id) {\n  switch (model_id) {\n#define MODEL_CASES IMU_ERROR_MODEL_CASES\n#define IMU_ERROR_MODEL_CASE(ImuModel) \\\n    case ImuModel::kModelId:             \\\n  return ImuModel::getNominalAugmentedParams<double>();\n\n    MODEL_SWITCH_CASES\n\n    #undef IMU_ERROR_MODEL_CASE\n    #undef MODEL_CASES\n    }\n}\n\ninline void ImuModelPredict(int model_id, const Eigen::Vector3d& bg, const Eigen::Vector3d& ba,\n                            const Eigen::Matrix<double, Eigen::Dynamic, 1>& params,\n                            const Eigen::Matrix<double, 3, 1>& w_b, const Eigen::Matrix<double, 3, 1>& a_b,\n                            Eigen::Matrix<double, 3, 1>* w, Eigen::Matrix<double, 3, 1>* a) {\n  switch (model_id) {\n#define MODEL_CASES IMU_ERROR_MODEL_CASES\n#define IMU_ERROR_MODEL_CASE(ImuModel) \\\n    case ImuModel::kModelId:             \\\n  return ImuModel::predict<double>(bg, ba, params, w_b, a_b, w, a);\n\n    MODEL_SWITCH_CASES\n\n    #undef IMU_ERROR_MODEL_CASE\n    #undef MODEL_CASES\n    }\n}\n\ninline void ImuModelCorrect(int model_id,\n                            const Eigen::Vector3d& bg, const Eigen::Vector3d& ba,\n                            const Eigen::Matrix<double, Eigen::Dynamic, 1>& params,\n                            const Eigen::Matrix<double, 3, 1>& w, const Eigen::Matrix<double, 3, 1>& a,\n                            Eigen::Matrix<double, 3, 1>* w_b, Eigen::Matrix<double, 3, 1>* a_b) {\n  switch (model_id) {\n#define MODEL_CASES IMU_ERROR_MODEL_CASES\n#define IMU_ERROR_MODEL_CASE(ImuModel) \\\n    case ImuModel::kModelId:             \\\n  return ImuModel::correct<double>(bg, ba, params, w, a, w_b, a_b);\n\n    MODEL_SWITCH_CASES\n\n    #undef IMU_ERROR_MODEL_CASE\n    #undef MODEL_CASES\n    }\n}\n\ninline Eigen::VectorXd ImuModelComputeAugmentedParamsError(\n    int model_id, const Eigen::VectorXd& parameters) {\n  switch (model_id) {\n#define MODEL_CASES IMU_ERROR_MODEL_CASES\n#define IMU_ERROR_MODEL_CASE(ImuModel) \\\n    case ImuModel::kModelId:             \\\n  return ImuModel::computeAugmentedParamsError(parameters);\n\n    MODEL_SWITCH_CASES\n\n    #undef IMU_ERROR_MODEL_CASE\n    #undef MODEL_CASES\n  }\n}\n}  // namespace swift_vio\n#endif  // INCLUDE_SWIFT_VIO_IMU_ERROR_MODELS_HPP_\n", "meta": {"hexsha": "f2ad55831ea864b39db07631c9cf97ca9a4cb437", "size": 25454, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "okvis_ceres/include/swift_vio/imu/ImuModels.hpp", "max_stars_repo_name": "wbl1997/okvis", "max_stars_repo_head_hexsha": "65e30d6ab25380d65c96c665485148e2ab55e93e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-26T15:31:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T15:31:53.000Z", "max_issues_repo_path": "okvis_ceres/include/swift_vio/imu/ImuModels.hpp", "max_issues_repo_name": "wbl1997/okvis", "max_issues_repo_head_hexsha": "65e30d6ab25380d65c96c665485148e2ab55e93e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "okvis_ceres/include/swift_vio/imu/ImuModels.hpp", "max_forks_repo_name": "wbl1997/okvis", "max_forks_repo_head_hexsha": "65e30d6ab25380d65c96c665485148e2ab55e93e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-08-01T16:49:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T09:00:03.000Z", "avg_line_length": 39.4024767802, "max_line_length": 147, "alphanum_fraction": 0.6180953878, "num_tokens": 8148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630722, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.2930620168604617}}
{"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\n#include \"Ediis.h\"\n#include \"EdiisCoefficientOptimizer.h\"\n#include <Eigen/QR>\n#include <iostream>\n\nnamespace Scine {\nnamespace Utils {\n\nEdiis::Ediis() {\n  setSubspaceSize(6);\n}\n\nvoid Ediis::setUnrestricted(bool b) {\n  unrestricted_ = b;\n}\n\nvoid Ediis::setSubspaceSize(int n) {\n  bool resizeNeeded = n != subspaceSize_;\n\n  subspaceSize_ = n;\n\n  if (resizeNeeded)\n    resizeMembers();\n}\n\nvoid Ediis::setNAOs(int n) {\n  bool resizeNeeded = n != nAOs_;\n\n  nAOs_ = n;\n\n  if (resizeNeeded)\n    resizeMembers();\n}\n\nvoid Ediis::resizeMembers() {\n  fockMatrices.resize(subspaceSize_);\n  densityMatrices.resize(subspaceSize_);\n  energies.resize(subspaceSize_);\n\n  B = Eigen::MatrixXd::Zero(subspaceSize_, subspaceSize_);\n\n  restart();\n}\n\nvoid Ediis::restart() {\n  iterationNo_ = 0;\n  index_ = 0;\n}\n\nvoid Ediis::addMatrices(double energy, const SpinAdaptedMatrix& F, const DensityMatrix& P) {\n  iterationNo_++;\n  lastAdded_ = index_;\n\n  fockMatrices[index_] = F;\n  densityMatrices[index_] = P;\n  energies[index_] = energy;\n\n  updateBMatrix();\n\n  index_ = (index_ + 1) % subspaceSize_;\n}\n\nvoid Ediis::updateBMatrix() {\n  int activeSize = iterationNo_ > subspaceSize_ ? subspaceSize_ : iterationNo_;\n\n  // Bii element\n  B(lastAdded_, lastAdded_) = 0;\n\n  // Bij elements\n  for (int i = 0; i < activeSize; i++) {\n    if (i == lastAdded_)\n      continue;\n    double v = getBMatrixElement(lastAdded_, i);\n    B(lastAdded_, i) = v;\n    B(i, lastAdded_) = B(lastAdded_, i);\n  }\n}\n\ndouble Ediis::getBMatrixElement(int i, int j) const {\n  if (unrestricted_) {\n    double va = ((fockMatrices[i].alphaMatrix() - fockMatrices[j].alphaMatrix()).selfadjointView<Eigen::Lower>() *\n                 (densityMatrices[i].alphaMatrix() - densityMatrices[j].alphaMatrix()))\n                    .trace();\n    double vb = ((fockMatrices[i].betaMatrix() - fockMatrices[j].betaMatrix()).selfadjointView<Eigen::Lower>() *\n                 (densityMatrices[i].betaMatrix() - densityMatrices[j].betaMatrix()))\n                    .trace();\n    return (va + vb) / 2;\n  }\n  else {\n    double v = ((fockMatrices[i].restrictedMatrix() - fockMatrices[j].restrictedMatrix()).selfadjointView<Eigen::Lower>() *\n                (densityMatrices[i].restrictedMatrix() - densityMatrices[j].restrictedMatrix()))\n                   .trace();\n    // Divide v by two because density matrix is RHF\n    return v / 2;\n  }\n}\n\nSpinAdaptedMatrix Ediis::getMixedFockMatrix() {\n  if (iterationNo_ > subspaceSize_)\n    iterationNo_ = subspaceSize_;\n\n  // If we have only one Fock matrix\n  if (iterationNo_ < 2) {\n    return fockMatrices[0];\n  }\n  else {\n    EdiisCoefficientOptimizer opt(energies, B.block(0, 0, iterationNo_, iterationNo_));\n    auto coefs = opt.getCoefficients();\n\n    return calculateLinearCombination(coefs);\n  }\n}\n\nSpinAdaptedMatrix Ediis::calculateLinearCombination(const Eigen::VectorXd& coefs) {\n  if (unrestricted_) {\n    Eigen::MatrixXd FAlpha = Eigen::MatrixXd::Zero(nAOs_, nAOs_);\n    Eigen::MatrixXd FBeta = Eigen::MatrixXd::Zero(nAOs_, nAOs_);\n    for (int i = 0; i < iterationNo_; i++) {\n      FAlpha += coefs[i] * fockMatrices[i].alphaMatrix();\n      FBeta += coefs[i] * fockMatrices[i].betaMatrix();\n    }\n    return SpinAdaptedMatrix::createUnrestricted(std::move(FAlpha), std::move(FBeta));\n  }\n  else {\n    Eigen::MatrixXd Fsol = Eigen::MatrixXd::Zero(nAOs_, nAOs_);\n    for (int i = 0; i < iterationNo_; i++)\n      Fsol += coefs[i] * fockMatrices[i].restrictedMatrix();\n    return SpinAdaptedMatrix::createRestricted(std::move(Fsol));\n  }\n}\n} // namespace Utils\n} // namespace Scine\n", "meta": {"hexsha": "d9a84c617b829e09dc9c451edb4d5bf7797f2409", "size": 3775, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Utils/Scf/ConvergenceAccelerators/Ediis.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/Scf/ConvergenceAccelerators/Ediis.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/Scf/ConvergenceAccelerators/Ediis.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": 26.9642857143, "max_line_length": 123, "alphanum_fraction": 0.659602649, "num_tokens": 1082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2928581713634865}}
{"text": "/***********************************************************************\nThis file is part of the librjmcmc project source files.\n\nCopyright : Institut Geographique National (2008-2012)\nContributors : Mathieu Brédif, Olivier Tournaire, Didier Boldo\nemail : librjmcmc@ign.fr\n\nThis software is a generic C++ library for stochastic optimization.\n\nThis software is governed by the CeCILL license under French law and\nabiding by the rules of distribution of free software. You can use,\nmodify and/or redistribute the software under the terms of the CeCILL\nlicense as circulated by CEA, CNRS and INRIA at the following URL\n\"http://www.cecill.info\".\n\nAs a counterpart to the access to the source code and rights to copy,\nmodify and redistribute granted by the license, users are provided only\nwith a limited warranty and the software's author, the holder of the\neconomic rights, and the successive licensors have only limited liability.\n\nIn this respect, the user's attention is drawn to the risks associated\nwith loading, using, modifying and/or developing or reproducing the\nsoftware by the user in light of its specific status of free software,\nthat may mean that it is complicated to manipulate, and that also\ntherefore means that it is reserved for developers and experienced\nprofessionals having in-depth computer knowledge. Users are therefore\nencouraged to load and test the software's suitability as regards their\nrequirements in conditions enabling the security of their systems and/or\ndata to be ensured and, more generally, to use and operate it in the\nsame conditions as regards security.\n\nThe fact that you are presently reading this means that you have had\nknowledge of the CeCILL license and that you accept its terms.\n\n***********************************************************************/\n\n#ifndef GRAPH_CONFIGURATION_HPP\n#define GRAPH_CONFIGURATION_HPP\n\n#include <boost/graph/adjacency_list.hpp>\n#include \"configuration.hpp\"\n#include \"rjmcmc/util/variant.hpp\" // apply_visitor\n\n\nnamespace marked_point_process {\n\n    template<typename T, typename UnaryEnergy, typename BinaryEnergy, typename Accelerator=trivial_accelerator, typename OutEdgeList = boost::listS, typename VertexList = boost::listS  >\n    class graph_configuration\n    {\n    public:\n\ttypedef graph_configuration<T,UnaryEnergy, BinaryEnergy, Accelerator, OutEdgeList, VertexList> self;\n        typedef T\tvalue_type;\n    private:\n\tclass edge {\n\tpublic:\n            edge() : m_energy(0) {}\n            inline double energy() const { return m_energy; }\n            inline void energy(double e) { m_energy = e;    }\n\n\tprivate:\n            double m_energy;\n\t};\n\n\tclass node {\n\tpublic:\n            node(const value_type& obj, double e) : m_value(obj), m_energy(e) { }\n            inline const value_type& value() const { return m_value; }\n            inline double energy() const { return m_energy; }\n\n\tprivate:\n            value_type\tm_value;\n            double\tm_energy;\n\t};\n\ttypedef boost::adjacency_list<OutEdgeList, VertexList, boost::undirectedS, node, edge> graph_type;\n\ttypedef typename graph_type::out_edge_iterator\tout_edge_iterator;\n\ttypedef\ttypename graph_type::vertex_descriptor\tvertex_descriptor;\n\ttypedef std::pair< typename graph_type::edge_descriptor , bool > edge_descriptor_bool;\n\n    public:\n\ttypedef\ttypename graph_type::vertex_iterator\titerator;\n\ttypedef\ttypename graph_type::vertex_iterator\tconst_iterator;\n\ttypedef typename graph_type::edge_iterator\tedge_iterator;\n\ttypedef typename graph_type::edge_iterator\tconst_edge_iterator;\n        typedef internal::modification<self>            modification;\n    public:\n\n\t// configuration constructors/destructors\n\tgraph_configuration(UnaryEnergy unary_energy, BinaryEnergy binary_energy, Accelerator accelerator=Accelerator()) : m_unary(0.), m_binary(0.), m_unary_energy(unary_energy), m_binary_energy(binary_energy), m_accelerator(accelerator)\n\t{}\n\t~graph_configuration()\n\t{}\n\n\t// configuration accessors\n\tinline double unary_energy () const { return m_unary;}\n\tinline double binary_energy() const { return m_binary;}\n\tinline double energy       () const {\n            return unary_energy()+binary_energy();\n\t}\n\n\t// values\n\tinline size_t size() const { return num_vertices(m_graph); }\n\tinline bool empty() const {\treturn (num_vertices(m_graph)==0); }\n\tinline iterator begin() { return vertices(m_graph).first; }\n\tinline iterator end  () { return vertices(m_graph).second; }\n\tinline const_iterator begin() const { return vertices(m_graph).first; }\n        inline const_iterator end  () const { return vertices(m_graph).second; }\n\tinline const value_type& value( const_iterator v ) const { return m_graph[ *v ].value(); }\n\tinline double energy( const_iterator v ) const { return m_graph[ *v ].energy(); }\n\n\t// interactions\n\tinline size_t size_of_interactions   () const { return num_edges(m_graph);    }\n\tinline edge_iterator interactions_begin() { return edges(m_graph).first; }\n\tinline edge_iterator interactions_end  () { return edges(m_graph).second; }\n\tinline const_edge_iterator interactions_begin() const { return edges(m_graph).first; }\n\tinline const_edge_iterator interactions_end  () const { return edges(m_graph).second; }\n\tinline double energy( edge_iterator e ) const { return m_graph[ *e ].energy(); }\n\n\t// evaluators\n\n\ttemplate <typename Modification> double delta_energy(const Modification &modif) const\n\t{\n            return delta_birth(modif)+delta_death(modif);\n\t}\n\n\ttemplate <typename Modification> double delta_birth(const Modification &modif) const\n\t{\n            double delta = 0;\n            typedef typename Modification::birth_type::const_iterator bci;\n            typedef typename Modification::death_type::const_iterator dci;\n            bci bbeg = modif.birth().begin();\n            bci bend = modif.birth().end();\n            dci dbeg = modif.death().begin();\n            dci dend = modif.death().end();\n            for(bci it=bbeg; it!=bend; ++it) {\n                delta += rjmcmc::apply_visitor(m_unary_energy,*it);\n                const_iterator   it2, end2;\n                boost::tie(it2,end2)=m_accelerator(*this,*it);\n                for (; it2 != end2; ++it2)\n                    if (std::find(dbeg,dend,it2)==dend)\n                        delta += rjmcmc::apply_visitor(m_binary_energy, *it, value(it2) );\n                for (bci it2=bbeg; it2 != it; ++it2)\n                    delta += rjmcmc::apply_visitor(m_binary_energy, *it, *it2);\n            }\n            return delta;\n\t}\n\n\ttemplate <typename Modification> double delta_death(const Modification &modif) const\n\t{\n            double delta = 0;\n            typedef typename Modification::death_type::const_iterator dci;\n            dci dbeg = modif.death().begin();\n            dci dend = modif.death().end();\n            for(dci it=dbeg; it!=dend; ++it) {\n                iterator v = *it;\n                delta -= energy(v);\n                out_edge_iterator it2, end;\n                for(boost::tie(it2,end) = out_edges( *v, m_graph ); it2!=end; ++it2) {\n                    vertex_descriptor dtarget = target(*it2, m_graph);\n                    bool found = false;\n                    for(dci it3=dbeg; it3!=it && !found; ++it3)\n                        found = (**it3 == dtarget);\n                    if (!found)\n                        delta -= m_graph[ *it2 ].energy();\n                }\n            }\n            return delta;\n        }\n\n\t// manipulators\n\tvoid insert(const value_type& obj)\n\t{\n            node n(obj, rjmcmc::apply_visitor(m_unary_energy,obj));\n            m_unary += n.energy();\n            vertex_descriptor d = add_vertex(n, m_graph);\n            iterator   it, end;\n\n            for (boost::tie(it,end)=m_accelerator(*this,obj); it != end; ++it) {\n                if ( *it == d ) continue;\n                double e = rjmcmc::apply_visitor(m_binary_energy, obj, value(it) );\n                if (   e == 0 ) continue;\n                edge_descriptor_bool new_edge = add_edge(d, *it, m_graph );\n                m_graph[ new_edge.first ].energy( e );\n                m_binary += e;\n            }\n\t}\n\n        template<typename F>\n        struct DerefAdapter\n        {\n            graph_type const & g_;\n            F f_;\n            DerefAdapter(graph_type const & g, F f) : g_(g), f_(f) {}\n            template<typename U> typename F::result_type operator()(U u) { return rjmcmc::apply_visitor(f_,g_[u].value()); }\n        };\n\n\n        template<typename F> inline void for_each(F f)       {\n            iterator it, end;\n            boost::tie(it,end) = vertices(m_graph);\n            DerefAdapter<F> da(m_graph,f);\n            std::for_each(it,end,da);\n        }\n        template<typename F> inline void for_each(F f) const {\n            iterator it, end;\n            boost::tie(it,end) = vertices(m_graph);\n            DerefAdapter<F> da(m_graph,f);\n            std::for_each(it,end,da);\n        }\n\n\tvoid remove( iterator v )\n\t{\n            out_edge_iterator it, end;\n            for(boost::tie(it,end) = out_edges( *v, m_graph ); it!=end; ++it)\n                m_binary -= m_graph[ *it ].energy();\n            m_unary -= m_graph[*v].energy();\n            clear_vertex ( *v , m_graph);\n            remove_vertex( *v , m_graph);\n\t}\n\n\tinline void clear() { m_graph.clear(); m_unary=m_binary=0; }\n\n\t// audit\n\tdouble audit_unary_energy() const\n\t{\n            double e = 0.;\n            for (const_iterator i=begin(); i != end(); ++i)\n                e += rjmcmc::apply_visitor(m_unary_energy, value(i) );\n            return e;\n\t}\n\n\tdouble audit_binary_energy() const\n\t{\n            double e = 0.;\n            const_edge_iterator it, end;\n            for(boost::tie(it,end) = edges( m_graph ); it!=end; ++it)\n                e += rjmcmc::apply_visitor(m_binary_energy,\tm_graph[source(*it,m_graph)].value() ,\n                                           m_graph[target(*it,m_graph)].value() );\n            return e;\n\t}\n\n\tunsigned int audit_structure() const\n\t{\n            unsigned int err = 0;\n            for (const_iterator i=begin(); i != end(); ++i)\n            {\n                const_iterator j = i;\n                for (++j; j != end(); ++j)\n                {\n                    bool computed = (0!= rjmcmc::apply_visitor(m_binary_energy,value(i), value(j)));\n                    bool stored = boost::edge(*i, *j, m_graph).second;\n                    if (computed != stored)\t++err;\n                }\n            }\n            return err;\n\t}\n\n    private:\n        double m_unary;\n        double m_binary;\n\tgraph_type m_graph;\n\tUnaryEnergy\tm_unary_energy;\n\tBinaryEnergy\tm_binary_energy;\n        Accelerator\tm_accelerator;\n    };\n\n}; // namespace marked_point_process\n\n#endif // GRAPH_CONFIGURATION_HPP\n", "meta": {"hexsha": "900ea05db48f57885da147c74b4020030815059c", "size": 10662, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rjmcmc/mpp/configuration/graph_configuration.hpp", "max_stars_repo_name": "qc2105/librjmcmc", "max_stars_repo_head_hexsha": "6e031a9f6f3612394f8918c745700ae41d2aa586", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-02-17T17:07:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-02T16:49:02.000Z", "max_issues_repo_path": "include/rjmcmc/mpp/configuration/graph_configuration.hpp", "max_issues_repo_name": "qc2105/librjmcmc", "max_issues_repo_head_hexsha": "6e031a9f6f3612394f8918c745700ae41d2aa586", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-09-24T09:39:33.000Z", "max_issues_repo_issues_event_max_datetime": "2016-01-03T13:22:49.000Z", "max_forks_repo_path": "include/rjmcmc/mpp/configuration/graph_configuration.hpp", "max_forks_repo_name": "qc2105/librjmcmc", "max_forks_repo_head_hexsha": "6e031a9f6f3612394f8918c745700ae41d2aa586", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-03-18T17:32:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-04T21:38:16.000Z", "avg_line_length": 39.6356877323, "max_line_length": 231, "alphanum_fraction": 0.6244607016, "num_tokens": 2375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.629774621301746, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.29278321105426236}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#include \"camera.h\"\n\n#include \"transforms.h\"\n#include \"util.h\"\n\n#include <Eigen/Geometry>\n#include <Eigen/LU>\n#include <cmath>\n#include <iostream>\n#include <limits>\n\nnamespace scenepic\n{\n  void check_valid_rotation(const Transform& rotation, float tolerance = 1e-6f)\n  {\n    auto ortho_diff = (rotation * rotation.transpose() - Transform::Identity())\n                        .array()\n                        .abs()\n                        .maxCoeff();\n    auto det_diff = std::abs(rotation.determinant() - 1.0f);\n    if (ortho_diff > tolerance)\n    {\n      std::cerr << \"camera rotation: not orthogonal within tolerance of \"\n                << tolerance << \": \" << ortho_diff << std::endl;\n    }\n\n    if (det_diff > tolerance)\n    {\n      std::cerr << \"camera rotation: |det \" << rotation.determinant()\n                << \" - 1| > \" << tolerance << std::endl;\n    }\n  }\n\n  Camera::Camera(\n    const Vector& center,\n    const Vector& look_at,\n    const Vector& up_dir,\n    double fov_y_degrees,\n    double near_crop_distance,\n    double far_crop_distance,\n    double aspect_ratio)\n  {\n    auto rotation = Transforms::look_at_rotation(center, look_at, up_dir);\n    auto translation = Transforms::translate(-center);\n    m_world_to_camera = rotation * translation;\n    m_camera_to_world = m_world_to_camera.inverse();\n    m_projection = Transforms::gl_projection(\n      fov_y_degrees, aspect_ratio, near_crop_distance, far_crop_distance);\n  }\n\n  Camera::Camera(\n    const Vector& center,\n    const Transform& rotation,\n    double fov_y_degrees,\n    double near_crop_distance,\n    double far_crop_distance,\n    double aspect_ratio)\n  {\n    check_valid_rotation(rotation);\n    auto translation = Transforms::translate(-center);\n    m_world_to_camera = rotation * translation;\n    m_camera_to_world = m_world_to_camera.inverse();\n    m_projection = Transforms::gl_projection(\n      fov_y_degrees, aspect_ratio, near_crop_distance, far_crop_distance);\n  }\n\n  Camera::Camera(\n    const Transform& world_to_camera,\n    double fov_y_degrees,\n    double near_crop_distance,\n    double far_crop_distance,\n    double aspect_ratio)\n  : m_world_to_camera(world_to_camera)\n  {\n    if (!m_world_to_camera.isZero())\n    {\n      check_valid_rotation(this->rotation());\n      m_camera_to_world = m_world_to_camera.inverse();\n    }\n\n    m_projection = Transforms::gl_projection(\n      fov_y_degrees, aspect_ratio, near_crop_distance, far_crop_distance);\n  }\n\n  Camera::Camera(const Transform& world_to_camera, const Transform& projection)\n  : m_world_to_camera(world_to_camera), m_projection(projection)\n  {\n    if (!m_world_to_camera.isZero())\n    {\n      check_valid_rotation(this->rotation());\n      m_camera_to_world = m_world_to_camera.inverse();\n    }\n  }\n\n  Vector Camera::center() const\n  {\n    Vector center = m_camera_to_world.topRightCorner(3, 1).transpose();\n    return center;\n  }\n\n  Vector Camera::look_at() const\n  {\n    Vector look_at(0, 0, -1);\n    look_at =\n      (look_at.homogeneous() * m_camera_to_world.transpose()).hnormalized();\n    return look_at;\n  }\n\n  Vector Camera::up_dir() const\n  {\n    Vector up_dir(0, 1, 0);\n    up_dir = (up_dir.homogeneous() * this->rotation()).hnormalized();\n    return up_dir;\n  }\n\n  Transform Camera::rotation() const\n  {\n    Transform rotation = m_world_to_camera;\n    rotation.topRightCorner(3, 1).fill(0);\n    return rotation;\n  }\n\n  JsonValue Camera::to_json() const\n  {\n    JsonValue obj;\n    obj[\"CommandType\"] = \"SetCamera\";\n    obj[\"Value\"][\"WorldToCamera\"] = matrix_to_json(m_world_to_camera);\n    obj[\"Value\"][\"Projection\"] = matrix_to_json(m_projection);\n    return obj;\n  }\n\n  bool Camera::is_none() const\n  {\n    return m_projection.isZero() && m_world_to_camera.isZero();\n  }\n\n  Camera Camera::None()\n  {\n    Transform world_to_camera = Transform::Zero();\n    Transform projection = Transform::Zero();\n    return Camera(world_to_camera, projection);\n  }\n\n  std::string Camera::to_string() const\n  {\n    return this->to_json().to_string();\n  }\n\n  const Transform& Camera::world_to_camera() const\n  {\n    return m_world_to_camera;\n  }\n\n  const Transform& Camera::camera_to_world() const\n  {\n    return m_camera_to_world;\n  }\n\n  const Transform& Camera::projection() const\n  {\n    return m_projection;\n  }\n\n  float Camera::aspect_ratio() const\n  {\n    return m_projection(1, 1) / m_projection(0, 0);\n  }\n\n  Camera& Camera::aspect_ratio(float aspect_ratio)\n  {\n    m_projection(0, 0) = m_projection(1, 1) / aspect_ratio;\n    return *this;\n  }\n\n  std::vector<Camera> Camera::orbit(\n    int num_frames,\n    float distance,\n    int num_times,\n    float min_altitude,\n    float max_altitude,\n    Vector up_dir,\n    Vector forward_dir,\n    double fov_y_degrees,\n    double aspect_ratio,\n    double near_crop_distance,\n    double far_crop_distance)\n  {\n    Vector right_dir = up_dir.cross(forward_dir);\n    Eigen::VectorXf azimuth(num_frames);\n    Eigen::VectorXf altitude(num_frames);\n    azimuth.setLinSpaced(0, num_times * 2 * EIGEN_PI);\n    int half_frames = num_frames / 2;\n    altitude.topRows(half_frames + 1).setLinSpaced(min_altitude, max_altitude);\n    altitude.bottomRows(half_frames).setLinSpaced(min_altitude, max_altitude);\n    altitude.bottomRows(half_frames).reverseInPlace();\n\n    Transform projection = Transforms::gl_projection(\n      fov_y_degrees, aspect_ratio, near_crop_distance, far_crop_distance);\n\n    Transform init_ext = Transforms::look_at_rotation(\n      -forward_dir * distance, Vector::Zero(), up_dir);\n    init_ext = Transforms::translate(-forward_dir * distance) * init_ext;\n    std::vector<Camera> cameras;\n    for (int i = 0; i < num_frames; ++i)\n    {\n      Transform elevate =\n        Transforms::rotation_matrix_from_axis_angle(right_dir, altitude[i]);\n      Transform rotate =\n        Transforms::rotation_matrix_from_axis_angle(up_dir, azimuth[i]);\n      Transform camera_to_world = rotate * elevate * init_ext;\n      Transform world_to_camera = camera_to_world.inverse();\n      cameras.push_back(Camera(world_to_camera, projection));\n    }\n\n    return cameras;\n  }\n\n} // namespace scenepic", "meta": {"hexsha": "638d3848f7867601fadb268be5247c599389104f", "size": 6145, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/scenepic/camera.cpp", "max_stars_repo_name": "microsoft/scenepic", "max_stars_repo_head_hexsha": "e3fd2c6312fa670a92b7888962b6812c262c6759", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2021-10-05T08:51:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T11:19:23.000Z", "max_issues_repo_path": "src/scenepic/camera.cpp", "max_issues_repo_name": "microsoft/scenepic", "max_issues_repo_head_hexsha": "e3fd2c6312fa670a92b7888962b6812c262c6759", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2021-10-05T11:36:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T13:33:43.000Z", "max_forks_repo_path": "src/scenepic/camera.cpp", "max_forks_repo_name": "microsoft/scenepic", "max_forks_repo_head_hexsha": "e3fd2c6312fa670a92b7888962b6812c262c6759", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-12-12T16:42:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T11:50:14.000Z", "avg_line_length": 27.8054298643, "max_line_length": 79, "alphanum_fraction": 0.6810414972, "num_tokens": 1493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044135, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.29278320459337065}}
{"text": "#include <polyfem/RhsAssembler.hpp>\n#include <polyfem/par_for.hpp>\n\n#include <polyfem/BoundarySampler.hpp>\n#include <polysolve/LinearSolver.hpp>\n\n#include <polyfem/Logger.hpp>\n\n#include <Eigen/Sparse>\n\n#ifdef POLYFEM_WITH_TBB\n#include <tbb/parallel_for.h>\n#include <tbb/enumerable_thread_specific.h>\n#endif\n\n#include <iostream>\n#include <map>\n#include <memory>\n\nnamespace polyfem\n{\n\tusing namespace polysolve;\n\tnamespace\n\t{\n\t\tclass LocalThreadScalarStorage\n\t\t{\n\t\tpublic:\n\t\t\tdouble val;\n\t\t\tElementAssemblyValues vals;\n\n\t\t\tLocalThreadScalarStorage()\n\t\t\t{\n\t\t\t\tval = 0;\n\t\t\t}\n\t\t};\n\t} // namespace\n\n\tRhsAssembler::RhsAssembler(const AssemblerUtils &assembler, const Mesh &mesh,\n\t\t\t\t\t\t\t   const int n_basis, const int size,\n\t\t\t\t\t\t\t   const std::vector<ElementBases> &bases, const std::vector<ElementBases> &gbases, const AssemblyValsCache &ass_vals_cache,\n\t\t\t\t\t\t\t   const std::string &formulation, const Problem &problem,\n\t\t\t\t\t\t\t   const std::string bc_method,\n\t\t\t\t\t\t\t   const std::string &solver, const std::string &preconditioner, const json &solver_params)\n\t\t: assembler_(assembler), mesh_(mesh),\n\t\t  n_basis_(n_basis), size_(size),\n\t\t  bases_(bases), gbases_(gbases), ass_vals_cache_(ass_vals_cache),\n\t\t  formulation_(formulation), problem_(problem),\n\t\t  bc_method_(bc_method),\n\t\t  solver_(solver), preconditioner_(preconditioner), solver_params_(solver_params)\n\t{\n\t}\n\n\tvoid RhsAssembler::assemble(const Density &density, Eigen::MatrixXd &rhs, const double t) const\n\t{\n\t\trhs = Eigen::MatrixXd::Zero(n_basis_ * size_, 1);\n\t\tif (!problem_.is_rhs_zero())\n\t\t{\n\t\t\tEigen::MatrixXd rhs_fun;\n\n\t\t\tconst int n_elements = int(bases_.size());\n\t\t\tElementAssemblyValues vals;\n\t\t\tfor (int e = 0; e < n_elements; ++e)\n\t\t\t{\n\t\t\t\tvals.compute(e, mesh_.is_volume(), bases_[e], gbases_[e]);\n\n\t\t\t\tconst Quadrature &quadrature = vals.quadrature;\n\n\t\t\t\tproblem_.rhs(assembler_, formulation_, vals.val, t, rhs_fun);\n\n\t\t\t\tfor (int d = 0; d < size_; ++d)\n\t\t\t\t{\n\t\t\t\t\t//rhs_fun.col(d) = rhs_fun.col(d).array() * vals.det.array() * quadrature.weights.array();\n\t\t\t\t\tfor (int q = 0; q < quadrature.weights.size(); ++q)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst double rho = density(vals.val(q, 0), vals.val(q, 1), vals.val.cols() == 2 ? 0. : vals.val(q, 2), vals.element_id);\n\t\t\t\t\t\trhs_fun(q, d) *= vals.det(q) * quadrature.weights(q) * rho;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst int n_loc_bases_ = int(vals.basis_values.size());\n\t\t\t\tfor (int i = 0; i < n_loc_bases_; ++i)\n\t\t\t\t{\n\t\t\t\t\tconst AssemblyValues &v = vals.basis_values[i];\n\n\t\t\t\t\tfor (int d = 0; d < size_; ++d)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst double rhs_value = (rhs_fun.col(d).array() * v.val.array()).sum();\n\t\t\t\t\t\tfor (std::size_t ii = 0; ii < v.global.size(); ++ii)\n\t\t\t\t\t\t\trhs(v.global[ii].index * size_ + d) += rhs_value * v.global[ii].val;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid RhsAssembler::initial_solution(Eigen::MatrixXd &sol) const\n\t{\n\t\ttime_bc([&](const Mesh &mesh, const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val)\n\t\t\t\t{ problem_.initial_solution(mesh, global_ids, pts, val); },\n\t\t\t\tsol);\n\t}\n\n\tvoid RhsAssembler::initial_velocity(Eigen::MatrixXd &sol) const\n\t{\n\t\ttime_bc([&](const Mesh &mesh, const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val)\n\t\t\t\t{ problem_.initial_velocity(mesh, global_ids, pts, val); },\n\t\t\t\tsol);\n\t}\n\n\tvoid RhsAssembler::initial_acceleration(Eigen::MatrixXd &sol) const\n\t{\n\t\ttime_bc([&](const Mesh &mesh, const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val)\n\t\t\t\t{ problem_.initial_acceleration(mesh, global_ids, pts, val); },\n\t\t\t\tsol);\n\t}\n\n\tvoid RhsAssembler::time_bc(const std::function<void(const Mesh &, const Eigen::MatrixXi &, const Eigen::MatrixXd &, Eigen::MatrixXd &)> &fun, Eigen::MatrixXd &sol) const\n\t{\n\t\tsol = Eigen::MatrixXd::Zero(n_basis_ * size_, 1);\n\t\tEigen::MatrixXd loc_sol;\n\n\t\tconst int n_elements = int(bases_.size());\n\t\tElementAssemblyValues vals;\n\t\tEigen::MatrixXi ids;\n\t\tfor (int e = 0; e < n_elements; ++e)\n\t\t{\n\t\t\tvals.compute(e, mesh_.is_volume(), bases_[e], gbases_[e]);\n\t\t\tids.resize(vals.val.rows(), 1);\n\t\t\tids.setConstant(e);\n\n\t\t\tconst Quadrature &quadrature = vals.quadrature;\n\t\t\t//problem_.initial_solution(vals.val, loc_sol);\n\t\t\tfun(mesh_, ids, vals.val, loc_sol);\n\n\t\t\tfor (int d = 0; d < size_; ++d)\n\t\t\t\tloc_sol.col(d) = loc_sol.col(d).array() * vals.det.array() * quadrature.weights.array();\n\n\t\t\tconst int n_loc_bases_ = int(vals.basis_values.size());\n\t\t\tfor (int i = 0; i < n_loc_bases_; ++i)\n\t\t\t{\n\t\t\t\tconst AssemblyValues &v = vals.basis_values[i];\n\n\t\t\t\tfor (int d = 0; d < size_; ++d)\n\t\t\t\t{\n\t\t\t\t\tconst double sol_value = (loc_sol.col(d).array() * v.val.array()).sum();\n\t\t\t\t\tfor (std::size_t ii = 0; ii < v.global.size(); ++ii)\n\t\t\t\t\t\tsol(v.global[ii].index * size_ + d) += sol_value * v.global[ii].val;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tEigen::MatrixXd b = sol;\n\t\tsol.setZero();\n\n\t\tconst double mmin = b.minCoeff();\n\t\tconst double mmax = b.maxCoeff();\n\n\t\tif (fabs(mmin) > 1e-8 || fabs(mmax) > 1e-8)\n\t\t{\n\t\t\tStiffnessMatrix mass;\n\t\t\tDensity d;\n\t\t\tassembler_.assemble_mass_matrix(formulation_, size_ == 3, n_basis_, d, bases_, gbases_, ass_vals_cache_, mass);\n\t\t\tauto solver = LinearSolver::create(solver_, preconditioner_);\n\t\t\tsolver->setParameters(solver_params_);\n\t\t\tsolver->analyzePattern(mass, mass.rows());\n\t\t\tsolver->factorize(mass);\n\n\t\t\tfor (long i = 0; i < b.cols(); ++i)\n\t\t\t{\n\t\t\t\tsolver->solve(b.col(i), sol.col(i));\n\t\t\t}\n\t\t\tlogger().trace(\"mass matrix error {}\", (mass * sol - b).norm());\n\t\t}\n\t}\n\n\tvoid RhsAssembler::lsq_bc(const std::function<void(const Eigen::MatrixXi &, const Eigen::MatrixXd &, const Eigen::MatrixXd &, Eigen::MatrixXd &)> &df,\n\t\t\t\t\t\t\t  const std::vector<LocalBoundary> &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, Eigen::MatrixXd &rhs) const\n\t{\n\t\tconst int n_el = int(bases_.size());\n\n\t\tEigen::MatrixXd uv, samples, gtmp, rhs_fun;\n\t\tEigen::VectorXi global_primitive_ids;\n\n\t\tint index = 0;\n\t\tstd::vector<int> indices;\n\t\tindices.reserve(n_el * 10);\n\t\t// std::map<int, int> global_index_to_col;\n\n\t\tlong total_size = 0;\n\n\t\tEigen::Matrix<bool, Eigen::Dynamic, 1> is_boundary(n_basis_);\n\t\tis_boundary.setConstant(false);\n\t\tEigen::VectorXi global_index_to_col(n_basis_);\n\t\tglobal_index_to_col.setConstant(-1);\n\n\t\tconst int actual_dim = problem_.is_scalar() ? 1 : mesh_.dimension();\n\n\t\t// assert((bounday_nodes.size()/actual_dim)*actual_dim == bounday_nodes.size());\n\n\t\tint skipped_count = 0;\n\t\tfor (int b : bounday_nodes)\n\t\t{\n\t\t\tint bindex = b / actual_dim;\n\n\t\t\tif (bindex < is_boundary.size())\n\t\t\t\tis_boundary[bindex] = true;\n\t\t\telse\n\t\t\t\tskipped_count++;\n\t\t}\n\t\tassert(skipped_count <= 1);\n\n\t\tfor (const auto &lb : local_boundary)\n\t\t{\n\t\t\tconst int e = lb.element_id();\n\t\t\tbool has_samples = sample_boundary(lb, resolution, true, uv, samples, global_primitive_ids);\n\n\t\t\tif (!has_samples)\n\t\t\t\tcontinue;\n\n\t\t\tconst ElementBases &bs = bases_[e];\n\t\t\tconst int n_local_bases = int(bs.bases.size());\n\n\t\t\ttotal_size += samples.rows();\n\n\t\t\tfor (int j = 0; j < n_local_bases; ++j)\n\t\t\t{\n\t\t\t\tconst Basis &b = bs.bases[j];\n\n\t\t\t\tfor (std::size_t ii = 0; ii < b.global().size(); ++ii)\n\t\t\t\t{\n\t\t\t\t\t//pt found\n\t\t\t\t\t// if(std::find(bounday_nodes.begin(), bounday_nodes.end(), size_ * b.global()[ii].index) != bounday_nodes.end())\n\t\t\t\t\tif (is_boundary[b.global()[ii].index])\n\t\t\t\t\t{\n\t\t\t\t\t\t// if(!global_index_to_col.contains(b.global()[ii].index))\n\t\t\t\t\t\tif (global_index_to_col(b.global()[ii].index) == -1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// global_index_to_col[b.global()[ii].index] = index++;\n\t\t\t\t\t\t\tglobal_index_to_col(b.global()[ii].index) = index++;\n\t\t\t\t\t\t\tindices.push_back(b.global()[ii].index);\n\t\t\t\t\t\t\tassert(indices.size() == size_t(index));\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\t\t// Eigen::MatrixXd global_mat = Eigen::MatrixXd::Zero(total_size, indices.size());\n\t\tEigen::MatrixXd global_rhs = Eigen::MatrixXd::Zero(total_size, size_);\n\n\t\tconst long buffer_size = total_size * long(indices.size());\n\t\tstd::vector<Eigen::Triplet<double>> entries, entries_t;\n\t\t// entries.reserve(buffer_size);\n\t\t// entries_t.reserve(buffer_size);\n\n\t\tindex = 0;\n\n\t\tint global_counter = 0;\n\t\tEigen::MatrixXd mapped;\n\n\t\tstd::vector<AssemblyValues> tmp_val;\n\n\t\tfor (const auto &lb : local_boundary)\n\t\t{\n\t\t\tconst int e = lb.element_id();\n\t\t\tbool has_samples = sample_boundary(lb, resolution, false, uv, samples, global_primitive_ids);\n\n\t\t\tif (!has_samples)\n\t\t\t\tcontinue;\n\n\t\t\tconst ElementBases &bs = bases_[e];\n\t\t\tconst ElementBases &gbs = gbases_[e];\n\t\t\tconst int n_local_bases = int(bs.bases.size());\n\n\t\t\tgbs.eval_geom_mapping(samples, mapped);\n\n\t\t\tbs.evaluate_bases(samples, tmp_val);\n\t\t\tfor (int j = 0; j < n_local_bases; ++j)\n\t\t\t{\n\t\t\t\tconst Basis &b = bs.bases[j];\n\t\t\t\tconst auto &tmp = tmp_val[j].val;\n\n\t\t\t\tfor (std::size_t ii = 0; ii < b.global().size(); ++ii)\n\t\t\t\t{\n\t\t\t\t\t// auto item = global_index_to_col.find(b.global()[ii].index);\n\t\t\t\t\t// if(item != global_index_to_col.end()){\n\t\t\t\t\tauto item = global_index_to_col(b.global()[ii].index);\n\t\t\t\t\tif (item != -1)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (int k = 0; k < int(tmp.size()); ++k)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// entries.push_back(Eigen::Triplet<double>(global_counter+k, item->second, tmp(k, j) * b.global()[ii].val));\n\t\t\t\t\t\t\t// entries_t.push_back(Eigen::Triplet<double>(item->second, global_counter+k, tmp(k, j) * b.global()[ii].val));\n\t\t\t\t\t\t\tentries.push_back(Eigen::Triplet<double>(global_counter + k, item, tmp(k) * b.global()[ii].val));\n\t\t\t\t\t\t\tentries_t.push_back(Eigen::Triplet<double>(item, global_counter + k, tmp(k) * b.global()[ii].val));\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// global_mat.block(global_counter, item->second, tmp.size(), 1) = tmp;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// problem_.bc(mesh_, global_primitive_ids, mapped, t, rhs_fun);\n\t\t\tdf(global_primitive_ids, uv, mapped, rhs_fun);\n\t\t\tglobal_rhs.block(global_counter, 0, rhs_fun.rows(), rhs_fun.cols()) = rhs_fun;\n\t\t\tglobal_counter += rhs_fun.rows();\n\n\t\t\t//UIState::ui_state().debug_data().add_points(mapped, Eigen::MatrixXd::Constant(1, 3, 0));\n\n\t\t\t//Eigen::MatrixXd asd(mapped.rows(), 3);\n\t\t\t//asd.col(0)=mapped.col(0);\n\t\t\t//asd.col(1)=mapped.col(1);\n\t\t\t//asd.col(2)=rhs_fun;\n\t\t\t//UIState::ui_state().debug_data().add_points(asd, Eigen::MatrixXd::Constant(1, 3, 0));\n\t\t}\n\n\t\tassert(global_counter == total_size);\n\n\t\tif (total_size > 0)\n\t\t{\n\t\t\tconst double mmin = global_rhs.minCoeff();\n\t\t\tconst double mmax = global_rhs.maxCoeff();\n\n\t\t\tif (fabs(mmin) < 1e-8 && fabs(mmax) < 1e-8)\n\t\t\t{\n\t\t\t\t// std::cout<<\"is all zero, skipping\"<<std::endl;\n\t\t\t\tfor (size_t i = 0; i < indices.size(); ++i)\n\t\t\t\t{\n\t\t\t\t\tfor (int d = 0; d < size_; ++d)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (problem_.all_dimensions_dirichlet() || std::find(bounday_nodes.begin(), bounday_nodes.end(), indices[i] * size_ + d) != bounday_nodes.end())\n\t\t\t\t\t\t\trhs(indices[i] * size_ + d) = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tStiffnessMatrix mat(int(total_size), int(indices.size()));\n\t\t\t\tmat.setFromTriplets(entries.begin(), entries.end());\n\n\t\t\t\tStiffnessMatrix mat_t(int(indices.size()), int(total_size));\n\t\t\t\tmat_t.setFromTriplets(entries_t.begin(), entries_t.end());\n\n\t\t\t\tStiffnessMatrix A = mat_t * mat;\n\t\t\t\tEigen::MatrixXd b = mat_t * global_rhs;\n\n\t\t\t\tEigen::MatrixXd coeffs(b.rows(), b.cols());\n\t\t\t\tauto solver = LinearSolver::create(solver_, preconditioner_);\n\t\t\t\tsolver->setParameters(solver_params_);\n\t\t\t\tsolver->analyzePattern(A, A.rows());\n\t\t\t\tsolver->factorize(A);\n\t\t\t\tcoeffs.setZero();\n\t\t\t\tfor (long i = 0; i < b.cols(); ++i)\n\t\t\t\t{\n\t\t\t\t\tsolver->solve(b.col(i), coeffs.col(i));\n\t\t\t\t}\n\t\t\t\tlogger().trace(\"RHS solve error {}\", (A * coeffs - b).norm());\n\n\t\t\t\tfor (long i = 0; i < coeffs.rows(); ++i)\n\t\t\t\t{\n\t\t\t\t\tfor (int d = 0; d < size_; ++d)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (problem_.all_dimensions_dirichlet() || std::find(bounday_nodes.begin(), bounday_nodes.end(), indices[i] * size_ + d) != bounday_nodes.end())\n\t\t\t\t\t\t\trhs(indices[i] * size_ + d) = coeffs(i, d);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid RhsAssembler::sample_bc(const std::function<void(const Eigen::MatrixXi &, const Eigen::MatrixXd &, const Eigen::MatrixXd &, Eigen::MatrixXd &)> &df,\n\t\t\t\t\t\t\t\t const std::vector<LocalBoundary> &local_boundary, const std::vector<int> &bounday_nodes, Eigen::MatrixXd &rhs) const\n\t{\n\t\tconst int n_el = int(bases_.size());\n\n\t\tEigen::MatrixXd rhs_fun;\n\t\tEigen::VectorXi global_primitive_ids(1);\n\t\tEigen::MatrixXd nans(1, 1);\n\t\tnans(0) = std::nan(\"\");\n\n#ifndef NDEBUG\n\t\tEigen::Matrix<bool, Eigen::Dynamic, 1> is_boundary(n_basis_);\n\t\tis_boundary.setConstant(false);\n\n\t\tconst int actual_dim = problem_.is_scalar() ? 1 : mesh_.dimension();\n\n\t\tint skipped_count = 0;\n\t\tfor (int b : bounday_nodes)\n\t\t{\n\t\t\tint bindex = b / actual_dim;\n\n\t\t\tif (bindex < is_boundary.size())\n\t\t\t\tis_boundary[bindex] = true;\n\t\t\telse\n\t\t\t\tskipped_count++;\n\t\t}\n\t\tassert(skipped_count <= 1);\n#endif\n\n\t\tfor (const auto &lb : local_boundary)\n\t\t{\n\t\t\tconst int e = lb.element_id();\n\t\t\tconst ElementBases &bs = bases_[e];\n\n\t\t\tfor (int i = 0; i < lb.size(); ++i)\n\t\t\t{\n\t\t\t\tglobal_primitive_ids(0) = lb.global_primitive_id(i);\n\t\t\t\tconst auto nodes = bs.local_nodes_for_primitive(global_primitive_ids(0), mesh_);\n\n\t\t\t\tfor (long n = 0; n < nodes.size(); ++n)\n\t\t\t\t{\n\t\t\t\t\tconst auto &b = bs.bases[nodes(n)];\n\t\t\t\t\tconst auto &glob = b.global();\n\n\t\t\t\t\tfor (size_t ii = 0; ii < glob.size(); ++ii)\n\t\t\t\t\t{\n\t\t\t\t\t\tassert(is_boundary[glob[ii].index]);\n\n\t\t\t\t\t\t//TODO, missing UV!!!!\n\t\t\t\t\t\tdf(global_primitive_ids, nans, glob[ii].node, rhs_fun);\n\n\t\t\t\t\t\tfor (int d = 0; d < size_; ++d)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (problem_.all_dimensions_dirichlet() || std::find(bounday_nodes.begin(), bounday_nodes.end(), glob[ii].index * size_ + d) != bounday_nodes.end())\n\t\t\t\t\t\t\t\trhs(glob[ii].index * size_ + d) = rhs_fun(0, d);\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\tvoid RhsAssembler::integrate_bc(const std::function<void(const Eigen::MatrixXi &, const Eigen::MatrixXd &, const Eigen::MatrixXd &, Eigen::MatrixXd &)> &df,\n\t\t\t\t\t\t\t\t\tconst std::vector<LocalBoundary> &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, Eigen::MatrixXd &rhs) const\n\t{\n\t\tEigen::MatrixXd uv, samples, rhs_fun, normals, mapped;\n\t\tEigen::VectorXd weights;\n\n\t\tEigen::VectorXi global_primitive_ids;\n\t\tstd::vector<AssemblyValues> tmp_val;\n\n\t\tEigen::Matrix<bool, Eigen::Dynamic, 1> is_boundary(n_basis_);\n\t\tis_boundary.setConstant(false);\n\n\t\tEigen::MatrixXd areas(rhs.rows(), 1);\n\t\tareas.setZero();\n\n\t\tconst int actual_dim = problem_.is_scalar() ? 1 : mesh_.dimension();\n\n\t\tint skipped_count = 0;\n\t\tfor (int b : bounday_nodes)\n\t\t{\n\t\t\trhs(b) = 0;\n\t\t\tint bindex = b / actual_dim;\n\n\t\t\tif (bindex < is_boundary.size())\n\t\t\t\tis_boundary[bindex] = true;\n\t\t\telse\n\t\t\t\tskipped_count++;\n\t\t}\n\t\tassert(skipped_count <= 1);\n\t\tElementAssemblyValues vals;\n\n\t\tfor (const auto &lb : local_boundary)\n\t\t{\n\t\t\tconst int e = lb.element_id();\n\t\t\tbool has_samples = boundary_quadrature(lb, resolution, false, uv, samples, normals, weights, global_primitive_ids);\n\n\t\t\tif (!has_samples)\n\t\t\t\tcontinue;\n\n\t\t\tconst ElementBases &bs = bases_[e];\n\t\t\tconst ElementBases &gbs = gbases_[e];\n\n\t\t\tvals.compute(e, mesh_.is_volume(), samples, bs, gbs);\n\n\t\t\tdf(global_primitive_ids, uv, vals.val, rhs_fun);\n\n\t\t\tfor (int d = 0; d < size_; ++d)\n\t\t\t\trhs_fun.col(d) = rhs_fun.col(d).array() * weights.array();\n\n\t\t\tfor (int i = 0; i < lb.size(); ++i)\n\t\t\t{\n\t\t\t\tconst int primitive_global_id = lb.global_primitive_id(i);\n\t\t\t\tconst auto nodes = bs.local_nodes_for_primitive(primitive_global_id, mesh_);\n\n\t\t\t\tfor (long n = 0; n < nodes.size(); ++n)\n\t\t\t\t{\n\t\t\t\t\t// const auto &b = bs.bases[nodes(n)];\n\t\t\t\t\tconst AssemblyValues &v = vals.basis_values[nodes(n)];\n\t\t\t\t\tconst double area = (weights.array() * v.val.array()).sum();\n\t\t\t\t\tfor (int d = 0; d < size_; ++d)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst double rhs_value = (rhs_fun.col(d).array() * v.val.array()).sum();\n\n\t\t\t\t\t\tfor (size_t g = 0; g < v.global.size(); ++g)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst int g_index = v.global[g].index * size_ + d;\n\t\t\t\t\t\t\tif (problem_.all_dimensions_dirichlet() || std::find(bounday_nodes.begin(), bounday_nodes.end(), g_index) != bounday_nodes.end())\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\trhs(g_index) += rhs_value * v.global[g].val;\n\t\t\t\t\t\t\t\tareas(g_index) += area * v.global[g].val;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (int b : bounday_nodes)\n\t\t{\n\t\t\tassert(areas(b) != 0);\n\t\t\trhs(b) /= areas(b);\n\t\t}\n\t}\n\n\tvoid RhsAssembler::set_bc(\n\t\tconst std::function<void(const Eigen::MatrixXi &, const Eigen::MatrixXd &, const Eigen::MatrixXd &, Eigen::MatrixXd &)> &df,\n\t\tconst std::function<void(const Eigen::MatrixXi &, const Eigen::MatrixXd &, const Eigen::MatrixXd &, const Eigen::MatrixXd &, Eigen::MatrixXd &)> &nf,\n\t\tconst std::vector<LocalBoundary> &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, const std::vector<LocalBoundary> &local_neumann_boundary, Eigen::MatrixXd &rhs) const\n\t{\n\t\tif (bc_method_ == \"sample\")\n\t\t\tsample_bc(df, local_boundary, bounday_nodes, rhs);\n\t\telse if (bc_method_ == \"integrate\")\n\t\t\tintegrate_bc(df, local_boundary, bounday_nodes, resolution, rhs);\n\t\telse\n\t\t\tlsq_bc(df, local_boundary, bounday_nodes, resolution, rhs);\n\n\t\t//Neumann\n\t\tEigen::MatrixXd uv, samples, gtmp, rhs_fun;\n\t\tEigen::VectorXi global_primitive_ids;\n\t\tEigen::MatrixXd points, normals;\n\t\tEigen::VectorXd weights;\n\n\t\tElementAssemblyValues vals;\n\n\t\tfor (const auto &lb : local_neumann_boundary)\n\t\t{\n\t\t\tconst int e = lb.element_id();\n\t\t\tbool has_samples = boundary_quadrature(lb, resolution, false, uv, points, normals, weights, global_primitive_ids);\n\n\t\t\tif (!has_samples)\n\t\t\t\tcontinue;\n\n\t\t\tconst ElementBases &gbs = gbases_[e];\n\t\t\tconst ElementBases &bs = bases_[e];\n\n\t\t\tvals.compute(e, mesh_.is_volume(), points, bs, gbs);\n\n\t\t\tfor (int n = 0; n < vals.jac_it.size(); ++n)\n\t\t\t{\n\t\t\t\tnormals.row(n) = normals.row(n) * vals.jac_it[n];\n\t\t\t\tnormals.row(n).normalize();\n\t\t\t}\n\t\t\t// problem_.neumann_bc(mesh_, global_primitive_ids, vals.val, t, rhs_fun);\n\t\t\tnf(global_primitive_ids, uv, vals.val, normals, rhs_fun);\n\n\t\t\t// UIState::ui_state().debug_data().add_points(vals.val, Eigen::RowVector3d(0,1,0));\n\n\t\t\tfor (int d = 0; d < size_; ++d)\n\t\t\t\trhs_fun.col(d) = rhs_fun.col(d).array() * weights.array();\n\n\t\t\tfor (int i = 0; i < lb.size(); ++i)\n\t\t\t{\n\t\t\t\tconst int primitive_global_id = lb.global_primitive_id(i);\n\t\t\t\tconst auto nodes = bs.local_nodes_for_primitive(primitive_global_id, mesh_);\n\n\t\t\t\tfor (long n = 0; n < nodes.size(); ++n)\n\t\t\t\t{\n\t\t\t\t\t// const auto &b = bs.bases[nodes(n)];\n\t\t\t\t\tconst AssemblyValues &v = vals.basis_values[nodes(n)];\n\t\t\t\t\tfor (int d = 0; d < size_; ++d)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst double rhs_value = (rhs_fun.col(d).array() * v.val.array()).sum();\n\n\t\t\t\t\t\tfor (size_t g = 0; g < v.global.size(); ++g)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst int g_index = v.global[g].index * size_ + d;\n\t\t\t\t\t\t\tconst bool is_neumann = std::find(bounday_nodes.begin(), bounday_nodes.end(), g_index) == bounday_nodes.end();\n\n\t\t\t\t\t\t\tif (is_neumann)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\trhs(g_index) += rhs_value * v.global[g].val;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid RhsAssembler::set_bc(const std::vector<LocalBoundary> &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, const std::vector<LocalBoundary> &local_neumann_boundary, Eigen::MatrixXd &rhs, const double t) const\n\t{\n\t\tset_bc(\n\t\t\t[&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val)\n\t\t\t{ problem_.bc(mesh_, global_ids, uv, pts, t, val); },\n\t\t\t[&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, const Eigen::MatrixXd &normals, Eigen::MatrixXd &val)\n\t\t\t{ problem_.neumann_bc(mesh_, global_ids, uv, pts, normals, t, val); },\n\t\t\tlocal_boundary, bounday_nodes, resolution, local_neumann_boundary, rhs);\n\t}\n\n\tvoid RhsAssembler::set_velocity_bc(const std::vector<LocalBoundary> &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, const std::vector<LocalBoundary> &local_neumann_boundary, Eigen::MatrixXd &rhs, const double t) const\n\t{\n\t\tset_bc(\n\t\t\t[&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val)\n\t\t\t{ problem_.velocity_bc(mesh_, global_ids, uv, pts, t, val); },\n\t\t\t[&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, const Eigen::MatrixXd &normals, Eigen::MatrixXd &val)\n\t\t\t{ problem_.neumann_velocity_bc(mesh_, global_ids, uv, pts, normals, t, val); },\n\t\t\tlocal_boundary, bounday_nodes, resolution, local_neumann_boundary, rhs);\n\t}\n\n\tvoid RhsAssembler::set_acceleration_bc(const std::vector<LocalBoundary> &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, const std::vector<LocalBoundary> &local_neumann_boundary, Eigen::MatrixXd &rhs, const double t) const\n\t{\n\t\tset_bc(\n\t\t\t[&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val)\n\t\t\t{ problem_.acceleration_bc(mesh_, global_ids, uv, pts, t, val); },\n\t\t\t[&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, const Eigen::MatrixXd &normals, Eigen::MatrixXd &val)\n\t\t\t{ problem_.neumann_acceleration_bc(mesh_, global_ids, uv, pts, normals, t, val); },\n\t\t\tlocal_boundary, bounday_nodes, resolution, local_neumann_boundary, rhs);\n\t}\n\n\tvoid RhsAssembler::compute_energy_grad(const std::vector<LocalBoundary> &local_boundary, const std::vector<int> &bounday_nodes, const Density &density, const int resolution, const std::vector<LocalBoundary> &local_neumann_boundary, const Eigen::MatrixXd &final_rhs, const double t, Eigen::MatrixXd &rhs) const\n\t{\n\t\tif (problem_.is_constant_in_time())\n\t\t{\n\t\t\trhs = final_rhs;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tassemble(density, rhs, t);\n\t\t\trhs *= -1;\n\t\t\t// set_bc(local_boundary, bounday_nodes, resolution, local_neumann_boundary, rhs, t);\n\n\t\t\tif (rhs.size() != final_rhs.size())\n\t\t\t{\n\t\t\t\tconst int prev_size = rhs.size();\n\t\t\t\trhs.conservativeResize(final_rhs.size(), rhs.cols());\n\t\t\t\t//Zero initial pressure\n\t\t\t\trhs.block(prev_size, 0, final_rhs.size() - prev_size, rhs.cols()).setZero();\n\t\t\t\trhs(rhs.size() - 1) = 0;\n\t\t\t}\n\n\t\t\tassert(rhs.size() == final_rhs.size());\n\t\t}\n\t}\n\n\tdouble RhsAssembler::compute_energy(const Eigen::MatrixXd &displacement, const std::vector<LocalBoundary> &local_neumann_boundary, const Density &density, const int resolution, const double t) const\n\t{\n\n\t\tdouble res = 0;\n\n\t\tif (!problem_.is_rhs_zero())\n\t\t{\n#if defined(POLYFEM_WITH_CPP_THREADS)\n\t\t\tstd::vector<LocalThreadScalarStorage> storages(polyfem::get_n_threads());\n#elif defined(POLYFEM_WITH_TBB)\n\t\t\ttypedef tbb::enumerable_thread_specific<LocalThreadScalarStorage> LocalStorage;\n\t\t\tLocalStorage storages((LocalThreadScalarStorage()));\n#else\n\t\t\tLocalThreadScalarStorage loc_storage;\n\t\t\tEigen::MatrixXd forces;\n#endif\n\n\t\t\tconst int n_bases = int(bases_.size());\n\n#if defined(POLYFEM_WITH_CPP_THREADS)\n\t\t\tpolyfem::par_for(n_bases, [&](int start, int end, int t)\n\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t auto &loc_storage = storages[t];\n\t\t\t\t\t\t\t\t Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1> local_displacement(size_);\n\t\t\t\t\t\t\t\t Eigen::MatrixXd forces;\n\t\t\t\t\t\t\t\t for (int e = start; e < end; ++e)\n\t\t\t\t\t\t\t\t {\n#elif defined(POLYFEM_WITH_TBB)\n\t\t\ttbb::parallel_for(tbb::blocked_range<int>(0, n_bases), [&](const tbb::blocked_range<int> &r) {\n\t\t\t\tLocalStorage::reference loc_storage = storages.local();\n\t\t\t\tEigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1> local_displacement(size_);\n\t\t\t\tEigen::MatrixXd forces;\n\t\t\t\tfor (int e = r.begin(); e != r.end(); ++e)\n\t\t\t\t{\n#else\n\t\t\tEigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1> local_displacement(size_);\n\n\t\t\tfor (int e = 0; e < n_bases; ++e)\n\t\t\t{\n#endif\n\t\t\t\t\t\t\t\t\t ElementAssemblyValues &vals = loc_storage.vals;\n\t\t\t\t\t\t\t\t\t vals.compute(e, mesh_.is_volume(), bases_[e], gbases_[e]);\n\n\t\t\t\t\t\t\t\t\t const Quadrature &quadrature = vals.quadrature;\n\t\t\t\t\t\t\t\t\t const Eigen::VectorXd da = vals.det.array() * quadrature.weights.array();\n\n\t\t\t\t\t\t\t\t\t problem_.rhs(assembler_, formulation_, vals.val, t, forces);\n\t\t\t\t\t\t\t\t\t assert(forces.rows() == da.size());\n\t\t\t\t\t\t\t\t\t assert(forces.cols() == size_);\n\n\t\t\t\t\t\t\t\t\t for (long p = 0; p < da.size(); ++p)\n\t\t\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t\t\t local_displacement.setZero();\n\n\t\t\t\t\t\t\t\t\t\t for (size_t i = 0; i < vals.basis_values.size(); ++i)\n\t\t\t\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t\t\t\t const auto &bs = vals.basis_values[i];\n\t\t\t\t\t\t\t\t\t\t\t assert(bs.val.size() == da.size());\n\t\t\t\t\t\t\t\t\t\t\t const double b_val = bs.val(p);\n\n\t\t\t\t\t\t\t\t\t\t\t for (int d = 0; d < size_; ++d)\n\t\t\t\t\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t\t\t\t\t for (std::size_t ii = 0; ii < bs.global.size(); ++ii)\n\t\t\t\t\t\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t\t\t\t\t\t local_displacement(d) += (bs.global[ii].val * b_val) * displacement(bs.global[ii].index * size_ + d);\n\t\t\t\t\t\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t\t\t\t const double rho = density(vals.val(p, 0), vals.val(p, 1), vals.val.cols() == 2 ? 0. : vals.val(p, 2), vals.element_id);\n\n\t\t\t\t\t\t\t\t\t\t for (int d = 0; d < size_; ++d)\n\t\t\t\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t\t\t\t loc_storage.val += forces(p, d) * local_displacement(d) * da(p) * rho;\n\t\t\t\t\t\t\t\t\t\t\t // res += forces(p, d) * local_displacement(d) * da(p);\n\t\t\t\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t\t\t }\n#if defined(POLYFEM_WITH_CPP_THREADS) || defined(POLYFEM_WITH_TBB)\n\t\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t });\n#else\n\t\t\t\t}\n#endif\n\n#if defined(POLYFEM_WITH_CPP_THREADS)\n\t\t\tfor (const auto &t : storages)\n\t\t\t{\n\t\t\t\tres += t.val;\n\t\t\t}\n#elif defined(POLYFEM_WITH_TBB)\n\t\t\t\tfor (LocalStorage::iterator i = storages.begin(); i != storages.end(); ++i)\n\t\t\t\t{\n\t\t\t\t\tres += i->val;\n\t\t\t\t}\n#else\n\t\t\t\tres = loc_storage.val;\n#endif\n\t\t}\n\n\t\tEigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1> local_displacement(size_);\n\t\tEigen::MatrixXd forces;\n\n\t\tElementAssemblyValues vals;\n\t\t//Neumann\n\t\tEigen::MatrixXd points, uv, normals;\n\t\tEigen::VectorXd weights;\n\t\tEigen::VectorXi global_primitive_ids;\n\t\tfor (const auto &lb : local_neumann_boundary)\n\t\t{\n\t\t\tconst int e = lb.element_id();\n\t\t\tbool has_samples = boundary_quadrature(lb, resolution, false, uv, points, normals, weights, global_primitive_ids);\n\n\t\t\tif (!has_samples)\n\t\t\t\tcontinue;\n\n\t\t\tconst ElementBases &gbs = gbases_[e];\n\t\t\tconst ElementBases &bs = bases_[e];\n\n\t\t\tvals.compute(e, mesh_.is_volume(), points, bs, gbs);\n\n\t\t\tfor (int n = 0; n < vals.jac_it.size(); ++n)\n\t\t\t{\n\t\t\t\tnormals.row(n) = normals.row(n) * vals.jac_it[n];\n\t\t\t\tnormals.row(n).normalize();\n\t\t\t}\n\t\t\tproblem_.neumann_bc(mesh_, global_primitive_ids, uv, vals.val, normals, t, forces);\n\n\t\t\t// UIState::ui_state().debug_data().add_points(vals.val, Eigen::RowVector3d(1,0,0));\n\n\t\t\tfor (long p = 0; p < weights.size(); ++p)\n\t\t\t{\n\t\t\t\tlocal_displacement.setZero();\n\n\t\t\t\tfor (size_t i = 0; i < vals.basis_values.size(); ++i)\n\t\t\t\t{\n\t\t\t\t\tconst auto &vv = vals.basis_values[i];\n\t\t\t\t\tassert(vv.val.size() == weights.size());\n\t\t\t\t\tconst double b_val = vv.val(p);\n\n\t\t\t\t\tfor (int d = 0; d < size_; ++d)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (std::size_t ii = 0; ii < vv.global.size(); ++ii)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlocal_displacement(d) += (vv.global[ii].val * b_val) * displacement(vv.global[ii].index * size_ + d);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor (int d = 0; d < size_; ++d)\n\t\t\t\t\tres -= forces(p, d) * local_displacement(d) * weights(p);\n\t\t\t}\n\t\t}\n\n\t\treturn res;\n\t}\n\n\tbool RhsAssembler::boundary_quadrature(const LocalBoundary &local_boundary, const int order, const bool skip_computation, Eigen::MatrixXd &uv, Eigen::MatrixXd &points, Eigen::MatrixXd &normals, Eigen::VectorXd &weights, Eigen::VectorXi &global_primitive_ids) const\n\t{\n\t\tuv.resize(0, 0);\n\t\tpoints.resize(0, 0);\n\t\tnormals.resize(0, 0);\n\t\tweights.resize(0);\n\t\tglobal_primitive_ids.resize(0);\n\n\t\tfor (int i = 0; i < local_boundary.size(); ++i)\n\t\t{\n\t\t\tconst int gid = local_boundary.global_primitive_id(i);\n\t\t\tEigen::MatrixXd tmp_p, tmp_uv, tmp_n;\n\t\t\tEigen::VectorXd tmp_w;\n\t\t\tswitch (local_boundary.type())\n\t\t\t{\n\t\t\tcase BoundaryType::TriLine:\n\t\t\t\tBoundarySampler::quadrature_for_tri_edge(local_boundary[i], order, gid, mesh_, tmp_uv, tmp_p, tmp_w);\n\t\t\t\tBoundarySampler::normal_for_tri_edge(local_boundary[i], tmp_n);\n\t\t\t\tbreak;\n\t\t\tcase BoundaryType::QuadLine:\n\t\t\t\tBoundarySampler::quadrature_for_quad_edge(local_boundary[i], order, gid, mesh_, tmp_uv, tmp_p, tmp_w);\n\t\t\t\tBoundarySampler::normal_for_quad_edge(local_boundary[i], tmp_n);\n\t\t\t\tbreak;\n\t\t\tcase BoundaryType::Quad:\n\t\t\t\tBoundarySampler::quadrature_for_quad_face(local_boundary[i], order, gid, mesh_, tmp_uv, tmp_p, tmp_w);\n\t\t\t\tBoundarySampler::normal_for_quad_face(local_boundary[i], tmp_n);\n\t\t\t\tbreak;\n\t\t\tcase BoundaryType::Tri:\n\t\t\t\tBoundarySampler::quadrature_for_tri_face(local_boundary[i], order, gid, mesh_, tmp_uv, tmp_p, tmp_w);\n\t\t\t\tBoundarySampler::normal_for_tri_face(local_boundary[i], tmp_n);\n\t\t\t\tbreak;\n\t\t\tcase BoundaryType::Polygon:\n\t\t\t\tBoundarySampler::quadrature_for_polygon_edge(local_boundary.element_id(), local_boundary.global_primitive_id(i), order, mesh_, tmp_uv, tmp_p, tmp_w);\n\t\t\t\tBoundarySampler::normal_for_polygon_edge(local_boundary.element_id(), local_boundary.global_primitive_id(i), mesh_, tmp_n);\n\t\t\t\tbreak;\n\t\t\tcase BoundaryType::Invalid:\n\t\t\t\tassert(false);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tassert(false);\n\t\t\t}\n\n\t\t\tuv.conservativeResize(uv.rows() + tmp_uv.rows(), tmp_uv.cols());\n\t\t\tuv.bottomRows(tmp_uv.rows()) = tmp_uv;\n\n\t\t\tpoints.conservativeResize(points.rows() + tmp_p.rows(), tmp_p.cols());\n\t\t\tpoints.bottomRows(tmp_p.rows()) = tmp_p;\n\n\t\t\tnormals.conservativeResize(normals.rows() + tmp_p.rows(), tmp_p.cols());\n\t\t\tfor (int k = normals.rows() - tmp_p.rows(); k < normals.rows(); ++k)\n\t\t\t\tnormals.row(k) = tmp_n;\n\n\t\t\tweights.conservativeResize(weights.rows() + tmp_w.rows(), tmp_w.cols());\n\t\t\tweights.bottomRows(tmp_w.rows()) = tmp_w;\n\n\t\t\tglobal_primitive_ids.conservativeResize(global_primitive_ids.rows() + tmp_p.rows());\n\t\t\tglobal_primitive_ids.bottomRows(tmp_p.rows()).setConstant(gid);\n\t\t}\n\n\t\tassert(uv.rows() == global_primitive_ids.size());\n\t\tassert(points.rows() == global_primitive_ids.size());\n\t\tassert(normals.rows() == global_primitive_ids.size());\n\t\tassert(weights.size() == global_primitive_ids.size());\n\n\t\treturn true;\n\t}\n\n\tbool RhsAssembler::sample_boundary(const LocalBoundary &local_boundary, const int n_samples, const bool skip_computation, Eigen::MatrixXd &uv, Eigen::MatrixXd &samples, Eigen::VectorXi &global_primitive_ids) const\n\t{\n\t\tuv.resize(0, 0);\n\t\tsamples.resize(0, 0);\n\t\tglobal_primitive_ids.resize(0);\n\n\t\tfor (int i = 0; i < local_boundary.size(); ++i)\n\t\t{\n\t\t\tEigen::MatrixXd tmp, tmp_uv;\n\t\t\tswitch (local_boundary.type())\n\t\t\t{\n\t\t\tcase BoundaryType::TriLine:\n\t\t\t\tBoundarySampler::sample_parametric_tri_edge(local_boundary[i], n_samples, tmp_uv, tmp);\n\t\t\t\tbreak;\n\t\t\tcase BoundaryType::QuadLine:\n\t\t\t\tBoundarySampler::sample_parametric_quad_edge(local_boundary[i], n_samples, tmp_uv, tmp);\n\t\t\t\tbreak;\n\t\t\tcase BoundaryType::Quad:\n\t\t\t\tBoundarySampler::sample_parametric_quad_face(local_boundary[i], n_samples, tmp_uv, tmp);\n\t\t\t\tbreak;\n\t\t\tcase BoundaryType::Tri:\n\t\t\t\tBoundarySampler::sample_parametric_tri_face(local_boundary[i], n_samples, tmp_uv, tmp);\n\t\t\t\tbreak;\n\t\t\tcase BoundaryType::Polygon:\n\t\t\t\tBoundarySampler::sample_polygon_edge(local_boundary.element_id(), local_boundary.global_primitive_id(i), n_samples, mesh_, tmp_uv, tmp);\n\t\t\t\tbreak;\n\t\t\tcase BoundaryType::Invalid:\n\t\t\t\tassert(false);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tassert(false);\n\t\t\t}\n\n\t\t\tuv.conservativeResize(uv.rows() + tmp_uv.rows(), tmp_uv.cols());\n\t\t\tuv.bottomRows(tmp_uv.rows()) = tmp_uv;\n\n\t\t\tsamples.conservativeResize(samples.rows() + tmp.rows(), tmp.cols());\n\t\t\tsamples.bottomRows(tmp.rows()) = tmp;\n\n\t\t\tglobal_primitive_ids.conservativeResize(global_primitive_ids.rows() + tmp.rows());\n\t\t\tglobal_primitive_ids.bottomRows(tmp.rows()).setConstant(local_boundary.global_primitive_id(i));\n\t\t}\n\n\t\tassert(uv.rows() == global_primitive_ids.size());\n\t\tassert(samples.rows() == global_primitive_ids.size());\n\n\t\treturn true;\n\t}\n\n} // namespace polyfem\n", "meta": {"hexsha": "59b96da8b2e2f11c53d5a4f8f3ade9148c38f034", "size": 31328, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/assembler/RhsAssembler.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/assembler/RhsAssembler.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/assembler/RhsAssembler.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": 34.1263616558, "max_line_length": 310, "alphanum_fraction": 0.6566330439, "num_tokens": 8954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2927832045933706}}
{"text": "#include <complex>\n#include <exception>\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <map>\n#include <fmt/format.h>\n//#include <boost/config/warning_disable.hpp>\n//#include <boost/spirit/home/x3.hpp>\n//#include <range/v3/all.hpp>\n#include <cstdint>\n// 0 ,1\n//1,2\n//(i,j)( i+j +1\n//i,j+1   (i+j+1,0\nint main(int argc, char **argv)\n{\n  int i = 2978 - 1, j = 3083 - 1;\n  int n = (i - 1) + j;\n  int total = 0;\n  for (int i = 0; i <= n; ++i) {\n    total += 1 + i;\n  }\n  total += j + 1;\n  //a[total]-1;\n  std::int64_t a = 20151125;\n  for (int i = 1; i < total; ++i) {\n    a *= 252533;\n    a %= 33554393;\n    //fmt::print(\";i:{},a:{}\", i, a);\n    //\n  }\n  fmt::print(\"{}\", a);\n}\n", "meta": {"hexsha": "746f6f1ae00183c40895a61c9d085dff1fbdce2c", "size": 710, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aoc2015/aoc152501.cpp", "max_stars_repo_name": "jiayuehua/adventOfCode", "max_stars_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aoc2015/aoc152501.cpp", "max_issues_repo_name": "jiayuehua/adventOfCode", "max_issues_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aoc2015/aoc152501.cpp", "max_forks_repo_name": "jiayuehua/adventOfCode", "max_forks_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7222222222, "max_line_length": 45, "alphanum_fraction": 0.5366197183, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2927756597023543}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T.Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSbd:E_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_DETAIL_GENERIC_TRIG_REDUCTION_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_DETAIL_GENERIC_TRIG_REDUCTION_HPP_INCLUDED\n\n#include <boost/simd/function/fast.hpp>\n#include <boost/simd/function/rem_pio2_medium.hpp>\n#include <boost/simd/function/rem_pio2_cephes.hpp>\n#include <boost/simd/function/rem_pio2_straight.hpp>\n#include <boost/simd/function/rem_pio2.hpp>\n#include <boost/simd/function/logical_and.hpp>\n#include <boost/simd/function/split.hpp>\n#include <boost/simd/function/group.hpp>\n#include <boost/dispatch/meta/upgrade.hpp>\n\n#include <boost/simd/function/all.hpp>\n#include <boost/simd/function/toint.hpp>\n#include <boost/simd/function/round2even.hpp>\n#include <boost/simd/function/if_else_nan.hpp>\n#include <boost/simd/function/is_ngt.hpp>\n#include <boost/simd/function/is_nez.hpp>\n#include <boost/simd/function/is_flint.hpp>\n#include <boost/simd/function/all.hpp>\n#include <boost/simd/function/inrad.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/divides.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/pi.hpp>\n#include <boost/simd/constant/pio_2.hpp>\n#include <boost/simd/constant/pio_4.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/constant/medium_pi.hpp>\n#include <boost/simd/constant/false.hpp>\n#include <boost/simd/constant/ratio.hpp>\n#include <boost/simd/constant/constant.hpp>\n#include <boost/simd/constant/real.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/dispatch/meta/scalar_of.hpp>\n\n\n//#include <nt2/sdk/meta/as_logical.hpp>\n//#include <boost/simd/sdk/meta/is_upgradable.hpp>\n\n\n\nnamespace boost { namespace simd\n{\n  namespace detail\n  {\n    template< class A0\n            , class unit_tag\n            , class style\n            , class mode\n            , class base_A0 = bd::scalar_of_t<A0>\n    >\n    struct trig_reduction;\n\n    // This class exposes the public static member:\n    // reduce:                to provide range reduction\n    //\n    // unit_tag allows to choose statically the scaling  among radian_tag, pi_tag, degree_tag\n    // meaning that the cosa function will (for example) define respectively\n    // x-->cos(x)          (radian_tag),\n    // x-->cos(p*x)        (pi_tag)\n    // x-->cos((pi/180)*x) (degree_tag)\n    //\n\n    // trigonometric reduction strategies in the [-pi/4, pi/4] range.\n    // these reductions are used in the accurate and fast\n    // trigonometric functions with different policies\n\n    template<class A0, class style, class mode>\n    struct trig_reduction < A0, tag::radian_tag, style, mode>\n    {\n      using i_t = bd::as_integer_t<A0, signed>;\n      using l_t = bs::as_logical_t<A0>;\n      using conversion_allowed_t = std::false_type; //bd::is_upgradable_on_ext_<A0>; // TODO\n\n      static BOOST_FORCEINLINE auto is_0_pio4_reduced(const A0&a0) BOOST_NOEXCEPT\n      ->  decltype(is_ngt(a0, Pio_4<A0>()))\n      {\n        return is_ngt(a0, Pio_4<A0>());\n      }\n      static BOOST_FORCEINLINE auto is_0_pio2_reduced(const A0&a0) BOOST_NOEXCEPT\n      ->  decltype(is_ngt(a0, Pio_2<A0>()))\n      {\n        return is_ngt(a0, Pio_2<A0>());\n      }\n      static BOOST_FORCEINLINE auto is_0_20pi_reduced(const A0&a0) BOOST_NOEXCEPT\n      ->  decltype(is_ngt(a0, Real<A0, 0X404F6A7A2955385EULL, 0X427B53D1UL>()))\n      {\n        return is_ngt(a0, Real<A0, 0X404F6A7A2955385EULL, 0X427B53D1UL>()); //20 pi;\n      }\n      static BOOST_FORCEINLINE auto is_0_mpi_reduced (const A0&a0) BOOST_NOEXCEPT\n      ->  decltype(is_ngt(a0, Medium_pi<A0>()))\n      {\n        return is_ngt(a0, Medium_pi<A0>()); //2^6 pi\n      }\n      static BOOST_FORCEINLINE auto is_0_dmpi_reduced(const A0&a0) BOOST_NOEXCEPT\n      ->  decltype(is_ngt(a0,Constant<A0,262144>()))\n      {\n        return is_ngt(a0, Ratio<A0,262144>()); //2^18 pi\n      }\n\n      static BOOST_FORCEINLINE l_t cot_invalid(const A0& )  BOOST_NOEXCEPT\n      {\n        return False<l_t>();\n      }\n      static BOOST_FORCEINLINE l_t tan_invalid(const A0& )  BOOST_NOEXCEPT\n      {\n        return False<l_t>();\n      }\n\n      static BOOST_FORCEINLINE i_t reduce(const A0& x, A0& xr)  BOOST_NOEXCEPT\n      {\n        return inner_reduce(x, xr);\n      }\n\n      static BOOST_FORCEINLINE i_t inner_reduce(const A0& x, A0& xr) BOOST_NOEXCEPT\n      {\n        A0 xx =  preliminary<mode>::clip(x);\n        return select_mode(xx, xr, boost::mpl::int_<mode::start>());\n      }\n\n      template < class Mode, bool clipped = Mode::clipped>\n      struct preliminary\n      {\n        static BOOST_FORCEINLINE A0 const& clip(const A0& x) BOOST_NOEXCEPT  { return x; }\n      };\n\n\n      template < class Mode>\n      struct preliminary<Mode, true>\n      {\n        static BOOST_FORCEINLINE A0 clip(const A0& x) BOOST_NOEXCEPT\n        {\n          return clipto(x, boost::mpl::int_<Mode::range>());\n        }\n      private :\n        static BOOST_FORCEINLINE A0 clipto(const A0& x\n                                          , boost::mpl::int_<tag::r_0_pio4> const&) BOOST_NOEXCEPT\n        {\n          return if_else_nan(is_0_pio4_reduced(x), x);\n        }\n        static BOOST_FORCEINLINE A0 clipto(const A0& x\n                                          , boost::mpl::int_<tag::r_0_20pi> const&) BOOST_NOEXCEPT\n        {\n          return if_else_nan(is_0_20pi_reduced(x), x);\n        }\n        static BOOST_FORCEINLINE A0 clipto(const A0& x\n                                          , boost::mpl::int_<tag::r_0_mpi> const&) BOOST_NOEXCEPT\n        {\n          return if_else_nan(is_0_mpi_reduced(x), x);\n        }\n        static BOOST_FORCEINLINE A0 clipto(const A0& x\n                                          , boost::mpl::int_<tag::r_0_dmpi> const&) BOOST_NOEXCEPT\n        {\n          return if_else_nan(is_0_dmpi_reduced(x), x);\n        }\n      };\n\n      static BOOST_FORCEINLINE i_t\n      select_range( const A0& xx, A0& xr\n                  , boost::mpl::true_ const&\n                  , boost::mpl::int_<tag::r_0_pio4> const&\n                  ) BOOST_NOEXCEPT\n      {\n        xr = xx;\n        return Zero<i_t>();\n      }\n\n      static BOOST_FORCEINLINE i_t\n      select_range( const A0& xx, A0& xr\n                  , boost::mpl::false_ const&\n                  , boost::mpl::int_<tag::r_0_pio4> const& r\n                  ) BOOST_NOEXCEPT\n      {\n        if(all(is_0_pio4_reduced(xx)))\n          return select_range(xx,xr,boost::mpl::true_(), r);\n\n        return select_mode(xx,xr,boost::mpl::int_<tag::r_0_pio2>());\n      }\n\n      static BOOST_FORCEINLINE i_t\n      select_mode(const A0& xx, A0& xr\n                 , boost::mpl::int_<tag::r_0_pio4> const& r) BOOST_NOEXCEPT\n      {\n        return select_range(xx,xr,boost::mpl::bool_<mode::range == tag::r_0_pio4>(),r);\n      }\n\n      static BOOST_FORCEINLINE i_t\n      select_mode(const A0& xx, A0& xr\n                 , boost::mpl::int_<tag::r_0_pio2> const&) BOOST_NOEXCEPT\n      {\n        if(all(is_0_pio2_reduced(xx)))\n          return rem_pio2_straight(xx, xr);\n        return select_mode(xx,xr,boost::mpl::int_<tag::r_0_20pi>());\n      }\n\n      static BOOST_FORCEINLINE i_t\n      select_range( const A0& xx, A0& xr\n                  , boost::mpl::true_ const&\n                  , boost::mpl::int_<tag::r_0_20pi> const&\n                  ) BOOST_NOEXCEPT\n      {\n        return rem_pio2_cephes(xx, xr);\n      }\n\n      static BOOST_FORCEINLINE i_t\n      select_range( const A0& xx, A0& xr\n                  , boost::mpl::false_ const&\n                  , boost::mpl::int_<tag::r_0_20pi> const& r\n                  ) BOOST_NOEXCEPT\n      {\n        if(all(is_0_20pi_reduced(xx)))\n          return select_range(xx,xr,boost::mpl::true_(), r);\n\n        return select_mode(xx,xr,boost::mpl::int_<tag::r_0_mpi>());\n      }\n\n      static BOOST_FORCEINLINE i_t\n      select_mode(const A0& xx, A0& xr\n                 , boost::mpl::int_< tag::r_0_20pi> const& r) BOOST_NOEXCEPT\n      {\n        return select_range(xx,xr,boost::mpl::bool_<mode::range == tag::r_0_20pi>(),r);\n      }\n\n\n\n      static BOOST_FORCEINLINE i_t\n      select_range( const A0& xx, A0& xr\n                  , boost::mpl::true_ const&\n                  , boost::mpl::int_<tag::r_0_mpi> const&\n                  ) BOOST_NOEXCEPT\n      {\n        return rem_pio2_medium(xx, xr);\n      }\n\n      static BOOST_FORCEINLINE i_t\n      select_range( const A0& xx, A0& xr\n                  , boost::mpl::false_ const&\n                  , boost::mpl::int_<tag::r_0_mpi> const& r\n                  ) BOOST_NOEXCEPT\n      {\n        if(all(is_0_mpi_reduced(xx)))\n          return select_range(xx,xr,boost::mpl::true_(), r);\n\n        return select_mode(xx,xr,boost::mpl::int_<tag::r_0_dmpi>());\n      }\n\n      static BOOST_FORCEINLINE i_t\n      select_mode(const A0& xx, A0& xr\n                 , boost::mpl::int_< tag::r_0_mpi> const& r) BOOST_NOEXCEPT\n      {\n        return select_range(xx,xr,boost::mpl::bool_<mode::range == tag::r_0_mpi>(),r);\n      }\n\n      static BOOST_FORCEINLINE i_t\n      select_mode(const A0& xx, A0& xr\n                 , boost::mpl::int_< tag::r_0_dmpi> const&) BOOST_NOEXCEPT\n      {\n        if(all(is_0_dmpi_reduced(xx)))\n           return use_conversion(xx, xr, style(), conversion_allowed_t());\n        return rem_pio2(xx, xr);\n      }\n\n      static BOOST_FORCEINLINE i_t\n      use_conversion(const A0 & xx,  A0& xr\n                    ,  const style &, std::false_type) BOOST_NOEXCEPT\n      {\n        return rem_pio2(xx, xr);\n      }\n\n      static BOOST_FORCEINLINE i_t\n      use_conversion(const A0 & xx,  A0& xr\n                    ,  const tag::not_simd_type &, std::true_type) BOOST_NOEXCEPT\n      {\n        // all of x are in [0, 2^18*pi],  conversion to double is used to reduce\n        using uA0 = bd::upgrade_t<A0>;\n        using aux_reduction = trig_reduction< uA0,tag::radian_tag,tag::not_simd_type,mode,double>;\n        uA0 ux = xx, uxr;\n        i_t n = static_cast<i_t>(aux_reduction::reduce(ux, uxr));\n        xr = static_cast<A0>(uxr);\n        return n;\n      }\n\n      static BOOST_FORCEINLINE i_t\n      use_conversion(const A0 & x,  A0& xr\n                    , const tag::simd_type &,std::true_type) BOOST_NOEXCEPT\n      {\n        // all of x are in [0, 2^18*pi],  conversion to double is used to reduce\n        using uA0 = bd::upgrade_t<A0>;\n        using aux_reduc_t = trig_reduction< uA0, tag::radian_tag,  tag::simd_type, mode, double>;\n        uA0 ux1, ux2, uxr1, uxr2;\n        split(x, ux1, ux2);\n        auto n1 = aux_reduc_t::reduce(ux1, uxr1);\n        auto n2 = aux_reduc_t::reduce(ux2, uxr2);\n        xr = group(uxr1, uxr2);\n        split(xr, ux1, ux2);\n        return group(n1, n2);\n      }\n    };\n\n    template<class A0, class style>\n    struct trig_reduction<A0,tag::degree_tag, style, tag::big_tag>\n    {\n      using i_t = bd::as_integer_t<A0, signed>;\n\n      static BOOST_FORCEINLINE auto cot_invalid(const A0& x) BOOST_NOEXCEPT\n      -> decltype(is_nez(x)&&is_flint(x*Ratio<A0,1,180>()))\n      {\n        return is_nez(x)&&is_flint(x*Ratio<A0,1,180>());\n      }\n      static BOOST_FORCEINLINE auto tan_invalid(const A0& x) BOOST_NOEXCEPT\n      -> decltype(is_flint((x- Ratio<A0,90>())*Ratio<A0,1,180>()))\n      {\n        return is_flint((x- Ratio<A0,90>())*Ratio<A0,1,180>());\n      }\n\n      static BOOST_FORCEINLINE i_t reduce(const A0& x, A0& xr) BOOST_NOEXCEPT\n      {\n        A0 xi = round2even(x*Ratio<A0,1,90>());\n        A0 x2 = x - xi * Ratio<A0,90>();\n\n        xr =  inrad(x2);\n        return bs::fast_(toint)(xi);\n      }\n    };\n\n#ifdef BOOST_SIMD_HAS_X87\n    template<class A0>\n    struct trig_reduction<A0,degree_tag, tag::not_simd_type, tag::big_tag>\n    {\n      using i_t = bd::as_integer_t<A0, signed>;\n\n      static BOOST_FORCEINLINE auto cot_invalid(const A0& x) BOOST_NOEXCEPT\n      -> decltype(is_nez(x)&&is_flint(x*Ratio<A0,1,180>()))\n      {\n        return is_nez(x)&&is_flint(x/Constant<A0,180>());\n      }\n      static BOOST_FORCEINLINE auto tan_invalid(const A0& x) BOOST_NOEXCEPT\n      -> decltype(is_flint((x- Ratio<A0,90>())/Constant<A0,180>()))\n      {\n        return is_flint((x- Ratio<A0,90>())*Ratio<A0,1,180>());\n      }\n\n      static BOOST_FORCEINLINE i_t reduce(const A0& x, A0& xr) BOOST_NOEXCEPT\n      {\n        A0 xi = round2even(x*Ratio<A0,1,90>());\n        A0 x2 = x - xi * Ratio<A0,90>();\n\n        xr =  inrad(x2);\n        return bs::fast_(toint)(xi);\n      }\n    };\n#endif\n\n    template < class A0, class style>\n    struct trig_reduction < A0, tag::pi_tag,  style, tag::big_tag>\n    {\n      using i_t = bd::as_integer_t<A0, signed>;\n\n      static BOOST_FORCEINLINE auto cot_invalid(const A0& x) BOOST_NOEXCEPT\n      -> decltype(is_nez(x)&&is_flint(x))\n      {\n        return is_nez(x)&&is_flint(x);\n      }\n      static BOOST_FORCEINLINE auto tan_invalid(const A0& x) BOOST_NOEXCEPT\n      -> decltype(is_flint(x-Half<A0>()))\n      {\n        return is_flint(x-Half<A0>()) ;\n      }\n\n      static BOOST_FORCEINLINE i_t reduce(const A0& x,  A0& xr) BOOST_NOEXCEPT\n      {\n        A0 xi = round2even(x*Two<A0>());\n        A0 x2 = x - xi * Half<A0>();\n        xr = x2*Pi<A0>();\n        return fast_(toint)(xi);\n      }\n    };\n  }\n} }\n\n\n#endif\n", "meta": {"hexsha": "7fda9d1faaf5ed37823b8b11611e9cf08cee0dc9", "size": 13559, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/detail/generic/trig_reduction.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/detail/generic/trig_reduction.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/detail/generic/trig_reduction.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.067839196, "max_line_length": 100, "alphanum_fraction": 0.5954716425, "num_tokens": 3837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.69925440852404, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.29277565970235425}}
{"text": "#include <boost/python/module.hpp>\n#include <boost/python/def.hpp>\n#include <dials/array_family/reflection_table.h>\n#include <cctbx/miller.h>\n\nnamespace xfel {\nnamespace merging {\nnamespace error_model {\nnamespace sdfac_refine {\n\ntypedef\n scitbx::af::versa<cctbx::miller::index<>, scitbx::af::flex_grid<> > shared_miller;\n\nusing namespace dials::af;\n\nstatic scitbx::af::shared<double>\ncompute_normalized_deviations(reflection_table ISIGI, shared_miller hkl_list) {\n  /*\n   * This formulation of the normalized deviations of a set of intensities and sigmas is similar to that\n   * described in Evans 2011, but includes the nn term as currently implmented by aimless\n   *\n   */\n  SCITBX_ASSERT(ISIGI.contains(\"scaled_intensity\"));\n  SCITBX_ASSERT(ISIGI.contains(\"meanprime_scaled_intensity\"));\n  SCITBX_ASSERT(ISIGI.contains(\"isigi\"));\n  SCITBX_ASSERT(ISIGI.contains(\"nn\"));\n\n  scitbx::af::shared<double>         result(ISIGI.size(), 0);\n  scitbx::af::const_ref<double>      scaled_intensity = ISIGI[\"scaled_intensity\"];\n  scitbx::af::const_ref<double>      meanprime_scaled_intensity = ISIGI[\"meanprime_scaled_intensity\"];\n  scitbx::af::const_ref<double>      isigi = ISIGI[\"isigi\"];\n  scitbx::af::const_ref<double>      nn = ISIGI[\"nn\"];\n\n  double sigma;\n  #pragma omp parallel for private(sigma)\n  for (int i = 0; i < ISIGI.size(); i++) {\n    if (isigi[i] == 0 || scaled_intensity[i] == 0) continue;\n    sigma = scaled_intensity[i] / isigi[i];\n    result[i] = std::sqrt(nn[i]) * (scaled_intensity[i] - meanprime_scaled_intensity[i]) / sigma;\n  }\n  return result;\n}\n\nvoid\napply_sd_error_params(reflection_table ISIGI, const double sdfac, const double sdb, const double sdadd, const bool squared_params) {\n  /*\n   * Apply a set of sd params (sdfac, sdb and sdd) to an ISIGI reflection table\n\n   Squared not only uses the squared formulation of sigma', but also fixes 2 bugs:\n   1) Use meanI not meanIprime\n   2) When returning isigi, don't multiply by slope\n\n   If using squared, it is assumed that sdfac, sdb and sdadd have already been squared\n   */\n  SCITBX_ASSERT(ISIGI.contains(\"scaled_intensity\"));\n  SCITBX_ASSERT(ISIGI.contains(\"mean_scaled_intensity\"));\n  SCITBX_ASSERT(ISIGI.contains(\"meanprime_scaled_intensity\"));\n  SCITBX_ASSERT(ISIGI.contains(\"isigi\"));\n  SCITBX_ASSERT(ISIGI.contains(\"slope\"));\n  SCITBX_ASSERT(ISIGI.contains(\"miller_id\"));\n\n  scitbx::af::const_ref<double>      scaled_intensity = ISIGI[\"scaled_intensity\"];\n  scitbx::af::const_ref<double>      mean_scaled_intensity = ISIGI[\"mean_scaled_intensity\"];\n  scitbx::af::const_ref<double>      meanprime_scaled_intensity = ISIGI[\"meanprime_scaled_intensity\"];\n  scitbx::af::ref<double>            isigi = ISIGI[\"isigi\"];\n  scitbx::af::const_ref<double>      slope = ISIGI[\"slope\"];\n  scitbx::af::shared<double>         sigmas(ISIGI.size(), 0);\n  scitbx::af::const_ref<std::size_t> miller_id = ISIGI[\"miller_id\"];\n\n  std::size_t max_miller_id = scitbx::af::max(miller_id);\n  scitbx::af::shared<std::size_t>    n_refl(max_miller_id+1, 0);\n  scitbx::af::shared<double>         isum(max_miller_id+1, 0);\n\n  double tmp = 0;\n  double sigma_corrected = 0;\n  double meanI, meanIprime, minimum;\n  #pragma omp parallel for private(meanI, meanIprime, minimum)\n  for (int i = 0; i < ISIGI.size(); i++) {\n    // scaled intensity (iobs/slope)\n    // corrected sigma (original sigma/slope)\n    sigmas[i] = scaled_intensity[i] / isigi[i];\n\n    // apply correction parameters\n    if (squared_params) {\n      // use meanI, which is the mean of all observations of this hkl\n      meanI = mean_scaled_intensity[i];\n      tmp = std::pow(sigmas[i],2) + sdb * meanI + sdadd * std::pow(meanI,2);\n    }\n    else {\n      // use meanIprime, which for each observation, is the mean of all other observations of this hkl\n      meanIprime = meanprime_scaled_intensity[i];\n      tmp = std::pow(sigmas[i],2) + sdb * meanIprime + std::pow(sdadd*meanIprime,2);\n    }\n\n    // avoid rare negatives\n    minimum = 0.1 * std::pow(sigmas[i],2);\n    if (tmp < minimum)\n      tmp = minimum;\n\n    if (squared_params) {\n      sigma_corrected = std::sqrt(sdfac * tmp);\n      SCITBX_ASSERT(sigma_corrected != 0.0);\n      isigi[i] = scaled_intensity[i] / sigma_corrected;\n    }\n    else {\n      sigma_corrected = sdfac * std::sqrt(tmp);\n      SCITBX_ASSERT(sigma_corrected != 0.0);\n      isigi[i] = scaled_intensity[i] * slope[i]/ sigma_corrected;\n    }\n  }\n}\n\nscitbx::af::shared<double> df_dpsq(scitbx::af::shared<double>all_sigmas_normalized,\n                                   scitbx::af::shared<double>sigma_prime,\n                                   scitbx::af::shared<double>dsigmasq_dpsq,\n                                   reflection_table ISIGI,\n                                   scitbx::af::shared<int>bin_indices,\n                                   size_t n_bins) {\n  scitbx::af::shared<double> g(n_bins, 0);\n  scitbx::af::shared<double> dsigmanormsq_dpsq(ISIGI.size());\n\n  scitbx::af::const_ref<double> scaled_intensity = ISIGI[\"scaled_intensity\"];\n  scitbx::af::const_ref<double> meanprime_scaled_intensity = ISIGI[\"meanprime_scaled_intensity\"];\n  scitbx::af::const_ref<double> nn = ISIGI[\"nn\"];\n\n  scitbx::af::shared<int> counts(n_bins);\n  scitbx::af::shared<double> bnssq(n_bins);\n  scitbx::af::shared<double> t3(n_bins);\n\n  double tmp, c; int b;\n  // OpenMP doesn't work here. Need a reduction. Easy in OpenMP 4.5 which isn't available yet for my gcc\n  for (int i = 0; i < ISIGI.size(); i++) {\n    tmp = scaled_intensity[i]-meanprime_scaled_intensity[i];\n    c = nn[i] * tmp * tmp;\n    dsigmanormsq_dpsq[i] = -c / std::pow(sigma_prime[i], 4) * dsigmasq_dpsq[i];\n\n    b = bin_indices[i];\n    counts[b]++;\n    bnssq[b] += all_sigmas_normalized[i] * all_sigmas_normalized[i];\n    t3[b] += dsigmanormsq_dpsq[i];\n  }\n\n  int n; double t1, t2;\n  #pragma omp parallel for private(n, t1, t2)\n  for (int b = 0; b < n_bins; b++) {\n    n = counts[b];\n\n    if (!(n == 0 || bnssq[b] == 0.)) {\n      bnssq[b] /= n;\n      t1 = 2 * (1 - std::sqrt(bnssq[b]));\n      t2 = -0.5 / std::sqrt(bnssq[b]);\n      t3[b] /= n;\n      g[b] = t1 * t2 * t3[b];\n    }\n  }\n  return g;\n}\n\n/* Jiffy function to compute statistics needed downstream\n  For every observation, computes:\n  mean_scaled_intensity: mean of all observations of this miller index\n  meanprime_scaled_intensity: mean of all observations of this miller index except this observation\n  n_refl: count of observed reflections for this miller index\n  nn: n_refl-1/n_refl\n*/\nvoid setup_isigi_stats(reflection_table ISIGI, scitbx::af::const_ref<cctbx::miller::index<> > indices) {\n  scitbx::af::shared<double> sumI                = scitbx::af::shared<double>(indices.size(), 0);\n  scitbx::af::shared<double> n_refl              = scitbx::af::shared<double>(indices.size(), 0);\n  scitbx::af::const_ref<size_t> miller_id        = ISIGI[\"miller_id\"];\n  scitbx::af::const_ref<double> scaled_intensity = ISIGI[\"scaled_intensity\"];\n\n  for (size_t i = 0; i < ISIGI.size(); i++) {\n    size_t hkl_id = miller_id[i];\n    sumI[hkl_id] += scaled_intensity[i];\n    n_refl[hkl_id] += 1;\n  }\n\n  scitbx::af::shared<double> all_meanI      = scitbx::af::shared<double>(ISIGI.size(), 0);\n  scitbx::af::shared<double> all_n_refl     = scitbx::af::shared<double>(ISIGI.size(), 0);\n  scitbx::af::shared<double> nn             = scitbx::af::shared<double>(ISIGI.size(), 0);\n  scitbx::af::shared<double> all_imeanprime = scitbx::af::shared<double>(ISIGI.size(), 0);\n  for (size_t i = 0; i < ISIGI.size(); i++) {\n    size_t hkl_id = miller_id[i];\n    all_meanI[i] = sumI[hkl_id]/n_refl[hkl_id];\n    all_n_refl[i] = n_refl[hkl_id];\n    nn[i] = (n_refl[hkl_id]-1)/n_refl[hkl_id];\n    SCITBX_ASSERT(n_refl[hkl_id] > 0);\n    if (n_refl[hkl_id] > 1)\n      all_imeanprime[i] = (sumI[hkl_id]-scaled_intensity[i])/(n_refl[hkl_id]-1);\n  }\n  ISIGI[\"mean_scaled_intensity\"] = all_meanI;\n  ISIGI[\"n_refl\"] = all_n_refl;\n  ISIGI[\"nn\"] = nn;\n  ISIGI[\"meanprime_scaled_intensity\"] = all_imeanprime ;\n}\n\nnamespace boost_python { namespace {\n  void\n  init_module() {\n    using namespace boost::python;\n    def(\"compute_normalized_deviations\", &compute_normalized_deviations);\n    def(\"apply_sd_error_params\", &apply_sd_error_params);\n    def(\"df_dpsq\", &df_dpsq);\n    def(\"setup_isigi_stats\", &setup_isigi_stats);\n}\n}}\n}}}} // namespace\n\nBOOST_PYTHON_MODULE(xfel_sdfac_refine_ext)\n{\n  xfel::merging::error_model::sdfac_refine::boost_python::init_module();\n\n}\n", "meta": {"hexsha": "790512877af92911309f756cc53f63db83d9aeb7", "size": 8390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xfel/merging/algorithms/error_model/sdfac_refine_ext.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "xfel/merging/algorithms/error_model/sdfac_refine_ext.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "xfel/merging/algorithms/error_model/sdfac_refine_ext.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 39.2056074766, "max_line_length": 132, "alphanum_fraction": 0.6661501788, "num_tokens": 2528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017746, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2927140846865681}}
{"text": "#include <Eigen/Geometry>\n#include <algorithm>\n#include <elasty/cloth-sim-object.hpp>\n#include <elasty/constraint.hpp>\n#include <elasty/particle.hpp>\n#include <elasty/utils.hpp>\n#include <iostream>\n#include <tiny_obj_loader.h>\n\nelasty::ClothSimObject::ClothSimObject(const unsigned           resolution,\n                                       const double             in_plane_stiffness,\n                                       const double             in_plane_compliance,\n                                       const double             out_of_plane_stiffness,\n                                       const double             out_of_plane_compliance,\n                                       const double             dt,\n                                       const Eigen::Affine3d&   transform,\n                                       const InPlaneStrategy    in_plane_strategy,\n                                       const OutOfPlaneStrategy out_of_plane_strategy)\n{\n    std::istringstream obj_data_stream(generateClothMeshObjData(2.0, 2.0, resolution, resolution));\n\n    tinyobj::attrib_t                attrib;\n    std::vector<tinyobj::shape_t>    shapes;\n    std::vector<tinyobj::material_t> materials;\n\n    std::string warn;\n    std::string err;\n    const bool  return_value = tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, &obj_data_stream);\n\n    if (!warn.empty())\n    {\n        std::cerr << warn << std::endl;\n    }\n    if (!err.empty())\n    {\n        std::cerr << err << std::endl;\n    }\n    if (!return_value)\n    {\n        throw std::runtime_error(\"\");\n    }\n    if (attrib.vertices.empty())\n    {\n        throw std::runtime_error(\"\");\n    }\n\n    const auto& shape = shapes[0];\n\n    assert(shapes.size() == 1);\n    assert(attrib.vertices.size() % 3 == 0);\n    assert(shape.mesh.indices.size() % 3 == 0);\n\n    m_triangle_list.resize(shape.mesh.indices.size() / 3, 3);\n    for (unsigned int i = 0; i < shape.mesh.indices.size() / 3; ++i)\n    {\n        m_triangle_list(i, 0) = shape.mesh.indices[i * 3 + 0].vertex_index;\n        m_triangle_list(i, 1) = shape.mesh.indices[i * 3 + 1].vertex_index;\n        m_triangle_list(i, 2) = shape.mesh.indices[i * 3 + 2].vertex_index;\n    }\n\n    if (!attrib.texcoords.empty())\n    {\n        m_uv_list.resize(shape.mesh.indices.size() / 3, 2 * 3);\n        for (unsigned int i = 0; i < shape.mesh.indices.size() / 3; ++i)\n        {\n            m_uv_list(i, 2 * 0 + 0) = attrib.texcoords[2 * shape.mesh.indices[i * 3 + 0].texcoord_index + 0];\n            m_uv_list(i, 2 * 0 + 1) = attrib.texcoords[2 * shape.mesh.indices[i * 3 + 0].texcoord_index + 1];\n            m_uv_list(i, 2 * 1 + 0) = attrib.texcoords[2 * shape.mesh.indices[i * 3 + 1].texcoord_index + 0];\n            m_uv_list(i, 2 * 1 + 1) = attrib.texcoords[2 * shape.mesh.indices[i * 3 + 1].texcoord_index + 1];\n            m_uv_list(i, 2 * 2 + 0) = attrib.texcoords[2 * shape.mesh.indices[i * 3 + 2].texcoord_index + 0];\n            m_uv_list(i, 2 * 2 + 1) = attrib.texcoords[2 * shape.mesh.indices[i * 3 + 2].texcoord_index + 1];\n        }\n    }\n\n    std::map<unsigned int, std::shared_ptr<Particle>> map_from_obj_vertex_index_to_particle;\n    for (unsigned int i = 0; i < attrib.vertices.size() / 3; ++i)\n    {\n        const Eigen::Vector3d position{\n            attrib.vertices[3 * i + 0], attrib.vertices[3 * i + 1], attrib.vertices[3 * i + 2]};\n\n        const Eigen::Vector3d x = transform * position;\n        const Eigen::Vector3d v = Eigen::Vector3d::Zero();\n        const double          m = 1.0 / double(attrib.vertices.size());\n\n        auto particle = std::make_shared<elasty::Particle>(x, v, m);\n\n        map_from_obj_vertex_index_to_particle[i] = particle;\n\n        m_particles.push_back(particle);\n    }\n\n    for (unsigned int i = 0; i < shape.mesh.indices.size() / 3; ++i)\n    {\n        const auto p_0 = map_from_obj_vertex_index_to_particle[shape.mesh.indices[i * 3 + 0].vertex_index];\n        const auto p_1 = map_from_obj_vertex_index_to_particle[shape.mesh.indices[i * 3 + 1].vertex_index];\n        const auto p_2 = map_from_obj_vertex_index_to_particle[shape.mesh.indices[i * 3 + 2].vertex_index];\n\n        if (in_plane_strategy == InPlaneStrategy::EdgeDistance || in_plane_strategy == InPlaneStrategy::Both)\n        {\n            m_constraints.push_back(std::make_shared<elasty::DistanceConstraint>(\n                p_0, p_1, in_plane_stiffness, in_plane_compliance, dt, (p_0->x - p_1->x).norm()));\n            m_constraints.push_back(std::make_shared<elasty::DistanceConstraint>(\n                p_0, p_2, in_plane_stiffness, in_plane_compliance, dt, (p_0->x - p_2->x).norm()));\n            m_constraints.push_back(std::make_shared<elasty::DistanceConstraint>(\n                p_1, p_2, in_plane_stiffness, in_plane_compliance, dt, (p_1->x - p_2->x).norm()));\n        }\n\n        if (in_plane_strategy == InPlaneStrategy::ContinuumTriangle || in_plane_strategy == InPlaneStrategy::Both)\n        {\n            m_constraints.push_back(std::make_shared<elasty::ContinuumTriangleConstraint>(\n                p_0, p_1, p_2, in_plane_stiffness, in_plane_compliance, dt, 1000.0, 0.10));\n        }\n    }\n\n    using vertex_t   = unsigned int;\n    using triangle_t = unsigned int;\n    using edge_t     = std::pair<vertex_t, vertex_t>;\n    std::map<edge_t, std::vector<triangle_t>> edges_and_triangles;\n    for (unsigned int i = 0; i < shape.mesh.indices.size() / 3; ++i)\n    {\n        const vertex_t index_0 = shape.mesh.indices[i * 3 + 0].vertex_index;\n        const vertex_t index_1 = shape.mesh.indices[i * 3 + 1].vertex_index;\n        const vertex_t index_2 = shape.mesh.indices[i * 3 + 2].vertex_index;\n\n        const edge_t e_01 = std::make_pair(std::min(index_0, index_1), std::max(index_0, index_1));\n        const edge_t e_02 = std::make_pair(std::min(index_0, index_2), std::max(index_0, index_2));\n        const edge_t e_12 = std::make_pair(std::min(index_1, index_2), std::max(index_1, index_2));\n\n        auto register_edge = [&](const edge_t& edge)\n        {\n            if (edges_and_triangles.find(edge) == edges_and_triangles.end())\n            {\n                edges_and_triangles[edge] = {i};\n            }\n            else\n            {\n                edges_and_triangles[edge].push_back(i);\n            }\n        };\n\n        register_edge(e_01);\n        register_edge(e_02);\n        register_edge(e_12);\n    }\n\n    for (const auto& key_value : edges_and_triangles)\n    {\n        const edge_t&                  edge      = key_value.first;\n        const std::vector<triangle_t>& triangles = key_value.second;\n\n        assert(triangles.size() == 1 || triangles.size() == 2);\n\n        // Boundary\n        if (triangles.size() == 1)\n        {\n            continue;\n        }\n\n        auto obtain_another_vertex = [&](const triangle_t& triangle, const edge_t& edge)\n        {\n            const vertex_t vertex_0 = shape.mesh.indices[3 * triangle + 0].vertex_index;\n            const vertex_t vertex_1 = shape.mesh.indices[3 * triangle + 1].vertex_index;\n            const vertex_t vertex_2 = shape.mesh.indices[3 * triangle + 2].vertex_index;\n\n            if (vertex_0 != edge.first && vertex_0 != edge.second)\n            {\n                return vertex_0;\n            }\n            else if (vertex_1 != edge.first && vertex_1 != edge.second)\n            {\n                return vertex_1;\n            }\n            else\n            {\n                assert(vertex_2 != edge.first && vertex_2 != edge.second);\n                return vertex_2;\n            }\n        };\n\n        const triangle_t another_vertex_0 = obtain_another_vertex(triangles[0], edge);\n        const triangle_t another_vertex_1 = obtain_another_vertex(triangles[1], edge);\n\n        switch (out_of_plane_strategy)\n        {\n            case OutOfPlaneStrategy::Bending:\n            {\n                const auto p_0 = map_from_obj_vertex_index_to_particle[edge.first];\n                const auto p_1 = map_from_obj_vertex_index_to_particle[edge.second];\n                const auto p_2 = map_from_obj_vertex_index_to_particle[another_vertex_0];\n                const auto p_3 = map_from_obj_vertex_index_to_particle[another_vertex_1];\n\n                const Eigen::Vector3d& x_0 = p_0->x;\n                const Eigen::Vector3d& x_1 = p_1->x;\n                const Eigen::Vector3d& x_2 = p_2->x;\n                const Eigen::Vector3d& x_3 = p_3->x;\n\n                const Eigen::Vector3d p_10 = x_1 - x_0;\n                const Eigen::Vector3d p_20 = x_2 - x_0;\n                const Eigen::Vector3d p_30 = x_3 - x_0;\n\n                const Eigen::Vector3d n_0 = p_10.cross(p_20).normalized();\n                const Eigen::Vector3d n_1 = p_10.cross(p_30).normalized();\n\n                assert(!n_0.hasNaN());\n                assert(!n_1.hasNaN());\n\n                // Typical value is 0.0 or pi\n                const double dihedral_angle = std::acos(std::clamp(n_0.dot(n_1), -1.0, 1.0));\n\n                assert(!std::isnan(dihedral_angle));\n\n                m_constraints.push_back(std::make_shared<elasty::BendingConstraint>(\n                    p_0, p_1, p_2, p_3, out_of_plane_stiffness, out_of_plane_compliance, dt, dihedral_angle));\n\n                break;\n            }\n            case OutOfPlaneStrategy::IsometricBending:\n            {\n                const auto p_0 = map_from_obj_vertex_index_to_particle[edge.first];\n                const auto p_1 = map_from_obj_vertex_index_to_particle[edge.second];\n                const auto p_2 = map_from_obj_vertex_index_to_particle[another_vertex_0];\n                const auto p_3 = map_from_obj_vertex_index_to_particle[another_vertex_1];\n\n                m_constraints.push_back(std::make_shared<elasty::IsometricBendingConstraint>(\n                    p_0, p_1, p_2, p_3, out_of_plane_stiffness, out_of_plane_compliance, dt));\n\n                break;\n            }\n            case OutOfPlaneStrategy::Cross:\n            {\n                const auto p_2 = map_from_obj_vertex_index_to_particle[another_vertex_0];\n                const auto p_3 = map_from_obj_vertex_index_to_particle[another_vertex_1];\n\n                const Eigen::Vector3d& x_2 = p_2->x;\n                const Eigen::Vector3d& x_3 = p_3->x;\n\n                m_constraints.push_back(std::make_shared<elasty::DistanceConstraint>(\n                    p_2, p_3, out_of_plane_stiffness, out_of_plane_compliance, dt, (x_2 - x_3).norm()));\n\n                break;\n            }\n        }\n    }\n\n    calculateAreas();\n}\n\nvoid elasty::ClothSimObject::applyAerodynamicForces(const Eigen::Vector3d& global_velocity,\n                                                    const double           drag_coeff,\n                                                    const double           lift_coeff)\n{\n    constexpr double rho = 1.225; // Taken from Wikipedia: https://en.wikipedia.org/wiki/Density_of_air\n\n    assert(drag_coeff >= lift_coeff);\n\n    const int num_triangles = m_triangle_list.rows();\n\n    for (int i = 0; i < num_triangles; ++i)\n    {\n        const auto& x_0 = m_particles[m_triangle_list.row(i)(0)]->x;\n        const auto& x_1 = m_particles[m_triangle_list.row(i)(1)]->x;\n        const auto& x_2 = m_particles[m_triangle_list.row(i)(2)]->x;\n\n        const auto& v_0 = m_particles[m_triangle_list.row(i)(0)]->v;\n        const auto& v_1 = m_particles[m_triangle_list.row(i)(1)]->v;\n        const auto& v_2 = m_particles[m_triangle_list.row(i)(2)]->v;\n\n        const auto& m_0 = m_particles[m_triangle_list.row(i)(0)]->m;\n        const auto& m_1 = m_particles[m_triangle_list.row(i)(1)]->m;\n        const auto& m_2 = m_particles[m_triangle_list.row(i)(2)]->m;\n\n        const double m_sum = m_0 + m_1 + m_2;\n\n        // Calculate the weighted average of the particle velocities\n        const Eigen::Vector3d v_triangle = (m_0 * v_0 + m_1 * v_1 + m_2 * v_2) / m_sum;\n\n        // Calculate the relative velocity of the triangle\n        const Eigen::Vector3d v_rel         = v_triangle - global_velocity;\n        const double          v_rel_squared = v_rel.squaredNorm();\n\n        const auto            cross         = (x_1 - x_0).cross(x_2 - x_0);\n        const double          area          = 0.5 * cross.norm();\n        const auto            n_either_side = cross.normalized();\n        const Eigen::Vector3d n             = (n_either_side.dot(v_rel) > 0.0) ? n_either_side : -n_either_side;\n\n        const double coeff = 0.5 * rho * area;\n\n        // Note: This wind force model was proposed by [Wilson+14]\n        const Eigen::Vector3d f =\n            -coeff * ((drag_coeff - lift_coeff) * v_rel.dot(n) * v_rel + lift_coeff * v_rel_squared * n);\n\n        m_particles[m_triangle_list.row(i)(0)]->f += (m_0 / m_sum) * f;\n        m_particles[m_triangle_list.row(i)(1)]->f += (m_1 / m_sum) * f;\n        m_particles[m_triangle_list.row(i)(2)]->f += (m_2 / m_sum) * f;\n    }\n}\n\nvoid elasty::ClothSimObject::calculateAreas()\n{\n    const int num_triangles = m_triangle_list.rows();\n\n    m_area_list = Eigen::VectorXd(num_triangles);\n\n    for (int i = 0; i < num_triangles; ++i)\n    {\n        const auto& x_0 = m_particles[m_triangle_list.row(i)[0]]->x;\n        const auto& x_1 = m_particles[m_triangle_list.row(i)[1]]->x;\n        const auto& x_2 = m_particles[m_triangle_list.row(i)[2]]->x;\n\n        const double area = 0.5 * (x_1 - x_0).cross(x_2 - x_0).norm();\n\n        m_area_list(i) = area;\n    }\n}\n", "meta": {"hexsha": "6ee11167446f5a0d9f9af798d8dd42febd460fd4", "size": 13327, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cloth-sim-object.cpp", "max_stars_repo_name": "yuki-koyama/elasty", "max_stars_repo_head_hexsha": "67c7a15c1483fe1979b8b3af64be4f34e110c760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 176.0, "max_stars_repo_stars_event_min_datetime": "2019-04-27T00:45:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T03:15:45.000Z", "max_issues_repo_path": "src/cloth-sim-object.cpp", "max_issues_repo_name": "yuki-koyama/elasty", "max_issues_repo_head_hexsha": "67c7a15c1483fe1979b8b3af64be4f34e110c760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2019-04-27T00:00:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-30T07:01:12.000Z", "max_forks_repo_path": "src/cloth-sim-object.cpp", "max_forks_repo_name": "yuki-koyama/elasty", "max_forks_repo_head_hexsha": "67c7a15c1483fe1979b8b3af64be4f34e110c760", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2019-04-27T01:09:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:30:41.000Z", "avg_line_length": 42.3079365079, "max_line_length": 114, "alphanum_fraction": 0.5824266527, "num_tokens": 3500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.29271407860371507}}
{"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#include <map>\n\n\n#include <functional>\n\n#include <Eigen/Core>\n\n#include \"Tudat/Astrodynamics/Propagators/variationalEquations.h\"\n#include \"Tudat/Astrodynamics/Propagators/rotationalMotionQuaternionsStateDerivative.h\"\n\n#include \"Tudat/Astrodynamics/OrbitDetermination/AccelerationPartials/accelerationPartial.h\"\n\n\nnamespace tudat\n{\n\nnamespace propagators\n{\n\ntemplate< typename StateScalarType >\nvoid VariationalEquations::getBodyInitialStatePartialMatrix(\n        const Eigen::Matrix< StateScalarType, Eigen::Dynamic, Eigen::Dynamic >& stateTransitionAndSensitivityMatrices,\n        Eigen::Block< Eigen::Matrix< StateScalarType, Eigen::Dynamic, Eigen::Dynamic > > currentMatrixDerivative )\n{\n    setBodyStatePartialMatrix( );\n\n    // Add partials of body positions and velocities.\n    currentMatrixDerivative.block( 0, 0, totalDynamicalStateSize_, numberOfParameterValues_ ) =\n            ( variationalMatrix_.template cast< StateScalarType >( ) * stateTransitionAndSensitivityMatrices );\n}\n\n//! Calculates matrix containing partial derivatives of state derivatives w.r.t. body state.\nvoid VariationalEquations::setBodyStatePartialMatrix( )\n{\n    // Initialize partial matrix\n    variationalMatrix_.setZero( );\n\n    if( dynamicalStatesToEstimate_.count( propagators::translational_state ) > 0 )\n    {\n        int startIndex = stateTypeStartIndices_.at( propagators::translational_state );\n        for( unsigned int i = 0; i < dynamicalStatesToEstimate_.at( propagators::translational_state ).size( ); i++ )\n        {\n            variationalMatrix_.block( startIndex + i * 6, startIndex + i * 6 + 3, 3, 3 ).setIdentity( );\n        }\n    }\n\n    if( dynamicalStatesToEstimate_.count( propagators::rotational_state ) > 0 )\n    {\n         Eigen::VectorXd rotationalStates = currentStatesPerTypeInConventionalRepresentation_.at(\n                     propagators::rotational_state );\n\n        int startIndex = stateTypeStartIndices_.at( propagators::rotational_state );\n        for( unsigned int i = 0; i < dynamicalStatesToEstimate_.at( propagators::rotational_state ).size( ); i++ )\n        {\n            variationalMatrix_.block( startIndex + i * 7, startIndex + i * 7 , 4, 4 ) =\n                    getQuaterionToQuaternionRateMatrix( rotationalStates.segment( 7 * i + 4, 3 ) );\n            variationalMatrix_.block( startIndex + i * 7, startIndex + i * 7 + 4, 4, 3 ) =\n                    getAngularVelocityToQuaternionRateMatrix( rotationalStates.segment( 7 * i, 4 ) );\n        }\n    }\n\n    // Iterate over all bodies undergoing accelerations for which initial condition is to be estimated.\n    for( std::map< IntegratedStateType, std::vector< std::multimap< std::pair< int, int >,\n         std::function< void( Eigen::Block< Eigen::MatrixXd > ) > > > >::iterator\n         typeIterator = statePartialList_.begin( ); typeIterator != statePartialList_.end( ); typeIterator++ )\n    {\n        int startIndex = stateTypeStartIndices_.at( typeIterator->first );\n        int currentStateSize = getSingleIntegrationSize( typeIterator->first );\n        int entriesToSkipPerEntry = currentStateSize - getGeneralizedAccelerationSize( typeIterator->first );\n\n        for( unsigned int i = 0; i < typeIterator->second.size( ); i++ )\n        {\n            // Iterate over all bodies exerting an acceleration on this body.\n            for( statePartialIterator_ = typeIterator->second.at( i ).begin( );\n                 statePartialIterator_ != typeIterator->second.at( i ).end( );\n                 statePartialIterator_++ )\n            {\n                statePartialIterator_->second(\n                            variationalMatrix_.block(\n                                startIndex + entriesToSkipPerEntry + i* currentStateSize, statePartialIterator_->first.first,\n                                currentStateSize - entriesToSkipPerEntry, statePartialIterator_->first.second ) );\n\n            }\n        }\n    }\n\n   for( unsigned int i = 0; i < statePartialAdditionIndices_.size( ); i++ )\n   {\n       variationalMatrix_.block( 0, statePartialAdditionIndices_.at( i ).second, totalDynamicalStateSize_, 3 ) +=\n               variationalMatrix_.block( 0, statePartialAdditionIndices_.at( i ).first, totalDynamicalStateSize_, 3 );\n   }\n\n   for( unsigned int i = 0; i < inertiaTensorsForMultiplication_.size( ); i++ )\n   {\n       variationalMatrix_.block( inertiaTensorsForMultiplication_.at( i ).first, 0, 3, totalDynamicalStateSize_ ) =\n               ( inertiaTensorsForMultiplication_.at( i ).second( ).inverse( ) ) *\n               variationalMatrix_.block( inertiaTensorsForMultiplication_.at( i ).first, 0, 3, totalDynamicalStateSize_ ).eval( );\n   }\n\n}\n\n//! Function to clear reference/cached values of state derivative partials.\nvoid VariationalEquations::clearPartials( )\n{\n    for( stateDerivativeTypeIterator_ = stateDerivativePartialList_.begin( );\n         stateDerivativeTypeIterator_ != stateDerivativePartialList_.end( );\n         stateDerivativeTypeIterator_++ )\n    {\n        for( unsigned int i = 0; i < stateDerivativeTypeIterator_->second.size( ); i++ )\n        {\n            for( unsigned int j = 0; j < stateDerivativeTypeIterator_->second.at( i ).size( ); j++ )\n            {\n                stateDerivativeTypeIterator_->second.at( i ).at( j )->resetTime( TUDAT_NAN );\n            }\n\n        }\n    }\n}\n\n//! Function (called by constructor) to set up the statePartialList_ member from the state derivative partials\nvoid VariationalEquations::setStatePartialFunctionList( )\n{\n    std::pair< std::function< void( Eigen::Block< Eigen::MatrixXd > ) >, int > currentDerivativeFunction;\n\n\n    // Iterate over all state types\n    for( std::map< propagators::IntegratedStateType,\n         orbit_determination::StateDerivativePartialsMap >::iterator\n         stateDerivativeTypeIterator_ = stateDerivativePartialList_.begin( );\n         stateDerivativeTypeIterator_ != stateDerivativePartialList_.end( );\n         stateDerivativeTypeIterator_++ )\n    {\n        // Iterate over all bodies undergoing 'accelerations' for which initial state is to be estimated.\n        for( unsigned int i = 0; i < stateDerivativeTypeIterator_->second.size( ); i++ )\n        {\n            std::multimap< std::pair< int, int >, std::function< void( Eigen::Block< Eigen::MatrixXd > ) > >\n                    currentBodyPartialList;\n\n            // Iterate over all 'accelerations' from single body on other single body\n            for( unsigned int j = 0; j < stateDerivativeTypeIterator_->second.at( i ).size( ); j++ )\n            {\n                for( std::map< propagators::IntegratedStateType,\n                     std::vector< std::pair< std::string, std::string > > >::iterator\n                     estimatedStateIterator = dynamicalStatesToEstimate_.begin( );\n                     estimatedStateIterator != dynamicalStatesToEstimate_.end( );\n                     estimatedStateIterator++ )\n                {\n                    // Iterate over all bodies to see if body exerting acceleration is also to be estimated (cross-terms)\n                    for( unsigned int k = 0; k < estimatedStateIterator->second.size( ); k++ )\n                    {\n                        currentDerivativeFunction = stateDerivativeTypeIterator_->second.at( i ).at( j )->\n                                getDerivativeFunctionWrtStateOfIntegratedBody(\n                                    estimatedStateIterator->second.at( k ), estimatedStateIterator->first );\n\n                        // If function is not-empty: add to list.\n                        if( currentDerivativeFunction.second != 0 )\n                        {\n                            currentBodyPartialList.insert(\n                                        std::make_pair(\n                                            std::make_pair( k * getSingleIntegrationSize( estimatedStateIterator->first ) +\n                                                            stateTypeStartIndices_.at( estimatedStateIterator->first ),\n                                                            getSingleIntegrationSize( estimatedStateIterator->first ) ),\n                                            currentDerivativeFunction.first ) );\n                        }\n                    }\n                }\n            }\n            statePartialList_[ stateDerivativeTypeIterator_->first ].push_back( currentBodyPartialList );\n        }\n    }\n}\n\n\ntemplate void VariationalEquations::getBodyInitialStatePartialMatrix< double >(\n        const Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic >& stateTransitionAndSensitivityMatrices,\n        Eigen::Block< Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic > > currentMatrixDerivative );\n\n//#if( BUILD_EXTENDED_PRECISION_PROPAGATION_TOOLS )\ntemplate void VariationalEquations::getBodyInitialStatePartialMatrix< long double >(\n        const Eigen::Matrix< long double, Eigen::Dynamic, Eigen::Dynamic >& stateTransitionAndSensitivityMatrices,\n        Eigen::Block< Eigen::Matrix< long double, Eigen::Dynamic, Eigen::Dynamic > > currentMatrixDerivative );\n//#endif\n\n} // namespace propagators\n\n} // namespace tudat\n", "meta": {"hexsha": "d549a2d3574ceb9dd9627d424edfccb462836f4e", "size": 9502, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Propagators/variationalEquations.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/Propagators/variationalEquations.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/Propagators/variationalEquations.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": 48.4795918367, "max_line_length": 130, "alphanum_fraction": 0.6429172806, "num_tokens": 2134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2927074971798268}}
{"text": "//---------------------------------Spheral++----------------------------------//\n// ProbabilisticDamageModel\n// A damage model based on Weibull statistics that uses volume based\n// probabilities per node to decide when damage starts to accrue.  Should\n// generate similar results to the classic Benz-Asphaug (Grady-Kipp) model\n// without generating explicit flaws.  Also appropriate for use with varying\n// resolution materials.\n//\n// Created by JMO, Tue Apr 13 15:58:08 PDT 2021\n//----------------------------------------------------------------------------//\n#include \"FileIO/FileIO.hh\"\n#include \"ProbabilisticDamageModel.hh\"\n#include \"TensorStrainPolicy.hh\"\n#include \"ProbabilisticDamagePolicy.hh\"\n#include \"YoungsModulusPolicy.hh\"\n#include \"LongitudinalSoundSpeedPolicy.hh\"\n#include \"DamageGradientPolicy.hh\"\n#include \"Strength/SolidFieldNames.hh\"\n#include \"NodeList/SolidNodeList.hh\"\n#include \"DataBase/DataBase.hh\"\n#include \"DataBase/State.hh\"\n#include \"DataBase/StateDerivatives.hh\"\n#include \"DataBase/ReplaceState.hh\"\n#include \"Hydro/HydroFieldNames.hh\"\n#include \"Field/FieldList.hh\"\n#include \"Boundary/Boundary.hh\"\n#include \"Neighbor/Neighbor.hh\"\n#include \"Utilities/mortonOrderIndices.hh\"\n#include \"Utilities/allReduce.hh\"\n#include \"Utilities/uniform_random.hh\"\n\n#include <boost/functional/hash.hpp>  // hash_combine\n\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <limits>\nusing std::vector;\nusing std::string;\nusing std::pair;\nusing std::make_pair;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::min;\nusing std::max;\nusing std::abs;\n\nnamespace Spheral {\n\n//------------------------------------------------------------------------------\n// Constructor.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nProbabilisticDamageModel<Dimension>::\nProbabilisticDamageModel(SolidNodeList<Dimension>& nodeList,\n                         const TableKernel<Dimension>& W,\n                         const double kWeibull,\n                         const double mWeibull,\n                         const size_t seed,\n                         const size_t minFlawsPerNode,\n                         const double crackGrowthMultiplier,\n                         const double volumeMultiplier,\n                         const DamageCouplingAlgorithm damageCouplingAlgorithm,\n                         const TensorStrainAlgorithm strainAlgorithm,\n                         const bool damageInCompression,\n                         const double criticalDamageThreshold,\n                         const Field<Dimension, int>& mask):\n  DamageModel<Dimension>(nodeList, W, crackGrowthMultiplier, damageCouplingAlgorithm),\n  mStrainAlgorithm(strainAlgorithm),\n  mDamageInCompression(damageInCompression),\n  mkWeibull(kWeibull),\n  mmWeibull(mWeibull),\n  mVolumeMultiplier(volumeMultiplier),\n  mVmin(std::numeric_limits<double>::max()),\n  mVmax(std::numeric_limits<double>::min()),\n  mCriticalDamageThreshold(criticalDamageThreshold),\n  mSeed(seed),\n  mMinFlawsPerNode(minFlawsPerNode),\n  mNumFlaws(SolidFieldNames::numFlaws, nodeList),\n  mMask(mask),\n  mMinFlaw(SolidFieldNames::minFlaw, nodeList),\n  mMaxFlaw(SolidFieldNames::maxFlaw, nodeList),\n  mInitialVolume(SolidFieldNames::initialVolume, nodeList),\n  mYoungsModulus(SolidFieldNames::YoungsModulus, nodeList),\n  mLongitudinalSoundSpeed(SolidFieldNames::longitudinalSoundSpeed, nodeList),\n  mDdamageDt(ProbabilisticDamagePolicy<Dimension>::prefix() + SolidFieldNames::scalarDamage, nodeList),\n  mStrain(SolidFieldNames::strainTensor, nodeList),\n  mEffectiveStrain(SolidFieldNames::effectiveStrainTensor, nodeList) {\n}\n\n//------------------------------------------------------------------------------\n// Destructor.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nProbabilisticDamageModel<Dimension>::\n~ProbabilisticDamageModel() {\n}\n\n//------------------------------------------------------------------------------\n// initializeProblemStartup\n//\n// After all initial state has been initialize (node positions, masses, etc),\n// but before we try to run any physics cycles.  This is when we initialize a\n// lot of our state for the damage model.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nvoid\nProbabilisticDamageModel<Dimension>::\ninitializeProblemStartup(DataBase<Dimension>& dataBase) {\n\n  // How many points are actually being damaged?\n  // We have to be careful to use an unsigned size_t here due to overflow\n  // problems with large numbers of points.\n  size_t nused_local = 0u;\n  for (auto i = 0u; i < mMask.numInternalElements(); ++i) {\n    if (mMask[i] == 1) ++nused_local;\n  }\n  const size_t nused_global = allReduce(nused_local, MPI_SUM, Communicator::communicator());\n\n  // Compute the Morton-ordering for hashing with the global seed to seed each\n  // point-wise random number generator.\n  typedef KeyTraits::Key Key;\n  const FieldList<Dimension, Key> keyList = mortonOrderIndices(dataBase);\n  const auto& nodes = this->nodeList();\n  CHECK(keyList.fieldForNodeList(nodes) < keyList.end());\n  const Field<Dimension, Key>& keys = **(keyList.fieldForNodeList(nodes));\n  \n  // Compute the initial volumes and random seeds for each node.  We hash the\n  // morton index of each point with the global seed value to create unique\n  // but reproducible seeds for each points random number generator.\n  const auto& mass = nodes.mass();\n  const auto& rho = nodes.massDensity();\n  const auto  nlocal = nodes.numInternalNodes();\n  vector<uniform_random> randomGenerators(nlocal);\n#pragma omp parallel for\n  for (auto i = 0u; i < nlocal; ++i) {\n    if (mMask(i) == 1) {\n      CHECK(mass(i) > 0.0 and rho(i) > 0.0);\n      mInitialVolume(i) = mass(i)/rho(i) * mVolumeMultiplier;\n      mVmin = std::min(mVmin, mInitialVolume(i));\n      mVmax = std::max(mVmax, mInitialVolume(i));\n      Key seedi = mSeed;\n      boost::hash_combine(seedi, keys(i));\n      randomGenerators[i].seed(seedi);      // starting out generating in [0,1)\n      randomGenerators[i]();                // Recommended to discard first value in sequence\n    }\n  }\n  mVmin = allReduce(mVmin, MPI_MIN, Communicator::communicator());\n  mVmax = allReduce(mVmax, MPI_MAX, Communicator::communicator());\n\n  // Generate min/max ranges of flaws for each point.\n  const auto mInv = 1.0/mmWeibull;\n  size_t minNumFlaws = std::numeric_limits<size_t>::max();\n  size_t maxNumFlaws = 0u;\n  size_t totalNumFlaws = 0u;\n  auto epsMin = std::numeric_limits<double>::max();\n  auto epsMax = std::numeric_limits<double>::min();\n  auto numFlawsRatio = 0.0;\n#pragma omp parallel for\n  for (auto i = 0u; i < nlocal; ++i) {\n    if (mMask(i) == 1) {\n      const auto Nflaws = size_t(mMinFlawsPerNode*mInitialVolume(i)/mVmin + 0.5);  // Target number of flaws on this point\n      CHECK(Nflaws >= mMinFlawsPerNode);\n      const auto Ai = pow(Nflaws/(mkWeibull*mInitialVolume(i)), mInv);\n      mMinFlaw(i) = 1.0;\n      mMaxFlaw(i) = 0.0;\n      auto ntries = 0u;\n      while (mMinFlaw(i) > mMaxFlaw(i) and ntries++ < 100u) {\n        mMinFlaw(i) = Ai*pow(1.0 - pow(randomGenerators[i](), 1.0/Nflaws), mInv);\n        mMaxFlaw(i) = Ai*pow(randomGenerators[i](), 1.0/(mmWeibull*Nflaws));\n      }\n      CHECK(mMaxFlaw(i) > mMinFlaw(i));\n      mNumFlaws(i) = std::max(1, 1 + int(mInitialVolume(i)*mkWeibull*(pow(mMaxFlaw(i), mmWeibull) - pow(mMinFlaw(i), mmWeibull))));\n\n      // Gather statistics\n#pragma omp critical\n      {\n        minNumFlaws = min(minNumFlaws, size_t(mNumFlaws(i)));\n        maxNumFlaws = max(maxNumFlaws, size_t(mNumFlaws(i)));\n        totalNumFlaws += size_t(mNumFlaws(i));\n        epsMin = std::min(epsMin, mMinFlaw(i));\n        epsMax = std::max(epsMax, mMaxFlaw(i));\n        numFlawsRatio += double(mNumFlaws(i))/Nflaws;\n      }\n    }\n  }\n\n  // Some diagnostic output.\n  if (nused_global > 0) {\n    minNumFlaws = allReduce(minNumFlaws, MPI_MIN, Communicator::communicator());\n    maxNumFlaws = allReduce(maxNumFlaws, MPI_MAX, Communicator::communicator());\n    totalNumFlaws = allReduce(totalNumFlaws, MPI_SUM, Communicator::communicator());\n    epsMin = allReduce(epsMin, MPI_MIN, Communicator::communicator());\n    epsMax = allReduce(epsMax, MPI_MAX, Communicator::communicator());\n    numFlawsRatio = allReduce(numFlawsRatio, MPI_SUM, Communicator::communicator())/nused_global;\n    if (Process::getRank() == 0) {\n      cerr << \"ProbabilisticDamageModel for \" << nodes.name() << \":\" << endl\n           << \" Min, max, max/min volumes: \" << mVmin << \" \" << mVmax << \" \" << mVmax*safeInv(mVmin) << endl\n           << \"    Min num flaws per node: \" << minNumFlaws << endl\n           << \"    Max num flaws per node: \" << maxNumFlaws << endl\n           << \"    Total num flaws       : \" << totalNumFlaws << endl\n           << \"    Avg flaws per node    : \" << totalNumFlaws/nused_global << endl\n           << \"    Min flaw strain       : \" << epsMin << endl\n           << \"    Max flaw strain       : \" << epsMax << endl\n           << \"    Avg Neff/Nflaws       : \" << numFlawsRatio << endl;\n    }\n  }\n}\n\n//------------------------------------------------------------------------------\n// Evaluate derivatives.\n//\n// In this model we compute the scalar damage derivative assuming unresolved\n// crack growth for every point. However, that is not applied in the tensor\n// damage update policy unless the flaws are actually activated.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nvoid\nProbabilisticDamageModel<Dimension>::\nevaluateDerivatives(const Scalar time,\n                    const Scalar dt,\n                    const DataBase<Dimension>& dataBase,\n                    const State<Dimension>& state,\n                    StateDerivatives<Dimension>& derivs) const {\n\n  // Set the scalar magnitude of the damage evolution.\n  const auto* nodeListPtr = &(this->nodeList());\n  auto&       DDDt = derivs.field(state.buildFieldKey(ProbabilisticDamagePolicy<Dimension>::prefix() + SolidFieldNames::scalarDamage, nodeListPtr->name()), 0.0);\n  this->computeScalarDDDt(dataBase,\n                          state,\n                          time,\n                          dt,\n                          DDDt);\n}\n\n//------------------------------------------------------------------------------\n// Vote on a time step.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\ntypename ProbabilisticDamageModel<Dimension>::TimeStepType\nProbabilisticDamageModel<Dimension>::\ndt(const DataBase<Dimension>& /*dataBase*/, \n   const State<Dimension>& /*state*/,\n   const StateDerivatives<Dimension>& /*derivs*/,\n   const Scalar /*currentTime*/) const {\n\n  // // Look at how quickly we're trying to change the damage.\n  // double dt = DBL_MAX;\n  // const Field<Dimension, SymTensor>& damage = this->nodeList().damage();\n  // const ConnectivityMap<Dimension>& connectivityMap = dataBase.connectivityMap();\n  // const vector<const NodeList<Dimension>*>& nodeLists = connectivityMap.nodeLists();\n  // const size_t nodeListi = distance(nodeLists.begin(), find(nodeLists.begin(), nodeLists.end(), &(this->nodeList())));\n  // for (typename ConnectivityMap<Dimension>::const_iterator iItr = connectivityMap.begin(nodeListi);\n  //      iItr != connectivityMap.end(nodeListi);\n  //      ++iItr) {\n  //   const int i = *iItr;\n  //   const double D0 = damage(i).Trace() / Dimension::nDim;\n  //   dt = min(dt, 0.8*max(D0, 1.0 - D0)/\n  //            std::sqrt(mDdamageDt(i)*mDdamageDt(i) + 1.0e-20));\n  // }\n  // return TimeStepType(dt, \"Rate of damage change\");\n\n  return TimeStepType(1.0e100, \"Rate of damage change -- NO VOTE.\");\n}\n\n//------------------------------------------------------------------------------\n// Register our state.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nvoid\nProbabilisticDamageModel<Dimension>::\nregisterState(DataBase<Dimension>& dataBase,\n              State<Dimension>& state) {\n\n  typedef typename State<Dimension>::PolicyPointer PolicyPointer;\n\n  // Register Youngs modulus and the longitudinal sound speed.\n  PolicyPointer EPolicy(new YoungsModulusPolicy<Dimension>());\n  PolicyPointer clPolicy(new LongitudinalSoundSpeedPolicy<Dimension>());\n  state.enroll(mYoungsModulus, EPolicy);\n  state.enroll(mLongitudinalSoundSpeed, clPolicy);\n\n  // Set the initial values for the Youngs modulus, sound speed, and pressure.\n  typename StateDerivatives<Dimension>::PackageList dummyPackages;\n  StateDerivatives<Dimension> derivs(dataBase, dummyPackages);\n  EPolicy->update(state.key(mYoungsModulus), state, derivs, 1.0, 0.0, 0.0);\n  clPolicy->update(state.key(mLongitudinalSoundSpeed), state, derivs, 1.0, 0.0, 0.0);\n\n  // Register the strain and effective strain.\n  PolicyPointer effectiveStrainPolicy(new TensorStrainPolicy<Dimension>(mStrainAlgorithm));\n  state.enroll(mStrain);\n  state.enroll(mEffectiveStrain, effectiveStrainPolicy);\n\n  // Register the damage and state it requires.\n  // Note we are overriding the default no-op policy for the damage\n  // as originally registered by the SolidSPHHydroBase class.\n  auto& damage = this->nodeList().damage();\n  PolicyPointer damagePolicy(new ProbabilisticDamagePolicy<Dimension>(mDamageInCompression,\n                                                                      mkWeibull,\n                                                                      mmWeibull));\n  state.enroll(damage, damagePolicy);\n  state.enroll(mNumFlaws);\n  state.enroll(mMinFlaw);\n  state.enroll(mMaxFlaw);\n  state.enroll(mInitialVolume);\n\n  // Mask out nodes beyond the critical damage threshold from setting the timestep.\n  auto maskKey = state.buildFieldKey(HydroFieldNames::timeStepMask, this->nodeList().name());\n  auto& mask = state.field(maskKey, 0);\n  const auto nlocal = this->nodeList().numInternalNodes();\n#pragma omp parallel for\n  for (auto i = 0u; i < nlocal; ++i) {\n    if (damage(i).Trace() > mCriticalDamageThreshold) mask(i) = 0;\n  }\n}\n\n//------------------------------------------------------------------------------\n// Register the derivatives.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nvoid\nProbabilisticDamageModel<Dimension>::\nregisterDerivatives(DataBase<Dimension>& /*dataBase*/,\n                    StateDerivatives<Dimension>& derivs) {\n  derivs.enroll(mDdamageDt);\n}\n\n//------------------------------------------------------------------------------\n// Apply the boundary conditions to the ghost nodes.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nvoid\nProbabilisticDamageModel<Dimension>::\napplyGhostBoundaries(State<Dimension>& state,\n                     StateDerivatives<Dimension>& /*derivs*/) {\n\n  // Grab this models damage field from the state.\n  typedef typename State<Dimension>::KeyType Key;\n  const Key nodeListName = this->nodeList().name();\n  const Key DKey = state.buildFieldKey(SolidFieldNames::tensorDamage, nodeListName);\n  CHECK(state.registered(DKey));\n  auto& D = state.field(DKey, SymTensor::zero);\n\n  // Apply ghost boundaries to the damage.\n  for (auto boundaryItr = this->boundaryBegin();\n       boundaryItr < this->boundaryEnd();\n       ++boundaryItr) {\n    (*boundaryItr)->applyGhostBoundary(D);\n  }\n}\n\n//------------------------------------------------------------------------------\n// Enforce boundary conditions for the physics specific fields.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nvoid\nProbabilisticDamageModel<Dimension>::\nenforceBoundaries(State<Dimension>& state,\n                  StateDerivatives<Dimension>& /*derivs*/) {\n\n  // Grab this models damage field from the state.\n  typedef typename State<Dimension>::KeyType Key;\n  const Key nodeListName = this->nodeList().name();\n  const Key DKey = state.buildFieldKey(SolidFieldNames::tensorDamage, nodeListName);\n  CHECK(state.registered(DKey));\n  auto& D = state.field(DKey, SymTensor::zero);\n\n  // Enforce!\n  for (auto boundaryItr = this->boundaryBegin(); \n       boundaryItr < this->boundaryEnd();\n       ++boundaryItr) {\n    (*boundaryItr)->enforceBoundary(D);\n  }\n}\n\n//------------------------------------------------------------------------------\n// Dump the current state to the given file.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nvoid\nProbabilisticDamageModel<Dimension>::\ndumpState(FileIO& file, const string& pathName) const {\n  DamageModel<Dimension>::dumpState(file, pathName);\n  file.write(mNumFlaws, pathName + \"/numFlaws\");\n  file.write(mMinFlaw, pathName + \"/minFlaw\");\n  file.write(mMaxFlaw, pathName + \"/maxFlaw\");\n  file.write(mStrain, pathName + \"/strain\");\n  file.write(mEffectiveStrain, pathName + \"/effectiveStrain\");\n  file.write(mDdamageDt, pathName + \"/DdamageDt\");\n  file.write(mMask, pathName + \"/mask\");\n}\n\n//------------------------------------------------------------------------------\n// Restore the state from the given file.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nvoid\nProbabilisticDamageModel<Dimension>::\nrestoreState(const FileIO& file, const string& pathName) {\n  DamageModel<Dimension>::restoreState(file, pathName);\n  file.read(mNumFlaws, pathName + \"/numFlaws\");\n  file.read(mMinFlaw, pathName + \"/minFlaw\");\n  file.read(mMaxFlaw, pathName + \"/maxFlaw\");\n  file.read(mStrain, pathName + \"/strain\");\n  file.read(mEffectiveStrain, pathName + \"/effectiveStrain\");\n  file.read(mDdamageDt, pathName + \"/DdamageDt\");\n  file.read(mMask, pathName + \"/mask\");\n}\n\n}\n\n", "meta": {"hexsha": "4943b23680a456878bdc36b4d0a7a3da23aa7550", "size": 17771, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Damage/ProbabilisticDamageModel.cc", "max_stars_repo_name": "jmikeowen/Spheral", "max_stars_repo_head_hexsha": "3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4", "max_stars_repo_licenses": ["BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2018-07-31T21:38:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-29T08:58:33.000Z", "max_issues_repo_path": "src/Damage/ProbabilisticDamageModel.cc", "max_issues_repo_name": "jmikeowen/Spheral", "max_issues_repo_head_hexsha": "3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4", "max_issues_repo_licenses": ["BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2020-09-28T23:14:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T17:01:33.000Z", "max_forks_repo_path": "src/Damage/ProbabilisticDamageModel.cc", "max_forks_repo_name": "jmikeowen/Spheral", "max_forks_repo_head_hexsha": "3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4", "max_forks_repo_licenses": ["BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T07:00:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-15T21:12:39.000Z", "avg_line_length": 43.0290556901, "max_line_length": 161, "alphanum_fraction": 0.6147656294, "num_tokens": 4101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.29264444814131685}}
{"text": "\n#include <NTL/ZZ.h>\n#include <NTL/vec_ZZ.h>\n#include <NTL/Lazy.h>\n#include <NTL/fileio.h>\n#include <NTL/SmartPtr.h>\n\n#include <NTL/BasicThreadPool.h>\n\n\n\n#if defined(NTL_HAVE_AVX2)\n#include <immintrin.h>\n#elif defined(NTL_HAVE_SSSE3)\n#include <emmintrin.h>\n#include <tmmintrin.h>\n#endif\n\n\n\n\n\nNTL_START_IMPL\n\n\n\n\n\nconst ZZ& ZZ::zero()\n{\n   \n   static const ZZ z; // GLOBAL (relies on C++11 thread-safe init)\n   return z;\n}\n\n\nconst ZZ& ZZ_expo(long e)\n{\n   NTL_TLS_LOCAL(ZZ, expo_helper);\n\n   conv(expo_helper, e);\n   return expo_helper;\n}\n\n\n\nvoid AddMod(ZZ& x, const ZZ& a, long b, const ZZ& n)\n{\n   NTL_ZZRegister(B);\n   conv(B, b);\n   AddMod(x, a, B, n);\n}\n\n\nvoid SubMod(ZZ& x, const ZZ& a, long b, const ZZ& n)\n{\n   NTL_ZZRegister(B);\n   conv(B, b);\n   SubMod(x, a, B, n);\n}\n\nvoid SubMod(ZZ& x, long a, const ZZ& b, const ZZ& n)\n{\n   NTL_ZZRegister(A);\n   conv(A, a);\n   SubMod(x, A, b, n);\n}\n\n\n\n// ****** input and output\n\n\nstatic NTL_CHEAP_THREAD_LOCAL long iodigits = 0;\nstatic NTL_CHEAP_THREAD_LOCAL long ioradix = 0;\n// iodigits is the greatest integer such that 10^{iodigits} < NTL_WSP_BOUND\n// ioradix = 10^{iodigits}\n\nstatic void InitZZIO()\n{\n   long x;\n\n   x = (NTL_WSP_BOUND-1)/10;\n   iodigits = 0;\n   ioradix = 1;\n\n   while (x) {\n      x = x / 10;\n      iodigits++;\n      ioradix = ioradix * 10;\n   }\n\n   if (iodigits <= 0) TerminalError(\"problem with I/O\");\n}\n\n\nistream& operator>>(istream& s, ZZ& x)\n{\n   long c;\n   long cval;\n   long sign;\n   long ndigits;\n   long acc;\n   NTL_ZZRegister(a);\n\n   if (!s) NTL_INPUT_ERROR(s, \"bad ZZ input\");\n\n   if (!iodigits) InitZZIO();\n\n   a = 0;\n\n   SkipWhiteSpace(s);\n   c = s.peek();\n\n   if (c == '-') {\n      sign = -1;\n      s.get();\n      c = s.peek();\n   }\n   else\n      sign = 1;\n\n   cval = CharToIntVal(c);\n\n   if (cval < 0 || cval > 9) NTL_INPUT_ERROR(s, \"bad ZZ input\");\n\n   ndigits = 0;\n   acc = 0;\n   while (cval >= 0 && cval <= 9) {\n      acc = acc*10 + cval;\n      ndigits++;\n\n      if (ndigits == iodigits) {\n         mul(a, a, ioradix);\n         add(a, a, acc);\n         ndigits = 0;\n         acc = 0;\n      }\n\n      s.get();\n      c = s.peek();\n      cval = CharToIntVal(c);\n   }\n\n   if (ndigits != 0) {\n      long mpy = 1;\n      while (ndigits > 0) {\n         mpy = mpy * 10;\n         ndigits--;\n      }\n\n      mul(a, a, mpy);\n      add(a, a, acc);\n   }\n\n   if (sign == -1)\n      negate(a, a);\n\n   x = a;\n   return s;\n}\n\n\n// The class _ZZ_local_stack should be defined in an empty namespace,\n// but since I don't want to rely on namespaces, we just give it a funny \n// name to avoid accidental name clashes.\n\nstruct _ZZ_local_stack {\n   long top;\n   Vec<long> data;\n\n   _ZZ_local_stack() { top = -1; }\n\n   long pop() { return data[top--]; }\n   long empty() { return (top == -1); }\n   void push(long x);\n};\n\nvoid _ZZ_local_stack::push(long x)\n{\n   if (top+1 >= data.length()) \n      data.SetLength(max(32, long(1.414*data.length())));\n\n   top++;\n   data[top] = x;\n}\n\n\nstatic\nvoid PrintDigits(ostream& s, long d, long justify)\n{\n   NTL_TLS_LOCAL_INIT(Vec<char>, buf, (INIT_SIZE, iodigits));\n\n   long i = 0;\n\n   while (d) {\n      buf[i] = IntValToChar(d % 10);\n      d = d / 10;\n      i++;\n   }\n\n   if (justify) {\n      long j = iodigits - i;\n      while (j > 0) {\n         s << \"0\";\n         j--;\n      }\n   }\n\n   while (i > 0) {\n      i--;\n      s << buf[i];\n   }\n}\n      \n\n   \n\nostream& operator<<(ostream& s, const ZZ& a)\n{\n   ZZ b;\n   _ZZ_local_stack S;\n   long r;\n   long k;\n\n   if (!iodigits) InitZZIO();\n\n   b = a;\n\n   k = sign(b);\n\n   if (k == 0) {\n      s << \"0\";\n      return s;\n   }\n\n   if (k < 0) {\n      s << \"-\";\n      negate(b, b);\n   }\n\n   do {\n      r = DivRem(b, b, ioradix);\n      S.push(r);\n   } while (!IsZero(b));\n\n   r = S.pop();\n   PrintDigits(s, r, 0);\n\n   while (!S.empty()) {\n      r = S.pop();\n      PrintDigits(s, r, 1);\n   }\n      \n   return s;\n}\n\n\n\nlong GCD(long a, long b)\n{\n   long u, v, t, x;\n\n   if (a < 0) {\n      if (a < -NTL_MAX_LONG) ResourceError(\"GCD: integer overflow\");\n      a = -a;\n   }\n\n   if (b < 0) {\n      if (b < -NTL_MAX_LONG) ResourceError(\"GCD: integer overflow\");\n      b = -b;\n   }\n\n\n   if (b==0)\n      x = a;\n   else {\n      u = a;\n      v = b;\n      do {\n         t = u % v;\n         u = v; \n         v = t;\n      } while (v != 0);\n\n      x = u;\n   }\n\n   return x;\n}\n\n         \n\nvoid XGCD(long& d, long& s, long& t, long a, long b)\n{\n   long  u, v, u0, v0, u1, v1, u2, v2, q, r;\n\n   long aneg = 0, bneg = 0;\n\n   if (a < 0) {\n      if (a < -NTL_MAX_LONG) ResourceError(\"XGCD: integer overflow\");\n      a = -a;\n      aneg = 1;\n   }\n\n   if (b < 0) {\n      if (b < -NTL_MAX_LONG) ResourceError(\"XGCD: integer overflow\");\n      b = -b;\n      bneg = 1;\n   }\n\n   u1=1; v1=0;\n   u2=0; v2=1;\n   u = a; v = b;\n\n   while (v != 0) {\n      q = u / v;\n      r = u % v;\n      u = v;\n      v = r;\n      u0 = u2;\n      v0 = v2;\n      u2 =  u1 - q*u2;\n      v2 = v1- q*v2;\n      u1 = u0;\n      v1 = v0;\n   }\n\n   if (aneg)\n      u1 = -u1;\n\n   if (bneg)\n      v1 = -v1;\n\n   d = u;\n   s = u1;\n   t = v1;\n}\n   \nlong InvModStatus(long& x, long a, long n)\n{\n   long d, s, t;\n\n   XGCD(d, s, t, a, n);\n   if (d != 1) {\n      x = d;\n      return 1;\n   }\n   else {\n      if (s < 0)\n         x = s + n;\n      else\n         x = s;\n\n      return 0;\n   }\n}\n\nlong InvMod(long a, long n)\n{\n   long d, s, t;\n\n   XGCD(d, s, t, a, n);\n   if (d != 1) {\n      InvModError(\"InvMod: inverse undefined\");\n   }\n   if (s < 0)\n      return s + n;\n   else\n      return s;\n}\n\n\nlong PowerMod(long a, long ee, long n)\n{\n   long x, y;\n\n   unsigned long e;\n\n   if (ee < 0)\n      e = - ((unsigned long) ee);\n   else\n      e = ee;\n\n   x = 1;\n   y = a;\n   while (e) {\n      if (e & 1) x = MulMod(x, y, n);\n      y = MulMod(y, y, n);\n      e = e >> 1;\n   }\n\n   if (ee < 0) x = InvMod(x, n);\n\n   return x;\n}\n\nstatic\nlong MillerWitness_sp(long n, long x)\n{\n   long m, y, z;\n   long j, k;\n\n   if (x == 0) return 0;\n\n   m = n - 1;\n   k = 0;\n   while((m & 1) == 0) {\n      m = m >> 1;\n      k++;\n   }\n   // n - 1 == 2^k * m, m odd\n\n   z = PowerMod(x, m, n);\n   if (z == 1) return 0;\n\n   j = 0;\n   do {\n      y = z;\n      z = MulMod(y, y, n);\n      j++;\n   } while (j != k && z != 1);\n\n   if (z != 1 || y != n-1) return 1;\n   return 0;\n}\n\nlong ProbPrime(long n, long NumTrials)\n{\n   if (NumTrials < 0) NumTrials = 0;\n\n   long m, x, y, z;\n   long i, j, k;\n\n   if (n <= 1) return 0;\n\n\n   if (n == 2) return 1;\n   if (n % 2 == 0) return 0;\n\n   if (n == 3) return 1;\n   if (n % 3 == 0) return 0;\n\n   if (n == 5) return 1;\n   if (n % 5 == 0) return 0;\n\n   if (n == 7) return 1;\n   if (n % 7 == 0) return 0;\n\n   if (n == 11) return 1;\n   if (n % 11 == 0) return 0;\n\n   if (n == 13) return 1;\n   if (n % 13 == 0) return 0;\n\n   if (n >= NTL_SP_BOUND) {\n      return ProbPrime(to_ZZ(n), NumTrials);\n   }\n\n   m = n - 1;\n   k = 0;\n   while((m & 1) == 0) {\n      m = m >> 1;\n      k++;\n   }\n\n   // n - 1 == 2^k * m, m odd\n\n   for (i = 0; i < NumTrials+1; i++) {\n      // for consistency with the multi-precision version,\n      // we first see if 2 is a witness, so we really do \n      // NumTrials+1 tests\n\n      if (i == 0) \n         x = 2;\n      else {\n\t do {\n\t    x = RandomBnd(n);\n\t } while (x == 0);\n         // x == 0 is not a useful candidate for a witness!\n      }\n\n      z = PowerMod(x, m, n);\n      if (z == 1) continue;\n   \n      j = 0;\n      do {\n         y = z;\n         z = MulMod(y, y, n);\n         j++;\n      } while (j != k && z != 1);\n\n      if (z != 1 || y !=  n-1) return 0;\n   }\n\n   return 1;\n}\n\n\nlong MillerWitness(const ZZ& n, const ZZ& x)\n{\n   if (n.SinglePrecision()) {\n      return MillerWitness_sp(to_long(n), to_long(x));\n   }\n\n   ZZ m, y, z;\n\n   long j, k;\n\n   if (x == 0) return 0;\n\n   add(m, n, -1);\n   k = MakeOdd(m);\n   // n - 1 == 2^k * m, m odd\n\n   PowerMod(z, x, m, n);\n   if (z == 1) return 0;\n\n   j = 0;\n   do {\n      y = z;\n      SqrMod(z, y, n);\n      j++;\n   } while (j != k && z != 1);\n\n   if (z != 1) return 1;\n   add(y, y, 1);\n   if (y != n) return 1;\n   return 0;\n}\n\n\n// ComputePrimeBound computes a reasonable bound for trial\n// division in the Miller-Rabin test.\n// It is computed a bit on the \"low\" side, since being a bit\n// low doesn't hurt much, but being too high can hurt a lot.\n\n// See the paper \"Fast generation of prime numbers and secure\n// public-key cryptographic parameters\" by Ueli Maurer.\n// In that paper, it is calculated that the optimal bound in\n// roughly T_exp/T_div, where T_exp is the time for an exponentiation\n// and T_div is is the time for a single precision division.\n// Of course, estimating these times is a bit tricky, and\n// the values we use are based on experimentation, assuming\n// GMP is being used.  I've tested this on various bit lengths\n// up to 16,000, and they seem to be pretty close to optimal. \n\nstatic\nlong ComputePrimeBound(long bn)\n{\n   long wn = (bn+NTL_ZZ_NBITS-1)/NTL_ZZ_NBITS;\n\n   long fn;\n\n   if (wn <= 36)\n      fn = wn/4 + 1;\n   else\n      fn = long(1.67*sqrt(double(wn)));\n\n   long prime_bnd;\n\n   if (NumBits(bn) + NumBits(fn) > NTL_SP_NBITS)\n      prime_bnd = NTL_SP_BOUND;\n   else\n      prime_bnd = bn*fn;\n\n   return prime_bnd;\n\n\n}\n\n\nlong ProbPrime(const ZZ& n, long NumTrials)\n{\n   if (NumTrials < 0) NumTrials = 0;\n\n   if (n <= 1) return 0;\n\n   if (n.SinglePrecision()) {\n      return ProbPrime(to_long(n), NumTrials);\n   }\n\n\n   long prime_bnd = ComputePrimeBound(NumBits(n));\n\n\n   PrimeSeq s;\n   long p;\n\n   p = s.next();\n   while (p && p < prime_bnd) {\n      if (rem(n, p) == 0)\n         return 0;\n\n      p = s.next();\n   }\n\n   ZZ W;\n   W = 2;\n\n   // first try W == 2....the exponentiation\n   // algorithm runs slightly faster in this case\n\n   if (MillerWitness(n, W))\n      return 0;\n\n\n   long i;\n\n   for (i = 0; i < NumTrials; i++) {\n      do {\n         RandomBnd(W, n);\n      } while (W == 0);\n      // W == 0 is not a useful candidate for a witness!\n\n      if (MillerWitness(n, W)) \n         return 0;\n   }\n\n   return 1;\n}\n\n\nstatic\nvoid MultiThreadedRandomPrime(ZZ& n, long l, long NumTrials)\n{\n\n   long nt = AvailableThreads();\n\n\n\n   const long LOCAL_ITER_BOUND = 8; \n   // since resetting the PRG comes at a certain cost,\n   // we perform a few iterations with each reset to\n   // amortize the reset cost. \n\n   unsigned long initial_counter = 0;\n   ZZ seed;\n   RandomBits(seed, 256);\n\n   for (;;) {\n\n      AtomicLowWaterMark low_water_mark(-1UL);\n      AtomicCounter counter(initial_counter);\n\n      Vec< UniquePtr<ZZ> > result(INIT_SIZE, nt);\n      Vec<unsigned long> result_ctr(INIT_SIZE, nt, -1UL);\n\n      NTL_EXEC_INDEX(nt, index)\n\n         RandomStreamPush push;\n\n\t SetSeed(seed);\n\t RandomStream& stream = GetCurrentRandomStream();\n\n\t ZZ cand;\n\n\t while (low_water_mark == -1UL) {\n\n\t    unsigned long local_ctr = counter.inc();\n            if (local_ctr >> (NTL_BITS_PER_NONCE-1)) {\n               // counter overflow...rather academic\n               break;\n            }\n\n\t    stream.set_nonce(local_ctr);\n\t    \n\t    for (long iter = 0; iter < LOCAL_ITER_BOUND && \n\t\t\t\tlocal_ctr <= low_water_mark; iter++) {\n\n\t       RandomLen(cand, l);\n\t       if (!IsOdd(cand)) add(cand, cand, 1);\n\n\t       if (ProbPrime(cand, 0)) { \n\t\t  result[index].make(cand);\n\t\t  result_ctr[index] = local_ctr;\n\t\t  low_water_mark.UpdateMin(local_ctr);\n\t\t  break;\n\t       }\n\t    }\n\t }\n\n      NTL_EXEC_INDEX_END\n\n      // find index of low_water_mark\n\n      unsigned long low_water_mark1 = low_water_mark;\n      long low_water_index = -1;\n\n      for (long index = 0; index < nt; index++) {\n\t if (result_ctr[index] == low_water_mark1) {\n\t    low_water_index = index;\n\t    break;\n\t }\n      }\n\n      if (low_water_index == -1) {\n         // counter overflow...rather academic\n         initial_counter = 0;\n         RandomBits(seed, 256);\n         continue;\n      }\n\n      ZZ N;\n      N = *result[low_water_index];\n\n      Vec<ZZ> W(INIT_SIZE, NumTrials);\n\n      for (long i = 0; i < NumTrials; i++) {\n         do { \n            RandomBnd(W[i], N);\n         } while (W[i] == 0);\n      }\n\n      AtomicBool tests_pass(true);\n\n      NTL_EXEC_RANGE(NumTrials, first, last)\n\n         for (long i = first; i < last && tests_pass; i++) {\n            if (MillerWitness(N, W[i])) tests_pass = false;\n         }\n\n      NTL_EXEC_RANGE_END\n\n      if (tests_pass) {\n         n = N;\n         return;\n      }\n\n      // very unlikey to get here\n      initial_counter = low_water_mark1 + 1;\n   }\n}\n\n\nvoid RandomPrime(ZZ& n, long l, long NumTrials)\n{\n   if (NumTrials < 0) NumTrials = 0;\n\n   if (l >= 256) { \n      MultiThreadedRandomPrime(n, l, NumTrials); \n      return;\n   }\n\n   if (l <= 1)\n      LogicError(\"RandomPrime: l out of range\");\n\n   if (l == 2) {\n      if (RandomBnd(2))\n         n = 3;\n      else\n         n = 2;\n\n      return;\n   }\n\n   do {\n      RandomLen(n, l);\n      if (!IsOdd(n)) add(n, n, 1);\n   } while (!ProbPrime(n, NumTrials));\n}\n\nvoid OldRandomPrime(ZZ& n, long l, long NumTrials)\n{\n   if (l <= 1)\n      LogicError(\"RandomPrime: l out of range\");\n\n   if (l == 2) {\n      if (RandomBnd(2))\n         n = 3;\n      else\n         n = 2;\n\n      return;\n   }\n\n   do {\n      RandomLen(n, l);\n      if (!IsOdd(n)) add(n, n, 1);\n   } while (!ProbPrime(n, NumTrials));\n}\n\nvoid NextPrime(ZZ& n, const ZZ& m, long NumTrials)\n{\n   ZZ x;\n\n   if (m <= 2) {\n      n = 2;\n      return;\n   }\n\n   x = m;\n\n   while (!ProbPrime(x, NumTrials))\n      add(x, x, 1);\n\n   n = x;\n}\n\nlong NextPrime(long m, long NumTrials)\n{\n   long x;\n\n   if (m <= 2) \n      return 2;\n\n   x = m;\n\n   while (x < NTL_SP_BOUND && !ProbPrime(x, NumTrials))\n      x++;\n\n   if (x >= NTL_SP_BOUND)\n      ResourceError(\"NextPrime: no more primes\");\n\n   return x;\n}\n\n\n\nlong NextPowerOfTwo(long m)\n{\n   long k; \n   unsigned long n, um;\n\n   if (m < 0) return 0;\n\n   um = m;\n   n = 1;\n   k = 0;\n\n   while (n < um) {\n      n = n << 1;\n      k++;\n   }\n\n   if (k >= NTL_BITS_PER_LONG-1)\n      ResourceError(\"NextPowerOfTwo: overflow\");\n\n   return k;\n}\n\n\n\n\nlong bit(long a, long k)\n{\n   unsigned long aa;\n   if (a < 0)\n      aa = - ((unsigned long) a);\n   else\n      aa = a;\n\n   if (k < 0 || k >= NTL_BITS_PER_LONG) \n      return 0;\n   else\n      return long((aa >> k) & 1);\n}\n\n\n\nlong divide(ZZ& q, const ZZ& a, const ZZ& b)\n{\n   NTL_ZZRegister(qq);\n   NTL_ZZRegister(r);\n\n   if (IsZero(b)) {\n      if (IsZero(a)) {\n         clear(q);\n         return 1;\n      }\n      else\n         return 0;\n   }\n\n\n   if (IsOne(b)) {\n      q = a;\n      return 1;\n   }\n\n   DivRem(qq, r, a, b);\n   if (!IsZero(r)) return 0;\n   q = qq;\n   return 1;\n}\n\nlong divide(const ZZ& a, const ZZ& b)\n{\n   NTL_ZZRegister(r);\n\n   if (IsZero(b)) return IsZero(a);\n   if (IsOne(b)) return 1;\n\n   rem(r, a, b);\n   return IsZero(r);\n}\n\nlong divide(ZZ& q, const ZZ& a, long b)\n{\n   NTL_ZZRegister(qq);\n\n   if (!b) {\n      if (IsZero(a)) {\n         clear(q);\n         return 1;\n      }\n      else\n         return 0;\n   }\n\n   if (b == 1) {\n      q = a;\n      return 1;\n   }\n\n   long r = DivRem(qq, a, b);\n   if (r) return 0;\n   q = qq;\n   return 1;\n}\n\nlong divide(const ZZ& a, long b)\n{\n   if (!b) return IsZero(a);\n   if (b == 1) {\n      return 1;\n   }\n\n   long r = rem(a,  b);\n   return (r == 0);\n}\n\n\nvoid InvMod(ZZ& x, const ZZ& a, const ZZ& n)\n{\n   // NOTE: the underlying LIP routines write to the first argument,\n   // even if inverse is undefined\n\n   NTL_ZZRegister(xx);\n   if (InvModStatus(xx, a, n)) \n      InvModError(\"InvMod: inverse undefined\", a, n);\n   x = xx;\n}\n\nvoid PowerMod(ZZ& x, const ZZ& a, const ZZ& e, const ZZ& n)\n{\n   // NOTE: this ensures that all modular inverses are computed\n   // in the routine InvMod above, rather than the LIP-internal\n   // modular inverse routine\n   if (e < 0) {\n      ZZ a_inv;\n      ZZ e_neg;\n\n      InvMod(a_inv, a, n);\n      negate(e_neg, e);\n      LowLevelPowerMod(x, a_inv, e_neg, n);\n   }\n   else\n      LowLevelPowerMod(x, a, e, n); \n}\n   \n#ifdef NTL_EXCEPTIONS\n\nvoid InvModError(const char *s, const ZZ& a, const ZZ& n)\n{\n   throw InvModErrorObject(s, a, n); \n}\n\n#else\n\nvoid InvModError(const char *s, const ZZ& a, const ZZ& n)\n{\n   TerminalError(s);\n}\n\n\n#endif\n\nlong RandomPrime_long(long l, long NumTrials)\n{\n   if (NumTrials < 0) NumTrials = 0;\n\n   if (l <= 1 || l >= NTL_BITS_PER_LONG)\n      ResourceError(\"RandomPrime: length out of range\");\n\n   long n;\n   do {\n      n = RandomLen_long(l);\n   } while (!ProbPrime(n, NumTrials));\n\n   return n;\n}\n\n\nstatic Lazy< Vec<char> > lowsieve_storage;\n// This is a GLOBAL VARIABLE\n\n\nPrimeSeq::PrimeSeq()\n{\n   movesieve = 0;\n   pshift = -1;\n   pindex = -1;\n   exhausted = 0;\n}\n\n\nlong PrimeSeq::next()\n{\n   if (exhausted) {\n      return 0;\n   }\n\n   if (pshift < 0) {\n      shift(0);\n      return 2;\n   }\n\n   for (;;) {\n      const char *p = movesieve;\n      long i = pindex;\n\n      while ((++i) < NTL_PRIME_BND) {\n         if (p[i]) {\n            pindex = i;\n            return pshift + 2 * i + 3;\n         }\n      }\n\n      long newshift = pshift + 2*NTL_PRIME_BND;\n\n      if (newshift > 2 * NTL_PRIME_BND * (2 * NTL_PRIME_BND + 1)) {\n         /* end of the road */\n         exhausted = 1;\n         return 0;\n      }\n\n      shift(newshift);\n   }\n}\n\nvoid PrimeSeq::shift(long newshift)\n{\n   long i;\n   long j;\n   long jstep;\n   long jstart;\n   long ibound;\n   char *p;\n\n   if (!lowsieve_storage.built())\n      start();\n\n   const char *lowsieve = lowsieve_storage->elts();\n\n\n   if (newshift < 0) {\n      pshift = -1;\n   }\n   else if (newshift == 0) {\n      pshift = 0;\n      movesieve = lowsieve;\n   } \n   else if (newshift != pshift) {\n      if (movesieve_mem.length() == 0) {\n         movesieve_mem.SetLength(NTL_PRIME_BND);\n      }\n\n      pshift = newshift;\n      movesieve = p = movesieve_mem.elts();\n      for (i = 0; i < NTL_PRIME_BND; i++)\n         p[i] = 1;\n\n      jstep = 3;\n      ibound = pshift + 2 * NTL_PRIME_BND + 1;\n      for (i = 0; jstep * jstep <= ibound; i++) {\n         if (lowsieve[i]) {\n            if (!((jstart = (pshift + 2) / jstep + 1) & 1))\n               jstart++;\n            if (jstart <= jstep)\n               jstart = jstep;\n            jstart = (jstart * jstep - pshift - 3) / 2;\n            for (j = jstart; j < NTL_PRIME_BND; j += jstep)\n               p[j] = 0;\n         }\n         jstep += 2;\n      }\n   }\n\n   pindex = -1;\n   exhausted = 0;\n}\n\n\nvoid PrimeSeq::start()\n{\n   long i;\n   long j;\n   long jstep;\n   long jstart;\n   long ibnd;\n   char *p;\n\n   do {\n      Lazy< Vec<char> >::Builder builder(lowsieve_storage);\n      if (!builder()) break;\n\n      UniquePtr< Vec<char> > ptr;\n      ptr.make();\n      ptr->SetLength(NTL_PRIME_BND);\n\n      p = ptr->elts();\n\n      for (i = 0; i < NTL_PRIME_BND; i++)\n         p[i] = 1;\n         \n      jstep = 1;\n      jstart = -1;\n      ibnd = (SqrRoot(2 * NTL_PRIME_BND + 1) - 3) / 2;\n      for (i = 0; i <= ibnd; i++) {\n         jstart += 2 * ((jstep += 2) - 1);\n         if (p[i])\n            for (j = jstart; j < NTL_PRIME_BND; j += jstep)\n               p[j] = 0;\n      }\n\n      builder.move(ptr);\n   } while (0);\n\n}\n\nvoid PrimeSeq::reset(long b)\n{\n   if (b > (2*NTL_PRIME_BND+1)*(2*NTL_PRIME_BND+1)) {\n      exhausted = 1;\n      return;\n   }\n\n   if (b <= 2) {\n      shift(-1);\n      return;\n   }\n\n   if ((b & 1) == 0) b++;\n\n   shift(((b-3) / (2*NTL_PRIME_BND))* (2*NTL_PRIME_BND));\n   pindex = (b - pshift - 3)/2 - 1;\n}\n \nlong Jacobi(const ZZ& aa, const ZZ& nn)\n{\n   ZZ a, n;\n   long t, k;\n   long d;\n\n   a = aa;\n   n = nn;\n   t = 1;\n\n   while (a != 0) {\n      k = MakeOdd(a);\n      d = trunc_long(n, 3);\n      if ((k & 1) && (d == 3 || d == 5)) t = -t;\n\n      if (trunc_long(a, 2) == 3 && (d & 3) == 3) t = -t;\n      swap(a, n);\n      rem(a, a, n);\n   }\n\n   if (n == 1)\n      return t;\n   else\n      return 0;\n}\n\n\nvoid SqrRootMod(ZZ& x, const ZZ& aa, const ZZ& nn)\n{\n   if (aa == 0 || aa == 1) {\n      x = aa;\n      return;\n   }\n\n   // at this point, we must have nn >= 5\n\n   if (trunc_long(nn, 2) == 3) {  // special case, n = 3 (mod 4)\n      ZZ n, a, e, z;\n\n      n = nn;\n      a  = aa;\n\n      add(e, n, 1);\n      RightShift(e, e, 2);\n\n      PowerMod(z, a, e, n);\n      x = z;\n\n      return;\n   }\n\n   ZZ n, m;\n   int h, nlen;\n\n   n = nn;\n   nlen = NumBits(n);\n\n   sub(m, n, 1);\n   h = MakeOdd(m);  // h >= 2\n\n\n   if (nlen > 50 && h < SqrRoot(nlen)) {\n      long i, j;\n      ZZ a, b, a_inv, c, r, m1, d;\n\n      a = aa;\n      InvMod(a_inv, a, n);\n\n      if (h == 2) \n         b = 2;\n      else {\n         do {\n            RandomBnd(b, n);\n         } while (Jacobi(b, n) != -1);\n      }\n\n\n      PowerMod(c, b, m, n);\n      \n      add(m1, m, 1);\n      RightShift(m1, m1, 1);\n      PowerMod(r, a, m1, n);\n\n      for (i = h-2; i >= 0; i--) {\n         SqrMod(d, r, n);\n         MulMod(d, d, a_inv, n);\n         for (j = 0; j < i; j++)\n            SqrMod(d, d, n);\n         if (!IsOne(d))\n            MulMod(r, r, c, n);\n         SqrMod(c, c, n);\n      } \n\n      x = r;\n      return;\n   } \n\n\n\n\n\n   long i, k;\n   ZZ ma, t, u, v, e;\n   ZZ t1, t2, t3, t4;\n\n   n = nn;\n   NegateMod(ma, aa, n);\n\n   // find t such that t^2 - 4*a is not a square\n\n   MulMod(t1, ma, 4, n);\n   do {\n      RandomBnd(t, n);\n      SqrMod(t2, t, n);\n      AddMod(t2, t2, t1, n);\n   } while (Jacobi(t2, n) != -1);\n\n   // compute u*X + v = X^{(n+1)/2} mod f, where f = X^2 - t*X + a\n\n   add(e, n, 1);\n   RightShift(e, e, 1);\n\n   u = 0;\n   v = 1;\n\n   k = NumBits(e);\n\n   for (i = k - 1; i >= 0; i--) {\n      add(t2, u, v);\n      sqr(t3, t2);  // t3 = (u+v)^2\n      sqr(t1, u);\n      sqr(t2, v);\n      sub(t3, t3, t1);\n      sub(t3, t3, t2); // t1 = u^2, t2 = v^2, t3 = 2*u*v\n      rem(t1, t1, n);\n      mul(t4, t1, t);\n      add(t4, t4, t3);\n      rem(u, t4, n);\n\n      mul(t4, t1, ma);\n      add(t4, t4, t2);\n      rem(v, t4, n);\n      \n      if (bit(e, i)) {\n         MulMod(t1, u, t, n);\n         AddMod(t1, t1, v, n);\n         MulMod(v, u, ma, n);\n         u = t1;\n      }\n\n   }\n\n   x = v;\n}\n\n\n\n// Chinese Remaindering.\n//\n// This version in new to v3.7, and is significantly\n// simpler and faster than the previous version.\n//\n// This function takes as input g, a, G, p,\n// such that a > 0, 0 <= G < p, and gcd(a, p) = 1.\n// It computes a' = a*p and g' such that \n//   * g' = g (mod a);\n//   * g' = G (mod p);\n//   * -a'/2 < g' <= a'/2.\n// It then sets g := g' and a := a', and returns 1 iff g has changed.\n//\n// Under normal use, the input value g satisfies -a/2 < g <= a/2;\n// however, this was not documented or enforced in earlier versions,\n// so to maintain backward compatability, no restrictions are placed\n// on g.  This routine runs faster, though, if -a/2 < g <= a/2,\n// and the first thing the routine does is to make this condition\n// hold.\n//\n// Also, under normal use, both a and p are odd;  however, the routine\n// will still work even if this is not so.\n//\n// The routine is based on the following simple fact.\n//\n// Let -a/2 < g <= a/2, and let h satisfy\n//   * g + a h = G (mod p);\n//   * -p/2 < h <= p/2.\n// Further, if p = 2*h and g > 0, set\n//   g' := g - a h;\n// otherwise, set\n//   g' := g + a h.\n// Then g' so defined satisfies the above requirements.\n//\n// It is trivial to see that g's satisfies the congruence conditions.\n// The only thing is to check that the \"balancing\" condition\n// -a'/2 < g' <= a'/2 also holds.\n\n\nlong CRT(ZZ& gg, ZZ& a, long G, long p)\n{\n   if (p >= NTL_SP_BOUND) {\n      ZZ GG, pp;\n      conv(GG, G);\n      conv(pp, p);\n      return CRT(gg, a, GG, pp);\n   }\n\n   long modified = 0;\n\n   NTL_ZZRegister(g);\n\n   if (!CRTInRange(gg, a)) {\n      modified = 1;\n      ZZ a1;\n      rem(g, gg, a);\n      RightShift(a1, a, 1);\n      if (g > a1) sub(g, g, a);\n   }\n   else\n      g = gg;\n\n\n   long p1;\n   p1 = p >> 1;\n\n   long a_inv;\n   a_inv = rem(a, p);\n   a_inv = InvMod(a_inv, p);\n\n   long h;\n   h = rem(g, p);\n   h = SubMod(G, h, p);\n   h = MulMod(h, a_inv, p);\n   if (h > p1)\n      h = h - p;\n\n   if (h != 0) {\n      modified = 1;\n\n      if (!(p & 1) && g > 0 && (h == p1))\n         MulSubFrom(g, a, h);\n      else\n         MulAddTo(g, a, h);\n   }\n\n   mul(a, a, p);\n   gg = g;\n\n   return modified;\n}\n\nlong CRT(ZZ& gg, ZZ& a, const ZZ& G, const ZZ& p)\n{\n   long modified = 0;\n\n   ZZ g;\n\n   if (!CRTInRange(gg, a)) {\n      modified = 1;\n      ZZ a1;\n      rem(g, gg, a);\n      RightShift(a1, a, 1);\n      if (g > a1) sub(g, g, a);\n   }\n   else\n      g = gg;\n\n\n   ZZ p1;\n   RightShift(p1, p, 1);\n\n   ZZ a_inv;\n   rem(a_inv, a, p);\n   InvMod(a_inv, a_inv, p);\n\n   ZZ h;\n   rem(h, g, p);\n   SubMod(h, G, h, p);\n   MulMod(h, h, a_inv, p);\n   if (h > p1)\n      sub(h, h, p);\n\n   if (h != 0) {\n      modified = 1;\n      ZZ ah;\n      mul(ah, a, h);\n\n      if (!IsOdd(p) && g > 0 &&  (h == p1))\n         sub(g, g, ah);\n      else\n         add(g, g, ah);\n   }\n\n   mul(a, a, p);\n   gg = g;\n\n   return modified;\n}\n\n\n\nvoid sub(ZZ& x, long a, const ZZ& b)\n{\n   NTL_ZZRegister(A);\n   conv(A, a);\n   sub(x, A, b);\n}\n\n\nvoid power2(ZZ& x, long e)\n{\n   if (e < 0) ArithmeticError(\"power2: negative exponent\");\n   set(x);\n   LeftShift(x, x, e);\n}\n\n   \n\nvoid bit_and(ZZ& x, const ZZ& a, long b)\n{\n   NTL_ZZRegister(B);\n   conv(B, b);\n   bit_and(x, a, B);\n}\n\nvoid bit_or(ZZ& x, const ZZ& a, long b)\n{\n   NTL_ZZRegister(B);\n   conv(B, b);\n   bit_or(x, a, B);\n}\n\nvoid bit_xor(ZZ& x, const ZZ& a, long b)\n{\n   NTL_ZZRegister(B);\n   conv(B, b);\n   bit_xor(x, a, B);\n}\n\n\nlong power_long(long a, long e)\n{\n   if (e < 0) ArithmeticError(\"power_long: negative exponent\");\n\n   if (e == 0) return 1;\n\n   if (a == 1) return 1;\n   if (a == -1) {\n      if (e & 1)\n         return -1;\n      else\n         return 1;\n   }\n\n   // no overflow check --- result is computed correctly\n   // modulo word size\n\n   unsigned long res = 1;\n   unsigned long aa = a;\n   long i;\n\n   for (i = 0; i < e; i++)\n      res *= aa;\n\n   return to_long(res);\n}\n\n\n\n// ======================= new PRG stuff ======================\n\n\n\n\n#if (NTL_BITS_PER_INT32 == 32)\n#define INT32MASK(x) (x)\n#else\n#define INT32MASK(x) ((x) & _ntl_uint32(0xffffffff))\n#endif\n\n\n\n// SHA256 code adapted from an implementauin by Brad Conte.\n// The following is from his original source files.\n/*********************************************************************\n* Filename:   sha256.c\n* Author:     Brad Conte (brad AT bradconte.com)\n* Copyright:\n* Disclaimer: This code is presented \"as is\" without any guarantees.\n* Details:    Implementation of the SHA-256 hashing algorithm.\n              SHA-256 is one of the three algorithms in the SHA2\n              specification. The others, SHA-384 and SHA-512, are not\n              offered in this implementation.\n              Algorithm specification can be found here:\n               * http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf\n              This implementation uses little endian byte order.\n*********************************************************************/\n\n// And the following is from the description at \n// https://github.com/B-Con/crypto-algorithms\n\n/*********************************************************************\n\nThese are basic implementations of standard cryptography algorithms, written by\nBrad Conte (brad@bradconte.com) from scratch and without any cross-licensing.\nThey exist to provide publically accessible, restriction-free implementations\nof popular cryptographic algorithms, like AES and SHA-1. These are primarily\nintended for educational and pragmatic purposes (such as comparing a\nspecification to actual implementation code, or for building an internal\napplication that computes test vectors for a product). The algorithms have been\ntested against standard test vectors.\n\nThis code is released into the public domain free of any restrictions. The\nauthor requests acknowledgement if the code is used, but does not require it.\nThis code is provided free of any liability and without any quality claims by\nthe author.\n\nNote that these are not cryptographically secure implementations. They have no\nresistence to side-channel attacks and should not be used in contexts that need\ncryptographically secure implementations.\n\nThese algorithms are not optimized for speed or space. They are primarily\ndesigned to be easy to read, although some basic optimization techniques have\nbeen employed.\n\n*********************************************************************/\n\n\n\n\n\n\n#define SHA256_BLOCKSIZE (64)\n#define SHA256_HASHSIZE  (32)\n\n// DBL_INT_ADD treats two unsigned ints a and b as one 64-bit integer and adds c to it\nstatic inline\nvoid DBL_INT_ADD(_ntl_uint32& a, _ntl_uint32& b, _ntl_uint32 c)\n{\n   _ntl_uint32 aa = INT32MASK(a);\n   if (aa > INT32MASK(_ntl_uint32(0xffffffff) - c)) b++;\n   a = aa + c;\n}\n\n#define ROTLEFT(a,b) (((a) << (b)) | (INT32MASK(a) >> (32-(b))))\n#define ROTRIGHT(a,b) ((INT32MASK(a) >> (b)) | ((a) << (32-(b))))\n\n#define CH(x,y,z) (((x) & (y)) ^ (~(x) & (z)))\n#define MAJ(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))\n#define EP0(x) (ROTRIGHT(x,2) ^ ROTRIGHT(x,13) ^ ROTRIGHT(x,22))\n#define EP1(x) (ROTRIGHT(x,6) ^ ROTRIGHT(x,11) ^ ROTRIGHT(x,25))\n#define SIG0(x) (ROTRIGHT(x,7) ^ ROTRIGHT(x,18) ^ (INT32MASK(x) >> 3))\n#define SIG1(x) (ROTRIGHT(x,17) ^ ROTRIGHT(x,19) ^ (INT32MASK(x) >> 10))\n\nstruct SHA256_CTX {\n   unsigned char data[64];\n   _ntl_uint32 datalen;\n   _ntl_uint32 bitlen[2];\n   _ntl_uint32 state[8];\n};\n\nstatic const _ntl_uint32 sha256_const[64] = {\n   0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,\n   0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,\n   0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,\n   0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,\n   0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,\n   0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,\n   0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,\n   0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2\n};\n\n\nstatic\nvoid sha256_transform(SHA256_CTX& ctx, unsigned char *data)\n{  \n   _ntl_uint32 a,b,c,d,e,f,g,h,i,j,t1,t2,m[64];\n      \n   for (i=0,j=0; i < 16; ++i, j += 4)\n      m[i] = (data[j] << 24) | (data[j+1] << 16) | (data[j+2] << 8) | (data[j+3]);\n   for ( ; i < 64; ++i)\n      m[i] = SIG1(m[i-2]) + m[i-7] + SIG0(m[i-15]) + m[i-16];\n\n   a = ctx.state[0];\n   b = ctx.state[1];\n   c = ctx.state[2];\n   d = ctx.state[3];\n   e = ctx.state[4];\n   f = ctx.state[5];\n   g = ctx.state[6];\n   h = ctx.state[7];\n   \n   for (i = 0; i < 64; ++i) {\n      t1 = h + EP1(e) + CH(e,f,g) + sha256_const[i] + m[i];\n      t2 = EP0(a) + MAJ(a,b,c);\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   ctx.state[0] += a;\n   ctx.state[1] += b;\n   ctx.state[2] += c;\n   ctx.state[3] += d;\n   ctx.state[4] += e;\n   ctx.state[5] += f;\n   ctx.state[6] += g;\n   ctx.state[7] += h;\n}  \n\nstatic\nvoid sha256_init(SHA256_CTX& ctx)\n{  \n   ctx.datalen = 0; \n   ctx.bitlen[0] = 0; \n   ctx.bitlen[1] = 0; \n   ctx.state[0] = 0x6a09e667;\n   ctx.state[1] = 0xbb67ae85;\n   ctx.state[2] = 0x3c6ef372;\n   ctx.state[3] = 0xa54ff53a;\n   ctx.state[4] = 0x510e527f;\n   ctx.state[5] = 0x9b05688c;\n   ctx.state[6] = 0x1f83d9ab;\n   ctx.state[7] = 0x5be0cd19;\n}\n\nstatic\nvoid sha256_update(SHA256_CTX& ctx, const unsigned char *data, _ntl_uint32 len)\n{  \n   _ntl_uint32 i;\n   \n   for (i=0; i < len; ++i) { \n      ctx.data[ctx.datalen] = data[i]; \n      ctx.datalen++; \n      if (ctx.datalen == 64) { \n         sha256_transform(ctx,ctx.data);\n         DBL_INT_ADD(ctx.bitlen[0],ctx.bitlen[1],512); \n         ctx.datalen = 0; \n      }  \n   }  \n}  \n\nstatic\nvoid sha256_final(SHA256_CTX& ctx, unsigned char *hash, \n                  long hlen=SHA256_HASHSIZE)\n{  \n   _ntl_uint32 i, j; \n   \n   i = ctx.datalen; \n   \n   // Pad whatever data is left in the buffer. \n   if (ctx.datalen < 56) { \n      ctx.data[i++] = 0x80; \n      while (i < 56) \n         ctx.data[i++] = 0x00; \n   }  \n   else { \n      ctx.data[i++] = 0x80; \n      while (i < 64) \n         ctx.data[i++] = 0x00; \n      sha256_transform(ctx,ctx.data);\n      memset(ctx.data,0,56); \n   }  \n   \n   // Append to the padding the total message's length in bits and transform. \n   DBL_INT_ADD(ctx.bitlen[0],ctx.bitlen[1],ctx.datalen * 8);\n\n   ctx.data[63] = ctx.bitlen[0]; \n   ctx.data[62] = ctx.bitlen[0] >> 8; \n   ctx.data[61] = ctx.bitlen[0] >> 16; \n   ctx.data[60] = ctx.bitlen[0] >> 24; \n   ctx.data[59] = ctx.bitlen[1]; \n   ctx.data[58] = ctx.bitlen[1] >> 8; \n   ctx.data[57] = ctx.bitlen[1] >> 16;  \n   ctx.data[56] = ctx.bitlen[1] >> 24; \n   sha256_transform(ctx,ctx.data);\n   \n   for (i = 0; i < 8; i++) {\n      _ntl_uint32 w = ctx.state[i];\n      for (j = 0; j < 4; j++) {\n         if (hlen <= 0) break;\n         hash[4*i + j] = w >> (24-j*8); \n         hlen--;\n      }\n   }\n\n}  \n\n\n\nstatic\nvoid sha256(const unsigned char *data, long dlen, unsigned char *hash, \n            long hlen=SHA256_HASHSIZE)\n{\n   if (dlen < 0) dlen = 0;\n   if (hlen < 0) hlen = 0;\n\n   SHA256_CTX ctx;\n   sha256_init(ctx);\n\n   const long BLKSIZE = 4096;\n\n   long i;\n   for (i = 0; i <= dlen-BLKSIZE; i += BLKSIZE) \n      sha256_update(ctx, data + i, BLKSIZE);\n\n   if (i < dlen)\n      sha256_update(ctx, data + i, dlen - i);\n\n   sha256_final(ctx, hash, hlen);\n}\n\n\nstatic\nvoid hmac_sha256(const unsigned char *key, long klen, \n                 const unsigned char *data, long dlen,\n                 unsigned char *hash, long hlen=SHA256_HASHSIZE)\n{\n   if (klen < 0) klen = 0;\n   if (dlen < 0) dlen = 0;\n   if (hlen < 0) hlen = 0;\n\n   unsigned char K[SHA256_BLOCKSIZE];\n   unsigned char tmp[SHA256_HASHSIZE];\n\n   long i;\n\n   if (klen <= SHA256_BLOCKSIZE) {\n      for (i = 0; i < klen; i++)\n         K[i] = key[i];\n      for (i = klen; i < SHA256_BLOCKSIZE; i++) \n         K[i] = 0;\n   }\n   else {\n      sha256(key, klen, K, SHA256_BLOCKSIZE); \n      for (i = SHA256_HASHSIZE; i < SHA256_BLOCKSIZE; i++)\n         K[i] = 0;\n   }\n\n   for (i = 0; i < SHA256_BLOCKSIZE; i++)\n      K[i] ^= 0x36;\n\n   SHA256_CTX ctx;\n   sha256_init(ctx);\n   sha256_update(ctx, K, SHA256_BLOCKSIZE);\n   sha256_update(ctx, data, dlen);\n   sha256_final(ctx, tmp);\n\n   for (i = 0; i < SHA256_BLOCKSIZE; i++)\n      K[i] ^= (0x36 ^ 0x5C);\n\n   sha256_init(ctx);\n   sha256_update(ctx, K, SHA256_BLOCKSIZE);\n   sha256_update(ctx, tmp, SHA256_HASHSIZE);\n   sha256_final(ctx, hash, hlen);\n}\n\n\n// This key derivation uses HMAC with a zero key to derive\n// an intermediate key K from the data, and then uses HMAC\n// as a PRF in counter mode with key K to derive the final key\n\nvoid DeriveKey(unsigned char *key, long klen,  \n               const unsigned char *data, long dlen)\n{\n   if (dlen < 0) LogicError(\"DeriveKey: bad args\");\n   if (klen < 0) LogicError(\"DeriveKey: bad args\");\n\n   long i, j;\n\n\n   unsigned char K[SHA256_HASHSIZE];\n   hmac_sha256(0, 0, data, dlen, K); \n\n   // initialize 64-bit counter to zero\n   unsigned char counter[8];\n   for (j = 0; j < 8; j++) counter[j] = 0;\n\n   for (i = 0; i <= klen-SHA256_HASHSIZE; i += SHA256_HASHSIZE) {\n      hmac_sha256(K, SHA256_HASHSIZE, counter, 8, key+i); \n\n      // increment counter\n      for (j = 0; j < 8; j++) {\n         counter[j]++;\n         if (counter[j] != 0) break; \n      }\n   }\n\n   if (i < klen) \n      hmac_sha256(K, SHA256_HASHSIZE, counter, 8, key+i, klen-i);\n}\n\n\n\n\n// ******************** ChaCha20 stuff ***********************\n\n// ============= old stuff\n\n#define LE(p) (((_ntl_uint32)((p)[0])) + ((_ntl_uint32)((p)[1]) << 8) + \\\n    ((_ntl_uint32)((p)[2]) << 16) + ((_ntl_uint32)((p)[3]) << 24))\n\n#define FROMLE(p, x) (p)[0] = (x), (p)[1] = ((x) >> 8), \\\n   (p)[2] = ((x) >> 16), (p)[3] = ((x) >> 24)\n\n\n#define QUARTERROUND(x, a, b, c, d) \\\n    x[a] += x[b], x[d] = ROTLEFT(x[d] ^ x[a], 16), \\\n    x[c] += x[d], x[b] = ROTLEFT(x[b] ^ x[c], 12), \\\n    x[a] += x[b], x[d] = ROTLEFT(x[d] ^ x[a], 8), \\\n    x[c] += x[d], x[b] = ROTLEFT(x[b] ^ x[c], 7)\n\n\nstatic\nvoid salsa20_core(_ntl_uint32* data)\n{\n   long i;\n\n   for (i = 0; i < 10; i++) {\n      QUARTERROUND(data, 0, 4, 8, 12);\n      QUARTERROUND(data, 1, 5, 9, 13);\n      QUARTERROUND(data, 2, 6, 10, 14);\n      QUARTERROUND(data, 3, 7, 11, 15);\n      QUARTERROUND(data, 0, 5, 10, 15);\n      QUARTERROUND(data, 1, 6, 11, 12);\n      QUARTERROUND(data, 2, 7, 8, 13);\n      QUARTERROUND(data, 3, 4, 9, 14);\n   }\n}\n\n\n// key K must be exactly 32 bytes\nstatic\nvoid salsa20_init(_ntl_uint32 *state, const unsigned char *K)  \n{\n   static const _ntl_uint32 chacha_const[4] = \n      { 0x61707865, 0x3320646e, 0x79622d32, 0x6b206574 };\n\n   long i;\n\n   for (i = 0; i < 4; i++)\n      state[i] = chacha_const[i];\n\n   for (i = 4; i < 12; i++)\n      state[i] = LE(K + 4*(i-4));\n\n   for (i = 12; i < 16; i++)\n      state[i] = 0;\n}\n\n\n\n// state and data are of length 16\nstatic\nvoid salsa20_apply(_ntl_uint32 *state, _ntl_uint32 *data)\n{\n   long i;\n\n   for (i = 0; i < 16; i++) data[i] = state[i];\n\n   salsa20_core(data);\n\n   for (i = 0; i < 16; i++) data[i] += state[i];\n\n   for (i = 12; i < 14; i++) {\n      state[i]++;\n      state[i] = INT32MASK(state[i]);\n      if (state[i] != 0) break;\n   }\n}\n\n\n\nold_RandomStream::old_RandomStream(const unsigned char *key)\n{\n   salsa20_init(state, key);\n   pos = 64;\n}\n\n\nvoid old_RandomStream::do_get(unsigned char *res, long n)\n{\n   if (n < 0) LogicError(\"RandomStream::get: bad args\");\n\n   long i, j;\n\n   if (n <= 64-pos) {\n      for (i = 0; i < n; i++) res[i] = buf[pos+i];\n      pos += n;\n      return;\n   }\n\n   // read remainder of buffer\n   for (i = 0; i < 64-pos; i++) res[i] = buf[pos+i];\n   n -= 64-pos;\n   res += 64-pos;\n   pos = 64;\n\n   _ntl_uint32 wdata[16];\n\n   // read 64-byte chunks\n   for (i = 0; i <= n-64; i += 64) {\n      salsa20_apply(state, wdata);\n      for (j = 0; j < 16; j++)\n         FROMLE(res + i + 4*j, wdata[j]);\n   }\n\n   if (i < n) { \n      salsa20_apply(state, wdata);\n\n      for (j = 0; j < 16; j++)\n         FROMLE(buf + 4*j, wdata[j]);\n\n      pos = n-i;\n      for (j = 0; j < pos; j++)\n         res[i+j] = buf[j];\n   }\n}\n\n#if (defined(NTL_HAVE_AVX2) || defined(NTL_HAVE_SSSE3))\n\n\n/*****************************************************************\n\nThis AVX2 implementation is derived from public domain code \noriginally developed by Martin Goll Shay Gueron, and obtained from \nhere:\n\nhttps://github.com/floodyberry/supercop/tree/master/crypto_stream/chacha20/goll_gueron\n\nOn a Haswell machine, ths code is about 4.x faster than the vanilla \nC code.\n\nThe following is the README from that page\n\n==================================================================\n\nThis code implements Daniel J. Bernstein's ChaCha stream cipher in C,\ntargeting architectures with AVX2 and future AVX512 vector extensions.\n\nThe implementation improves the slightly modified implementations of Ted Krovetz in the Chromium Project\n(http://src.chromium.org/viewvc/chrome/trunk/deps/third_party/nss/nss/lib/freebl/chacha20/chacha20_vec.c and\nhttp://src.chromium.org/viewvc/chrome/trunk/deps/third_party/openssl/openssl/crypto/chacha/chacha_vec.c)\nby using the Advanced Vector Extensions AVX2 and, if available in future, AVX512 to widen the vectorization\nto 256-bit, respectively 512-bit.\n\nOn Intel's Haswell architecture this implementation (using AVX2) is almost ~2x faster than the fastest \nimplementation here, when encrypting (decrypting) 2 blocks and more. Also, this implementation is expected \nto double the speed again, when encrypting (decrypting) 4 blocks and more, running on a future architecture\nwith support for AVX512.\n\nFurther details and our measurement results are provided in:\nGoll, M., and Gueron,S.: Vectorization of ChaCha Stream Cipher. Cryptology ePrint Archive, \nReport 2013/759, November, 2013, http://eprint.iacr.org/2013/759.pdf\n\nDevelopers and authors:\n*********************************************************\nMartin Goll (1) and Shay Gueron (2, 3), \n(1) Ruhr-University Bochum, Germany\n(2) University of Haifa, Israel\n(3) Intel Corporation, Israel Development Center, Haifa, Israel\n*********************************************************\n\nIntellectual Property Notices\n-----------------------------\n\nThere are no known present or future claims by a copyright holder that the\ndistribution of this software infringes the copyright. In particular, the author\nof the software is not making such claims and does not intend to make such\nclaims.\n\nThere are no known present or future claims by a patent holder that the use of\nthis software infringes the patent. In particular, the author of the software is\nnot making such claims and does not intend to make such claims.\n\nOur implementation is in public domain.\n\n*****************************************************************/\n\n\n// round selector, specified values:\n//  8:  low security - high speed\n// 12:  mid security -  mid speed\n// 20: high security -  low speed\n#ifndef CHACHA_RNDS\n#define CHACHA_RNDS 20\n#endif\n\n\n#if (defined(NTL_HAVE_AVX2))\n\ntypedef __m256i ivec_t;\n\n#define DELTA\t_mm256_set_epi64x(0,2,0,2)\n#define START   _mm256_set_epi64x(0,1,0,0)\n#define NONCE(nonce) _mm256_set_epi64x(nonce, 1, nonce, 0)   \n\n#define STOREU_VEC(m,r)\t_mm256_storeu_si256((__m256i*)(m), r)\n#define STORE_VEC(m,r)\t_mm256_store_si256((__m256i*)(m), r)\n\n#define LOAD_VEC(r,m) r = _mm256_load_si256((const __m256i *)(m))\n#define LOADU_VEC(r,m) r = _mm256_loadu_si256((const __m256i *)(m))\n\n#define LOADU_VEC_128(r, m) r = _mm256_broadcastsi128_si256(_mm_loadu_si128((const __m128i*)(m)))\n\n\n\n#define ADD_VEC_32(a,b)\t_mm256_add_epi32(a, b)\n#define ADD_VEC_64(a,b)\t_mm256_add_epi64(a, b)\n#define XOR_VEC(a,b)\t_mm256_xor_si256(a, b)\n\n\n#define ROR_VEC_V1(x)\t_mm256_shuffle_epi32(x,_MM_SHUFFLE(0,3,2,1))\n#define ROR_VEC_V2(x)\t_mm256_shuffle_epi32(x,_MM_SHUFFLE(1,0,3,2))\n#define ROR_VEC_V3(x)\t_mm256_shuffle_epi32(x,_MM_SHUFFLE(2,1,0,3))\n#define ROL_VEC_7(x)\tXOR_VEC(_mm256_slli_epi32(x, 7), _mm256_srli_epi32(x,25))\n#define ROL_VEC_12(x)\tXOR_VEC(_mm256_slli_epi32(x,12), _mm256_srli_epi32(x,20))\n\n#define ROL_VEC_8(x)\t_mm256_shuffle_epi8(x,_mm256_set_epi8(14,13,12,15,10,9,8,11,6,5,4,7,2,1,0,3,14,13,12,15,10,9,8,11,6,5,4,7,2,1,0,3))\n\n\n#define ROL_VEC_16(x)\t_mm256_shuffle_epi8(x,_mm256_set_epi8(13,12,15,14,9,8,11,10,5,4,7,6,1,0,3,2,13,12,15,14,9,8,11,10,5,4,7,6,1,0,3,2))\n\n\n\n#define WRITEU_VEC(op, d, v0, v1, v2, v3)\t\t\t\t\t\t\\\n    STOREU_VEC(op + (d + 0*4), _mm256_permute2x128_si256(v0, v1, 0x20));\t\\\n    STOREU_VEC(op + (d + 8*4), _mm256_permute2x128_si256(v2, v3, 0x20));\t\\\n    STOREU_VEC(op + (d +16*4), _mm256_permute2x128_si256(v0, v1, 0x31));\t\\\n    STOREU_VEC(op + (d +24*4), _mm256_permute2x128_si256(v2, v3, 0x31));\n\n#define WRITE_VEC(op, d, v0, v1, v2, v3)\t\t\t\t\t\t\\\n    STORE_VEC(op + (d + 0*4), _mm256_permute2x128_si256(v0, v1, 0x20));\t\\\n    STORE_VEC(op + (d + 8*4), _mm256_permute2x128_si256(v2, v3, 0x20));\t\\\n    STORE_VEC(op + (d +16*4), _mm256_permute2x128_si256(v0, v1, 0x31));\t\\\n    STORE_VEC(op + (d +24*4), _mm256_permute2x128_si256(v2, v3, 0x31));\n\n#define SZ_VEC (32)\n\n#define RANSTREAM_NCHUNKS (2)\n// leads to a BUFSZ of 512\n\n\n#elif defined(NTL_HAVE_SSSE3)\n\ntypedef __m128i ivec_t;\n\n#define DELTA\t_mm_set_epi32(0,0,0,1)\n#define START   _mm_setzero_si128()\n#define NONCE(nonce) _mm_set_epi64x(nonce,0)\n\n#define STOREU_VEC(m,r)\t_mm_storeu_si128((__m128i*)(m), r)\n#define STORE_VEC(m,r)\t_mm_store_si128((__m128i*)(m), r)\n\n#define LOAD_VEC(r,m) r = _mm_load_si128((const __m128i *)(m))\n#define LOADU_VEC(r,m) r = _mm_loadu_si128((const __m128i *)(m))\n\n#define LOADU_VEC_128(r, m) r = _mm_loadu_si128((const __m128i*)(m))\n\n#define ADD_VEC_32(a,b)\t_mm_add_epi32(a, b)\n#define ADD_VEC_64(a,b)\t_mm_add_epi64(a, b)\n#define XOR_VEC(a,b)\t_mm_xor_si128(a, b)\n\n\n#define ROR_VEC_V1(x)\t_mm_shuffle_epi32(x,_MM_SHUFFLE(0,3,2,1))\n#define ROR_VEC_V2(x)\t_mm_shuffle_epi32(x,_MM_SHUFFLE(1,0,3,2))\n#define ROR_VEC_V3(x)\t_mm_shuffle_epi32(x,_MM_SHUFFLE(2,1,0,3))\n#define ROL_VEC_7(x)\tXOR_VEC(_mm_slli_epi32(x, 7), _mm_srli_epi32(x,25))\n#define ROL_VEC_12(x)\tXOR_VEC(_mm_slli_epi32(x,12), _mm_srli_epi32(x,20))\n\n#define ROL_VEC_8(x)\t_mm_shuffle_epi8(x,_mm_set_epi8(14,13,12,15,10,9,8,11,6,5,4,7,2,1,0,3))\n\n\n#define ROL_VEC_16(x)\t_mm_shuffle_epi8(x,_mm_set_epi8(13,12,15,14,9,8,11,10,5,4,7,6,1,0,3,2))\n\n\n#define WRITEU_VEC(op, d, v0, v1, v2, v3)\t\\\n    STOREU_VEC(op + (d + 0*4), v0);\t\\\n    STOREU_VEC(op + (d + 4*4), v1);\t\\\n    STOREU_VEC(op + (d + 8*4), v2);\t\\\n    STOREU_VEC(op + (d +12*4), v3);\n\n#define WRITE_VEC(op, d, v0, v1, v2, v3)\t\\\n    STORE_VEC(op + (d + 0*4), v0);\t\\\n    STORE_VEC(op + (d + 4*4), v1);\t\\\n    STORE_VEC(op + (d + 8*4), v2);\t\\\n    STORE_VEC(op + (d +12*4), v3);\n\n#define SZ_VEC (16)\n\n#define RANSTREAM_NCHUNKS (4)\n// leads to a BUFSZ of 512\n\n#else\n\n#error \"unsupported architecture\"\n\n#endif\n\n\n#define DQROUND_VECTORS_VEC(a,b,c,d)\t\t\t\t\\\n    a = ADD_VEC_32(a,b); d = XOR_VEC(d,a); d = ROL_VEC_16(d);\t\\\n    c = ADD_VEC_32(c,d); b = XOR_VEC(b,c); b = ROL_VEC_12(b);\t\\\n    a = ADD_VEC_32(a,b); d = XOR_VEC(d,a); d = ROL_VEC_8(d);\t\\\n    c = ADD_VEC_32(c,d); b = XOR_VEC(b,c); b = ROL_VEC_7(b);\t\\\n    b = ROR_VEC_V1(b); c = ROR_VEC_V2(c); d = ROR_VEC_V3(d);\t\\\n    a = ADD_VEC_32(a,b); d = XOR_VEC(d,a); d = ROL_VEC_16(d);\t\\\n    c = ADD_VEC_32(c,d); b = XOR_VEC(b,c); b = ROL_VEC_12(b);\t\\\n    a = ADD_VEC_32(a,b); d = XOR_VEC(d,a); d = ROL_VEC_8(d);\t\\\n    c = ADD_VEC_32(c,d); b = XOR_VEC(b,c); b = ROL_VEC_7(b);\t\\\n    b = ROR_VEC_V3(b); c = ROR_VEC_V2(c); d = ROR_VEC_V1(d);\n\n\n\n#define RANSTREAM_STATESZ (4*SZ_VEC)\n\n#define RANSTREAM_CHUNKSZ (2*RANSTREAM_STATESZ)\n#define RANSTREAM_BUFSZ   (RANSTREAM_NCHUNKS*RANSTREAM_CHUNKSZ)\n\n\nstruct RandomStream_impl {\n\n   AlignedArray<unsigned char> state_store;\n   AlignedArray<unsigned char> buf_store;\n   long chunk_count;\n\n   void allocate_space() \n   {\n      state_store.SetLength(RANSTREAM_STATESZ);\n      buf_store.SetLength(RANSTREAM_BUFSZ);\n   }\n\n\n   explicit\n   RandomStream_impl(const unsigned char *key) \n   {\n      allocate_space();\n\n      unsigned char *state = state_store.elts();\n\n      unsigned int chacha_const[] = {\n\t      0x61707865,0x3320646E,0x79622D32,0x6B206574\n      };\n\n\n      ivec_t d0, d1, d2, d3;\n      LOADU_VEC_128(d0, chacha_const);\n      LOADU_VEC_128(d1, key);\n      LOADU_VEC_128(d2, key+16);\n\n      d3 = START;\n\n\n      STORE_VEC(state + 0*SZ_VEC, d0); \n      STORE_VEC(state + 1*SZ_VEC, d1); \n      STORE_VEC(state + 2*SZ_VEC, d2); \n      STORE_VEC(state + 3*SZ_VEC, d3); \n\n      chunk_count = 0;\n   }\n\n   RandomStream_impl(const RandomStream_impl& other) \n   {\n      allocate_space();\n      *this = other;\n   }\n\n   RandomStream_impl& operator=(const RandomStream_impl& other) \n   {\n      std::memcpy(state_store.elts(), other.state_store.elts(), RANSTREAM_STATESZ);\n      std::memcpy(buf_store.elts(), other.buf_store.elts(), RANSTREAM_BUFSZ);\n      chunk_count = other.chunk_count;\n      return *this;\n   }\n\n   const unsigned char *\n   get_buf() const\n   {\n      return buf_store.elts(); \n   }\n\n   long\n   get_buf_len() const\n   {\n      return RANSTREAM_BUFSZ;\n   }\n\n   // bytes are generated in chunks of RANSTREAM_BUFSZ bytes, except that\n   // initially, we may generate a few chunks of RANSTREAM_CHUNKSZ\n   // bytes.  This optimizes a bit for short bursts following a reset.\n\n   long\n   get_bytes(unsigned char *NTL_RESTRICT res, \n             long n, long pos)\n   {\n      if (n < 0) LogicError(\"RandomStream::get: bad args\");\n      if (n == 0) return pos;\n\n      unsigned char *NTL_RESTRICT buf = buf_store.elts();\n\n      if (n <= RANSTREAM_BUFSZ-pos) {\n\t std::memcpy(&res[0], &buf[pos], n);\n\t pos += n;\n\t return pos;\n      }\n\n      unsigned char *NTL_RESTRICT state = state_store.elts();\n\n      ivec_t d0, d1, d2, d3;\n      LOAD_VEC(d0, state + 0*SZ_VEC);\n      LOAD_VEC(d1, state + 1*SZ_VEC);\n      LOAD_VEC(d2, state + 2*SZ_VEC);\n      LOAD_VEC(d3, state + 3*SZ_VEC);\n\n\n      // read remainder of buffer\n      std::memcpy(&res[0], &buf[pos], RANSTREAM_BUFSZ-pos);\n      n -= RANSTREAM_BUFSZ-pos;\n      res += RANSTREAM_BUFSZ-pos;\n      pos = RANSTREAM_BUFSZ;\n\n      long i = 0;\n      for (;  i <= n-RANSTREAM_BUFSZ; i += RANSTREAM_BUFSZ) {\n\n         chunk_count |= RANSTREAM_NCHUNKS;  // disable small buffer strategy\n\n\t for (long j = 0; j < RANSTREAM_NCHUNKS; j++) {\n\t    ivec_t v0=d0, v1=d1, v2=d2, v3=d3;\n\t    ivec_t v4=d0, v5=d1, v6=d2, v7=ADD_VEC_64(d3, DELTA);\n\n\t    for (long k = 0; k < CHACHA_RNDS/2; k++) {\n\t\t    DQROUND_VECTORS_VEC(v0,v1,v2,v3)\n\t\t    DQROUND_VECTORS_VEC(v4,v5,v6,v7)\n\t    }\n\n\t    WRITEU_VEC(res+i+j*(8*SZ_VEC), 0, ADD_VEC_32(v0,d0), ADD_VEC_32(v1,d1), ADD_VEC_32(v2,d2), ADD_VEC_32(v3,d3))\n\t    d3 = ADD_VEC_64(d3, DELTA);\n\t    WRITEU_VEC(res+i+j*(8*SZ_VEC), 4*SZ_VEC, ADD_VEC_32(v4,d0), ADD_VEC_32(v5,d1), ADD_VEC_32(v6,d2), ADD_VEC_32(v7,d3))\n\t    d3 = ADD_VEC_64(d3, DELTA);\n\n\t }\n\n      }\n\n      if (i < n) {\n\n         long nchunks;\n\n         if (chunk_count < RANSTREAM_NCHUNKS) {\n            nchunks = long(cast_unsigned((n-i)+RANSTREAM_CHUNKSZ-1)/RANSTREAM_CHUNKSZ);\n            chunk_count += nchunks;\n         }\n         else\n            nchunks = RANSTREAM_NCHUNKS;\n\n         long pos_offset = RANSTREAM_BUFSZ - nchunks*RANSTREAM_CHUNKSZ;\n         buf += pos_offset;\n\n\t for (long j = 0; j < nchunks; j++) {\n\t    ivec_t v0=d0, v1=d1, v2=d2, v3=d3;\n\t    ivec_t v4=d0, v5=d1, v6=d2, v7=ADD_VEC_64(d3, DELTA);\n\n\t    for (long k = 0; k < CHACHA_RNDS/2; k++) {\n               DQROUND_VECTORS_VEC(v0,v1,v2,v3)\n               DQROUND_VECTORS_VEC(v4,v5,v6,v7)\n\t    }\n\n\t    WRITE_VEC(buf+j*(8*SZ_VEC), 0, ADD_VEC_32(v0,d0), ADD_VEC_32(v1,d1), ADD_VEC_32(v2,d2), ADD_VEC_32(v3,d3))\n\t    d3 = ADD_VEC_64(d3, DELTA);\n\t    WRITE_VEC(buf+j*(8*SZ_VEC), 4*SZ_VEC, ADD_VEC_32(v4,d0), ADD_VEC_32(v5,d1), ADD_VEC_32(v6,d2), ADD_VEC_32(v7,d3))\n\t    d3 = ADD_VEC_64(d3, DELTA);\n\t }\n\n\t pos = n-i+pos_offset;\n\t std::memcpy(&res[i], &buf[0], n-i);\n      }\n\n      STORE_VEC(state + 3*SZ_VEC, d3); \n\n      return pos;\n   }\n\n   void set_nonce(unsigned long nonce)\n   {\n      unsigned char *state = state_store.elts();\n      ivec_t d3;\n      d3 = NONCE(nonce);\n      STORE_VEC(state + 3*SZ_VEC, d3);\n      chunk_count = 0;\n   }\n\n};\n\n\n#else\n\nstruct RandomStream_impl {\n   _ntl_uint32 state[16];\n   unsigned char buf[64];\n\n   explicit\n   RandomStream_impl(const unsigned char *key)\n   {\n      salsa20_init(state, key);\n   }\n\n   const unsigned char *\n   get_buf() const\n   {\n      return &buf[0];\n   }\n\n   long\n   get_buf_len() const\n   {\n      return 64;\n   }\n\n   long get_bytes(unsigned char *res, long n, long pos) \n   {\n      if (n < 0) LogicError(\"RandomStream::get: bad args\");\n\n      long i, j;\n\n      if (n <= 64-pos) {\n\t for (i = 0; i < n; i++) res[i] = buf[pos+i];\n\t pos += n;\n\t return pos;\n      }\n\n      // read remainder of buffer\n      for (i = 0; i < 64-pos; i++) res[i] = buf[pos+i];\n      n -= 64-pos;\n      res += 64-pos;\n      pos = 64;\n\n      _ntl_uint32 wdata[16];\n\n      // read 64-byte chunks\n      for (i = 0; i <= n-64; i += 64) {\n\t salsa20_apply(state, wdata);\n\t for (j = 0; j < 16; j++)\n\t    FROMLE(res + i + 4*j, wdata[j]);\n      }\n\n      if (i < n) { \n\t salsa20_apply(state, wdata);\n\n\t for (j = 0; j < 16; j++)\n\t    FROMLE(buf + 4*j, wdata[j]);\n\n\t pos = n-i;\n\t for (j = 0; j < pos; j++)\n\t    res[i+j] = buf[j];\n      }\n\n      return pos;\n   }\n\n   void set_nonce(unsigned long nonce)\n   {\n      _ntl_uint32 nonce0, nonce1;\n\n      nonce0 = nonce;\n      nonce0 = INT32MASK(nonce0);\n\n      nonce1 = 0;\n\n#if (NTL_BITS_PER_LONG > 32)\n      nonce1 = nonce >> 32;\n      nonce1 = INT32MASK(nonce1);\n#endif\n\n      state[12] = 0;\n      state[13] = 0;\n      state[14] = nonce0;\n      state[15] = nonce1;\n   }\n};\n\n\n#endif\n\n\n\n// Boilerplate PIMPL code\n\nRandomStream_impl *\nRandomStream_impl_build(const unsigned char *key)\n{\n   UniquePtr<RandomStream_impl> p;\n   p.make(key);\n   return p.release();\n}\n\nRandomStream_impl *\nRandomStream_impl_build(const RandomStream_impl& other)\n{\n   UniquePtr<RandomStream_impl> p;\n   p.make(other);\n   return p.release();\n}\n\nvoid\nRandomStream_impl_copy(RandomStream_impl& x, const RandomStream_impl& y)\n{\n   x = y;\n}\n\nvoid\nRandomStream_impl_delete(RandomStream_impl* p)\n{\n   delete p;\n}\n\nconst unsigned char *\nRandomStream_impl_get_buf(const RandomStream_impl& x)\n{\n   return x.get_buf();\n}\n\nlong\nRandomStream_impl_get_buf_len(const RandomStream_impl& x)\n{\n   return x.get_buf_len();\n}\n\nlong\nRandomStream_impl_get_bytes(RandomStream_impl& impl, \n   unsigned char *res, long n, long pos)\n{\n   return impl.get_bytes(res, n, pos);\n}\n\n\nvoid \nRandomStream_impl_set_nonce(RandomStream_impl& impl, unsigned long nonce)\n{\n   impl.set_nonce(nonce);\n}\n\n\n\n\n\nNTL_TLS_GLOBAL_DECL(UniquePtr<RandomStream>,  CurrentRandomStream);\n\n\nvoid SetSeed(const RandomStream& s)\n{\n   NTL_TLS_GLOBAL_ACCESS(CurrentRandomStream);\n\n   if (!CurrentRandomStream)\n      CurrentRandomStream.make(s);\n   else\n      *CurrentRandomStream = s;\n}\n\n\nvoid SetSeed(const unsigned char *data, long dlen)\n{\n   if (dlen < 0) LogicError(\"SetSeed: bad args\");\n\n   Vec<unsigned char> key;\n   key.SetLength(NTL_PRG_KEYLEN);\n   DeriveKey(key.elts(), NTL_PRG_KEYLEN, data, dlen);\n \n   SetSeed(RandomStream(key.elts()));\n}\n\nvoid SetSeed(const ZZ& seed)\n{\n   long nb = NumBytes(seed);\n\n   Vec<unsigned char> buf;\n   buf.SetLength(nb);\n\n   BytesFromZZ(buf.elts(), seed, nb);\n\n   SetSeed(buf.elts(), nb);\n}\n\n\nstatic\nvoid InitRandomStream()\n{\n   const std::string& id = UniqueID();\n   SetSeed((const unsigned char *) id.c_str(), id.length());\n}\n\nstatic inline\nRandomStream& LocalGetCurrentRandomStream()\n{\n   NTL_TLS_GLOBAL_ACCESS(CurrentRandomStream);\n\n   if (!CurrentRandomStream) InitRandomStream();\n   return *CurrentRandomStream;\n}\n\nRandomStream& GetCurrentRandomStream()\n{\n   return LocalGetCurrentRandomStream();\n}\n\n\n\n\n\n\n\nstatic inline\nunsigned long WordFromBytes(const unsigned char *buf, long n)\n{\n   unsigned long res = 0;\n   long i;\n\n   for (i = n-1; i >= 0; i--)\n      res = (res << 8) | buf[i];\n\n   return res;\n}\n\n\nunsigned long RandomWord()\n{\n   RandomStream& stream = LocalGetCurrentRandomStream();\n   unsigned char buf[NTL_BITS_PER_LONG/8];\n\n   stream.get(buf, NTL_BITS_PER_LONG/8);\n   return WordFromBytes(buf, NTL_BITS_PER_LONG/8);\n}\n\n\nvoid VectorRandomWord(long k, unsigned long* x)\n{\n   RandomStream& stream = LocalGetCurrentRandomStream();\n   unsigned char buf[NTL_BITS_PER_LONG/8];\n\n   for (long i = 0; i < k; i++) {\n      stream.get(buf, NTL_BITS_PER_LONG/8);\n      x[i] = WordFromBytes(buf, NTL_BITS_PER_LONG/8);\n   }\n}\n\nlong RandomBits_long(long l)\n{\n   if (l <= 0) return 0;\n   if (l >= NTL_BITS_PER_LONG) \n      ResourceError(\"RandomBits: length too big\");\n\n   RandomStream& stream = LocalGetCurrentRandomStream();\n   unsigned char buf[NTL_BITS_PER_LONG/8];\n   long nb = (l+7)/8;\n   stream.get(buf, nb);\n\n   return long(WordFromBytes(buf, nb) & ((1UL << l)-1UL)); \n}\n\nunsigned long RandomBits_ulong(long l)\n{\n   if (l <= 0) return 0;\n   if (l > NTL_BITS_PER_LONG) \n      ResourceError(\"RandomBits: length too big\");\n\n   RandomStream& stream = LocalGetCurrentRandomStream();\n   unsigned char buf[NTL_BITS_PER_LONG/8];\n   long nb = (l+7)/8;\n   stream.get(buf, nb);\n   unsigned long res = WordFromBytes(buf, nb);\n   if (l < NTL_BITS_PER_LONG)\n      res = res & ((1UL << l)-1UL);\n   return res;\n}\n\nlong RandomLen_long(long l)\n{\n   if (l <= 0) return 0;\n   if (l == 1) return 1;\n   if (l >= NTL_BITS_PER_LONG) \n      ResourceError(\"RandomLen: length too big\");\n\n   RandomStream& stream = LocalGetCurrentRandomStream();\n   unsigned char buf[NTL_BITS_PER_LONG/8];\n   long nb = ((l-1)+7)/8;\n   stream.get(buf, nb);\n   unsigned long res = WordFromBytes(buf, nb);\n   unsigned long mask = (1UL << (l-1)) - 1UL;\n   return long((res & mask) | (mask+1UL)); \n}\n\n\nlong RandomBnd(long bnd)\n{\n   if (bnd <= 1) return 0;\n\n   RandomStream& stream = LocalGetCurrentRandomStream();\n   unsigned char buf[NTL_BITS_PER_LONG/8];\n   long l = NumBits(bnd-1);\n   long nb = (l+7)/8;\n\n   long tmp;\n   do {\n      stream.get(buf, nb);\n      tmp = long(WordFromBytes(buf, nb) & ((1UL << l)-1UL));\n   } while (tmp >= bnd);\n\n   return tmp;\n}\n\n\n\nvoid RandomBits(ZZ& x, long l)\n{\n   if (l <= 0) {\n      x = 0;\n      return;\n   }\n\n   if (NTL_OVERFLOW(l, 1, 0))\n      ResourceError(\"RandomBits: length too big\");\n\n   RandomStream& stream = LocalGetCurrentRandomStream();\n\n   long nb = (l+7)/8;\n   unsigned long mask = (1UL << (8 - nb*8 + l)) - 1UL;\n\n   NTL_TLS_LOCAL(Vec<unsigned char>, buf_mem);\n   Vec<unsigned char>::Watcher watch_buf_mem(buf_mem);\n\n   buf_mem.SetLength(nb);\n   unsigned char *buf = buf_mem.elts();\n\n   x.SetSize((l + NTL_ZZ_NBITS - 1)/NTL_ZZ_NBITS);\n   // pre-allocate to ensure strong ES\n\n   stream.get(buf, nb);\n   buf[nb-1] &= mask;\n   \n   ZZFromBytes(x, buf, nb);\n}\n\n\nvoid RandomLen(ZZ& x, long l)\n{\n   if (l <= 0) {\n      x = 0;\n      return;\n   }\n\n   if (l == 1) {\n      x = 1;\n      return;\n   }\n\n   if (NTL_OVERFLOW(l, 1, 0))\n      ResourceError(\"RandomLen: length too big\");\n\n   RandomStream& stream = LocalGetCurrentRandomStream();\n\n   long nb = (l+7)/8;\n   unsigned long mask = (1UL << (8 - nb*8 + l)) - 1UL;\n\n   NTL_TLS_LOCAL(Vec<unsigned char>, buf_mem);\n   Vec<unsigned char>::Watcher watch_buf_mem(buf_mem);\n\n   buf_mem.SetLength(nb);\n   unsigned char *buf = buf_mem.elts();\n\n   x.SetSize((l + NTL_ZZ_NBITS - 1)/NTL_ZZ_NBITS);\n   // pre-allocate to ensure strong ES\n\n   stream.get(buf, nb);\n   buf[nb-1] &= mask;\n   buf[nb-1] |= ((mask >> 1) + 1UL);\n   \n   ZZFromBytes(x, buf, nb);\n}\n\n\n\n\n\n/**********************************************************\n\nThe following implementation of RandomBnd is designed\nfor speed.  It certainly is not resilient against a\ntiming side-channel attack (but then again, none of these\nPRG routines are designed to be).\n\nThe naive strategy generates random candidates of the right \nbit length until the candidate < bnd.\nThe idea in this implementation is to generate the high\norder two bytes of the candidate first, and compare this\nto the high order two bytes of tmp.  We can discard the\ncandidate if this is already too large.\n\n***********************************************************/\n\nvoid RandomBnd(ZZ& x, const ZZ& bnd)\n{\n   if (bnd <= 1) {\n      x = 0;\n      return;\n   }\n\n   RandomStream& stream = LocalGetCurrentRandomStream();\n\n   long l = NumBits(bnd);\n   long nb = (l+7)/8;\n\n   if (nb <= 3) {\n      long lbnd = conv<long>(bnd);\n      unsigned char lbuf[3];\n      long ltmp;\n      \n      x.SetSize((l + NTL_ZZ_NBITS - 1)/NTL_ZZ_NBITS);\n      // pre-allocate to ensure strong ES\n      do {\n         stream.get(lbuf, nb);\n         ltmp = long(WordFromBytes(lbuf, nb) & ((1UL << l)-1UL));\n      } while (ltmp >= lbnd);\n\n     conv(x, ltmp);\n     return;\n   }\n\n   // deal with possible alias\n   NTL_ZZRegister(tmp_store);\n   const ZZ& bnd_ref = ((&x == &bnd) ? (tmp_store = bnd) : bnd); \n\n\n   NTL_ZZRegister(hbnd);\n   RightShift(hbnd, bnd_ref, (nb-2)*8);\n   long lhbnd = conv<long>(hbnd);\n\n   unsigned long mask = (1UL << (16 - nb*8 + l)) - 1UL;\n\n   NTL_TLS_LOCAL(Vec<unsigned char>, buf_mem);\n   Vec<unsigned char>::Watcher watch_buf_mem(buf_mem);\n   buf_mem.SetLength(nb);\n   unsigned char *buf = buf_mem.elts();\n\n   unsigned char hbuf[2];\n\n   x.SetSize((l + NTL_ZZ_NBITS - 1)/NTL_ZZ_NBITS);\n   // pre-allocate to ensure strong ES\n   for (;;) {\n      stream.get(hbuf, 2);\n      long hpart = long(WordFromBytes(hbuf, 2) & mask);\n\n      if (hpart > lhbnd) continue;\n\n      stream.get(buf, nb-2);\n      buf[nb-2] = ((unsigned long) hpart);\n      buf[nb-1] = ((unsigned long) hpart) >> 8; \n\n      ZZFromBytes(x, buf, nb);\n      if (hpart < lhbnd || x < bnd_ref) break;\n   }\n}\n\n\n\n\n// More prime generation stuff...\n\nstatic\ndouble Log2(double x)\n{\n   static const double log2 = log(2.0); // GLOBAL (relies on C++11 thread-safe init)\n   return log(x)/log2;\n}\n\n// Define p(k,t) to be the conditional probability that a random, odd, k-bit \n// number is composite, given that it passes t iterations of the \n// Miller-Rabin test.\n// If this routine returns a non-zero value, then\n//    p(k,t) <= 2^{-n}.\n// This basically encodes the estimates of Damgard, Landrock, and Pomerance;\n// it uses floating point arithmetic, but is coded in such a way\n// that its results should be correct, assuming that the log function\n// is computed with reasonable precision.\n// \n// It is assumed that k >= 3 and t >= 1; if this does not hold,\n// then 0 is returned.\n\nstatic\nlong ErrBoundTest(long kk, long tt, long nn)\n\n{\n   const double fudge = (1.0 + 1024.0/NTL_FDOUBLE_PRECISION);\n   const double log2_3 = Log2(3.0);\n   const double log2_7 = Log2(7.0);\n   const double log2_20 = Log2(20.0);\n\n   double k = kk;\n   double t = tt;\n   double n = nn;\n\n   if (k < 3 || t < 1) return 0;\n   if (n < 1) return 1;\n\n   // the following test is largely academic\n   if (9*t > NTL_FDOUBLE_PRECISION) LogicError(\"ErrBoundTest: t too big\");\n\n   double log2_k = Log2(k);\n\n   if ((n + log2_k)*fudge <= 2*t)\n      return 1;\n\n   if ((2*log2_k + 4.0 + n)*fudge <= 2*sqrt(k))\n      return 2;\n\n   if ((t == 2 && k >= 88) || (3 <= t && 9*t <= k && k >= 21)) {\n      if ((1.5*log2_k + t + 4.0 + n)*fudge <= 0.5*Log2(t) + 2*(sqrt(t*k)))\n         return 3;\n   }\n\n   if (k <= 9*t && 4*t <= k && k >= 21) {\n      if ( ((log2_3 + log2_7 + log2_k + n)*fudge <= log2_20 + 5*t)  &&\n           ((log2_3 + (15.0/4.0)*log2_k + n)*fudge <= log2_7 + k/2 + 2*t) &&\n           ((2*log2_3 + 2 + log2_k + n)*fudge <= k/4 + 3*t) )\n         return 4; \n   }\n\n   if (4*t >= k && k >= 21) {\n      if (((15.0/4.0)*log2_k + n)*fudge <= log2_7 + k/2 + 2*t)\n         return 5;\n   }\n\n   return 0;\n}\n\n\nvoid GenPrime(ZZ& n, long k, long err)\n{\n   if (k <= 1) LogicError(\"GenPrime: bad length\");\n\n   if (k > (1L << 20)) ResourceError(\"GenPrime: length too large\");\n\n   if (err < 1) err = 1;\n   if (err > 512) err = 512;\n\n   if (k == 2) {\n      if (RandomBnd(2))\n         n = 3;\n      else\n         n = 2;\n\n      return;\n   }\n\n\n   long t;\n\n   t = 1;\n   while (!ErrBoundTest(k, t, err))\n      t++;\n\n   RandomPrime(n, k, t);\n}\n\n\nlong GenPrime_long(long k, long err)\n{\n   if (k <= 1) LogicError(\"GenPrime: bad length\");\n\n   if (k >= NTL_BITS_PER_LONG) ResourceError(\"GenPrime: length too large\");\n\n   if (err < 1) err = 1;\n   if (err > 512) err = 512;\n\n   if (k == 2) {\n      if (RandomBnd(2))\n         return 3;\n      else\n         return 2;\n   }\n\n   long t;\n\n   t = 1;\n   while (!ErrBoundTest(k, t, err))\n      t++;\n\n   return RandomPrime_long(k, t);\n}\n\nvoid MultiThreadedGenGermainPrime(ZZ& n, long k, long err)\n{\n   long nt = AvailableThreads();\n\n\n   long prime_bnd = ComputePrimeBound(k);\n\n   if (NumBits(prime_bnd) >= k/2)\n      prime_bnd = (1L << (k/2-1));\n\n   ZZ two;\n   two = 2;\n\n   const long LOCAL_ITER_BOUND = 8;\n   // since resetting the PRG comes at a certain cost,\n   // we perform a few iterations with each reset to\n   // amortize the reset cost. \n\n   unsigned long initial_counter = 0;\n   ZZ seed;\n   RandomBits(seed, 256);\n\n\n   ZZ overflow_counter;\n\n   for (;;) {\n\n      AtomicLowWaterMark low_water_mark(-1UL);\n      AtomicCounter counter(initial_counter);\n\n      Vec< UniquePtr<ZZ> > result(INIT_SIZE, nt);\n      Vec<unsigned long> result_ctr(INIT_SIZE, nt, -1UL);\n\n      NTL_EXEC_INDEX(nt, index)\n\n         RandomStreamPush push;\n\n\t SetSeed(seed);\n\t RandomStream& stream = GetCurrentRandomStream();\n\n\t ZZ cand, n1;\n         PrimeSeq s;\n\n\t while (low_water_mark == -1UL) {\n\n\t    unsigned long local_ctr = counter.inc();\n            if (local_ctr >> (NTL_BITS_PER_NONCE-1)) {\n               // counter overflow...rather academic\n               break;\n            }\n\n\t    stream.set_nonce(local_ctr);\n\t    \n\t    for (long iter = 0; iter < LOCAL_ITER_BOUND && \n\t\t\t\tlocal_ctr <= low_water_mark; iter++) {\n\n\n\t       RandomLen(cand, k);\n\t       if (!IsOdd(cand)) add(cand, cand, 1);\n\n\t       s.reset(3);\n\t       long p;\n\n\t       long sieve_passed = 1;\n\n\t       p = s.next();\n\t       while (p && p < prime_bnd) {\n\t\t  long r = rem(cand, p);\n\n\t\t  if (r == 0) {\n\t\t     sieve_passed = 0;\n\t\t     break;\n\t\t  }\n\n\t\t  // test if 2*r + 1 = 0 (mod p)\n\t\t  if (r == p-r-1) {\n\t\t     sieve_passed = 0;\n\t\t     break;\n\t\t  }\n\n\t\t  p = s.next();\n\t       }\n\n               if (!sieve_passed) continue;\n\n\n               if (MillerWitness(cand, two)) continue;\n\n\t       // n1 = 2*cand+1\n\t       mul(n1, cand, 2);\n\t       add(n1, n1, 1);\n\n\n               if (MillerWitness(n1, two)) continue;\n\n\t       result[index].make(cand);\n\t       result_ctr[index] = local_ctr;\n\t       low_water_mark.UpdateMin(local_ctr);\n\t       break;\n            }\n         }\n\n      NTL_EXEC_INDEX_END\n\n      // find index of low_water_mark\n\n      unsigned long low_water_mark1 = low_water_mark;\n      long low_water_index = -1;\n\n      for (long index = 0; index < nt; index++) {\n\t if (result_ctr[index] == low_water_mark1) {\n\t    low_water_index = index;\n\t    break;\n\t }\n      }\n\n      if (low_water_index == -1) {\n         // counter overflow...rather academic\n         overflow_counter++;\n         initial_counter = 0;\n         RandomBits(seed, 256);\n         continue;\n      }\n\n      ZZ N;\n      N = *result[low_water_index];\n\n      ZZ iter = ((overflow_counter << (NTL_BITS_PER_NONCE-1)) +\n                 conv<ZZ>(low_water_mark1) + 1)*LOCAL_ITER_BOUND;\n\n      // now do t M-R iterations...just to make sure\n \n      // First compute the appropriate number of M-R iterations, t\n      // The following computes t such that \n      //       p(k,t)*8/k <= 2^{-err}/(5*iter^{1.25})\n      // which suffices to get an overall error probability of 2^{-err}.\n      // Note that this method has the advantage of not requiring \n      // any assumptions on the density of Germain primes.\n\n      long err1 = max(1, err + 7 + (5*NumBits(iter) + 3)/4 - NumBits(k));\n      long t;\n      t = 1;\n      while (!ErrBoundTest(k, t, err1))\n         t++;\n\n      Vec<ZZ> W(INIT_SIZE, t);\n\n      for (long i = 0; i < t; i++) {\n         do { \n            RandomBnd(W[i], N);\n         } while (W[i] == 0);\n      }\n\n      AtomicBool tests_pass(true);\n\n      NTL_EXEC_RANGE(t, first, last)\n\n         for (long i = first; i < last && tests_pass; i++) {\n            if (MillerWitness(N, W[i])) tests_pass = false;\n         }\n\n      NTL_EXEC_RANGE_END\n\n      if (tests_pass) {\n         n = N;\n         return;\n      }\n\n      // very unlikey to get here\n      initial_counter = low_water_mark1 + 1;\n   }\n}\n\nvoid GenGermainPrime(ZZ& n, long k, long err)\n{\n   if (k <= 1) LogicError(\"GenGermainPrime: bad length\");\n\n   if (k > (1L << 20)) ResourceError(\"GenGermainPrime: length too large\");\n\n   if (err < 1) err = 1;\n   if (err > 512) err = 512;\n\n   if (k == 2) {\n      if (RandomBnd(2))\n         n = 3;\n      else\n         n = 2;\n\n      return;\n   }\n\n   if (k >= 192) {\n      MultiThreadedGenGermainPrime(n, k, err);\n      return;\n   }\n\n\n   long prime_bnd = ComputePrimeBound(k);\n\n   if (NumBits(prime_bnd) >= k/2)\n      prime_bnd = (1L << (k/2-1));\n\n\n   ZZ two;\n   two = 2;\n\n   ZZ n1;\n\n   \n   PrimeSeq s;\n\n   ZZ iter;\n   iter = 0;\n\n\n   for (;;) {\n      iter++;\n\n      RandomLen(n, k);\n      if (!IsOdd(n)) add(n, n, 1);\n\n      s.reset(3);\n      long p;\n\n      long sieve_passed = 1;\n\n      p = s.next();\n      while (p && p < prime_bnd) {\n         long r = rem(n, p);\n\n         if (r == 0) {\n            sieve_passed = 0;\n            break;\n         }\n\n         // test if 2*r + 1 = 0 (mod p)\n         if (r == p-r-1) {\n            sieve_passed = 0;\n            break;\n         }\n\n         p = s.next();\n      }\n\n      if (!sieve_passed) continue;\n\n\n      if (MillerWitness(n, two)) continue;\n\n      // n1 = 2*n+1\n      mul(n1, n, 2);\n      add(n1, n1, 1);\n\n\n      if (MillerWitness(n1, two)) continue;\n\n      // now do t M-R iterations...just to make sure\n \n      // First compute the appropriate number of M-R iterations, t\n      // The following computes t such that \n      //       p(k,t)*8/k <= 2^{-err}/(5*iter^{1.25})\n      // which suffices to get an overall error probability of 2^{-err}.\n      // Note that this method has the advantage of not requiring \n      // any assumptions on the density of Germain primes.\n\n      long err1 = max(1, err + 7 + (5*NumBits(iter) + 3)/4 - NumBits(k));\n      long t;\n      t = 1;\n      while (!ErrBoundTest(k, t, err1))\n         t++;\n\n      ZZ W;\n      long MR_passed = 1;\n\n      long i;\n      for (i = 1; i <= t; i++) {\n         do {\n            RandomBnd(W, n);\n         } while (W == 0);\n         // W == 0 is not a useful candidate witness!\n\n         if (MillerWitness(n, W)) {\n            MR_passed = 0;\n            break;\n         }\n      }\n\n      if (MR_passed) break;\n   }\n}\n\nvoid OldGenGermainPrime(ZZ& n, long k, long err)\n{\n   if (k <= 1) LogicError(\"GenGermainPrime: bad length\");\n\n   if (k > (1L << 20)) ResourceError(\"GenGermainPrime: length too large\");\n\n   if (err < 1) err = 1;\n   if (err > 512) err = 512;\n\n   if (k == 2) {\n      if (RandomBnd(2))\n         n = 3;\n      else\n         n = 2;\n\n      return;\n   }\n\n\n   long prime_bnd = ComputePrimeBound(k);\n\n   if (NumBits(prime_bnd) >= k/2)\n      prime_bnd = (1L << (k/2-1));\n\n\n   ZZ two;\n   two = 2;\n\n   ZZ n1;\n\n   \n   PrimeSeq s;\n\n   ZZ iter;\n   iter = 0;\n\n\n   for (;;) {\n      iter++;\n\n      RandomLen(n, k);\n      if (!IsOdd(n)) add(n, n, 1);\n\n      s.reset(3);\n      long p;\n\n      long sieve_passed = 1;\n\n      p = s.next();\n      while (p && p < prime_bnd) {\n         long r = rem(n, p);\n\n         if (r == 0) {\n            sieve_passed = 0;\n            break;\n         }\n\n         // test if 2*r + 1 = 0 (mod p)\n         if (r == p-r-1) {\n            sieve_passed = 0;\n            break;\n         }\n\n         p = s.next();\n      }\n\n      if (!sieve_passed) continue;\n\n\n      if (MillerWitness(n, two)) continue;\n\n      // n1 = 2*n+1\n      mul(n1, n, 2);\n      add(n1, n1, 1);\n\n\n      if (MillerWitness(n1, two)) continue;\n\n      // now do t M-R iterations...just to make sure\n \n      // First compute the appropriate number of M-R iterations, t\n      // The following computes t such that \n      //       p(k,t)*8/k <= 2^{-err}/(5*iter^{1.25})\n      // which suffices to get an overall error probability of 2^{-err}.\n      // Note that this method has the advantage of not requiring \n      // any assumptions on the density of Germain primes.\n\n      long err1 = max(1, err + 7 + (5*NumBits(iter) + 3)/4 - NumBits(k));\n      long t;\n      t = 1;\n      while (!ErrBoundTest(k, t, err1))\n         t++;\n\n      ZZ W;\n      long MR_passed = 1;\n\n      long i;\n      for (i = 1; i <= t; i++) {\n         do {\n            RandomBnd(W, n);\n         } while (W == 0);\n         // W == 0 is not a useful candidate witness!\n\n         if (MillerWitness(n, W)) {\n            MR_passed = 0;\n            break;\n         }\n      }\n\n      if (MR_passed) break;\n   }\n}\n\nlong GenGermainPrime_long(long k, long err)\n{\n   if (k >= NTL_BITS_PER_LONG-1)\n      ResourceError(\"GenGermainPrime_long: length too long\");\n\n   ZZ n;\n   GenGermainPrime(n, k, err);\n   return to_long(n);\n}\n\n\nNTL_END_IMPL\n", "meta": {"hexsha": "60d5f8469c5f57fbce62d01624019c730945b722", "size": 70453, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/ntl-11.4.3/src/ZZ.cpp", "max_stars_repo_name": "fedlearnJDT/libfedlearn", "max_stars_repo_head_hexsha": "581dfeca7ba6c49c480b883a883001dce7922f76", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-07-20T01:54:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T07:56:04.000Z", "max_issues_repo_path": "libNTL/unix.d/src/ZZ.cpp", "max_issues_repo_name": "kalilearner/spot-on", "max_issues_repo_head_hexsha": "6f2d802c87a88e3001cb8238f65b5d7253bc6f49", "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": "libNTL/unix.d/src/ZZ.cpp", "max_forks_repo_name": "kalilearner/spot-on", "max_forks_repo_head_hexsha": "6f2d802c87a88e3001cb8238f65b5d7253bc6f49", "max_forks_repo_licenses": ["PostgreSQL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9868930593, "max_line_length": 137, "alphanum_fraction": 0.5558457411, "num_tokens": 23742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.2925942007574071}}
{"text": "/*\n * Copyright 2012, 2013 Matthew Harvey\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 GUARD_decimal_hpp_0809249049429432\n#define GUARD_decimal_hpp_0809249049429432\n\n/** @file\n */\n\n#include <boost/lexical_cast.hpp>\n#include <boost/numeric/conversion/cast.hpp>\n#include <algorithm>\n#include <cctype>\n#include <cstdlib>  // for abs\n#include <cmath>\n#include <istream>\n#include <locale>\n#include <memory>  // for allocator\n#include <ostream>\n#include <sstream>\n#include <string>\n#include <type_traits>\n#include <vector>\n\nnamespace jewel\n{\n\n/**\n * @brief A floating point decimal number class, with a somewhat limited\n * range, suited to use in accounting and financial applications.\n *\n * Each number is represented as an integer (of jewel::Decimal::int_type), and a\n * number of decimal places (of jewel::Decimal::places_type).\n *\n * The number of decimal places can be changed at runtime. As such this is a\n * floating rather than fixed point arithmetic type. However the range of\n * magnitudes is quite restricted compared to e.g. \\e double.\n *\n * There are two concepts of precision for this Decimal class. The\n * <em>total precision</em> of a Decimal is the total number of\n * decimal digits, to either the left or the right of the decimal point,\n * stored in the instance. The <em>fractional precision</em> is the number of\n * digits stored to the right of the decimal point, i.e. the number of\n * digits in the fractional part.\n *\n * The maximum total precision of any given Decimal is equal to the number\n * of decimal digits in the largest possible Decimal. This\n * number is implementation-dependent, and is the number returned by\n * Decimal::maximum_precision(). Regardless of any of the behaviour\n * outlined below, the total precision of a Decimal will never exceed this\n * level. Note we cannot end up with a number that has more than this many\n * digits in its whole part, even if all but one of these digits are zero.\n * This significantly limits the range of this Decimal class compared to\n * typical floating point implementations.\n *\n * A single leading zero to the left of the decimal point\n * does not count towards the total precision of the Decimal.\n *\n * When a Decimal is constructed from a string, all digits of\n * precision that are implied by that string are retained in the Decimal\n * that is thereby constructed - regardless of whether some of these digits\n * are trailing fractional zeroes. For example, \\c Decimal(\"0.2400\")\n * will create a Decimal with 4 digits of total precision, and 4 digits of\n * fractional precision. If a Decimal cannot be created that would hold the\n * number of digits of precision implied by string, then an exception is\n * thrown.\n *\n * Multiplication and division behave slightly differently to addition and\n * subtraction. Trailing fractional zeroes in the result of these operations\n * are always \"culled\", even if this\n * would reduce the fractional precision of the result below that of either of\n * the operands. However, as with addition and subtraction, only fractional\n * zeroes are culled, and never whole digits.\n *\n * Apart from the above requirements, Decimals will store as many digits of\n * precision as possible. So \"1/3\" will result in \"0.333....\" with as many\n * trailing '3's as are permitted by the implementation.\n *\n * @todo LOW PRIORITY\n * Multiplication and division throw exceptions in some cases where\n * they should be able to calculate an answer. I have documented these\n * behaviours in the API docs. I don't believe this is a \\e very serious\n * problem, as the behaviour is well documented and exceptions are thrown\n * rather than silent failure occurring. However, it is limiting\n * for certain use cases, and it makes for a messy API.\n * I should be able to get around this, and also\n * simplify my implementation of both division and multiplication, by\n * using boost::int32_t for int_type, while overflowing into boost::int64_t\n * within the implementation of these functions where required. The functions\n * will then only throw if the final value of m_intval cannot be fit into\n * boost::int32_t. The only problem then is that int_type is limited to\n * 32 bits. I'm not sure whether this is acceptable for e.g. an accounting\n * application. I think it is probably better to retain the current\n * \"messy\" situation until there's a clear need to reimplement things\n * in light of actual use cases.\n *\n * @todo LOW PRIORITY\n * Make it work as expected with standard library stream precision\n * manipulators and formatting. Create a function that takes a string\n * representation of a number, and the set of all the formatting flags\n * of an ostream (or a basic_ostream<>?), and use\n * those flags to format the string in accordance with those flags.\n * I should probably define this in a separate file. Note this is different\n * from the internationalization task which is separately noted.\n *\n * @todo MEDIUM PRIORITY\n * Internationalized output is working using the std::numpunct facilities.\n * But it doesn't support Boost.Locale. If the client uses Boost.Locale\n * instead of the standard library facilities, Decimal will\n * not do any formatting. Considering that\n * Boost.Locale \\e seems to be necessary to get things working on Windows\n * properly, do I want to provide support for Boost.Locale in\n * jewel::Decimal?\n *\n * @todo MEDIUM PRIORITY\n * Support internationalization of input.\n *\n * @todo LOW PRIORITY\n * Division now incorporates rounding but: (a) it is a bit inefficient;\n * and (b) it contains a \"hard-wired\" behaviour of rounding up at 5, while not\n * actually referring to the Decimal::s_rounding_threshold constant to achieve\n * this. This is a kind of code repetition and so is bad.\n */\nclass Decimal\n{\npublic:\n\n    /** The type of the underlying integer representation of the\n     * Decimal number.\n     */\n    typedef long long int_type;\n\n    /** The type of the integer representation of the number of\n     * decimal places (scale).\n     */\n    typedef unsigned char places_type;\n\n    // Output\n    template <typename charT, typename traits>\n    friend\n    std::basic_ostream<charT, traits>&\n    operator<<(std::basic_ostream<charT, traits>&, Decimal const&);\n\n    // Rounding\n    friend Decimal round\n    (   Decimal const& x,\n        Decimal::places_type decimal_places\n    );\n\n    /** Unary minus\n     *\n     * See separate documentation for this function.\n     */\n    friend Decimal operator-(Decimal const& d);\n\n    /** \n     * Initializes the Decimal to 0, with 0 decimal places.\n     *\n     * Exception safety: <em>nothrow guarantee</em>.\n     */\n    Decimal();\n\n    /**\n     * Constructs a Decimal with an underlying integer of\n     * p_intval and with p_places decimal places to the right\n     * of the spot.\n     *\n     * @exception DecimalRangeException thrown if p_places\n     * exceeds the value returned by Decimal::maximum_precision().\n     *\n     * Exception safety: <em>strong guarantee</em>.\n     */\n    Decimal(int_type m_intval, places_type p_places);\n\n    /** Constructs a Decimal from a string.\n     *\n     * @param str is the string representation of a Decimal number. Must\n     * be either a <em>std::string const&</em> or a\n     * <em>std::wstring const&</em>, or else compilation will fail.\n     *\n     * Currently str must be a non-empty series of digits\n     * between 0 and 9 inclusive, possibly preceded by a minus\n     * sign, possibly followed by a decimal point character, possibly\n     * followed by further digits between 0 and 9 inclusive. There must be\n     * at least one digit in the string. The spot character is\n     * determined by the current global \\e std::locale (whatever \\e std::locale\n     * is created by the default constructor for \\e std::locale). It could be\n     * be \".\", \",\" or some other character - whatever represents a\n     * decimal point in that locale.\n     *\n     * Assuming \".\" for the global locale's decimal point, the following are\n     * examples of accepted strings: \"10\", \"0.0012\", \"-1.3\", \".234\".\n     *\n     * Assuming a \".\" for the global locale's decimal point,\n     * the following are examples of non-accepted strings: \"10e2\",\n     * \"12312.234134341.23424\", \"1,000\".\n     *\n     * @exception DecimalFromStringException is thrown if:\\n\n     *   an empty string is passed to \\c str; or\\n\n     *   non-digit characters (other than '-' and the decimal point, at the\n     *   appropriate point) are included in the string.\n     * \n     * @exception DecimalRangeException is thrown if \\c str is otherwise\n     *   valid, but\n     *   the position of the decimal point implies a number of decimal places\n     *   greater than the value returned by Decimal::maximum_precision().\n     *\n     * @exception DecimalRangeException also thrown if the implied Decimal\n     *   number would be required to exceed the maximum of the underlying\n     *   integral representation.\n     *\n     * @exception std::bad_alloc may be thrown - but this is unlikely - since\n     * the implementation of this function involves the construction of a\n     * std::string.\n     *\n     * Trailing zeroes to the right of the decimal point in the passed string\n     * influence the number of digits of fractional precision stored in the\n     * resulting Decimal. So \\c Decimal(\"0.00\") is stored with two digits of\n     * fractional precision. However it is still the case that\n     * <tt> Decimal(\"0.00\") == Decimal(\"0\") </tt>.\n     * Note leading negative signs in front of \\c Decimal(\"0\") or its\n     * equivalents are \\e not stored.\n     *\n     * Exception safety: <em>strong guarantee</em>.\n     */\n    template <typename charT, typename traits, typename Alloc>\n    explicit Decimal(std::basic_string<charT, traits, Alloc> const& str);\n\n    /**\n     * Precondition: the string must be null-terminated.\n     *\n     * Behaviour re. exceptions is the same as for the constructor\n     * which takes a std::string.\n     */\n    explicit Decimal(char const* str);\n\n    /**\n     * Precondition: the string must be null-terminated.\n     * \n     * Behaviour re. exceptions is the same as for the constructor which\n     * takes a std::wstring.\n     */\n    explicit Decimal(wchar_t const* str);\n\n    Decimal(Decimal const&) = default;\n    Decimal(Decimal&&) = default;\n    Decimal& operator=(Decimal const&) = default;\n    Decimal& operator=(Decimal&&) = default;\n    ~Decimal() = default;\n\n    /**\n     * @exception DecimalAdditionException thrown if addition\n     * would cause overflow. If this occurs, the left hand operand\n     * will be unchanged from\n     * its original value (and the right hand operand, as it is passed by\n     * value, will also be unchanged).\n     *\n     * @exception DecimalRangeException thrown if fractional precision\n     * cannot be maintained at the same level as that of the more precise\n     * of the two numbers being\n     * added. This ensures that - unlike in unchecked floating point\n     * arithmetic - adding two non-zero Decimals is always yield a Decimal\n     * that is equal to neither of the original Decimals (or else will throw\n     * an exception). If this exception is thrown, the left hand operand will\n     * be unchanged from its original value (as will the right hand operand,\n     * since it is passed by value).\n     * \n     * Note trailing fractional zeroes are never \"rationalized away\" from the\n     * result. Stored fractional precision is always maintained at the level\n     * of the more precise of the operands, and if it cannot be, an exception\n     * is thrown.\n     *\n     * Exception safety: <em>strong guarantee</em>.\n     */    \n    Decimal& operator+=(Decimal);\n\n    /**\n     * @exception DecimalSubtractionException is thrown if\n     * subtraction would cause overflow.\n     *\n     * @exception DecimalRangeException is thrown if fractional precision\n     * cannot be maintained\n     * at the same level as that of the more precise of the two numbers\n     * involved (the minuend and the subrahend).\n     * This ensures that - unlike in unchecked floating point\n     * arithmetic - subtracting one non-zero number from another will always\n     * yield a number that is equal to neither of the original numbers (or\n     * else will throw an exception).\n     *\n     * Note trailing fractional zeroes are never \"rationalized away\" from the\n     * result. Stored fractional precision is always maintained at the level\n     * of the more precise of the operands, and if it cannot be, an exception\n     * is thrown.\n     *\n     * Exception safety: <em>strong guarantee</em>.\n     */\n    Decimal& operator-=(Decimal);\n\n    /**\n     * @exception DecimalMultiplicationException thrown if multiplication\n     * would cause overflow. If this occurs, the value of the left-hand\n     * operand will be unchanged from its original value, as will the value\n     * of the right-hand operand (since it is passed by value).\n     *\n     * Currently, for multiplication to be executed safely, it must be\n     * the case that the underlying integral representations of the Decimals\n     * being multiplied can themselves be multiplied without overflow. If\n     * this cannot occur, then the Decimal multiplication operation will\n     * throw an exception rather than proceeding with the operation. The\n     * simplest way to avoid an exception from multiplication is to ensure\n     * that the number of significant digits in the left multiplicand,\n     * plus the number of significant digits in the right multiplicand,\n     * is less than\n     * the value returned by Decimal::maximum_precision(). Note\n     * that all digits to the left of the decimal point (excluding the case\n     * where the only\n     * such digit is \\c 0) are counted as significant digits.\n     * In Decimals with fractional parts (digits to the right of the \n     * decimal point), the significant\n     * digits, going from left to right, start at the first non-zero digit,\n     * and continue consecutively until the last non-zero digit is reached\n     * (and the \"boundary digits\" just mentioned count as significant\n     * digits). The negative sign and the decimal point\n     * do not count as digits.\n     *\n     * Note also the smallest possible Decimal (the value returned by\n     * Decimal::minimum()) cannot be multiplied, and\n     * DecimalMultiplicationException is thrown if this is attempted.\n     *\n     * The fractional precision of the returned product is never more\n     * than a number of decimal places to the right\n     * of the decimal point equal to the value returned by \n     * Decimal::maximum_precision(). The returned product is as precise as\n     * possible within this constraint; however, trailing fractional zeroes\n     * are always eliminated rather than being stored within the returned\n     * product.\n     *\n     * Exception safety: <em>strong guarantee</em>.\n     */\n    Decimal& operator*=(Decimal);\n\n    /**\n     * @exception DecimalDivisionByZeroException is thrown if division by\n     * zero is attempted.\n     *\n     * @exception DecimalDivisionException is thrown if division would cause\n     * overflow.\n     *\n     * If an exception is thrown, the left-hand operand will be unchanged\n     * from its original value, as will the right-hand operand (since it\n     * is passed by value).\n     *\n     * The precision of the returned quotient is never more than\n     * a number of decimal places to the right\n     * of the decimal point, equal to the value\n     * returned by Decimal::maximum_precision().\n     * Also, the returned quotient never has\n     * more significant (non-zero) digits than this. Division returns a\n     * quotient that is as precise as possible within these constraints.\n     * However, pointless trailing zeroes to the right of the\n     * decimal point are eliminated rather than stored within the result.\n     *\n     * Currently, to be able to divide one Decimal by another,\n     * it must be possible for the implementation of the division\n     * function to increase the\n     * fractional precision (number of places to the right of the decimal\n     * point) of the dividend until it is greater than or equal to the\n     * fractional precision of the divisor. In some cases it is not possible to\n     * do this safely in which case an exception\n     * is thrown. You can avoid this\n     * possibility by ensuring that you only divide Decimals where the\n     * fractional precision of the dividend is at least as great as that\n     * of the divisor; or, failing that, where the sum of the number of\n     * significant digits in the dividend, and the number of extra digits\n     * of fractional precision that would need to be added to match the\n     * fractional precision of the divisor, is less than the value returned\n     * by Decimal::maximum_precision().\n     *\n     * In addition, an exception will be thrown in cases where the number\n     * of significant digits in the dividend is equal to the return\n     * value of Decimal::maximum_precision(). This is due to limitations\n     * in the implementation. For division to succeed, the number of\n     * significant digits in the dividend must be less than the value\n     * returned by Decimal::maximum_precision(). Note\n     * that all digits to the left of the decimal point (excluding the case\n     * where the only\n     * such digit is \\c 0) are counted as significant digits.\n     * In Decimals with fractional parts (digits to the right of the \n     * decimal point), the significant\n     * digits, going from left to right, start at the first non-zero digit,\n     * and continue consecutively until the last non-zero digit is reached\n     * (and the \"boundary digits\" just mentioned count as significant\n     * digits). The negative sign and the decimal point\n     * do not count as digits.\n     *\n     * Exception safety: <em>strong guarantee</em>.\n     */\n    Decimal& operator/=(Decimal);\n\n    /**\n     * @exception DecimalIncrementationException is thrown if incrementing\n     * would cause overflow. If this happens, the Decimal will be unchanged\n     * from its original value.\n     *\n     * Incrementing a Decimal never changes its fractional precision.\n     * \n     * Postfix and prefix version are both provided, with conventional\n     * semantics.\n     *\n     * Exception safety: <em>strong guarantee</em>.\n     */\n    Decimal const& operator++();\n    Decimal operator++(int);\n\n    /** @exception DecimalDecrementationException is throw if decrementing\n     * would cause overflow.\n     *\n     * Decrementing a Decimal never changes its fractional precision.\n     *\n     * Postfix and prefix version are both provided, with conventional\n     * semantics.\n     *\n     * Exception safety: <em>strong guarantee</em>.\n     */\n    Decimal const& operator--();\n    Decimal operator--(int);\n\n    /**\n     * Less-than operator. Compares Decimals by value.\n     *\n     * Exception safety: <em>nothrow guarantee</em>.\n     */\n    bool operator<(Decimal) const;\n\n    /**\n    * Equality operator. Compares Decimals by value.\n    * Note the following evaluates to \\c true: \\n\n    * Decimal(\"-0.000\") == Decimal(\"0\");\n    *\n    * Exception safety: <em>nothrow guarantee</em>.\n    */\n    bool operator==(Decimal) const;\n\n    /**\n     * Return the underlying integer representing the Decimal.\n     *\n     * Exception safety: <em>nothrow guarantee</em>.\n     */\n    int_type intval() const;    \n\n    /**\n     * Return the number of digits of fractional precision in the\n     * Decimal, i.e. the number of digits to the right of the decimal\n     * point.\n     *\n     * Exception safety: <em>nothrow guarantee</em>.\n     */\n    places_type places() const;\n\n    /**\n     * Returns the largest possible Decimal number\n     *\n     * Exception safety: <em>nothrow guarantee</em>.\n     */\n    static Decimal maximum();\n\n    /**\n     * Returns the smallest possible Decimal number\n     *\n     * Exception safety: <em>nothrow guarantee</em>.\n     */\n    static Decimal minimum();\n\n    /**\n     * Returns the maximum number of digits of precision\n     *\n     * Exception safety: <em>nothrow guarantee</em>.\n     */\n    static places_type maximum_precision();\n\n\nprivate:\n\n    /**\n     * Sets the number of decimal places of precision to \n     * the right of the decimal point, while also rescaling the\n     * underlying integer (which may involve rounding) to preserve\n     * the same order of magnitude.\n     *\n     * For example:\n     * @code\n     * Decimal d0(\"90.23457\");\n     * d0.rescale(3);\n     * assert(d0 == Decimal(\"90.235\"));\n     * d0.rescale(5);\n     * assert(d0 == Decimal(\"90.23500\"));\n     * assert(d0 == Decimal(\"90.235\"));\n     * assert(d0.precision() == 3);\n     * @endcode\n     *\n     * @param p_places the new number of decimal places (i.e. number\n     * of digits of precision to the right of the decimal point)\n     *\n     * If p_places exceeds s_max_places, or if the function cannot otherwise\n     * execute safely, an exception is \\e not thrown, but\n     * rather a non-zero value is returned to indicate error. If this occurs\n     * the unsafe operation is not actually executed, but rather the Decimal\n     * is retained in its original state.\n     *\n     * The function is non-throwing primarily for reasons of efficiency.\n     *\n     * @returns an integer indicating whether the operation was successful,\n     * viz. 0 if successful, otherwise a non-zero value. \n     */\n    int rescale(places_type p_places);\n\n    /**\n     * Where the final digit(s) of the Decimal number are '0', this\n     * method \"chops off the zeroes\" by reducing the number of\n     * decimal places, while re-scaling the underlying integer to\n     * preserve the same order of magnitude.\n     * \n     * For example: \"0.3234000\" rationalizes to \"0.3234\".\n     *\n     * If there are no trailing zeroes, then the function does nothing.\n     * \n     * A minimum number of places can be set, so that the number of digits\n     * of fractional precision is not reduced below this number of places.\n     *\n     * For example, with a minimum number places of 5, \"0.2324000\"\n     * rationalizes to \"0.23240\".\n     *\n     * @parameter min_places is the minimum number of decimal places to retain\n     * to the right of the decimal point.\n     */\n    void rationalize(places_type min_places = 0);\n\n    /**\n     * Base of arithmetic. I can't imagine this ever being equal to anything\n     * other than 10.\n     */\n    static int_type constexpr s_base = 10;\n\n    /**\n     * Threshold at which rounding goes up rather than down.\n     */\n    static int_type constexpr s_rounding_threshold = 5;\n\n    /**\n     * Maximum number of decimal places of precision to the right of\n     * the decimal point.\n     */\n    static size_t const s_max_places;\n\n    /**\n     * Largest possible Decimal.\n     */\n    static Decimal const s_maximum;\n\n    /**\n     * Smallest possible Decimal.\n     */\n    static Decimal const s_minimum;\n\n    /**\n     * Number of digits of precision to the right of the decimal point.\n     */\n    places_type m_places;\n\n    /**\n     * Underlying integer representation of Decimal number.\n     */\n    int_type m_intval;\n\n    /** \n     * Convert two Decimal objects to the same number of places by converting\n     * the one with the lesser number of places to the same number of places\n     * as the one with the greater number of places (while rescaling to\n     * maintain the same order of magnitude).\n     *\n     * @throws DecimalRangeException if the operation would cause\n     * overflow.\n     */\n    static void co_normalize(Decimal&, Decimal&);\n\n    /**\n     * Power of 10 by which the underlying integer is implicitly divided.\n     */\n    int_type implicit_divisor() const;\n\n    /** This constructor is deliberately unimplemented. Ensures if an int or\n     * a convertible-to-int is passed to constructor, compilation will fail.\n     */\n    explicit Decimal(int);\n\n    /**\n     * Called by output operator. This is not designed to be called by\n     * other functions. May throw boost::bad_lexical_cast (would be rare)\n     * or std::bad_alloc (even if exceptions not enabled on oss).\n     * Writes a Decimal number backwards on a stream. (Backwards is\n     * easier.)\n     */\n    template <typename charT, typename traits>\n    void output_aux(std::basic_ostream<charT, traits>& oss) const;\n\n    // Auxiliary class to help with char and wchar_t literals.\n    template <typename charT>\n    struct CharacterProvider\n    {\n        static charT constexpr null = '\\0';\n        static charT constexpr plus = '+';\n        static charT constexpr minus = '-';\n    };\n\n}; // class Decimal\n\n\n// Helper function\n\nnamespace detail\n{\n\ntemplate <typename charT>\nstatic bool is_digit(charT c);\n\n}  // namespace detail\n\n\n// non-member functions - declarations\n\n/** Write to an output stream.\n * \n * Exception safety: provides <em>nothrow guarantee</em>, \\e unless exceptions\n * have been enabled for the output stream. In the\n * event of output failure, std::ios_base::badbit will be set on the\n * stream; but the setting of this flag will trigger an exception only if\n * the client has enabled exceptions for std::ios_base::badbit for this\n * stream. (At the time of writing this is not common practice.) The thrown\n * exception will be an instance of std::ios_base::failure. This might be\n * caused by internal memory allocation failure in the body of this function\n * (extremely unlikely); or it might be caused by an \"external\" error, e.g.\n * a disk being removed during the course of writing to the disk.\n *\n * Output is sensitive to the std::numpunct facet of the locale of the\n * stream being written to. \"Thousands\" separators, digit groupings and\n * the decimal point sign will adjust according to the facet. However,\n * jewel::Decimal does NOT currently support locales set by Boost.Locale.\n * This is a significant shortcoming, since Boost.Locale offers superior\n * localization facilities to those of the standard library.\n */\ntemplate <typename charT, typename traits>\nstd::basic_ostream<charT, traits>&\noperator<<(std::basic_ostream<charT, traits>&, Decimal const&);\n\n/** Read from a std::istream\n *\n * @relates Decimal\n *\n * If the sequence of characters read from the stream is such that\n * it cannot be validly converted to a \\c Decimal (see the \\c Decimal\n * constructor that takes a \\c std::string \\c const& parameter, for\n * the circumstances in which this can occur), an exception is \\c not\n * generally thrown, but rather the input stream will have\n * std::ios_base::failbit set on the stream, per the common convention.\n * In this case, the Decimal argument then retains\n * the value it had prior to commencement of the read operation. However,\n * an exception viz. std::ios_base::failure \\e will be thrown if this\n * occurs where the input stream has had exceptions enabled for\n * std::ios_base::failbit. This is in\n * accordance with standard library convention. There is also an (extremely\n * small) chance of memory allocation failure during the read operation.\n * In this case, std::ios::badbit, and\n * an exception, being an instance of std::ios_base::failure, will be thrown\n * if and only if exceptions have been enabled for badbit for the stream.\n *\n * Exception safety: <em>nothrow guarantee</em>, unless exceptions have\n * been enabled for std::ios_base::failbit or std::ios_base::badbit for the\n * stream (see above).\n */\ntemplate <typename charT, typename traits>\nstd::basic_istream<charT, traits>&\noperator>>(std::basic_istream<charT, traits>&, Decimal&);\n\n/**\n * @relates Decimal\n *\n * Behaves as would be expected given the behaviour of operator+=, and\n * throws under the same circumstances.\n */\nDecimal const operator+(Decimal lhs, Decimal const& rhs);\n\n/**\n * @relates Decimal\n *\n * Behaves as would be expected given the behaviour of operator-=, and\n * throws under the same circumstances.\n */\nDecimal const operator-(Decimal lhs, Decimal const& rhs);\n\n/**\n * @relates Decimal\n *\n * Behaves as would be expected given the behaviour of operator*=, and\n * throws under the same circumstances.\n */\nDecimal const operator*(Decimal lhs, Decimal const& rhs);\n\n/**\n * @relates Decimal\n *\n * Behaves as would be expected given the behaviour of operator/=, and\n * throws under the same circumstances.\n */\nDecimal const operator/(Decimal lhs, Decimal const& rhs);\n\n/**\n * @relates Decimal\n *\n * Behaves as would be expected given the behaviour of operator==.\n */\nbool operator!=(Decimal const& lhs, Decimal const& rhs);\n\n/**\n * @relates Decimal\n *\n * Behaves as would be expected given the behaviour of operator< and\n * of operator==.\n */\nbool operator<=(Decimal const& lhs, Decimal const& rhs);\n\n/**\n * @relates Decimal\n *\n * Behaves as would be expected given the behaviour of operator<.\n */\nbool operator>(Decimal const& lhs, Decimal const& rhs);\n\n/**\n * @relates Decimal\n *\n * Behaves as would be expected given the behaviour of operator> and\n * of operator==.\n */\nbool operator>=(Decimal const& lhs, Decimal const& rhs);\n\n/** Unary minus\n *\n * @relates Decimal\n *\n * @throws DecimalUnaryMinusException if you try to apply unary\n * minus to a value for which this is unsafe; for example, where the\n * underlying integral representation is \\c long, it will be unsafe\n * to take the negative value of the Decimal corresponding to LONG_MIN\n * (which would then be the value returned by Decimal::minimum()).\n *\n * Exception safety: <em>strong guarantee</em>.\n */\nDecimal operator-(Decimal const& d);\n\n/** Unary plus\n *\n * Does what you would expect.\n *\n * @relates Decimal\n *\n * Exception safety: <em>nothrow guarantee</em>.\n */\nDecimal operator+(Decimal const& d);\n\n/** Rounding function\n *\n * @relates Decimal\n * \n * @param x The Decimal number to be rounded.\n * @param decimal_places The number of decimal digits after the\n * zero to which you wish to round. Should be a \\e Decimal::places_type.\n *\n * Note if you round to a number of decimal places greater than the current\n * fractional precision, it will return a Decimal with the requested\n * fractional precision (filling in the extra places effectively with zeroes).\n * If this cannot be safely done an exception will be thrown.\n *\n * @returns A decimal number by value (distinct from x, which is not changed).\n * @exception DecimalRangeException thrown if achieving the requested\n * degree of precision would cause overflow.\n *\n * Exception safety: <em>strong guarantee</em>.\n */\nDecimal round(Decimal const& x, Decimal::places_type decimal_places);\n\n\n}  // namespace jewel\n\n\n// ****************//\n\n#include \"assert.hpp\"\n#include \"decimal_exceptions.hpp\"\n#include \"exception.hpp\"\n\nnamespace jewel\n{\n\n\n// SPECIALIZATIONS - must come first\n\nnamespace detail\n{\n\ntemplate <>\nbool is_digit<char>(char c)\n{\n    return std::isdigit(c);\n}\n\ntemplate <>\nbool is_digit<wchar_t>(wchar_t c)\n{\n    return std::iswdigit(c);\n}\n\n}  // namespace detail\n\n\n// IMPLEMENTATIONS\n\ntemplate <typename charT, typename traits, typename Alloc>\nDecimal::Decimal(std::basic_string<charT, traits, Alloc> const& str):\n    m_places(0),\n    m_intval(0)\n{\n    // NOTE In regards to the restriction enforced by this static_assert,\n    // the ONLY reason this restriction is in place is that types other\n    // than std::string and std::wstring are UNTESTED. It may well be\n    // that the ONLY action required to make this work perfectly well with other\n    // types is to get rid of the static_assert.\n    static_assert\n    (   std::is_same<decltype(str), std::string const&>::value ||\n        std::is_same<decltype(str), std::wstring const&>::value,\n        \"Decimal constructor expected either std::string const& or \"\n        \"std::wstring const&, but received some other type.\"\n    );\n\n    typedef typename std::basic_string<charT> stringT;\n    typedef typename stringT::size_type sz_t;\n\n    std::locale const loc;  // global locale\n    charT const spot_char =\n        std::use_facet<std::numpunct<charT> >(loc).decimal_point();\n    charT const null_char = CharacterProvider<charT>::null;\n    charT const plus_char = CharacterProvider<charT>::plus;\n    charT const minus_char = CharacterProvider<charT>::minus;\n\n    // Writing through iterators here to make it as fast as I reasonably\n    // can.\n    //\n    // This seems to be about as fast as using indexing, but roughly 25%\n    // faster than using push_back.\n    //\n    // I've got plentiful asserts to ensure I don't read or write off the\n    // end.\n    //\n    // Note the lexical cast near the end accounts for a huge chunk of the\n    // execution time.\n    //\n    // Of course, if I want extremely fast construction of a Decimal,\n    // the constructor-from-string is not the best constructor to achieve\n    // that.\n    \n    if (str.empty())\n    {\n        JEWEL_THROW\n        (   DecimalFromStringException,\n            \"Cannot construct Decimal from an empty string\"\n        );\n    }\n    sz_t const str_size = str.size();\n    \n    // To hold string representation of underlying integer...\n    // We will decrease this size later if there's a spot (decimal point)\n    // as we won't hold the spot in str_rep.\n    stringT str_rep(str_size, null_char);\n    typename stringT::const_iterator si = str.begin();  // Read through this\n    typename stringT::iterator ri = str_rep.begin();    // Write through this\n\n    if (*si == minus_char || *si == plus_char)\n    {\n        JEWEL_ASSERT (ri < str_rep.end());\n        *ri++ = *si++;\n    }\n\n    typename stringT::const_iterator const str_end = str.end();\n    for ( ; *si != spot_char && si != str_end; ++si, ++ri)\n    {\n        JEWEL_ASSERT (si < str_end);\n        if (!detail::is_digit(*si))\n        {\n            JEWEL_THROW\n            (   DecimalFromStringException,\n                \"Invalid string passed to Decimal constructor.\"\n            );\n        }\n        JEWEL_ASSERT (ri < str_rep.end());\n        *ri = *si;\n    }\n    sz_t spot_position = 0;   // for the position of decimal point    \n    if (*si == spot_char)\n    {\n        // We have a spot.\n        // We have a str_rep that's one too big\n        sz_t reduced_size = str_size;\n        JEWEL_ASSERT (reduced_size > 0);\n        str_rep.resize(--reduced_size);\n        JEWEL_ASSERT (reduced_size == str_rep.size());    \n        JEWEL_ASSERT (reduced_size < str_size);\n        JEWEL_ASSERT (str_size >= 1);\n\n        // Jump over the spot in str\n        ++si;\n\n        // Now let's get the remaining the digits\n        JEWEL_ASSERT (str_end == str.end());\n        for ( ; si != str_end; ++si, ++ri)\n        {\n            ++spot_position;        // To count no. of fractional places\n            JEWEL_ASSERT (si < str_end);\n            if (!detail::is_digit(*si))\n            {\n                JEWEL_ASSERT (m_places == 0);\n                JEWEL_ASSERT (m_intval == 0);\n                JEWEL_THROW\n                (   DecimalFromStringException,\n                    \"Invalid string passed to Decimal constructor.\"\n                );\n            }\n            JEWEL_ASSERT (reduced_size == str_rep.size());\n            JEWEL_ASSERT (ri < str_rep.end());\n            *ri = *si;\n        }\n    }\n    if (spot_position > s_max_places)\n    {\n        JEWEL_THROW\n        (   DecimalRangeException,\n            \"Attempt to set m_places to a value exceeding that returned by \"\n            \"Decimal::maximum_precision().\"\n        );\n    }\n    if (str_rep.size() <= 1)\n    {\n        if\n        (   str_rep.empty() ||\n            str_rep == stringT(1, minus_char) ||\n            str_rep == stringT(1, plus_char)\n        )\n        {\n            JEWEL_THROW\n            (   DecimalFromStringException,\n                \"Attempt to create a Decimal without any digits.\"\n            );\n        }\n    }\n    try\n    {   \n        // This lexical cast accounted for over half of the execution\n        // time in this function last time I checked.\n        m_intval = boost::lexical_cast<int_type>(str_rep);\n    }\n    catch (boost::bad_lexical_cast&)\n    {\n        JEWEL_THROW\n        (   DecimalRangeException,\n            \"Attempt to create Decimal that is either too large, too small \"\n            \"or too precise than is supported by the Decimal implementation.\"\n        );\n    }\n    m_places = boost::numeric_cast<places_type>(spot_position);\n}\n\ninline\nDecimal::Decimal(char const* str)\n{\n    *this = Decimal(std::string(str));\n}\n\ninline\nDecimal::Decimal(wchar_t const* str)\n{\n    *this = Decimal(std::wstring(str));\n}\n\ninline\nDecimal::int_type\nDecimal::intval() const\n{\n    return m_intval;\n}\n\ninline \nDecimal::places_type\nDecimal::places() const\n{\n    return m_places;\n}\n\n// Inline static class functions\n\ninline\nDecimal::places_type Decimal::maximum_precision()\n{\n    return s_max_places;\n}\n\ninline\nDecimal\nDecimal::minimum()\n{\n    return s_minimum;\n}\n\ninline\nDecimal\nDecimal::maximum()\n{\n    return s_maximum;\n}\n\n\n// Inline non-member functions\n\ninline\nDecimal const\noperator+(Decimal lhs, Decimal const& rhs)\n{\n    lhs += rhs;\n    return lhs;\n}\n\ninline\nDecimal const\noperator-(Decimal lhs, Decimal const& rhs)\n{\n    lhs -= rhs;\n    return lhs;\n}\n\ninline\nDecimal const\noperator*(Decimal lhs, Decimal const& rhs)\n{\n    lhs *= rhs;\n    return lhs;\n}\n\ninline\nDecimal const\noperator/(Decimal lhs, Decimal const& rhs)\n{\n    lhs /= rhs;\n    return lhs;\n}\n\ninline\nDecimal\noperator+(Decimal const& d)\n{\n    return d;\n}\n\ninline\nbool\noperator!=(Decimal const& lhs, Decimal const& rhs)\n{\n    return !(lhs == rhs);\n}\n\ninline\nbool\noperator>(Decimal const& lhs, Decimal const& rhs)\n{\n    return rhs < lhs;\n}\n\ninline\nbool\noperator<=(Decimal const& lhs, Decimal const& rhs)\n{\n    return (lhs == rhs) || (lhs < rhs);\n}\n\ninline\nbool\noperator>=(Decimal const& lhs, Decimal const& rhs)\n{\n    return (lhs == rhs) || (rhs < lhs);\n}\n\n\n// Output\n\n\n\ntemplate <typename charT, typename traits>\nstd::basic_ostream<charT, traits>&\noperator<<(std::basic_ostream<charT, traits>& os, Decimal const& d)\n{   \n    if (!os)\n    {\n        return os;\n    }\n    try\n    {\n        // We will write to a basic_ostringstream initially. Only at the last\n        // minute will we write to os itself.\n        std::basic_ostringstream<charT, traits> ss;\n        \n        // Whatever exception-throwing behaviour the client has set for os\n        // should also be mirrored in ss.\n        ss.exceptions(os.exceptions());\n\n        ss.imbue(os.getloc());\n        d.output_aux(ss);\n        if (!ss)\n        {\n            // If any error flags have been set in ss, we now\n            // mirror them here in os, and return rather\n            // than potentially corrupt data to os.\n            os.setstate(ss.rdstate());\n            return os;\n        }\n        JEWEL_ASSERT (ss);\n        std::basic_string<charT> const s = ss.str();\n        std::reverse_copy\n        (   s.begin(),\n            s.end(),\n            std::ostream_iterator<charT, charT, traits>(os)\n        );\n    }\n    catch (std::exception&)\n    {\n        // Exception could be std::bad_alloc from failed allocation of\n        // ostringstream or string (though both are\n        // extremely unlikely).\n        // Possibly others? Catch std::exception to be sure.\n        os.setstate(std::ios_base::badbit);\n    }\n    return os;\n}\n\ntemplate <typename charT, typename traits>\nvoid\nDecimal::output_aux(std::basic_ostream<charT, traits>& oss) const\n{\n    using std::locale;\n    using std::numpunct;\n    using std::reverse_copy;\n    using std::use_facet;\n    typedef typename std::basic_string<charT> stringT;\n    typedef typename stringT::size_type str_sz;\n    typedef typename std::basic_ostringstream<charT> ostringstreamT;\n    typedef typename std::ostream_iterator<charT, charT, traits> ostream_itT;\n\n    // Record target locale\n    locale const loc(oss.getloc());\n    charT const decimal_point =\n        use_facet<numpunct<charT> >(loc).decimal_point();\n\n    // We will be \"manually\" reflecting the locale's numpunct facet\n    // in what we write to oss. If there is already a non-C\n    // locale on oss, we get rid of it now. We don't want\n    // some other locale's numpunct facet interfering with\n    // our manual labours.\n    oss.imbue(locale::classic());\n\n    // Now we write the number BACKWARDS onto oss. It's easier\n    // this way, especially when it comes to processing\n    // \"thousands separators\".\n\n    // special case of zero\n    if (m_intval == 0)\n    {\n        if (m_places > 0)\n        {\n            oss << stringT(m_places, oss.widen('0')) << decimal_point;\n        }\n        oss << oss.widen('0');\n    }\n\n    // special case of smallest possible m_intval - as we\n    // cannot take the absolute value below\n    else if (m_intval == std::numeric_limits<Decimal::int_type>::min())\n    {\n        JEWEL_ASSERT (m_places == 0);\n        ostringstreamT tempstream;\n        tempstream.imbue(loc);\n        tempstream << m_intval;\n        stringT const tempstring = tempstream.str();\n        reverse_copy\n        (   tempstring.begin(),\n            tempstring.end(),\n            ostream_itT(oss)\n        );\n    }\n\n    else\n    {\n        // Our starting point is the stringT of digits representing\n        // the absolute value of the underlying integer.\n        ostringstreamT tempstream;\n        tempstream.imbue(locale::classic());\n        tempstream << std::abs(m_intval);\n        stringT s = tempstream.str();\n    \n        // Write the fractional part\n        typename stringT::const_reverse_iterator const rend = s.rend();\n        typename stringT::const_reverse_iterator rit = s.rbegin();\n        str_sz digits_written  = 0;\n        for\n        (   ;\n            (digits_written != m_places) && (rit != rend);\n            ++rit, ++digits_written\n        )\n        {\n            oss << *rit;\n        }\n\n        // Deal with any \"filler zeroes\" required in the\n        // fractional part\n        while (digits_written != m_places)\n        {\n            oss << oss.widen('0');\n            ++digits_written;\n        }\n\n        // Write the decimal point if required\n        if (m_places != 0) oss << decimal_point;\n            \n        // Write the whole part\n        \n        // Get format specifier for digit grouping\n        std::string const grouping =\n            use_facet< numpunct<charT> >(loc).grouping();\n        if (grouping.empty())\n        {\n            // We don't have to deal with digit grouping\n            for\n            (   ;\n                rit != rend;\n                ++rit, ++digits_written\n            )\n            {\n                oss << *rit;\n            }\n        }\n        else\n        {\n            // We have to deal with digit grouping\n            charT const separator =\n                use_facet<numpunct<charT> >(loc).thousands_sep();\n            std::string::const_iterator grouping_it = grouping.begin();\n            JEWEL_ASSERT (!grouping.empty());\n            std::string::const_iterator const last_group_datum\n                = grouping.end() - 1;\n            str_sz digits_written_this_group = 0;\n            for\n            (   ;\n                rit != rend;\n                ++rit, ++digits_written, ++digits_written_this_group\n            )\n            {\n                if\n                (   digits_written_this_group ==\n                    static_cast<str_sz>(*grouping_it)\n                )\n                {\n                    oss << separator;\n                    digits_written_this_group = 0;\n                    if (grouping_it != last_group_datum) ++grouping_it;\n                }\n                oss << *rit;\n            }\n        }\n\n        // Write a leading zero if required\n        if (digits_written == m_places)\n        {\n            oss << oss.widen('0');\n        }\n        \n        // Write negative sign if required\n        if (m_intval < 0) oss << '-';\n    }\n    #ifdef JEWEL_PERFORM_DECIMAL_OUTPUT_FAILURE_TEST\n        // We cause bad memory allocation here to provoke\n        // failure. This is to test how Decimal output\n        // operator<< (which calls this function) handles\n        // failure.\n        std::string grow_me(\"a\");\n        while (true)\n        {\n            grow_me += grow_me;\n        }\n    #endif\n    return;\n}\n\n\n// Input\n\ntemplate <typename charT, typename traits>\nstd::basic_istream<charT, traits>&\noperator>>(std::basic_istream<charT, traits>& is, Decimal& d)\n{\n    if (!is)\n    {\n        return is;\n    }\n    Decimal temp = d;\n    try\n    {\n        std::string str;\n        is >> str;\n        if (!is)\n        {\n            return is;\n        }\n        try\n        {   \n            temp = Decimal(str);\n        }\n        catch (DecimalException&)\n        {\n            is.setstate(std::ios_base::failbit);\n            return is;\n        }\n        d = temp;\n    }\n    catch (std::bad_alloc&)\n    {\n        is.setstate(std::ios_base::badbit);\n        return is;\n    }\n    return is;\n}\n\n\n\n} // namespace jewel\n\n#endif  // GUARD_decimal_hpp_0809249049429432\n", "meta": {"hexsha": "c4fa7efc0357f04ddeafb1d3a4d1fa149b69e547", "size": 45092, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/decimal.hpp", "max_stars_repo_name": "skybaboon/jewel", "max_stars_repo_head_hexsha": "0cb7c9ccfd2b61fc44cc2013ee27ff127eaf0493", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/decimal.hpp", "max_issues_repo_name": "skybaboon/jewel", "max_issues_repo_head_hexsha": "0cb7c9ccfd2b61fc44cc2013ee27ff127eaf0493", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/decimal.hpp", "max_forks_repo_name": "skybaboon/jewel", "max_forks_repo_head_hexsha": "0cb7c9ccfd2b61fc44cc2013ee27ff127eaf0493", "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.0586510264, "max_line_length": 80, "alphanum_fraction": 0.657832875, "num_tokens": 10315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5428632831725051, "lm_q1q2_score": 0.29259420075740705}}
{"text": "#include <stdlib.h>\n\n#include <boost/program_options.hpp>\n#include <chrono>\n#include <limits>\n\n#include \"../space/initial_triangulation.hpp\"\n#include \"../time/basis.hpp\"\n#include \"../tools/util.hpp\"\n#include \"adaptive_heat_equation.hpp\"\n#include \"problems.hpp\"\n\nusing applications::AdaptiveHeatEquation;\nusing datastructures::DoubleTreeView;\nusing space::HierarchicalBasisFn;\nusing Time::OrthonormalWaveletFn;\nusing Time::ThreePointWaveletFn;\n\nusing namespace applications;\nnamespace po = boost::program_options;\n\nnamespace applications {\nstd::istream& operator>>(std::istream& in,\n                         HeatEquationOptions::SpaceInverse& inverse_type) {\n  std::string token;\n  in >> token;\n  if (token == \"DirectInverse\" || token == \"di\")\n    inverse_type = HeatEquationOptions::SpaceInverse::DirectInverse;\n  else if (token == \"Multigrid\" || token == \"mg\")\n    inverse_type = HeatEquationOptions::SpaceInverse::Multigrid;\n  else\n    in.setstate(std::ios_base::failbit);\n  return in;\n}\n\nvoid PrintTimeSliceSS(double t, AdaptiveHeatEquation::TypeXVector* solution) {\n  auto time_slice = spacetime::Trace(t, *solution);\n\n  // Calculate the triangulation corresponding to this space mesh.\n  space::TriangulationView triang(time_slice.Bfs());\n  std::cerr << \"triang{\";\n  for (auto [elem, vertices] : triang.element_leaves())\n    std::cerr << \"(\" << vertices[0] << \", \" << vertices[1] << \", \"\n              << vertices[2] << \");\";\n  std::cerr << \"}\\t\";\n\n  // Calculate the single scale representation\n  space::MassOperator op(triang);\n  Eigen::VectorXd u_SS = time_slice.ToVector();\n  assert(op.FeasibleVector(u_SS));\n  op.ApplyHierarchToSingle(u_SS);\n  assert(op.FeasibleVector(u_SS));\n\n  // Print the data in single scale.\n  time_slice.FromVector(u_SS);\n  std::cerr << \"vertices{\";\n  for (auto nv : time_slice.Bfs())\n    std::cerr << \"(\" << nv->node()->center().first << \",\"\n              << nv->node()->center().second << \") : \" << nv->value() << \";\";\n  std::cerr << \"}\";\n}\n\n// Compile time constants.\nconstexpr size_t N_t = 20;\nconstexpr size_t N_x = 197;\nconstexpr size_t N_y = 199;\n\nstd::vector<std::tuple<float, float, float, double>> PrintSampling(\n    AdaptiveHeatEquation::TypeXVector* solution) {\n  int cnt[N_t + 1][N_x + 1][N_y + 1] = {0};\n  double h_t = 1.0 / N_t;\n  double h_x = 1.0 / N_x;\n  double h_y = 1.0 / N_y;\n  for (auto dblnode : solution->Bfs())\n    for (int t = 0; t <= N_t; t++) {\n      if (dblnode->node_0()->Eval(t * h_t) == 0) continue;\n      for (int x = 0; x <= N_x; x++) {\n        if (!dblnode->node_1()->Contains(x * h_x,\n                                         dblnode->node_1()->center().second))\n          continue;\n        for (int y = 0; y <= N_y; y++) {\n          if (dblnode->node_1()->Eval(x * h_x, y * h_y) == 0) continue;\n          cnt[t][x][y]++;\n        }\n      }\n    }\n\n  std::vector<std::tuple<float, float, float, double>> result;\n  for (int t = 0; t <= N_t; t++)\n    for (int x = 0; x <= N_x; x++)\n      for (int y = 0; y <= N_y; y++) {\n        result.emplace_back(t * h_t, x * h_x, y * h_y, cnt[t][x][y]);\n      }\n\n  return result;\n}\n\nspace::InitialTriangulation InitialTriangulation(std::string domain,\n                                                 size_t initial_refines) {\n  if (domain == \"square\" || domain == \"unit-square\")\n    return space::InitialTriangulation::UnitSquare(initial_refines);\n  else if (domain == \"lshape\" || domain == \"l-shape\")\n    return space::InitialTriangulation::LShape(initial_refines);\n  else if (domain == \"pacman\")\n    return space::InitialTriangulation::Pacman(initial_refines);\n  else {\n    std::cout << \"domain not recognized :-(\" << std::endl;\n    exit(1);\n  }\n}\n}  // namespace applications\n\nint main(int argc, char* argv[]) {\n  std::string problem, domain;\n  size_t initial_refines = 0;\n  size_t max_dofs = 0;\n  bool calculate_condition_numbers = false;\n  bool print_centers = false;\n  bool print_sampling = false;\n  bool print_time_apply = false;\n  std::vector<double> print_time_slices;\n  boost::program_options::options_description problem_optdesc(\n      \"Problem options\");\n  problem_optdesc.add_options()(\n      \"problem\", po::value<std::string>(&problem)->default_value(\"singular\"))(\n      \"domain\", po::value<std::string>(&domain)->default_value(\"square\"))(\n      \"initial_refines\", po::value<size_t>(&initial_refines))(\n      \"max_dofs\", po::value<size_t>(&max_dofs)->default_value(\n                      std::numeric_limits<std::size_t>::max()))(\n      \"calculate_condition_numbers\",\n      po::value<bool>(&calculate_condition_numbers))(\n      \"print_centers\", po::value<bool>(&print_centers))(\n      \"print_sampling\", po::value<bool>(&print_sampling))(\n      \"print_time_slices\",\n      po::value<std::vector<double>>(&print_time_slices)->multitoken())(\n      \"print_time_apply\", po::value<bool>(&print_time_apply));\n\n  std::sort(print_time_slices.begin(), print_time_slices.end());\n\n  AdaptiveHeatEquationOptions adapt_opts;\n  boost::program_options::options_description adapt_optdesc(\n      \"AdaptiveHeatEquation options\");\n  adapt_optdesc.add_options()(\"use_cache\",\n                              po::value<bool>(&adapt_opts.use_cache))(\n      \"build_space_mats\", po::value<bool>(&adapt_opts.build_space_mats))(\n      \"solve_factor\", po::value<double>(&adapt_opts.solve_factor))(\n      \"solve_xi\", po::value<double>(&adapt_opts.solve_xi))(\n      \"solve_maxit\", po::value<size_t>(&adapt_opts.solve_maxit))(\n      \"estimate_saturation_layers\",\n      po::value<size_t>(&adapt_opts.estimate_saturation_layers))(\n      \"estimate_mean_zero\", po::value<bool>(&adapt_opts.estimate_mean_zero))(\n      \"mark_theta\", po::value<double>(&adapt_opts.mark_theta))(\n      \"PX_alpha\", po::value<double>(&adapt_opts.PX_alpha))(\n      \"PX_inv\",\n      po::value<HeatEquationOptions::SpaceInverse>(&adapt_opts.PX_inv))(\n      \"PY_inv\",\n      po::value<HeatEquationOptions::SpaceInverse>(&adapt_opts.PY_inv))(\n      \"PXY_mg_build\", po::value<bool>(&adapt_opts.PXY_mg_build))(\n      \"PX_mg_cycles\", po::value<size_t>(&adapt_opts.PX_mg_cycles))(\n      \"PY_mg_cycles\", po::value<size_t>(&adapt_opts.PY_mg_cycles));\n  boost::program_options::options_description cmdline_options;\n  cmdline_options.add(problem_optdesc).add(adapt_optdesc);\n\n  po::variables_map vm;\n  po::store(po::command_line_parser(argc, argv).options(cmdline_options).run(),\n            vm);\n  po::notify(vm);\n  std::cout << \"Problem options:\" << std::endl;\n  std::cout << \"\\tProblem: \" << problem << std::endl;\n  std::cout << \"\\tDomain: \" << domain\n            << \"; initial-refines: \" << initial_refines << std::endl;\n  std::cout << std::endl;\n  std::cout << adapt_opts << std::endl;\n\n  auto T = InitialTriangulation(domain, initial_refines);\n  auto B = Time::Bases();\n\n  T.hierarch_basis_tree.UniformRefine(1);\n  B.ortho_tree.UniformRefine(1);\n  B.three_point_tree.UniformRefine(1);\n\n  auto vec_Xd = std::make_shared<\n      DoubleTreeVector<ThreePointWaveletFn, HierarchicalBasisFn>>(\n      B.three_point_tree.meta_root(), T.hierarch_basis_tree.meta_root());\n  vec_Xd->SparseRefine(1);\n\n  std::pair<std::unique_ptr<LinearFormBase<Time::OrthonormalWaveletFn>>,\n            std::unique_ptr<LinearFormBase<Time::ThreePointWaveletFn>>>\n      problem_data;\n  if (problem == \"smooth\")\n    problem_data = SmoothProblem();\n  else if (problem == \"singular\")\n    problem_data = SingularProblem();\n  else if (problem == \"cylinder\")\n    problem_data = CylinderProblem();\n  else if (problem == \"moving-peak\")\n    problem_data = MovingPeakProblem(vec_Xd);\n  else {\n    std::cout << \"problem not recognized :-(\" << std::endl;\n    return 1;\n  }\n\n  AdaptiveHeatEquation heat_eq(vec_Xd, std::move(problem_data.first),\n                               std::move(problem_data.second), adapt_opts);\n\n  size_t ndof_Xd = 0;\n  Eigen::VectorXd x0 = Eigen::VectorXd::Zero(vec_Xd->container().size());\n  double t_delta = heat_eq.Estimate(x0).second.second.error;\n  std::cout << \"t_init: \" << t_delta << std::endl;\n  size_t iter = 0;\n  auto start_algorithm = std::chrono::steady_clock::now();\n  while (ndof_Xd < max_dofs) {\n    // Store a vector of all the nodes having maximum gradedness;\n    std::vector<typename HeatEquation::TypeXVector::DNType*> max_gradedness;\n\n    // A slight overestimate.\n    ndof_Xd = vec_Xd->Bfs().size();\n    size_t ndof_Xdd = heat_eq.vec_Xdd()->Bfs().size();\n    size_t ndof_Ydd = heat_eq.vec_Ydd()->Bfs().size();\n    std::cout << \"iter: \" << ++iter << \"\\n\\tXDelta-size: \" << ndof_Xd\n              << \"\\n\\tXDelta-Gradedness: \"\n              << vec_Xd->Gradedness(&max_gradedness)\n              << \"\\n\\tXDeltaDelta-size: \" << ndof_Xdd\n              << \"\\n\\tYDeltaDelta-size: \" << ndof_Ydd\n              << \"\\n\\ttotal-memory-kB: \" << getmem() << std::flush;\n\n    if (print_sampling) {\n      auto sampling = PrintSampling(vec_Xd.get());\n      std::cout << \"\\n\\tsampling: \";\n      for (auto [t, x, y, val] : sampling)\n        std::cout << \"\" << t << \",\" << x << \",\" << y << \",\" << val << \";\";\n      std::cout << std::endl;\n    }\n\n    if (calculate_condition_numbers) {\n      auto start = std::chrono::steady_clock::now();\n      std::chrono::duration<double> duration_cond =\n          std::chrono::steady_clock::now() - start;\n\n      // Set the initial vector to something valid.\n      heat_eq.vec_Ydd()->Reset();\n      for (auto nv : heat_eq.vec_Ydd()->Bfs())\n        if (!nv->node_1()->on_domain_boundary()) nv->set_random();\n      auto lanczos_Y = tools::linalg::Lanczos(\n          *heat_eq.heat_d_dd()->A(), *heat_eq.heat_d_dd()->P_Y(),\n          heat_eq.vec_Ydd()->ToVectorContainer());\n\n      // Set the initial vector to something valid.\n      heat_eq.vec_Xd()->Reset();\n      for (auto nv : heat_eq.vec_Xd()->Bfs())\n        if (!nv->node_1()->on_domain_boundary()) nv->set_random();\n      auto lanczos_X = tools::linalg::Lanczos(\n          *heat_eq.heat_d_dd()->S(), *heat_eq.heat_d_dd()->P_X(),\n          heat_eq.vec_Xd()->ToVectorContainer());\n      std::cout << \"\\n\\tlmin-PY-A: \" << lanczos_Y.min()\n                << \"\\n\\tlmax-PY-A: \" << lanczos_Y.max()\n                << \"\\n\\tlmin-PX-S: \" << lanczos_X.min()\n                << \"\\n\\tlmax-PX-S: \" << lanczos_X.max()\n                << \"\\n\\tcond-time: \" << duration_cond.count() << std::flush;\n    }\n\n    Eigen::VectorXd solution = x0;\n    double total_error;\n    AdaptiveHeatEquation::TypeXVector* residual;\n    int cycle = 1;\n\n    auto start = std::chrono::steady_clock::now();\n    auto rhs = heat_eq.RHS();\n    std::chrono::duration<double> duration_rhs =\n        std::chrono::steady_clock::now() - start;\n    std::cout << \"\\n\\trhs-time: \" << duration_rhs.count();\n    std::cout << \"\\n\\trhs-g-linform-time: \"\n              << heat_eq.g_lin_form()->TimeLastApply();\n    std::cout << \"\\n\\trhs-u0-linform-time: \"\n              << heat_eq.u0_lin_form()->TimeLastApply();\n\n    auto start_solve_estimate = std::chrono::steady_clock::now();\n    do {\n      t_delta /= adapt_opts.solve_factor;\n      std::cout << \"\\n\\tcycle: \" << cycle << \"\\n\\t\\tt_delta: \" << t_delta;\n      // Solve.\n      start = std::chrono::steady_clock::now();\n      auto [cur_solution, pcg_data] = heat_eq.Solve(solution, rhs, t_delta);\n      solution = cur_solution;\n      t_delta = pcg_data.algebraic_error;\n      std::chrono::duration<double> duration_solve =\n          std::chrono::steady_clock::now() - start;\n      std::cout << \"\\n\\t\\tsolve-PCG-steps: \" << pcg_data.iterations\n                << \"\\n\\t\\tsolve-PCG-initial-algebraic-error: \"\n                << pcg_data.initial_algebraic_error\n                << \"\\n\\t\\tsolve-PCG-algebraic-error: \"\n                << pcg_data.algebraic_error\n                << \"\\n\\t\\tsolve-time: \" << duration_solve.count()\n                << \"\\n\\t\\tsolve-memory: \" << getmem() << std::flush;\n\n      // Estimate.\n      start = std::chrono::steady_clock::now();\n      auto [residual, global_errors] = heat_eq.Estimate(solution);\n      auto [residual_norm, global_error] = global_errors;\n      total_error = global_error.error;\n      std::chrono::duration<double> duration_estimate =\n          std::chrono::steady_clock::now() - start;\n\n      std::cout << \"\\n\\t\\tresidual-norm: \" << residual_norm\n                << \"\\n\\t\\testimate-time: \" << duration_estimate.count()\n                << \"\\n\\t\\testimate-memory: \" << getmem() << std::flush;\n      std::cout << \"\\n\\t\\tglobal-error: \" << total_error\n                << \"\\n\\t\\tYnorm-error: \" << global_error.error_Yprime\n                << \"\\n\\t\\tT0-error: \" << global_error.error_t0 << std::flush;\n      cycle++;\n    } while (t_delta > adapt_opts.solve_xi * total_error);\n    t_delta = total_error;\n\n    std::chrono::duration<double> duration_solve_estimate =\n        std::chrono::steady_clock::now() - start_solve_estimate;\n    std::cout << \"\\n\\tsolve-estimate-time: \" << duration_solve_estimate.count();\n\n    if (print_time_apply) {\n      auto heat_d_dd = heat_eq.heat_d_dd();\n      std::cout << \"\\n\\tA-time-per-apply: \" << heat_d_dd->A()->TimePerApply()\n                << \"\\n\\tB-time-per-apply: \" << heat_d_dd->B()->TimePerApply()\n                << \"\\n\\tBT-time-per-apply: \" << heat_d_dd->BT()->TimePerApply()\n                << \"\\n\\tG-time-per-apply: \" << heat_d_dd->G()->TimePerApply()\n                << \"\\n\\tP_Y-time-per-apply: \"\n                << heat_d_dd->P_Y()->TimePerApply()\n                << \"\\n\\tP_X-time-per-apply: \"\n                << heat_d_dd->P_X()->TimePerApply()\n                << \"\\n\\tS-time-per-apply: \" << heat_d_dd->S()->TimePerApply()\n                << \"\\n\\ttotal-time-apply: \" << heat_d_dd->TotalTimeApply()\n                << \"\\n\\ttotal-time-construct: \"\n                << heat_d_dd->TotalTimeConstruct() << std::flush;\n    }\n\n    if (print_centers) {\n      vec_Xd->FromVectorContainer(solution);\n      auto print_dblnode = [](auto dblnode) {\n        std::cout << \"((\" << dblnode->node_0()->level() << \",\"\n                  << dblnode->node_0()->center() << \"),\"\n                  << \"(\" << dblnode->node_1()->level() << \",(\"\n                  << dblnode->node_1()->center().first << \",\"\n                  << dblnode->node_1()->center().second\n                  << \")) : \" << dblnode->value() << \";\";\n      };\n\n      std::cout << \"\\n\\tcenters: \";\n      for (auto dblnode : vec_Xd->Bfs()) print_dblnode(dblnode);\n\n      std::cout << \"\\n\\tcenters-max-gradedness: \";\n      for (auto dblnode : max_gradedness) print_dblnode(dblnode);\n    }\n\n    if (print_time_slices.size()) {\n      vec_Xd->FromVectorContainer(solution);\n      for (double t : print_time_slices) {\n        assert(t >= 0 && t <= 1);\n        std::cerr << \"time_slice \" << t << \" = \";\n        PrintTimeSliceSS(t, vec_Xd.get());\n        std::cerr << std::endl;\n      }\n      std::cerr << std::endl;\n    }\n\n#ifdef VERBOSE\n    std::cerr << std::endl << \"Adaptive::Trees\" << std::endl;\n    std::cerr << \"  T.vertex:   #bfs =  \" << T.vertex_tree.Bfs().size()\n              << std::endl;\n    std::cerr << \"  T.element:  #bfs =  \" << T.elem_tree.Bfs().size()\n              << std::endl;\n    std::cerr << \"  T.hierarch: #bfs =  \" << T.hierarch_basis_tree.Bfs().size()\n              << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"  B.elem:     #bfs =  \" << B.elem_tree.Bfs().size()\n              << std::endl;\n    std::cerr << \"  B.three_pt: #bfs =  \" << B.three_point_tree.Bfs().size()\n              << std::endl;\n    std::cerr << \"  B.ortho:    #bfs =  \" << B.ortho_tree.Bfs().size()\n              << std::endl;\n#endif\n\n    // Mark - Refine.\n    auto marked_nodes = heat_eq.Mark(residual);\n\n    start = std::chrono::steady_clock::now();\n    vec_Xd->FromVectorContainer(solution);\n    auto r_info = heat_eq.Refine(marked_nodes);\n    x0 = vec_Xd->ToVectorContainer();\n    std::chrono::duration<double> duration_refine =\n        std::chrono::steady_clock::now() - start;\n\n    std::cout << \"\\n\\tnodes-marked: \" << r_info.nodes_marked\n              << \"\\n\\tnodes-conforming: \" << r_info.nodes_conforming\n              << \"\\n\\tresidual-norm-marked: \" << r_info.res_norm_marked\n              << \"\\n\\tresidual-norm-conforming: \" << r_info.res_norm_conforming\n              << \"\\n\\trefine-time: \" << duration_refine.count()\n              << \"\\n\\ttotal-time-algorithm: \"\n              << std::chrono::duration<double>(\n                     std::chrono::steady_clock::now() - start_algorithm)\n                     .count()\n              << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "a622a0a30acb5fca0efc05a1648509e45bb4e0ce", "size": 16316, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/applications/adaptive.cpp", "max_stars_repo_name": "rvanvenetie/spacetime", "max_stars_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/applications/adaptive.cpp", "max_issues_repo_name": "rvanvenetie/spacetime", "max_issues_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/applications/adaptive.cpp", "max_forks_repo_name": "rvanvenetie/spacetime", "max_forks_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_forks_repo_licenses": ["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.3861386139, "max_line_length": 80, "alphanum_fraction": 0.5962245648, "num_tokens": 4456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.5, "lm_q1q2_score": 0.29255058433636155}}
{"text": "#include \"drake/systems/primitives/linear_system.h\"\n\n#include <string>\n#include <utility>\n\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <fmt/format.h>\n\n#include \"drake/common/autodiff.h\"\n#include \"drake/common/default_scalars.h\"\n#include \"drake/common/eigen_types.h\"\n#include \"drake/common/symbolic.h\"\n#include \"drake/common/symbolic_decompose.h\"\n#include \"drake/math/autodiff.h\"\n#include \"drake/math/autodiff_gradient.h\"\n#include \"drake/systems/framework/event.h\"\n#include \"drake/systems/framework/event_collection.h\"\n\nnamespace drake {\nnamespace systems {\n\nusing std::make_unique;\nusing std::unique_ptr;\n\ntemplate <typename T>\nLinearSystem<T>::LinearSystem(const Eigen::Ref<const Eigen::MatrixXd>& A,\n                              const Eigen::Ref<const Eigen::MatrixXd>& B,\n                              const Eigen::Ref<const Eigen::MatrixXd>& C,\n                              const Eigen::Ref<const Eigen::MatrixXd>& D,\n                              double time_period)\n    : LinearSystem<T>(SystemTypeTag<LinearSystem>{}, A, B, C, D,\n                      time_period) {}\n\ntemplate <typename T>\ntemplate <typename U>\nLinearSystem<T>::LinearSystem(const LinearSystem<U>& other)\n    : LinearSystem<T>(other.A(), other.B(), other.C(), other.D(),\n                      other.time_period()) {}\n\ntemplate <typename T>\nLinearSystem<T>::LinearSystem(SystemScalarConverter converter,\n                              const Eigen::Ref<const Eigen::MatrixXd>& A,\n                              const Eigen::Ref<const Eigen::MatrixXd>& B,\n                              const Eigen::Ref<const Eigen::MatrixXd>& C,\n                              const Eigen::Ref<const Eigen::MatrixXd>& D,\n                              double time_period)\n    : AffineSystem<T>(std::move(converter), A, B,\n                      Eigen::VectorXd::Zero(A.rows()), C, D,\n                      Eigen::VectorXd::Zero(C.rows()), time_period) {}\n\ntemplate <typename T>\nunique_ptr<LinearSystem<T>> LinearSystem<T>::MakeLinearSystem(\n    const Eigen::Ref<const VectorX<symbolic::Expression>>& dynamics,\n    const Eigen::Ref<const VectorX<symbolic::Expression>>& output,\n    const Eigen::Ref<const VectorX<symbolic::Variable>>& state_vars,\n    const Eigen::Ref<const VectorX<symbolic::Variable>>& input_vars,\n    const double time_period) {\n  // Need to extract, A, B, C, D such that,\n  //\n  //     dynamics = Ax + Bu\n  //     output   = Cx + Du\n  //\n  // where x = state_vars and u = input_vars.\n  const int num_states = state_vars.size();\n  DRAKE_DEMAND(num_states == dynamics.size());\n  const int num_inputs = input_vars.size();\n  const int num_outputs = output.size();\n\n  Eigen::MatrixXd AB(num_states, num_states + num_inputs);\n  VectorX<symbolic::Variable> vars(num_states + num_inputs);\n  vars << state_vars, input_vars;\n  DecomposeLinearExpressions(dynamics, vars, &AB);\n  const auto A = AB.leftCols(num_states);\n  const auto B = AB.rightCols(num_inputs);\n\n  Eigen::MatrixXd CD(num_outputs, num_states + num_inputs);\n  DecomposeLinearExpressions(output, vars, &CD);\n  const auto C = CD.leftCols(num_states);\n  const auto D = CD.rightCols(num_inputs);\n\n  return make_unique<LinearSystem<T>>(A, B, C, D, time_period);\n}\n\nnamespace {\n\n// Helper function allows reuse for both FirstOrderTaylorApproximation and\n// Linearize.\nstd::unique_ptr<AffineSystem<double>> DoFirstOrderTaylorApproximation(\n    const System<double>& system, const Context<double>& context,\n    std::variant<InputPortSelection, InputPortIndex> input_port_index,\n    std::variant<OutputPortSelection, OutputPortIndex> output_port_index,\n    std::optional<double> equilibrium_check_tolerance = std::nullopt) {\n  system.ValidateContext(context);\n\n  double time_period = 0.0;\n  const bool is_discrete_system =\n      system.IsDifferenceEquationSystem(&time_period);\n  DRAKE_THROW_UNLESS(context.is_stateless() ||\n                     context.has_only_continuous_state() || is_discrete_system);\n\n  // Create an autodiff version of the system.\n  std::unique_ptr<System<AutoDiffXd>> autodiff_system =\n      drake::systems::System<double>::ToAutoDiffXd(system);\n\n  // Initialize autodiff.\n  std::unique_ptr<Context<AutoDiffXd>> autodiff_context =\n      autodiff_system->CreateDefaultContext();\n  autodiff_context->SetTimeStateAndParametersFrom(context);\n  autodiff_system->FixInputPortsFrom(system, context, autodiff_context.get());\n\n  const InputPort<AutoDiffXd>* input_port =\n      autodiff_system->get_input_port_selection(input_port_index);\n  const OutputPort<AutoDiffXd>* output_port =\n      autodiff_system->get_output_port_selection(output_port_index);\n\n  // Verify that the input port is not abstract valued.\n  if (input_port &&\n      input_port->get_data_type() == PortDataType::kAbstractValued) {\n    throw std::logic_error(\n        \"Port requested for differentiation is abstract, and differentiation \"\n        \"of abstract ports is not supported.\");\n  }\n\n  const int num_inputs = input_port ? input_port->size() : 0;\n  const int num_outputs = output_port ? output_port->size() : 0;\n\n  const Eigen::VectorXd x0 =\n      context.is_stateless()\n          ? Eigen::VectorXd::Zero(0)\n          : ((context.has_only_continuous_state())\n                 ? context.get_continuous_state_vector().CopyToVector()\n                 : context.get_discrete_state(0).get_value());\n  const int num_states = x0.size();\n\n  Eigen::VectorXd u0 = Eigen::VectorXd::Zero(num_inputs);\n  if (input_port) {\n    u0 = system.get_input_port(input_port->get_index()).Eval(context);\n  }\n\n  auto autodiff_args = math::initializeAutoDiffTuple(x0, u0);\n  if (input_port) {\n    VectorX<AutoDiffXd> input_vector = std::get<1>(autodiff_args);\n    input_port->FixValue(autodiff_context.get(), input_vector);\n  }\n\n  Eigen::MatrixXd A(num_states, num_states), B(num_states, num_inputs);\n  Eigen::VectorXd f0(num_states);\n  if (num_states > 0) {\n    if (autodiff_context->has_only_continuous_state()) {\n      autodiff_context->get_mutable_continuous_state_vector().SetFromVector(\n          std::get<0>(autodiff_args));\n      std::unique_ptr<ContinuousState<AutoDiffXd>> autodiff_xdot =\n          autodiff_system->AllocateTimeDerivatives();\n      autodiff_system->CalcTimeDerivatives(*autodiff_context,\n                                           autodiff_xdot.get());\n      auto autodiff_xdot_vec = autodiff_xdot->CopyToVector();\n\n      const Eigen::MatrixXd AB =\n          math::autoDiffToGradientMatrix(autodiff_xdot_vec);\n      A = AB.leftCols(num_states);\n      B = AB.rightCols(num_inputs);\n\n      const Eigen::VectorXd xdot0 =\n          math::autoDiffToValueMatrix(autodiff_xdot_vec);\n\n      if (equilibrium_check_tolerance &&\n          !xdot0.isZero(*equilibrium_check_tolerance)) {\n        throw std::runtime_error(\n            \"The nominal operating point (x0,u0) is not an equilibrium point \"\n            \"of \"\n            \"the system.  Without additional information, a time-invariant \"\n            \"linearization of this system is not well defined.\");\n      }\n\n      f0 = xdot0 - A * x0 - B * u0;\n    } else {\n      DRAKE_ASSERT(is_discrete_system);\n      auto& autodiff_x0 =\n          autodiff_context->get_mutable_discrete_state().get_mutable_vector();\n      autodiff_x0.SetFromVector(std::get<0>(autodiff_args));\n      std::unique_ptr<DiscreteValues<AutoDiffXd>> autodiff_x1 =\n          autodiff_system->AllocateDiscreteVariables();\n      autodiff_system->CalcDiscreteVariableUpdates(*autodiff_context,\n                                                   autodiff_x1.get());\n      auto autodiff_x1_vec = autodiff_x1->get_vector().CopyToVector();\n\n      const Eigen::MatrixXd AB =\n          math::autoDiffToGradientMatrix(autodiff_x1_vec);\n      A = AB.leftCols(num_states);\n      B = AB.rightCols(num_inputs);\n\n      const Eigen::VectorXd x1 = math::autoDiffToValueMatrix(autodiff_x1_vec);\n\n      if (equilibrium_check_tolerance &&\n          !(x1 - x0).isZero(*equilibrium_check_tolerance)) {\n        throw std::runtime_error(\n            \"The nominal operating point (x0,u0) is not an equilibrium point \"\n            \"of the system.  Without additional information, a time-invariant \"\n            \"linearization of this system is not well defined.\");\n      }\n\n      f0 = x1 - A * x0 - B * u0;\n    }\n  } else {\n    DRAKE_ASSERT(num_states == 0);\n    A = Eigen::MatrixXd(0, 0);\n    B = Eigen::MatrixXd(0, num_inputs);\n    f0 = Eigen::VectorXd(0);\n  }\n\n  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(num_outputs, num_states);\n  Eigen::MatrixXd D = Eigen::MatrixXd::Zero(num_outputs, num_inputs);\n  Eigen::VectorXd y0 = Eigen::VectorXd::Zero(num_outputs);\n\n  if (output_port) {\n    const auto& autodiff_y0 = output_port->Eval(*autodiff_context);\n    const Eigen::MatrixXd CD = math::autoDiffToGradientMatrix(autodiff_y0);\n    C = CD.leftCols(num_states);\n    D = CD.rightCols(num_inputs);\n\n    const Eigen::VectorXd y = math::autoDiffToValueMatrix(autodiff_y0);\n\n    // Note: No tolerance check needed here.  We have defined that the output\n    // for the system produced by Linearize is in the coordinates (y-y0).\n\n    y0 = y - C * x0 - D * u0;\n  }\n\n  return std::make_unique<AffineSystem<double>>(A, B, f0, C, D, y0,\n                                                time_period);\n}\n\n}  // namespace\n\nstd::unique_ptr<LinearSystem<double>> Linearize(\n    const System<double>& system, const Context<double>& context,\n    std::variant<InputPortSelection, InputPortIndex> input_port_index,\n    std::variant<OutputPortSelection, OutputPortIndex> output_port_index,\n    double equilibrium_check_tolerance) {\n  std::unique_ptr<AffineSystem<double>> affine =\n      DoFirstOrderTaylorApproximation(\n          system, context, std::move(input_port_index),\n          std::move(output_port_index), equilibrium_check_tolerance);\n\n  return std::make_unique<LinearSystem<double>>(affine->A(), affine->B(),\n                                                affine->C(), affine->D(),\n                                                affine->time_period());\n}\n\nstd::unique_ptr<AffineSystem<double>> FirstOrderTaylorApproximation(\n    const System<double>& system, const Context<double>& context,\n    std::variant<InputPortSelection, InputPortIndex> input_port_index,\n    std::variant<OutputPortSelection, OutputPortIndex> output_port_index) {\n  return DoFirstOrderTaylorApproximation(system, context,\n                                         std::move(input_port_index),\n                                         std::move(output_port_index));\n}\n\n/// Returns the controllability matrix:  R = [B, AB, ..., A^{n-1}B].\nEigen::MatrixXd ControllabilityMatrix(const LinearSystem<double>& sys) {\n  DRAKE_DEMAND(sys.time_period() == 0.0);\n  // TODO(russt): handle the discrete time case\n\n  const int num_states = sys.B().rows(), num_inputs = sys.B().cols();\n  Eigen::MatrixXd R(num_states, num_states * num_inputs);\n  R.leftCols(num_inputs) = sys.B();\n  for (int i = 1; i < num_states; i++) {\n    R.middleCols(num_inputs * i, num_inputs) =\n        sys.A() * R.middleCols(num_inputs * (i - 1), num_inputs);\n  }\n  return R;\n}\n\n/// Returns true iff the controllability matrix is full row rank.\nbool IsControllable(const LinearSystem<double>& sys,\n                    std::optional<double> threshold) {\n  const auto R = ControllabilityMatrix(sys);\n  Eigen::ColPivHouseholderQR<Eigen::MatrixXd> lu_decomp(R);\n  if (threshold) {\n    lu_decomp.setThreshold(threshold.value());\n  }\n  return lu_decomp.rank() == sys.A().rows();\n}\n\n/// Returns the observability matrix: O = [ C; CA; ...; CA^{n-1} ].\nEigen::MatrixXd ObservabilityMatrix(const LinearSystem<double>& sys) {\n  DRAKE_DEMAND(sys.time_period() == 0.0);\n  // TODO(russt): handle the discrete time case\n\n  const int num_states = sys.C().cols(), num_outputs = sys.C().rows();\n  Eigen::MatrixXd O(num_states * num_outputs, num_states);\n  O.topRows(num_outputs) = sys.C();\n  for (int i = 1; i < num_states; i++) {\n    O.middleRows(num_outputs * i, num_outputs) =\n        O.middleRows(num_outputs * (i - 1), num_outputs) * sys.A();\n  }\n  return O;\n}\n\n/// Returns true iff the observability matrix is full column rank.\nbool IsObservable(const LinearSystem<double>& sys,\n                  std::optional<double> threshold) {\n  const auto O = ObservabilityMatrix(sys);\n  Eigen::ColPivHouseholderQR<Eigen::MatrixXd> lu_decomp(O);\n  if (threshold) {\n    lu_decomp.setThreshold(threshold.value());\n  }\n  return lu_decomp.rank() == sys.A().rows();\n}\n\n}  // namespace systems\n}  // namespace drake\n\nDRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(\n    class ::drake::systems::LinearSystem)\n\nDRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(\n    class ::drake::systems::TimeVaryingLinearSystem)\n", "meta": {"hexsha": "d3c07117e715116e50de790bb004505234cfd889", "size": 12636, "ext": "cc", "lang": "C++", "max_stars_repo_path": "systems/primitives/linear_system.cc", "max_stars_repo_name": "RobotLocomotion/drake-python3.7", "max_stars_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:01:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T04:52:04.000Z", "max_issues_repo_path": "systems/primitives/linear_system.cc", "max_issues_repo_name": "RobotLocomotion/drake-python3.7", "max_issues_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "systems/primitives/linear_system.cc", "max_forks_repo_name": "RobotLocomotion/drake-python3.7", "max_forks_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T12:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T12:05:39.000Z", "avg_line_length": 39.4875, "max_line_length": 80, "alphanum_fraction": 0.6695948085, "num_tokens": 3067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.5, "lm_q1q2_score": 0.29255058433636155}}
{"text": "/***\n *  $Id$\n **\n *  File: performance_indicators_diss.hpp\n *  Created: May 9, 2012\n *\n *  Author: Olga Wodo, Baskar Ganapathysubramanian\n *  Copyright (c) 2012 Olga Wodo, Baskar Ganapathysubramanian\n *  See accompanying LICENSE.\n *\n *  This file is part of GraSPI.\n */\n\n#ifndef PERFORMANCE_INDICATORS_DISS_HPP\n#define PERFORMANCE_INDICATORS_DISS_HPP\n\n#include <climits>\n#include <sstream>\n\n#include \"graspi_types.hpp\"\n#include \"graph_dijkstra.hpp\"\n#include \"graspi_predicates.hpp\"\n#include <boost/graph/filtered_graph.hpp>\n\n\nnamespace graspi {\n\n  struct foo_w_diss{\n      double A1,B1,C1;\n      foo_w_diss(){ A1=6.265; B1=-23.0; C1=17.17; }\n      double operator()(double d)const{\n\t  return A1*exp(-((d-B1)/C1)*((d-B1)/C1));\n      }\n  };\n\n  inline int\n  identify_n_vertices_within_distance( const std::vector<float>& d,\n\t\t\t\t       double Ld){\n      int n_Ld = 0;\n      for(unsigned int i = 0; i < d.size(); i++){\n\t  if( (d[i] < Ld) && (d[i] > 0) ) n_Ld++;\n      }\n      return n_Ld;\n  }\n\n  inline double\n  identify_weighted_vertices_within_distance( const std::vector<float>& d,\n\t\t\t\t\t      double Ld){\n      double wn_Ld = 0;\n      foo_w_diss wfoo;\n\n      for(unsigned int i = 0; i < d.size(); i++){\n\t  double d_i = d[i];\n\t  double wd_i = wfoo(d_i);\n\t  if( (d_i < Ld) && (d_i > 0) ) wn_Ld+= wd_i;\n      }\n      return wn_Ld;\n  }\n\n  inline std::pair<int,double>\n  identify_n_weighted_vertices_within_distance( const std::vector<float>& d,\n\t\t\t\t\t\tdouble Ld){\n      double wn_Ld = 0;\n      int n_Ld = 0;\n      foo_w_diss wfoo;\n\n      for(unsigned int i = 0; i < d.size(); i++){\n\t  double d_i = d[i];\n\t  double wd_i = wfoo(d_i);\n\t  if( (d_i < Ld) && (d_i > 0) ){\n\t      wn_Ld+= wd_i;\n\t      n_Ld++;\n\t  }\n      }\n      return std::pair<int,double>(n_Ld,wn_Ld);\n  }\n\n\n  inline std::pair<double,double>\n  wf_diss(\n\t  graph_t* G, const dim_g_t& d_g, const vertex_colors_t& C,\n\t  const edge_weights_t& W, const vertex_ccs_t& vCC,\n\t  const ccs_t& CC,\n\t  double Ld,\n\t  const std::string& filename_ColorToGreen,\n\t  const std::string& filename_WColorToGreen,\n\t  COLOR color = BLACK,\n\t  COLOR green = GREEN\n\t  ){\n      int n_color = 0;\n      int n_color_Ld = 0;\n      double wn_color_Ld = 0;\n\n      connect_color_green pred(*G,C,color,green);\n      unsigned int n = boost::num_vertices(*G);\n      vertex_t int_id = d_g.id(green);\n      std::vector<float> d(n);\n\n      determine_shortest_distances( G, W, int_id, pred, d);\n\n      foo_w_diss wfoo;\n      std::ostringstream oss_out_d;\n      std::ostringstream oss_out_wd;\n      for (unsigned int i = 0; i < d.size(); i++) {\n\t  unsigned int c = C[i];\n\t  if (c == color) n_color++;\n\t  if ( ( c == color )\n\t       && ( fabs(d[i]) < std::numeric_limits<float>::max() )\n\t       ) {\n\t      double d_i = d[i];\n\t      oss_out_d  << d_i       << std::endl;\n\t      oss_out_wd << d_i << \" \" << wfoo(d_i) << std::endl;\n\t  }\n      }\n      std::ofstream f_out(filename_ColorToGreen.c_str());\n      std::string buffer = oss_out_d.str();\n      int size = oss_out_d.str().size();\n      f_out.write (buffer.c_str(),size);\n      f_out.close();\n      f_out.open(filename_WColorToGreen.c_str());\n      buffer = oss_out_wd.str();\n      size = oss_out_wd.str().size();\n      f_out.write (buffer.c_str(),size);\n      f_out.close();\n\n      std::pair<int,double> pLd\n\t  = identify_n_weighted_vertices_within_distance(d,Ld);\n      n_color_Ld = pLd.first;\n      wn_color_Ld = pLd.second;\n\n#ifdef DEBUG\n      std::cout << \"[DEBUG] Number of \" << color << \"vertices: \"\n\t\t<< n_color << std::endl\n\t\t<< \"[DEBUG] Number of \" << color << \"vertices in \"\n\t\t<< Ld << \" distance to green: \"\n\t\t<< n_color_Ld << std::endl;\n#endif\n\n      return std::pair<double, double>(\n\t\t\t\t       (double)wn_color_Ld/n_color,\n\t\t\t\t       (double)n_color_Ld/n_color\n\t\t\t\t       );\n  }\n\n\n  inline std::pair<double,double>\n  wf_diss(\n\t  graph_t* G, const dim_g_t& d_g, const vertex_colors_t& C,\n\t  const edge_weights_t& W, const vertex_ccs_t& vCC,\n\t  const ccs_t& CC,\n\t  double Ld,\n\t  COLOR color = BLACK,\n\t  COLOR green = GREEN\n\t  ){\n      int n_color = 0;\n      int n_color_Ld = 0;\n      double wn_color_Ld = 0;\n\n      connect_color_green pred(*G,C,color,green);\n      unsigned int n = boost::num_vertices(*G);\n      vertex_t int_id = d_g.id(green);\n      std::vector<float> d(n);\n\n      determine_shortest_distances( G, W, int_id, pred, d);\n\n      foo_w_diss wfoo;\n      for (unsigned int i = 0; i < d.size(); i++) {\n\t  unsigned int c = C[i];\n\t  if (c == color) n_color++;\n      }\n\n      std::pair<int,double> pLd\n\t  = identify_n_weighted_vertices_within_distance(d,Ld);\n      n_color_Ld = pLd.first;\n      wn_color_Ld = pLd.second;\n\n      return std::pair<double, double>(\n\t\t\t\t       (double)wn_color_Ld/n_color,\n\t\t\t\t       (double)n_color_Ld/n_color\n\t\t\t\t       );\n  }\n\n\n}\n#endif\n", "meta": {"hexsha": "b4f6b009c46dafe18c7505140223a8de7b4298b9", "size": 4757, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/performance_indicators_diss.hpp", "max_stars_repo_name": "wd15/graspi", "max_stars_repo_head_hexsha": "cbdbee28062dbc18005a506f307171702ac249be", "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/performance_indicators_diss.hpp", "max_issues_repo_name": "wd15/graspi", "max_issues_repo_head_hexsha": "cbdbee28062dbc18005a506f307171702ac249be", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/performance_indicators_diss.hpp", "max_forks_repo_name": "wd15/graspi", "max_forks_repo_head_hexsha": "cbdbee28062dbc18005a506f307171702ac249be", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-27T19:05:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T19:05:48.000Z", "avg_line_length": 25.5752688172, "max_line_length": 76, "alphanum_fraction": 0.5965944923, "num_tokens": 1455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.5, "lm_q1q2_score": 0.29255058433636155}}
{"text": "/*\r\n(c) 2012 Fengtao Fan\r\n*/\r\n#include \"SimpleGraph.h\"\r\n#include \"SimpleMesh.h\"\r\n#include \"canonical_loops.h\"\r\n#include \"edge_annotations_gauss.h\"\r\n#include \"CycleOptimization/Annotation/AnnotationComputation.h\"\r\n#include \"psbmReebGraph.h\"\r\n\r\n#include <boost/progress.hpp>\r\n\r\n#include <fstream>\r\n#include <sstream>\r\n\r\n#include <map>\r\n\r\n//_simpGraph_vec meshGraph;\r\n//_SimpleMesh cycMesh;\r\n//std::vector<Vector3>   meshNormal;\r\nvoid LoadCycleData(psbmReebGraph &reebGraph, std::vector<std::vector<int> > &basis_h_loops,\r\n                   std::vector<std::vector<int> > &basis_v_loops, std::vector<int> &base_pt_vec) {\r\n    //\r\n    std::vector<bool> initVerticalLoopsType;\r\n    // set the flag bit for handle or tunnel loops\r\n    for (unsigned int i = 0; i < reebGraph.initVerticalLoops->size(); i++) {\r\n        if ((*reebGraph.initVerticalLoops)[i].pathType) {// this is a vertical loop\r\n            initVerticalLoopsType.push_back(true);\r\n        } else {\r\n            initVerticalLoopsType.push_back(false);\r\n        }\r\n    }\r\n    // Store the critical points\r\n    base_pt_vec.reserve(2 * reebGraph.criticalPairing->size());\r\n    for (unsigned int j = 0; j < reebGraph.criticalPairing->size(); j++) {\r\n        base_pt_vec.push_back((*reebGraph.criticalPairing)[j].first);\r\n        base_pt_vec.push_back((*reebGraph.criticalPairing)[j].second);\r\n    }\r\n    //\r\n    const int tot_genus = (int) reebGraph.vecVerticalLoopEdgePathOnMesh_Vertex.size();\r\n    basis_v_loops.reserve(tot_genus);\r\n    basis_h_loops.reserve(tot_genus);\r\n    // store v-basis\r\n    for (int i = 0; i < tot_genus; i++) {\r\n        std::vector<int> tempIntVec;\r\n        int edges_num = 0;\r\n        int row_num = i;\r\n        //\r\n        if (!initVerticalLoopsType[i])\r\n            row_num += tot_genus;\r\n        //\r\n        for (std::list<std::pair<int, int> >::iterator listIter = (reebGraph.invLinkNumbersMatrix)[row_num].begin();\r\n             listIter != (reebGraph.invLinkNumbersMatrix)[row_num].end(); listIter++) {\r\n            int col_num = listIter->first;\r\n            int counter = abs(listIter->second);\r\n            if (col_num >= tot_genus) {// it is a horizontal loop\r\n                edges_num +=\r\n                        counter * (int) (reebGraph.vecHorizontalLoopEdgePathOnMesh_Edge)[col_num - tot_genus].size();\r\n            } else {\r\n                edges_num += counter * (int) (reebGraph.vecVerticalLoopEdgePathOnMesh_Edge)[col_num].size();\r\n            }\r\n        }\r\n        //\r\n        //sstr << edges_num << std::endl;\r\n        tempIntVec.reserve(edges_num + 2);\r\n        for (std::list<std::pair<int, int> >::iterator listIter = (reebGraph.invLinkNumbersMatrix)[row_num].begin();\r\n             listIter != (reebGraph.invLinkNumbersMatrix)[row_num].end(); listIter++) {\r\n            int col_num = listIter->first;\r\n            int counter = abs(listIter->second);\r\n            if (col_num >= tot_genus) {// it is a horizontal loop\r\n                for (int j = 0; j < counter; j++) {\r\n                    for (std::vector<int>::iterator vIter = (reebGraph.vecHorizontalLoopEdgePathOnMesh_Edge)[col_num -\r\n                                                                                                             tot_genus].begin();\r\n                         vIter !=\r\n                         (reebGraph.vecHorizontalLoopEdgePathOnMesh_Edge)[col_num - tot_genus].end(); vIter++) {\r\n                        //sstr << *vIter << \" \";\r\n                        tempIntVec.push_back(*vIter);\r\n                    }\r\n                }\r\n            } else {\r\n                for (int j = 0; j < counter; j++) {\r\n                    for (std::vector<int>::iterator vIter = (reebGraph.vecVerticalLoopEdgePathOnMesh_Edge)[col_num].begin();\r\n                         vIter != (reebGraph.vecVerticalLoopEdgePathOnMesh_Edge)[col_num].end(); vIter++) {\r\n                        //sstr << *vIter << \" \";\r\n                        tempIntVec.push_back(*vIter);\r\n                    }\r\n                }\r\n            }\r\n        }\r\n        //\r\n        basis_v_loops.push_back(tempIntVec);\r\n        //sstr << std::endl;\r\n    }\r\n    //store h-basis\r\n    for (int i = 0; i < tot_genus; i++) {\r\n        std::vector<int> hTempIntVec;\r\n        int edges_num = 0;\r\n        int row_num = i;\r\n        //\r\n        if (initVerticalLoopsType[i])\r\n            row_num += tot_genus;\r\n        //\r\n        for (std::list<std::pair<int, int> >::iterator listIter = (reebGraph.invLinkNumbersMatrix)[row_num].begin();\r\n             listIter != (reebGraph.invLinkNumbersMatrix)[row_num].end(); listIter++) {\r\n            int col_num = listIter->first;\r\n            int counter = abs(listIter->second);\r\n            if (col_num >= tot_genus) {// it is a horizontal loop\r\n                edges_num +=\r\n                        counter * (int) (reebGraph.vecHorizontalLoopEdgePathOnMesh_Edge)[col_num - tot_genus].size();\r\n            } else {\r\n                edges_num += counter * (int) (reebGraph.vecVerticalLoopEdgePathOnMesh_Edge)[col_num].size();\r\n            }\r\n        }\r\n        //\r\n        //sstr << edges_num << std::endl;\r\n        hTempIntVec.reserve(edges_num + 2);\r\n        for (std::list<std::pair<int, int> >::iterator listIter = (reebGraph.invLinkNumbersMatrix)[row_num].begin();\r\n             listIter != (reebGraph.invLinkNumbersMatrix)[row_num].end(); listIter++) {\r\n            int col_num = listIter->first;\r\n            int counter = abs(listIter->second);\r\n            if (col_num >= tot_genus) {// it is a horizontal loop\r\n                for (int j = 0; j < counter; j++) {\r\n                    for (std::vector<int>::iterator vIter = (reebGraph.vecHorizontalLoopEdgePathOnMesh_Edge)[col_num -\r\n                                                                                                             tot_genus].begin();\r\n                         vIter !=\r\n                         (reebGraph.vecHorizontalLoopEdgePathOnMesh_Edge)[col_num - tot_genus].end(); vIter++) {\r\n                        //sstr << *vIter << \" \";\r\n                        hTempIntVec.push_back(*vIter);\r\n                    }\r\n                }\r\n            } else {\r\n                for (int j = 0; j < counter; j++) {\r\n                    for (std::vector<int>::iterator vIter = (reebGraph.vecVerticalLoopEdgePathOnMesh_Edge)[col_num].begin();\r\n                         vIter != (reebGraph.vecVerticalLoopEdgePathOnMesh_Edge)[col_num].end(); vIter++) {\r\n                        //sstr << *vIter << \" \";\r\n                        hTempIntVec.push_back(*vIter);\r\n                    }\r\n                }\r\n            }\r\n        }\r\n        //sstr << std::endl;\r\n        basis_h_loops.push_back(hTempIntVec);\r\n    }\r\n    return;\r\n}\r\n\r\nvoid AssembleMeshGraph(_simpGraph_vec &meshGraph, _SimpleMesh &mesh, std::vector<float> &sqEdgeLength,\r\n                       std::set<int> &extraVertices, const float fScaleRatio) {\r\n    meshGraph.InitNodes((int) mesh.vecVertex.size());\r\n    //\r\n    std::vector<bool> vertexFlag(mesh.vecVertex.size(), false);\r\n    //\r\n    for (std::set<int>::iterator sIter = extraVertices.begin();\r\n         sIter != extraVertices.end(); sIter++) {\r\n        vertexFlag[*sIter] = true;\r\n    }\r\n    //\r\n    std::vector<int> nonExistEdges;\r\n    //\r\n    float totEdgeLen = 0.0;\r\n    for (unsigned int eid = 0; eid < mesh.vecEdge.size(); eid++) {\r\n        int v_a = mesh.vecEdge[eid].v0;\r\n        int v_b = mesh.vecEdge[eid].v1;\r\n\r\n        Vector3 p_a(mesh.vecVertex[v_a].x, mesh.vecVertex[v_a].y, mesh.vecVertex[v_a].z);\r\n        Vector3 p_b(mesh.vecVertex[v_b].x, mesh.vecVertex[v_b].y, mesh.vecVertex[v_b].z);\r\n\r\n        //\r\n        sqEdgeLength.push_back(norm(p_a - p_b) * fScaleRatio);\r\n        //\r\n\r\n        meshGraph.AddEdge(v_a, v_b, eid);\r\n        //\r\n        totEdgeLen += sqEdgeLength.back();\r\n        //\r\n        if (vertexFlag[v_a] || vertexFlag[v_b]) {\r\n            nonExistEdges.push_back(eid);\r\n        }\r\n    }\r\n    //\r\n    for (unsigned int i = 0; i < nonExistEdges.size(); i++) {\r\n        //\r\n        sqEdgeLength[nonExistEdges[i]] = totEdgeLen;// std::numeric_limits<float>::max(); // totEdgeLen* 2;\r\n    }\r\n    return;\r\n}\r\n\r\nvoid AssembleMeshGraph(_simpGraph_vec &meshGraph, _SimpleMesh &mesh, std::vector<float> &sqEdgeLength,\r\n                       const float fScaleRatio) {\r\n    meshGraph.InitNodes((int) mesh.vecVertex.size());\r\n    //\r\n    for (unsigned int eid = 0; eid < mesh.vecEdge.size(); eid++) {\r\n        int v_a = mesh.vecEdge[eid].v0;\r\n        int v_b = mesh.vecEdge[eid].v1;\r\n\r\n        Vector3 p_a(mesh.vecVertex[v_a].x, mesh.vecVertex[v_a].y, mesh.vecVertex[v_a].z);\r\n        Vector3 p_b(mesh.vecVertex[v_b].x, mesh.vecVertex[v_b].y, mesh.vecVertex[v_b].z);\r\n\r\n        //\r\n        sqEdgeLength.push_back(norm(p_a - p_b) * fScaleRatio);\r\n        //\r\n\r\n        meshGraph.AddEdge(v_a, v_b, eid);\r\n    }\r\n}\r\n\r\n\r\nfloat BasisWeight(std::vector<std::set<int> > &basis, std::vector<float> sqEdgeLen) {\r\n    float tot_len = 0.0;\r\n    for (unsigned int i = 0; i < basis.size(); i++) {\r\n        for (std::set<int>::iterator sIter = basis[i].begin();\r\n             sIter != basis[i].end(); sIter++) {\r\n            tot_len += sqEdgeLen[*sIter];\r\n        }\r\n    }\r\n    return tot_len;\r\n}\r\n\r\nfloat BasisWeight(std::vector<std::vector<int> > &basis, std::vector<float> sqEdgeLen) {\r\n    float tot_len = 0.0;\r\n    for (unsigned int i = 0; i < basis.size(); i++) {\r\n        for (std::vector<int>::iterator vIter = basis[i].begin();\r\n             vIter != basis[i].end(); vIter++) {\r\n            tot_len += sqEdgeLen[*vIter];\r\n        }\r\n    }\r\n    return tot_len;\r\n}\r\n\r\nvoid CycleLocalOptimization_bdry(_SimpleMesh &locMesh, psbmReebGraph &reebgraph, std::vector<int> &OrientTriangles,\r\n                                 std::vector<std::set<int> > &out_v_basis_loops,\r\n                                 std::vector<std::set<int> > &out_h_basis_loops,\r\n                                 std::set<int> extraVertices,\r\n                                 const float fScaleRatio) {//\r\n    _simpGraph_vec locMeshGraph;\r\n    //\r\n    edge_annotation_computing edge_anno_proxy;\r\n    //\r\n    //\r\n    ComputeAnnotation(locMesh, edge_anno_proxy.edge_annotations, OrientTriangles);\r\n    edge_anno_proxy.vec_size = (int) edge_anno_proxy.edge_annotations[0].size();\r\n    //\r\n    if (edge_anno_proxy.vec_size == 0) {\r\n        std::cout << \"TRIVIAL LOOPS\" << std::endl;\r\n        exit(0);\r\n    }\r\n    std::vector<float> sqEdgeLen;\r\n    AssembleMeshGraph(locMeshGraph, locMesh, sqEdgeLen, extraVertices, fScaleRatio);\r\n    //\r\n    edge_anno_proxy.SetMeshPtr(&locMesh);\r\n    //edge_anno_proxy.ReadEdgeAnnotationsFromFile(argv[2]);\r\n//{//\r\n//\t//\r\n//\tedge_annotation_computing edge_anno_proxy;\r\n//\t//\r\n//\t//\r\n//\tLoadData(argv[1], edge_anno_proxy);\r\n//\t//\r\n//\tstd::set<int> extraVertices;\r\n//\tReadBoundaries(argv[argc - 1], extraVertices);\r\n//\t//\r\n//\tstd::vector<float> sqEdgeLen;\r\n//\tAssembleMeshGraph(meshGraph, cycMesh, sqEdgeLen, extraVertices);\r\n//\t//\r\n//\tedge_anno_proxy.SetMeshPtr(&cycMesh);\r\n//\t//edge_anno_proxy.ReadEdgeAnnotationsFromFile(argv[2]);\r\n    //\r\n    std::vector<std::vector<int> > basis_h_loops;\r\n    std::vector<std::vector<int> > basis_v_loops;\r\n    //\r\n    std::vector<Annotation_Type> basis_h_annotations;\r\n    std::vector<Annotation_Type> basis_v_annotations;\r\n    //\r\n    std::vector<int> base_pt_vec;\r\n    //\r\n    LoadCycleData(reebgraph, basis_h_loops, basis_v_loops, base_pt_vec);\r\n    //ReadBasisLoops(argv[4], basis_h_loops);\r\n    //ReadBasisLoops(argv[5], basis_v_loops);\r\n\r\n    edge_anno_proxy.CheckTwoGroupVectorOrthogonality(basis_v_loops, basis_v_annotations, basis_h_loops,\r\n                                                     basis_h_annotations);\r\n    //\r\n    canonical_loops_computing cano_loop_proxy;\r\n    //\r\n    //\r\n    //std::set<int> base_pt_set;\r\n    //for (unsigned int i = 0; i < basis_v_loops.size(); i++)\r\n    //{\r\n    //\tfor (unsigned int j = 0; j < basis_v_loops[i].size(); j++)\r\n    //\t{\r\n    //\t\tbase_pt_set.insert(mesh.vecEdge[basis_v_loops[i][j]].v0);\r\n    //\t\tbase_pt_set.insert(mesh.vecEdge[basis_v_loops[i][j]].v1);\r\n    //\t}\r\n    //}\r\n    //std::vector<int> base_pt_vec(base_pt_set.begin(), base_pt_set.end());//\r\n    //\r\n    //std::vector<int> base_pt_vec;\r\n    //ReadBasisCriticalPoints(argv[3], base_pt_vec);\r\n    std::set<int> base_pt_set(base_pt_vec.begin(), base_pt_vec.end());\r\n    //\r\n    //std::cout << \"old base_pt_vec \" << base_pt_vec.size() << std::endl;\r\n    //\r\n    cano_loop_proxy.SetGraphPtr(&locMeshGraph);\r\n    cano_loop_proxy.SetEdgeWeights(sqEdgeLen);\r\n    cano_loop_proxy.SetBasePointArray(base_pt_vec);\r\n    cano_loop_proxy.SetMeshPtr(&locMesh);\r\n    cano_loop_proxy.SetMeshGenus(edge_anno_proxy.vec_size / 2);\r\n    //\r\n    //cano_loop_proxy.ResetBaseVertices(basis_h_loops, edge_anno_proxy);\r\n    //std::cout << \"new base_pt_vec \" << cano_loop_proxy.base_pt_index.size() << std::endl;\r\n    //\r\n    //bool bPartialBasis = false;\r\n    std::cout << \"Time for shortening handle and tunnel loops : \" << std::endl;\r\n    float cur_basis_h_len = BasisWeight(basis_h_loops, sqEdgeLen);\r\n    float cur_basis_v_len = BasisWeight(basis_v_loops, sqEdgeLen);\r\n    std::vector<std::set<int> > tmp_short_h_basis_loop;\r\n    std::vector<std::set<int> > tmp_short_v_basis_loop;\r\n    {\r\n        // starting measuring the time\r\n        boost::progress_timer t;\r\n        //\r\n        std::vector<std::set<int> > cano_loops;\r\n        std::vector<int> non_tree_edges;\r\n        std::vector<Annotation_Type> cano_loop_annotations;\r\n        std::set<std::pair<float, int>, myFloatIntPairLessThan> sorted_cano_loops;\r\n        std::vector<int> non_tree_edges_for_sorted_cano_loops;\r\n        //\r\n        float pre_basis_h_len = 0.0;\r\n        float pre_basis_v_len = 0.0;\r\n\r\n\r\n        //\r\n        int iterNumber = 0;\r\n        // optimize the all loops together\r\n        do {\r\n            tmp_short_h_basis_loop.clear();\r\n            tmp_short_h_basis_loop.reserve(basis_h_loops.size());\r\n            tmp_short_v_basis_loop.clear();\r\n            tmp_short_v_basis_loop.reserve(basis_v_loops.size());\r\n            base_pt_vec.clear();\r\n            //\r\n            cano_loop_proxy.compute_canonical_loops_fibo(cano_loops, non_tree_edges, cano_loop_annotations,\r\n                                                         sorted_cano_loops, edge_anno_proxy);\r\n            //\r\n            if (edge_anno_proxy.ComputeShortestCanonicalLoops(basis_h_loops, basis_h_annotations, cano_loops,\r\n                                                              non_tree_edges,\r\n                                                              cano_loop_annotations, sorted_cano_loops,\r\n                                                              tmp_short_h_basis_loop,\r\n                                                              non_tree_edges_for_sorted_cano_loops)) {\r\n                std::cout << \".\";//ompletly use short loops\" << std::endl;\r\n            } else {\r\n                std::cout << \"*\"; //artially use short loops\" << std::endl;\r\n                //bPartialBasis = true;\r\n            }\r\n            /**/\r\n            cano_loop_proxy.base_pt_index.clear();//\r\n            cano_loop_proxy.base_pt_index.reserve(non_tree_edges_for_sorted_cano_loops.size() * 3);\r\n            for (unsigned int i = 0; i < non_tree_edges_for_sorted_cano_loops.size(); i++) {\r\n                int edge_idx = non_tree_edges_for_sorted_cano_loops[i];\r\n                //std::cout << edge_idx << std::endl;\r\n                if ((edge_idx >= 0) && base_pt_set.find(locMesh.vecEdge[edge_idx].v0) == base_pt_set.end()) {\r\n                    base_pt_set.insert(locMesh.vecEdge[edge_idx].v0);\r\n                    cano_loop_proxy.base_pt_index.push_back(locMesh.vecEdge[edge_idx].v0);\r\n                }\r\n                //if (base_pt_set.find(mesh.vecEdge[edge_idx].v1) == base_pt_set.end())\r\n                //{\r\n                //\tbase_pt_set.insert(mesh.vecEdge[edge_idx].v1);\r\n                //\tcano_loop_proxy.base_pt_index.push_back(mesh.vecEdge[edge_idx].v1);\r\n                //}\r\n            }\r\n\r\n\r\n            if (edge_anno_proxy.ComputeShortestCanonicalLoops(basis_v_loops, basis_v_annotations, cano_loops,\r\n                                                              non_tree_edges,\r\n                                                              cano_loop_annotations, sorted_cano_loops,\r\n                                                              tmp_short_v_basis_loop,\r\n                                                              non_tree_edges_for_sorted_cano_loops)) {\r\n                std::cout << \".\"; //ompletly use short loops\" << std::endl;\r\n            } else {\r\n                std::cout << \"*\"; //artially use short loops\" << std::endl;\r\n                //bPartialBasis = true;\r\n            }\r\n            //\r\n            pre_basis_v_len = cur_basis_v_len;\r\n            pre_basis_h_len = cur_basis_h_len;\r\n            cur_basis_v_len = BasisWeight(tmp_short_v_basis_loop, sqEdgeLen);\r\n            cur_basis_h_len = BasisWeight(tmp_short_h_basis_loop, sqEdgeLen);\r\n            //\r\n            for (unsigned int i = 0; i < non_tree_edges_for_sorted_cano_loops.size(); i++) {\r\n                int edge_idx = non_tree_edges_for_sorted_cano_loops[i];\r\n                //std::cout << edge_idx << std::endl;\r\n                if ((edge_idx >= 0) && base_pt_set.find(locMesh.vecEdge[edge_idx].v0) == base_pt_set.end()) {\r\n                    base_pt_set.insert(locMesh.vecEdge[edge_idx].v0);\r\n                    cano_loop_proxy.base_pt_index.push_back(locMesh.vecEdge[edge_idx].v0);\r\n                }\r\n                //if (base_pt_set.find(mesh.vecEdge[edge_idx].v1) == base_pt_set.end())\r\n                //{\r\n                //\tbase_pt_set.insert(mesh.vecEdge[edge_idx].v1);\r\n                //\tcano_loop_proxy.base_pt_index.push_back(mesh.vecEdge[edge_idx].v1);\r\n                //}\r\n            }\r\n            //std::cout << iterNumber << \"\\t\";//<< \" new base pt set size \" << base_pt_set.size() << std::endl;\r\n            //std::cout << iterNumber << \" new base pt size \" << cano_loop_proxy.base_pt_index.size() << std::endl;\r\n            iterNumber++;\r\n            if (cano_loop_proxy.base_pt_index.empty())\r\n                break;\r\n            if (iterNumber > 2000)\r\n                break;\r\n\r\n        } while (abs(cur_basis_h_len - pre_basis_h_len) > 0.000001 ||\r\n                 abs(cur_basis_v_len - pre_basis_v_len) > 0.000001);\r\n        //\r\n        std::cout << std::endl;\r\n    }\r\n    //\r\n    //\r\n    out_h_basis_loops = tmp_short_h_basis_loop;\r\n    //\r\n    out_v_basis_loops = tmp_short_v_basis_loop;\r\n    return;\r\n}\r\n\r\nvoid CycleGlobalOptimization(_SimpleMesh &locMesh, psbmReebGraph &reebgraph, std::vector<int> &OrientTriangles,\r\n                             std::vector<std::set<int> > &out_v_basis_loops,\r\n                             std::vector<std::set<int> > &out_h_basis_loops,\r\n                             const float fScaleRatio) {//\r\n    _simpGraph_vec locMeshGraph;\r\n    //\r\n    edge_annotation_computing edge_anno_proxy;\r\n    //\r\n    //\r\n    ComputeAnnotation(locMesh, edge_anno_proxy.edge_annotations, OrientTriangles);\r\n    edge_anno_proxy.vec_size = (int) edge_anno_proxy.edge_annotations[0].size();\r\n    //\r\n    if (edge_anno_proxy.vec_size == 0) {\r\n        std::cout << \"TRIVIAL LOOPS\" << std::endl;\r\n        exit(0);\r\n    }\r\n    std::vector<float> sqEdgeLen;\r\n    AssembleMeshGraph(locMeshGraph, locMesh, sqEdgeLen, fScaleRatio);\r\n    //\r\n    edge_anno_proxy.SetMeshPtr(&locMesh);\r\n    //edge_anno_proxy.ReadEdgeAnnotationsFromFile(argv[2]);\r\n//{\r\n//\t//\r\n//\tedge_annotation_computing edge_anno_proxy;\r\n//\t//\r\n//\t//std::vector<int> meshTriangles;\r\n//\tLoadData(argv[1], edge_anno_proxy);\r\n//\t//\r\n//\tstd::vector<float> sqEdgeLen;\r\n//\tAssembleMeshGraph(meshGraph, cycMesh, sqEdgeLen);\r\n//\t//\r\n//\tedge_anno_proxy.SetMeshPtr(&cycMesh);\r\n//\t//edge_anno_proxy.ReadEdgeAnnotationsFromFile(argv[2]);\r\n//\t//\r\n//\t//std::vector<int> fvs;\r\n//\t//ComputeFeedbackVertexSet(edge_anno_proxy.edge_annotations, fvs);\r\n\r\n    std::vector<std::vector<int> > basis_h_loops;\r\n    std::vector<std::vector<int> > basis_v_loops;\r\n    std::vector<Annotation_Type> basis_h_annotations;\r\n    std::vector<Annotation_Type> basis_v_annotations;\r\n    //\r\n    std::vector<int> base_pt_vec;\r\n    //\r\n    LoadCycleData(reebgraph, basis_h_loops, basis_v_loops, base_pt_vec);\r\n    //\r\n    edge_anno_proxy.CheckTwoGroupVectorOrthogonality(basis_v_loops, basis_v_annotations, basis_h_loops,\r\n                                                     basis_h_annotations);\r\n    //\r\n    canonical_loops_computing cano_loop_proxy;\r\n    //\r\n\r\n    //ReadBasisCriticalPoints(argv[3], base_pt_vec);\r\n    std::set<int> base_pt_set(base_pt_vec.begin(), base_pt_vec.end());\r\n    //\r\n    std::cout << \"old base_pt_vec \" << base_pt_vec.size() << std::endl;\r\n    //\r\n    cano_loop_proxy.SetGraphPtr(&locMeshGraph);\r\n    cano_loop_proxy.SetEdgeWeights(sqEdgeLen);\r\n    cano_loop_proxy.SetBasePointArray(base_pt_vec);\r\n    cano_loop_proxy.SetMeshPtr(&locMesh);\r\n    cano_loop_proxy.SetMeshGenus(edge_anno_proxy.vec_size / 2);\r\n    //\r\n    //cano_loop_proxy.ResetBaseVertices(basis_h_loops, edge_anno_proxy);\r\n    //std::cout << \"new base_pt_vec \" << cano_loop_proxy.base_pt_index.size() << std::endl;\r\n    //\r\n    std::cout << \"in cano loops computation\" << std::endl;\r\n    // starting measuring time\r\n    boost::progress_timer t;\r\n    //\r\n    std::vector<std::set<int> > cano_loops;\r\n    std::vector<int> non_tree_edges;\r\n    std::vector<Annotation_Type> cano_loop_annotations;\r\n    std::set<std::pair<float, int>, myFloatIntPairLessThan> sorted_cano_loops;\r\n    std::vector<int> non_tree_edges_for_sorted_cano_loops;\r\n    //\r\n    float pre_basis_h_len = 0.0;\r\n    float pre_basis_v_len = 0.0;\r\n    float cur_basis_h_len = BasisWeight(basis_h_loops, sqEdgeLen);\r\n    float cur_basis_v_len = BasisWeight(basis_v_loops, sqEdgeLen);\r\n    std::vector<std::set<int> > tmp_short_h_basis_loop;\r\n    std::vector<std::set<int> > tmp_short_v_basis_loop;\r\n    //\r\n    int iterNumber = 0;\r\n    // compute the vertical loops first\r\n    do {\r\n        tmp_short_h_basis_loop.clear();\r\n        tmp_short_h_basis_loop.reserve(basis_h_loops.size());\r\n        tmp_short_v_basis_loop.clear();\r\n        tmp_short_v_basis_loop.reserve(basis_v_loops.size());\r\n        base_pt_vec.clear();\r\n        //\r\n        cano_loop_proxy.compute_canonical_loops_fibo(cano_loops, non_tree_edges, cano_loop_annotations,\r\n                                                     sorted_cano_loops, edge_anno_proxy);\r\n        //\r\n        if (edge_anno_proxy.ComputeShortestCanonicalLoops(basis_h_loops, basis_h_annotations, cano_loops,\r\n                                                          non_tree_edges,\r\n                                                          cano_loop_annotations, sorted_cano_loops,\r\n                                                          tmp_short_h_basis_loop,\r\n                                                          non_tree_edges_for_sorted_cano_loops)) {\r\n            std::cout << \"c \\t \";//ompletly use short loops\" << std::endl;\r\n        } else {\r\n            std::cout << \"p \\t\"; //artially use short loops\" << std::endl;\r\n        }\r\n        /**/\r\n        cano_loop_proxy.base_pt_index.clear();//\r\n        cano_loop_proxy.base_pt_index.reserve(non_tree_edges_for_sorted_cano_loops.size() * 3);\r\n        for (unsigned int i = 0; i < non_tree_edges_for_sorted_cano_loops.size(); i++) {\r\n            int edge_idx = non_tree_edges_for_sorted_cano_loops[i];\r\n            //std::cout << edge_idx << std::endl;\r\n            if ((edge_idx >= 0) && base_pt_set.find(locMesh.vecEdge[edge_idx].v0) == base_pt_set.end()) {\r\n                base_pt_set.insert(locMesh.vecEdge[edge_idx].v0);\r\n                cano_loop_proxy.base_pt_index.push_back(locMesh.vecEdge[edge_idx].v0);\r\n            }\r\n            //if (base_pt_set.find(mesh.vecEdge[edge_idx].v1) == base_pt_set.end())\r\n            //{\r\n            //\tbase_pt_set.insert(mesh.vecEdge[edge_idx].v1);\r\n            //\tcano_loop_proxy.base_pt_index.push_back(mesh.vecEdge[edge_idx].v1);\r\n            //}\r\n        }\r\n\r\n\r\n        if (edge_anno_proxy.ComputeShortestCanonicalLoops(basis_v_loops, basis_v_annotations, cano_loops,\r\n                                                          non_tree_edges,\r\n                                                          cano_loop_annotations, sorted_cano_loops,\r\n                                                          tmp_short_v_basis_loop,\r\n                                                          non_tree_edges_for_sorted_cano_loops)) {\r\n            std::cout << \"c \\t\"; //ompletly use short loops\" << std::endl;\r\n        } else {\r\n            std::cout << \"p \\t\"; //artially use short loops\" << std::endl;\r\n        }\r\n        //\r\n        pre_basis_v_len = cur_basis_v_len;\r\n        pre_basis_h_len = cur_basis_h_len;\r\n        cur_basis_v_len = BasisWeight(tmp_short_v_basis_loop, sqEdgeLen);\r\n        cur_basis_h_len = BasisWeight(tmp_short_h_basis_loop, sqEdgeLen);\r\n        //\r\n        for (unsigned int i = 0; i < non_tree_edges_for_sorted_cano_loops.size(); i++) {\r\n            int edge_idx = non_tree_edges_for_sorted_cano_loops[i];\r\n            //std::cout << edge_idx << std::endl;\r\n            if ((edge_idx >= 0) && base_pt_set.find(locMesh.vecEdge[edge_idx].v0) == base_pt_set.end()) {\r\n                base_pt_set.insert(locMesh.vecEdge[edge_idx].v0);\r\n                cano_loop_proxy.base_pt_index.push_back(locMesh.vecEdge[edge_idx].v0);\r\n            }\r\n            //if (base_pt_set.find(mesh.vecEdge[edge_idx].v1) == base_pt_set.end())\r\n            //{\r\n            //\tbase_pt_set.insert(mesh.vecEdge[edge_idx].v1);\r\n            //\tcano_loop_proxy.base_pt_index.push_back(mesh.vecEdge[edge_idx].v1);\r\n            //}\r\n        }\r\n        std::cout << iterNumber << \"\\t\";//<< \" new base pt set size \" << base_pt_set.size() << std::endl;\r\n        //std::cout << iterNumber << \" new base pt size \" << cano_loop_proxy.base_pt_index.size() << std::endl;\r\n        iterNumber++;\r\n        if (cano_loop_proxy.base_pt_index.empty())\r\n            break;\r\n        if (iterNumber > 2000)\r\n            break;\r\n\r\n    } while (abs(cur_basis_h_len - pre_basis_h_len) > 0.000001 || abs(cur_basis_v_len - pre_basis_v_len) > 0.000001);\r\n    //\r\n    // use optimzed vertical loops to optimize horizontal loops\r\n    std::set<int> tmpSet;\r\n    cano_loop_proxy.base_pt_index.clear();\r\n    for (unsigned int i = 0; i < tmp_short_v_basis_loop.size(); i++) {\r\n        for (std::set<int>::iterator sIter = tmp_short_v_basis_loop[i].begin();\r\n             sIter != tmp_short_v_basis_loop[i].end(); sIter++) {\r\n            base_pt_set.insert(locMesh.vecEdge[*sIter].v0);\r\n            base_pt_set.insert(locMesh.vecEdge[*sIter].v1);\r\n            tmpSet.insert(locMesh.vecEdge[*sIter].v0);\r\n        }\r\n    }\r\n    //\r\n    for (unsigned int i = 0; i < tmp_short_h_basis_loop.size(); i++) {\r\n        for (std::set<int>::iterator sIter = tmp_short_h_basis_loop[i].begin();\r\n             sIter != tmp_short_h_basis_loop[i].end(); sIter++) {\r\n            base_pt_set.insert(locMesh.vecEdge[*sIter].v0);\r\n            base_pt_set.insert(locMesh.vecEdge[*sIter].v1);\r\n            tmpSet.insert(locMesh.vecEdge[*sIter].v0);\r\n        }\r\n    }\r\n    //\r\n    cano_loop_proxy.base_pt_index.assign(tmpSet.begin(), tmpSet.end());\r\n    //\r\n    tmp_short_h_basis_loop.clear();\r\n    tmp_short_h_basis_loop.reserve(basis_h_loops.size());\r\n    tmp_short_v_basis_loop.clear();\r\n    tmp_short_v_basis_loop.reserve(basis_v_loops.size());\r\n    //\r\n    cano_loop_proxy.compute_canonical_loops_fibo(cano_loops, non_tree_edges, cano_loop_annotations, sorted_cano_loops,\r\n                                                 edge_anno_proxy);\r\n    //\r\n\r\n    if (edge_anno_proxy.ComputeShortestCanonicalLoops(basis_v_loops, basis_v_annotations, cano_loops, non_tree_edges,\r\n                                                      cano_loop_annotations, sorted_cano_loops, tmp_short_v_basis_loop,\r\n                                                      non_tree_edges_for_sorted_cano_loops)) {\r\n        std::cout << \"c \\t\"; //ompletly use short loops\" << std::endl;\r\n    } else {\r\n        std::cout << \"p \\t\"; //artially use short loops\" << std::endl;\r\n    }\r\n    //\r\n    if (edge_anno_proxy.ComputeShortestCanonicalLoops(basis_h_loops, basis_h_annotations, cano_loops, non_tree_edges,\r\n                                                      cano_loop_annotations, sorted_cano_loops, tmp_short_h_basis_loop,\r\n                                                      non_tree_edges_for_sorted_cano_loops)) {\r\n        std::cout << \"completly use short loops\" << std::endl;\r\n    } else {\r\n        std::cout << \"partially use short loops\" << std::endl;\r\n    }\r\n    //\r\n    out_h_basis_loops = tmp_short_h_basis_loop;\r\n    //\r\n    out_v_basis_loops = tmp_short_v_basis_loop;\r\n    return;\r\n}\r\n//\r\n//int mainx(int argc, char** argv)\r\n//{\r\n//\tint optMethodOption;\r\n//\tstringstream sstr(stringstream::in | stringstream::out);\r\n//\tif (argc == 8)\r\n//\t{\r\n//\t\tsstr.str(argv[7]);\r\n//\t\tsstr >> optMethodOption;\r\n//\t\tsstr.clear();\r\n//\t\tstd::cout << optMethodOption << std::endl;\r\n//\t\tif (optMethodOption)\r\n//\t\t{\r\n//\t\t\t//GlobalOptimization(argc, argv);\r\n//\t\t}\r\n//\t\telse\r\n//\t\t{\r\n//\t\t\tLocalOptimization(argc, argv);\r\n//\t\t}\r\n//\t}\r\n//\telse\r\n//\t{\r\n//\t\tif (argc == 9)\r\n//\t\t\tLocalOptimization_bdry(argc, argv);\r\n//\t\telse\r\n//\t\t\tLocalOptimization(argc, argv);\r\n//\t}\r\n//\treturn 1;\r\n//\t//\r\n//}\r\n\r\nvoid CycleLocalOptimization(_SimpleMesh &locMesh, psbmReebGraph &reebgraph, std::vector<int> &OrientTriangles,\r\n                            std::vector<std::set<int> > &out_v_basis_loops,\r\n                            std::vector<std::set<int> > &out_h_basis_loops,\r\n                            const float fScaleRatio) {//\r\n    _simpGraph_vec locMeshGraph;\r\n    //\r\n    edge_annotation_computing edge_anno_proxy;\r\n    //\r\n    //std::cout << \"tris size\" << OrientTriangles.size() << std::endl;\r\n    //\r\n    ComputeAnnotation(locMesh, edge_anno_proxy.edge_annotations, OrientTriangles);\r\n    edge_anno_proxy.vec_size = (int) edge_anno_proxy.edge_annotations[0].size();\r\n    //\r\n    if (edge_anno_proxy.vec_size == 0) {\r\n        std::cout << \"TRIVIAL LOOPS\" << std::endl;\r\n        exit(0);\r\n    }\r\n    //std::cout << \"before assembe graph \" << edge_anno_proxy.vec_size << std::endl;\r\n    std::vector<float> sqEdgeLen;\r\n    AssembleMeshGraph(locMeshGraph, locMesh, sqEdgeLen, fScaleRatio);\r\n    //\r\n    edge_anno_proxy.SetMeshPtr(&locMesh);\r\n    //edge_anno_proxy.ReadEdgeAnnotationsFromFile(argv[2]);\r\n    //\r\n    std::vector<int> basis_h_LowestOnePos;\r\n    std::vector<int> basis_v_LowestOnePos;\r\n    std::vector<Annotation_Type> reduced_basis_h_annotations;\r\n    std::vector<Annotation_Type> reduced_basis_v_annotations;\r\n    //\r\n    std::vector<std::vector<int> > basis_h_loops;\r\n    std::vector<std::vector<int> > basis_v_loops;\r\n    std::vector<Annotation_Type> basis_h_annotations;\r\n    std::vector<Annotation_Type> basis_v_annotations;\r\n    //\r\n    std::vector<int> base_pt_vec;\r\n    //\r\n    LoadCycleData(reebgraph, basis_h_loops, basis_v_loops, base_pt_vec);\r\n\r\n    edge_anno_proxy.CheckTwoGroupVectorOrthogonality(basis_v_loops, basis_v_annotations, reduced_basis_v_annotations,\r\n                                                     basis_v_LowestOnePos,\r\n                                                     basis_h_loops, basis_h_annotations, reduced_basis_h_annotations,\r\n                                                     basis_h_LowestOnePos);\r\n    //\r\n    canonical_loops_computing cano_loop_proxy;\r\n    //\r\n    //\r\n    //std::set<int> base_pt_set;\r\n    //for (unsigned int i = 0; i < basis_v_loops.size(); i++)\r\n    //{\r\n    //\tfor (unsigned int j = 0; j < basis_v_loops[i].size(); j++)\r\n    //\t{\r\n    //\t\tbase_pt_set.insert(mesh.vecEdge[basis_v_loops[i][j]].v0);\r\n    //\t\tbase_pt_set.insert(mesh.vecEdge[basis_v_loops[i][j]].v1);\r\n    //\t}\r\n    //}\r\n    //std::vector<int> base_pt_vec(base_pt_set.begin(), base_pt_set.end());//\r\n    //\r\n\r\n    //ReadBasisCriticalPoints(argv[3], base_pt_vec);\r\n    std::set<int> base_pt_set(base_pt_vec.begin(), base_pt_vec.end());\r\n    //\r\n    //std::cout << \"old base_pt_vec \" << base_pt_vec.size() << std::endl;\r\n    //\r\n    cano_loop_proxy.SetGraphPtr(&locMeshGraph);\r\n    cano_loop_proxy.SetEdgeWeights(sqEdgeLen);\r\n    cano_loop_proxy.SetBasePointArray(base_pt_vec);\r\n    cano_loop_proxy.SetMeshPtr(&locMesh);\r\n    cano_loop_proxy.SetMeshGenus(edge_anno_proxy.vec_size / 2);\r\n    //\r\n    //cano_loop_proxy.ResetBaseVertices(basis_h_loops, edge_anno_proxy);\r\n    //std::cout << \"new base_pt_vec \" << cano_loop_proxy.base_pt_index.size() << std::endl;\r\n    //\r\n    std::cout << \"Time for shortening handle and tunnel loops : \" << std::endl;\r\n    float cur_basis_h_len = BasisWeight(basis_h_loops, sqEdgeLen);\r\n    float cur_basis_v_len = BasisWeight(basis_v_loops, sqEdgeLen);\r\n    std::vector<std::set<int> > tmp_short_h_basis_loop;\r\n    std::vector<std::set<int> > tmp_short_v_basis_loop;\r\n    {\r\n        // starting measuring the time\r\n        boost::progress_timer t;\r\n        //\r\n        std::vector<std::set<int> > cano_loops;\r\n        std::vector<int> non_tree_edges;\r\n        std::vector<Annotation_Type> cano_loop_annotations;\r\n        std::set<std::pair<float, int>, myFloatIntPairLessThan> sorted_cano_loops;\r\n        std::vector<int> non_tree_edges_for_sorted_cano_loops;\r\n        //\r\n        float pre_basis_h_len = 0.0;\r\n        float pre_basis_v_len = 0.0;\r\n\r\n\r\n        //\r\n        int iterNumber = 0;\r\n        // optimize the all loops together\r\n        do {\r\n            tmp_short_h_basis_loop.clear();\r\n            tmp_short_h_basis_loop.reserve(basis_h_loops.size());\r\n            tmp_short_v_basis_loop.clear();\r\n            tmp_short_v_basis_loop.reserve(basis_v_loops.size());\r\n            base_pt_vec.clear();\r\n            //\r\n\r\n            cano_loop_proxy.compute_canonical_loops_fibo(cano_loops, non_tree_edges, cano_loop_annotations,\r\n                                                         sorted_cano_loops, edge_anno_proxy);\r\n\r\n            //\r\n            //std::cout << \"in cano 1\" << std::endl;\r\n            if (edge_anno_proxy.ComputeShortestCanonicalLoops(basis_h_loops, basis_h_annotations,\r\n                                                              reduced_basis_h_annotations, basis_h_LowestOnePos,\r\n                                                              cano_loops, non_tree_edges,\r\n                                                              cano_loop_annotations, sorted_cano_loops,\r\n                                                              tmp_short_h_basis_loop,\r\n                                                              non_tree_edges_for_sorted_cano_loops)) {\r\n                std::cout << \".\";//ompletly use short loops\" << std::endl;\r\n            } else {\r\n                std::cout << \"*\"; //artially use short loops\" << std::endl;\r\n            }\r\n            //std::cout << \"out cano 1\" << std::endl;\r\n            /**/\r\n            cano_loop_proxy.base_pt_index.clear();//\r\n            cano_loop_proxy.base_pt_index.reserve(non_tree_edges_for_sorted_cano_loops.size() * 3);\r\n            for (unsigned int i = 0; i < non_tree_edges_for_sorted_cano_loops.size(); i++) {\r\n                int edge_idx = non_tree_edges_for_sorted_cano_loops[i];\r\n                //std::cout << edge_idx << std::endl;\r\n                if ((edge_idx >= 0) && base_pt_set.find(locMesh.vecEdge[edge_idx].v0) == base_pt_set.end()) {\r\n                    base_pt_set.insert(locMesh.vecEdge[edge_idx].v0);\r\n                    cano_loop_proxy.base_pt_index.push_back(locMesh.vecEdge[edge_idx].v0);\r\n                }\r\n                //if (base_pt_set.find(mesh.vecEdge[edge_idx].v1) == base_pt_set.end())\r\n                //{\r\n                //\tbase_pt_set.insert(mesh.vecEdge[edge_idx].v1);\r\n                //\tcano_loop_proxy.base_pt_index.push_back(mesh.vecEdge[edge_idx].v1);\r\n                //}\r\n            }\r\n\r\n            //std::cout << \"in cano 2\" << std::endl;\r\n            if (edge_anno_proxy.ComputeShortestCanonicalLoops(basis_v_loops, basis_v_annotations,\r\n                                                              reduced_basis_v_annotations, basis_v_LowestOnePos,\r\n                                                              cano_loops, non_tree_edges,\r\n                                                              cano_loop_annotations, sorted_cano_loops,\r\n                                                              tmp_short_v_basis_loop,\r\n                                                              non_tree_edges_for_sorted_cano_loops)) {\r\n                std::cout << \".\"; //ompletly use short loops\" << std::endl;\r\n            } else {\r\n                std::cout << \"*\"; //artially use short loops\" << std::endl;\r\n            }\r\n            //std::cout << \"out cano 2\" << std::endl;\r\n            //\r\n            pre_basis_v_len = cur_basis_v_len;\r\n            pre_basis_h_len = cur_basis_h_len;\r\n            cur_basis_v_len = BasisWeight(tmp_short_v_basis_loop, sqEdgeLen);\r\n            cur_basis_h_len = BasisWeight(tmp_short_h_basis_loop, sqEdgeLen);\r\n            //\r\n            for (unsigned int i = 0; i < non_tree_edges_for_sorted_cano_loops.size(); i++) {\r\n                int edge_idx = non_tree_edges_for_sorted_cano_loops[i];\r\n                //std::cout << edge_idx << std::endl;\r\n                if ((edge_idx >= 0) && base_pt_set.find(locMesh.vecEdge[edge_idx].v0) == base_pt_set.end()) {\r\n                    base_pt_set.insert(locMesh.vecEdge[edge_idx].v0);\r\n                    cano_loop_proxy.base_pt_index.push_back(locMesh.vecEdge[edge_idx].v0);\r\n                }\r\n                //if (base_pt_set.find(mesh.vecEdge[edge_idx].v1) == base_pt_set.end())\r\n                //{\r\n                //\tbase_pt_set.insert(mesh.vecEdge[edge_idx].v1);\r\n                //\tcano_loop_proxy.base_pt_index.push_back(mesh.vecEdge[edge_idx].v1);\r\n                //}\r\n            }\r\n            //std::cout << iterNumber << \"\\t\";//<< \" new base pt set size \" << base_pt_set.size() << std::endl;\r\n            //std::cout << iterNumber << \" new base pt size \" << cano_loop_proxy.base_pt_index.size() << std::endl;\r\n            iterNumber++;\r\n            if (cano_loop_proxy.base_pt_index.empty())\r\n                break;\r\n            if (iterNumber > 2000)\r\n                break;\r\n\r\n        } while (fabs(cur_basis_h_len - pre_basis_h_len) > 0.000001 ||\r\n                 fabs(cur_basis_v_len - pre_basis_v_len) > 0.000001);\r\n        //\r\n        std::cout << std::endl;\r\n    }\r\n    //\r\n    out_h_basis_loops = tmp_short_h_basis_loop;\r\n    //\r\n    //\r\n    out_v_basis_loops = tmp_short_v_basis_loop;\r\n    //\r\n    return;\r\n}\r\n", "meta": {"hexsha": "0ddebf7276604b425b9a601ef16bd0e8470d417a", "size": 38651, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/CycleOptimization/ShortCycles.cpp", "max_stars_repo_name": "anapupa/ReebHanTun", "max_stars_repo_head_hexsha": "679ba774b75f4f53c502cb79f69bc9061c009eb8", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CycleOptimization/ShortCycles.cpp", "max_issues_repo_name": "anapupa/ReebHanTun", "max_issues_repo_head_hexsha": "679ba774b75f4f53c502cb79f69bc9061c009eb8", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CycleOptimization/ShortCycles.cpp", "max_forks_repo_name": "anapupa/ReebHanTun", "max_forks_repo_head_hexsha": "679ba774b75f4f53c502cb79f69bc9061c009eb8", "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": 45.2587822014, "max_line_length": 129, "alphanum_fraction": 0.5636594137, "num_tokens": 9277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.5, "lm_q1q2_score": 0.29255056986686956}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"PointwiseFunctions/AnalyticSolutions/GeneralRelativity/Tov.hpp\"\n\n// Need Boost MultiArray because it is used internally by ODEINT\n#include \"DataStructures/BoostMultiArray.hpp\"  // IWYU pragma: keep\n\n#include <algorithm>\n#include <array>\n#include <boost/numeric/odeint.hpp>  // IWYU pragma: keep\n#include <cmath>\n#include <cstddef>\n#include <functional>\n#include <ostream>\n#include <pup.h>\n#include <vector>\n\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/Tensor/EagerMath/Magnitude.hpp\"\n#include \"Utilities/ConstantExpressions.hpp\"\n#include \"Utilities/ContainerHelpers.hpp\"\n#include \"Utilities/ErrorHandling/Assert.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/MakeWithValue.hpp\"\n\n// IWYU pragma: no_include <boost/numeric/odeint/integrate/integrate_adaptive.hpp>\n// IWYU pragma: no_include <boost/numeric/odeint/stepper/controlled_runge_kutta.hpp>\n// IWYU pragma: no_include <boost/numeric/odeint/stepper/dense_output_runge_kutta.hpp>\n// IWYU pragma: no_include <boost/numeric/odeint/stepper/generation/make_dense_output.hpp>\n// IWYU pragma: no_include <boost/numeric/odeint/stepper/runge_kutta_dopri5.hpp>\n// IWYU pragma: no_include <complex>\n\n// IWYU pragma: no_forward_declare boost::numeric::odeint::controlled_runge_kutta\n// IWYU pragma: no_forward_declare EquationsOfState::EquationOfState\n// IWYU pragma: no_forward_declare Tensor\n\nnamespace {\n\nvoid lindblom_rhs(const gsl::not_null<std::array<double, 2>*> dvars,\n                  const std::array<double, 2>& vars, const double log_enthalpy,\n                  const EquationsOfState::EquationOfState<true, 1>&\n                      equation_of_state) noexcept {\n  const double& radius_squared = vars[0];\n  const double& mass_over_radius = vars[1];\n  double& d_radius_squared = (*dvars)[0];\n  double& d_mass_over_radius = (*dvars)[1];\n  const double specific_enthalpy = std::exp(log_enthalpy);\n  const double rest_mass_density =\n      get(equation_of_state.rest_mass_density_from_enthalpy(\n          Scalar<double>{specific_enthalpy}));\n  const double pressure = get(equation_of_state.pressure_from_density(\n      Scalar<double>{rest_mass_density}));\n  const double energy_density =\n      specific_enthalpy * rest_mass_density - pressure;\n\n  // At the center of the star: (u,v) = (0,0)\n  if (UNLIKELY((radius_squared == 0.0) and (mass_over_radius == 0.0))) {\n    d_radius_squared = -3.0 / (2.0 * M_PI * (energy_density + 3.0 * pressure));\n    d_mass_over_radius =\n        -2.0 * energy_density / (energy_density + 3.0 * pressure);\n  } else {\n    const double common_factor =\n        (1.0 - 2.0 * mass_over_radius) /\n        (4.0 * M_PI * radius_squared * pressure + mass_over_radius);\n    d_radius_squared = -2.0 * radius_squared * common_factor;\n    d_mass_over_radius =\n        -(4.0 * M_PI * radius_squared * energy_density - mass_over_radius) *\n        common_factor;\n  }\n}\n\nclass Observer {\n public:\n  void operator()(const std::array<double, 2>& vars,\n                  const double current_log_enthalpy) noexcept {\n    radius.push_back(std::sqrt(vars[0]));\n    mass_over_radius.push_back(vars[1]);\n    log_enthalpy.push_back(current_log_enthalpy);\n  }\n  std::vector<double> radius;\n  std::vector<double> mass_over_radius;\n  std::vector<double> log_enthalpy;\n};\n\ntemplate <typename DataType>\nRelativisticEuler::Solutions::TovStar<\n    gr::Solutions::TovSolution>::RadialVariables<DataType>\ninterior_solution(\n    const EquationsOfState::EquationOfState<true, 1>& equation_of_state,\n    const DataType& radius, const DataType& mass_over_radius,\n    const DataType& log_specific_enthalpy,\n    const double log_lapse_at_outer_radius) noexcept {\n  RelativisticEuler::Solutions::TovStar<\n      gr::Solutions::TovSolution>::RadialVariables<DataType>\n      result(radius);\n  result.specific_enthalpy = Scalar<DataType>{exp(log_specific_enthalpy)};\n  result.rest_mass_density = equation_of_state.rest_mass_density_from_enthalpy(\n      result.specific_enthalpy);\n  result.pressure =\n      equation_of_state.pressure_from_density(result.rest_mass_density);\n  result.specific_internal_energy =\n      equation_of_state.specific_internal_energy_from_density(\n          result.rest_mass_density);\n  result.metric_time_potential =\n      log_lapse_at_outer_radius - log_specific_enthalpy;\n  result.dr_metric_time_potential =\n      (mass_over_radius / radius + 4.0 * M_PI * get(result.pressure) * radius) /\n      (1.0 - 2.0 * mass_over_radius);\n  result.metric_radial_potential = -0.5 * log(1.0 - 2.0 * mass_over_radius);\n  result.dr_metric_radial_potential =\n      (4.0 * M_PI * radius *\n           (get(result.specific_enthalpy) * get(result.rest_mass_density) -\n            get(result.pressure)) -\n       mass_over_radius / radius) /\n      (1.0 - 2.0 * mass_over_radius);\n  result.metric_angular_potential = make_with_value<DataType>(radius, 0.0);\n  result.dr_metric_angular_potential = make_with_value<DataType>(radius, 0.0);\n  return result;\n}\n\ntemplate <typename DataType>\nRelativisticEuler::Solutions::TovStar<\n    gr::Solutions::TovSolution>::RadialVariables<DataType>\nvacuum_solution(const DataType& radius, const double total_mass) noexcept {\n  RelativisticEuler::Solutions::TovStar<\n      gr::Solutions::TovSolution>::RadialVariables<DataType>\n      result(radius);\n  result.specific_enthalpy = make_with_value<Scalar<DataType>>(radius, 1.0);\n  result.rest_mass_density = make_with_value<Scalar<DataType>>(radius, 0.0);\n  result.pressure = make_with_value<Scalar<DataType>>(radius, 0.0);\n  result.specific_internal_energy =\n      make_with_value<Scalar<DataType>>(radius, 0.0);\n  const DataType one_minus_two_m_over_r = 1.0 - 2.0 * total_mass / radius;\n  result.metric_time_potential = 0.5 * log(one_minus_two_m_over_r);\n  result.dr_metric_time_potential =\n      total_mass / square(radius) / one_minus_two_m_over_r;\n  result.metric_radial_potential = -result.metric_time_potential;\n  result.dr_metric_radial_potential = -result.dr_metric_time_potential;\n  result.metric_angular_potential = make_with_value<DataType>(radius, 0.0);\n  result.dr_metric_angular_potential = make_with_value<DataType>(radius, 0.0);\n  return result;\n}\n\n}  // namespace\n\nnamespace gr::Solutions {\n\nTovSolution::TovSolution(\n    const EquationsOfState::EquationOfState<true, 1>& equation_of_state,\n    const double central_mass_density,\n    const double log_enthalpy_at_outer_radius, const double absolute_tolerance,\n    const double relative_tolerance) {\n  std::array<double, 2> u_and_v = {{0.0, 0.0}};\n  std::array<double, 2> dudh_and_dvdh{};\n  const double central_log_enthalpy =\n      std::log(get(equation_of_state.specific_enthalpy_from_density(\n          Scalar<double>{central_mass_density})));\n  lindblom_rhs(&dudh_and_dvdh, u_and_v, central_log_enthalpy,\n               equation_of_state);\n  const double initial_step = -std::min(std::abs(1.0 / dudh_and_dvdh[0]),\n                                        std::abs(1.0 / dudh_and_dvdh[1]));\n  using StateDopri5 =\n      boost::numeric::odeint::runge_kutta_dopri5<std::array<double, 2>>;\n  boost::numeric::odeint::dense_output_runge_kutta<\n      boost::numeric::odeint::controlled_runge_kutta<StateDopri5>>\n      dopri5 = make_dense_output(absolute_tolerance, relative_tolerance,\n                                 StateDopri5{});\n  Observer observer{};\n  boost::numeric::odeint::integrate_adaptive(\n      dopri5,\n      [&equation_of_state](const std::array<double, 2>& lindblom_u_and_v,\n                           std::array<double, 2>& lindblom_dudh_and_dvdh,\n                           const double lindblom_enthalpy) noexcept {\n        return lindblom_rhs(&lindblom_dudh_and_dvdh, lindblom_u_and_v,\n                            lindblom_enthalpy, equation_of_state);\n      },\n      u_and_v, central_log_enthalpy, log_enthalpy_at_outer_radius, initial_step,\n      std::ref(observer));\n  outer_radius_ = observer.radius.back();\n  const double total_mass_over_radius = observer.mass_over_radius.back();\n  total_mass_ = total_mass_over_radius * outer_radius_;\n  log_lapse_at_outer_radius_ = 0.5 * log(1.0 - 2.0 * total_mass_over_radius);\n  mass_over_radius_interpolant_ =\n      intrp::BarycentricRational(observer.radius, observer.mass_over_radius, 5);\n  // log_enthalpy(radius) is almost linear so an interpolant of order 3\n  // maximizes precision\n  log_enthalpy_interpolant_ =\n      intrp::BarycentricRational(observer.radius, observer.log_enthalpy, 3);\n}\n\ndouble TovSolution::outer_radius() const noexcept { return outer_radius_; }\n\ndouble TovSolution::mass_over_radius(const double r) const noexcept {\n  ASSERT(r >= 0.0 and r <= outer_radius_,\n         \"Invalid radius: \" << r << \" not in [0.0, \" << outer_radius_ << \"]\\n\");\n  return mass_over_radius_interpolant_(r);\n}\n\ndouble TovSolution::mass(const double r) const noexcept {\n  return mass_over_radius(r) * r;\n}\n\ndouble TovSolution::log_specific_enthalpy(const double r) const noexcept {\n  ASSERT(r >= 0.0 and r <= outer_radius_,\n         \"Invalid radius: \" << r << \" not in [0.0, \" << outer_radius_ << \"]\\n\");\n  return log_enthalpy_interpolant_(r);\n}\n\ntemplate <>\nRelativisticEuler::Solutions::TovStar<TovSolution>::RadialVariables<double>\nTovSolution::radial_variables(\n    const EquationsOfState::EquationOfState<true, 1>& equation_of_state,\n    const tnsr::I<double, 3>& x) const noexcept {\n  // add small number to avoid FPEs at origin\n  const double radius = get(magnitude(x)) + 1.e-30 * outer_radius_;\n  if (radius >= outer_radius_) {\n    return vacuum_solution(radius, total_mass_);\n  }\n  return interior_solution(equation_of_state, radius, mass_over_radius(radius),\n                           log_specific_enthalpy(radius),\n                           log_lapse_at_outer_radius_);\n}\n\ntemplate <>\nRelativisticEuler::Solutions::TovStar<TovSolution>::RadialVariables<DataVector>\nTovSolution::radial_variables(\n    const EquationsOfState::EquationOfState<true, 1>& equation_of_state,\n    const tnsr::I<DataVector, 3>& x) const noexcept {\n  // add small number to avoid FPEs at origin\n  const DataVector radius = get(magnitude(x)) + 1.e-30 * outer_radius_;\n  if (min(radius) >= outer_radius_) {\n    return vacuum_solution(radius, total_mass_);\n  }\n  if (max(radius) <= outer_radius_) {\n    DataVector mass_over_radius_data(radius.size());\n    DataVector log_of_specific_enthalpy(radius.size());\n    for (size_t i = 0; i < get_size(radius); i++) {\n      const double r = get_element(radius, i);\n      get_element(mass_over_radius_data, i) = mass_over_radius(r);\n      get_element(log_of_specific_enthalpy, i) = log_specific_enthalpy(r);\n    }\n    return interior_solution(equation_of_state, radius, mass_over_radius_data,\n                             log_of_specific_enthalpy,\n                             log_lapse_at_outer_radius_);\n  }\n  RelativisticEuler::Solutions::TovStar<TovSolution>::RadialVariables<\n      DataVector>\n      result(radius);\n  for (size_t i = 0; i < radius.size(); i++) {\n    const double r = radius[i];\n    auto radial_vars_at_r =\n        (r <= outer_radius_\n             ? interior_solution(equation_of_state, r, mass_over_radius(r),\n                                 log_specific_enthalpy(r),\n                                 log_lapse_at_outer_radius_)\n             : vacuum_solution(r, total_mass_));\n    get(result.rest_mass_density)[i] = get(radial_vars_at_r.rest_mass_density);\n    get(result.pressure)[i] = get(radial_vars_at_r.pressure);\n    get(result.specific_internal_energy)[i] =\n        get(radial_vars_at_r.specific_internal_energy);\n    get(result.specific_enthalpy)[i] = get(radial_vars_at_r.specific_enthalpy);\n    result.metric_time_potential[i] = radial_vars_at_r.metric_time_potential;\n    result.dr_metric_time_potential[i] =\n        radial_vars_at_r.dr_metric_time_potential;\n    result.metric_radial_potential[i] =\n        radial_vars_at_r.metric_radial_potential;\n    result.dr_metric_radial_potential[i] =\n        radial_vars_at_r.dr_metric_radial_potential;\n  }\n  result.metric_angular_potential = make_with_value<DataVector>(radius, 0.0);\n  result.dr_metric_angular_potential = make_with_value<DataVector>(radius, 0.0);\n  return result;\n}\n\nvoid TovSolution::pup(PUP::er& p) noexcept {  // NOLINT\n  p | outer_radius_;\n  p | total_mass_;\n  p | log_lapse_at_outer_radius_;\n  p | mass_over_radius_interpolant_;\n  p | log_enthalpy_interpolant_;\n}\n\n}  // namespace gr::Solutions\n", "meta": {"hexsha": "0f5fa4e93180f300a2f10769799ed69a4b1096b6", "size": 12381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PointwiseFunctions/AnalyticSolutions/GeneralRelativity/Tov.cpp", "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/PointwiseFunctions/AnalyticSolutions/GeneralRelativity/Tov.cpp", "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/PointwiseFunctions/AnalyticSolutions/GeneralRelativity/Tov.cpp", "max_forks_repo_name": "isaaclegred/spectre", "max_forks_repo_head_hexsha": "5765da85dad680cad992daccd479376c67458a8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-01-03T21:47:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-03T21:47:04.000Z", "avg_line_length": 43.4421052632, "max_line_length": 90, "alphanum_fraction": 0.7217510702, "num_tokens": 3240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.29253362152023465}}
{"text": "//\n// Copyright 2005-2007 Adobe Systems Incorporated\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n#ifndef BOOST_GIL_EXTENSION_NUMERIC_ALGORITHM_HPP\n#define BOOST_GIL_EXTENSION_NUMERIC_ALGORITHM_HPP\n\n#include <boost/gil/extension/numeric/pixel_numeric_operations.hpp>\n\n#include <boost/gil/metafunctions.hpp>\n#include <boost/gil/pixel_iterator.hpp>\n\n#include <boost/assert.hpp>\n\n#include <algorithm>\n#include <iterator>\n#include <numeric>\n#include <type_traits>\n\nnamespace boost { namespace gil {\n\n/// \\brief Reference proxy associated with a type that has a \\p \"reference\" member type alias.\n///\n/// The reference proxy is the reference type, but with stripped-out C++ reference.\n/// Models PixelConcept.\ntemplate <typename T>\nstruct pixel_proxy : std::remove_reference<typename T::reference> {};\n\n/// \\brief std::for_each for a pair of iterators\ntemplate <typename Iterator1, typename Iterator2, typename BinaryFunction>\nBinaryFunction for_each(Iterator1 first1, Iterator1 last1, Iterator2 first2, BinaryFunction f)\n{\n    while (first1 != last1)\n        f(*first1++, *first2++);\n    return f;\n}\n\ntemplate <typename SrcIterator, typename DstIterator>\ninline\nauto assign_pixels(SrcIterator src, SrcIterator src_end, DstIterator dst) -> DstIterator\n{\n    for_each(src, src_end, dst,\n        pixel_assigns_t\n        <\n            typename pixel_proxy<typename std::iterator_traits<SrcIterator>::value_type>::type,\n            typename pixel_proxy<typename std::iterator_traits<DstIterator>::value_type>::type\n        >());\n    return dst + (src_end - src);\n}\n\nnamespace detail {\n\ntemplate <std::size_t Size>\nstruct inner_product_k_t\n{\n    template\n    <\n        class InputIterator1,\n        class InputIterator2,\n        class T,\n        class BinaryOperation1,\n        class BinaryOperation2\n    >\n    static T apply(\n        InputIterator1 first1,\n        InputIterator2 first2, T init,\n        BinaryOperation1 binary_op1,\n        BinaryOperation2 binary_op2)\n    {\n        init = binary_op1(init, binary_op2(*first1, *first2));\n        return inner_product_k_t<Size - 1>::template apply(\n            first1 + 1, first2 + 1, init, binary_op1, binary_op2);\n    }\n};\n\ntemplate <>\nstruct inner_product_k_t<0>\n{\n    template\n    <\n        class InputIterator1,\n        class InputIterator2,\n        class T,\n        class BinaryOperation1,\n        class BinaryOperation2\n    >\n    static T apply(\n        InputIterator1 first1,\n        InputIterator2 first2,\n        T init,\n        BinaryOperation1 binary_op1,\n        BinaryOperation2 binary_op2)\n    {\n        return init;\n    }\n};\n\n} // namespace detail\n\n/// static version of std::inner_product\ntemplate\n<\n    std::size_t Size,\n    class InputIterator1,\n    class InputIterator2,\n    class T,\n    class BinaryOperation1,\n    class BinaryOperation2\n>\nBOOST_FORCEINLINE\nT inner_product_k(\n    InputIterator1 first1,\n    InputIterator2 first2,\n    T init,\n    BinaryOperation1 binary_op1,\n    BinaryOperation2 binary_op2)\n{\n    return detail::inner_product_k_t<Size>::template apply(\n        first1, first2, init, binary_op1, binary_op2);\n}\n\n/// \\brief 1D un-guarded cross-correlation with a variable-size kernel\ntemplate\n<\n    typename PixelAccum,\n    typename SrcIterator,\n    typename KernelIterator,\n    typename Size,\n    typename DstIterator\n>\ninline\nauto correlate_pixels_n(\n    SrcIterator src_begin,\n    SrcIterator src_end,\n    KernelIterator kernel_begin,\n    Size kernel_size,\n    DstIterator dst_begin)\n    -> DstIterator\n{\n    using src_pixel_ref_t = typename pixel_proxy\n        <\n            typename std::iterator_traits<SrcIterator>::value_type\n        >::type;\n    using dst_pixel_ref_t = typename pixel_proxy\n        <\n            typename std::iterator_traits<DstIterator>::value_type\n        >::type;\n    using kernel_value_t = typename std::iterator_traits<KernelIterator>::value_type;\n\n    PixelAccum accum_zero;\n    pixel_zeros_t<PixelAccum>()(accum_zero);\n    while (src_begin != src_end)\n    {\n        pixel_assigns_t<PixelAccum, dst_pixel_ref_t>()(\n            std::inner_product(\n                src_begin,\n                src_begin + kernel_size,\n                kernel_begin,\n                accum_zero,\n                pixel_plus_t<PixelAccum, PixelAccum, PixelAccum>(),\n                pixel_multiplies_scalar_t<src_pixel_ref_t, kernel_value_t, PixelAccum>()),\n            *dst_begin);\n\n        ++src_begin;\n        ++dst_begin;\n    }\n    return dst_begin;\n}\n\n/// \\brief 1D un-guarded cross-correlation with a fixed-size kernel\ntemplate\n<\n    std::size_t Size,\n    typename PixelAccum,\n    typename SrcIterator,\n    typename KernelIterator,\n    typename DstIterator\n>\ninline\nauto correlate_pixels_k(\n    SrcIterator src_begin,\n    SrcIterator src_end,\n    KernelIterator kernel_begin,\n    DstIterator dst_begin)\n    -> DstIterator\n{\n    using src_pixel_ref_t = typename pixel_proxy\n        <\n            typename std::iterator_traits<SrcIterator>::value_type\n        >::type;\n    using dst_pixel_ref_t = typename pixel_proxy\n        <\n            typename std::iterator_traits<DstIterator>::value_type\n        >::type;\n    using kernel_type = typename std::iterator_traits<KernelIterator>::value_type;\n\n    PixelAccum accum_zero;\n    pixel_zeros_t<PixelAccum>()(accum_zero);\n    while (src_begin != src_end)\n    {\n        pixel_assigns_t<PixelAccum, dst_pixel_ref_t>()(\n            inner_product_k<Size>(\n                src_begin,\n                kernel_begin,\n                accum_zero,\n                pixel_plus_t<PixelAccum, PixelAccum, PixelAccum>(),\n                pixel_multiplies_scalar_t<src_pixel_ref_t, kernel_type, PixelAccum>()),\n            *dst_begin);\n\n        ++src_begin;\n        ++dst_begin;\n    }\n    return dst_begin;\n}\n\n/// \\brief destination is set to be product of the source and a scalar\n/// \\tparam PixelAccum - TODO\n/// \\tparam SrcView Models ImageViewConcept\n/// \\tparam DstView Models MutableImageViewConcept\ntemplate <typename PixelAccum, typename SrcView, typename Scalar, typename DstView>\ninline\nvoid view_multiplies_scalar(SrcView const& src_view, Scalar const& scalar, DstView const& dst_view)\n{\n    static_assert(std::is_scalar<Scalar>::value, \"Scalar is not scalar\");\n    BOOST_ASSERT(src_view.dimensions() == dst_view.dimensions());\n    using src_pixel_ref_t = typename pixel_proxy<typename SrcView::value_type>::type;\n    using dst_pixel_ref_t = typename pixel_proxy<typename DstView::value_type>::type;\n    using y_coord_t = typename SrcView::y_coord_t;\n\n    y_coord_t const height = src_view.height();\n    for (y_coord_t y = 0; y < height; ++y)\n    {\n        typename SrcView::x_iterator it_src = src_view.row_begin(y);\n        typename DstView::x_iterator it_dst = dst_view.row_begin(y);\n        typename SrcView::x_iterator it_src_end = src_view.row_end(y);\n        while (it_src != it_src_end)\n        {\n            pixel_assigns_t<PixelAccum, dst_pixel_ref_t>()(\n                pixel_multiplies_scalar_t<src_pixel_ref_t, Scalar, PixelAccum>()(*it_src, scalar),\n                *it_dst);\n\n            ++it_src;\n            ++it_dst;\n        }\n    }\n}\n\n}} // namespace boost::gil\n\n#endif\n", "meta": {"hexsha": "d77edd1628daaf4178154b74007f1c5b5de23a91", "size": 7230, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/gil/extension/numeric/algorithm.hpp", "max_stars_repo_name": "macmade/gil", "max_stars_repo_head_hexsha": "124f621914d13315c3b72de13d18c0022c921f13", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/gil/extension/numeric/algorithm.hpp", "max_issues_repo_name": "macmade/gil", "max_issues_repo_head_hexsha": "124f621914d13315c3b72de13d18c0022c921f13", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/gil/extension/numeric/algorithm.hpp", "max_forks_repo_name": "macmade/gil", "max_forks_repo_head_hexsha": "124f621914d13315c3b72de13d18c0022c921f13", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4645669291, "max_line_length": 99, "alphanum_fraction": 0.6764868603, "num_tokens": 1690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2925325525177334}}
{"text": "#ifndef VIGRA_EXPORT_GRAPH_ALGORITHM_VISITOR_HXX\n#define VIGRA_EXPORT_GRAPH_ALGORITHM_VISITOR_HXX\n//#define NO_IMPORT_ARRAY\n\n/*boost python before anything else*/\n#include <boost/python.hpp>\n\n/*std*/\n#include <sstream>\n#include <string>\n\n/*vigra*/\n#include <vigra/numpy_array.hxx>\n#include <vigra/numpy_array_converters.hxx>\n#include <vigra/graphs.hxx>\n#include <vigra/graph_maps.hxx>\n#include <vigra/python_graph.hxx>\n#include <vigra/graph_algorithms.hxx>\n#include <vigra/metrics.hxx>\n#include <vigra/multi_gridgraph.hxx>\n#include <vigra/error.hxx>\n#include <vigra/multi_watersheds.hxx>\nnamespace python = boost::python;\n\nnamespace vigra{\n\n\ntemplate<class GRAPH>\nclass LemonGraphAlgorithmVisitor \n:   public boost::python::def_visitor<LemonGraphAlgorithmVisitor<GRAPH> >\n{\npublic:\n\n    friend class def_visitor_access;\n\n    typedef GRAPH Graph;\n\n    typedef LemonGraphAlgorithmVisitor<GRAPH> VisitorType;\n    // Lemon Graph Typedefs\n    \n    typedef typename Graph::index_type       index_type;\n    typedef typename Graph::Edge             Edge;\n    typedef typename Graph::Node             Node;\n    typedef typename Graph::Arc              Arc;\n\n    typedef typename Graph::NodeIt              NodeIt;\n    typedef typename Graph::EdgeIt              EdgeIt;\n    typedef typename Graph::ArcIt               ArcIt;\n\n\n    typedef EdgeHolder<Graph> PyEdge;\n    typedef NodeHolder<Graph> PyNode;\n    typedef  ArcHolder<Graph> PyArc;\n\n\n    // predefined array (for map usage)\n    const static unsigned int EdgeMapDim = IntrinsicGraphShape<Graph>::IntrinsicEdgeMapDimension;\n    const static unsigned int NodeMapDim = IntrinsicGraphShape<Graph>::IntrinsicNodeMapDimension;\n\n    typedef NumpyArray<EdgeMapDim,   Singleband<float > > FloatEdgeArray;\n    typedef NumpyArray<EdgeMapDim,   Singleband<UInt32> > UInt32EdgeArray;\n    typedef NumpyArray<EdgeMapDim,   Singleband<Int32 > > Int32EdgeArray;\n    typedef NumpyArray<NodeMapDim,   Singleband<float > > FloatNodeArray;\n    typedef NumpyArray<NodeMapDim,   Singleband<UInt32> > UInt32NodeArray;\n    typedef NumpyArray<NodeMapDim,   Singleband<Int32 > > Int32NodeArray;\n    typedef NumpyArray<NodeMapDim +1,Multiband <float > > MultiFloatNodeArray;\n    typedef NumpyArray<EdgeMapDim +1,Multiband <float > > MultiFloatEdgeArray;\n\n\n    typedef NumpyScalarEdgeMap<Graph,FloatEdgeArray>         FloatEdgeArrayMap;\n    typedef NumpyScalarEdgeMap<Graph,UInt32EdgeArray>        UInt32EdgeArrayMap;\n    typedef NumpyScalarEdgeMap<Graph,Int32EdgeArray>         Int32EdgeArrayMap;\n    typedef NumpyScalarNodeMap<Graph,FloatNodeArray>         FloatNodeArrayMap;\n    typedef NumpyScalarNodeMap<Graph,UInt32NodeArray>        UInt32NodeArrayMap;\n    typedef NumpyScalarNodeMap<Graph,Int32NodeArray>         Int32NodeArrayMap;\n    typedef NumpyMultibandNodeMap<Graph,MultiFloatNodeArray> MultiFloatNodeArrayMap;\n\n\n    typedef ShortestPathDijkstra<Graph,float> ShortestPathDijkstraType;\n\n\n    typedef typename GraphDescriptorToMultiArrayIndex<Graph>::IntrinsicNodeMapShape NodeCoordinate;\n    typedef NumpyArray<1,NodeCoordinate>  NodeCoorinateArray;\n\n    LemonGraphAlgorithmVisitor(const std::string clsName)\n    :clsName_(clsName){\n\n    }\n\n\n    void exportSegmentationAlgorithms()const{\n        python::def(\"_edgeWeightedWatershedsSegmentation\",registerConverters(&pyEdgeWeightedWatershedsSegmentation),\n            (\n                python::arg(\"graph\"),\n                python::arg(\"edgeWeights\"),\n                python::arg(\"seeds\"),\n                python::arg(\"out\")=python::object()\n            ),\n            \"Seeded watersheds on a edge weighted graph\"\n        );\n\n        python::def(\"_nodeWeightedWatershedsSegmentation\",registerConverters(&pyNodeWeightedWatershedsSegmentation),\n            (\n                python::arg(\"graph\"),\n                python::arg(\"nodeWeights\"),\n                python::arg(\"seeds\"),\n                python::arg(\"method\")=std::string(\"regionGrowing\"),\n                python::arg(\"out\")=python::object()\n            ),\n            \"Seeded watersheds on a node weighted graph\"\n        );\n        python::def(\"_nodeWeightedWatershedsSeeds\",registerConverters(&pyNodeWeightedWatershedsSeeds),\n            (\n                python::arg(\"graph\"),\n                python::arg(\"nodeWeights\"),\n                python::arg(\"out\")=python::object()\n            ),\n            \"Generate seeds for node weighted watersheds\"\n        );\n\n        python::def(\"_carvingSegmentation\",registerConverters(&pyCarvingSegmentation),\n            (\n                python::arg(\"graph\"),\n                python::arg(\"edgeWeights\"),\n                python::arg(\"seeds\"),\n                python::arg(\"backgroundLabel\"),\n                python::arg(\"backgroundBias\"),\n                python::arg(\"noBiasBelow\") = 0.0,\n                python::arg(\"out\")=python::object()\n            ),\n            \"Seeded watersheds on a edge weighted graph\"\n        );\n\n\n        python::def(\"_shortestPathSegmentation\",registerConverters(&pyShortestPathSegmentation),\n            (\n                python::arg(\"graph\"),\n                python::arg(\"edgeWeights\"),\n                python::arg(\"nodeWeights\"),\n                python::arg(\"seeds\"),\n                python::arg(\"out\")=python::object()\n            ),\n            \"Seeded shorted path segmentation on a edge and node weighted graph\"\n        );\n\n\n        python::def(\"_felzenszwalbSegmentation\",registerConverters(&pyFelzenszwalbSegmentation),\n            (\n                python::arg(\"graph\"),\n                python::arg(\"edgeWeights\"),\n                python::arg(\"nodeSizes\"),\n                python::arg(\"k\")=300.0f,\n                python::arg(\"nodeNumStop\")=-1,\n                python::arg(\"out\")=python::object()\n            ),\n            \"Felzenwalb graph based segmentation\"\n        );\n    }\n\n    void exportMiscAlgorithms()const{\n\n        python::def(\"_nodeFeatureDistToEdgeWeight\",registerConverters(&pyNodeFeatureDistToEdgeWeight),\n            (\n                python::arg(\"graph\"),\n                python::arg(\"nodeFeatures\"),\n                python::arg(\"metric\"),\n                python::arg(\"out\")=python::object()\n            ),\n            \"convert node features to edge weights with the given metric\"\n        );\n        python::def(\"_nodeFeatureSumToEdgeWeight\",registerConverters(&pyNodeFeatureSumToEdgeWeight),\n            (\n                python::arg(\"graph\"),\n                python::arg(\"nodeFeatures\"),\n                python::arg(\"out\")=python::object()\n            ),\n            \"convert node features to edge weights\"\n        );\n\n        python::def(\"_opengmMulticutDataStructure\",registerConverters(&pyMulticutDataStructure),\n            (\n                python::arg(\"graph\"),\n                python::arg(\"edgeWeights\")\n            )\n        );\n\n        \n\n        python::def(\"nodeGtToEdgeGt\",registerConverters(&pyNodeGtToEdgeGt),\n            (\n                python::arg(\"graph\"),\n                python::arg(\"nodeGt\"),\n                python::arg(\"ignoreLabel\"),\n                python::arg(\"out\")=python::object()\n            )\n        );\n\n        python::def(\"_opengmArgToLabeling\",registerConverters(&pyMulticutArgToLabeling),\n            (\n                python::arg(\"graph\"),\n                python::arg(\"arg\"),\n                python::arg(\"out\")=python::object()\n            )\n        );\n        python::def(\"_wardCorrection\",registerConverters(&pyWardCorrection),\n            (\n                python::arg(\"graph\"),\n                python::arg(\"edgeIndicator\"),\n                python::arg(\"nodeSize\"),\n                python::arg(\"out\")=python::object()\n            ),\n            \"apply wards method to an edgeIndicator\"\n        );\n    }\n\n    void exportSmoothingAlgorithms()const{\n\n        python::def(\"_recursiveGraphSmoothing\",registerConverters(&pyRecursiveGraphSmoothing),\n            (\n                python::arg(\"graph\"),\n                python::arg(\"nodeFeatures\"),\n                python::arg(\"edgeIndicator\"),\n                python::arg(\"gamma\"),\n                python::arg(\"edgeThreshold\"),\n                python::arg(\"scale\"),\n                python::arg(\"iterations\")=1,\n                python::arg(\"outBuffer\")=python::object(),\n                python::arg(\"out\")=python::object()\n            ),\n            \"recursive edge weighted guided graph smoothing\"\n        );\n\n    }\n\n    std::string clsName_;\n    template <class classT>\n    void visit(classT& c) const\n    {   \n        // - watersheds-segmentation\n        // - carving-segmentation\n        // - felzenwalb-segmentation\n        // - labeling\n        exportSegmentationAlgorithms();\n\n        // - node Labels (usefull to make grid graph labels from rag labels)\n        // - node feature distance to edge weights\n        exportMiscAlgorithms();\n\n        // - recursiveGraphSmoothing\n        exportSmoothingAlgorithms();\n    }\n\n\n    static NumpyAnyArray pyWardCorrection(\n        const Graph &           g,\n        const FloatEdgeArray    edgeWeightsArray,\n        const FloatNodeArray    nodeSizeArray,\n        const float             wardness,\n        FloatEdgeArray    outArray\n    ){\n        outArray.reshapeIfEmpty( IntrinsicGraphShape<Graph>::intrinsicEdgeMapShape(g));\n\n        // numpy arrays => lemon maps\n        FloatEdgeArrayMap  edgeWeightsArrayMap(g,edgeWeightsArray);\n        FloatNodeArrayMap  nodeSizeArrayMap(g,nodeSizeArray);\n        FloatEdgeArrayMap  outArrayMap(g,outArray);\n\n        for(EdgeIt iter(g);iter!=lemon::INVALID;++iter){\n            const float uSize=nodeSizeArrayMap[g.u(*iter)];\n            const float vSize=nodeSizeArrayMap[g.v(*iter)];\n            const float w = edgeWeightsArrayMap[*iter];\n            const float ward  = 1.0f/(1.0f/std::log(uSize) + 1.0f/std::log(vSize)  );\n            const float wardF = wardness*ward + (1.0-wardness);\n            outArrayMap[*iter]=w*wardF;\n        }\n        return outArray;\n\n    }\n\n\n    static python::tuple pyMulticutDataStructure(\n        const Graph &           g,\n        const FloatEdgeArray    edgeWeightsArray\n    ){\n        UInt32NodeArray toDenseArray( IntrinsicGraphShape<Graph>::intrinsicNodeMapShape(g));\n\n        // numpy arrays => lemon maps\n        UInt32NodeArrayMap toDenseArrayMap(g,toDenseArray);\n        FloatEdgeArrayMap  edgeWeightsArrayMap(g,edgeWeightsArray);\n\n        NumpyArray<2,UInt32> vis      ((    typename NumpyArray<2,UInt64>::difference_type(g.edgeNum(),2)));\n        NumpyArray<1,float > weights  ((    typename NumpyArray<1,double>::difference_type(g.edgeNum()  )));\n        \n        size_t denseIndex = 0 ;\n        for(NodeIt iter(g);iter!=lemon::INVALID;++iter){\n            toDenseArrayMap[*iter]=denseIndex;\n            ++denseIndex;\n        }\n        denseIndex=0;\n        for(EdgeIt iter(g);iter!=lemon::INVALID;++iter){\n            const size_t dU=toDenseArrayMap[g.u(*iter)];\n            const size_t dV=toDenseArrayMap[g.v(*iter)];\n            vis(denseIndex,0)=std::min(dU,dV);\n            vis(denseIndex,1)=std::max(dU,dV);\n            weights(denseIndex)=edgeWeightsArrayMap[*iter];\n            ++denseIndex;\n        }\n        return python::make_tuple(vis,weights);\n\n    }\n\n\n    static NumpyAnyArray pyNodeGtToEdgeGt(\n        const Graph &           g,\n        const UInt32NodeArray & nodeGt,\n        const Int64 ignoreLabel,\n        UInt32EdgeArray edgeGt\n    ){\n        edgeGt.reshapeIfEmpty(IntrinsicGraphShape<Graph>::intrinsicEdgeMapShape(g));\n\n        // numpy arrays => lemon maps\n        UInt32NodeArrayMap nodeGtMap(g,nodeGt);\n        UInt32EdgeArrayMap  edgeGtMap(g,edgeGt);\n        nodeGtToEdgeGt(g, nodeGtMap, ignoreLabel, edgeGtMap);\n        return edgeGt;\n    }\n\n\n\n    static NumpyAnyArray pyMulticutArgToLabeling(\n        const Graph &              g,\n        const NumpyArray<1,UInt32> arg,\n        UInt32NodeArray            labelsArray\n    ){\n        labelsArray.reshapeIfEmpty( IntrinsicGraphShape<Graph>::intrinsicNodeMapShape(g));\n        UInt32NodeArrayMap labelsArrayMap(g,labelsArray);\n        size_t denseIndex = 0 ;\n        for(NodeIt iter(g);iter!=lemon::INVALID;++iter){\n            labelsArrayMap[*iter]=arg(denseIndex);\n            ++denseIndex;\n        }\n        return labelsArray;\n    }\n    /*\n    static NumpyAnyArray pyNodeIdsLabels(\n        const GRAPH & g,\n        NumpyArray<1,Singleband<UInt32> >  nodeIds,\n        UInt32NodeArray                    nodeLabelArray,\n        NumpyArray<1,Singleband<UInt32> >  out\n    ){\n        // reshape out\n        out.reshapeIfEmpty(nodeIds.shape());\n\n        // numpy arrays => lemon maps\n        UInt32NodeArrayMap nodeLabelArrayMap(g,nodeLabelArray);\n\n        for(size_t i=0;i<nodeIds.shape(0);++i)\n            out(i)=nodeLabelArrayMap[g.nodeFromId(nodeIds(i))];\n        return out;\n    }\n    \n    static NumpyAnyArray pyNodeIdsFeatures(\n        const GRAPH & g,\n        NumpyArray<1,Singleband<UInt32> >  nodeIds,\n        MultiFloatNodeArray                nodeFeaturesArray,\n        NumpyArray<2,Multiband<float >  >  out\n    ){\n        //  reshape out ?\n        typename NumpyArray<2,Multiband<float> >::difference_type outShape(nodeIds.shape(0),nodeFeaturesArray.shape(NodeMapDim));\n        out.reshapeIfEmpty(  NumpyArray<2,Multiband<float >  >::ArrayTraits::taggedShape(outShape,\"xc\"));\n\n        // numpy arrays => lemon maps\n        MultiFloatNodeArrayMap nodeFeaturesArrayMap(g,nodeFeaturesArray);\n\n        typedef typename  NumpyArray<1,int>::difference_type Coord1;\n        for(size_t i=0;i<nodeIds.shape(0);++i)\n            out[Coord1(i)]=nodeFeaturesArrayMap[g.nodeFromId(nodeIds(i))];\n        return out;\n    }\n    */\n    static NumpyAnyArray pyNodeFeatureDistToEdgeWeight(\n        const GRAPH & g,\n        const MultiFloatNodeArray & nodeFeaturesArray,\n        const std::string & functor,\n        FloatEdgeArray edgeWeightsArray\n    ){\n        edgeWeightsArray.reshapeIfEmpty( IntrinsicGraphShape<Graph>::intrinsicEdgeMapShape(g) );\n\n        if(functor==std::string(\"euclidean\") || functor==std::string(\"norm\") || functor==std::string(\"l2\")){\n            typedef  metrics::Norm<float> DistFunctor;\n            DistFunctor f;\n            return pyNodeFeatureDistToEdgeWeightT<DistFunctor>(g,nodeFeaturesArray,f,edgeWeightsArray);\n        }\n        if(functor==std::string(\"squaredNorm\")){\n            typedef  metrics::SquaredNorm<float> DistFunctor;\n            DistFunctor f;\n            return pyNodeFeatureDistToEdgeWeightT<DistFunctor>(g,nodeFeaturesArray,f,edgeWeightsArray);\n        }\n        else if (functor==std::string(\"manhattan\") || functor==std::string(\"l1\")){\n            typedef  metrics::Manhattan<float> DistFunctor;\n            DistFunctor f;\n            return pyNodeFeatureDistToEdgeWeightT<DistFunctor>(g,nodeFeaturesArray,f,edgeWeightsArray);\n        }\n        else if (functor==std::string(\"chiSquared\")){\n            typedef  metrics::ChiSquared<float> DistFunctor;\n            DistFunctor f;\n            return pyNodeFeatureDistToEdgeWeightT<DistFunctor>(g,nodeFeaturesArray,f,edgeWeightsArray);\n        }\n        else{\n            throw std::runtime_error(\n                \"distance not supported\\n\"\n                \"supported distance types:\\n\"\n                \"- euclidean/norm/l2\\n\"\n                \"- squaredNorm\\n\"\n                \"- manhattan/l1\\n\"\n                \"- chiSquared\\n\"\n            );\n        }\n    }\n\n\n\n    static NumpyAnyArray pyNodeFeatureSumToEdgeWeight(\n        const GRAPH & g,\n        const FloatNodeArray & nodeFeaturesArray,\n        FloatEdgeArray edgeWeightsArray\n    ){\n        // reshape out?\n        edgeWeightsArray.reshapeIfEmpty( IntrinsicGraphShape<Graph>::intrinsicEdgeMapShape(g) );\n\n        // numpy arrays => lemon maps\n        FloatNodeArrayMap  nodeFeatureArrayMap(g,nodeFeaturesArray);\n        FloatEdgeArrayMap  edgeWeightsArrayMap(g,edgeWeightsArray);\n        \n        for(EdgeIt e(g);e!=lemon::INVALID;++e){\n            const Edge edge(*e);\n            const Node u=g.u(edge);\n            const Node v=g.v(edge);\n            edgeWeightsArrayMap[edge]=nodeFeatureArrayMap[u]+nodeFeatureArrayMap[v];\n        }\n        return edgeWeightsArray;\n    }\n\n    template<class FUNCTOR>\n    static NumpyAnyArray pyNodeFeatureDistToEdgeWeightT(\n        const GRAPH & g,\n        const MultiFloatNodeArray & nodeFeaturesArray,\n        FUNCTOR & functor,\n        FloatEdgeArray edgeWeightsArray\n    ){\n        // reshape out?\n        edgeWeightsArray.reshapeIfEmpty( IntrinsicGraphShape<Graph>::intrinsicEdgeMapShape(g) );\n\n        // numpy arrays => lemon maps\n        MultiFloatNodeArrayMap nodeFeatureArrayMap(g,nodeFeaturesArray);\n        FloatEdgeArrayMap      edgeWeightsArrayMap(g,edgeWeightsArray);\n        \n        for(EdgeIt e(g);e!=lemon::INVALID;++e){\n            const Edge edge(*e);\n            const Node u=g.u(edge);\n            const Node v=g.v(edge);\n            edgeWeightsArrayMap[edge]=functor(nodeFeatureArrayMap[u],nodeFeatureArrayMap[v]);\n        }\n        return edgeWeightsArray;\n    }\n\n    static NumpyAnyArray pyEdgeWeightedWatershedsSegmentation(\n        const GRAPH & g,\n        FloatEdgeArray edgeWeightsArray,\n        UInt32NodeArray seedsArray,\n        UInt32NodeArray labelsArray\n    ){\n        // resize output ? \n        labelsArray.reshapeIfEmpty( IntrinsicGraphShape<Graph>::intrinsicNodeMapShape(g) );\n\n        // numpy arrays => lemon maps\n        FloatEdgeArrayMap edgeWeightsArrayMap(g,edgeWeightsArray);\n        UInt32NodeArrayMap seedsArrayMap(g,seedsArray);\n        UInt32NodeArrayMap labelsArrayMap(g,labelsArray);\n\n        // call algorithm itself\n        edgeWeightedWatershedsSegmentation(g,edgeWeightsArrayMap,seedsArrayMap,labelsArrayMap);\n\n        // retun labels\n        return labelsArray;\n    }\n\n    static NumpyAnyArray pyNodeWeightedWatershedsSegmentation(\n        const Graph &       g,\n        FloatNodeArray      nodeWeightsArray,\n        UInt32NodeArray     seedsArray,\n        const std::string & method,\n        UInt32NodeArray     labelsArray\n    ){\n\n        // resize output ? \n        labelsArray.reshapeIfEmpty( IntrinsicGraphShape<Graph>::intrinsicNodeMapShape(g) );\n\n\n        WatershedOptions watershedsOption;\n        if(method==std::string(\"regionGrowing\"))\n            watershedsOption.regionGrowing();\n        else\n            watershedsOption.unionFind();\n\n        // numpy arrays => lemon maps\n        FloatNodeArrayMap  nodeWeightsArrayMap(g,nodeWeightsArray);\n        UInt32NodeArrayMap labelsArrayMap(g,labelsArray);\n\n        std::copy(seedsArray.begin(),seedsArray.end(),labelsArray.begin());\n\n        //lemon_graph::graph_detail::generateWatershedSeeds(g, nodeWeightsArrayMap, labelsArrayMap, watershedsOption.seed_options);\n        lemon_graph::watershedsGraph(g, nodeWeightsArrayMap, labelsArrayMap, watershedsOption);\n        //lemon_graph::graph_detail::seededWatersheds(g, nodeWeightsArrayMap, seedsArrayMap, watershedsOption);\n        \n        return labelsArray;\n    }\n\n\n\n\n\n    static NumpyAnyArray pyNodeWeightedWatershedsSeeds(\n        const Graph &       g,\n        FloatNodeArray      nodeWeightsArray,\n        UInt32NodeArray     seedsArray\n    ){\n        const std::string method=\"regionGrowing\";\n        // resize output ? \n        seedsArray.reshapeIfEmpty( IntrinsicGraphShape<Graph>::intrinsicNodeMapShape(g) );\n\n        WatershedOptions watershedsOption;\n        if(method==std::string(\"regionGrowing\"))\n            watershedsOption.regionGrowing();\n\n        // numpy arrays => lemon maps\n        FloatNodeArrayMap  nodeWeightsArrayMap(g,nodeWeightsArray);\n        UInt32NodeArrayMap seedsArrayMap(g,seedsArray);\n\n        lemon_graph::graph_detail::generateWatershedSeeds(g, nodeWeightsArrayMap, seedsArrayMap, watershedsOption.seed_options);\n\n        return seedsArray;\n    }\n\n    static NumpyAnyArray pyCarvingSegmentation(\n        const GRAPH & g,\n        FloatEdgeArray edgeWeightsArray,\n        UInt32NodeArray seedsArray,\n        const UInt32    backgroundLabel,\n        const float     backgroundBias,\n        const float     noBiasBelow,\n        UInt32NodeArray labelsArray\n    ){\n        // resize output ? \n        labelsArray.reshapeIfEmpty( IntrinsicGraphShape<Graph>::intrinsicNodeMapShape(g) );\n\n        // numpy arrays => lemon maps\n        FloatEdgeArrayMap edgeWeightsArrayMap(g,edgeWeightsArray);\n        UInt32NodeArrayMap seedsArrayMap(g,seedsArray);\n        UInt32NodeArrayMap labelsArrayMap(g,labelsArray);\n\n        // call algorithm itself\n        carvingSegmentation(g,edgeWeightsArrayMap,seedsArrayMap,backgroundLabel,backgroundBias,noBiasBelow,labelsArrayMap);\n\n        // retun labels\n        return labelsArray;\n    }\n\n    static NumpyAnyArray pyShortestPathSegmentation(\n        const Graph &       g,\n        FloatEdgeArray      edgeWeightsArray,\n        FloatNodeArray      nodeWeightsArray,\n        UInt32NodeArray     seedsArray,\n        UInt32NodeArray     labelsArray\n    ){\n\n        // resize output ? \n        labelsArray.reshapeIfEmpty( IntrinsicGraphShape<Graph>::intrinsicNodeMapShape(g) );\n\n        // numpy arrays => lemon maps\n        FloatEdgeArrayMap  edgeWeightsArrayMap(g,edgeWeightsArray);\n        FloatNodeArrayMap  nodeWeightsArrayMap(g,nodeWeightsArray);\n        UInt32NodeArrayMap labelsArrayMap(g,labelsArray);\n\n\n\n        std::copy(seedsArray.begin(),seedsArray.end(),labelsArray.begin());\n\n        shortestPathSegmentation<\n            Graph,FloatEdgeArrayMap, FloatNodeArrayMap, UInt32NodeArrayMap, float\n        >(g, edgeWeightsArrayMap, nodeWeightsArrayMap, labelsArrayMap);\n     \n        \n        return labelsArray;\n    }\n\n\n    static NumpyAnyArray pyFelzenszwalbSegmentation(\n        const GRAPH & g,\n        FloatEdgeArray edgeWeightsArray,\n        FloatNodeArray nodeSizesArray,\n        const float k,\n        const int nodeNumStop,\n        UInt32NodeArray labelsArray\n    ){\n        // resize output ? \n        labelsArray.reshapeIfEmpty(  IntrinsicGraphShape<Graph>::intrinsicNodeMapShape(g) );\n\n        // numpy arrays => lemon maps\n        FloatEdgeArrayMap  edgeWeightsArrayMap(g,edgeWeightsArray);\n        FloatNodeArrayMap  nodeSizesArrayMap(g,nodeSizesArray);\n        UInt32NodeArrayMap labelsArrayMap(g,labelsArray);\n\n        // call algorithm itself\n        felzenszwalbSegmentation(g,edgeWeightsArrayMap,nodeSizesArrayMap,k,labelsArrayMap,nodeNumStop);\n\n        // retun labels\n        return labelsArray;\n    }\n\n    static NumpyAnyArray pyRecursiveGraphSmoothing(\n        const GRAPH & g,\n        MultiFloatNodeArray nodeFeaturesArray,\n        FloatEdgeArray      edgeIndicatorArray,\n        const float         lambda,\n        const float         edgeThreshold,\n        const float         scale,\n        const size_t        iterations,\n        MultiFloatNodeArray nodeFeaturesBufferArray,\n        MultiFloatNodeArray nodeFeaturesOutArray\n    ){\n        TaggedShape inShape  = nodeFeaturesArray.taggedShape();\n        TaggedShape outShape = TaggedGraphShape<Graph>::taggedNodeMapShape(g);\n        if(inShape.hasChannelAxis()){\n            outShape.setChannelCount(inShape.channelCount());\n        }\n        nodeFeaturesBufferArray.reshapeIfEmpty(outShape);\n        nodeFeaturesOutArray.reshapeIfEmpty(outShape);\n\n        // numpy arrays => lemon maps\n        MultiFloatNodeArrayMap nodeFeaturesArrayMap(g,nodeFeaturesArray);\n        FloatEdgeArrayMap edgeIndicatorArrayMap(g,edgeIndicatorArray);\n        MultiFloatNodeArrayMap nodeFeaturesBufferArrayMap(g,nodeFeaturesBufferArray);\n        MultiFloatNodeArrayMap nodeFeaturesOutArrayMap(g,nodeFeaturesOutArray);\n\n        // call algorithm itself\n        recursiveGraphSmoothing(g,nodeFeaturesArrayMap,edgeIndicatorArrayMap,lambda,edgeThreshold,scale,iterations,nodeFeaturesBufferArrayMap,nodeFeaturesOutArrayMap);\n\n        // retun smoothed features\n        return nodeFeaturesOutArray;\n    }\n\n};\n\n\ntemplate<class GRAPH>\nclass LemonGridGraphAlgorithmAddonVisitor \n:   public boost::python::def_visitor<LemonGridGraphAlgorithmAddonVisitor<GRAPH> >\n{\npublic:\n\n    friend class def_visitor_access;\n\n    typedef GRAPH Graph;\n\n    typedef LemonGraphAlgorithmVisitor<GRAPH> VisitorType;\n    // Lemon Graph Typedefs\n    \n    typedef typename Graph::index_type       index_type;\n    typedef typename Graph::Edge             Edge;\n    typedef typename Graph::Node             Node;\n    typedef typename Graph::Arc              Arc;\n\n    typedef typename Graph::NodeIt              NodeIt;\n    typedef typename Graph::EdgeIt              EdgeIt;\n    typedef typename Graph::ArcIt               ArcIt;\n\n\n    typedef EdgeHolder<Graph> PyEdge;\n    typedef NodeHolder<Graph> PyNode;\n    typedef  ArcHolder<Graph> PyArc;\n\n\n    // predefined array (for map usage)\n    const static unsigned int EdgeMapDim = IntrinsicGraphShape<Graph>::IntrinsicEdgeMapDimension;\n    const static unsigned int NodeMapDim = IntrinsicGraphShape<Graph>::IntrinsicNodeMapDimension;\n\n    typedef NumpyArray<EdgeMapDim,   Singleband<float > > FloatEdgeArray;\n    typedef NumpyArray<NodeMapDim,   Singleband<float > > FloatNodeArray;\n    typedef NumpyArray<NodeMapDim,   Singleband<UInt32> > UInt32NodeArray;\n    typedef NumpyArray<NodeMapDim,   Singleband<Int32 > > Int32NodeArray;\n    typedef NumpyArray<NodeMapDim +1,Multiband <float > > MultiFloatNodeArray;\n    typedef NumpyArray<EdgeMapDim +1,Multiband <float > > MultiFloatEdgeArray;\n\n\n    typedef NumpyScalarEdgeMap<Graph,FloatEdgeArray>         FloatEdgeArrayMap;\n    typedef NumpyScalarNodeMap<Graph,FloatNodeArray>         FloatNodeArrayMap;\n    typedef NumpyScalarNodeMap<Graph,UInt32NodeArray>        UInt32NodeArrayMap;\n    typedef NumpyScalarNodeMap<Graph,Int32NodeArray>         Int32NodeArrayMap;\n    typedef NumpyMultibandNodeMap<Graph,MultiFloatNodeArray> MultiFloatNodeArrayMap;\n    typedef NumpyMultibandEdgeMap<Graph,MultiFloatEdgeArray> MultiFloatEdgeArrayMap;\n\n    typedef ShortestPathDijkstra<Graph,float> ShortestPathDijkstraType;\n\n\n    typedef typename GraphDescriptorToMultiArrayIndex<Graph>::IntrinsicNodeMapShape NodeCoordinate;\n    typedef NumpyArray<1,NodeCoordinate>  NodeCoorinateArray;\n\n    LemonGridGraphAlgorithmAddonVisitor(const std::string & clsName){}\n\n\n    template <class classT>\n    void visit(classT& c) const\n    {   \n\n        // - edge weights from interpolated image\n        exportMiscAlgorithms(c);\n\n    }\n\n    template <class classT>\n    void exportMiscAlgorithms(classT & c)const{\n        \n\n\n        python::def(\"edgeFeaturesFromInterpolatedImage\",registerConverters(&pyEdgeWeightsFromInterpolatedImage),\n            (\n                python::arg(\"graph\"),\n                python::arg(\"image\"),\n                python::arg(\"out\")=python::object()\n            ),\n            \"convert an image with with ``shape = graph.shape*2 - 1`` to an edge weight array\"\n        );\n\n        python::def(\"edgeFeaturesFromImage\",registerConverters(&pyEdgeWeightsFromImage),\n            (\n                python::arg(\"graph\"),\n                python::arg(\"image\"),\n                python::arg(\"out\")=python::object()\n            ),\n            \"convert an image with with shape = graph.shape OR shape = graph.shape *2 -1 to an edge weight array\"\n        );\n\n        python::def(\"edgeFeaturesFromImage\",registerConverters(&pyEdgeWeightsFromImageMb),\n            (\n                python::arg(\"graph\"),\n                python::arg(\"image\"),\n                python::arg(\"out\")=python::object()\n            ),\n            \"convert an image with with shape = graph.shape OR shape = graph.shape *2 -1 to an edge weight array\"\n        );\n\n\n        c\n        .def(\"affiliatedEdgesSerializationSize\",&pyAffiliatedEdgesSerializationSize,\n            (\n                python::arg(\"rag\"),\n                python::arg(\"affiliatedEdges\")\n            )\n        );\n\n\n        //'python::def(\"edgeFeaturesFromInterpolatedImageCorrected\",registerConverters(&pyEdgeWeightsFromInterpolatedImageCorrected),\n        //'    (\n        //'        python::arg(\"graph\"),\n        //'        python::arg(\"image\"),\n        //'        python::arg(\"out\")=python::object()\n        //'    ),\n        //'    \"convert an image with with shape = graph.shape *2 -1 to an edge weight array\"\n        //'    \"\"\n        //');\n    }\n\n\n\n    static size_t pyAffiliatedEdgesSerializationSize(\n        const GRAPH & gridGraph,\n        const AdjacencyListGraph & rag,\n        const typename AdjacencyListGraph:: template EdgeMap< std::vector<Edge> > & affiliatedEdges\n    ){\n        return affiliatedEdgesSerializationSize(gridGraph, rag, affiliatedEdges);\n    }\n\n\n    static NumpyAnyArray pyEdgeWeightsFromImage(\n        const GRAPH & g,\n        const FloatNodeArray & image,\n        FloatEdgeArray edgeWeightsArray\n    ){\n\n        bool regularShape=true;\n        bool topologicalShape=true;\n\n        for(size_t d=0;d<NodeMapDim;++d){\n            if(image.shape(d)!=g.shape()[d]){\n                regularShape=false;\n            }\n            if(image.shape(d)!=2*g.shape()[d]-1){\n                topologicalShape=false;\n            }\n        }\n       \n        if(regularShape)\n            return pyEdgeWeightsFromOrginalSizeImage(g,image,edgeWeightsArray);\n        else if(topologicalShape)\n            return pyEdgeWeightsFromInterpolatedImage(g,image,edgeWeightsArray);\n        else{\n            vigra_precondition(false, \"shape of edge image does not match graph shape\");\n            // to avid no return warnings\n            return pyEdgeWeightsFromOrginalSizeImage(g,image,edgeWeightsArray);\n        }\n    }\n\n\n    static NumpyAnyArray pyEdgeWeightsFromImageMb(\n        const GRAPH & g,\n        const MultiFloatNodeArray & image,\n        MultiFloatEdgeArray edgeWeightsArray\n    ){\n\n        bool regularShape=true;\n        bool topologicalShape=true;\n\n        for(size_t d=0;d<NodeMapDim;++d){\n            if(image.shape(d)!=g.shape()[d]){\n                regularShape=false;\n            }\n            if(image.shape(d)!=2*g.shape()[d]-1){\n                topologicalShape=false;\n            }\n        }\n       \n        if(regularShape)\n            return pyEdgeWeightsFromOrginalSizeImageMb(g,image,edgeWeightsArray);\n        else if(topologicalShape)\n            return pyEdgeWeightsFromInterpolatedImageMb(g,image,edgeWeightsArray);\n        else{\n            vigra_precondition(false, \"shape of edge image does not match graph shape\");\n            // to avid no return warnings\n            return pyEdgeWeightsFromOrginalSizeImageMb(g,image,edgeWeightsArray);\n        }\n    }\n\n\n    static NumpyAnyArray pyEdgeWeightsFromInterpolatedImage(\n        const GRAPH & g,\n        const FloatNodeArray & interpolatedImage,\n        FloatEdgeArray edgeWeightsArray\n    ){\n\n        for(size_t d=0;d<NodeMapDim;++d){\n            //std::cout<<\"is \"<<interpolatedImage.shape(d)<<\"gs \"<<2*g.shape()[d]-1<<\"\\n\";\n            vigra_precondition(interpolatedImage.shape(d)==2*g.shape()[d]-1, \"interpolated shape must be shape*2 -1\");\n        }\n        edgeWeightsArray.reshapeIfEmpty( IntrinsicGraphShape<Graph>::intrinsicEdgeMapShape(g) );\n\n        // numpy arrays => lemon maps\n        FloatEdgeArrayMap edgeWeightsArrayMap(g,edgeWeightsArray);\n        typedef typename FloatNodeArray::difference_type CoordType;\n        for(EdgeIt iter(g); iter!=lemon::INVALID; ++ iter){\n\n            const Edge edge(*iter);\n            const CoordType uCoord(g.u(edge));\n            const CoordType vCoord(g.v(edge));\n            const CoordType tCoord = uCoord+vCoord;\n            edgeWeightsArrayMap[edge]=interpolatedImage[tCoord];\n        }\n        return edgeWeightsArray;\n    }\n\n    static NumpyAnyArray pyEdgeWeightsFromOrginalSizeImage(\n        const GRAPH & g,\n        const FloatNodeArray & image,\n        FloatEdgeArray edgeWeightsArray\n    ){\n\n        for(size_t d=0;d<NodeMapDim;++d){\n            //std::cout<<\"is \"<<image.shape(d)<<\"gs \"<<2*g.shape()[d]-1<<\"\\n\";\n            vigra_precondition(image.shape(d)==g.shape()[d], \"interpolated shape must be shape*2 -1\");\n        }\n        edgeWeightsArray.reshapeIfEmpty( IntrinsicGraphShape<Graph>::intrinsicEdgeMapShape(g) );\n\n        // numpy arrays => lemon maps\n        FloatEdgeArrayMap edgeWeightsArrayMap(g,edgeWeightsArray);\n        typedef typename FloatNodeArray::difference_type CoordType;\n        for(EdgeIt iter(g); iter!=lemon::INVALID; ++ iter){\n\n            const Edge edge(*iter);\n            const CoordType uCoord(g.u(edge));\n            const CoordType vCoord(g.v(edge));\n            edgeWeightsArrayMap[edge]=(image[uCoord]+image[vCoord])/2.0;\n        }\n        return edgeWeightsArray;\n    }\n\n\n\n    static NumpyAnyArray pyEdgeWeightsFromInterpolatedImageMb(\n        const GRAPH & g,\n        const MultiFloatNodeArray & interpolatedImage,\n        MultiFloatEdgeArray edgeWeightsArray\n    ){\n\n        for(size_t d=0;d<NodeMapDim;++d){\n            //std::cout<<\"is \"<<interpolatedImage.shape(d)<<\"gs \"<<2*g.shape()[d]-1<<\"\\n\";\n            vigra_precondition(interpolatedImage.shape(d)==2*g.shape()[d]-1, \"interpolated shape must be shape*2 -1\");\n        }\n\n        // resize out\n        typename MultiArray<EdgeMapDim+1,int>::difference_type outShape;\n        for(size_t d=0;d<EdgeMapDim;++d){\n            outShape[d]=IntrinsicGraphShape<Graph>::intrinsicEdgeMapShape(g)[d];\n        }\n        outShape[EdgeMapDim] = interpolatedImage.shape(NodeMapDim);\n\n        edgeWeightsArray.reshapeIfEmpty(   MultiFloatEdgeArray::ArrayTraits::taggedShape(outShape,\"nc\") );\n\n        \n        // numpy arrays => lemon maps\n        MultiFloatEdgeArrayMap edgeWeightsArrayMap(g,edgeWeightsArray);\n        typedef typename FloatNodeArray::difference_type CoordType;\n        for(EdgeIt iter(g); iter!=lemon::INVALID; ++ iter){\n\n            const Edge edge(*iter);\n            const CoordType uCoord(g.u(edge));\n            const CoordType vCoord(g.v(edge));\n            const CoordType tCoord = uCoord+vCoord;\n            edgeWeightsArrayMap[edge]=interpolatedImage[tCoord];\n        }\n        return edgeWeightsArray;\n    }\n\n\n    static NumpyAnyArray pyEdgeWeightsFromOrginalSizeImageMb(\n        const GRAPH & g,\n        const MultiFloatNodeArray & image,\n        MultiFloatEdgeArray edgeWeightsArray\n    ){\n\n        for(size_t d=0;d<NodeMapDim;++d){\n            //std::cout<<\"is \"<<image.shape(d)<<\"gs \"<<2*g.shape()[d]-1<<\"\\n\";\n            vigra_precondition(image.shape(d)==g.shape()[d], \"interpolated shape must be shape*2 -1\");\n        }\n\n        // resize out\n        typename MultiArray<EdgeMapDim+1,int>::difference_type outShape;\n        for(size_t d=0;d<EdgeMapDim;++d){\n            outShape[d]=IntrinsicGraphShape<Graph>::intrinsicEdgeMapShape(g)[d];\n        }\n        outShape[EdgeMapDim] = image.shape(NodeMapDim);\n\n\n        //edgeWeightsArray.reshapeIfEmpty( IntrinsicGraphShape<Graph>::intrinsicEdgeMapShape(outShape),\"ec\" );\n\n\n        edgeWeightsArray.reshapeIfEmpty(   MultiFloatEdgeArray::ArrayTraits::taggedShape(outShape,\"nc\") );\n\n\n        // numpy arrays => lemon maps\n        MultiFloatEdgeArrayMap edgeWeightsArrayMap(g,edgeWeightsArray);\n        typedef typename FloatNodeArray::difference_type CoordType;\n        for(EdgeIt iter(g); iter!=lemon::INVALID; ++ iter){\n\n            const Edge edge(*iter);\n            const CoordType uCoord(g.u(edge));\n            const CoordType vCoord(g.v(edge));\n            MultiArray<1, float>  val = image[uCoord];\n            val+=image[vCoord];\n            val/=2.0;\n            edgeWeightsArrayMap[edge]=val;\n        }\n        return edgeWeightsArray;\n    }\n\n\n    /*\n    static NumpyAnyArray pyEdgeWeightsFromInterpolatedImageCorrected(\n        const GRAPH & g,\n        const FloatNodeArray & interpolatedImage,\n        FloatEdgeArray edgeWeightsArray\n    ){\n\n        for(size_t d=0;d<NodeMapDim;++d){\n            //std::cout<<\"is \"<<interpolatedImage.shape(d)<<\"gs \"<<2*g.shape()[d]-1<<\"\\n\";\n            vigra_precondition(interpolatedImage.shape(d)==2*g.shape()[d]-1, \"interpolated shape must be shape*2 -1\");\n        }\n\n\n        edgeWeightsArray.reshapeIfEmpty( IntrinsicGraphShape<Graph>::intrinsicEdgeMapShape(g) );\n\n        // numpy arrays => lemon maps\n        FloatEdgeArrayMap edgeWeightsArrayMap(g,edgeWeightsArray);\n        typedef typename FloatNodeArray::difference_type CoordType;\n        for(EdgeIt iter(g); iter!=lemon::INVALID; ++ iter){\n\n            const Edge edge(*iter);\n            const CoordType uCoord(g.u(edge));\n            const CoordType vCoord(g.v(edge));\n            const CoordType tCoord = uCoord+vCoord;\n            int diffCounter = 0;\n            for(int i=0; i<NodeMapDim; ++i) {\n                if (uCoord[i] != vCoord[i]) {\n                    diffCounter++;\n                }\n            }\n            edgeWeightsArrayMap[edge]=sqrt(diffCounter)*interpolatedImage[tCoord];\n        }\n        return edgeWeightsArray;\n    }\n    */\n};\n\n\n\n} // end namespace vigra\n\n#endif // VIGRA_EXPORT_GRAPH_ALGORITHM_VISITOR_HXX\n", "meta": {"hexsha": "c16e3799af46dda8e1c539b2698a6958edd41aa9", "size": 36665, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "vigranumpy/src/core/export_graph_algorithm_visitor.hxx", "max_stars_repo_name": "ThomasWalter/vigra", "max_stars_repo_head_hexsha": "e92c892aae38c3977dc3f6400f46377b0cb61799", "max_stars_repo_licenses": ["MIT"], "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/export_graph_algorithm_visitor.hxx", "max_issues_repo_name": "ThomasWalter/vigra", "max_issues_repo_head_hexsha": "e92c892aae38c3977dc3f6400f46377b0cb61799", "max_issues_repo_licenses": ["MIT"], "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/export_graph_algorithm_visitor.hxx", "max_forks_repo_name": "ThomasWalter/vigra", "max_forks_repo_head_hexsha": "e92c892aae38c3977dc3f6400f46377b0cb61799", "max_forks_repo_licenses": ["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.0166994106, "max_line_length": 167, "alphanum_fraction": 0.6312559662, "num_tokens": 8484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.2924877936209498}}
{"text": "\n\n#include <NTL/ZZ_p.h>\n#include <NTL/FFT.h>\n\n\n\nNTL_START_IMPL\n\n\n\nNTL_TLS_GLOBAL_DECL(SmartPtr<ZZ_pInfoT>, ZZ_pInfo_stg)\nNTL_TLS_GLOBAL_DECL(SmartPtr<ZZ_pTmpSpaceT>, ZZ_pTmpSpace_stg)\n\nNTL_CHEAP_THREAD_LOCAL ZZ_pInfoT *ZZ_pInfo = 0;\nNTL_CHEAP_THREAD_LOCAL ZZ_pTmpSpaceT *ZZ_pTmpSpace = 0;\nNTL_CHEAP_THREAD_LOCAL bool ZZ_pInstalled = false;\n\n\n\nZZ_pInfoT::ZZ_pInfoT(const ZZ& NewP)\n{\n   if (NewP <= 1) LogicError(\"ZZ_pContext: p must be > 1\");\n\n   p = NewP;\n   size = p.size();\n\n   ExtendedModulusSize = 2*size + \n                 (NTL_BITS_PER_LONG + NTL_ZZ_NBITS - 1)/NTL_ZZ_NBITS;\n\n}\n\n\n\n// we use a lazy strategy for initializing and installing\n// FFTInfo and TmpSpace related to a ZZ_p modulus.  \n// The routines GetFFTInfo and GetTmpSpace make sure this process \n// is complete.\n\nvoid ZZ_p::DoInstall()\n{\n   SmartPtr<ZZ_pTmpSpaceT> tmps; \n\n   do { // NOTE: thread safe lazy init \n      Lazy<ZZ_pFFTInfoT>::Builder builder(ZZ_pInfo->FFTInfo);\n      if (!builder()) break;\n\n      UniquePtr<ZZ_pFFTInfoT> FFTInfo;\n      FFTInfo.make();\n\n      ZZ B, M, M1, M2, M3;\n      long n, i;\n      long q, t;\n      mulmod_t qinv;\n\n      sqr(B, ZZ_pInfo->p);\n\n      LeftShift(B, B, NTL_FFTMaxRoot+NTL_FFTFudge);\n\n      // FIXME: the following is quadratic time...would\n      // be nice to get a faster solution...\n      // One could estimate the # of primes by summing logs,\n      // then multiply using a tree-based multiply, then \n      // adjust up or down...\n\n      // Assuming IEEE floating point, the worst case estimate\n      // for error guarantees a correct answer +/- 1 for\n      // numprimes up to 2^25...for sure we won't be\n      // using that many primes...we can certainly put in \n      // a sanity check, though. \n\n      // If I want a more accuaruate summation (with using Kahan,\n      // which has some portability issues), I could represent \n      // numbers as x = a + f, where a is integer and f is the fractional\n      // part.  Summing in this representation introduces an *absolute*\n      // error of 2 epsilon n, which is just as good as Kahan \n      // for this application.\n\n      // same strategy could also be used in the ZZX HomMul routine,\n      // if we ever want to make that subquadratic\n\n      set(M);\n      n = 0;\n      while (M <= B) {\n         UseFFTPrime(n);\n         q = GetFFTPrime(n);\n         n++;\n         mul(M, M, q);\n      }\n\n      FFTInfo->NumPrimes = n;\n      FFTInfo->MaxRoot = CalcMaxRoot(q);\n\n\n      double fn = double(n);\n\n      // NOTE: the following checks is somewhat academic,\n      // but the implementation relies on it\n\n      if (8.0*fn*(fn+48) > NTL_FDOUBLE_PRECISION)\n         ResourceError(\"modulus too big\");\n\n\n      FFTInfo->rem_struct.init(n, ZZ_pInfo->p, GetFFTPrime);\n      FFTInfo->crt_struct.init(n, ZZ_pInfo->p, GetFFTPrime);\n\n      if (!FFTInfo->crt_struct.special()) {\n         FFTInfo->prime.SetLength(n);\n         FFTInfo->prime_recip.SetLength(n);\n         FFTInfo->u.SetLength(n);\n         FFTInfo->uqinv.SetLength(n);\n\n         // montgomery\n         FFTInfo->reduce_struct.init(ZZ_pInfo->p, ZZ(n) << NTL_SP_NBITS);\n\n         ZZ qq, rr;\n\n         DivRem(qq, rr, M, ZZ_pInfo->p);\n\n         NegateMod(FFTInfo->MinusMModP, rr, ZZ_pInfo->p);\n\n         // montgomery\n         FFTInfo->reduce_struct.adjust(FFTInfo->MinusMModP);\n\n         for (i = 0; i < n; i++) {\n            q = GetFFTPrime(i);\n            qinv = GetFFTPrimeInv(i);\n\n            long tt = rem(qq, q);\n\n            mul(M2, ZZ_pInfo->p, tt);\n            add(M2, M2, rr); \n            div(M2, M2, q);  // = (M/q) rem p\n            \n\n            div(M1, M, q);\n            t = rem(M1, q);\n            t = InvMod(t, q);\n\n            // montgomery\n            FFTInfo->reduce_struct.adjust(M2);\n\n            FFTInfo->crt_struct.insert(i, M2);\n\n            FFTInfo->prime[i] = q;\n            FFTInfo->prime_recip[i] = 1/double(q);\n            FFTInfo->u[i] = t;\n            FFTInfo->uqinv[i] = PrepMulModPrecon(FFTInfo->u[i], q, qinv);\n         }\n\n      }\n\n      tmps = MakeSmart<ZZ_pTmpSpaceT>();\n      tmps->crt_tmp_vec.fetch(FFTInfo->crt_struct);\n      tmps->rem_tmp_vec.fetch(FFTInfo->rem_struct);\n\n      builder.move(FFTInfo);\n   } while (0);\n\n   if (!tmps) {\n      const ZZ_pFFTInfoT *FFTInfo = ZZ_pInfo->FFTInfo.get();\n      tmps = MakeSmart<ZZ_pTmpSpaceT>();\n      tmps->crt_tmp_vec.fetch(FFTInfo->crt_struct);\n      tmps->rem_tmp_vec.fetch(FFTInfo->rem_struct);\n   }\n\n   NTL_TLS_GLOBAL_ACCESS(ZZ_pTmpSpace_stg);\n   ZZ_pTmpSpace_stg = tmps; \n   ZZ_pTmpSpace = ZZ_pTmpSpace_stg.get();\n}\n\n\n\n\nvoid ZZ_p::init(const ZZ& p)\n{\n   ZZ_pContext c(p);\n   c.restore();\n}\n\n\nvoid ZZ_pContext::save() \n{ \n   NTL_TLS_GLOBAL_ACCESS(ZZ_pInfo_stg);\n   ptr = ZZ_pInfo_stg; \n}\n\nvoid ZZ_pContext::restore() const\n{\n   if (ZZ_pInfo == ptr.get()) return; \n   // NOTE: this simple optimization could be useful in some situations,\n   //    for example, a worker thread re-setting the current modulus\n   //    in a multi-threaded build\n\n   NTL_TLS_GLOBAL_ACCESS(ZZ_pInfo_stg);\n   ZZ_pInfo_stg = ptr;\n   ZZ_pInfo = ZZ_pInfo_stg.get();\n\n   NTL_TLS_GLOBAL_ACCESS(ZZ_pTmpSpace_stg);\n   ZZ_pTmpSpace_stg = 0;\n   ZZ_pTmpSpace = 0;\n\n   ZZ_pInstalled = false;\n}\n\n\n\nZZ_pBak::~ZZ_pBak()\n{\n   if (MustRestore) c.restore();\n}\n\nvoid ZZ_pBak::save()\n{\n   c.save();\n   MustRestore = true;\n}\n\n\nvoid ZZ_pBak::restore()\n{\n   c.restore();\n   MustRestore = false;\n}\n\n\nconst ZZ_p& ZZ_p::zero()\n{\n   static const ZZ_p z(INIT_NO_ALLOC); // GLOBAL (assumes C++11 thread-safe init)\n   return z;\n}\n\nNTL_CHEAP_THREAD_LOCAL\nZZ_p::DivHandlerPtr ZZ_p::DivHandler = 0;\n\n   \n\nZZ_p::ZZ_p(INIT_VAL_TYPE, const ZZ& a)  // NO_ALLOC\n{\n   conv(*this, a);\n} \n\nZZ_p::ZZ_p(INIT_VAL_TYPE, long a) // NO_ALLOC\n{\n   conv(*this, a);\n}\n\n\nvoid conv(ZZ_p& x, long a)\n{\n   if (a == 0)\n      clear(x);\n   else if (a == 1)\n      set(x);\n   else {\n      NTL_ZZRegister(y);\n\n      conv(y, a);\n      conv(x, y);\n   }\n}\n\nistream& operator>>(istream& s, ZZ_p& x)\n{\n   NTL_ZZRegister(y);\n\n   NTL_INPUT_CHECK_RET(s, s >> y);\n   conv(x, y);\n\n   return s;\n}\n\nvoid div(ZZ_p& x, const ZZ_p& a, const ZZ_p& b)\n{\n   NTL_ZZ_pRegister(T);\n\n   inv(T, b);\n   mul(x, a, T);\n}\n\nvoid inv(ZZ_p& x, const ZZ_p& a)\n{\n   NTL_ZZRegister(T);\n\n   if (InvModStatus(T, a._ZZ_p__rep, ZZ_p::modulus())) {\n      if (!IsZero(a._ZZ_p__rep) && ZZ_p::DivHandler)\n         (*ZZ_p::DivHandler)(a);\n\n      InvModError(\"ZZ_p: division by non-invertible element\",\n                   a._ZZ_p__rep, ZZ_p::modulus());\n   }\n\n   x._ZZ_p__rep = T;\n}\n\nlong operator==(const ZZ_p& a, long b)\n{\n   if (b == 0)\n      return IsZero(a);\n\n   if (b == 1)\n      return IsOne(a);\n\n   NTL_ZZ_pRegister(T);\n   conv(T, b);\n   return a == T;\n}\n\n\n\nvoid add(ZZ_p& x, const ZZ_p& a, long b)\n{\n   NTL_ZZ_pRegister(T);\n   conv(T, b);\n   add(x, a, T);\n}\n\nvoid sub(ZZ_p& x, const ZZ_p& a, long b)\n{\n   NTL_ZZ_pRegister(T);\n   conv(T, b);\n   sub(x, a, T);\n}\n\nvoid sub(ZZ_p& x, long a, const ZZ_p& b)\n{\n   NTL_ZZ_pRegister(T);\n   conv(T, a);\n   sub(x, T, b);\n}\n\nvoid mul(ZZ_p& x, const ZZ_p& a, long b)\n{\n   NTL_ZZ_pRegister(T);\n   conv(T, b);\n   mul(x, a, T);\n}\n\nvoid div(ZZ_p& x, const ZZ_p& a, long b)\n{\n   NTL_ZZ_pRegister(T);\n   conv(T, b);\n   div(x, a, T);\n}\n\nvoid div(ZZ_p& x, long a, const ZZ_p& b)\n{\n   if (a == 1) {\n      inv(x, b);\n   }\n   else {\n      NTL_ZZ_pRegister(T);\n      conv(T, a);\n      div(x, T, b);\n   }\n}\n\nNTL_END_IMPL\n", "meta": {"hexsha": "58ced8eb22021a33c385981ffb4d7a3832d49a80", "size": 7327, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/ZZ_p.cpp", "max_stars_repo_name": "dklee0501/PLDI_20_242_artifact_publication", "max_stars_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 160.0, "max_stars_repo_stars_event_min_datetime": "2016-05-11T09:45:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T09:32:19.000Z", "max_issues_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/ZZ_p.cpp", "max_issues_repo_name": "dklee0501/Lobster", "max_issues_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57.0, "max_issues_repo_issues_event_min_datetime": "2016-12-26T07:02:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T16:34:31.000Z", "max_forks_repo_path": "LibSource/ExtendedNTL/src/ZZ_p.cpp", "max_forks_repo_name": "ekzyis/CrypTool-2", "max_forks_repo_head_hexsha": "1af234b4f74486fbfeb3b3c49228cc36533a8c89", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 67.0, "max_forks_repo_forks_event_min_datetime": "2016-10-10T17:56:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T22:56:39.000Z", "avg_line_length": 20.4094707521, "max_line_length": 81, "alphanum_fraction": 0.5930121469, "num_tokens": 2310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2924872933327721}}
{"text": "#ifndef PLANE_DETECTOR__\n#define PLANE_DETECTOR__\n\n#include <vector>\n#include <random>\n#include <queue>\n#include \"detected_plane.hpp\"\n#include <eigen3/Eigen/Geometry>\n#include <eigen3/Eigen/Eigenvalues>\n#include <boost/array.hpp>\n#include <boost/thread.hpp>\n#include <exception>\n#include <opencv2/opencv.hpp>\n#include <iostream>\n\n#define __MIN_RANGE__ 0.3\n#define __MAX_RANGE__ 10.0\n\nstruct UnknownDepthException:public std::exception {\n  const char *what() const throw()\n  {\n    return \"Unknown Depth Exception\";\n  }\n  \n};\n\nenum PixelStatus {\n  UNPROCESSED = -3, IN_R_PRIMA, IN_QUEUE\n};\n\n//! @class PlaneDetector\n//! @brief Implements a fast plane detector on RGB-D images as presented in Poppinga IROS 2008\nclass PlaneDetector {\npublic:\n  //! Recommended constructor\n  PlaneDetector(double delta = 1.0, double epsilon = 1.0, double gamma = 10.0, int theta = 1000, double _std_dev = 0.03);\n  \n  //! @brief Detects the planes inside the image\n  int detectPlanes(const cv::Mat &depth);\n  \n  inline std::vector<DetectedPlane> getPlanes() const {\n    return _detected_planes;\n  }\n  \n  void resetStatus();\n  \n  inline int getPos(int i, int j) const {\n    return i + j * _width;\n  }\n  \n  void setCameraParameters(const boost::array< double, 9 >& k_);\n  \n  inline bool isInitialized() {return _initialized;}\n  \n  inline bool setFloatImage(bool new_value) {_float_image = new_value;}\n  \nprotected:\n  double _delta, _epsilon, _gamma; // Dynamically reconfigurable\n  int _theta;\n  std::vector <DetectedPlane> _detected_planes; // Vector de IDs\n  std::vector <int> _detected_ids; // Contiene todos los IDs que son considerados planos\n  std::vector<int> _status_vec; // Relaciona los puntos de la imagen con una region\n  std::queue<int> _q;\n  int _available_pixels;\n  bool _initialized;\n  bool _downsample;\n  double _std_dev;\n  cv::Mat _image;\n\n  std::vector<int> _curr_region; // Saves the region in coordinates --> i + j * _height\n  DetectedPlane _curr_plane;\n  \n  // Internal stuff for update Matrices\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> _es;\n  DetectedPlane _p;\n  \n  // Attributes of the image\n  int _width, _height;\n  bool _float_image;\n  \n  // Camera parameters\n  Eigen::Matrix3d _K;\n  float _kx, _cx, _ky , _cy; // Taken from camera parameters\n  \n  std::vector<Eigen::Vector3d> _color;\n  \n  int getRandomPixel(int region = (int)UNPROCESSED) const;\n  //! @brief Gets the unprocessed nearest neighbor of the image\n  int getNearestNeighbor(int index) const;\n  //! @brief Gets the amount of available pixels in image\n  int availablePixels() const;\n  \n  // For random numbers\n  static std::default_random_engine generator;\n  \n  //! @brief Adds pixels to region and adds its nearest neighbors to the queue (modifying status_vec)\n  void addPixelToRegion(int index, int _curr_region_id);\n  \n  Eigen::Vector3d get3DPoint(int i, int j) const;\n  Eigen::Vector3d get3DPoint(int index) const;\n  //! @brief Gets the depth of a depth image\n  //! @return THe depth value or -1.0 if the data is not valid\n  double getDepth(int i, int j) const;\n  \n  //! @brief updates s_g, m_k, p_k and MSE\n  //! @retval true The conditions of step 8 of the matrix (see [1]) are met --> the matrices are updated\n  bool  updateMatrices(const Eigen::Vector3d &v);\n  \n  //! @brief Initialize the color matrix\n  void initializeColors();\n};\n\nstd::default_random_engine PlaneDetector::generator;\n\nPlaneDetector::PlaneDetector(double delta, double epsilon, double gamma, int theta, double _std_dev):\n_delta(delta), _epsilon(epsilon), _gamma(gamma), _theta(theta),_initialized(false), _downsample(true),_std_dev(_std_dev)\n{\n  initializeColors();\n}\n\nvoid PlaneDetector::initializeColors() {\n  // Different colors for planes\n  Eigen::Vector3d v;\n  v(0) = 0.0; v(1) = 1.0; v(2) = 0.0;\n  _color.push_back(v);\n  v(0) = 1.0; v(1) = 0.0; v(2) = 0.0;\n  _color.push_back(v);\n  v(0) = 0.0; v(1) = 0.0; v(2) = 1.0;\n  _color.push_back(v);\n  v(0) = 0.0; v(1) = 1.0; v(2) = 1.0;\n  _color.push_back(v);\n  v(0) = 1.0; v(1) = 0.0; v(2) = 1.0;\n  _color.push_back(v);\n  v(0) = 1.0; v(1) = 1.0; v(2) = 0.0;\n  _color.push_back(v);\n  \n}\n  \nint PlaneDetector::detectPlanes(const cv::Mat& image)\n{\n  if (!_initialized) {\n    // The camera parameters have to be set before detecting planes\n    return 0;\n  }\n  // First: get parameters of the image (MUST BE AT THE FIRST)\n  _width = image.cols;\n  _height = image.rows;\n  this->_image = image; // TODO: será lento?\n  \n  if (_downsample) {\n    _width /= 2;\n    _height /= 2;\n  }\n  \n  // All internal status to zero or proper values\n  resetStatus();\n  _q.empty();\n  int _curr_region_id = 0;\n  \n  _available_pixels = availablePixels();\n  while (_available_pixels > _theta * 1.1) \n  {\n//     std::cout << \"Available pixels: \" << _available_pixels << std::endl;\n    _curr_region.clear();\n    // Initialization of the algorithm--> random point and nearest neighbor\n    int candidate = getRandomPixel();\n    int nearest = getNearestNeighbor(candidate);\n    \n    if (nearest > 0) \n    {\n      _status_vec[nearest] = _curr_region_id;\n      addPixelToRegion(candidate, _curr_region_id);\n      addPixelToRegion(nearest, _curr_region_id);\n      \n      // Initialize matrices and vectors\n      Eigen::Vector3d r_1 = get3DPoint(candidate);\n      Eigen::Vector3d r_2 = get3DPoint(nearest);\n      _curr_plane.s_g = r_1 + r_2;\n      _curr_plane.m_k = (r_1 - _curr_plane.s_g * 0.5)*(r_1 - _curr_plane.s_g * 0.5).transpose();\n      _curr_plane.m_k += (r_2 - _curr_plane.s_g * 0.5)*(r_2 - _curr_plane.s_g * 0.5).transpose();\n      _curr_plane.p_k = r_1 * r_1.transpose() + r_2*r_2.transpose();\n      _curr_plane.n_points = 2;\n      \n      while (!_q.empty()) \n      {\n        int new_point = _q.front();\n        _q.pop();\n        Eigen::Vector3d v = get3DPoint(new_point);\n        if (updateMatrices(v)) {\n          addPixelToRegion(new_point, _curr_region_id);\n        } else {\n          _available_pixels--;\n        }\n      }\n      \n      // The queue has been emptied --> clear possible QUEUE status and add the region to the detected planes if condition of step 12 (Algorithm 1)\n      if (_curr_region.size() > _theta) {\n        _curr_plane.makeDPositive();\n        _curr_plane.calculateCovariance(_std_dev);\n//         std::cout << \"Detected plane: \" << _curr_plane.toString() << std::endl;\n        _detected_planes.push_back(_curr_plane);\n        _detected_ids.push_back(_curr_region_id);\n      }\n      _curr_region_id++; // The next plane will have a new identificator\n    } else {\n      // No nearest neighbor available --> discard (to R_PRIMA)\n      _status_vec[candidate] = (int)IN_R_PRIMA;\n      _available_pixels--;\n    }\n  }\n  \n  return _detected_planes.size();\n}\n\nvoid PlaneDetector::resetStatus()\n{\n  if (_status_vec.size() != _width*_height) {\n    _status_vec.resize(_width*_height);\n  }\n  for (size_t i = 0; i < _width; i++) {\n    for (size_t j = 0; j < _height; j++) {\n      if (getDepth(i, j) > 0.0) {\n        _status_vec[getPos(i,j)] = (int)UNPROCESSED;\n      } else {\n        _status_vec[getPos(i,j)] = (int)IN_R_PRIMA;\n      }\n    }\n  }\n  \n  _p.init();\n  _curr_plane.init();\n  \n  \n  _detected_planes.clear();\n  _detected_ids.clear();\n}\n\nint PlaneDetector::getRandomPixel(int region) const\n{\n  std::uniform_int_distribution<int> distribution(0, _height * _width - 1);\n  int ret_val;\n  \n  do {\n    ret_val = distribution(generator);\n  } while (_status_vec[ret_val] != region);\n  \n  return ret_val;\n}\n\n//! Gets the unprocessed nearest neighbor of a pixel in a window of size 9\nint PlaneDetector::getNearestNeighbor(int index) const\n{\n  int near = -1;\n  int aux;\n  float min_dist = 1e10;\n  \n  Eigen::Vector3d v = get3DPoint(index);\n  Eigen::Vector3d v_;\n  for (int i = -1; i < 2; i++) {\n    for (int j = -1; j < 2; j++) {\n      if (i != 0 || j != 0) {\n        aux = index + i + j * _width;\n        \n        if (aux > 0 && aux < _height * _width) { // Check bounds\n          if (_status_vec[aux] == (int)UNPROCESSED) {\n            v_ = get3DPoint(aux);\n            double dist = (v - v_).norm();\n            if (dist < min_dist) {\n              near = aux;\n              min_dist = dist;\n            }\n          }\n        }\n      }\n    }\n  }\n  return near;\n}\n\nint PlaneDetector::availablePixels() const\n{\n  bool ret_val = false;\n  int cont = 0;\n  \n  //TODO: Uncomment\n  for (int i = 0; i < _width * _height /*&& cont < _theta*/; i++) {\n    if (_status_vec[i] == (int)UNPROCESSED) \n      cont++;\n  }\n  \n//   std::cout << \"availablePixels() --> cont = \" << cont << std::endl;\n  \n  return cont;\n}\n\nvoid PlaneDetector::setCameraParameters(const boost::array< double, 9 >& k_)\n{\n  for (int i = 0; i < 3;i++) \n  {\n    for (int j = 0; j < 3; j++) \n    {\n      _K(i,j) = k_[i*3 + j];\n    }\n  }\n  \n  _kx = 1.0/_K(0,0);\n  _cx = _K(0,2);\n  _ky = 1.0/_K(1,1);\n  _cy = _K(1,2);\n  _initialized = true;\n}\n\ndouble PlaneDetector::getDepth(int i, int j) const \n{\n  double ret_val = -1.0;\n  if (_downsample) {\n    i *= 2;\n    j *= 2;\n  }\n  \n  if (i >= _image.cols || j >= _image.rows)\n    return -1.0;\n//   std::cout << \"Data: \" << cvbDepth->image.at<float>(i,j) << \" \";\n  if(_float_image)\n    ret_val = _image.at<float>(j, i); /// CAUTION!!!! the indices in cv::Mat are row, cols (elsewhere cols, rows)\n  else\n    ret_val = _image.at<u_int16_t>(j, i)*0.001;\n  if(ret_val < __MIN_RANGE__ || ret_val > __MAX_RANGE__)\n  {\n    ret_val = -1.0;\n  }\n  return ret_val;\n}\n\n\nEigen::Vector3d PlaneDetector::get3DPoint(int i, int j) const\n{\n  Eigen::Vector3d pt;\n  \n  pt[2] = getDepth(i, j);\n  if (_downsample) {\n    i *= 2;\n    j *= 2;\n  }\n  if(pt[2] > __MIN_RANGE__ && pt[2] < __MAX_RANGE__)\n  {\n    pt[0] = (float)(i - _cx) * pt[2] * _kx;\n    pt[1] = (float)(j - _cy) * pt[2] * _ky;\n  } else {\n    throw UnknownDepthException();\n  }\n\n  return pt;\n}\n\nEigen::Vector3d PlaneDetector::get3DPoint(int index) const\n{\n  return get3DPoint(index%_width, index/_width);\n}\n  \nvoid PlaneDetector::addPixelToRegion(int index, int _curr_region_id)\n{\n  _status_vec[index] = _curr_region_id;\n  _curr_region.push_back(index);\n  Eigen::Vector3d v = get3DPoint(index);\n  _available_pixels--;\n  \n  int neighbor = getNearestNeighbor(index);\n  while (neighbor >= 0) {\n    Eigen::Vector3d v_2 = get3DPoint(neighbor);\n    if ( (v-v_2).norm() < _delta) { // First check --> the neighbor is sufficiently near to the point\n      _status_vec[neighbor] = (int)IN_QUEUE;\n      _q.push(neighbor);\n      neighbor = getNearestNeighbor(index);\n    } else {\n      neighbor = -1;\n    }\n  }\n}\n\nbool PlaneDetector::updateMatrices(const Eigen::Vector3d& v)\n{\n  size_t k = _curr_region.size();\n  double div_1 = 1.0 / (double)(k + 1);\n  double div = 1.0 / (double)(k);\n  \n  _p.s_g = _curr_plane.s_g + v;\n  _p.m_k = _curr_plane.m_k + v*v.transpose() - (_p.s_g * div_1)*_p.s_g.transpose() + (_curr_plane.s_g * div) * _curr_plane.s_g.transpose();\n  _p.p_k = _curr_plane.p_k + v*v.transpose();\n  \n  // Calculate d and n (n is the eigenvector related to the lowest eigenvalue)\n  \n  _es.compute(_p.m_k);\n  double min_eigenval = 1e10;\n  int min_i;\n  for (int i = 0; i < 3; i++) {\n    double curr_eigen = fabs(_es.eigenvalues()(i));\n    if (curr_eigen < min_eigenval) {\n      min_eigenval = curr_eigen;\n      min_i = i;\n    }\n    \n  }\n  _p.v = _es.eigenvectors().col(min_i);\n  _p.d = div_1 * _p.v.dot(_p.s_g);\n  \n  // Update the MSE (Eq 3)\n  _p.mse = div_1 * _p.v.transpose() * _p.p_k * _p.v - 2 * _p.v.dot(_p.s_g) * _p.d * div_1 + _p.d * _p.d;\n  _p.n_points = k + 1;\n  \n  \n  // Check if the new plane meets the constraint of algorithm 1 step 8. If so, update the values of the matrices of the class\n  if (_p.mse < _epsilon && _p.distance(v) < _gamma) \n  {\n    // Meets the constraints --> Actualize the plane\n    _p.r_g = _p.s_g * div_1;\n    _curr_plane = _p;\n    \n    return true;\n  }\n  return false;\n}\n\n#endif\n", "meta": {"hexsha": "e00606a70ee0d1ab5704319a1f2075f8040a9ecc", "size": 11724, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/plane_detector/plane_detector.hpp", "max_stars_repo_name": "robotics-upo/plane_detector", "max_stars_repo_head_hexsha": "c3ca7d25b5be9c7d7063489523bed9388d4a5ee0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 42.0, "max_stars_repo_stars_event_min_datetime": "2018-08-02T01:08:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T05:11:27.000Z", "max_issues_repo_path": "include/plane_detector/plane_detector.hpp", "max_issues_repo_name": "robotics-upo/plane_detector", "max_issues_repo_head_hexsha": "c3ca7d25b5be9c7d7063489523bed9388d4a5ee0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-07-17T04:03:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-27T11:02:45.000Z", "max_forks_repo_path": "include/plane_detector/plane_detector.hpp", "max_forks_repo_name": "robotics-upo/plane_detector", "max_forks_repo_head_hexsha": "c3ca7d25b5be9c7d7063489523bed9388d4a5ee0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-08-03T07:15:20.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-03T06:33:38.000Z", "avg_line_length": 27.5858823529, "max_line_length": 147, "alphanum_fraction": 0.6340839304, "num_tokens": 3661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.29243506406617564}}
{"text": "\n#include <iomanip>\n#include <cassert>\n#include \"boost/format.hpp\"\n\n#include \"amilab_messages.h\"\n#include \"DefineClass.hpp\"\n#include \"Variable.hpp\"\n#include <math.h>\n#include <iostream>\n\n#define NEW_SMARTPTR(type, var, value) \\\n  boost::shared_ptr<type> var(new type(value));\n\n#define RETURN_VARPTR(type,  value) \\\n  boost::shared_ptr<type> newval(new type(value)); \\\n  return Variable<type>::ptr( new Variable<type>(newval));\n\n#include <boost/numeric/conversion/cast.hpp>  \n\n\nstd::vector<std::string> AMILabType<float>::conversion_types = \n        {   \"bool\", \"double\", \n            \"long\", \"int\", \"short\", \n            \"unsigned long\", \"unsigned short\", \n            \"unsigned char\" };\n\n//------------------------------------------------------\n//------- Variable<float>\n//------------------------------------------------------\n\n/// Copy contents to new variable\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::NewCopy() const\n{\n  float_ptr newval( new float(Value()));\n  Variable<float>::ptr newvar(new Variable<float>(newval));\n  return newvar;\n}\n\n\n// Arithmetic operators\n\n/// +a\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator +()\n{  RETURN_VARPTR(float,Value());}\n\n/// prefix ++ operator ++a\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator ++()\n{\n  //std::cout << \"**\" << std::endl;\n  RETURN_VARPTR(float,++RefValue());\n}\n\n/// postfix ++ operator a++\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator ++(int)\n{\n  //std::cout << \"**\" << std::endl;\n  RETURN_VARPTR(float,RefValue()++);\n}\n\n/// -a\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator -()\n{   RETURN_VARPTR(float,-Value());}\n\n/// prefix -- operator --a\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator --()\n{  RETURN_VARPTR(float,--RefValue()); }\n\n/// postfix -- operator a--\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator --(int)\n{  RETURN_VARPTR(float,RefValue()--);  }\n\n\n\n/// a+b\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator +(const BasicVariable::ptr& b)\n{\n  if (b->IsNumeric()) {\n    RETURN_VARPTR(float,Value()+b->GetValueAsDouble());\n  }\n  else\n    CLASS_ERROR(\"operation not defined\");\n  return this->NewReference(); \n}\n\n/// a+=b\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator +=(const BasicVariable::ptr& b)\n{ \n  if (b->IsNumeric()) {\n    RefValue() += b->GetValueAsDouble();\n  } else\n    CLASS_ERROR(\"operation not defined\");\n  return this->NewReference(); \n}\n\n/// a-b\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator -(const BasicVariable::ptr& b)\n{\n  if (b->IsNumeric()) {\n    RETURN_VARPTR(float,Value()-b->GetValueAsDouble());\n  }\n  else\n    CLASS_ERROR(\"operation not defined\");\n  return this->NewReference(); \n}\n\n/// a-=b\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator -=(const BasicVariable::ptr& b)\n{ \n  if (b->IsNumeric()) {\n    RefValue() -= b->GetValueAsDouble();\n  } else\n    CLASS_ERROR(\"operation not defined\");\n  return this->NewReference(); \n}\n\n/// a*b\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator *(const BasicVariable::ptr& b)\n{\n  if (b->IsNumeric()) {\n    RETURN_VARPTR(float,Value()*b->GetValueAsDouble());\n  } \n  else\n    CLASS_ERROR(\"operation not defined\");\n  return this->NewReference(); \n}\n\n/// a*=b\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator *=(const BasicVariable::ptr& b)\n{ \n  if (b->IsNumeric()) {\n    RefValue() *= b->GetValueAsDouble();\n  } else\n    CLASS_ERROR(\"operation not defined\");\n  return this->NewReference(); \n}\n\n/// a/b\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator /(const BasicVariable::ptr& b)\n{\n  if (b->IsNumeric()) {\n    RETURN_VARPTR(float,Value()/b->GetValueAsDouble());\n  }\n  else\n    CLASS_ERROR(\"operation not defined\");\n  return this->NewReference(); \n}\n\n/// a/=b\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator /=(const BasicVariable::ptr& b)\n{ \n  if (b->IsNumeric()) {\n    RefValue() /= b->GetValueAsDouble();\n  } else\n    CLASS_ERROR(\"operation not defined\");\n  return this->NewReference(); \n}\n\n/// a%b\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator %(const BasicVariable::ptr& b)\n{\n  if (b->IsNumeric()) {\n    RETURN_VARPTR(float, ((int) round(Value())) % ((int) round(b->GetValueAsDouble())));\n  } else\n    CLASS_ERROR(\"operation not defined\");\n  return this->NewReference(); \n}\n\n/// a%=b\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator %=(const BasicVariable::ptr& b)\n{ \n  if (b->IsNumeric()) {\n    RefValue() =  ((int) round(Value())) % ((int) round(b->GetValueAsDouble()));\n  } else\n    CLASS_ERROR(\"operation not defined\");\n  return this->NewReference(); \n}\n\n//  Comparison Operators\n\n/// a<b\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator <(const BasicVariable::ptr& b)\n{ \n  if (b->IsNumeric()) {\n    RETURN_VARPTR(bool,Value()<b->GetValueAsDouble());\n  } else\n    CLASS_ERROR(\"operation not defined\");\n  return this->NewReference(); \n}\n\n/// a<=b\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator <=(const BasicVariable::ptr& b)\n{ \n  if (b->IsNumeric()) {\n    RETURN_VARPTR(bool,Value()<=b->GetValueAsDouble());\n  } else\n    CLASS_ERROR(\"operation not defined\");\n  return this->NewReference(); \n}\n\n/// a>b\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator >(const BasicVariable::ptr& b)\n{ \n  if (b->IsNumeric()) {\n    RETURN_VARPTR(bool,Value()>b->GetValueAsDouble());\n  } else\n    CLASS_ERROR(\"operation not defined\");\n  return this->NewReference(); \n}\n\n/// a>=b\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator >=(const BasicVariable::ptr& b)\n{ \n  if (b->IsNumeric()) {\n    RETURN_VARPTR(bool,Value()>=b->GetValueAsDouble());\n  } else\n    CLASS_ERROR(\"operation not defined\");\n  return this->NewReference(); \n}\n\n/// a!=b\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator !=(const BasicVariable::ptr& b)\n{ \n  if (b->IsNumeric()) {\n    RETURN_VARPTR(bool,Value()!=b->GetValueAsDouble());\n  } else\n    CLASS_ERROR(\"operation not defined\");\n  return this->NewReference(); \n}\n\n\n/// a==b\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator ==(const BasicVariable::ptr& b)\n{ \n  //std::cout << __func__ << std::endl;\n  if (b->IsNumeric()) {\n    RETURN_VARPTR(bool,Value()==b->GetValueAsDouble());\n  } else\n    CLASS_ERROR(\"operation not defined\");\n  return this->NewReference(); \n}\n\n// Logical operators\n\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator !() \n{\n  RETURN_VARPTR(bool,!(Value()>0.5));\n}\n\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator &&(const BasicVariable::ptr& b) \n{\n  if (b->IsNumeric()) {\n    RETURN_VARPTR(bool,(Value()>0.5)&& (bool) (b->GetValueAsDouble()>0.5));\n  } else\n    CLASS_ERROR(\"operation not defined\");\n  return this->NewReference(); \n}\n\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator ||(const BasicVariable::ptr& b) \n{\n  if (b->IsNumeric()) {\n    RETURN_VARPTR(bool,(Value()>0.5) || (bool) (b->GetValueAsDouble()>0.5));\n  } else\n    CLASS_ERROR(\"operation not defined\");\n  return this->NewReference(); \n}\n\n// Mathematical functions\n#define VAR_IMPL_FUNC(type,fname,func) \\\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<type>::m_##fname() \\\n{ \\\n    RETURN_VARPTR(float, func(Value())); \\\n}\n\nVAR_IMPL_FUNC(float,  sin,  sin)\nVAR_IMPL_FUNC(float,  cos,  cos)\nVAR_IMPL_FUNC(float,  tan,  tan)\nVAR_IMPL_FUNC(float,  asin, asin)\nVAR_IMPL_FUNC(float,  acos, acos)\nVAR_IMPL_FUNC(float,  atan, atan)\nVAR_IMPL_FUNC(float,  fabs, fabs)\nVAR_IMPL_FUNC(float,  round,round)\nVAR_IMPL_FUNC(float,  floor,floor)\nVAR_IMPL_FUNC(float,  exp,  exp)\nVAR_IMPL_FUNC(float,  log,  1.0/log(10.0)*log)\nVAR_IMPL_FUNC(float,  ln,   log)\nVAR_IMPL_FUNC(float,  norm, fabs)\nVAR_IMPL_FUNC(float,  sqrt, sqrt)\n//VAR_IMPL_FUNC(float,  pow,  pow)\n\n\n\n//---------------------------------------------------\ntemplate<> AMI_DLLEXPORT\nBasicVariable::ptr Variable<float>::TryCast(\n    const std::string& type_string) const\n{\n  try\n  {\n    // cast to double\n    if (type_string==AMILabType<double>::name_as_string()) {\n      RETURN_VARPTR(double, boost::numeric_cast<double>(Value()));\n    } else\n    // cast to int\n    if (type_string==AMILabType<int>::name_as_string()) {\n      RETURN_VARPTR(int, boost::numeric_cast<int>(Value()));\n    } else \n    // cast to long\n    if (type_string==AMILabType<long>::name_as_string()) {\n      RETURN_VARPTR(long, boost::numeric_cast<long>(Value()));\n    } else \n    // cast to unsigned long\n    if (type_string==AMILabType<unsigned long>::name_as_string()) {\n      RETURN_VARPTR(unsigned long, boost::numeric_cast<unsigned long>(Value()));\n    } else \n    // cast to short\n    if (type_string==AMILabType<short>::name_as_string()) {\n      RETURN_VARPTR(short, boost::numeric_cast<short>(Value()));\n    } else \n    // cast to unsigned short\n    if (type_string==AMILabType<unsigned short>::name_as_string()) {\n      RETURN_VARPTR(unsigned short, boost::numeric_cast<unsigned short>(Value()));\n    } else \n    // cast to unsigned char\n    if (type_string==AMILabType<unsigned char>::name_as_string()) {\n      RETURN_VARPTR(unsigned char, boost::numeric_cast<unsigned char>(Value()));\n    } else\n    // cast to bool\n    if (type_string==AMILabType<bool>::name_as_string()) {\n      RETURN_VARPTR(bool, boost::numeric_cast<bool>(Value()));\n    } else\n    {\n      // make default conversion to double??\n      CLASS_ERROR((boost::format(\"No conversion available for variable %1% from float to %2%\") % _name % type_string).str().c_str());\n    }\n  } catch (std::bad_cast &e)\n  {\n    CLASS_ERROR((boost::format(\"%1%, for variable %2% from float to %3%\") % e.what() % _name % type_string).str().c_str());\n    return BasicVariable::ptr();\n  }\n  return BasicVariable::ptr();\n}\n\n\n//\ntemplate<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::BasicCast(const int& type)\n{\n#define NUMCAST(amitype,type) \\\n      case amitype:  { RETURN_VARPTR(type, boost::numeric_cast<type>(Value())); }\n\n  try\n  {\n    switch((WORDTYPE)type) {\n      NUMCAST( WT_UNSIGNED_CHAR,  unsigned char )\n      NUMCAST( WT_SIGNED_SHORT,   short         )\n      NUMCAST( WT_UNSIGNED_SHORT, unsigned short)\n      NUMCAST( WT_SIGNED_INT,     int           )\n      NUMCAST( WT_SIGNED_LONG,    long          )\n      NUMCAST( WT_FLOAT,          float         )\n      NUMCAST( WT_DOUBLE,         double        )\n      case WT_UNSIGNED_INT: { RETURN_VARPTR(float, (unsigned int) Value()); }\n      default:\n        CLASS_ERROR(( boost::format(\"Conversion to type %1% not available\")%((WORDTYPE)type)).str().c_str());\n    }\n  } catch (std::bad_cast &e)\n  {\n    CLASS_ERROR((boost::format(\"%1%, for variable %2% from float to WORDTYPE %3%\") % e.what() % _name % (WORDTYPE)type ).str().c_str());\n    return BasicVariable::ptr();\n  }\n\n  RETURN_VARPTR(float, Value());\n\n}\n\n//\ntemplate<> AMI_DLLEXPORT\nBasicVariable::ptr Variable<float>::TernaryCondition(const BasicVariable::ptr& v1, const BasicVariable::ptr&v2)\n{\n\n  if (Value()>0.5) {\n    return v1->NewReference();\n  } else {\n    return v2->NewReference();\n  }\n  return NewReference();\n}\n\n#if !defined(ARRAY_SIZE)\n    #define ARRAY_SIZE(x) (sizeof((x)) / sizeof((x)[0]))\n#endif\n\ntemplate<> AMI_DLLEXPORT\n  BasicVariable::ptr Variable<float>::operator[](const BasicVariable::ptr& v)\n{\n  if (v->IsNumeric()) {\n    float* pointer = this->Pointer().get();\n    //std::cout << \"Size of array \" << ARRAY_SIZE(pointer) << std::endl;\n    // at the user own risk\n    float res = pointer[(int)(v->GetValueAsDouble()+0.5)];\n    return AMILabType<float>::CreateVar(res);\n  } else\n    CLASS_ERROR(\"operator[] only takes a numerical parameter\");\n  return NewReference();\n}\n\ntemplate<> AMI_DLLEXPORT \nBasicVariable::ptr Variable<float>::operator =(const BasicVariable::ptr& b)\n{\n  if (b->IsNumeric()) {\n    RefValue() = b->GetValueAsDouble();\n  } else\n    CLASS_ERROR(\"operation not defined\");\n  return NewReference();\n}\n", "meta": {"hexsha": "5c576ffce915e92a050afe4b9b98b5c4fec4a113", "size": 12035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/LanguageBase/Variable_float.cpp", "max_stars_repo_name": "karlkrissian/amilab_engine", "max_stars_repo_head_hexsha": "a361884e30bf3a92343319e70395fcaccb7abdde", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LanguageBase/Variable_float.cpp", "max_issues_repo_name": "karlkrissian/amilab_engine", "max_issues_repo_head_hexsha": "a361884e30bf3a92343319e70395fcaccb7abdde", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-08-11T09:50:37.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-11T14:02:46.000Z", "max_forks_repo_path": "src/LanguageBase/Variable_float.cpp", "max_forks_repo_name": "karlkrissian/amilab_engine", "max_forks_repo_head_hexsha": "a361884e30bf3a92343319e70395fcaccb7abdde", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0, "max_line_length": 136, "alphanum_fraction": 0.6563356876, "num_tokens": 3196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2923534660948397}}
{"text": "#ifndef STAN_MATH_TORSTEN_TWOCPT_EFFCPT_HPP\n#define STAN_MATH_TORSTEN_TWOCPT_EFFCPT_HPP\n\n#include <Eigen/Dense>\n#include <stan/math/prim/err/check_greater_or_equal.hpp>\n#include <stan/math/torsten/meta.hpp>\n#include <stan/math/torsten/to_array_2d.hpp>\n#include <stan/math/torsten/pmx_solve_cpt.hpp>\n#include <stan/math/torsten/ev_solver.hpp>\n#include <stan/math/torsten/ev_manager.hpp>\n#include <stan/math/torsten/pmx_twocpt_effcpt_model.hpp>\n#include <stan/math/torsten/pmx_population_check.hpp>\n#include <stan/math/prim/meta/return_type.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 coupled with effective-compartment\n * model with analytical solution.\n *\n * @tparam Ts types of parameters, see <code>pmx_solve_cpt</code> for\n *         details. \n * @return a matrix with predicted amount in each compartment \n *         at each event. \n *\n */\n  template <typename... Ts>\n  auto pmx_solve_twocpt_effcpt(Ts... args) {\n    return PMXSolveCPT<PMXTwocptEffCptModel>::solve(args...);\n  }\n\n/**\n * Overload function to allow user to pass an std::vector for \n * pMatrix/bioavailability/tlag\n */\n  template <typename T0, typename T1, typename T2, typename T3,\n            typename T_par, typename T_biovar, typename T_tlag,\n            typename = require_any_not_std_vector_t<T_par, T_biovar, T_tlag> >\n  stan::matrix_return_t<T0, T1, T2, T3, T_par, T_biovar, T_tlag>\n  pmx_solve_twocpt_effcpt(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<T_par>& pMatrix,\n                          const std::vector<T_biovar>& biovar,\n                          const std::vector<T_tlag>& tlag) {\n    auto param_ = torsten::to_array_2d(pMatrix);\n    auto biovar_ = torsten::to_array_2d(biovar);\n    auto tlag_ = torsten::to_array_2d(tlag);\n\n    return pmx_solve_twocpt_effcpt(time, amt, rate, ii, evid, cmt, addl, ss,\n                                   param_, biovar_, tlag_);\n  }\n\n  /**\n   * For population models, we follow the call signature\n   * but add the arrays of the length of each individual's data. \n   * The size of that vector is the size of\n   * the population.\n   */\ntemplate <typename T0, typename T1, typename T2, typename T3, typename T4,\n          typename T5, typename T6>\nEigen::Matrix<typename  EventsManager<NONMENEventsRecord<T0, T1, T2, T3>, NonEventParameters<T0, T4, std::vector, std::tuple<T5, T6> > >::T_scalar, // NOLINT\n              Eigen::Dynamic, Eigen::Dynamic>\npmx_solve_group_twocpt_effcpt(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                       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 ER = NONMENEventsRecord<T0, T1, T2, T3>;\n  using EM = EventsManager<ER, NonEventParameters<T0, T4, std::vector, std::tuple<T5, T6> >>;\n\n  int nCmt = torsten::PMXTwocptEffCptModel<double>::Ncmt;\n  ER events_rec(nCmt, len, time, amt, rate, ii, evid, cmt, addl, ss);\n\n  static const char* caller(\"pmx_solve_group_twocpt_effcpt\");\n  torsten::pmx_population_check(len, time, amt, rate, ii, evid, cmt, addl, ss,\n                                pMatrix, biovar, tlag, caller);\n\n  using model_type = torsten::PMXTwocptEffCptModel<typename EM::T_par>;\n   EventSolver<model_type, EM> pr;\n\n  Eigen::Matrix<typename EM::T_scalar, -1, -1> pred(events_rec.total_num_event_times, nCmt);\n\n  pr.pred(events_rec, pred, dsolve::PMXAnalyiticalIntegrator(), pMatrix, biovar, tlag);\n\n  return pred;\n}\n\n}\n#endif\n", "meta": {"hexsha": "d6ce81c793cca2dcf56c39f406fe8a75ebf08fd3", "size": 4374, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pmx_solve_twocpt_effcpt.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": "pmx_solve_twocpt_effcpt.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": "pmx_solve_twocpt_effcpt.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": 41.2641509434, "max_line_length": 157, "alphanum_fraction": 0.6250571559, "num_tokens": 1166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2923534602036347}}
{"text": "/*\n * Prover_toom.cpp\n *\n *  Created on: 24.04.2011\n *      Author: stephaniebayer\n */\n\n#include \"Prover_toom.h\"\n\n#include<vector>\n#include \"Cipher_elg.h\"\n#include \"G_q.h\"\n#include \"Mod_p.h\"\n#include \"Functions.h\"\n#include \"ElGammal.h\"\n#include \"multi_expo.h\"\n#include \"func_pro.h\"\n#include <fstream>\n#include <time.h>\n\n#include <NTL/ZZ.h>\nNTL_CLIENT\n\n//extern G_q G;\nextern G_q H;\nextern Pedersen Ped;\nextern ElGammal El;\nextern long mu;\nextern long mu_h;\nextern long m_r;\n\nProver_toom::Prover_toom() {\n\t// TODO Auto-generated constructor stub\n\n}\n\nProver_toom::Prover_toom(vector<vector<Cipher_elg>* >* Cin,vector<vector<ZZ>*>* Rin, vector<vector<vector<long>* >* >* piin, vector<long> num, ZZ gen){\n\n\t// set the dimensions of the row and columns according to the user input\n\tm = num[1]; //number of rows\n\tn = num[2]; //number of columns\n\tC = Cin; //sets the reencrypted chipertexts to the input\n\tR = Rin; //sets the random elements to the input\n\tpi = piin; // sets the permutation to the input\n\tomega_mulex = num[3]; //windowsize for sliding-window technique\n\tomega_sw = num[4]; //windowsize for multi-expo technique\n\tomega_LL = num[7]; //windowsize for multi-expo technique\n\n\n\t//Creates the matrices A\n\tA = new vector<vector<ZZ>* >(m);\n\tfunc_pro::set_A(A,pi, m, n);\n\n\n\t//Allocate the storage needed for the vectors\n\tchal_x6 = new vector<ZZ>(2*m); //x6, x6^2, ... challenges from round 6\n\tchal_y6 = new vector<ZZ>(n); //y6, y6^2, ... challenges form round 6\n\tchal_x8 = new vector<ZZ>(2*m +1); //x8, x8^2, ... challenges from round 8\n\n\t//Allocate the storage needed for the vectors\n\tc_A = new vector<Mod_p>(m+1); //commitments to the rows in A\n\tr_A = new vector<ZZ>(m+1); //random elements used for the commitments\n\n\tD = new vector<vector<ZZ>* >(m+1); //vector containing in the first row random values and in all others y*A(ij) + B(ij)-z\n\tD_h = new vector<vector<ZZ>* >(m); //Vector of the Hadamare products of the rows in D\n\tD_s = new vector<vector<ZZ>* >(m+1); //Shifted rows of D_h\n\td = new vector<ZZ>(n); //containing random elements to proof product of D_hm\n\tDelta = new vector<ZZ>(n); //containing random elements to proof product of D_hm\n\td_h = new vector<ZZ>(n); // vector containing the last row of D-h\n\n\tr_D_h = new vector<ZZ>(m);//random elements for commitments to D_h\n\tc_D_h = new vector<Mod_p>(m+2);//commitments to the rows in D_h\n\tC_small = new vector<vector<Cipher_elg>* >(m_r); //matrix of reduced ciphertexts\n\n\tB = new vector<vector<ZZ>* >(m);//matrix of permuted exponents, exponents are x2^i, i=1, ..N\n\tbasis_B = new vector<vector<vector<long>* >* >(m); //basis for the multi-expo, containing the Bij\n\tB_small = new vector<vector<ZZ>* >(m_r); //matrix of reduced exponents\n\tB_0 = new vector<ZZ>(n); //vector containing random exponents\n\tbasis_B0 = new vector<vector<long>* >(n); //basis for multi-expo, containing  the B0j\n\tr_B = new vector<ZZ>(m); //random elements used to commit to B\n\tr_B_small = new vector<ZZ>(m_r); //random elements for commitments to B_small\n\tc_B = new vector<Mod_p>(m); //vector of commitments to rows in T\n\ta = new vector<ZZ>(2*m); //elements used for reencryption in round 5\n\tr_a = new vector<ZZ>(2*m); //random elements to commit to elements in a\n\tc_a = new vector<Mod_p>(2*m); //commitments to elements a\n\tE = new vector<Cipher_elg>(2*m); //vector of the products of the diogonals of A^T generated in round 7\n\trho_a = new vector<ZZ>(2*m); //contains random elements used for the reencryption in 7\n\n\tC_c = new vector<Cipher_elg>(mu_h);  //Ciphertexts to prove correctness of reduction\n\tc_a_c= new vector<Mod_p>(mu_h); //vector containing the commitments to value used for the reencryption of E_c\n\ta_c= new vector<ZZ>(mu_h); //vector containing the values used for reecnrcyption\n\tr_c= new vector<ZZ>(mu_h); //random elements used to commit to a_c\n\trho_c = new vector<ZZ>(mu_h); //random elements used in the reencryption\n\n\ta = new vector<ZZ>(2*mu); //elements used for reencryption in round 5\n\tr_a = new vector<ZZ>(2*mu); //random elements to commit to elements in a\n\tc_a = new vector<Mod_p>(2*mu); //commitments to elements a\n\tE = new vector<Cipher_elg>(2*mu); //vector of the products of the diogonals of Y^T generated in round 9\n\trho_a = new vector<ZZ>(2*mu); //contains random elements used for the reencryption in 9\n\n\n\tDl = new vector<ZZ>(2*m+1); //bilinear_map(Y_pi, U, chal_t)\n\tr_Dl = new vector<ZZ>(2*m+1); //random elements to commit to the C_ls\n\tc_Dl = new vector<Mod_p>(2*m +1); //commitments to the C_ls\n\n\td_bar = new vector<ZZ>(n);// chal_x8*D_h(m-1) +d\n\tDelta_bar = new vector<ZZ>(n);//chal_x8*d_h+Delta\n\tD_h_bar = new vector<ZZ>(n);//sum over the rows in D_h\n\n\tB_bar  = new vector<ZZ>(n); // sum over the rows in B multiplied by chal^i\n\tA_bar = new vector<ZZ>(n); //sum over the rows in A times the challenges\n\tD_s_bar = new vector<ZZ>(n); // sum over the rows in D_s times the challenges\n\n}\n\n//Destructor deletes all pointers and frees the storage\nProver_toom::~Prover_toom() {\n\tdelete chal_x6;\n\tdelete chal_y6;\n\tdelete chal_x8;\n\tdelete c_A;\n\tdelete r_A;\n\n\tFunctions::delete_vector(D);\n\tFunctions::delete_vector(D_h);\n\tFunctions::delete_vector(D_s);\n\tdelete d;\n\tdelete Delta;\n\tdelete d_h;\n\n\tdelete r_D_h;\n\tdelete c_D_h;\n\tFunctions::delete_vector(B);\n\tFunctions::delete_vector(basis_B);\n\tdelete B_0;\n\tFunctions::delete_vector(basis_B0);\n\tdelete r_B;\n\tdelete r_B_small;\n\tdelete c_B;\n\tdelete a;\n\tdelete r_a;\n\tdelete c_a;\n\tdelete rho_a;\n\n\tdelete Dl;\n\tdelete r_Dl;\n\tdelete c_Dl;\n\n\tdelete D_h_bar;\n\tdelete d_bar;\n\tdelete Delta_bar;\n\tdelete B_bar;\n\tdelete A_bar;\n\tdelete D_s_bar;\n\n\tdelete C_c;\n\tdelete c_a_c; //vector containing the commitments to value used for the reencryption of E_low_up\n\tdelete a_c; //vector containing the exponents\n\tdelete r_c;\n\tdelete rho_c;\n\tdelete E;\n}\n\n\n\n\n//round_1 picks random elements and commits to the rows of A\nstring Prover_toom::round_1(){\n\tlong i;\n\tstring name;\n\ttime_t rawtime;\n\ttime ( &rawtime );\n\n\tname = \"round_1 \";\n\tname = name + ctime(&rawtime);\n\t//calculates commitments to rows of A\n\tFunctions::commit_op(A,r_A,c_A);\n\n\tofstream ost(name.c_str());\n\tfor (i=0; i<m; i++){\n\t\tost << c_A->at(i)<< \" \";\n\t}\n\treturn name;\n}\n\n//round_3, permuted the exponents in s,  picks random elements and commits to values\nstring Prover_toom::round_3(string in_name){\n\tlong i;\n\tZZ x2;\n\tvector<vector<ZZ>* >* chal_x2 = new vector<vector<ZZ>* >(m);\n\n\tstring name;\n\ttime_t rawtime;\n\ttime ( &rawtime );\n\n\t//reads in values of s\n\tifstream ist(in_name.c_str());\n\tif(!ist) cout<<\"Can't open \"<< in_name;\n\tist >> x2;\n\n\t//creates a matrix with entries x2,..., x2^N\n\tfunc_pro::set_x2(chal_x2,x2, m,n);\n\n\t//permutes chal_x2 according pi to create B\n\tfunc_pro::set_B_op(B, basis_B, chal_x2, pi , omega_mulex);\n\n\t//commits to the rows in B\n\tFunctions::commit_op(B,r_B,c_B);\n\n\tname = \"round_3 \";\n\tname = name + ctime(&rawtime);\n\n\t//write data in the file name\n\tofstream ost(name.c_str());\n\tfor (i=0; i<m;i++){\n\t\tost << c_B->at(i) <<\" \";\n\t}\n\n\tFunctions::delete_vector(chal_x2);\n\treturn name;\n}\n\n\n//round_5a calculates D and the commitments to the vectors chal_z, D_h\nvoid Prover_toom::round_5a(){\n\tlong i;\n\tZZ temp, t; //temporary variables\n\tvector<ZZ>* r = new vector<ZZ>(n);\n\tvector<ZZ>* v_z = new vector<ZZ>(n); //row containing the challenge alpha\n\tZZ ord = H.get_ord();\n\ttime_t rawtime;\n\ttime ( &rawtime );\n\n\t//calculate for each value in the first m rows in D: y* A_ij + A_ij -z\n\tfunc_pro::set_D(D, A,B, chal_z4, chal_y4);\n\n\t//Set the matrix D_h as the Hadamard product of the rows in D\n\tfunc_pro::set_D_h(D_h, D);\n\n\tfor( i=0; i<n;i++){\n\t\tv_z->at(i) = chal_z4; //fills the vector alpha with the challenge alpha\n\t\tNegateMod(r->at(i),to_ZZ(1),ord);\n\t}\n\n\t//Sets the additional row in D to contain -1\n\tD->at(m) = r;\n\t//random number to commit to last row in A\n\tr_A->at(m) = 0;\n\n\t//calculate commitment to alpha\n\tFunctions::commit_op(v_z, r_z, c_z);\n\t//calculate commitment to the rows in D_h\n\tFunctions::commit_op(D_h,r_D_h,c_D_h);\n\n\tdelete v_z;\n}\n\n\nvoid Prover_toom::round_5b(){\n\tfunc_pro::set_Rb(B, R, R_b);\n\tcommit_ac();\n\tcalculate_Cc(C,basis_B);\n\n}\n\nstring Prover_toom::round_5(string in_name ){\n\tlong i;\n\tstring name;\n\ttime_t rawtime;\n\ttime ( &rawtime );\n\n\t//reads the values out of the file\n\tifstream ist(in_name.c_str());\n\tif(!ist) cout<<\"Can't open \"<< in_name;\n\tist>>chal_z4;\n\tist >> chal_y4;\n\n\tround_5a();\n\tround_5b();\n\t//Set name of the output file and open stream\n\tname = \"round_5 \";\n\tname = name + ctime(&rawtime);\n\n\tofstream ost(name.c_str());\n\t//writes the commitments in the file\n\tost<<  c_z<< \"\\n\";\n\tfor (i = 0; i<m ; i++){\n\t\tost << c_D_h ->at(i)<< \" \";\n\t}\n\tost<<\"\\n\";\n\n\tfor(i=0; i<mu_h; i++){\n\t\tost<<C_c->at(i)<<\" \";\n\t}\n\tost<<\"\\n\";\n\tfor(i=0; i<mu_h; i++){\n\t\tost<<c_a_c->at(i)<<\" \";\n\t}\n\treturn name;\n}\n\nstring Prover_toom::round_5_red(string in_name){\n\tlong i;\n\tstring name;\n\ttime_t rawtime;\n\ttime ( &rawtime );\n\n\t//reads the values out of the file\n\tifstream ist(in_name.c_str());\n\tif(!ist) cout<<\"Can't open \"<< in_name;\n\tist>>chal_z4;\n\tist >> chal_y4;\n\n\tfunc_pro::set_Rb(B,R,R_b);\n\tcommit_ac();\n\n\tcalculate_Cc(C,basis_B);\n\n\tname = \"round_5_red \";\n\tname = name + ctime(&rawtime);\n\n\tofstream ost(name.c_str());\n\tfor(i=0; i<mu_h; i++){\n\t\tost<<C_c->at(i)<<\" \";\n\t}\n\tost<<\"\\n\";\n\tfor(i=0; i<mu_h; i++){\n\t\tost<<c_a_c->at(i)<<\" \";\n\t}\n\treturn name;\n\n}\n\nstring Prover_toom::round_5_red1(string in_name){\n\tlong i;\n\tdouble tstart, tstop;\n\tstring name;\n\ttime_t rawtime;\n\ttime ( &rawtime );\n\n\tx = new vector<ZZ>(mu_h);\n\n\t//reads the values out of the file\n\tifstream ist(in_name.c_str());\n\tif(!ist) cout<<\"Can't open \"<< in_name;\n\t//reads challenges x\n\tfor(i=0; i<mu_h; i++){\n\t\tist>> x->at(i);\n\t}\n\n\t//Call of round 5a\n\tround_5a();\n\n\t//calculate F_c and Z_c for the first reduction\n\tcalculate_ac_bar(x);\n\tcalculate_r_ac_bar(x);\n\n\t//reduction from m rows to m_r rows\n\ttstart= (double)clock()/CLOCKS_PER_SEC;\n\t\treduce_C(C, B, r_B, x, 4*m_r);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\ttime_di = time_di+tstop-tstart;\n\n\tset_Rb1(x);\n\tcommit_ac();\n\tcalculate_Cc(C_small, B_small);\n\n\tdelete x;\n\n\t//Set name of the output file and open stream\n\tname = \"round_5 \";\n\tname = name + ctime(&rawtime);\n\n\tofstream ost(name.c_str());\n\t//writes the commitments in the file\n\tost<<  c_z<< \"\\n\";\n\tfor (i = 0; i<m ; i++){\n\t\tost << c_D_h ->at(i)<< \" \";\n\t}\n\tost<<\"\\n\";\n\tfor(i=0; i<mu_h; i++){\n\t\tost<<C_c->at(i)<<\" \";\n\t}\n\tost<<\"\\n\";\n\tfor(i=0; i<mu_h; i++){\n\t\tost<<c_a_c->at(i)<<\" \";\n\t}\n\tost<<a_c_bar<<endl;\n\tost<<r_ac_bar<<endl;\n\treturn name;\n}\n\nvoid Prover_toom::round_7a(){\n\n\t//Set the rows in D_s as D_s(i) = chal_t_1^i+1*D_h(i) for i<m-1 and D_s(m-1) = sum(chal_x6^i+1 * D_s(i+1) and set last row of D_s to random values and also D(0)\n\tfunc_pro::set_D_s(D_s,D_h,D,chal_x6,r_Dl_bar);\n\n\t//calculate the values Dls as Dl(l) = sum(D(i)*D_s->at(i)*chal_y6) for j=n+i-l and commits to the values\n\tfunc_pro::commit_Dl_op(c_Dl,Dl, r_Dl, D, D_s, chal_y6);\n\n\n\t//commitments to D(0) and D_s(m)\n\tFunctions::commit_op(D->at(0),r_D0,c_D0);\n\tFunctions::commit_op(D_s->at(m), r_Dm, c_Dm);\n\n\t//commitments to prove that the product over the elements in D_h->at(m) is the desired product of n *y + x2n -z\n\tfunc_pro::commit_d_op(d,r_d,c_d);\n\tfunc_pro::commit_Delta_op(Delta, d, r_Delta, c_Delta);\n\tfunc_pro::commit_d_h_op(D_h,d_h,d,Delta, r_d_h, c_d_h);\n\n}\n\nvoid Prover_toom::round_7b(){\n\tcalculate_ac_bar(chal_x6);\n\tcalculate_r_ac_bar(chal_x6);\n\n}\n\nvoid  Prover_toom::round_7c(){\n\tdouble tstart, tstop;\n\tvector<Cipher_elg>* e = 0;\n\n\ttstart= (double)clock()/CLOCKS_PER_SEC;\n\treduce_C(C, B, r_B, chal_x6, m_r);\n\tset_Rb1(chal_x6);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\ttime_di = time_di+tstop-tstart;\n\n\tfunc_pro::commit_a_op(a, r_a, c_a);\n\tfunc_pro::commit_B0_op(B_0, basis_B0, r_B0, c_B0, omega_mulex);\n\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\n\te = calculate_e();\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\ttime_di = time_di+tstop-tstart;\n\t//cout<<\"To calculate the di's took \"<<time_di<<\" sec.\"<<endl;\n\n\tcalculate_E(e);\n\n\tdelete e;\n\tFunctions::delete_vector(C_small);\n}\n\nvoid  Prover_toom::round_7c_red(){\n\tvector<Cipher_elg>* e = 0;\n\tdouble tstart, tstop;\n\tvector<vector<Cipher_elg>* >* C_small_temp = 0;\n\tvector<vector<ZZ>* >* B_small_temp = 0;\n\tvector<ZZ>* r_B_small_temp = 0;\n\n\ttstart= (double)clock()/CLOCKS_PER_SEC;\n\t\tC_small_temp = copy_C();\n\t\tB_small_temp = copy_B();\n\t\tr_B_small_temp = copy_r_B();\n\n\t\tC_small = new vector<vector<Cipher_elg>* >(m_r);\n\t\tB_small = new vector<vector<ZZ>* >(m_r);\n\t\tr_B_small = new vector<ZZ>(m_r);\n\n\t\treduce_C(C_small_temp, B_small_temp, r_B_small_temp, chal_x6, m_r);\n\t\tset_Rb1(chal_x6);\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\ttime_di = time_di+tstop-tstart;\n\n\n\tfunc_pro::commit_a_op(a,r_a,c_a);\n\tfunc_pro::commit_B0_op(B_0, basis_B0, r_B0, c_B0, omega_mulex);\n\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\n\te= calculate_e();\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\ttime_di = time_di+tstop-tstart;\n\t//cout<<\"To calculate the di's took \"<<time_di<<\" sec.\"<<endl;\n\n\tcalculate_E(e);\n\n\tFunctions::delete_vector(C_small);\n\tFunctions::delete_vector(C_small_temp);\n\tFunctions::delete_vector(B_small_temp);\n\tdelete r_B_small_temp;\n\tdelete e;\n}\n\nstring Prover_toom::round_7(string in_name){\n\tlong i,l;\n\tstring name;\n\ttime_t rawtime;\n\ttime ( &rawtime );\n\t//reads the values out of the file\n\tifstream ist(in_name.c_str());\n\tif(!ist) cout<<\"Can't open \"<< in_name;\n\t//reads the vector t_1\n\tl=2*m;\n\tfor (i = 0; i<l; i++){\n\t\tist >> chal_x6->at(i);\n\t}\n\t//reads the vector t\n\tfor (i = 0; i<n; i++){\n\t\tist >> chal_y6->at(i);\n\t}\n\n\tround_7a();\n\tround_7b();\n\tround_7c();\n\n\t//Set name of the output file and open stream\n\tname = \"round_7 \";\n\tname = name + ctime(&rawtime);\n\n\tofstream ost(name.c_str());\tfor (i = 0; i<=l ; i++){\n\t\tost << c_Dl ->at(i)<< \" \";\n\t}\n\tost << \"\\n\";\n\tost<<c_D0<<\"\\n\";\n\tost <<c_Dm<<\"\\n\";\n\tost<<c_d<<\"\\n\";\n\tost<<c_Delta<<\"\\n\";\n\tost<<c_d_h<<\"\\n\";\n\tost<<a_c_bar<<\"\\n\";\n\tost<<r_ac_bar<<\"\\n\";\n\tfor(i=0; i<8; i++){\n\t\tost<<E->at(i)<<\" \";\n\t}\n\tost<<\"\\n\";\n\tost<<c_B0<<\"\\n\";\n\tfor(i=0; i<8; i++){\n\t\tost<<c_a->at(i)<<\" \";\n\t}\n\tost<<\"\\n\";\n\n\n\treturn name;\n}\n\nstring Prover_toom::round_7_red(string in_name){\n\tlong i,l;\n\tstring name;\n\ttime_t rawtime;\n\ttime ( &rawtime );\n\t//reads the values out of the file\n\tifstream ist(in_name.c_str());\n\tif(!ist) cout<<\"Can't open \"<< in_name;\n\t//reads the vector t_1\n\tl=2*m;\n\tfor (i = 0; i<l; i++){\n\t\tist >> chal_x6->at(i);\n\t}\n\t//reads the vector t\n\tfor (i = 0; i<n; i++){\n\t\tist >> chal_y6->at(i);\n\t}\n\n\tround_7a();\n\tround_7b();\n\tround_7c_red();\n\n\n\t//Set name of the output file and open stream\n\tname = \"round_7 \";\n\tname = name + ctime(&rawtime);\n\n\n\tofstream ost(name.c_str());\n\tfor (i = 0; i<=l ; i++){\n\t\tost << c_Dl ->at(i)<< \" \";\n\t}\n\tost << \"\\n\";\n\tost<<c_D0<<\"\\n\";\n\tost<<c_Dm<<\"\\n\";\n\tost<<c_d<<\"\\n\";\n\tost<<c_Delta<<\"\\n\";\n\tost<<c_d_h<<\"\\n\";\n\n\tost<<a_c_bar<<\"\\n\";\n\tost<<r_ac_bar<<\"\\n\";\n\tfor(i=0; i<8; i++){\n\t\tost<<E->at(i)<<\" \";\n\t}\n\tost<<\"\\n\";\n\tost<<c_B0<<\"\\n\";\n\tfor(i=0; i<8; i++){\n\t\tost<<c_a->at(i)<<\" \";\n\t}\n\tost<<\"\\n\";\n\treturn name;\n}\n\nvoid Prover_toom::round_9a(){\n\n\t//Calculate D_h_bar = sum(chal^i*D_h(row(i)))\n\tfunc_pro::calculate_D_h_bar(D_h_bar,D_h,chal_x8);\n\n\t//calculate r_Dh_bar = sum(chal^i*r_Dh_bar(i)), opening to prove correctness of D_h\n\tfunc_pro::calculate_r_Dh_bar(r_D_h, chal_x8, r_Dh_bar);\n\n\t//calculate d_bar, r_d_bar, Delta_bar, r_Delta_bar, openings to prove product over elements in D_h->at(m-1)\n\tfunc_pro::calculate_dbar_rdbar(D_h, chal_x8, d_bar,d,r_D_h, r_d, r_d_bar);\n\tfunc_pro::calculate_Deltabar_rDeltabar(d_h, chal_x8, Delta_bar, Delta, r_d_h, r_Delta, r_Delta_bar);\n\n\n}\n\nvoid  Prover_toom::round_9b(){\n\n\t//A_bar and r_A_bar, openings to prove permutation in D\n\tfunc_pro::calculate_A_bar(D, A_bar, chal_x8);\n\tfunc_pro::calculate_r_A_bar(r_D0, r_A, r_B, chal_x8, r_z, chal_y4, r_A_bar);\n\n\t//D_s_bar and r_Ds_bar, openings to prove correctness of D_s\n\tfunc_pro::calculate_D_s_bar(D_s, D_s_bar, chal_x8);\n\tfunc_pro::calculate_r_Ds_bar(r_D_h, chal_x6, chal_x8, r_Ds_bar, r_Dm);\n\n\t//sum of the random values used to commit to the Dl's, to prover correctness of them\n\tfunc_pro::calculate_r_Dl_bar(r_Dl, chal_x8, r_Dl_bar);\n\n}\n\nvoid  Prover_toom::round_9c(){\n\t//calculate B_bar\n\tfunc_pro::calculate_B_bar(B_0, B_small,chal_x8, B_bar );\n\tFunctions::delete_vector(B_small);\n\n\t//calculate r_B_bar\n\tfunc_pro::calculate_r_B_bar(r_B_small, chal_x8,r_B0, r_B_bar );\n\n\t//calculate a_bar\n\tfunc_pro::calculate_a_bar(a, chal_x8, a_bar);\n\n\t//calculate r_a_bar\n\tfunc_pro::calculate_r_a_bar(r_a, chal_x8, r_a_bar);\n\n\t//calculate rho_a_bar\n\tfunc_pro::calculate_rho_a_bar(rho_a, chal_x8, rho_bar);\n}\n\nstring Prover_toom::round_9(string in_name){\n\tlong i;\n\tlong l = chal_x8->size();\n\tZZ tem;\n\tstring name;\n\ttime_t rawtime;\n\ttime ( &rawtime );\n\n\t//reads the values out of the file\n\tifstream ist(in_name.c_str());\n\tif(!ist) cout<<\"Can't open \"<< in_name;\n\t//reads the vector e\n\tfor (i = 0; i<l ; i++){\n\t\tist >> chal_x8->at(i);\n\t}\n\n\tround_9a();\n\tround_9b();\n\tround_9c();\n\n\t//Set name of the output file and open stream\n\tname = \"round_9 \";\n\tname = name + ctime(&rawtime);\n\n\tofstream ost(name.c_str());\n\n\tfor (i = 0; i<n; i++){\n\t\tost << D_h_bar->at(i)<<\" \";\n\t}\n\tost <<\"\\n\";\n\n\tost<< r_Dh_bar;\n\tost <<\"\\n\";\n\n\tfor(i=0; i<n;i++){\n\t\tost<<d_bar->at(i)<<\" \";\n\t}\n\tost<<\"\\n\";\n\tost<< r_d_bar <<\"\\n\";\n\tfor(i=0; i<n; i++){\n\t\tost<<Delta_bar->at(i)<<\" \";\n\t}\n\tost<<\"\\n\";\n\tost<<r_Delta_bar <<\"\\n\";\n\n\tfor (i = 0; i<n; i++){\n\t\tost << A_bar->at(i)<<\" \";\n\t}\n\tost<<\"\\n\";\n\tost<<r_A_bar<<\"\\n\";\n\tfor(i=0; i<n; i++){\n\t\tost<<D_s_bar->at(i)<<\" \";\n\t}\n\tost<<\"\\n\";\n\tost<<r_Ds_bar<<\"\\n\";\n\tost<<r_Dl_bar<<\"\\n\";\n\tfor (i = 0; i<n; i++){\n\t\tost << B_bar->at(i)<<\" \";\n\t}\n\tost <<\"\\n\";\n\n\tost<< r_B_bar;\n\tost <<\"\\n\";\n\n\tost<< a_bar;\n\tost <<\"\\n\";\n\n\tost<< r_a_bar;\n\tost <<\"\\n\";\n\n\tost<< rho_bar;\n\tost <<\"\\n\";\n\n\treturn name;\n}\n\n\n\n\n\nvoid Prover_toom::commit_ac(){\n\tlong i;\n\tZZ ord = H.get_ord();\n\n\tfor(i= 0; i<mu_h; i++){\n\t\ta_c->at(i) = RandomBnd(ord);\n\t\tr_c->at(i) = RandomBnd(ord);\n\t\trho_c->at(i) = RandomBnd(ord);\n\t}\n\ta_c->at(mu-1) = to_ZZ(0);\n\tr_c->at(mu-1) = to_ZZ(0);\n\tNegateMod(rho_c->at(mu-1),R_b, ord);\n\tfor(i= 0; i<mu_h; i++){\n\t\tc_a_c->at(i) = Ped.commit_sw(a_c->at(i),r_c->at(i));\n\t}\n\n}\n\nvoid Prover_toom::calculate_Cc(vector<vector<Cipher_elg>* >* C, vector<vector<vector<long>* >* >* B){\n\tlong i, j, l,k;\n\tZZ mod = H.get_mod();\n\tZZ gen = H.get_gen().get_val();\n\tCipher_elg temp, temp_1;\n\tZZ t_1;\n\tdouble tstart, tstop;\n\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\n\tfor(k=0; k<mu_h; k++){\n\t\ttemp = Cipher_elg(1,1,mod);\n\t\tfor(i=0; i<mu; i++){\n\t\t\tj=k+1-mu+i;\n\t\t\tif(j>=0 & j<mu){\n\t\t\t\tfor(l=0; l<m_r; l++){\n\t\t\t\t\tmulti_expo::expo_mult(temp_1, C->at(4*l+i), B->at(4*l+j), omega_mulex);\n\t\t\t\t\tCipher_elg::mult(temp, temp, temp_1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tPowerMod(t_1, gen, a_c->at(k), mod);\n\t\ttemp_1 = El.encrypt(t_1, rho_c->at(k));\n\t\tCipher_elg::mult(C_c->at(k),temp, temp_1);\n\t}\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\ttime_di=0;\n\ttime_di = time_di + (tstop-tstart);\n}\n\nvoid Prover_toom::calculate_Cc(vector<vector<Cipher_elg>* >* C, vector<vector<ZZ>* >* B){\n\tlong i, j, l,k;\n\tZZ mod = H.get_mod();\n\tZZ gen = H.get_gen().get_val();\n\tCipher_elg temp, temp_1;\n\tZZ t_1;\n\tdouble tstart, tstop;\n\n\ttstart = (double)clock()/CLOCKS_PER_SEC;\n\tfor(k=0; k<mu_h; k++){\n\t\ttemp = Cipher_elg(1,1,mod);\n\t\tfor(i=0; i<mu; i++){\n\t\t\tj=k+1-mu+i;\n\t\t\tif(j>=0 & j<mu){\n\t\t\t\tfor(l=0; l<m_r; l++){\n\t\t\t\t\tmulti_expo::expo_mult(temp_1, C->at(4*l+i), B->at(4*l+j), omega_mulex);\n\t\t\t\t\tCipher_elg::mult(temp, temp, temp_1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tPowerMod(t_1, gen, a_c->at(k), mod);\n\t\ttemp_1 = El.encrypt(t_1, rho_c->at(k));\n\t\tCipher_elg::mult(C_c->at(k),temp, temp_1);\n\t}\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\ttime_di=0;\n\ttime_di = time_di + (tstop-tstart);\n}\n\n\nvoid Prover_toom::calculate_ac_bar(vector<ZZ>* x){\n\tlong i;\n\tZZ temp;\n\tZZ ord = H.get_ord();\n\n\ta_c_bar = a_c->at(0);\n\tfor(i=1; i<mu_h; i++){\n\t\tMulMod(temp, a_c->at(i), x->at(i-1), ord);\n\t\tAddMod(a_c_bar, a_c_bar, temp, ord);\n\t}\n}\n\nvoid Prover_toom::calculate_r_ac_bar(vector<ZZ>* x){\n\tlong i;\n\tZZ temp;\n\tZZ ord = H.get_ord();\n\n\tr_ac_bar = r_c->at(0);\n\tfor(i=1; i<mu_h; i++){\n\t\tMulMod(temp, r_c->at(i), x->at(i-1), ord);\n\t\tAddMod(r_ac_bar, r_ac_bar, temp, ord);\n\t}\n}\n\nvoid Prover_toom::reduce_C(vector<vector<Cipher_elg>*>* C, vector<vector<ZZ>* >* B, vector<ZZ>* r_B, vector<ZZ>* x, long length){\n\tlong i, j;\n\tZZ temp, temp_1;\n\tZZ ord  = H.get_ord();\n\tdouble tstart, tstop;\n\tvector<Cipher_elg>* row_C=0;\n\tvector<ZZ>* row_B=0;\n\tvector<ZZ>* x_temp = new vector<ZZ>(4);\n\n\ttstart= (double)clock()/CLOCKS_PER_SEC;\n\tx_temp->at(3)=1;\n\tx_temp->at(2)= x->at(0);\n\tx_temp->at(1) = x->at(1);\n\tx_temp->at(0)= x->at(2);\n\n\tfor(i=0; i<length;i++){\n\t\trow_C = new vector<Cipher_elg>(n);\n\t\trow_B = new vector<ZZ>(n);\n\t\tfor(j=0; j<n; j++){\n\t\t\tmulti_expo::multi_expo_LL(row_C->at(j), C->at(4*i)->at(j), C->at(4*i+1)->at(j),C->at(4*i+2)->at(j),C->at(4*i+3)->at(j), x_temp, omega_LL);\n\t\t\ttemp = B->at(4*i)->at(j);\n\t\t\tMulMod(temp_1, B->at(4*i+1)->at(j), x_temp->at(2), ord);\n\t\t\tAddMod(temp, temp, temp_1, ord);\n\t\t\tMulMod(temp_1, B->at(4*i+2)->at(j), x_temp->at(1), ord);\n\t\t\tAddMod(temp, temp, temp_1, ord);\n\t\t\tMulMod(temp_1, B->at(4*i+3)->at(j), x_temp->at(0), ord);\n\t\t\tAddMod(temp, temp, temp_1, ord);\n\t\t\trow_B->at(j) = temp;\n\t\t}\n\t\tC_small->at(i)=row_C;\n\t\tB_small->at(i)=row_B;\n\t\ttemp = r_B->at(4*i);\n\t\tMulMod(temp_1, r_B->at(4*i+1), x_temp->at(2), ord);\n\t\tAddMod(temp, temp, temp_1, ord);\n\t\tMulMod(temp_1, r_B->at(4*i+2), x_temp->at(1), ord);\n\t\tAddMod(temp, temp, temp_1, ord);\n\t\tMulMod(temp_1, r_B->at(4*i+3), x_temp->at(0), ord);\n\t\tAddMod(temp, temp, temp_1, ord);\n\t\tr_B_small->at(i) = temp;\n\t}\n\ttstop = (double)clock()/CLOCKS_PER_SEC;\n\ttime_di = time_di + (tstop-tstart);\n\tdelete x_temp;\n}\n\nvoid Prover_toom::set_Rb1(vector<ZZ>* x){\n\tlong i;\n\tZZ temp;\n\tZZ ord = H.get_ord();\n\n\tR_b = rho_c->at(0);\n\tfor(i=1; i<mu_h; i++){\n\t\tMulMod(temp, rho_c->at(i), x->at(i-1), ord);\n\t\tAddMod(R_b, R_b, temp, ord);\n\t}\n}\n\n\nvector<Cipher_elg>* Prover_toom::calculate_e(){\n\tlong k,l;\n\tCipher_elg temp;\n\tZZ ord = H.get_ord();\n\tZZ mod = H.get_mod();\n\tvector<Cipher_elg>* dt = 0;\n\tvector<Cipher_elg>* e = new vector<Cipher_elg>(2*m);\n\n\tdt = toom4_pow(C_small, B_small);\n\n\tmulti_expo::expo_mult(e->at(0),C_small->at(mu-1), basis_B0, omega_mulex);\n\tfor (k =1; k<mu; k++){\n\t\tmulti_expo::expo_mult(temp , C_small->at(mu-k-1), basis_B0, omega_mulex);\n\t\tCipher_elg::mult(e->at(k) ,temp,dt->at(2*mu-k-1));\n\t}\n\tl=2*mu;\n\tfor (k = mu; k<l; k++){\n\t\te->at(k) = dt->at(2*mu-k-1);\n\t}\n\n\tdelete dt;\n\treturn e;\n}\n\nvoid Prover_toom::calculate_E(vector<Cipher_elg>* e){\n\tlong i,l;\n\tMod_p t;\n\tMod_p gen = H.get_gen();\n\tZZ ord = H.get_ord();\n\n\tl=2*mu;\n\tfor (i = 0; i<l; i++){\n\t\trho_a->at(i)= RandomBnd(ord);\n\t}\n\trho_a->at(mu)=R_b ;\n\tfor (i = 0; i<l; i++){\n\t\t t = gen.expo(a->at(i));\n\t\t E->at(i) = El.encrypt(t,rho_a->at(i))*e->at(i);\n\t}\n}\n\n\nvector<vector<Cipher_elg>* >* Prover_toom::copy_C(){\n\tlong i,j,l;\n\tvector<Cipher_elg>* row_C;\n\tl=mu*m_r;\n\tvector<vector<Cipher_elg>* >* C_small_temp = new vector<vector<Cipher_elg>* >(l);\n\n\tfor(i=0; i<l; i++){\n\t\trow_C = new vector<Cipher_elg>(n);\n\t\tfor(j=0; j<n; j++){\n\t\t\trow_C->at(j)= C_small->at(i)->at(j);\n\t\t}\n\t\tC_small_temp ->at(i)= row_C;\n\t\tdelete C_small->at(i);\n\t\tC_small->at(i)=0;\n\t}\n\tdelete C_small;\n\tC_small=0;\n\n\treturn C_small_temp;\n}\n\nvector<vector<ZZ>* >* Prover_toom::copy_B(){\n\tlong i, j;\n\tlong l = mu*m_r;\n\tvector<vector<ZZ>* >* B_small_temp =new vector<vector<ZZ>* >(l);\n\tvector<ZZ>* row_B;\n\n\tfor(i=0; i<l; i++){\n\t\trow_B = new vector<ZZ>(n);\n\t\tfor(j=0; j<n; j++){\n\t\t\trow_B->at(j)=B_small->at(i)->at(j);\n\t\t}\n\t\tB_small_temp->at(i)=row_B;\n\t\tdelete B_small->at(i);\n\t\tB_small->at(i)=0;\n\t}\n\tdelete B_small;\n\n\treturn B_small_temp;\n}\n\nvector<ZZ>* Prover_toom::copy_r_B(){\n\tlong i;\n\tlong l=mu*m_r;\n\tvector<ZZ>* r_B_small_temp = new vector<ZZ>(l);\n\tfor(i=0; i<l; i++){\n\t\tr_B_small_temp->at(i)=r_B_small->at(i);\n\t}\n\tdelete r_B_small;\n\tr_B_small=0;\n\n\treturn r_B_small_temp;\n}\n\n\n\n\nvector<vector<ZZ>*>* Prover_toom::evulation(vector<vector<ZZ>*>* p){\n\tvector<vector<ZZ>*>* ret;\n\tvector<ZZ>* row;\n\tZZ p0,p1,p2,p3,ord,temp,temp_1;\n\tlong l,i;\n\tl= p->at(0)->size();\n\tord = H.get_ord();\n\tret = new vector<vector<ZZ>*>(l);\n\n\tfor(i = 0; i<l; i++){\n\t\trow = new vector<ZZ>(7);\n\t\t\tAddMod(p0,p->at(2)->at(i), p->at(0)->at(i),ord);\n\t\t\tAddMod(p1 ,p->at(3)->at(i) , p->at(1)->at(i), ord);\n\t\t\tMulMod(temp, p->at(2)->at(i),2,ord);\n\t\t\tMulMod(temp_1, p->at(0)->at(i), 8, ord);\n\t\t\tAddMod(p2 , temp , temp_1,ord);\n\t\t\tMulMod(temp, p->at(1)->at(i), 4, ord);\n\t\t\tAddMod(p3 ,p->at(3)->at(i) , temp,ord);\n\n\t\t\trow->at(0) = p->at(3)->at(i);\n\t\t\tMulMod(temp_1, p->at(1)->at(i), 2,ord);\n\t\t\tAddMod(temp,temp_1 , p->at(0)->at(i), ord);\n\t\t\tMulMod(temp_1, p->at(2)->at(i),4, ord);\n\t\t\tAddMod(temp,temp,temp_1,ord);\n\t\t\tMulMod(temp_1, p->at(3)->at(i), 8, ord);\n\t\t\tAddMod(row->at(1), temp,temp_1, ord);\n\t\t\tAddMod(row->at(2) , p0,p1,ord);\n\t\t\tSubMod(row->at(3) , p0,p1,ord);\n\t\t\tAddMod(row ->at(4) , p2,p3,ord);\n\t\t\tSubMod(row ->at(5),p2,p3,ord);\n\t\t\trow->at(6) = p->at(0)->at(i);\n\t\t\tret->at(i) = row;\n\t}\n\treturn ret;\n}\n\n\nvector<vector<vector<ZZ>*>*>* Prover_toom::evulation_pow(vector<vector<Cipher_elg>*>* p){\n\tvector<vector<vector<ZZ>*>*>* ret;\n\tvector<vector<ZZ>* >* ret_u;\n\tvector<vector<ZZ>* >* ret_v;\n\tvector<ZZ>* row_u;\n\tvector<ZZ>* row_v;\n\tZZ p0_u,p1_u,p2_u,p3_u,temp_u, temp_1_u;\n\tZZ p0_v,p1_v,p2_v,p3_v,temp_v, temp_1_v;\n\tZZ mod = H.get_mod();\n\tlong l, i;\n\tl = p->at(0)->size();\n\n\tret = new vector<vector<vector<ZZ>*>*>(2);\n\tret_u = new vector<vector<ZZ>*>(l);\n\tret_v = new vector<vector<ZZ>*>(l);\n\n\tfor(i = 0; i<l; i++){\n\t\trow_u = new vector<ZZ>(7);\n\t\trow_v = new vector<ZZ>(7);\n\t\tMulMod(p0_u,p->at(1)->at(i).get_u(), p->at(3)->at(i).get_u(),mod);\n\t\tMulMod(p0_v,p->at(1)->at(i).get_v(), p->at(3)->at(i).get_v(),mod);\n\t\tMulMod(p1_u ,p->at(0) ->at(i).get_u(), p->at(2)->at(i).get_u(), mod);\n\t\tMulMod(p1_v ,p->at(0) ->at(i).get_v(), p->at(2)->at(i).get_v(), mod);\n\t\tPowerMod(temp_u, p->at(1)->at(i).get_u(), 2,mod);\n\t\tPowerMod(temp_v, p->at(1)->at(i).get_v(), 2,mod);\n\t\tPowerMod(temp_1_u, p->at(3)->at(i).get_u(), 8,mod);\n\t\tPowerMod(temp_1_v, p->at(3)->at(i).get_v(), 8,mod);\n\t\tMulMod(p2_u ,temp_u , temp_1_u,mod);\n\t\tMulMod(p2_v ,temp_v , temp_1_v,mod);\n\t\tPowerMod(temp_u, p->at(2)->at(i).get_u(), 4, mod);\n\t\tPowerMod(temp_v, p->at(2)->at(i).get_v(), 4, mod);\n\t\tMulMod(p3_u ,p->at(0)->at(i).get_u() , temp_u,mod);\n\t\tMulMod(p3_v ,p->at(0)->at(i).get_v() , temp_v,mod);\n\n\t\trow_u->at(0) = p->at(0)->at(i).get_u();\n\t\tPowerMod(temp_u, p->at(2)->at(i).get_u(), 2,mod);\n\t\tMulMod(temp_u,temp_u , p->at(3)->at(i).get_u(), mod);\n\t\tPowerMod(temp_1_u, p->at(1)->at(i).get_u(), 4,mod);\n\t\tMulMod(temp_u,temp_u,temp_1_u,mod);\n\t\tPowerMod(temp_1_u, p->at(0)->at(i).get_u(), 8, mod);\n\t\tMulMod(row_u->at(1), temp_u,temp_1_u,mod);\n\t\tMulMod(row_u->at(2) , p0_u,p1_u,mod);\n\t\tInvMod(temp_u, p1_u, mod);\n\t\tMulMod(row_u->at(3) , p0_u,temp_u,mod);\n\t\tMulMod(row_u ->at(4) , p2_u,p3_u,mod);\n\t\tInvMod(temp_u, p3_u, mod);\n\t\tMulMod(row_u ->at(5),p2_u,temp_u,mod);\n\t\trow_u->at(6) = p->at(3)->at(i).get_u();\n\n\t\trow_v->at(0) = p->at(0)->at(i).get_v();\n\t\tPowerMod(temp_v, p->at(2)->at(i).get_v(), 2,mod);\n\t\tMulMod(temp_v,temp_v , p->at(3)->at(i).get_v(), mod);\n\t\tPowerMod(temp_1_v, p->at(1)->at(i).get_v(), 4,mod);\n\t\tMulMod(temp_v,temp_v,temp_1_v,mod);\n\t\tPowerMod(temp_1_v, p->at(0)->at(i).get_v(), 8, mod);\n\t\tMulMod(row_v->at(1), temp_v,temp_1_v,mod);\n\t\tMulMod(row_v->at(2) , p0_v,p1_v,mod);\n\t\tInvMod(temp_v, p1_v, mod);\n\t\tMulMod(row_v->at(3) , p0_v,temp_v,mod);\n\t\tMulMod(row_v ->at(4) , p2_v,p3_v,mod);\n\t\tInvMod(temp_v, p3_v, mod);\n\t\tMulMod(row_v ->at(5),p2_v,temp_v,mod);\n\t\trow_v->at(6) = p->at(3)->at(i).get_v();\n\n\t\tret_u->at(i) = row_u;\n\t\tret_v->at(i) = row_v;\n\t}\n\tret->at(0) = ret_u;\n\tret->at(1) = ret_v;\n\treturn ret;\n}\n\nvector<vector<vector<ZZ>*>*>* Prover_toom::point_pow(vector<vector<vector<ZZ>*>*>* points_p, vector<vector<ZZ>*>* points_q){\n\tlong i,j,l;\n\tvector<vector<vector<ZZ>*>*>* ret;\n\tvector<vector<ZZ>*>* ret_u;\n\tvector<vector<ZZ>*>* ret_v;\n\tvector<ZZ>* row_u;\n\tvector<ZZ>* row_v;\n\tZZ mod = H.get_mod();\n\tl = points_p->at(0)->size();\n\n\tret = new vector<vector<vector<ZZ>*>*>(2);\n\tret_u = new vector<vector<ZZ>*>(l);\n\tret_v = new vector<vector<ZZ>*>(l);\n\tfor(j = 0; j<l; j++){\n\t\trow_u = new vector<ZZ>(7);\n\t\trow_v = new vector<ZZ>(7);\n\t\tfor(i=0; i<7; i++){\n\t\t\tPowerMod(row_u->at(i) , points_p->at(0)->at(j)->at(i), points_q->at(j)->at(i),mod);\n\t\t\tPowerMod(row_v->at(i) , points_p->at(1)->at(j)->at(i), points_q->at(j)->at(i),mod);\n\n\t\t}\n\t\tret_u->at(j) = row_u;\n\t\tret_v->at(j) = row_v;\n\t}\n\tret->at(0)= ret_u;\n\tret->at(1) = ret_v;\n\tfor(i = 0; i< l ; i++){\n\t\tdelete points_p->at(0)->at(i);\n\t\tpoints_p->at(0)->at(i)=0;\n\t\tdelete points_p->at(1)->at(i);\n\t\tpoints_p->at(1)->at(i)=0;\n\t}\n\tdelete points_p->at(0);\n\tdelete points_p->at(1);\n\tdelete points_p;\n\tfor(i = 0; i< l ; i++){\n\t\tdelete points_q->at(i);\n\t\tpoints_q->at(i)=0;\n\t}\n\tdelete points_q;\n\treturn ret;\n}\n\n\nvector<vector<ZZ>*>* Prover_toom::mult_points(vector<vector<vector<ZZ>* >*>* points){\n\tlong i,l,j;\n\tvector<vector<ZZ>*>* ret = new vector<vector<ZZ>*>(2);\n\tvector<ZZ>* ret_u = new vector<ZZ>(7);\n\tvector<ZZ>* ret_v = new vector<ZZ>(7);\n\tl = points->at(0)->size();\n\tZZ temp_u, temp_v;\n\tZZ mod = H.get_mod();\n\n\tfor(i = 0; i<7; i++){\n\t\ttemp_u = 1;\n\t\ttemp_v = 1;\n\t\tfor(j = 0; j<l; j++){\n\t\t\tMulMod(temp_u, temp_u, points->at(0)->at(j)->at(i),mod);\n\t\t\tMulMod(temp_v, temp_v, points->at(1)->at(j)->at(i),mod);\n\t\t}\n\t\tret_u->at(i) = temp_u;\n\t\tret_v->at(i) = temp_v;\n\t}\n\tfor(i = 0; i<l;i++){\n\t\tdelete points->at(0)->at(i);\n\t\tpoints->at(0)->at(i) = 0;\n\t\tdelete points->at(1)->at(i);\n\t\tpoints->at(1)->at(i) = 0;\n\t}\n\tdelete points->at(0);\n\tpoints->at(0) =0;\n\tdelete points->at(1);\n\tpoints->at(1) =0;\n\tdelete points;\n\tret->at(0) = ret_u;\n\tret->at(1) = ret_v;\n\treturn ret;\n}\n\nvector<ZZ>* Prover_toom::interpolation_pow(vector<ZZ>* points){\n\tvector<ZZ>* ret = new vector<ZZ>(7);\n\tZZ r1,r2,r3,r4,r5,r6,r7,temp;\n\tZZ ord = H.get_ord();\n\tZZ mod = H.get_mod();\n\n\tr1 = points->at(0);\n\tr2 = points->at(1);\n\tr3 = points->at(2);\n\tr4 = points->at(3);\n\tr5 = points->at(4);\n\tr6 = points->at(5);\n\tr7 = points->at(6);\n\n\tMulMod(r2 ,r2, r5, mod);\n\tInvMod(temp,r5,mod);\n\tMulMod(r6 , r6,temp, mod);\n\tInvMod(temp, r3, mod);\n\tMulMod(r4 , r4,temp,mod);\n\tInvMod(temp, r1, mod);\n\tMulMod(r5,r5,temp,mod);\n\tPowerMod(temp, r7, 64,mod);\n\tInvMod(temp, temp, mod);\n\tMulMod(r5, r5,temp,mod);\n\tInvMod(temp,to_ZZ(2),ord);\n\tPowerMod(r4,r4,temp,mod);\n\tMulMod(r3, r3,r4,mod);\n\tPowerMod(temp, r5,2, mod);\n\tMulMod(r5 , temp , r6,mod);\n\n\tPowerMod(temp, r3, 65,mod);\n\tInvMod(temp, temp, mod);\n\tMulMod(r2 , r2,temp,mod);\n\tPowerMod(r4 ,r4,-1,mod);\n\tPowerMod(r6 , r6,-1,mod);\n\tInvMod(temp, r7, mod);\n\tMulMod(r3, r3, temp,mod);\n\tInvMod(temp, r1, mod);\n\tMulMod(r3 , r3,temp,mod);\n\tPowerMod(temp, r3, 45, mod);\n\tMulMod(r2 , r2,temp,mod);\n\tPowerMod(temp, r3, 8, mod);\n\tInvMod(temp, temp, mod);\n\tMulMod(r5 , r5,temp,mod);\n\n\tInvMod(temp,to_ZZ(24),ord);\n\tPowerMod(r5 , r5,temp, mod);\n\tInvMod(temp, r2, mod);\n\tMulMod(r6 , r6,temp,mod);\n\tPowerMod(temp, r4, 16, mod);\n\tInvMod(temp, temp, mod);\n\tMulMod(r2 , r2,temp,mod);\n\tInvMod(temp,to_ZZ(18), ord);\n\tPowerMod(r2 ,r2, temp, mod);\n\tInvMod(temp, r5, mod);\n\tMulMod(r3 , r3,temp,mod);\n\tInvMod(temp, r2, mod);\n\tMulMod(r4, r4,temp,mod);\n\tPowerMod(temp, r2, 30, mod);\n\tMulMod(r6 , r6,temp,mod);\n\tInvMod(temp, to_ZZ(60), ord);\n\tPowerMod(r6,  r6, temp, mod);\n\tInvMod(temp, r6, mod);\n\tMulMod(r2 , r2 ,temp,mod);\n\n\tret->at(0)= r1;\n\tret->at(1) = r2;\n\tret->at(2) = r3;\n\tret ->at(3) = r4;\n\tret->at(4) = r5;\n\tret->at(5) = r6;\n\tret->at(6) = r7;\n\n\treturn ret;\n}\n\n\nvector<Cipher_elg>* Prover_toom::toom4_pow(vector<vector<Cipher_elg>*>* p, vector<vector<ZZ>*>* q){\n\tvector<vector<vector<ZZ>*>*>* points_p;\n\tvector<vector<ZZ>*>* points_q;\n\tvector<vector<vector<ZZ>*>*>* points_temp;\n\tvector<vector<ZZ>*>* points;\n\tvector<ZZ>* ret_u;\n\tvector<ZZ>* ret_v;\n\tvector<Cipher_elg>* ret = new vector<Cipher_elg>(7);\n\tlong i,l;\n\tZZ mod = H.get_mod();\n\tpoints_p = evulation_pow(p);\n\tpoints_q = evulation(q);\n\tpoints_temp = point_pow(points_p, points_q);\n\tpoints = mult_points(points_temp);\n\tret_u = interpolation_pow(points->at(0));\n\tret_v = interpolation_pow(points->at(1));\n\tl = points->size();\n\tfor(i = 0; i<l; i++){\n\t\tdelete points->at(i);\n\t\tpoints->at(i)=0;\n\t}\n\tdelete points;\n\n\tfor(i = 0; i<7; i++){\n\t\tret->at(i)= Cipher_elg(ret_u->at(i), ret_v->at(i), mod);\n\t}\n\tdelete ret_u;\n\tdelete ret_v;\n\treturn ret;\n}\n\n\n\n", "meta": {"hexsha": "5fbd1c1ffa94754e9e1dbf73925b4b3de3046e41", "size": 32039, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Prover_toom.cpp", "max_stars_repo_name": "3for/verifiable-shuffle", "max_stars_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-01-11T14:06:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T08:28:26.000Z", "max_issues_repo_path": "src/Prover_toom.cpp", "max_issues_repo_name": "3for/verifiable-shuffle", "max_issues_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "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/Prover_toom.cpp", "max_forks_repo_name": "3for/verifiable-shuffle", "max_forks_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-13T06:11:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-03T15:21:49.000Z", "avg_line_length": 25.1878930818, "max_line_length": 161, "alphanum_fraction": 0.6346640032, "num_tokens": 11785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.29228572979896467}}
{"text": "/*!\n@file\nInternal header to break cyclic dependencies.\n\n@copyright Louis Dionne 2014\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_HANA_MONOID_DETAIL_MONOID_FWD_HPP\n#define BOOST_HANA_MONOID_DETAIL_MONOID_FWD_HPP\n\n#include <boost/hana/core/typeclass.hpp>\n#include <boost/hana/detail/constexpr.hpp>\n\n\nnamespace boost { namespace hana {\n    namespace monoid_detail { namespace operators { struct enable { }; }}\n\n    //! @ingroup group-typeclasses\n    //! The `Monoid` type class is used for data types with an associative\n    //! binary operation that has an identity.\n    //!\n    //! The method names refer to the monoid of numbers under addition, but\n    //! there are many other instances such as sequences under concatenation.\n    //! Some datatypes can be viewed as a monoid in more than one way, e.g.\n    //! both addition and multiplication on numbers.\n    //!\n    //! ### Laws\n    //! For all objects `x`, `y` and `z` whose data type `M` is a `Monoid`,\n    //! the following laws must be satisfied:\n    //! @code\n    //!     plus(zero<M>, x) == x                      // left zero\n    //!     plus(x, zero<M>) == x                      // right zero\n    //!     plus(x, plus(y, z)) == plus(plus(x, y), z) // associativity\n    //! @endcode\n    struct Monoid {\n        BOOST_HANA_BINARY_TYPECLASS(Monoid);\n\n        //! Minimal complete definition : `zero` and `plus`\n        struct mcd { };\n\n        struct laws;\n\n        using operators = monoid_detail::operators::enable;\n    };\n\n    //! Associative operation on a `Monoid`.\n    //! @relates Monoid\n    //!\n    //! ### Example\n    //! @snippet example/monoid/plus.cpp main\n    BOOST_HANA_CONSTEXPR_LAMBDA auto plus = [](auto x, auto y) {\n        return Monoid::instance<\n            datatype_t<decltype(x)>, datatype_t<decltype(y)>\n        >::plus_impl(x, y);\n    };\n\n    //! Identity of `plus`.\n    //! @relates Monoid\n    //!\n    //! Since `Monoid` is a binary type class and `zero` is a nullary method,\n    //! `zero<M>` is dispatched to the type class instance for `M` and `M`,\n    //! i.e. `Monoid::instance<M, M>`.\n    //!\n    //! @tparam M\n    //! The data type (a `Monoid`) of the returned identity.\n    //!\n    //! ### Example\n    //! @snippet example/monoid/zero.cpp main\n    template <typename M>\n    constexpr auto zero = Monoid::instance<M, M>::zero_impl();\n\n    namespace monoid_detail { namespace operators {\n        //! Equivalent to `plus`.\n        //! @relates boost::hana::Monoid\n        template <typename C1, typename C2>\n        constexpr auto operator+(C1 c1, C2 c2)\n        { return plus(c1, c2); }\n    }}\n}} // end namespace boost::hana\n\n#endif // !BOOST_HANA_MONOID_DETAIL_MONOID_FWD_HPP\n", "meta": {"hexsha": "e1f415e4cd6e398bc07282658ca645c7962a6220", "size": 2782, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/hana/monoid/detail/monoid_fwd.hpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "include/boost/hana/monoid/detail/monoid_fwd.hpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "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/hana/monoid/detail/monoid_fwd.hpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "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.119047619, "max_line_length": 78, "alphanum_fraction": 0.6189791517, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.29223971019559075}}
{"text": "/*    Copyright (c) 2010-2015, Delft University of Technology\n *    All rights reserved.\n *\n *    Redistribution and use in source and binary forms, with or without modification, are\n *    permitted provided that the following conditions are met:\n *      - Redistributions of source code must retain the above copyright notice, this list of\n *        conditions and the following disclaimer.\n *      - Redistributions in binary form must reproduce the above copyright notice, this list of\n *        conditions and the following disclaimer in the documentation and/or other materials\n *        provided with the distribution.\n *      - Neither the name of the Delft University of Technology nor the names of its contributors\n *        may be used to endorse or promote products derived from this software without specific\n *        prior written permission.\n *\n *    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS\n *    OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n *    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *    COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n *    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n *    GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n *    AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n *    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n *    OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *    Changelog\n *      YYMMDD    Author            Comment\n *      110620    F.M. Engelen      File created.\n *      110721    J. Melman         Comments, variable names, and consistency modified.\n *      110722    F.M. Engelen      Removed setRelativePath function.\n *\n *    References\n *\n *    Notes\n *\n */\n\n#include <iostream>\n\n#include <boost/make_shared.hpp>\n\n#include \"Tudat/InputOutput/matrixTextFileReader.h\"\n\n#include \"Tudat/Astrodynamics/Aerodynamics/tabulatedAtmosphere.h\"\n\nnamespace tudat\n{\nnamespace aerodynamics\n{\n\n//! Initialize atmosphere table reader.\nvoid TabulatedAtmosphere::initialize( const std::string& atmosphereTableFile )\n{\n    // Locally store the atmosphere table file name.\n    atmosphereTableFile_ = atmosphereTableFile;\n\n    Eigen::MatrixXd containerOfAtmosphereTableFileData\n            = input_output::readMatrixFromFile( atmosphereTableFile_, \" \\t\", \"%\" );\n\n    // Check whether data is present in the file.\n    if ( containerOfAtmosphereTableFileData.rows( ) < 1\n         || containerOfAtmosphereTableFileData.cols( ) < 1 )\n    {\n        std::cerr << \"The atmosphere table file is empty.\" << std::endl;\n        std::cerr << atmosphereTableFile_ << std::endl;\n    }\n\n    // Initialize vectors.\n    altitudeData_.resize( containerOfAtmosphereTableFileData.rows( ) );\n    densityData_.resize( containerOfAtmosphereTableFileData.rows( ) );\n    pressureData_.resize( containerOfAtmosphereTableFileData.rows( ) );\n    temperatureData_.resize( containerOfAtmosphereTableFileData.rows( ) );\n\n    // Loop through all the strings stored in the container and store the data\n    // in the right Eigen::VectorXd.\n    for ( int i = 0; i < containerOfAtmosphereTableFileData.rows( ); i++  )\n    {\n        altitudeData_[ i ] = containerOfAtmosphereTableFileData( i, 0 );\n        densityData_[ i ] = containerOfAtmosphereTableFileData( i, 1 );\n        pressureData_[ i ] = containerOfAtmosphereTableFileData( i, 2 );\n        temperatureData_[ i ] = containerOfAtmosphereTableFileData( i, 3 );\n    }\n\n    using namespace interpolators;\n\n    cubicSplineInterpolationForDensity_\n            = boost::make_shared< CubicSplineInterpolatorDouble >( altitudeData_, densityData_ );\n    cubicSplineInterpolationForPressure_\n            = boost::make_shared< CubicSplineInterpolatorDouble >( altitudeData_, pressureData_ );\n    cubicSplineInterpolationForTemperature_\n            = boost::make_shared< CubicSplineInterpolatorDouble >(\n                altitudeData_, temperatureData_ );\n}\n\n} // namespace aerodynamics\n} // namespace tudat\n", "meta": {"hexsha": "d5dbd4803d32b81e25299fa36115f65129c2ba98", "size": 4220, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Aerodynamics/tabulatedAtmosphere.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/Astrodynamics/Aerodynamics/tabulatedAtmosphere.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/Astrodynamics/Aerodynamics/tabulatedAtmosphere.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": 43.9583333333, "max_line_length": 99, "alphanum_fraction": 0.71492891, "num_tokens": 957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.2921442568576775}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <array>\n#include <vector>\n#include <deque>\n#include <forward_list>\n#include <list>\n#include <map>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <string>\n#include <Eigen/Geometry>\n#include <arc_utilities/arc_helpers.hpp>\n\n#ifndef PRETTY_PRINT_HPP\n#define PRETTY_PRINT_HPP\n\n// Handy functions for printing vectors and pairs\nnamespace PrettyPrint\n{\n    // Base template function for printing types\n    template <typename T>\n    inline std::string PrettyPrint(const T& toprint, const bool add_delimiters=false, const std::string& separator=\", \")\n    {\n        UNUSED(add_delimiters);\n        UNUSED(separator);\n        std::ostringstream strm;\n        strm << toprint;\n        return strm.str();\n    }\n\n    /////////////////////////////////////////////////////////////////////////////////////////////////////////\n    /////                                       PROTOTYPES ONLY                                         /////\n    ///// Specializations for specific types - if you want a specialization for a new type, add it here /////\n    /////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    template<>\n    inline std::string PrettyPrint(const bool& bool_to_print, const bool add_delimiters, const std::string& separator);\n\n    template<>\n    inline std::string PrettyPrint(const Eigen::Vector2d& vector_to_print, const bool add_delimiters, const std::string& separator);\n\n    template<>\n    inline std::string PrettyPrint(const Eigen::Vector3d& vector_to_print, const bool add_delimiters, const std::string& separator);\n\n    template<>\n    inline std::string PrettyPrint(const Eigen::Vector4d& vector_to_print, const bool add_delimiters, const std::string& separator);\n\n    template<>\n    inline std::string PrettyPrint(const Eigen::VectorXd& vector_to_print, const bool add_delimiters, const std::string& separator);\n\n    template<>\n    inline std::string PrettyPrint(const Eigen::MatrixXd& matrix_to_print, const bool add_delimiters, const std::string& separator);\n\n    template<>\n    inline std::string PrettyPrint(const Eigen::Quaterniond& quaternion_to_print, const bool add_delimiters, const std::string& separator);\n\n    template<>\n    inline std::string PrettyPrint(const Eigen::Isometry3d& transform_to_print, const bool add_delimiters, const std::string& separator);\n\n    template <typename A, typename B>\n    inline std::string PrettyPrint(const std::pair<A, B>& pairtoprint, const bool add_delimiters=false, const std::string& separator=\", \");\n\n    template <typename T, size_t N>\n    inline std::string PrettyPrint(const std::array<T, N>& arraytoprint, const bool add_delimiters=false, const std::string& separator=\", \");\n\n    template <typename T, typename Allocator=std::allocator<T>>\n    inline std::string PrettyPrint(const std::vector<T, Allocator>& vectoprint, const bool add_delimiters=false, const std::string& separator=\", \");\n\n    template <typename T, typename Allocator=std::allocator<T>>\n    inline std::string PrettyPrint(const std::list<T, Allocator>& listtoprint, const bool add_delimiters=false, const std::string& separator=\", \");\n\n    template <typename T, typename Allocator=std::allocator<T>>\n    inline std::string PrettyPrint(const std::forward_list<T, Allocator>& listtoprint, const bool add_delimiters=false, const std::string& separator=\", \");\n\n    template <typename T, typename Allocator=std::allocator<T>>\n    inline std::string PrettyPrint(const std::deque<T, Allocator>& dequetoprint, const bool add_delimiters=false, const std::string& separator=\", \");\n\n    template <typename A, typename B, typename Compare=std::less<A>, typename Allocator=std::allocator<std::pair<const A, B>>>\n    inline std::string PrettyPrint(const std::map<A, B, Compare, Allocator>& maptoprint, const bool add_delimiters=false, const std::string& separator=\", \");\n\n    template <typename A, typename B, typename Compare=std::less<A>, typename Allocator=std::allocator<std::pair<const A, B>>>\n    inline std::string PrettyPrint(const std::multimap<A, B, Compare, Allocator>& maptoprint, const bool add_delimiters=false, const std::string& separator=\", \");\n\n    template <typename T, typename Compare=std::less<T>, typename Allocator=std::allocator<T>>\n    inline std::string PrettyPrint(const std::set<T, Compare, Allocator>& settoprint, const bool add_delimiters=false, const std::string& separator=\", \");\n\n    template <typename T, typename Compare=std::less<T>, typename Allocator=std::allocator<T>>\n    inline std::string PrettyPrint(const std::multiset<T, Compare, Allocator>& settoprint, const bool add_delimiters=false, const std::string& separator=\", \");\n\n    template <typename A, typename B, typename Hash=std::hash<A>, typename Predicate=std::equal_to<A>, typename Allocator=std::allocator<std::pair<const A, B>>>\n    inline std::string PrettyPrint(const std::unordered_map<A, B, Hash, Predicate, Allocator>& maptoprint, const bool add_delimiters=false, const std::string& separator=\", \");\n\n    template <typename A, typename B, typename Hash=std::hash<A>, typename Predicate=std::equal_to<A>, typename Allocator=std::allocator<std::pair<const A, B>>>\n    inline std::string PrettyPrint(const std::unordered_multimap<A, B, Hash, Predicate, Allocator>& maptoprint, const bool add_delimiters=false, const std::string& separator=\", \");\n\n    template <typename T, typename Hash=std::hash<T>, typename Predicate=std::equal_to<T>, typename Allocator=std::allocator<T>>\n    inline std::string PrettyPrint(const std::unordered_set<T, Hash, Predicate, Allocator>& settoprint, const bool add_delimiters=false, const std::string& separator=\", \");\n\n    template <typename T, typename Hash=std::hash<T>, typename Predicate=std::equal_to<T>, typename Allocator=std::allocator<T>>\n    inline std::string PrettyPrint(const std::unordered_multiset<T, Hash, Predicate, Allocator>& settoprint, const bool add_delimiters=false, const std::string& separator=\", \");\n\n    /////////////////////////////////////////////////////////////////////////////////////////////////////////\n    /////                                   IMPLEMENTATIONS ONLY                                        /////\n    ///// Specializations for specific types - if you want a specialization for a new type, add it here /////\n    /////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    template<>\n    inline std::string PrettyPrint(const bool& bool_to_print, const bool add_delimiters, const std::string& separator)\n    {\n        UNUSED(add_delimiters);\n        UNUSED(separator);\n        if (bool_to_print)\n        {\n            return \"true\";\n        }\n        else\n        {\n            return \"false\";\n        }\n    }\n\n    template<>\n    inline std::string PrettyPrint(const Eigen::Vector2d& vector_to_print, const bool add_delimiters, const std::string& separator)\n    {\n        UNUSED(add_delimiters);\n        UNUSED(separator);\n        std::ostringstream strm;\n        strm << std::setprecision(12) << \"Vector2d: <x: \" << vector_to_print(0) << \" y: \" << vector_to_print(1) << \">\";\n        return strm.str();\n    }\n\n    template<>\n    inline std::string PrettyPrint(const Eigen::Vector3d& vector_to_print, const bool add_delimiters, const std::string& separator)\n    {\n        UNUSED(add_delimiters);\n        UNUSED(separator);\n        std::ostringstream strm;\n        strm << std::setprecision(12) << \"Vector3d: <x: \" << vector_to_print.x() << \" y: \" << vector_to_print.y() << \" z: \" << vector_to_print.z() << \">\";\n        return strm.str();\n    }\n\n    template<>\n    inline std::string PrettyPrint(const Eigen::Vector4d& vector_to_print, const bool add_delimiters, const std::string& separator)\n    {\n        UNUSED(add_delimiters);\n        UNUSED(separator);\n        std::ostringstream strm;\n        strm << std::setprecision(12) << \"Vector4d: <x: \" << vector_to_print(0) << \" y: \" << vector_to_print(1) << \" z: \" << vector_to_print(2) << \" w: \" << vector_to_print(3) << \">\";\n        return strm.str();\n    }\n\n    template<>\n    inline std::string PrettyPrint(const Eigen::VectorXd& vector_to_print, const bool add_delimiters, const std::string& separator)\n    {\n        UNUSED(add_delimiters);\n        UNUSED(separator);\n        if (vector_to_print.size() > 1)\n        {\n            std::ostringstream strm;\n            strm << \"VectorXd: <\" << std::to_string(vector_to_print(0));\n            for (std::ptrdiff_t idx = 1; idx < vector_to_print.size(); idx++)\n            {\n                strm << \", \" << std::to_string(vector_to_print(idx));\n            }\n            strm << \">\";\n            return strm.str();\n        }\n        else if (vector_to_print.size() == 1)\n        {\n            return \"VectorXd: <\" + std::to_string(vector_to_print(0)) + \">\";\n        }\n        else\n        {\n            return \"VectorXd: <>\";\n        }\n    }\n\n    template<>\n    inline std::string PrettyPrint(const Eigen::MatrixXd& matrix_to_print, const bool add_delimiters, const std::string& separator)\n    {\n        UNUSED(add_delimiters);\n        UNUSED(separator);\n        if (matrix_to_print.rows() > 0 && matrix_to_print.cols() > 0)\n        {\n            std::ostringstream strm;\n            strm << \"MatrixXd:\\n[\";\n            strm << std::to_string(matrix_to_print(0, 0));\n            for (int64_t col = 1; col < matrix_to_print.cols(); col++)\n            {\n                strm << \", \" << std::to_string(matrix_to_print(0, col));\n            }\n            for (int64_t row = 1; row < matrix_to_print.rows(); row++)\n            {\n                strm << \"\\n\" << std::to_string(matrix_to_print(row, 0));\n                for (int64_t col = 1; col < matrix_to_print.cols(); col++)\n                {\n                    strm << \", \" << std::to_string(matrix_to_print(row, col));\n                }\n            }\n            strm << \"]\";\n            return strm.str();\n        }\n        else\n        {\n            return \"MatrixXd:\\n[]\";\n        }\n    }\n\n    template<>\n    inline std::string PrettyPrint(const Eigen::Quaterniond& quaternion_to_print, const bool add_delimiters, const std::string& separator)\n    {\n        UNUSED(add_delimiters);\n        UNUSED(separator);\n        return \"Quaterniond <x: \" + std::to_string(quaternion_to_print.x()) + \" y: \" + std::to_string(quaternion_to_print.y()) + \" z: \" + std::to_string(quaternion_to_print.z()) + \" w: \" + std::to_string(quaternion_to_print.w()) + \">\";\n    }\n\n    template<>\n    inline std::string PrettyPrint(const Eigen::Isometry3d& transform_to_print, const bool add_delimiters, const std::string& separator)\n    {\n        UNUSED(add_delimiters);\n        UNUSED(separator);\n        Eigen::Vector3d vector_to_print = transform_to_print.translation();\n        Eigen::Quaterniond quaternion_to_print(transform_to_print.rotation());\n        return \"Isometry3d <x: \" + std::to_string(vector_to_print.x()) + \" y: \" + std::to_string(vector_to_print.y()) + \" z: \" + std::to_string(vector_to_print.z()) + \">, <x: \" + std::to_string(quaternion_to_print.x()) + \" y: \" + std::to_string(quaternion_to_print.y()) + \" z: \" + std::to_string(quaternion_to_print.z()) + \" w: \" + std::to_string(quaternion_to_print.w()) + \">\";\n    }\n\n    template <typename A, typename B>\n    inline std::string PrettyPrint(const std::pair<A, B>& pairtoprint, const bool add_delimiters, const std::string& separator)\n    {\n        std::ostringstream strm;\n        if (add_delimiters)\n        {\n            strm << \"<\" << PrettyPrint(pairtoprint.first, add_delimiters, separator) << \": \" << PrettyPrint(pairtoprint.second, add_delimiters, separator) << \">\";\n        }\n        else\n        {\n            strm << PrettyPrint(pairtoprint.first, add_delimiters, separator) << \": \" << PrettyPrint(pairtoprint.second, add_delimiters, separator);\n        }\n        return strm.str();\n    }\n\n    template <typename T, size_t N>\n    inline std::string PrettyPrint(const std::array<T, N>& arraytoprint, const bool add_delimiters, const std::string& separator)\n    {\n        std::ostringstream strm;\n        if (arraytoprint.size() > 0)\n        {\n            if (add_delimiters)\n            {\n                strm << \"[\" << PrettyPrint(arraytoprint[0], add_delimiters, separator);\n                for (size_t idx = 1; idx < arraytoprint.size(); idx++)\n                {\n                    strm << separator << PrettyPrint(arraytoprint[idx], add_delimiters, separator);\n                }\n                strm << \"]\";\n            }\n            else\n            {\n                strm << PrettyPrint(arraytoprint[0], add_delimiters, separator);\n                for (size_t idx = 1; idx < arraytoprint.size(); idx++)\n                {\n                    strm << separator << PrettyPrint(arraytoprint[idx], add_delimiters, separator);\n                }\n            }\n        }\n        return strm.str();\n    }\n\n    template <typename T, typename Allocator>\n    inline std::string PrettyPrint(const std::vector<T, Allocator>& vectoprint, const bool add_delimiters, const std::string& separator)\n    {\n        std::ostringstream strm;\n        if (vectoprint.size() > 0)\n        {\n            if (add_delimiters)\n            {\n                strm << \"[\" << PrettyPrint(vectoprint[0], add_delimiters, separator);\n                for (size_t idx = 1; idx < vectoprint.size(); idx++)\n                {\n                    strm << separator << PrettyPrint(vectoprint[idx], add_delimiters, separator);\n                }\n                strm << \"]\";\n            }\n            else\n            {\n                strm << PrettyPrint(vectoprint[0], add_delimiters, separator);\n                for (size_t idx = 1; idx < vectoprint.size(); idx++)\n                {\n                    strm << separator << PrettyPrint(vectoprint[idx], add_delimiters, separator);\n                }\n            }\n        }\n        return strm.str();\n    }\n\n    template <typename T, typename Allocator>\n    inline std::string PrettyPrint(const std::list<T, Allocator>& listtoprint, const bool add_delimiters, const std::string& separator)\n    {\n        std::ostringstream strm;\n        if (listtoprint.size() > 0)\n        {\n            if (add_delimiters)\n            {\n                strm << \"[\";\n                typename std::list<T, Allocator>::const_iterator itr;\n                for (itr = listtoprint.begin(); itr != listtoprint.end(); ++itr)\n                {\n                    if (itr != listtoprint.begin())\n                    {\n                        strm << separator << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                    else\n                    {\n                        strm << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                }\n                strm << \"]\";\n            }\n            else\n            {\n                typename std::list<T, Allocator>::const_iterator itr;\n                for (itr = listtoprint.begin(); itr != listtoprint.end(); ++itr)\n                {\n                    if (itr != listtoprint.begin())\n                    {\n                        strm << separator << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                    else\n                    {\n                        strm << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                }\n            }\n        }\n        return strm.str();\n    }\n\n    template <typename T, typename Allocator>\n    inline std::string PrettyPrint(const std::forward_list<T, Allocator>& listtoprint, const bool add_delimiters, const std::string& separator)\n    {\n        std::ostringstream strm;\n        if (listtoprint.size() > 0)\n        {\n            if (add_delimiters)\n            {\n                strm << \"[\";\n                typename std::forward_list<T, Allocator>::const_iterator itr;\n                for (itr = listtoprint.begin(); itr != listtoprint.end(); ++itr)\n                {\n                    if (itr != listtoprint.begin())\n                    {\n                        strm << separator << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                    else\n                    {\n                        strm << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                }\n                strm << \"]\";\n            }\n            else\n            {\n                typename std::forward_list<T, Allocator>::const_iterator itr;\n                for (itr = listtoprint.begin(); itr != listtoprint.end(); ++itr)\n                {\n                    if (itr != listtoprint.begin())\n                    {\n                        strm << separator << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                    else\n                    {\n                        strm << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                }\n            }\n        }\n        return strm.str();\n    }\n\n    template <typename T, typename Allocator>\n    inline std::string PrettyPrint(const std::deque<T, Allocator>& dequetoprint, const bool add_delimiters, const std::string& separator)\n    {\n        std::ostringstream strm;\n        if (dequetoprint.size() > 0)\n        {\n            if (add_delimiters)\n            {\n                strm << \"[\";\n                typename std::deque<T, Allocator>::const_iterator itr;\n                for (itr = dequetoprint.begin(); itr != dequetoprint.end(); ++itr)\n                {\n                    if (itr != dequetoprint.begin())\n                    {\n                        strm << separator << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                    else\n                    {\n                        strm << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                }\n                strm << \"]\";\n            }\n            else\n            {\n                typename std::deque<T, Allocator>::const_iterator itr;\n                for (itr = dequetoprint.begin(); itr != dequetoprint.end(); ++itr)\n                {\n                    if (itr != dequetoprint.begin())\n                    {\n                        strm << separator << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                    else\n                    {\n                        strm << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                }\n            }\n        }\n        return strm.str();\n    }\n\n    template <typename A, typename B, typename Compare, typename Allocator>\n    inline std::string PrettyPrint(const std::map<A, B, Compare, Allocator>& maptoprint, const bool add_delimiters, const std::string& separator)\n    {\n        std::ostringstream strm;\n        if (maptoprint.size() > 0)\n        {\n            if (add_delimiters)\n            {\n                strm << \"{\";\n                typename std::map<A, B, Compare, Allocator>::const_iterator itr;\n                for (itr = maptoprint.begin(); itr != maptoprint.end(); ++itr)\n                {\n                    std::pair<A, B> cur_pair(itr->first, itr->second);\n                    if (itr != maptoprint.begin())\n                    {\n                        strm << separator << PrettyPrint(cur_pair, add_delimiters, separator);\n                    }\n                    else\n                    {\n                        strm << PrettyPrint(cur_pair, add_delimiters, separator);\n                    }\n                }\n                strm << \"}\";\n            }\n            else\n            {\n                typename std::map<A, B, Compare, Allocator>::const_iterator itr;\n                for (itr = maptoprint.begin(); itr != maptoprint.end(); ++itr)\n                {\n                    std::pair<A, B> cur_pair(itr->first, itr->second);\n                    if (itr != maptoprint.begin())\n                    {\n                        strm << separator << PrettyPrint(cur_pair, add_delimiters, separator);\n                    }\n                    else\n                    {\n                        strm << PrettyPrint(cur_pair, add_delimiters, separator);\n                    }\n                }\n            }\n        }\n        return strm.str();\n    }\n\n    template <typename A, typename B, typename Compare, typename Allocator>\n    inline std::string PrettyPrint(const std::multimap<A, B, Compare, Allocator>& maptoprint, const bool add_delimiters, const std::string& separator)\n    {\n        std::ostringstream strm;\n        if (maptoprint.size() > 0)\n        {\n            if (add_delimiters)\n            {\n                strm << \"{\";\n                typename std::multimap<A, B, Compare, Allocator>::const_iterator itr;\n                for (itr = maptoprint.begin(); itr != maptoprint.end(); ++itr)\n                {\n                    std::pair<A, B> cur_pair(itr->first, itr->second);\n                    if (itr != maptoprint.begin())\n                    {\n                        strm << separator << PrettyPrint(cur_pair, add_delimiters, separator);\n                    }\n                    else\n                    {\n                        strm << PrettyPrint(cur_pair, add_delimiters, separator);\n                    }\n                }\n                strm << \"}\";\n            }\n            else\n            {\n                typename std::multimap<A, B, Compare, Allocator>::const_iterator itr;\n                for (itr = maptoprint.begin(); itr != maptoprint.end(); ++itr)\n                {\n                    std::pair<A, B> cur_pair(itr->first, itr->second);\n                    if (itr != maptoprint.begin())\n                    {\n                        strm << separator << PrettyPrint(cur_pair, add_delimiters, separator);\n                    }\n                    else\n                    {\n                        strm << PrettyPrint(cur_pair, add_delimiters, separator);\n                    }\n                }\n            }\n        }\n        return strm.str();\n    }\n\n    template <typename T, typename Compare, typename Allocator>\n    inline std::string PrettyPrint(const std::set<T, Compare, Allocator>& settoprint, const bool add_delimiters, const std::string& separator)\n    {\n        std::ostringstream strm;\n        if (settoprint.size() > 0)\n        {\n            if (add_delimiters)\n            {\n                strm << \"(\";\n                typename std::set<T, Compare, Allocator>::const_iterator itr;\n                for (itr = settoprint.begin(); itr != settoprint.end(); ++itr)\n                {\n                    if (itr != settoprint.begin())\n                    {\n                        strm << separator << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                    else\n                    {\n                        strm << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                }\n                strm << \")\";\n            }\n            else\n            {\n                typename std::set<T, Compare, Allocator>::const_iterator itr;\n                for (itr = settoprint.begin(); itr != settoprint.end(); ++itr)\n                {\n                    if (itr != settoprint.begin())\n                    {\n                        strm << separator << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                    else\n                    {\n                        strm << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                }\n            }\n        }\n        return strm.str();\n    }\n\n    template <typename T, typename Compare, typename Allocator>\n    inline std::string PrettyPrint(const std::multiset<T, Compare, Allocator>& settoprint, const bool add_delimiters, const std::string& separator)\n    {\n        std::ostringstream strm;\n        if (settoprint.size() > 0)\n        {\n            if (add_delimiters)\n            {\n                strm << \"(\";\n                typename std::multiset<T, Compare, Allocator>::const_iterator itr;\n                for (itr = settoprint.begin(); itr != settoprint.end(); ++itr)\n                {\n                    if (itr != settoprint.begin())\n                    {\n                        strm << separator << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                    else\n                    {\n                        strm << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                }\n                strm << \")\";\n            }\n            else\n            {\n                typename std::multiset<T, Compare, Allocator>::const_iterator itr;\n                for (itr = settoprint.begin(); itr != settoprint.end(); ++itr)\n                {\n                    if (itr != settoprint.begin())\n                    {\n                        strm << separator << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                    else\n                    {\n                        strm << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                }\n            }\n        }\n        return strm.str();\n    }\n\n    template <typename A, typename B, typename Hash, typename Predicate, typename Allocator>\n    inline std::string PrettyPrint(const std::unordered_map<A, B, Hash, Predicate, Allocator>& maptoprint, const bool add_delimiters, const std::string& separator)\n    {\n        std::ostringstream strm;\n        if (maptoprint.size() > 0)\n        {\n            if (add_delimiters)\n            {\n                strm << \"{\";\n                typename std::unordered_map<A, B, Hash, Predicate, Allocator>::const_iterator itr;\n                for (itr = maptoprint.begin(); itr != maptoprint.end(); ++itr)\n                {\n                    std::pair<A, B> cur_pair(itr->first, itr->second);\n                    if (itr != maptoprint.begin())\n                    {\n                        strm << separator << PrettyPrint(cur_pair, add_delimiters, separator);\n                    }\n                    else\n                    {\n                        strm << PrettyPrint(cur_pair, add_delimiters, separator);\n                    }\n                }\n                strm << \"}\";\n            }\n            else\n            {\n                typename std::unordered_map<A, B, Hash, Predicate, Allocator>::const_iterator itr;\n                for (itr = maptoprint.begin(); itr != maptoprint.end(); ++itr)\n                {\n                    std::pair<A, B> cur_pair(itr->first, itr->second);\n                    if (itr != maptoprint.begin())\n                    {\n                        strm << separator << PrettyPrint(cur_pair, add_delimiters, separator);\n                    }\n                    else\n                    {\n                        strm << PrettyPrint(cur_pair, add_delimiters, separator);\n                    }\n                }\n            }\n        }\n        return strm.str();\n    }\n\n    template <typename A, typename B, typename Hash, typename Predicate, typename Allocator>\n    inline std::string PrettyPrint(const std::unordered_multimap<A, B, Hash, Predicate, Allocator>& maptoprint, const bool add_delimiters, const std::string& separator)\n    {\n        std::ostringstream strm;\n        if (maptoprint.size() > 0)\n        {\n            if (add_delimiters)\n            {\n                strm << \"{\";\n                typename std::unordered_multimap<A, B, Hash, Predicate, Allocator>::const_iterator itr;\n                for (itr = maptoprint.begin(); itr != maptoprint.end(); ++itr)\n                {\n                    std::pair<A, B> cur_pair(itr->first, itr->second);\n                    if (itr != maptoprint.begin())\n                    {\n                        strm << separator << PrettyPrint(cur_pair, add_delimiters, separator);\n                    }\n                    else\n                    {\n                        strm << PrettyPrint(cur_pair, add_delimiters, separator);\n                    }\n                }\n                strm << \"}\";\n            }\n            else\n            {\n                typename std::unordered_multimap<A, B, Hash, Predicate, Allocator>::const_iterator itr;\n                for (itr = maptoprint.begin(); itr != maptoprint.end(); ++itr)\n                {\n                    std::pair<A, B> cur_pair(itr->first, itr->second);\n                    if (itr != maptoprint.begin())\n                    {\n                        strm << separator << PrettyPrint(cur_pair, add_delimiters, separator);\n                    }\n                    else\n                    {\n                        strm << PrettyPrint(cur_pair, add_delimiters, separator);\n                    }\n                }\n            }\n        }\n        return strm.str();\n    }\n\n    template <typename T, typename Hash, typename Predicate, typename Allocator>\n    inline std::string PrettyPrint(const std::unordered_set<T, Hash, Predicate, Allocator>& settoprint, const bool add_delimiters, const std::string& separator)\n    {\n        std::ostringstream strm;\n        if (settoprint.size() > 0)\n        {\n            if (add_delimiters)\n            {\n                strm << \"(\";\n                typename std::unordered_set<T, Hash, Predicate, Allocator>::const_iterator itr;\n                for (itr = settoprint.begin(); itr != settoprint.end(); ++itr)\n                {\n                    if (itr != settoprint.begin())\n                    {\n                        strm << separator << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                    else\n                    {\n                        strm << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                }\n                strm << \")\";\n            }\n            else\n            {\n                typename std::unordered_set<T, Hash, Predicate, Allocator>::const_iterator itr;\n                for (itr = settoprint.begin(); itr != settoprint.end(); ++itr)\n                {\n                    if (itr != settoprint.begin())\n                    {\n                        strm << separator << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                    else\n                    {\n                        strm << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                }\n            }\n        }\n        return strm.str();\n    }\n\n    template <typename T, typename Hash, typename Predicate, typename Allocator>\n    inline std::string PrettyPrint(const std::unordered_multiset<T, Hash, Predicate, Allocator>& settoprint, const bool add_delimiters, const std::string& separator)\n    {\n        std::ostringstream strm;\n        if (settoprint.size() > 0)\n        {\n            if (add_delimiters)\n            {\n                strm << \"(\";\n                typename std::unordered_multiset<T, Hash, Predicate, Allocator>::const_iterator itr;\n                for (itr = settoprint.begin(); itr != settoprint.end(); ++itr)\n                {\n                    if (itr != settoprint.begin())\n                    {\n                        strm << separator << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                    else\n                    {\n                        strm << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                }\n                strm << \")\";\n            }\n            else\n            {\n                typename std::unordered_multiset<T, Hash, Predicate, Allocator>::const_iterator itr;\n                for (itr = settoprint.begin(); itr != settoprint.end(); ++itr)\n                {\n                    if (itr != settoprint.begin())\n                    {\n                        strm << separator << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                    else\n                    {\n                        strm << PrettyPrint(*itr, add_delimiters, separator);\n                    }\n                }\n            }\n        }\n        return strm.str();\n    }\n}\n\n#endif // PRETTY_PRINT_HPP\n", "meta": {"hexsha": "10fd481a526c06650d8d944c7e4abffeb046c775", "size": 31967, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/arc_utilities/pretty_print.hpp", "max_stars_repo_name": "ToyotaResearchInstitute/arc_utilities", "max_stars_repo_head_hexsha": "f15a1dfd9fba5ca83296354bae8b97628895c1c2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/arc_utilities/pretty_print.hpp", "max_issues_repo_name": "ToyotaResearchInstitute/arc_utilities", "max_issues_repo_head_hexsha": "f15a1dfd9fba5ca83296354bae8b97628895c1c2", "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/arc_utilities/pretty_print.hpp", "max_forks_repo_name": "ToyotaResearchInstitute/arc_utilities", "max_forks_repo_head_hexsha": "f15a1dfd9fba5ca83296354bae8b97628895c1c2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-11-06T21:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-06T21:38:23.000Z", "avg_line_length": 41.5155844156, "max_line_length": 378, "alphanum_fraction": 0.5046141333, "num_tokens": 6455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.2920626865323512}}
{"text": "/*! \\file Peridigm_EnergyReleaseDamageModel.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//////////////////////////////////////////////////////////////////////////////////////    \n// Routine developed for Peridigm by\n// DLR Composite Structures and Adaptive Systems\n//                                __/|__\n//                                /_/_/_/  \n//            www.dlr.de/fa/en      |/ DLR\n//////////////////////////////////////////////////////////////////////////////////////    \n// Questions?\n// Christian Willberg  christian.willberg@dlr.de\n// Martin Raedel       martin.raedel@dlr.de\n//////////////////////////////////////////////////////////////////////////////////////   \n//@HEADER\n\n#include \"Peridigm_EnergyReleaseDamageModel.hpp\"\n#include \"Peridigm_Field.hpp\"\n#include \"material_utilities.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::EnergyReleaseDamageModel::EnergyReleaseDamageModel(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_damageModelFieldId(-1),\nm_OMEGA(PeridigmNS::InfluenceFunction::self().getInfluenceFunction()) {\n\n   \n    if (params.isParameter(\"Critical Energy\")) {\n        m_criticalEnergyTension = params.get<double>(\"Critical Energy Tension\");\n        m_criticalEnergyCompression = params.get<double>(\"Critical Energy Compression\");\n        m_criticalEnergyShear = params.get<double>(\"Critical Energy Shear\");\n          \n    } else {\n        if (params.isParameter(\"Critical Energy Tension\"))\n            m_criticalEnergyTension = params.get<double>(\"Critical Energy Tension\");\n        else\n            m_criticalEnergyTension = -1.0;\n        if (params.isParameter(\"Critical Energy Compression\"))\n            m_criticalEnergyCompression = params.get<double>(\"Critical Energy Compression\");\n        else\n            m_criticalEnergyCompression = -1.0;\n        if (params.isParameter(\"Critical Energy Shear\"))\n            m_criticalEnergyShear = params.get<double>(\"Critical Energy Shear\");\n        else\n            m_criticalEnergyShear = -1.0; \n        m_type = 1;\n        if (params.isType<string>(\"Energy Criterion\"))\n            m_type = 1;\n        if (params.isType<string>(\"Power Law\"))\n            m_type = 2;\n        if (params.isType<string>(\"Separated\"))\n            m_type = 3; \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(\"Model_Coordinates\");\n    m_coordinatesFieldId = fieldManager.getFieldId(\"Coordinates\");\n    m_volumeFieldId = fieldManager.getFieldId(PeridigmNS::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(PeridigmNS::PeridigmField::ELEMENT, PeridigmNS::PeridigmField::SCALAR, PeridigmNS::PeridigmField::TWO_STEP, \"Damage\");\n    m_bondDamageFieldId = fieldManager.getFieldId(PeridigmNS::PeridigmField::BOND, PeridigmNS::PeridigmField::SCALAR, PeridigmNS::PeridigmField::TWO_STEP, \"Bond_Damage\");\n    m_horizonFieldId = fieldManager.getFieldId(PeridigmNS::PeridigmField::ELEMENT, PeridigmNS::PeridigmField::SCALAR, PeridigmNS::PeridigmField::CONSTANT, \"Horizon\");\n    m_damageModelFieldId = fieldManager.getFieldId(PeridigmNS::PeridigmField::NODE, PeridigmNS::PeridigmField::VECTOR, PeridigmNS::PeridigmField::TWO_STEP, \"Damage_Model_Data\");\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_damageModelFieldId);\n    m_fieldIds.push_back(m_bondDamageFieldId);\n    m_fieldIds.push_back(m_horizonFieldId);\n\n}\n\nPeridigmNS::EnergyReleaseDamageModel::~EnergyReleaseDamageModel() {\n}\n\nvoid\nPeridigmNS::EnergyReleaseDamageModel::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\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::EnergyReleaseDamageModel::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;\n    double *cellVolume, *weightedVolume, *damageModel;\n    double criticalEnergyTension(-1.0), criticalEnergyCompression(-1.0), criticalEnergyShear(-1.0);\n    // for temperature dependencies easy to extent\n    double *deltaTemperature = NULL;\n    double m_alpha = 0;\n\n    dataManager.getData(m_damageFieldId, PeridigmField::STEP_NP1)->ExtractView(&damage);\n    dataManager.getData(m_modelCoordinatesFieldId, PeridigmField::STEP_NONE)->ExtractView(&x);\n    dataManager.getData(m_coordinatesFieldId, PeridigmField::STEP_NP1)->ExtractView(&y);\n    dataManager.getData(m_weightedVolumeFieldId, PeridigmField::STEP_NONE)->ExtractView(&weightedVolume);\n    dataManager.getData(m_volumeFieldId, PeridigmField::STEP_NONE)->ExtractView(&cellVolume);\n    //////////////////////////////////////////////////////////////\n    // transfer of data is done in ComputeDilation --> PeridigmMaterial.cpp\n    //////////////////////////////////////////////////////////////\n    dataManager.getData(m_damageModelFieldId, PeridigmField::STEP_NP1)->ExtractView(&damageModel);\n    dataManager.getData(m_horizonFieldId, PeridigmField::STEP_NONE)->ExtractView(&horizon);\n    ////////////////////////////////////\n    ////////////////////////////////////\n    // transfer of data is done in ComputeDilation --> PeridigmMaterial.cpp\n    dataManager.getData(m_bondDamageFieldId, PeridigmField::STEP_NP1)->ExtractView(&bondDamageNP1);\n    \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 alphaP1, alphaP2;\n    double nodeInitialX[3], nodeCurrentX[3], relativeExtension(0.0);\n    double bondEnergyIsotropic(0.0), bondEnergyDeviatoric(0.0);\n    double omegaP1, omegaP2;\n    double critDev, critIso, critComp;\n    double BulkMod1, BulkMod2;\n    double degradationFactor = 1.0; // Optional parameter if bond should be degradated and not fully destroyed instantaneously \n    double avgHorizon, quadhorizon;\n    //---------------------------\n    // INITIALIZE PROCESS STEP t\n    //---------------------------\n    \n    if (m_criticalEnergyTension > 0.0)\n        criticalEnergyTension = m_criticalEnergyTension;\n    if (m_criticalEnergyCompression > 0.0)\n        criticalEnergyCompression = m_criticalEnergyCompression;\n    if (m_criticalEnergyShear > 0.0)\n        criticalEnergyShear = m_criticalEnergyShear;\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) {\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        double dilatationP1 = damageModel[3*nodeId];\n        \n        alphaP1 = 15.0 * damageModel[3*nodeId+2]; // weightedVolume is already included in --> Perdigm_Material.cpp;\n        \n        for (iNID = 0; iNID < numNeighbors; ++iNID) {\n            \n            trialDamage = 0.0;\n            neighborID = neighborhoodList[neighborhoodListIndex++];\n            \n            double zeta = \n            distance(nodeInitialX[0], nodeInitialX[1], nodeInitialX[2],\n                 x[neighborID*3], x[neighborID*3+1], x[neighborID*3+2]);\n\n            double dY = \n            distance(nodeCurrentX[0], nodeCurrentX[1], nodeCurrentX[2],\n                 y[neighborID*3], y[neighborID*3+1], y[neighborID*3+2]);\n \n            relativeExtension = (dY - zeta)/zeta;    \n             // the direction switches between both bonds. This results in a switch of the forces\n             // as well. Therefore, all forces and bond deformations are normalized.\n            double eP = dY - zeta;\n            //double normZeta = sqrt(zeta*zeta);\n            \n            alphaP2 = 15.0 * damageModel[3*neighborID+2]; // weightedVolume is already included in --> Perdigm_Material.cpp;\n            \n            BulkMod1 = damageModel[3*nodeId+1];     // weightedVolume is already included in the variable --> Perdigm_Material.cpp;\n            BulkMod2 = damageModel[3*neighborID+1]; // weightedVolume is already included in the variable --> Perdigm_Material.cpp;\n            \n            \n            double dilatationP2 = damageModel[3*neighborID];\n            \n            omegaP1 = MATERIAL_EVALUATION::scalarInfluenceFunction(zeta, horizon[nodeId]); \n            omegaP2 = MATERIAL_EVALUATION::scalarInfluenceFunction(zeta, horizon[neighborID]); \n\n            double eiP1 = dilatationP1 * zeta / 3.0;\n            double eiP2 = dilatationP2 * zeta / 3.0;\n            double tiP1 = 3*BulkMod1*omegaP1*dilatationP1*zeta;\n            double tiP2 = 3*BulkMod2*omegaP2*dilatationP2*zeta;\n            \n\n            double edP1 = eP - sqrt(eiP1*eiP1);\n            double edP2 = eP - sqrt(eiP2*eiP2);\n            double tdP1 = omegaP1*alphaP1*edP1;\n            double tdP2 = omegaP2*alphaP2*edP2;\n            // absolute values of energy, because it is positive and coordinate errors are avoided.\n            bondEnergyIsotropic  = (1.0 - bondDamageNP1[bondIndex])*(sqrt(tiP1*eiP1*tiP1*eiP1) + sqrt(tiP2*eiP2*tiP2*eiP2)); \n            bondEnergyDeviatoric = (1.0 - bondDamageNP1[bondIndex])*(sqrt(tdP1*edP1*tdP2*edP2) + sqrt(tdP2*edP2*tdP2*edP2));\n            // the average horizon is taken, if multiple horizons are used\n            avgHorizon = 0.5*(horizon[nodeId]+horizon[neighborID]);\n\n            // geometrical part of the energy value\n            quadhorizon =  16.0 /( m_pi * avgHorizon * avgHorizon * avgHorizon * avgHorizon );\n            // the factor 16 can be split in three parts:\n            // 4 comes from the integration from Foster et al. (2009) Journal for Multiscale Computational Engineering; \n            // 2 comes from the force split motivated by the bond based formulation Bobaru et al. (2017) \"Handbook of Peridynamik Modeling\", page 48 ; \n            // 2 comes from the energy formulation itself\n            critIso = 0.0;\n            if (relativeExtension>0&&criticalEnergyTension != -1.0){\n               critIso = (bondEnergyIsotropic/(criticalEnergyTension*quadhorizon));\n            }\n            critDev = 0.0;\n            if (criticalEnergyShear != -1.0){\n               critDev = (bondEnergyDeviatoric/(criticalEnergyShear*quadhorizon));\n            }\n            critComp = 0.0;\n            if (relativeExtension < 0.0 && criticalEnergyCompression != -1.0){\n                critComp = (bondEnergyIsotropic/(criticalEnergyCompression*quadhorizon));\n                critIso = 0.0;\n            }\n            if (m_type == 1){ // Energy Criterion by Foster et al.(2009) Journal for Multiscale Computational Engineering;\n                double bondEnergy = sqrt((tdP1+tiP1)*(tdP1+tiP1)*eP*eP) + sqrt((tdP2 + tiP2)*(tdP2 + tiP2)*eP*eP);\n                critIso = bondEnergy/(criticalEnergyTension*quadhorizon);\n                if (m_criticalEnergyTension > 0.0 && critIso > 1.0 ) {\n                    trialDamage = bondDamageNP1[bondIndex] + degradationFactor;\n                } \n            }\n            \n            if (m_type == 2){// Power Law\n    \n                if (m_criticalEnergyTension > 0.0 &&critIso*critIso + critDev*critDev + critComp*critComp > 1.0) {\n                   trialDamage = bondDamageNP1[bondIndex] + degradationFactor;\n                }\n            }\n            if (m_type == 3){ // Separated\n                if (m_criticalEnergyTension > 0.0  &&critIso > 1.0) {\n                   trialDamage = bondDamageNP1[bondIndex] + degradationFactor;\n                }\n                if (m_criticalEnergyTension > 0.0 && critDev > 1.0) {\n                   trialDamage = bondDamageNP1[bondIndex] + degradationFactor;\n                } \n                if (m_criticalEnergyCompression > 0.0  && critComp > 1.0) {\n                   trialDamage = bondDamageNP1[bondIndex] + degradationFactor;\n                }\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    \n\n    //  Update the element damage (percent of bonds broken)\n\n    neighborhoodListIndex = 0;\n    bondIndex = 0;\n    for (iID = 0; iID < numOwnedPoints; ++iID) {\n        nodeId = ownedIDs[iID];\n        numNeighbors = neighborhoodList[neighborhoodListIndex++];\n        //neighborhoodListIndex += numNeighbors;\n        damageModel[3*nodeId] = 0.0;\n        damageModel[3*nodeId+1] = 0.0;\n        damageModel[3*nodeId+2] = 0.0;\n        totalDamage = 0.0;\n        for (iNID = 0; iNID < numNeighbors; ++iNID) {\n            \n            neighborID = neighborhoodList[neighborhoodListIndex++];\n            // must be zero to avoid synchronization errors\n            damageModel[3*neighborID] = 0.0;\n            damageModel[3*neighborID+1] = 0.0;\n            damageModel[3*neighborID+2] = 0.0;\n            \n            totalDamage += bondDamageNP1[bondIndex];\n\n            bondIndex += 1;\n        }\n        if (numNeighbors > 0)\n            totalDamage /= numNeighbors;\n        else\n            totalDamage = 0.0;\n        damage[nodeId] = totalDamage;\n    }\n}\n\n\n", "meta": {"hexsha": "9f7ca4bc381d80d3d88b2cc91ff8935038e8ee96", "size": 17531, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Peridigm/Code/Energy_damage_criterion/src/damage/Peridigm_EnergyReleaseDamageModel.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/Energy_damage_criterion/src/damage/Peridigm_EnergyReleaseDamageModel.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/Energy_damage_criterion/src/damage/Peridigm_EnergyReleaseDamageModel.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": 44.9512820513, "max_line_length": 177, "alphanum_fraction": 0.630825395, "num_tokens": 4408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.2920626789105918}}
{"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#include \"../Util/SimpleLogger.h\"\r\n#include \"../Util/StringUtil.h\"\r\n#include \"../Util/TrigonometryTables.h\"\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(lat);\r\n        SimpleLogger().Write(logDEBUG) << \"broken lat: \" << lat << \", bits: \" << y;\r\n    }\r\n    if (0 != (std::abs(lon) >> 30))\r\n    {\r\n        std::bitset<32> x(lon);\r\n        SimpleLogger().Write(logDEBUG) << \"broken lon: \" << lon << \", bits: \" << x;\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::isValid() 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 &c1,\r\n                                                 const FixedPointCoordinate &c2)\r\n{\r\n    return ApproximateDistance(c1.lat, c1.lon, c2.lat, c2.lon);\r\n}\r\n\r\nfloat FixedPointCoordinate::ApproximateEuclideanDistance(const FixedPointCoordinate &c1,\r\n                                                 const FixedPointCoordinate &c2)\r\n{\r\n    return ApproximateEuclideanDistance(c1.lat, c1.lon, c2.lat, c2.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.017453292519943295769236907684886;\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 = (float_lon2 - float_lon1) * cos((float_lat1 + float_lat2) / 2.);\r\n    const float y = (float_lat2 - float_lat1);\r\n    const float earth_radius = 6372797.560856;\r\n    return sqrt(x * x + y * y) * earth_radius;\r\n}\r\n\r\nfloat FixedPointCoordinate::ComputePerpendicularDistance(const FixedPointCoordinate &point,\r\n                                                          const FixedPointCoordinate &segA,\r\n                                                          const FixedPointCoordinate &segB)\r\n{\r\n    const float x = lat2y(point.lat / COORDINATE_PRECISION);\r\n    const float y = point.lon / COORDINATE_PRECISION;\r\n    const float a = lat2y(segA.lat / COORDINATE_PRECISION);\r\n    const float b = segA.lon / COORDINATE_PRECISION;\r\n    const float c = lat2y(segB.lat / COORDINATE_PRECISION);\r\n    const float d = segB.lon / COORDINATE_PRECISION;\r\n    float p, q, nY;\r\n    if (std::abs(a - c) > std::numeric_limits<float>::epsilon())\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. + 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. / COORDINATE_PRECISION))\r\n    {\r\n        nY = 0.;\r\n    }\r\n\r\n    float r = (p - nY * a) / c;\r\n    if (std::isnan(r))\r\n    {\r\n        r = ((segB.lat == point.lat) && (segB.lon == point.lon)) ? 1. : 0.;\r\n    }\r\n    else if (std::abs(r) <= std::numeric_limits<float>::epsilon())\r\n    {\r\n        r = 0.;\r\n    }\r\n    else if (std::abs(r - 1.) <= std::numeric_limits<float>::epsilon())\r\n    {\r\n        r = 1.;\r\n    }\r\n    FixedPointCoordinate nearest_location;\r\n    BOOST_ASSERT(!std::isnan(r));\r\n    if (r <= 0.)\r\n    { // point is \"left\" of edge\r\n        nearest_location.lat = segA.lat;\r\n        nearest_location.lon = segA.lon;\r\n    }\r\n    else if (r >= 1.)\r\n    { // point is \"right\" of edge\r\n        nearest_location.lat = segB.lat;\r\n        nearest_location.lon = segB.lon;\r\n    }\r\n    else\r\n    { // point lies in between\r\n        nearest_location.lat = y2lat(p) * COORDINATE_PRECISION;\r\n        nearest_location.lon = q * COORDINATE_PRECISION;\r\n    }\r\n    BOOST_ASSERT(nearest_location.isValid());\r\n    const float approximated_distance =\r\n        FixedPointCoordinate::ApproximateEuclideanDistance(point, nearest_location);\r\n    BOOST_ASSERT(0. <= approximated_distance);\r\n    return approximated_distance;\r\n}\r\n\r\nfloat FixedPointCoordinate::ComputePerpendicularDistance(const FixedPointCoordinate &coord_a,\r\n                                                   const FixedPointCoordinate &coord_b,\r\n                                                   const FixedPointCoordinate &query_location,\r\n                                                   FixedPointCoordinate &nearest_location,\r\n                                                   float &r)\r\n{\r\n    BOOST_ASSERT(query_location.isValid());\r\n\r\n    const float x = lat2y(query_location.lat / COORDINATE_PRECISION);\r\n    const float y = query_location.lon / COORDINATE_PRECISION;\r\n    const float a = lat2y(coord_a.lat / COORDINATE_PRECISION);\r\n    const float b = coord_a.lon / COORDINATE_PRECISION;\r\n    const float c = lat2y(coord_b.lat / COORDINATE_PRECISION);\r\n    const float d = coord_b.lon / COORDINATE_PRECISION;\r\n    float p, q /*,mX*/, nY;\r\n    if (std::abs(a - c) > std::numeric_limits<float>::epsilon())\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. + 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. / COORDINATE_PRECISION))\r\n    {\r\n        nY = 0.;\r\n    }\r\n\r\n    r = (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(r))\r\n    {\r\n        r = ((coord_b.lat == query_location.lat) && (coord_b.lon == query_location.lon)) ? 1. : 0.;\r\n    }\r\n    else if (std::abs(r) <= std::numeric_limits<float>::epsilon())\r\n    {\r\n        r = 0.;\r\n    }\r\n    else if (std::abs(r - 1.) <= std::numeric_limits<float>::epsilon())\r\n    {\r\n        r = 1.;\r\n    }\r\n    BOOST_ASSERT(!std::isnan(r));\r\n    if (r <= 0.)\r\n    {\r\n        nearest_location = coord_a;\r\n    }\r\n    else if (r >= 1.)\r\n    {\r\n        nearest_location = coord_b;\r\n    }\r\n    else\r\n    {\r\n        // point lies in between\r\n        nearest_location.lat = y2lat(p) * COORDINATE_PRECISION;\r\n        nearest_location.lon = q * COORDINATE_PRECISION;\r\n    }\r\n    BOOST_ASSERT(nearest_location.isValid());\r\n\r\n    // TODO: Replace with euclidean approximation when k-NN search is done\r\n    // const float approximated_distance = FixedPointCoordinate::ApproximateEuclideanDistance(\r\n    const float approximated_distance =\r\n        FixedPointCoordinate::ApproximateEuclideanDistance(query_location, nearest_location);\r\n    BOOST_ASSERT(0. <= approximated_distance);\r\n    return approximated_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 &A, const FixedPointCoordinate &B)\r\n{\r\n    const float delta_long = DegreeToRadian(B.lon / COORDINATE_PRECISION - A.lon / COORDINATE_PRECISION);\r\n    const float lat1 = DegreeToRadian(A.lat / COORDINATE_PRECISION);\r\n    const float lat2 = DegreeToRadian(B.lat / COORDINATE_PRECISION);\r\n    const float y = sin(delta_long) * cos(lat2);\r\n    const float x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(delta_long);\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 delta_long = 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 = std::sin(delta_long) * std::cos(lat2);\r\n    const float x = std::cos(lat1) * std::sin(lat2) - std::sin(lat1) * std::cos(lat2) * std::cos(delta_long);\r\n    float result = RadianToDegree(std::atan2(y, x));\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 * (M_PI / 180.f);\r\n}\r\n\r\nfloat FixedPointCoordinate::RadianToDegree(const float radian) \r\n{\r\n    return radian * (180.f / M_PI);\r\n}\r\n", "meta": {"hexsha": "3e99f8ec84d2a99d03de7c2431f08aa59d65fdb3", "size": 13809, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DataStructures/Coordinate.cpp", "max_stars_repo_name": "gberaudo/Project-OSRM", "max_stars_repo_head_hexsha": "04788f58fac77153e3a43d3cd46084410a953052", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-20T09:38:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-20T09:38:56.000Z", "max_issues_repo_path": "DataStructures/Coordinate.cpp", "max_issues_repo_name": "gberaudo/Project-OSRM", "max_issues_repo_head_hexsha": "04788f58fac77153e3a43d3cd46084410a953052", "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": "DataStructures/Coordinate.cpp", "max_forks_repo_name": "gberaudo/Project-OSRM", "max_forks_repo_head_hexsha": "04788f58fac77153e3a43d3cd46084410a953052", "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.2440944882, "max_line_length": 110, "alphanum_fraction": 0.6006227822, "num_tokens": 3485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.2920626789105918}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <boost/range/combine.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <cstddef>\n\n#include \"DataStructures/Index.hpp\"\n#include \"DataStructures/SliceIterator.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"DataStructures/Variables.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\n/// @{\n/*!\n * \\ingroup DataStructuresGroup\n * \\brief Slices volume `Tensor`s into a `Variables`\n *\n * The slice has a constant logical coordinate in direction `sliced_dim`,\n * slicing the volume at `fixed_index` in that dimension.  For\n * example, to get the lower boundary of `sliced_dim`, pass `0` for\n * `fixed_index`; to get the upper boundary, pass\n * `extents[sliced_dim] - 1`.\n */\ntemplate <typename... TagsToSlice, size_t VolumeDim>\nvoid data_on_slice(\n    const gsl::not_null<Variables<tmpl::list<TagsToSlice...>>*> interface_vars,\n    const Index<VolumeDim>& element_extents, const size_t sliced_dim,\n    const size_t fixed_index, const typename TagsToSlice::type&... tensors) {\n  const size_t interface_grid_points =\n      element_extents.slice_away(sliced_dim).product();\n  if (interface_vars->number_of_grid_points() != interface_grid_points) {\n    *interface_vars =\n        Variables<tmpl::list<TagsToSlice...>>(interface_grid_points);\n  }\n  for (SliceIterator si(element_extents, sliced_dim, fixed_index); si; ++si) {\n    const auto lambda = [&si](auto& interface_tensor,\n                              const auto& volume_tensor) {\n      for (decltype(auto) interface_and_volume_tensor_components :\n           boost::combine(interface_tensor, volume_tensor)) {\n        boost::get<0>(\n            interface_and_volume_tensor_components)[si.slice_offset()] =\n            boost::get<1>(\n                interface_and_volume_tensor_components)[si.volume_offset()];\n      }\n      return '0';\n    };\n    expand_pack(lambda(get<TagsToSlice>(*interface_vars), tensors)...);\n  }\n}\n\ntemplate <typename... TagsToSlice, size_t VolumeDim>\nVariables<tmpl::list<TagsToSlice...>> data_on_slice(\n    const Index<VolumeDim>& element_extents, const size_t sliced_dim,\n    const size_t fixed_index, const typename TagsToSlice::type&... tensors) {\n  Variables<tmpl::list<TagsToSlice...>> interface_vars(\n      element_extents.slice_away(sliced_dim).product());\n  data_on_slice<TagsToSlice...>(make_not_null(&interface_vars), element_extents,\n                                sliced_dim, fixed_index, tensors...);\n  return interface_vars;\n}\n/// @}\n", "meta": {"hexsha": "fed005b74434390094522fb83d56db923dbcabe5", "size": 2536, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/DataStructures/SliceTensorToVariables.hpp", "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/DataStructures/SliceTensorToVariables.hpp", "max_issues_repo_name": "GitHimanshuc/spectre", "max_issues_repo_head_hexsha": "4de4033ba36547113293fe4dbdd77591485a4aee", "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/DataStructures/SliceTensorToVariables.hpp", "max_forks_repo_name": "geoffrey4444/spectre", "max_forks_repo_head_hexsha": "9350d61830b360e2d5b273fdd176dcc841dbefb0", "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": 38.4242424242, "max_line_length": 80, "alphanum_fraction": 0.7054416404, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150636, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.29206267128883234}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2020 Nikita Kaskov <nbering@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_INJECT_HASH_HPP\n#define CRYPTO3_INJECT_HASH_HPP\n\n#include <boost/crypto3/detail/stream_endian.hpp>\n#include <boost/crypto3/detail/basic_functions.hpp>\n#include <boost/crypto3/detail/unbounded_shift.hpp>\n#include <boost/crypto3/detail/endian_shift.hpp>\n\nnamespace boost {\n    namespace crypto3 {\n        namespace detail {\n\n            template<typename Endianness, std::size_t WordBits, std::size_t BlockWords, std::size_t BlockBits>\n            struct word_injector;\n\n            template<int UnitBits, std::size_t WordBits, std::size_t BlockWords, std::size_t BlockBits>\n            struct word_injector<stream_endian::big_unit_big_bit<UnitBits>, WordBits, BlockWords, BlockBits>\n                : public basic_functions<WordBits> {\n\n                constexpr static const std::size_t word_bits = basic_functions<WordBits>::word_bits;\n                typedef typename basic_functions<WordBits>::word_type word_type;\n\n                typedef std::array<word_type, BlockWords> block_type;\n\n                static void inject(word_type w, std::size_t word_seen, block_type &b, std::size_t &block_seen) {\n                    // Insert word_seen-bit part of word into the block b according to endianness\n\n                    // Check whether we fall out of the block\n                    if (block_seen + word_seen <= BlockBits) {\n                        std::size_t last_word_ind = block_seen / word_bits;\n                        std::size_t last_word_seen = block_seen % word_bits;\n\n                        // Remove garbage\n                        w &= high_bits<word_bits>(~word_type(), word_seen);\n                        b[last_word_ind] &= high_bits<word_bits>(~word_type(), last_word_seen);\n\n                        // Add significant word bits to block word\n                        b[last_word_ind] |= unbounded_shr(w, last_word_seen);\n\n                        // If we fall out of the block word, push the remainder of element to the next block word\n                        if (last_word_seen + word_seen > word_bits)\n                            b[last_word_ind + 1] = unbounded_shl(w, word_bits - last_word_seen);\n\n                        block_seen += word_seen;\n                    }\n                }\n            };\n\n            template<int UnitBits, std::size_t WordBits, std::size_t BlockWords, std::size_t BlockBits>\n            struct word_injector<stream_endian::little_unit_big_bit<UnitBits>, WordBits, BlockWords, BlockBits>\n                : public basic_functions<WordBits> {\n\n                constexpr static const std::size_t word_bits = basic_functions<WordBits>::word_bits;\n                typedef typename basic_functions<WordBits>::word_type word_type;\n\n                typedef std::array<word_type, BlockWords> block_type;\n\n                static void inject(word_type w, std::size_t word_seen, block_type &b, std::size_t &block_seen) {\n                    // Insert word_seen-bit part of word into the block b according to endianness\n\n                    // Check whether we fall out of the block\n                    if (block_seen + word_seen <= BlockBits) {\n                        std::size_t last_word_ind = block_seen / word_bits;\n                        std::size_t last_word_seen = block_seen % word_bits;\n\n                        // Remove garbage\n                        std::size_t w_rem = word_seen % UnitBits;\n                        std::size_t w_unit_bits = word_seen - w_rem;\n                        word_type mask =\n                            low_bits<word_bits>(~word_type(), w_unit_bits) |\n                            unbounded_shl(low_bits<word_bits>(~word_type(), w_rem), w_unit_bits + UnitBits - w_rem);\n                        w &= mask;\n\n                        std::size_t b_rem = last_word_seen % UnitBits;\n                        std::size_t b_unit_bits = last_word_seen - b_rem;\n                        mask = low_bits<word_bits>(~word_type(), b_unit_bits) |\n                               unbounded_shl(low_bits<word_bits>(~word_type(), b_rem), b_unit_bits + UnitBits - b_rem);\n                        b[last_word_ind] &= mask;\n\n                        // Split and combine parts of unit values\n                        std::size_t sz[2] = {UnitBits - b_rem, b_rem};\n                        word_type masks[2];\n                        masks[0] = unbounded_shl(low_bits<word_bits>(~word_type(), UnitBits - b_rem), b_rem);\n                        masks[1] = low_bits<word_bits>(~word_type(), b_rem);\n                        std::size_t bw_space = word_bits - last_word_seen;\n                        std::size_t w_space = word_seen;\n                        word_type w_split = 0;\n                        std::size_t sz_ind = 0;\n\n                        while (bw_space && w_space) {\n                            w_split |= (!sz_ind ? unbounded_shr(w & masks[0], b_rem) :\n                                                  unbounded_shl(w & masks[1], UnitBits + sz[0]));\n                            bw_space -= sz[sz_ind];\n                            w_space -= (w_space >= sz[sz_ind]) ? sz[sz_ind] : w_space;\n                            masks[sz_ind] = unbounded_shl(masks[sz_ind], UnitBits);\n                            sz_ind = 1 - sz_ind;\n                        }\n\n                        // Add significant word bits to block word\n                        b[last_word_ind] |= unbounded_shl(w_split, b_unit_bits);\n\n                        // If we fall out of the block word, push the remainder of element to the next block word\n                        if (last_word_seen + word_seen > word_bits) {\n                            w = unbounded_shr(w, word_bits - b_unit_bits - UnitBits);\n                            w_split = 0;\n                            masks[0] =\n                                unbounded_shl(low_bits<word_bits>(~word_type(), UnitBits - b_rem), b_rem + UnitBits);\n                            masks[1] = low_bits<word_bits>(~word_type(), b_rem);\n\n                            while (w_space) {\n                                w_split |= (!sz_ind ? unbounded_shr(w & masks[0], b_rem) :\n                                                      unbounded_shl(w & masks[1], UnitBits + sz[0]));\n                                w_space -= (w_space >= sz[sz_ind]) ? sz[sz_ind] : w_space;\n                                masks[sz_ind] = unbounded_shl(masks[sz_ind], UnitBits);\n                                sz_ind = 1 - sz_ind;\n                            }\n\n                            b[last_word_ind + 1] = unbounded_shr(w_split, UnitBits);\n                        }\n\n                        block_seen += word_seen;\n                    }\n                }\n            };\n\n            template<int UnitBits, std::size_t WordBits, std::size_t BlockWords, std::size_t BlockBits>\n            struct word_injector<stream_endian::big_unit_little_bit<UnitBits>, WordBits, BlockWords, BlockBits>\n                : public basic_functions<WordBits> {\n\n                constexpr static const std::size_t word_bits = basic_functions<WordBits>::word_bits;\n                typedef typename basic_functions<WordBits>::word_type word_type;\n\n                typedef std::array<word_type, BlockWords> block_type;\n\n                static void inject(word_type w, std::size_t word_seen, block_type &b, std::size_t &block_seen) {\n                    // Insert word_seen-bit part of word into the block b according to endianness\n\n                    // Check whether we fall out of the block\n                    if (block_seen + word_seen <= BlockBits) {\n                        std::size_t last_word_ind = block_seen / word_bits;\n                        std::size_t last_word_seen = block_seen % word_bits;\n\n                        // Remove garbage\n                        std::size_t w_rem = word_seen % UnitBits;\n                        std::size_t w_unit_bits = word_seen - w_rem;\n                        word_type mask =\n                            high_bits<word_bits>(~word_type(), w_unit_bits) |\n                            unbounded_shr(high_bits<word_bits>(~word_type(), w_rem), w_unit_bits + UnitBits - w_rem);\n                        w &= mask;\n                        std::size_t b_rem = last_word_seen % UnitBits;\n                        std::size_t b_unit_bits = last_word_seen - b_rem;\n                        mask = high_bits<word_bits>(~word_type(), b_unit_bits) |\n                               unbounded_shr(high_bits<word_bits>(~word_type(), b_rem), b_unit_bits + UnitBits - b_rem);\n                        b[last_word_ind] &= mask;\n\n                        // Split and combine parts of unit values\n                        std::size_t sz[2] = {UnitBits - b_rem, b_rem};\n                        word_type masks[2] = {\n                            unbounded_shr(high_bits<word_bits>(~word_type(), UnitBits - b_rem), b_rem),\n                            high_bits<word_bits>(~word_type(), b_rem)};\n                        std::size_t bw_space = word_bits - last_word_seen;\n                        std::size_t w_space = word_seen;\n                        word_type w_split = 0;\n                        std::size_t sz_ind = 0;\n\n                        while (bw_space && w_space) {\n                            w_split |= (!sz_ind ? unbounded_shl(w & masks[0], b_rem) :\n                                                  unbounded_shr(w & masks[1], UnitBits + sz[0]));\n                            bw_space -= sz[sz_ind];\n                            w_space -= (w_space >= sz[sz_ind]) ? sz[sz_ind] : w_space;\n                            masks[sz_ind] = unbounded_shr(masks[sz_ind], UnitBits);\n                            sz_ind = 1 - sz_ind;\n                        }\n\n                        // Add significant word bits to block word\n                        b[last_word_ind] |= unbounded_shr(w_split, b_unit_bits);\n\n                        // If we fall out of the block word, push the remainder of element to the next block word\n                        if (last_word_seen + word_seen > word_bits) {\n                            w = unbounded_shl(w, word_bits - b_unit_bits - UnitBits);\n                            w_split = 0;\n                            masks[0] =\n                                unbounded_shr(high_bits<word_bits>(~word_type(), UnitBits - b_rem), b_rem + UnitBits);\n                            masks[1] = high_bits<word_bits>(~word_type(), b_rem);\n\n                            while (w_space) {\n                                w_split |= (!sz_ind ? unbounded_shl(w & masks[0], b_rem) :\n                                                      unbounded_shr(w & masks[1], UnitBits + sz[0]));\n                                w_space -= (w_space >= sz[sz_ind]) ? sz[sz_ind] : w_space;\n                                masks[sz_ind] = unbounded_shr(masks[sz_ind], UnitBits);\n                                sz_ind = 1 - sz_ind;\n                            }\n\n                            b[last_word_ind + 1] = unbounded_shl(w_split, UnitBits);\n                        }\n                        block_seen += word_seen;\n                    }\n                }\n            };\n\n            template<int UnitBits, std::size_t WordBits, std::size_t BlockWords, std::size_t BlockBits>\n            struct word_injector<stream_endian::little_unit_little_bit<UnitBits>, WordBits, BlockWords, BlockBits>\n                : public basic_functions<WordBits> {\n\n                constexpr static const std::size_t word_bits = basic_functions<WordBits>::word_bits;\n                typedef typename basic_functions<WordBits>::word_type word_type;\n\n                typedef std::array<word_type, BlockWords> block_type;\n\n                static void inject(word_type w, std::size_t word_seen, block_type &b, std::size_t &block_seen) {\n                    // Insert word_seen-bit part of word into the block b according to endianness\n\n                    // Check whether we fall out of the block\n                    if (block_seen + word_seen <= BlockBits) {\n                        std::size_t last_word_ind = block_seen / word_bits;\n                        std::size_t last_word_seen = block_seen % word_bits;\n\n                        // Remove garbage\n                        w &= low_bits<word_bits>(~word_type(), word_seen);\n                        b[last_word_ind] &= low_bits<word_bits>(~word_type(), last_word_seen);\n\n                        // Add significant word bits to block word\n                        b[last_word_ind] |= unbounded_shl(w, last_word_seen);\n\n                        // If we fall out of the block word, push the remainder of element to the next block word\n                        if (last_word_seen + word_seen > word_bits)\n                            b[last_word_ind + 1] = unbounded_shr(w, word_bits - last_word_seen);\n\n                        block_seen += word_seen;\n                    }\n                }\n            };\n\n            template<typename Endianness, std::size_t WordBits, std::size_t BlockWords, std::size_t BlockBits>\n            struct injector : word_injector<Endianness, WordBits, BlockWords, BlockBits> {\n\n                constexpr static const std::size_t word_bits = basic_functions<WordBits>::word_bits;\n                typedef typename basic_functions<WordBits>::word_type word_type;\n\n                typedef std::array<word_type, BlockWords> block_type;\n\n                static void inject(const block_type &b_src, std::size_t b_src_seen, block_type &b_dst,\n                                   std::size_t &b_dst_seen, std::size_t block_shift = 0) {\n                    // Insert word_seen-bit part of word into the block b according to endianness\n\n                    // Check whether we fall out of the block\n                    if (b_src_seen + b_dst_seen <= BlockBits) {\n\n                        std::size_t first_word_ind = block_shift / word_bits;\n                        std::size_t word_shift = block_shift % word_bits;\n\n                        std::size_t first_word_seen =\n                            (word_bits - word_shift) > b_src_seen ? b_src_seen : (word_bits - word_shift);\n\n                        inject(b_src[first_word_ind], first_word_seen, b_dst, b_dst_seen, word_shift);\n\n                        b_src_seen -= first_word_seen;\n\n                        for (std::size_t i = 0; i < (b_src_seen / word_bits); i++) {\n                            inject(b_src[first_word_ind + 1 + i], word_bits, b_dst, b_dst_seen);\n                        }\n\n                        if (b_src_seen % word_bits) {\n                            inject(b_src[first_word_ind + 1 + b_src_seen / word_bits], b_src_seen % word_bits, b_dst,\n                                   b_dst_seen);\n                        }\n                    }\n                }\n\n                static void inject(word_type w, std::size_t word_seen, block_type &b, std::size_t &block_seen,\n                                   std::size_t word_shift = 0) {\n\n                    word_type word_shifted = w;\n\n                    if (word_shift > 0) {\n                        endian_shift<Endianness, word_bits>::to_msb(word_shifted, word_shift);\n                    }\n\n                    word_injector<Endianness, WordBits, BlockWords, BlockBits>::inject(word_shifted, word_seen, b,\n                                                                                       block_seen);\n                }\n            };\n        }    // namespace detail\n    }        // namespace crypto3\n}    // namespace boost\n\n#endif    // CRYPTO3_INJECT_HASH_HPP\n", "meta": {"hexsha": "ac9ae282c0c21fc0e8c771ddcb9a2b4ce0b32a29", "size": 15878, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/crypto3/detail/inject.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/detail/inject.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/detail/inject.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": 53.4612794613, "max_line_length": 120, "alphanum_fraction": 0.5085653105, "num_tokens": 3259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2920127661247331}}
{"text": "// ----------------------------------------------------------------------------\n// -                        Open3D: www.open3d.org                            -\n// ----------------------------------------------------------------------------\n// The MIT License (MIT)\n//\n// Copyright (c) 2018 www.open3d.org\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\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n// ----------------------------------------------------------------------------\n\n#include \"open3d/geometry/PointCloud.h\"\n#include \"open3d/geometry/TriangleMesh.h\"\n#include \"open3d/utility/Console.h\"\n\n#include <Eigen/Dense>\n#include <cfloat>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n#include <iostream>\n#include <list>\n\n// clang-format off\n#include \"PoissonRecon/Src/PreProcessor.h\"\n#include \"PoissonRecon/Src/MyMiscellany.h\"\n#include \"PoissonRecon/Src/CmdLineParser.h\"\n#include \"PoissonRecon/Src/FEMTree.h\"\n#include \"PoissonRecon/Src/PPolynomial.h\"\n#include \"PoissonRecon/Src/PointStreamData.h\"\n// clang-format on\n\nnamespace open3d {\nnamespace geometry {\nnamespace poisson {\n\n// The order of the B-Spline used to splat in data for color interpolation\nstatic const int DATA_DEGREE = 0;\n// The order of the B-Spline used to splat in the weights for density estimation\nstatic const int WEIGHT_DEGREE = 2;\n// The order of the B-Spline used to splat in the normals for constructing the\n// Laplacian constraints\nstatic const int NORMAL_DEGREE = 2;\n// The default finite-element degree\nstatic const int DEFAULT_FEM_DEGREE = 1;\n// The default finite-element boundary type\nstatic const BoundaryType DEFAULT_FEM_BOUNDARY = BOUNDARY_NEUMANN;\n// The dimension of the system\nstatic const int DIMENSION = 3;\n\nclass Open3DData {\npublic:\n    Open3DData() : normal_(0, 0, 0), color_(0, 0, 0) {}\n    Open3DData(const Eigen::Vector3d& normal, const Eigen::Vector3d& color)\n        : normal_(normal), color_(color) {}\n\n    Open3DData operator*(double s) const {\n        return Open3DData(s * normal_, s * color_);\n    }\n    Open3DData operator/(double s) const {\n        return Open3DData(normal_ / s, (1 / s) * color_);\n    }\n    Open3DData& operator+=(const Open3DData& d) {\n        normal_ += d.normal_;\n        color_ += d.color_;\n        return *this;\n    }\n    Open3DData& operator*=(double s) {\n        normal_ *= s;\n        color_ *= s;\n        return *this;\n    }\n\npublic:\n    Eigen::Vector3d normal_;\n    Eigen::Vector3d color_;\n};\n\ntemplate <typename Real>\nclass Open3DPointStream\n    : public InputPointStreamWithData<Real, DIMENSION, Open3DData> {\npublic:\n    Open3DPointStream(const open3d::geometry::PointCloud* pcd)\n        : pcd_(pcd), xform_(nullptr), current_(0) {}\n    void reset(void) { current_ = 0; }\n    bool nextPoint(Point<Real, 3>& p, Open3DData& d) {\n        if (current_ >= pcd_->points_.size()) {\n            return false;\n        }\n        p.coords[0] = static_cast<Real>(pcd_->points_[current_](0));\n        p.coords[1] = static_cast<Real>(pcd_->points_[current_](1));\n        p.coords[2] = static_cast<Real>(pcd_->points_[current_](2));\n\n        if (xform_ != nullptr) {\n            p = (*xform_) * p;\n        }\n\n        if (pcd_->HasNormals()) {\n            d.normal_ = pcd_->normals_[current_];\n        } else {\n            d.normal_ = Eigen::Vector3d(0, 0, 0);\n        }\n\n        if (pcd_->HasColors()) {\n            d.color_ = pcd_->colors_[current_];\n        } else {\n            d.color_ = Eigen::Vector3d(0, 0, 0);\n        }\n\n        current_++;\n        return true;\n    }\n\npublic:\n    const open3d::geometry::PointCloud* pcd_;\n    XForm<Real, 4>* xform_;\n    size_t current_;\n};\n\ntemplate <typename _Real>\nclass Open3DVertex {\npublic:\n    typedef _Real Real;\n\n    Open3DVertex() : Open3DVertex(Point<Real, 3>(0, 0, 0)) {}\n    Open3DVertex(Point<Real, 3> point)\n        : point(point), normal_(0, 0, 0), color_(0, 0, 0), w_(0) {}\n\n    Open3DVertex& operator*=(Real s) {\n        point *= s;\n        normal_ *= s;\n        color_ *= s;\n        w_ *= s;\n        return *this;\n    }\n\n    Open3DVertex& operator+=(const Open3DVertex& p) {\n        point += p.point;\n        normal_ += p.normal_;\n        color_ += p.color_;\n        w_ += p.w_;\n        return *this;\n    }\n\n    Open3DVertex& operator/=(Real s) {\n        point /= s;\n        normal_ /= s;\n        color_ /= s;\n        w_ /= s;\n        return *this;\n    }\n\npublic:\n    // point can not have trailing _, because template methods assume that it is\n    // named this way\n    Point<Real, 3> point;\n    Eigen::Vector3d normal_;\n    Eigen::Vector3d color_;\n    double w_;\n};\n\ntemplate <unsigned int Dim, class Real>\nstruct FEMTreeProfiler {\n    FEMTree<Dim, Real>& tree;\n    double t;\n\n    FEMTreeProfiler(FEMTree<Dim, Real>& t) : tree(t) {}\n    void start(void) {\n        t = Time(), FEMTree<Dim, Real>::ResetLocalMemoryUsage();\n    }\n    void dumpOutput(const char* header) const {\n        FEMTree<Dim, Real>::MemoryUsage();\n        if (header) {\n            utility::LogDebug(\"{} {} (s), {} (MB) / {} (MB) / {} (MB)\", header,\n                              Time() - t,\n                              FEMTree<Dim, Real>::LocalMemoryUsage(),\n                              FEMTree<Dim, Real>::MaxMemoryUsage(),\n                              MemoryInfo::PeakMemoryUsageMB());\n        } else {\n            utility::LogDebug(\"{} (s), {} (MB) / {} (MB) / {} (MB)\", Time() - t,\n                              FEMTree<Dim, Real>::LocalMemoryUsage(),\n                              FEMTree<Dim, Real>::MaxMemoryUsage(),\n                              MemoryInfo::PeakMemoryUsageMB());\n        }\n    }\n};\n\ntemplate <class Real, unsigned int Dim>\nXForm<Real, Dim + 1> GetBoundingBoxXForm(Point<Real, Dim> min,\n                                         Point<Real, Dim> max,\n                                         Real scaleFactor) {\n    Point<Real, Dim> center = (max + min) / 2;\n    Real scale = max[0] - min[0];\n    for (unsigned int d = 1; d < Dim; d++) {\n        scale = std::max<Real>(scale, max[d] - min[d]);\n    }\n    scale *= scaleFactor;\n    for (unsigned int i = 0; i < Dim; i++) {\n        center[i] -= scale / 2;\n    }\n    XForm<Real, Dim + 1> tXForm = XForm<Real, Dim + 1>::Identity(),\n                         sXForm = XForm<Real, Dim + 1>::Identity();\n    for (unsigned int i = 0; i < Dim; i++) {\n        sXForm(i, i) = (Real)(1. / scale), tXForm(Dim, i) = -center[i];\n    }\n    return sXForm * tXForm;\n}\n\ntemplate <class Real, unsigned int Dim>\nXForm<Real, Dim + 1> GetBoundingBoxXForm(Point<Real, Dim> min,\n                                         Point<Real, Dim> max,\n                                         Real width,\n                                         Real scaleFactor,\n                                         int& depth) {\n    // Get the target resolution (along the largest dimension)\n    Real resolution = (max[0] - min[0]) / width;\n    for (unsigned int d = 1; d < Dim; d++) {\n        resolution = std::max<Real>(resolution, (max[d] - min[d]) / width);\n    }\n    resolution *= scaleFactor;\n    depth = 0;\n    while ((1 << depth) < resolution) {\n        depth++;\n    }\n\n    Point<Real, Dim> center = (max + min) / 2;\n    Real scale = (1 << depth) * width;\n\n    for (unsigned int i = 0; i < Dim; i++) {\n        center[i] -= scale / 2;\n    }\n    XForm<Real, Dim + 1> tXForm = XForm<Real, Dim + 1>::Identity(),\n                         sXForm = XForm<Real, Dim + 1>::Identity();\n    for (unsigned int i = 0; i < Dim; i++) {\n        sXForm(i, i) = (Real)(1. / scale), tXForm(Dim, i) = -center[i];\n    }\n    return sXForm * tXForm;\n}\n\ntemplate <class Real, unsigned int Dim>\nXForm<Real, Dim + 1> GetPointXForm(InputPointStream<Real, Dim>& stream,\n                                   Real width,\n                                   Real scaleFactor,\n                                   int& depth) {\n    Point<Real, Dim> min, max;\n    stream.boundingBox(min, max);\n    return GetBoundingBoxXForm(min, max, width, scaleFactor, depth);\n}\n\ntemplate <class Real, unsigned int Dim>\nXForm<Real, Dim + 1> GetPointXForm(InputPointStream<Real, Dim>& stream,\n                                   Real scaleFactor) {\n    Point<Real, Dim> min, max;\n    stream.boundingBox(min, max);\n    return GetBoundingBoxXForm(min, max, scaleFactor);\n}\n\ntemplate <unsigned int Dim, typename Real>\nstruct ConstraintDual {\n    Real target, weight;\n    ConstraintDual(Real t, Real w) : target(t), weight(w) {}\n    CumulativeDerivativeValues<Real, Dim, 0> operator()(\n            const Point<Real, Dim>& p) const {\n        return CumulativeDerivativeValues<Real, Dim, 0>(target * weight);\n    };\n};\n\ntemplate <unsigned int Dim, typename Real>\nstruct SystemDual {\n    Real weight;\n    SystemDual(Real w) : weight(w) {}\n    CumulativeDerivativeValues<Real, Dim, 0> operator()(\n            const Point<Real, Dim>& p,\n            const CumulativeDerivativeValues<Real, Dim, 0>& dValues) const {\n        return dValues * weight;\n    };\n    CumulativeDerivativeValues<double, Dim, 0> operator()(\n            const Point<Real, Dim>& p,\n            const CumulativeDerivativeValues<double, Dim, 0>& dValues) const {\n        return dValues * weight;\n    };\n};\n\ntemplate <unsigned int Dim>\nstruct SystemDual<Dim, double> {\n    typedef double Real;\n    Real weight;\n    SystemDual(Real w) : weight(w) {}\n    CumulativeDerivativeValues<Real, Dim, 0> operator()(\n            const Point<Real, Dim>& p,\n            const CumulativeDerivativeValues<Real, Dim, 0>& dValues) const {\n        return dValues * weight;\n    };\n};\n\ntemplate <typename Vertex,\n          typename Real,\n          typename SetVertexFunction,\n          unsigned int... FEMSigs,\n          typename... SampleData>\nvoid ExtractMesh(\n        float datax,\n        bool linear_fit,\n        UIntPack<FEMSigs...>,\n        std::tuple<SampleData...>,\n        FEMTree<sizeof...(FEMSigs), Real>& tree,\n        const DenseNodeData<Real, UIntPack<FEMSigs...>>& solution,\n        Real isoValue,\n        const std::vector<typename FEMTree<sizeof...(FEMSigs),\n                                           Real>::PointSample>* samples,\n        std::vector<Open3DData>* sampleData,\n        const typename FEMTree<sizeof...(FEMSigs),\n                               Real>::template DensityEstimator<WEIGHT_DEGREE>*\n                density,\n        const SetVertexFunction& SetVertex,\n        XForm<Real, sizeof...(FEMSigs) + 1> iXForm,\n        std::shared_ptr<open3d::geometry::TriangleMesh>& out_mesh,\n        std::vector<double>& out_densities) {\n    static const int Dim = sizeof...(FEMSigs);\n    typedef UIntPack<FEMSigs...> Sigs;\n    static const unsigned int DataSig =\n            FEMDegreeAndBType<DATA_DEGREE, BOUNDARY_FREE>::Signature;\n    typedef typename FEMTree<Dim,\n                             Real>::template DensityEstimator<WEIGHT_DEGREE>\n            DensityEstimator;\n\n    FEMTreeProfiler<Dim, Real> profiler(tree);\n\n    CoredMeshData<Vertex, node_index_type>* mesh;\n    mesh = new CoredVectorMeshData<Vertex, node_index_type>();\n\n    bool non_manifold = true;\n    bool polygon_mesh = false;\n\n    profiler.start();\n    typename IsoSurfaceExtractor<Dim, Real, Vertex>::IsoStats isoStats;\n    if (sampleData) {\n        SparseNodeData<ProjectiveData<Open3DData, Real>,\n                       IsotropicUIntPack<Dim, DataSig>>\n                _sampleData =\n                        tree.template setMultiDepthDataField<DataSig, false>(\n                                *samples, *sampleData, (DensityEstimator*)NULL);\n        for (const RegularTreeNode<Dim, FEMTreeNodeData, depth_and_offset_type>*\n                     n = tree.tree().nextNode();\n             n; n = tree.tree().nextNode(n)) {\n            ProjectiveData<Open3DData, Real>* clr = _sampleData(n);\n            if (clr) (*clr) *= (Real)pow(datax, tree.depth(n));\n        }\n        isoStats = IsoSurfaceExtractor<Dim, Real, Vertex>::template Extract<\n                Open3DData>(Sigs(), UIntPack<WEIGHT_DEGREE>(),\n                            UIntPack<DataSig>(), tree, density, &_sampleData,\n                            solution, isoValue, *mesh, SetVertex, !linear_fit,\n                            !non_manifold, polygon_mesh, false);\n    } else {\n        isoStats = IsoSurfaceExtractor<Dim, Real, Vertex>::template Extract<\n                Open3DData>(Sigs(), UIntPack<WEIGHT_DEGREE>(),\n                            UIntPack<DataSig>(), tree, density, NULL, solution,\n                            isoValue, *mesh, SetVertex, !linear_fit,\n                            !non_manifold, polygon_mesh, false);\n    }\n\n    mesh->resetIterator();\n    out_densities.clear();\n    for (size_t vidx = 0; vidx < mesh->outOfCorePointCount(); ++vidx) {\n        Vertex v;\n        mesh->nextOutOfCorePoint(v);\n        v.point = iXForm * v.point;\n        out_mesh->vertices_.push_back(\n                Eigen::Vector3d(v.point[0], v.point[1], v.point[2]));\n        out_mesh->vertex_normals_.push_back(v.normal_);\n        out_mesh->vertex_colors_.push_back(v.color_);\n        out_densities.push_back(v.w_);\n    }\n    for (size_t tidx = 0; tidx < mesh->polygonCount(); ++tidx) {\n        std::vector<CoredVertexIndex<node_index_type>> triangle;\n        mesh->nextPolygon(triangle);\n        if (triangle.size() != 3) {\n            open3d::utility::LogError(\"got polygon\");\n        } else {\n            out_mesh->triangles_.push_back(Eigen::Vector3i(\n                    triangle[0].idx, triangle[1].idx, triangle[2].idx));\n        }\n    }\n\n    delete mesh;\n}\n\ntemplate <class Real, typename... SampleData, unsigned int... FEMSigs>\nvoid Execute(const open3d::geometry::PointCloud& pcd,\n             std::shared_ptr<open3d::geometry::TriangleMesh>& out_mesh,\n             std::vector<double>& out_densities,\n             int depth,\n             size_t width,\n             float scale,\n             bool linear_fit,\n             UIntPack<FEMSigs...>) {\n    static const int Dim = sizeof...(FEMSigs);\n    typedef UIntPack<FEMSigs...> Sigs;\n    typedef UIntPack<FEMSignature<FEMSigs>::Degree...> Degrees;\n    typedef UIntPack<FEMDegreeAndBType<\n            NORMAL_DEGREE, DerivativeBoundary<FEMSignature<FEMSigs>::BType,\n                                              1>::BType>::Signature...>\n            NormalSigs;\n    typedef typename FEMTree<Dim,\n                             Real>::template DensityEstimator<WEIGHT_DEGREE>\n            DensityEstimator;\n    typedef typename FEMTree<Dim, Real>::template InterpolationInfo<Real, 0>\n            InterpolationInfo;\n\n    XForm<Real, Dim + 1> xForm, iXForm;\n    xForm = XForm<Real, Dim + 1>::Identity();\n\n    float datax = 32.f;\n    int base_depth = 0;\n    int base_v_cycles = 1;\n    float confidence = 0.f;\n    float point_weight = 2.f * DEFAULT_FEM_DEGREE;\n    float confidence_bias = 0.f;\n    float samples_per_node = 1.5f;\n    float cg_solver_accuracy = 1e-3f;\n    int full_depth = 5;\n    int iters = 8;\n    bool exact_interpolation = false;\n\n    double startTime = Time();\n    Real isoValue = 0;\n\n    FEMTree<Dim, Real> tree(MEMORY_ALLOCATOR_BLOCK_SIZE);\n    FEMTreeProfiler<Dim, Real> profiler(tree);\n\n    size_t pointCount;\n\n    Real pointWeightSum;\n    std::vector<typename FEMTree<Dim, Real>::PointSample> samples;\n    std::vector<Open3DData> sampleData;\n    DensityEstimator* density = NULL;\n    SparseNodeData<Point<Real, Dim>, NormalSigs>* normalInfo = NULL;\n    Real targetValue = (Real)0.5;\n\n    // Read in the samples (and color data)\n    {\n        Open3DPointStream<Real> pointStream(&pcd);\n\n        if (width > 0) {\n            xForm = GetPointXForm<Real, Dim>(pointStream, (Real)width,\n                                             (Real)(scale > 0 ? scale : 1.),\n                                             depth) *\n                    xForm;\n        } else {\n            xForm = scale > 0 ? GetPointXForm<Real, Dim>(pointStream,\n                                                         (Real)scale) *\n                                        xForm\n                              : xForm;\n        }\n\n        pointStream.xform_ = &xForm;\n\n        {\n            auto ProcessDataWithConfidence = [&](const Point<Real, Dim>& p,\n                                                 Open3DData& d) {\n                Real l = (Real)d.normal_.norm();\n                if (!l || l != l) return (Real)-1.;\n                return (Real)pow(l, confidence);\n            };\n            auto ProcessData = [](const Point<Real, Dim>& p, Open3DData& d) {\n                Real l = (Real)d.normal_.norm();\n                if (!l || l != l) return (Real)-1.;\n                d.normal_ /= l;\n                return (Real)1.;\n            };\n            if (confidence > 0) {\n                pointCount = FEMTreeInitializer<Dim, Real>::template Initialize<\n                        Open3DData>(tree.spaceRoot(), pointStream, depth,\n                                    samples, sampleData, true,\n                                    tree.nodeAllocators[0], tree.initializer(),\n                                    ProcessDataWithConfidence);\n            } else {\n                pointCount = FEMTreeInitializer<Dim, Real>::template Initialize<\n                        Open3DData>(tree.spaceRoot(), pointStream, depth,\n                                    samples, sampleData, true,\n                                    tree.nodeAllocators[0], tree.initializer(),\n                                    ProcessData);\n            }\n        }\n        iXForm = xForm.inverse();\n\n        utility::LogDebug(\"Input Points / Samples: {} / {}\", pointCount,\n                          samples.size());\n    }\n\n    int kernelDepth = depth - 2;\n    if (kernelDepth < 0) {\n        utility::LogError(\n                \"[CreateFromPointCloudPoisson] depth (={}) has to be >= 2\",\n                depth);\n    }\n\n    DenseNodeData<Real, Sigs> solution;\n    {\n        DenseNodeData<Real, Sigs> constraints;\n        InterpolationInfo* iInfo = NULL;\n        int solveDepth = depth;\n\n        tree.resetNodeIndices();\n\n        // Get the kernel density estimator\n        {\n            profiler.start();\n            density = tree.template setDensityEstimator<WEIGHT_DEGREE>(\n                    samples, kernelDepth, samples_per_node, 1);\n            profiler.dumpOutput(\"#   Got kernel density:\");\n        }\n\n        // Transform the Hermite samples into a vector field\n        {\n            profiler.start();\n            normalInfo = new SparseNodeData<Point<Real, Dim>, NormalSigs>();\n            std::function<bool(Open3DData, Point<Real, Dim>&)>\n                    ConversionFunction =\n                            [](Open3DData in, Point<Real, Dim>& out) {\n                                // Point<Real, Dim> n = in.template data<0>();\n                                Point<Real, Dim> n(in.normal_(0), in.normal_(1),\n                                                   in.normal_(2));\n                                Real l = (Real)Length(n);\n                                // It is possible that the samples have non-zero\n                                // normals but there are two co-located samples\n                                // with negative normals...\n                                if (!l) return false;\n                                out = n / l;\n                                return true;\n                            };\n            std::function<bool(Open3DData, Point<Real, Dim>&, Real&)>\n                    ConversionAndBiasFunction = [&](Open3DData in,\n                                                    Point<Real, Dim>& out,\n                                                    Real& bias) {\n                        // Point<Real, Dim> n = in.template data<0>();\n                        Point<Real, Dim> n(in.normal_(0), in.normal_(1),\n                                           in.normal_(2));\n                        Real l = (Real)Length(n);\n                        // It is possible that the samples have non-zero normals\n                        // but there are two co-located samples with negative\n                        // normals...\n                        if (!l) return false;\n                        out = n / l;\n                        bias = (Real)(log(l) * confidence_bias /\n                                      log(1 << (Dim - 1)));\n                        return true;\n                    };\n            if (confidence_bias > 0) {\n                *normalInfo = tree.setDataField(\n                        NormalSigs(), samples, sampleData, density,\n                        pointWeightSum, ConversionAndBiasFunction);\n            } else {\n                *normalInfo = tree.setDataField(\n                        NormalSigs(), samples, sampleData, density,\n                        pointWeightSum, ConversionFunction);\n            }\n            ThreadPool::Parallel_for(0, normalInfo->size(),\n                                     [&](unsigned int, size_t i) {\n                                         (*normalInfo)[i] *= (Real)-1.;\n                                     });\n            profiler.dumpOutput(\"#     Got normal field:\");\n            utility::LogDebug(\"Point weight / Estimated Area: {:e} / {:e}\",\n                              pointWeightSum, pointCount * pointWeightSum);\n        }\n\n        // Trim the tree and prepare for multigrid\n        {\n            profiler.start();\n            constexpr int MAX_DEGREE = NORMAL_DEGREE > Degrees::Max()\n                                               ? NORMAL_DEGREE\n                                               : Degrees::Max();\n            tree.template finalizeForMultigrid<MAX_DEGREE>(\n                    full_depth,\n                    typename FEMTree<Dim, Real>::template HasNormalDataFunctor<\n                            NormalSigs>(*normalInfo),\n                    normalInfo, density);\n            profiler.dumpOutput(\"#       Finalized tree:\");\n        }\n\n        // Add the FEM constraints\n        {\n            profiler.start();\n            constraints = tree.initDenseNodeData(Sigs());\n            typename FEMIntegrator::template Constraint<\n                    Sigs, IsotropicUIntPack<Dim, 1>, NormalSigs,\n                    IsotropicUIntPack<Dim, 0>, Dim>\n                    F;\n            unsigned int derivatives2[Dim];\n            for (unsigned int d = 0; d < Dim; d++) derivatives2[d] = 0;\n            typedef IsotropicUIntPack<Dim, 1> Derivatives1;\n            typedef IsotropicUIntPack<Dim, 0> Derivatives2;\n            for (unsigned int d = 0; d < Dim; d++) {\n                unsigned int derivatives1[Dim];\n                for (unsigned int dd = 0; dd < Dim; dd++)\n                    derivatives1[dd] = dd == d ? 1 : 0;\n                F.weights[d]\n                         [TensorDerivatives<Derivatives1>::Index(derivatives1)]\n                         [TensorDerivatives<Derivatives2>::Index(\n                                 derivatives2)] = 1;\n            }\n            tree.addFEMConstraints(F, *normalInfo, constraints, solveDepth);\n            profiler.dumpOutput(\"#  Set FEM constraints:\");\n        }\n\n        // Free up the normal info\n        delete normalInfo, normalInfo = NULL;\n\n        // Add the interpolation constraints\n        if (point_weight > 0) {\n            profiler.start();\n            if (exact_interpolation) {\n                iInfo = FEMTree<Dim, Real>::\n                        template InitializeExactPointInterpolationInfo<Real, 0>(\n                                tree, samples,\n                                ConstraintDual<Dim, Real>(\n                                        targetValue,\n                                        (Real)point_weight * pointWeightSum),\n                                SystemDual<Dim, Real>((Real)point_weight *\n                                                      pointWeightSum),\n                                true, false);\n            } else {\n                iInfo = FEMTree<Dim, Real>::\n                        template InitializeApproximatePointInterpolationInfo<\n                                Real, 0>(\n                                tree, samples,\n                                ConstraintDual<Dim, Real>(\n                                        targetValue,\n                                        (Real)point_weight * pointWeightSum),\n                                SystemDual<Dim, Real>((Real)point_weight *\n                                                      pointWeightSum),\n                                true, 1);\n            }\n            tree.addInterpolationConstraints(constraints, solveDepth, *iInfo);\n            profiler.dumpOutput(\"#Set point constraints:\");\n        }\n\n        utility::LogDebug(\n                \"Leaf Nodes / Active Nodes / Ghost Nodes: {} / {} / {}\",\n                tree.leaves(), tree.nodes(), tree.ghostNodes());\n        utility::LogDebug(\"Memory Usage: {:.3f} MB\",\n                          float(MemoryInfo::Usage()) / (1 << 20));\n\n        // Solve the linear system\n        {\n            profiler.start();\n            typename FEMTree<Dim, Real>::SolverInfo sInfo;\n            sInfo.cgDepth = 0, sInfo.cascadic = true, sInfo.vCycles = 1,\n            sInfo.iters = iters, sInfo.cgAccuracy = cg_solver_accuracy,\n            sInfo.verbose = utility::Logger::i().verbosity_level_ ==\n                            utility::VerbosityLevel::Debug,\n            sInfo.showResidual = utility::Logger::i().verbosity_level_ ==\n                                 utility::VerbosityLevel::Debug,\n            sInfo.showGlobalResidual = SHOW_GLOBAL_RESIDUAL_NONE,\n            sInfo.sliceBlockSize = 1;\n            sInfo.baseDepth = base_depth, sInfo.baseVCycles = base_v_cycles;\n            typename FEMIntegrator::template System<Sigs,\n                                                    IsotropicUIntPack<Dim, 1>>\n                    F({0., 1.});\n            solution = tree.solveSystem(Sigs(), F, constraints, solveDepth,\n                                        sInfo, iInfo);\n            profiler.dumpOutput(\"# Linear system solved:\");\n            if (iInfo) delete iInfo, iInfo = NULL;\n        }\n    }\n\n    {\n        profiler.start();\n        double valueSum = 0, weightSum = 0;\n        typename FEMTree<Dim, Real>::template MultiThreadedEvaluator<Sigs, 0>\n                evaluator(&tree, solution);\n        std::vector<double> valueSums(ThreadPool::NumThreads(), 0),\n                weightSums(ThreadPool::NumThreads(), 0);\n        ThreadPool::Parallel_for(\n                0, samples.size(), [&](unsigned int thread, size_t j) {\n                    ProjectiveData<Point<Real, Dim>, Real>& sample =\n                            samples[j].sample;\n                    Real w = sample.weight;\n                    if (w > 0)\n                        weightSums[thread] += w,\n                                valueSums[thread] +=\n                                evaluator.values(sample.data / sample.weight,\n                                                 thread, samples[j].node)[0] *\n                                w;\n                });\n        for (size_t t = 0; t < valueSums.size(); t++)\n            valueSum += valueSums[t], weightSum += weightSums[t];\n        isoValue = (Real)(valueSum / weightSum);\n        profiler.dumpOutput(\"Got average:\");\n        utility::LogDebug(\"Iso-Value: {:e} = {:e} / {:e}\", isoValue, valueSum,\n                          weightSum);\n    }\n\n    auto SetVertex = [](Open3DVertex<Real>& v, Point<Real, Dim> p, Real w,\n                        Open3DData d) {\n        v.point = p;\n        v.normal_ = d.normal_;\n        v.color_ = d.color_;\n        v.w_ = w;\n    };\n    ExtractMesh<Open3DVertex<Real>, Real>(\n            datax, linear_fit, UIntPack<FEMSigs...>(),\n            std::tuple<SampleData...>(), tree, solution, isoValue, &samples,\n            &sampleData, density, SetVertex, iXForm, out_mesh, out_densities);\n\n    if (density) delete density, density = NULL;\n    utility::LogDebug(\"#          Total Solve: {:9.1f} (s), {:9.1f} (MB)\",\n                      Time() - startTime, FEMTree<Dim, Real>::MaxMemoryUsage());\n}\n\n}  // namespace poisson\n\nstd::tuple<std::shared_ptr<TriangleMesh>, std::vector<double>>\nTriangleMesh::CreateFromPointCloudPoisson(const PointCloud& pcd,\n                                          size_t depth,\n                                          size_t width,\n                                          float scale,\n                                          bool linear_fit) {\n    static const BoundaryType BType = poisson::DEFAULT_FEM_BOUNDARY;\n    typedef IsotropicUIntPack<\n            poisson::DIMENSION,\n            FEMDegreeAndBType</* Degree */ 1, BType>::Signature>\n            FEMSigs;\n\n    if (!pcd.HasNormals()) {\n        utility::LogError(\"[CreateFromPointCloudPoisson] pcd has no normals\");\n    }\n\n#ifdef _OPENMP\n    ThreadPool::Init((ThreadPool::ParallelType)(int)ThreadPool::OPEN_MP,\n                     std::thread::hardware_concurrency());\n#else\n    ThreadPool::Init((ThreadPool::ParallelType)(int)ThreadPool::THREAD_POOL,\n                     std::thread::hardware_concurrency());\n#endif\n\n    auto mesh = std::make_shared<TriangleMesh>();\n    std::vector<double> densities;\n    poisson::Execute<float>(pcd, mesh, densities, static_cast<int>(depth),\n                            width, scale, linear_fit, FEMSigs());\n\n    ThreadPool::Terminate();\n\n    return std::make_tuple(mesh, densities);\n}\n\n}  // namespace geometry\n}  // namespace open3d\n", "meta": {"hexsha": "edd2e55292ce34f23ab1ee8d63d4d226a49880cc", "size": 30185, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/open3d/geometry/SurfaceReconstructionPoisson.cpp", "max_stars_repo_name": "appliedinnovation/Open3D", "max_stars_repo_head_hexsha": "2c33a864fe1241f54a96f720b0f46ebd780c3d3d", "max_stars_repo_licenses": ["MIT"], "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/open3d/geometry/SurfaceReconstructionPoisson.cpp", "max_issues_repo_name": "appliedinnovation/Open3D", "max_issues_repo_head_hexsha": "2c33a864fe1241f54a96f720b0f46ebd780c3d3d", "max_issues_repo_licenses": ["MIT"], "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/open3d/geometry/SurfaceReconstructionPoisson.cpp", "max_forks_repo_name": "appliedinnovation/Open3D", "max_forks_repo_head_hexsha": "2c33a864fe1241f54a96f720b0f46ebd780c3d3d", "max_forks_repo_licenses": ["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.5091623037, "max_line_length": 80, "alphanum_fraction": 0.5247970846, "num_tokens": 6848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.29201275974412266}}
{"text": "#ifndef ODF_TRANSFORMATION_PROCESS_HPP\n#define ODF_TRANSFORMATION_PROCESS_HPP\n#include <boost/math/special_functions/sinc.hpp>\n#include \"basic_process.hpp\"\n#include \"basic_voxel.hpp\"\n\n\n#include \"mapping/fa_template.hpp\"\nextern fa_template fa_template_imp;\n\nclass ReadDWIData : public BaseProcess{\npublic:\n    virtual void init(Voxel&) {}\n    virtual void run(Voxel& voxel, VoxelData& data)\n    {\n        data.space.resize(voxel.dwi_data.size());\n        for (unsigned int index = 0; index < data.space.size(); ++index)\n            data.space[index] = voxel.dwi_data[index][data.voxel_index];\n    }\n    virtual void end(Voxel&,gz_mat_write&) {}\n};\n\n\nvoid calculate_shell(const std::vector<float>& sorted_bvalues,\n                     std::vector<unsigned int>& shell);\nclass BalanceScheme : public BaseProcess{\n    std::vector<float> trans;\n    unsigned int new_q_count;\n    unsigned int old_q_count;\nprivate:\n    Voxel* stored_voxel;\n    std::vector<image::vector<3,float> > old_bvectors;\n    std::vector<float> old_bvalues;\npublic:\n    BalanceScheme(void):stored_voxel(0){}\n\n    virtual void init(Voxel& voxel)\n    {\n        if(!voxel.scheme_balance)\n            return;\n        std::vector<unsigned int> shell;\n        calculate_shell(voxel.bvalues,shell);\n        unsigned int b_count = voxel.bvalues.size();\n        unsigned int total_signals = 0;\n\n        tessellated_icosahedron new_dir;\n        new_dir.init(6);\n\n        std::vector<image::vector<3,float> > new_bvectors;\n        std::vector<float> new_bvalues;\n\n        // if b0\n        if(voxel.bvalues.front() == 0.0)\n        {\n            trans.resize(b_count);\n            trans[0] = 1;\n            new_bvectors.resize(1);\n            new_bvalues.resize(1);\n            total_signals += 1;\n        }\n\n        for(unsigned int shell_index = 0;shell_index < shell.size();++shell_index)\n        {\n            unsigned int from = shell[shell_index];\n            unsigned int to = (shell_index + 1 == shell.size() ? b_count:shell[shell_index+1]);\n            unsigned int num = to-from;\n\n\n            //calculate averaged angle distance\n            double averaged_angle = 0.0;\n            for(unsigned int i = from;i < to;++i)\n            {\n                double max_cos = 0.0;\n                for(unsigned int j = from;j < to;++j)\n                {\n                    if(i == j)\n                        continue;\n                    double cur_cos = std::fabs(std::cos(voxel.bvectors[i]*voxel.bvectors[j]));\n                    if(cur_cos > 0.998)\n                        continue;\n                    max_cos = std::max<double>(max_cos,cur_cos);\n                }\n                averaged_angle += std::acos(max_cos);\n            }\n            averaged_angle /= num;\n\n            //calculate averaged b_value\n            double avg_b = image::mean(voxel.bvalues.begin()+from,voxel.bvalues.begin()+to);\n            unsigned int trans_old_size = trans.size();\n            trans.resize(trans.size() + new_dir.half_vertices_count*b_count);\n            for(unsigned int i = 0; i < new_dir.half_vertices_count;++i)\n            {\n                std::vector<double> t(b_count);\n                double effective_b = 0.0;\n                for(unsigned int j = from;j < to;++j)\n                {\n                    double angle = std::acos(std::min<double>(1.0,std::fabs(new_dir.vertices[i]*voxel.bvectors[j])));\n                    angle/=averaged_angle;\n                    t[j] = std::exp(-2.0*angle*angle); // if the angle == 1, then weighting = 0.135\n                    effective_b += t[j]*voxel.bvalues[j];\n                }\n                double sum_t = std::accumulate(t.begin(),t.end(),0.0);\n                image::multiply_constant(t,avg_b/1000.0/sum_t);\n                std::copy(t.begin(),t.end(),trans.begin() + trans_old_size + i * b_count);\n                new_bvalues.push_back(effective_b/sum_t);\n                new_bvectors.push_back(new_dir.vertices[i]);\n            }\n            total_signals += new_dir.half_vertices_count;\n        }\n\n        old_q_count = voxel.bvalues.size();\n        new_q_count = total_signals;\n        voxel.bvalues.swap(new_bvalues);\n        voxel.bvectors.swap(new_bvectors);\n        new_bvalues.swap(old_bvalues);\n        new_bvectors.swap(old_bvectors);\n        stored_voxel = &voxel;\n\n    }\n    virtual void run(Voxel& voxel, VoxelData& data)\n    {\n\n        if(!voxel.scheme_balance)\n            return;\n        if(stored_voxel)// restored btalbe here in case user terminate the recon\n        {\n            stored_voxel = 0;\n            voxel.bvalues = old_bvalues;\n            voxel.bvectors = old_bvectors;\n        }\n        std::vector<float> new_data(new_q_count);\n        data.space.swap(new_data);\n        image::mat::vector_product(trans.begin(),new_data.begin(),data.space.begin(),image::dyndim(new_q_count,old_q_count));\n    }\n};\n\nstruct GeneralizedFA\n{\n    float operator()(const std::vector<float>& odf)\n    {\n        float m1 = 0.0;\n        float m2 = 0.0;\n        std::vector<float>::const_iterator iter = odf.begin();\n        std::vector<float>::const_iterator end = odf.end();\n        for (;iter != end; ++iter)\n        {\n            float t = *iter;\n            m1 += t;\n            m2 += t*t;\n        }\n        m1 *= m1;\n        m1 /= ((float)odf.size());\n        if (m2 == 0.0)\n            return 0.0;\n        return std::sqrt(((float)odf.size())/((float)odf.size()-1.0)*(m2-m1)/m2);\n    }\n};\n\nconst unsigned int odf_block_size = 20000;\nstruct OutputODF : public BaseProcess\n{\nprotected:\n    std::vector<std::vector<float> > odf_data;\n    std::vector<unsigned int> odf_index_map;\npublic:\n    virtual void init(Voxel& voxel)\n    {\n        odf_data.clear();\n        if (voxel.need_odf)\n        {\n            unsigned int total_count = 0;\n            odf_index_map.resize(voxel.mask.size());\n            for (unsigned int index = 0;index < voxel.mask.size();++index)\n                if (voxel.mask[index])\n                {\n                    odf_index_map[index] = total_count;\n                    ++total_count;\n                }\n            try\n            {\n                std::vector<unsigned int> size_list;\n                while (1)\n                {\n\n                    if (total_count > odf_block_size)\n                    {\n                        size_list.push_back(odf_block_size);\n                        total_count -= odf_block_size;\n                    }\n                    else\n                    {\n                        size_list.push_back(total_count);\n                        break;\n                    }\n                }\n                odf_data.resize(size_list.size());\n                for (unsigned int index = 0;index < odf_data.size();++index)\n                    odf_data[index].resize(size_list[index]*(voxel.ti.half_vertices_count));\n            }\n            catch (...)\n            {\n                odf_data.clear();\n                throw std::runtime_error(\"Memory not enough for creating an ODF containing fib file.\");\n            }\n        }\n\n    }\n    virtual void run(Voxel& voxel,VoxelData& data)\n    {\n\n        if (voxel.need_odf && data.fa[0] + 1.0 != 1.0)\n        {\n            unsigned int odf_index = odf_index_map[data.voxel_index];\n            std::copy(data.odf.begin(),data.odf.end(),\n                      odf_data[odf_index/odf_block_size].begin() + (odf_index%odf_block_size)*(voxel.ti.half_vertices_count));\n        }\n\n    }\n    virtual void end(Voxel& voxel,gz_mat_write& mat_writer)\n    {\n\n        if (!voxel.need_odf)\n            return;\n        {\n            set_title(\"output odfs\");\n            for (unsigned int index = 0;index < odf_data.size();++index)\n            {\n                if (!voxel.odf_deconvolusion)\n                    image::divide_constant(odf_data[index],voxel.z0);\n                std::ostringstream out;\n                out << \"odf\" << index;\n                mat_writer.write(out.str().c_str(),&*odf_data[index].begin(),\n                                      voxel.ti.half_vertices_count,\n                                      odf_data[index].size()/(voxel.ti.half_vertices_count));\n            }\n            odf_data.clear();\n        }\n\n    }\n};\n\n\nstruct ODFLoader : public BaseProcess\n{\n    std::vector<unsigned int> index_mapping1;\n    std::vector<unsigned int> index_mapping2;\npublic:\n    virtual void init(Voxel& voxel)\n    {\n        //voxel.qa_scaling must be 1\n        voxel.z0 = 0.0;\n        index_mapping1.resize(voxel.mask.size());\n        index_mapping2.resize(voxel.mask.size());\n        int voxel_index = 0;\n        for(unsigned int i = 0;i < voxel.template_odfs.size();++i)\n        {\n            for(unsigned int j = 0;j < voxel.template_odfs[i].size();j += voxel.ti.half_vertices_count)\n            {\n                int k_end = j + voxel.ti.half_vertices_count;\n                bool is_odf_zero = true;\n                for(int k = j;k < k_end;++k)\n                    if(voxel.template_odfs[i][k] != 0.0)\n                    {\n                        is_odf_zero = false;\n                        break;\n                    }\n                if(!is_odf_zero)\n                    for(;voxel_index < index_mapping1.size();++voxel_index)\n                        if(voxel.mask[voxel_index] != 0)\n                            break;\n                if(voxel_index >= index_mapping1.size())\n                    break;\n                index_mapping1[voxel_index] = i;\n                index_mapping2[voxel_index] = j;\n                ++voxel_index;\n            }\n        }\n    }\n    virtual void run(Voxel& voxel, VoxelData& data)\n    {\n        int cur_index = data.voxel_index;\n        std::copy(voxel.template_odfs[index_mapping1[cur_index]].begin() +\n                  index_mapping2[cur_index],\n                  voxel.template_odfs[index_mapping1[cur_index]].begin() +\n                  index_mapping2[cur_index]+data.odf.size(),data.odf.begin());\n\n    }\n    virtual void end(Voxel& voxel,gz_mat_write& mat_writer)\n    {\n        if (voxel.need_odf)\n        {\n            set_title(\"output odfs\");\n            for (unsigned int index = 0;index < voxel.template_odfs.size();++index)\n            {\n                std::ostringstream out;\n                out << \"odf\" << index;\n                mat_writer.write(out.str().c_str(),&*voxel.template_odfs[index].begin(),\n                                      voxel.ti.half_vertices_count,\n                                      voxel.template_odfs[index].size()/(voxel.ti.half_vertices_count));\n            }\n        }\n        mat_writer.write(\"trans\",&*voxel.param,4,4);\n    }\n};\n\n// for normalization\nclass RecordQA  : public BaseProcess\n{\npublic:\n    virtual void init(Voxel& voxel)\n    {\n        voxel.qa_map.resize(voxel.dim);\n        std::fill(voxel.qa_map.begin(),voxel.qa_map.end(),0.0);\n    }\n    virtual void run(Voxel& voxel, VoxelData& data)\n    {\n        voxel.qa_map[data.voxel_index] = data.fa[0];\n    }\n    virtual void end(Voxel&,gz_mat_write&)\n    {\n\n    }\n};\n\ndouble base_function(double theta);\nstruct SaveFA : public BaseProcess\n{\nprotected:\n    std::vector<float> iso,gfa;\n    std::vector<std::vector<float> > fa;\n    std::vector<std::vector<float> > rdi;\nprotected:\n    float z0;\npublic:\n    virtual void init(Voxel& voxel)\n    {\n\n        fa.resize(voxel.max_fiber_number);\n        for (unsigned int index = 0;index < voxel.max_fiber_number;++index)\n            fa[index].resize(voxel.dim.size());\n        gfa.clear();\n        gfa.resize(voxel.dim.size());\n        iso.clear();\n        iso.resize(voxel.dim.size());\n        if(voxel.output_rdi)\n        {\n            float sigma = voxel.param[0]; //optimal 1.24\n            for(float L = 0.2f;L <= sigma;L+= 0.2f)\n            {\n                rdi.push_back(std::vector<float>());\n                rdi.back().resize(voxel.dim.size());\n            }\n        }\n        if(voxel.csf_calibration)\n        {\n            std::vector<unsigned short> data(voxel.dwi_data[0],voxel.dwi_data[0]+voxel.dim.size());\n            std::sort(data.begin(),data.end());\n            // CSF selected at 125,000 mm^3\n            int size = 125000.0f/(voxel.vs[0]*voxel.vs[1]*voxel.vs[2]);\n            float water_b0 = *(data.end()-size);\n\n            float sigma = voxel.param[0]; //optimal 1.24\n            // numerically estimate free water ODF\n            unsigned int odf_size = voxel.ti.half_vertices_count;\n            std::vector<float> dwi(voxel.bvalues.size()),odf(odf_size);\n            for(int i = 0;i < dwi.size();++i)\n                dwi[i] = water_b0*std::exp(-voxel.bvalues[i]*0.003f); // free water diffusivity\n\n            std::vector<float> sinc_ql(odf_size*voxel.bvalues.size());\n            // calculate reconstruction matrix\n            for (unsigned int j = 0,index = 0; j < odf_size; ++j)\n                for (unsigned int i = 0; i < voxel.bvalues.size(); ++i,++index)\n                    sinc_ql[index] = voxel.bvectors[i]*\n                                 image::vector<3,float>(voxel.ti.vertices[j])*\n                                   std::sqrt(voxel.bvalues[i]*0.01506);\n\n            for (unsigned int index = 0; index < sinc_ql.size(); ++index)\n                sinc_ql[index] = voxel.r2_weighted ?\n                             base_function(sinc_ql[index]*sigma):\n                             boost::math::sinc_pi(sinc_ql[index]*sigma);\n\n            image::mat::vector_product(&*sinc_ql.begin(),&*dwi.begin(),&*odf.begin(),\n                                    image::dyndim(odf.size(),dwi.size()));\n            z0 = image::mean(odf.begin(),odf.end());\n        }\n\n    }\n    virtual void run(Voxel& voxel, VoxelData& data)\n    {\n        iso[data.voxel_index] = data.min_odf;\n        gfa[data.voxel_index] = GeneralizedFA()(data.odf);\n        for (unsigned int index = 0;index < voxel.max_fiber_number;++index)\n            fa[index][data.voxel_index] = data.fa[index];\n        if(voxel.output_rdi)\n            for (unsigned int index = 0;index < data.rdi.size();++index)\n                rdi[index][data.voxel_index] = data.rdi[index];\n    }\n    virtual void end(Voxel& voxel,gz_mat_write& mat_writer)\n    {\n        set_title(\"output data\");\n        mat_writer.write(\"gfa\",&*gfa.begin(),1,gfa.size());\n        if(voxel.csf_calibration)\n            voxel.z0 = z0;\n        if(voxel.z0 + 1.0 == 1.0)\n            voxel.z0 = 1.0;\n        mat_writer.write(\"z0\",&voxel.z0,1,1);\n\n        image::divide_constant(iso,voxel.z0);\n        mat_writer.write(\"iso\",&*iso.begin(),1,iso.size());\n\n        for (unsigned int index = 0;index < voxel.max_fiber_number;++index)\n        {\n            image::divide_constant(fa[index],voxel.z0);\n            std::ostringstream out;\n            out << index;\n            std::string num = out.str();\n            std::string fa_str = \"fa\";\n            fa_str += num;\n            set_title(fa_str.c_str());\n            mat_writer.write(fa_str.c_str(),&*fa[index].begin(),1,fa[index].size());\n        }\n\n        // output normalized qa\n        {\n            float max_qa = 0.0;\n            for (unsigned int i = 0;i < voxel.max_fiber_number;++i)\n                max_qa = std::max<float>(*std::max_element(fa[i].begin(),fa[i].end()),max_qa);\n\n            if(max_qa != 0.0)\n            for (unsigned int index = 0;index < voxel.max_fiber_number;++index)\n            {\n                image::divide_constant(fa[index],max_qa);\n                std::ostringstream out;\n                out << index;\n                std::string num = out.str();\n                std::string fa_str = \"nqa\";\n                fa_str += num;\n                set_title(fa_str.c_str());\n                mat_writer.write(fa_str.c_str(),&*fa[index].begin(),1,fa[index].size());\n            }\n        }\n\n        if(voxel.output_rdi)\n        {\n            for(unsigned int i = 0;i < rdi.size();++i)\n                image::divide_constant(rdi[i],voxel.z0);\n            float L = 0.2f;\n            for(unsigned int i = 0;i < rdi.size();++i,L += 0.2f)\n            {\n                std::ostringstream out;\n                out.precision(2);\n                out << \"rdi\" << std::setfill('0') << std::setw(2) << int(L*10) << \"L\";\n                mat_writer.write(out.str().c_str(),&*rdi[i].begin(),1,rdi[i].size());\n            }\n            for(unsigned int i = 0;i < rdi[0].size();++i)\n            for(unsigned int j = 0;j < rdi.size();++j)\n                rdi[j][i] = rdi[rdi.size()-1][i]-rdi[j][i];\n            L = 0.2f;\n            for(unsigned int i = 0;i < rdi.size();++i,L += 0.2f)\n            {\n                std::ostringstream out2;\n                out2.precision(2);\n                out2 << \"nrdi\" << std::setfill('0') << std::setw(2) << int(L*10) << \"L\";\n                mat_writer.write(out2.str().c_str(),&*rdi[i].begin(),1,rdi[i].size());\n            }\n        }\n    }\n};\n\n\n\nstruct SaveDirIndex : public BaseProcess\n{\nprotected:\n    std::vector<std::vector<short> > findex;\npublic:\n    virtual void init(Voxel& voxel)\n    {\n\n        findex.resize(voxel.max_fiber_number);\n        for (unsigned int index = 0;index < voxel.max_fiber_number;++index)\n            findex[index].resize(voxel.dim.size());\n    }\n    virtual void run(Voxel& voxel, VoxelData& data)\n    {\n\n        for (unsigned int index = 0;index < voxel.max_fiber_number;++index)\n            findex[index][data.voxel_index] = data.dir_index[index];\n    }\n    virtual void end(Voxel& voxel,gz_mat_write& mat_writer)\n    {\n        for (unsigned int index = 0;index < voxel.max_fiber_number;++index)\n        {\n            std::ostringstream out;\n            out << index;\n            std::string num = out.str();\n            std::string index_str = \"index\";\n            index_str += num;\n            set_title(index_str.c_str());\n            mat_writer.write(index_str.c_str(),&*findex[index].begin(),1,findex[index].size());\n        }\n    }\n};\n\n\nstruct SaveDir : public BaseProcess\n{\nprotected:\n    std::vector<std::vector<float> > dir;\npublic:\n    virtual void init(Voxel& voxel)\n    {\n\n        dir.resize(voxel.max_fiber_number);\n        for (unsigned int index = 0;index < voxel.max_fiber_number;++index)\n            dir[index].resize(voxel.dim.size()*3);\n    }\n    virtual void run(Voxel& voxel, VoxelData& data)\n    {\n\n        unsigned int dir_index = data.voxel_index;\n        for (unsigned int index = 0;index < voxel.max_fiber_number;++index)\n            std::copy(data.dir[index].begin(),data.dir[index].end(),dir[index].begin() + dir_index + dir_index + dir_index);\n    }\n    virtual void end(Voxel& voxel,gz_mat_write& mat_writer)\n    {\n        for (unsigned int index = 0;index < voxel.max_fiber_number;++index)\n        {\n            std::ostringstream out;\n            out << index;\n            std::string num = out.str();\n            std::string index_str = \"dir\";\n            index_str += num;\n            set_title(index_str.c_str());\n            mat_writer.write(index_str.c_str(),&*dir[index].begin(),1,dir[index].size());\n        }\n    }\n};\n\n\n\n\nstruct SearchLocalMaximum\n{\n    std::vector<std::vector<unsigned short> > neighbor;\n    std::map<float,unsigned short,std::greater<float> > max_table;\n    void init(Voxel& voxel)\n    {\n\n        unsigned int half_odf_size = voxel.ti.half_vertices_count;\n        unsigned int faces_count = voxel.ti.faces.size();\n        neighbor.resize(voxel.ti.half_vertices_count);\n        for (unsigned int index = 0;index < faces_count;++index)\n        {\n            short i1 = voxel.ti.faces[index][0];\n            short i2 = voxel.ti.faces[index][1];\n            short i3 = voxel.ti.faces[index][2];\n            if (i1 >= half_odf_size)\n                i1 -= half_odf_size;\n            if (i2 >= half_odf_size)\n                i2 -= half_odf_size;\n            if (i3 >= half_odf_size)\n                i3 -= half_odf_size;\n            neighbor[i1].push_back(i2);\n            neighbor[i1].push_back(i3);\n            neighbor[i2].push_back(i1);\n            neighbor[i2].push_back(i3);\n            neighbor[i3].push_back(i1);\n            neighbor[i3].push_back(i2);\n        }\n    }\n    void search(const std::vector<float>& old_odf)\n    {\n        max_table.clear();\n        for (unsigned int index = 0;index < neighbor.size();++index)\n        {\n            float value = old_odf[index];\n            bool is_max = true;\n            std::vector<unsigned short>& nei = neighbor[index];\n            for (unsigned int j = 0;j < nei.size();++j)\n            {\n                if (value < old_odf[nei[j]])\n                {\n                    is_max = false;\n                    break;\n                }\n            }\n            if (is_max)\n                max_table[value] = (unsigned short)index;\n        }\n    }\n};\n\n\nstruct DetermineFiberDirections : public BaseProcess\n{\n    SearchLocalMaximum lm;\n    std::mutex mutex;\npublic:\n    virtual void init(Voxel& voxel)\n    {\n        lm.init(voxel);\n    }\n\n    virtual void run(Voxel& voxel,VoxelData& data)\n    {\n        data.min_odf = *std::min_element(data.odf.begin(),data.odf.end());\n        std::lock_guard<std::mutex> lock(mutex);\n        lm.search(data.odf);\n        std::map<float,unsigned short,std::greater<float> >::const_iterator iter = lm.max_table.begin();\n        std::map<float,unsigned short,std::greater<float> >::const_iterator end = lm.max_table.end();\n        for (unsigned int index = 0;iter != end && index < voxel.max_fiber_number;++index,++iter)\n        {\n            data.dir_index[index] = iter->second;\n            data.fa[index] = iter->first - data.min_odf;\n        }\n    }\n};\n\nstruct ScaleZ0ToMinODF : public BaseProcess\n{\n    float max_min_odf;\npublic:\n    virtual void init(Voxel& voxel)\n    {\n        voxel.z0 = 0.0;\n    }\n\n    virtual void run(Voxel& voxel,VoxelData& data)\n    {\n        if(data.min_odf > voxel.z0)\n            voxel.z0 = data.min_odf;\n    }\n};\n\n\n\n\n#endif//ODF_TRANSFORMATION_PROCESS_HPP\n", "meta": {"hexsha": "655d1f8cb67ffcba0f117d03dcf5ecc09f92e57f", "size": 21723, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/dsi/odf_process.hpp", "max_stars_repo_name": "cbutakoff/DSI-Studio", "max_stars_repo_head_hexsha": "d77dffa4526d66da421fa84f7187e85bca6bce7c", "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/dsi/odf_process.hpp", "max_issues_repo_name": "cbutakoff/DSI-Studio", "max_issues_repo_head_hexsha": "d77dffa4526d66da421fa84f7187e85bca6bce7c", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/dsi/odf_process.hpp", "max_forks_repo_name": "cbutakoff/DSI-Studio", "max_forks_repo_head_hexsha": "d77dffa4526d66da421fa84f7187e85bca6bce7c", "max_forks_repo_licenses": ["BSD-3-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.9421875, "max_line_length": 126, "alphanum_fraction": 0.530129356, "num_tokens": 5341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.29177949564392064}}
{"text": "/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */\n/*                                                                  */\n/*                      Early Plume Microphysics                    */\n/*                              (EPM)                               */\n/*                                                                  */\n/* Integrate Header File                                            */\n/*                                                                  */\n/* Author               : Thibaud M. Fritz                          */\n/* Time                 : 9/27/2018                                 */\n/* File                 : Integrate.hpp                             */\n/*                                                                  */\n/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */\n\n#ifndef INTEGRATE_H_INCLUDED\n#define INTEGRATE_H_INCLUDED\n\n#include <iostream>\n#include <cmath>\n#include <vector>\n#include <boost/array.hpp>\n#include <boost/numeric/odeint.hpp>\n#include \"omp.h\"\n\n#include \"Util/ForwardDecl.hpp\"\n#include \"Util/PhysConstant.hpp\"\n#include \"Util/PhysFunction.hpp\"\n#include \"Core/Interface.hpp\"\n#include \"Core/Parameters.hpp\"\n#include \"Core/Monitor.hpp\"\n#include \"Core/Aircraft.hpp\"\n#include \"Core/Emission.hpp\"\n#include \"AIM/Coagulation.hpp\"\n#include \"AIM/Nucleation.hpp\"\n#include \"AIM/Aerosol.hpp\"\n#include \"odeSolver.hpp\"\n\nnamespace EPM\n{\n\n    static const int EPM_SUCCESS = 1;\n    static const int EPM_FAILURE = 0;\n\n    /* Vortex sinking timescales, taken from Unterstrasser et al., 2008 */\n    const RealDouble t_Vortex_0 = 8.00E+00;\n    const RealDouble t_Vortex_1 = 1.10E+02;\n\n    /* Dilution timescales for a B747, taken from:\n     * B. Kärcher, \"A trajectory box model for aircraft exhaust plumes\", Journal of Geophysical Research, 1995 */\n    const RealDouble t_0 = 1.00E-04; /* [s] */\n    const RealDouble t_j = 1.00E-02; /* [s] */\n    const RealDouble t_1 = 8.00E+00; /* [s] */\n    const RealDouble t_2 = 6.60E+01; /* [s] */\n   \n    const RealDouble m = 2.0;\n    const RealDouble n = 50.0;\n    const RealDouble Cv = 3.0;\n    \n    /* Engine exit plane characteristics for a B747, taken from:\n     * B. Kärcher, \"A trajectory box model for aircraft exhaust plumes\", Journal of Geophysical Research, 1995 */\n    /* Engine exit core area im m^2 */\n    const RealDouble Ac0 = 0.604;\n    /* Engine exit core velocity in m/s */\n    const RealDouble uc0 = 475.7;\n    /* Engine exit core temperature in K */\n    /* const RealDouble Tc0 = 547.3; */\n    /* RealDouble Tc0 */\n    /* Engine exit bypass area in m^2 */\n    /* const RealDouble Ab0 = 1.804; */\n    /* RealDouble Ab0 */\n\n    int Integrate( RealDouble &temperature_K, RealDouble pressure_Pa, RealDouble relHumidity_w, RealDouble varArray[], \\\n                   RealDouble fixArray[], RealDouble aerArray[][2], const Aircraft &AC, const Emission &EI, \\\n                   RealDouble &Ice_rad, RealDouble &Ice_den, RealDouble &Soot_den, RealDouble &H2O_mol, \\\n                   RealDouble &SO4g_mol, RealDouble &SO4l_mol, AIM::Aerosol &SO4Aer, AIM::Aerosol &IceAer, \\\n                   RealDouble &Area, RealDouble &Ab0, RealDouble &Tc0, const bool CHEMISTRY );\n    int RunMicrophysics( RealDouble &temperature_K, RealDouble pressure_Pa, RealDouble relHumidity_w, \\\n                         RealDouble varArray[], RealDouble fixArray[], RealDouble aerArray[][2], \\\n                         const Aircraft &AC, const Emission &EI, RealDouble delta_T_ad, RealDouble delta_T, \\\n                         RealDouble &Ice_rad, RealDouble &Ice_den, RealDouble &Soot_den, RealDouble &H2O_mol, \\\n                         RealDouble &SO4g_mol, RealDouble &SO4l_mol, AIM::Aerosol &SO4Aer, AIM::Aerosol &IceAer, \\\n                         RealDouble &Area, RealDouble &Ab0, RealDouble &Tc0, const bool CHEMISTRY );\n    RealDouble dT_Vortex( const RealDouble time, const RealDouble delta_T, bool deriv = 0 );\n    RealDouble dilutionRatio( const RealDouble time );\n    RealDouble depositionRate( const RealDouble r, const RealDouble T, const RealDouble P, const RealDouble H2O, \\\n                               const RealDouble r_0,  const RealDouble theta );\n    void odeRHS( const Vector_1D &x, Vector_1D &dxdt, const RealDouble t = 0.0 );\n    bool isFreezable( const RealDouble r, const RealDouble T, const RealDouble H2O, const RealDouble r0 );\n    RealDouble condensationRate( const RealDouble r, const RealDouble T, const RealDouble P, const RealDouble H2O, \\\n                                 const RealDouble theta );\n\n\n}\n\n\n#endif /* INTEGRATE_H_INCLUDED */\n", "meta": {"hexsha": "d1f609f81c244130cdf11a02000533ee56ffe530", "size": 4594, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Code.v05-00/include/EPM/Integrate.hpp", "max_stars_repo_name": "MIT-LAE/APCEMM", "max_stars_repo_head_hexsha": "2954bca64ec1c13552830d467d404dbe627ef71a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-03-21T20:49:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T17:25:31.000Z", "max_issues_repo_path": "Code.v05-00/include/EPM/Integrate.hpp", "max_issues_repo_name": "MIT-LAE/APCEMM", "max_issues_repo_head_hexsha": "2954bca64ec1c13552830d467d404dbe627ef71a", "max_issues_repo_licenses": ["MIT"], "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.v05-00/include/EPM/Integrate.hpp", "max_forks_repo_name": "MIT-LAE/APCEMM", "max_forks_repo_head_hexsha": "2954bca64ec1c13552830d467d404dbe627ef71a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-21T20:50:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T20:50:50.000Z", "avg_line_length": 47.8541666667, "max_line_length": 120, "alphanum_fraction": 0.5635611667, "num_tokens": 1124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723316860482762, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2917794899453057}}
{"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_PCHIP_HPP_INCLUDED\n#define NT2_TOOLBOX_INTERPOL_FUNCTIONS_GENERIC_PCHIP_HPP_INCLUDED\n\n#include <nt2/toolbox/interpol/functions/pchip.hpp>\n#include <nt2/include/functions/ppval.hpp>\n#include <nt2/include/functions/is_nge.hpp>\n#include <nt2/include/functions/is_nle.hpp>\n#include <nt2/include/functions/issorted.hpp>\n#include <nt2/include/functions/bsearch.hpp>\n#include <nt2/include/functions/diff.hpp>\n#include <nt2/include/functions/conj.hpp>\n#include <nt2/include/functions/abs.hpp>\n#include <nt2/include/functions/globalfind.hpp>\n#include <nt2/include/functions/if_else.hpp>\n#include <nt2/include/functions/is_gtz.hpp>\n#include <nt2/include/functions/fma.hpp>\n#include <nt2/include/functions/logical_or.hpp>\n#include <nt2/include/functions/zeros.hpp>\n#include <nt2/include/functions/oneminus.hpp>\n#include <nt2/include/functions/oneplus.hpp>\n#include <nt2/include/functions/repnum.hpp>\n#include <nt2/include/functions/width.hpp>\n#include <nt2/include/functions/average.hpp>\n#include <nt2/include/functions/first_index.hpp>\n#include <nt2/include/functions/isreal.hpp>\n#include <nt2/include/functions/colvect.hpp>\n#include <nt2/include/functions/rowvect.hpp>\n#include <nt2/include/functions/transpose.hpp>\n#include <nt2/include/functions/reshape.hpp>\n#include <nt2/include/functions/vertcat.hpp>\n#include <nt2/include/functions/multiplies.hpp>\n#include <nt2/include/functions/logical_and.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/include/constants/three.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/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::pchip_,N1,nt2::container::domain>))\n                            )\n  {\n    typedef typename boost::proto::result_of::child_c<A1&,0>::value_type  child0;\n    typedef typename boost::proto::result_of::child_c<A1&,1>::value_type  child1;\n    typedef typename boost::proto::result_of::child_c<A1&,2>::value_type  child2;\n    typedef typename child0::value_type                               value_type;\n    typedef typename meta::as_integer<value_type>::type               index_type;\n    typedef table<value_type>                                             vtab_t;\n    typedef table<index_type>                                             itab_t;\n    typedef A0&                                                      result_type;\n\n\n    result_type operator()(A0& yi, A1& inputs) const\n    {\n      yi.resize(inputs.extent());\n      const child0 & x   =  boost::proto::child_c<0>(inputs);\n      BOOST_ASSERT_MSG(issorted(x, 'a'), \"for 'pchip' interpolation x values must be sorted in ascending order\");\n      const child1 & y   =  boost::proto::child_c<1>(inputs);\n      const child2 & xi  =  boost::proto::child_c<2>(inputs);\n      bool extrap = false;\n      value_type extrapval = Nan<value_type>();\n      choices(inputs, extrap, extrapval, N1());\n      vtab_t h  =  nt2::diff(x,1,2);\n      vtab_t del = nt2::diff(y,1,2)/h;\n      pchipslopes(x,y,del, yi);\n      ppval <value_type> pp(x,y,yi,h,del);\n      yi =pp.eval(xi);\n      if (!extrap)\n      {\n        value_type  b =  value_type(x(begin_));\n        value_type  e =  value_type(x(end_));\n        yi = nt2::if_else(nt2::logical_or(boost::simd::is_nge(xi, b),\n                                          boost::simd::is_nle(xi, e)), extrapval, yi);\n      }\n      return yi;\n    }\n  private :\n    static void choices(const A1&, bool &,  value_type&, boost::mpl::long_<3> const &)\n    { }\n    static void choices(const A1& inputs, bool & extrap,  value_type& extrapval, 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, extrapval, param_type());\n    }\n    static void get(const A1& inputs, bool & extrap,  value_type&,  const bool &)\n    {\n      extrap =  boost::proto::child_c<3>(inputs);\n    }\n    static void get(const A1& inputs, bool &,  value_type& extrapval,  const value_type &)\n    {\n      extrapval =  boost::proto::child_c<3>(inputs);\n    }\n\n    static void pchipslopes(const child0 & x, const child1 & y, const vtab_t &del, A0& d)\n    {\n      itab_t k;\n      size_t n =  length(x);\n      if (nt2::numel(x) == 2) {\n        d =  nt2::repnum(value_type(del(begin_)), 1, width(y)); // del(begin_) is not of value_type !\n      } else {\n        d =  nt2::zeros(1, width(y), nt2::meta::as_<value_type>());\n        if (/* nt2::isreal(del)*/ true) //to do proper version for real types\n        { // is k 1 based or 0,  I hope 1 here ?\n          k = nt2::globalfind(nt2::is_gtz(nt2::multiplies(nt2::sign(del(nt2::_(begin_, begin_+n-3))), nt2::sign(del(nt2::_(begin_+1, begin_+n-2))))), nt2::meta::as_<index_type>());\n        }\n        else\n        {\n          k = nt2::globalfind(nt2::logical_and(is_eqz(del(nt2::_(begin_, begin_+n-3))), is_eqz(del(nt2::_(begin_+1,begin_+n-2)))), nt2::meta::as_<index_type>());\n        }\n      }\n      itab_t kp1 = oneplus(k);\n      itab_t kp2 = oneplus(kp1);\n      vtab_t h = nt2::diff(x, 1, 2);\n      vtab_t hs = h(1, k)+h(1, kp1);\n      vtab_t w1 = (h(1, k)+hs)/(Three<value_type>()*hs);\n      vtab_t w2 = (hs+h(1, kp1))/(Three<value_type>()*hs);\n      vtab_t dmax = nt2::max(nt2::abs(del(1, k)), nt2::abs(del(1, kp1)));\n      vtab_t dmin = nt2::min(nt2::abs(del(1, k)), nt2::abs(del(1, kp1)));\n      d(kp1) = dmin/nt2::conj(nt2::multiplies(w1,(del(1, k)/dmax)) + nt2::multiplies(w2, (del(1, kp1)/dmax)));\n      //   Slopes at end points.\n      //   Set d(0) and d(n-1) via non-centered, shape-preserving three-point formulae.\n      d(1) = ((2*h(1)+h(2))*del(1) - h(1)*del(2))/(h(1)+h(2));\n      if (/*nt2::isreal(d) && */(nt2::sign(d(nt2::first_index<1>(d))) != nt2::sign(del(1))))\n      {\n        d(nt2::first_index<2>(d)) = Zero<value_type>();\n      }\n      else if ((nt2::sign(del(1)) != nt2::sign(del(1))) &&\n               (nt2::abs(d(nt2::first_index<1>(d))) > nt2::abs(Three<value_type>()*del(1))))\n      {\n        d(nt2::first_index<2>(d)) = Three<value_type>()*del(1);\n      }\n      //      index_type end = n;\n      //     NT2_DISPLAY(h);\n      d(nt2::last_index<2>(d)) = ((Two<value_type>()*h(n-1)+h(n-2))*del(n-1) - h(n-1)*del(n-2))/(h(n-1)+h(n-2));\n      if (/*isreal(d) &&*/ (nt2::sign(d(nt2::last_index<1>(d))) != nt2::sign(del(n-1))))\n      {\n        d(nt2::last_index<2>(d)) = Zero<value_type>();\n      }\n      else if ((nt2::sign(del(n-1)) != nt2::sign(del(n-2))) &&\n               (nt2::abs(d(nt2::last_index<1>(d))) > nt2::abs(Three<value_type>()*del(n-1))))\n      {\n        d(nt2::last_index<2>(d)) = 3*del(n-1);\n      }\n    }\n  };\n} }\n\n\n#endif\n", "meta": {"hexsha": "ebf7488062d6c09848d2df0cf647143c22993b0f", "size": 7550, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/interpol/include/nt2/toolbox/interpol/functions/generic/pchip.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/pchip.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/pchip.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": 45.4819277108, "max_line_length": 180, "alphanum_fraction": 0.5856953642, "num_tokens": 2195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.29177495013178073}}
{"text": "/**  \\file posterior_mcmc.hpp \\brief Posterior distribution on GPs\n     based on MCMC over kernel parameters */\n/*\n-------------------------------------------------------------------------\n   This file is part of BayesOpt, an efficient C++ library for \n   Bayesian optimization.\n\n   Copyright (C) 2011-2015 Ruben Martinez-Cantin <rmcantin@unizar.es>\n \n   BayesOpt is free software: you can redistribute it and/or modify it \n   under the terms of the GNU Affero General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   BayesOpt is distributed in the hope that it will be useful, but \n   WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU Affero General Public License for more details.\n\n   You should have received a copy of the GNU Affero General Public License\n   along with BayesOpt.  If not, see <http://www.gnu.org/licenses/>.\n------------------------------------------------------------------------\n*/\n\n\n#ifndef  _POSTERIOR_MCMC_HPP_\n#define  _POSTERIOR_MCMC_HPP_\n\n#include <boost/ptr_container/ptr_vector.hpp>\n#include \"criteria_functors.hpp\"\n#include \"posteriormodel.hpp\"\n#include \"mcmc_sampler.hpp\"\n\nnamespace bayesopt {\n\n\n  /**\n   * \\brief Posterior model of nonparametric processes/criteria based\n   * on MCMC samples.\n   *\n   * For computational reasons we store a copy of each conditional\n   * models with the corresponding particle generated by MCMC. That is\n   * to avoid costly operations like matrix inversions for every\n   * kernel parameter in a GP prediction. Thus, we assume that the\n   * number of particles is not very large.\n   */\n  class MCMCModel: public PosteriorModel\n  {\n  public:\n\n    typedef boost::ptr_vector<NonParametricProcess>  GPVect;\n    typedef boost::ptr_vector<Criteria>  CritVect;\n\n    /** \n     * \\brief Constructor (Note: default constructor is private)\n     * \n     * @param dim number of input dimensions\n     * @param params configuration parameters (see parameters.hpp)\n     * @param eng random number generation engine (boost)\n     */\n    MCMCModel(size_t dim, Parameters params, randEngine& eng);\n\n    virtual ~MCMCModel();\n\n    void updateHyperParameters();\n    void fitSurrogateModel();\n    void updateSurrogateModel();\n\n    double evaluateCriteria(const vectord& query);\n    void updateCriteria(const vectord& query);\n\n    bool criteriaRequiresComparison();\n    void setFirstCriterium();\n    bool setNextCriterium(const vectord& prevResult);\n    std::string getBestCriteria(vectord& best);\n\n    ProbabilityDistribution* getPrediction(const vectord& query);\n   \n  private:\n    void setSurrogateModel(randEngine& eng);    \n    void setCriteria(randEngine& eng);\n\n  private:  // Members\n    size_t nParticles;\n    GPVect mGP;                ///< Pointer to surrogate model\n    CritVect mCrit;                    ///< Metacriteria model\n\n    boost::scoped_ptr<MCMCSampler> kSampler;\n\n  private: //Forbidden\n    MCMCModel();\n    MCMCModel(MCMCModel& copy);\n  };\n\n  /**@}*/\n\n  inline void MCMCModel::fitSurrogateModel()\n  { \n    for(GPVect::iterator it=mGP.begin(); it != mGP.end(); ++it)\n      it->fitSurrogateModel(); \n  };\n\n  inline void MCMCModel::updateSurrogateModel()\n  {     \n    for(GPVect::iterator it=mGP.begin(); it != mGP.end(); ++it)\n      it->updateSurrogateModel(); \n  };\n\n  inline double MCMCModel::evaluateCriteria(const vectord& query)\n  { \n    double sum = 0.0;\n    for(CritVect::iterator it=mCrit.begin(); it != mCrit.end(); ++it)\n      {\n\tsum += it->evaluate(query); \n      }\n    return sum/static_cast<double>(nParticles);\n  };\n\n  inline void MCMCModel::updateCriteria(const vectord& query)\n  { \n    for(CritVect::iterator it=mCrit.begin(); it != mCrit.end(); ++it)\n      {\n\tit->update(query); \n      }\n  };\n\n\n  inline bool MCMCModel::criteriaRequiresComparison()\n  {return mCrit[0].requireComparison(); };\n    \n  inline void MCMCModel::setFirstCriterium()\n  { \n    for(CritVect::iterator it=mCrit.begin(); it != mCrit.end(); ++it)\n      {\n\tit->initialCriteria();\n      }\n  };\n\n  // Although we change the criteria for all MCMC particles, we use\n  // only the first element to compute de Hedge algorithm, because it\n  // should be based on the average result, thus being common for all\n  // the particles.\n  inline bool MCMCModel::setNextCriterium(const vectord& prevResult)\n  { \n    bool rotated;\n    mCrit[0].pushResult(prevResult);\n    for(CritVect::iterator it=mCrit.begin(); it != mCrit.end(); ++it)\n      {\n\trotated = it->rotateCriteria();\n      }\n    return rotated; \n  };\n\n  inline std::string MCMCModel::getBestCriteria(vectord& best)\n  { return mCrit[0].getBestCriteria(best); };\n\n  inline \n  ProbabilityDistribution* MCMCModel::getPrediction(const vectord& query)\n  { return mGP[0].prediction(query); };\n\n\n\n} //namespace bayesopt\n\n\n#endif\n", "meta": {"hexsha": "9bf411ae2e4b338d524e1fb341fcf2bdded3b472", "size": 4893, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/bayesopt/include/posterior_mcmc.hpp", "max_stars_repo_name": "pchrapka/brain-modelling", "max_stars_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-13T19:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-13T19:37:52.000Z", "max_issues_repo_path": "external/bayesopt/include/posterior_mcmc.hpp", "max_issues_repo_name": "pchrapka/brain-modelling", "max_issues_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/bayesopt/include/posterior_mcmc.hpp", "max_forks_repo_name": "pchrapka/brain-modelling", "max_forks_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-25T12:22:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-25T12:22:05.000Z", "avg_line_length": 29.2994011976, "max_line_length": 75, "alphanum_fraction": 0.6691191498, "num_tokens": 1212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947155710234, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2917749381282313}}
{"text": "\n#include <boost/format.hpp>\n#include <boost/program_options.hpp>\n#include <vector>\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <cmath>\n\nint main(int argc, char * argv[])\n{\n  std::string S_fname, X_fname, out_fname; \n\n  namespace po = boost::program_options;\n\n  po::options_description desc(\"Options:\");\n  desc.add_options()\n    (\"help\", \"help message\")\n    (\"standard\", po::value<std::string>(&S_fname)->required(), \"Histogram file for null hypothesis\")\n    (\"experiment\", po::value<std::string>(&X_fname)->required(), \"Histogram file for experimental result\")\n    (\"out\", po::value<std::string>(&out_fname)->required(), \"Output file to contain PDF, CDF, pdf(X)/pdf(S)\");\n\n  \n  po::positional_options_description pos_opts ;\n  pos_opts.add(\"standard\", 1);\n  pos_opts.add(\"experiment\", 1);\n  pos_opts.add(\"out\", 1);     \n    \n  po::variables_map vm; \n\n  std::string what_am_i(\"Calculate pdf, cdf, and conditional probability from normative and experimental histograms\");\n\n  try {\n    po::store(po::command_line_parser(argc, argv).options(desc)\n\t      .positional(pos_opts).run(), vm);\n    \n    if(vm.count(\"help\")) {\n      std::cout << what_am_i\n\t\t<< desc << std::endl; \n      exit(-1);\n    }\n\n    po::notify(vm);\n  }\n  catch(po::required_option & e) {\n    std::cerr << \"ERROR: \" << e.what() << std::endl << std::endl; \n    std::cerr << what_am_i\n\t      << desc << std::endl;\n    exit(-1);    \n  }\n  catch(po::error & e) {\n    std::cerr << \"ERROR: \" << e.what() << std::endl << std::endl; \n    std::cerr << what_am_i\n\t      << desc << std::endl;\n    exit(-1);        \n  }\n\n  std::ifstream Sst(S_fname); \n  std::ifstream Xst(X_fname); \n  \n  std::vector<int> S; \n  std::vector<int> X; \n  \n  for(int n; Sst >> n; ) {\n    S.push_back(n); \n  }\n  for(int n; Xst >> n; ) {\n    X.push_back(n); \n  }\n\n\n  std::ofstream out(out_fname); \n  \n  int x_sum, s_sum; \n  x_sum = s_sum = 0; \n  int i; \n  for(i = 0; i < S.size(); i++) {\n    s_sum += S[i];\n    x_sum += X[i]; \n  }\n\n  // now build the pdf, cdf; \n  float r_x_sum = 1.0 / ((float) x_sum);\n  float r_s_sum = 1.0 / ((float) s_sum); \n\n  float x_cdf = 0.0; \n  float s_cdf = 0.0; \n  for(i = 0; i < S.size(); i++) {\n    float s = ((float) S[i]) * r_s_sum;\n    float x = ((float) X[i]) * r_x_sum;     \n    \n    s_cdf += s; \n    x_cdf += x; \n    out << boost::format(\"%d %f %f %f %f %f\\n\")\n      % i % s % s_cdf % x % x_cdf % (x / s); \n  }\n\n  out.close();\n}\n", "meta": {"hexsha": "a86a9dc26d4b4600728d35026334cedf42600030", "size": 2410, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/HistoStats.cxx", "max_stars_repo_name": "kb1vc/WSPRLog", "max_stars_repo_head_hexsha": "0c0121f9050a249905c3e72f2520479d60acba7c", "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/HistoStats.cxx", "max_issues_repo_name": "kb1vc/WSPRLog", "max_issues_repo_head_hexsha": "0c0121f9050a249905c3e72f2520479d60acba7c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HistoStats.cxx", "max_forks_repo_name": "kb1vc/WSPRLog", "max_forks_repo_head_hexsha": "0c0121f9050a249905c3e72f2520479d60acba7c", "max_forks_repo_licenses": ["BSD-3-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.1, "max_line_length": 118, "alphanum_fraction": 0.5647302905, "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.2917034689353762}}
{"text": "/* \n    Copyright (C) 2009 Wei Dong <wdong@princeton.edu>. All Rights Reserved.\n  \n    This file is part of LSHKIT.\n  \n    LSHKIT 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    LSHKIT 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 LSHKIT.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n/**\n * \\file embed.cpp\n * \\brief Example program of set embedding with random histograms.\n *\n * This program implements the two random histogram embedding methods\n * proposed in the random histogram paper by W. Dong et al.\n *\n * The program reads feature sets from an input text file.  The file\n * is of the following format\n *\n \\verbatim\n ID   N                   // ID is the identifier of the set, N is the number of features in the set\n weight   D1  D2  ...     // a weight followed by D dimensions, 1st feature\n weight   D1  D2  ...     // 2nd feature\n ...\n weight   D1  D2  ...     // Nth feature\n ID   N                   // another set\n weight   D1  D2  ...\n \\endverbatim\n * ID is string which cannot contain space characters; N is positive integer; weight and the dimension\n * values are floats.\n *\n * The program embedds the input sets into single feature vectors and output\n * them in the following format\n *\n \\verbatim\n ID D1  D2 ...              // The input IDs are copied to the output\n ID D1  D2 ...              // Following is the histogram, whose dimensionality is determined by the\n ...                        // input parameters.\n \\endverbatim\n *\n * The user is encouraged to modify this program to customize the input and output format.\n *\n * Usage:\n *\n \\verbatim\nAllowed options:\n  -h [ --help ]            produce help message.\n  -t [ --type ] arg (=1)   embedding algorithm:\n                           1 - stripe embedding [-B, -M, -N, -W],\n                           2 - random hyperplane [-B, -M, -N].\n\n  --norm                   normalize the output vector to unit length.\n  -I [ --input ] arg (=-)  input file.\n  -O [ --output ] arg (=-) output file.\n  -D [ --dim ] arg         input dimension.\n  -B [ -- ] arg (=8)       #bits per projection.\n  -M [ -- ] arg (=1)       take the sum of M.\n  -N [ -- ] arg (=10)      repeat N times.\n  -W [ -- ] arg (=1)       for type 1 only, LSH window size.\n \\endverbatim\n */\n\n\n#include <boost/program_options.hpp>\n#include <boost/foreach.hpp>\n#include <lshkit.h>\n\n/*\n The Histogram<> class in LSHKIT doesn't support polymorphism.\n Following we are going to wrap up Histogram<> with Embedder classes\n to support polymorphism, so the user can choose different\n embedder classes in command line.\n*/\n\n/// The abstract embedder.\n/**\n  * An Embedder class only have to implement two virtual functions: dim() and add().\n  */\nclass Embedder {\npublic:\n    /// The dimension of the output histogram.\n    virtual unsigned dim () const = 0;\n    /// Add a point to the output histogram with weight.\n    virtual void add (float *out, const float *in, float weight) const = 0;\n    /// Add a point to the output histogram with weight = 1.\n    void add (float *out, const float *in) const {\n        add(out, in , 1.0);\n    }\n    /// Initialize the output histogram to zeros.\n    void zero (float *out) const {\n        std::fill(out, out + dim(), 0);\n    }\n    /// Scale the output histogram by *s.\n    void scale (float *out, float s) const\n    {\n        for (unsigned i = 0; i < dim(); i++) out[i] *= s;\n    }\n    /// Normalize the output histogram to a unit vector.\n    void norm (float *out) const\n    {\n        float s = 0.0;\n        for (unsigned i = 0; i < dim(); i++) s += out[i] * out[i];\n        s = 1.0/sqrtf(s);\n        scale(out, s);\n    }\n};\n\n/// The Stripe LSH. See Section 4.1 of MM08 paper.\ntypedef lshkit::Repeat<lshkit::LSB<lshkit::GaussianLsh> > StripeLsh;\ntypedef lshkit::Histogram<StripeLsh> StripeEmbedderBase;\n\n/// Wrapper of the histogram embedder.\nclass StripeEmbedder: public Embedder, public StripeEmbedderBase {\n    typedef StripeEmbedderBase Base;\npublic:\n    struct Parameter: public Base::Parameter {\n        unsigned M, N;\n        /**\n          Inheritec parameters:\n          unsigned dim;\n          float W;\n          unsigned repeat\n         */\n\n    };\n\n    StripeEmbedder (const Parameter &param, lshkit::DefaultRng &rng)\n        : Base(param.M, param.N, param, rng) {\n    }\n\n    virtual unsigned dim () const {\n        return Base::dim();\n    }\n\n    virtual void add (float *out, const float *in, float weight) const {\n        Base::add(out, const_cast<float *>(in), weight);\n    }\n};\n\n/// Random hyperplane LSH. See Section 4.2 of MM08 paper.\ntypedef lshkit::Repeat<lshkit::HyperPlaneLsh> HyperPlaneLsh;\ntypedef lshkit::Histogram<HyperPlaneLsh> HyperPlaneEmbedderBase;\n\n/// Wrapper of the histogram embedder.\nclass HyperPlaneEmbedder: public Embedder, public HyperPlaneEmbedderBase {\n    typedef HyperPlaneEmbedderBase Base;\npublic:\n    struct Parameter: public Base::Parameter {\n        unsigned M, N;\n        /**\n          Inheritec parameters:\n          unsigned dim;\n          unsigned repeat\n         */\n    };\n\n    HyperPlaneEmbedder (const Parameter &param, lshkit::DefaultRng &rng)\n        : Base(param.M, param.N, param, rng) {\n    }\n\n    virtual unsigned dim () const {\n        return Base::dim();\n    }\n\n    virtual void add (float *out, const float *in, float weight) const {\n        Base::add(out, const_cast<float *>(in), weight);\n    }\n};\n\nusing namespace std;\nusing namespace lshkit;\nnamespace po = boost::program_options; \n\n#define EMBEDDER_STRIP  1\n#define EMBEDDER_RP 2\n\nint main (int argc, char *argv[])\n{\n    int type;\n\n    string input;\n    string output;\n\n    unsigned D, B, M, N;\n    float W;\n    bool norm = false;\n\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n        (\"help,h\", \"produce help message.\")\n        (\"type,t\", po::value(&type)->default_value(1), \"embedding algorithm:\\n\"\n            \"\\t1 - stripe embedding [-B, -M, -N, -W],\\n\"\n            \"\\t2 - random hyperplane [-B, -M, -N].\\n\"\n         )\n        (\"norm\", \"normalize the output vector to unit length.\")\n        (\"input,I\", po::value(&input)->default_value(\"-\"), \"input file.\")\n        (\"output,O\", po::value(&output)->default_value(\"-\"), \"output file.\")\n        (\"dim,D\", po::value(&D), \"input dimension.\")\n        (\",B\", po::value(&B)->default_value(8), \"#bits per projection.\")\n        (\",M\", po::value(&M)->default_value(1), \"take the sum of M.\")\n        (\",N\", po::value(&N)->default_value(10), \"repeat N times.\")\n        (\",W\", po::value(&W)->default_value(1.0), \"for type 1 only, LSH window size.\")\n        ;\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm); \n\n    if (vm.count(\"help\") || (vm.count(\"dim\") < 1))\n    {\n        cout << desc;\n        return 0;\n    }\n\n    if (vm.count(\"norm\")) norm = true;\n\n    DefaultRng rng;\n    Embedder *emb;\n\n    switch (type)\n    {\n        case 1: {\n                    StripeEmbedder::Parameter param;\n                    param.dim = D;\n                    param.W = W;\n                    param.repeat = B;\n                    param.M = M;\n                    param.N = N;\n                    emb = new StripeEmbedder(param, rng);\n                    break;\n                }\n        case 2: {\n\n                    HyperPlaneEmbedder::Parameter param;\n                    param.dim = D;\n                    param.repeat = B;\n                    param.M = M;\n                    param.N = N;\n                    emb = new HyperPlaneEmbedder(param, rng);\n                    break;\n                }\n        default:\n                throw invalid_argument(\"INVALID EMBEDDER TYPE.\");\n    }\n    \n    ifstream is(input.c_str());\n    ofstream os(output.c_str());\n\n    float *in = new float[D];\n    float *out = new float[emb->dim()];\n\n    for (;;)\n    {\n/* !!!!!!!!!!!!!!!!! Modify here for different input format !!!!!!!!!!!!!! */\n        unsigned n;  /* number of feature vectors for the next object */\n        string id;\n        is >> id >> n;\n        if (!is) break;\n        emb->zero(out);\n        // process the n vectors\n        for (unsigned i = 0; i < n; ++i)\n        {\n            float weight;\n            is >> weight;\n            /* read a feature vector */\n            for (unsigned j = 0; j < D; ++j) {\n                is >> in[j];\n            }\n            emb->add(out, in, weight);\n        }\n\n/* !!!!!!!!!!!!!!!!! Modify here for different output format !!!!!!!!!!!!!! */\n        if (norm) emb->norm(out);\n        os << id;\n        for (unsigned j = 0; j < emb->dim(); ++j) {\n            os << '\\t' << out[j];\n        }\n        os << endl;\n    }\n\n    delete emb;\n    delete []in;\n    delete []out;\n\n    return 0;\n}\n\n", "meta": {"hexsha": "174fa6501ec9a339dc62dfdf0db1d1ce669f2f23", "size": 9099, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "similarity_search/lshkit/tools/embed.cpp", "max_stars_repo_name": "huonw/nmslib", "max_stars_repo_head_hexsha": "2e424ef7c6eff10ecaf47392fd99f93f645e752f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 150.0, "max_stars_repo_stars_event_min_datetime": "2016-06-03T16:39:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T05:32:56.000Z", "max_issues_repo_path": "similarity_search/lshkit/tools/embed.cpp", "max_issues_repo_name": "huonw/nmslib", "max_issues_repo_head_hexsha": "2e424ef7c6eff10ecaf47392fd99f93f645e752f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2016-06-03T13:43:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-28T07:42:02.000Z", "max_forks_repo_path": "similarity_search/lshkit/tools/embed.cpp", "max_forks_repo_name": "huonw/nmslib", "max_forks_repo_head_hexsha": "2e424ef7c6eff10ecaf47392fd99f93f645e752f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 42.0, "max_forks_repo_forks_event_min_datetime": "2016-05-18T05:53:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-27T19:57:52.000Z", "avg_line_length": 30.533557047, "max_line_length": 102, "alphanum_fraction": 0.5670952852, "num_tokens": 2287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.29170346893537613}}
{"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_AMSGRAD_HPP\n#define NETKET_AMSGRAD_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <cassert>\n#include <cmath>\n#include <complex>\n#include <iostream>\n#include \"abstract_stepper.hpp\"\n\nnamespace netket {\n\nclass AMSGrad : public AbstractStepper {\n  int npar_;\n\n  double eta_;\n  double beta1_;\n  double beta2_;\n\n  Eigen::VectorXd mt_;\n  Eigen::VectorXd vt_;\n\n  double epscut_;\n\n  int mynode_;\n\n  const std::complex<double> I_;\n\n public:\n  // Json constructor\n  explicit AMSGrad(const json &pars)\n      : eta_(FieldOrDefaultVal(pars[\"Learning\"],\"LearningRate\",0.001)),\n        beta1_(FieldOrDefaultVal(pars[\"Learning\"],\"Beta1\",0.9)),\n        beta2_(FieldOrDefaultVal(pars[\"Learning\"],\"Beta2\",0.999)),\n        epscut_(FieldOrDefaultVal(pars[\"Learning\"],\"Epscut\",1.0e-7)),\n        I_(0, 1) {\n    npar_ = -1;\n\n    PrintParameters();\n  }\n\n  void PrintParameters() {\n    MPI_Comm_rank(MPI_COMM_WORLD, &mynode_);\n    if (mynode_ == 0) {\n      std::cout << \"# AMSGrad stepper initialized with these parameters : \"\n                << std::endl;\n      std::cout << \"# Learning Rate = \" << eta_ << std::endl;\n      std::cout << \"# Beta1 = \" << beta1_ << std::endl;\n      std::cout << \"# Beta2 = \" << beta2_ << std::endl;\n      std::cout << \"# Epscut = \" << epscut_ << std::endl;\n    }\n  }\n\n  void Init(const Eigen::VectorXd &pars) override {\n    npar_ = pars.size();\n    mt_.setZero(npar_);\n    vt_.setZero(npar_);\n\n  }\n\n  void Init(const Eigen::VectorXcd &pars) override {\n    npar_ = 2 * pars.size();\n    mt_.setZero(npar_);\n    vt_.setZero(npar_);\n\n  }\n\n  void Update(const Eigen::VectorXd &grad, Eigen::VectorXd &pars) override {\n    assert(npar_ > 0);\n\n    mt_=beta1_*mt_+(1.-beta1_)*grad;\n\n    for(int i=0;i<npar_;i++){\n      vt_(i)=std::max(vt_(i),beta2_*vt_(i)+(1-beta2_)*std::pow(grad(i),2));\n    }\n\n    for(int i=0;i<npar_;i++){\n      pars(i)-=eta_*mt_(i)/(std::sqrt(vt_(i))+epscut_);\n    }\n  }\n\n  void Update(const Eigen::VectorXcd &grad, Eigen::VectorXd &pars) override {\n    Update(Eigen::VectorXd(grad.real()), pars);\n  }\n\n  void Update(const Eigen::VectorXcd &grad, Eigen::VectorXcd &pars) override {\n    assert(npar_ == 2 * pars.size());\n\n    for(int i=0;i<pars.size();i++){\n      mt_(2*i)=beta1_*mt_(2*i)+(1.-beta1_)*grad(i).real();\n      mt_(2*i+1)=beta1_*mt_(2*i+1)+(1.-beta1_)*grad(i).imag();\n    }\n\n    for(int i=0;i<pars.size();i++){\n      vt_(2*i)=std::max(vt_(2*i),beta2_*vt_(2*i)+(1-beta2_)*std::pow(grad(i).real(),2));\n      vt_(2*i+1)=std::max(vt_(2*i+1),beta2_*vt_(2*i+1)+(1-beta2_)*std::pow(grad(i).imag(),2));\n    }\n\n    for(int i=0;i<pars.size();i++){\n      pars(i)-=eta_*mt_(2*i)/(std::sqrt(vt_(2*i))+epscut_);\n      pars(i)-=eta_*I_*mt_(2*i+1)/(std::sqrt(vt_(2*i+1))+epscut_);\n    }\n  }\n\n  void Reset() override {\n    mt_ = Eigen::VectorXd::Zero(npar_);\n    vt_ = Eigen::VectorXd::Zero(npar_);\n  }\n\n};\n\n}  // namespace netket\n\n#endif\n", "meta": {"hexsha": "01352adc2c379073166d837b026f79b977a206d1", "size": 3504, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NetKet/Learning/ams_grad.hpp", "max_stars_repo_name": "artemborin/netket", "max_stars_repo_head_hexsha": "c7f26d52fdb66d2a8f9f94f2e2cfdc8b4ab41334", "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/Learning/ams_grad.hpp", "max_issues_repo_name": "artemborin/netket", "max_issues_repo_head_hexsha": "c7f26d52fdb66d2a8f9f94f2e2cfdc8b4ab41334", "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/Learning/ams_grad.hpp", "max_forks_repo_name": "artemborin/netket", "max_forks_repo_head_hexsha": "c7f26d52fdb66d2a8f9f94f2e2cfdc8b4ab41334", "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.9538461538, "max_line_length": 94, "alphanum_fraction": 0.6247146119, "num_tokens": 1062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2917034689353761}}
{"text": "// Filename: CirculationModel_RV_PA.cpp\n// Created on 20 Aug 2007 by Boyce Griffith\n\n// Modified 2019, Alexander D. Kaiser\n\n#include \"CirculationModel_RV_PA.h\"\n#include \"pnpoly.h\"\n/////////////////////////////// INCLUDES /////////////////////////////////////\n\n#ifndef included_IBAMR_config\n#include <IBAMR_config.h>\n#define included_IBAMR_config\n#endif\n\n#ifndef included_SAMRAI_config\n#include <SAMRAI_config.h>\n#define included_SAMRAI_config\n#endif\n\n// SAMRAI INCLUDES\n#include <CartesianGridGeometry.h>\n#include <CartesianPatchGeometry.h>\n#include <PatchLevel.h>\n#include <SideData.h>\n#include <tbox/RestartManager.h>\n#include <tbox/SAMRAI_MPI.h>\n#include <tbox/Utilities.h>\n\n// C++ STDLIB INCLUDES\n#include <cassert>\n\n#include <Eigen/Dense>\nusing namespace Eigen;\n\nnamespace\n{\n// Name of output file.\nstatic const string DATA_FILE_NAME = \"bc_data.m\";\n\n} \n\n/////////////////////////////// NAMESPACE ////////////////////////////////////\n\n/////////////////////////////// STATIC ///////////////////////////////////////\n\n/////////////////////////////// PUBLIC ///////////////////////////////////////\n\nCirculationModel_RV_PA::CirculationModel_RV_PA(Pointer<Database> input_db, \n                                               const fourier_series_data *fourier_right_ventricle, \n                                               const fourier_series_data *fourier_right_pa, \n                                               const fourier_series_data *fourier_left_pa, \n                                               string right_ventricle_vertices_file_name,\n                                               string right_pa_vertices_file_name,\n                                               string left_pa_vertices_file_name,\n                                               const double  cycle_duration,\n                                               const double  t_offset_bcs_unscaled, \n                                               const double  initial_time, \n                                               double P_initial_pa,\n                                               bool rcr_bcs_on,\n                                               bool resistance_bcs_on,\n                                               bool inductor_bcs_on)\n    : \n      d_object_name(\"circ_model_rv_pa\"),  // constant name here  \n      d_registered_for_restart(true),      // always true\n      d_fourier_right_ventricle(fourier_right_ventricle), \n      d_fourier_right_pa(fourier_right_pa),       \n      d_fourier_left_pa(fourier_left_pa), \n      d_cycle_duration(cycle_duration),\n      d_t_offset_bcs_unscaled(t_offset_bcs_unscaled),\n      d_current_idx_series(0),\n      d_Q_right_ventricle(0.0), \n      d_Q_right_pa(0.0),\n      d_Q_left_pa(0.0),\n      d_Q_right_pa_previous(0.0),\n      d_Q_left_pa_previous(0.0),\n      d_time(initial_time), \n      d_right_pa_P(P_initial_pa), \n      d_right_pa_P_Wk(P_initial_pa),\n      d_right_pa_P_distal(P_initial_pa),\n      d_right_pa_P_distal_previous(P_initial_pa),\n      d_left_pa_P(P_initial_pa),\n      d_left_pa_P_Wk(P_initial_pa),\n      d_left_pa_P_distal(P_initial_pa),\n      d_left_pa_P_distal_previous(P_initial_pa),\n      d_area_right_ventricle(0.0),\n      d_area_right_pa(0.0),\n      d_area_left_pa (0.0),\n      d_area_initialized(false), \n      d_rcr_bcs_on(rcr_bcs_on),\n      d_resistance_bcs_on(resistance_bcs_on),\n      d_inductor_bcs_on(inductor_bcs_on)\n{\n    \n    if (d_registered_for_restart)\n    {\n        RestartManager::getManager()->registerRestartItem(d_object_name, this);\n    }\n\n    // Initialize object with data read from the input and restart databases.\n    const bool from_restart = RestartManager::getManager()->isFromRestart();\n    if (from_restart)\n    {\n        getFromRestart();\n    }\n    \n    if (d_rcr_bcs_on){\n        if (input_db){\n            // left and right equal for now\n            d_right_pa_R_proximal = input_db->getDouble(\"right_pa_R_proximal\");\n            d_right_pa_R_distal   = input_db->getDouble(\"right_pa_R_distal\");\n            d_right_pa_C          = input_db->getDouble(\"right_pa_C\");\n\n            d_left_pa_R_proximal  = input_db->getDouble(\"left_pa_R_proximal\");\n            d_left_pa_R_distal    = input_db->getDouble(\"left_pa_R_distal\");\n            d_left_pa_C           = input_db->getDouble(\"left_pa_C\");\n\n            std::cout << \"input db got values:\\n\";\n            std::cout << \"right: R_proximal = \" << d_right_pa_R_proximal << \"\\tR_distal = \" << d_right_pa_R_distal << \"\\tC = \" << d_right_pa_C << \"\\n\";\n            std::cout << \"left : R_proximal = \" << d_left_pa_R_proximal << \"\\tR_distal = \" << d_left_pa_R_distal << \"\\tC = \" << d_left_pa_C << \"\\n\";\n        }\n        else {\n            TBOX_ERROR(\"Must provide valid input_db\");\n        }\n    }\n\n    if (d_resistance_bcs_on){\n        d_right_pa_resistance = input_db->getDouble(\"right_pa_R\");\n        d_left_pa_resistance  = input_db->getDouble(\"left_pa_R\");\n        std::cout << \"input db got values:\\n\";\n        std::cout << \"right: resistance = \" << d_right_pa_resistance << \"\\n\";\n        std::cout << \"left : R_proximal = \" << d_left_pa_resistance << \"\\n\";\n    }\n\n    if (d_inductor_bcs_on){\n        d_right_pa_inductance = input_db->getDouble(\"right_pa_L\");\n        d_left_pa_inductance  = input_db->getDouble(\"left_pa_L\");\n        std::cout << \"input db got values:\\n\";\n        std::cout << \"right: inductance = \" << d_right_pa_inductance << \"\\n\";\n        std::cout << \"left : inductance = \" << d_left_pa_inductance << \"\\n\";\n    }\n\n    if ((d_rcr_bcs_on && d_resistance_bcs_on) || \n        (d_rcr_bcs_on && d_inductor_bcs_on)   ||\n        (d_inductor_bcs_on && d_resistance_bcs_on)) {\n        TBOX_ERROR(\"Cannot us two types of bc simulataneously\"); \n    }\n\n    double x,x_prev,y,y_prev,z,z_prev; \n    double tol = 1.0e-2; \n\n    // read vertices from file \n    ifstream right_ventricle_file(right_ventricle_vertices_file_name.c_str(), ios::in);\n\n    if(!right_ventricle_file){\n        TBOX_ERROR(\"Aorta file not found\\n\"); \n    }\n\n    right_ventricle_file >> d_n_pts_right_ventricle; \n    \n    d_right_ventricle_points_idx1 = new double[d_n_pts_right_ventricle]; \n    d_right_ventricle_points_idx2 = new double[d_n_pts_right_ventricle]; \n\n    for (int i=0; i<d_n_pts_right_ventricle; i++){\n        right_ventricle_file >> x; \n        right_ventricle_file >> d_right_ventricle_points_idx1[i]; \n        right_ventricle_file >> d_right_ventricle_points_idx2[i];\n        \n        if (i>0){\n            if (fabs(x_prev - x) > tol){\n                TBOX_ERROR(\"x coordinates must be consistent\\n\"); \n            }\n        }\n        x_prev = x; \n\n    }\n    pout << \"to right_ventricle file close\\n\"; \n    right_ventricle_file.close(); \n    d_right_ventricle_axis = 0; \n    d_right_ventricle_side = 0; \n\n    // read vertices from file \n    ifstream right_pa_file(right_pa_vertices_file_name.c_str(), ios::in);\n\n    if(!right_pa_file){\n        TBOX_ERROR(\"Aorta file not found\\n\"); \n    }\n\n    right_pa_file >> d_n_pts_right_pa; \n    \n    d_right_pa_points_idx1 = new double[d_n_pts_right_pa]; \n    d_right_pa_points_idx2 = new double[d_n_pts_right_pa]; \n\n    for (int i=0; i<d_n_pts_right_pa; i++){\n        right_pa_file >> d_right_pa_points_idx1[i]; \n        right_pa_file >> d_right_pa_points_idx2[i]; \n        right_pa_file >> z;\n        \n\n        if (i>0){\n            if (fabs(z_prev - z) > tol){\n                TBOX_ERROR(\"z coordinates must be consistent\\n\"); \n            }\n        }\n        z_prev = z; \n\n    }\n    pout << \"to right_pa file close\\n\"; \n    right_pa_file.close(); \n    d_right_pa_axis = 2; \n    d_right_pa_side = 0; \n\n    // read vertices from file \n    ifstream left_pa_file(left_pa_vertices_file_name.c_str(), ios::in);\n\n    if(!left_pa_file){\n        TBOX_ERROR(\"Left PA file not found\\n\"); \n    }\n\n    left_pa_file >> d_n_pts_left_pa; \n    \n    d_left_pa_points_idx1 = new double[d_n_pts_left_pa]; \n    d_left_pa_points_idx2 = new double[d_n_pts_left_pa]; \n\n    for (int i=0; i<d_n_pts_left_pa; i++){\n        left_pa_file >> d_left_pa_points_idx1[i]; \n        left_pa_file >> y; \n        left_pa_file >> d_left_pa_points_idx2[i]; \n\n        if (i>0){\n            if (fabs(y_prev - y) > tol){\n                TBOX_ERROR(\"y coordinates must be consistent\\n\"); \n            }\n        }\n        y_prev = y; \n\n    }\n    pout << \"to left_pa file close\\n\"; \n    left_pa_file.close();\n    d_left_pa_axis = 1; \n    d_left_pa_side = 0; \n\n    pout << \"passed contstructor\\n\"; \n\n    return;\n} // CirculationModel\n\nCirculationModel_RV_PA::~CirculationModel_RV_PA()\n{\n    return;\n} // ~CirculationModel_RV_PA\n\n\nvoid CirculationModel_RV_PA::advanceTimeDependentData(const double dt,\n                                                        const Pointer<PatchHierarchy<NDIM> > hierarchy,\n                                                        const int U_idx,\n                                                        const int /*P_idx*/,\n                                                        const int /*wgt_cc_idx*/,\n                                                        const int wgt_sc_idx)\n{\n    // Compute the mean flow rates in the vicinity of the inflow and outflow\n    // boundaries.\n    \n    double Q_right_ventricle_local = 0.0; \n    double Q_right_pa_local = 0.0; \n    double Q_left_pa_local = 0.0; \n\n    double area_right_ventricle_local = 0.0; \n    double area_right_pa_local = 0.0; \n    double area_left_pa_local = 0.0; \n\n    if (d_inductor_bcs_on){\n        // save old values of Q for taking time derivatives  \n        d_Q_right_pa_previous = d_Q_right_pa;\n        d_Q_left_pa_previous = d_Q_left_pa;\n    }\n\n\n    for (int ln = 0; ln <= hierarchy->getFinestLevelNumber(); ++ln)\n    {\n        Pointer<PatchLevel<NDIM> > level = hierarchy->getPatchLevel(ln);\n        for (PatchLevel<NDIM>::Iterator p(level); p; p++)\n        {\n            Pointer<Patch<NDIM> > patch = level->getPatch(p());\n            Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();\n            if (pgeom->getTouchesRegularBoundary())\n            {\n                Pointer<SideData<NDIM, double> > U_data = patch->getPatchData(U_idx);\n                Pointer<SideData<NDIM, double> > wgt_sc_data = patch->getPatchData(wgt_sc_idx);\n                const Box<NDIM>& patch_box = patch->getBox();\n                const double* const x_lower = pgeom->getXLower();\n                const double* const dx = pgeom->getDx();\n                double dV = 1.0;\n                for (int d = 0; d < NDIM; ++d)\n                {\n                    dV *= dx[d];\n                }\n\n                for(int axis=0; axis<3; axis++)\n                {\n                    for(int side=0; side<2; side++)\n                    {\n                        const bool is_lower = (side == 0);\n                        if (pgeom->getTouchesRegularBoundary(axis, side))\n                        {\n                            \n                            Vector n;\n                            for (int d = 0; d < NDIM; ++d)\n                            {\n                                n[d] = axis == d ? (is_lower ? -1.0 : +1.0) : 0.0;\n                            }\n                            Box<NDIM> side_box = patch_box;\n                            if (is_lower)\n                            {\n                                side_box.lower(axis) = patch_box.lower(axis);\n                                side_box.upper(axis) = patch_box.lower(axis);\n                            }\n                            else\n                            {\n                                side_box.lower(axis) = patch_box.upper(axis) + 1;\n                                side_box.upper(axis) = patch_box.upper(axis) + 1;\n                            }\n                            for (Box<NDIM>::Iterator b(side_box); b; b++)\n                            {\n                                const Index<NDIM>& i = b();\n\n                                double X[NDIM];\n                                for (int d = 0; d < NDIM; ++d)\n                                {\n                                    X[d] = x_lower[d] + dx[d] * (double(i(d) - patch_box.lower(d)) + (d == axis ? 0.0 : 0.5));\n                                }\n\n                                double X_in_plane_1 = 0.0; \n                                double X_in_plane_2 = 0.0; \n                                if (axis == 0)\n                                {\n                                    X_in_plane_1 = X[1]; \n                                    X_in_plane_2 = X[2]; \n                                }\n                                else if (axis == 1)\n                                {\n                                    X_in_plane_1 = X[0]; \n                                    X_in_plane_2 = X[2]; \n                                }\n                                else if (axis == 2)\n                                {\n                                    X_in_plane_1 = X[0]; \n                                    X_in_plane_2 = X[1]; \n                                }\n                                else{\n                                    TBOX_ERROR(\"Invalid value of axis\\n\"); \n                                }\n\n                                const int in_right_ventricle  = this->point_in_right_ventricle(X_in_plane_1, X_in_plane_2, axis, side);\n                                const int in_right_pa         = this->point_in_right_pa       (X_in_plane_1, X_in_plane_2, axis, side);\n                                const int in_left_pa          = this->point_in_left_pa        (X_in_plane_1, X_in_plane_2, axis, side);\n\n                                if (in_right_ventricle && in_right_pa){\n                                    TBOX_ERROR(\"Position is within two inlets and outlets, should be impossible\\n\"); \n                                }\n                                if (in_right_ventricle && in_left_pa){\n                                    TBOX_ERROR(\"Position is within two inlets and outlets, should be impossible\\n\"); \n                                }\n                                if (in_right_pa && in_left_pa){\n                                    TBOX_ERROR(\"Position is within two inlets and outlets, should be impossible\\n\"); \n                                }\n\n                                if (in_right_ventricle)\n                                {\n                                    const SideIndex<NDIM> i_s(i, axis, SideIndex<NDIM>::Lower);\n                                    if ((*wgt_sc_data)(i_s) > std::numeric_limits<double>::epsilon())\n                                    {\n                                        double dA = dV / dx[axis];\n                                        Q_right_ventricle_local += (*U_data)(i_s)* n[axis] * dA;\n\n                                        if (!d_area_initialized){\n                                            area_right_ventricle_local += dA;\n                                        }\n\n                                    }\n                                }\n\n                                if (in_right_pa)\n                                {\n                                    const SideIndex<NDIM> i_s(i, axis, SideIndex<NDIM>::Lower);\n                                    if ((*wgt_sc_data)(i_s) > std::numeric_limits<double>::epsilon())\n                                    {\n                                        double dA = dV / dx[axis];\n                                        Q_right_pa_local += (*U_data)(i_s) * n[axis] * dA;\n\n                                        if (!d_area_initialized){\n                                            area_right_pa_local += dA;\n                                        }\n\n                                    }\n                                }\n\n                                if (in_left_pa)\n                                {\n                                    const SideIndex<NDIM> i_s(i, axis, SideIndex<NDIM>::Lower);\n                                    if ((*wgt_sc_data)(i_s) > std::numeric_limits<double>::epsilon())\n                                    {\n                                        double dA = dV / dx[axis];\n                                        Q_left_pa_local += (*U_data)(i_s) * n[axis] * dA;\n\n                                        if (!d_area_initialized){\n                                            area_left_pa_local += dA;\n                                        }\n\n                                    }\n                                }\n\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    d_Q_right_ventricle = SAMRAI_MPI::sumReduction(Q_right_ventricle_local);\n    d_Q_right_pa        = SAMRAI_MPI::sumReduction(Q_right_pa_local);\n    d_Q_left_pa         = SAMRAI_MPI::sumReduction(Q_left_pa_local);\n\n    if (!d_area_initialized){\n        d_area_right_ventricle = SAMRAI_MPI::sumReduction(area_right_ventricle_local);\n        d_area_right_pa        = SAMRAI_MPI::sumReduction(area_right_pa_local);  \n        d_area_left_pa         = SAMRAI_MPI::sumReduction(area_left_pa_local);  \n        d_area_initialized = true;       \n    }\n\n    // print_summary();\n\n    // bool debug_out_areas = false; \n    // if (debug_out_areas){\n    //     pout << \"d_area_right_ventricle = \" << d_area_right_ventricle << \"\\n\"; \n    //     pout << \"d_area_right_pa = \" << d_area_right_pa << \"\\n\"; \n    //     pout << \"d_area_left_pa = \" << d_area_left_pa << \"\\n\"; \n    // }\n\n    d_time += dt; \n\n    // compute which index in the Fourier series we need here \n    // always use a time in current cycle \n    double t_reduced = d_time - d_cycle_duration * floor(d_time/d_cycle_duration); \n\n    // fourier series has its own period, scale to that \n    double t_scaled = t_reduced * (d_fourier_right_ventricle->L  / d_cycle_duration); \n\n    // start offset some arbitrary time in the cardiac cycle, but this is relative to the series length \n    double t_scaled_offset = t_scaled + d_t_offset_bcs_unscaled; \n\n    // Fourier data here\n    // index without periodicity \n    unsigned int k = (unsigned int) floor(t_scaled_offset / (d_fourier_right_ventricle->dt));\n    \n    // // take periodic reduction\n    d_current_idx_series = k % (d_fourier_right_ventricle->N_times);\n\n\n    if (d_rcr_bcs_on){\n        // The downstream pressure is determined by a three-element Windkessel model.\n\n        double coeff_left = (d_left_pa_C / dt + 1.0 / d_left_pa_R_distal); \n        double coeff_right = (d_right_pa_C / dt + 1.0 / d_right_pa_R_distal);\n\n        // grab the downstream pressures \n        d_right_pa_P_distal_previous = d_right_pa_P_distal; \n        d_right_pa_P_distal = MMHG_TO_CGS * d_fourier_right_pa->values[d_current_idx_series]; \n\n        d_left_pa_P_distal_previous = d_left_pa_P_distal; \n        d_left_pa_P_distal = MMHG_TO_CGS * d_fourier_left_pa->values[d_current_idx_series]; \n\n        // hooked to ground version \n        // d_right_pa_P_Wk = ((d_right_pa_C / dt) * d_right_pa_P_Wk + d_Q_right_pa) / (d_right_pa_C / dt + 1.0 / d_right_pa_R_distal);        \n        // d_right_pa_P = d_right_pa_P_Wk + d_right_pa_R_proximal * d_Q_right_pa;\n\n        // d_left_pa_P_Wk = ((d_left_pa_C / dt) * d_left_pa_P_Wk + d_Q_left_pa) / (d_left_pa_C / dt + 1.0 / d_left_pa_R_distal);        \n        // d_left_pa_P = d_left_pa_P_Wk + d_left_pa_R_proximal * d_Q_left_pa;\n\n        d_right_pa_P_Wk = ((d_right_pa_C / dt) * (d_right_pa_P_Wk - d_right_pa_P_distal_previous) + coeff_right*d_right_pa_P_distal + d_Q_right_pa) / coeff_right;        \n        d_right_pa_P = d_right_pa_P_Wk + d_right_pa_R_proximal * d_Q_right_pa;\n\n        d_left_pa_P_Wk = ((d_left_pa_C / dt) * (d_left_pa_P_Wk - d_left_pa_P_distal_previous) + coeff_right*d_left_pa_P_distal + d_Q_left_pa) / coeff_left;        \n        d_left_pa_P = d_left_pa_P_Wk + d_left_pa_R_proximal * d_Q_left_pa;\n\n    }\n    else if (d_resistance_bcs_on){\n        // pressure upstream of resistance determined by series \n        d_right_pa_P_Wk = MMHG_TO_CGS * d_fourier_right_pa->values[d_current_idx_series]; \n        d_left_pa_P_Wk  = MMHG_TO_CGS * d_fourier_left_pa->values[d_current_idx_series]; \n\n        // resistance bcs determine outlet pressure \n        d_right_pa_P = d_right_pa_P_Wk + d_right_pa_resistance * d_Q_right_pa;\n        d_left_pa_P  = d_left_pa_P_Wk  + d_left_pa_resistance  * d_Q_left_pa;\n    }\n\n    else if (d_inductor_bcs_on){\n        // pressure upstream of resistance determined by series \n        d_right_pa_P_Wk = MMHG_TO_CGS * d_fourier_right_pa->values[d_current_idx_series]; \n        d_left_pa_P_Wk  = MMHG_TO_CGS * d_fourier_left_pa->values[d_current_idx_series]; \n\n        // inductance bcs determine update on pressure \n        d_right_pa_P = d_right_pa_P_Wk + d_right_pa_inductance * (d_Q_right_pa - d_Q_right_pa_previous)/dt;\n        d_left_pa_P  = d_left_pa_P_Wk  + d_left_pa_inductance  * (d_Q_left_pa  - d_Q_left_pa_previous )/dt ;\n    }\n\n    else {\n        d_right_pa_P = MMHG_TO_CGS * d_fourier_right_pa->values[d_current_idx_series]; \n        d_left_pa_P  = MMHG_TO_CGS * d_fourier_left_pa->values[d_current_idx_series]; \n    }\n\n    // bool debug_out = false; \n    // if (debug_out){\n    //     pout << \"circ mode: d_time = \" << d_time << \", d_current_idx_series = \" << d_current_idx_series << \"\\n\"; \n    //     pout << \"t_reduced = \" << t_reduced << \" t_scaled = \" << t_scaled << \" t_scaled_offset = \" << t_scaled_offset << \"\\n\"; \n    //     pout << \"k (unreduced idx) = \" << k << \" d_current_idx_series = \" << d_current_idx_series << \"\\n\\n\"; \n    // }\n\n\n    writeDataFile(); \n\n} // advanceTimeDependentData\n\nvoid CirculationModel_RV_PA::set_Q_valve(double Q_valve){\n    d_Q_valve = Q_valve; \n}\n\n\n\nvoid\nCirculationModel_RV_PA::putToDatabase(Pointer<Database> db)\n{\n\n    db->putInteger(\"d_current_idx_series\", d_current_idx_series); \n    db->putDouble(\"d_Q_right_ventricle\", d_Q_right_ventricle); \n    db->putDouble(\"d_Q_right_pa\", d_Q_right_pa);\n    db->putDouble(\"d_Q_left_pa\", d_Q_left_pa);\n    db->putDouble(\"d_Q_right_pa_previous\", d_Q_right_pa_previous);\n    db->putDouble(\"d_Q_left_pa_previous\", d_Q_left_pa_previous);\n    db->putDouble(\"d_Q_valve\", d_Q_valve);\n    db->putDouble(\"d_right_pa_P\", d_right_pa_P);\n    db->putDouble(\"d_right_pa_P_Wk\", d_right_pa_P_Wk);\n    db->putDouble(\"d_right_pa_P_distal\", d_right_pa_P_distal);\n    db->putDouble(\"d_right_pa_P_distal_previous\", d_right_pa_P_distal_previous);\n    db->putDouble(\"d_left_pa_P\",d_left_pa_P);\n    db->putDouble(\"d_left_pa_P_Wk\",d_left_pa_P_Wk);\n    db->putDouble(\"d_left_pa_P_distal\", d_left_pa_P_distal);\n    db->putDouble(\"d_left_pa_P_distal_previous\", d_left_pa_P_distal_previous);\n    db->putDouble(\"d_time\", d_time); \n    db->putBool(\"d_rcr_bcs_on\", d_rcr_bcs_on); \n    db->putBool(\"d_resistance_bcs_on\", d_resistance_bcs_on); \n    db->putBool(\"d_inductor_bcs_on\", d_inductor_bcs_on); \n    return; \n} // putToDatabase\n\nvoid CirculationModel_RV_PA::print_summary(){\n\n    double P_right_ventricle = d_fourier_right_ventricle->values[d_current_idx_series]; \n    double P_right_pa; \n    double P_left_pa; \n\n    if (d_rcr_bcs_on){\n        P_right_pa        = d_right_pa_P / MMHG_TO_CGS;\n        P_left_pa         = d_left_pa_P / MMHG_TO_CGS;\n    }\n    else{\n        P_right_pa        = d_fourier_right_pa->values[d_current_idx_series];\n        P_left_pa         = d_fourier_left_pa->values[d_current_idx_series];\n    }\n\n    pout << \"rcr_bcs_on = \" << d_rcr_bcs_on << \"\\n\"; \n    pout << \"% time \\t P_right_ventricle (mmHg)\\t P_right_pa (mmHg)\\t P_left_pa (mmHg)\\t Q_right_ventricle (ml/s)\\t d_Q_right_pa (ml/s)\\t d_Q_right_pa (ml/s)\\tQ_valve (ml/s) \\t idx\" ;\n    if (d_rcr_bcs_on || d_resistance_bcs_on){\n        pout << \"\\t right_pa_P_Wk\\t left_pa_P_Wk\\t \"; \n    }\n    pout << \"\\n\";\n    pout << d_time << \" \" << P_right_ventricle <<  \" \" << P_right_pa << \" \" << P_left_pa << \" \" << d_Q_right_ventricle << \" \" << d_Q_right_pa << \" \" << d_Q_left_pa << \" \" << d_Q_valve << \" \" << d_current_idx_series; \n    if (d_rcr_bcs_on || d_resistance_bcs_on){\n        pout  << \" \" << d_right_pa_P_Wk << \" \" << d_left_pa_P_Wk; \n    }\n    pout << \"\\n\";\n\n}\n\nint CirculationModel_RV_PA::point_in_right_ventricle(double testx, double testy, int axis, int side){\n    // checks whether given point is in right ventricle\n\n    // quick exit for correct side and axis \n    if ((axis != d_right_ventricle_axis) || (side != d_right_ventricle_side))\n        return 0; \n\n    return pnpoly(d_n_pts_right_ventricle, d_right_ventricle_points_idx1, d_right_ventricle_points_idx2, testx, testy); \n}\n\nint CirculationModel_RV_PA::point_in_right_pa(double testx, double testy, int axis, int side){\n    // checks whether given point is in right ventricle\n\n    // quick exit for correct side and axis \n    if ((axis != d_right_pa_axis) || (side != d_right_pa_side))\n        return 0; \n\n    return pnpoly(d_n_pts_right_pa, d_right_pa_points_idx1, d_right_pa_points_idx2, testx, testy); \n}\n\nint CirculationModel_RV_PA::point_in_left_pa(double testx, double testy, int axis, int side){\n    // checks whether given point is in right ventricle\n\n    // quick exit for correct side and axis \n    if ((axis != d_left_pa_axis) || (side != d_left_pa_side))\n        return 0; \n\n    return pnpoly(d_n_pts_left_pa, d_left_pa_points_idx1, d_left_pa_points_idx2, testx, testy); \n}\n\nvoid CirculationModel_RV_PA::write_plot_code()\n{\n    static const int mpi_root = 0;\n    if (SAMRAI_MPI::getRank() == mpi_root)\n    {\n        ofstream fout(DATA_FILE_NAME.c_str(), ios::app);\n        fout.setf(ios_base::scientific);\n        fout.setf(ios_base::showpos);\n        fout.precision(10);\n\n        fout << \"];\\n\";\n        fout << \"MMHG_TO_CGS = 1333.22368;\\n\";\n        fout << \"fig = figure;\\n\";\n        fout << \"times   =  bc_vals(:,1);\\n\";\n        fout << \"p_rv    =  bc_vals(:,2);\\n\";\n        fout << \"p_rpa   =  bc_vals(:,3);\\n\";\n        fout << \"p_lpa   =  bc_vals(:,4);\\n\";\n        fout << \"q_rv    = -bc_vals(:,5); \\n\";\n        fout << \"q_rpa   =  bc_vals(:,6);\\n\";\n        fout << \"q_lpa   =  bc_vals(:,7);\\n\";\n        fout << \"q_valve =  bc_vals(:,8);\\n\";\n        fout << \"p_wk_rpa =  bc_vals(:,9);\\n\";\n        fout << \"p_wk_lpa =  bc_vals(:,10);\\n\";\n        fout << \"load '../bc_variables_experimental.mat'\\n\";\n        fout << \"subplot(2,1,1)\\n\";\n        fout << \"plot(times, p_rv, 'k')\\n\";\n        fout << \"hold on\\n\";\n        fout << \"plot(times, p_rpa, ':k')\\n\";\n        fout << \"plot(times, p_lpa, '-.k')\\n\";\n        fout << \"plot(times_exp, p_rv_exp)\\n\";\n        fout << \"plot(times_exp, p_pa_exp)\\n\";\n        fout << \"plot(times, p_wk_rpa)\\n\";\n        fout << \"plot(times, p_wk_lpa)\\n\";\n        fout << \"% legend('P RV', 'P RPA', 'PWK RPA', 'P LPA', 'PWK LPA', 'P EXP RV', 'P EXP PA', Location','NorthEastOutside');\\n\";\n        fout << \"legend('P RV', 'P RPA', 'P LPA', 'P EXP RV', 'P EXP PA', 'WK RPA', 'WK LPA', 'Location','NorthEastOutside');\\n\";\n        fout << \"xlabel('t (s)')\\n\";\n        fout << \"ylabel('P (mmHg)')\\n\";\n        fout << \"subplot(2,1,2)\\n\";\n        fout << \"plot(times, q_rv, 'k')\\n\";\n        fout << \"hold on\\n\";\n        fout << \"plot(times, q_rpa, '--k')\\n\";\n        fout << \"plot(times, q_lpa, '-.k')\\n\";\n        fout << \"plot(times_two_cycles, q_rv_exp)\\n\";\n        fout << \"plot(bc_vals(:,1), zeros(size(q_rv)), ':k')\\n\";\n        fout << \"legend('Q RV', 'Q RPA', 'Q LPA', 'Q EXP RV', 'Location', 'NorthEastOutside')\\n\";\n        fout << \"xlabel('t (s)')\\n\";\n        fout << \"ylabel('Flow (ml/s)')\\n\";\n        fout << \"set(fig, 'Position', [100, 100, 1000, 750])\\n\";\n        fout << \"set(fig,'PaperPositionMode','auto')\\n\";\n        fout << \"printfig(fig, 'bc_model_variables_with_experimental')\\n\";\n        fout << \"q_mean = mean(q_rv)\\n\";\n    }\n    return;\n}\n\n\n\n/////////////////////////////// PROTECTED ////////////////////////////////////\n\n/////////////////////////////// PRIVATE //////////////////////////////////////\n\nvoid\n    CirculationModel_RV_PA::writeDataFile() const\n{\n    static const int mpi_root = 0;\n    if (SAMRAI_MPI::getRank() == mpi_root)\n    {\n        static bool file_initialized = false;\n        const bool from_restart = RestartManager::getManager()->isFromRestart();\n        if (!from_restart && !file_initialized)\n        {\n            ofstream fout(DATA_FILE_NAME.c_str(), ios::out);\n            fout << \"% time \\t P_right_ventricle (mmHg)\\t P_right_pa (mmHg)\\t P_left_pa (mmHg)\\t d_Q_right_ventricle (ml/s)\\t d_Q_right_pa (ml/s)\\td_Q_left_pa (ml/s) \\td_Q_valve (ml/s) \\t d_right_pa_P_Wk \\t d_left_pa_P_Wk\"; \n            if (d_rcr_bcs_on){\n                fout << \"d_right_pa_P_distal \\t d_left_pa_P_distal\"; \n            }\n            fout << \"\\n\"\n                 << \"bc_vals = [\";\n            file_initialized = true;\n        }\n\n        ofstream fout(DATA_FILE_NAME.c_str(), ios::app);\n\n        fout << d_time;\n        fout.setf(ios_base::scientific);\n        fout.setf(ios_base::showpos);\n        fout.precision(10);\n\n        double P_right_ventricle = d_fourier_right_ventricle->values[d_current_idx_series]; \n\n        fout << \" \" << P_right_ventricle <<  \" \" << d_right_pa_P/MMHG_TO_CGS << \" \" << d_left_pa_P/MMHG_TO_CGS;\n        fout << \" \" << d_Q_right_ventricle << \" \" << d_Q_right_pa << \" \" << d_Q_left_pa << \" \" << d_Q_valve;         \n        fout << \" \" << d_right_pa_P_Wk/MMHG_TO_CGS << \" \" << d_left_pa_P_Wk/MMHG_TO_CGS;\n        if(d_rcr_bcs_on){\n            fout << \" \" << d_right_pa_P_distal/MMHG_TO_CGS << \" \" << d_left_pa_P_distal/MMHG_TO_CGS;\n        }\n        fout << \"; \\n\";\n\n    }\n\n    return;\n} // writeDataFile\n\nvoid\nCirculationModel_RV_PA::getFromRestart()\n{\n    Pointer<Database> restart_db = RestartManager::getManager()->getRootDatabase();\n    Pointer<Database> db;\n    if (restart_db->isDatabase(d_object_name))\n    {\n        db = restart_db->getDatabase(d_object_name);\n    }\n    else\n    {\n        TBOX_ERROR(\"Restart database corresponding to \" << d_object_name << \" not found in restart file.\");\n    }\n\n    d_current_idx_series         = db->getInteger(\"d_current_idx_series\"); \n    d_Q_right_ventricle          = db->getDouble(\"d_Q_right_ventricle\"); \n    d_Q_right_pa                 = db->getDouble(\"d_Q_right_pa\");\n    d_Q_left_pa                  = db->getDouble(\"d_Q_left_pa\");\n    d_Q_right_pa_previous        = db->getDouble(\"d_Q_right_pa_previous\");\n    d_Q_left_pa_previous         = db->getDouble(\"d_Q_left_pa_previous\");\n    d_Q_valve                    = db->getDouble(\"d_Q_valve\");\n    d_right_pa_P                 = db->getDouble(\"d_right_pa_P\");\n    d_right_pa_P_Wk              = db->getDouble(\"d_right_pa_P_Wk\");\n    d_right_pa_P_distal          = db->getDouble(\"d_right_pa_P_distal\");\n    d_right_pa_P_distal_previous = db->getDouble(\"d_right_pa_P_distal_previous\");\n    d_left_pa_P                  = db->getDouble(\"d_left_pa_P\");\n    d_left_pa_P_Wk               = db->getDouble(\"d_left_pa_P_Wk\");\n    d_left_pa_P_distal           = db->getDouble(\"d_left_pa_P_distal\");\n    d_left_pa_P_distal_previous  = db->getDouble(\"d_left_pa_P_distal_previous\");\n    d_time                       = db->getDouble(\"d_time\");\n    d_rcr_bcs_on                 = db->getBool(\"d_rcr_bcs_on\"); \n    d_resistance_bcs_on          = db->getBool(\"d_resistance_bcs_on\"); \n    d_inductor_bcs_on            = db->getBool(\"d_inductor_bcs_on\"); \n    return;\n} // getFromRestart\n\n/////////////////////////////// NAMESPACE ////////////////////////////////////\n\n/////////////////////////////// TEMPLATE INSTANTIATION ///////////////////////\n\n//////////////////////////////////////////////////////////////////////////////", "meta": {"hexsha": "146a8c54f3c717b93621c28db638be26721a83df", "size": 31405, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CirculationModel_RV_PA.cpp", "max_stars_repo_name": "alexkaiser/heart_valves", "max_stars_repo_head_hexsha": "53f30ec3680503542890a84949b7fb51d1734272", "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": "CirculationModel_RV_PA.cpp", "max_issues_repo_name": "alexkaiser/heart_valves", "max_issues_repo_head_hexsha": "53f30ec3680503542890a84949b7fb51d1734272", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CirculationModel_RV_PA.cpp", "max_forks_repo_name": "alexkaiser/heart_valves", "max_forks_repo_head_hexsha": "53f30ec3680503542890a84949b7fb51d1734272", "max_forks_repo_licenses": ["BSD-3-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.4313984169, "max_line_length": 224, "alphanum_fraction": 0.5430027066, "num_tokens": 8084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2916030639633188}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   MonteCarlo_ScreenedRutherfordElasticElectronScatteringDistribution.hpp\n//! \\author Luke Kersting\n//! \\brief  The screened Rutherford elastic electronscattering distribution base class\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef MONTE_CARLO_SCREENED_RUTHERFORD_ELASTIC_ELECTRON_SCATTERING_DISTRIBUTION_HPP\n#define MONTE_CARLO_SCREENED_RUTHERFORD_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 \"Utility_TabularDistribution.hpp\"\n#include \"Utility_TabularOneDDistribution.hpp\"\n#include \"MonteCarlo_ElectronScatteringDistribution.hpp\"\n#include \"MonteCarlo_AdjointElectronScatteringDistribution.hpp\"\n#include \"MonteCarlo_AnalogElasticElectronScatteringDistribution.hpp\"\n\nnamespace MonteCarlo{\n\n//! The scattering distribution base class\nclass ScreenedRutherfordElasticElectronScatteringDistribution : public ElectronScatteringDistribution,\n                                    public AdjointElectronScatteringDistribution\n{\n\npublic:\n\n  //! Typedef for the array of energy dependent screened rutherford paramters\n  //! (first = energy, second = Moliere screening constant, \n  //!  third = normalization constant\n  typedef Teuchos::Array<Utility::Trip<double,double,double> > ParameterArray;\n\n  typedef Teuchos::RCP<const AnalogElasticElectronScatteringDistribution>\n            ElasticDistribution;    \n\n  //! Constructor from ACE table data\n  ScreenedRutherfordElasticElectronScatteringDistribution(\n    const ElasticDistribution& elastic_cutoff_distribution,\n    const int atomic_number,\n    const double upper_cutoff_angle = 1.0e-6 );\n\n  //! Constructor from ENDL table data\n  ScreenedRutherfordElasticElectronScatteringDistribution(\n    const ParameterArray& screened_rutherford_parameters,\n    const double upper_cutoff_angle = 1.0e-6 );\n\n  //! Destructor \n  virtual ~ScreenedRutherfordElasticElectronScatteringDistribution()\n  { /* ... */ }\n\n  //! Evaluate the distribution\n  double evaluate( const double incoming_energy,\n                   const double scattering_angle ) const;\n\n  //! Evaluate the PDF\n  double evaluatePDF( const double incoming_energy,\n                      const double scattering_angle ) const;\n\n  //! Evaluate the integrated PDF\n  double evaluateIntegratedPDF( const double incoming_energy) const;\n\n  //! Evaluate the CDF\n  double evaluateCDF( const double incoming_energy,\n                      const double scattering_angle ) 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 ) 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,\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\n  //! Evaluate Moliere's atomic screening constant at the given electron energy\n  double evaluateMoliereScreeningConstant( const double energy ) const;\n\nprivate:\n\n  // Find the lower and upper bin boundary\n  void findLowerAndUpperBinBoundary( \n        const double incoming_energy,\n        ParameterArray::const_iterator& lower_bin_boundary,\n        ParameterArray::const_iterator& upper_bin_boundary,\n        double& interpolation_fraction ) const;\n\n  // evaluate the pdf integrated from 0 to angle\n  double evaluateIntegratedPDF( \n        const double& scattering_angle, \n        const ParameterArray::const_iterator& lower_bin_boundary, \n        const ParameterArray::const_iterator& upper_bin_boundary,\n        const double& interpolation_fraction ) const;\n\n  // The fine structure constant (fsc) squared\n  static double s_fine_structure_const_squared;\n\n  // A parameter for moliere's screening factor  (1/2*(fsc/0.885)**2)\n  static double s_screening_param1;\n\n  // Atomic number (Z) of the target atom\n  int d_atomic_number;\n\n  // Atomic number (Z) of the target atom to the 2/3 power (Z^2/3)\n  double d_Z_two_thirds_power;\n\n  // A parameter for moliere's screening factor (3.76*fsc**2*Z**2)\n  double d_screening_param2;\n\n  // The scattering angle below which the screened Rutherford distribution is used\n  double d_upper_cutoff_angle;\n\n  // The scattering angle cosine above which the screened Rutherford distribution is used\n  double d_lower_cutoff_angle_cosine;\n\n  // Flag to indicate that tabulated screened rutherford parameters are used\n  bool d_using_endl_tables;\n\n  // Analog elastic scattering distribution\n  ElasticDistribution d_elastic_cutoff_distribution;\n\n  // Screened Rutherford energy depended paramters: Moliere's screening constant and normalization constant\n  ParameterArray d_screened_rutherford_parameters;\n};\n\n} // end MonteCarlo namespace\n\n#endif // end MONTE_CARLO_SCREENED_RUTHERFORD_ELASTIC_ELECTRON_SCATTERING_DISTRIBUTION_HPP\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_ScreenedRutherfordElasticElectronScatteringDistribution.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "fd1fbbad32620c6a71c9308832b5b328c8f1df45", "size": 6240, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/collision/native/src/MonteCarlo_ScreenedRutherfordElasticElectronScatteringDistribution.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_ScreenedRutherfordElasticElectronScatteringDistribution.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_ScreenedRutherfordElasticElectronScatteringDistribution.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": 37.5903614458, "max_line_length": 107, "alphanum_fraction": 0.7016025641, "num_tokens": 1257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6654105720171531, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.29133238498813263}}
{"text": "\n#include \"hoCuNDArray_utils.h\"\n#include \"radial_utilities.h\"\n#include \"hoNDArray_fileio.h\"\n#include \"cuNDArray.h\"\n#include \"imageOperator.h\"\n#include \"identityOperator.h\"\n#include \"hoPartialDerivativeOperator.h\"\n#include \"hoCuConebeamProjectionOperator.h\"\n#include \"cuConvolutionOperator.h\"\n#include \"hoCuNDArray_blas.h\"\n#include \"hoCuNDArray_elemwise.h\"\n#include \"hoCuNDArray_blas.h\"\n#include \"cgSolver.h\"\n#include \"CBCT_acquisition.h\"\n#include \"complext.h\"\n#include \"encodingOperatorContainer.h\"\n#include \"vector_td_io.h\"\n#include \"hoPartialDerivativeOperator.h\"\n#include \"hoCuGPBBSolver.h\"\n#include \"hoCuTvOperator.h\"\n#include \"hoCuTvPicsOperator.h\"\n#include \"hoCuNCGSolver.h\"\n#include \"hoCuCgDescentSolver.h\"\n#include \"hoCuNDArray_utils.h\"\n#include \"hoCuPartialDerivativeOperator.h\"\n#include \"CBSubsetOperator.h\"\n#include \"osMOMSolverD.h\"\n#include \"osMOMSolverD3.h\"\n#include \"cuSolverUtils.h\"\n#include <iostream>\n#include <algorithm>\n#include <sstream>\n#include <math_constants.h>\n#include <boost/program_options.hpp>\n#include <boost/make_shared.hpp>\n#include <solvers/osMOMSolverD3.h>\n#include \"hoLinearResampleOperator_eigen.h\"\n#include \"multiplicationOperatorContainer.h\"\n#include \"cuLinearResampleOperator.h\"\n#include \"multiresRegistrationSolver.h\"\n#include \"cuCGHSOFSolver.h\"\n\n#include \"hdf5_utils.h\"\n#include \"hoCuOFPartialDerivativeOperator.h\"\n#include \"hoCuTVOFPartialDerivativeOperator.h\"\n\nusing namespace std;\nusing namespace Gadgetron;\n\nnamespace po = boost::program_options;\n\n\nboost::shared_ptr< hoCuNDArray<float> >\nperform_registration( boost::shared_ptr< hoCuNDArray<float> > volume, float of_alpha, float of_beta, unsigned int num_multires_levels )\n{\n\tstd::vector<size_t> volume_dims_3d = *volume->get_dimensions();\n\tvolume_dims_3d.pop_back();\n\tstd::vector<size_t> volume_dims_3d_3 = volume_dims_3d;\n\tvolume_dims_3d_3.push_back(3);\n\n\tsize_t num_elements_3d = volume_dims_3d[0]* volume_dims_3d[1]* volume_dims_3d[2];\n\tsize_t num_phases = volume->get_size(3);\n\n\tboost::shared_ptr< hoCuNDArray<float> > host_result_field( new hoCuNDArray<float> );\n\t{\n\t\tstd::vector<size_t> volume_dims_4d = volume_dims_3d;\n\t\tvolume_dims_4d.push_back(3);\n\t\tvolume_dims_4d.push_back(volume->get_size(3));\n\t\thost_result_field->create( &volume_dims_4d );\n\t}\n\n\t// Upload host data to device\n\t//\n\n\tfor( unsigned int i=0; i<num_phases; i++ ){\n\n\t\thoCuNDArray<float> host_fixed( &volume_dims_3d, volume->get_data_ptr()+((i+1)%num_phases)*num_elements_3d );\n\t\thoCuNDArray<float> host_moving( &volume_dims_3d, volume->get_data_ptr()+i*num_elements_3d );\n\n\t\tcuNDArray<float> fixed_image(&host_fixed);\n\t\tcuNDArray<float> moving_image(&host_moving);\n\n\t\tboost::shared_ptr< cuLinearResampleOperator<float,3> > R( new cuLinearResampleOperator<float,3>() );\n\n\t\t// Setup solver\n\t\t//\n\t\tcuCGHSOFSolver<float,3> OFs;\n\t\t//cuCKOpticalFlowSolver<float,3> OFs;\n\t\tOFs.set_interpolator( R );\n\t\tOFs.set_output_mode( cuCGHSOFSolver<float,3>::OUTPUT_VERBOSE );\n\t\tOFs.set_max_num_iterations_per_level( 500 );\n\t\tOFs.set_num_multires_levels( num_multires_levels );\n\t\tOFs.set_alpha(of_alpha);\n\t\t//OFs.set_beta(of_beta);\n\t\t//OFs.set_limit(0.01f);\n\n\t\t// Run registration\n\t\t//\n\t\tboost::shared_ptr< cuNDArray<float> > result = OFs.solve( &fixed_image, &moving_image );\n        std::cout << \"Dimensions of vector field \";\n        auto dims = *result->get_dimensions();\n        for (size_t d : dims) std::cout << d << \" \";\n        std::cout << std::endl;\n\n\t\tcuNDArray<float> dev_sub;\n\t\tdev_sub.create( &volume_dims_3d_3, result->get_data_ptr() );\n\n\t\thoCuNDArray<float> host_sub( &volume_dims_3d_3, host_result_field->get_data_ptr()+i*num_elements_3d*3 );\n\t\thost_sub = dev_sub;\n\n\t}\n\n\t/*\n {\n  std::cout << std::endl << \"Writing out registration results for phase \" << phase << \".\" << std::endl;\n  char filename[256];\n  sprintf(&(filename[0]), \"def_moving_%i.real\", phase);\n  write_nd_array<float>(&host_result_image, (char*)filename);\n }\n\t */\n\n\n\treturn host_result_field;\n}\nclass hoCuConvertOperator : public subsetOperator<hoCuNDArray<float>>{\n\npublic:\n\thoCuConvertOperator(boost::shared_ptr<subsetOperator<hoCuNDArray<float>>> _op) : subsetOperator<hoCuNDArray<float>>(_op->get_number_of_subsets()),op(_op){};\n\n\n\tvirtual void mult_M(hoCuNDArray<float> *in, hoCuNDArray<float> *out,int subset, bool accumulate) override { op->mult_M((hoCuNDArray<float>*)in,(hoCuNDArray<float>*) out, subset,accumulate);}\n\tvirtual void mult_MH(hoCuNDArray<float> *in, hoCuNDArray<float> *out,int subset, bool accumulate) override { op->mult_MH((hoCuNDArray<float>*)in,(hoCuNDArray<float>*) out, subset, accumulate);}\n\tvirtual void mult_MH_M(hoCuNDArray<float> *in, hoCuNDArray<float> *out,int subset, bool accumulate) override { op->mult_MH_M((hoCuNDArray<float>*)in,(hoCuNDArray<float>*) out, subset, accumulate);}\n\n\tvirtual boost::shared_ptr< std::vector<size_t> > get_codomain_dimensions(int i) { return op->get_codomain_dimensions(i);}\n\tvirtual boost::shared_ptr< std::vector<size_t> > get_domain_dimensions() { return op->get_domain_dimensions();}\n\tvirtual void set_domain_dimensions( std::vector<size_t> * dims) { return op->set_domain_dimensions(dims);}\n\tvirtual void set_codomain_dimensions( std::vector<size_t> * dims) { return op->set_codomain_dimensions(dims);}\n\n\n\nprotected:\n\tboost::shared_ptr<subsetOperator<hoCuNDArray<float>>> op;\n};\n\nboost::shared_ptr<hoCuNDArray<float> > calculate_prior(boost::shared_ptr<CBCT_binning>  binning,boost::shared_ptr<CBCT_acquisition> ps, hoCuNDArray<float>& projections, std::vector<size_t> is_dims, floatd3 imageDimensions){\n\tstd::cout << \"Calculating FDK prior\" << std::endl;\n\tboost::shared_ptr<CBCT_binning> binning_pics=binning->get_3d_binning();\n\tstd::vector<size_t> is_dims3d = is_dims;\n\tis_dims3d.pop_back();\n\tboost::shared_ptr< hoCuConebeamProjectionOperator >\n\tEp( new hoCuConebeamProjectionOperator() );\n\tEp->setup(ps,binning_pics,imageDimensions);\n\tEp->set_codomain_dimensions(ps->get_projections()->get_dimensions().get());\n\tEp->set_domain_dimensions(&is_dims3d);\n\tEp->set_use_filtered_backprojection(true);\n\tboost::shared_ptr<hoCuNDArray<float> > prior3d(new hoCuNDArray<float>(&is_dims3d));\n\tEp->mult_MH(&projections,prior3d.get());\n\n\thoCuNDArray<float> tmp_proj(*ps->get_projections());\n\tEp->mult_M(prior3d.get(),&tmp_proj);\n\tfloat s = dot(ps->get_projections().get(),&tmp_proj)/dot(&tmp_proj,&tmp_proj);\n\t*prior3d *= s;\n\tboost::shared_ptr<hoCuNDArray<float> > prior(new hoCuNDArray<float>(*expand( prior3d.get(), is_dims.back() )));\n\tstd::cout << \"Prior complete\" << std::endl;\n\treturn prior;\n}\n\nint main(int argc, char** argv)\n{\n\tstring acquisition_filename;\n\tstring outputFile;\n\tuintd3 imageSize;\n\tfloatd3 voxelSize;\n\tint device;\n\tunsigned int iterations;\n\tfloatd2 scale_factor;\n\tunsigned int subsets;\n\tint reg_iter;\n\tfloat rho;\n\tfloat tv_weight;\n    float tv_weight4d;\n    float tau;\n\tpo::options_description desc(\"Allowed options\");\n\tstring tv_prior_filename;\n\tdesc.add_options()\n    \t\t(\"help\", \"produce help message\")\n    \t\t(\"acquisition,a\", po::value<string>(&acquisition_filename)->default_value(\"acquisition.hdf5\"), \"Acquisition data\")\n    \t\t(\"samples,n\",po::value<unsigned int>(),\"Number of samples per ray\")\n    \t\t(\"output,f\", po::value<string>(&outputFile)->default_value(\"reconstruction.hdf5\"), \"Output filename\")\n    \t\t(\"size,s\",po::value<uintd3>(&imageSize)->default_value(uintd3(512,512,1)),\"Image size in pixels\")\n    \t\t(\"binning,b\",po::value<string>(),\"Binning file for 4d reconstruction\")\n    \t\t(\"SAG\",\"Use exact SAG correction if present\")\n    \t\t(\"voxelSize,v\",po::value<floatd3>(&voxelSize)->default_value(floatd3(0.488f,0.488f,1.0f)),\"Voxel size in mm\")\n    \t\t(\"dimensions,d\",po::value<floatd3>(),\"Image dimensions in mm. Overwrites voxelSize.\")\n    \t\t(\"iterations,i\",po::value<unsigned int>(&iterations)->default_value(10),\"Number of iterations\")\n    \t\t(\"device\",po::value<int>(&device)->default_value(0),\"Number of the device to use (0 indexed)\")\n\t\t\t\t\t(\"downsample,D\",po::value<floatd2>(&scale_factor)->default_value(floatd2(1,1)),\"Downsample projections this factor\")\n    \t\t(\"subsets,u\",po::value<unsigned int>(&subsets)->default_value(10),\"Number of subsets to use\")\n    \t\t(\"TV\",po::value<float>(&tv_weight)->default_value(0),\"Total variation weight\")\n            (\"TV4D\",po::value<float>(&tv_weight4d)->default_value(0),\"Total variation in temporal direction\")\n                    (\"tau\",po::value<float>(&tau)->default_value(1e-5),\"Solver tau\")\n\t\t\t\t\t(\"reg_iter\",po::value<int>(&reg_iter)->default_value(2),\"Regularization iterations\")\n    \t\t(\"use_prior\",\"Use an FDK prior\")\n    \t\t(\"TV-prior\",po::value<string>(&tv_prior_filename)->default_value(\"reconstructionTV.real\"),\"TV prior for registration\")\n                    (\"vector-field\",po::value<string>(),\"Stored vector field\")\n    \t\t(\"3D\",\"Only use binning data to determine wrong projections\")\n    \t\t;\n\n\tpo::variables_map vm;\n\tpo::store(po::parse_command_line(argc, argv, desc), vm);\n\tpo::notify(vm);\n\n\tif (vm.count(\"help\")) {\n\t\tcout << desc << \"\\n\";\n\t\treturn 1;\n\t}\n\n\tstd::cout << \"Command line options:\" << std::endl;\n\tfor (po::variables_map::iterator it = vm.begin(); it != vm.end(); ++it){\n\t\tboost::any a = it->second.value();\n\t\tstd::cout << it->first << \": \";\n\t\tif (a.type() == typeid(std::string)) std::cout << it->second.as<std::string>();\n\t\telse if (a.type() == typeid(int)) std::cout << it->second.as<int>();\n\t\telse if (a.type() == typeid(unsigned int)) std::cout << it->second.as<unsigned int>();\n\t\telse if (a.type() == typeid(float)) std::cout << it->second.as<float>();\n\t\telse if (a.type() == typeid(vector_td<float,3>)) std::cout << it->second.as<vector_td<float,3> >();\n\t\telse if (a.type() == typeid(vector_td<int,3>)) std::cout << it->second.as<vector_td<int,3> >();\n\t\telse if (a.type() == typeid(vector_td<unsigned int,3>)) std::cout << it->second.as<vector_td<unsigned int,3> >();\n\t\telse std::cout << \"Unknown type\" << std::endl;\n\t\tstd::cout << std::endl;\n\t}\n\n\tcudaSetDevice(device);\n\tcudaDeviceReset();\n\n\t//Really weird stuff. Needed to initialize the device?? Should find real bug.\n\tcudaDeviceManager::Instance()->lockHandle();\n\tcudaDeviceManager::Instance()->unlockHandle();\n\n\tboost::shared_ptr<CBCT_acquisition> ps(new CBCT_acquisition());\n\tps->load(acquisition_filename);\n\tps->get_geometry()->print(std::cout);\n    if (scale_factor[0] != 1 || scale_factor[1] != 1)\n        ps->downsample(scale_factor[0],scale_factor[1]);\n\n\tfloat SDD = ps->get_geometry()->get_SDD();\n\tfloat SAD = ps->get_geometry()->get_SAD();\n\n\tboost::shared_ptr<CBCT_binning> binning(new CBCT_binning());\n\tif (vm.count(\"binning\")){\n\t\tstd::cout << \"Loading binning data\" << std::endl;\n\t\tbinning->load(vm[\"binning\"].as<string>());\n\t\tif (vm.count(\"3D\"))\n\t\t\tbinning = binning->get_3d_binning();\n\t} else binning->set_as_default_3d_bin(ps->get_projections()->get_size(2));\n\tbinning->print(std::cout);\n\n\tfloatd3 imageDimensions;\n\tif (vm.count(\"dimensions\")){\n\t\timageDimensions = vm[\"dimensions\"].as<floatd3>();\n\t\tvoxelSize = imageDimensions/imageSize;\n\t}\n\telse imageDimensions = voxelSize*imageSize;\n\n\tfloat lengthOfRay_in_mm = norm(imageDimensions);\n\tunsigned int numSamplesPerPixel = 3;\n\tfloat minSpacing = min(voxelSize)/numSamplesPerPixel;\n\n\tunsigned int numSamplesPerRay;\n\tif (vm.count(\"samples\")) numSamplesPerRay = vm[\"samples\"].as<unsigned int>();\n\telse numSamplesPerRay = ceil( lengthOfRay_in_mm / minSpacing );\n\n\tfloat step_size_in_mm = lengthOfRay_in_mm / numSamplesPerRay;\n\tsize_t numProjs = ps->get_projections()->get_size(2);\n\tsize_t needed_bytes = 2 * prod(imageSize) * sizeof(float);\n\tstd::vector<size_t> is_dims = to_std_vector((uint64d3)imageSize);\n\n\tstd::cout << \"IS dimensions \" << is_dims[0] << \" \" << is_dims[1] << \" \" << is_dims[2] << std::endl;\n\tstd::cout << \"Image size \" << imageDimensions << std::endl;\n\n\tis_dims.push_back(binning->get_number_of_bins());\n\n\t// Define encoding matrix\n\tauto E = boost::make_shared<CBSubsetOperator<hoCuNDArray> >(subsets);\n\n\t//E->setup(ps,binning,imageDimensions);\n\tE->setup(ps,binning,imageDimensions);\n\tE->set_domain_dimensions(&is_dims);\n\tE->set_codomain_dimensions(ps->get_projections()->get_dimensions().get());\n\n\tauto E2 = boost::make_shared<hoCuConvertOperator>(E);\n\n\t//hoCuGPBBSolver<float> solver;\n\t//hoCuCgDescentSolver<float> solver;\n//\tosSPSSolver<hoCuNDArray<float>> solver;\n\tosMOMSolverD<hoCuNDArray<float>> solver;\n\t//osSPSSolver<hoCuNDArray<float>> solver;\n\t//hoCuNCGSolver<float> solver;\n\tsolver.set_encoding_operator(E);\n\t//solver.set_domain_dimensions(&is_dims);\n\tsolver.set_max_iterations(iterations);\n\tsolver.set_output_mode(hoCuGPBBSolver<float>::OUTPUT_VERBOSE);\n\tsolver.set_non_negativity_constraint(true);\n    solver.set_tau(tau);\n\tsolver.set_reg_steps(reg_iter);\n\t//solver.set_rho(rho);\n\n\thoCuNDArray<float> projections = *ps->get_projections();\n\tE->offset_correct(&projections);\n\n\tboost::shared_ptr<hoCuNDArray<float> > prior;\n\n\tif (vm.count(\"use_prior\")) {\n\t\tprior = calculate_prior(binning,ps,projections,is_dims,imageDimensions);\n\t\tsolver.set_x0(prior);\n\t}\n\t/*\n\tif (tv_weight > 0){\n\t\tauto total_variation = boost::make_shared<hoCuTvOperator<float,4>>();\n\t\ttotal_variation->set_weight(tv_weight);\n\t\t//total_variation->set_weight_array(weight_array);\n\t\tsolver.add_nonlinear_operator(total_variation);\n\t\tsolver.set_kappa(tv_weight);\n}\n*/\n\n\n    if (tv_weight4d > 0){\n        boost::shared_ptr<hoNDArray<float>> displacements;\n        if (vm.count(\"vector-field\")){\n            displacements = read_nd_array<float>(vm[\"vector-field\"].as<string>().c_str());\n            auto vdims = *displacements->get_dimensions();\n            for (auto v : vdims) std::cout << v << \" \";\n            std::cout<<std::endl;\n        } else {\n            auto tv_recon = boost::make_shared<hoCuNDArray<float>>();\n            *tv_recon = *read_nd_array<float>(tv_prior_filename.c_str());\n            displacements = perform_registration(tv_recon, 0.01, 1, 3);\n        }\n        //clear(displacements.get());\n        //auto DtOF = boost::make_shared<hoCuOFPartialDerivativeOperator<float>>();\n\n\t\tauto DtOF = boost::make_shared<hoCuTVOFPartialDerivativeOperator<float>>();\n\t\t//auto DtOF = boost::make_shared<hoCuPartialDerivativeOperator<float,4>>(3);\n        DtOF->set_weight(tv_weight4d);\n        DtOF->set_displacement_field(displacements);\n        DtOF->set_domain_dimensions(&is_dims);\n\t\tauto is_dimsTV = is_dims;\n\t\tis_dimsTV.push_back(3);\n        DtOF->set_codomain_dimensions(&is_dimsTV);\n        solver.add_regularization_operator(DtOF);\n    }\n\n  if (tv_weight > 0){\n\n  \tauto Dx = boost::make_shared<hoCuPartialDerivativeOperator<float,4>>(0);\n  \tDx->set_weight(tv_weight);\n  \tDx->set_domain_dimensions(&is_dims);\n  \tDx->set_codomain_dimensions(&is_dims);\n\n  \tauto Dy = boost::make_shared<hoCuPartialDerivativeOperator<float,4>>(1);\n  \tDy->set_weight(tv_weight);\n  \tDy->set_domain_dimensions(&is_dims);\n  \tDy->set_codomain_dimensions(&is_dims);\n\n\n  \tauto Dz = boost::make_shared<hoCuPartialDerivativeOperator<float,4>>(2);\n  \tDz->set_weight(tv_weight);\n  \tDz->set_domain_dimensions(&is_dims);\n  \tDz->set_codomain_dimensions(&is_dims);\n\tsolver.add_regularization_group({Dx,Dy,Dz});\n  }\n\n\n\n\tauto result = solver.solve(&projections);\n\n\t//write_nd_array<float>( result.get(), outputFile.c_str());\n\tsaveNDArray2HDF5(result.get(),outputFile,imageDimensions,floatd3(0,0,0),\"\",iterations);\n}\n\n", "meta": {"hexsha": "0153d0334c221de7d96398bb3e693e883de03a1f", "size": 15221, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xray/CBOS_OF_reconstruct.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/CBOS_OF_reconstruct.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/CBOS_OF_reconstruct.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": 39.6380208333, "max_line_length": 223, "alphanum_fraction": 0.7197293213, "num_tokens": 4233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2913323791780663}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   Utility_MaxwellFissionDistribution_def.hpp\n//! \\author Aaron Tumulak\n//! \\brief  Maxwell Fission distribution class definition. Modified by Alex\n//!         Robinson to accommodate units.\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef UTILITY_MAXWELL_FISSION_DISTRIBUTION_DEF_HPP\n#define UTILITY_MAXWELL_FISSION_DISTRIBUTION_DEF_HPP\n\n// Boost Includes\n#include <boost/units/cmath.hpp>\n\n// FRENSIE Includes\n#include \"Utility_RandomNumberGenerator.hpp\"\n#include \"Utility_ArrayString.hpp\"\n#include \"Utility_PhysicalConstants.hpp\"\n#include \"Utility_ExceptionTestMacros.hpp\"\n#include \"Utility_ExceptionCatchMacros.hpp\"\n#include \"Utility_ContractException.hpp\"\n\nnamespace Utility{\n\n// Constructor\ntemplate<typename IndependentUnit, typename DependentUnit>\nUnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::UnitAwareMaxwellFissionDistribution(\n  const typename UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::IndepQuantity incident_energy,\n  const typename UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::IndepQuantity nuclear_temperature,\n  const typename UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::IndepQuantity restriction_energy,\n  const double constant_multiplier )\n  : d_incident_energy( incident_energy ),\n    d_nuclear_temperature( nuclear_temperature ),\n    d_restriction_energy( restriction_energy ),\n    d_multiplier( DMQT::initializeQuantity( constant_multiplier ) ),\n    d_norm_constant()\n{\n  // Make sure values are valid\n  testPrecondition( !IQT::isnaninf( incident_energy ) );\n  testPrecondition( !IQT::isnaninf( nuclear_temperature ) );\n  testPrecondition( !IQT::isnaninf( restriction_energy ) );\n  testPrecondition( !QT::isnaninf( constant_multiplier ) );\n  // Make sure that incident energy and nuclear temperature is positive\n  testPrecondition( incident_energy > IQT::zero() );\n  testPrecondition( nuclear_temperature > IQT::zero() );\n  // Make sure that the constant multiplier is positive\n  testPrecondition( constant_multiplier > 0.0 );\n\n  // Calculate the norm constant\n  this->calculateNormalizationConstant();\n}\n\n// Constructor\n/*! \\details This constructor will explicitly cast the input quantities to\n * the distribution quantity (which includes any unit-conversion). The\n * dimension type must match and there must be a unit-conversion defined using\n * the boost methodology.\n */\ntemplate<typename IndependentUnit, typename DependentUnit>\ntemplate<typename InputIndepQuantityA,\n\t typename InputIndepQuantityB,\n\t typename InputIndepQuantityC>\nUnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::UnitAwareMaxwellFissionDistribution(\n\t\t\t\tconst InputIndepQuantityA incident_energy,\n\t\t\t\tconst InputIndepQuantityB nuclear_temperature,\n\t\t\t\tconst InputIndepQuantityC restriction_energy,\n\t\t\t\tconst double constant_multiplier )\n  : d_incident_energy( incident_energy ),\n    d_nuclear_temperature( nuclear_temperature ),\n    d_restriction_energy( restriction_energy ),\n    d_multiplier( DMQT::initializeQuantity( constant_multiplier ) ),\n    d_norm_constant()\n{\n  // Make sure values are valid\n  testPrecondition( !QuantityTraits<InputIndepQuantityA>::isnaninf( incident_energy ) );\n  testPrecondition( !QuantityTraits<InputIndepQuantityB>::isnaninf( nuclear_temperature ) );\n  testPrecondition( !QuantityTraits<InputIndepQuantityC>::isnaninf( restriction_energy ) );\n  testPrecondition( !QT::isnaninf( constant_multiplier ) );\n  // Make sure that incident energy and nuclear temperature is positive\n  testPrecondition( incident_energy > \n\t\t    QuantityTraits<InputIndepQuantityA>::zero() );\n  testPrecondition( nuclear_temperature > \n\t\t    QuantityTraits<InputIndepQuantityB>::zero() );\n  // Make sure that the constant multiplier is positive\n  testPrecondition( constant_multiplier > 0.0 );\n\n  // Calculate the norm constant \n  this->calculateNormalizationConstant();\n}\n\n// Copy constructor\n/*! \\details Just like boost::units::quantity objects, the unit-aware \n * distribution can be explicitly cast to a distribution with compatible\n * units. If the units are not compatible, this function will not compile. Note\n * that this allows distributions to be scaled safely (unit conversions \n * are completely taken care of by boost::units)!\n */\ntemplate<typename IndependentUnit, typename DependentUnit>\ntemplate<typename InputIndepUnit, typename InputDepUnit>\nUnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::UnitAwareMaxwellFissionDistribution(\n  const UnitAwareMaxwellFissionDistribution<InputIndepUnit,InputDepUnit>& dist_instance )\n  : d_incident_energy( dist_instance.d_incident_energy ),\n    d_nuclear_temperature( dist_instance.d_nuclear_temperature ),\n    d_restriction_energy( dist_instance.d_restriction_energy ),\n    d_multiplier(),\n    d_norm_constant()\n{\n  // Make sure the multipliers are valid\n  remember( typedef QuantityTraits<typename UnitAwareMaxwellFissionDistribution<InputIndepUnit,InputDepUnit>::IndepQuantity> InputIQT );\n  testPrecondition( !InputIQT::isnaninf( dist_instance.d_incident_energy ) );\n  testPrecondition( !InputIQT::isnaninf( dist_instance.d_nuclear_temperature));\n  testPrecondition( !InputIQT::isnaninf( dist_instance.d_restriction_energy) );\n  // Make sure that incident energy and nuclear temperature is positive\n  testPrecondition( dist_instance.d_incident_energy > InputIQT::zero() );\n  testPrecondition( dist_instance.d_nuclear_temperature > InputIQT::zero() );\n\n  // Calculate the scaled multiplier (for complex units, boost::units often has\n  // problems doing the conversion so we will do it manually)\n  d_multiplier = getRawQuantity( dist_instance.d_multiplier )*DepQuantity( QuantityTraits<typename UnitAwareMaxwellFissionDistribution<InputIndepUnit,InputDepUnit>::DepQuantity>::one() )/Utility::sqrt( IndepQuantity( QuantityTraits<typename UnitAwareMaxwellFissionDistribution<InputIndepUnit,InputDepUnit>::IndepQuantity>::one() ) );\n\n  // Calculate the norm constant\n  this->calculateNormalizationConstant();\n}\n\n// Copy constructor\ntemplate<typename IndependentUnit, typename DependentUnit>\nUnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::UnitAwareMaxwellFissionDistribution( const UnitAwareMaxwellFissionDistribution<void,void>& unitless_dist_instance, int )\n  : d_incident_energy( IQT::initializeQuantity( unitless_dist_instance.d_incident_energy ) ),\n    d_nuclear_temperature( IQT::initializeQuantity( unitless_dist_instance.d_nuclear_temperature ) ),\n    d_restriction_energy( IQT::initializeQuantity( unitless_dist_instance.d_restriction_energy ) ),\n    d_multiplier( DMQT::initializeQuantity( unitless_dist_instance.d_multiplier ) ),\n    d_norm_constant()\n{\n  // Make sure the multipliers are valid\n  testPrecondition( !QT::isnaninf( unitless_dist_instance.d_incident_energy ) );\n  testPrecondition( !QT::isnaninf( unitless_dist_instance.d_nuclear_temperature) );\n  testPrecondition( !QT::isnaninf( unitless_dist_instance.d_restriction_energy) );\n  // Make sure that incident energy and nuclear temperature is positive\n  testPrecondition( unitless_dist_instance.d_incident_energy > 0.0 );\n  testPrecondition( unitless_dist_instance.d_nuclear_temperature > 0.0 );\n\n  // Calculate the norm constant\n  this->calculateNormalizationConstant();\n}\n\n// Construct distribution from a unitless dist. (potentially dangerous)\n/*! \\details Constructing a unit-aware distribution from a unitless \n * distribution is potentially dangerous. By forcing users to construct objects\n * using this method instead of a standard constructor we are trying to make\n * sure users are aware of the danger. This is designed to mimic the interface \n * of the boost::units::quantity, which also has to deal with this issue. \n */\ntemplate<typename IndependentUnit, typename DependentUnit>\nUnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>\nUnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::fromUnitlessDistribution( const UnitAwareMaxwellFissionDistribution<void,void>& unitless_distribution )\n{\n  return ThisType( unitless_distribution, 0 );\n}\n\n// Assignment operator\ntemplate<typename IndependentUnit, typename DependentUnit>\nUnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>& \nUnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::operator=(\n    const UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>& dist_instance )\n{\n  // Make sure the distribution is valid\n  testPrecondition( !IQT::isnaninf( dist_instance.d_incident_energy ) );\n  testPrecondition( !IQT::isnaninf( dist_instance.d_nuclear_temperature ) );\n  testPrecondition( !IQT::isnaninf( dist_instance.d_restriction_energy ) );\n  testPrecondition( !DMQT::isnaninf( dist_instance.d_multiplier ) );\n  testPrecondition( dist_instance.d_incident_energy > IQT::zero() );\n  testPrecondition( dist_instance.d_nuclear_temperature > IQT::zero() );\n\n  if( this != &dist_instance )\n  {\n    d_incident_energy = dist_instance.d_incident_energy;\n    d_nuclear_temperature = dist_instance.d_nuclear_temperature;\n    d_restriction_energy = dist_instance.d_restriction_energy;\n    d_multiplier = dist_instance.d_multiplier;\n    d_norm_constant = dist_instance.d_norm_constant;\n  }\n  \n  return *this;\n}\n\n// Evaluate the distribution\n/*! \\details This is simply the unnormalized distribution. An implicit \n * conversion factor (1.0) is used to convert to the correct units.\n */\ntemplate<typename IndependentUnit, typename DependentUnit>\ntypename UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::DepQuantity\nUnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::evaluate( \n const typename UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::IndepQuantity indep_var_value ) const\n{\n  if( indep_var_value < IQT::zero() )\n    return DQT::zero();\n  else\n  {\n    return d_multiplier*Utility::sqrt( indep_var_value )*\n      exp( -indep_var_value / d_nuclear_temperature );\n  }\n}\n\n// Evaluate the PDF\ntemplate<typename IndependentUnit, typename DependentUnit>\ntypename UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::InverseIndepQuantity\nUnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::evaluatePDF( \nconst typename UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::IndepQuantity indep_var_value ) const\n{\n  return this->evaluate( indep_var_value )*d_norm_constant;\n}\n\n// Return a random sample from the distribution\ntemplate<typename IndependentUnit, typename DependentUnit>\ntypename UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::IndepQuantity\nUnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::sample() const\n{\n  return ThisType::sample( d_incident_energy,\n\t\t\t   d_nuclear_temperature,\n\t\t\t   d_restriction_energy );\n}\n\n// Return a random sample from the corresponding CDF and record the number of trials\ntemplate<typename IndependentUnit, typename DependentUnit>\ninline typename UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::IndepQuantity\nUnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::sample(\n  const typename UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::IndepQuantity incident_energy,\n  const typename UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::IndepQuantity nuclear_temperature,\n  const typename UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::IndepQuantity restriction_energy )\n{\n  unsigned trials = 0;\n\n  return ThisType::sampleAndRecordTrials( incident_energy,\n\t\t\t\t\t  nuclear_temperature,\n\t\t\t\t\t  restriction_energy,\n\t\t\t\t\t  trials );\n}\n\n// Return a random sample and record the number of trials\ntemplate<typename IndependentUnit, typename DependentUnit>\ntypename UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::IndepQuantity\nUnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::sampleAndRecordTrials( unsigned& trials ) const\n{\n  return ThisType::sampleAndRecordTrials( d_incident_energy,\n\t\t\t\t\t  d_nuclear_temperature,\n\t\t\t\t\t  d_restriction_energy,\n\t\t\t\t\t  trials );\n}\n\n// Return a random sample from the corresponding CDF and record the number of trials\ntemplate<typename IndependentUnit, typename DependentUnit>\ninline typename UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::IndepQuantity\nUnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::sampleAndRecordTrials(\n  const typename UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::IndepQuantity incident_energy,\n  const typename UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::IndepQuantity nuclear_temperature,\n  const typename UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::IndepQuantity restriction_energy,\n  unsigned& trials )\n{\n  // Make sure values are valid\n  testPrecondition( !IQT::isnaninf( incident_energy ) );\n  testPrecondition( !IQT::isnaninf( nuclear_temperature ) );\n  testPrecondition( !IQT::isnaninf( restriction_energy ) );\n  \n  // Make sure that incident energy and nuclear temperature is positive\n  testPrecondition( incident_energy > IQT::zero() );\n  testPrecondition( nuclear_temperature > IQT::zero() );\n  \n  double random_number_1, random_number_2, random_number_3;\n  double term_1, term_2, arg;\n  IndepQuantity sample;\n  \n  // Use the method outlined in OpenMC documentation under \"5.7.2.4. ACE Law 7 - UnitAwareMaxwell Fission Spectrum\"\n  while( true )\n  {\n    // Increment the trial counter\n    ++trials;\n    \n    random_number_1 = RandomNumberGenerator::getRandomNumber<double>();\n    random_number_2 = RandomNumberGenerator::getRandomNumber<double>();\n    random_number_3 = RandomNumberGenerator::getRandomNumber<double>();\n    \n    term_1 = log(random_number_1);\n    \n    arg = cos( PhysicalConstants::pi * random_number_3 * 0.5 );\n\n    term_2 = log(random_number_2)*arg*arg;\n    \n    sample = -nuclear_temperature * ( term_1 + term_2 );\n     \n    if( sample <= (incident_energy - restriction_energy) )\n      break;\n  }\n  \n  return sample;\n}\n\n// Calculate the normalization constant of the distribution\n/*\n * As given by ENDF Law 7\n * c^(-1) = T^(3/2)*[(sqrt(pi)/2)*erf(sqrt((E-U)/T)) - sqrt((E-U)/T)*exp(-(E-U)/T)]\n */\ntemplate<typename IndependentUnit, typename DependentUnit>\nvoid\nUnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::calculateNormalizationConstant()\n{\n  double argument = (d_incident_energy - d_restriction_energy) / d_nuclear_temperature;\n\n  d_norm_constant =  rpow<3,-2>(d_nuclear_temperature)/\n    (d_multiplier*(sqrt( PhysicalConstants::pi ) * 0.5 * erf( sqrt(argument) )-\n\t\t   sqrt(argument) * exp(-argument) ) );\n}\n\n// Return the upper bound of the distribution independent variable\ntemplate<typename IndependentUnit, typename DependentUnit>\ntypename UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::IndepQuantity\nUnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::getUpperBoundOfIndepVar() const\n{\n  return (d_incident_energy - d_restriction_energy);\n}\n\n// Return the lower bound of the distribution independent variable\ntemplate<typename IndependentUnit, typename DependentUnit>\ntypename UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::IndepQuantity\nUnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::getLowerBoundOfIndepVar() const\n{\n  return IQT::zero();\n}\n\n// Return the distribution type\ntemplate<typename IndependentUnit, typename DependentUnit>\nOneDDistributionType UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::getDistributionType() const\n{\n  return ThisType::distribution_type;\n}\n\n// Test if the distribution is continuous\ntemplate<typename IndependentUnit, typename DependentUnit>\nbool UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::isContinuous() const\n{\n  return true;\n}\n\n// Method for placing the object in an output stream\ntemplate<typename IndependentUnit, typename DependentUnit>\nvoid UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::toStream( std::ostream& os ) const\n{\n  os << \"{\" << getRawQuantity( d_incident_energy ) \n     << \",\" << getRawQuantity( d_nuclear_temperature )\n     << \",\" << getRawQuantity( d_restriction_energy );\n\n  // Only print the multiplier when a scaling has been done\n  if( d_multiplier != DMQT::one() )\n    os << \",\" << getRawQuantity( d_multiplier ) << \"}\";\n  else\n    os << \"}\";\n}\n\n// Method for initializing the object from an input stream\ntemplate<typename IndependentUnit, typename DependentUnit>\nvoid UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::fromStream( std::istream& is )\n{\n  // Read in the distribution representation\n  std::string dist_rep;\n  std::getline( is, dist_rep, '}' );\n  dist_rep += '}';\n  \n  Teuchos::Array<std::string> distribution;\n  try{\n    distribution = Teuchos::fromStringToArray<std::string>( dist_rep );\n  }\n  catch( Teuchos::InvalidArrayStringRepresentation& error )\n  {\n    std::string message( \"Error: the Maxwell Fission distribution cannot be \"\n                        \"constructed because the representation is not valid \"\n                        \"(see details below)!\\n\" );\n    message += error.what();\n    \n    throw InvalidDistributionStringRepresentation( message );\n  }\n  \n  TEST_FOR_EXCEPTION( distribution.size() > 4,\n                     InvalidDistributionStringRepresentation,\n                     \"Error: the Maxwell Fission distribution cannot \"\n                     \"be constructed because the representation is \"\n                     \"not valid\"\n                     \"(only 4 values or fewer  may be specified)!\" );\n  \n  // Set the incient neutron energy\n  if( distribution.size() > 0 )\n  {\n    TEST_FOR_EXCEPTION( distribution[0].find_first_not_of( \" 0123456789.e\" ) <\n\t\t\tdistribution[0].size(),\n\t\t\tInvalidDistributionStringRepresentation,\n\t\t\t\"Error: the Maxwell Fission distribution cannot be \"\n\t\t\t\"constructed because of an invalid incident energy \"\n\t\t\t<< distribution[0] );\n    {\n      double incident_energy;\n      \n      std::istringstream iss( distribution[0] );\n      Teuchos::extractDataFromISS( iss, incident_energy );\n\n      setQuantity( d_incident_energy, incident_energy );\n    }\n  \n    TEST_FOR_EXCEPTION( IQT::isnaninf( d_incident_energy ),\n\t\t\tInvalidDistributionStringRepresentation,\n\t\t\t\"Error: the Maxwell Fission distribution cannot be \"\n\t\t\t\"constructed because of an invalid incident energy \"\n\t\t\t<< d_incident_energy );\n  \n    TEST_FOR_EXCEPTION( d_incident_energy < IQT::zero(),\n\t\t\tInvalidDistributionStringRepresentation,\n\t\t\t\"Error: the Maxwell Fission distribution cannot be \"\n\t\t\t\"constructed because of an invalid incident energy \"\n\t\t\t<< d_incident_energy );\n  }\n  \n  // Set the nuclear temperature\n  if( distribution.size() > 1 )\n  {\n    TEST_FOR_EXCEPTION( distribution[1].find_first_not_of( \" 0123456789.e\" ) <\n\t\t\tdistribution[1].size(),\n\t\t\tInvalidDistributionStringRepresentation,\n\t\t\t\"Error: the Maxwell Fission distribution cannot be \"\n\t\t\t\"constructed because of an invalid nuclear temperature \"\n\t\t\t<< distribution[1] );\n    {\n      double nuclear_temperature;\n      \n      std::istringstream iss( distribution[1] );\n      Teuchos::extractDataFromISS( iss, nuclear_temperature );\n\n      setQuantity( d_nuclear_temperature, nuclear_temperature );\n    }\n  \n    TEST_FOR_EXCEPTION( IQT::isnaninf( d_nuclear_temperature ),\n\t\t\tInvalidDistributionStringRepresentation,\n\t\t\t\"Error: the Maxwell Fission distribution cannot be \"\n\t\t\t\"constructed because of an invalid nuclear temperature \"\n\t\t\t<< d_nuclear_temperature );\n  \n    TEST_FOR_EXCEPTION( d_nuclear_temperature <= IQT::zero(),\n\t\t\tInvalidDistributionStringRepresentation,\n\t\t\t\"Error: the Maxwell Fission distribution cannot be \"\n\t\t\t\"constructed because of an invalid nuclear temperature \"\n\t\t\t<< d_nuclear_temperature );\n  }\n\n  // Set the restriction energy\n  if( distribution.size() > 2 )\n  {\n    TEST_FOR_EXCEPTION( distribution[2].find_first_not_of( \" 0123456789.e\" ) <\n\t\t\tdistribution[2].size(),\n\t\t\tInvalidDistributionStringRepresentation,\n\t\t\t\"Error: the Maxwell Fission distribution cannot be \"\n\t\t\t\"construcqted because of an invalid restriction energy \"\n\t\t\t<< distribution[2] );\n    {\n      double restriction_energy;\n      \n      std::istringstream iss( distribution[2] );\n      Teuchos::extractDataFromISS( iss, restriction_energy );\n\n      setQuantity( d_restriction_energy, restriction_energy );\n    }\n    \n    TEST_FOR_EXCEPTION( IQT::isnaninf( d_restriction_energy ),\n\t\t\tInvalidDistributionStringRepresentation,\n\t\t\t\"Error: the Maxwell Fission distribution cannot be \"\n\t\t\t\"constructed because of an invalid restriction energy \"\n\t\t\t<< d_restriction_energy );\n  }\n\n  // Set the multiplier\n  if( distribution.size() > 3 )\n  {\n    TEST_FOR_EXCEPTION( distribution[3].find_first_not_of( \" 0123456789.e\" ) <\n\t\t\tdistribution[3].size(),\n\t\t\tInvalidDistributionStringRepresentation,\n\t\t\t\"Error: the Maxwell Fission distribution cannot be \"\n\t\t\t\"construcqted because of an invalid multiplier \"\n\t\t\t<< distribution[3] );\n\n    {\n      double multiplier;\n      \n      std::istringstream iss( distribution[3] );\n      Teuchos::extractDataFromISS( iss, multiplier );\n\n      setQuantity( d_multiplier, multiplier );\n    }\n\n    TEST_FOR_EXCEPTION( DMQT::isnaninf( d_multiplier ),\n\t\t\tInvalidDistributionStringRepresentation,\n\t\t\t\"Error: the Maxwell Fission distribution cannot be \"\n\t\t\t\"constructed because of an invalid multiplier \"\n\t\t\t<< getRawQuantity( d_multiplier ) );\n  }\n\n  // Calculate the normalization constant\n  this->calculateNormalizationConstant();\n}\n\n// Method for testing if two objects are equivalent\ntemplate<typename IndependentUnit, typename DependentUnit>\nbool UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>::isEqual( const UnitAwareMaxwellFissionDistribution<IndependentUnit,DependentUnit>& other ) const\n{\n  return d_incident_energy == other.d_incident_energy &&\n    d_nuclear_temperature == other.d_nuclear_temperature &&\n    d_restriction_energy == other.d_restriction_energy && \n    d_multiplier == other.d_multiplier;\n}\n\n} // end Utility namespace\n\n#endif // end UTILITY_MAXWELL_FISSION_DISTRIBUTION_DEF_HPP\n\n//---------------------------------------------------------------------------//\n// end Utility_MaxwellFissionDistribution_def.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "8ef86234bfcae1c0a6514e46f7b14225d57689a0", "size": 22434, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/utility/distribution/src/Utility_MaxwellFissionDistribution_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/utility/distribution/src/Utility_MaxwellFissionDistribution_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/utility/distribution/src/Utility_MaxwellFissionDistribution_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": 42.8948374761, "max_line_length": 333, "alphanum_fraction": 0.7685655701, "num_tokens": 4978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.29121016590677296}}
{"text": "/*======================================================================\nCopyright 2019 Google LLC\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    https://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n======================================================================*/\n\n\n#include <cmath>\n\n#include <Eigen/Dense>\n#include \"PCV_Types.h\"\n\n#include \"Servo_Timer.h\"\n#include \"Home.h\"\n#include \"Caster.h\"\n#include \"Vehicle.h\"\n\n\n#define N_2X2_MATRIX  \\\n    double N_00 = -cstr[i]->Ns; \\\n    double N_10 = -cstr[i]->Nt; \\\n    double N_11 =  cstr[i]->Nt * cstr[i]->Nw;\n\n#define Ni_2X2_MATRIX  \\\n    double Ni_00 = -1.0/cstr[i]->Ns; \\\n    double Ni_10 = -1.0/(cstr[i]->Ns * cstr[i]->Nw); \\\n    double Ni_11 =  1.0/(cstr[i]->Nt * cstr[i]->Nw);\n\nusing namespace std;\nusing namespace Eigen;\n\n// SINGLETON\nstatic Vehicle* gVehicle = NULL;\n\nbool\nVehicle::IsValid() const\n{ return gVehicle ? true : false;\n}\n\nVehicle*\nVehicle::HandleGet()\n{\n  if( gVehicle == NULL )\n  {\n    if( !( gVehicle = new Vehicle() ) ||\n        !gVehicle->IsValid() )\n    {\n      return NULL;\n    }\n  }\n  return gVehicle;\n}\n\n\nVehicle::Vehicle()\n  :Lambda(M3Z),Mu(V3Z),\n   X_veh(0),Y_veh(0),M_veh(0),I_veh(0),num_casters(0),\n   L_veh(M3Z),Mu_veh(V3Z),M_gross(0.0),I_gross(0.0),X_gross(0.0),Y_gross(0.0)\n{\n  hwi_ = HWInterface::HandleGet();\n\n  return;\n}\n\nVehicle::~Vehicle()\n{\n  // SHOULD SET DAC's TO ZERO HERE,\n  // BUT, FOR NOW, LET WATCHDOG DO IT FOR US\n\n  gVehicle = NULL; // SINGLETON\n\n  for( int i=0; i<num_casters; i++ )\n  {\n    delete cstr[i];\n  }\n  num_casters = 0;\n}\n\n\nvoid\nVehicle::Home()\n{\n  ::Home( cstr[0]->enc_offset,\n          cstr[1]->enc_offset,\n          cstr[2]->enc_offset,\n          cstr[3]->enc_offset);\n}\n\n\nvoid\nVehicle::Add_Caster( double _Kx, double _Ky, double _ang,\n                     double  _b, double  _r,\n                     double  _f, double _Mf, double _If,\n                     double _Ih, double _Ii, double _Is, double _It, double _Ij,\n                     double _Ns, double _Nt, double _Nw,\n                     double _px, double _py, double _Mp, double _Ip)\n{\n  cstr[num_casters] = new Caster( _Kx, _Ky, _ang,\n                                   _b,  _r,\n                                  _f, _Mf, _If,\n                                  _Ih, _Ii, _Is, _It, _Ij,\n                                  _Ns, _Nt, _Nw,\n                                  _px, _py, _Mp, _Ip);\n  num_casters++;\n\n  Add_Gross( _Kx, _Ky, _Mf+_Mp, _Ih+_Ii+_Is+_It+_Ij); // approximate only\n}\n\n\nvoid\nVehicle::JointRad(Vector8d &jRad)\n{\n  jRad.setZero();\n  return;\n  ENC_REGISTER e[8];\n  hwi_->EncReadAll(e); // LATCHed by HWInterface\n\n  for( int i=0; i<num_casters; i++ )\n  {\n    Ni_2X2_MATRIX;\n\n    int j = 2*i;\n\n    jRad[ j ] = -(Ni_00*e[j]               )*ENC_CNT2RAD;\n    jRad[j+1] = -(Ni_10*e[j] + Ni_11*e[j+1])*ENC_CNT2RAD;\n// NOTE: MINUS SIGN DUE TO DIRECTION OF ENCODERS\n// NOTE: ENCODERS GIVE OPPOSITE SIGN OF MOTOR ROTATION\n\n    cstr[i]->a = jRad[j];\n    cstr[i]->c = cos(jRad[j]);\n    cstr[i]->s = sin(jRad[j]);\n  }\n}\n\n\nvoid\nVehicle::MotorTq(Vector8d const &mtq)\n/*** Each motor will produce the specified torque ***/\n/*** tq should be a vector of 8 entries in Nm ***/\n{\n  long counts;\n\n  for( unsigned char j=0; j<2*num_casters; j++ )\n  {\n    counts =(long)( mtq[j] * (1.0/Nm_PER_AMP) * (1.0/AMPS_PER_VOLT) * COUNTS_PER_VOLT );\n    hwi_->RawDAC(j,counts); // RawDAC will check MAX/MIN values\n  }\n}\n\n\nvoid\nVehicle::JointTq(Vector8d const &jtq)\n/*** tq should be a vector of 8 entries in Nm ***/\n{\n  static Vector8d mtq;\n\n  for(int i=0; i<num_casters; i++ )\n  {\n    Ni_2X2_MATRIX;\n\n    int j = 2*i;\n    mtq[ j ] = Ni_00 * jtq[ j ] + Ni_10 * jtq[j+1];\n    mtq[j+1] =                    Ni_11 * jtq[j+1];\n  }\n  MotorTq(mtq);\n}\n\n\n// FOR DATA COLLECTION CONVENIENCE ONLY\nvoid\nVehicle::JtTq2MotAmp(Vector8d const &jtq, Vector8d &motAmp)\n{\n  static Vector8d mtq;\n  for(int i=0; i<num_casters; i++ )\n  {\n    Ni_2X2_MATRIX;\n    int j = 2*i;\n    mtq[ j ] = Ni_00 * jtq[ j ] + Ni_10 * jtq[j+1];\n    mtq[j+1] =                    Ni_11 * jtq[j+1];\n  }\n  motAmp = mtq * (1.0/Nm_PER_AMP);\n}\n\n\n// CONSTRAINT MATRIX\n\nvoid\nVehicle::Fill_C(Matrix3d &C)\n{\n  for(int i=0; i<num_casters ; i++ )\n  {\n    double bi = cstr[i]->bi;\n    double ri = cstr[i]->ri;\n    double c  = cstr[i]->c;\n    double s  = cstr[i]->s;\n    double Kx = cstr[i]->Kx;\n    double Ky = cstr[i]->Ky;\n\n    int j = 2*i;\n\n    C( j ,0) =   bi*s;\n    C( j ,1) =  -bi*c;\n    C( j ,2) =  -bi*(Kx*c+Ky*s) - 1.0;\n\n    C(j+1,0) =   ri*c;\n    C(j+1,1) =   ri*s;\n    C(j+1,2) =   ri*(Kx*s-Ky*c);\n  }\n}\n\n\n// JACOBIAN VIA C.P.'s to minimize slip in odometry\n// USE Jt_cp to minimize contact forces\n\nvoid\nVehicle::Fill_Jcp(Matrix3x8d &J)\n{\n  int i;\n  static Matrix8x3d  Cp;\n  static Matrix3x8d  CptCli;\n  static Matrix3d    J;\n\n  for( i=0; i<num_casters; i++ )\n  {   // Cli IS 2x2 BLOCK DIAGONAL, SO MULTIPLY\n      // IN PIECES TO AVOID SLOW NxN MATRIX OPERATIONS\n    double b = cstr[i]->b;\n    double r = cstr[i]->r;\n    double c = cstr[i]->c;\n    double s = cstr[i]->s;\n    double Kx= cstr[i]->Kx;\n    double Ky= cstr[i]->Ky;\n\n    int j = 2*i;\n\n    // Note: sign of p-dot is: wheel as viewed from ground\n\n    CptCli(0, j ) =  b*s;\n    CptCli(0,j+1) =  r*c;\n    CptCli(1, j ) = -b*c;\n    CptCli(1,j+1) =  r*s;\n    CptCli(2, j ) = -b*((Kx*c+Ky*s)+b);\n    CptCli(2,j+1) =  r* (Kx*s-Ky*c);\n\n    Cp( j ,0) =  1.0;\n    Cp( j ,1) =  0.0;\n    Cp( j ,2) = -b*s - Ky;\n\n    Cp(j+1,0) =  0.0;\n    Cp(j+1,1) =  1.0;\n    Cp(j+1,2) =  b*c + Kx;\n  }\n\n  // J = inv(Cpt*Cp)*Cpt * inv(Cl)\n  // J = inv(Cpt*Cp)*CptCli\n  J = (Cp.transpose()*Cp).llt().solve(CptCli);\n}\n\n\n// JACOBIAN to Minimize Motor Torques\n\nvoid\nVehicle::Fill_Jt_gamma(Matrix8x3d &Jt)\n{\n  int i;\n  static Matrix8x3d C    = Matrix8x3d::Zero();\n  static Matrix8x3d NC   = Matrix8x3d::Zero();\n  static Matrix3x8d NCtN = Matrix3x8d::Zero();\n\n  Fill_C( C );\n\n  for( i=0; i<num_casters ; i++ )\n  {   // N IS 2x2 BLOCK DIAGONAL, SO MULTIPLY\n      // IN PIECES TO AVOID SLOW NxN MATRIX OPERATIONS\n    N_2X2_MATRIX;\n\n    int j = 2*i;\n\n    NC( j ,0)   = N_00* C(j,0);\n    NC( j ,1)   = N_00* C(j,1);\n    NC( j ,2)   = N_00* C(j,2);\n    NC(j+1,0)   = N_10* C(j,0) + N_11* C(j+1,0);\n    NC(j+1,1)   = N_10* C(j,1) + N_11* C(j+1,1);\n    NC(j+1,2)   = N_10* C(j,2) + N_11* C(j+1,2);\n\n    NCtN(0, j ) = NC(j,0)*N_00 + NC(j+1,0)*N_10;\n    NCtN(1, j ) = NC(j,1)*N_00 + NC(j+1,1)*N_10;\n    NCtN(2, j ) = NC(j,2)*N_00 + NC(j+1,2)*N_10;\n    NCtN(0,j+1) =                NC(j+1,0)*N_11;\n    NCtN(1,j+1) =                NC(j+1,1)*N_11;\n    NCtN(2,j+1) =                NC(j+1,2)*N_11;\n  }\n\n  // wdot = Cn xdot ; wdot = N qdot ; qdot = C xdot\n  // J_gamma = Cn# N   ; Cn = N C\n  // J_gamma  = [(NC)t * NC]i * (NC)t N\n  // Jt_gamma = J_gamma.transpose()\n\n  Jt = ( (NC.transpose()*NC).llt().solve(NCtN) ).transpose()\n\n}\n\n\n// JACOBIAN FOR VIRTUAL LINKAGE AT CONTACT POINTS\n\n\nvoid\nVehicle::Fill_E_p(MatrixXd &E)\n{\n  int i,j;\n  double ex, ey, mag_inv;\n  double pix, pjx, piy, pjy;\n\n  // DESCRIBE CONNECTIONS OF VIRTUAL TRUSS\n\n//   int pi[NUM_TRUSS_LINKS]={0,1,2,3,1};\n//   int pj[NUM_TRUSS_LINKS]={1,2,3,0,3};\n  int pi[NUM_TRUSS_LINKS]={0,3,1,2,1,2};\n  int pj[NUM_TRUSS_LINKS]={3,1,2,0,0,3};\n\n  for( int k=0; k<NUM_TRUSS_LINKS; k++ )\n  {\n    i = pi[k];\n    j = pj[k];\n\n    pix = cstr[i]->Kx + cstr[i]->b*cstr[i]->c;\n    pjx = cstr[j]->Kx + cstr[j]->b*cstr[j]->c;\n\n    piy = cstr[i]->Ky + cstr[i]->b*cstr[i]->s;\n    pjy = cstr[j]->Ky + cstr[j]->b*cstr[j]->s;\n\n    ex = pix - pjx;\n    ey = piy - pjy;\n    mag_inv = 1.0/hypot(ex,ey);\n    E(k, 2*i  ) = ex * mag_inv;\n    E(k, 2*i+1) = ey * mag_inv;\n    E(k, 2*j  ) =  -E(k, 2*i  );\n    E(k, 2*j+1) =  -E(k, 2*i+1);\n  }\n\n}\n\n\nvoid\nVehicle::Fill_E_q(MatrixXd &E)\n{\n  int j = 2*num_casters;\n\n  MatrixXd Ep(NUM_TRUSS_LINKS,j);\n  MatrixXd Cli(j,j);\n  // q_dot = Cl * p_dot ==> p_dot = Cli * q_dot\n  // eps_dot = Ep * p_dot\n  // eps_dot = Ep * Cli * q_dot ==> E_q = Ep * Cli\n\n  Fill_E_p( Ep );\n  for(int i=0; i<num_casters; i++ )\n  {\n    j = 2*i;\n    Cli( j , j ) =  cstr[i]->b*cstr[i]->s;\n    Cli( j ,j+1) =  cstr[i]->r*cstr[i]->c;\n\n    Cli(j+1, j ) = -cstr[i]->b*cstr[i]->c;\n    Cli(j+1,j+1) =  cstr[i]->r*cstr[i]->s;\n  }\n\n  E = Ep * Cli;\n\n}\n\n\nvoid\nVehicle::Add_Solid(double _x, double _y,\n                   double _M, double _I)\n{\n\n  // COMPUTE NEW veh QUANTITIES w/ ARGS AND PREVIOUS M & I\n  X_veh  = (M_veh * X_veh + _M * _x) / (M_veh + _M);\n  Y_veh  = (M_veh * Y_veh + _M * _y) / (M_veh + _M);\n  M_veh += _M;  // TOTAL veh MASS\n  I_veh += _I +_M*(pow(_x,2) + pow(_y,2));  // new I at (0,0) local coords\n\n  // COMPUTE NEW VEHICLE MASS MATRIX L_veh\n  // (ie Lambda_Vehicle for fixed parts not including Casters)\n  L_veh(0,0) =  M_veh;\n  L_veh(0,1) =  0.0;\n  L_veh(0,2) = -M_veh * Y_veh;\n\n  L_veh(1,0) =  0.0;\n  L_veh(1,1) =  M_veh;\n  L_veh(1,2) =  M_veh * X_veh;\n\n  L_veh(2,0) =  L_veh.at(0,2);\n  L_veh(2,1) =  L_veh.at(1,2);\n  L_veh(2,2) =  I_veh;\n\n  Add_Gross(_x,_y,_M,_I);\n}\n\n\nvoid\nVehicle::Add_Gross(double _x, double _y,\n                   double _M, double _I)\n{\n  // COMPUTE NEW ESTIMATES FOR GROSS MASS AND INERTIA (includes Casters)\n  X_gross  = (M_gross * X_gross + _M * _x) / (M_gross + _M);\n  Y_gross  = (M_gross * Y_gross + _M * _y) / (M_gross + _M);\n  M_gross += _M;\n  I_gross += _I +_M*(pow(_x,2) + pow(_y,2));  // new I at (0,0) local coords\n}\n\n\ninline void\nVehicle::Fill_Mu_veh( double w )\n{\n  register double w2 = pow(w,2);\n\n  // (ie Mu_Vehicle for fixed parts not including Casters)\n  Mu_veh(0)  = -M_veh * X_veh * w2;\n  Mu_veh(1)  = -M_veh * Y_veh * w2;\n  Mu_veh(2)  =  0.0;\n}\n\n\nvoid\nVehicle::Dyn(Vector8d qd, double w)\n{\n  // INITIALIZE TO VEHICLE PROPERTIES\n  Lambda = L_veh;\n  Fill_Mu_veh( w );\n  Mu = Mu_veh;\n\n  // ADD DYNAMICS FROM THE CASTERS\n  for(int i=0; i<num_casters; i++)\n  { int j = 2*i;\n    cstr[i]->Fill_LM(qd[j],qd[j+1],w);\n    Lambda += cstr[i]->Lambda;\n    Mu += cstr[i]->Mu;\n  }\n}\n\n\nVector3d\nVehicle::Fill_tqS(Vector8d const &qd, Vector8d const &tq,\n                  Vector8d &tqS)\n{\n  // Experimental function to compute operational force to compensate for\n  // rotational friction of the wheel contact patches.\n\n  int i,j;\n  double m,b,frd,atq,tqX;\n//   double bM[4] = {0.35, 0.57, 0.35, 0.57};\n//   double mM[4] = {0.21, 0.17, 0.21, 0.17};\n//   double tqM   = 0.35;\n  double rdM   = 25.0;\n  double bM[4] = {0.20, 0.50, 0.20, 0.50};\n  double mM[4] = {0.10, 0.10, 0.10, 0.10};\n  double tqM   = 0.60;\n\n  double tqA = 0.0;\n  static Vector3d fS = Vector3d::Zero();\n\n  for(i=0; i<num_casters; i++)\n  { j = 2*i;\n    frd = 1.0 - fabs(qd[j+1])/rdM;\n    b = bM[i]*frd;\n    m = mM[i]*frd;\n    atq = fabs(tq[j]);\n    tqX = atq<tqM ? atq/tqM : 1.0;\n    tqS[j] = (m*qd[j] + (qd[j]>0?b:-b)) * tqX;\n    tqA += tqS[j];\n  }\n\n  fS[2] = tqA;\n  return fS;\n}\n", "meta": {"hexsha": "290899b8b45b3a6a50fb5abfe79ec6d2b52e1d63", "size": 11089, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Vehicle.cpp", "max_stars_repo_name": "google/powered-caster-vehicle", "max_stars_repo_head_hexsha": "ad231909e8cbe6785dbf682aac6bbe33797f92c8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-05-30T17:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-14T08:34:10.000Z", "max_issues_repo_path": "Vehicle.cpp", "max_issues_repo_name": "google/powered-caster-vehicle", "max_issues_repo_head_hexsha": "ad231909e8cbe6785dbf682aac6bbe33797f92c8", "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": "Vehicle.cpp", "max_forks_repo_name": "google/powered-caster-vehicle", "max_forks_repo_head_hexsha": "ad231909e8cbe6785dbf682aac6bbe33797f92c8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-30T18:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-16T23:17:59.000Z", "avg_line_length": 22.8639175258, "max_line_length": 88, "alphanum_fraction": 0.5465776896, "num_tokens": 4385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.29121016590677296}}
{"text": "﻿//*****************************************************************************\r\n//*****************************************************************************\r\n// Class: CLaricobiusOsakensis\r\n//          \r\n//\r\n// Description: the CLaricobiusOsakensis represents a group of LNF insect. scale by m_ScaleFactor\r\n//*****************************************************************************\r\n// 07/07/2021   Rémi Saint-Amant    Creation\r\n//*****************************************************************************\r\n\r\n#include \"LaricobiusOsakensisEquations.h\"\r\n#include \"LaricobiusOsakensis.h\"\r\n#include <boost/math/distributions/weibull.hpp>\r\n#include <boost/math/distributions/logistic.hpp>\r\n\r\nusing namespace std;\r\nusing namespace WBSF::HOURLY_DATA;\r\nusing namespace WBSF::LOF;\r\n\r\n\r\nnamespace WBSF\r\n{\r\n\r\n\t//*********************************************************************************\r\n\t//CLaricobiusOsakensis class\r\n\r\n\r\n\t//*****************************************************************************\r\n\t// Object creator\r\n\t//\r\n\t// Input: See CIndividual creator\r\n\t//\r\n\t// Note: m_RDR (relative Development Rate)  member is init with random values.\r\n\t//*****************************************************************************\r\n\tCLaricobiusOsakensis::CLaricobiusOsakensis(CHost* pHost, CTRef creationDate, double age, TSex sex, bool bFertil, size_t generation, double scaleFactor) :\r\n\t\tCIndividual(pHost, creationDate, age, sex, bFertil, generation, scaleFactor)\r\n\t{\r\n\t\t//reset creation date\r\n\t\tint year = creationDate.GetYear();\r\n\t\tm_creationDate = GetCreationDate(year);\r\n\t\tm_adult_emergence = GetAdultEmergence(year + 1);\r\n\r\n\t\tfor (size_t s = 0; s < NB_STAGES; s++)\r\n\t\t\tm_RDR[s] = Equations().GetRelativeDevRate(s);\r\n\r\n\t\tm_t = 0;\r\n\t\tm_Fi = (m_sex == FEMALE) ? Equations().GetFecondity() : 0;\r\n\t\tm_bDeadByAttrition = false;\r\n\t}\r\n\r\n\tCTRef CLaricobiusOsakensis::GetCreationDate(int year)const\r\n\t{\r\n\t\tCTRef creationDate;\r\n\t\tdouble creationCDD = Equations().GetCreationCDD();\r\n\r\n\t\tconst CWeatherStation& weather_station = GetStand()->GetModel()->m_weather;\r\n\t\t//CTRef begin = CTRef(year, JANUARY, DAY_01);\r\n\t\t//CTRef end = CTRef(year, JUNE, DAY_30);\r\n\r\n\t\tCTRef begin = CTRef(year, DECEMBER, DAY_01);\r\n\t\tCTRef end = CTRef(year+1, AUGUST, DAY_31);\r\n\r\n\t\tdouble CDD = 0;\r\n\t\tfor (CTRef TRef = begin; TRef <= end && !creationDate.IsInit(); TRef++)\r\n\t\t{\r\n\t\t\tconst CWeatherDay& wDay = weather_station.GetDay(TRef);\r\n\t\t\tdouble DD = GetStand()->m_DD.GetDD(wDay);\r\n\t\t\tCDD += DD;\r\n\r\n\t\t\tif (CDD  >= creationCDD)\r\n\t\t\t{\r\n\t\t\t\tcreationDate = wDay.GetTRef();\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (!creationDate.IsInit())\r\n\t\t\tcreationDate = end;//for text only\r\n\r\n\t\tASSERT(creationDate.IsInit());\r\n\r\n\t\treturn creationDate;\r\n\t}\r\n\r\n\tCTRef CLaricobiusOsakensis::GetAdultEmergence(int year)const\r\n\t{\r\n\t\tconst CWeatherStation& weather_station = GetStand()->GetModel()->m_weather;\r\n\t\tCTPeriod p = weather_station.GetEntireTPeriod(CTM::DAILY);\r\n\r\n\t\tCTRef adult_emergence;\r\n\t\tdouble adult_emerging_CDD = Equations().GetAdultEmergingCDD();\r\n\r\n\t\tCTRef begin = GetStand()->m_diapause_end;\r\n\t\tCTRef end = p.End();\r\n\t\tif (weather_station[year].HaveNext())\r\n\t\t\tend = min(p.End(), CTRef(begin.GetYear() + 1, JANUARY, DAY_31));\r\n\r\n\t\tdouble CDD = 0;\r\n\t\tfor (CTRef TRef = begin; TRef <= end && !adult_emergence.IsInit(); TRef++)\r\n\t\t{\r\n\t\t\tconst CWeatherDay& wday = weather_station.GetDay(TRef);\r\n\t\t\tdouble T = wday[H_TNTX][MEAN];\r\n\t\t\tdouble DD = max(0.0, T - Equations().m_EAS[Τᴴ]);\r\n\t\t\tCDD += DD;\r\n\t\t\tif (CDD >= adult_emerging_CDD)\r\n\t\t\t{\r\n\t\t\t\tadult_emergence = wday.GetTRef();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//if (!adult_emergence.IsInit())\r\n\t\t\t//adult_emergence = CTRef(year, DECEMBER, DAY_31);//pour test seulement a revoir...\r\n\r\n\t\t//ASSERT(adult_emergence.IsInit());\r\n\t\treturn adult_emergence;\r\n\t}\r\n\r\n\tCLaricobiusOsakensis& CLaricobiusOsakensis::operator=(const CLaricobiusOsakensis& in)\r\n\t{\r\n\t\tif (&in != this)\r\n\t\t{\r\n\t\t\tCIndividual::operator=(in);\r\n\r\n\t\t\t//new relative developement rate\r\n\t\t\tfor (size_t s = 0; s < NB_STAGES; s++)\r\n\t\t\t\tm_RDR[s] = Equations().GetRelativeDevRate(s);\r\n\r\n\r\n\t\t\tm_dropToGroundDate = in.m_dropToGroundDate;\r\n\t\t\tm_adult_emergence = in.m_adult_emergence;\r\n\t\t\tm_reachDate = in.m_reachDate;\r\n\t\t\tm_t = in.m_t;\r\n\t\t\tm_Fi = in.m_Fi;\r\n\t\t\tm_bDeadByAttrition = in.m_bDeadByAttrition;\r\n\t\t}\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\t//destructor\r\n\tCLaricobiusOsakensis::~CLaricobiusOsakensis(void)\r\n\t{}\r\n\r\n\r\n\r\n\r\n\tvoid CLaricobiusOsakensis::OnNewDay(const CWeatherDay& weather)\r\n\t{\r\n\t\tCIndividual::OnNewDay(weather);\r\n\r\n\t\tif (weather.GetTRef() == m_creationDate)\r\n\t\t{\r\n\t\t\tm_age = EGG;\r\n\t\t}\r\n\t}\r\n\r\n\t//*****************************************************************************\r\n\t// Develops all stages for one time step\r\n\t// Input:\tweather: weather of the hour\r\n\t//\t\t\ttimeStep: timeStep [h]\r\n\t//*****************************************************************************\r\n\tvoid CLaricobiusOsakensis::Live(const CHourlyData& weather, size_t timeStep)\r\n\t{\r\n\t\tassert(IsAlive());\r\n\t\tassert(m_status == HEALTHY);\r\n\r\n\t\tCLNFHost* pHost = GetHost();\r\n\t\tCLNFStand* pStand = GetStand();\r\n\r\n\t\tdouble nb_steps = (24.0 / timeStep);\r\n\t\tsize_t h = weather.GetTRef().GetHour();\r\n\t\tsize_t s = GetStage();\r\n\r\n\t\tdouble T = weather[H_TAIR];\r\n\t\t//T = AdjustTLab(weather.GetWeatherStation()->m_name, s, weather.GetTRef(), T);\r\n\r\n\t\tdouble day_length = weather.GetLocation().GetDayLength(weather.GetTRef()) / 3600.0;//[h]\r\n\r\n\t\tif (s < AESTIVAL_DIAPAUSE_ADULT || s == ACTIVE_ADULT)\r\n\t\t{\r\n\t\t\t//Time step development rate\r\n\t\t\tdouble r = Equations().GetRate(s, T) / nb_steps;\r\n\r\n\t\t\t//double corr_r = (s == EGG || s == LARVAE) ? : 1;\r\n\r\n\t\t\t//Relative development rate for this individual\r\n\t\t\tdouble rr = m_RDR[s];\r\n\r\n\t\t\t//Time step development rate for this individual\r\n\t\t\tr *= rr;\r\n\t\t\tASSERT(r >= 0 && r < 1);\r\n\r\n\t\t\t//Adjust age\r\n\t\t\tm_age += r;\r\n\r\n\t\t\tif (!m_dropToGroundDate.IsInit() && m_age > LARVAE4 + 0.9)//drop to the soil when 90% competed (guess)\r\n\t\t\t\tm_dropToGroundDate = weather.GetTRef().as(CTM::DAILY);\r\n\r\n\t\t\t//evaluate attrition once a day\r\n\t\t\tif (GetStand()->m_bApplyAttrition)\r\n\t\t\t{\r\n\t\t\t\tif (IsDeadByAttrition(s, T, r))\r\n\t\t\t\t\tm_bDeadByAttrition = true;\r\n\t\t\t}\r\n\r\n\t\t}\r\n\t\telse if (s == AESTIVAL_DIAPAUSE_ADULT)\r\n\t\t{\r\n\t\t\tCTRef TRef = weather.GetTRef().as(CTM::DAILY);\r\n\t\t\tif (TRef == m_adult_emergence)\r\n\t\t\t\tm_age = ACTIVE_ADULT;\r\n\t\t}\r\n\r\n\t\tif (m_sex == FEMALE && GetStage() >= ACTIVE_ADULT)\r\n\t\t{\r\n\t\t\tdouble to = 0;\r\n\t\t\tdouble t = timeStep / 24.0;\r\n\t\t\tdouble λ = Equations().GetFecondityRate(GetAge(), weather[H_TAIR]);\r\n\t\t\tdouble brood = m_Fi * (exp(-λ * (m_t - to)) - exp(-λ * (m_t + t - to)));\r\n\r\n\t\t\tm_broods += brood;\r\n\t\t\tm_totalBroods += brood;\r\n\r\n\t\t\tm_t += t;\r\n\t\t}\r\n\t\t//else//ACTIVE_ADULT\r\n\t\t//{\r\n\t\t//\tdouble r = (1.0 / m_adult_longevity) / nb_steps;\r\n\t\t//\tASSERT(r >= 0 && r < 1);\r\n\r\n\t\t//\tm_age += r;\r\n\t\t//}\r\n\t}\r\n\r\n\r\n\r\n\r\n\t//*****************************************************************************\r\n\t// Develops all stages, including adults\r\n\t// Input:\tweather: the weather of the day\r\n\t//*****************************************************************************\r\n\tvoid CLaricobiusOsakensis::Live(const CWeatherDay& weather)\r\n\t{\r\n\t\tCIndividual::Live(weather);\r\n\r\n\t\tASSERT(IsCreated(weather.GetTRef()));\r\n\r\n\t\tif (!IsCreated(weather.GetTRef()))\r\n\t\t\treturn;\r\n\r\n\t\tsize_t nbSteps = GetTimeStep().NbSteps();\r\n\t\tfor (size_t step = 0; step < nbSteps&&IsAlive(); step++)\r\n\t\t{\r\n\t\t\tsize_t h = step * GetTimeStep();\r\n\t\t\tLive(weather[h], GetTimeStep());\r\n\t\t}\r\n\r\n\t\tif (weather.GetTRef() == m_creationDate || HasChangedStage())\r\n\t\t\tm_reachDate[GetStage()] = weather.GetTRef();\r\n\r\n\r\n\t}\r\n\r\n\r\n\tvoid CLaricobiusOsakensis::Brood(const CWeatherDay& weather)\r\n\t{\r\n\t\tassert(/*IsAlive() &&*/ m_sex == FEMALE);\r\n\r\n\r\n\t\tif (GetStage() == ACTIVE_ADULT)\r\n\t\t{\r\n\t\t\t//no brood process done\r\n\r\n\t\t\t//brooding\r\n\t\t\t//m_broods = m_F;\r\n\t\t\t//m_totalBroods = m_F;\r\n\t\t\t//m_F = 0;\r\n\t\t\t//m_F -= m_F * r;\r\n\t\t}\r\n\t}\r\n\r\n\t// kills by old age and frost\r\n\t// Output:  Individual's state is updated to follow update\r\n\tvoid CLaricobiusOsakensis::Die(const CWeatherDay& weather)\r\n\t{\r\n\t\t//attrition mortality. Killed at the end of time step \r\n\r\n\t\tif (m_bDeadByAttrition)\r\n\t\t{\r\n\t\t\tm_status = DEAD;\r\n\t\t\tm_death = ATTRITION;\r\n\t\t}\r\n\t\telse if (GetStage() == DEAD_ADULT)\r\n\t\t{\r\n\t\t\t//Old age\r\n\t\t\tm_status = DEAD;\r\n\t\t\tm_death = OLD_AGE;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t//size_t s = GetStage();\r\n\r\n\t\t\t////Preliminary assessment of the cold tolerance of Laricobius Osakensis, a winter - active predator of the hemlock woolly adelgid from western canada\r\n\t\t\t////Leland M.Humble\r\n\t\t\t//static const double COLD_TOLERENCE_T[NB_STAGES] = { -27.5,-22.1, -99.0,-99.0,-19.0,-19.0 };\r\n\t\t\t////Toland:L. Osakensis was -13.6 oC (± 0.5) with temperatures that ranged from -6 oC to -21 oC.\r\n\t\t\t//if (weather[H_TMIN][MEAN] < COLD_TOLERENCE_T[s])\r\n\t\t\t//{\r\n\t\t\t//\tm_status = DEAD;\r\n\t\t\t//\tm_death = FROZEN;\r\n\t\t\t//}\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t//s: stage\r\n\t//T: temperature for this time step\r\n\t//r: devlopement rate for this time step\r\n\tbool CLaricobiusOsakensis::IsDeadByAttrition(size_t s, double T, double r)const\r\n\t{\r\n\t\tbool bDeath = false;\r\n\r\n\t\t//daily survival\r\n\t\tdouble ds = GetStand()->m_equations.GetDailySurvivalRate(s, T);\r\n\r\n\t\t//time step survival\r\n\t\tdouble S = pow(ds, r);\r\n\r\n\t\t//Computes attrition (probability of survival in a given time step, based on development rate)\r\n\t\tif (RandomGenerator().RandUniform() > S)\r\n\t\t\tbDeath = true;\r\n\r\n\t\treturn bDeath;\r\n\t}\r\n\r\n\r\n\r\n\t//*****************************************************************************\r\n\t// GetStat gather information of this object\r\n\t//\r\n\t// Input: stat: the statistic object\r\n\t// Output: The stat is modified\r\n\t//*****************************************************************************\r\n\tvoid CLaricobiusOsakensis::GetStat(CTRef d, CModelStat& stat)\r\n\t{\r\n\t\tif (IsCreated(d))\r\n\t\t{\r\n\t\t\tsize_t s = GetStage();\r\n\t\t\tASSERT(s <= DEAD_ADULT);\r\n\r\n\t\t\tif (IsAlive() || (s == DEAD_ADULT))\r\n\t\t\t\tstat[S_EGG + s] += m_scaleFactor;\r\n\r\n\t\t\tstat[S_LARVAE] = stat[S_L1]+ stat[S_L2]+ stat[S_L3]+ stat[S_L4];\r\n\t\t\t\r\n\t\t\tif (HasChangedStatus() && m_status == DEAD && m_death == ATTRITION)\r\n\t\t\t\tstat[S_DEAD_ATTRTION] += m_scaleFactor;\r\n\r\n\t\t\tif (HasChangedStage())\r\n\t\t\t\tstat[S_M_EGG + s] += m_scaleFactor;\r\n\r\n\t\t\t\r\n\t\t\t//if (s == ACTIVE_ADULT)\r\n\t\t\t//{\r\n\t\t\t//\tstat[S_ADULT_ABUNDANCE] += m_scaleFactor * m_adult_abundance;\r\n\t\t\t//}\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tvoid CLaricobiusOsakensis::Pack(const CIndividualPtr& pBug)\r\n\t{\r\n\t\tassert(m_sex == pBug->GetSex());\r\n\r\n\t\tCLaricobiusOsakensis* in = (CLaricobiusOsakensis*)(pBug.get());\r\n\t\tCIndividual::Pack(pBug);\r\n\t}\r\n\r\n\tdouble CLaricobiusOsakensis::GetInstar(bool includeLast)const\r\n\t{\r\n\t\treturn (IsAlive() || m_death == OLD_AGE) ? GetStage() : CBioSIMModelBase::VMISS;\r\n\t}\r\n\r\n\t//*********************************************************************************************************************\r\n\r\n\t//*********************************************************************************\r\n\t//CLNFHost\r\n\r\n\tCLNFHost::CLNFHost(CStand* pStand) :\r\n\t\tCHost(pStand)\r\n\t{\r\n\t}\r\n\r\n\r\n\tvoid CLNFHost::Live(const CWeatherDay& weather)\r\n\t{\r\n\t\tCHost::Live(weather);\r\n\t}\r\n\r\n\tvoid CLNFHost::GetStat(CTRef d, CModelStat& stat, size_t generation)\r\n\t{\r\n\t\tCHost::GetStat(d, stat, generation);\r\n\t}\r\n\r\n\t//*************************************************\r\n\t//CLNFStand\r\n\r\n\tvoid CLNFStand::init(int year, const CWeatherYears& weather)\r\n\t{\r\n\t\tm_diapause_end = ComputeDiapauseEnd(weather[year]);\r\n\t}\r\n\r\n\tCTRef CLNFStand::ComputeDiapauseEnd(const CWeatherYear& weather)const\r\n\t{\r\n\t\tCTPeriod p = weather.GetEntireTPeriod(CTM::DAILY);\r\n\t\t//CTPeriod p = weather.GetPrevious().GetEntireTPeriod(CTM::DAILY);\r\n\r\n\t\tdouble sumDD = 0;\r\n\r\n\t\tfor (size_t ii = (m_equations.m_ADE[ʎ0] - 1); ii <= (m_equations.m_ADE[ʎ1] - 1); ii++)\r\n\t\t{\r\n\t\t\tCTRef TRef = p.Begin() + ii;\r\n\t\t\tconst CWeatherDay& wday = weather.GetDay(TRef);\r\n\t\t\tdouble T = wday[H_TNTX][MEAN];\r\n\t\t\tdouble DD = min(0.0, T - m_equations.m_ADE[ʎb]);//DD is negative\r\n\t\t\tsumDD += DD;\r\n\t\t}\r\n\r\n\t\tboost::math::logistic_distribution<double> diapause_end_dist(m_equations.m_ADE[ʎ2], m_equations.m_ADE[ʎ3]);\r\n\t\tint begin = (int)Round((m_equations.m_ADE[ʎ1] - 1) + m_equations.m_ADE[ʎa] * cdf(diapause_end_dist, sumDD), 0);\r\n\r\n\t\treturn p.Begin() + begin;\r\n\t}\r\n\r\n\r\n\r\n\tvoid CLNFStand::GetStat(CTRef d, CModelStat& stat, size_t generation)\r\n\t{\r\n\t\tCStand::GetStat(d, stat, generation);\r\n\r\n\t\tconst CWeatherStation& weather_station = GetModel()->m_weather;\r\n\t\tconst CWeatherDay& wday = weather_station.GetDay(d);\r\n\r\n\t\t//use year of diapause to compute correctly the adult emergence cdd\r\n\t\tint year = m_diapause_end.GetYear();\r\n\t\t\r\n\t\tCTRef begin = CTRef(year, JANUARY, DAY_01);\r\n\t\tCTRef end = CTRef(year, DECEMBER, DAY_31);\r\n\r\n\t\tif (d >= begin && d <= end)\r\n\t\t{\r\n\t\t\t//Egg creation DD (allen 1976)\r\n\t\t\t//m_egg_creation_CDD += m_DD.GetDD(wday);\r\n\t\t\t//stat[S_EGG_CREATION_CDD] = m_egg_creation_CDD;\r\n\r\n\t\t\t//diapause end negative DD\r\n\t\t\tdouble T = wday[H_TNTX][MEAN];\r\n\t\t\t//T = max(m_equations.m_ADE[ʎa], T);\r\n\t\t\tdouble NDD = min(0.0, T - m_equations.m_ADE[ʎb]);//DD is negative\r\n\r\n\t\t\tint ii = d - begin;\r\n\t\t\tif (ii >= int(m_equations.m_ADE[ʎ0] - 1) && ii <= int(m_equations.m_ADE[ʎ1] - 1))\r\n\t\t\t\tm_diapause_end_NCDD += NDD;\r\n\r\n\t\t\tstat[S_DIAPAUSE_END_NCDD] = m_diapause_end_NCDD;\r\n\t\t}\r\n\r\n\r\n\t\tbegin = m_diapause_end;\r\n\t\tend = CTRef(m_diapause_end.GetYear() + 1, JANUARY, DAY_31);\r\n\t\tif (d >= begin && d <= end)\r\n\t\t{\r\n\t\t\t//adult emergence (growing DD)\r\n\t\t\tdouble T = wday[H_TNTX][MEAN];\r\n\t\t\tdouble GDD = max(0.0, T - m_equations.m_EAS[Τᴴ]);\r\n\t\t\tm_adult_emergence_CDD += GDD;\r\n\t\t\tstat[S_ADULT_EMERGENCE_CDD] = m_adult_emergence_CDD;\r\n\t\t}\r\n\r\n\t\t//compute egg creation\r\n\t\tbegin = CTRef(year-1, DECEMBER, DAY_01);\r\n\t\tend = CTRef(year, AUGUST, DAY_31);\r\n\r\n\t\tif (d >= begin && d <= end)\r\n\t\t{\r\n\t\t\t//Egg creation DD (allen 1976)\r\n\t\t\tm_egg_creation_CDD += m_DD.GetDD(wday);\r\n\t\t\tstat[S_EGG_CREATION_CDD] = m_egg_creation_CDD;\r\n\t\t}\r\n\t\t\r\n\r\n\t}\r\n\r\n\r\n}", "meta": {"hexsha": "3ca20f5b5a56d7409e4beeaa729974ef6db99367", "size": 13747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wbsModels/LaricobiusOsakensis/LaricobiusOsakensis.cpp", "max_stars_repo_name": "RNCan/WeatherBasedSimulationFramework", "max_stars_repo_head_hexsha": "19df207d11b1dddf414d78e52bece77f31d45df8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-05-26T21:19:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T14:17:29.000Z", "max_issues_repo_path": "wbsModels/LaricobiusOsakensis/LaricobiusOsakensis.cpp", "max_issues_repo_name": "RNCan/WeatherBasedSimulationFramework", "max_issues_repo_head_hexsha": "19df207d11b1dddf414d78e52bece77f31d45df8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-02-18T12:39:58.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-13T12:57:45.000Z", "max_forks_repo_path": "wbsModels/LaricobiusOsakensis/LaricobiusOsakensis.cpp", "max_forks_repo_name": "RNCan/WeatherBasedSimulationFramework", "max_forks_repo_head_hexsha": "19df207d11b1dddf414d78e52bece77f31d45df8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-16T02:49:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-16T02:49:20.000Z", "avg_line_length": 27.8843813387, "max_line_length": 155, "alphanum_fraction": 0.5815814359, "num_tokens": 4129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.29121015960654273}}
{"text": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <Eigen/Geometry>\n#include <arc_utilities/arc_helpers.hpp>\n#include <arc_utilities/eigen_typedefs.hpp>\n#include <map>\n#include <vector>\n\n#ifndef IIWA_14_FK_FAST_HPP\n#define IIWA_14_FK_FAST_HPP\n\nnamespace IIWA_14_FK_FAST {\nconst size_t IIWA_14_NUM_ACTIVE_JOINTS = 7;\nconst size_t IIWA_14_NUM_LINKS = 8;\n\nconst std::string IIWA_14_ACTIVE_JOINT_1_NAME = \"iiwa_joint_1\";\nconst std::string IIWA_14_ACTIVE_JOINT_2_NAME = \"iiwa_joint_2\";\nconst std::string IIWA_14_ACTIVE_JOINT_3_NAME = \"iiwa_joint_3\";\nconst std::string IIWA_14_ACTIVE_JOINT_4_NAME = \"iiwa_joint_4\";\nconst std::string IIWA_14_ACTIVE_JOINT_5_NAME = \"iiwa_joint_5\";\nconst std::string IIWA_14_ACTIVE_JOINT_6_NAME = \"iiwa_joint_6\";\nconst std::string IIWA_14_ACTIVE_JOINT_7_NAME = \"iiwa_joint_7\";\n\nconst std::string IIWA_14_LINK_1_NAME = \"iiwa_link_0\";\nconst std::string IIWA_14_LINK_2_NAME = \"iiwa_link_1\";\nconst std::string IIWA_14_LINK_3_NAME = \"iiwa_link_2\";\nconst std::string IIWA_14_LINK_4_NAME = \"iiwa_link_3\";\nconst std::string IIWA_14_LINK_5_NAME = \"iiwa_link_4\";\nconst std::string IIWA_14_LINK_6_NAME = \"iiwa_link_5\";\nconst std::string IIWA_14_LINK_7_NAME = \"iiwa_link_6\";\nconst std::string IIWA_14_LINK_8_NAME = \"iiwa_link_7\";\n\ninline Eigen::Isometry3d Get_link_0_joint_1_LinkJointTransform(const double joint_val) {\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\ninline Eigen::Isometry3d Get_link_1_joint_2_LinkJointTransform(const double joint_val) {\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\ninline Eigen::Isometry3d Get_link_2_joint_3_LinkJointTransform(const double joint_val) {\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\ninline Eigen::Isometry3d Get_link_3_joint_4_LinkJointTransform(const double joint_val) {\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\ninline Eigen::Isometry3d Get_link_4_joint_5_LinkJointTransform(const double joint_val) {\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\ninline Eigen::Isometry3d Get_link_5_joint_6_LinkJointTransform(const double joint_val) {\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\ninline Eigen::Isometry3d Get_link_6_joint_7_LinkJointTransform(const double joint_val) {\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\ninline EigenHelpers::VectorIsometry3d GetLinkTransforms(\n    const std::vector<double>& configuration, const Eigen::Isometry3d& base_transform = Eigen::Isometry3d::Identity()) {\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\ninline EigenHelpers::VectorIsometry3d GetLinkTransforms(\n    const std::map<std::string, double>& configuration,\n    const Eigen::Isometry3d& base_transform = Eigen::Isometry3d::Identity()) {\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\ninline EigenHelpers::MapStringIsometry3d GetLinkTransformsMap(\n    const std::vector<double>& configuration, const Eigen::Isometry3d& base_transform = Eigen::Isometry3d::Identity()) {\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\ninline EigenHelpers::MapStringIsometry3d GetLinkTransformsMap(\n    const std::map<std::string, double>& configuration,\n    const Eigen::Isometry3d& base_transform = Eigen::Isometry3d::Identity()) {\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}  // namespace IIWA_14_FK_FAST\n\n#endif  // IIWA_14_FK_FAST_HPP\n", "meta": {"hexsha": "83336964f18dbba2612f2ebd9af52b0e535dd700", "size": 9861, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/arc_utilities/iiwa_14_fk_fast.hpp", "max_stars_repo_name": "UM-ARM-Lab/arc_utilities", "max_stars_repo_head_hexsha": "e21bd5062983b25e61e33f832ec66b937540ba10", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2017-01-09T14:37:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T08:02:08.000Z", "max_issues_repo_path": "include/arc_utilities/iiwa_14_fk_fast.hpp", "max_issues_repo_name": "UM-ARM-Lab/arc_utilities", "max_issues_repo_head_hexsha": "e21bd5062983b25e61e33f832ec66b937540ba10", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2017-05-25T16:52:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T20:05:09.000Z", "max_forks_repo_path": "include/arc_utilities/iiwa_14_fk_fast.hpp", "max_forks_repo_name": "UM-ARM-Lab/arc_utilities", "max_forks_repo_head_hexsha": "e21bd5062983b25e61e33f832ec66b937540ba10", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-08-04T13:06:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T08:02:11.000Z", "avg_line_length": 59.0479041916, "max_line_length": 120, "alphanum_fraction": 0.8099584221, "num_tokens": 2847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2911087989449263}}
{"text": "#ifndef INCLUDED_STDDEFX\n#include \"stddefx.h\"\n#define INCLUDED_STDDEFX\n#endif\n\n#ifndef INCLUDED_CALC\n#include \"calc.h\"\n#define INCLUDED_CALC\n#endif\n\n// Library headers.\n#ifndef INCLUDED_IOSTREAM\n#include <iostream>\n#define INCLUDED_IOSTREAM\n#endif\n#ifndef INCLUDED_BOOST_NONCOPYABLE\n#include <boost/noncopyable.hpp>\n#define INCLUDED_BOOST_NONCOPYABLE\n#endif\n\n// PCRaster library headers.\n#ifndef INCLUDED_FIELDAPI_INTERFACE\n#include \"fieldapi_interface.h\"\n#define INCLUDED_FIELDAPI_INTERFACE\n#endif\n\n#ifndef INCLUDED_FIELDAPI_SCALARDOMAINCHECK\n#include \"fieldapi_scalardomaincheck.h\"\n#define INCLUDED_FIELDAPI_SCALARDOMAINCHECK\n#endif\n\n#ifndef INCLUDED_GEO_CELLLOCVISITOR\n#include \"geo_celllocvisitor.h\"\n#define INCLUDED_GEO_CELLLOCVISITOR\n#endif\n\n#ifndef INCLUDED_GEO_SIMPLERASTER\n#include \"geo_simpleraster.h\"\n#define INCLUDED_GEO_SIMPLERASTER\n#endif\n\n#ifndef INCLUDED_MISC\n#include \"misc.h\"\n#define INCLUDED_MISC\n#endif\n\n#ifndef INCLUDED_COM_INTERVALTYPES\n#include \"com_intervaltypes.h\"\n#define INCLUDED_COM_INTERVALTYPES\n#endif\n\n// Module headers.\n\n\n\n//------------------------------------------------------------------------------\n// Implicit finite difference according to:\n// Introduction to groundwater modeling\n// Wang & Anderson\n// Crank-Nicolson method, Gauss-Seidel iteration\n//------------------------------------------------------------------------------\n\nnamespace calc {\n\nstruct CalculationArgs {\n\n  double d_area;     // Cell area, constant.\n  double d_alpha;    // Constant.\n  double d_nrCells;  // Number of surrounding cells contributing to current cel.\n  double d_interval;\n  double d_currentElevation;\n  double d_recharge;\n  double d_transmissivity;   // Average t for all directions.\n  double d_storageCoefficient;\n  double d_h1;       // h * t for all directions, timestep n\n  double d_h2;       // h * t for all directions, timestep n + 1.\n\n};\n\n\n\ndouble calcElevation(const CalculationArgs& args)\n{\n  double f1 = (args.d_area * args.d_storageCoefficient) / args.d_interval;\n  double f2 = 1.0 / (f1 + args.d_nrCells * args.d_transmissivity *\n                   args.d_alpha);\n\n  return f2 * (args.d_alpha * args.d_h2 + f1 * args.d_currentElevation +\n                   (1.0 - args.d_alpha) *\n                   (args.d_h1 - args.d_currentElevation * args.d_nrCells *\n                   args.d_transmissivity) + args.d_area * args.d_recharge);\n}\n\n\n\nclass DiffuseAlgorithm: public boost::noncopyable \n{\n\npublic:\n\n  enum Direction {\n    NoDirection = 0x000,\n    Left = 0x0001,\n    Top = 0x0002,\n    Right = 0x0004,\n    Bottom = 0x0008,\n    UpperLeft = Top | Left,\n    UpperRight = Top | Right,\n    LowerLeft = Bottom | Left,\n    LowerRight = Bottom | Right,\n    Enclosed = Left | Top | Right | Bottom\n  };\n\n  enum FlowCondition  {\n    NOFLOW = 0,\n    CALCULATE = 1,\n    FIXED = 2\n  };\n\n\nprivate:\n\n  fieldapi::ReadWriteReal8&  d_resultElevation;\n  const fieldapi::ReadOnlyReal8& d_elevation;\n  const fieldapi::ReadOnlyReal8& d_recharge;\n  const fieldapi::ReadOnlyReal8& d_transmissivity;\n  const fieldapi::ReadOnlyInt4& d_flowCondition;\n  const fieldapi::ReadOnlyReal8& d_storageCoefficient;\n\n  CalculationArgs d_args;\n  geo::CellLoc d_location;    // A cell location.\n\n  geo::SimpleRaster<double> d_tmRight; // Average transm. values, right.\n  geo::SimpleRaster<double> d_tmBottom; // Average transm. values, bottom.\n\n  geo::SimpleRaster<unsigned int> d_noFlowBoundaries;\n\n\n\n  double calcElevationWithNoFlowBoundary(size_t r, size_t c, unsigned int direction)\n  {\n    if(direction == Enclosed) {\n      // Current cell is surrounded by no flow boundaries. Current elevation\n      // remains unchanged.\n      return d_elevation.value(r, c);\n    }\n\n    // Calculate new elevation.\n    d_args.d_h1 = 0.0;\n    d_args.d_h2 = 0.0;\n    d_args.d_nrCells = 0;\n\n    // Harmonic means of transmissivities.\n    double tmLeft(0), tmTop(0), tmRight(0), tmBottom(0);\n\n    // Cell to the left.\n    if(!(direction & Left)) {\n      tmLeft = d_tmRight.cell(r, c - 1);\n      d_args.d_h1 += tmLeft * d_elevation.value(r, c - 1);\n      d_args.d_h2 += tmLeft * d_resultElevation.value(r, c - 1);\n      ++d_args.d_nrCells;\n    }\n    else if(!(direction & Right)) {\n      // Copy value from Right cell.\n      tmLeft = d_tmRight.cell(r, c);\n      d_args.d_h1 += tmLeft * d_elevation.value(r, c + 1);\n      d_args.d_h2 += tmLeft * d_resultElevation.value(r, c + 1);\n      ++d_args.d_nrCells;\n    }\n\n    // Cell to the top.\n    if(!(direction & Top)) {\n      tmTop = d_tmBottom.cell(r - 1, c);\n      d_args.d_h1 += tmTop * d_elevation.value(r - 1, c);\n      d_args.d_h2 += tmTop * d_resultElevation.value(r - 1, c);\n      ++d_args.d_nrCells;\n    }\n    else if(!(direction & Bottom)) {\n      // Copy value from Bottom cell.\n      tmTop = d_tmBottom.cell(r, c);\n      d_args.d_h1 += tmTop * d_elevation.value(r + 1, c);\n      d_args.d_h2 += tmTop * d_resultElevation.value(r + 1, c);\n      ++d_args.d_nrCells;\n    }\n\n    // Cell to the right.\n    if(!(direction & Right)) {\n      tmRight = d_tmRight.cell(r, c);\n      d_args.d_h1 += tmRight * d_elevation.value(r, c + 1);\n      d_args.d_h2 += tmRight * d_resultElevation.value(r, c + 1);\n      ++d_args.d_nrCells;\n    }\n    else if(!(direction & Left)) {\n      // Copy value from Left cell.\n      tmRight = d_tmRight.cell(r, c - 1);\n      d_args.d_h1 += tmRight * d_elevation.value(r, c - 1);\n      d_args.d_h2 += tmRight * d_resultElevation.value(r, c - 1);\n      ++d_args.d_nrCells;\n    }\n\n    // Cell to the bottom.\n    if(!(direction & Bottom)) {\n      tmBottom = d_tmBottom.cell(r, c);\n      d_args.d_h1 += tmBottom * d_elevation.value(r + 1, c);\n      d_args.d_h2 += tmBottom * d_resultElevation.value(r + 1, c);\n      ++d_args.d_nrCells;\n    }\n    else if(!(direction & Top)) {\n      // Copy value from Top cell.\n      tmBottom = d_tmBottom.cell(r - 1, c);\n      d_args.d_h1 += tmBottom * d_elevation.value(r - 1, c);\n      d_args.d_h2 += tmBottom * d_resultElevation.value(r - 1, c);\n      ++d_args.d_nrCells;\n    }\n\n    PRECOND(d_args.d_nrCells > 0);\n\n    d_args.d_currentElevation = d_elevation.value(r, c);\n    d_args.d_recharge = d_recharge.value(r, c);\n    // Arithmic mean.\n    d_args.d_transmissivity = (tmLeft + tmTop + tmRight + tmBottom) /\n                   d_args.d_nrCells;\n    d_args.d_storageCoefficient = d_storageCoefficient.value(r, c);\n\n    return calc::calcElevation(d_args);\n  }\n\n\n\n  double calcElevationWithoutNoFlowBoundary(size_t r, size_t c)\n  {\n    d_args.d_h1 = 0.0;       // Elevation at t = n, * transmissivities.\n    d_args.d_h2 = 0.0;       // Elevation at t = n + 1, * transmissivities.\n    d_args.d_nrCells = 0;    // Nr of cells contributing to the current value.\n    static double tmLeft, tmTop, tmRight, tmBottom; // Harm. means of transm.\n\n    // The current cell has no no flow boundaries. All neighbours have\n    // valid values.\n\n    // Cell to the left.\n    tmLeft = d_tmRight.cell(r, c - 1);\n    d_args.d_h1 += tmLeft * d_elevation.value(r, c - 1);\n    d_args.d_h2 += tmLeft * d_resultElevation.value(r, c - 1);\n    ++d_args.d_nrCells;\n\n    // Cell to the top.\n    tmTop = d_tmBottom.cell(r - 1, c);\n    d_args.d_h1 += tmTop * d_elevation.value(r - 1, c);\n    d_args.d_h2 += tmTop * d_resultElevation.value(r - 1, c);\n    ++d_args.d_nrCells;\n\n    // Cell to the right.\n    tmRight = d_tmRight.cell(r, c);\n    d_args.d_h1 += tmRight * d_elevation.value(r, c + 1);\n    d_args.d_h2 += tmRight * d_resultElevation.value(r, c + 1);\n    ++d_args.d_nrCells;\n\n    // Cell to the bottom.\n    tmBottom = d_tmBottom.cell(r, c);\n    d_args.d_h1 += tmBottom * d_elevation.value(r + 1, c);\n    d_args.d_h2 += tmBottom * d_resultElevation.value(r + 1, c);\n    ++d_args.d_nrCells;\n\n    PRECOND(d_args.d_nrCells > 0);\n    PRECOND(d_args.d_nrCells == 4);\n\n    d_args.d_currentElevation = d_elevation.value(r, c);\n    d_args.d_recharge = d_recharge.value(r, c);\n    // Arithmic mean.\n    d_args.d_transmissivity = (tmLeft + tmTop + tmRight + tmBottom) /\n                   d_args.d_nrCells;\n    d_args.d_storageCoefficient = d_storageCoefficient.value(r, c);\n\n    return calc::calcElevation(d_args);\n  }\n\n\n\npublic:\n\n  DiffuseAlgorithm(fieldapi::ReadWriteReal8& resultElevation,\n         const fieldapi::ReadOnlyReal8& elevation,\n         const fieldapi::ReadOnlyReal8& recharge,\n         const fieldapi::ReadOnlyReal8& transmissivity,\n         const fieldapi::ReadOnlyInt4& flowCondition,\n         const fieldapi::ReadOnlyReal8& storageCoefficient,\n         double area, double alpha, double interval)\n\n    : d_resultElevation(resultElevation), d_elevation(elevation),\n      d_recharge(recharge), d_transmissivity(transmissivity),\n      d_flowCondition(flowCondition), d_storageCoefficient(storageCoefficient),\n      d_tmRight(resultElevation.nrRows(), resultElevation.nrCols()),\n      d_tmBottom(resultElevation.nrRows(), resultElevation.nrCols()),\n      d_noFlowBoundaries(resultElevation.nrRows(), resultElevation.nrCols(),\n      static_cast<const unsigned int>(NoDirection))\n\n  {\n    d_args.d_area = area;\n    d_args.d_alpha = alpha;\n    d_args.d_interval = interval;\n\n\n\n\n    geo::CellLoc loc;\n    size_t r, c; // comes from C ya know\n\n    //--------------------------------------------------------------------------\n    // Calculate transmissivities. These stay constant within a call to the\n    // function and are needed for each iteration so we calculate them here\n    // once. We trade memory space for speed.\n\n    // Harmonic mean transmissivities current and right cell.\n    // For every row.\n    for( r = 0; r < d_tmRight.nrRows(); ++r) {\n\n      loc.setRow(r);\n\n      // For every but the last col.\n      for( c = 0; c < d_tmRight.nrCols() - 1; ++c) {\n\n        loc.setCol(c);\n\n        if(!d_transmissivity.isMV(loc) &&\n                   !d_transmissivity.isMV(geo::CellLoc(r, c + 1))) {\n          d_tmRight.cell(r, c) =\n              2 * d_transmissivity.value(r, c + 1) *\n              d_transmissivity.value(r, c) /\n              (d_transmissivity.value(r, c + 1) + d_transmissivity.value(r, c));\n        }\n      }\n    }\n\n    // Harmonic mean transmissivities current and bottom cell.\n    // For every but the last row.\n    for( r = 0; r < d_tmBottom.nrRows() - 1; ++r) {\n\n      loc.setRow(r);\n\n      // For every col.\n      for( c = 0; c < d_tmBottom.nrCols(); ++c) {\n\n        loc.setCol(c);\n\n        if(!d_transmissivity.isMV(loc) &&\n                   !d_transmissivity.isMV(geo::CellLoc(r + 1, c))) {\n          d_tmBottom.cell(r, c) =\n              2 * d_transmissivity.value(r + 1, c) *\n              d_transmissivity.value(r, c) /\n              (d_transmissivity.value(r + 1, c) + d_transmissivity.value(r, c));\n        }\n      }\n    }\n\n    //--------------------------------------------------------------------------\n    // Calculate no flow boundaries. These stay constant within a call to the\n    // function and are needed for each iteration so we calculate them here\n    // once. We trade memory space for speed.\n    // d_noFlowBoundaries is already initialized with NoDirection.\n    // A bounding cell is regarded as a now flow boundary if:\n    // - it is missing (border cell of the raster)\n    // - it contains a missing value\n    // - if its flow condition is NOFLOW\n\n    PRECOND(d_noFlowBoundaries.nrRows() >= 1);\n    PRECOND(d_noFlowBoundaries.nrCols() >= 1);\n\n    // For every but the first and last row.\n    for( r = 1; r < d_noFlowBoundaries.nrRows() - 1; ++r) {\n\n      // For every but the first and last col.\n      for( c = 1; c < d_noFlowBoundaries.nrCols() - 1; ++c) {\n\n        // Cell to the left.\n        loc.setRow(r);\n        loc.setCol(c - 1);\n        if(d_elevation.isMV(loc) || d_flowCondition.isMV(loc) ||\n                   d_flowCondition.value(r, c - 1) == NOFLOW) {\n          d_noFlowBoundaries.cell(r, c) |= Left;\n        }\n\n        // Cell to the top.\n        loc.setRow(r - 1);\n        loc.setCol(c);\n        if(d_elevation.isMV(loc) || d_flowCondition.isMV(loc) ||\n                   d_flowCondition.value(r - 1, c) == NOFLOW) {\n          d_noFlowBoundaries.cell(r, c) |= Top;\n        }\n\n        // Cell to the right.\n        loc.setRow(r);\n        loc.setCol(c + 1);\n        if(d_elevation.isMV(loc) || d_flowCondition.isMV(loc) ||\n                   d_flowCondition.value(r, c + 1) == NOFLOW) {\n          d_noFlowBoundaries.cell(r, c) |= Right;\n        }\n\n        // Cell to the bottom.\n        loc.setRow(r + 1);\n        loc.setCol(c);\n        if(d_elevation.isMV(loc) || d_flowCondition.isMV(loc) ||\n                   d_flowCondition.value(r + 1, c) == NOFLOW) {\n          d_noFlowBoundaries.cell(r, c) |= Bottom;\n        }\n      }\n    }\n\n    // Handle no-flow conditions on the borders of the area. The value of head\n    // along the fictious column reflects across the border.\n\n\n    // Process borders of raster.\n\n    // First col.\n    c = 0;\n\n    // For every but the first and last row.\n    for(r = 1; r < d_noFlowBoundaries.nrRows() - 1; ++r) {\n\n      // Cell to the left.\n      d_noFlowBoundaries.cell(r, c) |= Left;\n\n      // Cell to the top.\n      loc.setRow(r - 1);\n      loc.setCol(c);\n      if(d_elevation.isMV(loc) || d_flowCondition.isMV(loc) ||\n                   d_flowCondition.value(r - 1, c) == NOFLOW) {\n        d_noFlowBoundaries.cell(r, c) |= Top;\n      }\n\n      // Cell to the right.\n      loc.setRow(r);\n      loc.setCol(c + 1);\n      if(d_elevation.isMV(loc) || d_flowCondition.isMV(loc) ||\n                   d_flowCondition.value(r, c + 1) == NOFLOW) {\n        d_noFlowBoundaries.cell(r, c) |= Right;\n      }\n\n      // Cell to the bottom.\n      loc.setRow(r + 1);\n      loc.setCol(c);\n      if(d_elevation.isMV(loc) || d_flowCondition.isMV(loc) ||\n                 d_flowCondition.value(r + 1, c) == NOFLOW) {\n        d_noFlowBoundaries.cell(r, c) |= Bottom;\n      }\n    }\n\n    // Last col.\n    c = d_noFlowBoundaries.nrCols() - 1;\n\n    // For every but the first and last row.\n    for(r = 1; r < d_noFlowBoundaries.nrRows() - 1; ++r) {\n\n      // Cell to the left.\n      loc.setRow(r);\n      loc.setCol(c - 1);\n      if(d_elevation.isMV(loc) || d_flowCondition.isMV(loc) ||\n                   d_flowCondition.value(r, c - 1) == NOFLOW) {\n        d_noFlowBoundaries.cell(r, c) |= Left;\n      }\n\n      // Cell to the top.\n      loc.setRow(r - 1);\n      loc.setCol(c);\n      if(d_elevation.isMV(loc) || d_flowCondition.isMV(loc) ||\n                   d_flowCondition.value(r - 1, c) == NOFLOW) {\n        d_noFlowBoundaries.cell(r, c) |= Top;\n      }\n\n      // Cell to the right.\n      d_noFlowBoundaries.cell(r, c) |= Right;\n\n      // Cell to the bottom.\n      loc.setRow(r + 1);\n      loc.setCol(c);\n      if(d_elevation.isMV(loc) || d_flowCondition.isMV(loc) ||\n                 d_flowCondition.value(r + 1, c) == NOFLOW) {\n        d_noFlowBoundaries.cell(r, c) |= Bottom;\n      }\n    }\n\n    // First row.\n    r = 0;\n\n    // For every but the first and last col.\n    for(c = 1; c < d_noFlowBoundaries.nrCols() - 1; ++c) {\n\n      // Cell to the left.\n      loc.setRow(r);\n      loc.setCol(c - 1);\n      if(d_elevation.isMV(loc) || d_flowCondition.isMV(loc) ||\n                   d_flowCondition.value(r, c - 1) == NOFLOW) {\n        d_noFlowBoundaries.cell(r, c) |= Left;\n      }\n\n      // Cell to the top.\n      d_noFlowBoundaries.cell(r, c) |= Top;\n\n      // Cell to the right.\n      loc.setRow(r);\n      loc.setCol(c + 1);\n      if(d_elevation.isMV(loc) || d_flowCondition.isMV(loc) ||\n                   d_flowCondition.value(r, c + 1) == NOFLOW) {\n        d_noFlowBoundaries.cell(r, c) |= Right;\n      }\n\n      // Cell to the bottom.\n      loc.setRow(r + 1);\n      loc.setCol(c);\n      if(d_elevation.isMV(loc) || d_flowCondition.isMV(loc) ||\n                 d_flowCondition.value(r + 1, c) == NOFLOW) {\n        d_noFlowBoundaries.cell(r, c) |= Bottom;\n      }\n    }\n\n    // Last row.\n    r = d_noFlowBoundaries.nrRows() - 1;\n\n    // For every but the first and last col.\n    for(c = 1; c < d_noFlowBoundaries.nrCols() - 1; ++c) {\n\n      // Cell to the left.\n      loc.setRow(r);\n      loc.setCol(c - 1);\n      if(d_elevation.isMV(loc) || d_flowCondition.isMV(loc) ||\n                   d_flowCondition.value(r, c - 1) == NOFLOW) {\n        d_noFlowBoundaries.cell(r, c) |= Left;\n      }\n\n      // Cell to the top.\n      loc.setRow(r - 1);\n      loc.setCol(c);\n      if(d_elevation.isMV(loc) || d_flowCondition.isMV(loc) ||\n                   d_flowCondition.value(r - 1, c) == NOFLOW) {\n        d_noFlowBoundaries.cell(r, c) |= Top;\n      }\n\n      // Cell to the right.\n      loc.setRow(r);\n      loc.setCol(c + 1);\n      if(d_elevation.isMV(loc) || d_flowCondition.isMV(loc) ||\n                   d_flowCondition.value(r, c + 1) == NOFLOW) {\n        d_noFlowBoundaries.cell(r, c) |= Right;\n      }\n\n      // Cell to the bottom.\n      d_noFlowBoundaries.cell(r, c) |= Bottom;\n    }\n\n    // Upper left corner.\n    r = 0;\n    c = 0;\n\n    d_noFlowBoundaries.cell(r, c) |= UpperLeft;\n\n    // Cell to the right.\n    loc.setRow(r);\n    loc.setCol(c + 1);\n    if(d_elevation.isMV(loc) || d_flowCondition.isMV(loc) ||\n                   d_flowCondition.value(r, c + 1) == NOFLOW) {\n      d_noFlowBoundaries.cell(r, c) |= Right;\n    }\n\n    // Cell to the bottom.\n    loc.setRow(r + 1);\n    loc.setCol(c);\n    if(d_elevation.isMV(loc) || d_flowCondition.isMV(loc) ||\n                 d_flowCondition.value(r + 1, c) == NOFLOW) {\n      d_noFlowBoundaries.cell(r, c) |= Bottom;\n    }\n\n    // Upper right corner.\n    r = 0;\n    c = d_noFlowBoundaries.nrCols() - 1;\n\n    d_noFlowBoundaries.cell(r, c) |= UpperRight;\n\n    // Cell to the left.\n    loc.setRow(r);\n    loc.setCol(c - 1);\n    if(d_elevation.isMV(loc) || d_flowCondition.isMV(loc) ||\n                   d_flowCondition.value(r, c - 1) == NOFLOW) {\n      d_noFlowBoundaries.cell(r, c) |= Left;\n    }\n\n    // Cell to the bottom.\n    loc.setRow(r + 1);\n    loc.setCol(c);\n    if(d_elevation.isMV(loc) || d_flowCondition.isMV(loc) ||\n                 d_flowCondition.value(r + 1, c) == NOFLOW) {\n      d_noFlowBoundaries.cell(r, c) |= Bottom;\n    }\n\n    // Lower right corner.\n    r = d_noFlowBoundaries.nrRows() - 1;\n    c = d_noFlowBoundaries.nrCols() - 1;\n\n    d_noFlowBoundaries.cell(r, c) |= LowerRight;\n\n    // Cell to the left.\n    loc.setRow(r);\n    loc.setCol(c - 1);\n    if(d_elevation.isMV(loc) || d_flowCondition.isMV(loc) ||\n                   d_flowCondition.value(r, c - 1) == NOFLOW) {\n      d_noFlowBoundaries.cell(r, c) |= Left;\n    }\n\n    // Cell to the top.\n    loc.setRow(r - 1);\n    loc.setCol(c);\n    if(d_elevation.isMV(loc) || d_flowCondition.isMV(loc) ||\n                   d_flowCondition.value(r - 1, c) == NOFLOW) {\n      d_noFlowBoundaries.cell(r, c) |= Top;\n    }\n\n    // Lower left corner.\n    r = d_noFlowBoundaries.nrRows() - 1;\n    c = 0;\n\n    d_noFlowBoundaries.cell(r, c) |= LowerLeft;\n\n    // Cell to the top.\n    loc.setRow(r - 1);\n    loc.setCol(c);\n    if(d_elevation.isMV(loc) || d_flowCondition.isMV(loc) ||\n                   d_flowCondition.value(r - 1, c) == NOFLOW) {\n      d_noFlowBoundaries.cell(r, c) |= Top;\n    }\n\n    // Cell to the right.\n    loc.setRow(r);\n    loc.setCol(c + 1);\n    if(d_elevation.isMV(loc) || d_flowCondition.isMV(loc) ||\n                   d_flowCondition.value(r, c + 1) == NOFLOW) {\n      d_noFlowBoundaries.cell(r, c) |= Right;\n    }\n  }\n\n\n\n//! Calculates the new elevation at a cell position.\n/*!\n  \\param     r Row of cell.\n  \\param     c Column of cell.\n  \\return    Elevation.\n  \\warning   All input variables and d_resultElevation must have a valid value\n             at \\a r, \\a c. This is forced by checking d_resultElevation.\n*/\n  double calcElevation(size_t r, size_t c)\n  {\n    PRECOND(!d_resultElevation.isMV(geo::CellLoc(r, c)));\n\n    if(d_noFlowBoundaries.cell(r, c) != NoDirection) {\n      return calcElevationWithNoFlowBoundary(r, c, d_noFlowBoundaries.cell(r, c));\n    }\n    else {\n      return calcElevationWithoutNoFlowBoundary(r, c);\n    }\n  }\n\n};\n\n\n\n} // namespace calc.\n\n\n//!\n/*!\n  \\param     .\n  \\return    .\n  \\exception .\n  \\warning   .\n  \\sa        .\n\n  Elevation                  scalar [ L       ]\n  Recharge                   scalar [ L , T-1 ]\n  Transmissivity             scalar [ L2, T-1 ]\n  Storage coefficient        scalar [ L3, L-3 ]\n  Interval                   scalar [ T       ]       > 0.0\n\n  Issues: cell length, error messages and handling of return values\n*/\nextern \"C\" int  Transient(void** out, const void** in, int nrArgs)\n{\n  using namespace calc; // hack hack\n  PRECOND(nrArgs == 7);\n  (void)nrArgs; // shut up compiler\n\n  ReadWriteReal8_ref(resultElevation, static_cast<MAP_REAL8*>(out[0]));\n  ReadOnlyReal8_ref(elevation, static_cast<const MAP_REAL8*>(in[0]));\n  ReadOnlyReal8_ref(recharge, static_cast<const MAP_REAL8*>(in[1]));\n  ReadOnlyReal8_ref(transmissivity, static_cast<const MAP_REAL8*>(in[2]));\n  ReadOnlyInt4_ref(flowCondition, static_cast<const MAP_INT4*>(in[3]));\n  ReadOnlyReal8_ref(storageCoefficient, static_cast<const MAP_REAL8*>(in[4]));\n  ReadOnlyReal8_ref(intervalInterface, static_cast<const MAP_REAL8*>(in[5]));\n  ReadOnlyReal8_ref(toleranceInterface, static_cast<const MAP_REAL8*>(in[6]));\n\n  PRECOND(!intervalInterface.spatial());\n  PRECOND(!toleranceInterface.spatial());\n\n  std::vector<const fieldapi::Common*> inputs;\n  inputs.push_back(&elevation);\n  inputs.push_back(&recharge);\n  inputs.push_back(&transmissivity);\n  inputs.push_back(&flowCondition);\n  inputs.push_back(&storageCoefficient);\n  inputs.push_back(&intervalInterface);\n  inputs.push_back(&toleranceInterface);\n  PRECOND(inputs.size() == static_cast<size_t>(nrArgs));\n\n  size_t nrRows = elevation.nrRows();\n  size_t nrCols = elevation.nrCols();\n  size_t r,c;\n  PRECOND(nrRows >= 2 && nrCols >= 2);\n\n  // Domain checks...\n  std::vector<fieldapi::ScalarDomainCheck> scalarDomains, nsDomains;\n  scalarDomains.push_back(fieldapi::ScalarDomainCheck(transmissivity,\n                   \"transmissivity\", com::GreaterThan<double>(0)));\n  scalarDomains.push_back(fieldapi::ScalarDomainCheck(storageCoefficient,\n                   \"storage coefficient\", com::GreaterThan<double>(0)));\n  nsDomains.push_back(fieldapi::ScalarDomainCheck(intervalInterface,\n                   \"interval\", com::GreaterThan<double>(0)));\n  nsDomains.push_back(fieldapi::ScalarDomainCheck(toleranceInterface,\n                   \"tolerance\", com::GreaterThan<double>(0)));\n\n  // Checks...\n  int check;\n\n  // Check non spatials.\n  check = fieldapi::checkScalarDomains(nsDomains, geo::CellLoc(0, 0));\n  if(check != -1) {\n    return RetError(1, nsDomains[check].msg().c_str());\n  }\n\n  // Check spatials.\n  for(geo::CellLocVisitor loc(elevation); loc.valid(); ++loc) {\n    check = fieldapi::checkScalarDomains(scalarDomains, *loc);\n    if(check != -1) {\n      return RetError(1, scalarDomains[check].msg().c_str());\n    }\n  }\n\n  // Inititalize...\n  double oldValue;\n  double tolerance = toleranceInterface.value(0, 0);\n  double difference, maxDifference;    // Current and max difference.\n  size_t nrIterations = 0;\n\n  // yepyep: fieldapi::Common::cellLength();\n  MAP_REAL8* map = static_cast<MAP_REAL8*>(out[0]);\n  double cellLength = map->CellLength(map);\n  PRECOND(cellLength > 0.0);\n\n  // Result elevation is missing value if any of the inputs is MV.\n  for(geo::CellLocVisitor visitor(elevation); visitor.valid(); ++visitor) {\n\n    if(fieldapi::nonMV(inputs, *visitor)) {\n      resultElevation.copy(elevation, *visitor);\n    }\n    else {\n      resultElevation.putMV(*visitor);\n    }\n  }\n\n  DiffuseAlgorithm algorithm(resultElevation, elevation, recharge,\n                   transmissivity, flowCondition, storageCoefficient,\n                   cellLength * cellLength, 0.5, intervalInterface.value(0, 0));\n  // std::cout << std::endl;\n\n  // Algorithm...\n  // Loop over all cells in the raster untill the maximum difference between\n  // the current elevation and the new elevation is smaller than the tolerance.\n  do {\n    maxDifference = 0.0;\n\n    for( r = 0; r < nrRows; ++r) {\n      for( c = 0; c < nrCols; ++c) {\n\n        // Skip missing values.\n        if(resultElevation.isMV(geo::CellLoc(r, c))) {\n          continue;\n        }\n\n        // Remember current elevation.\n        oldValue = resultElevation.value(r, c);\n\n        // Select calculation method for current cell, based on flow condition.\n        if(flowCondition.value(r, c) == DiffuseAlgorithm::CALCULATE) {\n          resultElevation.put(algorithm.calcElevation(r, c), r, c);\n        }\n        // (else FIXED, NOFLOW)\n\n        // Determine difference.\n        difference = ABS(resultElevation.value(r, c) - oldValue);\n        if(difference > maxDifference) {\n          maxDifference = difference;\n        }\n      }\n    }\n\n    ++nrIterations;\n\n    // yepyep: test op aantal iteraties?\n    // PRECOND(nrIterations < 30);\n    // std::cout << '.' << std::flush;\n\n  } while (maxDifference > tolerance);\n\n  // std::cout << \": \" << nrIterations << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "f93661fabcd1676bcff1df33275d84716eff16a0", "size": 24820, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/calc/calc_transient.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/calc/calc_transient.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/calc/calc_transient.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4539877301, "max_line_length": 84, "alphanum_fraction": 0.6066881547, "num_tokens": 6825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2910530633645006}}
{"text": "#include <iostream>\n#include <fstream>\n#include <armadillo>\n#include <math.h>\n#include <omp.h>\n#include <mpi.h>\n#include <unordered_set>\n\n#include \"class_partition.hpp\"\n#include \"constants.hpp\"\n\n/////////////////// Below are private member functions /////////////////\n\n/*   \nCreats knots in the current region\nInput: \n    xMin, xMax, yMin, yMax: the boudary of the current region\n    nKnotsX, nKnotsY: the number of knots in the current region in each direction\nOutput: \n    currentKnotsX: the array of the coordinates in longitude for each knot\n    currentKnotsY: the array of the coordinates in latitude for each knot\n*/\nvoid Partition::create_knots(double *&currentKnotsX, double *&currentKnotsY, const double &xMin, const double &xMax, const int &nKnotsX, const double &yMin, const double &yMax, const int &nKnotsY)\n{\n    double offsetX = (xMax-xMin)*OFFSET;\n    double offsetY = (yMax-yMin)*OFFSET;\n\n    double xStart = xMin+offsetX;\n    double xEnd = xMax-offsetX;\n    double yStart = yMin+offsetY;\n    double yEnd = yMax-offsetY;\n\n    double xIncrement = ( nKnotsX==1 ? 0 : (xEnd-xStart)/(nKnotsX-1));\n    double yIncrement = ( nKnotsY==1 ? 0 : (yEnd-yStart)/(nKnotsY-1));\n\n    #pragma omp parallel for\n    for(int iKnotX = 0; iKnotX < nKnotsX; iKnotX++)\n        for(int jKnotY = 0; jKnotY < nKnotsY; jKnotY++)\n        {\n            currentKnotsX[iKnotX*nKnotsY+jKnotY] = xEnd-(nKnotsX-iKnotX-1)*xIncrement;//xStart+iKnotX*xIncrement;\n            currentKnotsY[iKnotX*nKnotsY+jKnotY] = yEnd-(nKnotsY-jKnotY-1)*yIncrement;//yStart+jKnotY*yIncrement;\n        }\n}\n\n/*   \nCreats partitions in the current region\n*/\nvoid Partition::create_partitions(unsigned long region, double *partitionXMin, double *partitionXMax, double *partitionYMin, double *partitionYMax)\n{\n    double xMin=partitionXMin[region];\n    double xMax=partitionXMax[region];\n    double yMin=partitionYMin[region];\n    double yMax=partitionYMax[region];\n\n    if(NUM_PARTITIONS_J==2)\n    {\n        if((xMax-xMin)>=(yMax-yMin))\n        {\n            double xMid = (xMax+xMin)/2;\n            partitionXMin[region*2+1]=xMin; partitionXMin[region*2+2]=xMid;\n            partitionXMax[region*2+1]=xMid; partitionXMax[region*2+2]=xMax;\n\n            partitionYMin[region*2+1]=yMin; partitionYMin[region*2+2]=yMin;\n            partitionYMax[region*2+1]=yMax; partitionYMax[region*2+2]=yMax;\n        }else\n        {\n            double yMid = (yMax+yMin)/2;\n            partitionXMin[region*2+1]=xMin; partitionXMin[region*2+2]=xMin;\n            partitionXMax[region*2+1]=xMax; partitionXMax[region*2+2]=xMax;\n\n            partitionYMin[region*2+1]=yMin; partitionYMin[region*2+2]=yMid;\n            partitionYMax[region*2+1]=yMid; partitionYMax[region*2+2]=yMax;\n        }\n    }else\n    {\n        double xMid = (xMax+xMin)/2;\n        double yMid = (yMax+yMin)/2;\n\n        partitionXMin[region*4+1]=xMin; partitionXMin[region*4+2]=xMid; partitionXMin[region*4+3]=xMin; partitionXMin[region*4+4]=xMid;\n\n        partitionXMax[region*4+1]=xMid; partitionXMax[region*4+2]=xMax; partitionXMax[region*4+3]=xMid; partitionXMax[region*4+4]=xMax;\n\n        partitionYMin[region*4+1]=yMin; partitionYMin[region*4+2]=yMin; partitionYMin[region*4+3]=yMid; partitionYMin[region*4+4]=yMid;\n\n        partitionYMax[region*4+1]=yMid; partitionYMax[region*4+2]=yMid; partitionYMax[region*4+3]=yMax; partitionYMax[region*4+4]=yMax;\n    }\n}\n\n/////////////////// Above are private member functions /////////////////\n\n/////////////////// Below are public member functions /////////////////\n\n/*Implement the constructor of Partition. Assign values to nRegionsAtEachLevel for the array of the number of regions in each level, nRegionsInTotal for the total number of regions, and MPI quantities.\n*/\nPartition::Partition()\n{\n    //If user did not predetermine the number of levels, find the number of levels such that the average number of observations per region similar to the number of knots\n    if(NUM_LEVELS_M == -99)//-99 stands for the default method to automatically determine NUM_LEVELS_M \n    {\n        //Find the number of regions required at finest level, nRegionsAtFinestLevel \n        unsigned long nRegionsAtFinestLevel = ceil((double)NUM_OBSERVATIONS/(double)NUM_KNOTS_r);\n\n        //Find the number of levels, NUM_LEVELS_M, which satisfies NUM_PARTITIONS_J^(NUM_LEVELS_M-1)>=nRegionsAtFinestLevel\n        NUM_LEVELS_M = ceil(log(nRegionsAtFinestLevel)/log(NUM_PARTITIONS_J))+1;\n\n        if(NUM_LEVELS_M < 2)\n\t    {\n            if(WORKER == 0) cout<<\"Program exits with an error: the NUM_LEVELS_M calculated by default is \"<<NUM_LEVELS_M<<\", which is required to be larger than 1. Please decrease NUM_KNOTS_r to get a larger NUM_LEVELS_M.\\n\";\n            MPI_Barrier(MPI_COMM_WORLD);\n            MPI_Finalize();\n            exit(EXIT_FAILURE);\n\t    }\n    }\n\n    //Find the array of the number of regions in each level, nRgnsVec, and the total number of regions, nRegionsInTotal\n    nRegionsAtEachLevel = new unsigned long [NUM_LEVELS_M];\n    nRegionsAtEachLevel[0] = 1;\n    nRegionsInTotal = 1;\n    for(int iLevel = 1; iLevel < NUM_LEVELS_M; iLevel++)\n    {\n        nRegionsAtEachLevel[iLevel] = nRegionsAtEachLevel[iLevel-1]*NUM_PARTITIONS_J;\n        nRegionsInTotal += nRegionsAtEachLevel[iLevel];\n    }\n\n    //Calculate MPI information\n        WORKING_REGION_FLAG = new bool [nRegionsInTotal]();\n\n        unsigned long indexRegionAtFinestLevelStartThisWorker, indexRegionAtFinestLevelEndThisWorker;\n        WORKERS_FOR_EACH_REGION = new std::set<unsigned long>[nRegionsInTotal - nRegionsAtEachLevel[NUM_LEVELS_M-1]];\n\n        //Assign regions in the finest level to the worker\n        unsigned long nRegionsPerWorker = nRegionsAtEachLevel[NUM_LEVELS_M-1] / MPI_SIZE;\n        unsigned long nWorkersWithAdditionalRegion = nRegionsAtEachLevel[NUM_LEVELS_M-1] - nRegionsPerWorker * MPI_SIZE;\n\n\n        if(WORKER < nWorkersWithAdditionalRegion)\n        {\n            indexRegionAtFinestLevelStartThisWorker =  WORKER * (nRegionsPerWorker+1);\n            indexRegionAtFinestLevelEndThisWorker =  indexRegionAtFinestLevelStartThisWorker + nRegionsPerWorker;\n        }\n        else\n        {\n            indexRegionAtFinestLevelStartThisWorker =  nWorkersWithAdditionalRegion * (nRegionsPerWorker+1) + (WORKER -  nWorkersWithAdditionalRegion)* nRegionsPerWorker;\n            indexRegionAtFinestLevelEndThisWorker =  indexRegionAtFinestLevelStartThisWorker + nRegionsPerWorker - 1;\n        }\n\n        indexRegionAtFinestLevelStartThisWorker += nRegionsInTotal - nRegionsAtEachLevel[NUM_LEVELS_M-1];\n        indexRegionAtFinestLevelEndThisWorker += nRegionsInTotal - nRegionsAtEachLevel[NUM_LEVELS_M-1];\n\n        for(unsigned long i = indexRegionAtFinestLevelStartThisWorker; i < indexRegionAtFinestLevelEndThisWorker+1; i++)\n            WORKING_REGION_FLAG[i] = true;\n\n        //Find the regions dealt with by this worker at the second finest level\n        for(unsigned long index = indexRegionAtFinestLevelStartThisWorker; index <= indexRegionAtFinestLevelEndThisWorker; index++)\n        {\n            unsigned long ancestor = index;\n            while(ancestor > 0)\n            {\n                ancestor = (ancestor-1)/NUM_PARTITIONS_J;\n                //INDICES_REGIONS.insert(ancestor);\n                WORKING_REGION_FLAG[ancestor] = true;\n            }\n            INDICES_REGIONS_AT_CURRENT_LEVEL.insert((index-1)/NUM_PARTITIONS_J);\n        }\n\n        //Assign WORKERS_FOR_EACH_REGION at the second finest level\n        unsigned long indexStartFinestLevel = nRegionsInTotal - nRegionsAtEachLevel[NUM_LEVELS_M-1];\n        unsigned long tmpIndexStart = indexStartFinestLevel, tmpIndexEnd;\n        if(DYNAMIC_SCHEDULE_FLAG) origninalWorker = new int [nRegionsInTotal];\n\n        for(int iWorker = 0; iWorker < nWorkersWithAdditionalRegion; iWorker++)\n        {\n            tmpIndexEnd =  tmpIndexStart + nRegionsPerWorker + 1;\n            for(unsigned long index = tmpIndexStart; index < tmpIndexEnd; index++)\n            {\n                unsigned long ancestor = (index-1)/NUM_PARTITIONS_J;\n                WORKERS_FOR_EACH_REGION[ancestor].insert(iWorker);\n                if(DYNAMIC_SCHEDULE_FLAG) \n                {\n                    origninalWorker[index] = iWorker;\n                    origninalWorker[ancestor] = iWorker;\n                    while(ancestor > 0)\n                    {\n                        ancestor = (ancestor-1)/NUM_PARTITIONS_J;\n                        origninalWorker[ancestor] = iWorker;\n                    }\n                }\n            }\n            tmpIndexStart += nRegionsPerWorker+1;\n            tmpIndexEnd += nRegionsPerWorker+1;\n        }\n        for(int iWorker = nWorkersWithAdditionalRegion; iWorker < MPI_SIZE; iWorker++)\n        {\n            tmpIndexEnd =  tmpIndexStart + nRegionsPerWorker;\n            for(unsigned long index = tmpIndexStart; index < tmpIndexEnd; index++)\n            {\n                unsigned long ancestor = (index-1)/NUM_PARTITIONS_J;\n                WORKERS_FOR_EACH_REGION[ancestor].insert(iWorker);\n                if(DYNAMIC_SCHEDULE_FLAG) \n                {\n                    origninalWorker[index] = iWorker;\n                    origninalWorker[ancestor] = iWorker;\n                    while(ancestor > 0)\n                    {\n                        ancestor = (ancestor-1)/NUM_PARTITIONS_J;\n                        origninalWorker[ancestor] = iWorker;\n                    }\n                }\n            }\n            tmpIndexStart += nRegionsPerWorker;\n            tmpIndexEnd += nRegionsPerWorker;\n        }\n\n        //Assign regionStart and regionEnd for each level\n        REGION_START = new unsigned long [NUM_LEVELS_M];\n        REGION_END = new unsigned long [NUM_LEVELS_M];\n        REGION_START[NUM_LEVELS_M-1]=indexRegionAtFinestLevelStartThisWorker;\n        REGION_END[NUM_LEVELS_M-1]=indexRegionAtFinestLevelEndThisWorker;\n        for(int iLevel = NUM_LEVELS_M-2; iLevel > -1; iLevel--)\n        {\n            REGION_START[iLevel] = (REGION_START[iLevel+1]-1)/NUM_PARTITIONS_J;\n            REGION_END[iLevel] = (REGION_END[iLevel+1]-1)/NUM_PARTITIONS_J;\n        }\n}\n\n/*\nImplement the member function of Partition, build_partition, which builds the hierarchical partition\n*/\n\nvoid Partition::build_partition()\n{\n    if(WORKER == 0)\n\t{\n\t\tgettimeofday(&timeNow, NULL);\n\t\tcout<<\"===========================> Processor 1: building hierarchical grid starts. Elapsed time: \"<<(double)timeNow.tv_sec-(double)timeBegin.tv_sec+((double)timeNow.tv_usec-(double)timeBegin.tv_usec)/1000000.0<<\" seconds.\\n\";\n\t}\n\n    //The number of knots in each direction\n    int nKnotsX = ceil(sqrt(NUM_KNOTS_r));\n    int nKnotsY = (int)(NUM_KNOTS_r/nKnotsX);\n    nKnots = nKnotsX*nKnotsY;\n\n    //Allocate memory for the coordinates of knots\n    knotsX = new double* [nRegionsInTotal];\n    knotsY = new double* [nRegionsInTotal];\n\n    //Array of coordinates for the partition in each region with dimension [nRegionsInTotal]\n    double *partitionXMin, *partitionYMin, *partitionXMax, *partitionYMax;\n    partitionXMin = new double [nRegionsInTotal];\n    partitionXMax = new double [nRegionsInTotal];\n    partitionYMin = new double [nRegionsInTotal];\n    partitionYMax = new double [nRegionsInTotal];\n\n    partitionXMin[0] = data->domainBoundaries[0];\n    partitionXMax[0] = data->domainBoundaries[1];\n    partitionYMin[0] = data->domainBoundaries[2];\n    partitionYMax[0] = data->domainBoundaries[3];\n\n    for(int iLevel = 0; iLevel < NUM_LEVELS_M-1; iLevel++)\n    {\n        #pragma omp parallel for\n        for(unsigned long jRegion = REGION_START[iLevel]; jRegion < REGION_END[iLevel] + 1; jRegion++)\n            create_partitions(jRegion, partitionXMin, partitionXMax, partitionYMin, partitionYMax);\n    }\n\n    #pragma omp parallel for schedule(dynamic,1)\n    for(unsigned long iRegion = 0; iRegion < nRegionsInTotal - nRegionsAtEachLevel[NUM_LEVELS_M-1]; iRegion++)\n    {\n        if(WORKING_REGION_FLAG[iRegion])\n        {\n            knotsX[iRegion] = new double [nKnots];\n            knotsY[iRegion] = new double [nKnots];\n            create_knots(knotsX[iRegion], knotsY[iRegion], partitionXMin[iRegion], partitionXMax[iRegion], nKnotsX, partitionYMin[iRegion], partitionYMax[iRegion], nKnotsY);\n        }\n    }\n\n    //Allocate memory for nKnotsAtFinestLevel, nPredictionsAtFinestLevel\n    nKnotsAtFinestLevel = new unsigned long [nRegionsAtEachLevel[NUM_LEVELS_M-1]];\n    nPredictionsAtFinestLevel = new unsigned long [nRegionsAtEachLevel[NUM_LEVELS_M-1]];\n\n    //Allocate memory for nKnotsAtFinestLevel, nPredictionsAtFinestLevel\n    knotsResidual = new double* [nRegionsAtEachLevel[NUM_LEVELS_M-1]];\n    \n    //Allocate memory for the coordinates of predictions\n    predictionX = new double* [nRegionsAtEachLevel[NUM_LEVELS_M-1]];\n    predictionY = new double* [nRegionsAtEachLevel[NUM_LEVELS_M-1]];\n    \n    //Get coordinates of the knots and predictions at the regions in the finest level\n    int maxOpenMPThreads=omp_get_max_threads();\n\n    #pragma omp parallel for num_threads(maxOpenMPThreads) schedule(dynamic,1)\n    for(unsigned long iRegion = nRegionsInTotal - nRegionsAtEachLevel[NUM_LEVELS_M-1]; iRegion < nRegionsInTotal; iRegion++)\n    {\n        std::set<unsigned long> *indexObservationsInThisRegion = new std::set<unsigned long>;\n        std::set<unsigned long> *indexPredictionsInThisRegion = new std::set<unsigned long>;\n\n        unsigned long indexStartThisLevel = iRegion+nRegionsAtEachLevel[NUM_LEVELS_M-1]-nRegionsInTotal;\n        if(WORKING_REGION_FLAG[iRegion])\n        {\n            double xMin=partitionXMin[iRegion];\n            double xMax=partitionXMax[iRegion];\n            double yMin=partitionYMin[iRegion];\n            double yMax=partitionYMax[iRegion];\n\n            indexObservationsInThisRegion->clear();\n\n            for(unsigned long jObservation = 0; jObservation < NUM_OBSERVATIONS; jObservation++)\n            {\n                if(data->observationLon[jObservation] >= xMin && data->observationLon[jObservation] < xMax && data->observationLat[jObservation] >= yMin && data->observationLat[jObservation] < yMax)\n                {\n                    \n                    bool skip = false;\n                    //Skip if the observation location coincides with knots in levels above\n                    unsigned long ancestor = iRegion;\n                    for(int kLevel = 0; kLevel < NUM_LEVELS_M-1; kLevel++)\n                    {\n                        ancestor = (ancestor-1)/NUM_PARTITIONS_J;\n                        for(int pKnot = 0; pKnot < nKnots; pKnot++)\n                        {\n                            if(knotsX[ancestor][pKnot] == data->observationLon[jObservation] && knotsY[ancestor][pKnot] == data->observationLat[jObservation])\n                            {\n                                skip = true;\n                                break;\n                            }\n                        }\n                        if(skip) break;\n                    }\n                    \n                    //Add this observation\n                    if(!skip) indexObservationsInThisRegion->insert(jObservation);\n                }\n            }\n\n            nKnotsAtFinestLevel[indexStartThisLevel] = indexObservationsInThisRegion->size();\n            knotsX[iRegion] = new double [nKnotsAtFinestLevel[indexStartThisLevel]];            \n            knotsY[iRegion] = new double [nKnotsAtFinestLevel[indexStartThisLevel]];\n            knotsResidual[indexStartThisLevel] = new double [nKnotsAtFinestLevel[indexStartThisLevel]];\n       \n            unsigned long tmpIndex=0;\n            for(std::set<unsigned long>::iterator jObservation = indexObservationsInThisRegion->begin(); jObservation != indexObservationsInThisRegion->end(); jObservation++)\n            {\n                knotsX[iRegion][tmpIndex] = data->observationLon[*jObservation];\n                knotsY[iRegion][tmpIndex] = data->observationLat[*jObservation];\n                knotsResidual[indexStartThisLevel][tmpIndex++] = data->observationResiduals[*jObservation];\n            }\n\n            if(CALCULATION_MODE==\"prediction\")\n            {\n                indexPredictionsInThisRegion->clear();\n                for(unsigned long jPrediction = 0; jPrediction < NUM_PREDICTIONS; jPrediction++)\n                {\n                    if(data->predictionLon[jPrediction] >= xMin && data->predictionLon[jPrediction] < xMax && data->predictionLat[jPrediction] >= yMin && data->predictionLat[jPrediction] < yMax)\n                        indexPredictionsInThisRegion->insert(jPrediction);\n                }\n\n                nPredictionsAtFinestLevel[indexStartThisLevel] = indexPredictionsInThisRegion->size();\n                predictionX[indexStartThisLevel] = new double [nPredictionsAtFinestLevel[indexStartThisLevel]];            \n                predictionY[indexStartThisLevel] = new double [nPredictionsAtFinestLevel[indexStartThisLevel]];\n\n                unsigned long tmpIndex=0;\n                for(std::set<unsigned long>::iterator jPrediction = indexPredictionsInThisRegion->begin(); jPrediction != indexPredictionsInThisRegion->end(); jPrediction++)\n                {\n                    predictionX[indexStartThisLevel][tmpIndex] = data->predictionLon[*jPrediction];\n                    predictionY[indexStartThisLevel][tmpIndex++] = data->predictionLat[*jPrediction];\n                }\n            }\n        }    \n        indexObservationsInThisRegion->clear();\n        indexPredictionsInThisRegion->clear();\n    }\n    \n\n    //Release the memory for the temporary arrays\n    delete[] partitionXMin;\n    delete[] partitionYMin;\n    delete[] partitionXMax;\n    delete[] partitionYMax;\n\n    //Delete variables that are not used anymore\n    delete[] data->observationLon;\n    delete[] data->observationLat;\n    delete[] data->observationResiduals;\n\n    if(DYNAMIC_SCHEDULE_FLAG) \n\t\tdynamic_schedule();\n\telse\n\t\tWORLD = MPI_COMM_WORLD;\n\n    if(WORKER == 0)\n\t{\n\t\tgettimeofday(&timeNow, NULL);\n\t\tcout<<\"===========================> Processor 1: building hierarchical grid 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\t\tif(PRINT_DETAIL_FLAG) print_partition_summary();\n\t}\n}\n\n//Implement the member function of Partition, dynamic_schedule, which assign the work load for each worker by dynamic scheduling\nvoid Partition::dynamic_schedule()\n{\n    //Synchronize the knots of regions before the finest level\n    for(unsigned long iRegion = 0; iRegion < nRegionsInTotal - nRegionsAtEachLevel[NUM_LEVELS_M-1]; iRegion++)\n    {\n        if(!WORKING_REGION_FLAG[iRegion])\n        {\n            knotsX[iRegion] = new double [nKnots];\n            knotsY[iRegion] = new double [nKnots];\n        }\n    }\n\n    for(unsigned long iRegion = 0; iRegion < nRegionsInTotal - nRegionsAtEachLevel[NUM_LEVELS_M-1]; iRegion++)\n    {\n        MPI_Bcast(knotsX[iRegion],nKnots,MPI_DOUBLE,origninalWorker[iRegion],MPI_COMM_WORLD);\n        MPI_Bcast(knotsY[iRegion],nKnots,MPI_DOUBLE,origninalWorker[iRegion],MPI_COMM_WORLD);\n    }\n\n    //Synchronize the knots of regions at the finest level and predictions if predicting\n    unsigned long indexStartFinestLevel = nRegionsInTotal - nRegionsAtEachLevel[NUM_LEVELS_M-1];\n    for(unsigned long iRegion = indexStartFinestLevel; iRegion < nRegionsInTotal; iRegion++)\n    {\n\n        MPI_Bcast(&nKnotsAtFinestLevel[iRegion-indexStartFinestLevel],1,MPI_UNSIGNED_LONG,origninalWorker[iRegion],MPI_COMM_WORLD);\n        if(!WORKING_REGION_FLAG[iRegion])\n        {\n            knotsX[iRegion] = new double [nKnotsAtFinestLevel[iRegion-indexStartFinestLevel]];\n            knotsY[iRegion] = new double [nKnotsAtFinestLevel[iRegion-indexStartFinestLevel]];\n            knotsResidual[iRegion-indexStartFinestLevel] = new double [nKnotsAtFinestLevel[iRegion-indexStartFinestLevel]];\n        }\n\n        if(CALCULATION_MODE==\"prediction\")\n        {\n            MPI_Bcast(&nPredictionsAtFinestLevel[iRegion-indexStartFinestLevel],1,MPI_UNSIGNED_LONG,origninalWorker[iRegion],MPI_COMM_WORLD);\n            if(!WORKING_REGION_FLAG[iRegion])\n            {\n                predictionX[iRegion-indexStartFinestLevel] = new double [nPredictionsAtFinestLevel[iRegion-indexStartFinestLevel]];\n                predictionY[iRegion-indexStartFinestLevel] = new double [nPredictionsAtFinestLevel[iRegion-indexStartFinestLevel]];\n            }\n        }\n\n        MPI_Bcast(knotsX[iRegion],nKnotsAtFinestLevel[iRegion-indexStartFinestLevel],MPI_DOUBLE,origninalWorker[iRegion],MPI_COMM_WORLD);\n        MPI_Bcast(knotsY[iRegion],nKnotsAtFinestLevel[iRegion-indexStartFinestLevel],MPI_DOUBLE,origninalWorker[iRegion],MPI_COMM_WORLD);\n        MPI_Bcast(knotsResidual[iRegion-indexStartFinestLevel],nKnotsAtFinestLevel[iRegion-indexStartFinestLevel],MPI_DOUBLE,origninalWorker[iRegion],MPI_COMM_WORLD);\n\n        if(CALCULATION_MODE==\"prediction\")\n        {\n            MPI_Bcast(predictionX[iRegion-indexStartFinestLevel],nPredictionsAtFinestLevel[iRegion-indexStartFinestLevel],MPI_DOUBLE,origninalWorker[iRegion],MPI_COMM_WORLD);\n            MPI_Bcast(predictionY[iRegion-indexStartFinestLevel],nPredictionsAtFinestLevel[iRegion-indexStartFinestLevel],MPI_DOUBLE,origninalWorker[iRegion],MPI_COMM_WORLD);\n        }\n    }\n\n    //Dynamic schedule work load for each worker\n    \n    ///Clear WORKERS_FOR_EACH_REGION at the second finest level\n    for(unsigned long iRegion = nRegionsInTotal - nRegionsAtEachLevel[NUM_LEVELS_M-1] - nRegionsAtEachLevel[NUM_LEVELS_M-2]; iRegion < nRegionsInTotal - nRegionsAtEachLevel[NUM_LEVELS_M-1]; iRegion++)\n        WORKERS_FOR_EACH_REGION[iRegion].clear();\n\n    ///Clear WORKING_REGION_FLAG for all regions\n    memset(WORKING_REGION_FLAG,false,nRegionsInTotal);\n    \n    ///Clear INDICES_REGIONS_AT_CURRENT_LEVEL\n    INDICES_REGIONS_AT_CURRENT_LEVEL.clear();\n\n    ///Calculate work load\n    double totalComplexity = 0;\n    for(unsigned long index = 0; index < nRegionsAtEachLevel[NUM_LEVELS_M-1]; index++)\n    {\n        double tmp = nKnotsAtFinestLevel[index];\n        totalComplexity += tmp*tmp;//*tmp;\n    }\n    double complexityEachWorker = totalComplexity/MPI_SIZE;\n\n    ///Assign working regions for each worker\n    REGION_START[NUM_LEVELS_M-1]=nRegionsInTotal;\n    REGION_END[NUM_LEVELS_M-1]=0;\n    int thisWorker=-1;\n    double complexityThisWorker=0;  \n    unsigned long indexRegionAtFinestLevelStartThisWorker = nRegionsInTotal - nRegionsAtEachLevel[NUM_LEVELS_M-1], indexRegionAtFinestLevelEndThisWorker;\n    for(unsigned long index = 0; index < nRegionsAtEachLevel[NUM_LEVELS_M-1]; index++)\n    {\n        double tmp = nKnotsAtFinestLevel[index];\n        double complexityThisRegion = tmp*tmp;//*tmp;\n        complexityThisWorker += complexityThisRegion;\n        //if(WORKER==0) cout<<complexityThisRegion<<\" \"<<complexityEachWorker<<endl;\n        if(complexityThisWorker >= complexityEachWorker || index == nRegionsAtEachLevel[NUM_LEVELS_M-1]-1)\n        {\n            thisWorker++;\n            if(thisWorker == MPI_SIZE) thisWorker = MPI_SIZE-1;\n\n            indexRegionAtFinestLevelEndThisWorker = indexStartFinestLevel+index;\n            \n            //Check whether this region should be handled by this worker or next worker\n            if(complexityEachWorker - complexityThisWorker + complexityThisRegion < complexityThisWorker - complexityEachWorker \n                && index != nRegionsAtEachLevel[NUM_LEVELS_M-1]-1\n                && indexRegionAtFinestLevelEndThisWorker > indexRegionAtFinestLevelStartThisWorker)\n            {\n                //Next worker handle this region\n                indexRegionAtFinestLevelEndThisWorker--;\n                complexityThisWorker = complexityThisRegion;\n            }\n            else\n            {\n                //This worker handle this region\n                complexityThisWorker = 0;\n            }\n\n            //if(WORKER==0) cout<<thisWorker<<\" \"<<indexRegionAtFinestLevelStartThisWorker<<\" \"<<indexRegionAtFinestLevelEndThisWorker<<endl;\n\n            for(unsigned long jRegion = indexRegionAtFinestLevelStartThisWorker; jRegion < indexRegionAtFinestLevelEndThisWorker+1; jRegion++)\n            {\n                unsigned long ancestor = (jRegion-1)/NUM_PARTITIONS_J;\n                WORKERS_FOR_EACH_REGION[ancestor].insert(thisWorker);\n            }\n\n            if(thisWorker == WORKER)\n            {\n                for(unsigned long jRegion = indexRegionAtFinestLevelStartThisWorker; jRegion < indexRegionAtFinestLevelEndThisWorker+1; jRegion++)\n                {\n                    unsigned long ancestor = jRegion;\n                    WORKING_REGION_FLAG[ancestor] = true;\n                    while(ancestor > 0)\n                    {\n                        ancestor = (ancestor-1)/NUM_PARTITIONS_J;\n                        WORKING_REGION_FLAG[ancestor] = true;\n                    }\n                    INDICES_REGIONS_AT_CURRENT_LEVEL.insert((jRegion-1)/NUM_PARTITIONS_J);\n                }\n                if(indexRegionAtFinestLevelStartThisWorker<REGION_START[NUM_LEVELS_M-1]) REGION_START[NUM_LEVELS_M-1]=indexRegionAtFinestLevelStartThisWorker;\n                if(indexRegionAtFinestLevelEndThisWorker>REGION_END[NUM_LEVELS_M-1]) REGION_END[NUM_LEVELS_M-1]=indexRegionAtFinestLevelEndThisWorker;\n            }\n\n            indexRegionAtFinestLevelStartThisWorker = indexRegionAtFinestLevelEndThisWorker+1;\n        }\n    }\n\n    //Deactivate MPI processes that are not assigned any regions, which rarely happens\n    if(thisWorker<MPI_SIZE-1) \n    {\n        MPI_Group worldGroup;\n        MPI_Comm_group(MPI_COMM_WORLD,&worldGroup);\n\n        MPI_Group newWorldGroup;\n        int ranges[1][3]={{thisWorker+1,MPI_SIZE-1,1}};\n        MPI_Group_range_excl(worldGroup,1,ranges,&newWorldGroup);\n\n        MPI_Comm_create(MPI_COMM_WORLD, newWorldGroup, &WORLD);\n\n        MPI_SIZE=thisWorker+1;\n\n        if(WORKER>thisWorker)\n        {\n            MPI_Finalize();\n            exit(EXIT_SUCCESS);\n        }\n    }\n    else\n        WORLD = MPI_COMM_WORLD;\n    \n    for(int iLevel = NUM_LEVELS_M-2; iLevel > -1; iLevel--)\n    {\n        REGION_START[iLevel] = (REGION_START[iLevel+1]-1)/NUM_PARTITIONS_J;\n        REGION_END[iLevel] = (REGION_END[iLevel+1]-1)/NUM_PARTITIONS_J;\n    }\n\n    //Delete regions that are not handled by this WORKER\n    for(unsigned long iRegion = 0; iRegion < nRegionsInTotal; iRegion++)\n        if(!WORKING_REGION_FLAG[iRegion])\n        {\n            delete[] knotsX[iRegion]; knotsX[iRegion]=NULL;\n            delete[] knotsY[iRegion]; knotsY[iRegion]=NULL;\n        }\n\n    for(unsigned long iRegion = nRegionsInTotal - nRegionsAtEachLevel[NUM_LEVELS_M-1]; iRegion < nRegionsInTotal; iRegion++)\n        if(!WORKING_REGION_FLAG[iRegion])\n        {\n            delete[] knotsResidual[iRegion-indexStartFinestLevel]; knotsResidual[iRegion-indexStartFinestLevel]=NULL;\n\n            if(CALCULATION_MODE==\"prediction\")\n            {\n                delete[] predictionX[iRegion-indexStartFinestLevel]; predictionX[iRegion-indexStartFinestLevel]=NULL;\n                delete[] predictionY[iRegion-indexStartFinestLevel]; predictionY[iRegion-indexStartFinestLevel]=NULL;\n            }\n        }\n\n}\n\n//Implement the member function of Partition, print_partition_summary, which shows a brief summary of the partition\nvoid Partition::print_partition_summary()\n{\n    cout<<\">>The number of levels: \"<<NUM_LEVELS_M<<endl<<endl;\n    cout<<\">>The total number of regions: \"<<nRegionsInTotal<<endl<<endl;\n    cout<<\">>The number of regions in each level: \\n    \";\n    for(int iLevel = 0; iLevel < NUM_LEVELS_M; iLevel++) cout<<nRegionsAtEachLevel[iLevel]<<\" \";\n    cout<<endl<<endl;\n\n    cout<<\">>Knot coordinates in the coarsest region, up to ten knots are shown: \\n    longitude: \";\n    for(int iKnot = 0; iKnot < std::min(nKnots,10); iKnot++) \n        printf(\"%8.2lf \",knotsX[0][iKnot]);\n    cout<<\"\\n    latitude:  \";\n    for(int iKnot = 0; iKnot < std::min(nKnots,10); iKnot++) \n        printf(\"%8.2lf \",knotsY[0][iKnot]);\n    cout<<endl<<endl;\n\n    if(CALCULATION_MODE==\"predict\")\n        cout<<\">>The number of predictions after eliminating duplicates: \"<<NUM_PREDICTIONS<<endl<<endl;\n\n}\n\nvoid Partition::dump_structure_information()\n{\n    //Open the file \"structure_information.txt\" to store structure information\n    std::ofstream file;\n    file.open(\"structure_information.txt\");\n\n    //Dump the number of levels \n    file<<\"The number of levels: \"<<NUM_LEVELS_M<<endl<<endl;\n\n    //Dump the total number of regions\n    file<<\"The total number of regions: \"<<nRegionsInTotal<<endl<<endl;\n\n\n    //Dump the number of knots in regions before the finest level\n    file<<\"The actual number of knots in regions before the finest level: \"<<nKnots<<endl<<endl;\n\n    //Dump some statistics of the number of knots in each region at the finest level\n    unsigned long nKnotsMin = nKnotsAtFinestLevel[0];\n    unsigned long nKnotsMax = nKnotsAtFinestLevel[0];\n    unsigned long nRegionsHaveZeroKnots = 0;\n\n    for(unsigned long iRegion = 0; iRegion < nRegionsAtEachLevel[NUM_LEVELS_M-1]; iRegion++)\n    {\n        if(nKnotsMin>nKnotsAtFinestLevel[iRegion]) nKnotsMin=nKnotsAtFinestLevel[iRegion];\n        if(nKnotsMax<nKnotsAtFinestLevel[iRegion]) nKnotsMax=nKnotsAtFinestLevel[iRegion];\n        if(nKnotsAtFinestLevel[iRegion] == 0) nRegionsHaveZeroKnots++;\n    }\n\n    file<<\"The minimal number of knots in regions at the finest level: \"<<nKnotsMin<<endl<<endl;\n    file<<\"The maximal number of knots in regions at the finest level: \"<<nKnotsMax<<endl<<endl;\n    file<<\"The number of in regions at the finest level that have zero knots: \"<<nRegionsHaveZeroKnots<<endl<<endl;\n\n    unsigned long thresholdLeft, thresholdRight;\n    unsigned long nRegionsBetweenThresholds;\n    double interval = (nKnotsMax-nKnotsMin)/10;\n    \n    thresholdLeft=nKnotsMin;\n    file<<\"The number of regions at the finest level with number of knots in the following intervals:\"<<endl;\n    \n    for(int i = 0; i < 10; i++)\n    {\n        nRegionsBetweenThresholds = 0;\n        thresholdRight=thresholdLeft+interval;\n        if(i == 9) thresholdRight = nKnotsMax;\n        for(unsigned long iRegion = 0; iRegion < nRegionsAtEachLevel[NUM_LEVELS_M-1]; iRegion++)\n           if(thresholdLeft<=nKnotsAtFinestLevel[iRegion] && nKnotsAtFinestLevel[iRegion]<=thresholdRight) nRegionsBetweenThresholds++;\n        file<<\"[ \"<<thresholdLeft<<\" , \"<<thresholdRight<<\" ]: \"<<nRegionsBetweenThresholds<<endl;\n        thresholdLeft = thresholdRight+1;\n    }    \n    file<<endl;\n\n    //Dump the number of regions in each level\n    file<<\"The number of regions in each level: \\n\";\n    for(int iLevel = 0; iLevel < NUM_LEVELS_M; iLevel++) \n        file<<\"Level \"<<iLevel+1<<\": \"<<nRegionsAtEachLevel[iLevel]<<endl;\n    file<<endl;\n\n    //Dump the number of knots in each region at the finest level\n    file<<\"The number of knots in each region at the finest level: \\n\";\n    for(unsigned long iRegion = 0; iRegion < nRegionsAtEachLevel[NUM_LEVELS_M-1]; iRegion++)\n        file<<\"Region \"<<nRegionsInTotal-nRegionsAtEachLevel[NUM_LEVELS_M-1]+iRegion<<\": \"<<nKnotsAtFinestLevel[iRegion]<<endl;\n\n\n    //Close the file\n    file.close();\n}\n\nPartition::~Partition()\n{\n    delete[] nRegionsAtEachLevel;\n\n    delete[] knotsX;\n    delete[] knotsY;\n    delete[] knotsResidual;\n\n    delete[] predictionX, \n    delete[] predictionY;\n\n    delete[] nKnotsAtFinestLevel, \n    delete[] nPredictionsAtFinestLevel;\n    \n    if(DYNAMIC_SCHEDULE_FLAG) delete[] origninalWorker;\n    //cout<<\"Partition is deleted\\n\";\n}", "meta": {"hexsha": "f377ac26404268655155c03156fdbbb26862bfee", "size": 31500, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "parallel_MRA/src/class_partition.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_partition.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_partition.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": 45.652173913, "max_line_length": 235, "alphanum_fraction": 0.6648888889, "num_tokens": 8015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2910034779690752}}
{"text": "/**\n * @file methods/ann/rnn_impl.hpp\n * @author Marcus Edel\n *\n * Definition of the RNN class, which implements recurrent 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_RNN_IMPL_HPP\n#define MLPACK_METHODS_ANN_RNN_IMPL_HPP\n\n// In case it hasn't been included yet.\n#include \"rnn.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/deterministic_set_visitor.hpp\"\n#include \"visitor/gradient_set_visitor.hpp\"\n#include \"visitor/gradient_visitor.hpp\"\n#include \"visitor/weight_set_visitor.hpp\"\n\n#include <boost/serialization/variant.hpp>\n\nnamespace mlpack {\nnamespace ann /** Artificial Neural Network. */ {\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nRNN<OutputLayerType, InitializationRuleType, CustomLayers...>::RNN(\n    const size_t rho,\n    const bool single,\n    OutputLayerType outputLayer,\n    InitializationRuleType initializeRule) :\n    rho(rho),\n    outputLayer(std::move(outputLayer)),\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{\n  /* Nothing to do here */\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nRNN<OutputLayerType, InitializationRuleType, CustomLayers...>::~RNN()\n{\n  for (LayerTypes<CustomLayers...>& layer : network)\n  {\n    boost::apply_visitor(deleteVisitor, layer);\n  }\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\ntemplate<typename OptimizerType>\ntypename std::enable_if<\n      HasMaxIterations<OptimizerType, size_t&(OptimizerType::*)()>\n      ::value, void>::type\nRNN<OutputLayerType, InitializationRuleType, CustomLayers...>::\nWarnMessageMaxIterations(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 InitializationRuleType,\n         typename... CustomLayers>\ntemplate<typename OptimizerType>\ntypename std::enable_if<\n      !HasMaxIterations<OptimizerType, size_t&(OptimizerType::*)()>\n      ::value, void>::type\nRNN<OutputLayerType, InitializationRuleType, CustomLayers...>::\nWarnMessageMaxIterations(OptimizerType& /* optimizer */,\n                         size_t /* samples */) const\n{\n  return;\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\ntemplate<typename OptimizerType, typename... CallbackTypes>\ndouble RNN<OutputLayerType, InitializationRuleType, CustomLayers...>::Train(\n    arma::cube predictors,\n    arma::cube responses,\n    OptimizerType& optimizer,\n    CallbackTypes&&... callbacks)\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(\"rnn_optimization\");\n  const double out = optimizer.Optimize(*this, parameter, callbacks...);\n  Timer::Stop(\"rnn_optimization\");\n\n  Log::Info << \"RNN::RNN(): final objective of trained model is \" << out\n      << \".\" << std::endl;\n  return out;\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid RNN<OutputLayerType, InitializationRuleType,\n         CustomLayers...>::ResetCells()\n{\n  for (size_t i = 1; i < network.size(); ++i)\n  {\n    boost::apply_visitor(ResetCellVisitor(rho), network[i]);\n  }\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\ntemplate<typename OptimizerType, typename... CallbackTypes>\ndouble RNN<OutputLayerType, InitializationRuleType, CustomLayers...>::Train(\n    arma::cube predictors,\n    arma::cube responses,\n    CallbackTypes&&... callbacks)\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  Timer::Start(\"rnn_optimization\");\n  const double out = optimizer.Optimize(*this, parameter, callbacks...);\n  Timer::Stop(\"rnn_optimization\");\n\n  Log::Info << \"RNN::RNN(): final objective of trained model is \" << out\n      << \".\" << std::endl;\n  return out;\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid RNN<OutputLayerType, InitializationRuleType, CustomLayers...>::Predict(\n    arma::cube predictors, arma::cube& results, const size_t batchSize)\n{\n  ResetCells();\n\n  if (parameter.is_empty())\n  {\n    ResetParameters();\n  }\n\n  if (!deterministic)\n  {\n    deterministic = true;\n    ResetDeterministic();\n  }\n\n  const size_t effectiveBatchSize = std::min(batchSize,\n      size_t(predictors.n_cols));\n\n  Forward(arma::mat(predictors.slice(0).colptr(0), predictors.n_rows,\n      effectiveBatchSize, false, true));\n  arma::mat resultsTemp = boost::apply_visitor(outputParameterVisitor,\n      network.back());\n\n  outputSize = resultsTemp.n_rows;\n  results = arma::zeros<arma::cube>(outputSize, predictors.n_cols, rho);\n  results.slice(0).submat(0, 0, results.n_rows - 1,\n      effectiveBatchSize - 1) = resultsTemp;\n\n  // Process in accordance with the given batch size.\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 = !begin; seqNum < rho; ++seqNum)\n    {\n      Forward(arma::mat(predictors.slice(seqNum).colptr(begin),\n          predictors.n_rows, effectiveBatchSize, false, true));\n\n      results.slice(seqNum).submat(0, begin, results.n_rows - 1, begin +\n          effectiveBatchSize - 1) = boost::apply_visitor(outputParameterVisitor,\n          network.back());\n    }\n  }\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\ndouble RNN<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  {\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  ResetCells();\n\n  double performance = 0;\n  size_t responseSeq = 0;\n\n  for (size_t seqNum = 0; seqNum < rho; ++seqNum)\n  {\n    // Wrap a matrix around our data to avoid a copy.\n    arma::mat stepData(predictors.slice(seqNum).colptr(begin),\n        predictors.n_rows, batchSize, false, true);\n    Forward(stepData);\n    if (!single)\n    {\n      responseSeq = seqNum;\n    }\n\n    performance += outputLayer.Forward(boost::apply_visitor(\n        outputParameterVisitor, network.back()),\n        arma::mat(responses.slice(responseSeq).colptr(begin),\n            responses.n_rows, batchSize, false, true));\n  }\n\n  if (outputSize == 0)\n  {\n    outputSize = boost::apply_visitor(outputParameterVisitor,\n        network.back()).n_elem / batchSize;\n  }\n\n  return performance;\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\ndouble RNN<OutputLayerType, 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 InitializationRuleType,\n         typename... CustomLayers>\ntemplate<typename GradType>\ndouble RNN<OutputLayerType, InitializationRuleType, CustomLayers...>::\nEvaluateWithGradient(const arma::mat& /* parameters */,\n                     const size_t begin,\n                     GradType& gradient,\n                     const size_t batchSize)\n{\n  // Initialize passed gradient.\n  if (gradient.is_empty())\n  {\n    if (parameter.is_empty())\n    {\n      ResetParameters();\n    }\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  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  ResetCells();\n\n  double performance = 0;\n  size_t responseSeq = 0;\n  const size_t effectiveRho = std::min(rho, size_t(responses.size()));\n\n  for (size_t seqNum = 0; seqNum < effectiveRho; ++seqNum)\n  {\n    // Wrap a matrix around our data to avoid a copy.\n    arma::mat stepData(predictors.slice(seqNum).colptr(begin),\n        predictors.n_rows, batchSize, false, true);\n    Forward(stepData);\n    if (!single)\n    {\n      responseSeq = seqNum;\n    }\n\n    for (size_t l = 0; l < network.size(); ++l)\n    {\n      boost::apply_visitor(SaveOutputParameterVisitor(moduleOutputParameter),\n          network[l]);\n    }\n\n    performance += outputLayer.Forward(boost::apply_visitor(\n        outputParameterVisitor, network.back()),\n        arma::mat(responses.slice(responseSeq).colptr(begin),\n            responses.n_rows, batchSize, false, true));\n  }\n\n  if (outputSize == 0)\n  {\n    outputSize = boost::apply_visitor(outputParameterVisitor,\n        network.back()).n_elem / batchSize;\n  }\n\n  // Initialize current/working gradient.\n  if (currentGradient.is_empty())\n  {\n    currentGradient = arma::zeros<arma::mat>(parameter.n_rows,\n        parameter.n_cols);\n  }\n\n  ResetGradients(currentGradient);\n\n  for (size_t seqNum = 0; seqNum < effectiveRho; ++seqNum)\n  {\n    currentGradient.zeros();\n    for (size_t l = 0; l < network.size(); ++l)\n    {\n      boost::apply_visitor(LoadOutputParameterVisitor(moduleOutputParameter),\n          network[network.size() - 1 - l]);\n    }\n\n    if (single && seqNum > 0)\n    {\n      error.zeros();\n    }\n    else if (single && seqNum == 0)\n    {\n      outputLayer.Backward(boost::apply_visitor(\n          outputParameterVisitor, network.back()),\n          arma::mat(responses.slice(0).colptr(begin),\n          responses.n_rows, batchSize, false, true), error);\n    }\n    else\n    {\n      outputLayer.Backward(boost::apply_visitor(\n          outputParameterVisitor, network.back()),\n          arma::mat(responses.slice(effectiveRho - seqNum - 1).colptr(begin),\n          responses.n_rows, batchSize, false, true), error);\n    }\n\n    Backward();\n    Gradient(\n        arma::mat(predictors.slice(effectiveRho - seqNum - 1).colptr(begin),\n        predictors.n_rows, batchSize, false, true));\n    gradient += currentGradient;\n  }\n\n  return performance;\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid RNN<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 RNN<OutputLayerType, 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 InitializationRuleType,\n         typename... CustomLayers>\nvoid RNN<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  reset = true;\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid RNN<OutputLayerType, InitializationRuleType, CustomLayers...>::Reset()\n{\n  ResetParameters();\n  ResetCells();\n  currentGradient.zeros();\n  ResetGradients(currentGradient);\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid RNN<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 RNN<OutputLayerType, InitializationRuleType,\n         CustomLayers...>::ResetGradients(\n    arma::mat& gradient)\n{\n  size_t offset = 0;\n  for (LayerTypes<CustomLayers...>& layer : network)\n  {\n    offset += boost::apply_visitor(GradientSetVisitor(gradient, offset), layer);\n  }\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\ntemplate<typename InputType>\nvoid RNN<OutputLayerType, InitializationRuleType,\n         CustomLayers...>::Forward(const InputType& input)\n{\n  boost::apply_visitor(ForwardVisitor(input,\n      boost::apply_visitor(outputParameterVisitor, network.front())),\n      network.front());\n\n  for (size_t i = 1; i < network.size(); ++i)\n  {\n    boost::apply_visitor(ForwardVisitor(\n        boost::apply_visitor(outputParameterVisitor, network[i - 1]),\n        boost::apply_visitor(outputParameterVisitor, network[i])),\n        network[i]);\n  }\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid RNN<OutputLayerType, InitializationRuleType, CustomLayers...>::Backward()\n{\n  boost::apply_visitor(BackwardVisitor(\n        boost::apply_visitor(outputParameterVisitor, network.back()),\n        error, boost::apply_visitor(deltaVisitor,\n        network.back())), network.back());\n\n  for (size_t i = 2; i < network.size(); ++i)\n  {\n    boost::apply_visitor(BackwardVisitor(\n        boost::apply_visitor(outputParameterVisitor,\n        network[network.size() - i]), boost::apply_visitor(\n        deltaVisitor, network[network.size() - i + 1]),\n        boost::apply_visitor(deltaVisitor, network[network.size() - i])),\n        network[network.size() - i]);\n  }\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\ntemplate<typename InputType>\nvoid RNN<OutputLayerType, InitializationRuleType,\n         CustomLayers...>::Gradient(const InputType& input)\n{\n  boost::apply_visitor(GradientVisitor(input,\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(\n        boost::apply_visitor(outputParameterVisitor, network[i - 1]),\n        boost::apply_visitor(deltaVisitor, network[i + 1])),\n        network[i]);\n  }\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\ntemplate<typename Archive>\nvoid RNN<OutputLayerType, InitializationRuleType, CustomLayers...>::serialize(\n    Archive& ar, const unsigned int version)\n{\n  ar & BOOST_SERIALIZATION_NVP(parameter);\n  ar & BOOST_SERIALIZATION_NVP(rho);\n  ar & BOOST_SERIALIZATION_NVP(single);\n  ar & BOOST_SERIALIZATION_NVP(inputSize);\n  ar & BOOST_SERIALIZATION_NVP(outputSize);\n  ar & BOOST_SERIALIZATION_NVP(targetSize);\n\n  // Earlier versions of the RNN code did not serialize the 'reset' variable.\n  if (version > 0)\n  {\n    ar & BOOST_SERIALIZATION_NVP(reset);\n  }\n\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    // Earlier versions of the RNN code assumed that the weights needed to be\n    // reset on load.\n    if (version == 0)\n      reset = false;\n\n    size_t offset = 0;\n    for (LayerTypes<CustomLayers...>& layer : network)\n    {\n      offset += boost::apply_visitor(WeightSetVisitor(parameter, offset),\n          layer);\n\n      boost::apply_visitor(resetVisitor, layer);\n    }\n\n    deterministic = true;\n    ResetDeterministic();\n  }\n}\n\n} // namespace ann\n} // namespace mlpack\n\n#endif\n", "meta": {"hexsha": "8b15f50f352c51a5ba9887667f2b70141003d201", "size": 17713, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/methods/ann/rnn_impl.hpp", "max_stars_repo_name": "gaurav-singh1998/mlpack", "max_stars_repo_head_hexsha": "c104a2dcf0b51a98d9d6fcfc01d4e7047cc83872", "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-12-18T13:33:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-18T13:33:24.000Z", "max_issues_repo_path": "src/mlpack/methods/ann/rnn_impl.hpp", "max_issues_repo_name": "R-Aravind/mlpack", "max_issues_repo_head_hexsha": "99d11a9b4d379885cf7f8160d8c71fb792fa1bbc", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/methods/ann/rnn_impl.hpp", "max_forks_repo_name": "R-Aravind/mlpack", "max_forks_repo_head_hexsha": "99d11a9b4d379885cf7f8160d8c71fb792fa1bbc", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-17T21:33:59.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-17T21:33:59.000Z", "avg_line_length": 29.5216666667, "max_line_length": 80, "alphanum_fraction": 0.6915824536, "num_tokens": 4110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.29080524237603533}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n// \n// Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>\n// \n// This Source Code Form is subject to the terms of the Mozilla Public License \n// v. 2.0. If a copy of the MPL was not distributed with this file, You can \n// obtain one at http://mozilla.org/MPL/2.0/.\n#include \"arap_linear_block.h\"\n#include \"verbose.h\"\n#include \"cotmatrix_entries.h\"\n#include <Eigen/Dense>\n\ntemplate <typename MatV, typename MatF, typename Scalar>\nIGL_INLINE void igl::arap_linear_block(\n  const MatV & V,\n  const MatF & F,\n  const int d,\n  const igl::ARAPEnergyType energy,\n  Eigen::SparseMatrix<Scalar> & Kd)\n{\n  switch(energy)\n  {\n    case ARAP_ENERGY_TYPE_SPOKES:\n      return igl::arap_linear_block_spokes(V,F,d,Kd);\n      break;\n    case ARAP_ENERGY_TYPE_SPOKES_AND_RIMS:\n      return igl::arap_linear_block_spokes_and_rims(V,F,d,Kd);\n      break;\n    case ARAP_ENERGY_TYPE_ELEMENTS:\n      return igl::arap_linear_block_elements(V,F,d,Kd);\n      break;\n    default:\n      verbose(\"Unsupported energy type: %d\\n\",energy);\n      assert(false);\n  }\n}\n\n\ntemplate <typename MatV, typename MatF, typename Scalar>\nIGL_INLINE void igl::arap_linear_block_spokes(\n  const MatV & V,\n  const MatF & F,\n  const int d,\n  Eigen::SparseMatrix<Scalar> & Kd)\n{\n  using namespace std;\n  using namespace Eigen;\n  // simplex size (3: triangles, 4: tetrahedra)\n  int simplex_size = F.cols();\n  // Number of elements\n  int m = F.rows();\n  // Temporary output\n  Matrix<int,Dynamic,2> edges;\n  Kd.resize(V.rows(), V.rows());\n  vector<Triplet<Scalar> > Kd_IJV;\n  if(simplex_size == 3)\n  {\n    // triangles\n    Kd.reserve(7*V.rows());\n    Kd_IJV.reserve(7*V.rows());\n    edges.resize(3,2);\n    edges << \n      1,2,\n      2,0,\n      0,1;\n  }else if(simplex_size == 4)\n  {\n    // tets\n    Kd.reserve(17*V.rows());\n    Kd_IJV.reserve(17*V.rows());\n    edges.resize(6,2);\n    edges << \n      1,2,\n      2,0,\n      0,1,\n      3,0,\n      3,1,\n      3,2;\n  }\n  // gather cotangent weights\n  Matrix<Scalar,Dynamic,Dynamic> C;\n  cotmatrix_entries(V,F,C);\n  // should have weights for each edge\n  assert(C.cols() == edges.rows());\n  // loop over elements\n  for(int i = 0;i<m;i++)\n  {\n    // loop over edges of element\n    for(int e = 0;e<edges.rows();e++)\n    {\n      int source = F(i,edges(e,0));\n      int dest = F(i,edges(e,1));\n      double v = 0.5*C(i,e)*(V(source,d)-V(dest,d));\n      Kd_IJV.push_back(Triplet<Scalar>(source,dest,v));\n      Kd_IJV.push_back(Triplet<Scalar>(dest,source,-v));\n      Kd_IJV.push_back(Triplet<Scalar>(source,source,v));\n      Kd_IJV.push_back(Triplet<Scalar>(dest,dest,-v));\n    }\n  }\n  Kd.setFromTriplets(Kd_IJV.begin(),Kd_IJV.end());\n  Kd.makeCompressed();\n}\n\ntemplate <typename MatV, typename MatF, typename Scalar>\nIGL_INLINE void igl::arap_linear_block_spokes_and_rims(\n  const MatV & V,\n  const MatF & F,\n  const int d,\n  Eigen::SparseMatrix<Scalar> & Kd)\n{\n  using namespace std;\n  using namespace Eigen;\n  // simplex size (3: triangles, 4: tetrahedra)\n  int simplex_size = F.cols();\n  // Number of elements\n  int m = F.rows();\n  // Temporary output\n  Kd.resize(V.rows(), V.rows());\n  vector<Triplet<Scalar> > Kd_IJV;\n  Matrix<int,Dynamic,2> edges;\n  if(simplex_size == 3)\n  {\n    // triangles\n    Kd.reserve(7*V.rows());\n    Kd_IJV.reserve(7*V.rows());\n    edges.resize(3,2);\n    edges << \n      1,2,\n      2,0,\n      0,1;\n  }else if(simplex_size == 4)\n  {\n    // tets\n    Kd.reserve(17*V.rows());\n    Kd_IJV.reserve(17*V.rows());\n    edges.resize(6,2);\n    edges << \n      1,2,\n      2,0,\n      0,1,\n      3,0,\n      3,1,\n      3,2;\n    // Not implemented yet for tets\n    assert(false);\n  }\n  // gather cotangent weights\n  Matrix<Scalar,Dynamic,Dynamic> C;\n  cotmatrix_entries(V,F,C);\n  // should have weights for each edge\n  assert(C.cols() == edges.rows());\n  // loop over elements\n  for(int i = 0;i<m;i++)\n  {\n    // loop over edges of element\n    for(int e = 0;e<edges.rows();e++)\n    {\n      int source = F(i,edges(e,0));\n      int dest = F(i,edges(e,1));\n      double v = C(i,e)*(V(source,d)-V(dest,d))/3.0;\n      // loop over edges again\n      for(int f = 0;f<edges.rows();f++)\n      {\n        int Rs = F(i,edges(f,0));\n        int Rd = F(i,edges(f,1));\n        if(Rs == source && Rd == dest)\n        {\n          Kd_IJV.push_back(Triplet<Scalar>(Rs,Rd,v));\n          Kd_IJV.push_back(Triplet<Scalar>(Rd,Rs,-v));\n        }else if(Rd == source)\n        {\n          Kd_IJV.push_back(Triplet<Scalar>(Rd,Rs,v));\n        }else if(Rs == dest)\n        {\n          Kd_IJV.push_back(Triplet<Scalar>(Rs,Rd,-v));\n        }\n      }\n      Kd_IJV.push_back(Triplet<Scalar>(source,source,v));\n      Kd_IJV.push_back(Triplet<Scalar>(dest,dest,-v));\n    }\n  }\n  Kd.setFromTriplets(Kd_IJV.begin(),Kd_IJV.end());\n  Kd.makeCompressed();\n}\n\ntemplate <typename MatV, typename MatF, typename Scalar>\nIGL_INLINE void igl::arap_linear_block_elements(\n  const MatV & V,\n  const MatF & F,\n  const int d,\n  Eigen::SparseMatrix<Scalar> & Kd)\n{\n  using namespace std;\n  using namespace Eigen;\n  // simplex size (3: triangles, 4: tetrahedra)\n  int simplex_size = F.cols();\n  // Number of elements\n  int m = F.rows();\n  // Temporary output\n  Kd.resize(V.rows(), F.rows());\n  vector<Triplet<Scalar> > Kd_IJV;\n  Matrix<int,Dynamic,2> edges;\n  if(simplex_size == 3)\n  {\n    // triangles\n    Kd.reserve(7*V.rows());\n    Kd_IJV.reserve(7*V.rows());\n    edges.resize(3,2);\n    edges << \n      1,2,\n      2,0,\n      0,1;\n  }else if(simplex_size == 4)\n  {\n    // tets\n    Kd.reserve(17*V.rows());\n    Kd_IJV.reserve(17*V.rows());\n    edges.resize(6,2);\n    edges << \n      1,2,\n      2,0,\n      0,1,\n      3,0,\n      3,1,\n      3,2;\n  }\n  // gather cotangent weights\n  Matrix<Scalar,Dynamic,Dynamic> C;\n  cotmatrix_entries(V,F,C);\n  // should have weights for each edge\n  assert(C.cols() == edges.rows());\n  // loop over elements\n  for(int i = 0;i<m;i++)\n  {\n    // loop over edges of element\n    for(int e = 0;e<edges.rows();e++)\n    {\n      int source = F(i,edges(e,0));\n      int dest = F(i,edges(e,1));\n      double v = C(i,e)*(V(source,d)-V(dest,d));\n      Kd_IJV.push_back(Triplet<Scalar>(source,i,v));\n      Kd_IJV.push_back(Triplet<Scalar>(dest,i,-v));\n    }\n  }\n  Kd.setFromTriplets(Kd_IJV.begin(),Kd_IJV.end());\n  Kd.makeCompressed();\n}\n\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\ntemplate IGL_INLINE void igl::arap_linear_block<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, double>(Eigen::Matrix<double, -1, -1, 0, -1, -1> const&, Eigen::Matrix<int, -1, -1, 0, -1, -1> const&, int, igl::ARAPEnergyType, Eigen::SparseMatrix<double, 0, int>&);\n#endif\n", "meta": {"hexsha": "14886b2bc74cda6e3f0497fcaa08328a08a04f53", "size": 6657, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "igl/arap_linear_block.cpp", "max_stars_repo_name": "aviadtzemah/animation2", "max_stars_repo_head_hexsha": "9a3f980fbe27672fe71f8f61f73b5713f2af5089", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2392.0, "max_stars_repo_stars_event_min_datetime": "2016-12-17T14:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:40:40.000Z", "max_issues_repo_path": "igl/arap_linear_block.cpp", "max_issues_repo_name": "aviadtzemah/animation2", "max_issues_repo_head_hexsha": "9a3f980fbe27672fe71f8f61f73b5713f2af5089", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 106.0, "max_issues_repo_issues_event_min_datetime": "2018-04-19T17:47:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T19:44:11.000Z", "max_forks_repo_path": "igl/arap_linear_block.cpp", "max_forks_repo_name": "aviadtzemah/animation2", "max_forks_repo_head_hexsha": "9a3f980fbe27672fe71f8f61f73b5713f2af5089", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 184.0, "max_forks_repo_forks_event_min_datetime": "2017-11-15T09:55:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T16:30:46.000Z", "avg_line_length": 26.2086614173, "max_line_length": 296, "alphanum_fraction": 0.6050773622, "num_tokens": 2153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.44167300566462564, "lm_q1q2_score": 0.2908052364552689}}
{"text": "#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n#include <iterator>\n#include <fstream>\n#include <sstream>\n#include <list>\n#include <map>\n#include <ext/algorithm>\n#include <numeric>\n#include <sys/timeb.h>\n#include <time.h>\n#include <cstdlib>\n#include <cstdio>\n\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/serialization/vector.hpp>\n#include <boost/serialization/utility.hpp>\n\n#include \"rbt_coarse.h\"\n#include \"rbt_dense.h\"\n#include \"rbt_pose.h\"\n\n#include \"CGAL/Cartesian.h\"\n#include \"CGAL/Segment_tree_k.h\"\n#include \"CGAL/Range_segment_tree_traits.h\"\n\n#include \"CGAL/basic.h\" \n#include \"CGAL/Point_3.h\"\n#include \"CGAL/Range_tree_k.h\"\n\ntypedef CGAL::Cartesian<double> CTP_Representation;\ntypedef CGAL::Range_tree_map_traits_3<CTP_Representation, unsigned short> CTP_Traits;\ntypedef CGAL::Range_tree_3<CTP_Traits> CTP_Range_tree_3_type;\ntypedef CTP_Traits::Key CTP_Key;\ntypedef CTP_Traits::Pure_key CTP_Pure_key;\ntypedef CTP_Traits::Interval CTP_Interval;\n\nusing namespace std;\n\n\n//typedef double RotationMatrix[3][3];\n//typedef vector<vector<double> > RotationMatrix(3, vector<double>(3, 0));\n\ntemplate <class FirstType, class SecondType>\nstruct less_than_univ{\n    bool operator()(pair<FirstType, SecondType> pm_A, pair<FirstType, SecondType> pm_B)\n    {\n        if (pm_A.first < pm_B.first) return true;\n        else return false;\n    }\n};\n\n\ntemplate <class T>\nT rdl_dot_3d(const vector<T>& pm_v1, const vector<T>& pm_v2)\n{\n    T     r;\n    r  = pm_v1[0] * pm_v2[0];\n    r += pm_v1[1] * pm_v2[1];\n    r += pm_v1[2] * pm_v2[2];\n\n    return r;\n}\n\n\ntemplate <class T>\nvoid rdl_rotate(vector<T> const &pm_axis, \\\n                vector<T> const &pm_old_point, \\\n                T  \t            pm_angle, \\\n                vector<T>       &pm_new_point)\n{\n    pm_new_point[0] = 0.0;\n    pm_new_point[1] = 0.0;\n    pm_new_point[2] = 0.0;\n    double costheta, sintheta;\n\n    costheta = cos(pm_angle);\n    sintheta = sin(pm_angle);\n\n    pm_new_point[0] += (costheta + (1 - costheta) * pm_axis[0] * pm_axis[0]) * pm_old_point[0];\n    pm_new_point[0] += ((1 - costheta) * pm_axis[0] * pm_axis[1] - pm_axis[2] * sintheta) * pm_old_point[1];\n    pm_new_point[0] += ((1 - costheta) * pm_axis[0] * pm_axis[2] + pm_axis[1] * sintheta) * pm_old_point[2];\n\n    pm_new_point[1] += ((1 - costheta) * pm_axis[0] * pm_axis[1] + pm_axis[2] * sintheta) * pm_old_point[0];\n    pm_new_point[1] += (costheta + (1 - costheta) * pm_axis[1] * pm_axis[1]) * pm_old_point[1];\n    pm_new_point[1] += ((1 - costheta) * pm_axis[1] * pm_axis[2] - pm_axis[0] * sintheta) * pm_old_point[2];\n\n    pm_new_point[2] += ((1 - costheta) * pm_axis[0] * pm_axis[2] - pm_axis[1] * sintheta) * pm_old_point[0];\n    pm_new_point[2] += ((1 - costheta) * pm_axis[1] * pm_axis[2] + pm_axis[0] * sintheta) * pm_old_point[1];\n    pm_new_point[2] += (costheta + (1 - costheta) * pm_axis[2] * pm_axis[2]) * pm_old_point[2];\n\n    return;\n}\n\nvoid normalize(vector<double>& v)\n{\n\tdouble n;\n\tn = v[0] * v[0] + v[1] * v[1] + v[2] * v[2];\n\tif (n < 0.5){\n\t\tcerr << \"n is very small! = \" << n << endl; \n\t}\n\tn = sqrt(n);\n\tv[0] /= n;\n\tv[1] /= n;\n\tv[2] /= n;\n}\n\nstruct MyBall{\n\tCTP_Range_tree_3_type*      m_index;\n\n\tMyBall() \n\t{\n\t\tm_index = NULL;\n\t}\n\n\tvoid query_local(const vector<double>&\tpm_point, double pm_r, vector<unsigned short>& pm_out)\n\t{\n\t\tpm_out.clear();\n\n\t\tvector<CTP_Key> OutputList;\n\t\t\n\t\tCTP_Pure_key a = CTP_Pure_key(pm_point[0] - pm_r, pm_point[1] - pm_r, pm_point[2] - pm_r);\n\t\tCTP_Pure_key b = CTP_Pure_key(pm_point[0] + pm_r, pm_point[1] + pm_r, pm_point[2] + pm_r);\n\t\tCTP_Interval win = CTP_Interval(CTP_Key(a, 0), CTP_Key(b, 0));\n\t\tm_index->window_query(win, back_inserter(OutputList));\n\n\t\tif (OutputList.size() == 0){\n\t\t\tcerr << \"ERROR: OutputList.size() == 0 in query_nnb(...)! \" << endl;\n\t\t\tcerr << \"\\twhen query (\" << pm_point[0] << \", \" << pm_point[1] << \", \" << pm_point[2] << \")\" << endl;\n\t\t\texit(1);\n\t\t}\n\t\t\n\t\tvector<pair<double, unsigned short> >\ttmp_buffer;\n\t\tdouble tmp_dist;\t\n\t\tdouble tmp_rsq = pm_r * pm_r;\n\t\tsize_t i;\n\t\tfor (i = 0; i < OutputList.size(); i++){\n\t\t\ttmp_dist  = (pm_point[0] - OutputList[i].first.x()) * (pm_point[0] - OutputList[i].first.x());\n\t\t\ttmp_dist += (pm_point[1] - OutputList[i].first.y()) * (pm_point[1] - OutputList[i].first.y());\n\t\t\ttmp_dist += (pm_point[2] - OutputList[i].first.z()) * (pm_point[2] - OutputList[i].first.z());\n\t\t\tif (tmp_dist <= tmp_rsq){\n\t\t\t\tpm_out.push_back(OutputList[i].second);\n\t\t\t}\n\t\t}\n\t}\n\n\tunsigned short query_nn(const vector<double>&\tpm_point)\n\t{\n\t\tvector<CTP_Key> OutputList;\n\t\t\n\t\tdouble\ttmp_local_dist = 0.09;\n\t\tCTP_Pure_key a = CTP_Pure_key(pm_point[0] - tmp_local_dist, pm_point[1] - tmp_local_dist, pm_point[2] - tmp_local_dist);\n\t\tCTP_Pure_key b = CTP_Pure_key(pm_point[0] + tmp_local_dist, pm_point[1] + tmp_local_dist, pm_point[2] + tmp_local_dist);\n\t\tCTP_Interval win = CTP_Interval(CTP_Key(a, 0), CTP_Key(b, 0));\n\t\tm_index->window_query(win, back_inserter(OutputList));\n\n\t\tif (OutputList.size() == 0){\n\t\t\tcerr << \"ERROR: OutputList.size() == 0 in query_nnb(...)! \" << endl;\n\t\t\tcerr << \"\\twhen query (\" << pm_point[0] << \", \" << pm_point[1] << \", \" << pm_point[2] << \")\" << endl;\n\t\t\texit(1);\n\t\t}\n\t\t\n\t\tvector<pair<double, unsigned short> >\ttmp_buffer;\n\t\tdouble tmp_dist;\t\n\t\tsize_t i;\n\t\tfor (i = 0; i < OutputList.size(); i++){\n\t\t\ttmp_dist  = (pm_point[0] - OutputList[i].first.x()) * (pm_point[0] - OutputList[i].first.x());\n\t\t\ttmp_dist += (pm_point[1] - OutputList[i].first.y()) * (pm_point[1] - OutputList[i].first.y());\n\t\t\ttmp_dist += (pm_point[2] - OutputList[i].first.z()) * (pm_point[2] - OutputList[i].first.z());\n\t\t\ttmp_buffer.push_back(pair<double, unsigned short>(tmp_dist, OutputList[i].second));\n\t\t}\n\n\t\tsort(tmp_buffer.begin(), tmp_buffer.end(), less_than_univ<double, unsigned short>());\n\n\t\treturn tmp_buffer[0].second;\n\t}\n};\n\nstruct MyBall_Coarse: public MyBall{\n\n\tvoid init()\n\t{\n\t\tvector<CTP_Key>             InputList;\n\t\tvector<double>              tmp_point(3, 0);\n\t\tsize_t i;\n\n\t\tfor (i = 0; i < points_default_coarse; i ++){\n\t\t\tInputList.push_back(CTP_Key(CTP_Pure_key(vertex_default_coarse[i][0], vertex_default_coarse[i][1], vertex_default_coarse[i][2]), i));\n\t\t}\n\t\t\n\t\tm_index = new CTP_Range_tree_3_type(InputList.begin(), InputList.end());\n\t}\n};\n\nstruct MyBall_Dense: public MyBall{\n\n\tvoid init()\n\t{\n\t\tvector<CTP_Key>             InputList;\n\t\tvector<double>              tmp_point(3, 0);\n\t\tsize_t i;\n\n\t\tfor (i = 0; i < points_default_dense; i ++){\n\t\t\tInputList.push_back(CTP_Key(CTP_Pure_key(vertex_default_dense[i][0], vertex_default_dense[i][1], vertex_default_dense[i][2]), i));\n\t\t}\n\t\t\n\t\tm_index = new CTP_Range_tree_3_type(InputList.begin(), InputList.end());\n\t}\n};\n\nstruct MyBall_Pose: public MyBall{\n\tvector<vector<vector<double> > >\t\tm_arcs;\n\n\tvoid init()\n\t{\n\t\tvector<CTP_Key>             InputList;\n\t\tvector<double>              tmp_point(3, 0);\n\t\tsize_t i;\n\n\t\tfor (i = 0; i < points_default_pose; i ++){\n\t\t\tInputList.push_back(CTP_Key(CTP_Pure_key(vertex_default_pose[i][0], vertex_default_pose[i][1], vertex_default_pose[i][2]), i));\n\t\t}\n\t\t\n\t\tm_index = new CTP_Range_tree_3_type(InputList.begin(), InputList.end());\n\t}\n\n\tvoid init_pose()\n\t{\n\t\tsize_t i, j;\n\t\tvector<double>\tcurr_point(3, 0);\n\t\tvector<double>\trand_point(3, 0);\n\t\tdouble\t\t\tdist;\n\t\tdouble\t\t\ttheta;\n\t\tvector<double>\ttmp_Z(3, 0);\n\t\tvector<double>\ttmp_Y(3, 0);\n\t\tvector<double>\ttmp_X(3, 0);\n\n\t\tsrand(time(NULL));\n\t\tvector<vector<double> >\ttmp_buff;\n\t\tvector<vector<double> >\ttmp_coord;\n\n\t\tm_arcs.clear();\n\t\tfor (i = 0; i < points_default_pose; i ++){\n\t\t\tcurr_point[0] = vertex_default_pose[i][0];\n\t\t\tcurr_point[1] = vertex_default_pose[i][1];\n\t\t\tcurr_point[2] = vertex_default_pose[i][2];\n\t\t\tj = rand() % points_default_pose;\n\t\t\trand_point[0] = vertex_default_pose[j][0];\n\t\t\trand_point[1] = vertex_default_pose[j][1];\n\t\t\trand_point[2] = vertex_default_pose[j][2];\n\t\t\tdist  = (curr_point[0] - rand_point[0]) * (curr_point[0] - rand_point[0]);\n\t\t\tdist += (curr_point[1] - rand_point[1]) * (curr_point[1] - rand_point[1]);\n\t\t\tdist += (curr_point[2] - rand_point[2]) * (curr_point[2] - rand_point[2]);\n\t\t\twhile(dist < 1 || dist > 3){\n\t\t\t\tj = rand() % points_default_pose;\n\t\t\t\trand_point[0] = vertex_default_pose[j][0];\n\t\t\t\trand_point[1] = vertex_default_pose[j][1];\n\t\t\t\trand_point[2] = vertex_default_pose[j][2];\n\t\t\t\tdist  = (curr_point[0] - rand_point[0]) * (curr_point[0] - rand_point[0]);\n\t\t\t\tdist += (curr_point[1] - rand_point[1]) * (curr_point[1] - rand_point[1]);\n\t\t\t\tdist += (curr_point[2] - rand_point[2]) * (curr_point[2] - rand_point[2]);\n\t\t\t}\n\n\t\t\ttmp_Y[0] = curr_point[1] * rand_point[2] - curr_point[2] * rand_point[1];\n\t\t\ttmp_Y[1] = curr_point[2] * rand_point[0] - curr_point[0] * rand_point[2];\n\t\t\ttmp_Y[2] = curr_point[0] * rand_point[1] - curr_point[1] * rand_point[0];\n\t\t\tnormalize(tmp_Y);\n\t\t\ttmp_X[0] = tmp_Y[1] * curr_point[2] - tmp_Y[2] * curr_point[1];\n\t\t\ttmp_X[1] = tmp_Y[2] * curr_point[0] - tmp_Y[0] * curr_point[2];\n\t\t\ttmp_X[2] = tmp_Y[0] * curr_point[1] - tmp_Y[1] * curr_point[0];\n\t\t\tnormalize(tmp_X);\n\t\t\ttmp_buff.clear();\n\t\t\tfor (j = 0; j < 360; j ++){\n\t\t\t\ttheta = 2.0*i*M_PI/360;\n\t\t\t\trdl_rotate(curr_point, tmp_X, theta, rand_point);\n\t\t\t\ttmp_buff.push_back(rand_point);\n\t\t\t}\n\t\t\trandom_shuffle(tmp_buff.begin(), tmp_buff.end());\n\t\t\trand_point = tmp_buff[rand()%tmp_buff.size()];\n\n\t\t\ttmp_Y[0] = curr_point[1] * rand_point[2] - curr_point[2] * rand_point[1];\n\t\t\ttmp_Y[1] = curr_point[2] * rand_point[0] - curr_point[0] * rand_point[2];\n\t\t\ttmp_Y[2] = curr_point[0] * rand_point[1] - curr_point[1] * rand_point[0];\n\t\t\tnormalize(tmp_Y);\n\t\t\ttmp_X[0] = tmp_Y[1] * curr_point[2] - tmp_Y[2] * curr_point[1];\n\t\t\ttmp_X[1] = tmp_Y[2] * curr_point[0] - tmp_Y[0] * curr_point[2];\n\t\t\ttmp_X[2] = tmp_Y[0] * curr_point[1] - tmp_Y[1] * curr_point[0];\n\t\t\tnormalize(tmp_X);\n\t\t\ttmp_Z = curr_point;\n\n\t\t\ttmp_coord.clear();\n\t\t\ttmp_coord.push_back(tmp_X);\n\t\t\ttmp_coord.push_back(tmp_Y);\n\t\t\ttmp_coord.push_back(tmp_Z);\n\t\t\tm_arcs.push_back(tmp_coord);\n\n            //cout << \"X*Y = \" << rdl_dot_3d(tmp_X, tmp_Y) << endl;\n            //cout << \"Y*Z = \" << rdl_dot_3d(tmp_Y, tmp_Z) << endl;\n            //cout << \"Z*X = \" << rdl_dot_3d(tmp_Z, tmp_X) << endl;\n\n\n\t\t\ttmp_coord.clear();\n\t\t\ttmp_X[0] = 0 - tmp_X[0];\n\t\t\ttmp_X[1] = 0 - tmp_X[1];\n\t\t\ttmp_X[2] = 0 - tmp_X[2];\n\n\t\t\ttmp_Y[0] = 0 - tmp_Y[0];\n\t\t\ttmp_Y[1] = 0 - tmp_Y[1];\n\t\t\ttmp_Y[2] = 0 - tmp_Y[2];\n\n\t\t\ttmp_coord.push_back(tmp_X);\n\t\t\ttmp_coord.push_back(tmp_Y);\n\t\t\ttmp_coord.push_back(tmp_Z);\n\t\t\tm_arcs.push_back(tmp_coord);\n            \n            //cout << \"X*Y = \" << rdl_dot_3d(tmp_X, tmp_Y) << endl;\n            //cout << \"Y*Z = \" << rdl_dot_3d(tmp_Y, tmp_Z) << endl;\n            //cout << \"Z*X = \" << rdl_dot_3d(tmp_Z, tmp_X) << endl << endl;\n\t\t}\n\t}\n};\n\n\nstruct MyUnitBall{\n\tvector<vector<double> >\t\tm_unitball_coarse;\n\tvector<vector<double> >\t\tm_unitball_dense;\n\n\tMyBall_Coarse\t\t\tm_coarse;\n\tMyBall_Dense\t\t\t\tm_dense;\n\tMyBall_Pose\t\t\t\tm_pose;\n\tvector<vector<unsigned short> >\t\t\t\tm_table;\t\t//[12560*2][1256]\n\tvector<vector<pair<unsigned short, unsigned short> > >\tm_table_sort;\t\t//[12560*2][1256]\n\tvector<vector<unsigned short> >\t\t\t\tm_table_coarse2dense;\n\tvector<vector<unsigned short> >\t\t\t\tm_table_dense2coarse;\n\tvector<vector<vector<double> > >\t\t\tm_rmatrix;\n    \n\tvoid ssave_matching_table(string pm_filename)\n\t{\n\t\tstd::ofstream ofs(pm_filename.c_str());\n\t\tboost::archive::text_oarchive oa(ofs);\n\t\toa & m_table;\n\t}\n\t\n\n\tvoid ssave_matching_table_sort(string pm_filename)\n\t{\n\t\tstd::ofstream ofs(pm_filename.c_str());\n\t\tboost::archive::text_oarchive oa(ofs);\n\t\toa & m_table_sort;\n\t}\n\n\n\tvoid ssave_matching_table_coarse2dense(string pm_filename)\n\t{\n\t\tstd::ofstream ofs(pm_filename.c_str());\n\t\tboost::archive::text_oarchive oa(ofs);\n\t\toa & m_table_coarse2dense;\n\t}\n\n\tvoid ssave_matching_table_dense2coarse(string pm_filename)\n\t{\n\t\tstd::ofstream ofs(pm_filename.c_str());\n\t\tboost::archive::text_oarchive oa(ofs);\n\t\toa & m_table_dense2coarse;\n\t}\n\n\tvoid ssave_matching_table_rmatrix(string pm_filename)\n\t{\n\t\tstd::ofstream ofs(pm_filename.c_str());\n\t\tboost::archive::text_oarchive oa(ofs);\n\t\toa & m_rmatrix;\n\t}\n\t\n\n\n\tvoid sload_matching_table(string pm_filename)\n\t{\n\t\tm_table.clear();\n\t\tstd::ifstream ifs(pm_filename.c_str(), std::ios::binary);\n\t\tboost::archive::text_iarchive la(ifs);\n\t\tla & m_table;\n\t}\n\n\tvoid sload_matching_table_sort(string pm_filename)\n\t{\n\t\tm_table_sort.clear();\n\t\tstd::ifstream ifs(pm_filename.c_str(), std::ios::binary);\n\t\tboost::archive::text_iarchive la(ifs);\n\t\tla & m_table_sort;\n\t}\n\n\tvoid sload_matching_table_coarse2dense(string pm_filename)\n\t{\n\t\tm_table_coarse2dense.clear();\n\t\tstd::ifstream ifs(pm_filename.c_str(), std::ios::binary);\n\t\tboost::archive::text_iarchive la(ifs);\n\t\tla & m_table_coarse2dense;\n\t}\n\n\t\n\tvoid sload_matching_table_dense2coarse(string pm_filename)\n\t{\n\t\tm_table_dense2coarse.clear();\n\t\tstd::ifstream ifs(pm_filename.c_str(), std::ios::binary);\n\t\tboost::archive::text_iarchive la(ifs);\n\t\tla & m_table_dense2coarse;\n\t}\n\n\tvoid sload_matching_table_rmatrix(string pm_filename)\n\t{\n\t\tm_rmatrix.clear();\n\t\tstd::ifstream ifs(pm_filename.c_str(), std::ios::binary);\n\t\tboost::archive::text_iarchive la(ifs);\n\t\tla & m_rmatrix;\n\t}\n\n\n\n\tvoid check_table_sort()\n\t{\n\t\tsize_t i, j;\n\n\t\tfor (i = 0; i < m_table_sort.size(); i ++){\n\t\t\tfor (j = 0; j < m_table_sort[i].size(); j ++){\n\t\t\t\tif (m_table[i][m_table_sort[i][j].first] != m_table_sort[i][j].second){\n\t\t\t\t\tcout << \"ERROR: \" << m_table[i][m_table_sort[i][j].first] << \" \" << m_table_sort[i][j].second << endl;\n \t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid write_bin_matching_table_sort(string pm_filename)\n\t{\n        ofstream out_file (pm_filename.c_str(), ios::out|ios::binary);\n\t\tunsigned short* out_buffer = new unsigned short [m_table_sort.size() * m_table_sort[0].size() * 2];\n\t\tchar* head_buffer = reinterpret_cast<char *>(out_buffer);\n\t\tsize_t i, j;\n\t\t\n\t\tfor (i = 0; i < m_table_sort.size(); i ++){\n\t\t\tfor (j = 0; j < m_table_sort[i].size(); j ++){\n\t\t\t\t*(out_buffer++) = m_table_sort[i][j].first;\n\t\t\t\t*(out_buffer++) = m_table_sort[i][j].second;\n\t\t\t}\n\t\t}\n\n\n\t\tunsigned int len = m_table_sort.size();\n\t\tout_file.write(reinterpret_cast<char *>(&len), sizeof(len));\n\t\tlen = m_table_sort[0].size();\n\t\tout_file.write(reinterpret_cast<char *>(&len), sizeof(len));\n\n\t\tout_file.write(head_buffer, m_table_sort.size() * m_table_sort[0].size() * 2 * sizeof(unsigned short));\n\t\tout_file.close();\n\t}\n\n\tvoid read_bin_matching_table_sort(string pm_filename)\n\t{\n\t\tm_table_dense2coarse.clear();\n        ifstream in_file (pm_filename.c_str(), ios::in | ios::binary | ios::ate);\n\t\tifstream::pos_type in_size = in_file.tellg();\n\t\tchar* head_buffer = new char [in_size];\n\t\tin_file.seekg(0, ios::beg);\n\t\tin_file.read(head_buffer, in_size);\n\t\tin_file.close();\n\n\n\t\tunsigned int num_row = *(reinterpret_cast<unsigned int *>(head_buffer));\n\t\tunsigned int num_column = *(reinterpret_cast<unsigned int *>(head_buffer+sizeof(unsigned int)));\n\t\tm_table_sort.insert(m_table_sort.end(), num_row, vector<pair<unsigned short, unsigned short> >(num_column, pair<unsigned short, unsigned short>(0, 0)));\n\t\t\n\t\tsize_t i, j;\n\t\t\n\t\tfor (i = 0; i < num_row; i ++){\n\t\t\tfor (j = 0; j < num_column; j ++){\n\t\t\t\tm_table_sort[i][j].first = (reinterpret_cast<unsigned short *>(head_buffer+2*sizeof(unsigned int)))[i*num_column*2 + j*2];\n\t\t\t\tm_table_sort[i][j].second = (reinterpret_cast<unsigned short *>(head_buffer+2*sizeof(unsigned int)))[i*num_column*2 + j*2 + 1];\n\t\t\t}\n\t\t}\n\t\tdelete[] head_buffer;\n\t}\n\n\n\n\tvoid write_bin_matching_table_dense2coarse(string pm_filename)\n\t{\n        ofstream out_file (pm_filename.c_str(), ios::out|ios::binary);\n\t\tunsigned short* out_buffer = new unsigned short [m_table_dense2coarse.size() * m_table_dense2coarse[0].size()];\n\t\tchar* head_buffer = reinterpret_cast<char *>(out_buffer);\n\t\tsize_t i, j;\n\t\t\n\t\tfor (i = 0; i < m_table_dense2coarse.size(); i ++){\n\t\t\tfor (j = 0; j < m_table_dense2coarse[i].size(); j ++){\n\t\t\t\t*(out_buffer) = m_table_dense2coarse[i][j];\n\t\t\t\tout_buffer ++;\n\t\t\t}\n\t\t}\n\n\n\t\tunsigned int len = m_table_dense2coarse.size();\n\t\tout_file.write(reinterpret_cast<char *>(&len), sizeof(len));\n\t\tlen = m_table_dense2coarse[0].size();\n\t\tout_file.write(reinterpret_cast<char *>(&len), sizeof(len));\n\n\t\tout_file.write(head_buffer, m_table_dense2coarse.size() * m_table_dense2coarse[0].size() * sizeof(unsigned short));\n\t\tout_file.close();\n\t}\n\n\tvoid read_bin_matching_table_dense2coarse()\n\t{\n\t\tm_table_dense2coarse.clear();\n\t\tifstream in_file (\"matching_table_dense2coarse.bin\", ios::in | ios::binary | ios::ate);\n\t\tifstream::pos_type in_size = in_file.tellg();\n\t\tchar* head_buffer = new char [in_size];\n\t\tin_file.seekg(0, ios::beg);\n\t\tin_file.read(head_buffer, in_size);\n\t\tin_file.close();\n\n\n\t\tunsigned int num_row = *(reinterpret_cast<unsigned int *>(head_buffer));\n\t\tunsigned int num_column = *(reinterpret_cast<unsigned int *>(head_buffer+sizeof(unsigned int)));\n\t\tm_table_dense2coarse.insert(m_table_dense2coarse.end(), num_row, vector<unsigned short>(num_column, 0));\n\t\t\n\t\tsize_t i, j;\n\t\t\n\t\tfor (i = 0; i < num_row; i ++){\n\t\t\tfor (j = 0; j < num_column; j ++){\n\t\t\t\tm_table_dense2coarse[i][j] = (reinterpret_cast<unsigned short *>(head_buffer+2*sizeof(unsigned int)))[i*num_column + j];\n\t\t\t}\n\t\t}\n\t\tdelete[] head_buffer;\n\t}\n\n\tvoid write_bin_matching_table_coarse2dense(string pm_filename)\n\t{\n        ofstream out_file (pm_filename.c_str(), ios::out|ios::binary);\n\t\tunsigned short* out_buffer = new unsigned short [m_table_coarse2dense.size() * m_table_coarse2dense[0].size()];\n\t\tchar* head_buffer = reinterpret_cast<char *>(out_buffer);\n\t\tsize_t i, j;\n\t\t\n\t\tfor (i = 0; i < m_table_coarse2dense.size(); i ++){\n\t\t\tfor (j = 0; j < m_table_coarse2dense[i].size(); j ++){\n\t\t\t\t*(out_buffer) = m_table_coarse2dense[i][j];\n\t\t\t\tout_buffer ++;\n\t\t\t}\n\t\t}\n\n\n\t\tunsigned int len = m_table_coarse2dense.size();\n\t\tout_file.write(reinterpret_cast<char *>(&len), sizeof(len));\n\t\tlen = m_table_coarse2dense[0].size();\n\t\tout_file.write(reinterpret_cast<char *>(&len), sizeof(len));\n\n\t\tout_file.write(head_buffer, m_table_coarse2dense.size() * m_table_coarse2dense[0].size() * sizeof(unsigned short));\n\t\tout_file.close();\n\t}\n\n\tvoid read_bin_matching_table_coarse2dense()\n\t{\n\t\tm_table_coarse2dense.clear();\n\t\tifstream in_file (\"matching_table_coarse2dense.bin\", ios::in | ios::binary | ios::ate);\n\t\tifstream::pos_type in_size = in_file.tellg();\n\t\tchar* head_buffer = new char [in_size];\n\t\tin_file.seekg(0, ios::beg);\n\t\tin_file.read(head_buffer, in_size);\n\t\tin_file.close();\n\t\t\n\t\t\n\t\tunsigned int num_row = *(reinterpret_cast<unsigned int *>(head_buffer));\n\t\tunsigned int num_column = *(reinterpret_cast<unsigned int *>(head_buffer+sizeof(unsigned int)));\n\t\tm_table_coarse2dense.insert(m_table_coarse2dense.end(), num_row, vector<unsigned short>(num_column, 0));\n\t\t\n\t\tsize_t i, j;\n\t\t\n\t\tfor (i = 0; i < num_row; i ++){\n\t\t\tfor (j = 0; j < num_column; j ++){\n\t\t\t\tm_table_coarse2dense[i][j] = (reinterpret_cast<unsigned short *>(head_buffer+2*sizeof(unsigned int)))[i*num_column + j];\n\t\t\t}\n\t\t}\n\t\tdelete[] head_buffer;\n\t}\n\n\tvoid write_bin_matching_table(string pm_filename)\n\t{\n        ofstream out_file (pm_filename.c_str(), ios::out|ios::binary);\n\t\tunsigned short* out_buffer = new unsigned short [m_table.size() * m_table[0].size()];\n\t\tchar* head_buffer = reinterpret_cast<char *>(out_buffer);\n\t\tsize_t i, j;\n\t\t\n\t\tfor (i = 0; i < m_table.size(); i ++){\n\t\t\tfor (j = 0; j < m_table[i].size(); j ++){\n\t\t\t\t*(out_buffer) = m_table[i][j];\n\t\t\t\tout_buffer ++;\n\t\t\t}\n\t\t}\n\n\n\t\tunsigned int len = m_table.size();\n\t\tout_file.write(reinterpret_cast<char *>(&len), sizeof(len));\n\t\tlen = m_table[0].size();\n\t\tout_file.write(reinterpret_cast<char *>(&len), sizeof(len));\n\n\t\tout_file.write(head_buffer, m_table.size() * m_table[0].size() * sizeof(unsigned short));\n\t\tout_file.close();\n\t}\n\n\tvoid read_bin_matching_table()\n\t{\n\t\tm_table.clear();\n\t\tifstream in_file (\"matching_table.bin\", ios::in | ios::binary | ios::ate);\n\t\tifstream::pos_type in_size = in_file.tellg();\n\t\tchar* head_buffer = new char [in_size];\n\t\tin_file.seekg(0, ios::beg);\n\t\tin_file.read(head_buffer, in_size);\n\t\tin_file.close();\n\n\t\tunsigned int num_row = *(reinterpret_cast<unsigned int *>(head_buffer));\n\t\tunsigned int num_column = *(reinterpret_cast<unsigned int *>(head_buffer+sizeof(unsigned int)));\n\t\tm_table.insert(m_table.end(), num_row, vector<unsigned short>(num_column, 0));\n\t\t\n\t\tsize_t i, j;\n\t\t\n\t\tfor (i = 0; i < num_row; i ++){\n\t\t\tfor (j = 0; j < num_column; j ++){\n\t\t\t\tm_table[i][j] = (reinterpret_cast<unsigned short *>(head_buffer+2*sizeof(unsigned int)))[i*num_column + j];\n\t\t\t}\n\t\t}\n\n\t\tdelete[] head_buffer;\n\t}\n\n\n\tvoid write_bin_rotation_matrix(string pm_filename)\n\t{\n        ofstream out_file (pm_filename.c_str(), ios::out|ios::binary);\n\t\tdouble* out_buffer = new double [m_rmatrix.size() * 9];\n\t\tchar* head_buffer = reinterpret_cast<char *>(out_buffer);\n\t\tsize_t i, j, k;\n\t\t\n\t\tfor (i = 0; i < m_rmatrix.size(); i ++){\n\t\t\tfor (j = 0; j < m_rmatrix[i].size(); j ++){\n\t\t\t\tfor (k = 0; k < m_rmatrix[i][j].size(); k ++){\n\t\t\t\t\t*(out_buffer) = m_rmatrix[i][j][k];\n\t\t\t\t\tout_buffer ++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tunsigned int len = m_rmatrix.size();\n\t\tout_file.write(reinterpret_cast<char *>(&len), sizeof(len));\n\t\tout_file.write(head_buffer, m_rmatrix.size() * 9 * sizeof(double));\n\t\tout_file.close();\n\t}\n\n\tvoid read_bin_rotation_matrix()\n\t{\n\t\tm_rmatrix.clear();\n\t\tifstream in_file (\"rotation_matrix.bin\", ios::in | ios::binary | ios::ate);\n\t\tifstream::pos_type in_size = in_file.tellg();\n\t\tchar* head_buffer = new char [in_size];\n\t\tin_file.seekg(0, ios::beg);\n\t\tin_file.read(head_buffer, in_size);\n\t\tin_file.close();\n\n\t\tsize_t num_matrix = *(reinterpret_cast<unsigned int *>(head_buffer));\n\t\tm_rmatrix.insert(m_rmatrix.end(), num_matrix, vector<vector<double> >(3, vector<double>(3, 0)));\n\t\tsize_t i, j, k;\n\t\t\n\t\tfor (i = 0; i < num_matrix; i ++){\n\t\t\tfor (j = 0; j < 3; j ++){\n\t\t\t\tfor (k = 0; k < 3; k ++){\n\t\t\t\t\tm_rmatrix[i][j][k] = (reinterpret_cast<double *>(head_buffer+sizeof(unsigned int)))[i*9 + j*3 + k];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdelete[] head_buffer;\n\t}\n\n\tvoid print_rotation_matrix()\n\t{\n\t\tsize_t i;\n\t\t//stringstream out_buffer;\n\t\t//ofstream out_file(\"rotation_matrix.txt\");\n\t\t//out_buffer << m_rmatrix.size() << endl;\n\t\tFILE*\tf = fopen (\"rotation_matrix.txt\",\"w\");\n\t\tfprintf(f, \"%d\\n\", m_rmatrix.size());\n\t\tfor (i = 0; i < m_rmatrix.size(); i ++){\n\t\t\tfprintf(f, \"%+1.16e %+1.16e %+1.16e \",m_rmatrix[i][0][0], m_rmatrix[i][0][1], m_rmatrix[i][0][2]);\n\t\t\tfprintf(f, \"%+1.16e %+1.16e %+1.16e \",m_rmatrix[i][1][0], m_rmatrix[i][1][1], m_rmatrix[i][1][2]);\n\t\t\tfprintf(f, \"%+1.16e %+1.16e %+1.16e\\n\",m_rmatrix[i][2][0], m_rmatrix[i][2][1], m_rmatrix[i][2][2]);\n\n\t\t\t//out_buffer << m_rmatrix[i][0][0] << \" \";\n\t\t\t//out_buffer << m_rmatrix[i][0][1] << \" \";\n\t\t\t//out_buffer << m_rmatrix[i][0][2] << \" \";\n\t\t\t//out_buffer << m_rmatrix[i][1][0] << \" \";\n\t\t\t//out_buffer << m_rmatrix[i][1][1] << \" \";\n\t\t\t//out_buffer << m_rmatrix[i][1][2] << \" \";\n\t\t\t//out_buffer << m_rmatrix[i][2][0] << \" \";\n\t\t\t//out_buffer << m_rmatrix[i][2][1] << \" \";\n\t\t\t//out_buffer << m_rmatrix[i][2][2] << endl;\n\t\t}\n\t\t//out_file << out_buffer.str();\n\t\t//out_file.close();\n\t}\n\n\tvoid load_rotation_matrix()\n\t{\n\t\tm_rmatrix.clear();\n\n\t\tifstream in_file(\"rotation_matrix.txt\");\n\t\tint num;\n\t\tin_file >> num;\n\n\t\tvector<vector<double> > tmp_matrix(3, vector<double>(3, 0));\n\t\tint i;\n\n\t\tfor (i = 0; i < num; i ++){\n\t\t\tin_file >> tmp_matrix[0][0] \n\t\t\t        >> tmp_matrix[0][1] \n\t\t\t\t\t>> tmp_matrix[0][2] \n\t\t\t\t\t>> tmp_matrix[1][0] \n\t\t\t        >> tmp_matrix[1][1] \n\t\t\t\t\t>> tmp_matrix[1][2] \n\t\t\t\t\t>> tmp_matrix[2][0] \n\t\t\t        >> tmp_matrix[2][1] \n\t\t\t\t\t>> tmp_matrix[2][2]; \n\t\t\tm_rmatrix.push_back(tmp_matrix);\n\t\t}\n\n\t\tin_file.close();\n\t}\n\n\tvoid load_matching_table()\n\t{\n\t\tm_table.clear();\n\n\t\tifstream in_file(\"matching_table.txt\");\n\t\tint num_pose, num_coarse;\n\t\tin_file >> num_pose >> num_coarse;\n\t\t\n\t\tvector<unsigned short>\ttmp_row;\n\t\tunsigned short id_ray;\n\t\tint i, j;\n\t\tfor (i = 0; i < num_pose; i ++){\n\t\t\ttmp_row.clear();\n\t\t\tfor (j = 0; j < num_coarse; j ++){\n\t\t\t\tin_file >> id_ray;\n\t\t\t\ttmp_row.push_back(id_ray);\n\t\t\t}\n\t\t\tm_table.push_back(tmp_row);\n\t\t}\n\t\tin_file.close();\n\t}\n\n\tvoid load_matching_table_coarse2dense()\n\t{\n\t\tm_table_coarse2dense.clear();\n\n\t\tifstream in_file(\"matching_table_coarse2dense.txt\");\n\t\tint num_pose, num_coarse;\n\t\tin_file >> num_pose >> num_coarse;\n\t\t\n\t\tvector<unsigned short>\ttmp_row;\n\t\tunsigned short id_ray;\n\t\tint i, j;\n\t\tfor (i = 0; i < num_pose; i ++){\n\t\t\ttmp_row.clear();\n\t\t\tfor (j = 0; j < num_coarse; j ++){\n\t\t\t\tin_file >> id_ray;\n\t\t\t\ttmp_row.push_back(id_ray);\n\t\t\t}\n\t\t\tm_table_coarse2dense.push_back(tmp_row);\n\t\t}\n\t\tin_file.close();\n\t}\n\n\tvoid load_matching_table_dense2coarse()\n\t{\n\t\tm_table_dense2coarse.clear();\n\n\t\tifstream in_file(\"matching_table_dense2coarse.txt\");\n\t\tint num_pose, num_coarse;\n\t\tin_file >> num_pose >> num_coarse;\n\t\t\n\t\tvector<unsigned short>\ttmp_row;\n\t\tunsigned short id_ray;\n\t\tint i, j;\n\t\tfor (i = 0; i < num_pose; i ++){\n\t\t\ttmp_row.clear();\n\t\t\tfor (j = 0; j < num_coarse; j ++){\n\t\t\t\tin_file >> id_ray;\n\t\t\t\ttmp_row.push_back(id_ray);\n\t\t\t}\n\t\t\tm_table_dense2coarse.push_back(tmp_row);\n\t\t}\n\t\tin_file.close();\n\t}\n\n\tvoid init()\n\t{\n\t\tload_unitball();\n\t\tm_coarse.init();\n\t\tm_dense.init();\n\t\tm_pose.init();\n//cerr << \"m_pose.init_pose();\" << endl;\n\t\tm_pose.init_pose();\n\t}\t\n\n\tvoid load_unitball()\n\t{\n\t\tvector<double>\ttmp_point(3, 0);\n\t\tsize_t i;\n\n\t\tm_unitball_coarse.clear();\n\t\tfor (i = 0; i < points_default_coarse; i ++){\n\t\t\ttmp_point[0] = vertex_default_coarse[i][0];\n\t\t\ttmp_point[1] = vertex_default_coarse[i][1];\n\t\t\ttmp_point[2] = vertex_default_coarse[i][2];\n\t\t\tm_unitball_coarse.push_back(tmp_point);\n\t\t}\n\n\t\tm_unitball_dense.clear();\n\t\tfor (i = 0; i < points_default_dense; i ++){\n\t\t\ttmp_point[0] = vertex_default_dense[i][0];\n\t\t\ttmp_point[1] = vertex_default_dense[i][1];\n\t\t\ttmp_point[2] = vertex_default_dense[i][2];\n\t\t\tm_unitball_dense.push_back(tmp_point);\n\t\t}\n\n\t}\n\n\tvoid count_matching_table()\n\t{\n\t\tvector<int>\ttmp_counter(points_default_dense, 0);\n\t\tsize_t i, j;\n\t\t\n\t\tfor (i = 0; i < m_table.size(); i ++){\n\t\t\tfor (j = 0; j < m_table[i].size(); j ++){\n\t\t\t\ttmp_counter[m_table[i][j]] += 1;\n\t\t\t}\n\t\t}\n\n\t\tsort(tmp_counter.begin(), tmp_counter.end());\n\t\tcopy(tmp_counter.begin(), tmp_counter.end(), ostream_iterator<unsigned short>(cout, \"\\n\"));\n\t}\n\n\tvoid print_matching_table_coarse2dense()\n\t{\n\t\tsize_t i, j;\n\t\tstringstream out_buffer;\n\t\tout_buffer << m_table_coarse2dense.size() << \" \" << m_table_coarse2dense[0].size() << endl;\n\t\tfor (i = 0; i < m_table_coarse2dense.size(); i ++){\n\t\t\tfor (j = 0; j < m_table_coarse2dense[i].size(); j ++){\n\t\t\t\tout_buffer << m_table_coarse2dense[i][j] << \" \";\n\t\t\t}\n\t\t\tout_buffer << endl;\n\t\t}\n\n\t\tofstream out_file(\"matching_table_coarse2dense.txt\");\n\t\tout_file << out_buffer.str();\n\t\tout_file.close();\n\t}\n\n\tvoid print_matching_table_dense2coarse()\n\t{\n\t\tsize_t i, j;\n\t\tstringstream out_buffer;\n\t\tout_buffer << m_table_dense2coarse.size() << \" \" << m_table_dense2coarse[0].size() << endl;\n\t\tfor (i = 0; i < m_table_dense2coarse.size(); i ++){\n\t\t\tfor (j = 0; j < m_table_dense2coarse[i].size(); j ++){\n\t\t\t\tout_buffer << m_table_dense2coarse[i][j] << \" \";\n\t\t\t}\n\t\t\tout_buffer << endl;\n\t\t}\n\n\t\tofstream out_file(\"matching_table_dense2coarse.txt\");\n\t\tout_file << out_buffer.str();\n\t\tout_file.close();\n\t}\n\n\tvoid print_matching_table()\n\t{\n\t\tsize_t i, j;\n\t\tstringstream out_buffer;\n\t\tout_buffer << m_table.size() << \" \" << m_table[0].size() << endl;\n\t\tfor (i = 0; i < m_table.size(); i ++){\n\t\t\tfor (j = 0; j < m_table[i].size(); j ++){\n\t\t\t\tout_buffer << m_table[i][j] << \" \";\n\t\t\t}\n\t\t\tout_buffer << endl;\n\t\t}\n\n\t\tofstream out_file(\"matching_table.txt\");\n\t\tout_file << out_buffer.str();\n\t\tout_file.close();\n\t}\n\n\tvoid compute_matching_table()\n\t{\n\t\tm_table.clear();\n\t\tm_rmatrix.clear();\n\n\t\tvector<unsigned short>\ttmp_pose;\n\t\tvector<pair<double, pair<unsigned short, unsigned short> > >\ttmp_pose_sort;\n\t\tvector<pair<unsigned short, unsigned short> >\ttmp_pose_sort_row;\n\t\tvector<unsigned short>\ttmp_coarse2dense;\n\t\tvector<unsigned short>\ttmp_dense2coarse;\n\t\tunsigned short tmp_id_dense;\n\t\tsize_t i, j;\n\t\t//double M[3][3];\n\t\t//RotationMatrix M;\n\t\tvector<vector<double> > M(3, vector<double>(3, 0));\n\t\tvector<double>\ttmp_point_old(3, 0);\n\t\tvector<double>\ttmp_point_new(3, 0);\n\t\tdouble\t\t\ttmp_local_r_sq = 0.4;\n\t\tdouble\t\t\ttmp_dist;\n\t\t\n\t\tfor (i = 0; i < m_pose.m_arcs.size(); i ++){\nif (i/100*100 == i) cerr << \"i = \" << i << endl;\t\t\t\n\t\t\t\n\t\t\tM[0][0] = m_pose.m_arcs[i][0][0];\n\t\t\tM[1][0] = m_pose.m_arcs[i][0][1];\n\t\t\tM[2][0] = m_pose.m_arcs[i][0][2];\n\n\t\t\tM[0][1] = m_pose.m_arcs[i][1][0];\n\t\t\tM[1][1] = m_pose.m_arcs[i][1][1];\n\t\t\tM[2][1] = m_pose.m_arcs[i][1][2];\n\n\t\t\tM[0][2] = m_pose.m_arcs[i][2][0];\n\t\t\tM[1][2] = m_pose.m_arcs[i][2][1];\n\t\t\tM[2][2] = m_pose.m_arcs[i][2][2];\n\n\t\t\ttmp_dist  = M[0][2] * M[0][2];\n\t\t\ttmp_dist += M[1][2] * M[1][2];\n\t\t\ttmp_dist += (M[2][2] - 1) * (M[2][2] - 1);\n\t\t\tif (tmp_dist > tmp_local_r_sq) continue;\n\t\t\n\t\t\tm_rmatrix.push_back(M);\n\t\t\ttmp_pose.clear();\n\t\t\ttmp_pose_sort.clear();\n\n\t\t\tfor (j = 0; j < points_default_coarse; j++){\n\t\t\t\ttmp_point_old[0] = vertex_default_coarse[j][0];\n\t\t\t\ttmp_point_old[1] = vertex_default_coarse[j][1];\n\t\t\t\ttmp_point_old[2] = vertex_default_coarse[j][2];\n\t\t\t\ttmp_point_new[0] = M[0][0] * tmp_point_old[0] + M[0][1] * tmp_point_old[1] + M[0][2] * tmp_point_old[2];\n\t\t\t\ttmp_point_new[1] = M[1][0] * tmp_point_old[0] + M[1][1] * tmp_point_old[1] + M[1][2] * tmp_point_old[2];\n\t\t\t\ttmp_point_new[2] = M[2][0] * tmp_point_old[0] + M[2][1] * tmp_point_old[1] + M[2][2] * tmp_point_old[2];\n\t\t\t\ttmp_id_dense = m_dense.query_nn(tmp_point_new);\n\t\t\t\ttmp_pose.push_back(tmp_id_dense);\n\t\t\t\ttmp_pose_sort.push_back(pair<double, pair<unsigned short, unsigned short> >(2 * tmp_point_new[2] - tmp_point_old[2], pair<unsigned short, unsigned short>(j, tmp_id_dense)));\n\t\t\t}\n\t\t\tm_table.push_back(tmp_pose);\n\n\t\t\tsort(tmp_pose_sort.begin(), tmp_pose_sort.end(), less_than_univ<double, pair<unsigned short, unsigned short> >());\n\t\t\ttmp_pose_sort_row.clear();\n\t\t\tfor (j = 0; j < tmp_pose_sort.size(); j ++){\n\t\t\t\ttmp_pose_sort_row.push_back(tmp_pose_sort[j].second);\n\t\t\t}\n\t\t\tm_table_sort.push_back(tmp_pose_sort_row);\t\n\t\t\t\n\t\t\ttmp_coarse2dense.clear();\n\t\t\tfor (j = 0; j < points_default_pose; j++){\n\t\t\t\ttmp_point_old[0] = vertex_default_pose[j][0];\n\t\t\t\ttmp_point_old[1] = vertex_default_pose[j][1];\n\t\t\t\ttmp_point_old[2] = vertex_default_pose[j][2];\n\t\t\t\ttmp_point_new[0] = M[0][0] * tmp_point_old[0] + M[0][1] * tmp_point_old[1] + M[0][2] * tmp_point_old[2];\n\t\t\t\ttmp_point_new[1] = M[1][0] * tmp_point_old[0] + M[1][1] * tmp_point_old[1] + M[1][2] * tmp_point_old[2];\n\t\t\t\ttmp_point_new[2] = M[2][0] * tmp_point_old[0] + M[2][1] * tmp_point_old[1] + M[2][2] * tmp_point_old[2];\n\t\t\t\ttmp_coarse2dense.push_back(m_pose.query_nn(tmp_point_new));\n\t\t\t}\n\t\t\tm_table_coarse2dense.push_back(tmp_coarse2dense);\n\t\t\ttmp_dense2coarse = tmp_coarse2dense;\n\t\t\tfor (j = 0; j < tmp_coarse2dense.size(); j ++){\n\t\t\t\ttmp_dense2coarse[tmp_coarse2dense[j]] = j;\n\t\t\t}\n\t\t\tm_table_dense2coarse.push_back(tmp_dense2coarse);\n\t\t}\n\t}\n\n\n    //will generate full size table\n\tvoid compute_matching_table_v6()\n\t{\n\t\tm_table.clear();\n\t\tm_rmatrix.clear();\n\n\t\tvector<unsigned short>\ttmp_pose;\n\t\tvector<unsigned short>\ttmp_coarse2dense;\n\t\tvector<unsigned short>\ttmp_dense2coarse;\n\t\tunsigned short tmp_id_dense;\n\t\tsize_t i, j;\n\t\tvector<vector<double> > M(3, vector<double>(3, 0));\n\t\tvector<double>\ttmp_point_old(3, 0);\n\t\tvector<double>\ttmp_point_new(3, 0);\n\t\t\n\t\tfor (i = 0; i < m_pose.m_arcs.size(); i ++){\nif (i/100*100 == i) cerr << \"i = \" << i << endl;\t\t\t\n\t\t\t\n\t\t\tM[0][0] = m_pose.m_arcs[i][0][0];\n\t\t\tM[1][0] = m_pose.m_arcs[i][0][1];\n\t\t\tM[2][0] = m_pose.m_arcs[i][0][2];\n\n\t\t\tM[0][1] = m_pose.m_arcs[i][1][0];\n\t\t\tM[1][1] = m_pose.m_arcs[i][1][1];\n\t\t\tM[2][1] = m_pose.m_arcs[i][1][2];\n\n\t\t\tM[0][2] = m_pose.m_arcs[i][2][0];\n\t\t\tM[1][2] = m_pose.m_arcs[i][2][1];\n\t\t\tM[2][2] = m_pose.m_arcs[i][2][2];\n\n\t\t\tm_rmatrix.push_back(M);\n\t\t\ttmp_pose.clear();\n\n\t\t\tfor (j = 0; j < points_default_coarse; j++){\n\t\t\t\ttmp_point_old[0] = vertex_default_coarse[j][0];\n\t\t\t\ttmp_point_old[1] = vertex_default_coarse[j][1];\n\t\t\t\ttmp_point_old[2] = vertex_default_coarse[j][2];\n\t\t\t\ttmp_point_new[0] = M[0][0] * tmp_point_old[0] + M[0][1] * tmp_point_old[1] + M[0][2] * tmp_point_old[2];\n\t\t\t\ttmp_point_new[1] = M[1][0] * tmp_point_old[0] + M[1][1] * tmp_point_old[1] + M[1][2] * tmp_point_old[2];\n\t\t\t\ttmp_point_new[2] = M[2][0] * tmp_point_old[0] + M[2][1] * tmp_point_old[1] + M[2][2] * tmp_point_old[2];\n\t\t\t\ttmp_id_dense = m_dense.query_nn(tmp_point_new);\n\t\t\t\ttmp_pose.push_back(tmp_id_dense);\n\t\t\t}\n\t\t\tm_table.push_back(tmp_pose);\n\n\t\t\ttmp_coarse2dense.clear();\n\t\t\tfor (j = 0; j < points_default_dense; j++){\n\t\t\t\ttmp_point_old[0] = vertex_default_dense[j][0];\n\t\t\t\ttmp_point_old[1] = vertex_default_dense[j][1];\n\t\t\t\ttmp_point_old[2] = vertex_default_dense[j][2];\n\t\t\t\ttmp_point_new[0] = M[0][0] * tmp_point_old[0] + M[0][1] * tmp_point_old[1] + M[0][2] * tmp_point_old[2];\n\t\t\t\ttmp_point_new[1] = M[1][0] * tmp_point_old[0] + M[1][1] * tmp_point_old[1] + M[1][2] * tmp_point_old[2];\n\t\t\t\ttmp_point_new[2] = M[2][0] * tmp_point_old[0] + M[2][1] * tmp_point_old[1] + M[2][2] * tmp_point_old[2];\n\t\t\t\ttmp_coarse2dense.push_back(m_dense.query_nn(tmp_point_new));\n\t\t\t}\n\t\t\tm_table_coarse2dense.push_back(tmp_coarse2dense);\n\t\t\ttmp_dense2coarse = tmp_coarse2dense;\n\t\t\tfor (j = 0; j < tmp_coarse2dense.size(); j ++){\n\t\t\t\ttmp_dense2coarse[tmp_coarse2dense[j]] = j;\n\t\t\t}\n\t\t\tm_table_dense2coarse.push_back(tmp_dense2coarse);\n\t\t}\n\n        cout << \"m_table.size() = \" << m_table.size() << endl;\n        cout << \"m_rmatrix.size() = \" << m_rmatrix.size() << endl;\n        cout << \"m_table_coarse2dense.size() = \" << m_table_coarse2dense.size() << endl;\n        cout << \"m_table_dense2coarse.size() = \" << m_table_dense2coarse.size() << endl;\n\t}\n\n\n\tvoid compute_matching_table_v6_2(double pm_angle_degree)\n\t{\n\t\tm_table.clear();\n\t\tm_rmatrix.clear();\n\n\t\tvector<pair<double, pair<unsigned short, unsigned short> > >\ttmp_pose_sort(points_default_coarse, pair<double, pair<unsigned short, unsigned short> >(0, pair<unsigned short, unsigned short>(0, 0)));\n\t\tvector<pair<unsigned short, unsigned short> >\ttmp_pose_sort_row(points_default_coarse, pair<unsigned short, unsigned short>(0, 0));\n\n\t\tvector<unsigned short>\ttmp_pose(points_default_coarse, 0);\n\t\tvector<unsigned short>\ttmp_coarse2dense(points_default_dense, 0);\n\t\tvector<unsigned short>\ttmp_dense2coarse(points_default_dense, 0);\n\t\tunsigned short tmp_id_dense;\n\t\tsize_t i, j;\n\t\tvector<vector<double> > M(3, vector<double>(3, 0));\n\t\tvector<double>\ttmp_point_old(3, 0);\n\t\tvector<double>\ttmp_point_new(3, 0);\n\t\t\n\t\tdouble\t\t\ttmp_local_r_sq = sin(M_PI*pm_angle_degree/360)*sin(M_PI*pm_angle_degree/360)*4;; //0.268 = 30 degree, 0.362 = 35, 0.468 = 40, 0.586 = 45, \n\t\tdouble\t\t\ttmp_dist;\n\n\t\tm_table_sort.clear();\n\n        cout << \"Please wait ...\" << endl;\n\t\tfor (i = 0; i < m_pose.m_arcs.size(); i ++){\n//if (i/100*100 == i) cerr << \"i = \" << i << endl;\t\t\t\n\t\t\t\n\t\t\tM[0][0] = m_pose.m_arcs[i][0][0];\n\t\t\tM[1][0] = m_pose.m_arcs[i][0][1];\n\t\t\tM[2][0] = m_pose.m_arcs[i][0][2];\n\n\t\t\tM[0][1] = m_pose.m_arcs[i][1][0];\n\t\t\tM[1][1] = m_pose.m_arcs[i][1][1];\n\t\t\tM[2][1] = m_pose.m_arcs[i][1][2];\n\n\t\t\tM[0][2] = m_pose.m_arcs[i][2][0];\n\t\t\tM[1][2] = m_pose.m_arcs[i][2][1];\n\t\t\tM[2][2] = m_pose.m_arcs[i][2][2];\n\n\t\t\ttmp_dist  = M[0][2] * M[0][2];\n\t\t\ttmp_dist += M[1][2] * M[1][2];\n\t\t\ttmp_dist += (M[2][2] - 1) * (M[2][2] - 1);\n\t\t\tif (tmp_dist > tmp_local_r_sq) continue;\n\n\t\t\tm_rmatrix.push_back(M);\n\n\t\t\tfor (j = 0; j < points_default_coarse; j++){\n\t\t\t\ttmp_point_old[0] = vertex_default_coarse[j][0];\n\t\t\t\ttmp_point_old[1] = vertex_default_coarse[j][1];\n\t\t\t\ttmp_point_old[2] = vertex_default_coarse[j][2];\n\t\t\t\ttmp_point_new[0] = M[0][0] * tmp_point_old[0] + M[0][1] * tmp_point_old[1] + M[0][2] * tmp_point_old[2];\n\t\t\t\ttmp_point_new[1] = M[1][0] * tmp_point_old[0] + M[1][1] * tmp_point_old[1] + M[1][2] * tmp_point_old[2];\n\t\t\t\ttmp_point_new[2] = M[2][0] * tmp_point_old[0] + M[2][1] * tmp_point_old[1] + M[2][2] * tmp_point_old[2];\n\t\t\t\ttmp_id_dense = m_dense.query_nn(tmp_point_new);\n\t\t\t\ttmp_pose[j] = tmp_id_dense;\n\t\t\t\ttmp_pose_sort[j] = pair<double, pair<unsigned short, unsigned short> >(2 * tmp_point_new[2] - tmp_point_old[2], pair<unsigned short, unsigned short>(j, tmp_id_dense));\n\t\t\t}\n\t\t\tm_table.push_back(tmp_pose);\n\n\t\t\tsort(tmp_pose_sort.begin(), tmp_pose_sort.end(), less_than_univ<double, pair<unsigned short, unsigned short> >());\n\t\t\tfor (j = 0; j < tmp_pose_sort.size(); j ++){\n\t\t\t\ttmp_pose_sort_row[j] = tmp_pose_sort[j].second;\n\t\t\t}\n\t\t\tm_table_sort.push_back(tmp_pose_sort_row);\t\n\n\t\t\tfor (j = 0; j < points_default_dense; j++){\n\t\t\t\ttmp_point_old[0] = vertex_default_dense[j][0];\n\t\t\t\ttmp_point_old[1] = vertex_default_dense[j][1];\n\t\t\t\ttmp_point_old[2] = vertex_default_dense[j][2];\n\t\t\t\ttmp_point_new[0] = M[0][0] * tmp_point_old[0] + M[0][1] * tmp_point_old[1] + M[0][2] * tmp_point_old[2];\n\t\t\t\ttmp_point_new[1] = M[1][0] * tmp_point_old[0] + M[1][1] * tmp_point_old[1] + M[1][2] * tmp_point_old[2];\n\t\t\t\ttmp_point_new[2] = M[2][0] * tmp_point_old[0] + M[2][1] * tmp_point_old[1] + M[2][2] * tmp_point_old[2];\n\t\t\t\ttmp_coarse2dense[j] = m_dense.query_nn(tmp_point_new);\n\t\t\t}\n\t\t\tm_table_coarse2dense.push_back(tmp_coarse2dense);\n\n\t\t\tfor (j = 0; j < tmp_coarse2dense.size(); j ++){\n\t\t\t\ttmp_dense2coarse[tmp_coarse2dense[j]] = j;\n\t\t\t}\n\t\t\tm_table_dense2coarse.push_back(tmp_dense2coarse);\n\t\t}\n\n        cout << \"m_table.size() = \" << m_table.size() << endl;\n        cout << \"m_rmatrix.size() = \" << m_rmatrix.size() << endl;\n        cout << \"m_table_coarse2dense.size() = \" << m_table_coarse2dense.size() << endl;\n        cout << \"m_table_dense2coarse.size() = \" << m_table_dense2coarse.size() << endl;\n\t}\n\n};\n\nvoid task_map_sphere2circle(int argc, char *argv[])\n{\n\tif (argc < 3){\n\t\tcerr << \"USAGE: \" << argv[0] << \" <out_vtk_filename>\" << endl;\n\t\treturn;\n\t}\n\n    MyUnitBall myBall;\n\n    myBall.init();\n\n\t//m_unitball_dense\n\tsize_t i;\n\tdouble x, y, z, r, s, u, v;\n\tvector<vector<double> >\ttmp_points;\n\tvector<double>\t\t\ttmp_point(2, 0);\n\n\tfor (i = 0; i < myBall.m_unitball_dense.size(); i ++){\n\t\tx = myBall.m_unitball_dense[i][0];\n\t\ty = myBall.m_unitball_dense[i][1];\n\t\tz = myBall.m_unitball_dense[i][2];\n\t\tif (y < 0 || z < 0 || x < 0 || x == -1) continue;\n\t\ts = 0.5 * (1 - x);\n\t\tr = 2 * sqrt(1 - s);\n\t\tu = y / r;\n\t\tv = z / r;\n\t\ttmp_point[0] = u;\n\t\ttmp_point[1] = v;\n\t\ttmp_points.push_back(tmp_point);\n\t}\n\n\t//write to vtk file\n\tstring out_fn = argv[2];\n\tofstream out_file(out_fn.c_str());\n\tstringstream out_buffer;\n\n\tout_buffer << \"# vtk DataFile Version 3.0\" << endl;\n\tout_buffer << argv[2] << endl;\n\tout_buffer << \"ASCII\" << endl;\n\tout_buffer << \"DATASET POLYDATA\" << endl;\n\tout_buffer << \"POINTS \" << tmp_points.size() << \" float\" << endl;\n\n\tsize_t j;\n\tfor (j = 0; j < tmp_points.size(); j ++){\n\t\tout_buffer << tmp_points[j][0] << \" \"\n\t\t\t\t   << tmp_points[j][1] << \" \"\n\t\t\t       << 0 << endl;\n\t}\n\n\tout_buffer << \"VERTICES \" << tmp_points.size() << \" \" << tmp_points.size() * 2 << endl;\n\tfor(j = 0; j < tmp_points.size(); j ++){\n\t\tout_buffer << \"1 \" << j << endl;\n\t}\n\n\tout_file << out_buffer.str();\n\tout_file.close();\n\n\n}\n\nvoid task_mtgen_v6(int argc, char *argv[])\n{\n    MyUnitBall myBall;\n\n    myBall.init();\ncerr << \"myBall.compute_matching_table_v6(); \" << endl;\n\tmyBall.compute_matching_table_v6();\n\ncerr << \"serializing the tables...\" << endl;\n\tmyBall.ssave_matching_table(\"ssave_matching_table_v6.txt\");\n\tmyBall.ssave_matching_table_rmatrix(\"ssave_matching_table_v6_rmatrix.txt\");\n\t//myBall.ssave_matching_table_sort(\"ssave_matching_table_v6_sort.txt\");\n\tmyBall.ssave_matching_table_dense2coarse(\"ssave_matching_table_v6_dense2coarse.txt\");\n\tmyBall.ssave_matching_table_coarse2dense(\"ssave_matching_table_v6_coarse2dense.txt\");\n\n\n//cerr << \"myBall.write_bin_rotation_matrix();\" << endl;\n//\tmyBall.write_bin_rotation_matrix(\"matching_table_rotation_matrix_v6.bin\");\n//\n//cerr << \"myBall.write_bin_matching_table();\" << endl;\n//\tmyBall.write_bin_matching_table(\"matching_table_v6.bin\");\n//\n//cerr << \"myBall.write_bin_matching_table_coarse2dense();\" << endl;\n//\tmyBall.write_bin_matching_table_coarse2dense(\"matching_table_coarse2dense_v6.bin\");\n//\t\n//cerr << \"myBall.write_bin_matching_table_dense2coarse();\" << endl;\t\n//\tmyBall.write_bin_matching_table_dense2coarse(\"matching_table_dense2coarse_v6.bin\");\n\n}\n\n\nvoid task_mtgen_v6_2(int argc, char *argv[])\n{\n    MyUnitBall myBall;\n\n    myBall.init();\n//cerr << \"myBall.compute_matching_table_v6_2(); \" << endl;\n\tmyBall.compute_matching_table_v6_2(atof(argv[1]));\n\n\t\tstring fn_table = string(\"ssave_matching_table_\") + string(argv[1]) + string(\".txt\");\n\t\tstring fn_table_rmatrix = string(\"ssave_matching_table_\") + string(argv[1]) + string(\"_rmatrix.txt\");\n\t\tstring fn_table_sort = string(\"ssave_matching_table_\") + string(argv[1]) + string(\"_sort.txt\");\n\t\tstring fn_table_dense2coarse = string(\"ssave_matching_table_\") + string(argv[1]) + string(\"_dense2coarse.txt\");\n\t\tstring fn_table_coarse2dense = string(\"ssave_matching_table_\") + string(argv[1]) + string(\"_coarse2dense.txt\");\n\t\t\ncerr << \"serializing the tables...\" << endl;\n\tmyBall.ssave_matching_table(fn_table.c_str());\n\tmyBall.ssave_matching_table_rmatrix(fn_table_rmatrix.c_str());\n\tmyBall.ssave_matching_table_sort(fn_table_sort.c_str());\n\tmyBall.ssave_matching_table_dense2coarse(fn_table_dense2coarse.c_str());\n\tmyBall.ssave_matching_table_coarse2dense(fn_table_coarse2dense.c_str());\ncerr << \"Done!\" << endl;\n\n//cerr << \"myBall.write_bin_rotation_matrix();\" << endl;\n//\tmyBall.write_bin_rotation_matrix(\"matching_table_rotation_matrix_v6.bin\");\n//\n//cerr << \"myBall.write_bin_matching_table();\" << endl;\n//\tmyBall.write_bin_matching_table(\"matching_table_v6.bin\");\n//\n//cerr << \"myBall.write_bin_matching_table_coarse2dense();\" << endl;\n//\tmyBall.write_bin_matching_table_coarse2dense(\"matching_table_coarse2dense_v6.bin\");\n//\t\n//cerr << \"myBall.write_bin_matching_table_dense2coarse();\" << endl;\t\n//\tmyBall.write_bin_matching_table_dense2coarse(\"matching_table_dense2coarse_v6.bin\");\n\n}\n\n\nvoid task_mtgen(int argc, char *argv[])\n{\n\tMyUnitBall myBall;\n\n    myBall.init();\ncerr << \"myBall.compute_matching_table(); \" << endl;\n\tmyBall.compute_matching_table();\n\ncerr << \"serializing the tables...\" << endl;\n\tmyBall.ssave_matching_table(\"ssave_matching_table_full.txt\");\n\tmyBall.ssave_matching_table_rmatrix(\"ssave_matching_table_full_rmatrix.txt\");\n\tmyBall.ssave_matching_table_sort(\"ssave_matching_table_full_sort.txt\");\n\tmyBall.ssave_matching_table_dense2coarse(\"ssave_matching_table_full_dense2coarse.txt\");\n\tmyBall.ssave_matching_table_coarse2dense(\"ssave_matching_table_full_coarse2dense.txt\");\n\n//cerr << \"myBall.write_bin_rotation_matrix();\" << endl;\n//\tmyBall.write_bin_rotation_matrix(\"rotation_matrix.bin\");\n//\n//cerr << \"myBall.write_bin_matching_table();\" << endl;\n//\tmyBall.write_bin_matching_table(\"matching_table.bin\");\n//\n//cerr << \"myBall.write_bin_matching_table_coarse2dense();\" << endl;\n//\tmyBall.write_bin_matching_table_coarse2dense(\"matching_table_coarse2dense.bin\");\n//\t\n//cerr << \"myBall.write_bin_matching_table_dense2coarse();\" << endl;\t\n//\tmyBall.write_bin_matching_table_dense2coarse(\"matching_table_dense2coarse.bin\");\n//\t\n//cerr << \"myBall.write_bin_matching_table_sort();\" << endl;\t\n//\tmyBall.write_bin_matching_table_sort(\"matching_table_sort.bin\");\t\n\n}\n\nint main(int argc, char *argv[])\n{\n    //MyUnitBall myBall;\n    //myBall.init();\n\n\t\tif (argc != 2){\n\t\t\t\tcerr << \"Usage: \" << argv[0] << \" <angle>\" << endl;\n\t\t\t\treturn -1; \n\t\t}\n\t\t\n\t\ttask_mtgen_v6_2(argc, argv);\n\n/*\t\t\n    if (argc < 2){\n        task_mtgen(argc, argv);\n    }\n    else if (atoi(argv[1]) == 6){\n        task_mtgen_v6(argc, argv);\n    }\n    else if (atoi(argv[1]) == 62){\n        task_mtgen_v6_2(argc, argv);\n    }\n\t\telse if (atoi(argv[1]) == 5){\n\t\t\t\ttask_map_sphere2circle(argc, argv);\n\t\t}\n*/\n\n/*\n\tmyBall.load_rotation_matrix();\n\tmyBall.load_matching_table();\n\tmyBall.load_matching_table_coarse2dense();\n\tmyBall.load_matching_table_dense2coarse();\n\n\tmyBall.write_bin_rotation_matrix();\n\tmyBall.write_bin_matching_table();\n\tmyBall.write_bin_matching_table_coarse2dense();\n\tmyBall.write_bin_matching_table_dense2coarse();\n*/\n\n/*\n\tcout << \"myBall.read_bin_matching_table();\" << endl;\n\tmyBall.read_bin_matching_table();\n\n\t//cout << \"myBall.print_matching_table();\" << endl;\n\t//myBall.print_matching_table();\n\n\tcout << \"myBall.read_bin_matching_table();\" << endl;\n\tmyBall.read_bin_matching_table_sort();\n\n\tcout << \"myBall.read_bin_matching_table_coarse2dense();\" << endl;\n\tmyBall.read_bin_matching_table_coarse2dense();\n\n\t//cout << \"myBall.print_matching_table_coarse2dense();\" << endl;\n\t//myBall.print_matching_table_coarse2dense();\n\n\tcout << \"myBall.read_bin_matching_table_dense2coarse();\" << endl;\n\tmyBall.read_bin_matching_table_dense2coarse();\n\n\t//cout << \"myBall.print_matching_table_dense2coarse();\" << endl;\n\t//myBall.print_matching_table_dense2coarse();\n\n\tcout << \"myBall.read_bin_rotation_matrix();\" << endl;\n\tmyBall.read_bin_rotation_matrix();\n\n\t//cout << \"myBall.print_rotation_matrix();\" << endl;\n\t//myBall.print_rotation_matrix();\n\n\tmyBall.check_table_sort();\n*/\n\n\n    return 0;\n}\n", "meta": {"hexsha": "481fec73f9d3502c349458c06ad09bb4cf25d130", "size": 44859, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mtgen.cpp", "max_stars_repo_name": "zakimjz/ContextShapes", "max_stars_repo_head_hexsha": "93c441b60cb72fdff09e38135d2d343bac558ca9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-25T08:32:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-25T08:32:20.000Z", "max_issues_repo_path": "mtgen.cpp", "max_issues_repo_name": "zakimjz/ContextShapes", "max_issues_repo_head_hexsha": "93c441b60cb72fdff09e38135d2d343bac558ca9", "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": "mtgen.cpp", "max_forks_repo_name": "zakimjz/ContextShapes", "max_forks_repo_head_hexsha": "93c441b60cb72fdff09e38135d2d343bac558ca9", "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.6247272727, "max_line_length": 200, "alphanum_fraction": 0.6575937939, "num_tokens": 14232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.29080523645526885}}
{"text": "/* Copyright 2020 Gopinath Chennupati, Raviteja Vangara, Namita Kharat, Erik Skau and Boian Alexandrov,\nTriad National Security, LLC. All rights reserved\nThis program was produced under U.S. Government contract 89233218CNA000001 for Los Alamos National Laboratory (LANL), which is operated by Triad National Security, LLC for the U.S. Department of Energy/National Nuclear Security Administration. All rights in the program are reserved by Triad National Security, LLC, and the U.S. Department of Energy/National Nuclear Security Administration. The Government is granted for itself and others acting on its behalf a nonexclusive, paid-up, irrevocable worldwide license in this material to reproduce, prepare derivative works, distribute copies to the public, perform publicly and display publicly, and to permit others to do so.\n*/\n\n#ifndef DISTNMF_DISTREORDER_HPP_\n#define DISTNMF_DISTREORDER_HPP_\n\n#include <unistd.h>\n#include <armadillo>\n#include <string>\n#include \"../planc-master/common/utils.hpp\"\n#include \"../planc-master/common/distutils.hpp\"\n#include \"../planc-master/distnmf/mpicomm.hpp\"\n\n/**\n * File name formats\n */\n\nnamespace planc {\n\ntemplate <class MATTYPE>\nclass DistReOrder {\n private:\n  const MPICommunicator& m_mpicomm;\n  int m_ownedm;\n  int m_ownedn;\n  int m_globalm;\n  int m_globaln;\n\n  int m_pr;\n  int m_pc;\n  int m_k;\n\n  UROWVEC localMaxIDx; // vector of max element indices from each proc\n  ROWVEC localMax;     // vector of max elements from each proc\n\n  UROWVEC globalMaxIDx; // vector of max element indices from all proc(s)\n  ROWVEC globalMax;     // vector of max elements from all proc(s)\n\n  UROWVEC finalIDx;     //vector of final max element indices; \n                        //still contains the local indices\n  UROWVEC globalIDx;    //Contains the global row indexes for m_k columns\n  UVEC sortIDx;         //sort indices of W\n  UVEC sharedSortIDx;   //rank 0 initialized with same sortIDx for pr * pc\n  UVEC globalSortIDx;   // global sort indices of W\n\n  UMAT globalIMx;       // matrix of final max-val indices across all proc(s)\n  MAT globalM;          // matrix of final max elements across all proc(s)\n\n  MAT W, H;             //Both the low rank factors\n  MAT new_W, new_H;     //reordered low rank factors\n\n  /**\n   * Allocates matrices and vectors\n   */\n  void allocateData() {\n    // Init vectors\n    /*\n    DISTPRINTINFO(\"k::\"<< this->k <<\"::localm::\"<< this->m_ownedm <<\"::localn::\" \n                    << this->m_ownedn << \"::globalm::\" << this->m_globalm << \n                    \"::globaln::\"<< this->m_globaln <<\"::MPI_SIZE::\"<< MPI_SIZE);\n    */\n    localMax.zeros(this->m_k);\n    localMaxIDx.zeros(this->m_k);\n    globalMaxIDx.zeros(this->m_pr * this->m_pc * this->m_k);\n    globalMax.zeros(this->m_pr * this->m_pc * this->m_k);\n    finalIDx.zeros(this->m_k);\n    globalIDx.zeros(this->m_k);\n    sortIDx.zeros(this->m_k);\n    sharedSortIDx.zeros(this->m_pr * this->m_pc, 1);\n    globalSortIDx.zeros(this->m_k);\n\n    // Init matrices\n    globalIMx.zeros(this->m_pr * this->m_pc, this->m_k);\n    globalM.zeros(this->m_pr * this->m_pc, this->m_k);\n\n    // low-rank factor matrices\n    new_W.zeros(this->W.n_rows, this->W.n_cols);\n    new_H.zeros(this->H.n_rows, this->H.n_cols);\n  }\n\n  void freeMatrices() {\n    localMax.clear();\n    localMaxIDx.clear();\n    globalMaxIDx.clear();\n    globalMax.clear();\n    finalIDx.clear();\n    globalIDx.clear();\n    globalIMx.clear();\n    sortIDx.clear();\n    globalSortIDx.clear();\n    globalM.clear();\n    W.clear();\n    H.clear();\n    new_W.clear();\n    new_H.clear();\n  }\n\n public:\n    DistReOrder<MATTYPE>(const MAT &leftlowrankfactor, const MAT &rightlowrankfactor, \n            const MPICommunicator& communicator, const int k) \n        : m_mpicomm(communicator) {\n        assert(leftlowrankfactor.n_cols == rightlowrankfactor.n_cols);\n        this->m_k = k;\n        this->m_pr = NUMROWPROCS;\n        this->m_pc = NUMCOLPROCS;\n        //Assign the low-rank factors\n        this->W = leftlowrankfactor;\n        this->H = rightlowrankfactor;\n        this->m_ownedm  = leftlowrankfactor.n_rows;\n        this->m_ownedn = rightlowrankfactor.n_cols;\n        allocateData();\n        PRINTROOT(\"distreorder()::constructor succesful\");                        \n    }\n\n    ~DistReOrder() {\n      //freeMatrices();\n    }\n\n    void finalGlobalSortIDx() {\n        /* local Max and IDx */\n        localMax = arma::max(this->W,0);\n        localMaxIDx = arma::index_max(this->W, 0) + this->m_ownedm;\n        //TODO! Need to take care of the topk maxima and indices here\n        /* Global Max and IDx */\n        MPITIC;  // gather globalMax, globalMaxIDx\n        int sendcnt = this->m_k;\n        int recvcnt = this->m_k;\n        globalMax.zeros();\n        MPI_Gather(localMax.memptr(), sendcnt, MPI_DOUBLE, globalMax.memptr(),\n                recvcnt, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n        globalMaxIDx.zeros();\n        MPI_Gather(localMaxIDx.memptr(), sendcnt, MPI_DOUBLE, globalMaxIDx.memptr(),\n                recvcnt, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n        double temp = MPITOC;  // gather globalMax, globalMaxIDx\n        //TODO! Need to report time later  \n        /* finalIDx, globalM, globalIMx and globalIDx */   \n        if(MPI_RANK == 0)   {\n            globalIMx = arma::reshape(globalMaxIDx.t(), this->m_k, \n                                (this->m_pr * this->m_pc)).t();\n            globalM = arma::reshape(globalMax, this->m_k, \n                                (this->m_pr * this->m_pc)).t();\n            //globalM.print(\"globalM = \");\n            //globalIMx.print(\"globalIMx = \");\n            finalIDx = arma::index_max(globalM, 0);\n            for(int ki = 0; ki < this->m_k; ki++)   {\n                globalIDx(ki) = globalIMx(finalIDx(ki),ki);\n            }\n            //globalIDx.print(\"globalIDx = \");\n            sortIDx = arma::sort_index(globalIDx);\n            sortIDx.print(\"Rank 0 sortIDx = \");\n            sharedSortIDx = arma::repmat(sortIDx, this->m_pr * this->m_pc, 1);\n            //H.print(\"H in rank 0 = \");\n            //globalSortIDx.print(\"Rank 0 globalSortIDx = \"); \n        }\n        //Scatter the sortIDx to all the procs in MPI_COMM_WORLD\n        globalSortIDx.zeros();\n        MPI_Scatter(this->sharedSortIDx.memptr(), sendcnt, MPI_DOUBLE, this->globalSortIDx.memptr(),\n                    recvcnt, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n    }\n\n    void reorderW()   {\n        finalGlobalSortIDx();\n        MPI_Barrier(MPI_COMM_WORLD);\n        //Now is the time for reordering the columns in W\n        this->sortIDx.print(\"local sortIDx = \");\n        this->globalSortIDx.print(\"globalSortIDX = \");\n        //W.print(\"local W = \");\n        //new_W.zeros();\n        for(int col = 0; col < this->m_k; col++)    {\n            //W is stored as row-major order\n            new_W.col(col) = W.col(globalSortIDx(col));\n        }\n        if(MPI_RANK == 0) { new_W.print(\"local new_W = \"); std::cout<<\"current k \"<<this->m_k<<std::endl; }\n    }\n\n    void reorderH()   {\n        /*\n        if(arma::sum(sortIDx) == 0){\n            finalGlobalSortIDx();\n        }*/\n        MPI_Barrier(MPI_COMM_WORLD);\n        //Now is the time for reordering the rows in H\n        //new_H.zeros();\n        for(int col = 0; col < this->m_k; col++)    {\n            //In H also, swapping the cols, because, it is in column-major order\n            new_H.col(col) = H.col(this->globalSortIDx(col));\n        } \n    }\n\n    /// Returns the left low rank factor matrix W\n    MAT getLeftLowRankFactor() { return new_W; }\n    /// Returns the right low rank factor matrix H\n    MAT getRightLowRankFactor() { return new_H; }\n\n  }; //class DistReOrder\n\n}  // namespace planc\n\n// run with mpi run 3.\nvoid testDistClust(char argc, char* argv[]) {\n  planc::MPICommunicator mpicomm(argc, argv);\n  planc::DistReOrder<MAT> dc(arma::randn(10, 4), \n                  arma::randu(4,8), mpicomm, 8);;\n\n  dc.reorderW();\n}\n\n#endif  // DISTNMF_DISTREORDER_HPP_\n", "meta": {"hexsha": "2e9ca3be642336c439a52051c6858a2d91dba20f", "size": 7923, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distnmfk/distreorder.hpp", "max_stars_repo_name": "lanl/DnMFkCPP", "max_stars_repo_head_hexsha": "a6bca290bf7d57be07f7a80d049d6b7714fbdc61", "max_stars_repo_licenses": ["BSD-3-Clause", "Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-29T21:56:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T21:56:02.000Z", "max_issues_repo_path": "distnmfk/distreorder.hpp", "max_issues_repo_name": "rvangara/DnMFk", "max_issues_repo_head_hexsha": "a6bca290bf7d57be07f7a80d049d6b7714fbdc61", "max_issues_repo_licenses": ["BSD-3-Clause", "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": "distnmfk/distreorder.hpp", "max_forks_repo_name": "rvangara/DnMFk", "max_forks_repo_head_hexsha": "a6bca290bf7d57be07f7a80d049d6b7714fbdc61", "max_forks_repo_licenses": ["BSD-3-Clause", "Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-29T21:55:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-02T21:30:15.000Z", "avg_line_length": 37.5497630332, "max_line_length": 675, "alphanum_fraction": 0.6176953174, "num_tokens": 2159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2907418659723408}}
{"text": "#include <pybind11/numpy.h>\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n\n#include <Eigen/Dense>\n\n#include <algorithm>\n#include <cstdint>\n#include <limits>\n#include <map>\n#include <memory>\n#include <random>\n#include <stdexcept>\n#include <utility>\n#include <vector>\n\nnamespace py = pybind11;\n\nnamespace ote {\n\nconst double EPS = 1e-8;\nconst double EPS2 = 1e-5;\nconst double EPS3 = 1e-3;\n\ninline int32_t sign(float x) {\n  if (fabs(x) < EPS) {\n    throw std::logic_error(\"computing sign of ~0\");\n  }\n  if (x > 0) return 1;\n  return -1;\n}\n\nclass OTEstimators {\n public:\n  using NumPyFloatArray = py::array_t<float, py::array::c_style>;\n  using NumPyIntArray = py::array_t<int32_t, py::array::c_style>;\n\n  using EigenVector = Eigen::Matrix<float, 1, Eigen::Dynamic, Eigen::RowMajor>;\n  using EigenMatrix =\n      Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n  using Matrix = Eigen::Map<EigenMatrix>;\n\n  OTEstimators() : stage(0) {}\n\n  void load_vocabulary(NumPyFloatArray points) {\n    if (stage != 0) {\n      throw std::logic_error(\n          \"load_vocabulary() should be called once in the beginning\");\n    }\n    stage = 1;\n    py::buffer_info buf = points.request();\n    if (buf.ndim != 2) {\n      throw std::logic_error(\n          \"load_vocabulary() expects a two-dimensional NumPy array\");\n    }\n    auto n = buf.shape[0];\n    auto d = buf.shape[1];\n    dictionary = std::make_unique<Matrix>(static_cast<float *>(buf.ptr), n, d);\n    auto cmin = std::numeric_limits<float>::max();\n    auto cmax = std::numeric_limits<float>::min();\n    for (ssize_t i = 0; i < n; ++i) {\n      for (ssize_t j = 0; j < d; ++j) {\n        cmin = std::min(cmin, (*dictionary)(i, j));\n        cmax = std::max(cmax, (*dictionary)(i, j));\n      }\n    }\n    auto delta = cmax - cmin;\n    cmin -= delta;\n    std::random_device rd;\n    std::mt19937_64 gen(rd());\n    std::uniform_real_distribution<float> shift_gen(0.0, delta);\n    std::vector<std::pair<float, float>> bounding_box;\n    for (ssize_t i = 0; i < d; ++i) {\n      auto s = shift_gen(gen);\n      bounding_box.push_back(std::make_pair(cmin + s, cmax + s));\n    }\n    std::vector<int32_t> all;\n    for (ssize_t i = 0; i < n; ++i) {\n      all.push_back(i);\n    }\n    leaf.resize(n);\n    build_quadtree(all, bounding_box, 0, -1);\n    num_queries = 0;\n    marked.resize(parents.size());\n    for (auto &x : marked) {\n      x = -1;\n    }\n    node_id.resize(parents.size());\n  }\n\n  void load_dataset(\n      const std::vector<std::vector<std::pair<int32_t, float>>> &dataset) {\n    if (stage != 1) {\n      throw std::logic_error(\n          \"load_dataset() should be called once after calling \"\n          \"load_vocabulary()\");\n    }\n    stage = 2;\n    if (dataset.empty()) {\n      throw std::logic_error(\"the dataset can't be empty\");\n    }\n    for (auto &measure : dataset) {\n      check_measure(measure);\n      dataset_embedding.push_back(compute_embedding(measure));\n    }\n\n    raw_dataset = dataset;\n    for (auto &measure : raw_dataset) {\n      std::sort(measure.begin(), measure.end());\n    }\n\n    means.resize(dataset.size(), dictionary->cols());\n    for (size_t i = 0; i < dataset.size(); ++i) {\n      means.row(i) =\n          dictionary->row(dataset[i][0].first) * dataset[i][0].second;\n      for (size_t j = 1; j < dataset[i].size(); ++j) {\n        means.row(i) +=\n            dictionary->row(dataset[i][j].first) * dataset[i][j].second;\n      }\n    }\n    query_mean.resize(dictionary->cols());\n    distances.resize(dataset.size());\n  }\n\n  void means_rank(const std::vector<std::pair<int32_t, float>> &query,\n                  NumPyIntArray input_ids, NumPyIntArray output_ids,\n                  NumPyFloatArray output_scores, bool to_sort) {\n    check_stage();\n    check_measure(query);\n    check_input_output_arrays(input_ids, output_ids, output_scores);\n    query_mean = dictionary->row(query[0].first) * query[0].second;\n    for (size_t j = 1; j < query.size(); ++j) {\n      query_mean =\n          query_mean + dictionary->row(query[j].first) * query[j].second;\n    }\n    auto input_ids_buf = input_ids.request();\n    auto input_ids_raw = static_cast<int32_t *>(input_ids_buf.ptr);\n    int32_t k1 = input_ids_buf.shape[0];\n    for (int32_t i = 0; i < k1; ++i) {\n      float score = (query_mean - means.row(input_ids_raw[i])).squaredNorm();\n      distances[i] = std::make_pair(score, input_ids_raw[i]);\n    }\n    select_topk_aux(k1, output_ids, output_scores, to_sort);\n  }\n\n  void overlap_rank(const std::vector<std::pair<int32_t, float>> &query,\n                    NumPyIntArray input_ids, NumPyIntArray output_ids,\n                    NumPyFloatArray output_scores, bool to_sort) {\n    check_stage();\n    check_measure(query);\n    auto query_copy = query;\n    std::sort(query_copy.begin(), query_copy.end());\n    auto input_ids_buf = input_ids.request();\n    auto input_ids_raw = static_cast<int32_t *>(input_ids_buf.ptr);\n    int32_t k1 = input_ids_buf.shape[0];\n    for (int32_t i = 0; i < k1; ++i) {\n      auto &point = raw_dataset[input_ids_raw[i]];\n      float score = 0.0;\n      size_t qp = 0;\n      size_t dp = 0;\n\n      while (qp < query_copy.size() && dp < point.size()) {\n        if (query_copy[qp].first < point[dp].first) {\n          ++qp;\n        } else if (query_copy[qp].first > point[dp].first) {\n          ++dp;\n        } else {\n          score += 1;\n          ++dp;\n          ++qp;\n        }\n      }\n      distances[i] = std::make_pair(-score, input_ids_raw[i]);\n    }\n    select_topk_aux(k1, output_ids, output_scores, to_sort);\n  }\n\n  void quadtree_rank(const std::vector<std::pair<int32_t, float>> &query,\n                     NumPyIntArray input_ids, NumPyIntArray output_ids,\n                     NumPyFloatArray output_scores, bool to_sort) {\n    check_stage();\n    check_measure(query);\n    check_input_output_arrays(input_ids, output_ids, output_scores);\n    auto query_embedding = compute_embedding(query);\n    auto input_ids_buf = input_ids.request();\n    auto input_ids_raw = static_cast<int32_t *>(input_ids_buf.ptr);\n    int32_t k1 = input_ids_buf.shape[0];\n    for (int32_t i = 0; i < k1; ++i) {\n      auto &point_embedding = dataset_embedding[input_ids_raw[i]];\n      float score = 0.0;\n      size_t qp = 0;\n      size_t dp = 0;\n      while (qp < query_embedding.size() || dp < point_embedding.size()) {\n        if (qp == query_embedding.size()) {\n          score += point_embedding[dp].second;\n          ++dp;\n        } else if (dp == point_embedding.size()) {\n          score += query_embedding[qp].second;\n          ++qp;\n        } else if (query_embedding[qp].first < point_embedding[dp].first) {\n          score += query_embedding[qp].second;\n          ++qp;\n        } else if (point_embedding[dp].first < query_embedding[qp].first) {\n          score += point_embedding[dp].second;\n          ++dp;\n        } else {\n          score +=\n              fabs(query_embedding[qp].second - point_embedding[dp].second);\n          ++qp;\n          ++dp;\n        }\n      }\n      distances[i] = std::make_pair(score, input_ids_raw[i]);\n    }\n    select_topk_aux(k1, output_ids, output_scores, to_sort);\n  }\n\n  void flowtree_rank(const std::vector<std::pair<int32_t, float>> &query,\n                     NumPyIntArray input_ids, NumPyIntArray output_ids,\n                     NumPyFloatArray output_scores, bool to_sort) {\n    check_stage();\n    check_measure(query);\n    check_input_output_arrays(input_ids, output_ids, output_scores);\n    auto input_ids_buf = input_ids.request();\n    auto input_ids_raw = static_cast<int32_t *>(input_ids_buf.ptr);\n    int32_t k1 = input_ids_buf.shape[0];\n    for (int32_t i = 0; i < k1; ++i) {\n      auto cur_id = input_ids_raw[i];\n      auto score = flowtree_query(query, raw_dataset[cur_id]);\n      distances[i] = std::make_pair(score, cur_id);\n    }\n    select_topk_aux(k1, output_ids, output_scores, to_sort);\n  }\n\n  void select_topk(NumPyIntArray input_ids, NumPyFloatArray input_scores,\n                   NumPyIntArray output_ids, NumPyFloatArray output_scores,\n                   bool to_sort) {\n    check_input_output_arrays(input_ids, input_scores, output_ids,\n                              output_scores);\n    auto input_scores_buf = input_scores.request();\n    auto input_ids_buf = input_ids.request();\n    auto input_scores_raw = static_cast<float *>(input_scores_buf.ptr);\n    auto input_ids_raw = static_cast<int32_t *>(input_ids_buf.ptr);\n    int32_t k1 = input_ids_buf.shape[0];\n    for (int32_t i = 0; i < k1; ++i) {\n      distances[i] = std::make_pair(input_scores_raw[i], input_ids_raw[i]);\n    }\n    select_topk_aux(k1, output_ids, output_scores, to_sort);\n  }\n\n private:\n  std::vector<int32_t> parents;\n  std::vector<int32_t> leaf;\n  std::vector<int32_t> marked;\n  int32_t num_queries;\n  std::vector<int32_t> node_id;\n  std::vector<int32_t> id_node;\n  std::vector<std::vector<int32_t>> subtree;\n  std::vector<std::vector<std::pair<float, int32_t>>> excess;\n  std::vector<float> delta_node;\n  std::unique_ptr<Matrix> dictionary;\n  std::vector<int32_t> unleaf;\n  std::vector<std::vector<std::pair<int32_t, float>>> dataset_embedding;\n  std::vector<std::vector<std::pair<int32_t, float>>> raw_dataset;\n  EigenMatrix means;\n  EigenVector query_mean;\n  std::vector<std::pair<float, int32_t>> distances;\n  int32_t stage;\n\n  void build_quadtree(const std::vector<int32_t> &subset,\n                      const std::vector<std::pair<float, float>> &bounding_box,\n                      int32_t depth, int32_t parent) {\n    int32_t node_id(parents.size());\n    parents.push_back(parent);\n    if (subset.size() == 1) {\n      leaf[subset[0]] = node_id;\n      return;\n    }\n    int32_t d = dictionary->cols();\n    std::vector<float> mid(d);\n    for (int32_t i = 0; i < d; ++i) {\n      mid[i] = (bounding_box[i].first + bounding_box[i].second) / 2.0;\n    }\n    std::map<std::vector<uint8_t>, std::vector<int32_t>> parts;\n    for (auto ind : subset) {\n      std::vector<uint8_t> code((d + 7) / 8, 0);\n      for (int32_t i = 0; i < d; ++i) {\n        if ((*dictionary)(ind, i) > mid[i]) {\n          code[i / 8] |= 1 << (i % 8);\n        }\n      }\n      parts[code].push_back(ind);\n    }\n    std::vector<std::pair<float, float>> new_bounding_box(d);\n    for (const auto &part : parts) {\n      for (int32_t i = 0; i < d; ++i) {\n        uint8_t bit = (part.first[i / 8] >> (i % 8)) & 1;\n        if (bit) {\n          new_bounding_box[i] = std::make_pair(mid[i], bounding_box[i].second);\n        } else {\n          new_bounding_box[i] = std::make_pair(bounding_box[i].first, mid[i]);\n        }\n      }\n      build_quadtree(part.second, new_bounding_box, depth + 1, node_id);\n    }\n  }\n\n  std::vector<std::pair<int32_t, float>> compute_embedding(\n      const std::vector<std::pair<int32_t, float>> &a) {\n    std::vector<std::pair<int32_t, float>> result;\n    for (auto x : a) {\n      auto id = leaf[x.first];\n      int32_t level = 0;\n      while (id != -1) {\n        ++level;\n        id = parents[id];\n      }\n      id = leaf[x.first];\n      while (id != -1) {\n        --level;\n        result.push_back(std::make_pair(id, x.second / (1 << level)));\n        id = parents[id];\n      }\n    }\n    std::sort(result.begin(), result.end());\n    std::vector<std::pair<int32_t, float>> ans;\n    for (auto x : result) {\n      if (ans.empty() || ans.back().first != x.first) {\n        ans.push_back(x);\n      } else {\n        ans.back().second += x.second;\n      }\n    }\n    return ans;\n  }\n\n  float flowtree_query(const std::vector<std::pair<int32_t, float>> &a,\n                       const std::vector<std::pair<int32_t, float>> &b) {\n    int32_t num_nodes = 0;\n    id_node.clear();\n    for (auto x : a) {\n      auto id = leaf[x.first];\n      while (id != -1) {\n        if (marked[id] != num_queries) {\n          id_node.push_back(id);\n          node_id[id] = num_nodes++;\n        }\n        marked[id] = num_queries;\n        id = parents[id];\n      }\n    }\n    for (auto x : b) {\n      auto id = leaf[x.first];\n      while (id != -1) {\n        if (marked[id] != num_queries) {\n          id_node.push_back(id);\n          node_id[id] = num_nodes++;\n        }\n        marked[id] = num_queries;\n        id = parents[id];\n      }\n    }\n    if (static_cast<int32_t>(subtree.size()) < num_nodes) {\n      subtree.resize(num_nodes);\n    }\n    for (int32_t i = 0; i < num_nodes; ++i) {\n      subtree[i].clear();\n    }\n    for (int32_t i = 0; i < num_nodes; ++i) {\n      int32_t u = parents[id_node[i]];\n      if (u != -1) {\n        subtree[node_id[u]].push_back(i);\n      }\n    }\n    if (static_cast<int32_t>(excess.size()) < num_nodes) {\n      excess.resize(num_nodes);\n    }\n    delta_node.assign(num_nodes, 0.0);\n    unleaf.resize(num_nodes);\n    for (auto x : a) {\n      delta_node[node_id[leaf[x.first]]] += x.second;\n      unleaf[node_id[leaf[x.first]]] = x.first;\n    }\n    for (auto x : b) {\n      delta_node[node_id[leaf[x.first]]] -= x.second;\n      unleaf[node_id[leaf[x.first]]] = x.first;\n    }\n    float res = run_query(0, node_id[0]);\n    if (!excess[node_id[0]].empty()) {\n      float unassigned = 0.0;\n      for (auto x : excess[node_id[0]]) {\n        unassigned += x.first;\n      }\n      if (unassigned > EPS2) {\n        throw std::logic_error(\"too much unassigned flow\");\n      }\n    }\n    ++num_queries;\n    return res;\n  }\n\n  float run_query(int32_t depth, int32_t nd) {\n    float res = 0.0;\n    for (auto x : subtree[nd]) {\n      res += run_query(depth + 1, x);\n    }\n    excess[nd].clear();\n    if (subtree[nd].empty()) {\n      if (fabs(delta_node[nd]) > EPS) {\n        excess[nd].push_back(std::make_pair(delta_node[nd], unleaf[nd]));\n      }\n    } else {\n      for (auto x : subtree[nd]) {\n        if (excess[x].empty()) {\n          continue;\n        }\n        bool same = false;\n        if (excess[nd].empty()) {\n          same = true;\n        } else if (sign(excess[x][0].first) == sign(excess[nd][0].first)) {\n          same = true;\n        }\n        if (same) {\n          for (auto y : excess[x]) {\n            excess[nd].push_back(y);\n          }\n        } else {\n          while (!excess[x].empty() && !excess[nd].empty()) {\n            auto u = excess[nd].back();\n            auto v = excess[x].back();\n\n            float dist =\n                (dictionary->row(u.second) - dictionary->row(v.second)).norm();\n            if (fabs(u.first + v.first) < EPS) {\n              excess[nd].pop_back();\n              excess[x].pop_back();\n              res += dist * fabs(u.first);\n            } else if (fabs(u.first) < fabs(v.first)) {\n              excess[nd].pop_back();\n              excess[x].back().first += u.first;\n              res += dist * fabs(u.first);\n            } else {\n              excess[x].pop_back();\n              excess[nd].back().first += v.first;\n              res += dist * fabs(v.first);\n            }\n          }\n          if (!excess[x].empty()) {\n            excess[x].swap(excess[nd]);\n          }\n        }\n      }\n    }\n    return res;\n  }\n\n  void select_topk_aux(int32_t k1, NumPyIntArray output_ids,\n                       NumPyFloatArray output_scores, bool to_sort) {\n    auto output_ids_buf = output_ids.request();\n    auto output_ids_raw = static_cast<int32_t *>(output_ids_buf.ptr);\n    auto output_scores_buf = output_scores.request();\n    auto output_scores_raw = static_cast<float *>(output_scores_buf.ptr);\n    int32_t k2 = output_ids_buf.shape[0];\n    std::nth_element(distances.begin(), distances.begin() + k2 - 1,\n                     distances.begin() + k1);\n    if (to_sort) {\n      std::sort(distances.begin(), distances.begin() + k2);\n    }\n    for (int32_t i = 0; i < k2; ++i) {\n      output_scores_raw[i] = distances[i].first;\n      output_ids_raw[i] = distances[i].second;\n    }\n  }\n\n  void check_measure(const std::vector<std::pair<int32_t, float>> &measure) {\n    float sum = 0.0;\n    auto n = dictionary->rows();\n    for (auto &atom : measure) {\n      if (atom.first < 0 || atom.first >= n) {\n        throw std::logic_error(\"invalid index in the measure\");\n      }\n      if (atom.second < -EPS) {\n        throw std::logic_error(\"negative mass\");\n      }\n      sum += atom.second;\n    }\n    if (fabs(sum - 1.0) > EPS3) {\n      throw std::logic_error(\"the masses don't sum to 1\");\n    }\n  }\n\n  void check_stage() {\n    if (stage != 2) {\n      throw std::logic_error(\n          \"need to call load_vocabulary() and load_dataset() first\");\n    }\n  }\n\n  template <typename T>\n  void check_dimension(T x) {\n    auto buf = x.request();\n    if (buf.ndim != 1) {\n      throw std::logic_error(\n          \"input_ids, output_ids, output_scores must be one-dimensional\");\n    }\n  }\n\n  template <typename T>\n  ssize_t get_length(T x) {\n    return x.request().shape[0];\n  }\n\n  void check_input_output_arrays(NumPyIntArray input_ids,\n                                 NumPyIntArray output_ids,\n                                 NumPyFloatArray output_scores) {\n    check_dimension(input_ids);\n    check_dimension(output_ids);\n    check_dimension(output_scores);\n    auto l1 = get_length(input_ids);\n    auto l2 = get_length(output_ids);\n    auto l3 = get_length(output_scores);\n    if (l2 != l3) {\n      throw std::logic_error(\n          \"output_ids and output_scores must be of the same length\");\n    }\n    if (l2 > l1) {\n      throw std::logic_error(\n          \"output_ids and output_scores must be no longer than input_ids\");\n    }\n    auto buf = static_cast<int32_t *>(input_ids.request().ptr);\n    for (ssize_t i = 0; i < l1; ++i) {\n      auto val = buf[i];\n      if (val < 0 || val >= static_cast<int32_t>(raw_dataset.size())) {\n        throw std::logic_error(\"input_ids contain an invalid index\");\n      }\n    }\n  }\n\n  void check_input_output_arrays(NumPyIntArray input_ids,\n                                 NumPyFloatArray input_scores,\n                                 NumPyIntArray output_ids,\n                                 NumPyFloatArray output_scores) {\n    check_input_output_arrays(input_ids, output_ids, output_scores);\n    check_dimension(input_scores);\n    if (get_length(input_ids) != get_length(input_scores)) {\n      throw std::logic_error(\n          \"input_ids and input_scores must be of the same length\");\n    }\n  }\n};\n}  // namespace ote\n\nPYBIND11_MODULE(ot_estimators, m) {\n  using ote::OTEstimators;\n  py::class_<OTEstimators>(m, \"OTEstimators\")\n      .def(py::init<>())\n      .def(\"load_vocabulary\", &OTEstimators::load_vocabulary)\n      .def(\"load_dataset\", &OTEstimators::load_dataset)\n      .def(\"means_rank\", &OTEstimators::means_rank)\n      .def(\"overlap_rank\", &OTEstimators::overlap_rank)\n      .def(\"quadtree_rank\", &OTEstimators::quadtree_rank)\n      .def(\"flowtree_rank\", &OTEstimators::flowtree_rank)\n      .def(\"select_topk\", &OTEstimators::select_topk);\n}\n", "meta": {"hexsha": "8351f9a441f7d4d09ad1fbb7e7f8a9e17a0fc6a4", "size": 18682, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "native/src/ot_estimators.cpp", "max_stars_repo_name": "davibarreira/ot_estimators", "max_stars_repo_head_hexsha": "1423949de6886b3ab6e17da060c68bf3a76cff92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2020-04-23T00:46:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T15:13:02.000Z", "max_issues_repo_path": "native/src/ot_estimators.cpp", "max_issues_repo_name": "ilyaraz/ot_estimators", "max_issues_repo_head_hexsha": "1423949de6886b3ab6e17da060c68bf3a76cff92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "native/src/ot_estimators.cpp", "max_forks_repo_name": "ilyaraz/ot_estimators", "max_forks_repo_head_hexsha": "1423949de6886b3ab6e17da060c68bf3a76cff92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-04-24T06:08:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T12:36:54.000Z", "avg_line_length": 33.0654867257, "max_line_length": 79, "alphanum_fraction": 0.5834493095, "num_tokens": 5045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.29074186597234075}}
{"text": "#include <iostream>\n#include <cassert>\n#include <string>\n#include <fstream>\n#include <set>\n#include <vector>\n#include <map>\n#include <random>\n#include <chrono>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n\nusing namespace std;\nusing namespace boost;\n\n// Typedefs for Input and output graphs\nstruct vertex_p\n{\n    int name;\n    float color;\n    string fillcolor;\n};\n\nstruct edge_p\n{\n    double weight;\n    unsigned penwidth;\n};\n\ntypedef adjacency_list <listS, vecS, undirectedS, vertex_p, edge_p, no_property > graph_p;\n\ntypedef graph_traits<graph_p>::vertex_descriptor vd_p;\ntypedef graph_traits<graph_p>::edge_descriptor ed_p;\n\n// Typedefs for intermediate graphs\n\nstruct vertex_q\n{\n    unsigned name;\n    unsigned label;\n    float color;\n};\n\nstruct edge_q\n{\n    double weight;\n};\n\ntypedef adjacency_list <listS, vecS, undirectedS, vertex_q, edge_q, no_property > graph_q;\ntypedef graph_traits<graph_q>::vertex_descriptor vd_q;\ntypedef graph_traits<graph_q>::edge_descriptor ed_q;\n\n// Global Variables\nstring input_filename, output_filename;\nfloat multicast_fraction = 0.0;\nunsigned vertex_count = 0;\nset<unsigned> multicast_vertices;\n\n\nint main(int argc, char* argv[])\n{\n    if(argc != 4)\n    {\n        cerr << \"Usage: \" << argv[0] << \" <Multicast Fraction> <Input.dot> <Output.dot>\\n\";\n        return 1; \n    }\n\n    try\n    {\n        multicast_fraction = stof(string(argv[1]));\n        if(multicast_fraction < 0 || multicast_fraction > 1)\n            throw invalid_argument(\"Fraction should be > 0 and < 1.\");\n    }\n    catch(std::exception &err)\n    {\n        cerr << err.what() << endl;\n        cerr << \"Invalid fraction argument\\n\";\n        return 1;\n    }\n\n    input_filename.assign(argv[2]);\n    output_filename.assign(argv[3]);\n\n#ifdef DEBUG\n    cout << \"Running in debug mode\\n\";\n    ifstream input_file(\"steiner.dot\", ios::in);\n    ofstream output_file(\"debug.dot\", ios::out);\n#else\n    ifstream input_file(input_filename.c_str(), ios::in);\n    ofstream output_file(output_filename.c_str(), ios::out);\n#endif\n\n    assert(output_file.is_open() && input_file.is_open() && \"Error opening files\");\n\n    graph_p network(0);\n    dynamic_properties dp;\n    auto name = get(&vertex_p::name, network);\n    dp.property(\"node_id\", name);\n    auto fillcolor = get(&vertex_p::fillcolor, network);\n    dp.property(\"fillcolor\", fillcolor);\n    auto weight = get(&edge_p::weight, network);\n    dp.property(\"weight\", weight); \n    auto penwidth = get(&edge_p::penwidth, network);\n    dp.property(\"penwidth\", penwidth); \n\n    try\n    {\n        read_graphviz(input_file, network, dp, \"node_id\");\n    }\n    catch(std::exception &err)\n    {\n        cerr << err.what() << endl;\n        cerr << \"read_graphviz failed for \" << input_filename << \"\\n\";\n        return 1;\n    }\n\n    // Initialize all dynamic properties\n\n    BGL_FORALL_VERTICES(v, network, graph_p)\n    {\n        fillcolor[v] = \"white\";\n    }\n\n    BGL_FORALL_EDGES(e, network, graph_p)\n    {\n        penwidth[e] = 1;\n    }\n\n    // TODO: Add timing code\n\n    vertex_count = num_vertices(network);\n    unsigned multicast_count = unsigned(multicast_fraction * vertex_count);\n\n#ifndef DEBUG\n    // Assume that vertices are numbered 0 -- N-1 (generated by BRITE)\n    // Randomly select multicast nodes using uniform distribution\n\n    std::default_random_engine generator;\n    std::uniform_int_distribution<unsigned> distribution(0, multicast_count - 1);    \n\n    multicast_count = multicast_count == 0 ? 1 : multicast_count;\n\n    do\n    {\n        // Insert vd_p Names ( == vd_p descriptors )\n        unsigned value = distribution(generator) % multicast_count;\n        multicast_vertices.insert(value);\n    } while( multicast_vertices.size() < multicast_count);\n\n#else\n    // debug for steiner.dot\n    multicast_count = 4;\n    cout << \"Num vd_p: \" << vertex_count << endl;\n    cout << \"Num MCast: \" << multicast_count << endl;\n    multicast_vertices.insert(0);\n    multicast_vertices.insert(1);\n    multicast_vertices.insert(2);\n    multicast_vertices.insert(3);\n\n    // Debug\n    ostream dbg(std::cout.rdbuf());\n    write_graphviz_dp(dbg, network, dp);\n#endif\n\n    graph_q G1(0);\n    map<unsigned, vd_q> vd_p_to_vd_q_map;\n\n    for(auto &V : multicast_vertices)\n    {\n        vd_q Vx = add_vertex(G1); \n        //cout << Vx << \" \" << V << \"\\n\";\n        G1[Vx].label = V;\n        G1[Vx].name = Vx;\n        vd_p_to_vd_q_map.insert(make_pair(V,Vx));\n    }\n\n#ifdef DEBUG\n    // Debug\n    dynamic_properties dp_q;\n    auto name_q = get(&vertex_q::name, G1);\n    dp_q.property(\"node_id\", name_q);\n    auto label_q = get(&vertex_q::label, G1);\n    dp_q.property(\"label\", label_q);\n    auto weight_q = get(&edge_q::weight, G1);\n    dp_q.property(\"weight\", weight_q);\n    write_graphviz_dp(dbg, G1, dp_q);\n    cout << \"Step1-----------------------------------\\n\";\n#endif\n\n    map<vd_p, vector<vd_p> > AllPreds;\n    map<vd_p, vector<unsigned> > AllDistances;\n\n    auto start_step_1 = chrono::steady_clock::now();\n\n    // Step 1 -- Construct undirected distance graph G1, G and S.\n    for(auto V = multicast_vertices.begin(), E = multicast_vertices.end(); V != E; V++)\n    {\n        vd_p Vx = *V;\n        // Get the shortest path between Vx,All \n        vector<unsigned> D(vertex_count);\n\n        AllPreds.insert(pair<vd_p,vector<vd_p> >(Vx, vector<vd_p>(vertex_count)));\n        AllDistances.insert(pair<vd_p,vector<unsigned> >(Vx, vector<unsigned>(vertex_count)));\n\n        dijkstra_shortest_paths(network, Vx,\n                weight_map(get(&edge_p::weight,network))\n                .distance_map(make_iterator_property_map(AllDistances[Vx].begin(), get(vertex_index, network)))\n                .predecessor_map(make_iterator_property_map(AllPreds[Vx].begin(), get(vertex_index, network))));\n\n        for(auto W = std::next(V); W != E; W++)\n        {\n            vd_p Wx = *W; \n            //// Debug\n            //cout << \"Adding ed_p (Vx, Wx, D[Wx]): \" << Vx << \",\" << Wx << \",\" << D[Wx] << endl;\n            ed_q e; bool found;\n            tie(e,found) = add_edge(vd_p_to_vd_q_map[*V], vd_p_to_vd_q_map[*W], G1);\n            G1[e].weight = AllDistances[Vx][Wx];\n        }\n    }\n\n    auto end_step_1 = chrono::steady_clock::now();\n    cout << \"[KMB] Step1: \"<< chrono::duration <double, milli> (end_step_1-start_step_1).count() << \" ms\" << endl;\n\n#ifdef DEBUG\n    // Debug\n    write_graphviz_dp(dbg, G1, dp_q);\n    cout << \"Step2-----------------------------------\\n\";\n#endif\n\n    // Step 2a -- Construct Minimum Spanning Tree from G1\n\n    auto start_step_2 = chrono::steady_clock::now();\n\n    vector<ed_q> st;\n    kruskal_minimum_spanning_tree(G1, back_inserter(st), \n            weight_map(get(&edge_q::weight, G1)));\n\n    // Step 2b -- Trim G1 based on MST\n\n    set<vd_q> vKeep, vRemove;\n    set<ed_q> eKeep, eRemove;\n\n    for(auto &e : st)\n    {\n        vKeep.insert(source(e, G1)); vKeep.insert(target(e, G1));\n        eKeep.insert(e);\n    }\n\n    auto end_step_2 = chrono::steady_clock::now();\n    cout << \"[KMB] Step2: \"<< chrono::duration <double, milli> (end_step_2-start_step_2).count() << \" ms\" << endl;\n\n#ifdef DEBUG\n    BGL_FORALL_VERTICES(v, G1, graph_q) \n    {\n        if(vKeep.count(v) == 0) \n            vRemove.insert(v);\n    }\n\n    BGL_FORALL_EDGES(e, G1, graph_q)\n    {\n        if(eKeep.count(e) == 0)\n            eRemove.insert(e);\n    }\n\n    for(auto Ex : eRemove) remove_edge(Ex, G1);\n    for(auto Vx : vRemove) remove_vertex(Vx, G1);\n\n    write_graphviz_dp(dbg, G1, dp_q);\n    cout << \"Step3-----------------------------------\\n\";\n#endif\n\n    auto start_step_3 = chrono::steady_clock::now();\n    // Step 3 -- Add the shortest paths back to G1 (expand each edge)\n\n    graph_q G2(0);\n\n    // For each edge in the MST, get the path we saved earlier\n    // For each vertex in path, if vertex is not added, add vertex, add edge\n    // else check if edge is added else add edge. Set weight\n\n    set<unsigned> added_labels;\n    map<unsigned, vd_q> label_map;\n\n    for(auto &Ex : eKeep)\n    {\n\n#ifdef DEBUG\n        cout << \"Source: \" << G1[source(Ex,G1)].label << \"\\n\";\n        cout << \"Target: \" << G1[target(Ex,G1)].label << \"\\n\";\n#endif\n\n        // Traverse from sink to source\n\n        auto predecessor_map = AllPreds[G1[source(Ex,G1)].label];\n        vd_p v = G1[target(Ex, G1)].label;\n        for(vd_p u = predecessor_map[v];          // Start by setting 'u' to the destintaion node's predecessor\n                u != v;                          // Keep tracking the path until we get to the source\n                v = u, u = predecessor_map[v])   // Set the current vertex to the current predecessor, and the predecessor to one level up \n        {   \n            vd_q Vx, Ux;\n            if(added_labels.count(v) == 0) \n            {\n                Vx = add_vertex(G2);\n                G2[Vx].label = v;\n                G2[Vx].name = Vx;\n                added_labels.insert(v);\n                label_map.insert(make_pair(v,Vx));\n            }\n            else\n            {\n                Vx = label_map[v];\n            }\n\n\n            if(added_labels.count(u) == 0)\n            {\n                Ux = add_vertex(G2);\n                G2[Ux].label = u;\n                G2[Ux].name = Ux;\n                added_labels.insert(u);\n                label_map.insert(make_pair(u,Ux));\n            }\n            else\n            {\n                Ux = label_map[u];\n            }\n\n            ed_q eq; bool fq = false;\n            tie(eq, fq) = edge(Vx, Ux, G2);\n            if(!fq)\n            {\n                ed_p e; bool f = false;\n                tie(e, f) = edge(u, v, network);\n                assert(f && \"Could not find edge in original graph!\");           \n                double wt = network[e].weight;\n\n                tie(eq, fq) = add_edge(Vx, Ux, G2);\n                G2[eq].weight = wt;\n            }\n        }\n    }\n\n    auto end_step_3 = chrono::steady_clock::now();\n    cout << \"[KMB] Step3: \"<< chrono::duration <double, milli> (end_step_3-start_step_3).count() << \" ms\" << endl;\n\n#ifdef DEBUG\n    dynamic_properties dp_q2;\n    auto name_q2 = get(&vertex_q::name, G2);\n    dp_q2.property(\"node_id\", name_q2);\n    auto label_q2 = get(&vertex_q::label, G2);\n    dp_q2.property(\"label\", label_q2);\n    auto weight_q2 = get(&edge_q::weight, G2);\n    dp_q2.property(\"weight\", weight_q2);\n\n    write_graphviz_dp(dbg, G2, dp_q2);\n\n    cout << \"Step4-----------------------------------\\n\";\n#endif\n\n    auto start_step_4 = chrono::steady_clock::now();\n    // Step 4a -- Construct Minimum Spanning Tree from G2\n\n    vector<ed_q> st2;\n    kruskal_minimum_spanning_tree(G2, back_inserter(st2), \n            weight_map(get(&edge_q::weight, G2)));\n\n    // Step 4b -- Trim G2 based on MST\n\n    set<vd_q> vKeep2, vRemove2;\n    set<ed_q> eKeep2, eRemove2;\n\n    for(auto &e : st2)\n    {\n        vKeep2.insert(source(e, G2)); vKeep2.insert(target(e, G2));\n        eKeep2.insert(e);\n    }\n\n    BGL_FORALL_VERTICES(v, G2, graph_q) \n    {\n        if(vKeep2.count(v) == 0) \n            vRemove2.insert(v);\n    }\n\n    BGL_FORALL_EDGES(e, G2, graph_q)\n    {\n        if(eKeep2.count(e) == 0)\n            eRemove2.insert(e);\n    }\n\n    for(auto Ex : eRemove2) remove_edge(Ex, G2);\n    for(auto Vx : vRemove2) remove_vertex(Vx, G2);\n\n    auto end_step_4 = chrono::steady_clock::now();\n    cout << \"[KMB] Step4: \"<< chrono::duration <double, milli> (end_step_4-start_step_4).count() << \" ms\" << endl;\n\n#ifdef DEBUG\n    write_graphviz_dp(dbg, G2, dp_q2);\n    cout << \"Step5-----------------------------------\\n\";\n#endif\n\n    auto start_step_5 = chrono::steady_clock::now();\n\n    // Remove non-steiner leaf nodes\n    // Possible optimization : Start from leaf node and delete upwards instead \n    // of iterating over and over the graph and examining each time.\n\n    set<vd_q> to_remove;\n    do\n    {\n        for(auto v : to_remove)  \n        {\n            clear_vertex(v, G2);\n            remove_vertex(v, G2);\n        }\n\n        to_remove.clear();\n\n        BGL_FORALL_VERTICES(v, G2, graph_q)      \n        {\n            if(multicast_vertices.count(G2[v].label) == 0 && degree(v, G2) == 1)\n            {\n                //cout << \"Removing: \" << v << \" \" << G2[v].label << \"\\n\";\n                to_remove.insert(v);\n            }\n        }\n    } while(to_remove.size() > 0);\n\n    auto end_step_5 = chrono::steady_clock::now();\n    cout << \"[KMB] Step5: \"<< chrono::duration <double, milli> (end_step_5-start_step_5).count() << \" ms\" << endl;\n\n#ifdef DEBUG\n    write_graphviz_dp(dbg, G2, dp_q2);\n    cout << \"Step6-----------------------------------\\n\";\n#endif\n\n    // Update the fillcolor and penwidth in the original graph and print it out. \n\n    for(auto &m : multicast_vertices)\n    {\n        network[m].fillcolor = string(\"black\");\n    }\n\n    BGL_FORALL_EDGES(ed, G2, graph_q)\n    {\n        vd_p vx = G2[source(ed, G2)].label;\n        vd_p vy = G2[target(ed, G2)].label;\n\n        //cout << vx << \" \" << vy << \"\\n\";\n        ed_p e; bool f = false;\n        tie(e,f) = edge(vx, vy, network);\n        assert(f && \"ed_p not found in original graph!\");\n        network[e].penwidth = 5;\n    }\n\n    try\n    {\n        write_graphviz_dp(output_file, network, dp);\n    }\n    catch(std::exception &err)\n    {\n        cerr << err.what() << endl;\n        cerr << \"write_graphviz failed for \" << output_filename << \"\\n\";\n        return 1;\n    }\n\n    return 0;\n}\n\n\n", "meta": {"hexsha": "4342bace6839c834e0164aa6f9208ac32a83de8b", "size": 13436, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "KMB.cpp", "max_stars_repo_name": "snehasish/bgl-kmb", "max_stars_repo_head_hexsha": "a1eb9d8e1baa99371ff674edff964a468859dd7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-01-11T06:07:59.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-12T17:12:15.000Z", "max_issues_repo_path": "KMB.cpp", "max_issues_repo_name": "snehasish/bgl-kmb", "max_issues_repo_head_hexsha": "a1eb9d8e1baa99371ff674edff964a468859dd7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "KMB.cpp", "max_forks_repo_name": "snehasish/bgl-kmb", "max_forks_repo_head_hexsha": "a1eb9d8e1baa99371ff674edff964a468859dd7f", "max_forks_repo_licenses": ["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.4661016949, "max_line_length": 139, "alphanum_fraction": 0.5772551355, "num_tokens": 3624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2906515453221567}}
{"text": "/**\n\n\\file\n\\author Datta Ramadasan\n//==============================================================================\n//         Copyright 2015 INSTITUT PASCAL UMR 6602 CNRS/Univ. Clermont II\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n\n*/\n\n#ifndef __LMA_OPT2_BA_CREATE_HESSIAN_HPP__\n#define __LMA_OPT2_BA_CREATE_HESSIAN_HPP__\n\n#include \"make_type.hpp\"\n\n#include <libv/lma/ttt/mpl/for.hpp>\n#include <libv/lma/lm/function/function.hpp>\n#include <libv/lma/ttt/fusion/pair.hpp>\n#include <libv/lma/ttt/mpl/naming.hpp>\n#include <libv/lma/ttt/mpl/cat.hpp>\n#include <boost/mpl/unique.hpp>\n#include <boost/mpl/count_if.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/mpl/or.hpp>\n#include <boost/mpl/and.hpp>\n#include <boost/mpl/transform.hpp>\n#include <boost/mpl/replace.hpp>\n#include <boost/mpl/copy_if.hpp>\n#include <boost/type_traits/is_same.hpp>\n\nnamespace lma\n{\n\n  // extract parameters\n  template<class L1> using ListOfListOfParameters = mpl::transform<L1,Function<mpl::_1>>;\n\n  template<class A, class B> struct MakePair\n  {\n    typedef bf::pair<A,B> type;\n  };\n\n  template<class Int_, class List, class Int, class Result> struct CreatePairs3_\n  : mpl::push_back<\n                  Result,\n                  typename MakePair<typename mpl::at<List,Int_>::type,typename mpl::at<List,Int>::type>::type\n                  > {};\n\n  template<class Int> using CreatePairs3 = CreatePairs3_<Int,mpl::_1,mpl::_2,mpl::_3>;\n\n  template<class List, class Int, class Result> struct CreatePairs2_ : For<Int::value+1,mpl::size<List>::value,List,CreatePairs3<Int>,Result> {};\n\n  template<class L> using CreatePairs2 = CreatePairs2_<L,mpl::_2,mpl::_3>;\n\n  template<class T> struct Unique : mpl::unique<T, boost::is_same<mpl::_1,mpl::_2> > {};// ne retire que les doublons contigus\n\n  // L ne doit pas contenir de doublon\n  template<class L> struct CreatePairs : For<0,mpl::size<L>::value,L,CreatePairs2<L>> {};\n\n  // get cross parameters\n  template<class L2> using CrossParameters = mpl::transform<typename mpl::transform<L2,Unique<mpl::_1>>::type,CreatePairs<mpl::_1>>;\n\n  template<class T> struct Double {};\n  template<class T> struct Single {};\n\n  template<class T, class L> struct SingleOrDouble : mpl::if_c<(mpl::count_if<L,boost::is_same<mpl::_1,T>>::value>1),Double<T>,Single<T>> {};\n\n  template<class L> struct DiagHessianFunctor : mpl::transform<typename Unique<L>::type,SingleOrDouble<mpl::_1,L>> {};\n\n  template<class L2> using ToSingleOrDouble = mpl::transform<L2,DiagHessianFunctor<mpl::_1>>;\n\n  template<class L3, class L4> using CatCrossAndDiag = mpl::transform<L4,L3,Cat<mpl::_1,mpl::_2>>;\n\n  template<class L, class T> struct AddIf;\n\n  template<class L, class A, class B> struct AddIf<L,bf::pair<A,B>>\n  : mpl::if_<\n              mpl::or_<\n                      mpl::contains<L,bf::pair<A,B>>,\n                      mpl::contains<L,bf::pair<B,A>>\n                      >,\n              L,\n              typename mpl::push_back<L,bf::pair<A,B>>::type\n            > {};\n\n  template<class L, class T> struct AddIf<L,Single<T>>\n  : mpl::if_<\n              mpl::or_<\n                        mpl::contains<L,Single<T>>,\n                        mpl::contains<L,Double<T>>\n                      >,\n              L,\n              typename mpl::push_front<L,Single<T>>::type\n            > {};\n\n\n  template<class L, class T> struct AddIf<L,Double<T>>\n  :  mpl::if_<\n              boost::mpl::contains<L,Single<T>>,\n              typename mpl::replace<L,Single<T>,Double<T>>::type,\n              typename mpl::push_front<L,Double<T>>::type\n            > {};\n\n  template<class List, class Int, class Result> struct ForEachParameters : AddIf<Result,typename mpl::at<List,Int>::type> {};\n\n  template<class List, class Int, class Result> struct ForEachFunctor :\n  For<0,mpl::size<typename mpl::at<List,Int>::type>::value,typename mpl::at<List,Int>::type,ForEachParameters<mpl::_1,mpl::_2,mpl::_3>,Result> {};\n\n  template<class L> using TypesContainers = For<0,mpl::size<L>::value,L,ForEachFunctor<mpl::_1,mpl::_2,mpl::_3>>;\n  \n  template<class T, class Flt> struct ToTable;\n  \n  template<class A, class Flt> struct ToTable<Single<A>,Flt>// : MakeTupleTable<A,A,Flt> {\n  {\n    typedef bf::pair<bf::pair<A,A>,Table<A,A,Flt,Diagonal>> type;\n  };\n  \n  template<class A, class Flt> struct ToTable<Double<A>,Flt>\n  {\n    typedef bf::pair<bf::pair<A,A>,Table<A,A,Flt,Symetric>> type;\n  };\n  \n  template<class A, class B, class Flt> struct ToTable<bf::pair<A,B>,Flt> : MakeTupleTable<A,B,Flt> {};\n  \n  template<class L, class Flt> using Containers = mpl::transform<L,ToTable<mpl::_1,Flt>>;\n  \n  \n  template<class Result, class A, class B> struct add_ { typedef Result type; };\n  template<class Result, class A> struct add_<Result,A,Single<A>> : mpl::push_back<Result,Single<A>> {};\n  template<class Result, class A> struct add_<Result,A,Double<A>> : mpl::push_back<Result,Double<A>> {};\n  template<class Result, class A, class B> struct add_<Result,A,bf::pair<A,B>> : mpl::push_back<Result,bf::pair<A,B>> {};\n  template<class Elt, class L, class Int, class Result> struct Ordering2 : add_<Result,Elt,typename mpl::at<L,Int>::type> {};\n  \n  template<class L, class Ordre, class Int, class Result> struct Ordering : For<0,mpl::size<L>::value,L,Ordering2<typename mpl::at<Ordre,Int>::type,mpl::_1,mpl::_2,mpl::_3>,Result> {};\n  template<class L, class Ordre> struct Order : For<0,mpl::size<Ordre>::value,Ordre,Ordering<L,mpl::_1,mpl::_2,mpl::_3>> {};\n  \n  template<class Keys, class T> struct IsKeyUs : mpl::false_ { };\n  template<class Keys, class Key, class P, class Q, class T, class Tag> struct IsKeyUs<Keys, bf::pair< Key, Table<P,Q,T,Tag> >>\n    : mpl::and_< mpl::contains<Keys,P>, mpl::contains<Keys,Q> > { };\n  \n  template<class T> struct SymetricToDiagonal { typedef T type; };\n  template<class Key, class P, class T> struct SymetricToDiagonal<bf::pair< Key, Table<P,P,T,Diagonal> >>  { typedef bf::pair< Key, Table<P,P,T,Symetric> > type; };\n  \n  template<class H, class KeyUs> struct ListS\n  {\n    typedef typename mpl::copy_if<H, IsKeyUs<KeyUs,mpl::_1>>::type type0;\n    typedef typename mpl::transform<type0, SymetricToDiagonal<mpl::_1>>::type type;\n  };\n  \n  template<class Bundle, class flt> struct ListH\n  {\n    typedef typename Bundle::ListFunction ListFunction;\n    typedef typename Bundle::ListeParam ListeParam;\n    typedef typename Bundle::ParamFonctor ParamFonctor;\n    typedef ListFunction L1;\n\n//       typedef typename CreateListParam<ListFunction,ParamFonctor>::type parameters;\n      \n      typedef typename ListOfListOfParameters<L1>::type L2_;\n      typedef typename mpl::transform<L2_,ParamFonctor>::type L2;\n      \n      typedef typename CrossParameters<L2>::type L3;\n      \n      typedef typename ToSingleOrDouble<L2>::type L4;\n\n      typedef typename CatCrossAndDiag<L3,L4>::type L5;\n\n      typedef typename TypesContainers<L5>::type L6;\n      \n      typedef typename Order<L6,ListeParam>::type L7;\n      \n      typedef typename Containers<L7,flt>::type type;\n      \n      \n      \n      static void disp()\n      {\n        std::cout << \" Functors : \" << ttt::name<L1>() << std::endl;\n        std::cout << \" ListOfListOfParameters : \" << ttt::name<L2>() << std::endl;\n        std::cout << \" ToSingleOrDouble : \" << ttt::name<L4>() << std::endl;\n        std::cout << std::endl;\n        std::cout << \" CrossAndDiag : \" << ttt::name<L5>() << std::endl;\n        std::cout << std::endl;\n        std::cout << \" Types : \" << ttt::name<L6>() << std::endl;\n        std::cout << \" Order  : \" << ttt::name<L7>() << std::endl;\n        std::cout << \" Containers  : \" << ttt::name<type>() << std::endl;\n//         std::cout << \" Parmaeters \" << ttt::name<ListeParam>() << std::endl;\n      }\n  };\n  \n  \n  \n}\n\nnamespace ttt\n{\n  template<class T> struct Name<lma::Single<T>> { static std::string name() { return std::string(\"Single<\") + ttt::name<T>() + \">\"; } };\n  template<class T> struct Name<lma::Double<T>> { static std::string name() { return std::string(\"Double<\") + ttt::name<T>() + \">\"; } };\n}\n  \n#endif", "meta": {"hexsha": "999b8c0775f302fae8ced0f85cd34771c37576c3", "size": 8231, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libv/lma/lm/ba/create_hessian.hpp", "max_stars_repo_name": "bezout/LMA", "max_stars_repo_head_hexsha": "9555e41eed5f44690c5f6e3ea2d22d520ff1a9d2", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2015-12-08T12:07:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T21:23:01.000Z", "max_issues_repo_path": "src/libv/lma/lm/ba/create_hessian.hpp", "max_issues_repo_name": "ayumizll/LMA", "max_issues_repo_head_hexsha": "e945452e12a8b05bd17400b46a20a5322aeda01d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-07-11T16:23:48.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-05T13:33:00.000Z", "max_forks_repo_path": "src/libv/lma/lm/ba/create_hessian.hpp", "max_forks_repo_name": "bezout/LMA", "max_forks_repo_head_hexsha": "9555e41eed5f44690c5f6e3ea2d22d520ff1a9d2", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-12-21T01:52:27.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-26T02:26:55.000Z", "avg_line_length": 40.3480392157, "max_line_length": 184, "alphanum_fraction": 0.6259263759, "num_tokens": 2296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5, "lm_q1q2_score": 0.29065154532215665}}
{"text": "/* -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n// This file is a part of ChASE.\n// Copyright (c) 2015-2021, Simulation and Data Laboratory Quantum Materials, \n//   Forschungszentrum Juelich GmbH, Germany. All rights reserved.\n// License is 3-clause BSD:\n// https://github.com/ChASE-library/ChASE\n\n#include <boost/program_options.hpp>\n#include <boost/filesystem.hpp>\n#include <stdio.h>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <cmath>\n#include <time.h>\n#include <iomanip>\n#include <chrono>\n#include <cstdlib>\n\n#include \"algorithm/performance.hpp\"\n#include \"ChASE-MPI/chase_mpi.hpp\"\n\n#include \"ChASE-MPI/impl/chase_mpidla_blaslapack_seq.hpp\"\n#include \"ChASE-MPI/impl/chase_mpidla_blaslapack_seq_inplace.hpp\"\n#include \"ChASE-MPI/impl/chase_mpidla_blaslapack.hpp\"\n\n#ifdef DRIVER_BUILD_MGPU\n#include \"ChASE-MPI/impl/chase_mpidla_mgpu.hpp\"\n#endif\n\n#include \"scalapack_templates.hpp\"\n\nconst int i_zero = 0, i_one = 1;\nconst std::size_t sze_one = 1;\n\ntypedef std::size_t DESC[ 9 ];\n\nnamespace po = boost::program_options;\nnamespace bf = boost::filesystem;\n\nusing namespace::chase;\nusing namespace::chase::mpi;\n\n\ntemplate <typename T>\nstd::vector<T> generateEyeMat(std::size_t N){\n  int rank;\n  MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n  if (rank == 0) std::cout << \"]> Generating an Identity matrix as S\" << std::endl;\n\n  std::vector<T> S(N * N, T(0.0));\n  for (std::size_t i = 0; i < N; i++) {\n    S[i + i * N] = 1.0;\n  }\n\n  return S;\n}\n\ntemplate <typename T>\nstd::vector<T> generateClementMat(std::size_t N){\n  int rank;\n  MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n  if (rank == 0) std::cout << \"]> Generating a Clement matrix as H\" << std::endl;\n\n  std::vector<T> C(N * N, T(0.0));\n  for (auto i = 0; i < N; ++i) {\n    C[i + N * i] = 0;\n    if (i != N - 1) C[i + 1 + N * i] = std::sqrt(i * (N + 1 - i));\n    if (i != N - 1) C[i + N * (i + 1)] = std::sqrt(i * (N + 1 - i));\n  }\n\n  return C;\n}\n\n//write eigenvalues: path_out/eigenvalues_index.bin\n//write eigenvetors: path_out/eigenvectors_index.bin\ntemplate <typename T>\nvoid writeMatrix(T *H, std::string path_out, std::string prefix, \n\t\t       std::size_t index, std::string suffix, std::size_t size)\n{\n  std::ostringstream problem(std::ostringstream::ate);\n  problem << path_out << prefix << \"_\" << index << suffix;\n\n  std::cout << \"]> writing \";\n  std::cout << prefix << \" of size into \";\n  std::cout << problem.str() << std::endl;\n\n  auto outfile = std::fstream(problem.str().c_str(), std::ios::out | std::ios::binary);\n\n  outfile.write((char*)&H[0], size * sizeof(T));\n\n  outfile.close();\n\n}\n\n//read eigenvalues: path_in/eigenvalues_index.bin\n//read eigenvetors: path_in/eigenvectors_index.bin\ntemplate <typename T>\nvoid readMatrix(T *H, std::string path_in, std::string prefix,\n                       std::size_t index, std::string suffix, std::size_t size)\n{\n  std::ostringstream problem(std::ostringstream::ate);\n  problem << path_in << prefix << \"_\" << index << suffix;\n\n  std::cout << \"]> reading \";\n  std::cout << prefix << \" of size from \";\n  std::cout << problem.str() << std::endl;\n\n  auto infile = std::fstream(problem.str().c_str(), std::ios::binary);\n\n  infile.write((char*)&H[0], size * sizeof(T));\n\n  infile.close();\n\n}\n\n\ntemplate <typename T>\nvoid readMatrix(T* H, std::string path_in, std::string prefix,\n                std::size_t index, std::string suffix, std::size_t size, \n\t\tstd::size_t m, std::size_t mblocks, std::size_t nblocks,\n            \tstd::size_t* r_offs, std::size_t* r_lens, std::size_t* r_offs_l, \n\t\tstd::size_t* c_offs, std::size_t* c_lens, std::size_t* c_offs_l)\n{\n\n  std::size_t N = std::sqrt(size);\n  std::ostringstream problem(std::ostringstream::ate);\n\n  int rank;\n  MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n  problem << path_in << prefix << \"  1 \" << std::setw(2) << index << suffix;\n  if (rank == 0) std::cout << \"]> Loading \" << problem.str() << std::endl;\n\n  std::size_t file_size = bf::file_size(problem.str().c_str());\n\n  try{\n    if(size * sizeof(T) != file_size ){\n      throw std::logic_error(std::string(\"The given file : \") +\n                               problem.str() + std::string(\" of size \") + std::to_string(file_size) +\n                               std::string(\" doesn't equals to the required size of matrix of size \") + std::to_string(size * sizeof(T)));\n    }\n  }\n  catch(std::exception &e)\n  {\n    std::cerr << \"Caught \" << typeid( e ).name( ) << \" : \"<< e.what( ) << std::endl;\n    return ;\n  }\n\n  std::ifstream input(problem.str().c_str(), std::ios::binary);\n\n  if (!input.is_open()) {\n    throw new std::logic_error(std::string(\"error reading file: \") +\n                               problem.str());\n  }\n\n  for(std::size_t j = 0; j < nblocks; j++){\n      for(std::size_t i = 0; i < mblocks; i++){\n          for(std::size_t q = 0; q < c_lens[j]; q++){\n\t      input.seekg(((q + c_offs[j]) * N + r_offs[i])* sizeof(T));\n\t      input.read(reinterpret_cast<char*>(H + (q + c_offs_l[j]) * m + r_offs_l[i]), r_lens[i] * sizeof(T));\n\t  }\n      }\n  }\n}\n\nusing T = std::complex<double>;\n\n#ifdef DRIVER_BUILD_MGPU\ntypedef ChaseMpi<ChaseMpiDLAMultiGPU, T> CHASE;\n#else\ntypedef ChaseMpi<ChaseMpiDLABlaslapack, T> CHASE;\n#endif\n\nstruct ChASE_DriverProblemConfig {\n  std::size_t N;    // Size of the Matrix\n  std::size_t nev;  // Number of sought after eigenvalues\n  std::size_t nex;  // Extra size of subspace\n  std::size_t deg;  // initial degree\n  std::size_t bgn;  // beginning of sequence\n  std::size_t end;  // end of sequence\n\n  double tol;     // desired tolerance\n  bool sequence;  // handle this as a sequence?\n\n  std::string path_in;    // path to the matrix input files\n  std::string mode;       // Approx or Random mode\n  std::string opt;        // enable optimisation of degree\n  std::string arch;       // ??\n  std::string path_eigp;  // TODO\n  std::string path_out;\n  std::string path_name;\n\n  bool complex;\n  bool isdouble;\n  \n  std::size_t mbsize;\n  std::size_t nbsize;\n  int dim0;\n  int dim1;\n  int irsrc;\n  int icsrc;\n  std::string major;\n};\n\ntemplate <typename T>\nint do_chase_gev(ChASE_DriverProblemConfig& conf) {\n\n  T alpha = 0.5;\n  std::size_t N = conf.N;\n  std::size_t nev = conf.nev;\n  std::size_t nex = conf.nex;\n  std::size_t deg = conf.deg;\n  std::size_t bgn = conf.bgn;\n  std::size_t end = conf.end;\n\n  double tol = conf.tol;\n  bool sequence = conf.sequence;\n\n  std::string path_in = conf.path_in;\n  std::string mode = conf.mode;\n  std::string opt = conf.opt;\n  std::string arch;\n  std::string path_eigp = conf.path_eigp;\n  std::string path_out = conf.path_out;\n  std::string path_name = conf.path_name;\n\n  std::size_t mbsize = conf.mbsize;\n  std::size_t nbsize = conf.nbsize;\n  int dim0 = conf.dim0;\n  int dim1 = conf.dim1;\n  int irsrc = conf.irsrc;\n  int icsrc = conf.irsrc;\n  std::string major = conf.major;\n\n  if(dim0 == 0 || dim1 == 0){\n    int dims[2];\n    dims[0] = dims[1] = 0;\n    int gsize;\n    MPI_Comm_size(MPI_COMM_WORLD, &gsize);    \n    MPI_Dims_create(gsize, 2, dims);\n    dim0 = dims[0];\n    dim1 = dims[1];    \n  }\n\n  int rank, size;\n\n  MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n  MPI_Comm_size(MPI_COMM_WORLD, &size);\n\n  std::cout << std::setprecision(16);\n\n  if (rank == 0){\n    std::cout << \"\\nChASE example driver for a sequence of Generalized \"\n\t<<\"Eigenproblems.\"\n\t<< std::endl;\n  }\n\n  // Timing variables\n  std::chrono::high_resolution_clock::time_point st, ed, st_loc;\n  std::size_t prb_nb = end - bgn + 1;\n  std::chrono::duration<double> elapsed[6][prb_nb];\n\n  //Scalapack part\n  //Initalize Scalapack environment\n  int myproc, nprocs;\n  blacs_pinfo( &myproc, &nprocs );\n\n  int ictxt;\n  int val;\n  blacs_get( &ictxt, &i_zero, &val );\n\n  blacs_gridinit( &ictxt, major.at(0), &dim0, &dim1 );\n  int myrow, mycol;\n  blacs_gridinfo( &ictxt, &dim0, &dim1, &myrow, &mycol);\n\n  //get local size of matrix = N_loc_r x N_loc_c\n  std::size_t N_loc_r, N_loc_c;\n\n  N_loc_r = numroc( &N, &mbsize, &myrow, &irsrc, &dim0 );\n  N_loc_c = numroc( &N, &nbsize, &mycol, &icsrc, &dim1 );\n\n  //for column major matrix, the leading dimension\n  std::size_t lld_loc = std::max(N_loc_r, (std::size_t)1);\n\n  //construct scalapack matrix descriptor \n  DESC   desc;\n  int    info;\n\n  descinit( desc, &N, &N, &mbsize, &nbsize, &irsrc, &irsrc, &ictxt, &lld_loc, &info );\n\n  //ChASE part\n  //eigenpairs of standard eigenproblem\n  auto V__ = std::unique_ptr<T[]>(new T[N * (nev + nex)]);\n  auto Lambda__ = std::unique_ptr<Base<T>[]>(new Base<T>[(nev + nex)]);\n\n  T* V = V__.get();\n  Base<T>* Lambda = Lambda__.get();\n\n  //Setup ChASE environment for a standard eigenproblem\n  CHASE single(new ChaseMpiProperties<T>(N, mbsize, nbsize, nev, nex, dim0, \n\tdim1, const_cast<char*>(major.c_str()), irsrc, icsrc, MPI_COMM_WORLD), V, Lambda);\n\n  ChaseConfig<T>& config = single.GetConfig();\n  config.SetTol(tol);\n  config.SetDeg(deg);\n  config.SetOpt(opt == \"S\");\n  config.SetMaxIter(100);\n\n  if (rank == 0)\n    std::cout << \"\\n\"\n              << config;\n\n  std::mt19937 gen(1337.0);\n  std::normal_distribution<> d;\n\n  T* matrix = single.GetMatrixPtr();\n\n  // Using ChASE-MPI functionalities to get some additional information \n  // on the block cyclic data layout which faciliates the implementation\n  //local block number = mblocks x nblocks\n  std::size_t mblocks = single.get_mblocks(); \n  std::size_t nblocks = single.get_nblocks();\n\n  //local matrix size = m x n\n  std::size_t m = single.get_m(); // should = N_loc_r\n  std::size_t n = single.get_n(); // should = N_loc_c\n\n  //global and local offset/length of each block of block-cyclic data\n  std::size_t *r_offs, *c_offs, *r_lens, *c_lens, *r_offs_l, *c_offs_l;\n\n  single.get_offs_lens(r_offs, r_lens, r_offs_l, c_offs, c_lens, c_offs_l);\n\n  Base<T> scale; //for t_psy(he)gst in Scalapack\n\n  // GEV: H * X = LAMBDA * S * X, in which H and S are local matrices\n  T *H = new T [N_loc_r * N_loc_c];\n  T *S = new T [N_loc_r * N_loc_c];\n\n  //sequence of problem\n  for(auto idx = bgn; idx <= end; ++idx){\n\n    if (rank == 0) {\n      std::cout << \"]> Starting Problem #\" << idx << \"\\n\";\n    }\n    \n    st = std::chrono::high_resolution_clock::now();\n    st_loc = std::chrono::high_resolution_clock::now();\n\n    // if the path of matrices are empty, generate H as a Clement matrix\n    // and generate S as an Identity matrix\n    if(path_in.empty())\n    {\n      //Generate Clement matrix\n      std::vector<T> HH = generateClementMat<T>(N);\n      //Generate an Identify matrix\n      std::vector<T> SS = generateEyeMat<T>(N);\n      //redistribute into HH and SS into block cyclic layout\n      for(std::size_t j = 0; j < nblocks; j++){\n        for(std::size_t i = 0; i < mblocks; i++){\n          for(std::size_t q = 0; q < c_lens[j]; q++){\n\t    for(std::size_t p = 0; p < r_lens[i]; p++){\n\t      H[(q + c_offs_l[j]) * m + p + r_offs_l[i]] = HH[(q + c_offs[j]) * N + p + r_offs[i]];\n              S[(q + c_offs_l[j]) * m + p + r_offs_l[i]] = SS[(q + c_offs[j]) * N + p + r_offs[i]];\n\t    }\n\t  }\n        }\n      } \n    }else //if path of matrices are given, load them into H and S by parallel IO\n    {\n      //read matrix H from local\n      readMatrix(H, path_in, \"hmat\", idx, \".bin\", N * N, m, mblocks, nblocks,\n         r_offs, r_lens, r_offs_l, c_offs, c_lens, c_offs_l);\n      //read matrix S from local\n      readMatrix(S, path_in, \"smat\", idx, \".bin\", N * N, m, mblocks, nblocks,\n         r_offs, r_lens, r_offs_l, c_offs, c_lens, c_offs_l);\n    }\n\n    ed = std::chrono::high_resolution_clock::now();\n    elapsed[0][idx - 1] = std::chrono::duration_cast<std::chrono::duration<double>>(ed - st_loc);\n \n    st_loc = std::chrono::high_resolution_clock::now();\n\n    // Transform to standard problem using SCALAPACK\n    // Cholesky Factorization of S = L * L^T, S is overwritten by L\n    t_ppotrf<T>('U', N, S, sze_one, sze_one, desc);\n\n    ed = std::chrono::high_resolution_clock::now();\n    elapsed[1][idx - 1] = std::chrono::duration_cast<std::chrono::duration<double>>(ed - st_loc);\n\n    st_loc = std::chrono::high_resolution_clock::now();\n\n    // Reduce H * X = eig * S ( X to the standard from H' * X' = eig * X'\n    // with H' = L^{-1} * H * (L^T)^{-1}\n    t_psyhegst<T>(i_one, 'U', N, H, sze_one, sze_one, desc, S, sze_one, sze_one, desc, &scale);\n\n    // ensure H' to be exact Symmetric/Hermtian by H' = 0.5*H'+0.5*transpose(H')\n    T *tmpH = new T [m * n];\n    std::memcpy(tmpH, H, m * n * sizeof(T));\n    t_geadd<T>('T', N, N, alpha, tmpH, sze_one, sze_one, desc, alpha, H, sze_one, sze_one, desc);\n\n    ed = std::chrono::high_resolution_clock::now();\n    elapsed[2][idx - 1] = std::chrono::duration_cast<std::chrono::duration<double>>(ed - st_loc);\n\n    // Copy H into single.matrix()\n    std::memcpy(matrix, H, m * n * sizeof(T));\n\n    // for the first problem, generate randomly the initial guess of V\n    if (idx == bgn) {\n      config.SetApprox(false);\n      //random generated initial guess of V\n      for (std::size_t i = 0; i < N * (nev + nex); ++i) {\n        V[i] = T(d(gen), d(gen));\n      }\n    }else{\n      //use the eigenpairs from last problem\n      config.SetApprox(true);\n    }\n\n    PerformanceDecoratorChase<T> performanceDecorator(&single);\n\n    MPI_Barrier(MPI_COMM_WORLD);\n\n    st_loc = std::chrono::high_resolution_clock::now();\n\n    // ChASE to solve the standard eigenproblem H' * X' = eig * X'\n    chase::Solve(&performanceDecorator);\n\n    MPI_Barrier(MPI_COMM_WORLD);\n\n    ed = std::chrono::high_resolution_clock::now();\n    elapsed[3][idx - 1] = std::chrono::duration_cast<std::chrono::duration<double>>(ed - st_loc);\n\n    if (rank == 0) {\n      std::cout << \"\\n]> Output of ChASE for Problem #\" << idx << \"\\n\";\n      performanceDecorator.GetPerfData().print();\n      Base<T>* resid = single.GetResid();\n      std::cout << \"]> Printing first 5 eigenvalues and residuals\\n\";\n      std::cout\n          << \"| Index |       Eigenvalue      |         Residual      |\\n\"\n          << \"|-------|-----------------------|-----------------------|\\n\";\n      std::size_t width = 20;\n      std::cout << std::setprecision(12);\n      std::cout << std::setfill(' ');\n      std::cout << std::scientific;\n      std::cout << std::right;\n      for (auto i = 0; i < std::min(std::size_t(5), nev); ++i)\n        std::cout << \"|  \" << std::setw(4) << i + 1 << \" | \" << std::setw(width)\n                  << Lambda[i] << \"  | \" << std::setw(width) << resid[i]\n                  << \"  |\\n\";\n      std::cout << \"\\n\";\n    }\n\n\n    //Scalapack part\n    //In ChASE, the eigenvectors V is stored rebundantly on each proc\n    //In order to recover the generalized eigenvectors by Scalapack, it should be\n    //redistributed into block-cyclic format. We re-use H to restore V.\n    //this part is in parallel implicitly\n    \n    st_loc = std::chrono::high_resolution_clock::now();\n\n    for(std::size_t j = 0; j < nblocks; j++){\n      for(std::size_t i = 0; i < mblocks; i++){\n        for(std::size_t q = 0; q < c_lens[j]; q++){\n\t  for(std::size_t p = 0; p < r_lens[i]; p++){\n\t    if((q + c_offs[j]) * N + p + r_offs[i] < (nev + nex) * N){\n\t      H[(q + c_offs_l[j]) * m + p + r_offs_l[i]] = V[(q + c_offs[j]) * N + p + r_offs[i]];\n\t    }\n\t  }\n\t}\n      }\n    }\n\n    //Now the first (nev+nex) columns of H (a global view) is overwritten by V   \n    //Recover the genealized eigenvectors X by solving X' = L^T * X\n\n    t_ptrtrs<T>('U','N','N', N, nev + nex, S, sze_one, sze_one, desc, H, sze_one, sze_one, desc);\n\n    ed = std::chrono::high_resolution_clock::now();\n    elapsed[4][idx - 1] = std::chrono::duration_cast<std::chrono::duration<double>>(ed - st_loc);\n    elapsed[5][idx - 1] = std::chrono::duration_cast<std::chrono::duration<double>>(ed - st);\n\n    //copy V_dist -> V;\n    //restore eigenvectors from scalapack form to ChASE form\n\n    if (rank == 0) {\n      std::cout << \"]> Finished Problem #\" << idx << \"\\n\";\n      std::cout << \"**********************\"  << std::endl;\n    }\n  }\n\n  MPI_Barrier(MPI_COMM_WORLD);\n\n  if(rank == 0){\n    std::cout << \"\\nSUMMARY : Time (s)\" << \"\\n\";\n    std::cout\n          << \"---------------------------------------------------------------------------------------------------------------------------------------------------------------\\n\"\n          << \"|  Index|             Parallel IO|  Cholesky Factorization|    Transfer to Standard|            ChASE Solver|          Back Transform|                     All|\\n\"\n          << \"|-------|------------------------|------------------------|------------------------|------------------------|------------------------|------------------------|\";\n    std::cout << std::endl;\n\n    std::cout << std::setprecision(6);\n    std::cout << std::setfill(' ');\n    std::cout << std::scientific;\n    for(auto idx = bgn - 1; idx < end; ++idx){\n      std::cout << \"|\" << std::setw(7) << idx + 1 << \"|\"; \n      for(auto i = 0; i < 6; i++){\n\tstd::cout << std::setw(24) << elapsed[i][idx].count() << \"|\";\n      }\n      std::cout << std::endl;\n    }  \n\n    std::cout\n            << \"---------------------------------------------------------------------------------------------------------------------------------------------------------------\"\n\t    << std::endl;\n  }\n  \n  return 0;\n}\n\nint main(int argc, char* argv[]) {\n\n  MPI_Init(&argc, &argv);\n\n  ChASE_DriverProblemConfig conf;\n\n  po::options_description desc(\"ChASE Options\");\n\n  desc.add_options()(                                                     //\n      \"help,h\",                                                           //\n      \"show this message\"                                                 //\n      )(                                                                  //\n      \"n\", po::value<std::size_t>(&conf.N)->required(),                   //\n      \"Size of the Input Matrix\"                                          //\n      )(                                                                  //\n      \"double\", po::value<bool>(&conf.isdouble)->default_value(true),     //\n      \"Is matrix complex double valued, false indicates the single type\"  //\n      )(                                                                  //\n      \"complex\", po::value<bool>(&conf.complex)->default_value(true),     //\n      \"Matrix is complex valued\"                                          //\n      )(                                                                  //\n      \"nev\", po::value<std::size_t>(&conf.nev)->required(),               //\n      \"Wanted Number of Eigenpairs\"                                       //\n      )(                                                                  //\n      \"nex\", po::value<std::size_t>(&conf.nex)->default_value(25),        //\n      \"Extra Search Dimensions\"                                           //\n      )(                                                                  //\n      \"deg\", po::value<std::size_t>(&conf.deg)->default_value(20),        //\n      \"Initial filtering degree\"                                          //\n      )(                                                                  //\n      \"bgn\", po::value<std::size_t>(&conf.bgn)->default_value(1),         //\n      \"Start ell\"                                                         //\n      )(                                                                  //\n      \"end\", po::value<std::size_t>(&conf.end)->default_value(1),         //\n      \"End ell\"                                                           //\n      )(                                                                  //\n      \"tol\", po::value<double>(&conf.tol)->default_value(1e-10),          //\n      \"Tolerance for Eigenpair convergence\"                               //\n      )(                                                                  //\n      \"path_in\", po::value<std::string>(&conf.path_in)->default_value(\"\"),//\n      \"Path to the input matrix/matrices\"                                 //\n      )(                                                                  //\n      \"mode\", po::value<std::string>(&conf.mode)->default_value(\"A\"),     //\n      \"valid values are R(andom) or A(pproximate)\"                        //\n      )(                                                                  //\n      \"opt\", po::value<std::string>(&conf.opt)->default_value(\"S\"),       //\n      \"Optimi(S)e degree, or do (N)ot optimise\"                           //\n      )(                                                                  //\n      \"path_eigp\", po::value<std::string>(&conf.path_eigp),               //\n      \"Path to approximate solutions, only required when mode\"            //\n      \"is Approximate, otherwise not used\"                                //\n      )(                                                                  //\n      \"sequence\", po::value<bool>(&conf.sequence)->default_value(false),  //\n      \"Treat as sequence of Problems. Previous ChASE solution is used,\"   //\n      \"when available\"                                                    //\n      )(                                                                  //\n      \"mbsize\", po::value<std::size_t>(&conf.mbsize)->default_value(50),  //\n      \"block size for the row\"                                            //\n      )(                                                                  //\n      \"nbsize\", po::value<std::size_t>(&conf.nbsize)->default_value(50),  //\n      \"block size for the column\"                                         //\n      )(                                                                  //\n      \"dim0\", po::value<int>(&conf.dim0)->default_value(0),               //\n      \"row number of MPI proc grid\"                                       //\n      )(                                                                  //\n      \"dim1\", po::value<int>(&conf.dim1)->default_value(0),               //\n      \"column number of MPI proc grid\"                                    //\n      )(\t\t\t\t\t\t\t\t  //\n      \"irsrc\", po::value<int>(&conf.irsrc)->default_value(0),             //\n      \"The process row over which the first row of matrix is\"             //\n      \"distributed.\"                                                      //\n      )(                                                                  //\n      \"icsrc\", po::value<int>(&conf.icsrc)->default_value(0),             //\n      \"The process column over which the first column of the array A is\"  //\n      \"distributed.\"                                                      //\n      )(                                                                  //\n      \"major\", po::value<std::string>(&conf.major)->default_value(\"C\"),    //\n      \"Major of MPI proc grid, valid values are R(ow) or C(olumn)\"        //\n      );\n\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n\n  // print help\n  if (vm.count(\"help\")) {\n    std::cout << desc << std::endl;\n    return 1;\n  }\n\n  po::notify(vm);\n  conf.mode = toupper(conf.mode.at(0));\n  conf.opt = toupper(conf.opt.at(0));\n\n  if (conf.bgn > conf.end) {\n    std::cout << \"Begin must be smaller than End!\" << std::endl;\n    return -1;\n  }\n\n  if (conf.mode != \"R\" && conf.mode != \"A\") {\n    std::cout << \"Illegal value for mode: \\\"\" << conf.mode << \"\\\"\" << std::endl\n              << \"Legal values are R or A\" << std::endl;\n    return -1;\n  }\n\n  if (conf.opt != \"N\" && conf.opt != \"S\") {\n    std::cout << \"Illegal value for opt: \" << conf.opt << std::endl\n              << \"Legal values are N, S\" << std::endl;\n    return -1;\n  }\n\n  if (conf.path_eigp.empty() && conf.mode == \"A\") {\n    std::cout << \"eigp is required when mode is \" << conf.mode << std::endl;\n    return -1;\n  }\n\n  if (conf.isdouble) {\n    do_chase_gev<std::complex<double>>(conf);\n  } else {\n    std::cout << \"single not implemented\\n\";\n  }\n\n  MPI_Finalize();\n\n}\n\n", "meta": {"hexsha": "2838b9edb6b210ba039c715ba2a528d2fa079e19", "size": 23628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/4_gev/4_gev.cpp", "max_stars_repo_name": "brunowu/ChASE", "max_stars_repo_head_hexsha": "89649df6027cec70709f55d277b3625989e8cb3c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-03-18T14:04:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T18:21:57.000Z", "max_issues_repo_path": "examples/4_gev/4_gev.cpp", "max_issues_repo_name": "brunowu/ChASE", "max_issues_repo_head_hexsha": "89649df6027cec70709f55d277b3625989e8cb3c", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/4_gev/4_gev.cpp", "max_forks_repo_name": "brunowu/ChASE", "max_forks_repo_head_hexsha": "89649df6027cec70709f55d277b3625989e8cb3c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-03-18T14:14:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-19T10:21:13.000Z", "avg_line_length": 36.5758513932, "max_line_length": 176, "alphanum_fraction": 0.5174369392, "num_tokens": 6423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.2905029121828688}}
{"text": "//  Copyright John Maddock 2007.\n//  Copyright Paul A. Bristow 2007\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_PARETO_HPP\n#define BOOST_STATS_PARETO_HPP\n\n// http://en.wikipedia.org/wiki/Pareto_distribution\n// http://www.itl.nist.gov/div898/handbook/eda/section3/eda3661.htm\n// Also:\n// Weisstein, Eric W. \"Pareto Distribution.\"\n// From MathWorld--A Wolfram Web Resource.\n// http://mathworld.wolfram.com/ParetoDistribution.html\n\n#include <boost/math/distributions/fwd.hpp>\n#include <boost/math/distributions/complement.hpp>\n#include <boost/math/distributions/detail/common_error_handling.hpp>\n#include <boost/math/special_functions/powm1.hpp>\n\n#include <utility> // for BOOST_CURRENT_VALUE?\n\nnamespace boost\n{\n  namespace math\n  {\n    namespace detail\n    { // Parameter checking.\n      template <class RealType, class Policy>\n      inline bool check_pareto_location(\n        const char* function,\n        RealType location,\n        RealType* result, const Policy& pol)\n      {\n        if((boost::math::isfinite)(location))\n        { // any > 0 finite value is OK.\n          if (location > 0)\n          {\n            return true;\n          }\n          else\n          {\n            *result = policies::raise_domain_error<RealType>(\n              function,\n              \"Location parameter is %1%, but must be > 0!\", location, pol);\n            return false;\n          }\n        }\n        else\n        { // Not finite.\n          *result = policies::raise_domain_error<RealType>(\n            function,\n            \"Location parameter is %1%, but must be finite!\", location, pol);\n          return false;\n        }\n      } // bool check_pareto_location\n\n      template <class RealType, class Policy>\n      inline bool check_pareto_shape(\n        const char* function,\n        RealType shape,\n        RealType* result, const Policy& pol)\n      {\n        if((boost::math::isfinite)(shape))\n        { // Any finite value > 0 is OK.\n          if (shape > 0)\n          {\n            return true;\n          }\n          else\n          {\n            *result = policies::raise_domain_error<RealType>(\n              function,\n              \"Shape parameter is %1%, but must be > 0!\", shape, pol);\n            return false;\n          }\n        }\n        else\n        { // Not finite.\n          *result = policies::raise_domain_error<RealType>(\n            function,\n            \"Shape parameter is %1%, but must be finite!\", shape, pol);\n          return false;\n        }\n      } // bool check_pareto_shape(\n\n      template <class RealType, class Policy>\n      inline bool check_pareto_x(\n        const char* function,\n        RealType const& x,\n        RealType* result, const Policy& pol)\n      {\n        if((boost::math::isfinite)(x))\n        { // \n          if (x > 0)\n          {\n            return true;\n          }\n          else\n          {\n            *result = policies::raise_domain_error<RealType>(\n              function,\n              \"x parameter is %1%, but must be > 0 !\", x, pol);\n            return false;\n          }\n        }\n        else\n        { // Not finite..\n          *result = policies::raise_domain_error<RealType>(\n            function,\n            \"x parameter is %1%, but must be finite!\", x, pol);\n          return false;\n        }\n      } // bool check_pareto_x\n\n      template <class RealType, class Policy>\n      inline bool check_pareto( // distribution parameters.\n        const char* function,\n        RealType location,\n        RealType shape,\n        RealType* result, const Policy& pol)\n      {\n        return check_pareto_location(function, location, result, pol) \n           && check_pareto_shape(function, shape, result, pol);\n      } // bool check_pareto(\n\n    } // namespace detail\n\n    template <class RealType = double, class Policy = policies::policy<> >\n    class pareto_distribution\n    {\n    public:\n      typedef RealType value_type;\n      typedef Policy policy_type;\n\n      pareto_distribution(RealType location = 1, RealType shape = 1)\n        : m_location(location), m_shape(shape)\n      { // Constructor.\n        RealType result;\n        detail::check_pareto(\"boost::math::pareto_distribution<%1%>::pareto_distribution\", location, shape, &result, Policy());\n      }\n\n      RealType location()const\n      { // AKA Xm and b\n        return m_location;\n      }\n\n      RealType shape()const\n      { // AKA k and a\n        return m_shape;\n      }\n    private:\n      // Data members:\n      RealType m_location;  // distribution location (xm)\n      RealType m_shape;  // distribution shape (k)\n    };\n\n    typedef pareto_distribution<double> pareto; // Convenience to allow pareto(2., 3.);\n\n    template <class RealType, class Policy>\n    inline const std::pair<RealType, RealType> range(const pareto_distribution<RealType, Policy>& /*dist*/)\n    { // Range of permissible values for random variable x.\n      using boost::math::tools::max_value;\n      return std::pair<RealType, RealType>(0, max_value<RealType>()); // location zero to + infinity.\n    } // range\n\n    template <class RealType, class Policy>\n    inline const std::pair<RealType, RealType> support(const pareto_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>(dist.location(), max_value<RealType>() ); // location to + infinity.\n    } // support\n\n    template <class RealType, class Policy>\n    inline RealType pdf(const pareto_distribution<RealType, Policy>& dist, const RealType& x)\n    {\n      BOOST_MATH_STD_USING  // for ADL of std function pow.\n      static const char* function = \"boost::math::pdf(const pareto_distribution<%1%>&, %1%)\";\n      RealType location = dist.location();\n      RealType shape = dist.shape();\n      RealType result;\n      if(false == (detail::check_pareto_x(function, x, &result, Policy())\n         && detail::check_pareto(function, location, shape, &result, Policy())))\n         return result;\n      if (x < location)\n      { // regardless of shape, pdf is zero.\n        return 0; \n      }\n\n      result = shape * pow(location, shape) / pow(x, shape+1);\n      return result;\n    } // pdf\n\n    template <class RealType, class Policy>\n    inline RealType cdf(const pareto_distribution<RealType, Policy>& dist, const RealType& x)\n    {\n      BOOST_MATH_STD_USING  // for ADL of std function pow.\n      static const char* function = \"boost::math::cdf(const pareto_distribution<%1%>&, %1%)\";\n      RealType location = dist.location();\n      RealType shape = dist.shape();\n      RealType result;\n\n      if(false == (detail::check_pareto_x(function, x, &result, Policy())\n         && detail::check_pareto(function, location, shape, &result, Policy())))\n         return result;\n\n      if (x <= location)\n      { // regardless of shape, cdf is zero.\n        return 0; \n      }\n\n      // result = RealType(1) - pow((location / x), shape);\n      result = -boost::math::powm1(location/x, shape, Policy()); // should be more accurate.\n      return result;\n    } // cdf\n\n    template <class RealType, class Policy>\n    inline RealType quantile(const pareto_distribution<RealType, Policy>& dist, const RealType& p)\n    {\n      BOOST_MATH_STD_USING  // for ADL of std function pow.\n      static const char* function = \"boost::math::quantile(const pareto_distribution<%1%>&, %1%)\";\n      RealType result;\n      RealType location = dist.location();\n      RealType shape = dist.shape();\n      if(false == (detail::check_probability(function, p, &result, Policy())\n           && detail::check_pareto(function, location, shape, &result, Policy())))\n      {\n        return result;\n      }\n      if (p == 0)\n      {\n        return location; // x must be location (or less).\n      }\n      if (p == 1)\n      {\n        return tools::max_value<RealType>(); // x = + infinity.\n      }\n      result = location /\n        (pow((1 - p), 1 / shape));\n      // K. Krishnamoorthy,  ISBN 1-58488-635-8 eq 23.1.3\n      return result;\n    } // quantile\n\n    template <class RealType, class Policy>\n    inline RealType cdf(const complemented2_type<pareto_distribution<RealType, Policy>, RealType>& c)\n    {\n       BOOST_MATH_STD_USING  // for ADL of std function pow.\n       static const char* function = \"boost::math::cdf(const pareto_distribution<%1%>&, %1%)\";\n       RealType result;\n       RealType x = c.param;\n       RealType location = c.dist.location();\n       RealType shape = c.dist.shape();\n       if(false == (detail::check_pareto_x(function, x, &result, Policy())\n           && detail::check_pareto(function, location, shape, &result, Policy())))\n         return result;\n\n       if (x <= location)\n       { // regardless of shape, cdf is zero, and complement is unity.\n         return 1; \n       }\n       result = pow((location/x), shape);\n   \n       return result;\n    } // cdf complement\n    \n    template <class RealType, class Policy>\n    inline RealType quantile(const complemented2_type<pareto_distribution<RealType, Policy>, RealType>& c)\n    {\n      BOOST_MATH_STD_USING  // for ADL of std function pow.\n      static const char* function = \"boost::math::quantile(const pareto_distribution<%1%>&, %1%)\";\n      RealType result;\n      RealType q = c.param;\n      RealType location = c.dist.location();\n      RealType shape = c.dist.shape();\n      if(false == (detail::check_probability(function, q, &result, Policy())\n           && detail::check_pareto(function, location, shape, &result, Policy())))\n      {\n        return result;\n      }\n      if (q == 1)\n      {\n        return location; // x must be location (or less).\n      }\n      if (q == 0)\n      {\n        return tools::max_value<RealType>(); // x = + infinity.\n      }\n      result = location / (pow(q, 1 / shape));\n      // K. Krishnamoorthy,  ISBN 1-58488-635-8 eq 23.1.3\n      return result;\n    } // quantile complement\n\n    template <class RealType, class Policy>\n    inline RealType mean(const pareto_distribution<RealType, Policy>& dist)\n    {\n      RealType result;\n      static const char* function = \"boost::math::mean(const pareto_distribution<%1%>&, %1%)\";\n      if(false == detail::check_pareto(function, dist.location(), dist.shape(), &result, Policy()))\n      {\n        return result;\n      }\n      if (dist.shape() > RealType(1))\n      {\n        return dist.shape() * dist.location() / (dist.shape() - 1);\n      }\n      else\n      {\n        using boost::math::tools::max_value;\n        return max_value<RealType>(); // +infinity.\n      }\n    } // mean\n\n    template <class RealType, class Policy>\n    inline RealType mode(const pareto_distribution<RealType, Policy>& dist)\n    {\n      return dist.location();\n    } // mode\n\n    template <class RealType, class Policy>\n    inline RealType median(const pareto_distribution<RealType, Policy>& dist)\n    {\n      RealType result;\n      static const char* function = \"boost::math::median(const pareto_distribution<%1%>&, %1%)\";\n      if(false == detail::check_pareto(function, dist.location(), dist.shape(), &result, Policy()))\n      {\n        return result;\n      }\n      BOOST_MATH_STD_USING\n      return dist.location() * pow(RealType(2), (1/dist.shape()));\n    } // median\n\n    template <class RealType, class Policy>\n    inline RealType variance(const pareto_distribution<RealType, Policy>& dist)\n    {\n      RealType result;\n      RealType location = dist.location();\n      RealType shape = dist.shape();\n      static const char* function = \"boost::math::variance(const pareto_distribution<%1%>&, %1%)\";\n      if(false == detail::check_pareto(function, location, shape, &result, Policy()))\n      {\n        return result;\n      }\n      if (shape > 2)\n      {\n        result = (location * location * shape) /\n         ((shape - 1) *  (shape - 1) * (shape - 2));\n      }\n      else\n      {\n        result = policies::raise_domain_error<RealType>(\n          function,\n          \"variance is undefined for shape <= 2, but got %1%.\", dist.shape(), Policy());\n      }\n      return result;\n    } // variance\n\n    template <class RealType, class Policy>\n    inline RealType skewness(const pareto_distribution<RealType, Policy>& dist)\n    {  \n      BOOST_MATH_STD_USING\n      RealType result;\n      RealType shape = dist.shape();\n      static const char* function = \"boost::math::pdf(const pareto_distribution<%1%>&, %1%)\";\n      if(false == detail::check_pareto(function, dist.location(), shape, &result, Policy()))\n      {\n        return result;\n      }\n      if (shape > 3)\n      {\n        result = sqrt((shape - 2) / shape) *\n          2 * (shape + 1) /\n          (shape - 3);\n      }\n      else\n      {\n        result = policies::raise_domain_error<RealType>(\n          function,\n          \"skewness is undefined for shape <= 3, but got %1%.\", dist.shape(), Policy());\n      }\n      return result;\n    } // skewness\n\n    template <class RealType, class Policy>\n    inline RealType kurtosis(const pareto_distribution<RealType, Policy>& dist)\n    {\n      RealType result;\n      RealType shape = dist.shape();\n      static const char* function = \"boost::math::pdf(const pareto_distribution<%1%>&, %1%)\";\n      if(false == detail::check_pareto(function, dist.location(), shape, &result, Policy()))\n      {\n        return result;\n      }\n      if (shape > 4)\n      {\n        result = 3 * ((shape - 2) * (3 * shape * shape + shape + 2)) /\n          (shape * (shape - 3) * (shape - 4));\n      }\n      else\n      {\n        result = policies::raise_domain_error<RealType>(\n          function,\n          \"kurtosis_excess is undefined for shape <= 4, but got %1%.\", shape, Policy());\n      }\n      return result;\n    } // kurtosis\n\n    template <class RealType, class Policy>\n    inline RealType kurtosis_excess(const pareto_distribution<RealType, Policy>& dist)\n    {\n      RealType result;\n      RealType shape = dist.shape();\n      static const char* function = \"boost::math::pdf(const pareto_distribution<%1%>&, %1%)\";\n      if(false == detail::check_pareto(function, dist.location(), shape, &result, Policy()))\n      {\n        return result;\n      }\n      if (shape > 4)\n      {\n        result = 6 * ((shape * shape * shape) + (shape * shape) - 6 * shape - 2) /\n          (shape * (shape - 3) * (shape - 4));\n      }\n      else\n      {\n        result = policies::raise_domain_error<RealType>(\n          function,\n          \"kurtosis_excess is undefined for shape <= 4, but got %1%.\", dist.shape(), Policy());\n      }\n      return result;\n    } // kurtosis_excess\n\n    } // namespace math\n  } // namespace boost\n\n  // This include must be at the end, *after* the accessors\n  // for this distribution have been defined, in order to\n  // keep compilers that support two-phase lookup happy.\n#include <boost/math/distributions/detail/derived_accessors.hpp>\n\n#endif // BOOST_STATS_PARETO_HPP\n\n\n", "meta": {"hexsha": "d568a5af94b28a2bb303fd50124c81c6206caa5e", "size": 15004, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/math/distributions/pareto.hpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2016-04-23T04:55:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-19T10:26:27.000Z", "max_issues_repo_path": "boost/math/distributions/pareto.hpp", "max_issues_repo_name": "mike-code/boost_1_38_0", "max_issues_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-03-31T20:56:08.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-18T08:56:40.000Z", "max_forks_repo_path": "boost/math/distributions/pareto.hpp", "max_forks_repo_name": "mike-code/boost_1_38_0", "max_forks_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T13:16:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T06:13:14.000Z", "avg_line_length": 33.7927927928, "max_line_length": 127, "alphanum_fraction": 0.5943081845, "num_tokens": 3697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.2905029121828688}}
{"text": "/********************************************************************************\n *\n * This file is part of the Geneva library collection. The following license\n * applies to this file:\n *\n * ------------------------------------------------------------------------------\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * ------------------------------------------------------------------------------\n *\n * Note that other files in the Geneva library collection may use a different\n * license. Please see the licensing information in each file.\n *\n ********************************************************************************\n *\n * Geneva was started by Dr. Rüdiger Berlich and was later maintained together\n * with Dr. Ariel Garcia under the auspices of Gemfony scientific. For further\n * information on Gemfony scientific, see http://www.gemfomy.eu .\n *\n * The majority of files in Geneva was released under the Apache license v2.0\n * in February 2020.\n *\n * See the NOTICE file in the top-level directory of the Geneva library\n * collection for a list of contributors and copyright information.\n *\n ********************************************************************************/\n\n#pragma once\n\n// Global checks, defines and includes needed for all of Geneva\n#include \"common/GGlobalDefines.hpp\"\n\n// Standard header files go here\n#include <iostream>\n#include <cmath>\n#include <sstream>\n#include <vector>\n#include <tuple>\n#include <type_traits>\n\n// Boost header files go here\n#include <boost/math/constants/constants.hpp>\n\n// Geneva header files go here\n#include \"common/GParserBuilder.hpp\"\n#include \"common/GCommonMathHelperFunctions.hpp\"\n#include \"hap/GRandomT.hpp\"\n#include \"geneva/GDoubleCollection.hpp\"\n#include \"geneva/GConstrainedDoubleCollection.hpp\"\n#include \"geneva/GDoubleObjectCollection.hpp\"\n#include \"geneva/GConstrainedDoubleObjectCollection.hpp\"\n#include \"geneva/GConstrainedDoubleObject.hpp\"\n#include \"geneva/GDoubleGaussAdaptor.hpp\"\n#include \"geneva/GDoubleBiGaussAdaptor.hpp\"\n#include \"geneva/GParameterSet.hpp\"\n#include \"geneva/GParameterSetMultiConstraint.hpp\"\n#include \"geneva/GParameterSetFactory.hpp\"\n\nnamespace Gem {\nnamespace Geneva {\n\n/******************************************************************************/\n////////////////////////////////////////////////////////////////////////////////\n/******************************************************************************/\n/**\n * This enum denotes the possible demo function types\n */\nenum class solverFunction : Gem::Common::ENUMBASETYPE {\n\t PARABOLA = 0,\n\t NOISYPARABOLA = 1,\n\t ROSENBROCK = 2,\n\t ACKLEY = 3,\n\t RASTRIGIN = 4,\n\t SCHWEFEL = 5,\n\t SALOMON = 6,\n\t NEGPARABOLA = 7\n};\n\nconst solverFunction MAXDEMOFUNCTION = solverFunction::NEGPARABOLA;\n\n// Make sure solverFunction can be streamed\n/** @brief Puts a Gem::Geneva::solverFunction into a stream. Needed also for boost::lexical_cast<> */\nG_API_INDIVIDUALS std::ostream &operator<<(std::ostream &, const Gem::Geneva::solverFunction &);\n\n/** @brief Reads a Gem::Geneva::solverFunction from a stream. Needed also for boost::lexical_cast<> */\nG_API_INDIVIDUALS std::istream &operator>>(std::istream &, Gem::Geneva::solverFunction &);\n\n/**\n * This enum describes different parameter types that may be used to fill the object with data\n */\nenum class parameterType : Gem::Common::ENUMBASETYPE {\n\t USEGDOUBLECOLLECTION = 0,\n\t USEGCONSTRAINEDOUBLECOLLECTION = 1,\n\t USEGDOUBLEOBJECTCOLLECTION = 2,\n\t USEGCONSTRAINEDDOUBLEOBJECTCOLLECTION = 3,\n\t USEGCONSTRAINEDDOUBLEOBJECT = 4\n};\n\n// Make sure parameterType can be streamed\n/** @brief Puts a Gem::Geneva::parameterType into a stream. Needed also for boost::lexical_cast<> */\nG_API_INDIVIDUALS std::ostream &operator<<(std::ostream &, const Gem::Geneva::parameterType &);\n\n/** @brief Reads a Gem::Geneva::parameterType from a stream. Needed also for boost::lexical_cast<> */\nG_API_INDIVIDUALS std::istream &operator>>(std::istream &, Gem::Geneva::parameterType &);\n\n/**\n * This enum describes several ways of initializing the data collections\n */\nenum class initMode : Gem::Common::ENUMBASETYPE {\n\t INITRANDOM = 0 // random values for all variables\n\t , INITPERIMETER = 1 // Uses a parameter set on the perimeter of the allowed or common value range\n};\n\n// Make sure initMode can be streamed\n/** @brief Puts a Gem::Geneva::initMode into a stream. Needed also for boost::lexical_cast<> */\nG_API_INDIVIDUALS std::ostream &operator<<(std::ostream &, const Gem::Geneva::initMode &);\n\n/** @brief Reads a Gem::Geneva::initMode from a stream. Needed also for boost::lexical_cast<> */\nG_API_INDIVIDUALS std::istream &operator>>(std::istream &, Gem::Geneva::initMode &);\n\n/******************************************************************************/\n// A number of default settings for the factory\nconst double GFI_DEF_ADPROB = 1.0;\nconst double GFI_DEF_ADAPTADPROB = 0.1;\nconst double GFI_DEF_MINADPROB = 0.05;\nconst double GFI_DEF_MAXADPROB = 1.;\nconst std::uint32_t GFI_DEF_ADAPTIONTHRESHOLD = 1;\nconst bool GFI_DEF_USEBIGAUSSIAN = false;\nconst double GFI_DEF_SIGMA1 = 0.025;\nconst double GFI_DEF_SIGMASIGMA1 = 0.2;\nconst double GFI_DEF_MINSIGMA1 = 0.001;\nconst double GFI_DEF_MAXSIGMA1 = 1;\nconst double GFI_DEF_SIGMA2 = 0.025;\nconst double GFI_DEF_SIGMASIGMA2 = 0.2;\nconst double GFI_DEF_MINSIGMA2 = 0.001;\nconst double GFI_DEF_MAXSIGMA2 = 1;\nconst double GFI_DEF_DELTA = 0.05;\nconst double GFI_DEF_SIGMADELTA = 0.2;\nconst double GFI_DEF_MINDELTA = 0.001;\nconst double GFI_DEF_MAXDELTA = 1.;\nconst std::size_t GFI_DEF_PARDIM = 2;\nconst double GFI_DEF_MINVAR = -10.;\nconst double GFI_DEF_MAXVAR = 10.;\nconst bool GFI_DEF_USECONSTRAINEDDOUBLECOLLECTION = false;\nconst parameterType GFI_DEF_PARAMETERTYPE = parameterType::USEGCONSTRAINEDDOUBLEOBJECT;\nconst initMode GFI_DEF_INITMODE = initMode::INITPERIMETER;\nconst solverFunction GO_DEF_EVALFUNCTION = solverFunction::PARABOLA;\nconst double GFI_DEF_CROSSOVERPROB = 0.5;\n\n/******************************************************************************/\n// Forward declaraion\nclass GFunctionIndividualFactory;\n\n/******************************************************************************/\n/**\n * This individual searches for a minimum of a number of predefined functions, each capable\n * of processing their input in multiple dimensions.\n */\nclass GFunctionIndividual : public GParameterSet\n{\n\t ///////////////////////////////////////////////////////////////////////\n\t friend class boost::serialization::access;\n\n\t template<class Archive>\n\t void serialize(Archive &ar, const unsigned int) {\n\t\t ar\n\t\t & BOOST_SERIALIZATION_BASE_OBJECT_NVP(GParameterSet)\n\t\t & BOOST_SERIALIZATION_NVP(demoFunction_);\n\t }\n\n\t ///////////////////////////////////////////////////////////////////////\n\npublic:\n\t using FACTORYTYPE = GFunctionIndividualFactory;\n\n\t /** @brief The default constructor */\n\t G_API_INDIVIDUALS GFunctionIndividual() = default;\n\t /** @brief Initialization with the desired demo function */\n\t explicit G_API_INDIVIDUALS GFunctionIndividual(const solverFunction &);\n\t /** @brief A standard copy constructor */\n\t G_API_INDIVIDUALS GFunctionIndividual(const GFunctionIndividual& cp) = default;\n\n\t /** @brief The standard destructor */\n\t G_API_INDIVIDUALS ~GFunctionIndividual() override = default;\n\n\t /** @brief Allows to set the demo function */\n\t G_API_INDIVIDUALS void setDemoFunction(solverFunction);\n\t /** @brief Allows to retrieve the current demo function */\n\t G_API_INDIVIDUALS solverFunction getDemoFunction() const;\n\n\t /** @brief Allows to cross check the parameter size */\n\t G_API_INDIVIDUALS std::size_t getParameterSize() const;\n\n\t //---------------------------------------------------------------------------\n\t /**\n\t  * This function converts the function id to a string representation. This is a convenience\n\t  * function that is mostly used in GArgumentParser.cpp of various Geneva examples.\n\t  *\n\t  * @param df The id of the desired function individual\n\t  * @return A string representing the name of the current function\n\t  */\n\t static G_API_INDIVIDUALS std::string getStringRepresentation(const solverFunction &df) {\n\t\t std::string result;\n\n\t\t // Set up a single function individual, depending on the expected function type\n\t\t switch (df) {\n\t\t\t case solverFunction::PARABOLA:\n\t\t\t\t result = \"Parabola\";\n\t\t\t\t break;\n\t\t\t case solverFunction::NOISYPARABOLA:\n\t\t\t\t result = \"Berlich noisy parabola\";\n\t\t\t\t break;\n\t\t\t case solverFunction::ROSENBROCK:\n\t\t\t\t result = \"Rosenbrock\";\n\t\t\t\t break;\n\t\t\t case solverFunction::ACKLEY:\n\t\t\t\t result = \"Ackley\";\n\t\t\t\t break;\n\t\t\t case solverFunction::RASTRIGIN:\n\t\t\t\t result = \"Rastrigin\";\n\t\t\t\t break;\n\t\t\t case solverFunction::SCHWEFEL:\n\t\t\t\t result = \"Schwefel\";\n\t\t\t\t break;\n\t\t\t case solverFunction::SALOMON:\n\t\t\t\t result = \"Salomon\";\n\t\t\t\t break;\n\t\t\t case solverFunction::NEGPARABOLA:\n\t\t\t\t result = \"Negative parabola\";\n\t\t\t\t break;\n\t\t }\n\n\t\t return result;\n\t }\n\n\t //---------------------------------------------------------------------------\n\t /**\n\t  * Retrieves a string in ROOT format (see http://root.cern.ch) of the 2D version of a\n\t  * given function.\n\t  *\n\t  * @param df The id of the desired function individual\n\t  * @return A string suitable for plotting a 2D version of this function with the ROOT analysis framework\n\t  */\n\t static G_API_INDIVIDUALS std::string get2DROOTFunction(const solverFunction &df) {\n\t\t std::string result;\n\n\t\t // Set up a single function individual, depending on the expected function type\n\t\t switch (df) {\n\t\t\t case solverFunction::PARABOLA:\n\t\t\t\t result = \"x^2 + y^2\";\n\t\t\t\t break;\n\t\t\t case solverFunction::NOISYPARABOLA:\n\t\t\t\t result = \"(cos(x^2 + y^2) + 2.) * (x^2 + y^2)\";\n\t\t\t\t break;\n\t\t\t case solverFunction::ROSENBROCK:\n\t\t\t\t result = \"100.*(x^2 - y)^2 + (1 - x)^2\";\n\t\t\t\t break;\n\t\t\t case solverFunction::ACKLEY:\n\t\t\t\t result = \"exp(-0.2)*sqrt(x^2 + y^2) + 3.*(cos(2.*x) + sin(2.*y))\";\n\t\t\t\t break;\n\t\t\t case solverFunction::RASTRIGIN:\n\t\t\t\t result = \"20.+(x^2 - 10.*cos(2*pi*x)) + (y^2 - 10.*cos(2*pi*y))\";\n\t\t\t\t break;\n\t\t\t case solverFunction::SCHWEFEL:\n\t\t\t\t result = \"-0.5*(x*sin(sqrt(abs(x))) + y*sin(sqrt(abs(y))))\";\n\t\t\t\t break;\n\t\t\t case solverFunction::SALOMON:\n\t\t\t\t result = \"-cos(2.*pi*sqrt(x^2 + y^2)) + 0.1*sqrt(x^2 + y^2) + 1.\";\n\t\t\t\t break;\n\t\t\t case solverFunction::NEGPARABOLA:\n\t\t\t\t result = \"-(x^2 + y^2)\";\n\t\t\t\t break;\n\t\t }\n\n\t\t return result;\n\t }\n\n\t //---------------------------------------------------------------------------\n\t /**\n\t  * Retrieves the minimum x-value(s) of a given (2D) demo function\n\t  *\n\t  * @param df The id of the desired function individual\n\t  * @return The x-coordinate(s) of the global optimium in 2D\n\t  */\n\t static G_API_INDIVIDUALS std::vector<double> getXMin(const solverFunction &df) {\n\t\t std::vector<double> result;\n\n\t\t // Set up a single function individual, depending on the expected function type\n\t\t switch (df) {\n\t\t\t case solverFunction::PARABOLA:\n\t\t\t\t result.push_back(0.);\n\t\t\t\t break;\n\t\t\t case solverFunction::NOISYPARABOLA:\n\t\t\t\t result.push_back(0.);\n\t\t\t\t break;\n\t\t\t case solverFunction::ROSENBROCK:\n\t\t\t\t result.push_back(1.);\n\t\t\t\t break;\n\t\t\t case solverFunction::ACKLEY:\n\t\t\t\t // two global optima\n\t\t\t\t result.push_back(-1.5096201);\n\t\t\t\t result.push_back(1.5096201);\n\t\t\t\t break;\n\t\t\t case solverFunction::RASTRIGIN:\n\t\t\t\t result.push_back(0.);\n\t\t\t\t break;\n\t\t\t case solverFunction::SCHWEFEL:\n\t\t\t\t result.push_back(420.968746);\n\t\t\t\t break;\n\t\t\t case solverFunction::SALOMON:\n\t\t\t\t result.push_back(0.);\n\t\t\t\t break;\n\t\t\t case solverFunction::NEGPARABOLA:\n\t\t\t\t result.push_back(0.);\n\t\t\t\t break;\n\t\t }\n\n\t\t return result;\n\t }\n\n\t //---------------------------------------------------------------------------\n\t /**\n\t  * Retrieves the minimum y-value(s) of a given (2D) demo function\n\t  *\n\t  * @param df The id of the desired function individual\n\t  * @return The y-coordinate(s) of the global optimium in 2D\n\t  */\n\t static G_API_INDIVIDUALS std::vector<double> getYMin(const solverFunction &df) {\n\t\t std::vector<double> result;\n\n\t\t // Set up a single function individual, depending on the expected function type\n\t\t switch (df) {\n\t\t\t case solverFunction::PARABOLA:\n\t\t\t\t result.push_back(0.);\n\t\t\t\t break;\n\t\t\t case solverFunction::NOISYPARABOLA:\n\t\t\t\t result.push_back(0.);\n\t\t\t\t break;\n\t\t\t case solverFunction::ROSENBROCK:\n\t\t\t\t result.push_back(1.);\n\t\t\t\t break;\n\t\t\t case solverFunction::ACKLEY:\n\t\t\t\t result.push_back(-0.7548651);\n\t\t\t\t break;\n\t\t\t case solverFunction::RASTRIGIN:\n\t\t\t\t result.push_back(0.);\n\t\t\t\t break;\n\t\t\t case solverFunction::SCHWEFEL:\n\t\t\t\t result.push_back(420.968746);\n\t\t\t\t break;\n\t\t\t case solverFunction::SALOMON:\n\t\t\t\t result.push_back(0.);\n\t\t\t\t break;\n\t\t\t case solverFunction::NEGPARABOLA:\n\t\t\t\t result.push_back(0.);\n\t\t\t\t break;\n\t\t }\n\n\t\t return result;\n\t }\n\nprotected:\n\t //---------------------------------------------------------------------------\n\t /** @brief Adds local configuration options to a GParserBuilder object */\n\t G_API_INDIVIDUALS void addConfigurationOptions_(Gem::Common::GParserBuilder &) override;\n\t /** @brief Loads the data of another GFunctionIndividual */\n\t G_API_INDIVIDUALS void load_(const GObject *) final;\n\n\t/** @brief Allow access to this classes compare_ function */\n\tfriend void Gem::Common::compare_base_t<GFunctionIndividual>(\n\t\tGFunctionIndividual const &\n\t\t, GFunctionIndividual const &\n\t\t, Gem::Common::GToken &\n\t);\n\n\t/** @brief Searches for compliance with expectations with respect to another object of the same type */\n\tG_API_INDIVIDUALS void compare_(\n\t\tconst GObject & // the other object\n\t\t, const Gem::Common::expectation & // the expectation for this object, e.g. equality\n\t\t, const double & // the limit for allowed deviations of floating point types\n\t) const final;\n\n\t /** @brief The actual value calculation takes place here */\n\t G_API_INDIVIDUALS double fitnessCalculation() final;\n\n\t //---------------------------------------------------------------------------\n\n\t /** @brief Applies modifications to this object. */\n\t G_API_INDIVIDUALS bool modify_GUnitTests_() override;\n\t /** @brief Performs self tests that are expected to succeed. */\n\t G_API_INDIVIDUALS void specificTestsNoFailureExpected_GUnitTests_() override;\n\t /** @brief Performs self tests that are expected to fail. */\n\t G_API_INDIVIDUALS void specificTestsFailuresExpected_GUnitTests_() override;\n\nprivate:\n\t //---------------------------------------------------------------------------\n\t /** @brief Creates a deep clone of this object */\n\t G_API_INDIVIDUALS GObject *clone_() const final;\n\n\t //---------------------------------------------------------------------------\n\t // Data\n\n\t solverFunction demoFunction_ = solverFunction::PARABOLA; ///< Specifies which demo function should be used\n};\n\n/******************************************************************************/\n/**\n * Provide an easy way to print the individual's content\n */\nG_API_INDIVIDUALS std::ostream &operator<<(std::ostream &, const Gem::Geneva::GFunctionIndividual &);\n\nG_API_INDIVIDUALS std::ostream &operator<<(std::ostream &, std::shared_ptr <Gem::Geneva::GFunctionIndividual>);\n\n/******************************************************************************/\n////////////////////////////////////////////////////////////////////////////////\n/******************************************************************************/\n/**\n * A factory for GFunctionIndividual objects\n */\nclass GFunctionIndividualFactory\n\t: public GParameterSetFactory\n{\n\t ///////////////////////////////////////////////////////////////////////\n\t friend class boost::serialization::access;\n\n\t template<class Archive>\n\t void serialize(Archive &ar, const unsigned int) {\n\t\t ar\n\t\t & BOOST_SERIALIZATION_BASE_OBJECT_NVP(GParameterSetFactory)\n\t\t & BOOST_SERIALIZATION_NVP(adProb_)\n\t\t & BOOST_SERIALIZATION_NVP(adaptAdProb_)\n\t\t & BOOST_SERIALIZATION_NVP(minAdProb_)\n\t\t & BOOST_SERIALIZATION_NVP(maxAdProb_)\n\t\t & BOOST_SERIALIZATION_NVP(adaptionThreshold_)\n\t\t & BOOST_SERIALIZATION_NVP(useBiGaussian_)\n\t\t & BOOST_SERIALIZATION_NVP(sigma1_)\n\t\t & BOOST_SERIALIZATION_NVP(sigmaSigma1_)\n\t\t & BOOST_SERIALIZATION_NVP(minSigma1_)\n\t\t & BOOST_SERIALIZATION_NVP(maxSigma1_)\n\t\t & BOOST_SERIALIZATION_NVP(sigma2_)\n\t\t & BOOST_SERIALIZATION_NVP(sigmaSigma2_)\n\t\t & BOOST_SERIALIZATION_NVP(minSigma2_)\n\t\t & BOOST_SERIALIZATION_NVP(maxSigma2_)\n\t\t & BOOST_SERIALIZATION_NVP(delta_)\n\t\t & BOOST_SERIALIZATION_NVP(sigmaDelta_)\n\t\t & BOOST_SERIALIZATION_NVP(minDelta_)\n\t\t & BOOST_SERIALIZATION_NVP(maxDelta_)\n\t\t & BOOST_SERIALIZATION_NVP(parDim_)\n\t\t & BOOST_SERIALIZATION_NVP(minVar_)\n\t\t & BOOST_SERIALIZATION_NVP(maxVar_)\n\t\t & BOOST_SERIALIZATION_NVP(pT_)\n\t\t & BOOST_SERIALIZATION_NVP(iM_);\n\t }\n\n\t ///////////////////////////////////////////////////////////////////////\n\npublic:\n\t /** @brief The standard constructor */\n\t explicit G_API_INDIVIDUALS GFunctionIndividualFactory(boost::filesystem::path const&);\n\t /** @brief The copy constructor */\n\t G_API_INDIVIDUALS GFunctionIndividualFactory(const GFunctionIndividualFactory &cp) = default;\n\n\t /** @brief The destructor */\n\t G_API_INDIVIDUALS ~GFunctionIndividualFactory() override = default;\n\n\t //---------------------------------------------------------------------------\n\t // Getters and setters\n\n\t /** @brief Allows to retrieve the adaptionThreshold_ variable */\n\t G_API_INDIVIDUALS std::uint32_t getAdaptionThreshold() const;\n\t /** @brief Set the value of the adaptionThreshold_ variable */\n\t G_API_INDIVIDUALS void setAdaptionThreshold(std::uint32_t adaptionThreshold);\n\n\t /** @brief Allows to retrieve the adProb_ variable */\n\t G_API_INDIVIDUALS double getAdProb() const;\n\t /** @brief Set the value of the adProb_ variable */\n\t G_API_INDIVIDUALS void setAdProb(double adProb);\n\n\t /** @brief Allows to retrieve the iM_ variable */\n\t G_API_INDIVIDUALS initMode getIM() const;\n\t /** @brief Set the value of the iM_ variable */\n\t G_API_INDIVIDUALS void setIM(initMode im);\n\n\t /** @brief Allows to retrieve the parDim_ variable */\n\t G_API_INDIVIDUALS std::size_t getParDim() const;\n\t /** @brief (Re-)Set the dimension of the function */\n\t G_API_INDIVIDUALS void setParDim(std::size_t);\n\n\t /** @brief Allows to retrieve the pT_ variable */\n\t G_API_INDIVIDUALS parameterType getPT() const;\n\t /** @brief Set the value of the pT_ variable */\n\t G_API_INDIVIDUALS void setPT(parameterType pt);\n\n\t /** @brief Allows to retrieve the useBiGaussian_ variable */\n\t G_API_INDIVIDUALS bool getUseBiGaussian() const;\n\t /** @brief Set the value of the useBiGaussian_ variable */\n\t G_API_INDIVIDUALS void setUseBiGaussian(bool useBiGaussian);\n\n\t /** @brief Allows to retrieve the minVar_ variable */\n\t G_API_INDIVIDUALS double getMinVar() const;\n\t /** @brief Allows to retrieve the maxVar_ variable */\n\t G_API_INDIVIDUALS double getMaxVar() const;\n\t /** @brief Extract the minimum and maximum boundaries of the variables */\n\t G_API_INDIVIDUALS std::tuple<double, double> getVarBoundaries() const;\n\t /** @brief Set the minimum and maximum boundaries of the variables */\n\t G_API_INDIVIDUALS void setVarBoundaries(std::tuple<double, double>);\n\n\t /** @brief Allows to retrieve the delta_ variable */\n\t G_API_INDIVIDUALS double getDelta() const;\n\t /** @brief Set the value of the delta_ variable */\n\t G_API_INDIVIDUALS void setDelta(double delta);\n\t /** @brief Allows to retrieve the minDelta_ variable */\n\t G_API_INDIVIDUALS double getMinDelta() const;\n\t /** @brief Allows to retrieve the maxDelta_ variable */\n\t G_API_INDIVIDUALS double getMaxDelta() const;\n\t /** @brief Allows to retrieve the allowed value range of delta */\n\t G_API_INDIVIDUALS std::tuple<double, double> getDeltaRange() const;\n\t /** @brief Allows to set the allowed value range of delta */\n\t G_API_INDIVIDUALS void setDeltaRange(std::tuple<double, double>);\n\n\t /** @brief Allows to retrieve the minSigma1_ variable */\n\t G_API_INDIVIDUALS double getMinSigma1() const;\n\t /** @brief Allows to retrieve the maxSigma1_ variable */\n\t G_API_INDIVIDUALS double getMaxSigma1() const;\n\t /** @brief Allows to retrieve the allowed value range of sigma1_ */\n\t G_API_INDIVIDUALS std::tuple<double, double> getSigma1Range() const;\n\t /** @brief Allows to set the allowed value range of sigma1_ */\n\t G_API_INDIVIDUALS void setSigma1Range(std::tuple<double, double>);\n\n\t /** @brief Allows to retrieve the minSigma2_ variable */\n\t G_API_INDIVIDUALS double getMinSigma2() const;\n\t /** @brief Allows to retrieve the maxSigma2_ variable */\n\t G_API_INDIVIDUALS double getMaxSigma2() const;\n\t /** @brief Allows to retrieve the allowed value range of sigma2_ */\n\t G_API_INDIVIDUALS std::tuple<double, double> getSigma2Range() const;\n\t /** @brief Allows to set the allowed value range of sigma2_ */\n\t G_API_INDIVIDUALS void setSigma2Range(std::tuple<double, double>);\n\n\t /** @brief Allows to retrieve the sigma1_ variable */\n\t G_API_INDIVIDUALS double getSigma1() const;\n\t /** @brief Set the value of the sigma1_ variable */\n\t G_API_INDIVIDUALS void setSigma1(double sigma1);\n\n\t /** @brief Allows to retrieve the sigma2_ variable */\n\t G_API_INDIVIDUALS double getSigma2() const;\n\t /** @brief Set the value of the sigma2_ variable */\n\t G_API_INDIVIDUALS void setSigma2(double sigma2);\n\n\t /** @brief Allows to retrieve the sigmaDelta_ variable */\n\t G_API_INDIVIDUALS double getSigmaDelta() const;\n\t /** @brief Set the value of the sigmaDelta_ variable */\n\t G_API_INDIVIDUALS void setSigmaDelta(double sigmaDelta);\n\n\t /** @brief Allows to retrieve the sigmaSigma1_ variable */\n\t G_API_INDIVIDUALS double getSigmaSigma1() const;\n\t /** @brief Set the value of the sigmaSigma1_ variable */\n\t G_API_INDIVIDUALS void setSigmaSigma1(double sigmaSigma1);\n\n\t /** @brief Allows to retrieve the sigmaSigma2_ variable */\n\t G_API_INDIVIDUALS double getSigmaSigma2() const;\n\t /** @brief Set the value of the sigmaSigma2_ variable */\n\t G_API_INDIVIDUALS void setSigmaSigma2(double sigmaSigma2);\n\n\t /** @brief Allows to retrieve the rate of evolutionary adaption of adProb_ */\n\t G_API_INDIVIDUALS double getAdaptAdProb() const;\n\t /** @brief Allows to specify an adaption factor for adProb_ (or 0, if you do not want this feature) */\n\t G_API_INDIVIDUALS void setAdaptAdProb(double adaptAdProb);\n\n\t /** @brief Allows to retrieve the allowed range for adProb_ variation */\n\t G_API_INDIVIDUALS std::tuple<double, double> getAdProbRange() const;\n\t /** @brief Allows to set the allowed range for adaption probability variation */\n\t G_API_INDIVIDUALS void setAdProbRange(double minAdProb, double maxAdProb);\n\n\t // End of public getters and setters\n\t //--------------------------------------------------------------------------\n\n\t /** @brief Loads the data of another GFunctionIndividualFactory object */\n\t G_API_INDIVIDUALS void load(std::shared_ptr <Gem::Common::GFactoryT<GParameterSet>>) override;\n\t /** @brief Creates a deep clone of this object */\n\t G_API_INDIVIDUALS std::shared_ptr <Gem::Common::GFactoryT<GParameterSet>> clone() const override;\n\nprotected:\n\t /** @brief Allows to describe local configuration options in derived classes */\n\t G_API_INDIVIDUALS void describeLocalOptions_(Gem::Common::GParserBuilder &) override;\n\t /** @brief Allows to act on the configuration options received from the configuration file */\n\t G_API_INDIVIDUALS void postProcess_(std::shared_ptr<GParameterSet> &) override;\n\nprivate:\n     /** @brief Creates individuals of this type */\n     G_API_INDIVIDUALS std::shared_ptr <GParameterSet> getObject_(Gem::Common::GParserBuilder &, const std::size_t &) override;\n\n\t /** @brief Set the value of the minVar_ variable */\n\t void setMinVar(double minVar);\n\n\t /** @brief Set the value of the maxVar_ variable */\n\t void setMaxVar(double maxVar);\n\n\t /** @brief Set the value of the minDelta_ variable */\n\t void setMinDelta(double minDelta);\n\n\t /** @brief Set the value of the maxDelta_ variable */\n\t void setMaxDelta(double maxDelta);\n\n\t /** @brief Set the value of the minSigma1_ variable */\n\t void setMinSigma1(double minSigma1);\n\n\t /** @brief Set the value of the maxSigma1_ variable */\n\t void setMaxSigma1(double maxSigma1);\n\n\t /** @brief Set the value of the minSigma2_ variable */\n\t void setMinSigma2(double minSigma2);\n\n\t /** @brief Set the value of the maxSigma2_ variable */\n\t void setMaxSigma2(double maxSigma2);\n\n\t /** @brief The default constructor; Only needed for (de-)serialization purposes. */\n\t GFunctionIndividualFactory();\n\n\t Gem::Common::GOneTimeRefParameterT<double> adProb_{GFI_DEF_ADPROB};\n\t Gem::Common::GOneTimeRefParameterT<double> adaptAdProb_{GFI_DEF_ADAPTADPROB};\n\t Gem::Common::GOneTimeRefParameterT<double> minAdProb_{GFI_DEF_MINADPROB};\n\t Gem::Common::GOneTimeRefParameterT<double> maxAdProb_{GFI_DEF_MAXADPROB};\n\t Gem::Common::GOneTimeRefParameterT<std::uint32_t> adaptionThreshold_{GFI_DEF_ADAPTIONTHRESHOLD};\n\t Gem::Common::GOneTimeRefParameterT<bool> useBiGaussian_{GFI_DEF_USEBIGAUSSIAN};\n\t Gem::Common::GOneTimeRefParameterT<double> sigma1_{GFI_DEF_SIGMA1};\n\t Gem::Common::GOneTimeRefParameterT<double> sigmaSigma1_{GFI_DEF_SIGMASIGMA1};\n\t Gem::Common::GOneTimeRefParameterT<double> minSigma1_{GFI_DEF_MINSIGMA1};\n\t Gem::Common::GOneTimeRefParameterT<double> maxSigma1_{GFI_DEF_MAXSIGMA1};\n\t Gem::Common::GOneTimeRefParameterT<double> sigma2_{GFI_DEF_SIGMA2};\n\t Gem::Common::GOneTimeRefParameterT<double> sigmaSigma2_{GFI_DEF_SIGMASIGMA2};\n\t Gem::Common::GOneTimeRefParameterT<double> minSigma2_{GFI_DEF_MINSIGMA2};\n\t Gem::Common::GOneTimeRefParameterT<double> maxSigma2_{GFI_DEF_MAXSIGMA2};\n\t Gem::Common::GOneTimeRefParameterT<double> delta_{GFI_DEF_DELTA};\n\t Gem::Common::GOneTimeRefParameterT<double> sigmaDelta_{GFI_DEF_SIGMADELTA};\n\t Gem::Common::GOneTimeRefParameterT<double> minDelta_{GFI_DEF_MINDELTA};\n\t Gem::Common::GOneTimeRefParameterT<double> maxDelta_{GFI_DEF_MAXDELTA};\n\t Gem::Common::GOneTimeRefParameterT<std::size_t> parDim_{GFI_DEF_PARDIM};\n\t Gem::Common::GOneTimeRefParameterT<double> minVar_{GFI_DEF_MINVAR};\n\t Gem::Common::GOneTimeRefParameterT<double> maxVar_{GFI_DEF_MAXVAR};\n\t Gem::Common::GOneTimeRefParameterT<parameterType> pT_{GFI_DEF_PARAMETERTYPE};\n\t Gem::Common::GOneTimeRefParameterT<initMode> iM_{GFI_DEF_INITMODE};\n};\n\n/******************************************************************************/\n////////////////////////////////////////////////////////////////////////////////\n/******************************************************************************/\n/**\n * A simple constraint checker searching for valid solutions that fulfill\n * a given constraint. Here, the sum of all double variables needs to be smaller\n * than a given constant.\n */\nclass GDoubleSumConstraint : public GParameterSetConstraint {\n\t ///////////////////////////////////////////////////////////////////////\n\t friend class boost::serialization::access;\n\n\t template<typename Archive>\n\t void serialize(Archive &ar, const unsigned int) {\n\t\t using boost::serialization::make_nvp;\n\t\t ar\n\t\t & BOOST_SERIALIZATION_BASE_OBJECT_NVP(GParameterSetConstraint)\n\t\t & BOOST_SERIALIZATION_NVP(C_);\n\t }\n\t ///////////////////////////////////////////////////////////////////////\npublic:\n\n\t /** @brief The default constructor */\n\t G_API_INDIVIDUALS GDoubleSumConstraint() = default;\n\t /** @brief Initialization with the constant */\n\t explicit G_API_INDIVIDUALS GDoubleSumConstraint(const double &);\n\t /** @brief The copy constructor */\n\t G_API_INDIVIDUALS GDoubleSumConstraint(const GDoubleSumConstraint &cp) = default;\n\n\t /** @brief The destructor */\n\t G_API_INDIVIDUALS ~GDoubleSumConstraint() override = default;\n\nprotected:\n\t G_API_INDIVIDUALS double check_(const GParameterSet *) const override;\n\n\t /** @brief Adds local configuration options to a GParserBuilder object */\n\t G_API_INDIVIDUALS void addConfigurationOptions_(Gem::Common::GParserBuilder&) override;\n\t /** @brief Loads the data of another GParameterSetMultiConstraint */\n\t G_API_INDIVIDUALS void load_(const GObject *) override;\n\n\t/** @brief Allow access to this classes compare_ function */\n\tfriend void Gem::Common::compare_base_t<GDoubleSumConstraint>(\n\t\tGDoubleSumConstraint const &\n\t\t, GDoubleSumConstraint const &\n\t\t, Gem::Common::GToken &\n\t);\n\n\t/** @brief Searches for compliance with expectations with respect to another object of the same type */\n\tG_API_INDIVIDUALS void compare_(\n\t\tconst GObject & // the other object\n\t\t, const Gem::Common::expectation & // the expectation for this object, e.g. equality\n\t\t, const double & // the limit for allowed deviations of floating point types\n\t) const final;\n\nprivate:\n\t /** @brief Creates a deep clone of this object */\n\t G_API_INDIVIDUALS GObject *clone_() const override;\n\n\t double C_ = 1.; ///< The constant that should not be exceeded by the sum of parameters\n};\n\n/******************************************************************************/\n////////////////////////////////////////////////////////////////////////////////\n/******************************************************************************/\n/**\n * A constraint checker trying to enforce a condition x+y+z=C (note the equal\n * sign!) for double variables\n */\nclass GDoubleSumGapConstraint : public GParameterSetConstraint {\n\t ///////////////////////////////////////////////////////////////////////\n\t friend class boost::serialization::access;\n\n\t template<typename Archive>\n\t void serialize(Archive &ar, const unsigned int) {\n\t\t using boost::serialization::make_nvp;\n\t\t ar\n\t\t & BOOST_SERIALIZATION_BASE_OBJECT_NVP(GParameterSetConstraint)\n\t\t & BOOST_SERIALIZATION_NVP(C_)\n\t\t & BOOST_SERIALIZATION_NVP(gap_);\n\t }\n\t ///////////////////////////////////////////////////////////////////////\npublic:\n\n\t /** @brief The default constructor */\n\t G_API_INDIVIDUALS GDoubleSumGapConstraint() = default;\n\t /** @brief Initialization with the constant */\n\t G_API_INDIVIDUALS GDoubleSumGapConstraint(const double &, const double &);\n\t /** @brief The copy constructor */\n\t G_API_INDIVIDUALS GDoubleSumGapConstraint(const GDoubleSumGapConstraint& cp) = default;\n\n\t /** @brief The destructor */\n\t G_API_INDIVIDUALS ~GDoubleSumGapConstraint() override = default;\n\nprotected:\n\t G_API_INDIVIDUALS double check_(const GParameterSet *) const override;\n\n\t /** @brief Adds local configuration options to a GParserBuilder object */\n\t G_API_INDIVIDUALS void addConfigurationOptions_(Gem::Common::GParserBuilder &) override;\n\t /** @brief Loads the data of another GParameterSetMultiConstraint */\n\t G_API_INDIVIDUALS void load_(const GObject *) override;\n\n\t/** @brief Allow access to this classes compare_ function */\n\tfriend void Gem::Common::compare_base_t<GDoubleSumGapConstraint>(\n\t\tGDoubleSumGapConstraint const &\n\t\t, GDoubleSumGapConstraint const &\n\t\t, Gem::Common::GToken &\n\t);\n\n\t/** @brief Searches for compliance with expectations with respect to another object of the same type */\n\tG_API_INDIVIDUALS void compare_(\n\t\tconst GObject & // the other object\n\t\t, const Gem::Common::expectation & // the expectation for this object, e.g. equality\n\t\t, const double & // the limit for allowed deviations of floating point types\n\t) const final;\n\nprivate:\n\t /** @brief Creates a deep clone of this object */\n\t G_API_INDIVIDUALS GObject *clone_() const override;\n\n\t double C_ = 1.; ///< The constant that should not be exceeded by the sum of parameters\n\t double gap_ = 0.5; ///< A tolerance around C_ that is still considered to be valid\n};\n\n/******************************************************************************/\n////////////////////////////////////////////////////////////////////////////////\n/******************************************************************************/\n/**\n * A simple constraint checker searching for valid solutions that fulfill\n * a given constraint. Here, valid solutions lie in a sphere around 0\n */\nclass GSphereConstraint : public GParameterSetConstraint {\n\t ///////////////////////////////////////////////////////////////////////\n\t friend class boost::serialization::access;\n\n\t template<typename Archive>\n\t void serialize(Archive &ar, const unsigned int) {\n\t\t using boost::serialization::make_nvp;\n\t\t ar\n\t\t &BOOST_SERIALIZATION_BASE_OBJECT_NVP(GParameterSetConstraint);\n\t }\n\t ///////////////////////////////////////////////////////////////////////\npublic:\n\n\t /** @brief The default constructor */\n\t G_API_INDIVIDUALS GSphereConstraint() = default;\n\t /** @brief Initialization with the diameter */\n\t explicit G_API_INDIVIDUALS GSphereConstraint(const double &cp);\n\t /** @brief The copy constructor */\n\t G_API_INDIVIDUALS GSphereConstraint(const GSphereConstraint &) = default;\n\n\t /** @brief The destructor */\n\t G_API_INDIVIDUALS ~GSphereConstraint() override = default;\n\nprotected:\n\t G_API_INDIVIDUALS double check_(const GParameterSet *) const override;\n\n\t /** @brief Adds local configuration options to a GParserBuilder object */\n\t G_API_INDIVIDUALS void addConfigurationOptions_(Gem::Common::GParserBuilder &) override;\n\t /** @brief Loads the data of another GParameterSetMultiConstraint */\n\t G_API_INDIVIDUALS void load_(const GObject *) override;\n\n\t/** @brief Allow access to this classes compare_ function */\n\tfriend void Gem::Common::compare_base_t<GSphereConstraint>(\n\t\tGSphereConstraint const &\n\t\t, GSphereConstraint const &\n\t\t, Gem::Common::GToken &\n\t);\n\n\t/** @brief Searches for compliance with expectations with respect to another object of the same type */\n\tG_API_INDIVIDUALS void compare_(\n\t\tconst GObject & // the other object\n\t\t, const Gem::Common::expectation & // the expectation for this object, e.g. equality\n\t\t, const double & // the limit for allowed deviations of floating point types\n\t) const final;\n\nprivate:\n\t /** @brief Creates a deep clone of this object */\n\t G_API_INDIVIDUALS GObject *clone_() const override;\n\n\t /** @brief The diameter of the sphere */\n\t double diameter_ = 1.;\n};\n\n/******************************************************************************/\n////////////////////////////////////////////////////////////////////////////////\n/******************************************************************************/\n} /* namespace Geneva */\n} /* namespace Gem */\n\nBOOST_CLASS_EXPORT_KEY(Gem::Geneva::GFunctionIndividual)\nBOOST_CLASS_EXPORT_KEY(Gem::Geneva::GFunctionIndividualFactory)\nBOOST_CLASS_EXPORT_KEY(Gem::Geneva::GDoubleSumConstraint)\nBOOST_CLASS_EXPORT_KEY(Gem::Geneva::GDoubleSumGapConstraint)\nBOOST_CLASS_EXPORT_KEY(Gem::Geneva::GSphereConstraint)\n\n", "meta": {"hexsha": "829e7863c5fb2bed5f2b87d1b7d116aa058befc8", "size": 34505, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/geneva-individuals/GFunctionIndividual.hpp", "max_stars_repo_name": "madmongo1/geneva", "max_stars_repo_head_hexsha": "15f1046ce578cb83f3ed5c2b3ae9f52f7cf4934f", "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": "include/geneva-individuals/GFunctionIndividual.hpp", "max_issues_repo_name": "madmongo1/geneva", "max_issues_repo_head_hexsha": "15f1046ce578cb83f3ed5c2b3ae9f52f7cf4934f", "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": "include/geneva-individuals/GFunctionIndividual.hpp", "max_forks_repo_name": "madmongo1/geneva", "max_forks_repo_head_hexsha": "15f1046ce578cb83f3ed5c2b3ae9f52f7cf4934f", "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": 40.6898584906, "max_line_length": 127, "alphanum_fraction": 0.6652948848, "num_tokens": 8151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.2905029121828687}}
{"text": "// g2o - General Graph Optimization\n// Copyright (C) 2011 R. Kuemmerle, G. Grisetti, H. Strasdat, 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 <signal.h>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <fstream>\n#include <sstream>\n#include <algorithm>\n#include <cassert>\n#include <sstream>\n#include \"g2o/apps/g2o_cli/dl_wrapper.h\"\n#include \"g2o/apps/g2o_cli/output_helper.h\"\n#include \"g2o/apps/g2o_cli/g2o_common.h\"\n\n#include \"g2o/core/estimate_propagator.h\"\n#include \"g2o/core/sparse_optimizer.h\"\n#include \"g2o/core/factory.h\"\n#include \"g2o/core/optimization_algorithm_factory.h\"\n#include \"g2o/core/hyper_dijkstra.h\"\n\n#include \"g2o/stuff/macros.h\"\n#include \"g2o/stuff/color_macros.h\"\n#include \"g2o/stuff/command_args.h\"\n#include \"g2o/stuff/filesys_tools.h\"\n#include \"g2o/stuff/string_tools.h\"\n#include \"g2o/stuff/timeutil.h\"\n\n#include \"edge_labeler.h\"\n#include \"edge_creator.h\"\n#include \"star.h\"\n\n#include \"g2o/stuff/unscented.h\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n\nusing namespace std;\nusing namespace g2o;\nusing namespace Eigen;\n\ntypedef SigmaPoint<VectorXd> MySigmaPoint;\n\nvoid testMarginals(SparseOptimizer& optimizer){\n  cerr << \"Projecting marginals\" << endl;\n  std::vector<std::pair<int, int> > blockIndices;\n  for (size_t i=0; i<optimizer.activeVertices().size(); i++) {\n    OptimizableGraph::Vertex* v=optimizer.activeVertices()[i];\n    if (v->hessianIndex()>=0){\n      blockIndices.push_back(make_pair(v->hessianIndex(), v->hessianIndex()));\n    }\n    // if (v->hessianIndex()>0){\n    //   blockIndices.push_back(make_pair(v->hessianIndex()-1, v->hessianIndex()));\n    // }\n  }\n  SparseBlockMatrix<MatrixXd> spinv;\n  if (optimizer.computeMarginals(spinv, blockIndices)) {\n    for (size_t i=0; i<optimizer.activeVertices().size(); i++) {\n      OptimizableGraph::Vertex* v=optimizer.activeVertices()[i];\n      cerr << \"Vertex id:\" << v->id() << endl;\n      if (v->hessianIndex()>=0){\n        cerr << \"increments block :\" << v->hessianIndex() << \", \" << v->hessianIndex()<< \" covariance:\" <<  endl;\n        VectorXd mean(v->minimalEstimateDimension()); //HACK: need to set identity\n        mean.fill(0);\n        VectorXd oldMean(v->minimalEstimateDimension()); //HACK: need to set identity\n        v->getMinimalEstimateData(&oldMean[0]);\n        MatrixXd& cov= *(spinv.block(v->hessianIndex(), v->hessianIndex()));\n        std::vector<MySigmaPoint, Eigen::aligned_allocator<MySigmaPoint> > spts;\n        cerr << cov << endl;\n        if (! sampleUnscented(spts,mean,cov) )\n          continue;\n\n        // now apply the oplus operator to the sigma points,\n        // and get the points in the global space\n        std::vector<MySigmaPoint, Eigen::aligned_allocator<MySigmaPoint> > tspts = spts;\n\n        for (size_t j=0; j<spts.size(); j++) {\n          v->push();\n          // cerr << \"v_before [\" << j << \"]\" << endl;\n          v->getMinimalEstimateData(&mean[0]);\n          // cerr << mean << endl;\n          // cerr << \"sigma [\" << j << \"]\" << endl;\n          // cerr << spts[j]._sample << endl;\n          v->oplus(&(spts[j]._sample[0]));\n          v->getMinimalEstimateData(&mean[0]);\n          tspts[j]._sample=mean;\n          // cerr << \"oplus [\" << j << \"]\" << endl;\n          // cerr << tspts[j]._sample << endl;\n          v->pop();\n        }\n        MatrixXd cov2=cov;\n        reconstructGaussian(mean, cov2, tspts);\n        cerr << \"global block :\" << v->hessianIndex() << \", \" << v->hessianIndex()<< endl;\n        cerr << \"mean: \" << endl;\n        cerr <<  mean << endl;\n        cerr << \"oldMean: \" << endl;\n        cerr <<  oldMean << endl;\n        cerr << \"cov: \" << endl;\n        cerr << cov2 << endl;\n\n      }\n      // if (v->hessianIndex()>0){\n      //   cerr << \"inv block :\" << v->hessianIndex()-1 << \", \" << v->hessianIndex()<< endl;\n      //   cerr << *(spinv.block(v->hessianIndex()-1, v->hessianIndex()));\n      //   cerr << endl;\n      // }\n    }\n  }\n}\n\nint unscentedTest(){\n  MatrixXd m=MatrixXd(6,6);\n  for (int i=0; i<6; i++){\n    for (int j=i; j<6; j++){\n      m(i,j)=m(j,i)=i*j+1;\n    }\n  }\n  m+=MatrixXd::Identity(6,6);\n  cerr << m;\n  VectorXd mean(6);\n  mean.fill(1);\n\n  std::vector<MySigmaPoint, Eigen::aligned_allocator<MySigmaPoint> > spts;\n  sampleUnscented(spts,mean,m);\n  for (size_t i =0; i<spts.size(); i++){\n    cerr << \"Point \" << i << \" \" << endl << \"wi=\" << spts[i]._wi << \" wp=\" << spts[i]._wp << \" \" << endl;\n    cerr << spts[i]._sample << endl;\n  }\n\n  VectorXd recMean(6);\n  MatrixXd recCov(6,6);\n\n  reconstructGaussian(recMean, recCov, spts);\n\n  cerr << \"recMean\" << endl;\n  cerr << recMean << endl;\n\n  cerr << \"recCov\" << endl;\n  cerr << recCov << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "2121e361bd0c68b53e44a38d7d59034b41937d8d", "size": 5954, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/g2o/g2o/apps/g2o_hierarchical/g2o_hierarchical_test_functions.cpp", "max_stars_repo_name": "xloem/xivo", "max_stars_repo_head_hexsha": "a7dd2553aed28adeee6b6f4c69feb9ba760f12f2", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": 662.0, "max_stars_repo_stars_event_min_datetime": "2019-09-01T02:16:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T19:24:07.000Z", "max_issues_repo_path": "3rdPartLib/g2o/g2o/apps/g2o_hierarchical/g2o_hierarchical_test_functions.cpp", "max_issues_repo_name": "JazzyFeng/FLVIS-gpu", "max_issues_repo_head_hexsha": "74dd8a136d1923592d2ca74d2408cc2c3bbb8c7b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2019-09-05T05:02:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T02:59:49.000Z", "max_forks_repo_path": "3rdPartLib/g2o/g2o/apps/g2o_hierarchical/g2o_hierarchical_test_functions.cpp", "max_forks_repo_name": "JazzyFeng/FLVIS-gpu", "max_forks_repo_head_hexsha": "74dd8a136d1923592d2ca74d2408cc2c3bbb8c7b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 104.0, "max_forks_repo_forks_event_min_datetime": "2019-09-01T07:41:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T16:24:54.000Z", "avg_line_length": 35.6526946108, "max_line_length": 113, "alphanum_fraction": 0.6367148136, "num_tokens": 1621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632683808532, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.290485281869701}}
{"text": "#ifndef SEGMATCH_GRAPH_UTILITIES_HPP_\n#define SEGMATCH_GRAPH_UTILITIES_HPP_\n\n#include <iostream>\n#include <fstream>\n\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/filtered_graph.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <glog/logging.h>\n\nnamespace segmatch {\n\n/// \\brief Provide generic graph utility functions.\nclass GraphUtilities {\n public:\n  /// \\brief Prevent instantiation of static class.\n  GraphUtilities() = delete;\n\n  /// \\brief Writes the specified graph to a .dot file that can be visualized in graphviz\n  /// ( http://www.graphviz.org/ ).\n  /// \\param graph The graph that needs to be saved.\n  /// \\param file_name The destination file.\n  template<typename Graph>\n  static void saveGraphForGraphviz(const Graph& graph, const std::string& file_name) {\n    std::ofstream output_file;\n    output_file.open(file_name);\n    if (output_file.is_open()) {\n      boost::write_graphviz(output_file, graph);\n    } else {\n      LOG(ERROR) << \"Unable to write graph to file: \" << file_name;\n    }\n  }\n\n  /// \\brief Finds the vertices of a graph belonging to the a maximum clique. Only one maximum\n  /// clique is returned.\n  /// Closely follows the exact algorithm described in:\n  /// \"Fast Algorithms for the Maximum Clique Problem on Massive Sparse Graphs\"\n  /// Pattabiraman, Bharath Mostofa Ali Patwary, Md Gebremedhin, Assefaw H Liao, Wei-keng\n  /// Choudhary, Alok ( https://arxiv.org/pdf/1209.5818.pdf )\n  /// The algorithm is modified so that vertices are visited in increasing degeneracy order. This\n  /// limits the search depth to the degeneracy of the graph.\n  /// \\param graph The input graph. The graph must be indirected and the underlying data structure\n  /// must support random access.\n  /// \\param min_clique_size The minimum size of the maximum clique, smaller cliques will be\n  /// ignored. Must be greater or equal 2.\n  /// \\returns Vector containing the vertices belonging to a maximum clique. If the vector is\n  /// empty, no clique with the specified minimum size exists.\n  template<typename Graph>\n  static std::vector<typename boost::graph_traits<Graph>::vertex_descriptor> findMaximumClique(\n      const Graph& graph, const size_t min_clique_size) {\n    // Ensure that the graph type is supported and define type shortcuts.\n    CHECK(min_clique_size >= 2);\n    assertIsUndirectedAndRandomAccessGraph(graph);\n    typedef boost::graph_traits<Graph> GraphTraits;\n    typedef typename GraphTraits::vertex_descriptor Vertex;\n\n    const size_t n_vertices = boost::num_vertices(graph);\n    std::vector<Vertex> neighbors;\n    neighbors.reserve(n_vertices);\n\n    std::vector<Vertex> maximum_clique_tmp;\n    std::vector<Vertex> maximum_clique;\n    maximum_clique_tmp.reserve(n_vertices);\n    size_t max_found_size = min_clique_size - 1u;\n\n    // Use bin-sort to sort the vertex indices in increasing degree order.\n    std::vector<size_t> bin_starts;\n    std::vector<Vertex> sorted_vertices;\n    std::vector<size_t> vertex_positions;\n    std::vector<size_t> vertex_degrees;\n    binSortVerticesByDegree(graph, bin_starts, sorted_vertices, vertex_positions, vertex_degrees);\n\n    // Try to find a clique starting from each vertex.\n    for (size_t i = 0u; i < sorted_vertices.size(); ++i) {\n      const Vertex vertex = sorted_vertices[i];\n      const size_t vertex_degree = vertex_degrees[vertex];\n\n      // Skip the vertex if it doesn't have enough neighbors to be a maximum clique.\n      if (vertex_degree >= max_found_size) {\n        neighbors.clear();\n\n        // Collect all the neighbors that have enough neighbors to be a maximum clique.\n        typename GraphTraits::out_edge_iterator e_it, e_end;\n        for (boost::tie(e_it, e_end) = boost::out_edges(vertex, graph); e_it != e_end; ++e_it) {\n          const Vertex neighbor = boost::target(*e_it, graph);\n          if(vertex_positions[neighbor] > vertex_positions[vertex] &&\n              vertex_degrees[neighbor] >= max_found_size)\n            neighbors.push_back(neighbor);\n        }\n\n        // Get the size of the maximum clique contained in the subgraph defined by the current vertex\n        // and its neighbors.\n        const size_t new_found_size = findMaximumCliqueSubset(graph, neighbors, vertex_degrees, 1u,\n                                                              max_found_size, maximum_clique_tmp);\n\n        // If a bigger clique is found, set it as the new maximum clique.\n        if(new_found_size > max_found_size) {\n          max_found_size = new_found_size;\n          maximum_clique_tmp.push_back(vertex);\n          maximum_clique = std::move(maximum_clique_tmp);\n        } else {\n          maximum_clique_tmp.clear();\n        }\n      }\n\n      // Decrease the degree of neighbor vertices of higher degree. This is equivalent to removing\n      // this vertex and the incident edges.\n      typename GraphTraits::out_edge_iterator e_it, e_end;\n      for (boost::tie(e_it, e_end) = boost::out_edges(sorted_vertices[i], graph);\n           e_it != e_end; ++e_it) {\n        const Vertex neighbor = boost::target(*e_it, graph);\n        const size_t neighbor_degree = vertex_degrees[neighbor];\n        if (neighbor_degree > vertex_degree) {\n          const size_t neighbor_position = vertex_positions[neighbor];\n          const size_t swapped_neighbor_position = bin_starts[neighbor_degree];\n          const Vertex swapped_neighbor = sorted_vertices[swapped_neighbor_position];\n          if (neighbor != swapped_neighbor) {\n            vertex_positions[neighbor] = swapped_neighbor_position;\n            vertex_positions[swapped_neighbor] = neighbor_position;\n            sorted_vertices[neighbor_position] = swapped_neighbor;\n            sorted_vertices[swapped_neighbor_position] = neighbor;\n          }\n          ++bin_starts[neighbor_degree];\n          --vertex_degrees[neighbor];\n        }\n      }\n    }\n\n    return maximum_clique;\n  }\n\n  /// \\brief Finds the vertex degrees and the maximum vertex degree in the graph.\n  /// \\param graph The input graph. The graph must be indirected and the underlying data structure\n  /// must support random access.\n  /// \\param vertex_degrees Vector in which the vertex degrees will be stored.\n  /// \\returns Maximum vertex degree in the graph.\n  template<typename Graph>\n  static size_t getVertexDegreesAndGraphMaxDegree(const Graph& graph,\n                                                  std::vector<size_t>& vertex_degrees) {\n    // Ensure that the graph type is supported and define type shortcuts.\n    assertIsUndirectedAndRandomAccessGraph(graph);\n\n    // Get and store the vertex degrees.\n    vertex_degrees.clear();\n    vertex_degrees.resize(num_vertices(graph));\n    size_t maximum_degree = 0u;\n    typename boost::graph_traits<Graph>::vertex_iterator v_it, v_end;\n    for (boost::tie(v_it, v_end) = boost::vertices(graph); v_it != v_end; ++v_it) {\n      vertex_degrees[*v_it] = boost::out_degree(*v_it, graph);\n      maximum_degree = std::max(maximum_degree, vertex_degrees[*v_it]);\n    }\n    return maximum_degree;\n  }\n\n private:\n  // Statically verify that a graph is undirected and based on data structures that allow random\n  // access.\n  template<typename Graph>\n  static void assertIsUndirectedAndRandomAccessGraph(const Graph& graph) {\n    BOOST_CONCEPT_ASSERT((boost::concepts::GraphConcept<Graph>));\n    typedef boost::graph_traits<Graph> GraphTraits;\n    typedef typename GraphTraits::vertex_descriptor Vertex;\n    static_assert(std::is_same<typename GraphTraits::directed_category,\n                               boost::undirected_tag>::value,\n                  \"GraphUtilities::findMaximumKCore only supports undirected graphs\");\n    static_assert(std::is_same<Vertex, size_t>::value,\n                  \"GraphUtilities::findMaximumKCore only supports graphs with vertex descriptors \"\n                  \"of type size_t (usually graphs based on random access containers).\");\n  }\n\n  // Sort the vertices of a graph in increasing vertex degree order using bin-sorting.\n  template<typename Graph>\n  static size_t binSortVerticesByDegree(\n      const Graph& graph, std::vector<size_t>& bin_starts,\n      std::vector<typename boost::graph_traits<Graph>::vertex_descriptor>& sorted_vertices,\n      std::vector<size_t>& vertex_positions, std::vector<size_t>& vertex_degrees) {\n\n    // Ensure that the graph type is supported.\n    assertIsUndirectedAndRandomAccessGraph(graph);\n    typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\n\n    // Get and store the vertex degrees.\n    size_t maximum_degree = getVertexDegreesAndGraphMaxDegree(graph, vertex_degrees);\n\n    // Use bin-sort to sort the vertex indices in increasing degree order.\n    // 1) Find the size of each bin.\n    std::vector<size_t> bin_sizes(maximum_degree + 1u);\n    for (const auto degree : vertex_degrees) ++bin_sizes[degree];\n\n    // 2) Find the starting index of each bin.\n    bin_starts.resize(maximum_degree + 1u);\n    size_t next_bin_start = 0u;\n    for (size_t i = 0u; i < bin_sizes.size(); ++i) {\n      bin_starts[i] = next_bin_start;\n      next_bin_start += bin_sizes[i];\n    }\n\n    // 3) Sort vertex indices\n    std::vector<size_t> bin_offsets(bin_starts);\n    sorted_vertices.resize(boost::num_vertices(graph));\n    vertex_positions.resize(boost::num_vertices(graph));\n    typename boost::graph_traits<Graph>::vertex_iterator v_it, v_end;\n    for (boost::tie(v_it, v_end) = boost::vertices(graph); v_it != v_end; ++v_it) {\n      vertex_positions[*v_it] = bin_offsets[vertex_degrees[*v_it]]++;\n      sorted_vertices[vertex_positions[*v_it]] = *v_it;\n    }\n  }\n\n  // Helper recursive function for the findMaximumClique() function.\n  template<typename Graph>\n  static size_t findMaximumCliqueSubset(\n      const Graph& graph,\n      std::vector<typename boost::graph_traits<Graph>::vertex_descriptor>& subset,\n      const std::vector<size_t>& vertex_degrees,\n      const size_t clique_size, size_t max_found_size,\n      std::vector<typename boost::graph_traits<Graph>::vertex_descriptor>& maximum_clique_tmp) {\n    // Ensure that the graph type is supported and define type shortcuts.\n    assertIsUndirectedAndRandomAccessGraph(graph);\n    typedef boost::graph_traits<Graph> GraphTraits;\n    typedef typename GraphTraits::vertex_descriptor Vertex;\n\n    const size_t n_vertices = boost::num_vertices(graph);\n    std::vector<Vertex> neighbors;\n    neighbors.reserve(n_vertices);\n\n    // Final step of the recursion: if there are no more vertices to process, the search is\n    // complete.\n    if(subset.empty()) {\n      if(clique_size > max_found_size) {\n        maximum_clique_tmp.clear();\n        return clique_size;\n      }\n      return max_found_size;\n    }\n\n    // Process the given subset of vertices.\n    while(!subset.empty()) {\n      // Continue the search only if there are enough remaining candidates.\n      if(clique_size + subset.size() <= max_found_size) break;\n      Vertex vertex = subset.back();\n      subset.pop_back();\n\n      // Collect the vertices that have enough neighbors and are connected to the current vertex.\n      for (const Vertex candidate : subset) {\n        if (vertex_degrees[candidate] >= max_found_size &&\n            boost::edge(vertex, candidate, graph).second)\n            neighbors.push_back(candidate);\n      }\n\n      // Get the size of the maximum clique contained in the subgraph defined by the current vertex\n      // and its neighbors.\n      const size_t new_found_size = findMaximumCliqueSubset(graph, neighbors, vertex_degrees,\n                                                            clique_size + 1u, max_found_size,\n                                                            maximum_clique_tmp);\n\n      // If a bigger clique is found, use the current vertex.\n      if(new_found_size > max_found_size) {\n        max_found_size = new_found_size;\n        maximum_clique_tmp.push_back(vertex);\n      }\n      neighbors.clear();\n    }\n\n    return max_found_size;\n  }\n}; // class GraphUtilities\n\n} // namespace segmatch\n\n#endif // SEGMATCH_GRAPH_UTILITIES_HPP_\n", "meta": {"hexsha": "7194f723ac8ff5e6798fd88c27aecd4b18108c0a", "size": 12021, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "segmatch/include/segmatch/recognizers/graph_utilities.hpp", "max_stars_repo_name": "Oofs/segmap", "max_stars_repo_head_hexsha": "98f1fddc15b863c781b78f59c65487be5e0dc497", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 771.0, "max_stars_repo_stars_event_min_datetime": "2018-04-21T06:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:49:32.000Z", "max_issues_repo_path": "segmatch/include/segmatch/recognizers/graph_utilities.hpp", "max_issues_repo_name": "Oofs/segmap", "max_issues_repo_head_hexsha": "98f1fddc15b863c781b78f59c65487be5e0dc497", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 111.0, "max_issues_repo_issues_event_min_datetime": "2018-04-22T10:11:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T02:16:12.000Z", "max_forks_repo_path": "segmatch/include/segmatch/recognizers/graph_utilities.hpp", "max_forks_repo_name": "Oofs/segmap", "max_forks_repo_head_hexsha": "98f1fddc15b863c781b78f59c65487be5e0dc497", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 287.0, "max_forks_repo_forks_event_min_datetime": "2018-04-21T06:43:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T17:45:05.000Z", "avg_line_length": 44.032967033, "max_line_length": 101, "alphanum_fraction": 0.6933699359, "num_tokens": 2656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.2904324311152723}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\file GaussNewtonSolverBase.cpp\n///\n/// \\author Sean Anderson, ASRL\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n#include <steam/solver/GaussNewtonSolverBase.hpp>\n\n#include <iostream>\n#include <Eigen/Cholesky>\n\n#include <steam/common/Timer.hpp>\n\nnamespace steam {\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Constructor\n//////////////////////////////////////////////////////////////////////////////////////////////\nGaussNewtonSolverBase::GaussNewtonSolverBase(OptimizationProblem* problem) :\n  SolverBase(problem), patternInitialized_(false), factorizedInformationSuccesfully_(false) {\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Query the covariance related to a single state variable\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::MatrixXd GaussNewtonSolverBase::queryCovariance(const steam::StateKey& key) {\n\n  return queryCovariance(key, key);\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Query the covariance relating two state variables\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::MatrixXd GaussNewtonSolverBase::queryCovariance(const steam::StateKey& rowKey,\n                                                       const steam::StateKey& colKey) {\n\n  std::vector<steam::StateKey> rkeys; rkeys.push_back(rowKey);\n  std::vector<steam::StateKey> ckeys; ckeys.push_back(colKey);\n  BlockMatrix m = queryCovarianceBlock(rkeys, ckeys);\n  return m.at(0,0);\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Query a block of covariances\n//////////////////////////////////////////////////////////////////////////////////////////////\nBlockMatrix GaussNewtonSolverBase::queryCovarianceBlock(const std::vector<steam::StateKey>& keys) {\n\n  return queryCovarianceBlock(keys, keys);\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Query a block of covariances\n//////////////////////////////////////////////////////////////////////////////////////////////\nBlockMatrix GaussNewtonSolverBase::queryCovarianceBlock(const std::vector<steam::StateKey>& rowKeys,\n                                                        const std::vector<steam::StateKey>& colKeys) {\n\n  // Check if the Hessian has been factorized (without augmentation, i.e. the Information matrix)\n  if (!factorizedInformationSuccesfully_) {\n    throw std::runtime_error(\"Cannot query covariance, as the plain approximate Hessian \"\n                             \"was not factorized properly. If using LevMarq, you may \"\n                             \"have to call solveCovariances().\");\n  }\n\n  // Creating indexing\n  BlockMatrixIndexing indexing(this->getStateVector().getStateBlockSizes());\n  const BlockDimIndexing& blkRowIndexing = indexing.rowIndexing();\n  const BlockDimIndexing& blkColIndexing = indexing.colIndexing();\n\n  // Fixed sizes\n  unsigned int numRowKeys = rowKeys.size();\n  unsigned int numColKeys = colKeys.size();\n\n  // Look up block indexes\n  std::vector<unsigned int> blkRowIndices; blkRowIndices.resize(numRowKeys);\n  for (unsigned int i = 0; i < numRowKeys; i++) {\n    blkRowIndices[i] = this->getStateVector().getStateBlockIndex(rowKeys[i]);\n  }\n  std::vector<unsigned int> blkColIndices; blkColIndices.resize(numColKeys);\n  for (unsigned int i = 0; i < numColKeys; i++) {\n    blkColIndices[i] = this->getStateVector().getStateBlockIndex(colKeys[i]);\n  }\n\n  // Look up block size of state variables\n  std::vector<unsigned int> blkRowSizes; blkRowSizes.resize(numRowKeys);\n  for (unsigned int i = 0; i < numRowKeys; i++) {\n    blkRowSizes[i] = blkRowIndexing.blkSizeAt(blkRowIndices[i]);\n  }\n  std::vector<unsigned int> blkColSizes; blkColSizes.resize(numColKeys);\n  for (unsigned int i = 0; i < numColKeys; i++) {\n    blkColSizes[i] = blkColIndexing.blkSizeAt(blkColIndices[i]);\n  }\n\n  // Create result container\n  BlockMatrix result(blkRowSizes, blkColSizes);\n\n  // For each column key\n  for (unsigned int c = 0; c < numColKeys; c++) {\n\n    // For each scalar column\n    Eigen::VectorXd projection(blkRowIndexing.scalarSize()); projection.setZero();\n    for (unsigned int j = 0; j < blkColSizes[c]; j++) {\n\n      // Get scalar index\n      unsigned int scalarColIndex = blkColIndexing.cumSumAt(blkColIndices[c]) + j;\n\n      // Solve for scalar column of covariance matrix\n      projection(scalarColIndex) = 1.0;\n      Eigen::VectorXd x = hessianSolver_.solve(projection);\n      projection(scalarColIndex) = 0.0;\n\n      // For each block row\n      for (unsigned int r = 0; r < numRowKeys; r++) {\n\n        // Get scalar index into solution vector\n        unsigned int scalarRowIndex = blkRowIndexing.cumSumAt(blkRowIndices[r]);\n\n        // Do the backward pass, using the Cholesky factorization (fast)\n        result.at(r,c).block(0, j, blkRowSizes[r], 1) = x.block(scalarRowIndex, 0, blkRowSizes[r], 1);\n      }\n    }\n  }\n\n  return result;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Build the left-hand and right-hand sides of the Gauss-Newton system of equations\n//////////////////////////////////////////////////////////////////////////////////////////////\nvoid GaussNewtonSolverBase::buildGaussNewtonTerms(Eigen::SparseMatrix<double>* approximateHessian,\n                                                  Eigen::VectorXd* gradientVector) {\n  this->getProblem().buildGaussNewtonTerms(this->getStateVector(), approximateHessian, gradientVector);\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Perform the LLT decomposition on the approx. Hessian matrix\n//////////////////////////////////////////////////////////////////////////////////////////////\nvoid GaussNewtonSolverBase::factorizeHessian(const Eigen::SparseMatrix<double>& approximateHessian,\n                                             bool augmentedHessian) {\n\n  // Check if the pattern has been initialized\n  if (!patternInitialized_) {\n\n    // The first time we are solving the problem we need to analyze the sparsity pattern\n    // ** Note we use approximate-minimal-degree (AMD) reordering.\n    //    Also, this step does not actually use the numerical values in gaussNewtonLHS\n    hessianSolver_.analyzePattern(approximateHessian);\n    patternInitialized_ = true;\n  }\n\n  // Perform a Cholesky factorization of the approximate Hessian matrix\n  factorizedInformationSuccesfully_ = false;\n  hessianSolver_.factorize(approximateHessian);\n\n  // Check if the factorization succeeded\n  if (hessianSolver_.info() != Eigen::Success) {\n\n    std::cout << \"Approximate Hessian is: \" << std::endl;\n    std::cout << approximateHessian << std::endl;\n\n    throw decomp_failure(\"During steam solve, Eigen LLT decomposition failed. \"\n                         \"It is possible that the matrix was ill-conditioned, in which case \"\n                         \"adding a prior may help. On the other hand, it is also possible that \"\n                         \"the problem you've constructed is not positive semi-definite.\");\n  } else {\n\n    // Information matrix was solved successfully, if the hessian was not augmented\n    factorizedInformationSuccesfully_ = !augmentedHessian;\n  }\n\n  // todo - it would be nice to check the condition number (not just the determinant) of the\n  // solved system... need to find a fast way to do this\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Solve the Gauss-Newton system of equations: A*x = b\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::VectorXd GaussNewtonSolverBase::solveGaussNewton(const Eigen::SparseMatrix<double>& approximateHessian,\n                                                        const Eigen::VectorXd& gradientVector,\n                                                        bool augmentedHessian) {\n\n  // Perform a Cholesky factorization of the approximate Hessian matrix\n  this->factorizeHessian(approximateHessian, augmentedHessian);\n\n  // Do the backward pass, using the Cholesky factorization (fast)\n  return hessianSolver_.solve(gradientVector);\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Find the Cauchy point (used for the Dogleg method).\n///        The cauchy point is the optimal step length in the gradient descent direction.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::VectorXd GaussNewtonSolverBase::getCauchyPoint(const Eigen::SparseMatrix<double>& approximateHessian,\n                                                      const Eigen::VectorXd& gradientVector) {\n  double num = gradientVector.squaredNorm();\n  double den = gradientVector.transpose() *\n               (approximateHessian.selfadjointView<Eigen::Upper>() * gradientVector);\n  return (num/den)*gradientVector;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Get the predicted cost reduction based on the proposed step\n//////////////////////////////////////////////////////////////////////////////////////////////\ndouble GaussNewtonSolverBase::predictedReduction(const Eigen::SparseMatrix<double>& approximateHessian,\n                                                 const Eigen::VectorXd& gradientVector,\n                                                 const Eigen::VectorXd& step) {\n  // grad^T * step - 0.5 * step^T * Hessian * step\n  double gradTransStep = gradientVector.transpose() * step;\n  double stepTransHessianStep = step.transpose()\n                                * (approximateHessian.selfadjointView<Eigen::Upper>() * step);\n  return gradTransStep - 0.5 * stepTransHessianStep;\n}\n\n} // steam\n\n", "meta": {"hexsha": "b093e5270e622662683ddb01f40a7d386c5fa028", "size": 10159, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solver/GaussNewtonSolverBase.cpp", "max_stars_repo_name": "neophack/steam", "max_stars_repo_head_hexsha": "28f0637e3ae4ff2c21ad12b2331c535e9873c997", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2019-10-17T01:37:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T03:55:47.000Z", "max_issues_repo_path": "src/solver/GaussNewtonSolverBase.cpp", "max_issues_repo_name": "neophack/steam", "max_issues_repo_head_hexsha": "28f0637e3ae4ff2c21ad12b2331c535e9873c997", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-12-21T21:25:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-01T23:08:57.000Z", "max_forks_repo_path": "src/solver/GaussNewtonSolverBase.cpp", "max_forks_repo_name": "neophack/steam", "max_forks_repo_head_hexsha": "28f0637e3ae4ff2c21ad12b2331c535e9873c997", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-12-21T21:13:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T23:42:14.000Z", "avg_line_length": 47.2511627907, "max_line_length": 110, "alphanum_fraction": 0.5420809135, "num_tokens": 1951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.2904324311152723}}
{"text": "/*  $Id: triangle.cpp 745 2011-05-16 10:32:25Z anders.e.e.wallin $\n * \n *  Copyright 2010 Anders Wallin (anders.e.e.wallin \"at\" gmail.com)\n *  \n *  This file is part of OpenCAMlib.\n *\n *  OpenCAMlib 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 *  OpenCAMlib 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 OpenCAMlib.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <cassert>\n\n#include <boost/foreach.hpp>\n\n#include \"triangle.h\"\n#include \"point.h\"\n#include \"numeric.h\"\n\nnamespace ocl\n{\n\nTriangle::Triangle() {\n    p[0]=Point(1,0,0);\n    p[1]=Point(0,1,0);\n    p[2]=Point(0,0,1);\n    calcNormal();\n    calcBB();\n}\n\nTriangle::Triangle(Point p1, Point p2, Point p3) {\n    p[0]=p1;\n    p[1]=p2;\n    p[2]=p3;\n    calcNormal();\n    calcBB();\n}\n\nTriangle::Triangle(const Triangle &t) {\n    p[0]=t.p[0];\n    p[1]=t.p[1];\n    p[2]=t.p[2];\n    calcNormal();\n    calcBB();\n}\n \n\n\n\n/// calculate bounding box values\nvoid Triangle::calcBB() {\n    bb.clear();\n    bb.addTriangle( *this );\n}\n\n/// calculate, normalize, and set the Triangle normal\nvoid Triangle::calcNormal() {\n    Point v1=p[0]-p[1];\r\n    Point v2=p[0]-p[2];\n    Point ntemp = v1.cross(v2);  // the normal is in the direction of the cross product between the edge vectors\n    ntemp.normalize(); // FIXME this might fail if norm()==0\n    n = Point(ntemp.x,ntemp.y,ntemp.z);\n}\n\nPoint Triangle::upNormal() const {\n    return (n.z < 0) ? -1.0* n : n; \n}\n\nbool Triangle::zslice_verts(Point& p1, Point& p2, const double zcut) const {\n    if ( (zcut <= this->bb.minpt.z) || ((zcut >= this->bb.maxpt.z)) )\n        return false; // no zslice\n    // find out how many vertices are below zcut\n    std::vector<Point> below;\n    std::vector<Point> above;\n    for (int m=0;m<3;++m) {\n        if ( p[m].z <= zcut )\n            below.push_back(p[m]);\n        else\n            above.push_back(p[m]);\n    }\n    if ( !(below.size() == 1) && !(below.size() == 2) ) {\n        std::cout << \"triangle.cpp: zslice_verts() error while trying to z-slice\\n\";\n        std::cout << \" triangle=\" << *this << \"\\n\";\n        std::cout << \" zcut=\" << zcut << \"\\n\";\n        std::cout << above.size() << \" above points:\\n\";\n        BOOST_FOREACH(Point p, above) {\n            std::cout << \"   \" << p << \"\\n\";\n        }\n        std::cout << below.size() << \" below points:\\n\";\n        BOOST_FOREACH(Point p, below) {\n            std::cout << \"   \" << p << \"\\n\";\n        }\n    }\n    assert( (below.size() == 1) || (below.size() == 2) );\n    \n    if ( below.size() == 2 ) {\n        assert( above.size() == 1 );\n        // find two new intersection points \n        // edge is p1 + t*(p2-p1) = zcut\n        // so t = zcut-p1 / (p2-p1)\n        double t1 = (zcut - above[0].z) / (below[0].z - above[0].z); // div by zero?!\n        double t2 = (zcut - above[0].z) / (below[1].z - above[0].z);\n        p1 = above[0] + t1*(below[0] - above[0]);\n        p2 = above[0] + t2*(below[1] - above[0]);\n        return true;\n    } else if ( below.size() == 1 ) {\n        assert( above.size() == 2 );\n        // find intersection points and add two new triangles\n        // t = (zcut -p1) / (p2-p1)\n        double t1 = (zcut - above[0].z) / (below[0].z - above[0].z); \n        double t2 = (zcut - above[1].z) / (below[0].z - above[1].z);\n        p1 = above[0] + t1*(below[0]-above[0]); \n        p2 = above[1] + t2*(below[0]-above[1]);\n        return true;\n    } else {\n        assert(0);\n        return false;\n    }\n    \n}\n\nvoid Triangle::rotate(double xr, double yr, double zr) {\n    for (int n=0;n<3;++n) {\n        p[n].xRotate(xr);\n        p[n].yRotate(yr);\n        p[n].zRotate(zr);\n    }\n    calcNormal();\n    calcBB();\n}\n\nstd::ostream &operator<<(std::ostream &stream, const Triangle t) {\n  stream <<  \"T: \" << t.p[0] << \" \" << t.p[1] << \" \" << t.p[2] <<  \"n=\" << t.n ;\n  return stream;\n}\n\n}  // end namespace\n// end file triangle.cpp\n", "meta": {"hexsha": "812fd4549b7130854f34ec0ddac0320ab2bc1e43", "size": 4317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "opencamlib-read-only/src/geo/triangle.cpp", "max_stars_repo_name": "play113/swer", "max_stars_repo_head_hexsha": "78764c67885dfacb1fa24e494a20681265f5254c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "opencamlib-read-only/src/geo/triangle.cpp", "max_issues_repo_name": "play113/swer", "max_issues_repo_head_hexsha": "78764c67885dfacb1fa24e494a20681265f5254c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "opencamlib-read-only/src/geo/triangle.cpp", "max_forks_repo_name": "play113/swer", "max_forks_repo_head_hexsha": "78764c67885dfacb1fa24e494a20681265f5254c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-04T13:58:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-04T13:58:00.000Z", "avg_line_length": 29.1689189189, "max_line_length": 112, "alphanum_fraction": 0.5499189252, "num_tokens": 1357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.29043242326880114}}
{"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_LOCAL_OPERATOR_HPP\n#define NETKET_LOCAL_OPERATOR_HPP\n\n#include <mpi.h>\n#include <Eigen/Dense>\n#include <algorithm>\n#include <cassert>\n#include <complex>\n#include <iostream>\n#include <limits>\n#include <map>\n#include <vector>\n\nnamespace netket {\n\n/**\n    Class for local operators acting on a list of sites and for generic local\n    Hilbert spaces.\n*/\n\nclass LocalOperator {\n public:\n  using MatType = std::vector<std::vector<std::complex<double>>>;\n\n private:\n  const Hilbert &hilbert_;\n  MatType mat_;\n\n  std::vector<int> sites_;\n\n  std::map<std::vector<double>, int> invstate_;\n  int localsize_;\n\n  std::vector<std::vector<double>> states_;\n  std::vector<std::vector<int>> connected_;\n\n public:\n  LocalOperator(const Hilbert &hilbert, const MatType &mat,\n                const std::vector<int> &sites)\n      : hilbert_(hilbert), mat_(mat), sites_(sites) {\n    Init();\n  }\n\n  void Init() {\n    if (!hilbert_.IsDiscrete()) {\n      std::cerr << \"Cannot construct operators on infinite local hilbert spaces\"\n                << std::endl;\n      std::abort();\n    }\n\n    if (*std::max_element(sites_.begin(), sites_.end()) >= hilbert_.Size() ||\n        *std::min_element(sites_.begin(), sites_.end()) < 0) {\n      std::cerr << \"Operator acts on an invalid set of sites\" << std::endl;\n      std::abort();\n    }\n\n    auto localstates = hilbert_.LocalStates();\n    localsize_ = localstates.size();\n\n    // Finding the non-zero matrix elements\n    const double epsilon = 1.0e-6;\n\n    connected_.resize(mat_.size());\n\n    if (mat_.size() != std::pow(localsize_, sites_.size())) {\n      std::cerr << \"Matrix size in operator is inconsistent with Hilbert space\"\n                << std::endl;\n      std::abort();\n    }\n\n    for (std::size_t i = 0; i < mat_.size(); i++) {\n      for (std::size_t j = 0; j < mat_[i].size(); j++) {\n        if (mat_.size() != mat_[i].size()) {\n          std::cerr\n              << \"Matrix size in operator is inconsistent with Hilbert space\"\n              << std::endl;\n          std::abort();\n        }\n\n        if (i != j && std::abs(mat_[i][j]) > epsilon) {\n          connected_[i].push_back(j);\n        }\n      }\n    }\n\n    // Construct the mapping\n    // Internal index -> State\n    std::vector<double> st(sites_.size(), 0);\n\n    do {\n      states_.push_back(st);\n    } while (netket::next_variation(st.begin(), st.end(), localsize_ - 1));\n\n    for (std::size_t i = 0; i < states_.size(); i++) {\n      for (std::size_t k = 0; k < states_[i].size(); k++) {\n        states_[i][k] = localstates[states_[i][k]];\n      }\n    }\n\n    // Now construct the inverse mapping\n    // State -> Internal index\n    std::size_t k = 0;\n    for (auto state : states_) {\n      invstate_[state] = k;\n      k++;\n    }\n\n    assert(k == mat_.size());\n  }\n\n  void FindConn(const Eigen::VectorXd &v,\n                std::vector<std::complex<double>> &mel,\n                std::vector<std::vector<int>> &connectors,\n                std::vector<std::vector<double>> &newconfs) const {\n    assert(v.size() == hilbert_.Size());\n\n    connectors.clear();\n    newconfs.clear();\n    mel.resize(0);\n\n    AddConn(v, mel, connectors, newconfs);\n  }\n\n  void AddConn(const Eigen::VectorXd &v, std::vector<std::complex<double>> &mel,\n               std::vector<std::vector<int>> &connectors,\n               std::vector<std::vector<double>> &newconfs) const {\n    if (mel.size() == 0) {\n      connectors.resize(1);\n      newconfs.resize(1);\n      mel.resize(1);\n\n      mel[0] = 0;\n      connectors[0].resize(0);\n      newconfs[0].resize(0);\n    }\n\n    int st1 = StateNumber(v);\n    assert(st1 < int(mat_.size()));\n    assert(st1 < int(connected_.size()));\n\n    mel[0] += (mat_[st1][st1]);\n\n    // off-diagonal part\n    for (auto st2 : connected_[st1]) {\n      connectors.push_back(sites_);\n      assert(st2 < int(states_.size()));\n      newconfs.push_back(states_[st2]);\n      mel.push_back(mat_[st1][st2]);\n    }\n  }\n\n  inline int StateNumber(const Eigen::VectorXd &v) const {\n    std::vector<double> state(sites_.size());\n    for (std::size_t i = 0; i < sites_.size(); i++) {\n      state[i] = v(sites_[i]);\n    }\n    return invstate_.at(state);\n  }\n};\n\n}  // namespace netket\n#endif\n", "meta": {"hexsha": "9cf671578781ccfbd38a9633fcff5d6c9ef8c426", "size": 4808, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NetKet/Hamiltonian/local_operator.hpp", "max_stars_repo_name": "artemborin/netket", "max_stars_repo_head_hexsha": "c7f26d52fdb66d2a8f9f94f2e2cfdc8b4ab41334", "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/Hamiltonian/local_operator.hpp", "max_issues_repo_name": "artemborin/netket", "max_issues_repo_head_hexsha": "c7f26d52fdb66d2a8f9f94f2e2cfdc8b4ab41334", "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/Hamiltonian/local_operator.hpp", "max_forks_repo_name": "artemborin/netket", "max_forks_repo_head_hexsha": "c7f26d52fdb66d2a8f9f94f2e2cfdc8b4ab41334", "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.1638418079, "max_line_length": 80, "alphanum_fraction": 0.599625624, "num_tokens": 1276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2903757976894321}}
{"text": "#include <LRModel.h>\n#include <Utils.h>\n#include <MlUtils.h>\n#include <Eigen/Dense>\n#include <Checksum.h>\n#include <algorithm>\n\nnamespace cirrus {\n\nLRModel::LRModel(uint64_t d) {\n    weights_.resize(d);\n}\n\nLRModel::LRModel(const FEATURE_TYPE* w, uint64_t d) {\n    weights_.resize(d);\n    std::copy(w, w + d, weights_.begin());\n}\n\nuint64_t LRModel::size() const {\n  return weights_.size();\n}\n\n/**\n  * Serialization / deserialization routines\n  */\n\n/** FORMAT\n  * weights\n  */\nstd::unique_ptr<CirrusModel> LRModel::deserialize(void* data, uint64_t size) const {\n    uint64_t d = size / sizeof(FEATURE_TYPE);\n    std::unique_ptr<LRModel> model = std::make_unique<LRModel>(\n            reinterpret_cast<FEATURE_TYPE*>(data), d);\n    return model;\n}\n\nstd::pair<std::unique_ptr<char[]>, uint64_t>\nLRModel::serialize() const {\n    std::pair<std::unique_ptr<char[]>, uint64_t> res;\n    uint64_t size = getSerializedSize();\n    res.first.reset(new char[size]);\n\n    res.second = size;\n    std::memcpy(res.first.get(), weights_.data(), getSerializedSize());\n\n    return res;\n}\n\nvoid LRModel::serializeTo(void* mem) const {\n    std::memcpy(mem, weights_.data(), getSerializedSize());\n}\n\nuint64_t LRModel::getSerializedSize() const {\n    return size() * sizeof(FEATURE_TYPE);\n}\n\nvoid LRModel::loadSerialized(const void* data) {\n    const FEATURE_TYPE* v = reinterpret_cast<const FEATURE_TYPE*>(data);\n    std::copy(v, v + size(), weights_.begin());\n}\n\n/***\n   *\n   */\n\nvoid LRModel::randomize() {\n    for (auto& w : weights_) {\n        w = 0.001 + get_rand_between_0_1();\n    }\n}\n\nstd::unique_ptr<CirrusModel> LRModel::copy() const {\n    std::unique_ptr<LRModel> new_model =\n        std::make_unique<LRModel>(weights_.data(), size());\n    return new_model;\n}\n\nvoid LRModel::sgd_update(double learning_rate,\n        const ModelGradient* gradient) {\n    const LRGradient* grad = dynamic_cast<const LRGradient*>(gradient);\n\n    if (grad == nullptr) {\n        throw std::runtime_error(\"Error in dynamic cast\");\n    }\n\n    for (uint64_t i = 0; i < size(); ++i) {\n       weights_[i] += learning_rate * grad->weights[i];\n    }\n}\n\nstd::unique_ptr<ModelGradient> LRModel::minibatch_grad(\n        const Matrix& dataset,\n        FEATURE_TYPE* labels,\n        uint64_t labels_size,\n        double epsilon) const {\n    auto w = weights_;\n#ifdef DEBUG\n    dataset.check();\n#endif\n\n    if (dataset.cols != size() || labels_size != dataset.rows) {\n      throw std::runtime_error(\"Sizes don't match\");\n    }\n\n    const FEATURE_TYPE* dataset_data = dataset.data.get();\n    // create Matrix for dataset\n    Eigen::Map<Eigen::Matrix<FEATURE_TYPE, Eigen::Dynamic,\n        Eigen::Dynamic, Eigen::RowMajor>>\n          ds(const_cast<FEATURE_TYPE*>(dataset_data), dataset.rows, dataset.cols);\n\n    // create weight vector\n    Eigen::Map<Eigen::Matrix<FEATURE_TYPE, -1, 1>> tmp_weights(w.data(), size());\n\n    // create vector with labels\n    Eigen::Map<Eigen::Matrix<FEATURE_TYPE, -1, 1>> lab(labels, labels_size);\n\n    // apply logistic function to matrix multiplication\n    // between dataset and weights\n    auto part1_1 = (ds * tmp_weights);\n    auto part1 = part1_1.unaryExpr(std::ptr_fun(s_1_float)); // XXX fix this\n\n    Eigen::Map<Eigen::Matrix<FEATURE_TYPE, -1, 1>> lbs(labels, labels_size);\n\n    // compute difference between labels and logistic probability\n    auto part2 = lbs - part1;\n    auto part3 = ds.transpose() * part2;\n    auto part4 = tmp_weights * 2 * epsilon;\n    auto res = part4 + part3;\n\n    std::vector<FEATURE_TYPE> vec_res;\n    vec_res.resize(res.size());\n    Eigen::Matrix<FEATURE_TYPE, -1, 1>::Map(vec_res.data(), res.size()) = res;\n\n    std::unique_ptr<LRGradient> ret = std::make_unique<LRGradient>(vec_res);\n\n#ifdef DEBUG\n    ret->check_values();\n#endif\n\n    return ret;\n}\n\nstd::pair<double, double> LRModel::calc_loss(Dataset& dataset) const {\n  double total_loss = 0;\n  auto w = weights_;\n\n#ifdef DEBUG\n  dataset.check();\n#endif\n\n  const FEATURE_TYPE* ds_data =\n    reinterpret_cast<const FEATURE_TYPE*>(dataset.samples_.data.get());\n\n  Eigen::Map<Eigen::Matrix<FEATURE_TYPE, Eigen::Dynamic,\n    Eigen::Dynamic, Eigen::RowMajor>>\n      ds(const_cast<FEATURE_TYPE*>(ds_data),\n          dataset.samples_.rows, dataset.samples_.cols);\n\n  Eigen::Map<Eigen::Matrix<FEATURE_TYPE, -1, 1>> weights_eig(w.data(), size());\n\n  // count how many samples are wrongly classified\n  uint64_t wrong_count = 0;\n  for (uint64_t i = 0; i < dataset.num_samples(); ++i) {\n    // get labeled class for the ith sample\n    FEATURE_TYPE class_i =\n      reinterpret_cast<const FEATURE_TYPE*>(dataset.labels_.get())[i];\n\n    assert(is_integer(class_i));\n\n    int predicted_class = 0;\n\n    auto r1 = ds.row(i) *  weights_eig;\n    if (s_1((FEATURE_TYPE)r1) > 0.5) {\n      predicted_class = 1;\n    }\n    if (predicted_class != class_i) {\n      wrong_count++;\n    }\n\n    FEATURE_TYPE v1 = log_aux(1 - s_1((FEATURE_TYPE)(ds.row(i) * weights_eig)));\n    FEATURE_TYPE v2 = log_aux(s_1((FEATURE_TYPE)(ds.row(i) *  weights_eig)));\n\n    FEATURE_TYPE value = class_i * v2 + (1 - class_i) * v1;\n\n    // XXX not sure this check is necessary\n    if (value > 0 && value < 1e-6)\n      value = 0;\n\n    if (value > 0) {\n      std::cout << \"ds row: \" << std::endl << ds.row(i) << std::endl;\n      std::cout << \"weights: \" << std::endl << weights_eig << std::endl;\n      std::cout << \"Class: \" << class_i << \" \" << v1 << \" \" << v2\n        << std::endl;\n      throw std::runtime_error(\"Error: logistic loss is > 0\");\n    }\n\n    total_loss -= value;\n  }\n\n  if (total_loss < 0) {\n    throw std::runtime_error(\"total_loss < 0\");\n  }\n\n  FEATURE_TYPE accuracy = (1.0 - (1.0 * wrong_count / dataset.num_samples()));\n  if (std::isnan(total_loss) || std::isinf(total_loss))\n    throw std::runtime_error(\"calc_log_loss generated nan/inf\");\n\n  return std::make_pair(total_loss, accuracy);\n}\n\nuint64_t LRModel::getSerializedGradientSize() const {\n    return size() * sizeof(FEATURE_TYPE);\n}\n\nstd::unique_ptr<ModelGradient> LRModel::loadGradient(void* mem) const {\n    auto grad = std::make_unique<LRGradient>(size());\n\n    for (uint64_t i = 0; i < size(); ++i) {\n        grad->weights[i] = reinterpret_cast<FEATURE_TYPE*>(mem)[i];\n    }\n\n    return grad;\n}\n\nbool LRModel::is_integer(FEATURE_TYPE n) const {\n    return floor(n) == n;\n}\n\ndouble LRModel::checksum() const {\n    return crc32(weights_.data(), weights_.size() * sizeof(FEATURE_TYPE));\n}\n\nvoid LRModel::print() const {\n    std::cout << \"MODEL: \";\n    for (const auto& w : weights_) {\n        std::cout << \" \" << w;\n    }\n    std::cout << std::endl;\n}\n\n} // namespace cirrus\n", "meta": {"hexsha": "775e512c1d56682cc468ae7de8139ad2841bcf96", "size": 6573, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/LRModel.cpp", "max_stars_repo_name": "FTWH/cirrus", "max_stars_repo_head_hexsha": "04c9a370205ff1e53513a9b91736a36dfbbb4745", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 116.0, "max_stars_repo_stars_event_min_datetime": "2018-06-14T22:51:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T16:34:15.000Z", "max_issues_repo_path": "src/LRModel.cpp", "max_issues_repo_name": "FTWH/cirrus", "max_issues_repo_head_hexsha": "04c9a370205ff1e53513a9b91736a36dfbbb4745", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2018-06-09T04:09:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-14T21:40:04.000Z", "max_forks_repo_path": "src/LRModel.cpp", "max_forks_repo_name": "FTWH/cirrus", "max_forks_repo_head_hexsha": "04c9a370205ff1e53513a9b91736a36dfbbb4745", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2018-07-16T00:10:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-16T02:20:49.000Z", "avg_line_length": 27.1611570248, "max_line_length": 84, "alphanum_fraction": 0.6439981743, "num_tokens": 1779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.29037579146964887}}
{"text": "#ifndef HOPS_DIKINELLIPSOIDCALCULATOR_HPP\n#define HOPS_DIKINELLIPSOIDCALCULATOR_HPP\n\n#include <Eigen/Cholesky>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include \"../../FileWriter/CsvWriter.hpp\"\n\nnamespace hops {\n    template<typename MatrixType, typename VectorType>\n    class DikinEllipsoidCalculator {\n    public:\n        DikinEllipsoidCalculator(MatrixType A, VectorType b);\n\n        std::pair<bool, Eigen::Matrix<typename MatrixType::Scalar, Eigen::Dynamic, Eigen::Dynamic>>\n        computeCholeskyFactorOfDikinEllipsoid(const VectorType &x);\n\n        Eigen::Matrix<typename MatrixType::Scalar, Eigen::Dynamic, Eigen::Dynamic>\n        computeDikinEllipsoid(const VectorType &x);\n\n    private:\n        MatrixType A;\n        VectorType b;\n    };\n\n    template<typename MatrixType, typename VectorType>\n    DikinEllipsoidCalculator<MatrixType, VectorType>::DikinEllipsoidCalculator(MatrixType A, VectorType b) :\n            A(std::move(A)), b(std::move(b)) {}\n\n    template<typename MatrixType, typename VectorType>\n    std::pair<bool, Eigen::Matrix<typename MatrixType::Scalar, Eigen::Dynamic, Eigen::Dynamic>>\n    DikinEllipsoidCalculator<MatrixType, VectorType>::computeCholeskyFactorOfDikinEllipsoid(const VectorType &x) {\n        Eigen::Matrix<typename MatrixType::Scalar, Eigen::Dynamic, Eigen::Dynamic> dikinEllipsoid =\n                computeDikinEllipsoid(x);\n\n        Eigen::LLT<Eigen::Matrix<typename MatrixType::Scalar, Eigen::Dynamic, Eigen::Dynamic>> solver(dikinEllipsoid);\n        bool successful = solver.info() == Eigen::Success;\n        return std::make_pair(successful, solver.matrixL());\n    }\n\n    template<typename MatrixType, typename VectorType>\n    Eigen::Matrix<typename MatrixType::Scalar, Eigen::Dynamic, Eigen::Dynamic>\n    DikinEllipsoidCalculator<MatrixType, VectorType>::computeDikinEllipsoid(const VectorType &x) {\n        Eigen::Matrix<typename MatrixType::Scalar, Eigen::Dynamic, 1> inv_slack = (this->b -\n                                                                                   this->A * x).cwiseInverse();\n\n        Eigen::Matrix<typename MatrixType::Scalar, Eigen::Dynamic, Eigen::Dynamic> halfDikin =\n                inv_slack.asDiagonal() * this->A;\n        Eigen::Matrix<typename MatrixType::Scalar, Eigen::Dynamic, Eigen::Dynamic> dikin =\n                halfDikin.transpose() * halfDikin;\n        return dikin;\n    }\n}\n\n#endif //HOPS_DIKINELLIPSOIDCALCULATOR_HPP\n", "meta": {"hexsha": "062e807f95fd8061803d40a2d50b2b4b9184c0fa", "size": 2421, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hops/MarkovChain/Proposal/DikinEllipsoidCalculator.hpp", "max_stars_repo_name": "modsim/hops", "max_stars_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-11-26T05:13:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T02:08:40.000Z", "max_issues_repo_path": "include/hops/MarkovChain/Proposal/DikinEllipsoidCalculator.hpp", "max_issues_repo_name": "modsim/hops", "max_issues_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-20T23:16:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-20T23:16:34.000Z", "max_forks_repo_path": "include/hops/MarkovChain/Proposal/DikinEllipsoidCalculator.hpp", "max_forks_repo_name": "modsim/hops", "max_forks_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.2321428571, "max_line_length": 118, "alphanum_fraction": 0.6873192895, "num_tokens": 579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2903757914696488}}
{"text": "/**\n * Copyright Soramitsu Co., Ltd. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n#include \"utils/amount_utils.hpp\"\n#include <boost/format.hpp>\n\nnamespace shared_model {\n  namespace detail {\n    const boost::multiprecision::uint256_t ten = 10;\n\n    boost::multiprecision::uint256_t increaseValuePrecision(\n        const boost::multiprecision::uint256_t &value, int degree) {\n      return value * pow(ten, degree);\n    }\n\n    /**\n     * Sums up two amounts.\n     * Result is returned\n     * @param a left term\n     * @param b right term\n     */\n    iroha::expected::PolymorphicResult<shared_model::interface::Amount,\n                                       std::string>\n    operator+(const shared_model::interface::Amount &a,\n              const shared_model::interface::Amount &b) {\n      auto max_precision = std::max(a.precision(), b.precision());\n      auto val_a =\n          increaseValuePrecision(a.intValue(), max_precision - a.precision());\n      auto val_b =\n          increaseValuePrecision(b.intValue(), max_precision - b.precision());\n      if (val_a < a.intValue() || val_b < b.intValue() || val_a + val_b < val_a\n          || val_a + val_b < val_b) {\n        return iroha::expected::makeError(std::make_shared<std::string>(\n            (boost::format(\"addition overflows (%s + %s)\") % a.intValue().str()\n             % b.intValue().str())\n                .str()));\n      }\n      std::string val = (val_a + val_b).str();\n      if (max_precision != 0) {\n        val.insert((val.rbegin() + max_precision).base(), '.');\n      }\n      return iroha::expected::makeValue(\n          std::make_shared<shared_model::interface::Amount>(std::move(val)));\n    }\n\n    /**\n     * Subtracts two amounts.\n     * Result is returned\n     * @param a left term\n     * @param b right term\n     */\n    iroha::expected::PolymorphicResult<shared_model::interface::Amount,\n                                       std::string>\n    operator-(const shared_model::interface::Amount &a,\n              const shared_model::interface::Amount &b) {\n      auto max_precision = std::max(a.precision(), b.precision());\n      auto val_a =\n          increaseValuePrecision(a.intValue(), max_precision - a.precision());\n      auto val_b =\n          increaseValuePrecision(b.intValue(), max_precision - b.precision());\n      if (val_a < a.intValue() || val_b < b.intValue()) {\n        return iroha::expected::makeError(\n            std::make_shared<std::string>(\"new precision overflows number\"));\n      }\n      auto diff = val_a - val_b;\n      std::string val = diff.str();\n      if (max_precision != 0 && val.size() > max_precision + 1) {\n        auto ptr = val.rbegin() + max_precision;\n        val.insert(ptr.base(), '.');\n      }\n      return iroha::expected::makeValue(\n          std::make_shared<shared_model::interface::Amount>(std::move(val)));\n    }\n\n    /**\n     * Make amount with bigger precision\n     * Result is returned\n     * @param a amount\n     * @param b right term\n     */\n    iroha::expected::PolymorphicResult<shared_model::interface::Amount,\n                                       std::string>\n    makeAmountWithPrecision(const shared_model::interface::Amount &amount,\n                            const int new_precision) {\n      if (amount.precision() > new_precision) {\n        return iroha::expected::makeError(std::make_shared<std::string>(\n            (boost::format(\"new precision is smaller than current (%d < %d)\")\n             % new_precision % amount.precision())\n                .str()));\n      }\n      auto val_amount = increaseValuePrecision(\n          amount.intValue(), new_precision - amount.precision());\n      if (val_amount < amount.intValue()) {\n        return iroha::expected::makeError(\n            std::make_shared<std::string>(\"operation overflows number\"));\n      }\n      std::string val = val_amount.str();\n      if (new_precision != 0) {\n        val.insert((val.rbegin() + new_precision).base(), '.');\n      }\n      return iroha::expected::makeValue(\n          std::make_shared<shared_model::interface::Amount>(std::move(val)));\n    }\n\n    int compareAmount(const shared_model::interface::Amount &a,\n                      const shared_model::interface::Amount &b) {\n      if (a.precision() == b.precision()) {\n        return (a.intValue() < b.intValue())\n            ? -1\n            : (a.intValue() > b.intValue()) ? 1 : 0;\n      }\n      // when different precisions transform to have the same scale\n      auto max_precision = std::max(a.precision(), b.precision());\n\n      auto val1 =\n          increaseValuePrecision(a.intValue(), max_precision - a.precision());\n      auto val2 =\n          increaseValuePrecision(b.intValue(), max_precision - b.precision());\n      return (val1 < val2) ? -1 : (val1 > val2) ? 1 : 0;\n    }\n  }  // namespace detail\n}  // namespace shared_model\n", "meta": {"hexsha": "7e3256ec07757db870abd647617235459af1de00", "size": 4820, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "shared_model/utils/amount_utils.cpp", "max_stars_repo_name": "truongnmt/iroha", "max_stars_repo_head_hexsha": "e9b969df9a0eb6ce62eae3ab62c5c3f046a5e6e1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-03T02:01:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T02:01:43.000Z", "max_issues_repo_path": "shared_model/utils/amount_utils.cpp", "max_issues_repo_name": "truongnmt/iroha", "max_issues_repo_head_hexsha": "e9b969df9a0eb6ce62eae3ab62c5c3f046a5e6e1", "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": "shared_model/utils/amount_utils.cpp", "max_forks_repo_name": "truongnmt/iroha", "max_forks_repo_head_hexsha": "e9b969df9a0eb6ce62eae3ab62c5c3f046a5e6e1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-03T02:00:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-03T02:00:05.000Z", "avg_line_length": 38.56, "max_line_length": 79, "alphanum_fraction": 0.5852697095, "num_tokens": 1114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2903366676051643}}
{"text": "#include <vector>\n#include <map>\n#include <set>\n#include <algorithm>\n#include <deque>\n#include <queue>\n\n#include <igl/remove_unreferenced.h>\n#include <igl/writeOBJ.h>\n#include <igl/adjacency_list.h>\n#include <igl/cotmatrix.h>\n#include <igl/boundary_loop.h>\n\n#include <Eigen/Eigenvalues> \n#include <Eigen/SPQRSupport>\n#include <Eigen/CholmodSupport>\n\n#include \"PhiEstimate.h\"\n\n#include \"../MeshConnectivity.h\"\n#include \"../CoMISoWrapper.h\"\n#include \"../MeshGeometry.h\"\n#include \"../IntrinsicGeometry.h\"\n#include \"../CommonFunctions.h\"\n#include \"../GurobiMIPWrapper.h\"\n#include \"../EigenNASOQ.h\"\n\nvoid findCuts(const Eigen::MatrixXi &F, std::vector<std::vector<int> > &cuts)\n{\n\tcuts.clear();\n\n\tint nfaces = F.rows();\n\n\tif (nfaces == 0)\n\t\treturn;\n\n\tstd::map<std::pair<int, int>, std::vector<int> > edges;\n\t// build edges\n\n\tfor (int i = 0; i < nfaces; i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tint v0 = F(i, j);\n\t\t\tint v1 = F(i, (j + 1) % 3);\n\t\t\tstd::pair<int, int> e;\n\t\t\te.first = std::min(v0, v1);\n\t\t\te.second = std::max(v0, v1);\n\t\t\tedges[e].push_back(i);\n\t\t}\n\t}\n\n\tint nedges = edges.size();\n\tEigen::MatrixXi edgeVerts(nedges,2);\n\tEigen::MatrixXi edgeFaces(nedges,2);\n\tEigen::MatrixXi faceEdges(nfaces, 3);\n\tstd::set<int> boundaryEdges;\n\tstd::map<std::pair<int, int>, int> edgeidx;\n\tint idx = 0;\n\tfor (auto it : edges)\n\t{\n\t\tedgeidx[it.first] = idx;\n\t\tedgeVerts(idx, 0) = it.first.first;\n\t\tedgeVerts(idx, 1) = it.first.second;\n\t\tedgeFaces(idx, 0) = it.second[0];\n\t\tif (it.second.size() > 1)\n\t\t{\n\t\t\tedgeFaces(idx, 1) = it.second[1];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tedgeFaces(idx, 1) = -1;\n\t\t\tboundaryEdges.insert(idx);\n\t\t}\n\t\tidx++;\n\t}\n\tfor (int i = 0; i < nfaces; i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tint v0 = F(i, j);\n\t\t\tint v1 = F(i, (j + 1) % 3);\n\t\t\tstd::pair<int, int> e;\n\t\t\te.first = std::min(v0, v1);\n\t\t\te.second = std::max(v0, v1);\n\t\t\tfaceEdges(i, j) = edgeidx[e];\n\t\t}\n\t}\n\n\tbool *deleted = new bool[nfaces];\n\tfor (int i = 0; i < nfaces; i++)\n\t\tdeleted[i] = false;\n\n\tstd::set<int> deletededges;\n\n\t// loop over faces\n\tfor (int face = 0; face < nfaces; face++)\n\t{\n\t\t// stop at first undeleted face\n\t\tif (deleted[face])\n\t\t\tcontinue;\n\t\tdeleted[face] = true;\n\t\tstd::deque<int> processEdges;\n\t\tfor (int i = 0; i < 3; i++)\n\t\t{\n\t\t\tint e = faceEdges(face, i);\n\t\t\tif (boundaryEdges.count(e))\n\t\t\t\tcontinue;\n\t\t\tint ndeleted = 0;\n\t\t\tif (deleted[edgeFaces(e, 0)])\n\t\t\t\tndeleted++;\n\t\t\tif (deleted[edgeFaces(e, 1)])\n\t\t\t\tndeleted++;\n\t\t\tif (ndeleted == 1)\n\t\t\t\tprocessEdges.push_back(e);\n\t\t}\n\t\t// delete all faces adjacent to edges with exactly one adjacent face\n\t\twhile (!processEdges.empty())\n\t\t{\n\t\t\tint nexte = processEdges.front();\n\t\t\tprocessEdges.pop_front();\n\t\t\tint todelete = -1;\n\t\t\tif (!deleted[edgeFaces(nexte, 0)])\n\t\t\t\ttodelete = edgeFaces(nexte, 0);\n\t\t\tif (!deleted[edgeFaces(nexte, 1)])\n\t\t\t\ttodelete = edgeFaces(nexte, 1);\n\t\t\tif (todelete != -1)\n\t\t\t{\n\t\t\t\tdeletededges.insert(nexte);\n\t\t\t\tdeleted[todelete] = true;\n\t\t\t\tfor (int i = 0; i < 3; i++)\n\t\t\t\t{\n\t\t\t\t\tint e = faceEdges(todelete, i);\n\t\t\t\t\tif (boundaryEdges.count(e))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tint ndeleted = 0;\n\t\t\t\t\tif (deleted[edgeFaces(e, 0)])\n\t\t\t\t\t\tndeleted++;\n\t\t\t\t\tif (deleted[edgeFaces(e, 1)])\n\t\t\t\t\t\tndeleted++;\n\t\t\t\t\tif (ndeleted == 1)\n\t\t\t\t\t\tprocessEdges.push_back(e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tdelete[] deleted;\n\n\t// accumulated non-deleted edges\n\tstd::vector<int> leftedges;\n\tfor (int i = 0; i < nedges; i++)\n\t{\n\t\tif (!deletededges.count(i))\n\t\t\tleftedges.push_back(i);\n\t}\n\n\tdeletededges.clear();\n\t// prune spines\n\tstd::map<int, std::vector<int> > spinevertedges;\n\tfor (int i : leftedges)\n\t{\n\t\tspinevertedges[edgeVerts(i, 0)].push_back(i);\n\t\tspinevertedges[edgeVerts(i, 1)].push_back(i);\n\t}\n\n\tstd::deque<int> vertsProcess;\n\tstd::map<int, int> spinevertnbs;\n\tfor (auto it : spinevertedges)\n\t{\n\t\tspinevertnbs[it.first] = it.second.size();\n\t\tif (it.second.size() == 1)\n\t\t\tvertsProcess.push_back(it.first);\n\t}\n\twhile (!vertsProcess.empty())\n\t{\n\t\tint vert = vertsProcess.front();\n\t\tvertsProcess.pop_front();\n\t\tfor (int e : spinevertedges[vert])\n\t\t{\n\t\t\tif (!deletededges.count(e))\n\t\t\t{\n\t\t\t\tdeletededges.insert(e);\n\t\t\t\tfor (int j = 0; j < 2; j++)\n\t\t\t\t{\n\t\t\t\t\tspinevertnbs[edgeVerts(e, j)]--;\n\t\t\t\t\tif (spinevertnbs[edgeVerts(e, j)] == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tvertsProcess.push_back(edgeVerts(e, j));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tstd::vector<int> loopedges;\n\tfor (int i : leftedges)\n\t\tif (!deletededges.count(i))\n\t\t\tloopedges.push_back(i);\n\n\tint nloopedges = loopedges.size();\n\tif (nloopedges == 0)\n\t\treturn;\n\n\tstd::map<int, std::vector<int> > loopvertedges;\n\tfor (int e : loopedges)\n\t{\n\t\tloopvertedges[edgeVerts(e, 0)].push_back(e);\n\t\tloopvertedges[edgeVerts(e, 1)].push_back(e);\n\t}\n\n\tstd::set<int> usededges;\n\tfor (int e : loopedges)\n\t{\n\t\t// make a cycle or chain starting from this edge\n\t\twhile (!usededges.count(e))\n\t\t{\n\t\t\tstd::vector<int> cycleverts;\n\t\t\tstd::vector<int> cycleedges;\n\t\t\tcycleverts.push_back(edgeVerts(e, 0));\n\t\t\tcycleverts.push_back(edgeVerts(e, 1));\n\t\t\tcycleedges.push_back(e);\n\n\t\t\tstd::map<int, int> cycleidx;\n\t\t\tcycleidx[cycleverts[0]] = 0;\n\t\t\tcycleidx[cycleverts[1]] = 1;\n\n\t\t\tint curvert = edgeVerts(e, 1);\n\t\t\tint cure = e;\n\t\t\tbool foundcycle = false;\n\t\t\twhile (curvert != -1 && !foundcycle)\n\t\t\t{\n\t\t\t\tint nextvert = -1;\n\t\t\t\tint nexte = -1;\n\t\t\t\tfor (int cande : loopvertedges[curvert])\n\t\t\t\t{\n\t\t\t\t\tif (!usededges.count(cande) && cande != cure)\n\t\t\t\t\t{\n\t\t\t\t\t\tint vidx = 0;\n\t\t\t\t\t\tif (curvert == edgeVerts(cande, vidx))\n\t\t\t\t\t\t\tvidx = 1;\n\t\t\t\t\t\tnextvert = edgeVerts(cande, vidx);\n\t\t\t\t\t\tnexte = cande;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (nextvert != -1)\n\t\t\t\t{\n\t\t\t\t\tauto it = cycleidx.find(nextvert);\n\t\t\t\t\tif (it != cycleidx.end())\n\t\t\t\t\t{\n\t\t\t\t\t\t// we've hit outselves\n\t\t\t\t\t\tstd::vector<int> cut;\n\t\t\t\t\t\tfor (int i = it->second; i < cycleverts.size(); i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcut.push_back(cycleverts[i]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcut.push_back(nextvert);\n\t\t\t\t\t\tcuts.push_back(cut);\n\t\t\t\t\t\tfor (int i = it->second; i < cycleedges.size(); i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tusededges.insert(cycleedges[i]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tusededges.insert(nexte);\n\t\t\t\t\t\tfoundcycle = true;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tcycleidx[nextvert] = cycleverts.size();\n\t\t\t\t\t\tcycleverts.push_back(nextvert);\n\t\t\t\t\t\tcycleedges.push_back(nexte);                        \n\t\t\t\t\t}\n\t\t\t\t}                \n\t\t\t\tcurvert = nextvert;\n\t\t\t\tcure = nexte;\n\t\t\t}\n\t\t\tif (!foundcycle)\n\t\t\t{\n\t\t\t\t// we've hit a dead end. reverse and try the other direction\n\t\t\t\tstd::reverse(cycleverts.begin(), cycleverts.end());\n\t\t\t\tstd::reverse(cycleedges.begin(), cycleedges.end());\n\t\t\t\tcycleidx.clear();\n\t\t\t\tfor (int i = 0; i < cycleverts.size(); i++)\n\t\t\t\t{\n\t\t\t\t\tcycleidx[cycleverts[i]] = i;\n\t\t\t\t}\n\t\t\t\tcurvert = cycleverts.back();\n\t\t\t\tcure = cycleedges.back();\n\t\t\t\twhile (curvert != -1 && !foundcycle)\n\t\t\t\t{\n\t\t\t\t\tint nextvert = -1;\n\t\t\t\t\tint nexte = -1;\n\t\t\t\t\tfor (int cande : loopvertedges[curvert])\n\t\t\t\t\t{\n\t\t\t\t\t\tif (!usededges.count(cande) && cande != cure)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint vidx = 0;\n\t\t\t\t\t\t\tif (curvert == edgeVerts(cande, vidx))\n\t\t\t\t\t\t\t\tvidx = 1;\n\t\t\t\t\t\t\tnextvert = edgeVerts(cande, vidx);\n\t\t\t\t\t\t\tnexte = cande;\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\tif (nextvert != -1)\n\t\t\t\t\t{\n\t\t\t\t\t\tauto it = cycleidx.find(nextvert);\n\t\t\t\t\t\tif (it != cycleidx.end())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// we've hit outselves\n\t\t\t\t\t\t\tstd::vector<int> cut;\n\t\t\t\t\t\t\tfor (int i = it->second; i < cycleverts.size(); i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcut.push_back(cycleverts[i]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcut.push_back(nextvert);\n\t\t\t\t\t\t\tcuts.push_back(cut);\n\t\t\t\t\t\t\tfor (int i = it->second; i < cycleedges.size(); i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tusededges.insert(cycleedges[i]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tusededges.insert(nexte);\n\t\t\t\t\t\t\tfoundcycle = true;\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\tcycleidx[nextvert] = cycleverts.size();\n\t\t\t\t\t\t\tcycleverts.push_back(nextvert);\n\t\t\t\t\t\t\tcycleedges.push_back(nexte);                        \n\t\t\t\t\t\t}\n\t\t\t\t\t}                \n\t\t\t\t\tcurvert = nextvert;\n\t\t\t\t\tcure = nexte;\n\t\t\t\t}\n\t\t\t\tif (!foundcycle)\n\t\t\t\t{\n\t\t\t\t\t// we've found a chain\n\t\t\t\t\tstd::vector<int> cut;\n\t\t\t\t\tfor (int i = 0; i < cycleverts.size(); i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tcut.push_back(cycleverts[i]);\n\t\t\t\t\t}\n\t\t\t\t\tcuts.push_back(cut);\n\t\t\t\t\tfor (int i = 0; i < cycleedges.size(); i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tusededges.insert(cycleedges[i]);\n\t\t\t\t\t}                    \n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nvoid cutMesh(const Eigen::MatrixXi &F,\n\t// list of cuts, each of which is a list (in order) of vertex indices of one cut.\n\t// Cuts can be closed loops (in which case the last vertex index should equal the\n\t// first) or open (in which case the two endpoint vertices should be distinct).\n\t// Multiple cuts can cross but there may be strange behavior if cuts share endpoint\n\t// vertices, or are non-edge-disjoint.\n\tconst std::vector<std::vector<int> > &cuts,\n\t// new vertices and faces\n\t// **DO NOT ALIAS V OR F!**\n\tEigen::MatrixXi &newF\n)\n{\n\tint ncuts = (int)cuts.size();\n\n\t// junction vertices that lie on multiple cuts\n\tstd::set<int> junctions;\n\tstd::set<int> seenverts;\n\tfor (int i = 0; i < ncuts; i++)\n\t{\n\t\tstd::set<int> seenincut;\n\t\tfor (int j = 0; j < cuts[i].size(); j++)\n\t\t{\n\t\t\tif (seenverts.count(cuts[i][j]))\n\t\t\t\tjunctions.insert(cuts[i][j]);\n\t\t\tseenincut.insert(cuts[i][j]);\n\t\t}\n\t\tfor (int v : seenincut)\n\t\t\tseenverts.insert(v);\n\t}\n\n\t// \"interior\" cut vertices: vertices that are part of a cut but not a cut endpoint\n\t// or junction vertex\n\tstd::vector<std::set<int> > cutints;\n\tcutints.resize(ncuts);\n\tfor (int i = 0; i < ncuts; i++)\n\t{\n\t\tif (cuts[i].empty())\n\t\t\tcontinue;\n\t\tif (cuts[i].front() == cuts[i].back())\n\t\t{\n\t\t\t// closed loop\n\t\t\tfor (int v : cuts[i])\n\t\t\t{\n\t\t\t\tif(!junctions.count(v))\n\t\t\t\t\tcutints[i].insert(v);                \n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// open cut\n\t\t\tfor (int j = 1; j < cuts[i].size() - 1; j++)\n\t\t\t{\n\t\t\t\tif(!junctions.count(cuts[i][j]))\n\t\t\t\t\tcutints[i].insert(cuts[i][j]);                \n\t\t\t}\n\t\t}\n\t}\n\n\tstruct edge\n\t{\n\t\tstd::pair<int, int> verts;\n\t\tedge(int v1, int v2)\n\t\t{\n\t\t\tverts.first = std::min(v1, v2);\n\t\t\tverts.second = std::max(v1, v2);\n\t\t}\n\n\t\tbool operator<(const edge &other) const\n\t\t{\n\t\t\treturn verts < other.verts;\n\t\t}\n\t};\n\n\t// maps each edge to incident triangles\n\tstd::map<edge, std::vector<int> > edgeTriangles;\n\tfor (int i = 0; i < F.rows(); i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tedge e(F(i, j), F(i, (j + 1) % 3));\n\t\t\tedgeTriangles[e].push_back(i);\n\t\t}\n\t}\n\n\t// have we visited this face yet?\n\tbool *visited = new bool[F.rows()];\n\n\t// edges that form part of a cut\n\tstd::set<edge> forbidden;\n\tfor (int i = 0; i < ncuts; i++)\n\t{        \n\t\tfor (int j = 0; j < (int)cuts[i].size() - 1; j++)\n\t\t{\n\t\t\t// works for both open and closed curves\n\t\t\tedge e(cuts[i][j], cuts[i][j + 1]);\n\t\t\tforbidden.insert(e);\n\t\t}\n\t}\n\n\t// connected components of faces adjacent to the cuts\n\tstd::vector<std::vector<std::vector<int> > > components;\n\tcomponents.resize(ncuts);\n\n\t// for each cut\n\tfor (int cut = 0; cut < ncuts; cut++)\n\t{\n\t\tfor (int i = 0; i < (int)F.rows(); i++)\n\t\t\tvisited[i] = false;\n\n\t\t// find a face we haven't visited yet\n\t\tfor (int i = 0; i < F.rows(); i++)\n\t\t{\n\t\t\tif (visited[i]) continue;\n\t\t\tbool found = false;\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tif (cutints[cut].count(F(i, j)))\n\t\t\t\t{\n\t\t\t\t\tfound = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (found)\n\t\t\t{\n\t\t\t\t// run a BFS along the cut edges, accumulating one connected component\n\t\t\t\t// cross only edges that contain a vertex in cutints[cut], but are not forbidden\n\t\t\t\tstd::deque<int> q;\n\t\t\t\tstd::vector<int> component;\n\t\t\t\tq.push_back(i);\n\t\t\t\twhile (!q.empty())\n\t\t\t\t{\n\t\t\t\t\tint next = q.front();\n\t\t\t\t\tq.pop_front();\n\t\t\t\t\tif (visited[next])\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tvisited[next] = true;\n\t\t\t\t\tcomponent.push_back(next);\n\t\t\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t\t\t{\n\t\t\t\t\t\tint v1 = F(next, j);\n\t\t\t\t\t\tint v2 = F(next, (j + 1) % 3);\n\t\t\t\t\t\tedge e(v1, v2);\n\t\t\t\t\t\tif (cutints[cut].count(v1) == 0 && cutints[cut].count(v2) == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (forbidden.count(e))\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\tfor (int nb : edgeTriangles[e])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (!visited[nb])\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tq.push_back(nb);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} // end BFS\n\t\t\t\t}\n\t\t\t\tcomponents[cut].push_back(component);\n\t\t\t} // end if found\n\t\t} // end loop over all faces\n\t} // end loop over cuts\n\n\tstd::map<int, std::vector<std::vector<int> > > junctcomponents;\n\n\t// for each junction\n\tfor (int junc : junctions)\n\t{\n\t\tfor (int i = 0; i < (int)F.rows(); i++)\n\t\t\tvisited[i] = false;\n\n\t\t// find a face we haven't visited yet\n\t\tfor (int i = 0; i < F.rows(); i++)\n\t\t{\n\t\t\tif (visited[i]) continue;\n\t\t\tbool found = false;\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tif (junc == F(i, j))\n\t\t\t\t{\n\t\t\t\t\tfound = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (found)\n\t\t\t{\n\t\t\t\t// run a BFS along the cut edges, accumulating one connected component\n\t\t\t\t// cross only edges that contain the junction, but are not forbidden\n\t\t\t\tstd::deque<int> q;\n\t\t\t\tstd::vector<int> component;\n\t\t\t\tq.push_back(i);\n\t\t\t\twhile (!q.empty())\n\t\t\t\t{\n\t\t\t\t\tint next = q.front();\n\t\t\t\t\tq.pop_front();\n\t\t\t\t\tif (visited[next])\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tvisited[next] = true;\n\t\t\t\t\tcomponent.push_back(next);\n\t\t\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t\t\t{\n\t\t\t\t\t\tint v1 = F(next, j);\n\t\t\t\t\t\tint v2 = F(next, (j + 1) % 3);\n\t\t\t\t\t\tedge e(v1, v2);\n\t\t\t\t\t\tif (v1 != junc && v2 != junc)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (forbidden.count(e))\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\tfor (int nb : edgeTriangles[e])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (!visited[nb])\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tq.push_back(nb);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} // end BFS\n\t\t\t\t}\n\t\t\t\tjunctcomponents[junc].push_back(component);\n\t\t\t} // end if found\n\t\t} // end loop over all faces\n\t} // end loop over cuts\n\n\tint vertstoadd = 0;\n\t// create a copy of each vertex for each component of each cut\n\tfor (int i = 0; i < ncuts; i++)\n\t{\n\t\tvertstoadd += components[i].size() * cutints[i].size();\n\t}\n\t// create a copy of each junction point for each component of each junction\n\tfor (int v : junctions)\n\t{\n\t\tvertstoadd += junctcomponents[v].size();\n\t}\n\n\t// create new faces\n\tEigen::MatrixXi augF = F;\n\n\t// duplicate vertices and reindex faces\n\n\tint idx = 0;\n\tfor (int i = 0; i < F.rows(); i++)\n\t\tfor (int j = 0; j < 3; j++)\n\t\t\tidx = std::max(idx, F(i, j));\n\tidx++;\n\n\tfor (int cut = 0; cut < ncuts; cut++)\n\t{\n\t\tfor (int i = 0; i < components[cut].size(); i++)\n\t\t{\n\t\t\t// duplicate vertices\n\t\t\tstd::map<int, int> idxmap;\n\t\t\tfor (int v : cutints[cut])\n\t\t\t{\n\t\t\t\tidxmap[v] = idx;\n\t\t\t\tidx++;\n\t\t\t}\n\t\t\tfor (int f : components[cut][i])\n\t\t\t{\n\t\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t\t{\n\t\t\t\t\tint v = augF(f, j);\n\t\t\t\t\tif (cutints[cut].count(v))\n\t\t\t\t\t\taugF(f, j) = idxmap[v];\n\t\t\t\t}\n\t\t\t}\n\t\t}        \n\t}\n\n\tfor (int junc : junctions)\n\t{\n\t\tfor (int i = 0; i < junctcomponents[junc].size(); i++)\n\t\t{\n\n\t\t\tint newidx = idx;\n\t\t\tidx++;\n\n\t\t\tfor (int f : junctcomponents[junc][i])\n\t\t\t{\n\t\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t\t{\n\t\t\t\t\tint v = augF(f, j);\n\t\t\t\t\tif (v == junc)\n\t\t\t\t\t\taugF(f, j) = newidx;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tnewF = augF;\n\tdelete[] visited;\n}\n\nstatic double angle(const Eigen::Vector3d &v1, const Eigen::Vector3d &v2, const Eigen::Vector3d axis)\n{\n\treturn 2.0 * atan2(v1.cross(v2).dot(axis), v1.norm() * v2.norm() + v1.dot(v2));\n}\n\nvoid vectorFieldSingularities(const Eigen::MatrixXi &F, const std::vector<Eigen::Matrix2d> &abars, const Eigen::MatrixXd &w, std::vector<int> &singularities)\n{\n\tsingularities.clear();\n\tMeshConnectivity mesh(F);\n\tIntrinsicGeometry geom(mesh, abars);\n\t\n\tstd::set<int> checked;\n\n\tint nfaces = F.rows();\n\tfor(int i=0; i<nfaces; i++)\n\t{\n\t\tfor(int j=0; j<3; j++)\n\t\t{\n\t\t\tint centervert = F(i,j);\n\t\t\tif(!checked.count(centervert))\n\t\t\t{\n\t\t\t\tint startface = i;\n\t\t\t\tint startspoke = (j+1)%3;\n\t\t\n\t\t\t\tdouble wangle = 0;\n\n\t\t\t\tint curface = startface;\n\t\t\t\tint curspoke = startspoke;\n\t\t\t\tdouble totangle = 0;\n\n\t\t\t\tbool isboundary = false;\n\n\t\t\t\twhile (true)\n\t\t\t\t{\n\t\t\t\t\tint edge = mesh.faceEdge(curface, curspoke);\n\t\t\t\t\tint side = (mesh.edgeFace(edge, 0) == curface) ? 0 : 1;\n\t\t\t\t\tint nextface = mesh.edgeFace(edge, 1 - side);\n\t\t\t\t\tif (nextface == -1)\n\t\t\t\t\t{\n\t\t\t\t\t\tisboundary = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\n\t\t\t\t\tEigen::Vector2d curw = abars[curface].inverse() * w.row(curface).transpose();\n\t\t\t\t\tEigen::Vector2d nextwbary = abars[nextface].inverse() * w.row(nextface).transpose();\n\t\t\t\t\t\n\t\t\t\t\tEigen::Vector2d nextw = geom.Ts.block<2, 2>(2 * edge, 2 - 2 * side) * nextwbary;\n\t\t\t\t\tEigen::Vector2d nextwperp = geom.Js.block<2, 2>(2 * curface, 0) * nextw;\n\t\t\t\t\tdouble curwnorm = curw.transpose() * abars[curface] * curw;\n\t\t\t\t\tdouble nextwnorm = nextw.transpose() * abars[curface] * nextw;\n\t\t\t\t\tdouble crossprod = (nextwperp.transpose() * abars[curface] * curw);\n\t\t\t\t\tdouble innerprod = (nextw.transpose() * abars[curface] * curw);\n\t\t\t\t\tdouble angleopt = std::atan2(crossprod, innerprod);\n\t\t\t\t\t\n\t\t\t\t\twangle += angleopt;\n\t\t\t\t\t\n\t\t\t\t\tint spokep1 = (curspoke + 1) % 3;\n\t\t\t\t\tint apex = (curspoke + 2) % 3;\n\t\t\t\t\tEigen::Vector2d barys[3] = { {0,0}, {1,0}, {0,1} };\n\t\t\t\t\tEigen::Vector2d edge1 = barys[curspoke] - barys[apex];\n\t\t\t\t\tEigen::Vector2d edge2 = barys[spokep1] - barys[apex];\n\t\t\t\t\tdouble e1norm = std::sqrt(edge1.transpose() * abars[curface] * edge1);\n\t\t\t\t\tdouble e2norm = std::sqrt(edge2.transpose() * abars[curface] * edge2);\n\t\t\t\t\tdouble eprod = edge1.transpose() * abars[curface] * edge2;\n\t\t\t\t\tdouble cose = std::min(std::max(eprod / e1norm / e2norm, -1.0), 1.0);\n\t\t\t\t\ttotangle += std::acos(cose);\n\n\t\t\t\t\tcurface = nextface;\n\t\t\t\t\tfor (int k = 0; k < 3; k++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (F(nextface, k) == centervert)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcurspoke = (k + 1) % 3;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\n\t\t\t\t\tif (curface == startface)\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (!isboundary)\n\t\t\t\t{\n\t\t\t\t\tconst double PI = 3.1415926535898;\n\t\t\t\t\tdouble index = wangle + 2 * PI - totangle;                    \n\t\t\t\t\tif (fabs(index) > PI)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << wangle << \" \" << totangle << std::endl;\n\t\t\t\t\t\tsingularities.push_back(centervert);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tchecked.insert(centervert);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid punctureMesh(const Eigen::MatrixXi &F, const std::vector<int> &singularities, Eigen::MatrixXi &puncturedF, Eigen::VectorXi &newFacesToOld)\n{\n\tstd::vector<int> okfaces;\n\tint nfaces = F.rows();\n\tstd::set<int> singularset;\n\tfor(auto it : singularities)\n\t\tsingularset.insert(it);\n\t\t\n\tfor(int i=0; i<nfaces; i++)\n\t{\n\t\tbool ok = true;\n\t\tfor(int j=0; j<3; j++)\n\t\t{\n\t\t\tif(singularset.count(F(i,j)))\n\t\t\t\tok = false;\n\t\t}\n\t\tif(ok)\n\t\t\tokfaces.push_back(i);\n\t}\n\t\n\tpuncturedF.resize(okfaces.size(), 3);\n\tnewFacesToOld.resize(okfaces.size());\n\tint idx=0;\n\tfor(auto it : okfaces)\n\t{\n\t\tnewFacesToOld[idx] = it;\n\t\tpuncturedF.row(idx) = F.row(it);\n\t\tidx++;\n\t}\n}\n\nvoid punctureMeshUsingPureTension(const Eigen::MatrixXi& F, const std::set<int>& tensionFaces, Eigen::MatrixXi& puncturedF, Eigen::VectorXi& newFacesToOld)\n{\n\tstd::vector<int> okfaces;\n\tint nfaces = F.rows();\n\n\tfor (int i = 0; i < nfaces; i++)\n\t{\n\t\tbool ok = true;\n\t\tif (tensionFaces.count(i))\n\t\t\tok = false;\n\t\tif (ok)\n\t\t\tokfaces.push_back(i);\n\t}\n\n\tpuncturedF.resize(okfaces.size(), 3);\n\tnewFacesToOld.resize(okfaces.size());\n\tint idx = 0;\n\tfor (auto it : okfaces)\n\t{\n\t\tnewFacesToOld[idx] = it;\n\t\tpuncturedF.row(idx) = F.row(it);\n\t\tidx++;\n\t}\n}\n\nstruct UnionFind\n{\n\tstd::vector<int> parent;\n\tstd::vector<int> sign;\n\tUnionFind(int items) \n\t{\n\t\tparent.resize(items);\n\t\tsign.resize(items);\n\t\tfor(int i=0; i<items; i++)\n\t\t{\n\t\t\tparent[i] = i;\n\t\t\tsign[i] = 1;\n\t\t}\n\t}\n\t\t\n\tstd::pair<int, int> find(int i)\n\t{\n\t\tif(parent[i] != i)\n\t\t{\n\t\t\tauto newparent = find(parent[i]);\n\t\t\tsign[i] *= newparent.second;\n\t\t\tparent[i] = newparent.first;\n\t\t}\n\t\t\n\t\treturn {parent[i], sign[i]};\n\t}\n\t\n\tvoid dounion(int i, int j, int usign)\n\t{\n\t\tauto xroot = find(i);\n\t\tauto yroot = find(j);\n\t\tif(xroot.first != yroot.first)\n\t\t{\n\t\t\tparent[xroot.first] = yroot.first;\n\t\t\tsign[xroot.first] = usign * xroot.second * yroot.second;\n\t\t}\n\t}\n};\n\nstatic const double PI = 3.1415926535898;\n\nvoid combField(const Eigen::MatrixXi &F, \n\tconst std::vector<Eigen::Matrix2d> &abars, \n\tconst Eigen::VectorXd* weight,\n\tconst Eigen::MatrixXd &w, Eigen::MatrixXd &combedW)\n{\n\tint nfaces = F.rows();\n\tUnionFind uf(nfaces);\n\tMeshConnectivity mesh(F);\n\tIntrinsicGeometry geom(mesh, abars);\n\tstruct Visit\n\t{\n\t\tint edge;\n\t\tint sign;\n\t\tdouble norm;\n\t\tbool operator<(const Visit &other) const\n\t\t{\n\t\t\treturn norm > other.norm;\n\t\t}\n\t};\n\t\n\tstd::priority_queue<Visit> pq;\n\t\n\tint nedges = mesh.nEdges();\n\tfor(int i=0; i<nedges; i++)\n\t{\n\t\tint face1 = mesh.edgeFace(i, 0);\n\t\tint face2 = mesh.edgeFace(i, 1);\n\t\tif(face1 == -1 || face2 == -1)\n\t\t\tcontinue;\n\t\t\t\n\t\tEigen::Vector2d curw = abars[face1].inverse() * w.row(face1).transpose();\n\t\tEigen::Vector2d nextwbary1 = abars[face2].inverse() * w.row(face2).transpose();                    \n\t\tEigen::Vector2d nextw = geom.Ts.block<2, 2>(2 * i, 2) * nextwbary1;\n\t\tint sign = ( (curw.transpose() * abars[face1] * nextw) < 0 ? -1 : 1);\n\t\tdouble innerp = curw.transpose() * abars[face1] * nextw;\n\n\t\tif (!weight)\n\t\t{\n\t\t\tdouble normcw = std::sqrt(curw.transpose() * abars[face1] * curw);\n\t\t\tdouble normnw = std::sqrt(nextw.transpose() * abars[face1] * nextw);\n\t\t\tdouble negnorm = -std::min(normcw, normnw);\n\t\t\tpq.push({ i, sign, negnorm });\n\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdouble compcw = weight->coeffRef(face1);\n\t\t\tdouble compnw = weight->coeffRef(face2);\n\t\t\tdouble negw = -std::min(compcw, compnw);\n\n\t\t\tpq.push({ i, sign, negw });\n\t\t}\n\n\t\t\n\t}\n\t\n\twhile(!pq.empty())\n\t{\n\t\tauto next = pq.top();\n\t\tpq.pop();\n\t\tuf.dounion(mesh.edgeFace(next.edge, 0), mesh.edgeFace(next.edge, 1), next.sign);\n\t}\n\t\n\tcombedW.resize(nfaces, 2);\n\tfor(int i=0; i<nfaces; i++)\n\t{\n\t\tint sign = uf.find(i).second;\n\t\tcombedW.row(i) = w.row(i) * sign;\n\t}\n\n}\n\nvoid combFieldCutbyTension(const Eigen::MatrixXi& F,\n\tconst std::vector<Eigen::Matrix2d>& abars,\n\tconst std::set<int> tensionFaces,\n\tconst Eigen::MatrixXd& w, Eigen::MatrixXd& combedW)\n{\n\tEigen::MatrixXi puncturedF;\n\tEigen::VectorXi newFacesToOld;\n\tpunctureMeshUsingPureTension(F, tensionFaces, puncturedF, newFacesToOld);\n\n\tMeshConnectivity puncturedMesh(puncturedF);\n\tint nPuncturedFaces = puncturedMesh.nFaces();\n\tEigen::MatrixXd puncturedW(nPuncturedFaces, 2);\n\tstd::vector<Eigen::Matrix2d> puncturedAbars(nPuncturedFaces);\n\n\tfor (int i = 0; i < nPuncturedFaces; i++)\n\t{\n\t\tpuncturedW.row(i) = w.row(newFacesToOld(i));\n\t\tpuncturedAbars[i] = abars[newFacesToOld(i)];\n\t}\n\n\tEigen::MatrixXd combedPuncturedW;\n\n\tcombField(puncturedF, puncturedAbars, NULL, puncturedW, combedPuncturedW);\n\n\tcombedW = w;\n\tfor (int i = 0; i < nPuncturedFaces; i++)\n\t{\n\t\tcombedW.row(newFacesToOld(i)) = combedPuncturedW.row(i);\n\t}\n\n}\n\n\nvoid reindex(Eigen::MatrixXi &F)\n{\n\tstd::map<int, int> old2new;\n\tfor(int i=0; i<F.rows(); i++)\n\t{\n\t\tfor(int j=0; j<3; j++)\n\t\t{\n\t\t\tint vidx = F(i,j);\n\t\t\tif(old2new.find(vidx) == old2new.end())\n\t\t\t{\n\t\t\t\tint newidx = old2new.size();\n\t\t\t\told2new[vidx] = newidx;\n\t\t\t}\n\t\t}\n\t}\n\tfor(int i=0; i<F.rows(); i++)\n\t{\n\t\tfor(int j=0; j<3; j++)\n\t\t{\n\t\t\tint vidx = F(i,j);\n\t\t\tint newvidx = old2new[vidx];\n\t\t\tF(i,j) = newvidx;\n\t\t}\n\t}\n}\n\n\nvoid removeLocalSingularity(const Eigen::VectorXd& phi, const Eigen::MatrixXi& F, Eigen::VectorXd& newPhi)\n{\n\tstd::vector<std::vector<int>> adjacencyLists;\n\tMeshConnectivity mesh(F);\n\n\tint nverts = phi.rows();\n\tigl::adjacency_list(F, adjacencyLists);\n\n\tnewPhi = phi;\n\n\n\tdouble absAvePhiDiff = 0;\n\tfor (int i = 0; i < mesh.nEdges(); i++)\n\t{\n\t\tdouble phiDiff = phi(mesh.edgeVertex(i, 0)) - phi(mesh.edgeVertex(i, 1));\n\t\tabsAvePhiDiff += abs(phiDiff);\n\t}\n\n\tabsAvePhiDiff /= mesh.nEdges();\n\tEigen::VectorXi singularity(nverts);\n\tsingularity.setZero();\n\n\tfor (int i = 0; i < nverts; i++)\n\t{\n\t\tconst std::vector<int> neighbors = adjacencyLists[i];\n\t\tdouble centerPhi = phi(i);\n\n\t\tbool isSingularity = true;\n\t\tint count = 0;\n\t\tfor (int j = 0; j < neighbors.size(); j++)\n\t\t{\n\t\t\tif (abs(phi(neighbors[j]) - centerPhi) < absAvePhiDiff)\n\t\t\t\tisSingularity = false;\n\t\t\telse\n\t\t\t\tcount++;\n\t\t}\n\n\t\t//if(!isSingularity) // check 2-rings\n\t\t//{\n\t\t//\tfor (int j = 0; j < neighbors.size(); j++)\n\t\t//\t{\n\t\t//\t\tint centerCount = count;\n\t\t//\t\t// check 2 neighbors\n\t\t//\t\tint neigVert = neighbors[j];\n\t\t//\t\tdouble anothercenterPhi = phi(neigVert);\n\t\t//\t\tfor (int k = 0; k < adjacencyLists[neigVert].size(); k++)\n\t\t//\t\t{\n\t\t//\t\t\tif (abs(phi(adjacencyLists[neigVert][k]) - anothercenterPhi) > absAvePhiDiff)\n\t\t//\t\t\t\tcenterCount++;\n\t\t//\t\t}\n\t\t//\t\tif (centerCount >= neighbors.size() + adjacencyLists[neigVert].size() - 2)\n\t\t//\t\t\tisSingularity = true;\n\t\t//\t}\n\t\t//}\n\t\tif (isSingularity)\n\t\t\tsingularity(i) = 1;\n\n\t}\n\n\tint numSingularity = 0;\n\n\tfor (int i = 0; i < nverts; i++)\n\t{\n\t\tif (singularity(i))\n\t\t{\n\t\t\tnumSingularity++;\n\t\t\tconst std::vector<int> neighbors = adjacencyLists[i];\n\n\t\t\tnewPhi(i) = 0;\n\t\t   \n\n\t\t\tfor (int j = 0; j < neighbors.size(); j++)\n\t\t\t{\n\t\t\t\tnewPhi(i) += phi(neighbors[j]);\n\t\t\t   \n\t\t\t}\n\n\t\t\tnewPhi(i) /= neighbors.size();\n\t\t}\n\t}\n\tstd::cout << \"number of singularities in phi: \" << numSingularity << std::endl;\n\n\n}\n\n\nvoid estimateAmpOmegaFromStrain(const std::vector<Eigen::Matrix2d>& abars,\n\tconst Eigen::MatrixXd& curPos,\n\tconst Eigen::MatrixXi& F,\n\tconst std::set<int>& clampedVerts,\n\tdouble amplitudeEstimate,\n\tEigen::VectorXd& amp,\n\tEigen::MatrixXd& w,\n\tstd::set<int>& tensionFaces)\n{\n\tMeshConnectivity mesh(F);\n\tMeshGeometry curGeo(curPos, mesh);\n\tassert(abars.size() == F.rows());\n\tint nfaces = F.rows();\n\n\tEigen::MatrixXd wguess(nfaces, 2);\n\twguess.setZero();\n\n\tstd::set<int> pureTensionVerts;\n\n\tdouble length = curPos.row(0).maxCoeff() - curPos.row(0).minCoeff();\n\tdouble width = curPos.row(1).maxCoeff() - curPos.row(1).minCoeff();\n\tdouble height = curPos.row(2).maxCoeff() - curPos.row(2).minCoeff();\n\n\tdouble bboxSize = std::max(length, width);\n\tbboxSize = std::max(bboxSize, height);\n\tstd::cout << \"bbox: \" << length << \",  \" << width << \", \" << height << std::endl;\n\n\tlocatePotentialPureTensionFaces(abars, curPos, F, tensionFaces);\n\tdouble newAmpEstimate = std::min(amplitudeEstimate, 0.1 * bboxSize);\n\n\tEigen::VectorXd faceAmp(nfaces);\n\tfaceAmp.setZero();\n\n\tfor (int i = 0; i < nfaces; i++)\n\t{\n\t\tif (tensionFaces.find(i) != tensionFaces.end())\n\t\t\tcontinue;\n\t\tEigen::Matrix2d abar = abars[i];\n\t\tEigen::Matrix2d a = curGeo.Bs[i].transpose() * curGeo.Bs[i];\n\t\tEigen::Matrix2d diff = a - abar;\n\t\tEigen::GeneralizedSelfAdjointEigenSolver<Eigen::Matrix2d> solver(diff, abar);\n\t\tEigen::Vector2d evec = solver.eigenvectors().col(0);\n\n\t\tfaceAmp(i) = std::sqrt(2.0 * std::fabs(solver.eigenvalues()[0]));\n\t\twguess.row(i) = (abar * evec).transpose();\t// convert to one-form\n\t}\n\n\t// rescale the faceAmp such that we don't have a huge amp\n\tdouble coeff = newAmpEstimate / (faceAmp.maxCoeff() + 1e-6);;\n\tfaceAmp = faceAmp * coeff;\n\twguess = wguess / coeff;\n\n\tstd::cout << \"w estimated finished! \" << std::endl;\n\tstd::cout << \"max face amp = \" << faceAmp.maxCoeff() << std::endl;\n\n\tEigen::MatrixXd combedW = wguess;\n\tcombField(F, abars, &faceAmp, wguess, combedW);\n\n\tw = combedW;\n\n\tamp.resize(curPos.rows());\n\tamp.setZero();\n\n\tEigen::VectorXd vdegree(curPos.rows());\n\tvdegree.setZero();\n\n\tfor (int i = 0; i < nfaces; i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tint vid = mesh.faceVertex(i, j);\n\t\t\tvdegree(vid) += 1.0;\n\t\t\tamp(vid) += faceAmp(i);\n\t\t}\n\t}\n\tfor (int i = 0; i < curPos.rows(); i++)\n\t{\n\t\tamp(i) /= vdegree(i);\n\t}\n\n\n\tfor (auto& f : tensionFaces)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tint vid = mesh.faceVertex(f, j);\n\t\t\tif (pureTensionVerts.find(vid) == pureTensionVerts.end())\n\t\t\t\tpureTensionVerts.insert(vid);\n\t\t}\n\t}\n\n\tfor (auto& vid : pureTensionVerts)\n\t\tamp(vid) = 0;\n\tfor (auto& vid : clampedVerts)\n\t\tamp(vid) = 0;\n\n\t// smoothing for the amplitude\n\tstd::vector<std::vector<int>> vertNeis;\n\tigl::adjacency_list(F, vertNeis);\n\n\tEigen::SparseMatrix<double> L(curPos.rows(), curPos.rows());\n\tstd::vector<Eigen::Triplet<double>> Lcoeff;\n\n\tfor (int i = 0; i < curPos.rows(); i++)\n\t{\n\t\tif (amp(i) > 0) // not pure tension vertices or clamped vertices\n\t\t{\n\t\t\tfor (auto& neiV : vertNeis[i])\n\t\t\t{\n\t\t\t\tLcoeff.push_back(Eigen::Triplet<double>(i, neiV, 1.0 / vertNeis[i].size()));\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tLcoeff.push_back(Eigen::Triplet<double>(i, i, 1.0));\n\t}\n\n\tL.setFromTriplets(Lcoeff.begin(), Lcoeff.end());\n\n\t// apply twice by default\n\tamp = L * (L * amp);\n}\n\nvoid roundPhiFromOmega(\n\tconst Eigen::MatrixXi& F,\n\tconst std::vector<Eigen::Matrix2d>& abars,\n\tconst Eigen::MatrixXd& w,\n\tEigen::VectorXd& phi,\n\tEigen::MatrixXd& roundedW)\n{\n\tint nfaces = F.rows();\n\n\tstd::vector<std::vector<int> > cuts;\n\tfindCuts(F, cuts);\n\tstd::cout << \"Used \" << cuts.size() << \" cuts\" << std::endl;\n\n\tstd::map<std::pair<int, int>, int> cutpairs;\n\n\t// convert cuts to edge indices\n\tfor (int i = 0; i < cuts.size(); i++)\n\t{\n\t\tint len = cuts[i].size();\n\t\tfor (int j = 0; j < len - 1; j++)\n\t\t{\n\t\t\tcutpairs[std::pair<int, int>(cuts[i][j], cuts[i][j + 1])] = i;\n\t\t}\n\t}\n\n\tEigen::MatrixXi newF;\n\n\tcutMesh(F, cuts, newF);\n\treindex(newF);\n\n\tint newverts = 0;\n\tfor (int i = 0; i < newF.rows(); i++)\n\t\tfor (int j = 0; j < 3; j++)\n\t\t\tnewverts = std::max(newverts, newF(i, j) + 1);\n\n\tint intdofs = 0;\n\tMeshConnectivity punctmesh(F);\n\n\tstd::vector<Eigen::Triplet<double> > Ccoeffs;\n\n\t// integer constraints on the two sides of the cut\n\tint row = 0;\n\tfor (int i = 0; i < punctmesh.nEdges(); i++)\n\t{\n\t\tint f1 = punctmesh.edgeFace(i, 0);\n\t\tint f2 = punctmesh.edgeFace(i, 1);\n\t\tif (f1 == -1 || f2 == -1)\n\t\t\tcontinue;\n\t\tint v1 = punctmesh.edgeVertex(i, 0);\n\t\tint v2 = punctmesh.edgeVertex(i, 1);\n\t\tdouble sign = 1.0;\n\t\tauto it = cutpairs.find(std::pair<int, int>(v1, v2));\n\t\tif (it == cutpairs.end())\n\t\t{\n\t\t\tit = cutpairs.find(std::pair<int, int>(v2, v1));\n\t\t\tsign = -1.0;\n\t\t}\n\t\tif (it == cutpairs.end())\n\t\t\tcontinue;\n\n\t\tint newv1 = -1;\n\t\tint newv2 = -1;\n\t\tint neww1 = -1;\n\t\tint neww2 = -1;\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tif (F(f1, j) == v1)\n\t\t\t\tnewv1 = newF(f1, j);\n\t\t\tif (F(f2, j) == v1)\n\t\t\t\tnewv2 = newF(f2, j);\n\t\t\tif (F(f1, j) == v2)\n\t\t\t\tneww1 = newF(f1, j);\n\t\t\tif (F(f2, j) == v2)\n\t\t\t\tneww2 = newF(f2, j);\n\t\t}\n\n\t\tCcoeffs.push_back(Eigen::Triplet<double>(row, newv1, sign));\n\t\tCcoeffs.push_back(Eigen::Triplet<double>(row, newv2, -sign));\n\t\tCcoeffs.push_back(Eigen::Triplet<double>(row, newverts + intdofs, 1.0));\n\t\tCcoeffs.push_back(Eigen::Triplet<double>(row + 1, neww1, sign));\n\t\tCcoeffs.push_back(Eigen::Triplet<double>(row + 1, neww2, -sign));\n\t\tCcoeffs.push_back(Eigen::Triplet<double>(row + 1, newverts + intdofs, 1.0));\n\t\trow += 2;\n\t\tintdofs++;\n\t}\n\tEigen::SparseMatrix<double> C(row, newverts + intdofs + 1);\n\tC.setFromTriplets(Ccoeffs.begin(), Ccoeffs.end());\n\n\tstd::vector<Eigen::Triplet<double> > Acoeffs;\n\tint newfaces = newF.rows();\n\t//assert(newfaces == punctF.rows());\n\n\tfor (int i = 0; i < newfaces; i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tAcoeffs.push_back(Eigen::Triplet<double>(3 * i + j, newF(i, j), 1.0));\n\t\t}\n\t}\n\tEigen::SparseMatrix<double> A(3 * newfaces, newverts + intdofs);\n\tA.setFromTriplets(Acoeffs.begin(), Acoeffs.end());\n\n\tstd::vector<Eigen::Triplet<double> > L2Minvcoeffs;\n\tstd::vector<Eigen::Triplet<double> > Mcoeffs;\n\tfor (int i = 0; i < newfaces; i++)\n\t{\n\t\tdouble area = 0.5 * std::sqrt(abars[i].determinant());\n\t\tfor (int j = 0; j < 2; j++)\n\t\t\tfor (int k = 0; k < 2; k++)\n\t\t\t{\n\t\t\t\tL2Minvcoeffs.push_back(Eigen::Triplet<double>(2 * i + j, 2 * i + k, area * abars[i].inverse()(j, k)));\n\t\t\t\tMcoeffs.push_back(Eigen::Triplet<double>(2 * i + j, 2 * i + k, abars[i](j, k)));\n\t\t\t}\n\t}\n\tEigen::SparseMatrix<double> L2Minv(2 * newfaces, 2 * newfaces);\n\tL2Minv.setFromTriplets(L2Minvcoeffs.begin(), L2Minvcoeffs.end());\n\tEigen::SparseMatrix<double> M(2 * newfaces, 2 * newfaces);\n\tM.setFromTriplets(Mcoeffs.begin(), Mcoeffs.end());\n\n\tstd::vector<Eigen::Triplet<double> > Dcoeffs;\n\tfor (int i = 0; i < newfaces; i++)\n\t{\n\t\tDcoeffs.push_back(Eigen::Triplet<double>(2 * i, 3 * i + 1, 1.0));\n\t\tDcoeffs.push_back(Eigen::Triplet<double>(2 * i, 3 * i, -1.0));\n\t\tDcoeffs.push_back(Eigen::Triplet<double>(2 * i + 1, 3 * i + 2, 1.0));\n\t\tDcoeffs.push_back(Eigen::Triplet<double>(2 * i + 1, 3 * i, -1.0));\n\t}\n\tEigen::SparseMatrix<double> D(2 * newfaces, 3 * newfaces);\n\tD.setFromTriplets(Dcoeffs.begin(), Dcoeffs.end());\n\n\tEigen::SparseMatrix<double> Mat = A.transpose() * D.transpose() * L2Minv * D * A;\n\tEigen::VectorXd punctfield(2 * newfaces);\n\tfor (int i = 0; i < newfaces; i++)\n\t{\n\t\tpunctfield[2 * i] = w(i, 0) / 2.0 / PI;\n\t\tpunctfield[2 * i + 1] = w(i, 1) / 2.0 / PI;\n\t}\n\tEigen::VectorXd rhs = A.transpose() * D.transpose() * L2Minv * punctfield;\n\n\tEigen::VectorXd result;\n\tEigen::VectorXi toRound(intdofs);\n\tfor (int i = 0; i < intdofs; i++)\n\t{\n\t\ttoRound[i] = newverts + i;\n\t}\n\tstd::cout << intdofs << \" integer variables\" << std::endl;\n\tComisoWrapper(C, Mat, result, rhs, toRound, 1e-6);\n\tstd::cout << \"Solver residual: \" << (Mat * result - rhs).norm() << std::endl;\n\tstd::cout << \"Reconstruction residual: \" << (D * A * result - punctfield).transpose() * L2Minv * (D * A * result - punctfield) << std::endl;\n\n\t// map phi back to the original mesh\n\tint oldverts = 0;\n\tfor (int i = 0; i < F.rows(); i++)\n\t\tfor (int j = 0; j < 3; j++)\n\t\t\toldverts = std::max(oldverts, F(i, j) + 1);\n\n\tphi.resize(oldverts);\n\tphi.setZero();\n\tfor (int i = 0; i < newfaces; i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tphi[F(i, j)] = 2.0 * PI * result[newF(i, j)];\n\t\t}\n\t}\n\n\tEigen::VectorXd cutPhi;\n\tcutPhi.resize(newverts);\n\troundedW.resize(newfaces, 2);\n\troundedW.setZero();\n\n\tfor (int i = 0; i < newfaces; i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tcutPhi(newF(i, j)) = 2.0 * PI * result(newF(i, j));\n\t\t}\n\t}\n\tEigen::VectorXd newPhi;\n\tremoveLocalSingularity(cutPhi, newF, newPhi);\n\n\tfor (int i = 0; i < newfaces; i++)\n\t{\n\t\troundedW(i, 0) = newPhi(newF(i, 1)) - newPhi(newF(i, 0));\n\t\troundedW(i, 1) = newPhi(newF(i, 2)) - newPhi(newF(i, 0));\n\t}\n\n}\n\nvoid estimateWrinkleVariablesFromStrain(\n\tconst std::vector<Eigen::Matrix2d>& abars,\n\tconst Eigen::MatrixXd& curPos,\n\tconst Eigen::MatrixXi& F,\n\tconst std::set<int>& clampedVerts,\n\tdouble amplitudeEstimate,\n\tEigen::VectorXd& amp,\n\tEigen::VectorXd& phi,\n\tEigen::VectorXd& dphi,\n\tstd::set<int>& tensionFaces)\n{\n\tMeshConnectivity mesh(F);\n\tMeshGeometry curGeo(curPos, mesh);\n\tassert(abars.size() == F.rows());\n\tint nfaces = F.rows();\n\n\tEigen::MatrixXd w;\n\testimateAmpOmegaFromStrain(abars, curPos, F, clampedVerts, amplitudeEstimate, amp, w, tensionFaces);\n\n\tstd::vector<int> singularVertices;\n\tvectorFieldSingularities(F, abars, w, singularVertices);\n\tstd::cout << \"Found \" << singularVertices.size() << \" singularities\" << std::endl;\n\tEigen::MatrixXi punctF;\n\tEigen::VectorXi new2old;\n\tpunctureMesh(F, singularVertices, punctF, new2old);\n\tint newfaces = punctF.rows();\n\tEigen::VectorXd punctphi;\n\n\tstd::vector<Eigen::Matrix2d> punctabars;\n\tfor (int i = 0; i < newfaces; i++)\n\t\tpunctabars.push_back(abars[new2old[i]]);\n\n\tEigen::MatrixXd punctW(newfaces, 2);\n\tfor (int i = 0; i < newfaces; i++)\n\t\tpunctW.row(i) = w.row(new2old[i]);\n\n\tEigen::MatrixXd roundedW;\n\tstd::cout << \"Round phi from omega\" << std::endl;\n\troundPhiFromOmega(punctF, punctabars, punctW, punctphi, roundedW);\n\tstd::cout << \"Round phi from omega finished\" << std::endl;\n\n\tphi.resize(curPos.rows());\n\tphi.setZero();\n\n\tEigen::MatrixXd faceDphi(F.rows(), 2);\n\tfaceDphi.setZero();\n\n\tfor (int i = 0; i < newfaces; i++)\n\t{\n\t\tint oldface = new2old[i];\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tphi[F(oldface, j)] = punctphi[punctF(i, j)];\n\t\t}\n\t\tfaceDphi.row(oldface) = roundedW.row(i);\n\t}\n\n\tstd::vector<std::vector<int>> adjLst;\n\tigl::adjacency_list(F, adjLst);\n\tauto backupPhi = phi;\n\n\tfor (auto& it : singularVertices)\n\t{\n\t\tif (backupPhi(it))\n\t\t{\n\t\t\tstd::cout << \"something wrong happened\" << std::endl;\n\t\t}\n\t\tfor (int j = 0; j < adjLst[it].size(); j++)\n\t\t{\n\t\t\tphi(it) += backupPhi(adjLst[it][j]);\n\t\t}\n\t\tphi(it) /= adjLst[it].size();\n\t}\n\n\tEigen::VectorXd newPhi;\n\tremoveLocalSingularity(phi, F, newPhi);\n\n\tphi = newPhi;\n\n\tint nedges = mesh.nEdges();\n\tdphi.resize(nedges);\n\tdphi.setZero();\n\tfor (int i = 0; i < nfaces; i++)\n\t{\n\t\tfor (int e = 0; e < 3; e++)\n\t\t{\n\t\t\tint edge = mesh.faceEdge(i, e);\n\t\t\tint vert1 = mesh.edgeVertex(edge, 0);\n\t\t\tint vert2 = mesh.edgeVertex(edge, 1);\n\t\t\tEigen::Vector2d barys[3] = { {0,0}, {1,0}, {0,1} };\n\t\t\tEigen::Vector2d facee(0, 0);\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tif (vert1 == mesh.faceVertex(i, j))\n\t\t\t\t\tfacee -= barys[j];\n\t\t\t\telse if (vert2 == mesh.faceVertex(i, j))\n\t\t\t\t\tfacee += barys[j];\n\t\t\t}\n\t\t\tdphi[edge] = faceDphi.row(i).dot(facee);\n\t\t}\n\t}\n}\n\nvoid faceDPhi2EdgeDPhi(const Eigen::MatrixXd& faceDphi, \n\tconst std::set<int>& tensionFaces, \n\tconst std::vector<Eigen::Matrix2d>& abars,\n\tEigen::MatrixXi F, \n\tEigen::VectorXd& dphi)\n{\n\tMeshConnectivity mesh(F);\n\tint nedges = mesh.nEdges();\n\tint nfaces = mesh.nFaces();\n\tif (nfaces != faceDphi.rows())\n\t{\n\t\tstd::cout << \"Error in face dphi value\" << std::endl;\n\t}\n\n\tEigen::SparseMatrix<double> C;\n\tstd::vector<Eigen::Triplet<double> > constraintCoeff;\n\n\tint row = 0;\n\tfor (int i = 0; i < nfaces; i++)\n\t{\n\t\tif (tensionFaces.find(i) != tensionFaces.end())\n\t\t\tcontinue;\n\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tint eid = mesh.faceEdge(i, j);\n\t\t\tint vert1 = mesh.edgeVertex(eid, 0);\n\t\t\tint vert2 = mesh.edgeVertex(eid, 1);\n\n\t\t\tif (vert1 == mesh.faceVertex(i, (j + 1) % 3))\n\t\t\t\tconstraintCoeff.push_back(Eigen::Triplet<double>(row, eid, 1.0));\n\t\t\telse\n\t\t\t\tconstraintCoeff.push_back(Eigen::Triplet<double>(row, eid, -1.0));\n\t\t}\n\n\t\trow++;\n\t}\n\tC.resize(row, nedges);\n\tC.setFromTriplets(constraintCoeff.begin(), constraintCoeff.end());\n\tstd::cout << nfaces - row << \" faces are removed from integrabilty due to pure tension check.\" << std::endl;\n\n\tstd::vector<Eigen::Triplet<double> > Mcoeffs;\t\n\tfor (int i = 0; i < nfaces; i++)\n\t{\n\t\tEigen::Matrix2d ainv = abars[i].inverse();\n\t\tdouble area = std::sqrt(abars[i].determinant());\n\t\tfor (int j = 0; j < 2; j++)\n\t\t{\n\t\t\tfor (int k = 0; k < 2; k++)\n\t\t\t{\n\t\t\t\tMcoeffs.push_back({ 2 * i + j, 2 * i + k, ainv(j,k) * area });\n\t\t\t}\n\t\t}\n\t}\n\tEigen::SparseMatrix<double> M(2 * nfaces, 2 * nfaces);\n\tM.setFromTriplets(Mcoeffs.begin(), Mcoeffs.end());\n\n\tstd::vector<Eigen::Triplet<double> > L;\n\tEigen::SparseMatrix<double> edgeDphi2FaceDphi(2 * nfaces, nedges);\n\n\tfor (int i = 0; i < nfaces; i++)\n\t{\n\t\tif (tensionFaces.find(i) != tensionFaces.end())\n\t\t\tcontinue;\n\t\tEigen::Vector3i edgeIndices;\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tedgeIndices(j) = mesh.faceEdge(i, j);\n\t\t}\n\n\t\tdouble flagU = 1.0;\n\t\tdouble flagV = 1.0;\n\n\t\tif (mesh.faceVertex(i, 0) > mesh.faceVertex(i, 1))\n\t\t{\n\t\t\tflagU = -1;\n\t\t}\n\t\tif (mesh.faceVertex(i, 0) > mesh.faceVertex(i, 2))\n\t\t{\n\t\t\tflagV = -1;\n\t\t}\n\n\t\tL.push_back(Eigen::Triplet<double>(2 * i, edgeIndices(2), flagU));\n\t\tL.push_back(Eigen::Triplet<double>(2 * i + 1, edgeIndices(1), flagV));\n\t}\n\tedgeDphi2FaceDphi.setFromTriplets(L.begin(), L.end());\n\n\tdouble reg = 1e-8;\n\tEigen::VectorXd B, Beq, Bieq;\n\tEigen::SparseMatrix<double> Q, Aeq, Aieq;\n\tEigen::VectorXd lx, ux, delta_x;\n\n\tQ = edgeDphi2FaceDphi.transpose() * M * edgeDphi2FaceDphi;\n\tAeq = C;\n\tBeq = Eigen::VectorXd::Zero(Aeq.rows());\n\n\tlx.resize(0);\n\tux.resize(0);\n\n\tBieq.resize(0);\n\tAieq.resize(0, 0);\n\n\tEigen::VectorXd w(2 * nfaces);\n\tfor (int i = 0; i < nfaces; i++)\n\t{\n\t\tif (tensionFaces.find(i) != tensionFaces.end())\n\t\t{\n\t\t\tw(2 * i) = 0;\n\t\t\tw(2 * i + 1) = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tw(2 * i) = faceDphi(i, 0);\n\t\t\tw(2 * i + 1) = faceDphi(i, 1);\n\t\t}\n\t}\n\tstd::cout << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << \"|| w || = \" << w.norm() << std::endl;\n\tB = -edgeDphi2FaceDphi.transpose() * M * w;\n\n\tEigen::SparseMatrix<double> I(Q.rows(), Q.cols());\n\tI.setIdentity();\n\n\tQ = Q + 1e-8 * I;\n\tstd::cout << \"QP Solver Start: \" << std::endl;\n\tEigenNASOQSparse qp;\n\tqp.setAccThresh(1e-6);\n\t\n\tdelta_x.setZero();\n\tdouble perturb = 1e-9;\n\tbool isQPSuccess = qp.solve(Q, B, Aeq, Beq, Aieq, Bieq, lx, ux, delta_x, perturb);\n\n\tdphi = delta_x;\n\tdouble sqerrorResidual = (edgeDphi2FaceDphi * dphi - w).transpose() * M * (edgeDphi2FaceDphi * dphi - w);\n\tdouble errorResidual = std::sqrt(sqerrorResidual);\n\tdouble constraintsResidual = (C * dphi).norm();\n\tdouble initialwNorm = w.transpose() * M * w;\n\n\tstd::cout << \"|| w ||_ainv = \" << initialwNorm << std::endl;\n\tstd::cout << \"|| dphi - w ||_ainv = \" << errorResidual << std::endl;\n\tstd::cout << \"|| C * dphi || = \" << constraintsResidual << std::endl;\n\n\n\t/*dphi.resize(nedges);\n\tdphi.setZero();\n\tfor (int i = 0; i < nfaces; i++)\n\t{\n\t\tfor (int e = 0; e < 3; e++)\n\t\t{\n\t\t\tint edge = mesh.faceEdge(i, e);\n\t\t\tint vert1 = mesh.edgeVertex(edge, 0);\n\t\t\tint vert2 = mesh.edgeVertex(edge, 1);\n\t\t\tEigen::Vector2d barys[3] = { {0,0}, {1,0}, {0,1} };\n\t\t\tEigen::Vector2d facee(0, 0);\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tif (vert1 == mesh.faceVertex(i, j))\n\t\t\t\t\tfacee -= barys[j];\n\t\t\t\telse if (vert2 == mesh.faceVertex(i, j))\n\t\t\t\t\tfacee += barys[j];\n\t\t\t}\n\t\t\tdphi[edge] += faceDphi.row(i).dot(facee);\n\t\t}\n\t}\n\tfor (int i = 0; i < nedges; i++)\n\t{\n\t\tint f1 = mesh.edgeFace(i, 0);\n\t\tint f2 = mesh.edgeFace(i, 1);\n\n\t\tif (f1 != -1 && f2 != -1)\n\t\t\tdphi[i] /= 2.0;\n\t}*/\n}\n\nvoid estimateWrinkleVariablesFromStrainCutbyTension(\n\tconst std::vector<Eigen::Matrix2d>& abars,\n\tconst Eigen::MatrixXd& curPos,\n\tconst Eigen::MatrixXi& F,\n\tconst std::set<int>& clampedVerts,\n\tdouble amplitudeEstimate,\n\tEigen::VectorXd& amp,\n\tEigen::VectorXd& phi,\n\tEigen::VectorXd& dphi,\n\tstd::set<int>& tensionFaces)\n{\n\ttensionFaces.clear();\n\tMeshConnectivity mesh(F);\n\tMeshGeometry curGeo(curPos, mesh);\n\tassert(abars.size() == F.rows());\n\tint nfaces = F.rows();\n\tEigen::MatrixXd w;\n\testimateAmpOmegaFromStrain(abars, curPos, F, clampedVerts, amplitudeEstimate, amp, w, tensionFaces);\n\tfaceDPhi2EdgeDPhi(w, tensionFaces, abars, F, dphi);\n\n\tEigen::MatrixXd cutV;\n\tEigen::MatrixXi cutF;\n\n\tEigen::VectorXd cutAmp, cutPhi;\n\n\troundPhiFromDphiCutbyTension(curPos, F, cutV, cutF, abars, amp, dphi, ComisoRound, phi, cutPhi, cutAmp, tensionFaces, false);// by setting to false, round phi codes will use provided pure tension faces to cut the mesh and do rounding.\n\treturn;\n\n\t\n\n\t//std::cout << \"round phi from omega cut by tension. \" << std::endl;\n\t//roundPhiFromOmegaCutbyTension(curPos, F, cutV, cutF, abars, amp, w, phi, cutPhi, cutAmp, tensionFaces, false);\t// by setting to false, round phi codes will use provided pure tension faces to cut the mesh and do rounding.\n\n\t//MeshConnectivity cutMesh(cutF);\n\t//Eigen::VectorXd cutDphi(cutMesh.nEdges());\n\t//for (int i = 0; i < cutMesh.nEdges(); i++)\n\t//{\n\t//\tint v0 = cutMesh.edgeVertex(i, 0);\n\t//\tint v1 = cutMesh.edgeVertex(i, 1);\n\n\t//\tif (v0 < v1)\n\t//\t\tcutDphi(i) = cutPhi(v1) - cutPhi(v0);\n\t//\telse\n\t//\t\tcutDphi(i) = cutPhi(v0) - cutPhi(v1);\n\n\t//\t\t\n\t//}\n\n\t//int nedges = mesh.nEdges();\n\t//dphi.resize(nedges);\n\t//dphi.setZero();\n\n\t//Eigen::VectorXi isVisited(mesh.nEdges());\n\t//isVisited.setZero();\n\n\t//for (int f = 0; f < nfaces; f++)\n\t//{\n\t//\tif (tensionFaces.find(f) != tensionFaces.end())\n\t//\t\tcontinue;\n\t//\tfor (int e = 0; e < 3; e++)\n\t//\t{\n\t//\t\tint eid = mesh.faceEdge(f, e);\n\t//\t\tif (isVisited(eid))\n\t//\t\t\tcontinue;\n\t//\t\tisVisited(eid) = 1;\n\n\t//\t\tint vid0 = mesh.edgeVertex(eid, 0);\n\t//\t\tint vid1 = mesh.edgeVertex(eid, 1);\n\t//\t\tEigen::Vector2d phiVals;\n\t//\t\tphiVals << std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity();\n\n\t//\t\tfor (int v = 0; v < 3; v++)\n\t//\t\t{\n\t//\t\t\tint cutVid = cutMesh.faceVertex(f, v);\n\t//\t\t\n\t//\t\t\tif ((cutV.row(cutVid) - curPos.row(vid0)).norm() < 1e-6)\n\t//\t\t\t\tphiVals(0) = cutPhi(cutVid);\n\n\t//\t\t\tif ((cutV.row(cutVid) - curPos.row(vid1)).norm() < 1e-6)\n\t//\t\t\t\tphiVals(1) = cutPhi(cutVid);\n\n\t//\t\t}\n\n\t//\t\tif (phiVals(0) == std::numeric_limits<double>::infinity() || phiVals(1) == std::numeric_limits<double>::infinity())\n\t//\t\t\tstd::cout << \"error!\" << std::endl;\n\n\n\t//\t\tif (vid0 < vid1)\n\t//\t\t\tdphi(eid) = phiVals(1) - phiVals(0);\n\t//\t\telse\n\t//\t\t\tdphi(eid) = phiVals(1) - phiVals(0);\n\t//\t\t\t\n\t//\t}\n\t//}\n\t//igl::writeOBJ(\"../cutByTensionV.obj\", cutV, cutF);\n}\n\n\n\nstatic void integrabilityConstraintMatrix(const MeshConnectivity& mesh,\n\tconst IntrinsicGeometry& geo,\n\tEigen::SparseMatrix<double>& C)\n{\n\tint rows = 0;\n\tstd::vector<Eigen::Triplet<double> > Ccoeffs;\n\tfor (int i = 0; i < mesh.nEdges(); i++)\n\t{\n\t\tif (mesh.edgeFace(i, 0) != -1 && mesh.edgeFace(i, 1) != -1)\n\t\t{\n\t\t\tint face1 = mesh.edgeFace(i, 0);\n\t\t\tint face2 = mesh.edgeFace(i, 1);\n\n\t\t\tint vert1 = mesh.edgeVertex(i, 0);\n\t\t\tint vert2 = mesh.edgeVertex(i, 1);\n\t\t\t\n\t\t\tEigen::Vector2d barys[3] = { {0,0}, {1,0}, {0,1} };\n\t\t\tEigen::Vector2d face1e(0, 0);\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tif (vert1 == mesh.faceVertex(face1, j))\n\t\t\t\t\tface1e -= barys[j];\n\t\t\t\telse if (vert2 == mesh.faceVertex(face1, j))\n\t\t\t\t\tface1e += barys[j];\n\t\t\t}\n\n\t\t\tface1e /= std::sqrt(face1e.transpose() * geo.abars[face1] * face1e);\n\n\t\t\tEigen::Matrix2d T = geo.Ts.block<2, 2>(2 * i, 2);\n\t\t\tEigen::RowVector2d oppdot = -face1e.transpose() * geo.abars[face1] * T;\n\t\t\tEigen::RowVector2d samedot = face1e.transpose() * geo.abars[face1];\n\t\t\tfor (int k = 0; k < 2; k++)\n\t\t\t{\n\t\t\t\tCcoeffs.push_back({ rows, 2 * face1 + k, samedot[k] });\n\t\t\t\tCcoeffs.push_back({ rows, 2 * face2 + k, oppdot[k] });\n\t\t\t}\n\n\t\t\trows++;\n\t\t}\n\t}\n\tC.resize(rows, 2 * mesh.nFaces());\n\tC.setFromTriplets(Ccoeffs.begin(), Ccoeffs.end());\n}\n\nstatic void scalarDifferentialMatrix(const MeshConnectivity& mesh, const IntrinsicGeometry& geo, \n\tconst std::vector<int>& facesmap,\n\tint numsvars,\n\tEigen::SparseMatrix<double>& sD)\n{\n\tstd::vector<Eigen::Triplet<double> > Dcoeffs;\n\tint rows = 0;\n\tfor (int i = 0; i < mesh.nEdges(); i++)\n\t{\n\t\tif (mesh.edgeFace(i, 0) != -1 && mesh.edgeFace(i, 1) != -1)\n\t\t{\n\t\t\tint face1 = mesh.edgeFace(i, 0);\n\t\t\tint face2 = mesh.edgeFace(i, 1);\n\t\t\tif (facesmap[face1] != -1 && facesmap[face2] != -1)\n\t\t\t{\n\t\t\t\tDcoeffs.push_back({ rows, facesmap[face1], 1.0 });\n\t\t\t\tDcoeffs.push_back({ rows, facesmap[face2], -1.0 });\n\t\t\t}\n\t\t\trows++;\n\t\t}\n\t}\n\tsD.resize(rows, numsvars);\n\tsD.setFromTriplets(Dcoeffs.begin(), Dcoeffs.end());\n}\n\nstatic void dualDifferentialMatrix(const MeshConnectivity& mesh, const IntrinsicGeometry& geo, Eigen::SparseMatrix<double>& D)\n{\n\tstd::vector<Eigen::Triplet<double> > Dcoeffs;\n\tint rows = 0;\n\tfor (int i = 0; i < mesh.nEdges(); i++)\n\t{\n\t\tif (mesh.edgeFace(i, 0) != -1 && mesh.edgeFace(i, 1) != -1)\n\t\t{\n\t\t\tint face1 = mesh.edgeFace(i, 0);\n\t\t\tint face2 = mesh.edgeFace(i, 1);\n\t\t\t\n\t\t\tEigen::Matrix2d T21 = geo.Ts.block<2, 2>(2 * i, 2);\n\t\t\tEigen::Matrix2d T12 = geo.Ts.block<2, 2>(2 * i, 0);\n\t\t\t\n\t\t\tfor (int k = 0; k < 2; k++)\n\t\t\t{\n\t\t\t\tDcoeffs.push_back({ rows + k, 2 * face1 + k, 1.0 });\n\t\t\t\tfor (int l = 0; l < 2; l++)\n\t\t\t\t{\n\t\t\t\t\tDcoeffs.push_back({ rows + k, 2 * face2 + l, -T21(k,l) });\n\t\t\t\t}                \n\t\t\t}\n\t\t\trows+=2;\n\t\t\tfor (int k = 0; k < 2; k++)\n\t\t\t{\n\t\t\t\tDcoeffs.push_back({ rows + k, 2 * face2 + k, 1.0 });\n\t\t\t\tfor (int l = 0; l < 2; l++)\n\t\t\t\t{\n\t\t\t\t\tDcoeffs.push_back({ rows + k, 2 * face1 + l, -T12(k,l) });\n\t\t\t\t}\n\t\t\t}\n\t\t\trows += 2;\n\t\t}\n\t}\n\tD.resize(rows, 2 * mesh.nFaces());\n\tD.setFromTriplets(Dcoeffs.begin(), Dcoeffs.end());\n}\n\nstatic void dualMassMatrix(const MeshConnectivity& mesh, \n\tconst IntrinsicGeometry& geo, \n\tEigen::SparseMatrix<double>& M,\n\tconst std::vector<int> &facesmap,\n\tdouble usedreg, double unusedreg)\n{\n\tstd::vector<Eigen::Triplet<double> > Mcoeffs;\n\tint rows = 0;\n\tfor (int i = 0; i < mesh.nEdges(); i++)\n\t{\n\t\tif (mesh.edgeFace(i, 0) != -1 && mesh.edgeFace(i, 1) != -1)\n\t\t{\n\t\t\tint face1 = mesh.edgeFace(i, 0);\n\t\t\tint face2 = mesh.edgeFace(i, 1);\n\n\t\t\tdouble reg = unusedreg;\n\t\t\tif (facesmap[face1] != -1 && facesmap[face2] != -1)\n\t\t\t\treg = usedreg;\n\n\t\t\tfor (int k = 0; k < 2; k++)\n\t\t\t\tfor (int l = 0; l < 2; l++)\n\t\t\t\t{\n\t\t\t\t\tMcoeffs.push_back({ rows + k, rows + l, reg * geo.abars[face1](k,l) });\n\t\t\t\t}\n\t\t\trows += 2;\n\t\t\tfor (int k = 0; k < 2; k++)\n\t\t\t\tfor (int l = 0; l < 2; l++)\n\t\t\t\t{\n\t\t\t\t\tMcoeffs.push_back({ rows + k, rows + l, reg * geo.abars[face2](k,l) });\n\t\t\t\t}\n\t\t\trows += 2;\n\t\t}\n\t}\n\tM.resize(rows, rows);\n\tM.setFromTriplets(Mcoeffs.begin(), Mcoeffs.end());\n}\n\nvoid laplacianInterpolation(const Eigen::SparseMatrix<double> L, const Eigen::VectorXd& x, const std::set<int>& clampedDOFs, Eigen::VectorXd& smoothedX)\n{\n\tstd::cout << \"Laplacian interpolation.\" << std::endl;\n\tint nVars = x.size();\n\n\tEigen::SparseMatrix<double> Proj;\n\tint row = 0;\n\tstd::vector<Eigen::Triplet<double>> T;\n\n\tfor (int i = 0; i < nVars; i++)\n\t{\n\t\tif (clampedDOFs.find(i) != clampedDOFs.end())\n\t\t{\n\t\t\tT.push_back(Eigen::Triplet<double>(row, i, 1.0));\n\t\t\trow++;\n\t\t}\n\t}\n\tProj.resize(row, nVars);\n\tProj.setFromTriplets(T.begin(), T.end());\n\n\tEigen::VectorXd B, Beq, Bieq;\n\tEigen::SparseMatrix<double> Q, Aeq, Aieq, C;\n\tEigen::VectorXd lx, ux, delta_x;\n\n\tEigen::SparseMatrix<double> I(nVars, nVars);\n\tI.setIdentity();\n\n\tQ = -L + 1e-8 * I;\n\tint nEq = row;\n\tint nIneq = 0;\n\n\tAieq.resize(nIneq, nVars);\n\tBieq.resize(nIneq);\n\n\tdelta_x.resize(nVars);\n\tdelta_x = x;\n\n\tAeq = Proj;\n\tBeq = Proj * x;\n\n\tB.resize(nVars);\n\tB.setZero();\n\n\n\tlx.resize(nVars);\n\tlx.setZero();\n\n\n\tux.resize(0);\n\n\tstd::cout << \"QP Solver Start: \" << std::endl;\n\tEigenNASOQSparse qp;\n\t//if (this->m_current.fDelta > 1e-6)\n\tqp.setAccThresh(1e-6);\n\tdouble perturb = 1e-9;\n\tbool isQPSuccess = qp.solve(Q, B, Aeq, Beq, Aieq, Bieq, lx, ux, delta_x, perturb);\n\n\tsmoothedX = delta_x;\n\tfor (auto& v : clampedDOFs)\n\t\tsmoothedX(v) = x(v);\n}\n\nvoid amplitudeSmoothing(const Eigen::VectorXd& amp, const Eigen::MatrixXd& V, const Eigen::MatrixXi& F, const std::vector<int>& fxiedFaces, Eigen::VectorXd &smoothedAmp)\n{\n\tstd::set<int> freeVerts;\n\tfor (int i = 0; i < fxiedFaces.size(); i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tint vid = F(fxiedFaces[i], j);\n\t\t\tif (freeVerts.find(vid) == freeVerts.end())\n\t\t\t{\n\t\t\t\tfreeVerts.insert(vid);\n\t\t\t}\n\t\t}\n\t}\n\tEigen::SparseMatrix<double> L;\n\tigl::cotmatrix(V, F, L);\n\tlaplacianInterpolation(L, amp, freeVerts, smoothedAmp);\n}\n\n\nvoid roundPhiFromDphiCutbyTension(\n\tconst Eigen::MatrixXd& V,\n\tconst Eigen::MatrixXi& F,\n\tEigen::MatrixXd& seamedV,\n\tEigen::MatrixXi& seamedF,\n\tconst std::vector<Eigen::Matrix2d>& abars,\n\tconst Eigen::VectorXd& amp,\n\tconst Eigen::VectorXd& dPhi, // |E| vector of phi jumps\t\n\tconst RoundingType& roundType,// how to solve the MIP, either use comiso or gurobi\n\tEigen::VectorXd& phi,\n\tEigen::VectorXd& seamedPhi,\n\tEigen::VectorXd& seamedAmp,\n\tstd::set<int> &problemFaces,\n\tbool isRecomputeProbF // The assumption is that pure tension faces having zero amplitude\n\t)\t\t\t\n{\n\tMeshConnectivity mesh(F);\n\tint nonzeroamps = 0;\n\n\tif (isRecomputeProbF || problemFaces.size() == 0)\n\t{\n\t\tstd::cout << \"recompute the problem faces. \" << std::endl;\n\t\tproblemFaces.clear();\n\t\tlocatePotentialPureTensionFaces(abars, V, F, problemFaces);\t// by default, pure tension faces have zero amplitudes\n\n\n\t\tfor (int i = 0; i < F.rows(); i++)\n\t\t{\n\t\t\tbool isZeroFace = true;\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tif (amp(F(i, j)) > 0)\n\t\t\t\t\tisZeroFace = false;\n\t\t\t}\n\t\t\tif (isZeroFace)\n\t\t\t\tproblemFaces.insert(i);\n\t\t}\n\t}\n\n\tnonzeroamps = F.rows() - problemFaces.size();\n\n\tstd::vector<int> nonzero2old(nonzeroamps);\n\tEigen::MatrixXi nonzeroF(nonzeroamps, 3);\n\tEigen::MatrixXi zeroF(F.rows() - nonzeroamps, 3);\n\tstd::vector<int> zero2old(F.rows() - nonzeroamps);\n\n\tint nzidx = 0;\n\tint zidx = 0;\n\tfor (int i = 0; i < F.rows(); i++)\n\t{\n\t\tif (problemFaces.find(i) == problemFaces.end())\n\t\t{\n\t\t\tnonzeroF.row(nzidx) = F.row(i);\n\t\t\tnonzero2old[nzidx] = i;\n\t\t\tnzidx++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tzeroF.row(zidx) = F.row(i);\n\t\t\tzero2old[zidx] = i;\n\t\t\tzidx++;\n\t\t}\n\t}\n\n\tMeshConnectivity origNonZeroMesh(nonzeroF);\n\n\tstd::vector<int> bdryedgecount(V.rows());\n\tfor (int i = 0; i < origNonZeroMesh.nEdges(); i++)\n\t{\n\t\tint face1 = origNonZeroMesh.edgeFace(i, 0);\n\t\tint face2 = origNonZeroMesh.edgeFace(i, 1);\n\t\tif (face1 == -1 || face2 == -1)\n\t\t{\n\t\t\tbdryedgecount[origNonZeroMesh.edgeVertex(i, 0)]++;\n\t\t\tbdryedgecount[origNonZeroMesh.edgeVertex(i, 1)]++;\n\t\t}\n\t}\n\n\tstd::map<int, std::vector<std::pair<int, int> > > nonmanifoldVerts;\n\tfor (int i = 0; i < nonzeroF.rows(); i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tif (bdryedgecount[nonzeroF(i, j)] > 2)\n\t\t\t{\n\t\t\t\tnonmanifoldVerts[nonzeroF(i, j)].push_back({ i,j });\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::vector<std::vector<std::vector<std::pair<int, int> > > > nonmanifoldClusters;\n\tfor (auto& it : nonmanifoldVerts)\n\t{\n\t\tconst auto& cluster = it.second;\n\t\tnonmanifoldClusters.push_back(std::vector<std::vector<std::pair<int, int> > >());\n\t\tint nclusterfaces = cluster.size();\n\t\tstd::map<int, int> face2id;\n\t\tfor (int i = 0; i < nclusterfaces; i++)\n\t\t{\n\t\t\tface2id[cluster[i].first] = i;\n\t\t}\n\t\tstd::vector<bool> visited(nclusterfaces);\n\t\tfor (int i = 0; i < nclusterfaces; i++)\n\t\t{\n\t\t\tif (visited[i])\n\t\t\t\tcontinue;\n\t\t\tstd::deque<int> tovisit;\n\t\t\ttovisit.push_back(i);\n\t\t\tstd::vector<std::pair<int, int> > newcluster;\n\t\t\twhile (!tovisit.empty())\n\t\t\t{\n\t\t\t\tint next = tovisit.front();\n\t\t\t\ttovisit.pop_front();\n\t\t\t\tif (visited[next])\n\t\t\t\t\tcontinue;\n\t\t\t\tvisited[next] = true;\n\t\t\t\tnewcluster.push_back(cluster[next]);\n\t\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t\t{\n\t\t\t\t\tint edge = origNonZeroMesh.faceEdge(cluster[next].first, j);\n\t\t\t\t\tint orient = origNonZeroMesh.faceEdgeOrientation(cluster[next].first, j);\n\t\t\t\t\tint opp = origNonZeroMesh.edgeFace(edge, 1 - orient);\n\t\t\t\t\tif (opp != -1)\n\t\t\t\t\t{\n\t\t\t\t\t\tauto it = face2id.find(opp);\n\t\t\t\t\t\tif (it != face2id.end())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (!visited[it->second])\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttovisit.push_back(it->second);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tnonmanifoldClusters.back().push_back(newcluster);\n\t\t}\n\t}\n\n\tEigen::MatrixXi origNonZeroF = nonzeroF;\n\n\tint freeidx = V.rows();\n\tfor (auto& it : nonmanifoldClusters)\n\t{\n\t\tfor (int i = 1; i < it.size(); i++)\n\t\t{\n\t\t\tfor (auto vf : it[i])\n\t\t\t{\n\t\t\t\tnonzeroF(vf.first, vf.second) = freeidx;\n\t\t\t}\n\t\t\tfreeidx++;\n\t\t}\t\t\n\t}\n\n\tstd::cout << \"Found \" << nonmanifoldVerts.size() << \" nonmanifold vertices \" << std::endl;\n\n\tMeshConnectivity punctmesh(nonzeroF);\n\n\tstd::vector<std::vector<int> > cuts;\n\tfindCuts(nonzeroF, cuts);\n\tstd::cout << \"Used \" << cuts.size() << \" cuts\" << std::endl;\n\n\tstd::map<std::pair<int, int>, int> cutpairs;\n\n\t// convert cuts to edge indices\n\tfor (int i = 0; i < cuts.size(); i++)\n\t{\n\t\tint len = cuts[i].size();\n\t\tfor (int j = 0; j < len - 1; j++)\n\t\t{\n\t\t\tcutpairs[std::pair<int, int>(cuts[i][j], cuts[i][j + 1])] = i;\n\t\t\t//std::cout << cuts[i][j] << \", \";\n\t\t}\n\t}\n\n\tEigen::MatrixXi newF;\n\n\tcutMesh(nonzeroF, cuts, newF);\n\treindex(newF);\n\n\tint newverts = 0;\n\tfor (int i = 0; i < newF.rows(); i++)\n\t\tfor (int j = 0; j < 3; j++)\n\t\t\tnewverts = std::max(newverts, newF(i, j) + 1);\n\n\treindex(zeroF);\n\tint zeroverts = 0;\n\tfor (int i = 0; i < zeroF.rows(); i++)\n\t\tfor (int j = 0; j < 3; j++)\n\t\t\tzeroverts = std::max(zeroverts, zeroF(i, j) + 1);\n\n\tint intdofs = 0;\t\n\n\tstd::vector<Eigen::Triplet<double> > Ccoeffs;\n\n\t// integer constraints on the two sides of the cut\n\tint row = 0;\n\tfor (int i = 0; i < punctmesh.nEdges(); i++)\n\t{\n\t\tint f1 = punctmesh.edgeFace(i, 0);\n\t\tint f2 = punctmesh.edgeFace(i, 1);\n\t\tif (f1 == -1 || f2 == -1)\n\t\t\tcontinue;\n\t\tint v1 = punctmesh.edgeVertex(i, 0);\n\t\tint v2 = punctmesh.edgeVertex(i, 1);\n\t\tdouble sign = 1.0;\n\t\tauto it = cutpairs.find(std::pair<int, int>(v1, v2));\n\t\tif (it == cutpairs.end())\n\t\t{\n\t\t\tit = cutpairs.find(std::pair<int, int>(v2, v1));\n\t\t\tsign = -1.0;\n\t\t}\n\t\tif (it == cutpairs.end())\n\t\t\tcontinue;\n\n\t\tint newv1 = -1;\n\t\tint newv2 = -1;\n\t\tint neww1 = -1;\n\t\tint neww2 = -1;\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tif (nonzeroF(f1, j) == v1)\n\t\t\t\tnewv1 = newF(f1, j);\n\t\t\tif (nonzeroF(f2, j) == v1)\n\t\t\t\tnewv2 = newF(f2, j);\n\t\t\tif (nonzeroF(f1, j) == v2)\n\t\t\t\tneww1 = newF(f1, j);\n\t\t\tif (nonzeroF(f2, j) == v2)\n\t\t\t\tneww2 = newF(f2, j);\n\t\t}\n\n\t\tCcoeffs.push_back(Eigen::Triplet<double>(row, newv1, sign));\n\t\tCcoeffs.push_back(Eigen::Triplet<double>(row, newv2, -sign));\n\t\tCcoeffs.push_back(Eigen::Triplet<double>(row, newverts + intdofs, 1.0));\n\t\tCcoeffs.push_back(Eigen::Triplet<double>(row + 1, neww1, sign));\n\t\tCcoeffs.push_back(Eigen::Triplet<double>(row + 1, neww2, -sign));\n\t\tCcoeffs.push_back(Eigen::Triplet<double>(row + 1, newverts + intdofs, 1.0));\n\t\trow += 2;\n\t\tintdofs++;\n\t}\n\n\t// add integer jumps for non-manifold vertices that connect the same connected component to itself\n\n\tstd::vector<int> parent(newverts);\n\tfor (int i = 0; i < newverts; i++)\n\t\tparent[i] = i;\n\n\tfor (int i = 0; i < newF.rows(); i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tint idx1 = newF(i, j);\n\t\t\tint idx2 = newF(i, (j + 1) % 3);\n\t\t\twhile (parent[idx1] != idx1)\n\t\t\t\tidx1 = parent[idx1];\n\t\t\twhile (parent[idx2] != idx2)\n\t\t\t\tidx2 = parent[idx2];\n\t\t\tif (idx1 != idx2)\n\t\t\t{\n\t\t\t\t// union\n\t\t\t\tparent[idx2] = idx1;\n\t\t\t}\n\t\t}\n\t}\n\n\tint redundantManiJumps = 0;\n\tint essentialManiJumps = 0;\n\n\tfor (auto &it : nonmanifoldClusters)\n\t{\n\t\tint nclusters = it.size();\t\t\n\t\tassert(nclusters > 1);\n\t\tint basef = it[0][0].first;\n\t\tint basev = it[0][0].second;\n\n\t\tfor (int j = 1; j < nclusters; j++)\n\t\t{\n\t\t\tint newv1 = newF(basef, basev);\n\t\t\tint newv2 = newF(it[j][0].first, it[j][0].second);\n\n\t\t\tint idx1 = newv1;\n\t\t\tint idx2 = newv2;\n\t\t\twhile (parent[idx1] != idx1)\n\t\t\t\tidx1 = parent[idx1];\n\t\t\twhile (parent[idx2] != idx2)\n\t\t\t\tidx2 = parent[idx2];\n\t\t\tif (idx1 == idx2)\n\t\t\t{\n\t\t\t\tessentialManiJumps++;\n\t\t\t\tCcoeffs.push_back({ row, newv1, 1.0 });\n\t\t\t\tCcoeffs.push_back({ row, newv2, -1.0 });\n\t\t\t\tCcoeffs.push_back({ row, newverts + intdofs, 1.0 });\n\t\t\t\trow++;\n\t\t\t\tintdofs++;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// integer jump not needed; force 0\n\t\t\t\tredundantManiJumps++;\n\t\t\t\tparent[idx2] = idx1;\n\t\t\t\tCcoeffs.push_back({ row, newv1, 1.0 });\n\t\t\t\tCcoeffs.push_back({ row, newv2, -1.0 });\n\t\t\t\trow++;\n\t\t\t}\n\t\t}\n\t}\n\tEigen::SparseMatrix<double> C(row, newverts + intdofs + 1);\n\tC.setFromTriplets(Ccoeffs.begin(), Ccoeffs.end());\n\n\tstd::cout << \"For non-manifold vertices, added \" << essentialManiJumps << \" integer jumps and \" << redundantManiJumps << \" zero-jumps\" << std::endl;\n\n\tstd::vector<Eigen::Triplet<double> > Acoeffs;\n\tint newfaces = newF.rows();\n\t//assert(newfaces == punctF.rows());\n\n\tfor (int i = 0; i < newfaces; i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tAcoeffs.push_back(Eigen::Triplet<double>(3 * i + j, newF(i, j), 1.0));\n\t\t}\n\t}\n\tEigen::SparseMatrix<double> A(3 * newfaces, newverts + intdofs);\n\tA.setFromTriplets(Acoeffs.begin(), Acoeffs.end());\n\n\tstd::vector<Eigen::Triplet<double> > L2Minvcoeffs;\n\tfor (int i = 0; i < newfaces; i++)\n\t{\n\t\tdouble area = 0.5 * std::sqrt(abars[nonzero2old[i]].determinant());\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\t//double avamp = 0.5 * (amp[F(nonzero2old[i], (j + 1) % 3)] + amp[F(nonzero2old[i], (j + 2) % 3)]);\n\t\t\t//L2Minvcoeffs.push_back(Eigen::Triplet<double>(3 * i + j, 3 * i + j, area * avamp));\n\t\t\tL2Minvcoeffs.push_back(Eigen::Triplet<double>(3 * i + j, 3 * i + j, area));\n\t\t}\n\t}\n\tEigen::SparseMatrix<double> L2Minv(3 * newfaces, 3 * newfaces);\n\tL2Minv.setFromTriplets(L2Minvcoeffs.begin(), L2Minvcoeffs.end());\n\n\n\n\tstd::vector<Eigen::Triplet<double> > Dcoeffs;\n\tfor (int i = 0; i < newfaces; i++)\n\t{\n\t\tDcoeffs.push_back(Eigen::Triplet<double>(3 * i, 3 * i + 2, 1.0));\n\t\tDcoeffs.push_back(Eigen::Triplet<double>(3 * i, 3 * i + 1, -1.0));\n\t\tDcoeffs.push_back(Eigen::Triplet<double>(3 * i + 1, 3 * i, 1.0));\n\t\tDcoeffs.push_back(Eigen::Triplet<double>(3 * i + 1, 3 * i + 2, -1.0));\n\t\tDcoeffs.push_back(Eigen::Triplet<double>(3 * i + 2, 3 * i + 1, 1.0));\n\t\tDcoeffs.push_back(Eigen::Triplet<double>(3 * i + 2, 3 * i, -1.0));\n\t}\n\tEigen::SparseMatrix<double> D(3 * newfaces, 3 * newfaces);\n\tD.setFromTriplets(Dcoeffs.begin(), Dcoeffs.end());\n\n\tEigen::SparseMatrix<double> Mat = A.transpose() * D.transpose() * L2Minv * D * A;\n\n\tEigen::VectorXd punctfield(3 * newfaces);\n\tfor (int i = 0; i < newfaces; i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tint edgeidx = mesh.faceEdge(nonzero2old[i], j);\n\t\t\tdouble sign = (mesh.faceEdgeOrientation(nonzero2old[i], j) == 0 ? 1.0 : -1.0);\n\t\t\tpunctfield[3 * i + j] = dPhi[edgeidx] * sign / 2.0 / PI;\n\t\t}\n\t}\n\tEigen::VectorXd rhs = A.transpose() * D.transpose() * L2Minv * punctfield;\n\n\tEigen::VectorXd result;\n\tEigen::VectorXi toRound(intdofs);\n\tfor (int i = 0; i < intdofs; i++)\n\t{\n\t\ttoRound[i] = newverts + i;\n\t}\n\tstd::cout << intdofs << \" integer variables\" << std::endl;\n\tstd::cout << roundType << std::endl;\n\tif(roundType == ComisoRound)\n\t{\n\t\tstd::cout << \"Comiso round\" << std::endl;\n\t\tComisoWrapper(C, Mat, result, rhs, toRound, 1e-6);\n\t}\n\t\t\n\telse\n\t{\n\t\tstd::cout << \"Gurobi round\" << std::endl;\n\t\tGurobiMIPWrapper(C, Mat, result, rhs, toRound, 1e-6);\n\t}\n\t\t\n\tstd::cout << \"Solver residual: \" << (Mat * result - rhs).norm() << std::endl;\n\tstd::cout << \"Reconstruction residual: \" << (D * A * result - punctfield).transpose() * L2Minv * (D * A * result - punctfield) << std::endl;\n\tstd::cout << \"Integer jumps: \";\n\tfor (int i = 0; i < intdofs; i++)\n\t\tstd::cout << result[newverts + i] << \" \";\n\tstd::cout << std::endl;\n\n\t// map phi back to the original mesh\n\tint oldverts = V.rows();\n\tphi.resize(oldverts);\n\tphi.setZero();\n\tfor (int i = 0; i < newfaces; i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tphi[origNonZeroF(i, j)] = 2.0 * PI * result[newF(i, j)];\n\t\t}\n\t}\n\n\tseamedV.resize(newverts + zeroverts, 3);\n\n\t// construct new position\n\tfor (int i = 0; i < newfaces; i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tseamedV.row(newF(i, j)) = V.row(origNonZeroF(i, j));\n\t\t}\n\t}\n\n\tfor (int i = 0; i < zeroF.rows(); i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tseamedV.row(newverts + zeroF(i, j)) = V.row(F(zero2old[i], j));\n\t\t}\n\t}\n\n\tseamedF.resize(F.rows(), 3);\n\tfor (int i = 0; i < newfaces; i++)\n\t{\n\t\tseamedF.row(nonzero2old[i]) = newF.row(i);\n\t}\n\tfor (int i = 0; i < zeroF.rows(); i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tseamedF(zero2old[i], j) = newverts + zeroF(i, j);\n\t\t}\n\t}\n\n\t// construct new phi and amp with the seam\n\tseamedPhi.resize(newverts + zeroverts);\n\tseamedAmp.resize(newverts + zeroverts);\n\tseamedPhi.setZero();\n\tseamedAmp.setZero();\n\tstd::set<int> freeDOFs;\n\tfor (int i = 0; i < newfaces; i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tseamedPhi(newF(i, j)) = 2.0 * PI * result(newF(i, j));\n\t\t\tseamedAmp(newF(i, j)) = amp(origNonZeroF(i, j));\n\t\t}\n\t}\n\n\tfor (int i = 0; i < zeroF.rows(); i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\t//seamedAmp(newverts + zeroF(i, j)) = amp(F(zero2old[i], j));\n\t\t\tseamedAmp(newverts + zeroF(i, j)) = 0;\n\t\t}\n\t}\n\t//igl::writeOBJ(\"../cut.obj\", seamedV, seamedF);\n}\n\nvoid roundPhiFromOmegaCutbyTension(\n\tconst Eigen::MatrixXd& V,\n\tconst Eigen::MatrixXi& F,\n\tEigen::MatrixXd& seamedV,\n\tEigen::MatrixXi& seamedF,\n\tconst std::vector<Eigen::Matrix2d>& abars,\n\tconst Eigen::VectorXd& amp,\n\tconst Eigen::MatrixXd& w, // |F| x 2 one-form in the barycentric basis, i.e. w.row(i){1,0} is the integral of w along edge (0,1) of the ith face\n\tEigen::VectorXd& phi,\n\tEigen::VectorXd& seamedPhi,\n\tEigen::VectorXd& seamedAmp,\n\tstd::set<int>& problemFaces,\n\tbool isRecomputeProbF)\n{\n\tMeshConnectivity mesh(F);\n\tint nonzeroamps = 0;\n\n\tif (isRecomputeProbF || problemFaces.size() == 0)\n\t{\n\t\tproblemFaces.clear();\n\t\tlocatePotentialPureTensionFaces(abars, V, F, problemFaces);\t// by default, pure tension faces have zero amplitudes\n\n\n\t\tfor (int i = 0; i < F.rows(); i++)\n\t\t{\n\t\t\tbool isZeroFace = true;\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tif (amp(F(i, j)) > 0)\n\t\t\t\t\tisZeroFace = false;\n\t\t\t}\n\t\t\tif (isZeroFace)\n\t\t\t{\n\t\t\t\tproblemFaces.insert(i);\n\t\t\t}\n\t\t}\n\t}\n\t\n\n\tnonzeroamps = F.rows() - problemFaces.size();\n\n\tstd::vector<int> nonzero2old(nonzeroamps);\n\tEigen::MatrixXi nonzeroF(nonzeroamps, 3);\n\tEigen::MatrixXi zeroF(F.rows() - nonzeroamps, 3);\n\tstd::vector<int> zero2old(F.rows() - nonzeroamps);\n\n\tint nzidx = 0;\n\tint zidx = 0;\n\tfor (int i = 0; i < F.rows(); i++)\n\t{\n\t\tif (problemFaces.find(i) == problemFaces.end())\n\t\t{\n\t\t\tnonzeroF.row(nzidx) = F.row(i);\n\t\t\tnonzero2old[nzidx] = i;\n\t\t\tnzidx++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tzeroF.row(zidx) = F.row(i);\n\t\t\tzero2old[zidx] = i;\n\t\t\tzidx++;\n\t\t}\n\t}\n\n\tMeshConnectivity origNonZeroMesh(nonzeroF);\n\n\tstd::vector<int> bdryedgecount(V.rows());\n\tfor (int i = 0; i < origNonZeroMesh.nEdges(); i++)\n\t{\n\t\tint face1 = origNonZeroMesh.edgeFace(i, 0);\n\t\tint face2 = origNonZeroMesh.edgeFace(i, 1);\n\t\tif (face1 == -1 || face2 == -1)\n\t\t{\n\t\t\tbdryedgecount[origNonZeroMesh.edgeVertex(i, 0)]++;\n\t\t\tbdryedgecount[origNonZeroMesh.edgeVertex(i, 1)]++;\n\t\t}\n\t}\n\n\tstd::map<int, std::vector<std::pair<int, int> > > nonmanifoldVerts;\n\tfor (int i = 0; i < nonzeroF.rows(); i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tif (bdryedgecount[nonzeroF(i, j)] > 2)\n\t\t\t{\n\t\t\t\tnonmanifoldVerts[nonzeroF(i, j)].push_back({ i,j });\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::vector<std::vector<std::vector<std::pair<int, int> > > > nonmanifoldClusters;\n\tfor (auto& it : nonmanifoldVerts)\n\t{\n\t\tconst auto& cluster = it.second;\n\t\tnonmanifoldClusters.push_back(std::vector<std::vector<std::pair<int, int> > >());\n\t\tint nclusterfaces = cluster.size();\n\t\tstd::map<int, int> face2id;\n\t\tfor (int i = 0; i < nclusterfaces; i++)\n\t\t{\n\t\t\tface2id[cluster[i].first] = i;\n\t\t}\n\t\tstd::vector<bool> visited(nclusterfaces);\n\t\tfor (int i = 0; i < nclusterfaces; i++)\n\t\t{\n\t\t\tif (visited[i])\n\t\t\t\tcontinue;\n\t\t\tstd::deque<int> tovisit;\n\t\t\ttovisit.push_back(i);\n\t\t\tstd::vector<std::pair<int, int> > newcluster;\n\t\t\twhile (!tovisit.empty())\n\t\t\t{\n\t\t\t\tint next = tovisit.front();\n\t\t\t\ttovisit.pop_front();\n\t\t\t\tif (visited[next])\n\t\t\t\t\tcontinue;\n\t\t\t\tvisited[next] = true;\n\t\t\t\tnewcluster.push_back(cluster[next]);\n\t\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t\t{\n\t\t\t\t\tint edge = origNonZeroMesh.faceEdge(cluster[next].first, j);\n\t\t\t\t\tint orient = origNonZeroMesh.faceEdgeOrientation(cluster[next].first, j);\n\t\t\t\t\tint opp = origNonZeroMesh.edgeFace(edge, 1 - orient);\n\t\t\t\t\tif (opp != -1)\n\t\t\t\t\t{\n\t\t\t\t\t\tauto it = face2id.find(opp);\n\t\t\t\t\t\tif (it != face2id.end())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (!visited[it->second])\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttovisit.push_back(it->second);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tnonmanifoldClusters.back().push_back(newcluster);\n\t\t}\n\t}\n\n\tEigen::MatrixXi origNonZeroF = nonzeroF;\n\n\tint freeidx = V.rows();\n\tfor (auto& it : nonmanifoldClusters)\n\t{\n\t\tfor (int i = 1; i < it.size(); i++)\n\t\t{\n\t\t\tfor (auto vf : it[i])\n\t\t\t{\n\t\t\t\tnonzeroF(vf.first, vf.second) = freeidx;\n\t\t\t}\n\t\t\tfreeidx++;\n\t\t}\n\t}\n\n\tstd::cout << \"Found \" << nonmanifoldVerts.size() << \" nonmanifold vertices \" << std::endl;\n\n\tMeshConnectivity punctmesh(nonzeroF);\n\n\tstd::vector<std::vector<int> > cuts;\n\tfindCuts(nonzeroF, cuts);\n\tstd::cout << \"Used \" << cuts.size() << \" cuts\" << std::endl;\n\n\tstd::map<std::pair<int, int>, int> cutpairs;\n\n\t// convert cuts to edge indices\n\tfor (int i = 0; i < cuts.size(); i++)\n\t{\n\t\tint len = cuts[i].size();\n\t\tfor (int j = 0; j < len - 1; j++)\n\t\t{\n\t\t\tcutpairs[std::pair<int, int>(cuts[i][j], cuts[i][j + 1])] = i;\n\t\t\t//std::cout << cuts[i][j] << \", \";\n\t\t}\n\t}\n\n\tEigen::MatrixXi newF;\n\n\tcutMesh(nonzeroF, cuts, newF);\n\treindex(newF);\n\n\tint newverts = 0;\n\tfor (int i = 0; i < newF.rows(); i++)\n\t\tfor (int j = 0; j < 3; j++)\n\t\t\tnewverts = std::max(newverts, newF(i, j) + 1);\n\n\treindex(zeroF);\n\tint zeroverts = 0;\n\tfor (int i = 0; i < zeroF.rows(); i++)\n\t\tfor (int j = 0; j < 3; j++)\n\t\t\tzeroverts = std::max(zeroverts, zeroF(i, j) + 1);\n\n\tint intdofs = 0;\n\n\tstd::vector<Eigen::Triplet<double> > Ccoeffs;\n\n\t// integer constraints on the two sides of the cut\n\tint row = 0;\n\tfor (int i = 0; i < punctmesh.nEdges(); i++)\n\t{\n\t\tint f1 = punctmesh.edgeFace(i, 0);\n\t\tint f2 = punctmesh.edgeFace(i, 1);\n\t\tif (f1 == -1 || f2 == -1)\n\t\t\tcontinue;\n\t\tint v1 = punctmesh.edgeVertex(i, 0);\n\t\tint v2 = punctmesh.edgeVertex(i, 1);\n\t\tdouble sign = 1.0;\n\t\tauto it = cutpairs.find(std::pair<int, int>(v1, v2));\n\t\tif (it == cutpairs.end())\n\t\t{\n\t\t\tit = cutpairs.find(std::pair<int, int>(v2, v1));\n\t\t\tsign = -1.0;\n\t\t}\n\t\tif (it == cutpairs.end())\n\t\t\tcontinue;\n\n\t\tint newv1 = -1;\n\t\tint newv2 = -1;\n\t\tint neww1 = -1;\n\t\tint neww2 = -1;\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tif (nonzeroF(f1, j) == v1)\n\t\t\t\tnewv1 = newF(f1, j);\n\t\t\tif (nonzeroF(f2, j) == v1)\n\t\t\t\tnewv2 = newF(f2, j);\n\t\t\tif (nonzeroF(f1, j) == v2)\n\t\t\t\tneww1 = newF(f1, j);\n\t\t\tif (nonzeroF(f2, j) == v2)\n\t\t\t\tneww2 = newF(f2, j);\n\t\t}\n\n\t\tCcoeffs.push_back(Eigen::Triplet<double>(row, newv1, sign));\n\t\tCcoeffs.push_back(Eigen::Triplet<double>(row, newv2, -sign));\n\t\tCcoeffs.push_back(Eigen::Triplet<double>(row, newverts + intdofs, 1.0));\n\t\tCcoeffs.push_back(Eigen::Triplet<double>(row + 1, neww1, sign));\n\t\tCcoeffs.push_back(Eigen::Triplet<double>(row + 1, neww2, -sign));\n\t\tCcoeffs.push_back(Eigen::Triplet<double>(row + 1, newverts + intdofs, 1.0));\n\t\trow += 2;\n\t\tintdofs++;\n\t}\n\tfor (auto& it : nonmanifoldClusters)\n\t{\n\t\tint nclusters = it.size();\n\t\tassert(nclusters > 1);\n\t\tint basef = it[0][0].first;\n\t\tint basev = it[0][0].second;\n\n\t\tfor (int j = 1; j < nclusters; j++)\n\t\t{\n\t\t\tint newv1 = newF(basef, basev);\n\t\t\tint newv2 = newF(it[j][0].first, it[j][0].second);\n\t\t\tCcoeffs.push_back({ row, newv1, 1.0 });\n\t\t\tCcoeffs.push_back({ row, newv2, -1.0 });\n\t\t\tCcoeffs.push_back({ row, newverts + intdofs, 1.0 });\n\t\t\trow++;\n\t\t\tintdofs++;\n\t\t}\n\t}\n\tEigen::SparseMatrix<double> C(row, newverts + intdofs + 1);\n\tC.setFromTriplets(Ccoeffs.begin(), Ccoeffs.end());\n\n\tstd::vector<Eigen::Triplet<double> > Acoeffs;\n\tint newfaces = newF.rows();\n\t//assert(newfaces == punctF.rows());\n\n\tfor (int i = 0; i < newfaces; i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tAcoeffs.push_back(Eigen::Triplet<double>(3 * i + j, newF(i, j), 1.0));\n\t\t}\n\t}\n\tEigen::SparseMatrix<double> A(3 * newfaces, newverts + intdofs);\n\tA.setFromTriplets(Acoeffs.begin(), Acoeffs.end());\n\n\tstd::vector<Eigen::Triplet<double> > L2Minvcoeffs;\n\tfor (int i = 0; i < newfaces; i++)\n\t{\n\t\tdouble area = 0.5 * std::sqrt(abars[nonzero2old[i]].determinant());\n\t\tfor (int j = 0; j < 2; j++)\n\t\t{\n\t\t\t//double avamp = 0.5 * (amp[F(nonzero2old[i], (j + 1) % 3)] + amp[F(nonzero2old[i], (j + 2) % 3)]);\n\t\t\t//L2Minvcoeffs.push_back(Eigen::Triplet<double>(3 * i + j, 3 * i + j, area * avamp));\n\t\t\tL2Minvcoeffs.push_back(Eigen::Triplet<double>(2 * i + j, 2 * i + j, area));\n\t\t}\n\t}\n\tEigen::SparseMatrix<double> L2Minv(2 * newfaces, 2 * newfaces);\n\tL2Minv.setFromTriplets(L2Minvcoeffs.begin(), L2Minvcoeffs.end());\n\n\n\n\tstd::vector<Eigen::Triplet<double> > Dcoeffs;\n\tfor (int i = 0; i < newfaces; i++)\n\t{\n\t\tDcoeffs.push_back(Eigen::Triplet<double>(2 * i, 3 * i + 1, 1.0));\n\t\tDcoeffs.push_back(Eigen::Triplet<double>(2 * i, 3 * i, -1.0));\n\t\tDcoeffs.push_back(Eigen::Triplet<double>(2 * i + 1, 3 * i + 2, 1.0));\n\t\tDcoeffs.push_back(Eigen::Triplet<double>(2 * i + 1, 3 * i, -1.0));\n\t}\n\n\tEigen::SparseMatrix<double> D(2 * newfaces, 3 * newfaces);\n\tD.setFromTriplets(Dcoeffs.begin(), Dcoeffs.end());\n\n\tEigen::SparseMatrix<double> Mat = A.transpose() * D.transpose() * L2Minv * D * A;\n\tEigen::VectorXd punctfield(2 * newfaces);\n\tfor (int i = 0; i < newfaces; i++)\n\t{\n\t\tfor (int j = 0; j < 2; j++)\n\t\t{\n\t\t\tpunctfield[2 * i + j] = w(nonzero2old[i], j) / 2.0 / PI;\n\t\t}\n\t}\n\n\tEigen::VectorXd rhs = A.transpose() * D.transpose() * L2Minv * punctfield;\n\n\tEigen::VectorXd result;\n\tEigen::VectorXi toRound(intdofs);\n\tfor (int i = 0; i < intdofs; i++)\n\t{\n\t\ttoRound[i] = newverts + i;\n\t}\n\n\tstd::cout << intdofs << \" integer variables\" << std::endl;\n\tComisoWrapper(C, Mat, result, rhs, toRound, 1e-6);\n\tstd::cout << \"Solver residual: \" << (Mat * result - rhs).norm() << std::endl;\n\tstd::cout << \"Reconstruction residual: \" << (D * A * result - punctfield).transpose() * L2Minv * (D * A * result - punctfield) << std::endl;\n\tstd::cout << \"Integer jumps: \";\n\tfor (int i = 0; i < intdofs; i++)\n\t\tstd::cout << result[newverts + i] << \" \";\n\tstd::cout << std::endl;\n\n\t// map phi back to the original mesh\n\tint oldverts = V.rows();\n\tphi.resize(oldverts);\n\tphi.setZero();\n\tfor (int i = 0; i < newfaces; i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tphi[origNonZeroF(i, j)] = 2.0 * PI * result[newF(i, j)];\n\t\t}\n\t}\n\n\tseamedV.resize(newverts + zeroverts, 3);\n\n\t// construct new position\n\tfor (int i = 0; i < newfaces; i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tseamedV.row(newF(i, j)) = V.row(origNonZeroF(i, j));\n\t\t}\n\t}\n\n\tfor (int i = 0; i < zeroF.rows(); i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tseamedV.row(newverts + zeroF(i, j)) = V.row(F(zero2old[i], j));\n\t\t}\n\t}\n\n\tseamedF.resize(F.rows(), 3);\n\tfor (int i = 0; i < newfaces; i++)\n\t{\n\t\tseamedF.row(nonzero2old[i]) = newF.row(i);\n\t}\n\tfor (int i = 0; i < zeroF.rows(); i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tseamedF(zero2old[i], j) = newverts + zeroF(i, j);\n\t\t}\n\t}\n\n\t// construct new phi and amp with the seam\n\tseamedPhi.resize(newverts + zeroverts);\n\tseamedAmp.resize(newverts + zeroverts);\n\tseamedPhi.setZero();\n\tseamedAmp.setZero();\n\tstd::set<int> freeDOFs;\n\tfor (int i = 0; i < newfaces; i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tseamedPhi(newF(i, j)) = 2.0 * PI * result(newF(i, j));\n\t\t\tseamedAmp(newF(i, j)) = amp(origNonZeroF(i, j));\n\t\t}\n\t}\n\n\tfor (int i = 0; i < zeroF.rows(); i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\t//seamedAmp(newverts + zeroF(i, j)) = amp(F(zero2old[i], j));\n\t\t\tseamedAmp(newverts + zeroF(i, j)) = 0;\n\t\t}\n\t}\n}", "meta": {"hexsha": "5715cb4b815f45a320b0cdf2e1caa8f25ac7f074", "size": 71755, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "WTFShell/PhiEstimate.cpp", "max_stars_repo_name": "csyzzkdcz/effective-garbanzo", "max_stars_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WTFShell/PhiEstimate.cpp", "max_issues_repo_name": "csyzzkdcz/effective-garbanzo", "max_issues_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WTFShell/PhiEstimate.cpp", "max_forks_repo_name": "csyzzkdcz/effective-garbanzo", "max_forks_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_forks_repo_licenses": ["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.3282739146, "max_line_length": 235, "alphanum_fraction": 0.5962929413, "num_tokens": 25277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.29026507221653597}}
{"text": "/* This software and supporting documentation are distributed by\n *     Institut Federatif de Recherche 49\n *     CEA/NeuroSpin, Batiment 145,\n *     91191 Gif-sur-Yvette cedex\n *     France\n *\n * This software is governed by the CeCILL-B license under\n * French law and abiding by the rules of distribution of free software.\n * You can  use, modify and/or redistribute the software under the\n * terms of the CeCILL-B license as circulated by CEA, CNRS\n * and INRIA at the following URL \"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-B license and that you accept its terms.\n */\n\n\n// activate deprecation warning\n#ifdef AIMSDATA_CLASS_NO_DEPREC_WARNING\n#undef AIMSDATA_CLASS_NO_DEPREC_WARNING\n#endif\n\n#include <cstdlib>\n#include <aims/mesh/curv.h>\n#include <set>\n#include <algorithm>\n#include <float.h>\n#define use_boost\n#ifdef use_boost\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/operation_sparse.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#if BOOST_VERSION < 103300\ntypedef boost::numeric::ublas::sparse_matrix<float> boost_sparse_matrix;\n#else\ntypedef boost::numeric::ublas::mapped_matrix<float> boost_sparse_matrix;\n#endif\n#endif\n\nusing namespace std;\n\n//All the functions for \n//Curvature and Laplacian estimations\n\nfloat fsign(float x) \n{\n  if (x>0) return(1);\n  else\n    if (x<0) return(-1);\n    else\n      return(0);\n}\n\n \n\n// Cross product between two 3D points\nPoint3df cross(Point3df a, Point3df b)\n{\n  \n  Point3df n;\n  n[0] = a[1]*b[2] - a[2]*b[1];\n  n[1] = a[2]*b[0] - a[0]*b[2];\n  n[2] = a[0]*b[1] - a[1]*b[0];\n  return (n);\n}\n\n\nTimeTexture<float> AimsMeshCurvature( const AimsSurface<3,Void> & mesh)\n{\n  TimeTexture<float>\t\t\t\ttex;\n  const vector<Point3df>\t\t\t& vert = mesh.vertex(), & normal = mesh.normal() ;\n  const vector< AimsVector<uint,3> >\t\t& poly = mesh.polygon();\n  unsigned\t\t\t\t\ti, n = vert.size();\n  vector<float>\t\t\t\t\tbary(n), bary2(n);\n  map<unsigned, set<unsigned> >\t\t\tneighbours;\n  set<unsigned>::iterator \t                inei,enei;\n  unsigned\t\t\t\t\tv1, v2, v3;\n  Point3df\t\t\t\t\ta;\n  \n  //  neighbours map\n\n  for( i=0; i<poly.size(); ++i )\n    {\n      v1 = poly[i][0];\n      v2 = poly[i][1];\n      v3 = poly[i][2];\n     \n      neighbours[v1].insert( v2 );\n      neighbours[v2].insert( v1 );\n      neighbours[v1].insert( v3 );\n      neighbours[v3].insert( v1 );\n      neighbours[v2].insert( v3 );\n      neighbours[v3].insert( v2 );\n      \n    }\n\n\n  //Barycenter and sign \n  for (i=0; i<n; ++i)\n    {\n      a = Point3df(0,0,0) ;\n      bary[i] = 0 ; \n      for (inei = neighbours[i].begin(), enei = neighbours[i].end(); inei != enei; ++inei)\n\ta += vert[*inei];\n      a /= neighbours[i].size(); //barycenter\n      a = vert[i] - a;\n      bary[i] = a.norm() * fsign( a.dot(normal[i]) );\n      bary2[i] = a.dot(normal[i] );\n      tex[0].push_back( bary[i] ); //barycenter\n      //tex[1].push_back( bary[i] );\n      \n    }\n\n  return(tex);\n}\n \n\n\n\n\nTexture<float> AimsMeshBoixCurvature( const AimsSurface<3,Void> & mesh,\n\t\t\t\t      const vector<float> & ALPHA,\n\t\t\t\t      const vector<float> & BETA,\n\t\t\t\t      const vector<list <float> > & SURFACE)\n{\n  const vector<Point3df>\t\t\t& vert = mesh.vertex() ;\n  unsigned\t\t\t\t\ti, n = vert.size();\n  Texture<float>\t\t\t\ttex(n);\n  float                                         H,nume,deno,aire;\n  list <float>::const_iterator              il,el;\n \n  for (i=0; i<n; ++i)\n    {\n      nume = BETA[i];\n      aire = 0;\n      for (il = SURFACE[i].begin(), el = SURFACE[i].end(); il != el; ++il)\n\taire += *il;\n\n      deno = (aire * 0.5 + ALPHA[i] );\n      H = nume / deno;\n      tex.item(i) = H;\n    }\n\n  return(tex);\n}\n \n\nTexture<float> AimsMeshFiniteElementCurvature( const AimsSurface<3,Void> & mesh,\n\t\t\t\t\t       const vector< list<unsigned> > & neighbourso,\n\t\t\t\t\t       const vector< list<float> > & PHI,\n\t\t\t\t\t       const vector< list<float> > & THETA,\n\t\t\t\t\t       const vector< list<float> > & SURFACE,\n\t\t\t\t\t       const vector< list<float> > & DOT)\n{\n  const vector<Point3df>\t\t\t& vert = mesh.vertex() ;\n  unsigned\t\t\t\t\ti, n = vert.size();\n  Texture<float>\t\t\t\ttex(n);\n  list<unsigned>::const_iterator\t\tilist,elist;\n  list<float>::const_iterator\t\t        iphi,idot,itheta,isurf;\n  unsigned\t\t\t\t\t/*nb,*/s,p,d,t;\t\n  float \t\t\t\t\tK,surface;\n  \n  for (i=0; i<n; ++i)\n    {\n      s = SURFACE[i].size();\n      p = PHI[i].size();\n      t = THETA[i].size();\n      d = DOT[i].size();\n      //nb = neighbourso[i].size() ;\n      if ( !( s == p && s == t && s == d && p==t && p==d && t==d ) )\n\t{\n\t  cout << \"Problem with the mesh features...\" << endl;\n\t  ASSERT(0);\n\t}\n      K = 0;\n      surface = 0;\n      for ( elist =  neighbourso[i].end(),ilist = neighbourso[i].begin(),\n\t      iphi = PHI[i].begin(),idot = DOT[i].begin(),\n\t      isurf = SURFACE[i].begin(), itheta = THETA[i].begin();\n\t    ilist != elist;++ilist, ++iphi,++itheta,++idot,++isurf )\n\t{\n\t  K +=(*iphi + *itheta)*(*idot);\n\t  surface += *isurf;\n\t  //cout << *iphi << \" \" << *itheta << \" \" <<  *idot << \" \" << *isurf << endl;\n\t}\n      \n     if ( surface != 0 )\n       K = K/(surface * 4);\n     else\n       {\n\t cout << \"Triangle with null surface\\n\";\n\t K = 0;\n       }\n     tex.item(i) = K;\n    }\n\n  return(tex);\n}\n\n\n\n\n\nvector< list<float> > AimsMeshFiniteElementPhi( const AimsSurface<3,Void> & mesh,\n\t\t\t\t\t\tconst vector< list<unsigned> > & neighbourso,\n\t\t\t\t\t\tconst vector< list<float> > & surf)\n{\n  const vector<Point3df>\t\t\t& vert = mesh.vertex() ;\n  unsigned\t\t\t\t\ti, n = vert.size();\n  vector< list<float> >                         PHI(n);//id but triangle are put in order \n  list<unsigned>::iterator        \t\tilist,elist;\n  list<unsigned>::const_iterator        \tel;\n  list<float>::const_iterator        \t        efl,iflist;\n  unsigned\t\t\t\t\tv1, v2;\n  float\t\t\t\t\t\tphi,t;\t\n  vector< list<unsigned> >                     neigho = neighbourso;\n  vector< list<float> >                        surfl = surf;\n  \n  for (i=0; i<n; ++i)\n    {\n      el = neighbourso[i].end();\n      --el;\n      neigho[i].push_front(*el);\n      efl = surf[i].end();\n      --efl;\n      surfl[i].push_front(*efl);\n    }\n  \n  \n  for (i=0; i<n; ++i)\n    {\n      phi = 0;\n      ASSERT(neigho[i].size() == surfl[i].size() );\n      iflist = surfl[i].begin();\n      elist = neigho[i].end();\n      --elist;\n      ilist = neigho[i].begin();\n      while ( ilist != elist ) \n\t{\n\t  v1 = *ilist;\n\t  ++ilist;\n\t  v2 = *ilist;\n\t  t = *iflist;\n\t  ++iflist;\n\t  if (fabs(t) != 0 )\n\t      phi =   ( ( vert[v1] - vert[i] ).dot( vert[v1] - vert[v2]  ) )/(2 * t);\n\t  else\n\t    {\n\t      cout << \"Triangle with a  null surface \\n\"; \n\t      phi = 0;\n\t    }\n\t  PHI[i].push_back(phi);\n\t}\n    }\n\n  return(PHI);\n}\n\n\n\n\n\nvector<float> AimsMeshFiniteElementBeta( const AimsSurface<3,Void> & mesh,\n\t\t\t\t\t const vector< list<unsigned> > & neighbourso)\n{\n  const vector<Point3df>\t\t\t& vert = mesh.vertex(), &normal = mesh.normal() ;\n  unsigned\t\t\t\t\ti, n = vert.size();\n  vector<float>                                 BETA(n); \n  list<unsigned>::iterator       \t\tilist,elist;\n  list<unsigned>::const_iterator       \t\til,el;\n  unsigned\t\t\t\t\tv1, v2, v3;\n  float\t\t\t\t\t\tb,nj1n,nj2n;\t\n  Point3df                                      nj1,nj2;\n  vector< list<unsigned> >                      neigho = neighbourso;\n\n  for (i=0; i<n; ++i)\n    {\n      il = neighbourso[i].begin();\n      el = neighbourso[i].end();\n      --el;\n      neigho[i].push_front(*el);\n      neigho[i].push_back(*il);\n    }\n\n  for (i=0; i<n; ++i)\n    {\n      b = 0;\n      elist =  neigho[i].end();\n      --elist;\n      --elist;\n      ilist = neigho[i].begin();\n      while ( ilist != elist ) \n\t{\n\t  v1 = *ilist;\n\t  ++ilist;\n\t  v2 = *ilist;\n\t  ++ilist;\n\t  v3 = *ilist;\n\t  --ilist;\n\t  nj1 = (normal[i] + normal[v1] + normal[v2]);\n\t  nj2 = (normal[i] + normal[v3] + normal[v2]);\n\t  nj1n = nj1.norm();\n\t  nj2n = nj2.norm();\n\t  if (nj1n  != 0 &&  nj2n != 0)\n\t    {\n\t      nj2 /= nj2n;\n\t      nj1 /= nj1n;\n\t      if (nj1.dot(nj2) != 1)\n\t\tb += (vert[v2] - vert[i]).norm() * acos( (double)nj1.dot(nj2) );\n\t      \n\n\t    }\n\t  else\n\t    cout << \"Triangle of size null\\n\";\n\t    \n\t}\n      BETA[i] = 0.25 * b;\n    }\n\n  return(BETA);\n}\n\n\n\n\n\nvector<float> AimsMeshFiniteElementAlpha( const AimsSurface<3,Void> & mesh,\n\t\t\t\t\t  const vector< list<unsigned> > & neighbourso)\n{\n  const vector<Point3df>\t\t\t& vert = mesh.vertex() ;\n  unsigned\t\t\t\t\ti, n = vert.size();\n  vector<float>                                 ALPHA(n); \n  list<unsigned>::iterator       \t\tilist,elist;\n  unsigned\t\t\t\t\tv1, v2;\n  float\t\t\t\t\t\ta,t;\t\n  Point3df                                      nj1,nj2;\n  vector< list<unsigned> >                      neigho = neighbourso;\n\n  for (i=0; i<n; ++i)\n    neigho[i].push_front(*neigho[i].rbegin());//the first element is the last one (circular)\n  \n  for (i=0; i<n; ++i)\n    {\n      a = 0;\n      elist =  neigho[i].end();\n      --elist;\n      ilist = neigho[i].begin();\n      while ( ilist != elist ) \n\t{\n\t  v1 = *ilist;\n\t  ++ilist;\n\t  v2 = *ilist;\n\t  nj1 = (vert[i] - vert[v2]);\n\t  nj2 = (vert[i] - vert[v1]);\n\t  t = 0.5 * fabs(cross(nj1,nj2).norm());\n\t  if ( t != 0)\n\t    a +=(vert[v1] - vert[v2]).norm2() * nj1.dot(nj2)/(2*t);\n\t}\n       ALPHA[i] = -a/8;\n    }\n\n  return(ALPHA);\n}\n\n\n\n\n\n\nvector< list<float> > AimsMeshFiniteElementDot( const AimsSurface<3,Void> & mesh,\n\t\t\t\t\t\tconst vector< list<unsigned> > & neighbourso)\n{\n \n  const vector<Point3df>\t\t\t& vert = mesh.vertex(), & normal = mesh.normal() ;\n  unsigned\t\t\t\t\ti, n = vert.size();\n  vector< list<float> >                         DOT(n);\n  list<unsigned>::const_iterator\t\tilist,elist;\n\n  for (i=0; i<n; ++i)\n    for (ilist = neighbourso[i].begin(),elist =  neighbourso[i].end(); ilist != elist ; ++ilist) \n      DOT[i].push_back(normal[i].dot( - vert[*ilist] + vert[i]) );\n  //DOT[i].push_back(normal[i].dot( vert[*ilist] - vert[i]) ); //BUG in CHUNG paper ?! YES : SEE ref. Desbrun99\n\n  return(DOT);\n}\n\n\n\n\n\n\nvector< list<float> > AimsMeshFiniteElementTheta( const AimsSurface<3,Void> & mesh,\n\t\t\t\t\t\t  const vector< list<unsigned> > & neighbourso,\n\t\t\t\t\t\t  const vector< list<float> > & surf)\n{\n  const vector<Point3df>\t\t\t& vert = mesh.vertex() ;\n  unsigned\t\t\t\t\ti, n = vert.size();\n  vector< list<float> >                         THETA(n);\n  list<float>::const_iterator\t\t        il;\n  list<unsigned>::iterator       \t\tilist,elist;\n  unsigned\t\t\t\t\tv1, v2;\n  float\t\t\t\t\t\ttheta,t;\t\n  vector< list<unsigned> >                      neigho = neighbourso;\n  vector< list<float> >                         surfl=surf;\n\n  for (i=0; i<n; ++i)//the first element is the same as the last one (circular)\n    {\n      neigho[i].push_back(*neighbourso[i].begin());\n      surfl[i].push_back(*surf[i].begin());\n    }\n  \n  for (i=0; i<n; ++i)\n    {\n      theta = 0;\n      il = surfl[i].begin();      \n      elist =  neigho[i].end();\n      --elist;\n      ilist = neigho[i].begin();\n      ASSERT(neigho[i].size() == surfl[i].size() );\n      while ( ilist != elist ) \n\t{\n\t  v1 = *ilist; \n\t  ++ilist;\n\t  v2 = *ilist;\n\t  t = *il;\n\t  ++il;\n\t  if (fabs(t)  != 0)\n\t    theta = ( ( vert[v2] - vert[i] ).dot( vert[v2] - vert[v1]  ) )/(2 * t);\n\t  else\n\t    {\n\t      cout << \"Triangle with null surface \\n\"; \n\t      theta = 0;\n\t    }\n\t  THETA[i].push_back(theta);\n\t}\n    }\n\n  return(THETA);\n}\n\n\n//ie the sum of all the neighbouring triangle surface\nvector< list<float> > AimsMeshFiniteElementSurface( const AimsSurface<3,Void> & mesh,\n\t\t\t\t\t\t    const vector< list<unsigned> > & neighbourso)\n{\n  const vector<Point3df>\t\t\t& vert = mesh.vertex() ;\n  unsigned\t\t\t\t\ti, n = vert.size();\n  vector< list<float> >                         SURFACE(n);\n  list<unsigned>::iterator\t\t\tilist,elist;\n  unsigned\t\t\t\t\tv1, v2;\n  float\t\t\t\t\t\tt;\t\n  vector< list<unsigned> >                      neigho = neighbourso;\n\n  for (i=0; i<n; ++i)\n    neigho[i].push_back(*neighbourso[i].begin());//the first element is the last one (circular)\n\n  for (i=0; i<n; ++i)\n    {\n      elist =  neigho[i].end();\n      --elist;\n      ilist = neigho[i].begin();\n      while ( ilist != elist ) \n\t{\n\t  v1 = *ilist;\n\t  ++ilist;\n\t  v2 = *ilist;\n\t  t = 0.5 * ( cross(vert[v2] - vert[i], vert[v1] - vert[i]).norm() );\n\t  SURFACE[i].push_back(t);\n\t}\n    }\n\n\n  return(SURFACE);\n}\n\n\nvector< list<unsigned> > AimsMeshOrderNode(const AimsSurface<3,Void> & mesh)\n{\n  const vector<Point3df>\t\t\t& vert = mesh.vertex(), & normal = mesh.normal() ;\n  const vector< AimsVector<uint,3> >\t\t& poly = mesh.polygon();\n   unsigned\t\t\t\t\ti,n = vert.size();\n   vector<list<unsigned> >                       neighbourso(n);//id but nodes are put in order\n  vector< list<unsigned> >                      trineigho(n);//id but triangle are put in order\n  list<unsigned>::iterator\t\t\tilist,elist,jlist;\n\n  trineigho = AimsMeshOrderTriangle(mesh);\n\n  for ( i=0; i<n; ++i)\n    {\n      set<unsigned> setinter;\n      insert_iterator<set<unsigned> > ii( setinter,setinter.begin() );\n      elist=trineigho[i].end();\n      --elist;\n      ilist= trineigho[i].begin();\n      set<unsigned> tn1,tn2;\n      tn1.insert(poly[*ilist][0]);\n      tn1.insert(poly[*ilist][1]);\n      tn1.insert(poly[*ilist][2]);\n      //cout << poly[*ilist][0] << \" \" << poly[*ilist][1] << \" \"<< poly[*ilist][2]<< endl;\n      tn1.erase(i);\n      ++ilist;\n      tn2.insert(poly[*ilist][0]);\n      tn2.insert(poly[*ilist][1]);\n      tn2.insert(poly[*ilist][2]);\n      //cout << poly[*ilist][0] << \" \" << poly[*ilist][1] << \" \"<< poly[*ilist][2]<< endl;\n      tn2.erase(i);\n      set_intersection( tn1.begin(),tn1.end(),tn2.begin(),tn2.end(),ii );\n      tn1.erase(*setinter.begin());\n      tn2.erase(*setinter.begin());\n      //cout << \"setinter size: \" << setinter.size() << endl;\n      neighbourso[i].push_back(*tn1.begin() );\n      neighbourso[i].push_back(*setinter.begin());\n      neighbourso[i].push_back(*tn2.begin() );\n      \n      while (ilist != elist)\n\t{\n\t  //cout << \"in loop\" << endl;\n\t  tn1.clear();\n\t  tn2.clear();\n\t  tn1.insert(poly[*ilist][0]);\n\t  tn1.insert(poly[*ilist][1]);\n\t  tn1.insert(poly[*ilist][2]);\n\t  //cout << poly[*ilist][0] << \" \" << poly[*ilist][1] << \" \"<< poly[*ilist][2]<< endl;\n\t  tn1.erase(i);\n\t  ++ilist;\n\t  tn2.insert(poly[*ilist][0]);\n\t  tn2.insert(poly[*ilist][1]);\n\t  tn2.insert(poly[*ilist][2]);\n\t  //cout << poly[*ilist][0] << \" \" << poly[*ilist][1] << \" \"<< poly[*ilist][2]<< endl;\n\t  tn2.erase(i);\n\n\t  setinter.clear();\n\t  insert_iterator<set<unsigned> > jj( setinter,setinter.begin() );\n\t  set_intersection( tn1.begin(),tn1.end(),tn2.begin(),tn2.end(),jj );\n\t  //cout << \"setinter size: \" << setinter.size() << endl;\n\t  tn2.erase(*setinter.begin());\n\t  neighbourso[i].push_back(*tn2.begin() );\n\t}\n    }\n\n  for (i=0; i<n;++i)\n    neighbourso[i].pop_front();//remove the repeated first element\n\n  for (i=0; i<n;++i)\n    {\n      //cout << i << \" \" << neighbourso[i].size() << endl;\n      Point3df nor = normal[i],a,b;\n      //elist=neighbourso[i].end();\n      ilist=neighbourso[i].begin();\n      a = vert[*ilist] - vert[i];\n      jlist = ilist;\n      ++jlist;\n      b = vert[*jlist] - vert[*ilist];\n      if ( cross(a,b).dot(nor) < 0 )//clockwise ordering\n\tneighbourso[i].reverse();\n    }\n  \n \n  return(neighbourso);\n}\n\n\n\n\nvector< list<unsigned> > AimsMeshOrderTriangle(const AimsSurface<3,Void> & mesh)\n{\n  const vector<Point3df>\t\t\t& vert = mesh.vertex() ;\n  const vector< AimsVector<uint,3> >\t\t& poly = mesh.polygon();\n  unsigned\t\t\t\t\ti,j,n = vert.size();\n  unsigned\t\t\t\t\tv1, v2, v3;\n  map<unsigned, set<unsigned> >\t\t\tneighbours;//give for each vertex a list of the  adjacent triangles \n  vector< set <unsigned> >                      trineigh(n); //give for each vertex a list of the  adjacent triangles \n  vector< list<unsigned> >                      trineigho(n);//id but triangle are put in order \n  set<unsigned>::iterator \t                inei,enei;\n\n   //  neighbours map\n\n  for( i=0; i<poly.size(); ++i )\n    {\n      v1 = poly[i][0];\n      v2 = poly[i][1];\n      v3 = poly[i][2];\n     \n      neighbours[v1].insert( v2 );\n      neighbours[v2].insert( v1 );\n      neighbours[v1].insert( v3 );\n      neighbours[v3].insert( v1 );\n      neighbours[v2].insert( v3 );\n      neighbours[v3].insert( v2 );\n      \n      trineigh[v1].insert( i );\n      trineigh[v2].insert( i );\n      trineigh[v3].insert( i );\n    }\n\n  //order neighbour nodes \n  set<unsigned>\t        nodes;\n  set<unsigned>\t\ttmpNodes;\n  bool\t\t\tstopLoop=false;\n  for ( i=0; i<n; ++i)\n    {\n      // cout << i << \" -> \" ;\n      tmpNodes = trineigh[i];\n      inei = tmpNodes.begin();\n      trineigho[i].push_back( *inei );\n      tmpNodes.erase( inei );\n      while ( !tmpNodes.empty() )\n\t{\n\t  enei = tmpNodes.end();\n\t  stopLoop = false;\n\t  for ( inei=tmpNodes.begin(); inei!=enei && !stopLoop; ++inei )\n\t    {\n\t      nodes.clear();\n\t      j = trineigho[i].back();\n\t      nodes.insert(poly[*inei][0]);\n\t      nodes.insert(poly[*inei][1]);\n\t      nodes.insert(poly[*inei][2]);\n\t      nodes.insert(poly[j][0]);\n\t      nodes.insert(poly[j][1]);\n\t      nodes.insert(poly[j][2]);\n\t      if (nodes.size() == 4) // 2 adjacent triangles ?\n\t\t{\n\t\t  trineigho[i].push_back(*inei);\n\t\t  tmpNodes.erase( inei );\n\t\t  stopLoop = true;\n\t\t  //cout << *inei << \" \";\n\t\t}\n\t    }\n          if( !stopLoop )\n          {\n            cout << \"warning, mesh is not closed.\\n\";\n            tmpNodes.clear();\n          }\n\t}\n      // cout << endl;\n    } \n  return(trineigho);\n}\n\n\n\n\n\n\nTexture<float> AimsMeshLaplacian( const Texture<float> &inittex, \n                                  const map<unsigned, set< pair<unsigned,float> > > &lapl)\n{\n  unsigned\t\t\t\t\tn =inittex.nItem();\n  Texture<float>\t\t\t\ttex(n);\n  AimsMeshLaplacian( inittex.data(), tex.data(), lapl );\n\n  return(tex);\n}\n\n\ntemplate <typename T>\nvoid AimsMeshLaplacian( const vector<T> &inittex, vector<T> & outtex,\n                        const map<unsigned, set< pair<unsigned,float> > > &lapl)\n{\n  unsigned neigh,node, n =inittex.size();\n  map<unsigned, set< pair<unsigned,float> > >::const_iterator il,el;\n  set< pair<unsigned,float> >::iterator      ip,ep;\n  float                                        L,weight;\n  ASSERT ( lapl.size() == n);\n  // resize/clear output texture\n  if( outtex.size() != n )\n    outtex.resize( n );\n\n  for (il = lapl.begin(), node=0, el = lapl.end(); il != el; ++il)\n    {\n      node = il->first;\n      L = 0;\n\n      //Weighted sum on the neighbour of the node\n      for ( ip = (il->second).begin(), ep = (il->second).end(); ip != ep; ++ip    )\n        {\n          neigh = ip->first;\n          weight = ip->second;\n          L += weight * (- inittex[node] + inittex[neigh]);\n        }\n        \n      outtex[node] = L;\n    }\n}\n\n\ntemplate void AimsMeshLaplacian( const vector<float> &inittex,\n  vector<float> & outtex,\n  const map<unsigned, set< pair<unsigned,float> > > &lapl);\ntemplate void AimsMeshLaplacian( const vector<double> &inittex,\n  vector<double> & outtex,\n  const map<unsigned, set< pair<unsigned,float> > > &lapl);\n\n\n\n\n\n\n\n\n\nmap<unsigned, set< pair<unsigned,float> > >  AimsMeshWeightFiniteElementLaplacian( const AimsSurface<3,Void> & mesh, \n                                      const float Wmax)\n\n{\n  unsigned\t\t\t\t\tneigh,i, n =mesh.vertex().size();\n  list<unsigned>::const_iterator\t\tilist,elist;\n  list<float>::const_iterator\t\t        iphi,itheta,isurf,esurf;\n  float\t\t\t\t\t\tweight,s,p,t,surface;\t\n  map<unsigned, set< pair<unsigned,float> > > lapl;\n  map<unsigned, set< pair<unsigned,float> > >::iterator il,el;\n  vector< list<unsigned> > neighbourso;\n  vector< list<float> >  PHI;\n  vector< list<float> > THETA;\n  vector< list<float> >  SURFACE;\n  set<float> values;\n\n  cout << \"Node ordering...\" << flush;\n  neighbourso = AimsMeshOrderNode(mesh);\n  cout << \"done \\n\";\n  cout << \"Extract mesh features...\" <<flush;\n  SURFACE =  AimsMeshFiniteElementSurface(mesh,neighbourso);\n  PHI = AimsMeshFiniteElementPhi(mesh,neighbourso,SURFACE);\n  THETA = AimsMeshFiniteElementTheta(mesh,neighbourso,SURFACE);\n  cout << \"done \\n\";\n\n  for (i=0; i<n; ++i)\n  {\n    s = SURFACE[i].size()  ;\n    p = PHI[i].size();\n    t = THETA[i].size();\n    if ( !( s == p && s == t && p==t ) )\n    {\n      cout << \"Problem with the mesh features...\" << endl;\n      ASSERT(0);\n    }\n    elist =  neighbourso[i].end();\n    ilist = neighbourso[i].begin();\n    iphi = PHI[i].begin();\n    isurf = SURFACE[i].begin();\n    esurf = SURFACE[i].end();\n    itheta = THETA[i].begin();\n    surface = 0;\n    while ( isurf != esurf )\n    {\n      surface += *isurf;\n      ++isurf;\n    }\n\n    while ( ilist != elist )\n    {\n      neigh = *ilist;\n\n      if (surface != 0 )\n        weight = (*iphi + *itheta) / surface;\n      else\n      {\n        cerr << \"Triangle(s) with null surface on vertex \" << i << endl;\n        // ASSERT (0);\n        weight = 0.;\n      }\n\n      values.insert(weight);\n      lapl[i].insert( pair<unsigned,float>(neigh,weight) );\n      ++ ilist;\n      ++iphi;\n      ++itheta;\n    }\n  }\n\n  //Threshold definition\n  set<float>::iterator iv;\n  set<float>::reverse_iterator riv;\n  unsigned   nbValues,inc = 0 ;\n  set< pair<unsigned,float> >::iterator isp,esp;\n  float Wm, WM;\n  nbValues = (unsigned) rint ( (1 - Wmax) * values.size() );\n  cout << \"Thresholding  \" << 100*(1 - Wmax) << \"% of the Laplacian weights (\" << nbValues << \"/\" <<  values.size() << \")\" << endl;\n  iv = values.begin();\n  riv = values.rbegin();\n  cout << \"Weights:\" << endl << \"Before: min: \" << *iv << \" max: \" << *riv << endl;\n  while ( inc < nbValues)\n  {\n    ++inc;\n    ++iv;\n  }\n  Wm = *iv;\n  inc = 0;\n  while ( inc < nbValues)\n  {\n    ++inc;\n    ++riv;\n  }\n  WM = *riv;\n  cout << \"After: min: \" << Wm << \" max: \" << WM << endl;\n  for (il = lapl.begin(), el = lapl.end(); il != el; ++il)\n    for ( isp = (il->second).begin(), esp = (il->second).end(); isp != esp; ++isp)\n    {\n      neigh = isp->first;\n      weight = isp->second;\n      if (weight > WM)\n      {\n        il->second.erase(pair<unsigned,float>(neigh,weight) );\n        il->second.insert(pair<unsigned,float>(neigh,WM) );\n      }\n      else\n        if (weight < Wm)\n        {\n          il->second.erase(pair<unsigned,float>(neigh,weight) );\n          il->second.insert(pair<unsigned,float>(neigh,Wm) );\n        }\n    }\n\n  return(lapl);\n}\n\n\n\nfloat AimsMeshFiniteElementDt(  const Texture<float> &tex,\n\t\t\t       const Texture<float> &lapl,\n\t\t\t       float tmax)\n{\n  set<float>      s1,s2;\n  float           maxv,minv,dt;\n  unsigned        i,n=tex.nItem();\n\n  for (i=0; i<n; ++i)\n    s1.insert(tex.item(i));\n\n  maxv = *s1.rbegin();\n  minv = *s1.begin();\n\n  for (i=0; i<n; ++i)\n    if (lapl.item(i) != 0 && fabs(tex.item(i)) < tmax)\n      {\n      s2.insert( fabs((maxv - tex.item(i)) / lapl.item(i)));\n      s2.insert( fabs((minv - tex.item(i)) / lapl.item(i)));\n      }\t  \n  s2.erase(0);\n  dt = *s2.begin();\n\n  return(dt);\n}\n\n\n\n\n\n\n\n//Regularization of the  curvature map\n//Threshold outlier curvature values \n//From mean and std deviation\n//The value of the thresholded node\n//is then the average of its neighbourhood\nTexture<float> AimsRegularizeTexture( const Texture<float> &tex,\n\t\t\t\t      const AimsSurface<3,Void> & mesh,\n\t\t\t\t      float alpha) \n{\n\n  const vector<Point3df>\t\t& vert = mesh.vertex();\n  const vector< AimsVector<uint,3> >\t& poly = mesh.polygon();\n  unsigned\t\t\t\ti, n = vert.size();\n  map<unsigned, set<unsigned> >\t\tneighbours;\n  set<unsigned>::iterator\t\til,el;\n  unsigned\t\t\t\tv1, v2, v3;\n  Texture<float>\t\t\toutTex;\n\n  ASSERT( tex.nItem() == n );\n  \n  //Neighbouring \n  for( i=0; i<poly.size(); ++i )\n    {\n      v1 = poly[i][0];\n      v2 = poly[i][1];\n      v3 = poly[i][2];\n      neighbours[v1].insert( v2 );\n      neighbours[v2].insert( v1 );\n      neighbours[v1].insert( v3 );\n      neighbours[v3].insert( v1 );\n      neighbours[v2].insert( v3 );\n      neighbours[v3].insert( v2 );\n    }\n  \n  \n  float max=-FLT_MAX, min=FLT_MAX,mean = 0, std = 0, Hmax, nval;\n\n  for (i = 0; i < tex.nItem(); ++i)\n    {\n      if (tex.item(i)>max)\n\tmax = tex.item(i);\n      if (tex.item(i)<min)\n\tmin = tex.item(i);\n      outTex.push_back( tex.item(i) );\n    }\n\n  for (i = 0; i < tex.nItem(); ++i)\n    mean += tex.item(i);\n  mean = mean/tex.nItem();\n  \n  for (i = 0; i < tex.nItem(); ++i)\n    std += (tex.item(i) - mean) * (tex.item(i) - mean) ;\n  std = sqrt(std / tex.nItem() );\n  \n  Hmax = mean +  alpha * std;\n  \n  cout << \"min: \" << min << \" max: \" << max \n       << \" mean:\" << mean << \" std: \" << std << \" Hmax:\" << Hmax << endl;\n  \n  unsigned inc1 = 0, inc2 = 0; \n  Point3df pos;\n  float    d;\n\n  for (i = 0; i < tex.nItem(); ++i)\n    {\n      if ( (tex.item(i) > Hmax) || (tex.item(i)< -Hmax) )\n\t{\n\t  ++inc1;\n\t  nval = 0;\n\t  mean = 0;\n\t  for ( il=neighbours[i].begin(), el=neighbours[i].end(); il!=el; ++il )\n\t    if( (tex.item(*il) < Hmax) && (tex.item(*il) > -Hmax) )\n\t      {\n\t\tpos = vert[i] - vert[*il];\n\t\td = sqrt(pos[0]*pos[0] + pos[2]*pos[2] + pos[1]*pos[1]) ;\n\t\tmean += tex.item(*il) / d  ;\n\t\tnval += 1/d ;\n\t      }\n\t  if (nval != 0) \n\t  outTex.item(i) = mean / nval; \n\t  else\n\t    {\n\t      ++inc2;\n\t      outTex.item(i) = fsign(tex.item(i)) * Hmax;\n\t    }\n\t}\n    }    \n  cout << \"Nb of regularized points: \"<< inc1 << endl; \n  cout << \"Nb of non regularized points: \" << inc2 <<  endl;\n  \n  return(outTex);\n\n\n}\n\nTexture<float> AimsRegularizeTexture(const Texture<float> & tex,\n\t\t\t\t     float ratio )\n{\n\n  Texture<float>                otex = tex;\n  set<float>                    values; \n  unsigned \t\t\t i, n = tex.nItem();\n  set<float>::iterator iv;\n  set<float>::reverse_iterator riv;\n  unsigned   nbValues,inc = 0 ;\n  float Wm, WM;\n\n  for ( i=0; i<n; ++i )\n    values.insert(tex.item(i));\n  \n  ASSERT(ratio <= 1 && ratio >= 0);\n  nbValues = (unsigned) rint ( (1 - ratio) * values.size() );\n  cout <<  \"Nb of rejected values: \" << nbValues << \"/\" <<  values.size() <<  endl;\n  iv = values.begin();\n  riv = values.rbegin();\n  cout << \"Values before: min: \" << *iv << \" max: \" << *riv << endl; \n  while ( inc < nbValues)\n    {\n      ++inc;\n      ++iv;\n    }\n  Wm = *iv;\n  inc = 0;\n  while ( inc < nbValues)\n    {\n      ++inc;\n      ++riv;\n    }\n  WM = *riv;\n  cout << \"Values after: min: \" << Wm << \" max: \" << WM << endl; \n  \n  for ( i=0; i<n; ++i )\n    if (tex.item(i) > WM)\n      otex.item(i) = WM;\n    else\n      if (tex.item(i) < Wm)\n\totex.item(i) = Wm;\n\n  return(otex);\n}\n\n\nnamespace aims\n{\n\n  void makeLaplacianMatrix( const LaplacianWeights & weights,\n                            LaplacianWeights & lmat, float dt )\n  {\n    /* make weights matrix A = I + dt * W\n       W diagonal being substracted the sum of weights of its line.\n       so that applying the laplacian smoothing is a matricial operation:\n       X(t+1) = A.X(t)\n       and X(t) = W^t.X(0)\n    */\n    cout << \"makeLaplacianMatrix...\\n\";\n    float w = 0;\n    unsigned i, j;\n    LaplacianWeights::const_iterator iw, ew = weights.end();\n\n    for( iw=weights.begin(); iw!=ew; ++iw )\n    {\n      set<pair<unsigned int, float> >::const_iterator\n        ij, ej = iw->second.end();\n      w = 0;\n      i = iw->first;\n      set<pair<unsigned int, float> > & ow = lmat[ i ];\n\n      for( ij=iw->second.begin(); ij!=ej; ++ij )\n      {\n        j = ij->first;\n        if( i == j )\n        {\n          cout << \"problem: ii found: \" << i << endl;\n        }\n        else\n        {\n          w += ij->second;\n          ow.insert( make_pair( j, ij->second * dt ) );\n        }\n      }\n      ow.insert( make_pair( i, 1. - dt * w ) );\n    }\n    cout << \"makeLaplacianMatrix done.\\n\";\n  }\n\n\n  void makeLaplacianMatrix( const LaplacianWeights & weights,\n                            boost_sparse_matrix & lmat,\n                            float dt )\n  {\n    /* make weights matrix A = I + dt * W\n       W diagonal being substracted the sum of weights of its line.\n       so that applying the laplacian smoothing is a matricial operation:\n       X(t+1) = A.X(t)\n       and X(t) = W^t.X(0)\n    */\n    cout << \"makeLaplacianMatrix... \" << weights.size() << endl;\n    float w = 0;\n    unsigned i, j;\n    lmat.resize( weights.size(), weights.size(), false );\n    LaplacianWeights::const_iterator iw, ew = weights.end();\n\n    for( iw=weights.begin(); iw!=ew; ++iw )\n    {\n      set<pair<unsigned int, float> >::const_iterator\n        ij, ej = iw->second.end();\n      w = 0;\n      i = iw->first;\n\n      for( ij=iw->second.begin(); ij!=ej; ++ij )\n      {\n        j = ij->first;\n        if( i == j )\n        {\n          cout << \"problem: ii found: \" << i << endl;\n        }\n        else\n        {\n          w += ij->second;\n          lmat( i, j ) = ij->second * dt;\n        }\n      }\n      lmat( i, i ) = 1. - dt * w;\n    }\n    cout << \"makeLaplacianMatrix done: \" << lmat.size1() << \" x \" << lmat.size2() << endl;\n  }\n\n\n  void laplacianMatrixThreshold( LaplacianWeights & lmat, float threshold )\n  {\n    /* remove weights under threshold (in absolute value) on non-diagonal\n       coefs, and re-norm diagonal to ensure conservation of the total weight\n    */\n    cout << \"laplacianMatrixThreshold...\\n\";\n    float w = 0, t;\n    unsigned i, j;\n    LaplacianWeights::iterator iw, ew = lmat.end();\n\n    for( iw=lmat.begin(); iw!=ew; ++iw )\n    {\n      set<pair<unsigned int, float> > & line = iw->second;\n      set<pair<unsigned int, float> >::const_iterator\n        ij = line.begin(), ej = line.end(), ti, ii = ej;\n      w = 0;\n      i = iw->first;\n      while( ij!=ej )\n      {\n        j = ij->first;\n        if( i == j )\n        {\n          ii = ij;\n          ++ij;\n        }\n        else\n        {\n          t = ij->second;\n          if( fabs( t ) <= threshold )\n          {\n            ti = ij;\n            ++ij;\n            // remove matrix entry here\n            line.erase( ti );\n          }\n          else\n          {\n            w += t;\n            ++ij;\n          }\n        }\n      }\n      // diagonal coef: 1 - sum( line weights )\n      if( ii != ej )\n        line.erase( ii );\n      line.insert( make_pair( i, 1. - w ) );\n    }\n    cout << \"laplacianMatrixThreshold done.\\n\";\n  }\n\n\n  void laplacianMatrixThreshold( boost_sparse_matrix & lmat, float threshold )\n  {\n    /* remove weights under threshold (in absolute value) on non-diagonal\n       coefs, and re-norm diagonal to ensure conservation of the total weight\n    */\n    cout << \"laplacianMatrixThreshold...\\n\";\n    float w = 0, t;\n    unsigned i, j;\n    boost_sparse_matrix::iterator1 iw, ew = lmat.end1();\n    boost_sparse_matrix::iterator2 jw, ejw;\n\n    for( iw=lmat.begin1(); iw!=ew; ++iw )\n    {\n      boost_sparse_matrix::iterator2\n        ij = iw.begin(), ej = iw.end();\n      w = 0;\n      i = iw.index1();\n      while( ij!=ej )\n      {\n        j = ij.index2();\n        if( i == j )\n          ++ij;\n        else\n        {\n          t = *ij;\n          if( fabs( t ) <= threshold )\n          {\n            ++ij;\n            // remove matrix entry here\n#if BOOST_VERSION < 103300\n            lmat.erase( i, j );\n#else\n            lmat.erase_element( i, j );\n#endif\n          }\n          else\n          {\n            w += t;\n            ++ij;\n          }\n        }\n      }\n      // diagonal coef: 1 - sum( line weights )\n      lmat( i, i ) =1. - w;\n    }\n    cout << \"laplacianMatrixThreshold done.\\n\";\n  }\n\n\n  LaplacianWeights* sparseMult( const LaplacianWeights & in1,\n                                const LaplacianWeights & in2,\n                                float sparseThresh )\n  {\n#ifdef use_boost\n    cout << \"sparseMult...\\n\";\n    LaplacianWeights *out = new LaplacianWeights;\n    unsigned ncoef = 0; // debug\n\n    LaplacianWeights::const_iterator iin1, ein1 = in1.end(),\n      iin2, ein2 = in2.end();\n    set<pair<unsigned int, float> >::const_iterator ik, ek, ik2, ek2;\n    cout << \"convert to boost sparse matrix...\\n\";\n    boost_sparse_matrix\n      mat1( in1.size(), in1.size() ), mat2( in2.size(), in2.size() );\n    unsigned i;\n    for( iin1=in1.begin(); iin1!=ein1; ++iin1 )\n    {\n      i = iin1->first;\n      for( ik=iin1->second.begin(), ek=iin1->second.end(); ik!=ek; ++ik )\n        mat1( i, ik->first ) = ik->second;\n    }\n    for( iin2=in2.begin(); iin2!=ein2; ++iin2 )\n    {\n      i = iin2->first;\n      for( ik=iin2->second.begin(), ek=iin2->second.end(); ik!=ek; ++ik )\n        mat2( i, ik->first ) = ik->second;\n    }\n    cout << \"convert done. Sizes: \" << mat1.size1() << \" x \" << mat1.size2()\n      << \", \" << mat2.size1() << \" x \" << mat1.size2() << endl;\n    boost_sparse_matrix mat3( mat1.size1(), mat2.size2() );\n    boost::numeric::ublas::sparse_prod( mat1, mat2, mat3 );\n    cout << \"mult done. converting back...\\n\";\n    boost_sparse_matrix::iterator1 il, el = mat3.end1();\n    boost_sparse_matrix::iterator2 ic, ec;\n    for( il=mat3.begin1(); il!=el; ++il )\n    {\n      set<pair<unsigned int, float> > & line = (*out)[ il.index1() ];\n      for( ic=il.begin(), ec=il.end(); ic!=ec; ++ic )\n      {\n        line.insert( make_pair( ic.index2(), *ic ) );\n        ++ncoef;\n      }\n    }\n\n    sparseThresh = sparseThresh; // compilation warning...\n    cout << \"out size: \" << mat3.size1() << \" x \" << mat3.size2() << \" / \" << out->size() << endl;\n    cout << \"\\nsparseMult done, weights num: \" << ncoef << endl;\n    return out;\n\n#else\n\n    cout << \"sparseMult...\\n\";\n    LaplacianWeights *out = new LaplacianWeights;\n    unsigned ncoef = 0; // debug\n\n    vector<map<unsigned, float> > lin2( in2.size() );\n    LaplacianWeights::const_iterator iin1, ein1 = in1.end(),\n      iin2, ein2 = in2.end();\n    set<pair<unsigned int, float> >::const_iterator ik, ek, ik2, ek2;\n    unsigned i, j, k, n = in1.size();\n    map<unsigned, float>::iterator ic, ec;\n\n    // transpose in2 for faster access\n    for( iin2=in2.begin(); iin2!=ein2; ++iin2 )\n    {\n      i = iin2->first;\n      for( ik2=iin2->second.begin(), ek2=iin2->second.end(); ik2!=ek2;\n          ++ik2 )\n        lin2[ ik2->first ][ i ] = ik2->second;\n    }\n    cout << \"transposition done.\\n\";\n\n    // out(i,j) = S_k( in1(i,k) * in2(k,j) )\n    // with in2(k,j) = lin2(j,k)\n\n    for( iin1=in1.begin(); iin1!=ein1; ++iin1 )\n    {\n      i = iin1->first;\n      if( i % 1000 == 0 )\n        cout << \"\\rline: \" << i << flush;\n      set<pair<unsigned int, float> > & oline = (*out)[i];\n      const set<pair<unsigned int, float> > & iline = iin1->second;\n      ek = iline.end();\n\n      for( j=0; j<n; ++j )\n      {\n        map<unsigned, float> & col2 = lin2[j];\n        ec = col2.end();\n        float oij = 0.F;\n        if( col2.size() <= iline.size() )\n        {\n          // iterate on in2 cols\n          for( ic=col2.begin(), ec=col2.end(); ic!=ec; ++ic )\n          {\n            k = ic->first;\n            ik = iline.lower_bound( make_pair( k, -FLT_MAX ) );\n            if( ik != ek && ik->first == k )\n              oij += ik->second * ic->second;\n          }\n        }\n        else\n        {\n          // iterate on in1 lines\n          ic = col2.begin();\n          for( ik=iline.begin(); ik!=ek; ++ik )\n          {\n            k = ik->first;\n            while( ic != ec && ic->first < k )\n              ++ic;\n            if( ic != ec && ic->first == k )\n            {\n              oij += ik->second * ic->second;\n            }\n          }\n        }\n//         for( ic=col2.begin(), ec=col2.end(); ic!=ec; ++ic )\n//         {\n//           iin2 = in2.find( ik->first );\n//           if( iin2 != ein2 )\n//           {\n//             ik2 = iin2->second.lower_bound( make_pair( j, -FLT_MAX ) );\n//             if( ik2 != iin2->second.end() && ik2->first == j )\n//               oij += ik->second * ik2->second;\n//           }\n//         }\n        if( fabs( oij ) > sparseThresh )\n        {\n          oline.insert( make_pair( j, oij ) );\n          ++ncoef;\n        }\n      }\n    }\n\n    cout << \"\\nsparseMult done, weights num: \" << ncoef << endl;\n    return out;\n#endif\n  }\n\n\n  LaplacianWeights*\n    makeLaplacianSmoothingCoefficients( const LaplacianWeights & weights,\n                                        unsigned niter, float dt,\n                                        float sparseThresh )\n\n  {\n#ifdef use_boost\n    boost_sparse_matrix weightLaplMat;\n    makeLaplacianMatrix( weights, weightLaplMat, dt ); // matricial representation\n    laplacianMatrixThreshold( weightLaplMat, sparseThresh );\n    boost_sparse_matrix\n      *weightLaplPow = &weightLaplMat,\n      *weightLapl2, *weightLapl3 = 0;\n\n    unsigned t, iterbin = niter;\n    cout << \"size: \" << weightLaplMat.size1() << \" x \" << weightLaplMat.size2() << \", niter: \" << niter << endl;\n\n    if( iterbin & 1 ) // small bit is set: keep weightLaplMat\n    {\n      weightLapl3 = &weightLaplMat;\n    }\n    iterbin = iterbin >> 1;\n\n    for( t=0; iterbin!=0; ++t, iterbin=iterbin>>1 )\n    {\n      //if (t%10 == 0)\n      {\n        cout << \"                \";\n        cout << \"\\r\" << rint(100.*t/log(float(niter))*log(2.)) << \"%\" << flush;\n      }\n      weightLapl2 = new boost_sparse_matrix(\n        weightLaplMat.size1(), weightLaplMat.size2() );\n      // multiply the weights matrix to power niter\n      sparse_prod( *weightLaplPow, *weightLaplPow, *weightLapl2 );\n      // renormalize diagonal\n      laplacianMatrixThreshold( *weightLapl2, sparseThresh );\n      if( weightLaplPow != & weightLaplMat && weightLaplPow != weightLapl3 )\n        delete weightLaplPow;\n      weightLaplPow = weightLapl2;\n      // weightLapl2 is weightLaplMat ^ (2^t)\n      if( iterbin & 1 )\n      {\n        // keep weightLaplPow * weightLapl3 in weightLapl3\n        if( weightLapl3 )\n        {\n          weightLapl2 = weightLapl3;\n          weightLapl3 = new boost_sparse_matrix(\n          weightLaplMat.size1(), weightLaplMat.size2() );\n          sparse_prod( *weightLaplPow, *weightLapl2, *weightLapl3 );\n          if( weightLapl2 != & weightLaplMat )\n            delete weightLapl2;\n          laplacianMatrixThreshold( *weightLapl3, sparseThresh );\n        }\n        else\n          weightLapl3 = weightLaplPow;\n      }\n    }\n    weightLaplPow = weightLapl3; // result\n    if( !weightLaplPow ) // zero iterations\n      weightLaplPow = &weightLaplMat; // take initial matrix\n\n    // convert to LaplacianWeights type\n    LaplacianWeights *weightLaplPowL = new LaplacianWeights;\n    boost_sparse_matrix::iterator1 il, el = weightLaplPow->end1();\n    boost_sparse_matrix::iterator2 ic, ec;\n    for( il=weightLaplPow->begin1(); il!=el; ++il )\n    {\n      set<pair<unsigned int, float> >\n        & line = (*weightLaplPowL)[ il.index1() ];\n      for( ic=il.begin(), ec=il.end(); ic!=ec; ++ic )\n        line.insert( make_pair( ic.index2(), *ic ) );\n    }\n    cout << \"makeLaplacianSmoothingCoefficients done, size: \" << weightLaplPow->size1() << \" x \" << weightLaplPow->size2() << endl;\n    if( weightLaplPow != &weightLaplMat )\n      delete weightLaplPow;\n    return weightLaplPowL;\n\n#else\n\n    LaplacianWeights weightLaplMat;\n    makeLaplacianMatrix( weights, weightLaplMat, dt ); // matricial representation\n    laplacianMatrixThreshold( weightLaplMat, sparseThresh );\n    LaplacianWeights *weightLaplPow = &weightLaplMat, *weightLapl2;\n\n    unsigned t;\n\n    for( t=0; t<niter; ++t )\n    {\n      //if (t%10 == 0)\n      {\n        cout << \"                \";\n        cout << \"\\r\" << rint(100*t/niter) << \"%\" << flush;\n      }\n      // multiply the weights matrix to power niter\n      weightLapl2 = sparseMult( *weightLaplPow, weightLaplMat,\n                                sparseThresh );\n      // renormalize diagonal\n      laplacianMatrixThreshold( *weightLapl2, sparseThresh );\n      if( t != 0 )\n        delete weightLaplPow;\n      weightLaplPow = weightLapl2;\n    }\n    return weightLaplPow;\n#endif\n  }\n\n\n  template <typename T>\n  void applyLaplacianMatrix( const vector<T> &inittex, vector<T> & outtex,\n                             const LaplacianWeights &lapl )\n  {\n    unsigned neigh,node, n =inittex.size();\n    map<unsigned, set< pair<unsigned,float> > >::const_iterator il,el;\n    set< pair<unsigned,float> >::iterator      ip,ep;\n    float                                      L,weight;\n    ASSERT ( lapl.size() == n);\n    // resize/clear output texture\n    if( outtex.size() != n )\n      outtex.resize( n );\n\n    for( il = lapl.begin(), el = lapl.end(); il != el; ++il )\n    {\n      node = il->first;\n      L = 0;\n\n      //Weighted sum on the neighbour of the node\n      for( ip = (il->second).begin(), ep = (il->second).end(); ip != ep;\n           ++ip )\n      {\n        neigh = ip->first;\n        weight = ip->second;\n        L += weight * inittex[neigh];\n      }\n\n      outtex[node] = L;\n    }\n  }\n\n\n  // --- template instanciations ---\n\n\n  template void applyLaplacianMatrix( const vector<float> &inittex,\n    vector<float> & outtex, const LaplacianWeights &lapl);\n  template void applyLaplacianMatrix( const vector<double> &inittex,\n    vector<double> & outtex, const LaplacianWeights &lapl);\n\n}\n\n\n", "meta": {"hexsha": "7f8a8e0688c2caf2758dd240feeaf69d1f023647", "size": 41501, "ext": "cc", "lang": "C++", "max_stars_repo_path": "aimsalgo/src/aimsalgo/mesh/curv.cc", "max_stars_repo_name": "brainvisa/aims-free", "max_stars_repo_head_hexsha": "5852c1164292cadefc97cecace022d14ab362dc4", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-07-09T05:34:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-16T00:03:15.000Z", "max_issues_repo_path": "aimsalgo/src/aimsalgo/mesh/curv.cc", "max_issues_repo_name": "brainvisa/aims-free", "max_issues_repo_head_hexsha": "5852c1164292cadefc97cecace022d14ab362dc4", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": 72.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T14:52:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T11:22:51.000Z", "max_forks_repo_path": "aimsalgo/src/aimsalgo/mesh/curv.cc", "max_forks_repo_name": "brainvisa/aims-free", "max_forks_repo_head_hexsha": "5852c1164292cadefc97cecace022d14ab362dc4", "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": 27.9092131809, "max_line_length": 131, "alphanum_fraction": 0.5383725693, "num_tokens": 12522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.29026507221653597}}
{"text": "// Copyright 2010-2013 The Trustees of Indiana University.\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// 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// 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 OWNER 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\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//  Authors: Jeremiah Willcock\n//           Andrew Lumsdaine\n\n#ifndef BOOST_DISTRIBUTED_ERDOS_RENYI_GENERATOR_HPP\n#define BOOST_DISTRIBUTED_ERDOS_RENYI_GENERATOR_HPP\n\n#include \"splittable_ecuyer1988.hpp\"\n#include <boost/iterator.hpp>\n#include <boost/random/geometric_distribution.hpp>\n#include <boost/random/uniform_01.hpp>\n\nnamespace boost {\n  template <typename VertexDistribution, typename Generator = boost::random::splittable_ecuyer1988, typename VertexType = size_t>\n  class distributed_erdos_renyi_iterator:\n          public boost::iterator_facade<distributed_erdos_renyi_iterator<VertexDistribution, Generator, VertexType>,\n                                        std::pair<VertexType, VertexType>,\n                                        std::input_iterator_tag,\n                                        std::pair<VertexType, VertexType> >\n  {\n    VertexDistribution owner;\n    typedef size_t rank_type;\n    rank_type my_rank;\n    typename Generator::split_iterator_pair generators; // One for each source vertex\n    Generator current_generator;\n    VertexType current_source, current_target, nverts;\n    bool is_undirected, allow_self_loops;\n    boost::geometric_distribution<VertexType> distrib;\n\n    void next_source_vertex() {\n      // fprintf(stderr, \"next_source_vertex()\\n\");\n      ++current_source;\n      current_target = (VertexType)(-1);\n      ++generators.first;\n      if (generators.first != generators.second) {\n        current_generator = *generators.first;\n      }\n    }\n\n    void step_to_owned_vertex() {\n      // Find a source that I own\n      while (current_source != nverts &&\n             rank_type(owner(current_source)) != my_rank) {\n        next_source_vertex();\n      }\n    }\n\n    void raw_increment() { // Does not always produce a valid vertex\n      if (current_source == nverts) return;\n      boost::random::uniform_01_wrapper<Generator> wr(current_generator);\n      VertexType delta = distrib(wr);\n      // fprintf(stderr, \"delta = %zu\\n\", delta);\n      // First test is to deal with overflows, plus handle that the current\n      // target might be -1 and so delta == nverts would be valid\n      if (delta > nverts || current_target + delta >= nverts) {\n        next_source_vertex();\n        step_to_owned_vertex();\n        // Return target as -1, so raw_increment() will be repeated\n      } else {\n        current_target += delta;\n      }\n      // fprintf(stderr, \"New loc is (%zu, %zu)\\n\", current_source, current_target);\n    }\n\n    public:\n    distributed_erdos_renyi_iterator(): owner(), my_rank(0), current_source(0), current_target((VertexType)(-1)), nverts(0) {}\n\n    distributed_erdos_renyi_iterator(Generator& gen, VertexType nverts, double prob, bool is_undirected, bool allow_self_loops, VertexDistribution owner, rank_type my_rank): owner(owner), my_rank(my_rank), current_source(0), current_target((VertexType)(-1)), nverts(nverts), is_undirected(is_undirected), allow_self_loops(allow_self_loops), distrib(1. - prob) {\n      generators = gen.split_off_n(nverts);\n      raw_increment();\n    }\n\n    std::pair<VertexType, VertexType> dereference() const {\n      return std::make_pair(current_source, current_target);\n    }\n\n    bool equal(const distributed_erdos_renyi_iterator& o) const {\n      // Only really works on end iterators or those generated with the same parameters\n      return (nverts - current_source) == (o.nverts - o.current_source) && current_target == o.current_target;\n    }\n\n    void increment() {\n      do {\n        raw_increment();\n      } while (current_source != nverts &&\n               (current_target == (VertexType)(-1) ||\n                (!allow_self_loops && current_source == current_target) ||\n                (is_undirected && current_target > current_source)));\n    }\n  };\n\n}\n\n#endif // BOOST_DISTRIBUTED_ERDOS_RENYI_GENERATOR_HPP\n", "meta": {"hexsha": "90d68f5ba6c762c8c14ec41f56e6208e6d66ec30", "size": 5176, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "runtime/tests/distributed_erdos_renyi_generator.hpp", "max_stars_repo_name": "thejkane/AGM", "max_stars_repo_head_hexsha": "4d5cfe9522461d207ceaef7d90c1cd10ce9b469c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-03T10:22:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T10:22:04.000Z", "max_issues_repo_path": "runtime/tests/distributed_erdos_renyi_generator.hpp", "max_issues_repo_name": "thejkane/AGM", "max_issues_repo_head_hexsha": "4d5cfe9522461d207ceaef7d90c1cd10ce9b469c", "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": "runtime/tests/distributed_erdos_renyi_generator.hpp", "max_forks_repo_name": "thejkane/AGM", "max_forks_repo_head_hexsha": "4d5cfe9522461d207ceaef7d90c1cd10ce9b469c", "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.6206896552, "max_line_length": 361, "alphanum_fraction": 0.7003477589, "num_tokens": 1148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.2901763759500361}}
{"text": "// Copyright (c) 2019, Torsten Sattler\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\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 the copyright holder nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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// author: Torsten Sattler, torsten.sattler.de@googlemail.com\n\n#include <algorithm>\n#include <cmath>\n#include <cstddef>\n#include <cstdint>\n#include <limits>\n#include <random>\n#include <vector>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Geometry>\n\n#include \"hybrid_line_estimator.h\"\n\nnamespace ransac_lib {\n\nHybridLineEstimator::HybridLineEstimator(\n    const Eigen::Matrix2Xd& points, const Eigen::Matrix4Xd& points_with_normals,\n    const std::vector<double>& prior_probabilities) {\n  points_ = points;\n  num_points_ = points_.cols();\n  points_with_normals_ = points_with_normals;\n  num_points_with_normals_ = points_with_normals_.cols();\n  prior_probabilities_ = prior_probabilities;\n}\n\nvoid HybridLineEstimator::LeastSquares(\n    const std::vector<std::vector<int>>& sample, Eigen::Vector3d* line) const {\n  const int kNumSamplesPoints = static_cast<int>(sample[0].size());\n  const int kNumSamplesPointsWithNormals = static_cast<int>(sample[1].size());\n  const int kNumSamples = kNumSamplesPoints + kNumSamplesPointsWithNormals;\n\n  if (kNumSamples < 6) return;\n  // We fit the line by estimating the eigenvectors of the covariance matrix\n  // of the data.\n  Eigen::Vector2d mean(0.0, 0.0);\n  for (int i = 0; i < kNumSamplesPoints; ++i) {\n    mean += points_.col(sample[0][i]);\n  }\n  for (int i = 0; i < kNumSamplesPointsWithNormals; ++i) {\n    mean += points_with_normals_.col(sample[1][i]).head<2>();\n  }\n  mean /= static_cast<double>(kNumSamples);\n\n  // Builds the covariance matrix C.\n  Eigen::Matrix2d C = Eigen::Matrix2d::Zero();\n\n  for (int i = 0; i < kNumSamplesPoints; ++i) {\n    Eigen::Vector2d d = points_.col(sample[0][i]) - mean;\n    C += d * d.transpose();\n  }\n  for (int i = 0; i < kNumSamplesPointsWithNormals; ++i) {\n    Eigen::Vector2d d = points_with_normals_.col(sample[1][i]).head<2>() - mean;\n    C += d * d.transpose();\n  }\n  C /= static_cast<double>(kNumSamples - 1);\n\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix2d> eig_solver(C);\n  if (eig_solver.info() != Eigen::Success) return;\n\n  line->head<2>() = eig_solver.eigenvectors().col(1);\n\n  // Re-estimates the translation along the line to account for subtraction\n  // of mean.\n  (*line)[2] = -line->head<2>().dot(mean);\n}\n\n// Evaluates the line on the i-th data point of the t-th data type.\ndouble HybridLineEstimator::EvaluateModelOnPoint(const Eigen::Vector3d& line,\n                                                 int t, int i) const {\n  double residual = 0.0;\n  if (t == 0) {\n    residual = line.dot(points_.col(i).homogeneous());\n  } else {\n    residual = line.dot(points_with_normals_.col(i).head<2>().homogeneous());\n  }\n  return residual * residual;\n}\n\nint HybridLineEstimator::TwoPointSolver(\n    const std::vector<int>& sample, std::vector<Eigen::Vector3d>* lines) const {\n  lines->clear();\n  if (sample.size() < 2u) return 0;\n\n  lines->resize(1);\n  Eigen::Vector3d p1(points_(0, sample[0]), points_(1, sample[0]), 1.0);\n  Eigen::Vector3d p2(points_(0, sample[1]), points_(1, sample[1]), 1.0);\n  (*lines)[0] = p1.cross(p2);\n  // Normalizes the line such that the normal of the line has unit length.\n  double normal_norm = (*lines)[0].head<2>().norm();\n  if (normal_norm == 0.0) {\n    lines->clear();\n    return 0;\n  }\n\n  (*lines)[0] /= normal_norm;\n\n  return 1;\n}\n\nint HybridLineEstimator::PointNormalSolver(\n    const std::vector<int>& sample, std::vector<Eigen::Vector3d>* lines) const {\n  lines->clear();\n  if (sample.size() < 1u) return 0;\n\n  lines->resize(1);\n  Eigen::Vector2d normal = points_with_normals_.col(sample[0]).tail<2>();\n  normal.normalize();\n  double c = -normal.dot(points_with_normals_.col(sample[0]).head<2>());\n  (*lines)[0] = Eigen::Vector3d(normal[0], normal[1], c);\n  // Normalizes the line such that the normal of the line has unit length.\n  double normal_norm = (*lines)[0].head<2>().norm();\n  if (normal_norm == 0.0) {\n    lines->clear();\n    return 0;\n  }\n\n  (*lines)[0] /= normal_norm;\n\n  return 1;\n}\n\n}  // namespace ransac_lib\n", "meta": {"hexsha": "690b7b375a2ee82119253d66f1a951f9989cf4eb", "size": 5584, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/hybrid_line_estimator.cc", "max_stars_repo_name": "erikstenborg/RansacLib", "max_stars_repo_head_hexsha": "9c2d140dd11b3b62661083266d20a2f90db70eaa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 216.0, "max_stars_repo_stars_event_min_datetime": "2019-08-17T14:22:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T06:19:08.000Z", "max_issues_repo_path": "examples/hybrid_line_estimator.cc", "max_issues_repo_name": "erikstenborg/RansacLib", "max_issues_repo_head_hexsha": "9c2d140dd11b3b62661083266d20a2f90db70eaa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2019-09-27T07:26:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-04T16:41:41.000Z", "max_forks_repo_path": "examples/hybrid_line_estimator.cc", "max_forks_repo_name": "erikstenborg/RansacLib", "max_forks_repo_head_hexsha": "9c2d140dd11b3b62661083266d20a2f90db70eaa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 32.0, "max_forks_repo_forks_event_min_datetime": "2019-08-18T05:52:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:01:54.000Z", "avg_line_length": 36.0258064516, "max_line_length": 80, "alphanum_fraction": 0.6944842407, "num_tokens": 1487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2901763622493575}}
{"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_calderon_projector.hpp\"\n\n#include \"../common/shared_ptr.hpp\"\n\n#include \"laplace_3d_single_layer_boundary_operator.hpp\"\n#include \"laplace_3d_double_layer_boundary_operator.hpp\"\n#include \"laplace_3d_hypersingular_boundary_operator.hpp\"\n#include \"identity_operator.hpp\"\n#include \"blocked_operator_structure.hpp\"\n#include \"../fiber/explicit_instantiation.hpp\"\n#include \"../assembly/context.hpp\"\n\n#include <boost/make_shared.hpp>\n\nnamespace Bempp {\n\ntemplate <typename BasisFunctionType, typename ResultType>\nBlockedBoundaryOperator<BasisFunctionType, ResultType>\nlaplace3dExteriorCalderonProjector(\n    const shared_ptr<const Context<BasisFunctionType, ResultType>> &context,\n    const shared_ptr<const Space<BasisFunctionType>> &hminusSpace,\n    const shared_ptr<const Space<BasisFunctionType>> &hplusSpace,\n    const std::string &label) {\n\n  typedef BoundaryOperator<BasisFunctionType, ResultType> BdOp;\n\n  shared_ptr<const Space<BasisFunctionType>> internalHplusSpace =\n      hplusSpace->discontinuousSpace(hplusSpace);\n\n  BdOp internalSlp = laplace3dSingleLayerBoundaryOperator(\n      context, internalHplusSpace, internalHplusSpace, internalHplusSpace,\n      label + \"_slp\", SYMMETRIC);\n\n  BdOp dlp = laplace3dDoubleLayerBoundaryOperator(context, hplusSpace,\n                                                  hplusSpace, hminusSpace,\n                                                  label + \"_dlp\", NO_SYMMETRY);\n\n  BdOp adjDlp = adjoint(dlp);\n\n  BdOp hyp = laplace3dHypersingularBoundaryOperator(\n      context, hplusSpace, hminusSpace, hplusSpace, label + \"_hyp\", SYMMETRIC,\n      internalSlp);\n\n  BdOp idSpaceTransformation1 = identityOperator(\n      context, hminusSpace, internalHplusSpace, internalHplusSpace);\n  BdOp idSpaceTransformation2 =\n      identityOperator(context, internalHplusSpace, hplusSpace, hminusSpace);\n  BdOp idDouble =\n      identityOperator(context, hplusSpace, hplusSpace, hminusSpace);\n  BdOp idAdjDouble =\n      identityOperator(context, hminusSpace, hminusSpace, hplusSpace);\n\n  // Now Assemble the entries of the Calderon Projector\n\n  BlockedOperatorStructure<BasisFunctionType, ResultType> structure;\n\n  structure.setBlock(0, 0, .5 * idDouble + dlp);\n  structure.setBlock(0, 1, -1. * idSpaceTransformation2 * internalSlp *\n                               idSpaceTransformation1);\n  structure.setBlock(1, 0, -1. * hyp);\n  structure.setBlock(1, 1, .5 * idAdjDouble - adjDlp);\n\n  return BlockedBoundaryOperator<BasisFunctionType, ResultType>(structure);\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nBlockedBoundaryOperator<BasisFunctionType, ResultType>\nlaplace3dInteriorCalderonProjector(\n    const shared_ptr<const Context<BasisFunctionType, ResultType>> &context,\n    const shared_ptr<const Space<BasisFunctionType>> &hminusSpace,\n    const shared_ptr<const Space<BasisFunctionType>> &hplusSpace,\n    const std::string &label) {\n\n  typedef BoundaryOperator<BasisFunctionType, ResultType> BdOp;\n\n  shared_ptr<const Space<BasisFunctionType>> internalHplusSpace =\n      hplusSpace->discontinuousSpace(hplusSpace);\n\n  BdOp internalSlp = laplace3dSingleLayerBoundaryOperator(\n      context, internalHplusSpace, internalHplusSpace, internalHplusSpace,\n      label + \"_slp\", SYMMETRIC);\n\n  BdOp dlp = laplace3dDoubleLayerBoundaryOperator(context, hplusSpace,\n                                                  hplusSpace, hminusSpace,\n                                                  label + \"_dlp\", NO_SYMMETRY);\n\n  BdOp adjDlp = adjoint(dlp);\n\n  BdOp hyp = laplace3dHypersingularBoundaryOperator(\n      context, hplusSpace, hminusSpace, hplusSpace, label + \"_hyp\", SYMMETRIC,\n      internalSlp);\n\n  BdOp idSpaceTransformation1 = identityOperator(\n      context, hminusSpace, internalHplusSpace, internalHplusSpace);\n  BdOp idSpaceTransformation2 =\n      identityOperator(context, internalHplusSpace, hplusSpace, hminusSpace);\n  BdOp idDouble =\n      identityOperator(context, hplusSpace, hplusSpace, hminusSpace);\n  BdOp idAdjDouble =\n      identityOperator(context, hminusSpace, hminusSpace, hplusSpace);\n\n  // Now Assemble the entries of the Calderon Projector\n\n  BlockedOperatorStructure<BasisFunctionType, ResultType> structure;\n\n  structure.setBlock(0, 0, .5 * idDouble - dlp);\n  structure.setBlock(0, 1, idSpaceTransformation2 * internalSlp *\n                               idSpaceTransformation1);\n  structure.setBlock(1, 0, hyp);\n  structure.setBlock(1, 1, .5 * idAdjDouble + adjDlp);\n\n  return BlockedBoundaryOperator<BasisFunctionType, ResultType>(structure);\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nBlockedBoundaryOperator<BasisFunctionType, ResultType>\nlaplace3dExteriorCalderonProjector(\n    const ParameterList &parameterList,\n    const shared_ptr<const Space<BasisFunctionType>> &hminusSpace,\n    const shared_ptr<const Space<BasisFunctionType>> &hplusSpace,\n    const std::string &label) {\n\n  shared_ptr<const Context<BasisFunctionType, ResultType>> context(\n      new Context<BasisFunctionType, ResultType>(parameterList));\n  return laplace3dExteriorCalderonProjector<BasisFunctionType, ResultType>(\n      context, hminusSpace, hplusSpace, label);\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nBlockedBoundaryOperator<BasisFunctionType, ResultType>\nlaplace3dInteriorCalderonProjector(\n    const ParameterList &parameterList,\n    const shared_ptr<const Space<BasisFunctionType>> &hminusSpace,\n    const shared_ptr<const Space<BasisFunctionType>> &hplusSpace,\n    const std::string &label) {\n\n  shared_ptr<const Context<BasisFunctionType, ResultType>> context(\n      new Context<BasisFunctionType, ResultType>(parameterList));\n  return laplace3dInteriorCalderonProjector<BasisFunctionType, ResultType>(\n      context, hminusSpace, hplusSpace, label);\n}\n\n#define INSTANTIATE_NONMEMBER_CONSTRUCTOR(BASIS, RESULT)                       \\\n  template BlockedBoundaryOperator<BASIS, RESULT>                              \\\n  laplace3dExteriorCalderonProjector(                                          \\\n      const ParameterList &, const shared_ptr<const Space<BASIS>> &,           \\\n      const shared_ptr<const Space<BASIS>> &, const std::string &);            \\\n  template BlockedBoundaryOperator<BASIS, RESULT>                              \\\n  laplace3dInteriorCalderonProjector(                                          \\\n      const ParameterList &, const shared_ptr<const Space<BASIS>> &,           \\\n      const shared_ptr<const Space<BASIS>> &, const std::string &);            \\\n  template BlockedBoundaryOperator<BASIS, RESULT>                              \\\n  laplace3dExteriorCalderonProjector(                                          \\\n      const shared_ptr<const Context<BASIS, RESULT>> &,                        \\\n      const shared_ptr<const Space<BASIS>> &,                                  \\\n      const shared_ptr<const Space<BASIS>> &, const std::string &);            \\\n  template BlockedBoundaryOperator<BASIS, RESULT>                              \\\n  laplace3dInteriorCalderonProjector(                                          \\\n      const shared_ptr<const Context<BASIS, RESULT>> &,                        \\\n      const shared_ptr<const Space<BASIS>> &,                                  \\\n      const shared_ptr<const Space<BASIS>> &, const std::string &)\n\nFIBER_ITERATE_OVER_BASIS_AND_RESULT_TYPES(INSTANTIATE_NONMEMBER_CONSTRUCTOR);\n\n} // Bempp\n", "meta": {"hexsha": "c1708fc3a867e7a485c9a23c502f946c58cbab56", "size": 8514, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/assembly/laplace_3d_calderon_projector.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_calderon_projector.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_calderon_projector.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": 45.7741935484, "max_line_length": 80, "alphanum_fraction": 0.7096546864, "num_tokens": 1964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.2901763622493575}}
{"text": "#include \"../include/cte_bits/bunch.hpp\"\n#include \"../include/cte_bits/distributions.hpp\"\n#include \"../include/cte_bits/physics.hpp\"\n#include \"../include/cte_bits/radiation.hpp\"\n#include \"../include/cte_bits/random.hpp\"\n#include \"../include/cte_bits/synch.hpp\"\n#include \"../include/cte_bits/utils.hpp\"\n#include <algorithm>\n#include <boost/math/tools/roots.hpp>\n#include <fstream>\n#include <ibs>\n#include <iterator>\n#include <map>\n#include <random>\n#include <sstream>\n#include <string>\n#include <vector>\n\nnamespace cte_long {\n/*\n *****************************************************************************\n *****************************************************************************\n * FUNCTOR TO RETURN VOLTAGE * CHARGE - U0 AND DERIVATIVE AS TUPLE\n * THIS IS USED AS INPUT FOR BOOST NEWTON RAPHSON ROOT SEARCH.\n *****************************************************************************\n * Authors:\n *  - Tom Mertens\n *\n * History:\n *  - 10/08/2021 : updated version from original ste code\n *****************************************************************************\n * Arguments:\n * ----------\n *  - T const &target\n *      Target value for the voltage (RF compensate for U0 so U0 in eV)\n *  - std::vector<double> &voltages\n *      Voltages of RF systems IMPORTANT: first element is for main RF\n *  - std::vector<double> &harmonicNumbers\n *      Harmonic numbers  IMPORTANT: first element is for main RF\n *  - double charge\n *      Particle charge\n *  - T const &phi\n *      phase in rad\n ******************************************************************************\n ******************************************************************************\n */\ntemplate <class T> struct synchronousPhaseFunctor {\n  synchronousPhaseFunctor(T const &target, std::vector<double> &voltages,\n                          std::vector<double> &harmonicNumbers, double charge)\n      : U0(target), volts(voltages), hs(harmonicNumbers), ch(charge) {}\n  std::tuple<double, double> operator()(T const &phi) {\n\n    // init\n    T vrf = ch * volts[0] * sin(phi);\n    T dvrf = ch * volts[0] * cos(phi);\n\n    // add the rest taking harmonic numbers into account\n    for (int i = 1; i < hs.size(); i++) {\n      vrf += ch * volts[i] * sin((hs[i] / hs[0]) * phi);\n      dvrf += ch * volts[i] * (hs[i] / hs[0]) * cos((hs[i] / hs[0]) * phi);\n    }\n\n    std::tuple<double, double> out = {vrf - U0, dvrf};\n    return out;\n  }\n\nprivate:\n  T U0;\n  std::vector<double> volts;\n  std::vector<double> hs;\n  double ch;\n};\n\n/*\n================================================================================\n================================================================================\nBOOST NEWTON RAPHSON ROOT SEARCH FOR SYNCHRONOUS PHASE.\n================================================================================\n\n================================================================================\nArguments:\n\n//phi is in rad\n================================================================================\n================================================================================\n*/\ntemplate <class T>\nT synchronousPhaseFunctorRoot(T x, std::vector<double> &voltages,\n                              std::vector<double> &harmnumbers, double charge,\n                              T guess, T min, T max) {\n  // return cube root of x using 1st derivative and Newton_Raphson.\n  using namespace boost::math::tools;\n\n  const int digits =\n      std::numeric_limits<T>::digits; // Maximum possible binary digits accuracy\n                                      // for type T.\n  int get_digits = static_cast<int>(\n      digits * 0.6); // Accuracy doubles with each step, so stop when we have\n                     // just over half the digits correct.\n  const boost::uintmax_t maxit = 20;\n  boost::uintmax_t it = maxit;\n  T result = newton_raphson_iterate(\n      synchronousPhaseFunctor<T>(x, voltages, harmnumbers, charge), guess, min,\n      max, get_digits, it);\n  return result;\n};\n\n/********************************************************************************\n ********************************************************************************\n * CALCULATE TOTAL RF VOLTAGE FOR GIVEN PHASE (IN RAD)\n *\n ********************************************************************************\n */\ndouble VoltageRf(double phi, std::vector<double> &volts,\n                 std::vector<double> &hs) {\n  double vrf = volts[0] * sin(phi);\n\n  for (int i = 1; i < hs.size(); i++) {\n    vrf += volts[i] * sin((hs[i] / hs[0]) * phi);\n  }\n\n  return vrf;\n};\n\ndouble VoltageRfPrime(double phi, double charge, std::vector<double> &volts,\n                      std::vector<double> &hs) {\n  // init\n  double vrf = volts[0] * cos(phi);\n\n  // add other rfs\n  for (int i = 1; i < volts.size(); i++) {\n    vrf += volts[i] * (hs[i] / hs[0]) * cos((hs[i] / hs[0]) * phi);\n  }\n\n  // V -> eV\n  vrf *= charge;\n  return vrf;\n}\n\ndouble SynchrotronTune(double omega0, double U0, double charge,\n                       std::vector<double> &volts, std::vector<double> &hs,\n                       double phis, double eta, double pc) {\n  return sqrt(hs[0] * eta *\n              fabs(charge * VoltageRfPrime(phis, charge, volts, hs)) /\n              (2 * pi * pc * 1e9));\n}\n\n} // namespace cte_long\n\nBunch::Bunch(std::map<std::string, double> &twissheader,\n             std::map<std::string, std::vector<double>> &twiss,\n             std::map<std::string, double> &bparam, std::vector<double> &h,\n             std::vector<double> &v) {\n  twheader = twissheader;\n  tw = twiss;\n  bunchParam = bparam;\n\n  setBasic();\n  setLongitudinalParameters(h, v);\n  setRadiationParameters();\n  setDistribution(h, v);\n};\n\nvoid Bunch::setBasic() {\n  // basic\n  double gamma = twheader[\"GAMMA\"];\n  double gammatr = twheader[\"GAMMATR\"];\n  double p0 = twheader[\"PC\"];\n  double len = twheader[\"LENGTH\"];\n  double mass = twheader[\"MASS\"];\n  double charge = twheader[\"CHARGE\"];\n  // set Atomic Number in twiss header\n  twheader[\"aatom\"] = bunchParam[\"atomNumber\"];\n  twheader[\"sigs\"] = bunchParam[\"sigs\"];\n  twheader[\"betar\"] = BetaRelativisticFromGamma(gamma);\n  twheader[\"trev\"] = len / (twheader[\"betar\"] * clight);\n  twheader[\"frev\"] = 1.0 / twheader[\"trev\"];\n  twheader[\"omega\"] = 2.0 * pi * twheader[\"frev\"];\n  twheader[\"eta\"] = eta(gamma, gammatr);\n  twheader[\"timeratio\"] = bunchParam[\"timeRatio\"];\n}\n\nvoid Bunch::setLongitudinalParameters(std::vector<double> &h,\n                                      std::vector<double> &v) {\n  double gamma = twheader[\"GAMMA\"];\n  double gammatr = twheader[\"GAMMATR\"];\n  double angularf = twheader[\"trev\"] * h[0] * twheader[\"omega\"];\n\n  // search synch phase parameters\n  double search1 = angularf / (8.0 * *std::max_element(h.begin(), h.end()));\n  double search2 = search1 + angularf / *std::min_element(h.begin(), h.end());\n  double searchWidth = angularf / (2.0 * *std::max_element(h.begin(), h.end()));\n\n  // bucket number determines phis\n  search1 += bunchParam[\"bucket\"] * 2.0 * pi;\n  search2 += bunchParam[\"bucket\"] * 2.0 * pi;\n\n  // energy loss per turn\n  double U0 = cte_radiation::RadiationLossesPerTurn(twheader);\n\n  // synchronuous phases\n  double phis = cte_long::synchronousPhaseFunctorRoot(\n      U0, v, h, bunchParam[\"charge\"], search1, search1 - searchWidth,\n      search1 + searchWidth);\n  double phis1 = cte_long::synchronousPhaseFunctorRoot(\n      U0, v, h, bunchParam[\"charge\"], search2, search2 - searchWidth,\n      search2 + searchWidth);\n\n  double phisNext = cte_long::synchronousPhaseFunctorRoot(\n      U0, v, h, bunchParam[\"charge\"], search1 + pi,\n      search1 + pi - searchWidth / 2.0, search1 + pi + searchWidth / 2.0);\n  double phis1Next = cte_long::synchronousPhaseFunctorRoot(\n      U0, v, h, bunchParam[\"charge\"], search2 + pi,\n      search2 + pi - searchWidth / 2.0, search2 + pi + searchWidth / 2.0);\n\n  // save\n  longitudinalParameters[\"sigs\"] = bunchParam[\"sigs\"];\n  longitudinalParameters[\"phis\"] = phis;\n  longitudinalParameters[\"phis1\"] = phis1;\n  longitudinalParameters[\"phisNext\"] = phisNext;\n  longitudinalParameters[\"phisNext1\"] = phis1Next;\n\n  longitudinalParameters[\"qs\"] =\n      CTESYNCH::SynchrotronTune(twheader, longitudinalParameters, v, h);\n  longitudinalParameters[\"tauhat\"] =\n      abs((phisNext - phis) / (h[0] * twheader[\"omega\"]));\n\n  // add to twheader for easy passing around of the values (pre-existing code)\n  // twheader[\"phis\"] = phis;\n  // twheader[\"phisNext\"] = phisNext;\n  // twheader[\"qs\"] = longitudinalParameters[\"qs\"];\n  twheader[\"tauhat\"] = longitudinalParameters[\"tauhat\"];\n  twheader[\"betxavg\"] = twheader[\"LENGTH\"] / (twheader[\"Q1\"] * 2.0 * pi);\n  twheader[\"betyavg\"] = twheader[\"LENGTH\"] / (twheader[\"Q2\"] * 2.0 * pi);\n  longitudinalParameters[\"sige\"] =\n      sigefromsigs(twheader[\"omega\"], bunchParam[\"sigs\"],\n                   longitudinalParameters[\"qs\"], gamma, gammatr);\n  longitudinalParameters[\"delta\"] =\n      dee_to_dpp(twheader[\"sige\"], twheader[\"betar\"]);\n}\n\nvoid Bunch::setRadiationParameters() {\n  // add energy loss per turn\n  double U0 = cte_radiation::RadiationLossesPerTurn(twheader);\n  // add the equilibrium values and radiation damping times\n  radiationParameters =\n      cte_radiation::radiationEquilib(twheader, longitudinalParameters);\n  radiationParameters[\"U0\"] = U0;\n  cte_radiation::CalcRadDecayExcitation(twheader, radiationParameters);\n};\n\nvoid Bunch::setDistribution(std::vector<double> &h, std::vector<double> &v) {\n  distribution = cte_distributions::GenerateDistributionMatched(\n      bunchParam[\"nMacro\"], twheader[\"betxavg\"], bunchParam[\"ex\"],\n      twheader[\"betyavg\"], bunchParam[\"ey\"], h, v, twheader,\n      longitudinalParameters, bunchParam[\"seed\"]);\n}\n\nvoid Bunch::getEmittance() {\n  std::vector<double> out, avg;\n  std::vector<double> res;\n  for (int i = 0; i < distribution[0].size(); i++) {\n    out.push_back(0.0);\n    avg.push_back(0.0);\n  }\n\n  // calculate averages\n  std::for_each(distribution.begin(), distribution.end(),\n                [&](std::vector<double> v) {\n                  for (int i = 0; i < distribution[0].size(); i++) {\n                    avg[i] += v[i] / distribution.size();\n                  }\n                });\n\n  // subtract avg, square and sum\n  std::for_each(\n      distribution.begin(), distribution.end(), [&](std::vector<double> v) {\n        for (int i = 0; i < distribution[0].size(); i++) {\n          out[i] += ((v[i] - avg[i]) * (v[i] - avg[i])) / distribution.size();\n        }\n      });\n\n  out[0] /= twheader[\"betxavg\"];\n  out[2] /= twheader[\"betyavg\"];\n  out[4] = sqrt(out[4]) * clight;\n  out[5] = sqrt(out[5]);\n\n  res.push_back(out[0]);\n  res.push_back(out[2]);\n  res.push_back(out[4]);\n  res.push_back(out[5]);\n\n  emittances.push_back(res);\n}\n\nvoid Bunch::getIBSGrowthRates(int model) {\n\n  double pnumber = bunchParam[\"nReal\"];\n  std::vector<double> emit = emittances.back();\n  double ex = emit[0];\n  double ey = emit[1];\n  double sigs = emit[2];\n  double sige = emit[3];\n  double aatom = twheader[\"aatom\"];\n  double r0 = ParticleRadius(twheader[\"CHARGE\"], aatom);\n  double *ibs;\n  /*\n    std::printf(\"%-30s %12.8e\\n\", \"aatom\", aatom);\n    std::printf(\"%-30s %12.8e\\n\", \"ex\", ex);\n    std::printf(\"%-30s %12.8e\\n\", \"ey\", ey);\n    std::printf(\"%-30s %12.8e\\n\", \"ro\", r0);\n    std::printf(\"%-30s %12.8e\\n\", \"pnumber\", pnumber);\n  */\n  // ibs growth rates update\n  switch (model) {\n  case 1:\n    ibs = PiwinskiSmooth(pnumber, ex, ey, sigs, sige, twheader, r0);\n    break;\n  case 2:\n    ibs = PiwinskiLattice(pnumber, ex, ey, sigs, sige, twheader, tw, r0);\n    break;\n  case 3:\n    ibs =\n        PiwinskiLatticeModified(pnumber, ex, ey, sigs, sige, twheader, tw, r0);\n    break;\n  case 4:\n    ibs = Nagaitsev(pnumber, ex, ey, sigs, sige, twheader, tw, r0);\n    break;\n  case 5:\n    ibs =\n        Nagaitsevtailcut(pnumber, ex, ey, sigs, sige, twheader, tw, r0, aatom);\n    break;\n  case 6:\n    ibs = ibsmadx(pnumber, ex, ey, sigs, sige, twheader, tw, r0, false);\n    break;\n  case 7:\n    ibs = ibsmadxtailcut(pnumber, ex, ey, sigs, sige, twheader, tw, r0, aatom);\n    break;\n  case 8:\n    ibs = BjorkenMtingwa2(pnumber, ex, ey, sigs, sige, twheader, tw, r0);\n    break;\n  case 9:\n    ibs = BjorkenMtingwa(pnumber, ex, ey, sigs, sige, twheader, tw, r0);\n    break;\n  case 10:\n    ibs = BjorkenMtingwatailcut(pnumber, ex, ey, sigs, sige, twheader, tw, r0,\n                                aatom);\n    break;\n  case 11:\n    ibs = ConteMartini(pnumber, ex, ey, sigs, sige, twheader, tw, r0);\n    break;\n  case 12:\n    ibs = ConteMartinitailcut(pnumber, ex, ey, sigs, sige, twheader, tw, r0,\n                              aatom);\n    break;\n  case 13:\n    ibs = MadxIBS(pnumber, ex, ey, sigs, sige, twheader, tw, r0);\n    break;\n  }\n\n  std::vector<double> ibsgr;\n  for (int i = 0; i < 3; i++) {\n    // std::printf(\"%-30s %12.8e\\n\", \"ibs\", ibs[i]);\n    ibsgr.push_back(ibs[i] * 2.0 * bunchParam[\"fracibstot\"] *\n                    bunchParam[\"nMacro\"] * bunchParam[\"timeRatio\"] /\n                    bunchParam[\"nReal\"]);\n  }\n  ibsGrowthRates.push_back(ibsgr);\n}\n\nvoid Bunch::getIBSCoefficients() {\n  double coeffs, coeffx, coeffy;\n  double alphaAverage;\n  double coeffMulT;\n\n  std::vector<double> ibsgr = ibsGrowthRates.back();\n  double alfax = ibsgr[1];\n  double alfay = ibsgr[2];\n  double alfap = ibsgr[0];\n  /*\n    std::printf(\"%-30s %12.8e\\n\", \"alfax\", alfax);\n    std::printf(\"%-30s %12.8e\\n\", \"alfay\", alfay);\n    std::printf(\"%-30s %12.8e\\n\", \"alfap\", alfap);\n  */\n  double dtsamp2 = 2.0 * longitudinalParameters[\"tauhat\"] / bunchParam[\"nbins\"];\n  double rmsdelta = CalcRMS(distribution)[5];\n  std::vector<double> emit = emittances.back();\n  double sigs = emit[3];\n\n  double rmsx = sqrt(emit[0] * twheader[\"betxavg\"]);\n  double rmsy = sqrt(emit[1] * twheader[\"betyavg\"]);\n\n  // debugging\n  // cout << \"alfap \" << alfap << endl << endl;\n  if (alfap > 0.0)\n    coeffs = sqrt(6.0 * alfap * twheader[\"trev\"]) * rmsdelta;\n  else\n    coeffs = 0.00;\n\n  // coupling\n  if (bunchParam[\"ibsCoupling\"] == 0.0) {\n    if (alfay > 0.0)\n      coeffy = sqrt(6.0 * alfay * twheader[\"trev\"]) * rmsy;\n    else\n      coeffy = 0.0;\n\n    if (alfax > 0.0)\n      coeffx = sqrt(6.0 * alfax * twheader[\"trev\"]) * rmsx;\n    else\n      coeffx = 0.0;\n  } else {\n    // alphaAverage\n    alphaAverage = 0.5 * (alfax + alfay);\n    if (alphaAverage > 0.0) {\n      coeffx = sqrt(6.0 * alphaAverage * twheader[\"trev\"]) * rmsx;\n      coeffy = sqrt(6.0 * alphaAverage * twheader[\"trev\"]) * rmsy;\n    } else {\n      coeffx = 0.0;\n      coeffy = 0.0;\n    }\n    // end if alphaAverage\n  }\n  // end if ibs coupling\n  coeffMulT = sigs * 2.0 * sqrt(pi) / (bunchParam[\"nMacro\"] * dtsamp2 * clight);\n\n  std::vector<double> ibscoeffs;\n  ibscoeffs.push_back(coeffx);\n  ibscoeffs.push_back(coeffy);\n  ibscoeffs.push_back(coeffs);\n  ibscoeffs.push_back(coeffMulT);\n\n  ibsCoeff.push_back(ibscoeffs);\n}\n\nvoid Bunch::updateIBS(std::vector<double> &h) {\n  histogramTime = ParticlesTimesToHistogram(\n      distribution, bunchParam[\"nbins\"], longitudinalParameters[\"tauhat\"] / 2.,\n      longitudinalParameters[\"phisNext\"] / (h[0] * twheader[\"omega\"]));\n  /*\n    for (std::vector<int>::const_iterator i = histogramTime.begin();\n         i != histogramTime.end(); ++i) {\n      std::printf(\"%3i\\n\", *i);\n    }\n  */\n  getIBSGrowthRates(bunchParam[\"model\"]);\n  getIBSCoefficients();\n  /*\n  std::for_each(ibsCoeff.begin(), ibsCoeff.end(),\n                [](std::vector<double> &particle) {\n                  std::printf(\"%12.8e %12.8e %12.8e \\n\", particle[0],\n                              particle[1], particle[2]);\n                });\n*/\n  sqrthistogram = HistogramToSQRTofCumul(histogramTime, ibsCoeff.back()[3]);\n  // for (std::vector<double>::const_iterator i = sqrthistogram.begin();\n  //   i != sqrthistogram.end(); ++i)\n  //  std::printf(\"%4.2f \", *i);\n  // std::printf(\"\\n\");\n}\n/*\n************************************************************************************************************************\n************************************************************************************************************************\n*/\nvoid Bunch::printBunchParameters() {\n  std::printf(\"%-30s\\n\", \"Bunch Parameters\");\n  std::printf(\"%-30s\\n\", \"================\");\n  for (auto const &pair : bunchParam) {\n    std::printf(\"%-30s %16.8e\\n\", pair.first.c_str(), pair.second);\n  }\n  std::printf(\"\\n\");\n}\n\nvoid Bunch::printTwissHeader() {\n  std::printf(\"%-30s\\n\", \"Twiss Header\");\n  std::printf(\"%-30s\\n\", \"============\");\n  for (auto const &pair : twheader) {\n    std::printf(\"%-30s %16.8e\\n\", pair.first.c_str(), pair.second);\n  }\n  std::printf(\"\\n\");\n}\n\nvoid Bunch::printLongParam() {\n  std::printf(\"%-30s\\n\", \"Longitudinal Parameters\");\n  std::printf(\"%-30s\\n\", \"=======================\");\n  for (auto const &pair : longitudinalParameters) {\n    std::printf(\"%-30s %16.8e\\n\", pair.first.c_str(), pair.second);\n  }\n  std::printf(\"\\n\");\n}\nvoid Bunch::printRadiationParameters() {\n  std::printf(\"%-30s\\n\", \"Radiation Parameters\");\n  std::printf(\"%-30s\\n\", \"===================\");\n  for (auto const &pair : Bunch::radiationParameters) {\n    std::printf(\"%-30s %16.8e\\n\", pair.first.c_str(), pair.second);\n  }\n  std::printf(\"\\n\");\n}\n\nvoid Bunch::printDistribution() {\n  std::for_each(distribution.begin(), distribution.end(),\n                [](std::vector<double> &particle) {\n                  std::printf(\"%12.8e %12.8e %12.8e %12.8e %12.8e %12.8e\\n\",\n                              particle[0], particle[1], particle[2],\n                              particle[3], particle[4], particle[5]);\n                });\n\n  std::printf(\"\\n\");\n};\n\nvoid Bunch::printEmittance() {\n  std::for_each(emittances.begin(), emittances.end(),\n                [](std::vector<double> &particle) {\n                  std::printf(\"%12.8e %12.8e %12.8e %12.8e\\n\", particle[0],\n                              particle[1], particle[2], particle[3]);\n                });\n\n  std::printf(\"\\n\");\n};\n\nvoid Bunch::printIBSGrowthRates() {\n  std::for_each(ibsGrowthRates.begin(), ibsGrowthRates.end(),\n                [](std::vector<double> &particle) {\n                  std::printf(\"%12.8e %12.8e %12.8e\\n\", particle[0],\n                              particle[1], particle[2]);\n                });\n\n  std::printf(\"\\n\");\n};\n\nvoid Bunch::printDebunchLosses() {\n  for (int i = 0; i < debunchLosses.size(); i++) {\n    std::printf(\"%12i\\n\", debunchLosses[i]);\n  };\n}\n#define MAX_DATE 12\n\nstd::string Bunch::get_date() {\n\n  /* function returning current date as string for creating timestamped output\n   * files */\n\n  time_t now;\n\n  // struct tm * timeinfo;\n  char the_date[MAX_DATE];\n  // char buffer [80];\n\n  // time_t rawtime;\n  // timeinfo = localtime (&rawtime);\n  // strftime (buffer,80,\"Now it's %I:%M%p.\",timeinfo);\n\n  // std::stringstream ss;\n  // ss << fn << \"_\" << \"%d_%m_%Y\" << \"_\" << buffer << \".dat\";\n  // std::string s = ss.str();\n\n  the_date[0] = '\\0';\n\n  now = time(NULL);\n\n  if (now != -1) {\n    strftime(the_date, MAX_DATE, \"%d_%m_%Y\", gmtime(&now));\n  }\n\n  return std::string(the_date);\n}\n\ntemplate <typename T>\nstd::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {\n  for (int i = 0; i < v.size(); i++) {\n    os << std::scientific << std::setw(15) << v[i];\n  }\n  // os << std::endl;\n  // std::copy(v.begin(), v.end(), ostream_iterator<T>(os, \"\\t\"));\n  return os;\n}\n\ntemplate <typename T>\nstd::ostream &operator<<(std::ostream &os,\n                         const std::vector<std::vector<T>> &v) {\n  using namespace std;\n\n  // NOTE: for some reason std::copy doesn't work here, so I use manual loop\n  // copy(v.begin(), v.end(), ostream_iterator<std::vector<T>>(os, \"\\n\"));\n\n  for (size_t i = 0; i < v.size(); ++i)\n    os << std::setw(6) << i << v[i] << \"\\n\";\n  return os;\n}\n\nvoid Bunch::writeDistribution(int turn) {\n\n  std::stringstream ss;\n  ss << \"Distribution_bucket_\" << bunchParam[\"bucket\"] << \"_\"\n     << get_date()\n     // << \"_turn_\" << std::setw(10) << std::setfill('0') << turn\n     << \".dat\";\n\n  std::string s;\n  s = ss.str();\n\n  if (turn == 0) {\n    if (remove(s.c_str()) != 0)\n      perror(\"Error deleting file\");\n    else\n      puts(\"File successfully deleted\");\n  }\n  std::ofstream ofile;\n  ofile.open(s.c_str(), std::ios_base::app);\n  ofile << distribution;\n  // std::copy(distribution.begin(), distribution.end(),\n  //        std::ostream_iterator<std::vector<double>>(ofile));\n\n  // std::cout << \"writing vector size = \" << distribution.size() << std::endl;\n  ofile.close();\n}\n\nvoid Bunch::writeEmittances() {\n\n  std::stringstream ss;\n  ss << \"CTE_Emittances_\" << bunchParam[\"bucket\"] << \"_\" << get_date()\n     << \".dat\";\n\n  std::string s;\n  s = ss.str();\n\n  if (remove(s.c_str()) != 0)\n    perror(\"Error deleting file\");\n  else\n    puts(\"File successfully deleted\");\n\n  std::ofstream ofile(s.c_str());\n  ofile << emittances;\n\n  ofile.close();\n}", "meta": {"hexsha": "303fe0364c0476a14bfd2f95b0b6551cbb58625b", "size": 20705, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/bunch.cpp", "max_stars_repo_name": "tomerten/ctelib", "max_stars_repo_head_hexsha": "582c215667e240a65f07ac75468e0870bee88a4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/src/bunch.cpp", "max_issues_repo_name": "tomerten/ctelib", "max_issues_repo_head_hexsha": "582c215667e240a65f07ac75468e0870bee88a4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/src/bunch.cpp", "max_forks_repo_name": "tomerten/ctelib", "max_forks_repo_head_hexsha": "582c215667e240a65f07ac75468e0870bee88a4d", "max_forks_repo_licenses": ["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.6062992126, "max_line_length": 120, "alphanum_fraction": 0.5556145858, "num_tokens": 5913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2901198522155667}}
{"text": "#include \"utils/stl_to_string.hpp\"\n#include \"trajopt/kinematic_constraints.hpp\"\n#include \"trajopt/utils.hpp\"\n#include \"trajopt/rave_utils.hpp\"\n#include \"utils/logging.hpp\"\n#include \"sco/expr_ops.hpp\"\n#include \"sco/modeling_utils.hpp\"\n#include <boost/format.hpp>\n#include <boost/bind.hpp>\n#include <iostream>\n#include <Eigen/Geometry>\n#include <openrave/openrave.h>\n#include \"utils/eigen_conversions.hpp\"\n#include \"utils/eigen_slicing.hpp\"\nusing namespace std;\nusing namespace sco;\nusing namespace Eigen;\nusing namespace util;\n\nnamespace {\n\n\nstatic MatrixXd diffAxis0(const MatrixXd& in) {\n  return in.middleRows(1, in.rows()-1) - in.middleRows(0, in.rows()-1);\n}\nVector3d rotVec(const Matrix3d& m) {\n  Quaterniond q; q = m;\n  return Vector3d(q.x(), q.y(), q.z());\n}\nVector3d rotVec(const OpenRAVE::Vector& q) {\n  return Vector3d(q[1], q[2], q[3]);\n}\n\nVectorXd concat(const VectorXd& a, const VectorXd& b) {\n  VectorXd out(a.size()+b.size());\n  out.topRows(a.size()) = a;\n  out.middleRows(a.size(), b.size()) = b;\n  return out;\n}\n\ntemplate <typename T>\nvector<T> concat(const vector<T>& a, const vector<T>& b) {\n  vector<T> out;\n  vector<int> x;\n  out.insert(out.end(), a.begin(), a.end());\n  out.insert(out.end(), b.begin(), b.end());\n  return out;\n}\n\n\n}\n\nnamespace trajopt {\n\n//////////////////////\n\n\n\nvoid makeTrajVariablesAndBounds(int n_steps, RobotAndDOFPtr manip, OptProb& prob_out, VarArray& vars_out) {\n  int n_dof = manip->GetDOF();\n  DblVec lower, upper;\n  manip->GetDOFLimits(lower, upper);\n  LOG_INFO(\"Dof limits: %s, %s\", CSTR(lower), CSTR(upper));\n  vector<double> vlower, vupper;\n  vector<string> names;\n  for (int i=0; i < n_steps; ++i) {\n    vlower.insert(vlower.end(), lower.data(), lower.data()+lower.size());\n    vupper.insert(vupper.end(), upper.data(), upper.data()+upper.size());\n    for (unsigned j=0; j < n_dof; ++j) {\n      names.push_back( (boost::format(\"j_%i_%i\")%i%j).str() );\n    }\n  }\n\n  prob_out.createVariables(names, vlower, vupper);\n  vars_out = VarArray(n_steps, n_dof, prob_out.getVars().data());\n\n}\n\nJointPosCost::JointPosCost(const VarVector& vars, const VectorXd& vals, const VectorXd& coeffs) :\n    Cost(\"JointVel\"), vars_(vars), vals_(vals), coeffs_(coeffs) {\n    for (int i=0; i < vars.size(); ++i) {\n      if (coeffs[i] > 0) {\n        AffExpr diff = exprSub(AffExpr(vars[i]), AffExpr(vals[i]));\n        exprInc(expr_, exprMult(exprSquare(diff), coeffs[i]));\n      }\n    }\n}\ndouble JointPosCost::value(const vector<double>& xvec) {\n  VectorXd dofs = getVec(xvec, vars_);\n  return ((dofs - vals_).array().square() * coeffs_.array()).sum();\n}\nConvexObjectivePtr JointPosCost::convex(const vector<double>& x, Model* model) {\n  ConvexObjectivePtr out(new ConvexObjective(model));\n  out->addQuadExpr(expr_);\n  return out;\n}\n\n\nJointVelCost::JointVelCost(const VarArray& vars, const VectorXd& coeffs) :\n    Cost(\"JointVel\"), vars_(vars), coeffs_(coeffs) {\n  for (int i=0; i < vars.rows()-1; ++i) {\n    for (int j=0; j < vars.cols(); ++j) {\n      AffExpr vel;\n      exprInc(vel, exprMult(vars(i,j), -1));\n      exprInc(vel, exprMult(vars(i+1,j), 1));\n      exprInc(expr_, exprMult(exprSquare(vel),coeffs_[j]));\n    }\n  }\n}\ndouble JointVelCost::value(const vector<double>& xvec) {\n  MatrixXd traj = getTraj(xvec, vars_);\n  return (diffAxis0(traj).array().square().matrix() * coeffs_.asDiagonal()).sum();\n}\nConvexObjectivePtr JointVelCost::convex(const vector<double>& x, Model* model) {\n  ConvexObjectivePtr out(new ConvexObjective(model));\n  out->addQuadExpr(expr_);\n  return out;\n}\n\n\n\nJointAccCost::JointAccCost(const VarArray& vars, const VectorXd& coeffs) :\n    Cost(\"JointAcc\"), vars_(vars), coeffs_(coeffs) {\n  for (int i=0; i < vars.rows()-2; ++i) {\n    for (int j=0; j < vars.cols(); ++j) {\n      AffExpr acc;\n      exprInc(acc, exprMult(vars(i,j), -1));\n      exprInc(acc, exprMult(vars(i+1,j), 2));\n      exprInc(acc, exprMult(vars(i+2,j), -1));\n      exprInc(expr_, exprMult(exprSquare(acc), coeffs_[j]));\n    }\n  }\n}\ndouble JointAccCost::value(const vector<double>& xvec) {\n  MatrixXd traj = getTraj(xvec, vars_);\n  return (diffAxis0(diffAxis0(traj)).array().square().matrix() * coeffs_.asDiagonal()).sum();\n}\nConvexObjectivePtr JointAccCost::convex(const vector<double>& x, Model* model) {\n  ConvexObjectivePtr out(new ConvexObjective(model));\n  out->addQuadExpr(expr_);\n  return out;\n}\n\n\n\n\nstruct CartPoseErrCalculator : public VectorOfVector {\n  OR::Transform pose_inv_;\n  RobotAndDOFPtr manip_;\n  OR::KinBody::LinkPtr link_;\n  VectorXd coeffs_;\n  CartPoseErrCalculator(const OR::Transform& pose, RobotAndDOFPtr manip, OR::KinBody::LinkPtr link, const VectorXd& coeffs) :\n  pose_inv_(pose.inverse()),\n  manip_(manip),\n  link_(link),\n  coeffs_(coeffs)\n  {}\n//  CartPoseCostCalculator(const CartPoseCostCalculator& other) : pose_(other.pose_), manip_(other.manip_), rs_(other.rs_) {}\n  VectorXd operator()(const VectorXd& dof_vals) const {\n    manip_->SetDOFValues(toDblVec(dof_vals));\n    OR::Transform newpose = link_->GetTransform();\n\n    OR::Transform pose_err = pose_inv_ * newpose;\n    VectorXd err = coeffs_.cwiseProduct(concat(rotVec(pose_err.rot), toVector3d(pose_err.trans)));\n    return err;\n  }\n};\n\nCartPoseCost::CartPoseCost(const VarVector& vars, const OR::Transform& pose, const Vector3d& rot_coeffs,\n    const Vector3d& pos_coeffs, RobotAndDOFPtr manip, KinBody::LinkPtr link) :\n    CostFromErrFunc(VectorOfVectorPtr(new CartPoseErrCalculator(pose, manip, link, VectorXd::Ones(6))),\n        vars, concat(rot_coeffs, pos_coeffs), ABS, \"CartPose\")\n{}\nvoid CartPoseCost::Plot(const DblVec& x, OR::EnvironmentBase& env, std::vector<OR::GraphHandlePtr>& handles) {\n  CartPoseErrCalculator* calc = static_cast<CartPoseErrCalculator*>(f_.get());\n  DblVec dof_vals = getDblVec(x, vars_);\n  calc->manip_->SetDOFValues(dof_vals);\n  OR::Transform target = calc->pose_inv_.inverse(), cur = calc->link_->GetTransform();\n  PlotAxes(env, cur, .1,  handles);\n  PlotAxes(env, target, .1,  handles);\n  handles.push_back(env.drawarrow(cur.trans, target.trans, .01, OR::Vector(1,0,1,1)));\n}\n\n\nCartPoseConstraint::CartPoseConstraint(const VarVector& vars, const OR::Transform& pose,\n    RobotAndDOFPtr manip, KinBody::LinkPtr link, const VectorXd& coeffs) :\n    ConstraintFromFunc(VectorOfVectorPtr(new CartPoseErrCalculator(pose, manip, link, coeffs)),\n        vars, EQ, \"CartPose\")\n{\n}\n\nvoid CartPoseConstraint::Plot(const DblVec& x, OR::EnvironmentBase& env, std::vector<OR::GraphHandlePtr>& handles) {\n  // IDENTITCAL TO CartPoseCost::Plot\n  CartPoseErrCalculator* calc = static_cast<CartPoseErrCalculator*>(f_.get());\n  DblVec dof_vals = getDblVec(x, vars_);\n  calc->manip_->SetDOFValues(dof_vals);\n  OR::Transform target = calc->pose_inv_.inverse(), cur = calc->link_->GetTransform();\n  PlotAxes(env, cur, .1,  handles);\n  PlotAxes(env, target, .1,  handles);\n  handles.push_back(env.drawarrow(cur.trans, target.trans, .01, OR::Vector(1,0,1,1)));\n}\n\n\nstruct CartPositionErrCalculator {\n  Vector3d pt_world_;\n  RobotAndDOFPtr manip_;\n  OR::KinBody::LinkPtr link_;\n  CartPositionErrCalculator(const Vector3d& pt_world, RobotAndDOFPtr manip, OR::KinBody::LinkPtr link) :\n  pt_world_(pt_world),\n  manip_(manip),\n  link_(link)\n  {}\n  VectorXd operator()(const VectorXd& dof_vals) {\n    manip_->SetDOFValues(toDblVec(dof_vals));\n    OR::Transform newpose = link_->GetTransform();\n    return pt_world_ - toVector3d(newpose.trans);\n  }\n};\n\nstruct CartVelJacCalculator : MatrixOfVector {\n  RobotAndDOFPtr manip_;\n  KinBody::LinkPtr link_;\n  double limit_;\n  CartVelJacCalculator(RobotAndDOFPtr manip, KinBody::LinkPtr link, double limit) :\n    manip_(manip), link_(link), limit_(limit) {}\n\n  MatrixXd operator()(const VectorXd& dof_vals) const {\n    int n_dof = manip_->GetDOF();\n    MatrixXd out(6, 2*n_dof);\n    manip_->SetDOFValues(toDblVec(dof_vals.topRows(n_dof)));\n    OR::Transform pose0 = link_->GetTransform();\n    MatrixXd jac0 = manip_->PositionJacobian(link_->GetIndex(), pose0.trans);\n    manip_->SetDOFValues(toDblVec(dof_vals.bottomRows(n_dof)));\n    OR::Transform pose1 = link_->GetTransform();\n    MatrixXd jac1 = manip_->PositionJacobian(link_->GetIndex(), pose1.trans);\n    out.block(0,0,3,n_dof) = -jac0;\n    out.block(0,n_dof,3,n_dof) = jac1;\n    out.block(3,0,3,n_dof) = jac0;\n    out.block(3,n_dof,3,n_dof) = -jac1;\n    return out;\n  }\n};\n\nstruct CartVelCalculator : VectorOfVector {\n  RobotAndDOFPtr manip_;\n  KinBody::LinkPtr link_;\n  double limit_;\n  CartVelCalculator(RobotAndDOFPtr manip, KinBody::LinkPtr link, double limit) :\n    manip_(manip), link_(link), limit_(limit) {}\n\n  VectorXd operator()(const VectorXd& dof_vals) const {\n    int n_dof = manip_->GetDOF();\n    manip_->SetDOFValues(toDblVec(dof_vals.topRows(n_dof)));\n    OR::Transform pose0 = link_->GetTransform();\n    manip_->SetDOFValues(toDblVec(dof_vals.bottomRows(n_dof)));\n    OR::Transform pose1 = link_->GetTransform();\n    VectorXd out(6);\n    out.topRows(3) = toVector3d(pose1.trans - pose0.trans - OR::Vector(limit_,limit_,limit_));\n    out.bottomRows(3) = toVector3d( - pose1.trans + pose0.trans - OR::Vector(limit_, limit_, limit_));\n    return out;\n  }\n};\n\nCartVelConstraint::CartVelConstraint(const VarVector& step0vars, const VarVector& step1vars, RobotAndDOFPtr manip, KinBody::LinkPtr link, double distlimit) :\n        ConstraintFromFunc(VectorOfVectorPtr(new CartVelCalculator(manip, link, distlimit)),\n                           MatrixOfVectorPtr(new CartVelJacCalculator(manip, link, distlimit)),\n                          concat(step0vars, step1vars), INEQ, \"CartVel\")\n{}\n\n\n\nstruct UpErrorCalculator {\n  Vector3d dir_local_;\n  Vector3d goal_dir_world_;\n  RobotAndDOFPtr manip_;\n  OR::KinBody::LinkPtr link_;\n  MatrixXd perp_basis_; // 2x3 matrix perpendicular to goal_dir_world\n  UpErrorCalculator(const Vector3d& dir_local, const Vector3d& goal_dir_world, RobotAndDOFPtr manip, KinBody::LinkPtr link) :\n    dir_local_(dir_local),\n    goal_dir_world_(goal_dir_world),\n    manip_(manip),\n    link_(link)\n  {\n    Vector3d perp0 = goal_dir_world_.cross(Vector3d::Random()).normalized();\n    Vector3d perp1 = goal_dir_world_.cross(perp0);\n    perp_basis_.resize(2,3);\n    perp_basis_.row(0) = perp0.transpose();\n    perp_basis_.row(1) = perp1.transpose();\n  }\n  VectorXd operator()(const VectorXd& dof_vals) {\n    manip_->SetDOFValues(toDblVec(dof_vals));\n    OR::Transform newpose = link_->GetTransform();\n    return perp_basis_*(toRot(newpose.rot) * dir_local_ - goal_dir_world_);\n  }\n};\n}\n", "meta": {"hexsha": "b34539dae7675efd10160b4d7d969bc2c23a3de9", "size": 10441, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/trajopt/kinematic_constraints.cpp", "max_stars_repo_name": "alexlee-gk/trajopt", "max_stars_repo_head_hexsha": "49f56583b22a921d88eede6b268181167b049b41", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-04-07T14:03:38.000Z", "max_stars_repo_stars_event_max_datetime": "2016-04-07T14:03:38.000Z", "max_issues_repo_path": "src/trajopt/kinematic_constraints.cpp", "max_issues_repo_name": "alexlee-gk/trajopt", "max_issues_repo_head_hexsha": "49f56583b22a921d88eede6b268181167b049b41", "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/trajopt/kinematic_constraints.cpp", "max_forks_repo_name": "alexlee-gk/trajopt", "max_forks_repo_head_hexsha": "49f56583b22a921d88eede6b268181167b049b41", "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.1548821549, "max_line_length": 157, "alphanum_fraction": 0.6975385499, "num_tokens": 3030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.29007846727883835}}
{"text": "#include \"outer_hull.h\"\n#include \"order_facets_around_edges.h\"\n#include \"../outer_facet.h\"\n#include \"../sortrows.h\"\n#include \"../facet_components.h\"\n#include \"../winding_number.h\"\n#include \"../triangle_triangle_adjacency.h\"\n#include \"../unique_edge_map.h\"\n#include \"../barycenter.h\"\n#include \"../per_face_normals.h\"\n#include \"../writePLY.h\"\n#include \"../sort_angles.h\"\n\n#include <Eigen/Geometry>\n#include <vector>\n#include <map>\n#include <queue>\n#include <iostream>\n#include <CGAL/number_utils.h>\n//#define IGL_OUTER_HULL_DEBUG\n\ntemplate <\n  typename DerivedV,\n  typename DerivedF,\n  typename DerivedN,\n  typename DerivedG,\n  typename DerivedJ,\n  typename Derivedflip>\nIGL_INLINE void igl::outer_hull(\n  const Eigen::PlainObjectBase<DerivedV> & V,\n  const Eigen::PlainObjectBase<DerivedF> & F,\n  const Eigen::PlainObjectBase<DerivedN> & N,\n  Eigen::PlainObjectBase<DerivedG> & G,\n  Eigen::PlainObjectBase<DerivedJ> & J,\n  Eigen::PlainObjectBase<Derivedflip> & flip)\n{\n#ifdef IGL_OUTER_HULL_DEBUG\n  std::cerr << \"Extracting outer hull\" << std::endl;\n#endif\n  using namespace Eigen;\n  using namespace std;\n  typedef typename DerivedF::Index Index;\n  Matrix<Index,DerivedF::RowsAtCompileTime,1> C;\n  typedef Matrix<typename DerivedV::Scalar,Dynamic,DerivedV::ColsAtCompileTime> MatrixXV;\n  typedef Matrix<typename DerivedF::Scalar,Dynamic,DerivedF::ColsAtCompileTime> MatrixXF;\n  typedef Matrix<typename DerivedG::Scalar,Dynamic,DerivedG::ColsAtCompileTime> MatrixXG;\n  typedef Matrix<typename DerivedJ::Scalar,Dynamic,DerivedJ::ColsAtCompileTime> MatrixXJ;\n  typedef Matrix<typename DerivedN::Scalar,1,3> RowVector3N;\n  const Index m = F.rows();\n\n  // UNUSED:\n  //const auto & duplicate_simplex = [&F](const int f, const int g)->bool\n  //{\n  //  return\n  //    (F(f,0) == F(g,0) && F(f,1) == F(g,1) && F(f,2) == F(g,2)) ||\n  //    (F(f,1) == F(g,0) && F(f,2) == F(g,1) && F(f,0) == F(g,2)) ||\n  //    (F(f,2) == F(g,0) && F(f,0) == F(g,1) && F(f,1) == F(g,2)) ||\n  //    (F(f,0) == F(g,2) && F(f,1) == F(g,1) && F(f,2) == F(g,0)) ||\n  //    (F(f,1) == F(g,2) && F(f,2) == F(g,1) && F(f,0) == F(g,0)) ||\n  //    (F(f,2) == F(g,2) && F(f,0) == F(g,1) && F(f,1) == F(g,0));\n  //};\n\n#ifdef IGL_OUTER_HULL_DEBUG\n  cout<<\"outer hull...\"<<endl;\n#endif\n\n#ifdef IGL_OUTER_HULL_DEBUG\n  cout<<\"edge map...\"<<endl;\n#endif\n  typedef Matrix<typename DerivedF::Scalar,Dynamic,2> MatrixX2I;\n  typedef Matrix<typename DerivedF::Index,Dynamic,1> VectorXI;\n  typedef Matrix<typename DerivedV::Scalar, 3, 1> Vector3F;\n  MatrixX2I E,uE;\n  VectorXI EMAP;\n  vector<vector<typename DerivedF::Index> > uE2E;\n  unique_edge_map(F,E,uE,EMAP,uE2E);\n#ifdef IGL_OUTER_HULL_DEBUG\n  for (size_t ui=0; ui<uE.rows(); ui++) {\n      std::cout << ui << \": \" << uE2E[ui].size() << \" -- (\";\n      for (size_t i=0; i<uE2E[ui].size(); i++) {\n          std::cout << uE2E[ui][i] << \", \";\n      }\n      std::cout << \")\" << std::endl;\n  }\n#endif\n\n  std::vector<std::vector<typename DerivedF::Index> > uE2oE;\n  std::vector<std::vector<bool> > uE2C;\n  order_facets_around_edges(V, F, N, E, uE, EMAP, uE2E, uE2oE, uE2C);\n  uE2E = uE2oE;\n  VectorXI diIM(3*m);\n  for (auto ue : uE2E) {\n      for (size_t i=0; i<ue.size(); i++) {\n          auto fe = ue[i];\n          diIM[fe] = i;\n      }\n  }\n\n  vector<vector<vector<Index > > > TT,_1;\n  triangle_triangle_adjacency(E,EMAP,uE2E,false,TT,_1);\n  VectorXI counts;\n#ifdef IGL_OUTER_HULL_DEBUG\n  cout<<\"facet components...\"<<endl;\n#endif\n  facet_components(TT,C,counts);\n  assert(C.maxCoeff()+1 == counts.rows());\n  const size_t ncc = counts.rows();\n  G.resize(0,F.cols());\n  J.resize(0,1);\n  flip.setConstant(m,1,false);\n\n#ifdef IGL_OUTER_HULL_DEBUG\n  cout<<\"reindex...\"<<endl;\n#endif\n  // H contains list of faces on outer hull;\n  vector<bool> FH(m,false);\n  vector<bool> EH(3*m,false);\n  vector<MatrixXG> vG(ncc);\n  vector<MatrixXJ> vJ(ncc);\n  vector<MatrixXJ> vIM(ncc);\n  //size_t face_count = 0;\n  for(size_t id = 0;id<ncc;id++)\n  {\n    vIM[id].resize(counts[id],1);\n  }\n  // current index into each IM\n  vector<size_t> g(ncc,0);\n  // place order of each face in its respective component\n  for(Index f = 0;f<m;f++)\n  {\n    vIM[C(f)](g[C(f)]++) = f;\n  }\n\n#ifdef IGL_OUTER_HULL_DEBUG\n  cout<<\"barycenters...\"<<endl;\n#endif\n  // assumes that \"resolve\" has handled any coplanar cases correctly and nearly\n  // coplanar cases can be sorted based on barycenter.\n  MatrixXV BC;\n  barycenter(V,F,BC);\n\n#ifdef IGL_OUTER_HULL_DEBUG\n  cout<<\"loop over CCs (=\"<<ncc<<\")...\"<<endl;\n#endif\n  for(Index id = 0;id<(Index)ncc;id++)\n  {\n    auto & IM = vIM[id];\n    // starting face that's guaranteed to be on the outer hull and in this\n    // component\n    int f;\n    bool f_flip;\n#ifdef IGL_OUTER_HULL_DEBUG\n  cout<<\"outer facet...\"<<endl;\n#endif\n    outer_facet(V,F,N,IM,f,f_flip);\n#ifdef IGL_OUTER_HULL_DEBUG\n  cout<<\"outer facet: \"<<f<<endl;\n  cout << V.row(F(f, 0)) << std::endl;\n  cout << V.row(F(f, 1)) << std::endl;\n  cout << V.row(F(f, 2)) << std::endl;\n#endif\n    int FHcount = 1;\n    FH[f] = true;\n    // Q contains list of face edges to continue traversing upong\n    queue<int> Q;\n    Q.push(f+0*m);\n    Q.push(f+1*m);\n    Q.push(f+2*m);\n    flip(f) = f_flip;\n    //std::cout << \"face \" << face_count++ << \": \" << f << std::endl;\n    //std::cout << \"f \" << F.row(f).array()+1 << std::endl;\n    //cout<<\"flip(\"<<f<<\") = \"<<(flip(f)?\"true\":\"false\")<<endl;\n#ifdef IGL_OUTER_HULL_DEBUG\n  cout<<\"BFS...\"<<endl;\n#endif\n    while(!Q.empty())\n    {\n      // face-edge\n      const int e = Q.front();\n      Q.pop();\n      // face\n      const int f = e%m;\n      // corner\n      const int c = e/m;\n#ifdef IGL_OUTER_HULL_DEBUG\n      std::cout << \"edge: \" << e << \", ue: \" << EMAP(e) << std::endl;\n      std::cout << \"face: \" << f << std::endl;\n      std::cout << \"corner: \" << c << std::endl;\n      std::cout << \"consistent: \" << uE2C[EMAP(e)][diIM[e]] << std::endl;\n#endif\n      // Should never see edge again...\n      if(EH[e] == true)\n      {\n        continue;\n      }\n      EH[e] = true;\n      // source of edge according to f\n      const int fs = flip(f)?F(f,(c+2)%3):F(f,(c+1)%3);\n      // destination of edge according to f\n      const int fd = flip(f)?F(f,(c+1)%3):F(f,(c+2)%3);\n      // edge valence\n      const size_t val = uE2E[EMAP(e)].size();\n#ifdef IGL_OUTER_HULL_DEBUG\n      std::cout << \"vd: \" << V.row(fd) << std::endl;\n      std::cout << \"vs: \" << V.row(fs) << std::endl;\n      std::cout << \"edge: \" << V.row(fd) - V.row(fs) << std::endl;\n      for (size_t i=0; i<val; i++) {\n          if (i == diIM(e)) {\n              std::cout << \"* \";\n          } else {\n              std::cout << \"  \";\n          }\n          std::cout << i << \": \"\n              << \" (e: \" << uE2E[EMAP(e)][i] << \", f: \"\n              << uE2E[EMAP(e)][i] % m * (uE2C[EMAP(e)][i] ? 1:-1) << \")\" << std::endl;\n      }\n#endif\n      //// find overlapping face-edges\n      //const auto & neighbors = uE2E[EMAP(e)];\n      //// normal after possible flipping\n      //const auto & fN = (flip(f)?-1.:1.)*N.row(f);\n      //// Edge vector according to f's (flipped) orientation.\n      ////const auto & eV = (V.row(fd)-V.row(fs)).normalized();\n\n//#warning \"EXPERIMENTAL, DO NOT USE\"\n      //// THIS IS WRONG! The first face is---after sorting---no longer the face\n      //// used for orienting the sort.\n      //const auto ui = EMAP(e);\n      //const auto fe0 = uE2E[ui][0];\n      //const auto es = F(fe0%m,((fe0/m)+1)%3);\n\n      // is edge consistent with edge of face used for sorting\n      const int e_cons = (uE2C[EMAP(e)][diIM(e)] ? 1: -1);\n      int nfei = -1;\n      // Loop once around trying to find suitable next face\n      for(size_t step = 1; step<val+2;step++)\n      {\n        const int nfei_new = (diIM(e) + 2*val + e_cons*step*(flip(f)?-1:1))%val;\n        const int nf = uE2E[EMAP(e)][nfei_new] % m;\n        // Don't consider faces with identical dihedral angles\n        //if ((di[EMAP(e)][diIM(e)].array() != di[EMAP(e)][nfei_new].array()).any())\n        //if((di[EMAP(e)][diIM(e)] != di[EMAP(e)][nfei_new]))\n//#warning \"THIS IS HACK, FIX ME\"\n//        if( abs(di[EMAP(e)][diIM(e)] - di[EMAP(e)][nfei_new]) < 1e-15 )\n        {\n#ifdef IGL_OUTER_HULL_DEBUG\n        //cout<<\"Next facet: \"<<(f+1)<<\" --> \"<<(nf+1)<<\", |\"<<\n        //  di[EMAP(e)][diIM(e)]<<\" - \"<<di[EMAP(e)][nfei_new]<<\"| = \"<<\n        //    abs(di[EMAP(e)][diIM(e)] - di[EMAP(e)][nfei_new])\n        //    <<endl;\n#endif\n\n\n\n          // Only use this face if not already seen\n          if(!FH[nf])\n          {\n            nfei = nfei_new;\n          //} else {\n          //    std::cout << \"skipping face \" << nfei_new << \" because it is seen before\"\n          //        << std::endl;\n          }\n          break;\n        //} else {\n        //    std::cout << di[EMAP(e)][diIM(e)].transpose() << std::endl;\n        //    std::cout << di[EMAP(e)][diIM(nfei_new)].transpose() << std::endl;\n        //    std::cout << \"skipping face \" << nfei_new << \" with identical dihedral angle\"\n        //        << std::endl;\n        }\n//#ifdef IGL_OUTER_HULL_DEBUG\n//        cout<<\"Skipping co-planar facet: \"<<(f+1)<<\" --> \"<<(nf+1)<<endl;\n//#endif\n      }\n\n      int max_ne = -1;\n      //// Loop over and find max dihedral angle\n      //typename DerivedV::Scalar max_di = -1;\n      //for(const auto & ne : neighbors)\n      //{\n      //  const int nf = ne%m;\n      //  if(nf == f)\n      //  {\n      //    continue;\n      //  }\n      //  // Corner of neighbor\n      //  const int nc = ne/m;\n      //  // Is neighbor oriented consistently with (flipped) f?\n      //  //const int ns = F(nf,(nc+1)%3);\n      //  const int nd = F(nf,(nc+2)%3);\n      //  const bool cons = (flip(f)?fd:fs) == nd;\n      //  // Normal after possibly flipping to match flip or orientation of f\n      //  const auto & nN = (cons? (flip(f)?-1:1.) : (flip(f)?1.:-1.) )*N.row(nf);\n      //  // Angle between n and f\n      //  const auto & ndi = M_PI - atan2( fN.cross(nN).dot(eV), fN.dot(nN));\n      //  if(ndi>=max_di)\n      //  {\n      //    max_ne = ne;\n      //    max_di = ndi;\n      //  }\n      //}\n\n      ////cout<<(max_ne != max_ne_2)<<\" =?= \"<<e_cons<<endl;\n      //if(max_ne != max_ne_2)\n      //{\n      //  cout<<(f+1)<<\" ---> \"<<(max_ne%m)+1<<\" != \"<<(max_ne_2%m)+1<<\" ... \"<<e_cons<<\" \"<<flip(f)<<endl;\n      //  typename DerivedV::Scalar max_di = -1;\n      //  for(size_t nei = 0;nei<neighbors.size();nei++)\n      //  {\n      //    const auto & ne = neighbors[nei];\n      //    const int nf = ne%m;\n      //    if(nf == f)\n      //    {\n      //      cout<<\"  \"<<(ne%m)+1<<\":\\t\"<<0<<\"\\t\"<<di[EMAP[e]][nei]<<\" \"<<diIM(ne)<<endl;\n      //      continue;\n      //    }\n      //    // Corner of neighbor\n      //    const int nc = ne/m;\n      //    // Is neighbor oriented consistently with (flipped) f?\n      //    //const int ns = F(nf,(nc+1)%3);\n      //    const int nd = F(nf,(nc+2)%3);\n      //    const bool cons = (flip(f)?fd:fs) == nd;\n      //    // Normal after possibly flipping to match flip or orientation of f\n      //    const auto & nN = (cons? (flip(f)?-1:1.) : (flip(f)?1.:-1.) )*N.row(nf);\n      //    // Angle between n and f\n      //    const auto & ndi = M_PI - atan2( fN.cross(nN).dot(eV), fN.dot(nN));\n      //    cout<<\"  \"<<(ne%m)+1<<\":\\t\"<<ndi<<\"\\t\"<<di[EMAP[e]][nei]<<\" \"<<diIM(ne)<<endl;\n      //    if(ndi>=max_di)\n      //    {\n      //      max_ne = ne;\n      //      max_di = ndi;\n      //    }\n      //  }\n      //}\n      if(nfei >= 0)\n      {\n        max_ne = uE2E[EMAP(e)][nfei];\n      }\n\n      if(max_ne>=0)\n      {\n        // face of neighbor\n        const int nf = max_ne%m;\n#ifdef IGL_OUTER_HULL_DEBUG\n        if(!FH[nf])\n        {\n          // first time seeing face\n          cout<<(f+1)<<\" --> \"<<(nf+1)<<endl;\n        }\n#endif\n        FH[nf] = true;\n        //std::cout << \"face \" << face_count++ << \": \" << nf << std::endl;\n        //std::cout << \"f \" << F.row(nf).array()+1 << std::endl;\n        FHcount++;\n        // corner of neighbor\n        const int nc = max_ne/m;\n        const int nd = F(nf,(nc+2)%3);\n        const bool cons = (flip(f)?fd:fs) == nd;\n        flip(nf) = (cons ? flip(f) : !flip(f));\n        //cout<<\"flip(\"<<nf<<\") = \"<<(flip(nf)?\"true\":\"false\")<<endl;\n        const int ne1 = nf+((nc+1)%3)*m;\n        const int ne2 = nf+((nc+2)%3)*m;\n        if(!EH[ne1])\n        {\n          Q.push(ne1);\n        }\n        if(!EH[ne2])\n        {\n          Q.push(ne2);\n        }\n      }\n    }\n\n    {\n      vG[id].resize(FHcount,3);\n      vJ[id].resize(FHcount,1);\n      //nG += FHcount;\n      size_t h = 0;\n      assert(counts(id) == IM.rows());\n      for(int i = 0;i<counts(id);i++)\n      {\n        const size_t f = IM(i);\n        //if(f_flip)\n        //{\n        //  flip(f) = !flip(f);\n        //}\n        if(FH[f])\n        {\n          vG[id].row(h) = (flip(f)?F.row(f).reverse().eval():F.row(f));\n          vJ[id](h,0) = f;\n          h++;\n        }\n      }\n      assert((int)h == FHcount);\n    }\n  }\n\n  // Is A inside B? Assuming A and B are consistently oriented but closed and\n  // non-intersecting.\n  const auto & is_component_inside_other = [](\n    const Eigen::MatrixXd & V,\n    const MatrixXV & BC,\n    const MatrixXG & A,\n    const MatrixXJ & AJ,\n    const MatrixXG & B)->bool\n  {\n    const auto & bounding_box = [](\n      const Eigen::MatrixXd & V,\n      const MatrixXG & F)->\n      Eigen::MatrixXd\n    {\n      Eigen::MatrixXd BB(2,3);\n      BB<<\n         1e26,1e26,1e26,\n        -1e26,-1e26,-1e26;\n      const size_t m = F.rows();\n      for(size_t f = 0;f<m;f++)\n      {\n        for(size_t c = 0;c<3;c++)\n        {\n          const auto & vfc = V.row(F(f,c));\n          BB.row(0) = BB.row(0).array().min(vfc.array()).eval();\n          BB.row(1) = BB.row(1).array().max(vfc.array()).eval();\n        }\n      }\n      return BB;\n    };\n    // A lot of the time we're dealing with unrelated, distant components: cull\n    // them.\n    Eigen::MatrixXd ABB = bounding_box(V,A);\n    Eigen::MatrixXd BBB = bounding_box(V,B);\n    if( (BBB.row(0)-ABB.row(1)).maxCoeff()>0  ||\n        (ABB.row(0)-BBB.row(1)).maxCoeff()>0 )\n    {\n      // bounding boxes do not overlap\n      return false;\n    }\n    ////////////////////////////////////////////////////////////////////////\n    // POTENTIAL ROBUSTNESS WEAK AREA\n    ////////////////////////////////////////////////////////////////////////\n    //\n\n    // winding_number_3 expects colmajor\n    // q could be so close (<~1e-15) to B that the winding number is not a robust way to\n    // determine inside/outsideness. We could try to find a _better_ q which is\n    // farther away, but couldn't they all be bad?\n    double q[3] = {\n        CGAL::to_double(BC(AJ(0), 0)),\n        CGAL::to_double(BC(AJ(0), 1)),\n        CGAL::to_double(BC(AJ(0), 2)) };\n    // In a perfect world, it's enough to test a single point.\n    double w;\n    winding_number_3(\n      V.data(),V.rows(),\n      B.data(),B.rows(),\n      q,1,&w);\n    return w > 0.5 || w < -0.5;\n  };\n\n  Eigen::MatrixXd Vcol(V.rows(), V.cols());\n  for (size_t i=0; i<(size_t)V.rows(); i++) {\n      for (size_t j=0; j<(size_t)V.cols(); j++) {\n          Vcol(i, j) = CGAL::to_double(V(i, j));\n      }\n  }\n\n  // Reject components which are completely inside other components\n  vector<bool> keep(ncc,true);\n  size_t nG = 0;\n  // This is O( ncc * ncc * m)\n  for(size_t id = 0;id<ncc;id++)\n  {\n    for(size_t oid = 0;oid<ncc;oid++)\n    {\n      if(id == oid)\n      {\n        continue;\n      }\n      const bool inside = is_component_inside_other(Vcol,BC,vG[id],vJ[id],vG[oid]);\n#ifdef IGL_OUTER_HULL_DEBUG\n      cout<<id<<\" is inside \"<<oid<<\" ? \"<<inside<<endl;\n#endif\n      keep[id] = keep[id] && !inside;\n    }\n    if(keep[id])\n    {\n      nG += vJ[id].rows();\n    }\n  }\n\n  // collect G and J across components\n  G.resize(nG,3);\n  J.resize(nG,1);\n  {\n    size_t off = 0;\n    for(Index id = 0;id<(Index)ncc;id++)\n    {\n      if(keep[id])\n      {\n        assert(vG[id].rows() == vJ[id].rows());\n        G.block(off,0,vG[id].rows(),vG[id].cols()) = vG[id];\n        J.block(off,0,vJ[id].rows(),vJ[id].cols()) = vJ[id];\n        off += vG[id].rows();\n      }\n    }\n  }\n}\n\ntemplate <\n  typename DerivedV,\n  typename DerivedF,\n  typename DerivedG,\n  typename DerivedJ,\n  typename Derivedflip>\nIGL_INLINE void igl::outer_hull(\n  const Eigen::PlainObjectBase<DerivedV> & V,\n  const Eigen::PlainObjectBase<DerivedF> & F,\n  Eigen::PlainObjectBase<DerivedG> & G,\n  Eigen::PlainObjectBase<DerivedJ> & J,\n  Eigen::PlainObjectBase<Derivedflip> & flip)\n{\n  Eigen::Matrix<typename DerivedV::Scalar,DerivedF::RowsAtCompileTime,3> N;\n  per_face_normals_stable(V,F,N);\n  return outer_hull(V,F,N,G,J,flip);\n}\n\n\n#ifdef IGL_STATIC_LIBRARY\n\n#include <igl/barycenter.cpp>\ntemplate void igl::barycenter<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> >(Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> >&);\n\n#include <igl/outer_facet.cpp>\ntemplate void igl::outer_facet<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<long, -1, 1, 0, -1, 1>, int>(Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> > const&, int&, bool&);\n\n#include <igl/cgal/order_facets_around_edges.cpp>\ntemplate std::__1::enable_if<std::is_same<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>::Scalar, CGAL::Lazy_exact_nt<CGAL::Gmpq> >::value, void>::type igl::order_facets_around_edges<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 2, 0, -1, 2>, Eigen::Matrix<int, -1, 2, 0, -1, 2>, Eigen::Matrix<long, -1, 1, 0, -1, 1>, long, long, bool>(Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 2, 0, -1, 2> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 2, 0, -1, 2> > const&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> > const&, std::__1::vector<std::__1::vector<long, std::__1::allocator<long> >, std::__1::allocator<std::__1::vector<long, std::__1::allocator<long> > > > const&, std::__1::vector<std::__1::vector<long, std::__1::allocator<long> >, std::__1::allocator<std::__1::vector<long, std::__1::allocator<long> > > >&, std::__1::vector<std::__1::vector<bool, std::__1::allocator<bool> >, std::__1::allocator<std::__1::vector<bool, std::__1::allocator<bool> > > >&);\n\n// Explicit template specialization\ntemplate void igl::outer_hull<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<long, -1, 1, 0, -1, 1>, Eigen::Matrix<bool, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<long, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<bool, -1, 1, 0, -1, 1> >&);\ntemplate void igl::outer_hull<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);\ntemplate void igl::outer_hull<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<bool, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<bool, -1, 1, 0, -1, 1> >&);\n#endif\n", "meta": {"hexsha": "f0c496d56857035e3567b90be02ab53e5676c9a8", "size": 20870, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/quadwild/libs/libigl/include/igl/cgal/outer_hull.cpp", "max_stars_repo_name": "Pentacode-IAFA/Quad-Remeshing", "max_stars_repo_head_hexsha": "f8fd4c10abf1c54656b38a00b8a698b952a85fe2", "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/quadwild/libs/libigl/include/igl/cgal/outer_hull.cpp", "max_issues_repo_name": "Pentacode-IAFA/Quad-Remeshing", "max_issues_repo_head_hexsha": "f8fd4c10abf1c54656b38a00b8a698b952a85fe2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/quadwild/libs/libigl/include/igl/cgal/outer_hull.cpp", "max_forks_repo_name": "Pentacode-IAFA/Quad-Remeshing", "max_forks_repo_head_hexsha": "f8fd4c10abf1c54656b38a00b8a698b952a85fe2", "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.4346224678, "max_line_length": 1362, "alphanum_fraction": 0.5478677528, "num_tokens": 7184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.29006278648569095}}
{"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\n#ifndef OPENGV_ABSOLUTE_POSE_MODULES_GPNP4_MODULES_HPP_\n#define OPENGV_ABSOLUTE_POSE_MODULES_GPNP4_MODULES_HPP_\n\n#include <stdlib.h>\n#include <Eigen/Eigen>\n#include <vector>\n\nnamespace opengv\n{\nnamespace absolute_pose\n{\nnamespace modules\n{\nnamespace gpnp4\n{\n\nvoid init(\n    Eigen::Matrix<double,25,37> & groebnerMatrix,\n    const Eigen::Matrix<double,12,1> & a,\n    Eigen::Matrix<double,12,1> & n,\n    Eigen::Matrix<double,12,1> & m,\n    Eigen::Matrix<double,12,1> & k,\n    Eigen::Matrix<double,12,1> & l,\n    Eigen::Vector3d & c0,\n    Eigen::Vector3d & c1,\n    Eigen::Vector3d & c2,\n    Eigen::Vector3d & c3 );\nvoid compute( Eigen::Matrix<double,25,37> & groebnerMatrix );\nvoid sPolynomial5( Eigen::Matrix<double,25,37> & groebnerMatrix );\nvoid sPolynomial6( Eigen::Matrix<double,25,37> & groebnerMatrix );\nvoid groebnerRow5_0000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid sPolynomial7( Eigen::Matrix<double,25,37> & groebnerMatrix );\nvoid groebnerRow6_0000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid sPolynomial8( Eigen::Matrix<double,25,37> & groebnerMatrix );\nvoid groebnerRow7_0000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid sPolynomial9( Eigen::Matrix<double,25,37> & groebnerMatrix );\nvoid groebnerRow7_0100_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow8_0100_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow5_1000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow6_1000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow7_1000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow8_1000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow8_0000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid sPolynomial10( Eigen::Matrix<double,25,37> & groebnerMatrix );\nvoid groebnerRow6_0100_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow9_0000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid sPolynomial11( Eigen::Matrix<double,25,37> & groebnerMatrix );\nvoid groebnerRow4_1000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow10_0000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow4_0000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid sPolynomial12( Eigen::Matrix<double,25,37> & groebnerMatrix );\nvoid groebnerRow5_0100_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow11_0000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid sPolynomial13( Eigen::Matrix<double,25,37> & groebnerMatrix );\nvoid groebnerRow6_0010_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow4_0100_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow12_0000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid sPolynomial14( Eigen::Matrix<double,25,37> & groebnerMatrix );\nvoid groebnerRow5_0010_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow13_0000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid sPolynomial15( Eigen::Matrix<double,25,37> & groebnerMatrix );\nvoid groebnerRow14_1000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow14_0000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid sPolynomial16( Eigen::Matrix<double,25,37> & groebnerMatrix );\nvoid groebnerRow13_1000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow15_0100_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow15_1000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow15_0000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid sPolynomial17( Eigen::Matrix<double,25,37> & groebnerMatrix );\nvoid groebnerRow12_1000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow16_1000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow16_0000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid sPolynomial18( Eigen::Matrix<double,25,37> & groebnerMatrix );\nvoid groebnerRow14_0001_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow14_0010_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow17_1000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow17_0000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid sPolynomial19( Eigen::Matrix<double,25,37> & groebnerMatrix );\nvoid groebnerRow18_0000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid sPolynomial20( Eigen::Matrix<double,25,37> & groebnerMatrix );\nvoid groebnerRow18_1000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow19_1000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow19_0000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid sPolynomial21( Eigen::Matrix<double,25,37> & groebnerMatrix );\nvoid groebnerRow20_1000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow20_0000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid sPolynomial22( Eigen::Matrix<double,25,37> & groebnerMatrix );\nvoid groebnerRow19_0001_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow19_0010_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow20_0001_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow20_0010_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow21_0010_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow20_0100_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow21_0100_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow21_1000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow21_0000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid sPolynomial23( Eigen::Matrix<double,25,37> & groebnerMatrix );\nvoid groebnerRow20_1100_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow21_1100_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow22_1100_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow19_0100_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow22_0100_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow22_1000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid groebnerRow22_0000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\nvoid sPolynomial24( Eigen::Matrix<double,25,37> & groebnerMatrix );\nvoid groebnerRow23_0000_f( Eigen::Matrix<double,25,37> & groebnerMatrix, int targetRow );\n\n}\n}\n}\n}\n\n#endif /* OPENGV_ABSOLUTE_POSE_MODULES_GPNP4_MODULES_HPP_ */\n", "meta": {"hexsha": "4041438df687680586148a35a3761995286484a5", "size": 9625, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/opengv/absolute_pose/modules/gpnp4/modules.hpp", "max_stars_repo_name": "PXLVision/opengv", "max_stars_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "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/opengv/absolute_pose/modules/gpnp4/modules.hpp", "max_issues_repo_name": "PXLVision/opengv", "max_issues_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/opengv/absolute_pose/modules/gpnp4/modules.hpp", "max_forks_repo_name": "PXLVision/opengv", "max_forks_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 66.3793103448, "max_line_length": 89, "alphanum_fraction": 0.716987013, "num_tokens": 2764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2900070523155883}}
{"text": "#include \"predictor.h\"\n#include <Eigen/Unsupported/KroneckerProduct>\n\nnamespace statiskit\n{\n    namespace glm\n    {\n        ScalarPredictor::ScalarPredictor(const MultivariateSampleSpace& explanatory_space)\n        { _explanatory_space = explanatory_space.copy().release(); }\n\n        ScalarPredictor::~ScalarPredictor()\n        { delete _explanatory_space; }\n\n        ScalarPredictor::ScalarPredictor(const ScalarPredictor& predictor)\n        { _explanatory_space = predictor._explanatory_space->copy().release(); }\n\n        const MultivariateSampleSpace* ScalarPredictor::get_explanatory_space() const\n        { return _explanatory_space; }\n\n        CompleteScalarPredictor::CompleteScalarPredictor(const MultivariateSampleSpace& explanatory_space) : CompleteScalarPredictor(explanatory_space, explanatory_space.encode())\n        {}\n\n        CompleteScalarPredictor::CompleteScalarPredictor(const MultivariateSampleSpace& explanatory_space, const size_t& size) : ScalarPredictor(explanatory_space)\n        {\n            alpha = 0.;\n            _delta = Eigen::VectorXd::Zero(size);\n        }\n\n        CompleteScalarPredictor::CompleteScalarPredictor(const CompleteScalarPredictor& predictor) : ScalarPredictor(predictor)\n        {\n            alpha = predictor.alpha;\n            _delta = predictor._delta;\n        }\n         \n        double CompleteScalarPredictor::operator() (const MultivariateEvent& event) const\n        { return alpha + _explanatory_space->encode(event) * _delta; }\n\n    \tvoid CompleteScalarPredictor::set_beta(const Eigen::VectorXd& beta)\n    \t{\n    \t\tif(beta.rows() != (1 + _delta.rows()) )\n    \t\t{ throw statiskit::size_error(\"beta\", beta.rows(), 1+_delta.rows()); }\t\n    \t\talpha = beta(0);\n    \t\t_delta = beta.segment(1, _delta.rows());\n    \t}\n    \t\n    \tsize_t CompleteScalarPredictor::size() const\n    \t{ return (1+_delta.size()); }\n    \t\n    \tconst Eigen::VectorXd& CompleteScalarPredictor::get_delta() const\n    \t{ return _delta; }\n\n        void CompleteScalarPredictor::set_delta(const Eigen::VectorXd& delta)\n        {\n            if(delta.rows() != _delta.rows() )\n            { throw statiskit::size_error(\"delta\", delta.rows(), _delta.rows()); }  \n            _delta = delta;\n        }\n\n        std::unique_ptr< ScalarPredictor > CompleteScalarPredictor::copy() const\n        { return std::make_unique< CompleteScalarPredictor >(*this); }\n\n\n        ConstrainedScalarPredictor::ConstrainedScalarPredictor(const MultivariateSampleSpace& explanatory_space, const Eigen::MatrixXd& constraint) : CompleteScalarPredictor(explanatory_space, constraint.cols())\n        { \n        \tif(constraint.rows() != explanatory_space.encode() )\n        \t{ throw statiskit::size_error(\"constraint\", constraint.rows(), explanatory_space.encode() ); } \n        \tif(constraint.cols() > constraint.rows())\n        \t{ throw statiskit::size_error(\"constraint\", constraint.cols(), constraint.rows(), statiskit::size_error::size_type::superior); }     \t   \n        \t_constraint = constraint; \n        }\n\n        ConstrainedScalarPredictor::ConstrainedScalarPredictor(const ConstrainedScalarPredictor& predictor) : CompleteScalarPredictor(predictor)\n        { _constraint = predictor._constraint; }\n         \n        double ConstrainedScalarPredictor::operator() (const MultivariateEvent& event) const\n        { return alpha + _explanatory_space->encode(event) * _constraint * _delta; }\n        \n        const Eigen::MatrixXd& ConstrainedScalarPredictor::get_constraint() const\n        { return _constraint; }\n        \n    \tvoid ConstrainedScalarPredictor::set_constraint(const Eigen::MatrixXd& constraint)\n    \t{\n    \t\tif(constraint.rows() != _constraint.rows())\n    \t\t{ throw statiskit::size_error(\"constraint\", constraint.rows(), _constraint.rows()); }\n    \t\tif(constraint.cols() != _constraint.cols())\n    \t\t{ throw statiskit::size_error(\"constraint\", constraint.cols(), _constraint.cols()); }\t\t\t\n    \t\t_constraint = constraint;\n    \t}\n    \t\n        std::unique_ptr< ScalarPredictor > ConstrainedScalarPredictor::copy() const\n        { return std::make_unique< ConstrainedScalarPredictor >(*this); }\n        \n\n        VectorPredictor::VectorPredictor(const MultivariateSampleSpace& explanatory_space)\n        { _explanatory_space = explanatory_space.copy().release(); }\n      \n        VectorPredictor::~VectorPredictor()\n        { delete _explanatory_space; } \n        \n        VectorPredictor::VectorPredictor(const VectorPredictor& predictor)\n        { _explanatory_space = predictor._explanatory_space->copy().release(); }\n        \n        const MultivariateSampleSpace* VectorPredictor::get_explanatory_space() const\n        { return _explanatory_space; }\n        \n\n        CompleteVectorPredictor::CompleteVectorPredictor(const MultivariateSampleSpace& explanatory_space, const size_t& dimension) : VectorPredictor(explanatory_space)\n        {\n        \t_alpha = Eigen::VectorXd::Zero(dimension);\n        \t_delta = Eigen::MatrixXd::Zero(dimension, explanatory_space.encode()); \n        }\n        \n        CompleteVectorPredictor::CompleteVectorPredictor(const CompleteVectorPredictor& predictor) : VectorPredictor(predictor)\n        {\n        \t_alpha = predictor._alpha; \n        \t_delta = predictor._delta; \n        }\n\n        Eigen::VectorXd CompleteVectorPredictor::operator() (const MultivariateEvent& event) const\n        { return _alpha + _delta * (_explanatory_space->encode(event)).transpose(); }\n        \n        size_t CompleteVectorPredictor::size() const\n        { return _alpha.rows() + _delta.size(); }\n                \n        void CompleteVectorPredictor::set_beta(const Eigen::VectorXd& beta)\n    \t{\n    \t\tif(beta.rows() != _alpha.rows() + _delta.rows() * _delta.cols())\n    \t\t{ throw statiskit::size_error(\"beta\", beta.rows(),  _alpha.rows() + _delta.rows() * _delta.cols()); }\n    \t\t_alpha = beta.segment(0, _alpha.rows());\n    \t\tfor(size_t j=0; j<_alpha.rows(); ++j)\n            { _delta.block(j, 0, 1, _delta.cols()) = ( beta.segment(_alpha.rows() + j * _delta.cols(),_delta.cols() ) ).transpose(); } //_alpha.rows() + (j+1) * _delta.cols() - 1) ).transpose(); }\n    \t}\n    \t\t\n    \tconst Eigen::VectorXd& CompleteVectorPredictor::get_alpha() const\n    \t{ return _alpha; }\t\n\n    \tvoid CompleteVectorPredictor::set_alpha(const Eigen::VectorXd& alpha)\n        {\n            if(alpha.rows() != _alpha.rows() )\n            { throw statiskit::size_error(\"alpha\", alpha.rows(),  _alpha.rows() ); }\n            _alpha = alpha;\n        }\n\n    \tconst Eigen::MatrixXd& CompleteVectorPredictor::get_delta() const\n    \t{ return _delta; }\n\n        void CompleteVectorPredictor::set_delta(const Eigen::MatrixXd& delta)\n        {\n            if(delta.rows() != _delta.rows() )\n            { throw statiskit::size_error(\"delta nb rows\", delta.rows(),  _delta.rows() ); }\n            if(delta.cols() != _delta.cols() )\n            { throw statiskit::size_error(\"delta nb cols\", delta.cols(),  _delta.cols() ); }   \n            _delta = delta;\n        }    \n    \t\n        std::unique_ptr< VectorPredictor > CompleteVectorPredictor::copy() const\n        { return std::make_unique< CompleteVectorPredictor >(*this); }\t\n        \n           \n        ProportionalVectorPredictor::ProportionalVectorPredictor(const MultivariateSampleSpace& explanatory_space, const size_t& dimension) : VectorPredictor(explanatory_space)\n        {\n        \t_alpha = Eigen::VectorXd::Zero(dimension); \n        \t_delta = Eigen::VectorXd::Zero(explanatory_space.encode());\n        }\n        \n        ProportionalVectorPredictor::ProportionalVectorPredictor(const ProportionalVectorPredictor& predictor) : VectorPredictor(predictor)\n        {\n         \t_alpha = predictor._alpha;\n        \t_delta = predictor._delta; \n        }\n    \t\n        Eigen::VectorXd ProportionalVectorPredictor::operator() (const MultivariateEvent& event) const\n        { return _alpha + _explanatory_space->encode(event) * _delta * Eigen::VectorXd::Ones(_alpha.rows()); }\n        \n        size_t ProportionalVectorPredictor::size() const\n        { return _alpha.rows() + _delta.rows(); }\n                \n        void ProportionalVectorPredictor::set_beta(const Eigen::VectorXd& beta)\n    \t{\n    \t\tif(beta.rows() != _alpha.rows() + _delta.rows() * _delta.cols())\n    \t\t{ throw statiskit::size_error(\"beta\", beta.rows(),  _alpha.rows() + _delta.rows() * _delta.cols()); }\n    \t\t_alpha = beta.segment(0, _alpha.rows() );\n    \t\t_delta = beta.segment(_alpha.rows(),  _delta.rows() );\n    \t}\n    \t\t\n    \tconst Eigen::VectorXd& ProportionalVectorPredictor::get_alpha() const\n    \t{ return _alpha; }\t\t\n    \t\n        void ProportionalVectorPredictor::set_alpha(const Eigen::VectorXd& alpha)\n        {\n            if(alpha.rows() != _alpha.rows() )\n            { throw statiskit::size_error(\"alpha\", alpha.rows(),  _alpha.rows() ); }\n            _alpha = alpha;\n        }\n\n    \tconst Eigen::VectorXd& ProportionalVectorPredictor::get_delta() const\n    \t{ return _delta; }\n\n        void ProportionalVectorPredictor::set_delta(const Eigen::VectorXd& delta)\n        {\n            if(delta.rows() != _delta.rows() )\n            { throw statiskit::size_error(\"delta\", delta.rows(),  _delta.rows() ); }\n            _delta = delta;\n        }   \n    \t\n        std::unique_ptr< VectorPredictor > ProportionalVectorPredictor::copy() const\n        { return std::make_unique< ProportionalVectorPredictor >(*this); }\t\n\n        ProportionalVectorPredictor::ProportionalVectorPredictor(const MultivariateSampleSpace& explanatory_space) : VectorPredictor(explanatory_space)\n        {}\n\n\n        ConstrainedVectorPredictor::ConstrainedVectorPredictor(const MultivariateSampleSpace& explanatory_space, const size_t& dimension, const Eigen::MatrixXd& constraint) : ProportionalVectorPredictor(explanatory_space)\n        {   \n        \tif(constraint.rows() != ( explanatory_space.encode() * dimension ) )\n        \t{ throw statiskit::size_error(\"constraint\", constraint.rows(),  explanatory_space.encode() * dimension ); } \n        \tif(constraint.cols() > constraint.rows())\n        \t{ throw statiskit::size_error(\"constraint\", constraint.cols(), constraint.rows(), statiskit::size_error::size_type::superior); }     \t   \n        \t_constraint = constraint; \n        \t_intercept_constraint = Eigen::MatrixXd::Identity(dimension, dimension);\n            _alpha = Eigen::VectorXd::Zero(dimension); \n            _delta = Eigen::VectorXd::Zero(constraint.cols());  \n        }\n        \n        ConstrainedVectorPredictor::ConstrainedVectorPredictor(const MultivariateSampleSpace& explanatory_space, const Eigen::MatrixXd& constraint, const Eigen::MatrixXd& intercept_constraint) : ProportionalVectorPredictor(explanatory_space)\n        { \n        \tif(constraint.rows() != ( explanatory_space.encode() * intercept_constraint.rows()) )\n        \t{ throw statiskit::size_error(\"constraint\", constraint.rows(),  explanatory_space.encode() * intercept_constraint.rows()); } \n        \tif(constraint.cols() >  constraint.rows())\n        \t{ throw statiskit::size_error(\"constraint\", constraint.cols(), constraint.rows(), statiskit::size_error::size_type::superior); } \n        \t_constraint = constraint;\n        \tif(intercept_constraint.cols() > intercept_constraint.rows() )\n        \t{ throw statiskit::size_error(\"intercept_constraint\", intercept_constraint.cols(), intercept_constraint.rows(), statiskit::size_error::size_type::superior); }     \t    \t   \n        \t_intercept_constraint = intercept_constraint; \n            _alpha = Eigen::VectorXd::Zero(intercept_constraint.cols()); \n            _delta = Eigen::VectorXd::Zero(constraint.cols());        \n        }    \n\n        ConstrainedVectorPredictor::ConstrainedVectorPredictor(const MultivariateSampleSpace& explanatory_space, const size_t& dimension, const Indices& proportional) : ConstrainedVectorPredictor(explanatory_space, dimension, partial_proportional_constraint(explanatory_space, dimension, proportional))\n        {}\n\n        ConstrainedVectorPredictor::ConstrainedVectorPredictor(const ConstrainedVectorPredictor& predictor) : ProportionalVectorPredictor(predictor)\n        { \n        \t_constraint = predictor._constraint; \n        \t_intercept_constraint = predictor._intercept_constraint;\n        }\n         \n        Eigen::VectorXd ConstrainedVectorPredictor::operator() (const MultivariateEvent& event) const\n        { \n            Eigen::VectorXd xt = _explanatory_space->encode(event).transpose();\n            Eigen::MatrixXd Identity = Eigen::MatrixXd::Identity(_intercept_constraint.rows(), _intercept_constraint.rows());\n            return _intercept_constraint * _alpha + Eigen::kroneckerProduct(Identity, xt) * _constraint * _delta;\n        }\n        \n        const Eigen::MatrixXd& ConstrainedVectorPredictor::get_constraint() const\n        { return _constraint; }\n        \n    \tvoid ConstrainedVectorPredictor::set_constraint(const Eigen::MatrixXd& constraint)\n    \t{\n    \t\tif(constraint.rows() != _constraint.rows())\n    \t\t{ throw statiskit::size_error(\"constraint\", constraint.rows(), _constraint.rows()); }\n    \t\tif(constraint.cols() != _constraint.cols())\n    \t\t{ throw statiskit::size_error(\"constraint\", constraint.cols(), _constraint.cols()); }\t\t\t\n    \t\t_constraint = constraint;\n    \t}\n    \t\n        const Eigen::MatrixXd& ConstrainedVectorPredictor::get_intercept_constraint() const\n        { return _intercept_constraint; }\n        \n    \tvoid ConstrainedVectorPredictor::set_intercept_constraint(const Eigen::MatrixXd& intercept_constraint)\n    \t{\n    \t\tif(intercept_constraint.rows() != _intercept_constraint.rows())\n    \t\t{ throw statiskit::size_error(\"intercept_constraint\", intercept_constraint.rows(), _intercept_constraint.rows()); }\n    \t\tif(intercept_constraint.cols() != _intercept_constraint.cols())\n    \t\t{ throw statiskit::size_error(\"intercept_constraint\", intercept_constraint.cols(), _intercept_constraint.cols()); }\t\t\t\n    \t\t_intercept_constraint = intercept_constraint;\n    \t}\t\n    \t\n        std::unique_ptr< VectorPredictor > ConstrainedVectorPredictor::copy() const\n        { return std::make_unique< ConstrainedVectorPredictor >(*this); }\n\n        Eigen::MatrixXd ConstrainedVectorPredictor::partial_proportional_constraint(const MultivariateSampleSpace& explanatory_space, const size_t& dimension, const Indices& proportional)\n        {\n            Index nb_cols=0, nb_block_rows=0, current_row = 0, current_col=0;\n            std::vector< Index > rows, cols;\n            for(Index i=0; i<explanatory_space.size(); ++i)\n            {\n                if(explanatory_space.get(i)->get_outcome() == outcome_type::CATEGORICAL)\n                { \n                    Index K = static_cast< const CategoricalSampleSpace* >( explanatory_space.get(i) )->get_cardinality();\n                    rows.push_back(K-1); \n                }\n                else\n                { rows.push_back(1); }\n                nb_block_rows += rows.back();\n\n                if(proportional.find(i) == proportional.end()) // complete\n                { cols.push_back(rows.back() * dimension); }\n                else\n                { cols.push_back(rows.back()); }  \n                nb_cols += cols.back();   \n            }\n            Eigen::MatrixXd constraint = Eigen::MatrixXd::Zero(nb_block_rows*dimension, nb_cols);\n            for(Index i=0; i<explanatory_space.size(); ++i)\n            {\n                Eigen::MatrixXd identity = Eigen::MatrixXd::Identity(rows[i], rows[i]); \n                if(proportional.find(i) == proportional.end()) \n                {  \n                    for(Index j=0; j<dimension; ++j)\n                    {\n                        Eigen::RowVectorXd indicator = Eigen::RowVectorXd::Zero(dimension);\n                        indicator[j] = 1;    \n                        constraint.block(j*nb_block_rows + current_row, current_col, rows[i], cols[i]) = Eigen::kroneckerProduct(indicator, identity); \n                    }\n                }\n                else\n                {\n                    for(Index j=0; j<dimension; ++j)\n                    {constraint.block(j*nb_block_rows + current_row, current_col, rows[i], cols[i]) = identity; }\n                } \n                current_col += cols[i];\n                current_row += rows[i];               \n            }\n            return constraint;\n        }\n\n        Eigen::MatrixXd ConstrainedVectorPredictor::partial_proportional_constraint(const UnivariateConditionalData& data, const Indices& proportional)\n        {\n            Index J = static_cast< const CategoricalSampleSpace* >(data.get_response()->get_sample_space())->get_cardinality();\n            const MultivariateData* _data = data.get_explanatories();\n            const MultivariateSampleSpace* explanatory_space = _data->get_sample_space();\n            return partial_proportional_constraint(*explanatory_space, J-1, proportional);\n        }\n    }\n}\n", "meta": {"hexsha": "c215bf59354af78a34cc4df3c1f8be82c68b554f", "size": 16817, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/predictor.cpp", "max_stars_repo_name": "jpeyhardi/GLM", "max_stars_repo_head_hexsha": "6f0fd763aec2a0ccdef3901b71ed990f20119510", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-09T03:49:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-09T03:49:49.000Z", "max_issues_repo_path": "src/cpp/predictor.cpp", "max_issues_repo_name": "jpeyhardi/GLM", "max_issues_repo_head_hexsha": "6f0fd763aec2a0ccdef3901b71ed990f20119510", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-05-23T12:32:06.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-03T10:59:30.000Z", "max_forks_repo_path": "src/cpp/predictor.cpp", "max_forks_repo_name": "jpeyhardi/GLM", "max_forks_repo_head_hexsha": "6f0fd763aec2a0ccdef3901b71ed990f20119510", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-03-20T10:21:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T18:27:17.000Z", "avg_line_length": 50.0505952381, "max_line_length": 302, "alphanum_fraction": 0.6450020812, "num_tokens": 3706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.28986940757271795}}
{"text": "// Copyright 2021, Autonomous Space Robotics Lab (ASRL)\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 * \\file cloud.hpp\r\n * \\brief PointXYZ, PointXY, PointCloud class definition\r\n *\r\n * \\author Hugues Thomas, Autonomous Space Robotics Lab (ASRL)\r\n */\r\n#pragma once\r\n\r\n#include <stdio.h>\r\n#include <string.h>\r\n#include <algorithm>\r\n#include <cmath>\r\n#include <iomanip>\r\n#include <iostream>\r\n#include <map>\r\n#include <numeric>\r\n#include <unordered_map>\r\n#include <vector>\r\n\r\n#include <time.h>\r\n\r\n#include <Eigen/Dense>\r\n\r\n#include <vtr_lidar/npm_ply/ply_file_in.h>\r\n#include <vtr_lidar/npm_ply/ply_file_out.h>\r\n#include <vtr_lidar/npm_ply/ply_types.h>\r\n\r\nnamespace vtr {\r\nnamespace lidar {\r\n\r\n//------------------------------------------------------------------------------------------------------------\r\n// Point class\r\n// ***********\r\n//\r\n//------------------------------------------------------------------------------------------------------------\r\n\r\nclass PointXYZ {\r\n public:\r\n  using Vector3fMap = Eigen::Map<Eigen::Vector3f>;\r\n  using Vector3fMapConst = const Eigen::Map<const Eigen::Vector3f>;\r\n  // Elements\r\n  // ********\r\n  union {\r\n    struct {\r\n      float x;\r\n      float y;\r\n      float z;\r\n    };\r\n    float data[3];\r\n  };\r\n\r\n  // Methods\r\n  // *******\r\n\r\n  // Constructor\r\n  PointXYZ(float x0 = 0, float y0 = 0, float z0 = 0) : x(x0), y(y0), z(z0) {}\r\n\r\n  Vector3fMap getVector3fMap() { return (Vector3fMap(data)); }\r\n  Vector3fMapConst getVector3fMap() const { return (Vector3fMapConst(data)); }\r\n\r\n  // array type accessor\r\n  float operator[](int i) const {\r\n    if (i == 0)\r\n      return x;\r\n    else if (i == 1)\r\n      return y;\r\n    else\r\n      return z;\r\n  }\r\n\r\n  // opperations\r\n  float dot(const PointXYZ P) const { return x * P.x + y * P.y + z * P.z; }\r\n\r\n  float sq_norm() const { return x * x + y * y + z * z; }\r\n\r\n  PointXYZ cross(const PointXYZ P) const {\r\n    return PointXYZ(y * P.z - z * P.y, z * P.x - x * P.z, x * P.y - y * P.x);\r\n  }\r\n\r\n  PointXYZ& operator+=(const PointXYZ& P) {\r\n    x += P.x;\r\n    y += P.y;\r\n    z += P.z;\r\n    return *this;\r\n  }\r\n\r\n  PointXYZ& operator-=(const PointXYZ& P) {\r\n    x -= P.x;\r\n    y -= P.y;\r\n    z -= P.z;\r\n    return *this;\r\n  }\r\n\r\n  PointXYZ& operator*=(const float& a) {\r\n    x *= a;\r\n    y *= a;\r\n    z *= a;\r\n    return *this;\r\n  }\r\n};\r\n\r\n// Point Opperations\r\n// *****************\r\n\r\ninline PointXYZ operator+(const PointXYZ A, const PointXYZ B) {\r\n  return PointXYZ(A.x + B.x, A.y + B.y, A.z + B.z);\r\n}\r\n\r\ninline PointXYZ operator-(const PointXYZ A, const PointXYZ B) {\r\n  return PointXYZ(A.x - B.x, A.y - B.y, A.z - B.z);\r\n}\r\n\r\ninline PointXYZ operator*(const PointXYZ P, const float a) {\r\n  return PointXYZ(P.x * a, P.y * a, P.z * a);\r\n}\r\n\r\ninline PointXYZ operator*(const float a, const PointXYZ P) {\r\n  return PointXYZ(P.x * a, P.y * a, P.z * a);\r\n}\r\n\r\ninline PointXYZ operator/(const PointXYZ P, const float a) {\r\n  return PointXYZ(P.x / a, P.y / a, P.z / a);\r\n}\r\n\r\ninline PointXYZ operator/(const float a, const PointXYZ P) {\r\n  return PointXYZ(P.x / a, P.y / a, P.z / a);\r\n}\r\n\r\ninline std::ostream& operator<<(std::ostream& os, const PointXYZ P) {\r\n  return os << \"[\" << P.x << \", \" << P.y << \", \" << P.z << \"]\";\r\n}\r\n\r\ninline bool operator==(const PointXYZ A, const PointXYZ B) {\r\n  return A.x == B.x && A.y == B.y && A.z == B.z;\r\n}\r\n\r\ninline PointXYZ floor(const PointXYZ P) {\r\n  return PointXYZ(std::floor(P.x), std::floor(P.y), std::floor(P.z));\r\n}\r\n\r\nPointXYZ max_point(const std::vector<PointXYZ>& points);\r\nPointXYZ min_point(const std::vector<PointXYZ>& points);\r\nPointXYZ max_point(const PointXYZ A, const PointXYZ B);\r\nPointXYZ min_point(const PointXYZ A, const PointXYZ B);\r\n\r\n//------------------------------------------------------------------------------------------------------------\r\n// Point class 2D\r\n// **************\r\n//\r\n//------------------------------------------------------------------------------------------------------------\r\n\r\nclass PointXY {\r\n public:\r\n  // Elements\r\n  // ********\r\n\r\n  float x, y;\r\n\r\n  // Methods\r\n  // *******\r\n\r\n  // Constructor\r\n  PointXY() {\r\n    x = 0;\r\n    y = 0;\r\n  }\r\n  PointXY(float x0, float y0) {\r\n    x = x0;\r\n    y = y0;\r\n  }\r\n  PointXY(PointXYZ P) {\r\n    x = P.x;\r\n    y = P.y;\r\n  }\r\n\r\n  // array type accessor\r\n  float operator[](int i) const {\r\n    if (i == 0)\r\n      return x;\r\n    else\r\n      return y;\r\n  }\r\n\r\n  // opperations\r\n  float dot(const PointXY P) const { return x * P.x + y * P.y; }\r\n\r\n  float sq_norm() const { return x * x + y * y; }\r\n\r\n  float cross(const PointXY P) const { return x * P.y - y * P.x; }\r\n\r\n  PointXY& operator+=(const PointXY& P) {\r\n    x += P.x;\r\n    y += P.y;\r\n    return *this;\r\n  }\r\n\r\n  PointXY& operator-=(const PointXY& P) {\r\n    x -= P.x;\r\n    y -= P.y;\r\n    return *this;\r\n  }\r\n\r\n  PointXY& operator*=(const float& a) {\r\n    x *= a;\r\n    y *= a;\r\n    return *this;\r\n  }\r\n};\r\n\r\n// Point Opperations\r\n// *****************\r\n\r\ninline PointXY operator+(const PointXY A, const PointXY B) {\r\n  return PointXY(A.x + B.x, A.y + B.y);\r\n}\r\n\r\ninline PointXY operator-(const PointXY A, const PointXY B) {\r\n  return PointXY(A.x - B.x, A.y - B.y);\r\n}\r\n\r\ninline PointXY operator*(const PointXY P, const float a) {\r\n  return PointXY(P.x * a, P.y * a);\r\n}\r\n\r\ninline PointXY operator*(const float a, const PointXY P) {\r\n  return PointXY(P.x * a, P.y * a);\r\n}\r\n\r\ninline PointXY operator/(const PointXY P, const float a) {\r\n  return PointXY(P.x / a, P.y / a);\r\n}\r\n\r\ninline PointXY operator/(const float a, const PointXY P) {\r\n  return PointXY(P.x / a, P.y / a);\r\n}\r\n\r\ninline std::ostream& operator<<(std::ostream& os, const PointXY P) {\r\n  return os << \"[\" << P.x << \", \" << P.y << \"]\";\r\n}\r\n\r\ninline bool operator==(const PointXY A, const PointXY B) {\r\n  return A.x == B.x && A.y == B.y;\r\n}\r\n\r\ninline PointXY floor(const PointXY P) {\r\n  return PointXY(std::floor(P.x), std::floor(P.y));\r\n}\r\n\r\n//------------------------------------------------------------------------------------------------------------\r\n// Pointcloud class\r\n// ****************\r\n//\r\n//------------------------------------------------------------------------------------------------------------\r\n\r\nstruct PointCloud {\r\n  std::vector<PointXYZ> pts;\r\n\r\n  // Must return the number of data points\r\n  inline size_t kdtree_get_point_count() const { return pts.size(); }\r\n\r\n  // Returns the dim'th component of the idx'th point in the class:\r\n  // Since this is inlined and the \"dim\" argument is typically an immediate\r\n  // value, the\r\n  //  \"if/else's\" are actually solved at compile time.\r\n  inline float kdtree_get_pt(const size_t idx, const size_t dim) const {\r\n    if (dim == 0)\r\n      return pts[idx].x;\r\n    else if (dim == 1)\r\n      return pts[idx].y;\r\n    else\r\n      return pts[idx].z;\r\n  }\r\n\r\n  // Optional bounding-box computation: return false to default to a standard\r\n  // bbox computation loop.\r\n  //   Return true if the BBOX was already computed by the class and returned in\r\n  //   \"bb\" so it can be avoided to redo it again. Look at bb.size() to find out\r\n  //   the expected dimensionality (e.g. 2 or 3 for point clouds)\r\n  template <class BBOX>\r\n  bool kdtree_get_bbox(BBOX& /* bb */) const {\r\n    return false;\r\n  }\r\n};\r\n\r\n// Utility function for pointclouds\r\ntemplate <typename T1, typename T2>\r\nvoid filterVector(std::vector<T1>& vec, std::vector<T2>& scores,\r\n                  T2 filter_value) {\r\n  // Remove every element whose score is < filter_value\r\n  auto vec_address = vec.data();\r\n  vec.erase(std::remove_if(vec.begin(), vec.end(),\r\n                           [&scores, vec_address, filter_value](const T1& f) {\r\n                             return scores[(size_t)(&f - vec_address)] <\r\n                                    filter_value;\r\n                           }),\r\n            vec.end());\r\n}\r\n\r\ntemplate <typename T>\r\nvoid filterVector(std::vector<T>& vec, T filter_value) {\r\n  vec.erase(std::remove_if(\r\n                vec.begin(), vec.end(),\r\n                [filter_value](const float s) { return s < filter_value; }),\r\n            vec.end());\r\n}\r\n\r\ntemplate <typename T>\r\nvoid filterFloatVector(std::vector<T>& vec, std::vector<float>& scores,\r\n                       float filter_value) {\r\n  // Remove every element whose score is < filter_value\r\n  auto vec_address = vec.data();\r\n  vec.erase(std::remove_if(vec.begin(), vec.end(),\r\n                           [&scores, vec_address, filter_value](const T& f) {\r\n                             return scores[(size_t)(&f - vec_address)] <\r\n                                    filter_value;\r\n                           }),\r\n            vec.end());\r\n}\r\n\r\nvoid filterPointCloud(std::vector<PointXYZ>& pts, std::vector<float>& scores,\r\n                      float filter_value);\r\nvoid filterFloatVector(std::vector<float>& vec, float filter_value);\r\n\r\n// PLY reading/saving functions\r\nvoid save_cloud(std::string dataPath, std::vector<PointXYZ>& points,\r\n                std::vector<PointXYZ>& normals, std::vector<float>& features);\r\nvoid save_cloud(std::string dataPath, std::vector<PointXYZ>& points,\r\n                std::vector<float>& features);\r\nvoid save_cloud(std::string dataPath, std::vector<PointXYZ>& points,\r\n                std::vector<PointXYZ>& normals);\r\nvoid save_cloud(std::string dataPath, std::vector<PointXYZ>& points);\r\n\r\nvoid load_cloud(std::string& dataPath, std::vector<PointXYZ>& points);\r\n\r\nvoid load_cloud(std::string& dataPath, std::vector<PointXYZ>& points,\r\n                std::vector<float>& float_scalar,\r\n                std::string& float_scalar_name, std::vector<int>& int_scalar,\r\n                std::string& int_scalar_name);\r\n\r\nvoid load_cloud_normals(std::string& dataPath, std::vector<PointXYZ>& points,\r\n                        std::vector<PointXYZ>& normals,\r\n                        std::vector<float>& float_scalar,\r\n                        std::string& float_scalar_name,\r\n                        std::vector<int>& int_scalar,\r\n                        std::string& int_scalar_name);\r\n\r\n//------------------------------------------------------------------------------------------------------------\r\n// Plane3D class\r\n// *************\r\n//\r\n//------------------------------------------------------------------------------------------------------------\r\n\r\nclass Plane3D {\r\n public:\r\n  // Elements\r\n  // ********\r\n\r\n  // The plane is define by the equation a*x + b*y + c*z = d. The values (a, b,\r\n  // c) are stored in a PointXYZ called u.\r\n  PointXYZ u;\r\n  float d;\r\n\r\n  // Methods\r\n  // *******\r\n\r\n  // Constructor\r\n  Plane3D() {\r\n    u.x = 1;\r\n    u.y = 0;\r\n    u.z = 0;\r\n    d = 0;\r\n  }\r\n  Plane3D(const float a0, const float b0, const float c0, const float d0) {\r\n    u.x = a0;\r\n    u.y = b0;\r\n    u.z = c0;\r\n    d = d0;\r\n  }\r\n  Plane3D(const PointXYZ P0, const PointXYZ N0) {\r\n    // Init with point and normal\r\n    u = N0;\r\n    d = N0.dot(P0);\r\n  }\r\n  Plane3D(const PointXYZ A, const PointXYZ B, const PointXYZ C) {\r\n    // Init with three points\r\n    u = (B - A).cross(C - A);\r\n    d = u.dot(A);\r\n  }\r\n\r\n  // Method getting distance to one point\r\n  float point_distance(const PointXYZ P) {\r\n    return std::abs((u.dot(P) - d) / std::sqrt(u.sq_norm()));\r\n  }\r\n\r\n  // Method getting square distance to one point\r\n  float point_sq_dist(const PointXYZ P) {\r\n    float tmp = u.dot(P) - d;\r\n    return tmp * tmp / u.sq_norm();\r\n  }\r\n\r\n  // Method getting distances to some points\r\n  void point_distances(std::vector<PointXYZ>& points,\r\n                       std::vector<float>& distances) {\r\n    if (distances.size() != points.size())\r\n      distances = std::vector<float>(points.size());\r\n    size_t i = 0;\r\n    float inv_norm_u = 1 / std::sqrt(u.sq_norm());\r\n    for (auto& p : points) {\r\n      distances[i] = std::abs((u.dot(p) - d) * inv_norm_u);\r\n      i++;\r\n    }\r\n  }\r\n\r\n  int in_range(std::vector<PointXYZ>& points, float threshold) {\r\n    int count = 0;\r\n    float inv_norm_u = 1 / std::sqrt(u.sq_norm());\r\n    for (auto& p : points) {\r\n      if (std::abs((u.dot(p) - d) * inv_norm_u) < threshold) count++;\r\n    }\r\n    return count;\r\n  }\r\n};\r\n\r\n}  // namespace lidar\r\n}  // namespace vtr", "meta": {"hexsha": "172e7085d5141fc524f8c42a3c2f92b67b2eda24", "size": 12593, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "main/src/vtr_lidar/include/vtr_lidar/cloud/cloud.hpp", "max_stars_repo_name": "utiasASRL/vtr3", "max_stars_repo_head_hexsha": "b4edca56a19484666d3cdb25a032c424bdc6f19d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2021-09-15T03:42:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:40:01.000Z", "max_issues_repo_path": "main/src/vtr_lidar/include/vtr_lidar/cloud/cloud.hpp", "max_issues_repo_name": "shimp-t/vtr3", "max_issues_repo_head_hexsha": "bdcad784ffe26fabfa737d0e195bcb3bacb930c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2021-09-18T19:18:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-02T11:15:40.000Z", "max_forks_repo_path": "main/src/vtr_lidar/include/vtr_lidar/cloud/cloud.hpp", "max_forks_repo_name": "shimp-t/vtr3", "max_forks_repo_head_hexsha": "bdcad784ffe26fabfa737d0e195bcb3bacb930c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-09-18T01:31:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T05:09:37.000Z", "avg_line_length": 28.6856492027, "max_line_length": 111, "alphanum_fraction": 0.5313269277, "num_tokens": 3159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.2898694000081951}}
{"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  CombinedImuFactor.cpp\n *  @author Luca Carlone\n *  @author Stephen Williams\n *  @author Richard Roberts\n *  @author Vadim Indelman\n *  @author David Jensen\n *  @author Frank Dellaert\n *  @author Varun Agrawal\n **/\n\n#include <gtsam/navigation/CombinedImuFactor.h>\n#include <boost/serialization/export.hpp>\n\n/* External or standard includes */\n#include <ostream>\n\nnamespace gtsam {\n\nusing namespace std;\n\n//------------------------------------------------------------------------------\n// Inner class PreintegrationCombinedParams\n//------------------------------------------------------------------------------\nvoid PreintegrationCombinedParams::print(const string& s) const {\n  PreintegrationParams::print(s);\n  cout << \"biasAccCovariance:\\n[\\n\" << biasAccCovariance << \"\\n]\"\n       << endl;\n  cout << \"biasOmegaCovariance:\\n[\\n\" << biasOmegaCovariance << \"\\n]\"\n       << endl;\n  cout << \"biasAccOmegaInt:\\n[\\n\" << biasAccOmegaInt << \"\\n]\"\n       << endl;\n}\n\n//------------------------------------------------------------------------------\nbool PreintegrationCombinedParams::equals(const PreintegratedRotationParams& other,\n                                  double tol) const {\n  auto e = dynamic_cast<const PreintegrationCombinedParams*>(&other);\n  return e != nullptr && PreintegrationParams::equals(other, tol) &&\n         equal_with_abs_tol(biasAccCovariance, e->biasAccCovariance,\n                            tol) &&\n         equal_with_abs_tol(biasOmegaCovariance, e->biasOmegaCovariance,\n                            tol) &&\n         equal_with_abs_tol(biasAccOmegaInt, e->biasAccOmegaInt, tol);\n}\n\n//------------------------------------------------------------------------------\n// Inner class PreintegratedCombinedMeasurements\n//------------------------------------------------------------------------------\nvoid PreintegratedCombinedMeasurements::print(const string& s) const {\n  PreintegrationType::print(s);\n  cout << \"  preintMeasCov [ \" << preintMeasCov_ << \" ]\" << endl;\n}\n\n//------------------------------------------------------------------------------\nbool PreintegratedCombinedMeasurements::equals(\n    const PreintegratedCombinedMeasurements& other, double tol) const {\n  return PreintegrationType::equals(other, tol)\n      && equal_with_abs_tol(preintMeasCov_, other.preintMeasCov_, tol);\n}\n\n//------------------------------------------------------------------------------\nvoid PreintegratedCombinedMeasurements::resetIntegration() {\n  PreintegrationType::resetIntegration();\n  preintMeasCov_.setZero();\n}\n\n//------------------------------------------------------------------------------\n// sugar for derivative blocks\n#define D_R_R(H) (H)->block<3,3>(0,0)\n#define D_R_t(H) (H)->block<3,3>(0,3)\n#define D_R_v(H) (H)->block<3,3>(0,6)\n#define D_t_R(H) (H)->block<3,3>(3,0)\n#define D_t_t(H) (H)->block<3,3>(3,3)\n#define D_t_v(H) (H)->block<3,3>(3,6)\n#define D_v_R(H) (H)->block<3,3>(6,0)\n#define D_v_t(H) (H)->block<3,3>(6,3)\n#define D_v_v(H) (H)->block<3,3>(6,6)\n#define D_a_a(H) (H)->block<3,3>(9,9)\n#define D_g_g(H) (H)->block<3,3>(12,12)\n\n//------------------------------------------------------------------------------\nvoid PreintegratedCombinedMeasurements::integrateMeasurement(\n    const Vector3& measuredAcc, const Vector3& measuredOmega, double dt) {\n  // Update preintegrated measurements.\n  Matrix9 A; // overall Jacobian wrt preintegrated measurements (df/dx)\n  Matrix93 B, C;\n  PreintegrationType::update(measuredAcc, measuredOmega, dt, &A, &B, &C);\n\n  // Update preintegrated measurements covariance: as in [2] we consider a first\n  // order propagation that can be seen as a prediction phase in an EKF\n  // framework. In this implementation, in contrast to [2], we consider the\n  // uncertainty of the bias selection and we keep correlation between biases\n  // and preintegrated measurements\n\n  // Single Jacobians to propagate covariance\n  // TODO(frank): should we not also account for bias on position?\n  Matrix3 theta_H_biasOmega = -C.topRows<3>();\n  Matrix3 vel_H_biasAcc = -B.bottomRows<3>();\n\n  // overall Jacobian wrt preintegrated measurements (df/dx)\n  Eigen::Matrix<double, 15, 15> F;\n  F.setZero();\n  F.block<9, 9>(0, 0) = A;\n  F.block<3, 3>(0, 12) = theta_H_biasOmega;\n  F.block<3, 3>(6, 9) = vel_H_biasAcc;\n  F.block<6, 6>(9, 9) = I_6x6;\n\n  // propagate uncertainty\n  // TODO(frank): use noiseModel routine so we can have arbitrary noise models.\n  const Matrix3& aCov = p().accelerometerCovariance;\n  const Matrix3& wCov = p().gyroscopeCovariance;\n  const Matrix3& iCov = p().integrationCovariance;\n\n  // first order uncertainty propagation\n  // Optimized matrix multiplication   (1/dt) * G * measurementCovariance *\n  // G.transpose()\n  Eigen::Matrix<double, 15, 15> G_measCov_Gt;\n  G_measCov_Gt.setZero(15, 15);\n\n  // BLOCK DIAGONAL TERMS\n  D_t_t(&G_measCov_Gt) = dt * iCov;\n  D_v_v(&G_measCov_Gt) = (1 / dt) * vel_H_biasAcc\n      * (aCov + p().biasAccOmegaInt.block<3, 3>(0, 0))\n      * (vel_H_biasAcc.transpose());\n  D_R_R(&G_measCov_Gt) = (1 / dt) * theta_H_biasOmega\n      * (wCov + p().biasAccOmegaInt.block<3, 3>(3, 3))\n      * (theta_H_biasOmega.transpose());\n  D_a_a(&G_measCov_Gt) = dt * p().biasAccCovariance;\n  D_g_g(&G_measCov_Gt) = dt * p().biasOmegaCovariance;\n\n  // OFF BLOCK DIAGONAL TERMS\n  Matrix3 temp = vel_H_biasAcc * p().biasAccOmegaInt.block<3, 3>(3, 0)\n      * theta_H_biasOmega.transpose();\n  D_v_R(&G_measCov_Gt) = temp;\n  D_R_v(&G_measCov_Gt) = temp.transpose();\n  preintMeasCov_ = F * preintMeasCov_ * F.transpose() + G_measCov_Gt;\n}\n\n//------------------------------------------------------------------------------\n// CombinedImuFactor methods\n//------------------------------------------------------------------------------\nCombinedImuFactor::CombinedImuFactor(Key pose_i, Key vel_i, Key pose_j,\n    Key vel_j, Key bias_i, Key bias_j,\n    const PreintegratedCombinedMeasurements& pim) :\n    Base(noiseModel::Gaussian::Covariance(pim.preintMeasCov_), pose_i, vel_i,\n        pose_j, vel_j, bias_i, bias_j), _PIM_(pim) {\n}\n\n//------------------------------------------------------------------------------\ngtsam::NonlinearFactor::shared_ptr CombinedImuFactor::clone() const {\n  return boost::static_pointer_cast<gtsam::NonlinearFactor>(\n      gtsam::NonlinearFactor::shared_ptr(new This(*this)));\n}\n\n//------------------------------------------------------------------------------\nvoid CombinedImuFactor::print(const string& s,\n    const KeyFormatter& keyFormatter) const {\n  cout << (s.empty() ? s : s + \"\\n\") << \"CombinedImuFactor(\"\n       << keyFormatter(this->key1()) << \",\" << keyFormatter(this->key2()) << \",\"\n       << keyFormatter(this->key3()) << \",\" << keyFormatter(this->key4()) << \",\"\n       << keyFormatter(this->key5()) << \",\" << keyFormatter(this->key6())\n       << \")\\n\";\n  _PIM_.print(\"  preintegrated measurements:\");\n  this->noiseModel_->print(\"  noise model: \");\n}\n\n//------------------------------------------------------------------------------\nbool CombinedImuFactor::equals(const NonlinearFactor& other, double tol) const {\n  const This* e = dynamic_cast<const This*>(&other);\n  return e != nullptr && Base::equals(*e, tol) && _PIM_.equals(e->_PIM_, tol);\n}\n\n//------------------------------------------------------------------------------\nVector CombinedImuFactor::evaluateError(const Pose3& pose_i,\n    const Vector3& vel_i, const Pose3& pose_j, const Vector3& vel_j,\n    const imuBias::ConstantBias& bias_i, const imuBias::ConstantBias& bias_j,\n    boost::optional<Matrix&> H1, boost::optional<Matrix&> H2,\n    boost::optional<Matrix&> H3, boost::optional<Matrix&> H4,\n    boost::optional<Matrix&> H5, boost::optional<Matrix&> H6) const {\n\n  // error wrt bias evolution model (random walk)\n  Matrix6 Hbias_i, Hbias_j;\n  Vector6 fbias = traits<imuBias::ConstantBias>::Between(bias_j, bias_i,\n      H6 ? &Hbias_j : 0, H5 ? &Hbias_i : 0).vector();\n\n  Matrix96 D_r_pose_i, D_r_pose_j, D_r_bias_i;\n  Matrix93 D_r_vel_i, D_r_vel_j;\n\n  // error wrt preintegrated measurements\n  Vector9 r_Rpv = _PIM_.computeErrorAndJacobians(pose_i, vel_i, pose_j, vel_j,\n      bias_i, H1 ? &D_r_pose_i : 0, H2 ? &D_r_vel_i : 0, H3 ? &D_r_pose_j : 0,\n      H4 ? &D_r_vel_j : 0, H5 ? &D_r_bias_i : 0);\n\n  // if we need the jacobians\n  if (H1) {\n    H1->resize(15, 6);\n    H1->block<9, 6>(0, 0) = D_r_pose_i;\n    // adding: [dBiasAcc/dPi ; dBiasOmega/dPi]\n    H1->block<6, 6>(9, 0).setZero();\n  }\n  if (H2) {\n    H2->resize(15, 3);\n    H2->block<9, 3>(0, 0) = D_r_vel_i;\n    // adding: [dBiasAcc/dVi ; dBiasOmega/dVi]\n    H2->block<6, 3>(9, 0).setZero();\n  }\n  if (H3) {\n    H3->resize(15, 6);\n    H3->block<9, 6>(0, 0) = D_r_pose_j;\n    // adding: [dBiasAcc/dPj ; dBiasOmega/dPj]\n    H3->block<6, 6>(9, 0).setZero();\n  }\n  if (H4) {\n    H4->resize(15, 3);\n    H4->block<9, 3>(0, 0) = D_r_vel_j;\n    // adding: [dBiasAcc/dVi ; dBiasOmega/dVi]\n    H4->block<6, 3>(9, 0).setZero();\n  }\n  if (H5) {\n    H5->resize(15, 6);\n    H5->block<9, 6>(0, 0) = D_r_bias_i;\n    // adding: [dBiasAcc/dBias_i ; dBiasOmega/dBias_i]\n    H5->block<6, 6>(9, 0) = Hbias_i;\n  }\n  if (H6) {\n    H6->resize(15, 6);\n    H6->block<9, 6>(0, 0).setZero();\n    // adding: [dBiasAcc/dBias_j ; dBiasOmega/dBias_j]\n    H6->block<6, 6>(9, 0) = Hbias_j;\n  }\n\n  // overall error\n  Vector r(15);\n  r << r_Rpv, fbias; // vector of size 15\n  return r;\n}\n\n//------------------------------------------------------------------------------\nstd::ostream& operator<<(std::ostream& os, const CombinedImuFactor& f) {\n  f._PIM_.print(\"combined preintegrated measurements:\\n\");\n  os << \"  noise model sigmas: \" << f.noiseModel_->sigmas().transpose();\n  return os;\n}\n}\n /// namespace gtsam\n\n/// Boost serialization export definition for derived class\nBOOST_CLASS_EXPORT_IMPLEMENT(gtsam::PreintegrationCombinedParams);\n\n", "meta": {"hexsha": "ca1c5b93a64eb95e9f582565d78579a52ebab4c2", "size": 10154, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/navigation/CombinedImuFactor.cpp", "max_stars_repo_name": "Alevs2R/gtsam", "max_stars_repo_head_hexsha": "6cef675e6eaeaf89f2462e8cfec4a4a9a497fac8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1402.0, "max_stars_repo_stars_event_min_datetime": "2017-03-28T00:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:28:32.000Z", "max_issues_repo_path": "gtsam/navigation/CombinedImuFactor.cpp", "max_issues_repo_name": "Alevs2R/gtsam", "max_issues_repo_head_hexsha": "6cef675e6eaeaf89f2462e8cfec4a4a9a497fac8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "gtsam/navigation/CombinedImuFactor.cpp", "max_forks_repo_name": "Alevs2R/gtsam", "max_forks_repo_head_hexsha": "6cef675e6eaeaf89f2462e8cfec4a4a9a497fac8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 565.0, "max_forks_repo_forks_event_min_datetime": "2017-11-30T16:15:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:53:04.000Z", "avg_line_length": 38.7557251908, "max_line_length": 83, "alphanum_fraction": 0.574354934, "num_tokens": 2858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.28986940000819506}}
{"text": "#include <iostream>\n#include <boost/program_options.hpp>\n#include <boost/filesystem.hpp>\n#include \"netsne.h\"\n#include <armadillo>\n\nusing namespace std;\nnamespace po = boost::program_options;\nnamespace fsys = boost::filesystem;\n\nbool load_data(string infile_X, mat &X, int &num_instances, int &num_features) {\n\n  FILE *fp = fopen(infile_X.c_str(), \"rb\");\n\tif (fp == NULL) {\n\t\tcout << \"Error: could not open data file \" << infile_X << endl;\n\t\treturn false;\n\t}\n\n  uint64_t ret;\n\tret = fread(&num_instances, sizeof(int), 1, fp);\n\tret = fread(&num_features, sizeof(int), 1, fp);\n\n  X.set_size(num_features, num_instances);\n\n  uint64_t nelem = (uint64_t)num_instances * num_features;\n\n  size_t batch_size = 1e8;\n  double *ptr = X.memptr();\n  ret = 0;\n  for (uint64_t remaining = nelem; remaining > 0; remaining -= batch_size) {\n    if (remaining < batch_size) {\n      batch_size = remaining;\n    }\n    ret += fread(ptr, sizeof(double), batch_size, fp);\n    ptr += batch_size;\n  }\n  \n  if (ret != nelem) {\n    cout << \"Error: reading input returned incorrect number of elements (\" << ret\n         << \", expected \" << nelem << \")\" << endl;\n    return false;\n  }\n  \n\tfclose(fp);\n\n\treturn true;\n}\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-X\", po::value<string>()->value_name(\"FILE\")->default_value(\"data.dat\"), \"name of binary input file containing data feature matrix (see prepare_input.m)\")\n    (\"input-P\", po::value<string>()->value_name(\"FILE\")->default_value(\"P.dat\"), \"name of binary input file containing P matrix (see ComputeP)\")\n    (\"input-Y\", po::value<string>()->value_name(\"FILE\"), \"if this option is provided, net-SNE will train to match the provided embedding instead of using the P matrix\")\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(0.02, \"0.02\"), \"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    (\"num-local-sample\", po::value<int>()->value_name(\"NUM\")->default_value(20), \"number of local samples for each data point in the mini-batch\")\n    (\"batch-frac\", po::value<double>()->value_name(\"NUM\")->default_value(0.1, \"0.1\"), \"fraction of data to sample for mini-batch\")\n    (\"min-sample-Z\", po::value<double>()->value_name(\"NUM\")->default_value(0.1, \"0.1\"), \"minimum fraction of data to use for approximating the normalization factor Z in the gradient\")\n    (\"l2-reg\", po::value<double>()->value_name(\"NUM\")->default_value(0, \"0\"), \"L2 regularization parameter\")\n    (\"init-model-prefix\", po::value<string>()->value_name(\"STR\"), \"prefix of model files for initialization\")\n    (\"step-method\", po::value<string>()->value_name(\"STR\")->default_value(\"adam\"), \"gradient step schedule; 'adam', 'mom' (momentum), 'mom_gain' (momentum with gains), 'fixed'\")\n    (\"num-input-feat\", po::value<int>()->value_name(\"NUM\"), \"if set, use only the first NUM features for the embedding function\")\n    (\"init-map\", po::bool_switch()->default_value(false), \"output initial mapping for the entire data\")\n    (\"num-layers\", po::value<int>()->value_name(\"NUM\")->default_value(2), \"number of layers in the neural network\")\n    (\"num-units\", po::value<int>()->value_name(\"NUM\")->default_value(50), \"number of units for each layer in the neural network\")\n    (\"act-fn\", po::value<string>()->value_name(\"STR\")->default_value(\"relu\"), \"activation function of the neural network; 'sigmoid' or 'relu'\")\n    (\"test-model\", po::bool_switch()->default_value(false), \"if set, use the model provided with --init-model-prefix and visualize the entire data set then terminate without training\")\n    (\"no-target\", po::bool_switch()->default_value(false), \"if this option is provided (ignored if --test-model is not set), then only the new embedding is printed, without the objective value\")\n    (\"perm-iter\", po::value<int>()->value_name(\"NUM\")->default_value(INT_MAX, \"INT_MAX\"), \"After every NUM iterations, permute the ordering of data points for fast mini-batching\")\n    (\"cache-iter\", po::value<int>()->value_name(\"NUM\")->default_value(INT_MAX, \"INT_MAX\"), \"After every NUM iterations, write intermediary embeddings and parameters to disk. Final embedding is always reported.\")\n    (\"no-sgd\", po::bool_switch()->default_value(false), \"if set, do not use SGD acceleration; equivalent to t-SNE with an additional backpropagation step to train a neural network. Effective for small datasets\")\n    //(\"batch-norm\", po::bool_switch()->default_value(false), \"turn on batch normalization\")\n    //(\"monte-carlo-pos\", po::bool_switch()->default_value(false), \"use monte-carlo integration for positive gradient term\")\n    //(\"match-pos-neg\", po::bool_switch()->default_value(false), \"compute negative forces for points sampled for positive force\")\n\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_P = vm[\"input-P\"].as<string>();\n  string infile_X = vm[\"input-X\"].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 (\" << outdir << \") already exists\" << endl;\n    return 1;\n  }\n  if (fsys::create_directory(dir)) {\n    cout << \"Output directory created: \" << outdir << endl; \n  }\n\n  fsys::path paramfile = dir;\n  paramfile /= \"param.txt\";\n  ofstream ofs(paramfile.string().c_str());\n\n  NETSNE* netsne = new NETSNE();\n\n  bool use_known_Y = vm.count(\"input-Y\");\n  string infile_Y;\n\n  netsne->TEST_RUN = vm[\"test-model\"].as<bool>();\n  netsne->NO_TARGET = netsne->TEST_RUN && vm[\"no-target\"].as<bool>();\n\n  if (!netsne->NO_TARGET) {\n    if (use_known_Y) {\n      infile_Y = vm[\"input-Y\"].as<string>();\n      ofs << \"input-Y: \" << infile_Y << endl;\n      cout << \"Learning to match the provided embedding: \" << infile_Y << endl;\n    } else {\n      ofs << \"input-P: \" << infile_P << endl;\n    }\n  }\n  ofs << \"input-X: \" << infile_X << endl;\n  ofs << \"out-dir: \" << fsys::canonical(dir).string() << endl;\n\n  netsne->BATCH_FRAC = vm[\"batch-frac\"].as<double>(); ofs << \"batch-frac: \" << netsne->BATCH_FRAC << endl;\n  netsne->N_SAMPLE_LOCAL = vm[\"num-local-sample\"].as<int>(); ofs << \"num-local-sample: \" << netsne->N_SAMPLE_LOCAL << endl;\n  netsne->MIN_SAMPLE_Z = vm[\"min-sample-Z\"].as<double>(); ofs << \"min-sample-Z: \" << netsne->MIN_SAMPLE_Z << endl;\n  netsne->STOP_LYING = vm[\"early-exag-iter\"].as<int>(); ofs << \"early-exag-iter: \" << netsne->STOP_LYING << endl;\n  netsne->STEP_METHOD = vm[\"step-method\"].as<string>(); ofs << \"step-method: \" << netsne->STEP_METHOD << endl;\n  netsne->LEARN_RATE = vm[\"learn-rate\"].as<double>(); ofs << \"learn-rate: \" <<  netsne->LEARN_RATE << endl;\n  netsne->L2_REG = vm[\"l2-reg\"].as<double>(); ofs << \"l2-reg: \" <<  netsne->L2_REG << endl;\n  netsne->SGD_FLAG = !vm[\"no-sgd\"].as<bool>(); ofs << \"sgd: \" << netsne->SGD_FLAG << endl;\n  netsne->PERM_ITER = vm[\"perm-iter\"].as<int>(); ofs << \"perm-iter: \" << netsne->PERM_ITER << endl;\n  netsne->CACHE_ITER = vm[\"cache-iter\"].as<int>(); ofs << \"cache-iter: \" << netsne->CACHE_ITER << endl;\n  //netsne->BATCH_NORM = vm[\"batch-norm\"].as<bool>(); ofs << \"batch-norm: \" << netsne->BATCH_NORM << endl;\n  //netsne->MONTE_CARLO_POS = vm[\"monte-carlo-pos\"].as<bool>(); ofs << \"monte-carlo-pos: \" << netsne->MONTE_CARLO_POS << endl;\n  //netsne->MATCH_POS_NEG = vm[\"match-pos-neg\"].as<bool>(); ofs << \"match-pos-neg: \" << netsne->MATCH_POS_NEG << endl;\n\n  netsne->MODEL_PREFIX_FLAG = vm.count(\"init-model-prefix\");\n  if (netsne->MODEL_PREFIX_FLAG) {\n    netsne->MODEL_PREFIX = vm[\"init-model-prefix\"].as<string>();\n  }\n  ofs << \"init-model-prefix: \" << netsne->MODEL_PREFIX << endl;\n\n  if (netsne->TEST_RUN) {\n    netsne->COMPUTE_INIT = true;\n\n    if (!netsne->MODEL_PREFIX_FLAG) {\n      cout << \"Error: if --test-model is set, then --init-model-prefix must be provided; see --help\" << endl;\n      return 1;\n    }\n  } else {\n    netsne->COMPUTE_INIT = vm[\"init-map\"].as<bool>();\n  }\n  ofs << \"init-map: \" << netsne->COMPUTE_INIT << endl;\n\n  if (!netsne->MODEL_PREFIX_FLAG) {\n    netsne->NUM_LAYERS = vm[\"num-layers\"].as<int>(); ofs << \"num-layers: \" << netsne->NUM_LAYERS << endl;\n    netsne->NUM_UNITS = vm[\"num-units\"].as<int>(); ofs << \"num-units: \" << netsne->NUM_UNITS << endl;\n    netsne->ACT_FN = vm[\"act-fn\"].as<string>(); ofs << \"act-fn: \" << netsne->ACT_FN << endl;\n  }\n\n  if (netsne->STEP_METHOD == \"mom\" || netsne->STEP_METHOD == \"mom_gain\") {\n    netsne->MOM_SWITCH_ITER = vm[\"mom-switch-iter\"].as<int>(); ofs << \"mom-switch-iter: \" << netsne->MOM_SWITCH_ITER << endl;\n    netsne->MOM_INIT = vm[\"mom-init\"].as<double>(); ofs << \"mom-init: \" << netsne->MOM_INIT << endl;\n    netsne->MOM_FINAL = vm[\"mom-final\"].as<double>(); ofs << \"mom-final: \" << netsne->MOM_FINAL << endl;\n  }\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  int max_iter = vm[\"max-iter\"].as<int>(); ofs << \"max-iter: \" << max_iter << endl;\n\n  ofs.close();\n\n  if (vm.count(\"help\")) {\n    cout << \"Usage: RunBhtsne [options]\" << endl;\n    cout << desc << \"\\n\";\n    return 1;\n  }\n\n  if (netsne->STEP_METHOD != \"adam\" && netsne->STEP_METHOD != \"mom\" && netsne->STEP_METHOD != \"mom_gain\"\n      && netsne->STEP_METHOD != \"fixed\") {\n    cout << \"Error: Unrecognized --step-method argument \" << netsne->STEP_METHOD << \"; see --help\" << endl;\n    return 1;\n  } \n\n  if (netsne->ACT_FN != \"sigmoid\" && netsne->ACT_FN != \"relu\") {\n    cout << \"Error: Unrecognized --act-fn argument \" << netsne->ACT_FN << \"; see --help\" << endl;\n    return 1;\n  } \n\n  int num_input_feat;\n  if (vm.count(\"num-input-feat\")) {\n    num_input_feat = vm[\"num-input-feat\"].as<int>();\n  } else {\n    num_input_feat = INT_MAX;\n  }\n\n  cout << \"Loading input features ... \";\n  mat X;\n  int num_instances;\n  int num_features;\n\tif (!load_data(infile_X, X, num_instances, num_features)) {\n    return 1;\n  }\n  cout << endl;\n\n  if (X.n_rows > num_input_feat) {\n    cout << \"Truncating to top \" << num_input_feat << \" features\" << endl;\n    X = X.head_rows(num_input_feat);\n  }\n\n  cout << \"Data feature matrix is \" << X.n_rows << \" by \" << X.n_cols << endl;\n\n  int N;\n  unsigned int *row_P = NULL;\n  unsigned int *col_P = NULL;\n  double *val_P = NULL;\n  mat target_Y;\n\n  if (netsne->NO_TARGET) {\n\n    cout << \"No target provided\" << endl;\n    N = X.n_cols;\n\n  } else if (use_known_Y) {\n\n    cout << \"Loading target Y ... \";\n    target_Y.load(infile_Y, arma_ascii);\n    target_Y = target_Y.t();\n    cout << \"done\" << endl;\n\n    N = target_Y.n_cols;\n\n    if (N != X.n_cols) {\n      cout << \"Error: Y matrix dimensions (\" << N << \") do not match with X matrix (\" << X.n_cols << \")\" << endl;\n      return 1;\n    }\n\n  } else {\n\n    cout << \"Loading input similarities ... \";\n    if (!netsne->load_P(infile_P, N, &row_P, &col_P, &val_P)) {\n      cout << \"Error: failed to load P from \" << infile_P << endl;\n      return 1;\n    }\n    cout << \"done\" << endl;\n\n    if (N != X.n_cols) {\n      cout << \"Error: P matrix dimensions (\" << N << \") do not match with X matrix (\" << X.n_cols << \")\" << endl;\n      return 1;\n    }\n\n  }\n\n  mat Y(no_dims, N);\n\n  if (!netsne->run(N, row_P, col_P, val_P, target_Y, X, Y, no_dims, theta, rand_seed,\n           max_iter, dir)) {\n    return 1;\n  }\n\n  free(row_P);\n  free(col_P);\n  free(val_P);\n\n  delete(netsne);\n\n  cout << \"Done\" << endl;\n}\n", "meta": {"hexsha": "43977ac14d1426fb02a40a2e6f4efbf1b1497043", "size": 12925, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RunNetsne.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": "RunNetsne.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": "RunNetsne.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.5105633803, "max_line_length": 211, "alphanum_fraction": 0.6335009671, "num_tokens": 3649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.4921881357207955, "lm_q1q2_score": 0.289844243418859}}
{"text": "// MIT License\n//\n// Copyright (c) 2021 Aditya Shridhar Hegde\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 \"mean_shift.hpp\"\n\n#include <NTL/ZZ.h>\n\n#include <algorithm>\n#include <numeric>\n#include <random>\n#include <stdexcept>\n\nMeanShift::MeanShift(Scheme &scheme, long logn, long logq, long logq_boot,\n                     long logp, long logt)\n    : scheme(scheme),\n      logn(logn),\n      logq(logq),\n      logq_boot(logq_boot),\n      logp(logp),\n      logt(logt) {\n  slots = 1 << logn;\n  refreshSeed();\n}\n\nMeanShift::MeanShift(Scheme &scheme, long logn, long logq, long logq_boot,\n                     long logp, long logt, long seed)\n    : scheme(scheme),\n      logn(logn),\n      logq(logq),\n      logq_boot(logq_boot),\n      logp(logp),\n      logt(logt),\n      seed(seed) {\n  slots = 1 << logn;\n}\n\nvoid MeanShift::refreshSeed(long s) { seed = s; }\n\nvoid MeanShift::refreshSeed() { seed = std::rand(); }\n\nvoid MeanShift::leftRotateAndEqual(Ciphertext &x, long r) {\n  while (r & (-r)) {\n    scheme.leftRotateFastAndEqual(x, r & (-r));\n    r -= (r & (-r));\n  }\n}\n\nvoid MeanShift::rightRotateAndEqual(Ciphertext &x, long r) {\n  while (r & (-r)) {\n    scheme.rightRotateFastAndEqual(x, r & (-r));\n    r -= (r & (-r));\n  }\n}\n\n// x.logq := x.logq\nvoid MeanShift::repeatSlotRight(Ciphertext &x, long rep, long step) {\n  Ciphertext orig;\n  Ciphertext temp;\n  orig.copy(x);\n\n  long rot = 1;\n  for (long i = NumBits(rep) - 2; i >= 0; --i) {\n    temp.copy(x);\n    rightRotateAndEqual(temp, step * rot);\n    scheme.addAndEqual(x, temp);\n    rot *= 2;\n\n    if (bit(rep, i)) {\n      temp.copy(orig);\n      rightRotateAndEqual(temp, rot * step);\n      scheme.addAndEqual(x, temp);\n      rot += 1;\n    }\n  }\n}\n\n// x.logq := x.logq\nvoid MeanShift::sumSlotsLeft(Ciphertext &x, long num, long step) {\n  Ciphertext orig;\n  Ciphertext temp;\n  orig.copy(x);\n\n  long rot = 1;\n  for (long i = NumBits(num) - 2; i >= 0; --i) {\n    temp.copy(x);\n    leftRotateAndEqual(temp, rot * step);\n    scheme.addAndEqual(x, temp);\n    rot *= 2;\n\n    if (bit(num, i)) {\n      temp.copy(orig);\n      leftRotateAndEqual(temp, rot * step);\n      scheme.addAndEqual(x, temp);\n      rot += 1;\n    }\n  }\n}\n\n// x.logq := x.logq - logp\nvoid MeanShift::clearSlotsRight(Ciphertext &x, long ret_size, long skip,\n                                long max_slot) {\n  std::vector<complex<double>> selector(slots, complex<double>{0, 0});\n\n  for (long i = 0; i + ret_size <= max_slot; i += skip) {\n    std::fill(selector.begin() + i, selector.begin() + i + ret_size,\n              complex<double>{1, 0});\n  }\n\n  scheme.multByConstVecAndEqual(x, selector.data(), logp);\n  scheme.reScaleByAndEqual(x, logp);\n}\n\n// res.logq = x.logq - (steps + 2) * logp\nvoid MeanShift::inverse(Ciphertext &res, Ciphertext &x, double m, long steps) {\n  Ciphertext scaled;\n  scheme.multByConst(scaled, x, 2.0 / m, logp);\n  scheme.reScaleByAndEqual(scaled, logp);\n\n  SchemeAlgo schemeAlgo(scheme);\n  schemeAlgo.inverse(res, scaled, scaled.logp, steps);\n\n  scheme.multByConstAndEqual(res, 2.0 / m, res.logp);\n  scheme.reScaleByAndEqual(res, logp);\n}\n\n// res[i].logq = x[i].logq - (inv_steps + t + 3) * logp\nvoid MeanShift::minIdx(std::vector<Ciphertext> &res, std::vector<Ciphertext> &x,\n                       long t, long inv_steps) {\n  Ciphertext sum;\n  res.resize(x.size());\n\n  for (size_t i = 0; i < x.size(); ++i) {\n    // res[i] := 1 - x[i]\n    scheme.negate(res[i], x[i]);\n    scheme.addConstAndEqual(res[i], 1.0, logp);\n\n    // res[i] := res[i]^(2^t)\n    for (long j = 0; j < t; ++j) {\n      scheme.squareAndEqual(res[i]);\n      scheme.reScaleByAndEqual(res[i], logp);\n    }\n\n    // sum := sum + res[i]\n    if (i == 0)\n      sum.copy(res[0]);\n    else {\n      scheme.addAndEqual(sum, res[i]);\n    }\n  }\n\n  // inv := 1/sum\n  Ciphertext inv;\n  inverse(inv, sum, x.size(), inv_steps);\n\n  // res[i] := res[i] / sum\n  for (size_t i = 0; i < res.size(); ++i) {\n    scheme.modDownToAndEqual(res[i], inv.logq);\n    scheme.multAndEqual(res[i], inv);\n    scheme.reScaleByAndEqual(res[i], logp);\n  }\n}\n\n// res.logq := x.logq - (inv_steps + t + 4) logp\nvoid MeanShift::minIdxSIMD(Ciphertext &res, Ciphertext &x, long dim,\n                           long npoints, long t, long inv_steps,\n                           long batchsize) {\n  scheme.negate(res, x);\n  scheme.addConstAndEqual(res, 1.0, logp);\n\n  for (long j = 0; j < t; ++j) {\n    scheme.squareAndEqual(res);\n    scheme.reScaleByAndEqual(res, logp);\n  }\n\n  Ciphertext sum;\n  sum.copy(res);\n  sumSlotsLeft(sum, batchsize, npoints * dim);\n  clearSlotsRight(sum, npoints * dim, slots, slots);\n  repeatSlotRight(sum, batchsize, npoints * dim);\n\n  Ciphertext inv;\n  inverse(inv, sum, batchsize, inv_steps);\n\n  scheme.modDownToAndEqual(res, inv.logq);\n  scheme.multAndEqual(res, inv);\n  scheme.reScaleByAndEqual(res, logp);\n}\n\n// res.logq = x.logq - logp\nvoid MeanShift::l2NormSquared(Ciphertext &res, Ciphertext &x) {\n  Ciphertext rot;\n  scheme.square(res, x);\n  scheme.reScaleByAndEqual(res, logp);\n  rot.copy(res);\n  for (long i = 1; i < slots; ++i) {\n    scheme.leftRotateFastAndEqual(rot, 1);\n    scheme.addAndEqual(res, rot);\n  }\n}\n\n// res.logq := x.logq - 2 logp\nvoid MeanShift::l2NormSquaredSIMD(Ciphertext &res, Ciphertext &x, long dim,\n                                  long num_points) {\n  scheme.square(res, x);\n  scheme.reScaleByAndEqual(res, logp);\n  sumSlotsLeft(res, dim, 1);\n  clearSlotsRight(res, 1, dim, num_points * dim);\n  repeatSlotRight(res, dim, 1);\n}\n\n// res.logq := x.logq - (degree + 1) * logp\nvoid MeanShift::kernel(Ciphertext &res, Ciphertext &x, Ciphertext &y,\n                       long degree) {\n  // diff = (x - y)^2\n  Ciphertext diff;\n  scheme.sub(diff, x, y);\n\n  l2NormSquared(res, diff);\n\n  // res = (1 - res)^(2^degree)\n  scheme.negateAndEqual(res);\n  scheme.addConstAndEqual(res, 1.0, logp);\n  for (long i = 0; i < degree; ++i) {\n    scheme.squareAndEqual(res);\n    scheme.reScaleByAndEqual(res, logp);\n  }\n}\n\n// res.logp := x.logp - (degree + 2) logp\nvoid MeanShift::kernelSIMD(Ciphertext &res, Ciphertext &x, Ciphertext &y,\n                           long dim, long num_points, long degree) {\n  // diff = (x - y)^2\n  Ciphertext diff;\n  scheme.sub(diff, x, y);\n\n  l2NormSquaredSIMD(res, diff, dim, num_points);\n\n  // res = (1 - res)^(2^degree)\n  scheme.negateAndEqual(res);\n  scheme.addConstAndEqual(res, 1.0, logp);\n  for (long i = 0; i < degree; ++i) {\n    scheme.squareAndEqual(res);\n    scheme.reScaleByAndEqual(res, logp);\n  }\n}\n\nvoid MeanShift::modeSeeking(std::vector<Ciphertext> &res,\n                            std::vector<Ciphertext> &points, long d, long steps,\n                            long kdegree, long inv_steps) {\n  res.resize(d);\n\n  // Choose dusts\n  std::mt19937 gen(seed);\n  std::uniform_int_distribution<> distrib(0, points.size() - 1);\n  for (long i = 0; i < d; ++i) {\n    res[i].copy(points[distrib(gen)]);\n  }\n\n  // Gradient ascent\n  for (long iter = 0; iter < steps; ++iter) {\n    // dust.logq := dust.logq - (kdegree + inv_steps + 4) * logp\n    for (auto &dust : res) {\n      // Bootstrap if modulus not large enough for one more iteration\n      if (dust.logq < (kdegree + inv_steps + 4) * logp + 1) {\n        scheme.bootstrapAndEqual(dust, logq_boot, logQ, logt);\n      }\n\n      Ciphertext sum, A, a, tpoint, temp;\n\n      for (size_t k = 0; k < points.size(); ++k) {\n        if (points[k].logq != dust.logq)\n          scheme.modDownTo(tpoint, points[k], dust.logq);\n        else\n          tpoint.copy(points[k]);\n\n        kernel(a, tpoint, dust, kdegree);\n\n        scheme.modDownTo(temp, tpoint, a.logq);\n        scheme.multAndEqual(temp, a);\n        scheme.reScaleByAndEqual(temp, logp);\n\n        if (k == 0) {\n          sum.copy(a);\n          A.copy(temp);\n        } else {\n          scheme.addAndEqual(sum, a);\n          scheme.addAndEqual(A, temp);\n        }\n      }\n\n      Ciphertext inv;\n      inverse(inv, sum, points.size(), inv_steps);\n\n      scheme.modDownToAndEqual(A, inv.logq);\n      scheme.mult(dust, inv, A);\n      scheme.reScaleByAndEqual(dust, logp);\n    }\n  }\n}\n\nvoid MeanShift::refreshDusts(Ciphertext &dusts, long dim, long npoints,\n                             long d) {\n  Ciphertext temp1, temp2;\n\n  // The cost of bootstrapping is proportional to the number of underlying\n  // plaintext slots. Bootstrapping constitutes one of the most expensive\n  // operations in the algorithm.\n  //\n  // Currently dusts are of the form (d1, d1, ..., d1, d2, d2, ..., dd).\n  // We want convert it to (d1, d2, d3, ..., dd) to reduce the number of\n  // plaintext slots.\n  std::vector<complex<double>> selector(slots, complex<double>{0, 0});\n  for (long i = 0; i < d; ++i) {\n    std::fill(selector.begin() + i * npoints * dim,\n              selector.begin() + i * npoints * dim + dim,\n              complex<double>{1, 0});\n    scheme.multByConstVec(temp1, dusts, selector.data(), logp);\n    scheme.reScaleByAndEqual(temp1, logp);\n    std::fill(selector.begin() + i * npoints * dim,\n              selector.begin() + i * npoints * dim + dim,\n              complex<double>{0, 0});\n\n    if (i == 0) {\n      temp2.copy(temp1);\n    } else {\n      leftRotateAndEqual(temp1, i * dim * (npoints - 1));\n      scheme.addAndEqual(temp2, temp1);\n    }\n  }\n\n  long step = 1 << ((long)std::ceil(std::log2(dim * d)));\n  repeatSlotRight(temp2, slots / step, step);\n  auto temp = temp2.n;\n  temp2.n = step;\n\n  scheme.bootstrapAndEqual(temp2, logq_boot, logQ, logt);\n  temp2.n = temp;\n\n  for (long i = 0; i < d; ++i) {\n    std::fill(selector.begin() + i * dim, selector.begin() + (i + 1) * dim,\n              complex<double>{1, 0});\n    scheme.multByConstVec(temp1, temp2, selector.data(), logp);\n    scheme.reScaleByAndEqual(temp1, logp);\n    std::fill(selector.begin() + i * dim, selector.begin() + (i + 1) * dim,\n              complex<double>{0, 0});\n\n    if (i == 0) {\n      dusts.copy(temp1);\n    } else {\n      rightRotateAndEqual(temp1, i * dim * (npoints - 1));\n      scheme.addAndEqual(dusts, temp1);\n    }\n  }\n}\n\nvoid MeanShift::modeSeekingSIMD(Ciphertext &dusts,\n                                std::vector<Ciphertext> &points, long dim,\n                                long npoints, long d, long steps, long kdegree,\n                                long inv_steps) {\n  Ciphertext temp;\n\n  // Choose dusts\n  std::mt19937 gen(seed);\n  // Can also choose a ciphertext at random and then a point in the ciphertext\n  // at random. However, this approach allows easy verification when computed\n  // in plaintext (check plaintext_clustering).\n  std::uniform_int_distribution<> distrib(0, npoints * points.size() - 1);\n  std::vector<complex<double>> selector(slots, complex<double>{0, 0});\n\n  // Assume d < slots / (dim * npoints)\n  for (long i = 0; i < d; ++i) {\n    long r = distrib(gen);\n    long pi = r % npoints;\n    long ci = r / npoints;\n\n    std::fill(selector.begin() + pi * dim, selector.begin() + (pi + 1) * dim,\n              complex<double>{1, 0});\n    scheme.multByConstVec(temp, points[ci], selector.data(), logp);\n    scheme.reScaleByAndEqual(temp, logp);\n    std::fill(selector.begin() + pi * dim, selector.begin() + (pi + 1) * dim,\n              complex<double>{0, 0});\n\n    long beg = i * npoints;\n    if (beg < pi) {\n      leftRotateAndEqual(temp, (pi - beg) * dim);\n    } else if (beg > pi) {\n      rightRotateAndEqual(temp, (beg - pi) * dim);\n    }\n\n    if (i == 0)\n      dusts.copy(temp);\n    else\n      scheme.addAndEqual(dusts, temp);\n  }\n\n  // dusts will be repeated in loop below. The current dust format is expected\n  // at the start of each iteration.\n\n  // Gradient ascent\n  // Now, dusts.logq = points.logq - logp\n\n  Ciphertext grad, sum, A, temp2, tpoint;\n\n  for (long iter = 0; iter < steps; ++iter) {\n    // Bootstrap if modulus not large enough for one more iteration\n    if (dusts.logq - (kdegree + inv_steps + 6) * logp < logq_boot) {\n      refreshDusts(dusts, dim, npoints, d);\n    }\n\n    if (dusts.logq - (kdegree + inv_steps + 6) * logp < logq_boot) {\n      throw std::runtime_error(\n          \"Modulus not large enough for mode seeking after bootstrap.\");\n    }\n\n    // In the beginning of each iteration, only the first `dim` slots of dusts\n    // have the right value and everything else has 0.\n    repeatSlotRight(dusts, npoints, dim);\n\n    for (size_t i = 0; i < points.size(); ++i) {\n      scheme.modDownTo(tpoint, points[i], dusts.logq);\n      kernelSIMD(grad, dusts, tpoint, dim, npoints * d, kdegree);\n\n      scheme.modDownTo(temp2, tpoint, grad.logq);\n      scheme.mult(temp, grad, temp2);\n      scheme.reScaleByAndEqual(temp, logp);\n      sumSlotsLeft(temp, npoints, dim);\n      if (i == 0) {\n        A.copy(temp);\n      } else {\n        scheme.addAndEqual(A, temp);\n      }\n\n      sumSlotsLeft(grad, npoints, dim);\n      if (i == 0) {\n        sum.copy(grad);\n      } else {\n        scheme.addAndEqual(sum, grad);\n      }\n    }\n\n    Ciphertext inv;\n    inverse(inv, sum, npoints * points.size(), inv_steps);\n\n    scheme.modDownToAndEqual(A, inv.logq);\n    scheme.mult(dusts, inv, A);\n    scheme.reScaleByAndEqual(dusts, logp);\n    clearSlotsRight(dusts, dim, dim * npoints, d * npoints * dim);\n  }\n\n  repeatSlotRight(dusts, npoints, dim);\n}\n\n// z := max(kdegree + 2, inv_steps + minidx_t + 5)\n// res.logq = dusts.logq - z * logp\nvoid MeanShift::pointLabeling(std::vector<std::vector<Ciphertext>> &res,\n                              std::vector<Ciphertext> &dusts,\n                              std::vector<Ciphertext> &points, long kdegree,\n                              long inv_steps, long minidx_t) {\n  std::vector<Ciphertext> nbhd(dusts.size());\n  Ciphertext temp;\n\n  for (size_t i = 0; i < dusts.size(); ++i) {\n    for (size_t j = 0; j < dusts.size(); ++j) {\n      kernel(temp, dusts[i], dusts[j], kdegree);\n\n      if (j == 0) {\n        nbhd[i].copy(temp);\n      } else {\n        scheme.addAndEqual(nbhd[i], temp);\n      }\n    }\n  }\n\n  std::vector<Ciphertext> Cbar;\n  std::vector<Ciphertext> norms(dusts.size());\n\n  res.resize(points.size());\n\n  for (size_t i = 0; i < points.size(); ++i) {\n    for (size_t j = 0; j < dusts.size(); ++j) {\n      scheme.sub(temp, points[i], dusts[j]);\n      l2NormSquared(norms[j], temp);\n    }\n\n    minIdx(Cbar, norms, minidx_t, inv_steps);\n    res[i].resize(dusts.size());\n\n    for (size_t j = 0; j < dusts.size(); ++j) {\n      // make compatible for multiplication\n      if (Cbar[j].logq < nbhd[j].logq) {\n        // this will be run once for all points\n        scheme.modDownToAndEqual(nbhd[j], Cbar[j].logq);\n      } else if (Cbar[j].logq > nbhd[j].logq) {\n        scheme.modDownToAndEqual(Cbar[j], nbhd[j].logq);\n      }\n\n      scheme.mult(res[i][j], Cbar[j], nbhd[j]);\n      scheme.reScaleByAndEqual(res[i][j], logp);\n    }\n  }\n}\n\n// res.logq := dusts.logq - max(kdegree + 5, inv_steps + minidx_t + 7) logp\nvoid MeanShift::pointLabelingSIMD(std::vector<Ciphertext> &res,\n                                  Ciphertext &dusts,\n                                  std::vector<Ciphertext> &points, long dim,\n                                  long npoints, long d, long kdegree,\n                                  long inv_steps, long minidx_t) {\n  Ciphertext temp1, temp2, nbhd;\n\n  // Currently dusts are of the form (d1, d1, ..., d1, d2, d2, ..., dd).\n  // We want to now convert it to\n  // (d1, d2, d3, ..., dd, 0, .., 0, d1, d2, d3, ... (repeated d times), dd, 0,\n  // .., 0) so that we can easily compute pairwise kernel on the dusts.\n  std::vector<complex<double>> selector(slots, complex<double>{0, 0});\n  for (long i = 0; i < d; ++i) {\n    std::fill(selector.begin() + i * npoints * dim,\n              selector.begin() + i * npoints * dim + dim,\n              complex<double>{1, 0});\n    scheme.multByConstVec(temp1, dusts, selector.data(), logp);\n    scheme.reScaleByAndEqual(temp1, logp);\n    std::fill(selector.begin() + i * npoints * dim,\n              selector.begin() + i * npoints * dim + dim,\n              complex<double>{0, 0});\n\n    if (i == 0) {\n      temp2.copy(temp1);\n    } else {\n      leftRotateAndEqual(temp1, i * dim * (npoints - 1));\n      scheme.addAndEqual(temp2, temp1);\n    }\n  }\n\n  // `temp2` will now contain the dusts in the required format.\n  repeatSlotRight(temp2, d, npoints * dim);\n\n  // Compute `nbhd` which is the sum of the kernel value of a dust to every\n  // other dust. (Refer paper for details)\n  scheme.modDownBy(temp1, dusts, logp);\n  kernelSIMD(nbhd, temp2, temp1, dim, npoints * d, kdegree);\n  sumSlotsLeft(nbhd, d, dim);\n  clearSlotsRight(nbhd, dim, npoints * dim, d * npoints * dim);\n  repeatSlotRight(nbhd, npoints, dim);\n\n  // Compute labels for each point ciphertext and store result in `res`.\n  res.resize(points.size());\n  for (size_t i = 0; i < points.size(); ++i) {\n    scheme.sub(temp1, dusts, points[i]);\n    l2NormSquaredSIMD(temp2, temp1, dim, npoints * d);\n    minIdxSIMD(temp1, temp2, dim, npoints, minidx_t, inv_steps, d);\n\n    if (nbhd.logq < temp1.logq)\n      scheme.modDownToAndEqual(temp1, nbhd.logq);\n    else if (nbhd.logq > temp1.logq)\n      scheme.modDownToAndEqual(nbhd, temp1.logq);\n\n    scheme.mult(res[i], temp1, nbhd);\n    scheme.reScaleByAndEqual(res[i], logp);\n  }\n}\n\nvoid MeanShift::clusterSIMD(std::vector<Ciphertext> &res,\n                            std::vector<Ciphertext> &points, long dim,\n                            long npoints, long num_dusts, long iterations,\n                            long mode_kdegree, long label_kdegree,\n                            long mode_inv_steps, long label_inv_steps,\n                            long minidx_t) {\n  Ciphertext dusts;\n  modeSeekingSIMD(dusts, points, dim, npoints, num_dusts, iterations,\n                  mode_kdegree, mode_inv_steps);\n\n  // `dusts` has a lower modulus\n  // Check if modulus suffices for point labeling\n  if (dusts.logq < logq_boot)\n    throw std::runtime_error(\n        \"Modulus lower than logl after mode seeking. Cannot bootstrap.\");\n\n  if (dusts.logq <\n      std::max(label_kdegree + 5, label_inv_steps + minidx_t + 7) * logp) {\n    refreshDusts(dusts, dim, npoints, num_dusts);\n    repeatSlotRight(dusts, npoints, dim);\n  }\n\n  if (dusts.logq <\n      std::max(label_kdegree + 5, label_inv_steps + minidx_t + 7) * logp)\n    throw std::runtime_error(\n        \"Modulus not large enough for point labelling after bootstrap.\");\n\n  if (dusts.logq <\n      std::max(label_kdegree + 5, label_inv_steps + minidx_t + 7) * logp)\n    throw std::runtime_error(\n        \"Modulus not large enough for point labelling after bootstrap.\");\n\n  // `pointLabelingSIMD` expects `dusts` and `points` to have same modulus.\n  std::vector<Ciphertext> mod_points(points.size());\n  for (size_t i = 0; i < points.size(); ++i) {\n    scheme.modDownTo(mod_points[i], points[i], dusts.logq);\n  }\n\n  pointLabelingSIMD(res, dusts, mod_points, dim, npoints, num_dusts,\n                    label_kdegree, label_inv_steps, minidx_t);\n}\n", "meta": {"hexsha": "04b402d31e017c5a7df218e2c62c2216f538993f", "size": 19816, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "he_meanshift/src/ckp19/mean_shift.cpp", "max_stars_repo_name": "encryptogroup/SoK_ppClustering", "max_stars_repo_head_hexsha": "6b008a09bfe3f3b8074e24059ac3e2aa6b87f227", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-18T08:09:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T05:41:24.000Z", "max_issues_repo_path": "he_meanshift/src/ckp19/mean_shift.cpp", "max_issues_repo_name": "encryptogroup/SoK_ppClustering", "max_issues_repo_head_hexsha": "6b008a09bfe3f3b8074e24059ac3e2aa6b87f227", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "he_meanshift/src/ckp19/mean_shift.cpp", "max_forks_repo_name": "encryptogroup/SoK_ppClustering", "max_forks_repo_head_hexsha": "6b008a09bfe3f3b8074e24059ac3e2aa6b87f227", "max_forks_repo_licenses": ["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.8585209003, "max_line_length": 81, "alphanum_fraction": 0.6031489705, "num_tokens": 5819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.289844243418859}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https://www.mrpt.org/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2022, Individual contributors, see AUTHORS file     |\n   | See: https://www.mrpt.org/Authors - All rights reserved.               |\n   | Released under BSD License. See: https://www.mrpt.org/License          |\n   +------------------------------------------------------------------------+ */\n\n#include \"poses-precomp.h\"\t// Precompiled headers\n//\n#include <mrpt/poses/CPose3D.h>\n#include <mrpt/poses/CPose3DQuat.h>\n#include <mrpt/serialization/CArchive.h>\n#include <mrpt/serialization/CSchemeArchiveBase.h>\n#include <mrpt/serialization/CSerializable.h>\n\n#include <Eigen/Dense>\n#include <iomanip>\n#include <limits>\n\nusing namespace std;\nusing namespace mrpt;\nusing namespace mrpt::math;\nusing namespace mrpt::poses;\n\nIMPLEMENTS_SERIALIZABLE(CPose3DQuat, CSerializable, mrpt::poses)\n\n/** Constructor from a CPose3D */\nCPose3DQuat::CPose3DQuat(const CPose3D& p)\n{\n\tx() = p.x();\n\ty() = p.y();\n\tz() = p.z();\n\tp.getAsQuaternion(m_quat);\n}\n\n/** Constructor from a 4x4 homogeneous transformation matrix.\n */\nCPose3DQuat::CPose3DQuat(const CMatrixDouble44& M)\n\t: m_quat(UNINITIALIZED_QUATERNION)\n{\n\tm_coords[0] = M(0, 3);\n\tm_coords[1] = M(1, 3);\n\tm_coords[2] = M(2, 3);\n\tCPose3D p(M);\n\tp.getAsQuaternion(m_quat);\n}\n\n/** Returns the corresponding 4x4 homogeneous transformation matrix for the\n * point(translation) or pose (translation+orientation).\n * \\sa getInverseHomogeneousMatrix\n */\nvoid CPose3DQuat::getHomogeneousMatrix(CMatrixDouble44& out_HM) const\n{\n\tm_quat.rotationMatrixNoResize(out_HM);\n\tout_HM(0, 3) = m_coords[0];\n\tout_HM(1, 3) = m_coords[1];\n\tout_HM(2, 3) = m_coords[2];\n\tout_HM(3, 0) = out_HM(3, 1) = out_HM(3, 2) = 0;\n\tout_HM(3, 3) = 1;\n}\n\n/** Returns a 1x7 vector with [x y z qr qx qy qz] */\nvoid CPose3DQuat::asVector(vector_t& v) const\n{\n\tv[0] = m_coords[0];\n\tv[1] = m_coords[1];\n\tv[2] = m_coords[2];\n\tv[3] = m_quat[0];\n\tv[4] = m_quat[1];\n\tv[5] = m_quat[2];\n\tv[6] = m_quat[3];\n}\n\n/**  Makes \"this = A (+) B\"; this method is slightly more efficient than \"this=\n * A + B;\" since it avoids the temporary object.\n *  \\note A or B can be \"this\" without problems.\n */\nvoid CPose3DQuat::composeFrom(const CPose3DQuat& A, const CPose3DQuat& B)\n{\n\t// The 3D point:\n\tdouble gx, gy, gz;\n\tA.m_quat.rotatePoint(\n\t\tB.m_coords[0], B.m_coords[1], B.m_coords[2], gx, gy, gz);\n\tthis->m_coords[0] = A.m_coords[0] + gx;\n\tthis->m_coords[1] = A.m_coords[1] + gy;\n\tthis->m_coords[2] = A.m_coords[2] + gz;\n\n\t// The 3D rotation:\n\tthis->m_quat.crossProduct(A.m_quat, B.m_quat);\n}\n\n/**  Makes \\f$ this = A \\ominus B \\f$ this method is slightly more efficient\n * than \"this= A - B;\" since it avoids the temporary object.\n *  \\note A or B can be \"this\" without problems.\n * \\sa composeFrom\n */\nvoid CPose3DQuat::inverseComposeFrom(const CPose3DQuat& A, const CPose3DQuat& B)\n{\n\t// The 3D point:\n\tconst CQuaternionDouble B_conj(\n\t\tB.m_quat.r(), -B.m_quat.x(), -B.m_quat.y(), -B.m_quat.z());\n\tB_conj.rotatePoint(\n\t\tA.m_coords[0] - B.m_coords[0], A.m_coords[1] - B.m_coords[1],\n\t\tA.m_coords[2] - B.m_coords[2], this->m_coords[0], this->m_coords[1],\n\t\tthis->m_coords[2]);\n\t// The 3D rotation:\n\tthis->m_quat.crossProduct(B_conj, A.m_quat);\n}\n\n/**  Computes the 3D point G such as \\f$ G = this \\oplus L \\f$.\n * \\sa inverseComposeFrom\n */\nvoid CPose3DQuat::composePoint(\n\tconst double lx, const double ly, const double lz, double& gx, double& gy,\n\tdouble& gz, mrpt::math::CMatrixFixed<double, 3, 3>* out_jacobian_df_dpoint,\n\tmrpt::math::CMatrixFixed<double, 3, 7>* out_jacobian_df_dpose) const\n{\n\tif (out_jacobian_df_dpoint || out_jacobian_df_dpose)\n\t{\n\t\tconst double qx2 = square(m_quat.x());\n\t\tconst double qy2 = square(m_quat.y());\n\t\tconst double qz2 = square(m_quat.z());\n\n\t\t// Jacob: df/dpoint\n\t\tif (out_jacobian_df_dpoint)\n\t\t{\n\t\t\t// 3x3:  df_{qr} / da\n\n\t\t\talignas(MRPT_MAX_STATIC_ALIGN_BYTES) const double vals[3 * 3] = {\n\t\t\t\t1 - 2 * (qy2 + qz2),\n\t\t\t\t2 * (m_quat.x() * m_quat.y() - m_quat.r() * m_quat.z()),\n\t\t\t\t2 * (m_quat.r() * m_quat.y() + m_quat.x() * m_quat.z()),\n\n\t\t\t\t2 * (m_quat.r() * m_quat.z() + m_quat.x() * m_quat.y()),\n\t\t\t\t1 - 2 * (qx2 + qz2),\n\t\t\t\t2 * (m_quat.y() * m_quat.z() - m_quat.r() * m_quat.x()),\n\n\t\t\t\t2 * (m_quat.x() * m_quat.z() - m_quat.r() * m_quat.y()),\n\t\t\t\t2 * (m_quat.r() * m_quat.x() + m_quat.y() * m_quat.z()),\n\t\t\t\t1 - 2 * (qx2 + qy2)};\n\t\t\tout_jacobian_df_dpoint->loadFromArray(vals);\n\t\t}\n\n\t\t// Jacob: df/dpose\n\t\tif (out_jacobian_df_dpose)\n\t\t{\n\t\t\t// 3x7:  df_{qr} / dp\n\t\t\talignas(MRPT_MAX_STATIC_ALIGN_BYTES) const double vals1[3 * 7] = {\n\t\t\t\t1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0};\n\t\t\tout_jacobian_df_dpose->loadFromArray(vals1);\n\n\t\t\talignas(MRPT_MAX_STATIC_ALIGN_BYTES) const double vals[3 * 4] = {\n\t\t\t\t2 * (-m_quat.z() * ly + m_quat.y() * lz),\n\t\t\t\t2 * (m_quat.y() * ly + m_quat.z() * lz),\n\t\t\t\t2 * (-2 * m_quat.y() * lx + m_quat.x() * ly + m_quat.r() * lz),\n\t\t\t\t2 * (-2 * m_quat.z() * lx - m_quat.r() * ly + m_quat.x() * lz),\n\n\t\t\t\t2 * (m_quat.z() * lx - m_quat.x() * lz),\n\t\t\t\t2 * (m_quat.y() * lx - 2 * m_quat.x() * ly - m_quat.r() * lz),\n\t\t\t\t2 * (m_quat.x() * lx + m_quat.z() * lz),\n\t\t\t\t2 * (m_quat.r() * lx - 2 * m_quat.z() * ly + m_quat.y() * lz),\n\n\t\t\t\t2 * (-m_quat.y() * lx + m_quat.x() * ly),\n\t\t\t\t2 * (m_quat.z() * lx + m_quat.r() * ly - 2 * m_quat.x() * lz),\n\t\t\t\t2 * (-m_quat.r() * lx + m_quat.z() * ly - 2 * m_quat.y() * lz),\n\t\t\t\t2 * (m_quat.x() * lx + m_quat.y() * ly)};\n\n\t\t\tCMatrixDouble44 norm_jacob(UNINITIALIZED_MATRIX);\n\t\t\tthis->quat().normalizationJacobian(norm_jacob);\n\n\t\t\tout_jacobian_df_dpose->asEigen().block<3, 4>(0, 3) =\n\t\t\t\t(CMatrixFixed<double, 3, 4>(vals) * norm_jacob).eval();\n\t\t}\n\t}\n\n\t// function itself:\n\tm_quat.rotatePoint(lx, ly, lz, gx, gy, gz);\n\tgx += m_coords[0];\n\tgy += m_coords[1];\n\tgz += m_coords[2];\n}\n\n/**  Computes the 3D point G such as \\f$ L = G \\ominus this \\f$.\n * \\sa composeFrom\n */\nvoid CPose3DQuat::inverseComposePoint(\n\tconst double gx, const double gy, const double gz, double& lx, double& ly,\n\tdouble& lz, mrpt::math::CMatrixFixed<double, 3, 3>* out_jacobian_df_dpoint,\n\tmrpt::math::CMatrixFixed<double, 3, 7>* out_jacobian_df_dpose) const\n{\n\tif (out_jacobian_df_dpoint || out_jacobian_df_dpose)\n\t{\n\t\tconst double qx2 = square(m_quat.x());\n\t\tconst double qy2 = square(m_quat.y());\n\t\tconst double qz2 = square(m_quat.z());\n\n\t\t// Jacob: df/dpoint\n\t\tif (out_jacobian_df_dpoint)\n\t\t{\n\t\t\t// 3x3:  df_{m_quat.r()} / da\n\t\t\t//\t\tinv_df_da =\n\t\t\t//\t\t[ - 2*qy^2 - 2*qz^2 + 1,     2*qx*qy - 2*qr*qz,     2*qr*qy\n\t\t\t//+\n\t\t\t// 2*qx*qz]\n\t\t\t//\t\t[     2*qr*qz + 2*qx*qy, - 2*qx^2 - 2*qz^2 + 1,     2*qy*qz\n\t\t\t//-\n\t\t\t// 2*qr*qx]\n\t\t\t//\t\t[     2*qx*qz - 2*qr*qy,     2*qr*qx + 2*qy*qz, - 2*qx^2 -\n\t\t\t// 2*qy^2 + 1]\n\t\t\t//\n\n\t\t\talignas(MRPT_MAX_STATIC_ALIGN_BYTES) const double vals[3 * 3] = {\n\t\t\t\t1 - 2 * (qy2 + qz2),\n\t\t\t\t2 * (m_quat.x() * m_quat.y() + m_quat.r() * m_quat.z()),\n\t\t\t\t2 * (-m_quat.r() * m_quat.y() + m_quat.x() * m_quat.z()),\n\n\t\t\t\t2 * (-m_quat.r() * m_quat.z() + m_quat.x() * m_quat.y()),\n\t\t\t\t1 - 2 * (qx2 + qz2),\n\t\t\t\t2 * (m_quat.y() * m_quat.z() + m_quat.r() * m_quat.x()),\n\n\t\t\t\t2 * (m_quat.x() * m_quat.z() + m_quat.r() * m_quat.y()),\n\t\t\t\t2 * (-m_quat.r() * m_quat.x() + m_quat.y() * m_quat.z()),\n\t\t\t\t1 - 2 * (qx2 + qy2)};\n\t\t\tout_jacobian_df_dpoint->loadFromArray(vals);\n\t\t}\n\n\t\t// Jacob: df/dpose\n\t\tif (out_jacobian_df_dpose)\n\t\t{\n\t\t\t// 3x7:  df_{m_quat.r()} / dp\n\t\t\t//\t\tinv_df_dp =\n\t\t\t//[ 2*qy^2 + 2*qz^2 - 1, - 2*qr*qz - 2*qx*qy,   2*qr*qy - 2*qx*qz,\n\t\t\t// 2*qz*(ay - y) - 2*qy*(az - z),                 2*qy*(ay - y) +\n\t\t\t// 2*qz*(az - z), 2*qx*(ay - y) - 4*qy*(ax - x) - 2*qr*(az - z),\n\t\t\t// 2*qr*(ay - y) - 4*qz*(ax - x) + 2*qx*(az - z)]\n\t\t\t//[   2*qr*qz - 2*qx*qy, 2*qx^2 + 2*qz^2 - 1, - 2*qr*qx - 2*qy*qz,\n\t\t\t// 2*qx*(az - z) - 2*qz*(ax - x), 2*qy*(ax - x) - 4*qx*(ay - y) +\n\t\t\t// 2*qr*(az - z),                 2*qx*(ax - x) + 2*qz*(az - z),\n\t\t\t// 2*qy*(az - z) - 4*qz*(ay - y) - 2*qr*(ax - x)]\n\t\t\t//[ - 2*qr*qy - 2*qx*qz,   2*qr*qx - 2*qy*qz, 2*qx^2 + 2*qy^2 - 1,\n\t\t\t// 2*qy*(ax - x) - 2*qx*(ay - y), 2*qz*(ax - x) - 2*qr*(ay - y) -\n\t\t\t// 4*qx*(az - z), 2*qr*(ax - x) + 2*qz*(ay - y) - 4*qy*(az - z),\n\t\t\t// 2*qx*(ax - x) + 2*qy*(ay - y)]\n\t\t\t//\n\t\t\tconst double qr = m_quat.r();\n\t\t\tconst double qx = m_quat.x();\n\t\t\tconst double qy = m_quat.y();\n\t\t\tconst double qz = m_quat.z();\n\n\t\t\talignas(MRPT_MAX_STATIC_ALIGN_BYTES) const double vals1[3 * 7] = {\n\t\t\t\t2 * qy2 + 2 * qz2 - 1,\n\t\t\t\t-2 * qr * qz - 2 * qx * qy,\n\t\t\t\t2 * qr * qy - 2 * qx * qz,\n\t\t\t\t0,\n\t\t\t\t0,\n\t\t\t\t0,\n\t\t\t\t0,\n\n\t\t\t\t2 * qr * qz - 2 * qx * qy,\n\t\t\t\t2 * qx2 + 2 * qz2 - 1,\n\t\t\t\t-2 * qr * qx - 2 * qy * qz,\n\t\t\t\t0,\n\t\t\t\t0,\n\t\t\t\t0,\n\t\t\t\t0,\n\n\t\t\t\t-2 * qr * qy - 2 * qx * qz,\n\t\t\t\t2 * qr * qx - 2 * qy * qz,\n\t\t\t\t2 * qx2 + 2 * qy2 - 1,\n\t\t\t\t0,\n\t\t\t\t0,\n\t\t\t\t0,\n\t\t\t\t0,\n\t\t\t};\n\n\t\t\tout_jacobian_df_dpose->loadFromArray(vals1);\n\n\t\t\tconst double Ax = 2 * (gx - m_coords[0]);\n\t\t\tconst double Ay = 2 * (gy - m_coords[1]);\n\t\t\tconst double Az = 2 * (gz - m_coords[2]);\n\n\t\t\talignas(MRPT_MAX_STATIC_ALIGN_BYTES) const double vals[3 * 4] = {\n\t\t\t\t-qy * Az + qz * Ay,\n\t\t\t\tqy * Ay + qz * Az,\n\t\t\t\tqx * Ay - 2 * qy * Ax - qr * Az,\n\t\t\t\tqx * Az + qr * Ay - 2 * qz * Ax,\n\n\t\t\t\tqx * Az - qz * Ax,\n\t\t\t\tqy * Ax - 2 * qx * Ay + qr * Az,\n\t\t\t\tqx * Ax + qz * Az,\n\t\t\t\tqy * Az - 2 * qz * Ay - qr * Ax,\n\n\t\t\t\tqy * Ax - qx * Ay,\n\t\t\t\tqz * Ax - qr * Ay - 2 * qx * Az,\n\t\t\t\tqr * Ax + qz * Ay - 2 * qy * Az,\n\t\t\t\tqx * Ax + qy * Ay};\n\n\t\t\tCMatrixDouble44 norm_jacob(UNINITIALIZED_MATRIX);\n\t\t\tthis->quat().normalizationJacobian(norm_jacob);\n\n\t\t\tout_jacobian_df_dpose->insertMatrix(\n\t\t\t\t0, 3, (CMatrixFixed<double, 3, 4>(vals) * norm_jacob).eval());\n\t\t}\n\t}\n\n\t// function itself:\n\tm_quat.inverseRotatePoint(\n\t\tgx - m_coords[0], gy - m_coords[1], gz - m_coords[2], lx, ly, lz);\n}\n\n/*---------------------------------------------------------------\n\t*=\n  ---------------------------------------------------------------*/\nvoid CPose3DQuat::operator*=(const double s)\n{\n\tm_coords[0] *= s;\n\tm_coords[1] *= s;\n\tm_coords[2] *= s;\n\tm_quat[0] *= s;\n\tm_quat[1] *= s;\n\tm_quat[2] *= s;\n\tm_quat[3] *= s;\n}\n\nuint8_t CPose3DQuat::serializeGetVersion() const { return 0; }\nvoid CPose3DQuat::serializeTo(mrpt::serialization::CArchive& out) const\n{\n\tout << m_coords[0] << m_coords[1] << m_coords[2] << m_quat[0] << m_quat[1]\n\t\t<< m_quat[2] << m_quat[3];\n}\nvoid CPose3DQuat::serializeFrom(\n\tmrpt::serialization::CArchive& in, uint8_t version)\n{\n\tswitch (version)\n\t{\n\t\tcase 0:\n\t\t{\n\t\t\tin >> m_coords[0] >> m_coords[1] >> m_coords[2] >> m_quat[0] >>\n\t\t\t\tm_quat[1] >> m_quat[2] >> m_quat[3];\n\t\t}\n\t\tbreak;\n\t\tdefault: MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version);\n\t};\n}\n/** Serialize CSerializable Object to CSchemeArchiveBase derived object*/\nvoid CPose3DQuat::serializeTo(\n\tmrpt::serialization::CSchemeArchiveBase& out) const\n{\n\tSCHEMA_SERIALIZE_DATATYPE_VERSION(1);\n\tCPoint3D point(m_coords[0], m_coords[1], m_coords[2]);\n\tout[\"point\"] = point;\n\tout[\"orientation\"][\"r\"] = m_quat[0];\n\tout[\"orientation\"][\"x\"] = m_quat[1];\n\tout[\"orientation\"][\"y\"] = m_quat[2];\n\tout[\"orientation\"][\"z\"] = m_quat[3];\n}\n/** Serialize CSchemeArchiveBase derived object to CSerializable Object*/\nvoid CPose3DQuat::serializeFrom(mrpt::serialization::CSchemeArchiveBase& in)\n{\n\tuint8_t version;\n\tSCHEMA_DESERIALIZE_DATATYPE_VERSION();\n\tswitch (version)\n\t{\n\t\tcase 1:\n\t\t{\n\t\t\tCPoint3D point;\n\t\t\tin[\"point\"].readTo(point);\n\t\t\tm_coords[0] = point.x();\n\t\t\tm_coords[1] = point.y();\n\t\t\tm_coords[2] = point.z();\n\t\t\tm_quat[0] = static_cast<double>(in[\"orientation\"][\"r\"]);\n\t\t\tm_quat[1] = static_cast<double>(in[\"orientation\"][\"x\"]);\n\t\t\tm_quat[2] = static_cast<double>(in[\"orientation\"][\"y\"]);\n\t\t\tm_quat[3] = static_cast<double>(in[\"orientation\"][\"z\"]);\n\t\t}\n\t\tbreak;\n\t\tdefault: MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version);\n\t}\n}\n/*---------------------------------------------------------------\n\t\tsphericalCoordinates\n---------------------------------------------------------------*/\nvoid CPose3DQuat::sphericalCoordinates(\n\tconst TPoint3D& point, double& out_range, double& out_yaw,\n\tdouble& out_pitch,\n\tmrpt::math::CMatrixFixed<double, 3, 3>* out_jacob_dryp_dpoint,\n\tmrpt::math::CMatrixFixed<double, 3, 7>* out_jacob_dryp_dpose) const\n{\n\tconst bool comp_jacobs =\n\t\tout_jacob_dryp_dpoint != nullptr || out_jacob_dryp_dpose != nullptr;\n\n\t// Pass to coordinates as seen from this 6D pose:\n\tCMatrixFixed<double, 3, 3> jacob_dinv_dpoint,\n\t\t*ptr_ja1 = comp_jacobs ? &jacob_dinv_dpoint : nullptr;\n\tCMatrixFixed<double, 3, 7> jacob_dinv_dpose,\n\t\t*ptr_ja2 = comp_jacobs ? &jacob_dinv_dpose : nullptr;\n\n\tTPoint3D local;\n\tthis->inverseComposePoint(\n\t\tpoint.x, point.y, point.z, local.x, local.y, local.z, ptr_ja1, ptr_ja2);\n\n\t// Range:\n\tout_range = local.norm();\n\n\t// Yaw:\n\tif (local.y != 0 || local.x != 0) out_yaw = atan2(local.y, local.x);\n\telse\n\t\tout_yaw = 0;\n\n\t// Pitch:\n\tif (out_range != 0) out_pitch = -asin(local.z / out_range);\n\telse\n\t\tout_pitch = 0;\n\n\t// Jacobians are:\n\t//  dryp_dpoint = dryp_dlocalpoint  * dinv_dpoint\n\t//  dryp_dpose  = dryp_dlocalpoint  * dinv_dpose\n\tif (comp_jacobs)\n\t{\n\t\tif (out_range == 0)\n\t\t\tTHROW_EXCEPTION(\"Jacobians are undefined for range=0\");\n\n\t\t/* MATLAB:\n\t\t\tsyms H h_range h_yaw h_pitch real;\n\t\t\tsyms xi_ yi_ zi_ real;\n\t\t\th_range = sqrt(xi_^2+yi_^2+zi_^2);\n\t\t\th_yaw   = atan(yi_/xi_);\n\t\t\t% h_pitch = -asin(zi_/ sqrt( xi_^2 + yi_^2 + zi_^2 ) );\n\t\t\th_pitch = -atan(zi_, sqrt( xi_^2 + yi_^2) );\n\t\t\tH=[ h_range ; h_yaw ; h_pitch ];\n\t\t\tjacob_fesf_xyz=jacobian(H,[xi_ yi_ zi_])\n\t\t*/\n\t\tconst double _r = 1.0 / out_range;\n\t\tconst double x2 = square(local.x);\n\t\tconst double y2 = square(local.y);\n\n\t\tconst double t2 = std::sqrt(x2 + y2);\n\t\tconst double _K = 1.0 / (t2 * square(out_range));\n\n\t\tdouble vals[3 * 3] = {\n\t\t\tlocal.x * _r,\n\t\t\tlocal.y * _r,\n\t\t\tlocal.z * _r,\n\t\t\t-local.y / (x2 * (y2 / x2 + 1)),\n\t\t\t1.0 / (local.x * (y2 / x2 + 1)),\n\t\t\t0,\n\t\t\t(local.x * local.z) * _K,\n\t\t\t(local.y * local.z) * _K,\n\t\t\t-t2 / square(out_range)};\n\n\t\tconst CMatrixDouble33 dryp_dlocalpoint(vals);\n\t\tif (out_jacob_dryp_dpoint)\n\t\t\t*out_jacob_dryp_dpoint = dryp_dlocalpoint * jacob_dinv_dpoint;\n\t\tif (out_jacob_dryp_dpose)\n\t\t\t*out_jacob_dryp_dpose = dryp_dlocalpoint * jacob_dinv_dpose;\n\t}\n}\n\n/**  Textual output stream function.\n */\nstd::ostream& mrpt::poses::operator<<(std::ostream& o, const CPose3DQuat& p)\n{\n\tconst std::streamsize old_pre = o.precision();\n\tconst ios_base::fmtflags old_flags = o.flags();\n\to << \"(x,y,z,qr,qx,qy,qz)=(\" << std::fixed << std::setprecision(4)\n\t  << p.m_coords[0] << \",\" << p.m_coords[1] << \",\" << p.m_coords[2] << \",\"\n\t  << p.quat()[0] << \",\" << p.quat()[1] << \",\" << p.quat()[2] << \",\"\n\t  << p.quat()[3] << \")\";\n\to.flags(old_flags);\n\to.precision(old_pre);\n\treturn o;\n}\n\n/** Unary - operator: return the inverse pose \"-p\" (Note that is NOT the same\n * than a pose with all its arguments multiplied by \"-1\") */\nCPose3DQuat mrpt::poses::operator-(const CPose3DQuat& p)\n{\n\tCPose3DQuat ret = p;\n\tret.inverse();\n\treturn ret;\n}\n\n/** Convert this pose into its inverse, saving the result in itself. \\sa\n * operator- */\nvoid CPose3DQuat::inverse()\n{\n\t// Invert translation:\n\tthis->inverseComposePoint(0, 0, 0, m_coords[0], m_coords[1], m_coords[2]);\n\n\t// Invert rotation: [qr qx qy qz] ==> [qr -qx -qy -qz]\n\tm_quat[1] = -m_quat[1];\n\tm_quat[2] = -m_quat[2];\n\tm_quat[3] = -m_quat[3];\n}\n\nvoid CPose3DQuat::setToNaN()\n{\n\tfor (int i = 0; i < 3; i++)\n\t\tm_coords[i] = std::numeric_limits<double>::quiet_NaN();\n\n\tfor (int i = 0; i < 4; i++)\n\t\tquat()[i] = std::numeric_limits<double>::quiet_NaN();\n}\n\nbool mrpt::poses::operator==(const CPose3DQuat& p1, const CPose3DQuat& p2)\n{\n\treturn p1.quat() == p2.quat() && p1.x() == p2.x() && p1.y() == p2.y() &&\n\t\tp1.z() == p2.z();\n}\n\nbool mrpt::poses::operator!=(const CPose3DQuat& p1, const CPose3DQuat& p2)\n{\n\treturn !(p1 == p2);\n}\n\nCPoint3D mrpt::poses::operator-(const CPoint3D& G, const CPose3DQuat& p)\n{\n\tCPoint3D L;\n\tp.inverseComposePoint(G[0], G[1], G[2], L[0], L[1], L[2]);\n\treturn L;\n}\n\nTPoint3D mrpt::poses::operator-(const TPoint3D& G, const CPose3DQuat& p)\n{\n\tmrpt::math::TPoint3D L;\n\tp.inverseComposePoint(G[0], G[1], G[2], L[0], L[1], L[2]);\n\treturn L;\n}\n\nTPose3DQuat CPose3DQuat::asTPose() const\n{\n\treturn TPose3DQuat(\n\t\tx(), y(), z(), m_quat.r(), m_quat.x(), m_quat.y(), m_quat.z());\n}\n\nvoid CPose3DQuat::fromString(const std::string& s)\n{\n\tmrpt::math::CMatrixDouble m;\n\tif (!m.fromMatlabStringFormat(s))\n\t\tTHROW_EXCEPTION_FMT(\n\t\t\t\"Malformed expression in ::fromString, s=\\\"%s\\\"\", s.c_str());\n\tASSERTMSG_(m.rows() == 1 && m.cols() == 7, \"Expected vector length=7\");\n\tm_coords[0] = m(0, 0);\n\tm_coords[1] = m(0, 1);\n\tm_coords[2] = m(0, 2);\n\tm_quat[0] = m(0, 3);\n\tm_quat[1] = m(0, 4);\n\tm_quat[2] = m(0, 5);\n\tm_quat[3] = m(0, 6);\n}\n\nvoid CPose3DQuat::fromStringRaw(const std::string& s)\n{\n\tthis->fromString(\"[\" + s + \"]\");\n}\n", "meta": {"hexsha": "f6a52a01db9f214cb1b2d61d6dfc78373a26fc93", "size": 16863, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/poses/src/CPose3DQuat.cpp", "max_stars_repo_name": "wstnturner/mrpt", "max_stars_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T05:24:26.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-17T00:30:02.000Z", "max_issues_repo_path": "libs/poses/src/CPose3DQuat.cpp", "max_issues_repo_name": "wstnturner/mrpt", "max_issues_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2015-01-03T22:43:00.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-17T18:52:59.000Z", "max_forks_repo_path": "libs/poses/src/CPose3DQuat.cpp", "max_forks_repo_name": "wstnturner/mrpt", "max_forks_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T12:32:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-30T15:50:13.000Z", "avg_line_length": 30.2204301075, "max_line_length": 80, "alphanum_fraction": 0.5807981972, "num_tokens": 6440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2896410905224101}}
{"text": "#ifndef _CELERITE2_INTERNAL_HPP_DEFINED_\n#define _CELERITE2_INTERNAL_HPP_DEFINED_\n\n#include <Eigen/Core>\n\nnamespace celerite2 {\nnamespace core {\n\n#define UNUSED(x) (void)(x)\n\n#define CAST_BASE(TYPE, VAR) Eigen::MatrixBase<TYPE> &VAR = const_cast<Eigen::MatrixBase<TYPE> &>(VAR##_out)\n\n#define CAST_VEC(TYPE, VAR, ROWS)                                                                                                                    \\\n  CAST_BASE(TYPE, VAR);                                                                                                                              \\\n  VAR.derived().resize(ROWS)\n\n#define CAST_MAT(TYPE, VAR, ROWS, COLS)                                                                                                              \\\n  CAST_BASE(TYPE, VAR);                                                                                                                              \\\n  VAR.derived().resize(ROWS, COLS)\n\nconst int THE_WORKSPACE_VARIABLE_MUST_BE_ROW_MAJOR = 0;\n#define ASSERT_ROW_MAJOR(TYPE) EIGEN_STATIC_ASSERT((TYPE::ColsAtCompileTime == 1) || TYPE::IsRowMajor, THE_WORKSPACE_VARIABLE_MUST_BE_ROW_MAJOR)\n\nnamespace internal {\n\ntemplate <bool do_update = true>\nstruct update_workspace {\n  template <typename A, typename B>\n  static void apply(Eigen::Index n, const Eigen::MatrixBase<A> &a, Eigen::MatrixBase<B> const &b_out) {\n    CAST_BASE(B, b);\n    b.row(n) = a;\n  }\n};\n\ntemplate <>\nstruct update_workspace<false> {\n  template <typename A, typename B>\n  static void apply(Eigen::Index n, const Eigen::MatrixBase<A> &a, Eigen::MatrixBase<B> const &b_out) {\n    UNUSED(n);\n    UNUSED(a);\n    UNUSED(b_out);\n  }\n};\n\ntemplate <bool is_solve = false>\nstruct update_f {\n  template <typename A, typename B, typename C, typename D>\n  static void apply(const Eigen::MatrixBase<A> &a, const Eigen::MatrixBase<B> &b, const Eigen::MatrixBase<C> &c, Eigen::MatrixBase<D> const &d_out) {\n    CAST_BASE(D, d);\n    d.noalias() += a * b;\n    UNUSED(c);\n  }\n\n  template <typename A, typename B, typename C, typename D, typename E, typename F, typename G>\n  static void reverse(const Eigen::MatrixBase<A> &a, const Eigen::MatrixBase<B> &b, const Eigen::MatrixBase<C> &c, const Eigen::MatrixBase<D> &d,\n                      Eigen::MatrixBase<E> const &e_out, Eigen::MatrixBase<F> const &f_out, Eigen::MatrixBase<G> const &g_out) {\n    CAST_BASE(E, e);\n    CAST_BASE(F, f);\n    e.noalias() += b * d.transpose();\n    f.noalias() += a * d;\n    UNUSED(c);\n    UNUSED(g_out);\n  }\n};\n\ntemplate <>\nstruct update_f<true> {\n  template <typename A, typename B, typename C, typename D>\n  static void apply(const Eigen::MatrixBase<A> &a, const Eigen::MatrixBase<B> &b, const Eigen::MatrixBase<C> &c, Eigen::MatrixBase<D> const &d_out) {\n    CAST_BASE(D, d);\n    d.noalias() += a * c;\n    UNUSED(b);\n  }\n\n  template <typename A, typename B, typename C, typename D, typename E, typename F, typename G>\n  static void reverse(const Eigen::MatrixBase<A> &a, const Eigen::MatrixBase<B> &b, const Eigen::MatrixBase<C> &c, const Eigen::MatrixBase<D> &d,\n                      Eigen::MatrixBase<E> const &e_out, Eigen::MatrixBase<F> const &f_out, Eigen::MatrixBase<G> const &g_out) {\n    CAST_BASE(E, e);\n    CAST_BASE(G, g);\n    e.noalias() += c * d.transpose();\n    g.noalias() += a * d;\n    UNUSED(b);\n    UNUSED(f_out);\n  }\n};\n\ntemplate <bool is_solve = false>\nstruct update_z {\n  template <typename A, typename B>\n  static void apply(const Eigen::MatrixBase<A> &a, Eigen::MatrixBase<B> const &b_out) {\n    CAST_BASE(B, b);\n    b.noalias() += a;\n  }\n};\n\ntemplate <>\nstruct update_z<true> {\n  template <typename A, typename B>\n  static void apply(const Eigen::MatrixBase<A> &a, Eigen::MatrixBase<B> const &b_out) {\n    CAST_BASE(B, b);\n    b.noalias() -= a;\n  }\n};\n\ntemplate <bool is_solve, bool do_update = true, typename Input, typename Coeffs, typename LowRank, typename RightHandSide, typename RightHandSideOut,\n          typename Work>\nvoid forward(const Eigen::MatrixBase<Input> &t,                // (N,)\n             const Eigen::MatrixBase<Coeffs> &c,               // (J,)\n             const Eigen::MatrixBase<LowRank> &U,              // (N, J)\n             const Eigen::MatrixBase<LowRank> &V,              // (N, J)\n             const Eigen::MatrixBase<RightHandSide> &Y,        // (N, Nrhs)\n             Eigen::MatrixBase<RightHandSideOut> const &Z_out, // (N, Nrhs)\n             Eigen::MatrixBase<Work> const &F_out              // (N, J * Nrhs)\n) {\n  ASSERT_ROW_MAJOR(Work);\n\n  typedef typename LowRank::Scalar Scalar;\n  typedef typename Eigen::internal::plain_row_type<RightHandSide>::type RowVector;\n  typedef typename Eigen::internal::plain_col_type<Coeffs>::type CoeffVector;\n  typedef typename Eigen::Matrix<Scalar, LowRank::ColsAtCompileTime, RightHandSide::ColsAtCompileTime> Inner;\n\n  Eigen::Index N = U.rows(), J = U.cols(), nrhs = Y.cols();\n  CAST_BASE(RightHandSideOut, Z); // Must already be the right shape\n  CAST_BASE(Work, F);\n  if (do_update) {\n    F.derived().resize(N, J * nrhs);\n    F.row(0).setZero();\n  }\n\n  CoeffVector p(J);\n  Inner Fn(J, nrhs);\n  Eigen::Map<typename Eigen::internal::plain_row_type<Work>::type> ptr(Fn.data(), 1, J * nrhs);\n\n  // This will track the previous row allowing for inplace operations\n  RowVector tmp = Y.row(0);\n\n  Fn.setZero();\n  for (Eigen::Index n = 1; n < N; ++n) {\n    p = exp(c.array() * (t(n - 1) - t(n)));\n    update_f<is_solve>::apply(V.row(n - 1).transpose(), tmp, Z.row(n - 1), Fn);\n    tmp = Y.row(n);\n    update_workspace<do_update>::apply(n, ptr, F);\n    Fn = p.asDiagonal() * Fn;\n    update_z<is_solve>::apply(U.row(n) * Fn, Z.row(n));\n  }\n}\n\ntemplate <bool is_solve, bool do_update = true, typename Input, typename Coeffs, typename LowRank, typename RightHandSide, typename RightHandSideOut,\n          typename Work>\nvoid backward(const Eigen::MatrixBase<Input> &t,                // (N,)\n              const Eigen::MatrixBase<Coeffs> &c,               // (J,)\n              const Eigen::MatrixBase<LowRank> &U,              // (N, J)\n              const Eigen::MatrixBase<LowRank> &V,              // (N, J)\n              const Eigen::MatrixBase<RightHandSide> &Y,        // (N, Nrhs)\n              Eigen::MatrixBase<RightHandSideOut> const &Z_out, // (N, Nrhs)\n              Eigen::MatrixBase<Work> const &F_out              // (N, J * Nrhs)\n) {\n  ASSERT_ROW_MAJOR(Work);\n\n  typedef typename LowRank::Scalar Scalar;\n  typedef typename Eigen::internal::plain_row_type<RightHandSide>::type RowVector;\n  typedef typename Eigen::internal::plain_col_type<Coeffs>::type CoeffVector;\n  typedef typename Eigen::Matrix<Scalar, LowRank::ColsAtCompileTime, RightHandSide::ColsAtCompileTime> Inner;\n\n  Eigen::Index N = U.rows(), J = U.cols(), nrhs = Y.cols();\n  CAST_BASE(RightHandSideOut, Z); // Must already be the right shape\n  CAST_BASE(Work, F);\n  if (do_update) {\n    F.derived().resize(N, J * nrhs);\n    F.row(N - 1).setZero();\n  }\n\n  CoeffVector p(J);\n  Inner Fn(J, nrhs);\n  Eigen::Map<typename Eigen::internal::plain_row_type<Work>::type> ptr(Fn.data(), 1, J * nrhs);\n\n  // This will track the previous row allowing for inplace operations\n  RowVector tmp = Y.row(N - 1);\n\n  Fn.setZero();\n  for (Eigen::Index n = N - 2; n >= 0; --n) {\n    p = exp(c.array() * (t(n) - t(n + 1)));\n    update_f<is_solve>::apply(U.row(n + 1).transpose(), tmp, Z.row(n + 1), Fn);\n    tmp = Y.row(n);\n    update_workspace<do_update>::apply(n, ptr, F);\n    Fn = p.asDiagonal() * Fn;\n    update_z<is_solve>::apply(V.row(n) * Fn, Z.row(n));\n  }\n}\n\ntemplate <bool is_solve, typename Input, typename Coeffs, typename LowRank, typename RightHandSide, typename RightHandSideOptional, typename Work,\n          typename RightHandSideInternal, typename InputOut, typename CoeffsOut, typename LowRankOut, typename RightHandSideOut>\nvoid forward_rev(const Eigen::MatrixBase<Input> &t,                      // (N,)\n                 const Eigen::MatrixBase<Coeffs> &c,                     // (J,)\n                 const Eigen::MatrixBase<LowRank> &U,                    // (N, J)\n                 const Eigen::MatrixBase<LowRank> &V,                    // (N, J)\n                 const Eigen::MatrixBase<RightHandSideOptional> &Y,      // (N, Nrhs)\n                 const Eigen::MatrixBase<RightHandSide> &Z,              // (N, Nrhs)\n                 const Eigen::MatrixBase<Work> &F,                       // (N, J * Nrhs)\n                 Eigen::MatrixBase<RightHandSideInternal> const &bZ_out, // (N, Nrhs)\n                 Eigen::MatrixBase<InputOut> const &bt_out,              // (N,)\n                 Eigen::MatrixBase<CoeffsOut> const &bc_out,             // (J,)\n                 Eigen::MatrixBase<LowRankOut> const &bU_out,            // (N, J)\n                 Eigen::MatrixBase<LowRankOut> const &bV_out,            // (N, J)\n                 Eigen::MatrixBase<RightHandSideOut> const &bY_out       // (N, Nrhs)  -  Must be the right shape already (and zeroed)\n) {\n  ASSERT_ROW_MAJOR(Work);\n\n  typedef typename LowRank::Scalar Scalar;\n  typedef typename Eigen::internal::plain_col_type<Coeffs>::type CoeffVector;\n  typedef typename Eigen::Matrix<Scalar, LowRank::ColsAtCompileTime, RightHandSide::ColsAtCompileTime> Inner;\n\n  Eigen::Index N = U.rows(), J = U.cols(), nrhs = Y.cols();\n  CAST_VEC(InputOut, bt, N);\n  CAST_VEC(CoeffsOut, bc, J);\n  CAST_MAT(LowRankOut, bU, N, J);\n  CAST_MAT(LowRankOut, bV, N, J);\n  CAST_BASE(RightHandSideOut, bY);\n  CAST_BASE(RightHandSideInternal, bZ);\n\n  Scalar dt, factor;\n  CoeffVector p(J), bp(J);\n  Inner Fn(J, nrhs), bF(J, nrhs);\n  Eigen::Map<typename Eigen::internal::plain_row_type<Work>::type> ptr(Fn.data(), 1, J * nrhs);\n  bF.setZero();\n  for (Eigen::Index n = N - 1; n >= 1; --n) {\n    dt  = t(n - 1) - t(n);\n    p   = exp(c.array() * dt);\n    ptr = F.row(n);\n\n    // Reverse: update_z<is_solve>::apply(U.row(n) * Fn, Z.row(n));\n    update_z<is_solve>::apply(bZ.row(n) * (p.asDiagonal() * Fn).transpose(), bU.row(n));\n    update_z<is_solve>::apply(U.row(n).transpose() * bZ.row(n), bF);\n\n    // Reverse: Fn = P.row(n - 1).asDiagonal() * Fn;\n    bp.array() = (Fn * bF.transpose()).diagonal().array() * p.array();\n    bc.noalias() += dt * bp;\n    factor = (c.array() * bp.array()).sum();\n    bt(n) -= factor;\n    bt(n - 1) += factor;\n    bF = p.asDiagonal() * bF;\n\n    // Reverse: update_f<is_solve>::apply(V.row(n - 1).transpose(), Y.row(n - 1), Z.row(n - 1), Fn);\n    update_f<is_solve>::reverse(V.row(n - 1), Y.row(n - 1), Z.row(n - 1), bF, bV.row(n - 1), bY.row(n - 1), bZ.row(n - 1));\n  }\n}\n\ntemplate <bool is_solve, typename Input, typename Coeffs, typename LowRank, typename RightHandSide, typename Work, typename RightHandSideInternal,\n          typename InputOut, typename CoeffsOut, typename LowRankOut, typename RightHandSideOut>\nvoid backward_rev(const Eigen::MatrixBase<Input> &t,                      // (N,)\n                  const Eigen::MatrixBase<Coeffs> &c,                     // (J,)\n                  const Eigen::MatrixBase<LowRank> &U,                    // (N, J)\n                  const Eigen::MatrixBase<LowRank> &V,                    // (N, J)\n                  const Eigen::MatrixBase<RightHandSide> &Y,              // (N, Nrhs)\n                  const Eigen::MatrixBase<RightHandSide> &Z,              // (N, Nrhs)\n                  const Eigen::MatrixBase<Work> &F,                       // (N, J * Nrhs)\n                  Eigen::MatrixBase<RightHandSideInternal> const &bZ_out, // (N, Nrhs)\n                  Eigen::MatrixBase<InputOut> const &bt_out,              // (N,)\n                  Eigen::MatrixBase<CoeffsOut> const &bc_out,             // (J,)\n                  Eigen::MatrixBase<LowRankOut> const &bU_out,            // (N, J)\n                  Eigen::MatrixBase<LowRankOut> const &bV_out,            // (N, J)\n                  Eigen::MatrixBase<RightHandSideOut> const &bY_out       // (N, Nrhs)  -  Must be the right shape already (and zeroed)\n) {\n  ASSERT_ROW_MAJOR(Work);\n\n  typedef typename LowRank::Scalar Scalar;\n  typedef typename Eigen::internal::plain_col_type<Coeffs>::type CoeffVector;\n  typedef typename Eigen::Matrix<Scalar, LowRank::ColsAtCompileTime, RightHandSide::ColsAtCompileTime> Inner;\n\n  Eigen::Index N = U.rows(), J = U.cols(), nrhs = Y.cols();\n  CAST_VEC(InputOut, bt, N);\n  CAST_VEC(CoeffsOut, bc, J);\n  CAST_MAT(LowRankOut, bU, N, J);\n  CAST_MAT(LowRankOut, bV, N, J);\n  CAST_BASE(RightHandSideOut, bY);\n  CAST_BASE(RightHandSideInternal, bZ);\n\n  Scalar dt, factor;\n  CoeffVector p(J), bp(J);\n  Inner Fn(J, nrhs), bF(J, nrhs);\n  Eigen::Map<typename Eigen::internal::plain_row_type<Work>::type> ptr(Fn.data(), 1, J * nrhs);\n  bF.setZero();\n  for (Eigen::Index n = 0; n <= N - 2; ++n) {\n    dt  = t(n) - t(n + 1);\n    p   = exp(c.array() * dt);\n    ptr = F.row(n);\n\n    // Reverse: update_z<is_solve>::apply(V.row(n) * Fn, Z.row(n));\n    update_z<is_solve>::apply(bZ.row(n) * (p.asDiagonal() * Fn).transpose(), bV.row(n));\n    update_z<is_solve>::apply(V.row(n).transpose() * bZ.row(n), bF);\n\n    // Reverse: Fn = P.row(n).asDiagonal() * Fn;\n    bp.array() = (Fn * bF.transpose()).diagonal().array() * p.array();\n    bc.noalias() += dt * bp;\n    factor = (c.array() * bp.array()).sum();\n    bt(n + 1) -= factor;\n    bt(n) += factor;\n    bF = p.asDiagonal() * bF;\n\n    // Reverse: update_f<is_solve>::apply(U.row(n + 1).transpose(), Y.row(n + 1), Z.row(n + 1), Fn);\n    update_f<is_solve>::reverse(U.row(n + 1), Y.row(n + 1), Z.row(n + 1), bF, bU.row(n + 1), bY.row(n + 1), bZ.row(n + 1));\n  }\n}\n\n} // namespace internal\n\n} // namespace core\n} // namespace celerite2\n\n#endif // _CELERITE2_INTERNAL_HPP_DEFINED_\n", "meta": {"hexsha": "efdd2b76efe39c394983e94507f0147606d44310", "size": 13600, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "c++/include/celerite2/internal.hpp", "max_stars_repo_name": "jacksonloper/celerite2", "max_stars_repo_head_hexsha": "e413e28dc43ba33e67960b51a9cbbac43c2f58df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2020-10-10T02:43:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:59:21.000Z", "max_issues_repo_path": "c++/include/celerite2/internal.hpp", "max_issues_repo_name": "jacksonloper/celerite2", "max_issues_repo_head_hexsha": "e413e28dc43ba33e67960b51a9cbbac43c2f58df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34.0, "max_issues_repo_issues_event_min_datetime": "2020-10-06T18:50:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T10:33:04.000Z", "max_forks_repo_path": "c++/include/celerite2/internal.hpp", "max_forks_repo_name": "jacksonloper/celerite2", "max_forks_repo_head_hexsha": "e413e28dc43ba33e67960b51a9cbbac43c2f58df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-11-09T18:12:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T20:20:59.000Z", "avg_line_length": 43.729903537, "max_line_length": 150, "alphanum_fraction": 0.5845588235, "num_tokens": 3837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2896410905224101}}
{"text": "/*\n * Copyright (C) 2017 Martin Lambers <marlam@marlam.de>\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 \"webcam-head-tracker.hpp\"\n\n#include <chrono>\n#include <cstdlib>\n#include <cstdio>\n#include <cmath>\n\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/objdetect/objdetect.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/video/tracking.hpp>\n\n#include <dlib/opencv.h>\n#include <dlib/image_processing.h>\n\n/* Helpers for timing */\n\nclass timer\n{\npublic:\n    std::chrono::steady_clock::time_point t;\n    void setNow() { t = std::chrono::steady_clock::now(); }\n};\n\nfloat duration(const timer& start, const timer& end)\n{\n    std::chrono::duration<long long, std::micro> time_span\n        = std::chrono::duration_cast<std::chrono::duration<long long, std::micro>>(end.t - start.t);\n    return time_span.count() / 1e3f;\n}\n\n/* Double Exponential Smoothing\n * This implements double exponential smoothing-based prediction\n * as described in Sec. 2 of \"Double Exponential Smoothing: An alternative to\n * Kalman Filter-Based Predictive Tracking\" by Joseph J. LaViola Jr.\n */\n\nclass DoubleExponentialSmoothing\n{\nprivate:\n    bool _isInitialized;\n    double _lastVecS[3], _lastVecS2[3];\n    double _lastQuatS[4], _lastQuatS2[4];\n\n    inline void copy3(double* result, const double* value)\n    {\n        result[0] = value[0];\n        result[1] = value[1];\n        result[2] = value[2];\n    }\n\n    inline void copy4(double* result, const double* value)\n    {\n        result[0] = value[0];\n        result[1] = value[1];\n        result[2] = value[2];\n        result[3] = value[3];\n    }\n\n    inline double mix(double alpha, double x, double y)\n    {\n        return alpha * y + (1.0 - alpha) * x;\n    }\n\n    inline void mix3(double* result, double alpha, const double* v, const double* w)\n    {\n        result[0] = mix(alpha, v[0], w[0]);\n        result[1] = mix(alpha, v[1], w[1]);\n        result[2] = mix(alpha, v[2], w[2]);\n    }\n\n    inline void mix4(double* result, double alpha, const double* v, const double* w)\n    {\n        result[0] = mix(alpha, v[0], w[0]);\n        result[1] = mix(alpha, v[1], w[1]);\n        result[2] = mix(alpha, v[2], w[2]);\n        result[3] = mix(alpha, v[3], w[3]);\n    }\n\n    inline double dot4(const double* v, const double* w)\n    {\n        return (v[0] * w[0] + v[1] * w[1] + v[2] * w[2] + v[3] * w[3]);\n    }\n\n    inline void normalize4(double* v)\n    {\n        double s = std::sqrt(dot4(v, v));\n        v[0] /= s;\n        v[1] /= s;\n        v[2] /= s;\n        v[3] /= s;\n    }\n\n    inline void slerp(double* result, double alpha, const double* q, const double* r)\n    {\n        double w[4] = { r[0], r[1], r[2], r[3] };\n        double cosHalfAngle = dot4(q, r);\n        if (cosHalfAngle < 0.0) {\n            // quat(x, y, z, w) and quat(-x, -y, -z, -w) represent the same rotation\n            w[0] = -w[0]; w[1] = -w[1]; w[2] = -w[2]; w[3] = -w[3];\n            cosHalfAngle = -cosHalfAngle;\n        }\n        double tmpQ, tmpW;\n        if (std::fabs(cosHalfAngle) >= 1.0) {\n            // angle is zero => rotations are identical\n            tmpQ = 1.0;\n            tmpW = 0.0;\n        } else {\n            double halfAngle = acos(cosHalfAngle);\n            double sinHalfAngle = sqrt(1.0 - cosHalfAngle * cosHalfAngle);\n            if (std::fabs(sinHalfAngle) < 0.001) {\n                // angle is 180 degrees => result is not clear\n                tmpQ = 0.5;\n                tmpW = 0.5;\n            } else {\n                tmpQ = std::sin((1.0 - alpha) * halfAngle) / sinHalfAngle;\n                tmpW = sin(alpha * halfAngle) / sinHalfAngle;\n            }\n        }\n        result[0] = q[0] * tmpQ + w[0] * tmpW;\n        result[1] = q[1] * tmpQ + w[1] * tmpW;\n        result[2] = q[2] * tmpQ + w[2] * tmpW;\n        result[3] = q[3] * tmpQ + w[3] * tmpW;\n    }\n\npublic:\n    DoubleExponentialSmoothing() : _isInitialized(false) {}\n\n    void step(const double* vec, const double* quat,\n            double alpha, double tau, double* estimatedVec, double* estimatedQuat)\n    {\n        if (!_isInitialized) {\n            copy3(_lastVecS, vec);\n            copy3(_lastVecS2, vec);\n            copy4(_lastQuatS, quat);\n            copy4(_lastQuatS2, quat);\n            _isInitialized = true;\n        }\n        double vecS[3], vecS2[3], quatS[4], quatS2[4];\n        // Eq. (1), (2)\n        mix3(vecS, alpha, _lastVecS, vec);\n        mix3(vecS2, alpha, _lastVecS2, vecS);\n        mix4(quatS, alpha, _lastQuatS, quat);\n        mix4(quatS2, alpha, _lastQuatS2, quatS);\n        copy3(_lastVecS, vecS);\n        copy3(_lastVecS2, vecS2);\n        copy4(_lastQuatS, quatS);\n        copy4(_lastQuatS2, quatS2);\n        // Eq. (6) for floor(tau) and ceil(tau)\n        double floorTau = std::floor(tau);\n        double betaFloorTau = 2.0 + alpha * floorTau / (1.0 - alpha);\n        double estimatedVecFloorTau[3], estimatedQuatFloorTau[4];\n        mix3(estimatedVecFloorTau, betaFloorTau, vecS2, vecS);\n        mix4(estimatedQuatFloorTau, betaFloorTau, quatS2, quatS);\n        normalize4(estimatedQuatFloorTau);\n        double ceilTau = std::ceil(tau);\n        double betaCeilTau = 2.0 + alpha * ceilTau / (1.0 - alpha);\n        double estimatedVecCeilTau[3], estimatedQuatCeilTau[4];\n        mix3(estimatedVecCeilTau, betaCeilTau, vecS2, vecS);\n        mix4(estimatedQuatCeilTau, betaCeilTau, quatS2, quatS);\n        normalize4(estimatedQuatCeilTau);\n        // mix results for floor(tau) and ceil(tau)\n        mix3(estimatedVec, tau - floorTau, estimatedVecCeilTau, estimatedVecFloorTau);\n        slerp(estimatedQuat, tau - floorTau, estimatedQuatCeilTau, estimatedQuatFloorTau);\n    }\n};\n\n/* WebcamHeadTracker */\n\nWebcamHeadTracker::WebcamHeadTracker(unsigned int debugOptions) :\n    _debugOptions(debugOptions),\n    _isReady(false),\n    _capture(NULL),\n    _frame(NULL),\n    _w(0), _h(0),\n    _fps(0.0f),\n    _fx(0.0f), _fy(0.0f),\n    _cx(0.0f), _cy(0.0f),\n    _k1(0.0f), _k2(0.0f), _p1(0.0f), _p2(0.0f), _k3(0.0f),\n    _faceCascade(NULL),\n    _faceModel(NULL),\n    _filter(Filter_Double_Exponential),\n    _kalmanFilter(NULL),\n    _despFilter(NULL),\n    _headPosition { 0.0f, 0.0f, 0.5f },\n    _headOrientation { 0.0f, 0.0f, 0.0f, 0.0f }\n{\n}\n\nWebcamHeadTracker::~WebcamHeadTracker()\n{\n    delete _capture;\n    delete _frame;\n    delete _faceCascade;\n    delete _faceModel;\n    delete _kalmanFilter;\n    delete _despFilter;\n}\n\nbool WebcamHeadTracker::initWebcam()\n{\n    if (_capture)\n        return isReady();\n    _capture = new cv::VideoCapture(0);\n    if (_capture && _capture->isOpened()) {\n        _capture->set(cv::CAP_PROP_FRAME_WIDTH, 640);\n        _capture->set(cv::CAP_PROP_FRAME_HEIGHT, 480);\n        _frame = new cv::Mat;\n        _w = _capture->get(cv::CAP_PROP_FRAME_WIDTH);\n        _h = _capture->get(cv::CAP_PROP_FRAME_HEIGHT);\n        _fps = _capture->get(cv::CAP_PROP_FPS);\n        if (_fps <= 0.0f)\n            _fps = 30.0f;\n        const char* intrinsics;\n        float fx, fy, cx, cy;\n        if ((intrinsics = std::getenv(\"WEBCAM_INTRINSIC_PARAMETERS\"))\n                && std::sscanf(intrinsics, \"%g,%g,%g,%g\", &fx, &fy, &cx, &cy) == 4) {\n            _fx = fx;\n            _fy = fy;\n            _cx = cx;\n            _cy = cy;\n        } else {\n            _fx = 0.9f * _w;\n            _fy = _fx;\n            _cx = _w / 2.0f;\n            _cy = _h / 2.0f;\n        }\n        const char* distCoeffs;\n        float k1, k2, p1, p2, k3;\n        if ((distCoeffs = std::getenv(\"WEBCAM_DISTORTION_COEFFICIENTS\"))\n                && std::sscanf(distCoeffs, \"%g,%g,%g,%g,%g\", &k1, &k2, &p1, &p2, &k3) == 5) {\n            _k1 = k1;\n            _k2 = k2;\n            _p1 = p1;\n            _p2 = p2;\n            _k3 = k3;\n        }\n        return true;\n    } else {\n        return false;\n    }\n}\n\n#define STRINGIFY(s) STRINGIFY_HELPER(s)\n#define STRINGIFY_HELPER(s) #s\n\nconst char* WebcamHeadTracker::filePathFrontalFaceXml()\n{\n#ifdef HAARCASCADE_FRONTALFACE_ALT_XML\n    static const char s[] = STRINGIFY(HAARCASCADE_FRONTALFACE_ALT_XML);\n#else\n    static const char s[] = \"\";\n#endif\n    return s;\n}\n\nconst char* WebcamHeadTracker::filePathFaceLandmarksDat()\n{\n#ifdef SHAPE_PREDICTOR_68_FACE_LANDMARKS_DAT\n    static const char s[] = STRINGIFY(SHAPE_PREDICTOR_68_FACE_LANDMARKS_DAT);\n#else\n    static const char s[] = \"\";\n#endif\n    return s;\n}\n\nbool WebcamHeadTracker::initPoseEstimator(const char* frontalFaceXml, const char* faceLandmarksDat)\n{\n    if (isReady())\n        return true;\n\n    _faceCascade = new cv::CascadeClassifier;\n    if (!_faceCascade->load(frontalFaceXml)) {\n        delete _faceCascade;\n        _faceCascade = NULL;\n        return false;\n    }\n\n    _faceModel = new dlib::shape_predictor;\n    try {\n        dlib::deserialize(faceLandmarksDat) >> *_faceModel;\n    }\n    catch (std::exception& e) {\n        delete _faceCascade;\n        _faceCascade = NULL;\n        delete _faceModel;\n        _faceModel = NULL;\n        return false;\n    }\n\n    // See http://docs.opencv.org/trunk/dc/d2c/tutorial_real_time_pose.html\n    // for information on this!\n    _kalmanFilter = new cv::KalmanFilter;\n    _kalmanFilter->init(18, 6, 0, CV_64F);\n    cv::setIdentity(_kalmanFilter->processNoiseCov, cv::Scalar::all(1e-3));\n    cv::setIdentity(_kalmanFilter->measurementNoiseCov, cv::Scalar::all(1e-1));\n    cv::setIdentity(_kalmanFilter->errorCovPost, cv::Scalar::all(1));\n    float dt = 1.0f / _fps;\n    _kalmanFilter->transitionMatrix.at<double>(0, 3) = dt;\n    _kalmanFilter->transitionMatrix.at<double>(1, 4) = dt;\n    _kalmanFilter->transitionMatrix.at<double>(2, 5) = dt;\n    _kalmanFilter->transitionMatrix.at<double>(3, 6) = dt;\n    _kalmanFilter->transitionMatrix.at<double>(4, 7) = dt;\n    _kalmanFilter->transitionMatrix.at<double>(5, 8) = dt;\n    _kalmanFilter->transitionMatrix.at<double>(0, 6) = 0.5f * dt * dt;\n    _kalmanFilter->transitionMatrix.at<double>(1, 7) = 0.5f * dt * dt;\n    _kalmanFilter->transitionMatrix.at<double>(2, 8) = 0.5f * dt * dt;\n    _kalmanFilter->transitionMatrix.at<double>(9, 12) = dt;\n    _kalmanFilter->transitionMatrix.at<double>(10, 13) = dt;\n    _kalmanFilter->transitionMatrix.at<double>(11, 14) = dt;\n    _kalmanFilter->transitionMatrix.at<double>(12, 15) = dt;\n    _kalmanFilter->transitionMatrix.at<double>(13, 16) = dt;\n    _kalmanFilter->transitionMatrix.at<double>(14, 17) = dt;\n    _kalmanFilter->transitionMatrix.at<double>(9, 15) = 0.5f * dt * dt;\n    _kalmanFilter->transitionMatrix.at<double>(10, 16) = 0.5f * dt * dt;\n    _kalmanFilter->transitionMatrix.at<double>(11, 17) = 0.5f * dt * dt;\n    _kalmanFilter->measurementMatrix.at<double>(0, 0) = 1;\n    _kalmanFilter->measurementMatrix.at<double>(1, 1) = 1;\n    _kalmanFilter->measurementMatrix.at<double>(2, 2) = 1;\n    _kalmanFilter->measurementMatrix.at<double>(3, 9) = 1;\n    _kalmanFilter->measurementMatrix.at<double>(4, 10) = 1;\n    _kalmanFilter->measurementMatrix.at<double>(5, 11) = 1;\n\n    _despFilter = new DoubleExponentialSmoothing;\n\n    _isReady = true;\n    return true;\n}\n\nvoid WebcamHeadTracker::setFocalLengthsInPixels(float fx, float fy)\n{\n    _fx = fx;\n    _fy = fy;\n}\n\nvoid WebcamHeadTracker::setPrincipalPointInPixels(float cx, float cy)\n{\n    _cx = cx;\n    _cy = cy;\n}\n\nvoid WebcamHeadTracker::setDistortionCoefficients(float k1, float k2, float p1, float p2, float k3)\n{\n    _k1 = k1;\n    _k2 = k2;\n    _p1 = p1;\n    _p2 = p2;\n    _k3 = k3;\n}\n\nvoid WebcamHeadTracker::setFilter(enum Filter filter)\n{\n    _filter = filter;\n}\n\nvoid WebcamHeadTracker::getNewFrame()\n{\n    timer t0, t1;\n    t0.setNow();\n    *_capture >> *_frame;\n    t1.setNow();\n    if (_debugOptions & Debug_Timing) {\n        fprintf(stderr, \"WHT: acquiring webcam frame:  %4.1f ms\\n\", duration(t0, t1));\n    }\n}\n\nstatic void rodriguesToQuaternion(const double* r, double* q)\n{\n    // Note: the OpenCV use of Rodrigues rotation vectors seems to differ from\n    // other uses. They multiply the unit rotation axis with the rotation angle\n    // instead of with the tangens of half the angle. This is all crap. Everyone\n    // should always use quaternions ;)\n    double angle = std::sqrt(r[0] * r[0] + r[1] * r[1] + r[2] * r[2]);\n    double axis[3] = { r[0] / angle, r[1] / angle, r[2] / angle};\n    double sinHalfAngle = std::sin(angle / 2.0f);\n    q[0] = axis[0] * sinHalfAngle;\n    q[1] = axis[1] * sinHalfAngle;\n    q[2] = axis[2] * sinHalfAngle;\n    q[3] = std::cos(angle / 2.0f);\n}\n\nstatic void quaternionToRodrigues(const double* q, double* r)\n{\n    double halfAngle = std::acos(q[3]);\n    double sinHalfAngle = std::sin(halfAngle);\n    double angle = halfAngle * 2.0;\n    double factor = angle / sinHalfAngle;\n    r[0] = factor * q[0];\n    r[1] = factor * q[1];\n    r[2] = factor * q[2];\n}\n\nstatic void quaternionToEuler(const double* q, double* euler)\n{\n    double singularityTest = q[0] * q[1] + q[2] * q[3];\n    if (singularityTest > 0.4999) {\n        // north pole\n        euler[0] = 2.0 * std::atan2(q[0], q[3]);\n        euler[1] = M_PI_2;\n        euler[2] = 0.0;\n    } else if (singularityTest < -0.4999) {\n        // south pole\n        euler[0] = -2.0 * std::atan2(q[0], q[3]);\n        euler[1] = -M_PI_2;\n        euler[2] = 0.0f;\n    } else {\n        euler[0] = std::atan2(2.0 * (q[3] * q[0] + q[1] * q[2]), 1.0 - 2.0 * (q[0] * q[0] + q[1] * q[1]));\n        euler[1] = std::asin(2.0 * (q[3] * q[1] - q[0] * q[2]));\n        euler[2] = std::atan2(2.0 * (q[3] * q[2] + q[0] * q[1]), 1.0 - 2.0 * (q[1] * q[1] + q[2] * q[2]));\n    }\n}\n\nstatic void eulerToQuaternion(const double* euler, double* q)\n{\n    double x2 = euler[0] / 2.0;\n    double y2 = euler[1] / 2.0;\n    double z2 = euler[2] / 2.0;\n    double sx2 = std::sin(x2);\n    double cx2 = std::cos(x2);\n    double sy2 = std::sin(y2);\n    double cy2 = std::cos(y2);\n    double sz2 = std::sin(z2);\n    double cz2 = std::cos(z2);\n    q[0] = sx2 * cy2 * cz2 - cx2 * sy2 * sz2;\n    q[1] = cx2 * sy2 * cz2 + sx2 * cy2 * sz2;\n    q[2] = cx2 * cy2 * sz2 - sx2 * sy2 * cz2;\n    q[3] = cx2 * cy2 * cz2 + sx2 * sy2 * sz2;\n}\n\nbool WebcamHeadTracker::computeHeadPose()\n{\n    if (!_faceCascade)\n        return false;\n\n    timer t0, t1, t2, t3, t4;\n\n    /* Face detection */\n    t0.setNow();\n    const int minFaceSize = 80;\n    std::vector<cv::Rect> faces;\n    _faceCascade->detectMultiScale(*_frame, faces, 1.1, 2,\n            cv::CASCADE_SCALE_IMAGE | cv::CASCADE_FIND_BIGGEST_OBJECT,\n            cv::Size(minFaceSize, minFaceSize));\n    if (faces.size() < 1)\n        return false;\n    cv::Rect faceRect = faces[0];\n    t1.setNow();\n\n    /* Face landmark detection */\n#if 1\n    // A temporary workaround for a Dlib/OpenCV incompatibility:\n    IplImage iplImg = cvIplImage(*_frame);\n    dlib::cv_image<dlib::bgr_pixel> dlibFrame(&iplImg);\n#else\n    dlib::cv_image<dlib::bgr_pixel> dlibFrame(*_frame); // does not copy data\n#endif\n    dlib::rectangle dlibRect(faceRect.x, faceRect.y,\n            faceRect.x + faceRect.width - 1, faceRect.y + faceRect.height - 1);\n    dlib::full_object_detection shape = (*_faceModel)(dlibFrame, dlibRect);\n    if (shape.num_parts() != 68)\n        return false;\n    std::vector<cv::Point2f> landmarks;\n    landmarks.resize(68);\n    for (int i = 0; i < 68; i++) {\n        dlib::point p = shape.part(i);\n        landmarks[i] = cv::Point(p.x(), p.y());\n    }\n    t2.setNow();\n\n    /* Extract a subset of landmarks for which we have good guesses for\n     * average positions from <https://en.wikipedia.org/wiki/Human_head>.\n     * Everything must be in mm to be consistent with OpenCV assumptions.\n     * We use landmarks that tend not to change too much with varying\n     * facial expressions. */\n    const cv::Point3f landmarkLeftEctocanthi  (-60.0f,   0.0f,   0.0f);\n    const cv::Point3f landmarkRightEctocanthi (+60.0f,   0.0f,   0.0f);\n    const cv::Point3f landmarkSellion         (  0.0f,   5.0f, -20.0f);\n    const cv::Point3f landmarkSubnasale       (  0.0f, -42.0f, -30.0f);\n    const cv::Point3f landmarkStomion         (  0.0f, -67.0f, -32.0f);\n    const cv::Point3f landmarkLeftTragion     (-70.0f,   0.0f,  99.9f);\n    const cv::Point3f landmarkRightTragion    (+70.0f,   0.0f,  99.9f);\n    const std::vector<cv::Point3f> modelLandmarks( {\n            landmarkLeftEctocanthi,\n            landmarkLeftEctocanthi,\n            landmarkRightEctocanthi,\n            landmarkRightEctocanthi,\n            landmarkSellion,\n            landmarkSubnasale,\n            landmarkStomion,\n            landmarkLeftTragion,\n            landmarkRightTragion\n            });\n    const int landmarkLeftEctocanthiIndex = 36;\n    const int landmarkRightEctocanthiIndex = 45;\n    const int landmarkSellionIndex = 27;\n    const int landmarkSubnasaleIndex = 33;\n    const int landmarkStomionIndex = 51;\n    const int landmarkLeftTragionIndex = 0;\n    const int landmarkRightTragionIndex = 16;\n    const std::vector<cv::Point2f> imageLandmarks( {\n            landmarks[landmarkLeftEctocanthiIndex],\n            landmarks[landmarkLeftEctocanthiIndex],\n            landmarks[landmarkRightEctocanthiIndex],\n            landmarks[landmarkRightEctocanthiIndex],\n            landmarks[landmarkSellionIndex],\n            landmarks[landmarkSubnasaleIndex],\n            landmarks[landmarkStomionIndex],\n            landmarks[landmarkLeftTragionIndex],\n            landmarks[landmarkRightTragionIndex]\n            });\n    cv::Matx33f cameraMatrix;\n    cameraMatrix(0, 0) = _fx;\n    cameraMatrix(0, 1) = 0.0f;\n    cameraMatrix(0, 2) = _cx;\n    cameraMatrix(1, 0) = 0.0f;\n    cameraMatrix(1, 1) = _fy;\n    cameraMatrix(1, 2) = _cy;\n    cameraMatrix(2, 0) = 0.0f;\n    cameraMatrix(2, 1) = 0.0f;\n    cameraMatrix(2, 2) = 1.0f;\n    cv::Mat distCoeffs(1, 5, CV_32F);\n    distCoeffs.at<float>(0) = _k1;\n    distCoeffs.at<float>(1) = _k2;\n    distCoeffs.at<float>(2) = _p1;\n    distCoeffs.at<float>(3) = _p2;\n    distCoeffs.at<float>(4) = _k3;\n    cv::Mat rvec(1, 3, CV_64F);\n    rvec.at<double>(0) = M_PI; // 180 deg around x axis: null rotation in OpenCV orientation\n    rvec.at<double>(1) = 0.0f;\n    rvec.at<double>(2) = 0.0f;\n    cv::Mat tvec(1, 3, CV_64F);\n    tvec.at<double>(0) = 0.0f;\n    tvec.at<double>(1) = 0.0f;\n    tvec.at<double>(2) = 500.0f;\n    // in my tests, using the CV_P3P solver with 4 points was less stable than using the iterative solver with 7\n    //cv::solvePnP(modelLandmarks, imageLandmarks, cameraMatrix, distCoeffs, rvec, tvec, false, CV_P3P);\n    cv::solvePnP(modelLandmarks, imageLandmarks, cameraMatrix, distCoeffs, rvec, tvec, true, cv::SOLVEPNP_ITERATIVE);\n    double observedVec[3] = { tvec.at<double>(0), tvec.at<double>(1), tvec.at<double>(2) };\n    double observedQuat[4];\n    rodriguesToQuaternion(&(rvec.at<double>(0)), observedQuat);\n    t3.setNow();\n\n    /* Feed the new measurement to the filter and save result */\n    double estimatedVec[3] = { 0, 0, 0 };\n    double estimatedQuat[4] = { 0, 0, 0, 0 };\n    switch (_filter) {\n    case Filter_None:\n        {\n            estimatedVec[0] = observedVec[0];\n            estimatedVec[1] = observedVec[1];\n            estimatedVec[2] = observedVec[2];\n            estimatedQuat[0] = observedQuat[0];\n            estimatedQuat[1] = observedQuat[1];\n            estimatedQuat[2] = observedQuat[2];\n            estimatedQuat[3] = observedQuat[3];\n        }\n        break;\n    case Filter_Kalman:\n        {\n            double observedEulerAngles[3];\n            quaternionToEuler(observedQuat, observedEulerAngles);\n            // See http://docs.opencv.org/trunk/dc/d2c/tutorial_real_time_pose.html\n            // for information on this!\n            cv::Mat measurement(6, 1, CV_64F);\n            measurement.at<double>(0) = observedVec[0];\n            measurement.at<double>(1) = observedVec[1];\n            measurement.at<double>(2) = observedVec[2];\n            measurement.at<double>(3) = observedEulerAngles[0];\n            measurement.at<double>(4) = observedEulerAngles[1];\n            measurement.at<double>(5) = observedEulerAngles[2];\n            cv::Mat prediction = _kalmanFilter->predict();\n            cv::Mat estimation = _kalmanFilter->correct(measurement);\n            estimatedVec[0] = estimation.at<double>(0);\n            estimatedVec[1] = estimation.at<double>(1);\n            estimatedVec[2] = estimation.at<double>(2);\n            eulerToQuaternion(&(estimation.at<double>(9)), estimatedQuat);\n        }\n        break;\n    case Filter_Double_Exponential:\n        {\n            _despFilter->step(observedVec, observedQuat,\n                    0.2, 0.7,\n                    estimatedVec, estimatedQuat);\n        }\n        break;\n    }\n    t4.setNow();\n\n    /* Convert the internal representation to the external representation */\n    // convert position\n    _headPosition[0] = -estimatedVec[0] / 1000.0;\n    _headPosition[1] = -estimatedVec[1] / 1000.0;\n    _headPosition[2] =  estimatedVec[2] / 1000.0;\n    // convert orientation (rotate 180 deg around x)\n    _headOrientation[0] =  estimatedQuat[3];\n    _headOrientation[1] = -estimatedQuat[2];\n    _headOrientation[2] =  estimatedQuat[1];\n    _headOrientation[3] = -estimatedQuat[0];\n\n    /* Debug output */\n    if (_debugOptions & Debug_Timing) {\n        fprintf(stderr, \"WHT: face detection:          %4.1f ms\\n\", duration(t0, t1));\n        fprintf(stderr, \"WHT: face landmark detection: %4.1f ms\\n\", duration(t1, t2));\n        fprintf(stderr, \"WHT: face model matching:     %4.1f ms\\n\", duration(t2, t3));\n        fprintf(stderr, \"WHT: filtering:               %4.1f ms\\n\", duration(t4, t3));\n    }\n    if (_debugOptions & Debug_Window) {\n        // render face rectangle\n        cv::rectangle(*_frame, faceRect, cv::Scalar(0, 0, 255));\n        // render face model\n        for (int i = 1; i <= 16; i++)\n            cv::line(*_frame, landmarks[i - 1], landmarks[i], cv::Scalar(0, 255, 0), 1, 1, 0);\n        for (int i = 18; i <= 21; i++)\n            cv::line(*_frame, landmarks[i - 1], landmarks[i], cv::Scalar(0, 255, 0), 1, 1, 0);\n        for (int i = 23; i <= 26; i++)\n            cv::line(*_frame, landmarks[i - 1], landmarks[i], cv::Scalar(0, 255, 0), 1, 1, 0);\n        for (int i = 28; i <= 30; i++)\n            cv::line(*_frame, landmarks[i - 1], landmarks[i], cv::Scalar(0, 255, 0), 1, 1, 0);\n        for (int i = 31; i <= 35; i++)\n            cv::line(*_frame, landmarks[i - 1], landmarks[i], cv::Scalar(0, 255, 0), 1, 1, 0);\n        cv::line(*_frame, landmarks[30], landmarks[35], cv::Scalar(0, 255, 0), 1, 1, 0);\n        for (int i = 37; i <= 41; i++)\n            cv::line(*_frame, landmarks[i - 1], landmarks[i], cv::Scalar(0, 255, 0), 1, 1, 0);\n        cv::line(*_frame, landmarks[36], landmarks[41], cv::Scalar(0, 255, 0), 1, 1, 0);\n        for (int i = 43; i <= 47; i++)\n            cv::line(*_frame, landmarks[i - 1], landmarks[i], cv::Scalar(0, 255, 0), 1, 1, 0);\n        cv::line(*_frame, landmarks[42], landmarks[47], cv::Scalar(0, 255, 0), 1, 1, 0);\n        for (int i = 49; i <= 59; i++)\n            cv::line(*_frame, landmarks[i - 1], landmarks[i], cv::Scalar(0, 255, 0), 1, 1, 0);\n        cv::line(*_frame, landmarks[48], landmarks[49], cv::Scalar(0, 255, 0), 1, 1, 0);\n        for (int i = 61; i <= 67; i++)\n            cv::line(*_frame, landmarks[i - 1], landmarks[i], cv::Scalar(0, 255, 0), 1, 1, 0);\n        cv::line(*_frame, landmarks[60], landmarks[67], cv::Scalar(0, 255, 0), 1, 1, 0);\n        for (int i = 0; i < 68; i++)\n            cv::circle(*_frame, landmarks[i], 2.5f, cv::Scalar(0, 0, 255), 1, 1, 0);\n        cv::circle(*_frame, landmarks[landmarkLeftEctocanthiIndex],  3.0f, cv::Scalar(255, 255, 255), 1, 1, 0);\n        cv::circle(*_frame, landmarks[landmarkRightEctocanthiIndex], 3.0f, cv::Scalar(255, 255, 255), 1, 1, 0);\n        cv::circle(*_frame, landmarks[landmarkSellionIndex],         3.0f, cv::Scalar(255, 255, 255), 1, 1, 0);\n        cv::circle(*_frame, landmarks[landmarkSubnasaleIndex],       3.0f, cv::Scalar(255, 255, 255), 1, 1, 0);\n        cv::circle(*_frame, landmarks[landmarkStomionIndex],         3.0f, cv::Scalar(255, 255, 255), 1, 1, 0);\n        cv::circle(*_frame, landmarks[landmarkLeftTragionIndex],     3.0f, cv::Scalar(255, 255, 255), 1, 1, 0);\n        cv::circle(*_frame, landmarks[landmarkRightTragionIndex],    3.0f, cv::Scalar(255, 255, 255), 1, 1, 0);\n        // render projected face model landmarks\n        std::vector<cv::Point2f> projectedModelLandmarks;\n        cv::projectPoints(modelLandmarks, rvec, tvec, cameraMatrix, distCoeffs, projectedModelLandmarks);\n        cv::line(*_frame, projectedModelLandmarks[7], projectedModelLandmarks[0], cv::Scalar(255, 0, 0));\n        cv::line(*_frame, projectedModelLandmarks[0], projectedModelLandmarks[4], cv::Scalar(255, 0, 0));\n        cv::line(*_frame, projectedModelLandmarks[4], projectedModelLandmarks[2], cv::Scalar(255, 0, 0));\n        cv::line(*_frame, projectedModelLandmarks[2], projectedModelLandmarks[8], cv::Scalar(255, 0, 0));\n        cv::line(*_frame, projectedModelLandmarks[4], projectedModelLandmarks[5], cv::Scalar(255, 0, 0));\n        cv::line(*_frame, projectedModelLandmarks[5], projectedModelLandmarks[6], cv::Scalar(255, 0, 0));\n        cv::circle(*_frame, projectedModelLandmarks[0], 3.0f, cv::Scalar(255, 0, 0));\n        cv::circle(*_frame, projectedModelLandmarks[2], 3.0f, cv::Scalar(255, 0, 0));\n        cv::circle(*_frame, projectedModelLandmarks[4], 3.0f, cv::Scalar(255, 0, 0));\n        cv::circle(*_frame, projectedModelLandmarks[5], 3.0f, cv::Scalar(255, 0, 0));\n        cv::circle(*_frame, projectedModelLandmarks[6], 3.0f, cv::Scalar(255, 0, 0));\n        cv::circle(*_frame, projectedModelLandmarks[7], 3.0f, cv::Scalar(255, 0, 0));\n        cv::circle(*_frame, projectedModelLandmarks[8], 3.0f, cv::Scalar(255, 0, 0));\n        // render projected filtered model\n        std::vector<cv::Point2f> projectedFilteredModelLandmarks;\n        tvec.at<double>(0) = estimatedVec[0];\n        tvec.at<double>(1) = estimatedVec[1];\n        tvec.at<double>(2) = estimatedVec[2];\n        quaternionToRodrigues(estimatedQuat, &(rvec.at<double>(0)));\n        cv::projectPoints(modelLandmarks, rvec, tvec, cameraMatrix, distCoeffs, projectedFilteredModelLandmarks);\n        cv::line(*_frame, projectedFilteredModelLandmarks[7], projectedFilteredModelLandmarks[0], cv::Scalar(255, 255, 0));\n        cv::line(*_frame, projectedFilteredModelLandmarks[0], projectedFilteredModelLandmarks[4], cv::Scalar(255, 255, 0));\n        cv::line(*_frame, projectedFilteredModelLandmarks[4], projectedFilteredModelLandmarks[2], cv::Scalar(255, 255, 0));\n        cv::line(*_frame, projectedFilteredModelLandmarks[2], projectedFilteredModelLandmarks[8], cv::Scalar(255, 255, 0));\n        cv::line(*_frame, projectedFilteredModelLandmarks[4], projectedFilteredModelLandmarks[5], cv::Scalar(255, 255, 0));\n        cv::line(*_frame, projectedFilteredModelLandmarks[5], projectedFilteredModelLandmarks[6], cv::Scalar(255, 255, 0));\n        cv::circle(*_frame, projectedFilteredModelLandmarks[0], 3.0f, cv::Scalar(255, 255, 0));\n        cv::circle(*_frame, projectedFilteredModelLandmarks[2], 3.0f, cv::Scalar(255, 255, 0));\n        cv::circle(*_frame, projectedFilteredModelLandmarks[4], 3.0f, cv::Scalar(255, 255, 0));\n        cv::circle(*_frame, projectedFilteredModelLandmarks[5], 3.0f, cv::Scalar(255, 255, 0));\n        cv::circle(*_frame, projectedFilteredModelLandmarks[6], 3.0f, cv::Scalar(255, 255, 0));\n        cv::circle(*_frame, projectedFilteredModelLandmarks[7], 3.0f, cv::Scalar(255, 255, 0));\n        cv::circle(*_frame, projectedFilteredModelLandmarks[8], 3.0f, cv::Scalar(255, 255, 0));\n        // show\n        cv::imshow(\"webcam head tracker\", *_frame);\n        int key = cv::waitKey(1);\n        if (key == 27 || key == 'q')\n            _isReady = false;\n        if (key == 'f')\n            _filter = (_filter == Filter_None ? Filter_Kalman\n                    : _filter == Filter_Kalman ? Filter_Double_Exponential\n                    : Filter_None);\n    }\n    return true;\n}\n\nvoid WebcamHeadTracker::getHeadPosition(float* headPosition) const\n{\n    headPosition[0] = _headPosition[0];\n    headPosition[1] = _headPosition[1];\n    headPosition[2] = _headPosition[2];\n}\n\nvoid WebcamHeadTracker::getHeadOrientation(float* headOrientation) const\n{\n    headOrientation[0] = _headOrientation[0];\n    headOrientation[1] = _headOrientation[1];\n    headOrientation[2] = _headOrientation[2];\n    headOrientation[3] = _headOrientation[3];\n}\n", "meta": {"hexsha": "2c46e4a3ec1cb9442aacaa396d12280db9e6827b", "size": 29312, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "webcam-head-tracker.cpp", "max_stars_repo_name": "marlam/webcam-head-tracker-mirror", "max_stars_repo_head_hexsha": "4527f7ab236c418e54b5818422fd82fad7d753df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-12-12T09:08:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T05:26:40.000Z", "max_issues_repo_path": "webcam-head-tracker.cpp", "max_issues_repo_name": "marlam/webcam-head-tracker-mirror", "max_issues_repo_head_hexsha": "4527f7ab236c418e54b5818422fd82fad7d753df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "webcam-head-tracker.cpp", "max_forks_repo_name": "marlam/webcam-head-tracker-mirror", "max_forks_repo_head_hexsha": "4527f7ab236c418e54b5818422fd82fad7d753df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-14T20:48:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-14T20:48:27.000Z", "avg_line_length": 40.2085048011, "max_line_length": 123, "alphanum_fraction": 0.6101255459, "num_tokens": 9427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.28964107553793816}}
{"text": "/* -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n// This file is a part of ChASE.\n// Copyright (c) 2015-2021, Simulation and Data Laboratory Quantum Materials, \n//   Forschungszentrum Juelich GmbH, Germany. All rights reserved.\n// License is 3-clause BSD:\n// https://github.com/ChASE-library/ChASE\n\n#include <boost/program_options.hpp>\n#include <boost/filesystem.hpp>\n#include <limits>\n#include <random>\n#include <memory>\n#include <random>\n#include <vector>\n#include <iostream> \n#include <fstream>\n#include <chrono>\n\n#include \"algorithm/performance.hpp\"\n#include \"ChASE-MPI/chase_mpi.hpp\"\n\n#include \"ChASE-MPI/impl/chase_mpidla_blaslapack_seq.hpp\"\n#include \"ChASE-MPI/impl/chase_mpidla_blaslapack_seq_inplace.hpp\"\n\n#ifdef USE_MPI\n#include \"ChASE-MPI/impl/chase_mpidla_blaslapack.hpp\"\n  #ifdef DRIVER_BUILD_MGPU\n  #include \"ChASE-MPI/impl/chase_mpidla_mgpu.hpp\"\n  #endif\n#endif\n\nusing namespace chase;\nusing namespace chase::mpi;\n\nnamespace po = boost::program_options;\nnamespace bf = boost::filesystem;\n\ntemplate <typename T>\nvoid readMatrix(T* H, std::string path_in, std::string spin, std::size_t kpoint,\n                std::size_t index, std::string suffix, std::size_t size,\n                bool legacy) {\n  std::ostringstream problem(std::ostringstream::ate);\n  if (legacy)\n    problem << path_in << \"gmat  1 \" << std::setw(2) << index << suffix;\n  else\n    problem << path_in << \"mat_\" << spin << \"_\" << std::setfill('0')\n            << std::setw(2) << kpoint << \"_\" << std::setfill('0')\n            << std::setw(2) << index << suffix;\n\n  std::cout << problem.str() << std::endl;\n  std::ifstream input(problem.str().c_str(), std::ios::binary);\n\n  std::cout << problem.str().c_str() << \" \" << \"---\" << bf::file_size(problem.str().c_str()) << '\\n';\n\n  if (input.is_open()) {\n    input.read((char*)H, sizeof(T) * size);\n  } else {\n    throw std::string(\"error reading file: \") + problem.str();\n  }\n}\n\ntemplate <typename T>\nvoid readMatrix(T* H, std::string path_in, std::string spin, std::size_t kpoint,\n                std::size_t index, std::string suffix, std::size_t size,\n                bool legacy, std::size_t xoff, std::size_t yoff,\n                std::size_t xlen, std::size_t ylen) {\n  std::size_t N = std::sqrt(size);\n  std::ostringstream problem(std::ostringstream::ate);\n\n  int rank;\n\n#ifdef USE_MPI\n  MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n#else\n  rank = 0;\n#endif\n\n  if (legacy){\n\tproblem << path_in << \"gmat  1 \" << std::setw(2) << index << suffix;\n  }\n  else{\n    problem << path_in << \"mat_\" << spin << \"_\" << std::setfill('0')\n            << std::setw(2) << kpoint << \"_\" << std::setfill('0')\n            << std::setw(2) << index << suffix;\n  } \n\n  if (rank == 0) std::cout << problem.str() << std::endl;\n\n  std::size_t file_size = bf::file_size(problem.str().c_str());\n\n  try{\n    if(size * sizeof(T) != file_size ){\n      throw std::logic_error(std::string(\"The given file : \") +\n                               problem.str() + std::string(\" of size \") + std::to_string(file_size) +\n                               std::string(\" doesn't equals to the required size of matrix of size \") + std::to_string(size * sizeof(T)));\n    }\n  }\n  catch(std::exception &e)\n  {\n    std::cerr << \"Caught \" << typeid( e ).name( ) << \" : \"<< e.what( ) << std::endl;\n    return ;\n  } \n\n  std::ifstream input(problem.str().c_str(), std::ios::binary);\n  if (!input.is_open()) {\n    throw new std::logic_error(std::string(\"error reading file: \") +\n                               problem.str());\n  }\n\n  for (std::size_t y = 0; y < ylen; y++) {\n    input.seekg(((xoff) + N * (yoff + y)) * sizeof(T));\n    input.read(reinterpret_cast<char*>(H + xlen * y), xlen * sizeof(T));\n  }\n}\n\ntemplate <typename T>\nvoid readMatrix(T* H, std::string path_in, std::string spin, std::size_t kpoint,\n                std::size_t index, std::string suffix, std::size_t size, bool legacy, \n\t\tstd::size_t m, std::size_t mblocks, std::size_t nblocks,\n            \tstd::size_t* r_offs, std::size_t* r_lens, std::size_t* r_offs_l, \n\t\tstd::size_t* c_offs, std::size_t* c_lens, std::size_t* c_offs_l){\n  std::size_t N = std::sqrt(size);\n  std::ostringstream problem(std::ostringstream::ate);\n\n  int rank;\n\n#ifdef USE_MPI\n  MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n#else\n  rank = 0;\n#endif\n\n  if (legacy){\n        problem << path_in << \"gmat  1 \" << std::setw(2) << index << suffix;\n  }\n  else{\n    problem << path_in << \"mat_\" << spin << \"_\" << std::setfill('0')\n            << std::setw(2) << kpoint << \"_\" << std::setfill('0')\n            << std::setw(2) << index << suffix;\n  }\n\n  if (rank == 0) std::cout << problem.str() << std::endl;\n  \n  std::size_t file_size = bf::file_size(problem.str().c_str());\n\n  try{\n    if(size * sizeof(T) != file_size ){\n      throw std::logic_error(std::string(\"The given file : \") +\n                               problem.str() + std::string(\" of size \") + std::to_string(file_size) +\n                               std::string(\" doesn't equals to the required size of matrix of size \") + std::to_string(size * sizeof(T)));\n    }\n  }\n  catch(std::exception &e)\n  {\n    std::cerr << \"Caught \" << typeid( e ).name( ) << \" : \"<< e.what( ) << std::endl;\n    return ;\n  }\n\n  std::ifstream input(problem.str().c_str(), std::ios::binary);\n  if (!input.is_open()) {\n    throw new std::logic_error(std::string(\"error reading file: \") +\n                               problem.str());\n  }\n   \n  for(std::size_t j = 0; j < nblocks; j++){\n      for(std::size_t i = 0; i < mblocks; i++){\n          for(std::size_t q = 0; q < c_lens[j]; q++){\n\t      input.seekg(((q + c_offs[j]) * N + r_offs[i])* sizeof(T));\n\t      input.read(reinterpret_cast<char*>(H + (q + c_offs_l[j]) * m + r_offs_l[i]), r_lens[i] * sizeof(T));\n\t  }\n      }\n  }\n  \n}\n\ntemplate <typename T>\nvoid readMatrix(T* H, std::string path_in, std::size_t size,\n                std::size_t xoff, std::size_t yoff,\n                std::size_t xlen, std::size_t ylen) {\n  std::size_t N = std::sqrt(size);\n  std::ostringstream problem(std::ostringstream::ate);\n  problem << path_in;\n  int rank;\n#ifdef USE_MPI\n  MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n#else\n  rank = 0;\n#endif\n\n  if (rank == 0) std::cout << problem.str() << std::endl;\n\n\n  std::size_t file_size = bf::file_size(problem.str().c_str());\n\n  try{\n    if(size * sizeof(T) != file_size ){\n      throw std::logic_error(std::string(\"The given file : \") +\n                               problem.str() + std::string(\" of size \") + std::to_string(file_size) +\n                               std::string(\" doesn't equals to the required size of matrix of size \") + std::to_string(size * sizeof(T)));\n    }\n  }\n  catch(std::exception &e)\n  {\n    std::cerr << \"Caught \" << typeid( e ).name( ) << \" : \"<< e.what( ) << std::endl;\n    return ;\n  }\n\n  std::ifstream input(problem.str().c_str(), std::ios::binary);\n\n  if (!input.is_open()) {\n    throw new std::logic_error(std::string(\"error reading file: \") +\n                               problem.str());\n  }\n\n  for (std::size_t y = 0; y < ylen; y++) {\n    input.seekg(((xoff) + N * (yoff + y)) * sizeof(T));\n    input.read(reinterpret_cast<char*>(H + xlen * y), xlen * sizeof(T));\n  }\n}\n\n\ntemplate <typename T>\nvoid readMatrix(T* H, std::string path_in, std::size_t size, \n                std::size_t m, std::size_t mblocks, std::size_t nblocks,\n                std::size_t* r_offs, std::size_t* r_lens, std::size_t* r_offs_l,\n                std::size_t* c_offs, std::size_t* c_lens, std::size_t* c_offs_l){\n\n      \tstd::size_t N = std::sqrt(size);\n  std::ostringstream problem(std::ostringstream::ate);\n  problem << path_in;\n\n  int rank;\n\n#ifdef USE_MPI\n  MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n#else\n  rank = 0;\n#endif\n\n  if (rank == 0) std::cout << problem.str() << std::endl;\n\n\n  std::size_t file_size = bf::file_size(problem.str().c_str());\n\n  try{\n    if(size * sizeof(T) != file_size ){\n      throw std::logic_error(std::string(\"The given file : \") +\n                               problem.str() + std::string(\" of size \") + std::to_string(file_size) +\n                               std::string(\" doesn't equals to the required size of matrix of size \") + std::to_string(size * sizeof(T)));\n    }\n  }\n  catch(std::exception &e)\n  {\n    std::cerr << \"Caught \" << typeid( e ).name( ) << \" : \"<< e.what( ) << std::endl;\n    return ;\n  }\n\n  std::ifstream input(problem.str().c_str(), std::ios::binary);\n  if (!input.is_open()) {\n    throw new std::logic_error(std::string(\"error reading file: \") +\n                               problem.str());\n  }\n\n  for(std::size_t j = 0; j < nblocks; j++){\n      for(std::size_t i = 0; i < mblocks; i++){\n          for(std::size_t q = 0; q < c_lens[j]; q++){\n              input.seekg(((q + c_offs[j]) * N + r_offs[i])* sizeof(T));\n              input.read(reinterpret_cast<char*>(H + (q + c_offs_l[j]) * m + r_offs_l[i]), r_lens[i] * sizeof(T));\n          }\n      }\n  }\n\n}\n\nstruct ChASE_DriverProblemConfig {\n  std::size_t N;    // Size of the Matrix\n  std::size_t nev;  // Number of sought after eigenvalues\n  std::size_t nex;  // Extra size of subspace\n  std::size_t deg;  // initial degree\n  std::size_t bgn;  // beginning of sequence\n  std::size_t end;  // end of sequence\n  \n  std::size_t maxIter; // maximum number of subspace iterations within ChASE.\n  std::size_t maxDeg; //maximum value of the degree of the Chebyshev filter\n  double tol;     // desired tolerance\n  bool sequence;  // handle this as a sequence?\n\n  std::string path_in;    // path to the matrix input files\n  std::string mode;       // Approx or Random mode\n  std::string opt;        // enable optimisation of degree\n  std::string arch;       // ??\n  std::string path_eigp;  // TODO\n  std::string path_out;\n  std::string path_name;\n\n  std::size_t kpoint;\n  bool legacy;\n  std::string spin;\n\n  bool iscomplex;\n  bool isdouble;\n\n  std::size_t lanczosIter; \n  std::size_t numLanczos;\n\n#ifdef USE_BLOCK_CYCLIC\n  std::size_t mbsize;\n  std::size_t nbsize;\n  int dim0;\n  int dim1;\n  int irsrc;\n  int icsrc;\n  std::string major;\n#endif  \n};\n\ntemplate <typename T>\nint do_chase(ChASE_DriverProblemConfig& conf) {\n  // todo due to legacy reasons we unpack the struct\n  std::size_t N = conf.N;\n  std::size_t nev = conf.nev;\n  std::size_t nex = conf.nex;\n  std::size_t deg = conf.deg;\n  std::size_t bgn = conf.bgn;\n  std::size_t end = conf.end;\n  std::size_t maxDeg = conf.maxDeg;\n  std::size_t maxIter = conf.maxIter;\n\n  double tol = conf.tol;\n  bool sequence = conf.sequence;\n\n  std::string path_in = conf.path_in;\n  std::string mode = conf.mode;\n  std::string opt = conf.opt;\n  std::string arch;\n  std::string path_eigp = conf.path_eigp;\n  std::string path_out = conf.path_out;\n  std::string path_name = conf.path_name;\n\n  std::size_t lanczosIter = conf.lanczosIter;\n  std::size_t numLanczos = conf.numLanczos;\n\n  std::size_t kpoint = conf.kpoint;\n  bool legacy = conf.legacy;\n  std::string spin = conf.spin;\n#ifdef USE_BLOCK_CYCLIC\n  std::size_t mbsize = conf.mbsize;\n  std::size_t nbsize = conf.nbsize;\n  int dim0 = conf.dim0;\n  int dim1 = conf.dim1;\n  int irsrc = conf.irsrc;\n  int icsrc = conf.irsrc;\n  std::string major = conf.major;\n\n  if(dim0 == 0 || dim1 == 0){\n    int dims[2];\n    dims[0] = dims[1] = 0;\n    int gsize;\n    MPI_Comm_size(MPI_COMM_WORLD, &gsize);    \n    MPI_Dims_create(gsize, 2, dims);\n    dim0 = dims[0];\n    dim1 = dims[1];    \n  }\n#endif  \n  int rank, size;\n\n#ifdef USE_MPI\n  MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n  MPI_Comm_size(MPI_COMM_WORLD, &size);\n#else\n  rank = 0;\n  size = 1;\n#endif\n\n  //----------------------------------------------------------------------------\n  std::cout << std::setprecision(16);\n\n  auto V__ = std::unique_ptr<T[]>(new T[N * (nev + nex)]);\n  auto Lambda__ = std::unique_ptr<Base<T>[]>(new Base<T>[(nev + nex)]);\n\n  T* V = V__.get();\n  Base<T>* Lambda = Lambda__.get();\n\n#ifdef USE_MPI\n    #ifdef DRIVER_BUILD_MGPU\n        typedef ChaseMpi<ChaseMpiDLAMultiGPU, T> CHASE;\n    #else\n        typedef ChaseMpi<ChaseMpiDLABlaslapack, T> CHASE;\n    #endif //CUDA or not\n#else\n    typedef ChaseMpi<ChaseMpiDLABlaslapackSeq, T> CHASE;\n#endif //seq ChASE\n\n#ifdef USE_MPI\n#ifdef USE_BLOCK_CYCLIC\n  CHASE single(new ChaseMpiProperties<T>(N, mbsize, nbsize, nev, nex, dim0, dim1, const_cast<char*>(major.c_str()), irsrc, icsrc, MPI_COMM_WORLD),\n                    V, Lambda);\n#else\n  CHASE single(new ChaseMpiProperties<T>(N, nev, nex, MPI_COMM_WORLD), V,\n               Lambda);\n#endif\n#else\n  CHASE single(N, nev, nex, V, Lambda);\n#endif\n\n  ChaseConfig<T>& config = single.GetConfig();\n  config.SetTol(tol);\n  config.SetDeg(deg);\n  config.SetOpt(opt == \"S\");\n  config.SetLanczosIter(lanczosIter);\n  config.SetNumLanczos(numLanczos);\n  config.SetMaxDeg(maxDeg);\n  config.SetMaxIter(maxIter);\n\n  std::mt19937 gen(1337.0);\n  std::normal_distribution<> d;\n\n  T* H = single.GetMatrixPtr();\n\n  if(!sequence){\n    bgn = end = 1;\n  }\n\n  for (auto i = bgn; i <= end; ++i) {\n    if (i == bgn || !sequence) {\n      if (mode[0] == 'A') {\n        readMatrix(V, path_eigp, spin, kpoint, i - 1, \".vct\", N * (nev + nex),\n                     legacy);\n        readMatrix(Lambda, path_eigp, spin, kpoint, i - 1, \".vls\", (nev + nex),\n                     legacy);\n      }else{ \n        for (std::size_t i = 0; i < N * (nev + nex); ++i) {\n          V[i] = getRandomT<T>([&]() { \n\t\t\treturn d(gen);\n\t\t     }\n                 );\n        }\n\n        for (int j = 0; j < (nev + nex); j++) {\n\t  Lambda[j] = 0.0;\n        };\n      }\n    }else{\n      config.SetApprox(true);\n    }\n\n#ifdef USE_BLOCK_CYCLIC\n  /*local block number = mblocks x nblocks*/\n    std::size_t mblocks = single.get_mblocks();\n    std::size_t nblocks = single.get_nblocks();\n\n    /*local matrix size = m x n*/\n    std::size_t m = single.get_m();\n    std::size_t n = single.get_n();\n\n    /*global and local offset/length of each block of block-cyclic data*/\n    std::size_t *r_offs, *c_offs, *r_lens, *c_lens, *r_offs_l, *c_offs_l;\n\n    single.get_offs_lens(r_offs, r_lens, r_offs_l, c_offs, c_lens, c_offs_l);\n#else    \n    std::size_t xoff;\n    std::size_t yoff;\n    std::size_t xlen;\n    std::size_t ylen;\n\n    single.GetOff(&xoff, &yoff, &xlen, &ylen);\n#endif\n\n    std::chrono::high_resolution_clock::time_point start, end;\n    std::chrono::duration<double> elapsed;\n\n    start = std::chrono::high_resolution_clock::now();\n\n    if(rank == 0) std::cout << \"start reading matrix\\n\";\n#ifdef USE_BLOCK_CYCLIC\n    if(sequence){\n      readMatrix(H, path_in, spin, kpoint, i, \".bin\", N*N, legacy, m, mblocks, nblocks, r_offs, r_lens, r_offs_l, c_offs, c_lens, c_offs_l);\n    }else{\n      readMatrix(H, path_in, N*N, m, mblocks, nblocks, r_offs, r_lens, r_offs_l, c_offs, c_lens, c_offs_l);    \n    }\n#else\n    if(sequence){    \n      readMatrix(H, path_in, spin, kpoint, i, \".bin\", N * N, legacy, xoff, yoff, xlen, ylen);\n    }else{\n      readMatrix(H, path_in, N * N, xoff, yoff, xlen, ylen);    \n    }\n#endif\n\n    MPI_Barrier(MPI_COMM_WORLD);\n\n    end = std::chrono::high_resolution_clock::now();\n\n    elapsed = std::chrono::duration_cast<std::chrono::duration<double>>(end - start);\n\n    if(rank == 0) std::cout <<  \"matrix are loaded in \" << elapsed.count() << \" seconds\" << std::endl;\n    \n    PerformanceDecoratorChase<T> performanceDecorator(&single);\n\n#ifdef USE_MPI\n    MPI_Barrier(MPI_COMM_WORLD);\n#endif\n    chase::Solve(&performanceDecorator);\n\n#ifdef USE_MPI\n    MPI_Barrier(MPI_COMM_WORLD);\n#endif\n\n    if (rank == 0) {\n      std::cout << \" ChASE timings: \" << \"\\n\";\n      performanceDecorator.GetPerfData().print();\n#ifdef PRINT_EIGENVALUES\n      Base<T>* resid = single.GetResid();\n      std::cout << \"Finished Problem \\n\";\n      std::cout << \"Printing first 5 eigenvalues and residuals\\n\";\n      std::cout\n          << \"| Index |       Eigenvalue      |         Residual      |\\n\"\n          << \"|-------|-----------------------|-----------------------|\\n\";\n      std::size_t width = 20;\n      std::cout << std::setprecision(12);\n      std::cout << std::setfill(' ');\n      std::cout << std::scientific;\n      std::cout << std::right;\n      for (auto i = 0; i < std::min(std::size_t(5), nev); ++i)\n        std::cout << \"|  \" << std::setw(4) << i + 1 << \" | \" << std::setw(width)\n                  << Lambda[i] << \"  | \" << std::setw(width) << resid[i]\n                  << \"  |\\n\";\n      std::cout << \"\\n\\n\\n\";\n#endif      \n    }    \n  }\n\n  return 0;\n\n}\n\nint main(int argc, char* argv[]) {\n\n#ifdef USE_MPI\n  MPI_Init(&argc, &argv);\n#endif\n\n  ChASE_DriverProblemConfig conf;\n\n  po::options_description desc(\"ChASE Options\");\n\n  desc.add_options()(                                                     //\n      \"help,h\",                                                           //\n      \"show this message\"                                                 //\n      )(                                                                  //\n      \"n\", po::value<std::size_t>(&conf.N)->required(),                   //\n      \"Size of the Input Matrix\"                                          //\n      )(                                                                  //\n      \"double\", po::value<bool>(&conf.isdouble)->default_value(true),     //\n      \"Is matrix double valued, false indicates the single type\"  \t\t  //\n      )(                                                                  //\n      \"complex\", po::value<bool>(&conf.iscomplex)->default_value(true),   //\n      \"Matrix is complex, false indicated the real matrix\"\t\t          //\n      )(                                                                  //\n      \"nev\", po::value<std::size_t>(&conf.nev)->required(),               //\n      \"Wanted Number of Eigenpairs\"                                       //\n      )(                                                                  //\n      \"nex\", po::value<std::size_t>(&conf.nex)->default_value(25),        //\n      \"Extra Search Dimensions\"                                           //\n      )(                                                                  //\n      \"deg\", po::value<std::size_t>(&conf.deg)->default_value(20),        //\n      \"Initial filtering degree\"                                          //\n      )(\n      \"maxDeg\", po::value<std::size_t>(&conf.maxDeg)->default_value(36),  //\n      \"Sets the maximum value of the degree of the Chebyshev filter\"\n      )(\n      \"maxIter\", po::value<std::size_t>(&conf.maxIter)->default_value(25), //\n      \"Sets the value of the maximum number of subspace iterations\"\n      \"within ChASE\"\n      )(                                                                  //\n      \"bgn\", po::value<std::size_t>(&conf.bgn)->default_value(2),         //\n      \"Start ell\"                                                         //\n      )(                                                                  //\n      \"end\", po::value<std::size_t>(&conf.end)->default_value(2),         //\n      \"End ell\"                                                           //\n      )(                                                                  //\n      \"spin\", po::value<std::string>(&conf.spin)->default_value(\"d\"),     //\n      \"spin\"                                                              //\n      )(                                                                  //\n      \"kpoint\", po::value<std::size_t>(&conf.kpoint)->default_value(0),   //\n      \"kpoint\"                                                            //\n      )(                                                                  //\n      \"tol\", po::value<double>(&conf.tol)->default_value(1e-10),          //\n      \"Tolerance for Eigenpair convergence\"                               //\n      )(                                                                  //\n      \"path_in\", po::value<std::string>(&conf.path_in)->required(),       //\n      \"Path to the input matrix/matrices\"                                 //\n      )(                                                                  //\n      \"mode\", po::value<std::string>(&conf.mode)->default_value(\"A\"),     //\n      \"valid values are R(andom) or A(pproximate)\"                        //\n      )(                                                                  //\n      \"opt\", po::value<std::string>(&conf.opt)->default_value(\"S\"),       //\n      \"Optimi(S)e degree, or do (N)ot optimise\"                           //\n      )(                                                                  //\n      \"path_eigp\", po::value<std::string>(&conf.path_eigp),               //\n      \"Path to approximate solutions, only required when mode\"            //\n      \"is Approximate, otherwise not used\"                                //\n      )(                                                                  //\n      \"sequence\", po::value<bool>(&conf.sequence)->default_value(false),  //\n      \"Treat as sequence of Problems. Previous ChASE solution is used,\"   //\n      \"when available\"                                                    //\n      )(\n      \"lanczosIter\",po::value<std::size_t>(&conf.lanczosIter)->default_value(25),\n      \"Sets the number of Lanczos iterations executed by ChASE.\"\n      )(\n      \"numLanczos\", po::value<std::size_t>(&conf.numLanczos)->default_value(4),\t\n      \" Sets the number of stochastic vectors used for the spectral estimates\"\n      \"in Lanczos\" \n      )\n#ifdef USE_BLOCK_CYCLIC\n      (                                                                   //\n      \"mbsize\", po::value<std::size_t>(&conf.mbsize)->default_value(400),  //\n      \"block size for the row\"                                            //\n      )(                                                                  //\n      \"nbsize\", po::value<std::size_t>(&conf.nbsize)->default_value(400),  //\n      \"block size for the column\"                                         //\n      )(                                                                  //\n      \"dim0\", po::value<int>(&conf.dim0)->default_value(0),               //\n      \"row number of MPI proc grid\"                                       //\n      )(                                                                  //\n      \"dim1\", po::value<int>(&conf.dim1)->default_value(0),               //\n      \"column number of MPI proc grid\"                                    //\n      )(\t\t\t\t\t\t\t\t  //\n      \"irsrc\", po::value<int>(&conf.irsrc)->default_value(0),             //\n      \"The process row over which the first row of matrix is\"             //\n      \"distributed.\"                                                      //\n      )(                                                                  //\n      \"icsrc\", po::value<int>(&conf.icsrc)->default_value(0),             //\n      \"The process column over which the first column of the array A is\"  //\n      \"distributed.\"                                                      //\n      )(                                                                  //\n      \"major\", po::value<std::string>(&conf.mode)->default_value(\"C\"),    //\n      \"Major of MPI proc grid, valid values are R(ow) or C(olumn)\"        //\n      )\n#endif      \n      (\"legacy\", po::value<bool>(&conf.legacy)->default_value(false),     //\n      \"Use legacy naming scheme?\");                                       //\n\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n\n  // print help\n  if (vm.count(\"help\")) {\n    std::cout << desc << std::endl;\n    return 1;\n  }\n\n  po::notify(vm);\n  conf.mode = toupper(conf.mode.at(0));\n  conf.opt = toupper(conf.opt.at(0));\n\n  if (conf.bgn > conf.end) {\n    std::cout << \"Begin must be smaller than End!\" << std::endl;\n    return -1;\n  }\n\n  if (conf.mode != \"R\" && conf.mode != \"A\") {\n    std::cout << \"Illegal value for mode: \\\"\" << conf.mode << \"\\\"\" << std::endl\n              << \"Legal values are R or A\" << std::endl;\n    return -1;\n  }\n\n  if (conf.opt != \"N\" && conf.opt != \"S\") {\n    std::cout << \"Illegal value for opt: \" << conf.opt << std::endl\n              << \"Legal values are N, S\" << std::endl;\n    return -1;\n  }\n\n  if (conf.path_eigp.empty() && conf.mode == \"A\") {\n    std::cout << \"eigp is required when mode is \" << conf.mode << std::endl;\n    return -1;\n  }\n\n  if (conf.isdouble) {\n\tif (conf.iscomplex) {\n    \tdo_chase<std::complex<double>>(conf);\n\t} else {\n\t\tdo_chase<double>(conf);\n\t}\n  } else {\n    std::cout << \"single not implemented\\n\";\n  }\n\n#ifdef USE_MPI\n  MPI_Finalize();\n#else\n  return 0;\n#endif\n\n}\n\n", "meta": {"hexsha": "6bdda807c8566315608f291dc6a01757c2a79839", "size": 24363, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/2_input_output/2_input_output.cpp", "max_stars_repo_name": "brunowu/ChASE", "max_stars_repo_head_hexsha": "89649df6027cec70709f55d277b3625989e8cb3c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-03-18T14:04:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T18:21:57.000Z", "max_issues_repo_path": "examples/2_input_output/2_input_output.cpp", "max_issues_repo_name": "brunowu/ChASE", "max_issues_repo_head_hexsha": "89649df6027cec70709f55d277b3625989e8cb3c", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/2_input_output/2_input_output.cpp", "max_forks_repo_name": "brunowu/ChASE", "max_forks_repo_head_hexsha": "89649df6027cec70709f55d277b3625989e8cb3c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-03-18T14:14:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-19T10:21:13.000Z", "avg_line_length": 35.0043103448, "max_line_length": 146, "alphanum_fraction": 0.5143865698, "num_tokens": 6388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2895999082155286}}
{"text": "/*\nrelaxation.cpp\n\nCopyright (c) 2014, 2015, 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 \"mpi_common.h\"\n#include <fstream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n#include <set>\n#include <boost/lexical_cast.hpp>\n\n#ifdef _OPENMP\n#include <omp.h>\n#endif \n\n#include \"conductivity.h\"\n#include \"dynamical.h\"\n#include \"error.h\"\n#include \"fcs_phonon.h\"\n#include \"integration.h\"\n#include \"kpoint.h\"\n#include \"memory.h\"\n#include \"parsephon.h\"\n#include \"phonon_dos.h\"\n#include \"thermodynamics.h\"\n#include \"phonon_velocity.h\"\n#include \"relaxation.h\"\n#include \"selfenergy.h\"\n#include \"symmetry_core.h\"\n#include \"system.h\"\n#include \"write_phonons.h\"\n#include \"timer.h\"\n#include \"constants.h\"\n#include \"mathfunctions.h\"\n#include \"integration.h\"\n\nusing namespace PHON_NS;\n\nRelaxation::Relaxation(PHON *phon): Pointers(phon) {\n    im = std::complex<double>(0.0, 1.0);\n}\n\nRelaxation::~Relaxation(){};\n\nvoid Relaxation::setup_relaxation()\n{\n\n    nk = kpoint->nk;\n    ns = dynamical->neval;\n    nks = ns*nk;\n    int nk_tmp[3];\n\n    if (mympi->my_rank == 0) {\n        std::cout << std::endl;\n        std::cout << \" ------------------------------------------------------------\" << std::endl << std::endl;\n        std::cout << \" Now, move on to phonon lifetime calculations.\" << std::endl;\n    }\n\n    setup_mode_analysis();\n    setup_cubic();\n\n    use_tuned_ver = true;\n    nk_tmp[0] = kpoint->nkx;\n    nk_tmp[1] = kpoint->nky;\n    nk_tmp[2] = kpoint->nkz;\n    store_exponential_for_acceleration(nk_tmp, nk_represent, exp_phase, exp_phase3);\n\n    if (ks_analyze_mode) {\n\n        if (kpoint->kpoint_mode == 2 && use_triplet_symmetry) {\n            use_triplet_symmetry = false;\n            if (mympi->my_rank == 0) {\n                std::cout << std::endl;\n                std::cout << \" TRISYM was automatically set to 0.\" << std::endl;\n                std::cout << std::endl;\n            }\n        }\n\n        MPI_Bcast(&calc_realpart, 1, MPI_LOGICAL, 0, MPI_COMM_WORLD);\n        MPI_Bcast(&atom_project_mode, 1, MPI_LOGICAL, 0, MPI_COMM_WORLD);\n        MPI_Bcast(&calc_fstate_k, 1, MPI_LOGICAL, 0, MPI_COMM_WORLD);\n        MPI_Bcast(&calc_fstate_omega, 1, MPI_LOGICAL, 0, MPI_COMM_WORLD);\n\n        if (mympi->my_rank == 0) {\n            if (calc_fstate_omega) sym_permutation = false;\n        }\n        MPI_Bcast(&sym_permutation, 1, MPI_LOGICAL, 0, MPI_COMM_WORLD);\n\n        if (quartic_mode > 0) {\n\n            // This is for quartic vertexes.\n\n            if (mympi->my_rank == 0) {\n                std::cout << \" QUARTIC = 1 : Frequency shift due to the loop diagram associated with\" << std::endl;\n                std::cout << \"               quartic anharmonicity will be calculated.\" << std::endl;\n                std::cout << \"               Please check the accuracy of the quartic IFCs \" << std::endl;\n                std::cout << \"               before doing serious calculations.\" << std::endl;\n                std::cout << std::endl;\n            }\n\n            setup_quartic();\n        }\n\n        if (calc_realpart && integration->ismear != 0) {\n            error->exit(\"setup_relaxation\", \"Sorry. REALPART = 1 can be used only with ISMEAR = 0\");\n        }\n        \n        dynamical->modify_eigenvectors();\n    }\n    \n    if (kpoint->kpoint_mode == 2) {\n        generate_triplet_k(use_triplet_symmetry, sym_permutation);\n    }\n}\n\nvoid Relaxation::finish_relaxation()\n{\n    memory->deallocate(vec_for_v3);\n    memory->deallocate(invmass_for_v3);\n    memory->deallocate(evec_index);\n    memory->deallocate(fcs_group);\n\n    if (use_tuned_ver) {\n        if (tune_type == 0) {\n            memory->deallocate(exp_phase);\n        } else if (tune_type == 1) {\n            memory->deallocate(exp_phase3);\n        }\n    }\n\n    if (ks_analyze_mode && (quartic_mode > 0)) {\n        memory->deallocate(vec_for_v4);\n        memory->deallocate(invmass_for_v4);\n        memory->deallocate(evec_index4);\n        memory->deallocate(fcs_group2);\n    }\n}\n\n// void Relaxation::print_minimum_energy_diff()\n// {\n//     int i, j;\n//     unsigned int nk_near = 0;\n//     double domega_min;\n//     double dist_k_min, dist_k;\n//     double xk_tmp[3], xk_tmp2[3];\n//     int ik;\n// \n//     domega_min = 0.0;\n// \n//     if (nk > 1) {\n// \n//         for (i = 0; i < 3; ++i) {\n//             xk_tmp[i] = 0.5;\n//         }\n//         rotvec(xk_tmp2, xk_tmp, system->rlavec_p, 'T');\n//         dist_k_min = std::sqrt(xk_tmp2[0]*xk_tmp2[0] + xk_tmp2[1]*xk_tmp2[1] + xk_tmp2[2]*xk_tmp2[2]);\n// \n//         for (ik = 1; ik < nk; ++ik) {\n//             for (j = 0; j < 3; ++j) {\n//                 xk_tmp[j] = kpoint->xk[ik][j];\n//             }\n//             rotvec(xk_tmp2, xk_tmp, system->rlavec_p, 'T');\n// \n//             dist_k = std::sqrt(xk_tmp2[0]*xk_tmp2[0] + xk_tmp2[1]*xk_tmp2[1] + xk_tmp2[2]*xk_tmp2[2]);\n// \n//             if (dist_k <= dist_k_min) {\n//                 dist_k_min = dist_k;\n//                 nk_near = ik;\n//             }\n//         }\n//         domega_min =  writes->in_kayser(dynamical->eval_phonon[nk_near][0]);\t\n//     } else {\n//         std::cout << \"There is only 1 reciprocal point.\" << std::endl;\n//     }\n// \n//     std::cout << std::endl;\n//     std::cout << \" Estimated minimum energy difference (cm^-1) = \" << domega_min << std::endl;\n//     std::cout << std::endl;\n// }\n\nvoid Relaxation::prepare_relative_vector(std::vector<FcsArrayWithCell> fcs_in, const unsigned int N, double ***vec_out)\n{\n\n    int i, j, k;\n    int ix, iy, iz;\n\n    double vec[3];\n    double **xshift_s;\n\n    unsigned int icell;\n\n    std::vector<unsigned int> atm_super, atm_prim;\n    std::vector<unsigned int> xyz;\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    memory->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    unsigned int atm_p, atm_s;\n    unsigned int tran_tmp;\n    unsigned int icount = 0;\n\n    for (std::vector<FcsArrayWithCell>::const_iterator it = fcs_in.begin(); it != fcs_in.end(); ++it) {\n\n        atm_super.clear();\n        atm_prim.clear();\n        xyz.clear();\n        cells.clear();\n\n        for (i = 0; i < (*it).pairs.size(); ++i) {\n            atm_p = (*it).pairs[i].index / 3;\n            tran_tmp = (*it).pairs[i].tran;\n            atm_s = system->map_p2s_anharm[atm_p][tran_tmp];\n\n            atm_prim.push_back(atm_p);\n            atm_super.push_back(atm_s);\n            cells.push_back((*it).pairs[i].cell_s);\n        }\n\n\n        for (i = 0; i < N - 1; ++i) {\n\n            for (j = 0; j < 3; ++j) {\n                vec[j] = system->xr_s_anharm[atm_super[i + 1]][j] + xshift_s[cells[i + 1]][j] \n                - system->xr_s_anharm[system->map_p2s_anharm[atm_prim[i + 1]][0]][j];\n            }\n\n            rotvec(vec, vec, mat_convert);\n\n            for (j = 0; j < 3; ++j) {\n                vec_out[j][i][icount] = vec[j];\n            }\n        }\n        ++icount;\n    }\n    memory->deallocate(xshift_s);\n}\n\nvoid Relaxation::prepare_group_of_force_constants(std::vector<FcsArrayWithCell> fcs_in, const unsigned int N, \n                                                  int &number_of_groups, std::vector<double> *&fcs_group_out) \n{\n    // Find the number of groups which has different evecs.\n\n    unsigned int i;\n    number_of_groups = 0;\n\n\n    std::vector<int> arr_old, arr_tmp;\n\n    arr_old.clear();\n    for (i = 0; i < N; ++i) {\n        arr_old.push_back(-1);\n    }\n\n    for (std::vector<FcsArrayWithCell>::const_iterator it = fcs_in.begin(); it != fcs_in.end(); ++it) {\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    memory->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 (std::vector<FcsArrayWithCell>::const_iterator it = fcs_in.begin(); it != fcs_in.end(); ++it) {\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\nvoid Relaxation::setup_mode_analysis()\n{\n    // Judge if ks_analyze_mode should be turned on or not.\n\n    unsigned int i;\n\n    if (mympi->my_rank == 0) {\n        if (!ks_input.empty()) {\n            std::cout << std::endl;\n            std::cout << \" KS_INPUT-tag is given : Analysis on the specified phonon modes\" << std::endl;\n            std::cout << \" will be performed instead of thermal conductivity calculation.\" << std::endl;\n            std::cout << std::endl;\n\n            std::ifstream ifs_ks;\n            ifs_ks.open(ks_input.c_str(), std::ios::in);\n            if (!ifs_ks) error->exit(\"setup_mode_analysis\", \"Cannot open file KS_INPUT\");\n\n            unsigned int nlist;\n            double ktmp[3];\n            unsigned int snum_tmp;\n            int knum_tmp;\n\n            ifs_ks >> nlist;\n\n            if (nlist <= 0) error->exit(\"setup_mode_analysis\", \n                \"First line in KS_INPUT files should be a positive integer.\");\n\n            if (calc_fstate_k) {\n                kslist_fstate_k.clear();\n\n                for (i = 0; i < nlist; ++i) {\n\n                    ifs_ks >> ktmp[0] >> ktmp[1] >> ktmp[2] >> snum_tmp;\n\n                    if (snum_tmp <= 0 || snum_tmp > dynamical->neval) {\n                        error->exit(\"setup_mode_analysis\", \"Mode index out of range.\");\n                    }\n\n                    kslist_fstate_k.push_back(KsListMode(ktmp, snum_tmp - 1));\n                }\n                std::cout << \" The number of entries = \" << kslist_fstate_k.size() << std::endl;\n\n            } else {\n                kslist.clear();\n                for (i = 0; i < nlist; ++i) {\n\n                    ifs_ks >> ktmp[0] >> ktmp[1] >> ktmp[2] >> snum_tmp;\n                    knum_tmp = kpoint->get_knum(ktmp[0], ktmp[1], ktmp[2]);\n\n                    if (knum_tmp == -1) error->exit(\"setup_mode_analysis\", \n                        \"Given kpoint does not exist in given k-point grid.\");\n                    if (snum_tmp <= 0 || snum_tmp > dynamical->neval) {\n                        error->exit(\"setup_mode_analysis\", \"Mode index out of range.\");\n                    }\n                    kslist.push_back(knum_tmp * dynamical->neval + snum_tmp - 1);\n                }\n                std::cout << \" The number of entries = \" << kslist.size() << std::endl;\n            }\n\n            ks_analyze_mode = true;\n            ifs_ks.close();\n\n        } else {\n\n            ks_analyze_mode = false;\n\n        }\n    }\n    MPI_Bcast(&ks_analyze_mode, 1, MPI_LOGICAL, 0, MPI_COMM_WORLD);\n\n    unsigned int *kslist_arr;\n    unsigned int nlist;\n    double **vec_tmp;\n    unsigned int *mode_tmp;\n\n    if (kpoint->kpoint_mode == 3) {\n        int j;\n\n        // Broadcast kslist_fstate_k\n\n        nlist = kslist_fstate_k.size();\n        MPI_Bcast(&nlist, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);\n\n        memory->allocate(vec_tmp, nlist, 3);\n        memory->allocate(mode_tmp, nlist);\n\n        if (mympi->my_rank == 0) {\n            for (i = 0; i < nlist; ++i) {\n                for (j = 0; j < 3; ++j) {\n                    vec_tmp[i][j] = kslist_fstate_k[i].xk[j];\n                }\n                mode_tmp[i] = kslist_fstate_k[i].nmode;\n            }\n        }\n\n        MPI_Bcast(&vec_tmp[0][0], 3 * nlist, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n        MPI_Bcast(&mode_tmp[0], nlist, MPI_INT, 0, MPI_COMM_WORLD);\n\n        if (mympi->my_rank > 0) {\n            kslist_fstate_k.clear();\n\n            for (i = 0; i < nlist; ++i) {\n                kslist_fstate_k.push_back(KsListMode(vec_tmp[i], mode_tmp[i]));\n            }\n        }\n\n        memory->deallocate(vec_tmp);\n        memory->deallocate(mode_tmp);\n\n    } else {\n        nlist = kslist.size();\n\n        // Broadcast kslist\n\n        MPI_Bcast(&nlist, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);\n        memory->allocate(kslist_arr, nlist);\n\n        if (mympi->my_rank == 0) {\n            for (i = 0; i < nlist; ++i) kslist_arr[i] = kslist[i];\n        }\n        MPI_Bcast(&kslist_arr[0], nlist, MPI_UNSIGNED, 0, MPI_COMM_WORLD);\n\n        if (mympi->my_rank > 0) {\n            kslist.clear();\n            for (i = 0; i < nlist; ++i) kslist.push_back(kslist_arr[i]);\n        }\n        memory->deallocate(kslist_arr);\n    }\n}\n\nstd::complex<double> Relaxation::V3(const unsigned int ks[3])\n{\n    unsigned int i, j, ielem;\n    unsigned int kn[3], sn[3];\n    unsigned int nsize_group;\n\n    double phase, omega[3];\n    double phase3[3];\n\n    std::complex<double> ret = std::complex<double>(0.0, 0.0);\n    std::complex<double> ret_in, vec_tmp;\n\n    int iloc, loc[3];\n    int ii;\n    double inv2pi = 1.0 / (2.0 * pi);\n    double dnk_represent = static_cast<double>(nk_represent);\n\n    for (i = 0; i < 3; ++i){\n        kn[i] = ks[i] / ns;\n        sn[i] = ks[i] % ns;\n        omega[i] = dynamical->eval_phonon[kn[i]][sn[i]];\n    }\n\n    ielem = 0;\n\n    if (use_tuned_ver) {\n        if (tune_type == 0) {\n\n            // Tuned version used when nk1=nk2=nk3.\n            for (i = 0; i < ngroup; ++i) {\n\n                vec_tmp = dynamical->evec_phonon[kn[0]][sn[0]][evec_index[ielem][0]] \n                * dynamical->evec_phonon[kn[1]][sn[1]][evec_index[ielem][1]]\n                * dynamical->evec_phonon[kn[2]][sn[2]][evec_index[ielem][2]];\n\n                ret_in = std::complex<double>(0.0, 0.0);\n\n                nsize_group = fcs_group[i].size();\n\n                for (j = 0; j < nsize_group; ++j) {\n\n                    phase = vec_for_v3[0][0][ielem] * kpoint->xk[kn[1]][0] \n                    + vec_for_v3[1][0][ielem] * kpoint->xk[kn[1]][1]\n                    + vec_for_v3[2][0][ielem] * kpoint->xk[kn[1]][2]\n                    + vec_for_v3[0][1][ielem] * kpoint->xk[kn[2]][0] \n                    + vec_for_v3[1][1][ielem] * kpoint->xk[kn[2]][1] \n                    + vec_for_v3[2][1][ielem] * kpoint->xk[kn[2]][2];\n\n                    iloc = nint(phase * dnk_represent * inv2pi) % nk_represent + nk_represent - 1;\n\n                    ret_in += fcs_group[i][j] * invmass_for_v3[ielem] * exp_phase[iloc];\n\n                    ++ielem;\n                }\n                ret += ret_in * vec_tmp;\n            }\n        } else if (tune_type == 1) {\n\n            // Tuned version used when nk1=nk2=nk3 is not met.\n            for (i = 0; i < ngroup; ++i) {\n\n                vec_tmp = dynamical->evec_phonon[kn[0]][sn[0]][evec_index[ielem][0]] \n                * dynamical->evec_phonon[kn[1]][sn[1]][evec_index[ielem][1]]\n                * dynamical->evec_phonon[kn[2]][sn[2]][evec_index[ielem][2]];\n\n                ret_in = std::complex<double>(0.0, 0.0);\n\n                nsize_group = fcs_group[i].size();\n\n                for (j = 0; j < nsize_group; ++j) {\n\n                    for (ii = 0; ii < 3; ++ii) {\n                        phase3[ii] = vec_for_v3[ii][0][ielem] * kpoint->xk[kn[1]][ii] \n                        + vec_for_v3[ii][1][ielem] * kpoint->xk[kn[2]][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[i][j] * invmass_for_v3[ielem] * exp_phase3[loc[0]][loc[1]][loc[2]];\n\n                    ++ielem;\n                }\n                ret += ret_in * vec_tmp;\n            }\n        } \n\n    } else {\n        // Original version\n        for (i = 0; i < ngroup; ++i) {\n\n            vec_tmp = dynamical->evec_phonon[kn[0]][sn[0]][evec_index[ielem][0]] \n            * dynamical->evec_phonon[kn[1]][sn[1]][evec_index[ielem][1]]\n            * dynamical->evec_phonon[kn[2]][sn[2]][evec_index[ielem][2]];\n\n            ret_in = std::complex<double>(0.0, 0.0);\n\n            nsize_group = fcs_group[i].size();\n\n            for (j = 0; j < nsize_group; ++j) {\n\n                phase = vec_for_v3[0][0][ielem] * kpoint->xk[kn[1]][0] \n                + vec_for_v3[1][0][ielem] * kpoint->xk[kn[1]][1]\n                + vec_for_v3[2][0][ielem] * kpoint->xk[kn[1]][2]\n                + vec_for_v3[0][1][ielem] * kpoint->xk[kn[2]][0] \n                + vec_for_v3[1][1][ielem] * kpoint->xk[kn[2]][1] \n                + vec_for_v3[2][1][ielem] * kpoint->xk[kn[2]][2];\n\n                ret_in += fcs_group[i][j] * invmass_for_v3[ielem] * std::exp(im*phase);\n\n                ++ielem;\n            }\n            ret += ret_in * vec_tmp;\n        }\n    }\n\n    return ret / std::sqrt(omega[0] * omega[1] * omega[2]);\n}\n\n\nstd::complex<double> Relaxation::V4(const unsigned int ks[4]) \n{\n    int ii;\n    unsigned int i, j, ielem;\n    unsigned int kn[4], sn[4];\n\n    double phase, phase3[3];\n    double omega[4];\n\n    std::complex<double> ctmp, ret_in, vec_tmp;\n    std::complex<double> ret = std::complex<double>(0.0, 0.0);\n\n    int iloc, loc[3];\n    double inv2pi = 1.0 / (2.0 * pi);\n    double dnk_represent = static_cast<double>(nk_represent);\n\n    for (i = 0; i < 4; ++i){\n        kn[i] = ks[i] / ns;\n        sn[i] = ks[i] % ns;\n        omega[i] = dynamical->eval_phonon[kn[i]][sn[i]];\n    }\n\n    ielem = 0;\n\n    if (use_tuned_ver) {\n        if (tune_type == 0) {\n            for (i = 0; i < ngroup2; ++i) {\n\n                vec_tmp = dynamical->evec_phonon[kn[0]][sn[0]][evec_index4[ielem][0]] \n                * dynamical->evec_phonon[kn[1]][sn[1]][evec_index4[ielem][1]]\n                * dynamical->evec_phonon[kn[2]][sn[2]][evec_index4[ielem][2]]\n                * dynamical->evec_phonon[kn[3]][sn[3]][evec_index4[ielem][3]];\n\n                ret_in = std::complex<double>(0.0, 0.0);\n\n                for (j = 0; j < fcs_group2[i].size(); ++j) {\n                    phase =\n                        vec_for_v4[0][0][ielem] * kpoint->xk[kn[1]][0] \n                    + vec_for_v4[1][0][ielem] * kpoint->xk[kn[1]][1] \n                    + vec_for_v4[2][0][ielem] * kpoint->xk[kn[1]][2]\n                    + vec_for_v4[0][1][ielem] * kpoint->xk[kn[2]][0] \n                    + vec_for_v4[1][1][ielem] * kpoint->xk[kn[2]][1] \n                    + vec_for_v4[2][1][ielem] * kpoint->xk[kn[2]][2]\n                    + vec_for_v4[0][2][ielem] * kpoint->xk[kn[3]][0] \n                    + vec_for_v4[1][2][ielem] * kpoint->xk[kn[3]][1] \n                    + vec_for_v4[2][2][ielem] * kpoint->xk[kn[3]][2];\n\n                    iloc = nint(phase * dnk_represent * inv2pi) % nk_represent + nk_represent - 1;\n\n                    ctmp = fcs_group2[i][j] * invmass_for_v4[ielem] * exp_phase[iloc];\n                    ret_in += ctmp;\n\n                    ++ielem;\n                }\n                ret += ret_in * vec_tmp;\n            }\n        } else if (tune_type == 1) {\n            for (i = 0; i < ngroup2; ++i) {\n\n                vec_tmp = dynamical->evec_phonon[kn[0]][sn[0]][evec_index4[ielem][0]] \n                * dynamical->evec_phonon[kn[1]][sn[1]][evec_index4[ielem][1]]\n                * dynamical->evec_phonon[kn[2]][sn[2]][evec_index4[ielem][2]]\n                * dynamical->evec_phonon[kn[3]][sn[3]][evec_index4[ielem][3]];\n\n                ret_in = std::complex<double>(0.0, 0.0);\n\n                for (j = 0; j < fcs_group2[i].size(); ++j) {\n\n                    for (ii = 0; ii < 3; ++ii) {\n                        phase3[ii] = vec_for_v4[ii][0][ielem] * kpoint->xk[kn[1]][ii]\n                        + vec_for_v4[ii][1][ielem] * kpoint->xk[kn[2]][ii] \n                        + vec_for_v4[ii][2][ielem] * kpoint->xk[kn[3]][ii];\n                       \n                        loc[ii] = nint(phase3[ii] * dnk[ii] * inv2pi) % nk_grid[ii] + nk_grid[ii] - 1;\n                    }\n\n                    ctmp = fcs_group2[i][j] * invmass_for_v4[ielem] * exp_phase3[loc[0]][loc[1]][loc[2]];\n                    ret_in += ctmp;\n\n                    ++ielem;\n                }\n                ret += ret_in * vec_tmp;\n            }\n        }\n\n    } else {\n        for (i = 0; i < ngroup2; ++i) {\n\n            vec_tmp = dynamical->evec_phonon[kn[0]][sn[0]][evec_index4[ielem][0]] \n            * dynamical->evec_phonon[kn[1]][sn[1]][evec_index4[ielem][1]]\n            * dynamical->evec_phonon[kn[2]][sn[2]][evec_index4[ielem][2]]\n            * dynamical->evec_phonon[kn[3]][sn[3]][evec_index4[ielem][3]];\n\n            ret_in = std::complex<double>(0.0, 0.0);\n\n            for (j = 0; j < fcs_group2[i].size(); ++j) {\n                phase =\n                    vec_for_v4[0][0][ielem] * kpoint->xk[kn[1]][0] \n                + vec_for_v4[1][0][ielem] * kpoint->xk[kn[1]][1] \n                + vec_for_v4[2][0][ielem] * kpoint->xk[kn[1]][2]\n                + vec_for_v4[0][1][ielem] * kpoint->xk[kn[2]][0] \n                + vec_for_v4[1][1][ielem] * kpoint->xk[kn[2]][1] \n                + vec_for_v4[2][1][ielem] * kpoint->xk[kn[2]][2]\n                + vec_for_v4[0][2][ielem] * kpoint->xk[kn[3]][0] \n                + vec_for_v4[1][2][ielem] * kpoint->xk[kn[3]][1] \n                + vec_for_v4[2][2][ielem] * kpoint->xk[kn[3]][2];\n\n                ctmp = fcs_group2[i][j] * invmass_for_v4[ielem] * std::exp(im * phase);\n                ret_in += ctmp;\n\n                ++ielem;\n            }\n            ret += ret_in * vec_tmp;\n        }\n    }\n    \n\n    return ret / std::sqrt(omega[0] * omega[1] * omega[2] * omega[3]);\n}\n\n\nstd::complex<double> Relaxation::V3_mode(int mode, double *xk2, double *xk3, \n                                         int is, int js, double **eval, std::complex<double> ***evec)\n{\n    int ielem;\n\n    double phase;\n    std::complex<double> ctmp = std::complex<double>(0.0, 0.0);\n\n    for (ielem = 0; ielem < fcs_phonon->force_constant_with_cell[1].size(); ++ielem) {\n\n        phase = vec_for_v3[0][0][ielem] * xk2[0] \n        + vec_for_v3[1][0][ielem] * xk2[1]\n        + vec_for_v3[2][0][ielem] * xk2[2] \n        + vec_for_v3[0][1][ielem] * xk3[0]\n        + vec_for_v3[1][1][ielem] * xk3[1]\n        + vec_for_v3[2][1][ielem] * xk3[2];\n\n\n        ctmp += fcs_phonon->force_constant_with_cell[1][ielem].fcs_val * invmass_for_v3[ielem] * std::exp(im * phase)\n            * evec[0][mode][evec_index[ielem][0]] * evec[1][is][evec_index[ielem][1]] * evec[2][js][evec_index[ielem][2]];\n    }\n\n    return ctmp / std::sqrt(eval[0][mode] * eval[1][is] * eval[2][js]);\n}\n\n// \n// void Relaxation::calc_realpart_V4(const unsigned int N, double *T, const double omega, \n//                                   const unsigned int knum, const unsigned int snum, double *ret)\n// {\n//     unsigned int i, ik, is;\n//     unsigned int arr[4];\n//     double n1, omega1;\n//     double v4_tmp, T_tmp;\n// \n//     for (i = 0; i < N; ++i) ret[i] = 0.0;\n// \n//     arr[0] = ns * kpoint->knum_minus[knum] + snum;\n//     arr[1] = ns * knum + snum;\n// \n//     for (ik = 0; ik < nk; ++ik) {\n//         for (is = 0; is < ns; ++is) {\n// \n//             arr[2] = ns * ik + is;\n//             arr[3] = ns * kpoint->knum_minus[ik] + is;\n// \n//             v4_tmp = V4(arr).real();\n// \n//             omega1 = dynamical->eval_phonon[ik][is];\n// \n//             for (i = 0; i < N; ++i) {\n//                 T_tmp = T[i];\n//                 n1 = phonon_thermodynamics->fB(omega1, T_tmp);\n// \n//                 ret[i] += v4_tmp * (2.0 * n1 + 1.0);\n//             }\n//         }\n//     }\n// \n//     for (i = 0; i < N; ++i) ret[i] *= - 1.0 / (8.0 * static_cast<double>(nk));\n// }\n\n\nvoid Relaxation::calc_damping_smearing(const unsigned int N, double *T, const double omega, \n                                       const unsigned int ik_in, const unsigned int snum, double *ret)\n{\n    // This function returns the imaginary part of phonon self-energy \n    // for the given frequency omega.\n    // Lorentzian or Gaussian smearing will be used.\n    // This version employs the crystal symmetry to reduce the computational cost\n\n    unsigned int i;\n    int ik;\n    unsigned int is, js; \n    unsigned int arr[3];\n\n    int k1, k2;\n    int npair_uniq;\n\n    double T_tmp;\n    double n1, n2;\n    double omega_inner[2];\n\n    int knum, knum_minus;\n    double multi;\n\n    for (i = 0; i < N; ++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    double epsilon = integration->epsilon;\n\n    npair_uniq = pair_uniq[ik_in].size();\n\n    memory->allocate(v3_arr, npair_uniq, ns * ns);\n    memory->allocate(delta_arr, npair_uniq, ns * ns, 2);\n\n    knum = kpoint->kpoint_irred_all[ik_in][0].knum;\n    knum_minus = kpoint->knum_minus[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 < pair_uniq[ik_in].size(); ++ik) {\n        multi = static_cast<double>(pair_uniq[ik_in][ik].group.size());\n\n        arr[0] = ns * knum_minus + snum;\n\n        k1 = pair_uniq[ik_in][ik].group[0].ks[0];\n        k2 = pair_uniq[ik_in][ik].group[0].ks[1];\n\n        for (is = 0; is < ns; ++is) {\n            arr[1] = ns * k1 + is;\n            omega_inner[0] = dynamical->eval_phonon[k1][is];\n\n            for (js = 0; js < ns; ++js) {\n                arr[2] = ns * k2 + js;\n                omega_inner[1] = dynamical->eval_phonon[k2][js];\n           \n                v3_arr[ik][ns * is + js] = std::norm(V3(arr)) * multi;\n\n                if (integration->ismear == 0) {\n                    delta_arr[ik][ns * is + js][0] = delta_lorentz(omega - omega_inner[0] - omega_inner[1], epsilon)\n                        - delta_lorentz(omega + omega_inner[0] + omega_inner[1], epsilon);\n                    delta_arr[ik][ns * is + js][1] = delta_lorentz(omega - omega_inner[0] + omega_inner[1], epsilon)\n                        - delta_lorentz(omega + omega_inner[0] - omega_inner[1], epsilon);\n                } else if (integration->ismear == 1) {\n                    delta_arr[ik][ns * is + js][0] = delta_gauss(omega - omega_inner[0] - omega_inner[1], epsilon)\n                        - delta_gauss(omega + omega_inner[0] + omega_inner[1], epsilon);\n                    delta_arr[ik][ns * is + js][1] = delta_gauss(omega - omega_inner[0] + omega_inner[1], epsilon)\n                        - delta_gauss(omega + omega_inner[0] - omega_inner[1], epsilon);\n                }\n            }\n        }   \n    }\n\n    for (i = 0; i < N; ++i) {\n        T_tmp = T[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 = pair_uniq[ik_in][ik].group[0].ks[0];\n            k2 = pair_uniq[ik_in][ik].group[0].ks[1];\n\n            for (is = 0; is < ns; ++is){\n\n                omega_inner[0] = dynamical->eval_phonon[k1][is];\n                f1 = thermodynamics->fB(omega_inner[0], T_tmp);\n\n                for (js = 0; js < ns; ++js) {\n\n                    omega_inner[1] = dynamical->eval_phonon[k2][js];\n                    f2 = thermodynamics->fB(omega_inner[1], T_tmp);\n\n                    n1 =  f1 + f2 + 1.0;\n                    n2 =  f1 - f2;\n\n                    ret_tmp += v3_arr[ik][ns * is + js] \n                    * (n1 * delta_arr[ik][ns * is + js][0] - n2 * delta_arr[ik][ns * is + js][1]);\n                }\n            }\n        }\n        ret[i] = ret_tmp;\n    }\n\n    memory->deallocate(v3_arr);\n    memory->deallocate(delta_arr);\n\n    for (i = 0; i < N; ++i) ret[i] *=  pi * std::pow(0.5, 4) / static_cast<double>(nk);\n}\n\nvoid Relaxation::calc_damping_tetrahedron(const unsigned int N, double *T, const double omega, \n                                          const unsigned int ik_in, const unsigned int snum, double *ret)\n{\n    // This function returns the imaginary part of phonon self-energy \n    // for the given frequency omega.\n    // Tetrahedron method will be used.\n    // This version employs the crystal symmetry to reduce the computational cost\n\n    int ik, ib;\n    int 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    unsigned int npair_uniq;\n\n    int knum, knum_minus;\n\n    double T_tmp;\n    double n1, n2;\n    double f1, f2;\n\n    double xk_tmp[3];\n    double omega_inner[2];\n\n    double ret_tmp;\n    double epsilon = integration->epsilon;\n\n    int *kmap_identity;\n    double **energy_tmp;\n    double **weight_tetra;\n    double **v3_arr;\n    double ***delta_arr;\n\n\n    for (i = 0; i < N; ++i) ret[i] = 0.0;\n\n    npair_uniq = pair_uniq[ik_in].size();\n\n    memory->allocate(v3_arr, npair_uniq, ns2);\n    memory->allocate(delta_arr, npair_uniq, ns2, 2);\n\n    knum = kpoint->kpoint_irred_all[ik_in][0].knum;\n    knum_minus = kpoint->knum_minus[knum];\n\n    memory->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        memory->allocate(energy_tmp, 3, nk);\n        memory->allocate(weight_tetra, 3, nk);\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 tetrahedron method\n\n                for (i = 0; i < 3; ++i) xk_tmp[i] = kpoint->xk[knum][i] - kpoint->xk[k1][i];\n\n                k2 = kpoint->get_knum(xk_tmp[0], xk_tmp[1], xk_tmp[2]);\n\n                energy_tmp[0][k1] = dynamical->eval_phonon[k1][is] + dynamical->eval_phonon[k2][js];\n                energy_tmp[1][k1] = dynamical->eval_phonon[k1][is] - dynamical->eval_phonon[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, weight_tetra[i], energy_tmp[i], omega);\n            }\n\n            for (ik = 0; ik < npair_uniq; ++ik) {\n\n                k1 = pair_uniq[ik_in][ik].group[0].ks[0];\n                k2 = pair_uniq[ik_in][ik].group[0].ks[1];\n\n                arr[0] = ns * knum_minus + snum;\n                arr[1] = ns * k1 + is;\n                arr[2] = ns * k2 + js;\n              \n                v3_arr[ik][ib] = std::norm(V3(arr));\n\n                delta_arr[ik][ib][0] = 0.0;\n                delta_arr[ik][ib][1] = 0.0;\n\n                for (i = 0; i < pair_uniq[ik_in][ik].group.size(); ++i) {\n                    jk = pair_uniq[ik_in][ik].group[i].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\n        memory->deallocate(energy_tmp);\n        memory->deallocate(weight_tetra);\n    }\n\n\n    for (i = 0; i < N; ++i) {\n        T_tmp = T[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 = pair_uniq[ik_in][ik].group[0].ks[0];\n            k2 = pair_uniq[ik_in][ik].group[0].ks[1];\n\n            for (is = 0; is < ns; ++is){\n\n                omega_inner[0] = dynamical->eval_phonon[k1][is];\n                f1 = thermodynamics->fB(omega_inner[0], T_tmp);\n\n                for (js = 0; js < ns; ++js) {\n\n                    omega_inner[1] = dynamical->eval_phonon[k2][js];\n                    f2 = thermodynamics->fB(omega_inner[1], T_tmp);\n\n                    n1 =  f1 + f2 + 1.0;\n                    n2 =  f1 - f2;\n\n                    ret_tmp += v3_arr[ik][ns * is + js] \n                    * (n1 * delta_arr[ik][ns * is + js][0] - n2 * delta_arr[ik][ns * is + js][1]);\n                }\n            }\n        }\n        ret[i] = ret_tmp;\n    }\n\n    memory->deallocate(v3_arr);\n    memory->deallocate(delta_arr);\n    memory->deallocate(kmap_identity);\n\n    for (i = 0; i < N; ++i) ret[i] *=  pi * std::pow(0.5, 4);\n\n}\n\n\nvoid Relaxation::calc_frequency_resolved_final_state(const unsigned int N, double *T, const double omega0, \n                                                     const unsigned int M, const double *omega, const unsigned int ik_in, const unsigned int snum, double **ret)\n{\n    int i, j, ik;\n\n    double multi;\n    int knum, knum_minus;\n    int k1, k2;\n    int is, js;\n    unsigned int arr[3];\n    double omega_inner[2];\n    double v3_tmp;\n    double T_tmp;\n    double n1, n2;\n    double f1, f2;\n    double prod_tmp[2];\n    double **ret_mpi;\n\n    double epsilon = integration->epsilon;\n\n    memory->allocate(ret_mpi, N, M);\n\n    for (i = 0; i < N; ++i) {\n        for (j = 0; j < M; ++j) {\n            ret_mpi[i][j] = 0.0;\n        }\n    }\n\n    for (ik = mympi->my_rank; ik < pair_uniq[ik_in].size(); ik += mympi->nprocs) {\n\n        multi = static_cast<double>(pair_uniq[ik_in][ik].group.size());\n        knum = kpoint->kpoint_irred_all[ik_in][0].knum;\n        knum_minus = kpoint->knum_minus[knum];\n\n        arr[0] = ns * knum_minus + snum;\n\n        k1 = pair_uniq[ik_in][ik].group[0].ks[0];\n        k2 = pair_uniq[ik_in][ik].group[0].ks[1];\n\n        for (is = 0; is < ns; ++is) {\n            for (js = 0; js < ns; ++js) {\n                arr[1] = ns * k1 + is;\n                arr[2] = ns * k2 + js;\n\n                omega_inner[0] = dynamical->eval_phonon[k1][is];\n                omega_inner[1] = dynamical->eval_phonon[k2][js];\n\n                v3_tmp = std::norm(V3(arr));\n\n                for (i = 0; i < N; ++i) {\n                    T_tmp = T[i];\n\n                    f1 = thermodynamics->fB(omega_inner[0], T_tmp);\n                    f2 = thermodynamics->fB(omega_inner[1], T_tmp);\n                    n1 = f1 + f2 + 1.0;\n                    n2 = f1 - f2;\n\n                    if (integration->ismear == 0) {\n                        prod_tmp[0] = n1 * (delta_lorentz(omega0 - omega_inner[0] - omega_inner[1], epsilon) \n                            - delta_lorentz(omega0 + omega_inner[0] + omega_inner[1], epsilon));\n                        prod_tmp[1] = n2 * (delta_lorentz(omega0 + omega_inner[0] - omega_inner[1], epsilon)\n                            - delta_lorentz(omega0 - omega_inner[0] + omega_inner[1], epsilon));\n\n                        for (j = 0; j < M; ++j) {\n                            ret_mpi[i][j] += v3_tmp * multi * delta_lorentz(omega[j] - omega_inner[0], epsilon)\n                                * (prod_tmp[0] + prod_tmp[1]);\n                        }\n                    } else if (integration->ismear == 1) {\n                        prod_tmp[0] = n1 * (delta_gauss(omega0 - omega_inner[0] - omega_inner[1], epsilon) \n                            - delta_gauss(omega0 + omega_inner[0] + omega_inner[1], epsilon));\n                        prod_tmp[1] = n2 * (delta_gauss(omega0 + omega_inner[0] - omega_inner[1], epsilon)\n                            - delta_gauss(omega0 - omega_inner[0] + omega_inner[1], epsilon));\n\n                        for (j = 0; j < M; ++j) {\n                            ret_mpi[i][j] += v3_tmp * multi * delta_gauss(omega[j] - omega_inner[0], epsilon)\n                                * (prod_tmp[0] + prod_tmp[1]);\n                        }\n                    }\n\n                }\n            }\n        }\n    }\n    for (i = 0; i < N; ++i) {\n        for (j = 0; j < M; ++j) {\n            ret_mpi[i][j] *=  pi * std::pow(0.5, 4) / static_cast<double>(nk);\n        }\n    }\n\n    MPI_Reduce(&ret_mpi[0][0], &ret[0][0], N*M, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);\n\n    memory->deallocate(ret_mpi);\n}\n\n\nvoid Relaxation::perform_mode_analysis()\n{\n    unsigned int i, j;\n    unsigned int NT;\n    unsigned int knum, snum;\n\n    double Tmax = system->Tmax;\n    double Tmin = system->Tmin;\n    double dT = system->dT;\n    double omega;\n    double *T_arr;\n\n    std::ofstream ofs_linewidth, ofs_shift, ofs_fstate_w;\n    std::string file_linewidth, file_shift, file_fstate_w;\n\n\n    NT = static_cast<unsigned int>((Tmax - Tmin) / dT) + 1;\n    memory->allocate(T_arr, NT);\n    for (i = 0; i < NT; ++i) T_arr[i] = Tmin + static_cast<double>(i)*dT;\n\n    double epsilon = integration->epsilon;\n\n    if (print_V3) {\n\n        double **v3norm;\n        std::string file_V3;\n        std::ofstream ofs_V3;\n\n        int ik_irred;\n        unsigned int nk_size;\n        unsigned int ib, is, js, k1, k2;\n\n        for (i = 0; i < kslist.size(); ++i) {\n            knum = kslist[i] / ns;\n            snum = kslist[i] % ns;\n\n            omega = dynamical->eval_phonon[knum][snum];\n\n            if (mympi->my_rank == 0) {\n                std::cout << std::endl;\n                std::cout << \" Number : \" << std::setw(5) << i + 1 << std::endl;\n                std::cout << \"  Phonon at k = (\";\n                for (j = 0; j < 3; ++j) {\n                    std::cout << std::setw(10) << std::fixed << kpoint->xk[knum][j];\n                    if (j < 2) std::cout << \",\";\n                }\n                std::cout << \")\" << std::endl;\n                std::cout << \"  Mode index = \" << std::setw(5) << snum + 1 << std::endl;\n                std::cout << \"  Frequency (cm^-1) : \" << std::setw(15) << writes->in_kayser(omega) << std::endl;\n            }\n\n            ik_irred = kpoint->kmap_to_irreducible[knum];\n            nk_size = pair_uniq[ik_irred].size();\n\n            memory->allocate(v3norm, nk_size, ns * ns);\n\n            calc_V3norm2(ik_irred, snum, v3norm);\n\n            if (mympi->my_rank == 0) {\n\n                file_V3 = input->job_title + \".V3.\" + boost::lexical_cast<std::string>(i + 1);\n                ofs_V3.open(file_V3.c_str(), std::ios::out);\n                if (!ofs_V3) error->exit(\"perform_mode_analysis\", \"Cannot open file file_V3\");\n\n                ofs_V3 << \"# xk = \";\n\n                for (j = 0; j < 3; ++j) {\n                    ofs_V3 << std::setw(15) << kpoint->xk[knum][j];\n                }\n                ofs_V3 << std::endl;\n                ofs_V3 << \"# mode = \" << snum + 1<< std::endl;\n                ofs_V3 << \"# Frequency = \" << writes->in_kayser(omega) << std::endl;\n                ofs_V3 << \"## Matrix elements |V3|^2 for given mode\" << std::endl;\n                ofs_V3 << \"## q', j', omega(q'j') (cm^-1), q'', j'', omega(q''j'') (cm^-1), |V3(-qj,q'j',q''j'')| (cm^-2)\" << std::endl;\n\n                for (j = 0; j < nk_size; ++j) {\n\n                    k1 = pair_uniq[ik_irred][j].group[0].ks[0];\n                    k2 = pair_uniq[ik_irred][j].group[0].ks[1];\n\n                    ib = 0;\n\n                    for (is = 0; is < ns; ++is) {\n                        for (js = 0; js < ns; ++js) {\n                            ofs_V3 << std::setw(5) << k1 + 1 << std::setw(5) << is + 1;\n                            ofs_V3 << std::setw(15) << writes->in_kayser(dynamical->eval_phonon[k1][is]);\n                            ofs_V3 << std::setw(5) << k2 + 1 << std::setw(5) << js + 1;\n                            ofs_V3 << std::setw(15) << writes->in_kayser(dynamical->eval_phonon[k2][js]);\n                            ofs_V3 << std::setw(15) << v3norm[j][ib];\n                            ofs_V3 << std::endl;\n\n                            ++ib;\n                        }\n                        ofs_V3 << std::endl;\n                    }\n                }\n\n                ofs_V3.close();\n\n            }\n            memory->deallocate(v3norm);\n        }\n\n    } else if (calc_fstate_k) {\n\n        // Momentum-resolved final state amplitude\n        print_momentum_resolved_final_state(NT, T_arr, epsilon);\n\n    } else if (calc_fstate_omega) {\n\n        print_frequency_resolved_final_state(NT, T_arr);\n\n    } else {\n\n        double *damping_a;\n        double omega_shift;\n        std::complex<double> *self_tadpole;\n        std::complex<double> *self_a, *self_b, *self_c, *self_d, *self_e;\n        std::complex<double> *self_f, *self_g, *self_h, *self_i, *self_j;\n\n        if (mympi->my_rank == 0) {\n            std::cout << std::endl;\n            std::cout << \" Calculate the line width (FWHM) of phonons\" << std::endl;\n            std::cout << \" due to 3-phonon interactions for given \" << kslist.size() << \" modes.\" << std::endl;\n\n            if (calc_realpart) {\n                if (quartic_mode == 1) {\n                    std::cout << \" REALPART = 1 and \" << std::endl;\n                    std::cout << \" QUARTIC  = 1     : Additionally, frequency shift of phonons due to 3-phonon\" << std::endl;\n                    std::cout << \"                    and 4-phonon interactions will be calculated.\" << std::endl;\n                } else {\n                    std::cout << \" REALPART = 1 : Additionally, frequency shift of phonons due to 3-phonon\" << std::endl;\n                    std::cout << \"                interactions will be calculated.\" << std::endl;\n                }\n            }\n\n            if (quartic_mode == 2) {\n                std::cout << std::endl;\n                std::cout << \" QUARTIC = 2 : Additionally, phonon line width due to 4-phonon\" << std::endl;\n                std::cout << \"               interactions will be calculated.\" << std::endl;\n                std::cout << \" WARNING     : This is very very expensive.\" << std::endl;\n            }\n        }\n\n        memory->allocate(damping_a, NT);\n        memory->allocate(self_a, NT);\n        memory->allocate(self_b, NT);\n        memory->allocate(self_tadpole, NT);\n\n        if (quartic_mode == 2) {\n            memory->allocate(self_c, NT);\n            memory->allocate(self_d, NT);\n            memory->allocate(self_e, NT);\n            memory->allocate(self_f, NT);\n            memory->allocate(self_g, NT);\n            memory->allocate(self_h, NT);\n            memory->allocate(self_i, NT);\n            memory->allocate(self_j, NT);\n        }\n\n        for (i = 0; i < kslist.size(); ++i) {\n            knum = kslist[i] / ns;\n            snum = kslist[i] % ns;\n\n            omega = dynamical->eval_phonon[knum][snum];\n\n            if (mympi->my_rank == 0) {\n                std::cout << std::endl;\n                std::cout << \" Number : \" << std::setw(5) << i + 1 << std::endl;\n                std::cout << \"  Phonon at k = (\";\n                for (j = 0; j < 3; ++j) {\n                    std::cout << std::setw(10) << std::fixed << kpoint->xk[knum][j];\n                    if (j < 2) std::cout << \",\";\n                }\n                std::cout << \")\" << std::endl;\n                std::cout << \"  Mode index = \" << std::setw(5) << snum + 1 << std::endl;\n                std::cout << \"  Frequency (cm^-1) : \" << std::setw(15) << writes->in_kayser(omega) << std::endl;\n            }\n\n            int ik_irred = kpoint->kmap_to_irreducible[knum];\n\n            if (integration->ismear == -1) {\n                calc_damping_tetrahedron(NT, T_arr, omega, ik_irred, snum, damping_a);\n            } else {\n                calc_damping_smearing(NT, T_arr, omega, ik_irred, snum, damping_a);\n            }\n            if (quartic_mode == 2) {\n                selfenergy->selfenergy_c(NT, T_arr, omega, knum, snum, self_c);\n             //   selfenergy->selfenergy_d(NT, T_arr, omega, knum, snum, self_d);\n             //   selfenergy->selfenergy_e(NT, T_arr, omega, knum, snum, self_e);\n             //   selfenergy->selfenergy_f(NT, T_arr, omega, knum, snum, self_f);\n//                 selfenergy->selfenergy_g(NT, T_arr, omega, knum, snum, self_g);\n//                 selfenergy->selfenergy_h(NT, T_arr, omega, knum, snum, self_h);\n//                 selfenergy->selfenergy_i(NT, T_arr, omega, knum, snum, self_i);\n//                 selfenergy->selfenergy_j(NT, T_arr, omega, knum, snum, self_j);\n            }\n\n            if (mympi->my_rank == 0) {\n                file_linewidth = input->job_title + \".Gamma.\" + boost::lexical_cast<std::string>(i + 1);\n                ofs_linewidth.open(file_linewidth.c_str(), std::ios::out);\n                if (!ofs_linewidth) error->exit(\"perform_mode_analysis\", \"Cannot open file file_linewidth\");\n\n                ofs_linewidth << \"# xk = \";\n\n                for (j = 0; j < 3; ++j) {\n                    ofs_linewidth << std::setw(15) << kpoint->xk[knum][j];\n                }\n                ofs_linewidth << std::endl;\n                ofs_linewidth << \"# mode = \" << snum + 1<< std::endl;\n                ofs_linewidth << \"# Frequency = \" << writes->in_kayser(omega) << std::endl;\n                ofs_linewidth << \"## Temperature dependence of 2*Gamma (FWHM) for the given mode\" << std::endl;\n                ofs_linewidth << \"## T[K], 2*Gamma3 (cm^-1) (bubble)\";\n                if (quartic_mode == 2) ofs_linewidth << \", 2*Gamma4(cm^-1) <-- specific diagram only\";\n                ofs_linewidth << std::endl;\n\n                for (j = 0; j < NT; ++j) {\n                    ofs_linewidth << std::setw(10) << T_arr[j] << std::setw(15) << writes->in_kayser(2.0 * damping_a[j]);\n\n                    if (quartic_mode == 2) {\n                        //\t\t\t\t\t\t\tofs_mode_tau << std::setw(15) << writes->in_kayser(damp4[j]);\n                        ofs_linewidth << std::setw(15) << writes->in_kayser(2.0 * self_c[j].imag());\n                        ofs_linewidth << std::setw(15) << writes->in_kayser(2.0 * self_d[j].imag());\n                        ofs_linewidth << std::setw(15) << writes->in_kayser(2.0 * self_e[j].imag());\n                        ofs_linewidth << std::setw(15) << writes->in_kayser(2.0 * self_f[j].imag());\n                        ofs_linewidth << std::setw(15) << writes->in_kayser(2.0 * self_g[j].imag());\n                        ofs_linewidth << std::setw(15) << writes->in_kayser(2.0 * self_h[j].imag());\n                        ofs_linewidth << std::setw(15) << writes->in_kayser(2.0 * self_i[j].imag());\n                        ofs_linewidth << std::setw(15) << writes->in_kayser(2.0 * self_j[j].imag());\n                    }\n\n                    ofs_linewidth << std::endl; \n                }\n                ofs_linewidth.close();\n                std::cout << \"  Phonon line-width is printed in \" << file_linewidth << std::endl;\n            }\n\n\n            if (calc_realpart) {\n\n                selfenergy->selfenergy_tadpole(NT, T_arr, omega, knum, snum, self_tadpole);\n                selfenergy->selfenergy_a(NT, T_arr, omega, knum, snum, self_a);\n\n                if (quartic_mode == 1) {\n                    selfenergy->selfenergy_b(NT, T_arr, omega, knum, snum, self_b);\n                }\n\n                if (mympi->my_rank == 0) {\n\n                    file_shift = input->job_title + \".Shift.\" + boost::lexical_cast<std::string>(i + 1);\n                    ofs_shift.open(file_shift.c_str(), std::ios::out);\n                    if (!ofs_shift) error->exit(\"perform_mode_analysis\", \"Cannot open file file_shift\");\n\n                    ofs_shift << \"# xk = \";\n\n                    for (j = 0; j < 3; ++j) {\n                        ofs_shift << std::setw(15) << kpoint->xk[knum][j];\n                    }\n                    ofs_shift << std::endl;\n                    ofs_shift << \"# mode = \" << snum + 1<< std::endl;\n                    ofs_shift << \"# Frequency = \" << writes->in_kayser(omega) << std::endl;\n                    ofs_shift << \"## T[K], Shift3 (cm^-1) (tadpole), Shift3 (cm^-1) (bubble)\";\n                    if (quartic_mode == 1) ofs_shift << \", Shift4 (cm^-1) (loop)\";\n                    ofs_shift << \", Shifted frequency (cm^-1)\";\n                    ofs_shift << std::endl;\n\n\n                    for (j = 0; j < NT; ++j) {\n                        ofs_shift << std::setw(10) << T_arr[j];\n                        ofs_shift << std::setw(15) << writes->in_kayser(-self_tadpole[j].real());\n                        ofs_shift << std::setw(15) << writes->in_kayser(-self_a[j].real());\n\n                        omega_shift = omega - self_tadpole[j].real() - self_a[j].real();\n\n                        if (quartic_mode == 1) { \n                            ofs_shift << std::setw(15) << writes->in_kayser(-self_b[j].real());\n                            omega_shift -= self_b[j].real();\n                        }\n                        ofs_shift << std::setw(15) << writes->in_kayser(omega_shift);\n                        ofs_shift << std::endl; \n\n                    }\n\n                    ofs_shift.close();\n                    std::cout << \"  Phonon frequency shift is printed in \" << file_shift << std::endl;\n                }\n            }\n        }\n\n        memory->deallocate(damping_a);\n        memory->deallocate(self_a);\n        memory->deallocate(self_b);\n        memory->deallocate(self_tadpole);\n\n        if (quartic_mode == 2) {\n            memory->deallocate(self_c);\n            memory->deallocate(self_d);\n            memory->deallocate(self_e);\n            memory->deallocate(self_f);\n            memory->deallocate(self_g);\n            memory->deallocate(self_h);\n            memory->deallocate(self_i);\n            memory->deallocate(self_j);\n        }\n\n    }\n    memory->deallocate(T_arr);\n\n}\nvoid Relaxation::print_frequency_resolved_final_state(const unsigned int NT, double *T_arr)\n{\n    int i, j;\n    unsigned int knum, snum;\n    double omega, omega0;\n    double **gamma_final;\n    double *freq_array;\n    int ienergy;\n    std::ofstream ofs_omega;\n    std::string file_omega;\n\n    memory->allocate(gamma_final, NT, dos->n_energy);\n    memory->allocate(freq_array, dos->n_energy);\n\n    for (i = 0; i < dos->n_energy; ++i) {\n        freq_array[i] = dos->energy_dos[i] * time_ry / Hz_to_kayser;\n    }\n\n    if (mympi->my_rank == 0) {\n\n        std::cout << std::endl;\n        std::cout << \" FSTATE_W = 1 : Calculate the frequency-resolved final state amplitude\" << std::endl;\n        std::cout << \"                due to 3-phonon interactions.\" << std::endl;\n\n        if (integration->ismear == -1) {\n            error->exit(\"print_frequency_resolved_final_state\",\n                \"Sorry, ISMEAR=-1 cannot be used with FSTATE_W = 1\");\n        }\n    }\n\n    for (i = 0; i < kslist.size(); ++i) {\n        knum = kslist[i] / ns;\n        snum = kslist[i] % ns;\n\n        omega0 = dynamical->eval_phonon[knum][snum];\n\n        if (mympi->my_rank == 0) {\n            std::cout << std::endl;\n            std::cout << \" Number : \" << std::setw(5) << i + 1 << std::endl;\n            std::cout << \"  Phonon at k = (\";\n            for (j = 0; j < 3; ++j) {\n                std::cout << std::setw(10) << std::fixed << kpoint->xk[knum][j];\n                if (j < 2) std::cout << \",\";\n            }\n            std::cout << \")\" << std::endl;\n            std::cout << \"  Mode index = \" << std::setw(5) << snum + 1 << std::endl;\n            std::cout << \"  Frequency (cm^-1) : \" << std::setw(15) << writes->in_kayser(omega0) << std::endl;\n        }\n\n        calc_frequency_resolved_final_state(NT, T_arr, omega0, dos->n_energy, \n            freq_array, kpoint->kmap_to_irreducible[knum], snum, gamma_final);\n\n        if (mympi->my_rank == 0) {\n\n            file_omega = input->job_title + \".fw.\" + boost::lexical_cast<std::string>(i + 1);\n            ofs_omega.open(file_omega.c_str(), std::ios::out);\n            if (!ofs_omega) error->exit(\"print_frequency_resolved_final_state\", \"Cannot open file file_omega\");\n\n            ofs_omega << \"# xk = \";\n\n            for (j = 0; j < 3; ++j) {\n                ofs_omega << std::setw(15) << kpoint->xk[knum][j];\n            }\n            ofs_omega << std::endl;\n            ofs_omega << \"# mode = \" << snum << std::endl;\n            ofs_omega << \"# Frequency = \" << writes->in_kayser(omega0) << std::endl;\n\n            ofs_omega<< \"## Frequency-resolved final state amplitude for given modes\" << std::endl;\n            ofs_omega << \"## Gamma[omega][temperature] in cm^-1\";\n            ofs_omega << std::endl;\n\n            ofs_omega << \"## \";\n            for (j = 0; j < NT; ++j) {\n                ofs_omega << std::setw(10) << T_arr[j];\n            }\n            ofs_omega << std::endl;\n            for (ienergy = 0; ienergy < dos->n_energy; ++ienergy) {\n                omega = dos->energy_dos[ienergy];\n\n                ofs_omega << std::setw(10) << omega;\n                for (j = 0; j < NT; ++j) ofs_omega << std::setw(15) << writes->in_kayser(gamma_final[j][ienergy]);\n                ofs_omega << std::endl;\n            }\n            ofs_omega.close();\n            std::cout << \"  Frequency-resolved final state amplitude is printed in \" << file_omega << std::endl;\n        }\n    }\n\n    memory->deallocate(freq_array);\n    memory->deallocate(gamma_final);\n}\n\nvoid Relaxation::print_momentum_resolved_final_state(const unsigned int NT, double *T_arr, double epsilon)\n{\n    int i, j, k, l, m;\n    int iT;\n    int is, js;\n    int nklist;\n    int mode;\n    double xk1[3], xk2[3], xk3[3];\n    double kvec[3];\n    double f1, f2, n1, n2;\n    double norm, T_tmp;\n    double V3norm;\n    double **eval, **eval2;\n    double **gamma_k;\n\n    std::complex<double> ***evec;\n\n    std::ofstream ofs_mode_tau;\n    std::string file_mode_tau;\n\n    if (mympi->my_rank == 0) {\n        std::cout << std::endl;\n        if (integration->ismear == -1) {\n            std::cout << \" ISMEAR = -1: Tetrahedron method will be used.\" << std::endl;\n            std::cout << \" Sorry. Currently, ISMEAR = -1 cannot be used with FSTATE_K = 1.\";\n            error->exit(\"calc_momentum_resolved_final_state\", \"exit.\");\n        } else if (integration->ismear == 0) {\n            std::cout << \" ISMEAR = 0: Lorentzian broadening with epsilon = \" \n                << std::fixed << std::setprecision(2) << epsilon << \" (cm^-1)\" << std::endl;\n        } else if (integration->ismear == 1) {\n            std::cout << \" ISMEAR = 1: Gaussian broadening with epsilon = \"\n                << std::fixed << std::setprecision(2) << epsilon << \" (cm^-1)\" << std::endl;\n        } else {\n            error->exit(\"setup_relaxation\", \"Invalid ksum_mode\");\n        }\n\n        std::cout << std::endl;\n        std::cout << \" FSTATE_K = 1 : Calculate the momentum-resolved final state amplitude\" << std::endl;\n        std::cout << \"                due to 3-phonon interactions for given \" \n            << kslist_fstate_k.size() << \" entries.\" << std::endl;\n        std::cout << std::endl;\n    }\n\n    double **xk_plane, **xk_plane2;\n    double **kvec_plane;\n    int nk1_plane, nk2_plane, nk_plane;\n    double xk_vec1[3], xk_vec2[3];\n    double div1, div2;\n    double *eval_tmp;\n    double omega_sum[3];\n    double frac;\n    int knum_triangle[3];\n    std::vector<std::vector<double> > ***kplist_conserved; \n    std::vector<KpointListWithCoordinate> ***kplist_for_target_mode;\n    std::vector<double> xk_vec;\n    double xk_norm[3], xk_tmp[3];\n    double norm1, norm2, dprod, norm_ref;\n    double theta, theta_ref;\n\n    memory->allocate(kplist_conserved, ns, ns, 2);\n    memory->allocate(kplist_for_target_mode, ns, ns, kslist_fstate_k.size());\n\n    theta_ref = 0.0;\n\n    // Loop over k point planes\n\n    for (i = 0; i < kpoint->kp_plane_geometry.size(); ++i) {\n\n        nk1_plane = kpoint->kp_plane_geometry[i].npoints[0];\n        nk2_plane = kpoint->kp_plane_geometry[i].npoints[1];\n\n        div1 = 1.0 / static_cast<double>(nk1_plane - 1);\n        div2 = 1.0 / static_cast<double>(nk2_plane - 1);\n\n        nk_plane = nk1_plane * nk2_plane;\n\n        for (j = 0; j < 3; ++j) {\n            xk_vec1[j] = kpoint->kp_plane_geometry[i].xk_edges[0][j] \n            - kpoint->kp_plane_geometry[i].xk_origin[j];\n            xk_vec2[j] = kpoint->kp_plane_geometry[i].xk_edges[1][j] \n            - kpoint->kp_plane_geometry[i].xk_origin[j];\n        }\n\n\n        for (j = 0; j < 3; ++j) {\n            xk_norm[j] = xk_vec1[j];\n        }\n\n        rotvec(xk_norm, xk_norm, system->rlavec_p, 'T');\n        norm_ref = std::sqrt(xk_norm[0] * xk_norm[0] + xk_norm[1] * xk_norm[1] + xk_norm[2] * xk_norm[2]);\n\n        memory->allocate(xk_plane, nk_plane, 3);\n        memory->allocate(xk_plane2, nk_plane, 3);\n        memory->allocate(kvec_plane, nk_plane, 3);\n        memory->allocate(eval, nk_plane, ns);\n        memory->allocate(eval2, nk_plane, ns);\n        memory->allocate(eval_tmp, ns);\n        memory->allocate(evec, 1, 1, 1);\n\n        // Constructing xk's for the plane\n        m = 0;\n        for (j = 0; j < nk1_plane; ++j) {\n            for (k = 0; k < nk2_plane; ++k) {\n                for (l = 0; l < 3; ++l) {\n                    xk_plane[m][l] = kpoint->kp_plane_geometry[i].xk_origin[l] \n                    + xk_vec1[l] * static_cast<double>(j) * div1 \n                        + xk_vec2[l] * static_cast<double>(k) * div2;\n                }\n                ++m;\n            }\n        }\n\n        // Get frequencies of each k point\n\n        for (j = 0; j < nk_plane; ++j) {\n\n            for (k = 0; k < 3; ++k) kvec_plane[j][k] = dynamical->fold(xk_plane[j][k]);\n            rotvec(kvec_plane[j], kvec_plane[j], system->rlavec_p, 'T');\n            norm = std::sqrt(kvec_plane[j][0] * kvec_plane[j][0] \n            + kvec_plane[j][1] * kvec_plane[j][1] \n            + kvec_plane[j][2] * kvec_plane[j][2]);\n\n            if (norm > eps) {\n                for (k = 0; k < 3; ++k) kvec_plane[j][k] /= norm;\n            }\n        }\n\n        for (j = 0; j < nk_plane; ++j) {\n            dynamical->eval_k(xk_plane[j], kvec_plane[j], fcs_phonon->fc2_ext, eval[j], evec[0], false);            \n            for (k = 0; k < ns; ++k) {\n                eval[j][k] = dynamical->freq(eval[j][k]);\n            }\n        }\n\n        // Loop over k points to analyze the final state amplitude\n\n        for (j = 0; j < kslist_fstate_k.size(); ++j) {\n\n            for (k = 0; k < 3; ++k) xk1[k] = -kslist_fstate_k[j].xk[k];\n            mode = kslist_fstate_k[j].nmode;\n\n            for (k = 0; k < 3; ++k) kvec[k] = dynamical->fold(xk1[k]);\n            rotvec(kvec, kvec, system->rlavec_p, 'T');\n            norm = std::sqrt(kvec[0] * kvec[0] + kvec[1] * kvec[1] + kvec[2] * kvec[2]);\n\n            if (norm > eps) {\n                for (k = 0; k < 3; ++k) kvec[k] /= norm;\n            }\n\n            for (k = 0; k < 3; ++k) xk1[k] = dynamical->fold(xk1[k]);\n\n            dynamical->eval_k(xk1, kvec, fcs_phonon->fc2_ext, eval_tmp, evec[0], false);\n            for (k = 0; k < ns; ++k) eval_tmp[k] = dynamical->freq(eval_tmp[k]);\n\n            // Calculate xk's for the third index that satisfy the momentum conservation\n\n            for (k = 0; k < nk_plane; ++k) {\n                for (l = 0; l < 3; ++l) {\n                    xk_plane2[k][l] = dynamical->fold(-xk1[l]-xk_plane[k][l]);\n                }\n            }\n\n            // Get frequencies of each k point\n\n            for (k = 0; k < nk_plane; ++k) {\n                for (l = 0; l < 3; ++l) kvec_plane[k][l] = xk_plane2[k][l];\n                rotvec(kvec_plane[k], kvec_plane[k], system->rlavec_p, 'T');\n                norm = std::sqrt(kvec_plane[k][0] * kvec_plane[k][0] \n                + kvec_plane[k][1] * kvec_plane[k][1] \n                + kvec_plane[k][2] * kvec_plane[k][2]);\n\n                if (norm > eps) {\n                    for (l = 0; l < 3; ++l) kvec_plane[k][l] /= norm;\n                }\n            }\n\n            for (k = 0; k < nk_plane; ++k) {\n                dynamical->eval_k(xk_plane2[k], kvec_plane[k], fcs_phonon->fc2_ext, eval2[k], evec[0], false);            \n                for (l = 0; l < ns; ++l) {\n                    eval2[k][l] = dynamical->freq(eval2[k][l]);\n                }\n            }\n\n            // Find a list of k points which satisfy the energy conservation\n\n            for (std::vector<KpointPlaneTriangle>::const_iterator it = kpoint->kp_planes_tri[i].begin();\n                it != kpoint->kp_planes_tri[i].end(); ++it) \n            {\n\n                // K point indexes for each triangle\n                for (k = 0; k < 3; ++k) knum_triangle[k] = (*it).knum[k];\n\n                for (is = 0; is < ns; ++is) {\n                    for (js = 0; js < ns; ++js) {\n\n                        // The case of delta(w1 - w2 - w3) \n\n                        for (k = 0; k < 3; ++k) {\n                            omega_sum[k] = eval_tmp[mode] - eval[knum_triangle[k]][is] - eval2[knum_triangle[k]][js];\n                        }\n                        if ((omega_sum[0] > 0.0 && omega_sum[1] > 0.0 && omega_sum[2] > 0.0) ||\n                            (omega_sum[0] < 0.0 && omega_sum[1] < 0.0 && omega_sum[2] < 0.0)) continue;\n\n                        if (omega_sum[0] * omega_sum[1] < 0.0) {\n                            xk_vec.clear();\n\n                            frac = - omega_sum[0] / (omega_sum[1] - omega_sum[0]);\n\n                            for (k = 0; k < 3; ++k) {\n                                xk_vec.push_back((1.0 - frac) * xk_plane[knum_triangle[0]][k] + frac * xk_plane[knum_triangle[1]][k]);\n                            }\n                            kplist_conserved[is][js][0].push_back(xk_vec);\n                        }\n\n                        if (omega_sum[0] * omega_sum[2] < 0.0) {\n                            xk_vec.clear();\n\n                            frac = - omega_sum[0] / (omega_sum[2] - omega_sum[0]);\n\n                            for (k = 0; k < 3; ++k) {\n                                xk_vec.push_back((1.0 - frac) * xk_plane[knum_triangle[0]][k] + frac * xk_plane[knum_triangle[2]][k]);\n                            }\n                            kplist_conserved[is][js][0].push_back(xk_vec);\n                        }\n\n                        if (omega_sum[1] * omega_sum[2] < 0.0) {\n                            xk_vec.clear();\n\n                            frac = - omega_sum[1] / (omega_sum[2] - omega_sum[1]);\n\n                            for (k = 0; k < 3; ++k) {\n                                xk_vec.push_back((1.0 - frac) * xk_plane[knum_triangle[1]][k] + frac * xk_plane[knum_triangle[2]][k]);\n                            }\n                            kplist_conserved[is][js][0].push_back(xk_vec);\n                        }\n\n                        // The case of delta(w1 - w2 + w3)\n\n                        for (k = 0; k < 3; ++k) {\n                            omega_sum[k] = eval_tmp[mode] - eval[knum_triangle[k]][is] + eval2[knum_triangle[k]][js];\n                        }\n                        if ((omega_sum[0] > 0.0 && omega_sum[1] > 0.0 && omega_sum[2] > 0.0) ||\n                            (omega_sum[0] < 0.0 && omega_sum[1] < 0.0 && omega_sum[2] < 0.0)) continue;\n\n                        if (omega_sum[0] * omega_sum[1] < 0.0) {\n                            xk_vec.clear();\n\n                            frac = - omega_sum[0] / (omega_sum[1] - omega_sum[0]);\n\n                            for (k = 0; k < 3; ++k) {\n                                xk_vec.push_back((1.0 - frac) * xk_plane[knum_triangle[0]][k] + frac * xk_plane[knum_triangle[1]][k]);\n                            }\n                            kplist_conserved[is][js][1].push_back(xk_vec);\n                        }\n\n                        if (omega_sum[0] * omega_sum[2] < 0.0) {\n                            xk_vec.clear();\n\n                            frac = - omega_sum[0] / (omega_sum[2] - omega_sum[0]);\n\n                            for (k = 0; k < 3; ++k) {\n                                xk_vec.push_back((1.0 - frac) * xk_plane[knum_triangle[0]][k] + frac * xk_plane[knum_triangle[2]][k]);\n                            }\n                            kplist_conserved[is][js][1].push_back(xk_vec);\n                        }\n\n                        if (omega_sum[1] * omega_sum[2] < 0.0) {\n                            xk_vec.clear();\n\n                            frac = - omega_sum[1] / (omega_sum[2] - omega_sum[1]);\n\n                            for (k = 0; k < 3; ++k) {\n                                xk_vec.push_back((1.0 - frac) * xk_plane[knum_triangle[1]][k] + frac * xk_plane[knum_triangle[2]][k]);\n                            }\n                            kplist_conserved[is][js][1].push_back(xk_vec);\n                        }\n                    }\n                }\n            }\n\n            for (is = 0; is < ns; ++is) {\n                for (js = 0; js < ns; ++js) {\n\n                    for (std::vector<std::vector<double> >::const_iterator it2 = kplist_conserved[is][js][0].begin();\n                        it2 != kplist_conserved[is][js][0].end(); ++it2) {\n\n                            for (k = 0; k < 3; ++k) {\n                                xk_tmp[k] = (*it2)[k];\n                            }\n                            rotvec(xk_tmp, xk_tmp, system->rlavec_p, 'T');\n\n                            norm1 = 0.0;\n                            dprod = 0.0;\n                            for (k = 0; k < 3; ++k) {\n                                norm1 += xk_tmp[k] * xk_tmp[k];\n                                dprod += xk_tmp[k] * xk_norm[k];\n                            }\n                            theta = std::acos(dprod/(norm_ref*std::sqrt(norm1)));\n\n                            kplist_for_target_mode[is][js][j].push_back(KpointListWithCoordinate(*it2, std::cos(theta + theta_ref) * std::sqrt(norm1),\n                                std::sin(theta + theta_ref) * std::sqrt(norm1), i, 0));\n                    }\n\n                    for (std::vector<std::vector<double> >::const_iterator it2 = kplist_conserved[is][js][1].begin();\n                        it2 != kplist_conserved[is][js][1].end(); ++it2) {\n\n                            for (k = 0; k < 3; ++k) {\n                                xk_tmp[k] = (*it2)[k];\n                            }\n                            rotvec(xk_tmp, xk_tmp, system->rlavec_p, 'T');\n\n                            norm1 = 0.0;\n                            dprod = 0.0;\n                            for (k = 0; k < 3; ++k) {\n                                norm1 += xk_tmp[k] * xk_tmp[k];\n                                dprod += xk_tmp[k] * xk_norm[k];\n                            }\n                            theta = std::acos(dprod/(norm_ref*std::sqrt(norm1)));\n\n                            kplist_for_target_mode[is][js][j].push_back(KpointListWithCoordinate(*it2, std::cos(theta + theta_ref) * std::sqrt(norm1),\n                                std::sin(theta + theta_ref) * std::sqrt(norm1), i, 1));\n                    }\n\n                    kplist_conserved[is][js][0].clear();\n                    kplist_conserved[is][js][1].clear();\n                }\n            }\n        }\n\n        memory->deallocate(xk_plane);\n        memory->deallocate(xk_plane2);\n        memory->deallocate(kvec_plane);\n        memory->deallocate(eval);\n        memory->deallocate(eval2);\n        memory->deallocate(eval_tmp);\n        memory->deallocate(evec);\n\n        rotvec(xk_vec1, xk_vec1, system->rlavec_p, 'T');\n        rotvec(xk_vec2, xk_vec2, system->rlavec_p, 'T');\n\n        norm1 = 0.0;\n        norm2 = 0.0;\n        dprod = 0.0;\n        for (j = 0; j < 3; ++j) {\n            norm1 += xk_vec1[j] * xk_vec1[j];\n            norm2 += xk_vec2[j] * xk_vec2[j];\n            dprod += xk_vec1[j] * xk_vec2[j];\n        }\n        theta = std::acos(dprod / std::sqrt(norm1*norm2));\n\n        theta_ref += theta;\n    }\n\n    memory->deallocate(kplist_conserved);\n\n\n    std::vector<std::vector<double> > **final_state_xy;\n    std::vector<double> triplet_xyG;\n    std::vector<int> small_group_k;\n    double pos_x, pos_y;\n    int selection_type;\n\n    int isym;\n\n\n    double srot[3][3];\n    double xk_sym[3];\n    double srot_inv[3][3], srot_inv_t[3][3];\n    double ***symop_k;\n    double diff;\n\n    memory->allocate(symop_k, symmetry->nsym, 3, 3);\n    memory->allocate(final_state_xy, kslist_fstate_k.size(), NT);\n\n    memory->allocate(eval, 3, ns);\n    memory->allocate(evec, 3, ns, ns);\n\n    for (i = 0; i < kslist_fstate_k.size(); ++i) {\n\n        for (j = 0; j < 3; ++j) xk1[j] = -kslist_fstate_k[i].xk[j];\n        mode = kslist_fstate_k[i].nmode;\n\n        for (j = 0; j < 3; ++j) kvec[j] = dynamical->fold(xk1[j]);\n        rotvec(kvec, kvec, system->rlavec_p, 'T');\n        norm = std::sqrt(kvec[0] * kvec[0] + kvec[1] * kvec[1] + kvec[2] * kvec[2]);\n\n        if (norm > eps) for (j = 0; j < 3; ++j) kvec[j] /= norm;\n        for (j = 0; j < 3; ++j) xk1[j] = dynamical->fold(xk1[j]);\n\n        dynamical->eval_k(xk1, kvec, fcs_phonon->fc2_ext, eval[0], evec[0], true);\n        for (j = 0; j < ns; ++j) eval[0][j] = dynamical->freq(eval[0][j]);\n\n        small_group_k.clear();\n\n        for (isym = 0; isym < symmetry->nsym; ++isym) {\n            for (j = 0; j < 3; ++j) {\n                for (k = 0; k < 3; ++k) {\n                    srot[j][k] = static_cast<double>(symmetry->SymmList[isym].rot[j][k]);\n                }\n            }\n\n            invmat3(srot_inv, srot);\n            transpose3(srot_inv_t, srot_inv);\n\n            for (j = 0; j < 3; ++j) {\n                for (k = 0; k < 3; ++k) {\n                    symop_k[isym][j][k] = srot_inv_t[j][k];\n                }\n            }\n\n            rotvec(xk_sym, xk1, symop_k[isym]);\n\n            for (j = 0; j < 3; ++j) xk_sym[j] = xk_sym[j] - nint(xk_sym[j]);\n\n            diff = 0.0;\n            for (j = 0; j < 3; ++j) diff += std::pow(xk_sym[j] - xk1[j], 2);\n\n            if (std::sqrt(diff) < eps8) {\n                small_group_k.push_back(isym);\n            }\n\n        }\n\n        if (mympi->my_rank == 0) {\n            std::cout << \" Number : \" << std::setw(5) << i + 1 << std::endl;\n            std::cout << \"  Phonon at k = (\";\n            for (j = 0; j < 3; ++j) {\n                std::cout << std::setw(10) << std::fixed << kslist_fstate_k[i].xk[j];\n                if (j < 2) std::cout << \",\";\n            }\n            std::cout << \")\" << std::endl;\n            std::cout << \"  Mode index = \" << std::setw(5) << mode + 1 << std::endl;\n            std::cout << \"  Frequency (cm^-1) : \" << std::setw(15) << writes->in_kayser(eval[0][mode]) << std::endl;\n\n            int count_kp = 0;\n\n            for (is = 0; is < ns; ++is) {\n                for (js = 0; js < ns; ++js) {\n                    count_kp += kplist_for_target_mode[is][js][i].size();\n                }\n            }\n            std::cout << \"  Number of k points satisfying the selection rule : \"  << count_kp << std::endl;\n            std::cout << \"  Number of symmetry operations at k point : \"  << small_group_k.size() << std::endl << std::endl;\n        }\n\n        for (is = 0; is < ns; ++is) {\n            for (js = 0; js < ns; ++js) {\n\n                nklist = kplist_for_target_mode[is][js][i].size();\n\n                if (nklist == 0) continue;\n\n                memory->allocate(gamma_k, nklist, NT);\n\n                for (k = 0; k < nklist; ++k) {\n                    for (l = 0; l < NT; ++l) {\n                        gamma_k[k][l] = 0.0;\n                    }\n                }\n\n                for (k = 0; k < nklist; ++k) {\n\n                    for (l = 0; l < 3; ++l) xk2[l] = dynamical->fold(kplist_for_target_mode[is][js][i][k].xk[l]);\n\n                    for (isym = 0; isym < small_group_k.size(); ++isym) {\n\n                        rotvec(xk_sym, xk2, symop_k[small_group_k[isym]]);\n\n                        for (l = 0; l < 3; ++l) xk3[l] = dynamical->fold(-xk1[l]-xk_sym[l]);\n\n                        for (l = 0; l < 3; ++l) kvec[l] = xk_sym[l];\n                        rotvec(kvec, kvec, system->rlavec_p, 'T');\n                        norm = std::sqrt(kvec[0] * kvec[0] + kvec[1] * kvec[1] + kvec[2] * kvec[2]);\n\n                        if (norm > eps) for (l = 0; l < 3; ++l) kvec[l] /= norm;\n\n                        dynamical->eval_k(xk_sym, kvec, fcs_phonon->fc2_ext, eval[1], evec[1], true);\n\n                        for (l = 0; l < 3; ++l) kvec[l] = xk3[l];\n                        rotvec(kvec, kvec, system->rlavec_p, 'T');\n                        norm = std::sqrt(kvec[0] * kvec[0] + kvec[1] * kvec[1] + kvec[2] * kvec[2]);\n\n                        if (norm > eps) for (l = 0; l < 3; ++l) kvec[l] /= norm;\n\n                        dynamical->eval_k(xk3, kvec, fcs_phonon->fc2_ext, eval[2], evec[2], true);\n\n                        for (l = 0; l < ns; ++l) {\n                            eval[1][l] = dynamical->freq(eval[1][l]);\n                            eval[2][l] = dynamical->freq(eval[2][l]);\n                        }\n\n                        V3norm = std::norm(V3_mode(mode, xk_sym, xk3, is, js, eval, evec));\n\n                        for (iT = 0; iT < NT; ++iT) {\n                            T_tmp = T_arr[iT];\n\n                            f1 = thermodynamics->fB(eval[1][is], T_tmp);\n                            f2 = thermodynamics->fB(eval[2][js], T_tmp);\n                            n1 = f1 + f2 + 1.0;\n                            n2 = f1 - f2;\n\n                            if (selection_type == 0) {\n                                gamma_k[k][iT] += V3norm * n1;  \n                            } else if (selection_type == 1) {\n                                gamma_k[k][iT] += V3norm * n2;\n                            }\n                        }\n                    }\n\n                    for (iT = 0; iT < NT; ++iT) gamma_k[k][iT] *= pi * std::pow(0.5, 4) / static_cast<double>(small_group_k.size());\n\n                    pos_x = kplist_for_target_mode[is][js][i][k].x;\n                    pos_y = kplist_for_target_mode[is][js][i][k].y;\n                    selection_type = kplist_for_target_mode[is][js][i][k].selection_type;\n\n                    for (iT = 0; iT < NT; ++iT) {\n                        triplet_xyG.clear();\n                        triplet_xyG.push_back(pos_x);\n                        triplet_xyG.push_back(pos_y);\n                        triplet_xyG.push_back(gamma_k[k][iT]);\n                        final_state_xy[i][iT].push_back(triplet_xyG);\n                    }\n\n                }\n                memory->deallocate(gamma_k);\n            }\n        }\n\n        if (mympi->my_rank == 0) {\n\n            file_mode_tau = input->job_title + \".fk.\" + boost::lexical_cast<std::string>(i + 1);\n            ofs_mode_tau.open(file_mode_tau.c_str(), std::ios::out);\n            if (!ofs_mode_tau) error->exit(\"compute_mode_tau\", \"Cannot open file file_mode_tau\");\n\n            ofs_mode_tau << \"## Momentum-resolved final state amplitude\" << std::endl;\n\n            ofs_mode_tau << \"# \" << \"Gamma at \";\n            for (l = 0; l < 3; ++l) ofs_mode_tau << std::setw(10) << -xk1[l];\n            ofs_mode_tau << \" , mode = \" << mode + 1 << std::endl;\n            ofs_mode_tau << \" # Temperature [K], coordinate in FBZ, final state amplitude\" << std::endl;\n            for (iT = 0; iT < NT; ++iT) {\n                for (k = 0; k < final_state_xy[i][iT].size(); ++k) {\n                    ofs_mode_tau << std::setw(10) << T_arr[iT];\n                    ofs_mode_tau << std::setw(15) << final_state_xy[i][iT][k][0];\n                    ofs_mode_tau << std::setw(15) << final_state_xy[i][iT][k][1];\n                    ofs_mode_tau << std::setw(15) << final_state_xy[i][iT][k][2] << std::endl;\n                }\n            }\n\n            ofs_mode_tau.close();\n            std::cout << \"  The result is saved in \" << file_mode_tau << std::endl;\n            std::cout << std::endl;\n        }\n    }\n\n    memory->deallocate(kplist_for_target_mode);\n    memory->deallocate(final_state_xy);\n    memory->deallocate(symop_k);\n\n    /*\n    for (i = 0; i < kslist_fstate_k.size(); ++i) {\n\n    for (j = 0; j < 3; ++j) xk1[j] = -kslist_fstate_k[i].xk[j];\n    mode = kslist_fstate_k[i].nmode;\n    for (j = 0; j < 3; ++j) kvec[j] = dynamical->fold(xk1[j]);\n    rotvec(kvec, kvec, system->rlavec_p, 'T');\n    norm = std::sqrt(kvec[0] * kvec[0] + kvec[1] * kvec[1] + kvec[2] * kvec[2]);\n\n    if (norm > eps) for (j = 0; j < 3; ++j) kvec[j] /= norm;\n    for (j = 0; j < 3; ++j) xk1[j] = dynamical->fold(xk1[j]);\n\n    dynamical->eval_k(xk1, kvec, fcs_phonon->fc2_ext, eval[0], evec[0], true);\n    for (j = 0; j < ns; ++j) eval[0][j] = dynamical->freq(eval[0][j]);\n\n    if (mympi->my_rank == 0) {\n    std::cout << \" Number : \" << std::setw(5) << i + 1 << std::endl;\n    std::cout << \"  Phonon at k = (\";\n    for (j = 0; j < 3; ++j) {\n    std::cout << std::setw(10) << std::fixed << kslist_fstate_k[i].xk[j];\n    if (j < 2) std::cout << \",\";\n    }\n    std::cout << \")\" << std::endl;\n    std::cout << \"  Mode index = \" << std::setw(5) << mode + 1 << std::endl;\n    std::cout << \"  Frequency (cm^-1) : \" << std::setw(15) << writes->in_kayser(eval[0][mode]) << std::endl;\n    }\n\n    for (j = 0; j < kpoint->nplanes; ++j) {\n\n    nklist = kpoint->kp_planes[j].size();\n\n    memory->allocate(gamma_k, nklist, NT);\n    memory->allocate(gamma_k_mpi, nklist, NT);\n\n    for (k = 0; k < nklist; ++k) {\n    for (l = 0; l < NT; ++l) {\n    gamma_k[k][l] = 0.0;\n    gamma_k_mpi[k][l] = 0.0;\n    }\n    }\n\n    for (k = mympi->my_rank; k < nklist; k += mympi->nprocs) {\n\n    for (l = 0; l < 3; ++l) xk2[l] = dynamical->fold(kpoint->kp_planes[j][k].k[l]);\n    for (l = 0; l < 3; ++l) xk3[l] = dynamical->fold(-xk1[l]-xk2[l]);\n\n    for (l = 0; l < 3; ++l) kvec[l] = xk2[l];\n    rotvec(kvec, kvec, system->rlavec_p, 'T');\n    norm = std::sqrt(kvec[0] * kvec[0] + kvec[1] * kvec[1] + kvec[2] * kvec[2]);\n\n    if (norm > eps) for (l = 0; l < 3; ++l) kvec[l] /= norm;\n\n    dynamical->eval_k(xk2, kvec, fcs_phonon->fc2_ext, eval[1], evec[1], true);\n\n    for (l = 0; l < 3; ++l) kvec[l] = xk3[l];\n    rotvec(kvec, kvec, system->rlavec_p, 'T');\n    norm = std::sqrt(kvec[0] * kvec[0] + kvec[1] * kvec[1] + kvec[2] * kvec[2]);\n\n    if (norm > eps) for (l = 0; l < 3; ++l) kvec[l] /= norm;\n\n    dynamical->eval_k(xk3, kvec, fcs_phonon->fc2_ext, eval[2], evec[2], true);\n\n    for (l = 0; l < ns; ++l) {\n    eval[1][l] = dynamical->freq(eval[1][l]);\n    eval[2][l] = dynamical->freq(eval[2][l]);\n    }\n\n    for (is = 0; is < ns; ++is) {\n    for (js = 0; js < ns; ++js) {\n    // V3norm = std::norm(V3_mode(mode, xk2, xk3, is, js, eval, evec));\n    V3norm = 1.0;\n\n    if (integration->ismear == 0) {\n    delta_tmp[0] = delta_lorentz(eval[0][mode] - eval[1][is] - eval[2][js], epsilon)\n    - delta_lorentz(eval[0][mode] + eval[1][is] + eval[2][js], epsilon);\n    delta_tmp[1] = delta_lorentz(eval[0][mode] + eval[1][is] - eval[2][js], epsilon)\n    - delta_lorentz(eval[0][mode] - eval[1][is] + eval[2][js], epsilon);\n    } else {\n    delta_tmp[0] = delta_gauss(eval[0][mode] - eval[1][is] - eval[2][js], epsilon)\n    - delta_gauss(eval[0][mode] + eval[1][is] + eval[2][js], epsilon);\n    delta_tmp[1] = delta_gauss(eval[0][mode] + eval[1][is] - eval[2][js], epsilon)\n    - delta_gauss(eval[0][mode] - eval[1][is] + eval[2][js], epsilon);\n    }\n\n    for (iT = 0; iT < NT; ++iT) {\n    T_tmp = T_arr[iT];\n\n    f1 = phonon_thermodynamics->fB(eval[1][is], T_tmp);\n    f2 = phonon_thermodynamics->fB(eval[2][js], T_tmp);\n    n1 = f1 + f2 + 1.0;\n    n2 = f1 - f2;\n\n    gamma_k_mpi[k][iT] += V3norm * (n1 * delta_tmp[0] + n2 * delta_tmp[1]);\n    }\n    }\n    }\n    for (iT = 0; iT < NT; ++iT) gamma_k_mpi[k][iT] *= pi * std::pow(0.5, 4);\n    }\n\n    MPI_Reduce(&gamma_k_mpi[0][0], &gamma_k[0][0], NT*nklist, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);\n\n    if (mympi->my_rank == 0) {\n\n    file_mode_tau = input->job_title + \".fk.\" + boost::lexical_cast<std::string>(i + 1);\n    ofs_mode_tau.open(file_mode_tau.c_str(), std::ios::out);\n    if (!ofs_mode_tau) error->exit(\"compute_mode_tau\", \"Cannot open file file_mode_tau\");\n\n    ofs_mode_tau << \"## Momentum-resolved final state amplitude\" << std::endl;\n\n    ofs_mode_tau << \"# \" << \"Gamma at \";\n    for (l = 0; l < 3; ++l) ofs_mode_tau << std::setw(10) << -xk1[l];\n    ofs_mode_tau << \" , mode = \" << mode + 1 << std::endl;\n\n    for (iT = 0; iT < NT; ++iT) {\n    ofs_mode_tau << \"# T = \" << std::setw(10) << T_arr[iT] << std::endl;\n    ofs_mode_tau << \"# Plane = \" << std::setw(5) << j + 1 << std::endl;\n    for (k = 0; k < nklist; ++k) {\n    ofs_mode_tau << std::setw(5) << kpoint->kp_planes[j][k].n[0];\n    ofs_mode_tau << std::setw(5) << kpoint->kp_planes[j][k].n[1];\n    ofs_mode_tau << std::setw(15) << gamma_k[k][iT] << std::endl;\n    }\n    }\n\n    ofs_mode_tau.close();\n    std::cout << \"  The result is saved in \" << file_mode_tau << std::endl;\n    std::cout << std::endl;\n    }\n\n    memory->deallocate(gamma_k);\n    memory->deallocate(gamma_k_mpi);\n    }\n    }\n    */\n    memory->deallocate(eval);\n    memory->deallocate(evec);\n}\n\nint Relaxation::knum_sym(const int nk_in, const int symop_num) {\n\n    int i, j;\n    double srot[3][3];\n    double srot_inv[3][3], srot_inv_t[3][3];\n    double xk_orig[3], xk_sym[3];\n\n    if (symop_num < 0 || symop_num >= symmetry->nsym) {\n        error->exit(\"knum_sym\", \"Invalid symop_num\");\n    }\n\n    for (i = 0; i < 3; ++i) {\n        for (j = 0; j < 3; ++j) {\n            srot[i][j] = static_cast<double>(symmetry->SymmList[symop_num].rot[i][j]);\n        }\n    }\n\n    invmat3(srot_inv, srot);\n    transpose3(srot_inv_t, srot_inv);\n\n    for (i = 0; i < 3; ++i) xk_orig[i] = kpoint->xk[nk_in][i];\n\n    rotvec(xk_sym, xk_orig, srot_inv_t);\n    for (i = 0; i < 3; ++i){\n        xk_sym[i] = xk_sym[i] - nint(xk_sym[i]);\n    }\n\n    int ret = kpoint->get_knum(xk_sym[0], xk_sym[1], xk_sym[2]);\n\n    return ret;\n}\n\nbool Relaxation::is_proper(const int isym)\n{\n    int i, j;\n    double det;\n    double S[3][3];\n    bool ret;\n\n    for (i = 0; i < 3; ++i) {\n        for (j = 0; j < 3; ++j) {\n            S[i][j] = static_cast<double>(symmetry->SymmList[isym].rot[i][j]);\n        }\n    }\n\n    det = S[0][0] * (S[1][1] * S[2][2] - S[2][1] * S[1][2])\n        - S[1][0] * (S[0][1] * S[2][2] - S[2][1] * S[0][2])\n        + S[2][0] * (S[0][1] * S[1][2] - S[1][1] * S[0][2]);\n\n    if (std::abs(det - 1.0) < eps12) {\n        ret = true;\n    } else if (std::abs(det + 1.0) < eps12) {\n        ret = false;\n    } else {\n        error->exit(\"is_proper\", \"This cannot happen.\");\n    }\n\n    return ret;\n}\n\nbool Relaxation::is_symmorphic(const int isym)\n{\n    int i;\n    double tran[3];\n    bool ret;\n\n    for (i = 0; i < 3; ++i) tran[i] = symmetry->SymmList[isym].tran[i];\n\n    if (std::abs(tran[0]) < eps && std::abs(tran[1]) < eps && std::abs(tran[2]) < eps) {\n        ret = true;\n    } else {\n        ret = false;\n    }\n    return ret;\n}\n\nvoid Relaxation::generate_triplet_k(const bool use_triplet_symmetry, const bool use_permutation_symmetry)\n{\n    int i, j;\n    int *num_group_k;\n    int **symmetry_group_k;\n\n    int knum, isym, ksym;\n    int ik1, ik2;\n    int ks_in[2], tmp;\n    double xk[3], xk1[3], xk2[3];\n\n    bool *flag_found;\n\n    std::vector<KsList> kslist;\n\n    memory->allocate(num_group_k, kpoint->nk_reduced);\n    memory->allocate(symmetry_group_k, kpoint->nk_reduced, symmetry->nsym);\n    memory->allocate(pair_uniq, kpoint->nk_reduced);\n    memory->allocate(flag_found, kpoint->nk);\n\n    for (i = 0; i < kpoint->nk_reduced; ++i) {\n\n        knum = kpoint->kpoint_irred_all[i][0].knum;\n\n        if (use_triplet_symmetry) {\n\n            num_group_k[i] = 0;\n            j = 0;\n\n            for (isym = 0; isym < symmetry->nsym; ++isym) {\n\n                ksym = knum_sym(knum, isym);\n                if (ksym == knum) {\n                    num_group_k[i] += 1;\n                    symmetry_group_k[i][j++] = isym;\n                }\n            }\n        } else {\n            num_group_k[i] = 1;\n            symmetry_group_k[i][0] = 0; // Identity matrix\n        }\n\n        for (j = 0; j < 3; ++j) xk[j] = kpoint->xk[knum][j];\n\n        for (j = 0; j < kpoint->nk; ++j) flag_found[j] = false;\n\n        pair_uniq[i].clear();\n\n        for (ik1 = 0; ik1 < nk; ++ik1) {\n\n            for (j = 0; j < 3; ++j) xk1[j] = kpoint->xk[ik1][j];\n            for (j = 0; j < 3; ++j) xk2[j] = xk[j] - xk1[j];\n\n            ik2 = kpoint->get_knum(xk2[0], xk2[1], xk2[2]);\n\n            kslist.clear();\n\n            if (ik1 > ik2 && use_permutation_symmetry) continue;\n\n            for (isym = 0; isym < num_group_k[i]; ++isym) {\n\n                ks_in[0] = knum_sym(ik1, symmetry_group_k[i][isym]);\n                ks_in[1] = knum_sym(ik2, symmetry_group_k[i][isym]);\n\n                if (!flag_found[ks_in[0]]) {\n                    kslist.push_back(KsList(2, ks_in, symmetry_group_k[i][isym]));\n                    flag_found[ks_in[0]] = true;\n                }\n\n                if (ks_in[0] != ks_in[1] && use_permutation_symmetry) {\n                    tmp = ks_in[0];\n                    ks_in[0] = ks_in[1];\n                    ks_in[1] = tmp;\n\n                    if (!flag_found[ks_in[0]]) {\n                        kslist.push_back(KsList(2, ks_in, symmetry_group_k[i][isym]));\n                        flag_found[ks_in[0]] = true;\n                    }\n                }\n            }\n\n            if (kslist.size() > 0) {\n                pair_uniq[i].push_back(kslist);\n            }\n        }\n    }\n\n    memory->deallocate(num_group_k);\n    memory->deallocate(symmetry_group_k);\n    memory->deallocate(flag_found);\n}\n\n\nvoid Relaxation::calc_V3norm2(const unsigned int ik_in, const unsigned int snum, double **ret)\n{\n    int ib;\n    unsigned int ik;\n    unsigned int is, js;\n    unsigned int k1, k2;\n    unsigned int arr[3];\n    unsigned int knum, knum_minus;\n\n    int ns2 = ns * ns;\n\n    double factor = std::pow(0.5, 3) * std::pow(Hz_to_kayser / time_ry, 2);\n\n    knum = kpoint->kpoint_irred_all[ik_in][0].knum;\n    knum_minus = kpoint->knum_minus[knum];\n#ifdef _OPENMP\n#pragma omp parallel for private(is, js, ik, k1, k2, arr)\n#endif\n    for (ib = 0; ib < ns2; ++ib) {\n        is = ib / ns;\n        js = ib % ns;\n\n        for (ik = 0; ik < pair_uniq[ik_in].size(); ++ik) {\n\n            k1 = pair_uniq[ik_in][ik].group[0].ks[0];\n            k2 = pair_uniq[ik_in][ik].group[0].ks[1];\n\n            arr[0] = ns * knum_minus + snum;\n            arr[1] = ns * k1 + is;\n            arr[2] = ns * k2 + js;\n\n            ret[ik][ib] = std::norm(V3(arr)) * factor;\n        }\n    }\n}\n\nvoid Relaxation::setup_cubic()\n{\n    int i, j;\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(), fcs_phonon->force_constant_with_cell[1].end());\n    prepare_group_of_force_constants(fcs_phonon->force_constant_with_cell[1], 3, ngroup, fcs_group);\n\n    memory->allocate(vec_for_v3, 3, 2, fcs_phonon->force_constant_with_cell[1].size());\n    memory->allocate(invmass_for_v3, fcs_phonon->force_constant_with_cell[1].size());\n    memory->allocate(evec_index, fcs_phonon->force_constant_with_cell[1].size(), 3);\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    j = 0;\n    for (std::vector<FcsArrayWithCell>::const_iterator it  = fcs_phonon->force_constant_with_cell[1].begin();\n        it != fcs_phonon->force_constant_with_cell[1].end(); ++it) {\n            invmass_for_v3[j] \n            = invsqrt_mass_p[(*it).pairs[0].index / 3]\n            * invsqrt_mass_p[(*it).pairs[1].index / 3]\n            * invsqrt_mass_p[(*it).pairs[2].index / 3];\n\n            ++j;\n    }\n\n    prepare_relative_vector(fcs_phonon->force_constant_with_cell[1], 3, vec_for_v3);\n\n    for (i = 0; i < fcs_phonon->force_constant_with_cell[1].size(); ++i) {\n        for (j = 0; j < 3; ++j) {\n            evec_index[i][j] = fcs_phonon->force_constant_with_cell[1][i].pairs[j].index;\n        }\n    }\n\n    memory->deallocate(invsqrt_mass_p);\n}\n\nvoid Relaxation::setup_quartic()\n{\n    int i, j;\n    double *invsqrt_mass_p;\n    std::sort(fcs_phonon->force_constant_with_cell[2].begin(), fcs_phonon->force_constant_with_cell[2].end());\n    prepare_group_of_force_constants(fcs_phonon->force_constant_with_cell[2], 4, ngroup2, fcs_group2);\n\n    memory->allocate(vec_for_v4, 3, 3, fcs_phonon->force_constant_with_cell[2].size());\n    memory->allocate(invmass_for_v4, fcs_phonon->force_constant_with_cell[2].size());\n    memory->allocate(evec_index4, fcs_phonon->force_constant_with_cell[2].size(), 4);\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    j = 0;\n    for (std::vector<FcsArrayWithCell>::const_iterator it  = fcs_phonon->force_constant_with_cell[2].begin(); \n        it != fcs_phonon->force_constant_with_cell[2].end(); ++it) {\n            invmass_for_v4[j] \n            = invsqrt_mass_p[(*it).pairs[0].index / 3] \n            * invsqrt_mass_p[(*it).pairs[1].index / 3] \n            * invsqrt_mass_p[(*it).pairs[2].index / 3] \n            * invsqrt_mass_p[(*it).pairs[3].index / 3];\n\n            ++j;     \n    }\n    prepare_relative_vector(fcs_phonon->force_constant_with_cell[2], 4, vec_for_v4);\n\n    for (i = 0; i < fcs_phonon->force_constant_with_cell[2].size(); ++i) {\n        for (j = 0; j < 4; ++j) {\n            evec_index4[i][j] = fcs_phonon->force_constant_with_cell[2][i].pairs[j].index;\n        }\n    }\n\n\n    memory->deallocate(invsqrt_mass_p);\n}\n\nvoid Relaxation::store_exponential_for_acceleration( const int nk_in[3], int &nkrep_out, std::complex<double> *exp_out, std::complex<double> ***exp3_out )\n{\n    // For accelerating function V3 and V4 by avoiding continual call of std::exp.\n\n    int i;\n\n    MPI_Bcast(&use_tuned_ver, 1, MPI_LOGICAL, 0, MPI_COMM_WORLD);\n\n    if (use_tuned_ver) {\n\n        nk_grid[0] = nk_in[0];\n        nk_grid[1] = nk_in[1];\n        nk_grid[2] = nk_in[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            nkrep_out = nk_grid[0];\n            tune_type = 0;\n\n        } else if (nk_grid[0] == nk_grid[1] && nk_grid[2] == 1) {\n            nkrep_out = nk_grid[0];\n            tune_type = 0;\n\n        } else if (nk_grid[1] == nk_grid[2] && nk_grid[0] == 1) {\n            nkrep_out = nk_grid[1];\n            tune_type = 0;\n\n        } else if (nk_grid[2] == nk_grid[0] && nk_grid[1] == 1) {\n            nkrep_out = nk_grid[2];\n            tune_type = 0;\n\n        } else if (nk_grid[0] == 1 && nk_grid[1] == 1) {\n            nkrep_out = nk_grid[2];\n            tune_type = 0;\n\n        } else if (nk_grid[1] == 1 && nk_grid[2] == 1) {\n            nkrep_out = nk_grid[0];\n            tune_type = 0;\n\n        } else if (nk_grid[2] == 1 && nk_grid[0] == 1) {\n            nkrep_out = nk_grid[1];\n            tune_type = 0;\n\n        } else {\n            tune_type = 1;\n        }\n\n        int ii, jj, kk;\n\n        if (tune_type == 0) {\n\n            double phase;\n\n            memory->allocate(exp_phase, 2 * nkrep_out - 1);\n#ifdef _OPENMP\n#pragma omp parallel for private(phase)\n#endif\n            for (ii = 0; ii < 2 * nkrep_out - 1; ++ii) {\n                phase = 2.0 * pi * static_cast<double>(ii - nkrep_out + 1) / static_cast<double>(nkrep_out);\n                exp_phase[ii] = std::exp(im * phase);\n            }\n\n        } else if (tune_type == 1) {\n\n            double phase[3];\n\n            memory->allocate(exp_phase3, 2 * nk_grid[0] - 1, 2 * nk_grid[1] - 1, 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] = 2.0 * pi * static_cast<double>(ii - nk_grid[0] + 1) / dnk[0];\n                for (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 (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}\n", "meta": {"hexsha": "86e72d688d6829f0df465a9100afac3a5ee456fd", "size": 92176, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "anphon/relaxation.cpp", "max_stars_repo_name": "dlnguyen/alamode", "max_stars_repo_head_hexsha": "f99d333262489f28a3ef4838dfbe3147dc239261", "max_stars_repo_licenses": ["MIT"], "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/relaxation.cpp", "max_issues_repo_name": "dlnguyen/alamode", "max_issues_repo_head_hexsha": "f99d333262489f28a3ef4838dfbe3147dc239261", "max_issues_repo_licenses": ["MIT"], "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/relaxation.cpp", "max_forks_repo_name": "dlnguyen/alamode", "max_forks_repo_head_hexsha": "f99d333262489f28a3ef4838dfbe3147dc239261", "max_forks_repo_licenses": ["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.6304599923, "max_line_length": 160, "alphanum_fraction": 0.4859507898, "num_tokens": 28248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.2895550883425256}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n//\n// (C) Copyright Alejandro Cabrera 2011.\n// Distributed under the Boost\n// 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// See http://www.boost.org/libs/bloom_filter for documentation.\n//\n//////////////////////////////////////////////////////////////////////////////\n\n#ifndef BOOST_BLOOM_FILTER_DYNAMIC_COUNTING_BLOOM_FILTER_HPP\n#define BOOST_BLOOM_FILTER_DYNAMIC_COUNTING_BLOOM_FILTER_HPP 1\n\n#include <cmath>\n#include <vector>\n\n#include <boost/config.hpp>\n\n#include <boost/mpl/vector.hpp>\n#include <boost/mpl/size.hpp>\n\n#include <boost/static_assert.hpp>\n#include <boost/type_traits/is_integral.hpp>\n#include <boost/type_traits/is_unsigned.hpp>\n\n#include <boost/bloom_filter/detail/counting_apply_hash.hpp>\n#include <boost/bloom_filter/hash/default.hpp>\n\nnamespace boost {\n  namespace bloom_filters {\n    template <typename T,\n\t      size_t BitsPerBin = 4,\n\t      class HashFunctions = mpl::vector<boost_hash<T> >,\n\t      typename Block = size_t,\n\t      typename Allocator = std::allocator<Block> >\n    class dynamic_counting_bloom_filter {\n\n      // Block needs to be an integral type\n      BOOST_STATIC_ASSERT( boost::is_integral<Block>::value == true);\n\n      // Block needs to be an unsigned type\n      BOOST_STATIC_ASSERT( boost::is_unsigned<Block>::value == true);\n\n      // BitsPerBin needs to be greater than 0\n      BOOST_STATIC_ASSERT( BitsPerBin > 0);\n\n      // it doesn't make sense to ever support using a BitsPerBin value larger\n      // than the number of bits per Block. In that case, the user shouldn't\n      // be using a Bloom filter to represent their data.\n      BOOST_STATIC_ASSERT( (BitsPerBin < (sizeof(Block) * 8) ) );\n\n      // because of the nature of this implementation, the Bloom filter\n      // can have internal fragmentation if the calculation for \n      // bins_per_slot has a remainder. The severity of the  internal\n      // fragmentation is equal to the remainder * the number of slots.\n      // This check prevents internal fragmentation.\n      // This also necessarily limits to bin sizes to one of:\n      // [1,2,4,8,16,32(64-bit system only)] bits\n      BOOST_STATIC_ASSERT( ((sizeof(Block) * 8) % BitsPerBin) == 0);\n\n    public:\n      typedef T value_type;\n      typedef T key_type;\n      typedef HashFunctions hash_function_type;\n      typedef Block block_type;\n      typedef Allocator allocator_type;\n      typedef dynamic_counting_bloom_filter<T, BitsPerBin, \n\t\t\t\t\t    HashFunctions, \n\t\t\t\t\t    Block, Allocator> this_type;\n\n      typedef std::vector<Block, Allocator> bucket_type;\n      typedef typename bucket_type::iterator bucket_iterator;\n      typedef typename bucket_type::const_iterator bucket_const_iterator;\n\n      static const size_t slot_bits = sizeof(block_type) * 8;\n      static const size_t default_num_bins = 32;\n\n    private:\n      size_t bucket_size(const size_t requested_bins) const {\n\tconst size_t bin_bits = requested_bins * BitsPerBin;\n\treturn bin_bits / slot_bits + 1;\n      }\n\n      typedef detail::counting_apply_hash<mpl::size<HashFunctions>::value - 1,\n\t\t\t\t\t  this_type> apply_hash_type;\n\n    public:\n      //* constructors\n      dynamic_counting_bloom_filter() \n\t: bits(bucket_size(default_num_bins)),\n\t  _num_bins(default_num_bins)\n      {\n      }\n\n      explicit dynamic_counting_bloom_filter(const size_t requested_bins)\n\t: bits(bucket_size(requested_bins)),\n\t  _num_bins(requested_bins)\n      {\n      }\n\n      template <typename InputIterator>\n      dynamic_counting_bloom_filter(const InputIterator start, \n\t\t\t\t    const InputIterator end) \n\t: bits(bucket_size(std::distance(start, end) * 4)),\n\t  _num_bins(std::distance(start, end) * 4)\n      {\n\tfor (InputIterator i = start; i != end; ++i)\n\t  this->insert(*i);\n      }\n\n      //* meta functions\n      size_t num_bins() const\n      {\n\treturn this->_num_bins;\n      }\n\n      static BOOST_CONSTEXPR size_t bits_per_bin()\n      {\n\treturn BitsPerBin;\n      }\n\n      static BOOST_CONSTEXPR size_t bins_per_slot()\n      {\n\treturn sizeof(block_type) * 8 / BitsPerBin;\n      }\n\n      static BOOST_CONSTEXPR size_t mask()\n      {\n\treturn static_cast<Block>(0 - 1) >> (sizeof(Block) * 8 - BitsPerBin);\n      }\n\n      size_t bit_capacity() const\n      {\n        return this->num_bins() * BitsPerBin;\n      }\n\n      static BOOST_CONSTEXPR size_t num_hash_functions() \n      {\n        return mpl::size<HashFunctions>::value;\n      }\n\n      double false_positive_rate() const \n      {\n        const double n = static_cast<double>(this->count());\n        static const double k = static_cast<double>(num_hash_functions());\n        static const double m = static_cast<double>(this->num_bins());\n        static const double e =\n\t  2.718281828459045235360287471352662497757247093699959574966;\n        return std::pow(1 - std::pow(e, -k * n / m), k);\n      }\n\n      //? returns the number of bins that have at least 1 bit set\n      size_t count() const \n      {\n\tsize_t ret = 0;\n\n\tfor (bucket_const_iterator i = this->bits.begin(), \n\t       end = this->bits.end(); \n\t     i != end; ++i) {\n\t  for (size_t bin = 0; bin < this->bins_per_slot(); ++bin) {\n\t    const size_t offset_bits = bin * BitsPerBin;\n\t    const size_t target_bits = (*i >> offset_bits) & this->mask();\n\n\t    if (target_bits > 0)\n\t      ++ret;\n\t  }\n\t}\n\n        return ret;\n      }\n\n      bool empty() const\n      {\n\treturn this->count() == 0;\n      }\n\n      const bucket_type&\n      data() const \n      {\n\treturn this->bits;\n      }\n\n      //* core ops\n      void insert(const T& t)\n      {\n\tapply_hash_type::insert(t, \n\t\t\t\tthis->bits,\n\t\t\t\tthis->num_bins());\n      }\n\n      template <typename InputIterator>\n      void insert(const InputIterator start, const InputIterator end)\n      {\n\tfor (InputIterator i = start; i != end; ++i) {\n\t  this->insert(*i);\n\t}\n      }\n\n      void remove(const T& t)\n      {\n\tapply_hash_type::remove(t, \n\t\t\t\tthis->bits,\n\t\t\t\tthis->num_bins());\n      }\n\n      template <typename InputIterator>\n      void remove(const InputIterator start, const InputIterator end)\n      {\n\tfor (InputIterator i = start; i != end; ++i) {\n\t  this->remove(*i);\n\t}\n      }\n\n      bool probably_contains(const T& t) const\n      {\n\treturn apply_hash_type::contains(t,\n\t\t\t\t\t this->bits,\n\t\t\t\t\t this->num_bins());\n      }\n\n      //* auxiliary ops\n      void clear()\n      {\n\tfor (bucket_iterator i = bits.begin(), end = bits.end();\n\t     i != end; ++i)\n\t  *i = 0;\n      }\n\n      void swap(dynamic_counting_bloom_filter& other)\n      {\n\tdynamic_counting_bloom_filter tmp = other;\n\tother = *this;\n\t*this = tmp;\n      }\n\n      //* equality comparison operators\n      template <typename _T, size_t _BitsPerBin,\n\t\ttypename _HashFns, typename _Block, typename _Allocator>\n      friend bool\n      operator==(const dynamic_counting_bloom_filter<_T, _BitsPerBin,\n\t\t\t\t\t\t     _HashFns, _Block,\n\t\t\t\t\t\t     _Allocator>& lhs,\n\t\t const dynamic_counting_bloom_filter<_T, _BitsPerBin,\n\t\t\t\t\t\t     _HashFns, _Block,\n\t\t\t\t\t\t     _Allocator>& rhs);\n\n      template <typename _T, size_t _BitsPerBin,\n\t\ttypename _HashFns, typename _Block, typename _Allocator>\n      friend bool\n      operator!=(const dynamic_counting_bloom_filter<_T, _BitsPerBin,\n\t\t\t\t\t\t     _HashFns, _Block,\n\t\t\t\t\t\t     _Allocator>& lhs,\n\t\t const dynamic_counting_bloom_filter<_T, _BitsPerBin,\n\t\t\t\t\t\t     _HashFns, _Block,\n\t\t\t\t\t\t     _Allocator>& rhs);\n\n\n    private:\n      bucket_type bits;\n      size_t _num_bins;\n    };\n\n    template<class T, size_t BitsPerBin, class HashFunctions,\n\t     typename Block, typename Allocator>\n    void\n    swap(dynamic_counting_bloom_filter<T, BitsPerBin, \n\t\t\t\t       HashFunctions, Block,\n\t\t\t\t       Allocator>& lhs,\n\t dynamic_counting_bloom_filter<T, BitsPerBin,\n\t\t\t\t       HashFunctions, Block,\n\t\t\t\t       Allocator>& rhs)\n\n    {\n      lhs.swap(rhs);\n    }\n\n    template<class T, size_t BitsPerBin, class HashFunctions,\n\t     typename Block, typename Allocator>\n    bool\n    operator==(const dynamic_counting_bloom_filter<T, BitsPerBin, \n\t\t\t\t\t\t   HashFunctions, \n\t\t\t\t\t\t   Block,\n\t\t\t\t\t\t   Allocator>& lhs,\n\t       const dynamic_counting_bloom_filter<T, BitsPerBin,\n\t\t\t\t\t\t   HashFunctions, \n\t\t\t\t\t\t   Block,\n\t\t\t\t\t\t   Allocator>& rhs)\n    {\n      if (lhs.bit_capacity() != rhs.bit_capacity())\n\tthrow detail::incompatible_size_exception();\n\n      return (lhs.bits == rhs.bits);\n    }\n\n    template<class T, size_t BitsPerBin, class HashFunctions,\n\t     typename Block, typename Allocator>\n    bool\n    operator!=(const dynamic_counting_bloom_filter<T, BitsPerBin, \n\t\t\t\t\t\t   HashFunctions, \n\t\t\t\t\t\t   Block,\n\t\t\t\t\t\t   Allocator>& lhs,\n\t       const dynamic_counting_bloom_filter<T, BitsPerBin,\n\t\t\t\t\t\t   HashFunctions, \n\t\t\t\t\t\t   Block,\n\t\t\t\t\t\t   Allocator>& rhs)\n    {\n      if (lhs.bit_capacity() != rhs.bit_capacity())\n\tthrow detail::incompatible_size_exception();\n\n      return !(lhs == rhs);\n    }\n\n  } // namespace bloom_filter\n} // namespace boost\n#endif\n", "meta": {"hexsha": "77a736cbdf8d0ea0617de6cb22d0ac76cafcd695", "size": 8977, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/bloom_filter/dynamic_counting_bloom_filter.hpp", "max_stars_repo_name": "tetzank/boost-bloom-filters", "max_stars_repo_head_hexsha": "7c6717f403c041a092187568908f3661782ddb24", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T16:05:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T03:01:42.000Z", "max_issues_repo_path": "boost/bloom_filter/dynamic_counting_bloom_filter.hpp", "max_issues_repo_name": "tetzank/boost-bloom-filters", "max_issues_repo_head_hexsha": "7c6717f403c041a092187568908f3661782ddb24", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/bloom_filter/dynamic_counting_bloom_filter.hpp", "max_forks_repo_name": "tetzank/boost-bloom-filters", "max_forks_repo_head_hexsha": "7c6717f403c041a092187568908f3661782ddb24", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2016-04-15T18:17:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-16T06:29:58.000Z", "avg_line_length": 28.2295597484, "max_line_length": 78, "alphanum_fraction": 0.6348446029, "num_tokens": 2135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2895550820156163}}
{"text": "#include <Eigen/Core>\n#include <Eigen/StdVector>\n#include <Eigen/Geometry>\n#include <iostream>\n\n#include \"data.hpp\"\n#include \"../helper.hpp\"\n\n#include \"g2o/core/sparse_optimizer.h\"\n#include \"g2o/core/block_solver.h\"\n#include \"g2o/core/solver.h\"\n#include \"g2o/core/optimization_algorithm_levenberg.h\"\n#include \"g2o/core/base_vertex.h\"\n#include \"g2o/core/base_unary_edge.h\"\n#include \"g2o/solvers/csparse/linear_solver_csparse.h\"\n\nusing namespace std;\n\ntypedef g2o::BlockSolver< g2o::BlockSolverTraits<2, 1> >  KLTBlockSolver;\ntypedef g2o::LinearSolverCSparse<KLTBlockSolver::PoseMatrixType> KLTLinearSolver;\n\nclass VertexKLT : public g2o::BaseVertex<2, Eigen::Vector2d>\n{\n  public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n    VertexKLT()\n    {\n    }\n\n    virtual bool read(std::istream& /*is*/)\n    {\n      cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\n      return false;\n    }\n\n    virtual bool write(std::ostream& /*os*/) const\n    {\n      cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\n      return false;\n    }\n\n    virtual void setToOriginImpl()\n    {\n      cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\n    }\n\n    virtual void oplusImpl(const double* update)\n    {\n      Eigen::Vector2d::ConstMapType v(update);\n      _estimate += v;\n    }\n};\n\nclass EdgeKLT : public g2o::BaseUnaryEdge<1, Eigen::VectorXd, VertexKLT>\n{\n  public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    EdgeKLT(const cv::Mat& _img1, const cv::Mat& _Ix, const cv::Mat& _Iy)\n    :img1(_img1), Ix(_Ix), Iy(_Iy){}\n\n    virtual bool read(std::istream& /*is*/)\n    {\n      cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\n      return false;\n    }\n    virtual bool write(std::ostream& /*os*/) const\n    {\n      cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\n      return false;\n    }\n\n    void computeError();\n    // void linearizeOplus();\n\n  private:\n    const cv::Mat& img1;\n    const cv::Mat& Ix;\n    const cv::Mat& Iy;\n};\n", "meta": {"hexsha": "397104353ca27f656c6e6275dd6c6b4306bb6ec3", "size": 1968, "ext": "hpp", "lang": "C++", "max_stars_repo_path": ".backup/klt_edge.hpp", "max_stars_repo_name": "jiawei-mo/dsvo", "max_stars_repo_head_hexsha": "a6d6f3a5377b472550fd3f48308adc701ed5c679", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2018-09-22T16:00:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:14:04.000Z", "max_issues_repo_path": ".backup/klt_edge.hpp", "max_issues_repo_name": "TianQi-777/dsvo", "max_issues_repo_head_hexsha": "60f4153bc970718b7ebb4be66fa1ebb0f1372a38", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-12-22T02:12:15.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-28T18:57:12.000Z", "max_forks_repo_path": ".backup/klt_edge.hpp", "max_forks_repo_name": "jiawei-mo/dsvo", "max_forks_repo_head_hexsha": "a6d6f3a5377b472550fd3f48308adc701ed5c679", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-01-02T02:05:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-16T08:00:28.000Z", "avg_line_length": 24.6, "max_line_length": 81, "alphanum_fraction": 0.6595528455, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2895550820156163}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2021 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n\n#include \"SiconosConfig.h\"\n\n#pragma GCC diagnostic ignored \"-Wunused-local-typedefs\"\n\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/operation_sparse.hpp>\n\n//#define BIND_FORTRAN_LOWERCASE_UNDERSCORE\n#include <boost/numeric/bindings/ublas/vector_proxy.hpp>\n#include <boost/numeric/bindings/ublas/matrix_proxy.hpp>\n#include <boost/numeric/bindings/trans.hpp>\n#include <boost/numeric/bindings/blas.hpp>\n#include <boost/numeric/bindings/lapack.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/std/vector.hpp>\n\nnamespace lapack = boost::numeric::bindings::lapack;\n\n\n#include \"SiconosVector.hpp\"\n#include \"cholesky.hpp\"\n#include \"SimpleMatrix.hpp\"\n#include \"BlockMatrixIterators.hpp\"\n#include \"BlockMatrix.hpp\"\n\n#include \"SiconosAlgebra.hpp\"\n\n#include \"NumericsMatrix.h\"\n#include \"NumericsSparseMatrix.h\"\n#include \"CSparseMatrix.h\"\n\n//#define DEBUG_MESSAGES\n#include \"siconos_debug.h\"\n\n#ifdef DEBUG_MESSAGES\n#include \"NumericsVector.h\"\n#include <cs.h>\n#endif\n\nusing namespace Siconos;\n\nvoid SimpleMatrix::PLUFactorizationInPlace()\n{\n  if (_isPLUFactorized)\n  {\n    std::cout << \"SimpleMatrix::PLUFactorizationInPlace warning: this matrix is already PLUFactorized. \" << std::endl;\n    return;\n  }\n  if (_num == Siconos::DENSE)\n  {\n    if (!_ipiv)\n      _ipiv.reset(new VInt(size(0)));\n    else\n      _ipiv->resize(size(0));\n    int info = lapack::getrf(*mat.Dense, *_ipiv);\n    if (info != 0)\n    {\n      _isPLUFactorized = false;\n      _isPLUFactorizedInPlace = true;\n      THROW_EXCEPTION(\"SimpleMatrix::PLUFactorizationInPlace failed: the matrix is singular.\");\n    }\n    else\n    {\n      _isPLUFactorized = true;\n      _isPLUFactorizedInPlace = true;\n    }\n  }\n  else\n  {\n    int info = cholesky_decompose(*sparse());\n    // \\warning: VA 24/11/2010: work only for symmetric matrices. Should be replaced by efficient implementatation (e.g. mumps )\n    if (info != 0)\n    {\n      display();\n      _isPLUFactorized = false;\n      _isPLUFactorizedInPlace = false;\n      std::cout << \"Problem in Cholesky Decomposition for the row number\" << info   << std::endl;\n      THROW_EXCEPTION(\"SimpleMatrix::PLUFactorizationInPlace failed. \");\n    }\n    else\n    {\n      _isPLUFactorized = true;\n      _isPLUFactorizedInPlace = false;\n    }\n  }\n\n}\n\n\n\nvoid SimpleMatrix::PLUInverseInPlace()\n{\n  if(!_isPLUFactorized)\n    PLUFactorizationInPlace();\n  if(_num != Siconos::DENSE)\n    THROW_EXCEPTION(\" SimpleMatrix::PLUInverseInPlace: only implemented for dense matrices.\");\n\n#if defined(HAS_LAPACK_dgetri)\n  int info = lapack::getri(*mat.Dense, *_ipiv);   // solve from factorization\n\n  if(info != 0)\n    THROW_EXCEPTION(\"SimpleMatrix::PLUInverseInPlace failed, the matrix is singular.\");\n\n  _isPLUInversed = true;\n#else\n  THROW_EXCEPTION(\"SimpleMatrix::PLUInverseInPlace not implemented with lapack.\");\n#endif\n}\n\nvoid SimpleMatrix::PLUForwardBackwardInPlace(SiconosMatrix &B)\n{\n  if(B.isBlock())\n    THROW_EXCEPTION(\"SimpleMatrix PLUForwardBackwardInPlace(B) failed at solving Ax = B. Not yet implemented for a BlockMatrix B.\");\n  int info = 0;\n\n  if(_num == Siconos::DENSE)\n  {\n    if(!_isPLUFactorized)  // call gesv => LU-factorize+solve\n    {\n      // solve system:\n      if(!_ipiv)\n        _ipiv.reset(new VInt(size(0)));\n      else\n        _ipiv->resize(size(0));\n      info = lapack::gesv(*mat.Dense, *_ipiv, *(B.dense()));\n      _isPLUFactorized = true;\n\n      /*\n        ublas::vector<double> S(std::max(size(0),size(1)));\n        ublas::matrix<double, ublas::column_major> U(size(0),size(1));\n        ublas::matrix<double, ublas::column_major> VT(size(0),size(1));\n\n        int ierr = lapack::gesdd(*mat.Dense, S, U, VT);\n        printf(\"info = %d, ierr = %d, emax = %f, emin = %f , cond = %f\\n\",info,ierr,S(0),S(2),S(0)/S(2));\n      */\n      // B now contains solution:\n    }\n    else // call getrs: only solve using previous lu-factorization\n      if(B.num() == DENSE)\n        info = lapack::getrs(*mat.Dense, *_ipiv, *(B.dense()));\n      else\n        THROW_EXCEPTION(\" SimpleMatrix::PLUInverseInPlace: only implemented for dense matrices in RHS.\");\n\n  }\n  else\n  {\n    if(!_isPLUFactorized)  // call first PLUFactorizationInPlace\n    {\n      PLUFactorizationInPlace();\n    }\n    // and then solve\n    if(B.num() == Siconos::DENSE)\n    {\n      inplace_solve(*sparse(), *(B.dense()), ublas::lower_tag());\n      inplace_solve(ublas::trans(*sparse()), *(B.dense()), ublas::upper_tag());\n    }\n    else if(B.num() == Siconos::SPARSE)\n    {\n      inplace_solve(*sparse(), *(B.sparse()), ublas::lower_tag());\n      inplace_solve(ublas::trans(*sparse()), *(B.sparse()), ublas::upper_tag());\n    }\n    else\n      THROW_EXCEPTION(\" SimpleMatrix::PLUInverseInPlace: only implemented for dense ans sparse matrices in RHS.\");\n    info = 0 ;\n  }\n  //  THROW_EXCEPTION(\" SimpleMatrix::PLUInverseInPlace: only implemented for dense matrices.\");\n\n\n\n  if(info != 0)\n    THROW_EXCEPTION(\"SimpleMatrix::PLUForwardBackwardInPlace failed.\");\n}\n\nvoid SimpleMatrix::PLUForwardBackwardInPlace(SiconosVector &B)\n{\n  DenseMat tmpB(B.size(), 1);\n  ublas::column(tmpB, 0) = *(B.dense()); // Conversion of vector to matrix. Temporary solution.\n  int info;\n\n  if(_num == Siconos::DENSE)\n  {\n    if(!_isPLUFactorized)  // call gesv => LU-factorize+solve\n    {\n      // solve system:\n      if(!_ipiv)\n        _ipiv.reset(new VInt(size(0)));\n      else\n        _ipiv->resize(size(0));\n\n      info = lapack::gesv(*mat.Dense, *_ipiv, tmpB);\n      _isPLUFactorized = true;\n\n      /*\n        ublas::matrix<double> COPY(*mat.Dense);\n        ublas::vector<double> S(std::max(size(0),size(1)));\n        ublas::matrix<double, ublas::column_major> U(size(0),size(1));\n`        ublas::matrix<double, ublas::column_major> VT(size(0),size(1));\n\n        int ierr = lapack::gesdd(COPY, S, U, VT);\n        printf(\"info = %d, ierr = %d, emax = %f, emin = %f , cond = %f\\n\",info,ierr,S(0),S(2),S(0)/S(2));\n      */\n      // B now contains solution:\n    }\n    else // call getrs: only solve using previous lu-factorization\n      info = lapack::getrs(*mat.Dense, *_ipiv, tmpB);\n  }\n  else\n  {\n    if(!_isPLUFactorized)  // call first PLUFactorizationInPlace\n    {\n      PLUFactorizationInPlace();\n    }\n    // and then solve\n    inplace_solve(*sparse(), tmpB, ublas::lower_tag());\n    inplace_solve(ublas::trans(*sparse()), tmpB, ublas::upper_tag());\n    info = 0;\n  }\n  if(info != 0)\n    THROW_EXCEPTION(\"SimpleMatrix::PLUForwardBackwardInPlace failed.\");\n\n  noalias(*(B.dense())) = ublas::column(tmpB, 0);\n\n}\n\nvoid SimpleMatrix::resetLU()\n{\n  if(_ipiv) _ipiv->clear();\n  _isPLUFactorized = false;\n  _isPLUFactorizedInPlace = false;\n  _isPLUInversed = false;\n}\n\nvoid SimpleMatrix::resetCholesky()\n{\n  _isCholeskyFactorized = false;\n  _isCholeskyFactorizedInPlace = false;\n}\n\nvoid SimpleMatrix::resetQR()\n{\n  _isQRFactorized = false;\n\n}\n\nvoid SimpleMatrix::resetFactorizationFlags()\n{\n  resetLU();\n  resetCholesky();\n  resetQR();\n}\n\n\n// const SimpleMatrix operator * (const SimpleMatrix & A, const SimpleMatrix& B )\n// {\n//   return (DenseMat)prod(*A.dense() , *B.dense());\n//   //  return A;\n// }\n\nvoid SimpleMatrix::SolveByLeastSquares(SiconosMatrix &B)\n{\n  if(B.isBlock())\n    THROW_EXCEPTION(\"SimpleMatrix::SolveByLeastSquares(Siconos Matrix &B) failed. Not yet implemented for M being a BlockMatrix.\");\n  int info = 0;\n#ifdef USE_OPTIMAL_WORKSPACE\n  info += lapack::gels(*mat.Dense, *(B.dense()), lapack::optimal_workspace());\n#endif\n#ifdef USE_MINIMAL_WORKSPACE\n  info += lapack::gels(*mat.Dense, *(B.dense()), lapack::minimal_workspace());\n#endif\n  if(info != 0)\n    THROW_EXCEPTION(\"SimpleMatrix::SolveByLeastSquares failed.\");\n}\n\n\n\n\nvoid SimpleMatrix::SolveByLeastSquares(SiconosVector &B)\n{\n  DenseMat tmpB(B.size(), 1);\n  ublas::column(tmpB, 0) = *(B.dense()); // Conversion of vector to matrix. Temporary solution.\n  int info = 0;\n\n#ifdef USE_OPTIMAL_WORKSPACE\n  info += lapack::gels(*mat.Dense, tmpB, lapack::optimal_workspace());\n#endif\n#ifdef USE_MINIMAL_WORKSPACE\n  info += lapack::gels(*mat.Dense, tmpB, lapack::minimal_workspace());\n#endif\n  if(info != 0)\n  {\n    std::cout << \"info = \" << info << std::endl;\n    THROW_EXCEPTION(\"SimpleMatrix::SolveByLeastSquares failed.\");\n  }\n  else\n  {\n    noalias(*(B.dense())) = ublas::column(tmpB, 0);\n  }\n\n}\n\n/*\nvoid polePlacement(const SiconosMatrix& A, const SiconosVector& B, SiconosVector& P, bool transpose)\n{\n  unsigned int n = A.size(0);\n  DenseMat AA(n, n);\n  DenseMat Q(n, n);\n  DenseVect tau(n);\n  DenseVect BB(n);\n  noalias(AA) = (*A.dense());\n  lapack::gehrd(1, n, AA, tau);\n  lapack::orghr(n, 1, n, Q, tau);\n  noalias(BB) = prod(Q, *B.dense());\n}\n*/\n\n\nvoid SimpleMatrix::Factorize()\n{\n  DEBUG_BEGIN(\"void SimpleMatrix::Factorize()\\n\");\n  if(isFactorized())\n  {\n    std::cout << \"SimpleMatrix::PLUFactorize warning: this matrix is already Factorized. \" << std::endl;\n    return;\n  }\n\n  /* set the numericsMatrix */\n\n  updateNumericsMatrix();\n  NumericsMatrix * NM = numericsMatrix();\n\n  /* Factorization calling the right method in Numerics */\n  int info =1;\n  if (isSymmetric())\n  {\n    if (isPositiveDefinite()) // Cholesky Factorization\n    {\n      //std::cout << \"Cholesky Factorize\"<< std::endl;\n      info  = NM_Cholesky_factorize(NM);\n\n      if(info != 0)\n      {\n        _isCholeskyFactorized = false;\n        THROW_EXCEPTION(\"SimpleMatrix::Factorize failed (Cholesky)\");\n      }\n      else\n      {\n        _isCholeskyFactorized = true;\n      }\n    }\n    else  //  LDLT Factorization\n    {\n      THROW_EXCEPTION(\"SimpleMatrix::Factorize failed: LDL^T not yet implemented.\");\n    }\n  }\n  else //  LU Factorization  by default\n  {\n    info  = NM_LU_factorize(NM);\n\n    if(info != 0)\n    {\n      _isPLUFactorized = false;\n      if(_num == DENSE)\n        _isPLUFactorizedInPlace = true;\n      THROW_EXCEPTION(\"SimpleMatrix::PLUFactorize failed: the matrix is singular.\");\n    }\n    else\n    {\n      _isPLUFactorized = true;\n       if(_num == DENSE)\n         _isPLUFactorizedInPlace = true;\n    }\n  }\n  DEBUG_END(\"void SimpleMatrix::Factorize()\\n\");\n}\n\n//#define SPARSE_RHS_COPY_TO_DENSE 1\n\nvoid SimpleMatrix::Solve(SiconosMatrix &B)\n{\n  if(B.isBlock())\n    THROW_EXCEPTION(\"SimpleMatrix Solve(B) failed at solving Ax = B. Not yet implemented for a BlockMatrix B.\");\n\n  int info = 1;\n  if(!isFactorized())\n  {\n    Factorize();\n  }\n  // and then solve\n  NumericsMatrix * NM = _numericsMatrix.get();\n\n\n#ifdef SPARSE_RHS_COPY_TO_DENSE\n\n  double * b;\n  SP::SimpleMatrix Bdense;\n\n  if(B.num() == DENSE)\n  {\n    b = B.getArray();\n  }\n  else if(B.num() == SPARSE)\n  {\n    // First way.\n    // We copy to dense since our sparse solver is not able to take\n    // into account for sparse r.h.s, yet.\n    Bdense.reset (new SimpleMatrix(size(0),size(1)));\n    * Bdense= B ;                                                // copy to dense\n    b = &(*Bdense->getArray());\n\n    // Second way\n    // use inplace_solve of ublas (see above with SolveInPlace)\n    // For that, we need to fill our factorization given by NM_LU_factorize\n    // into a ublas sparse matrix\n    // inplace_solve(*sparse(), *(B.sparse()), ublas::lower_tag());\n    // inplace_solve(ublas::trans(*sparse()), *(B.sparse()), ublas::upper_tag());\n\n  }\n  else\n    THROW_EXCEPTION(\" SimpleMatrix::Solve: only implemented for dense and sparse matrices in RHS.\");\n\n#else\n  B.updateNumericsMatrix();\n  NumericsMatrix * NM_B = B.numericsMatrix();\n  //NM_display(NM_B);\n#endif\n\n\n\n  if (isSymmetric())\n  {\n    if (isPositiveDefinite()) // Cholesky Solving\n    {\n      //std::cout << \"Cholesky Solve\"<< std::endl;\n#ifdef SPARSE_RHS_COPY_TO_DENSE\n      info  = NM_Cholesky_solve(NM, b, B.size(1));\n#else\n      info  = NM_Cholesky_solve_matrix_rhs(NM, NM_B);\n#endif\n      if(info != 0)\n      {\n        THROW_EXCEPTION(\"SimpleMatrix::Solve failed (Cholesky)\");\n      }\n    }\n    else  //  LDLT Factorization\n    {\n      THROW_EXCEPTION(\"SimpleMatrix::Solve failed: LDL^T not yet implemented.\");\n    }\n  }\n  else //  LU Factorization  by default\n  {\n#ifdef SPARSE_RHS_COPY_TO_DENSE\n    info  = NM_LU_solve(NM, b, B.size(1));\n#else\n    info  = NM_LU_solve_matrix_rhs(NM, NM_B);\n#endif\n    if(info != 0)\n    {\n      THROW_EXCEPTION(\"SimpleMatrix::PLUFactorize failed: the matrix is singular.\");\n    }\n  }\n\n  if(B.num() == SPARSE)\n  {\n#ifdef SPARSE_RHS_COPY_TO_DENSE\n    B = *Bdense ; // we copy back to sparse.\n    //B.displayExpert();\n#else\n    /* we need to fill back again */\n    //B.fromCSC(NM_csc(NM_B));\n#endif\n  }\n\n\n  if(info != 0)\n    THROW_EXCEPTION(\"SimpleMatrix::Solve failed.\");\n}\n\nvoid SimpleMatrix::Solve(SiconosVector &B)\n{\n  DEBUG_BEGIN(\"SimpleMatrix::PLUSolve(SiconosVector &B)\\n\");\n\n  if(!isFactorized())\n  {\n    Factorize();\n  }\n\n  // and then solve\n  int info =1;\n  NumericsMatrix * NM;\n  double * b;\n  SP::SiconosVector Bdense;\n\n\n  if(B.num() == DENSE)\n  {\n    NM = _numericsMatrix.get();\n    b = B.getArray();\n  }\n  else if(B.num() == SPARSE)\n  {\n    // First way. We copy to dense since our sparse solver is not able to take into account sparse r.h.s\n    Bdense.reset (new SiconosVector(size(0)));\n    * Bdense= B ;\n    b = &(*Bdense->getArray());\n    NM = _numericsMatrix.get();\n\n    // Second way use inplace_solve of ublas\n    // For that, we need to fill our factorization given by NM_LU_factorize into a ublas sparse matrix\n    //inplace_solve(*sparse(), *(B.sparse()), ublas::lower_tag());\n    //inplace_solve(ublas::trans(*sparse()), *(B.sparse()), ublas::upper_tag());\n  }\n  else\n    THROW_EXCEPTION(\" SimpleMatrix::Solve: only implemented for dense and sparse matrices in RHS.\");\n\n\n  if (isSymmetric())\n  {\n    if (isPositiveDefinite()) // Cholesky Factorization\n    {\n      //std::cout << \"Cholesky Solve\"<< std::endl;\n      info  = NM_Cholesky_solve(NM, b, 1);\n\n      if(info != 0)\n      {\n        THROW_EXCEPTION(\"SimpleMatrix::Solve failed (Cholesky)\");\n      }\n    }\n    else  //  LDLT Factorization\n    {\n      THROW_EXCEPTION(\"SimpleMatrix::Solve failed: LDL^T not yet implemented.\");\n    }\n  }\n  else //  LU Factorization  by default\n  {\n    info  = NM_LU_solve(NM, b, 1);\n\n    if(info != 0)\n    {\n      THROW_EXCEPTION(\"SimpleMatrix::Solve failed (LU)\");\n    }\n  }\n\n  if(B.num() == SPARSE)\n  {\n    B = *Bdense ;                                                // we copy back to sparse.\n  }\n\n\n\n\n\n  if(info != 0)\n    THROW_EXCEPTION(\"SimpleMatrix::Solve failed.\");\n  // else\n  // {\n  //   noalias(*(B.dense())) = ublas::column(tmpB, 0);\n  // }\n  DEBUG_END(\"SimpleMatrix::Solve(SiconosVector &B)\\n\");\n}\n", "meta": {"hexsha": "784d58e3de4b89bd29e702eec9a3635aa3d43966", "size": 15246, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixSolvers.cpp", "max_stars_repo_name": "BuildJet/siconos", "max_stars_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixSolvers.cpp", "max_issues_repo_name": "BuildJet/siconos", "max_issues_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixSolvers.cpp", "max_forks_repo_name": "BuildJet/siconos", "max_forks_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 26.2862068966, "max_line_length": 132, "alphanum_fraction": 0.6446280992, "num_tokens": 4365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2895550820156163}}
{"text": "#include <string>\n#include <sstream>\n#include <iostream>\n#include <map>\n#include <regex>\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n\n#include \"../common.hpp\"\n\nusing namespace std;\n\nstd::ostream nullout(nullptr);\n\nclass IntcodeComputer {\n    public:\n        deque<long> inputs;\n        long output = 0; // TODO should this be a list?\n        vector<long> backup;\n        vector<long> memory;\n        bool halted = true;\n\n        void load(istream& is);\n        void run();    // Run the computer (until it halts or blocks on input)\n        void resume(); // Resumes after being blocked\n        bool hasHalted() const { return halted; }; // has the computer halted.\n\n        void dump_memory();\n\n    private:\n        std::ostream & debug = nullout; // cout;\n\n        int pc = 0;\n        long relative_base = 0;\n\n        long * param(int parameter, bool must_be_address = false);\n        int ensure_bounds(int address);\n\n        // Some debug prints\n        string param_string(int parameter) const;\n        string address_string(int address) const;\n};\n\n// Ensure there is enough memory (in the computer) to write to this address.\n// This may cause pointers to change! Make sure any existing pointers into memory are refreshed.\nint IntcodeComputer::ensure_bounds(int address) {\n    assert(address >= 0);\n    assert(address < 1024 * 1024 * 1024); // Arbitraray limit\n    if (memory.size() < address) {\n        memory.resize(address);\n    }\n\n    return address;\n}\n\n// Returns the the address of a value to read/write.\n// This is always a valid pointer.\nlong * IntcodeComputer::param(int parameter, bool for_writing) {\n    int offset = pow(10, parameter + 1);\n    int mode = memory.at(pc) / offset % 10;\n\n    if (mode == 0) { // position (read or writing)\n        int address = ensure_bounds(memory.at(pc + parameter));\n        return &memory[address];\n    }\n    if (mode == 2) { // relative base (read or writing)\n        int address = ensure_bounds(memory.at(pc + parameter) + relative_base);\n        return &memory[address];\n    }\n\n    assert(!for_writing);\n\n    if (mode == 1) { // immediate (only for reading)\n        return &memory[pc + parameter];\n    }\n\n    assert(false);\n}\n\nstring IntcodeComputer::address_string(int address) const {\n    if (address < 0 || address >= memory.size()) {\n        return \" (\\?\\?\\?)\";\n    }\n    return \" (\" + to_string(memory.at(address)) + \")\";\n}\n\n// Debug string\nstring IntcodeComputer::param_string(int parameter) const {\n    int offset = pow(10, parameter + 1);\n    int mode = memory.at(pc) / offset % 10;\n    if (mode == 0) { // position\n        int address = memory.at(pc + parameter);\n        return \"&\" + to_string(address) + address_string(address);\n    }\n    if (mode == 1) { // immediate\n        int value = memory.at(pc + parameter);\n        return to_string(value);\n    }\n    if (mode == 2) { // relative base\n        int address = memory.at(pc + parameter) + relative_base;\n        return \"rel &\" + to_string(relative_base) + \" + \" + to_string(memory.at(pc + parameter)) + address_string(address);\n    }\n    assert(false);\n}\n\nvoid IntcodeComputer::run() {\n    this->memory = this->backup; // Reset the software\n    ensure_bounds(1024 * 1024);\n\n    this->pc = 0;\n    this->relative_base = 0;\n    this->halted = false;\n\n    resume();\n}\n\nvoid IntcodeComputer::resume() {\n    int last_pc = -1;\n    while (pc >= 0 && pc < memory.size()) {\n        assert(pc != last_pc); // Stuck in loop\n        last_pc = pc;\n\n        int op = memory.at(pc) % 100;\n        switch (op) {\n            case 1: { // add\n                debug << \"ADD \" << param_string(3) << \" = \" << param_string(1) << \" + \" << param_string(2) << endl;\n\n                long * dest = param(3, true);\n                long * src1 = param(1);\n                long * src2 = param(2);\n                *dest = *src1 + *src2;\n                pc += 4;\n                break;\n            }\n            case 2: {// mul\n                debug << \"MUL \" << param_string(3) << \" = \" << param_string(1) << \" * \" << param_string(2) << endl;\n\n                long * dest = param(3, true);\n                long * src1 = param(1);\n                long * src2 = param(2);\n                *dest = *src1 * *src2;\n                pc += 4;\n                break;\n            }\n            case 3: { // input\n                debug << \"INPUT \" << param_string(1) << endl;\n\n                if (inputs.size() <= 0 ) {\n                    // Block (a resume() call has to be made)\n                    return;\n                }\n\n                long * dest = param(1, true);\n                *dest = inputs.front();\n                inputs.pop_front();\n\n                pc += 2;\n                break;\n            }\n            case 4: { // output\n                debug << \"OUTPUT \" << param_string(1) << endl;\n                long * src = param(1);\n                output = *src;\n                pc += 2;\n                break;\n            }\n\n            case 5: { // jump-if-true\n                debug << \"IF \" << param_string(1) << \" != TRUE then pc = \" << param_string(2) << endl;\n                long * cond = param(1);\n                if (*cond != 0) {\n                    pc = *param(2);\n                } else {\n                    pc += 3;\n                }\n                break;\n            }\n\n            case 6: { // jump-if-false\n                debug << \"IF \" << param_string(1) << \" = FALSE then pc = \" << param_string(2) << endl;\n                long * cond = param(1);\n                if (*cond == 0) {\n                    pc = *param(2);\n                } else {\n                    pc += 3;\n                }\n                break;\n            }\n\n            case 7: { // less than\n                debug << param_string(3) << \" = \" << param_string(1) << \" < \" << param_string(2) << endl;\n                long * dest = param(3, true);\n                long * src1 = param(1);\n                long * src2 = param(2);\n\n                *dest = (*src1 < *src2) ? 1 : 0;\n     \n                pc += 4;\n                break;\n            }\n\n            case 8: { // equals\n                debug << param_string(3) << \" = \" << param_string(1) << \" == \" << param_string(2) << endl;\n                long * dest = param(3, true);\n                long * src1 = param(1);\n                long * src2 = param(2);\n\n                *dest = (*src1 == *src2) ? 1 : 0;\n     \n                pc += 4;\n                break;\n            }\n\n            case 9: { // adjusts the relative base\n                debug << \"REL_BASE(\" << this->relative_base << \") += \" << param_string(1) << endl;\n\n                long * base = param(1);\n                this->relative_base += *base;\n\n                pc += 2;\n                break;\n            }\n\n            case 99: // break\n                halted = true;\n                return;\n            default:\n                halted = true;\n                cout << \"Unhandled op:\" << op << \" modes:\" << (memory.at(pc) / 100) << endl;\n                return;\n        };\n    }\n\n    cout << \"No more instructions without halting pc:\" << pc << endl;\n    dump_memory();\n}\n\nvoid IntcodeComputer::dump_memory() {\n    for (int i = 0; i < memory.size(); i++) {\n        cout << i << \"\\t\" << memory[i] << endl;\n    }\n}\n\nvoid IntcodeComputer::load(istream& in) {\n    // Read the program\n    this->backup.clear();\n\n    string line; \n    while (getline(in, line, ',')) {\n        boost::trim(line);\n\n        if (line == \"\") {\n            continue;\n        }\n\n        backup.push_back(stoi(line));\n    }\n}\n\nint main() {\n    ifstream file (\"2019/9.txt\");\n    if (!file.is_open()) {\n        cout << \"Failed to open file: \" << strerror(errno) << endl;\n        return -1;\n    }\n\n    IntcodeComputer computer;\n    computer.load(file);\n    computer.inputs.push_back(1);\n    computer.run();\n\n    long answer1 = computer.output;\n    cout << \"Answer 9.1: \" << answer1 << endl;\n\n    computer.inputs.push_back(2);\n    computer.run();\n\n    long answer2 = computer.output;\n    cout << \"Answer 9.2: \" << answer2 << endl; \n}", "meta": {"hexsha": "5beb5bffb601b5bb442e249b349656dda942bf69", "size": 8013, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2019/9.cpp", "max_stars_repo_name": "bramp/aoc", "max_stars_repo_head_hexsha": "e6e2bf343786e58b3e0513dc88858e54c06f1cf6", "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": "2019/9.cpp", "max_issues_repo_name": "bramp/aoc", "max_issues_repo_head_hexsha": "e6e2bf343786e58b3e0513dc88858e54c06f1cf6", "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": "2019/9.cpp", "max_forks_repo_name": "bramp/aoc", "max_forks_repo_head_hexsha": "e6e2bf343786e58b3e0513dc88858e54c06f1cf6", "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.6178571429, "max_line_length": 123, "alphanum_fraction": 0.4775989018, "num_tokens": 1962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.28951002393155195}}
{"text": "/*\nCopyright 2009-2019 Nicolas Colombe\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#include <math/aabb2dpolygon.hpp>\n#include <math/polygon_def.hpp>\n#include <boost/polygon/detail/iterator_points_to_compact.hpp>\n#include <boost/polygon/detail/iterator_compact_to_points.hpp>\n#include <core/containers.hpp>\nnamespace boost \n{ \n  namespace polygon \n  {\n\n    template <typename Real>\n    struct geometry_concept<eXl::AABB2DPolygon<Real> >{ typedef polygon_90_with_holes_concept /*polygon_90_concept*/ type; };\n\n    template <typename Real>\n    struct geometry_concept<eXl::Vector<eXl::Vector2<Real> > >{ typedef polygon_90_concept type; };\n\n    template <typename Real>\n    struct geometry_concept<eXl::Vector<eXl::AABB2DPolygon<Real> > >{ typedef polygon_90_set_concept type; };\n\n    template <typename Real>\n    struct polygon_90_traits<eXl::AABB2DPolygon<Real> > {\n      typedef Real coordinate_type;\n      typedef iterator_points_to_compact<typename eXl::Vector<eXl::Vector2<Real> >::const_iterator,eXl::Vector2<Real> > compact_iterator_type;\n      typedef eXl::Vector2<Real> point_type;\n\n      static inline compact_iterator_type begin_compact(eXl::AABB2DPolygon<Real> const& t) {\n          return compact_iterator_type (t.Border().begin(),t.Border().end());\n      }\n      static inline compact_iterator_type end_compact(eXl::AABB2DPolygon<Real> const& t) {\n          return compact_iterator_type (t.Border().end(),t.Border().end());\n      }\n\n      // Get the number of sides of the polygon\n      static inline std::size_t size(eXl::AABB2DPolygon<Real> const& t) {\n        return t.Border().size();\n      }\n\n      // Get the winding direction of the polygon\n      static inline winding_direction winding(eXl::AABB2DPolygon<Real> const& t) {\n        return unknown_winding;\n      }\n    };\n\n    template <typename Real>\n    struct polygon_90_mutable_traits<eXl::AABB2DPolygon<Real> > {\n\n      template <typename iT>\n      static inline eXl::AABB2DPolygon<Real>& set_compact(eXl::AABB2DPolygon<Real> & t, \n                                         iT input_begin, iT input_end) {\n\n        eXl::Vector<eXl::Vector2<Real>> tempStor;\n        iterator_compact_to_points<iT,eXl::Vector2<Real>> iterBegin(input_begin,input_end);\n        iterator_compact_to_points<iT,eXl::Vector2<Real>> iterEnd(input_end,input_end);\n\n        tempStor.assign(iterBegin,iterEnd);\n\n        t = eXl::AABB2DPolygon<Real>(tempStor);\n        t.ForceClockwise();\n        return t;\n      }\n\n    };\n\n    template <typename Real>\n    struct polygon_90_traits<eXl::Vector<eXl::Vector2<Real> > > {\n      typedef Real coordinate_type;\n      typedef iterator_points_to_compact<typename eXl::Vector<eXl::Vector2<Real> >::const_iterator,eXl::Vector2<Real> > compact_iterator_type;\n      typedef eXl::Vector2<Real> point_type;\n\n      static inline compact_iterator_type begin_compact(typename eXl::AABB2DPolygon<Real>::PtList const& t) {\n          return compact_iterator_type (t.begin(),t.end());\n      }\n      static inline compact_iterator_type end_compact(typename eXl::AABB2DPolygon<Real>::PtList const& t) {\n          return compact_iterator_type (t.end(),t.end());\n      }\n\n      // Get the number of sides of the polygon\n      static inline std::size_t size(typename eXl::AABB2DPolygon<Real>::PtList const& t) {\n        return t.size();\n      }\n\n      // Get the winding direction of the polygon\n      static inline winding_direction winding(typename eXl::AABB2DPolygon<Real>::PtList const& t) {\n        return unknown_winding;\n      }\n    };\n\n    template <typename Real>\n    struct polygon_90_mutable_traits<eXl::Vector<eXl::Vector2<Real> > > {\n\n      template <typename iT>\n      static inline typename eXl::AABB2DPolygon<Real>::PtList& set_compact(typename eXl::AABB2DPolygon<Real>::PtList & t, \n                                         iT input_begin, iT input_end) {\n\n        iterator_compact_to_points<iT,eXl::Vector2<Real> > iterBegin(input_begin,input_end);\n        iterator_compact_to_points<iT,eXl::Vector2<Real> > iterEnd(input_end,input_end);\n        t.assign(iterBegin,iterEnd);\n\n        return t;\n      }\n\n    };\n\n    template <typename Real,typename enable>\n    struct polygon_with_holes_traits<eXl::AABB2DPolygon<Real>,enable> {\n         typedef typename eXl::AABB2DPolygon<Real>::PtLists::const_iterator iterator_holes_type;\n         typedef typename eXl::AABB2DPolygon<Real>::PtList hole_type;\n         static inline iterator_holes_type begin_holes(const eXl::AABB2DPolygon<Real>& t) {\n              return t.Holes().begin();\n         }\n         static inline iterator_holes_type end_holes(const eXl::AABB2DPolygon<Real>& t) {\n              return t.Holes().end();\n         }\n         static inline Real size_holes(const eXl::AABB2DPolygon<Real>& t) {\n              return t.Holes().size();\n         }\n    };\n\n    template <typename Real, typename enable>\n    struct polygon_with_holes_mutable_traits<eXl::AABB2DPolygon<Real>,enable> {\n         template <typename iT>\n         static inline eXl::AABB2DPolygon<Real>& set_holes(eXl::AABB2DPolygon<Real>& t, iT inputBegin, iT inputEnd) {\n              //t.Holes().assign(inputBegin, inputEnd);\n              for(;inputBegin != inputEnd;++inputBegin)\n              {\n                typename eXl::AABB2DPolygon<Real>::PtList hole;\n\n                polygon_90_mutable_traits<typename eXl::AABB2DPolygon<Real>::PtList>::set_compact(hole, polygon_90_traits<decltype(*inputBegin)>::begin_compact(*inputBegin),\n                  polygon_90_traits<decltype(*inputBegin)>::end_compact(*inputBegin));\n\n                t.HolesRW().push_back(typename eXl::AABB2DPolygon<Real>::PtList());\n                t.HolesRW().back().swap(hole);\n              }\n              t.ForceCClockwiseHoles();\n              return t;\n         }\n    };\n\n    //template <typename T>\n    //struct is_polygon_90_set_type<eXl::Vector<T> > {\n    //  typedef gtl_yes type;\n    //};\n    //\n    //template <typename T>\n    //struct is_mutable_polygon_90_set_type<eXl::Vector<T> > {\n    //  typedef gtl_yes type;\n    //};\n\n    template <typename Real>\n    struct polygon_90_set_traits<eXl::Vector<eXl::AABB2DPolygon<Real>> >\n    {\n      typedef Real coordinate_type;\n      typedef typename eXl::Vector<eXl::AABB2DPolygon<Real>>::const_iterator iterator_type;\n      typedef eXl::Vector<eXl::AABB2DPolygon<Real>> operator_arg_type;\n    \n      static inline iterator_type begin(const eXl::Vector<eXl::AABB2DPolygon<Real>>& polygon_set) \n      {\n        return polygon_set.begin();\n      }\n    \n      static inline iterator_type end(const eXl::Vector<eXl::AABB2DPolygon<Real>>& polygon_set) \n      {\n        return polygon_set.end();\n      }\n    \n      static inline orientation_2d orient(const eXl::Vector<eXl::AABB2DPolygon<Real>>&) { return HORIZONTAL; }\n    \n      static inline bool clean(const eXl::Vector<eXl::AABB2DPolygon<Real>>&) { return false; }\n    \n      static inline bool sorted(const eXl::Vector<eXl::AABB2DPolygon<Real>>&) { return false; }\n    };\n\n    template <typename Real>\n    struct polygon_90_set_mutable_traits<eXl::Vector<eXl::AABB2DPolygon<Real>> > \n    {\n      typedef polygon_90_with_holes_concept concept_type;\n      template <typename input_iterator_type>\n      static inline void set(eXl::Vector<eXl::AABB2DPolygon<Real>>& polygon_set, input_iterator_type input_begin, input_iterator_type input_end, orientation_2d orient) \n      {\n        polygon_set.clear();\n        size_t num_ele = std::distance(input_begin, input_end);\n        polygon_set.reserve(num_ele);\n        polygon_90_set_data<Real> ps(orient);\n        ps.reserve(num_ele);\n        ps.insert(input_begin, input_end, orient);\n        ps.clean();\n        get_90_dispatch(polygon_set, ps, orient, concept_type());\n      }\n    };\n\n} }\n\nnamespace eXl\n{\n  class Serializer;\n  template <typename PolygonType>\n  Err Stream_T(PolygonType& iPoly, Serializer iStreamer);\n\n  template <typename Real> \n  struct PreciseVector\n  {\n    typedef eXl::Vector2<typename eXl::PreciseType<Real>::type > type; \n  };\n\n  template <typename Real> \n  inline typename PreciseVector<Real>::type ToPrecise(Vector2<Real> const& iVec)\n  {\n    return typename PreciseVector<Real>::type(Math<Real>::ToPrecise(iVec.X()), Math<Real>::ToPrecise(iVec.Y()));\n  }\n\n  template <typename Real> \n  inline bool VectorNotnullptr(Vector2<Real> const& iVec)\n  {\n    return iVec.Length() > Math<Real>::ZERO_TOLERANCE;\n  }\n\n  template <> \n  inline bool VectorNotnullptr<int>(Vector2i const& iVec)\n  {\n    return iVec != Vector2i::ZERO;\n  }\n\n  template <typename Real>\n  AABB2DPolygon<Real>::AABB2DPolygon(){}  \n\n  template <typename Real>\n  void AABB2DPolygon<Real>::Translate(Vector2<Real> const& iTrans)\n  {\n    for (unsigned int i = 0; i < m_Ext.size(); ++i)\n    {\n      m_Ext[i] += iTrans;\n    }\n\n    for (unsigned int i = 0; i < m_Holes.size(); ++i)\n    {\n      for (unsigned int j = 0; j < m_Holes[i].size(); ++j)\n      {\n        m_Holes[i][j] += iTrans;\n      }\n    }\n    m_AABB.m_Data[0] += iTrans;\n    m_AABB.m_Data[1] += iTrans;\n  }\n\n  template <typename Real>\n  void AABB2DPolygon<Real>::Scale(Real iNum, Real iDenom)\n  {\n    //Polygone valide si edge confondues ??\n    for (unsigned int i = 0; i < m_Ext.size(); ++i)\n    {\n      m_Ext[i] = (m_Ext[i] * iNum) / iDenom;\n    }\n\n    for (unsigned int i = 0; i < m_Holes.size(); ++i)\n    {\n      for (unsigned int j = 0; j < m_Holes[i].size(); ++j)\n      {\n        m_Holes[i][j] = (m_Holes[i][j] * iNum) / iDenom;\n      }\n    }\n\n    boost::polygon::extents(m_AABB, *this);\n  }\n\n  template <typename Real>\n  void AABB2DPolygon<Real>::ScaleComponents(Real iNumX, Real iNumY, Real iDenomX, Real iDenomY)\n  {\n    for (unsigned int i = 0; i < m_Ext.size(); ++i)\n    {\n      m_Ext[i].X() = (m_Ext[i].X() * iNumX) / iDenomX;\n      m_Ext[i].Y() = (m_Ext[i].Y() * iNumY) / iDenomY;\n    }\n\n    for (unsigned int i = 0; i < m_Holes.size(); ++i)\n    {\n      for (unsigned int j = 0; j < m_Holes[i].size(); ++j)\n      {\n        m_Holes[i][j].X() = (m_Holes[i][j].X() * iNumX) / iDenomX;\n        m_Holes[i][j].Y() = (m_Holes[i][j].Y() * iNumY) / iDenomY;\n      }\n    }\n\n    boost::polygon::extents(m_AABB, *this);\n  }\n\n  template <typename Real>\n  AABB2DPolygon<Real>::AABB2DPolygon(Vector<Vector2<Real>> const& iPoints)\n  {\n    m_Ext.clear();\n    \n    if(iPoints.size()>=4)\n    {\n      m_Ext = iPoints;\n      if((m_Ext[0]-m_Ext[1]).GetY() != 0)\n      {\n        Vector2<Real> tempPt = m_Ext[0];\n        //memmove(&m_Points[0],&m_Points[1],m_Points.size() * sizeof(Vector2<Real>));\n        m_Ext.erase(m_Ext.begin());\n        m_Ext.push_back(tempPt);\n      }\n    }\n    if(m_Ext.front() != m_Ext.back())\n      m_Ext.push_back(m_Ext.front());\n\n    boost::polygon::extents(m_AABB,*this);\n  }\n\n  template <typename Real>\n  AABB2DPolygon<Real>::AABB2DPolygon(AABB2D<Real> const& iBox)\n  {\n    AddBox(iBox);\n    if(m_Ext.front() != m_Ext.back())\n      m_Ext.push_back(m_Ext.front());\n  }\n\n  template <typename Real>\n  void AABB2DPolygon<Real>::RemoveUselessPoints()\n  {\n    _RemoveUselessPoints(m_Ext);\n    for(unsigned int i = 0; i<m_Holes.size(); ++i)\n    {\n      _RemoveUselessPoints(m_Holes[i]);\n    }\n  }\n\n  template <class Real>\n  void AABB2DPolygon<Real>::_RemoveUselessPoints(Vector<Vector2<Real> >& ioPoints)\n  {\n    if(ioPoints.size() > 2)\n    {\n      if(ioPoints.back() == ioPoints.front())\n      {\n        ioPoints.pop_back();\n      }\n\n      for (uint32_t i = 0; i < ioPoints.size() - 1; ++i)\n      {\n        if (ioPoints[i] == ioPoints[i + 1])\n        {\n          ioPoints.erase(ioPoints.begin() + i + 1);\n        }\n      }\n\n      Vector2<Real> prevPt1 = ioPoints[ioPoints.size() - 1];\n      Vector2<Real> prevPt2 = ioPoints[ioPoints.size() - 2];\n      for (int i = 0; i<(int)ioPoints.size(); ++i)\n      {\n        unsigned int prevIdx = i > 0 ? i - 1 : (i == -1 ? ioPoints.size() - 2 : ioPoints.size() - 1);\n        unsigned int curIdx = i >= 0 ? i : ioPoints.size() - 1;\n        Vector2<Real> curPt = ioPoints[curIdx];\n        if (curPt != prevPt1 && prevPt1 != prevPt2)\n        {\n          typename PreciseVector<Real>::type dir1 = ToPrecise<int>(prevPt1 - prevPt2);\n          typename PreciseVector<Real>::type dir2 = ToPrecise<int>(curPt - prevPt2);\n          typename PreciseType<Real>::type len1 = dir1.Normalize();\n          typename PreciseType<Real>::type len2 = dir2.Normalize();\n          if (dir1.Dot(dir2) > (1 - eXl::Math<typename PreciseType<Real>::type>::EPSILON) && len1 < len2)\n          {\n            ioPoints[prevIdx] = curPt;\n            ioPoints.erase(ioPoints.begin() + curIdx);\n            prevPt1 = curPt;\n            --i;\n            continue;\n          }\n        }\n        prevPt2 = prevPt1;\n        prevPt1 = curPt;\n      }\n\n      if(ioPoints.front() != ioPoints.back())\n        ioPoints.push_back(ioPoints.front());\n    }\n    else\n    {\n      ioPoints.clear();\n    }\n  }\n\n  template <typename Real>\n  void AABB2DPolygon<Real>::Swap(AABB2DPolygon& iOther)\n  {\n    AABB2D<Real> temp = iOther.m_AABB;\n    iOther.m_Ext.swap(m_Ext);\n    iOther.m_Holes.swap(m_Holes);\n    iOther.m_AABB = m_AABB;\n    m_AABB = temp;\n  }\n\n  template <typename Real>\n  Real AABB2DPolygon<Real>::Perimeter()const\n  {\n    return boost::polygon::perimeter(*this);\n  }\n\n  template <typename Real>\n  Real AABB2DPolygon<Real>::Area() const\n  {\n    return boost::polygon::area(*this);\n  }\n\n  template <typename Real>\n  void AABB2DPolygon<Real>::ForceClockwise()\n  {\n    if(boost::polygon::winding(*this) != boost::polygon::CLOCKWISE)\n    {\n      std::reverse(m_Ext.begin(),m_Ext.end());\n    }\n  }\n\n  template <typename Real>\n  void AABB2DPolygon<Real>::ForceCClockwiseHoles()\n  {\n    for(unsigned int i = 0;i<m_Holes.size();++i)\n    {\n      if(boost::polygon::winding(m_Holes[i]) != boost::polygon::COUNTERCLOCKWISE)\n      {\n        std::reverse(m_Holes[i].begin(),m_Holes[i].end());\n      }\n    }\n  }\n\n  template <typename Real>\n  void AABB2DPolygon<Real>::InternalSwap(AABB2DPolygon &iOther)const\n  {\n    m_Ext.swap(iOther.m_Ext);\n    m_Holes.swap(iOther.m_Holes);\n    std::swap(iOther.m_AABB, m_AABB);\n  }\n\n  template <typename Real>\n  void AABB2DPolygon<Real>::Clear()\n  {\n    m_Ext.clear();\n    m_Holes.clear();\n    m_AABB = AABB2D<Real>();\n  }\n\n  template <typename Real>\n  bool AABB2DPolygon<Real>::Empty() const\n  {\n    return m_Ext.empty();\n  }\n\n  template <typename Real>\n  void AABB2DPolygon<Real>::GetBoxes(Vector<AABB2D<Real> >& oBoxes)const\n  {\n    Vector<AABB2DPolygon> meSet;\n    meSet.push_back(AABB2DPolygon());\n    InternalSwap(meSet[0]);\n\n    Vector<AABB2D<Real>> vBoxes;\n    boost::polygon::get_rectangles(vBoxes,meSet);\n\n    Vector<AABB2DPolygon> swappedPoly(1, meSet[0]);\n    for(auto& pt : swappedPoly[0].Border())\n    {\n      std::swap(pt.X(), pt.Y());\n    }\n    for(auto& hole : swappedPoly[0].Holes())\n    {\n      for(auto& pt : hole)\n      {\n        std::swap(pt.X(), pt.Y());\n      }\n    }\n\n    Vector<AABB2D<Real>> hBoxes;\n    boost::polygon::get_rectangles(hBoxes,swappedPoly);\n\n    for(auto const& hBoxSwapped : hBoxes)\n    {\n      AABB2D<Real> hBox = hBoxSwapped;\n      std::swap(hBox.m_Data[0].X(), hBox.m_Data[0].Y());\n      std::swap(hBox.m_Data[1].X(), hBox.m_Data[1].Y());\n      for(auto const& vBox : vBoxes)\n      {\n        AABB2D<Real> commonBox;\n        commonBox.SetCommonBox(vBox, hBox);\n        if(!commonBox.Empty())\n        {\n          oBoxes.push_back(commonBox);\n        }\n      }\n    }\n\n    InternalSwap(meSet[0]);\n  }\n\n  template <typename Real>\n  void AABB2DPolygon<Real>::Merge(Vector<AABB2DPolygon>& ioPoly)\n  {\n    Vector<AABB2DPolygon> res;\n    if(ioPoly.size() > 0)\n    {\n      res.push_back(ioPoly.front());\n      for(unsigned int i = 1 ; i<ioPoly.size();++i)\n      {\n        boost::polygon::operators::operator|=(res,ioPoly[i]);\n      }\n    }\n    ioPoly.swap(res);\n  }\n\n  template <typename Real>\n  void AABB2DPolygon<Real>::Union(AABB2DPolygon const& iOther, AABB2DPolygon& oPoly)const\n  {   \n    oPoly.Clear();\n\n    Vector<AABB2DPolygon> meSet;\n    Vector<AABB2DPolygon> otherSet;\n\n    meSet.push_back(AABB2DPolygon());\n    InternalSwap(meSet[0]);\n\n    otherSet.push_back(AABB2DPolygon());\n    iOther.InternalSwap(otherSet[0]);\n\n    Vector<AABB2DPolygon> result;\n    boost::polygon::assign(result,boost::polygon::operators::operator+(meSet,otherSet));\n\n    InternalSwap(meSet[0]);\n    iOther.InternalSwap(otherSet[0]);\n    if(result.size() == 1)\n      oPoly.Swap(result[0]);\n  }\n\n  template <typename Real>\n  void AABB2DPolygon<Real>::Difference(AABB2DPolygon const& iOther, Vector<AABB2DPolygon>& oPoly)const\n  {\n    oPoly.clear();\n\n    Vector<AABB2DPolygon> meSet;\n    Vector<AABB2DPolygon> otherSet;\n    \n    meSet.push_back(AABB2DPolygon());\n    InternalSwap(meSet[0]);\n\n    otherSet.push_back(AABB2DPolygon());\n    iOther.InternalSwap(otherSet[0]);\n\n    boost::polygon::assign(oPoly,boost::polygon::operators::operator-(meSet,otherSet));\n\n    InternalSwap(meSet[0]);\n    iOther.InternalSwap(otherSet[0]);\n\n  }\n\n  template <typename Real>\n  void AABB2DPolygon<Real>::Intersection(AABB2DPolygon const& iOther, Vector<AABB2DPolygon>& oPoly)const\n  {\n    Vector<AABB2DPolygon> meSet;\n    Vector<AABB2DPolygon> otherSet;\n    \n    meSet.push_back(AABB2DPolygon());\n    InternalSwap(meSet[0]);\n\n    otherSet.push_back(AABB2DPolygon());\n    iOther.InternalSwap(otherSet[0]);\n\n    boost::polygon::assign(oPoly,boost::polygon::operators::operator&(meSet,otherSet));\n\n    InternalSwap(meSet[0]);\n    iOther.InternalSwap(otherSet[0]);\n  }\n\n  template <typename Real>\n  void AABB2DPolygon<Real>::Shrink(Real iFactor,Vector<AABB2DPolygon>& oOut)const\n  {\n    Vector<AABB2DPolygon> meSet;\n    meSet.push_back(*this);\n\n    boost::polygon::shrink(meSet,iFactor/2,iFactor/2,iFactor/2,iFactor/2);\n\n    if(meSet.size()>0)\n      meSet.swap(oOut);\n    else\n      oOut.clear();\n  }\n\n  template <typename Real>\n  void AABB2DPolygon<Real>::Bloat(Real iFactor,AABB2DPolygon& oOut)const\n  {\n    Vector<AABB2DPolygon> meSet;\n    meSet.push_back(*this);\n\n    boost::polygon::bloat(meSet,iFactor/2,iFactor/2,iFactor/2,iFactor/2);\n\n    if(meSet.size()>0)\n      meSet[0].Swap(oOut);\n    else\n      oOut.Clear();\n  }\n\n  template <typename Real>\n  void AABB2DPolygon<Real>::RemoveTiny(Real iFactor,Vector<AABB2DPolygon>& oOut,Vector<AABB2DPolygon>& oRemoved)const\n  {\n    oOut.clear();\n    oRemoved.clear();\n    Vector<AABB2DPolygon> meSet;\n    meSet.push_back(*this);\n\n    /*meSet = */boost::polygon::shrink(meSet,iFactor/2,iFactor/2,iFactor/2,iFactor/2);\n\n    /*meSet = */boost::polygon::bloat(meSet,iFactor/2,iFactor/2,iFactor/2,iFactor/2);\n\n    //meSet = boost::polygon::keep(meSet,0,ULLONG_MAX,iFactor,ULLONG_MAX,iFactor,ULLONG_MAX);\n\n    if(meSet.empty())\n    {\n      oRemoved.push_back(*this);\n    }\n    else\n    {\n\n      Vector<AABB2DPolygon> good;\n      good.push_back(AABB2DPolygon());\n      InternalSwap(good.back());\n\n      boost::polygon::assign(oRemoved,boost::polygon::operators::operator-(good,meSet));\n      InternalSwap(good.back());\n\n      //meSet.back().Swap(*this);\n      oOut.swap(meSet);\n    }\n  }\n\n  template <typename Real>\n  int AABB2DPolygon<Real>::AddBox(AABB2D<Real> const& iBox)\n  {\n    if (Empty())\n    {\n      m_Ext.push_back(Vector2<Real>(iBox.m_Data[1].X(), iBox.m_Data[0].Y()));\n      m_Ext.push_back(Vector2<Real>(iBox.m_Data[0].X(), iBox.m_Data[0].Y()));\n      m_Ext.push_back(Vector2<Real>(iBox.m_Data[0].X(), iBox.m_Data[1].Y()));\n      m_Ext.push_back(Vector2<Real>(iBox.m_Data[1].X(), iBox.m_Data[1].Y()));\n\n      boost::polygon::extents(m_AABB, *this);\n\n      return 1;\n    }\n    else\n    {\n\n      Vector<Vector2<Real>> temp;\n      temp.push_back(Vector2<Real>(iBox.m_Data[1].X(), iBox.m_Data[0].Y()));\n      temp.push_back(Vector2<Real>(iBox.m_Data[0].X(), iBox.m_Data[0].Y()));\n      temp.push_back(Vector2<Real>(iBox.m_Data[0].X(), iBox.m_Data[1].Y()));\n      temp.push_back(Vector2<Real>(iBox.m_Data[1].X(), iBox.m_Data[1].Y()));\n\n      Vector<AABB2DPolygon> meSet;\n      Vector<AABB2DPolygon> boxSet;\n\n      meSet.push_back(AABB2DPolygon());\n      InternalSwap(meSet[0]);\n\n\n      boxSet.push_back(AABB2DPolygon());\n      boxSet[0].m_Ext.swap(temp);\n\n      boost::polygon::operators::operator|=(boxSet, meSet);\n      //meSet.clear();\n      //temp.get_polygons(meSet);\n      if (boxSet.size() == 1)\n      {\n        InternalSwap(boxSet[0]);\n        boost::polygon::extents(m_AABB, *this);\n        return 1;\n      }\n      else\n      {\n        InternalSwap(meSet[0]);\n        return 0;\n      }\n\n\n      return 1;\n    }\n  }\n}\n\n#include <core/stream/serializer.hpp>\n\nnamespace eXl\n{\n\n  template <typename PolygonType>\n  Err Stream_T(PolygonType& iPoly, Serializer iStreamer)\n  {\n    iStreamer.BeginStruct();\n    iStreamer.PushKey(\"Border\");\n    iStreamer &= iPoly.Border();\n    iStreamer.PopKey();\n    iStreamer.PushKey(\"Holes\");\n    iStreamer &= iPoly.Holes();\n    iStreamer.PopKey();\n    iStreamer.EndStruct();\n\n    RETURN_SUCCESS;\n  }\n\n  template <typename Real>\n  Err AABB2DPolygon<Real>::Stream(Streamer& iStreamer) const\n  {\n    Serializer serializer(iStreamer);\n    return Stream_T(*this, serializer);\n  }\n\n  template <typename Real>\n  Err AABB2DPolygon<Real>::Unstream(Unstreamer& iStreamer)\n  {\n    Serializer serializer(iStreamer);\n    Err res = Stream_T(*this, serializer);\n    if (res)\n    {\n      boost::polygon::extents(m_AABB, *this);\n    }\n    return res;\n  }\n}", "meta": {"hexsha": "459002ce4207e833e599e7115409c68957cd96b4", "size": 22213, "ext": "inl", "lang": "C++", "max_stars_repo_path": "include/math/aabb2dpolygon.inl", "max_stars_repo_name": "eXl-Nic/eXl", "max_stars_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/math/aabb2dpolygon.inl", "max_issues_repo_name": "eXl-Nic/eXl", "max_issues_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/math/aabb2dpolygon.inl", "max_forks_repo_name": "eXl-Nic/eXl", "max_forks_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_forks_repo_licenses": ["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.5123626374, "max_line_length": 460, "alphanum_fraction": 0.6397605006, "num_tokens": 6299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091673, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.28938232770379235}}
{"text": "﻿#include \"BlocksEngine/pch.h\"\n#include \"BlocksEngine/Core/Math/Vector2.h\"\n\n#include <boost/container_hash/hash.hpp>\n\n#include \"BlocksEngine/Core/Math/Quaternion.h\"\n\nusing namespace BlocksEngine;\nusing namespace DirectX;\n\n//------------------------------------------------------------------------------\n// Constructors\n//------------------------------------------------------------------------------\n\ntemplate <class T>\nVector2<T>::Vector2() noexcept\n    : Vector2Base<T>::Base{0, 0}\n{\n}\n\ntemplate <class T>\nconstexpr Vector2<T>::Vector2(const T a) noexcept\n    : Vector2Base<T>::Base{a, a}\n{\n}\n\ntemplate <class T>\nVector2<T>::Vector2(_In_reads_(2) const T* pArray) noexcept\n    : Vector2Base<T>::Base{pArray}\n{\n}\n\ntemplate <class T>\nVector2<T>::Vector2(FXMVECTOR v) noexcept // NOLINT(cppcoreguidelines-pro-type-member-init)\n{\n    Store(this, v);\n}\n\ntemplate <class T>\nVector2<T>::Vector2(const typename Vector2Base<T>::Base& v) noexcept\n    : Vector2Base<T>::Base{v.x, v.y}\n{\n}\n\ntemplate <>\nVector2<float>::Vector2(const Vector2Base<float>::Vector& v) noexcept\n    : Vector2Base<float>::Base{v.f[0], v.f[1]}\n{\n}\n\ntemplate <>\nVector2<int32_t>::Vector2(const Vector2Base<int32_t>::Vector& v) noexcept\n    : Vector2Base<int32_t>::Base{v.i[0], v.i[1]}\n{\n}\n\ntemplate <>\nVector2<uint32_t>::Vector2(const Vector2Base<uint32_t>::Vector& v) noexcept\n    : Vector2Base<uint32_t>::Base{v.u[0], v.u[1]}\n{\n}\n\n//------------------------------------------------------------------------------\n// Converter operators\n//------------------------------------------------------------------------------\n\ntemplate <class T>\nVector2<T>::operator DirectX::XMVECTOR() const noexcept\n{\n    return Load(this);\n}\n\n//------------------------------------------------------------------------------\n// Comparision operators\n//------------------------------------------------------------------------------\n\ntemplate <class T>\nbool Vector2<T>::operator==(const Vector2<T>& v) const noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR v2 = Load(&v);\n    return XMVector2Equal(v1, v2);\n}\n\ntemplate <class T>\nbool Vector2<T>::operator!=(const Vector2<T>& v) const noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR v2 = Load(&v);\n    return XMVector2NotEqual(v1, v2);\n}\n\n//------------------------------------------------------------------------------\n// Assignment operators\n//------------------------------------------------------------------------------\n\ntemplate <>\nVector2<float>& Vector2<float>::operator=(const Vector2Base<float>::Vector& f) noexcept\n{\n    this->x = f.f[0];\n    this->y = f.f[1];\n\n    return *this;\n}\n\ntemplate <>\nVector2<int32_t>& Vector2<int32_t>::operator=(const Vector2Base<int32_t>::Vector& f) noexcept\n{\n    this->x = f.i[0];\n    this->y = f.i[1];\n\n    return *this;\n}\n\ntemplate <>\nVector2<uint32_t>& Vector2<uint32_t>::operator=(const Vector2Base<uint32_t>::Vector& f) noexcept\n{\n    this->x = f.u[0];\n    this->y = f.u[1];\n\n    return *this;\n}\n\ntemplate <class T>\ntemplate <class U>\nVector2<T>& Vector2<T>::operator+=(const Vector2<U>& v) noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR v2 = Load(&v);\n    const XMVECTOR x = XMVectorAdd(v1, v2);\n    Store(this, x);\n\n    return *this;\n}\n\ntemplate <class T>\ntemplate <class U>\nVector2<T>& Vector2<T>::operator-=(const Vector2<U>& v) noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR v2 = Load(&v);\n    const XMVECTOR x = XMVectorSubtract(v1, v2);\n    Store(this, x);\n\n    return *this;\n}\n\ntemplate <class T>\ntemplate <class U>\nVector2<T>& Vector2<T>::operator*=(const Vector2<U>& v) noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR v2 = Load(&v);\n    const XMVECTOR x = XMVectorMultiply(v1, v2);\n    Store(this, x);\n\n    return *this;\n}\n\ntemplate <class T>\nVector2<T>& Vector2<T>::operator*=(const float s) noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR x = XMVectorScale(v1, s);\n    Store(this, x);\n\n    return *this;\n}\n\ntemplate <class T>\nVector2<T>& Vector2<T>::operator/=(const float s) noexcept\n{\n    assert(s != 0.0f);\n\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR x = XMVectorScale(v1, 1.f / s);\n    Store(this, x);\n\n    return *this;\n}\n\n//------------------------------------------------------------------------------\n// Unary operators\n//------------------------------------------------------------------------------\n\ntemplate <class T>\nVector2<T> Vector2<T>::operator+() const noexcept\n{\n    return *this;\n}\n\n// TODO: Could be done with XMVectorNegate, but test it\ntemplate <>\nVector2<float> Vector2<float>::operator-() const noexcept\n{\n    return Vector2(-this->x, -this->y);\n}\n\ntemplate <>\nVector2<int32_t> Vector2<int32_t>::operator-() const noexcept\n{\n    return Vector2(-this->x, -this->y);\n}\n\ntemplate <>\nVector2<uint32_t> Vector2<uint32_t>::operator-() const noexcept\n{\n    return Vector2(this->x, this->y);\n}\n\n//------------------------------------------------------------------------------\n// Hashing\n//------------------------------------------------------------------------------\n\n/*template <class T>\nstd::size_t hash_value(const Vector2<T>& v)\n{\n    std::size_t seed = 0;\n    boost::hash_combine(seed, v.x);\n    boost::hash_combine(seed, v.y);\n\n    return seed;\n}*/\n\n//------------------------------------------------------------------------------\n// Vector operations\n//------------------------------------------------------------------------------\n\ntemplate <class T>\ntemplate <class U>\nbool Vector2<T>::InBounds(const Vector2<U>& bounds) const noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR v2 = Load(&bounds);\n    return XMVector2InBounds(v1, v2);\n}\n\ntemplate <class T>\nfloat Vector2<T>::Length() const noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR x = XMVector2Length(v1);\n    return XMVectorGetX(x);\n}\n\ntemplate <class T>\nfloat Vector2<T>::LengthSquared() const noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR x = XMVector2LengthSq(v1);\n    return XMVectorGetX(x);\n}\n\ntemplate <class T>\ntemplate <class U>\nfloat Vector2<T>::Dot(const Vector2<U>& v) const noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR v2 = Load(&v);\n    const XMVECTOR x = XMVector2Dot(v1, v2);\n    return XMVectorGetX(x);\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nvoid Vector2<T>::Cross(const Vector2<U>& v, Vector2<V>& result) const noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR v2 = Load(&v);\n    const XMVECTOR r = XMVector2Cross(v1, v2);\n    Store(&result, r);\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nVector2<U> Vector2<T>::Cross(const Vector2<V>& v) const noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR v2 = Load(&v);\n    const XMVECTOR r = XMVector2Cross(v1, v2);\n\n    Vector2<U> result;\n    Store(&result, r);\n    return result;\n}\n\ntemplate <class T>\nvoid Vector2<T>::Normalize() noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR x = XMVector2Normalize(v1);\n\n    Store(this, x);\n}\n\ntemplate <class T>\ntemplate <class U>\nvoid Vector2<T>::Normalize(Vector2<U>& result) const noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR x = XMVector2Normalize(v1);\n    Store(&result, x);\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nvoid Vector2<T>::Clamp(const Vector2<U>& vMin, const Vector2<V>& vMax) noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR v2 = Load(&vMin);\n    const XMVECTOR v3 = Load(&vMax);\n    const XMVECTOR x = XMVectorClamp(v1, v2, v3);\n\n    Store(this, x);\n}\n\ntemplate <class T>\ntemplate <class U, class V, class W>\nvoid Vector2<T>::Clamp(const Vector2<U>& vMin, const Vector2<V>& vMax, Vector2<W>& result) const noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR v2 = Load(&vMin);\n    const XMVECTOR v3 = Load(&vMax);\n    const XMVECTOR x = XMVectorClamp(v1, v2, v3);\n\n    Store(&result, x);\n}\n\n//------------------------------------------------------------------------------\n// Static functions\n//------------------------------------------------------------------------------\n\ntemplate <class T>\ntemplate <class U, class V>\nfloat Vector2<T>::Distance(const Vector2<U>& v1, const Vector2<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 = XMVector2Length(v);\n\n    return XMVectorGetX(x);\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nfloat Vector2<T>::DistanceSquared(const Vector2<U>& v1, const Vector2<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 = XMVector2LengthSq(v);\n\n    return XMVectorGetX(x);\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nvoid Vector2<T>::Min(const Vector2<U>& v1, const Vector2<V>& v2, Vector2<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>\nVector2<T> Vector2<T>::Min(const Vector2<U>& v1, const Vector2<V>& v2) noexcept\n{\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&v2);\n    const XMVECTOR x = XMVectorMin(x1, x2);\n\n    Vector2<T> result;\n    Store(&result, x);\n    return result;\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nvoid Vector2<T>::Max(const Vector2<U>& v1, const Vector2<V>& v2, Vector2<T>& result) noexcept\n{\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&v2);\n    const XMVECTOR x = XMVectorMax(x1, x2);\n\n    Store(&result, x);\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nVector2<T> Vector2<T>::Max(const Vector2<U>& v1, const Vector2<V>& v2) noexcept\n{\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&v2);\n    const XMVECTOR x = XMVectorMax(x1, x2);\n\n    Vector2<T> result;\n    Store(&result, x);\n    return result;\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nvoid Vector2<T>::Lerp(const Vector2<U>& v1, const Vector2<V>& v2, const float t, Vector2<T>& result) noexcept\n{\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>\nVector2<T> Vector2<T>::Lerp(const Vector2<U>& v1, const Vector2<V>& v2, const float t) noexcept\n{\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&v2);\n    const XMVECTOR x = XMVectorLerp(x1, x2, t);\n\n    Vector2<T> result;\n    Store(&result, x);\n    return result;\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nvoid Vector2<T>::SmoothStep(const Vector2<U>& v1, const Vector2<V>& v2, float t, Vector2<T>& result) noexcept\n{\n    t = t > 1.0f ? 1.0f : t < 0.0f ? 0.0f : t; // Clamp value to 0 to 1\n    t = t * t * (3.f - 2.f * 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>\nVector2<T> Vector2<T>::SmoothStep(const Vector2<U>& v1, const Vector2<V>& v2, float t) noexcept\n{\n    t = t > 1.0f ? 1.0f : t < 0.0f ? 0.0f : t; // Clamp value to 0 to 1\n    t = t * t * (3.f - 2.f * t);\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&v2);\n    const XMVECTOR x = XMVectorLerp(x1, x2, t);\n\n    Vector2<T> result;\n    Store(&result, x);\n    return result;\n}\n\ntemplate <class T>\ntemplate <class U, class V, class W>\nvoid Vector2<T>::Barycentric(const Vector2<U>& v1, const Vector2<V>& v2, const Vector2<W>& v3, const float f,\n                             const float g, Vector2<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>\nVector2<T> Vector2<T>::Barycentric(const Vector2<U>& v1, const Vector2<V>& v2, const Vector2<W>& v3, const float f,\n                                   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    Vector2<T> result;\n    Store(&result, x);\n    return result;\n}\n\ntemplate <class T>\ntemplate <class U, class V, class W, class X>\nvoid Vector2<T>::CatmullRom(const Vector2<U>& v1, const Vector2<V>& v2, const Vector2<W>& v3, const Vector2<X>& v4,\n                            const float t, Vector2<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>\nVector2<T> Vector2<T>::CatmullRom(const Vector2<U>& v1, const Vector2<V>& v2, const Vector2<W>& v3,\n                                  const Vector2<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    Vector2<T> result;\n    Store(&result, x);\n    return result;\n}\n\ntemplate <class T>\ntemplate <class U, class V, class W, class X>\nvoid Vector2<T>::Hermite(const Vector2<U>& v1, const Vector2<V>& t1, const Vector2<W>& v2, const Vector2<X>& t2,\n                         const float t, Vector2<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>\nVector2<T> Vector2<T>::Hermite(const Vector2<U>& v1, const Vector2<V>& t1, const Vector2<W>& v2, const Vector2<X>& t2,\n                               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    Vector2<T> result;\n    Store(&result, x);\n    return result;\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nvoid Vector2<T>::Reflect(const Vector2<U>& iVec, const Vector2<V>& nVec, Vector2<T>& result) noexcept\n{\n    const XMVECTOR i = Load(&iVec);\n    const XMVECTOR n = Load(&nVec);\n    const XMVECTOR x = XMVector2Reflect(i, n);\n\n    Store(&result, x);\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nVector2<T> Vector2<T>::Reflect(const Vector2<U>& iVec, const Vector2<V>& nVec) noexcept\n{\n    const XMVECTOR i = Load(&iVec);\n    const XMVECTOR n = Load(&nVec);\n    const XMVECTOR x = XMVector2Reflect(i, n);\n\n    Vector2<T> result;\n    Store(&result, x);\n    return result;\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nvoid Vector2<T>::Refract(const Vector2<U>& iVec, const Vector2<V>& nVec, const float refractionIndex,\n                         Vector2<T>& result) noexcept\n{\n    const XMVECTOR i = Load(&iVec);\n    const XMVECTOR n = Load(&nVec);\n    const XMVECTOR x = XMVector2Refract(i, n, refractionIndex);\n\n    Store(&result, x);\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nVector2<T> Vector2<T>::Refract(const Vector2<U>& iVec, const Vector2<V>& nVec, const float refractionIndex) noexcept\n{\n    const XMVECTOR i = Load(&iVec);\n    const XMVECTOR n = Load(&nVec);\n    const XMVECTOR x = XMVector2Refract(i, n, refractionIndex);\n\n    Vector2<T> result;\n    Store(&result, x);\n    return result;\n}\n\ntemplate <class T>\ntemplate <class U>\nvoid Vector2<T>::Transform(const Vector2<U>& v, const Quaternion& quat, Vector2<T>& result) noexcept\n{\n    const XMVECTOR v1 = Load(&v);\n    const XMVECTOR q = XMLoadFloat4(&quat);\n    const XMVECTOR x = XMVector3Rotate(v1, q);\n\n    Store(&result, x);\n}\n\ntemplate <class T>\ntemplate <class U>\nVector2<T> Vector2<T>::Transform(const Vector2<U>& v, const Quaternion& quat) noexcept\n{\n    const XMVECTOR v1 = Load(&v);\n    const XMVECTOR q = XMLoadFloat4(&quat);\n    const XMVECTOR x = XMVector3Rotate(v1, q);\n\n    Vector2<T> result;\n    Store(&result, x);\n    return result;\n}\n\ntemplate <class T>\ntemplate <class U>\nvoid Vector2<T>::Transform(const Vector2<U>& v, const Matrix& m, Vector2<T>& result) noexcept\n{\n    const XMVECTOR v1 = Load(&v);\n    const XMMATRIX m1 = XMLoadFloat4x4(&m);\n    const XMVECTOR x = XMVector2TransformCoord(v1, m1);\n\n    Store(&result, x);\n}\n\ntemplate <class T>\ntemplate <class U>\nVector2<T> Vector2<T>::Transform(const Vector2<U>& v, const Matrix& m) noexcept\n{\n    const XMVECTOR v1 = Load(&v);\n    const XMMATRIX m1 = XMLoadFloat4x4(&m);\n    const XMVECTOR x = XMVector2TransformCoord(v1, m1);\n\n    Vector2<T> result;\n    Store(&result, x);\n    return result;\n}\n\ntemplate <class T>\ntemplate <class U>\n_Use_decl_annotations_\n\nvoid Vector2<T>::Transform(const Vector2<U>* varray, const size_t count, const Matrix& m,\n                           Vector2<T>* resultArray) noexcept\n{\n    const XMMATRIX m1 = XMLoadFloat4x4(&m);\n    XMVector2TransformCoordStream(resultArray, sizeof Vector2Base<U>::Vector, varray, sizeof Vector2Base<T>::Vector,\n                                  count, m1);\n}\n\n\ntemplate <class T>\ntemplate <class U>\nvoid Vector2<T>::TransformNormal(const Vector2<U>& v, const Matrix& m, Vector2<T>& result) noexcept\n{\n    const XMVECTOR v1 = Load(&v);\n    const XMMATRIX m1 = XMLoadFloat4x4(&m);\n    const XMVECTOR x = XMVector2TransformNormal(v1, m1);\n\n    Store(&result, x);\n}\n\ntemplate <class T>\ntemplate <class U>\nVector2<T> Vector2<T>::TransformNormal(const Vector2<U>& v, const Matrix& m) noexcept\n{\n    const XMVECTOR v1 = Load(&v);\n    const XMMATRIX m1 = XMLoadFloat4x4(&m);\n    const XMVECTOR x = XMVector2TransformNormal(v1, m1);\n\n    Vector2<T> result;\n    Store(&result, x);\n    return result;\n}\n\ntemplate <class T>\ntemplate <class U>\n_Use_decl_annotations_\n\nvoid Vector2<T>::TransformNormal(const Vector2<U>* varray, const size_t count, const Matrix& m,\n                                 Vector2<T>* resultArray) noexcept\n{\n    const XMMATRIX m1 = XMLoadFloat4x4(&m);\n    XMVector2TransformNormalStream(resultArray, sizeof Vector2Base<U>::Vector, varray, sizeof Vector2Base<T>::Vector,\n                                   count, m1);\n}\n\n\n//------------------------------------------------------------------------------\n// Binary operators\n//------------------------------------------------------------------------------\n\ntemplate <class T, class U, class V>\nVector2<T> operator+(const Vector2<U>& v1, const Vector2<V>& v2) noexcept\n{\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&v2);\n    const XMVECTOR x = XMVectorAdd(x1, x2);\n\n    Vector2<T> r;\n    Vector2<T>::Store(&r, x);\n    return r;\n}\n\ntemplate <class T, class U, class V>\nVector2<T> operator-(const Vector2<U>& v1, const Vector2<V>& v2) noexcept\n{\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&v2);\n    const XMVECTOR x = XMVectorSubtract(x1, x2);\n\n    Vector2<T> r;\n    Vector2<T>::Store(&r, x);\n    return r;\n}\n\ntemplate <class T, class U, class V>\nVector2<T> operator*(const Vector2<U>& v1, const Vector2<V>& v2) noexcept\n{\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&v2);\n    const XMVECTOR x = XMVectorMultiply(x1, x2);\n\n    Vector2<T> r;\n    Vector2<T>::Store(&r, x);\n    return r;\n}\n\ntemplate <class T, class U>\nVector2<T> operator*(const Vector2<U>& v, const float s) noexcept\n{\n    const XMVECTOR x1 = Load(&v);\n    const XMVECTOR x = XMVectorScale(x1, s);\n\n    Vector2<T> r;\n    Vector2<T>::Store(&r, x);\n    return r;\n}\n\ntemplate <class T, class U, class V>\nVector2<T> operator/(const Vector2<U>& v1, const Vector2<V>& v2) noexcept\n{\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&v2);\n    const XMVECTOR x = XMVectorDivide(x1, x2);\n\n    Vector2<T> r;\n    Vector2<T>::Store(&r, x);\n    return r;\n}\n\ntemplate <class T, class U>\nVector2<T> operator/(const Vector2<U>& v, const float s) noexcept\n{\n    const XMVECTOR v1 = Load(&v);\n    const XMVECTOR x = XMVectorScale(v1, 1.f / s);\n\n    Vector2<T> r;\n    Vector2<T>::Store(&r, x);\n    return r;\n}\n\ntemplate <class T, class U>\nVector2<T> operator*(const float s, const Vector2<U>& v) noexcept\n{\n    const XMVECTOR v1 = Load(&v);\n    const XMVECTOR x = XMVectorScale(v1, s);\n\n    Vector2<T> r;\n    Vector2<T>::Store(&r, x);\n    return r;\n}\n\ntemplate struct Vector2<float>;\ntemplate struct Vector2<int32_t>;\ntemplate struct Vector2<uint32_t>;\n", "meta": {"hexsha": "3c5c136ca1fd318d4a22ba11137145a8427dc176", "size": 20555, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BlocksEngine/src/Core/Math/Vector2.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/Vector2.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/Vector2.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.3525641026, "max_line_length": 118, "alphanum_fraction": 0.6024324982, "num_tokens": 5833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.289249323369957}}
{"text": "#include \"geometric/bounding_box.hpp\"\n\n#include <algorithm>\n#include <cmath>       // for atan, exp\n#include <type_traits> // for move, swap\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace nepomuk\n{\nnamespace geometric\n{\n\nWGS84BoundingBox::WGS84BoundingBox(WGS84Coordinate lower_left, WGS84Coordinate upper_right)\n    : lower_left(std::move(lower_left)), upper_right(std::move(upper_right))\n{\n}\n\nWGS84BoundingBox::WGS84BoundingBox(std::uint32_t const horizontal,\n                                   std::uint32_t const vertical,\n                                   std::uint32_t const zoom_level,\n                                   double const tile_size,\n                                   std::int32_t const mercator_buffer)\n{\n    double min_lon = horizontal * tile_size - mercator_buffer;\n    double max_lon = (horizontal + 1.0) * tile_size + mercator_buffer;\n\n    double min_lat = (vertical + 1.0) * tile_size + mercator_buffer;\n    double max_lat = vertical * tile_size - mercator_buffer;\n\n    // 2^z * TILE_SIZE\n    const double shift = (1u << static_cast<unsigned>(zoom_level)) * tile_size;\n\n    auto const shift_lon = [shift](double const lon) {\n        return (lon - 0.5 * shift) / shift * 360.0;\n    };\n\n    auto const shift_lat = [shift](double const lat) {\n        auto const tmp =\n            boost::math::constants::pi<double>() * constants::rad_to_degree * (1 - 2 * lat / shift);\n\n        auto const clamped = std::max<long double>(-180., std::min<long double>(180., tmp));\n        auto const normalized =\n            constants::rad_to_degree * 2. * std::atan(std::exp(clamped * constants::degree_to_rad));\n\n        return normalized - 90.;\n    };\n\n    min_lon = shift_lon(min_lon);\n    max_lon = shift_lon(max_lon);\n    min_lat = shift_lat(min_lat);\n    max_lat = shift_lat(max_lat);\n\n    lower_left = WGS84Coordinate(makeLatLonFromDouble<FixedLongitude>(min_lon),\n                                 makeLatLonFromDouble<FixedLatitude>(min_lat));\n    upper_right = WGS84Coordinate(makeLatLonFromDouble<FixedLongitude>(max_lon),\n                                  makeLatLonFromDouble<FixedLatitude>(max_lat));\n}\n\nbool WGS84BoundingBox::contains(WGS84Coordinate const &coordinate) const\n{\n    return lower_left.longitude <= coordinate.longitude &&\n           coordinate.longitude <= upper_right.longitude &&\n           lower_left.latitude <= coordinate.latitude &&\n           coordinate.latitude <= upper_right.latitude;\n}\n\ndouble WGS84BoundingBox::width() const\n{\n    return doubleFromLatLon(upper_right.longitude) - doubleFromLatLon(lower_left.longitude);\n}\n\ndouble WGS84BoundingBox::height() const\n{\n    return doubleFromLatLon(upper_right.latitude) - doubleFromLatLon(lower_left.latitude);\n}\n\nMercatorBoundingBox::MercatorBoundingBox(MercatorCoordinate lower_left_,\n                                         MercatorCoordinate upper_right_)\n    : lower_left(lower_left_), upper_right(upper_right_)\n{\n    // mercator transformations switch invert latitude (counting from upper right). If the\n    // coordinates don't match up (e.g. due to conversion issues) we need to swap them to the\n    // correct order\n    if (lower_left.latitude > upper_right.latitude)\n        std::swap(lower_left.latitude, upper_right.latitude);\n}\n\nMercatorBoundingBox::MercatorBoundingBox(std::uint32_t const horizontal,\n                                         std::uint32_t const vertical,\n                                         std::uint32_t const zoom_level,\n                                         double const tile_size,\n                                         std::int32_t const mercator_buffer)\n{\n    WGS84BoundingBox bbox(horizontal, vertical, zoom_level, tile_size, mercator_buffer);\n    lower_left = MercatorCoordinate(bbox.lower_left);\n    upper_right = MercatorCoordinate(bbox.upper_right);\n    std::swap(lower_left.latitude, upper_right.latitude);\n}\n\nbool MercatorBoundingBox::contains(MercatorCoordinate const &coordinate) const\n{\n    return lower_left.longitude <= coordinate.longitude &&\n           coordinate.longitude <= upper_right.longitude &&\n           lower_left.latitude <= coordinate.latitude &&\n           coordinate.latitude <= upper_right.latitude;\n}\n\ndouble MercatorBoundingBox::width() const\n{\n    return doubleFromLatLon(upper_right.longitude) - doubleFromLatLon(lower_left.longitude);\n}\ndouble MercatorBoundingBox::height() const\n{\n    return doubleFromLatLon(upper_right.latitude) - doubleFromLatLon(lower_left.latitude);\n}\n\n} // namespace geometric\n} // namespace nepomuk\n", "meta": {"hexsha": "7330dd63e2b69917be0dd1c24436232566860819", "size": 4509, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometric/bounding_box.cpp", "max_stars_repo_name": "mapbox/nepomuk", "max_stars_repo_head_hexsha": "8771482edb9b16bb0f5a152c15681c57eb3bb6b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2017-05-12T11:52:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T06:05:08.000Z", "max_issues_repo_path": "src/geometric/bounding_box.cpp", "max_issues_repo_name": "mapbox/nepomuk", "max_issues_repo_head_hexsha": "8771482edb9b16bb0f5a152c15681c57eb3bb6b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 49.0, "max_issues_repo_issues_event_min_datetime": "2017-05-11T16:13:58.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-13T11:19:17.000Z", "max_forks_repo_path": "src/geometric/bounding_box.cpp", "max_forks_repo_name": "mapbox/nepomuk", "max_forks_repo_head_hexsha": "8771482edb9b16bb0f5a152c15681c57eb3bb6b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-11-19T12:04:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T06:14:25.000Z", "avg_line_length": 37.575, "max_line_length": 100, "alphanum_fraction": 0.6675537813, "num_tokens": 955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558604, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2889901633737459}}
{"text": "#include <iostream>\n#include <boost/astronomy/coordinate/cartesian_representation.hpp>\n#include <boost/units/systems/si/length.hpp>\n#include <boost/units/io.hpp>\n\nusing namespace boost::astronomy::coordinate;\nusing namespace boost::units;\nusing namespace boost::units::si;\n\ntypedef boost::geometry::model::point<double, 3, boost::geometry::cs::spherical<boost::geometry::degree>> geometry_point;\n\nint main()\n{\n    //creating point without any value\n    cartesian_representation<double, quantity<si::length>, quantity<si::length>, quantity<si::length>> point1;\n\n    //creating a point by directly providing values of x, y and z\n    auto point2 = make_cartesian_representation(10.0 * meter, 20.0 * meter, 30.0 * meter);\n\n    //assigning value of individual component\n    point1.set_x(50.0 * meter);\n    point1.set_y(40.0 * meter);\n    point1.set_z(880.0 * meter);\n\n    //or to set all the values in single statement tuple could be used as follow\n    point2.set_x_y_z(38.5 * meter, 50.0 * meter, 64.23 * meter);\n\n    //creating a point from another point\n    auto point3 = make_cartesian_representation(point2);\n\n    //creating a point from boost::geometry::model::point\n    //any type of point can be used here\n    //here we will demonstrate with cartesian point\n    //https://www.boost.org/doc/libs/1_71_0/libs/geometry/doc/html/geometry/reference/models/model_point.html\n    //https://www.boost.org/doc/libs/1_71_0/libs/geometry/doc/html/geometry/reference/cs.html\n    geometry_point gp(45.0, 60.0, 50.0);\n    auto point4 = make_cartesian_representation<double, quantity<si::length>, quantity<si::length>, quantity<si::length>>(gp);\n\n    //accessing each component of representation\n    std::cout << point4.get_x() << point4.get_y()<<std::endl; //methods get_y and get_z are available\n\n    //get boost::geometry::model::point of current object\n    auto stored_point = point3.get_point();\n\n    //get the tuple of the component in the coordinate\n    std::tuple<quantity<si::length>, quantity<si::length>, quantity<si::length>>\n        components = point3.get_x_y_z();\n\n    std::cin.get();\n    return 0;\n}", "meta": {"hexsha": "2e5882858d3e721d902669c40c150df3e8ae2e48", "size": 2102, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "astro.cpp", "max_stars_repo_name": "avinal/C_ode", "max_stars_repo_head_hexsha": "f056da37c8c56a4a62a06351c2ea3773d16d1b11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-23T20:21:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-23T20:21:35.000Z", "max_issues_repo_path": "astro.cpp", "max_issues_repo_name": "avinal/C_ode", "max_issues_repo_head_hexsha": "f056da37c8c56a4a62a06351c2ea3773d16d1b11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "astro.cpp", "max_forks_repo_name": "avinal/C_ode", "max_forks_repo_head_hexsha": "f056da37c8c56a4a62a06351c2ea3773d16d1b11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-03-18T10:22:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-03T10:12:28.000Z", "avg_line_length": 41.2156862745, "max_line_length": 126, "alphanum_fraction": 0.7174119886, "num_tokens": 546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.28890034460258746}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2008 Lorella Fatone\n Copyright (C) 2008 Francesca Mariani\n Copyright (C) 2008 Maria Cristina Recchioni\n Copyright (C) 2008 Francesco Zirilli\n Copyright (C) 2008 StatPro Italia srl\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <ql/experimental/varianceoption/integralhestonvarianceoptionengine.hpp>\n#include <ql/errors.hpp>\n#include <ql/function.hpp>\n#include <boost/scoped_array.hpp>\n#include <complex>\n\nnamespace QuantLib {\n\n    namespace {\n\n    /*\n     *****************************************************************\n     **\n     ** Parameters defining the initial condition of the Heston model\n     ** and the European call option\n     **\n     *****************************************************************\n     */\n    /*\n     *****************************************************************\n     ** Assign: v0, eprice, tau, rtax\n     ******************************************************************\n     ******************************************************************\n     **     v0: initial variance\n     ** eprice: realized variance strike price\n     **    tau: time to maturity\n     *    rtax: risk free interest rate\n     ****************************************************************\n     */\n\n    typedef std::complex<Real> Complex;\n\n    Real IvopOneDim(Real eps, Real chi, Real theta, Real /*rho*/,\n                      Real v0, Real eprice, Time tau, Real rtax)\n    {\n        Real ss=0.0;\n        boost::scoped_array<double> xiv(new double[2048*2048+1]);\n        double nris=0.0;\n        int j=0,mm=0;\n        double pi=0,pi2=0;\n        double dstep=0;\n        Real option=0, impart=0;\n\n        boost::scoped_array<Complex> ff(new Complex[2048*2048]);\n        Complex xi;\n        Complex ui,beta,zita,gamma,csum,vero;\n        Complex contrib, caux, caux1,caux2,caux3;\n\n        ui=Complex(0.0,1.0);\n\n        /*\n         **********************************************************\n         **   i0: initial integrated variance i0=0\n         **********************************************************\n         */\n        Real i0=0.0;\n        //s=2.0*chi*theta/(eps*eps)-1.0;\n\n        //s=s+1;\n\n        /*\n         *************************************************\n         ** Start integration procedure\n         *************************************************\n         */\n\n        pi= 3.14159265358979324;\n        pi2=2.0*pi;\n        Real s=2.0*chi*theta/(eps*eps)-1.0;\n        /*\n         ****************************************\n         ** Note that s must be greater than zero\n         ****************************************\n         */\n\n        if(s<=0)\n        {\n            QL_FAIL(\"this parameter must be greater than zero-> \" << s);\n        }\n\n        ss=s+1;\n\n        /*\n         *************************************************\n         ** Start integration procedure\n         *************************************************\n\n         **************************************************************\n         ** The oscillatory integral that approximates the price of\n         ** the realized variance option is computed using the method\n         ** proposed by Bailey, Swarztrauber in the paper published in\n         ** Siam Journal on Scientific Computing Vol 15(5) 1994\n         ** p. 1105-1110\n         **************************************************************\n\n         **************************************************************\n         ** dstep: real number, generally a power of two, that must be\n         **        assigned to determine the grid of\n         **        integration. Hint: dstep=256 or 512 (dstep<=2048)\n         **************************************************************\n         */\n        dstep=256.0;\n        nris=std::sqrt(pi2)/dstep;\n        mm=(int)(pi2/(nris*nris));\n\n        /*\n         ******************************************\n         **  Definition of the integration grid  **\n         ******************************************\n         */\n        for (j=0;j<=mm-1;j++)\n        {\n            xiv[j+1]=(double)(j-mm/2)*nris;\n        }\n\n        for (j=0;j<=mm-1;j++)\n        {\n            xi=xiv[j+1];\n            caux=chi*chi;\n            caux1=2.0*eps*eps;\n            caux1=caux1*xi;\n            caux1=caux1*ui;\n            caux2=caux1+caux;\n\n            zita=0.5*std::sqrt(caux2);\n\n            caux1=std::exp(-2.0*tau*zita);\n\n            beta=0.5*chi+zita;\n            beta=beta+caux1*(zita-0.5*chi);\n            gamma=1.0-caux1;\n\n            caux=-ss*tau;\n            caux2=caux*(zita-0.5*chi);\n            caux=ss*std::log(2.0*(zita/beta));\n            caux3=-v0*ui*xi*(gamma/beta);\n            caux=caux+caux3;\n            caux=caux+caux2;\n\n            ff[j+1]=std::exp(caux);\n            if(std::sqrt(std::imag(xi)*std::imag(xi)+std::real(xi)*std::real(xi))>1.e-06)\n            {\n                contrib=-eprice/(ui*xi);\n                caux=ui*xi;\n                caux=caux*eprice;\n                caux=std::exp(caux);\n                caux=caux-1.0;\n                caux2=ui*xi*ui*xi;\n                contrib=contrib+caux/caux2;\n            }\n            else\n            {\n                contrib=eprice*eprice*0.5;\n            }\n            ff[j+1]=ff[j+1]*contrib;\n        }\n        csum=0.0;\n        for (j=0;j<=mm-1;j++)\n        {\n            caux=std::pow(-1.0,j);\n            caux2=-2.0*pi*(double)mm*(double)j*0.5/(double)mm;\n            caux3=ui*caux2;\n            csum=csum+ff[j+1]*caux*std::exp(caux3);\n        }\n        csum=csum*std::sqrt(std::pow(-1.0,mm))*nris/pi2;\n        vero=i0-eprice+theta*tau+(1.0-std::exp(-chi*tau))*(v0-theta)/chi;\n        csum=csum+vero;\n        option=std::exp(-rtax*tau)*std::real(csum);\n        impart=std::imag(csum);\n        QL_ENSURE(impart <= 1e-12,\n                  \"imaginary part option (must be zero) = \" << impart);\n        return option;\n    }\n\n\n\n    Real IvopTwoDim(Real eps, Real chi, Real theta, Real /*rho*/,\n                    Real v0, Time tau, Real rtax,\n                    const ext::function<Real(Real)>& payoff) {\n\n        Real ss=0.0;\n        boost::scoped_array<double> xiv(new double[2048*2048+1]);\n        boost::scoped_array<double> ivet(new double[2048 * 2048 + 1]);\n        double nris=0.0;\n        int j=0,mm=0,k=0;\n        double pi=0,pi2=0;\n\n        double dstep=0;\n        Real ip=0;\n        Real payoffval=0;\n        Real option=0/*, impart=0*/;\n\n        Real sumr=0;//,sumi=0;\n        Complex dxi,z;\n\n        boost::scoped_array<Complex> ff(new Complex[2048*2048]);\n        Complex xi;\n        Complex ui,beta,zita,gamma,csum;\n        Complex caux,caux1,caux2,caux3;\n\n        ui=Complex(0.0,1.0);\n\n        /*\n         **********************************************************\n         **   i0: initial integrated variance i0=0\n         **********************************************************\n         */\n        Real i0=0.0;\n\n        /*\n         *************************************************\n         ** Start integration procedure\n         *************************************************\n         */\n\n        pi= 3.14159265358979324;\n        pi2=2.0*pi;\n\n        Real s=2.0*chi*theta/(eps*eps)-1.0;\n        /*\n         ****************************************\n         ** Note that s must be greater than zero\n         ****************************************\n         */\n\n        if(s<=0)\n        {\n            QL_FAIL(\"this parameter must be greater than zero-> \" << s);\n        }\n\n        ss=s+1;\n\n        /*\n         *************************************************\n         ** Start integration procedure\n         *************************************************\n\n         **************************************************************\n         ** The oscillatory integral that approximates the price of\n         ** the realized variance option is computed using the method\n         ** proposed by Bailey, Swarztrauber in the paper published in\n         ** Siam Journal on Scientific Computing Vol 15(5) 1994\n         ** p. 1105-1110\n         **************************************************************\n\n         **************************************************************\n         ** dstep: real number, generally a power of two that must be\n         **        assigned to determine the grid of\n         **        integration. Hint: dstep=256 or 512 (dstep<=2048)\n         **************************************************************\n         */\n        dstep=64.0;\n        nris=std::sqrt(pi2)/dstep;\n        mm=(int)(pi2/(nris*nris));\n\n        /*\n         ******************************************\n         **  Definition of the integration grid  **\n         ******************************************\n         */\n\n        for (j=0;j<=mm-1;j++)\n        {\n            xiv[j+1]=(double)(j-mm/2)*nris;\n            ivet[j+1]=(double)(j-mm/2)*pi2/((double)mm*nris);\n        }\n\n        for (j=0;j<=mm-1;j++)\n        {\n            xi=xiv[j+1];\n\n            caux=chi*chi;\n            caux1=2.0*eps*eps;\n            caux1=caux1*xi;\n            caux1=caux1*ui;\n            caux2=caux1+caux;\n\n            zita=0.5*std::sqrt(caux2);\n            caux1=std::exp(-2.0*tau*zita);\n\n            beta=0.5*chi+zita;\n            beta=beta+caux1*(zita-0.5*chi);\n\n            gamma=1.0-caux1;\n\n            caux=-ss*tau;\n            caux2=caux*(zita-0.5*chi);\n            caux=ss*std::log(2.0*(zita/beta));\n            caux3=-v0*ui*xi*(gamma/beta);\n            caux=caux+caux3;\n            caux=caux+caux2;\n            ff[j+1]=std::exp(caux);\n        }\n\n        sumr=0.0;\n        //sumi=0.0;\n        for (k=0;k<=mm-1;k++)\n        {\n            ip=i0-ivet[k+1];\n            payoffval=payoff(ip);\n\n            dxi=2.0*pi*(double)k/(double)mm*ui;\n            csum=0.0;\n            for (j=0;j<=mm-1;j++)\n            {\n                z=-(double)j*dxi;\n                caux=std::pow(-1.0,j);\n                csum=csum+ff[j+1]*caux*std::exp(z);\n            }\n            csum=csum*std::pow(-1.0,k)*nris/pi2;\n\n            sumr=sumr+payoffval*std::real(csum);\n            //sumi=sumi+payoffval*std::imag(csum);\n        }\n        sumr=sumr*nris;\n        //sumi=sumi*nris;\n\n        option=std::exp(-rtax*tau)*sumr;\n        //impart=sumi;\n        //QL_ENSURE(impart <= 1e-3,\n        //          \"imaginary part option (must be close to zero) = \" << impart);\n        return option;\n    }\n\n    struct payoff_adapter {\n        ext::shared_ptr<QuantLib::Payoff> payoff;\n        explicit payoff_adapter(ext::shared_ptr<QuantLib::Payoff> payoff)\n        : payoff(payoff) {}\n        Real operator()(Real S) const {\n            return (*payoff)(S);\n        }\n    };\n\n    }\n\n    IntegralHestonVarianceOptionEngine::IntegralHestonVarianceOptionEngine(\n                              const ext::shared_ptr<HestonProcess>& process)\n    : process_(process) {\n        registerWith(process_);\n    }\n\n    void IntegralHestonVarianceOptionEngine::calculate() const {\n\n        QL_REQUIRE(process_->dividendYield().empty(),\n                   \"this engine does not manage dividend yields\");\n\n        Handle<YieldTermStructure> riskFreeRate = process_->riskFreeRate();\n\n        Real epsilon = process_->sigma();\n        Real chi = process_->kappa();\n        Real theta = process_->theta();\n        Real rho = process_->rho();\n        Real v0 = process_->v0();\n\n        Time tau = riskFreeRate->dayCounter().yearFraction(\n                                        Settings::instance().evaluationDate(),\n                                        arguments_.maturityDate);\n        Rate r = riskFreeRate->zeroRate(arguments_.maturityDate,\n                                        riskFreeRate->dayCounter(),\n                                        Continuous);\n\n        ext::shared_ptr<PlainVanillaPayoff> plainPayoff =\n            ext::dynamic_pointer_cast<PlainVanillaPayoff>(arguments_.payoff);\n        if (plainPayoff && plainPayoff->optionType() == Option::Call) {\n            // a specialization for Call options is available\n            Real strike = plainPayoff->strike();\n            results_.value = IvopOneDim(epsilon, chi, theta, rho,\n                                        v0, strike, tau, r)\n                * arguments_.notional;\n        } else {\n            results_.value = IvopTwoDim(epsilon, chi, theta, rho, v0, tau, r,\n                                        payoff_adapter(arguments_.payoff))\n                * arguments_.notional;\n        }\n    }\n\n}\n\n", "meta": {"hexsha": "819a12fdb8bf7654567d30739d5a471752830c2e", "size": 13059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/varianceoption/integralhestonvarianceoptionengine.cpp", "max_stars_repo_name": "boobar/QuantLib", "max_stars_repo_head_hexsha": "d7c43398e7bc78d6ad9ea2dc93f899e93e452875", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ql/experimental/varianceoption/integralhestonvarianceoptionengine.cpp", "max_issues_repo_name": "boobar/QuantLib", "max_issues_repo_head_hexsha": "d7c43398e7bc78d6ad9ea2dc93f899e93e452875", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ql/experimental/varianceoption/integralhestonvarianceoptionengine.cpp", "max_forks_repo_name": "boobar/QuantLib", "max_forks_repo_head_hexsha": "d7c43398e7bc78d6ad9ea2dc93f899e93e452875", "max_forks_repo_licenses": ["BSD-3-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.4850746269, "max_line_length": 89, "alphanum_fraction": 0.4349490773, "num_tokens": 3182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2888084850178978}}
{"text": "/*\n * Copyright (c) 2017 Louis Langholtz https://github.com/louis-langholtz/Box2D\n *\n * This software is provided 'as-is', without any express or implied\n * warranty. In no event will the authors be held liable for any damages\n * arising from the use of this software.\n *\n * Permission is granted to anyone to use this software for any purpose,\n * including commercial applications, and to alter it and redistribute it\n * freely, subject to the following restrictions:\n *\n * 1. The origin of this software must not be misrepresented; you must not\n *    claim that you wrote the original software. If you use this software\n *    in a product, an acknowledgment in the product documentation would be\n *    appreciated but is not required.\n * 2. Altered source versions must be plainly marked as such, and must not be\n *    misrepresented as being the original software.\n * 3. This notice may not be removed or altered from any source distribution.\n */\n\n/**\n * @file\n * @brief Units file.\n */\n\n#ifndef Units_hpp\n#define Units_hpp\n\n#include <Box2D/Common/RealNum.hpp>\n#include <Box2D/Common/Templates.hpp>\n\n// #define USE_BOOST_UNITS\n#ifdef USE_BOOST_UNITS\n#include <boost/units/io.hpp>\n#include <boost/units/systems/si/length.hpp>\n#include <boost/units/systems/si/time.hpp>\n#include <boost/units/systems/si/velocity.hpp>\n#include <boost/units/systems/si/acceleration.hpp>\n#include <boost/units/systems/si/frequency.hpp>\n#include <boost/units/systems/si/velocity.hpp>\n#include <boost/units/systems/si/mass.hpp>\n#include <boost/units/systems/si/momentum.hpp>\n#include <boost/units/systems/si/inverse_mass.hpp>\n#include <boost/units/systems/si/area.hpp>\n#include <boost/units/systems/si/plane_angle.hpp>\n#include <boost/units/systems/si/angular_momentum.hpp>\n#include <boost/units/systems/si/angular_velocity.hpp>\n#include <boost/units/systems/si/angular_acceleration.hpp>\n#include <boost/units/systems/si/second_moment_of_area.hpp>\n#include <boost/units/systems/si/surface_density.hpp>\n#include <boost/units/systems/si/moment_of_inertia.hpp>\n#include <boost/units/systems/si/inverse_moment_of_inertia.hpp>\n#include <boost/units/systems/si/force.hpp>\n#include <boost/units/systems/si/torque.hpp>\n#include <boost/units/systems/angle/degrees.hpp>\n#endif\n\nnamespace box2d\n{    \n#ifdef USE_BOOST_UNITS\n    \n    using Time = boost::units::quantity<boost::units::si::time, Real>;\n    constexpr auto Second = Time{boost::units::si::second * Real{1}};\n    \n    using Frequency = boost::units::quantity<boost::units::si::frequency, Real>;\n    constexpr auto Hertz = Frequency{boost::units::si::hertz * Real{1}};\n    \n    using Length = boost::units::quantity<boost::units::si::length, Real>;\n    constexpr auto Meter = Length{boost::units::si::meter * Real{1}};\n    \n    using LinearVelocity = boost::units::quantity<boost::units::si::velocity, Real>;\n    constexpr auto MeterPerSecond = LinearVelocity{boost::units::si::meter_per_second * Real{1}};\n    \n    using LinearAcceleration = boost::units::quantity<boost::units::si::acceleration, Real>;\n    constexpr auto MeterPerSquareSecond = LinearAcceleration{boost::units::si::meter_per_second_squared * Real{1}};\n    \n    using Mass = boost::units::quantity<boost::units::si::mass, Real>;\n    constexpr auto Kilogram = Mass{boost::units::si::kilogram * Real{1}};\n    \n    using InvMass = boost::units::quantity<boost::units::si::inverse_mass, Real>;\n    \n    using Area = boost::units::quantity<boost::units::si::area, Real>;\n    constexpr auto SquareMeter = Area{boost::units::si::square_meter * Real{1}};\n    \n    using Density = boost::units::quantity<boost::units::si::surface_density, Real>;\n    constexpr auto KilogramPerSquareMeter = Density{boost::units::si::kilogram_per_square_meter * Real{1}};\n    \n    using Angle = boost::units::quantity<boost::units::si::plane_angle, Real>;\n    constexpr auto Radian = Angle{boost::units::si::radian * Real{1}};\n    constexpr auto Degree = Angle{boost::units::degree::degree * Real{1}};\n    constexpr auto SquareRadian = Radian * Radian;\n    \n    using AngularVelocity = boost::units::quantity<boost::units::si::angular_velocity, Real>;\n    constexpr auto RadianPerSecond = AngularVelocity{boost::units::si::radian_per_second * Real{1}};\n    constexpr auto DegreePerSecond = AngularVelocity{RadianPerSecond * Degree / Radian};\n    \n    using AngularAcceleration = boost::units::quantity<boost::units::si::angular_acceleration, Real>;\n    constexpr auto RadianPerSquareSecond = Radian / (Second * Second);\n    \n    using Force = boost::units::quantity<boost::units::si::force, Real>;\n    constexpr auto Newton = Force{boost::units::si::newton * Real{1}};\n    \n    using Torque = boost::units::quantity<boost::units::si::torque, Real>;\n    constexpr auto NewtonMeter = Torque{boost::units::si::newton_meter * Real{1}};\n    \n    using SecondMomentOfArea = boost::units::quantity<boost::units::si::second_moment_of_area, Real>;\n    \n    using RotInertia = boost::units::quantity<boost::units::si::moment_of_inertia, Real>;\n    using InvRotInertia = boost::units::quantity<boost::units::si::inverse_moment_of_inertia, Real>;\n    \n    using Momentum = boost::units::quantity<boost::units::si::momentum, Real>;\n    constexpr auto NewtonSecond = Newton * Second;\n    \n    /// @brief Angular momentum.\n    /// @note Units of L^2 M T^-1 QP^-1.\n    using AngularMomentum = boost::units::quantity<boost::units::si::angular_momentum, Real>;\n    \n#else // USE_BOOST_UNITS\n    \n    using Time = Real;\n    constexpr auto Second = Real{1};\n    \n    using Frequency = Real;\n    constexpr auto Hertz = Real{1};\n    \n    using Length = Real;\n    constexpr auto Meter = Real{1};\n    \n    using LinearVelocity = Real;\n    constexpr auto MeterPerSecond = Real{1};\n    \n    using LinearAcceleration = Real;\n    constexpr auto MeterPerSquareSecond = Real{1};\n    \n    using Mass = Real;\n    constexpr auto Kilogram = Real{1};\n    \n    using InvMass = Real;\n    \n    using Area = Real;\n    constexpr auto SquareMeter = Real{1};\n    \n    using Density = Real;\n    constexpr auto KilogramPerSquareMeter = Real{1};\n    \n    using Angle = Real;\n    constexpr auto Radian = Real{1};\n    constexpr auto Degree = Pi / Real{180};\n    constexpr auto SquareRadian = Radian * Radian;\n    \n    using AngularVelocity = Real;\n    constexpr auto RadianPerSecond = Real{1};\n    constexpr auto DegreePerSecond = Degree;\n    \n    using AngularAcceleration = Real;\n    constexpr auto RadianPerSquareSecond = Real{1};\n    \n    using Force = Real;\n    constexpr auto Newton = Real{1};\n    \n    using Torque = Real;\n    constexpr auto NewtonMeter = Real{1};\n    \n    using SecondMomentOfArea = Real;\n    \n    using RotInertia = Real;\n    using InvRotInertia = Real;\n    \n    using Momentum = Real;\n    constexpr auto NewtonSecond = Real{1};\n    \n    using AngularMomentum = Real;\n    \n#endif // USE_BOOST_UNITS\n    \n    constexpr inline Real StripUnit(const Real value)\n    {\n        return value;\n    }\n    \n#ifdef USE_BOOST_UNITS\n    \n    constexpr inline Real StripUnit(const Angle value)\n    {\n        return Real{value / Radian};\n    }\n    \n    constexpr inline Real StripUnit(const Length value)\n    {\n        return Real{value / Meter};\n    }\n    \n    constexpr inline Real StripUnit(const Area value)\n    {\n        return Real{value / SquareMeter};\n    }\n    \n    constexpr inline Real StripUnit(const Mass value)\n    {\n        // InvMass has units of M^-1\n        return Real{value / Kilogram};\n    }\n    \n    constexpr inline Real StripUnit(const InvMass value)\n    {\n        // InvMass has units of M^-1\n        return Real{value * Kilogram};\n    }\n    \n    constexpr inline Real StripUnit(const RotInertia value)\n    {\n        return Real{value * SquareRadian / (SquareMeter * Kilogram)};\n    }\n    \n    constexpr inline Real StripUnit(const InvRotInertia value)\n    {\n        // InvRotInertia has units of L^-2 M^-1 QP^2\n        return Real{value * SquareMeter * Kilogram / SquareRadian};\n    }\n    \n    constexpr inline Real StripUnit(const Momentum value)\n    {\n        // Momentum has units of M L T^-1\n        return Real{value * Second / (Kilogram * Meter)};\n    }\n    \n    constexpr inline Real StripUnit(const LinearVelocity value)\n    {\n        return Real{value / MeterPerSecond};\n    }\n    \n    constexpr inline Real StripUnit(const AngularVelocity value)\n    {\n        return Real{value / RadianPerSecond};\n    }\n    \n    constexpr inline Real StripUnit(const Density value)\n    {\n        return Real{value / KilogramPerSquareMeter};\n    }\n    \n    constexpr inline Real StripUnit(const Force value)\n    {\n        // Force has units of Newtons - which are M L T^2\n        return Real{value / Newton};\n    }\n    \n    constexpr inline Real StripUnit(const Torque value)\n    {\n        return Real{value / NewtonMeter};\n    }\n        \n    template <>\n    constexpr Angle GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() * Radian;\n    }\n    \n    template <>\n    constexpr inline bool IsValid(const Angle& x) noexcept\n    {\n        return IsValid(Real{x / Radian});\n    }\n    \n    template <>\n    constexpr Frequency GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() * Hertz;\n    }\n    \n    template <>\n    constexpr inline bool IsValid(const Frequency& x) noexcept\n    {\n        return IsValid(Real{x / Hertz});\n    }\n    \n    template <>\n    constexpr AngularVelocity GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() * RadianPerSecond;\n    }\n    \n    template <>\n    constexpr inline bool IsValid(const AngularVelocity& x) noexcept\n    {\n        return IsValid(Real{x / RadianPerSecond});\n    }\n    \n    template <>\n    constexpr Time GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() * Second;\n    }\n    \n    template <>\n    constexpr inline bool IsValid(const Time& x) noexcept\n    {\n        return IsValid(Real{x / Second});\n    }\n    \n    template <>\n    constexpr Length GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() * Meter;\n    }\n    \n    template <>\n    constexpr inline bool IsValid(const Length& x) noexcept\n    {\n        return IsValid(Real{x / Meter});\n    }\n    \n    template <>\n    constexpr Mass GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() * Kilogram;\n    }\n    \n    template <>\n    constexpr inline bool IsValid(const Mass& x) noexcept\n    {\n        return IsValid(Real{x / Kilogram});\n    }\n    \n    template <>\n    constexpr InvMass GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() / Kilogram;\n    }\n    \n    template <>\n    constexpr inline bool IsValid(const InvMass& x) noexcept\n    {\n        return IsValid(Real{x * Kilogram});\n    }\n    \n    template <>\n    constexpr Momentum GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() * Kilogram * MeterPerSecond;\n    }\n    \n    template <>\n    constexpr inline bool IsValid(const Momentum& x) noexcept\n    {\n        return IsValid(Real{x / (Kilogram * MeterPerSecond)});\n    }\n    \n    template <>\n    constexpr Force GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() * Newton;\n    }\n    \n    template <>\n    constexpr inline bool IsValid(const Force& x) noexcept\n    {\n        return IsValid(Real{x / Newton});\n    }\n    \n    template <>\n    constexpr Torque GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() * NewtonMeter;\n    }\n    \n    template <>\n    constexpr inline bool IsValid(const Torque& x) noexcept\n    {\n        return IsValid(Real{x / NewtonMeter});\n    }\n    \n    template <>\n    constexpr LinearVelocity GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() * MeterPerSecond;\n    }\n    \n    template <>\n    constexpr inline bool IsValid(const LinearVelocity& x) noexcept\n    {\n        return IsValid(Real{x / MeterPerSecond});\n    }\n    \n    template <>\n    constexpr LinearAcceleration GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() * MeterPerSquareSecond;\n    }\n    \n    template <>\n    constexpr inline bool IsValid(const LinearAcceleration& x) noexcept\n    {\n        return IsValid(Real{x / MeterPerSquareSecond});\n    }\n    \n    template <>\n    constexpr AngularAcceleration GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() * RadianPerSquareSecond;\n    }\n    \n    template <>\n    constexpr inline bool IsValid(const AngularAcceleration& x) noexcept\n    {\n        return IsValid(Real{x / RadianPerSquareSecond});\n    }\n    \n    template <>\n    constexpr RotInertia GetInvalid() noexcept\n    {\n        // RotInertia is L^2  M    QP^-2\n        return GetInvalid<Real>() * SquareMeter * Kilogram / SquareRadian;\n    }\n    \n    template <>\n    constexpr inline bool IsValid(const RotInertia& value) noexcept\n    {\n        return IsValid(Real{value / (SquareMeter * Kilogram / SquareRadian)});\n    }\n    \n#endif\n\n} // namespace box2d\n\n#endif /* Units_hpp */\n", "meta": {"hexsha": "40399bbe36d507aab53c8cddbee211d68ed43c1b", "size": 12765, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Box2D/Common/Units.hpp", "max_stars_repo_name": "louis-langholtz/Box2D", "max_stars_repo_head_hexsha": "7c74792bf177cf36640d735de2bba0225bf7f852", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2016-10-20T05:55:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T16:34:41.000Z", "max_issues_repo_path": "Box2D/Common/Units.hpp", "max_issues_repo_name": "louis-langholtz/Box2D", "max_issues_repo_head_hexsha": "7c74792bf177cf36640d735de2bba0225bf7f852", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 50.0, "max_issues_repo_issues_event_min_datetime": "2017-01-07T21:40:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-31T10:04:05.000Z", "max_forks_repo_path": "Box2D/Common/Units.hpp", "max_forks_repo_name": "louis-langholtz/Box2D", "max_forks_repo_head_hexsha": "7c74792bf177cf36640d735de2bba0225bf7f852", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-02-09T10:02:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-23T22:49:04.000Z", "avg_line_length": 29.8946135831, "max_line_length": 115, "alphanum_fraction": 0.6567959264, "num_tokens": 3021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.5, "lm_q1q2_score": 0.28874768986450766}}
{"text": "//          Copyright (C) 2012, Michele Caini.\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//          Two Graphs Common Spanning Trees Algorithm\n//      Based on academic article of Mint, Read and Tarjan\n//     Efficient Algorithm for Common Spanning Tree Problem\n// Electron. Lett., 28 April 1983, Volume 19, Issue 9, p.346-347\n\n\n#ifndef BOOST_GRAPH_TWO_GRAPHS_COMMON_SPANNING_TREES_HPP\n#define BOOST_GRAPH_TWO_GRAPHS_COMMON_SPANNING_TREES_HPP\n\n\n#include <boost/config.hpp>\n\n#include <boost/bimap.hpp>\n#include <boost/type_traits.hpp>\n#include <boost/concept/requires.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/undirected_dfs.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/filtered_graph.hpp>\n#include <vector>\n#include <stack>\n#include <map>\n\n\nnamespace boost\n{\n\n\nnamespace detail {\n\n\n  template\n    <\n      typename TreeMap,\n      typename PredMap,\n      typename DistMap,\n      typename LowMap,\n      typename Buffer\n    >\n  struct bridges_visitor: public default_dfs_visitor\n  {\n    bridges_visitor(\n        TreeMap tree,\n        PredMap pred,\n        DistMap dist,\n        LowMap low,\n        Buffer& buffer\n      ): mTree(tree), mPred(pred), mDist(dist), mLow(low), mBuffer(buffer)\n    { mNum = -1; }\n\n    template <typename Vertex, typename Graph>\n    void initialize_vertex(const Vertex& u, const Graph& g)\n    {\n      put(mPred, u, u);\n      put(mDist, u, -1);\n    }\n\n    template <typename Vertex, typename Graph>\n    void discover_vertex(const Vertex& u, const Graph& g)\n    {\n      put(mDist, u, ++mNum);\n      put(mLow, u, get(mDist, u));\n    }\n\n    template <typename Edge, typename Graph>\n    void tree_edge(const Edge& e, const Graph& g)\n    {\n      put(mPred, target(e, g), source(e, g));\n      put(mTree, target(e, g), e);\n    }\n\n    template <typename Edge, typename Graph>\n    void back_edge(const Edge& e, const Graph& g)\n    {\n      put(mLow, source(e, g),\n        (std::min)(get(mLow, source(e, g)), get(mDist, target(e, g))));\n    }\n\n    template <typename Vertex, typename Graph>\n    void finish_vertex(const Vertex& u, const Graph& g)\n    {\n      Vertex parent = get(mPred, u);\n      if(get(mLow, u) > get(mDist, parent))\n        mBuffer.push(get(mTree, u));\n      put(mLow, parent,\n        (std::min)(get(mLow, parent), get(mLow, u)));\n    }\n\n    TreeMap mTree;\n    PredMap mPred;\n    DistMap mDist;\n    LowMap mLow;\n    Buffer& mBuffer;\n    int mNum;\n  };\n\n\n  template <typename Buffer>\n  struct cycle_finder: public base_visitor< cycle_finder<Buffer> >\n  {\n    typedef on_back_edge event_filter;\n    cycle_finder(): mBuffer(0) { }\n    cycle_finder(Buffer* buffer)\n      : mBuffer(buffer) { }\n    template <typename Edge, typename Graph>\n    void operator()(const Edge& e, const Graph& g)\n      {\n        if(mBuffer)\n          mBuffer->push(e);\n      }\n    Buffer* mBuffer;\n  };\n\n\n  template <typename DeletedMap>\n  struct deleted_edge_status\n  {\n    deleted_edge_status() { }\n    deleted_edge_status(DeletedMap map): mMap(map) { }\n    template <typename Edge>\n    bool operator()(const Edge& e) const\n      { return (!get(mMap, e)); }\n    DeletedMap mMap;\n  };\n\n\n  template <typename InLMap>\n  struct inL_edge_status\n  {\n    inL_edge_status() { }\n    inL_edge_status(InLMap map): mMap(map) { }\n    template <typename Edge>\n    bool operator()(const Edge& e) const\n      { return get(mMap, e); }\n    InLMap mMap;\n  };\n\n\n  template <\n    typename Graph,\n    typename Func,\n    typename Seq,\n    typename Map\n  >\n  void rec_two_graphs_common_spanning_trees\n    (\n      const Graph& iG,\n      bimap<\n          bimaps::set_of<int>,\n          bimaps::set_of< typename graph_traits<Graph>::edge_descriptor >\n        > iG_bimap,\n      Map aiG_inL,\n      Map diG,\n      const Graph& vG,\n      bimap<\n          bimaps::set_of<int>,\n          bimaps::set_of< typename graph_traits<Graph>::edge_descriptor >\n        > vG_bimap,\n      Map avG_inL,\n      Map dvG,\n      Func func,\n      Seq inL\n    )\n  {\n    typedef graph_traits<Graph> GraphTraits;\n\n    typedef typename GraphTraits::vertex_descriptor vertex_descriptor;\n    typedef typename GraphTraits::edge_descriptor edge_descriptor;\n\n    typedef typename Seq::size_type seq_size_type;\n\n    int edges = num_vertices(iG) - 1;\n//\n//  [ Michele Caini ]\n//\n//  Using the condition (edges != 0) leads to the accidental submission of\n//    sub-graphs ((V-1+1)-fake-tree, named here fat-tree).\n//  Remove this condition is a workaround for the problem of fat-trees.\n//  Please do not add that condition, even if it improves performance.\n//\n//  Here is proposed the previous guard (that was wrong):\n//     for(seq_size_type i = 0; (i < inL.size()) && (edges != 0); ++i)\n//\n    {\n      for(seq_size_type i = 0; i < inL.size(); ++i)\n        if(inL[i])\n          --edges;\n\n      if(edges < 0)\n        return;\n    }\n\n    bool is_tree = (edges == 0);\n    if(is_tree) {\n      func(inL);\n    } else {\n      std::map<vertex_descriptor, default_color_type> vertex_color;\n      std::map<edge_descriptor, default_color_type> edge_color;\n\n      std::stack<edge_descriptor> iG_buf, vG_buf;\n      bool found = false;\n\n      seq_size_type m;\n      for(seq_size_type j = 0; j < inL.size() && !found; ++j) {\n        if(!inL[j]\n            && !get(diG, iG_bimap.left.at(j))\n            && !get(dvG, vG_bimap.left.at(j)))\n        {\n          put(aiG_inL, iG_bimap.left.at(j), true);\n          put(avG_inL, vG_bimap.left.at(j), true);\n\n          undirected_dfs(\n              make_filtered_graph(iG,\n                detail::inL_edge_status< associative_property_map<\n                  std::map<edge_descriptor, bool> > >(aiG_inL)),\n              make_dfs_visitor(\n                detail::cycle_finder< std::stack<edge_descriptor> > (&iG_buf)),\n              associative_property_map<\n                std::map<vertex_descriptor, default_color_type> >(vertex_color),\n              associative_property_map<\n                std::map<edge_descriptor, default_color_type> >(edge_color)\n            );\n          undirected_dfs(\n              make_filtered_graph(vG,\n                detail::inL_edge_status< associative_property_map<\n                  std::map<edge_descriptor, bool> > >(avG_inL)),\n              make_dfs_visitor(\n                detail::cycle_finder< std::stack<edge_descriptor> > (&vG_buf)),\n              associative_property_map<\n                std::map<vertex_descriptor, default_color_type> >(vertex_color),\n              associative_property_map<\n                std::map<edge_descriptor, default_color_type> >(edge_color)\n            );\n\n          if(iG_buf.empty() && vG_buf.empty()) {\n            inL[j] = true;\n            found = true;\n            m = j;\n          } else {\n            while(!iG_buf.empty()) iG_buf.pop();\n            while(!vG_buf.empty()) vG_buf.pop();\n            put(aiG_inL, iG_bimap.left.at(j), false);\n            put(avG_inL, vG_bimap.left.at(j), false);\n          }\n        }\n      }\n\n      if(found) {\n\n        std::stack<edge_descriptor> iG_buf_copy, vG_buf_copy;\n        for(seq_size_type j = 0; j < inL.size(); ++j) {\n          if(!inL[j]\n              && !get(diG, iG_bimap.left.at(j))\n              && !get(dvG, vG_bimap.left.at(j)))\n          {\n\n            put(aiG_inL, iG_bimap.left.at(j), true);\n            put(avG_inL, vG_bimap.left.at(j), true);\n\n            undirected_dfs(\n                make_filtered_graph(iG,\n                  detail::inL_edge_status< associative_property_map<\n                    std::map<edge_descriptor, bool> > >(aiG_inL)),\n                make_dfs_visitor(\n                  detail::cycle_finder<\n                    std::stack<edge_descriptor> > (&iG_buf)),\n               associative_property_map< std::map<\n                  vertex_descriptor, default_color_type> >(vertex_color),\n                associative_property_map<\n                  std::map<edge_descriptor, default_color_type> >(edge_color)\n              );\n            undirected_dfs(\n                make_filtered_graph(vG,\n                  detail::inL_edge_status< associative_property_map<\n                    std::map<edge_descriptor, bool> > >(avG_inL)),\n                make_dfs_visitor(\n                  detail::cycle_finder<\n                    std::stack<edge_descriptor> > (&vG_buf)),\n                associative_property_map< std::map<\n                  vertex_descriptor, default_color_type> >(vertex_color),\n                associative_property_map<\n                  std::map<edge_descriptor, default_color_type> >(edge_color)\n              );\n\n            if(!iG_buf.empty() || !vG_buf.empty()) {\n              while(!iG_buf.empty()) iG_buf.pop();\n              while(!vG_buf.empty()) vG_buf.pop();\n              put(diG, iG_bimap.left.at(j), true);\n              put(dvG, vG_bimap.left.at(j), true);\n              iG_buf_copy.push(iG_bimap.left.at(j));\n              vG_buf_copy.push(vG_bimap.left.at(j));\n            }\n\n            put(aiG_inL, iG_bimap.left.at(j), false);\n            put(avG_inL, vG_bimap.left.at(j), false);\n          }\n        }\n\n        // REC\n        detail::rec_two_graphs_common_spanning_trees<Graph, Func, Seq, Map>\n          (iG, iG_bimap, aiG_inL, diG, vG, vG_bimap, aiG_inL, dvG, func, inL);\n\n        while(!iG_buf_copy.empty()) {\n          put(diG, iG_buf_copy.top(), false);\n          put(dvG, vG_bimap.left.at(\n            iG_bimap.right.at(iG_buf_copy.top())), false);\n          iG_buf_copy.pop();\n        }\n        while(!vG_buf_copy.empty()) {\n          put(dvG, vG_buf_copy.top(), false);\n          put(diG, iG_bimap.left.at(\n            vG_bimap.right.at(vG_buf_copy.top())), false);\n          vG_buf_copy.pop();\n        }\n\n        inL[m] = false;\n        put(aiG_inL, iG_bimap.left.at(m), false);\n        put(avG_inL, vG_bimap.left.at(m), false);\n\n        put(diG, iG_bimap.left.at(m), true);\n        put(dvG, vG_bimap.left.at(m), true);\n\n        std::map<vertex_descriptor, edge_descriptor> tree_map;\n        std::map<vertex_descriptor, vertex_descriptor> pred_map;\n        std::map<vertex_descriptor, int> dist_map, low_map;\n\n        detail::bridges_visitor<\n            associative_property_map<\n                std::map<vertex_descriptor, edge_descriptor>\n              >,\n            associative_property_map<\n                std::map<vertex_descriptor, vertex_descriptor>\n              >,\n            associative_property_map< std::map<vertex_descriptor, int> >,\n            associative_property_map< std::map<vertex_descriptor, int> >,\n            std::stack<edge_descriptor>\n          >\n        iG_vis(\n            associative_property_map<\n              std::map< vertex_descriptor, edge_descriptor> >(tree_map),\n            associative_property_map<\n              std::map< vertex_descriptor, vertex_descriptor> >(pred_map),\n            associative_property_map<\n              std::map< vertex_descriptor, int> >(dist_map),\n            associative_property_map<\n              std::map< vertex_descriptor, int> >(low_map),\n            iG_buf\n          ),\n        vG_vis(\n            associative_property_map<\n              std::map< vertex_descriptor, edge_descriptor> >(tree_map),\n            associative_property_map<\n              std::map< vertex_descriptor, vertex_descriptor> >(pred_map),\n            associative_property_map<\n              std::map< vertex_descriptor, int> >(dist_map),\n            associative_property_map<\n              std::map< vertex_descriptor, int> >(low_map),\n            vG_buf\n          );\n\n        undirected_dfs(make_filtered_graph(iG,\n              detail::deleted_edge_status< associative_property_map<\n              std::map<edge_descriptor, bool> > >(diG)),\n            iG_vis,\n            associative_property_map<\n              std::map<vertex_descriptor, default_color_type> >(vertex_color),\n            associative_property_map<\n              std::map<edge_descriptor, default_color_type> >(edge_color)\n          );\n        undirected_dfs(make_filtered_graph(vG,\n              detail::deleted_edge_status< associative_property_map<\n              std::map<edge_descriptor, bool> > >(dvG)),\n            vG_vis,\n            associative_property_map<\n              std::map<vertex_descriptor, default_color_type> >(vertex_color),\n            associative_property_map<\n              std::map<edge_descriptor, default_color_type> >(edge_color)\n          );\n\n        found = false;\n        std::stack<edge_descriptor> iG_buf_tmp, vG_buf_tmp;\n        while(!iG_buf.empty() && !found) {\n          if(!inL[iG_bimap.right.at(iG_buf.top())]) {\n            put(aiG_inL, iG_buf.top(), true);\n            put(avG_inL, vG_bimap.left.at(\n              iG_bimap.right.at(iG_buf.top())), true);\n\n            undirected_dfs(\n                make_filtered_graph(iG,\n                  detail::inL_edge_status< associative_property_map<\n                    std::map<edge_descriptor, bool> > >(aiG_inL)),\n                make_dfs_visitor(\n                  detail::cycle_finder<\n                    std::stack<edge_descriptor> > (&iG_buf_tmp)),\n                associative_property_map<\n                  std::map<\n                    vertex_descriptor, default_color_type> >(vertex_color),\n                associative_property_map<\n                  std::map<edge_descriptor, default_color_type> >(edge_color)\n              );\n            undirected_dfs(\n                make_filtered_graph(vG,\n                  detail::inL_edge_status< associative_property_map<\n                    std::map<edge_descriptor, bool> > >(avG_inL)),\n                make_dfs_visitor(\n                  detail::cycle_finder<\n                    std::stack<edge_descriptor> > (&vG_buf_tmp)),\n                associative_property_map<\n                  std::map<\n                    vertex_descriptor, default_color_type> >(vertex_color),\n                associative_property_map<\n                  std::map<edge_descriptor, default_color_type> >(edge_color)\n              );\n\n            if(!iG_buf_tmp.empty() || !vG_buf_tmp.empty()) {\n              found = true;\n            } else {\n              while(!iG_buf_tmp.empty()) iG_buf_tmp.pop();\n              while(!vG_buf_tmp.empty()) vG_buf_tmp.pop();\n              iG_buf_copy.push(iG_buf.top());\n            }\n\n            put(aiG_inL, iG_buf.top(), false);\n            put(avG_inL, vG_bimap.left.at(\n              iG_bimap.right.at(iG_buf.top())), false);\n          }\n          iG_buf.pop();\n        }\n        while(!vG_buf.empty() && !found) {\n          if(!inL[vG_bimap.right.at(vG_buf.top())]) {\n            put(avG_inL, vG_buf.top(), true);\n            put(aiG_inL, iG_bimap.left.at(\n              vG_bimap.right.at(vG_buf.top())), true);\n\n            undirected_dfs(\n                make_filtered_graph(iG,\n                  detail::inL_edge_status< associative_property_map<\n                    std::map<edge_descriptor, bool> > >(aiG_inL)),\n                make_dfs_visitor(\n                  detail::cycle_finder<\n                    std::stack<edge_descriptor> > (&iG_buf_tmp)),\n                associative_property_map<\n                  std::map<\n                    vertex_descriptor, default_color_type> >(vertex_color),\n                associative_property_map<\n                  std::map<edge_descriptor, default_color_type> >(edge_color)\n              );\n            undirected_dfs(\n                make_filtered_graph(vG,\n                  detail::inL_edge_status< associative_property_map<\n                    std::map<edge_descriptor, bool> > >(avG_inL)),\n                make_dfs_visitor(\n                  detail::cycle_finder<\n                    std::stack<edge_descriptor> > (&vG_buf_tmp)),\n                associative_property_map<\n                  std::map<\n                    vertex_descriptor, default_color_type> >(vertex_color),\n                associative_property_map<\n                  std::map<edge_descriptor, default_color_type> >(edge_color)\n              );\n\n            if(!iG_buf_tmp.empty() || !vG_buf_tmp.empty()) {\n              found = true;\n            } else {\n              while(!iG_buf_tmp.empty()) iG_buf_tmp.pop();\n              while(!vG_buf_tmp.empty()) vG_buf_tmp.pop();\n              vG_buf_copy.push(vG_buf.top());\n            }\n\n            put(avG_inL, vG_buf.top(), false);\n            put(aiG_inL, iG_bimap.left.at(\n              vG_bimap.right.at(vG_buf.top())), false);\n          }\n          vG_buf.pop();\n        }\n\n        if(!found) {\n\n          while(!iG_buf_copy.empty()) {\n            inL[iG_bimap.right.at(iG_buf_copy.top())] = true;\n            put(aiG_inL, iG_buf_copy.top(), true);\n            put(avG_inL, vG_bimap.left.at(\n              iG_bimap.right.at(iG_buf_copy.top())), true);\n            iG_buf.push(iG_buf_copy.top());\n            iG_buf_copy.pop();\n          }\n          while(!vG_buf_copy.empty()) {\n            inL[vG_bimap.right.at(vG_buf_copy.top())] = true;\n            put(avG_inL, vG_buf_copy.top(), true);\n            put(aiG_inL, iG_bimap.left.at(\n              vG_bimap.right.at(vG_buf_copy.top())), true);\n            vG_buf.push(vG_buf_copy.top());\n            vG_buf_copy.pop();\n          }\n\n          // REC\n          detail::rec_two_graphs_common_spanning_trees<\n              Graph, Func, Seq, Map>\n            (iG, iG_bimap, aiG_inL, diG, vG, vG_bimap, aiG_inL, dvG, func, inL);\n\n          while(!iG_buf.empty()) {\n            inL[iG_bimap.right.at(iG_buf.top())] = false;\n            put(aiG_inL, iG_buf.top(), false);\n            put(avG_inL, vG_bimap.left.at(\n              iG_bimap.right.at(iG_buf.top())), false);\n            iG_buf.pop();\n          }\n          while(!vG_buf.empty()) {\n            inL[vG_bimap.right.at(vG_buf.top())] = false;\n            put(avG_inL, vG_buf.top(), false);\n            put(aiG_inL, iG_bimap.left.at(\n              vG_bimap.right.at(vG_buf.top())), false);\n            vG_buf.pop();\n          }\n\n        }\n\n        put(diG, iG_bimap.left.at(m), false);\n        put(dvG, vG_bimap.left.at(m), false);\n\n      }\n    }\n  }\n\n} // namespace detail\n\n\n\ntemplate <typename Coll, typename Seq>\nstruct tree_collector\n{\n\npublic:\n  BOOST_CONCEPT_ASSERT((BackInsertionSequence<Coll>));\n  BOOST_CONCEPT_ASSERT((RandomAccessContainer<Seq>));\n  BOOST_CONCEPT_ASSERT((CopyConstructible<Seq>));\n\n  typedef typename Coll::value_type coll_value_type;\n  typedef typename Seq::value_type seq_value_type;\n\n  BOOST_STATIC_ASSERT((is_same<coll_value_type, Seq>::value));\n  BOOST_STATIC_ASSERT((is_same<seq_value_type, bool>::value));\n\n  tree_collector(Coll& seqs): mSeqs(seqs) { }\n\n  inline void operator()(Seq seq)\n    { mSeqs.push_back(seq); }\n\nprivate:\n  Coll& mSeqs;\n\n};\n\n\n\ntemplate <\n  typename Graph,\n  typename Order,\n  typename Func,\n  typename Seq\n>\nBOOST_CONCEPT_REQUIRES(\n  ((RandomAccessContainer<Order>))\n  ((IncidenceGraphConcept<Graph>))\n  ((UnaryFunction<Func, void, Seq>))\n  ((Mutable_RandomAccessContainer<Seq>))\n  ((VertexAndEdgeListGraphConcept<Graph>)),\n  (void)\n)\ntwo_graphs_common_spanning_trees\n  (\n    const Graph& iG,\n    Order iG_map,\n    const Graph& vG,\n    Order vG_map,\n    Func func,\n    Seq inL\n  )\n{\n  typedef graph_traits<Graph> GraphTraits;\n\n  typedef typename GraphTraits::directed_category directed_category;\n  typedef typename GraphTraits::vertex_descriptor vertex_descriptor;\n  typedef typename GraphTraits::edge_descriptor edge_descriptor;\n\n  typedef typename GraphTraits::edges_size_type edges_size_type;\n  typedef typename GraphTraits::edge_iterator edge_iterator;\n\n  typedef typename Seq::const_iterator seq_const_iterator;\n  typedef typename Seq::difference_type seq_diff_type;\n  typedef typename Seq::value_type seq_value_type;\n  typedef typename Seq::size_type seq_size_type;\n  typedef typename Seq::iterator seq_iterator;\n\n  typedef typename Order::const_iterator order_const_iterator;\n  typedef typename Order::difference_type order_diff_type;\n  typedef typename Order::value_type order_value_type;\n  typedef typename Order::size_type order_size_type;\n  typedef typename Order::iterator order_iterator;\n\n  BOOST_STATIC_ASSERT((is_same<order_value_type, edge_descriptor>::value));\n  BOOST_CONCEPT_ASSERT((Convertible<order_size_type, edges_size_type>));\n\n  BOOST_CONCEPT_ASSERT((Convertible<seq_size_type, edges_size_type>));\n  BOOST_STATIC_ASSERT((is_same<seq_value_type, bool>::value));\n\n  BOOST_STATIC_ASSERT((is_same<directed_category, undirected_tag>::value));\n\n  if(num_vertices(iG) != num_vertices(vG))\n    return;\n\n  if(inL.size() != num_edges(iG)\n      || inL.size() != num_edges(vG))\n    return;\n\n  if(iG_map.size() != num_edges(iG)\n      || vG_map.size() != num_edges(vG))\n    return;\n\n  typedef bimaps::bimap<\n      bimaps::set_of< int >,\n      bimaps::set_of< order_value_type >\n    > bimap_type;\n  typedef typename bimap_type::value_type bimap_value;\n\n  bimap_type iG_bimap, vG_bimap;\n  for(order_size_type i = 0; i < iG_map.size(); ++i)\n    iG_bimap.insert(bimap_value(i, iG_map[i]));\n  for(order_size_type i = 0; i < vG_map.size(); ++i)\n    vG_bimap.insert(bimap_value(i, vG_map[i]));\n\n  edge_iterator current, last;\n  boost::tuples::tie(current, last) = edges(iG);\n  for(; current != last; ++current)\n    if(iG_bimap.right.find(*current) == iG_bimap.right.end())\n      return;\n  boost::tuples::tie(current, last) = edges(vG);\n  for(; current != last; ++current)\n    if(vG_bimap.right.find(*current) == vG_bimap.right.end())\n      return;\n\n  std::stack<edge_descriptor> iG_buf, vG_buf;\n\n  std::map<vertex_descriptor, edge_descriptor> tree_map;\n  std::map<vertex_descriptor, vertex_descriptor> pred_map;\n  std::map<vertex_descriptor, int> dist_map, low_map;\n\n  detail::bridges_visitor<\n      associative_property_map<\n          std::map<vertex_descriptor, edge_descriptor>\n        >,\n      associative_property_map<\n          std::map<vertex_descriptor, vertex_descriptor>\n        >,\n      associative_property_map< std::map<vertex_descriptor, int> >,\n      associative_property_map< std::map<vertex_descriptor, int> >,\n      std::stack<edge_descriptor>\n    >\n  iG_vis(\n      associative_property_map<\n        std::map< vertex_descriptor, edge_descriptor> >(tree_map),\n      associative_property_map<\n        std::map< vertex_descriptor, vertex_descriptor> >(pred_map),\n      associative_property_map<std::map< vertex_descriptor, int> >(dist_map),\n      associative_property_map<std::map< vertex_descriptor, int> >(low_map),\n      iG_buf\n    ),\n  vG_vis(\n      associative_property_map<\n        std::map< vertex_descriptor, edge_descriptor> >(tree_map),\n      associative_property_map<\n        std::map< vertex_descriptor, vertex_descriptor> >(pred_map),\n      associative_property_map<std::map< vertex_descriptor, int> >(dist_map),\n      associative_property_map<std::map< vertex_descriptor, int> >(low_map),\n      vG_buf\n    );\n\n  std::map<vertex_descriptor, default_color_type> vertex_color;\n  std::map<edge_descriptor, default_color_type> edge_color;\n\n  undirected_dfs(iG, iG_vis,\n      associative_property_map<\n        std::map<vertex_descriptor, default_color_type> >(vertex_color),\n      associative_property_map<\n        std::map<edge_descriptor, default_color_type> >(edge_color)\n    );\n  undirected_dfs(vG, vG_vis,\n      associative_property_map<\n        std::map<vertex_descriptor, default_color_type> >(vertex_color),\n      associative_property_map<\n        std::map<edge_descriptor, default_color_type> >(edge_color)\n    );\n\n  while(!iG_buf.empty()) {\n    inL[iG_bimap.right.at(iG_buf.top())] = true;\n    iG_buf.pop();\n  }\n  while(!vG_buf.empty()) {\n    inL[vG_bimap.right.at(vG_buf.top())] = true;\n    vG_buf.pop();\n  }\n\n  std::map<edge_descriptor, bool> iG_inL, vG_inL;\n  associative_property_map< std::map<edge_descriptor, bool> >\n    aiG_inL(iG_inL), avG_inL(vG_inL);\n\n  for(seq_size_type i = 0; i < inL.size(); ++i)\n  {\n    if(inL[i]) {\n      put(aiG_inL, iG_bimap.left.at(i), true);\n      put(avG_inL, vG_bimap.left.at(i), true);\n    } else {\n      put(aiG_inL, iG_bimap.left.at(i), false);\n      put(avG_inL, vG_bimap.left.at(i), false);\n    }\n  }\n\n  undirected_dfs(\n      make_filtered_graph(iG,\n        detail::inL_edge_status< associative_property_map<\n          std::map<edge_descriptor, bool> > >(aiG_inL)),\n      make_dfs_visitor(\n        detail::cycle_finder< std::stack<edge_descriptor> > (&iG_buf)),\n      associative_property_map<\n        std::map<vertex_descriptor, default_color_type> >(vertex_color),\n      associative_property_map<\n        std::map<edge_descriptor, default_color_type> >(edge_color)\n    );\n  undirected_dfs(\n      make_filtered_graph(vG,\n        detail::inL_edge_status< associative_property_map<\n          std::map<edge_descriptor, bool> > >(avG_inL)),\n      make_dfs_visitor(\n        detail::cycle_finder< std::stack<edge_descriptor> > (&vG_buf)),\n      associative_property_map<\n        std::map<vertex_descriptor, default_color_type> >(vertex_color),\n      associative_property_map<\n        std::map<edge_descriptor, default_color_type> >(edge_color)\n    );\n\n  if(iG_buf.empty() && vG_buf.empty()) {\n\n    std::map<edge_descriptor, bool> iG_deleted, vG_deleted;\n    associative_property_map< std::map<edge_descriptor, bool> > diG(iG_deleted);\n    associative_property_map< std::map<edge_descriptor, bool> > dvG(vG_deleted);\n\n    boost::tuples::tie(current, last) = edges(iG);\n    for(; current != last; ++current)\n      put(diG, *current, false);\n    boost::tuples::tie(current, last) = edges(vG);\n    for(; current != last; ++current)\n      put(dvG, *current, false);\n\n    for(seq_size_type j = 0; j < inL.size(); ++j) {\n      if(!inL[j]) {\n        put(aiG_inL, iG_bimap.left.at(j), true);\n        put(avG_inL, vG_bimap.left.at(j), true);\n\n        undirected_dfs(\n            make_filtered_graph(iG,\n              detail::inL_edge_status< associative_property_map<\n                std::map<edge_descriptor, bool> > >(aiG_inL)),\n            make_dfs_visitor(\n              detail::cycle_finder< std::stack<edge_descriptor> > (&iG_buf)),\n            associative_property_map<\n              std::map<vertex_descriptor, default_color_type> >(vertex_color),\n            associative_property_map<\n              std::map<edge_descriptor, default_color_type> >(edge_color)\n          );\n        undirected_dfs(\n            make_filtered_graph(vG,\n              detail::inL_edge_status< associative_property_map<\n                std::map<edge_descriptor, bool> > >(avG_inL)),\n            make_dfs_visitor(\n              detail::cycle_finder< std::stack<edge_descriptor> > (&vG_buf)),\n            associative_property_map<\n              std::map<vertex_descriptor, default_color_type> >(vertex_color),\n            associative_property_map<\n              std::map<edge_descriptor, default_color_type> >(edge_color)\n          );\n\n        if(!iG_buf.empty() || !vG_buf.empty()) {\n          while(!iG_buf.empty()) iG_buf.pop();\n          while(!vG_buf.empty()) vG_buf.pop();\n          put(diG, iG_bimap.left.at(j), true);\n          put(dvG, vG_bimap.left.at(j), true);\n        }\n\n        put(aiG_inL, iG_bimap.left.at(j), false);\n        put(avG_inL, vG_bimap.left.at(j), false);\n      }\n    }\n\n    int cc = 0;\n\n    std::map<vertex_descriptor, int> com_map;\n    cc += connected_components(\n        make_filtered_graph(iG,\n          detail::deleted_edge_status<associative_property_map<\n            std::map<edge_descriptor, bool> > >(diG)),\n        associative_property_map<std::map<vertex_descriptor, int> >(com_map)\n      );\n    cc += connected_components(\n        make_filtered_graph(vG,\n          detail::deleted_edge_status<associative_property_map<\n            std::map<edge_descriptor, bool> > >(dvG)),\n        associative_property_map< std::map<vertex_descriptor, int> >(com_map)\n      );\n\n    if(cc != 2)\n      return;\n\n    // REC\n    detail::rec_two_graphs_common_spanning_trees<Graph, Func, Seq,\n        associative_property_map< std::map<edge_descriptor, bool> > >\n      (iG, iG_bimap, aiG_inL, diG, vG, vG_bimap, aiG_inL, dvG, func, inL);\n\n  }\n\n}\n\n\ntemplate <\n  typename Graph,\n  typename Func,\n  typename Seq\n>\nBOOST_CONCEPT_REQUIRES(\n  ((IncidenceGraphConcept<Graph>))\n  ((EdgeListGraphConcept<Graph>)),\n  (void)\n)\ntwo_graphs_common_spanning_trees\n  (\n    const Graph& iG,\n    const Graph& vG,\n    Func func,\n    Seq inL\n  )\n{\n  typedef graph_traits<Graph> GraphTraits;\n\n  typedef typename GraphTraits::edge_descriptor edge_descriptor;\n  typedef typename GraphTraits::edges_size_type edges_size_type;\n  typedef typename GraphTraits::edge_iterator edge_iterator;\n\n  std::vector<edge_descriptor> iGO, vGO;\n  edge_iterator curr, last;\n\n  boost::tuples::tie(curr, last) = edges(iG);\n  for(; curr != last; ++curr)\n    iGO.push_back(*curr);\n\n  boost::tuples::tie(curr, last) = edges(vG);\n  for(; curr != last; ++curr)\n    vGO.push_back(*curr);\n\n  two_graphs_common_spanning_trees(iG, iGO, vG, vGO, func, inL);\n}\n\n\n} // namespace boost\n\n\n#endif // BOOST_GRAPH_TWO_GRAPHS_COMMON_SPANNING_TREES_HPP\n", "meta": {"hexsha": "86d57ece076e2c20ed8be285f19b766c311e0799", "size": 28919, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/graph/two_graphs_common_spanning_trees.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2015-01-17T00:29:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-09T02:59:16.000Z", "max_issues_repo_path": "boost/boost/graph/two_graphs_common_spanning_trees.hpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2015-07-22T07:35:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-14T16:03:06.000Z", "max_forks_repo_path": "boost/boost/graph/two_graphs_common_spanning_trees.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 44.0, "max_forks_repo_forks_event_min_datetime": "2015-03-18T09:20:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T08:09:17.000Z", "avg_line_length": 33.2020665901, "max_line_length": 80, "alphanum_fraction": 0.607835679, "num_tokens": 7159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290152, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2887476898645076}}
{"text": "// practice 5-6\n\n#include <iostream>\n#include <boost/type_traits/is_reference.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/type_traits/is_pointer.hpp>\n#include <boost/type_traits/is_float.hpp>\n#include <boost/type_traits/alignment_of.hpp>\n#include <boost/type_traits/remove_reference.hpp>\n#include <boost/type_traits/remove_pointer.hpp>\n#include <boost/type_traits/add_pointer.hpp>\n#include <boost/type_traits/is_function.hpp>\n#include <boost/type_traits/is_const.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/mpl/apply.hpp>\n\n#include <boost/mpl/vector_c.hpp>\n#include <boost/mpl/vector.hpp>\n#include <boost/mpl/transform.hpp>\n#include <boost/mpl/equal.hpp>\n#include <boost/mpl/equal_to.hpp>\n#include <boost/mpl/not_equal_to.hpp>\n#include <boost/mpl/greater.hpp>\n#include <boost/mpl/plus.hpp>\n#include <boost/mpl/minus.hpp>\n#include <boost/mpl/or.hpp>\n#include <boost/mpl/and.hpp>\n#include <boost/mpl/multiplies.hpp>\n\n#include <boost/mpl/at.hpp>\n#include <boost/mpl/next.hpp>\n#include <boost/mpl/prior.hpp>\n#include <boost/mpl/begin.hpp>\n#include <boost/mpl/end.hpp>\n#include <boost/mpl/advance.hpp>\n#include <boost/mpl/push_front.hpp>\n#include <boost/mpl/pop_front.hpp>\n#include <boost/mpl/insert.hpp>\n#include <boost/mpl/size.hpp>\n\n\nusing namespace boost::mpl::placeholders;\n#include <iterator>\n#include <utility>\n#include <list>\n#include <vector>\n#include <string>\n#include <assert.h>\n\nnamespace mpl = boost::mpl;\n\n\n\ntemplate<class T> struct dim\n{\n\tBOOST_STATIC_ASSERT(0);\n};\n\ntemplate<class A, int N1, int N2, int N3>\nstruct dim< A[N1][N2][N3] > :\n\tmpl::vector_c<int, N1, N2, N3>\n{\n\ttypedef typename A value_type;\n};\n\n\ntemplate < class T >\nstruct dimensions :\n\tdim<T>::type\n{};\n\n\nstruct test : \n\tdimensions< float[10][5][3] >\n{\n\n};\n\n// dimensions seq<array>\n//size<seq>\n//at_c<seq,0>::type::value\ntypedef dimensions< char[10][9][8] > seq;\nBOOST_STATIC_ASSERT( mpl::size<seq>::value == 3 );\n\n//BOOST_STATIC_ASSERT( mpl::at<seq, mpl::int_<0> >::type::value );\n// BOOST_STATIC_ASSERT( \n// \t\tmpl::at<\n// \t\tmpl::vector_c<int, 10,1,2>\n// \t\t, mpl::int_<0>\n// \t\t>::type::value == 10 );\n\nstruct none{};\n\ntemplate<class T=int>\nstruct wrapAssert : T\n{\n\ttypedef typename T type;\n\tBOOST_STATIC_ASSERT(0);\n};\n\nstruct test2 :\n\tmpl::eval_if< \n\t\tmpl::equal< \n\t\t\tmpl::at<seq, mpl::int_<0> >::type\n\t\t\t, mpl::int_<10>\n\t\t>\n\t\t, none\n\t\t, wrapAssert<>\n\t>\n{};\n\nstruct test3 :\n\tmpl::eval_if< \n\tmpl::equal< \n\tmpl::at<seq, mpl::int_<1> >::type\n\t, mpl::int_<5>\n\t>\n\t, none\n\t, wrapAssert<>\n\t>\n{};\n\nstruct test4 :\n\tmpl::eval_if< \n\tmpl::equal< \n\tmpl::at<seq, mpl::int_<2> >::type\n\t, mpl::int_<3>\n\t>\n\t, none\n\t, wrapAssert<>\n\t>\n{};\n\nstruct test5 :\n\tmpl::push_back< seq >::type\n{};\n\n\nvoid main()\n{\n// \tint n1 = test::type::n1;\n// \tint n2 = test::type::n2;\n//\ttest::type::value_type a;\n\n}\n", "meta": {"hexsha": "1458a4203e5f6601bd7b025cddc7fde73e353e0f", "size": 2821, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Ex5/Prac5.6/main.cpp", "max_stars_repo_name": "jjuiddong/TemplateMetaProgramming", "max_stars_repo_head_hexsha": "ccfa4b21205c8cd3da1906f64cdbeb200902812a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-31T05:50:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-31T05:50:22.000Z", "max_issues_repo_path": "Ex5/Prac5.6/main.cpp", "max_issues_repo_name": "jjuiddong/TemplateMetaProgramming", "max_issues_repo_head_hexsha": "ccfa4b21205c8cd3da1906f64cdbeb200902812a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ex5/Prac5.6/main.cpp", "max_forks_repo_name": "jjuiddong/TemplateMetaProgramming", "max_forks_repo_head_hexsha": "ccfa4b21205c8cd3da1906f64cdbeb200902812a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-31T05:50:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-31T05:50:41.000Z", "avg_line_length": 19.1904761905, "max_line_length": 66, "alphanum_fraction": 0.6859269762, "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.5, "lm_q1q2_score": 0.28874768259290584}}
{"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\nvoid projectToHalspaceSpereIntersection(float& x, float& y, float& z, float nx, float ny, float nz, float dist, float radius)\n{\n    // check if point inside halfspace\n    float pd = nx*x + ny*y + nz*z;\n    if (pd < dist) {\n        // project to sphere\n        float norm = std::sqrt(x*x + y*y + z*z);\n        float denom = std::max(1.f, norm/radius);\n        x /= denom;\n        y /= denom;\n        z /= denom;\n    } else {\n        // project on halfplane\n        float distDiff = pd-dist;\n        x -= distDiff*nx;\n        y -= distDiff*ny;\n        z -= distDiff*nz;\n\n        // check if inside sphere, if so we are done, otherwise project on circle (assuming radius > dist)\n        float norm = std::sqrt(x*x + y*y + z*z);\n        if (norm > radius) {\n            // precompute for more efficient implemenetation\n            float cicleRadius = std::sqrt(radius*radius - dist*dist);\n\n            // shift to origin\n            x -= dist*nx;\n            y -= dist*ny;\n            z -= dist*nz;\n\n            // rescale such that norm = circleRadius\n            norm = std::sqrt(x*x + y*y + z*z);\n            x *= cicleRadius/norm;\n            y *= cicleRadius/norm;\n            z *= cicleRadius/norm;\n\n            // shift to plane\n            x += dist*nx;\n            y += dist*ny;\n            z += dist*nz;\n        }\n    }\n}\n\nstruct Hist {\n    float counts[8];\n};\n\nstruct NormalInfo {\n    bool isIsotropic;\n    Eigen::Vector3f n1;\n    Eigen::Vector3f n2;\n    Eigen::Vector3f n3;\n};\n\nD3D::Grid<float> runTVHist(D3D::Grid<Hist>& dataCost, D3D::Grid<NormalInfo>& normals, Eigen::Vector3f& minCorner, Eigen::Vector3f& size,\n                           Eigen::Matrix4f boxToGlobal, Eigen::Vector3f color, std::string vrmlOutputFile,\n                           const int numIter, 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> lambda11(dataCost.getWidth(), dataCost.getHeight(), dataCost.getDepth(), 0);\n    D3D::Grid<float> lambda12(dataCost.getWidth(), dataCost.getHeight(), dataCost.getDepth(), 0);\n    D3D::Grid<float> lambda13(dataCost.getWidth(), dataCost.getHeight(), dataCost.getDepth(), 0);\n    D3D::Grid<float> lambda21(dataCost.getWidth(), dataCost.getHeight(), dataCost.getDepth(), 0);\n    D3D::Grid<float> lambda22(dataCost.getWidth(), dataCost.getHeight(), dataCost.getDepth(), 0);\n    D3D::Grid<float> lambda23(dataCost.getWidth(), dataCost.getHeight(), dataCost.getDepth(), 0);\n\n    D3D::Grid<float> lambdaBar11 = lambda11.clone();\n    D3D::Grid<float> lambdaBar12 = lambda12.clone();\n    D3D::Grid<float> lambdaBar13 = lambda13.clone();\n    D3D::Grid<float> lambdaBar21 = lambda21.clone();\n    D3D::Grid<float> lambdaBar22 = lambda22.clone();\n    D3D::Grid<float> lambdaBar23 = lambda23.clone();\n\n    // dual variables\n    D3D::Grid<float> p11(dataCost.getWidth(), dataCost.getHeight(), dataCost.getDepth(), 0);\n    D3D::Grid<float> p12(dataCost.getWidth(), dataCost.getHeight(), dataCost.getDepth(), 0);\n    D3D::Grid<float> p13(dataCost.getWidth(), dataCost.getHeight(), dataCost.getDepth(), 0);\n    D3D::Grid<float> p21(dataCost.getWidth(), dataCost.getHeight(), dataCost.getDepth(), 0);\n    D3D::Grid<float> p22(dataCost.getWidth(), dataCost.getHeight(), dataCost.getDepth(), 0);\n    D3D::Grid<float> p23(dataCost.getWidth(), dataCost.getHeight(), dataCost.getDepth(), 0);\n    D3D::Grid<float> p31(dataCost.getWidth(), dataCost.getHeight(), dataCost.getDepth(), 0);\n    D3D::Grid<float> p32(dataCost.getWidth(), dataCost.getHeight(), dataCost.getDepth(), 0);\n    D3D::Grid<float> p33(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/3.f;\n    const float tau = 0.99f/12.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& p1w = p11(x,y,z);\n                    float& p1h = p12(x,y,z);\n                    float& p1d = p13(x,y,z);\n                    float& p2w = p21(x,y,z);\n                    float& p2h = p22(x,y,z);\n                    float& p2d = p23(x,y,z);\n                    float& p3w = p31(x,y,z);\n                    float& p3h = p32(x,y,z);\n                    float& p3d = p33(x,y,z);\n\n                    p1w += sigma*(u_x + lambdaBar11(x,y,z));\n                    p1h += sigma*(u_y + lambdaBar12(x,y,z));\n                    p1d += sigma*(u_z + lambdaBar13(x,y,z));\n\n                    p2w += sigma*(-lambdaBar11(x,y,z) + lambdaBar21(x,y,z));\n                    p2h += sigma*(-lambdaBar12(x,y,z) + lambdaBar22(x,y,z));\n                    p2d += sigma*(-lambdaBar13(x,y,z) + lambdaBar23(x,y,z));\n\n                    p3w += sigma*(-lambdaBar21(x,y,z));\n                    p3h += sigma*(-lambdaBar22(x,y,z));\n                    p3d += sigma*(-lambdaBar23(x,y,z));\n\n\n                    if (normals(x,y,z).isIsotropic) {\n                        float tv = sqrtf(p1w*p1w + p1h*p1h + p1d*p1d);\n                        float denom = std::max(1.f, tv/2.f);\n                        p1w /= denom;\n                        p1h /= denom;\n                        p1d /= denom;\n\n                        tv = sqrtf(p2w*p2w + p2h*p2h + p2d*p2d);\n                        denom = std::max(1.f, tv/2.f);\n                        p2w /= denom;\n                        p2h /= denom;\n                        p2d /= denom;\n\n                        tv = sqrtf(p3w*p3w + p3h*p3h + p3d*p3d);\n                        denom = std::max(1.f, tv/2.f);\n                        p3w /= denom;\n                        p3h /= denom;\n                        p3d /= denom;\n                    } else {\n                        Eigen::Vector3f n1 = -normals(x,y,z).n1;\n                        Eigen::Vector3f n2 = -normals(x,y,z).n2;\n                        Eigen::Vector3f n3 = -normals(x,y,z).n3;\n                        projectToHalspaceSpereIntersection(p1w, p1h, p1d, n1(0), n1(1), n1(2), 0.5, 2.0);\n                        projectToHalspaceSpereIntersection(p2w, p2h, p2d, n2(0), n2(1), n2(2), 0.5, 2.0);\n                        projectToHalspaceSpereIntersection(p3w, p3h, p3d, n3(0), n3(1), n3(2), 0.5, 2.0);\n                    }\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 ? p11(x,y,z) : 0.0f) - (X0 >= 0 ? p11(X0, y, z) : 0.0f) +\n                                      (Y0 < yDim -1 ? p12(x,y,z) : 0.0f) - (Y0 >= 0 ? p12(x, Y0, z) : 0.0f) +\n                                      (Z0 < zDim -1 ? p13(x,y,z) : 0.0f) - (Z0 >= 0 ? p13(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                    float const L11 = lambda11(x,y,z) - tau*(p11(x,y,z) - p21(x,y,z));\n                    float const L12 = lambda12(x,y,z) - tau*(p12(x,y,z) - p22(x,y,z));\n                    float const L13 = lambda13(x,y,z) - tau*(p13(x,y,z) - p23(x,y,z));\n\n                    lambdaBar11(x,y,z) = L11 + theta*(L11 - lambda11(x,y,z));\n                    lambdaBar12(x,y,z) = L12 + theta*(L12 - lambda12(x,y,z));\n                    lambdaBar13(x,y,z) = L13 + theta*(L13 - lambda13(x,y,z));\n\n                    lambda11(x,y,z) = L11;\n                    lambda12(x,y,z) = L12;\n                    lambda13(x,y,z) = L13;\n\n                    float const L21 = lambda21(x,y,z) - tau*(p21(x,y,z) - p31(x,y,z));\n                    float const L22 = lambda22(x,y,z) - tau*(p22(x,y,z) - p32(x,y,z));\n                    float const L23 = lambda23(x,y,z) - tau*(p23(x,y,z) - p33(x,y,z));\n\n                    lambdaBar21(x,y,z) = L21 + theta*(L21 - lambda21(x,y,z));\n                    lambdaBar22(x,y,z) = L22 + theta*(L22 - lambda22(x,y,z));\n                    lambdaBar23(x,y,z) = L23 + theta*(L23 - lambda23(x,y,z));\n\n                    lambda21(x,y,z) = L21;\n                    lambda22(x,y,z) = L22;\n                    lambda23(x,y,z) = L23;\n                }\n            }\n        }\n\n        if ((c+1) % 50 == 0) {\n            D3D::saveVolumeAsVRMLMesh(u, 0.0f, minCorner, size, boxToGlobal, color, vrmlOutputFile, true);\n            u.saveAsDataFile(\"tvHistNormalFusionU.dat\");\n            std::cout << std::endl;\n\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 clusteredNormalsFile;\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            (\"clusteredNormalsFile\", boost::program_options::value<std::string>(&clusteredNormalsFile)->default_value(\"clusteredNormals.dat\"), \"Clustered normals 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(\"tvHistNormalModel.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    // load clustered normals\n    D3D::Grid<NormalInfo> clusteredNormals;\n    clusteredNormals.loadFromDataFile(clusteredNormalsFile);\n\n    std::cout << \"Clustered Normals Loaded: width = \" << clusteredNormals.getWidth() << \", height = \" << clusteredNormals.getHeight() << \", depth = \" << clusteredNormals.getDepth() << std::endl;\n\n    if (bpResX != (int) clusteredNormals.getWidth() || bpResY != (int) clusteredNormals.getHeight() || bpResZ != (int) clusteredNormals.getDepth())\n    {\n        D3D_THROW_EXCEPTION(\"Resolution specified in the config file does not match the dimension of the grid with the clustered normals.\")\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, clusteredNormals, minCorner, size, boxToGlobal, color, vrmlOutputFile, ffNumIter, hfLambda, 1);\n}\n", "meta": {"hexsha": "4df49c4e93526218a41961798a842a33d783f3a0", "size": 21212, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vision-normal-fusion/src/tvHistNormalFusion.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/tvHistNormalFusion.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/tvHistNormalFusion.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": 37.5433628319, "max_line_length": 194, "alphanum_fraction": 0.5205544032, "num_tokens": 5879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2887417489020611}}
{"text": "#ifndef HOPS_DATA_HPP\n#define HOPS_DATA_HPP\n\n#include <hops/FileWriter/FileWriter.hpp>\n#include <hops/FileWriter/FileWriterFactory.hpp>\n#include <hops/FileWriter/FileWriterType.hpp>\n#include <hops/MarkovChain/MarkovChain.hpp>\n#include <hops/Statistics/ExpectedSquaredJumpDistance.hpp>\n#include <hops/Statistics/EffectiveSampleSize.hpp>\n#include <hops/Statistics/PotentialScaleReductionFactor.hpp>\n#include <hops/Utility/ChainData.hpp>\n\n#include <Eigen/Core>\n\n#include <vector>\n#include <memory>\n\nnamespace hops {\n    class Data {\n    public:\n        Data(long dimension = 0) : dimension(dimension) {\n            //\n        }\n\n        Data(const std::vector<std::shared_ptr<MarkovChain>>& markovChains, long dimension = 0) : dimension(dimension) {\n            linkWithChains(markovChains);\n        }\n\n        void setDimension(long dimension) {\n            this->dimension = dimension;\n        }\n\n        void linkWithChains(const std::vector<std::shared_ptr<MarkovChain>>& markovChains) {\n            chains.resize(markovChains.size());\n            for (size_t i = 0; i < markovChains.size(); ++i) {\n                markovChains[i]->installDataObject(chains[i]); \n            }\n        }\n\n\n        std::vector<const std::vector<double>*> getAcceptanceRates() {\n            std::vector<const std::vector<double>*> acceptanceRates(chains.size());\n            for (size_t i = 0; i < acceptanceRates.size(); ++i) {\n                acceptanceRates[i] = chains[i].acceptanceRates.get();\n            }\n            return acceptanceRates;\n        }\n\n        std::vector<const std::vector<double>*> getNegativeLogLikelihood() {\n            std::vector<const std::vector<double>*> negativeLogLikelihood(chains.size());\n            for (size_t i = 0; i < negativeLogLikelihood.size(); ++i) {\n                negativeLogLikelihood[i] = chains[i].negativeLogLikelihood.get();\n            }\n            return negativeLogLikelihood;\n        }\n\n        std::vector<const std::vector<Eigen::VectorXd>*> getStates() {\n            std::vector<const std::vector<Eigen::VectorXd>*> states(chains.size());\n            for (size_t i = 0; i < states.size(); ++i) {\n                states[i] = chains[i].states.get();\n            }\n            return states;\n        }\n\n        std::vector<const std::vector<long>*> getTimestamps() {\n            std::vector<const std::vector<long>*> timestamps(chains.size());\n            for (size_t i = 0; i < timestamps.size(); ++i) {\n                timestamps[i] = chains[i].timestamps.get();\n            }\n            return timestamps;\n        }\n\n\n        void computeTotalNumberOfSamples() {\n            totalNumberOfSamples = 0;\n            for (size_t i = 0; i < chains.size(); ++i) {\n                totalNumberOfSamples += chains[i].getStates().size();\n            }\n        }\n\n        void computeAcceptanceRate() {\n            acceptanceRate = Eigen::VectorXd(chains.size());\n            for (size_t i = 0; i < chains.size(); ++i) {\n                acceptanceRate(i) = chains[i].getAcceptanceRates().back();\n            }\n        }\n\n        void computeEffectiveSampleSize() {\n            std::vector<const std::vector<Eigen::VectorXd>*> states(chains.size());\n\t\t\tif (!chains.size()) {\n\t\t\t\tthrow EmptyChainDataException();\n\t\t\t}\n\n            for (size_t i = 0; i < states.size(); ++i) {\n                states[i] = chains[i].states.get();\n\t\t\t\tif (!states[i]) {\n\t\t\t\t\tthrow EmptyChainDataException();\n\t\t\t\t}\n            }\n            std::vector<double> effectiveSampleSize = ::hops::computeEffectiveSampleSize(states);\n            this->effectiveSampleSize = Eigen::Map<Eigen::VectorXd>(effectiveSampleSize.data(), dimension);\n        }\n\n        void computeExpectedSquaredJumpDistance() {\n            std::vector<const std::vector<Eigen::VectorXd>*> states(chains.size());\n\t\t\tif (!chains.size()) {\n\t\t\t\tthrow EmptyChainDataException();\n\t\t\t}\n\n            for (size_t i = 0; i < states.size(); ++i) {\n                states[i] = chains[i].states.get();\n\t\t\t\tif (!states[i]) {\n\t\t\t\t\tthrow EmptyChainDataException();\n\t\t\t\t}\n            }\n            std::vector<double> expectedSquaredJumpDistance = ::hops::computeExpectedSquaredJumpDistance<Eigen::VectorXd, Eigen::MatrixXd>(states);\n            this->expectedSquaredJumpDistance = Eigen::Map<Eigen::VectorXd>(expectedSquaredJumpDistance.data(), chains.size());\n        }\n\n        void computePotentialScaleReductionFactor() {\n            std::vector<const std::vector<Eigen::VectorXd>*> states(chains.size());\n\t\t\tif (!chains.size()) {\n\t\t\t\tthrow EmptyChainDataException();\n\t\t\t}\n\n            for (size_t i = 0; i < states.size(); ++i) {\n                states[i] = chains[i].states.get();\n\t\t\t\tif (!states[i]) {\n\t\t\t\t\tthrow EmptyChainDataException();\n\t\t\t\t}\n            }\n            std::vector<double> potentialScaleReductionFactor = ::hops::computePotentialScaleReductionFactor(states);\n            this->potentialScaleReductionFactor = Eigen::Map<Eigen::VectorXd>(potentialScaleReductionFactor.data(), dimension);\n        }\n\n        void computeTotalTimeTaken() {\n            totalTimeTaken = Eigen::VectorXd(chains.size());\n            for (size_t i = 0; i < chains.size(); ++i) {\n                totalTimeTaken(i) = chains[i].getTimestamps().back() - chains[i].getTimestamps().front();\n            }\n        }\n\n        void reset() {\n            for (size_t i = 0; i < chains.size(); ++i) {\n                chains[i].reset();\n            }\n        }\n\n        void write(const std::string& outputDirectory, bool discardRawData = false) const {\n            if (!discardRawData) {\n                for (size_t i = 0; i < chains.size(); ++i) {\n                    auto fileWriter = FileWriterFactory::createFileWriter(outputDirectory + \"/chain\" + std::to_string(i), FileWriterType::CSV);\n                    chains[i].write(fileWriter.get());\n                }\n            }\n\n\t\t\tauto statisticsWriter = FileWriterFactory::createFileWriter(outputDirectory + \"/statistics\", FileWriterType::CSV);\n\n            if (acceptanceRate.size() > 0) {\n                statisticsWriter->write(\"acceptanceRate\", Eigen::MatrixXd(acceptanceRate.transpose()));\n            }\n\n            if (expectedSquaredJumpDistance.size() > 0) {\n                statisticsWriter->write(\"expectedSquaredJumpDistance\", Eigen::MatrixXd(expectedSquaredJumpDistance.transpose()));\n            }\n\n            if (effectiveSampleSize.size() > 0) {\n                statisticsWriter->write(\"effectiveSampleSize\", Eigen::MatrixXd(effectiveSampleSize.transpose()));\n            }\n\n            if (potentialScaleReductionFactor.size() > 0) {\n                statisticsWriter->write(\"potentialScaleReductionFactor\", Eigen::MatrixXd(potentialScaleReductionFactor.transpose()));\n            }\n\n            if (totalNumberOfSamples > 0) {\n                statisticsWriter->write(\"totalNumberOfSamples\", Eigen::MatrixXd(totalNumberOfSamples * Eigen::MatrixXd::Identity(1,1)));\n            }\n\n            if (totalTimeTaken.size() > 0) {\n                statisticsWriter->write(\"totalTimeTaken\", Eigen::MatrixXd(totalTimeTaken.transpose()));\n            }\n\n            if (totalNumberOfTuningSamples > 0) {\n                auto tuningWriter = FileWriterFactory::createFileWriter(outputDirectory + \"/tuning\", FileWriterType::CSV);\n                tuningWriter->write(\"totalNumberOfTuningSamples\", std::vector<long>{static_cast<long>(totalNumberOfTuningSamples)});\n                tuningWriter->write(\"stepSize\", std::vector<double>{tunedStepSize});\n                tuningWriter->write(\"objectiveValue\", std::vector<double>{tunedObjectiveValue});\n                tuningWriter->write(\"totalTimeTaken\", std::vector<double>{totalTuningTimeTaken});\n\n                if (tuningData.size() > 0) {\n                    tuningWriter->write(\"data\", tuningData);\n                }\n\n                if (tuningPosterior.size() > 0) {\n                    tuningWriter->write(\"posterior\", tuningPosterior);\n                }\n            }\n        }\n\n        void setTuningMethod(const std::string& tuningMethod) {\n            this->tuningMethod = tuningMethod;\n        }\n\n        void setTotalNumberOfTuningSamples(unsigned long totalNumberOfTuningSamples) {\n            this->totalNumberOfTuningSamples = totalNumberOfTuningSamples;\n        }\n\n        void setTunedStepSize(double tunedStepSize) {\n            this->tunedStepSize = tunedStepSize;\n        }\n\n        void setTunedObjectiveValue(double tunedObjectiveValue) {\n            this->tunedObjectiveValue = tunedObjectiveValue;\n        }\n\n        void setTotalTuningTimeTaken(double totalTuningTimeTaken) {\n            this->totalTuningTimeTaken = totalTuningTimeTaken;\n        }\n\n        void setTuningData(const Eigen::MatrixXd& tuningData) {\n            this->tuningData = tuningData;\n        }\n\n        void setTuningPosterior(const Eigen::MatrixXd& tuningPosterior) {\n            this->tuningPosterior = tuningPosterior;\n        }\n\n    private:\n        std::vector<ChainData> chains;\n\n        double totalNumberOfSamples;\n        Eigen::VectorXd acceptanceRate;\n        Eigen::VectorXd expectedSquaredJumpDistance;\n        Eigen::VectorXd effectiveSampleSize;\n        Eigen::VectorXd potentialScaleReductionFactor;\n        Eigen::VectorXd totalTimeTaken;\n\n        // tuning data\n        std::string tuningMethod;\n        unsigned long totalNumberOfTuningSamples = 0;\n        double tunedStepSize;\n        double tunedObjectiveValue;\n        double totalTuningTimeTaken;\n\n        Eigen::MatrixXd tuningData;\n        Eigen::MatrixXd tuningPosterior;\n\n        std::vector<std::vector<double>> sampleVariances;\n        std::vector<std::vector<double>> intraChainExpectations;\n        std::vector<double> interChainExpectation;\n        unsigned long numSeen = 0;\n\n        long dimension = 0;\n        friend Eigen::VectorXd computeAcceptanceRate(Data& data);\n        friend Eigen::VectorXd computeExpectedSquaredJumpDistance(Data& data);\n        friend Eigen::VectorXd computeEffectiveSampleSize(Data& data);\n        friend Eigen::VectorXd computePotentialScaleReductionFactor(Data& data);\n        friend double computeTotalNumberOfSamples(Data& data);\n        friend Eigen::VectorXd computeTotalTimeTaken(Data& data);\n    };\n\n    inline Eigen::VectorXd computeAcceptanceRate(Data& data) {\n        data.computeAcceptanceRate();\n        return data.acceptanceRate;\n    }\n\n    inline Eigen::VectorXd computeExpectedSquaredJumpDistance(Data& data) {\n        data.computeExpectedSquaredJumpDistance();\n        return data.expectedSquaredJumpDistance;\n    }\n\n    inline Eigen::VectorXd computeEffectiveSampleSize(Data& data) {\n        data.computeEffectiveSampleSize();\n        return data.effectiveSampleSize;\n    }\n\n    inline Eigen::VectorXd computePotentialScaleReductionFactor(Data& data) {\n        data.computePotentialScaleReductionFactor();\n        return data.potentialScaleReductionFactor;\n    }\n\n    inline double computeTotalNumberOfSamples(Data& data) {\n        data.computeTotalNumberOfSamples();\n        return data.totalNumberOfSamples;\n    }\n\n    inline Eigen::VectorXd computeTotalTimeTaken(Data& data) {\n        data.computeTotalTimeTaken();\n        return data.totalTimeTaken;\n    }\n}\n\n#endif // HOPS_DATA_HPP\n\n", "meta": {"hexsha": "b43e510fc989046eea14ccee819ebf3a52cee188", "size": 11182, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hops/Utility/Data.hpp", "max_stars_repo_name": "modsim/hops", "max_stars_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-11-26T05:13:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T02:08:40.000Z", "max_issues_repo_path": "include/hops/Utility/Data.hpp", "max_issues_repo_name": "modsim/hops", "max_issues_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-20T23:16:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-20T23:16:34.000Z", "max_forks_repo_path": "include/hops/Utility/Data.hpp", "max_forks_repo_name": "modsim/hops", "max_forks_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9050847458, "max_line_length": 147, "alphanum_fraction": 0.6144696834, "num_tokens": 2410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2886537580679386}}
{"text": "#include <iostream>\n#include <tr1/memory>\n\n#include <boost/program_options.hpp>\n#include <boost/program_options/variables_map.hpp>\n\n#include \"filelib.h\"\n#include \"dict.h\"\n#include \"sampler.h\"\n#include \"ccrp.h\"\n\nusing namespace std;\nusing namespace std::tr1;\nnamespace po = boost::program_options;\n\nDict d; // global dictionary\n\nstring Join(char joiner, const vector<int>& phrase) {\n  ostringstream os;\n  for (int i = 0; i < phrase.size(); ++i) {\n    if (i > 0) os << joiner;\n    os << d.Convert(phrase[i]);\n  }\n  return os.str();\n}\n\nostream& operator<<(ostream& os, const vector<int>& phrase) {\n  for (int i = 0; i < phrase.size(); ++i)\n    os << (i == 0 ? \"\" : \" \") << d.Convert(phrase[i]);\n  return os;\n}\n\nstruct UnigramLM {\n  explicit UnigramLM(const string& fname) {\n    ifstream in(fname.c_str());\n    assert(in);\n  }\n\n  double logprob(int word) const {\n    assert(word < freqs_.size());\n    return freqs_[word];\n  }\n\n  vector<double> freqs_;\n};\n\nvoid InitCommandLine(int argc, char** argv, po::variables_map* conf) {\n  po::options_description opts(\"Configuration options\");\n  opts.add_options()\n        (\"samples,s\",po::value<unsigned>()->default_value(1000),\"Number of samples\")\n        (\"input,i\",po::value<string>(),\"Read file from\")\n        (\"random_seed,S\",po::value<uint32_t>(), \"Random seed\")\n        (\"write_cdec_grammar,g\", po::value<string>(), \"Write cdec grammar to this file\")\n        (\"write_cdec_weights,w\", po::value<string>(), \"Write cdec weights to this file\")\n        (\"poisson_length,p\", \"Use a Poisson distribution as the length of a phrase in the base distribuion\")\n        (\"no_hyperparameter_inference,N\", \"Disable hyperparameter inference\");\n  po::options_description clo(\"Command line options\");\n  clo.add_options()\n        (\"config\", po::value<string>(), \"Configuration file\")\n        (\"help,h\", \"Print this help message and exit\");\n  po::options_description dconfig_options, dcmdline_options;\n  dconfig_options.add(opts);\n  dcmdline_options.add(opts).add(clo);\n  \n  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);\n  if (conf->count(\"config\")) {\n    ifstream config((*conf)[\"config\"].as<string>().c_str());\n    po::store(po::parse_config_file(config, dconfig_options), *conf);\n  }\n  po::notify(*conf);\n\n  if (conf->count(\"help\") || (conf->count(\"input\") == 0)) {\n    cerr << dcmdline_options << endl;\n    exit(1);\n  }\n}\n\nvoid ReadCorpus(const string& filename, vector<vector<int> >* c, set<int>* vocab) {\n  c->clear();\n  istream* in;\n  if (filename == \"-\")\n    in = &cin;\n  else\n    in = new ifstream(filename.c_str());\n  assert(*in);\n  string line;\n  while(*in) {\n    getline(*in, line);\n    if (line.empty() && !*in) break;\n    c->push_back(vector<int>());\n    vector<int>& v = c->back();\n    d.ConvertWhitespaceDelimitedLine(line, &v);\n    for (int i = 0; i < v.size(); ++i) vocab->insert(v[i]);\n  }\n  if (in != &cin) delete in;\n}\n\ndouble log_poisson(unsigned x, const double& lambda) {\n  assert(lambda > 0.0);\n  return log(lambda) * x - lgamma(x + 1) - lambda;\n}\n\nstruct UniphraseLM {\n  UniphraseLM(const vector<vector<int> >& corpus,\n              const set<int>& vocab,\n              const po::variables_map& conf) :\n    phrases_(1,1,1,1),\n    gen_(1,1,1,1),\n    corpus_(corpus),\n    uniform_word_(1.0 / vocab.size()),\n    gen_p0_(0.5),\n    p_end_(0.5),\n    use_poisson_(conf.count(\"poisson_length\") > 0) {}\n\n  double p0(const vector<int>& phrase) const {\n    static vector<double> p0s(10000, 0.0);\n    assert(phrase.size() < 10000);\n    double& p = p0s[phrase.size()];\n    if (p) return p;\n    p = exp(log_p0(phrase));\n    if (!p) {\n      cerr << \"0 prob phrase: \" << phrase << \"\\nAssigning std::numeric_limits<double>::min()\\n\";\n      p = std::numeric_limits<double>::min();\n    }\n    return p;\n  }\n\n  double log_p0(const vector<int>& phrase) const {\n    double len_logprob;\n    if (use_poisson_)\n      len_logprob = log_poisson(phrase.size(), 1.0);\n    else\n      len_logprob = log(1 - p_end_) * (phrase.size() -1) + log(p_end_);\n    return log(uniform_word_) * phrase.size() + len_logprob;\n  }\n\n  double llh() const {\n    double llh = gen_.log_crp_prob();\n    llh += gen_.num_tables(false) * log(gen_p0_) +\n           gen_.num_tables(true) * log(1 - gen_p0_);\n    double llhr = phrases_.log_crp_prob();\n    for (CCRP<vector<int> >::const_iterator it = phrases_.begin(); it != phrases_.end(); ++it) {\n      llhr += phrases_.num_tables(it->first) * log_p0(it->first);\n      //llhr += log_p0(it->first);\n      if (!isfinite(llh)) {\n        cerr << it->first << endl;\n        cerr << log_p0(it->first) << endl;\n        abort();\n      }\n    }\n    return llh + llhr;\n  }\n\n  void Sample(unsigned int samples, bool hyp_inf, MT19937* rng) {\n    cerr << \"Initializing...\\n\";\n    z_.resize(corpus_.size());\n    int tc = 0;\n    for (int i = 0; i < corpus_.size(); ++i) {\n      const vector<int>& line = corpus_[i];\n      const int ls = line.size();\n      const int last_pos = ls - 1;\n      vector<bool>& z = z_[i];\n      z.resize(ls);\n      int prev = 0;\n      for (int j = 0; j < ls; ++j) {\n        z[j] = rng->next() < 0.5;\n        if (j == last_pos) z[j] = true;  // break phrase at the end of the sentence\n        if (z[j]) {\n          const vector<int> p(line.begin() + prev, line.begin() + j + 1);\n          phrases_.increment(p, p0(p), rng);\n          //cerr << p << \": \" << p0(p) << endl;\n          prev = j + 1;\n          gen_.increment(false, gen_p0_, rng);\n          ++tc; // remove\n        }\n      }\n      ++tc;\n      gen_.increment(true, 1.0 - gen_p0_, rng); // end of utterance\n    }\n    cerr << \"TC: \" << tc << endl;\n    cerr << \"Initial LLH: \" << llh() << endl;\n    cerr << \"Sampling...\\n\";\n    cerr << gen_ << endl;\n    for (int s = 1; s < samples; ++s) {\n      cerr << '.';\n      if (s % 10 == 0) {\n        cerr << \" [\" << s;\n        if (hyp_inf) ResampleHyperparameters(rng);\n        cerr << \" LLH=\" << llh() << \"]\\n\";\n        vector<int> z(z_[0].size(), 0);\n        //for (int j = 0; j < z.size(); ++j) z[j] = z_[0][j];\n        //SegCorpus::Write(corpus_[0], z, d);\n      }\n      for (int i = 0; i < corpus_.size(); ++i) {\n        const vector<int>& line = corpus_[i];\n        const int ls = line.size();\n        const int last_pos = ls - 1;\n        vector<bool>& z = z_[i];\n        int prev = 0;\n        for (int j = 0; j < last_pos; ++j) { // don't resample last position\n          int next = j+1;  while(!z[next]) { ++next; }\n          const vector<int> p1p2(line.begin() + prev, line.begin() + next + 1);\n          const vector<int> p1(line.begin() + prev, line.begin() + j + 1);\n          const vector<int> p2(line.begin() + j + 1, line.begin() + next + 1);\n\n          if (z[j]) {\n            phrases_.decrement(p1, rng);\n            phrases_.decrement(p2, rng);\n            gen_.decrement(false, rng);\n            gen_.decrement(false, rng);\n          } else {\n            phrases_.decrement(p1p2, rng);\n            gen_.decrement(false, rng);\n          }\n\n          const double d1 = phrases_.prob(p1p2, p0(p1p2)) * gen_.prob(false, gen_p0_);\n          double d2 = phrases_.prob(p1, p0(p1)) * gen_.prob(false, gen_p0_);\n          phrases_.increment(p1, p0(p1), rng);\n          gen_.increment(false, gen_p0_, rng);\n          d2 *= phrases_.prob(p2, p0(p2)) * gen_.prob(false, gen_p0_);\n          phrases_.decrement(p1, rng);\n          gen_.decrement(false, rng);\n          z[j] = rng->SelectSample(d1, d2);\n\n          if (z[j]) {\n            phrases_.increment(p1, p0(p1), rng);\n            phrases_.increment(p2, p0(p2), rng);\n            gen_.increment(false, gen_p0_, rng);\n            gen_.increment(false, gen_p0_, rng);\n            prev = j + 1;\n          } else {\n            phrases_.increment(p1p2, p0(p1p2), rng);\n            gen_.increment(false, gen_p0_, rng);\n          }\n        }\n      }\n    }\n//    cerr << endl << endl << gen_ << endl << phrases_ << endl;\n    cerr << gen_.prob(false, gen_p0_) << \" \" << gen_.prob(true, 1 - gen_p0_) << endl;\n  }\n\n  void WriteCdecGrammarForCurrentSample(ostream* os) const {\n    CCRP<vector<int> >::const_iterator it = phrases_.begin();\n    for (; it != phrases_.end(); ++it) {\n      (*os) << \"[X] ||| \" << Join(' ', it->first) << \" ||| \"\n                          << Join('_', it->first) << \" ||| C=1 P=\" \n                          << log(phrases_.prob(it->first, p0(it->first))) << endl;\n    }\n  }\n\n  double OOVUnigramLogProb() const {\n    vector<int> x(1,99999999);\n    return log(phrases_.prob(x, p0(x)));\n  }\n\n  void ResampleHyperparameters(MT19937* rng) {\n    phrases_.resample_hyperparameters(rng);\n    gen_.resample_hyperparameters(rng);\n    cerr << \" d=\" << phrases_.discount() << \",c=\" << phrases_.concentration();\n  }\n\n  CCRP<vector<int> > phrases_;\n  CCRP<bool> gen_;\n  vector<vector<bool> > z_;   // z_[i] is there a phrase boundary after the ith word\n  const vector<vector<int> >& corpus_;\n  const double uniform_word_;\n  const double gen_p0_;\n  const double p_end_; // in base length distribution, p of the end of a phrase\n  const bool use_poisson_;\n};\n\n\nint main(int argc, char** argv) {\n  po::variables_map conf;\n  InitCommandLine(argc, argv, &conf);\n  shared_ptr<MT19937> prng;\n  if (conf.count(\"random_seed\"))\n    prng.reset(new MT19937(conf[\"random_seed\"].as<uint32_t>()));\n  else\n    prng.reset(new MT19937);\n  MT19937& rng = *prng;\n\n  vector<vector<int> > corpus;\n  set<int> vocab;\n  ReadCorpus(conf[\"input\"].as<string>(), &corpus, &vocab);\n  cerr << \"Corpus size: \" << corpus.size() << \" sentences\\n\";\n  cerr << \"Vocabulary size: \" << vocab.size() << \" types\\n\";\n\n  UniphraseLM ulm(corpus, vocab, conf);\n  ulm.Sample(conf[\"samples\"].as<unsigned>(), conf.count(\"no_hyperparameter_inference\") == 0, &rng);\n  cerr << \"OOV unigram prob: \" << ulm.OOVUnigramLogProb() << endl;\n\n  for (int i = 0; i < corpus.size(); ++i)\n//    SegCorpus::Write(corpus[i], shmmlm.z_[i], d);\n ;\n  if (conf.count(\"write_cdec_grammar\")) {\n    string fname = conf[\"write_cdec_grammar\"].as<string>();\n    cerr << \"Writing model to \" << fname << \" ...\\n\";\n    WriteFile wf(fname);\n    ulm.WriteCdecGrammarForCurrentSample(wf.stream());\n  }\n\n  if (conf.count(\"write_cdec_weights\")) {\n    string fname = conf[\"write_cdec_weights\"].as<string>();\n    cerr << \"Writing weights to \" << fname << \" .\\n\";\n    WriteFile wf(fname);\n    ostream& os = *wf.stream();\n    os << \"# make C smaller to use more phrases\\nP 1\\nPassThrough \" << ulm.OOVUnigramLogProb() << \"\\nC -3\\n\";\n  }\n\n  \n\n  return 0;\n}\n\n", "meta": {"hexsha": "29b3d7ea1398d55d66a1be8355b9e0295033382a", "size": 10406, "ext": "cc", "lang": "C++", "max_stars_repo_path": "phrasinator/gibbs_train_plm.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": "phrasinator/gibbs_train_plm.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": "phrasinator/gibbs_train_plm.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": 32.9303797468, "max_line_length": 109, "alphanum_fraction": 0.5737074765, "num_tokens": 3061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2886537580679386}}
{"text": "//=======================================================================\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\n// Copyright 2009 Trustees of Indiana University.\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek, Michael Hansen\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n\n#ifndef BOOST_GRAPH_DIJKSTRA_NO_COLOR_MAP_HPP\n#define BOOST_GRAPH_DIJKSTRA_NO_COLOR_MAP_HPP\n\n#include <boost/pending/indirect_cmp.hpp>\n#include <boost/graph/relax.hpp>\n#include <boost/pending/relaxed_heap.hpp>\n#include <boost/graph/detail/d_ary_heap.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/iteration_macros.hpp>\n\nnamespace boost {\n\n  // No init version\n  template <typename Graph, typename DijkstraVisitor,\n            typename PredecessorMap, typename DistanceMap,\n            typename WeightMap, typename VertexIndexMap,\n            typename DistanceCompare, typename DistanceWeightCombine,\n            typename DistanceInfinity, typename DistanceZero>\n  void dijkstra_shortest_paths_no_color_map_no_init\n    (const Graph& graph,\n     typename graph_traits<Graph>::vertex_descriptor start_vertex,\n     PredecessorMap predecessor_map,\n     DistanceMap distance_map,\n     WeightMap weight_map,\n     VertexIndexMap index_map,\n     DistanceCompare distance_compare,\n     DistanceWeightCombine distance_weight_combine,\n     DistanceInfinity distance_infinity,\n     DistanceZero distance_zero,\n     DijkstraVisitor visitor)\n  {\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n    typedef typename property_traits<DistanceMap>::value_type Distance;\n    typedef typename property_traits<WeightMap>::value_type Weight;\n    \n    typedef indirect_cmp<DistanceMap, DistanceCompare> DistanceIndirectCompare;\n    DistanceIndirectCompare\n      distance_indirect_compare(distance_map, distance_compare);\n  \n    // Choose vertex queue type\n#if BOOST_GRAPH_DIJKSTRA_USE_RELAXED_HEAP\n    typedef relaxed_heap<Vertex, DistanceIndirectCompare, VertexIndexMap>\n      VertexQueue;\n    VertexQueue vertex_queue(num_vertices(graph),\n                             distance_indirect_compare,\n                             index_map);\n#else\n    // Default - use d-ary heap (d = 4)\n    typedef\n      detail::vertex_property_map_generator<Graph, VertexIndexMap, std::size_t>\n      IndexInHeapMapHelper;\n    typedef typename IndexInHeapMapHelper::type IndexInHeapMap;\n    typedef\n      d_ary_heap_indirect<Vertex, 4, IndexInHeapMap, DistanceMap, DistanceCompare>\n      VertexQueue;\n  \n    boost::scoped_array<std::size_t> index_in_heap_map_holder;\n    IndexInHeapMap index_in_heap =\n      IndexInHeapMapHelper::build(graph, index_map,\n                                  index_in_heap_map_holder);  \n    VertexQueue vertex_queue(distance_map, index_in_heap, distance_compare);\n#endif\n  \n    // Add vertex to the queue\n    vertex_queue.push(start_vertex);\n  \n    // Starting vertex will always be the first discovered vertex\n    visitor.discover_vertex(start_vertex, graph);\n  \n    while (!vertex_queue.empty()) {\n      Vertex min_vertex = vertex_queue.top();\n      vertex_queue.pop();\n      \n      visitor.examine_vertex(min_vertex, graph);\n  \n      // Check if any other vertices can be reached\n      Distance min_vertex_distance = get(distance_map, min_vertex);\n      \n      if (!distance_compare(min_vertex_distance, distance_infinity)) {\n        // This is the minimum vertex, so all other vertices are unreachable\n        return;\n      }\n  \n      // Examine neighbors of min_vertex\n      typedef typename graph_traits<Graph>::edge_descriptor Edge;\n      BGL_FORALL_OUTEDGES_T(min_vertex, current_edge, graph, Graph) {\n        visitor.examine_edge(current_edge, graph);\n        \n        // Check if the edge has a negative weight\n        if (distance_compare(get(weight_map, current_edge), distance_zero)) {\n          boost::throw_exception(negative_edge());\n        }\n  \n        // Extract the neighboring vertex and get its distance\n        Vertex neighbor_vertex = target(current_edge, graph);\n        Distance neighbor_vertex_distance = get(distance_map, neighbor_vertex);\n        bool is_neighbor_undiscovered = \n          !distance_compare(neighbor_vertex_distance, distance_infinity);\n\n        // Attempt to relax the edge\n        bool was_edge_relaxed = relax(current_edge, graph, weight_map,\n          predecessor_map, distance_map,\n          distance_weight_combine, distance_compare);\n  \n        if (was_edge_relaxed) {\n          vertex_queue.update(neighbor_vertex);\n          visitor.edge_relaxed(current_edge, graph);\n        } else {\n          visitor.edge_not_relaxed(current_edge, graph);\n        }\n  \n        if (is_neighbor_undiscovered) {\n          visitor.discover_vertex(neighbor_vertex, graph);\n          vertex_queue.push(neighbor_vertex);\n        }\n      } // end out edge iteration\n  \n      visitor.finish_vertex(min_vertex, graph);\n    } // end while queue not empty\n  }\n\n  // Full init version\n  template <typename Graph, typename DijkstraVisitor,\n            typename PredecessorMap, typename DistanceMap,\n            typename WeightMap, typename VertexIndexMap,\n            typename DistanceCompare, typename DistanceWeightCombine,\n            typename DistanceInfinity, typename DistanceZero>\n  void dijkstra_shortest_paths_no_color_map\n    (const Graph& graph,\n     typename graph_traits<Graph>::vertex_descriptor start_vertex,\n     PredecessorMap predecessor_map,\n     DistanceMap distance_map,\n     WeightMap weight_map,\n     VertexIndexMap index_map,\n     DistanceCompare distance_compare,\n     DistanceWeightCombine distance_weight_combine,\n     DistanceInfinity distance_infinity,\n     DistanceZero distance_zero,\n     DijkstraVisitor visitor)\n  {\n    // Initialize vertices\n    BGL_FORALL_VERTICES_T(current_vertex, graph, Graph) {\n      visitor.initialize_vertex(current_vertex, graph);\n      \n      // Default all distances to infinity\n      put(distance_map, current_vertex, distance_infinity);\n  \n      // Default all vertex predecessors to the vertex itself\n      put(predecessor_map, current_vertex, current_vertex);\n    }\n  \n    // Set distance for start_vertex to zero\n    put(distance_map, start_vertex, distance_zero);\n  \n    // Pass everything on to the no_init version\n    dijkstra_shortest_paths_no_color_map_no_init(graph,\n      start_vertex, predecessor_map, distance_map, weight_map,\n      index_map, distance_compare, distance_weight_combine,\n      distance_infinity, distance_zero, visitor);\n  }\n\n  namespace detail {\n\n    // Handle defaults for PredecessorMap, DistanceCompare,\n    // DistanceWeightCombine, DistanceInfinity and DistanceZero\n    template <typename Graph, typename DistanceMap, typename WeightMap,\n              typename VertexIndexMap, typename Params>\n    inline void\n    dijkstra_no_color_map_dispatch2\n      (const Graph& graph,\n       typename graph_traits<Graph>::vertex_descriptor start_vertex,\n       DistanceMap distance_map, WeightMap weight_map,\n       VertexIndexMap index_map, const Params& params)\n    {\n      // Default for predecessor map\n      dummy_property_map predecessor_map;\n\n      typedef typename property_traits<DistanceMap>::value_type DistanceType;\n      dijkstra_shortest_paths_no_color_map\n        (graph, start_vertex,\n         choose_param(get_param(params, vertex_predecessor), predecessor_map),\n         distance_map, weight_map, index_map,\n         choose_param(get_param(params, distance_compare_t()),\n                      std::less<DistanceType>()),\n         choose_param(get_param(params, distance_combine_t()),\n                      closed_plus<DistanceType>()),\n         choose_param(get_param(params, distance_inf_t()),\n                      (std::numeric_limits<DistanceType>::max)()),\n         choose_param(get_param(params, distance_zero_t()),\n                      DistanceType()),\n         choose_param(get_param(params, graph_visitor),\n                      make_dijkstra_visitor(null_visitor())));\n    }\n\n    template <typename Graph, typename DistanceMap, typename WeightMap,\n              typename IndexMap, typename Params>\n    inline void\n    dijkstra_no_color_map_dispatch1\n      (const Graph& graph,\n       typename graph_traits<Graph>::vertex_descriptor start_vertex,\n       DistanceMap distance_map, WeightMap weight_map,\n       IndexMap index_map, const Params& params)\n    {\n      // Default for distance map\n      typedef typename property_traits<WeightMap>::value_type DistanceType;\n      typename std::vector<DistanceType>::size_type\n        vertex_count = is_default_param(distance_map) ? num_vertices(graph) : 1;\n        \n      std::vector<DistanceType> default_distance_map(vertex_count);\n\n      detail::dijkstra_no_color_map_dispatch2\n        (graph, start_vertex, choose_param(distance_map,\n         make_iterator_property_map(default_distance_map.begin(), index_map,\n                                    default_distance_map[0])),\n         weight_map, index_map, params);\n    }\n  } // namespace detail\n\n  // Named parameter version\n  template <typename Graph, typename Param, typename Tag, typename Rest>\n  inline void\n  dijkstra_shortest_paths_no_color_map\n    (const Graph& graph,\n     typename graph_traits<Graph>::vertex_descriptor start_vertex,\n     const bgl_named_params<Param, Tag, Rest>& params)\n  {\n    // Default for edge weight and vertex index map is to ask for them\n    // from the graph. Default for the visitor is null_visitor.\n    detail::dijkstra_no_color_map_dispatch1\n      (graph, start_vertex,\n       get_param(params, vertex_distance),\n       choose_const_pmap(get_param(params, edge_weight), graph, edge_weight),\n       choose_const_pmap(get_param(params, vertex_index), graph, vertex_index),\n       params);\n  }\n\n} // namespace boost\n\n#endif // BOOST_GRAPH_DIJKSTRA_NO_COLOR_MAP_HPP\n", "meta": {"hexsha": "443984ff0c1e5bb8b08ed8ca87b0b8d72dc843fa", "size": 9971, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/lib/boost/graph/dijkstra_shortest_paths_no_color_map.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/dijkstra_shortest_paths_no_color_map.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/dijkstra_shortest_paths_no_color_map.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": 39.884, "max_line_length": 82, "alphanum_fraction": 0.7023367767, "num_tokens": 2040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.2886132388436675}}
{"text": "// Copyright 2020 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/// \\copyright Copyright 2020 Apex.AI, Inc.\n/// All rights reserved.\n\n#include <state_estimation_nodes/kalman_filter_wrapper.hpp>\n\n#include <common/types.hpp>\n#include <kalman_filter/esrcf.hpp>\n#include <motion_model/constant_acceleration.hpp>\n#include <nav_msgs/msg/odometry.hpp>\n#include <rclcpp/time.hpp>\n#include <state_estimation_nodes/measurement.hpp>\n#include <tf2_geometry_msgs/tf2_geometry_msgs.h>\n#include <tf2/LinearMath/Quaternion.h>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <limits>\n#include <cstdint>\n#include <algorithm>\n\n\nnamespace\n{\nconstexpr auto kCovarianceMatrixRows = 6U;\nconstexpr auto kIndexX = 0U;\nconstexpr auto kIndexY = kCovarianceMatrixRows + 1U;\nconstexpr auto kCovarianceMatrixRowsSquared = kCovarianceMatrixRows * kCovarianceMatrixRows;\nstatic_assert(\n  std::tuple_size<\n    geometry_msgs::msg::PoseWithCovariance::_covariance_type>::value ==\n  kCovarianceMatrixRowsSquared, \"We expect the covariance matrix to have 36 entries.\");\n\n/// Convert a chrono timepoint to ros time.\nrclcpp::Time to_ros_time(const std::chrono::system_clock::time_point & time_point)\n{\n  using std::chrono::duration_cast;\n  using std::chrono::nanoseconds;\n  return rclcpp::Time{duration_cast<nanoseconds>(time_point.time_since_epoch()).count()};\n}\n\n}  // namespace\n\nnamespace autoware\n{\nnamespace prediction\n{\n\nusing motion::motion_model::ConstantAcceleration;\nusing common::types::float64_t;\nusing common::types::bool8_t;\n\ntemplate<typename MotionModelT, std::int32_t kNumOfStates, int32_t kProcessNoiseDim>\nvoid KalmanFilterWrapper<MotionModelT, kNumOfStates, kProcessNoiseDim>::reset(\n  const VectorT<kNumOfStates> & state,\n  const SquareMatrixT<kNumOfStates> & initial_covariance_chol,\n  const MeasurementBasedTime & event_timestamp,\n  const GlobalTime & time_of_event_occurance)\n{\n  m_ekf->reset(state, initial_covariance_chol);\n  m_time_keeper = MeasurementBasedTimeKeeper{time_of_event_occurance, event_timestamp};\n  m_ekf_initialized = true;\n}\n\ntemplate<typename MotionModelT, std::int32_t kNumOfStates, int32_t kProcessNoiseDim>\n// cppcheck-suppress syntaxError\ntemplate<typename MeasurementT>\nvoid KalmanFilterWrapper<MotionModelT, kNumOfStates, kProcessNoiseDim>::reset(\n  const MeasurementT & measurement,\n  const GlobalTime & time_of_event_occurance)\n{\n  reset(\n    measurement.get_values_in_full_state(m_motion_model.get_state()),\n    m_initial_covariance_factor,\n    measurement.get_acquisition_time(),\n    time_of_event_occurance);\n}\n\ntemplate<typename MotionModelT, std::int32_t kNumOfStates, int32_t kProcessNoiseDim>\n// cppcheck-suppress syntaxError\ntemplate<TimeReferenceFrame kTimeReferenceFrame>\ncommon::types::bool8_t  // We cannot use an alias here as Doxygen thinks its a different signature.\nKalmanFilterWrapper<MotionModelT, kNumOfStates, kProcessNoiseDim>::temporal_update(\n  const Time<kTimeReferenceFrame> & time_of_update)\n{\n  if (!is_initialized()) {return false;}\n  const auto dt = m_time_keeper.time_since_last_temporal_update(time_of_update);\n  if (dt <= std::chrono::nanoseconds{0LL}) {return false;}\n  m_ekf->temporal_update(dt);\n  m_time_keeper.increment_last_temporal_update_time(dt);\n  return true;\n}\n\ntemplate<typename MotionModelT, std::int32_t kNumOfStates, int32_t kProcessNoiseDim>\n// cppcheck-suppress syntaxError\ntemplate<typename MeasurementT>\ncommon::types::bool8_t  // We cannot use an alias here as Doxygen thinks its a different signature.\nKalmanFilterWrapper<MotionModelT, kNumOfStates, kProcessNoiseDim>::observation_update(\n  const GlobalTime & global_time_of_message_received,\n  const MeasurementT & measurement)\n{\n  if (!is_initialized()) {\n    // TODO(igor): this is not strictly correct, but should be good enough. If we get an observation\n    // and the filter is not set to any state, we reset it. In this case we assume that this\n    // measurement actually is statefull (not purely differential) and we ignore the variance of\n    // this measurement.\n    reset(measurement, global_time_of_message_received);\n    return true;\n  }\n  // TODO(igor): I am not sure this should be calling latest_timestamp() as if we had a prediction\n  // step with a later timestamp than our measurement here we will discard the measurement. Should\n  // be just compare to the latest measurement time stored in the time keeper?\n  if (m_time_keeper.latest_timestamp() > measurement.get_acquisition_time()) {return false;}\n  if (!temporal_update(measurement.get_acquisition_time())) {return false;}\n  // TODO(igor): 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 and\n  // only compute the distance in the measurement world. Don't really know which one is best here.\n  if (!passes_mahalanobis_gate(\n      measurement.get_values_in_full_state(m_motion_model.get_state()),\n      m_motion_model.get_state(),\n      m_ekf->get_covariance())) {return false;}\n  m_ekf->observation_update(\n    measurement.get_values(),\n    MeasurementT::template get_observation_to_state_mapping<kNumOfStates>(),\n    measurement.get_variances());\n  m_time_keeper.update_with_measurement(global_time_of_message_received, measurement);\n  return true;\n}\n\ntemplate<typename MotionModelT, std::int32_t kNumOfStates, int32_t kProcessNoiseDim>\nbool8_t KalmanFilterWrapper<MotionModelT, kNumOfStates,\n  kProcessNoiseDim>::passes_mahalanobis_gate(\n  const VectorT<kNumOfStates> & sample,\n  const VectorT<kNumOfStates> & mean,\n  const SquareMatrixT<kNumOfStates> & covariance_factor) const\n{\n  // This is equivalent to the squared Mahalanobis distance of the form: diff.T * C.inv() * diff\n  // Instead of the covariance matrix C we have its lower-triangular factor L, such that C = L * L.T\n  // squared_mahalanobis_distance = diff.T * C.inv() * diff\n  // = diff.T * (L * L.T).inv() * diff\n  // = diff.T * L.T.inv() * L.inv() * diff\n  // = (L.inv() * diff).T * (L.inv() * diff)\n  // this allows us to efficiently find the squared Mahalanobis distance using (L.inv() * diff),\n  // which can be found as a solution to: L * x = diff.\n  const auto diff = sample - mean;\n  const auto squared_threshold = m_mahalanobis_threshold * m_mahalanobis_threshold;\n  const auto x = covariance_factor.ldlt().solve(diff);\n  return x.transpose() * x < squared_threshold;\n}\n\ntemplate<typename MotionModelT, std::int32_t kNumOfStates, int32_t kProcessNoiseDim>\nnav_msgs::msg::Odometry KalmanFilterWrapper<MotionModelT, kNumOfStates,\n  kProcessNoiseDim>::get_state() const\n{\n  static_assert(\n    sizeof(MotionModelT) == -1,\n    \"You have to have a specialization for get_state() function!\");\n  // We only throw here because otherwise the linter complaints there is no return value.\n  throw std::runtime_error(\"You have to have a specialization for get_state() function!\");\n}\n\ntemplate<>\nnav_msgs::msg::Odometry ConstantAccelerationFilter::get_state() const\n{\n  using std::chrono::duration_cast;\n  using std::chrono::nanoseconds;\n  nav_msgs::msg::Odometry msg{};\n  if (!is_initialized()) {\n    throw std::runtime_error(\"Filter not is_initialized, cannot get state.\");\n  }\n  msg.header.stamp = rclcpp::Time{to_ros_time(m_time_keeper.latest_timestamp())};\n  msg.header.frame_id = m_frame_id;\n  // Fill state.\n  msg.pose.pose.position.x =\n    static_cast<float64_t>(m_motion_model[ConstantAcceleration::States::POSE_X]);\n  msg.pose.pose.position.y =\n    static_cast<float64_t>(m_motion_model[ConstantAcceleration::States::POSE_Y]);\n  msg.twist.twist.linear.x =\n    static_cast<float64_t>(m_motion_model[ConstantAcceleration::States::VELOCITY_X]);\n  msg.twist.twist.linear.y =\n    static_cast<float64_t>(m_motion_model[ConstantAcceleration::States::VELOCITY_Y]);\n\n  const auto rotation_around_z = std::atan2(msg.twist.twist.linear.y, msg.twist.twist.linear.x);\n  tf2::Quaternion rotation;\n  rotation.setRPY(0.0, 0.0, rotation_around_z);\n  msg.pose.pose.orientation = tf2::toMsg(rotation);\n\n  // Fill covariances.\n  const auto & covariance_factor = m_ekf->get_covariance();\n  const auto covariance = covariance_factor * covariance_factor.transpose();\n  msg.pose.covariance[kIndexX] = static_cast<double>(covariance(\n      ConstantAcceleration::States::POSE_X, ConstantAcceleration::States::POSE_X));\n  msg.pose.covariance[kIndexY] = static_cast<double>(covariance(\n      ConstantAcceleration::States::POSE_Y, ConstantAcceleration::States::POSE_Y));\n  msg.twist.covariance[kIndexX] = static_cast<double>(covariance(\n      ConstantAcceleration::States::VELOCITY_X, ConstantAcceleration::States::VELOCITY_X));\n  msg.twist.covariance[kIndexY] = static_cast<double>(covariance(\n      ConstantAcceleration::States::VELOCITY_Y, ConstantAcceleration::States::VELOCITY_Y));\n  // TODO(igor): do we need elements off the diagonal?\n  return msg;\n}\n\n/// Excplicit class instantiation.\ntemplate class KalmanFilterWrapper<ConstantAcceleration, 6, 2>;\n\nusing MeasurementPose = Measurement<common::types::float32_t,\n    ConstantAcceleration::States::POSE_X,\n    ConstantAcceleration::States::POSE_Y>;\n\nusing MeasurementPoseAndSpeed = Measurement<common::types::float32_t,\n    ConstantAcceleration::States::POSE_X,\n    ConstantAcceleration::States::POSE_Y,\n    ConstantAcceleration::States::VELOCITY_X,\n    ConstantAcceleration::States::VELOCITY_Y>;\n\nusing MeasurementSpeed = Measurement<common::types::float32_t,\n    ConstantAcceleration::States::VELOCITY_X,\n    ConstantAcceleration::States::VELOCITY_Y>;\n\ntemplate bool8_t KalmanFilterWrapper<ConstantAcceleration, 6, 2>::observation_update<>(\n  const GlobalTime &, const MeasurementPose &);\ntemplate bool8_t KalmanFilterWrapper<ConstantAcceleration, 6, 2>::observation_update<>(\n  const GlobalTime &, const MeasurementSpeed &);\ntemplate bool8_t KalmanFilterWrapper<ConstantAcceleration, 6, 2>::observation_update<>(\n  const GlobalTime &, const MeasurementPoseAndSpeed &);\n\ntemplate bool8_t KalmanFilterWrapper<ConstantAcceleration, 6, 2>::temporal_update<>(\n  const GlobalTime &);\ntemplate bool8_t KalmanFilterWrapper<ConstantAcceleration, 6, 2>::temporal_update<>(\n  const MeasurementBasedTime &);\n\n}  // namespace prediction\n}  // namespace autoware\n", "meta": {"hexsha": "f75fb02fed0879ceb6c7889c9eb88a3933c57454", "size": 10803, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/prediction/state_estimation_nodes/src/kalman_filter_wrapper.cpp", "max_stars_repo_name": "fanyu2021/fyAutowareAuto", "max_stars_repo_head_hexsha": "073661c0634de671ff01bda8a316a5ce10c96ca9", "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/prediction/state_estimation_nodes/src/kalman_filter_wrapper.cpp", "max_issues_repo_name": "fanyu2021/fyAutowareAuto", "max_issues_repo_head_hexsha": "073661c0634de671ff01bda8a316a5ce10c96ca9", "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/prediction/state_estimation_nodes/src/kalman_filter_wrapper.cpp", "max_forks_repo_name": "fanyu2021/fyAutowareAuto", "max_forks_repo_head_hexsha": "073661c0634de671ff01bda8a316a5ce10c96ca9", "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": 43.3855421687, "max_line_length": 100, "alphanum_fraction": 0.7720077756, "num_tokens": 2655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.39981164073979497, "lm_q1q2_score": 0.28856133550264296}}
{"text": "\n// Library includes\n#include <string>\n#include <ostream>\n#include <iostream>\n#include <boost/program_options/options_description.hpp>\n#include <boost/program_options/parsers.hpp>\n#include <boost/program_options/variables_map.hpp>\n#include <boost/tokenizer.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/filesystem.hpp>\n#include <cmath>\n#include <thread>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Geometry>\n\n// Project includes\n#include \"parseCommandLineOptions.hpp\"\n#include \"hornRegistration.hpp\"\n#include \"PivotCalibration.hpp\"\n#include \"PA3_4_DataConstants.hpp\"\n#include \"parsePA3_4.hpp\"\n#include \"DistortionCalibration.hpp\"\n#include \"IterativeClosestPoint.hpp\"\n\nnamespace po = boost::program_options;\n\n\n\n/// Produce an output CIS CSV file\n/// Note: I tried to make an output function but it probably has bugs\ntemplate<typename T>\nvoid output1CISCSV_PA3(std::ostream& ostr, const std::string& outputName = \"name-output-3.txt\", const T & dk = std::vector<Eigen::Vector3d>(), const T & ck = std::vector<Eigen::Vector3d>(), const std::vector<double> & error = std::vector<double>()){\n    \n    ostr << dk.size() << \" \" << outputName << \"\\n\";\n    \n    typename T::const_iterator dIterator = dk.begin();\n    typename T::const_iterator cIterator = ck.begin();\n    std::vector<double>::const_iterator eIterator = error.begin();\n    for(; dIterator != dk.end() && cIterator != ck.end() && eIterator != error.end();\n        ++dIterator, ++cIterator, ++eIterator){\n            ostr  << (*dIterator)(0) << \"   \"  << (*dIterator)(1) << \"  \"  << (*dIterator)(2) << \"  \" << (*cIterator)(0) << \"   \"  << (*cIterator)(1) << \"  \"  << (*cIterator)(2) << \"  \" << *eIterator << \"\\n\";\n    }\n\n    ostr.flush();\n    \n}\n\n\n/// read the command line options from argc,argv and load them into the params object\n/// @see boost::program_options for details on how the command line parsing library works.\nbool readCommandLine(int argc, char* argv[], ParsedCommandLineCommandsPA3_4 & pclp){\n\n\n    static const bool optional = false; // false means parameters are not required, and therefore optional\n    static const bool required = true;  // true means parameters are required\n\n\n\n    po::options_description generalOptions(\"General Options\");\n    generalOptions.add_options()\n    (\"responseFile\", po::value<std::string>(), \"File containing additional command line parameters\")\n    CLO_HELP\n    CLO_DEBUG\n    (\"debugParser\",\"display debug information for data file parser\")\n    ;\n\n    \n    TerminationCriteriaParams tcp; // default termination criteria params\n\n    po::options_description algorithmOptions(\"Algorithm Options\");\n    algorithmOptions.add_options()\n    (\"threads\",\"run each source data file in a separate thread. May speed up execution dramatically.\")\n    (\"icpAlgorithm\"                         ,po::value<std::string>()->default_value(\"spatialIndex\"         ),\"Options: spatialIndex, simpleSearch. Selects the ICP algorithm version to use. spatialIndex provides a substantial performance boost for large data sets. \")\n    (\"meanErrorThreshold\"                   ,po::value<double>()->default_value(tcp.meanErrorThreshold)       ,\"stop ICP when mean error drops below this level\")\n    (\"maxErrorThreshold\"                    ,po::value<double>()->default_value(tcp.maxErrorThreshold)       ,\"stop ICP when max error drops below this level\")\n    (\"minVarianceInMeanErrorBetweenIterations\"                   ,po::value<double>()->default_value(tcp.minVarianceInMeanErrorBetweenIterations)       ,\"stop ICP when mean error no longer varies between iterations\")\n    (\"minIterationCount\"                   ,po::value<int>()->default_value(tcp.minIterationCount)       ,\"Do not stop ICP unless this many iterations have run\")\n    (\"maxIterationCount\"                    ,po::value<int>()->default_value(tcp.maxIterationCount)       ,\"Stop ICP when the maximum iteration count threshold is reached, superceded by minIterationCount\")\n    \n    ;\n\n\n    // create algorithm command line options\n    //algorithmOptions.add_options()\n\t// todo, add options for configuring algorithms\n\n    po::options_description dataOptions(\"Data Options\");\n\n\n    std::string currentPath(boost::filesystem::path( boost::filesystem::current_path() ).string());\n\n    // create algorithm command line options\n    dataOptions.add_options()\n            (\"pa3\", \"set automatic programming assignment 3 source data parameters, overrides DataFilenamePrefix, exclusive of pa4\")\n            (\"pa4\", \"set automatic programming assignment 4 source data parameters, overrides DataFilenamePrefix, exclusive of pa3\")\n    \n            (\"dataFolderPath\"                   ,po::value<std::string>()->default_value(currentPath)       ,\"folder containing data files, defaults to current working directory\"   )\n            (\"outputDataFolderPath\"             ,po::value<std::string>()->default_value(currentPath)       ,\"folder for output data files, defaults to current working directory\"   )\n            (\"dataFilenamePrefix\"               ,po::value<std::vector<std::string> >()->default_value(PA4DataFilePrefixes(),\"\"),\"constant prefix of data filename path. Specify this multiple times to run on many data sources at once\"   )\n\t\t\t(\"dataFilenameProblemPrefix\"               ,po::value<std::string >()->default_value(pa4problemPrefix),\"constant prefix of data typically starting with \\\"Problem\\\" filename path. Specify this multiple times to run on many data sources at once\"   )\n\t\t  \t(\"suffixAnswer\"    ,po::value<std::string>()->default_value(DefaultAnswer         ),\"suffix of data filename path\"   )\n\t\t  \t(\"suffixOutput\"    ,po::value<std::string>()->default_value(DefaultOutput         ),\"suffix of data filename path\"   )\n\t\t  \t(\"suffixSample\"    ,po::value<std::string>()->default_value(DefaultSampleReadings ),\"suffix of data filename path\"   )\n\t\t  \t(\"suffixMesh\"      ,po::value<std::string>()->default_value(DefaultMesh           ),\"suffix of data filename path\"   )\n\t\t  \t(\"suffixBodyA\"     ,po::value<std::string>()->default_value(DefaultBodyA          ),\"suffix of data filename path\"   )\n\t\t  \t(\"suffixBodyB\"     ,po::value<std::string>()->default_value(DefaultBodyB          ),\"suffix of data filename path\"   )\n\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t  \t(\"AnswerPath\"                    ,po::value<std::string>() , \"full path to data txt file, optional alternative to prefix+suffix name combination\"   )\n\t\t  \t(\"OutputPath\"                    ,po::value<std::string>() , \"full path to data txt file, optional alternative to prefix+suffix name combination\"   )\n\t\t  \t(\"SamplePath\"                    ,po::value<std::string>() , \"full path to data txt file, optional alternative to prefix+suffix name combination\"   )\n\t\t  \t(\"MeshPath\"                      ,po::value<std::string>() , \"full path to data txt file, optional alternative to prefix+suffix name combination\"   )\n\t\t  \t(\"BodyAPath\"                     ,po::value<std::string>() , \"full path to data txt file, optional alternative to prefix+suffix name combination\"   )\n\t\t  \t(\"BodyBPath\"  \t\t\t         ,po::value<std::string>() , \"full path to data txt file, optional alternative to prefix+suffix name combination\"   )\n\t\t  \t(\"em_fiducialsPath\"  \t\t\t ,po::value<std::string>() , \"full path to data txt file, optional alternative to prefix+suffix name combination\"   )\n\t\t  \t(\"em_navPath\"        \t\t\t ,po::value<std::string>() , \"full path to data txt file, optional alternative to prefix+suffix name combination\"   )\n\t\t  \t(\"output2Path\"       \t\t\t ,po::value<std::string>() , \"full path to data txt file, optional alternative to prefix+suffix name combination\"   )\n    \n\t\t\t  ;\n\n    po::options_description allOptions;\n    allOptions.add(generalOptions).add(algorithmOptions).add(dataOptions);\n\n    po::variables_map vmap;\n\n    try\n    {\n      po::store(po::command_line_parser(argc, argv).options(allOptions).run(), vmap);\n      po::notify(vmap);\n    }\n    catch (std::exception& e)\n    {\n      std::cerr << \"[Error] \" << BOOST_CURRENT_FUNCTION << std::endl\n      << \"    \" << e.what() << std::endl\n      << std::endl\n      << allOptions << std::endl;\n      return false;\n    }\n\n    if (vmap.count(CLO_GET_ARG_STR2(CLO_HELP)) || argc < 2)\n    {\n      std::cout << allOptions << std::endl;\n      return false;\n    }\n    \n    pclp.debugParser = vmap.count(\"debugParser\");\n\n\tparseResponseFiles(vmap,allOptions);\n\n\t// initalize string params\n\tstd::string  dataFolderPath\n\t\t\t\t,dataFileNameSuffix_AnswerPath  \n\t\t\t\t,dataFileNameSuffix_OutputPath   \n\t\t\t\t,dataFileNameSuffix_SamplePath  \n\t\t\t\t,dataFileNameSuffix_MeshPath  \n\t\t\t\t,dataFileNameSuffix_BodyAPath   \n\t\t\t\t,dataFileNameSuffix_BodyBPath \n\t\t\t\t;\n\n    DataSourcePA3_4 datasource;\n\n    std::vector<std::string> dataFilenamePrefixList;\n\tstd::string dataFilenameProblemPrefix, icpAlgorithm;\n\n    // load up parameter values from the variable map\n    po::readOption(vmap, \"dataFolderPath\"                  ,dataFolderPath                     ,optional);\n    po::readOption(vmap, \"outputDataFolderPath\"            ,pclp.outputDataFolderPath          ,optional);\n\tpo::readOption(vmap, \"dataFilenamePrefix\"              ,dataFilenamePrefixList             ,optional);\n\tpo::readOption(vmap, \"dataFilenameProblemPrefix\"       ,dataFilenameProblemPrefix          ,optional);\n\tpo::readOption(vmap, \"suffixAnswer\"                    ,dataFileNameSuffix_AnswerPath      ,optional);\n\tpo::readOption(vmap, \"suffixOutput\"                    ,dataFileNameSuffix_OutputPath      ,optional);\n\tpo::readOption(vmap, \"suffixSample\"                    ,dataFileNameSuffix_SamplePath      ,optional);\n\tpo::readOption(vmap, \"suffixMesh\"                      ,dataFileNameSuffix_MeshPath        ,optional);\n\tpo::readOption(vmap, \"suffixBodyA\"                     ,dataFileNameSuffix_BodyAPath       ,optional);\n\tpo::readOption(vmap, \"suffixBodyB\"                     ,dataFileNameSuffix_BodyBPath       ,optional);\n    \n\n    /// @todo consider allowing these values to be specified separately for each data source\n\tpo::readOption(vmap, \"meanErrorThreshold\"              ,tcp.meanErrorThreshold       ,optional);\n\tpo::readOption(vmap, \"maxErrorThreshold\"               ,tcp.maxErrorThreshold        ,optional);\n\tpo::readOption(vmap, \"minVarianceInMeanErrorBetweenIterations\"               ,tcp.minVarianceInMeanErrorBetweenIterations        ,optional);\n\tpo::readOption(vmap, \"minIterationCount\"               ,tcp.minIterationCount        ,optional);\n\tpo::readOption(vmap, \"maxIterationCount\"               ,tcp.maxIterationCount        ,optional);\n    \n    // min iteration count supercedes max\n    tcp.maxIterationCount = std::max(tcp.minIterationCount,tcp.maxIterationCount);\n\t\n    // enable threads if specified\n    pclp.threads = vmap.count(\"threads\");\n    \n    // enable spatialIndex if selected\n\tpo::readOption(vmap, \"icpAlgorithm\"                     ,icpAlgorithm       ,optional);\n    pclp.useSpatialIndex = (icpAlgorithm == \"spatialIndex\");\n    \n    if (vmap.count(\"pa3\")) {\n        dataFilenamePrefixList = PA3DataFilePrefixes();\n\t\tdataFilenameProblemPrefix = pa3problemPrefix;\n    } else if (vmap.count(\"pa4\")) {\n        dataFilenamePrefixList = PA4DataFilePrefixes();\n\t\tdataFilenameProblemPrefix = pa4problemPrefix;\n    }\n    \n\n    int prefixCount = dataFilenamePrefixList.size();\n    if(!prefixCount){\n        pclp.dataSources.push_back(DataSourcePA3_4());\n    }\n\n    if(prefixCount<=1){\n        po::readOption(vmap,\"calbodyPath\"                      ,pclp.dataSources[0].BodyA            ,optional);\n        po::readOption(vmap,\"calreadingsPath\"                  ,pclp.dataSources[0].BodyB            ,optional);\n        po::readOption(vmap,\"empivotPath\"                      ,pclp.dataSources[0].SampleReadings   ,optional);\n        po::readOption(vmap,\"optpivotPath\"                     ,pclp.dataSources[0].Answer           ,optional);\n        po::readOption(vmap,\"output1Path\"                      ,pclp.dataSources[0].Output           ,optional);\n        po::readOption(vmap,\"ct_fiducialsPath\"                 ,pclp.dataSources[0].Mesh             ,optional);\n    }\n\n\n\t// check if the user supplied a full path, if not assemble a path\n\t// from the default paths and the defualt prefix/suffix combos\n    for(auto&& prefix : dataFilenamePrefixList){\n        DataSourcePA3_4 dataSource;\n\t\tdataSource.terminationCriteriaParams = tcp;\n        dataSource.filenamePrefix = prefix;\n        dataSource.filenameProblemPrefix = dataFilenameProblemPrefix;\n        assemblePathIfFullPathNotSupplied(dataFolderPath,dataSource.filenameProblemPrefix       ,dataFileNameSuffix_BodyAPath   ,dataSource.BodyA            ,required);\n        assemblePathIfFullPathNotSupplied(dataFolderPath,dataSource.filenameProblemPrefix       ,dataFileNameSuffix_BodyBPath   ,dataSource.BodyB            ,required);\n        assemblePathIfFullPathNotSupplied(dataFolderPath,dataSource.filenamePrefix              ,dataFileNameSuffix_SamplePath  ,dataSource.SampleReadings   ,required);\n        assemblePathIfFullPathNotSupplied(dataFolderPath,dataSource.filenamePrefix              ,dataFileNameSuffix_AnswerPath  ,dataSource.Answer           ,optional);\n        assemblePathIfFullPathNotSupplied(dataFolderPath,dataSource.filenamePrefix              ,dataFileNameSuffix_OutputPath  ,dataSource.Output           ,optional);\n        assemblePathIfFullPathNotSupplied(dataFolderPath,dataSource.filenameProblemPrefix       ,dataFileNameSuffix_MeshPath    ,dataSource.Mesh             ,required);\n\n        pclp.dataSources.push_back(dataSource);\n    }\n\n    pclp.debug = vmap.count(CLO_GET_ARG_STR2(CLO_DEBUG));\n\n    return false;\n}\n\n\n/// run the PA3 algorithm and create then write the output file\nvoid generateOutputFilePA3_4(AlgorithmDataPA3_4 ad, std::string outputDataFolderPath, std::string dataFilenamePrefix, bool useSpatialIndex = false, TerminationCriteriaParams tcp = TerminationCriteriaParams(), bool debug = false){\n    \n    Eigen::MatrixXd skMat;\n    Eigen::MatrixXd ckMat;\n\t\n    std::vector<double> errork;\n    Eigen::Affine3d Freg;\n    TerminationCriteria tc(tcp);\n    tc.description = dataFilenamePrefix;\n\t\n    Eigen::MatrixXd dkMat = dkKnownMeshPointsBaseFrame(ad.sampleReadings.NA, ad.sampleReadings.NB, ad.bodyA.tip, ad.bodyA.markerLEDs, ad.bodyB.markerLEDs);\n    if(!useSpatialIndex){ // original slower way\n        ICPwithSimpleSearch(dkMat, ad.mesh.vertices, ad.mesh.vertexTriangleNeighborIndex,tc,Freg,skMat,ckMat,errork,debug);\n    } else { // new cool fast big data structure way\n        ICPwithSpatialIndex(dkMat, ad.mesh.vertices, ad.mesh.vertexTriangleNeighborIndex,tc,Freg,skMat,ckMat,errork,debug);\n    }\n    \n\n    std::vector<Eigen::Vector3d> sk(splitVectors(skMat));\n    std::vector<Eigen::Vector3d> ck(splitVectors(ckMat));\n\t\n    std::string outputFilename =  dataFilenamePrefix + \"-Output.txt\";\n    std::ofstream ofs (outputFilename, std::ofstream::out);\n    output1CISCSV_PA3(ofs,outputFilename,sk,ck,errork);\n    \n    ofs.close();\n    \n}\n\n\n\n/**************************************************************************/\n/**\n * @brief Main function\n *\n * @param argc  Number of input arguments\n * @param argv  Pointer to input arguments\n *\n * @return int\n */\nint main(int argc,char**argv) {\n\n\tParsedCommandLineCommandsPA3_4 pclp;\n\treadCommandLine(argc,argv,pclp);\n    \n    // thread pool to speed up execution\n    std::vector<std::thread> th;\n\n    for(auto&& dataSource : pclp.dataSources){\n        AlgorithmDataPA3_4 ad;\n        ad.bodyA          = parseProblemBody    (loadStringFromFile(dataSource.BodyA)            ,pclp.debugParser       );\n        ad.bodyB          = parseProblemBody    (loadStringFromFile(dataSource.BodyB)            ,pclp.debugParser       );\n\t\tad.mesh           = parseMesh           (loadStringFromFile(dataSource.Mesh)             ,pclp.debugParser       );\n\t\tad.sampleReadings = parseSampleReadings (loadStringFromFile(dataSource.SampleReadings)   , ad.bodyA.markerLEDs.rows(), ad.bodyB.markerLEDs.rows() ,pclp.debugParser       );\n\n        if(pclp.threads) {\n            // run all data sources in separate threads to speed up execution\n            th.push_back(std::thread(generateOutputFilePA3_4,ad, pclp.outputDataFolderPath, dataSource.filenamePrefix,pclp.useSpatialIndex,dataSource.terminationCriteriaParams,pclp.debug));\n        } else {\n            generateOutputFilePA3_4(ad, pclp.outputDataFolderPath, dataSource.filenamePrefix,pclp.useSpatialIndex,dataSource.terminationCriteriaParams,pclp.debug);\n        }\n    }\n    \n    \n    //Join the threads with the main thread\n    for(auto &t : th){\n        t.join();\n    }\n\t\n\treturn 0;\n}\n\n\n\n", "meta": {"hexsha": "c8f1f04446f3d3cef075bc377075ec476483d412", "size": 16581, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cisHW3-4.cpp", "max_stars_repo_name": "ahundt/cis", "max_stars_repo_head_hexsha": "bd55e8c77ec78994454247ffe7d67f537710a53f", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-17T03:13:01.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-17T03:13:01.000Z", "max_issues_repo_path": "src/cisHW3-4.cpp", "max_issues_repo_name": "ahundt/cis", "max_issues_repo_head_hexsha": "bd55e8c77ec78994454247ffe7d67f537710a53f", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cisHW3-4.cpp", "max_forks_repo_name": "ahundt/cis", "max_forks_repo_head_hexsha": "bd55e8c77ec78994454247ffe7d67f537710a53f", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.3343653251, "max_line_length": 267, "alphanum_fraction": 0.6672697666, "num_tokens": 3830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.28840907444608993}}
{"text": "/**********************************************************************\r\n*  Copyright (c) 2008-2014, Alliance for Sustainable Energy.\r\n*  All rights reserved.\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 Street, Fifth Floor, Boston, MA  02110-1301  USA\r\n**********************************************************************/\r\n\r\n#include \"Matrix.hpp\"\r\n\r\n#include \"../core/Optional.hpp\"\r\n#include \"../math/FloatCompare.hpp\"\r\n\r\n#include <random>\r\n\r\n// this should all be moved to a utilities/core/Random.h\r\n#include <boost/random/uniform_real.hpp>\r\n#include <boost/random/variate_generator.hpp>\r\n\r\nnamespace openstudio{\r\n\r\n  bool operator==(const Matrix& lhs, const Matrix& rhs)\r\n  {\r\n    bool result = false;\r\n    if (lhs.size1() == rhs.size1()){\r\n      if (lhs.size2() == rhs.size2()){\r\n        result = true;\r\n        for (unsigned i = 0; i < lhs.size1(); ++i){\r\n          for (unsigned j = 0; j < lhs.size2(); ++j){\r\n            if (lhs(i,j) != rhs(i,j)){\r\n              return false;\r\n            }\r\n          }\r\n        }\r\n      }\r\n    }\r\n    return result;\r\n  }\r\n\r\n  bool operator!=(const Matrix& lhs, const Matrix& rhs)\r\n  {\r\n    return !(lhs==rhs);\r\n  }\r\n\r\n  /// linear interpolation of the function v = f(x, y) at point xi, yi\r\n  /// assumes that x and y are strictly increasing\r\n  double interp(const Vector& x, const Vector& y, const Matrix& v, double xi, double yi, InterpMethod interpMethod, ExtrapMethod extrapMethod)\r\n  {\r\n    double result = 0.0;\r\n\r\n    unsigned M = x.size();\r\n    unsigned N = y.size();\r\n\r\n    if ((M != v.size1()) || (N != v.size2())){\r\n      return result;\r\n    }\r\n\r\n    InterpInfo xInfo = interpInfo(x, xi);\r\n\r\n    if (xInfo.extrapolated){\r\n      switch(extrapMethod){\r\n        case NoneExtrap:\r\n          // set all weights to zero\r\n          xInfo.wa = 0.0; xInfo.wb = 0.0;\r\n          break;\r\n        case NearestExtrap:\r\n          // pick closest point\r\n          // no-op\r\n          break;\r\n      }\r\n    }else{\r\n      switch(interpMethod){\r\n        case LinearInterp:\r\n          // linear interpolation\r\n          // no-op\r\n          break;\r\n        case NearestInterp:\r\n          // pick closest point\r\n          if(xInfo.wa > xInfo.wb){\r\n            xInfo.wa = 1.0; xInfo.wb = 0.0;\r\n          }else{\r\n            xInfo.wa = 0.0; xInfo.wb = 1.0;\r\n          }\r\n          break;\r\n        case HoldLastInterp:\r\n          // set to previous value\r\n          xInfo.wa = 1.0; xInfo.wb = 0.0;\r\n          break;\r\n        case HoldNextInterp:\r\n          // set to next value\r\n          xInfo.wa = 0.0; xInfo.wb = 1.0;\r\n          break;\r\n      }\r\n    }\r\n\r\n    InterpInfo yInfo = interpInfo(y, yi);\r\n\r\n    if (yInfo.extrapolated){\r\n      switch(extrapMethod){\r\n        case NoneExtrap:\r\n          // set all weights to zero\r\n          yInfo.wa = 0.0; yInfo.wb = 0.0;\r\n          break;\r\n        case NearestExtrap:\r\n          // pick closest point\r\n          // no-op\r\n          break;\r\n      }\r\n    }else{\r\n      switch(interpMethod){\r\n        case LinearInterp:\r\n          // linear interpolation\r\n          // no-op\r\n          break;\r\n        case NearestInterp:\r\n          // pick closest point\r\n          if(yInfo.wa > yInfo.wb){\r\n            yInfo.wa = 1.0; yInfo.wb = 0.0;\r\n          }else{\r\n            yInfo.wa = 0.0; yInfo.wb = 1.0;\r\n          }\r\n          break;\r\n        case HoldLastInterp:\r\n          // set to previous value\r\n          yInfo.wa = 1.0; yInfo.wb = 0.0;\r\n          break;\r\n        case HoldNextInterp:\r\n          // set to next value\r\n          yInfo.wa = 0.0; yInfo.wb = 1.0;\r\n          break;\r\n      }\r\n    }\r\n\r\n    // we have set weights appropriately so that here we can compute in the same way all the time\r\n    result = xInfo.wa*yInfo.wa*v(xInfo.ia, yInfo.ia) +\r\n             xInfo.wa*yInfo.wb*v(xInfo.ia, yInfo.ib) +\r\n             xInfo.wb*yInfo.wa*v(xInfo.ib, yInfo.ia) +\r\n             xInfo.wb*yInfo.wb*v(xInfo.ib, yInfo.ib);\r\n\r\n    return result;\r\n  }\r\n\r\n  /// linear interpolation of the function v = f(x, y) at points xi, yi\r\n  /// assumes that x and y are strictly increasing\r\n  Vector interp(const Vector& x, const Vector& y, const Matrix& v, const Vector& xi, double yi, InterpMethod interpMethod, ExtrapMethod extrapMethod)\r\n  {\r\n    unsigned M = x.size();\r\n\r\n    Vector result(M);\r\n\r\n    if (M != v.size1()){\r\n      return result;\r\n    }\r\n\r\n    for (unsigned i = 0; i < M; ++i){\r\n      result(i) = interp(x, y, v, xi(i), yi, interpMethod, extrapMethod);\r\n    }\r\n\r\n    return result;\r\n  }\r\n\r\n  /// linear interpolation of the function v = f(x, y) at points xi, yi\r\n  /// assumes that x and y are strictly increasing\r\n  Vector interp(const Vector& x, const Vector& y, const Matrix& v, double xi, const Vector& yi, InterpMethod interpMethod, ExtrapMethod extrapMethod)\r\n  {\r\n    unsigned N = y.size();\r\n\r\n    Vector result(N);\r\n\r\n    if (N != v.size2()){\r\n      return result;\r\n    }\r\n\r\n    for (unsigned j = 0; j < N; ++j){\r\n      result(j) = interp(x, y, v, xi, yi(j), interpMethod, extrapMethod);\r\n    }\r\n\r\n    return result;\r\n  }\r\n\r\n  /// linear interpolation of the function v = f(x, y) at points xi, yi\r\n  /// assumes that x and y are strictly increasing\r\n  Matrix interp(const Vector& x, const Vector& y, const Matrix& v, const Vector& xi, const Vector& yi, InterpMethod interpMethod, ExtrapMethod extrapMethod)\r\n  {\r\n    unsigned M = x.size();\r\n    unsigned N = y.size();\r\n\r\n    Matrix result(M, N);\r\n\r\n    if ((M != v.size1()) || (N != v.size2())){\r\n      return result;\r\n    }\r\n\r\n    for (unsigned i = 0; i < M; ++i){\r\n      for (unsigned j = 0; j < N; ++j){\r\n        result(i,j) = interp(x, y, v, xi(i), yi(j), interpMethod, extrapMethod);\r\n      }\r\n    }\r\n\r\n    return result;\r\n  }\r\n\r\n  /// matrix product\r\n  Matrix prod(const Matrix& lop, const Matrix& rop)\r\n  {\r\n    return boost::numeric::ublas::prod(lop, rop);\r\n  }\r\n\r\n  /// vector product\r\n  Vector prod(const Matrix& m, const Vector& v)\r\n  {\r\n    return boost::numeric::ublas::prod(m, v);\r\n  }\r\n\r\n  /// outer product\r\n  Matrix outerProd(const Vector& lhs, const Vector& rhs)\r\n  {\r\n    return boost::numeric::ublas::outer_prod(lhs, rhs);\r\n  }\r\n\r\n  /// take the natural logarithm of a Matrix\r\n  Matrix log(const Matrix& v)\r\n  {\r\n    unsigned M = v.size1();\r\n    unsigned N = v.size2();\r\n    Matrix result(M, N);\r\n    for (unsigned i = 0; i < M; ++i){\r\n      for (unsigned j = 0; j < N; ++j){\r\n        result(i,j) = std::log(v(i,j));\r\n      }\r\n    }\r\n    return result;\r\n  }\r\n\r\n  /// take the logarithm of a Matrix with certain base\r\n  Matrix log(const Matrix& v, double base)\r\n  {\r\n    double logBase = std::log(base);\r\n    unsigned M = v.size1();\r\n    unsigned N = v.size2();\r\n    Matrix result(M, N);\r\n    for (unsigned i = 0; i < M; ++i){\r\n      for (unsigned j = 0; j < N; ++j){\r\n        result(i,j) = std::log(v(i,j)) / logBase;\r\n      }\r\n    }\r\n    return result;\r\n  }\r\n\r\n  /// generates a Matrix of M*N points randomly drawn between and including a and b.\r\n  Matrix randMatrix(double a, double b, unsigned M, unsigned N)\r\n  {\r\n    // ETH@20100120. What library does this come from? The user should be able to seed the\r\n    // generator independently of this function.\r\n    // seed random number generator\r\n    static std::minstd_rand generator(42u);\r\n\r\n    // define distribution\r\n    boost::uniform_real<> dist(a,b);\r\n\r\n    // create a generator\r\n    boost::variate_generator<std::minstd_rand&, boost::uniform_real<> > uniformGenerator(generator, dist);\r\n\r\n    // ETH@20120723 Started seeing this as DataFixture.Matrix_RandMatrix hanging on Windows 7,\r\n    // with BoostPro installer.\r\n    // handle degenerate case\r\n    OptionalDouble singlePoint;\r\n    if (equal(a,b)) {\r\n      singlePoint = (a + b) / 2.0;\r\n    }\r\n\r\n    Matrix result(M, N);\r\n    for (unsigned i = 0; i < M; ++i){\r\n      for (unsigned j = 0; j < N; ++j){\r\n        if (singlePoint) {\r\n          result(i,j) = *singlePoint;\r\n        }\r\n        else {\r\n          result(i,j) = uniformGenerator();\r\n        }\r\n      }\r\n    }\r\n    return result;\r\n  }\r\n\r\n  /// sum\r\n  double sum(const Matrix& matrix)\r\n  {\r\n    double result = 0.0;\r\n    for (unsigned i = 0; i < matrix.size1(); ++i){\r\n      for (unsigned j = 0; j < matrix.size2(); ++j){\r\n        result += matrix(i,j);\r\n      }\r\n    }\r\n    return result;\r\n  }\r\n\r\n  /// maximum\r\n  double maximum(const Matrix& matrix)\r\n  {\r\n    double max = 0;\r\n    if ((matrix.size1() > 0) && (matrix.size2() > 0)){\r\n      max = matrix(0,0);\r\n      for (unsigned i = 0; i < matrix.size1(); ++i){\r\n        for (unsigned j = 0; j < matrix.size2(); ++j){\r\n          max = std::max(max, matrix(i,j));\r\n        }\r\n      }\r\n    }\r\n    return max;\r\n  }\r\n\r\n  /// minimum\r\n  double minimum(const Matrix& matrix)\r\n  {\r\n    double min = 0;\r\n    if ((matrix.size1() > 0) && (matrix.size2() > 0)){\r\n      min = matrix(0,0);\r\n      for (unsigned i = 0; i < matrix.size1(); ++i){\r\n        for (unsigned j = 0; j < matrix.size2(); ++j){\r\n          min = std::min(min, matrix(i,j));\r\n        }\r\n      }\r\n    }\r\n    return min;\r\n  }\r\n\r\n  /// mean\r\n  double mean(const Matrix& matrix)\r\n  {\r\n    double avg = 0;\r\n    unsigned N = matrix.size1()*matrix.size2();\r\n    if (N > 0){\r\n      avg = sum(matrix) / N;\r\n    }\r\n    return avg;\r\n  }\r\n\r\n  /// get the connected components from an NxN adjacency matrix (1.0 for i-j connected, 0.0 for i-j not connected)\r\n  std::vector<std::vector<unsigned> > findConnectedComponents(const Matrix& matrix)\r\n  {\r\n    double tol = 0.001;\r\n\r\n    std::vector<std::vector<unsigned> > result;\r\n    \r\n    unsigned N = matrix.size1();\r\n    if (N != matrix.size2()){\r\n      return result;\r\n    }\r\n\r\n    Matrix A(N, N, 0.0);\r\n    for (unsigned i = 0; i < N; ++i){\r\n\r\n      A(i,i) = 1.0; // must be self connected\r\n      if ( std::abs(matrix(i,i) - 1.0) > tol){\r\n        // warn\r\n      }\r\n\r\n      for (unsigned j = i+1; j < N; ++j){\r\n\r\n        if (matrix(i,j) < 0){\r\n          // warn\r\n        }else if (matrix(i,j) > tol){\r\n          A(i,j) = 1.0;\r\n        }\r\n\r\n        if (matrix(j,i) < 0){\r\n          // warn\r\n        }else if (matrix(j,i) > tol){\r\n          A(j,i) = 1.0;\r\n        }\r\n      }\r\n    }\r\n\r\n    // raise A to the Nth power, maximum distance between two nodes\r\n    for (unsigned i = 0; i < N; ++i){\r\n      A = prod(A,A);\r\n    } \r\n\r\n    std::set<unsigned> added;\r\n    for (unsigned i = 0; i < N; ++i){\r\n      if (added.find(i) != added.end()){\r\n        continue;\r\n      }\r\n\r\n      std::vector<unsigned> group;\r\n      group.push_back(i);\r\n      added.insert(i);\r\n\r\n      for (unsigned j = i+1; j < N; ++j){\r\n        if ((A(i,j) > 0) || (A(j,i) > 0)){\r\n          group.push_back(j);\r\n          added.insert(j);\r\n        }\r\n      }\r\n\r\n      result.push_back(group);\r\n    }\r\n\r\n    return result;\r\n  }\r\n\r\n} // openstudio\r\n", "meta": {"hexsha": "61a84a1afa3ce8e25bd505d252a2d8b5d9524e55", "size": 11336, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openstudiocore/src/utilities/data/Matrix.cpp", "max_stars_repo_name": "zhouchong90/OpenStudio", "max_stars_repo_head_hexsha": "f8570cb8297547b5e9cc80fde539240d8f7b9c24", "max_stars_repo_licenses": ["BSL-1.0", "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/utilities/data/Matrix.cpp", "max_issues_repo_name": "zhouchong90/OpenStudio", "max_issues_repo_head_hexsha": "f8570cb8297547b5e9cc80fde539240d8f7b9c24", "max_issues_repo_licenses": ["BSL-1.0", "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/utilities/data/Matrix.cpp", "max_forks_repo_name": "zhouchong90/OpenStudio", "max_forks_repo_head_hexsha": "f8570cb8297547b5e9cc80fde539240d8f7b9c24", "max_forks_repo_licenses": ["BSL-1.0", "blessing"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3156626506, "max_line_length": 157, "alphanum_fraction": 0.5272582922, "num_tokens": 3073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.28838087632101844}}
{"text": "#pragma once\n\n#include \"node.hpp\"\n#include \"random.hpp\"\n#include \"settings.hpp\"\n#include \"data.hpp\"\n#include \"MeanShift.hpp\"\n#include <Eigen/Geometry>\n#include <Eigen/StdVector>\n\n#include <vector>\n#include <cstdint>\n#include <ctime>\n#include <queue>\n\n#include <unordered_map>\n\nnamespace ISUE {\n  namespace RelocForests {\n    class Point3D {\n    public:\n      Point3D(double x, double y, double z) : x(x), y(y), z(z) {};\n      double x, y, z;\n    };\n\n    struct hashFunc{\n      size_t operator()(const Point3D &k) const {\n        size_t h1 = std::hash<double>()(k.x);\n        size_t h2 = std::hash<double>()(k.y);\n        size_t h3 = std::hash<double>()(k.z);\n        return (h1 ^ (h2 << 1)) ^ h3;\n      }\n    };\n\n    struct equalsFunc {\n      bool operator()(const Point3D &l, const Point3D &r) const{\n        return (l.x == r.x) && (l.y == r.y) && (l.z == r.z);\n      }\n    };\n\n    typedef std::unordered_map<Point3D, uint32_t, hashFunc, equalsFunc> Point3DMap;\n\n    template <typename D, typename RGB>\n    class Tree {\n    public:\n      Tree()\n      {\n        root_ = new Node<D, RGB>();\n        root_->depth_ = 0;\n      };\n\n      ~Tree()\n      {\n        delete root_;\n      };\n\n      void WriteTree(std::ostream& o, Node<D, RGB> *node) const\n      {\n        if (node == nullptr) {\n          o.write(\"#\", sizeof('#'));\n          return;\n        }\n        node->Serialize(o);\n        WriteTree(o, node->left_);\n        WriteTree(o, node->right_);\n      }\n\n      void Serialize(std::ostream& stream) const\n      {\n        const int majorVersion = 0, minorVersion = 0;\n        \n        stream.write(binaryFileHeader_, strlen(binaryFileHeader_));\n        stream.write((const char*)(&majorVersion), sizeof(majorVersion));\n        stream.write((const char*)(&minorVersion), sizeof(minorVersion));\n\n        //stream.write((const char*)(&settings_->max_tree_depth_), sizeof(settings_->max_tree_depth_));\n\n        WriteTree(stream, root_);\n      }\n\n      Node<D, RGB>* ReadTree(std::istream& i)\n      {\n        int flag = i.peek();\n        char val = (char)flag;\n        if (val == '#') {\n          i.get();\n          return nullptr;\n        }\n        Node<D, RGB> *tmp = new Node<D, RGB>();\n        tmp->Deserialize(i);\n        tmp->left_ = ReadTree(i);\n        tmp->right_ = ReadTree(i);\n        return tmp;\n      }\n\n      Tree* Deserialize(std::istream& stream)\n      {\n        settings_ = new Settings();\n\n        std::vector<char> buffer(strlen(binaryFileHeader_) + 1);\n        stream.read(&buffer[0], strlen(binaryFileHeader_));\n        buffer[buffer.size() - 1] = '\\0';\n        if (strcmp(&buffer[0], binaryFileHeader_) != 0)\n          throw std::runtime_error(\"Unsupported forest format.\");\n\n        const int majorVersion = 0, minorVersion = 0;\n        stream.read((char*)(&majorVersion), sizeof(majorVersion));\n        stream.read((char*)(&minorVersion), sizeof(minorVersion));\n\n\n        root_ = ReadTree(stream);\n\n      }\n\n      bool IsValidRecurse(Node<D, RGB> *node, bool prevSplit)\n      {\n\n        if (!node && prevSplit)\n          return false;\n\n        if (node->is_leaf_)\n          return true;\n\n        return IsValidRecurse(node->left_, node->is_split_) && IsValidRecurse(node->right_, node->is_split_);\n      }\n\n      bool IsValid()\n      {\n        return IsValidRecurse(root_, true);\n      }\n\n      // learner output\n      enum DECISION { LEFT, RIGHT, TRASH };\n\n      //  Evaluates weak learner. Decides whether the point should go left or right.\n      //  Returns DECISION enum value.\n      DECISION eval_learner(DepthAdaptiveRGB<D, RGB> feature, cv::Mat depth_image, cv::Mat rgb_image, cv::Point2i pos)\n      {\n        bool valid = true;\n        float response = feature.GetResponse(depth_image, rgb_image, pos, *settings_, valid);\n\n        if (!valid) // no depth or out of bounds\n          return DECISION::TRASH;\n\n        return (DECISION)(response >= feature.GetThreshold());\n      }\n\n      // V(S)\n      double variance(std::vector<LabeledPixel> labeled_data)\n      {\n        if (labeled_data.size() == 0)\n          return 0.0;\n        double V = (1.0f / (double)labeled_data.size());\n        double sum = 0.0f;\n\n        // calculate mean of S\n        cv::Point3f tmp;\n        for (auto p : labeled_data)\n          tmp += p.label_;\n        uint32_t size = labeled_data.size();\n        cv::Point3f mean(tmp.x / size, tmp.y / size, tmp.z / size);\n\n        for (auto p : labeled_data) {\n          cv::Point3f val = (p.label_ - mean);\n          sum += val.x * val.x  + val.y * val.y + val.z * val.z;\n        }\n\n        return V * sum;\n      }\n\n\n      // Q(S_n, \\theta)\n      double objective_function(std::vector<LabeledPixel> data, std::vector<LabeledPixel> left, std::vector<LabeledPixel> right)\n      {\n        double var = variance(data);\n        double left_val = ((double)left.size() / (double)data.size()) * variance(left);\n        double right_val = ((double)right.size() / (double)data.size()) * variance(right);\n\n        return var - (left_val + right_val);\n      }\n\n      Eigen::Vector3d GetLeafMode(std::vector<LabeledPixel> S)\n      {\n        std::vector<Eigen::Vector3d> data;\n\n        // calc mode for leaf, sub-sample N_SS = 500\n        for (uint16_t i = 0; i < (S.size() < 500 ? S.size() : 500); i++) {\n          auto p = S.at(i);\n          Eigen::Vector3d point{ p.label_.x, p.label_.y, p.label_.z };\n          data.push_back(point);\n        }\n\n        // cluster\n        MeanShift ms = MeanShift(nullptr);\n        double kernel_bandwidth = 0.01f; // gaussian\n        std::vector<Eigen::Vector3d> cluster = ms.cluster(data, kernel_bandwidth);\n\n        // find mode\n        std::vector<Point3D> clustered_points;\n        for (auto c : cluster)\n          clustered_points.push_back(Point3D(floor(c[0] * 10000) / 10000,\n                                             floor(c[1] * 10000) / 10000,\n                                             floor(c[2] * 10000) / 10000));\n\n        Point3DMap cluster_map;\n\n        for (auto p : clustered_points)\n          cluster_map[p]++;\n\n        std::pair<Point3D, uint32_t> mode(Point3D(0.0, 0.0, 0.0), 0);\n\n        for (auto p : cluster_map)\n          if (p.second > mode.second)\n            mode = p;\n\n        return Eigen::Vector3d(mode.first.x, mode.first.y, mode.first.z);\n      }\n\n\n      void train_recurse(Node<D, RGB> *node, std::vector<LabeledPixel> S) \n      {\n        uint16_t height = node->depth_;\n        if (S.size() == 1 || ((height == settings_->max_tree_depth_ - 1) && S.size() >= 1)) {\n\n          node->mode_ = GetLeafMode(S);\n          node->is_leaf_ = true;\n          node->left_ = nullptr;\n          node->right_ = nullptr;\n          return;\n        }\n\n        uint32_t num_candidates = 5,\n                feature = 0;\n        double minimum_objective = DBL_MAX;\n\n        std::vector<DepthAdaptiveRGB<D, RGB> > candidate_params;\n        std::vector<LabeledPixel> left_final, right_final;\n\n\n        for (uint32_t i = 0; i < num_candidates; ++i) {\n\n          // add candidate\n          candidate_params.push_back(DepthAdaptiveRGB<D, RGB>::CreateRandom(random_));\n\n          // partition data with candidate\n          std::vector<LabeledPixel> left_data, right_data;\n\n          for (uint32_t j = 0; j < S.size(); ++j) {\n\n            LabeledPixel p = S.at(j);\n            DECISION val = eval_learner(candidate_params.at(i), data_->GetDepthImage(p.frame_), data_->GetRGBImage(p.frame_), p.pos_);\n\n            switch (val) {\n            case LEFT:\n              left_data.push_back(S.at(j));\n              break;\n            case RIGHT:\n              right_data.push_back(S.at(j));\n              break;\n            case TRASH:\n              // do nothing\n              break;\n            }\n\n          }\n\n          // eval tree training objective function and take best\n          // todo: ensure objective function is correct\n          double objective = objective_function(S, left_data, right_data);\n\n          if (objective < minimum_objective) {\n            feature = i;\n            minimum_objective = objective;\n            left_final = left_data;\n            right_final = right_data;\n          }\n        }\n\n        // split went only one way\n        if (left_final.empty()) {\n          node->mode_ = GetLeafMode(right_final);\n          node->is_leaf_ = true;\n          node->left_ = nullptr;\n          node->right_ = nullptr;\n          return;\n        }\n        if (right_final.empty()) {\n          node->mode_ = GetLeafMode(left_final);\n          node->is_leaf_ = true;\n          node->left_ = nullptr;\n          node->right_ = nullptr;\n          return;\n        }\n\n        // set feature\n        node->is_split_ = true;\n        node->is_leaf_ = false;\n        node->feature_ = candidate_params.at(feature);\n        node->left_ = new Node<D, RGB>();\n        node->right_ = new Node<D, RGB>();\n        node->left_->depth_ = node->right_->depth_ = node->depth_ + 1;\n\n        train_recurse(node->left_, left_final);\n        train_recurse(node->right_, right_final);\n      }\n\n      void Train(Data *data, std::vector<LabeledPixel> labeled_data, Random *random, Settings *settings) \n      {\n        data_ = data;\n        random_ = random;\n        settings_ = settings;\n        train_recurse(root_, labeled_data);\n      }\n\n      Eigen::Vector3d eval_recursive(Node<D, RGB> **node, int row, int col, cv::Mat rgb_image, cv::Mat depth_image, bool &valid)\n      {\n        if ((*node)->is_leaf_) {\n          return (*node)->mode_;\n        }\n\n        DECISION val = eval_learner((*node)->feature_, depth_image, rgb_image, cv::Point2i(col, row));\n\n        switch (val) {\n        case LEFT:\n          return eval_recursive(&(*node)->left_, row, col, rgb_image, depth_image, valid);\n          break;\n        case RIGHT:\n          return eval_recursive(&(*node)->right_, row, col, rgb_image, depth_image, valid);\n          break;\n        case TRASH:\n          valid = false;\n          break;\n        }\n      }\n\n      // Evaluate tree at a pixel\n      Eigen::Vector3d Eval(int row, int col, cv::Mat rgb_image, cv::Mat depth_image, bool &valid)\n      {\n        auto m = eval_recursive(&root_, row, col, rgb_image, depth_image, valid);\n        return m;\n      }\n\n\n    private:\n      Node<D, RGB> *root_;\n      Data *data_;\n      Random *random_;\n      Settings *settings_;\n      const char* binaryFileHeader_ = \"ISUE.RelocForests.Tree\";\n    };\n  }\n}\n", "meta": {"hexsha": "a389913aa9bc08ff7df976b08e9063ba04d1c79a", "size": 10323, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/tree.hpp", "max_stars_repo_name": "ISUE/relocforests", "max_stars_repo_head_hexsha": "1515c55e069aae82bca52076232b5b0df660886b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 51.0, "max_stars_repo_stars_event_min_datetime": "2016-02-29T01:40:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T09:23:53.000Z", "max_issues_repo_path": "include/tree.hpp", "max_issues_repo_name": "ISUE/relocforests", "max_issues_repo_head_hexsha": "1515c55e069aae82bca52076232b5b0df660886b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2016-02-01T21:18:18.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-27T05:21:37.000Z", "max_forks_repo_path": "include/tree.hpp", "max_forks_repo_name": "ISUE/relocforests", "max_forks_repo_head_hexsha": "1515c55e069aae82bca52076232b5b0df660886b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-04-08T01:28:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T10:52:00.000Z", "avg_line_length": 29.2436260623, "max_line_length": 134, "alphanum_fraction": 0.5498401627, "num_tokens": 2605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.28837770943708557}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2008 Jose Aparicio\n Copyright (C) 2008 Chris Kenyon\n Copyright (C) 2008 Roland Lichters\n Copyright (C) 2008 StatPro Italia srl\n Copyright (C) 2009 Ferdinando Ametrano\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 hazardratestructure.hpp\n    \\brief hazard-rate term structure\n*/\n\n#ifndef quantlib_hazard_rate_structure_hpp\n#define quantlib_hazard_rate_structure_hpp\n\n#include <ql/termstructures/defaulttermstructure.hpp>\n\nnamespace QuantLib {\n\n    //! Hazard-rate term structure\n    /*! This abstract class acts as an adapter to\n        DefaultProbabilityTermStructure allowing the programmer to implement\n        only the <tt>hazardRateImpl(Time)</tt> method in derived classes.\n\n        Survival/default probabilities and default densities are calculated\n        from hazard rates.\n\n        Hazard rates are defined with annual frequency and continuous\n        compounding.\n\n        \\ingroup defaultprobabilitytermstructures\n    */\n    class HazardRateStructure : public DefaultProbabilityTermStructure {\n      public:\n        /*! \\name Constructors\n            See the TermStructure documentation for issues regarding\n            constructors.\n        */\n        //@{\n        HazardRateStructure(\n            const DayCounter& dayCounter = DayCounter(),\n            const std::vector<Handle<Quote> >& jumps = std::vector<Handle<Quote> >(),\n            const std::vector<Date>& jumpDates = std::vector<Date>());\n        HazardRateStructure(\n            const Date& referenceDate,\n            const Calendar& cal = Calendar(),\n            const DayCounter& dayCounter = DayCounter(),\n            const std::vector<Handle<Quote> >& jumps = std::vector<Handle<Quote> >(),\n            const std::vector<Date>& jumpDates = std::vector<Date>());\n        HazardRateStructure(\n            Natural settlementDays,\n            const Calendar& cal,\n            const DayCounter& dayCounter = DayCounter(),\n            const std::vector<Handle<Quote> >& jumps = std::vector<Handle<Quote> >(),\n            const std::vector<Date>& jumpDates = std::vector<Date>());\n        //@}\n      protected:\n        /*! \\name Calculations\n\n            This method must be implemented in derived classes to\n            perform the actual calculations. When it is called,\n            range check has already been performed; therefore, it\n            must assume that extrapolation is required.\n        */\n        //@{\n        //! hazard rate calculation\n        virtual Real hazardRateImpl(Time) const = 0;\n        //@}\n\n        //! \\name DefaultProbabilityTermStructure implementation\n        //@{\n        /*! survival probability calculation\n            implemented in terms of the hazard rate \\f$ h(t) \\f$ as\n            \\f[\n            S(t) = \\exp\\left( - \\int_0^t h(\\tau) d\\tau \\right).\n            \\f]\n\n            \\warning This default implementation uses numerical integration,\n                     which might be inefficient and inaccurate.\n                     Derived classes should override it if a more efficient\n                     implementation is available.\n        */\n        Probability survivalProbabilityImpl(Time) const;\n        //! default density calculation\n        Real defaultDensityImpl(Time) const;\n        //@}\n    };\n\n    // inline definitions\n\n    inline Real HazardRateStructure::defaultDensityImpl(Time t) const {\n        return hazardRateImpl(t)*survivalProbabilityImpl(t);\n    }\n\n}\n\n\n/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2008 Jose Aparicio\n Copyright (C) 2008 Chris Kenyon\n Copyright (C) 2008 Roland Lichters\n Copyright (C) 2008 StatPro Italia srl\n Copyright (C) 2009 Ferdinando Ametrano\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/math/integrals/gaussianquadratures.hpp>\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-local-typedefs\"\n#endif\n#include <boost/bind.hpp>\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic pop\n#endif\n\nusing namespace boost;\n\nnamespace QuantLib {\n\n    namespace {\n\n        template <class F>\n        struct remapper {\n            F f;\n            Time T;\n            remapper(const F& f, Time T) : f(f), T(T) {}\n            // This remaps [-1,1] to [0,T]. No differential included.\n            Real operator()(Real x) const {\n                const Real arg = (x+1.0)*T/2.0;\n                return f(arg);\n            }\n        };\n\n        template <class F>\n        remapper<F> remap(const F& f, Time T) {\n            return remapper<F>(f,T);\n        }\n\n    }\n\n    inline HazardRateStructure::HazardRateStructure(\n                                    const DayCounter& dc,\n                                    const std::vector<Handle<Quote> >& jumps,\n                                    const std::vector<Date>& jumpDates)\n    : DefaultProbabilityTermStructure(dc, jumps, jumpDates) {}\n\n    inline HazardRateStructure::HazardRateStructure(\n                                    const Date& refDate,\n                                    const Calendar& cal,\n                                    const DayCounter& dc,\n                                    const std::vector<Handle<Quote> >& jumps,\n                                    const std::vector<Date>& jumpDates)\n    : DefaultProbabilityTermStructure(refDate, cal, dc, jumps, jumpDates) {}\n\n    inline HazardRateStructure::HazardRateStructure(\n                                    Natural settlDays,\n                                    const Calendar& cal,\n                                    const DayCounter& dc,\n                                    const std::vector<Handle<Quote> >& jumps,\n                                    const std::vector<Date>& jumpDates)\n    : DefaultProbabilityTermStructure(settlDays, cal, dc, jumps, jumpDates) {}\n\n    inline Probability HazardRateStructure::survivalProbabilityImpl(Time t) const {\n        static GaussChebyshevIntegration integral(48);\n        // this stores the address of the method to integrate (so that\n        // we don't have to insert its full expression inside the\n        // integral below--it's long enough already)\n        Real (HazardRateStructure::*f)(Time) const =\n            &HazardRateStructure::hazardRateImpl;\n        // the Gauss-Chebyshev quadratures integrate over [-1,1],\n        // hence the remapping (and the Jacobian term t/2)\n        return std::exp(-integral(remap(bind(f,this,_1), t)) * t/2.0);\n    }\n\n}\n\n#endif\n", "meta": {"hexsha": "c234d14756d5823b018df33b972dc89f1e61aa58", "size": 7904, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/termstructures/credit/hazardratestructure.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/termstructures/credit/hazardratestructure.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/termstructures/credit/hazardratestructure.hpp", "max_forks_repo_name": "markxio/Quantuccia", "max_forks_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2017-03-19T05:56:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T13:30:20.000Z", "avg_line_length": 38.0, "max_line_length": 87, "alphanum_fraction": 0.6247469636, "num_tokens": 1694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883592602049, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.28837770943708557}}
{"text": "/* [auto_generated]\n boost/numeric/odeint/stepper/controlled_runge_kutta.hpp\n\n [begin_description]\n The default controlled stepper which can be used with all explicit Runge-Kutta error steppers.\n [end_description]\n\n Copyright 2010-2013 Karsten Ahnert\n Copyright 2010-2015 Mario Mulansky\n Copyright 2012 Christoph Koke\n\n Distributed under the Boost Software License, Version 1.0.\n (See accompanying file LICENSE_1_0.txt or\n copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n\n#ifndef BOOST_NUMERIC_ODEINT_STEPPER_CONTROLLED_RUNGE_KUTTA_HPP_INCLUDED\n#define BOOST_NUMERIC_ODEINT_STEPPER_CONTROLLED_RUNGE_KUTTA_HPP_INCLUDED\n\n\n\n#include <cmath>\n\n#include <boost/config.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits/is_same.hpp>\n\n#include <boost/numeric/odeint/util/bind.hpp>\n#include <boost/numeric/odeint/util/unwrap_reference.hpp>\n#include <boost/numeric/odeint/util/copy.hpp>\n\n#include <boost/numeric/odeint/util/state_wrapper.hpp>\n#include <boost/numeric/odeint/util/is_resizeable.hpp>\n#include <boost/numeric/odeint/util/resizer.hpp>\n#include <boost/numeric/odeint/util/detail/less_with_sign.hpp>\n\n#include <boost/numeric/odeint/algebra/range_algebra.hpp>\n#include <boost/numeric/odeint/algebra/default_operations.hpp>\n#include <boost/numeric/odeint/algebra/algebra_dispatcher.hpp>\n\n#include <boost/numeric/odeint/stepper/controlled_step_result.hpp>\n#include <boost/numeric/odeint/stepper/stepper_categories.hpp>\n\nnamespace boost {\nnamespace numeric {\nnamespace odeint {\n\n\ntemplate\n<\nclass Value ,\nclass Algebra ,\nclass Operations\n>\nclass default_error_checker\n{\npublic:\n\n    typedef Value value_type;\n    typedef Algebra algebra_type;\n    typedef Operations operations_type;\n\n    default_error_checker(\n            value_type eps_abs = static_cast< value_type >( 1.0e-6 ) ,\n            value_type eps_rel = static_cast< value_type >( 1.0e-6 ) ,\n            value_type a_x = static_cast< value_type >( 1 ) ,\n            value_type a_dxdt = static_cast< value_type >( 1 ))\n        : m_eps_abs( eps_abs ) , m_eps_rel( eps_rel ) , m_a_x( a_x ) , m_a_dxdt( a_dxdt )\n    { }\n\n\n    template< class State , class Deriv , class Err, class Time >\n    value_type error( const State &x_old , const Deriv &dxdt_old , Err &x_err , Time dt ) const\n    {\n        return error( algebra_type() , x_old , dxdt_old , x_err , dt );\n    }\n\n    template< class State , class Deriv , class Err, class Time >\n    value_type error( algebra_type &algebra , const State &x_old , const Deriv &dxdt_old , Err &x_err , Time dt ) const\n    {\n        using std::abs;\n        // this overwrites x_err !\n        algebra.for_each3( x_err , x_old , dxdt_old ,\n                typename operations_type::template rel_error< value_type >( m_eps_abs , m_eps_rel , m_a_x , m_a_dxdt * abs(get_unit_value( dt )) ) );\n\n        // value_type res = algebra.reduce( x_err ,\n        //        typename operations_type::template maximum< value_type >() , static_cast< value_type >( 0 ) );\n        return algebra.norm_inf( x_err );\n    }\n\nprivate:\n\n    value_type m_eps_abs;\n    value_type m_eps_rel;\n    value_type m_a_x;\n    value_type m_a_dxdt;\n\n};\n\n\ntemplate< typename Value, typename Time >\nclass default_step_adjuster\n{\npublic:\n    typedef Time time_type;\n    typedef Value value_type;\n\n    default_step_adjuster(const time_type max_dt=static_cast<time_type>(0))\n            : m_max_dt(max_dt)\n    {}\n\n\n    time_type decrease_step(time_type dt, const value_type error, const int error_order) const\n    {\n        // returns the decreased time step\n        BOOST_USING_STD_MIN();\n        BOOST_USING_STD_MAX();\n        using std::pow;\n\n        dt *= max\n        BOOST_PREVENT_MACRO_SUBSTITUTION(\n                static_cast<value_type>( static_cast<value_type>(9) / static_cast<value_type>(10) *\n                                         pow(error, static_cast<value_type>(-1) / (error_order - 1))),\n                static_cast<value_type>( static_cast<value_type>(1) / static_cast<value_type> (5)));\n        if(m_max_dt != static_cast<time_type >(0))\n            // limit to maximal stepsize even when decreasing\n            dt = detail::min_abs(dt, m_max_dt);\n        return dt;\n    }\n\n    time_type increase_step(time_type dt, value_type error, const int stepper_order) const\n    {\n        // returns the increased time step\n        BOOST_USING_STD_MIN();\n        BOOST_USING_STD_MAX();\n        using std::pow;\n\n        // adjust the size if dt is smaller than max_dt (providede max_dt is not zero)\n        if(error < 0.5)\n        {\n            // error should be > 0\n            error = max BOOST_PREVENT_MACRO_SUBSTITUTION (\n                    static_cast<value_type>( pow( static_cast<value_type>(5.0) , -static_cast<value_type>(stepper_order) ) ) ,\n                    error);\n            // time_type dt_old = dt;   unused variable warning\n            //error too small - increase dt and keep the evolution and limit scaling factor to 5.0\n            dt *= static_cast<value_type>(9)/static_cast<value_type>(10) *\n                  pow(error, static_cast<value_type>(-1) / stepper_order);\n            if(m_max_dt != static_cast<time_type >(0))\n                // limit to maximal stepsize\n                dt = detail::min_abs(dt, m_max_dt);\n        }\n        return dt;\n    }\n\n    bool check_step_size_limit(const time_type dt)\n    {\n        if(m_max_dt != static_cast<time_type >(0))\n            return detail::less_eq_with_sign(dt, m_max_dt, dt);\n        return true;\n    }\n\n    time_type get_max_dt() { return m_max_dt; }\n\nprivate:\n    time_type m_max_dt;\n};\n\n\n\n/*\n * error stepper category dispatcher\n */\ntemplate<\nclass ErrorStepper ,\nclass ErrorChecker = default_error_checker< typename ErrorStepper::value_type ,\n    typename ErrorStepper::algebra_type ,\n    typename ErrorStepper::operations_type > ,\nclass StepAdjuster = default_step_adjuster< typename ErrorStepper::value_type ,\n    typename ErrorStepper::time_type > ,\nclass Resizer = typename ErrorStepper::resizer_type ,\nclass ErrorStepperCategory = typename ErrorStepper::stepper_category\n>\nclass controlled_runge_kutta ;\n\n\n\n/*\n * explicit stepper version\n *\n * this class introduces the following try_step overloads\n    * try_step( sys , x , t , dt )\n    * try_step( sys , x , dxdt , t , dt )\n    * try_step( sys , in , t , out , dt )\n    * try_step( sys , in , dxdt , t , out , dt )\n */\n/**\n * \\brief Implements step size control for Runge-Kutta steppers with error\n * estimation.\n *\n * This class implements the step size control for standard Runge-Kutta\n * steppers with error estimation.\n *\n * \\tparam ErrorStepper The stepper type with error estimation, has to fulfill the ErrorStepper concept.\n * \\tparam ErrorChecker The error checker\n * \\tparam Resizer The resizer policy type.\n */\ntemplate<\nclass ErrorStepper,\nclass ErrorChecker,\nclass StepAdjuster,\nclass Resizer\n>\nclass controlled_runge_kutta< ErrorStepper , ErrorChecker , StepAdjuster, Resizer ,\n        explicit_error_stepper_tag >\n{\n\npublic:\n\n    typedef ErrorStepper stepper_type;\n    typedef typename stepper_type::state_type state_type;\n    typedef typename stepper_type::value_type value_type;\n    typedef typename stepper_type::deriv_type deriv_type;\n    typedef typename stepper_type::time_type time_type;\n    typedef typename stepper_type::algebra_type algebra_type;\n    typedef typename stepper_type::operations_type operations_type;\n    typedef Resizer resizer_type;\n    typedef ErrorChecker error_checker_type;\n    typedef StepAdjuster step_adjuster_type;\n    typedef explicit_controlled_stepper_tag stepper_category;\n\n#ifndef DOXYGEN_SKIP\n    typedef typename stepper_type::wrapped_state_type wrapped_state_type;\n    typedef typename stepper_type::wrapped_deriv_type wrapped_deriv_type;\n\n    typedef controlled_runge_kutta< ErrorStepper , ErrorChecker , StepAdjuster ,\n            Resizer , explicit_error_stepper_tag > controlled_stepper_type;\n#endif //DOXYGEN_SKIP\n\n\n    /**\n     * \\brief Constructs the controlled Runge-Kutta stepper.\n     * \\param error_checker An instance of the error checker.\n     * \\param stepper An instance of the underlying stepper.\n     */\n    controlled_runge_kutta(\n            const error_checker_type &error_checker = error_checker_type( ) ,\n            const step_adjuster_type &step_adjuster = step_adjuster_type() ,\n            const stepper_type &stepper = stepper_type( )\n    )\n        : m_stepper(stepper), m_error_checker(error_checker) , m_step_adjuster(step_adjuster)\n    { }\n\n\n\n    /*\n     * Version 1 : try_step( sys , x , t , dt )\n     *\n     * The overloads are needed to solve the forwarding problem\n     */\n    /**\n     * \\brief Tries to perform one step.\n     *\n     * This method tries to do one step with step size dt. If the error estimate\n     * is to large, the step is rejected and the method returns fail and the\n     * step size dt is reduced. If the error estimate is acceptably small, the\n     * step is performed, success is returned and dt might be increased to make\n     * the steps as large as possible. This method also updates t if a step is\n     * performed.\n     *\n     * \\param system The system function to solve, hence the r.h.s. of the ODE. It must fulfill the\n     *               Simple System concept.\n     * \\param x The state of the ODE which should be solved. Overwritten if\n     * the step is successful.\n     * \\param t The value of the time. Updated if the step is successful.\n     * \\param dt The step size. Updated.\n     * \\return success if the step was accepted, fail otherwise.\n     */\n    template< class System , class StateInOut >\n    controlled_step_result try_step( System system , StateInOut &x , time_type &t , time_type &dt )\n    {\n        return try_step_v1( system , x , t, dt );\n    }\n\n    /**\n     * \\brief Tries to perform one step. Solves the forwarding problem and\n     * allows for using boost range as state_type.\n     *\n     * This method tries to do one step with step size dt. If the error estimate\n     * is to large, the step is rejected and the method returns fail and the\n     * step size dt is reduced. If the error estimate is acceptably small, the\n     * step is performed, success is returned and dt might be increased to make\n     * the steps as large as possible. This method also updates t if a step is\n     * performed.\n     *\n     * \\param system The system function to solve, hence the r.h.s. of the ODE. It must fulfill the\n     *               Simple System concept.\n     * \\param x The state of the ODE which should be solved. Overwritten if\n     * the step is successful. Can be a boost range.\n     * \\param t The value of the time. Updated if the step is successful.\n     * \\param dt The step size. Updated.\n     * \\return success if the step was accepted, fail otherwise.\n     */\n    template< class System , class StateInOut >\n    controlled_step_result try_step( System system , const StateInOut &x , time_type &t , time_type &dt )\n    {\n        return try_step_v1( system , x , t, dt );\n    }\n\n\n\n    /*\n     * Version 2 : try_step( sys , x , dxdt , t , dt )\n     *\n     * this version does not solve the forwarding problem, boost.range can not be used\n     */\n    /**\n     * \\brief Tries to perform one step.\n     *\n     * This method tries to do one step with step size dt. If the error estimate\n     * is to large, the step is rejected and the method returns fail and the\n     * step size dt is reduced. If the error estimate is acceptably small, the\n     * step is performed, success is returned and dt might be increased to make\n     * the steps as large as possible. This method also updates t if a step is\n     * performed.\n     *\n     * \\param system The system function to solve, hence the r.h.s. of the ODE. It must fulfill the\n     *               Simple System concept.\n     * \\param x The state of the ODE which should be solved. Overwritten if\n     * the step is successful.\n     * \\param dxdt The derivative of state.\n     * \\param t The value of the time. Updated if the step is successful.\n     * \\param dt The step size. Updated.\n     * \\return success if the step was accepted, fail otherwise.\n     */\n    template< class System , class StateInOut , class DerivIn >\n    controlled_step_result try_step( System system , StateInOut &x , const DerivIn &dxdt , time_type &t , time_type &dt )\n    {\n        m_xnew_resizer.adjust_size( x , detail::bind( &controlled_runge_kutta::template resize_m_xnew_impl< StateInOut > , detail::ref( *this ) , detail::_1 ) );\n        controlled_step_result res = try_step( system , x , dxdt , t , m_xnew.m_v , dt );\n        if( res == success )\n        {\n            boost::numeric::odeint::copy( m_xnew.m_v , x );\n        }\n        return res;\n    }\n\n    /*\n     * Version 3 : try_step( sys , in , t , out , dt )\n     *\n     * this version does not solve the forwarding problem, boost.range can not be used\n     *\n     * the disable is needed to avoid ambiguous overloads if state_type = time_type\n     */\n    /**\n     * \\brief Tries to perform one step.\n     *\n     * \\note This method is disabled if state_type=time_type to avoid ambiguity.\n     *\n     * This method tries to do one step with step size dt. If the error estimate\n     * is to large, the step is rejected and the method returns fail and the\n     * step size dt is reduced. If the error estimate is acceptably small, the\n     * step is performed, success is returned and dt might be increased to make\n     * the steps as large as possible. This method also updates t if a step is\n     * performed.\n     *\n     * \\param system The system function to solve, hence the r.h.s. of the ODE. It must fulfill the\n     *               Simple System concept.\n     * \\param in The state of the ODE which should be solved.\n     * \\param t The value of the time. Updated if the step is successful.\n     * \\param out Used to store the result of the step.\n     * \\param dt The step size. Updated.\n     * \\return success if the step was accepted, fail otherwise.\n     */\n    template< class System , class StateIn , class StateOut >\n    typename boost::disable_if< boost::is_same< StateIn , time_type > , controlled_step_result >::type\n    try_step( System system , const StateIn &in , time_type &t , StateOut &out , time_type &dt )\n    {\n        typename odeint::unwrap_reference< System >::type &sys = system;\n        m_dxdt_resizer.adjust_size( in , detail::bind( &controlled_runge_kutta::template resize_m_dxdt_impl< StateIn > , detail::ref( *this ) , detail::_1 ) );\n        sys( in , m_dxdt.m_v , t );\n        return try_step( system , in , m_dxdt.m_v , t , out , dt );\n    }\n\n\n    /*\n     * Version 4 : try_step( sys , in , dxdt , t , out , dt )\n     *\n     * this version does not solve the forwarding problem, boost.range can not be used\n     */\n    /**\n     * \\brief Tries to perform one step.\n     *\n     * This method tries to do one step with step size dt. If the error estimate\n     * is to large, the step is rejected and the method returns fail and the\n     * step size dt is reduced. If the error estimate is acceptably small, the\n     * step is performed, success is returned and dt might be increased to make\n     * the steps as large as possible. This method also updates t if a step is\n     * performed.\n     *\n     * \\param system The system function to solve, hence the r.h.s. of the ODE. It must fulfill the\n     *               Simple System concept.\n     * \\param in The state of the ODE which should be solved.\n     * \\param dxdt The derivative of state.\n     * \\param t The value of the time. Updated if the step is successful.\n     * \\param out Used to store the result of the step.\n     * \\param dt The step size. Updated.\n     * \\return success if the step was accepted, fail otherwise.\n     */\n    template< class System , class StateIn , class DerivIn , class StateOut >\n    controlled_step_result try_step( System system , const StateIn &in , const DerivIn &dxdt , time_type &t , StateOut &out , time_type &dt )\n    {\n        if( !m_step_adjuster.check_step_size_limit(dt) )\n        {\n            // given dt was above step size limit - adjust and return fail;\n            dt = m_step_adjuster.get_max_dt();\n            return fail;\n        }\n\n        m_xerr_resizer.adjust_size( in , detail::bind( &controlled_runge_kutta::template resize_m_xerr_impl< StateIn > , detail::ref( *this ) , detail::_1 ) );\n\n        // do one step with error calculation\n        m_stepper.do_step( system , in , dxdt , t , out , dt , m_xerr.m_v );\n\n        value_type max_rel_err = m_error_checker.error( m_stepper.algebra() , in , dxdt , m_xerr.m_v , dt );\n\n        if( max_rel_err > 1.0 )\n        {\n            // error too big, decrease step size and reject this step\n            dt = m_step_adjuster.decrease_step(dt, max_rel_err, m_stepper.error_order());\n            return fail;\n        } else\n        {\n            // otherwise, increase step size and accept\n            t += dt;\n            dt = m_step_adjuster.increase_step(dt, max_rel_err, m_stepper.stepper_order());\n            return success;\n        }\n    }\n\n    /**\n     * \\brief Adjust the size of all temporaries in the stepper manually.\n     * \\param x A state from which the size of the temporaries to be resized is deduced.\n     */\n    template< class StateType >\n    void adjust_size( const StateType &x )\n    {\n        resize_m_xerr_impl( x );\n        resize_m_dxdt_impl( x );\n        resize_m_xnew_impl( x );\n        m_stepper.adjust_size( x );\n    }\n\n    /**\n     * \\brief Returns the instance of the underlying stepper.\n     * \\returns The instance of the underlying stepper.\n     */\n    stepper_type& stepper( void )\n    {\n        return m_stepper;\n    }\n\n    /**\n     * \\brief Returns the instance of the underlying stepper.\n     * \\returns The instance of the underlying stepper.\n     */\n    const stepper_type& stepper( void ) const\n    {\n        return m_stepper;\n    }\n\nprivate:\n\n\n    template< class System , class StateInOut >\n    controlled_step_result try_step_v1( System system , StateInOut &x , time_type &t , time_type &dt )\n    {\n        typename odeint::unwrap_reference< System >::type &sys = system;\n        m_dxdt_resizer.adjust_size( x , detail::bind( &controlled_runge_kutta::template resize_m_dxdt_impl< StateInOut > , detail::ref( *this ) , detail::_1 ) );\n        sys( x , m_dxdt.m_v ,t );\n        return try_step( system , x , m_dxdt.m_v , t , dt );\n    }\n\n    template< class StateIn >\n    bool resize_m_xerr_impl( const StateIn &x )\n    {\n        return adjust_size_by_resizeability( m_xerr , x , typename is_resizeable<state_type>::type() );\n    }\n\n    template< class StateIn >\n    bool resize_m_dxdt_impl( const StateIn &x )\n    {\n        return adjust_size_by_resizeability( m_dxdt , x , typename is_resizeable<deriv_type>::type() );\n    }\n\n    template< class StateIn >\n    bool resize_m_xnew_impl( const StateIn &x )\n    {\n        return adjust_size_by_resizeability( m_xnew , x , typename is_resizeable<state_type>::type() );\n    }\n\n\n\n    stepper_type m_stepper;\n    error_checker_type m_error_checker;\n    step_adjuster_type m_step_adjuster;\n\n    resizer_type m_dxdt_resizer;\n    resizer_type m_xerr_resizer;\n    resizer_type m_xnew_resizer;\n\n    wrapped_deriv_type m_dxdt;\n    wrapped_state_type m_xerr;\n    wrapped_state_type m_xnew;\n};\n\n\n\n\n\n\n\n\n\n\n/*\n * explicit stepper fsal version\n *\n * the class introduces the following try_step overloads\n    * try_step( sys , x , t , dt )\n    * try_step( sys , in , t , out , dt )\n    * try_step( sys , x , dxdt , t , dt )\n    * try_step( sys , in , dxdt_in , t , out , dxdt_out , dt )\n */\n/**\n * \\brief Implements step size control for Runge-Kutta FSAL steppers with\n * error estimation.\n *\n * This class implements the step size control for FSAL Runge-Kutta\n * steppers with error estimation.\n *\n * \\tparam ErrorStepper The stepper type with error estimation, has to fulfill the ErrorStepper concept.\n * \\tparam ErrorChecker The error checker\n * \\tparam Resizer The resizer policy type.\n */\ntemplate<\nclass ErrorStepper ,\nclass ErrorChecker ,\nclass StepAdjuster ,\nclass Resizer\n>\nclass controlled_runge_kutta< ErrorStepper , ErrorChecker , StepAdjuster , Resizer , explicit_error_stepper_fsal_tag >\n{\n\npublic:\n\n    typedef ErrorStepper stepper_type;\n    typedef typename stepper_type::state_type state_type;\n    typedef typename stepper_type::value_type value_type;\n    typedef typename stepper_type::deriv_type deriv_type;\n    typedef typename stepper_type::time_type time_type;\n    typedef typename stepper_type::algebra_type algebra_type;\n    typedef typename stepper_type::operations_type operations_type;\n    typedef Resizer resizer_type;\n    typedef ErrorChecker error_checker_type;\n    typedef StepAdjuster step_adjuster_type;\n    typedef explicit_controlled_stepper_fsal_tag stepper_category;\n\n#ifndef DOXYGEN_SKIP\n    typedef typename stepper_type::wrapped_state_type wrapped_state_type;\n    typedef typename stepper_type::wrapped_deriv_type wrapped_deriv_type;\n\n    typedef controlled_runge_kutta< ErrorStepper , ErrorChecker , StepAdjuster , Resizer , explicit_error_stepper_tag > controlled_stepper_type;\n#endif // DOXYGEN_SKIP\n\n    /**\n     * \\brief Constructs the controlled Runge-Kutta stepper.\n     * \\param error_checker An instance of the error checker.\n     * \\param stepper An instance of the underlying stepper.\n     */\n    controlled_runge_kutta(\n            const error_checker_type &error_checker = error_checker_type() ,\n            const step_adjuster_type &step_adjuster = step_adjuster_type() ,\n            const stepper_type &stepper = stepper_type()\n    )\n    : m_stepper( stepper ) , m_error_checker( error_checker ) , m_step_adjuster(step_adjuster) ,\n      m_first_call( true )\n    { }\n\n    /*\n     * Version 1 : try_step( sys , x , t , dt )\n     *\n     * The two overloads are needed in order to solve the forwarding problem\n     */\n    /**\n     * \\brief Tries to perform one step.\n     *\n     * This method tries to do one step with step size dt. If the error estimate\n     * is to large, the step is rejected and the method returns fail and the\n     * step size dt is reduced. If the error estimate is acceptably small, the\n     * step is performed, success is returned and dt might be increased to make\n     * the steps as large as possible. This method also updates t if a step is\n     * performed.\n     *\n     * \\param system The system function to solve, hence the r.h.s. of the ODE. It must fulfill the\n     *               Simple System concept.\n     * \\param x The state of the ODE which should be solved. Overwritten if\n     * the step is successful.\n     * \\param t The value of the time. Updated if the step is successful.\n     * \\param dt The step size. Updated.\n     * \\return success if the step was accepted, fail otherwise.\n     */\n    template< class System , class StateInOut >\n    controlled_step_result try_step( System system , StateInOut &x , time_type &t , time_type &dt )\n    {\n        return try_step_v1( system , x , t , dt );\n    }\n\n\n    /**\n     * \\brief Tries to perform one step. Solves the forwarding problem and\n     * allows for using boost range as state_type.\n     *\n     * This method tries to do one step with step size dt. If the error estimate\n     * is to large, the step is rejected and the method returns fail and the\n     * step size dt is reduced. If the error estimate is acceptably small, the\n     * step is performed, success is returned and dt might be increased to make\n     * the steps as large as possible. This method also updates t if a step is\n     * performed.\n     *\n     * \\param system The system function to solve, hence the r.h.s. of the ODE. It must fulfill the\n     *               Simple System concept.\n     * \\param x The state of the ODE which should be solved. Overwritten if\n     * the step is successful. Can be a boost range.\n     * \\param t The value of the time. Updated if the step is successful.\n     * \\param dt The step size. Updated.\n     * \\return success if the step was accepted, fail otherwise.\n     */\n    template< class System , class StateInOut >\n    controlled_step_result try_step( System system , const StateInOut &x , time_type &t , time_type &dt )\n    {\n        return try_step_v1( system , x , t , dt );\n    }\n\n\n\n    /*\n     * Version 2 : try_step( sys , in , t , out , dt );\n     *\n     * This version does not solve the forwarding problem, boost::range can not be used.\n     *\n     * The disabler is needed to solve ambiguous overloads\n     */\n    /**\n     * \\brief Tries to perform one step.\n     *\n     * \\note This method is disabled if state_type=time_type to avoid ambiguity.\n     *\n     * This method tries to do one step with step size dt. If the error estimate\n     * is to large, the step is rejected and the method returns fail and the\n     * step size dt is reduced. If the error estimate is acceptably small, the\n     * step is performed, success is returned and dt might be increased to make\n     * the steps as large as possible. This method also updates t if a step is\n     * performed.\n     *\n     * \\param system The system function to solve, hence the r.h.s. of the ODE. It must fulfill the\n     *               Simple System concept.\n     * \\param in The state of the ODE which should be solved.\n     * \\param t The value of the time. Updated if the step is successful.\n     * \\param out Used to store the result of the step.\n     * \\param dt The step size. Updated.\n     * \\return success if the step was accepted, fail otherwise.\n     */\n    template< class System , class StateIn , class StateOut >\n    typename boost::disable_if< boost::is_same< StateIn , time_type > , controlled_step_result >::type\n    try_step( System system , const StateIn &in , time_type &t , StateOut &out , time_type &dt )\n    {\n        if( m_dxdt_resizer.adjust_size( in , detail::bind( &controlled_runge_kutta::template resize_m_dxdt_impl< StateIn > , detail::ref( *this ) , detail::_1 ) ) || m_first_call )\n        {\n            initialize( system , in , t );\n        }\n        return try_step( system , in , m_dxdt.m_v , t , out , dt );\n    }\n\n\n    /*\n     * Version 3 : try_step( sys , x , dxdt , t , dt )\n     *\n     * This version does not solve the forwarding problem, boost::range can not be used.\n     */\n    /**\n     * \\brief Tries to perform one step.\n     *\n     * This method tries to do one step with step size dt. If the error estimate\n     * is to large, the step is rejected and the method returns fail and the\n     * step size dt is reduced. If the error estimate is acceptably small, the\n     * step is performed, success is returned and dt might be increased to make\n     * the steps as large as possible. This method also updates t if a step is\n     * performed.\n     *\n     * \\param system The system function to solve, hence the r.h.s. of the ODE. It must fulfill the\n     *               Simple System concept.\n     * \\param x The state of the ODE which should be solved. Overwritten if\n     * the step is successful.\n     * \\param dxdt The derivative of state.\n     * \\param t The value of the time. Updated if the step is successful.\n     * \\param dt The step size. Updated.\n     * \\return success if the step was accepted, fail otherwise.\n     */\n    template< class System , class StateInOut , class DerivInOut >\n    controlled_step_result try_step( System system , StateInOut &x , DerivInOut &dxdt , time_type &t , time_type &dt )\n    {\n        m_xnew_resizer.adjust_size( x , detail::bind( &controlled_runge_kutta::template resize_m_xnew_impl< StateInOut > , detail::ref( *this ) , detail::_1 ) );\n        m_dxdt_new_resizer.adjust_size( x , detail::bind( &controlled_runge_kutta::template resize_m_dxdt_new_impl< StateInOut > , detail::ref( *this ) , detail::_1 ) );\n        controlled_step_result res = try_step( system , x , dxdt , t , m_xnew.m_v , m_dxdtnew.m_v , dt );\n        if( res == success )\n        {\n            boost::numeric::odeint::copy( m_xnew.m_v , x );\n            boost::numeric::odeint::copy( m_dxdtnew.m_v , dxdt );\n        }\n        return res;\n    }\n\n\n    /*\n     * Version 4 : try_step( sys , in , dxdt_in , t , out , dxdt_out , dt )\n     *\n     * This version does not solve the forwarding problem, boost::range can not be used.\n     */\n    /**\n     * \\brief Tries to perform one step.\n     *\n     * This method tries to do one step with step size dt. If the error estimate\n     * is to large, the step is rejected and the method returns fail and the\n     * step size dt is reduced. If the error estimate is acceptably small, the\n     * step is performed, success is returned and dt might be increased to make\n     * the steps as large as possible. This method also updates t if a step is\n     * performed.\n     *\n     * \\param system The system function to solve, hence the r.h.s. of the ODE. It must fulfill the\n     *               Simple System concept.\n     * \\param in The state of the ODE which should be solved.\n     * \\param dxdt The derivative of state.\n     * \\param t The value of the time. Updated if the step is successful.\n     * \\param out Used to store the result of the step.\n     * \\param dt The step size. Updated.\n     * \\return success if the step was accepted, fail otherwise.\n     */\n    template< class System , class StateIn , class DerivIn , class StateOut , class DerivOut >\n    controlled_step_result try_step( System system , const StateIn &in , const DerivIn &dxdt_in , time_type &t ,\n            StateOut &out , DerivOut &dxdt_out , time_type &dt )\n    {\n        if( !m_step_adjuster.check_step_size_limit(dt) )\n        {\n            // given dt was above step size limit - adjust and return fail;\n            dt = m_step_adjuster.get_max_dt();\n            return fail;\n        }\n\n        m_xerr_resizer.adjust_size( in , detail::bind( &controlled_runge_kutta::template resize_m_xerr_impl< StateIn > , detail::ref( *this ) , detail::_1 ) );\n\n        //fsal: m_stepper.get_dxdt( dxdt );\n        //fsal: m_stepper.do_step( sys , x , dxdt , t , dt , m_x_err );\n        m_stepper.do_step( system , in , dxdt_in , t , out , dxdt_out , dt , m_xerr.m_v );\n\n        // this potentially overwrites m_x_err! (standard_error_checker does, at least)\n        value_type max_rel_err = m_error_checker.error( m_stepper.algebra() , in , dxdt_in , m_xerr.m_v , dt );\n\n        if( max_rel_err > 1.0 )\n        {\n            // error too big, decrease step size and reject this step\n            dt = m_step_adjuster.decrease_step(dt, max_rel_err, m_stepper.error_order());\n            return fail;\n        }\n        // otherwise, increase step size and accept\n        t += dt;\n        dt = m_step_adjuster.increase_step(dt, max_rel_err, m_stepper.stepper_order());\n        return success;\n    }\n\n\n    /**\n     * \\brief Resets the internal state of the underlying FSAL stepper.\n     */\n    void reset( void )\n    {\n        m_first_call = true;\n    }\n\n    /**\n     * \\brief Initializes the internal state storing an internal copy of the derivative.\n     *\n     * \\param deriv The initial derivative of the ODE.\n     */\n    template< class DerivIn >\n    void initialize( const DerivIn &deriv )\n    {\n        boost::numeric::odeint::copy( deriv , m_dxdt.m_v );\n        m_first_call = false;\n    }\n\n    /**\n     * \\brief Initializes the internal state storing an internal copy of the derivative.\n     *\n     * \\param system The system function to solve, hence the r.h.s. of the ODE. It must fulfill the\n     *               Simple System concept.\n     * \\param x The initial state of the ODE which should be solved.\n     * \\param t The initial time.\n     */\n    template< class System , class StateIn >\n    void initialize( System system , const StateIn &x , time_type t )\n    {\n        typename odeint::unwrap_reference< System >::type &sys = system;\n        sys( x , m_dxdt.m_v , t );\n        m_first_call = false;\n    }\n\n    /**\n     * \\brief Returns true if the stepper has been initialized, false otherwise.\n     *\n     * \\return true, if the stepper has been initialized, false otherwise.\n     */\n    bool is_initialized( void ) const\n    {\n        return ! m_first_call;\n    }\n\n\n    /**\n     * \\brief Adjust the size of all temporaries in the stepper manually.\n     * \\param x A state from which the size of the temporaries to be resized is deduced.\n     */\n    template< class StateType >\n    void adjust_size( const StateType &x )\n    {\n        resize_m_xerr_impl( x );\n        resize_m_dxdt_impl( x );\n        resize_m_dxdt_new_impl( x );\n        resize_m_xnew_impl( x );\n    }\n\n\n    /**\n     * \\brief Returns the instance of the underlying stepper.\n     * \\returns The instance of the underlying stepper.\n     */\n    stepper_type& stepper( void )\n    {\n        return m_stepper;\n    }\n\n    /**\n     * \\brief Returns the instance of the underlying stepper.\n     * \\returns The instance of the underlying stepper.\n     */\n    const stepper_type& stepper( void ) const\n    {\n        return m_stepper;\n    }\n\n\n\nprivate:\n\n\n    template< class StateIn >\n    bool resize_m_xerr_impl( const StateIn &x )\n    {\n        return adjust_size_by_resizeability( m_xerr , x , typename is_resizeable<state_type>::type() );\n    }\n\n    template< class StateIn >\n    bool resize_m_dxdt_impl( const StateIn &x )\n    {\n        return adjust_size_by_resizeability( m_dxdt , x , typename is_resizeable<deriv_type>::type() );\n    }\n\n    template< class StateIn >\n    bool resize_m_dxdt_new_impl( const StateIn &x )\n    {\n        return adjust_size_by_resizeability( m_dxdtnew , x , typename is_resizeable<deriv_type>::type() );\n    }\n\n    template< class StateIn >\n    bool resize_m_xnew_impl( const StateIn &x )\n    {\n        return adjust_size_by_resizeability( m_xnew , x , typename is_resizeable<state_type>::type() );\n    }\n\n\n    template< class System , class StateInOut >\n    controlled_step_result try_step_v1( System system , StateInOut &x , time_type &t , time_type &dt )\n    {\n        if( m_dxdt_resizer.adjust_size( x , detail::bind( &controlled_runge_kutta::template resize_m_dxdt_impl< StateInOut > , detail::ref( *this ) , detail::_1 ) ) || m_first_call )\n        {\n            initialize( system , x , t );\n        }\n        return try_step( system , x , m_dxdt.m_v , t , dt );\n    }\n\n\n    stepper_type m_stepper;\n    error_checker_type m_error_checker;\n    step_adjuster_type m_step_adjuster;\n\n    resizer_type m_dxdt_resizer;\n    resizer_type m_xerr_resizer;\n    resizer_type m_xnew_resizer;\n    resizer_type m_dxdt_new_resizer;\n\n    wrapped_deriv_type m_dxdt;\n    wrapped_state_type m_xerr;\n    wrapped_state_type m_xnew;\n    wrapped_deriv_type m_dxdtnew;\n    bool m_first_call;\n};\n\n\n/********** DOXYGEN **********/\n\n/**** DEFAULT ERROR CHECKER ****/\n\n/**\n * \\class default_error_checker\n * \\brief The default error checker to be used with Runge-Kutta error steppers\n *\n * This class provides the default mechanism to compare the error estimates\n * reported by Runge-Kutta error steppers with user defined error bounds.\n * It is used by the controlled_runge_kutta steppers.\n *\n * \\tparam Value The value type.\n * \\tparam Time The time type.\n * \\tparam Algebra The algebra type.\n * \\tparam Operations The operations type.\n */\n\n    /**\n     * \\fn default_error_checker( value_type eps_abs , value_type eps_rel , value_type a_x , value_type a_dxdt ,\n     * time_type max_dt)\n     * \\brief Constructs the error checker.\n     *\n     * The error is calculated as follows: ????\n     *\n     * \\param eps_abs Absolute tolerance level.\n     * \\param eps_rel Relative tolerance level.\n     * \\param a_x Factor for the weight of the state.\n     * \\param a_dxdt Factor for the weight of the derivative.\n     * \\param max_dt Maximum allowed step size.\n     */\n\n    /**\n     * \\fn error( const State &x_old , const Deriv &dxdt_old , Err &x_err , time_type dt ) const\n     * \\brief Calculates the error level.\n     *\n     * If the returned error level is greater than 1, the estimated error was\n     * larger than the permitted error bounds and the step should be repeated\n     * with a smaller step size.\n     *\n     * \\param x_old State at the beginning of the step.\n     * \\param dxdt_old Derivative at the beginning of the step.\n     * \\param x_err Error estimate.\n     * \\param dt Time step.\n     * \\return error\n     */\n\n    /**\n     * \\fn error( algebra_type &algebra , const State &x_old , const Deriv &dxdt_old , Err &x_err , time_type dt ) const\n     * \\brief Calculates the error level using a given algebra.\n     *\n     * If the returned error level is greater than 1, the estimated error was\n     * larger than the permitted error bounds and the step should be repeated\n     * with a smaller step size.\n     *\n     * \\param algebra The algebra used for calculation of the error.\n     * \\param x_old State at the beginning of the step.\n     * \\param dxdt_old Derivative at the beginning of the step.\n     * \\param x_err Error estimate.\n     * \\param dt Time step.\n     * \\return error\n     */\n\n    /**\n     * \\fn time_type decrease_step(const time_type dt, const value_type error, const int error_order)\n     * \\brief Returns a decreased step size based on the given error and order\n     *\n     * Calculates a new smaller step size based on the given error and its order.\n     *\n     * \\param dt The old step size.\n     * \\param error The computed error estimate.\n     * \\param error_order The error order of the stepper.\n     * \\return dt_new The new, reduced step size.\n     */\n\n    /**\n     * \\fn time_type increase_step(const time_type dt, const value_type error, const int error_order)\n     * \\brief Returns an increased step size based on the given error and order.\n     *\n     * Calculates a new bigger step size based on the given error and its order. If max_dt != 0, the\n     * new step size is limited to max_dt.\n     *\n     * \\param dt The old step size.\n     * \\param error The computed error estimate.\n     * \\param error_order The order of the stepper.\n     * \\return dt_new The new, increased step size.\n     */\n\n\n} // odeint\n} // numeric\n} // boost\n\n\n#endif // BOOST_NUMERIC_ODEINT_STEPPER_CONTROLLED_RUNGE_KUTTA_HPP_INCLUDED\n", "meta": {"hexsha": "b8bfd9c6d52bdf21c239dd1f51ae3eb2e6ca15d5", "size": 37959, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/numeric/odeint/stepper/controlled_runge_kutta.hpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "deps/src/boost_1_65_1/boost/numeric/odeint/stepper/controlled_runge_kutta.hpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "deps/src/boost_1_65_1/boost/numeric/odeint/stepper/controlled_runge_kutta.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": 37.3980295567, "max_line_length": 182, "alphanum_fraction": 0.6640322453, "num_tokens": 9271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.2883740644816865}}
{"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_CENTROID_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_CENTROID_HPP\n\n\n#include <cstddef>\n\n#include <boost/range.hpp>\n#include <boost/typeof/typeof.hpp>\n\n#include <boost/geometry/core/closure.hpp>\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/core/coordinate_dimension.hpp>\n#include <boost/geometry/core/exception.hpp>\n#include <boost/geometry/core/exterior_ring.hpp>\n#include <boost/geometry/core/interior_rings.hpp>\n#include <boost/geometry/core/tag_cast.hpp>\n\n#include <boost/geometry/algorithms/convert.hpp>\n#include <boost/geometry/algorithms/distance.hpp>\n#include <boost/geometry/algorithms/not_implemented.hpp>\n#include <boost/geometry/geometries/concepts/check.hpp>\n#include <boost/geometry/strategies/centroid.hpp>\n#include <boost/geometry/strategies/concepts/centroid_concept.hpp>\n#include <boost/geometry/views/closeable_view.hpp>\n\n#include <boost/geometry/util/for_each_coordinate.hpp>\n#include <boost/geometry/util/select_coordinate_type.hpp>\n\n\n\nnamespace boost { namespace geometry\n{\n\n\n#if ! defined(BOOST_GEOMETRY_CENTROID_NO_THROW)\n\n/*!\n\\brief Centroid Exception\n\\ingroup centroid\n\\details The centroid_exception is thrown if the free centroid function is called with\n    geometries for which the centroid cannot be calculated. For example: a linestring\n    without points, a polygon without points, an empty multi-geometry.\n\\qbk{\n[heading See also]\n\\* [link geometry.reference.algorithms.centroid the centroid function]\n}\n\n */\nclass centroid_exception : public geometry::exception\n{\npublic:\n\n    inline centroid_exception() {}\n\n    virtual char const* what() const throw()\n    {\n        return \"Boost.Geometry Centroid calculation exception\";\n    }\n};\n\n#endif\n\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace centroid\n{\n\nstruct centroid_point\n{\n    template<typename Point, typename PointCentroid, typename Strategy>\n    static inline void apply(Point const& point, PointCentroid& centroid,\n            Strategy const&)\n    {\n        geometry::convert(point, centroid);\n    }\n};\n\ntemplate\n<\n    typename Indexed,\n    typename Point,\n    std::size_t Dimension,\n    std::size_t DimensionCount\n>\nstruct centroid_indexed_calculator\n{\n    typedef typename select_coordinate_type\n        <\n            Indexed, Point\n        >::type coordinate_type;\n    static inline void apply(Indexed const& indexed, Point& centroid)\n    {\n        coordinate_type const c1 = get<min_corner, Dimension>(indexed);\n        coordinate_type const c2 = get<max_corner, Dimension>(indexed);\n        coordinate_type m = c1 + c2;\n        coordinate_type const two = 2;\n        m /= two;\n\n        set<Dimension>(centroid, m);\n\n        centroid_indexed_calculator\n            <\n                Indexed, Point,\n                Dimension + 1, DimensionCount\n            >::apply(indexed, centroid);\n    }\n};\n\n\ntemplate<typename Indexed, typename Point, std::size_t DimensionCount>\nstruct centroid_indexed_calculator<Indexed, Point, DimensionCount, DimensionCount>\n{\n    static inline void apply(Indexed const& , Point& )\n    {\n    }\n};\n\n\nstruct centroid_indexed\n{\n    template<typename Indexed, typename Point, typename Strategy>\n    static inline void apply(Indexed const& indexed, Point& centroid,\n            Strategy const&)\n    {\n        centroid_indexed_calculator\n            <\n                Indexed, Point,\n                0, dimension<Indexed>::type::value\n            >::apply(indexed, centroid);\n    }\n};\n\n\n// There is one thing where centroid is different from e.g. within.\n// If the ring has only one point, it might make sense that\n// that point is the centroid.\ntemplate<typename Point, typename Range>\ninline bool range_ok(Range const& range, Point& centroid)\n{\n    std::size_t const n = boost::size(range);\n    if (n > 1)\n    {\n        return true;\n    }\n    else if (n <= 0)\n    {\n#if ! defined(BOOST_GEOMETRY_CENTROID_NO_THROW)\n        throw centroid_exception();\n#endif\n        return false;\n    }\n    else // if (n == 1)\n    {\n        // Take over the first point in a \"coordinate neutral way\"\n        geometry::convert(*boost::begin(range), centroid);\n        return false;\n    }\n    return true;\n}\n\n\n/*!\n    \\brief Calculate the centroid of a ring.\n*/\ntemplate <closure_selector Closure>\nstruct centroid_range_state\n{\n    template<typename Ring, typename Strategy>\n    static inline void apply(Ring const& ring,\n            Strategy const& strategy, typename Strategy::state_type& state)\n    {\n        typedef typename closeable_view<Ring const, Closure>::type view_type;\n\n        typedef typename boost::range_iterator<view_type const>::type iterator_type;\n\n        view_type view(ring);\n        iterator_type it = boost::begin(view);\n        iterator_type end = boost::end(view);\n\n        for (iterator_type previous = it++;\n            it != end;\n            ++previous, ++it)\n        {\n            strategy.apply(*previous, *it, state);\n        }\n    }\n};\n\ntemplate <closure_selector Closure>\nstruct centroid_range\n{\n    template<typename Range, typename Point, typename Strategy>\n    static inline void apply(Range const& range, Point& centroid,\n            Strategy const& strategy)\n    {\n        if (range_ok(range, centroid))\n        {\n            typename Strategy::state_type state;\n            centroid_range_state<Closure>::apply(range, strategy, state);\n            strategy.result(state, centroid);\n        }\n    }\n};\n\n\n/*!\n    \\brief Centroid of a polygon.\n    \\note Because outer ring is clockwise, inners are counter clockwise,\n    triangle approach is OK and works for polygons with rings.\n*/\nstruct centroid_polygon_state\n{\n    template<typename Polygon, typename Strategy>\n    static inline void apply(Polygon const& poly,\n            Strategy const& strategy, typename Strategy::state_type& state)\n    {\n        typedef typename ring_type<Polygon>::type ring_type;\n        typedef centroid_range_state<geometry::closure<ring_type>::value> per_ring;\n\n        per_ring::apply(exterior_ring(poly), strategy, state);\n\n        typename interior_return_type<Polygon const>::type rings\n                    = interior_rings(poly);\n        for (BOOST_AUTO_TPL(it, boost::begin(rings)); it != boost::end(rings); ++it)\n        {\n            per_ring::apply(*it, strategy, state);\n        }\n    }\n};\n\nstruct centroid_polygon\n{\n    template<typename Polygon, typename Point, typename Strategy>\n    static inline void apply(Polygon const& poly, Point& centroid,\n            Strategy const& strategy)\n    {\n        if (range_ok(exterior_ring(poly), centroid))\n        {\n            typename Strategy::state_type state;\n            centroid_polygon_state::apply(poly, strategy, state);\n            strategy.result(state, centroid);\n        }\n    }\n};\n\n\n}} // namespace detail::centroid\n#endif // DOXYGEN_NO_DETAIL\n\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\ntemplate\n<\n    typename Geometry,\n    typename Tag = typename tag<Geometry>::type\n>\nstruct centroid: not_implemented<Tag>\n{};\n\ntemplate <typename Geometry>\nstruct centroid<Geometry, point_tag>\n    : detail::centroid::centroid_point\n{};\n\ntemplate <typename Box>\nstruct centroid<Box, box_tag>\n    : detail::centroid::centroid_indexed\n{};\n\ntemplate <typename Segment>\nstruct centroid<Segment, segment_tag>\n    : detail::centroid::centroid_indexed\n{};\n\ntemplate <typename Ring>\nstruct centroid<Ring, ring_tag>\n    : detail::centroid::centroid_range<geometry::closure<Ring>::value>\n{};\n\ntemplate <typename Linestring>\nstruct centroid<Linestring, linestring_tag>\n    : detail::centroid::centroid_range<closed>\n {};\n\ntemplate <typename Polygon>\nstruct centroid<Polygon, polygon_tag>\n    : detail::centroid::centroid_polygon\n {};\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\n/*!\n\\brief \\brief_calc{centroid} \\brief_strategy\n\\ingroup centroid\n\\details \\details_calc{centroid,geometric center (or: center of mass)}. \\details_strategy_reasons\n\\tparam Geometry \\tparam_geometry\n\\tparam Point \\tparam_point\n\\tparam Strategy \\tparam_strategy{Centroid}\n\\param geometry \\param_geometry\n\\param c \\param_point \\param_set{centroid}\n\\param strategy \\param_strategy{centroid}\n\n\\qbk{distinguish,with strategy}\n\\qbk{[include reference/algorithms/centroid.qbk]}\n\\qbk{[include reference/algorithms/centroid_strategies.qbk]}\n}\n\n*/\ntemplate<typename Geometry, typename Point, typename Strategy>\ninline void centroid(Geometry const& geometry, Point& c,\n        Strategy const& strategy)\n{\n    //BOOST_CONCEPT_ASSERT( (geometry::concept::CentroidStrategy<Strategy>) );\n\n    concept::check_concepts_and_equal_dimensions<Point, Geometry const>();\n\n    typedef typename point_type<Geometry>::type point_type;\n\n    // Call dispatch apply method. That one returns true if centroid\n    // should be taken from state.\n    dispatch::centroid<Geometry>::apply(geometry, c, strategy);\n}\n\n\n/*!\n\\brief \\brief_calc{centroid}\n\\ingroup centroid\n\\details \\details_calc{centroid,geometric center (or: center of mass)}. \\details_default_strategy\n\\tparam Geometry \\tparam_geometry\n\\tparam Point \\tparam_point\n\\param geometry \\param_geometry\n\\param c The calculated centroid will be assigned to this point reference\n\n\\qbk{[include reference/algorithms/centroid.qbk]}\n\\qbk{\n[heading Example]\n[centroid]\n[centroid_output]\n}\n */\ntemplate<typename Geometry, typename Point>\ninline void centroid(Geometry const& geometry, Point& c)\n{\n    concept::check_concepts_and_equal_dimensions<Point, Geometry const>();\n\n    typedef typename strategy::centroid::services::default_strategy\n        <\n            typename cs_tag<Geometry>::type,\n            typename tag_cast\n                <\n                    typename tag<Geometry>::type,\n                    pointlike_tag,\n                    linear_tag,\n                    areal_tag\n                >::type,\n            dimension<Geometry>::type::value,\n            Point,\n            Geometry\n        >::type strategy_type;\n\n    centroid(geometry, c, strategy_type());\n}\n\n\n/*!\n\\brief \\brief_calc{centroid}\n\\ingroup centroid\n\\details \\details_calc{centroid,geometric center (or: center of mass)}. \\details_return{centroid}.\n\\tparam Point \\tparam_point\n\\tparam Geometry \\tparam_geometry\n\\param geometry \\param_geometry\n\\return \\return_calc{centroid}\n\n\\qbk{[include reference/algorithms/centroid.qbk]}\n */\ntemplate<typename Point, typename Geometry>\ninline Point return_centroid(Geometry const& geometry)\n{\n    concept::check_concepts_and_equal_dimensions<Point, Geometry const>();\n\n    Point c;\n    centroid(geometry, c);\n    return c;\n}\n\n/*!\n\\brief \\brief_calc{centroid} \\brief_strategy\n\\ingroup centroid\n\\details \\details_calc{centroid,geometric center (or: center of mass)}. \\details_return{centroid}. \\details_strategy_reasons\n\\tparam Point \\tparam_point\n\\tparam Geometry \\tparam_geometry\n\\tparam Strategy \\tparam_strategy{centroid}\n\\param geometry \\param_geometry\n\\param strategy \\param_strategy{centroid}\n\\return \\return_calc{centroid}\n\n\\qbk{distinguish,with strategy}\n\\qbk{[include reference/algorithms/centroid.qbk]}\n\\qbk{[include reference/algorithms/centroid_strategies.qbk]}\n */\ntemplate<typename Point, typename Geometry, typename Strategy>\ninline Point return_centroid(Geometry const& geometry, Strategy const& strategy)\n{\n    //BOOST_CONCEPT_ASSERT( (geometry::concept::CentroidStrategy<Strategy>) );\n\n    concept::check_concepts_and_equal_dimensions<Point, Geometry const>();\n\n    Point c;\n    centroid(geometry, c, strategy);\n    return c;\n}\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_CENTROID_HPP\n", "meta": {"hexsha": "f673c133d39decf8ee0d5fd4e10be5e805c0b63c", "size": 12056, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "venv/bin/boost/geometry/algorithms/centroid.hpp", "max_stars_repo_name": "NixaSoftware/CVis", "max_stars_repo_head_hexsha": "076a36e1542036d3a8907b7d3b798ccd7e815675", "max_stars_repo_licenses": ["Apache-2.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": "venv/bin/boost/geometry/algorithms/centroid.hpp", "max_issues_repo_name": "NixaSoftware/CVis", "max_issues_repo_head_hexsha": "076a36e1542036d3a8907b7d3b798ccd7e815675", "max_issues_repo_licenses": ["Apache-2.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": "venv/bin/boost/geometry/algorithms/centroid.hpp", "max_forks_repo_name": "NixaSoftware/CVis", "max_forks_repo_head_hexsha": "076a36e1542036d3a8907b7d3b798ccd7e815675", "max_forks_repo_licenses": ["Apache-2.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": 27.6513761468, "max_line_length": 124, "alphanum_fraction": 0.7057067021, "num_tokens": 2643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.28837406448168645}}
{"text": "//\n// Created by Сергей Кривонос on 25.09.17.\n//\n#include \"Product.h\"\n\n#include \"Fraction.h\"\n#include \"Modulo.h\"\n#include \"Infinity.h\"\n#include \"Integer.h\"\n#include \"Sum.h\"\n#include \"e.h\"\n#include \"i.h\"\n#include \"pi.h\"\n#include <type_traits>\n#include <boost/multiprecision/cpp_int.hpp>\n\nnamespace omnn{\nnamespace math {\n    \n    using namespace std;\n    \n    type_index order[] = {\n        // for fast optimizing\n        typeid(NaN),\n        typeid(MInfinity),\n        typeid(Infinity),\n        typeid(Sum),\n        typeid(Product),\n        // general order\n        typeid(Integer),\n        typeid(MinusOneSq),\n        typeid(Euler),\n        typeid(Pi),\n        typeid(Fraction),\n        typeid(Exponentiation),\n        typeid(Variable),\n        typeid(Modulo),\n    };\n    \n    auto ob = std::begin(order);\n    auto oe = std::end(order);\n    \n    // inequality should cover all cases\n    bool ProductOrderComparator::operator()(const Valuable& x, const Valuable& y) const\n    {\n        auto it1 = std::find(ob, oe, x.Type());\n        if (it1==oe) IMPLEMENT\n\n        auto it2 = std::find(ob, oe, y.Type());\n        if (it2==oe) IMPLEMENT\n\n        return it1 == it2 ? x.IsComesBefore(y) : it1 < it2;\n    }\n    \n    Product::Product() : members{1}\n    {\n        hash = members.begin()->Hash();\n    }\n    \n    Product::Product(const std::initializer_list<Valuable>& l)\n    {\n        for (const auto& arg : l)\n        {\n            if (arg.IsProduct())\n                for (auto& m : arg.as<Product>().members)\n                    this->Add(m, end());\n            else\n                this->Add(arg, end());\n        }\n    }\n    \n    int Product::findMaxVaExp()\n    {\n        vaExpsSum = 0;\n        for (auto& i:vars) {\n            if (!i.second.IsInt()) {\n                IMPLEMENT;\n            }\n            vaExpsSum += i.second;\n        }\n        auto it = std::max_element(vars.begin(), vars.end(), [](auto& x, auto& y){\n            return x.second < y.second;\n        });\n        if (it != vars.end()) {\n            return static_cast<int>(it->second.as<Integer>());\n        }\n        return 0;\n    }\n\n    void Product::AddToVars(const Variable & va, const Valuable & exponentiation)\n    {\n        if (!exponentiation.IsInt()) {\n            std::cerr << va.str() << '^' << exponentiation.str() << std::endl;\n            IMPLEMENT // estimate in to be greater for those which you want to see first in sum sequence\n        }\n        if(exponentiation==0)\n            return;\n\n        auto& eai = exponentiation.as<Integer>();\n        vaExpsSum += eai;\n        \n        auto& e = vars[va];\n        if (!e.IsInt()) {\n            IMPLEMENT\n        }\n        auto wasMax = maxVaExp == max_exp_t(e.ca(), 1);\n        e += exponentiation;\n      \n        auto isMax = maxVaExp < e.ca();\n        if (isMax) {\n            maxVaExp = e.ca();\n        }\n        \n        if (e == 0) {\n            vars.erase(va);\n        }\n        \n        if (!isMax && wasMax) {\n            assert(eai < 0);\n            maxVaExp = findMaxVaExp();\n        }\n    }\n\n    void Product::AddToVarsIfVaOrVaExp(const Valuable &item)\n    {\n        if(item.IsVa())\n        {\n            AddToVars(item.as<Variable>(), 1_v);\n        }\n        else if (item.IsExponentiation())\n        {\n            auto& e = item.as<Exponentiation>();\n            auto& base = e.getBase();\n            if (base.IsVa())\n            {\n                AddToVars(base.as<Variable>(), e.getExponentiation());\n            }\n            else\n            {\n                auto itemMaxVaExp = item.getMaxVaExp();\n                if (itemMaxVaExp > maxVaExp) {\n                    maxVaExp = itemMaxVaExp;\n                }\n            }\n        }\n        else if (!item.IsSum() && item.FindVa())\n        {\n            IMPLEMENT\n        }\n    }\n    \n    Product::iterator Product::Had(iterator it)\n    {\n        hash ^= it->Hash();\n        AddToVarsIfVaOrVaExp(*it);\n        base::Update(it, *it ^ 2);\n        return it;\n    }\n    \n    const Product::iterator Product::Add(const Valuable& item, const iterator hint)\n    {\n        iterator it;\n        \n        if (members.size() == 1 && !item.IsSimple()) {\n            it = begin();\n            if (it->Same(1_v)) {\n                Delete(it);\n            }\n        }\n        \n        if (item.IsInt()) {\n            if (item == 1_v)\n                it = begin();\n            else if ((it = GetFirstOccurence<Integer>()) != end()\n                || ((it = GetFirstOccurence<Fraction>()) != end() && it->IsSimpleFraction())\n            ) {\n                Update(it, *it * item);\n            } else {\n                it = base::Add(item, hint);\n            }\n        } else if (item.IsSimpleFraction()) {\n            if ((it = GetFirstOccurence<Fraction>()) != end()\n                || (it = GetFirstOccurence<Integer>()) != end()\n            ) {\n                Update(it, item * *it);\n            } else {\n                it = base::Add(item, hint);\n            }\n        } else if (item.IsProduct()) {\n            it = hint;\n            for (auto& i : item.as<Product>()) {\n                it = Add(i, it);\n            }\n        } else if (item.IsFraction() && item.FindVa()) {\n            auto& f = item.as<Fraction>();\n            auto cmp = members.value_comp();\n            it = std::min(Add(f.getNumerator()),\n                          Add(f.getDenominator() ^ -1),\n                          [&](auto& _1, auto& _2){ return cmp(*_1, *_2); });\n        }\n        else\n        {\n            it = std::find(members.begin(), members.end(), item);\n            if(it==end()) {\n                it = base::Add(item, hint);\n                AddToVarsIfVaOrVaExp(item);\n            } else\n                Update(it, item.Sq());\n        }\n        return it;\n    }\n\n    void Product::Delete(typename cont::iterator& it)\n    {\n        std::function<void()> addToVars;\n        if(it->IsVa())\n        {\n            addToVars = std::bind(&Product::AddToVars, this, it->as<Variable>(), -1_v);\n        }\n        else if (it->IsExponentiation())\n        {\n            auto& e = it->as<Exponentiation>();\n            auto& ebase = e.getBase();\n            if (ebase.IsVa()) {\n                addToVars = std::bind(&Product::AddToVars, this, ebase.as<Variable>(), -e.getExponentiation());\n            }\n        }\n        \n        base::Delete(it);\n\n        if(addToVars)\n            addToVars();\n    }\n\n    void Product::optimize()\n    {\n        if (!optimizations || optimized)\n            return;\n        optimized = true;\n\n        // zero\n        auto it = GetFirstOccurence<Integer>();\n        if (it != end()) {\n            if (it->Same(0)) {\n                Become(0);\n                return;\n            }\n            \n        // one\n            if (it->Same(1) && size() > 1) {\n                Delete(it);\n            }\n        }\n\n        // fractionless\n        bool updated;\n        do {\n            updated = {};\n            for (auto it = GetFirstOccurence<Fraction>(); it != end(); ++it) {\n                if (it->IsFraction() && it->FindVa()) {\n                    auto& f = it->as<Fraction>();\n                    auto& dn = f.getDenominator();\n                    auto defract = dn.FindVa() ? (dn ^ (-1_v)) : 1_v / dn;\n                    auto& n = f.getNumerator();\n                    if(n==1_v)\n                    {\n                        Delete(it);\n                    }\n                    else\n                    {\n                        Update(it, n);\n                        OptimizeOff o;\n                        operator*=(defract);\n                    }\n                    updated = true;\n                }\n            }\n        } while (updated);\n\n        \n        // optimize members, if found a sum then become the sum multiplied by other members\n        for (auto it = members.begin(); it != members.end();)\n        {\n            if (it->IsSum())\n            {\n                auto sum = std::move(const_cast<Valuable&&>(*it));\n                sum.optimize();\n                Delete(it);\n//                auto was = optimizations;\n//                optimizations = false;\n                for (auto& it : members)\n                {\n                    sum *= it;\n                }\n//                optimizations = was;\n                Become(std::move(sum));\n                return;\n            }\n            auto c = *it;\n            c.optimize();\n            if (!it->Same(c)) {\n                Update(it, c);\n                continue;\n            }\n            else\n                ++it;\n        }\n        \n        // emerge inner products\n        for (auto it = members.begin(); it != members.end();)\n        {\n            if (it->IsProduct()) {\n                for (auto& m : it->as<Product>())\n                    Add(m);\n                Delete(it);\n            }\n            else\n                ++it;\n        }\n\n        do\n        {\n            updated = {};\n            for (auto it = members.begin(); it != members.end();)\n            {\n                if (members.size() == 1)\n                {\n                    Become(std::move(*const_cast<Valuable*>(&*it)));\n                    return;\n                }\n\n                if (*it == 1)\n                {\n                    Delete(it);\n                    continue;\n                }\n\n                if (*it == 0)\n                {\n                    Become(0);\n                    return;\n                }\n\n                auto c = *it;\n                auto it2 = it;\n                ++it2;\n                while (it2 != members.end())\n                {\n                    if (c.MultiplyIfSimplifiable(*it2)) {\n                        if (c.IsProduct()) {\n                            auto& cAsP = c.as<Product>();\n                            if(cAsP.size() == 2 && cAsP.begin()->IsSimple()) {\n                                break;\n                            } else {\n                                IMPLEMENT\n                            }\n                        }\n                        Delete(it2);\n                        continue;\n                    }\n                    else\n                        ++it2;\n                }\n\n                if (!it->Same(c)) {\n                    Update(it, c);\n                    updated = true;\n                } else {\n                    ++it;\n                }\n            }\n        } while (updated);\n        \n        // fraction optimizations\n        auto f = GetFirstOccurence<Fraction>();\n        if (f != members.end()) {\n            Valuable fo = *f;\n            auto& dn = fo.as<Fraction>().getDenominator();\n            if (dn.IsProduct()) {\n                auto& pd = dn.as<Product>();\n                for (auto it = members.begin(); it != members.end();)\n                {\n                    if (it != f && pd.Has(*it)) {\n                        fo *= *it;\n                        Delete(it);\n                        \n                        if (!fo.IsFraction() ||\n                            !fo.as<Fraction>().getDenominator().IsProduct()\n                            ) {\n                            break;\n                        }\n                    }\n                    else  ++it;\n                }\n            }\n            \n            fo.optimize();\n            \n            if (fo.IsFraction()) {\n                auto& dn = fo.as<Fraction>().getDenominator();\n                if (!dn.IsProduct()) {\n                    for (auto it = members.begin(); it != members.end();)\n                    {\n                        if (dn == *it) {\n                            Delete(it);\n                            fo *= dn;\n                            break;\n                        } else if (it->IsExponentiation() && it->as<Exponentiation>().getBase() == dn) {\n                            Update(it, *it/dn);\n                            fo *= dn;\n                            break;\n                        }\n                        else  ++it;\n                    }\n                }\n            }\n            \n            if(!f->Same(fo))\n            {\n                Update(f,fo);\n            }\n        }\n        \n        if(members.size()==0)\n            Become(1_v);\n        else if (members.size()==1)\n            Become(std::move(const_cast<Valuable&&>(*members.begin())));\n    }\n\n    Valuable Product::Sqrt() const\n    {\n        return Each([](auto& m){ return m.Sqrt(); });\n    }\n\n    Valuable & Product::sq()\n    {\n        Product p;\n        for (auto m : members)\n        {\n            p.Add(m.Sq());\n        }\n        return Become(std::move(p));\n    }\n    \n    const Product::vars_cont_t& Product::getCommonVars() const\n    {\n        return vars;\n    }\n    \n    Product::vars_cont_t Product::getCommonVars(const vars_cont_t& with) const\n    {\n        vars_cont_t common;\n        for(auto& kv : vars)\n        {\n            auto it = with.find(kv.first);\n            if (it != with.end()) {\n                auto& i1 = kv.second.ca();\n                auto& i2 = it->second.ca();\n                if (i1 > 0_v && i2 > 0_v) {\n                    common[kv.first] = std::min(i1, i2);\n                }\n                else\n                {\n                    IMPLEMENT\n                }\n            }\n        }\n        return common;\n    }\n    \n    Valuable Product::calcFreeMember() const\n    {\n        Valuable _ = 1_v;\n        if (getCommonVars().empty()) {\n            for(auto& m : *this) {\n                auto c = m.calcFreeMember();\n                if(c.IsInt()) {\n                    _ *= c;\n                } else\n                    IMPLEMENT\n            }\n        } else\n            _ = 0_v;\n        return _;\n    }\n    \n    Valuable Product::getCommVal(const Product& with) const\n    {\n        return VaVal(getCommonVars(with.getCommonVars()));\n    }\n\n    Valuable Product::InCommonWith(const Valuable& v) const\n    {\n        auto _ = 1_v;\n        auto check = [&](auto& with){\n            if (std::find(members.begin(), members.end(), with) != members.end())\n                _ *= with;\n            else\n                for(auto&m:members){\n                    auto c = m.InCommonWith(with);\n                    if (c!=1_v)\n                        _*=c;\n                }\n        };\n\n        if (v.IsProduct())\n            for(auto& m : v.as<Product>())\n                check(m);\n        else if (v.IsSum())\n            _ = v.InCommonWith(*this);\n        else\n            check(v);\n        return _;\n    }\n\n    // NOTE : inequality must cover all cases for bugless Sum::Add\n    bool Product::IsComesBefore(const Valuable& v) const\n    {\n        auto mae = getMaxVaExp();\n        auto vme = v.getMaxVaExp();\n        \n        if (mae != vme)\n            return mae > vme;\n        \n        char vp[sizeof(Product)];\n        auto isSameType = v.IsProduct();\n        if(!isSameType)\n        {\n            static const ProductOrderComparator oc;\n            return oc(*this,v);\n        }\n        auto p = isSameType ? &v.as<Product>() : new(vp) Product{v};\n        auto d = [isSameType](const Product* _){\n            if (!isSameType && _){\n                _->~Product();\n            }\n        };\n        std::unique_ptr<const Product , decltype(d)> up(p,d);\n        if (p)\n        {\n            if (vme != p->getMaxVaExp()) {\n                std::cout << vme << std::endl;\n                std::cout << p->getMaxVaExp() << std::endl;\n                IMPLEMENT\n            }\n\n            if (vaExpsSum.ca() != p->vaExpsSum.ca())\r\n            {\n                return vaExpsSum > p->vaExpsSum;\n            }\n            \n            if (members == p->members)\n                return false;\n            \n            if (members.size() != p->members.size()) {\n                return members.size() > p->members.size();\n            }\n            \n            auto i1 = members.begin();\n            auto i2 = p->members.begin();\n            for (; i1 != members.end(); ++i1, ++i2) {\n                auto it1 = std::find(ob, oe, i1->Type());\n                assert(it1!=oe); // IMPLEMENT, add to order table\n                auto it2 = std::find(ob, oe, i2->Type());\n                assert(it2!=oe); // IMPLEMENT\n                if (it1 != it2) {\n                    return it1 < it2;\n                }\n            }\n            // same types set, compare by value\n            i1 = members.begin();\n            i2 = p->members.begin();\n            for (; i1 != members.end(); ++i1, ++i2) {\n                if(*i1 != *i2)\n                {\n                    return i1->IsComesBefore(*i2);\n                }\n            }\n            \n            // everything is equal, should not be so\n            IMPLEMENT\n        }\n        else\n            IMPLEMENT\n    }\n    \n    Valuable& Product::operator +=(const Valuable& v)\n    {\n        if(v == 0_v)\n            return *this;\n        if (*this == v)\n            return *this *= 2;\n        if(*this == -v)\n            return Become(0_v);\n        if(v.IsProduct()){\n            auto& vAsP = v.as<Product>();\n            Product thisHasNotCommonWithV, vHasNotInCommonWithThis;\n            Product common;\n            for(auto&& item : GetCont()){\n                if(vAsP.Has(item))\n                    common.Add(std::move(item));\n                else\n                    thisHasNotCommonWithV.Add(std::move(item));\n            }\n            for(auto& item : vAsP.GetConstCont()){\n                if(!common.Has(item))\n                    vHasNotInCommonWithThis.Add(item);\n            }\n            if(!(common.size()==1 && *common.begin()==1)){ // unchanged\n                Valuable sum = Sum {thisHasNotCommonWithV, vHasNotInCommonWithThis};\n                sum.optimize();\n                sum *= common;\n                sum.optimize();\n                return Become(std::move(sum));\n            }\n        } else if (v.IsSum()) {\n            return Become(v + *this);\n        }\n        else{\n        auto& cv = getCommonVars();\n        if (!cv.empty() && cv == v.getCommonVars())\n        {\n            auto valuable = varless() + v.varless();\n            if(!valuable.IsSum())\n                valuable *= getVaVal();\n            return Become(std::move(valuable));\n        }\n        }\n        return Become(Sum { *this, v });\n    }\n\n    std::pair<Valuable, Valuable> Product::SplitSimplePart() const {\n        std::pair<Valuable, Valuable> parts;\n        auto it = begin();\n        IMPLEMENT\n    }\n\n    std::pair<Valuable, Valuable> Product::split_simple_part(){\n        IMPLEMENT\n\n    }\n\n   std::pair<bool,Valuable> Product::IsSummationSimplifiable(const Valuable& v) const\n   {\n       std::pair<bool,Valuable> is;\n       is.first = v == 0;\n       if (is.first)\n           is.second = *this;\n       else if ((is.first = operator==(v)))\n           is.second = *this * 2;\n       else if ((is.first = operator==(-v)))\n           is.second = 0;\n       else if (Has(v)) {\n           //OptimizeOn o;\n           auto div = *this / v;\n           auto divPlusOneIsSimple = div.IsSummationSimplifiable(vo<1>::get());\n           is.first = divPlusOneIsSimple.first;\n           if(divPlusOneIsSimple.first) {\n               is.second = divPlusOneIsSimple.second * v;\n           }\n       } else if (v.IsExponentiation()) {\n           is.first = Has(v) && size() == 2 && begin()->IsSimple();\n           if(is.first) {\n               is.second++ = *this;\n               is.first = !is.second.IsSum();\n           }\n       } else if (v.IsSimple()) {\n       } else if (v.IsProduct()\n                  || v.IsVa()\n                  || v.IsFraction()\n                  ) {\n           //OptimizeOn o;\n           auto icw = InCommonWith(v);\n           if (icw != 1) {\n               auto thisNoCommon = *this / icw;\n               if (!operator==(thisNoCommon)) { //multivalue cases (example ((-17)/16)*(4^((1/2))) / (1/2)*(4^((1/2))) = ((-17)/16)*(4^((1/2)))\n                   auto vNoCommon = v / icw;\n                   //std::cout << thisNoCommon << \".IsSummationSimplifiable(\" << vNoCommon << ')' << std::endl;\n                   is = thisNoCommon.IsSummationSimplifiable(vNoCommon);\n                   if(is.first){\n                       is.second *= icw;\n                   }\n               }\n           }\n//           auto& vp = v.as<Product>();\n//           auto sp = SplitSimplePart();\n//           auto vsp = vp.SplitSimplePart();\n//           if(sp.second == vsp.second){\n//\n//               IMPLEMENT\n//           }\n       } else {\n//           std::cout << v <<std::endl;\n           LOG_AND_IMPLEMENT(\"Unknown case (need to implement) in Product::IsSummationSimplifiable for \" << *this << \" and \" << v);\n       }\n       return is;\n   }\n\n    Valuable& Product::operator *=(const Valuable& v)\n    {\n        if ((size() == 1 && *begin() == 1) || size() == 0)\n            return Become(Valuable(v));\n\n        if (v.IsInt()){\n            if (v==0) {\n                return Become(0);\n            } else if (v==1) {\n                goto yes;\n            } else {\n                auto b = begin();\n                if(b->IsSimple()){\n                    auto up = *b * v;\n                    if(up == 1)\n                        Delete(b);\n                    else\n                        Update(b, up);\n                    goto yes;\n                }\n            }\n        }\n\n        if (v.IsSum())\n            return Become(v**this);\n\n        if (v.IsVa())\n        {\n            auto& va = v.as<Variable>();\n            for (auto it = members.begin(); it != members.end(); ++it)\n            {\n                if (it->Same(v)) {\n                    Update(it, Exponentiation(va, 2));\n                    goto yes;\n                }\n                else if (it->IsExponentiation())\n                {\n                    auto& e = it->as<Exponentiation>();\n                    if (e.getBase() == va) {\n                        Update(it, va ^ (e.getExponentiation()+1));\n                        goto yes;\n                    }\n                }\n            }\n        }\n        else if (v.IsExponentiation())\n        {\n            auto& e = v.as<Exponentiation>();\n            auto& vExpBase = e.getBase();\n            for (auto it = members.begin(); it != members.end();)\n            {\n                if (it->IsExponentiation() &&\n                    it->as<Exponentiation>().getBase() == vExpBase)\n                {\n                    Update(it, *it*v);\n                    goto yes;\n                }\n                else\n                {\n                    if (vExpBase == *it) {\n                        Update(it, vExpBase ^ (e.getExponentiation()+1));\n                        goto yes;\n                    }\n                    else\n                        ++it;\n                }\n            }\n        }\n        else if (v.IsProduct())\n        {\n            if(operator==(v))\n                sq();\n            else\n                for(auto& m : v.as<Product>())\n                    base::Add(m);\n            goto yes;\n        }\n        else\n        {\n            for (auto it = members.begin(); it != members.end();)\n            {\n                if (it->OfSameType(v)) {\n                    auto up = *it * v;\n                    if(up == 1){\n                        Delete(it);\n                    } else {\n                        Update(it, up);\n                    }\n                    goto yes;\n                }\n                else\n                    ++it;\n            }\n        }\n        \n        // add new member\n        Add(v);\n        \n    yes:\n        optimize();\n        return *this;\n    }\n\n    Valuable& Product::operator /=(const Valuable& v)\n    {\n        if (v.IsProduct()) {\n            auto opts = optimizations;\n            optimizations = {};\n            for(auto& i : v.as<Product>())\n                *this /= i;\n            optimizations = opts;\n            optimize();\n            return *this;\n        }\n        else if (v.IsSimple()) {\n            if (v == 1_v) {\n                return *this;\n            }\n            auto first = begin();\n            if (first->IsSimple()) {\n                auto _ = (*first) / v;\n                if (_.IsInt() && _.ca() == 1)\n                    Delete(first);\n                else {\n                    Update(first, _);\n                    optimized = {};\n                }\n                optimize();\n                return *this;\n            }\n            else {\n                return operator *=(Fraction{ 1_v,v });\n            }\n        }\n        else\n        {\n            auto it = std::find(begin(), end(), v);\n            if(it != end()){\n                Delete(it); // TODO : Review this branch to make it compatible with multivalue v\n                optimize();\n                return *this;\n            }\n            auto vIsExp = v.IsExponentiation();\n            auto e = vIsExp ? &v.as<Exponentiation>() : nullptr;\n            for (auto it = members.begin(); it != members.end(); ++it)\n            {\n                if (*it == v)\n                {\n                    if (v.IsMultival() == YesNoMaybe::No) {\n                        Delete(it);\n                        optimize();\n                        return *this;\n//                    } else if (v.IsMultival() == YesNoMaybe::Maybe) {\n                        \n                    } else {\n                        Update(it, *it * (v^-1));\n                        optimize();\n                        return *this;\n                    }\n                }\n                else if (vIsExp && *it == e->getBase())\n                {\n                    return *this *= e->getBase() ^ (-e->getExponentiation());\n                }\n                else if (it->IsExponentiation() && it->as<Exponentiation>().getBase() == v)\n                {\n                    Update(it, *it / v);\n                    optimize();\n                    return *this;\n                }\n            }\n        }\n//        else if (v.IsVa())\n//        {\n//            auto it = getCommonVars().find(v);\n//            if (it != getCommonVars().end() && *it != 0_v) {\n//                if (*it == 1_v) {\n//                    auto _ = find(begin(), end(), v);\n//                    if (_ == end()) {\n//                        IMPLEMENT\n//                    }\n//                    else\n//                    {\n//                        Delete(_);\n//                    }\n//                } else {\n//                    for(auto i = begin(); i != end(); ++i)\n//                    {\n//                        if (i->IsExponentiation()) {\n//                            auto e = Exponentiation::cast(*i);\n//                            if (e->getBase() == v) {\n//                                Update(i, *e / v);\n//                                optimize();\n//                                break;\n//                            }\n//                        }\n//                    }\n//                }\n//            }\n//        }\n        return *this *= v ^ -1;\n\t}\n\n    Valuable& Product::operator ^=(const Valuable& v)\n    {\n        auto _ = 1_v;\n        for(auto& m : members)\n        {\n            _ *= m ^ v;\n        }\n        Become(std::move(_));\n        return *this;\n    }\n\n\tValuable& Product::operator %=(const Valuable& v)\n\t{\n\t\treturn base::operator %=(v);\n\t}\n\n\tnamespace {\n        constexpr std::hash<a_int> Hasher;\n        const size_t Hash1 = Hasher(1);\n    }\n    bool Product::operator ==(const Valuable& v) const\n    {\n        auto sameHash = (Valuable::hash & ~Hash1) == (v.Hash() & ~Hash1); // ignore multiplication by 1\n        auto same = v.Is<Product>() && sameHash;\n        auto& c1 = GetConstCont();\n        auto sz1 = c1.size();\n        if (same) {\n            auto& vp = v.as<Product>();\n            auto& c2 = vp.GetConstCont();\n            auto sz2 = c2.size();\n            auto sameSizes = sz1 == sz2;\n            if(sameSizes) {\n                same = c1 == c2;                \n            } else if (sz1-sz2==1 || sz2-sz1==1) {\n                auto it1 = c1.begin(), it2 = c2.begin();\n                auto e1 = c1.end(), e2 = c2.end();                    \n                for(same = true;\n                    same && it1 != e1 && it2 != e2;\n                    ++it1, ++it2)\n                {\n                    if(it1->Same(1_v)){\n                        ++it1;\n                    }\n                    if(it2->Same(1_v)){\n                        ++it2;\n                    }\n                    \n                    if(it1 == e1 || it2 == e2)\n                        continue;\n                    \n                    same = same && it1->Same(*it2);\n                }\n                \n                same = same && it1 == e1 && it2 == e2;\n            } else {\n                same = {};\n            }\n        }\n        else if (sameHash\n                 && (sz1 == 1\n                     || (sz1 == 2 && c1.begin()->Same(1_v) )))\n        {\n            same = c1.rbegin()->operator==(v);\n        }\n        return same;\n    }\n\n    Product::operator double() const\n    {\n        double d=1;\n        for(auto& i:members)\n        {\n            d*=static_cast<double>(i);\n        }\n        return d;\n    }\n\n    Valuable& Product::d(const Variable& x)\n    {\n        if(vars.find(x) != vars.end())\n        {\n            *this *= vars[x];\n            *this /= x;\n            optimize();\n        }else\n            Become(0_v);\n        return *this;\n    }\n    \n    Valuable Product::operator()(const Variable& va) const\n    {\n        return operator()(va, 0_v);\n    }\n    \n    Valuable Product::operator()(const Variable& va, const Valuable& augmentation) const\n    {\n        Valuable s; s.SetView(Valuable::View::Flat);\n       \n        if(augmentation.HasVa(va)) {\n            IMPLEMENT;\n        } else {\n            auto coVa = getCommonVars();\n            auto it = coVa.find(va);\n            if (it != coVa.end()) {\n                if (it->second < 0) {\n                    s = ((*this / (it->first ^ it->second)) / augmentation) ^ (1_v / -it->second);\n                }\n                else\n                {\n                    s = (augmentation / (*this / (it->first ^ it->second))) ^ (1_v / it->second);\n                }\n            }\n            else\n            {\n                auto a = 1_v;\n                auto aug = augmentation;\n                for(auto& m : members)\n                    if (m.HasVa(va))\n                        a *= m;\n                    else\n                        aug *= m;\n                if (a==1) {\n                    IMPLEMENT\n                }\n                s = a(va,aug);\n            }\n        }\n        \n//        if(augmentation.HasVa(va)) {\n//            IMPLEMENT;\n//        } else {\n//            auto _ = augmentation;\n//            auto left = 1_v;\n//            for(auto& m : members)\n//            {\n//                if (m.HasVa(va)) {\n//                    left *= m;\n//                } else {\n//                    _ /= m;\n//                }\n//            }\n//            \n//            left.optimize();\n//            if (left.IsProduct()) {\n//                IMPLEMENT\n//            }\n//            \n//            return left(va, _);\n//        }\n//        auto cova = getCommonVars();\n//        auto it = cova.find(va);\n//        if (it != cova.end()) {\n//            auto _ = augmentation / (*this / (va ^ it->second));\n//            if(_.HasVa(va))\n//                IMPLEMENT;\n//            s.insert(_);\n//            if (it->second % 2 == 0) {\n//                s.insert(-_);\n//            }\n//        }\n//        else\n//        {\n//            IMPLEMENT\n//        }\n        return s;\n    }\n    \n    void Product::solve(const Variable& va, solutions_t& solutions) const\n    {\n        auto it = std::find(members.begin(), members.end(), va);\n        if(it != members.end())\n            solutions.insert(0_v);\n        else {\n            it = begin();\n            bool found = {};\n            const Exponentiation* e = {};\n            while (it != end()\n                    && !(it->IsExponentiation()\n                     && (found = it->as<Exponentiation>().getBase() == va)\n                     ) ) {\n                ++it;\n            }\n            if (found) {\n                if (e->getExponentiation() == 0_v) {\n                    IMPLEMENT\n                }\n                solutions.insert(0_v);\n            }\n            else {\n                std::cout << \"Solving \" << str() << std::endl;\n                IMPLEMENT // TODO: find exponentiations of va\n            }\n        }\n    }\n\n    Valuable::solutions_t Product::Distinct() const {\n        solutions_t branches = { 1_v };\n        for (auto& m : members) {\n            solutions_t newBranches;\n            for (auto&& branch : m.Distinct()) {\n                for (auto& b : branches) {\n                    newBranches.emplace(b * branch);\n                }\n            }\n            branches = std::move(newBranches);\n        }\n        return branches;\n    }\n\n\tstd::ostream& Product::print(std::ostream& out) const\n\t{\n        std::stringstream s;\n        constexpr char sep[] = \"*\";\n        for (auto& b : members)\n            s << b << sep;\n        auto str = s.str();\n        auto cstr = const_cast<char*>(str.c_str());\n        cstr[str.size() - sizeof(sep) + 1] = 0;\n        out << cstr;\n        return out;\n\t}\n    \n}}\n", "meta": {"hexsha": "abacdeb32a25bb71bf025d3ff7ebc66c6f4f32bd", "size": 33073, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "omnn/math/Product.cpp", "max_stars_repo_name": "SergMariaDB/openmind", "max_stars_repo_head_hexsha": "98ad7f1c2c5c02d41418c7f9af25876342270d25", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-04T20:00:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T20:00:05.000Z", "max_issues_repo_path": "omnn/math/Product.cpp", "max_issues_repo_name": "SergMariaDB/openmind", "max_issues_repo_head_hexsha": "98ad7f1c2c5c02d41418c7f9af25876342270d25", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "omnn/math/Product.cpp", "max_forks_repo_name": "SergMariaDB/openmind", "max_forks_repo_head_hexsha": "98ad7f1c2c5c02d41418c7f9af25876342270d25", "max_forks_repo_licenses": ["BSD-3-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.3982222222, "max_line_length": 143, "alphanum_fraction": 0.3735977988, "num_tokens": 7339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.28834742783299483}}
{"text": "// Copyright (c) 1997-2001  ETH Zurich (Switzerland).\n// All rights reserved.\n//\n// This file is part of CGAL (www.cgal.org).\n//\n// $URL$\n// $Id$\n// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial\n//\n//\n// Author(s)     : Kaspar Fischer <fischerk@inf.ethz.ch>\n\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <string>\n#include <cstdlib>\n\n#include <CGAL/boost/iterator/transform_iterator.hpp>\n#include <boost/iterator/zip_iterator.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include <CGAL/Exact_rational.h>\n#include <CGAL/MP_Float.h>\n#include <CGAL/QP_solver/QP_solver.h>\n#include <CGAL/QP_solver/QP_full_exact_pricing.h>\n#include <CGAL/QP_solver/QP_exact_bland_pricing.h>\n#include <CGAL/QP_solver/QP_partial_exact_pricing.h>\n#include <CGAL/QP_solver/QP_full_filtered_pricing.h>\n#include <CGAL/QP_solver/QP_partial_filtered_pricing.h>\n\n#include <CGAL/QP_models.h>\n#include <CGAL/QP_functions.h>\n\n#include <CGAL/boost_mp.h>\n//Currently already included in boost_mp.h\n//#ifdef CGAL_USE_BOOST_MP\n//# include <boost/multiprecision/cpp_int.hpp>\n//// After some CGAL includes so we get a chance to define CGAL_USE_GMP.\n//# ifdef CGAL_USE_GMP\n//#  include <boost/multiprecision/gmp.hpp>\n//# endif\n//#endif\n\n// Routines to output to MPS format:\nnamespace QP_from_mps_detail {\n\n  template<typename T>\n  struct MPS_type_name {\n    static const char *name() { return nullptr; }\n  };\n\n  template<>\n  struct MPS_type_name<double> {\n    static const char *name() { return \"floating-point\"; }\n  };\n\n  template<>\n  struct MPS_type_name<int> {\n    static const char *name() { return \"integer\"; }\n  };\n#ifdef CGAL_USE_BOOST_MP\n  template <class Backend, boost::multiprecision::expression_template_option Eto>\n  struct MPS_type_name<boost::multiprecision::number<Backend, Eto> > {\n    typedef boost::multiprecision::number<Backend, Eto> NT;\n    static const char *name() {\n      if (boost::multiprecision::number_category<NT>::value == boost::multiprecision::number_kind_integer)\n        return \"integer\";\n      else if (boost::multiprecision::number_category<NT>::value == boost::multiprecision::number_kind_rational)\n        return \"rational\";\n      else\n        return nullptr;\n    }\n  };\n#endif\n#ifdef CGAL_USE_GMPXX\n  template<>\n  struct MPS_type_name<mpq_class> {\n    static const char *name() { return \"rational\"; }\n  };\n#endif\n#ifdef CGAL_USE_GMP\n  template<>\n  struct MPS_type_name<CGAL::Gmpq> {\n    static const char *name() { return \"rational\"; }\n  };\n#endif\n\n#ifdef CGAL_USE_LEDA\n  template<>\n  struct MPS_type_name<leda::rational> {\n    static const char *name() { return \"rational\"; }\n  };\n#endif\n  template<>\n  struct MPS_type_name<CGAL::Quotient<CGAL::MP_Float> > {\n    static const char *name() { return \"rational\"; }\n  };\n\n  template<typename IT>\n  struct IT_to_ET {\n  };\n\n  template<>\n  struct IT_to_ET<double> {\n    typedef CGAL::MP_Float ET;\n  };\n#ifdef CGAL_USE_BOOST_MP\n  template<>\n  struct IT_to_ET<boost::multiprecision::cpp_rational> {\n    typedef boost::multiprecision::cpp_rational ET;\n  };\n#endif\n\n#ifdef CGAL_USE_GMP\n#ifdef CGAL_USE_GMPXX\n  template<>\n  struct IT_to_ET<int> {\n    typedef mpz_class ET;\n  };\n\n  template<>\n  struct IT_to_ET<mpq_class> {\n    typedef mpq_class ET;\n  };\n#elif defined CGAL_USE_BOOST_MP\n  template<>\n  struct IT_to_ET<int> {\n    typedef boost::multiprecision::mpz_int ET;\n  };\n\n  template<>\n  struct IT_to_ET<boost::multiprecision::mpq_rational> {\n    typedef boost::multiprecision::mpq_rational ET;\n  };\n#else\n  template<>\n  struct IT_to_ET<int> {\n    typedef CGAL::Gmpz ET;\n  };\n#endif\n\n  template<>\n  struct IT_to_ET<CGAL::Gmpq> {\n    typedef CGAL::Gmpq ET;\n  };\n#endif\n\n#ifdef CGAL_USE_LEDA\n// Pick one arbitrarily if we have both LEDA and GMP\n#ifndef CGAL_USE_GMP\n  template<>\n  struct IT_to_ET<int> {\n    typedef leda::integer ET;\n  };\n#endif\n\n  template<>\n  struct IT_to_ET<leda::rational> {\n    typedef leda::rational ET;\n  };\n#endif\n  template<>\n  struct IT_to_ET<CGAL::Quotient<CGAL::MP_Float> > {\n    typedef CGAL::Quotient<CGAL::MP_Float> ET;\n  };\n\n#if defined CGAL_USE_BOOST_MP && !defined CGAL_USE_GMP && !defined CGAL_USE_LEDA\n  // Last chance for int\n  template<>\n  struct IT_to_ET<int> {\n    typedef boost::multiprecision::cpp_int ET;\n  };\n#endif\n} // QP_from_mps_detail\n\ntemplate<typename QP>\nvoid write_MPS(std::ostream& out,\n               const std::string& number_type, // pass \"\" to deduce\n                                               // the number-type from\n                                               // U_iterator::value_type\n               const std::string& description,\n               const std::string& generator_name,\n               const std::string& problem_name,\n               const QP& qp)\n{\n  // output header:\n  if (number_type.length() == 0) {\n    const char *tn = QP_from_mps_detail::MPS_type_name\n      <typename\n      std::iterator_traits<typename QP::U_iterator>::value_type>::name();\n    if (tn != nullptr)\n      out << \"* Number-type: \" << tn << \"\\n\";\n  } else\n      out << \"* Number-type: \" << number_type << \"\\n\";\n  out << \"* Description: \" << description << \"\\n\"\n      << \"* Generated-by: \" << generator_name << \"\\n\";\n\n  // print in qmatrix format\n  CGAL::print_quadratic_program(out, qp, problem_name);\n}\n\nboost::shared_ptr<std::ofstream>\ncreate_output_file(const char *filename, // Note: \"Bernd3\" and not\n                                         // \"Bernd3.mps\".\n                   const char *directory,\n                   const char *suffix)   // Note: \"shifted\"\n                                         // and not \"_shifted\".\n{\n  std::string new_name = std::string(directory) +\n    std::string(\"/\") + std::string(filename) + std::string(\"_\") +\n    std::string(suffix) + std::string(\".mps\");\n  return boost::shared_ptr<std::ofstream>(new std::ofstream(new_name.c_str(),\n                                                            std::ios_base::trunc |\n                                                            std::ios_base::out));\n}\n\ntemplate<typename NT>\nstruct tuple_add :\n  public CGAL::cpp98::unary_function<const boost::tuple<NT, NT>&, NT>\n{\n  NT operator()(const boost::tuple<NT, NT>& t) const\n  {\n    return boost::tuples::get<0>(t) + boost::tuples::get<1>(t);\n  }\n};\n\ntemplate<typename IT,   // input number type\n         typename ET>   // exact number type compatible with IT (ET is used,\n                        // for instance, by QP in the query methods\n                        // has_equalities_only_and_full_rank())\nvoid create_shifted_instance(const CGAL::Quadratic_program_from_mps <IT>& qp,\n                             const char *file,   // Note: \"Bernd3\" and\n                                                 // not \"Bernd3.mps\".\n                             const char *dir)\n{\n  // This routine implements the following transformation:\n  //\n  //   A  -> A\n  //   b  -> b + A v\n  //   c  -> c - 2 v^T\n  //   D  -> D\n  //   row_types -> row_types\n  //   l  -> l + v\n  //   u  -> u + v\n  //   fl -> fl\n  //   fu -> fu\n  //\n  // where v = [1,...,n]^T.\n\n  // extract data from qp:\n  const int n = qp.get_n();\n  const int m = qp.get_m();\n\n  // offset vector:\n  std::vector<IT> v(n);\n  for (int i=0; i<n; ++i)\n    v[i] = i+1;\n\n  // compute A v into Av;\n  std::vector<IT> Av(m, IT(0));\n  for (int i=0; i<m; ++i)\n    for (int j=0; j<n; ++j)\n      Av[i] += (const IT&)(*(qp.get_a()+j))[i] * v[j];\n\n  // compute - 2 v^T D into mvTD:\n  std::vector<IT> mvTD(n, IT(0));  // -2D^Tv\n  for (int i=0; i<n; ++i) {\n    for (int j=0; j<n; ++j)\n      mvTD[i]\n        += ( j <= i ? (const IT&)(*(qp.get_d()+i))[j] : (const IT&)(*(qp.get_d()+j))[i]) * v[j];\n    mvTD[i] *= -1;\n  }\n\n  // output:\n  using boost::make_transform_iterator;\n  using boost::make_zip_iterator;\n  boost::shared_ptr<std::ofstream> out = create_output_file(file, dir, \"shifted\");\n\n  write_MPS(*out,\n                  \"\", // deduce number-type\n                  \"Shifted instance of original file\",\n                  \"master_mps_to_derivatives-create_shifted_instance\",\n                  qp.get_problem_name(),\n                  CGAL::make_quadratic_program_from_iterators(\n     n,\n     m,\n     qp.get_a(),\n     make_transform_iterator(\n                             make_zip_iterator(boost::make_tuple(qp.get_b(),Av.begin())),\n                             tuple_add<IT>()),\n     qp.get_r(),\n     qp.get_fl(),\n     make_transform_iterator(\n                              make_zip_iterator(boost::make_tuple(qp.get_l(),v.begin())),\n                              tuple_add<IT>()),\n     qp.get_fu(),\n     make_transform_iterator(\n                             make_zip_iterator(boost::make_tuple(qp.get_u(),v.begin())),\n                             tuple_add<IT>()),\n     qp.get_d(),\n     make_transform_iterator(\n                           make_zip_iterator(boost::make_tuple(qp.get_c(),mvTD.begin())),\n                           tuple_add<IT>()),\n     qp.get_c0()\n     )\n);\n  out->close();\n}\n\ntemplate<typename IT,   // input number type\n         typename ET>   // exact number type compatible with IT (ET is used,\n                        // for instance, by QP in the query methods\n                        // has_equalities_only_and_full_rank())\nvoid create_free_instance(CGAL::Quadratic_program_from_mps<IT>& qp,\n                          const char *file,   // Note: \"Bernd3\" and\n                                              // not \"Bernd3.mps\".\n                          const char *dir)\n{\n  // This routine converts the given instance into an equivalent\n  // problem where all bounds are modelled by additional rows of A and\n  // where all variables are free.\n  //\n  // That is, the quantities c and D do not change, but A, b, and\n  // row_types are augmented by at most 2n additional rows/entries\n  // (and fl and fu are adjusted as well).\n\n  // extract data from qp:\n  const unsigned int n = qp.get_n();\n  unsigned int m = qp.get_m();\n\n  // add rows to A and corresponding entries to b:\n  for (unsigned int i=0; i<n; ++i) {\n    if (*(qp.get_fl()+i)) {                        // x >= l\n      // add a row to A:\n      for (unsigned int j=0; j<n; ++j)\n        qp.set_a (j, m, (i==j? 1 : 0));\n\n      // add corresponding entry to b:\n      qp.set_b(m, qp.get_l()[i]);\n\n      // add corresponding row type:\n      qp.set_r(m, CGAL::LARGER);\n      ++m;\n    }\n    qp.set_l(i, false);                           // variable becomes free\n    if (*(qp.get_fu()+i)) {                        // x <= u\n      // add a row to A:\n      for (unsigned int j=0; j<n; ++j)\n        qp.set_a (j, m ,(i==j? 1 : 0));\n\n      // add corresponding entry to b:\n      qp.set_b(m, qp.get_u()[i]);\n\n      // add corresponding row type:\n      qp.set_r(m, CGAL::SMALLER);\n      ++m;\n    }\n    qp.set_u(i, false);                         // variable becomes free\n  }\n  // output:\n  boost::shared_ptr<std::ofstream> out = create_output_file(file, dir, \"free\");\n  write_MPS(*out,\n                  \"\", // deduce number-type\n                  \"Freed instance of original file\",\n                  \"master_mps_to_derivatives-create_free_instance\",\n                  qp.get_problem_name(),\n            qp);\n  out->close();\n}\n\ntemplate<typename IT>\nbool create_derivatives(const char *path,\n                        const char *file,\n                        const char *dir,\n                        std::string& msg)\n{\n  using std::cerr;\n  using CGAL::Tag_true;\n  using CGAL::Tag_false;\n\n  // diagnostics:\n  cerr << \"  Trying to load input MPS using \"\n       << QP_from_mps_detail::MPS_type_name<IT>::name()\n       << \" number-type...\\n\";\n\n  // open input file:\n  std::ifstream f(path);\n  if (!f) {\n    cerr << \"    Could not open file '\" << path << \"'.\\n\";\n    return false;\n  }\n\n  // load QP instance:\n  typedef typename QP_from_mps_detail::IT_to_ET<IT>::ET ET;\n  typedef CGAL::Quadratic_program_from_mps<IT> QP;\n  QP qp(f);\n\n  // check for format errors in MPS file:\n  if (!qp.is_valid()) {\n    msg = \"Input is not a valid MPS file: \" + qp.get_error();\n    return false;\n  }\n  cerr << \"    MPS-file successfully input.\\n\";\n\n  // no derivatives if comment says so\n  if (qp.get_comment().find(std::string(\"Derivatives: none\"))!=std::string::npos)\n    cerr << \"    No derivatives made.\\n\";\n  else {\n    // derivates:\n    create_shifted_instance<IT, ET>(qp, file, dir);\n    create_free_instance<IT, ET>(qp, file, dir);\n    // Note: insert additional derivative routines here! Your routine may use\n    // create_output_file() to create the output file.\n  }\n  // cleanup:\n  f.close();\n  return true;\n}\n\nint main(const int argnr, const char **argv) {\n  typedef CGAL::Exact_rational Rational;\n\n  // output usage information:\n  if (argnr != 4) {\n    std::cerr << \"Usage: \" << argv[0] << \" path-to-master.mps name \"\n              << \"dest-directory\\n\\n\"\n              << \"Given a master MPS-file, this program constructs from it \"\n              << \"several other, derived\\nMPS-files and saves them in the \"\n              << \"destination directory.\\n\\n\"\n              << \"The argument 'name' should be the basename (without \"\n              << \"extension) of the\\nargument 'path-to-master.mps'.\\n\\n\"\n              << \"Usually, you do not have to call this program directly; \"\n              << \"./create_testsuite does\\nit for you automagically.\\n\";\n    return 0; // Note: 0 because otherwise the testsuite will fail...\n  }\n\n  // extract arguments:\n  const char *path = argv[1];\n  const char *file = argv[2];\n  const char *dir  = argv[3];\n\n  // As we do not know the number-type used in the MPS-file, we simply try\n  // to load the MPS-file once with a double type, once with a Rational\n  // type, and once with an int type.\n  // we try the most special one first, so the order is\n  // int -> double -> rational\n  std::string message;\n  if (!create_derivatives<int>(path, file, dir, message))\n    if (!create_derivatives<double>(path, file, dir, message))\n      if (!create_derivatives<Rational>(path, file, dir, message)) {\n        // Here, the MPS-file must be ill-formatted.\n        std::cerr << \"  \" << message << \"\\n\";\n        return 2;\n      }\n\n  return 0;\n}\n", "meta": {"hexsha": "22a72be23f9c25beee9c73c0624a984326e7cd0d", "size": 14016, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QP_solver/test/QP_solver/master_mps_to_derivatives.cpp", "max_stars_repo_name": "mtola/cgal", "max_stars_repo_head_hexsha": "e7b91b92b8c6949e3b62023bdd1e9f3ad8472626", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-08T23:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-08T23:06:26.000Z", "max_issues_repo_path": "QP_solver/test/QP_solver/master_mps_to_derivatives.cpp", "max_issues_repo_name": "samrat2825/cgal-dev", "max_issues_repo_head_hexsha": "eab5df14e118deb20db7373717bac273f1775a92", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-12T14:38:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-12T14:38:20.000Z", "max_forks_repo_path": "QP_solver/test/QP_solver/master_mps_to_derivatives.cpp", "max_forks_repo_name": "szobov/cgal", "max_forks_repo_head_hexsha": "e7b91b92b8c6949e3b62023bdd1e9f3ad8472626", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5359477124, "max_line_length": 112, "alphanum_fraction": 0.5872574201, "num_tokens": 3703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.28830405371452594}}
{"text": "/*\n symmetry.cpp\n\n Copyright (c) 2014, 2015, 2016 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 <cmath>\n#include <iostream>\n#include <iomanip>\n#include \"mathfunctions.h\"\n#include \"symmetry.h\"\n#include \"system.h\"\n#include \"memory.h\"\n#include \"constants.h\"\n#include \"timer.h\"\n#include \"error.h\"\n#include \"interaction.h\"\n#include \"files.h\"\n#include <cmath>\n#include <vector>\n#include <set>\n#include <algorithm>\n\n#ifdef _USE_EIGEN\n#include <Eigen/Core>\n#endif\n\nusing namespace ALM_NS;\n\nSymmetry::Symmetry(ALM *alm) : Pointers(alm) \n{\n    file_sym = \"SYMM_INFO\";\n}\n\nSymmetry::~Symmetry() \n{\n    memory->deallocate(symrel);\n    memory->deallocate(symrel_int);\n    memory->deallocate(tnons);\n    memory->deallocate(map_sym);\n    memory->deallocate(map_p2s);\n    memory->deallocate(map_s2p);\n    memory->deallocate(symnum_tran);\n    memory->deallocate(sym_available);\n}\n\nvoid Symmetry::init()\n{\n    int i, j;\n    int nat = system->nat;\n\n    std::cout << \" SYMMETRY\" << std::endl;\n    std::cout << \" ========\" << std::endl << std::endl;\n\n    setup_symmetry_operation(nat, nsym, system->lavec, system->rlavec, \n        system->xcoord, system->kd);\n\n    memory->allocate(tnons, nsym, 3);\n    memory->allocate(symrel_int, nsym, 3, 3);\n\n    int isym = 0;\n    for (std::vector<SymmetryOperation>::iterator iter = SymmList.begin(); iter != SymmList.end(); ++iter) {\n        for (i = 0; i < 3; ++i) {\n            for (j = 0; j < 3; ++j) {\n                symrel_int[isym][i][j] = (*iter).rot[i][j];\n            }\n        }\n        for (i = 0; i < 3; ++i) {\n            tnons[isym][i] = (*iter).tran[i];\n        }\n        ++isym;\n    }\n\n    std::cout << \"  Number of symmetry operations = \" << nsym << std::endl;\n    memory->allocate(symrel, nsym, 3, 3);\n    symop_in_cart(system->lavec, system->rlavec);\n\n    memory->allocate(sym_available, nsym);\n    int nsym_fc;\n    symop_availability_check(symrel, sym_available, nsym, nsym_fc);\n\n    if (nsym_fc == nsym) {\n        std::cout << \"  All symmetry operations will be used to reduce the number of force constants.\" << std::endl;\n    } else {\n        std::cout << \"  \" << nsym_fc << \" symmetry operations out of \" \n            << nsym << \" will be used to reduce the number of parameters.\" << std::endl;\n        std::cout << \"  Other \" << nsym - nsym_fc \n            << \" symmetry operations will be imposed as constraints.\" << std::endl;\n    }\n    std::cout << std::endl;\n\n    pure_translations();\n\n    memory->allocate(map_sym, nat, nsym);\n    memory->allocate(map_p2s, natmin, ntran);\n    memory->allocate(map_s2p, nat);\n\n    genmaps(nat, system->xcoord, map_sym, map_p2s, map_s2p);\n\n    std::cout << std::endl;\n    std::cout << \"  **Cell-Atom Correspondens Below**\" << std::endl;\n    std::cout << std::setw(6) << \" CELL\" << \" | \" << std::setw(5) << \"ATOM\" << std::endl;\n\n    for (int i = 0; i < ntran; ++i) {\n        std::cout << std::setw(6) << i + 1 << \" | \";\n        for (int j = 0; j < natmin; ++j)  {\n            std::cout << std::setw(5) << map_p2s[j][i] + 1;\n            if((j + 1)%5 == 0) {\n                std::cout << std::endl << \"       | \";\n            }\n        }\n        std::cout << std::endl;\n    }\n    std::cout << std::endl;\n\n    timer->print_elapsed();\n    std::cout << \" --------------------------------------------------------------\" << std::endl;\n    std::cout << std::endl;\n}\n\nvoid Symmetry::setup_symmetry_operation(int nat, unsigned int &nsym, \n                                        double aa[3][3], double bb[3][3], double **x, int *kd)\n{\n    int i, j;\n\n    SymmList.clear();\n\n    if (nsym == 0) {\n\n        // Automatically find symmetries.\n\n        std::cout << \"  NSYM = 0 : Trying to find symmetry operations.\" << std::endl;\n        std::cout << \"             Please be patient. \" << std::endl;\n        std::cout << \"             This can take a while for a large supercell.\" << std::endl << std::endl;\n\n        findsym(nat, aa, x, SymmList);\n        // The order in SymmList changes for each run because it was generated\n        // with OpenMP. Therefore, we sort the list here to have the same result. \n        std::sort(SymmList.begin()+1,SymmList.end());\n        nsym = SymmList.size();\n\n        if (is_printsymmetry) {\n            std::ofstream ofs_sym;\n            std::cout << \"  PRINTSYM = 1: Symmetry information will be stored in SYMM_INFO file.\" \n                << std::endl << std::endl;\n            ofs_sym.open(file_sym.c_str(), std::ios::out);\n            ofs_sym << nsym << std::endl;\n\n            for (std::vector<SymmetryOperation>::iterator p = SymmList.begin(); p != SymmList.end(); ++p) {\n                for (i = 0; i < 3; ++i) {\n                    for (j = 0; j < 3; ++j) {\n                        ofs_sym << std::setw(4) << (*p).rot[i][j];\n                    }\n                }\n                ofs_sym << \"  \";\n                for (i = 0; i < 3; ++i) {\n                    ofs_sym << std::setprecision(15) << std::setw(20) << (*p).tran[i];\n                }\n                ofs_sym << std::endl;\n            }\n\n            ofs_sym.close();\n        }\n\n    } else if (nsym == 1) {\n\n        // Identity operation only !\n\n        std::cout << \"  NSYM = 1 : Only the identity matrix will be considered.\" << std::endl << std::endl;\n\n        int rot_tmp[3][3];\n        double tran_tmp[3];\n\n        for (i = 0; i < 3; ++i) {\n            for (j = 0; j < 3; ++j) {\n                if (i == j) {\n                    rot_tmp[i][j] = 1;\n                } else {\n                    rot_tmp[i][j] = 0;\n                }\n            }\n            tran_tmp[i] = 0.0;\n        }\n\n        SymmList.push_back(SymmetryOperation(rot_tmp, tran_tmp));\n\n    } else {\n\n        std::cout << \"  NSYM > 1 : Symmetry operations will be read from SYMM_INFO file\" << std::endl << std::endl;\n\n        int nsym2;\n        int rot_tmp[3][3];\n        double tran_tmp[3];\n        std::ifstream ifs_sym;\n\n        ifs_sym.open(file_sym.c_str(), std::ios::in);\n        ifs_sym >> nsym2; \n\n        if (nsym != nsym2) error->exit(\"setup_symmetry_operations\", \n            \"nsym in the given file and the input file are not consistent.\");\n\n        for (i = 0; i < nsym; ++i) {\n            ifs_sym >> rot_tmp[0][0] >> rot_tmp[0][1] >> rot_tmp[0][2]\n            >> rot_tmp[1][0] >> rot_tmp[1][1] >> rot_tmp[1][2] \n            >> rot_tmp[2][0] >> rot_tmp[2][1] >> rot_tmp[2][2]\n            >> tran_tmp[0] >> tran_tmp[1] >> tran_tmp[2];\n\n            SymmList.push_back(SymmetryOperation(rot_tmp, tran_tmp));\n        }\n        ifs_sym.close();\n    }\n\n#ifdef _DEBUG\n    print_symmetrized_coordinate(x);\n#endif\n}\n\nvoid Symmetry::findsym(int nat, double aa[3][3], double **x, std::vector<SymmetryOperation> &symop_all) {\n\n    std::vector<RotationMatrix> LatticeSymmList;\n\n    // Generate rotational matrices that don't change the metric tensor\n    LatticeSymmList.clear();\n    find_lattice_symmetry(aa, LatticeSymmList);\n\n    // Generate all the space group operations with translational vectors\n    symop_all.clear();\n    find_crystal_symmetry(nat, system->nclassatom, system->atomlist_class, x,\n        LatticeSymmList, symop_all);\n\n    LatticeSymmList.clear();\n}\n\nvoid Symmetry::find_lattice_symmetry(double aa[3][3], std::vector<RotationMatrix> &LatticeSymmList) {\n\n    /*\n    Find the rotational matrices that leave the metric tensor invariant.\n\n    Metric tensor G = (g)_{ij} = a_{i} * a_{j} is invariant under crystal symmetry operations T,\n    i.e. T^{t}GT = G. Since G can be written as G = A^{t}A, the invariance condition is given by\n    (AT)^{t}(AT) = G0 (original).\n    */\n\n    int i, j, k;\n    int m11, m12, m13, m21, m22, m23, m31, m32, m33;\n\n    int nsym_tmp = 0;\n    int mat_tmp[3][3];\n    double det, res;\n    double rot_tmp[3][3];\n    double aa_rot[3][3];\n\n    double metric_tensor[3][3];\n    double metric_tensor_rot[3][3];\n\n\n    for (i = 0; i < 3; ++i) {\n        for (j = 0; j < 3; ++j) {\n            metric_tensor[i][j] = 0.0;\n            for (k = 0; k < 3; ++k) {\n                metric_tensor[i][j] += aa[k][i] * aa[k][j];\n            }\n        }\n    }\n\n    for (i = 0; i < 3; ++i) {\n        for (j = 0; j < 3; ++j) {\n            if (i == j) {\n                mat_tmp[i][i] = 1;\n            } else {\n                mat_tmp[i][j] = 0;\n            }\n        }\n    }\n\n    // Identity matrix should be the first entry.\n    LatticeSymmList.push_back(mat_tmp);\n\n    for (m11 = -1; m11 <= 1; ++m11){\n        for (m12 = -1; m12 <= 1; ++m12) {\n            for (m13 = -1; m13 <= 1; ++m13){\n                for (m21 = -1; m21 <= 1; ++m21){\n                    for (m22 = -1; m22 <= 1; ++m22){\n                        for (m23 = -1; m23 <= 1; ++m23){\n                            for (m31 = -1; m31 <= 1; ++m31){\n                                for (m32 = -1; m32 <= 1; ++m32){\n                                    for (m33 = -1; m33 <= 1; ++m33){\n\n                                        if (m11 == 1 && m12 == 0 && m13 == 0 &&\n                                            m21 == 0 && m22 == 1 && m23 == 0 &&\n                                            m31 == 0 && m32 == 0 && m33 == 1) continue;\n\n                                        det = m11 * (m22 * m33 - m32 * m23)\n                                            - m21 * (m12 * m33 - m32 * m13)\n                                            + m31 * (m12 * m23 - m22 * m13);\n\n                                        if (det != 1 && det != -1) continue;\n\n                                        rot_tmp[0][0] = m11;\n                                        rot_tmp[0][1] = m12;\n                                        rot_tmp[0][2] = m13;\n                                        rot_tmp[1][0] = m21;\n                                        rot_tmp[1][1] = m22;\n                                        rot_tmp[1][2] = m23;\n                                        rot_tmp[2][0] = m31;\n                                        rot_tmp[2][1] = m32;\n                                        rot_tmp[2][2] = m33;\n\n                                        // Here, aa_rot = aa * rot_tmp is correct.\n                                        matmul3(aa_rot, aa, rot_tmp);\n\n                                        for (i = 0; i < 3; ++i) {\n                                            for (j = 0; j < 3; ++j) {\n                                                metric_tensor_rot[i][j] = 0.0;\n                                                for (k = 0; k < 3; ++k) {\n                                                    metric_tensor_rot[i][j] += aa_rot[k][i] * aa_rot[k][j];\n                                                }\n                                            }\n                                        }\n\n                                        res = 0.0;\n                                        for (i = 0; i < 3; ++i) {\n                                            for (j = 0; j < 3; ++j) {\n                                                res += std::pow(metric_tensor[i][j] - metric_tensor_rot[i][j], 2.0);\n                                            }\n                                        }\n\n                                        // Metric tensor is invariant under symmetry operations.\n\n                                        if (res < tolerance * tolerance) {\n                                            ++nsym_tmp;\n                                            for (i = 0; i < 3; ++i) {\n                                                for (j = 0; j < 3; ++j) {\n                                                    mat_tmp[i][j] = static_cast<int>(rot_tmp[i][j]);\n                                                }\n                                            }\n                                            LatticeSymmList.push_back(mat_tmp);\n                                        }\n\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    if (LatticeSymmList.size() > 48) {\n        error->exit(\"find_lattice_symmetry\", \"Number of lattice symmetry is larger than 48.\");\n    }\n}\n\nvoid Symmetry::find_crystal_symmetry(int nat, int nclass, std::vector<unsigned int> *atomclass, double **x, \n                                     std::vector<RotationMatrix> LatticeSymmList, \n                                     std::vector<SymmetryOperation> &CrystalSymmList)\n{\n    unsigned int i, j;\n    unsigned int iat, jat, kat, lat;\n    double x_rot[3];\n    double rot[3][3], rot_tmp[3][3], rot_cart[3][3];\n    double mag[3], mag_rot[3];\n    double tran[3];\n    double x_rot_tmp[3];\n    double tmp[3];\n    double diff;\n\n    int rot_int[3][3];\n\n    int ii, jj, kk;\n    unsigned int itype;\n\n    bool is_found;\n    bool isok;\n    bool mag_sym1, mag_sym2;\n\n    bool is_identity_matrix;\n\n\n    // Add identity matrix first.\n    for (i = 0; i < 3; ++i) {\n        for (j = 0; j < 3; ++j) {\n            if (i == j) {\n                rot_int[i][j] = 1;\n            } else {\n                rot_int[i][j] = 0;\n            }\n        }\n        tran[i] = 0.0;\n    }\n\n    CrystalSymmList.push_back(SymmetryOperation(rot_int, tran));\n\n\n    for (std::vector<RotationMatrix>::iterator it_latsym = LatticeSymmList.begin(); \n        it_latsym != LatticeSymmList.end(); ++it_latsym) {\n\n            iat = atomclass[0][0];\n\n            for (i = 0; i < 3; ++i) {\n                for (j = 0; j < 3; ++j) {\n                    rot[i][j] = static_cast<double>((*it_latsym).mat[i][j]);\n                }\n            }\n\n            rotvec(x_rot, x[iat], rot);\n\n#ifdef _OPENMP\n#pragma omp parallel for private(jat, tran, isok, kat, x_rot_tmp, is_found, lat, tmp, diff, \\\n    i, j, itype, jj, kk, is_identity_matrix, mag, mag_rot, rot_tmp, rot_cart, mag_sym1, mag_sym2)\n#endif\n            for (ii = 0; ii < atomclass[0].size(); ++ii) {\n                jat = atomclass[0][ii];\n\n                for (i = 0; i < 3; ++i) {\n                    tran[i] = x[jat][i] - x_rot[i];\n                    tran[i] = tran[i] - nint(tran[i]);\n                }\n\n                if ((std::abs(tran[0]) > eps12 && !interaction->is_periodic[0]) ||\n                    (std::abs(tran[1]) > eps12 && !interaction->is_periodic[1]) ||\n                    (std::abs(tran[2]) > eps12 && !interaction->is_periodic[2])) continue;\n\n                is_identity_matrix = \n                    ( std::pow(rot[0][0] - 1.0, 2) + std::pow(rot[0][1], 2) + std::pow(rot[0][2], 2) \n                    + std::pow(rot[1][0], 2) + std::pow(rot[1][1] - 1.0, 2) + std::pow(rot[1][2], 2)\n                    + std::pow(rot[2][0], 2) + std::pow(rot[2][1], 2) + std::pow(rot[2][2] - 1.0, 2)\n                    + std::pow(tran[0], 2) + std::pow(tran[1], 2) + std::pow(tran[2], 2) ) < eps12;\n                if (is_identity_matrix) continue;\n\n                isok = true;\n\n                for (itype = 0; itype < nclass; ++itype) {\n\n                    for (jj = 0; jj < atomclass[itype].size(); ++jj) {\n\n                        kat = atomclass[itype][jj];\n\n                        rotvec(x_rot_tmp, x[kat], rot);\n\n                        for (i = 0; i < 3; ++i) {\n                            x_rot_tmp[i] += tran[i];\n                        }\n\n                        is_found = false;\n\n                        for (kk = 0; kk < atomclass[itype].size(); ++kk) {\n\n                            lat = atomclass[itype][kk];\n\n                            for (i = 0; i < 3; ++i) {\n                                tmp[i] = std::fmod(std::abs(x[lat][i] - x_rot_tmp[i]), 1.0);\n                                tmp[i] = std::min<double>(tmp[i], 1.0 - tmp[i]);\n                            }\n                            diff = tmp[0] * tmp[0] + tmp[1] * tmp[1] + tmp[2] * tmp[2];\n                            if (diff < tolerance * tolerance) {\n                                is_found = true;\n                                break;\n                            }\n                        }\n\n                        if (!is_found) isok = false;\n                    }\n                }\n\n                if (isok && system->lspin && system->noncollinear) {\n                    for (i = 0; i < 3; ++i) {\n                        mag[i] = system->magmom[jat][i];\n                        mag_rot[i] = system->magmom[iat][i];\n                    }\n\n                    matmul3(rot_tmp, rot, system->rlavec);\n                    matmul3(rot_cart, system->lavec, rot_tmp);\n\n                    for (i = 0; i < 3; ++i) {\n                        for (j = 0; j < 3; ++j) {\n                            rot_cart[i][j] /= (2.0 * pi);\n                        }\n                    }\n                    rotvec(mag_rot, mag_rot, rot_cart);\n\n                    // In the case of improper rotation, the factor -1 should be multiplied\n                    // because the inversion operation doesn't flip the spin.\n                    if (!is_proper(rot_cart)) {\n                        for (i = 0; i < 3; ++i) {\n                            mag_rot[i] = -mag_rot[i];\n                        }\n                    }\n\n                    mag_sym1 = (std::pow(mag[0] - mag_rot[0], 2.0)\n                        + std::pow(mag[1] - mag_rot[1], 2.0)\n                        + std::pow(mag[2] - mag_rot[2], 2.0) ) < eps6;\n\n                    mag_sym2 = (std::pow(mag[0] + mag_rot[0], 2.0)\n                        + std::pow(mag[1] + mag_rot[1], 2.0)\n                        + std::pow(mag[2] + mag_rot[2], 2.0) ) < eps6;\n\n                    if (!mag_sym1 && !mag_sym2) {\n                        isok = false;\n                    } else if (!mag_sym1 && mag_sym2 && !trev_sym_mag) {\n                        isok = false;\n                    }\n                }\n\n                if (isok) {\n#ifdef _OPENMP\n#pragma omp critical\n#endif\n                    CrystalSymmList.push_back(SymmetryOperation((*it_latsym).mat, tran));\n                }\n            }\n\n    }\n}\n\n/*\nvoid Symmetry::find_nnp_for_translation(unsigned int &ret, std::vector<SymmetryOperationTransFloat> symminfo) \n{\nint i;\n\nret = 1;\n\nstd::set<double> translation_set;\ndouble tran_tmp;\ndouble tran_numerator;\nbool is_integer;\nbool is_found;\n\ntranslation_set.clear();\n\nfor (std::vector<SymmetryOperationTransFloat>::iterator it = symminfo.begin(); it != symminfo.end(); ++it) {\n\nfor (i = 0; i < 3; ++i) {\ntran_tmp = std::abs((*it).tran[i]);\n\nif (translation_set.find(tran_tmp) == translation_set.end()) {\ntranslation_set.insert(tran_tmp);\n}\n}\n}\n\nis_found = false;\n\nwhile(1) {\n\nis_integer = true;\n\nfor (std::set<double>::iterator it = translation_set.begin(); it != translation_set.end(); ++it) {\n\ntran_numerator = (*it) * static_cast<double>(ret);\nif (std::abs(tran_numerator - static_cast<double>(nint(tran_numerator))) > tolerance) {\nis_integer = false;\nbreak;\n}\n}\n\nif (is_integer) {\nis_found = true;\nbreak;\n}\n\nif (ret > 1000) break;\n++ret;\n}\n\n\nif (!is_found) {\n// This should not happen.\nerror->exit(\"find_nnp_for_translation\", \"Cannot find nnp.\");\n}\n}\n*/\n\nvoid Symmetry::symop_in_cart(double lavec[3][3], double rlavec[3][3])\n{\n    int i, j;\n\n#ifdef _USE_EIGEN\n    Eigen::Matrix3d aa, bb, sym_tmp;\n    Eigen::Matrix3d sym_crt;\n\n    for (i = 0; i < 3; ++i) {\n        for (j = 0; j < 3; ++j) {\n            aa(i,j) = lavec[i][j];\n            bb(i,j) = rlavec[i][j];\n        }\n    }\n\n#else \n    double sym_tmp[3][3], sym_crt[3][3];\n    double tmp[3][3];\n#endif\n\n    for (int isym = 0; isym < nsym; ++isym) {\n\n        for (i = 0; i < 3; ++i) {\n            for (j = 0; j < 3; ++j) {\n#ifdef _USE_EIGEN\n                sym_tmp(i,j) = static_cast<double>(symrel_int[isym][i][j]);\n#else\n                sym_tmp[i][j] = static_cast<double>(symrel_int[isym][i][j]);\n#endif\n            }\n        }\n#ifdef _USE_EIGEN\n        sym_crt = (aa * (sym_tmp * bb)) / (2.0 * pi);\n        for (i = 0; i < 3; ++i) {\n            for (j = 0; j < 3; ++j) {\n                symrel[isym][i][j] = sym_crt(i,j);\n            }\n        }\n#else\n        matmul3(tmp, sym_tmp, rlavec);\n        matmul3(sym_crt, lavec, tmp);\n\n        for (i = 0; i < 3; ++i) {\n            for (j = 0; j < 3; ++j) {\n                symrel[isym][i][j] = sym_crt[i][j] / (2.0 * pi);\n            }\n        }\n#endif\n    }\n\n#ifdef _DEBUG\n\n    std::cout << \"Symmetry Operations in Cartesian Coordinate\" << std::endl;\n    for (int isym = 0; isym < nsym; ++isym) {\n        for (i = 0; i < 3; ++i) {\n            for (j = 0; j < 3; ++j) {\n                std::cout << std::setw(8) << symrel[isym][i][j];    \n            }\n        }\n        std::cout << std::endl;\n    }\n#endif\n}\n\nvoid Symmetry::pure_translations()\n{\n    int i;\n\n    ntran = 0;\n    for (i = 0; i < nsym; ++i) {\n        if (is_translation(symrel_int[i])) ++ntran;\n    }\n\n    natmin = system->nat / ntran;\n\n    if (ntran > 1) {\n        std::cout << \"  Given system is not primitive cell.\" << std::endl;\n        std::cout << \"  There are \" << std::setw(5) <<  ntran << \" translation operations.\" << std::endl;\n    } else {\n        std::cout << \"  Given system is a primitive cell.\" << std::endl;\n    }\n    std::cout << \"  Primitive cell contains \" << natmin << \" atoms\" << std::endl;\n\n    if (system->nat % ntran) {\n        error->exit(\"pure_translations\", \"nat != natmin * ntran. Something is wrong in the structure.\");\n    }\n\n    memory->allocate(symnum_tran, ntran);\n\n    int isym = 0;\n\n    for (i = 0; i < nsym; ++i) {\n        if (is_translation(symrel_int[i])) symnum_tran[isym++] = i;\n    }\n}\n\nvoid Symmetry::genmaps(int nat, double **x, int **map_sym, int **map_p2s, Maps *map_s2p)\n{\n    int isym, iat, jat;\n    int i, j;\n    int itype;\n    int ii, jj;\n    double xnew[3];\n    double tmp[3], diff; \n    double rot_double[3][3];\n\n    for (iat = 0; iat < nat; ++iat) {\n        for (isym = 0; isym < nsym; ++isym) {\n            map_sym[iat][isym] = -1;\n        }\n    }\n\n#ifdef  _OPENMP\n#pragma omp parallel for private(i, j, rot_double, itype, ii, iat, xnew, jj, jat, tmp, diff, isym)\n#endif\n    for (isym = 0; isym < nsym; ++isym) {\n\n        for (i = 0; i < 3; ++i) {\n            for (j = 0; j < 3; ++j) {\n                rot_double[i][j] = static_cast<double>(symrel_int[isym][i][j]);\n            }\n        }\n\n        for (itype = 0; itype < system->nclassatom; ++itype) {\n\n            for (ii = 0; ii < system->atomlist_class[itype].size(); ++ii) {\n\n                iat = system->atomlist_class[itype][ii];\n\n                rotvec(xnew, x[iat], rot_double);\n\n                for (i = 0; i < 3; ++i) xnew[i] += tnons[isym][i];\n\n                for (jj = 0; jj < system->atomlist_class[itype].size(); ++jj) {\n\n                    jat = system->atomlist_class[itype][jj];\n\n                    for (i = 0; i < 3; ++i) {\n                        tmp[i] = std::fmod(std::abs(x[jat][i] - xnew[i]), 1.0);\n                        tmp[i] = std::min<double>(tmp[i], 1.0 - tmp[i]);\n                    }\n                    diff = tmp[0] * tmp[0] + tmp[1] * tmp[1] + tmp[2] * tmp[2];\n                    if (diff < tolerance * tolerance) {\n                        map_sym[iat][isym] = jat;\n                        break;\n                    }\n                }\n                if (map_sym[iat][isym] == -1) error->exit(\"genmaps\", \"cannot find symmetry for operation # \", isym + 1);\n            }\n        }\n    }\n\n    bool *is_checked;\n    memory->allocate(is_checked, nat);\n\n    for (i = 0; i < nat; ++i) is_checked[i] = false;\n\n    jat = 0;\n    int atomnum_translated;\n    for (iat = 0; iat < nat; ++iat) {\n\n        if (is_checked[iat]) continue;\n        for (i = 0; i < ntran; ++i) {\n            atomnum_translated = map_sym[iat][symnum_tran[i]];\n            map_p2s[jat][i] = atomnum_translated;\n            is_checked[atomnum_translated] = true;\n        }\n        ++jat;\n    }\n\n    memory->deallocate(is_checked);\n\n    for (iat = 0; iat < natmin; ++iat) {\n        for (i  = 0; i < ntran; ++i) {\n            atomnum_translated = map_p2s[iat][i];\n            map_s2p[atomnum_translated].atom_num = iat;\n            map_s2p[atomnum_translated].tran_num = i;\n        }\n    }\n}\n\nbool Symmetry::is_translation(int **rot) \n{\n    bool ret;\n\n    ret = \n        rot[0][0] == 1 && rot[0][1] == 0 && rot[0][2] == 0 &&\n        rot[1][0] == 0 && rot[1][1] == 1 && rot[1][2] == 0 && \n        rot[2][0] == 0 && rot[2][1] == 0 && rot[2][2] == 1;\n\n    return ret;\n}\n\nvoid Symmetry::symop_availability_check(double ***rot, bool *flag, const int n, int &nsym_fc)\n{\n    int i, j, k;\n    int nfinite;\n\n    nsym_fc = 0;\n\n    for (i = 0; i < nsym; ++i) {\n\n        nfinite = 0;\n        for (j = 0; j < 3; ++j) {\n            for (k = 0; k < 3; ++k) {\n                if(std::abs(rot[i][j][k]) > eps) ++nfinite;\n            }\n        }\n\n        if (nfinite == 3) {\n            ++nsym_fc;\n            flag[i] = true;\n        } else {\n            flag[i] = false;\n        }\n    }\n}\n\nvoid Symmetry::print_symmetrized_coordinate(double **x)\n{\n    int i, j, k, l;\n    int isym = 0;\n    int nat = system->nat;\n    int m11, m12, m13, m21, m22, m23, m31, m32, m33;\n    int det;\n    double tran[3];\n    double **x_symm, **x_avg;\n#ifdef _USE_EIGEN\n    Eigen::Matrix3d rot;\n    Eigen::Vector3d wsi, usi, vsi, tmp;\n#else \n    double rot[3][3];\n    double wsi[3], usi[3], vsi[3], tmp[3];\n#endif\n\n    memory->allocate(x_symm, nat, 3);\n    memory->allocate(x_avg, nat, 3);\n\n    for (i = 0; i < nat; ++i) {\n        for (j = 0; j < 3; ++j) {\n            x_avg[i][j] = 0.0;\n        }\n    }\n\n    for (std::vector<SymmetryOperation>::iterator it = SymmList.begin(); it != SymmList.end(); ++it) {\n\n        ++isym;\n        std::cout << \"Symmetry No. : \" << std::setw(5) << isym << std::endl;\n\n        m11 = (*it).rot[0][0];\n        m12 = (*it).rot[0][1];\n        m13 = (*it).rot[0][2];\n        m21 = (*it).rot[1][0];\n        m22 = (*it).rot[1][1];\n        m23 = (*it).rot[1][2];\n        m31 = (*it).rot[2][0];\n        m32 = (*it).rot[2][1];\n        m33 = (*it).rot[2][2];\n\n        for (i = 0; i < 3; ++i) tran[i] = (*it).tran[i];\n\n        det = m11 * (m22 * m33 - m32 * m23)\n            - m21 * (m12 * m33 - m32 * m13)\n            + m31 * (m12 * m23 - m22 * m13);\n\n#ifdef _USE_EIGEN\n        rot(0,0) = static_cast<double>((m22 * m33 - m23 * m32) * det);\n        rot(0,1) = static_cast<double>((m23 * m31 - m21 * m33) * det);\n        rot(0,2) = static_cast<double>((m21 * m32 - m22 * m31) * det);\n        rot(1,0) = static_cast<double>((m32 * m13 - m33 * m12) * det);\n        rot(1,1) = static_cast<double>((m33 * m11 - m31 * m13) * det);\n        rot(1,2) = static_cast<double>((m31 * m12 - m32 * m11) * det);\n        rot(2,0) = static_cast<double>((m12 * m23 - m13 * m22) * det);\n        rot(2,1) = static_cast<double>((m13 * m21 - m11 * m23) * det);\n        rot(2,2) = static_cast<double>((m11 * m22 - m12 * m21) * det);\n#else\n        rot[0][0] = static_cast<double>((m22 * m33 - m23 * m32) * det);\n        rot[0][1] = static_cast<double>((m23 * m31 - m21 * m33) * det);\n        rot[0][2] = static_cast<double>((m21 * m32 - m22 * m31) * det);\n        rot[1][0] = static_cast<double>((m32 * m13 - m33 * m12) * det);\n        rot[1][1] = static_cast<double>((m33 * m11 - m31 * m13) * det);\n        rot[1][2] = static_cast<double>((m31 * m12 - m32 * m11) * det);\n        rot[2][0] = static_cast<double>((m12 * m23 - m13 * m22) * det);\n        rot[2][1] = static_cast<double>((m13 * m21 - m11 * m23) * det);\n        rot[2][2] = static_cast<double>((m11 * m22 - m12 * m21) * det);\n#endif\n\n        for (i = 0; i < nat; ++i) {\n            for (j = 0; j < 3; ++j) {   \n#ifdef _USE_EIGEN\n                wsi(j) = x[i][j] - tran[j];\n#else \n                wsi[j] = x[i][j] - tran[j];\n#endif\n            }\n\n#ifdef _USE_EIGEN\n            usi = rot * wsi;\n#else\n            rotvec(usi, wsi, rot);\n#endif\n\n            l = -1;\n\n            for (j = 0; j < nat; ++j) {\n                for (k = 0; k < 3; ++k) {\n#ifdef _USE_EIGEN\n                    vsi(k) = x[j][k];\n                    tmp(k) = std::fmod(std::abs(usi(k) - vsi(k)), 1.0); \n                    // need \"std\" to specify floating point operation\n                    // especially for Intel compiler (there was no problem in MSVC)\n                    tmp(k) = std::min<double>(tmp(k), 1.0 - tmp(k)) ;\n#else\n                    vsi[k] = x[j][k];\n                    tmp[k] = std::fmod(std::abs(usi[k] - vsi[k]), 1.0);\n                    tmp[k] = std::min<double>(tmp[k], 1.0 - tmp[k]);\n#endif\n                }\n#ifdef _USE_EIGEN\n                double diff = tmp.dot(tmp);\n#else\n                double diff = tmp[0]*tmp[0] + tmp[1]*tmp[1] + tmp[2]*tmp[2];\n#endif\n                if (diff < tolerance * tolerance) {\n                    l = j;\n                    break;\n                }\n            }\n            if (l == -1) error->exit(\"print_symmetrized_coordinate\", \"This cannot happen.\");\n\n            for (j = 0; j < 3; ++j) {\n#ifdef _USE_EIGEN\n                x_symm[l][j] = usi(j);\n#else \n                x_symm[l][j] = usi[j];\n#endif\n                /*\n                do {\n                if (x_symm[l][j] < 0.0) {\n                x_symm[l][j] += 1.0;\n                } else if (x_symm[l][j] >= 1.0) {\n                x_symm[l][j] -= 1.0;\n                }\n                } while(x_symm[l][j] < 0.0 || x_symm[l][j] >= 1.0);\n                */\n            }\n\n        }\n\n        for (i = 0; i < nat; ++i) {\n            for (j = 0; j < 3; ++j) {\n                std::cout << std::setw(20) << std::scientific << x_symm[i][j];\n            }\n            std::cout << \" ( \";\n            for (j = 0; j < 3; ++j) {\n                std::cout << std::setw(20) << std::scientific << x_symm[i][j]-x[i][j];\n            }\n            std::cout << \" )\" << std::endl;\n\n            for (j = 0; j < 3; ++j) {\n                x_avg[i][j] += x_symm[i][j];\n            }\n        }\n\n    }\n\n    for (i = 0; i < nat; ++i) {\n        for (j = 0; j < 3; ++j) {\n            x_avg[i][j] /= static_cast<double>(SymmList.size());\n        }\n    }\n\n    std::cout << \"Symmetry Averaged Coordinate\" << std::endl;\n    for (i = 0; i < nat; ++i) {\n        for (j = 0; j < 3; ++j) {\n            std::cout << std::setw(20) << std::scientific << std::setprecision(9) << x_avg[i][j];\n        }\n        std::cout << std::endl;\n    }\n    std::cout << std::endl;\n\n    std::cout.setf(std::ios::floatfield);\n\n    memory->deallocate(x_symm);\n    memory->deallocate(x_avg);\n}\n\nbool Symmetry::is_proper(double rot[3][3])\n{\n    double det;\n    bool ret;\n\n    det = rot[0][0] * (rot[1][1] * rot[2][2] - rot[2][1] * rot[1][2])\n        - rot[1][0] * (rot[0][1] * rot[2][2] - rot[2][1] * rot[0][2])\n        + rot[2][0] * (rot[0][1] * rot[1][2] - rot[1][1] * rot[0][2]);\n\n    if (std::abs(det - 1.0) < eps12) {\n        ret = true;\n    } else if (std::abs(det + 1.0) < eps12) {\n        ret = false;\n    } else {\n        error->exit(\"is_proper\", \"This cannot happen.\");\n    }\n\n    return ret;\n}\n", "meta": {"hexsha": "ece80e233471f832478ce970dd9aa9c211dca943", "size": 30794, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "alm/symmetry.cpp", "max_stars_repo_name": "dlnguyen/alamode", "max_stars_repo_head_hexsha": "f99d333262489f28a3ef4838dfbe3147dc239261", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "alm/symmetry.cpp", "max_issues_repo_name": "dlnguyen/alamode", "max_issues_repo_head_hexsha": "f99d333262489f28a3ef4838dfbe3147dc239261", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "alm/symmetry.cpp", "max_forks_repo_name": "dlnguyen/alamode", "max_forks_repo_head_hexsha": "f99d333262489f28a3ef4838dfbe3147dc239261", "max_forks_repo_licenses": ["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.2629441624, "max_line_length": 120, "alphanum_fraction": 0.4384295642, "num_tokens": 9190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2882706598431057}}
{"text": "/*\n * Copyright (c) 2019, 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// Implementation of Kalman filtering accounting for unknown inputs.\n// Please refer to: https://hal.archives-ouvertes.fr/hal-00143941/document\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include <quads/scalar_output_smoother.h>\n#include <quads/types.h>\n\n#include <Eigen/QR>\n#include <iostream>\n#include <unsupported/Eigen/MatrixFunctions>\n\nnamespace quads {\n\nvoid ScalarOutputSmoother::Update(double y, double dt) {\n  // Discretize time.\n  const Matrix4x4d A_dt = (A_ * dt).exp();\n\n  // Predict step.\n  const Vector4d x_predict = A_dt * x_;\n  const Matrix4x4d Px_predict = A_dt * Px_ * A_dt.transpose() + W_ * dt;\n\n  // Update step.\n  const double innovation = y - H_ * x_predict;\n  const double S = V_ + H_ * Px_predict * H_.transpose();\n  const Vector4d K = Px_predict * H_.transpose() / S;\n\n  x_ = x_predict + K * innovation;\n  Px_ = (Matrix4d::Identity() - K * H_) * Px_predict;\n}\n\n}  // namespace quads\n", "meta": {"hexsha": "6e7f7f62e2059df2af933278ccd077c597019b71", "size": 2833, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ros/src/quads/src/scalar_output_smoother.cpp", "max_stars_repo_name": "HJReachability/learning_feedback_linearization", "max_stars_repo_head_hexsha": "cb655ade4cfbf53f5dd19f79c943f7665666f2cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-12-18T01:51:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T14:49:31.000Z", "max_issues_repo_path": "ros/src/quads/src/scalar_output_smoother.cpp", "max_issues_repo_name": "HJReachability/learning_feedback_linearization", "max_issues_repo_head_hexsha": "cb655ade4cfbf53f5dd19f79c943f7665666f2cb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-19T22:41:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-19T22:41:51.000Z", "max_forks_repo_path": "ros/src/quads/src/scalar_output_smoother.cpp", "max_forks_repo_name": "HJReachability/learning_feedback_linearization", "max_forks_repo_head_hexsha": "cb655ade4cfbf53f5dd19f79c943f7665666f2cb", "max_forks_repo_licenses": ["BSD-3-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.9014084507, "max_line_length": 79, "alphanum_fraction": 0.6886692552, "num_tokens": 631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.288270653973943}}
{"text": "/* Copyright (C) 2011 Ion Torrent Systems, Inc. All Rights Reserved */\n\n#include <armadillo>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <cinttypes>\n\n#include \"ByteSwapUtils.h\"\n#include \"LSRowImageProcessor.h\"\n\n#define N_CORRECTION_GROUPS 8\n#define SKIP_ROWS_AT_END    10\n\n#define PINNED_HIGH_LIMIT   16373\n#define PINNED_LOW_LIMIT    10\n\n#define LSROWIMAGE_MAGIC_VALUE    0xFF115E3A\n\nusing namespace arma;\n// generate an electrical cross-talk correction from the lsrow image\n// if the file pointed to by lsimg_path does not exist, the method returns NULL\n// If lsimg_path does exist, then a correction is generated and a pointer to\n// a ChannelXTCorrection object with all the relevant information is returned\nChannelXTCorrection *LSRowImageProcessor::GenerateCorrection(const char *lsimg_path)\n{\n    uint32_t magic_value;\n    uint32_t file_version;\n    uint32_t rows = 0;\n    uint32_t cols = 0;\n    int nread;\n\n    // the lsrowimage file contains:\n    // uint32 magic value (0xFF115E3A)\n    // uint32 file version number (0+)\n    // uint32 rows\n    // uint32 columns\n    // uint16[rows*columns] high-speed and low-speed reference data, in row major order\n    //  ..with the first row in the image being a high-speed collected row\n    //    and the next row in the image being the low-speed reference for the previous high-speed row data\n\n    FILE *lsrowfile;\n\n    lsrowfile = fopen(lsimg_path,\"rb\");\n\n    // if we have trouble opening the file, just return NULL\n    if(lsrowfile == NULL)\n        return NULL;\n\n    nread = fread(&magic_value,sizeof(int32_t),1,lsrowfile);\n    if(nread != 1)\n    {\n        printf(\"Ivalid lsrowfile detected\\n\");\n        fclose(lsrowfile);\n        return NULL;\n    }\n    magic_value = BYTE_SWAP_4(magic_value);\n\n    if(magic_value != LSROWIMAGE_MAGIC_VALUE)\n    {\n        printf(\"Ivalid lsrowfile detected\\n\");\n        fclose(lsrowfile);\n        return NULL;\n    }\n\n    nread = fread(&file_version,sizeof(int32_t),1,lsrowfile);\n    if(nread != 1)\n    {\n        printf(\"Ivalid lsrowfile detected\\n\");\n        fclose(lsrowfile);\n        return NULL;\n    }\n    file_version = BYTE_SWAP_4(file_version);\n\n    if(file_version != 0)\n    {\n        printf(\"Unsupported lsrowimage file version\\n\");\n        fclose(lsrowfile);\n        return NULL;\n    }\n\n    nread = fread(&rows,sizeof(int32_t),1,lsrowfile);\n    if(nread != 1)\n    {\n        printf(\"Ivalid lsrowfile detected\\n\");\n        fclose(lsrowfile);\n        return NULL;\n    }\n    rows = BYTE_SWAP_4(rows);\n\n    nread = fread(&cols,sizeof(int32_t),1,lsrowfile);\n    if(nread != 1)\n    {\n        printf(\"Ivalid lsrowfile detected\\n\");\n        fclose(lsrowfile);\n        return NULL;\n    }\n    cols = BYTE_SWAP_4(cols);\n\n    int tot_pts = rows*cols;\n\n    printf(\"reading lsrowfile with %d rows and %d columns\\n\",rows,cols);\n    uint16_t *img = new uint16_t[tot_pts];\n\n    nread = fread(img,sizeof(uint16_t),tot_pts,lsrowfile);\n    if(nread != tot_pts)\n    {\n        printf(\"Ivalid lsrowfile detected\\n\");\n        delete [] img;\n        fclose(lsrowfile);\n        return NULL;\n    }\n\n    // byte swap the image\n    for(int i=0;i < tot_pts;i++)\n        img[i] = BYTE_SWAP_2(img[i]);\n\n    // this version of the code generates a correction for columns-modulo eight. (it generates a correction\n    // for columns that belong to one of eight different groups, where membership is determined from \n    // (column % 8))\n    ChannelXTCorrection *xtptr = new ChannelXTCorrection();\n    float *pvects = xtptr->AllocateVectorStorage(N_CORRECTION_GROUPS,nLen);\n    float **vect_ptrs = xtptr->AllocateVectorPointerStorage(N_CORRECTION_GROUPS);\n    xtptr->SetVectorIndicies(indicies,nLen);\n\n    bool correction_valid = true;\n\n    for(int i=0;i < N_CORRECTION_GROUPS;i++)\n    {\n        vect_ptrs[i] = pvects+nLen*i;\n        if (GenerateGroupCorrection(i,vect_ptrs[i],rows,cols,img) == false)\n        {\n            correction_valid = false;\n            break;\n        }\n    }\n\n    delete [] img;\n    fclose(lsrowfile);\n\n    if(!correction_valid)\n    {\n        printf(\"Unable to compute valid correction\\n\");\n        delete xtptr;\n        return NULL;\n    }\n\n    return xtptr;\n}\n\n// generates a set of correction coefficients for a group of columns\n// this basically solves the matrix equation Ax=B for x, where A are the measured high-speed \n// pixel values and B are the low-speed measured pixels values.  The special image collected on the PGM\n// contains pairs of high-speed and low-speed rows for the same pixels that can be used to populate\n// these matricies\n// \n// As written, A is a nLen column matrix, with many rows in it (one for each example pixel we extract from the data)\n// and B is an nLen row vector, again with one row per example pixel we extract from the data.\n// When the equation is solved, both sides are multiplied by A-tranpose, which turns the left side into a square\n// nLen by nLen matrix, and the rhs into an nLen row vector.  In order to facilitate ease of adding example pixels to\n// the equations sequentially, A and B are not computed, and instead lhs = (A-transpose x A) and rhs = (A-transpose x B)\n// are computed directly from the low-level data, and the solution is determined from lhs x = rhs\nbool LSRowImageProcessor::GenerateGroupCorrection(int group_num,float *vect_output,int rows,int cols,uint16_t *img)\n{\n    double lhs[nLen*nLen];\n    double rhs[nLen];\n\n    memset(lhs,0,sizeof(lhs));\n    memset(rhs,0,sizeof(rhs));\n\n    // the image contains some invalid rows at the end that should be skipped\n    int row_limit = rows - SKIP_ROWS_AT_END;\n\n    int mcnt = 0;\n\n    for(int column = group_num;column < cols;column += N_CORRECTION_GROUPS)\n    {\n        // make sure we have enough space on the left and right-hand sides to use this particular column\n        if (((column + indicies[0]) < 0) || ((column + indicies[nLen-1]) >= cols))\n            continue;\n\n        // every other row is the start of a pair of rows, one high-speed and one reference\n        for(int row = 0;row < row_limit;row += 2)\n        {\n            double amat[nLen];\n            bool skip = false;\n\n            uint16_t *hsrow = &img[row*cols];\n            uint16_t *lsrow = &img[(row+1)*cols];\n\n            // get the data points that are to be added to the matrix, making sure to filter out entries\n            // that might reference pinned values\n            for(int i=0;i < nLen;i++)\n            {\n                uint16_t temp = hsrow[indicies[i]+column];\n\n                if((temp < PINNED_LOW_LIMIT) || (temp > PINNED_HIGH_LIMIT))\n                {\n                    skip = true;\n                    break;\n                }\n                amat[i] = (double)temp;\n\n                temp = lsrow[indicies[i]+column];\n                if((temp < PINNED_LOW_LIMIT) || (temp > PINNED_HIGH_LIMIT))\n                {\n                    skip = true;\n                    break;\n                }\n            }\n\n            // if everything checks out, add this data into the matrix equation\n            if(!skip)\n            {\n                mcnt++;    \n                AccumulateMatrixData(lhs,rhs,amat,(double)(lsrow[column]));\n            }\n        }\n    }\n\n\n    Mat<double> lhs_matrix(nLen,nLen);\n    Col<double> rhs_vector(nLen);\n    Col<double> coeffs(nLen);\n    bool result_ok = true;\n\n    for(int col=0;col < nLen;col++)\n        for(int row=0;row <= col;row++)\n        {\n            lhs_matrix(row,col) = lhs[row*nLen+col];\n            lhs_matrix(col,row) = lhs[row*nLen+col];\n        }\n\n    for(int row=0;row < nLen;row++)\n        rhs_vector(row) = rhs[row];\n\n    try {\n      //LaSpdMatFactorize(lhs_matrix,lhs_matrix_fact);\n      //LaLinearSolve(lhs_matrix_fact,coeffs,rhs_vector);\n      coeffs = solve(lhs_matrix,rhs_vector);\n    }\n    catch (std::runtime_error& le) {\n        result_ok = false;\n        coeffs.zeros(nLen);\n    }\n\n    // make sure derived coefficients are valid\n    for(int row=0;row < nLen;row++)\n        if(std::isnan(coeffs(row)))\n        {\n            result_ok = false;\n            break;\n        }\n        else\n            vect_output[row] = coeffs(row);\n\n    printf(\"group %d correction coefficients: \",group_num);\n    for(int row=0;row < nLen;row++)\n        printf(\"%11.8lf \",coeffs(row));\n\n    printf(\"\\n\");\n\n    return(result_ok);\n}\n\n// Adds one example pixel's data into the lhs and rhs matrix and vector\nvoid LSRowImageProcessor::AccumulateMatrixData(double *lhs,double *rhs,double *amat,double bval)\n{\n    for(int col=0;col < nLen;col++)\n        for(int row=0;row <= col;row++)\n            lhs[row*nLen+col] += amat[row]*amat[col];\n\n    for(int row=0;row < nLen;row++)\n        rhs[row] += amat[row]*bval;\n}\n\n", "meta": {"hexsha": "15e3efaebc0461a78c1e7100d189ef51ebd9eae6", "size": 8652, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Analysis/Image/LSRowImageProcessor.cpp", "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/Image/LSRowImageProcessor.cpp", "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/Image/LSRowImageProcessor.cpp", "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": 31.2346570397, "max_line_length": 120, "alphanum_fraction": 0.6230929265, "num_tokens": 2187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.28827064810478026}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2012-2016 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#ifndef NMIII_APCG_HH\n#define NMIII_APCG_HH\n\n#include <numeric>\n#include <string>\n\n#include <boost/circular_buffer.hpp>\n#include <boost/timer/timer.hpp>\n\n#include \"dune/common/timer.hh\"\n#include \"dune/istl/istlexception.hh\"\n#include \"dune/istl/operators.hh\"\n#include \"dune/istl/preconditioners.hh\"\n#include \"dune/istl/scalarproducts.hh\"\n#include \"dune/istl/solvers.hh\"\n\n#include \"linalg/symmetricOperators.hh\"\n#include \"utilities/detailed_exception.hh\"\n#include \"utilities/geometric_sequence.hh\"\n#include \"utilities/scalar.hh\"\n\nnamespace Kaskade\n{\n  /**\n   * \\ingroup iterative\n   * \\brief Whether a preconditioner needs zero initialized result vector or not.\n   * \n   * For a couple of known preconditioners, this function returns the actual information.\n   * For unknown preconditioners, it errs on the conservative side, i.e. reports true.\n   * \n   * The function is moderately expensive, hence don't use it inside of loops.\n   */\n  template <class Domain, class Range>\n  bool requiresInitializedInput(Dune::Preconditioner<Domain,Range> const* p)\n  {\n    if (dynamic_cast<Dune::Richardson<Domain,Range> const*>(p))\n      return false;\n    if (auto sp = dynamic_cast<SymmetricPreconditioner<Domain,Range> const*>(p))\n      return sp->requiresInitializedInput();\n    return true;\n  }\n  \n  /**\n   * \\ingroup iterative\n   * \\brief Interface for IterateType::PCG termination criterion policy classes\n   * \\tparam R a floating point type for real numbers\n   */\n  template <class R>\n  class PCGTerminationCriterion \n  {\n  public:\n    /**\n     * \\brief real field type\n     */\n    typedef R Real;\n    \n    /**\n     * \\brief re-initializes the termination criterion for a new IterateType::CG run\n     */\n    virtual void clear() = 0;\n    \n    /**\n     * \\brief set requested tolerance\n     * \n     * \\param tol the requested tolerance (nonnegative)\n     */\n    virtual PCGTerminationCriterion<R>& tolerance(Real tol) = 0;\n    \n    /**\n     * \\brief supplies energy of step to the termination criterion\n     * \\param gamma2 the energy of the step\n     */\n    virtual void step(Real gamma2) = 0;\n    \n    /**\n     * \\brief supplies the preconditioned residual to the termination criterion\n     * \\param sigma the preconditioned residual norm\n     */\n    virtual void residual(Real sigma) = 0;\n    \n    /**\n     * \\brief termination decision\n     * \\return true if the iteration has reached the required accuracy\n     */\n    virtual operator bool() const = 0;\n  };\n  \n  /**\n   * \\ingroup iterative\n   * \\brief TerminationCriterion based on an absolute energy error estimate\n   * \n   * This termination criterion assumes the error reduction occurs in two phases: First a smoothing phase where\n   * \\f$ \\epsilon_k^2 \\approx a^2/(1+\\sqrt{k})^2 + b^2 \\f$, and a linear convergence phase with \\f$ \\epsilon_k \\approx q^k \\epsilon_0 \\f$.\n   * The termination criterion tries to fit the model parameters \\f$ a, b, q \\f$ and to decide where the crossover of both \n   * phases occurs. Based on this decision, the energy error \\f$ \\epsilon_k \\f$ is estimated as \\f$ [\\epsilon_k] \\f$.\n   * \n   * For greater robustnes, the actual error estimate used is \\f[ [\\epsilon_{k-l}]^2 := [\\epsilon_k]^2 + \\sum_{i=k-l}^{k-1} \\gamma_i^2. \\f] with\n   * \\f$ \\gamma_i = \\|u_{i+1}-u_i\\|_A \\f$.The lookahead value \\f$ l \\f$ can be set using \\ref lookahead.\n   * \n   * \\tparam R the real field type. Currently instantiated for float and double in file apcg.cpp.\n   */\n  template <class R>\n  class PCGEnergyErrorTerminationCriterion: public PCGTerminationCriterion<R> {\n  public:\n    typedef R Real;\n    \n    /**\n     * \\brief constructor\n     * \n     * The pcg iteration is terminated as soon as either \\f$ [\\epsilon] \\le \\mathrm{atol} \\f$ or \n     * the number of iterations exceeds the limit maxit.\n     * \n     * \\param atol the absolute error tolerance for termination\n     * \\param maxit the maximum number of iterations\n     */\n    PCGEnergyErrorTerminationCriterion(Real atol, int maxit);\n    \n    /**\n     * \\brief re-initializes the termination criterion for a new IterateType::CG run\n     */\n    virtual void clear();\n    \n    /**\n     * \\brief set requested absolute tolerance\n     * \n     * \\param atol the requested tolerance (nonnegative)\n     */\n    virtual PCGEnergyErrorTerminationCriterion<Real>& tolerance(Real atol);\n    \n    /**\n     * \\brief set requested lookahead value\n     * \n     * \\param lah the requested lookahead (nonnegative)\n     * \n     * The default value is 6.\n     */\n     PCGEnergyErrorTerminationCriterion<Real>& lookahead(int lah);\n    \n    /**\n     * \\brief supplies energy of step to the termination criterion\n     * \\param gamma2 the energy \\f$ \\gamma^2 = \\| u_{k+1}-u_k \\|_A^2 \\f$ of the step\n     */\n    virtual void step(Real gamma2);\n    \n    /**\n     * \\brief supplies the preconditioned residual to the termination criterion\n     * \\param sigma the preconditioned residual norm\n     */\n    virtual void residual(Real sigma) {}\n    \n    /**\n     * \\brief termination decision\n     * \\return true if the iteration has reached the required accuracy\n     */\n    virtual operator bool() const;\n    \n    /**\n     * \\brief returns the estimated absolute energy error\n     */\n    Real error() const;\n    \n    std::vector<Real> const& gamma2() const {return gammas2; }\n    \n  private:\n    Real tol;\n    int maxit;\n    // squared gammas\n    std::vector<Real> gammas2;\n    int lookah;\n  };\n  \n\n /**\n  * \\ingroup iterative\n  * \\brief preconditioned conjugate gradient method\n  * \n  * This implements a preconditioned IterateType::CG iteration for an operator \\f$ A: X\\to X^* \\f$, preconditioned by a\n  * preconditioner \\f$ B^{-1}: X^* \\to X \\f$. The termination is policy-based.\n  * \n  * The implementation follows Deuflhard/Weiser, Section 5.3.3.\n  * \n  * \\tparam X the type of vectors from the primal space\n  * \\tparam Xstar the type of vectors from the dual space\n  * \n  * \\see PCGEnergyErrorTerminationCriterion\n  */\n  template<class X, class Xstar>\n  class Pcg : public Dune::InverseOperator<X,Xstar> {\n  public:\n    /// \\brief The domain type of the operator to be inverted.\n    typedef X domain_type;\n    /// \\brief The range type of the operator to be inverted.\n    typedef Xstar range_type;\n    /// \\brief The field type of the operator to be inverted.\n    typedef typename X::field_type field_type;\n    \n    /**\n     * \\brief the real field type corresponding to field_type\n     */\n    typedef typename ScalarTraits<field_type>::Real Real;\n\n    /** \n     * \\brief Set up conjugate gradient solver.\n     * \n     * \\param op the operator\n     * \\param prec the preconditioner\n     * \\param terminate the termination criterion. The object has to exist during the lifetime of the pcg object as it is referenced.\n     * \\param verbose controls the verbosity of logging to std::cout. 0 means no output at all (default). Values in 0,1,2 are valid.\n     */\n    Pcg(SymmetricLinearOperator<X,Xstar>& op_, SymmetricPreconditioner<X,Xstar>& prec_, \n        PCGTerminationCriterion<Real>& terminate_, int verbose_=0) : \n      proxyOp(op_,zeroDp), op(op_), \n      proxyPrec(prec_,zeroDp), prec(prec_), \n      terminate(terminate_), verbose(verbose_), requiresInit(requiresInitializedInput(&prec))\n    {\n// Do we need this in Kaskade7? \n//         dune_static_assert( static_cast<int>(L::category) == static_cast<int>(P::category),\n//                             \"L and P must have the same category!\");\n//         dune_static_assert( static_cast<int>(L::category) == static_cast<int>(SolverCategory::sequential),\n//                             \"L must be sequential!\");\n    }\n\n    /** \n     * \\brief Set up conjugate gradient solver.\n     * \n     * \\param op the operator\n     * \\param prec the preconditioner\n     * \\param dp the dual pairing with respect to which the operator is symmetric\n     * \\param terminate the termination criterion. The object has to exist during the lifetime of the pcg object as it is referenced.\n     * \\param verbose controls the verbosity of logging to std::cout. 0 means no output at all (default). Values in 0,1,2 are valid.\n     */\n    Pcg(Dune::LinearOperator<X,Xstar>& op_, Dune::Preconditioner<X,Xstar>& prec_, DualPairing<X,Xstar> const& dp_,\n        PCGTerminationCriterion<Real>& terminate_, int verbose_=0) : \n      proxyOp(op_,dp_), op(proxyOp), \n      proxyPrec(prec_,dp_), prec(proxyPrec), \n      terminate(terminate_), verbose(verbose_), requiresInit(requiresInitializedInput(&prec))\n    {    }\n    \n    /**\n     * \\brief Apply inverse operator by performing a number of IterateType::PCG iterations.\n     * \n     * \\param u the initial value (starting iterate)\n     * \\param b the right hand side (which will not be modified)\n     */\n    virtual void apply (X& u, Xstar& b, Dune::InverseOperatorResult& res) {\n      res.clear();                // clear solver statistics\n      terminate.clear();          // clear termination criterion\n      Dune::Timer watch;          // start a timer\n      \n      boost::timer::cpu_timer mvTimer;\n      mvTimer.stop();\n      boost::timer::cpu_timer apTimer;\n      apTimer.stop();\n      boost::timer::cpu_timer prTimer;\n      prTimer.stop();\n    \n      Xstar r(b); \n      op.applyscaleadd(-1,u,r);  // r = b-Au\n\n      // Keeping rq and q in unique_ptr allows efficient computation of q = rq + beta*q below by swapping the pointers.\n      // More elegant would be a swap method directly on X, but this is hard to implement as there is no swap either \n      // for boost::fusion vectors nor for Dune::BlockVectors. Even more elegant would be a loop fusion expression\n      // framework for BLAS level 1 operations.\n      std::unique_ptr<X> rq(new X(u)); *rq = 0;\n      prec.apply(*rq,r); // rq = B^{-1} r\n      \n      std::unique_ptr<X> q(new X(*rq));\n\n      X Aq(b);\n    \n\n      // some local variables\n      field_type alpha,beta,sigma,gamma;\n      sigma = op.dp(*rq,r); // preconditioned residual norm squard\n      terminate.residual(ScalarTraits<field_type>::real(sigma));\n      double const sigma0 = std::abs(sigma);\n      \n      // Check for trivial case\n      if (sigma0 == 0)\n        return;\n\n      if (verbose>0) {            // printing\n        std::cout << \"=== Kaskade7 IterateType::PCG\" << std::endl;\n        if (verbose>1) {\n          this->printHeader(std::cout);\n          this->printOutput(std::cout,0.0,sigma0);\n        }\n      }\n\n      // the loop\n      int i=1; \n      for ( ; true; i++ ) {\n        // minimize in given search direction p\n        mvTimer.resume();\n        field_type qAq = op.applyDp(*q,Aq);             // compute Aq = A*q and qAq = <q,A*q>\nif (std::isnan(qAq)) std:: cerr << \"qAq is nan\\n\";        \n        mvTimer.stop();\n        \t\n\tif (std::abs(qAq) < 1e-28*sigma) \n\t  break; // oops.\n\t  \n        if (qAq <= 0)\n          throw NonpositiveMatrixException(\"encountered nonpositive energy product \" + std::to_string(qAq) + \" vs sigma \" + std::to_string(sigma) + \" in IterateType::PCG.\",__FILE__,__LINE__);\n          \n        alpha = sigma/qAq;\n        apTimer.resume();\n        u.axpy(alpha,*q);\n        apTimer.stop();\n        gamma = sigma*alpha;\n\tterminate.step(ScalarTraits<field_type>::real(gamma));\n\tresDebug.push_back(std::sqrt(sigma));\n\n        // convergence test\n        if (terminate)\n\t  break;\n\n        apTimer.resume();\n        r.axpy(-alpha,Aq); // r = r - alpha*A*q\n        apTimer.stop();\n        \n        prTimer.resume();\n        if (requiresInit)\n          *rq = 0;\n        double sigmaNew = prec.applyDp(*rq,r); // compute rq = B^{-1}r and <rq,r>\n        prTimer.stop();\n\n        // determine new search direction\n\tterminate.residual(ScalarTraits<field_type>::real(sigmaNew));\n        if (verbose>1)             // print\n          this->printOutput(std::cout,static_cast<double>(i),std::abs(sigmaNew),std::abs(sigma));\n\n\t// convergence check to prevent division by zero if we obtained an exact solution\n\t// (which may happen for low dimensional systems)\n\tif (std::abs(sigmaNew) < 1e-28*sigma0)\n\t  break;\n\t\n        beta = sigmaNew/sigma;\n        sigma = sigmaNew;\n        apTimer.resume();\n        rq->axpy(beta,*q); // compute q = rq + beta*q\n        std::swap(rq,q);\n        apTimer.stop();\n      }\n\n      if (verbose>0)                // printing for non verbose\n        this->printOutput(std::cout,static_cast<double>(i),std::abs(sigma));\n\n      res.iterations = i;               // fill statistics\n      res.reduction = std::sqrt(std::abs(sigma)/sigma0);\n      res.conv_rate  = pow(res.reduction,1.0/i);\n      res.elapsed = watch.elapsed();\n\n      if (verbose>0)                 // final print \n      {\n        std::cout << \"=== rate=\" << res.conv_rate\n                  << \", T=\" << res.elapsed\n                  << \", TIT=\" << res.elapsed/i\n                  << \", IT=\" << i << std::endl;\n        \n        std::cout << \"Matrix-Vector time: \" << mvTimer.format() \n                  << \"vector ops        : \" << apTimer.format() \n                  << \"preconditioner    : \" << prTimer.format() << '\\n';\n      } \n  }\n\n    /** \n     * \\brief Apply inverse operator with given tolerance.\n     * \n     * This method is equivalent to setting first the tolerance in the termination criterion, then calling apply().\n     */\n  virtual void apply (X& x, X& b, double tol, Dune::InverseOperatorResult& res) {\n    terminate.tolerance(tol);\n    (*this).apply(x,b,res);\n  }\n\n  private:\n    // The solver may be constructed with either symmetric operator/preconditioner interface provided,\n    // or with Dune interfaces provided. The implementation relies on the symmetric interface\n    // in order to exploit performance gains with simultaneous evaluation of matrix-vector products\n    // and dual pairings.\n    // Therefore we hold \"working\" references to symmetric operator/preconditioners. Those reference\n    // either the provided ones, or wrapper objects relaying the evaluation to provided Dune interfaces.\n    // For the second case, we hold the (small) wrapper objects ourselves. In the first case, those\n    // wrapper objects have to be initialized correctly (even though they are never accessed). For this \n    // we need a dual pairing, hence the dummy zeroDp.\n    ZeroDualPairing<X,Xstar>                zeroDp;  // just a dummy\n    \n    SymmetricLinearOperatorWrapper<X,Xstar> proxyOp; // proxy in case a Dune::LinearOperator is provided\n    SymmetricLinearOperator<X,Xstar>& op;  // working reference to operator\n\n    SymmetricPreconditionerWrapper<X,Xstar>  proxyPrec; // proxy in case a Dune::Preconditioner is provided\n    SymmetricPreconditioner<X,Xstar>&        prec;      // working reference to preconditioner\n    \n    PCGTerminationCriterion<Real>& terminate;\n    int verbose;\n    bool requiresInit;\n    \n    std::vector<double> resDebug;\n  };\n} // namespace Kaskade\n#endif\n", "meta": {"hexsha": "2c35d90230d8f5a01fd95b0ce3fea785c42f66b5", "size": 15604, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/linalg/apcg.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/linalg/apcg.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/linalg/apcg.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 37.690821256, "max_line_length": 191, "alphanum_fraction": 0.6127915919, "num_tokens": 3880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.28819909939536564}}
{"text": "/**\n * @file origin.cpp\n * @brief Parse origin from xml string\n *\n * @author Levi Armstrong\n * @date September 1, 2019\n * @version TODO\n * @bug No known bugs\n *\n * @copyright Copyright (c) 2019, Southwest Research Institute\n *\n * @par License\n * Software License Agreement (Apache License)\n * @par\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 * @par\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 <tesseract_common/macros.h>\nTESSERACT_COMMON_IGNORE_WARNINGS_PUSH\n#include <stdexcept>\n#include <tesseract_common/utils.h>\n#include <Eigen/Geometry>\n#include <vector>\n#include <boost/algorithm/string.hpp>\n#include <tinyxml2.h>\nTESSERACT_COMMON_IGNORE_WARNINGS_POP\n\n#include <tesseract_urdf/origin.h>\n\nEigen::Isometry3d tesseract_urdf::parseOrigin(const tinyxml2::XMLElement* xml_element, int /*version*/)\n{\n  Eigen::Isometry3d origin = Eigen::Isometry3d::Identity();\n\n  if (xml_element->Attribute(\"xyz\") == nullptr && xml_element->Attribute(\"rpy\") == nullptr &&\n      xml_element->Attribute(\"wxyz\") == nullptr)\n    std::throw_with_nested(std::runtime_error(\"Origin: Error missing required attributes 'xyz' and 'rpy' and/or 'wxyz' \"\n                                              \"for origin element!\"));\n\n  std::string xyz_string, rpy_string, wxyz_string;\n  tinyxml2::XMLError status = tesseract_common::QueryStringAttribute(xml_element, \"xyz\", xyz_string);\n  if (status != tinyxml2::XML_NO_ATTRIBUTE && status != tinyxml2::XML_SUCCESS)\n    std::throw_with_nested(std::runtime_error(\"Origin: Failed to parse attribute 'xyz'!\"));\n\n  if (status != tinyxml2::XML_NO_ATTRIBUTE)\n  {\n    std::vector<std::string> tokens;\n    boost::split(tokens, xyz_string, boost::is_any_of(\" \"), boost::token_compress_on);\n    if (tokens.size() != 3 || !tesseract_common::isNumeric(tokens))\n      std::throw_with_nested(std::runtime_error(\"Origin: Failed to parse attribute 'xyz' string!\"));\n\n    double x{ 0 }, y{ 0 }, z{ 0 };\n    // No need to check return values because the tokens are verified above\n    tesseract_common::toNumeric<double>(tokens[0], x);\n    tesseract_common::toNumeric<double>(tokens[1], y);\n    tesseract_common::toNumeric<double>(tokens[2], z);\n\n    origin.translation() = Eigen::Vector3d(x, y, z);\n  }\n\n  if (xml_element->Attribute(\"wxyz\") == nullptr)\n  {\n    status = tesseract_common::QueryStringAttribute(xml_element, \"rpy\", rpy_string);\n    if (status != tinyxml2::XML_NO_ATTRIBUTE && status != tinyxml2::XML_SUCCESS)\n      std::throw_with_nested(std::runtime_error(\"Origin: Failed to parse attribute 'rpy'!\"));\n\n    if (status != tinyxml2::XML_NO_ATTRIBUTE)\n    {\n      std::vector<std::string> tokens;\n      boost::split(tokens, rpy_string, boost::is_any_of(\" \"), boost::token_compress_on);\n      if (tokens.size() != 3 || !tesseract_common::isNumeric(tokens))\n        std::throw_with_nested(std::runtime_error(\"Origin: Failed to parse attribute 'rpy' string!\"));\n\n      double r{ 0 }, p{ 0 }, y{ 0 };\n      // No need to check return values because the tokens are verified above\n      tesseract_common::toNumeric<double>(tokens[0], r);\n      tesseract_common::toNumeric<double>(tokens[1], p);\n      tesseract_common::toNumeric<double>(tokens[2], y);\n\n      Eigen::AngleAxisd rollAngle(r, Eigen::Vector3d::UnitX());\n      Eigen::AngleAxisd pitchAngle(p, Eigen::Vector3d::UnitY());\n      Eigen::AngleAxisd yawAngle(y, Eigen::Vector3d::UnitZ());\n\n      Eigen::Quaterniond rpy = yawAngle * pitchAngle * rollAngle;\n\n      origin.linear() = rpy.toRotationMatrix();\n    }\n  }\n  else\n  {\n    status = tesseract_common::QueryStringAttribute(xml_element, \"wxyz\", wxyz_string);\n    if (status != tinyxml2::XML_NO_ATTRIBUTE && status != tinyxml2::XML_SUCCESS)\n      std::throw_with_nested(std::runtime_error(\"Origin: Failed to parse attribute 'wxyz'!\"));\n\n    if (status != tinyxml2::XML_NO_ATTRIBUTE)\n    {\n      std::vector<std::string> tokens;\n      boost::split(tokens, wxyz_string, boost::is_any_of(\" \"), boost::token_compress_on);\n      if (tokens.size() != 4 || !tesseract_common::isNumeric(tokens))\n        std::throw_with_nested(std::runtime_error(\"Origin: Failed to parse attribute 'wxyz' string!\"));\n\n      double qw{ 0 }, qx{ 0 }, qy{ 0 }, qz{ 0 };\n      // No need to check return values because the tokens are verified above\n      tesseract_common::toNumeric<double>(tokens[0], qw);\n      tesseract_common::toNumeric<double>(tokens[1], qx);\n      tesseract_common::toNumeric<double>(tokens[2], qy);\n      tesseract_common::toNumeric<double>(tokens[3], qz);\n\n      Eigen::Quaterniond q(qw, qx, qy, qz);\n      q.normalize();\n\n      origin.linear() = q.toRotationMatrix();\n    }\n  }\n  return origin;\n}\n", "meta": {"hexsha": "eca90590a149fd2b9e7678facfa8ffba1aeb2644", "size": 5076, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tesseract_urdf/src/origin.cpp", "max_stars_repo_name": "jf---/tesseract", "max_stars_repo_head_hexsha": "d04e9ddf2f940e780d1c8262eca7a6c8f5db2260", "max_stars_repo_licenses": ["BSD-2-Clause", "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": "tesseract_urdf/src/origin.cpp", "max_issues_repo_name": "jf---/tesseract", "max_issues_repo_head_hexsha": "d04e9ddf2f940e780d1c8262eca7a6c8f5db2260", "max_issues_repo_licenses": ["BSD-2-Clause", "Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-03-25T17:43:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-25T17:43:35.000Z", "max_forks_repo_path": "tesseract_urdf/src/origin.cpp", "max_forks_repo_name": "jf---/tesseract", "max_forks_repo_head_hexsha": "d04e9ddf2f940e780d1c8262eca7a6c8f5db2260", "max_forks_repo_licenses": ["BSD-2-Clause", "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.608, "max_line_length": 120, "alphanum_fraction": 0.689322301, "num_tokens": 1304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.28805922129003864}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2002-2015 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#ifndef COARSENING_HH\n#define COARSENING_HH\n\n\n#include <boost/timer/timer.hpp>\n#include <boost/type_traits/remove_pointer.hpp>\n#include <boost/type_traits/remove_reference.hpp>\n\n#include <boost/fusion/algorithm.hpp>\n#include <boost/fusion/sequence.hpp>\n\n#include \"fem/errorest.hh\"\n#include \"fem/embedded_errorest.hh\"\n#include \"fem/fetransfer.hh\"\n#include \"fem/firstless.hh\"\n#include \"fem/fixfusion.hh\"\n#include \"fem/iterate_grid.hh\"\n#include \"utilities/power.hh\"\n\n#include \"linalg/dynamicMatrix.hh\"\n\nnamespace Kaskade\n{\n  namespace CoarseningDetail\n  {\n\n    using namespace boost::fusion;\n    \n    // A class representing a local projector for a given FE space\n    template <class Sp>\n    struct Projector\n    {\n      typedef Sp Space;\n      \n      Space const*                                                  space;  // pointer to FE space\n      std::vector<size_t>                                           gidx;   // global indices\n      DynamicMatrix<Dune::FieldMatrix<typename Space::Scalar,1,1>>  q;      // stores a factor of the projection matrix Q Q^T.\n\n      // these are declared here to be used in GetLocalTransferProjection - avoid frequent reallocations\n      DynamicMatrix<Dune::FieldMatrix<typename Space::Scalar,1,1>> pLocal;\n      std::vector<int>                                             idx; \n    };\n    \n    // A functor creating local projectors for a given FE space\n    struct CreateProjection\n    {\n      template <class T> struct result {};\n      \n      template <class SpacePtr>\n      struct result<CreateProjection(SpacePtr)> {\n        typedef typename boost::remove_pointer<typename boost::remove_reference<SpacePtr>::type>::type Space;\n        typedef Projector<Space> type;\n      };\n      \n      template <class SpacePtr>\n      typename result<CreateProjection(SpacePtr)>::type operator()(SpacePtr space) const\n      {\n        typename result<CreateProjection(SpacePtr)>::type p;\n        p.space = space;\n        return p;\n      }\n    };\n\n\n    // A functor filling a local projector with actual data for a given cell\n    template <class CellPointer>\n    struct GetLocalTransferProjection\n    {\n      // father points to the father cell,\n      // children contains pointer to its children\n      GetLocalTransferProjection(CellPointer father_, std::vector<CellPointer> const& children_): father(father_), children(children_)\n      { }\n\n      template <class Projector>\n      void operator()(Projector& p) const\n      {\n\ttypedef typename Projector::Space Space;\n\t// We could use LocalTransfer here, but this is conceptual and computational overkill. It supports different FE spaces (we need only one here)\n\t// and creates new shape function sets just in case the cell vanishes on coarsening. We do the projection here before coarsening...\n\t// Moreover we know here that all children of the father cell are leafs.\n\n        // Following a direct implementation exploiting our a priori knowledge for simplicity and performance.\n        // Obtain all global indices associated to leaf cells within this father cell\n        p.gidx.clear();\n        for (int i=0; i<children.size(); ++i) \n        {\n          auto gi = p.space->mapper().globalIndices(*children[i]);\n          p.gidx.insert(p.gidx.end(),gi.begin(),gi.end());\n        }\n        // global indices can be duplicate - make unique\n        std::sort(p.gidx.begin(),p.gidx.end());\n        p.gidx.erase(std::unique(p.gidx.begin(),p.gidx.end()),p.gidx.end());\n        \n        // Step through all children and obtain the prolongation matrix. Scatter this to the \n        // prolongation matrix P for all children's degrees of freedom.\n        p.q.setSize(p.gidx.size(),p.space->mapper().shapefunctions(*father).size());\n//        p.q = 0 // causes compilation error with dune-2.4.0 and clang++ on OS X (Darwin)\n        p.q.fill(0);\n        typedef typename Space::Grid Grid;\n        typedef typename Space::Scalar   Scalar;\n        int const sfComponents = Space::sfComponents;\n        DynamicMatrix<Dune::FieldMatrix<Scalar,sfComponents,1>> afValues; // declare out of loop to prevent frequent reallocations\n        std::vector<Dune::FieldVector<typename Grid::ctype,Grid::dimension> > iNodes; // declare out of loop to prevent frequent reallocations\n        for (int i=0; i<children.size(); ++i) \n        {\n          // Compute the mapping of global indices on the child to the set of global indices on all children.\n          auto gi = p.space->mapper().globalIndices(*children[i]);\n          p.idx.resize(gi.size());\n          for (int j=0; j<gi.size(); ++j) \n            p.idx[j] = std::lower_bound(p.gidx.begin(),p.gidx.end(),gi[j]) - p.gidx.begin();\n          \n          // Compute local prolongation matrix p.pLocal. As father and child spaces are the same, we can use the same shape function set\n          // (assuming that the type of cell doesn't change...).\n          auto const& sfs = p.space->mapper().shapefunctions(*children[i]);\n          localProlongationMatrix(*p.space,children[i],*p.space,father,p.pLocal,sfs,sfs);\n          \n          // Enter prolongation values on this child into the whole prolongation matrix for all children\n          for(size_t k=0; k<p.idx.size(); ++k)\n            for(int j=0; j<p.q.M(); ++j)\n              p.q[p.idx[k]][j] = p.pLocal[k][j];\n        }\n        \n        // Now the projection onto a coarser space is P P^+, where P^+, the pseudoinverse of P, is the restriction matrix.\n        // Note that this formulation of the (not uniquely defined restriction) is different from the interpolation-based\n        // restriction as obtained from LocalTransfer. Nevertheless, both make sense and both appear to work very similar.\n        // In fact one might argue that the pseudoinverse formulation here makes even more sense, as it leads to a \n        // least-squares approximation of the fine grid solution by the coarse grid restriction. \"Least squares\" is, however,\n        // a norm-dependent concept, and the euclidean norm of FE coefficient vectors as implicitly used here might not \n        // be the best suited.\n        // With a QR decomposition of P = Q [R;0], the pseudoinverse is P^+ = [R^{-1} 0] Q^T and hence the projection\n        // P P^+ = Q [I 0; 0 0] Q^T. If Q = [Q1 Q2], then P P^+ = Q1 Q1^T holds. The image space of Q1 is the same as that\n        // of P. For computing Q1, we therefore do not need to compute a full QR decomposition, but only the first columns of\n        // Q. The most simple method is Gram-Schmidt. Though it is numerically instable if the columns of P are almost linear\n        // dependent, we use it here, as the columns of P are associated to the shape functions on the father cell and \n        // should be comfortably linearly independent, though not orthogonal.\n        // Instead of forming Q1 Q1^T, we store just Q1, and apply the product if needed. As Q1 is high and tall, this is \n        // (slightly) more efficient.\n        for (int j=0; j<p.q.M(); ++j) // step through all columns\n        {\n          Scalar tmp = 0;\n          \n          // Normalize column j.\n          for (int i=0; i<p.q.N(); ++i)\n            tmp += power<2>(p.q[i][j]);\n          tmp = std::sqrt(tmp);\n          for (int i=0; i<p.q.N(); ++i)\n            p.q[i][j] /= tmp;\n          \n          // Orthogonalize remaining columns.\n          for (int k=j+1; k<p.q.M(); ++k)\n          {\n            tmp = 0;\n            for (int i=0; i<p.q.N(); ++i) \n              tmp += p.q[i][j] * p.q[i][k];\n            for (int i=0; i<p.q.N(); ++i)\n              p.q[i][k] -= tmp*p.q[i][j];\n          }\n        }\n      }\n\n    private:\n      CellPointer father; \n      std::vector<CellPointer> const& children; \n    };\n\n\n    // A functor that applies the appropriate projector provided on construction to the \n    // FE function that is given as argument.\n    template <class Projectors>\n    struct ProjectCoefficients\n    {\n      // Construct the functor, giving a list of (local) projectors indexed by the FE space index.\n      ProjectCoefficients(Projectors const& projectors_): projectors(projectors_) {}\n\n      // Apply the appropriate projector to the provided FE function. The pair consists of a variable description\n      // (containing the space index) and the FE function itself.\n      template <class Pair>\n      void operator()(Pair const& pair) const\n      {\n        typedef typename boost::remove_reference<typename result_of::value_at_c<Pair,0>::type>::type VarDesc;\n        typedef typename boost::remove_reference<typename result_of::value_at_c<Pair,1>::type>::type Function;\n\n        int const sIdx = VarDesc::spaceIndex;\n        auto const& proj = at_c<sIdx>(projectors);\n        int const n = proj.gidx.size();\n\n        // Multiplication of projector Q Q^T and coefficient vector. The\n        // multiplication has to be done manually because of\n        // type-incompatible entries. This results in the coefficients of\n        // the projection residual.\n        auto const& q = proj.q;\n        int const m = q.M();\n        typename Function::StorageType x(n);\n        typename Function::StorageType y(m);\n\n        // y <- Q^T v\n        for (int i=0; i<m; ++i) {\n          y[i] = 0;\n          for (int j=0; j<n; ++j)\n            y[i].axpy(q[j][i][0][0],(at_c<1>(pair).coefficients())[proj.gidx[j]]);\n        }\n        \n        // x <- Q y\n        for (int i=0; i<n; ++i) {\n          typename Function::StorageValueType x(0);\n          for (int j=0; j<m; ++j)\n            x.axpy(q[i][j][0][0],y[j]);\n          (at_c<1>(pair).coefficients())[proj.gidx[i]] = x;\n        }\n      }\n\n    private:\n      Projectors const& projectors;\n    };\n    \n    // Convenience function for template type deduction.\n    template <class Projectors>\n    ProjectCoefficients<Projectors> getCoefficientProjectors(Projectors const& ps) { return ProjectCoefficients<Projectors>(ps); }\n\n    \n    \n    class GroupByCell\n    {\n    public:\n      GroupByCell(std::vector<size_t> const& groups_)\n      : groups(&groups_), nGroups(*std::max_element(groups_.begin(),groups_.end())+1) {}\n      \n      size_t operator[](size_t idx) const { return (*groups)[idx]; }\n      size_t nGroups;\n      \n    private:\n      std::vector<size_t> const* groups;\n    };\n\n\n  } // End of namespace CoarseningDetail\n\n\n  /** \\ingroup adapt\n   * In order to maintain compatibility with existing code,\n   * this overload is needed, as non const reference parameters (coarsenedCells) can not\n   * have default values. All it does is call the original method with a temporary\n   * parameter.\n   */\n  template <class VariableSetDescription, class Scaling>\n  void coarsening(VariableSetDescription const& varDesc,\n                  typename VariableSetDescription::VariableSet const& sol,\n                  Scaling const& scaling,\n                  std::vector<std::pair<double,double> > const& tol,\n                  GridManager<typename VariableSetDescription::Grid>& gridManager, int verbosity=1, int minRefLevel=0)\n  {\n    std::vector<bool> tmp;\n    coarsening(varDesc, sol, scaling, tol, gridManager, tmp, verbosity, minRefLevel);\n  }\n\n  /** \\ingroup adapt\n   * \\brief coarsening routine\n   *\n   * Perform a projection from a fine grid onto a coarse grid. If the error is small, locally\n   * coarsen the grid there.\n   *\n   * \\param varDesc\n   * \\param sol \n   * \\param scaling\n   * \\param tol \n   * \\param gridManager\n   * \\param coarsenedCells\n   * \\param verbosity\n   * \\param minRefLevel do not coarse cells that are on this level or below.\n   */\n  template <class VariableSetDescription, class Scaling>\n  void coarsening(VariableSetDescription const& varDesc,\n                  typename VariableSetDescription::VariableSet const& sol,\n                  Scaling const& scaling,\n                  std::vector<std::pair<double,double> > const& tol,\n                  GridManager<typename VariableSetDescription::Grid>& gridManager,\n                  std::vector<bool>& coarsenedCells, int verbosity=1, int minRefLevel=0)\n  {\n    using namespace boost::fusion;\n    using namespace CoarseningDetail;\n\n// boost::timer::cpu_timer timer;\n// boost::timer::cpu_timer timerA, timerB;\n// timerA.stop(); timerB.stop();\n\n\n    typedef typename VariableSetDescription::Grid           Grid;\n    typedef typename Grid::LocalIdSet    IdSet;\n    typedef typename Grid::LeafIndexSet  IndexSet;\n    typedef typename Grid::template Codim<0>::Entity        Cell;\n    typedef typename Grid::template Codim<0>::EntityPointer CellPointer;\n    typedef typename Cell::HierarchicIterator               HierarchicIterator;\n\n    IndexSet const& indexSet = varDesc.indexSet;\n\n    // A set of FE functions that will contain the projection.\n    typename VariableSetDescription::VariableSet pSol(sol);\n\n    // A container of local projectors - defined here to avoid multiple allocations inside the cell loop\n    auto projectors = as_vector(transform(varDesc.spaces,CreateProjection()));\n\n    // a container for caching computed cell pointers to children. Prevents doubled hierarchical grid traversal \n    // and frequent reallocation\n    std::vector<CellPointer> children;\n    \n    // A mapping from leaf cells to their coarsening group number. A\n    // coarsening group is defined as follows. If all the direct\n    // children of a non-leaf cell are leafs (i.e. none of the children\n    // has been refined), these children form a coarsening group. Either\n    // all or none cells of a coarsening group are marked for\n    // coarsening. The special group number 0 collects all cells which\n    // are not element of a regular coarsening group (and hence cannot be\n    // removed during refinement).\n    std::vector<size_t> coarseningGroup(indexSet.size(0),0);\n    size_t coarseningGroupCount = 0;\n\n    // Step through all leaf cells and process their fathers.\n    typedef typename Grid::template Codim<0>::template Partition<Dune::All_Partition>::LeafIterator CellIterator;\n    CellIterator end = gridManager.grid().template leafend<0>();\n    for (CellIterator ci=gridManager.grid().template leafbegin<0>(); ci!=end; ++ci) // TODO: parallelize this loop\n      // Father has already been processed if cell belongs to a regular\n      // cell group. No father exists if the level is 0.\n      if (coarseningGroup[indexSet.index(*ci)]==0 && ci->level()>0) { // not yet processed, not on coarse grid\n        // Only process fathers which are suitable for coarsening.\n        CellPointer father = ci->father();\n        bool canBeCoarsened = true;\n        children.clear();\n        HierarchicIterator first = father->hbegin(father->level()+1), last = father->hend(father->level()+1);\n        for (HierarchicIterator hi=first; canBeCoarsened && hi!=last; ++hi) // early termination in case we find a non-leaf child\n        {\n          canBeCoarsened = canBeCoarsened && hi->isLeaf();\n          children.push_back(CellPointer(hi));\n        }\n        \n        if (canBeCoarsened) {\n// timerA.resume();\n          // Gather all the children into a new coarsening group.\n          ++coarseningGroupCount;\n          for (auto const& c: children)\n            coarseningGroup[indexSet.index(*c)] = coarseningGroupCount; // not coarseningGroupCount-1: group number 0 is for not coarsenable cells\n          // Compute the projections to the locally coarser subspace.\n          for_each(projectors,GetLocalTransferProjection<CellPointer>(father,children));\n// timerA.stop();\n// timerB.resume();          \n\n          // Apply the projectors to the FE functions.\n          for_each2(typename VariableSetDescription::Variables(),pSol.data,getCoefficientProjectors(projectors));\n// timerB.stop();\n        }\n      }\n\n    // Create the projection residual (i.e. the error introduced by coarsening).\n    pSol -= sol;\n\n//     std::cerr << \"Coarsening part Ia time: \" << timer.format()\n//               << \"       A               : \" << timerA.format()\n//               << \"       B               : \" << timerB.format();\n//     timer.start();\n\n    // Compute scaled L2 norms of the function and difference,\n    // attributing the cell contributions to its coarsening group.\n    ErrorestDetail::GroupedSummationCollector<GroupByCell> sum{GroupByCell(coarseningGroup)};\n    scaledTwoNormSquared(join(typename VariableSetDescription::Variables(),typename VariableSetDescription::Variables()),\n                         join(pSol.data,sol.data),varDesc.spaces,scaling,sum);\n//     std::cerr << \"Coarsening part Ib time: \" << timer.format();\n//     timer.start();\n\n    // For each variable, compute the (squared) relative error\n    // contribution, that is e_i^2 = |p_i|^2/(atol^2+|f|^2*rtol^2),\n    // where f is the function and p the difference to its hierarchic\n    // projection.\n    std::vector<double> norm2(varDesc.noOfVariables,0);\n    for (int i=0; i<varDesc.noOfVariables; ++i)\n      for (int j=0; j<=coarseningGroupCount; ++j)\n        norm2[i] += sum.sums[j][i+varDesc.noOfVariables];\n    if ( verbosity>0 )\n    {\n      std::cout << \"coarsening solution norms2: \"; \n      std::copy(norm2.begin(),norm2.end(),\n      std::ostream_iterator<double>(std::cout,\" \")); std::cout  << '\\n';\n    };\n\n    for (int i=0; i<varDesc.noOfVariables; ++i) {\n      double toli = power(tol[i].first,2) + norm2[i]*power(tol[i].second,2);\n      for (int j=0; j<=coarseningGroupCount; ++j)\n        sum.sums[j][i] /= toli;\n    }\n    \n\n    // Select a maximal subset C of the coarsening groups, such that for\n    // each variable the sum of C's relative errors is below 1.\n    //\n    // A greedy algorithm may work as follows: Maintain a vector E_i (of\n    // size the number of variables) that contains the remaining allowed\n    // relative error. Of the remaining coarsening groups j with\n    // relative errors e_ji select the one for which max_i e_ji / E_i is\n    // minimal.\n    //\n    // However, this has quadratic complexity. Thus we resort to the\n    // following simplification.  First we assign to each coarsening\n    // group j the maximal relative error e_j = max_i e_ji encountered\n    // in any variable. Subsequently, these are sorted in ascending\n    // order. Then the first k groups for which sum_{j=0}^k e_j <= 1\n    // hold are selected. Non-coarsenable cells (in the irregular\n    // coarsening group 0) are ignored.\n    //\n    // WARNING: Despite the fact that in principle we can compute the\n    // projection error exactly, the value we obtain is just an\n    // estimate. This is not only due to the heuristic suboptimal\n    // selection of C, but also due to the fact that the coarsening\n    // errors are modeled strictly locally. In conforming meshes, mesh\n    // adaptation can lead to nonlocal effects, e.g. the removal of no\n    // longer needed green closures (the introduced error is not taken\n    // into account), the introduction of green closures on newly\n    // coarsened cells (in which case the error could be below our\n    // estimate, depending on the actual transfer - currently the\n    // transfer is suboptimal and our error estimate should be exact),\n    // or a cell group can actually be retained for mesh topology\n    // reasons even if marked for coarsening (in which case the actual\n    // local error would be zero).\n    std::vector<std::pair<double,size_t> > e(coarseningGroupCount);\n    for (int j=0; j<coarseningGroupCount; ++j) {\n      e[j].second = j+1;                            // omit the irregular coarsening group 0\n      for (int i=0; i<varDesc.noOfVariables; ++i)\n        e[j].first = std::max(e[j].first,sum.sums[j+1][i]); \n    }\n\n    std::sort(e.begin(),e.end(),FirstLess());\n\n    std::vector<size_t> selectedCoarseningGroups;\n    double totalError = 0;\n    for (int i=0; i<e.size(); ++i) {\n      totalError += e[i].first;\n      if (totalError<=1)\n        selectedCoarseningGroups.push_back(e[i].second);\n      else\n        break;\n    }\n\n    // for compression: need to keep track of coarsening history\n    coarsenedCells.clear() ;\n    coarsenedCells.resize( indexSet.size(0), false ) ;\n    // no coarsening: just stop here\n    //   return ;\n\n    // If no cell can be coarsened, we don't need to touch the grid.\n    if (selectedCoarseningGroups.empty())\n      return;\n\n    // Now we sweep over the whole grid and mark all cells for\n    // coarsening which belong to a selected coarsening group.\n    std::sort(selectedCoarseningGroups.begin(),selectedCoarseningGroups.end());\n    for (CellIterator ci=gridManager.grid().template leafbegin<0>(); ci!=gridManager.grid().template leafend<0>(); ++ci)\n    {\n      auto idx = indexSet.index(*ci);\n      if (ci->level()>minRefLevel && std::binary_search(selectedCoarseningGroups.begin(),selectedCoarseningGroups.end(),\n                                                        coarseningGroup[idx])) // for uniform refinement: just delete level\n      {\n        coarsenedCells[idx] = true ; // for compression: coarsening history\n        gridManager.mark(-1,*ci);\n      }\n    }\n\n//     std::cerr << \"Coarsening part II time: \" << timer.format();\n//     timer.start();\n\n    gridManager.adaptAtOnce();\n    \n//     std::cerr << \"Coarsening part III time: \" << timer.format();\n  }\n} /* end of namespace Kaskade */\n\n#endif\n", "meta": {"hexsha": "352a996eb126f8d759aa1838b0d768dae1d94e2a", "size": 21933, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/fem/coarsening.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/fem/coarsening.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/fem/coarsening.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 45.1296296296, "max_line_length": 146, "alphanum_fraction": 0.625359048, "num_tokens": 5315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2878970345390851}}
{"text": "#include <cstdio>\n#include <cstdlib>\n#include <cmath>\n\n#include <boost/numeric/odeint.hpp>\n#include <boost/numeric/odeint/stepper/dense_output_runge_kutta.hpp>\n#include <boost/numeric/odeint/stepper/runge_kutta_dopri5.hpp>\n#include \"ch_ethz_bhepp_ode_boost_FixedBoostOdeintSolver.h\"\n\n#include \"Utilities.hpp\"\n\nusing namespace boost::numeric::odeint;\n\ntypedef boost::numeric::ublas::vector<double> vector_type;\ntypedef vector_type state_type;\ntypedef result_of::make_dense_output<\n    runge_kutta_dopri5< state_type > >::type dense_dopri5_stepper_type;\n\n//typedef int (*CALLBACK_F_PTR)(double t, N_Vector y, N_Vector ydot, void* user_data);\n//typedef int (*CALLBACK_G_PTR)(double t, N_Vector y, double* gout, void* user_data);\n\n\nstruct ode_system;\n\nstruct boost_solver_data {\n//\tdense_output_runge_kutta< runge_kutta_dopri5< state_type > > stepper;\n//\trunge_kutta_dopri5< state_type > stepper;\n\tode_system* system;\n\tdense_dopri5_stepper_type stepper;\n    JNIEnv* env;\n    jobject ode;\n    jmethodID vectorFieldMethodID;\n    jdouble stepSize;\n    jdouble t;\n    jdouble t1;\n    jdouble* x;\n    jdouble* xTmp;\n    jdouble* xDot;\n    state_type y;\n    state_type yDot;\n};\n\nstruct ode_system {\n\n    boost_solver_data* data;\n\n\tvoid operator()(const state_type &x, state_type &dxdt, double t )\n    {\n\t    JNIEnv *env = data->env;\n//\t    for (state_type::const_iterator it=x.begin(); it != x.end(); ++it) {\n\t\tfor (int i=0; i < x.size(); i++)\n\t    \tdata->xTmp[i] = x[i];\n\t    env->CallVoidMethod(data->ode, data->vectorFieldMethodID, t);\n\t    if (env->ExceptionCheck() == JNI_TRUE) {\n\t        fprintf(stderr, \"f_direct_bridge: Failed to call computeVectorField!\\n\");\n\t        return;\n\t    }\n//\t    for (state_type::const_iterator it=x.begin(); it != x.end(); ++it)\n\t\tfor (int i=0; i < dxdt.size(); i++)\n\t    \tdxdt[i] = data->xDot[i];\n    }\n\n};\n\nstruct ode_system_wrapper {\n\n\tode_system* system;\n\n\tode_system_wrapper(ode_system* system)\n\t\t: system(system) { }\n\tvoid operator()(const state_type &x, state_type &dxdt, double t ) {\n\t\tsystem->operator ()(x, dxdt, t);\n\t}\n\n};\n\n/*int jac_bridge(long int N, double t, N Vector y, N Vector fy, DlsMat Jac,\n               void *user data, N Vector tmp1, N Vector tmp2, N Vector tmp3) {\n    return 0;\n}*/\n\nJNIEXPORT jlong JNICALL Java_ch_ethz_bhepp_ode_boost_FixedBoostOdeintSolver_jni_1initialize\n\t(JNIEnv *env, jobject obj, jobject ode, jobject xBuffer, jobject xTmpBuffer, jobject xDotBuffer,\n\t\t\tjdouble stepSize, jdouble relTol, jdouble absTol, jint stepperType) {\n    jclass odeCls = env->GetObjectClass(ode);\n    if (env->ExceptionCheck() == JNI_TRUE) {\n        fprintf(stderr, \"jni_initialize: Failed to get class of ode object\\n\");\n        return 0;\n    }\n    jmethodID methodID = env->GetMethodID(odeCls, \"getDimensionOfVectorField\", \"()I\");\n    if (env->ExceptionCheck() == JNI_TRUE) {\n        fprintf(stderr, \"jni_initialize: Failed to get method ID of getDimensionOfVectorField\\n\");\n        return 0;\n    }\n    jint jdimension = env->CallIntMethod(ode, methodID);\n    state_type::size_type dimension = jdimension;\n    if (env->ExceptionCheck() == JNI_TRUE) {\n        fprintf(stderr, \"jni_initialize: Failed to call getDimensionOfVectorField\\n\");\n        return 0;\n    }\n\n    // Allocate and initialize boost_solver_data\n    boost_solver_data* data = new boost_solver_data();\n    // FIXME\n    if (env->ExceptionCheck() == JNI_TRUE) {\n        fprintf(stderr, \"jni_initialize: Failed to allocate boost_solver_data\\n\");\n        return 0;\n    }\n    data->stepSize = stepSize;\n\n    data->env = env;\n    // Acquire method IDs of callbacks and put them into boost_solver_data\n    data->ode = env->NewGlobalRef(ode);\n    if (env->ExceptionCheck() == JNI_TRUE) {\n        fprintf(stderr, \"jni_initialize: Failed to create global reference to ode object\\n\");\n        delete data;\n        return 0;\n    }\n    data->vectorFieldMethodID = env->GetMethodID(odeCls, \"computeVectorField\", \"(D)V\");\n    if (env->ExceptionCheck() == JNI_TRUE) {\n        fprintf(stderr, \"jni_initialize: Failed to get method ID of computeVectorField\\n\");\n        // Delete global java references\n        env->DeleteGlobalRef(data->ode);\n        delete data;\n        return 0;\n    }\n\n    // Check capacities of direct buffer objects\n    if (env->GetDirectBufferCapacity(xBuffer) < dimension) {\n        throw_java_exception(env, \"jni_initialize: Direct buffer xBuffer is not big enough\\n\");\n        // Delete global java references\n        env->DeleteGlobalRef(data->ode);\n        delete data;\n        return 0;\n    }\n    if (env->GetDirectBufferCapacity(xTmpBuffer) < dimension) {\n        throw_java_exception(env, \"jni_initialize: Direct buffer xTmpBuffer is not big enough\\n\");\n        // Delete global java references\n        env->DeleteGlobalRef(data->ode);\n        delete data;\n        return 0;\n    }\n    if (env->GetDirectBufferCapacity(xDotBuffer) < dimension) {\n        throw_java_exception(env, \"jni_initialize: Direct buffer xDotBuffer is not big enough\\n\");\n        // Delete global java references\n        env->DeleteGlobalRef(data->ode);\n        delete data;\n        return 0;\n    }\n    // Get addresses of direct buffer objects\n    data->x = static_cast<jdouble*>(env->GetDirectBufferAddress(xBuffer));\n    if (data->x == NULL) {\n        fprintf(stderr, \"jni_initialize: Failed to get direct address of xBuffer\\n\");\n        // Delete global java references\n        env->DeleteGlobalRef(data->ode);\n        delete data;\n        return 0;\n    }\n    data->xTmp = static_cast<jdouble*>(env->GetDirectBufferAddress(xTmpBuffer));\n    if (data->xTmp == NULL) {\n        fprintf(stderr, \"jni_initialize: Failed to get direct address of xTmpBuffer\\n\");\n        // Delete global java references\n        env->DeleteGlobalRef(data->ode);\n        delete data;\n        return 0;\n    }\n    data->xDot = static_cast<jdouble*>(env->GetDirectBufferAddress(xDotBuffer));\n    if (data->xDot == NULL) {\n        fprintf(stderr, \"jni_initialize: Failed to get direct address of xDotBuffer\\n\");\n        // Delete global java references\n        env->DeleteGlobalRef(data->ode);\n        delete data;\n        return 0;\n    }\n\n    data->y.resize(dimension, false);\n    data->yDot.resize(dimension, false);\n\n    data->system = new ode_system;\n    data->system->data = data;\n\n    // Pass pointer-address of boost_solver_data back to Java\n    jlong jni_pointer = (jlong)data;\n    return jni_pointer;\n}\n\nJNIEXPORT void JNICALL Java_ch_ethz_bhepp_ode_boost_FixedBoostOdeintSolver_jni_1dispose\n  (JNIEnv *env, jobject obj, jlong jni_pointer) {\n    boost_solver_data* data = (boost_solver_data*)jni_pointer;\n    if (data != NULL) {\n        // Delete global java references\n        if (data->ode != NULL)\n            env->DeleteGlobalRef(data->ode);\n        // Free data structure\n        delete data;\n    }\n}\n\nJNIEXPORT void JNICALL Java_ch_ethz_bhepp_ode_boost_FixedBoostOdeintSolver_jni_1prepareStep\n\t(JNIEnv *env, jobject obj, jlong jni_pointer, jdouble t0, jdouble t1) {\n    boost_solver_data* data = reinterpret_cast< boost_solver_data* >(jni_pointer);\n    data->t = t0;\n    data->t1 = t1;\n    for (int i=0; i < data->y.size(); i++)\n    \tdata->y[i] = data->x[i];\n    data->stepper.initialize(data->y, data->t, data->stepSize);\n}\n\n/*\n * Class:     ch_ethz_bhepp_ode_boost_FixedBoostOdeintSolver\n * Method:    jni_integrateOneStep\n * Signature: (J)D\n */\nJNIEXPORT jdouble JNICALL Java_ch_ethz_bhepp_ode_boost_FixedBoostOdeintSolver_jni_1integrateOneStep\n(JNIEnv *env, jobject obj, jlong jni_pointer) {\n    boost_solver_data* data = reinterpret_cast< boost_solver_data* >(jni_pointer);\n    std::pair< double , double > times = data->stepper.do_step(ode_system_wrapper(data->system));\n    const dense_dopri5_stepper_type::state_type& current_state = data->stepper.current_state();\n    for (int i=0; i < data->y.size(); i++)\n    \tdata->x[i] = current_state[i];\n    return times.second;\n}\n", "meta": {"hexsha": "874e5ce1aaab934ec02050caa84e8325ef9f0081", "size": 7870, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "JavaOde/jni/boost/src/FixedBoostOdeintSolver.cpp", "max_stars_repo_name": "bennihepp/HybridStochasticSimulation", "max_stars_repo_head_hexsha": "a19a777339be375a7301b69fbf1c0d840040e471", "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": "JavaOde/jni/boost/src/FixedBoostOdeintSolver.cpp", "max_issues_repo_name": "bennihepp/HybridStochasticSimulation", "max_issues_repo_head_hexsha": "a19a777339be375a7301b69fbf1c0d840040e471", "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": "JavaOde/jni/boost/src/FixedBoostOdeintSolver.cpp", "max_forks_repo_name": "bennihepp/HybridStochasticSimulation", "max_forks_repo_head_hexsha": "a19a777339be375a7301b69fbf1c0d840040e471", "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.2914798206, "max_line_length": 99, "alphanum_fraction": 0.6775095299, "num_tokens": 2072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635841117624, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2878970283723962}}
{"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 StereoSessionIsis.cc\n///\n\n// Vision Workbench\n#include <vw/FileIO.h>\n#include <vw/Math/Functors.h>\n#include <vw/Math/Geometry.h>\n#include <vw/Math/RANSAC.h>\n#include <vw/InterestPoint.h>\n#include <vw/Stereo/DisparityMap.h>\n#include <vw/Cartography.h>\n\n// Stereo Pipeline\n#include <asp/Sessions/ISIS/StereoSessionIsis.h>\n#include <asp/IsisIO/IsisCameraModel.h>\n#include <asp/Core/StereoSettings.h>\n#include <asp/IsisIO/IsisAdjustCameraModel.h>\n#include <asp/IsisIO/DiskImageResourceIsis.h>\n#include <asp/Sessions/ISIS/PhotometricOutlier.h>\n\n// Boost\n#include <boost/filesystem/operations.hpp>\n#include <boost/shared_ptr.hpp>\nnamespace fs = boost::filesystem;\n\n#include <algorithm>\n\nusing namespace vw;\nusing namespace vw::camera;\nusing namespace asp;\n\n// Allows FileIO to correctly read/write these pixel types\nnamespace vw {\n  template<> struct PixelFormatID<Vector3>   { static const PixelFormatEnum value = VW_PIXEL_GENERIC_3_CHANNEL; };\n}\n\n// Process a single ISIS image to find an ideal min max. The reason we\n// need to do this, is that ASP is to get image intensity values in\n// the range of 0-1. To some extent we are compressing the dynamic\n// range, but we try to minimize that.\nvoid find_ideal_isis_range( std::string const& in_file,\n                            std::string const& tag,\n                            float & isis_lo, float & isis_hi ) {\n\n  boost::shared_ptr<DiskImageResourceIsis> isis_rsrc( new DiskImageResourceIsis(in_file) );\n  DiskImageView<PixelGray<float> > disk_image(isis_rsrc);\n\n  float isis_mean, isis_std;\n\n  // Calculating statistics. We subsample the images so statistics\n  // only does about a million samples.\n  {\n    vw_out(InfoMessage) << \"\\t--> Computing statistics for the \"+tag+\" image\\n\";\n    int left_stat_scale = int(ceil(sqrt(float(disk_image.cols())*float(disk_image.rows()) / 1000000)));\n    ChannelAccumulator<math::CDFAccumulator<float> > accumulator;\n    for_each_pixel(\n      subsample(create_mask( edge_extend(disk_image, ConstantEdgeExtension()),\n                             isis_rsrc->valid_minimum(),\n                             isis_rsrc->valid_maximum() ),\n                left_stat_scale ),\n      accumulator );\n    isis_lo = accumulator.quantile(0);\n    isis_hi = accumulator.quantile(1);\n    isis_mean = accumulator.approximate_mean();\n    isis_std  = accumulator.approximate_stddev();\n\n    vw_out(InfoMessage) << \"\\t  \"+tag+\": [ lo:\" << isis_lo << \" hi:\" << isis_hi\n                        << \" m: \" << isis_mean << \" s: \" << isis_std <<  \"]\\n\";\n  }\n\n  // Normalizing to -+2 sigmas around mean\n  if ( stereo_settings().force_max_min == 0 ) {\n    vw_out(InfoMessage) << \"\\t--> Adjusting hi and lo to -+2 sigmas around mean.\\n\";\n\n    if ( isis_lo < isis_mean - 2*isis_std )\n      isis_lo = isis_mean - 2*isis_std;\n    if ( isis_hi > isis_mean + 2*isis_std )\n      isis_hi = isis_mean + 2*isis_std;\n\n    vw_out(InfoMessage) << \"\\t    \"+tag+\" changed: [ lo:\"\n                        << isis_lo << \" hi:\" << isis_hi << \"]\\n\";\n  }\n}\n\n// This actually modifies and writes the pre-processed image.\nvoid write_preprocessed_isis_image( BaseOptions const& opt,\n                                    std::string const& in_file,\n                                    std::string const& out_file,\n                                    std::string const& tag,\n                                    float isis_lo, float isis_hi,\n                                    float out_lo, float out_hi,\n                                    Matrix<double> const& matrix,\n                                    Vector2i const& crop_size ) {\n  DiskImageView<PixelGray<float> > disk_image(in_file);\n  ImageViewRef<PixelGray<float> > applied_image;\n  if ( matrix == math::identity_matrix<3>() ) {\n    applied_image =\n      crop(edge_extend(clamp(normalize(remove_isis_special_pixels(disk_image,\n                                                                  isis_lo, isis_hi, out_lo),\n                           out_lo, out_hi, 0.0, 1.0)),\n                       ZeroEdgeExtension()),\n           0, 0, crop_size[0], crop_size[1]);\n  } else {\n    applied_image =\n      transform(clamp(normalize(remove_isis_special_pixels(disk_image,\n                                                           isis_lo, isis_hi,\n                                                           out_lo),\n                                out_lo, out_hi, 0.0, 1.0)),\n                HomographyTransform(matrix),\n                crop_size[0], crop_size[1]);\n  }\n\n  // Write the results to disk.\n  vw_out() << \"\\t--> Writing normalized images.\\n\";\n  block_write_gdal_image( out_file, applied_image, opt,\n                          TerminalProgressCallback(\"asp\", \"\\t  \"+tag+\":  \") );\n}\n\nvoid\nasp::StereoSessionIsis::pre_preprocessing_hook(std::string const& input_file1,\n                                               std::string const& input_file2,\n                                               std::string & output_file1,\n                                               std::string & output_file2) {\n  output_file1 = m_out_prefix + \"-L.tif\";\n  output_file2 = m_out_prefix + \"-R.tif\";\n\n  if ( fs::exists(output_file1) && fs::exists(output_file2) ) {\n    try {\n      vw_log().console_log().rule_set().add_rule(-1,\"fileio\");\n      DiskImageView<PixelGray<float32> > out1(output_file1);\n      DiskImageView<PixelGray<float32> > out2(output_file2);\n      vw_out(InfoMessage) << \"\\t--> Using cached normalized input images.\\n\";\n      vw_settings().reload_config();\n      return;\n    } catch (vw::ArgumentErr const& e) {\n      // This throws on a corrupted file.\n      vw_settings().reload_config();\n    } catch (vw::IOErr const& e) {\n      vw_settings().reload_config();\n    }\n  }\n\n  float left_lo, left_hi, right_lo, right_hi;\n  find_ideal_isis_range( input_file1, \"left\",\n                         left_lo, left_hi );\n  find_ideal_isis_range( input_file2, \"right\",\n                         right_lo, right_hi );\n\n  // Working out alignment\n  float lo = std::min (left_lo, right_lo);  // Finding global\n  float hi = std::max (left_hi, right_hi);\n  Matrix<double> align_matrix(3,3);\n  align_matrix.set_identity();\n  if ( stereo_settings().keypoint_alignment) {\n    DiskImageView<PixelGray<float> > left_disk_image(input_file1);\n    DiskImageView<PixelGray<float> > right_disk_image(input_file2);\n    ImageViewRef<PixelGray<float> > left_view =\n      normalize(remove_isis_special_pixels(left_disk_image, lo),\n                lo, hi, 0, 1.0);\n    ImageViewRef<PixelGray<float> > right_view =\n      normalize(remove_isis_special_pixels(right_disk_image, lo),\n                lo, hi, 0, 1.0);\n    align_matrix = determine_image_align(input_file1, input_file2,\n                                         left_view, right_view );\n  }\n  write_matrix( m_out_prefix + \"-align.exr\", align_matrix );\n\n  // Getting left image size\n  Vector2i left_size;\n  {\n    DiskImageView<PixelGray<float> > left_image(input_file1);\n    left_size = Vector2i(left_image.cols(), left_image.rows());\n  }\n\n  // Apply alignment and normalization\n  if (stereo_settings().individually_normalize == 0 ) {\n    vw_out() << \"\\t--> Normalizing globally to: [\"<<lo<<\" \"<<hi<<\"]\\n\";\n    write_preprocessed_isis_image( m_options, input_file1, output_file1, \"left\",\n                                   left_lo, left_hi, lo, hi,\n                                   math::identity_matrix<3>(), left_size );\n    write_preprocessed_isis_image( m_options, input_file2, output_file2, \"right\",\n                                   right_lo, right_hi, lo, hi,\n                                   align_matrix, left_size );\n  } else {\n    vw_out() << \"\\t--> Individually normalizing.\\n\";\n    write_preprocessed_isis_image( m_options, input_file1, output_file1, \"left\",\n                                   left_lo, left_hi, left_lo, left_hi,\n                                   math::identity_matrix<3>(), left_size );\n    write_preprocessed_isis_image( m_options, input_file2, output_file2, \"right\",\n                                   right_lo, right_hi, right_lo, right_hi,\n                                   align_matrix, left_size );\n  }\n}\n\ninline std::string write_shadow_mask( BaseOptions const& opt,\n                                      std::string const& output_prefix,\n                                      std::string const& input_image,\n                                      std::string const& mask_postfix ) {\n  // This thresholds at -25000 as the input sub4s for Apollo that I've\n  // processed have a range somewhere between -32000 and +32000. -ZMM\n  DiskImageView<PixelGray<float> > disk_image( input_image );\n  DiskImageView<uint8> disk_mask( output_prefix + mask_postfix );\n  ImageViewRef<uint8> mask =\n    apply_mask(intersect_mask(create_mask(disk_mask),\n                              create_mask(threshold(disk_image,-25000,0,1.0))));\n  std::string output_mask =\n    output_prefix+mask_postfix.substr(0,mask_postfix.size()-4)+\"Debug.tif\";\n\n  block_write_gdal_image( output_mask, mask, opt,\n                          TerminalProgressCallback(\"asp\",\"\\t  Shadow:\") );\n  return output_mask;\n}\n\n// Stage 2: Correlation\n//\n// Pre file is a pair of grayscale images.  ( ImageView<PixelGray<float> > )\n// Post file is a disparity map.            ( ImageView<PixelMask<Vector2f> > )\nvoid\nasp::StereoSessionIsis::pre_filtering_hook(std::string const& input_file,\n                                           std::string & output_file) {\n  output_file = input_file;\n\n  // ****************************************************\n  // The following code is for Apollo Metric Camera ONLY!\n  // (use at your own risk)\n  // ****************************************************\n  if (stereo_settings().mask_flatfield) {\n    vw_out() << \"\\t--> Masking pixels that are less than 0.0.  (NOTE: Use this option with Apollo Metric Camera frames only!)\\n\";\n    output_file = m_out_prefix + \"-R-masked.exr\";\n\n    std::string shadowLmask_name =\n      write_shadow_mask( m_options, m_out_prefix, m_left_image_file,\n                         \"-lMask.tif\" );\n    std::string shadowRmask_name =\n      write_shadow_mask( m_options, m_out_prefix, m_right_image_file,\n                         \"-rMask.tif\" );\n\n    DiskImageView<uint8> shadowLmask( shadowLmask_name );\n    DiskImageView<uint8> shadowRmask( shadowRmask_name );\n\n    DiskImageView<PixelMask<Vector2f> > disparity_disk_image(input_file);\n    ImageViewRef<PixelMask<Vector2f> > disparity_map =\n      stereo::disparity_mask(disparity_disk_image,\n                             shadowLmask, shadowRmask );\n\n    DiskImageResourceOpenEXR disparity_map_rsrc(output_file, disparity_map.format() );\n    Vector2i block_size(std::min<size_t>(vw_settings().default_tile_size(),\n                                         disparity_map.cols()),\n                        std::min<size_t>(vw_settings().default_tile_size(),\n                                         disparity_map.rows()));\n    disparity_map_rsrc.set_block_write_size(block_size);\n    block_write_image( disparity_map_rsrc, disparity_map,\n                       TerminalProgressCallback( \"asp\", \"\\t--> Saving Mask :\") );\n  }\n}\n\n// Reverse any pre-alignment that was done to the images.\nvoid\nasp::StereoSessionIsis::pre_pointcloud_hook(std::string const& input_file,\n                                            std::string & output_file) {\n\n  // ****************************************************\n  // The following code is for Apollo Metric Camera ONLY!\n  // (use at your own risk)\n  // ****************************************************\n  std::string dust_result = input_file;\n  if ( stereo_settings().mask_flatfield ) {\n    vw_out() << \"\\t--> Masking pixels that appear to be dust.  (NOTE: Use this option with Apollo Metric Camera frames only!)\\n\";\n    photometric_outlier_rejection( m_out_prefix, input_file,\n                                   dust_result, stereo_settings().h_kern );\n  }\n\n  DiskImageView<PixelMask<Vector2f> > disparity_map(dust_result);\n  output_file = m_out_prefix + \"-F-corrected.tif\";\n\n  // We used a homography to line up the images, we may want\n  // to generate pre-alignment disparities before passing this information\n  // onto the camera model in the next stage of the stereo pipeline.\n  Matrix<double> align_matrix;\n  try {\n    read_matrix(align_matrix, m_out_prefix + \"-align.exr\");\n    vw_out(DebugMessage) << \"Alignment Matrix: \" << align_matrix << \"\\n\";\n  } catch (vw::IOErr const& e) {\n    vw_out() << \"\\nCould not read in aligment matrix: \" << m_out_prefix\n             << \"-align.exr.  Exiting. \\n\\n\";\n    exit(1);\n  }\n\n  // Remove pixels that are outside the bounds of the secondary image.\n  DiskImageView<PixelGray<float> > right_disk_image(m_right_image_file);\n  ImageViewRef<PixelMask<Vector2f> > result =\n    stereo::disparity_range_mask(stereo::transform_disparities(disparity_map,\n                                          HomographyTransform(align_matrix)),\n                                 Vector2f(0,0),\n                                 Vector2f( right_disk_image.cols(),\n                                           right_disk_image.rows() ) );\n\n  block_write_gdal_image( output_file, result, m_options,\n                          TerminalProgressCallback(\"asp\", \"\\t    Processing:\") );\n}\n\nboost::shared_ptr<vw::camera::CameraModel>\nasp::StereoSessionIsis::camera_model(std::string const& image_file,\n                                     std::string const& camera_file) {\n\n  if (boost::ends_with(boost::to_lower_copy(camera_file), \".isis_adjust\")){\n    // Creating Equations for the files\n    std::ifstream input( camera_file.c_str() );\n    boost::shared_ptr<asp::BaseEquation> posF = read_equation( input );\n    boost::shared_ptr<asp::BaseEquation> poseF = read_equation( input );\n    input.close();\n\n    // Finally creating camera model\n    return boost::shared_ptr<camera::CameraModel>(new IsisAdjustCameraModel( image_file, posF, poseF ));\n\n  } else {\n    return boost::shared_ptr<camera::CameraModel>(new IsisCameraModel(image_file));\n  }\n\n}\n\n\n", "meta": {"hexsha": "4709f367a45e4874514cb67d0a28628594a46918", "size": 14142, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/asp/Sessions/ISIS/StereoSessionIsis.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/Sessions/ISIS/StereoSessionIsis.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/Sessions/ISIS/StereoSessionIsis.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": 42.8545454545, "max_line_length": 129, "alphanum_fraction": 0.6068448593, "num_tokens": 3274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.28789702837239617}}
{"text": "// Copyright 2017 Zerocoin Electric Coin Company 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 \"common/default_types/r1cs_ppzksnark_pp.hpp\"\n#include \"zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp\"\n#include \"gadgetlib1/gadgets/hashes/sha256/sha256_gadget.hpp\"\n#include \"gadgetlib1/gadgets/merkle_tree/merkle_tree_check_read_gadget.hpp\"\n\n#include <boost/foreach.hpp>\n\ntemplate<typename FieldT>\npb_variable_array<FieldT> from_bits(std::vector<bool> bits, pb_variable<FieldT>& ZERO) {\n    pb_variable_array<FieldT> acc;\n\n    BOOST_FOREACH(bool bit, bits) {\n        acc.emplace_back(bit ? ONE : ZERO);\n    }\n\n    return acc;\n}\n\nstd::vector<unsigned char> convertIntToVectorLE(const uint64_t val_int) {\n    std::vector<unsigned char> bytes;\n\n    for(size_t i = 0; i < 8; i++) {\n        bytes.push_back(val_int >> (i * 8));\n    }\n\n    return bytes;\n}\n\n// Convert bytes into boolean vector. (MSB to LSB)\nstd::vector<bool> convertBytesVectorToVector(const std::vector<unsigned char>& bytes) {\n    std::vector<bool> ret;\n    ret.resize(bytes.size() * 8);\n\n    unsigned char c;\n    for (size_t i = 0; i < bytes.size(); i++) {\n        c = bytes.at(i);\n        for (size_t j = 0; j < 8; j++) {\n            ret.at((i*8)+j) = (c >> (7-j)) & 1;\n        }\n    }\n\n    return ret;\n}\n\n// Convert boolean vector (big endian) to integer\nuint64_t convertVectorToInt(const std::vector<bool>& v) {\n    if (v.size() > 64) {\n        throw std::length_error (\"boolean vector can't be larger than 64 bits\");\n    }\n\n    uint64_t result = 0;\n    for (size_t i=0; i<v.size();i++) {\n        if (v.at(i)) {\n            result |= (uint64_t)1 << ((v.size() - 1) - i);\n        }\n    }\n\n    return result;\n}\n\nstd::vector<bool> uint64_to_bool_vector(uint64_t input) {\n    auto num_bv = convertIntToVectorLE(input);\n    \n    return convertBytesVectorToVector(num_bv);\n}\n\ntemplate<typename FieldT>\nclass KeyHasher : gadget<FieldT> {\nprivate:\n    std::shared_ptr<block_variable<FieldT>> block;\n    std::shared_ptr<sha256_compression_function_gadget<FieldT>> hasher;\n\npublic:\n    KeyHasher(\n        protoboard<FieldT> &pb,\n        pb_variable<FieldT>& ZERO,\n        pb_variable_array<FieldT> sk,\n        std::shared_ptr<digest_variable<FieldT>> pk\n    ) : gadget<FieldT>(pb) {\n        pb_linear_combination_array<FieldT> IV = SHA256_default_IV(pb);\n\n        pb_variable_array<FieldT> length_padding =\n            from_bits({\n                // padding\n                1,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,1,\n                0,0,0,0,0,0,0,0\n        }, ZERO);\n\n        block.reset(new block_variable<FieldT>(pb, {\n            sk,\n            length_padding\n        }, \"\"));\n\n        hasher.reset(new sha256_compression_function_gadget<FieldT>(\n            pb,\n            IV,\n            block->bits,\n            *pk,\n        \"\"));\n    }\n\n    void generate_r1cs_constraints() {\n        hasher->generate_r1cs_constraints();\n    }\n\n    void generate_r1cs_witness() {\n        hasher->generate_r1cs_witness();\n    }\n};\n\ntemplate<typename FieldT>\nclass SendNullifier : gadget<FieldT> {\nprivate:\n\tstd::shared_ptr<block_variable<FieldT>> block;\n\tstd::shared_ptr<sha256_compression_function_gadget<FieldT>> hasher;\n\npublic:\n\tSendNullifier(\n\t\tprotoboard<FieldT> &pb,\n\t\tpb_variable<FieldT>& ZERO,\n\t\tpb_variable_array<FieldT> rho,\n\t\tstd::shared_ptr<digest_variable<FieldT>> result\n\t) : gadget<FieldT>(pb) {\n\t\tpb_linear_combination_array<FieldT> IV = SHA256_default_IV(pb);\n\n\t\tpb_variable_array<FieldT> discriminants;\n        discriminants.emplace_back(ZERO);\n        discriminants.emplace_back(ZERO);\n        discriminants.emplace_back(ZERO);\n        discriminants.emplace_back(ZERO);\n        discriminants.emplace_back(ZERO);\n        discriminants.emplace_back(ZERO);\n        discriminants.emplace_back(ZERO);\n        discriminants.emplace_back(ZERO);\n\n        pb_variable_array<FieldT> length_padding =\n            from_bits({\n                // padding\n                1,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,1,\n                0,0,0,0,1,0,0,0\n\t\t}, ZERO);\n\n\t\tblock.reset(new block_variable<FieldT>(pb, {\n            discriminants,\n            rho,\n            length_padding\n        }, \"\"));\n\n        hasher.reset(new sha256_compression_function_gadget<FieldT>(\n            pb,\n            IV,\n            block->bits,\n            *result,\n        \"\"));\n\t}\n\n\tvoid generate_r1cs_constraints() {\n        hasher->generate_r1cs_constraints();\n    }\n\n    void generate_r1cs_witness() {\n        hasher->generate_r1cs_witness();\n    }\n};\n\ntemplate<typename FieldT>\nclass SpendNullifier : gadget<FieldT> {\nprivate:\n    std::shared_ptr<block_variable<FieldT>> block1;\n    std::shared_ptr<sha256_compression_function_gadget<FieldT>> hasher1;\n    std::shared_ptr<digest_variable<FieldT>> intermediate;\n    std::shared_ptr<block_variable<FieldT>> block2;\n    std::shared_ptr<sha256_compression_function_gadget<FieldT>> hasher2;\n\npublic:\n    SpendNullifier(\n        protoboard<FieldT> &pb,\n        pb_variable<FieldT>& ZERO,\n        pb_variable_array<FieldT> rho,\n        pb_variable_array<FieldT> sk,\n        std::shared_ptr<digest_variable<FieldT>> result\n    ) : gadget<FieldT>(pb) {\n        pb_linear_combination_array<FieldT> IV = SHA256_default_IV(pb);\n\n        pb_variable_array<FieldT> discriminants;\n        discriminants.emplace_back(ZERO);\n        discriminants.emplace_back(ZERO);\n        discriminants.emplace_back(ZERO);\n        discriminants.emplace_back(ZERO);\n        discriminants.emplace_back(ZERO);\n        discriminants.emplace_back(ZERO);\n        discriminants.emplace_back(ZERO);\n        discriminants.emplace_back(ONE);\n\n        block1.reset(new block_variable<FieldT>(pb, {\n            discriminants,\n            rho,\n            pb_variable_array<FieldT>(sk.begin(), sk.begin() + 248)\n        }, \"\"));\n\n        intermediate.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        hasher1.reset(new sha256_compression_function_gadget<FieldT>(\n            pb,\n            IV,\n            block1->bits,\n            *intermediate,\n        \"\"));\n\n        pb_variable_array<FieldT> length_padding =\n            from_bits({\n                // padding\n                1,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,1,0,\n                0,0,0,0,1,0,0,0\n        }, ZERO);\n\n        block2.reset(new block_variable<FieldT>(pb, {\n            pb_variable_array<FieldT>(sk.begin() + 248, sk.end()),\n            length_padding\n        }, \"\"));\n\n        pb_linear_combination_array<FieldT> IV2(intermediate->bits);\n\n        hasher2.reset(new sha256_compression_function_gadget<FieldT>(\n            pb,\n            IV2,\n            block2->bits,\n            *result,\n        \"\"));\n    }\n\n    void generate_r1cs_constraints() {\n        hasher1->generate_r1cs_constraints();\n        hasher2->generate_r1cs_constraints();\n    }\n\n    void generate_r1cs_witness() {\n        hasher1->generate_r1cs_witness();\n        hasher2->generate_r1cs_witness();\n    }\n};\n\ntemplate<typename FieldT>\nclass NoteCommitment : gadget<FieldT> {\nprivate:\n\tstd::shared_ptr<block_variable<FieldT>> block1;\n\tstd::shared_ptr<sha256_compression_function_gadget<FieldT>> hasher1;\n\tstd::shared_ptr<digest_variable<FieldT>> intermediate;\n\tstd::shared_ptr<block_variable<FieldT>> block2;\n\tstd::shared_ptr<sha256_compression_function_gadget<FieldT>> hasher2;\n\npublic:\n\tNoteCommitment(\n\t\tprotoboard<FieldT> &pb,\n\t\tpb_variable<FieldT>& ZERO,\n\t\tpb_variable_array<FieldT> rho,\n\t\tpb_variable_array<FieldT> pk,\n\t\tpb_variable_array<FieldT> value,\n\t\tstd::shared_ptr<digest_variable<FieldT>> result\n\t) : gadget<FieldT>(pb) {\n\t\tpb_linear_combination_array<FieldT> IV = SHA256_default_IV(pb);\n\n\t\tblock1.reset(new block_variable<FieldT>(pb, {\n            rho,\n            pk\n        }, \"\"));\n\n        intermediate.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        hasher1.reset(new sha256_compression_function_gadget<FieldT>(\n            pb,\n            IV,\n            block1->bits,\n            *intermediate,\n        \"\"));\n\n        pb_variable_array<FieldT> length_padding =\n            from_bits({\n                // padding\n                1,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,0,0,\n                0,0,0,0,0,0,1,0,\n                0,1,0,0,0,0,0,0\n\t\t}, ZERO);\n\n        block2.reset(new block_variable<FieldT>(pb, {\n            value,\n            length_padding\n        }, \"\"));\n\n        pb_linear_combination_array<FieldT> IV2(intermediate->bits);\n\n        hasher2.reset(new sha256_compression_function_gadget<FieldT>(\n            pb,\n            IV2,\n            block2->bits,\n            *result,\n        \"\"));\n\t}\n\n\tvoid generate_r1cs_constraints() {\n        hasher1->generate_r1cs_constraints();\n        hasher2->generate_r1cs_constraints();\n    }\n\n    void generate_r1cs_witness() {\n        hasher1->generate_r1cs_witness();\n        hasher2->generate_r1cs_witness();\n    }\n};\n\ntemplate<typename FieldT>\nclass ShieldingCircuit : gadget<FieldT> {\nprivate:\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\n    // SHA256(0x00 | rho)\n    std::shared_ptr<digest_variable<FieldT>> send_nullifier;\n    // The note commitment: SHA256(rho | pk | value)\n    std::shared_ptr<digest_variable<FieldT>> cm;\n    // 64-bit value\n    pb_variable_array<FieldT> value;\n\n    // Aux inputs\n    pb_variable<FieldT> ZERO;\n    std::shared_ptr<digest_variable<FieldT>> rho;\n    std::shared_ptr<digest_variable<FieldT>> pk;\n\n    // Note commitment hasher\n    std::shared_ptr<NoteCommitment<FieldT>> cm_hasher;\n\n    // Send nullifier hasher\n    std::shared_ptr<SendNullifier<FieldT>> nf_hasher;\n\npublic:\n    ShieldingCircuit(protoboard<FieldT> &pb) : gadget<FieldT>(pb) {\n    \t// Inputs\n    \t{\n\t    \tzk_packed_inputs.allocate(pb, verifying_field_element_size());\n\t    \tpb.set_input_sizes(verifying_field_element_size());\n\n\t    \tsend_nullifier.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\t    \tzk_unpacked_inputs.insert(zk_unpacked_inputs.end(), send_nullifier->bits.begin(), send_nullifier->bits.end());\n\n\t    \tcm.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\t    \tzk_unpacked_inputs.insert(zk_unpacked_inputs.end(), cm->bits.begin(), cm->bits.end());\n\n\t    \tvalue.allocate(pb, 64, \"\");\n\t    \tzk_unpacked_inputs.insert(zk_unpacked_inputs.end(), value.begin(), value.end());\n\n\t    \tassert(zk_unpacked_inputs.size() == verifying_input_bit_size());\n\n\t    \tunpacker.reset(new multipacking_gadget<FieldT>(\n\t            pb,\n\t            zk_unpacked_inputs,\n\t            zk_packed_inputs,\n\t            FieldT::capacity(),\n\t            \"unpacker\"\n\t        ));\n\t    }\n\n\t    // Aux\n\t    ZERO.allocate(pb);\n\t    rho.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\t    pk.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n\t    cm_hasher.reset(new NoteCommitment<FieldT>(pb, ZERO, rho->bits, pk->bits, value, cm));\n\t    nf_hasher.reset(new SendNullifier<FieldT>(pb, ZERO, rho->bits, send_nullifier));\n    }\n\n    void generate_r1cs_constraints() {\n        unpacker->generate_r1cs_constraints(true);\n        generate_r1cs_equals_const_constraint<FieldT>(this->pb, ZERO, FieldT::zero(), \"ZERO\");\n\n        rho->generate_r1cs_constraints();\n        pk->generate_r1cs_constraints();\n\n        cm_hasher->generate_r1cs_constraints();\n        nf_hasher->generate_r1cs_constraints();\n    }\n\n    void generate_r1cs_witness(\n        const std::vector<unsigned char>& witness_rho,\n        const std::vector<unsigned char>& witness_pk,\n        uint64_t witness_value\n    ) {\n        this->pb.val(ZERO) = FieldT::zero();\n\n        rho->bits.fill_with_bits(\n            this->pb,\n            convertBytesVectorToVector(witness_rho)\n        );\n\n        pk->bits.fill_with_bits(\n            this->pb,\n            convertBytesVectorToVector(witness_pk)\n        );\n\n        value.fill_with_bits(\n            this->pb,\n            uint64_to_bool_vector(witness_value)\n        );\n\n        cm_hasher->generate_r1cs_witness();\n        nf_hasher->generate_r1cs_witness();\n\n        unpacker->generate_r1cs_witness_from_bits();\n    }\n\n    static r1cs_primary_input<FieldT> witness_map(\n        const std::vector<unsigned char> &witness_nf,\n        const std::vector<unsigned char> &witness_cm,\n        uint64_t witness_value\n    ) {\n        std::vector<bool> verify_inputs;\n\n        std::vector<bool> nf_bits = convertBytesVectorToVector(witness_nf);\n        std::vector<bool> cm_bits = convertBytesVectorToVector(witness_cm);\n        std::vector<bool> value_bits = uint64_to_bool_vector(witness_value);\n\n        verify_inputs.insert(verify_inputs.end(), nf_bits.begin(), nf_bits.end());\n        verify_inputs.insert(verify_inputs.end(), cm_bits.begin(), cm_bits.end());\n        verify_inputs.insert(verify_inputs.end(), value_bits.begin(), value_bits.end());\n\n        assert(verify_inputs.size() == verifying_input_bit_size());\n        auto verify_field_elements = 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    static size_t verifying_field_element_size() {\n        return div_ceil(verifying_input_bit_size(), FieldT::capacity());\n    }\n\n    static size_t verifying_input_bit_size() {\n        size_t acc = 0;\n\n        acc += 256; // the nullifier\n        acc += 256; // the note commitment\n        acc += 64; // the value of the note\n\n        return acc;\n    }\n};\n\n#define INCREMENTAL_MERKLE_TREE_DEPTH 29\n\ntemplate<typename FieldT>\nclass merkle_tree_gadget : gadget<FieldT> {\nprivate:\n    typedef sha256_two_to_one_hash_gadget<FieldT> sha256_gadget;\n\n    pb_variable_array<FieldT> positions;\n    std::shared_ptr<merkle_authentication_path_variable<FieldT, sha256_gadget>> authvars;\n    std::shared_ptr<merkle_tree_check_read_gadget<FieldT, sha256_gadget>> auth;\n\npublic:\n    merkle_tree_gadget(\n        protoboard<FieldT>& pb,\n        digest_variable<FieldT> leaf,\n        digest_variable<FieldT> root,\n        pb_variable<FieldT>& enforce\n    ) : gadget<FieldT>(pb) {\n        positions.allocate(pb, INCREMENTAL_MERKLE_TREE_DEPTH);\n        authvars.reset(new merkle_authentication_path_variable<FieldT, sha256_gadget>(\n            pb, INCREMENTAL_MERKLE_TREE_DEPTH, \"auth\"\n        ));\n        auth.reset(new merkle_tree_check_read_gadget<FieldT, sha256_gadget>(\n            pb,\n            INCREMENTAL_MERKLE_TREE_DEPTH,\n            positions,\n            leaf,\n            root,\n            *authvars,\n            enforce,\n            \"\"\n        ));\n    }\n\n    void generate_r1cs_constraints() {\n        for (size_t i = 0; i < INCREMENTAL_MERKLE_TREE_DEPTH; i++) {\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(\n        size_t path_index,\n        const std::vector<std::vector<bool>>& authentication_path\n    ) {\n        positions.fill_with_bits_of_ulong(this->pb, path_index);\n\n        authvars->generate_r1cs_witness(path_index, authentication_path);\n        auth->generate_r1cs_witness();\n    }\n};\n\ntemplate<typename FieldT>\nclass UnshieldingCircuit : gadget<FieldT> {\nprivate:\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\n    // 64-bit value\n    pb_variable_array<FieldT> value;\n\n    // Aux inputs\n    pb_variable<FieldT> ZERO;\n    std::shared_ptr<digest_variable<FieldT>> cm; // Note commitment\n    std::shared_ptr<digest_variable<FieldT>> rho;\n    std::shared_ptr<digest_variable<FieldT>> pk;\n    std::shared_ptr<digest_variable<FieldT>> sk;\n\n    // Key hasher\n    std::shared_ptr<KeyHasher<FieldT>> key_hasher;\n\n    // Note commitment hasher\n    std::shared_ptr<NoteCommitment<FieldT>> cm_hasher;\n\n    // Spend nullifier hasher\n    std::shared_ptr<SpendNullifier<FieldT>> nf_hasher;\n\n    // Merkle tree lookup\n    std::shared_ptr<merkle_tree_gadget<FieldT>> merkle_lookup;\n\npublic:\n    // The anchor of the tree\n    std::shared_ptr<digest_variable<FieldT>> anchor;\n\n    // SHA256(0x01 | rho)\n    std::shared_ptr<digest_variable<FieldT>> spend_nullifier;\n\n    UnshieldingCircuit(protoboard<FieldT> &pb) : gadget<FieldT>(pb) {\n        // Inputs\n        {\n            zk_packed_inputs.allocate(pb, verifying_field_element_size());\n            pb.set_input_sizes(verifying_field_element_size());\n\n            spend_nullifier.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n            zk_unpacked_inputs.insert(zk_unpacked_inputs.end(), spend_nullifier->bits.begin(), spend_nullifier->bits.end());\n\n            anchor.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n            zk_unpacked_inputs.insert(zk_unpacked_inputs.end(), anchor->bits.begin(), anchor->bits.end());\n\n            value.allocate(pb, 64, \"\");\n            zk_unpacked_inputs.insert(zk_unpacked_inputs.end(), value.begin(), value.end());\n\n            assert(zk_unpacked_inputs.size() == verifying_input_bit_size());\n\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        // Aux\n        ZERO.allocate(pb);\n        rho.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n        sk.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n        pk.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n        cm.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        key_hasher.reset(new KeyHasher<FieldT>(pb, ZERO, sk->bits, pk));\n        cm_hasher.reset(new NoteCommitment<FieldT>(pb, ZERO, rho->bits, pk->bits, value, cm));\n        nf_hasher.reset(new SpendNullifier<FieldT>(pb, ZERO, rho->bits, sk->bits, spend_nullifier));\n        auto test = ONE;\n        merkle_lookup.reset(new merkle_tree_gadget<FieldT>(pb, *cm, *anchor, test));\n    }\n\n    void generate_r1cs_constraints() {\n        unpacker->generate_r1cs_constraints(true);\n        generate_r1cs_equals_const_constraint<FieldT>(this->pb, ZERO, FieldT::zero(), \"ZERO\");\n\n        rho->generate_r1cs_constraints();\n        sk->generate_r1cs_constraints();\n\n        key_hasher->generate_r1cs_constraints();\n        cm_hasher->generate_r1cs_constraints();\n        nf_hasher->generate_r1cs_constraints();\n        merkle_lookup->generate_r1cs_constraints();\n    }\n\n    void generate_r1cs_witness(\n        const std::vector<unsigned char>& witness_rho,\n        const std::vector<unsigned char>& witness_sk,\n        uint64_t witness_value,\n        size_t path_index,\n        const std::vector<std::vector<bool>>& authentication_path\n    ) {\n        this->pb.val(ZERO) = FieldT::zero();\n\n        rho->bits.fill_with_bits(\n            this->pb,\n            convertBytesVectorToVector(witness_rho)\n        );\n\n        sk->bits.fill_with_bits(\n            this->pb,\n            convertBytesVectorToVector(witness_sk)\n        );\n\n        value.fill_with_bits(\n            this->pb,\n            uint64_to_bool_vector(witness_value)\n        );\n\n        key_hasher->generate_r1cs_witness();\n        cm_hasher->generate_r1cs_witness();\n        nf_hasher->generate_r1cs_witness();\n        merkle_lookup->generate_r1cs_witness(path_index, authentication_path);\n\n        unpacker->generate_r1cs_witness_from_bits();\n    }\n\n    static r1cs_primary_input<FieldT> witness_map(\n        const std::vector<unsigned char> &witness_nf,\n        const std::vector<unsigned char> &witness_anchor,\n        uint64_t witness_value\n    ) {\n        std::vector<bool> verify_inputs;\n\n        std::vector<bool> nf_bits = convertBytesVectorToVector(witness_nf);\n        std::vector<bool> anchor_bits = convertBytesVectorToVector(witness_anchor);\n        std::vector<bool> value_bits = uint64_to_bool_vector(witness_value);\n\n        verify_inputs.insert(verify_inputs.end(), nf_bits.begin(), nf_bits.end());\n        verify_inputs.insert(verify_inputs.end(), anchor_bits.begin(), anchor_bits.end());\n        verify_inputs.insert(verify_inputs.end(), value_bits.begin(), value_bits.end());\n\n        assert(verify_inputs.size() == verifying_input_bit_size());\n        auto verify_field_elements = 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    static size_t verifying_field_element_size() {\n        return div_ceil(verifying_input_bit_size(), FieldT::capacity());\n    }\n\n    static size_t verifying_input_bit_size() {\n        size_t acc = 0;\n\n        acc += 256; // the nullifier\n        acc += 256; // the anchor\n        acc += 64; // the value of the note\n\n        return acc;\n    }\n};\n\ntemplate<typename T>\nT swap_endianness_u64(T v) {\n    if (v.size() != 64) {\n        throw std::length_error(\"invalid bit length for 64-bit unsigned integer\");\n    }\n\n    for (size_t i = 0; i < 4; i++) {\n        for (size_t j = 0; j < 8; j++) {\n            std::swap(v[i*8 + j], v[((7-i)*8)+j]);\n        }\n    }\n\n    return v;\n}\n\ntemplate<typename FieldT>\nlinear_combination<FieldT> packed_addition(pb_variable_array<FieldT> input) {\n    auto input_swapped = swap_endianness_u64(input);\n\n    return pb_packing_sum<FieldT>(pb_variable_array<FieldT>(\n        input_swapped.rbegin(), input_swapped.rend()\n    ));\n}\n\ntemplate<typename FieldT>\nclass TransferCircuit : gadget<FieldT> {\nprivate:\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\n    // Aux inputs\n    pb_variable<FieldT> ZERO;\n\n    // Verifier inputs\n    std::shared_ptr<digest_variable<FieldT>> anchor;\n    std::shared_ptr<digest_variable<FieldT>> spend_nullifier_input_1;\n    std::shared_ptr<digest_variable<FieldT>> spend_nullifier_input_2;\n    std::shared_ptr<digest_variable<FieldT>> send_nullifier_output_1;\n    std::shared_ptr<digest_variable<FieldT>> send_nullifier_output_2;\n\n    // Input stuff.\n    std::shared_ptr<digest_variable<FieldT>> input_sk_1;\n    std::shared_ptr<digest_variable<FieldT>> input_sk_2;\n    std::shared_ptr<digest_variable<FieldT>> input_pk_1;\n    std::shared_ptr<digest_variable<FieldT>> input_pk_2;\n    std::shared_ptr<KeyHasher<FieldT>> key_hasher_1;\n    std::shared_ptr<KeyHasher<FieldT>> key_hasher_2;\n    std::shared_ptr<digest_variable<FieldT>> input_rho_1;\n    std::shared_ptr<digest_variable<FieldT>> input_rho_2;\n    std::shared_ptr<SpendNullifier<FieldT>> input_nf_hasher_1;\n    std::shared_ptr<SpendNullifier<FieldT>> input_nf_hasher_2;\n    pb_variable_array<FieldT> input_value_1;\n    pb_variable_array<FieldT> input_value_2;\n    std::shared_ptr<digest_variable<FieldT>> input_cm_1;\n    std::shared_ptr<digest_variable<FieldT>> input_cm_2;\n    std::shared_ptr<NoteCommitment<FieldT>> input_cm_hasher_1;\n    std::shared_ptr<NoteCommitment<FieldT>> input_cm_hasher_2;\n    pb_variable<FieldT> enforce_input_1;\n    pb_variable<FieldT> enforce_input_2;\n    std::shared_ptr<merkle_tree_gadget<FieldT>> merkle_lookup_1;\n    std::shared_ptr<merkle_tree_gadget<FieldT>> merkle_lookup_2;\n\n    // Output stuff.\n    std::shared_ptr<digest_variable<FieldT>> output_cm_1;\n    pb_variable_array<FieldT> output_value_1;\n    std::shared_ptr<digest_variable<FieldT>> output_rho_1;\n    std::shared_ptr<digest_variable<FieldT>> output_pk_1;\n    std::shared_ptr<NoteCommitment<FieldT>> output_cm_hasher_1;\n    std::shared_ptr<SendNullifier<FieldT>> output_nf_hasher_1;\n\n    std::shared_ptr<digest_variable<FieldT>> output_cm_2;\n    pb_variable_array<FieldT> output_value_2;\n    std::shared_ptr<digest_variable<FieldT>> output_rho_2;\n    std::shared_ptr<digest_variable<FieldT>> output_pk_2;\n    std::shared_ptr<NoteCommitment<FieldT>> output_cm_hasher_2;\n    std::shared_ptr<SendNullifier<FieldT>> output_nf_hasher_2;\n\npublic:\n\n    TransferCircuit(protoboard<FieldT> &pb) : gadget<FieldT>(pb) {\n        // Inputs\n        {\n            zk_packed_inputs.allocate(pb, verifying_field_element_size());\n            pb.set_input_sizes(verifying_field_element_size());\n\n            anchor.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n            zk_unpacked_inputs.insert(zk_unpacked_inputs.end(), anchor->bits.begin(), anchor->bits.end());\n\n            spend_nullifier_input_1.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n            zk_unpacked_inputs.insert(zk_unpacked_inputs.end(), spend_nullifier_input_1->bits.begin(), spend_nullifier_input_1->bits.end());\n\n            spend_nullifier_input_2.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n            zk_unpacked_inputs.insert(zk_unpacked_inputs.end(), spend_nullifier_input_2->bits.begin(), spend_nullifier_input_2->bits.end());\n\n            send_nullifier_output_1.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n            zk_unpacked_inputs.insert(zk_unpacked_inputs.end(), send_nullifier_output_1->bits.begin(), send_nullifier_output_1->bits.end());\n\n            send_nullifier_output_2.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n            zk_unpacked_inputs.insert(zk_unpacked_inputs.end(), send_nullifier_output_2->bits.begin(), send_nullifier_output_2->bits.end());\n\n            output_cm_1.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n            zk_unpacked_inputs.insert(zk_unpacked_inputs.end(), output_cm_1->bits.begin(), output_cm_1->bits.end());\n\n            output_cm_2.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n            zk_unpacked_inputs.insert(zk_unpacked_inputs.end(), output_cm_2->bits.begin(), output_cm_2->bits.end());\n\n            assert(zk_unpacked_inputs.size() == verifying_input_bit_size());\n\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        // Aux\n        ZERO.allocate(pb);\n        input_cm_1.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n        input_cm_2.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n        input_sk_1.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n        input_sk_2.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n        input_pk_1.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n        input_pk_2.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n        input_rho_1.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n        input_rho_2.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n        key_hasher_1.reset(new KeyHasher<FieldT>(pb, ZERO, input_sk_1->bits, input_pk_1));\n        key_hasher_2.reset(new KeyHasher<FieldT>(pb, ZERO, input_sk_2->bits, input_pk_2));\n        input_nf_hasher_1.reset(new SpendNullifier<FieldT>(pb, ZERO, input_rho_1->bits, input_sk_1->bits, spend_nullifier_input_1));\n        input_nf_hasher_2.reset(new SpendNullifier<FieldT>(pb, ZERO, input_rho_2->bits, input_sk_2->bits, spend_nullifier_input_2));\n\n        input_value_1.allocate(pb, 64, \"\");\n        input_value_2.allocate(pb, 64, \"\");\n\n        input_cm_hasher_1.reset(new NoteCommitment<FieldT>(pb, ZERO, input_rho_1->bits, input_pk_1->bits, input_value_1, input_cm_1));\n        input_cm_hasher_2.reset(new NoteCommitment<FieldT>(pb, ZERO, input_rho_2->bits, input_pk_2->bits, input_value_2, input_cm_2));\n\n        enforce_input_1.allocate(pb);\n        enforce_input_2.allocate(pb);\n        \n        merkle_lookup_1.reset(new merkle_tree_gadget<FieldT>(pb, *input_cm_1, *anchor, enforce_input_1));\n        merkle_lookup_2.reset(new merkle_tree_gadget<FieldT>(pb, *input_cm_2, *anchor, enforce_input_2));\n\n        output_value_1.allocate(pb, 64, \"\");\n        output_value_2.allocate(pb, 64, \"\");\n\n        output_rho_1.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n        output_rho_2.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n        output_pk_1.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n        output_pk_2.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        output_cm_hasher_1.reset(new NoteCommitment<FieldT>(pb, ZERO, output_rho_1->bits, output_pk_1->bits, output_value_1, output_cm_1));\n        output_cm_hasher_2.reset(new NoteCommitment<FieldT>(pb, ZERO, output_rho_2->bits, output_pk_2->bits, output_value_2, output_cm_2));\n\n        output_nf_hasher_1.reset(new SendNullifier<FieldT>(pb, ZERO, output_rho_1->bits, send_nullifier_output_1));\n        output_nf_hasher_2.reset(new SendNullifier<FieldT>(pb, ZERO, output_rho_2->bits, send_nullifier_output_2));\n    }\n\n    void generate_r1cs_constraints() {\n        unpacker->generate_r1cs_constraints(true);\n        generate_r1cs_equals_const_constraint<FieldT>(this->pb, ZERO, FieldT::zero(), \"ZERO\");\n\n        input_sk_1->generate_r1cs_constraints();\n        input_sk_2->generate_r1cs_constraints();\n        input_rho_1->generate_r1cs_constraints();\n        input_rho_2->generate_r1cs_constraints();\n        key_hasher_1->generate_r1cs_constraints();\n        key_hasher_2->generate_r1cs_constraints();\n        input_nf_hasher_1->generate_r1cs_constraints();\n        input_nf_hasher_2->generate_r1cs_constraints();\n\n        for (size_t i = 0; i < 64; i++) {\n            generate_boolean_r1cs_constraint<FieldT>(\n                this->pb,\n                input_value_1[i],\n                \"\"\n            );\n            generate_boolean_r1cs_constraint<FieldT>(\n                this->pb,\n                input_value_2[i],\n                \"\"\n            );\n        }\n\n        input_cm_hasher_1->generate_r1cs_constraints();\n        input_cm_hasher_2->generate_r1cs_constraints();\n\n        generate_boolean_r1cs_constraint<FieldT>(this->pb, enforce_input_1, \"\");\n\n        this->pb.add_r1cs_constraint(r1cs_constraint<FieldT>(\n                    packed_addition(input_value_1),\n                    (1 - enforce_input_1),\n                    0\n        ), \"\");\n\n        generate_boolean_r1cs_constraint<FieldT>(this->pb, enforce_input_2, \"\");\n\n        this->pb.add_r1cs_constraint(r1cs_constraint<FieldT>(\n                    packed_addition(input_value_2),\n                    (1 - enforce_input_2),\n                    0\n        ), \"\");\n\n        merkle_lookup_1->generate_r1cs_constraints();\n        merkle_lookup_2->generate_r1cs_constraints();\n\n        for (size_t i = 0; i < 64; i++) {\n            generate_boolean_r1cs_constraint<FieldT>(\n                this->pb,\n                output_value_1[i],\n                \"\"\n            );\n            generate_boolean_r1cs_constraint<FieldT>(\n                this->pb,\n                output_value_2[i],\n                \"\"\n            );\n        }\n\n        output_rho_1->generate_r1cs_constraints();\n        output_rho_2->generate_r1cs_constraints();\n        output_pk_1->generate_r1cs_constraints();\n        output_pk_2->generate_r1cs_constraints();\n\n        output_cm_hasher_1->generate_r1cs_constraints();\n        output_cm_hasher_2->generate_r1cs_constraints();\n\n        output_nf_hasher_1->generate_r1cs_constraints();\n        output_nf_hasher_2->generate_r1cs_constraints();\n\n        {\n            linear_combination<FieldT> left_side =\n                packed_addition(input_value_1) + packed_addition(input_value_2);\n\n            linear_combination<FieldT> right_side =\n                packed_addition(output_value_1) + packed_addition(output_value_2);\n\n            // Ensure that both sides are equal\n            this->pb.add_r1cs_constraint(r1cs_constraint<FieldT>(\n                left_side,\n                1,\n                right_side\n            ));\n        }\n    }\n\n    void generate_r1cs_witness(\n        const std::vector<unsigned char>& witness_rho_1,\n        const std::vector<unsigned char>& witness_sk_1,\n        uint64_t witness_value_1,\n        size_t path_index_1,\n        const std::vector<std::vector<bool>>& authentication_path_1,\n        const std::vector<unsigned char>& witness_rho_2,\n        const std::vector<unsigned char>& witness_sk_2,\n        uint64_t witness_value_2,\n        size_t path_index_2,\n        const std::vector<std::vector<bool>>& authentication_path_2,\n        const std::vector<unsigned char>& output_witness_rho_1,\n        const std::vector<unsigned char>& output_witness_pk_1,\n        uint64_t output_witness_value_1,\n        const std::vector<unsigned char>& output_witness_rho_2,\n        const std::vector<unsigned char>& output_witness_pk_2,\n        uint64_t output_witness_value_2\n    ) {\n        this->pb.val(ZERO) = FieldT::zero();\n\n        this->pb.val(enforce_input_1) = (witness_value_1 != 0) ? FieldT::one() : FieldT::zero();\n        this->pb.val(enforce_input_2) = (witness_value_2 != 0) ? FieldT::one() : FieldT::zero();\n\n        input_rho_1->bits.fill_with_bits(\n            this->pb,\n            convertBytesVectorToVector(witness_rho_1)\n        );\n\n        input_sk_1->bits.fill_with_bits(\n            this->pb,\n            convertBytesVectorToVector(witness_sk_1)\n        );\n\n        input_value_1.fill_with_bits(\n            this->pb,\n            uint64_to_bool_vector(witness_value_1)\n        );\n\n        key_hasher_1->generate_r1cs_witness();\n        input_cm_hasher_1->generate_r1cs_witness();\n        input_nf_hasher_1->generate_r1cs_witness();\n        merkle_lookup_1->generate_r1cs_witness(path_index_1, authentication_path_1);\n\n        input_rho_2->bits.fill_with_bits(\n            this->pb,\n            convertBytesVectorToVector(witness_rho_2)\n        );\n\n        input_sk_2->bits.fill_with_bits(\n            this->pb,\n            convertBytesVectorToVector(witness_sk_2)\n        );\n\n        input_value_2.fill_with_bits(\n            this->pb,\n            uint64_to_bool_vector(witness_value_2)\n        );\n\n        key_hasher_2->generate_r1cs_witness();\n        input_cm_hasher_2->generate_r1cs_witness();\n        input_nf_hasher_2->generate_r1cs_witness();\n        merkle_lookup_2->generate_r1cs_witness(path_index_2, authentication_path_2);\n\n        output_rho_1->bits.fill_with_bits(\n            this->pb,\n            convertBytesVectorToVector(output_witness_rho_1)\n        );\n\n        output_pk_1->bits.fill_with_bits(\n            this->pb,\n            convertBytesVectorToVector(output_witness_pk_1)\n        );\n\n        output_value_1.fill_with_bits(\n            this->pb,\n            uint64_to_bool_vector(output_witness_value_1)\n        );\n\n        output_cm_hasher_1->generate_r1cs_witness();\n        output_nf_hasher_1->generate_r1cs_witness();\n\n        output_rho_2->bits.fill_with_bits(\n            this->pb,\n            convertBytesVectorToVector(output_witness_rho_2)\n        );\n\n        output_pk_2->bits.fill_with_bits(\n            this->pb,\n            convertBytesVectorToVector(output_witness_pk_2)\n        );\n\n        output_value_2.fill_with_bits(\n            this->pb,\n            uint64_to_bool_vector(output_witness_value_2)\n        );\n\n        output_cm_hasher_2->generate_r1cs_witness();\n        output_nf_hasher_2->generate_r1cs_witness();\n\n        unpacker->generate_r1cs_witness_from_bits();\n    }\n\n    static r1cs_primary_input<FieldT> witness_map(\n        const std::vector<unsigned char> &witness_anchor,\n        const std::vector<unsigned char> &input_nf_1,\n        const std::vector<unsigned char> &input_nf_2,\n        const std::vector<unsigned char> &output_nf_1,\n        const std::vector<unsigned char> &output_nf_2,\n        const std::vector<unsigned char> &output_cm_1,\n        const std::vector<unsigned char> &output_cm_2\n    )\n    {\n        std::vector<bool> verify_inputs;\n\n        std::vector<bool> anchor_bits = convertBytesVectorToVector(witness_anchor);\n        std::vector<bool> input_nf1_bits = convertBytesVectorToVector(input_nf_1);\n        std::vector<bool> input_nf2_bits = convertBytesVectorToVector(input_nf_2);\n        std::vector<bool> output_nf1_bits = convertBytesVectorToVector(output_nf_1);\n        std::vector<bool> output_nf2_bits = convertBytesVectorToVector(output_nf_2);\n        std::vector<bool> output_cm1_bits = convertBytesVectorToVector(output_cm_1);\n        std::vector<bool> output_cm2_bits = convertBytesVectorToVector(output_cm_2);\n\n        verify_inputs.insert(verify_inputs.end(), anchor_bits.begin(), anchor_bits.end());\n        verify_inputs.insert(verify_inputs.end(), input_nf1_bits.begin(), input_nf1_bits.end());\n        verify_inputs.insert(verify_inputs.end(), input_nf2_bits.begin(), input_nf2_bits.end());\n        verify_inputs.insert(verify_inputs.end(), output_nf1_bits.begin(), output_nf1_bits.end());\n        verify_inputs.insert(verify_inputs.end(), output_nf2_bits.begin(), output_nf2_bits.end());\n        verify_inputs.insert(verify_inputs.end(), output_cm1_bits.begin(), output_cm1_bits.end());\n        verify_inputs.insert(verify_inputs.end(), output_cm2_bits.begin(), output_cm2_bits.end());\n\n        assert(verify_inputs.size() == verifying_input_bit_size());\n        auto verify_field_elements = 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    static size_t verifying_field_element_size() {\n        return div_ceil(verifying_input_bit_size(), FieldT::capacity());\n    }\n\n    static size_t verifying_input_bit_size() {\n        size_t acc = 0;\n\n        acc += 256; // the anchor\n        acc += 256; // input 1 nullifier\n        acc += 256; // input 2 nullifier\n        acc += 256; // output 1 nullifier\n        acc += 256; // output 2 nullifier\n        acc += 256; // output 1 commitment\n        acc += 256; // output 2 commitment\n\n        return acc;\n    }\n};\n", "meta": {"hexsha": "6b12b748a7c61b8cdd0634081d722c0acf4452de", "size": 43738, "ext": "tcc", "lang": "C++", "max_stars_repo_path": "zsl-golang/zsl/snark/gadgets.tcc", "max_stars_repo_name": "kobigurk/zsl-q", "max_stars_repo_head_hexsha": "918385ee41a5c3a7e44a1fc97881e0801381b1f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-09T22:46:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-09T22:46:57.000Z", "max_issues_repo_path": "zsl-golang/zsl/snark/gadgets.tcc", "max_issues_repo_name": "susytech/zsl-susy", "max_issues_repo_head_hexsha": "622a5657cc5e25c486fa37d3888a13165b235709", "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": "zsl-golang/zsl/snark/gadgets.tcc", "max_forks_repo_name": "susytech/zsl-susy", "max_forks_repo_head_hexsha": "622a5657cc5e25c486fa37d3888a13165b235709", "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.8787878788, "max_line_length": 140, "alphanum_fraction": 0.6011020166, "num_tokens": 12480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.287893090017197}}
{"text": "/*****************************************************************************/\n/*  Copyright (c) 2017, Aleksandrs Ecins                                     */\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#ifndef MIN_CUT_HPP\n#define MIN_CUT_HPP\n\n// Boost includes\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/boykov_kolmogorov_max_flow.hpp>\n\n// Utilities includes\n#include <graph/graph_weighted.hpp>\n\n// Typedefs\n// NOTE! This should be moved inside the functions, so that they don't spread these typedefs outside this function.\n// The likely solution is to put the whole mincut algorithm into it's own class\ntypedef boost::adjacency_list_traits  < boost::vecS, boost::vecS, boost::directedS > Traits;\ntypedef boost::adjacency_list         < boost::vecS,                                                                            // Container used for vertices\n                                        boost::vecS,                                                                            // Container used for edges\n                                        boost::directedS,                                                                       // Directional graph\n                                        boost::property < boost::vertex_name_t, std::string,                                    // Vertex properties\n                                        boost::property < boost::vertex_index_t, long,\n                                        boost::property < boost::vertex_color_t, boost::default_color_type,\n                                        boost::property < boost::vertex_distance_t, long,\n                                        boost::property < boost::vertex_predecessor_t, Traits::edge_descriptor > > > > >,\n\n                                        boost::property < boost::edge_capacity_t, float,                                       // Edge properties\n                                        boost::property < boost::edge_residual_capacity_t, float,\n                                        boost::property < boost::edge_reverse_t, Traits::edge_descriptor > > > > GraphBoost;\n\ntypedef boost::property_map< GraphBoost, boost::edge_capacity_t >::type CapacityMap;\ntypedef boost::property_map< GraphBoost, boost::edge_reverse_t>::type ReverseEdgeMap;\ntypedef boost::property_map< GraphBoost, boost::vertex_color_t, boost::default_color_type>::type VertexColorMap;\n\n////////////////////////////////////////////////////////////////////////////////\nbool addEdge (Traits::vertex_descriptor &v1, Traits::vertex_descriptor &v2, GraphBoost &graph, const float weight, CapacityMap &capacity_map, ReverseEdgeMap &reverse_edge_map)\n{\n  Traits::edge_descriptor edge, reverse_edge;\n  bool edge_was_added, reverse_edge_was_added;\n\n  boost::tie (edge, edge_was_added) = boost::add_edge ( v1, v2, graph );\n  boost::tie (reverse_edge, reverse_edge_was_added) = boost::add_edge ( v2, v1, graph );\n  if ( !edge_was_added || !reverse_edge_was_added )\n    return (false);\n  \n  capacity_map[edge] = weight;\n  capacity_map[reverse_edge] = weight;\n  reverse_edge_map[edge] = reverse_edge;\n  reverse_edge_map[reverse_edge] = edge;\n  \n  return true;\n}\n                                    \nnamespace utl\n{\n  /** \\brief Perform a min cut on a graph\n   *  \\param[in]  source_potentials   weights between nodes and source node\n   *  \\param[in]  sink_potentials     weights between nodes and sink node\n   *  \\param[in]  binary_potentials   binary potential structure and weights\n   *  \\param[out] source_points       points belonging to source\n   *  \\param[out] sink_points         points belonging to sink\n   */\n  double mincut ( const std::vector<float> &source_potentials, \n                  const std::vector<float> &sink_potentials,\n                  const utl::GraphWeighted &binary_potentials,\n                  std::vector<int> &source_points,\n                  std::vector<int> &sink_points\n                )\n  {\n    ////////////////////////////////////////////////////////////////////////////\n    // Check input\n    if (! (   (source_potentials.size() == sink_potentials.size()) && \n              (source_potentials.size() == binary_potentials.getNumVertices())))\n    {\n      std::cout << \"[utl::minCut] number of vertices in source potentials, sink potentials and binary potentials are not equal.\" << std::endl;\n      return -1.0;\n    }\n    \n    ////////////////////////////////////////////////////////////////////////////\n    // Build graph\n    \n    int numVertices = source_potentials.size();\n    GraphBoost graph;\n    std::vector< Traits::vertex_descriptor > vertices;\n    Traits::vertex_descriptor source;\n    Traits::vertex_descriptor sink;\n    CapacityMap capacity          = boost::get (boost::edge_capacity, graph);\n    ReverseEdgeMap reverseEdgeMap = boost::get (boost::edge_reverse, graph);\n    VertexColorMap vertexColorMap = boost::get (boost::vertex_color, graph);\n\n      // Add vertices\n    vertices.resize(numVertices + 2);\n    for (size_t i = 0; i < static_cast<size_t>(numVertices + 2); i++)\n      vertices[i] = boost::add_vertex(graph);\n    \n    source  = vertices[source_potentials.size()];\n    sink    = vertices[source_potentials.size()+1];\n    \n    // Add source and sink edges\n    for (size_t i = 0; i < static_cast<size_t>(numVertices); i++)\n    {\n      addEdge(vertices[i], source, graph, source_potentials[i], capacity, reverseEdgeMap);\n      addEdge(vertices[i], sink,   graph, sink_potentials[i], capacity, reverseEdgeMap);\n    }\n    \n    // Add binary edges\n    for (size_t edgeId = 0; edgeId < binary_potentials.getNumEdges(); edgeId++)\n    {\n      // Get edge information\n      int vtx1Id, vtx2Id;\n      float weight;\n      \n      if (!binary_potentials.getEdge(edgeId, vtx1Id, vtx2Id, weight))\n      {\n        std::cout << \"[utl::minCut] could not add binary edges to Boost graph.\" << std::endl;\n        abort();        \n      }\n      \n      // Add it to Boost graph\n      Traits::vertex_descriptor v1 = vertices[vtx1Id];\n      Traits::vertex_descriptor v2 = vertices[vtx2Id];\n      addEdge(v1, v2, graph, weight, capacity, reverseEdgeMap);      \n    }\n        \n    ////////////////////////////////////////////////////////////////////////////\n    // Compute maximim flow\n    \n    double flow = boost::boykov_kolmogorov_max_flow(graph, source, sink);\n    \n    ////////////////////////////////////////////////////////////////////////////\n    // Find foreground and background points\n    \n    source_points.clear();\n    sink_points.clear();\n    \n    for (size_t i = 0; i < static_cast<size_t>(numVertices); i++)\n    {    \n      if (vertexColorMap(vertices[i]) == 0)\n        source_points.push_back(i);\n      else\n        sink_points.push_back(i);\n    }\n    \n    return flow;\n  }\n}\n\n# endif // MIN_CUT_HPP", "meta": {"hexsha": "02c7ebf358a27fbf5a7813e90a74a15f55c13473", "size": 9022, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utilities/graph/min_cut.hpp", "max_stars_repo_name": "Cznielsen/symseg", "max_stars_repo_head_hexsha": "b1c1e1e2f21f6a3d8b65e4f68d3516bc0bbbf06e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 51.0, "max_stars_repo_stars_event_min_datetime": "2017-05-15T15:16:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T22:37:29.000Z", "max_issues_repo_path": "utilities/graph/min_cut.hpp", "max_issues_repo_name": "Cznielsen/symseg", "max_issues_repo_head_hexsha": "b1c1e1e2f21f6a3d8b65e4f68d3516bc0bbbf06e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2017-05-31T05:32:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T01:35:49.000Z", "max_forks_repo_path": "utilities/graph/min_cut.hpp", "max_forks_repo_name": "Cznielsen/symseg", "max_forks_repo_head_hexsha": "b1c1e1e2f21f6a3d8b65e4f68d3516bc0bbbf06e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2017-08-08T17:43:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T17:59:08.000Z", "avg_line_length": 50.9717514124, "max_line_length": 175, "alphanum_fraction": 0.5428951452, "num_tokens": 1760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.2878845253438698}}
{"text": "/* Copyright 2017 Battelle Energy Alliance, 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/*\n * distribution_1D.cpp\n *\n *  Created on: Mar 22, 2012\n *      Author: MANDD\n *      Modified: alfoa\n *      References:\n *      1- G. Cassella, R.G. Berger, \"Statistical Inference\", 2nd ed. Pacific Grove, CA: Duxbury Press (2001).\n *\n */\n\n#include \"distribution_1D.h\"\n#include \"distributionFunctions.h\"\n#include <cmath>               // needed to use erfc error function\n#include <string>\n#include \"dynamicArray.h\"\n#include <ctime>\n#include <cstdlib>\n//#include \"InterpolationFunctions.h\"\n#include <string>\n#include <limits>\n#include <iso646.h>\n#include <boost/math/distributions/uniform.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/lognormal.hpp>\n#include <boost/math/distributions/triangular.hpp>\n#include <boost/math/distributions/exponential.hpp>\n#include <boost/math/distributions/weibull.hpp>\n#include <boost/math/distributions/gamma.hpp>\n#include <boost/math/distributions/beta.hpp>\n#include <boost/math/distributions/poisson.hpp>\n#include <boost/math/distributions/binomial.hpp>\n#include <boost/math/distributions/logistic.hpp>\n#include <boost/math/distributions/bernoulli.hpp>\n#include <boost/math/distributions/laplace.hpp>\n#include <boost/math/distributions/geometric.hpp>\n\n#define _USE_MATH_DEFINES   // needed in order to use M_PI = 3.14159\n\n#define throwError(msg) { std::cerr << \"\\n\\n\" << msg << \"\\n\\n\"; throw std::runtime_error(\"Error\"); }\n\nclass DistributionBackend {\npublic:\n  virtual double pdf(double x) = 0;\n  virtual double cdf(double x) = 0;\n  virtual double cdfComplement(double x) = 0;\n  virtual double quantile(double x) = 0;\n  virtual double mean() = 0;\n  virtual double standard_deviation() = 0;\n  virtual double median() = 0;\n  virtual double mode() = 0;\n  virtual double hazard(double x) = 0;\n  virtual ~DistributionBackend() {};\n};\n\n/*\n * Class Basic Truncated Distribution\n * This class implements a basic truncated distribution that can\n * be inherited from.\n */\n\nBasicTruncatedDistribution::BasicTruncatedDistribution(double x_min, double x_max)\n{\n  if(not hasParameter(\"truncation\"))\n  {\n    _dist_parameters[\"truncation\"] = 1.0;\n  }\n    _dist_parameters[\"xMin\"] = x_min;\n    _dist_parameters[\"xMax\"] = x_max;\n}\n\ndouble\nBasicTruncatedDistribution::pdf(double x){\n  double value;\n  double x_min = _dist_parameters.find(\"xMin\") ->second;\n  double x_max = _dist_parameters.find(\"xMax\") ->second;\n\n  if (_dist_parameters.find(\"truncation\") ->second == 1) {\n    if ((x<x_min)||(x>x_max)) {\n      value=0;\n    } else {\n      value = 1/(untrCdf(x_max) - untrCdf(x_min)) * untrPdf(x);\n    }\n  } else {\n    value=-1;\n  }\n\n  return value;\n}\n\ndouble\nBasicTruncatedDistribution::cdf(double x){\n  double value;\n  double x_min = _dist_parameters.find(\"xMin\") ->second;\n  double x_max = _dist_parameters.find(\"xMax\") ->second;\n\n  if (_dist_parameters.find(\"truncation\") ->second == 1) {\n    if (x<x_min) {\n      value=0;\n    } else if (x>x_max) {\n      value=1;\n    } else{\n      value = 1/(untrCdf(x_max) - untrCdf(x_min)) * (untrCdf(x)- untrCdf(x_min));\n    }\n  } else {\n    value=-1;\n  }\n\n  return value;\n}\n\ndouble\nBasicTruncatedDistribution::inverseCdf(double x){\n  double value;\n  double x_min = _dist_parameters.find(\"xMin\") ->second;\n  double x_max = _dist_parameters.find(\"xMax\") ->second;\n\n  if(x == 0.0) {\n    //Using == in floats is generally a bad idea, but\n    // 0.0 can be represented exactly.\n    //In this case, return the minimum value\n    return x_min;\n  }\n  if(x == 1.0) {\n    //Using == in floats is generally a bad idea, but\n    // 1.0 can be represented exactly.\n    //In this case, return the maximum value\n    return x_max;\n  }\n  if (_dist_parameters.find(\"truncation\") ->second == 1){\n    double temp=untrCdf(x_min)+x*(untrCdf(x_max)-untrCdf(x_min));\n    value=untrInverseCdf(temp);\n  } else {\n    throwError(\"A valid solution for inverseCdf was not found!\");\n  }\n  return value;\n}\n\n\ndouble BasicTruncatedDistribution::untrPdf(double x) {\n  return _backend->pdf(x);\n}\n\ndouble BasicTruncatedDistribution::untrCdf(double x) {\n  return _backend->cdf(x);\n}\n\ndouble BasicTruncatedDistribution::untrCdfComplement(double x) {\n  return _backend->cdfComplement(x);\n}\n\ndouble BasicTruncatedDistribution::untrInverseCdf(double x) {\n  return _backend->quantile(x);\n}\n\ndouble BasicTruncatedDistribution::untrMean() {\n  return _backend->mean();\n}\n\n/**\n   Calculates the untruncated standard deviation\n   \\return the standard deviation\n*/\ndouble BasicTruncatedDistribution::untrStdDev() {\n  return _backend->standard_deviation();\n}\n\ndouble BasicTruncatedDistribution::untrMedian() {\n  return _backend->median();\n}\n\ndouble BasicTruncatedDistribution::untrMode() {\n  return _backend->mode();\n}\n\ndouble BasicTruncatedDistribution::untrHazard(double x) {\n  return _backend->hazard(x);\n}\n\n\n\n/*\n * Class Basic Discrete Distribution\n * This class implements a basic discrete distribution that can\n * be inherited from.\n */\n\ndouble BasicDiscreteDistribution::untrPdf(double x) {\n  return _backend->pdf(x);\n}\n\ndouble BasicDiscreteDistribution::untrCdf(double x) {\n  return _backend->cdf(x);\n}\n\ndouble BasicDiscreteDistribution::untrCdfComplement(double x) {\n  return _backend->cdfComplement(x);\n}\n\ndouble BasicDiscreteDistribution::untrInverseCdf(double x) {\n  return _backend->quantile(x);\n}\n\ndouble BasicDiscreteDistribution::untrMean() {\n  return _backend->mean();\n}\n\n/**\n   Calculates the untruncated standard deviation\n   \\return the standard deviation\n*/\ndouble BasicDiscreteDistribution::untrStdDev() {\n  return _backend->standard_deviation();\n}\n\ndouble BasicDiscreteDistribution::untrMedian() {\n  return _backend->median();\n}\n\ndouble BasicDiscreteDistribution::untrMode() {\n  return _backend->mode();\n}\n\ndouble BasicDiscreteDistribution::untrHazard(double x) {\n  return _backend->hazard(x);\n}\n\ndouble BasicDiscreteDistribution::pdf(double x) {\n  return untrPdf(x);\n}\n\ndouble BasicDiscreteDistribution::cdf(double x) {\n  return untrCdf(x);\n}\n\ndouble BasicDiscreteDistribution::inverseCdf(double x) {\n  return untrInverseCdf(x);\n}\n\n/*\n * Class DistributionBackendTemplate implements a template that\n * can be used to create a DistributionBackend from a boost distribution\n */\n\ntemplate <class T>\nclass DistributionBackendTemplate : public DistributionBackend {\npublic:\n  double pdf(double x) { return boost::math::pdf(*_backend, x); };\n  double cdf(double x) { return boost::math::cdf(*_backend, x); };\n  double cdfComplement(double x) { return boost::math::cdf(boost::math::complement(*_backend, x)); };\n  double quantile(double x) { return boost::math::quantile(*_backend, x); };\n  double mean() { return boost::math::mean(*_backend); };\n  double standard_deviation() { return boost::math::standard_deviation(*_backend); };\n  double median() { return boost::math::median(*_backend); };\n  double mode() { return boost::math::mode(*_backend); };\n  double hazard(double x) { return boost::math::hazard(*_backend, x); };\nprotected:\n  T *_backend;\n};\n\n/*\n * CLASS UNIFORM DISTRIBUTION\n */\n\n\nclass UniformDistributionBackend : public DistributionBackendTemplate<boost::math::uniform> {\npublic:\n  UniformDistributionBackend(double x_min, double x_max) {\n    _backend = new boost::math::uniform(x_min,x_max);\n  }\n  ~UniformDistributionBackend() {\n    delete _backend;\n  }\n};\n\n\nBasicUniformDistribution::BasicUniformDistribution(double x_min, double x_max)\n{\n  _dist_parameters[\"xMin\"] = x_min;\n  _dist_parameters[\"xMax\"] = x_max;\n  _backend = new UniformDistributionBackend(x_min, x_max);\n\n  if (x_min>x_max)\n    throwError(\"ERROR: bounds for uniform distribution are incorrect\");\n}\n\nBasicUniformDistribution::~BasicUniformDistribution()\n{\n  delete _backend;\n}\n\ndouble\nBasicUniformDistribution::pdf(double x){\n  return untrPdf(x);\n}\n\ndouble\nBasicUniformDistribution::cdf(double x){\n  return untrCdf(x);\n}\n\ndouble\nBasicUniformDistribution::inverseCdf(double x){\n  return untrInverseCdf(x);\n}\n\nclass NormalDistributionBackend : public DistributionBackendTemplate<boost::math::normal> {\npublic:\n  NormalDistributionBackend(double mean, double sd) {\n    _backend = new boost::math::normal(mean, sd);\n  }\n  ~NormalDistributionBackend() {\n    delete _backend;\n  }\n};\n\n/*\n * CLASS NORMAL DISTRIBUTION\n */\n\nBasicNormalDistribution::BasicNormalDistribution(double mu, double sigma) {\n  _dist_parameters[\"mu\"] = mu; //mean\n  _dist_parameters[\"sigma\"] = sigma; //sd\n  if(not hasParameter(\"truncation\")) {\n    _dist_parameters[\"truncation\"] = 1.0;\n  }\n  if(not hasParameter(\"xMin\")) {\n    _dist_parameters[\"xMin\"] = -std::numeric_limits<double>::max( );\n  }\n  if(not hasParameter(\"xMax\")) {\n    _dist_parameters[\"xMax\"] = std::numeric_limits<double>::max( );\n  }\n  //std::cout << \"mu \" << mu << \" sigma \" << sigma\n  //          << \" truncation \" << _dist_parameters[\"truncation\"]\n  //          << \" xMin \" << _dist_parameters[\"xMin\"]\n  //          << \" xMax \" << _dist_parameters[\"xMax\"] << std::endl;\n  _backend = new NormalDistributionBackend(mu, sigma);\n}\n\nBasicNormalDistribution::BasicNormalDistribution(double mu, double sigma, double x_min, double x_max):\n  BasicTruncatedDistribution(x_min,x_max)\n{\n  _dist_parameters[\"mu\"] = mu; //mean\n  _dist_parameters[\"sigma\"] = sigma; //sd\n  //if(not hasParameter(\"truncation\")) {\n  //  _dist_parameters[\"truncation\"] = 1.0;\n  //}\n  //_dist_parameters[\"xMin\"] = x_min;\n  //_dist_parameters[\"xMax\"] = x_max;\n  //std::cout << \"mu \" << mu << \" sigma \" << sigma\n  //          << \" truncation \" << _dist_parameters[\"truncation\"]\n  //          << \" xMin \" << _dist_parameters[\"xMin\"]\n  //          << \" xMax \" << _dist_parameters[\"xMax\"] << std::endl;\n  _backend = new NormalDistributionBackend(mu, sigma);\n\n}\n\n\nBasicNormalDistribution::~BasicNormalDistribution(){\n  delete _backend;\n}\n\n\ndouble\nBasicNormalDistribution::inverseCdf(double x){\n  return BasicTruncatedDistribution::inverseCdf(x);\n}\n\nclass LogNormalDistributionBackend : public DistributionBackendTemplate<boost::math::lognormal> {\npublic:\n  LogNormalDistributionBackend(double mean, double sd) {\n    _backend = new boost::math::lognormal(mean, sd);\n  }\n  ~LogNormalDistributionBackend() {\n    delete  _backend;\n  }\n};\n\n/*\n * CLASS LOG NORMAL DISTRIBUTION\n */\n\n\nBasicLogNormalDistribution::BasicLogNormalDistribution(double mu, double sigma, double low)\n{\n  _dist_parameters[\"mu\"] = mu;\n  _dist_parameters[\"sigma\"] = sigma;\n  _dist_parameters[\"low\"] = low;\n\n  if(not hasParameter(\"truncation\")) {\n    _dist_parameters[\"truncation\"] = 1.0;\n  }\n  if(not hasParameter(\"xMin\")) {\n    _dist_parameters[\"xMin\"] = low;\n  }\n  if(not hasParameter(\"xMax\")) {\n    _dist_parameters[\"xMax\"] = std::numeric_limits<double>::max( );\n  }\n\n  _backend = new LogNormalDistributionBackend(mu, sigma);\n\n}\n\nBasicLogNormalDistribution::BasicLogNormalDistribution(double mu, double sigma, double x_min, double x_max, double low):\n  BasicTruncatedDistribution(x_min,x_max)\n{\n  _dist_parameters[\"mu\"] = mu;\n  _dist_parameters[\"sigma\"] = sigma;\n  _dist_parameters[\"low\"] = low;\n\n  _backend = new LogNormalDistributionBackend(mu, sigma);\n\n}\n\n\nBasicLogNormalDistribution::~BasicLogNormalDistribution()\n{\n  delete _backend;\n}\n\ndouble\nBasicLogNormalDistribution::untrPdf(double x){\n  double low = _dist_parameters.find(\"low\") ->second;\n  if(x <= low) {\n    return 0.0;\n  } else {\n    return _backend->pdf(x-low);\n  }\n}\n\ndouble\nBasicLogNormalDistribution::untrCdf(double x){\n  double low = _dist_parameters.find(\"low\") ->second;\n  if(x <= low) {\n    return 0.0;\n  } else {\n    return _backend->cdf(x-low);\n  }\n}\n\n\ndouble\nBasicLogNormalDistribution::inverseCdf(double x){\n  double low = _dist_parameters.find(\"low\") ->second;\n  return BasicTruncatedDistribution::inverseCdf(x)+low;\n}\n\n/*\n * CLASS LOGISTIC DISTRIBUTION\n */\n\n\nclass LogisticDistributionBackend : public DistributionBackendTemplate<boost::math::logistic_distribution<> > {\npublic:\n  LogisticDistributionBackend(double location, double scale) {\n    _backend = new boost::math::logistic_distribution<>(location, scale);\n  }\n  ~LogisticDistributionBackend() {\n    delete _backend;\n  }\n};\n\n\nBasicLogisticDistribution::BasicLogisticDistribution(double location, double scale)\n{\n  _dist_parameters[\"location\"] = location;\n  _dist_parameters[\"scale\"] = scale;\n\n  if(not hasParameter(\"truncation\")) {\n    _dist_parameters[\"truncation\"] = 1.0;\n  }\n  if(not hasParameter(\"xMin\")) {\n    _dist_parameters[\"xMin\"] = -std::numeric_limits<double>::max( );\n  }\n  if(not hasParameter(\"xMax\")) {\n    _dist_parameters[\"xMax\"] = std::numeric_limits<double>::max( );\n  }\n\n  _backend = new LogisticDistributionBackend(location, scale);\n}\n\nBasicLogisticDistribution::BasicLogisticDistribution(double location, double scale, double x_min, double x_max):\n  BasicTruncatedDistribution(x_min,x_max)\n{\n    _dist_parameters[\"location\"] = location;\n    _dist_parameters[\"scale\"] = scale;\n\n    _backend = new LogisticDistributionBackend(location, scale);\n}\n\nBasicLogisticDistribution::~BasicLogisticDistribution()\n{\n  delete _backend;\n}\n\n/*\n * CLASS LAPLACE DISTRIBUTION\n */\nclass LaplaceDistributionBackend : public DistributionBackendTemplate<boost::math::laplace_distribution<> > {\npublic:\n  LaplaceDistributionBackend(double location, double scale) {\n    _backend = new boost::math::laplace_distribution<>(location, scale);\n  }\n  ~LaplaceDistributionBackend() {\n    delete _backend;\n  }\n};\n\nBasicLaplaceDistribution::BasicLaplaceDistribution(double location, double scale, double x_min, double x_max):\n    BasicTruncatedDistribution(x_min,x_max)\n{\n  _dist_parameters[\"location\"] = location;\n  _dist_parameters[\"scale\"] = scale;\n\n  _backend = new LaplaceDistributionBackend(location, scale);\n}\n\nBasicLaplaceDistribution::~BasicLaplaceDistribution()\n{\n  delete _backend;\n}\n\n\n/*\n * CLASS TRIANGULAR DISTRIBUTION\n */\n\n\n\nclass TriangularDistributionBackend : public DistributionBackendTemplate<boost::math::triangular> {\npublic:\n  TriangularDistributionBackend(double lower, double mode, double upper) {\n    _backend = new boost::math::triangular(lower, mode, upper);\n  }\n  ~TriangularDistributionBackend() {\n    delete _backend;\n  }\n};\n\n\nBasicTriangularDistribution::BasicTriangularDistribution(double x_peak, double lower_bound, double upper_bound)\n{\n  _dist_parameters[\"xPeak\"] = x_peak;\n  _dist_parameters[\"lowerBound\"] = lower_bound;\n  _dist_parameters[\"upperBound\"] = upper_bound;\n\n  if(not hasParameter(\"truncation\")) {\n    _dist_parameters[\"truncation\"] = 1.0;\n  }\n  if(not hasParameter(\"xMin\")) {\n    _dist_parameters[\"xMin\"] = lower_bound;\n  }\n  if(not hasParameter(\"xMax\")) {\n    _dist_parameters[\"xMax\"] = upper_bound;\n  }\n\n\n  if (upper_bound < lower_bound)\n    throwError(\"ERROR: bounds for triangular distribution are incorrect\");\n  if (upper_bound < _dist_parameters.find(\"xMin\") ->second)\n    throwError(\"ERROR: bounds and LB/UB are inconsistent for triangular distribution\");\n  if (lower_bound > _dist_parameters.find(\"xMax\") ->second)\n    throwError(\"ERROR: bounds and LB/UB are inconsistent for triangular distribution\");\n  _backend = new TriangularDistributionBackend(lower_bound, x_peak, upper_bound);\n\n}\nBasicTriangularDistribution::~BasicTriangularDistribution()\n{\n  delete _backend;\n}\n\n\n/*\n * CLASS EXPONENTIAL DISTRIBUTION\n */\n\n\nclass ExponentialDistributionBackend : public DistributionBackendTemplate<boost::math::exponential> {\npublic:\n  ExponentialDistributionBackend(double lambda) {\n    _backend = new boost::math::exponential(lambda);\n  }\n  ~ExponentialDistributionBackend() {\n    delete _backend;\n  }\n};\n\n\nBasicExponentialDistribution::BasicExponentialDistribution(double lambda, double low)\n{\n  _dist_parameters[\"lambda\"] = lambda;\n  _dist_parameters[\"low\"] = low;\n\n  if(not hasParameter(\"truncation\")) {\n    _dist_parameters[\"truncation\"] = 1.0;\n  }\n  if(not hasParameter(\"xMin\")) {\n    _dist_parameters[\"xMin\"] = low;\n  }\n  if(not hasParameter(\"xMax\")) {\n    _dist_parameters[\"xMax\"] = std::numeric_limits<double>::max( );\n  }\n\n\n  if (lambda<0)\n    throwError(\"ERROR: incorrect value of lambda for exponential distribution\");\n\n  _backend = new ExponentialDistributionBackend(lambda);\n}\n\n\nBasicExponentialDistribution::BasicExponentialDistribution(double lambda, double x_min, double x_max, double low):\n  BasicTruncatedDistribution(x_min,x_max)\n{\n    _dist_parameters[\"lambda\"] = lambda;\n    _dist_parameters[\"low\"] = low;\n    if (lambda<0)\n    throwError(\"ERROR: incorrect value of lambda for exponential distribution\");\n    _backend = new ExponentialDistributionBackend(lambda);\n}\n\n\nBasicExponentialDistribution::~BasicExponentialDistribution()\n{\n  delete _backend;\n}\n\n\n\ndouble\nBasicExponentialDistribution::untrPdf(double x){\n  double low = _dist_parameters.find(\"low\") ->second;\n  if(x >= low) {\n    return _backend->pdf(x-low);\n  } else {\n    return 0.0;\n  }\n}\n\ndouble\nBasicExponentialDistribution::untrCdf(double x){\n  double low = _dist_parameters.find(\"low\") ->second;\n  if(x >= low) {\n    return _backend->cdf(x-low);\n  } else {\n    return 0.0;\n  }\n}\n\ndouble\nBasicExponentialDistribution::cdf(double x){\n  return BasicTruncatedDistribution::cdf(x);\n  //double low = _dist_parameters.find(\"low\") ->second;\n}\n\ndouble\nBasicExponentialDistribution::inverseCdf(double x){\n  double low = _dist_parameters.find(\"low\") ->second;\n  return BasicTruncatedDistribution::inverseCdf(x) + low;\n}\n\n/*\n * CLASS WEIBULL DISTRIBUTION\n */\n\n\nclass WeibullDistributionBackend : public DistributionBackendTemplate< boost::math::weibull>  {\npublic:\n  WeibullDistributionBackend(double shape, double scale) {\n    _backend = new boost::math::weibull(shape, scale);\n  }\n  ~WeibullDistributionBackend() {\n    delete _backend;\n  }\n};\n\n\nBasicWeibullDistribution::BasicWeibullDistribution(double k, double lambda, double low)\n{\n  _dist_parameters[\"k\"] = k; //shape\n  _dist_parameters[\"lambda\"] = lambda; //scale\n  _dist_parameters[\"low\"] = low; //scale\n\n  if(not hasParameter(\"truncation\")) {\n    _dist_parameters[\"truncation\"] = 1.0;\n  }\n  if(not hasParameter(\"xMin\")) {\n    _dist_parameters[\"xMin\"] = low;\n  }\n  if(not hasParameter(\"xMax\")) {\n    _dist_parameters[\"xMax\"] = std::numeric_limits<double>::max( );\n  }\n\n  if ((lambda<0) || (k<0))\n    throwError(\"ERROR: incorrect value of k or lambda for weibull distribution\");\n\n  _backend = new WeibullDistributionBackend(k, lambda);\n}\n\nBasicWeibullDistribution::BasicWeibullDistribution(double k, double lambda, double x_min, double x_max, double low):\n  BasicTruncatedDistribution(x_min,x_max)\n{\n    _dist_parameters[\"k\"] = k; //shape\n    _dist_parameters[\"lambda\"] = lambda; //scale\n    _dist_parameters[\"low\"] = low; //scale\n\n    if ((lambda<0) || (k<0))\n    throwError(\"ERROR: incorrect value of k or lambda for weibull distribution\");\n    _backend = new WeibullDistributionBackend(k, lambda);\n}\n\nBasicWeibullDistribution::~BasicWeibullDistribution()\n{\n  delete _backend;\n}\n\n\ndouble\nBasicWeibullDistribution::untrPdf(double x){\n  double low = _dist_parameters.find(\"low\") ->second;\n  if(x >= low) {\n    return _backend->pdf(x-low);\n  } else {\n    return 0.0;\n  }\n}\n\ndouble\nBasicWeibullDistribution::untrCdf(double x){\n  double low = _dist_parameters.find(\"low\") ->second;\n  if(x >= low) {\n    return _backend->cdf(x-low);\n  } else {\n    return 0.0;\n  }\n}\n\ndouble\nBasicWeibullDistribution::inverseCdf(double x){\n  double low = _dist_parameters.find(\"low\") ->second;\n  return BasicTruncatedDistribution::inverseCdf(x) + low;\n}\n\n/*\n * CLASS GAMMA DISTRIBUTION\n */\n\n\nclass GammaDistributionBackend : public DistributionBackendTemplate<boost::math::gamma_distribution<> > {\npublic:\n  GammaDistributionBackend(double shape, double scale) {\n    _backend = new boost::math::gamma_distribution<>(shape, scale);\n  }\n  ~GammaDistributionBackend() {\n    delete _backend;\n  }\n};\n\n\nBasicGammaDistribution::BasicGammaDistribution(double k, double theta, double low)\n{\n  _dist_parameters[\"k\"] = k; //shape\n  _dist_parameters[\"theta\"] = theta; //scale\n  _dist_parameters[\"low\"] = low; //low value shift. 0.0 would be a regular gamma\n  // distribution\n\n  if(not hasParameter(\"truncation\")) {\n    _dist_parameters[\"truncation\"] = 1.0;\n  }\n  if(not hasParameter(\"xMin\")) {\n    _dist_parameters[\"xMin\"] = low;\n  }\n  if(not hasParameter(\"xMax\")) {\n    _dist_parameters[\"xMax\"] = std::numeric_limits<double>::max( );\n  }\n\n\n  if ((theta<0) || (k<0))\n    throwError(\"ERROR: incorrect value of k or theta for gamma distribution\");\n\n  _backend = new GammaDistributionBackend(k, theta);\n}\n\nBasicGammaDistribution::BasicGammaDistribution(double k, double theta, double low, double x_min, double x_max):\n  BasicTruncatedDistribution(x_min,x_max)\n{\n    _dist_parameters[\"k\"] = k; //shape\n    _dist_parameters[\"theta\"] = theta; //scale\n    _dist_parameters[\"low\"] = low; //low value shift. 0.0 would be a regular gamma\n    // distribution\n\n    if ((theta<0) || (k<0))\n    throwError(\"ERROR: incorrect value of k or theta for gamma distribution\");\n\n    _backend = new GammaDistributionBackend(k, theta);\n}\n\nBasicGammaDistribution::~BasicGammaDistribution()\n{\n  delete _backend;\n}\n\n\ndouble\nBasicGammaDistribution::untrCdf(double x){\n  double low = _dist_parameters.find(\"low\") ->second;\n  if(x > 1.0e100) {\n    return 1.0;\n  } else if(x >= low) {\n    return _backend->cdf(x - low);\n  } else  {\n    return 0.0;\n  }\n}\n\n\ndouble\nBasicGammaDistribution::untrPdf(double x){\n  double low = _dist_parameters.find(\"low\") ->second;\n  return BasicTruncatedDistribution::untrPdf(x - low);\n}\n\ndouble\nBasicGammaDistribution::untrInverseCdf(double x){\n  double low = _dist_parameters.find(\"low\") ->second;\n  return BasicTruncatedDistribution::untrInverseCdf(x) + low;\n}\n\n/*\n * CLASS BETA DISTRIBUTION\n */\n\n\nclass BetaDistributionBackend : public DistributionBackendTemplate<boost::math::beta_distribution<> > {\npublic:\n  BetaDistributionBackend(double alpha, double beta) {\n    _backend = new boost::math::beta_distribution<>(alpha, beta);\n  }\n  ~BetaDistributionBackend() {\n    delete _backend;\n  }\n};\n\n\nBasicBetaDistribution::BasicBetaDistribution(double alpha, double beta, double scale, double low)\n{\n  _dist_parameters[\"alpha\"] = alpha;\n  _dist_parameters[\"beta\" ] = beta;\n  _dist_parameters[\"scale\"] = scale;\n  _dist_parameters[\"low\"  ] = low;\n\n  if(not hasParameter(\"truncation\")) {\n    _dist_parameters[\"truncation\"] = 1.0;\n  }\n  if(not hasParameter(\"xMin\")) {\n    _dist_parameters[\"xMin\"] = low;\n  }\n  if(not hasParameter(\"xMax\")) {\n    _dist_parameters[\"xMax\"] = low+scale;\n  }\n\n  if ((alpha<0) || (beta<0))\n    throwError(\"ERROR: incorrect value of alpha or beta for beta distribution\");\n\n  _backend = new BetaDistributionBackend(alpha, beta);\n}\n\nBasicBetaDistribution::BasicBetaDistribution(double alpha, double beta, double scale, double x_min, double x_max, double low):\n  BasicTruncatedDistribution(x_min,x_max)\n{\n    _dist_parameters[\"alpha\"] = alpha;\n    _dist_parameters[\"beta\" ] = beta;\n    _dist_parameters[\"scale\"] = scale;\n    _dist_parameters[\"low\"  ] = low;\n\n    if ((alpha<0) || (beta<0))\n    throwError(\"ERROR: incorrect value of alpha or beta for beta distribution\");\n\n\n    _backend = new BetaDistributionBackend(alpha, beta);\n}\n\nBasicBetaDistribution::~BasicBetaDistribution()\n{\n  delete _backend;\n}\n\ndouble\nBasicBetaDistribution::untrPdf(double x){\n  double scale = _dist_parameters.find(\"scale\") ->second;\n  double low   = _dist_parameters.find(\"low\"  ) ->second;\n  return _backend->pdf( (x-low)/scale);\n}\n\ndouble\nBasicBetaDistribution::untrCdf(double x){\n  double scale = _dist_parameters.find(\"scale\") ->second;\n  double low   = _dist_parameters.find(\"low\"  ) ->second;\n  if(x >= low and x <= low+scale) {\n    return _backend->cdf( (x-low)/scale );\n  } else if(x < low){\n    return 0.0;\n  } else {\n    return 1.0;\n  }\n}\n\ndouble\nBasicBetaDistribution::pdf(double x){\n  double scale   = _dist_parameters.find(\"scale\"  ) ->second;\n  return BasicTruncatedDistribution::pdf( x )/scale;// scaling happens in untrPdf\n}\n\ndouble\nBasicBetaDistribution::cdf(double x){\n  //double scale = _dist_parameters.find(\"scale\") ->second;\n  //double low   = _dist_parameters.find(\"low\"  ) ->second;\n  return BasicTruncatedDistribution::cdf( x );// -low)/scale ); scaling happens in untrCdf\n}\n\ndouble\nBasicBetaDistribution::inverseCdf(double x){\n  double scale = _dist_parameters.find(\"scale\") ->second;\n  double low   = _dist_parameters.find(\"low\"  ) ->second;\n  return BasicTruncatedDistribution::inverseCdf( x )*scale+low;\n}\n\n/*\n * CLASS POISSON DISTRIBUTION\n */\n\n\nclass PoissonDistributionBackend : public DistributionBackendTemplate<boost::math::poisson_distribution<> > {\npublic:\n  PoissonDistributionBackend(double mu) {\n    _backend = new boost::math::poisson_distribution<>(mu);\n  }\n  ~PoissonDistributionBackend() {\n    delete _backend;\n  }\n};\n\n\nBasicPoissonDistribution::BasicPoissonDistribution(double mu)\n{\n  _dist_parameters[\"mu\"] = mu;\n\n  if(not hasParameter(\"truncation\")) {\n    _dist_parameters[\"truncation\"] = 1.0;\n  }\n  if(not hasParameter(\"xMin\")) {\n    _dist_parameters[\"xMin\"] = -std::numeric_limits<double>::max( );\n  }\n  if(not hasParameter(\"xMax\")) {\n    _dist_parameters[\"xMax\"] = std::numeric_limits<double>::max( );\n  }\n\n  if (mu<0)\n    throwError(\"ERROR: incorrect value of mu for poisson distribution\");\n\n  _backend = new PoissonDistributionBackend(mu);\n}\n\n\nBasicPoissonDistribution::~BasicPoissonDistribution()\n{\n  delete _backend;\n}\n\ndouble\nBasicPoissonDistribution::untrCdf(double x){\n  if(x >= 0) {\n    return _backend->cdf(x);\n  } else {\n    return 0.0;\n  }\n}\n\ndouble\nBasicPoissonDistribution::pdf(double x){\n   double x_min = _dist_parameters.find(\"xMin\") ->second;\n   double x_max = _dist_parameters.find(\"xMax\") ->second;\n\n   double value;\n\n   if (_dist_parameters.find(\"truncation\") ->second == 1)\n          if (x<x_min)\n                  value=0;\n          else if (x>x_max)\n                  value=0;\n          else\n                  value = 1/(untrCdf(x_max) - untrCdf(x_min)) * untrPdf(x);\n   else\n      value=-1;\n\n   return value;\n}\n\ndouble\nBasicPoissonDistribution::cdf(double x){\n   double x_min = _dist_parameters.find(\"xMin\") ->second;\n   double x_max = _dist_parameters.find(\"xMax\") ->second;\n\n   double value;\n\n   if (_dist_parameters.find(\"truncation\") ->second == 1)\n          if (x<x_min)\n                  value=0;\n          else if (x>x_max)\n                  value=1;\n          else\n                  value = 1/(untrCdf(x_max) - untrCdf(x_min)) * (untrCdf(x) - untrCdf(x_min));\n   else\n      value=-1;\n\n   return value;\n}\n\ndouble\nBasicPoissonDistribution::inverseCdf(double x){\n   double value;\n   double x_min = _dist_parameters.find(\"xMin\") ->second;\n   double x_max = _dist_parameters.find(\"xMax\") ->second;\n\n   if(x == 1.0) {\n     return x_max;\n   }\n   if (_dist_parameters.find(\"truncation\") ->second == 1){\n     double temp = untrCdf(x_min) + x * (untrCdf(x_max)-untrCdf(x_min));\n     value=untrInverseCdf(temp);\n   } else {\n      value=-1;\n   }\n   return value;\n}\n\n/*\n * CLASS BINOMIAL DISTRIBUTION\n */\n\n\nclass BinomialDistributionBackend : public DistributionBackendTemplate<boost::math::binomial_distribution<> > {\npublic:\n  BinomialDistributionBackend(double n, double p) {\n    _backend = new boost::math::binomial_distribution<>(n, p);\n  }\n  ~BinomialDistributionBackend() {\n    delete _backend;\n  }\n};\n\n\nBasicBinomialDistribution::BasicBinomialDistribution(double n, double p)\n{\n  _dist_parameters[\"n\"] = n;\n  _dist_parameters[\"p\"] = p;\n\n  if (n<0 or p<0)\n    throwError(\"ERROR: incorrect value of n or p for binomial distribution\");\n\n  _backend = new BinomialDistributionBackend(n, p);\n}\n\nBasicBinomialDistribution::~BasicBinomialDistribution()\n{\n  delete _backend;\n}\n\ndouble\nBasicBinomialDistribution::untrCdf(double x){\n  if(x >= 0) {\n    return _backend->cdf(x);\n  } else {\n    return 0.0;\n  }\n}\n\n/*\n * CLASS BERNOULLI DISTRIBUTION\n */\n\n\nclass BernoulliDistributionBackend : public DistributionBackendTemplate<boost::math::bernoulli_distribution<> > {\npublic:\n  BernoulliDistributionBackend(double p) {\n    _backend = new boost::math::bernoulli_distribution<>(p);\n  }\n  ~BernoulliDistributionBackend() {\n    delete _backend;\n  }\n};\n\n\nBasicBernoulliDistribution::BasicBernoulliDistribution(double p)\n{\n  _dist_parameters[\"p\"] = p;\n\n  if (p<0)\n    throwError(\"ERROR: incorrect value of p for bernoulli distribution\");\n\n  _backend = new BernoulliDistributionBackend(p);\n}\n\nBasicBernoulliDistribution::~BasicBernoulliDistribution()\n{\n  delete _backend;\n}\n\n/*\n * CLASS GEOMETRIC DISTRIBUTION\n */\n\nclass GeometricDistributionBackend : public DistributionBackendTemplate<boost::math::geometric_distribution<> > {\npublic:\n  GeometricDistributionBackend(double p) {\n    _backend = new boost::math::geometric_distribution<>(p);\n  }\n  ~GeometricDistributionBackend() {\n    delete _backend;\n  }\n};\n\nBasicGeometricDistribution::BasicGeometricDistribution(double p)\n{\n  _dist_parameters[\"p\"] = p;\n\n  if (p<0)\n    throwError(\"ERROR: incorrect value of p for geometric distribution\");\n\n  _backend = new GeometricDistributionBackend(p);\n}\n\nBasicGeometricDistribution::~BasicGeometricDistribution()\n{\n  delete _backend;\n}\n\n/*\n * CLASS CONSTANT DISTRIBUTION\n */\n\nBasicConstantDistribution::BasicConstantDistribution(double value){\n  _value = value;\n}\nBasicConstantDistribution::~BasicConstantDistribution(){}\ndouble  BasicConstantDistribution::pdf(double x){\n  return untrPdf(x);\n}\ndouble  BasicConstantDistribution::cdf(double x){\n  return untrCdf(x);\n}\ndouble  BasicConstantDistribution::inverseCdf(double x){\n  return untrInverseCdf(x);\n}\n\ndouble BasicConstantDistribution::untrPdf(double x){\n  if(x == _value){\n    return std::numeric_limits<double>::max( )/2.0;\n  } else {\n    return 0.0;\n  }\n}\n\ndouble BasicConstantDistribution::untrCdf(double x){\n  if(x < _value) {\n    return 0.0;\n  } else if(x > _value) {\n    return 1.0;\n  } else {\n    return 0.5;\n  }\n}\n\ndouble BasicConstantDistribution::untrCdfComplement(double){\n  throwError(\"Not Implemented\");\n  return _value;\n}\n\ndouble BasicConstantDistribution::untrInverseCdf(double){\n  return _value;\n}\n\ndouble BasicConstantDistribution::untrMean(){\n  return _value;\n}\n\n/**\n   Calculates the untruncated standard deviation\n   \\return the standard deviation\n*/\ndouble BasicConstantDistribution::untrStdDev(){\n  return 0.0;\n}\n\ndouble BasicConstantDistribution::untrMedian(){\n  return _value;\n}\n\ndouble BasicConstantDistribution::untrMode(){\n  return _value;\n}\n\ndouble BasicConstantDistribution::untrHazard(double /*x*/){\n  throwError(\"Not implemented\");\n  return _value;\n}\n\n\n/*\n * CLASS CUSTOM DISTRIBUTION\n */\n\n\n// BasicCustomDistribution::BasicCustomDistribution(double x_coordinates, double y_coordinates, int fitting_type, double n_points)\n// {\n//    _dist_parameters[\"x_coordinates\"] = x_coordinates;\n//    _dist_parameters[\"y_coordinates\"] = y_coordinates;\n//    _dist_parameters[\"fitting_type\"] = fitting_type;\n//    _dist_parameters[\"n_points\"] = n_points;\n\n// }\n\n// BasicCustomDistribution::~BasicCustomDistribution()\n// {\n// }\n\n// double\n// BasicCustomDistribution::pdf(double & x){\n//    double value=_interpolation.interpolation(x);\n\n//    return value;\n// }\n\n// double\n// BasicCustomDistribution::cdf(double & ){\n//   //XXX implement\n//    double value=-1;\n\n//    return value;\n// }\n\n// double\n// BasicCustomDistribution::inverseCdf(double & ){\n//   //XXX implement\n//    double value=-1;\n//    return value;\n// }\n\n\n\n//\n//   // Beta pdf\n//      double distribution_1D::betaPdf (double x){\n//         // parameter1=alpha   >0\n//         // parameter2=beta    >0\n//         // 0<x<1\n//\n//         double value;\n//\n//         /*if ((x > 0)&&(x < 1)&&(_parameter1 > 0)&&(_parameter2 > 0))\n//              value = 1/betaFunc(_parameter1,_parameter2)*pow(x,_parameter1-1)*pow(1-x,_parameter2-1);\n//              else */\n//            value=-1;\n//\n//         return value;\n//      }\n//\n//      double distribution_1D::betaCdf (double x){\n//         // parameter1=alpha   >0\n//         // parameter2=beta    >0\n//         // 0<x<1\n//\n//         double value;\n//\n//         /*if ((x > 0)&&(x < 1)&&(_parameter1 > 0)&&(_parameter2 > 0))\n//            value = betaInc(_parameter1,_parameter2 ,x);\n//                else */\n//            value=-1;\n//\n//         return value;\n//      }\n\n//\n//   // Gamma pdf\n//      double distribution_1D::gammaPdf(double x){\n//         // parameter1= k   >0\n//         // parameter2= theta     >0\n//         // x>=0\n//\n//         double value;\n//\n//         /* if ((x >= 0)&&(_parameter1 > 0)&&(_parameter2 > 0))\n//            value=1/gammaFunc(_parameter1)/pow(_parameter2,_parameter1)*pow(x,_parameter1-1)*exp(-x/_parameter2);\n//                else */\n//            value=1;\n//\n//         return value;\n//      }\n//\n//      double distribution_1D::gammaCdf(double x){\n//         // parameter1=alpha, k   >0\n//         // parameter2=beta, theta     >0\n//         // x>=0\n//\n//         double value;\n//\n//         /* if ((x >= 0)&&(_parameter1 > 0)&&(_parameter2 > 0))\n//              value= gammp(_parameter1,x/_parameter2);\n//              else */\n//            value=1;\n//\n//         return value;\n//      }\n\n\n//      double distribution_1D::gammaRandNumberGenerator(){\n//          double value=-1;//gammaRNG(_parameter1,_parameter2);\n//         return value;\n//      }\n//\n//      double distribution_1D::betaRandNumberGenerator(){\n//          double value=-1;//betaRNG(_parameter1,_parameter2);\n//         return value;\n//      }\n//\n//      double distribution_1D::triangularRandNumberGenerator(){\n//         double value;\n//         double RNG = rand()/double(RAND_MAX);\n//         double referenceValue=(_parameter1-_x_min)/(_x_max-_x_min);\n//\n//         if (RNG<referenceValue)\n//            value= _x_min+sqrt(RNG*(_parameter1-_x_min)*(_x_max-_x_min));\n//         else\n//            value=_x_max-sqrt((1-RNG)*(_x_max-_parameter1)*(_x_max-_x_min));\n//         return value;\n//      }\n", "meta": {"hexsha": "5ec89c6a776a3f54baba7b0d01fefd383e03ecb9", "size": 34219, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "crow/src/distributions/distribution_1D.cxx", "max_stars_repo_name": "rinelson456/raven", "max_stars_repo_head_hexsha": "1114246136a2f72969e75b5e99a11b35500d4eef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 159.0, "max_stars_repo_stars_event_min_datetime": "2017-03-24T21:07:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:44:40.000Z", "max_issues_repo_path": "crow/src/distributions/distribution_1D.cxx", "max_issues_repo_name": "rinelson456/raven", "max_issues_repo_head_hexsha": "1114246136a2f72969e75b5e99a11b35500d4eef", "max_issues_repo_licenses": ["Apache-2.0"], "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": "crow/src/distributions/distribution_1D.cxx", "max_forks_repo_name": "rinelson456/raven", "max_forks_repo_head_hexsha": "1114246136a2f72969e75b5e99a11b35500d4eef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 95.0, "max_forks_repo_forks_event_min_datetime": "2017-03-24T21:05:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T17:30:22.000Z", "avg_line_length": 25.3286454478, "max_line_length": 130, "alphanum_fraction": 0.6920716561, "num_tokens": 8846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2876858608313316}}
{"text": "/*  $Id$\n * \n *  Copyright 2010 Anders Wallin (anders.e.e.wallin \"at\" gmail.com)\n *  \n *  This file is part of OpenCAMlib.\n *\n *  OpenCAMlib 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 *  OpenCAMlib 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 OpenCAMlib.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n// this is mostly a translation to c++ of the earlier c# code\n// http://code.google.com/p/monocam/source/browse/trunk/Project2/monocam_console/monocam_console/kdtree.cs\n\n\n\n#include <boost/foreach.hpp>\n\n#include \"millingcutter.h\"\n#include \"point.h\"\n#include \"triangle.h\"\n#include \"numeric.h\"\n#include \"kdtree.h\"\n\nnamespace ocl\n{\n\n//#define DEBUG_KD\n\n\n\n//********   KDNode ********************** */\n\n\nKDNode::KDNode(int d, double cv, KDNode *parent, KDNode *hi_c, KDNode *lo_c,\n            const std::list<Triangle> *tlist, int lev) \n{\n    dim = d;\n    cutval = cv;\n    up = parent;\n    hi = hi_c;\n    lo = lo_c;\n    tris = tlist;\n    level = lev;\n}\n\n\n\n/// given a list of triangles, build and return the root node of a kd-tree with the triangles\nKDNode* KDNode::build_kdtree(const std::list<Triangle> *tris, \n                             unsigned int bucketSize,   // defaults to 1\n                             int level,                 // defualts to 0 == root\n                             KDNode *parent)            // defaults to NULL    \n{\n    \n    if (tris->size() == 0) { //this is a fatal error.\n        std::cout << \"kdtree.cpp ERROR: build_kdtree() called with tris->size()==0 ! \\n\";\n        assert(0);\n        return 0;\n    }\n    \n    // calculate spread in order to know how to cut\n    //static int spreadstat[4];\n    Spread* spr = KDNode::spread(tris);\n    //spreadstat[ spr->d ]++;\n    // calculate cut value\n    double cutvalue = spr->start + spr->val/2; // cut in the middle\n    \n    // if spr.val==0 (no need/possibility to subdivide anymore)\n    // OR number of triangles is smaller than bucketSize \n    // then return a bucket node\n    if ( (tris->size() <= bucketSize) || (spr->val == 0.0)) {\n        //std::cout << \"Bucket with len(tris)=\" << tris->size() << \"\\n\";\n        KDNode *bucket;\n        if ( (spr->d == 0) || (spr->d == 2) )  {// maxx or maxy cut\n            // does the node spread value make a difference here??\n            bucket = new KDNode(spr->d, spr->start+spr->val, parent , NULL, NULL, tris, level);\n            //bucket = new KDNode(spr->d, 0.0 , parent , NULL, NULL, tris, level);\n        }\n        else {// the min cut case:\n            // does the node spread value make a difference here??\n             bucket = new KDNode(spr->d, spr->start, parent , NULL, NULL, tris, level);\n            //bucket = new KDNode(spr->d, 0.0 , parent , NULL, NULL, tris, level);\n        }\n        return bucket;\n    }\n    \n   \n    \n    // build lists of triangles for hi and lo child nodes\n    std::list<Triangle> *lolist = new std::list<Triangle>();\n    std::list<Triangle> *hilist = new std::list<Triangle>();\n    BOOST_FOREACH(Triangle t, *tris) { // loop through each triangle and put it in either lolist or hilist\n        #ifdef DEBUG_KD\n            std::cout << \"adding tri=\" << t;\n            std::cout << \" dim=\" << spr->d << \"\\n\";\n        #endif\n        if (spr->d == 0) { // cut along maxx\n            if (t.maxx > cutvalue) {\n                hilist->push_back(t);\n            }\n            else {\n                lolist->push_back(t);\n            }\n        } else if (spr->d == 1) { // cut along minx\n            if (t.minx > cutvalue) {\n                hilist->push_back(t);\n            }\n            else {\n                lolist->push_back(t);           \n            }\n        } else if (spr->d == 2) { // cut along maxy\n            if (t.maxy > cutvalue) {\n                hilist->push_back(t);\n            }\n            else {\n                lolist->push_back(t);           \n            }\n        } else if (spr->d == 3) { // cut along miny\n            if (t.miny > cutvalue) {\n                hilist->push_back(t);\n            }\n            else {\n                lolist->push_back(t);           \n            }\n        }\n            \n    } // end loop through each triangle\n    \n    if (hilist->size() == 0) {// an error ??\n        std::cout << \"kdtree.cpp: hilist.size()==0!\\n\";\n        assert(0);\n    }\n    if (lolist->size() == 0) {\n        std::cout << \"kdtree.cpp: lolist.size()==0!\\n\";\n        assert(0);\n    }\n    \n    /*\n    std::cout << \"hilist.size()=\" << hilist->size() << \"\\n\";\n    std::cout << \"lolist.size()=\" << lolist->size() << \"\\n\";\n    std::cout << \"sum: \" << hilist->size()+lolist->size() << \"== \" << tris->size() << \" ? \\n\";\n    char c;\n    std::cin >> c;\n    */\n    \n    //                         dim     value    parent  hi   lo   trilist  level\n    KDNode *node = new KDNode(spr->d, cutvalue, parent, NULL,NULL,NULL, level);\n    \n    // recursion:                   list    bucketsize   level   parent\n    node->hi = KDNode::build_kdtree(hilist, bucketSize, level+1, node);\n    node->lo = KDNode::build_kdtree(lolist, bucketSize, level+1, node);    \n    \n    /*\n    for (int m=0;m<4;m++)\n        std::cout << m << \" : \" << spreadstat[ m ] << \"\\n\";\n    */\n    // return a new node\n    return node;\n}\n\n\nbool Spread::spread_compare(Spread *x, Spread *y) {\n    if (x->val > y->val)\n        return true;\n    else\n        return false;\n}\n\nint KDNode::cutcount=0;\n\n/// find the maximum 'extent' of Triangle list tris along dimension d\nSpread* KDNode::spread(const std::list<Triangle> *tris) {\n    double max_xplus, min_xplus, max_xminus, min_xminus;\n    double max_yplus, min_yplus, max_yminus, min_yminus;\n    \n    double spr_xplus, spr_xminus, spr_yplus, spr_yminus;\n    \n    if (tris->size() == 0) {\n        std::cout << \"kdtree.cpp ERROR, spread() called with tris->size()==0 ! \\n\";\n        assert( 0 );\n        return NULL;\n    } else {\n        bool first=true;\n        BOOST_FOREACH(Triangle t, *tris) {\n            // t.calcBB(); //ugly...\n            if (first) { // initialize things on the first run\n                max_xplus  = t.maxx;\n                min_xplus  = t.maxx;\n                max_xminus = t.minx;\n                min_xminus = t.minx;\n\n                max_yplus  = t.maxy;\n                min_yplus  = t.maxy;\n                max_yminus = t.miny;\n                min_yminus = t.miny;\n                first=false;\n            } // end initialize\n            else { // FIXME madness really, but for only 4 dimensions this works...\n            \n                // compute spread in xplus\n                if (t.maxx > max_xplus)\n                    max_xplus = t.maxx;\n                if (t.maxx < min_xplus)\n                    min_xplus = t.maxx;\n                    \n                // compute spread in xminus\n                if (t.minx > max_xminus)\n                    max_xminus = t.minx;\n                if (t.minx < min_xminus)\n                    min_xminus = t.minx;\n                \n                // compute spread in yplus\n                if (t.maxy > max_yplus)\n                    max_yplus = t.maxy;\n                if (t.maxy < min_yplus)\n                    min_yplus = t.maxy;\n                    \n                // compute spread in yminus\n                if (t.miny > max_yminus)\n                    max_yminus = t.miny;\n                if (t.miny < min_yminus)\n                    min_yminus = t.miny;\n            }\n        \n        } // end FOREACH triangle in tris\n        \n        // calculate the spread along each dimension\n        spr_xplus  =  max_xplus  - min_xplus;\n        spr_xminus =  max_xminus - min_xminus;\n        spr_yplus  =  max_yplus  - min_yplus;\n        spr_yminus =  max_yminus - min_yminus;\n        \n        // spreads are distances, they should be zero or positive.\n        assert(  spr_xplus  >= 0.0 );\n        assert(  spr_xminus >= 0.0 );\n        assert(  spr_yplus  >= 0.0 );\n        assert(  spr_yminus >= 0.0 );\n      \n        // put the spreads in a list\n        std::vector<Spread*> spreads;\n        spreads.push_back( new Spread(0, spr_xplus , min_xplus)   );  // dim=0  is maxx\n        spreads.push_back( new Spread(1, spr_xminus, min_xminus) );   // dim=1  is minx\n        spreads.push_back( new Spread(2, spr_yplus , min_yplus)   );  // dim=2  is maxy\n        spreads.push_back( new Spread(3, spr_yminus, min_yminus) );   // dim=3  is miny\n        std::sort(spreads.begin(), spreads.end(), Spread::spread_compare); // sort the list\n        // priority-queue could also be used ??\n        \n        /*\n        std::cout << \"\\n\";\n        std::cout <<\"spreads for \" << tris->size() << \" triangles:\\n\";\n        std::cout <<\"0: spread=\" << spr_xplus << \"\\n\";\n        std::cout <<\"1: spread=\" << spr_xminus << \"\\n\";\n        std::cout <<\"2: spread=\" << spr_yplus << \"\\n\";\n        std::cout <<\"3: spread=\" << spr_yminus << \"\\n\";\n        std::cout << \" selecting \" << (spreads[0])->d << \" with s=\"<< (spreads[0])->val << \"\\n\";\n        char c;\n        std::cin >> c;\n        */\n        \n        \n        cutcount++;\n        if (cutcount == 4)\n            cutcount = 0;\n        \n        // select each dim in turn\n        //return spreads[ cutcount ];\n        \n        // select the biggest spread and return\n        return spreads[ 0 ];\n        \n    } // end tris->size != 0\n\n} // end spread()\n\nbool KDNode::overlap(const KDNode *node, const CLPoint &cl, const MillingCutter &cutter)\n{\n    switch(node->dim) { \n        case 0: // cut along xplus\n            if ( node->cutval <= cl.x - cutter.getRadius() )\n                return false;\n            else \n                return true;\n            break;\n        case 1: // cut along xminus\n            if ( node->cutval >= cl.x + cutter.getRadius() )\n                return false;\n            else \n                return true;\n            break;\n        case 2: // cut along yplus\n            if ( node->cutval <= cl.y - cutter.getRadius() )\n                return false;\n            else \n                return true;\n            break;\n        case 3: // cut along yminus\n            if ( node->cutval >= cl.y + cutter.getRadius() )\n                return false;\n            else \n                return true;\n            break;\n        default:\n            assert(0);\n    } // end of switch(dim)\n\n    return false;\n}\n\n\n/// returns all triangles under KDNode node in the tree\nvoid KDNode::getTriangles( std::list<Triangle> *tris, KDNode *node)\n{\n    if (node->tris != NULL) { \n        // found a bucket node, add all triangles\n        BOOST_FOREACH(Triangle t, *(node->tris)) {\n            tris->push_back(t); \n        }\n        return;\n    }\n    // not a bucket node, so search recursively high and low:\n    KDNode::getTriangles(tris, node->hi);\n    KDNode::getTriangles(tris, node->lo);\n    return;\n}\n\n#define DEBUG_KD_SEARCH\n\n\n/// search kd-tree starting at KDNode node for triangles.\n/// find the ones which overlap (in the xy-plane)\n/// with the MillingCutter cutter positioned at  Point cl\n/// these triangles are added to the tris list.\nvoid KDNode::search_kdtree( std::list<Triangle>* tris,      // found triangles added to tris\n                            const CLPoint &cl,              // cutter positioned at cl\n                            const MillingCutter &cutter,    // cutter\n                            KDNode *node)                   // start search here and recurse into tree\n{\n    // we found a bucket node, so add all triangles and return.\n    if (node->tris != NULL) { \n        //std::cout << \"bucket: cl=\" << cl << \"r=\" << cutter.getRadius() \n        //          << \" len(tris)=\" << node->tris->size() << \" KDNode:\" << *node << \"\\n\";\n\n        //if ( KDNode::overlap(node,cl,cutter) ) {  // check if node overlaps\n            #ifdef DEBUG_KD_SEARCH\n                 //std::cout << \" returning bucket node with len(tris)=\"<< (*(node->tris)).size() << \"\\n\";\n                 //char c;\n                 //std::cin >> c;\n            #endif\n            BOOST_FOREACH( Triangle t, *(node->tris) ) {\n                //std::cout << t << \"\\n\";\n                //double r = cutter.getRadius();\n                //std::cout << \"T: \" << t.minx << \"\\t\" << t.maxx << \"\\t\" << t.miny << \"\\t\" << t.maxy << \"\\n\";\n                //std::cout << \"C: \" << cl.x-r << \"\\t\" << cl.x+r << \"\\t\" << cl.y-r << \"\\t\" << cl.y+r << \"\\n\";\n                //std::cout << \"overlap?:\" << KDTree::overlap(node,cl,cutter) << \"\\n\";\n                \n                // THIS IS PROBABLY WRONG, should not have to do an explicit overlap check here\n                // if ( cutter.overlaps(cl,t) ) { // explicit cutter-overlap check\n                    tris->push_back(t); \n                //}\n                \n                \n            } // loop through triangles\n\n        //} // node overlap check\n\n        return;\n    } // end bucket-node\n    \n    // not a bucket node, so recursevily seach hi/lo branches of KDNode\n    \n    #ifdef DEBUG_KD_SEARCH\n        //std::cout << \"dim=\" << node->dim << \" cv=\" << node->cutval << \"\\n\";\n    #endif \n    //std::cout << \"cl=\" << cl << \"r=\" << cutter.getRadius() \n    //              << \" Internal KDNode:\" << *node << \"\\n\";\n    switch(node->dim) { // ugly, solve with polymorphism?\n        case 0: // cut along xplus\n            // if one child node is not overlapping, search only the other\n            if ( node->cutval < ( cl.x - cutter.getRadius() ) ) {\n                #ifdef DEBUG_KD_SEARCH\n                    //std::cout << \" dim=\" << node->dim << \" branch hi\\n\";\n                    //std::cout << \"NO triangles with xmax < \" << node-> cutval << \"\\n\"; \n                #endif \n                KDNode::search_kdtree(tris, cl, cutter, node->hi); //hi\n            } \n            else { // else we need to search both child-nodes\n                #ifdef DEBUG_KD_SEARCH\n                    //std::cout << \" dim=\" << node->dim << \" branch hi AND lo\\n\";\n                #endif \n                KDNode::search_kdtree(tris, cl, cutter, node->hi);\n                KDNode::search_kdtree(tris, cl, cutter, node->lo);\n            }\n            break;\n        case 1: // cut along xminus\n            if ( node->cutval > ( cl.x + cutter.getRadius() ) ) {\n                #ifdef DEBUG_KD_SEARCH\n                    //std::cout << \" dim=\" << node->dim << \" branch lo\\n\";\n                    //std::cout << \"NO triangles with xmin < \" << node-> cutval << \"\\n\";\n                #endif \n                KDNode::search_kdtree(tris, cl, cutter, node->lo);\n            }\n            else {\n                KDNode::search_kdtree(tris, cl, cutter, node->hi);\n                KDNode::search_kdtree(tris, cl, cutter, node->lo);\n            }\n            break;\n        case 2: // cut along yplus\n            if ( node->cutval < ( cl.y - cutter.getRadius() ) ) {\n                #ifdef DEBUG_KD_SEARCH\n                    // std::cout << \" dim=\" << node->dim << \" branch hi\\n\";\n                    //std::cout << \"NO triangles with ymax < \" << node-> cutval << \"\\n\";\n                #endif \n                KDNode::search_kdtree(tris, cl, cutter, node->hi);\n            }\n            else {\n                #ifdef DEBUG_KD_SEARCH\n                    // std::cout << \" dim=\" << node->dim << \" branch hi AND lo\\n\";\n                #endif \n                KDNode::search_kdtree(tris, cl, cutter, node->hi);\n                KDNode::search_kdtree(tris, cl, cutter, node->lo);\n            }        \n            break;\n        case 3: // cut along yminus\n            if ( node->cutval > ( cl.y + cutter.getRadius() ) ) {\n                #ifdef DEBUG_KD_SEARCH\n                    //std::cout << \" dim=\" << node->dim << \" branch lo\\n\";\n                    //std::cout << \"NO triangles with ymin > \" << node-> cutval << \"\\n\";\n                #endif \n                KDNode::search_kdtree(tris, cl, cutter, node->lo);\n            }\n            else {\n                #ifdef DEBUG_KD_SEARCH\n                    //std::cout << \" dim=\" << node->dim << \" branch hi AND lo\\n\";\n                #endif \n                KDNode::search_kdtree(tris, cl, cutter, node->lo);\n                KDNode::search_kdtree(tris, cl, cutter, node->hi);\n            }      \n            break;\n        default:\n            std::cout << \"kdtree.cpp ERROR!\\n\"; // error\n            assert(0);\n    } // end of switch(dim)\n    \n    // we get here after all the recursive calls above.\n    return; \n    \n\n} // end search_kdtree()\n\n//*********** Spread ****************\n\nSpread::Spread(int dim, double v, double s)\n{\n    d = dim;\n    val = v;\n    start = s;\n}\n\n\n\n//********  string output ********************** */\nstd::string KDNode::str() const\n{\n    std::ostringstream o;\n    o << *this;\n    return o.str();\n}\n\nstd::ostream& operator<<(std::ostream &stream, const KDNode root)\n{\n    stream << \"KDNode d:\" << root.dim << \" cv:\" << root.cutval;    \n    return stream;\n}\n\n} // end namespace\n// end file kdtree.cpp\n", "meta": {"hexsha": "22fc34c9f76a09dd816ba56884df2b65c4592515", "size": 17239, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "opencamlib/src/attic/kdtree.cpp", "max_stars_repo_name": "JohnyEngine/CNC", "max_stars_repo_head_hexsha": "e4c77250ab2b749d3014022cbb5eb9924e939993", "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": "opencamlib/src/attic/kdtree.cpp", "max_issues_repo_name": "JohnyEngine/CNC", "max_issues_repo_head_hexsha": "e4c77250ab2b749d3014022cbb5eb9924e939993", "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": "opencamlib/src/attic/kdtree.cpp", "max_forks_repo_name": "JohnyEngine/CNC", "max_forks_repo_head_hexsha": "e4c77250ab2b749d3014022cbb5eb9924e939993", "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.3983572895, "max_line_length": 109, "alphanum_fraction": 0.4895875631, "num_tokens": 4509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765155565327, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2876750577850073}}
{"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// Copyright (c) 2003, 2006   Gerald I. Evenden\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_OMERC_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_OMERC_HPP\r\n\r\n#include <boost/geometry/util/math.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_phi2.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_tsfn.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 omerc\r\n    {\r\n            template <typename T>\r\n            struct par_omerc\r\n            {\r\n                T   A, B, E, AB, ArB, BrA, rB, singam, cosgam, sinrot, cosrot;\r\n                T   v_pole_n, v_pole_s, u_0;\r\n                int no_rot;\r\n            };\r\n\r\n            static const double tolerance = 1.e-7;\r\n            static const double epsilon = 1.e-10;\r\n\r\n            // template class, using CRTP to implement forward/inverse\r\n            template <typename T, typename Parameters>\r\n            struct base_omerc_ellipsoid\r\n                : public base_t_fi<base_omerc_ellipsoid<T, Parameters>, T, Parameters>\r\n            {\r\n                par_omerc<T> m_proj_parm;\r\n\r\n                inline base_omerc_ellipsoid(const Parameters& par)\r\n                    : base_t_fi<base_omerc_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 const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const\r\n                {\r\n                    static const T half_pi = detail::half_pi<T>();\r\n\r\n                    T  s, t, U, V, W, temp, u, v;\r\n\r\n                    if (fabs(fabs(lp_lat) - half_pi) > epsilon) {\r\n                        W = this->m_proj_parm.E / math::pow(pj_tsfn(lp_lat, sin(lp_lat), this->m_par.e), this->m_proj_parm.B);\r\n                        temp = 1. / W;\r\n                        s = .5 * (W - temp);\r\n                        t = .5 * (W + temp);\r\n                        V = sin(this->m_proj_parm.B * lp_lon);\r\n                        U = (s * this->m_proj_parm.singam - V * this->m_proj_parm.cosgam) / t;\r\n                        if (fabs(fabs(U) - 1.0) < epsilon) {\r\n                            BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\r\n                        }\r\n                        v = 0.5 * this->m_proj_parm.ArB * log((1. - U)/(1. + U));\r\n                        temp = cos(this->m_proj_parm.B * lp_lon);\r\n                        if(fabs(temp) < tolerance) {\r\n                            u = this->m_proj_parm.A * lp_lon;\r\n                        } else {\r\n                            u = this->m_proj_parm.ArB * atan2((s * this->m_proj_parm.cosgam + V * this->m_proj_parm.singam), temp);\r\n                        }\r\n                    } else {\r\n                        v = lp_lat > 0 ? this->m_proj_parm.v_pole_n : this->m_proj_parm.v_pole_s;\r\n                        u = this->m_proj_parm.ArB * lp_lat;\r\n                    }\r\n                    if (this->m_proj_parm.no_rot) {\r\n                        xy_x = u;\r\n                        xy_y = v;\r\n                    } else {\r\n                        u -= this->m_proj_parm.u_0;\r\n                        xy_x = v * this->m_proj_parm.cosrot + u * this->m_proj_parm.sinrot;\r\n                        xy_y = u * this->m_proj_parm.cosrot - v * this->m_proj_parm.sinrot;\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 const& xy_x, T const& xy_y, T& lp_lon, T& lp_lat) const\r\n                {\r\n                    static const T half_pi = detail::half_pi<T>();\r\n\r\n                    T  u, v, Qp, Sp, Tp, Vp, Up;\r\n\r\n                    if (this->m_proj_parm.no_rot) {\r\n                        v = xy_y;\r\n                        u = xy_x;\r\n                    } else {\r\n                        v = xy_x * this->m_proj_parm.cosrot - xy_y * this->m_proj_parm.sinrot;\r\n                        u = xy_y * this->m_proj_parm.cosrot + xy_x * this->m_proj_parm.sinrot + this->m_proj_parm.u_0;\r\n                    }\r\n                    Qp = exp(- this->m_proj_parm.BrA * v);\r\n                    Sp = .5 * (Qp - 1. / Qp);\r\n                    Tp = .5 * (Qp + 1. / Qp);\r\n                    Vp = sin(this->m_proj_parm.BrA * u);\r\n                    Up = (Vp * this->m_proj_parm.cosgam + Sp * this->m_proj_parm.singam) / Tp;\r\n                    if (fabs(fabs(Up) - 1.) < epsilon) {\r\n                        lp_lon = 0.;\r\n                        lp_lat = Up < 0. ? -half_pi : half_pi;\r\n                    } else {\r\n                        lp_lat = this->m_proj_parm.E / sqrt((1. + Up) / (1. - Up));\r\n                        if ((lp_lat = pj_phi2(math::pow(lp_lat, T(1) / this->m_proj_parm.B), this->m_par.e)) == HUGE_VAL) {\r\n                            BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\r\n                        }\r\n                        lp_lon = - this->m_proj_parm.rB * atan2((Sp * this->m_proj_parm.cosgam -\r\n                            Vp * this->m_proj_parm.singam), cos(this->m_proj_parm.BrA * u));\r\n                    }\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"omerc_ellipsoid\";\r\n                }\r\n\r\n            };\r\n\r\n            // Oblique Mercator\r\n            template <typename Params, typename Parameters, typename T>\r\n            inline void setup_omerc(Params const& params, Parameters& par, par_omerc<T>& proj_parm)\r\n            {\r\n                static const T fourth_pi = detail::fourth_pi<T>();\r\n                static const T half_pi = detail::half_pi<T>();\r\n                static const T pi = detail::pi<T>();\r\n                static const T two_pi = detail::two_pi<T>();\r\n\r\n                T con, com, cosph0, D, F, H, L, sinph0, p, J, gamma=0,\r\n                  gamma0, lamc=0, lam1=0, lam2=0, phi1=0, phi2=0, alpha_c=0;\r\n                int alp, gam, no_off = 0;\r\n\r\n                proj_parm.no_rot = pj_get_param_b<srs::spar::no_rot>(params, \"no_rot\", srs::dpar::no_rot);\r\n                alp = pj_param_r<srs::spar::alpha>(params, \"alpha\", srs::dpar::alpha, alpha_c);\r\n                gam = pj_param_r<srs::spar::gamma>(params, \"gamma\", srs::dpar::gamma, gamma);\r\n                if (alp || gam) {\r\n                    lamc = pj_get_param_r<T, srs::spar::lonc>(params, \"lonc\", srs::dpar::lonc);\r\n                    // NOTE: This is not needed in Boost.Geometry\r\n                    //no_off =\r\n                    //            /* For libproj4 compatability */\r\n                    //            pj_param_exists(par.params, \"no_off\")\r\n                    //            /* for backward compatibility */\r\n                    //            || pj_param_exists(par.params, \"no_uoff\");\r\n                    //if( no_off )\r\n                    //{\r\n                    //    /* Mark the parameter as used, so that the pj_get_def() return them */\r\n                    //    pj_get_param_s(par.params, \"no_uoff\");\r\n                    //    pj_get_param_s(par.params, \"no_off\");\r\n                    //}\r\n                } else {\r\n                    lam1 = pj_get_param_r<T, srs::spar::lon_1>(params, \"lon_1\", srs::dpar::lon_1);\r\n                    phi1 = pj_get_param_r<T, srs::spar::lat_1>(params, \"lat_1\", srs::dpar::lat_1);\r\n                    lam2 = pj_get_param_r<T, srs::spar::lon_2>(params, \"lon_2\", srs::dpar::lon_2);\r\n                    phi2 = pj_get_param_r<T, srs::spar::lat_2>(params, \"lat_2\", srs::dpar::lat_2);\r\n                    if (fabs(phi1 - phi2) <= tolerance ||\r\n                        (con = fabs(phi1)) <= tolerance ||\r\n                        fabs(con - half_pi) <= tolerance ||\r\n                        fabs(fabs(par.phi0) - half_pi) <= tolerance ||\r\n                        fabs(fabs(phi2) - half_pi) <= tolerance)\r\n                        BOOST_THROW_EXCEPTION( projection_exception(error_lat_0_or_alpha_eq_90) );\r\n                }\r\n                com = sqrt(par.one_es);\r\n                if (fabs(par.phi0) > epsilon) {\r\n                    sinph0 = sin(par.phi0);\r\n                    cosph0 = cos(par.phi0);\r\n                    con = 1. - par.es * sinph0 * sinph0;\r\n                    proj_parm.B = cosph0 * cosph0;\r\n                    proj_parm.B = sqrt(1. + par.es * proj_parm.B * proj_parm.B / par.one_es);\r\n                    proj_parm.A = proj_parm.B * par.k0 * com / con;\r\n                    D = proj_parm.B * com / (cosph0 * sqrt(con));\r\n                    if ((F = D * D - 1.) <= 0.)\r\n                        F = 0.;\r\n                    else {\r\n                        F = sqrt(F);\r\n                        if (par.phi0 < 0.)\r\n                            F = -F;\r\n                    }\r\n                    proj_parm.E = F += D;\r\n                    proj_parm.E *= math::pow(pj_tsfn(par.phi0, sinph0, par.e), proj_parm.B);\r\n                } else {\r\n                    proj_parm.B = 1. / com;\r\n                    proj_parm.A = par.k0;\r\n                    proj_parm.E = D = F = 1.;\r\n                }\r\n                if (alp || gam) {\r\n                    if (alp) {\r\n                        gamma0 = aasin(sin(alpha_c) / D);\r\n                        if (!gam)\r\n                            gamma = alpha_c;\r\n                    } else\r\n                        alpha_c = aasin(D*sin(gamma0 = gamma));\r\n                    par.lam0 = lamc - aasin(.5 * (F - 1. / F) *\r\n                       tan(gamma0)) / proj_parm.B;\r\n                } else {\r\n                    H = math::pow(pj_tsfn(phi1, sin(phi1), par.e), proj_parm.B);\r\n                    L = math::pow(pj_tsfn(phi2, sin(phi2), par.e), proj_parm.B);\r\n                    F = proj_parm.E / H;\r\n                    p = (L - H) / (L + H);\r\n                    J = proj_parm.E * proj_parm.E;\r\n                    J = (J - L * H) / (J + L * H);\r\n                    if ((con = lam1 - lam2) < -pi)\r\n                        lam2 -= two_pi;\r\n                    else if (con > pi)\r\n                        lam2 += two_pi;\r\n                    par.lam0 = adjlon(.5 * (lam1 + lam2) - atan(\r\n                       J * tan(.5 * proj_parm.B * (lam1 - lam2)) / p) / proj_parm.B);\r\n                    gamma0 = atan(2. * sin(proj_parm.B * adjlon(lam1 - par.lam0)) /\r\n                       (F - 1. / F));\r\n                    gamma = alpha_c = aasin(D * sin(gamma0));\r\n                }\r\n                proj_parm.singam = sin(gamma0);\r\n                proj_parm.cosgam = cos(gamma0);\r\n                proj_parm.sinrot = sin(gamma);\r\n                proj_parm.cosrot = cos(gamma);\r\n                proj_parm.BrA = 1. / (proj_parm.ArB = proj_parm.A * (proj_parm.rB = 1. / proj_parm.B));\r\n                proj_parm.AB = proj_parm.A * proj_parm.B;\r\n                if (no_off)\r\n                    proj_parm.u_0 = 0;\r\n                else {\r\n                    proj_parm.u_0 = fabs(proj_parm.ArB * atan(sqrt(D * D - 1.) / cos(alpha_c)));\r\n                    if (par.phi0 < 0.)\r\n                        proj_parm.u_0 = - proj_parm.u_0;\r\n                }\r\n                F = 0.5 * gamma0;\r\n                proj_parm.v_pole_n = proj_parm.ArB * log(tan(fourth_pi - F));\r\n                proj_parm.v_pole_s = proj_parm.ArB * log(tan(fourth_pi + F));\r\n            }\r\n\r\n    }} // namespace detail::omerc\r\n    #endif // doxygen\r\n\r\n    /*!\r\n        \\brief Oblique Mercator 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 Projection parameters\r\n         - no_rot: No rotation\r\n         - alpha: Alpha (degrees)\r\n         - gamma: Gamma (degrees)\r\n         - no_off: Only for compatibility with libproj, proj4 (string)\r\n         - lonc: Longitude (only used if alpha (or gamma) is specified) (degrees)\r\n         - lon_1 (degrees)\r\n         - lat_1: Latitude of first standard parallel (degrees)\r\n         - lon_2 (degrees)\r\n         - lat_2: Latitude of second standard parallel (degrees)\r\n         - no_uoff (string)\r\n        \\par Example\r\n        \\image html ex_omerc.gif\r\n    */\r\n    template <typename T, typename Parameters>\r\n    struct omerc_ellipsoid : public detail::omerc::base_omerc_ellipsoid<T, Parameters>\r\n    {\r\n        template <typename Params>\r\n        inline omerc_ellipsoid(Params const& params, Parameters const& par)\r\n            : detail::omerc::base_omerc_ellipsoid<T, Parameters>(par)\r\n        {\r\n            detail::omerc::setup_omerc(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_omerc, omerc_ellipsoid, omerc_ellipsoid)\r\n\r\n        // Factory entry(s)\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(omerc_entry, omerc_ellipsoid)\r\n\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_BEGIN(omerc_init)\r\n        {\r\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(omerc, omerc_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_OMERC_HPP\r\n\r\n", "meta": {"hexsha": "e750f86e4168e6b136cfa40b376dcec99f091871", "size": 15689, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "externals/boost/boost/geometry/srs/projections/proj/omerc.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/omerc.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/omerc.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-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 46.9730538922, "max_line_length": 132, "alphanum_fraction": 0.5003505641, "num_tokens": 3752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.287489820131949}}
{"text": "/*\n * This file belongs to the Galois project, a C++ library for exploiting parallelism.\n * The code is being released under the terms of the 3-Clause BSD License (a\n * copy is located in LICENSE.txt at the top-level directory).\n *\n * Copyright (C) 2018, The University of Texas at Austin. All rights reserved.\n * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS\n * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF\n * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF\n * DEALING OR USAGE OF TRADE.  NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH\n * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances\n * shall University be liable for incidental, special, indirect, direct or\n * consequential damages or loss of profits, interruption of business, or\n * related expenses which may arise from use of Software or Documentation,\n * including but not limited to those resulting from defects in Software and/or\n * Documentation, or loss or inaccuracy of data of any kind.\n */\n\n#include \"galois/Reduction.h\"\n#include \"galois/Bag.h\"\n#include \"galois/Galois.h\"\n#include \"galois/Timer.h\"\n#include \"galois/graphs/LCGraph.h\"\n#include \"llvm/Support/CommandLine.h\"\n\n#include \"Lonestar/BoilerPlate.h\"\n\n#include <boost/iterator/iterator_adaptor.hpp>\n\n#include <fstream>\n#include <iostream>\n\nnamespace cll = llvm::cl;\n\nconst char* name = \"Preflow Push\";\nconst char* desc =\n    \"Finds the maximum flow in a network using the preflow push technique\";\nconst char* url = \"preflow_push\";\n\nenum DetAlgo { nondet = 0, detBase, detDisjoint };\n\nstatic cll::opt<std::string> filename(cll::Positional,\n                                      cll::desc(\"<input file>\"), cll::Required);\nstatic cll::opt<uint32_t> sourceId(cll::Positional, cll::desc(\"sourceID\"),\n                                   cll::Required);\nstatic cll::opt<uint32_t> sinkId(cll::Positional, cll::desc(\"sinkID\"),\n                                 cll::Required);\nstatic cll::opt<bool> useHLOrder(\"useHLOrder\",\n                                 cll::desc(\"Use HL ordering heuristic\"),\n                                 cll::init(false));\nstatic cll::opt<bool>\n    useUnitCapacity(\"useUnitCapacity\",\n                    cll::desc(\"Assume all capacities are unit\"),\n                    cll::init(false));\nstatic cll::opt<bool> useSymmetricDirectly(\n    \"useSymmetricDirectly\",\n    cll::desc(\"Assume input graph is symmetric and has unit capacities\"),\n    cll::init(false));\nstatic cll::opt<int>\n    relabelInt(\"relabel\",\n               cll::desc(\"relabel interval X: relabel every X iterations \"\n                         \"(default 0 uses default interval)\"),\n               cll::init(0));\nstatic cll::opt<DetAlgo> detAlgo(\n    cll::desc(\"Deterministic algorithm:\"),\n    cll::values(clEnumVal(nondet, \"Non-deterministic (default)\"),\n                clEnumVal(detBase, \"Base execution\"),\n                clEnumVal(detDisjoint, \"Disjoint execution\")),\n    cll::init(nondet));\n\n/**\n * Alpha parameter the original Goldberg algorithm to control when global\n * relabeling occurs. For comparison purposes, we keep them the same as\n * before, but it is possible to achieve much better performance by adjusting\n * the global relabel frequency.\n */\nstatic const int ALPHA = 6;\n\n/**\n * Beta parameter the original Goldberg algorithm to control when global\n * relabeling occurs. For comparison purposes, we keep them the same as\n * before, but it is possible to achieve much better performance by adjusting\n * the global relabel frequency.\n */\nstatic const int BETA = 12;\n\nstruct Node {\n  uint32_t id;\n  int64_t excess;\n  int height;\n  int current;\n\n  Node() : excess(0), height(1), current(0) {}\n};\n\nstd::ostream& operator<<(std::ostream& os, const Node& n) {\n  os << \"(\"\n     << \"id: \" << n.id << \", excess: \" << n.excess << \", height: \" << n.height\n     << \", current: \" << n.current << \")\";\n  return os;\n}\n\nusing Graph =\n    galois::graphs::LC_CSR_Graph<Node, int32_t>::with_numa_alloc<false>::type;\nusing GNode   = Graph::GraphNode;\nusing Counter = galois::GAccumulator<int>;\n\nstruct PreflowPush {\n\n  Graph graph;\n  GNode sink;\n  GNode source;\n  int global_relabel_interval;\n  bool should_global_relabel = false;\n  galois::LargeArray<Graph::edge_iterator>\n      reverseDirectionEdgeIterator; // ideally should be on the graph as\n                                    // graph.getReverseEdgeIterator()\n\n  void reduceCapacity(const Graph::edge_iterator& ii, const GNode& src,\n                      const GNode& dst, int64_t amount) {\n    Graph::edge_data_type& cap1 = graph.getEdgeData(ii);\n    Graph::edge_data_type& cap2 =\n        graph.getEdgeData(reverseDirectionEdgeIterator[*ii]);\n    cap1 -= amount;\n    cap2 += amount;\n  }\n\n  Graph::edge_iterator findEdge(GNode src, GNode dst) {\n\n    auto i     = graph.edge_begin(src, galois::MethodFlag::UNPROTECTED);\n    auto end_i = graph.edge_end(src, galois::MethodFlag::UNPROTECTED);\n\n    if ((end_i - i) < 32) {\n      return findEdgeLinear(dst, i, end_i);\n\n    } else {\n      return findEdgeLog2(dst, i, end_i);\n    }\n  }\n\n  Graph::edge_iterator findEdgeLinear(GNode dst, Graph::edge_iterator beg_e,\n                                      Graph::edge_iterator end_e) {\n\n    auto ii = beg_e;\n    for (; ii != end_e; ++ii) {\n      if (graph.getEdgeDst(ii) == dst)\n        break;\n    }\n    assert(ii != end_e); // Never return the end iterator\n    return ii;\n  }\n\n  Graph::edge_iterator findEdgeLog2(GNode dst, Graph::edge_iterator i,\n                                    Graph::edge_iterator end_i) {\n\n    struct EdgeDstIter\n        : public boost::iterator_facade<\n              EdgeDstIter, GNode, boost::random_access_traversal_tag, GNode> {\n      Graph* g;\n      Graph::edge_iterator ei;\n\n      EdgeDstIter(void) : g(nullptr) {}\n\n      EdgeDstIter(Graph* g, Graph::edge_iterator ei) : g(g), ei(ei) {}\n\n    private:\n      friend boost::iterator_core_access;\n\n      GNode dereference(void) const { return g->getEdgeDst(ei); }\n\n      void increment(void) { ++ei; }\n\n      void decrement(void) { --ei; }\n\n      bool equal(const EdgeDstIter& that) const {\n        assert(this->g == that.g);\n        return this->ei == that.ei;\n      }\n\n      void advance(ptrdiff_t n) { ei += n; }\n\n      ptrdiff_t distance_to(const EdgeDstIter& that) const {\n        assert(this->g == that.g);\n\n        return that.ei - this->ei;\n      }\n    };\n\n    EdgeDstIter ai(&graph, i);\n    EdgeDstIter end_ai(&graph, end_i);\n\n    auto ret = std::lower_bound(ai, end_ai, dst);\n\n    assert(ret != end_ai);\n    assert(*ret == dst);\n\n    return ret.ei;\n  }\n\n  void acquire(const GNode& src) {\n    // LC Graphs have a different idea of locking\n    for (auto ii : graph.edges(src, galois::MethodFlag::WRITE)) {\n      GNode dst = graph.getEdgeDst(ii);\n      graph.getData(dst, galois::MethodFlag::WRITE);\n    }\n  }\n\n  void relabel(const GNode& src) {\n    int minHeight = std::numeric_limits<int>::max();\n    int minEdge   = 0;\n\n    int current = 0;\n    for (auto ii : graph.edges(src, galois::MethodFlag::UNPROTECTED)) {\n      GNode dst   = graph.getEdgeDst(ii);\n      int64_t cap = graph.getEdgeData(ii);\n      if (cap > 0) {\n        const Node& dnode = graph.getData(dst, galois::MethodFlag::UNPROTECTED);\n        if (dnode.height < minHeight) {\n          minHeight = dnode.height;\n          minEdge   = current;\n        }\n      }\n      ++current;\n    }\n\n    assert(minHeight != std::numeric_limits<int>::max());\n    ++minHeight;\n\n    Node& node = graph.getData(src, galois::MethodFlag::UNPROTECTED);\n    if (minHeight < (int)graph.size()) {\n      node.height  = minHeight;\n      node.current = minEdge;\n    } else {\n      node.height = graph.size();\n    }\n  }\n\n  template <typename C>\n  bool discharge(const GNode& src, C& ctx) {\n    // Node& node = graph.getData(src, galois::MethodFlag::WRITE);\n    Node& node = graph.getData(src, galois::MethodFlag::UNPROTECTED);\n    // int prevHeight = node.height;\n    bool relabeled = false;\n\n    if (node.excess == 0 || node.height >= (int)graph.size()) {\n      return false;\n    }\n\n    while (true) {\n      // galois::MethodFlag flag = relabeled ? galois::MethodFlag::UNPROTECTED :\n      // galois::MethodFlag::WRITE;\n      galois::MethodFlag flag = galois::MethodFlag::UNPROTECTED;\n      bool finished           = false;\n      int current             = node.current;\n\n      auto ii = graph.edge_begin(src, flag);\n      auto ee = graph.edge_end(src, flag);\n\n      std::advance(ii, node.current);\n\n      for (; ii != ee; ++ii, ++current) {\n        GNode dst   = graph.getEdgeDst(ii);\n        int64_t cap = graph.getEdgeData(ii);\n        if (cap == 0) // || current < node.current)\n          continue;\n\n        Node& dnode = graph.getData(dst, galois::MethodFlag::UNPROTECTED);\n        if (node.height - 1 != dnode.height)\n          continue;\n\n        // Push flow\n        int64_t amount = std::min(node.excess, cap);\n        reduceCapacity(ii, src, dst, amount);\n\n        // Only add once\n        if (dst != sink && dst != source && dnode.excess == 0)\n          ctx.push(dst);\n\n        assert(node.excess >= amount);\n        node.excess -= amount;\n        dnode.excess += amount;\n\n        if (node.excess == 0) {\n          finished     = true;\n          node.current = current;\n          break;\n        }\n      }\n\n      if (finished)\n        break;\n\n      relabel(src);\n      relabeled = true;\n\n      if (node.height == (int)graph.size())\n        break;\n\n      // prevHeight = node.height;\n    }\n\n    return relabeled;\n  }\n\n  template <DetAlgo version>\n  void detDischarge(galois::InsertBag<GNode>& initial, Counter& counter) {\n    typedef galois::worklists::Deterministic<> DWL;\n\n    auto detIDfn = [this](const GNode& item) -> uint32_t {\n      return graph.getData(item, galois::MethodFlag::UNPROTECTED).id;\n    };\n\n    const int relabel_interval =\n        global_relabel_interval / galois::getActiveThreads();\n\n    auto detBreakFn = [&, this](void) -> bool {\n      if (this->global_relabel_interval > 0 &&\n          counter.peekLocal() >= relabel_interval) {\n        this->should_global_relabel = true;\n        return true;\n      } else {\n        return false;\n      }\n    };\n\n    galois::for_each(\n        galois::iterate(initial),\n        [&, this](GNode& src, auto& ctx) {\n          if (version != nondet) {\n            if (ctx.isFirstPass()) {\n              this->acquire(src);\n            }\n            if (version == detDisjoint && ctx.isFirstPass()) {\n              return;\n            } else {\n              this->graph.getData(src, galois::MethodFlag::WRITE);\n              ctx.cautiousPoint();\n            }\n          }\n\n          int increment = 1;\n          if (this->discharge(src, ctx)) {\n            increment += BETA;\n          }\n\n          counter += increment;\n        },\n        galois::loopname(\"detDischarge\"), galois::wl<DWL>(),\n        galois::per_iter_alloc(), galois::det_id<decltype(detIDfn)>(detIDfn),\n        galois::det_parallel_break<decltype(detBreakFn)>(detBreakFn));\n  }\n\n  template <typename W>\n  void nonDetDischarge(galois::InsertBag<GNode>& initial, Counter& counter,\n                       const W& wl_opt) {\n\n    // per thread\n    const int relabel_interval =\n        global_relabel_interval / galois::getActiveThreads();\n\n    galois::for_each(\n        galois::iterate(initial),\n        [&counter, relabel_interval, this](GNode& src, auto& ctx) {\n          int increment = 1;\n          this->acquire(src);\n          if (this->discharge(src, ctx)) {\n            increment += BETA;\n          }\n\n          counter += increment;\n          if (this->global_relabel_interval > 0 &&\n              counter.peekLocal() >= relabel_interval) { // local check\n\n            this->should_global_relabel = true;\n            ctx.breakLoop();\n            return;\n          }\n        },\n        galois::loopname(\"nonDetDischarge\"), galois::parallel_break(), wl_opt);\n  }\n\n  /**\n   * Do reverse BFS on residual graph.\n   */\n  template <DetAlgo version, typename WL, bool useCAS = true>\n  void updateHeights() {\n\n    galois::for_each(\n        galois::iterate({sink}),\n        [&, this](const GNode& src, auto& ctx) {\n          if (version != nondet) {\n\n            if (ctx.isFirstPass()) {\n              for (auto ii :\n                   this->graph.edges(src, galois::MethodFlag::WRITE)) {\n                GNode dst = this->graph.getEdgeDst(ii);\n                int64_t rdata =\n                    this->graph.getEdgeData(reverseDirectionEdgeIterator[*ii]);\n                if (rdata > 0) {\n                  this->graph.getData(dst, galois::MethodFlag::WRITE);\n                }\n              }\n            }\n\n            if (version == detDisjoint && ctx.isFirstPass()) {\n              return;\n            } else {\n              this->graph.getData(src, galois::MethodFlag::WRITE);\n              ctx.cautiousPoint();\n            }\n          }\n\n          for (auto ii :\n               this->graph.edges(src, useCAS ? galois::MethodFlag::UNPROTECTED\n                                             : galois::MethodFlag::WRITE)) {\n            GNode dst = this->graph.getEdgeDst(ii);\n            int64_t rdata =\n                this->graph.getEdgeData(reverseDirectionEdgeIterator[*ii]);\n            if (rdata > 0) {\n              Node& node =\n                  this->graph.getData(dst, galois::MethodFlag::UNPROTECTED);\n              int newHeight =\n                  this->graph.getData(src, galois::MethodFlag::UNPROTECTED)\n                      .height +\n                  1;\n              if (useCAS) {\n                int oldHeight;\n                while (newHeight < (oldHeight = node.height)) {\n                  if (__sync_bool_compare_and_swap(&node.height, oldHeight,\n                                                   newHeight)) {\n                    ctx.push(dst);\n                    break;\n                  }\n                }\n              } else {\n                if (newHeight < node.height) {\n                  node.height = newHeight;\n                  ctx.push(dst);\n                }\n              }\n            }\n          } // end for\n        },\n        galois::wl<WL>(), galois::no_conflicts(),\n        galois::loopname(\"updateHeights\"));\n  }\n\n  template <typename IncomingWL>\n  void globalRelabel(IncomingWL& incoming) {\n\n    galois::do_all(galois::iterate(graph),\n                   [&](const GNode& src) {\n                     Node& node =\n                         graph.getData(src, galois::MethodFlag::UNPROTECTED);\n                     node.height  = graph.size();\n                     node.current = 0;\n                     if (src == sink)\n                       node.height = 0;\n                   },\n                   galois::loopname(\"ResetHeights\"));\n\n    using BSWL = galois::worklists::BulkSynchronous<>;\n    using DWL  = galois::worklists::Deterministic<>;\n    switch (detAlgo) {\n    case nondet:\n      updateHeights<nondet, BSWL>();\n      break;\n    case detBase:\n      updateHeights<detBase, DWL>();\n      break;\n    case detDisjoint:\n      updateHeights<detDisjoint, DWL>();\n      break;\n    default:\n      std::cerr << \"Unknown algorithm\" << detAlgo << \"\\n\";\n      abort();\n    }\n\n    galois::do_all(galois::iterate(graph),\n                   [&incoming, this](const GNode& src) {\n                     Node& node = this->graph.getData(\n                         src, galois::MethodFlag::UNPROTECTED);\n                     if (src == this->sink || src == this->source ||\n                         node.height >= (int)this->graph.size())\n                       return;\n                     if (node.excess > 0)\n                       incoming.push_back(src);\n                   },\n                   galois::loopname(\"FindWork\"));\n  }\n\n  template <typename C>\n  void initializePreflow(C& initial) {\n    for (auto ii : graph.edges(source)) {\n      GNode dst   = graph.getEdgeDst(ii);\n      int64_t cap = graph.getEdgeData(ii);\n      reduceCapacity(ii, source, dst, cap);\n      Node& node = graph.getData(dst);\n      node.excess += cap;\n      if (cap > 0)\n        initial.push_back(dst);\n    }\n  }\n\n  void run() {\n    Graph *captured_graph = &graph;\n    auto obimIndexer = [=](const GNode& n) {\n      return -captured_graph->getData(n, galois::MethodFlag::UNPROTECTED).height;\n    };\n\n    typedef galois::worklists::PerSocketChunkFIFO<16> Chunk;\n    typedef galois::worklists::OrderedByIntegerMetric<decltype(obimIndexer),\n                                                      Chunk>\n        OBIM;\n\n    galois::InsertBag<GNode> initial;\n    initializePreflow(initial);\n\n    while (initial.begin() != initial.end()) {\n      galois::StatTimer T_discharge(\"DischargeTime\");\n      T_discharge.start();\n      Counter counter;\n      switch (detAlgo) {\n      case nondet:\n        if (useHLOrder) {\n          nonDetDischarge(initial, counter, galois::wl<OBIM>(obimIndexer));\n        } else {\n          nonDetDischarge(initial, counter, galois::wl<Chunk>());\n        }\n        break;\n      case detBase:\n        detDischarge<detBase>(initial, counter);\n        break;\n      case detDisjoint:\n        detDischarge<detDisjoint>(initial, counter);\n        break;\n      default:\n        std::cerr << \"Unknown algorithm\" << detAlgo << \"\\n\";\n        abort();\n      }\n      T_discharge.stop();\n\n      if (should_global_relabel) {\n        galois::StatTimer T_global_relabel(\"GlobalRelabelTime\");\n        T_global_relabel.start();\n        initial.clear();\n        globalRelabel(initial);\n        should_global_relabel = false;\n        std::cout << \" Flow after global relabel: \"\n                  << graph.getData(sink).excess << \"\\n\";\n        T_global_relabel.stop();\n      } else {\n        break;\n      }\n    }\n  }\n\n  template <typename EdgeTy>\n  static void writePfpGraph(const std::string& inputFile,\n                            const std::string& outputFile) {\n    typedef galois::graphs::FileGraph ReaderGraph;\n    typedef ReaderGraph::GraphNode ReaderGNode;\n\n    ReaderGraph reader;\n    reader.fromFile(inputFile);\n\n    typedef galois::graphs::FileGraphWriter Writer;\n    typedef galois::LargeArray<EdgeTy> EdgeData;\n    typedef typename EdgeData::value_type edge_value_type;\n\n    Writer p;\n    EdgeData edgeData;\n\n    // Count edges\n    size_t numEdges = 0;\n    for (ReaderGraph::iterator ii = reader.begin(), ei = reader.end(); ii != ei;\n         ++ii) {\n      ReaderGNode rsrc = *ii;\n      for (auto jj : reader.edges(rsrc)) {\n        ReaderGNode rdst = reader.getEdgeDst(jj);\n        if (rsrc == rdst)\n          continue;\n        if (!reader.hasNeighbor(rdst, rsrc))\n          ++numEdges;\n        ++numEdges;\n      }\n    }\n\n    p.setNumNodes(reader.size());\n    p.setNumEdges(numEdges);\n    p.setSizeofEdgeData(sizeof(edge_value_type));\n\n    p.phase1();\n    for (ReaderGraph::iterator ii = reader.begin(), ei = reader.end(); ii != ei;\n         ++ii) {\n      ReaderGNode rsrc = *ii;\n      for (auto jj : reader.edges(rsrc)) {\n        ReaderGNode rdst = reader.getEdgeDst(jj);\n        if (rsrc == rdst)\n          continue;\n        if (!reader.hasNeighbor(rdst, rsrc))\n          p.incrementDegree(rdst);\n        p.incrementDegree(rsrc);\n      }\n    }\n\n    EdgeTy one = 1;\n    static_assert(sizeof(one) == sizeof(uint32_t), \"Unexpected edge data size\");\n    one = galois::convert_le32toh(one);\n\n    p.phase2();\n    edgeData.create(numEdges);\n    for (ReaderGraph::iterator ii = reader.begin(), ei = reader.end(); ii != ei;\n         ++ii) {\n      ReaderGNode rsrc = *ii;\n      for (auto jj : reader.edges(rsrc)) {\n        ReaderGNode rdst = reader.getEdgeDst(jj);\n        if (rsrc == rdst)\n          continue;\n        if (!reader.hasNeighbor(rdst, rsrc))\n          edgeData.set(p.addNeighbor(rdst, rsrc), 0);\n        EdgeTy cap = useUnitCapacity ? one : reader.getEdgeData<EdgeTy>(jj);\n        edgeData.set(p.addNeighbor(rsrc, rdst), cap);\n      }\n    }\n\n    edge_value_type* rawEdgeData = p.finish<edge_value_type>();\n    std::uninitialized_copy(std::make_move_iterator(edgeData.begin()),\n                            std::make_move_iterator(edgeData.end()),\n                            rawEdgeData);\n\n    using Wnode = Writer::GraphNode;\n\n    struct IdLess {\n      bool operator()(\n          const galois::graphs::EdgeSortValue<Wnode, edge_value_type>& e1,\n          const galois::graphs::EdgeSortValue<Wnode, edge_value_type>& e2)\n          const {\n        return e1.dst < e2.dst;\n      }\n    };\n\n    for (Writer::iterator i = p.begin(), end_i = p.end(); i != end_i; ++i) {\n      p.sortEdges<edge_value_type>(*i, IdLess());\n    }\n\n    p.toFile(outputFile);\n  }\n\n  void initializeGraph(std::string inputFile, uint32_t sourceId,\n                       uint32_t sinkId) {\n    if (useSymmetricDirectly) {\n      galois::graphs::readGraph(graph, inputFile);\n      for (auto ss : graph)\n        for (auto ii : graph.edges(ss))\n          graph.getEdgeData(ii) = 1;\n    } else {\n      if (inputFile.find(\".gr.pfp\") != inputFile.size() - strlen(\".gr.pfp\")) {\n        std::string pfpName = inputFile + \".pfp\";\n        std::ifstream pfpFile(pfpName.c_str());\n        if (!pfpFile.good()) {\n          galois::gPrint(\"Writing new input file: \", pfpName, \"\\n\");\n          writePfpGraph<Graph::edge_data_type>(inputFile, pfpName);\n        }\n        inputFile = pfpName;\n      }\n      galois::gPrint(\"Reading graph: \", inputFile, \"\\n\");\n      galois::graphs::readGraph(graph, inputFile);\n\n      // Assume that input edge data has already been converted instead\n#if 0 // def HAVE_BIG_ENDIAN\n      // Convert edge data to host ordering\n      for (auto ss : newApp->graph) {\n        for (auto ii : newApp->graph.edges(ss)) {\n          Graph::edge_data_type& cap = newApp->graph.getEdgeData(ii);\n          static_assert(sizeof(cap) == sizeof(uint32_t), \"Unexpected edge data size\");\n          cap = galois::convert_le32toh(cap);\n        }\n      }\n#endif\n    }\n\n    if (sourceId == sinkId || sourceId >= graph.size() ||\n        sinkId >= graph.size()) {\n      std::cerr << \"invalid source or sink id\\n\";\n      abort();\n    }\n\n    uint32_t id = 0;\n    for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei;\n         ++ii, ++id) {\n      if (id == sourceId) {\n        source                       = *ii;\n        graph.getData(source).height = graph.size();\n      } else if (id == sinkId) {\n        sink = *ii;\n      }\n      graph.getData(*ii).id = id;\n    }\n\n    reverseDirectionEdgeIterator.allocateInterleaved(graph.sizeEdges());\n    // memoize the reverse direction edge-iterators\n    galois::do_all(galois::iterate(graph.begin(), graph.end()),\n                   [&, this](const GNode& src) {\n                     for (auto ii : this->graph.edges(\n                              src, galois::MethodFlag::UNPROTECTED)) {\n                       GNode dst = this->graph.getEdgeDst(ii);\n                       reverseDirectionEdgeIterator[*ii] =\n                           this->findEdge(dst, src);\n                     }\n                   },\n                   galois::loopname(\"FindReverseDirectionEdges\"));\n  }\n\n  void checkSorting(void) {\n    for (auto n : graph) {\n      galois::optional<GNode> prevDst;\n      for (auto e : graph.edges(n, galois::MethodFlag::UNPROTECTED)) {\n        GNode dst = graph.getEdgeDst(e);\n        if (prevDst.is_initialized()) {\n          Node& prevNode =\n              graph.getData(*prevDst, galois::MethodFlag::UNPROTECTED);\n          Node& currNode = graph.getData(dst, galois::MethodFlag::UNPROTECTED);\n          GALOIS_ASSERT(prevNode.id != currNode.id,\n                        \"Adjacency list cannot have duplicates\");\n          GALOIS_ASSERT(prevNode.id <= currNode.id, \"Adjacency list unsorted\");\n        }\n        prevDst = dst;\n      }\n    }\n  }\n\n  void checkAugmentingPath() {\n    // Use id field as visited flag\n    for (Graph::iterator ii = graph.begin(), ee = graph.end(); ii != ee; ++ii) {\n      GNode src             = *ii;\n      graph.getData(src).id = 0;\n    }\n\n    std::deque<GNode> queue;\n\n    graph.getData(source).id = 1;\n    queue.push_back(source);\n\n    while (!queue.empty()) {\n      GNode& src = queue.front();\n      queue.pop_front();\n      for (auto ii : graph.edges(src)) {\n        GNode dst = graph.getEdgeDst(ii);\n        if (graph.getData(dst).id == 0 && graph.getEdgeData(ii) > 0) {\n          graph.getData(dst).id = 1;\n          queue.push_back(dst);\n        }\n      }\n    }\n\n    if (graph.getData(sink).id != 0) {\n      assert(false && \"Augmenting path exisits\");\n      abort();\n    }\n  }\n\n  void checkHeights() {\n    for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) {\n      GNode src = *ii;\n      int sh    = graph.getData(src).height;\n      for (auto jj : graph.edges(src)) {\n        GNode dst   = graph.getEdgeDst(jj);\n        int64_t cap = graph.getEdgeData(jj);\n        int dh      = graph.getData(dst).height;\n        if (cap > 0 && sh > dh + 1) {\n          std::cerr << \"height violated at \" << graph.getData(src) << \"\\n\";\n          abort();\n        }\n      }\n    }\n  }\n\n  void checkConservation(PreflowPush& orig) {\n    std::vector<GNode> map;\n    map.resize(graph.size());\n\n    // Setup ids assuming same iteration order in both graphs\n    uint32_t id = 0;\n    for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei;\n         ++ii, ++id) {\n      graph.getData(*ii).id = id;\n    }\n    id = 0;\n    for (Graph::iterator ii = orig.graph.begin(), ei = orig.graph.end();\n         ii != ei; ++ii, ++id) {\n      orig.graph.getData(*ii).id = id;\n      map[id]                    = *ii;\n    }\n\n    // Now do some checking\n    for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) {\n      GNode src        = *ii;\n      const Node& node = graph.getData(src);\n      uint32_t srcId   = node.id;\n\n      if (src == source || src == sink)\n        continue;\n\n      if (node.excess != 0 && node.height != (int)graph.size()) {\n        std::cerr << \"Non-zero excess at \" << node << \"\\n\";\n        abort();\n      }\n\n      int64_t sum = 0;\n      for (auto jj : graph.edges(src)) {\n        GNode dst      = graph.getEdgeDst(jj);\n        uint32_t dstId = graph.getData(dst).id;\n        int64_t ocap =\n            orig.graph.getEdgeData(orig.findEdge(map[srcId], map[dstId]));\n        int64_t delta = 0;\n        if (ocap > 0)\n          delta -= (ocap - graph.getEdgeData(jj));\n        else\n          delta += graph.getEdgeData(jj);\n        sum += delta;\n      }\n\n      if (node.excess != sum) {\n        std::cerr << \"Not pseudoflow: \" << node.excess << \" != \" << sum\n                  << \" at \" << node << \"\\n\";\n        abort();\n      }\n    }\n  }\n\n  void verify(PreflowPush& orig) {\n    // FIXME: doesn't fully check result\n    checkHeights();\n    checkConservation(orig);\n    checkAugmentingPath();\n  }\n};\n\nint main(int argc, char** argv) {\n  galois::SharedMemSys G;\n  LonestarStart(argc, argv, name, desc, url);\n\n  PreflowPush app;\n  app.initializeGraph(filename, sourceId, sinkId);\n\n  app.checkSorting();\n\n  if (relabelInt == 0) {\n    app.global_relabel_interval =\n        app.graph.size() * ALPHA + app.graph.sizeEdges() / 3;\n  } else {\n    app.global_relabel_interval = relabelInt;\n  }\n  std::cout << \"Number of nodes: \" << app.graph.size() << \"\\n\";\n  std::cout << \"Global relabel interval: \" << app.global_relabel_interval\n            << \"\\n\";\n\n  galois::StatTimer T;\n  galois::preAlloc(numThreads * app.graph.size() /\n                   galois::runtime::pagePoolSize());\n  galois::reportPageAlloc(\"MeminfoPre\");\n  T.start();\n  app.run();\n  T.stop();\n  galois::reportPageAlloc(\"MeminfoPost\");\n\n  std::cout << \"Flow is \" << app.graph.getData(app.sink).excess << \"\\n\";\n\n  if (!skipVerify) {\n    PreflowPush orig;\n    orig.initializeGraph(filename, sourceId, sinkId);\n    app.verify(orig);\n    std::cout << \"(Partially) Verified\\n\";\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "f559a485d3c177139f0782df2d522080d8705dca", "size": 27746, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lonestar/preflowpush/Preflowpush.cpp", "max_stars_repo_name": "bowu/Galois", "max_stars_repo_head_hexsha": "81f619a2bb1bdc95899729f2d96a7da38dd0c0a3", "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": "lonestar/preflowpush/Preflowpush.cpp", "max_issues_repo_name": "bowu/Galois", "max_issues_repo_head_hexsha": "81f619a2bb1bdc95899729f2d96a7da38dd0c0a3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lonestar/preflowpush/Preflowpush.cpp", "max_forks_repo_name": "bowu/Galois", "max_forks_repo_head_hexsha": "81f619a2bb1bdc95899729f2d96a7da38dd0c0a3", "max_forks_repo_licenses": ["BSD-3-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.5295454545, "max_line_length": 86, "alphanum_fraction": 0.5657752469, "num_tokens": 6978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.28743092757451677}}
{"text": "/*\n * This file is part of the statismo library.\n *\n * Author: Marcel Luethi (marcel.luethi@unibas.ch)\n *\n * Copyright (c) 2011 University of Basel\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 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 * Neither the name of the project's author 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\n * FOR 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 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 */\n\n\n// This example shows how a partial shape can be reconstructed using a statistical shape model.\n//\n// WARNING: This example assumes that the closest point of the partial shape to the model mean is also its\n// corresponding point. This is only true if the partial shape is close to the model mean. If this is not the\n// case, a more sophisticated method for establishing correspondence needs to be used.\n//\n#include <iostream>\n#include <boost/scoped_ptr.hpp>\n\n#include <vtkPolyData.h>\n#include <vtkPolyDataReader.h>\n#include <vtkPolyDataWriter.h>\n#include <vtkVersion.h>\n\n#include \"DataManager.h\"\n#include \"PosteriorModelBuilder.h\"\n#include \"StatisticalModel.h\"\n#include \"StatismoIO.h\"\n\n#include \"vtkStandardMeshRepresenter.h\"\n\ntypedef statismo::VectorType VectorType;\ntypedef statismo::MatrixType MatrixType;\ntypedef statismo::vtkStandardMeshRepresenter RepresenterType;\ntypedef statismo::StatisticalModel<vtkPolyData> StatisticalModelType;\ntypedef statismo::PosteriorModelBuilder<vtkPolyData> PosteriorModelBuilderType;\ntypedef StatisticalModelType::DomainType DomainType;\ntypedef DomainType::DomainPointsListType::const_iterator DomainPointsConstIterator;\n\n\nvtkPolyData* loadVTKPolyData(const std::string& filename) {\n    vtkPolyDataReader* reader = vtkPolyDataReader::New();\n    reader->SetFileName(filename.c_str());\n    reader->Update();\n    vtkPolyData* pd = vtkPolyData::New();\n    pd->DeepCopy(reader->GetOutput());\n    reader->Delete();\n    return pd;\n}\n\n\n/**\n  * Computes the mahalanobis distance of the targetPt, to the model point with the given pointId.\n  */\ndouble mahalanobisDistance(const StatisticalModelType* model, unsigned ptId, const statismo::vtkPoint& targetPt) {\n    statismo::MatrixType cov = model->GetCovarianceAtPoint(ptId, ptId);\n    statismo::vtkPoint meanPt = model->DrawMeanAtPoint(ptId);\n    unsigned pointDim = model->GetRepresenter()->GetDimensions();\n    assert(pointDim <= 3);\n\n    VectorType x = VectorType::Zero(pointDim);\n    for (unsigned d = 0; d < pointDim; d++) {\n        x(d) = targetPt[d] - meanPt[d];\n    }\n    return x.transpose() * cov.inverse() * x;\n}\n\n\n/**\n  * Given the inputModel and a partialMesh, the program outputs the posterior model (a statistical model) and\n  * its mean, which is the best reconstruction of the partial shape given the model.\n */\nint main(int argc, char** argv) {\n\n    if (argc < 5) {\n        std::cout << \"Usage \" << argv[0] << \" inputModel  partialShapeMesh posteriorModel reconstructedShape\" << std::endl;\n        exit(-1);\n    }\n\n\n    std::string inputModelName(argv[1]);\n    std::string partialShapeMeshName(argv[2]);\n    std::string posteriorModelName(argv[3]);\n    std::string reconstructedShapeName(argv[4]);\n\n    try {\n\n\n        vtkPolyData* partialShape = loadVTKPolyData(partialShapeMeshName);\n\n        RepresenterType* representer = RepresenterType::Create();\n        boost::scoped_ptr<StatisticalModelType> inputModel(\n                statismo::IO<vtkPolyData>::LoadStatisticalModel(representer, inputModelName));\n        vtkPolyData* refPd = const_cast<vtkPolyData*>(inputModel->GetRepresenter()->GetReference());\n\n\n        StatisticalModelType::PointValueListType constraints;\n\n        // for each point we get the closest point and check how far it is away (in mahalanobis distance).\n        // If it is close, we add it as a constraint, otherwise we ignore the remaining points.\n        const DomainType::DomainPointsListType& domainPoints = inputModel->GetDomain().GetDomainPoints();\n        for (unsigned ptId = 0; ptId < domainPoints.size(); ptId++) {\n            statismo::vtkPoint domainPoint = domainPoints[ptId];\n\n            unsigned closestPointId = ptId;\n            statismo::vtkPoint closestPointOnPartialShape = partialShape->GetPoint(closestPointId);\n            double mhdist = mahalanobisDistance(inputModel.get(), ptId, closestPointOnPartialShape);\n            if (mhdist < 5) {\n                StatisticalModelType::PointValuePairType ptWithTargetPt(domainPoint, closestPointOnPartialShape);\n                constraints.push_back(ptWithTargetPt);\n            }\n        }\n\n        // build the new model. In addition to the input model and the constraints, we also specify\n        // the inaccuracy of our value (variance of the error).\n\n        boost::scoped_ptr<PosteriorModelBuilderType> posteriorModelBuilder(PosteriorModelBuilderType::Create());\n        boost::scoped_ptr<StatisticalModelType> constraintModel(posteriorModelBuilder->BuildNewModelFromModel(inputModel.get(), constraints, 0.5));\n\n\n        // The resulting model is a normal statistical model, from which we could for example sample examples.\n        // Here we simply  save it to disk for later use.\n        statismo::IO<vtkPolyData>::SaveStatisticalModel(constraintModel.get(), posteriorModelName);\n        std::cout << \"successfully saved the model to \" << posteriorModelName << std::endl;\n\n        // The mean of the constraint model is the optimal reconstruction\n        vtkPolyData* pmean = constraintModel->DrawMean();\n        vtkPolyDataWriter* writer = vtkPolyDataWriter::New();\n#if (VTK_MAJOR_VERSION == 5 )\n        writer->SetInput(pmean);\n#else\n        writer->SetInputData(pmean);\n#endif\n        writer->SetFileName(reconstructedShapeName.c_str());\n        writer->Update();\n    } catch (statismo::StatisticalModelException& e) {\n        std::cout << \"Exception occured while building the intenisity model\" << std::endl;\n        std::cout << e.what() << std::endl;\n    }\n}\n", "meta": {"hexsha": "0a837cbf02a529972dfc62508ee32675ca0cc1b7", "size": 7143, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "modules/VTK/examples/vtkBuildPosteriorModelExample.cxx", "max_stars_repo_name": "skn123/statismo", "max_stars_repo_head_hexsha": "5998a32e1b1fd496f2703eea27dc143a6b3f8e1f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 223.0, "max_stars_repo_stars_event_min_datetime": "2015-02-02T18:50:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T08:14:17.000Z", "max_issues_repo_path": "modules/VTK/examples/vtkBuildPosteriorModelExample.cxx", "max_issues_repo_name": "skn123/statismo", "max_issues_repo_head_hexsha": "5998a32e1b1fd496f2703eea27dc143a6b3f8e1f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 84.0, "max_issues_repo_issues_event_min_datetime": "2015-01-07T09:54:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-05T17:17:05.000Z", "max_forks_repo_path": "modules/VTK/examples/vtkBuildPosteriorModelExample.cxx", "max_forks_repo_name": "skn123/statismo", "max_forks_repo_head_hexsha": "5998a32e1b1fd496f2703eea27dc143a6b3f8e1f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 94.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T20:02:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T08:45:18.000Z", "avg_line_length": 42.2662721893, "max_line_length": 147, "alphanum_fraction": 0.7260254795, "num_tokens": 1615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.28743092013945154}}
{"text": "#pragma once\n\n#include <armadillo>\n\n#include \"heattransfer/radial.hpp\"\n\nclass Pipeline;\nclass PipeWall;\nclass BurialMedium;\nclass AmbientFluid;\n\n/*!\n * \\brief Class that implements steady state heat transfer between gas and\n * pipeline surroundings.\n *\n * This is well documented in Jan Fredrik Helgaker's PhD thesis.\n */\nclass SteadyStateHeatTransfer : public RadialHeatTransfer\n{\npublic:\n    /*!\n     * \\brief Construct from full description of pipeline.\n     * \\param diameter Inner diameter [m]\n     * \\param pipeWall PipeWall instance\n     * \\param burialDepth Distance from top of pipe to top of burial medium [m]\n     * \\param burialMedium BurialMedium instace\n     * \\param ambientFluid AmbientFluid instance\n     */\n    SteadyStateHeatTransfer(\n            const double diameter,\n            const PipeWall& pipeWall,\n            const double burialDepth,\n            const BurialMedium& burialMedium,\n            const AmbientFluid& ambientFluid);\n\n    /*!\n     * \\brief Constructor with default pipe wall, burial medium and ambient medium.\n     * \\param diameter Inner diameter [m]\n     * \\param burialDepth Distance from top of pipe to top of burial medium [m]\n     */\n    SteadyStateHeatTransfer(\n            const double diameter = 1.0,\n            const double burialDepth = 1.0);\n\n    /*!\n     * \\brief Evaluate 1d radial steady state heat transfer.\n     *\n     * Operates on a HeatTransferState and returns a new HeatTransferState,\n     * but does not require discretization temperature.\n     *\n     * \\param current Current HeatTransferState\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 gasHeatCapacity Gas heat capacity (\\f$c_p\\f$) [J/(kg K)]\n     * \\param gasViscosity Gas dynamic viscosity [Pa s] = [kg/m*s]\n     * \\return HeatTransferState with new heat flux.\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 gasHeatCapacity,\n            const double gasViscosity) const override;\n\n    /*!\n     * \\brief Internal method used for evaluating steady state heat transfer.\n     *\n     * This is exposed for testing purposes. We typically use pointers anyway,\n     * so this is not accessible without casting to SteadyStateHeatTransfer.\n     *\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 gasHeatCapacity Gas heat capacity (\\f$c_p\\f$) [J/(kg K)]\n     * \\param gasViscosity Gas dynamic viscosity [Pa s] = [kg/m*s]\n     * \\return HeatTransferState with new heat flux.\n     */\n    HeatTransferState evaluateInternal(\n            const double ambientTemperature,\n            const double gasPressure,\n            const double gasTemperature,\n            const double gasReynoldsNumber,\n            const double gasHeatCapacity,\n            const double gasViscosity) const;\n\n    /*!\n     * \\brief Calculate the total heat transfer coefficient U.\n     *\n     * This is exposed for testing purposes. We typically use pointers anyway,\n     * so this is not accessible without casting to SteadyStateHeatTransfer.\n     *\n     * \\param gasPressure Gas pressure [Pa]\n     * \\param gasReynoldsNumber Gas Reynolds number [-]\n     * \\param gasHeatCapacityConstantPressure Gas heat capacity (\\f$c_p\\f$) [J/(kg K)]\n     * \\param gasViscosity Gas dynamic viscosity [Pa s] = [kg/m*s]\n     * \\return Total heat transfer coefficient U [W/(m2 K)]\n     */\n    double calculateHeatTransferCoefficient(\n            const double gasPressure,\n            const double gasReynoldsNumber,\n            const double gasHeatCapacityConstantPressure,\n            const double gasViscosity) const;\n\n    //! Get the total heat transfer coefficient of all radial discretization shells.\n    //! Does not include the inner film coefficient.\n    double getOverallHeatTransferCoefficient() const { return m_overallHeatTransferCoefficient; }\n    //! Get the total thermal resistance of all radial discretization shells.\n    //! Does not include the inner film coefficient.\n    double getOverallThermalResistance() const { return m_overallThermalResistance; }\n\nprivate:\n    //! Total heat transfer coefficient of all radial discretization shells.\n    //! Does not include the inner film coefficient.\n    double m_overallHeatTransferCoefficient;\n\n    //! Total thermal resistance of all radial discretization shells.\n    //! Does not include the inner film coefficient.\n    double m_overallThermalResistance;\n};\n", "meta": {"hexsha": "28a33ab4822e70cf6d8dea3259a58b0d95dd1c96", "size": 4952, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/heattransfer/steadystate.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/steadystate.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/steadystate.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": 38.9921259843, "max_line_length": 97, "alphanum_fraction": 0.6855815832, "num_tokens": 1057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.28743092013945154}}
{"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_OEA_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_OEA_HPP\r\n\r\n#include <boost/math/special_functions/hypot.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/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 oea\r\n    {\r\n            template <typename T>\r\n            struct par_oea\r\n            {\r\n                T    theta;\r\n                T    m, n;\r\n                T    two_r_m, two_r_n, rm, rn, hm, hn;\r\n                T    cp0, sp0;\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_oea_spheroid\r\n                : public base_t_fi<base_oea_spheroid<T, Parameters>, T, Parameters>\r\n            {\r\n                par_oea<T> m_proj_parm;\r\n\r\n                inline base_oea_spheroid(const Parameters& par)\r\n                    : base_t_fi<base_oea_spheroid<T, Parameters>, T, Parameters>(*this, par)\r\n                {}\r\n\r\n                // FORWARD(s_forward)  sphere\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                    T Az, M, N, cp, sp, cl, shz;\r\n\r\n                    cp = cos(lp_lat);\r\n                    sp = sin(lp_lat);\r\n                    cl = cos(lp_lon);\r\n                    Az = aatan2(cp * sin(lp_lon), this->m_proj_parm.cp0 * sp - this->m_proj_parm.sp0 * cp * cl) + this->m_proj_parm.theta;\r\n                    shz = sin(0.5 * aacos(this->m_proj_parm.sp0 * sp + this->m_proj_parm.cp0 * cp * cl));\r\n                    M = aasin(shz * sin(Az));\r\n                    N = aasin(shz * cos(Az) * cos(M) / cos(M * this->m_proj_parm.two_r_m));\r\n                    xy_y = this->m_proj_parm.n * sin(N * this->m_proj_parm.two_r_n);\r\n                    xy_x = this->m_proj_parm.m * sin(M * this->m_proj_parm.two_r_m) * cos(N) / cos(N * this->m_proj_parm.two_r_n);\r\n                }\r\n\r\n                // INVERSE(s_inverse)  sphere\r\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\r\n                inline void inv(T const& xy_x, T const& xy_y, T& lp_lon, T& lp_lat) const\r\n                {\r\n                    T N, M, xp, yp, z, Az, cz, sz, cAz;\r\n\r\n                    N = this->m_proj_parm.hn * aasin(xy_y * this->m_proj_parm.rn);\r\n                    M = this->m_proj_parm.hm * aasin(xy_x * this->m_proj_parm.rm * cos(N * this->m_proj_parm.two_r_n) / cos(N));\r\n                    xp = 2. * sin(M);\r\n                    yp = 2. * sin(N) * cos(M * this->m_proj_parm.two_r_m) / cos(M);\r\n                    cAz = cos(Az = aatan2(xp, yp) - this->m_proj_parm.theta);\r\n                    z = 2. * aasin(0.5 * boost::math::hypot(xp, yp));\r\n                    sz = sin(z);\r\n                    cz = cos(z);\r\n                    lp_lat = aasin(this->m_proj_parm.sp0 * cz + this->m_proj_parm.cp0 * sz * cAz);\r\n                    lp_lon = aatan2(sz * sin(Az),\r\n                        this->m_proj_parm.cp0 * cz - this->m_proj_parm.sp0 * sz * cAz);\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"oea_spheroid\";\r\n                }\r\n\r\n            };\r\n\r\n            // Oblated Equal Area\r\n            template <typename Params, typename Parameters, typename T>\r\n            inline void setup_oea(Params const& params, Parameters& par, par_oea<T>& proj_parm)\r\n            {\r\n                if (((proj_parm.n = pj_get_param_f<T, srs::spar::n>(params, \"n\", srs::dpar::n)) <= 0.) ||\r\n                    ((proj_parm.m = pj_get_param_f<T, srs::spar::m>(params, \"m\", srs::dpar::m)) <= 0.)) {\r\n                    BOOST_THROW_EXCEPTION( projection_exception(error_invalid_m_or_n) );\r\n                } else {\r\n                    proj_parm.theta = pj_get_param_r<T, srs::spar::theta>(params, \"theta\", srs::dpar::theta);\r\n                    proj_parm.sp0 = sin(par.phi0);\r\n                    proj_parm.cp0 = cos(par.phi0);\r\n                    proj_parm.rn = 1./ proj_parm.n;\r\n                    proj_parm.rm = 1./ proj_parm.m;\r\n                    proj_parm.two_r_n = 2. * proj_parm.rn;\r\n                    proj_parm.two_r_m = 2. * proj_parm.rm;\r\n                    proj_parm.hm = 0.5 * proj_parm.m;\r\n                    proj_parm.hn = 0.5 * proj_parm.n;\r\n                    par.es = 0.;\r\n                }\r\n            }\r\n\r\n    }} // namespace detail::oea\r\n    #endif // doxygen\r\n\r\n    /*!\r\n        \\brief Oblated Equal Area 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        \\par Projection parameters\r\n         - n (real)\r\n         - m (real)\r\n         - theta: Theta (degrees)\r\n        \\par Example\r\n        \\image html ex_oea.gif\r\n    */\r\n    template <typename T, typename Parameters>\r\n    struct oea_spheroid : public detail::oea::base_oea_spheroid<T, Parameters>\r\n    {\r\n        template <typename Params>\r\n        inline oea_spheroid(Params const& params, Parameters const& par)\r\n            : detail::oea::base_oea_spheroid<T, Parameters>(par)\r\n        {\r\n            detail::oea::setup_oea(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_oea, oea_spheroid, oea_spheroid)\r\n\r\n        // Factory entry(s)\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(oea_entry, oea_spheroid)\r\n\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_BEGIN(oea_init)\r\n        {\r\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(oea, oea_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_OEA_HPP\r\n\r\n", "meta": {"hexsha": "f66051dfca04a854b1ce37a62e64fdfd88c58d5c", "size": 8367, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "externals/boost/boost/geometry/srs/projections/proj/oea.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/oea.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/oea.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": 42.4720812183, "max_line_length": 139, "alphanum_fraction": 0.5809728696, "num_tokens": 2028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.28737635408826206}}
{"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/LICENSbd:E_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_DETAIL_SIMD_TRIG_REDUCTION_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_DETAIL_SIMD_TRIG_REDUCTION_HPP_INCLUDED\n\n#include <boost/simd/arch/common/detail/generic/trig_reduction.hpp>\n#include <boost/simd/function/rem_pio2_medium.hpp>\n#include <boost/simd/function/rem_pio2_cephes.hpp>\n#include <boost/simd/function/rem_pio2.hpp>\n#include <boost/simd/function/logical_and.hpp>\n#include <boost/simd/function/split.hpp>\n#include <boost/simd/function/group.hpp>\n#include <boost/simd/detail/dispatch/meta/upgrade.hpp>\n\n#include <boost/simd/function/all.hpp>\n#include <boost/simd/function/toint.hpp>\n#include <boost/simd/function/nearbyint.hpp>\n#include <boost/simd/function/if_else_nan.hpp>\n#include <boost/simd/function/is_not_greater.hpp>\n#include <boost/simd/function/is_nez.hpp>\n#include <boost/simd/function/is_flint.hpp>\n#include <boost/simd/function/all.hpp>\n#include <boost/simd/function/inrad.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/divides.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/pi.hpp>\n#include <boost/simd/constant/pio_2.hpp>\n#include <boost/simd/constant/pio_4.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/detail/constant/medium_pi.hpp>\n#include <boost/simd/constant/false.hpp>\n#include <boost/simd/constant/ratio.hpp>\n#include <boost/simd/constant/constant.hpp>\n#include <boost/simd/constant/real.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/simd/detail/dispatch/meta/scalar_of.hpp>\n#include <utility>\n\nnamespace boost { namespace simd\n{\n  namespace detail\n  {\n    template<class A0, class mode>\n    struct trig_reduction < A0, tag::radian_tag, tag::simd_type, mode>\n    {\n      using i_t = bd::as_integer_t<A0, signed>;\n      using l_t = bs::as_logical_t<A0>;\n      using conversion_allowed_t = bd::is_upgradable<A0>;\n\n      static BOOST_FORCEINLINE auto is_0_pio4_reduced(const A0&a0) BOOST_NOEXCEPT\n      ->  decltype(is_not_greater(a0, Pio_4<A0>()))\n      {\n        return is_not_greater(a0, Pio_4<A0>());\n      }\n      static BOOST_FORCEINLINE auto is_0_pio2_reduced(const A0&a0) BOOST_NOEXCEPT\n      ->  decltype(is_not_greater(a0, Pio_2<A0>()))\n      {\n        return is_not_greater(a0, Pio_2<A0>());\n      }\n      static BOOST_FORCEINLINE auto is_0_20pi_reduced(const A0&a0) BOOST_NOEXCEPT\n      ->  decltype(is_not_greater(a0, Real<A0, 0X404F6A7A2955385EULL, 0X427B53D1UL>()))\n      {\n        return is_not_greater(a0, Real<A0, 0X404F6A7A2955385EULL, 0X427B53D1UL>()); //20 pi;\n      }\n      static BOOST_FORCEINLINE auto is_0_mpi_reduced (const A0&a0) BOOST_NOEXCEPT\n      ->  decltype(is_not_greater(a0, Medium_pi<A0>()))\n      {\n        return is_not_greater(a0, Medium_pi<A0>()); //2^6 pi\n      }\n      static BOOST_FORCEINLINE auto is_0_dmpi_reduced(const A0&a0) BOOST_NOEXCEPT\n      ->  decltype(is_not_greater(a0,Constant<A0,262144>()))\n      {\n        return is_not_greater(a0, Ratio<A0,262144>()); //2^18 pi\n      }\n\n      static BOOST_FORCEINLINE l_t cot_invalid(const A0& )  BOOST_NOEXCEPT\n      {\n        return False<l_t>();\n      }\n      static BOOST_FORCEINLINE l_t tan_invalid(const A0& )  BOOST_NOEXCEPT\n      {\n        return False<l_t>();\n      }\n\n      static BOOST_FORCEINLINE i_t reduce(const A0& x, A0& xr)  BOOST_NOEXCEPT\n      {\n        return inner_reduce(x, xr);\n      }\n\n      static BOOST_FORCEINLINE i_t inner_reduce(const A0& x, A0& xr) BOOST_NOEXCEPT\n      {\n        A0 xx =  preliminary<mode>::clip(x);\n        return select_mode(xx, xr, boost::mpl::int_<mode::start>());\n      }\n\n      template < class Mode, bool clipped = Mode::clipped>\n      struct preliminary\n      {\n        static BOOST_FORCEINLINE A0 const& clip(const A0& x) BOOST_NOEXCEPT  { return x; }\n      };\n\n\n      template < class Mode>\n      struct preliminary<Mode, true>\n      {\n        static BOOST_FORCEINLINE A0 clip(const A0& x) BOOST_NOEXCEPT\n        {\n          return clipto(x, boost::mpl::int_<Mode::range>());\n        }\n      private :\n        static BOOST_FORCEINLINE A0 clipto(const A0& x\n                                          , boost::mpl::int_<tag::r_0_pio4> const&) BOOST_NOEXCEPT\n        {\n          return if_else_nan(is_0_pio4_reduced(x), x);\n        }\n        static BOOST_FORCEINLINE A0 clipto(const A0& x\n                                          , boost::mpl::int_<tag::r_0_20pi> const&) BOOST_NOEXCEPT\n        {\n          return if_else_nan(is_0_20pi_reduced(x), x);\n        }\n        static BOOST_FORCEINLINE A0 clipto(const A0& x\n                                          , boost::mpl::int_<tag::r_0_mpi> const&) BOOST_NOEXCEPT\n        {\n          return if_else_nan(is_0_mpi_reduced(x), x);\n        }\n        static BOOST_FORCEINLINE A0 clipto(const A0& x\n                                          , boost::mpl::int_<tag::r_0_dmpi> const&) BOOST_NOEXCEPT\n        {\n          return if_else_nan(is_0_dmpi_reduced(x), x);\n        }\n      };\n\n      static BOOST_FORCEINLINE i_t\n      select_range( const A0& xx, A0& xr\n                  , boost::mpl::true_ const&\n                  , boost::mpl::int_<tag::r_0_pio4> const&\n                  ) BOOST_NOEXCEPT\n      {\n        xr = xx;\n        return Zero<i_t>();\n      }\n\n      static BOOST_FORCEINLINE i_t\n      select_range( const A0& xx, A0& xr\n                  , boost::mpl::false_ const&\n                  , boost::mpl::int_<tag::r_0_pio4> const& r\n                  ) BOOST_NOEXCEPT\n      {\n        if(all(is_0_pio4_reduced(xx)))\n        {\n          return select_range(xx,xr,boost::mpl::true_(), r);\n        }\n\n        return select_mode(xx,xr,boost::mpl::int_<tag::r_0_pio2>());\n      }\n\n      static BOOST_FORCEINLINE i_t\n      select_mode(const A0& xx, A0& xr\n                 , boost::mpl::int_<tag::r_0_pio4> const& r) BOOST_NOEXCEPT\n      {\n        return select_range(xx,xr,boost::mpl::bool_<mode::range == tag::r_0_pio4>(),r);\n      }\n\n      static BOOST_FORCEINLINE i_t\n      select_mode(const A0& xx, A0& xr\n                 , boost::mpl::int_<tag::r_0_pio2> const&) BOOST_NOEXCEPT\n      {\n        if(all(is_0_pio2_reduced(xx)))\n        {\n          auto test = is_greater(xx, Pio_4<A0>());\n          xr = xx-Pio2_1<A0>();\n          xr -= Pio2_2<A0>();\n          xr -= Pio2_3<A0>();\n          xr = if_else(test, xr, xx);\n          return -bitwise_cast<i_t>(genmask(test));\n        }\n\n        return select_mode(xx,xr,boost::mpl::int_<tag::r_0_20pi>());\n      }\n\n      static BOOST_FORCEINLINE i_t\n      select_range( const A0& xx, A0& xr\n                  , boost::mpl::true_ const&\n                  , boost::mpl::int_<tag::r_0_20pi> const&\n                  ) BOOST_NOEXCEPT\n      {\n        i_t n;\n        std::tie(n, xr) = rem_pio2_cephes(xx);\n        return n;\n      }\n\n      static BOOST_FORCEINLINE i_t\n      select_range( const A0& xx, A0& xr\n                  , boost::mpl::false_ const&\n                  , boost::mpl::int_<tag::r_0_20pi> const& r\n                  ) BOOST_NOEXCEPT\n      {\n        if(all(is_0_20pi_reduced(xx)))\n          return select_range(xx,xr,boost::mpl::true_(), r);\n\n        return select_mode(xx,xr,boost::mpl::int_<tag::r_0_mpi>());\n      }\n\n      static BOOST_FORCEINLINE i_t\n      select_mode(const A0& xx, A0& xr\n                 , boost::mpl::int_< tag::r_0_20pi> const& r) BOOST_NOEXCEPT\n      {\n        return select_range(xx,xr,boost::mpl::bool_<mode::range == tag::r_0_20pi>(),r);\n      }\n\n\n\n      static BOOST_FORCEINLINE i_t\n      select_range( const A0& xx, A0& xr\n                  , boost::mpl::true_ const&\n                  , boost::mpl::int_<tag::r_0_mpi> const&\n                  ) BOOST_NOEXCEPT\n      {\n        i_t n;\n        std::tie(n, xr) = rem_pio2_medium(xx);\n        return n;\n      }\n\n      static BOOST_FORCEINLINE i_t\n      select_range( const A0& xx, A0& xr\n                  , boost::mpl::false_ const&\n                  , boost::mpl::int_<tag::r_0_mpi> const& r\n                  ) BOOST_NOEXCEPT\n      {\n        if(all(is_0_mpi_reduced(xx)))\n          return select_range(xx,xr,boost::mpl::true_(), r);\n\n        return select_mode(xx,xr,boost::mpl::int_<tag::r_0_dmpi>());\n      }\n\n      static BOOST_FORCEINLINE i_t\n      select_mode(const A0& xx, A0& xr\n                 , boost::mpl::int_< tag::r_0_mpi> const& r) BOOST_NOEXCEPT\n      {\n        return select_range(xx,xr,boost::mpl::bool_<mode::range == tag::r_0_mpi>(),r);\n      }\n\n      static BOOST_FORCEINLINE i_t\n      select_mode(const A0& xx, A0& xr\n                 , boost::mpl::int_< tag::r_0_dmpi> const&) BOOST_NOEXCEPT\n      {\n        if(all(is_0_dmpi_reduced(xx)))\n           return use_conversion(xx, xr, conversion_allowed_t());\n        i_t n;\n        std::tie(n, xr) = rem_pio2(xx);\n        return n;\n      }\n\n      static BOOST_FORCEINLINE i_t\n      use_conversion(const A0 & xx,  A0& xr\n                    , std::false_type) BOOST_NOEXCEPT\n      {\n        i_t n;\n        std::tie(n, xr) = rem_pio2(xx);\n        return n;\n      }\n\n      static BOOST_FORCEINLINE i_t\n      use_conversion(const A0 & x,  A0& xr\n                    ,std::true_type) BOOST_NOEXCEPT\n      {\n        // all of x are in [0, 2^18*pi],  conversion to double is used to reduce\n        using uA0 = bd::upgrade_t<A0>;\n        using aux_reduc_t = trig_reduction< uA0, tag::radian_tag,  tag::simd_type, mode, double>;\n\n        auto uxs = split(x);\n        uA0  uxr1, uxr2;\n\n        auto n1 = aux_reduc_t::reduce(uxs[0], uxr1);\n        auto n2 = aux_reduc_t::reduce(uxs[1], uxr2);\n\n          xr = group(uxr1, uxr2);\n        return group(n1, n2);\n      }\n    };\n\n  }\n} }\n\n#endif\n", "meta": {"hexsha": "113d45f1e869cf03db78bba2457e3a39eedbdcb0", "size": 10033, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/detail/simd/trig_reduction.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "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": "third_party/boost/simd/arch/common/detail/simd/trig_reduction.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/detail/simd/trig_reduction.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-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.7811447811, "max_line_length": 100, "alphanum_fraction": 0.5891557859, "num_tokens": 2788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2873023983012238}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@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_DETAIL_EXPLODER_HPP\n#define CRYPTO3_DETAIL_EXPLODER_HPP\n\n#include <nil/crypto3/detail/stream_endian.hpp>\n#include <nil/crypto3/detail/unbounded_shift.hpp>\n\n#include <boost/integer.hpp>\n#include <boost/static_assert.hpp>\n\n#include <iterator>\n\n#include <climits>\n#include <cstring>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace detail {\n\n            // By definition, for all exploders, InputBits > OutputBits,\n            // so we're taking one value and splitting it into many smaller values\n\n            template<typename OutIter, int OutBits, typename T = typename std::iterator_traits<OutIter>::value_type>\n            struct outvalue_helper {\n                typedef T type;\n            };\n            template<typename OutIter, int OutBits>\n            struct outvalue_helper<OutIter, OutBits, void> {\n                typedef typename boost::uint_t<OutBits>::least type;\n            };\n\n            template<typename Endianness, int InputBits, int OutputBits, int k>\n            struct exploder_step;\n\n            template<int UnitBits, int InputBits, int OutputBits, int k>\n            struct exploder_step<stream_endian::big_unit_big_bit<UnitBits>, InputBits, OutputBits, k> {\n                template<typename InputValue, typename OutIter>\n                static void step(InputValue const &x, OutIter &out) {\n                    int const shift = InputBits - (OutputBits + k);\n                    typedef typename outvalue_helper<OutIter, OutputBits>::type OutValue;\n                    InputValue y = unbounded_shr<shift>(x);\n                    *out++ = OutValue(low_bits<OutputBits>(y));\n                }\n            };\n\n            template<int UnitBits, int InputBits, int OutputBits, int k>\n            struct exploder_step<stream_endian::little_unit_big_bit<UnitBits>, InputBits, OutputBits, k> {\n                template<typename InputValue, typename OutIter>\n                static void step(InputValue const &x, OutIter &out) {\n                    int const kb = (k % UnitBits);\n                    int const ku = k - kb;\n                    int const shift = OutputBits >= UnitBits ? k :\n                                      InputBits >= UnitBits  ? ku + (UnitBits - (OutputBits + kb)) :\n                                                               InputBits - (OutputBits + kb);\n                    typedef typename outvalue_helper<OutIter, OutputBits>::type OutValue;\n                    InputValue y = unbounded_shr<shift>(x);\n                    *out++ = OutValue(low_bits<OutputBits>(y));\n                }\n            };\n\n            template<int UnitBits, int InputBits, int OutputBits, int k>\n            struct exploder_step<stream_endian::big_unit_little_bit<UnitBits>, InputBits, OutputBits, k> {\n                template<typename InputValue, typename OutIter>\n                static void step(InputValue const &x, OutIter &out) {\n                    int const kb = (k % UnitBits);\n                    int const ku = k - kb;\n                    int const shift = OutputBits >= UnitBits ? InputBits - (OutputBits + k) :\n                                      InputBits >= UnitBits  ? InputBits - (UnitBits + ku) + kb :\n                                                               kb;\n                    typedef typename outvalue_helper<OutIter, OutputBits>::type OutValue;\n                    InputValue y = unbounded_shr<shift>(x);\n                    *out++ = OutValue(low_bits<OutputBits>(y));\n                }\n            };\n\n            template<int UnitBits, int InputBits, int OutputBits, int k>\n            struct exploder_step<stream_endian::little_unit_little_bit<UnitBits>, InputBits, OutputBits, k> {\n                template<typename InputValue, typename OutIter>\n                static void step(InputValue const &x, OutIter &out) {\n                    int const shift = k;\n                    typedef typename outvalue_helper<OutIter, OutputBits>::type OutValue;\n                    InputValue y = unbounded_shr<shift>(x);\n                    *out++ = OutValue(low_bits<OutputBits>(y));\n                }\n            };\n\n            template<int UnitBits, int InputBits, int OutputBits, int k>\n            struct exploder_step<stream_endian::host_unit<UnitBits>, InputBits, OutputBits, k> {\n                template<typename InputValue, typename OutIter>\n                static void step(InputValue const &x, OutIter &out) {\n                    typedef typename outvalue_helper<OutIter, OutputBits>::type OutValue;\n                    BOOST_STATIC_ASSERT(sizeof(InputValue) * CHAR_BIT == InputBits);\n                    BOOST_STATIC_ASSERT(sizeof(OutValue) * CHAR_BIT == OutputBits);\n                    OutValue value;\n                    std::memcpy(&value, (char *)&x + k / CHAR_BIT, OutputBits / CHAR_BIT);\n                    *out++ = value;\n                }\n            };\n\n            template<typename Endianness, int InputBits, int OutputBits, int k = 0>\n            struct exploder;\n\n            template<template<int> class Endian, int UnitBits, int InputBits, int OutputBits, int k>\n            struct exploder<Endian<UnitBits>, InputBits, OutputBits, k> {\n\n                // To keep the implementation managable, input and output sizes must\n                // be multiples or factors of the unit size.\n                // If one of these is firing, you may want a bit-only stream_endian\n                // rather than one that mentions bytes or octets.\n                BOOST_STATIC_ASSERT(!(InputBits % UnitBits && UnitBits % InputBits));\n                BOOST_STATIC_ASSERT(!(OutputBits % UnitBits && UnitBits % OutputBits));\n\n                typedef Endian<UnitBits> Endianness;\n                typedef exploder_step<Endianness, InputBits, OutputBits, k> step_type;\n                typedef exploder<Endianness, InputBits, OutputBits, k + OutputBits> next_type;\n\n                template<typename InputValue, typename OutIter>\n                static void explode(InputValue const &x, OutIter &out) {\n                    step_type::step(x, out);\n                    next_type::explode(x, out);\n                }\n            };\n\n            template<template<int> class Endian, int UnitBits, int InputBits, int OutputBits>\n            struct exploder<Endian<UnitBits>, InputBits, OutputBits, InputBits> {\n                template<typename InputValue, typename OutIter>\n                static void explode(InputValue const &, OutIter &) {\n                }\n            };\n\n        }    // namespace detail\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_BLOCK_DETAIL_EXPLODER_HPP\n", "meta": {"hexsha": "1b84ae3fb1105e334fb7e31270049aadc2a01097", "size": 7922, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/detail/exploder.hpp", "max_stars_repo_name": "nemo1369/vdf", "max_stars_repo_head_hexsha": "69c18131b42429e58788a7854b2deb7def217364", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-11-14T03:02:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-25T13:20:52.000Z", "max_issues_repo_path": "include/nil/crypto3/detail/exploder.hpp", "max_issues_repo_name": "nemo1369/vdf", "max_issues_repo_head_hexsha": "69c18131b42429e58788a7854b2deb7def217364", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-11-07T18:17:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-22T14:22:28.000Z", "max_forks_repo_path": "include/nil/crypto3/detail/exploder.hpp", "max_forks_repo_name": "nemo1369/vdf", "max_forks_repo_head_hexsha": "69c18131b42429e58788a7854b2deb7def217364", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-11T15:36:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-11T15:36:12.000Z", "avg_line_length": 49.8238993711, "max_line_length": 116, "alphanum_fraction": 0.5849532946, "num_tokens": 1607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.2872622592485895}}
{"text": "/*\n    Copyright (c) 2013, Philipp Krähenbühl\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 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\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    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 \"densecrf.h\"\n#include \"permutohedral.h\"\n#include \"util.h\"\n#include \"pairwise.h\"\n#include <cmath>\n#include <cstring>\n#include <iostream>\n#include <cstdio>\n#include <ctime>\n#include <algorithm>    // std::min\n#include <boost/concept_check.hpp>\n\ntemplate<typename Derived>\ninline bool is_finite(const Eigen::MatrixBase<Derived>& x)\n{\n\treturn ((x.array() == x.array())).all();\n}\n\n/////////////////////////////\n/////  Alloc / Dealloc  /////\n/////////////////////////////\nDenseCRF::DenseCRF(int N, int M) : N_(N), M_(M), unary_(0), unary2_(0) {\n  printf(\"DenseCRF  constructor get called\\n\");\n}\nDenseCRF::~DenseCRF() {\n  printf(\"DenseCRF destructor  get called, pairwise size is %d\\n\", pairwise_.size());\n\tif (unary_)\n\t\tdelete unary_;\n\tif (unary2_)\n\t\tdelete unary2_;\n        //if (pairwise_.size() > 4)\n\t//for( unsigned int i=0; i<pairwise_.size(); i++ )\n        //  if (pairwise_[i])\n\t//\tdelete pairwise_[i];\n}\nDenseCRF2D::DenseCRF2D(int W, int H, int M) : DenseCRF(W*H,M), W_(W), H_(H) {\n}\nDenseCRF2D::~DenseCRF2D() {\n}\n\nDenseCRF3D::DenseCRF3D(int N,  int M) : DenseCRF(N, M) {\n  printf(\"DenseCRF3d  constructor get called\\n\");\n}\nDenseCRF3D::~DenseCRF3D() {\n}\n/////////////////////////////////\n/////  Pairwise Potentials  /////\n/////////////////////////////////\nvoid DenseCRF::addPairwiseEnergy (const MatrixXf & features, LabelCompatibility * function, KernelType kernel_type, NormalizationType normalization_type) {\n// \tassert( features.cols() == N_ ); //HACK  comment by me, for hierarchical use\n  addPairwiseEnergy(std::shared_ptr<PairwisePotential> (new PairwisePotential( features, function, kernel_type, normalization_type )) );\n}\nvoid DenseCRF::addPairwiseEnergy ( std::shared_ptr<PairwisePotential> potential ){\n\tpairwise_.push_back( potential );\n}\n\nvoid DenseCRF2D::addPairwiseGaussian ( float sx, float sy, LabelCompatibility * function, KernelType kernel_type, NormalizationType normalization_type ) {\n\tMatrixXf feature( 2, N_ );\n\tfor( int j=0; j<H_; j++ )\n\t\tfor( int i=0; i<W_; i++ ){\n\t\t\tfeature(0,j*W_+i) = i / sx;\n\t\t\tfeature(1,j*W_+i) = j / sy;\n\t\t}\n\taddPairwiseEnergy( feature, function, kernel_type, normalization_type );\n}\n\nvoid DenseCRF2D::addPairwiseBilateral ( float sx, float sy, float sr, float sg, float sb, const unsigned char* im, LabelCompatibility * function, KernelType kernel_type, NormalizationType normalization_type ) {\n// \tMatrixXf feature_Bilateral( 5, N_ ); // some part of feature_Bilateral is fixed all the time\n\tif (!init_pose_pairwise)\n\t    addBilateral_pos(sx,sy);  \n\tfor( int j=0; j<H_; j++ )\n\t\tfor( int i=0; i<W_; i++ ){\n// \t\t\tfeature_Bilateral(0,j*W_+i) = i / sx;\n// \t\t\tfeature_Bilateral(1,j*W_+i) = j / sy;\n\t\t\tfeature_Bilateral(2,j*W_+i) = im[(i+j*W_)*3+0] / sr;\n\t\t\tfeature_Bilateral(3,j*W_+i) = im[(i+j*W_)*3+1] / sg;\n\t\t\tfeature_Bilateral(4,j*W_+i) = im[(i+j*W_)*3+2] / sb;\n\t\t}\n\taddPairwiseEnergy( feature_Bilateral, function, kernel_type, normalization_type );\n}\n\n\nvoid DenseCRF2D::addPairwiseBilateral ( float sx, float sy, float sr, float sg, float sb, VectorX8u im, LabelCompatibility * function, KernelType kernel_type, NormalizationType normalization_type ) {\n// \tMatrixXf feature( 5, N_ );\n\tif (!init_pose_pairwise)\n\t    addBilateral_pos(sx,sy);\n\tfor( int j=0; j<H_; j++ )\n\t\tfor( int i=0; i<W_; i++ ){\n// \t\t\tfeature_Bilateral(0,j*W_+i) = i / sx;\n// \t\t\tfeature_Bilateral(1,j*W_+i) = j / sy;\n\t\t\tfeature_Bilateral(2,j*W_+i) = im[(i+j*W_)*3+0] / sr;\n\t\t\tfeature_Bilateral(3,j*W_+i) = im[(i+j*W_)*3+1] / sg;\n\t\t\tfeature_Bilateral(4,j*W_+i) = im[(i+j*W_)*3+2] / sb;\n\t\t}\n\taddPairwiseEnergy( feature_Bilateral, function, kernel_type, normalization_type );\n}\n\nvoid DenseCRF2D::addBilateral_pos(float sx,float sy)  // this is fixed, doesn't change with color\n{\n\tfeature_Bilateral.resize( 5, N_ );\n\tfor( int j=0; j<H_; j++ )\n\t      for( int i=0; i<W_; i++ ){\n\t\t      feature_Bilateral(0,j*W_+i) = i / sx;\n\t\t      feature_Bilateral(1,j*W_+i) = j / sy;\n\t      }\n\tinit_pose_pairwise=true;\n}\n\nvoid DenseCRF3D::addPairwiseGaussian( float sx, float sy, float sz, const MatrixXf& posList, \n\t\t\t\t\t        LabelCompatibility * function, KernelType kernel_type, NormalizationType normalization_type ) {\n// \tassert(posList.cols()==N_); // comment this for hierarchical crf\n\tMatrixXf feature( 3, posList.cols() );\n\tfor (int i=0; i<posList.cols(); i++) {\n\t\tfloat x = posList(0,i);\n\t\tfloat y = posList(1,i);\n\t\tfloat z = posList(2,i);\n\t\t\n\t\tfeature(0, i) = x / sx;\n\t\tfeature(1, i) = y / sy;\n\t\tfeature(2, i) = z / sz;\n\t}\n\taddPairwiseEnergy( feature, function, kernel_type, normalization_type );\n}\n\n\nvoid DenseCRF3D::addPairwiseBilateral ( float sx, float sy, float sz, float sr, float sg, float sb, const MatrixXf& posList, \n\t\t\t\t\t  const MatrixXf& colorList, LabelCompatibility * function, KernelType kernel_type, NormalizationType normalization_type ) {\n//       assert(posList.cols()==N_);  // comment this for hierarchical crf\n//       assert(colorList.cols()==N_);\n      assert(colorList.cols()==posList.cols());\n      MatrixXf feature_Bilateral(6, posList.cols() );  // some part could be precompute  by me\n      for (int i=0; i<posList.cols(); i++) {\n\t\tfloat x = posList(0,i);\n\t\tfloat y = posList(1,i);\n\t\tfloat z = posList(2,i);\n\t\t\n\t\tfeature_Bilateral(0, i) = x / sx;\n\t\tfeature_Bilateral(1, i) = y / sy;\n\t\tfeature_Bilateral(2, i) = z / sz;\n\t\t\n\t\tfeature_Bilateral(3, i) = colorList(0,i) / sr;\n\t\tfeature_Bilateral(4, i) = colorList(1,i) / sg;\n\t\tfeature_Bilateral(5, i) = colorList(2,i) / sb;\n\t}\t\n\taddPairwiseEnergy( feature_Bilateral, function, kernel_type, normalization_type );\n}\n\n\n//////////////////////////////\n/////  Unary Potentials  /////\n//////////////////////////////\nvoid DenseCRF::setUnaryEnergy ( UnaryEnergy * unary ) {\n\tif( unary_ ) delete unary_;\n\tunary_ = unary;\n}\nvoid DenseCRF::setUnaryEnergy( const MatrixXf & unary ) {\n\tsetUnaryEnergy( new ConstUnaryEnergy( unary ) );\n}\nvoid DenseCRF::setUnaryEnergy2( const MatrixXf & unary ) {\n\tif( unary2_ ) delete unary2_;\n\tunary2_ = new ConstUnaryEnergy( unary );\n}\n\nvoid  DenseCRF::setUnaryEnergy( const MatrixXf & L, const MatrixXf & f ) {\n\tsetUnaryEnergy( new LogisticUnaryEnergy( L, f ) );\n}\n///////////////////////\n/////  Inference  /////\n///////////////////////\nvoid expAndNormalize ( MatrixXf & out, const MatrixXf & in ) {\n\tout.resize( in.rows(), in.cols() );\n\tfor( int i=0; i<out.cols(); i++ ){\n\t\tVectorXf b = in.col(i);\n\t\tb.array() -= b.maxCoeff();\n\t\tb = b.array().exp();\n\t\tout.col(i) = b / b.array().sum();\n\t}\n}\n\nvoid sumAndNormalize( MatrixXf & out, const MatrixXf & in, const MatrixXf & Q ) {\n\tout.resize( in.rows(), in.cols() );\n\tfor( int i=0; i<in.cols(); i++ ){\n\t\tVectorXf b = in.col(i);\n\t\tVectorXf q = Q.col(i);\n\t\tout.col(i) = b.array().sum()*q - b;\n\t}\n}\n\nMatrixXf DenseCRF::inference ( int n_iterations ) {\n  \tif (fuse_last_Q_dist)\n\t    return inference_fuse( n_iterations );\n\t\n\tif (addHO && hierarchical_high_order)\n\t    return inference_hierarchical( n_iterations );\n\t\n\tMatrixXf Q( M_, N_ ), tmp1, unary( M_, N_ ), tmp2;\n\tunary.fill(0);\n\tif( unary_ )\n\t\tunary = unary_->get();\n\n\texpAndNormalize( Q, -unary );\n\t\n\tfor( int it=0; it<n_iterations; it++ ) \n\t{\n\t\ttmp1 = -unary; //  tmp1, negative number  the higher, the larger prob\n\t\tif(addHO)\n\t\t{\n\t\t\tset_mem_init_higherorder();\n\t\t\tcalculate_higherorder_pot(Q,tmp1);\n\t\t\tif (!decoupled_high_order)\n\t\t\t    tmp1 += high_order_sp_to_pix;  // minus high order potential energy\n\t\t}\n\t\t\n\t\tfor( unsigned int k=0; k<pairwise_.size(); k++ ) {  // usually two. color and position\n\t\t\tpairwise_[k]->apply( tmp2, Q );  // each kind of features generate tmp2 (similary as unary, represent mutual energy)\n\t\t\ttmp1 -= tmp2;  // minus pairwise potential energy (minus a negative number)\n\t\t}\n\t\texpAndNormalize( Q, tmp1 ); //update Q (change energy into probability, each column independenty), doesn't change tmp1\n\t}\n\treturn Q;\n}\n\n\nMatrixXf DenseCRF::inference_hierarchical( int n_iterations )\n{\n\tint sp_num=all_3d_superpixels_.size();\n\t\n\tMatrixXf Q_low( M_, N_ ), tmp1_low, unary_low( M_, N_ ), tmp2_low;\n\tMatrixXf Q_high( M_, sp_num ), tmp1_high, unary_high( M_, sp_num), tmp2_high;\n\n\tstd::cout<<\"Hierarchical CRF low level size  \"<<N_<<\"  high level size  \"<<sp_num<<std::endl;\n\t\n\tunary_low.fill(0);\n\tif( unary_ )\n\t\tunary_low = -unary_->get(); //NOTE, I keep a minus here, because all later operations use minus\n\t\n\tunary_high.fill(0); // high order unary set to 0, corresponding to clique's low cost is 0\n\tif( unary2_ )\n\t\tunary_high = -unary2_->get();\n\n\tstd::clock_t start;\n\n\texpAndNormalize( Q_low,  unary_low);\n\texpAndNormalize( Q_high, unary_high);\n\n\tbool separate_two_level=true;\n\tif (separate_two_level)\n\t{\n\t      for( int it=0; it<n_iterations; it++ ) \n\t      {\n\t\t      tmp1_low = unary_low;  // tmp1_low the higher, the larger prob\n\t\t      tmp1_high = unary_high;\n// \t\t      set_mem_init_higherorder();  // if want to use  high_order_pix_to_sp etc.\n\t\t      \n\t\t      // first optimize high level nodes's label\n\t\t      calculate_hierar_highlevel_pot(Q_low,Q_high,tmp1_high);\n// \t\t      tmp1_high -= high_order_pix_to_sp;\n\t\t      for( unsigned int k=2; k<4; k++ ) {  // for high level pixels\n\t\t\t      pairwise_[k]->apply( tmp2_high, Q_high );  // each kind of features generate tmp2 (similary as unary, represent mutual energy)\n\t\t\t      tmp1_high -= tmp2_high;  // minus pairwise potential energy\n\t\t      }\n\t\t      expAndNormalize( Q_high, tmp1_high ); //update Q (change energy into probability, each column independenty), doesn't change tmp1\n\t\t      for (int sp_id=0;sp_id<all_3d_superpixels_.size();sp_id++)\n\t\t\t    all_3d_superpixels_[sp_id]->max_label_prob=Q_high.col(sp_id).maxCoeff(&all_3d_superpixels_[sp_id]->label);\n\t\t      \n\t\t      // then fix high level nodes, only optimize low level nodes.\n\t\t      calculate_hierar_lowlevel_pot(Q_low,tmp1_low);\n// \t\t      tmp1_low -= high_order_sp_to_pix;\n\t\t      for( unsigned int k=0; k<2; k++ ) {  // for low level pixels\n\t\t\t      pairwise_[k]->apply( tmp2_low, Q_low );  // each kind of features generate tmp2 (similary as unary, represent mutual energy)\n\t\t\t      tmp1_low -= tmp2_low;  // minus pairwise potential energy\n\t\t      }\n\t\t      expAndNormalize( Q_low, tmp1_low ); //update Q (change energy into probability, each column independenty), doesn't change tmp1\n\t      }\n\t}\n\telse\n\t{\n\t      for( int it=0; it<n_iterations; it++ ) \n\t      {\n\t\t      tmp1_low = unary_low;\n\t\t      tmp1_high = unary_high;\n// \t\t      set_mem_init_higherorder();\n\n\t\t      calculate_hierarchical_pot(Q_low,Q_high,tmp1_low,tmp1_high);\n// \t\t      tmp1_low -= high_order_sp_to_pix;\n// \t\t      tmp1_high -= high_order_pix_to_sp;\n\n\t\t      for( unsigned int k=0; k<2; k++ ) {  // for low level pixels\n\t\t\t      pairwise_[k]->apply( tmp2_low, Q_low );  // each kind of features generate tmp2 (similary as unary, represent mutual energy)\n\t\t\t      tmp1_low -= tmp2_low;  // minus pairwise potential energy\n\t\t      }\n\n\t\t      for( unsigned int k=2; k<4; k++ ) {  // for high level pixels\n\t\t\t      pairwise_[k]->apply( tmp2_high, Q_high );  // each kind of features generate tmp2 (similary as unary, represent mutual energy)\n\t\t\t      tmp1_high -= tmp2_high;  // minus pairwise potential energy\n\t\t      }\n\t\t      expAndNormalize( Q_low, tmp1_low ); //update Q (change energy into probability, each column independenty), doesn't change tmp1\n\t\t      expAndNormalize( Q_high, tmp1_high ); //update Q (change energy into probability, each column independenty), doesn't change tmp1\n\t      }\n\t}\n\treturn Q_low;\n}\n\n\n\nvoid fuse_Q_dist(MatrixXf& curr_Q, const MatrixXf& last_Q, const float last_weight)\n{\n\tcurr_Q=last_weight*last_Q+(1-last_weight)*curr_Q;\n\t// normalize to sum to 1 in each column\n\tfor( int i=0; i<curr_Q.cols(); i++ ){\n\t\tVectorXf b = curr_Q.col(i);\n\t\tcurr_Q.col(i) = b / b.array().sum();\n\t}\n}\n\n\nMatrixXf DenseCRF::inference_fuse ( int n_iterations ) {\n\tMatrixXf Q, tmp1, unary( M_, N_ ), tmp2;\n\tunary.fill(0);\n\tif( unary_ )\n\t    unary = unary_->get();\n\t\t\n\texpAndNormalize( Q, -unary );\n\tif (Q_dist_initialized)  // fuse Q with last time\n\t    fuse_Q_dist(Q, Q_last, last_Q_weight);\n\t\n\tfor( int it=0; it<n_iterations; it++ ) {\n\t\ttmp1 = -unary;  // right or not??? whether use Q\n\t\tfor( unsigned int k=0; k<pairwise_.size(); k++ ) {\n\t\t\tpairwise_[k]->apply( tmp2, Q );\n\t\t\ttmp1 -= tmp2;\n\t\t}\n\t\texpAndNormalize( Q, tmp1 );\n\t}\n\tQ_last=Q;\n\tQ_dist_initialized=true;\n\treturn Q;\n}\n\nVectorXi DenseCRF::map ( int n_iterations ) {\n\t// Run inference\n\tMatrixXf Q = inference( n_iterations );\n\t// Find the map\n\treturn currentMap( Q );\n}\n\n\n// MatrixXf DenseCRF::map_prob( int n_iterations ) const{\n//        return inference( n_iterations );\n// }\n      \n///////////////////\n/////  Debug  /////\n///////////////////\nVectorXf DenseCRF::unaryEnergy(const VectorXi & l) {\n\tassert( l.cols() == N_ );\n\tVectorXf r( N_ );\n\tr.fill(0.f);\n\tif( unary_ ) {\n\t\tMatrixXf unary = unary_->get();\n\t\t\n\t\tfor( int i=0; i<N_; i++ )\n\t\t\tif ( 0 <= l[i] && l[i] < M_ )\n\t\t\t\tr[i] = unary( l[i], i );\n\t}\n\treturn r;\n}\nVectorXf DenseCRF::pairwiseEnergy(const VectorXi & l, int term) {\n\tassert( l.cols() == N_ );\n\tVectorXf r( N_ );\n\tr.fill(0.f);\n\t\n\tif( term == -1 ) {\n\t\tfor( unsigned int i=0; i<pairwise_.size(); i++ )\n\t\t\tr += pairwiseEnergy( l, i );\n\t\treturn r;\n\t}\n\t\n\tMatrixXf Q( M_, N_ );\n\t// Build the current belief [binary assignment]\n\tfor( int i=0; i<N_; i++ )\n\t\tfor( int j=0; j<M_; j++ )\n\t\t\tQ(j,i) = (l[i] == j);\n\tpairwise_[ term ]->apply( Q, Q );\n\tfor( int i=0; i<N_; i++ )\n\t\tif ( 0 <= l[i] && l[i] < M_ )\n\t\t\tr[i] =-0.5*Q(l[i],i );\n\t\telse\n\t\t\tr[i] = 0;\n\treturn r;\n}\nMatrixXf DenseCRF::startInference() const{\n\tMatrixXf Q( M_, N_ );\n\tQ.fill(0);\n\t\n\t// Initialize using the unary energies\n\tif( unary_ )\n\t\texpAndNormalize( Q, -unary_->get() );\n\treturn Q;\n}\nvoid DenseCRF::stepInference( MatrixXf & Q, MatrixXf & tmp1, MatrixXf & tmp2 ) const{\n\ttmp1.resize( Q.rows(), Q.cols() );\n\ttmp1.fill(0);\n\tif( unary_ )\n\t\ttmp1 -= unary_->get();\n\t\n\t// Add up all pairwise potentials\n\tfor( unsigned int k=0; k<pairwise_.size(); k++ ) {\n\t\tpairwise_[k]->apply( tmp2, Q );\n\t\ttmp1 -= tmp2;\n\t}\n\t\n\t// Exponentiate and normalize\n\texpAndNormalize( Q, tmp1 );\n}\nVectorXi DenseCRF::currentMap( const MatrixXf & Q ) const{\n\tVectorXi r(Q.cols());\n\t// Find the map\n\tfor( int i=0; i<N_; i++ ){\n\t\tint m;\n\t\tQ.col(i).maxCoeff( &m );\n\t\tr[i] = m;\n\t}\n\treturn r;\n}\n\n// Compute the KL-divergence of a set of marginals\ndouble DenseCRF::klDivergence( const MatrixXf & Q ) const {\n\tdouble kl = 0;\n\t// Add the entropy term\n\tfor( int i=0; i<Q.cols(); i++ )\n\t\tfor( int l=0; l<Q.rows(); l++ )\n\t\t\tkl += Q(l,i)*log(std::max( Q(l,i), 1e-20f) );\n\t// Add the unary term\n\tif( unary_ ) {\n\t\tMatrixXf unary = unary_->get();\n\t\tfor( int i=0; i<Q.cols(); i++ )\n\t\t\tfor( int l=0; l<Q.rows(); l++ )\n\t\t\t\tkl += unary(l,i)*Q(l,i);\n\t}\n\t\n\t// Add all pairwise terms\n\tMatrixXf tmp;\n\tfor( unsigned int k=0; k<pairwise_.size(); k++ ) {\n\t\tpairwise_[k]->apply( tmp, Q );\n\t\tkl += (Q.array()*tmp.array()).sum();\n\t}\n\treturn kl;\n}\n\n// Gradient computations\ndouble DenseCRF::gradient( int n_iterations, const ObjectiveFunction & objective, VectorXf * unary_grad, VectorXf * lbl_cmp_grad, VectorXf * kernel_grad) const {\n\t// Run inference\n\tstd::vector< MatrixXf > Q(n_iterations+1);\n\tMatrixXf tmp1, unary( M_, N_ ), tmp2;\n\tunary.fill(0);\n\tif( unary_ )\n\t\tunary = unary_->get();\n\texpAndNormalize( Q[0], -unary );\n\tfor( int it=0; it<n_iterations; it++ ) {\n\t\ttmp1 = -unary;\n\t\tfor( unsigned int k=0; k<pairwise_.size(); k++ ) {\n\t\t\tpairwise_[k]->apply( tmp2, Q[it] );\n\t\t\ttmp1 -= tmp2;\n\t\t}\n\t\texpAndNormalize( Q[it+1], tmp1 );\n\t}\n\t\n\t// Compute the objective value\n\tMatrixXf b( M_, N_ );\n\tdouble r = objective.evaluate( b, Q[n_iterations] );\n\tsumAndNormalize( b, b, Q[n_iterations] );\n\n\t// Compute the gradient\n\tif(unary_grad && unary_)\n\t\t*unary_grad = unary_->gradient( b );\n\tif( lbl_cmp_grad )\n\t\t*lbl_cmp_grad = 0*labelCompatibilityParameters();\n\tif( kernel_grad )\n\t\t*kernel_grad = 0*kernelParameters();\n\t\n\tfor( int it=n_iterations-1; it>=0; it-- ) {\n\t\t// Do the inverse message passing\n\t\ttmp1.fill(0);\n\t\tint ip = 0, ik = 0;\n\t\t// Add up all pairwise potentials\n\t\tfor( unsigned int k=0; k<pairwise_.size(); k++ ) {\n\t\t\t// Compute the pairwise gradient expression\n\t\t\tif( lbl_cmp_grad ) {\n\t\t\t\tVectorXf pg = pairwise_[k]->gradient( b, Q[it] );\n\t\t\t\tlbl_cmp_grad->segment( ip, pg.rows() ) += pg;\n\t\t\t\tip += pg.rows();\n\t\t\t}\n\t\t\t// Compute the kernel gradient expression\n\t\t\tif( kernel_grad ) {\n\t\t\t\tVectorXf pg = pairwise_[k]->kernelGradient( b, Q[it] );\n\t\t\t\tkernel_grad->segment( ik, pg.rows() ) += pg;\n\t\t\t\tik += pg.rows();\n\t\t\t}\n\t\t\t// Compute the new b\n\t\t\tpairwise_[k]->applyTranspose( tmp2, b );\n\t\t\ttmp1 += tmp2;\n\t\t}\n\t\tsumAndNormalize( b, tmp1.array()*Q[it].array(), Q[it] );\n\t\t\n\t\t// Add the gradient\n\t\tif(unary_grad && unary_)\n\t\t\t*unary_grad += unary_->gradient( b );\n\t}\n\treturn r;\n}\nVectorXf DenseCRF::unaryParameters() const {\n\tif( unary_ )\n\t\treturn unary_->parameters();\n\treturn VectorXf();\n}\nvoid DenseCRF::setUnaryParameters( const VectorXf & v ) {\n\tif( unary_ )\n\t\tunary_->setParameters( v );\n}\nVectorXf DenseCRF::labelCompatibilityParameters() const {\n\tstd::vector< VectorXf > terms;\n\tfor( unsigned int k=0; k<pairwise_.size(); k++ )\n\t\tterms.push_back( pairwise_[k]->parameters() );\n\tint np=0;\n\tfor( unsigned int k=0; k<pairwise_.size(); k++ )\n\t\tnp += terms[k].rows();\n\tVectorXf r( np );\n\tfor( unsigned int k=0,i=0; k<pairwise_.size(); k++ ) {\n\t\tr.segment( i, terms[k].rows() ) = terms[k];\n\t\ti += terms[k].rows();\n\t}\t\n\treturn r;\n}\nvoid DenseCRF::setLabelCompatibilityParameters( const VectorXf & v ) {\n\tstd::vector< int > n;\n\tfor( unsigned int k=0; k<pairwise_.size(); k++ )\n\t\tn.push_back( pairwise_[k]->parameters().rows() );\n\tint np=0;\n\tfor( unsigned int k=0; k<pairwise_.size(); k++ )\n\t\tnp += n[k];\n\t\n\tfor( unsigned int k=0,i=0; k<pairwise_.size(); k++ ) {\n\t\tpairwise_[k]->setParameters( v.segment( i, n[k] ) );\n\t\ti += n[k];\n\t}\t\n}\nVectorXf DenseCRF::kernelParameters() const {\n\tstd::vector< VectorXf > terms;\n\tfor( unsigned int k=0; k<pairwise_.size(); k++ )\n\t\tterms.push_back( pairwise_[k]->kernelParameters() );\n\tint np=0;\n\tfor( unsigned int k=0; k<pairwise_.size(); k++ )\n\t\tnp += terms[k].rows();\n\tVectorXf r( np );\n\tfor( unsigned int k=0,i=0; k<pairwise_.size(); k++ ) {\n\t\tr.segment( i, terms[k].rows() ) = terms[k];\n\t\ti += terms[k].rows();\n\t}\t\n\treturn r;\n}\nvoid DenseCRF::setKernelParameters( const VectorXf & v ) {\n\tstd::vector< int > n;\n\tfor( unsigned int k=0; k<pairwise_.size(); k++ )\n\t\tn.push_back( pairwise_[k]->kernelParameters().rows() );\n\tint np=0;\n\tfor( unsigned int k=0; k<pairwise_.size(); k++ )\n\t\tnp += n[k];\n\t\n\tfor( unsigned int k=0,i=0; k<pairwise_.size(); k++ ) {\n\t\tpairwise_[k]->setKernelParameters( v.segment( i, n[k] ) );\n\t\ti += n[k];\n\t}\t\n}\n\n\n// start adding higher order potential related stuffs\nvoid DenseCRF::set_ho(bool add_ho)\n{\n\taddHO=add_ho;\n}\n\n\nvoid DenseCRF::set_mem_init_higherorder()\n{\n\tif(addHO)\n\t{\n\t\tif (high_order_sp_to_pix.rows()!=M_)\n\t\t    high_order_sp_to_pix=MatrixXf::Zero(M_, N_);\n\t\telse\n\t\t    high_order_sp_to_pix.setZero();\n\n\t\tif (hierarchical_high_order)\n\t\t{\n\t\t    if (high_order_pix_to_sp.rows()!=M_)\n\t\t\thigh_order_pix_to_sp=MatrixXf::Zero(M_,all_3d_superpixels_.size());\n\t\t    else\n\t\t\thigh_order_pix_to_sp.setZero();\n\t\t}\n\t}\n}\n\nvoid DenseCRF::calculate_higherorder_pot(const MatrixXf& Q,MatrixXf& temp_energy) \n{\n\tif(!decoupled_high_order)\n\t{\n\t\tint segment_count=all_3d_superpixels_.size();\n\t\tMatrixXf h_norm = MatrixXf::Ones(M_, segment_count);  // label distribution for each superpixels, directly multiply all pixels probability of that class\n\n\t\tint curr_pix_label = 0, curr_pix_index; // int x, y; \n\n\t\tVectorXf::Index max_label;\n\n\t\tfloat higher_order_prob;\n\t\tint pixels_num_in_superpixel = 0; \n\t\tfor(int sp_id = 0; sp_id < segment_count; sp_id++)  // for each superpixel\n\t\t{\n\t\t\tpixels_num_in_superpixel = all_3d_superpixels_[sp_id]->pixel_indexes.size();\n\t\t\tfor(int k = 0; k < M_; k++) // for all the class\n\t\t\t{\n\t\t\t\thigher_order_prob = 0.0; \n\t\t\t\tfor(int j = 0; j < pixels_num_in_superpixel; j++) // for each pixel in the superpixel //TODO change to vector production\n\t\t\t\t{\n\t\t\t\t\tcurr_pix_index = all_3d_superpixels_[sp_id]->pixel_indexes[j];\n\t\t\t\t\thigher_order_prob = higher_order_prob + Q(k,curr_pix_index); // change product to sum, avoid underflow\n\t\t\t\t}\n\t\t\t\th_norm(k,sp_id) = higher_order_prob; // multiply all pixel prob in one superpixel\n\t\t\t}\n\t\t}\n\n\t\tdouble alpha = 0.5;\n\t\tfloat cost_l = 1;  //10\n\t\tfloat cost_max = 5;  //100\n\t\tfloat high_order_weight = 1; // weight relative to unary and pairwise. TODO should be large?\n\t\tfor(int sp_id = 0; sp_id < segment_count; sp_id++)   // for each superpixel\n\t\t{\n\t\t\tpixels_num_in_superpixel = all_3d_superpixels_[sp_id]->pixel_indexes.size();\n\t\t\tfor(int j = 0; j < pixels_num_in_superpixel; j++)   //  for each pixel in the superpixel\n\t\t\t{\n\t\t\t    VectorXf::Index max_label;\n\t\t\t    curr_pix_index = all_3d_superpixels_[sp_id]->pixel_indexes[j]; \n\t\t\t    for(int k = 0; k < M_; k++)  //  for all the class\n\t\t\t    {\n\t\t\t\thigher_order_prob = h_norm(k,sp_id)-Q(k,curr_pix_index)+0.0001;\n\t\t\t\thigher_order_prob = higher_order_prob/float(pixels_num_in_superpixel);\n\t\t\t      \n\t\t\t\t// higher_order_prob is very small, so this is very close to cost_max\n\t\t\t\thigh_order_sp_to_pix(k,curr_pix_index) += higher_order_prob*cost_l+(1-higher_order_prob)*cost_max;\n\n\t\t\t\t// our proposed.   superpixel's label influce the clique,\n// \t\t\t\thigh_order_sp_to_pix(k,curr_pix_index) -= ( all_3d_superpixels_[sp_id]->label_distri).dot( Q.col(curr_pix_index) ) * 100; // 100 is a weght\n// \t\t\t\tif (k==all_3d_superpixels_[sp_id]->label)\n// \t\t\t\t    high_order_sp_to_pix(k,curr_pix_index) -= higher_order_prob*all_3d_superpixels_[sp_id]->label_distri[k]*100;\n\t\t\t    }\n\t\t\t}\n\t\t}\n\t\thigh_order_sp_to_pix = high_order_sp_to_pix*high_order_weight;\n\t}\n\telse  // change robust Pn model into pairwise+auxiliary node. but assume auxiliary's node is fixed.\n\t{\n\t\tint curr_pix_label = 0, curr_pix_index; // int x, y;\n\n\t\tfor(int sp_id = 0; sp_id < all_3d_superpixels_.size(); sp_id++)  // for each superpixel\n\t\t{\n\t\t\tfor(int j = 0; j < all_3d_superpixels_[sp_id]->pixel_indexes.size(); j++) // for each pixel in the superpixel //TODO change to vector production\n\t\t\t{\n\t\t\t\tcurr_pix_index = all_3d_superpixels_[sp_id]->pixel_indexes[j];\n\t\t\t\tfloat max_prob = Q.col(curr_pix_index).maxCoeff(&curr_pix_label);\n\t\t\t\tif (curr_pix_label==all_3d_superpixels_[sp_id]->label)\n\t\t\t\t    temp_energy(curr_pix_label,curr_pix_index) -= all_3d_superpixels_[sp_id]->max_label_prob*10.0; \n\t\t\t\t  // only one label (superpixel's label) has some energy.\n// \t\t\t\t    high_order_sp_to_pix(curr_pix_label,curr_pix_index) -= 10.0; //if label the same, give negative energy\n\t\t\t}\n\t\t}\n\t}\n}\n\n//both minimize_x_y  E(x,y)\nvoid DenseCRF::calculate_hierarchical_pot(const MatrixXf& Q_low,MatrixXf& Q_high,MatrixXf& temp_low_energy,MatrixXf& temp_high_energy)\n{\n\tint curr_pix_label = 0, curr_pix_index; // int x, y;\n\tint curr_sp_label = 0;\n\n\tfor(int sp_id = 0; sp_id < all_3d_superpixels_.size(); sp_id++)  // for each superpixel\n\t{\n\t\tfloat max_prob_sp = Q_high.col(sp_id).maxCoeff(&curr_sp_label);\n\t\tfor(int j = 0; j < all_3d_superpixels_[sp_id]->pixel_indexes.size(); j++) // for each pixel in the superpixel\n\t\t{\n\t\t\tcurr_pix_index = all_3d_superpixels_[sp_id]->pixel_indexes[j];\n\t\t\tfloat max_prob_pix = Q_low.col(curr_pix_index).maxCoeff(&curr_pix_label);\n\t\t\tif (curr_pix_label==curr_sp_label)\n\t\t\t{\n// \t\t\t      high_order_sp_to_pix(curr_pix_label,curr_pix_index) -= max_prob_sp*0.2; \n// \t\t\t      high_order_pix_to_sp(curr_sp_label,sp_id) -= max_prob_pix*0.2;\n\t\t\t      temp_low_energy(curr_pix_label,curr_pix_index) -= max_prob_sp*0.2;  // directly minus, faster\n\t\t\t      temp_high_energy(curr_sp_label,sp_id) -= max_prob_pix*0.2;\n\t\t\t}\n\t\t}\n\t}\n}\n\n//only minimize_y E(x,y)\nvoid DenseCRF::calculate_hierar_highlevel_pot(const MatrixXf& Q_low,const MatrixXf& Q_high,MatrixXf& temp_high_energy)\n{\n\tint curr_pix_label = 0, curr_pix_index; // int x, y;\n\tint curr_sp_label = 0;\n\n\tfor(int sp_id = 0; sp_id < all_3d_superpixels_.size(); sp_id++)  // for each superpixel\n\t{\n\t\tfloat max_prob_sp = Q_high.col(sp_id).maxCoeff(&curr_sp_label);\n\t\tfor(int j = 0; j < all_3d_superpixels_[sp_id]->pixel_indexes.size(); j++) // for each pixel in the superpixel\n\t\t{\n\t\t\tcurr_pix_index = all_3d_superpixels_[sp_id]->pixel_indexes[j];\n\t\t\tfloat max_prob_pix = Q_low.col(curr_pix_index).maxCoeff(&curr_pix_label);\n\t\t\tif (curr_pix_label==curr_sp_label) // if the same label, encourage, give negative energy.  could also penalize for different label.\n\t\t\t{\n// \t\t\t      high_order_pix_to_sp(curr_sp_label,sp_id) -= max_prob_pix*0.2;\n\t\t\t      temp_high_energy(curr_sp_label,sp_id) += 0.1;  // faster, directly add, originally, increase it to encourage it\n\t\t\t}\n\t\t}\n\t}\n}\n\n// using the minimal y, min_x E(x,y)\nvoid DenseCRF::calculate_hierar_lowlevel_pot(const MatrixXf& Q_low,MatrixXf& temp_low_energy)\n{\n\tint curr_pix_label = 0, curr_pix_index; // int x, y;\n\n\tstd::clock_t begin = std::clock();\n\tfor(int sp_id = 0; sp_id < all_3d_superpixels_.size(); sp_id++)  // for each superpixel\n\t{\n\t\tfor(int j = 0; j < all_3d_superpixels_[sp_id]->pixel_indexes.size(); j++) // for each pixel in the superpixel\n\t\t{\n\t\t\tcurr_pix_index = all_3d_superpixels_[sp_id]->pixel_indexes[j];\n\t\t\tfloat max_prob_pix = Q_low.col(curr_pix_index).maxCoeff(&curr_pix_label);\n\t\t\tif (curr_pix_label==all_3d_superpixels_[sp_id]->label)\n\t\t\t{\n\t\t\t      temp_low_energy(curr_pix_label,curr_pix_index) += 5.0;\n\t\t\t}\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "8247d71c4f4b83303dd9a46fcde3e76003b29a4a", "size": 26766, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dense_crf/libs/densecrf.cpp", "max_stars_repo_name": "zeroAska/BGKOctoMap-CRF", "max_stars_repo_head_hexsha": "b093b667eadc6c941e5576c714ed91d14ce52a56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-08T10:37:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T10:37:48.000Z", "max_issues_repo_path": "dense_crf/libs/densecrf.cpp", "max_issues_repo_name": "zeroAska/BGKOctoMap-CRF", "max_issues_repo_head_hexsha": "b093b667eadc6c941e5576c714ed91d14ce52a56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dense_crf/libs/densecrf.cpp", "max_forks_repo_name": "zeroAska/BGKOctoMap-CRF", "max_forks_repo_head_hexsha": "b093b667eadc6c941e5576c714ed91d14ce52a56", "max_forks_repo_licenses": ["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.761038961, "max_line_length": 210, "alphanum_fraction": 0.6628185011, "num_tokens": 8177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.28723234644775997}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2015 Johannes Göttker-Schnetmann\n Copyright (C) 2015 Klaus Spanderen\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file hestonslvmcmodel.cpp\n*/\n\n#include <ql/math/functional.hpp>\n#include <ql/termstructures/volatility/equityfx/fixedlocalvolsurface.hpp>\n#include <ql/experimental/models/hestonslvmcmodel.hpp>\n#include <ql/experimental/processes/hestonslvprocess.hpp>\n\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-local-typedefs\"\n#endif\n#include <boost/multi_array.hpp>\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic pop\n#endif\n\nnamespace QuantLib {\n    HestonSLVMCModel::HestonSLVMCModel(\n        const Handle<LocalVolTermStructure>& localVol,\n        const Handle<HestonModel>& hestonModel,\n        const ext::shared_ptr<BrownianGeneratorFactory>& brownianGeneratorFactory,\n        const Date& endDate,\n        Size timeStepsPerYear,\n        Size nBins,\n        Size calibrationPaths,\n        const std::vector<Date>& mandatoryDates,\n        const Real mixingFactor)\n    : localVol_(localVol),\n      hestonModel_(hestonModel),\n      brownianGeneratorFactory_(brownianGeneratorFactory),\n      endDate_(endDate),\n      nBins_(nBins),\n      calibrationPaths_(calibrationPaths),\n      mixingFactor_(mixingFactor) {\n\n        registerWith(localVol_);\n        registerWith(hestonModel_);\n\n        const DayCounter dc = hestonModel_->process()->riskFreeRate()->dayCounter();\n        const Date refDate = hestonModel_->process()->riskFreeRate()->referenceDate();\n\n        std::vector<Time> gridTimes;\n        gridTimes.reserve(mandatoryDates.size()+1);\n        for (Size i=0; i < mandatoryDates.size(); ++i) {\n            gridTimes.push_back(dc.yearFraction(refDate, mandatoryDates[i]));\n\n        }\n        gridTimes.push_back(dc.yearFraction(refDate, endDate));\n\n        timeGrid_ = ext::make_shared<TimeGrid>(gridTimes.begin(), gridTimes.end(),\n                std::max(Size(2), Size(gridTimes.back()*timeStepsPerYear)));\n    }\n\n    ext::shared_ptr<HestonProcess> HestonSLVMCModel::hestonProcess() const {\n        return hestonModel_->process();\n    }\n\n    ext::shared_ptr<LocalVolTermStructure> HestonSLVMCModel::localVol() const {\n        return localVol_.currentLink();\n    }\n\n    ext::shared_ptr<LocalVolTermStructure>\n    HestonSLVMCModel::leverageFunction() const {\n        calculate();\n\n        return leverageFunction_;\n    }\n\n    void HestonSLVMCModel::performCalculations() const {\n        const ext::shared_ptr<HestonProcess> hestonProcess\n            = hestonModel_->process();\n        const ext::shared_ptr<Quote> spot\n            = hestonProcess->s0().currentLink();\n\n        const Real v0            = hestonProcess->v0();\n        const DayCounter dc      = hestonProcess->riskFreeRate()->dayCounter();\n        const Date referenceDate = hestonProcess->riskFreeRate()->referenceDate();\n\n        const Volatility lv0\n            = localVol_->localVol(0.0, spot->value())/std::sqrt(v0);\n\n        const ext::shared_ptr<Matrix> L(new Matrix(nBins_, timeGrid_->size()));\n\n        std::vector<ext::shared_ptr<std::vector<Real> > >\n            vStrikes(timeGrid_->size());\n        for (Size i=0; i < timeGrid_->size(); ++i) {\n            const Integer u = nBins_/2;\n            const Real dx = spot->value()*std::sqrt(QL_EPSILON);\n\n            vStrikes[i] = ext::make_shared<std::vector<Real> >(nBins_);\n\n            for (Integer j=0; j < Integer(nBins_); ++j)\n                vStrikes[i]->at(j) = spot->value() + (j - u)*dx;\n        }\n\n        std::fill(L->column_begin(0),L->column_end(0), lv0);\n\n        leverageFunction_ = ext::make_shared<FixedLocalVolSurface>(\n            referenceDate,\n            std::vector<Time>(timeGrid_->begin(), timeGrid_->end()),\n            vStrikes, L, dc);\n\n        const ext::shared_ptr<HestonSLVProcess> slvProcess\n            = ext::make_shared<HestonSLVProcess>(hestonProcess, leverageFunction_, mixingFactor_);\n\n        std::vector<std::pair<Real, Real> > pairs(\n                calibrationPaths_, std::make_pair(spot->value(), v0));\n\n        const Size k = calibrationPaths_ / nBins_;\n        const Size m = calibrationPaths_ % nBins_;\n\n        const Size timeSteps = timeGrid_->size()-1;\n\n        typedef boost::multi_array<Real, 3> path_type;\n        path_type paths(boost::extents[calibrationPaths_][timeSteps][2]);\n\n        const ext::shared_ptr<BrownianGenerator> brownianGenerator =\n            brownianGeneratorFactory_->create(2, timeSteps);\n\n        for (Size i=0; i < calibrationPaths_; ++i) {\n            brownianGenerator->nextPath();\n            std::vector<Real> tmp(2);\n            for (Size j=0; j < timeSteps; ++j) {\n                brownianGenerator->nextStep(tmp);\n                paths[i][j][0] = tmp[0];\n                paths[i][j][1] = tmp[1];\n            }\n        }\n\n        for (Size n=1; n < timeGrid_->size(); ++n) {\n            const Time t = timeGrid_->at(n-1);\n            const Time dt = timeGrid_->dt(n-1);\n\n            Array x0(2), dw(2);\n\n            for (Size i=0; i < calibrationPaths_; ++i) {\n                x0[0] = pairs[i].first;\n                x0[1] = pairs[i].second;\n\n                dw[0] = paths[i][n-1][0];\n                dw[1] = paths[i][n-1][1];\n\n                x0 = slvProcess->evolve(t, x0, dt, dw);\n\n                pairs[i].first = x0[0];\n                pairs[i].second = x0[1];\n            }\n\n            std::sort(pairs.begin(), pairs.end());\n\n            Size s = 0U, e = 0U;\n            for (Size i=0; i < nBins_; ++i) {\n                const Size inc = k + static_cast<unsigned long>(i < m);\n                e = s + inc;\n\n                Real sum=0.0;\n                for (Size j=s; j < e; ++j) {\n                    sum+=pairs[j].second;\n                }\n                sum/=inc;\n\n                vStrikes[n]->at(i) = 0.5*(pairs[e-1].first + pairs[s].first);\n                (*L)[i][n] = std::sqrt(square<Real>()(\n                     localVol_->localVol(t, vStrikes[n]->at(i), true))/sum);\n\n                s = e;\n            }\n\n            leverageFunction_->setInterpolation<Linear>();\n        }\n    }\n}\n", "meta": {"hexsha": "29febd267e0588dd66ea3e532ec6d9e0b1bea559", "size": 6930, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/models/hestonslvmcmodel.cpp", "max_stars_repo_name": "urgu00/QuantLib", "max_stars_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-13T09:57:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-13T09:57:04.000Z", "max_issues_repo_path": "ql/experimental/models/hestonslvmcmodel.cpp", "max_issues_repo_name": "urgu00/QuantLib", "max_issues_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2020-11-23T08:36:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T10:06:53.000Z", "max_forks_repo_path": "ql/experimental/models/hestonslvmcmodel.cpp", "max_forks_repo_name": "urgu00/QuantLib", "max_forks_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-24T17:51:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-20T09:41:33.000Z", "avg_line_length": 35.7216494845, "max_line_length": 98, "alphanum_fraction": 0.6015873016, "num_tokens": 1776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2872049221622996}}
{"text": "// Boost.Geometry\r\n\r\n// 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#ifndef BOOST_GEOMETRY_SRS_PROJECTIONS_DPAR_HPP\r\n#define BOOST_GEOMETRY_SRS_PROJECTIONS_DPAR_HPP\r\n\r\n\r\n#include <boost/geometry/core/radius.hpp>\r\n#include <boost/geometry/core/tag.hpp>\r\n#include <boost/geometry/core/tags.hpp>\r\n\r\n#include <boost/geometry/srs/projections/exception.hpp>\r\n#include <boost/geometry/srs/projections/par_data.hpp>\r\n#include <boost/geometry/srs/sphere.hpp>\r\n#include <boost/geometry/srs/spheroid.hpp>\r\n\r\n#include <boost/mpl/assert.hpp>\r\n#include <boost/mpl/if.hpp>\r\n#include <boost/tuple/tuple.hpp>\r\n#include <boost/variant/variant.hpp>\r\n#include <boost/type_traits/integral_constant.hpp>\r\n#include <boost/type_traits/is_same.hpp>\r\n#include <boost/type_traits/is_void.hpp>\r\n\r\n#include <string>\r\n#include <vector>\r\n\r\nnamespace boost { namespace geometry { namespace srs\r\n{\r\n\r\nnamespace detail\r\n{\r\n\r\ntemplate\r\n<\r\n    typename Types,\r\n    typename T,\r\n    typename Iter = typename boost::mpl::begin<Types>::type,\r\n    typename End = typename boost::mpl::end<Types>::type,\r\n    int I = 0\r\n>\r\nstruct find_type_index\r\n{\r\n    typedef typename boost::mpl::deref<Iter>::type type;\r\n    static const int value = boost::is_same<type, T>::value\r\n                           ? I\r\n                           : find_type_index\r\n                                <\r\n                                    Types,\r\n                                    T,\r\n                                    typename boost::mpl::next<Iter>::type,\r\n                                    End,\r\n                                    I + 1\r\n                                >::value;\r\n                            \r\n};\r\n\r\ntemplate\r\n<\r\n    typename Types,\r\n    typename T,\r\n    typename End,\r\n    int I\r\n>\r\nstruct find_type_index<Types, T, End, End, I>\r\n{\r\n    static const int value = I;\r\n};\r\n\r\n\r\ntemplate\r\n<\r\n    typename Range,\r\n    typename ToValue,\r\n    bool IsRange = boost::has_range_iterator<Range>::value\r\n>\r\nstruct is_convertible_range\r\n    : boost::is_convertible\r\n        <\r\n            typename boost::range_value<Range>::type,\r\n            ToValue\r\n        >\r\n{};\r\n\r\ntemplate\r\n<\r\n    typename Range,\r\n    typename ToValue\r\n>\r\nstruct is_convertible_range<Range, ToValue, false>\r\n    : boost::false_type\r\n{};\r\n\r\n} // namespace detail\r\n\r\n\r\nnamespace dpar\r\n{\r\n\r\nenum value_datum\r\n{\r\n    datum_wgs84 = 0,\r\n    datum_ggrs87,\r\n    datum_nad83,\r\n    datum_nad27,\r\n    datum_potsdam,\r\n    datum_carthage,\r\n    datum_hermannskogel,\r\n    datum_ire65,\r\n    datum_nzgd49,\r\n    datum_osgb36,\r\n};\r\n\r\nenum value_ellps\r\n{\r\n    ellps_merit = 0,\r\n    ellps_sgs85,\r\n    ellps_grs80,\r\n    ellps_iau76,\r\n    ellps_airy,\r\n    ellps_apl4_9,\r\n    ellps_nwl9d,\r\n    ellps_mod_airy,\r\n    ellps_andrae,\r\n    ellps_aust_sa,\r\n    ellps_grs67,\r\n    ellps_bessel,\r\n    ellps_bess_nam,\r\n    ellps_clrk66,\r\n    ellps_clrk80,\r\n    ellps_clrk80ign,\r\n    ellps_cpm,\r\n    ellps_delmbr,\r\n    ellps_engelis,\r\n    ellps_evrst30,\r\n    ellps_evrst48,\r\n    ellps_evrst56,\r\n    ellps_evrst69,\r\n    ellps_evrstss,\r\n    ellps_fschr60,\r\n    ellps_fschr60m,\r\n    ellps_fschr68,\r\n    ellps_helmert,\r\n    ellps_hough,\r\n    ellps_intl,\r\n    ellps_krass,\r\n    ellps_kaula,\r\n    ellps_lerch,\r\n    ellps_mprts,\r\n    ellps_new_intl,\r\n    ellps_plessis,\r\n    ellps_seasia,\r\n    ellps_walbeck,\r\n    ellps_wgs60,\r\n    ellps_wgs66,\r\n    ellps_wgs72,\r\n    ellps_wgs84,\r\n    ellps_sphere\r\n};\r\n\r\nenum value_mode\r\n{\r\n    mode_plane = 0,\r\n    mode_di,\r\n    mode_dd,\r\n    mode_hex\r\n};\r\n\r\nenum value_orient\r\n{\r\n    orient_isea = 0,\r\n    orient_pole,\r\n};\r\n\r\nenum value_pm\r\n{\r\n    pm_greenwich = 0,\r\n    pm_lisbon,\r\n    pm_paris,\r\n    pm_bogota,\r\n    pm_madrid,\r\n    pm_rome,\r\n    pm_bern,\r\n    pm_jakarta,\r\n    pm_ferro,\r\n    pm_brussels,\r\n    pm_stockholm,\r\n    pm_athens,\r\n    pm_oslo\r\n};\r\n\r\nenum value_proj\r\n{\r\n    proj_unknown = 0,\r\n    proj_aea, proj_leac,\r\n    proj_aeqd,\r\n    proj_airy,\r\n    proj_aitoff, proj_wintri,\r\n    proj_august,\r\n    proj_apian, proj_ortel, proj_bacon,\r\n    proj_bipc,\r\n    proj_boggs,\r\n    proj_bonne,\r\n    proj_cass,\r\n    proj_cc,\r\n    proj_cea,\r\n    proj_chamb,\r\n    proj_collg,\r\n    proj_crast,\r\n    proj_denoy,\r\n    proj_eck1,\r\n    proj_eck2,\r\n    proj_eck3, proj_putp1, proj_wag6, proj_kav7,\r\n    proj_eck4,\r\n    proj_eck5,\r\n    proj_eqc,\r\n    proj_eqdc,\r\n    proj_etmerc, proj_utm,\r\n    proj_fahey,\r\n    proj_fouc_s,\r\n    proj_gall,\r\n    proj_geocent,\r\n    proj_geos,\r\n    proj_gins8,\r\n    proj_gn_sinu, proj_sinu, proj_eck6, proj_mbtfps,\r\n    proj_gnom,\r\n    proj_goode,\r\n    proj_gstmerc,\r\n    proj_hammer,\r\n    proj_hatano,\r\n    proj_healpix,\r\n    proj_rhealpix,\r\n    proj_igh,\r\n    proj_imw_p,\r\n    proj_isea,\r\n    proj_krovak,\r\n    proj_labrd,\r\n    proj_laea,\r\n    proj_lagrng,\r\n    proj_larr,\r\n    proj_lask,\r\n    proj_lonlat, proj_latlon, proj_latlong, proj_longlat,\r\n    proj_lcc,\r\n    proj_lcca,\r\n    proj_loxim,\r\n    proj_lsat,\r\n    proj_mbt_fps,\r\n    proj_mbtfpp,\r\n    proj_mbtfpq,\r\n    proj_merc,\r\n    proj_mill,\r\n    proj_mil_os, proj_lee_os, proj_gs48, proj_alsk, proj_gs50,\r\n    proj_moll, proj_wag4, proj_wag5,\r\n    proj_natearth,\r\n    proj_nell,\r\n    proj_nell_h,\r\n    proj_nicol,\r\n    proj_nsper, proj_tpers,\r\n    proj_nzmg,\r\n    proj_ob_tran,\r\n    proj_ocea,\r\n    proj_oea,\r\n    proj_omerc,\r\n    proj_ortho,\r\n    proj_poly,\r\n    proj_putp2,\r\n    proj_putp3, proj_putp3p,\r\n    proj_putp4p, proj_weren,\r\n    proj_putp5, proj_putp5p,\r\n    proj_putp6, proj_putp6p,\r\n    proj_qsc,\r\n    proj_robin,\r\n    proj_rouss,\r\n    proj_rpoly,\r\n    proj_euler, proj_murd1, proj_murd2, proj_murd3, proj_pconic, proj_tissot, proj_vitk1,\r\n    proj_somerc,\r\n    proj_stere, proj_ups,\r\n    proj_sterea,\r\n    proj_kav5, proj_qua_aut, proj_fouc, proj_mbt_s,\r\n    proj_tcc,\r\n    proj_tcea,\r\n    proj_tmerc,\r\n    proj_tpeqd,\r\n    proj_urm5,\r\n    proj_urmfps, proj_wag1,\r\n    proj_vandg,\r\n    proj_vandg2, proj_vandg3,\r\n    proj_vandg4,\r\n    proj_wag2,\r\n    proj_wag3,\r\n    proj_wag7,\r\n    proj_wink1,\r\n    proj_wink2\r\n};\r\n\r\nenum value_sweep\r\n{\r\n    sweep_x = 0, sweep_y\r\n};\r\n\r\nenum value_units\r\n{\r\n    units_km = 0,\r\n    units_m,\r\n    units_dm,\r\n    units_cm,\r\n    units_mm,\r\n    units_kmi,\r\n    units_in,\r\n    units_ft,\r\n    units_yd,\r\n    units_mi,\r\n    units_fath,\r\n    units_ch,\r\n    units_link,\r\n    units_us_in,\r\n    units_us_ft,\r\n    units_us_yd,\r\n    units_us_ch,\r\n    units_us_mi,\r\n    units_ind_yd,\r\n    units_ind_ft,\r\n    units_ind_ch\r\n};\r\n\r\nenum name_f\r\n{\r\n    a = 0,\r\n    b,\r\n    e,\r\n    es,\r\n    f,\r\n    h,\r\n    //h_0, // currently not used\r\n    k = 7,\r\n    k_0,\r\n    m, // also used for M\r\n    n,\r\n    //phdg_0, // currently not used\r\n    //plat_0, // currently not used\r\n    //plon_0, // currently not used\r\n    q = 14,\r\n    r, // originally R\r\n    rf,\r\n    to_meter,\r\n    vto_meter,\r\n    w, // originally W\r\n    x_0,\r\n    y_0\r\n};\r\n\r\nenum name_r\r\n{\r\n    alpha = 22,\r\n    azi,\r\n    gamma,\r\n    lat_0,\r\n    lat_1,\r\n    lat_2,\r\n    lat_3,\r\n    lat_b,\r\n    lat_ts, // 30\r\n    lon_0,\r\n    lon_1,\r\n    lon_2,\r\n    lon_3,\r\n    lon_wrap,\r\n    lonc,\r\n    o_alpha,\r\n    o_lat_1,\r\n    o_lat_2,\r\n    o_lat_c, // 40\r\n    o_lat_p,\r\n    o_lon_1,\r\n    o_lon_2,\r\n    o_lon_c,\r\n    o_lon_p,\r\n    r_lat_a, // originally R_lat_a\r\n    r_lat_g, // originally R_lat_g\r\n    theta,\r\n    tilt\r\n};\r\n\r\nenum name_i\r\n{\r\n    aperture = 50,\r\n    lsat,\r\n    north_square,\r\n    path,\r\n    resolution,\r\n    south_square,\r\n    zone\r\n};\r\n\r\nenum name_be\r\n{\r\n    czech = 57,\r\n    geoc,\r\n    guam,\r\n    no_cut, // 60\r\n    no_defs,\r\n    no_rot,\r\n    ns,\r\n    over,\r\n    r_au, // originally R_A\r\n    r_a, // originally R_a\r\n    r_g, // originally R_g\r\n    r_h, // originally R_h\r\n    r_v, // originally R_V\r\n    rescale, // 70\r\n    south\r\n};\r\n\r\n/*enum name_catalog\r\n{\r\n    catalog = 72 // currently not used\r\n};\r\n\r\nenum name_date\r\n{\r\n    date = 73 // currently not used\r\n};*/\r\n\r\nenum name_datum\r\n{\r\n    datum = 74\r\n};\r\n\r\nenum name_ellps\r\n{\r\n    ellps = 75 // id, sphere or spheroid\r\n};\r\n\r\n/*enum name_geoidgrids\r\n{\r\n    geoidgrids = 76 // currently not used\r\n};*/\r\n\r\nenum name_mode\r\n{\r\n    mode = 77\r\n};\r\n\r\nenum name_nadgrids\r\n{\r\n    nadgrids = 78 // arbitrary-length list of strings\r\n};\r\n\r\nenum name_orient\r\n{\r\n    orient = 79\r\n};\r\n\r\nenum name_pm\r\n{\r\n    pm = 80 // id or angle\r\n};\r\n\r\nenum name_proj\r\n{\r\n    o_proj = 81,\r\n    proj\r\n};\r\n\r\nenum name_sweep\r\n{\r\n    sweep = 83\r\n};\r\n\r\nenum name_towgs84\r\n{\r\n    towgs84 = 84 // 3 or 7 element list of numbers\r\n};\r\n\r\nenum name_units\r\n{\r\n    units = 85,\r\n    vunits\r\n};\r\n\r\ntemplate <typename T>\r\nstruct parameter\r\n{\r\n    parameter()\r\n        : m_id(-1), m_value(false)\r\n    {}\r\n\r\n    parameter(name_f id, T const& v)\r\n        : m_id(id), m_value(v)\r\n    {}\r\n\r\n    // TODO various angle units\r\n    parameter(name_r id, T const& v)\r\n        : m_id(id), m_value(v)\r\n    {}\r\n\r\n    parameter(name_i id, int v)\r\n        : m_id(id), m_value(v)\r\n    {}\r\n\r\n    parameter(name_be id)\r\n        : m_id(id), m_value(true)\r\n    {}\r\n\r\n    parameter(name_be id, bool v)\r\n        : m_id(id), m_value(v)\r\n    {}\r\n\r\n    parameter(name_datum id, value_datum v)\r\n        : m_id(id), m_value(int(v))\r\n    {}\r\n\r\n    parameter(value_datum v)\r\n        : m_id(datum), m_value(int(v))\r\n    {}\r\n\r\n    // TODO: store model at this point?\r\n    parameter(name_ellps id, value_ellps v)\r\n        : m_id(id), m_value(int(v))\r\n    {}\r\n    // TODO: store model at this point?\r\n    parameter(value_ellps v)\r\n        : m_id(ellps), m_value(int(v))\r\n    {}\r\n\r\n    template <typename Sphere>\r\n    parameter(name_ellps id, Sphere const& v,\r\n              typename boost::enable_if_c\r\n                <\r\n                    boost::is_same<typename geometry::tag<Sphere>::type, srs_sphere_tag>::value\r\n                >::type * = 0)\r\n        : m_id(id)\r\n        , m_value(T(get_radius<0>(v)))\r\n    {}\r\n\r\n    template <typename Spheroid>\r\n    parameter(name_ellps id, Spheroid const& v,\r\n              typename boost::enable_if_c\r\n                <\r\n                    boost::is_same<typename geometry::tag<Spheroid>::type, srs_spheroid_tag>::value\r\n                >::type * = 0)\r\n        : m_id(id)\r\n        , m_value(srs::spheroid<T>(get_radius<0>(v), get_radius<2>(v)))\r\n    {}\r\n\r\n    parameter(name_mode id, value_mode v)\r\n        : m_id(id), m_value(int(v))\r\n    {}\r\n\r\n    parameter(value_mode v)\r\n        : m_id(mode), m_value(int(v))\r\n    {}\r\n\r\n    template <typename Range>\r\n    parameter(name_nadgrids id, Range const& v,\r\n              typename boost::enable_if_c\r\n                <\r\n                    detail::is_convertible_range<Range const, std::string>::value\r\n                >::type * = 0)\r\n        : m_id(id)\r\n        , m_value(srs::detail::nadgrids(boost::begin(v), boost::end(v)))\r\n    {}\r\n\r\n#ifndef BOOST_NO_CXX11_HDR_INITIALIZER_LIST\r\n    parameter(name_nadgrids id, std::initializer_list<std::string> v)\r\n        : m_id(id)\r\n        , m_value(srs::detail::nadgrids(v))\r\n    {}\r\n#endif\r\n\r\n    parameter(name_orient id, value_orient v)\r\n        : m_id(id), m_value(int(v))\r\n    {}\r\n\r\n    parameter(value_orient v)\r\n        : m_id(orient), m_value(int(v))\r\n    {}\r\n\r\n    // TODO: store to_meters at this point?\r\n    parameter(name_pm id, value_pm v)\r\n        : m_id(id), m_value(int(v))\r\n    {}\r\n    // TODO: store to_meters at this point?\r\n    parameter(value_pm v)\r\n        : m_id(pm), m_value(int(v))\r\n    {}\r\n\r\n    // TODO angle units\r\n    parameter(name_pm id, T const& v)\r\n        : m_id(id), m_value(v)\r\n    {}\r\n\r\n    parameter(name_proj id, value_proj v)\r\n        : m_id(id), m_value(int(v))\r\n    {}\r\n\r\n    parameter(value_proj v)\r\n        : m_id(proj), m_value(int(v))\r\n    {}\r\n\r\n    parameter(name_sweep id, value_sweep v)\r\n        : m_id(id), m_value(int(v))\r\n    {}\r\n\r\n    parameter(value_sweep v)\r\n        : m_id(sweep), m_value(int(v))\r\n    {}\r\n\r\n    template <typename Range>\r\n    parameter(name_towgs84 id, Range const& v,\r\n              typename boost::enable_if_c\r\n                <\r\n                    detail::is_convertible_range<Range const, T>::value\r\n                >::type * = 0)\r\n        : m_id(id)\r\n        , m_value(srs::detail::towgs84<T>(boost::begin(v), boost::end(v)))\r\n    {\r\n        std::size_t n = boost::size(v);\r\n        if (n != 3 && n != 7)\r\n        {\r\n            BOOST_THROW_EXCEPTION( projection_exception(\"Invalid number of towgs84 elements. Should be 3 or 7.\") );\r\n        }\r\n    }\r\n\r\n#ifndef BOOST_NO_CXX11_HDR_INITIALIZER_LIST\r\n    parameter(name_towgs84 id, std::initializer_list<T> v)\r\n        : m_id(id)\r\n        , m_value(srs::detail::towgs84<T>(v))\r\n    {\r\n        std::size_t n = v.size();\r\n        if (n != 3 && n != 7)\r\n        {\r\n            BOOST_THROW_EXCEPTION( projection_exception(\"Invalid number of towgs84 elements. Should be 3 or 7.\") );\r\n        }\r\n    }\r\n#endif\r\n\r\n    parameter(name_units id, value_units v)\r\n        : m_id(id), m_value(int(v))\r\n    {}\r\n\r\n    parameter(value_units v)\r\n        : m_id(units), m_value(int(v))\r\n    {}\r\n    \r\nprivate:\r\n    typedef boost::variant\r\n        <\r\n            bool,\r\n            int,\r\n            T,\r\n            srs::spheroid<T>,\r\n            srs::detail::nadgrids,\r\n            srs::detail::towgs84<T>\r\n        > variant_type;\r\n\r\npublic:\r\n    bool is_id_equal(name_f const& id) const { return m_id == int(id); }\r\n    bool is_id_equal(name_r const& id) const { return m_id == int(id); }\r\n    bool is_id_equal(name_i const& id) const { return m_id == int(id); }\r\n    bool is_id_equal(name_be const& id) const { return m_id == int(id); }\r\n    bool is_id_equal(name_datum const& id) const { return m_id == int(id); }\r\n    bool is_id_equal(name_ellps const& id) const { return m_id == int(id); }\r\n    bool is_id_equal(name_mode const& id) const { return m_id == int(id); }\r\n    bool is_id_equal(name_nadgrids const& id) const { return m_id == int(id); }\r\n    bool is_id_equal(name_orient const& id) const { return m_id == int(id); }\r\n    bool is_id_equal(name_pm const& id) const { return m_id == int(id); }\r\n    bool is_id_equal(name_proj const& id) const { return m_id == int(id); }\r\n    bool is_id_equal(name_sweep const& id) const { return m_id == int(id); }\r\n    bool is_id_equal(name_towgs84 const& id) const { return m_id == int(id); }\r\n    bool is_id_equal(name_units const& id) const { return m_id == int(id); }\r\n\r\n    template <typename V>\r\n    V const& get_value() const\r\n    {\r\n        return boost::get<V>(m_value);\r\n    }\r\n\r\n    template <typename V>\r\n    bool is_value_set() const\r\n    {\r\n        return m_value.which() == srs::detail::find_type_index\r\n            <\r\n                typename variant_type::types,\r\n                V\r\n            >::value;\r\n    }\r\n    \r\nprivate:\r\n    int m_id;\r\n    variant_type m_value;\r\n};\r\n\r\ntemplate <typename T = double>\r\nclass parameters\r\n{\r\n    typedef std::vector<parameter<T> > container_type;\r\n\r\npublic:\r\n    typedef typename container_type::value_type value_type;\r\n    typedef typename container_type::const_iterator const_iterator;\r\n    typedef typename container_type::const_reference const_reference;\r\n    typedef typename container_type::size_type size_type;\r\n\r\n    BOOST_DEFAULTED_FUNCTION(parameters(), {})\r\n\r\n#if defined(BOOST_NO_CXX11_RVALUE_REFERENCES) || defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)\r\n    template <typename Id>\r\n    explicit parameters(Id id)\r\n    {\r\n        add(id);\r\n    }\r\n\r\n    template <typename Id>\r\n    parameters & add(Id id)\r\n    {\r\n        m_params.push_back(parameter<T>(id));\r\n        return *this;\r\n    }\r\n\r\n    template <typename Id>\r\n    parameters & operator()(Id id)\r\n    {\r\n        return add(id);\r\n    }\r\n\r\n    template <typename Id, typename V>\r\n    parameters(Id id, V const& value)\r\n    {\r\n        add(id, value);\r\n    }\r\n\r\n    template <typename Id, typename V>\r\n    parameters & add(Id id, V const& value)\r\n    {\r\n        m_params.push_back(parameter<T>(id, value));\r\n        return *this;\r\n    }\r\n\r\n    template <typename Id, typename V>\r\n    parameters & operator()(Id id, V const& value)\r\n    {\r\n        return add(id, value);\r\n    }\r\n\r\n#ifndef BOOST_NO_CXX11_HDR_INITIALIZER_LIST\r\n    template <typename Id, typename V>\r\n    parameters(Id id, std::initializer_list<V> value)\r\n    {\r\n        add(id, value);\r\n    }\r\n\r\n    template <typename Id, typename V>\r\n    parameters & add(Id id, std::initializer_list<V> value)\r\n    {\r\n        m_params.push_back(parameter<T>(id, value));\r\n        return *this;\r\n    }\r\n\r\n    template <typename Id, typename V>\r\n    parameters & operator()(Id id, std::initializer_list<V> value)\r\n    {\r\n        return add(id, value);\r\n    }\r\n#endif // BOOST_NO_CXX11_HDR_INITIALIZER_LIST\r\n#else // BOOST_NO_CXX11_RVALUE_REFERENCES || BOOST_NO_CXX11_RVALUE_REFERENCES\r\n    template <typename Id>\r\n    explicit parameters(Id id)\r\n    {\r\n        add(id);\r\n    }\r\n\r\n    template <typename Id>\r\n    parameters & add(Id id)\r\n    {\r\n        m_params.emplace_back(id);\r\n        return *this;\r\n    }\r\n\r\n    template <typename Id>\r\n    parameters & operator()(Id id)\r\n    {\r\n        return add(id);\r\n    }\r\n\r\n    template <typename Id, typename V>\r\n    parameters(Id id, V && value)\r\n    {\r\n        add(id, std::forward<V>(value));\r\n    }\r\n\r\n    template <typename Id, typename V>\r\n    parameters & add(Id id, V && value)\r\n    {\r\n        m_params.emplace_back(id, std::forward<V>(value));\r\n        return *this;\r\n    }\r\n\r\n    template <typename Id, typename V>\r\n    parameters & operator()(Id id, V && value)\r\n    {\r\n        return add(id, std::forward<V>(value));\r\n    }\r\n\r\n#ifndef BOOST_NO_CXX11_HDR_INITIALIZER_LIST\r\n    template <typename Id, typename V>\r\n    parameters(Id id, std::initializer_list<V> value)\r\n    {\r\n        add(id, value);\r\n    }\r\n\r\n    template <typename Id, typename V>\r\n    parameters & add(Id id, std::initializer_list<V> value)\r\n    {\r\n        m_params.emplace_back(id, value);\r\n        return *this;\r\n    }\r\n\r\n    template <typename Id, typename V>\r\n    parameters & operator()(Id id, std::initializer_list<V> value)\r\n    {\r\n        return add(id, value);\r\n    }\r\n#endif // BOOST_NO_CXX11_HDR_INITIALIZER_LIST\r\n#endif // BOOST_NO_CXX11_RVALUE_REFERENCES || BOOST_NO_CXX11_RVALUE_REFERENCES\r\n\r\n    const_iterator begin() const { return m_params.begin(); }\r\n    const_iterator end() const { return m_params.end(); }\r\n    const_reference operator[](size_type i) const { return m_params[i]; }\r\n    size_type size() { return m_params.size(); }\r\n    bool empty() { return m_params.empty(); }\r\n\r\nprivate:\r\n    container_type m_params;\r\n};\r\n\r\n\r\n} // namespace dpar\r\n\r\n\r\n}}} // namespace boost::geometry::srs\r\n\r\n\r\n#endif // BOOST_GEOMETRY_SRS_PROJECTIONS_DPAR_HPP\r\n", "meta": {"hexsha": "ecb0d8b3a98780991a173b3cec6c03a63918b13b", "size": 18707, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "externals/boost/boost/geometry/srs/projections/dpar.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/dpar.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/dpar.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": 21.982373678, "max_line_length": 116, "alphanum_fraction": 0.5781792912, "num_tokens": 5079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2871522673399509}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n/// \\file\n/// Defines class AdamsBashforthN\n\n#pragma once\n\n#include <algorithm>\n#include <boost/iterator/transform_iterator.hpp>\n#include <cstddef>\n#include <iosfwd>\n#include <iterator>\n#include <limits>\n#include <map>\n#include <pup.h>\n#include <tuple>\n#include <type_traits>\n#include <vector>\n\n#include \"NumericalAlgorithms/Interpolation/LagrangePolynomial.hpp\"\n#include \"Options/Options.hpp\"\n#include \"Parallel/CharmPupable.hpp\"\n#include \"Time/EvolutionOrdering.hpp\"\n#include \"Time/Time.hpp\"\n#include \"Time/TimeStepId.hpp\"\n#include \"Time/TimeSteppers/TimeStepper.hpp\"  // IWYU pragma: keep\n#include \"Utilities/CachedFunction.hpp\"\n#include \"Utilities/ErrorHandling/Assert.hpp\"\n#include \"Utilities/ErrorHandling/Error.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/MakeWithValue.hpp\"\n#include \"Utilities/Overloader.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\n/// \\cond\nnamespace TimeSteppers {\ntemplate <typename LocalVars, typename RemoteVars, typename CouplingResult>\nclass BoundaryHistory;  // IWYU pragma: keep\ntemplate <typename Vars, typename DerivVars>\nclass History;\n}  // namespace TimeSteppers\n/// \\endcond\n\nnamespace TimeSteppers {\n\n/*!\n * \\ingroup TimeSteppersGroup\n *\n * An Nth order Adams-Bashforth time stepper.\n *\n * The stable step size factors for different orders are given by:\n *\n * <table class=\"doxtable\">\n *  <tr>\n *    <th> %Order </th>\n *    <th> CFL Factor </th>\n *  </tr>\n *  <tr>\n *    <td> 1 </td>\n *    <td> 1 </td>\n *  </tr>\n *  <tr>\n *    <td> 2 </td>\n *    <td> 1 / 2 </td>\n *  </tr>\n *  <tr>\n *    <td> 3 </td>\n *    <td> 3 / 11 </td>\n *  </tr>\n *  <tr>\n *    <td> 4 </td>\n *    <td> 3 / 20 </td>\n *  </tr>\n *  <tr>\n *    <td> 5 </td>\n *    <td> 45 / 551 </td>\n *  </tr>\n *  <tr>\n *    <td> 6 </td>\n *    <td> 5 / 114 </td>\n *  </tr>\n *  <tr>\n *    <td> 7 </td>\n *    <td> 945 / 40663 </td>\n *  </tr>\n *  <tr>\n *    <td> 8 </td>\n *    <td> 945 / 77432 </td>\n *  </tr>\n * </table>\n */\nclass AdamsBashforthN : public LtsTimeStepper::Inherit {\n public:\n  static constexpr const size_t maximum_order = 8;\n\n  struct Order {\n    using type = size_t;\n    static constexpr Options::String help = {\"Convergence order\"};\n    static type lower_bound() noexcept { return 1; }\n    static type upper_bound() noexcept { return maximum_order; }\n  };\n  using options = tmpl::list<Order>;\n  static constexpr Options::String help = {\n      \"An Adams-Bashforth Nth order time-stepper.\"};\n\n  AdamsBashforthN() = default;\n  explicit AdamsBashforthN(size_t order) noexcept;\n  AdamsBashforthN(const AdamsBashforthN&) noexcept = default;\n  AdamsBashforthN& operator=(const AdamsBashforthN&) noexcept = default;\n  AdamsBashforthN(AdamsBashforthN&&) noexcept = default;\n  AdamsBashforthN& operator=(AdamsBashforthN&&) noexcept = default;\n  ~AdamsBashforthN() noexcept override = default;\n\n  template <typename Vars, typename DerivVars>\n  void update_u(gsl::not_null<Vars*> u,\n                gsl::not_null<History<Vars, DerivVars>*> history,\n                const TimeDelta& time_step) const noexcept;\n\n  template <typename Vars, typename ErrVars, typename DerivVars>\n  bool update_u(gsl::not_null<Vars*> u, gsl::not_null<ErrVars*> u_error,\n                gsl::not_null<History<Vars, DerivVars>*> history,\n                const TimeDelta& time_step) const noexcept;\n\n  template <typename Vars, typename DerivVars>\n  bool dense_update_u(gsl::not_null<Vars*> u,\n                      const History<Vars, DerivVars>& history,\n                      double time) const noexcept;\n\n  // This is defined as a separate type alias to keep the doxygen page\n  // width somewhat under control.\n  template <typename LocalVars, typename RemoteVars, typename Coupling>\n  using BoundaryHistoryType =\n      BoundaryHistory<LocalVars, RemoteVars,\n                      std::result_of_t<const Coupling&(LocalVars, RemoteVars)>>;\n\n  /*!\n   * An explanation of the computation being performed by this\n   * function:\n   * \\f$\\newcommand\\tL{t^L}\\newcommand\\tR{t^R}\\newcommand\\tU{\\tilde{t}\\!}\n   * \\newcommand\\mat{\\mathbf}\\f$\n   *\n   * Suppose the local and remote sides of the interface are evaluated\n   * at times \\f$\\ldots, \\tL_{-1}, \\tL_0, \\tL_1, \\ldots\\f$ and\n   * \\f$\\ldots, \\tR_{-1}, \\tR_0, \\tR_1, \\ldots\\f$, respectively, with\n   * the starting location of the numbering arbitrary in each case.\n   * Let the step we wish to calculate the effect of be the step from\n   * \\f$\\tL_{m_S}\\f$ to \\f$\\tL_{m_S+1}\\f$.  We call the sequence\n   * produced from the union of the local and remote time sequences\n   * \\f$\\ldots, \\tU_{-1}, \\tU_0, \\tU_1, \\ldots\\f$.  For example, one\n   * possible sequence of times is:\n   * \\f{equation}\n   *   \\begin{aligned}\n   *     \\text{Local side:} \\\\ \\text{Union times:} \\\\ \\text{Remote side:}\n   *   \\end{aligned}\n   *   \\cdots\n   *   \\begin{gathered}\n   *     \\, \\\\ \\tU_1 \\\\ \\tR_5\n   *   \\end{gathered}\n   *   \\leftarrow \\Delta \\tU_1 \\rightarrow\n   *   \\begin{gathered}\n   *     \\tL_4 \\\\ \\tU_2 \\\\ \\,\n   *   \\end{gathered}\n   *   \\leftarrow \\Delta \\tU_2 \\rightarrow\n   *   \\begin{gathered}\n   *     \\, \\\\ \\tU_3 \\\\ \\tR_6\n   *   \\end{gathered}\n   *   \\leftarrow \\Delta \\tU_3 \\rightarrow\n   *   \\begin{gathered}\n   *    \\, \\\\ \\tU_4 \\\\ \\tR_7\n   *   \\end{gathered}\n   *   \\leftarrow \\Delta \\tU_4 \\rightarrow\n   *   \\begin{gathered}\n   *     \\tL_5 \\\\ \\tU_5 \\\\ \\,\n   *   \\end{gathered}\n   *   \\cdots\n   * \\f}\n   * We call the indices of the step's start and end times in the\n   * union time sequence \\f$n_S\\f$ and \\f$n_E\\f$, respectively.  We\n   * define \\f$n^L_m\\f$ to be the union-time index corresponding to\n   * \\f$\\tL_m\\f$ and \\f$m^L_n\\f$ to be the index of the last local\n   * time not later than \\f$\\tU_n\\f$ and similarly for the remote\n   * side.  So for the above example, \\f$n^L_4 = 2\\f$ and \\f$m^R_2 =\n   * 5\\f$, and if we wish to compute the step from \\f$\\tL_4\\f$ to\n   * \\f$\\tL_5\\f$ we would have \\f$m_S = 4\\f$, \\f$n_S = 2\\f$, and\n   * \\f$n_E = 5\\f$.\n   *\n   * If we wish to evaluate the change over this step to \\f$k\\f$th\n   * order, we can write the change in the value as a linear\n   * combination of the values of the coupling between the elements at\n   * unequal times:\n   * \\f{equation}\n   *   \\mat{F}_{m_S} =\n   *   \\mspace{-10mu}\n   *   \\sum_{q^L = m_S-(k-1)}^{m_S}\n   *   \\,\n   *   \\sum_{q^R = m^R_{n_S}-(k-1)}^{m^R_{n_E-1}}\n   *   \\mspace{-10mu}\n   *   \\mat{D}_{q^Lq^R}\n   *   I_{q^Lq^R},\n   * \\f}\n   * where \\f$\\mat{D}_{q^Lq^R}\\f$ is the coupling function evaluated\n   * between data from \\f$\\tL_{q^L}\\f$ and \\f$\\tR_{q^R}\\f$.  The\n   * coefficients can be written as the sum of three terms,\n   * \\f{equation}\n   *   I_{q^Lq^R} = I^E_{q^Lq^R} + I^R_{q^Lq^R} + I^L_{q^Lq^R},\n   * \\f}\n   * which can be interpreted as a contribution from equal-time\n   * evaluations and contributions related to the remote and local\n   * evaluation times.  These are given by\n   * \\f{align}\n   *   I^E_{q^Lq^R} &=\n   *   \\mspace{-10mu}\n   *   \\sum_{n=n_S}^{\\min\\left\\{n_E, n^L+k\\right\\}-1}\n   *   \\mspace{-10mu}\n   *   \\tilde{\\alpha}_{n,n-n^L} \\Delta \\tU_n\n   *   &&\\text{if $\\tL_{q^L} = \\tR_{q^R}$, otherwise 0}\n   *   \\\\\n   *   I^R_{q^Lq^R} &=\n   *   \\ell_{q^L - m_S + k}\\!\\left(\n   *     \\tU_{n^R}; \\tL_{m_S - (k-1)}, \\ldots, \\tL_{m_S}\\right)\n   *   \\mspace{-10mu}\n   *   \\sum_{n=\\max\\left\\{n_S, n^R\\right\\}}\n   *       ^{\\min\\left\\{n_E, n^R+k\\right\\}-1}\n   *   \\mspace{-10mu}\n   *   \\tilde{\\alpha}_{n,n-n^R} \\Delta \\tU_n\n   *   &&\\text{if $\\tR_{q^R}$ is not in $\\{\\tL_{\\vphantom{|}\\cdots}\\}$,\n   *     otherwise 0}\n   *   \\\\\n   *   I^L_{q^Lq^R} &=\n   *   \\mspace{-10mu}\n   *   \\sum_{n=\\max\\left\\{n_S, n^R\\right\\}}\n   *       ^{\\min\\left\\{n_E, n^L+k, n^R_{q^R+k}\\right\\}-1}\n   *   \\mspace{-10mu}\n   *   \\ell_{q^R - m^R_n + k}\\!\\left(\\tU_{n^L};\n   *     \\tR_{m^R_n - (k-1)}, \\ldots, \\tR_{m^R_n}\\right)\n   *   \\tilde{\\alpha}_{n,n-n^L} \\Delta \\tU_n\n   *   &&\\text{if $\\tL_{q^L}$ is not in $\\{\\tR_{\\vphantom{|}\\cdots}\\}$,\n   *     otherwise 0,}\n   * \\f}\n   * where for brevity we write \\f$n^L = n^L_{q^L}\\f$ and \\f$n^R =\n   * n^R_{q^R}\\f$, and where \\f$\\ell_a(t; x_1, \\ldots, x_k)\\f$ a\n   * Lagrange interpolating polynomial and \\f$\\tilde{\\alpha}_{nj}\\f$\n   * is the \\f$j\\f$th coefficient for an Adams-Bashforth step over the\n   * union times from step \\f$n\\f$ to step \\f$n+1\\f$.\n   */\n  template <typename LocalVars, typename RemoteVars, typename Coupling>\n  std::result_of_t<const Coupling&(LocalVars, RemoteVars)>\n  compute_boundary_delta(\n      const Coupling& coupling,\n      gsl::not_null<BoundaryHistoryType<LocalVars, RemoteVars, Coupling>*>\n          history,\n      const TimeDelta& time_step) const noexcept;\n\n  template <typename LocalVars, typename RemoteVars, typename Coupling>\n  std::result_of_t<const Coupling&(LocalVars, RemoteVars)>\n  boundary_dense_output(\n      const Coupling& coupling,\n      const BoundaryHistoryType<LocalVars, RemoteVars, Coupling>& history,\n      double time) const noexcept;\n\n  size_t order() const noexcept override;\n\n  size_t error_estimate_order() const noexcept override;\n\n  size_t number_of_past_steps() const noexcept override;\n\n  double stable_step() const noexcept override;\n\n  TimeStepId next_time_id(const TimeStepId& current_id,\n                          const TimeDelta& time_step) const noexcept override;\n\n  template <typename Vars, typename DerivVars>\n  bool can_change_step_size(\n      const TimeStepId& time_id,\n      const TimeSteppers::History<Vars, DerivVars>& history) const noexcept;\n\n  WRAPPED_PUPable_decl_template(AdamsBashforthN);  // NOLINT\n\n  explicit AdamsBashforthN(CkMigrateMessage* /*unused*/) noexcept {}\n\n  // clang-tidy: do not pass by non-const reference\n  void pup(PUP::er& p) noexcept override;  // NOLINT\n\n private:\n  friend bool operator==(const AdamsBashforthN& lhs,\n                         const AdamsBashforthN& rhs) noexcept;\n\n  // Some of the private methods take a parameter of type \"Delta\" or\n  // \"TimeType\".  Delta is expected to be a TimeDelta or an\n  // ApproximateTimeDelta, and TimeType is expected to be a Time or an\n  // ApproximateTime.  The former cases will detect and optimize the\n  // constant-time-step case, while the latter are necessary for dense\n  // output.\n\n  template <typename UpdateVars, typename Vars, typename DerivVars,\n            typename Delta>\n  void update_u_impl(gsl::not_null<UpdateVars*> u,\n                     const History<Vars, DerivVars>& history,\n                     const Delta& time_step, size_t order) const noexcept;\n\n  template <typename LocalVars, typename RemoteVars, typename Coupling,\n            typename TimeType>\n  std::result_of_t<const Coupling&(LocalVars, RemoteVars)> boundary_impl(\n      const Coupling& coupling,\n      const BoundaryHistoryType<LocalVars, RemoteVars, Coupling>& history,\n      const TimeType& end_time) const noexcept;\n\n  /// Get coefficients for a time step.  Arguments are an iterator\n  /// pair to past times, oldest to newest, and the time step to take.\n  template <typename Iterator, typename Delta>\n  static std::vector<double> get_coefficients(const Iterator& times_begin,\n                                              const Iterator& times_end,\n                                              const Delta& step) noexcept;\n\n  static std::vector<double> get_coefficients_impl(\n      const std::vector<double>& steps) noexcept;\n\n  static std::vector<double> variable_coefficients(\n      const std::vector<double>& steps) noexcept;\n\n  static std::vector<double> constant_coefficients(size_t order) noexcept;\n\n  struct ApproximateTimeDelta;\n\n  // Time-like interface to a double used for dense output\n  struct ApproximateTime {\n    double time = std::numeric_limits<double>::signaling_NaN();\n    double value() const noexcept { return time; }\n\n    // Only the operators that are actually used are defined.\n    friend ApproximateTimeDelta operator-(const ApproximateTime& a,\n                                          const Time& b) noexcept {\n      return {a.value() - b.value()};\n    }\n\n    friend bool operator<(const Time& a, const ApproximateTime& b) noexcept {\n      return a.value() < b.value();\n    }\n\n    friend bool operator<(const ApproximateTime& a, const Time& b) noexcept {\n      return a.value() < b.value();\n    }\n\n    friend std::ostream& operator<<(std::ostream& s,\n                                    const ApproximateTime& t) noexcept {\n      return s << t.value();\n    }\n  };\n\n  // TimeDelta-like interface to a double used for dense output\n  struct ApproximateTimeDelta {\n    double delta = std::numeric_limits<double>::signaling_NaN();\n    double value() const noexcept { return delta; }\n    bool is_positive() const noexcept { return delta > 0.; }\n\n    // Only the operators that are actually used are defined.\n    friend bool operator<(const ApproximateTimeDelta& a,\n                          const ApproximateTimeDelta& b) noexcept {\n      return a.value() < b.value();\n    }\n  };\n\n  size_t order_ = 3;\n};\n\nbool operator!=(const AdamsBashforthN& lhs,\n                const AdamsBashforthN& rhs) noexcept;\n\ntemplate <typename Vars, typename DerivVars>\nvoid AdamsBashforthN::update_u(\n    const gsl::not_null<Vars*> u,\n    const gsl::not_null<History<Vars, DerivVars>*> history,\n    const TimeDelta& time_step) const noexcept {\n  ASSERT(history->size() >= history->integration_order(),\n         \"Insufficient data to take an order-\" << history->integration_order()\n         << \" step.  Have \" << history->size() << \" times, need \"\n         << history->integration_order());\n  history->mark_unneeded(\n      history->end() -\n      static_cast<typename decltype(history->end())::difference_type>(\n          history->integration_order()));\n  update_u_impl(u, *history, time_step, history->integration_order());\n}\n\ntemplate <typename Vars, typename ErrVars, typename DerivVars>\nbool AdamsBashforthN::update_u(\n    const gsl::not_null<Vars*> u, const gsl::not_null<ErrVars*> u_error,\n    const gsl::not_null<History<Vars, DerivVars>*> history,\n    const TimeDelta& time_step) const noexcept {\n  ASSERT(history->size() >= history->integration_order(),\n         \"Insufficient data to take an order-\" << history->integration_order()\n         << \" step.  Have \" << history->size() << \" times, need \"\n         << history->integration_order());\n  history->mark_unneeded(\n      history->end() -\n      static_cast<typename decltype(history->end())::difference_type>(\n          history->integration_order()));\n  update_u_impl(u, *history, time_step, history->integration_order());\n  // the error estimate is only useful once the history has enough elements to\n  // do more than one order of step\n  update_u_impl(u_error, *history, time_step, history->integration_order() - 1);\n  *u_error = *u - *u_error;\n  return true;\n}\n\ntemplate <typename Vars, typename DerivVars>\nbool AdamsBashforthN::dense_update_u(const gsl::not_null<Vars*> u,\n                                     const History<Vars, DerivVars>& history,\n                                     const double time) const noexcept {\n  ASSERT(history.integration_order() == order_,\n         \"Dense output is only supported at full order\");\n  const ApproximateTimeDelta time_step{time - history.back().value()};\n  update_u_impl(u, history, time_step, order_);\n  return true;\n}\n\ntemplate <typename UpdateVars, typename Vars, typename DerivVars,\n          typename Delta>\nvoid AdamsBashforthN::update_u_impl(const gsl::not_null<UpdateVars*> u,\n                                    const History<Vars, DerivVars>& history,\n                                    const Delta& time_step,\n                                    const size_t order) const noexcept {\n  ASSERT(\n      history.size() > 0,\n      \"Cannot meaningfully update the evolved variables with an empty history\");\n  ASSERT(order <= order_,\n         \"Requested integration order higher than integrator order\");\n\n  const auto history_start =\n      history.end() -\n      static_cast<typename History<Vars, DerivVars>::difference_type>(order);\n  const auto coefficients =\n      get_coefficients(history_start, history.end(), time_step);\n\n  *u = (history.end() - 1).value();\n  auto coefficient = coefficients.rbegin();\n  for (auto history_entry = history_start;\n       history_entry != history.end();\n       ++history_entry, ++coefficient) {\n    *u += time_step.value() * *coefficient * history_entry.derivative();\n  }\n}\n\ntemplate <typename LocalVars, typename RemoteVars, typename Coupling>\nstd::result_of_t<const Coupling&(LocalVars, RemoteVars)>\nAdamsBashforthN::compute_boundary_delta(\n    const Coupling& coupling,\n    const gsl::not_null<BoundaryHistoryType<LocalVars, RemoteVars, Coupling>*>\n        history,\n    const TimeDelta& time_step) const noexcept {\n  const auto signed_order =\n      static_cast<typename decltype(history->local_end())::difference_type>(\n          history->integration_order());\n\n  ASSERT(history->local_size() >= history->integration_order(),\n         \"Insufficient data to take an order-\" << history->integration_order()\n         << \" step.  Have \" << history->local_size() << \" times, need \"\n         << history->integration_order());\n  history->local_mark_unneeded(history->local_end() - signed_order);\n\n  if (std::equal(history->local_begin(), history->local_end(),\n                 history->remote_end() - signed_order)) {\n    // GTS\n    ASSERT(history->remote_size() >= history->integration_order(),\n           \"Insufficient data to take an order-\" << history->integration_order()\n           << \" step.  Have \" << history->remote_size() << \" times, need \"\n           << history->integration_order());\n    history->remote_mark_unneeded(history->remote_end() - signed_order);\n  } else {\n    const auto remote_step_for_step_start =\n        std::upper_bound(history->remote_begin(), history->remote_end(),\n                         *(history->local_end() - 1),\n                         evolution_less<Time>{time_step.is_positive()});\n    ASSERT(remote_step_for_step_start - history->remote_begin() >= signed_order,\n           \"Insufficient data to take an order-\" << history->integration_order()\n           << \" step.  Have \"\n           << remote_step_for_step_start - history->remote_begin()\n           << \" times before the step, need \" << history->integration_order());\n    history->remote_mark_unneeded(remote_step_for_step_start - signed_order);\n  }\n\n  return boundary_impl(coupling, *history,\n                       *(history->local_end() - 1) + time_step);\n}\n\ntemplate <typename LocalVars, typename RemoteVars, typename Coupling>\nstd::result_of_t<const Coupling&(LocalVars, RemoteVars)>\nAdamsBashforthN::boundary_dense_output(\n    const Coupling& coupling,\n    const BoundaryHistoryType<LocalVars, RemoteVars, Coupling>& history,\n    const double time) const noexcept {\n  return boundary_impl(coupling, history, ApproximateTime{time});\n}\n\ntemplate <typename LocalVars, typename RemoteVars, typename Coupling,\n          typename TimeType>\nstd::result_of_t<const Coupling&(LocalVars, RemoteVars)>\nAdamsBashforthN::boundary_impl(\n    const Coupling& coupling,\n    const BoundaryHistoryType<LocalVars, RemoteVars, Coupling>& history,\n    const TimeType& end_time) const noexcept {\n  // Might be different from order_ during self-start.\n  const auto current_order = history.integration_order();\n\n  ASSERT(current_order <= order_,\n         \"Local history is too long for target order (\" << current_order\n         << \" should not exceed \" << order_ << \")\");\n  ASSERT(history.remote_size() >= current_order,\n         \"Remote history is too short (\" << history.remote_size()\n         << \" should be at least \" << current_order << \")\");\n\n  // Avoid billions of casts\n  const auto order_s = static_cast<typename BoundaryHistoryType<\n      LocalVars, RemoteVars, Coupling>::remote_iterator::difference_type>(\n      current_order);\n\n  // Start and end of the step we are trying to take\n  const Time start_time = *(history.local_end() - 1);\n  const auto time_step = end_time - start_time;\n\n  // Result variable.  We evaluate the coupling only for the\n  // structure.  This evaluation may be expensive, but by choosing the\n  // most recent times on both sides we should guarantee that it is a\n  // result we need later, so this will serve to get it into the\n  // coupling cache so we don't have to compute it when we actually use it.\n  auto accumulated_change =\n      make_with_value<std::result_of_t<const Coupling&(LocalVars, RemoteVars)>>(\n          history.coupling(coupling, history.local_end() - 1,\n                           history.remote_end() - 1),\n          0.);\n\n  // We define the local_begin and remote_begin variables as the start\n  // of the part of the history relevant to this calculation.\n  // Boundary history cleanup happens immediately before the step, but\n  // boundary dense output happens before that, so there may be data\n  // left over that was needed for the previous step and has not been\n  // cleaned out yet.\n  const auto local_begin = history.local_end() - order_s;\n\n  if (std::equal(local_begin, history.local_end(),\n                 history.remote_end() - order_s)) {\n    // No local time-stepping going on.\n    const auto coefficients =\n        get_coefficients(local_begin, history.local_end(), time_step);\n\n    auto local_it = local_begin;\n    auto remote_it = history.remote_end() - order_s;\n    for (auto coefficients_it = coefficients.rbegin();\n         coefficients_it != coefficients.rend();\n         ++coefficients_it, ++local_it, ++remote_it) {\n      accumulated_change +=\n          *coefficients_it * history.coupling(coupling, local_it, remote_it);\n    }\n    accumulated_change *= time_step.value();\n\n    return accumulated_change;\n  }\n\n  ASSERT(current_order == order_,\n         \"Cannot perform local time-stepping while self-starting.\");\n\n  const evolution_less<> less{time_step.is_positive()};\n  const auto remote_begin =\n      std::upper_bound(history.remote_begin(), history.remote_end(),\n                       start_time, less) -\n      order_s;\n\n  ASSERT(std::is_sorted(local_begin, history.local_end(), less),\n         \"Local history not in order\");\n  ASSERT(std::is_sorted(remote_begin, history.remote_end(), less),\n         \"Remote history not in order\");\n  ASSERT(not less(start_time, *(remote_begin + (order_s - 1))),\n         \"Remote history does not extend far enough back\");\n  ASSERT(less(*(history.remote_end() - 1), end_time),\n         \"Please supply only older data: \" << *(history.remote_end() - 1)\n         << \" is not before \" << end_time);\n\n  // Union of times of all step boundaries on any side.\n  const auto union_times = [&history, &local_begin, &remote_begin,\n                            &less]() noexcept {\n    std::vector<Time> ret;\n    ret.reserve(history.local_size() + history.remote_size());\n    std::set_union(local_begin, history.local_end(), remote_begin,\n                   history.remote_end(), std::back_inserter(ret), less);\n    return ret;\n  }();\n\n  using UnionIter = typename decltype(union_times)::const_iterator;\n\n  // Find the union times iterator for a given time.\n  const auto union_step = [&union_times, &less](const Time& t) noexcept {\n    return std::lower_bound(union_times.cbegin(), union_times.cend(), t, less);\n  };\n\n  // The union time index for the step start.\n  const auto union_step_start = union_step(start_time);\n\n  // min(union_times.end(), it + order_s) except being careful not\n  // to create out-of-range iterators.\n  const auto advance_within_step =\n      [order_s, &union_times](const UnionIter& it) noexcept {\n    return union_times.end() - it >\n                   static_cast<typename decltype(union_times)::difference_type>(\n                       order_s)\n               ? it + static_cast<typename decltype(\n                          union_times)::difference_type>(order_s)\n               : union_times.end();\n  };\n\n  // Calculating the Adams-Bashforth coefficients is somewhat\n  // expensive, so we cache them.  ab_coefs(it, step) returns the\n  // coefficients used to step from *it to *it + step.\n  auto ab_coefs = make_overloader(\n      make_cached_function<std::tuple<UnionIter, TimeDelta>,\n                           std::map>([order_s](\n          const std::tuple<UnionIter, TimeDelta>& args) noexcept {\n        return get_coefficients(\n            std::get<0>(args) -\n                static_cast<typename UnionIter::difference_type>(order_s - 1),\n            std::get<0>(args) + 1, std::get<1>(args));\n      }),\n      make_cached_function<std::tuple<UnionIter, ApproximateTimeDelta>,\n                           std::map>([order_s](\n          const std::tuple<UnionIter, ApproximateTimeDelta>& args) noexcept {\n        return get_coefficients(\n            std::get<0>(args) -\n                static_cast<typename UnionIter::difference_type>(order_s - 1),\n            std::get<0>(args) + 1, std::get<1>(args));\n      }));\n\n  // The value of the coefficient of `evaluation_step` when doing\n  // a standard Adams-Bashforth integration over the union times\n  // from `step` to `step + 1`.\n  const auto base_summand = [&ab_coefs, &end_time, &union_times](\n      const UnionIter& step, const UnionIter& evaluation_step) noexcept {\n    if (step + 1 != union_times.end()) {\n      const TimeDelta step_size = *(step + 1) - *step;\n      return step_size.value() *\n             ab_coefs(std::make_tuple(\n                 step, step_size))[static_cast<size_t>(step - evaluation_step)];\n    } else {\n      const auto step_size = end_time - *step;\n      return step_size.value() *\n             ab_coefs(std::make_tuple(\n                 step, step_size))[static_cast<size_t>(step - evaluation_step)];\n    }\n  };\n\n  for (auto local_evaluation_step = local_begin;\n       local_evaluation_step != history.local_end();\n       ++local_evaluation_step) {\n    const auto union_local_evaluation_step = union_step(*local_evaluation_step);\n    for (auto remote_evaluation_step = remote_begin;\n         remote_evaluation_step != history.remote_end();\n         ++remote_evaluation_step) {\n      double deriv_coef = 0.;\n\n      if (*local_evaluation_step == *remote_evaluation_step) {\n        // The two elements stepped at the same time.  This gives a\n        // standard Adams-Bashforth contribution to each segment\n        // making up the current step.\n        const auto union_step_upper_bound =\n            advance_within_step(union_local_evaluation_step);\n        for (auto step = union_step_start;\n             step < union_step_upper_bound;\n             ++step) {\n          deriv_coef += base_summand(step, union_local_evaluation_step);\n        }\n      } else {\n        // In this block we consider a coupling evaluation that is not\n        // performed at equal times on the two sides of the mortar.\n\n        // Makes an iterator with a map to give time as a double.\n        const auto make_lagrange_iterator = [](const auto& it) noexcept {\n          return boost::make_transform_iterator(\n              it, [](const Time& t) noexcept { return t.value(); });\n        };\n\n        const auto union_remote_evaluation_step =\n            union_step(*remote_evaluation_step);\n        const auto union_step_lower_bound =\n            std::max(union_step_start, union_remote_evaluation_step);\n\n        // Compute the contribution to an interpolation over the local\n        // times to `remote_evaluation_step->value()`, which we will\n        // use as the coupling value for that time.  If there is an\n        // actual evaluation at that time then skip this because the\n        // Lagrange polynomial will be zero.\n        if (not std::binary_search(local_begin, history.local_end(),\n                                   *remote_evaluation_step, less)) {\n          const auto union_step_upper_bound =\n              advance_within_step(union_remote_evaluation_step);\n          for (auto step = union_step_lower_bound;\n               step < union_step_upper_bound;\n               ++step) {\n            deriv_coef += base_summand(step, union_remote_evaluation_step);\n          }\n          deriv_coef *=\n              lagrange_polynomial(make_lagrange_iterator(local_evaluation_step),\n                                  remote_evaluation_step->value(),\n                                  make_lagrange_iterator(local_begin),\n                                  make_lagrange_iterator(history.local_end()));\n        }\n\n        // Same qualitative calculation as the previous block, but\n        // interpolating over the remote times.  This case is somewhat\n        // more complicated because the latest remote time that can be\n        // used varies for the different segments making up the step.\n        if (not std::binary_search(remote_begin, history.remote_end(),\n                                   *local_evaluation_step, less)) {\n          auto union_step_upper_bound =\n              advance_within_step(union_local_evaluation_step);\n          if (history.remote_end() - remote_evaluation_step > order_s) {\n            union_step_upper_bound = std::min(\n                union_step_upper_bound,\n                union_step(*(remote_evaluation_step + order_s)));\n          }\n\n          auto control_points = make_lagrange_iterator(\n              remote_evaluation_step - remote_begin >= order_s\n                  ? remote_evaluation_step - (order_s - 1)\n                  : remote_begin);\n          for (auto step = union_step_lower_bound;\n               step < union_step_upper_bound;\n               ++step, ++control_points) {\n            deriv_coef +=\n                base_summand(step, union_local_evaluation_step) *\n                lagrange_polynomial(\n                    make_lagrange_iterator(remote_evaluation_step),\n                    local_evaluation_step->value(), control_points,\n                    control_points +\n                        static_cast<typename decltype(\n                            control_points)::difference_type>(order_s));\n          }\n        }\n      }\n\n      if (deriv_coef != 0.) {\n        // Skip the (potentially expensive) coupling calculation if\n        // the coefficient is zero.\n        accumulated_change +=\n            deriv_coef * history.coupling(coupling, local_evaluation_step,\n                                          remote_evaluation_step);\n      }\n    }  // for remote_evaluation_step\n  }  // for local_evaluation_step\n\n  return accumulated_change;\n}\n\ntemplate <typename Vars, typename DerivVars>\nbool AdamsBashforthN::can_change_step_size(\n    const TimeStepId& time_id,\n    const TimeSteppers::History<Vars, DerivVars>& history) const noexcept {\n  // We need to forbid local time-stepping before initialization is\n  // complete.  The self-start procedure itself should never consider\n  // changing the step size, but we need to wait during the main\n  // evolution until the self-start history has been replaced with\n  // \"real\" values.\n  const evolution_less<Time> less{time_id.time_runs_forward()};\n  return history.size() == 0 or\n         (less(history.back(), time_id.step_time()) and\n          std::is_sorted(history.begin(), history.end(), less));\n}\n\ntemplate <typename Iterator, typename Delta>\nstd::vector<double> AdamsBashforthN::get_coefficients(\n    const Iterator& times_begin, const Iterator& times_end,\n    const Delta& step) noexcept {\n  if (times_begin == times_end) {\n    return {};\n  }\n  std::vector<double> steps;\n  // This may be slightly more space than we need, but we can't get\n  // the exact amount without iterating through the iterators, which\n  // is not necessarily cheap depending on the iterator type.\n  steps.reserve(maximum_order);\n  for (auto t = times_begin; std::next(t) != times_end; ++t) {\n    steps.push_back((*std::next(t) - *t).value());\n  }\n  steps.push_back(step.value());\n  return get_coefficients_impl(steps);\n}\n}  // namespace TimeSteppers\n", "meta": {"hexsha": "4fcbfb74d786b0ffde69aca2efeaba6c622de36a", "size": 31615, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Time/TimeSteppers/AdamsBashforthN.hpp", "max_stars_repo_name": "AntoniRamosBuades/spectre", "max_stars_repo_head_hexsha": "85dbdb5889e6ac7251e37b570495b0a601763ec8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Time/TimeSteppers/AdamsBashforthN.hpp", "max_issues_repo_name": "AntoniRamosBuades/spectre", "max_issues_repo_head_hexsha": "85dbdb5889e6ac7251e37b570495b0a601763ec8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Time/TimeSteppers/AdamsBashforthN.hpp", "max_forks_repo_name": "AntoniRamosBuades/spectre", "max_forks_repo_head_hexsha": "85dbdb5889e6ac7251e37b570495b0a601763ec8", "max_forks_repo_licenses": ["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.2226463104, "max_line_length": 80, "alphanum_fraction": 0.643586905, "num_tokens": 8041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2871522673399509}}
{"text": "/* Copyright 2020 Oinam Romesh Meitei\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 <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n#include <pybind11/eigen.h>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <cmath>\n#include <vector>\n#include \"getham.h\"\n\nnamespace py = pybind11;\n\n\n\nEigen::MatrixXcd solve_func(double &t, std::vector<std::complex<double> > &y,\n\t\t\t    pulsec &pobj,\n\t\t\t    std::vector< std::vector< Eigen::SparseMatrix<double,0,ptrdiff_t> > > &hdrive,\n\t\t\t    std::vector< std::complex<double> > &dsham){\n\n  int dsham_len = dsham.size();\n  Eigen::SparseMatrix<std::complex<double> >\n    matexp_(dsham_len, dsham_len);\n  \n  Eigen::SparseMatrix<std::complex<double> > H =\n    getham(t, pobj, hdrive, dsham, dsham_len, matexp_);\n  \n  Eigen::Map<Eigen::VectorXcd> y_(y.data(), y.size());\n  auto H_ = std::complex<double>(0.0,-1.0) * H * y_;\n  return H_;\n}\n\n\n\nPYBIND11_MODULE(solve,m){\n  m.def(\"solve_func\", &solve_func, \"solve_func \");\n  py::class_<pulsec>(m, \"pulsec\")\n    .def(py::init<\n         std::vector< std::vector< double > > &,\n         std::vector< std::vector< double > > &,\n         std::vector< double > &, double &, int &,\n         int & > ())\n    .def_readonly(\"amp\", &pulsec::amp)\n    .def_readonly(\"tseq\", &pulsec::tseq)\n    .def_readonly(\"freq\", &pulsec::freq)\n    .def_readonly(\"duration\", &pulsec::duration)\n    .def_readonly(\"nqubit\", &pulsec::nqubit)\n    .def_readonly(\"nwindow\", &pulsec::nwindow);\n}\n", "meta": {"hexsha": "24cff8cab067001572262321d7319100897497ee", "size": 1985, "ext": "cc", "lang": "C++", "max_stars_repo_path": "ctrlq/lib/solve.cc", "max_stars_repo_name": "asthanaa/ctrlq", "max_stars_repo_head_hexsha": "4af7721ed679a1ac2d4147a9406fa794f2af64d8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-09-25T14:50:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T17:36:53.000Z", "max_issues_repo_path": "ctrlq/lib/solve.cc", "max_issues_repo_name": "asthanaa/ctrlq", "max_issues_repo_head_hexsha": "4af7721ed679a1ac2d4147a9406fa794f2af64d8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-21T18:54:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-21T18:54:38.000Z", "max_forks_repo_path": "ctrlq/lib/solve.cc", "max_forks_repo_name": "asthanaa/ctrlq", "max_forks_repo_head_hexsha": "4af7721ed679a1ac2d4147a9406fa794f2af64d8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-18T18:19:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-26T13:48:44.000Z", "avg_line_length": 31.015625, "max_line_length": 85, "alphanum_fraction": 0.6685138539, "num_tokens": 582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.28710070666653087}}
{"text": "/*\nCopyright 2009-2021 Nicolas Colombe\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 <math/seginter.hpp>\n#include <math/mathtools.hpp>\n#include <boost/optional.hpp>\n\nnamespace eXl\n{\n  Intersector::Event::Event(PooledList<uint32_t>::Pool& iPool, Vector2Q const& iPoint, uint32_t iSeg, Type iType)\n    : m_SegmentsStart(iPool)\n    , m_SegmentsInter(iPool)\n    , m_SegmentsEnd(iPool)\n    , m_Point(iPoint)\n  {\n    if(iType == Start)\n    {\n      m_SegmentsStart.PushBack(iSeg);\n    }\n    else if (iType == End)\n    {\n      m_SegmentsEnd.PushBack(iSeg);\n    }\n  }\n\n  Intersector::Event::Event(PooledList<uint32_t>::Pool& iPool, Vector2Q const& iPoint, uint32_t iSeg1, uint32_t iSeg2)\n    : m_SegmentsStart(iPool)\n    , m_SegmentsInter(iPool)\n    , m_SegmentsEnd(iPool)\n    , m_Point(iPoint)\n  {\n    m_SegmentsInter.PushBack(iSeg1);\n    m_SegmentsInter.PushBack(iSeg2);\n  }\n\n  Intersector::Event::Event(Event const& iEvt)\n    : m_SegmentsStart(iEvt.m_SegmentsStart)\n    , m_SegmentsInter(iEvt.m_SegmentsInter)\n    , m_SegmentsEnd(iEvt.m_SegmentsEnd)\n    , m_Point(iEvt.m_Point)\n  {\n\n  }\n\n  Intersector::Event& Intersector::Event::operator=(Event const& iEvt)\n  {\n    m_SegmentsStart = iEvt.m_SegmentsStart;\n    m_SegmentsInter = iEvt.m_SegmentsInter;\n    m_SegmentsEnd = iEvt.m_SegmentsEnd;\n    m_Point = iEvt.m_Point;\n\n    return *this;\n  }\n\n  Intersector::Event::Event(Event&& iEvt)\n    : m_SegmentsStart(std::move(iEvt.m_SegmentsStart))\n    , m_SegmentsInter(std::move(iEvt.m_SegmentsInter))\n    , m_SegmentsEnd(std::move(iEvt.m_SegmentsEnd))\n    , m_Point(iEvt.m_Point)\n  {\n\n  }\n\n  Intersector::Event& Intersector::Event::operator=(Event&& iEvt)\n  {\n    m_SegmentsStart = std::move(iEvt.m_SegmentsStart);\n    m_SegmentsInter = std::move(iEvt.m_SegmentsInter);\n    m_SegmentsEnd = std::move(iEvt.m_SegmentsEnd);\n    m_Point = iEvt.m_Point;\n\n    return *this;\n  }\n\n  bool Intersector::Event::IsEmpty() const\n  {\n    return m_SegmentsStart.Begin() == m_SegmentsStart.End() \n      && m_SegmentsEnd.Begin() == m_SegmentsEnd.End() \n      && m_SegmentsInter.Begin() == m_SegmentsInter.End();\n  }\n\n\n  bool Intersector::Event::operator<(Event const& iOther) const\n  {\n    return m_Point < iOther.m_Point;\n  }\n\n  Intersector::OrderedSeg::OrderedSeg(Segmenti const& iSeg, uint32_t iOrigSeg)\n    : m_Start(ToVec2Q(iSeg.m_Ext1))\n    , m_End(ToVec2Q(iSeg.m_Ext2))\n    , m_OrigSeg(iOrigSeg)\n  {\n    if(iSeg.m_Ext2 < iSeg.m_Ext1)\n    {\n      std::swap(m_Start, m_End);\n    }\n    if(m_End.X() != m_Start.X())\n    {\n      m_Slope = QType(m_End.Y() - m_Start.Y()) / QType(m_End.X() - m_Start.X());\n    }\n  }\n\n  QType Intersector::OrderedSeg::GetYAt(QType iX, Event const& iEvt) const\n  {\n    if(m_Slope)\n    {\n      return m_Start.Y() + (*m_Slope) * (iX - m_Start.X());\n    }\n    else\n    {\n      return iEvt.m_Point.Y();\n    }\n  }\n\n  bool Intersector::CheckIntersection(Event const& iEvt, OrderedSeg const& iSeg1, OrderedSeg const& iSeg2, boost::optional<Event>& outSeg)\n  {\n    uint32_t seg1Idx = &iSeg1 - m_Segments.data();\n    uint32_t seg2Idx = &iSeg2 - m_Segments.data();\n\n    Vector2Q interPt;\n    uint32_t res = Segment<QType>::Intersect(iSeg1.m_Start, iSeg1.m_End, iSeg2.m_Start, iSeg2.m_End, interPt, 0);\n    if(res == Segment<QType>::PointOnSegments)\n    {\n      if(iEvt.m_Point < interPt || iEvt.m_Point == interPt)\n      {\n        outSeg = Event(m_SegListPool, interPt, seg1Idx, seg2Idx);\n      }\n    }\n    else if(res & Segment<QType>::ConfoundSegments)\n    {\n      //eXl_ASSERT(iEvt.m_Type == Event::Start);\n\n      if(iSeg1.m_End.m_X > iSeg2.m_End.m_X)\n      {\n        //Reinsert seg1's start at seg2's end.\n        Event newStart(m_SegListPool, iSeg2.m_End, seg1Idx, Event::Start);\n        auto lowerBound = std::lower_bound(m_EventQueue.rbegin(), m_EventQueue.rend(), newStart);\n        if(lowerBound->m_Point == iSeg2.m_End)\n        {\n          lowerBound->m_SegmentsStart.PushBack(seg1Idx);\n        }\n        else\n        {\n          m_EventQueue.insert(lowerBound.base(), std::move(newStart));\n        }\n        \n        //m_EventQueue.emplace(std::move(newStart));\n      }\n      else if(iSeg1.m_End != iEvt.m_Point)\n      {\n        //Seg1 is useless, remove it.\n        Event evt(m_SegListPool, iSeg1.m_End, seg1Idx, Event::End);\n        auto toFixup = std::lower_bound(m_EventQueue.rbegin(), m_EventQueue.rend(), evt);\n\n        // remove iSeg1's endpoint from the list.\n        auto iterToRemove = std::prev(toFixup.base());\n        auto endingSegs = iterToRemove->m_SegmentsEnd.Begin();\n        while(*endingSegs != seg1Idx)\n        {\n          ++endingSegs;\n        }\n\n        //eXl_ASSERT(endingSegs != iterToRemove->m_SegmentsEnd.End());\n        iterToRemove->m_SegmentsEnd.Erase(endingSegs);\n\n        if(iterToRemove->IsEmpty())\n        {\n          m_EventQueue.erase(iterToRemove);\n        }\n      }\n\n      for (auto iter = m_ActiveSegments.begin(); iter != m_ActiveSegments.end(); ++iter)\n      {\n        if (iter->m_Idx == seg1Idx)\n        {\n          m_ActiveSegments.erase(iter);\n          break;\n        }\n      }\n\n      return false;\n    }\n\n    return true;\n  }\n\n  void Intersector::InsertEvent(Event&& iEvt)\n  {\n    //for(auto iter = iEvt.m_Segments.Begin(); iter != iEvt.m_Segments.End(); ++iter)\n    //{\n    //  ++m_SegInsertCount[*iter];\n    //}\n\n    auto lowerBound = std::lower_bound(m_EventQueue.rbegin(), m_EventQueue.rend(), iEvt);\n    //auto lowerBound = m_EventQueue.find(iEvt);\n    if(lowerBound != m_EventQueue.rend() \n      //lowerBound != m_EventQueue.end()\n      //&& lowerBound->m_Type == Event::Intersection \n      && lowerBound->m_Point == iEvt.m_Point\n      )\n    {\n      for(auto startSegIter = iEvt.m_SegmentsStart.Begin(); startSegIter != iEvt.m_SegmentsStart.End(); ++startSegIter )\n      {\n        lowerBound->m_SegmentsStart.PushBack(*startSegIter);\n      }\n      for(auto endSegIter = iEvt.m_SegmentsEnd.Begin(); endSegIter != iEvt.m_SegmentsEnd.End(); ++endSegIter )\n      {\n        lowerBound->m_SegmentsEnd.PushBack(*endSegIter);\n      }\n      for(auto interSegIter = iEvt.m_SegmentsInter.Begin(); interSegIter != iEvt.m_SegmentsInter.End(); ++interSegIter )\n      {\n        lowerBound->m_SegmentsInter.PushBack(*interSegIter);\n      }\n    }\n    else\n    {\n      m_EventQueue.insert(lowerBound.base(), std::move(iEvt));\n      //m_EventQueue.emplace(std::move(iEvt));\n    }\n    \n  }\n\n  void Intersector::CheckIntersection(Event const& iEvt, OrderedSeg const& iSeg1, OrderedSeg const& iSeg2)\n  {\n    boost::optional<Event> evt;\n    CheckIntersection(iEvt, iSeg1, iSeg2, evt);\n    if(evt && evt->m_Point != iEvt.m_Point)\n    {\n      InsertEvent(std::move(*evt));\n    }\n  }\n\n  void Intersector::RemoveEvt(uint32_t iSeg1, uint32_t iSeg2)\n  {\n    if(iSeg1 != iSeg2)\n    {\n      //if(m_SegInsertCount[iSeg1] == 0 || m_SegInsertCount[iSeg2] == 0)\n      //{\n      //  return;\n      //}\n\n      for(auto iter = m_EventQueue.begin(); iter!= m_EventQueue.end(); ++iter)\n      {\n        uint32_t countSeg = 0;\n        PooledList<uint32_t>::Iterator segs[] = {iter->m_SegmentsInter.End(), iter->m_SegmentsInter.End()};\n        for(auto iterSeg = iter->m_SegmentsInter.Begin(); iterSeg != iter->m_SegmentsInter.End(); ++iterSeg)\n        {\n          ++countSeg;\n          if(*iterSeg == iSeg1 && segs[0] == iter->m_SegmentsInter.End())\n          {\n            segs[0] = iterSeg;\n          } \n          if(*iterSeg == iSeg2 && segs[1] == iter->m_SegmentsInter.End())\n          {\n            segs[1] = iterSeg;\n          }\n        }\n\n        if(segs[0] != iter->m_SegmentsInter.End()\n          && segs[1] != iter->m_SegmentsInter.End())\n        {\n          if(iter->IsEmpty())\n          {\n            m_EventQueue.erase(iter);\n          }\n          else\n          {\n            iter->m_SegmentsInter.Erase(segs[0]);\n            iter->m_SegmentsInter.Erase(segs[1]);\n          }\n          //m_SegInsertCount[iSeg1]--;\n          //m_SegInsertCount[iSeg2]--;\n\n          break;\n        }\n      }\n    }\n  };\n\n  Intersector::Intersector()\n    //: m_EvtListAlloc(4096)\n    //, m_EventQueue(std::less<Event>(), PooledAllocator<Event>(m_EvtListAlloc))\n  {\n\n  }\n\n  void Intersector::SortSegmentExtremities()\n  {\n    for(auto& evt : m_EventQueue)\n    {\n      auto sortPredicate = [&] (uint32_t const& iSeg1, uint32_t const& iSeg2)\n      {\n        auto const& seg1 = m_Segments[iSeg1];\n        auto const& seg2 = m_Segments[iSeg2];\n\n        if(seg1.m_Slope)\n        {\n          if(seg2.m_Slope)\n          {\n            return *seg1.m_Slope < *seg2.m_Slope;\n          }\n        }\n\n        return seg2.m_Slope && !seg1.m_Slope;\n\n      };\n\n      m_SortArray.clear();\n      for(auto startSegIter = evt.m_SegmentsStart.Begin(); startSegIter != evt.m_SegmentsStart.End(); ++startSegIter )\n      {\n        m_SortArray.push_back(*startSegIter);\n      }\n      evt.m_SegmentsStart.Clear();\n\n      std::sort(m_SortArray.begin(), m_SortArray.end(), sortPredicate);\n\n      for(uint32_t segIdx : m_SortArray)\n      {\n        evt.m_SegmentsStart.PushBack(segIdx);\n      }\n\n      m_SortArray.clear();\n      for(auto endSegIter = evt.m_SegmentsEnd.Begin(); endSegIter != evt.m_SegmentsEnd.End(); ++endSegIter )\n      {\n        m_SortArray.push_back(*endSegIter);\n      }\n      evt.m_SegmentsEnd.Clear();\n\n      std::sort(m_SortArray.begin(), m_SortArray.end(), sortPredicate);\n\n      for(uint32_t segIdx : m_SortArray)\n      {\n        evt.m_SegmentsEnd.PushBack(segIdx);\n      }\n\n    }\n  }\n\n  Err Intersector::IntersectSegments(Vector<Segmenti> const& iSegments, Vector<std::pair<uint32_t, Segmenti>>& oSegs, Parameters const& iParams)\n  {\n    //m_EventQueue.~EventQueue();\n    //m_EvtListAlloc.Reset();\n    //new(&m_EventQueue) EventQueue(std::less<Event>(), PooledAllocator<Event>(m_EvtListAlloc));\n    //m_SegListPool.Reserve(1024);\n\n    m_EventQueue.clear();\n    m_Segments.clear();\n    m_ActiveSegments.clear();\n    m_SegInsertCount.clear();\n\n    {\n      uint32_t segCounter = 0;\n      for(auto const& seg : iSegments)\n      {\n        if(seg.m_Ext1 != seg.m_Ext2)\n        {\n          m_Segments.push_back(OrderedSeg(seg, segCounter++));\n\n          //m_EventQueue.emplace_back(Event(m_SegListPool, m_Segments.back().m_Start, m_Segments.size() - 1, Event::Start));\n          //m_EventQueue.emplace_back(Event(m_SegListPool, m_Segments.back().m_End, m_Segments.size() - 1, Event::End));\n\n          InsertEvent(Event(m_SegListPool, m_Segments.back().m_Start, m_Segments.size() - 1, Event::Start));\n          InsertEvent(Event(m_SegListPool, m_Segments.back().m_End, m_Segments.size() - 1, Event::End));\n\n          //m_EventQueue.emplace(Event(m_SegListPool, m_Segments.back().m_Start, m_Segments.size() - 1, Event::Start));\n          //m_EventQueue.emplace(Event(m_SegListPool, m_Segments.back().m_End, m_Segments.size() - 1, Event::End));\n\n          //m_SegInsertCount.push_back(0);\n        }\n      }\n      //if(iParams.m_UsrEvtCb)\n      //{\n      //  for(uint32_t pos = 0; pos < iParams.m_UsrEvts.size(); ++pos)\n      //  {\n      //    m_EventQueue.emplace_back(Event(m_SegListPool, ToVec2Q(iParams.m_UsrEvts[pos].m_Position), pos, Event::User));\n      //  }\n      //}\n\n      //std::sort(m_EventQueue.begin(), m_EventQueue.end());\n    }\n\n    //std::reverse(m_EventQueue.begin(), m_EventQueue.end());\n\n    SortSegmentExtremities();\n\n    while(!m_EventQueue.empty())\n    {\n      Event curEvt = std::move(m_EventQueue.back());\n      m_EventQueue.pop_back();\n\n      //Event curEvt = *m_EventQueue.begin();\n      //m_EventQueue.erase(m_EventQueue.begin());\n\n      auto curX = curEvt.m_Point.X();\n\n      auto activeSegComp = [this, curX, &curEvt](ActiveSegment const& iSeg1, ActiveSegment const& iSeg2)\n      {\n        auto const& seg1 = m_Segments[iSeg1.m_Idx];\n        auto const& seg2 = m_Segments[iSeg2.m_Idx];\n\n        auto y1 = seg1.GetYAt(curX, curEvt);\n        auto y2 = seg2.GetYAt(curX, curEvt);\n\n        if(y1 != y2)\n        {\n          return y1 < y2;\n        }\n        else\n        {\n          if(seg1.m_Slope)\n          {\n            if(seg2.m_Slope)\n            {\n              return *seg1.m_Slope < *seg2.m_Slope;\n            }\n            return true;\n          }\n          return false;\n          \n        }\n      };\n\n      //if(curEvt.m_Type == Event::Intersection)\n      //{\n      //  for(auto iter = curEvt.m_Segments.Begin(); iter != curEvt.m_Segments.End(); ++iter)\n      //  {\n      //    --m_SegInsertCount[*iter];\n      //  }\n      //}\n\n      //switch(curEvt.m_Type)\n      {\n\n      //case Event::Intersection:\n      if(curEvt.m_SegmentsInter.Begin() != curEvt.m_SegmentsInter.End())\n      {\n        //Set<uint32_t> checkSet;\n        int32_t posLow = INT_MAX;\n        int32_t posHigh = -INT_MAX;\n\n        for(auto iter = curEvt.m_SegmentsInter.Begin(); iter != curEvt.m_SegmentsInter.End(); ++iter)\n        {\n          for(int32_t i = 0; i<m_ActiveSegments.size(); ++i)\n          {\n            if(m_ActiveSegments[i].m_Idx == *iter)\n            {\n              if(i < posLow)\n              {\n                posLow = i;\n              }\n              if(i > posHigh)\n              {\n                posHigh = i;\n              }\n              //checkSet.insert(i);\n              break;\n            }\n          }\n        }\n        //if(checkSet.size() != (posHigh - posLow) + 1)\n        //{\n        //  //eXl_ASSERT(false);\n        //  return Err::Failure;\n        //}\n        if(!(posLow < m_ActiveSegments.size() && posHigh > posLow))\n        {\n          //eXl_ASSERT(false);\n          return Err::Failure;\n        }\n\n        for(int32_t i = posLow; i<=posHigh; ++i)\n        {\n          ActiveSegment& activeSeg = m_ActiveSegments[i];\n\n          if(activeSeg.m_Point != curEvt.m_Point)\n          {\n            if(!iParams.m_Filter || iParams.m_Filter(m_ActiveSegments, i, Segment<QType>{activeSeg.m_Point, curEvt.m_Point} ))\n            {\n              Segmenti interSeg = {FromVec2Q<int>(activeSeg.m_Point), FromVec2Q<int>(curEvt.m_Point)};\n              oSegs.push_back(std::make_pair(activeSeg.m_Idx, interSeg));\n            }\n            activeSeg.m_Point = curEvt.m_Point;\n          }\n        }\n\n        std::reverse(m_ActiveSegments.begin() + posLow, m_ActiveSegments.begin() + posHigh + 1);\n\n        //Order is reversed now.\n        uint32_t lowSegIdx = m_ActiveSegments[posLow].m_Idx;\n        uint32_t highSegIdx = m_ActiveSegments[posHigh].m_Idx;\n        auto const& lowSeg = m_Segments[lowSegIdx];\n        auto const& highSeg = m_Segments[highSegIdx];\n\n        if(posHigh + 1 < m_ActiveSegments.size()) \n        {\n          uint32_t higherSegIdx = m_ActiveSegments[posHigh + 1].m_Idx;\n\n          auto const& higherSeg = m_Segments[higherSegIdx];\n          CheckIntersection(curEvt, highSeg, higherSeg);\n          RemoveEvt(higherSegIdx, lowSegIdx);\n        }\n        if(posLow > 0) \n        {\n          uint32_t lowerSegIdx = m_ActiveSegments[posLow - 1].m_Idx;\n\n          auto const& lowerSeg = m_Segments[lowerSegIdx];\n          CheckIntersection(curEvt, lowSeg, lowerSeg);\n          RemoveEvt(highSegIdx, lowerSegIdx);\n        }\n      }\n\n      //case Event::End:\n      for(auto iterEnd = curEvt.m_SegmentsEnd.Begin(); iterEnd != curEvt.m_SegmentsEnd.End(); ++iterEnd)\n      {\n        uint32_t curSegIdx = *iterEnd;\n        auto const& curSeg = m_Segments[curSegIdx];\n\n        //ActiveSegment activeSeg = {curEvt.m_Point, curSegIdx};\n\n        //auto lowerBound = std::lower_bound(m_ActiveSegments.begin(), m_ActiveSegments.end(), activeSeg, activeSegComp);\n        int32_t curSegPos = -1;\n\n        for(auto& seg : m_ActiveSegments)\n        {\n          if(seg.m_Idx == curSegIdx)\n          {\n            curSegPos = &seg - m_ActiveSegments.data();\n          }\n        }\n\n        if(curSegPos == -1)\n        {\n          //eXl_ASSERT(false);\n          return Err::Failure;\n        }\n\n        //Segmenti finalSeg = {FromVec2Q<int>(m_ActiveSegments[curSegPos].m_Point), FromVec2Q<int>(curEvt.m_Point)};\n        if(m_ActiveSegments[curSegPos].m_Point != curEvt.m_Point)\n        {\n          if(!(iParams.m_Filter) || iParams.m_Filter(m_ActiveSegments, curSegPos, Segment<QType>{m_ActiveSegments[curSegPos].m_Point, curEvt.m_Point}))\n          {\n            Segmenti finalSeg = {FromVec2Q<int>(m_ActiveSegments[curSegPos].m_Point), FromVec2Q<int>(curEvt.m_Point)};\n            oSegs.push_back(std::make_pair(curSegIdx, finalSeg));\n          }\n        }\n\n        m_ActiveSegments.erase(m_ActiveSegments.begin() + curSegPos);\n\n        int32_t lowerSegIdx = -1;\n        int32_t higherSegIdx = -1;\n\n        if(curSegPos > 0) \n        {\n          lowerSegIdx = m_ActiveSegments[curSegPos - 1].m_Idx;\n        }\n        if(curSegPos < m_ActiveSegments.size()) \n        {\n          higherSegIdx = m_ActiveSegments[curSegPos].m_Idx;\n        }\n\n        if(lowerSegIdx != -1 && higherSegIdx != -1) \n        {\n          auto const& lowerSeg = m_Segments[lowerSegIdx];\n          auto const& higherSeg = m_Segments[higherSegIdx];\n\n          CheckIntersection(curEvt, lowerSeg, higherSeg);\n        }\n      }\n\n      //case Event::Start:\n      for(auto iterStart = curEvt.m_SegmentsStart.Begin(); iterStart != curEvt.m_SegmentsStart.End(); ++iterStart)\n      {\n        uint32_t curSegIdx = *iterStart;\n        auto const& curSeg = m_Segments[curSegIdx];\n\n        ActiveSegment newSeg = {curEvt.m_Point, curSegIdx};\n\n        auto lowerBound = std::lower_bound(m_ActiveSegments.begin(), m_ActiveSegments.end(), newSeg, activeSegComp);\n\n        int32_t lowerSegIdx = -1;\n        int32_t higherSegIdx = -1;\n\n        boost::optional<Event> evts[2];\n\n        bool acceptSegment = true;\n\n        if(lowerBound > m_ActiveSegments.begin())\n        {\n          lowerSegIdx = (lowerBound - 1)->m_Idx;\n          auto const& lowerSeg = m_Segments[lowerSegIdx];\n\n          acceptSegment &= CheckIntersection(curEvt, curSeg, lowerSeg, evts[0]);\n        }\n        if(lowerBound != m_ActiveSegments.end())\n        {\n          higherSegIdx = lowerBound->m_Idx;\n          auto const& higherSeg = m_Segments[higherSegIdx];\n\n          acceptSegment &= CheckIntersection(curEvt, curSeg, higherSeg, evts[1]);\n        }\n\n        if(acceptSegment)\n        {\n          for(auto& optEvt : evts)\n          {\n            if(optEvt)\n            {\n              if(optEvt->m_Point != curEvt.m_Point)\n              {\n                InsertEvent(std::move(*optEvt));\n              }\n              else\n              {\n                ActiveSegment* activeSeg = nullptr;\n                // Only report event.\n                for(auto iterSeg = optEvt->m_SegmentsInter.Begin(); iterSeg != optEvt->m_SegmentsInter.End(); ++iterSeg)\n                {\n                  uint32_t segIdx = *iterSeg;\n                  if(segIdx == curSegIdx)\n                    continue;\n\n                  for(auto& seg : m_ActiveSegments)\n                  {\n                    if(seg.m_Idx == segIdx)\n                    {\n                      activeSeg = &seg;\n                      break;\n                    }\n                  }\n\n                  //eXl_ASSERT(activeSeg);\n\n                  if(activeSeg->m_Point != curEvt.m_Point)\n                  {\n                    if(!iParams.m_Filter || iParams.m_Filter(m_ActiveSegments, activeSeg - m_ActiveSegments.data(), Segment<QType>{activeSeg->m_Point, curEvt.m_Point}))\n                    {\n                      Segmenti interSeg = {FromVec2Q<int>(activeSeg->m_Point), FromVec2Q<int>(curEvt.m_Point)};\n                      oSegs.push_back(std::make_pair(activeSeg->m_Idx, interSeg));\n                    }\n                    activeSeg->m_Point = curEvt.m_Point;\n                  }\n                }\n              }\n            }\n          }\n\n          m_ActiveSegments.insert(lowerBound, newSeg);\n\n          if(lowerSegIdx != -1 && higherSegIdx != -1)\n          {\n            // Only remove the event when the three segments do not intersect at the same point.\n            if(!evts[0] \n              || !evts[1] \n              || evts[0]->m_Point != evts[1]->m_Point)\n            {\n              RemoveEvt(lowerSegIdx, higherSegIdx);\n            }\n          }\n        }\n      }\n      \n      /*\n      case Event::User:\n      {\n        auto userPtComp = [this, curX, &curEvt](ActiveSegment const& iSeg1, ActiveSegment const& iSeg2)\n        {\n          auto const& seg = m_Segments[iSeg1.m_Idx == -1 ? iSeg2.m_Idx : iSeg1.m_Idx];\n          \n          auto y1 = seg.GetYAt(curX, curEvt);\n          \n          return y1 < curEvt.m_Point.Y();\n        };\n\n        ActiveSegment dummySeg = {curEvt.m_Point, -1};\n        auto lowerBound = std::lower_bound(m_ActiveSegments.begin(), m_ActiveSegments.end(), dummySeg, userPtComp);\n\n        int32_t lowSeg = -1;\n        int32_t highSeg = -1;\n\n        if(lowerBound != m_ActiveSegments.begin())\n        {\n          lowSeg = (lowerBound - 1) - m_ActiveSegments.begin();\n        }\n\n        if(lowerBound != m_ActiveSegments.end())\n        {\n          highSeg = lowerBound - m_ActiveSegments.begin();\n        }\n\n        iParams.m_UsrEvtCb(m_ActiveSegments, lowSeg, highSeg, iParams.m_UsrEvts[*curEvt.m_Segments.Begin()]);\n\n        break;\n      }*/\n      \n      }\n    }\n\n    return Err::Success;\n  }\n}", "meta": {"hexsha": "679a48563b85767dad81682de0e4a7b1f69a1137", "size": 22039, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/seginter.cpp", "max_stars_repo_name": "eXl-Nic/eXl", "max_stars_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/math/seginter.cpp", "max_issues_repo_name": "eXl-Nic/eXl", "max_issues_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/seginter.cpp", "max_forks_repo_name": "eXl-Nic/eXl", "max_forks_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_forks_repo_licenses": ["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.216713881, "max_line_length": 460, "alphanum_fraction": 0.5847815237, "num_tokens": 5992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2871007066665308}}
{"text": "/*ckwg +29\n * Copyright 2015 by Kitware, 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 *  * 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 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 name of Kitware, Inc. nor the names of any contributors may be used\n *    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''\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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR\n * 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/**\n * \\file\n * \\brief core homography template implementations\n */\n\n#include \"homography.h\"\n\n#include <cmath>\n\n#include <maptk/exceptions/math.h>\n#include <maptk/logging_macros.h>\n\n#include <Eigen/LU>\n\n\nnamespace maptk\n{\n\nnamespace //anonymous\n{\n\n/// Private helper method for point transformation via homography matrix\ntemplate <typename T>\nEigen::Matrix<T,2,1>\nh_map_point( Eigen::Matrix<T,3,3> const &h, Eigen::Matrix<T,2,1> const &p )\n{\n  Eigen::Matrix<T,3,1> out_pt = h * Eigen::Matrix<T,3,1>(p[0], p[1], 1.0);\n  if( fabs(out_pt[2]) <= Eigen::NumTraits<T>::dummy_precision() )\n  {\n    throw point_maps_to_infinity();\n  }\n  return Eigen::Matrix<T,2,1>( out_pt[0] / out_pt[2], out_pt[1] / out_pt[2] );\n}\n\n} // end anonymous namespace\n\n\n/// Construct an identity homography\ntemplate <typename T>\nhomography_<T>\n::homography_()\n  : h_( matrix_t::Identity() )\n{\n}\n\n/// Construct from a provided transformation matrix\ntemplate <typename T>\nhomography_<T>\n::homography_( Eigen::Matrix<T,3,3> const &mat )\n  : h_( mat )\n{\n}\n\n/// Conversion Copy constructor -- float specialization\ntemplate <>\ntemplate <>\nhomography_<float>\n::homography_( homography_<float> const &other )\n  : h_( other.get_matrix() )\n{\n}\n\n/// Conversion Copy constructor -- double specialization\ntemplate <>\ntemplate <>\nhomography_<double>\n::homography_( homography_<double> const &other )\n  : h_( other.get_matrix() )\n{\n}\n\n/// Construct from a generic homography\ntemplate <typename T>\nhomography_<T>\n::homography_( homography const &base )\n  : h_( base.matrix().template cast<T>() )\n{\n}\n\n/// Construct from a generic homography -- double specialization\ntemplate <>\nhomography_<double>\n::homography_( homography const &base )\n  : h_( base.matrix() )\n{\n}\n\n/// Create a clone of outself as a shared pointer\ntemplate <typename T>\nhomography_sptr\nhomography_<T>\n::clone() const\n{\n  return homography_sptr( new homography_<T>( *this ) );\n}\n\n/// Get a double-typed copy of the underlying matrix transformation\ntemplate <typename T>\nEigen::Matrix<double,3,3>\nhomography_<T>\n::matrix() const\n{\n  return this->h_.template cast<double>();\n}\n\n/// Specialization for homographies with native double type\ntemplate <>\nEigen::Matrix<double,3,3>\nhomography_<double>\n::matrix() const\n{\n  return this->h_;\n}\n\n/// Normalize homography transformation in-place\ntemplate <typename T>\nhomography_sptr\nhomography_<T>\n::normalize() const\n{\n  matrix_t norm = this->get_matrix();\n  if( fabs(norm(2,2)) >= Eigen::NumTraits<T>::dummy_precision() )\n  {\n    norm /= norm(2,2);\n  }\n  return homography_sptr( new homography_<T>( norm ) );\n}\n\n/// Inverse the homography transformation returning a new transformation\ntemplate <typename T>\nhomography_sptr\nhomography_<T>\n::inverse() const\n{\n  matrix_t inv;\n  bool isvalid;\n  this->h_.computeInverseWithCheck( inv, isvalid );\n  if( !isvalid )\n  {\n    throw non_invertible_matrix();\n  }\n  return homography_sptr( new homography_<T>( inv ) );\n}\n\n/// Map a 2D double-type point using this homography\ntemplate <typename T>\nEigen::Matrix<double,2,1>\nhomography_<T>\n::map( Eigen::Matrix<double,2,1> const &p ) const\n{\n  // Explicitly refer to templated version of method so as to not infinitely\n  // recurse.\n  Eigen::Matrix<double,3,3> m = h_.template cast<double>();\n  return h_map_point( m, p );\n}\n\n/// Map a 2D double-type point using this homography -- double specialization\ntemplate <>\nEigen::Matrix<double,2,1>\nhomography_<double>\n::map( Eigen::Matrix<double,2,1> const &p ) const\n{\n  return h_map_point( h_, p );\n}\n\n/// Get the underlying matrix transformation\ntemplate <typename T>\ntypename homography_<T>::matrix_t&\nhomography_<T>\n::get_matrix()\n{\n  return this->h_;\n}\n\n/// Get a const new copy of the underlying matrix transformation.\ntemplate <typename T>\ntypename homography_<T>::matrix_t const&\nhomography_<T>\n::get_matrix() const\n{\n  return this->h_;\n}\n\n/// Map a 2D point using this homography -- generic version\ntemplate <typename T>\nEigen::Matrix<T,2,1>\nhomography_<T>\n::map_point( Eigen::Matrix<T,2,1> const &p ) const\n{\n  return h_map_point<T>( h_.template cast<T>(), p );\n}\n\n/// Map a 2D point using this homography -- float specialization\ntemplate <>\nEigen::Matrix<float,2,1>\nhomography_<float>\n::map_point( Eigen::Matrix<float,2,1> const &p ) const\n{\n  return h_map_point( h_, p );\n}\n\n/// Map a 2D point using this homography -- double specialization\ntemplate <>\nEigen::Matrix<double,2,1>\nhomography_<double>\n::map_point( Eigen::Matrix<double,2,1> const &p ) const\n{\n  return h_map_point( h_, p );\n}\n\n/// Custom f2f_homography multiplication operator.\ntemplate <typename T>\nhomography_<T>\nhomography_<T>\n::operator*( homography_<T> const &rhs )\n{\n  return homography_<T>( h_ * rhs.h_ );\n}\n\n\n// ===========================================================================\n// Other Functions\n// ---------------------------------------------------------------------------\n\n/// homography_<T> output stream operator\ntemplate <typename T>\nstd::ostream&\noperator<<( std::ostream &s, homography_<T> const &h )\n{\n  s << h.get_matrix();\n  return s;\n}\n\n/// Output stream operator for \\p homography instances\nstd::ostream&\noperator<<( std::ostream &s, homography const &h )\n{\n  s << h.matrix();\n  return s;\n}\n\n// ===========================================================================\n// Template class instantiation\n// ---------------------------------------------------------------------------\n/// \\cond DoxygenSuppress\n#define INSTANTIATE_HOMOGRAPHY(T) \\\n  template class homography_<T>; \\\n  template std::ostream& operator<<( std::ostream &, \\\n                                     homography_<T> const & )\n\nINSTANTIATE_HOMOGRAPHY(float);\nINSTANTIATE_HOMOGRAPHY(double);\n#undef INSTANTIATE_HOMOGRAPHY\n/// \\endcond\n\n\n} // end maptk namespace\n", "meta": {"hexsha": "18c076fbfc1db789ead37d700ecc35cdedb5aacd", "size": 7303, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "maptk/homography.cxx", "max_stars_repo_name": "efernandez/maptk", "max_stars_repo_head_hexsha": "c74546cf4056bffd1c3989055c7e60c5725eb3ab", "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": "maptk/homography.cxx", "max_issues_repo_name": "efernandez/maptk", "max_issues_repo_head_hexsha": "c74546cf4056bffd1c3989055c7e60c5725eb3ab", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "maptk/homography.cxx", "max_forks_repo_name": "efernandez/maptk", "max_forks_repo_head_hexsha": "c74546cf4056bffd1c3989055c7e60c5725eb3ab", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-01T09:29:55.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-01T09:29:55.000Z", "avg_line_length": 25.3576388889, "max_line_length": 81, "alphanum_fraction": 0.6827331234, "num_tokens": 1799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.28696419612357715}}
{"text": "/*! \\class EikonalSolver\n    \\brief Abstract class that serves as interface for the actual EikonalSolvers implemented.\n    It requires (at least) the computeInternal method to be implemented,\n\n    It uses as a main container the nDGridMap class. The nDGridMap template paramenter\n    has to be an FMCell or something inherited from it.\n\n    Copyright (C) 2015 Javier V. Gomez\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\n#ifndef EIKONALSOLVER_H_\n#define EIKONALSOLVER_H_\n\n#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <numeric>\n#include <fstream>\n#include <array>\n#include <chrono>\n\n#include <boost/concept_check.hpp>\n\n#include <fast_methods/fm/solver.hpp>\n#include <fast_methods/console/console.h>\n\ntemplate <class grid_t>\nclass EikonalSolver : public Solver<grid_t>{\n\n    public:\n        EikonalSolver() : Solver<grid_t>(\"EikonalSolver\") {}\n        EikonalSolver(const std::string& name) : Solver<grid_t>(name) {}\n\n        /** \\brief Solves nD Eikonal equation for cell idx. If heuristics are activated, it will add\n            the estimated travel time to goal with current velocity. */\n        virtual double solveEikonal(const int & idx) \n        {   \n            unsigned int a = grid_t::getNDims(); // a parameter of the Eikonal equation.\n            Tvalues_.clear();\n\n            for (unsigned int dim = 0; dim < grid_t::getNDims(); ++dim) {\n                double minTInDim = grid_->getMinValueInDim(idx, dim);\n                if (!std::isinf(minTInDim) && minTInDim < grid_->getCell(idx).getArrivalTime())\n                    Tvalues_.push_back(minTInDim);\n                else\n                    a -=1;\n            }\n\n            if (a == 0)\n                return std::numeric_limits<double>::infinity();\n\n            // Sort the neighbor values to make easy the following code.\n            /// \\todo given that this sorts a small vector, a n^2 methods could be better. Test it.\n            std::sort(Tvalues_.begin(), Tvalues_.end());\n            double updatedT;\n            for (unsigned i = 1; i <= a; ++i) {\n                updatedT = solveEikonalNDims(idx, i);\n                // If no more dimensions or increasing one dimension will not improve time.\n                if (i == a || (updatedT - Tvalues_[i]) < utils::COMP_MARGIN)\n                    break;\n            }\n            return updatedT;\n        }\n\n    protected:\n        /** \\brief Solves the Eikonal equation assuming that Tvalues_\n            is sorted. */\n        double solveEikonalNDims\n        (unsigned int idx, unsigned int dim) {\n            // Solve for 1 dimension.\n            if (dim == 1)\n                return Tvalues_[0] + grid_->getLeafSize() / grid_->getCell(idx).getVelocity();\n\n            // Solve for any number > 1 of dimensions.\n            double sumT = 0;\n            double sumTT = 0;\n            for (unsigned i = 0; i < dim; ++i) {\n                sumT += Tvalues_[i];\n                sumTT += Tvalues_[i]*Tvalues_[i];\n            }\n\n            // These a,b,c values are simplified since leafsize^2, which should be present in the three\n            // terms but they are cancelled out when solving the quadratic function.\n            double a = dim;\n            double b = -2*sumT;\n            double c = sumTT - grid_->getLeafSize() * grid_->getLeafSize() / (grid_->getCell(idx).getVelocity()*grid_->getCell(idx).getVelocity());\n            double quad_term = b*b - 4*a*c;\n\n            if (quad_term < 0)\n                return std::numeric_limits<double>::infinity();\n            else\n                return (-b + sqrt(quad_term))/(2*a);\n        }\n\n        /** \\brief Auxiliar vector with values T0,T1...Tn-1 variables in the Discretized Eikonal Equation. */\n        std::vector<double>          Tvalues_;\n\n        /** \\brief Auxiliar array which stores the neighbor of each iteration of the computeFM() function. */\n        std::array <unsigned int, 2*grid_t::getNDims()> neighbors_;\n\n        using Solver<grid_t>::grid_;\n};\n\n#endif /* EIKONALSOLVER_H_*/\n", "meta": {"hexsha": "bc9a97d70de213e93ff8445de9b91d5095dc56b7", "size": 4626, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Btraj/third_party/fast_methods/fm/eikonalsolver.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/fm/eikonalsolver.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/fm/eikonalsolver.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": 39.5384615385, "max_line_length": 147, "alphanum_fraction": 0.6111111111, "num_tokens": 1094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.28695615375597644}}
{"text": "/*\n * This file is part of the statismo library.\n *\n * Author: Marcel Luethi (marcel.luethi@unibas.ch)\n *\n * Copyright (c) 2011 University of Basel\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 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 * Neither the name of the project's author 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\n * FOR 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 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 */\n\n#ifndef __PosteriorModelBuilder_hxx\n#define __PosteriorModelBuilder_hxx\n\n#include \"PosteriorModelBuilder.h\"\n\n#include <iostream>\n\n#include <Eigen/SVD>\n\n#include \"CommonTypes.h\"\n#include \"PCAModelBuilder.h\"\n\nnamespace statismo {\n\n//\n// PosteriorModelBuilder\n//\n//\n\ntemplate <typename T>\nPosteriorModelBuilder<T>::PosteriorModelBuilder()\n    : Superclass() {\n}\n\n\ntemplate <typename T>\ntypename PosteriorModelBuilder<T>::StatisticalModelType*\nPosteriorModelBuilder<T>::BuildNewModel(\n    const DataItemListType& sampleDataList,\n    const PointValueListType& pointValues,\n    double pointValuesNoiseVariance,\n    double noiseVariance) const {\n    return BuildNewModel(sampleDataList, TrivialPointValueWithCovarianceListWithUniformNoise(pointValues, pointValuesNoiseVariance), noiseVariance);\n}\n\n\ntemplate <typename T>\ntypename PosteriorModelBuilder<T>::StatisticalModelType*\nPosteriorModelBuilder<T>::BuildNewModelFromModel(\n    const StatisticalModelType* inputModel,\n    const PointValueListType& pointValues,\n    double pointValuesNoiseVariance,\n    bool computeScores) const {\n\n    return BuildNewModelFromModel(inputModel, TrivialPointValueWithCovarianceListWithUniformNoise(pointValues,pointValuesNoiseVariance), computeScores);\n\n}\n\ntemplate <typename T>\ntypename PosteriorModelBuilder<T>::PointValueWithCovarianceListType\nPosteriorModelBuilder<T>::TrivialPointValueWithCovarianceListWithUniformNoise(\n    const PointValueListType& pointValues, double pointValueNoiseVariance) const {\n\n    const MatrixType pointCovarianceMatrix = pointValueNoiseVariance * MatrixType::Identity(3,3);\n    PointValueWithCovarianceListType pvcList;//(pointValues.size());\n\n\n    for (typename PointValueListType::const_iterator it = pointValues.begin(); it != pointValues.end(); ++it) {\n        pvcList.push_back(PointValueWithCovariancePairType(*it,pointCovarianceMatrix));\n    }\n\n    return pvcList;\n\n}\n\n\ntemplate <typename T>\ntypename PosteriorModelBuilder<T>::StatisticalModelType*\nPosteriorModelBuilder<T>::BuildNewModel(\n    const DataItemListType& sampleDataList,\n    const PointValueWithCovarianceListType& pointValuesWithCovariance,\n    double noiseVariance) const {\n    typedef PCAModelBuilder<T> PCAModelBuilderType;\n    PCAModelBuilderType* modelBuilder = PCAModelBuilderType::Create();\n    StatisticalModelType* model = modelBuilder->BuildNewModel(sampleDataList, noiseVariance);\n    StatisticalModelType* PosteriorModel = BuildNewModelFromModel(model, pointValuesWithCovariance, noiseVariance);\n    delete modelBuilder;\n    delete model;\n    return PosteriorModel;\n}\n\n\ntemplate <typename T>\ntypename PosteriorModelBuilder<T>::StatisticalModelType*\nPosteriorModelBuilder<T>::BuildNewModelFromModel(\n    const StatisticalModelType* inputModel,\n    const PointValueWithCovarianceListType& pointValuesWithCovariance,\n    bool computeScores) const {\n\n    typedef statismo::Representer<T> RepresenterType;\n\n    const RepresenterType* representer = inputModel->GetRepresenter();\n\n\n    // The naming of the variables correspond to those used in the paper\n    // Posterior Shape Models,\n    // Thomas Albrecht, Marcel Luethi, Thomas Gerig, Thomas Vetter\n    //\n    const MatrixType& Q =  inputModel->GetPCABasisMatrix();\n    const VectorType& mu = inputModel->GetMeanVector();\n\n    // this method only makes sense for a proper PPCA model (e.g. the noise term is properly defined)\n    // if the model has zero noise, we assume a small amount of noise\n    double rho2 = std::max((double) inputModel->GetNoiseVariance(), (double) Superclass::TOLERANCE);\n\n    unsigned dim = representer->GetDimensions();\n\n\n    // build the part matrices with , considering only the points that are fixed\n    //\n    unsigned numPrincipalComponents = inputModel->GetNumberOfPrincipalComponents();\n    MatrixType Q_g(pointValuesWithCovariance.size()* dim, numPrincipalComponents);\n    VectorType mu_g(pointValuesWithCovariance.size() * dim);\n    VectorType s_g(pointValuesWithCovariance.size() * dim);\n\n    MatrixType LQ_g(pointValuesWithCovariance.size()* dim, numPrincipalComponents);\n\n    unsigned i = 0;\n    for (typename PointValueWithCovarianceListType::const_iterator it = pointValuesWithCovariance.begin(); it != pointValuesWithCovariance.end(); ++it) {\n        VectorType val = representer->PointSampleToPointSampleVector(it->first.second);\n        unsigned pt_id = representer->GetPointIdForPoint(it->first.first);\n\n        // In the formulas, we actually need the precision matrix, which is the inverse of the covariance.\n        const MatrixType pointPrecisionMatrix = it->second.inverse();\n\n        // Get the three rows pertaining to this point:\n        const MatrixType Qrows_for_pt_id = Q.block(pt_id * dim, 0, dim, numPrincipalComponents);\n\n        Q_g.block(i * dim, 0, dim, numPrincipalComponents) = Qrows_for_pt_id;\n        mu_g.block(i * dim, 0, dim, 1) = mu.block(pt_id * dim, 0, dim, 1);\n        s_g.block(i * dim, 0, dim, 1) = val;\n\n        LQ_g.block(i * dim, 0, dim, numPrincipalComponents) = pointPrecisionMatrix * Qrows_for_pt_id;\n        i++;\n    }\n\n    VectorType D2 = inputModel->GetPCAVarianceVector().array();\n\n    const MatrixType& Q_gT = Q_g.transpose();\n\n    MatrixType M = Q_gT * LQ_g;\n    M.diagonal() += VectorType::Ones(Q_g.cols());\n\n    MatrixTypeDoublePrecision Minv = M.cast<double>().inverse();\n\n    // the MAP solution for the latent variables (coefficients)\n    VectorType coeffs = Minv.cast<ScalarType>() * LQ_g.transpose() * (s_g - mu_g);\n\n    // the MAP solution in the sample space\n    VectorType mu_c = inputModel->GetRepresenter()->SampleToSampleVector(inputModel->DrawSample(coeffs));\n\n    const VectorType& pcaVariance = inputModel->GetPCAVarianceVector();\n    VectorTypeDoublePrecision pcaSdev = pcaVariance.cast<double>().array().sqrt();\n\n    VectorType D2MinusRho = D2 - VectorType::Ones(D2.rows()) * rho2;\n    // the values of D2 can be negative. We need to be careful when taking the root\n    for (unsigned i = 0; i < D2MinusRho.rows(); i++) {\n        D2MinusRho(i) = std::max((ScalarType) 0, D2(i));\n    }\n    VectorType D2MinusRhoSqrt = D2MinusRho.array().sqrt();\n\n\n    typedef Eigen::JacobiSVD<MatrixTypeDoublePrecision> SVDType;\n    MatrixTypeDoublePrecision innerMatrix = D2MinusRhoSqrt.cast<double>().asDiagonal() * Minv * D2MinusRhoSqrt.cast<double>().asDiagonal();\n    SVDType svd(innerMatrix, Eigen::ComputeThinU);\n\n\n    // SVD of the inner matrix\n    VectorType D_c = svd.singularValues().cast<ScalarType>();\n\n    // Todo: Maybe it is possible to do this with Q, so that we don\"t need to get U as well.\n    MatrixType U_c = inputModel->GetOrthonormalPCABasisMatrix() * svd.matrixU().cast<ScalarType>();\n\n    StatisticalModelType* PosteriorModel = StatisticalModelType::Create(representer , mu_c, U_c, D_c, rho2);\n\n    // Write the parameters used to build the models into the builderInfo\n\n    typename ModelInfo::BuilderInfoList builderInfoList = inputModel->GetModelInfo().GetBuilderInfoList();\n\n    BuilderInfo::ParameterInfoList bi;\n    bi.push_back(BuilderInfo::KeyValuePair(\"NoiseVariance \", Utils::toString(rho2)));\n    bi.push_back(BuilderInfo::KeyValuePair(\"FixedPointsVariance \", Utils::toString(0.2)));\n//\n    BuilderInfo::DataInfoList di;\n\n    unsigned pt_no = 0;\n    for (typename PointValueWithCovarianceListType::const_iterator it = pointValuesWithCovariance.begin(); it != pointValuesWithCovariance.end(); ++it) {\n        VectorType val = representer->PointSampleToPointSampleVector(it->first.second);\n\n        // TODO we looked up the PointId for the same point before. Having it here again is inefficient.\n        unsigned pt_id = representer->GetPointIdForPoint(it->first.first);\n        std::ostringstream keySStream;\n        keySStream << \"Point constraint \" << pt_no;\n        std::ostringstream valueSStream;\n        valueSStream << \"(\" << pt_id << \", (\";\n\n        for (unsigned d = 0; d < dim - 1; d++) {\n            valueSStream << val[d] << \",\";\n        }\n        valueSStream << val[dim -1];\n        valueSStream << \"))\";\n        di.push_back(BuilderInfo::KeyValuePair(keySStream.str(), valueSStream.str()));\n        pt_no++;\n    }\n\n\n    BuilderInfo builderInfo(\"PosteriorModelBuilder\", di, bi);\n    builderInfoList.push_back(builderInfo);\n\n    MatrixType inputScores = inputModel->GetModelInfo().GetScoresMatrix();\n    MatrixType scores = MatrixType::Zero(inputScores.rows(), inputScores.cols());\n\n    if (computeScores == true) {\n\n        // get the scores from the input model\n        for (unsigned i = 0; i < inputScores.cols(); i++) {\n            // reconstruct the sample from the input model and project it back into the model\n            typename RepresenterType::DatasetPointerType ds = inputModel->DrawSample(inputScores.col(i));\n            scores.col(i) = PosteriorModel->ComputeCoefficientsForDataset(ds);\n            representer->DeleteDataset(ds);\n        }\n    }\n    ModelInfo info(scores, builderInfoList);\n    PosteriorModel->SetModelInfo(info);\n\n    return PosteriorModel;\n\n}\n\n} // namespace statismo\n\n#endif\n", "meta": {"hexsha": "2886187c462f227f1291ace2a48b8855d744d343", "size": 10662, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "modules/core/include/PosteriorModelBuilder.hxx", "max_stars_repo_name": "thewtex/statismo", "max_stars_repo_head_hexsha": "fc49565185584943e7cd98153c2fa31680bb822f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-07-18T11:30:55.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-18T11:30:55.000Z", "max_issues_repo_path": "modules/core/include/PosteriorModelBuilder.hxx", "max_issues_repo_name": "thewtex/statismo", "max_issues_repo_head_hexsha": "fc49565185584943e7cd98153c2fa31680bb822f", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/include/PosteriorModelBuilder.hxx", "max_forks_repo_name": "thewtex/statismo", "max_forks_repo_head_hexsha": "fc49565185584943e7cd98153c2fa31680bb822f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-03-31T11:27:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-22T09:13:02.000Z", "avg_line_length": 39.4888888889, "max_line_length": 153, "alphanum_fraction": 0.7356030763, "num_tokens": 2548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791787121629465, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2869561537559764}}
{"text": "/**\n * Author\t: Michael Fonder\n * Year\t\t: 2016\n **/\n\n#include <iostream>\n#include <sstream>\n#include <time.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <math.h>\n#include <Eigen/Dense>\n#include <Eigen/QR>\n#include <Eigen/Dense>\n#include <Eigen/Eigen>\n#include <Eigen/Sparse>\n\n#include <unordered_map>\n#include <unordered_set>\n#include <set>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/video/video.hpp>\n\n#include \"dynamicVectorContainer.hpp\"\n#include \"dynamicVectorReference.hpp\"\n#include \"imuState.hpp\"\n#include \"MSCKF.hpp\"\n\n#ifndef _CRT_SECURE_NO_WARNINGS\n# define _CRT_SECURE_NO_WARNINGS\n#endif\n\nusing namespace cv;\nusing namespace std;\n\n\n\nint main(int argc, char* argv[])\n{\n\tFileStorage fs;\n\tMat distCoeffs;\n\tMat cameraMatrix;\n\t\n\t//******************************************************************************\n\t\n\tstring filename = \"distCoeffs\";\n\tfs.open(filename+\".yml\", FileStorage::READ);\n\tfs[filename] >> distCoeffs;\n\t\n\tfilename = \"cameraMatrix\";\n\tfs.open(filename+\".yml\", FileStorage::READ);\n\tfs[filename] >> cameraMatrix;\n\t\n\tfilename = \"featurePos\";\n\tfs.open(filename+\".yml\", FileStorage::READ);\n\tMat featurePos;\n\tfs[filename] >> featurePos;\n\tcout <<featurePos  << endl;\n\t\n\tfilename = \"data\";\n\tfs.open(filename+\".yml\", FileStorage::READ);\n\tMat data;\n\tfs[filename] >> data;\n\tcout << filename+\".yml\" << endl;\n\tdata = data.t();\n\t\n\tMat ba, bg, IMU_noise, p_CI, q_CI, MSCKF_params, init_uncertainty;\n\tfilename = \"parameters\";\n\tfs.open(filename+\".yml\", FileStorage::READ);\n\tfs[\"ba\"] >> ba;\n\tfs[\"bg\"] >> bg;\n\tfs[\"IMU_noise\"] >> IMU_noise;\n\tfs[\"init_uncertainty\"] >> init_uncertainty;\n\tfs[\"p_CI\"] >> p_CI;\n\tfs[\"q_CI\"] >> q_CI;\n\tfs[\"MSCKF_params\"] >> MSCKF_params;\n\tcout << filename+\".yml\" << endl;\n\tcout << ba << bg << IMU_noise << p_CI << q_CI << MSCKF_params << endl;\n\t\n\tMeasurement newMeasurement;\n\tIMUstate imustate;\n\tcout << \"datatestbegin *********************************\" << endl;\n\t\n\tVideoCapture capture(\"flight_cut.avi\"); // attempt to open it as a video file or image sequence\n//\tVideoCapture capture(\"test_syn.avi\"); // attempt to open it as a video file or image sequence\n\t\n\tif (!capture.isOpened()){  // returns true if video capturing has been initialized already\n\t\tcerr << \"Failed to open the video file or image sequence...\\n\" << endl;\n\t\treturn 1;\n\t}\n\tMat frame;\n\tbool finished = false;\n\tsize_t timeIMU=0, timeVideo=0;\n\tMSCKF filter;\n\tfilter.trueFeaturesPos = featurePos;\n\tfilter.camera.distCoeffs = distCoeffs;\n\tfilter.camera.intrisic = cameraMatrix;\n\tfilter.setCameraParams(p_CI, q_CI);\n\tfilter.setFilterParams(MSCKF_params);\n\tba.copyTo(filter.imustate->ba);\n\tbg.copyTo(filter.imustate->bg);\n\tfilter.imustate->setQ(IMU_noise);\n\tfilter.imustate->resetCovar(init_uncertainty);\n\tcapture >> frame;\n\t\n\tMat log_p = Mat::zeros(1,6,CV_32FC1);\n\tMat local = Mat::zeros(1,6,CV_32FC1);\n\t\n\tMat log_q = Mat::zeros(1,7,CV_32FC1);\n\tMat localq = Mat::zeros(1,7,CV_32FC1);\n\t\n\twhile(!finished)\n\t{\n\t\tcapture >> frame;\n\t\tif (frame.empty())\n\t\t{\n\t\t\tfinished = true;\n\t\t\tcontinue;\n\t\t}\n// \t\tif(timeVideo > 150)\n// \t\t\tbreak;\n\t\t\n\t\twhile(float(timeIMU)*0.01 <= float(timeVideo)/30)\n\t\t{\n//\t\t\tdata.rowRange(6,9).col(timeIMU).copyTo(filter.truePos); \n//\t\t\tdata.rowRange(9,13).col(timeIMU).copyTo(filter.trueQuat);\n\t\t\t\n\t\t\tdata.rowRange(0,3).col(timeIMU).copyTo(newMeasurement.a_I);\n\t\t\t//newMeasurement.a_I.row(0) *= -1;\n\t\t\tdata.rowRange(3,6).col(timeIMU).copyTo(newMeasurement.omega);\n\t\t\t//newMeasurement.omega.rowRange(0,2)*=-1.0;\n\t\t\tfilter.propagateIMUStateAndCovar(newMeasurement, float(timeIMU)*0.01);\n\t\t\tlocal.colRange(0,3) = filter.imustate->p_G.t();\n\t\t\tlocal.at<float>(0,3) = \tfilter.imustate->covar.at<float>(12,12);\n\t\t\tlocal.at<float>(0,4) = \tfilter.imustate->covar.at<float>(13,13);\n\t\t\tlocal.at<float>(0,5) = \tfilter.imustate->covar.at<float>(14,14);\n\t\t\tlog_p.push_back(local);\n\t\t\t\n\t\t\tlocalq.colRange(0,4) = filter.imustate->q_IG.t();\n\t\t\tlocalq.at<float>(0,4) = \tfilter.imustate->covar.at<float>(0,0);\n\t\t\tlocalq.at<float>(0,5) = \tfilter.imustate->covar.at<float>(1,1);\n\t\t\tlocalq.at<float>(0,6) = \tfilter.imustate->covar.at<float>(2,2);\n\t\t\tlog_q.push_back(localq);\n\t\t\t++timeIMU;\n\t\t}\n\t\t\n\t\tcvtColor(frame, frame, CV_BGR2GRAY);\n\t\tif(!(timeVideo%2))\n\t\t{\n\t\t\tcout << \"augment \" << timeVideo << endl;\n\t\t\tfilter.augmentState(frame, float(timeVideo)/30);\n\t\t\tcout << \"correct \" << timeVideo << endl;\n\t\t\tfilter.update();\n\t\t}\n\t\t++timeVideo;\n\t\tFileStorage logFilep(\"log_p.yml\", FileStorage::WRITE);\n\t\tlogFilep << \"log_p\" << log_p;\n\t\tFileStorage logFileq(\"log_q.yml\", FileStorage::WRITE);\n\t\tlogFileq << \"log_q\" << log_q;\n\t\tFileStorage covar_IMU(\"covar_IMU.yml\", FileStorage::WRITE);\n\t\tcovar_IMU << \"covar_IMU\" << filter.imustate->covar;\n\t\t\n\t\tcout << \"Estimated attitude : \" << filter.getOrientation().t() << endl;\n\t\tcout << \"Estimated position : \" << filter.getPosition().t() << endl;\n\t\t\n\t}\n\t\n\tcout << filter.getPosition() << endl;\n\t\n    \t\n    return 0;\n}", "meta": {"hexsha": "22c82ef44310e1ea6020188d36e266daecba58f2", "size": 4889, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MSCKF/main.cpp", "max_stars_repo_name": "michael-fonder/fonder_thesis-2016", "max_stars_repo_head_hexsha": "59631865169857f935a52ffd89a07243fe00e7d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2016-09-22T08:41:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T02:49:45.000Z", "max_issues_repo_path": "MSCKF/main.cpp", "max_issues_repo_name": "michael-fonder/fonder_thesis-2016", "max_issues_repo_head_hexsha": "59631865169857f935a52ffd89a07243fe00e7d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2016-09-06T11:25:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-31T12:29:50.000Z", "max_forks_repo_path": "MSCKF/main.cpp", "max_forks_repo_name": "michael-fonder/fonder_thesis-2016", "max_forks_repo_head_hexsha": "59631865169857f935a52ffd89a07243fe00e7d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2016-08-30T07:17:51.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-08T07:29:18.000Z", "avg_line_length": 28.0977011494, "max_line_length": 96, "alphanum_fraction": 0.6625076703, "num_tokens": 1452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2867283018206714}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https://www.mrpt.org/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2019, Individual contributors, see AUTHORS file     |\n   | See: https://www.mrpt.org/Authors - All rights reserved.               |\n   | Released under BSD License. See: https://www.mrpt.org/License          |\n   +------------------------------------------------------------------------+ */\n\n#include \"vision-precomp.h\"  // Precompiled headers\n\n#include <mrpt/core/round.h>\n#include <mrpt/poses/Lie/SE.h>\n#include <mrpt/system/CTicTac.h>\n#include <mrpt/vision/CDifodo.h>\n#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace mrpt;\nusing namespace mrpt::vision;\nusing namespace mrpt::math;\nusing namespace std;\nusing namespace Eigen;\nusing mrpt::round;\nusing mrpt::square;\n\nCDifodo::CDifodo()\n{\n\trows = 60;\n\tcols = 80;\n\tfovh = M_PIf * 58.6f / 180.0f;\n\tfovv = M_PIf * 45.6f / 180.0f;\n\tcam_mode = 1;  // (1 - 640 x 480, 2 - 320 x 240, 4 - 160 x 120)\n\tdownsample = 1;\n\tctf_levels = 1;\n\tm_width = 640 / (cam_mode * downsample);\n\tm_height = 480 / (cam_mode * downsample);\n\tfast_pyramid = true;\n\n\t// Resize pyramid\n\tconst unsigned int pyr_levels =\n\t\tround(log(float(m_width / cols)) / log(2.f)) + ctf_levels;\n\tdepth.resize(pyr_levels);\n\tdepth_old.resize(pyr_levels);\n\tdepth_inter.resize(pyr_levels);\n\tdepth_warped.resize(pyr_levels);\n\txx.resize(pyr_levels);\n\txx_inter.resize(pyr_levels);\n\txx_old.resize(pyr_levels);\n\txx_warped.resize(pyr_levels);\n\tyy.resize(pyr_levels);\n\tyy_inter.resize(pyr_levels);\n\tyy_old.resize(pyr_levels);\n\tyy_warped.resize(pyr_levels);\n\ttransformations.resize(pyr_levels);\n\n\tfor (unsigned int i = 0; i < pyr_levels; i++)\n\t{\n\t\tunsigned int s = pow(2.f, int(i));\n\t\tcols_i = m_width / s;\n\t\trows_i = m_height / s;\n\t\tdepth[i].resize(rows_i, cols_i);\n\t\tdepth_inter[i].resize(rows_i, cols_i);\n\t\tdepth_old[i].resize(rows_i, cols_i);\n\t\tdepth[i].fill(0.0f);\n\t\tdepth_old[i].fill(0.0f);\n\t\txx[i].resize(rows_i, cols_i);\n\t\txx_inter[i].resize(rows_i, cols_i);\n\t\txx_old[i].resize(rows_i, cols_i);\n\t\txx[i].fill(0.0f);\n\t\txx_old[i].fill(0.0f);\n\t\tyy[i].resize(rows_i, cols_i);\n\t\tyy_inter[i].resize(rows_i, cols_i);\n\t\tyy_old[i].resize(rows_i, cols_i);\n\t\tyy[i].fill(0.0f);\n\t\tyy_old[i].fill(0.0f);\n\t\ttransformations[i].resize(4, 4);\n\n\t\tif (cols_i <= cols)\n\t\t{\n\t\t\tdepth_warped[i].resize(rows_i, cols_i);\n\t\t\txx_warped[i].resize(rows_i, cols_i);\n\t\t\tyy_warped[i].resize(rows_i, cols_i);\n\t\t}\n\t}\n\n\tdepth_wf.setSize(m_height, m_width);\n\n\tfps = 30.f;  // In Hz\n\n\tprevious_speed_const_weight = 0.05f;\n\tprevious_speed_eig_weight = 0.5f;\n\tkai_loc_old = TTwist3D();\n\tnum_valid_points = 0;\n\n\t// Compute gaussian mask\n\tVectorXf v_mask(4);\n\tv_mask(0) = 1.f;\n\tv_mask(1) = 2.f;\n\tv_mask(2) = 2.f;\n\tv_mask(3) = 1.f;\n\tfor (unsigned int i = 0; i < 4; i++)\n\t\tfor (unsigned int j = 0; j < 4; j++)\n\t\t\tf_mask(i, j) = v_mask(i) * v_mask(j) / 36.f;\n\n\t// Compute gaussian mask\n\tfloat v_mask2[5] = {1, 4, 6, 4, 1};\n\tfor (unsigned int i = 0; i < 5; i++)\n\t\tfor (unsigned int j = 0; j < 5; j++)\n\t\t\tg_mask[i][j] = v_mask2[i] * v_mask2[j] / 256.f;\n}\n\nvoid CDifodo::buildCoordinatesPyramid()\n{\n\tconst float max_depth_dif = 0.1f;\n\n\t// Push coordinates back\n\tdepth_old.swap(depth);\n\txx_old.swap(xx);\n\tyy_old.swap(yy);\n\n\t// The number of levels of the pyramid does not match the number of levels\n\t// used\n\t// in the odometry computation (because we might want to finish with lower\n\t// resolutions)\n\n\tunsigned int pyr_levels =\n\t\tround(log(float(m_width / cols)) / log(2.f)) + ctf_levels;\n\n\t// Generate levels\n\tfor (unsigned int i = 0; i < pyr_levels; i++)\n\t{\n\t\tunsigned int s = pow(2.f, int(i));\n\t\tcols_i = m_width / s;\n\t\trows_i = m_height / s;\n\t\tconst int rows_i2 = 2 * rows_i;\n\t\tconst int cols_i2 = 2 * cols_i;\n\t\tconst int i_1 = i - 1;\n\n\t\tif (i == 0) depth[i].swap(depth_wf);\n\n\t\t//                              Downsampling\n\t\t//-----------------------------------------------------------------------------\n\t\telse\n\t\t{\n\t\t\tfor (unsigned int u = 0; u < cols_i; u++)\n\t\t\t\tfor (unsigned int v = 0; v < rows_i; v++)\n\t\t\t\t{\n\t\t\t\t\tconst int u2 = 2 * u;\n\t\t\t\t\tconst int v2 = 2 * v;\n\t\t\t\t\tconst float dcenter = depth[i_1](v2, u2);\n\n\t\t\t\t\t// Inner pixels\n\t\t\t\t\tif ((v > 0) && (v < rows_i - 1) && (u > 0) &&\n\t\t\t\t\t\t(u < cols_i - 1))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (dcenter > 0.f)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfloat sum = 0.f;\n\t\t\t\t\t\t\tfloat weight = 0.f;\n\n\t\t\t\t\t\t\tfor (int l = -2; l < 3; l++)\n\t\t\t\t\t\t\t\tfor (int k = -2; k < 3; k++)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tconst float abs_dif = abs(\n\t\t\t\t\t\t\t\t\t\tdepth[i_1](v2 + k, u2 + l) - dcenter);\n\t\t\t\t\t\t\t\t\tif (abs_dif < max_depth_dif)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tconst float aux_w =\n\t\t\t\t\t\t\t\t\t\t\tg_mask[2 + k][2 + l] *\n\t\t\t\t\t\t\t\t\t\t\t(max_depth_dif - abs_dif);\n\t\t\t\t\t\t\t\t\t\tweight += aux_w;\n\t\t\t\t\t\t\t\t\t\tsum +=\n\t\t\t\t\t\t\t\t\t\t\taux_w * depth[i_1](v2 + k, u2 + l);\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\tdepth[i](v, u) = sum / weight;\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\tfloat min_depth = 10.f;\n\t\t\t\t\t\t\tfor (int l = -2; l < 3; l++)\n\t\t\t\t\t\t\t\tfor (int k = -2; k < 3; k++)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tconst float d = depth[i_1](v2 + k, u2 + l);\n\t\t\t\t\t\t\t\t\tif ((d > 0.f) && (d < min_depth))\n\t\t\t\t\t\t\t\t\t\tmin_depth = d;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (min_depth < 10.f)\n\t\t\t\t\t\t\t\tdepth[i](v, u) = min_depth;\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tdepth[i](v, u) = 0.f;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Boundary\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tif (dcenter > 0.f)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfloat sum = 0.f;\n\t\t\t\t\t\t\tfloat weight = 0.f;\n\n\t\t\t\t\t\t\tfor (int l = -2; l < 3; l++)\n\t\t\t\t\t\t\t\tfor (int k = -2; k < 3; k++)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tconst int indv = v2 + k, indu = u2 + l;\n\t\t\t\t\t\t\t\t\tif ((indv >= 0) && (indv < rows_i2) &&\n\t\t\t\t\t\t\t\t\t\t(indu >= 0) && (indu < cols_i2))\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tconst float abs_dif = abs(\n\t\t\t\t\t\t\t\t\t\t\tdepth[i_1](indv, indu) - dcenter);\n\t\t\t\t\t\t\t\t\t\tif (abs_dif < max_depth_dif)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tconst float aux_w =\n\t\t\t\t\t\t\t\t\t\t\t\tg_mask[2 + k][2 + l] *\n\t\t\t\t\t\t\t\t\t\t\t\t(max_depth_dif - abs_dif);\n\t\t\t\t\t\t\t\t\t\t\tweight += aux_w;\n\t\t\t\t\t\t\t\t\t\t\tsum +=\n\t\t\t\t\t\t\t\t\t\t\t\taux_w * depth[i_1](indv, indu);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tdepth[i](v, u) = sum / weight;\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\tfloat min_depth = 10.f;\n\t\t\t\t\t\t\tfor (int l = -2; l < 3; l++)\n\t\t\t\t\t\t\t\tfor (int k = -2; k < 3; k++)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tconst int indv = v2 + k, indu = u2 + l;\n\t\t\t\t\t\t\t\t\tif ((indv >= 0) && (indv < rows_i2) &&\n\t\t\t\t\t\t\t\t\t\t(indu >= 0) && (indu < cols_i2))\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tconst float d = depth[i_1](indv, indu);\n\t\t\t\t\t\t\t\t\t\tif ((d > 0.f) && (d < min_depth))\n\t\t\t\t\t\t\t\t\t\t\tmin_depth = d;\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\tif (min_depth < 10.f)\n\t\t\t\t\t\t\t\tdepth[i](v, u) = min_depth;\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tdepth[i](v, u) = 0.f;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n\n\t\t// Calculate coordinates \"xy\" of the points\n\t\tconst float inv_f_i = 2.f * tan(0.5f * fovh) / float(cols_i);\n\t\tconst float disp_u_i = 0.5f * (cols_i - 1);\n\t\tconst float disp_v_i = 0.5f * (rows_i - 1);\n\n\t\tfor (unsigned int u = 0; u < cols_i; u++)\n\t\t\tfor (unsigned int v = 0; v < rows_i; v++)\n\t\t\t\tif (depth[i](v, u) > 0.f)\n\t\t\t\t{\n\t\t\t\t\txx[i](v, u) = (u - disp_u_i) * depth[i](v, u) * inv_f_i;\n\t\t\t\t\tyy[i](v, u) = (v - disp_v_i) * depth[i](v, u) * inv_f_i;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\txx[i](v, u) = 0.f;\n\t\t\t\t\tyy[i](v, u) = 0.f;\n\t\t\t\t}\n\t}\n}\n\nvoid CDifodo::buildCoordinatesPyramidFast()\n{\n\tconst float max_depth_dif = 0.1f;\n\n\t// Push coordinates back\n\tdepth_old.swap(depth);\n\txx_old.swap(xx);\n\tyy_old.swap(yy);\n\n\t// The number of levels of the pyramid does not match the number of levels\n\t// used\n\t// in the odometry computation (because we might want to finish with lower\n\t// resolutions)\n\n\tunsigned int pyr_levels =\n\t\tround(log(float(m_width / cols)) / log(2.f)) + ctf_levels;\n\n\t// Generate levels\n\tfor (unsigned int i = 0; i < pyr_levels; i++)\n\t{\n\t\tunsigned int s = pow(2.f, int(i));\n\t\tcols_i = m_width / s;\n\t\trows_i = m_height / s;\n\t\t// const int rows_i2 = 2*rows_i;\n\t\t// const int cols_i2 = 2*cols_i;\n\t\tconst int i_1 = i - 1;\n\n\t\tif (i == 0) depth[i].swap(depth_wf);\n\n\t\t//                              Downsampling\n\t\t//-----------------------------------------------------------------------------\n\t\telse\n\t\t{\n\t\t\tfor (unsigned int u = 0; u < cols_i; u++)\n\t\t\t\tfor (unsigned int v = 0; v < rows_i; v++)\n\t\t\t\t{\n\t\t\t\t\tconst int u2 = 2 * u;\n\t\t\t\t\tconst int v2 = 2 * v;\n\n\t\t\t\t\t// Inner pixels\n\t\t\t\t\tif ((v > 0) && (v < rows_i - 1) && (u > 0) &&\n\t\t\t\t\t\t(u < cols_i - 1))\n\t\t\t\t\t{\n\t\t\t\t\t\tconst Matrix4f d_block =\n\t\t\t\t\t\t\tdepth[i_1].block<4, 4>(v2 - 1, u2 - 1);\n\t\t\t\t\t\tfloat depths[4] = {d_block(5), d_block(6), d_block(9),\n\t\t\t\t\t\t\t\t\t\t   d_block(10)};\n\t\t\t\t\t\tfloat dcenter;\n\n\t\t\t\t\t\t// Sort the array (try to find a good/representative\n\t\t\t\t\t\t// value)\n\t\t\t\t\t\tfor (signed char k = 2; k >= 0; k--)\n\t\t\t\t\t\t\tif (depths[k + 1] < depths[k])\n\t\t\t\t\t\t\t\tstd::swap(depths[k + 1], depths[k]);\n\t\t\t\t\t\tfor (unsigned char k = 1; k < 3; k++)\n\t\t\t\t\t\t\tif (depths[k] > depths[k + 1])\n\t\t\t\t\t\t\t\tstd::swap(depths[k + 1], depths[k]);\n\t\t\t\t\t\tif (depths[2] < depths[1])\n\t\t\t\t\t\t\tdcenter = depths[1];\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tdcenter = depths[2];\n\n\t\t\t\t\t\tif (dcenter > 0.f)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfloat sum = 0.f;\n\t\t\t\t\t\t\tfloat weight = 0.f;\n\n\t\t\t\t\t\t\tfor (unsigned char k = 0; k < 16; k++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconst float abs_dif = abs(d_block(k) - dcenter);\n\t\t\t\t\t\t\t\tif (abs_dif < max_depth_dif)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tconst float aux_w =\n\t\t\t\t\t\t\t\t\t\tf_mask[k] * (max_depth_dif - abs_dif);\n\t\t\t\t\t\t\t\t\tweight += aux_w;\n\t\t\t\t\t\t\t\t\tsum += aux_w * d_block(k);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (weight > 0) depth[i](v, u) = sum / weight;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tdepth[i](v, u) = 0.f;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Boundary\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tconst Matrix2f d_block = depth[i_1].block<2, 2>(v2, u2);\n\t\t\t\t\t\tconst float new_d = 0.25f * d_block.array().sum();\n\t\t\t\t\t\tif (new_d < 0.4f)\n\t\t\t\t\t\t\tdepth[i](v, u) = 0.f;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tdepth[i](v, u) = new_d;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n\n\t\t// Calculate coordinates \"xy\" of the points\n\t\tconst float inv_f_i = 2.f * tan(0.5f * fovh) / float(cols_i);\n\t\tconst float disp_u_i = 0.5f * (cols_i - 1);\n\t\tconst float disp_v_i = 0.5f * (rows_i - 1);\n\n\t\tfor (unsigned int u = 0; u < cols_i; u++)\n\t\t\tfor (unsigned int v = 0; v < rows_i; v++)\n\t\t\t\tif (depth[i](v, u) > 0.f)\n\t\t\t\t{\n\t\t\t\t\txx[i](v, u) = (u - disp_u_i) * depth[i](v, u) * inv_f_i;\n\t\t\t\t\tyy[i](v, u) = (v - disp_v_i) * depth[i](v, u) * inv_f_i;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\txx[i](v, u) = 0.f;\n\t\t\t\t\tyy[i](v, u) = 0.f;\n\t\t\t\t}\n\t}\n}\n\nvoid CDifodo::performWarping()\n{\n\t// Camera parameters (which also depend on the level resolution)\n\tconst float f = float(cols_i) / (2.f * tan(0.5f * fovh));\n\tconst float disp_u_i = 0.5f * float(cols_i - 1);\n\tconst float disp_v_i = 0.5f * float(rows_i - 1);\n\n\t// Rigid transformation estimated up to the present level\n\tMatrix4f acu_trans;\n\tacu_trans.setIdentity();\n\tfor (unsigned int i = 1; i <= level; i++)\n\t\tacu_trans = transformations[i - 1].asEigen() * acu_trans;\n\n\tMatrixXf wacu(rows_i, cols_i);\n\twacu.fill(0.f);\n\tdepth_warped[image_level].fill(0.f);\n\n\tconst auto cols_lim = float(cols_i - 1);\n\tconst auto rows_lim = float(rows_i - 1);\n\n\t//\t\t\t\t\t\tWarping loop\n\t//---------------------------------------------------------\n\tfor (unsigned int j = 0; j < cols_i; j++)\n\t\tfor (unsigned int i = 0; i < rows_i; i++)\n\t\t{\n\t\t\tconst float z = depth[image_level](i, j);\n\n\t\t\tif (z > 0.f)\n\t\t\t{\n\t\t\t\t// Transform point to the warped reference frame\n\t\t\t\tconst float depth_w = acu_trans(0, 0) * z +\n\t\t\t\t\t\t\t\t\t  acu_trans(0, 1) * xx[image_level](i, j) +\n\t\t\t\t\t\t\t\t\t  acu_trans(0, 2) * yy[image_level](i, j) +\n\t\t\t\t\t\t\t\t\t  acu_trans(0, 3);\n\t\t\t\tconst float x_w = acu_trans(1, 0) * z +\n\t\t\t\t\t\t\t\t  acu_trans(1, 1) * xx[image_level](i, j) +\n\t\t\t\t\t\t\t\t  acu_trans(1, 2) * yy[image_level](i, j) +\n\t\t\t\t\t\t\t\t  acu_trans(1, 3);\n\t\t\t\tconst float y_w = acu_trans(2, 0) * z +\n\t\t\t\t\t\t\t\t  acu_trans(2, 1) * xx[image_level](i, j) +\n\t\t\t\t\t\t\t\t  acu_trans(2, 2) * yy[image_level](i, j) +\n\t\t\t\t\t\t\t\t  acu_trans(2, 3);\n\n\t\t\t\t// Calculate warping\n\t\t\t\tconst float uwarp = f * x_w / depth_w + disp_u_i;\n\t\t\t\tconst float vwarp = f * y_w / depth_w + disp_v_i;\n\n\t\t\t\t// The warped pixel (which is not integer in general)\n\t\t\t\t// contributes to all the surrounding ones\n\t\t\t\tif ((uwarp >= 0.f) && (uwarp < cols_lim) && (vwarp >= 0.f) &&\n\t\t\t\t\t(vwarp < rows_lim))\n\t\t\t\t{\n\t\t\t\t\tconst int uwarp_l = uwarp;\n\t\t\t\t\tconst int uwarp_r = uwarp_l + 1;\n\t\t\t\t\tconst int vwarp_d = vwarp;\n\t\t\t\t\tconst int vwarp_u = vwarp_d + 1;\n\t\t\t\t\tconst float delta_r = float(uwarp_r) - uwarp;\n\t\t\t\t\tconst float delta_l = uwarp - float(uwarp_l);\n\t\t\t\t\tconst float delta_u = float(vwarp_u) - vwarp;\n\t\t\t\t\tconst float delta_d = vwarp - float(vwarp_d);\n\n\t\t\t\t\t// Warped pixel very close to an integer value\n\t\t\t\t\tif (abs(round(uwarp) - uwarp) + abs(round(vwarp) - vwarp) <\n\t\t\t\t\t\t0.05f)\n\t\t\t\t\t{\n\t\t\t\t\t\tdepth_warped[image_level](round(vwarp), round(uwarp)) +=\n\t\t\t\t\t\t\tdepth_w;\n\t\t\t\t\t\twacu(round(vwarp), round(uwarp)) += 1.f;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tconst float w_ur = square(delta_l) + square(delta_d);\n\t\t\t\t\t\tdepth_warped[image_level](vwarp_u, uwarp_r) +=\n\t\t\t\t\t\t\tw_ur * depth_w;\n\t\t\t\t\t\twacu(vwarp_u, uwarp_r) += w_ur;\n\n\t\t\t\t\t\tconst float w_ul = square(delta_r) + square(delta_d);\n\t\t\t\t\t\tdepth_warped[image_level](vwarp_u, uwarp_l) +=\n\t\t\t\t\t\t\tw_ul * depth_w;\n\t\t\t\t\t\twacu(vwarp_u, uwarp_l) += w_ul;\n\n\t\t\t\t\t\tconst float w_dr = square(delta_l) + square(delta_u);\n\t\t\t\t\t\tdepth_warped[image_level](vwarp_d, uwarp_r) +=\n\t\t\t\t\t\t\tw_dr * depth_w;\n\t\t\t\t\t\twacu(vwarp_d, uwarp_r) += w_dr;\n\n\t\t\t\t\t\tconst float w_dl = square(delta_r) + square(delta_u);\n\t\t\t\t\t\tdepth_warped[image_level](vwarp_d, uwarp_l) +=\n\t\t\t\t\t\t\tw_dl * depth_w;\n\t\t\t\t\t\twacu(vwarp_d, uwarp_l) += w_dl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t// Scale the averaged depth and compute spatial coordinates\n\tconst float inv_f_i = 1.f / f;\n\tfor (unsigned int u = 0; u < cols_i; u++)\n\t\tfor (unsigned int v = 0; v < rows_i; v++)\n\t\t{\n\t\t\tif (wacu(v, u) > 0.f)\n\t\t\t{\n\t\t\t\tdepth_warped[image_level](v, u) /= wacu(v, u);\n\t\t\t\txx_warped[image_level](v, u) =\n\t\t\t\t\t(u - disp_u_i) * depth_warped[image_level](v, u) * inv_f_i;\n\t\t\t\tyy_warped[image_level](v, u) =\n\t\t\t\t\t(v - disp_v_i) * depth_warped[image_level](v, u) * inv_f_i;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdepth_warped[image_level](v, u) = 0.f;\n\t\t\t\txx_warped[image_level](v, u) = 0.f;\n\t\t\t\tyy_warped[image_level](v, u) = 0.f;\n\t\t\t}\n\t\t}\n}\n\nvoid CDifodo::calculateCoord()\n{\n\tnull.resize(rows_i, cols_i);\n\tnull.fill(false);\n\tnum_valid_points = 0;\n\n\tfor (unsigned int u = 0; u < cols_i; u++)\n\t\tfor (unsigned int v = 0; v < rows_i; v++)\n\t\t{\n\t\t\tif ((depth_old[image_level](v, u)) == 0.f ||\n\t\t\t\t(depth_warped[image_level](v, u) == 0.f))\n\t\t\t{\n\t\t\t\tdepth_inter[image_level](v, u) = 0.f;\n\t\t\t\txx_inter[image_level](v, u) = 0.f;\n\t\t\t\tyy_inter[image_level](v, u) = 0.f;\n\t\t\t\tnull(v, u) = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdepth_inter[image_level](v, u) =\n\t\t\t\t\t0.5f * (depth_old[image_level](v, u) +\n\t\t\t\t\t\t\tdepth_warped[image_level](v, u));\n\t\t\t\txx_inter[image_level](v, u) =\n\t\t\t\t\t0.5f *\n\t\t\t\t\t(xx_old[image_level](v, u) + xx_warped[image_level](v, u));\n\t\t\t\tyy_inter[image_level](v, u) =\n\t\t\t\t\t0.5f *\n\t\t\t\t\t(yy_old[image_level](v, u) + yy_warped[image_level](v, u));\n\t\t\t\tnull(v, u) = false;\n\t\t\t\tif ((u > 0) && (v > 0) && (u < cols_i - 1) && (v < rows_i - 1))\n\t\t\t\t\tnum_valid_points++;\n\t\t\t}\n\t\t}\n}\n\nvoid CDifodo::calculateDepthDerivatives()\n{\n\tdt.resize(rows_i, cols_i);\n\tdt.fill(0.f);\n\tdu.resize(rows_i, cols_i);\n\tdu.fill(0.f);\n\tdv.resize(rows_i, cols_i);\n\tdv.fill(0.f);\n\n\t// Compute connectivity\n\tMatrixXf rx_ninv(rows_i, cols_i);\n\tMatrixXf ry_ninv(rows_i, cols_i);\n\trx_ninv.fill(1.f);\n\try_ninv.fill(1.f);\n\n\tfor (unsigned int u = 0; u < cols_i - 1; u++)\n\t\tfor (unsigned int v = 0; v < rows_i; v++)\n\t\t\tif (null(v, u) == false)\n\t\t\t{\n\t\t\t\trx_ninv(v, u) = sqrtf(\n\t\t\t\t\tsquare(\n\t\t\t\t\t\txx_inter[image_level](v, u + 1) -\n\t\t\t\t\t\txx_inter[image_level](v, u)) +\n\t\t\t\t\tsquare(\n\t\t\t\t\t\tdepth_inter[image_level](v, u + 1) -\n\t\t\t\t\t\tdepth_inter[image_level](v, u)));\n\t\t\t}\n\n\tfor (unsigned int u = 0; u < cols_i; u++)\n\t\tfor (unsigned int v = 0; v < rows_i - 1; v++)\n\t\t\tif (null(v, u) == false)\n\t\t\t{\n\t\t\t\try_ninv(v, u) = sqrtf(\n\t\t\t\t\tsquare(\n\t\t\t\t\t\tyy_inter[image_level](v + 1, u) -\n\t\t\t\t\t\tyy_inter[image_level](v, u)) +\n\t\t\t\t\tsquare(\n\t\t\t\t\t\tdepth_inter[image_level](v + 1, u) -\n\t\t\t\t\t\tdepth_inter[image_level](v, u)));\n\t\t\t}\n\n\t// Spatial derivatives\n\tfor (unsigned int v = 0; v < rows_i; v++)\n\t{\n\t\tfor (unsigned int u = 1; u < cols_i - 1; u++)\n\t\t\tif (null(v, u) == false)\n\t\t\t\tdu(v, u) =\n\t\t\t\t\t(rx_ninv(v, u - 1) * (depth_inter[image_level](v, u + 1) -\n\t\t\t\t\t\t\t\t\t\t  depth_inter[image_level](v, u)) +\n\t\t\t\t\t rx_ninv(v, u) * (depth_inter[image_level](v, u) -\n\t\t\t\t\t\t\t\t\t  depth_inter[image_level](v, u - 1))) /\n\t\t\t\t\t(rx_ninv(v, u) + rx_ninv(v, u - 1));\n\n\t\tdu(v, 0) = du(v, 1);\n\t\tdu(v, cols_i - 1) = du(v, cols_i - 2);\n\t}\n\n\tfor (unsigned int u = 0; u < cols_i; u++)\n\t{\n\t\tfor (unsigned int v = 1; v < rows_i - 1; v++)\n\t\t\tif (null(v, u) == false)\n\t\t\t\tdv(v, u) =\n\t\t\t\t\t(ry_ninv(v - 1, u) * (depth_inter[image_level](v + 1, u) -\n\t\t\t\t\t\t\t\t\t\t  depth_inter[image_level](v, u)) +\n\t\t\t\t\t ry_ninv(v, u) * (depth_inter[image_level](v, u) -\n\t\t\t\t\t\t\t\t\t  depth_inter[image_level](v - 1, u))) /\n\t\t\t\t\t(ry_ninv(v, u) + ry_ninv(v - 1, u));\n\n\t\tdv(0, u) = dv(1, u);\n\t\tdv(rows_i - 1, u) = dv(rows_i - 2, u);\n\t}\n\n\t// Temporal derivative\n\tfor (unsigned int u = 0; u < cols_i; u++)\n\t\tfor (unsigned int v = 0; v < rows_i; v++)\n\t\t\tif (null(v, u) == false)\n\t\t\t\tdt(v, u) = fps * (depth_warped[image_level](v, u) -\n\t\t\t\t\t\t\t\t  depth_old[image_level](v, u));\n}\n\nvoid CDifodo::computeWeights()\n{\n\tweights.resize(rows_i, cols_i);\n\tweights.fill(0.f);\n\n\t// Obtain the velocity associated to the rigid transformation estimated up\n\t// to the present level\n\tCVectorFixedFloat<6> kai_level;\n\tkai_level.setFromMatrixLike(kai_loc_old);\n\n\tMatrix4f acu_trans;\n\tacu_trans.setIdentity();\n\tfor (unsigned int i = 0; i < level; i++)\n\t\tacu_trans = transformations[i].asEigen() * acu_trans;\n\n\t// Alternative way to compute the log\n\tauto mat_aux = CMatrixDouble44(acu_trans.cast<double>().eval());\n\n\tauto trans_vec = poses::Lie::SE<3>::log(poses::CPose3D(mat_aux));\n\ttrans_vec *= fps;\n\tconst auto kai_level_acu = CVectorFixedDouble<6>(trans_vec);\n\n\tkai_level -= kai_level_acu.cast_float();\n\n\t// Parameters for the measurement error\n\tconst float f_inv = float(cols_i) / (2.f * tan(0.5f * fovh));\n\tconst float kz2 = 8.122e-12f;  // square(1.425e-5) / 25\n\n\t// Parameters for linearization error\n\tconst float kduv = 20e-5f;\n\tconst float kdt = kduv / square(fps);\n\tconst float k2dt = 5e-6f;\n\tconst float k2duv = 5e-6f;\n\n\tfor (unsigned int u = 1; u < cols_i - 1; u++)\n\t\tfor (unsigned int v = 1; v < rows_i - 1; v++)\n\t\t\tif (null(v, u) == false)\n\t\t\t{\n\t\t\t\t//\t\t\t\t\tCompute measurment error (simplified)\n\t\t\t\t//-----------------------------------------------------------------------\n\t\t\t\tconst float z = depth_inter[image_level](v, u);\n\t\t\t\tconst float inv_d = 1.f / z;\n\t\t\t\t// const float dycomp = du2(v,u)*f_inv_y*inv_d;\n\t\t\t\t// const float dzcomp = dv2(v,u)*f_inv_z*inv_d;\n\t\t\t\tconst float z2 = z * z;\n\t\t\t\tconst float z4 = z2 * z2;\n\n\t\t\t\t// const float var11 = kz2*z4;\n\t\t\t\t// const float var12 =\n\t\t\t\t// kz2*xx_inter[image_level](v,u)*z2*depth_inter[image_level](v,u);\n\t\t\t\t// const float var13 =\n\t\t\t\t// kz2*yy_inter[image_level](v,u)*z2*depth_inter[image_level](v,u);\n\t\t\t\t// const float var22 =\n\t\t\t\t// kz2*square(xx_inter[image_level](v,u))*z2;\n\t\t\t\t// const float var23 =\n\t\t\t\t// kz2*xx_inter[image_level](v,u)*yy_inter[image_level](v,u)*z2;\n\t\t\t\t// const float var33 =\n\t\t\t\t// kz2*square(yy_inter[image_level](v,u))*z2;\n\t\t\t\tconst float var44 = kz2 * z4 * square(fps);\n\t\t\t\tconst float var55 = kz2 * z4 * 0.25f;\n\t\t\t\tconst float var66 = var55;\n\n\t\t\t\t// const float j1 =\n\t\t\t\t// -2.f*inv_d*inv_d*(xx_inter[image_level](v,u)*dycomp +\n\t\t\t\t// yy_inter[image_level](v,u)*dzcomp)*(kai_level[0] +\n\t\t\t\t// yy_inter[image_level](v,u)*kai_level[4] -\n\t\t\t\t// xx_inter[image_level](v,u)*kai_level[5])\n\t\t\t\t//\t\t\t\t+ inv_d*dycomp*(kai_level[1] -\n\t\t\t\t// yy_inter[image_level](v,u)*kai_level[3]) +\n\t\t\t\t// inv_d*dzcomp*(kai_level[2] +\n\t\t\t\t// xx_inter[image_level](v,u)*kai_level[3]);\n\t\t\t\t// const float j2 = inv_d*dycomp*(kai_level[0] +\n\t\t\t\t// yy_inter[image_level](v,u)*kai_level[4] -\n\t\t\t\t// 2.f*xx_inter[image_level](v,u)*kai_level[5]) -\n\t\t\t\t// dzcomp*kai_level[3];\n\t\t\t\t// const float j3 = inv_d*dzcomp*(kai_level[0] +\n\t\t\t\t// 2.f*yy_inter[image_level](v,u)*kai_level[4] -\n\t\t\t\t// xx_inter[image_level](v,u)*kai_level[5]) +\n\t\t\t\t// dycomp*kai_level[3];\n\n\t\t\t\tconst float j4 = 1.f;\n\t\t\t\tconst float j5 =\n\t\t\t\t\txx_inter[image_level](v, u) * inv_d * inv_d * f_inv *\n\t\t\t\t\t\t(kai_level[0] +\n\t\t\t\t\t\t yy_inter[image_level](v, u) * kai_level[4] -\n\t\t\t\t\t\t xx_inter[image_level](v, u) * kai_level[5]) +\n\t\t\t\t\tinv_d * f_inv *\n\t\t\t\t\t\t(-kai_level[1] - z * kai_level[5] +\n\t\t\t\t\t\t yy_inter[image_level](v, u) * kai_level[3]);\n\t\t\t\tconst float j6 =\n\t\t\t\t\tyy_inter[image_level](v, u) * inv_d * inv_d * f_inv *\n\t\t\t\t\t\t(kai_level[0] +\n\t\t\t\t\t\t yy_inter[image_level](v, u) * kai_level[4] -\n\t\t\t\t\t\t xx_inter[image_level](v, u) * kai_level[5]) +\n\t\t\t\t\tinv_d * f_inv *\n\t\t\t\t\t\t(-kai_level[2] + z * kai_level[4] -\n\t\t\t\t\t\t xx_inter[image_level](v, u) * kai_level[3]);\n\n\t\t\t\t// error_measurement(v,u) = j1*(j1*var11+j2*var12+j3*var13) +\n\t\t\t\t// j2*(j1*var12+j2*var22+j3*var23)\n\t\t\t\t//\t\t\t\t\t\t+j3*(j1*var13+j2*var23+j3*var33) +\n\t\t\t\t// j4*j4*var44\n\t\t\t\t//+\n\t\t\t\t// j5*j5*var55 + j6*j6*var66;\n\n\t\t\t\tconst float error_m =\n\t\t\t\t\tj4 * j4 * var44 + j5 * j5 * var55 + j6 * j6 * var66;\n\n\t\t\t\t//\t\t\t\t\tCompute linearization error\n\t\t\t\t//-----------------------------------------------------------------------\n\t\t\t\tconst float ini_du = depth_old[image_level](v, u + 1) -\n\t\t\t\t\t\t\t\t\t depth_old[image_level](v, u - 1);\n\t\t\t\tconst float ini_dv = depth_old[image_level](v + 1, u) -\n\t\t\t\t\t\t\t\t\t depth_old[image_level](v - 1, u);\n\t\t\t\tconst float final_du = depth_warped[image_level](v, u + 1) -\n\t\t\t\t\t\t\t\t\t   depth_warped[image_level](v, u - 1);\n\t\t\t\tconst float final_dv = depth_warped[image_level](v + 1, u) -\n\t\t\t\t\t\t\t\t\t   depth_warped[image_level](v - 1, u);\n\n\t\t\t\tconst float dut = ini_du - final_du;\n\t\t\t\tconst float dvt = ini_dv - final_dv;\n\t\t\t\tconst float duu = du(v, u + 1) - du(v, u - 1);\n\t\t\t\tconst float dvv = dv(v + 1, u) - dv(v - 1, u);\n\t\t\t\tconst float dvu =\n\t\t\t\t\tdv(v, u + 1) -\n\t\t\t\t\tdv(v, u - 1);  // Completely equivalent to compute duv\n\n\t\t\t\tconst float error_l =\n\t\t\t\t\tkdt * square(dt(v, u)) +\n\t\t\t\t\tkduv * (square(du(v, u)) + square(dv(v, u))) +\n\t\t\t\t\tk2dt * (square(dut) + square(dvt)) +\n\t\t\t\t\tk2duv * (square(duu) + square(dvv) + square(dvu));\n\n\t\t\t\t// Weight\n\t\t\t\tweights(v, u) = sqrt(1.f / (error_m + error_l));\n\t\t\t}\n\n\t// Normalize weights in the range [0,1]\n\tconst float inv_max = 1.f / weights.maxCoeff();\n\tweights *= inv_max;\n}\n\nvoid CDifodo::solveOneLevel()\n{\n\tMatrixXf A(num_valid_points, 6);\n\tMatrixXf B(num_valid_points, 1);\n\tunsigned int cont = 0;\n\n\t// Fill the matrix A and the vector B\n\t// The order of the unknowns is (vz, vx, vy, wz, wx, wy)\n\t// The points order will be (1,1), (1,2)...(1,cols-1), (2,1),\n\t// (2,2)...(row-1,cols-1).\n\n\tconst float f_inv = float(cols_i) / (2.f * tan(0.5f * fovh));\n\n\tfor (unsigned int u = 1; u < cols_i - 1; u++)\n\t\tfor (unsigned int v = 1; v < rows_i - 1; v++)\n\t\t\tif (null(v, u) == false)\n\t\t\t{\n\t\t\t\t// Precomputed expressions\n\t\t\t\tconst float d = depth_inter[image_level](v, u);\n\t\t\t\tconst float inv_d = 1.f / d;\n\t\t\t\tconst float x = xx_inter[image_level](v, u);\n\t\t\t\tconst float y = yy_inter[image_level](v, u);\n\t\t\t\tconst float dycomp = du(v, u) * f_inv * inv_d;\n\t\t\t\tconst float dzcomp = dv(v, u) * f_inv * inv_d;\n\t\t\t\tconst float tw = weights(v, u);\n\n\t\t\t\t// Fill the matrix A\n\t\t\t\tA(cont, 0) =\n\t\t\t\t\ttw * (1.f + dycomp * x * inv_d + dzcomp * y * inv_d);\n\t\t\t\tA(cont, 1) = tw * (-dycomp);\n\t\t\t\tA(cont, 2) = tw * (-dzcomp);\n\t\t\t\tA(cont, 3) = tw * (dycomp * y - dzcomp * x);\n\t\t\t\tA(cont, 4) = tw * (y + dycomp * inv_d * y * x +\n\t\t\t\t\t\t\t\t   dzcomp * (y * y * inv_d + d));\n\t\t\t\tA(cont, 5) = tw * (-x - dycomp * (x * x * inv_d + d) -\n\t\t\t\t\t\t\t\t   dzcomp * inv_d * y * x);\n\t\t\t\tB(cont, 0) = tw * (-dt(v, u));\n\n\t\t\t\tcont++;\n\t\t\t}\n\n\t// Solve the linear system of equations using weighted least squares\n\tconst MatrixXf AtA = A.transpose() * A;\n\tconst MatrixXf AtB = A.transpose() * B;\n\tVectorXf Var = AtA.ldlt().solve(AtB);\n\n\t// Covariance matrix calculation\n\tMatrixXf res = -B;\n\tfor (unsigned int k = 0; k < 6; k++) res += Var(k) * A.col(k);\n\n\test_cov =\n\t\t(1.f / float(num_valid_points - 6)) * AtA.inverse() * res.squaredNorm();\n\n\t// Update last velocity in local coordinates\n\t// (vx, vy, vz, wx, wy, wz)\n\tkai_loc_level.fromVector(Var);\n}\n\nvoid CDifodo::odometryCalculation()\n{\n\t// Clock to measure the runtime\n\tmrpt::system::CTicTac clock;\n\tclock.Tic();\n\n\t// Build the gaussian pyramid\n\tif (fast_pyramid)\n\t\tbuildCoordinatesPyramidFast();\n\telse\n\t\tbuildCoordinatesPyramid();\n\n\t// Coarse-to-fines scheme\n\tfor (unsigned int i = 0; i < ctf_levels; i++)\n\t{\n\t\t// Previous computations\n\t\ttransformations[i].setIdentity();\n\n\t\tlevel = i;\n\t\tunsigned int s = pow(2.f, int(ctf_levels - (i + 1)));\n\t\tcols_i = cols / s;\n\t\trows_i = rows / s;\n\t\timage_level =\n\t\t\tctf_levels - i + round(log(float(m_width / cols)) / log(2.f)) - 1;\n\n\t\t// 1. Perform warping\n\t\tif (i == 0)\n\t\t{\n\t\t\tdepth_warped[image_level] = depth[image_level];\n\t\t\txx_warped[image_level] = xx[image_level];\n\t\t\tyy_warped[image_level] = yy[image_level];\n\t\t}\n\t\telse\n\t\t\tperformWarping();\n\n\t\t// 2. Calculate inter coords and find null measurements\n\t\tcalculateCoord();\n\n\t\t// 3. Compute derivatives\n\t\tcalculateDepthDerivatives();\n\n\t\t// 4. Compute weights\n\t\tcomputeWeights();\n\n\t\t// 5. Solve odometry\n\t\tif (num_valid_points > 6) solveOneLevel();\n\n\t\t// 6. Filter solution\n\t\tfilterLevelSolution();\n\t}\n\n\t// Update poses\n\tposeUpdate();\n\n\t// Save runtime\n\texecution_time = 1000.f * clock.Tac();\n}\n\nvoid CDifodo::filterLevelSolution()\n{\n\t//\t\tCalculate Eigenvalues and Eigenvectors\n\t//----------------------------------------------------------\n\tCMatrixFloat66 Bii;\n\tstd::vector<float> eigenVals;\n\n\tif (est_cov.eig_symmetric(Bii, eigenVals))\n\t{\n\t\tstd::cerr\n\t\t\t<< \"\\n Eigensolver couldn't find a solution. Pose is not updated\\n\";\n\t\treturn;\n\t}\n\n\t// First, we have to describe both the new linear and angular velocities in\n\t// the \"eigenvector\" basis\n\t//-------------------------------------------------------------------------------------------------\n\tauto kai_b = CVectorFixedFloat<6>(Bii.asEigen().colPivHouseholderQr().solve(\n\t\tkai_loc_level.asVector<Matrix<float, 6, 1>>()));\n\n\t// Second, we have to describe both the old linear and angular velocities in\n\t// the \"eigenvector\" basis\n\t//-------------------------------------------------------------------------------------------------\n\tauto kai_loc_sub = kai_loc_old.asVector<Eigen::Matrix<float, 6, 1>>();\n\n\t// Important: we have to substract the previous levels' solutions from the\n\t// old velocity.\n\tMatrix4f acu_trans;\n\tacu_trans.setIdentity();\n\tfor (unsigned int i = 0; i < level; i++)\n\t\tacu_trans = transformations[i].asEigen() * acu_trans;\n\n\tauto mat_aux = CMatrixDouble44(acu_trans.cast<double>());\n\tauto acu_trans_vec = poses::Lie::SE<3>::log(poses::CPose3D(mat_aux));\n\tacu_trans_vec *= fps;\n\tconst auto kai_level_acu = CVectorFixedDouble<6>(acu_trans_vec);\n\n\tkai_loc_sub -= kai_level_acu.asEigen().cast<float>();\n\n\t// Matrix<float, 4, 4> log_trans = fps*acu_trans.log();\n\t// kai_loc_sub(0) -= log_trans(0,3); kai_loc_sub(1) -= log_trans(1,3);\n\t// kai_loc_sub(2) -= log_trans(2,3);\n\t// kai_loc_sub(3) += log_trans(1,2); kai_loc_sub(4) -= log_trans(0,2);\n\t// kai_loc_sub(5) += log_trans(0,1);\n\n\t// Transform that local representation to the \"eigenvector\" basis\n\tconst Matrix<float, 6, 1> kai_b_old =\n\t\tBii.asEigen().colPivHouseholderQr().solve(kai_loc_sub);\n\n\t//\t\t\t\t\t\t\t\t\tFilter velocity\n\t//--------------------------------------------------------------------------------\n\tconst float cf = previous_speed_eig_weight * expf(-int(level)),\n\t\t\t\tdf = previous_speed_const_weight * expf(-int(level));\n\tMatrix<float, 6, 1> kai_b_fil;\n\tfor (unsigned int i = 0; i < 6; i++)\n\t\tkai_b_fil(i) =\n\t\t\t(kai_b.asEigen()(i) + (cf * eigenVals[i] + df) * kai_b_old(i)) /\n\t\t\t(1.f + cf * eigenVals[i] + df);\n\n\t// Transform filtered velocity to the local reference frame\n\tMatrix<float, 6, 1> kai_loc_fil =\n\t\tBii.asEigen().inverse().colPivHouseholderQr().solve(kai_b_fil);\n\n\t// Compute the rigid transformation\n\tauto aux_vel =\n\t\tmrpt::math::CVectorFixedDouble<6>(kai_loc_fil.cast<double>() / fps);\n\tconst poses::CPose3D aux2 = mrpt::poses::Lie::SE<3>::exp(aux_vel);\n\n\tCMatrixDouble44 trans;\n\taux2.getHomogeneousMatrix(trans);\n\ttransformations[level] = trans.cast_float();\n}\n\nvoid CDifodo::poseUpdate()\n{\n\t// First, compute the overall transformation\n\t//---------------------------------------------------\n\tMatrix4f acu_trans;\n\tacu_trans.setIdentity();\n\tfor (unsigned int i = 1; i <= ctf_levels; i++)\n\t\tacu_trans = transformations[i - 1].asEigen() * acu_trans;\n\n\t// Compute the new estimates in the local and absolutes reference frames\n\t//---------------------------------------------------------------------\n\tauto mat_aux = CMatrixDouble44(acu_trans.cast<double>().eval());\n\tauto acu_trans_vec = poses::Lie::SE<3>::log(poses::CPose3D(mat_aux));\n\tacu_trans_vec *= fps;\n\tconst CVectorFixedDouble<6> kai_level_acu(acu_trans_vec);\n\tkai_loc.fromVector(kai_level_acu.cast_float());\n\n\t//---------------------------------------------------------------------------------------------\n\t// Directly from Eigen:\n\t//- Eigen 3.1.0 needed for Matrix::log()\n\t//- The line \"#include <unsupported/Eigen/MatrixFunctions>\" should be\n\t// uncommented (CDifodo.h)\n\t//\n\t// Matrix<float, 4, 4> log_trans = fps*acu_trans.log();\n\t// kai_loc(0) = log_trans(0,3); kai_loc(1) = log_trans(1,3); kai_loc(2) =\n\t// log_trans(2,3);\n\t// kai_loc(3) = -log_trans(1,2); kai_loc(4) = log_trans(0,2); kai_loc(5) =\n\t// -log_trans(0,1);\n\t//---------------------------------------------------------------------------------------------\n\n\tCMatrixDouble33 inv_trans;\n\n\tcam_pose.getRotationMatrix(inv_trans);\n\tconst auto v_abs =\n\t\t(inv_trans.asEigen() *\n\t\t (kai_loc.asVector<Eigen::Matrix<double, 6, 1>>().topRows(3)))\n\t\t\t.eval();\n\tconst auto w_abs =\n\t\t(inv_trans.asEigen() *\n\t\t (kai_loc.asVector<Eigen::Matrix<double, 6, 1>>().bottomRows(3)))\n\t\t\t.eval();\n\tkai_abs.vx = v_abs.x();\n\tkai_abs.vy = v_abs.y();\n\tkai_abs.vz = v_abs.z();\n\n\tkai_abs.wx = w_abs.x();\n\tkai_abs.wy = w_abs.y();\n\tkai_abs.wz = w_abs.z();\n\n\t//\t\t\t\t\t\tUpdate poses\n\t//-------------------------------------------------------\n\tcam_oldpose = cam_pose;\n\tconst auto pose_aux = poses::CPose3D(CMatrixDouble44(acu_trans));\n\tcam_pose = cam_pose + pose_aux;\n\n\t// Compute the velocity estimate in the new ref frame (to be used by the\n\t// filter in the next iteration)\n\t//---------------------------------------------------------------------------------------------------\n\tcam_pose.getRotationMatrix(inv_trans);\n\tconst auto old_vtrans =\n\t\t(inv_trans.asEigen().inverse() *\n\t\t (kai_abs.asVector<Eigen::Matrix<double, 6, 1>>().topRows(3)))\n\t\t\t.eval();\n\tconst auto old_w =\n\t\t(inv_trans.asEigen().inverse() *\n\t\t (kai_abs.asVector<Eigen::Matrix<double, 6, 1>>().bottomRows(3)))\n\t\t\t.eval();\n\n\tkai_loc_old.vx = old_vtrans.x();\n\tkai_loc_old.vy = old_vtrans.y();\n\tkai_loc_old.vz = old_vtrans.z();\n\n\tkai_loc_old.wx = old_w.x();\n\tkai_loc_old.wy = old_w.y();\n\tkai_loc_old.wz = old_w.z();\n}\n\nvoid CDifodo::setFOV(float new_fovh, float new_fovv)\n{\n\tfovh = M_PI * new_fovh / 180.0;\n\tfovv = M_PI * new_fovv / 180.0;\n}\n\nvoid CDifodo::getPointsCoord(CMatrixFloat& x, CMatrixFloat& y, CMatrixFloat& z)\n{\n\tx.resize(rows, cols);\n\ty.resize(rows, cols);\n\tz.resize(rows, cols);\n\n\tz = depth_inter[0];\n\tx = xx_inter[0];\n\ty = yy_inter[0];\n}\n\nvoid CDifodo::getDepthDerivatives(\n\tCMatrixFloat& cur_du, CMatrixFloat& cur_dv, CMatrixFloat& cur_dt)\n{\n\tcur_du.resize(rows, cols);\n\tcur_dv.resize(rows, cols);\n\tcur_dt.resize(rows, cols);\n\n\tcur_du = du;\n\tcur_dv = dv;\n\tcur_dt = dt;\n}\n\nvoid CDifodo::getWeights(CMatrixFloat& w)\n{\n\tw.resize(rows, cols);\n\tw = weights;\n}\n", "meta": {"hexsha": "24317923cfbbd4eab46e864089e750e592db7db5", "size": 31483, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/vision/src/CDifodo.cpp", "max_stars_repo_name": "zarmomin/mrpt", "max_stars_repo_head_hexsha": "1baff7cf8ec9fd23e1a72714553bcbd88c201966", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-10T06:24:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T06:24:08.000Z", "max_issues_repo_path": "libs/vision/src/CDifodo.cpp", "max_issues_repo_name": "gao-ouyang/mrpt", "max_issues_repo_head_hexsha": "4af5fdf7e45b00be4a64c3d4f009acb9ef415ec7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/vision/src/CDifodo.cpp", "max_forks_repo_name": "gao-ouyang/mrpt", "max_forks_repo_head_hexsha": "4af5fdf7e45b00be4a64c3d4f009acb9ef415ec7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-11T02:55:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-11T02:55:04.000Z", "avg_line_length": 29.6171213547, "max_line_length": 102, "alphanum_fraction": 0.5626846234, "num_tokens": 10465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558604, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2866101450074311}}
{"text": "/*\nCopyright 2009-2021 Nicolas Colombe\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#pragma once\n\n#include <core/random.hpp>\n#include <math/polygon.hpp>\n#include <math/aabb2dpolygon.hpp>\n#include <math/math.hpp>\n\n#include <boost/random.hpp>\n#include <cstdint>\n\n\nnamespace eXl\n{\n  class Serializer;\n\n  class MathTools\n  {\n  public:\n\n    //template <typename Real>\n    //static Err Stream(Vector2<Real> const& iPoint, Serializer iStreamer);\n\n    //template <typename Real>\n    //static Err Unstream(Vector2<Real>& oPoint, Unstreamer& iUnstreamer);\n\n    //template <typename Real>\n    //static Err Stream(Polygon<Real> const& iPolygon, Streamer& iStreamer);\n    //\n    //template <typename Real>\n    //static Err Unstream(Polygon<Real>& oPolygon, Unstreamer& iUnstreamer);\n    //\n    //template <typename Real>\n    //static Err Stream(AABB2DPolygon<Real> const& iPolygon, Streamer& iStreamer);\n    //\n    //template <typename Real>\n    //static Err Unstream(AABB2DPolygon<Real>& oPolygon, Unstreamer& iUnstreamer);\n\n    //Clamp angle between 0 and 2*PI\n    inline static float ClampAngle(float iAngle)\n    {\n      int div = iAngle / (Mathf::PI * 2);\n      if(iAngle < 0)\n      {\n        --div;\n      }\n      return iAngle - div * Mathf::PI * 2;\n    }\n\n    // AngleDist between -PI and PI\n    inline static float AngleDist(float iAngle1, float iAngle2)\n    {\n      float dist = ClampAngle(iAngle1) - ClampAngle(iAngle2);\n      if(dist > Mathf::PI)\n      {\n        return 2.0 * Mathf::PI - dist;\n      }\n      else if(dist < -Mathf::PI)\n      {\n        return dist + 2.0 * Mathf::PI;\n      }\n      return dist;\n    }\n\n\n    template <typename Real>\n    static inline Vector2<Real> Perp(Vector2<Real> const& iVec)\n    {\n      return Vector2<Real>(-iVec.Y(), iVec.X());\n    }\n\n    static inline uint64_t SquaredLength(Vector2i const& iVect)\n    {\n      return (int64_t)iVect.X() * (int64_t)iVect.X() + (int64_t)iVect.Y() * (int64_t)iVect.Y();\n    }\n\n    template <typename Real>\n    static inline Vector2i ToIVec(Vector2<Real> const& iVec)\n    {\n      return Vector2i(Math<Real>::Round(iVec.X()), Math<Real>::Round(iVec.Y()));\n    }\n\n    template <typename Real>\n    static inline Vector2f ToFVec(Vector2<Real> const& iVec)\n    {\n      return Vector2f(iVec.X(), iVec.Y());\n    }\n\n    template <typename Real>\n    static inline Vector2d ToDVec(Vector2<Real> const& iVec)\n    {\n      return Vector2d(iVec.X(), iVec.Y());\n    }\n\n    template <typename Real>\n    static inline Real Sign(Real iValue)\n    {\n      return iValue > 0 ? 1 : -1;\n    }\n\n    template <typename Real1, typename Real2>\n    static inline bool NearestPointOnPoly(Vector2<Real1> const& iPoint, Polygon<Real2> const& iPoly, Real1 iMinSegLen, unsigned int &oSegNum, Vector2<Real1>& oPoint, Vector2<Real1>& oDir, bool iCheckExt = true)\n    {\n      int dummyHole;\n      Vector2<Real2> dummy;\n      return NearestPointOnPoly(iPoint,iPoly, iMinSegLen, dummy, oSegNum, dummyHole, oPoint, oDir, iCheckExt, false);\n    }\n\n    template <typename Real1, typename Real2>\n    static inline bool NearestPointOnPoly(Vector2<Real1> const& iPoint, Polygon<Real2> const& iPoly, Real1 iMinSegLen, Vector2<Real2> (&oSeg)[2], Vector2<Real1>& oPoint, Vector2<Real1>& oDir, bool iCheckExt = true)\n    {\n      int dummyHole;\n      unsigned int dummy;\n      return NearestPointOnPoly(iPoint,iPoly, iMinSegLen, oSeg, dummy, dummyHole, oPoint, oDir, iCheckExt, false);\n    }\n\n    template <typename Real1, typename Real2>\n    static inline bool NearestPointOnPoly(Vector2<Real1> const& iPoint, Polygon<Real2> const& iPoly, Real1 iMinSegLen, Vector2<Real2> (&oSeg)[2], unsigned int& oSegNum, Vector2<Real1>& oPoint, Vector2<Real1>& oDir, bool iCheckExt = true)\n    {\n      int dummyHole;\n      return NearestPointOnPoly(iPoint,iPoly, iMinSegLen, oSeg, oSegNum, dummyHole, oPoint, oDir, iCheckExt, false);\n    }\n\n    template <typename Real1, typename Real2>\n    static inline bool NearestPointOnPoly(Vector2<Real1> const& iPoint, Polygon<Real2> const& iPoly, Real1 iMinSegLen, Vector2<Real2> (&oSeg)[2], unsigned int& oSegNum, int& oHole, Vector2<Real1>& oPoint, Vector2<Real1>& oDir, bool iCheckExt = true, bool iCheckHoles = false)\n    {\n      Real1 minDist;\n      oHole = -1;\n      bool res = _NearestPointOnPoly(iPoint, iPoly.Border(), iMinSegLen, oSeg, oSegNum, oPoint, oDir, minDist, iCheckExt);\n      if(iCheckHoles)\n      {\n        for(unsigned int i = 0 ; i< iPoly.Holes().size(); ++i)\n        {\n          unsigned int segNum;\n          Vector2<Real1> point;\n          Vector2<Real2> seg[2];\n          Vector2<Real1>    dir;\n          Real1 curMin;\n          bool newRes = _NearestPointOnPoly(iPoint, iPoly.Holes()[i], iMinSegLen, seg, segNum, point, dir, curMin, iCheckExt);\n          if(newRes)\n          {\n            if(!res || curMin < minDist)\n            {\n              oHole = i;\n              res = newRes;\n              oSegNum = segNum;\n              oPoint = point;\n              oDir = dir;\n              oSeg[0] = seg[0];\n              oSeg[1] = seg[1];\n              minDist = curMin;\n            }\n          }\n        }\n      }\n      return res;\n    }\n\n    template <typename Real1, typename Real2>\n    static inline bool _NearestPointOnPoly(Vector2<Real1> const& iPoint, Vector<Vector2<Real2> > const& polyBorder, Real1 iMinSegLen, Vector2<Real2> (&oSeg)[2], unsigned int& oSegNum, Vector2<Real1>& oPoint, Vector2<Real1>& oDir, Real1& oDist, bool iCheckExt)\n    {\n      Vector2<Real1> polyCenter;\n      for(auto point : polyBorder)\n      {\n        polyCenter += Vector2<Real1>(point.X(), point.Y());\n      }\n\n      if(polyBorder.front() == polyBorder.back())\n      {\n        polyCenter -= Vector2<Real1>(polyBorder.front().X(), polyBorder.front().Y());\n        polyCenter = polyCenter / (polyBorder.size() - 1);\n      }\n      else\n      {\n        polyCenter = polyCenter / polyBorder.size();\n      }\n\n      //Vector2<Real1> iDir = polyCenter - iPoint;\n      //Real1 minDist = iDir.Normalize();\n\n      Vector2<Real1> prevPoint(polyBorder.back().X(), polyBorder.back().Y());\n\n      Vector2<Real1> iDir = polyCenter - iPoint;\n      iDir.Normalize();\n      Real1 minDist = (iPoint - prevPoint).Length() + 1;\n\n      for (unsigned int i = 0; i < polyBorder.size(); ++i)\n      {\n        Vector2<Real1> curPoint(polyBorder[i].X(), polyBorder[i].Y());\n\n        if (curPoint != prevPoint)\n        {\n          Vector2<Real1> dir = curPoint - prevPoint;\n          Vector2<Real1> extDir(MathTools::Perp(dir));\n\n          if (!iCheckExt || (iDir).Dot(extDir) < 0)\n          {\n            Real1 segLen = dir.Normalize();\n            if (segLen > iMinSegLen)\n            {\n              Vector2<Real1> prevPointOff = prevPoint + dir * 0.5 * iMinSegLen;\n              Vector2<Real1> curPointOff = curPoint - dir * 0.5 * iMinSegLen;\n              segLen -= iMinSegLen;\n              Real1 dirPoj = (iPoint - prevPointOff).Dot(dir);\n              Vector2<Real1> candidate;\n\n              if (dirPoj < -Math<Real1>::ZERO_TOLERANCE)\n              {\n                candidate = prevPointOff;\n              }\n              else if (dirPoj > segLen - Math<Real1>::ZERO_TOLERANCE)\n              {\n                candidate = curPointOff;\n              }\n              else\n              {\n                candidate = prevPointOff + (dir * dirPoj);\n              }\n\n              Real1 curDist = (candidate - iPoint).Length();\n              if (curDist < minDist)\n              {\n                oSeg[0] = Vector2<Real2>(prevPoint.X(), prevPoint.Y());\n                oSeg[1] = Vector2<Real2>(curPoint.X(), curPoint.Y());\n                if(i == 0)\n                  oSegNum = polyBorder.size() - 1;\n                else\n                  oSegNum = i - 1;\n                oPoint = candidate;\n                oDir = extDir;\n                oDir.Normalize();\n                minDist = curDist;\n              }\n            }\n          }\n        }\n\n        prevPoint = curPoint;\n      }\n\n      oDist = minDist;\n\n      if(minDist != (iPoint - polyCenter).Length())\n        return true;\n      else\n        return false;\n    }\n\n    template <typename Real>\n    static void SimplifyPolygon(Polygon<Real> const& iPoly1, double iEpsilon, Polygon<Real>& oPoly);\n\n    template <typename Real1, typename Real2>\n    static inline unsigned int FindPolyIntersection(Vector2<Real1> const& iPoint1, Vector2<Real1> const& iPoint2, Polygon<Real2> const& iPoly, Vector2<Real1>(&oPoints)[2])\n    {\n      unsigned int curInter = 0;\n      Vector<Vector2<Real2> > const& border = iPoly.Border();\n      Vector2<Real1> prevPoint(border.back().X(), border.back().Y());\n      for (unsigned int i = 0; i < border.size() && curInter < 2; ++i)\n      {\n        Vector2<Real1> curPoint(border[i].X(), border[i].Y());\n            \n        unsigned int res = Segment<Real1>::Intersect(prevPoint, curPoint, iPoint1, iPoint2, oPoints[curInter]);\n        if (res & Segmentd::PointOnSegment1)\n        {\n          if ((curInter == 0 || (oPoints[0] - oPoints[curInter]).Length() > Math<Real1>::ZERO_TOLERANCE))\n          {\n            ++curInter;\n          }\n        }\n        prevPoint = curPoint;\n      }\n      return curInter;\n    }\n\n    template <typename Real1, typename Real2>\n    static bool FindCommonSegment(Polygon<Real2> const& iPoly1, Polygon<Real2> const& iPoly2, Vector2<Real1>& oSegPt1, Vector2<Real1>& oSegPt2, Real1 iMinLen = Math<Real1>::ZERO_TOLERANCE)\n    {\n      bool foundCommon = false;\n      Vector2<Real1> prevPt1 = Vector2<Real1>(iPoly1.Border().back().X(),iPoly1.Border().back().Y());\n      for(auto curPt1I : iPoly1.Border())\n      {\n        Vector2<Real1> curPt1 = Vector2<Real1>(curPt1I.X(),curPt1I.Y());\n        if(prevPt1 != curPt1)\n        {\n          Vector2<Real1> prevPt2 = Vector2<Real1>(iPoly2.Border().back().X(), iPoly2.Border().back().Y());\n          for(auto curPt2I : iPoly2.Border())\n          {\n            Vector2<Real1> curPt2 = Vector2<Real1>(curPt2I.X(),curPt2I.Y());\n            if(prevPt2 != curPt2)\n            {\n                unsigned int res = Segment<Real1>::Intersect(prevPt1, curPt1, prevPt2, curPt2);\n                if(res & Segment<Real1>::AlignedSegments\n                && (res & Segment<Real1>::ConfoundSegments || res & Segmentd::PointOnSegments))\n                {\n                  Vector2<Real1> dir = curPt1 - prevPt1;\n                  AABB2D<Real1> box1(0.0,0.0, dir.Normalize(), 0.0);\n                  double val1 = (prevPt2 - prevPt1).Dot(dir);\n                  double val2 = (curPt2 - prevPt1).Dot(dir);\n                  AABB2D<Real1> box2 = val1 > val2 ? AABB2D<Real1>(val2, 0.0, val1, 0.0) : AABB2D<Real1>(val1, 0.0, val2, 0.0);\n                  AABB2D<Real1> result;\n                  result.SetCommonBox(box1, box2);\n                  double commonLen = result.m_Data[1].X() - result.m_Data[0].X();\n                  if(commonLen >= iMinLen)\n                  {\n                    foundCommon = true;\n                    oSegPt1 = prevPt1 + dir * result.m_Data[0].X();\n                    oSegPt2 = prevPt1 + dir * (result.m_Data[0].X() + commonLen);\n                    break;\n                  }\n                }\n            }\n            prevPt2 = curPt2;\n          }\n        }\n        if(foundCommon)\n          break;\n        prevPt1 = curPt1;\n      }\n      return foundCommon;\n    }\n\n    template <typename Real>\n    static inline Real GetAngleFromVec(Vector2<Real> const& iDir)\n    {\n      return Math<Real>::Abs(iDir.X()) < Math<Real>::EPSILON ? (iDir.Y() > 0.0 ? Math<Real>::PI * 0.5 : Math<Real>::PI * 1.5) \n        : (iDir.X() > 0.0 ? Math<Real>::ATan(iDir.Y() / iDir.X()) : Math<Real>::PI - Math<Real>::ATan(iDir.Y() / (-1.0 * iDir.X())));\n    }\n\n    template<typename Real>\n    static inline Vector2<Real> GetPerp(Vector2<Real> const& iVec)\n    {\n      return Vector2<Real>(iVec.Y() * -1.0, iVec.X());\n    }\n\n    template<typename Real>\n    static inline Vector2<Real> GetLocal(Vector2<Real> const& iBase, Vector2<Real> const& iVec)\n    {\n      return Vector2<Real>(iBase.X() * iVec.X() + iBase.Y() * iVec.Y(), iBase.X() * iVec.Y() - iBase.Y() * iVec.X());\n    }\n\n    template<typename Real>\n    static inline Vector2i RoundVector(Vector2<Real> const& iVec)\n    {\n      return Vector2i(Math<Real>::Round(iVec.X()), Math<Real>::Round(iVec.Y()));\n    }\n\n    template <typename Real>\n    static inline Real ModAngle(Real iAngle)\n    {\n      iAngle = fmod(iAngle, 2.0*Math<Real>::PI);\n      iAngle -= Mathf::PI;\n      return iAngle;\n    }\n\n    template <typename Real>\n    static inline Real RandFloatIn(Random& randGen, Real iMin, Real iMax)\n    {\n      return Real(randGen() % 10000) / 10000.0 * (iMax - iMin) + iMin;\n    };\n\n    template <typename Real>\n    static inline Real RandNormFloatIn(Random& randGen, Real iMin, Real iMax)\n    {\n      boost::random::normal_distribution<Real> distrib;\n      RandomWrapper randW(&randGen);\n      Real rangeValNorm = distrib(randW);\n      Real rangeVal = rangeValNorm * ((iMax-iMin) * 0.33);\n      Real offsetVal = rangeVal + (iMax + iMin) * 0.5;\n\n      return Math<Real>::Clamp( offsetVal , iMin, iMax);\n    };\n\n    static inline int RandIntIn(Random& randGen, int iMin, int iMax)\n    {\n      return (randGen() % (iMax - iMin)) + iMin;\n    };\n\n    static inline Vector2f Perturbate(Random& iRand, Vector2f const& iPos, float iRadius)\n    {\n      float const angle = ((iRand.Generate() % 10000) / 10000.0 - 1.0) * Mathf::PI;\n      float const dist = ((iRand.Generate() % 10000) / 10000.0 ) * iRadius;\n\n      return iPos + Vector2f(Mathd::Cos(angle), Mathd::Sin(angle)) * dist;\n    }\n\n    template <typename Real>\n    static inline Vector2<Real> const& As2DVec(Vector3<Real> const& iVec)\n    {\n      return reinterpret_cast<Vector2<Real> const&>(iVec);\n    }\n\n    template <typename Real>\n    static inline Vector2<Real>& As2DVec(Vector3<Real>& iVec)\n    {\n      return reinterpret_cast<Vector2<Real>&>(iVec);\n    }\n\n    template <typename Real>\n    static inline Vector3<Real> To3DVec(Vector2<Real> const& iVec, Real iZComp = 0)\n    {\n      return Vector3<Real>(iVec.X(), iVec.Y(), iZComp);\n    }\n\n    template <typename Real>\n    static inline Vector3<Real> const& GetPosition(Matrix4<Real> const& iMat)\n    {\n      return *reinterpret_cast<Vector3<Real> const*>(iMat.m_Data + 12);\n    }\n\n    template <typename Real>\n    static inline Vector2<Real> const& GetPosition2D(Matrix4<Real> const& iMat)\n    {\n      return *reinterpret_cast<Vector2<Real> const*>(iMat.m_Data + 12);\n    }\n\n    template <typename Real>\n    static inline Vector3<Real>& GetPosition(Matrix4<Real>& iMat)\n    {\n      return *reinterpret_cast<Vector3<Real>*>(iMat.m_Data + 12);\n    }\n\n    template <typename Real>\n    static inline Vector2<Real>& GetPosition2D(Matrix4<Real>& iMat)\n    {\n      return *reinterpret_cast<Vector2<Real>*>(iMat.m_Data + 12);\n    }\n\n    // Prereq : points have to be in CCW order\n    template <typename Real>\n    static Vector2<Real> ConeGetMidSegment(Vector2<Real> const (&iRange)[2])\n    {\n      Vector2<Real> mid = iRange[0] + iRange[1];\n      Real dist = mid.Normalize();\n      if (dist < Math<Real>::ZERO_TOLERANCE)\n      {\n        mid = GetPerp(iRange[0]);\n      }\n      mid *= Math<Real>::Sign(Segment<Real>::Cross(iRange[0], mid));\n\n      return mid;\n    }\n\n    template <typename Real>\n    static void ConeUpdateRange(Vector2<Real> const (&iRange)[2], Vector2<Real>& oMid, Real& oLowLimit)\n    {\n      oMid = ConeGetMidSegment(iRange);\n      oLowLimit = iRange[0].Dot(oMid) / iRange[0].Length();\n    }\n\n    template <typename Real>\n    static bool IsInCone(Vector2<Real> const& iDir, Vector2<Real> const& iMidSeg, Real iLowLimit, Real iEpsilon = Math<Real>::EPSILON)\n    {\n      return iDir.Dot(iMidSeg) > (iLowLimit - iEpsilon);\n    }\n\n    template <typename Real>\n    static Vector3<Real> Reflect(Vector3<Real> const& iIncomingDir, Vector3<Real> const& iNormal)\n    {\n      return iIncomingDir - iNormal * iIncomingDir.Dot(iNormal) * 2;\n    }\n\n    template <typename Real>\n    static void ClampToBox(Vector2<Real>& ioPoint, AABB2D<Real> const& iBox)\n    {\n      for (uint32_t i = 0; i < 2; ++i)\n      {\n        ioPoint.m_Data[i] = Math<Real>::Clamp(ioPoint.m_Data[i], iBox.m_Data[0].m_Data[i], iBox.m_Data[1].m_Data[i]);\n      }\n    }\n\n    //static void AlignVector(Vector2d& ioDir, Vector2i& oCanonicalVector, unsigned int iFactor)\n    //{\n    //  if (Mathd::Abs(ioDir.X()) > Mathd::ZERO_TOLERANCE)\n    //  {\n    //    if (Mathd::Abs(ioDir.Y()) > Mathd::ZERO_TOLERANCE)\n    //    {\n    //      double ratio = (ioDir.X() / ioDir.Y()));\n    //      int sign = Sign(ratio);\n    //      ratio = ratio * sign;\n    //      if (ratio > 1)\n    //      {\n    //        ratio = 1 / ratio;\n    //        unsigned int ratioI = Mathi::Round(ratio * iFactor);\n    //        oCanonicalVector = Vector2i(Sign(ioDir.X()) * iFactor, Sign(ioDir.Y()) * ratioI);\n    //      }\n    //      else\n    //      {\n    //        unsigned int ratioI = Mathi::Round(ratio * iFactor);\n    //        oCanonicalVector = Vector2i(Sign(ioDir.X()) * ratioI, Sign(ioDir.Y()) * iFactor);\n    //      }\n    //      ioDir = MathTools::ToDVec(oCanonicalVector) * ioDir.Length() / Mathd::Sqrt(ratioI*ratioI + iFactor*iFactor);\n    //      return;\n    //    }\n    //  }\n    //  ioDir = Vector2d::ZERO;\n    //  oCanonicalVector = Vector2i::ZERO;\n    //}\n    //\n    //static void AlignSegment(Vector2d& ioPoint1, Vector2d ioPoint2, unsigned int iFactor)\n    //{\n    //  \n    //}\n\n  };\n\n  //template <>\n  //EXL_MATH_API Err MathTools::Stream<float>(Vector2f const& iPoint, Serializer iStreamer);\n\n  //template <>\n  //EXL_MATH_API Err MathTools::Unstream<float>(Vector2f& oPoint, Unstreamer& iUnstreamer);\n\n  //template <>\n  //EXL_MATH_API Err MathTools::Stream<int>(Vector2i const& iPoint, Serializer iStreamer);\n\n  //template <>\n  //EXL_MATH_API Err MathTools::Unstream<int>(Vector2i& oPoint, Unstreamer& iUnstreamer);\n\n  //template <>\n  //EXL_MATH_API Err MathTools::Stream<int>(Polygoni const& iPoint, Streamer& iStreamer);\n  //\n  //template <>\n  //EXL_MATH_API Err MathTools::Unstream<int>(Polygoni& oPoint, Unstreamer& iUnstreamer);\n  //\n  //template <>\n  //EXL_MATH_API Err MathTools::Stream<int>(AABB2DPolygoni const& iPoint, Streamer& iStreamer);\n  //\n  //template <>\n  //EXL_MATH_API Err MathTools::Unstream<int>(AABB2DPolygoni& oPoint, Unstreamer& iUnstreamer);\n\n  template <>\n  EXL_MATH_API void MathTools::SimplifyPolygon<int>(Polygoni const& iPoly1, double iEpsilon, Polygoni& oPoly);\n  //template <>\n  //EXL_GEN_API void MathTools::SimplifyPolygon<float>(Polygonf const& iPoly1, double iEpsilon, Polygonf& oPoly);\n  //template <>\n  //EXL_GEN_API void MathTools::SimplifyPolygon<double>(Polygond const& iPoly1, double iEpsilon, Polygond& oPoly);\n\n  //template <typename Real>\n  //struct StreamerTemplateHandler<Polygon<Real>>\n  //{\n  //  static Err Do(Streamer& iStreamer, Polygon<Real> const* iObj)\n  //  {\n  //    return MathTools::Stream<Real>(*iObj, iStreamer);\n  //  }\n  //};\n  //\n  //template <typename Real>\n  //struct UnstreamerTemplateHandler<Polygon<Real>>\n  //{\n  //  static Err Do(Unstreamer& iUnstreamer, Polygon<Real>* iObj)\n  //  {\n  //    return MathTools::Unstream<Real>(*iObj, iUnstreamer);\n  //  }\n  //};\n\n  EXL_MATH_API uint32_t Factorial(uint32_t i);\n\n  struct EXL_MATH_API CombinationHelper_Iter\n  {\n    // Compute K amongst N with as an iterator adaptor.\n    CombinationHelper_Iter(uint32_t iSize, uint32_t iNum, bool iIsEnd);\n\n    void ComputeMaxStep(uint32_t iSize, uint32_t iNum);\n\n    Vector<uint32_t> const& operator*() const { return m_Stack; }\n\n    CombinationHelper_Iter& operator ++()\n    {\n      Advance();\n      return *this;\n    }\n\n    bool operator == (CombinationHelper_Iter const& iOther) const\n    {\n      return m_Step == iOther.m_Step;\n    }\n    bool operator != (CombinationHelper_Iter const& iOther) const\n    {\n      return !(*this == iOther);\n    }\n\n    void Advance();\n\n    Vector<uint32_t> m_Stack;\n    uint32_t m_Size;\n    uint32_t m_Num;\n    uint32_t m_Step;\n    uint32_t m_MaxStep;\n  };\n\n  struct CombinationHelper\n  {\n    CombinationHelper(uint32_t iSize, uint32_t iNum)\n      : m_Size(iSize)\n      , m_Num(iNum)\n    {\n\n    }\n\n    CombinationHelper_Iter begin() const { return CombinationHelper_Iter(m_Size, m_Num, false); }\n    CombinationHelper_Iter end() const { return CombinationHelper_Iter(m_Size, m_Num, true); }\n\n    uint32_t m_Size;\n    uint32_t m_Num;\n  };\n\n  template <typename T>\n  struct TCombinationHelper_Set_Iter\n  {\n    TCombinationHelper_Set_Iter(Vector<T> const& iElements, CombinationHelper_Iter const& iIter, bool iEnd)\n      : m_Elements(iElements)\n      , m_Iter(iIter)\n    {\n      if (iEnd)\n      {\n        m_Cur = iIter.m_Num;\n      }\n      else\n      {\n        m_Cur = 0;\n      }\n    }\n\n    T const& operator*()\n    {\n      return m_Elements[(*m_Iter)[m_Cur]];\n    }\n\n    TCombinationHelper_Set_Iter& operator ++()\n    {\n      ++m_Cur;\n      return *this;\n    }\n\n    bool operator == (TCombinationHelper_Set_Iter const& iOther) const\n    {\n      return m_Cur == iOther.m_Cur;\n    }\n    bool operator != (TCombinationHelper_Set_Iter const& iOther) const\n    {\n      return !(*this == iOther);\n    }\n\n    uint32_t m_Cur;\n    Vector<T> const& m_Elements;\n    CombinationHelper_Iter const& m_Iter;\n  };\n\n  template <typename T>\n  struct TCombinationHelper_Set\n  {\n    TCombinationHelper_Set(Vector<T> const& iElements, CombinationHelper_Iter const& iIter)\n      : m_Elements(iElements)\n      , m_Iter(iIter)\n    {\n\n    }\n\n    TCombinationHelper_Set_Iter<T> begin() const { return TCombinationHelper_Set_Iter<T>(m_Elements, m_Iter, false); }\n    TCombinationHelper_Set_Iter<T> end() const { return TCombinationHelper_Set_Iter<T>(m_Elements, m_Iter, true); }\n\n    Vector<T> const& m_Elements;\n    CombinationHelper_Iter const& m_Iter;\n  };\n\n  template <typename T>\n  struct TCombinationHelper_Iter\n  {\n    TCombinationHelper_Iter(Vector<T> const& iElements, uint32_t iNum, bool iEnd)\n      : m_Elements(iElements)\n      , m_Iter(iElements.size(), iNum, iEnd)\n    {\n\n    }\n\n    TCombinationHelper_Set<T> operator*()\n    {\n      return TCombinationHelper_Set<T>(m_Elements, m_Iter);\n    }\n\n    TCombinationHelper_Iter& operator ++()\n    {\n      ++m_Iter;\n      return *this;\n    }\n\n    bool operator == (TCombinationHelper_Iter const& iOther) const\n    {\n      return m_Iter == iOther.m_Iter;\n    }\n    bool operator != (TCombinationHelper_Iter const& iOther) const\n    {\n      return !(*this == iOther);\n    }\n\n    Vector<T> const& m_Elements;\n    CombinationHelper_Iter m_Iter;\n  };\n\n  template <typename T>\n  struct TCombinationHelper\n  {\n    TCombinationHelper(Vector<T> const& iElements, uint32_t iNum)\n      : m_Elements(iElements)\n      , m_Num(iNum)\n    {\n\n    }\n\n    TCombinationHelper_Iter<T> begin() const { return TCombinationHelper_Iter<T>(m_Elements, m_Num, false); }\n    TCombinationHelper_Iter<T> end() const { return TCombinationHelper_Iter<T>(m_Elements, m_Num, true); }\n\n    Vector<T> const& m_Elements;\n    uint32_t m_Num;\n  };\n}\n", "meta": {"hexsha": "b6c3462d39dceea5fce3e84cc2ced49064f8a040", "size": 23908, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/math/mathtools.hpp", "max_stars_repo_name": "eXl-Nic/eXl", "max_stars_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/math/mathtools.hpp", "max_issues_repo_name": "eXl-Nic/eXl", "max_issues_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/math/mathtools.hpp", "max_forks_repo_name": "eXl-Nic/eXl", "max_forks_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_forks_repo_licenses": ["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.9765517241, "max_line_length": 460, "alphanum_fraction": 0.6120545424, "num_tokens": 6717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.28661014500743104}}
{"text": "// The code is open source under the MIT license.\n// Copyright 2019-2020, Phillip Keldenich, TU Braunschweig, Algorithms Group\n// https://ibr.cs.tu-bs.de/alg\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy of\n// this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to\n// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n// of the Software, and to permit persons to whom the Software is furnished to do\n// 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// Created by Phillip Keldenich on 2019-09-23.\n//\n\n#pragma once\n\n#include <gmpxx.h>\n#include <mpfr.h>\n\n#include <type_traits>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <utility>\n#include <limits>\n#include <climits>\n#include <vector>\n\n#include <cassert>\n#include <climits>\n#include <cstddef>\n#include <cstdint>\n#include <cmath>\n\n#include <boost/io/ios_state.hpp>\n#include <boost/config.hpp>\n\n#include \"ivarp/rounding.hpp\"\n#include \"ivarp/bool.hpp\"\n#include \"ivarp/metaprogramming.hpp\"\n#include \"number/fwd.hpp\"\n#include \"number/device_compat.hpp\"\n#include \"number/exact_less_than.hpp\"\n\nnamespace ivarp {\n    /// A traits template that defines methods for getting lower and\n    /// upper bounds as well as possible/definite undefinedness.\n    template<typename NT> struct NumberTraits {\n        static constexpr bool is_number = false;\n    };\n\n    /// A type and an object that can be passed to intervals to set the corresponding bound to infinity;\n    /// needed for intervals if the underlying number type has no infinities.\n    struct InfinityType {\n        constexpr IVARP_HD InfinityType operator-() const noexcept { return InfinityType{}; }\n    };\n\n    static IVARP_CUDA_DEVICE_OR_CONSTEXPR InfinityType infinity{};\n\n    template<typename Number> IVARP_HD constexpr static inline std::enable_if_t<!std::is_floating_point<Number>::value, bool>\n        is_finite(const Number&) noexcept\n    {\n        return true;\n    }\n\n    template<typename Number> IVARP_HD static inline std::enable_if_t<std::is_floating_point<Number>::value, bool>\n        is_finite(Number n) noexcept\n    {\n        return IVARP_NOCUDA_USE_STD isfinite(n);\n    }\n\n    template<typename Number> IVARP_HD static inline bool possibly_undefined(const Number& n) {\n        return NumberTraits<Number>::possibly_undefined(n);\n    }\n\n    template<typename Number> IVARP_HD static inline bool definitely_defined(const Number& n) {\n        return !NumberTraits<Number>::possibly_undefined(n);\n    }\n\n    template<typename Number>\n        static inline IVARP_HD std::enable_if_t<NumberTraits<Number>::allows_cuda, typename NumberTraits<Number>::BoundType> lb(const Number& n)\n    {\n        return NumberTraits<Number>::lb(n);\n    }\n\n    template<typename Number>\n        static inline IVARP_H std::enable_if_t<!NumberTraits<Number>::allows_cuda, typename NumberTraits<Number>::BoundType> lb(const Number& n)\n    {\n        return NumberTraits<Number>::lb(n);\n    }\n\n    template<typename Number>\n        static inline IVARP_HD std::enable_if_t<NumberTraits<Number>::allows_cuda, typename NumberTraits<Number>::BoundType> ub(const Number& n)\n    {\n        return NumberTraits<Number>::ub(n);\n    }\n\n    template<typename Number>\n        static inline IVARP_H std::enable_if_t<!NumberTraits<Number>::allows_cuda, typename NumberTraits<Number>::BoundType> ub(const Number& n)\n    {\n        return NumberTraits<Number>::ub(n);\n    }\n\n    template<typename IntType> using IsIntegral = std::integral_constant<bool,\n        std::is_integral<BareType<IntType>>::value || std::is_same<BareType<IntType>, BigInt>::value\n    >;\n\n    template<typename T> struct IsRationalImpl : std::false_type {};\n    template<typename A> struct IsRationalImpl<__gmp_expr<mpq_t, A>> : std::true_type {};\n\n    template<typename NumType> using IsNumber = std::integral_constant<bool,\n        NumberTraits<BareType<NumType>>::is_number>;\n\n    template<bool IsNumber, typename NumType> struct IsCUDANumberImpl : std::false_type {};\n    template<typename NumType> struct IsCUDANumberImpl<true, NumType> : std::integral_constant<bool, NumberTraits<NumType>::allows_cuda> {};\n    template<typename NumType> using IsCUDANumber = IsCUDANumberImpl<IsNumber<NumType>::value, NumType>;\n\n    template<typename T> using IsIntOrRational = std::integral_constant<bool,\n            IsIntegral<T>::value || IsRational<T>::value>;\n\n    template<typename T, bool B = IsNumber<T>::value> struct IsIntervalType : std::false_type {};\n    template<typename T> struct IsIntervalType<T,true> : std::integral_constant<bool, NumberTraits<T>::is_interval> {};\n\n    /// An interval class that also keeps track of definedness issues.\n    template<typename NumberType> class Interval;\n\n    // Intervals of float, double and Rational type.\n    using IFloat  = Interval<float>;\n    using IDouble = Interval<double>;\n    using IRational = Interval<Rational>;\n\n    /**\n     * @brief Generate a (canonicalized) rational number from one or two integers.\n     * Compared to the native GMP interface, this provides two benefits:\n     * - It canonicalizes the number; failure to do so can results in difficult-to-diagnose bugs.\n     * - It works with _all_ integral types including [unsigned] long long and std::[u]int64_t.\n     * There also are versions where one or both of the arguments are BigInt.\n     * @return The rational\n     */\n    template<typename IntegralType1, std::enable_if_t<IsIntegral<IntegralType1>::value,int> = 0>\n        static inline Rational rational(IntegralType1 num);\n    template<typename IntegralType1, typename IntegralType2>\n        static inline std::enable_if_t<IsIntegral<IntegralType1>::value && IsIntegral<IntegralType2>::value, Rational>\n            rational(IntegralType1 num, IntegralType2 denom);\n\n    // a metafunction that computes the promoted number type for a set of argument types:\n    // computations are done, unless additional promotions to intervals occur due to some operations, using\n    // the number type with the highest rank between all arguments.\n    // If a promotion to intervals occurs, it uses the interval version of the basic number type.\n    // Rank is determined as follows:\n    //  - Any interval type has higher rank than any number type. In particular, passing one float interval and\n    //    a rational parameter leads to the computation being done on float intervals.\n    //  - More precise number types have higher rank.\n    template<typename Arg1, typename... Args> struct NumberTypePromotion;\n    template<typename... Args> using Promote = typename NumberTypePromotion<BareType<Args>...>::type;\n//  template<typename TargetType, typename SourceType> static inline\n//      TargetType convert_number(const SourceType& source);\n}\n\n#include \"number/mpfr.hpp\"\n#include \"number/interval.hpp\"\n#include \"number/traits.hpp\"\n#include \"number/rational.hpp\"\n#include \"number/fixed_point_bounds.hpp\"\n#include \"number/fixed_point_bounds_sqrt.hpp\"\n#include \"number/fixed_point_bounds_sin.hpp\"\n#include \"number/fixed_point_bounds_cos.hpp\"\n#include \"number/float_interval_ops.hpp\"\n#include \"number/interval_comparisons.hpp\"\n#include \"number/bounded_rational.hpp\"\n#include \"number/type_conversions.hpp\"\n#include \"number/minmax.hpp\"\n#include \"number/literals.hpp\"\n#include \"number/factorize.hpp\"\n", "meta": {"hexsha": "cd56ca99059194f24e434b27055c3f70e28da2b0", "size": 8010, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ivarp/include/ivarp/number.hpp", "max_stars_repo_name": "phillip-keldenich/squares-in-disk", "max_stars_repo_head_hexsha": "501ebeb00b909b9264a9611fd63e082026cdd262", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ivarp/include/ivarp/number.hpp", "max_issues_repo_name": "phillip-keldenich/squares-in-disk", "max_issues_repo_head_hexsha": "501ebeb00b909b9264a9611fd63e082026cdd262", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ivarp/include/ivarp/number.hpp", "max_forks_repo_name": "phillip-keldenich/squares-in-disk", "max_forks_repo_head_hexsha": "501ebeb00b909b9264a9611fd63e082026cdd262", "max_forks_repo_licenses": ["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.8342245989, "max_line_length": 144, "alphanum_fraction": 0.734082397, "num_tokens": 1821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.28661013172967786}}
{"text": "/*\n *  The MIT License (MIT)\n *\n *  Copyright (c) 2015 MRL-SPL RoboCup Team\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\n\n/* \n * File:   Chain.cpp\n * Author: <a href=\"a.sharpasand@mrl-spl.ir\">Mohammad Ali Sharpasand</a>\n *\n * Created on March 17, 2016\n */\n\n#include \"Chain.hpp\"\n#include \"Angle.hpp\"\n#include \"Utility.hpp\"\n\n#include <stdexcept>\n#include <vector>\n#include <armadillo>\n#include <ceres/ceres.h>\nusing namespace BipedLibrary;\nusing namespace BipedLibrary::Utility;\nusing ceres::CostFunction;\nusing ceres::SizedCostFunction;\nusing ceres::Problem;\nusing ceres::Solver;\nusing ceres::Solve;\n\nChain::Chain(vec3 const posi_body_body, mat33 const ori_body) :\nposi_body_body_(posi_body_body),\nori_body_(ori_body)\n{\n\n}\n\nvec3 Chain::posi_body_body(int frame) const\n{\n    return ori_body_ * position_base_base(frame) + posi_body_body_;\n}\n\nmat33 const& Chain::ori_body() const\n{\n    return ori_body_;\n}\n\nvec3 Chain::posi_end_last_last() const\n{\n\treturn posi_end_last_last_;\n}\nmat33 Chain::ori_end_last() const\n{\n\treturn ori_end_last_;\n}\n\nChain& Chain::setPosi_body_body(vec3 const& posi_body_body)\n{\n    \n    posi_body_body_ = posi_body_body;\n    return *this;\n}\n\nChain& Chain::setOri_body(mat33 const& ori_body)\n{\n    ori_body_ = ori_body;\n    return *this;\n}\n\nChain& Chain::setPosi_end_last_last(vec3 const& posi_end_last_last)\n{\n\tposi_end_last_last_ = posi_end_last_last;\n\treturn *this;\n}\n\nChain& Chain::setOri_end_last(mat33 const& ori_end_last)\n{\n\tori_end_last_ = ori_end_last;\n\treturn *this;\n}\n\nvec3 Chain::position_end_body_body() const\n{\n\tmat33 const ori_last_base = orientation_base();\n\tvec3 const posi_end_base_base = position_base_base() + ori_last_base * posi_end_last_last_;\n\treturn posi_body_body_ + ori_body_ * posi_end_base_base;\n}\n\nvec3 Chain::position_base_base(int frame) const\n{\n    if(frame == -1)\n        frame = size() - 1;\n   \n    if(frame < 0 || (size_t)frame >= size())\n        throw(std::out_of_range(\"Index out of range in BipedLibrary::Chain::position_base_base(int)\"));\n    \n    if(frame == 0)\n        return position_pre_pre(frame);\n    \n    return position_base_base(frame - 1) + orientation_base(frame - 1) * position_pre_pre(frame);\n}\n\nvec3 Chain::position_body_body(int frame) const\n{\n\treturn posi_body_body_ + ori_body_ * position_base_base(frame);\n}\n\nvec3 Chain::position_pre_pre(int i) const\n{\n    vec3 output;\n\n    try\n    {\n        output <<   at(i).r()                       << endr\n               << - at(i).d() * at(i).alpha().sin() << endr\n               <<   at(i).d() * at(i).alpha().cos() << endr;\n    }\n    catch(std::out_of_range &)\n    {\n        throw(std::out_of_range(\"Out of range index in Chain::position_pre_pre(int).\"));\n    }\n    \n    return output;\n}\n\nvec3 Chain::position_com(int frame) const\n{\n    // FIXME: This is not actually COM! Be warned!\n    return vec3({at(frame).r() / 2.f, 0.f, 0.f});\n}\n\nmat33 Chain::orientation_end_body() const\n{\n\treturn ori_body_ * orientation_base() * ori_end_last_;\n\n}\n\nmat33 Chain::orientation_base(int frame) const\n{\n    if(frame == -1)\n        frame = size() - 1;\n    \n    if(frame < 0 || (size_t)frame >= size())\n        throw(std::out_of_range(\"Index out of range in BipedLibrary::Chain::orientation_base(int)\"));\n\n    if (frame == 0)\n        return orientation_pre(frame);\n    else\n        return orientation_base(frame-1) * orientation_pre(frame);\n    \n}\n\nmat33 Chain::orientation_body(int frame) const\n{\n\treturn ori_body_ * orientation_base(frame);\n}\n\n// TODO: This should be in DHFrame class\nmat33 Chain::orientation_pre(int i) const\n{\n    mat33 output;\n    Angle theta,alpha;\n    theta = at(i).theta();\n    alpha = at(i).alpha();\n    try\n    {\n        output  << theta.cos()               << -theta.sin()              << 0            << endr\n                << theta.sin() * alpha.cos() << theta.cos() * alpha.cos() << -alpha.sin() << endr\n\t            << theta.sin() * alpha.sin() << theta.cos() * alpha.sin() <<  alpha.cos() << endr;\n    }\n    catch(std::out_of_range &)\n    {\n        throw(std::out_of_range(\"Out of range index in Chain::orientation_pre(int).\"));\n    }\n    \n    return output;\n\n}\n\nmat66 Chain::jacobi_base(int frame, vec3 target) const\n{\n    mat66 jacobi = zeros(6, 6);\n    vec3 const z = {0, 0, 1};\n    for (int i=0; i<=frame; i++)\n    {\n        vec3 const z_i_base = orientation_base(i) * z;\n        vec3 const r_frame_i_base = position_base_base(frame) - position_base_base(i) + orientation_base(frame) * target;\n        jacobi.col(i).rows(0, 2) = crossProductMatrix(z_i_base) * r_frame_i_base;\n        jacobi.col(i).rows(3, 5) = z_i_base;\n    }\n\n    return jacobi;\n}\n\nmat66 Chain::jacobi_body(int frame, vec3 target) const\n{\n\tmat66 doubleOrientation = zeros(6, 6);\n\tdoubleOrientation(span(0, 2), span(0, 2)) = ori_body();\n\tdoubleOrientation(span(3, 5), span(3, 5)) = ori_body();\n\n\treturn doubleOrientation * jacobi_base(frame, target);\n}\n\nbool Chain::solveForJointAngles(vec3 const& posi_end_body, mat33 ori_end_body)\n{\n//\tgoogle::InitGoogleLogging(\"\");\n\n\tclass IKCostFunction : public CostFunction\n\t{\n\t public:\n\t\tIKCostFunction(Chain& chain, vec3 const& posi_end_body, mat33 ori_end_body)\n\t \t : chain_(chain),\n\t\t   posi_end_body_(posi_end_body),\n\t\t   ori_end_body_(ori_end_body)\n\t {\n\t\tmutable_parameter_block_sizes()->push_back(chain.size());\n\n\n\n\t   set_num_residuals(6);\n\t }\n\n\t  virtual ~IKCostFunction() {}\n\n\t  virtual bool Evaluate(double const* const* parameters,\n\t                        double* residuals,\n\t                        double** jacobians) const\n\t  {\n\t\t  int i = 0;\n\t\t  for(DHFrame& frame : chain_)\n\t\t  {\n\t\t\t  frame.setTheta(parameters[0][i]);\n\t\t\t  i++;\n\t\t  }\n\n\t\t  vec3 const posiRes = chain_.position_end_body_body() - posi_end_body_;\n\t\t  for(int i = 0; i < 3; i++)\n\t\t\t  residuals[i] = posiRes(i);\n\n\t\t  mat33 const  oriResMat = ori_end_body_.t() * chain_.orientation_end_body();\n\t\t  vec3 const oriRes = Utility::rotationMatrixToAxisAngle(oriResMat).asAVector();\n\n//\t\t  vec3 const oriRes = Utility::rotationMatrixToAxisAngle(chain_.orientation_end_body()).asAVector() - Utility::rotationMatrixToAxisAngle(ori_end_body_).asAVector();\n\t\t  std::cout << \"oriRes: \" << oriRes << std::endl;\n\n\t\t  for(int i = 0; i < 3; i++)\n\t\t\t  residuals[i + 3] = oriRes(i);\n\n\n\t\t\tif (jacobians != NULL && jacobians[0] != NULL)\n\t\t\t{\n\t\t\t\tmat66 jacob = chain_.jacobi_body(5, chain_.posi_end_last_last());\n\t\t\t\tstd::cout << \"yagjouni: \" << jacob << std::endl;\n\t\t\t\tfor(int i = 0; i < 6; i++)\n\t\t\t\t\tfor(int j = 0; j < 6; j++)\n\t\t\t\t\t\tjacobians[0][i * 6 + j] = jacob(i, j);\n\n\t\t\t}\n\t\t\treturn true;\n\t  }\n\t private:\n\t  Chain& chain_;\n\t  vec3 posi_end_body_;\n\t  mat33 ori_end_body_;\n\t};\n\n\n\tdouble joints[size()];\n\tstd::vector<double*> parameters;\n\tparameters.push_back(joints);\n\tint i = 0;\n\tfor(iterator ii = begin(); ii < end(); ii++, i++)\n\t\tjoints[i] = ii->theta().toFloat();\n\n\tProblem problem;\n\tCostFunction *costFunction = new IKCostFunction(*this, posi_end_body, ori_end_body);\n\n\tproblem.AddResidualBlock(costFunction, NULL, parameters);\n\n\tSolver::Options options;\n\toptions.minimizer_progress_to_stdout = true;\n\toptions.trust_region_strategy_type = ceres::LEVENBERG_MARQUARDT;\n\toptions.jacobi_scaling = true;\n\toptions.check_gradients = true;\n\tSolver::Summary summary;\n\tSolve(options, &problem, &summary);\n\tstd::cout << summary.BriefReport() << \"\\n\";\n\n\tfor(unsigned i = 0; i < size(); i++)\n\t\tat(i).setTheta(parameters.at(0)[i]);\n\n\treturn true;\n}\n", "meta": {"hexsha": "480f75e9ce1ace6bfe0566f076b27f2d39e5a3b9", "size": 8408, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Chain.cpp", "max_stars_repo_name": "mrlspl/biped-library", "max_stars_repo_head_hexsha": "158c2017990a124ac9e6f78b29efd68ea3bda240", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-06-23T21:36:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-23T21:36:34.000Z", "max_issues_repo_path": "src/Chain.cpp", "max_issues_repo_name": "mrlspl/biped-library", "max_issues_repo_head_hexsha": "158c2017990a124ac9e6f78b29efd68ea3bda240", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Chain.cpp", "max_forks_repo_name": "mrlspl/biped-library", "max_forks_repo_head_hexsha": "158c2017990a124ac9e6f78b29efd68ea3bda240", "max_forks_repo_licenses": ["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.8626198083, "max_line_length": 168, "alphanum_fraction": 0.6653187441, "num_tokens": 2284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2865734165545495}}
{"text": "/*\n * Copyright (c) 2011-2016, Graphics Lab, Georgia Tech Research Corporation\n * Copyright (c) 2011-2016, Humanoid Lab, Georgia Tech Research Corporation\n * Copyright (c) 2016, Personal Robotics Lab, Carnegie Mellon University\n * All rights reserved.\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// Algorithm details and publications: http://www.golems.org/node/1570\n\n#include \"dart/planning/Path.hpp\"\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <Eigen/Geometry>\n\nusing namespace std;\nusing namespace Eigen;\n\nnamespace dart {\nnamespace planning {\n\nclass LinearPathSegment : public PathSegment\n{\npublic:\n\tLinearPathSegment(const Eigen::VectorXd &start, const Eigen::VectorXd &end) :\n    PathSegment((end-start).norm()),\n\t\tstart(start),\n    end(end)\n\t{\n\t}\n\n\tEigen::VectorXd getConfig(double s) const {\n\t\ts /= length;\n\t\ts = std::max(0.0, std::min(1.0, s));\n\t\treturn (1.0 - s) * start + s * end;\n\t}\n\n\tEigen::VectorXd getTangent(double /* s */) const {\n\t\treturn (end - start) / length;\n\t}\n\n\tEigen::VectorXd getCurvature(double /* s */) const {\n\t\treturn Eigen::VectorXd::Zero(start.size());\n\t}\n\n\tlist<double> getSwitchingPoints() const {\n\t\treturn list<double>();\n\t}\n\n\tLinearPathSegment* clone() const {\n\t\treturn new LinearPathSegment(*this);\n\t}\n\nprivate:\n\tEigen::VectorXd start;\n\tEigen::VectorXd end;\n};\n\n\nclass CircularPathSegment : public PathSegment\n{\npublic:\n\tCircularPathSegment(const Eigen::VectorXd &start, const Eigen::VectorXd &intersection, const Eigen::VectorXd &end, double maxDeviation) {\n\t\tif((intersection - start).norm() < 0.000001 || (end - intersection).norm() < 0.000001) {\n\t\t\tlength = 0.0;\n\t\t\tradius = 1.0;\n\t\t\tcenter = intersection;\n\t\t\tx = Eigen::VectorXd::Zero(start.size());\n\t\t\ty = Eigen::VectorXd::Zero(start.size());\n\t\t\treturn;\n\t\t}\n\n\t\tconst Eigen::VectorXd startDirection = (intersection - start).normalized();\n\t\tconst Eigen::VectorXd endDirection = (end - intersection).normalized();\n\n\t\tif((startDirection - endDirection).norm() < 0.000001) {\n\t\t\tlength = 0.0;\n\t\t\tradius = 1.0;\n\t\t\tcenter = intersection;\n\t\t\tx = Eigen::VectorXd::Zero(start.size());\n\t\t\ty = Eigen::VectorXd::Zero(start.size());\n\t\t\treturn;\n\t\t}\n\n    // const double startDistance = (start - intersection).norm();\n    // const double endDistance = (end - intersection).norm();\n\n\t\tdouble distance = std::min((start - intersection).norm(), (end - intersection).norm());\n\t\tconst double angle = acos(startDirection.dot(endDirection));\n\n\t\tdistance = std::min(distance, maxDeviation * sin(0.5 * angle) / (1.0 - cos(0.5 * angle)));  // enforce max deviation\n\n\t\tradius = distance / tan(0.5 * angle);\n\t\tlength = angle * radius;\n\n\t\tcenter = intersection + (endDirection - startDirection).normalized() * radius / cos(0.5 * angle);\n\t\tx = (intersection - distance * startDirection - center).normalized();\n\t\ty = startDirection;\n\n\t\t//debug\n\t\tdouble dotStart = startDirection.dot((intersection - getConfig(0.0)).normalized());\n\t\tdouble dotEnd = endDirection.dot((getConfig(length) - intersection).normalized());\n    if(std::abs(dotStart - 1.0) > 0.0001 || std::abs(dotEnd - 1.0) > 0.0001) {\n\t\t\tstd::cout << \"Error\\n\";\n\t\t}\n\t}\n\n\tEigen::VectorXd getConfig(double s) const {\n\t\tconst double angle = s / radius;\n\t\treturn center + radius * (x * cos(angle) + y * sin(angle));\n\t}\n\n\tEigen::VectorXd getTangent(double s) const {\n\t\tconst double angle = s / radius;\n\t\treturn - x * sin(angle) + y * cos(angle);\n\t}\n\n\tEigen::VectorXd getCurvature(double s) const {\n\t\tconst double angle = s / radius;\n\t\treturn - 1.0 / radius * (x * cos(angle) + y * sin(angle));\n\t}\n\n\tlist<double> getSwitchingPoints() const {\n\t\tlist<double> switchingPoints;\n\t\tconst double dim = x.size();\n\t\tfor(unsigned int i = 0; i < dim; i++) {\n\t\t\tdouble switchingAngle = atan2(y[i], x[i]);\n\t\t\tif(switchingAngle < 0.0) {\n\t\t\t\tswitchingAngle += M_PI;\n\t\t\t}\n\t\t\tconst double switchingPoint = switchingAngle * radius;\n\t\t\tif(switchingPoint < length) {\n\t\t\t\tswitchingPoints.push_back(switchingPoint);\n\t\t\t}\n\t\t}\n\t\tswitchingPoints.sort();\n\t\treturn switchingPoints;\n\t}\n\n\tCircularPathSegment* clone() const {\n\t\treturn new CircularPathSegment(*this);\n\t}\n\nprivate:\n\tdouble radius;\n\tEigen::VectorXd center;\n\tEigen::VectorXd x;\n\tEigen::VectorXd y;\n};\n\n\n\nPath::Path(const list<VectorXd> &path, double maxDeviation) :\n\tlength(0.0)\n{\n\tif(path.size() < 2)\n\t\treturn;\n\tlist<VectorXd>::const_iterator config1 = path.begin();\n\tlist<VectorXd>::const_iterator config2 = config1;\n  ++config2;\n\tlist<VectorXd>::const_iterator config3;\n\tVectorXd startConfig = *config1;\n\twhile(config2 != path.end()) {\n\t\tconfig3 = config2;\n    ++config3;\n\t\tif(maxDeviation > 0.0 && config3 != path.end()) {\n\t\t\tCircularPathSegment* blendSegment = new CircularPathSegment(0.5 * (*config1 + *config2), *config2, 0.5 * (*config2 + *config3), maxDeviation);\n\t\t\tVectorXd endConfig = blendSegment->getConfig(0.0);\n\t\t\tif((endConfig - startConfig).norm() > 0.000001) {\n\t\t\t\tpathSegments.push_back(new LinearPathSegment(startConfig, endConfig));\n\t\t\t}\n\t\t\tpathSegments.push_back(blendSegment);\n\t\t\t\n\t\t\tstartConfig = blendSegment->getConfig(blendSegment->getLength());\n\n\t\t\t//debug\n\t\t\tif(((endConfig - *config1).norm() > 0.000001 && (*config2 - endConfig).norm() > 0.000001\n        && std::abs((endConfig - *config1).normalized().dot((*config2 - endConfig).normalized()) - 1.0) > 0.000001)\n\t\t\t\t|| ((startConfig - *config2).norm() > 0.000001 && (*config3 - startConfig).norm() > 0.000001\n        && std::abs((startConfig - *config2).normalized().dot((*config3 - startConfig).normalized()) - 1.0) > 0.000001)) {\n\t\t\t\t\tcout << \"error\" << endl;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tpathSegments.push_back(new LinearPathSegment(startConfig, *config2));\n\t\t\tstartConfig = *config2;\n\t\t}\n\t\tconfig1 = config2;\n    ++config2;\n\t}\n\n\t// create list of switching point candidates, calculate total path length and absolute positions of path segments\n  for(list<PathSegment*>::iterator segment = pathSegments.begin(); segment != pathSegments.end(); ++segment) {\n\t\t(*segment)->position = length;\n\t\tlist<double> localSwitchingPoints = (*segment)->getSwitchingPoints();\n    for(list<double>::const_iterator point = localSwitchingPoints.begin(); point != localSwitchingPoints.end(); ++point) {\n\t\t\tswitchingPoints.push_back(make_pair(length + *point, false));\n\t\t}\n\t\tlength += (*segment)->getLength();\n\t\tswitchingPoints.push_back(make_pair(length, true));\n\t}\n\tswitchingPoints.pop_back();\n}\n\nPath::Path(const Path &path) :\n\tlength(path.length),\n\tswitchingPoints(path.switchingPoints)\n{\n  for(list<PathSegment*>::const_iterator it = path.pathSegments.begin(); it != path.pathSegments.end(); ++it) {\n\t\tpathSegments.push_back((*it)->clone());\n\t}\n}\n\nPath::~Path() {\n  for(list<PathSegment*>::iterator it = pathSegments.begin(); it != pathSegments.end(); ++it) {\n\t\tdelete *it;\n\t}\n}\n\ndouble Path::getLength() const {\n\treturn length;\n}\n\nPathSegment* Path::getPathSegment(double &s) const {\n\tlist<PathSegment*>::const_iterator it = pathSegments.begin();\n\tlist<PathSegment*>::const_iterator next = it;\n  ++next;\n\twhile(next != pathSegments.end() && s >= (*next)->position) {\n\t\tit = next;\n    ++next;\n\t}\n\ts -= (*it)->position;\n\treturn *it;\n}\n\nVectorXd Path::getConfig(double s) const {\n\tconst PathSegment* pathSegment = getPathSegment(s);\n\treturn pathSegment->getConfig(s);\n}\n\nVectorXd Path::getTangent(double s) const {\n\tconst PathSegment* pathSegment = getPathSegment(s);\n\treturn pathSegment->getTangent(s);\n}\n\nVectorXd Path::getCurvature(double s) const {\n\tconst PathSegment* pathSegment = getPathSegment(s);\n\treturn pathSegment->getCurvature(s);\n}\n\ndouble Path::getNextSwitchingPoint(double s, bool &discontinuity) const {\n\tlist<pair<double, bool> >::const_iterator it = switchingPoints.begin();\n\twhile(it != switchingPoints.end() && it->first <= s) {\n    ++it;\n\t}\n\tif(it == switchingPoints.end()) {\n\t\tdiscontinuity = true;\n\t\treturn length;\n\t}\n\telse {\n\t\tdiscontinuity = it->second;\n\t\treturn it->first;\n\t}\n}\n\nlist<pair<double, bool> > Path::getSwitchingPoints() const {\n\treturn switchingPoints;\n}\n\n} // namespace planning\n} // namespace dart\n", "meta": {"hexsha": "eb3aaf8fd9e463f8e7b8527f9657374762d9aa02", "size": 9366, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dart/planning/Path.cpp", "max_stars_repo_name": "purewind7/CS7496", "max_stars_repo_head_hexsha": "ca0b8376db400f265d9515d8307d928590a1569a", "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": "dart/planning/Path.cpp", "max_issues_repo_name": "purewind7/CS7496", "max_issues_repo_head_hexsha": "ca0b8376db400f265d9515d8307d928590a1569a", "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/planning/Path.cpp", "max_forks_repo_name": "purewind7/CS7496", "max_forks_repo_head_hexsha": "ca0b8376db400f265d9515d8307d928590a1569a", "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.4295302013, "max_line_length": 145, "alphanum_fraction": 0.6900491138, "num_tokens": 2414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2865734096611813}}
{"text": "#include <boost/program_options.hpp>\n#include <chrono>\n#include <cmath>\n#include <map>\n#include <random>\n#include <set>\n\n#include \"../tools/util.hpp\"\n#include \"bases.hpp\"\n#include \"bilinear_form.hpp\"\n\nint bsd_rnd() {\n  static unsigned int seed = 0;\n  int a = 1103515245;\n  int c = 12345;\n  unsigned int m = 2147483648;\n  return (seed = (a * seed + c) % m);\n}\n\nusing namespace Time;\nusing namespace datastructures;\n\nnamespace po = boost::program_options;\n\ntemplate <typename I>\nlong long MaxIndex(int level);\n\ntemplate <>\nlong long MaxIndex<OrthonormalWaveletFn>(int level) {\n  return std::pow(2, level);\n}\n\ntemplate <>\nlong long MaxIndex<ThreePointWaveletFn>(int level) {\n  return std::pow(2, level - 1);\n}\n\ntemplate <typename I>\nTreeVector<I> GradedTree(I *meta_root, int max_lvl, bool towards_origin,\n                         double theta = 0.5) {\n  TreeVector<I> result(meta_root);\n  result.DeepRefine(/* call_filter */\n                    [&](auto psi) {\n                      if (towards_origin)\n                        return (psi->level() <= max_lvl &&\n                                psi->index() <=\n                                    std::pow(1 + theta, psi->level()));\n                      else\n                        return (psi->level() <= max_lvl &&\n                                psi->index() >=\n                                    MaxIndex<I>(psi->level()) -\n                                        std::pow(1 + theta, psi->level()));\n                    }, /* call_postprocess */\n                    [&](auto nv) {\n                      nv->set_random();\n                      nv->node()->Refine();\n                    });\n  return result;\n}\nauto Now() { return std::chrono::high_resolution_clock::now(); }\ndouble Duration(std::chrono::high_resolution_clock::time_point start) {\n  return std::chrono::duration<double>(Now() - start).count();\n}\n\ntemplate <template <typename, typename> class Operator, typename WaveletBasisIn,\n          typename WaveletBasisOut>\nvoid TimeBilForm(std::string name,\n                 const datastructures::TreeVector<WaveletBasisIn> &vec_in,\n                 const datastructures::TreeVector<WaveletBasisOut> &vec_out) {\n  double time_create = 0, time_apply = 0, time_apply_upp = 0,\n         time_apply_low = 0;\n  size_t iters = 0;\n  while (time_apply < 20 && iters < 30) {\n    ++iters;\n    auto time_start = Now();\n    auto bilform = CreateBilinearForm<Operator>(vec_in, vec_out);\n    time_create += Duration(time_start);\n\n    time_start = Now();\n    bilform.Apply();\n    time_apply += Duration(time_start);\n\n    time_start = Now();\n    bilform.ApplyUpp();\n    time_apply_upp += Duration(time_start);\n\n    time_start = Now();\n    bilform.ApplyLow();\n    time_apply_low += Duration(time_start);\n  }\n  std::cout << \"\\n\\ttime-\" << name << \"-create: \" << time_create / iters;\n  std::cout << \"\\n\\ttime-\" << name << \"-apply: \" << time_apply / iters;\n  std::cout << \"\\n\\ttime-\" << name << \"-apply-upp: \" << time_apply_upp / iters;\n  std::cout << \"\\n\\ttime-\" << name << \"-apply-low: \" << time_apply_low / iters;\n  std::cout << std::flush;\n}\n\nint main(int argc, char *argv[]) {\n  double theta = 0.3;\n  bool print_mesh = false;\n  size_t max_iter = 999;\n  boost::program_options::options_description adapt_optdesc(\"Refine options\");\n  adapt_optdesc.add_options()(\"theta\", po::value<double>(&theta))(\n      \"print_mesh\", po::value<bool>(&print_mesh))(\"max_iter\",\n                                                  po::value<size_t>(&max_iter));\n  boost::program_options::options_description cmdline_options;\n  cmdline_options.add(adapt_optdesc);\n\n  po::variables_map vm;\n  po::store(po::command_line_parser(argc, argv).options(cmdline_options).run(),\n            vm);\n  po::notify(vm);\n  std::cout << \"Adaptive options:\" << std::endl;\n  std::cout << \"\\ttheta: \" << theta << std::endl << std::endl;\n  std::cout << std::endl;\n\n  Bases B;\n  int iter = 0;\n  bool uniform_refine = theta >= 1;\n  while (iter < max_iter) {\n    std::cout << \"iter: \" << ++iter;\n\n    if (uniform_refine) {\n      TreeVector<OrthonormalWaveletFn> ortho_tree(B.ortho_tree.meta_root());\n      TreeVector<ThreePointWaveletFn> threept_tree(\n          B.three_point_tree.meta_root());\n      ortho_tree.UniformRefine(std::array{iter}, /* grow_tree */ true);\n      threept_tree.UniformRefine(std::array{iter}, /* grow_tree */ true);\n      std::cout << \"\\n\\tortho-tree-size: \" << ortho_tree.Bfs().size()\n                << \"\\n\\tthreept-tree-size: \" << threept_tree.Bfs().size()\n                << \"\\n\\ttotal-memory-kB: \" << getmem() << std::flush;\n      TimeBilForm<MassOperator>(\"M-o-o\", ortho_tree, ortho_tree);\n      TimeBilForm<MassOperator>(\"M-t-o\", threept_tree, ortho_tree);\n      TimeBilForm<TransportOperator>(\"T-t-o\", threept_tree, ortho_tree);\n    } else {\n      // Local refine.\n      auto ortho_tree_0 =\n          GradedTree(B.ortho_tree.meta_root(), iter, true, theta);\n      auto ortho_tree_1 =\n          GradedTree(B.ortho_tree.meta_root(), iter, false, theta);\n      auto threept_tree_0 =\n          GradedTree(B.three_point_tree.meta_root(), iter, true, theta);\n      auto threept_tree_1 =\n          GradedTree(B.three_point_tree.meta_root(), iter, false, theta);\n      std::cout << \"\\n\\tortho-tree-0-size: \" << ortho_tree_0.Bfs().size()\n                << \"\\n\\tortho-tree-1-size: \" << ortho_tree_1.Bfs().size()\n                << \"\\n\\tthreept-tree-0-size: \" << threept_tree_0.Bfs().size()\n                << \"\\n\\tthreept-tree-1-size: \" << threept_tree_1.Bfs().size()\n                << \"\\n\\ttotal-memory-kB: \" << getmem() << std::flush;\n\n      TimeBilForm<MassOperator>(\"M-o0-o0\", ortho_tree_0, ortho_tree_0);\n      // TimeBilForm<MassOperator>(\"M-o0-o1\", ortho_tree_0, ortho_tree_1);\n      // TimeBilForm<MassOperator>(\"M-t0-t0\", threept_tree_0, threept_tree_0);\n      // TimeBilForm<MassOperator>(\"M-t0-t1\", threept_tree_0, threept_tree_1);\n      // TimeBilForm<MassOperator>(\"M-o0-t0\", ortho_tree_0, threept_tree_0);\n      // TimeBilForm<MassOperator>(\"M-o0-t1\", ortho_tree_0, threept_tree_1);\n      TimeBilForm<MassOperator>(\"M-t0-o0\", threept_tree_0, ortho_tree_0);\n      TimeBilForm<MassOperator>(\"M-t0-o1\", threept_tree_0, ortho_tree_1);\n\n      TimeBilForm<TransportOperator>(\"T-t0-o0\", threept_tree_0, ortho_tree_0);\n      TimeBilForm<TransportOperator>(\"T-t0-o1\", threept_tree_0, ortho_tree_1);\n      // TimeBilForm<TransportOperator>(\"T-t1-o0\", threept_tree_1,\n      // ortho_tree_0);\n\n      if (print_mesh) {\n        std::cout << \"\\n\\tortho-tree-0: [\";\n        for (auto nv : ortho_tree_0.Bfs())\n          std::cout << \"(\" << nv->node()->level() << \",\" << nv->node()->center()\n                    << \"),\";\n        std::cout << \"]\" << std::flush;\n        std::cout << \"\\n\\tortho-tree-1: [\";\n        for (auto nv : ortho_tree_1.Bfs())\n          std::cout << \"(\" << nv->node()->level() << \",\" << nv->node()->center()\n                    << \"),\";\n        std::cout << \"]\" << std::flush;\n        std::cout << \"\\n\\tthreept-tree-0: [\";\n        for (auto nv : threept_tree_0.Bfs())\n          std::cout << \"(\" << nv->node()->level() << \",\" << nv->node()->center()\n                    << \"),\";\n        std::cout << \"]\" << std::flush;\n        std::cout << \"\\n\\tthreept-tree-1: [\";\n        for (auto nv : threept_tree_1.Bfs())\n          std::cout << \"(\" << nv->node()->level() << \",\" << nv->node()->center()\n                    << \"),\";\n        std::cout << \"]\" << std::flush;\n      }\n    }\n    std::cout << std::endl;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "cefbe31825567120409811c5ee65774be3201392", "size": 7456, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/time/bilinear_form_performance.cpp", "max_stars_repo_name": "rvanvenetie/spacetime", "max_stars_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/time/bilinear_form_performance.cpp", "max_issues_repo_name": "rvanvenetie/spacetime", "max_issues_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/time/bilinear_form_performance.cpp", "max_forks_repo_name": "rvanvenetie/spacetime", "max_forks_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_forks_repo_licenses": ["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.8333333333, "max_line_length": 80, "alphanum_fraction": 0.5716201717, "num_tokens": 2048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.28649188721673646}}
{"text": "// graph-tool -- a general graph modification and manipulation thingy\n//\n// Copyright (C) 2006-2018 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        parallel_vertex_loop\n            (g,\n             [&](auto v)\n             {\n                 embed_map[v].clear();\n                 for (auto& e : embedding[v])\n                     embed_map[v].push_back(edge_index[e]);\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\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(), std::placeholders::_1, gi.get_vertex_index(),\n                       gi.get_edge_index(), std::placeholders::_2, std::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": "f339835ea40663e44830bd5a3b79d4c44f16d139", "size": 3982, "ext": "cc", "lang": "C++", "max_stars_repo_path": "graph-tool-2.27/src/graph/topology/graph_planar.cc", "max_stars_repo_name": "Znigneering/CSCI-3154", "max_stars_repo_head_hexsha": "bc318efc73d2a80025b98f5b3e4f7e4819e952e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "graph-tool-2.27/src/graph/topology/graph_planar.cc", "max_issues_repo_name": "Znigneering/CSCI-3154", "max_issues_repo_head_hexsha": "bc318efc73d2a80025b98f5b3e4f7e4819e952e4", "max_issues_repo_licenses": ["MIT"], "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-2.27/src/graph/topology/graph_planar.cc", "max_forks_repo_name": "Znigneering/CSCI-3154", "max_forks_repo_head_hexsha": "bc318efc73d2a80025b98f5b3e4f7e4819e952e4", "max_forks_repo_licenses": ["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.8738738739, "max_line_length": 92, "alphanum_fraction": 0.6496735309, "num_tokens": 905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.28631293892047366}}
{"text": "#pragma once\n#include <boost/function.hpp>\n#include <Eigen/Dense>\n#include <boost/shared_ptr.hpp>\n/*\n * Numerical derivatives\n */\n\nnamespace sco {\nusing boost::function;\nusing Eigen::VectorXd;\nusing Eigen::MatrixXd;\nclass ScalarOfVector;\nclass VectorOfVector;\nclass MatrixOfVector;\ntypedef boost::shared_ptr<ScalarOfVector> ScalarOfVectorPtr;\ntypedef boost::shared_ptr<VectorOfVector> VectorOfVectorPtr;\ntypedef boost::shared_ptr<MatrixOfVector> MatrixOfVectorPtr;\n\nclass ScalarOfVector {\npublic:\n  virtual double operator()(const VectorXd& x) const = 0;\n  double call(const VectorXd& x) const {return operator()(x);}\n  virtual ~ScalarOfVector() {}\n\n  typedef function<double(VectorXd)> boost_func;\n  static ScalarOfVectorPtr construct(const boost_func&);\n  //  typedef VectorXd (*c_func)(const VectorXd&);\n  //  static ScalarOfVectorPtr construct(const c_func&);\n\n};\nclass VectorOfVector {\npublic:\n  virtual VectorXd operator()(const VectorXd& x) const = 0;\n  VectorXd call(const VectorXd& x) const {return operator()(x);}\n  virtual ~VectorOfVector() {}\n\n  typedef function<VectorXd(VectorXd)> boost_func;\n  static VectorOfVectorPtr construct(const boost_func&);\n  //  typedef VectorXd (*c_func)(const VectorXd&);\n  //  static VectorOfVectorPtr construct(const c_func&);\n\n};\nclass MatrixOfVector {\npublic:\n  virtual MatrixXd operator()(const VectorXd& x) const = 0;\n  MatrixXd call(const VectorXd& x) const {return operator()(x);}\n  virtual ~MatrixOfVector() {}\n\n  typedef function<MatrixXd(VectorXd)> boost_func;\n  static MatrixOfVectorPtr construct(const boost_func&);\n  //  typedef VectorMatrixXd (*c_func)(const VectorXd&);\n  //  static MatrixOfVectorPtr construct(const c_func&);\n};\n\n\nVectorXd calcForwardNumGrad(const ScalarOfVector& f, const VectorXd& x, double epsilon);\nMatrixXd calcForwardNumJac(const VectorOfVector& f, const VectorXd& x, double epsilon);\nvoid calcGradAndDiagHess(const ScalarOfVector& f, const VectorXd& x, double epsilon,\n    double& y, VectorXd& grad, VectorXd& hess);\nvoid calcGradHess(ScalarOfVectorPtr f, const VectorXd& x, double epsilon,\n    double& y, VectorXd& grad, MatrixXd& hess);\nVectorOfVectorPtr forwardNumGrad(ScalarOfVectorPtr f, double epsilon);\nMatrixOfVectorPtr forwardNumJac(VectorOfVectorPtr f, double epsilon);\n\n\n\n}\n", "meta": {"hexsha": "090a859e956a6aba4ba91b002e2849454ba387cf", "size": 2269, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/sco/num_diff.hpp", "max_stars_repo_name": "HARPLab/trajopt", "max_stars_repo_head_hexsha": "40e2260d8f1e4d0a6a7a8997927bd65e5f36c3a4", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 250.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T04:38:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T15:52:54.000Z", "max_issues_repo_path": "src/sco/num_diff.hpp", "max_issues_repo_name": "HARPLab/trajopt", "max_issues_repo_head_hexsha": "40e2260d8f1e4d0a6a7a8997927bd65e5f36c3a4", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2015-08-19T13:14:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T08:08:26.000Z", "max_forks_repo_path": "src/sco/num_diff.hpp", "max_forks_repo_name": "HARPLab/trajopt", "max_forks_repo_head_hexsha": "40e2260d8f1e4d0a6a7a8997927bd65e5f36c3a4", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 118.0, "max_forks_repo_forks_event_min_datetime": "2015-01-08T16:06:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T11:44:00.000Z", "avg_line_length": 32.884057971, "max_line_length": 88, "alphanum_fraction": 0.765976201, "num_tokens": 552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.2863129389204736}}
{"text": "//  (C) Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_TOOLS_NEWTON_SOLVER_HPP\n#define BOOST_MATH_TOOLS_NEWTON_SOLVER_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n#include <boost/multiprecision/detail/number_base.hpp> // test for multiprecision types.\n#include <boost/type_traits/is_complex.hpp> // test for complex types\n\n#include <iostream>\n#include <utility>\n#include <boost/config/no_tr1/cmath.hpp>\n#include <stdexcept>\n\n#include <boost/math/tools/config.hpp>\n#include <boost/cstdint.hpp>\n#include <boost/assert.hpp>\n#include <boost/throw_exception.hpp>\n\n#ifdef BOOST_MSVC\n#pragma warning(push)\n#pragma warning(disable: 4512)\n#endif\n#include <boost/math/tools/tuple.hpp>\n#ifdef BOOST_MSVC\n#pragma warning(pop)\n#endif\n\n#include <boost/math/special_functions/sign.hpp>\n#include <boost/math/tools/toms748_solve.hpp>\n#include <boost/math/policies/error_handling.hpp>\n\nnamespace boost{ namespace math{ namespace tools{\n\nnamespace detail{\n\nnamespace dummy{\n\n   template<int n, class T>\n   typename T::value_type get(const T&) BOOST_MATH_NOEXCEPT(T);\n}\n\ntemplate <class Tuple, class T>\nvoid unpack_tuple(const Tuple& t, T& a, T& b) BOOST_MATH_NOEXCEPT(T)\n{\n   using dummy::get;\n   // Use ADL to find the right overload for get:\n   a = get<0>(t);\n   b = get<1>(t);\n}\ntemplate <class Tuple, class T>\nvoid unpack_tuple(const Tuple& t, T& a, T& b, T& c) BOOST_MATH_NOEXCEPT(T)\n{\n   using dummy::get;\n   // Use ADL to find the right overload for get:\n   a = get<0>(t);\n   b = get<1>(t);\n   c = get<2>(t);\n}\n\ntemplate <class Tuple, class T>\ninline void unpack_0(const Tuple& t, T& val) BOOST_MATH_NOEXCEPT(T)\n{\n   using dummy::get;\n   // Rely on ADL to find the correct overload of get:\n   val = get<0>(t);\n}\n\ntemplate <class T, class U, class V>\ninline void unpack_tuple(const std::pair<T, U>& p, V& a, V& b) BOOST_MATH_NOEXCEPT(T)\n{\n   a = p.first;\n   b = p.second;\n}\ntemplate <class T, class U, class V>\ninline void unpack_0(const std::pair<T, U>& p, V& a) BOOST_MATH_NOEXCEPT(T)\n{\n   a = p.first;\n}\n\ntemplate <class F, class T>\nvoid handle_zero_derivative(F f,\n                            T& last_f0,\n                            const T& f0,\n                            T& delta,\n                            T& result,\n                            T& guess,\n                            const T& min,\n                            const T& max) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n{\n   if(last_f0 == 0)\n   {\n      // this must be the first iteration, pretend that we had a\n      // previous one at either min or max:\n      if(result == min)\n      {\n         guess = max;\n      }\n      else\n      {\n         guess = min;\n      }\n      unpack_0(f(guess), last_f0);\n      delta = guess - result;\n   }\n   if(sign(last_f0) * sign(f0) < 0)\n   {\n      // we've crossed over so move in opposite direction to last step:\n      if(delta < 0)\n      {\n         delta = (result - min) / 2;\n      }\n      else\n      {\n         delta = (result - max) / 2;\n      }\n   }\n   else\n   {\n      // move in same direction as last step:\n      if(delta < 0)\n      {\n         delta = (result - max) / 2;\n      }\n      else\n      {\n         delta = (result - min) / 2;\n      }\n   }\n}\n\n} // namespace\n\ntemplate <class F, class T, class Tol, class Policy>\nstd::pair<T, T> bisect(F f, T min, T max, Tol tol, boost::uintmax_t& max_iter, const Policy& pol) BOOST_NOEXCEPT_IF(policies::is_noexcept_error_policy<Policy>::value && BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n{\n   T fmin = f(min);\n   T fmax = f(max);\n   if(fmin == 0)\n   {\n      max_iter = 2;\n      return std::make_pair(min, min);\n   }\n   if(fmax == 0)\n   {\n      max_iter = 2;\n      return std::make_pair(max, max);\n   }\n\n   //\n   // Error checking:\n   //\n   static const char* function = \"boost::math::tools::bisect<%1%>\";\n   if(min >= max)\n   {\n      return boost::math::detail::pair_from_single(policies::raise_evaluation_error(function,\n         \"Arguments in wrong order in boost::math::tools::bisect (first arg=%1%)\", min, pol));\n   }\n   if(fmin * fmax >= 0)\n   {\n      return boost::math::detail::pair_from_single(policies::raise_evaluation_error(function,\n         \"No change of sign in boost::math::tools::bisect, either there is no root to find, or there are multiple roots in the interval (f(min) = %1%).\", fmin, pol));\n   }\n\n   //\n   // Three function invocations so far:\n   //\n   boost::uintmax_t count = max_iter;\n   if(count < 3)\n      count = 0;\n   else\n      count -= 3;\n\n   while(count && (0 == tol(min, max)))\n   {\n      T mid = (min + max) / 2;\n      T fmid = f(mid);\n      if((mid == max) || (mid == min))\n         break;\n      if(fmid == 0)\n      {\n         min = max = mid;\n         break;\n      }\n      else if(sign(fmid) * sign(fmin) < 0)\n      {\n         max = mid;\n         fmax = fmid;\n      }\n      else\n      {\n         min = mid;\n         fmin = fmid;\n      }\n      --count;\n   }\n\n   max_iter -= count;\n\n#ifdef BOOST_MATH_INSTRUMENT\n   std::cout << \"Bisection iteration, final count = \" << max_iter << std::endl;\n\n   static boost::uintmax_t max_count = 0;\n   if(max_iter > max_count)\n   {\n      max_count = max_iter;\n      std::cout << \"Maximum iterations: \" << max_iter << std::endl;\n   }\n#endif\n\n   return std::make_pair(min, max);\n}\n\ntemplate <class F, class T, class Tol>\ninline std::pair<T, T> bisect(F f, T min, T max, Tol tol, boost::uintmax_t& max_iter)  BOOST_NOEXCEPT_IF(policies::is_noexcept_error_policy<policies::policy<> >::value && BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n{\n   return bisect(f, min, max, tol, max_iter, policies::policy<>());\n}\n\ntemplate <class F, class T, class Tol>\ninline std::pair<T, T> bisect(F f, T min, T max, Tol tol) BOOST_NOEXCEPT_IF(policies::is_noexcept_error_policy<policies::policy<> >::value && BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n{\n   boost::uintmax_t m = (std::numeric_limits<boost::uintmax_t>::max)();\n   return bisect(f, min, max, tol, m, policies::policy<>());\n}\n\n\ntemplate <class F, class T>\nT newton_raphson_iterate(F f, T guess, T min, T max, int digits, boost::uintmax_t& max_iter) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n{\n   BOOST_MATH_STD_USING\n\n   T f0(0), f1, last_f0(0);\n   T result = guess;\n\n   T factor = static_cast<T>(ldexp(1.0, 1 - digits));\n   T delta = tools::max_value<T>();\n   T delta1 = tools::max_value<T>();\n   T delta2 = tools::max_value<T>();\n\n   boost::uintmax_t count(max_iter);\n\n   do{\n      last_f0 = f0;\n      delta2 = delta1;\n      delta1 = delta;\n      detail::unpack_tuple(f(result), f0, f1);\n      --count;\n      if(0 == f0)\n         break;\n      if(f1 == 0)\n      {\n         // Oops zero derivative!!!\n#ifdef BOOST_MATH_INSTRUMENT\n         std::cout << \"Newton iteration, zero derivative found\" << std::endl;\n#endif\n         detail::handle_zero_derivative(f, last_f0, f0, delta, result, guess, min, max);\n      }\n      else\n      {\n         delta = f0 / f1;\n      }\n#ifdef BOOST_MATH_INSTRUMENT\n      std::cout << \"Newton iteration, delta = \" << delta << std::endl;\n#endif\n      if(fabs(delta * 2) > fabs(delta2))\n      {\n         // last two steps haven't converged.\n         T shift = (delta > 0) ? (result - min) / 2 : (result - max) / 2;\n         if ((result != 0) && (fabs(shift) > fabs(result)))\n         {\n            delta = sign(delta) * result; // protect against huge jumps!\n         }\n         else\n            delta = shift;\n         // reset delta1/2 so we don't take this branch next time round:\n         delta1 = 3 * delta;\n         delta2 = 3 * delta;\n      }\n      guess = result;\n      result -= delta;\n      if(result <= min)\n      {\n         delta = 0.5F * (guess - min);\n         result = guess - delta;\n         if((result == min) || (result == max))\n            break;\n      }\n      else if(result >= max)\n      {\n         delta = 0.5F * (guess - max);\n         result = guess - delta;\n         if((result == min) || (result == max))\n            break;\n      }\n      // update brackets:\n      if(delta > 0)\n         max = guess;\n      else\n         min = guess;\n   }while(count && (fabs(result * factor) < fabs(delta)));\n\n   max_iter -= count;\n\n#ifdef BOOST_MATH_INSTRUMENT\n   std::cout << \"Newton Raphson iteration, final count = \" << max_iter << std::endl;\n\n   static boost::uintmax_t max_count = 0;\n   if(max_iter > max_count)\n   {\n      max_count = max_iter;\n      std::cout << \"Maximum iterations: \" << max_iter << std::endl;\n   }\n#endif\n\n   return result;\n}\n\ntemplate <class F, class T>\ninline T newton_raphson_iterate(F f, T guess, T min, T max, int digits) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n{\n   boost::uintmax_t m = (std::numeric_limits<boost::uintmax_t>::max)();\n   return newton_raphson_iterate(f, guess, min, max, digits, m);\n}\n\nnamespace detail{\n\n   struct halley_step\n   {\n      template <class T>\n      static T step(const T& /*x*/, const T& f0, const T& f1, const T& f2) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(T))\n      {\n         using std::fabs;\n         T denom = 2 * f0;\n         T num = 2 * f1 - f0 * (f2 / f1);\n         T delta;\n\n         BOOST_MATH_INSTRUMENT_VARIABLE(denom);\n         BOOST_MATH_INSTRUMENT_VARIABLE(num);\n\n         if((fabs(num) < 1) && (fabs(denom) >= fabs(num) * tools::max_value<T>()))\n         {\n            // possible overflow, use Newton step:\n            delta = f0 / f1;\n         }\n         else\n            delta = denom / num;\n         return delta;\n      }\n   };\n\n   template <class Stepper, class F, class T>\n   T second_order_root_finder(F f, T guess, T min, T max, int digits, boost::uintmax_t& max_iter) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n   {\n      BOOST_MATH_STD_USING\n\n         T f0(0), f1, f2;\n      T result = guess;\n\n      T factor = ldexp(static_cast<T>(1.0), 1 - digits);\n      T delta = (std::max)(T(10000000 * guess), T(10000000));  // arbitarily large delta\n      T last_f0 = 0;\n      T delta1 = delta;\n      T delta2 = delta;\n      bool out_of_bounds_sentry = false;\n\n#ifdef BOOST_MATH_INSTRUMENT\n      std::cout << \"Second order root iteration, limit = \" << factor << std::endl;\n#endif\n\n      boost::uintmax_t count(max_iter);\n\n      do{\n         last_f0 = f0;\n         delta2 = delta1;\n         delta1 = delta;\n         detail::unpack_tuple(f(result), f0, f1, f2);\n         --count;\n\n         BOOST_MATH_INSTRUMENT_VARIABLE(f0);\n         BOOST_MATH_INSTRUMENT_VARIABLE(f1);\n         BOOST_MATH_INSTRUMENT_VARIABLE(f2);\n\n         if(0 == f0)\n            break;\n         if(f1 == 0)\n         {\n            // Oops zero derivative!!!\n#ifdef BOOST_MATH_INSTRUMENT\n            std::cout << \"Second order root iteration, zero derivative found\" << std::endl;\n#endif\n            detail::handle_zero_derivative(f, last_f0, f0, delta, result, guess, min, max);\n         }\n         else\n         {\n            if(f2 != 0)\n            {\n               delta = Stepper::step(result, f0, f1, f2);\n               if(delta * f1 / f0 < 0)\n               {\n                  // Oh dear, we have a problem as Newton and Halley steps\n                  // disagree about which way we should move.  Probably\n                  // there is cancelation error in the calculation of the\n                  // Halley step, or else the derivatives are so small\n                  // that their values are basically trash.  We will move\n                  // in the direction indicated by a Newton step, but\n                  // by no more than twice the current guess value, otherwise\n                  // we can jump way out of bounds if we're not careful.\n                  // See https://svn.boost.org/trac/boost/ticket/8314.\n                  delta = f0 / f1;\n                  if(fabs(delta) > 2 * fabs(guess))\n                     delta = (delta < 0 ? -1 : 1) * 2 * fabs(guess);\n               }\n            }\n            else\n               delta = f0 / f1;\n         }\n#ifdef BOOST_MATH_INSTRUMENT\n         std::cout << \"Second order root iteration, delta = \" << delta << std::endl;\n#endif\n         T convergence = fabs(delta / delta2);\n         if((convergence > 0.8) && (convergence < 2))\n         {\n            // last two steps haven't converged.\n            delta = (delta > 0) ? (result - min) / 2 : (result - max) / 2;\n            if ((result != 0) && (fabs(delta) > result))\n               delta = sign(delta) * result; // protect against huge jumps!\n            // reset delta2 so that this branch will *not* be taken on the\n            // next iteration:\n            delta2 = delta * 3;\n            delta1 = delta * 3;\n            BOOST_MATH_INSTRUMENT_VARIABLE(delta);\n         }\n         guess = result;\n         result -= delta;\n         BOOST_MATH_INSTRUMENT_VARIABLE(result);\n\n         // check for out of bounds step:\n         if(result < min)\n         {\n            T diff = ((fabs(min) < 1) && (fabs(result) > 1) && (tools::max_value<T>() / fabs(result) < fabs(min)))\n               ? T(1000)\n               : (fabs(min) < 1) && (fabs(tools::max_value<T>() * min) < fabs(result))\n               ? ((min < 0) != (result < 0)) ? -tools::max_value<T>() : tools::max_value<T>() : T(result / min);\n            if(fabs(diff) < 1)\n               diff = 1 / diff;\n            if(!out_of_bounds_sentry && (diff > 0) && (diff < 3))\n            {\n               // Only a small out of bounds step, lets assume that the result\n               // is probably approximately at min:\n               delta = 0.99f * (guess - min);\n               result = guess - delta;\n               out_of_bounds_sentry = true; // only take this branch once!\n            }\n            else\n            {\n               delta = (guess - min) / 2;\n               result = guess - delta;\n               if((result == min) || (result == max))\n                  break;\n            }\n         }\n         else if(result > max)\n         {\n            T diff = ((fabs(max) < 1) && (fabs(result) > 1) && (tools::max_value<T>() / fabs(result) < fabs(max))) ? T(1000) : T(result / max);\n            if(fabs(diff) < 1)\n               diff = 1 / diff;\n            if(!out_of_bounds_sentry && (diff > 0) && (diff < 3))\n            {\n               // Only a small out of bounds step, lets assume that the result\n               // is probably approximately at min:\n               delta = 0.99f * (guess - max);\n               result = guess - delta;\n               out_of_bounds_sentry = true; // only take this branch once!\n            }\n            else\n            {\n               delta = (guess - max) / 2;\n               result = guess - delta;\n               if((result == min) || (result == max))\n                  break;\n            }\n         }\n         // update brackets:\n         if(delta > 0)\n            max = guess;\n         else\n            min = guess;\n      } while(count && (fabs(result * factor) < fabs(delta)));\n\n      max_iter -= count;\n\n#ifdef BOOST_MATH_INSTRUMENT\n      std::cout << \"Second order root iteration, final count = \" << max_iter << std::endl;\n#endif\n\n      return result;\n   }\n\n}\n\ntemplate <class F, class T>\nT halley_iterate(F f, T guess, T min, T max, int digits, boost::uintmax_t& max_iter) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n{\n   return detail::second_order_root_finder<detail::halley_step>(f, guess, min, max, digits, max_iter);\n}\n\ntemplate <class F, class T>\ninline T halley_iterate(F f, T guess, T min, T max, int digits) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n{\n   boost::uintmax_t m = (std::numeric_limits<boost::uintmax_t>::max)();\n   return halley_iterate(f, guess, min, max, digits, m);\n}\n\nnamespace detail{\n\n   struct schroder_stepper\n   {\n      template <class T>\n      static T step(const T& x, const T& f0, const T& f1, const T& f2) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(T))\n      {\n         using std::fabs;\n         T ratio = f0 / f1;\n         T delta;\n         if((x != 0) && (fabs(ratio / x) < 0.1))\n         {\n            delta = ratio + (f2 / (2 * f1)) * ratio * ratio;\n            // check second derivative doesn't over compensate:\n            if(delta * ratio < 0)\n               delta = ratio;\n         }\n         else\n            delta = ratio;  // fall back to Newton iteration.\n         return delta;\n      }\n   };\n\n}\n\ntemplate <class F, class T>\nT schroder_iterate(F f, T guess, T min, T max, int digits, boost::uintmax_t& max_iter) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n{\n   return detail::second_order_root_finder<detail::schroder_stepper>(f, guess, min, max, digits, max_iter);\n}\n\ntemplate <class F, class T>\ninline T schroder_iterate(F f, T guess, T min, T max, int digits) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n{\n   boost::uintmax_t m = (std::numeric_limits<boost::uintmax_t>::max)();\n   return schroder_iterate(f, guess, min, max, digits, m);\n}\n//\n// These two are the old spelling of this function, retained for backwards compatibity just in case:\n//\ntemplate <class F, class T>\nT schroeder_iterate(F f, T guess, T min, T max, int digits, boost::uintmax_t& max_iter) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n{\n   return detail::second_order_root_finder<detail::schroder_stepper>(f, guess, min, max, digits, max_iter);\n}\n\ntemplate <class F, class T>\ninline T schroeder_iterate(F f, T guess, T min, T max, int digits) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n{\n   boost::uintmax_t m = (std::numeric_limits<boost::uintmax_t>::max)();\n   return schroder_iterate(f, guess, min, max, digits, m);\n}\n\n#ifndef BOOST_NO_CXX11_AUTO_DECLARATIONS\n/*\n * Why do we set the default maximum number of iterations to the number of digits in the type?\n * Because for double roots, the number of digits increases linearly with the number of iterations,\n * so this default should recover full precision even in this somewhat pathological case.\n * For isolated roots, the problem is so rapidly convergent that this doesn't matter at all.\n */\ntemplate<class Complex, class F>\nComplex complex_newton(F g, Complex guess, int max_iterations=std::numeric_limits<typename Complex::value_type>::digits)\n{\n    typedef typename Complex::value_type Real;\n    using std::norm;\n    using std::abs;\n    using std::max;\n    // z0, z1, and z2 cannot be the same, in case we immediately need to resort to Muller's Method:\n    Complex z0 = guess + Complex(1,0);\n    Complex z1 = guess + Complex(0,1);\n    Complex z2 = guess;\n\n    do {\n       auto pair = g(z2);\n       if (norm(pair.second) == 0)\n       {\n           // Muller's method. Notation follows Numerical Recipes, 9.5.2:\n           Complex q = (z2 - z1)/(z1 - z0);\n           auto P0 = g(z0);\n           auto P1 = g(z1);\n           Complex qp1 = static_cast<Complex>(1)+q;\n           Complex A = q*(pair.first - qp1*P1.first + q*P0.first);\n\n           Complex B = (static_cast<Complex>(2)*q+static_cast<Complex>(1))*pair.first - qp1*qp1*P1.first +q*q*P0.first;\n           Complex C = qp1*pair.first;\n           Complex rad = sqrt(B*B - static_cast<Complex>(4)*A*C);\n           Complex denom1 = B + rad;\n           Complex denom2 = B - rad;\n           Complex correction = (z1-z2)*static_cast<Complex>(2)*C;\n           if (norm(denom1) > norm(denom2))\n           {\n               correction /= denom1;\n           }\n           else\n           {\n               correction /= denom2;\n           }\n\n           z0 = z1;\n           z1 = z2;\n           z2 = z2 + correction;\n       }\n       else\n       {\n           z0 = z1;\n           z1 = z2;\n           z2 = z2  - (pair.first/pair.second);\n       }\n\n       // See: https://math.stackexchange.com/questions/3017766/constructing-newton-iteration-converging-to-non-root\n       // If f' is continuous, then convergence of x_n -> x* implies f(x*) = 0.\n       // This condition approximates this convergence condition by requiring three consecutive iterates to be clustered.\n       Real tol = max(abs(z2)*std::numeric_limits<Real>::epsilon(), std::numeric_limits<Real>::epsilon());\n       bool real_close = abs(z0.real() - z1.real()) < tol && abs(z0.real() - z2.real()) < tol && abs(z1.real() - z2.real()) < tol;\n       bool imag_close = abs(z0.imag() - z1.imag()) < tol && abs(z0.imag() - z2.imag()) < tol && abs(z1.imag() - z2.imag()) < tol;\n       if (real_close && imag_close)\n       {\n           return z2;\n       }\n\n   } while(max_iterations--);\n\n    // The idea is that if we can get abs(f) < eps, we should, but if we go through all these iterations\n    // and abs(f) < sqrt(eps), then roundoff error simply does not allow that we can evaluate f to < eps\n    // This is somewhat awkward as it isn't scale invariant, but using the Daubechies coefficient example code,\n    // I found this condition generates correct roots, whereas the scale invariant condition discussed here:\n    // https://scicomp.stackexchange.com/questions/30597/defining-a-condition-number-and-termination-criteria-for-newtons-method\n    // allows nonroots to be passed off as roots.\n    auto pair = g(z2);\n    if (abs(pair.first) < sqrt(std::numeric_limits<Real>::epsilon()))\n    {\n        return z2;\n    }\n\n    return {std::numeric_limits<Real>::quiet_NaN(),\n            std::numeric_limits<Real>::quiet_NaN()};\n}\n#endif\n\n\n#if !defined(BOOST_NO_CXX17_IF_CONSTEXPR)\n// https://stackoverflow.com/questions/48979861/numerically-stable-method-for-solving-quadratic-equations/50065711\nnamespace detail\n{\n    template<class T>\n    inline T discriminant(T const & a, T const & b, T const & c)\n    {\n        T w = 4*a*c;\n        T e = std::fma(-c, 4*a, w);\n        T f = std::fma(b, b, -w);\n        return f + e;\n    }\n}\n\ntemplate<class T>\nauto quadratic_roots(T const& a, T const& b, T const& c)\n{\n    using std::copysign;\n    using std::sqrt;\n    if constexpr (std::is_integral<T>::value)\n    {\n        // What I want is to write:\n        // return quadratic_roots(double(a), double(b), double(c));\n        // but that doesn't compile.\n        double nan = std::numeric_limits<double>::quiet_NaN();\n        if(a==0)\n        {\n            if (b==0 && c != 0)\n            {\n                return std::pair<double, double>(nan, nan);\n            }\n            else if (b==0 && c==0)\n            {\n                return std::pair<double, double>(0,0);\n            }\n            return std::pair<double, double>(-c/b, -c/b);\n        }\n        if (b==0)\n        {\n            double x0_sq = -double(c)/double(a);\n            if (x0_sq < 0) {\n                return std::pair<double, double>(nan, nan);\n            }\n            double x0 = sqrt(x0_sq);\n            return std::pair<double, double>(-x0,x0);\n        }\n        double discriminant = detail::discriminant(double(a), double(b), double(c));\n        if (discriminant < 0)\n        {\n            return std::pair<double, double>(nan, nan);\n        }\n        double q = -(b + copysign(sqrt(discriminant), double(b)))/T(2);\n        double x0 = q/a;\n        double x1 = c/q;\n        if (x0 < x1) {\n            return std::pair<double, double>(x0, x1);\n        }\n        return std::pair<double, double>(x1, x0);\n    }\n    else if constexpr (std::is_floating_point<T>::value)\n    {\n        T nan = std::numeric_limits<T>::quiet_NaN();\n        if(a==0)\n        {\n            if (b==0 && c != 0)\n            {\n                return std::pair<T, T>(nan, nan);\n            }\n            else if (b==0 && c==0)\n            {\n                return std::pair<T, T>(0,0);\n            }\n            return std::pair<T, T>(-c/b, -c/b);\n        }\n        if (b==0)\n        {\n            T x0_sq = -c/a;\n            if (x0_sq < 0) {\n                return std::pair<T, T>(nan, nan);\n            }\n            T x0 = sqrt(x0_sq);\n            return std::pair<T, T>(-x0,x0);\n        }\n        T discriminant = detail::discriminant(a, b, c);\n        // Is there a sane way to flush very small negative values to zero?\n        // If there is I don't know of it.\n        if (discriminant < 0)\n        {\n            return std::pair<T, T>(nan, nan);\n        }\n        T q = -(b + copysign(sqrt(discriminant), b))/T(2);\n        T x0 = q/a;\n        T x1 = c/q;\n        if (x0 < x1)\n        {\n            return std::pair<T, T>(x0, x1);\n        }\n        return std::pair<T, T>(x1, x0);\n    }\n    else if constexpr (boost::is_complex<T>::value || boost::multiprecision::number_category<T>::value == boost::multiprecision::number_kind_complex)\n    {\n        typename T::value_type nan = std::numeric_limits<typename T::value_type>::quiet_NaN();\n        if(a.real()==0 && a.imag() ==0)\n        {\n            using std::norm;\n            if (b.real()==0 && b.imag() && norm(c) != 0)\n            {\n                return std::pair<T, T>({nan, nan}, {nan, nan});\n            }\n            else if (b.real()==0 && b.imag() && c.real() ==0 && c.imag() == 0)\n            {\n                return std::pair<T, T>({0,0},{0,0});\n            }\n            return std::pair<T, T>(-c/b, -c/b);\n        }\n        if (b.real()==0 && b.imag() == 0)\n        {\n            T x0_sq = -c/a;\n            T x0 = sqrt(x0_sq);\n            return std::pair<T, T>(-x0, x0);\n        }\n        // There's no fma for complex types:\n        T discriminant = b*b - T(4)*a*c;\n        T q = -(b + sqrt(discriminant))/T(2);\n        return std::pair<T, T>(q/a, c/q);\n    }\n    else // Most likely the type is a boost.multiprecision.\n    {    //There is no fma for multiprecision, and in addition it doesn't seem to be useful, so revert to the naive computation.\n        T nan = std::numeric_limits<T>::quiet_NaN();\n        if(a==0)\n        {\n            if (b==0 && c != 0)\n            {\n                return std::pair<T, T>(nan, nan);\n            }\n            else if (b==0 && c==0)\n            {\n                return std::pair<T, T>(0,0);\n            }\n            return std::pair<T, T>(-c/b, -c/b);\n        }\n        if (b==0)\n        {\n            T x0_sq = -c/a;\n            if (x0_sq < 0) {\n                return std::pair<T, T>(nan, nan);\n            }\n            T x0 = sqrt(x0_sq);\n            return std::pair<T, T>(-x0,x0);\n        }\n        T discriminant = b*b - 4*a*c;\n        if (discriminant < 0)\n        {\n            return std::pair<T, T>(nan, nan);\n        }\n        T q = -(b + copysign(sqrt(discriminant), b))/T(2);\n        T x0 = q/a;\n        T x1 = c/q;\n        if (x0 < x1)\n        {\n            return std::pair<T, T>(x0, x1);\n        }\n        return std::pair<T, T>(x1, x0);\n    }\n}\n#endif\n\n} // namespace tools\n} // namespace math\n} // namespace boost\n\n#endif // BOOST_MATH_TOOLS_NEWTON_SOLVER_HPP\n", "meta": {"hexsha": "e16294dc15f9c391fd32189047c03004e9780c4b", "size": 26949, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "core/lib/boost/boost/math/tools/roots.hpp", "max_stars_repo_name": "RomanWlm/lib-ledger-core", "max_stars_repo_head_hexsha": "8c068fccb074c516096abb818a4e20786e02318b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 124.0, "max_stars_repo_stars_event_min_datetime": "2021-07-14T21:25:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T20:40:16.000Z", "max_issues_repo_path": "depends/x86_64-w64-mingw32/include/boost/math/tools/roots.hpp", "max_issues_repo_name": "slowriot/bitgesell", "max_issues_repo_head_hexsha": "9b7f9e207323e9863253ad2598068b0ad0b159d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 242.0, "max_issues_repo_issues_event_min_datetime": "2016-11-28T11:13:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T13:02:53.000Z", "max_forks_repo_path": "depends/x86_64-w64-mingw32/include/boost/math/tools/roots.hpp", "max_forks_repo_name": "slowriot/bitgesell", "max_forks_repo_head_hexsha": "9b7f9e207323e9863253ad2598068b0ad0b159d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 91.0, "max_forks_repo_forks_event_min_datetime": "2017-06-20T10:35:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T14:15:40.000Z", "avg_line_length": 32.390625, "max_line_length": 244, "alphanum_fraction": 0.5479609633, "num_tokens": 7367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.2863129389204736}}
{"text": "//=======================================================================\n// Copyright (c)\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file steiner_strategy.hpp\n * @brief\n * @author Maciej Andrejczuk\n * @version 1.0\n * @date 2013-08-01\n */\n#ifndef PAAL_STEINER_STRATEGY_HPP\n#define PAAL_STEINER_STRATEGY_HPP\n\n#include \"paal/data_structures/bimap.hpp\"\n#include \"paal/data_structures/subset_iterator.hpp\"\n#include \"paal/iterative_rounding/steiner_tree/steiner_components.hpp\"\n#include \"paal/utils/assign_updates.hpp\"\n\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/filtered_graph.hpp>\n#include <boost/range/as_array.hpp>\n#include <boost/range/algorithm_ext/erase.hpp>\n#include <boost/range/algorithm/sort.hpp>\n#include <boost/range/algorithm/unique.hpp>\n#include <boost/random/discrete_distribution.hpp>\n\n#include <random>\n#include <unordered_set>\n#include <vector>\n\n\nnamespace paal {\nnamespace ir {\n\n/**\n * Generates all the components possible.\n * It iterates over all subsets of terminals with no more than K elements.\n */\nclass steiner_tree_all_generator {\nprivate:\n    template<typename Metric>\n    using MTraits = typename data_structures::metric_traits<Metric>;\n\npublic:\n    /// Constructor.\n    steiner_tree_all_generator(int K = 4) : m_component_max_size(K) {}\n\n    /// Generates all possible components.\n    template<typename Metric, typename Terminals>\n    void gen_components(const Metric& cost_map, const Terminals& terminals,\n            const Terminals& steiner_vertices,\n            steiner_components<\n                typename MTraits<Metric>::VertexType,\n                typename MTraits<Metric>::DistanceType>& components) {\n\n        using Vertex = typename MTraits<Metric>::VertexType;\n        using Dist = typename MTraits<Metric>::DistanceType;\n        std::vector<Vertex> current_terminals;\n        gen_all_components<Vertex, Dist>(components, 0, terminals.size(),\n            current_terminals, cost_map, terminals, steiner_vertices);\n    }\nprivate:\n    template<typename Vertex, typename Dist, typename Metric, typename Terminals>\n    void gen_all_components(steiner_components<Vertex, Dist>& components,\n            int first_avail, int last, std::vector<Vertex>& curr,\n            const Metric& cost_map, const Terminals& terminals,\n            const Terminals& steiner_vertices) {\n\n        if (curr.size() > 1) {\n            steiner_component<Vertex, Dist> c(cost_map, curr, steiner_vertices);\n            components.add(std::move(c));\n        }\n        if ((int) curr.size() >= m_component_max_size)\n            return;\n        for (int i = first_avail; i < last; ++i) {\n            curr.push_back(terminals[i]);\n            gen_all_components(components, i + 1, last, curr, cost_map,\n                terminals, steiner_vertices);\n            curr.pop_back();\n        }\n    }\n\n    int m_component_max_size;\n};\n\nnamespace detail {\n\ntemplate<typename Vertex>\nstruct vertex_filter {\n    bool operator()(Vertex v) const { return vertices.find(v) == vertices.end(); }\n    std::unordered_set<Vertex> vertices;\n};\n\n}// detail\n\n/**\n * Generates all the components possible based on the underlying graph.\n * It iterates over all subsets of terminals with no more than K elements.\n */\ntemplate<typename Graph, typename Vertex, typename Terminals>\nclass steiner_tree_graph_all_generator {\nprivate:\n    template<typename Metric>\n    using MTraits = typename data_structures::metric_traits<Metric>;\n\npublic:\n    /// Constructor.\n    steiner_tree_graph_all_generator(const Graph& graph,\n        const Terminals& terminals, int K = 4) : m_component_max_size(K),\n            m_index(terminals),\n            m_terminals_graph(m_index.size()) {\n        initialize_terminals_graph(graph, terminals);\n    }\n\n    /// Generates all possible components.\n    template<typename Metric>\n    void gen_components(const Metric& cost_map, const Terminals& terminals,\n            const Terminals& steiner_vertices,\n            steiner_components<\n                typename MTraits<Metric>::VertexType,\n                typename MTraits<Metric>::DistanceType>& components) {\n\n        using Dist = typename MTraits<Metric>::DistanceType;\n        merge_vertices<Dist>(cost_map);\n        std::vector<Vertex> current_terminals;\n        gen_all_components<Dist>(components, 0, terminals.size(),\n            current_terminals, cost_map, terminals, steiner_vertices);\n    }\n\nprivate:\n    using AuxGraph = boost::adjacency_list<boost::setS, boost::vecS, boost::undirectedS>;\n    using VertexIndex = data_structures::bimap<Vertex>;\n\n    int m_component_max_size;\n    VertexIndex m_index;\n    AuxGraph m_terminals_graph;\n\n    void initialize_terminals_graph(const Graph& graph, const Terminals& terminals) {\n        detail::vertex_filter<Vertex> filter;\n        filter.vertices.insert(terminals.begin(), terminals.end());\n        auto index = get(boost::vertex_index, graph);\n        std::vector<int> components(num_vertices(graph));\n        for (auto u : terminals) {\n            for (auto v : terminals) {\n                if (u == v) continue;\n                filter.vertices.erase(u);\n                filter.vertices.erase(v);\n                boost::filtered_graph<Graph, boost::keep_all, decltype(filter)>\n                    fg(graph, boost::keep_all{}, filter);\n                boost::connected_components(fg, &components[0]);\n                if (components[index[u]] == components[index[v]]) {\n                    add_edge(get_idx(u), get_idx(v), m_terminals_graph);\n                }\n                filter.vertices.insert(u);\n                filter.vertices.insert(v);\n            }\n        }\n    }\n\n    template<typename Dist, typename Metric>\n    void merge_vertices(const Metric& cost_map) {\n        auto range = vertices(m_terminals_graph);\n        for (auto v_pair : data_structures::make_subsets_iterator_range<2>(\n                range.first, range.second)) {\n            auto i = std::get<0>(v_pair);\n            auto j = std::get<1>(v_pair);\n            if (cost_map(get_val(i), get_val(j)) == Dist{}) {\n                merge_vertices(i, j);\n                merge_vertices(j, i);\n            }\n        }\n    }\n\n    void merge_vertices(Vertex trg, Vertex src) {\n        for (auto v : boost::as_array(adjacent_vertices(src,\n                m_terminals_graph))) {\n            if (trg != static_cast<Vertex>(v)) {\n                add_edge(trg, v, m_terminals_graph);\n            }\n        }\n    }\n\n    auto get_idx(Vertex v) const -> decltype(m_index.get_idx(v)) {\n        return m_index.get_idx(v);\n    }\n\n    auto get_val(int idx) const -> decltype(m_index.get_val(idx)) {\n        return m_index.get_val(idx);\n    }\n\n    bool is_graph_component(const std::vector<Vertex>& comp) const {\n        for (auto term_pair : data_structures::make_subsets_iterator_range<2>(\n                comp.begin(), comp.end())) {\n            if (!edge(\n                    get_idx(std::get<0>(term_pair)),\n                    get_idx(std::get<1>(term_pair)),\n                    m_terminals_graph).second) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    template<typename Dist, typename Metric>\n    void gen_all_components(steiner_components<Vertex, Dist>& components,\n            int first_avail, int last, std::vector<Vertex>& curr,\n            const Metric& cost_map, const Terminals& terminals,\n            const Terminals& steiner_vertices) {\n\n        // TODO implement a subset_iterator with K passed as a parameter\n        // not as a template parameter (also in the gen_all_components method\n        // in steiner_tree_all_generator)\n        if (curr.size() > 1) {\n            if (!is_graph_component(curr))\n                return;\n            steiner_component<Vertex, Dist> c(cost_map, curr, steiner_vertices);\n            components.add(std::move(c));\n        }\n        if ((int) curr.size() >= m_component_max_size)\n            return;\n        for (int i = first_avail; i < last; ++i) {\n            curr.push_back(terminals[i]);\n            gen_all_components(components, i + 1, last, curr, cost_map,\n                terminals, steiner_vertices);\n            curr.pop_back();\n        }\n    }\n};\n\n/**\n * Makes a graph_all_generator object.\n */\ntemplate<typename Vertex, typename Graph, typename Terminals>\nsteiner_tree_graph_all_generator<Graph, Vertex, Terminals>\nmake_steiner_tree_graph_all_generator(const Graph& graph,\n        const Terminals& terminals, int K = 4) {\n    return steiner_tree_graph_all_generator<Graph, Vertex, Terminals>(\n        graph, terminals, K);\n}\n\n/**\n * Generates specified number of components by selecting random elements.\n */\nclass steiner_tree_random_generator {\npublic:\n    /// Constructor.\n    steiner_tree_random_generator(int N = 100, int K = 3) :\n            m_iterations(N), m_component_max_size(K) {\n    }\n\n    /// Generates a specified number of components by selecting random elements.\n    template<typename Metric, typename Terminals>\n    void gen_components(const Metric& cost_map, const Terminals & terminals,\n            const Terminals& steiner_vertices,\n            steiner_components<\n                typename data_structures::metric_traits<Metric>::VertexType,\n                typename data_structures::metric_traits<Metric>::DistanceType>& components) {\n\n        using Vertex = typename data_structures::metric_traits<Metric>::VertexType;\n        using Dist = typename data_structures::metric_traits<Metric>::DistanceType;\n        if (terminals.size() < 2) {\n            return;\n        }\n        for (int i = 0; i < m_iterations; ++i) {\n            std::set<Vertex> curr;\n            while ((int)curr.size() < m_component_max_size) {\n                if (curr.size() > 1) {\n                    int c =\n                        (int)rand() %\n                        m_component_max_size; // TODO: Is this fair probability?\n                    if (c == 0) {\n                        break;\n                    }\n                }\n                int r = (int)rand() % terminals.size();\n                curr.insert(terminals[r]);\n            }\n            std::vector<Vertex> elements(curr.begin(), curr.end());\n            steiner_component<Vertex, Dist> c(cost_map, elements, steiner_vertices);\n            components.add(std::move(c));\n        }\n        // TODO some terminals may not be in any component\n    }\n\n  private:\n    int m_iterations;\n    int m_component_max_size;\n};\n\n/**\n * Generates specified number of components by randomly selecting elements\n * with probability dependent on distance from vertices already selected.\n */\nclass steiner_tree_smart_generator {\n    std::default_random_engine m_rng;\npublic:\n    /// Constructor.\n    steiner_tree_smart_generator(int N = 100, int K = 3, std::default_random_engine rng = std::default_random_engine{}) :\n            m_iterations(N), m_component_max_size(K) {\n    }\n\n    /// Generates components.\n    template<typename Metric, typename Terminals>\n    void gen_components(const Metric& cost_map, const Terminals& terminals,\n            const Terminals& steiner_vertices,\n            steiner_components<\n                    typename data_structures::metric_traits<Metric>::VertexType,\n                    typename data_structures::metric_traits<Metric>::DistanceType>& components) {\n\n        using Vertex = typename data_structures::metric_traits<Metric>::VertexType;\n        using Dist = typename data_structures::metric_traits<Metric>::DistanceType;\n        std::vector<Vertex> elements;\n        std::vector<double> prob;\n        for (Vertex start : terminals) {\n            for (int i = 0; i < m_iterations; ++i) {\n                elements.clear();\n                elements.push_back(start);\n                int limit = 2 + rand() % (m_component_max_size - 1);\n                while ((int)elements.size() < limit) {\n                    prob.resize(terminals.size());\n                    for (int k = 0; k < (int)prob.size(); ++k) {\n                        for (auto e : elements) {\n                            if (e == terminals[k]) {\n                                prob[k] = 0;\n                                break;\n                            }\n                            int cost = cost_map(e, terminals[k]);\n                            assert(cost > 0);\n                            assign_max(prob[k], 1. / cost);\n                        }\n                    }\n                    auto selected = boost::random::discrete_distribution<std::size_t>(prob)(m_rng);\n                    if (selected == prob.size()) break;\n                    elements.push_back(terminals[selected]);\n                }\n                boost::erase(elements, boost::unique<boost::return_found_end>(boost::sort(elements)));\n\n                steiner_component<Vertex, Dist> c(cost_map, elements, steiner_vertices);\n                components.add(std::move(c));\n            }\n        }\n    }\n\n  private:\n    int m_iterations;\n    int m_component_max_size;\n};\n\n} // ir\n} // paal\n\n#endif // PAAL_STEINER_STRATEGY_HPP\n", "meta": {"hexsha": "57ce271c3e1100de860dfbc7355a5c0c93f0beca", "size": 13153, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/iterative_rounding/steiner_tree/steiner_strategy.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/iterative_rounding/steiner_tree/steiner_strategy.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/iterative_rounding/steiner_tree/steiner_strategy.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": 36.8431372549, "max_line_length": 121, "alphanum_fraction": 0.6055652703, "num_tokens": 2759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5273165233795672, "lm_q1q2_score": 0.28626077915294296}}
{"text": "#include <vector>\n#include <Eigen/Dense>\n#include <cassert>\n#include <numeric>\n#include <math.h>\n#include <errno.h>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <vector>\n#include <algorithm>\n#include <regex>\n#include \"MorrisMethod.h\"\n#include \"Transformable.h\"\n#include \"RunManagerAbstract.h\"\n#include \"ParamTransformSeq.h\"\n#include \"ModelRunPP.h\"\n#include \"utilities.h\"\n#include \"FileManager.h\"\n#include \"Stats.h\"\n//#include \"Ensemble.h\"\n\nusing namespace std;\nusing namespace pest_utils;\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nvoid MorrisObsSenFile::initialize(const vector<string> &_par_names_vec, const vector<string> &_obs_names_vec, double _no_data, const GsaAbstractBase *_gsa_abstract_base)\n{\n\tpar_names_vec =_par_names_vec;\n\tobs_names_vec = _obs_names_vec;\n\tgsa_abstract_base = _gsa_abstract_base;\n\tno_data = _no_data;\n}\n\nvoid MorrisObsSenFile::add_sen_run_pair(const std::string &par_name, double p1, Observations &obs1, double p2, Observations &obs2)\n{\n\tassert (obs1.size() == obs2.size());\n\n\t// compute sensitivities of individual observations\n\tdouble isen;\n\tdouble del_par = p2 - p1;\n\n\tfor (const auto &iobs : obs_names_vec)\n\t{\n\t\tisen = (obs2[iobs] - obs1[iobs]) / del_par;\n\t\tconst auto id = make_pair(par_name, iobs);\n\t\tif (map_obs_stats.find(id) == map_obs_stats.end())\n\t\t{\n\t\t\tmap_obs_stats[id] = RunningStats();\n\t\t}\n\t\tmap_obs_stats[make_pair(par_name, iobs)].add(isen);\n\t}\n}\n\nvoid MorrisObsSenFile::calc_pooled_obs_sen(ofstream &fout_obs_sen, map<string, double> &obs_2_sen_weight,\n\tmap<string, double> &par_2_sen_weight)\n{\n\tfout_obs_sen << \"par_name, n_samples, obs_name, mean, abs_mean, sigma, scaled_sen\" << endl;\n\tfor (const auto &ip : par_names_vec)\n\t{\n\t\tstring ipar = ip;\n\t\tfor (const auto &iobs : obs_names_vec)\n\t\t{\n\t\t\tdouble mean = no_data;\n\t\t\tdouble abs_mean = no_data;\n\t\t\tdouble sigma = no_data;\n\t\t\tint n_samples = 0;\n\t\t\tconst auto id = make_pair(ipar, iobs);\n\t\t\tauto sen_itr = map_obs_stats.find(id);\n\t\t\tif (sen_itr != map_obs_stats.end() && sen_itr->second.comp_nsamples() > 0)\n\t\t\t{\n\t\t\t\tmean = sen_itr->second.comp_mean();\n\t\t\t\tabs_mean = sen_itr->second.comp_abs_mean();\n\t\t\t\tsigma = sen_itr->second.comp_sigma();\n\t\t\t\tn_samples = sen_itr->second.comp_nsamples();\n\t\t\t}\n\t\t\tstring weighted_sen = \"N/A\";\n\t\t\tauto it_obs = obs_2_sen_weight.find(iobs);\n\t\t\tauto it_par = par_2_sen_weight.find(ipar);\n\t\t\tif (it_obs != obs_2_sen_weight.end() && it_par != par_2_sen_weight.end() && abs_mean != no_data)\n\t\t\t{\n\t\t\t\tstringstream sstr;\n\t\t\t\tdouble value = abs_mean * it_par->second / it_obs->second;\n\t\t\t\tsstr << value;\n\t\t\t\tweighted_sen = sstr.str();\n\t\t\t}\n\t\t\tfout_obs_sen << ipar << \", \" << n_samples << \", \" << iobs << \", \" << mean << \", \" << abs_mean << \", \" << sigma << \", \" << weighted_sen << endl;\n\t\t}\n\t}\n}\n\nvoid MorrisMethod::process_pooled_var_file()\n{\n\tif (calc_obs_sen == true)\n\t{\n\t\tifstream &fin = file_manager_ptr->open_ifile_ext(\"pgp\");\n\t\tstd::set<string> obs_group_names;\n\t\tfor (const auto &imap : obs_info_ptr->groups)\n\t\t\tobs_group_names.insert(imap.first);\n\n\t\tstring line;\n\t\tstring cur_pool_grp;\n\t\tregex reg_reg(\"regex\\\\s*\\\\(\\\"(.+)\\\"\\\\)\", regex_constants::icase);\n\t\tregex reg_grp(\"pool_group\\\\s*\\\\((.+)\\\\)\", regex_constants::icase);\n\t\tcmatch mr;\n\t\twhile (getline(fin, line))\n\t\t{\n\t\t\tif (regex_match(line.c_str(), mr, reg_reg))\n\t\t\t{\n\t\t\t\tregex inp_reg = regex(mr[1].str(), regex_constants::icase);\n\n\t\t\t\tfor (auto itr = obs_group_names.begin(); itr != obs_group_names.end();)\n\t\t\t\t{\n\t\t\t\t\tauto  here = itr++;\n\t\t\t\t\tif (regex_match(*here, inp_reg))\n\t\t\t\t\t{\n\t\t\t\t\t\tgroup_2_pool_group_map[*here] = cur_pool_grp;\n\t\t\t\t\t\tobs_group_names.erase(here);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tif (regex_match(line.c_str(), mr, reg_grp))\n\t\t\t{\n\t\t\t\tcur_pool_grp = mr[1];\n\t\t\t}\n\t\t}\n\t}\n\tfile_manager_ptr->close_file(\"pgp\");\n}\n\nMatrixXd MorrisMethod::create_P_star_mat(int k)\n{\n\tMatrixXd b_mat = create_B_mat(k);\n\tMatrixXd j_mat = create_J_mat(k);\n\tMatrixXd d_mat = create_D_mat(k);\n\tMatrixXd x_vec = create_x_vec(k);\n\tMatrixXd p_mat = create_P_mat(k);\n\tb_star_mat = j_mat.col(0) * x_vec.transpose() + (delta/2.0)*((2.0 * b_mat - j_mat) * d_mat + j_mat) ;\n\treturn b_star_mat;\n}\n\nMorrisMethod::MorrisMethod(Pest &_pest_scenario,\n\tFileManager &_file_manager, ObjectiveFunc *_obj_func_ptr,\n\tconst ParamTransformSeq &_par_transform,\n\tint _p, int _r, double _delta,\n\tbool _calc_pooled_obs, bool _calc_morris_obs_sen, PARAM_DIST _par_dist, unsigned int _seed)\n\t: GsaAbstractBase(_pest_scenario, _file_manager, _obj_func_ptr, _par_transform,\n\t\t_par_dist, _seed),\n\tcalc_obs_sen(_calc_pooled_obs), calc_morris_obs_sen(_calc_morris_obs_sen)\n{\n\tinitialize(_p, _r, _delta);\n}\n\n\nvoid MorrisMethod::initialize(int _p, int _r, double _delta)\n{\n\tp = _p;\n\tr = _r;\n\tdelta = _delta;\n\t//delta = p / (2.0 * (p - 1));\n}\n\nMatrixXd MorrisMethod::create_B_mat(int k)\n{\n\tMatrixXd b_mat = MatrixXd::Constant(k+1, k, 0.0);\n\tint nrow = k+1;\n\tint ncol = k;\n\tfor (int icol=0; icol<ncol; ++icol)\n\t{\n\t\tfor (int irow=icol+1; irow<nrow; ++irow)\n\t\t{\n\t\t\tb_mat(irow, icol) = 1.0;\n\t\t}\n\t}\n\treturn b_mat;\n}\n\nMatrixXd MorrisMethod::create_J_mat(int k)\n{\n\tMatrixXd j_mat = MatrixXd::Constant(k+1, k, 1.0);\n\treturn j_mat;\n}\n\nMatrixXd MorrisMethod::create_D_mat(int k)\n{\n\tMatrixXd d_mat=MatrixXd::Constant(k, k, 0.0);\n\tfor (int i=0; i<k; ++i) {\n\t\td_mat(i,i) = rand_plus_minus_1();\n\t}\n\treturn d_mat;\n}\n\nMatrixXd MorrisMethod::create_P_mat(int k)\n{\n\t// generate and return a random permutation matrix\n\tMatrixXd p_mat=MatrixXd::Constant(k, k, 0.0);\n\tvector<int> rand_idx;\n\trand_idx.reserve(k);\n\tfor (int i=0; i<k; ++i) {\n\t\trand_idx.push_back(i);\n\t}\n\t// Shuffle random index vector\n\tshuffle(rand_idx.begin(), rand_idx.end(), rand_engine);\n\n\tfor(int irow=0; irow<k; ++irow)\n\t{\n\t  p_mat(irow, rand_idx[irow]) = 1;\n\t}\n\n\treturn p_mat;\n}\n\nVectorXd MorrisMethod::create_x_vec(int k)\n{\n\t// Warning Satelli's book is wrong.  Need to use Morris's original paper\n\t// to compute x.  Maximim value of any xi shoud be 1.0 - delta.\n\tVectorXd x(k);\n\tdouble rnum;\n\t// Used with the randon number generator below, max_num will produce a\n\t// random interger which varies between 0 and (p-2)/2.  This will in turn\n\t// produce the correct xi's which vary from {0, 1/(p-1), 2/(p-1), .... 1 - delta)\n\t// when divided by (p-1).  See Morris's paper for the derivaition.\n\t// Satelli's book has this equation wrong!\n\tint max_num = 1+(p-2)/2;\n\tfor (int i=0; i<k; ++i)\n\t{\n\t\trnum = rand_engine() % max_num;\n\t\tx(i) = rnum / (p - 1);\n\t}\n\treturn x;\n}\n\n\nint MorrisMethod::rand_plus_minus_1(void)\n{\n\treturn (rand_engine() % 2 * 2) - 1;\n}\n\n\nParameters MorrisMethod::get_numeric_parameters(int row)\n{\n\tParameters numeric_pars;\n\tauto e=adj_par_name_vec.end();\n\tsize_t n_cols = b_star_mat.cols();\n\tfor (int j=0; j<n_cols; ++j)\n\t{\n\t\tconst string &p = adj_par_name_vec[j];\n\t\tauto it_lbnd = min_numeric_pars.find(p);\n\t\tassert(it_lbnd != min_numeric_pars.end());\n\t\tauto it_ubnd = max_numeric_pars.find(p);\n\t\tassert(it_ubnd != max_numeric_pars.end());\n\t\tnumeric_pars[p] =  it_lbnd->second + (it_ubnd->second - it_lbnd->second) * b_star_mat(row, j);\n\t}\n\treturn numeric_pars;\n}\n\nvoid MorrisMethod::assemble_runs(RunManagerAbstract &run_manager)\n{\n\tmap<int, Parameters> par_map;\n\tfor (int tmp_r=0; tmp_r<r; ++tmp_r)\n\t{\n\t\tb_star_mat = create_P_star_mat(adj_par_name_vec.size());\n\t\tauto n_rows = b_star_mat.rows();\n\t\tint run_id;\n\t\tstring par_name = \"\";\n\t\tfor (int i=0; i<n_rows; ++i)\n\t\t{\n\t\t\tpar_name.clear();\n\t\t\t//get control parameters\n\t\t\tParameters pars = get_numeric_parameters(i);\n\t\t\t// convert control parameters to model parameters\n\t\t\tbase_partran_seq_ptr->numeric2model_ip(pars);\n\t\t\t// convert control parameters to model parameters\n\t\t\tbase_partran_seq_ptr->ctl2model_ip(pars);\n\t\t\tif (i>0)\n\t\t\t{\n\t\t\t\tpar_name = adj_par_name_vec[i-1];\n\t\t\t}\n\t\t\trun_id = run_manager.add_run(pars, par_name, Parameters::no_data);\n\t\t\tbase_partran_seq_ptr->model2ctl_ip(pars);\n\t\t\tpar_map[run_id] =  pars;\n\n\t\t}\n\t}\n\t//write the parameter sequence to a csv file\n\tstring filename = file_manager_ptr->get_base_filename() + \".sen.par.csv\";\n\tofstream fout(filename);\n\tvector<string> var_names = pest_scenario_ptr->get_ctl_ordered_par_names();\n\tfout << \"run_id\";\n\tfor (auto pname : var_names)\n\t\tfout << \",\" << pname;\n\tfout << endl;\n\tfor (auto &p : par_map)\n\t{\n\t\tfout << p.first;\n\t\tfor (auto &pname : var_names)\n\t\t\tfout << \",\" << p.second.get_rec(pname);\n\t\tfout << endl;\n\t}\n\t/*ParameterEnsemble pe(pest_scenario_ptr);\n\tvector<string> real_names,var_names=pest_scenario_ptr->get_ctl_ordered_par_names();\n\tstringstream ss;\n\tmap<int, string> real_name_map;\n\tfor (auto &p : par_map)\n\t{\n\t\tss.str(\"\");\n\t\tss << p.first;\n\t\treal_names.push_back(ss.str());\n\t\treal_name_map[p.first] = ss.str();\n\t}\n\tpe.set_trans_status(ParameterEnsemble::transStatus::CTL);\n\tpe.reserve(real_names, var_names);\n\tfor (auto &p : par_map)\n\t{\n\t\tpe.update_real_ip(real_name_map[p.first], p.second.get_data_eigen_vec(var_names));\n\t}\n\tstring filename = file_manager_ptr->get_base_filename() + \".sen.par.csv\";\n\tpe.to_csv(filename);*/\n\n\n}\n\nvoid  MorrisMethod::calc_sen(RunManagerAbstract &run_manager, ModelRun model_run)\n{\n\tofstream &fout_morris = file_manager_ptr->open_ofile_ext(\"msn\");\n\tofstream &fout_raw = file_manager_ptr->open_ofile_ext(\"raw.csv\");\n\n\tModelRun run0 = model_run;\n\tModelRun run1 = model_run;\n\tParameters pars0;\n\tObservations obs0;\n\tParameters pars1;\n\tObservations obs1;\n\n\tmap<string, RunningStats > sen_map;\n\tmap<string, RunningStats> obs_stats_map;\n\n\tfor (auto &it_p : adj_par_name_vec)\n\t{\n\t\tsen_map[it_p] = RunningStats();\n\t}\n\n\tfor (auto &it_obs : obs_name_vec)\n\t{\n\t\tobs_stats_map[it_obs] = RunningStats();\n\t}\n\n\tconst vector<string> &run_mngr_obs_name_vec = run_manager.get_obs_name_vec();\n\tobs_sen_file.initialize(adj_par_name_vec, run_mngr_obs_name_vec, Observations::no_data, this);\n\n\tfout_raw << \"parameter_name, phi_0, phi_1, par_0, par_1, elem_effect\" << endl;\n\tint n_runs = run_manager.get_nruns();\n\tbool run0_ok = false;\n\tbool run1_ok = false;\n\tstring par_name_1;\n\tdouble null_value;\n\tstringstream message;\n\tcout << endl;\n\trun1_ok = run_manager.get_run(0, pars1, obs1);\n\tbase_partran_seq_ptr->model2numeric_ip(pars1);\n\tfor (int i_run=1; i_run<n_runs; ++i_run)\n\t{\n\t\tstd::cout << string(message.str().size(), '\\b');\n\t\tmessage.str(\"\");\n\t\tmessage << \"processing run \" << i_run+1 << \" / \" << n_runs;\n\t\tstd::cout << message.str();\n\n\t\trun0_ok = run1_ok;\n\t\tpars0 = pars1;\n\t\tobs0 = obs1;\n\t\trun1_ok = run_manager.get_run(i_run, pars1, obs1, par_name_1, null_value);\n\t\tbase_partran_seq_ptr->model2numeric_ip(pars1);\n\t\t// Add run0 to obs_stats\n\t\tif (run0_ok)\n\t\t{\n\t\t\tfor (const auto &i_obs : run_mngr_obs_name_vec)\n\t\t\t{\n\t\t\t\tauto it = obs0.find(i_obs);\n\t\t\t\tif (it != obs0.end() && it->second != Observations::no_data)\n\t\t\t\t{\n\t\t\t\t\tobs_stats_map[i_obs].add(obs0[i_obs]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (run0_ok && run1_ok && !par_name_1.empty())\n\t\t{\n\t\t\tParameters tmp_ctl_par = base_partran_seq_ptr->numeric2ctl_cp(pars0);\n\t\t\trun0.update_ctl(tmp_ctl_par, obs0);\n\t\t\tdouble phi0 = run0.get_phi(DynamicRegularization::get_zero_reg_instance());\n\t\t\ttmp_ctl_par = base_partran_seq_ptr->numeric2ctl_cp(pars1);\n\t\t\trun1.update_ctl(tmp_ctl_par, obs1);\n\t\t\tdouble phi1 = run1.get_phi(DynamicRegularization::get_zero_reg_instance());\n\t\t\tdouble p0 = pars0[par_name_1];\n\t\t\tdouble p1 = pars1[par_name_1];\n\t\t\t// compute standard Morris Sensitivity on the global objective function\n\t\t\tdouble sen = (phi1 - phi0) / delta;\n\t\t\tfout_raw << par_name_1 << \",  \" << phi1 << \",  \" << phi0 << \",  \" << p1 << \",  \" << p0 << \", \" << sen << endl;\n\n\t\t\tconst auto &it_senmap = sen_map.find(par_name_1);\n\t\t\tif (it_senmap != sen_map.end())\n\t\t\t{\n\t\t\t\tit_senmap->second.add(sen);\n\t\t\t}\n\n\t\t\t//Compute sensitvities of indiviual observations\n\t\t\tobs_sen_file.add_sen_run_pair(par_name_1, p0, obs0, p1, obs1);\n\t\t}\n\t}\n\t// Add final run to obs_stats\n\tif (run1_ok)\n\t{\n\t\tfor (const auto &i_obs : run_mngr_obs_name_vec)\n\t\t{\n\t\t\tauto it = obs1.find(i_obs);\n\t\t\tif (it != obs1.end() && it->second != Observations::no_data)\n\t\t\t{\n\t\t\t\tobs_stats_map[i_obs].add(obs0[i_obs]);\n\t\t\t}\n\t\t}\n\t}\n\tcout << endl;\n\tcout << \"writing output files\" << endl;\n\t// write standard Morris Sensitivity for the global objective function\n\tfout_morris << \"parameter_name, n_samples, sen_mean, sen_mean_abs, sen_std_dev\" << endl;\n\tfor (const auto &it_par : adj_par_name_vec)\n\t{\n\t\tconst auto &it_senmap = sen_map.find(it_par);\n\t\tif (it_senmap != sen_map.end())\n\t\t{\n\t\t\tfout_morris << it_par << \", \" << it_senmap->second.comp_nsamples() << \", \" << it_senmap->second.comp_mean() << \", \" << it_senmap->second.comp_abs_mean() << \", \" << sqrt(it_senmap->second.comp_var()) << endl;\n\t\t}\n\t}\n\tif (calc_morris_obs_sen)\n\t{\n\t\t// write standard Morris Sensitivity for individual observations\n\t\tofstream &fout_mis = file_manager_ptr->open_ofile_ext(\"mio\");\n\t\tcalc_morris_obs(fout_mis, obs_sen_file);\n\t\tfile_manager_ptr->close_file(\"mio\");\n\t}\n\n\tif (calc_obs_sen)\n\t{\n\t\tofstream &fout_mos = file_manager_ptr->open_ofile_ext(\"mos\");\n\t\t////compute pooled standard deviations\n\t\tmap<string, double> obs_2_sen_weight;\n\t\t{\n\t\t\t//Compute Pooled Standard Deviations\n\t\t\tmap<string, vector<RunningStats> > tmp_pool_grps;\n\t\t\tfor (const auto &it : obs_stats_map)\n\t\t\t{\n\t\t\t\tconst string &obs_name = it.first;\n\t\t\t\tconst string &obs_group = obs_info_ptr->get_group(obs_name);\n\t\t\t\tauto it_pg = group_2_pool_group_map.find(obs_group);\n\t\t\t\tif (it_pg != group_2_pool_group_map.end())\n\t\t\t\t{\n\t\t\t\t\tconst string &pool_group = it_pg->second;\n\t\t\t\t\tif (tmp_pool_grps.find(pool_group) == tmp_pool_grps.end())\n\t\t\t\t\t{\n\t\t\t\t\t\ttmp_pool_grps[pool_group] = vector<RunningStats>();\n\t\t\t\t\t}\n\t\t\t\t\ttmp_pool_grps[pool_group].push_back(it.second);\n\t\t\t\t}\n\t\t\t}\n\t\t\t////compute pooled standard deviations\n\t\t\tmap<string, double> obs_pooled_grp_std_dev;\n\t\t\tfor (const auto &i_pgrp : tmp_pool_grps)\n\t\t\t{\n\t\t\t\tconst string &pool_group = i_pgrp.first;\n\t\t\t\tdouble var_sum = 0;\n\t\t\t\tlong int weight_sum = 0;\n\t\t\t\tfor (const auto &istat : i_pgrp.second)\n\t\t\t\t{\n\t\t\t\t\tlong int weight = istat.comp_nsamples() - 1;\n\t\t\t\t\tvar_sum += weight * istat.comp_var();\n\t\t\t\t\tweight_sum += weight;\n\t\t\t\t}\n\t\t\t\tif (weight_sum > 0)\n\t\t\t\t{\n\t\t\t\t\tobs_pooled_grp_std_dev[pool_group] = sqrt(var_sum / weight_sum);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const auto &iobs : obs_name_vec)\n\t\t\t{\n\t\t\t\tconst string &obs_name = iobs;\n\t\t\t\tconst string &obs_group = obs_info_ptr->get_group(obs_name);\n\t\t\t\tauto it_pg = group_2_pool_group_map.find(obs_group);\n\t\t\t\tif (it_pg != group_2_pool_group_map.end())\n\t\t\t\t{\n\t\t\t\t\tconst string &pool_group = it_pg->second;\n\t\t\t\t\tif (obs_pooled_grp_std_dev.find(pool_group) != obs_pooled_grp_std_dev.end())\n\t\t\t\t\t{\n\t\t\t\t\t\tobs_2_sen_weight[iobs] = obs_pooled_grp_std_dev[pool_group];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//compute parameter standard deviations\n\t\tmap<string, double> par_std_dev;\n\t\tpar_std_dev = calc_parameter_unif_std_dev();\n\t\tobs_sen_file.calc_pooled_obs_sen(fout_mos, obs_2_sen_weight, par_std_dev);\n\t\tfile_manager_ptr->close_file(\"mos\");\n\t}\n\tfile_manager_ptr->close_file(\"msn\");\n\tfile_manager_ptr->close_file(\"raw\");\n}\n\nvoid MorrisMethod::calc_morris_obs(ostream &fout, MorrisObsSenFile &morris_sen_file)\n{\n\t// write standard Morris Sensitivity\n\tfout << \"observation_name,parameter_name,n_samples,sen_mean,sen_mean_abs,sen_std_dev\" << endl;\n\n\tfor (const auto &i_obs : morris_sen_file.obs_names_vec)\n\t{\n\t\t//fout << \"Method of Morris for observation: \" << i_obs << endl;\n\t\t//fout << \"parameter_name, n_samples, sen_mean, sen_mean_abs, sen_std_dev\" << endl;\n\t\t//fout << i_obs;\n\t\tfor (const auto &i_par : morris_sen_file.par_names_vec)\n\t\t{\n\t\t\tconst auto &it_senmap = morris_sen_file.map_obs_stats.find(make_pair(i_par, i_obs));\n\t\t\tif (it_senmap != morris_sen_file.map_obs_stats.end())\n\t\t\t{\n\t\t\t\tfout << i_obs <<\",\" << i_par << \",\" << it_senmap->second.comp_nsamples() << \",\" << it_senmap->second.comp_mean() << \",\" << it_senmap->second.comp_abs_mean() << \",\" << sqrt(it_senmap->second.comp_var()) << endl;\n\t\t\t}\n\t\t}\n\t\t//fout << endl;\n\t}\n}\n\n\nMorrisMethod::~MorrisMethod(void)\n{\n}\n", "meta": {"hexsha": "a667d3fa8c3d154ffdc4fdca52544932a5360ad6", "size": 15747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/src_pestpp/programs/gsa/MorrisMethod.cpp", "max_stars_repo_name": "jtwhite79/worked_example", "max_stars_repo_head_hexsha": "cae16f633073f82fa09c45ed37a080a902c59097", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-23T20:47:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-23T20:47:29.000Z", "max_issues_repo_path": "src/src_pestpp/programs/gsa/MorrisMethod.cpp", "max_issues_repo_name": "jtwhite79/worked_example", "max_issues_repo_head_hexsha": "cae16f633073f82fa09c45ed37a080a902c59097", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/src_pestpp/programs/gsa/MorrisMethod.cpp", "max_forks_repo_name": "jtwhite79/worked_example", "max_forks_repo_head_hexsha": "cae16f633073f82fa09c45ed37a080a902c59097", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-01-03T17:14:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-04T14:21:27.000Z", "avg_line_length": 29.3240223464, "max_line_length": 214, "alphanum_fraction": 0.6897186766, "num_tokens": 4781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.28622458756596625}}
{"text": "/*\n * Copyright 2010, 2011, 2012\n * François Bleibel,\n * Olivier Stasse,\n * Florent Lamiraux\n * Nicolas Mansard\n *\n * CNRS/AIST\n *\n */\n\n/* --------------------------------------------------------------------- */\n/* --- INCLUDE --------------------------------------------------------- */\n/* --------------------------------------------------------------------- */\n\n/* --- SOT --- */\n//#define VP_DEBUG\n//#define VP_DEBUG_MODE 45\n#include <dynamic-graph/command-bind.h>\n#include <dynamic-graph/command-getter.h>\n#include <dynamic-graph/command-setter.h>\n#include <dynamic-graph/command.h>\n\n#include <Eigen/LU>\n\n#include <sot/core/debug.hh>\n#include <sot/core/exception-feature.hh>\n#include <sot/core/feature-point6d.hh>\n\nusing namespace std;\nusing namespace dynamicgraph;\nusing namespace dynamicgraph::sot;\n\n#include <sot/core/factory.hh>\nDYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(FeaturePoint6d, \"FeaturePoint6d\");\n\n/* --------------------------------------------------------------------- */\n/* --- CLASS ----------------------------------------------------------- */\n/* --------------------------------------------------------------------- */\n\nconst FeaturePoint6d::ComputationFrameType\n    FeaturePoint6d::COMPUTATION_FRAME_DEFAULT = FRAME_DESIRED;\n\nFeaturePoint6d::FeaturePoint6d(const string &pointName)\n    : FeatureAbstract(pointName), computationFrame_(COMPUTATION_FRAME_DEFAULT),\n      positionSIN(NULL, \"sotFeaturePoint6d(\" + name +\n                            \")::input(matrixHomo)::position\"),\n      velocitySIN(NULL,\n                  \"sotFeaturePoint6d(\" + name + \")::input(vector)::velocity\"),\n      articularJacobianSIN(NULL, \"sotFeaturePoint6d(\" + name +\n                                     \")::input(matrix)::Jq\"),\n      error_th_(), R_(), Rref_(), Rt_(), Rreft_(), P_(3, 3), Pinv_(3, 3),\n      accuracy_(1e-8) {\n  jacobianSOUT.addDependency(positionSIN);\n  jacobianSOUT.addDependency(articularJacobianSIN);\n\n  errorSOUT.addDependency(positionSIN);\n\n  signalRegistration(positionSIN << articularJacobianSIN);\n  signalRegistration(errordotSOUT << velocitySIN);\n  errordotSOUT.setFunction(\n      boost::bind(&FeaturePoint6d::computeErrordot, this, _1, _2));\n  errordotSOUT.addDependency(velocitySIN);\n  errordotSOUT.addDependency(positionSIN);\n  errordotSOUT.addDependency(errorSOUT);\n\n  // Commands\n  //\n  {\n    using namespace dynamicgraph::command;\n    std::string docstring;\n    // Set computation frame\n    docstring = \"Set computation frame\\n\"\n                \"\\n\"\n                \"  Input:\\n\"\n                \"    a string: 'current' or 'desired'.\\n\"\n                \"      If 'current', the error is defined as the rotation \"\n                \"vector (VectorUTheta)\\n\"\n                \"      corresponding to the position of the reference in the \"\n                \"current frame:\\n\"\n                \"                         -1 *\\n\"\n                \"        error = utheta (M  M )\\n\"\n                \"      If 'desired',      *-1\\n\"\n                \"        error = utheta (M   M)\\n\";\n    addCommand(\"frame\",\n               new dynamicgraph::command::Setter<FeaturePoint6d, std::string>(\n                   *this, &FeaturePoint6d::computationFrame, docstring));\n    docstring = \"Get frame of computation of the error\\n\"\n                \"\\n\"\n                \"  See command 'frame' for definition.\\n\";\n    addCommand(\"getFrame\",\n               new dynamicgraph::command::Getter<FeaturePoint6d, std::string>(\n                   *this, &FeaturePoint6d::computationFrame, docstring));\n    addCommand(\n        \"keep\",\n        makeCommandVoid0(\n            *this, &FeaturePoint6d::servoCurrentPosition,\n            docCommandVoid0(\n                \"modify the desired position to servo at current pos.\")));\n  }\n}\n\nvoid FeaturePoint6d::addDependenciesFromReference(void) {\n  assert(isReferenceSet());\n  errorSOUT.addDependency(getReference()->positionSIN);\n  jacobianSOUT.addDependency(getReference()->positionSIN);\n}\n\nvoid FeaturePoint6d::removeDependenciesFromReference(void) {\n  assert(isReferenceSet());\n  errorSOUT.removeDependency(getReference()->positionSIN);\n  jacobianSOUT.removeDependency(getReference()->positionSIN);\n}\n\n/* --------------------------------------------------------------------- */\n/* --------------------------------------------------------------------- */\n/* --------------------------------------------------------------------- */\nvoid FeaturePoint6d::computationFrame(const std::string &inFrame) {\n  if (inFrame == \"current\")\n    computationFrame_ = FRAME_CURRENT;\n  else if (inFrame == \"desired\")\n    computationFrame_ = FRAME_DESIRED;\n  else {\n    std::string msg(\"FeaturePoint6d::computationFrame: \" + inFrame +\n                    \": invalid argument,\\n\"\n                    \"expecting 'current' or 'desired'\");\n    throw ExceptionFeature(ExceptionFeature::GENERIC, msg);\n  }\n}\n\n/// \\brief Get computation frame\nstd::string FeaturePoint6d::computationFrame() const {\n  switch (computationFrame_) {\n  case FRAME_CURRENT:\n    return \"current\";\n  case FRAME_DESIRED:\n    return \"desired\";\n  }\n  assert(false && \"Case not handled\");\n  return \"Case not handled\";\n}\n/* --------------------------------------------------------------------- */\n/* --------------------------------------------------------------------- */\n/* --------------------------------------------------------------------- */\n\nunsigned int &FeaturePoint6d::getDimension(unsigned int &dim, int time) {\n  sotDEBUG(25) << \"# In {\" << endl;\n\n  const Flags &fl = selectionSIN.access(time);\n\n  dim = 0;\n  for (int i = 0; i < 6; ++i)\n    if (fl(i))\n      dim++;\n\n  sotDEBUG(25) << \"# Out }\" << endl;\n  return dim;\n}\n\n/** Compute the interaction matrix from a subset of\n * the possible features.\n */\nMatrix &FeaturePoint6d::computeJacobian(Matrix &J, int time) {\n  sotDEBUG(15) << \"# In {\" << endl;\n\n  const Matrix &Jq = articularJacobianSIN(time);\n  const int &dim = dimensionSOUT(time);\n  const Flags &fl = selectionSIN(time);\n\n  sotDEBUG(25) << \"dim = \" << dimensionSOUT(time) << \" time:\" << time << \" \"\n               << dimensionSOUT.getTime() << \" \" << dimensionSOUT.getReady()\n               << endl;\n  sotDEBUG(25) << \"selec = \" << selectionSIN(time) << \" time:\" << time << \" \"\n               << selectionSIN.getTime() << \" \" << selectionSIN.getReady()\n               << endl;\n\n  sotDEBUG(15) << \"Dimension=\" << dim << std::endl;\n\n  const Matrix::Index cJ = Jq.cols();\n  J.resize(dim, cJ);\n  Matrix LJq(6, cJ);\n\n  if (FRAME_CURRENT == computationFrame_) {\n    /* The Jacobian on rotation is equal to Jr = - hdRh Jr6d.\n     * The Jacobian in translation is equalt to Jt = [hRw(wthd-wth)]x Jr - Jt.\n     */\n    const MatrixHomogeneous &wMh = positionSIN(time);\n    MatrixRotation wRh;\n    wRh = wMh.linear();\n    MatrixRotation wRhd;\n    Vector hdth(3), Rhdth(3);\n\n    if (isReferenceSet()) {\n      const MatrixHomogeneous &wMhd = getReference()->positionSIN(time);\n      wRhd = wMhd.linear();\n      for (unsigned int i = 0; i < 3; ++i)\n        hdth(i) = wMhd(i, 3) - wMh(i, 3);\n    } else {\n      wRhd.setIdentity();\n      for (unsigned int i = 0; i < 3; ++i)\n        hdth(i) = -wMh(i, 3);\n    }\n    Rhdth = (wRh.inverse()) * hdth;\n    MatrixRotation hdRh;\n    hdRh = (wRhd.inverse()) * wRh;\n\n    Matrix Lx(6, 6);\n    for (unsigned int i = 0; i < 3; i++) {\n      for (unsigned int j = 0; j < 3; j++) {\n        if (i == j) {\n          Lx(i, j) = -1;\n        } else {\n          Lx(i, j) = 0;\n        }\n        Lx(i + 3, j) = 0;\n        Lx(i + 3, j + 3) = -hdRh(i, j);\n      }\n    }\n    const double &X = Rhdth(0), &Y = Rhdth(1), &Z = Rhdth(2);\n    Lx(0, 4) = -Z;\n    Lx(0, 5) = Y;\n    Lx(1, 3) = Z;\n    Lx(1, 5) = -X;\n    Lx(2, 3) = -Y;\n    Lx(2, 4) = X;\n    Lx(0, 3) = 0;\n    Lx(1, 4) = 0;\n    Lx(2, 5) = 0;\n    sotDEBUG(15) << \"Lx= \" << Lx << endl;\n\n    LJq = Lx * Jq;\n  } else {\n    /* The Jacobian in rotation is equal to Jr = hdJ = hdRh Jr.\n     * The Jacobian in translation is equal to Jr = hdJ = hdRh Jr. */\n    const MatrixHomogeneous &wMh = positionSIN(time);\n    MatrixRotation wRh;\n    wRh = wMh.linear();\n    MatrixRotation hdRh;\n\n    if (isReferenceSet()) {\n      const MatrixHomogeneous &wMhd = getReference()->positionSIN(time);\n      MatrixRotation wRhd;\n      wRhd = wMhd.linear();\n      hdRh = (wRhd.inverse()) * wRh;\n    } else {\n      hdRh = wRh;\n    }\n\n    LJq.fill(0);\n    for (unsigned int i = 0; i < 3; i++)\n      for (unsigned int j = 0; j < cJ; j++) {\n        for (unsigned int k = 0; k < 3; k++) {\n          LJq(i, j) += hdRh(i, k) * Jq(k, j);\n          LJq(i + 3, j) += hdRh(i, k) * Jq(k + 3, j);\n        }\n      }\n  }\n\n  /* Select the active line of Jq. */\n  unsigned int rJ = 0;\n  for (unsigned int r = 0; r < 6; ++r)\n    if (fl(r)) {\n      for (unsigned int c = 0; c < cJ; ++c)\n        J(rJ, c) = LJq(r, c);\n      rJ++;\n    }\n\n  sotDEBUG(15) << \"# Out }\" << endl;\n  return J;\n}\n\n#define SOT_COMPUTE_H1MH2(wMh, wMhd, hMhd)                                     \\\n  {                                                                            \\\n    MatrixHomogeneous hMw;                                                     \\\n    hMw = wMh.inverse(Eigen::Affine);                                          \\\n    sotDEBUG(15) << \"hMw = \" << hMw << endl;                                   \\\n    hMhd = hMw * wMhd;                                                         \\\n    sotDEBUG(15) << \"hMhd = \" << hMhd << endl;                                 \\\n  }\n\n/** Compute the error between two visual features from a subset\n * a the possible features.\n */\nVector &FeaturePoint6d::computeError(Vector &error, int time) {\n  sotDEBUGIN(15);\n\n  const Flags &fl = selectionSIN(time);\n  const MatrixHomogeneous &wMh = positionSIN(time);\n  sotDEBUG(15) << \"wMh = \" << wMh << endl;\n\n  /* Computing only translation:                                        *\n   * trans( hMw wMhd ) = htw + hRw wthd                                 *\n   *                   = -hRw wth + hrW wthd                            *\n   *                   = hRw ( wthd - wth )                             *\n   * The second line is obtained by writting hMw as the inverse of wMh. */\n\n  MatrixHomogeneous hMhd;\n  if (isReferenceSet()) {\n    const MatrixHomogeneous &wMhd = getReference()->positionSIN(time);\n    sotDEBUG(15) << \"wMhd = \" << wMhd << endl;\n    switch (computationFrame_) {\n    case FRAME_CURRENT:\n      SOT_COMPUTE_H1MH2(wMh, wMhd, hMhd);\n      break;\n    case FRAME_DESIRED:\n      SOT_COMPUTE_H1MH2(wMhd, wMh, hMhd);\n      break; // Compute hdMh indeed.\n    };\n  } else {\n    switch (computationFrame_) {\n    case FRAME_CURRENT:\n      hMhd = wMh.inverse();\n      break;\n    case FRAME_DESIRED:\n      hMhd = wMh;\n      break; // Compute hdMh indeed.\n    };\n  }\n\n  sotDEBUG(25) << \"dim = \" << dimensionSOUT(time) << \" time:\" << time << \" \"\n               << dimensionSOUT.getTime() << \" \" << dimensionSOUT.getReady()\n               << endl;\n  sotDEBUG(25) << \"selec = \" << selectionSIN(time) << \" time:\" << time << \" \"\n               << selectionSIN.getTime() << \" \" << selectionSIN.getReady()\n               << endl;\n\n  error.resize(dimensionSOUT(time));\n  unsigned int cursor = 0;\n  for (unsigned int i = 0; i < 3; ++i) {\n    if (fl(i))\n      error(cursor++) = hMhd(i, 3);\n  }\n\n  if (fl(3) || fl(4) || fl(5)) {\n    MatrixRotation hRhd;\n    hRhd = hMhd.linear();\n    error_th_.fromRotationMatrix(hRhd);\n    for (unsigned int i = 0; i < 3; ++i) {\n      if (fl(i + 3))\n        error(cursor++) = error_th_.angle() * error_th_.axis()(i);\n    }\n  }\n\n  sotDEBUGOUT(15);\n  return error;\n}\n\nvoid FeaturePoint6d::inverseJacobianRodrigues() {\n  const double &r1 = error_th_.angle() * error_th_.axis()(0);\n  const double &r2 = error_th_.angle() * error_th_.axis()(1);\n  const double &r3 = error_th_.angle() * error_th_.axis()(2);\n  double r1_2 = r1 * r1;\n  double r2_2 = r2 * r2;\n  double r3_2 = r3 * r3;\n  double r1_3 = r1 * r1_2;\n  double r2_3 = r2 * r2_2;\n  double r3_3 = r3 * r3_2;\n  double r1_4 = r1_2 * r1_2;\n  double r2_4 = r2_2 * r2_2;\n  double r3_4 = r3_2 * r3_2;\n  double norm_2 = r3_2 + r2_2 + r1_2;\n\n  if (norm_2 < accuracy_) {\n    P_.setIdentity();\n  } else {\n    // This code has been generated by maxima software\n    P_(0, 0) =\n        ((r3_2 + r2_2) * sqrt(norm_2) * sin(sqrt(norm_2)) + r1_2 * r3_2 +\n         r1_2 * r2_2 + r1_4) /\n        (r3_4 + (2 * r2_2 + 2 * r1_2) * r3_2 + r2_4 + 2 * r1_2 * r2_2 + r1_4);\n    P_(0, 1) =\n        -(r1 * r2 * sqrt(norm_2) * sin(sqrt(norm_2)) +\n          (r3_3 + (r2_2 + r1_2) * r3) * cos(sqrt(norm_2)) - r3_3 -\n          r1 * r2 * r3_2 + (-r2_2 - r1_2) * r3 - r1 * r2_3 - r1_3 * r2) /\n        (r3_4 + (2 * r2_2 + 2 * r1_2) * r3_2 + r2_4 + 2 * r1_2 * r2_2 + r1_4);\n    P_(0, 2) =\n        -(r1 * r3 * sqrt(norm_2) * sin(sqrt(norm_2)) +\n          (-r2 * r3_2 - r2_3 - r1_2 * r2) * cos(sqrt(norm_2)) - r1 * r3_3 +\n          r2 * r3_2 + (-r1 * r2_2 - r1_3) * r3 + r2_3 + r1_2 * r2) /\n        (r3_4 + (2 * r2_2 + 2 * r1_2) * r3_2 + r2_4 + 2 * r1_2 * r2_2 + r1_4);\n    P_(1, 0) =\n        -(r1 * r2 * sqrt(norm_2) * sin(sqrt(norm_2)) +\n          ((-r2_2 - r1_2) * r3 - r3_3) * cos(sqrt(norm_2)) + r3_3 -\n          r1 * r2 * r3_2 + (r2_2 + r1_2) * r3 - r1 * r2_3 - r1_3 * r2) /\n        (r3_4 + (2 * r2_2 + 2 * r1_2) * r3_2 + r2_4 + 2 * r1_2 * r2_2 + r1_4);\n    P_(1, 1) =\n        ((r3_2 + r1_2) * sqrt(norm_2) * sin(sqrt(norm_2)) + r2_2 * r3_2 + r2_4 +\n         r1_2 * r2_2) /\n        (r3_4 + (2 * r2_2 + 2 * r1_2) * r3_2 + r2_4 + 2 * r1_2 * r2_2 + r1_4);\n    P_(1, 2) =\n        -(r2 * r3 * sqrt(norm_2) * sin(sqrt(norm_2)) +\n          (r1 * r3_2 + r1 * r2_2 + r1_3) * cos(sqrt(norm_2)) - r2 * r3_3 -\n          r1 * r3_2 + (-r2_3 - r1_2 * r2) * r3 - r1 * r2_2 - r1_3) /\n        (r3_4 + (2 * r2_2 + 2 * r1_2) * r3_2 + r2_4 + 2 * r1_2 * r2_2 + r1_4);\n    P_(2, 0) =\n        -(r1 * r3 * sqrt(norm_2) * sin(sqrt(norm_2)) +\n          (r2 * r3_2 + r2_3 + r1_2 * r2) * cos(sqrt(norm_2)) - r1 * r3_3 -\n          r2 * r3_2 + (-r1 * r2_2 - r1_3) * r3 - r2_3 - r1_2 * r2) /\n        (r3_4 + (2 * r2_2 + 2 * r1_2) * r3_2 + r2_4 + 2 * r1_2 * r2_2 + r1_4);\n    P_(2, 1) =\n        -(r2 * r3 * sqrt(norm_2) * sin(sqrt(norm_2)) +\n          (-r1 * r3_2 - r1 * r2_2 - r1_3) * cos(sqrt(norm_2)) - r2 * r3_3 +\n          r1 * r3_2 + (-r2_3 - r1_2 * r2) * r3 + r1 * r2_2 + r1_3) /\n        (r3_4 + (2 * r2_2 + 2 * r1_2) * r3_2 + r2_4 + 2 * r1_2 * r2_2 + r1_4);\n    P_(2, 2) =\n        ((r2_2 + r1_2) * sqrt(norm_2) * sin(sqrt(norm_2)) + r3_4 +\n         (r2_2 + r1_2) * r3_2) /\n        (r3_4 + (2 * r2_2 + 2 * r1_2) * r3_2 + r2_4 + 2 * r1_2 * r2_2 + r1_4);\n  }\n  Pinv_ = P_.inverse();\n}\n\nVector &FeaturePoint6d::computeErrordot(Vector &errordot, int time) {\n  if (isReferenceSet()) {\n    const Vector &velocity = getReference()->velocitySIN(time);\n    const MatrixHomogeneous &M = positionSIN(time);\n    const MatrixHomogeneous &Mref = getReference()->positionSIN(time);\n    // Linear velocity if the reference frame\n    v_(0) = velocity(0);\n    v_(1) = velocity(1);\n    v_(2) = velocity(2);\n    // Angular velocity if the reference frame\n    omega_(0) = velocity(3);\n    omega_(1) = velocity(4);\n    omega_(2) = velocity(5);\n    R_ = M.linear();\n    t_ = M.translation();\n    Rt_ = R_.transpose();\n    Rref_ = Mref.linear();\n    tref_ = Mref.translation();\n    Rreft_ = Rref_.transpose();\n    errorSOUT.recompute(time);\n    inverseJacobianRodrigues();\n    switch (computationFrame_) {\n    case FRAME_CURRENT:\n      // \\dot{e}_{t} = R^{T} v\n      errordot_t_ = Rt_ * v_;\n      // \\dot{e}_{\\theta} = P^{-1}(e_{theta})R^{*T}\\omega\n      Rreftomega_ = Rreft_ * omega_;\n      errordot_th_ = Pinv_ * Rreftomega_;\n      break;\n    case FRAME_DESIRED:\n      errordot_t_ = Rreft_ * (omega_.cross(tref_ - t_) - v_);\n      errordot_th_ = -Pinv_ * (Rt_ * omega_);\n      break;\n    }\n  } else {\n    errordot_t_.setZero();\n    errordot_th_.setZero();\n  }\n\n  const Flags &fl = selectionSIN(time);\n  errordot.resize(dimensionSOUT(time));\n  unsigned int cursor = 0;\n  for (unsigned int i = 0; i < 3; ++i) {\n    if (fl(i)) {\n      errordot(cursor++) = errordot_t_(i);\n    }\n  }\n\n  if (fl(3) || fl(4) || fl(5)) {\n    for (unsigned int i = 0; i < 3; ++i) {\n      if (fl(i + 3)) {\n        errordot(cursor++) = errordot_th_(i);\n      }\n    }\n  }\n\n  return errordot;\n}\n\n/* Modify the value of the reference (sdes) so that it corresponds\n * to the current position. The effect on the servo is to maintain the\n * current position and correct any drift. */\nvoid FeaturePoint6d::servoCurrentPosition(void) {\n  sotDEBUGIN(15);\n\n  if (!isReferenceSet()) {\n    sotERROR << \"The reference is not set, this function should not be called\"\n             << std::endl;\n    throw ExceptionFeature(\n        ExceptionFeature::GENERIC,\n        \"The reference is not set, this function should not be called\");\n  }\n  getReference()->positionSIN = positionSIN.accessCopy();\n\n  sotDEBUGOUT(15);\n}\n\nstatic const char *featureNames[] = {\"X \", \"Y \", \"Z \", \"RX\", \"RY\", \"RZ\"};\nvoid FeaturePoint6d::display(std::ostream &os) const {\n  os << \"Point6d <\" << name << \">: (\";\n\n  try {\n    const Flags &fl = selectionSIN.accessCopy();\n    bool first = true;\n    for (int i = 0; i < 6; ++i)\n      if (fl(i)) {\n        if (first) {\n          first = false;\n        } else {\n          os << \",\";\n        }\n        os << featureNames[i];\n      }\n    os << \") \";\n  } catch (ExceptionAbstract e) {\n    os << \" selectSIN not set.\";\n  }\n}\n", "meta": {"hexsha": "5568faa4086b002e6eab546c9d8f3243e0a735d5", "size": 17284, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/feature/feature-point6d.cpp", "max_stars_repo_name": "Rascof/sot-core", "max_stars_repo_head_hexsha": "281ed2a1b40b7945b5a3d5735f785b9004b19f87", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2016-03-28T07:15:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T13:41:06.000Z", "max_issues_repo_path": "src/feature/feature-point6d.cpp", "max_issues_repo_name": "Rascof/sot-core", "max_issues_repo_head_hexsha": "281ed2a1b40b7945b5a3d5735f785b9004b19f87", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 121.0, "max_issues_repo_issues_event_min_datetime": "2015-02-17T08:38:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-01T10:54:05.000Z", "max_forks_repo_path": "src/feature/feature-point6d.cpp", "max_forks_repo_name": "Rascof/sot-core", "max_forks_repo_head_hexsha": "281ed2a1b40b7945b5a3d5735f785b9004b19f87", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2015-07-01T16:25:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-08T15:06:58.000Z", "avg_line_length": 33.8238747554, "max_line_length": 80, "alphanum_fraction": 0.5185720898, "num_tokens": 5591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283035, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.28622435070446317}}
{"text": "/* Copyright (c) 2017, Waterloo Autonomous Vehicles Laboratory (WAVELab),\n * Waterloo Intelligent Systems Engineering Lab (WISELab),\n * University of Waterloo.\n *\n * Refer to the accompanying LICENSE file for license information.\n *\n * ############################################################################\n ******************************************************************************\n |                                                                            |\n |                         /\\/\\__/\\_/\\      /\\_/\\__/\\/\\                       |\n |                         \\          \\____/          /                       |\n |                          '----________________----'                        |\n |                              /                \\                            |\n |                            O/_____/_______/____\\O                          |\n |                            /____________________\\                          |\n |                           /    (#UNIVERSITY#)    \\                         |\n |                           |[**](#OFWATERLOO#)[**]|                         |\n |                           \\______________________/                         |\n |                            |_\"\"__|_,----,_|__\"\"_|                          |\n |                            ! !                ! !                          |\n |                            '-'                '-'                          |\n |       __    _   _  _____  ___  __  _  ___  _    _  ___  ___   ____  ____   |\n |      /  \\  | | | ||_   _|/ _ \\|  \\| |/ _ \\| \\  / |/ _ \\/ _ \\ /     |       |\n |     / /\\ \\ | |_| |  | |  ||_||| |\\  |||_|||  \\/  |||_||||_|| \\===\\ |====   |\n |    /_/  \\_\\|_____|  |_|  \\___/|_| \\_|\\___/|_|\\/|_|\\___/\\___/ ____/ |____   |\n |                                                                            |\n ******************************************************************************\n * ############################################################################\n *\n * File: pose_cov_comp.cpp\n * Desc: File containing the impl. for pose composition with uncertainty\n * Auth: Chunshang Li and Jordan Hu\n *\n * ############################################################################\n */\n\n#include \"wave/utils/pose_cov_comp.hpp\"\n#include <Eigen/Dense>\n\nnamespace wave {\n\nPoseWithCovariance::PoseWithCovariance() {\n    this->position.setZero();\n    this->rotation_matrix.setIdentity();\n    this->covariance.setZero();\n}\n\nPoseWithCovariance::PoseWithCovariance(Vector6 &p, Matrix6x6 &cov) {\n    Vector3 ypr;\n\n    ypr << p[5], p[4], p[3];\n\n    this->position = p.block<3, 1>(0, 0);\n    this->rotation_matrix = pose_comp::yprToRotMatrix(ypr);\n    this->covariance = cov;\n}\n\nPoseWithCovariance::PoseWithCovariance(Vector3 &p,\n                                       Matrix3x3 &r,\n                                       Matrix6x6 &cov) {\n    this->position = p;\n    this->rotation_matrix = r;\n    this->covariance = cov;\n}\n\n\nVector3 PoseWithCovariance::getPosition() const {\n    return this->position;\n}\n\nVector3 PoseWithCovariance::getYPR() const {\n    Vector3 ypr = pose_comp::rotMatrixToYPR(this->rotation_matrix);\n    return ypr;\n}\n\nEigen::Quaterniond PoseWithCovariance::getQuaternion() const {\n    Eigen::Quaterniond q = pose_comp::rotMatrixToQuat(this->rotation_matrix);\n\n    q.normalize();\n\n    return q;\n}\n\nVector7 PoseWithCovariance::getPoseQuaternion() const {\n    Vector7 pose;\n    Eigen::Quaterniond q = this->getQuaternion();\n    Vector4 q_coeffs;\n\n    q_coeffs << q.coeffs().w(), q.coeffs().x(), q.coeffs().y(), q.coeffs().z();\n    pose << this->position, q_coeffs;\n\n    return pose;\n}\n\nEigen::Affine3d PoseWithCovariance::getTransformMatrix() const {\n    Eigen::Affine3d T_m;\n\n    T_m.translation() = this->position;\n    T_m.linear() = this->rotation_matrix;\n\n    return T_m;\n}\n\nPoseWithCovariance composePose(PoseWithCovariance &p1, PoseWithCovariance &p2) {\n    PoseWithCovariance r;  // store all the results\n\n    // Use Eigen Transform to transform poses\n    // This is the same as implementing Equation (5.5)\n    Eigen::Affine3d T_p1, T_p2, T_r;\n    T_p1 = p1.getTransformMatrix();\n    T_p2 = p2.getTransformMatrix();\n    T_r = T_p1 * T_p2;\n\n    r.position = T_r.translation();\n    r.rotation_matrix = T_r.rotation();\n\n    // compute the covariances\n    // p6 = [x y z roll pitch yaw]', transformation using YPR\n    // p7 = [x y z qr, qx, qy, qz]', transformation using Quaternion, qr is qw\n\n    // get covariances from PoseWithCovariance objects\n    Matrix6x6 cov_p1 = p1.covariance, cov_p2 = p2.covariance;\n\n    // pR7 is the composed pose in p7 form\n    // p17 is the p1 in p7 form, p27 is p2 in p7 form, p16 is p1 in p6 form,\n    // p26 is p2 in p6 form\n    Vector7 pR7, p17, p27;\n    Vector6 p16, p26;\n\n    pR7 = r.getPoseQuaternion();\n    p17 = p1.getPoseQuaternion();\n    p27 = p2.getPoseQuaternion();\n\n    p16 << p1.getPosition(), pose_comp::quatToYPR(p1.getQuaternion());\n    p26 << p2.getPosition(), pose_comp::quatToYPR(p2.getQuaternion());\n\n    // Equation (5.3)\n    Matrix6x7 jacobian_p7_to_p6 = jacobian_p7_to_p6_wrt_p(pR7);\n    Matrix7x7 jacobian_p7_p7_composition =\n      jacobian_p7_p7_Composition_wrt_p1(p17, p27);\n    Matrix7x6 jacobian_p6_to_p7 = jacobian_p6_to_p7_wrt_p(p16);\n    Matrix6x6 dfpc_dp =\n      jacobian_p7_to_p6 * jacobian_p7_p7_composition * jacobian_p6_to_p7;\n\n    // Equation (5.4)\n    jacobian_p7_p7_composition = jacobian_p7_p7_Composition_wrt_p2(p17, p27);\n    jacobian_p6_to_p7 = jacobian_p6_to_p7_wrt_p(p26);\n    Matrix6x6 dfpc_dq =\n      jacobian_p7_to_p6 * jacobian_p7_p7_composition * jacobian_p6_to_p7;\n\n    // Equation (5.2)\n    // putting everything together\n    Matrix6x6 final_cov = dfpc_dp * cov_p1 * dfpc_dp.transpose() +\n                          dfpc_dq * cov_p2 * dfpc_dq.transpose();\n\n    r.covariance = final_cov;\n\n    return r;\n}\n\n/// the jacobian of quaternion normalization function\n/// quat in the form of [qr, qx, qt, qz]\n/// Equation (1.7)\nMatrix4x4 jacobian_Quat_Norm_wrt_q(const Vector4 &q) {\n    const double &qr = q(0), &qx = q(1), &qy = q(2), &qz = q(3);\n    Matrix4x4 m;\n\n    // See Equation (1.7)\n    double k = 1 / pow(qr * qr + qx * qx + qy * qy + qz * qz, 1.5);\n\n    // clang-format off\n    m << qx * qx + qy * qy + qz * qz, -qr * qx, -qr * qy, -qr * qz,\n        -qx * qr, qr * qr + qy * qy + qz * qz, -qx * qy, -qx * qz,\n        -qy * qr, -qy * qx, qr * qr + qx * qx + qz * qz, -qy * qz,\n        -qz * qr, -qz * qx, -qz * qy, qr * qr + qx * qx + qy * qy;\n    // clang-format on\n\n    m = m * k;\n\n    return m;\n}\n\n// the jacobian of normalized quaternion to rpy function\n// Equation (2.9) to Equation (2.10)\nMatrix3x4 jacobian_Quat_Norm_to_Rpy_wrt_q(const Vector4 &q) {\n    const double &qr = q(0), &qx = q(1), &qy = q(2), &qz = q(3);\n\n    Matrix3x4 m;\n\n    // Equation (2.9)\n    double delta = qr * qy - qx * qz;\n\n    // handle special (rare) cases for when |delta| = 0.5\n    if (fabs(delta - 0.5) < 1e-10) {  // delta = 0.5\n                                      // clang-format off\n        m << (2*qx)/(qr*qr + qx*qx), -(2*qr)/(qr*qr + qx*qx), 0, 0,\n                                    0,                     0, 0, 0,\n                                    0,                     0, 0, 0;\n\n        // clang-format on\n\n    } else if (fabs(delta + 0.5) < 1e-10) {  // delta = -0.5\n                                             // clang-format off\n        m << -(2*qx)/(qr*qr + qx*qx), (2*qr)/(qr*qr + qx*qx), 0, 0,\n                                     0,                    0, 0, 0,\n                                     0,                    0, 0, 0;\n                                             // clang-format on\n    } else {\n        // Equation (2.10)\n        // Jacobian obtained symbolically from SymPy by taking the derivative\n        // of this below\n        //     roll  = [[        2*(qr*qz + qx*qy)/(-2*qy*qy - 2*qz*qz + 1)],\n        //     pitch =  [                           asin(2*qr*qy - 2*qx*qz)],\n        //     yaw   =  [atan((2*qr*qx + 2*qy*qz)/(-2*qx*qx - 2*qy*qy + 1))]]\n        // with respect to qr, qx, qy, qz using SymPy\n\n        // just for convenience\n        auto sq = [](double x) { return x * x; };\n\n        // clang-format off\n        m << \n            2*qz*(-2*qy*qy - 2*qz*qz + 1)/(sq(2*qr*qz + 2*qx*qy) + sq(-2*qy*qy - 2*qz*qz + 1)),\n            2*qy*(-2*qy*qy - 2*qz*qz + 1)/(sq(2*qr*qz + 2*qx*qy) + sq(-2*qy*qy - 2*qz*qz + 1)),\n            2*qx*(-2*qy*qy - 2*qz*qz + 1)/(sq(2*qr*qz + 2*qx*qy) + sq(-2*qy*qy - 2*qz*qz + 1)) - 4*qy*(-2*qr*qz - 2*qx*qy)/(sq(2*qr*qz + 2*qx*qy) + sq(-2*qy*qy - 2*qz*qz + 1)),\n            2*qr*(-2*qy*qy - 2*qz*qz + 1)/(sq(2*qr*qz + 2*qx*qy) + sq(-2*qy*qy - 2*qz*qz + 1)) - 4*qz*(-2*qr*qz - 2*qx*qy)/(sq(2*qr*qz + 2*qx*qy) + sq(-2*qy*qy - 2*qz*qz + 1)),\n\n            2*qy/sqrt(-sq(2*qr*qy - 2*qx*qz) + 1),\n            -2*qz/sqrt(-sq(2*qr*qy - 2*qx*qz) + 1),\n            2*qr/sqrt(-sq(2*qr*qy - 2*qx*qz) + 1),\n            -2*qx/sqrt(-sq(2*qr*qy - 2*qx*qz) + 1),\n\n            2*qx*(-2*qx*qx - 2*qy*qy + 1)/(sq(2*qr*qx + 2*qy*qz) + sq(-2*qx*qx - 2*qy*qy + 1)),\n            2*qr*(-2*qx*qx - 2*qy*qy + 1)/(sq(2*qr*qx + 2*qy*qz) + sq(-2*qx*qx - 2*qy*qy + 1)) - 4*qx*(-2*qr*qx - 2*qy*qz)/(sq(2*qr*qx + 2*qy*qz) + sq(-2*qx*qx - 2*qy*qy + 1)),\n            -4*qy*(-2*qr*qx - 2*qy*qz)/(sq(2*qr*qx + 2*qy*qz) + sq(-2*qx*qx - 2*qy*qy + 1)) + 2*qz*(-2*qx*qx - 2*qy*qy + 1)/(sq(2*qr*qx + 2*qy*qz) + sq(-2*qx*qx - 2*qy*qy + 1)),\n            2*qy*(-2*qx*qx - 2*qy*qy + 1)/(sq(2*qr*qx + 2*qy*qz) + sq(-2*qx*qx - 2*qy*qy + 1));\n\n        // clang-format on\n    }\n\n    return m;\n}\n\n/// the jacobian of p7 to p6 conversion\n/// Equation (2.12)\nMatrix6x7 jacobian_p7_to_p6_wrt_p(const Vector7 &p) {\n    Matrix6x7 r = Matrix6x7::Zero();\n\n    // Equation (2.12)\n    // bottom left 3x3 is zero\n    // top right 3x4 is zero\n    // top left 3x3 is identity\n    r(0, 0) = 1;\n    r(1, 1) = 1;\n    r(2, 2) = 1;\n\n    // This function takes the un-normalized quaternion\n    Matrix4x4 jacobian_quat_norm =\n      jacobian_Quat_Norm_wrt_q(p.block<4, 1>(3, 0));\n\n    Matrix3x4 jacobian_quat_norm_to_rpy =\n      jacobian_Quat_Norm_to_Rpy_wrt_q(p.block<4, 1>(3, 0));\n\n    r.block<3, 4>(3, 3) = jacobian_quat_norm_to_rpy * jacobian_quat_norm;\n\n    return r;\n}\n\n// jacobian of composing a point to a p7\n// Equation (3.8)\nMatrix3x7 jacobian_p7_Point_Composition_wrt_p(const Vector7 &p,\n                                              const Vector3 &a) {\n    Matrix3x7 m = Matrix3x7::Zero();\n\n    // The 3x3 on the top left is the identity matrix\n    m.block<3, 3>(0, 0) << 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0;\n\n    // Equation (3.9)\n    double ax = a(0), ay = a(1), az = a(2);\n    double qr = p(3), qx = p(4), qy = p(5), qz = p(6);\n\n    // clang-format off\n    m.block<3, 4>(0, 3) <<\n        -qz*ay+qy*az, qy*ay+qz*az, -2*qy*ax+qx*ay+qr*az, -2*qz*ax-qr*ay+qx*az,\n        qz*ax-qx*az, qy*ax-2*qx*ay-qr*az, qx*ax+qz*az, qr*ax-2*qz*ay+qy*az,\n        -qy*ax+qx*ay, qz*ax+qr*ay-2*qx*az, -qr*ax+qz*ay-2*qy*az, qx*ax+qy*ay;\n    // clang-format on\n\n    m.block<3, 4>(0, 3) *= 2;\n\n    // applying jacobian normalization\n    Matrix4x4 jacobian_quat_norm =\n      jacobian_Quat_Norm_wrt_q(p.block<4, 1>(3, 0));\n    m.block<3, 4>(0, 3) *= jacobian_quat_norm;\n\n    return m;\n}\n\n// jacobian of the composition of p7 poses\n// Equation (5.8)\nMatrix7x7 jacobian_p7_p7_Composition_wrt_p1(const Vector7 &p1,\n                                            const Vector7 &p2) {\n    Matrix7x7 m = Matrix7x7::Zero();\n\n    Vector4 q2 = p2.block<4, 1>(3, 0);\n    double qr2 = q2(0), qx2 = q2(1), qy2 = q2(2), qz2 = q2(3);\n\n    // clang-format off\n    m.block<4, 4>(3, 3) << qr2, -qx2, -qy2, -qz2,\n                           qx2, qr2, qz2, -qy2,\n                           qy2, -qz2, qr2, qx2,\n                           qz2, qy2, -qx2, qr2;\n    // clang-format on\n\n    // Note: this quaternion normalization jacobian matrix is not present in\n    // the book's formulation, but it should be there if a jacobian\n    // normalization is performed on the input\n    Matrix4x4 jacobian_quat_norm =\n      jacobian_Quat_Norm_wrt_q(p1.block<4, 1>(3, 0));\n    m.block<4, 4>(3, 3) *= jacobian_quat_norm;\n\n    m.block<3, 7>(0, 0) =\n      jacobian_p7_Point_Composition_wrt_p(p1, p2.block<3, 1>(0, 0));\n\n    return m;\n}\n\n// jacobian of composing a point to a p7\n// Equation (3.10)\nMatrix3x3 jacobian_p7_Point_Composition_wrt_a(const Vector7 &p,\n                                              const Vector3 &a) {\n    Matrix3x3 m = Matrix3x3::Zero();\n\n    double qr = p(3), qx = p(4), qy = p(5), qz = p(6);\n\n    // clang-format off\n    m << 0.5 - qy*qy - qz*qz , qx*qy - qr*qz, qr*qy + qx*qz,\n         qr*qz + qx*qy, 0.5 - qx*qx - qz*qz, qy*qz - qr*qx,\n         qx*qz - qr*qy, qr*qx + qy*qz, 0.5 - qx*qx - qy*qy;\n    // clang-format on\n\n    m *= 2;\n\n    // To avoid warnings\n    (void) a;\n\n    return m;\n}\n\n// jacobian of the composition of p7 poses\n// Equation (5.9)\nMatrix7x7 jacobian_p7_p7_Composition_wrt_p2(const Vector7 &p1,\n                                            const Vector7 &p2) {\n    Matrix7x7 m = Matrix7x7::Zero();\n\n    Vector4 q1 = p1.block<4, 1>(3, 0);\n    double qr1 = q1(0), qx1 = q1(1), qy1 = q1(2), qz1 = q1(3);\n\n    // clang-format off\n    m.block<4, 4>(3, 3) << qr1, -qx1, -qy1, -qz1,\n                           qx1, qr1, -qz1, qy1,\n                           qy1, qz1, qr1, -qx1,\n                           qz1, -qy1, qx1, qr1;\n    // clang-format on\n\n    // Note: this quaternion normalization jacobian matrix is not present in\n    // the book's formulation, but it should be there if a jacobian\n    // normalization is performed on the input\n    Matrix4x4 jacobian_quat_norm =\n      jacobian_Quat_Norm_wrt_q(p2.block<4, 1>(3, 0));\n    m.block<4, 4>(3, 3) *= jacobian_quat_norm;\n\n    m.block<3, 3>(0, 0) =\n      jacobian_p7_Point_Composition_wrt_a(p1, p2.block<3, 1>(0, 0));\n\n    return m;\n}\n\n// jacobian of converting a p6 to a p7\n// Equation (2.8)\nMatrix7x6 jacobian_p6_to_p7_wrt_p(const Vector6 &p) {\n    Matrix7x6 m = Matrix7x6::Zero();\n\n    // top left corner is a identity matrix\n    // the bottom left 4x3 and top right 3x3 is zero\n    m.block<3, 3>(0, 0) << 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0;\n\n    double ccc, ccs, csc, scc, ssc, sss, scs, css;\n    double roll = p(5), pitch = p(4), yaw = p(3);\n    ccc = cos(roll / 2) * cos(pitch / 2) * cos(yaw / 2);\n    ccs = cos(roll / 2) * cos(pitch / 2) * sin(yaw / 2);\n    csc = cos(roll / 2) * sin(pitch / 2) * cos(yaw / 2);\n    scs = sin(roll / 2) * cos(pitch / 2) * sin(yaw / 2);\n    css = cos(roll / 2) * sin(pitch / 2) * sin(yaw / 2);\n    scc = sin(roll / 2) * cos(pitch / 2) * cos(yaw / 2);\n    ssc = sin(roll / 2) * sin(pitch / 2) * cos(yaw / 2);\n    sss = sin(roll / 2) * sin(pitch / 2) * sin(yaw / 2);\n\n    // clang-format off\n    m.block<4, 3>(3, 3) <<\n        (ssc - ccs) / 2.0, (scs - csc) / 2.0, (css - scc) / 2.0,\n        -(csc + scs) / 2.0, -(ssc + ccs) / 2.0, (ccc + sss) / 2.0,\n        (scc - css) / 2.0, (ccc - sss) / 2.0, (ccs - ssc) / 2.0,\n        (ccc + sss) / 2.0, -(css + scc) / 2.0, -(csc + scs) / 2.0;\n    // clang-format on\n\n    return m;\n}\n}  // namespace wave\n\nnamespace wave {\nnamespace pose_comp {\n\nVector3 quatToYPR(const Eigen::Quaterniond &q) {\n    Vector3 v;\n    double qr = q.coeffs().w(), qx = q.coeffs().x(), qy = q.coeffs().y(),\n           qz = q.coeffs().z();\n    double delta = qr * qy - qx * qz;  // discriminant of normalized quaternion\n    double roll, pitch, yaw;\n\n    // Check for special cases when abs(delta) =~ 0.5 (Equation (2.10))\n    if (fabs(delta - 0.5) < 1e-6) {\n        yaw = -2 * atan2(qx, qr);\n        pitch = M_PI / 2;\n        roll = 0;\n\n    } else if (fabs(delta + 0.5) < 1e-6) {\n        yaw = 2 * atan2(qx, qr);\n        pitch = -M_PI / 2;\n        roll = 0;\n    } else {\n        yaw = atan2(2 * (qr * qz + qx * qy), (1 - 2 * (qy * qy + qz * qz)));\n        pitch = asin(2 * delta);\n        roll = atan2(2 * (qr * qx + qy * qz), (1 - 2 * (qx * qx + qy * qy)));\n    }\n\n    v(0) = yaw;\n    v(1) = pitch;\n    v(2) = roll;\n\n    return v;\n}\n\nEigen::Quaterniond yprToQuat(const Vector3 &ypr) {\n    Eigen::Quaterniond q;\n    double qr, qx, qy, qz;\n    double half_y = ypr(0) / 2, half_p = ypr(1) / 2, half_r = ypr(2) / 2;\n    double cy = cos(half_y), cp = cos(half_p), cr = cos(half_r),\n           sy = sin(half_y), sp = sin(half_p), sr = sin(half_r);\n\n    qr = cr * cp * cy + sr * sp * sy;\n    qx = sr * cp * cy - cr * sp * sy;\n    qy = cr * sp * cy + sr * cp * sy;\n    qz = cr * cp * sy - sr * sp * cy;\n\n    q.coeffs() << qx, qy, qz, qr;\n\n    return q;\n}\n\nMatrix3x3 yprToRotMatrix(const Vector3 &ypr) {\n    double y = ypr(0), p = ypr(1), r = ypr(2);\n    Matrix3x3 rotMatrix;\n    double cy = cos(y), cp = cos(p), cr = cos(r), sy = sin(y), sp = sin(p),\n           sr = sin(r);\n\n    rotMatrix << cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr,\n      sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr, -sp, cp * sr,\n      cp * cr;\n\n    return rotMatrix;\n}\n\nVector3 rotMatrixToYPR(const Matrix3x3 &p) {\n    Vector3 ypr;\n    double yaw, pitch, roll;\n    double p11 = p(0, 0), p12 = p(0, 1), p13 = p(0, 2), p21 = p(1, 0),\n           p22 = p(1, 1), p23 = p(1, 2), p31 = p(2, 0), p32 = p(2, 1),\n           p33 = p(2, 2);\n\n    pitch = atan2(-p31, sqrt(p11 * p11 + p21 * p21));\n\n    if (fabs(pitch + M_PI * 1.0 / 2) < 1e-6) {\n        yaw = atan2(-p23, -p13);\n        roll = 0;\n    } else if (fabs(pitch - M_PI * 1.0 / 2) < 1e-6) {\n        yaw = atan2(p23, p13);\n        roll = 0;\n    } else {\n        yaw = atan2(p21, p11);\n        roll = atan2(p32, p33);\n    }\n\n    ypr << yaw, pitch, roll;\n\n    // To avoid warnings\n    (void) p12;\n    (void) p22;\n\n    return ypr;\n}\n\nEigen::Quaterniond rotMatrixToQuat(const Matrix3x3 &p) {\n    Eigen::Quaterniond q;\n    Vector3 ypr;\n\n    ypr = rotMatrixToYPR(p);\n    q = yprToQuat(ypr);\n\n    return q;\n}\n}  // namespace pose_comp\n}  // namespace wave", "meta": {"hexsha": "53b29ec1f4f7add1887138ee8aa7df178603f73f", "size": 17822, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wave_utils/src/pose_cov_comp.cpp", "max_stars_repo_name": "wavelab/wavelib", "max_stars_repo_head_hexsha": "7bebff52859c8b77f088e39913223904988c141e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2017-03-12T18:57:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:44:33.000Z", "max_issues_repo_path": "wave_utils/src/pose_cov_comp.cpp", "max_issues_repo_name": "wavelab/wavelib", "max_issues_repo_head_hexsha": "7bebff52859c8b77f088e39913223904988c141e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 210.0, "max_issues_repo_issues_event_min_datetime": "2017-03-13T15:01:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-15T03:19:44.000Z", "max_forks_repo_path": "wave_utils/src/pose_cov_comp.cpp", "max_forks_repo_name": "wavelab/wavelib", "max_forks_repo_head_hexsha": "7bebff52859c8b77f088e39913223904988c141e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2017-08-14T16:54:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T06:44:16.000Z", "avg_line_length": 34.80859375, "max_line_length": 177, "alphanum_fraction": 0.4943889575, "num_tokens": 6389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.28622435070446306}}
{"text": "//\n// Copyright Jesse Manning 2007\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_GELSD_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_GELSD_HPP\n\n#include <algorithm>\n\n#include <boost/numeric/bindings/traits/type.hpp>\n#include <boost/numeric/bindings/traits/traits.hpp>\n#include <boost/numeric/bindings/traits/type_traits.hpp>\n#include <boost/numeric/bindings/lapack/lapack.h>\n#include <boost/numeric/bindings/lapack/workspace.hpp>\n#include <boost/numeric/bindings/traits/detail/array.hpp>\n#include <boost/numeric/bindings/traits/detail/utils.hpp>\n#include <boost/numeric/bindings/lapack/ilaenv.hpp>\n\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n#  include <boost/static_assert.hpp>\n#  include <boost/type_traits.hpp>\n#endif\n\nnamespace boost { namespace numeric { namespace bindings {\n\n    namespace lapack {\n\n        namespace detail {\n\n            inline void gelsd(const integer_t m, const integer_t n, const integer_t nrhs,\n                              float *a, const integer_t lda, float *b, const integer_t ldb,\n                              float *s, const float rcond, integer_t *rank, float *work,\n                              const integer_t lwork, integer_t *iwork, integer_t *info)\n            {\n                LAPACK_SGELSD(&m, &n, &nrhs, a, &lda, b, &ldb, s,\n                              &rcond, rank, work, &lwork, iwork, info);\n            }\n\n            inline void gelsd(const integer_t m, const integer_t n, const integer_t nrhs,\n                              double *a, const integer_t lda, double *b, const integer_t ldb,\n                              double *s, const double rcond, integer_t *rank, double *work,\n                              const integer_t lwork, integer_t *iwork, integer_t *info)\n            {\n                LAPACK_DGELSD(&m, &n, &nrhs, a, &lda, b, &ldb, s,\n                              &rcond, rank, work, &lwork, iwork, info);\n            }\n\n            inline void gelsd(const integer_t m, const integer_t n, const integer_t nrhs,\n                              traits::complex_f *a, const integer_t lda, traits::complex_f *b,\n                              const integer_t ldb, float *s, const float rcond, integer_t *rank,\n                              traits::complex_f *work, const integer_t lwork, float *rwork,\n                              integer_t *iwork, integer_t *info)\n            {\n                LAPACK_CGELSD(&m, &n, &nrhs, traits::complex_ptr(a),\n                              &lda, traits::complex_ptr(b), &ldb, s,\n                              &rcond, rank, traits::complex_ptr(work),\n                              &lwork, rwork, iwork, info);\n            }\n\n            inline void gelsd(const integer_t m, const integer_t n, const integer_t nrhs,\n                              traits::complex_d *a, const integer_t lda, traits::complex_d *b,\n                              const integer_t ldb, double *s, const double rcond, integer_t *rank,\n                              traits::complex_d *work, const integer_t lwork, double *rwork,\n                              integer_t *iwork, integer_t *info)\n            {\n                LAPACK_ZGELSD(&m, &n, &nrhs, traits::complex_ptr(a),\n                              &lda, traits::complex_ptr(b), &ldb, s,\n                              &rcond, rank, traits::complex_ptr(work),\n                              &lwork, rwork, iwork, info);\n            }\n\n            // gelsd for real type\n            template <typename MatrA, typename MatrB, typename VecS, typename Work>\n            int gelsd(MatrA& A, MatrB& B, VecS& s, Work& work)\n            {\n                typedef typename MatrA::value_type val_t;\n                typedef typename traits::type_traits<val_t>::real_type real_t;\n\n                const std::ptrdiff_t m = traits::matrix_size1(A);\n                const std::ptrdiff_t n = traits::matrix_size2(A);\n                const std::ptrdiff_t nrhs = traits::matrix_size2(B);\n                const std::ptrdiff_t maxmn = std::max(m, n);\n                const std::ptrdiff_t minmn = std::min(m, n);\n\n                // sanity checks\n                assert(m >= 0 && n >= 0);\n                assert(nrhs >= 0);\n                assert(traits::leading_dimension(A) >= std::max<std::ptrdiff_t>(1, m));\n                assert(traits::leading_dimension(B) >= std::max<std::ptrdiff_t>(1, maxmn));\n                assert(traits::vector_size(work) >= 1);\n                assert(traits::vector_size(s) >= std::max<std::ptrdiff_t>(1, minmn));\n\n                integer_t info;\n                const real_t rcond = -1;    // use machine precision\n                integer_t rank;\n\n                // query for maximum size of subproblems\n                const integer_t smlsiz = ilaenv(9, \"GELSD\", \"\");\n                const integer_t nlvl = static_cast<integer_t>(((std::log(static_cast<float>(minmn))/std::log(2.f))/ (smlsiz+1)) + 1);\n\n                traits::detail::array<integer_t> iwork(3*minmn*nlvl + 11*minmn);\n\n                detail::gelsd(traits::matrix_size1(A),\n                              traits::matrix_size2(A),\n                              traits::matrix_size2(B),\n                              traits::matrix_storage(A),\n                              traits::leading_dimension(A),\n                              traits::matrix_storage(B),\n                              traits::leading_dimension(B),\n                              traits::vector_storage(s),\n                              rcond,\n                              &rank,\n                              traits::vector_storage(work),\n                              traits::vector_size(work),\n                              traits::vector_storage(iwork),\n                              &info);\n\n                return info;\n            }\n\n            // gelsd for complex type\n            template <typename MatrA, typename MatrB, typename VecS,\n                        typename Work, typename RWork>\n            int gelsd(MatrA& A, MatrB& B, VecS& s, Work& work, RWork& rwork)\n            {\n                typedef typename MatrA::value_type val_t;\n                typedef typename traits::type_traits<val_t>::real_type real_t;\n\n                const std::ptrdiff_t m = traits::matrix_size1(A);\n                const std::ptrdiff_t n = traits::matrix_size2(A);\n                const std::ptrdiff_t nrhs = traits::matrix_size2(B);\n                const std::ptrdiff_t maxmn = std::max(m, n);\n                const std::ptrdiff_t minmn = std::min(m, n);\n\n                // sanity checks\n                assert(m >= 0 && n >= 0);\n                assert(nrhs >= 0);\n                assert(traits::leading_dimension(A) >= std::max<std::ptrdiff_t>(1, m));\n                assert(traits::leading_dimension(B) >= std::max<std::ptrdiff_t>(1, maxmn));\n                assert(traits::vector_size(work) >= 1);\n                assert(traits::vector_size(s) >= std::max<std::ptrdiff_t>(1, minmn));\n\n                integer_t info;\n                const real_t rcond = -1;    // use machine precision\n                integer_t rank;\n\n                // query for maximum size of subproblems\n                const integer_t smlsiz = ilaenv(9, \"GELSD\", \"\");\n                const integer_t nlvl = static_cast<integer_t>(((std::log(static_cast<float>(minmn))/std::log(2.f))/ (smlsiz+1)) + 1);\n\n                traits::detail::array<integer_t> iwork(3*minmn*nlvl + 11*minmn);\n\n                detail::gelsd(traits::matrix_size1(A),\n                    traits::matrix_size2(A),\n                    traits::matrix_size2(B),\n                    traits::matrix_storage(A),\n                    traits::leading_dimension(A),\n                    traits::matrix_storage(B),\n                    traits::leading_dimension(B),\n                    traits::vector_storage(s),\n                    rcond,\n                    &rank,\n                    traits::vector_storage(work),\n                    traits::vector_size(work),\n                    traits::vector_storage(rwork),\n                    traits::vector_storage(iwork),\n                    &info);\n\n                return info;\n            }\n\n            template <int N>\n            struct Gelsd { };\n\n            // specialization for gelsd real flavors (sgelsd, dgelsd)\n            template <>\n            struct Gelsd<1>\n            {\n                template <typename MatrA, typename MatrB, typename VecS>\n                int operator() (MatrA& A, MatrB& B, VecS& s, minimal_workspace) const\n                {\n                    typedef typename MatrA::value_type val_t;\n\n                    const std::ptrdiff_t m = traits::matrix_size1(A);\n                    const std::ptrdiff_t n = traits::matrix_size2(A);\n                    const std::ptrdiff_t nrhs = traits::matrix_size2(B);\n\n                    const std::ptrdiff_t minmn = std::min(m, n);           // minmn = m < n ? m : n\n                    //const std::ptrdiff_t maxmn = std::max(m, n);           // maxmn = m > n ? m : n\n                    //const std::ptrdiff_t maxmnr = std::max(maxmn, nrhs);   // maxmnr = maxmn > nrhs ? maxmn : nrhs\n\n                    // query for maximum size of subproblems\n                    const integer_t smlsiz = ilaenv(9, \"GELSD\", \"\");\n                    const integer_t nlvl = static_cast<integer_t>(((std::log(static_cast<float>(minmn))/std::log(2.f))/ (smlsiz+1)) + 1);\n\n                    const integer_t lwork = 12*minmn + 2*minmn*smlsiz + 8*minmn*nlvl +\n                                      minmn*nrhs + (smlsiz+1)*(smlsiz+1);\n\n                    traits::detail::array<val_t> work(lwork);\n\n                    return gelsd(A, B, s, work);\n                }\n\n                template <typename MatrA, typename MatrB, typename VecS>\n                int operator() (MatrA& A, MatrB& B, VecS& s, optimal_workspace) const\n                {\n                    typedef typename MatrA::value_type val_t;\n                    typedef typename traits::type_traits<val_t>::real_type real_t;\n\n                    //const std::ptrdiff_t m = traits::matrix_size1(A);\n                    //const std::ptrdiff_t n = traits::matrix_size2(A);\n                    //const std::ptrdiff_t nrhs = traits::matrix_size2(B);\n\n                    //const std::ptrdiff_t minmn = std::min(m, n);           // minmn = m < n ? m : n\n                    //const std::ptrdiff_t maxmn = std::max(m, n);           // maxmn = m > n ? m : n\n                    //const std::ptrdiff_t maxmnr = std::max(maxmn, nrhs);   // maxmnr = maxmn > nrhs ? maxmn : nrhs\n\n                    val_t temp_work;\n                    integer_t temp_iwork;\n\n                    const real_t rcond = -1;\n                    integer_t rank;\n                    integer_t info;\n\n                    // query for optimal workspace size\n                    detail::gelsd(traits::matrix_size1(A),\n                                  traits::matrix_size2(A),\n                                  traits::matrix_size2(B),\n                                  traits::matrix_storage(A),\n                                  traits::leading_dimension(A),\n                                  traits::matrix_storage(B),\n                                  traits::leading_dimension(B),\n                                  traits::vector_storage(s),\n                                  rcond,\n                                  &rank,\n                                  &temp_work,   //traits::vector_storage(work),\n                                  -1,           //traits::vector_size(work),\n                                  &temp_iwork,\n                                  &info);\n\n                    assert(info == 0);\n\n                    const integer_t lwork = traits::detail::to_int(temp_work);\n\n                    traits::detail::array<val_t> work(lwork);\n\n                    return gelsd(A, B, s, work);\n                }\n\n                template <typename MatrA, typename MatrB, typename VecS, typename Work>\n                int operator() (MatrA& A, MatrB& B, VecS& s, detail::workspace1<Work> workspace) const\n                {\n                    //const std::ptrdiff_t m = traits::matrix_size1(A);\n                    //const std::ptrdiff_t n = traits::matrix_size2(A);\n                    //const std::ptrdiff_t nrhs = traits::matrix_size2(B);\n\n                    //const std::ptrdiff_t minmn = std::min(m, n);           // minmn = m < n ? m : n\n                    //const std::ptrdiff_t maxmn = std::max(m, n);           // maxmn = m > n ? m : n\n                    //const std::ptrdiff_t maxmnr = std::max(maxmn, nrhs);   // maxmnr = maxmn > nrhs ? maxmn : nrhs\n\n                    typedef typename traits::vector_traits<VecS>::value_type value_type ;\n                    return gelsd(A, B, s, workspace.select(value_type()));\n                }\n            };\n\n            // specialization for gelsd (cgelsd, zgelsd)\n            template <>\n            struct Gelsd<2>\n            {\n                template <typename MatrA, typename MatrB, typename VecS>\n                int operator() (MatrA& A, MatrB& B, VecS& s, minimal_workspace) const\n                {\n                    typedef typename MatrA::value_type val_t;\n                    typedef typename traits::type_traits<val_t>::real_type real_t;\n\n                    const std::ptrdiff_t m = traits::matrix_size1(A);\n                    const std::ptrdiff_t n = traits::matrix_size2(A);\n                    const std::ptrdiff_t nrhs = traits::matrix_size2(B);\n\n                    const std::ptrdiff_t minmn = std::min(m, n);           // minmn = m < n ? m : n\n                    //const std::ptrdiff_t maxmn = std::max(m, n);           // maxmn = m > n ? m : n\n                    //const std::ptrdiff_t maxmnr = std::max(maxmn, nrhs);   // maxmnr = maxmn > nrhs ? maxmn : nrhs\n\n                    // query for maximum size of subproblems\n                    const integer_t smlsiz = ilaenv(9, \"GELSD\", \"\");\n                    const integer_t nlvl = static_cast<integer_t>(((std::log(static_cast<float>(minmn))/std::log(2.f))/ (smlsiz+1)) + 1);\n\n                    traits::detail::array<val_t> work(2*minmn + minmn*nrhs);\n\n                    const std::ptrdiff_t rwork_size = 10*minmn + 2*minmn*smlsiz + 8*minmn*nlvl +\n                                           3*smlsiz*nrhs + (smlsiz+1)*(smlsiz+1);\n\n                    traits::detail::array<real_t> rwork(std::max<std::ptrdiff_t>(1, rwork_size));\n\n                    return gelsd(A, B, s, work, rwork);\n                }\n\n                template <typename MatrA, typename MatrB, typename VecS>\n                int operator() (MatrA& A, MatrB& B, VecS& s, optimal_workspace) const\n                {\n                    typedef typename MatrA::value_type val_t;\n                    typedef typename traits::type_traits<val_t>::real_type real_t;\n\n                    const std::ptrdiff_t m = traits::matrix_size1(A);\n                    const std::ptrdiff_t n = traits::matrix_size2(A);\n                    const std::ptrdiff_t nrhs = traits::matrix_size2(B);\n\n                    const std::ptrdiff_t minmn = std::min(m, n);           // minmn = m < n ? m : n\n                    //const std::ptrdiff_t maxmn = std::max(m, n);           // maxmn = m > n ? m : n\n                    //const std::ptrdiff_t maxmnr = std::max(maxmn, nrhs);   // maxmnr = maxmn > nrhs ? maxmn : nrhs\n\n                    val_t temp_work;\n                    real_t temp_rwork;\n                    integer_t temp_iwork;\n\n                    const real_t rcond = -1;\n                    integer_t rank;\n                    integer_t info;\n\n                    // query for optimal workspace size\n                    detail::gelsd(traits::matrix_size1(A),\n                                  traits::matrix_size2(A),\n                                  traits::matrix_size2(B),\n                                  traits::matrix_storage(A),\n                                  traits::leading_dimension(A),\n                                  traits::matrix_storage(B),\n                                  traits::leading_dimension(B),\n                                  traits::vector_storage(s),\n                                  rcond,\n                                  &rank,\n                                  &temp_work,   //traits::vector_storage(work),\n                                  -1,           //traits::vector_size(work),\n                                  &temp_rwork,\n                                  &temp_iwork,\n                                  &info);\n\n                    assert(info == 0);\n\n                    const integer_t lwork = traits::detail::to_int(temp_work);\n\n                    traits::detail::array<val_t> work(lwork);\n\n                    // query for maximum size of subproblems\n                    const integer_t smlsiz = ilaenv(9, \"GELSD\", \"\");\n                    const integer_t nlvl = static_cast<integer_t>(((std::log(static_cast<float>(minmn))/std::log(2.f))/ (smlsiz+1)) + 1);\n\n                    const std::ptrdiff_t rwork_size = 10*minmn + 2*minmn*smlsiz + 8*minmn*nlvl +\n                                            3*smlsiz*nrhs + (smlsiz+1)*(smlsiz+1);\n\n                    traits::detail::array<real_t> rwork(std::max<std::ptrdiff_t>(1, rwork_size));\n\n                    return gelsd(A, B, s, work, rwork);\n                }\n\n                template <typename MatrA, typename MatrB, typename VecS, typename Work, typename RWork>\n                int operator() (MatrA& A, MatrB& B, VecS& s, detail::workspace2<Work, RWork> workspace) const\n                {\n                    //const std::ptrdiff_t m = traits::matrix_size1(A);\n                    //const std::ptrdiff_t n = traits::matrix_size2(A);\n                    //const std::ptrdiff_t nrhs = traits::matrix_size2(B);\n\n                    //const std::ptrdiff_t minmn = std::min(m, n);           // minmn = m < n ? m : n\n                    //const std::ptrdiff_t maxmn = std::max(m, n);           // maxmn = m > n ? m : n\n                    //const std::ptrdiff_t maxmnr = std::max(maxmn, nrhs);   // maxmnr = maxmn > nrhs ? maxmn : nrhs\n\n                    typedef typename traits::vector_traits<VecS>::value_type    value_type ;\n                    typedef typename traits::type_traits<value_type>::real_type real_type ;\n                    return gelsd(A, B, s, workspace.select(value_type()), workspace.select(real_type()));\n                }\n            };\n\n        } // detail\n\n        // gelsd\n        // Parameters:\n        //  A:          matrix of coefficients\n        //  B:          matrix of solutions (stored column-wise)\n        //  s:          vector to store singular values on output, length >= max(1, min(m,n))\n        //  workspace:  either optimal, minimal, or user supplied\n        //\n        template <typename MatrA, typename MatrB, typename VecS, typename Work>\n        int gelsd(MatrA& A, MatrB& B, VecS& s, Work workspace)\n        {\n            typedef typename MatrA::value_type val_t;\n\n            return detail::Gelsd<n_workspace_args<val_t>::value>() (A, B, s, workspace);\n        }\n\n        // gelsd, no singular values are returned\n        // Parameters:\n        //  A:          matrix of coefficients\n        //  B:          matrix of solutions (stored column-wise)\n        //  workspace:  either optimal, minimal, or user supplied\n        //\n        template <typename MatrA, typename MatrB, typename Work>\n        int gelsd(MatrA& A, MatrB& B, Work workspace)\n        {\n            typedef typename MatrA::value_type val_t;\n            typedef typename traits::type_traits<val_t>::real_type real_t;\n\n            const std::ptrdiff_t m = traits::matrix_size1(A);\n            const std::ptrdiff_t n = traits::matrix_size2(A);\n\n            const std::ptrdiff_t s_size = std::max<std::ptrdiff_t>(1, std::min(m,n));\n            traits::detail::array<real_t> s(s_size);\n\n            return detail::Gelsd<n_workspace_args<val_t>::value>() (A, B, s, workspace);\n        }\n\n    } // lapack\n\n}}}\n\n#endif\n", "meta": {"hexsha": "b469cd0121891e60ca00a036faf3f45828f12f9c", "size": 20050, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/lapack/gelsd.hpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/lapack/gelsd.hpp", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/lapack/gelsd.hpp", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.7380952381, "max_line_length": 137, "alphanum_fraction": 0.4930174564, "num_tokens": 4603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.2861104916132148}}
{"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/*\nMegan E. Marsh, Raymond J. Spiteri\nNumerical Simulation Laboratory\nUniversity of Saskatchewan\nDecember 2011\nPartial support provided by research grants from the National\nScience and Engineering Research Council (NSERC) of Canada\nand the MITACS/Mprime Canadian Network of Centres of Excellence.\n*/\n\n#ifndef _GRL2IVPODESOLVER_HPP_\n#define _GRL2IVPODESOLVER_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n#include \"AbstractOneStepIvpOdeSolver.hpp\"\n\n/**\n * A concrete one step ODE solver class that employs the GRL2 second-order solver.\n * Method is described in J. Sundnes, R. Artebrant, O. Skavhaug, and A. Tveito.\n * A second-order algorithm for solving dynamic cell membrane equations.\n * IEEE Trans. Biomed. Eng., 56(10):2546-2548, 2009.\n */\nclass GRL2IvpOdeSolver : public AbstractOneStepIvpOdeSolver\n{\nprivate:\n\n    /** Needed for serialization. */\n    friend class boost::serialization::access;\n    /**\n     * Archive the abstract IVP Solver, never used directly - boost uses this.\n     *\n     * @param archive the 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        // This calls serialize on the base class.\n        archive & boost::serialization::base_object<AbstractOneStepIvpOdeSolver>(*this);\n    }\n\n    /** Working memory for the solver */\n    std::vector<double> mEvalF;\n\n    /** Working memory for the solver */\n    std::vector<double> mPartialF;\n\n    /** Working memory for the solver */\n    std::vector<double> mTemp;\n\n    /** Working memory for the solver */\n    std::vector<double> mYinit;\n\nprotected:\n\n    /**\n     * Calculate the solution to the ODE system at the next timestep.\n     *\n     * @param pAbstractOdeSystem  the ODE system to solve\n     * @param timeStep  dt\n     * @param time  the current time\n     * @param rCurrentYValues  the current (initial) state\n     * @param rNextYValues  the state at the next timestep\n     */\n    void CalculateNextYValue(AbstractOdeSystem* pAbstractOdeSystem,\n                             double timeStep,\n                             double time,\n                             std::vector<double>& rCurrentYValues,\n                             std::vector<double>& rNextYValues);\n\npublic:\n\n    /**\n     * Constructor.\n     */\n    GRL2IvpOdeSolver()\n    {}\n};\n\n#include \"SerializationExportWrapper.hpp\"\nCHASTE_CLASS_EXPORT(GRL2IvpOdeSolver)\n\n#endif //_GRL2IVPODESOLVER_HPP_\n", "meta": {"hexsha": "e1b55760cd86b491d69076bc49e341f322982524", "size": 4226, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ode/src/solver/GRL2IvpOdeSolver.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": "ode/src/solver/GRL2IvpOdeSolver.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": "ode/src/solver/GRL2IvpOdeSolver.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": 35.2166666667, "max_line_length": 88, "alphanum_fraction": 0.7311878845, "num_tokens": 943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.28605225875726326}}
{"text": "\n#include \"./pybind11/include/pybind11/pybind11.h\"\n#include \"./pybind11/include/pybind11/stl_bind.h\"\n#include \"./pybind11/include/pybind11/numpy.h\"\n\n#include <algorithm>\n#include <dogm/dogm.h>\n#include <dogm/dogm_types.h>\n#include <dogm/mapping/laser_to_meas_grid.h>\n#include <iostream>\n\n#include <Eigen/Dense>\n\nnamespace py = pybind11;\n\nPYBIND11_MAKE_OPAQUE(std::vector<float>);\nPYBIND11_MAKE_OPAQUE(std::vector<dogm::GridCell>);\n\nnamespace dogm {\n\n  // https://stackoverflow.com/questions/48982143/returning-and-passing-around-raw-pod-pointers-arrays-with-python-c-and-pyb\n  template <class T> class ptr_wrapper\n  {\n  public:\n    ptr_wrapper() : ptr(nullptr) {}\n    ptr_wrapper(T* ptr) : ptr(ptr) {}\n    ptr_wrapper(const ptr_wrapper& other) : ptr(other.ptr) {}\n    T& operator* () const { return *ptr; }\n    T* operator->() const { return  ptr; }\n    T* get() const { return ptr; }\n    void destroy() { delete ptr; }\n    T& operator[](std::size_t idx) const { return ptr[idx]; }\n  private:\n    T* ptr;\n  };\n\n  ptr_wrapper<MeasurementCell> wrap_laser_grid( LaserMeasurementGrid& lmg, const std::vector<float>& measurements ) {\n    ptr_wrapper<MeasurementCell> ptr(lmg.generateGrid( measurements ));\n    return ptr;\n  }\n\n  void wrap_dogm_grid( DOGM& grid, ptr_wrapper<MeasurementCell>& ptr, float x, float y, float yaw, float dt, bool device){\n    grid.updateGrid( ptr.get(), x, y, yaw, dt, device );\n  }\n\n  float pignisticTransformation(float free_mass, float occ_mass) {\n    return occ_mass + 0.5f * (1.0f - occ_mass - free_mass);\n  }\n\n  void hsvToRGB(float hue, float saturation, float value, float &r, float &g, float &b) {\n\n    if (saturation == 0.0f) {\n      r = g = b = value;\n    } else {\n      int i = static_cast<int>(hue * 6.0f);\n      float f = (hue * 6.0f) - i;\n      float p = value * (1.0f - saturation);\n      float q = value * (1.0f - saturation * f);\n      float t = value * (1.0f - saturation * (1.0f - f));\n      int res = i % 6;\n\n      switch (res) {\n        case 0:\n          r = value;\n          g = t;\n          b = p;\n          break;\n        case 1:\n          r = q;\n          g = value;\n          b = p;\n          break;\n        case 2:\n          r = p;\n          g = value;\n          b = t;\n          break;\n        case 3:\n          r = p;\n          g = q;\n          b = value;\n          break;\n        case 4:\n          r = t;\n          g = p;\n          b = value;\n          break;\n        case 5:\n          r = value;\n          g = p;\n          b = q;\n          break;\n        default:\n          r = g = b = value;\n      }\n    }\n  }\n\n  py::array_t<float> render_dynamic_occupancy_grid( const DOGM& grid, double occupancy_threshold,\n                                                            double dynamic_threshold, double max_velocity ) {\n    auto width = grid.getGridSize();\n    auto height = grid.getGridSize();\n    auto depth = 3;\n    float *grid_ptr = new float[ depth * width * height ];\n\n    const auto grid_cells = grid.getGridCells();\n    #pragma omp parallel for\n    for( int y = 0; y < height; y++ ) {\n      for( int x = 0; x < width; x++ ) {\n        auto cell = grid_cells[y*width + x];\n        float occ = pignisticTransformation(cell.free_mass, cell.occ_mass);\n\n        Eigen::Vector2f vel;\n        vel << cell.mean_x_vel, cell.mean_y_vel;\n\n        Eigen::Matrix2f covar;\n        covar << cell.var_x_vel, cell.covar_xy_vel, cell.covar_xy_vel, cell.var_y_vel;\n\n        auto mdist = vel.transpose() * covar.inverse() * vel;\n\n        float r, g, b;\n        if (occ >= occupancy_threshold && mdist >= dynamic_threshold ) {\n          float angle = atan2(cell.mean_y_vel, cell.mean_x_vel) + M_PI;\n\n          auto value = std::min(1.0, sqrt(cell.mean_x_vel * cell.mean_x_vel +\n                                          cell.mean_y_vel * cell.mean_y_vel) / max_velocity );\n\n          hsvToRGB(angle / M_PI, 1.0f, value, r, g, b);\n        } else {\n          r = g = b = 1.0f - occ;\n        }\n        grid_ptr[ depth * ( y*width + x ) ] = r;\n        grid_ptr[ depth * ( y*width + x ) + 1 ] = g;\n        grid_ptr[ depth * ( y*width + x ) + 2 ] = b;\n      }\n    }\n\n    // Create a Python object that will free the allocated\n    // memory when destroyed:\n    py::capsule delete_fn(grid_ptr, [](void *p) {\n      float *ptr = reinterpret_cast<float *>(p);\n      delete[] ptr;\n    });\n\n    return py::array_t<float>(\n            {height, width, depth}, // shape\n            {depth*width*sizeof(float), depth*sizeof(float), sizeof(float)}, // C-style contiguous strides\n            grid_ptr, // the data pointer\n            delete_fn); // numpy array references this parent\n  }\n\n\n  py::array_t<float> render_occupancy_grid( const DOGM& grid ) {\n    auto width = grid.getGridSize();\n    auto height = grid.getGridSize();\n    float *grid_ptr = new float[ width * height ];\n\n    const auto grid_cells = grid.getGridCells();\n  #pragma omp parallel for\n    for( int y = 0; y < height; y++ ) {\n      for( int x = 0; x < width; x++ ) {\n        auto cell = grid_cells[y*width + x];\n        float prob = pignisticTransformation( cell.free_mass, cell.occ_mass );\n        grid_ptr[ y*width + x ] = 1.0f - prob;\n      }\n    }\n\n    // Create a Python object that will free the allocated\n    // memory when destroyed:\n    py::capsule delete_fn(grid_ptr, [](void *p) {\n      float *ptr = reinterpret_cast<float *>(p);\n      delete[] ptr;\n    });\n\n    return py::array_t<float>(\n            {height, width}, // shape\n            {width*sizeof(float), sizeof(float)}, // C-style contiguous strides\n            grid_ptr, // the data pointer\n            delete_fn); // numpy array references this parent\n  }\n\n\n  PYBIND11_MODULE(dogm_py, m) {\n    // bind a vector of floats to pass into the laser measurement grid\n    py::bind_vector<std::vector<float>>(m, \"VectorFloat\", py::buffer_protocol());\n\n    m.doc() = \"Python bindings for the Dynamic Occupancy Grid Map Library\";\n\n    py::class_<ptr_wrapper<MeasurementCell>>(m, \"MeasurementCellPtr\")\n      .def(py::init<>(), \"Wrapper for CUDA pointer returned by LaserMeasurementGrid\" );\n\n    m.def( \"generateMeasurements\", &wrap_laser_grid, py::arg( \"laser_measurement_grid\"),\n           py::arg(\"measurements\") );\n\n    m.def( \"updateGrid\", &wrap_dogm_grid, \"Wrapper function for grid update\",\n           py::arg(\"grid\"), py::arg(\"measurement_ptr\"), py::arg(\"x\"),\n           py::arg(\"y\"), py::arg(\"yaw\"),\n           py::arg(\"dt\"), py::arg(\"device\"));\n\n    py::class_<LaserMeasurementGrid::Params>(m, \"LaserMeasurementGridParams\")\n            .def(py::init<float, float, float, float>(),\n                 R\"lmgPARAM(\n    struct Params {\n      float max_range;\n      float resolution;\n      float fov;\n      float angle_increment;\n    };\n                        )lmgPARAM\", py::arg(\"max_range\"), py::arg(\"resolution\"),\n                        py::arg(\"fov\"), py::arg(\"angle_increment\"))\n            .def_readwrite(\"max_range\", &LaserMeasurementGrid::Params::max_range)\n            .def_readwrite(\"resolution\", &LaserMeasurementGrid::Params::resolution)\n            .def_readwrite(\"fov\", &LaserMeasurementGrid::Params::fov)\n            .def_readwrite(\"angle_increment\", &LaserMeasurementGrid::Params::angle_increment)\n            ;\n\n    py::class_<LaserMeasurementGrid>(m, \"LaserMeasurementGrid\")\n            .def(py::init<const LaserMeasurementGrid::Params&, float, float>(),\n                 py::arg(\"params\"), py::arg(\"size\"), py::arg(\"resolution\"))\n            .def(\"generateGrid\", &LaserMeasurementGrid::generateGrid, \"Create a grid representation of supplied laser measurements\",\n                 py::arg(\"measurements\"));\n\n    py::class_<DOGM::Params>(m, \"DOGMParams\")\n            .def(py::init<float, float, int, int, float, float, float, float, float, float>(),\n                    R\"DogmPARAM(\n    struct Params {\n      float size;                          // Grid size [m]\n      float resolution;                    // Grid cell size [m/cell]\n      int particle_count;                  // Number of persistent particles\n      int new_born_particle_count;         // Number of birth particles\n      float persistence_prob;              // Probability of persistence\n      float stddev_process_noise_position; // Process noise position\n      float stddev_process_noise_velocity; // Process noise velocity\n      float birth_prob;                    // Probability of birth\n      float stddev_velocity;               // Velocity to sample birth particles from (normal distribution) [m/s]\n      float init_max_velocity;             // Velocity to sample the initial particles from (uniform distribution) [m/s]\n    }\n                        )DogmPARAM\", py::arg(\"size\"),py::arg(\"resolution\"),py::arg(\"particle_count\"),\n                   py::arg(\"new_born_particle_count\"),py::arg(\"persistance_prob\"),py::arg(\"stddev_process_noise_position\"),\n                   py::arg(\"stddev_process_noise_velocity\"), py::arg(\"birth_prob\"), py::arg(\"stddev_velocity\"),\n                   py::arg(\"init_max_velocity\"));\n\n    // define a vector of GridCells for return types\n    py::class_<GridCell>(m, \"GridCell\")\n            .def(py::init<>())\n            .def_readwrite(\"occ_mass\", &GridCell::occ_mass)\n            .def_readwrite(\"free_mass\", &GridCell::free_mass);\n\n    py::bind_vector<std::vector<GridCell>>(m, \"VectorGridCell\");\n\n    py::class_<DOGM>(m, \"DOGM\")\n            .def(py::init<const DOGM::Params&>(), py::arg(\"params\") )\n            .def(\"updateGrid\", &DOGM::updateGrid, \"Update the current state with constructed measurement grid\",\n                 py::arg(\"cellData\"), py::arg(\"x\"), py::arg(\"y\"), py::arg(\"yaw\"), py::arg(\"dt\"), py::arg(\"device\"))\n            .def(\"getGridCells\", &DOGM::getGridCells)\n            .def(\"getMeasurementCells\", &DOGM::getMeasurementCells)\n            .def(\"getParticles\", &DOGM::getParticles)\n            .def(\"getGridSize\", &DOGM::getGridSize)\n            .def(\"getResolution\", &DOGM::getResolution)\n            .def(\"getPositionX\", &DOGM::getPositionX)\n            .def(\"getPositionY\", &DOGM::getPositionY)\n            .def(\"getYaw\", &DOGM::getYaw)\n            .def(\"getIteration\", &DOGM::getIteration);\n\n    m.def( \"renderOccupancyGrid\", &render_occupancy_grid, \"Convert the occupancy grid into a numpy array\",\n           py::arg(\"grid\"));\n\n    m.def( \"renderDynamicOccupancyGrid\", &render_dynamic_occupancy_grid, \"Convert the occupancy grid into a RGB numpy array encoding of dynamic elements\",\n           py::arg(\"grid\"), py::arg(\"occupancy_threshold\"), py::arg(\"dynamic_threshold\"), py::arg(\"max_velocity\"));\n\n  }\n\n\n}\n\n\n", "meta": {"hexsha": "c44a43640030bb260733819701ac916babbdbd8c", "size": 10517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dogm_py.cpp", "max_stars_repo_name": "idlebear/dogm_cuda", "max_stars_repo_head_hexsha": "f286eb6608e89be7d5d01bcd15570154db634896", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dogm_py.cpp", "max_issues_repo_name": "idlebear/dogm_cuda", "max_issues_repo_head_hexsha": "f286eb6608e89be7d5d01bcd15570154db634896", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dogm_py.cpp", "max_forks_repo_name": "idlebear/dogm_cuda", "max_forks_repo_head_hexsha": "f286eb6608e89be7d5d01bcd15570154db634896", "max_forks_repo_licenses": ["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.9675090253, "max_line_length": 154, "alphanum_fraction": 0.58524294, "num_tokens": 2695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573377, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.2860375520122532}}
{"text": "// Copyright 2020 Tier IV, 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// Author: v1.0 Yukihiro Saito\n//\n\n#include \"multi_object_tracker/tracker/model/pedestrian_tracker.hpp\"\n\n#include \"multi_object_tracker/utils/utils.hpp\"\n\n#include <autoware_utils/autoware_utils.hpp>\n\n#include <bits/stdc++.h>\n#include <tf2/LinearMath/Matrix3x3.h>\n#include <tf2/LinearMath/Quaternion.h>\n#include <tf2/utils.h>\n#include <tf2_geometry_msgs/tf2_geometry_msgs.h>\n\n#define EIGEN_MPL2_ONLY\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nPedestrianTracker::PedestrianTracker(\n  const rclcpp::Time & time, const autoware_auto_perception_msgs::msg::DetectedObject & object)\n: Tracker(time, object.classification),\n  logger_(rclcpp::get_logger(\"PedestrianTracker\")),\n  last_update_time_(time),\n  z_(object.kinematics.pose_with_covariance.pose.position.z)\n{\n  object_ = object;\n\n  // initialize params\n  ekf_params_.use_measurement_covariance = false;\n  float q_stddev_x = 0.0;                               // [m/s]\n  float q_stddev_y = 0.0;                               // [m/s]\n  float q_stddev_yaw = autoware_utils::deg2rad(20);     // [rad/s]\n  float q_stddev_vx = autoware_utils::kmph2mps(5);      // [m/(s*s)]\n  float q_stddev_wz = autoware_utils::deg2rad(20);      // [rad/(s*s)]\n  float r_stddev_x = 0.4;                               // [m]\n  float r_stddev_y = 0.4;                               // [m]\n  float r_stddev_yaw = autoware_utils::deg2rad(30);     // [rad]\n  float p0_stddev_x = 1.0;                              // [m/s]\n  float p0_stddev_y = 1.0;                              // [m/s]\n  float p0_stddev_yaw = autoware_utils::deg2rad(1000);  // [rad/s]\n  float p0_stddev_vx = autoware_utils::kmph2mps(5);     // [m/(s*s)]\n  float p0_stddev_wz = autoware_utils::deg2rad(10);     // [rad/(s*s)]\n  ekf_params_.q_cov_x = std::pow(q_stddev_x, 2.0);\n  ekf_params_.q_cov_y = std::pow(q_stddev_y, 2.0);\n  ekf_params_.q_cov_yaw = std::pow(q_stddev_yaw, 2.0);\n  ekf_params_.q_cov_vx = std::pow(q_stddev_vx, 2.0);\n  ekf_params_.q_cov_wz = std::pow(q_stddev_wz, 2.0);\n  ekf_params_.r_cov_x = std::pow(r_stddev_x, 2.0);\n  ekf_params_.r_cov_y = std::pow(r_stddev_y, 2.0);\n  ekf_params_.r_cov_yaw = std::pow(r_stddev_yaw, 2.0);\n  ekf_params_.p0_cov_x = std::pow(p0_stddev_x, 2.0);\n  ekf_params_.p0_cov_y = std::pow(p0_stddev_y, 2.0);\n  ekf_params_.p0_cov_yaw = std::pow(p0_stddev_yaw, 2.0);\n  ekf_params_.p0_cov_vx = std::pow(p0_stddev_vx, 2.0);\n  ekf_params_.p0_cov_wz = std::pow(p0_stddev_wz, 2.0);\n  max_vx_ = autoware_utils::kmph2mps(10);  // [m/s]\n  max_wz_ = autoware_utils::deg2rad(30);   // [rad/s]\n\n  // initialize X matrix\n  Eigen::MatrixXd X(ekf_params_.dim_x, 1);\n  X(IDX::X) = object.kinematics.pose_with_covariance.pose.position.x;\n  X(IDX::Y) = object.kinematics.pose_with_covariance.pose.position.y;\n  X(IDX::YAW) = tf2::getYaw(object.kinematics.pose_with_covariance.pose.orientation);\n  if (object.kinematics.has_twist) {\n    X(IDX::VX) = object.kinematics.twist_with_covariance.twist.linear.x;\n    X(IDX::WZ) = object.kinematics.twist_with_covariance.twist.angular.z;\n  } else {\n    X(IDX::VX) = 0.0;\n    X(IDX::WZ) = 0.0;\n  }\n\n  // initialize P matrix\n  Eigen::MatrixXd P = Eigen::MatrixXd::Zero(ekf_params_.dim_x, ekf_params_.dim_x);\n  if (\n    !ekf_params_.use_measurement_covariance ||\n    object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::X_X] == 0.0 ||\n    object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::Y_Y] == 0.0 ||\n    object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::YAW_YAW] == 0.0) {\n    const double cos_yaw = std::cos(X(IDX::YAW));\n    const double sin_yaw = std::sin(X(IDX::YAW));\n    const double sin_2yaw = std::sin(2.0f * X(IDX::YAW));\n    // Rotate the covariance matrix according to the vehicle yaw\n    // because p0_cov_x and y are in the vehicle coordinate system.\n    P(IDX::X, IDX::X) =\n      ekf_params_.p0_cov_x * cos_yaw * cos_yaw + ekf_params_.p0_cov_y * sin_yaw * sin_yaw;\n    P(IDX::X, IDX::Y) = 0.5f * (ekf_params_.p0_cov_x - ekf_params_.p0_cov_y) * sin_2yaw;\n    P(IDX::Y, IDX::Y) =\n      ekf_params_.p0_cov_x * sin_yaw * sin_yaw + ekf_params_.p0_cov_y * cos_yaw * cos_yaw;\n    P(IDX::Y, IDX::X) = P(IDX::X, IDX::Y);\n    P(IDX::YAW, IDX::YAW) = ekf_params_.p0_cov_yaw;\n    P(IDX::VX, IDX::VX) = ekf_params_.p0_cov_vx;\n    P(IDX::WZ, IDX::WZ) = ekf_params_.p0_cov_wz;\n  } else {\n    P(IDX::X, IDX::X) = object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::X_X];\n    P(IDX::X, IDX::Y) = object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::X_Y];\n    P(IDX::Y, IDX::Y) = object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::Y_Y];\n    P(IDX::Y, IDX::X) = object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::Y_X];\n    P(IDX::YAW, IDX::YAW) =\n      object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::YAW_YAW];\n    if (object.kinematics.has_twist_covariance) {\n      P(IDX::VX, IDX::VX) =\n        object.kinematics.twist_with_covariance.covariance[utils::MSG_COV_IDX::X_X];\n      P(IDX::WZ, IDX::WZ) =\n        object.kinematics.twist_with_covariance.covariance[utils::MSG_COV_IDX::YAW_YAW];\n    } else {\n      P(IDX::VX, IDX::VX) = ekf_params_.p0_cov_vx;\n      P(IDX::WZ, IDX::WZ) = ekf_params_.p0_cov_wz;\n    }\n  }\n\n  bounding_box_ = {0.5, 0.5, 1.7};\n  cylinder_ = {0.3, 1.7};\n  if (object.shape.type == autoware_auto_perception_msgs::msg::Shape::BOUNDING_BOX) {\n    bounding_box_ = {\n      object.shape.dimensions.x, object.shape.dimensions.y, object.shape.dimensions.z};\n  } else if (object.shape.type == autoware_auto_perception_msgs::msg::Shape::CYLINDER) {\n    cylinder_ = {object.shape.dimensions.x, object.shape.dimensions.z};\n  }\n\n  ekf_.init(X, P);\n}\n\nbool PedestrianTracker::predict(const rclcpp::Time & time)\n{\n  const double dt = (time - last_update_time_).seconds();\n  bool ret = predict(dt, ekf_);\n  if (ret) {\n    last_update_time_ = time;\n  }\n  return ret;\n}\n\nbool PedestrianTracker::predict(const double dt, KalmanFilter & ekf) const\n{\n  /*  == Nonlinear model ==\n   *\n   * x_{k+1}   = x_k + vx_k * cos(yaw_k) * dt\n   * y_{k+1}   = y_k + vx_k * sin(yaw_k) * dt\n   * yaw_{k+1} = yaw_k + (wz_k) * dt\n   * vx_{k+1}  = vx_k\n   * wz_{k+1}  = wz_k\n   *\n   */\n\n  /*  == Linearized model ==\n   *\n   * A = [ 1, 0, -vx*sin(yaw)*dt, cos(yaw)*dt,  0]\n   *     [ 0, 1,  vx*cos(yaw)*dt, sin(yaw)*dt,  0]\n   *     [ 0, 0,               1,           0, dt]\n   *     [ 0, 0,               0,           1,  0]\n   *     [ 0, 0,               0,           0,  1]\n   */\n\n  // X t\n  Eigen::MatrixXd X_t(ekf_params_.dim_x, 1);  // predicted state\n  ekf.getX(X_t);\n  const double cos_yaw = std::cos(X_t(IDX::YAW));\n  const double sin_yaw = std::sin(X_t(IDX::YAW));\n  const double sin_2yaw = std::sin(2.0f * X_t(IDX::YAW));\n\n  // X t+1\n  Eigen::MatrixXd X_next_t(ekf_params_.dim_x, 1);                // predicted state\n  X_next_t(IDX::X) = X_t(IDX::X) + X_t(IDX::VX) * cos_yaw * dt;  // dx = v * cos(yaw)\n  X_next_t(IDX::Y) = X_t(IDX::Y) + X_t(IDX::VX) * sin_yaw * dt;  // dy = v * sin(yaw)\n  X_next_t(IDX::YAW) = X_t(IDX::YAW) + (X_t(IDX::WZ)) * dt;      // dyaw = omega\n  X_next_t(IDX::VX) = X_t(IDX::VX);\n  X_next_t(IDX::WZ) = X_t(IDX::WZ);\n\n  // A\n  Eigen::MatrixXd A = Eigen::MatrixXd::Identity(ekf_params_.dim_x, ekf_params_.dim_x);\n  A(IDX::X, IDX::YAW) = -X_t(IDX::VX) * sin_yaw * dt;\n  A(IDX::X, IDX::VX) = cos_yaw * dt;\n  A(IDX::Y, IDX::YAW) = X_t(IDX::VX) * cos_yaw * dt;\n  A(IDX::Y, IDX::VX) = sin_yaw * dt;\n  A(IDX::YAW, IDX::WZ) = dt;\n\n  // Q\n  Eigen::MatrixXd Q = Eigen::MatrixXd::Zero(ekf_params_.dim_x, ekf_params_.dim_x);\n  // Rotate the covariance matrix according to the vehicle yaw\n  // because q_cov_x and y are in the vehicle coordinate system.\n  Q(IDX::X, IDX::X) =\n    (ekf_params_.q_cov_x * cos_yaw * cos_yaw + ekf_params_.q_cov_y * sin_yaw * sin_yaw) * dt * dt;\n  Q(IDX::X, IDX::Y) = (0.5f * (ekf_params_.q_cov_x - ekf_params_.q_cov_y) * sin_2yaw) * dt * dt;\n  Q(IDX::Y, IDX::Y) =\n    (ekf_params_.q_cov_x * sin_yaw * sin_yaw + ekf_params_.q_cov_y * cos_yaw * cos_yaw) * dt * dt;\n  Q(IDX::Y, IDX::X) = Q(IDX::X, IDX::Y);\n  Q(IDX::YAW, IDX::YAW) = ekf_params_.q_cov_yaw * dt * dt;\n  Q(IDX::VX, IDX::VX) = ekf_params_.q_cov_vx * dt * dt;\n  Q(IDX::WZ, IDX::WZ) = ekf_params_.q_cov_wz * dt * dt;\n  Eigen::MatrixXd B = Eigen::MatrixXd::Zero(ekf_params_.dim_x, ekf_params_.dim_x);\n  Eigen::MatrixXd u = Eigen::MatrixXd::Zero(ekf_params_.dim_x, 1);\n\n  if (!ekf.predict(X_next_t, A, Q)) {\n    RCLCPP_WARN(logger_, \"Cannot predict\");\n  }\n\n  return true;\n}\n\nbool PedestrianTracker::measureWithPose(\n  const autoware_auto_perception_msgs::msg::DetectedObject & object)\n{\n  constexpr int dim_y = 2;  // pos x, pos y depending on Pose output\n  // double measurement_yaw =\n  //   autoware_utils::normalizeRadian(tf2::getYaw(object.state.pose_covariance.pose.orientation));\n  // {\n  //   Eigen::MatrixXd X_t(ekf_params_.dim_x, 1);\n  //   ekf_.getX(X_t);\n  //   while (M_PI_2 <= X_t(IDX::YAW) - measurement_yaw) {\n  //     measurement_yaw = measurement_yaw + M_PI;\n  //   }\n  //   while (M_PI_2 <= measurement_yaw - X_t(IDX::YAW)) {\n  //     measurement_yaw = measurement_yaw - M_PI;\n  //   }\n  //   float theta = std::acos(\n  //     std::cos(X_t(IDX::YAW)) * std::cos(measurement_yaw) +\n  //     std::sin(X_t(IDX::YAW)) * std::sin(measurement_yaw));\n  //   if (autoware_utils::deg2rad(60) < std::fabs(theta)) return false;\n  // }\n\n  /* Set measurement matrix */\n  Eigen::MatrixXd Y(dim_y, 1);\n  Y << object.kinematics.pose_with_covariance.pose.position.x,\n    object.kinematics.pose_with_covariance.pose.position.y;\n\n  /* Set measurement matrix */\n  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(dim_y, ekf_params_.dim_x);\n  C(0, IDX::X) = 1.0;  // for pos x\n  C(1, IDX::Y) = 1.0;  // for pos y\n  // C(2, IDX::YAW) = 1.0;  // for yaw\n\n  /* Set measurement noise covariance */\n  Eigen::MatrixXd R = Eigen::MatrixXd::Zero(dim_y, dim_y);\n  if (\n    !ekf_params_.use_measurement_covariance ||\n    object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::X_X] == 0.0 ||\n    object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::Y_Y] == 0.0) {\n    R(0, 0) = ekf_params_.r_cov_x;  // x - x\n    R(0, 1) = 0.0;                  // x - y\n    R(1, 1) = ekf_params_.r_cov_y;  // y - y\n    R(1, 0) = R(0, 1);              // y - x\n    // R(2, 2) = ekf_params_.r_cov_yaw;                        // yaw - yaw\n  } else {\n    R(0, 0) = object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::X_X];\n    R(0, 1) = object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::X_Y];\n    // R(0, 2) = object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::X_YAW];\n    R(1, 0) = object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::Y_X];\n    R(1, 1) = object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::Y_Y];\n    // R(1, 2) = object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::Y_YAW];\n    // R(2, 0) = object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::YAW_X];\n    // R(2, 1) = object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::YAW_Y];\n    // R(2, 2) = object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::YAW_YAW];\n  }\n  if (!ekf_.update(Y, C, R)) {\n    RCLCPP_WARN(logger_, \"Cannot update\");\n  }\n\n  // normalize yaw and limit vx, wz\n  {\n    Eigen::MatrixXd X_t(ekf_params_.dim_x, 1);\n    Eigen::MatrixXd P_t(ekf_params_.dim_x, ekf_params_.dim_x);\n    ekf_.getX(X_t);\n    ekf_.getP(P_t);\n    X_t(IDX::YAW) = autoware_utils::normalizeRadian(X_t(IDX::YAW));\n    if (!(-max_vx_ <= X_t(IDX::VX) && X_t(IDX::VX) <= max_vx_)) {\n      X_t(IDX::VX) = X_t(IDX::VX) < 0 ? -max_vx_ : max_vx_;\n    }\n    if (!(-max_wz_ <= X_t(IDX::WZ) && X_t(IDX::WZ) <= max_wz_)) {\n      X_t(IDX::WZ) = X_t(IDX::WZ) < 0 ? -max_wz_ : max_wz_;\n    }\n    ekf_.init(X_t, P_t);\n  }\n\n  // position z\n  constexpr float gain = 0.9;\n  z_ = gain * z_ + (1.0 - gain) * object.kinematics.pose_with_covariance.pose.position.z;\n\n  return true;\n}\n\nbool PedestrianTracker::measureWithShape(\n  const autoware_auto_perception_msgs::msg::DetectedObject & object)\n{\n  constexpr float gain = 0.9;\n  if (object.shape.type == autoware_auto_perception_msgs::msg::Shape::BOUNDING_BOX) {\n    bounding_box_.width = gain * bounding_box_.width + (1.0 - gain) * object.shape.dimensions.x;\n    bounding_box_.length = gain * bounding_box_.length + (1.0 - gain) * object.shape.dimensions.y;\n    bounding_box_.height = gain * bounding_box_.height + (1.0 - gain) * object.shape.dimensions.z;\n  } else if (object.shape.type == autoware_auto_perception_msgs::msg::Shape::CYLINDER) {\n    cylinder_.width = gain * cylinder_.width + (1.0 - gain) * object.shape.dimensions.x;\n    cylinder_.height = gain * cylinder_.height + (1.0 - gain) * object.shape.dimensions.z;\n  } else {\n    return false;\n  }\n\n  return true;\n}\n\nbool PedestrianTracker::measure(\n  const autoware_auto_perception_msgs::msg::DetectedObject & object, const rclcpp::Time & time)\n{\n  object_ = object;\n\n  if (0.01 /*10msec*/ < std::fabs((time - last_update_time_).seconds())) {\n    RCLCPP_WARN(\n      logger_, \"There is a large gap between predicted time and measurement time. (%f)\",\n      (time - last_update_time_).seconds());\n  }\n\n  measureWithPose(object);\n  measureWithShape(object);\n\n  return true;\n}\n\nbool PedestrianTracker::getTrackedObject(\n  const rclcpp::Time & time, autoware_auto_perception_msgs::msg::TrackedObject & object) const\n{\n  object = utils::toTrackedObject(object_);\n  object.object_id = getUUID();\n  object.classification = getClassification();\n\n  // predict kinematics\n  KalmanFilter tmp_ekf_for_no_update = ekf_;\n  const double dt = (time - last_update_time_).seconds();\n  if (0.001 /*1msec*/ < dt) {\n    predict(dt, tmp_ekf_for_no_update);\n  }\n  Eigen::MatrixXd X_t(ekf_params_.dim_x, 1);                // predicted state\n  Eigen::MatrixXd P(ekf_params_.dim_x, ekf_params_.dim_x);  // predicted state\n  tmp_ekf_for_no_update.getX(X_t);\n  tmp_ekf_for_no_update.getP(P);\n\n  // position\n  object.kinematics.pose_with_covariance.pose.position.x = X_t(IDX::X);\n  object.kinematics.pose_with_covariance.pose.position.y = X_t(IDX::Y);\n  object.kinematics.pose_with_covariance.pose.position.z = z_;\n  // quaternion\n  {\n    double roll, pitch, yaw;\n    tf2::Quaternion original_quaternion;\n    tf2::fromMsg(object_.kinematics.pose_with_covariance.pose.orientation, original_quaternion);\n    tf2::Matrix3x3(original_quaternion).getRPY(roll, pitch, yaw);\n    tf2::Quaternion filtered_quaternion;\n    filtered_quaternion.setRPY(roll, pitch, X_t(IDX::YAW));\n    object.kinematics.pose_with_covariance.pose.orientation.x = filtered_quaternion.x();\n    object.kinematics.pose_with_covariance.pose.orientation.y = filtered_quaternion.y();\n    object.kinematics.pose_with_covariance.pose.orientation.z = filtered_quaternion.z();\n    object.kinematics.pose_with_covariance.pose.orientation.w = filtered_quaternion.w();\n    object.kinematics.orientation_availability =\n      autoware_auto_perception_msgs::msg::TrackedObjectKinematics::SIGN_UNKNOWN;\n  }\n  // position covariance\n  constexpr double z_cov = 0.1 * 0.1;  // TODO(yukkysaito) Currently tentative\n  constexpr double r_cov = 0.1 * 0.1;  // TODO(yukkysaito) Currently tentative\n  constexpr double p_cov = 0.1 * 0.1;  // TOTODO(yukkysaito)DO Currently tentative\n  object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::X_X] = P(IDX::X, IDX::X);\n  object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::X_Y] = P(IDX::X, IDX::Y);\n  object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::Y_X] = P(IDX::Y, IDX::X);\n  object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::Y_Y] = P(IDX::Y, IDX::Y);\n  object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::Z_Z] = z_cov;\n  object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::ROLL_ROLL] = r_cov;\n  object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::PITCH_PITCH] = p_cov;\n  object.kinematics.pose_with_covariance.covariance[utils::MSG_COV_IDX::YAW_YAW] =\n    P(IDX::YAW, IDX::YAW);\n\n  // twist\n  object.kinematics.twist_with_covariance.twist.linear.x = X_t(IDX::VX);\n  object.kinematics.twist_with_covariance.twist.angular.z = X_t(IDX::WZ);\n  // twist covariance\n  constexpr double vy_cov = 0.1 * 0.1;  // TODO(yukkysaito) Currently tentative\n  constexpr double vz_cov = 0.1 * 0.1;  // TODO(yukkysaito) Currently tentative\n  constexpr double wx_cov = 0.1 * 0.1;  // TODO(yukkysaito) Currently tentative\n  constexpr double wy_cov = 0.1 * 0.1;  // TODO(yukkysaito) Currently tentative\n  object.kinematics.twist_with_covariance.covariance[utils::MSG_COV_IDX::X_X] = P(IDX::VX, IDX::VX);\n  object.kinematics.twist_with_covariance.covariance[utils::MSG_COV_IDX::Y_Y] = vy_cov;\n  object.kinematics.twist_with_covariance.covariance[utils::MSG_COV_IDX::Z_Z] = vz_cov;\n  object.kinematics.twist_with_covariance.covariance[utils::MSG_COV_IDX::X_YAW] =\n    P(IDX::VX, IDX::WZ);\n  object.kinematics.twist_with_covariance.covariance[utils::MSG_COV_IDX::YAW_X] =\n    P(IDX::WZ, IDX::VX);\n  object.kinematics.twist_with_covariance.covariance[utils::MSG_COV_IDX::ROLL_ROLL] = wx_cov;\n  object.kinematics.twist_with_covariance.covariance[utils::MSG_COV_IDX::PITCH_PITCH] = wy_cov;\n  object.kinematics.twist_with_covariance.covariance[utils::MSG_COV_IDX::YAW_YAW] =\n    P(IDX::WZ, IDX::WZ);\n\n  // set shape\n  if (object.shape.type == autoware_auto_perception_msgs::msg::Shape::BOUNDING_BOX) {\n    object.shape.dimensions.x = bounding_box_.width;\n    object.shape.dimensions.y = bounding_box_.length;\n    object.shape.dimensions.z = bounding_box_.height;\n  } else if (object.shape.type == autoware_auto_perception_msgs::msg::Shape::CYLINDER) {\n    object.shape.dimensions.x = cylinder_.width;\n    object.shape.dimensions.y = cylinder_.width;\n    object.shape.dimensions.z = cylinder_.height;\n  }\n\n  return true;\n}\n", "meta": {"hexsha": "f69ac9426e9740315ab38d96e6a2092abf4045c5", "size": 18481, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "perception/object_recognition/tracking/multi_object_tracker/src/tracker/model/pedestrian_tracker.cpp", "max_stars_repo_name": "taikitanaka3/AutowareArchitectureProposal.iv", "max_stars_repo_head_hexsha": "0d47ea532118c98458516a8c83fbdab3d27c6231", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2020-09-25T08:52:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-05T02:39:31.000Z", "max_issues_repo_path": "perception/object_recognition/tracking/multi_object_tracker/src/tracker/model/pedestrian_tracker.cpp", "max_issues_repo_name": "taikitanaka3/AutowareArchitectureProposal.iv", "max_issues_repo_head_hexsha": "0d47ea532118c98458516a8c83fbdab3d27c6231", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2021-12-13T04:28:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T13:53:15.000Z", "max_forks_repo_path": "perception/object_recognition/tracking/multi_object_tracker/src/tracker/model/pedestrian_tracker.cpp", "max_forks_repo_name": "taikitanaka3/AutowareArchitectureProposal.iv", "max_forks_repo_head_hexsha": "0d47ea532118c98458516a8c83fbdab3d27c6231", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2020-09-27T05:27:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-08T03:14:25.000Z", "avg_line_length": 44.4254807692, "max_line_length": 100, "alphanum_fraction": 0.6778312862, "num_tokens": 6174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.2860348415788107}}
{"text": "#ifndef STAN_MATH_GPU_MULTIPLY_HPP\n#define STAN_MATH_GPU_MULTIPLY_HPP\n#ifdef STAN_OPENCL\n#include <stan/math/gpu/matrix_gpu.hpp>\n#include <stan/math/gpu/kernels/scalar_mul.hpp>\n#include <stan/math/gpu/kernels/matrix_multiply.hpp>\n#include <Eigen/Dense>\n\nnamespace stan {\nnamespace math {\n/**\n * Multiplies the specified matrix on the GPU\n * with the specified scalar.\n *\n * @param A matrix\n * @param scalar scalar\n * @return matrix multipled with scalar\n */\ninline matrix_gpu multiply(const matrix_gpu& A, const double scalar) {\n  matrix_gpu temp(A.rows(), A.cols());\n  if (A.size() == 0)\n    return temp;\n  try {\n    opencl_kernels::scalar_mul(cl::NDRange(A.rows(), A.cols()), temp.buffer(),\n                               A.buffer(), scalar, A.rows(), A.cols());\n  } catch (const cl::Error& e) {\n    check_opencl_error(\"multiply scalar\", e);\n  }\n  return temp;\n}\n\n/**\n * Multiplies the specified matrix on the GPU\n * with the specified scalar.\n *\n * @param scalar scalar\n * @param A matrix\n * @return matrix multipled with scalar\n */\ninline auto multiply(const double scalar, const matrix_gpu& A) {\n  return multiply(A, scalar);\n}\n\n/**\n * Computes the product of the specified GPU matrices.\n *\n * Computes the matrix multiplication C[M, K] = A[M, N] x B[N, K]\n *\n * @param A first matrix\n * @param B second matrix\n * @return the product of the first and second matrix\n *\n * @throw <code>std::invalid_argument</code> if the\n *   number of columns in A and rows in B do not match\n */\ninline auto multiply(const matrix_gpu& A, const matrix_gpu& B) {\n  check_size_match(\"multiply (GPU)\", \"A.cols()\", A.cols(), \"B.rows()\",\n                   B.rows());\n  matrix_gpu temp(A.rows(), B.cols());\n  if (A.size() == 0 || B.size() == 0) {\n    temp.zeros();\n    return temp;\n  }\n  int local = opencl_kernels::matrix_multiply.make_functor.get_opts().at(\n      \"THREAD_BLOCK_SIZE\");\n  int Mpad = ((A.rows() + local - 1) / local) * local;\n  int Npad = ((B.cols() + local - 1) / local) * local;\n  int Kpad = ((A.cols() + local - 1) / local) * local;\n  // padding the matrices so the dimensions are divisible with local\n  // improves performance and readability because we can omit\n  // if statements in the\n  // multiply kernel\n  matrix_gpu tempPad(Mpad, Npad);\n  matrix_gpu Apad(Mpad, Kpad);\n  matrix_gpu Bpad(Kpad, Npad);\n  opencl_kernels::zeros(cl::NDRange(Mpad, Kpad), Apad.buffer(), Mpad, Kpad,\n                        TriangularViewGPU::Entire);\n  opencl_kernels::zeros(cl::NDRange(Kpad, Npad), Bpad.buffer(), Kpad, Npad,\n                        TriangularViewGPU::Entire);\n  Apad.sub_block(A, 0, 0, 0, 0, A.rows(), A.cols());\n  Bpad.sub_block(B, 0, 0, 0, 0, B.rows(), B.cols());\n  int wpt = opencl_kernels::matrix_multiply.make_functor.get_opts().at(\n      \"WORK_PER_THREAD\");\n  try {\n    opencl_kernels::matrix_multiply(\n        cl::NDRange(Mpad, Npad / wpt), cl::NDRange(local, local / wpt),\n        Apad.buffer(), Bpad.buffer(), tempPad.buffer(), Apad.rows(),\n        Bpad.cols(), Bpad.rows());\n  } catch (cl::Error& e) {\n    check_opencl_error(\"multiply\", e);\n  }\n  // unpadding the result matrix\n  temp.sub_block(tempPad, 0, 0, 0, 0, temp.rows(), temp.cols());\n  return temp;\n}\n\n/**\n * Templated product operator for GPU matrices.\n *\n * Computes the matrix multiplication C[M, K] = A[M, N] x B[N, K].\n *\n * @param A A matrix or scalar\n * @param B A matrix or scalar\n * @return the product of the first and second arguments\n *\n * @throw <code>std::invalid_argument</code> if the\n *   number of columns in A and rows in B do not match\n */\ninline matrix_gpu operator*(const matrix_gpu& A, const matrix_gpu& B) {\n  return multiply(A, B);\n}\ninline matrix_gpu operator*(const matrix_gpu& B, const double scalar) {\n  return multiply(B, scalar);\n}\ninline matrix_gpu operator*(const double scalar, const matrix_gpu& B) {\n  return multiply(scalar, B);\n}\n}  // namespace math\n}  // namespace stan\n\n#endif\n#endif\n", "meta": {"hexsha": "14c9cda500cfb12a37e94ef483653a53c21f9ca9", "size": 3898, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/gpu/multiply.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/gpu/multiply.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/gpu/multiply.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": 31.6910569106, "max_line_length": 78, "alphanum_fraction": 0.6580297589, "num_tokens": 1070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.28595531056210705}}
{"text": "//\n//=======================================================================\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n//\n\n/*\n  This file implements the function\n\n  template <class EdgeListGraph, class Size, class P, class T, class R>\n  bool bellman_ford_shortest_paths(EdgeListGraph& g, Size N, \n     const bgl_named_params<P, T, R>& params)\n  \n */\n\n\n#ifndef BOOST_GRAPH_BELLMAN_FORD_SHORTEST_PATHS_HPP\n#define BOOST_GRAPH_BELLMAN_FORD_SHORTEST_PATHS_HPP\n\n#include <boost/config.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/relax.hpp>\n#include <boost/graph/visitors.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <boost/concept/assert.hpp>\n\nnamespace boost {\n\n  template <class Visitor, class Graph>\n  struct BellmanFordVisitorConcept {\n    void constraints() {\n      BOOST_CONCEPT_ASSERT(( CopyConstructibleConcept<Visitor> ));\n      vis.examine_edge(e, g);\n      vis.edge_relaxed(e, g);\n      vis.edge_not_relaxed(e, g);\n      vis.edge_minimized(e, g);\n      vis.edge_not_minimized(e, g);\n    }\n    Visitor vis;\n    Graph g;\n    typename graph_traits<Graph>::edge_descriptor e;\n  };\n\n  template <class Visitors = null_visitor>\n  class bellman_visitor {\n  public:\n    bellman_visitor() { }\n    bellman_visitor(Visitors vis) : m_vis(vis) { }\n\n    template <class Edge, class Graph>\n    void examine_edge(Edge u, Graph& g) {\n      invoke_visitors(m_vis, u, g, on_examine_edge());\n    }\n    template <class Edge, class Graph>\n    void edge_relaxed(Edge u, Graph& g) {\n      invoke_visitors(m_vis, u, g, on_edge_relaxed());      \n    }\n    template <class Edge, class Graph>\n    void edge_not_relaxed(Edge u, Graph& g) {\n      invoke_visitors(m_vis, u, g, on_edge_not_relaxed());\n    }\n    template <class Edge, class Graph>\n    void edge_minimized(Edge u, Graph& g) {\n      invoke_visitors(m_vis, u, g, on_edge_minimized());\n    }\n    template <class Edge, class Graph>\n    void edge_not_minimized(Edge u, Graph& g) {\n      invoke_visitors(m_vis, u, g, on_edge_not_minimized());\n    }\n  protected:\n    Visitors m_vis;\n  };\n  template <class Visitors>\n  bellman_visitor<Visitors>\n  make_bellman_visitor(Visitors vis) {\n    return bellman_visitor<Visitors>(vis);\n  }\n  typedef bellman_visitor<> default_bellman_visitor;\n\n  template <class EdgeListGraph, class Size, class WeightMap,\n            class PredecessorMap, class DistanceMap,\n            class BinaryFunction, class BinaryPredicate,\n            class BellmanFordVisitor>\n  bool bellman_ford_shortest_paths(EdgeListGraph& g, Size N, \n                         WeightMap weight, \n                         PredecessorMap pred,\n                         DistanceMap distance, \n                         BinaryFunction combine, \n                         BinaryPredicate compare,\n                         BellmanFordVisitor v)\n  {\n    BOOST_CONCEPT_ASSERT(( EdgeListGraphConcept<EdgeListGraph> ));\n    typedef graph_traits<EdgeListGraph> GTraits;\n    typedef typename GTraits::edge_descriptor Edge;\n    typedef typename GTraits::vertex_descriptor Vertex;\n    BOOST_CONCEPT_ASSERT(( ReadWritePropertyMapConcept<DistanceMap, Vertex> ));\n    BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<WeightMap, Edge> ));\n    typedef typename property_traits<DistanceMap>::value_type D_value;\n    typedef typename property_traits<WeightMap>::value_type W_value;\n\n    typename GTraits::edge_iterator i, end;\n\n    for (Size k = 0; k < N; ++k) {\n      bool at_least_one_edge_relaxed = false;\n      for (boost::tie(i, end) = edges(g); i != end; ++i) {\n        v.examine_edge(*i, g);\n        if (relax(*i, g, weight, pred, distance, combine, compare)) {\n          at_least_one_edge_relaxed = true;\n          v.edge_relaxed(*i, g);\n        } else\n          v.edge_not_relaxed(*i, g);\n      }\n      if (!at_least_one_edge_relaxed)\n        break;\n    }\n\n    for (boost::tie(i, end) = edges(g); i != end; ++i)\n      if (compare(combine(get(distance, source(*i, g)), get(weight, *i)),\n                  get(distance, target(*i,g))))\n      {\n        v.edge_not_minimized(*i, g);\n        return false;\n      } else\n        v.edge_minimized(*i, g);\n\n    return true;\n  }\n\n  namespace detail {\n\n    template<typename VertexAndEdgeListGraph, typename Size, \n             typename WeightMap, typename PredecessorMap, typename DistanceMap,\n             typename P, typename T, typename R>\n    bool \n    bellman_dispatch2\n      (VertexAndEdgeListGraph& g, \n       typename graph_traits<VertexAndEdgeListGraph>::vertex_descriptor s,\n       Size N, WeightMap weight, PredecessorMap pred, DistanceMap distance,\n       const bgl_named_params<P, T, R>& params)\n    {\n      typedef typename property_traits<DistanceMap>::value_type D;\n      bellman_visitor<> null_vis;\n      typedef typename property_traits<WeightMap>::value_type weight_type;\n      typename graph_traits<VertexAndEdgeListGraph>::vertex_iterator v, v_end;\n      for (boost::tie(v, v_end) = vertices(g); v != v_end; ++v) {\n        put(distance, *v, (std::numeric_limits<weight_type>::max)());\n        put(pred, *v, *v);\n      }\n      put(distance, s, weight_type(0));\n      return bellman_ford_shortest_paths\n               (g, N, weight, pred, distance,\n                choose_param(get_param(params, distance_combine_t()),\n                             closed_plus<D>()),\n                choose_param(get_param(params, distance_compare_t()),\n                             std::less<D>()),\n                choose_param(get_param(params, graph_visitor),\n                             null_vis)\n                );\n    }\n\n    template<typename VertexAndEdgeListGraph, typename Size, \n             typename WeightMap, typename PredecessorMap, typename DistanceMap,\n             typename P, typename T, typename R>\n    bool \n    bellman_dispatch2\n      (VertexAndEdgeListGraph& g, \n       detail::error_property_not_found,\n       Size N, WeightMap weight, PredecessorMap pred, DistanceMap distance,\n       const bgl_named_params<P, T, R>& params)\n    {\n      typedef typename property_traits<DistanceMap>::value_type D;\n      bellman_visitor<> null_vis;\n      return bellman_ford_shortest_paths\n               (g, N, weight, pred, distance,\n                choose_param(get_param(params, distance_combine_t()),\n                             closed_plus<D>()),\n                choose_param(get_param(params, distance_compare_t()),\n                             std::less<D>()),\n                choose_param(get_param(params, graph_visitor),\n                             null_vis)\n                );\n    }\n\n    template <class EdgeListGraph, class Size, class WeightMap,\n              class DistanceMap, class P, class T, class R>\n    bool bellman_dispatch(EdgeListGraph& g, Size N, \n                          WeightMap weight, DistanceMap distance, \n                          const bgl_named_params<P, T, R>& params)\n    {\n      dummy_property_map dummy_pred;\n      return \n        detail::bellman_dispatch2\n          (g, \n           get_param(params, root_vertex_t()),\n           N, weight,\n           choose_param(get_param(params, vertex_predecessor), dummy_pred),\n           distance,\n           params);\n    }\n  } // namespace detail\n\n  template <class EdgeListGraph, class Size, class P, class T, class R>\n  bool bellman_ford_shortest_paths\n    (EdgeListGraph& g, Size N, \n     const bgl_named_params<P, T, R>& params)\n  {                                \n    return detail::bellman_dispatch\n      (g, N,\n       choose_const_pmap(get_param(params, edge_weight), g, edge_weight),\n       choose_pmap(get_param(params, vertex_distance), g, vertex_distance),\n       params);\n  }\n\n  template <class EdgeListGraph, class Size>\n  bool bellman_ford_shortest_paths(EdgeListGraph& g, Size N)\n  {                                \n    bgl_named_params<int,int> params(0);\n    return bellman_ford_shortest_paths(g, N, params);\n  }\n\n  template <class VertexAndEdgeListGraph, class P, class T, class R>\n  bool bellman_ford_shortest_paths\n    (VertexAndEdgeListGraph& g, \n     const bgl_named_params<P, T, R>& params)\n  {               \n    BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<VertexAndEdgeListGraph> ));\n    return detail::bellman_dispatch\n      (g, num_vertices(g),\n       choose_const_pmap(get_param(params, edge_weight), g, edge_weight),\n       choose_pmap(get_param(params, vertex_distance), g, vertex_distance),\n       params);\n  }\n} // namespace boost\n\n#endif // BOOST_GRAPH_BELLMAN_FORD_SHORTEST_PATHS_HPP\n", "meta": {"hexsha": "c80ebe7c7d3fbb19d97da6d7e49ca122a4fa4436", "size": 8810, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/graph/bellman_ford_shortest_paths.hpp", "max_stars_repo_name": "brinkqiang/dmspirit", "max_stars_repo_head_hexsha": "4eb09bed3a69d9327610560fe38c54d9f24112d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-01-03T23:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T17:41:27.000Z", "max_issues_repo_path": "Boost_1_49/boost/graph/bellman_ford_shortest_paths.hpp", "max_issues_repo_name": "jjzhang166/WinUtil4", "max_issues_repo_head_hexsha": "7c7b1e9bbe2fb6177bb066d74764d10711748ec5", "max_issues_repo_licenses": ["MIT"], "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_1_49/boost/graph/bellman_ford_shortest_paths.hpp", "max_forks_repo_name": "jjzhang166/WinUtil4", "max_forks_repo_head_hexsha": "7c7b1e9bbe2fb6177bb066d74764d10711748ec5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-02-08T18:01:56.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-04T21:30:08.000Z", "avg_line_length": 36.2551440329, "max_line_length": 79, "alphanum_fraction": 0.6313280363, "num_tokens": 2078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.28589601441379686}}
{"text": "#include \"adafParameters.h\"\n#include \"adafFunctions.h\"\n#include <math.h>\n#include <iostream>\n#include <fstream>\n#include <fmath/physics.h>\n#include <fparameters/parameters.h>\n#include <boost/property_tree/ptree.hpp>\n#include <fparameters/SpaceIterator.h>\n#include \"State.h\"\n\nusing namespace std;\n\n///////////////////////\n\nvoid adafParameters() \n{\t\n\tifstream adafFile, adafParams;\n\n\tadafFile.open(\"adafFile.txt\"); adafParams.open(\"adafParameters.txt\");\n\tadafFile >> nRaux;\n\tadafParams >> blackHoleMass >> accRateOut >> s >> magFieldPar >> alpha >> jAngMom >> delta >> rTr >> powerIndex;\n\tadafParams.close();\n\t\n\tlogr.resize(nRaux,0.0);\n\tlogTi.resize(nRaux,0.0);\n\tlogTe.resize(nRaux,0.0);\n\tlogv.resize(nRaux,0.0);\n\t\n\tfor (size_t i=0;i<nRaux;i++) {\n\t\tadafFile >> logr[i] >> logTi[i] >> logTe[i] >> logv[i];\n\t}\n\tadafFile.close();\n    \n\tblackHoleMass *= solarMass;\n\tschwRadius = 2.0*gravitationalConstant*blackHoleMass / cLight2;\n\taccRateOut = accRateOut * 1.39e18 * blackHoleMass/solarMass;\n\tcout << \"Total outer accretion power = \" << accRateOut*cLight2 << \" erg s^{-1}\" << endl;\n\tcout << \"Total inner accretion power = \" << accRateOut*pow(1.0/exp(logr.back()), s)*cLight2 \n\t\t << \" erg s^{-1}\" << endl;\n    \n\trTr = rTr * schwRadius;\n\trOutCD = GlobalConfig.get<double>(\"rOutCD\") * schwRadius;\n\teMeanMolecularWeight = GlobalConfig.get<double>(\"mu_e\");\n\tiMeanMolecularWeight = GlobalConfig.get<double>(\"mu_i\");\n\n\tnR = GlobalConfig.get<int>(\"model.particle.default.dim.radius.samples\");\n\tnE = GlobalConfig.get<int>(\"model.particle.photon.dim.energy.samples\");\n\tnRcd = GlobalConfig.get<int>(\"model.particle.default.dim.radius_cd.samples\");\n    \n    paso_r = pow(exp(logr.back())/exp(logr.front()),1.0/(nR));\n\tpaso_rCD = pow(rOutCD/rTr,1.0/(nRcd));\n\n\tlogMinEnergy = GlobalConfig.get<double>(\"model.particle.photon.dim.energy.min\");\n\tlogMaxEnergy = GlobalConfig.get<double>(\"model.particle.photon.dim.energy.max\");\n\n\tinclination = GlobalConfig.get<double>(\"inclination\");\n    \n    calculateComptonScatt = GlobalConfig.get<int>(\"calculateComptonScatt\");\n\theight_method = GlobalConfig.get<int>(\"height_method\");\n    \n    calculateThermal = GlobalConfig.get<int>(\"calculateThermal\");\n\tnumProcesses = GlobalConfig.get<int>(\"thermal.numProcesses\");\n    if (calculateThermal) {\n        calculateComptonRedMatrix = GlobalConfig.get<int>(\"thermal.compton.calculateRedMatrix\");\n        comptonMethod = GlobalConfig.get<int>(\"thermal.compton.method\");\n        if (1) {\n\n            nGammaCompton = GlobalConfig.get<size_t>(\"thermal.compton.redMatrixParams.nGammaCompton\");\n            nTempCompton = GlobalConfig.get<size_t>(\"thermal.compton.redMatrixParams.nTempCompton\");\n            nNuPrimCompton = GlobalConfig.get<size_t>(\"thermal.compton.redMatrixParams.nNuPrimCompton\");\n            nNuCompton = GlobalConfig.get<size_t>(\"thermal.compton.redMatrixParams.nNuCompton\");\n            gammaMinCompton = GlobalConfig.get<double>(\"thermal.compton.redMatrixParams.gammaMinCompton\");\n            gammaMaxCompton = GlobalConfig.get<double>(\"thermal.compton.redMatrixParams.gammaMaxCompton\");\n            tempMinCompton = GlobalConfig.get<double>(\"thermal.compton.redMatrixParams.tempMinCompton\");\n            tempMaxCompton = GlobalConfig.get<double>(\"thermal.compton.redMatrixParams.tempMaxCompton\");\n            nuPrimMinCompton = GlobalConfig.get<double>(\"thermal.compton.redMatrixParams.nuPrimMinCompton\");\n            nuPrimMaxCompton = GlobalConfig.get<double>(\"thermal.compton.redMatrixParams.nuPrimMaxCompton\");\n            nuMinCompton = GlobalConfig.get<double>(\"thermal.compton.redMatrixParams.nuMinCompton\");\n            nuMaxCompton = GlobalConfig.get<double>(\"thermal.compton.redMatrixParams.nuMaxCompton\");\n            \n            ofstream fileSizes;\n            fileSizes.open(\"comptonRedMatrix/sizesVecCompton.dat\",ios::out);\n            fileSizes << nGammaCompton << \"\\t\" << gammaMinCompton << \"\\t\" << gammaMaxCompton << endl\n                      << nTempCompton << \"\\t\" << tempMinCompton << \"\\t\" << tempMaxCompton << endl\n                      << nNuPrimCompton << \"\\t\" << nuPrimMinCompton << \"\\t\" << nuPrimMaxCompton << endl\n                      << nNuCompton << \"\\t\" << nuMinCompton << \"\\t\" << nuMaxCompton << endl;\n            fileSizes.close();\n        } else {\n            ifstream fileSizes;\n            fileSizes.open(\"comptonRedMatrix/sizesVecCompton.dat\",ios::in);\n            fileSizes >> nGammaCompton >> gammaMinCompton >> gammaMaxCompton\n                      >> nTempCompton >> tempMinCompton >> tempMaxCompton\n                      >> nNuPrimCompton >> nuPrimMinCompton >> nuPrimMaxCompton\n                      >> nNuCompton >> nuMinCompton >> nuMaxCompton;\n            fileSizes.close();\n        }\n        calculatePhotonDensityGap = GlobalConfig.get<int>(\"thermal.calculatePhotonDensityGap\");\n    }\n\tcalculateJetEmission = GlobalConfig.get<int>(\"nonThermal.calculateJetEmission\");\n\t\n    calculateNonThermal = GlobalConfig.get<int>(\"calculateNonThermal\");\n    if (calculateNonThermal) {\n\t\taccMethod = GlobalConfig.get<double>(\"nonThermal.acc_method\");\n\t\tcalculateNTprotons = GlobalConfig.get<int>(\"nonThermal.protons\");\n\t\tcalculateNTelectrons = GlobalConfig.get<int>(\"nonThermal.electrons\");\n        calculateLosses = GlobalConfig.get<int>(\"nonThermal.calculateLosses\");\n\t\tcalculateFlare = GlobalConfig.get<int>(\"nonThermal.calculateFlare\");\n        calculateNTdistributions = GlobalConfig.get<int>(\"nonThermal.calculateDistributions\");\n        calculateNonThermalLum = GlobalConfig.get<int>(\"nonThermal.calculateLuminosities\");\n\t\tcalculateNonThermalHE = GlobalConfig.get<int>(\"nonThermal.calculateHighEnergyProcesses\");\n        calculateNeutronInj = GlobalConfig.get<int>(\"nonThermal.neutrons.calculateInjection\");\n\t\tcalculateNeutronDis = GlobalConfig.get<int>(\"nonThermal.neutrons.calculatePropagation\");\n\t\tcalculateJetDecay = GlobalConfig.get<int>(\"nonThermal.neutrons.calculateJetDecay\");\n\t\tcalculateSecondaries = GlobalConfig.get<int>(\"nonThermal.calculateSecondaries\");\n\t\tcalculateNeutrinos = GlobalConfig.get<int>(\"nonThermal.calculateNeutrinos\");\n\t}\n}", "meta": {"hexsha": "bd78a3fbb30c2c0a4fe162855a2952158165f314", "size": 6075, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/adaf/adafParameters.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/adafParameters.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/adafParameters.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": 51.4830508475, "max_line_length": 113, "alphanum_fraction": 0.698436214, "num_tokens": 1528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.285859508239037}}
{"text": "/**\n * @file kde_model_impl.hpp\n * @author Roberto Hueso\n *\n * Implementation of KDE Model.\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_KDE_MODEL_IMPL_HPP\n#define MLPACK_METHODS_KDE_MODEL_IMPL_HPP\n\n// In case it hasn't been included yet.\n#include \"kde_model.hpp\"\n\n#include <boost/serialization/variant.hpp>\n\nnamespace mlpack {\nnamespace kde {\n\n//! Initialize the KDEModel with the given parameters.\ninline KDEModel::KDEModel(const double bandwidth,\n                          const double relError,\n                          const double absError,\n                          const KernelTypes kernelType,\n                          const TreeTypes treeType) :\n  bandwidth(bandwidth),\n  relError(relError),\n  absError(absError),\n  kernelType(kernelType),\n  treeType(treeType)\n{\n  // Nothing to do.\n}\n\n// Copy constructor.\ninline KDEModel::KDEModel(const KDEModel& other) :\n  bandwidth(other.bandwidth),\n  relError(other.relError),\n  absError(other.absError),\n  kernelType(other.kernelType),\n  treeType(other.treeType)\n{\n  // Nothing to do.\n}\n\n// Move constructor.\ninline KDEModel::KDEModel(KDEModel&& other) :\n  bandwidth(other.bandwidth),\n  relError(other.relError),\n  absError(other.absError),\n  kernelType(other.kernelType),\n  treeType(other.treeType),\n  kdeModel(std::move(other.kdeModel))\n{\n  // Reset other model.\n  other.bandwidth = 1.0;\n  other.relError = 0.05;\n  other.absError = 0;\n  other.kernelType = KernelTypes::GAUSSIAN_KERNEL;\n  other.treeType = TreeTypes::KD_TREE;\n  other.kdeModel = decltype(other.kdeModel)();\n}\n\ninline KDEModel& KDEModel::operator=(KDEModel other)\n{\n  boost::apply_visitor(DeleteVisitor(), kdeModel);\n  bandwidth = other.bandwidth;\n  relError = other.relError;\n  absError = other.absError;\n  kernelType = other.kernelType;\n  treeType = other.treeType;\n  kdeModel = std::move(other.kdeModel);\n  return *this;\n}\n\n// Clean memory.\ninline KDEModel::~KDEModel()\n{\n  boost::apply_visitor(DeleteVisitor(), kdeModel);\n}\n\ninline void KDEModel::BuildModel(arma::mat&& referenceSet)\n{\n  // Clean memory, if necessary.\n  boost::apply_visitor(DeleteVisitor(), kdeModel);\n\n  // Build the actual model.\n  if (kernelType == GAUSSIAN_KERNEL && treeType == KD_TREE)\n  {\n    kdeModel = new KDEType<kernel::GaussianKernel, tree::KDTree>\n        (relError, absError, kernel::GaussianKernel(bandwidth));\n  }\n  else if (kernelType == GAUSSIAN_KERNEL && treeType == BALL_TREE)\n  {\n    kdeModel = new KDEType<kernel::GaussianKernel, tree::BallTree>\n        (relError, absError, kernel::GaussianKernel(bandwidth));\n  }\n  else if (kernelType == GAUSSIAN_KERNEL && treeType == COVER_TREE)\n  {\n    kdeModel = new KDEType<kernel::GaussianKernel, tree::StandardCoverTree>\n        (relError, absError, kernel::GaussianKernel(bandwidth));\n  }\n  else if (kernelType == GAUSSIAN_KERNEL && treeType == OCTREE)\n  {\n    kdeModel = new KDEType<kernel::GaussianKernel, tree::Octree>\n        (relError, absError, kernel::GaussianKernel(bandwidth));\n  }\n  else if (kernelType == GAUSSIAN_KERNEL && treeType == R_TREE)\n  {\n    kdeModel = new KDEType<kernel::GaussianKernel, tree::RTree>\n        (relError, absError, kernel::GaussianKernel(bandwidth));\n  }\n  else if (kernelType == EPANECHNIKOV_KERNEL && treeType == KD_TREE)\n  {\n    kdeModel = new KDEType<kernel::EpanechnikovKernel, tree::KDTree>\n        (relError, absError, kernel::EpanechnikovKernel(bandwidth));\n  }\n  else if (kernelType == EPANECHNIKOV_KERNEL && treeType == BALL_TREE)\n  {\n    kdeModel = new KDEType<kernel::EpanechnikovKernel, tree::BallTree>\n        (relError, absError, kernel::EpanechnikovKernel(bandwidth));\n  }\n  else if (kernelType == EPANECHNIKOV_KERNEL && treeType == COVER_TREE)\n  {\n    kdeModel = new KDEType<kernel::EpanechnikovKernel, tree::StandardCoverTree>\n        (relError, absError, kernel::EpanechnikovKernel(bandwidth));\n  }\n  else if (kernelType == EPANECHNIKOV_KERNEL && treeType == OCTREE)\n  {\n    kdeModel = new KDEType<kernel::EpanechnikovKernel, tree::Octree>\n        (relError, absError, kernel::EpanechnikovKernel(bandwidth));\n  }\n  else if (kernelType == EPANECHNIKOV_KERNEL && treeType == R_TREE)\n  {\n    kdeModel = new KDEType<kernel::EpanechnikovKernel, tree::RTree>\n        (relError, absError, kernel::EpanechnikovKernel(bandwidth));\n  }\n  else if (kernelType == LAPLACIAN_KERNEL && treeType == KD_TREE)\n  {\n    kdeModel = new KDEType<kernel::LaplacianKernel, tree::KDTree>\n        (relError, absError, kernel::LaplacianKernel(bandwidth));\n  }\n  else if (kernelType == LAPLACIAN_KERNEL && treeType == BALL_TREE)\n  {\n    kdeModel = new KDEType<kernel::LaplacianKernel, tree::BallTree>\n        (relError, absError, kernel::LaplacianKernel(bandwidth));\n  }\n  else if (kernelType == LAPLACIAN_KERNEL && treeType == COVER_TREE)\n  {\n    kdeModel = new KDEType<kernel::LaplacianKernel, tree::StandardCoverTree>\n        (relError, absError, kernel::LaplacianKernel(bandwidth));\n  }\n  else if (kernelType == LAPLACIAN_KERNEL && treeType == OCTREE)\n  {\n    kdeModel = new KDEType<kernel::LaplacianKernel, tree::Octree>\n        (relError, absError, kernel::LaplacianKernel(bandwidth));\n  }\n  else if (kernelType == LAPLACIAN_KERNEL && treeType == R_TREE)\n  {\n    kdeModel = new KDEType<kernel::LaplacianKernel, tree::RTree>\n        (relError, absError, kernel::LaplacianKernel(bandwidth));\n  }\n  else if (kernelType == SPHERICAL_KERNEL && treeType == KD_TREE)\n  {\n    kdeModel = new KDEType<kernel::SphericalKernel, tree::KDTree>\n        (relError, absError, kernel::SphericalKernel(bandwidth));\n  }\n  else if (kernelType == SPHERICAL_KERNEL && treeType == BALL_TREE)\n  {\n    kdeModel = new KDEType<kernel::SphericalKernel, tree::BallTree>\n        (relError, absError, kernel::SphericalKernel(bandwidth));\n  }\n  else if (kernelType == SPHERICAL_KERNEL && treeType == COVER_TREE)\n  {\n    kdeModel = new KDEType<kernel::SphericalKernel, tree::StandardCoverTree>\n        (relError, absError, kernel::SphericalKernel(bandwidth));\n  }\n  else if (kernelType == SPHERICAL_KERNEL && treeType == OCTREE)\n  {\n    kdeModel = new KDEType<kernel::SphericalKernel, tree::Octree>\n        (relError, absError, kernel::SphericalKernel(bandwidth));\n  }\n  else if (kernelType == SPHERICAL_KERNEL && treeType == R_TREE)\n  {\n    kdeModel = new KDEType<kernel::SphericalKernel, tree::RTree>\n        (relError, absError, kernel::SphericalKernel(bandwidth));\n  }\n  else if (kernelType == TRIANGULAR_KERNEL && treeType == KD_TREE)\n  {\n    kdeModel = new KDEType<kernel::TriangularKernel, tree::KDTree>\n        (relError, absError, kernel::TriangularKernel(bandwidth));\n  }\n  else if (kernelType == TRIANGULAR_KERNEL && treeType == BALL_TREE)\n  {\n    kdeModel = new KDEType<kernel::TriangularKernel, tree::BallTree>\n        (relError, absError, kernel::TriangularKernel(bandwidth));\n  }\n  else if (kernelType == TRIANGULAR_KERNEL && treeType == COVER_TREE)\n  {\n    kdeModel = new KDEType<kernel::TriangularKernel, tree::StandardCoverTree>\n        (relError, absError, kernel::TriangularKernel(bandwidth));\n  }\n  else if (kernelType == TRIANGULAR_KERNEL && treeType == OCTREE)\n  {\n    kdeModel = new KDEType<kernel::TriangularKernel, tree::Octree>\n        (relError, absError, kernel::TriangularKernel(bandwidth));\n  }\n  else if (kernelType == TRIANGULAR_KERNEL && treeType == R_TREE)\n  {\n    kdeModel = new KDEType<kernel::TriangularKernel, tree::RTree>\n        (relError, absError, kernel::TriangularKernel(bandwidth));\n  }\n\n  // Train the model.\n  TrainVisitor train(std::move(referenceSet));\n  boost::apply_visitor(train, kdeModel);\n}\n\n// Perform bichromatic evaluation.\ninline void KDEModel::Evaluate(arma::mat&& querySet, arma::vec& estimations)\n{\n  Log::Info << \"Evaluating KDE...\" << std::endl;\n  DualBiKDE eval(std::move(querySet), estimations);\n  boost::apply_visitor(eval, kdeModel);\n}\n\n// Perform monochromatic evaluation.\ninline void KDEModel::Evaluate(arma::vec& estimations)\n{\n  Log::Info << \"Evaluating KDE...\" << std::endl;\n  DualMonoKDE eval(estimations);\n  boost::apply_visitor(eval, kdeModel);\n}\n\n// Clean memory.\ninline void KDEModel::CleanMemory()\n{\n  boost::apply_visitor(DeleteVisitor(), kdeModel);\n}\n\n// Parameters for KDE evaluation.\nDualMonoKDE::DualMonoKDE(arma::vec& estimations):\n    estimations(estimations)\n{}\n\n// Default KDE evaluation.\ntemplate<typename KernelType,\n         template<typename TreeMetricType,\n                  typename TreeStatType,\n                  typename TreeMatType> class TreeType>\nvoid DualMonoKDE::operator()(KDETypeT<KernelType, TreeType>* kde) const\n{\n  if (kde)\n  {\n    kde->Evaluate(estimations);\n    const size_t dimension = (kde->ReferenceTree())->Dataset().n_rows;\n    KernelNormalizer::ApplyNormalizer<KernelType>(kde->Kernel(),\n                                                  dimension,\n                                                  estimations);\n  }\n  else\n  {\n    throw std::runtime_error(\"no KDE model initialized\");\n  }\n}\n\n// Parameters for KDE evaluation.\nDualBiKDE::DualBiKDE(arma::mat&& querySet, arma::vec& estimations):\n    dimension(querySet.n_rows),\n    querySet(std::move(querySet)),\n    estimations(estimations)\n{}\n\n// Default KDE evaluation.\ntemplate<typename KernelType,\n         template<typename TreeMetricType,\n                  typename TreeStatType,\n                  typename TreeMatType> class TreeType>\nvoid DualBiKDE::operator()(KDETypeT<KernelType, TreeType>* kde) const\n{\n  if (kde)\n  {\n    kde->Evaluate(std::move(querySet), estimations);\n    KernelNormalizer::ApplyNormalizer<KernelType>(kde->Kernel(),\n                                                  dimension,\n                                                  estimations);\n  }\n  else\n  {\n    throw std::runtime_error(\"no KDE model initialized\");\n  }\n}\n\n// Parameters for Train.\nTrainVisitor::TrainVisitor(arma::mat&& referenceSet) :\n    referenceSet(std::move(referenceSet))\n{}\n\n// Default Train.\ntemplate<typename KernelType,\n         template<typename TreeMetricType,\n                  typename TreeStatType,\n                  typename TreeMatType> class TreeType>\nvoid TrainVisitor::operator()(KDEType<KernelType, TreeType>* kde) const\n{\n  Log::Info << \"Training KDE model...\" << std::endl;\n  if (kde)\n    kde->Train(std::move(referenceSet));\n  else\n    throw std::runtime_error(\"no KDE model initialized\");\n}\n\n// Delete model.\ntemplate<typename KDEType>\nvoid DeleteVisitor::operator()(KDEType* kde) const\n{\n  if (kde)\n    delete kde;\n}\n\n// Mode of model.\ntemplate<typename KDEType>\nKDEMode& ModeVisitor::operator()(KDEType* kde) const\n{\n  if (kde)\n    return kde->Mode();\n  else\n    throw std::runtime_error(\"no KDE model initialized\");\n}\n\n// Get mode of model.\nKDEMode KDEModel::Mode() const\n{\n  return boost::apply_visitor(ModeVisitor(), kdeModel);\n}\n\n// Modify mode of model.\nKDEMode& KDEModel::Mode()\n{\n  return boost::apply_visitor(ModeVisitor(), kdeModel);\n}\n\n// Serialize the model.\ntemplate<typename Archive>\nvoid KDEModel::serialize(Archive& ar, const unsigned int /* version */)\n{\n  ar & BOOST_SERIALIZATION_NVP(bandwidth);\n  ar & BOOST_SERIALIZATION_NVP(relError);\n  ar & BOOST_SERIALIZATION_NVP(absError);\n  ar & BOOST_SERIALIZATION_NVP(kernelType);\n  ar & BOOST_SERIALIZATION_NVP(treeType);\n\n  if (Archive::is_loading::value)\n    boost::apply_visitor(DeleteVisitor(), kdeModel);\n\n  ar & BOOST_SERIALIZATION_NVP(kdeModel);\n}\n\n} // namespace kde\n} // namespace mlpack\n\n#endif\n", "meta": {"hexsha": "eec8797325a6d3092273cba9bf921ef510e2dbda", "size": 11581, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/methods/kde/kde_model_impl.hpp", "max_stars_repo_name": "RMaron/mlpack", "max_stars_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T04:20:29.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-21T23:30:34.000Z", "max_issues_repo_path": "src/mlpack/methods/kde/kde_model_impl.hpp", "max_issues_repo_name": "RMaron/mlpack", "max_issues_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-01-23T18:39:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-15T13:58:34.000Z", "max_forks_repo_path": "src/mlpack/methods/kde/kde_model_impl.hpp", "max_forks_repo_name": "RMaron/mlpack", "max_forks_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-01-20T00:54:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-16T05:34:32.000Z", "avg_line_length": 31.6420765027, "max_line_length": 79, "alphanum_fraction": 0.6875917451, "num_tokens": 3111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.28570520137738664}}
{"text": "/* \n// Copyright 2018 University of Liege\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n//     http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n// Authors:\n// - Adrien Crovato\n*/\n\n//// Main\n// Link program modules (pre, solver, post)\n//\n// Variables accessed throughout the code\n//\n// *Geometry*\n// - symY: defines symmetry about Y axis\n// - sRef: reference surface of the full wing\n//\n// *Networks and Field*\n// - bPan: (network of) body panels (structure)\n// - wPan: (network of) wake panels (structure)\n// - fPan: field panels (structure)\n// - sp: sub-panels (structure)\n//\n// *Physics*\n// - Minf: freestream Mach number\n// - alpha: freestream angle of attack\n// - vInf: freestream velocity vector\n// - cL: lift coefficient\n// - cD: drag coefficient\n//\n// *Numerics*\n// - numC: numerical parameters (structure)\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <ctime>\n#include \"pre.h\"\n#include \"solver.h\"\n#include \"post.h\"\n\n#define ANSI_COLOR_BLUE    \"\\x1b[1;34m\"\n#define ANSI_COLOR_RESET   \"\\x1b[0m\"\n\nusing namespace std;\nusing namespace Eigen;\n\nint main( int argc, char *argv[] ) {\n\n    //// Variable definition\n\t// Geometry\n    bool symY = 0;\n    double sRef = 1;\n    // Constants\n    Numerical_CST numC = {};\n\t// Freestream\n    double Minf = 0;\n    double alpha = 0;\n    Vector3d vInf(1.0, 0.0, 0.0);\n\t// Surface and wake panels\n    // TODO: if several Networks are considered, use std::vector <network>\n\tNetwork bPan = {};\n\tNetwork wPan = {};\n\t// Field cells\n\tField fPan = {};\n    // Sub-panels\n    Subpanel sp = {};\n\t// Forces\n    double cL = 0, cD = 0;\n\n    //// Begin flow\n    // Hello World\n    time_t now = time(0); // get time now\n    char* localNow = ctime(&now);\n    cout << ANSI_COLOR_BLUE;\n    cout << \"***********************************\" << endl;\n    cout << \"**              \\\\_/              **\" << endl;\n    cout << \"**     \\\\_______O(_)O_______/     **\" << endl;\n    cout << \"**         _                     **\" << endl;\n    cout << \"**        / \\\\   __  __  __       **\" << endl;\n    cout << \"**       / _ \\\\ |__||__||  |      **\" << endl;\n    cout << \"**      /_/ \\\\_\\\\|__ |  \\\\|__|      **\" << endl;\n    cout << \"***********************************\";\n    cout << ANSI_COLOR_RESET << endl;\n    cout << \"Hi! My name is Aero v1.0-1809\" << endl;\n    cout << \"Solver started on \" << localNow << endl;\n\n    // Check parameters\n    if (argc != 3) {\n        cout << \"Incorrect number of parameters provided!\" << endl;\n        cout << \"Usage: ./aero <pathToConfigFile(.cfg)> <pathToGridgridFile(.pts)>.\" << endl;\n        return 1;\n    }\n\n    // Set time counter\n    clock_t start = clock();\n    clock_t startS = clock();\n\n    // Pre-processing\n    pre(argv, numC, symY, sRef, Minf, alpha, vInf, bPan, wPan, fPan, sp);\n    clock_t endS = clock();\n    cout << \"Preprocessing time: \" << (endS - startS) / (double) CLOCKS_PER_SEC << \"s\" << endl << endl;\n\n    // Solver\n    startS = clock();\n    solver(numC, symY, sRef, alpha, vInf, Minf, bPan, wPan, fPan, sp, cL, cD);\n    endS = clock();\n    cout << \"Solver time: \" << (endS - startS) / (double) CLOCKS_PER_SEC << \"s\" << endl << endl;\n\n    // Post-processing\n    startS = clock();\n    post(sRef, alpha, Minf, bPan, fPan, cL, cD);\n    endS = clock();\n    cout << \"Postprocessing time: \" << (endS - startS) / (double) CLOCKS_PER_SEC << \"s\" << endl << endl;\n\n    // Total time\n    clock_t end = clock();\n    cout << \"***** Run summary *****\" << endl;\n    cout << \"Total time: \" << (end - start) / (double) CLOCKS_PER_SEC << \"s\" << endl << endl;\n\n    return 0;\n}", "meta": {"hexsha": "3fe292cd7f8e71cb6e57f0b92125f82db91df573", "size": 3991, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "acrovato/aero", "max_stars_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-11-16T15:24:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T09:36:09.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "acrovato/aero", "max_issues_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "acrovato/aero", "max_forks_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2348484848, "max_line_length": 104, "alphanum_fraction": 0.5722876472, "num_tokens": 1152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.5117166047041652, "lm_q1q2_score": 0.2857052013773866}}
{"text": "// Copyright (c) 2015-2018, CNRS\n// Authors: Justin Carpentier <jcarpent@laas.fr>\n\n#ifndef __multicontact_api_trajectories_cubic_hermite_spline_hpp__\n#define __multicontact_api_trajectories_cubic_hermite_spline_hpp__\n\n#include \"multicontact-api/trajectories/fwd.hpp\"\n#include \"multicontact-api/serialization/eigen-matrix.hpp\"\n#include \"multicontact-api/serialization/archive.hpp\"\n\n#include <Eigen/Dense>\n\nnamespace multicontact_api\n{\n  namespace trajectories\n  {\n    namespace detail\n    {\n//      template<typename _Scalar, int _dim>\n    }\n\n    template<typename _Scalar, int _dim>\n    struct CubicHermiteSplineTpl\n    : public serialization::Serializable< CubicHermiteSplineTpl<_Scalar,_dim> >\n    {\n      EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n      typedef _Scalar Scalar;\n      enum { dim = _dim };\n      typedef Eigen::Matrix<Scalar,dim,Eigen::Dynamic> MatrixDx;\n      typedef Eigen::Matrix<Scalar,Eigen::Dynamic,1> VectorX;\n      typedef Eigen::Matrix<Scalar,dim,1> VectorD;\n      typedef Eigen::DenseIndex Index;\n\n      CubicHermiteSplineTpl()\n      : m_absicca()\n      , m_points(_dim,0)\n      , m_derivatives(_dim,0)\n      , m_ds()\n      {}\n\n      CubicHermiteSplineTpl(const Index size)\n      : m_absicca(size)\n      , m_points(_dim,size)\n      , m_derivatives(_dim,size)\n      , m_ds((size-1>0)?size-1:0)\n      {}\n\n      template<typename VectorDerived, typename MatrixDerived>\n      CubicHermiteSplineTpl(const Eigen::MatrixBase<VectorDerived> & absicca,\n                            const Eigen::MatrixBase<MatrixDerived> & points,\n                            const Eigen::MatrixBase<MatrixDerived> & derivatives\n                            )\n      : m_absicca(absicca)\n      , m_points(points)\n      , m_derivatives(derivatives)\n      , m_ds(absicca.size()-1)\n      {\n        //EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(MatrixDerived,MatrixDx);\n        //EIGEN_STATIC_ASSERT_SAME_VECTOR_SIZE(VectorDerived,VectorX);\n\n        assert(points.cols() == derivatives.cols() && \"Points and derivatives must have the same number of columns.\");\n        assert(points.cols() == absicca.size() && \"Points and times must have the same dimension.\");\n\n        compute();\n        assert(check());\n      }\n\n      template<typename OtherScalar>\n      CubicHermiteSplineTpl(const CubicHermiteSplineTpl<OtherScalar,dim> & other)\n      : m_absicca(other.m_absicca)\n      , m_points(other.m_points)\n      , m_derivatives(other.m_derivatives)\n      {\n        compute();\n      }\n\n      static CubicHermiteSplineTpl Constant(const VectorD & point)\n      {\n        MatrixDx points(point.size(),2), derivatives(MatrixDx::Zero(point.size(),2));\n        points << point, point;\n\n        VectorX absicca(2); absicca << 0., 1.;\n\n        return CubicHermiteSplineTpl(absicca,points,derivatives);\n      }\n\n      template<typename OtherScalar>\n      bool operator==(const CubicHermiteSplineTpl<OtherScalar,dim> & other) const\n      {\n        return\n        m_absicca == other.m_absicca\n        && m_points == other.m_points\n        && m_derivatives == other.m_derivatives\n        && m_ds == other.m_ds\n        ;\n      }\n\n      template<typename OtherScalar>\n      CubicHermiteSplineTpl operator+(const CubicHermiteSplineTpl<OtherScalar,dim> & other) const\n      {\n        assert(dimension() == other.dimension());\n        assert(m_absicca.isApprox(other.m_absicca));\n        return CubicHermiteSplineTpl(m_absicca, m_points+other.m_points,\n                                     m_derivatives+other.m_derivatives);\n      }\n\n\n      template<typename OtherScalar>\n      CubicHermiteSplineTpl operator-(const CubicHermiteSplineTpl<OtherScalar,dim> & other) const\n      {\n        assert(dimension() == other.dimension());\n        assert(m_absicca.isApprox(other.m_absicca));\n        return CubicHermiteSplineTpl(m_absicca, m_points-other.m_points,\n                                     m_derivatives-other.m_derivatives);\n      }\n\n      template<typename OtherScalar>\n      CubicHermiteSplineTpl& operator+=(const CubicHermiteSplineTpl<OtherScalar,dim> & other)\n      {\n        assert(dimension() == other.dimension());\n        assert(m_absicca.isApprox(other.m_absicca));\n        m_points += other.m_points;\n        m_derivatives += other.m_derivatives;\n        return *this;\n      }\n\n\n      template<typename OtherScalar>\n      CubicHermiteSplineTpl& operator-=(const CubicHermiteSplineTpl<OtherScalar,dim> & other)\n      {\n        assert(dimension() == other.dimension());\n        assert(m_absicca.isApprox(other.m_absicca));\n        m_points-=other.m_points;\n        m_derivatives-=other.m_derivatives;\n        return *this;\n      }\n\n      template<typename OtherScalar>\n      bool operator!=(const CubicHermiteSplineTpl<OtherScalar,dim> & other) const\n      { return !(*this != other); }\n\n      const VectorX & absicca() const { return m_absicca; }\n      void setAbsicca(const VectorX & absicca)\n      {\n        assert(absicca.size() == size());\n        m_absicca = absicca;\n        compute();\n        assert(check());\n      }\n\n      const MatrixDx & points() const { return m_points; }\n      MatrixDx & points() { return m_points; }\n\n      const MatrixDx & derivatives() const { return m_derivatives; }\n      MatrixDx & derivatives() { return m_derivatives; }\n\n      ///\n      /// \\brief Returns the number of points contained in the trajectory.\n      ///\n      Index size() const { return m_points.cols(); }\n\n      ///\n      /// \\brief Resize the trajectory with the given input size.\n      ///\n      void resize(const Index size)\n      {\n        assert(size >= 0);\n        m_points.conservativeResize(dimension(),size);\n        m_derivatives.conservativeResize(dimension(),size);\n        m_absicca.conservativeResize(size);\n        m_ds.conservativeResize(size-1);\n      }\n\n      ///\n      /// \\brief Returns the dimension of the trajectory.\n      ///\n      Index dimension() const { return m_points.rows(); }\n\n      ///\n      /// \\brief Returns the number of intervals contained in the trajectory.\n      ///\n      Index numIntervals() const { return size()-1; }\n\n      ///\n      /// \\brief Eval the spline at value s.\n      ///\n      template<typename Derived1, typename Derived2>\n      void eval(const Scalar t,\n                const Eigen::MatrixBase<Derived1> & p,\n                const Eigen::MatrixBase<Derived2> & m) const\n      {\n        //EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(Derived1,VectorD)\n        //EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(Derived2,VectorD)\n\n        const Index id = findInterval(t);\n        Eigen::MatrixBase<Derived1> & p_ = const_cast<Eigen::MatrixBase<Derived1> &>(p);\n        Eigen::MatrixBase<Derived2> & m_ = const_cast<Eigen::MatrixBase<Derived2> &>(m);\n        if(id == size()-1)\n        {\n          p_ = m_points.template rightCols<1>();\n          m_ = m_derivatives.template rightCols<1>();\n          return;\n        }\n\n        const typename MatrixDx::ConstColXpr p0 = m_points.col(id);\n        const typename MatrixDx::ConstColXpr p1 = m_points.col(id+1);\n\n        const typename MatrixDx::ConstColXpr m0 = m_derivatives.col(id);\n        const typename MatrixDx::ConstColXpr m1 = m_derivatives.col(id+1);\n\n        const Scalar & t0 = m_absicca[id];\n        const Scalar & t1 = m_absicca[id+1];\n\n        const Scalar dt = (t1-t0);\n        const Scalar alpha = (t - t0)/dt;\n\n        assert(0. <= alpha <= 1. && \"alpha must be in [0,1]\");\n\n        Scalar h00, h10, h01, h11;\n        evalCoeffs(alpha,h00,h10,h01,h11);\n        h10 *= dt; h11 *= dt;\n\n        p_ = (h00 * p0 + h10 * m0 + h01 * p1 + h11 * m1);\n\n        m_ = (1.-alpha) * m0 + alpha * m1;\n      }\n\n    protected:\n\n      static void evalCoeffs(const Scalar t,\n                             Scalar & h00, Scalar & h10, Scalar & h01, Scalar & h11)\n      {\n        h00 = 1.; h10 = t; h01 = 0.; h11 = 0.;\n\n        Scalar t_pow = t;\n\n        // t^2\n        t_pow = t*t;\n        h00 -= 3*t_pow;\n        h10 -= 2*t_pow;\n        h01 += 3*t_pow;\n        h11 -= t_pow;\n\n        // t^3\n        t_pow *= t;\n        h00 += 2*t_pow;\n        h10 += t_pow;\n        h01 -= 2*t_pow;\n        h11 += t_pow;\n      }\n\n      ///\n      /// \\brief Internal check. It checks if the abissica is monotone.\n      ///\n      bool check() const\n      {\n        return (m_ds.array() > 0.).all();\n      }\n\n      ///\n      /// \\brief Internal computation\n      ///\n      void compute()\n      {\n        assert(numIntervals() >= 1 && \"The number of intervals must be greater or equal to 1.\");\n        m_ds = m_absicca.tail(numIntervals()) - m_absicca.head(numIntervals());\n      }\n\n      ///\n      /// \\brief Returns the index of the interval for the interpolation.\n      ///\n      Index findInterval(const Scalar t) const\n      {\n        if(t < m_absicca[0]) return 0;\n        if(t > m_absicca[size()-1]) return numIntervals()-1;\n\n        Index left_id = 0;\n        Index right_id = size()-1;\n\n        while(left_id <= right_id)\n        {\n          const Index middle_id = left_id + (right_id - left_id)/2;\n          if(m_absicca[middle_id] < t)\n            left_id = middle_id+1;\n          else if(m_absicca[middle_id] > t)\n            right_id = middle_id-1;\n          else\n            return middle_id;\n        }\n\n        return left_id-1;\n      }\n\n      VectorX m_absicca;\n      MatrixDx m_points;\n      MatrixDx m_derivatives;\n      VectorX m_ds;\n\n      // Serialization of the class\n      friend class boost::serialization::access;\n\n      template<class Archive>\n      void save(Archive & ar, const unsigned int /*version*/) const\n      {\n        const Index m_size = size();\n        ar & boost::serialization::make_nvp(\"size\",m_size);\n        ar & boost::serialization::make_nvp(\"absicca\",m_absicca);\n        ar & boost::serialization::make_nvp(\"points\",m_points);\n        ar & boost::serialization::make_nvp(\"derivatives\",m_derivatives);\n      }\n\n      template<class Archive>\n      void load(Archive & ar, const unsigned int /*version*/)\n      {\n        Index m_size;\n        ar & boost::serialization::make_nvp(\"size\",m_size);\n        resize(m_size);\n\n        ar & boost::serialization::make_nvp(\"absicca\",m_absicca);\n        ar & boost::serialization::make_nvp(\"points\",m_points);\n        ar & boost::serialization::make_nvp(\"derivatives\",m_derivatives);\n\n        compute();\n      }\n\n      BOOST_SERIALIZATION_SPLIT_MEMBER()\n\n    };\n\n    template<typename Scalar, int dim> CubicHermiteSplineTpl<Scalar,dim>\n    createHermiteSplineAtAbsicca(const CubicHermiteSplineTpl<Scalar,dim>& spline,\n                                    const typename\n                                    CubicHermiteSplineTpl<Scalar,dim>::VectorX& absicca)\n    {\n      typedef CubicHermiteSplineTpl<Scalar,dim> SplineType;\n      typedef typename SplineType::VectorX VectorX;\n      typedef typename SplineType::MatrixDx MatrixDx;\n      const VectorX& t0 = spline.absicca();\n\n      //Assert that the final and initial point is the same\n      assert(absicca[0] == t0[0]);\n      assert(absicca[absicca.size()-1] == t0[t0.size()-1]);\n      //Assert that the new resolution is higher.\n      //Otherwise, there might be loss of information.\n      assert(absicca.size() >= spline.size());\n\n      MatrixDx p_new(dim, absicca.size());\n      MatrixDx m_new(dim, absicca.size());\n\n      for (int k=0;k<absicca.size();k++)\n      {\n        typename MatrixDx::ColXpr p = p_new.col(k);\n        typename MatrixDx::ColXpr m = m_new.col(k);\n        spline.eval(absicca[k], p, m);\n      }\n\n      return SplineType(absicca, p_new, m_new);\n    }\n  }\n}\n\n#endif // ifndef __multicontact_api_trajectories_cubic_hermite_spline_hpp__\n", "meta": {"hexsha": "765b22f5bca8ff59cacf7bfa1aab6b7605ce1a26", "size": 11522, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/multicontact-api/trajectories/cubic-hermite-spline.hpp", "max_stars_repo_name": "pFernbach/multicontact-api", "max_stars_repo_head_hexsha": "efe4cf25d37aba9184875df6036a864d7aa34b88", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-17T09:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-17T09:19:05.000Z", "max_issues_repo_path": "include/multicontact-api/trajectories/cubic-hermite-spline.hpp", "max_issues_repo_name": "pFernbach/multicontact-api", "max_issues_repo_head_hexsha": "efe4cf25d37aba9184875df6036a864d7aa34b88", "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/multicontact-api/trajectories/cubic-hermite-spline.hpp", "max_forks_repo_name": "pFernbach/multicontact-api", "max_forks_repo_head_hexsha": "efe4cf25d37aba9184875df6036a864d7aa34b88", "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.6538461538, "max_line_length": 118, "alphanum_fraction": 0.606231557, "num_tokens": 2969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2857051938559796}}
{"text": "#ifndef TVTML_DATA2D_HPP\n#define TVTML_DATA2D_HPP\n\n// system includes\n#include <cassert>\n#include <limits>\n#include <cmath>\n#include <random>\n\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n\n// OpenCV includes\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#ifdef TV_DATA_DEBUG\n    #include <opencv2/highgui/highgui.hpp>\n#endif\n\n//Eigen includes\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n// video++ includes\n#include <vpp/vpp.hh>\n#include <vpp/utils/opencv_bridge.hh>\n\n// own includes \n#include \"manifold.hpp\"\n\nnamespace tvmtl{\n\n// Specialization 2D Data\ntemplate < typename MANIFOLD >\nclass Data< MANIFOLD, 2>{\n\n    public:\n\tstatic const int img_dim;\n\t// Manifold typedefs\n\ttypedef typename MANIFOLD::value_type value_type;\n\ttypedef typename MANIFOLD::scalar_type scalar_type;\n\t\n\n\t// Storage typedefs\n\ttypedef vpp::image2d<value_type> storage_type;\n\t\n\ttypedef double weights_type;\n\ttypedef vpp::image2d<weights_type> weights_mat;\n\t\n\ttypedef bool inp_type;\n\ttypedef vpp::image2d<inp_type> inp_mat;\n\n\tinline bool doInpaint() const { return inpaint_; }\n\t    \n\t// Data Init functions\n\tinline void initEdgeweights();\n\tinline void initInp();\n\n\t// Input functions\n\tvoid rgb_imread(std::string filename); \n\tvoid rgb_readBrightness(std::string filename); \n\tvoid rgb_readChromaticity(std::string filename); \n\t\n\tvoid readMatrixDataFromCSV(std::string filename, const int nx, const int ny);\n\t\n\t// Noise functions\n\tvoid add_gaussian_noise(double stdev);\n\t//void add_gaussian_noise_spd(double stdev);\n\n\t// Random Input functions\n\t// TODO: - Paramaterize for manifold type\n\t//       - Use user-defined functor as parameter\n\tvoid create_nonsmooth_son(const int ny, const int nx);\n\tvoid create_nonsmooth_spd(const int ny, const int nx);\n\n\t// EdgeFunctions\n\tvoid findEdgeWeights();\n\tvoid setEdgeWeights(const weights_mat&);\n\n\t// Inpainting Functions\n\tvoid findInpWeights(const int channel=2);\n\tvoid createRandInpWeights(const double threshold);\n\n\n\t// OutputFunctions\n\tvoid rgb_saveimage(std::string fname);\n\tvoid rgb_show();\n\t\n\tvoid output_weights(const weights_mat& mat, std::string filename) const;\n\t\n\tvoid output_img(std::string filename) const;\n\tvoid output_matval_img(std::string filename) const;\n\tvoid output_nimg(std::string filename) const;\n//    private:\n\t// Data members\n\t// TODO Don't forget to initialize with 1px border\n\t// alignment defaults to 16byte for SSE/SSE2, 32 Byte for AVX\n\tstorage_type img_;\n\tstorage_type noise_img_;\n\tweights_mat edge_weights_;\n\n\tbool inpaint_;\n\tinp_mat inp_; \n};\n\n\n/*----- Implementation 2D Data ------*/\ntemplate < typename MANIFOLD >\nconst int Data<MANIFOLD, 2>::img_dim = 2;\n\ntemplate < typename MANIFOLD >\nvoid Data<MANIFOLD, 2>::setEdgeWeights(const weights_mat& w){\n    edge_weights_= vpp::clone(w);\n}\n\ntemplate < typename MANIFOLD >\nvoid Data<MANIFOLD, 2>::initInp(){\n    inp_ = inp_mat(noise_img_.domain());\n    vpp::fill(inp_, false);\n    inpaint_ = false;\n}\n\ntemplate < typename MANIFOLD >\nvoid Data<MANIFOLD, 2>::initEdgeweights(){\n    edge_weights_ = weights_mat(noise_img_.domain());\n    vpp::fill(edge_weights_, 1.0);\n}\n\n\n// FIXME: This is problematic for greyscale pictures since vuchar3 and vu[i] is hardcoded, works only due to range check of Eigen for []\ntemplate < typename MANIFOLD >\nvoid Data<MANIFOLD, 2>::findEdgeWeights(){\n    #ifdef TV_DATA_DEBUG\n\tstd::cout << \"Find Edges...\" << std::endl;\n    #endif\n    cv::Mat gray, edge;\n    \n    { // Local Scope to save memory\n\tvpp::image2d<vpp::vuchar3> ucharimg(noise_img_.domain());\n\t\n\t// Convert double to uchar function\n\tauto double2uchar = [] (auto& i, const auto& n) {\n\t    value_type v = n * static_cast<typename MANIFOLD::scalar_type>(std::numeric_limits<unsigned char>::max());\n\t    vpp::vuchar3 vu = vpp::vuchar3::Zero();\n\t    vu[0]=static_cast<unsigned char>(v[2]);\n\t    vu[1]=static_cast<unsigned char>(v[1]);\n\t    vu[2]=static_cast<unsigned char>(v[0]);\n\t    i = vu;\n\t}; \n\n\tvpp::pixel_wise(ucharimg, noise_img_) | double2uchar;\n\tcv::Mat src = vpp::to_opencv(ucharimg);\n\tcv::cvtColor(src, gray, CV_BGR2GRAY);\n    }\n\n    cv::blur(gray, edge, cv::Size(3,3));\n    cv::Canny(edge, edge, 50, 150, 3);\n    \n    #ifdef TV_DATA_DEBUG\n\tcv::namedWindow( \"Detected Edges\", cv::WINDOW_NORMAL ); \n\tcv::imshow(\"Detected Edges\", edge);\n\tcv::waitKey(0);\n    #endif\n\n    vpp::image2d<unsigned char> ucharweights = vpp::from_opencv<unsigned char>(edge);\n    vpp::pixel_wise(ucharweights, edge_weights_)() | [] (const unsigned char &uw, weights_type& ew) {\n\tew = 1.0 - 0.99 * ( static_cast<weights_type>(uw) / static_cast<weights_type>(std::numeric_limits<unsigned char>::max()) );\n    };\n\n    #ifdef TV_DATA_DEBUG\n\toutput_weights(edge_weights_, \"wedge.csv\");\n    #endif\n}\n\n//TODO: static assert to avoid data that has not exactly 3 channels\n// static assert that channel is element {1,2,3}\n// make enum RGB out\ntemplate < typename MANIFOLD >\nvoid Data<MANIFOLD, 2>::findInpWeights(const int channel){\n    #ifdef TV_DATA_DEBUG\n\tstd::cout << \"Find Inpainting Area...\" << std::endl;\n    #endif\n    inp_ = inp_mat(noise_img_.domain());\n    vpp::pixel_wise(noise_img_, inp_) | [&] (const value_type& img, inp_type& inp) { inp = static_cast<inp_type>(img[channel-1] > 0.95); };\n    //vpp::pixel_wise(noise_img_, inp_) | [&] (const value_type& img, inp_type& inp) { inp = static_cast<inp_type>(img[channel-1] > 0.95); };\n    #ifdef TV_DATA_DEBUG\n\tint nr = inp_.nrows();\n\tint nc = inp_.ncols();\n\n\tstd::fstream f;\n\tf.open(\"inp.csv\", std::fstream::out);\n\n\tfor (int r=0; r<nr; r++){\n\t    const inp_type* cur = &inp_(r,0);\n\t    for (int c=0; c<nc; c++){\n\t\tf << cur[c];\n\t\tif(c != nc-1) f << \",\";\n\t    }\n\t    f <<  std::endl;\n\t}\n\tf.close();\n    #endif\n}\n\n//TODO: static assert to avoid data that has not exactly 3 channels\n// static assert that channel is element {1,2,3}\n// make enum RGB out\ntemplate < typename MANIFOLD >\nvoid Data<MANIFOLD, 2>::createRandInpWeights(const double threshold){\n    \n    #ifdef TV_DATA_DEBUG\n\tstd::cout << \"Create Random Inp Weights...\" << std::endl;\n    #endif\n\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_real_distribution<> rand(0.0, 1.0);\n \n    inp_ = inp_mat(noise_img_.domain());\n    vpp::pixel_wise(noise_img_, inp_) | [&] (const value_type& img, inp_type& inp) { inp = static_cast<inp_type>(rand(gen) > threshold); };\n    \n    #ifdef TV_DATA_DEBUG\n\tint nr = inp_.nrows();\n\tint nc = inp_.ncols();\n\n\tstd::fstream f;\n\tf.open(\"inp.csv\", std::fstream::out);\n\n\tfor (int r=0; r<nr; r++){\n\t    const inp_type* cur = &inp_(r,0);\n\t    for (int c=0; c<nc; c++){\n\t\tf << cur[c];\n\t\tif(c != nc-1) f << \",\";\n\t    }\n\t    f <<  std::endl;\n\t}\n\tf.close();\n    #endif\n}\n\ntemplate < typename MANIFOLD >\nvoid Data<MANIFOLD, 2>::rgb_imread(std::string filename){\n\tstatic_assert(MANIFOLD::value_dim == 3,\"ERROR: RGB Input requires a Manifold with embedding dimension N=3!\");\n\tvpp::image2d<vpp::vuchar3> input_image;\n\tinput_image = vpp::clone(vpp::from_opencv<vpp::vuchar3 >(cv::imread(filename)));\n\tnoise_img_ = storage_type(input_image.domain());\n\t// Convert Picture of uchar to double \n\t    vpp::pixel_wise(input_image, noise_img_) | [] (auto& i, auto& n) {\n\t    value_type v = value_type::Zero();\n\t    vpp::vuchar3 vu = i;\n\t    // TODO: insert manifold scalar type\n\t    v[0]=static_cast<double>(vu[2]); //opencv saves as BGR\n\t    v[1]=static_cast<double>(vu[1]);\n\t    v[2]=static_cast<double>(vu[0]);\n\t    n = v / static_cast<double>(std::numeric_limits<unsigned char>::max());\n\t};\n    img_ = vpp::clone(noise_img_, vpp::_border = 1);\n\n    initInp();\n    initEdgeweights();\n}\n\ntemplate < typename MANIFOLD >\nvoid Data<MANIFOLD, 2>::rgb_saveimage(std::string fname){\n    static_assert(MANIFOLD::value_dim == 3,\"ERROR: RGB Ouput requires a Manifold with embedding dimension N=3!\");\n\t// Convert Picture of double to uchar\n\tvpp::image2d<vpp::vuchar3> vucharimg(img_.domain());\n\tvpp::pixel_wise(vucharimg, img_) | [] (auto& i, auto& n) {\n\t    value_type v = n * (double) std::numeric_limits<unsigned char>::max();\n\t    vpp::vuchar3 vu = vpp::vuchar3::Zero();\n\t    vu[0]=(unsigned char) v[2];\n\t    vu[1]=(unsigned char) v[1];\n\t    vu[2]=(unsigned char) v[0];\n\t    i = vu;\n\t};\n\n\tcv::imwrite(fname, to_opencv(vucharimg));\n}\n\ntemplate < typename MANIFOLD >\nvoid Data<MANIFOLD, 2>::rgb_show(){\n    static_assert(MANIFOLD::value_dim == 3,\"ERROR: RGB Ouput requires a Manifold with embedding dimension N=3!\");\n\t// Convert Picture of double to uchar\n\tvpp::image2d<vpp::vuchar3> vucharimg(img_.domain());\n\tvpp::pixel_wise(vucharimg, img_) | [] (auto& i, auto& n) {\n\t    value_type v = n * (double) std::numeric_limits<unsigned char>::max();\n\t    vpp::vuchar3 vu = vpp::vuchar3::Zero();\n\t    vu[0]=(unsigned char) v[2];\n\t    vu[1]=(unsigned char) v[1];\n\t    vu[2]=(unsigned char) v[0];\n\t    i = vu;\n\t};\n\tcv::namedWindow(\"Image Viewer\", cv::WINDOW_NORMAL ); \n\tcv::imshow( \"Image Viewer\", vpp::to_opencv(vucharimg));\n\tcv::waitKey(0);\n\n}\n\ntemplate < typename MANIFOLD >\nvoid Data<MANIFOLD, 2>::rgb_readBrightness(std::string filename){\n\tstatic_assert(MANIFOLD::value_dim == 1,\"ERROR: Brightness Input requires a Manifold with embedding dimension N=1!\");\n\tvpp::image2d<vpp::vuchar3> input_image;\n\tinput_image = vpp::clone(vpp::from_opencv<vpp::vuchar3 >(cv::imread(filename)));\n\tnoise_img_ = storage_type(input_image.domain());\n\t// Convert Picture of uchar to double \n\t    vpp::pixel_wise(input_image, noise_img_)(vpp::_no_threads) | [] (auto& i, auto& n) {\n\t    vpp::vdouble3 v; \n\t    vpp::vuchar3 vu = i;\n\t    // TODO: insert manifold scalar type\n\t    v[0]=static_cast<double>(vu[2]); //opencv saves as BGR\n\t    v[1]=static_cast<double>(vu[1]);\n\t    v[2]=static_cast<double>(vu[0]);\n\t    v = v / static_cast<double>(std::numeric_limits<unsigned char>::max());\n\t    n.setConstant(v.norm()/std::sqrt(3));\n\t};\n    img_ = vpp::clone(noise_img_, vpp::_border = 1);\n\n    initInp();\n    initEdgeweights();\n}\n\ntemplate < typename MANIFOLD >\nvoid Data<MANIFOLD, 2>::rgb_readChromaticity(std::string filename){\n\tstatic_assert(MANIFOLD::value_dim == 3,\"ERROR: Chromaticity Input requires a Manifold with embedding dimension N=3!\");\n\tvpp::image2d<vpp::vuchar3> input_image;\n\tinput_image = vpp::clone(vpp::from_opencv<vpp::vuchar3 >(cv::imread(filename)));\n\tnoise_img_ = storage_type(input_image.domain());\n\t// Convert Picture of uchar to double \n\t    vpp::pixel_wise(input_image, noise_img_) | [] (auto& i, auto& n) {\n\t    value_type v; \n\t    // TODO: insert manifold scalar type\n\t    v[0]=static_cast<double>(i[2])+1.0; //opencv saves as BGR\n\t    v[1]=static_cast<double>(i[1])+1.0;\n\t    v[2]=static_cast<double>(i[0])+1.0;\n\t    v = v / (static_cast<double>(std::numeric_limits<unsigned char>::max())+1.0);\n\t    \n\t    double norm = v.norm();\n\t    if(norm!=0)\n\t\tn = v / norm;\n\t    else \n\t\tn = v;\n\n\t    #ifdef TV_DATA_DEBUG\n\t\tif(!std::isfinite(n(0))){\n\t\t    std::cout << \"\\nvuchar pixel \" << i << std::endl;\n\t\t    std::cout << \"double pixel \" << v << std::endl; \n\t\t    std::cout << \"normalized pixel \" << n << std::endl; \n\t\t}\n\t    #endif\n\t};\n    img_ = vpp::clone(noise_img_, vpp::_border = 1);\n    \n    initInp();\n    initEdgeweights();\n}\n\n\ntemplate <typename MANIFOLD>\nvoid Data<MANIFOLD, 2>::readMatrixDataFromCSV(std::string filename, const int nx, const int ny){\n    #ifdef TV_DATA_DEBUG\n\tstd::cout << \"ReadMatrixData from CSV File...\" << std::endl;\n    #endif\n    noise_img_ = storage_type(ny, nx);\n    vpp::fill(noise_img_, MANIFOLD::value_type::Zero());\n\n    const int N = MANIFOLD::value_type::RowsAtCompileTime; \n    const int N2 = MANIFOLD::value_dim;\n    int cols, rows = 0;\n\n    std::ifstream infile(filename, std::ifstream::in);\n    \n    std::string line = \"\";\n    while (std::getline(infile, line)){\n\tstd::stringstream strstr(line);\n\tstd::string word = \"\";\n\t\n\tif(cols == 0)\n\t    while (std::getline(strstr, word, ','))\n\t\tcols++;\n\t\n\trows++;\n    }\n\n    assert(N2==cols);\n    assert(nx*ny==rows);\n    \n    infile.clear();\n    infile.seekg(0, std::ios_base::beg);\n    \n    Eigen::Matrix<typename MANIFOLD::scalar_type, N2, 1> vectorizedMat;\n    vectorizedMat.setZero();\n\n    auto it = noise_img_.begin();\n    while (std::getline(infile, line)){\n\tstd::stringstream strstr(line);\n\tstd::string word = \"\";\n\tint j=0;\n\twhile (std::getline(strstr, word,',')){\n\t    typename MANIFOLD::scalar_type entry= static_cast<typename MANIFOLD::scalar_type>(std::stod(word));\n\t    vectorizedMat(j) = entry;\n\t    ++j;\n\t}\n\t*it = Eigen::Map<typename MANIFOLD::value_type>(vectorizedMat.data());\n\tit.next();\n    }\n    img_ = vpp::clone(noise_img_, vpp::_border = 1);\n    fill_border_closest(img_);\n\n    initInp();\n    initEdgeweights();\n}\n\n\ntemplate <typename MANIFOLD>\nvoid Data<MANIFOLD, 2>::add_gaussian_noise(double stdev){\n\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::normal_distribution<typename MANIFOLD::scalar_type> rand(0.0, stdev);\n\n    auto generate = [&] (typename MANIFOLD::scalar_type entry){\n\treturn entry + rand(gen);\n    };\n    \n\tif(MANIFOLD::non_isometric_embedding)\n\t    vpp::pixel_wise(noise_img_) | [&] (value_type& i){ MANIFOLD::interpolation_preprocessing(i); };\n\n    vpp::pixel_wise(noise_img_) | [&] (value_type& i) { i = i.unaryExpr(generate); }; \n\n\tif(MANIFOLD::non_isometric_embedding)\n\t    vpp::pixel_wise(noise_img_) | [&] (value_type& i){ MANIFOLD::interpolation_postprocessing(i); };\n\n    vpp::pixel_wise(noise_img_) | [&] (value_type& i) { MANIFOLD::projector(i); };\n\n    img_ = vpp::clone(noise_img_, vpp::_border = 1);\n    fill_border_closest(img_);\n}\n\n/*\n//TODO: Generalize implementation to be compatible with add_gaussian_noise\ntemplate <typename MANIFOLD>\nvoid Data<MANIFOLD, 2>::add_gaussian_noise_spd(double stdev){\n\n    static_assert(MANIFOLD::MyType==SPD,\"add_gaussian_noise_spd is implemented only for SPD(N)!\");\n    \n    vpp::pixel_wise(noise_img_) | [&] (value_type& i){ MANIFOLD::interpolation_preprocessing(i); };\n\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::normal_distribution<scalar_type> rand(0.0, stdev);\n\n    auto generate = [&] (scalar_type entry){\n\treturn rand(gen);\n    };\n\n    vpp::pixel_wise(noise_img_) | [&] (value_type& i) { \n\tvalue_type r = value_type::Zero().unaryExpr(generate);\n\ti = i + (r + r.transpose()) * 0.5; \n    }; \n\n    vpp::pixel_wise(noise_img_) | [&] (value_type& i){ MANIFOLD::interpolation_postprocessing(i); };\n\n    img_ = vpp::clone(noise_img_, vpp::_border = 1);\n}\n*/\n\n\n// TODO: Generalize to general N\ntemplate <typename MANIFOLD>\nvoid Data<MANIFOLD, 2>::create_nonsmooth_son(const int ny,const int nx){\n    #ifdef TV_DATA_DEBUG\n\tstd::cout << \"Create Nonsmooth SO(3) Picture...\" << std::endl;\n    #endif\n\n    const int N = MANIFOLD::value_type::RowsAtCompileTime; \n\n    static_assert(MANIFOLD::MyType==SO, \"ERROR: Only possible for SO(N) manifolds\");\n    static_assert(N==3, \"ERROR: Only possible for SO(3) manifolds\");\n    \n    noise_img_ = storage_type(ny, nx);\n\n    auto son_inserter = [&] (typename MANIFOLD::value_type& v, const vpp::vint2& coord){\n\n\ttypename MANIFOLD::scalar_type x = coord(1)*1.0 / nx;\n\ttypename MANIFOLD::scalar_type y = coord(0)*1.0 / ny;\n\tEigen::Matrix<typename MANIFOLD::scalar_type, N, 1> rotation_axis;\n\tif(x > 0.5)\n\t    rotation_axis << 2.0 * x, y, 0.0;\n\telse\n\t    rotation_axis << 0.0, 2.0 * x, 0.5;\n\t\n\ttypename MANIFOLD::scalar_type alpha;\n\tif(x > y)\n\t    alpha = x + y;\n\telse\n\t    alpha = M_PI * 0.5 + x - y;\n\t\n\t//v = MANIFOLD::value_type::Identity();\n\tv = Eigen::AngleAxis<typename MANIFOLD::scalar_type>(alpha, rotation_axis.normalized());\n    };\n\n    vpp::pixel_wise(noise_img_, noise_img_.domain()) | son_inserter;\n    img_ = vpp::clone(noise_img_, vpp::_border = 1);\n    fill_border_closest(img_);\n\n    initInp();\n    initEdgeweights();\n}\n\n// TODO: Generalize to general N\ntemplate <typename MANIFOLD>\nvoid Data<MANIFOLD, 2>::create_nonsmooth_spd(const int ny,const int nx){\n    #ifdef TV_DATA_DEBUG\n\tstd::cout << \"Create Nonsmooth SPD(3) Picture...\" << std::endl;\n    #endif\n\n    const int N = MANIFOLD::value_type::RowsAtCompileTime; \n\n    static_assert(MANIFOLD::MyType==SPD, \"ERROR: Only possible for SPD(N) manifolds\");\n    static_assert(N==3, \"ERROR: Only possible for SPD(3) manifolds\");\n    \n    noise_img_ = storage_type(ny, nx);\n\n    auto spd_inserter = [&] (typename MANIFOLD::value_type& v, const vpp::vint2& coord){\n\n\ttypename MANIFOLD::scalar_type x = 1.0 * coord(1) / nx;\n\ttypename MANIFOLD::scalar_type y = 1.0 * coord(0) / ny;\n\t\n\tEigen::Matrix<typename MANIFOLD::scalar_type, N, N> R;\n\tEigen::DiagonalMatrix< typename MANIFOLD::scalar_type, N> D(N);\n\tEigen::Matrix<typename MANIFOLD::scalar_type, N, 1> rotation_axis;\n\ttypename MANIFOLD::scalar_type alpha;\n\n\tif(x + y < 1.0){\n\t    rotation_axis << x, y, 2.0;\n\t    alpha = x + 2.0 * y;\n\t}\n\telse{\n\t    rotation_axis << y, -x, 1.0;\n\t    alpha = y + 2.0 * x;\n\t}\n\t\n\tD.diagonal() << x + 0.2, y + 0.2, 0.5;\n\tR  = Eigen::AngleAxis<typename MANIFOLD::scalar_type>(alpha, rotation_axis.normalized());\n\tv = R.transpose() * D * R;\n    };\n\n    vpp::pixel_wise(noise_img_, noise_img_.domain()) | spd_inserter;\n    img_ = vpp::clone(noise_img_, vpp::_border = 1);\n    fill_border_closest(img_);\n\n    initInp();\n    initEdgeweights();\n}\n\n\ntemplate < typename MANIFOLD >\nvoid Data<MANIFOLD, 2>::output_weights(const weights_mat& weights, std::string filename) const{\n    int nr = weights.nrows();\n    int nc = weights.ncols();\n\n    std::fstream f;\n    f.open(filename, std::fstream::out);\n\n    for (int r=0; r<nr; r++){\n\tconst typename Data<MANIFOLD,2>::weights_type* cur = &weights(r,0);\n\tfor (int c=0; c<nc; c++){\n\t    f << cur[c];\n\t    if(c != nc-1) f << \",\";\n\t}\n\tf <<  std::endl;\n    }\n    f.close();\n}\n\ntemplate < typename MANIFOLD >\nvoid Data<MANIFOLD, 2>::output_matval_img(std::string 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}\ntemplate < typename MANIFOLD >\nvoid Data<MANIFOLD, 2>::output_img(std::string 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 < typename MANIFOLD >\nvoid Data<MANIFOLD, 2>::output_nimg(std::string filename) const{\n    int nr = noise_img_.nrows();\n    int nc = noise_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 = &noise_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\n}// end namespace tvmtl\n\n#endif\n", "meta": {"hexsha": "286601dcbe1b898c5509359542a0107f1306c6c0", "size": 19127, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mtvmtl/core/data2d.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/data2d.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/data2d.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": 30.1687697161, "max_line_length": 141, "alphanum_fraction": 0.6581272547, "num_tokens": 5784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032313, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.28569517816586554}}
{"text": "/*\n Copyright (C) 2017 Quaternion Risk Management Ltd\n Copyright (C) 2017 Aareal Bank AG\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/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/termstructures/credit/flathazardrate.hpp>\n#include <ql/termstructures/yield/zerospreadedtermstructure.hpp>\n#include <qle/pricingengines/discountingriskybondengine.hpp>\n\nusing namespace std;\nusing namespace QuantLib;\n\nnamespace QuantExt {\n\nDiscountingRiskyBondEngine::DiscountingRiskyBondEngine(const Handle<YieldTermStructure>& discountCurve,\n                                                       const Handle<DefaultProbabilityTermStructure>& defaultCurve,\n                                                       const Handle<Quote>& recoveryRate,\n                                                       const Handle<Quote>& securitySpread, Period timestepPeriod,\n                                                       boost::optional<bool> includeSettlementDateFlows)\n    : defaultCurve_(defaultCurve), recoveryRate_(recoveryRate), securitySpread_(securitySpread),\n      timestepPeriod_(timestepPeriod), includeSettlementDateFlows_(includeSettlementDateFlows) {\n    discountCurve_ =\n        securitySpread_.empty()\n            ? discountCurve\n            : Handle<YieldTermStructure>(boost::make_shared<ZeroSpreadedTermStructure>(discountCurve, securitySpread));\n    registerWith(discountCurve_);\n    registerWith(defaultCurve_);\n    registerWith(recoveryRate_);\n    registerWith(securitySpread_);\n}\n\nDiscountingRiskyBondEngine::DiscountingRiskyBondEngine(const Handle<YieldTermStructure>& discountCurve,\n                                                       const Handle<Quote>& securitySpread, Period timestepPeriod,\n                                                       boost::optional<bool> includeSettlementDateFlows)\n    : securitySpread_(securitySpread), timestepPeriod_(timestepPeriod),\n      includeSettlementDateFlows_(includeSettlementDateFlows) {\n    discountCurve_ =\n        securitySpread_.empty()\n            ? discountCurve\n            : Handle<YieldTermStructure>(boost::make_shared<ZeroSpreadedTermStructure>(discountCurve, securitySpread));\n    registerWith(discountCurve_);\n    registerWith(securitySpread_);\n}\n\nvoid DiscountingRiskyBondEngine::calculate() const {\n    QL_REQUIRE(!discountCurve_.empty(), \"discounting term structure handle is empty\");\n\n    results_.valuationDate = (*discountCurve_)->referenceDate();\n    results_.value = calculateNpv(results_.valuationDate, arguments_.cashflows);\n\n    bool includeRefDateFlows =\n        includeSettlementDateFlows_ ? *includeSettlementDateFlows_ : Settings::instance().includeReferenceDateEvents();\n    // a bond's cashflow on settlement date is never taken into\n    // account, so we might have to play it safe and recalculate\n    // same parameters as above, we can avoid another call\n    if (!includeRefDateFlows && results_.valuationDate == arguments_.settlementDate) {\n        results_.settlementValue = results_.value;\n    } else {\n        // no such luck\n        results_.settlementValue = calculateNpv(arguments_.settlementDate, arguments_.cashflows);\n    }\n}\n\nReal DiscountingRiskyBondEngine::calculateNpv(Date npvDate, const Leg& cashflows,\n                                              const Handle<YieldTermStructure>& incomeCurve,\n                                              const bool conditionalOnSurvival) const {\n    Real npvValue = 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        defaultCurve_.empty()\n            ? boost::make_shared<QuantLib::FlatHazardRate>(results_.valuationDate, 0.0, discountCurve_->dayCounter())\n            : defaultCurve_.currentLink();\n    Rate recoveryVal = recoveryRate_.empty() ? 0.0 : recoveryRate_->value();\n\n    // compounding factors for npv date\n    Real dfSettl = incomeCurve.empty() ? discountCurve_->discount(npvDate) : incomeCurve->discount(npvDate);\n    Real spSettl = conditionalOnSurvival ? creditCurvePtr->survivalProbability(npvDate) : 1.0;\n\n    Size numCoupons = 0;\n    bool hasLiveCashFlow = false;\n    for (Size i = 0; i < cashflows.size(); i++) {\n        boost::shared_ptr<CashFlow> cf = cashflows[i];\n        if (cf->hasOccurred(npvDate, includeSettlementDateFlows_))\n            continue;\n        hasLiveCashFlow = true;\n\n        // Coupon value is discounted future payment times the survival probability\n        Probability S = creditCurvePtr->survivalProbability(cf->date()) / spSettl;\n        npvValue += cf->amount() * S * discountCurve_->discount(cf->date()) / dfSettl;\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>(cf);\n        if (coupon) {\n            numCoupons++;\n            Date startDate = coupon->accrualStartDate();\n            Date endDate = coupon->accrualEndDate();\n            Date effectiveStartDate = (startDate <= npvDate && npvDate <= endDate) ? npvDate : startDate;\n            Date defaultDate = effectiveStartDate + (endDate - effectiveStartDate) / 2;\n            Probability P = creditCurvePtr->defaultProbability(effectiveStartDate, endDate) / spSettl;\n\n            npvValue += coupon->nominal() * recoveryVal * P * discountCurve_->discount(defaultDate) / dfSettl;\n        }\n    }\n\n    // the ql instrument might not yet be expired and still have not anything to value if\n    // the npvDate > evaluation date\n    if (!hasLiveCashFlow)\n        return 0.0;\n\n    if (cashflows.size() > 1 && numCoupons == 0) {\n        QL_FAIL(\"DiscountingRiskyBondEngine does not support bonds with multiple cashflows but no coupons\");\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 (cashflows.size() == 1) {\n        boost::shared_ptr<Redemption> redemption = boost::dynamic_pointer_cast<Redemption>(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) / spSettl;\n\n                npvValue += redemption->amount() * recoveryVal * P * discountCurve_->discount(defaultDate) / dfSettl;\n                startDate = stepDate;\n            }\n        }\n    }\n\n    return npvValue;\n}\n} // namespace QuantExt\n", "meta": {"hexsha": "cb431eff09e506a00f5f0fb728a9cbfb4f014fee", "size": 8085, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/pricingengines/discountingriskybondengine.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/discountingriskybondengine.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/discountingriskybondengine.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": 49.6012269939, "max_line_length": 119, "alphanum_fraction": 0.6837353123, "num_tokens": 1754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2855136759739083}}
{"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 <cmath>\n#include <Eigen/Geometry>\n#include <boost/format.hpp>\n#include <comma/base/exception.h>\n#include <comma/math/compare.h>\n#include \"../angle.h\"\n#include \"coordinates.h\"\n#include <iomanip>\n\nnamespace {\n\n    static const double eighty_degrees = 80 * M_PI / 180.0;\n\n    static const double scaled_cos_eighty_degrees = 2.0 / M_PI * std::cos( eighty_degrees );\n\n    bool precise_is_far( const snark::spherical::coordinates & l, const snark::spherical::coordinates & r, double _epsilon )\n    {\n        return Eigen::AngleAxis< double >( Eigen::Quaternion< double >::FromTwoVectors( l.to_cartesian(), r.to_cartesian() ) ).angle() > _epsilon;\n    }\n\n    bool is_far( const snark::spherical::coordinates & l, const snark::spherical::coordinates & r, double _epsilon )\n    {\n        // for very short arcs skip shortcuts and enforce thorough comparison because of numerical stability issues in Eigen\n        // the actual value is about 6 m / earth radius; enough to make AngleAxis::angle() non-zero\n        double threshold = std::max( snark::spherical::coordinates::epsilon, _epsilon );\n        // make quick decisions first; for latitude shortcut no explanations needed\n        if ( std::abs( l.latitude - r.latitude ) > threshold ) { return true; }\n        double delta_longitude = std::abs( l.longitude - r.longitude );\n        // nearly 360 delta means very close; take the shorter of the two possible arcs\n        delta_longitude = delta_longitude > M_PI ? 2 * M_PI - delta_longitude : delta_longitude;\n        // longitude shortcut:\n        //     ignore near-Pole regions\n        //     take a lower limit on great circle arc length:\n        //         the arc at the higher (by modulo) of the two latitudes is shorter than the real arc (lower estimate)\n        //             proof not given here; differentiate the exact expression by one of the latitudes; the derivative sign is\n        //             defined by the other latitude: negative in the Northern hemisphere, positive in the Southern; therefore,\n        //             if the fixed latitude (not the one being differentiated upon) is chosen as the max by modulo, the function\n        //             may only increase as the other latitude moves either South or North, respectively\n        //         for the same latitudes, use the lower estimate of the great circle arc length:\n        //             exact length = 2 * asin( cos(latitude) * sin( delta_longitude / 2 ) )\n        //             estimates: asin(x) >= x for any x in [0, 1]\n        //                        sin(y) >= 2/pi * y for any y in [0, pi/2]\n        //             thus exact length >= 2 cos(latitude) * sin( delta_longitude / 2 ) >= cos(latitude) * 2/pi * delta_longitude >= cos(80 degrees) * 2/pi * delta_longitude\n        //     if the lower limit is above the threshold, the real arc length is above the threshold as well\n        double max_latitude = std::max( std::abs( l.latitude ), std::abs( r.latitude ) );\n        if ( max_latitude < eighty_degrees && delta_longitude * scaled_cos_eighty_degrees > threshold ) { return true; }\n        // shortcuts failed, do lengthy computations\n        return precise_is_far( l, r, threshold );\n    }\n}\n\nnamespace snark { namespace spherical {\n\nconst double coordinates::epsilon = 1e-6;\n\nbool coordinates::operator==( const coordinates& rhs ) const\n{\n    return !is_far( *this, rhs, epsilon );\n}\n\nbool coordinates::is_near( const coordinates& c, double epsilon ) const\n{\n    return !is_far( *this, c, epsilon );\n}\n\nbool coordinates::is_near( const coordinates & l, const coordinates & r, double _epsilon )\n{\n    return !is_far( l, r, _epsilon );\n}\n\n/// limits longitude to [-PI, PI)\nstatic double limit( const double longitude )\n{\n    // todo: this is just a quick patch, not a real fix; what if longitude equals e.g. -3*M_PI?\n    // todo: seriously quick and dirty, to fix anti merridian crossing\n    return longitude < -M_PI ? longitude + 2 * M_PI : longitude >= M_PI ? longitude - 2 * M_PI : longitude;\n}\n\ncoordinates::coordinates( const double latitude, const double longitude ) : latitude( latitude ), longitude( limit( longitude ) )\n{\n}\n\ncoordinates::coordinates( const snark::bearing_elevation& be ) : latitude( be.elevation() ), longitude( limit( be.bearing() ) )\n{\n}\n\ncoordinates::coordinates( const Eigen::Vector3d& xyz )\n{\n    snark::range_bearing_elevation rbe( xyz );\n    latitude = rbe.elevation();\n    longitude = limit( rbe.bearing() );\n}\n\nEigen::Vector3d to_navigation_frame( const coordinates& c, const Eigen::Vector3d& v )\n{\n    const Eigen::Matrix3d& r1 = Eigen::AngleAxis< double >( -c.longitude, Eigen::Vector3d( 0, 0, 1 ) ).toRotationMatrix();\n    const Eigen::Matrix3d& r2 = Eigen::AngleAxis< double >( c.latitude + M_PI / 2, Eigen::Vector3d( 0, 1, 0 ) ).toRotationMatrix();\n    return r2 * r1 * v;\n}\n\ncoordinates& coordinates::operator+=( const coordinates& rhs )\n{\n    double d = latitude + rhs.latitude;\n    static const double epsilon = 0.00005;\n    if( comma::math::equal( d, M_PI / 2, epsilon ) ) { d = M_PI / 2; }\n    else if( comma::math::equal( d, -M_PI / 2, epsilon ) ) { d = -M_PI / 2; }\n    else if( d > M_PI / 2 || d < -M_PI / 2 ) { COMMA_THROW( comma::exception, \"adding \" << ( latitude * 180 / M_PI ) << \" and \" << ( rhs.latitude * 180 / M_PI ) << \" gives invalid latitude of \" << ( d * 180 / M_PI ) << \" degress\" ); }\n    latitude = d;\n    longitude += rhs.longitude;\n    while( longitude < -M_PI ) { longitude += 2 * M_PI; } // brutal, but mod() is slower in most cases, i think\n    while( this->longitude >= M_PI ) { longitude -= 2 * M_PI; } // brutal, but mod() is slower in most cases, i think\n    return *this;\n}\n\ncoordinates::operator std::string() const\n{\n    const std::pair< double, double >& c = to_degrees();\n    return (boost::format(\"%.2f\") % c.first ).str() + \",\" + (boost::format(\"%.2f\") % c.second).str();\n}\n\nbool coordinates::is_near( const Eigen::Vector3d& c, double _epsilon ) const\n{\n    return ( to_cartesian() - c ).lpNorm<Eigen::Infinity>() < _epsilon;\n}\n\ncoordinates coordinates::from_degrees(double latitude, double longitude)\n{\n    return coordinates( snark::math::radians( snark::math::degrees( latitude ) ).value,\n                        snark::math::radians( snark::math::degrees( longitude ) ).value );\n}\n\nstd::pair< double, double > coordinates::to_degrees() const\n{\n    return std::make_pair( snark::math::degrees( snark::math::radians( latitude ) ).value\n                         , snark::math::degrees( snark::math::radians( longitude ) ).value );\n}\n\n} } // namespace snark { namespace spherical {\n", "meta": {"hexsha": "420704b5022ac2f9793a821832b3ba0ddd5cdc05", "size": 8333, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math/spherical_geometry/coordinates.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": 63.0, "max_stars_repo_stars_event_min_datetime": "2015-01-14T14:38:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T09:56:03.000Z", "max_issues_repo_path": "math/spherical_geometry/coordinates.cpp", "max_issues_repo_name": "NEU-LC/snark", "max_issues_repo_head_hexsha": "db890f73f4c4bbe679405f3a607fd9ea373deb2c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 39.0, "max_issues_repo_issues_event_min_datetime": "2015-01-21T00:57:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-22T04:22:35.000Z", "max_forks_repo_path": "math/spherical_geometry/coordinates.cpp", "max_forks_repo_name": "NEU-LC/snark", "max_forks_repo_head_hexsha": "db890f73f4c4bbe679405f3a607fd9ea373deb2c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 36.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T04:17:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T17:13:35.000Z", "avg_line_length": 49.6011904762, "max_line_length": 234, "alphanum_fraction": 0.6744269771, "num_tokens": 2041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.28546859880733916}}
{"text": "/**\n * @file      MeshFitterImpl.cpp\n *\n * @brief     Implementation file for MeshFitter::Impl\n *\n * @author    Stefan Reinhold\n * @copyright Copyright (C) 2018 Stefan Reinhold  -- All Rights Reserved.\n *            You may use, distribute and modify this code under the terms of\n *            the AFL 3.0 license; see LICENSE for full license details.\n */\n\n#include \"MeshFitterImpl.h\"\n\n#include \"CommonMath.h\"\n#include \"DiscreteRangeDecorators.h\"\n#include \"DisplacementOptimizer.h\"\n#include \"EigenAdaptors.h\"\n#include \"MeshAdaptors.h\"\n#include \"MeshFitterHiddenState.h\"\n#include \"MeshHelpers.h\"\n#include \"Sampler.h\"\n#include \"WeightedARAPFitter.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <gsl/gsl>\n\nnamespace CortidQCT {\n\nusing namespace Internal;\n\n/**********************\n * Helper Functions\n */\n\n// MARK: -\n// MARK: Helper Function\n\n/**\n * @brief Returns a matrix containing positions to sample a voxel volume at\n *\n * Let \\f$N := |V|\\f$ and let \\f$M := |R|\\f$, where \\f$R\\f$ represent\n * `model.samplingRange`, then the returned NMx3 matrix contains N*M positions,\n * where each M consecutive postitions represent a line through a vertex in `V`\n * sampled along the surface normal in `N`.\n *\n * @param V Nx3 matrix with vertex positions\n * @param N Nx3 matrix of per-vertex surface normals\n * @param model MeasurementModel instance\n * @return NMx3 matrix containing sampling positions\n */\ntemplate <class DerivedV, class DerivedN>\nEigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 3>\nsamplingPoints(Eigen::MatrixBase<DerivedV> const &V,\n               Eigen::MatrixBase<DerivedN> const &N,\n               MeasurementModel const &model) {\n  using Scalar = typename DerivedV::Scalar;\n  using Eigen::Dynamic;\n  using Eigen::Index;\n  using Eigen::Matrix;\n  using gsl::narrow_cast;\n\n  auto const t = Internal::discreteRangeElementVector(model.samplingRange);\n  Matrix<Scalar, Dynamic, 3> samples(V.rows() * t.rows(), 3);\n\n  for (auto i = 0; i < V.rows(); ++i) {\n    auto const iStart = i * t.rows();\n    samples.block(iStart, 0, t.rows(), 3).colwise() = -t;\n    samples.block(iStart, 0, t.rows(), 3).array().rowwise() *= N.row(i).array();\n    samples.block(iStart, 0, t.rows(), 3).rowwise() += V.row(i);\n  }\n\n  return samples;\n}\n\n/***********************************\n * MeshFitter::Impl Implementation\n */\n\n// MARK: -\n// MARK: MeshFitter::Impl Implementation\n\nMeshFitter::Result MeshFitter::Impl::fit(VoxelVolume const &volume) const {\n\n  auto state = init(volume);\n\n  VertexMatrix<float> Vlast =\n      Adaptor::vertexMap(state.deformedMesh).transpose();\n\n  while (!state.converged) {\n\n    fitOneIteration(state);\n\n    auto V = Adaptor::vertexMap(state.deformedMesh);\n\n    auto const diff = (V.transpose() - Vlast).norm() / V.norm();\n    Vlast = V.transpose();\n\n    auto disNorm = Adaptor::map(state.displacementVector).norm() /\n                   static_cast<float>(state.displacementVector.size());\n\n    std::cout << \"Converged after iteration \" << state.iteration << \": \"\n              << std::boolalpha << state.converged << \" (\" << diff << \" | \"\n              << disNorm << \" | \" << state.nonDecreasing << \")\" << std::endl;\n  }\n\n  state.success = true;\n\n  return std::move(state);\n}\n\nMeshFitter::State MeshFitter::Impl::init(VoxelVolume const &volume) const {\n  using Eigen::Dynamic;\n  using Eigen::Index;\n  using Eigen::Map;\n  using Eigen::Matrix;\n  using Eigen::MatrixXf;\n  using Eigen::Vector3f;\n  using Eigen::VectorXf;\n  using gsl::narrow_cast;\n\n  MeshFitter::State state;\n\n  auto const &conf = fitter_.configuration;\n  // auto const &model = fitter_.configuration.model;\n\n  // Init result state\n  state.referenceMesh = conf.referenceMesh;\n\n  auto const nVertices = narrow_cast<Index>(conf.referenceMesh.vertexCount());\n\n  // Apply initial transofrmation on the vertices of the reference mesh\n  auto const translation = Adaptor::vec(conf.meshTranslation(volume));\n  Vector3f const rotInRad = Adaptor::vec(conf.referenceMeshRotation) *\n                            static_cast<float>(M_PI) / 180.f;\n  auto V0 = Adaptor::vertexMap(state.referenceMesh);\n\n  // Apply transformation to vertices of reference mesh\n  V0 = ((Eigen::Translation<float, 3>{translation} *\n         Eigen::AngleAxisf(rotInRad[0], Vector3f::UnitX()) *\n         Eigen::AngleAxisf(rotInRad[1], Vector3f::UnitY()) *\n         Eigen::AngleAxisf(rotInRad[2], Vector3f::UnitZ())) *\n        Adaptor::vec(conf.referenceMeshScale).asDiagonal() * V0);\n\n  // Init vertex normals\n  state.referenceMesh.updatePerVertexNormals();\n  // This will be removed in versino 2.0:\n  state.vertexNormals.resize(narrow_cast<std::size_t>(nVertices));\n  Adaptor::map(state.vertexNormals) =\n      Adaptor::vertexNormalMap(state.referenceMesh);\n\n  // Init deformed mesh with reference mesh\n  state.deformedMesh = state.referenceMesh;\n\n  // Init displacement vector\n  state.displacementVector =\n      std::vector<float>(narrow_cast<std::size_t>(nVertices), .0f);\n\n  // Init weight vector\n  state.weights = std::vector<float>(narrow_cast<std::size_t>(nVertices),\n                                     1 / static_cast<float>(nVertices));\n\n  // Init vertex normals\n  state.vertexNormals.resize(narrow_cast<std::size_t>(nVertices));\n\n  // Init hidden state\n  state.hiddenState_ = std::make_unique<State::HiddenState>(\n      volume, DisplacementOptimizer{conf},\n      WeightedARAPFitter<float>{V0.transpose(), facetMatrix(conf.referenceMesh),\n                                narrow_cast<float>(conf.sigmaE)},\n      facetMatrix(conf.referenceMesh));\n\n  // Init volume sampling positions\n  auto const nSamples = conf.model.samplingRange.numElements() *\n                        narrow_cast<std::size_t>(nVertices);\n  state.volumeSamplingPositions.resize(nSamples);\n\n  // Init volume samples\n  state.volumeSamples.resize(nSamples);\n\n  sampleVolume(state);\n\n  return state;\n} // namespace CortidQCT\n\nvoid MeshFitter::Impl::fitOneIteration(MeshFitter::State &state) const {\n\n  if (state.hiddenState_ == nullptr) {\n    throw std::invalid_argument(\"Invalid state argument, call init() first!\");\n  }\n\n  findOptimalDisplacements(state);\n  findOptimalDeformation(state);\n  sampleVolume(state);\n  computeLogLikelihood(state);\n  checkConvergence(state);\n\n  ++state.iteration;\n}\n\nvoid MeshFitter::Impl::findOptimalDisplacements(\n    MeshFitter::State &state) const {\n  if (state.hiddenState_ == nullptr) {\n    throw std::invalid_argument(\"Invalid state argument, call init() first!\");\n  }\n\n  // Get maps to state variables\n  auto const labels = Adaptor::labelMap(state.referenceMesh);\n  auto const N = Adaptor::vertexNormalMap(state.deformedMesh);\n  auto const volumeSamples = Adaptor::map(state.volumeSamples);\n  auto optimalDisplacements = Adaptor::map(state.displacementVector);\n  auto gamma = Adaptor::map(state.weights);\n\n  // Find optimal displacements\n  std::tie(optimalDisplacements, gamma) =\n      state.hiddenState_->displacementOptimizer(\n          N.transpose(), labels, volumeSamples, state.nonDecreasing,\n          state.effectiveSigmaS);\n}\n\nvoid MeshFitter::Impl::findOptimalDeformation(MeshFitter::State &state) const {\n  if (state.hiddenState_ == nullptr) {\n    throw std::invalid_argument(\"Invalid state argument, call init() first!\");\n  }\n\n  auto const N = Adaptor::vertexNormalMap(state.deformedMesh);\n  auto const optimalDisplacements = Adaptor::map(state.displacementVector);\n  auto const gamma = Adaptor::map(state.weights);\n  auto V = Adaptor::vertexMap(state.deformedMesh);\n\n  VertexMatrix<> const Y =\n      (V - (N.array().rowwise() * optimalDisplacements.array().transpose())\n               .matrix())\n          .transpose();\n\n  // Fit mesh\n  V = state.hiddenState_->meshFitter.fit(Y, N.transpose(), gamma).transpose();\n  // Update normals\n  state.deformedMesh.updatePerVertexNormals();\n  // This will be removed in v2.0:\n  Adaptor::map(state.vertexNormals) =\n      Adaptor::vertexNormalMap(state.deformedMesh);\n}\n\nvoid MeshFitter::Impl::sampleVolume(MeshFitter::State &state) const {\n\n  using Eigen::Map;\n  using Eigen::MatrixXf;\n  using Eigen::VectorXf;\n\n  if (state.hiddenState_ == nullptr) {\n    throw std::invalid_argument(\"Invalid state argument, call init() first!\");\n  }\n\n  auto const &conf = fitter_.configuration;\n  auto const V = Adaptor::vertexMap(state.deformedMesh);\n  auto const nVertices = V.cols();\n  auto N = Adaptor::vertexNormalMap(state.deformedMesh);\n  auto volumeSamplingPositions = Adaptor::map(state.volumeSamplingPositions);\n  auto volumeSamples = Adaptor::map(state.volumeSamples);\n\n  // Copmute new sampling positions\n  volumeSamplingPositions =\n      samplingPoints(V.transpose(), N.transpose(), conf.model).transpose();\n\n  // Sample the volume\n  auto const volumeSampler = VolumeSampler{\n      state.hiddenState_->volume, conf.ignoreExteriorSamples\n                                      ? std::numeric_limits<float>::quiet_NaN()\n                                      : 0.f};\n  volumeSampler(volumeSamplingPositions.transpose(), volumeSamples,\n                fitter_.configuration.calibrationSlope,\n                fitter_.configuration.calibrationIntercept);\n\n  // Reorder samples\n  state.hiddenState_->volumeSamplesMatrix =\n      Map<MatrixXf const>{volumeSamples.data(),\n                          volumeSamples.rows() / nVertices, nVertices}\n          .transpose();\n\n  volumeSamples = Map<VectorXf const>{\n      state.hiddenState_->volumeSamplesMatrix.data(), volumeSamples.rows()};\n}\n\nvoid MeshFitter::Impl::computeLogLikelihood(MeshFitter::State &state) const {\n  using Eigen::Map;\n  using Eigen::VectorXf;\n  using gsl::narrow_cast;\n\n  if (state.hiddenState_ == nullptr) {\n    throw std::invalid_argument(\"Invalid state argument, call init() first!\");\n  }\n\n  auto const labels = Adaptor::labelMap(state.referenceMesh);\n  auto const N = Adaptor::vertexNormalMap(state.deformedMesh);\n  auto const volumeSamples = Adaptor::map(state.volumeSamples);\n\n  auto const llVec =\n      state.hiddenState_->displacementOptimizer.logLikelihoodVector(\n          N.transpose(), labels, volumeSamples);\n  auto const LL = llVec.sum();\n\n  state.logLikelihood = LL;\n  state.perVertexLogLikelihood.resize(narrow_cast<std::size_t>(llVec.size()));\n\n  Map<VectorXf>{state.perVertexLogLikelihood.data(), llVec.rows(), 1} = llVec;\n}\n\nvoid MeshFitter::Impl::checkConvergence(MeshFitter::State &state) const {\n  if (state.hiddenState_ == nullptr) {\n    throw std::invalid_argument(\"Invalid state argument, call init() first!\");\n  }\n\n  auto const optimalDisplacements = Adaptor::map(state.displacementVector);\n  auto const &conf = fitter_.configuration;\n\n  state.converged = state.iteration >= conf.maxIterations ||\n                    (optimalDisplacements.norm() < 1e-3f);\n\n  auto disNorm = optimalDisplacements.norm() / optimalDisplacements.rows();\n  if (disNorm < state.minDisNorm) {\n    state.minDisNorm = disNorm;\n    state.nonDecreasing = 0;\n  } else {\n    ++state.nonDecreasing;\n  }\n}\n\n} // namespace CortidQCT\n", "meta": {"hexsha": "308ac76b2e9aa186b26d4542d5dc24fce456bc57", "size": 10904, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/MeshFitterImpl.cpp", "max_stars_repo_name": "ithron/CortidQCT", "max_stars_repo_head_hexsha": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-21T17:30:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-21T17:30:23.000Z", "max_issues_repo_path": "lib/MeshFitterImpl.cpp", "max_issues_repo_name": "ithron/CortidQCT", "max_issues_repo_head_hexsha": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2018-10-23T10:51:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-22T08:11:33.000Z", "max_forks_repo_path": "lib/MeshFitterImpl.cpp", "max_forks_repo_name": "ithron/CortidQCT", "max_forks_repo_head_hexsha": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0424242424, "max_line_length": 80, "alphanum_fraction": 0.6880044021, "num_tokens": 2656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2854685920681385}}
{"text": "#include \"geodesic.hh\"\r\n#include \"Geo/entity.hh\"\r\n#include \"Geo/polynomial_solver.hh\"\r\n#include \"Topology/topology.hh\"\r\n#include \"Topology/impl.hh\"\r\n#include \"Topology/iterator.hh\"\r\n#include \"Utils/error_handling.hh\"\r\n\r\n#include <boost/math/tools/roots.hpp>\r\n\r\n#include <bitset>\r\n#include <functional>\r\n#include <fstream>\r\n\r\n\r\n#if 1\r\n\r\n\r\n#include <map>\r\n#include <queue>\r\n#include <set>\r\n\r\nnamespace Offset\r\n{\r\nstruct EdgeDistance;\r\nusing EdgeDistances = std::multimap<Topo::Wrap<Topo::Type::EDGE>, EdgeDistance>;\r\nusing EdgeAndDistance = EdgeDistances::value_type;\r\n\r\nstruct EdgeDistance\r\n{\r\n  EdgeDistance()\r\n  {\r\n    static int id_seq = 0;\r\n    id_ = id_seq++;\r\n  }\r\n  ~EdgeDistance()\r\n  {}\r\n\r\n  void init(const Topo::Wrap<Topo::Type::FACE>& _f,\r\n            const EdgeAndDistance* _parent)\r\n  {\r\n    if (x_ < 0)\r\n    {\r\n      x_ *= -1;\r\n      y_ed_[0] *= -1;\r\n      y_ed_[1] *= -1;\r\n    }\r\n    update_parameter();\r\n    origin_face_ = _f;\r\n    parent_ = _parent;\r\n  }\r\n\r\n  void update_parameter()\r\n  {\r\n    y_[0] = y_ed_[0] + (y_ed_[1] - y_ed_[0]) * param_range_[0];\r\n    y_[1] = y_ed_[0] + (y_ed_[1] - y_ed_[0]) * param_range_[1];\r\n    distance_range_.set_empty();\r\n    distance_range_.add(sqrt(Geo::sq(x_) + Geo::sq(y_[0])) + dist0_);\r\n    distance_range_.add(sqrt(Geo::sq(x_) + Geo::sq(y_[1])) + dist0_);\r\n    if ((y_[0] > 0) != (y_[1] > 0))\r\n      distance_range_.add(x_ + dist0_);\r\n  }\r\n\r\n  double get_distance(double _par,  double* _first_der = nullptr) const\r\n  {\r\n    auto dy = y_ed_[1] - y_ed_[0];\r\n    auto y_part = y_ed_[0] + _par * dy;\r\n    auto dist = sqrt(Geo::sq(x_) + Geo::sq(y_part));\r\n    if (_first_der != nullptr)\r\n      *_first_der = dy * y_part / dist;\r\n    return dist0_ + dist;\r\n  }\r\n\r\n  size_t parameters(const double _dist, std::array<double, 2>& _pars)\r\n  {\r\n    if (!distance_range_.contain_close(_dist))\r\n      return 0;\r\n    auto y = std::sqrt(Geo::sq(_dist - dist0_) - Geo::sq(x_));\r\n    size_t sol_nmbr = 0;\r\n    auto get_solution = [this, &sol_nmbr, &_pars](double _y)\r\n    {\r\n      _pars[sol_nmbr] = (_y - y_ed_[0]) / (y_ed_[1] - y_ed_[0]);\r\n      if (_pars[sol_nmbr] >= 0 && _pars[sol_nmbr] < 1)\r\n        ++sol_nmbr;\r\n    };\r\n    get_solution(y);\r\n    get_solution(-y);\r\n    return sol_nmbr;\r\n  }\r\n\r\n  enum class Status { Keep = 0, Skip = 1, Remove = 2 };\r\n\r\n  int id_;\r\n  Topo::Wrap<Topo::Type::FACE> origin_face_; // Face used to get there\r\n  double x_;\r\n  double y_ed_[2];\r\n  double dist0_ = 0;\r\n  Geo::Interval<double> param_range_;  // Portion of edges\r\n  Status status_ = Status::Keep;\r\n  double y_[2];\r\n  Geo::Interval<double> distance_range_;             // range of distances\r\n  std::array<EdgeAndDistance*, 2> children_ = {nullptr};\r\n  const EdgeAndDistance* parent_ = nullptr;\r\n};\r\n\r\nvoid check(const EdgeAndDistance& _edd, const Geo::Point& _orig)\r\n{\r\n  auto t = _edd.second.param_range_.interpolate(0.5);\r\n  Topo::Iterator<Topo::Type::EDGE, Topo::Type::VERTEX> ev(_edd.first);\r\n  Geo::Point pt, pt1;\r\n  ev.get(0)->geom(pt);\r\n  ev.get(1)->geom(pt1);\r\n  pt = Geo::interpolate(pt, pt1, t);\r\n  auto dist = Geo::angle(_orig, pt) * 5;\r\n  if (!_edd.second.distance_range_.contain_close(dist)) dist; // std::cout << \"error\";\r\n}\r\n\r\n// Return 0 if _apr is a root, else \r\n// < 0 ==> _a < _b\r\n// > 0 ==> _b < _a \r\n\r\nint find_minimum(const EdgeDistance& _a, const EdgeDistance& _b,\r\n                 double& _par, Geo::Interval<double> _range)\r\n{\r\n  auto func = [&_a, &_b](const double& _t)\r\n  {\r\n    double der_a, der_b;\r\n    auto val_a = _a.get_distance(_t, &der_a);\r\n    auto val_b = _b.get_distance(_t, &der_b);\r\n    return std::make_tuple(val_a - val_b, der_a - der_b);\r\n  };\r\n  boost::uintmax_t max_iter = 20;\r\n  _par = boost::math::tools::newton_raphson_iterate(\r\n    func, (_range[0] + _range[1]) / 2, _range[0], _range[1],\r\n    std::numeric_limits<double>::digits - 4, max_iter);\r\n  if (max_iter < 20)\r\n    return 0;\r\n  return std::get<0>(func(_range.interpolate(0.5))) > 0 ? 1 : -1;\r\n}\r\n\r\nstruct GeodesicDistance: public IGeodesic\r\n{\r\n  Geo::Point origin_;\r\n  // First smaller distances. Priority queue process first big elements.\r\n  struct CompareEdgeDistancePtr\r\n  {\r\n    bool operator()(const EdgeAndDistance* _a, const EdgeAndDistance* _b) const\r\n    {\r\n      return _a->second.distance_range_[1] > _b->second.distance_range_[1];\r\n    }\r\n  };\r\n\r\n  EdgeDistances edge_distances_;\r\n  std::priority_queue<const EdgeAndDistance*, std::vector<const EdgeAndDistance*>,\r\n    CompareEdgeDistancePtr> priority_queue_;\r\n\r\n  bool compute(const Topo::Wrap<Topo::Type::VERTEX>& _v) override;\r\n\r\n  bool find_graph(\r\n    double _dist,\r\n    std::vector<Geo::VectorD3>& _pts,\r\n    std::vector<std::array<size_t, 2>>& _inds) override;\r\n\r\nprivate:\r\n  void advance(const EdgeAndDistance* _ed_span, \r\n               const Topo::Wrap<Topo::Type::FACE>& _f);\r\n  void merge(Topo::Wrap<Topo::Type::EDGE> _ed,\r\n             EdgeDistance& _ed_dist);\r\n\r\n  void insert_element(const Topo::Wrap<Topo::Type::EDGE> _ed,\r\n                      EdgeDistance& _ed_dist)\r\n  {\r\n    auto it = edge_distances_.emplace(_ed, _ed_dist);\r\n    check(*it, origin_);\r\n    priority_queue_.push(&(*it));\r\n  }\r\n};\r\n\r\nstd::shared_ptr<IGeodesic> IGeodesic::make()\r\n{\r\n  return std::make_shared<GeodesicDistance>();\r\n}\r\n\r\n\r\nbool GeodesicDistance::compute(const Topo::Wrap<Topo::Type::VERTEX>& _v)\r\n{\r\n  _v->geom(origin_);\r\n  Topo::Iterator<Topo::Type::VERTEX, Topo::Type::EDGE> vert_it(_v);\r\n  for (auto e : vert_it)\r\n  {\r\n    EdgeDistance ed_dist;\r\n    Topo::Iterator<Topo::Type::EDGE, Topo::Type::VERTEX> ed_vert_it(e);\r\n    auto v1 = ed_vert_it.get(1);\r\n    auto inv = v1 == _v;\r\n    if (inv)\r\n      v1 = ed_vert_it.get(0);\r\n    Geo::Point pt;\r\n    v1->geom(pt);\r\n    ed_dist.x_ = 0;\r\n    ed_dist.y_ed_[0] = 0;\r\n    ed_dist.y_ed_[1] = Geo::length(pt - origin_);\r\n    if (inv)\r\n      std::swap(ed_dist.y_ed_[0], ed_dist.y_ed_[1]);\r\n    ed_dist.param_range_ = { 0, 1 };\r\n    ed_dist.init(Topo::Wrap<Topo::Type::FACE>(), nullptr);\r\n    ed_dist.status_ = EdgeDistance::Status::Skip;\r\n    insert_element(e, ed_dist);\r\n  }\r\n  Topo::Iterator<Topo::Type::VERTEX, Topo::Type::FACE> face_it(_v);\r\n  for (auto f : face_it)\r\n  {\r\n    Topo::Iterator<Topo::Type::FACE, Topo::Type::EDGE> ed_it(f);\r\n    Topo::Wrap<Topo::Type::EDGE> curr_ed;\r\n    for (auto e : ed_it)\r\n    {\r\n      auto it = edge_distances_.equal_range(e);\r\n      if (it.first == it.second)\r\n      {\r\n        curr_ed = e;\r\n        break;\r\n      }\r\n    }\r\n    if (curr_ed.get() == nullptr)\r\n      continue;\r\n    EdgeDistance ed_dist;\r\n    Topo::Iterator<Topo::Type::EDGE, Topo::Type::VERTEX> ed_vert(curr_ed);\r\n    Geo::Segment seg;\r\n    ed_vert.get(0)->geom(seg[0]);\r\n    ed_vert.get(1)->geom(seg[1]);\r\n    double dist_sq, t;\r\n    Geo::VectorD3 proj;\r\n    if (!Gen::closest_point<double, 3, true>(seg, origin_, &proj, &t, &dist_sq))\r\n      return false;\r\n    ed_dist.x_ = sqrt(dist_sq);\r\n    ed_dist.y_ed_[0] = Geo::length(seg[0] - proj);\r\n    ed_dist.y_ed_[1] = Geo::length(seg[1] - proj);\r\n    if (t < 1 && t > 0)\r\n      ed_dist.y_ed_[ed_dist.y_ed_[1] < ed_dist.y_ed_[0]] *= -1;\r\n    ed_dist.param_range_ = { 0, 1 };\r\n    ed_dist.init(f, nullptr);\r\n    insert_element(curr_ed, ed_dist);\r\n  }\r\n  while (!priority_queue_.empty())\r\n  {\r\n    auto edge_span = priority_queue_.top();\r\n    priority_queue_.pop();\r\n    if (edge_span->second.status_ != EdgeDistance::Status::Keep)\r\n      continue;\r\n    Topo::Iterator<Topo::Type::EDGE, Topo::Type::FACE> fe_it(edge_span->first);\r\n    for (auto f : fe_it)\r\n    {\r\n      if (f != edge_span->second.origin_face_)\r\n        advance(edge_span, f);\r\n    }\r\n  }\r\n  for (auto it = edge_distances_.begin(); it != edge_distances_.end();)\r\n  {\r\n    if (it->second.status_ == EdgeDistance::Status::Remove)\r\n      it = edge_distances_.erase(it);\r\n    else\r\n      ++it;\r\n  }\r\n  std::ofstream outf(\"c:/t/out.txt\");\r\n  outf << \"V0 V1 Id Px Py Pz Qx Qy Qz x y0 y1 interval0 interval1 distance0  distance1 dist0 par_id \\n\";\r\n  for (auto& es : edge_distances_)\r\n  {\r\n    Geo::Segment seg;\r\n    es.first->geom(seg);\r\n    Topo::Iterator<Topo::Type::EDGE, Topo::Type::VERTEX> ed_it(es.first);\r\n    outf << ed_it.get(0)->id() << \" \" << ed_it.get(1)->id() << \" \";\r\n    outf << es.second.id_ << \" \" << seg[0] << \" \" << seg[1] << \" \";\r\n    outf << es.second.x_ << \" \";\r\n    outf << es.second.y_ed_[0] << \" \" << es.second.y_ed_[1] << \" \";\r\n    outf << es.second.param_range_[0] << \" \" << es.second.param_range_[1] << \" \";\r\n    outf << es.second.distance_range_[0] << \" \" << es.second.distance_range_[1] << \" \";\r\n    outf << es.second.dist0_ << \" \";\r\n    if (es.second.parent_ == nullptr)\r\n      outf << -1;\r\n    else\r\n      outf << es.second.parent_->second.id_;\r\n    outf  << std::endl;\r\n  }\r\n  outf << \"SIZE = \" << edge_distances_.size() << \"\\n\";\r\n  return true;\r\n}\r\n\r\nvoid GeodesicDistance::advance(\r\n  const EdgeAndDistance* _parent, const Topo::Wrap<Topo::Type::FACE>& _f)\r\n{\r\n  Topo::Iterator<Topo::Type::EDGE, Topo::Type::VERTEX> it_ev_pa(_parent->first);\r\n  Topo::Wrap<Topo::Type::VERTEX> verts[2] = { it_ev_pa.get(0), it_ev_pa.get(1) };\r\n  Geo::VectorD3 p_parent[2];\r\n  Geo::iterate_forw<2>::eval([&verts, &p_parent](int _i) { verts[_i]->geom(p_parent[_i]); });\r\n  Geo::VectorD3 v_parent = p_parent[1] - p_parent[0];\r\n  Topo::Iterator<Topo::Type::FACE, Topo::Type::EDGE> it_fe(_f);\r\n  struct OtherEdge\r\n  {\r\n    Topo::Wrap<Topo::Type::EDGE> ed_;\r\n    bool inv_;\r\n    Geo::VectorD3 v_;\r\n  };\r\n  Gen::Segment<double, 2> parent_seg{ {\r\n    { _parent->second.x_, _parent->second.y_[0] },\r\n    { _parent->second.x_, _parent->second.y_[1] } } };\r\n  Gen::Segment<double, 2> parent_trace_segs[2];\r\n  for (int i = 0; i < 2; ++i)\r\n  {\r\n    parent_trace_segs[i][0] = {};\r\n    parent_trace_segs[i][1] = parent_seg[i];\r\n  }\r\n\r\n  OtherEdge oth_eds[2];\r\n  auto dy_par = _parent->second.y_ed_[1] - _parent->second.y_ed_[0];\r\n  for (auto& fe : it_fe)\r\n  {\r\n    if (fe == _parent->first)\r\n      continue;\r\n    EdgeDistance new_edd;\r\n    Topo::Iterator<Topo::Type::EDGE, Topo::Type::VERTEX> it_ev(fe);\r\n    bool idx = it_ev.get(1) == verts[1] || it_ev.get(0) == verts[1];\r\n    auto inv = it_ev.get(1) == verts[idx];\r\n    oth_eds[idx].ed_ = fe;\r\n    oth_eds[idx].inv_ = inv;\r\n    Geo::VectorD3 p[2];\r\n    Geo::iterate_forw<2>::eval([&it_ev, &p](int _i) { it_ev.get(_i)->geom(p[_i]); });\r\n    auto v0 = v_parent;\r\n    if (dy_par < 0) v0 *= -1.;\r\n    v0 /= Geo::length(v0);\r\n    auto v1 = oth_eds[idx].v_ = p[1] - p[0];\r\n    if (inv) v1 *= -1.;\r\n    auto dy = v0 * v1;\r\n    //if (dy * dy_par < 0)\r\n    //  continue;\r\n    auto dx = Geo::length(v0 % v1);\r\n    Gen::Segment<double, 2> v2 = { {\r\n      { _parent->second.x_, _parent->second.y_ed_[idx] },\r\n      { _parent->second.x_ + dx, _parent->second.y_ed_[idx] + dy } } };\r\n    if (inv)\r\n      std::swap(v2[0], v2[1]);\r\n    auto dist_3d = Geo::length(p[0] - p[1]);\r\n\r\n    auto compute_x_y_ed = [dist_3d](const Gen::Segment<double, 2>& _v, EdgeDistance& _new_ed)\r\n    {\r\n      Geo::VectorD2 proj;\r\n      double dist_sq, par;\r\n      Gen::closest_point<double, 2, true>(_v, Geo::VectorD2{},\r\n                                          &proj, &par, &dist_sq);\r\n      _new_ed.x_ = sqrt(dist_sq);\r\n      _new_ed.y_ed_[0] = Geo::length(_v[0] - proj);\r\n      _new_ed.y_ed_[1] = Geo::length(_v[1] - proj);\r\n      if (par > 0 && par < 1)\r\n        _new_ed.y_ed_[_new_ed.y_ed_[0] >_new_ed.y_ed_[1]] *= -1;\r\n      THROW_IF((fabs(_new_ed.y_ed_[1] - _new_ed.y_ed_[0]) - dist_3d) > 1e-8,\r\n               \"Wrong y reange\");\r\n    };\r\n    compute_x_y_ed(v2, new_edd);\r\n\r\n    Geo::Interval<double> tmp;\r\n    for (int i = 0; i < 2; ++i)\r\n    {\r\n      bool done = false;\r\n      for (int j = 0; j < 2; ++j)\r\n      {\r\n        double t, dist_sq;\r\n        Gen::closest_point<double, 2, true>(\r\n          parent_trace_segs[i], v2[j], nullptr, &t, &dist_sq);\r\n        done = dist_sq < Geo::epsilon_sq(v2[j]);\r\n        if (done)\r\n        {\r\n          tmp.add(j);\r\n          break;\r\n        }\r\n      }\r\n      if (done)\r\n        continue;\r\n\r\n      double pars[2], dist_sq;\r\n      Gen::closest_point<double, 2, true, true>(\r\n        parent_trace_segs[i], v2, nullptr, pars, &dist_sq);\r\n      auto dir = v2[1] - v2[0];\r\n      double cr_pr = fabs(parent_trace_segs[i][1] % dir);\r\n      if (cr_pr < 1e-12)\r\n        pars[1] = Geo::length_square(v2[1]) > Geo::length_square(v2[0]) ? 1: 0;\r\n      //auto val_sq = std::max(Geo::length_square(v2[0]), Geo::length_square(v2[1]));\r\n      else if (pars[0] <= 1e-12)\r\n      {\r\n        if (pars[1] <= 0) pars[1] = 1;\r\n        else if (pars[1] >= 1) pars[1] = 0;\r\n        else \r\n          THROW(\"Bad par\");\r\n        \r\n      }\r\n      else if (pars[0] <= 1 - 1e-12)\r\n        continue;\r\n      tmp.add(std::clamp(pars[1], 0., 1.));\r\n    }\r\n\r\n    if (!tmp.empty())\r\n    {\r\n      new_edd.param_range_ = tmp;\r\n      new_edd.dist0_ = _parent->second.dist0_;\r\n      new_edd.init(_f, _parent);\r\n      merge(fe, new_edd);\r\n    }\r\n\r\n    size_t par_bndr_to_fill = idx;\r\n    if (tmp.empty() &&\r\n        (_parent->second.param_range_[par_bndr_to_fill] == par_bndr_to_fill))\r\n    {\r\n      EdgeDistance new_edd2;\r\n      new_edd2.dist0_ = _parent->second.get_distance(static_cast<double>(par_bndr_to_fill));\r\n      auto orig = Geo::VectorD2{ _parent->second.x_, _parent->second.y_ed_[par_bndr_to_fill] };\r\n      Gen::Segment<double, 2> new_seg;\r\n      new_seg[0] = v2[0] - orig;\r\n      new_seg[1] = v2[1] - orig;\r\n      compute_x_y_ed(new_seg, new_edd2);\r\n      new_edd2.param_range_ = { 0., 1. };\r\n      new_edd2.init(_f, _parent);\r\n      merge(fe, new_edd2);\r\n    }\r\n    par_bndr_to_fill = !idx;\r\n    size_t new_par = !inv;\r\n    if (!tmp.empty() && tmp[new_par] != new_par &&\r\n      (_parent->second.param_range_[par_bndr_to_fill] == par_bndr_to_fill))\r\n    {\r\n      EdgeDistance new_edd2;\r\n      new_edd2.dist0_ = _parent->second.get_distance(static_cast<double>(par_bndr_to_fill));\r\n      auto orig = Geo::VectorD2{ _parent->second.x_, _parent->second.y_ed_[par_bndr_to_fill] };\r\n      Gen::Segment<double, 2> new_seg;\r\n      new_seg[0] = v2[0] - orig;\r\n      new_seg[1] = v2[1] - orig;\r\n      compute_x_y_ed(new_seg, new_edd2);\r\n      if (inv)\r\n        new_edd2.param_range_ = Geo::Interval<double>(0., tmp[0]);\r\n      else\r\n        new_edd2.param_range_ = Geo::Interval<double>(tmp[1], 1.);\r\n      new_edd2.init(_f, _parent);\r\n      merge(fe, new_edd2);\r\n    }\r\n\r\n  }\r\n  THROW_IF(!oth_eds[0].ed_.get() || !oth_eds[1].ed_.get(), \"\");\r\n}\r\n\r\nstatic std::bitset<2> intersect(EdgeDistance& _a, EdgeDistance& _b,\r\n                                Geo::Interval<double> _extras[2])\r\n{\r\n  auto inters_par_range = _a.param_range_ * _b.param_range_;\r\n  if (inters_par_range.length() < 1e-12)\r\n    return 0;\r\n  double root;\r\n  auto a_minus_b = find_minimum(_a, _b, root, inters_par_range);\r\n  std::bitset<2> res;\r\n  if (a_minus_b > 0)\r\n    res[0] = _a.param_range_.subtract(inters_par_range, _extras[0]);\r\n  else if (a_minus_b < 0)\r\n    res[1] = _b.param_range_.subtract(inters_par_range, _extras[1]);\r\n  else\r\n  {\r\n    auto snap_to_boundary = [](double& _root, const Geo::Interval<double>& _interv)\r\n    {\r\n      for (int i = 0; i < 2; ++i)\r\n        if (fabs(_root - _interv[i]) < 1e-8)\r\n        {\r\n          _root = _interv[i];\r\n          return true;\r\n        }\r\n      return false;\r\n    };\r\n    snap_to_boundary(root, _a.param_range_) || snap_to_boundary(root, _b.param_range_);\r\n    Geo::Interval<double> near_a(Geo::Interval<double>::min(), root);\r\n    Geo::Interval<double> near_b(root, Geo::Interval<double>::max());\r\n    if (_a.get_distance(root - 1) > _b.get_distance(root - 1))\r\n      std::swap(near_a, near_b);\r\n\r\n    near_b *= _b.param_range_;\r\n    res[0] = _a.param_range_.subtract(near_b, _extras[0]);\r\n    near_a *= _a.param_range_;\r\n    res[1] = _b.param_range_.subtract(near_a, _extras[1]);\r\n  }\r\n  return res;\r\n}\r\n\r\nvoid GeodesicDistance::merge(Topo::Wrap<Topo::Type::EDGE> _ed,\r\n                             EdgeDistance& _ed_dist)\r\n{\r\n  auto range = edge_distances_.equal_range(_ed);\r\n  Topo::Iterator<Topo::Type::EDGE, Topo::Type::VERTEX> edv(_ed);\r\n  if (edv.get(0)->id() == 395 && edv.get(1)->id() == 436)\r\n  {\r\n    std::cout << \"Here we are\";\r\n  }\r\n  std::vector<EdgeDistance*> old_ed_dists;\r\n  for (auto it = range.first; it != range.second; ++it)\r\n    old_ed_dists.push_back(&(it->second));\r\n  std::vector<EdgeDistance> new_edds;\r\n  new_edds.push_back(_ed_dist);\r\n  for (auto old_edd : old_ed_dists)\r\n  {\r\n    //if (it->second.status_ != EdgeDistance::Status::Keep)\r\n    if (old_edd->status_ == EdgeDistance::Status::Remove)\r\n      continue;\r\n    auto size = new_edds.size();\r\n    for (size_t i = 0; i < size; ++i)\r\n    {\r\n      auto& new_edd = new_edds[i];\r\n      Geo::Interval<double> extras[2];\r\n      auto int_res = intersect(new_edd, *old_edd, extras);\r\n      if (!int_res.any())\r\n        continue;\r\n      if (int_res[1])\r\n      {\r\n        if (old_edd->param_range_.empty())\r\n        {\r\n          std::function<void(EdgeDistance* _ed_dist)> skip_children =\r\n            [&](EdgeDistance* _ed_dist)\r\n          {\r\n            _ed_dist->status_ = EdgeDistance::Status::Remove;\r\n            for (auto child : _ed_dist->children_)\r\n              if (child != nullptr)\r\n                skip_children(&child->second);\r\n          };\r\n          skip_children(old_edd);\r\n        }\r\n        else\r\n        {\r\n          old_edd->update_parameter();\r\n          if (!extras[1].empty())\r\n          {\r\n            auto split_piece = *old_edd;\r\n            split_piece.param_range_ = extras[1];\r\n            split_piece.update_parameter();\r\n            insert_element(_ed, split_piece);\r\n          }\r\n        }\r\n      }\r\n      if (int_res[0])\r\n      {\r\n        new_edd.update_parameter();\r\n        if (!extras[0].empty())\r\n        {\r\n          auto new_el = new_edds.emplace_back(new_edd);\r\n          new_el.param_range_ = extras[0];\r\n          new_el.update_parameter();\r\n        }\r\n      }\r\n    }\r\n  }\r\n  for (auto& new_edd : new_edds)\r\n    if (!new_edd.param_range_.empty())\r\n      insert_element(_ed, new_edd);\r\n}\r\n\r\nbool GeodesicDistance::find_graph(\r\n  double _dist,\r\n  std::vector<Geo::VectorD3>& _pts,\r\n  std::vector<std::array<size_t, 2>>& _inds)\r\n{\r\n  using FacePointMap = std::map<Topo::Wrap<Topo::Type::FACE>, std::vector<size_t>>;\r\n  FacePointMap fp_map;\r\n  for (auto& ed_dist : edge_distances_)\r\n  {\r\n    std::array<double, 2> pars;\r\n    auto sol_num = ed_dist.second.parameters(_dist, pars);\r\n    if (sol_num == 0)\r\n      continue;\r\n    Topo::Iterator<Topo::Type::EDGE, Topo::Type::VERTEX> vert_it(ed_dist.first);\r\n    Geo::Segment seg;\r\n    vert_it.get(0)->geom(seg[0]);\r\n    vert_it.get(1)->geom(seg[1]);\r\n    Topo::Iterator<Topo::Type::EDGE, Topo::Type::FACE> face_it(ed_dist.first);\r\n    for (int i = 0; i < sol_num; ++i)\r\n    {\r\n      auto pt = Geo::evaluate(seg, pars[i]);\r\n      for (auto f : face_it)\r\n        fp_map[f].push_back(_pts.size());\r\n      _pts.push_back(pt);\r\n    }\r\n  }\r\n  for (auto& fp : fp_map)\r\n  {\r\n    for (auto it = fp.second.begin(); it != fp.second.end(); ++it)\r\n      for (auto it1 = it; ++it1 != fp.second.end(); )\r\n        _inds.push_back({ *it, *it1 });\r\n  }\r\n  return true;\r\n}\r\n\r\n} // namespace Offset\r\n\r\n#endif", "meta": {"hexsha": "faf1e134d95fa84ef1a22cb726a071cd4f212132", "size": 19059, "ext": "cc", "lang": "C++", "max_stars_repo_path": "main/src/Offset/geodesic.cc", "max_stars_repo_name": "marcomanno/ploygon_triangulation", "max_stars_repo_head_hexsha": "c98b99e3f9598252ffc27eb202939f0183ac872b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main/src/Offset/geodesic.cc", "max_issues_repo_name": "marcomanno/ploygon_triangulation", "max_issues_repo_head_hexsha": "c98b99e3f9598252ffc27eb202939f0183ac872b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main/src/Offset/geodesic.cc", "max_forks_repo_name": "marcomanno/ploygon_triangulation", "max_forks_repo_head_hexsha": "c98b99e3f9598252ffc27eb202939f0183ac872b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2487309645, "max_line_length": 105, "alphanum_fraction": 0.5773650244, "num_tokens": 5870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2854528086844193}}
{"text": "#include \"Sh3FixedPoint.h\"\n\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <cryptoTools/Common/BitVector.h>\nnamespace aby3\n{\n\ttemplate<typename T, Decimal D>\n\tfp<T, D> fp<T, D>::operator*(const fp<T, D>& rhs) const\n\t{\n\t\tboost::multiprecision::int128_t v0 = mValue, v1 = rhs.mValue;\n\n\t\tv0 = v0 * v1;\n\t\tv0 = v0 / (1ull << mDecimal);\n\n\t\treturn {\n\t\t\tstatic_cast<i64>(v0),\n\t\t\tmonostate{}\n\t\t};\n\t}\n\n\n\t//template<typename T, Decimal D>\n\t//std::ostream& operator<<(std::ostream& o, const fp<T, D>& f)\n\t//{\n\t//\tauto mask = ((1ull << f.mDecimal) - 1);\n\t//\tauto print = [mask](T v) {\n\t//\t\tstd::stringstream s;\n\t//\t\toc::BitVector bv;\n\t//\t\tbv.append((u8*)& v, D);\n\t//\t\ts << bv;\n\n\t//\t\ts << \".\";\n\t//\t\tbv = {};\n\t//\t\tbv.append((u8*)& v, 64 - D, D);\n\t//\t\ts << bv;\n\t//\t\treturn s.str();\n\t//\t};\n\n\t//\tstd::stringstream ss;\n\t//\t//auto& ss = o;\n\t//\tauto vv = (f.mValue / double(1 << f.mDecimal));\n\t//\to << std::setprecision(std::numeric_limits<long double>::digits10 + 1)\n\t//\t\t<< vv << std::endl;\n\t//\to << print(f.mValue) << std::endl;\n\n\t//\tu64 v = 0;\n\t//\tif (f.mValue >= 0)\n\t//\t\tv = f.mValue;\n\t//\telse\n\t//\t{\n\t//\t\tss << '-';\n\t//\t\tv =-f.mValue;\n\t//\t}\n\n\t//\tss << (v >> f.mDecimal) << \".\";\n\n\n\t//\tv &= mask;\n\n\t//\tint i = 0;\n\t//\tif (v)\n\t//\t{\n\t//\t\to << \"[\"<<i<<\"]  \" << print(v) << std::endl;\n\t//\t\twhile (v & mask)\n\t//\t\t{\n\t//\t\t\t++i;\n\t//\t\t\tv *= 10;\n\t//\t\t\tss << (v >> f.mDecimal);\n\t//\t\t\to << \"[\" << i << \"]  \" << print(v) << std::endl;\n\n\t//\t\t\tv &= mask;\n\t//\t\t\to << \"[\" << i << \"]* \" << print(v) << std::endl;\n\t//\t\t}\n\t//\t}\n\t//\telse\n\t//\t{\n\t//\t\tss << '0';\n\t//\t}\n\t//\to << ss.str();\n\n\t//\treturn o;\n\t//}\n\n\t//template std::ostream& operator<<<i64, D8>(std::ostream& o, const fp<i64, D8>& f);\n\t//template std::ostream& operator<<<i64, D16>(std::ostream& o, const fp<i64, D16>& f);\n\t//template std::ostream& operator<<<i64, D32>(std::ostream& o, const fp<i64, D32>& f);\n\n\ttemplate struct fp<i64, D0>;\n\ttemplate struct fp<i64, D8>;\n\ttemplate struct fp<i64, D16>;\n\ttemplate struct fp<i64, D32>;\n\n\ttemplate struct sf64<D0>;\n\ttemplate struct sf64<D8>;\n\ttemplate struct sf64<D16>;\n\ttemplate struct sf64<D32>;\n\n\ttemplate struct sf64Matrix<D0>;\n\ttemplate struct sf64Matrix<D8>;\n\ttemplate struct sf64Matrix<D16>;\n\ttemplate struct sf64Matrix<D32>;\n\n}\n", "meta": {"hexsha": "21849b788fd8597aee2a6d78f846f3297a0794a5", "size": 2207, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aby3/sh3/Sh3FixedPoint.cpp", "max_stars_repo_name": "cyckun/aby3", "max_stars_repo_head_hexsha": "99af31ccaef6cd2c22df8ef57d8b7a07d62c66cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 121.0, "max_stars_repo_stars_event_min_datetime": "2019-06-25T01:35:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T12:53:17.000Z", "max_issues_repo_path": "aby3/sh3/Sh3FixedPoint.cpp", "max_issues_repo_name": "cyckun/aby3", "max_issues_repo_head_hexsha": "99af31ccaef6cd2c22df8ef57d8b7a07d62c66cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2020-01-21T16:47:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T12:41:22.000Z", "max_forks_repo_path": "aby3/sh3/Sh3FixedPoint.cpp", "max_forks_repo_name": "cyckun/aby3", "max_forks_repo_head_hexsha": "99af31ccaef6cd2c22df8ef57d8b7a07d62c66cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 36.0, "max_forks_repo_forks_event_min_datetime": "2019-09-05T08:35:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T11:57:22.000Z", "avg_line_length": 21.019047619, "max_line_length": 87, "alphanum_fraction": 0.5310376076, "num_tokens": 804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2854528023852887}}
{"text": "// TopicModelLocalStepCPPX.cpp\n// Define this symbol to enable runtime tests for allocations\n#define EIGEN_RUNTIME_NO_MALLOC \n\n#include <math.h>\n#include \"Eigen/Dense\"\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n\nusing namespace Eigen;\nusing namespace std;\n\n// ======================================================== Declare funcs\n// ======================================================== visible externally\n\nextern \"C\" {\n    void sparseLocalStepSingleDoc(\n        double* ElogLik_d_IN,\n        double* alphaEbeta_IN,\n        int nnzPerRow,\n        int N,\n        int K,\n        int nCoordAscentIterLP,\n        double convThrLP,\n        int initProbsToEbeta,\n        double* topicCount_d_OUT,\n        double* spResp_data_OUT,\n        int* spResp_colids_OUT,\n        int d,\n        int D,\n        int* numIterVec_OUT,\n        double* maxDiffVec_OUT\n        );\n\n    void sparseLocalStepSingleDoc_ActiveOnly(\n        double* ElogLik_d_IN,\n        double* wc_d_IN,\n        double* alphaEbeta_IN,\n        int nnzPerRow,\n        int N,\n        int K,\n        int nCoordAscentIterLP,\n        double convThrLP,\n        int initProbsToEbeta,\n        double* topicCount_d_OUT,\n        double* spResp_data_OUT,\n        int* spResp_colids_OUT,\n        int d,\n        int D,\n        int* numIterVec_OUT,\n        double* maxDiffVec_OUT,\n        int doTrackELBO,\n        double* elboVec_OUT,\n        int numRestarts,\n        int REVISE_FIRST,\n        int REVISE_EVERY,\n        int *rAcceptVec_IN, int* rTrialVec_IN,\n        int verbose\n        );\n\n\n    void sparseLocalStepSingleDocWithWordCounts(\n        double* wordcounts_d_IN,\n        double* ElogLik_d_IN,\n        double* alphaEbeta_IN,\n        int nnzPerRow,\n        int N,\n        int K,\n        int nCoordAscentIterLP,\n        double convThrLP,\n        int initProbsToEbeta,\n        double* topicCount_d_OUT,\n        double* spResp_data_OUT,\n        int* spResp_colids_OUT\n        );   \n}\n\n// ======================================================== Custom Type Defs\n// ========================================================\n// Simple names for array types\ntypedef Matrix<double, Dynamic, Dynamic, RowMajor> Mat2D_d;\ntypedef Matrix<double, 1, Dynamic, RowMajor> Mat1D_d;\ntypedef Array<double, Dynamic, Dynamic, RowMajor> Arr2D_d;\ntypedef Array<double, 1, Dynamic, RowMajor> Arr1D_d;\ntypedef Array<int, 1, Dynamic, RowMajor> Arr1D_i;\n\n// Simple names for array types with externally allocated memory\ntypedef Map<Mat2D_d> ExtMat2D_d;\ntypedef Map<Mat1D_d> ExtMat1D_d;\ntypedef Map<Arr2D_d> ExtArr2D_d;\ntypedef Map<Arr1D_d> ExtArr1D_d;\ntypedef Map<Arr1D_i> ExtArr1D_i;\n\ndouble calcELBOForSingleDoc_V2(\n    Arr1D_d alphaEbeta,\n    Arr1D_d topicCount_d,\n    Arr1D_d spResp_data,\n    Arr1D_i spResp_colids,\n    Arr2D_d ElogLik_d,\n    int K,\n    int N,\n    int nnzPerRow\n    )\n{\n    double ELBO = 0.0;\n    // Lalloc\n    for (int k = 0; k < K; k++) {\n        ELBO += boost::math::lgamma(topicCount_d(k) + alphaEbeta(k));\n    }\n    \n    // Ldata and Lentropy\n    for (int n = 0; n < N; n++) {\n        for (int nzk = n * nnzPerRow; nzk < (n+1) * nnzPerRow; nzk++) {\n            int k = spResp_colids(nzk);\n            ELBO += spResp_data(nzk) * ElogLik_d(n,k);\n            if (spResp_data(nzk) > 1e-9) {\n                ELBO -= spResp_data(nzk) * log(spResp_data(nzk));\n            }\n        }\n    }\n    return ELBO;\n}\n\ndouble calcELBOForSingleDoc_V1(\n    ExtArr1D_d alphaEbeta,\n    ExtArr1D_d topicCount_d,\n    Arr1D_d ElogProb_d,\n    Arr1D_i activeTopics_d,\n    double totalLogSumResp,\n    double sum_gammalnalphaEbeta,\n    int Kactive\n    )\n{\n    // Compute Lalloc = \\sum_k gammaln(\\theta_dk)\n    double ELBO = sum_gammalnalphaEbeta;\n    for (int ka = 0; ka < Kactive; ka++) {\n        int k = activeTopics_d(ka);\n        ELBO += (\n            boost::math::lgamma(topicCount_d(k) + alphaEbeta(k))\n            - boost::math::lgamma(alphaEbeta(k))\n            - topicCount_d(k) * ElogProb_d(k)\n            );\n    }\n    ELBO += totalLogSumResp;\n    return ELBO;\n}\n\ndouble updateAssignments_FixPerTokenActiveSet(\n    ExtArr2D_d ElogLik_d,\n    ExtArr1D_d wc_d,\n    ExtArr1D_d alphaEbeta,\n    Arr1D_i activeTopics_d,\n    ExtArr1D_d& topicCount_d, // & makes sure we can edit passed array in place\n    Arr1D_d& ElogProb_d,\n    Arr1D_d& logScores_n,\n    ExtArr1D_d& spResp_data,\n    ExtArr1D_i& spResp_colids,\n    int N,\n    int K, \n    int Kactive,\n    int nnzPerRow,\n    int doTrackELBO\n    )\n{\n    assert(nnzPerRow > 1);\n    double totalLogSumResp = 0.0;\n    // UPDATE ElogProb_d using input doc-topic counts\n    for (int ka = 0; ka < Kactive; ka++) {\n        int k = activeTopics_d(ka);\n        ElogProb_d(k) = boost::math::digamma(\n            topicCount_d(k) + alphaEbeta(k));\n    }\n    // RESET topicCounts to all zeros\n    topicCount_d.fill(0);\n    // UPDATE assignments, obeying sparsity constraint\n    for (int n = 0; n < N; n++) {\n        double sumResp_n = 0.0;\n        int m = n * nnzPerRow;\n        double maxScore_n;\n        for (int ka = 0; ka < nnzPerRow; ka++) {\n            int k = spResp_colids(m + ka);\n            logScores_n(ka) = ElogProb_d(k) + ElogLik_d(n,k);\n            if (ka == 0 || logScores_n(ka) > maxScore_n) {\n                maxScore_n = logScores_n(ka);\n            }\n        }\n        for (int nzk = 0; nzk < nnzPerRow; nzk++) {\n            spResp_data(m + nzk) = \\\n                exp(logScores_n(nzk) - maxScore_n);\n            sumResp_n += spResp_data(m + nzk);\n        }\n\n        for (int nzk = m; nzk < m + nnzPerRow; nzk++) {\n            spResp_data(nzk) /= sumResp_n;\n            topicCount_d(spResp_colids(nzk)) += \\\n                wc_d(n) * spResp_data(nzk);\n        }\n        if (doTrackELBO) {\n            totalLogSumResp += wc_d(n) * (maxScore_n + log(sumResp_n));\n        }\n    } // end for loop over tokens n\n    assert(abs(wc_d.sum() - topicCount_d.sum()) < .000001);\n    return totalLogSumResp;\n}\n\ndouble updateAssignments_ActiveOnly(\n    ExtArr2D_d ElogLik_d,\n    ExtArr1D_d wc_d,\n    ExtArr1D_d alphaEbeta,\n    Arr1D_i activeTopics_d,\n    ExtArr1D_d& topicCount_d, // & makes sure we can edit passed array in place\n    Arr1D_d& ElogProb_d,\n    Arr1D_d& logScores_n,\n    Arr1D_d& tempScores_n,\n    ExtArr1D_d& spResp_data,\n    ExtArr1D_i& spResp_colids,\n    int N,\n    int K, \n    int Kactive,\n    int nnzPerRow,\n    int iter,\n    int initProbsToEbeta,\n    int doTrackELBO\n    )\n{\n    double totalLogSumResp = 0.0;\n\n    // UPDATE ElogProb_d using input doc-topic counts\n    if (iter == 0 and initProbsToEbeta == 1) {\n        for (int ka = 0; ka < Kactive; ka++) {\n            int k = activeTopics_d(ka);\n            ElogProb_d(k) = log(alphaEbeta(k));\n        }\n    } else {\n        for (int ka = 0; ka < Kactive; ka++) {\n            int k = activeTopics_d(ka);\n            ElogProb_d(k) = boost::math::digamma(\n                topicCount_d(k) + alphaEbeta(k));\n        }\n    }\n    // RESET topicCounts to all zeros\n    topicCount_d.fill(0);\n    // UPDATE assignments, obeying sparsity constraint\n    for (int n = 0; n < N; n++) {\n        int m = n * nnzPerRow;\n        int argmax_n = 0;\n        double maxScore_n;\n        for (int ka = 0; ka < Kactive; ka++) {\n            int k = activeTopics_d(ka);\n            logScores_n(ka) = ElogProb_d(k) + ElogLik_d(n,k);\n            if (ka == 0 || logScores_n(ka) > maxScore_n) {\n                maxScore_n = logScores_n(ka);\n                if (nnzPerRow == 1) {\n                    argmax_n = k;\n                }\n            }\n        }\n        if (nnzPerRow == 1) {\n            spResp_data(m) = 1.0;\n            spResp_colids(m) = argmax_n;\n            topicCount_d(argmax_n) += wc_d(n);\n            if (doTrackELBO) {\n                totalLogSumResp += wc_d(n) * maxScore_n;\n            }\n        } else {\n            // Find the top L entries in logScores_n\n            // Copy current row over into a temp buffer\n            std::copy(\n                logScores_n.data(),\n                logScores_n.data() + Kactive,\n                tempScores_n.data());\n            // Sort the data in the temp buffer (in place)\n            std::nth_element(\n                tempScores_n.data(),\n                tempScores_n.data() + Kactive - nnzPerRow,\n                tempScores_n.data() + Kactive);\n            // Walk thru this row and find the top \"nnzPerRow\" positions\n            double pivotScore = tempScores_n(Kactive - nnzPerRow);\n\n            int nzk = m;\n            double sumResp_n = 0.0;\n            for (int ka = 0; ka < Kactive; ka++) {\n                if (logScores_n(ka) >= pivotScore) {\n                    spResp_data(nzk) = \\\n                        exp(logScores_n(ka) - maxScore_n);\n                    spResp_colids(nzk) = activeTopics_d(ka);\n                    sumResp_n += spResp_data(nzk);\n                    nzk += 1;                        \n                }\n            }\n            //assert(nzk - m == nnzPerRow);\n\n            for (nzk = m; nzk < m + nnzPerRow; nzk++) {\n                spResp_data(nzk) /= sumResp_n;\n                topicCount_d(spResp_colids(nzk)) += \\\n                    wc_d(n) * spResp_data(nzk);\n            }\n            if (doTrackELBO) {\n                totalLogSumResp += wc_d(n) * (maxScore_n + log(sumResp_n));\n            }\n        } // end if statement branch for nnz > 1\n    } // end for loop over tokens n\n    return totalLogSumResp;\n}\n\nvoid sparseLocalStepSingleDoc_ActiveOnly(\n        double* ElogLik_d_IN,\n        double* wc_d_IN,\n        double* alphaEbeta_IN,\n        int nnzPerRow,\n        int N,\n        int K,\n        int nCoordAscentIterLP,\n        double convThrLP,\n        int initProbsToEbeta,\n        double* topicCount_d_OUT,\n        double* spResp_data_OUT,\n        int* spResp_colids_OUT,\n        int d,\n        int D,\n        int* numIterVec_OUT,\n        double* maxDiffVec_OUT,\n        int doTrackELBO,\n        double* elboVec_OUT,\n        int numRestarts,\n        int REVISE_FIRST,\n        int REVISE_EVERY,\n        int* rAcceptVec_IN,\n        int* rTrialVec_IN,\n        int verbose\n        )\n{\n    nCoordAscentIterLP = max(nCoordAscentIterLP + max(0, initProbsToEbeta), 1);\n\n    // Unpack inputs, treated as fixed constants\n    ExtArr2D_d ElogLik_d (ElogLik_d_IN, N, K);\n    ExtArr1D_d wc_d (wc_d_IN, N);\n    ExtArr1D_d alphaEbeta (alphaEbeta_IN, K);\n\n    // Unpack outputs\n    ExtArr1D_d spResp_data (spResp_data_OUT, N * nnzPerRow);\n    ExtArr1D_i spResp_colids (spResp_colids_OUT, N * nnzPerRow);\n    ExtArr1D_d topicCount_d (topicCount_d_OUT, K);\n\n    ExtArr1D_i numIterVec (numIterVec_OUT, D);\n    ExtArr1D_d maxDiffVec (maxDiffVec_OUT, D);\n    ExtArr1D_d elboVec (elboVec_OUT, nCoordAscentIterLP);\n\n    ExtArr1D_i rAcceptVec (rAcceptVec_IN, 1);\n    ExtArr1D_i rTrialVec (rTrialVec_IN, 1);\n    \n    // Temporary storage\n    Arr1D_d ElogProb_d (K);\n    Arr1D_d prevTopicCount_d (K);\n    Arr1D_d logScores_n (K);\n    Arr1D_d tempScores_n (K);\n\n    Arr1D_i activeTopics_d (K);\n    Arr1D_i spareActiveTopics_d (nnzPerRow);\n\n    prevTopicCount_d.fill(-1);\n    double maxDiff = N;\n    int iter = 0;\n    int Kactive = K;\n    double ACTIVE_THR = 1e-9;\n    double totalLogSumResp = 0.0;\n    double sum_gammalnalphaEbeta = 0.0;\n    if (doTrackELBO || numRestarts > 0) {\n        for (int k = 0; k < K; k++) {\n            sum_gammalnalphaEbeta += boost::math::lgamma(alphaEbeta(k));\n        }\n    }\n    // Before any updates... All topics are active!\n    for (int k = 0; k < K; k++) {\n        activeTopics_d(k) = k;\n    }\n    if (verbose > 1) {\n        printf(\"Initial topic counts \\n\");\n        for (int k = 0; k < K; k++) {\n            printf(\"%d:%6.1f \", k, topicCount_d(k));\n        }\n        printf(\"\\n\");\n    }\n\n    for (iter = 0; iter < nCoordAscentIterLP; iter++) {\n        int doReviseActiveSet;\n        if (iter >= REVISE_FIRST && Kactive <= nnzPerRow) {\n            // Set of active docs is already very small,\n            // so nothing big to gain from revising\n            doReviseActiveSet = 0;\n        } else if (iter < REVISE_FIRST || (iter - 1) % REVISE_EVERY == 0) {\n            doReviseActiveSet = 1;\n        } else {\n            doReviseActiveSet = 0;\n        }\n\n        if (iter > 0 || initProbsToEbeta < 0) {\n            if (doReviseActiveSet) {\n                int newKactive = 0;\n                int ia = 0; // index for spare inactive topics\n                for (int a = 0; a < Kactive; a++) {\n                    int k = activeTopics_d(a);\n                    if (topicCount_d(k) > ACTIVE_THR) {\n                        activeTopics_d(newKactive) = k;\n                        prevTopicCount_d(k) = topicCount_d(k);\n                        newKactive += 1;\n                    } else if (newKactive < nnzPerRow - ia) {\n                        spareActiveTopics_d(ia) = k;\n                        ia += 1;\n                    }\n                }\n                // If num topics above threshold is less than nnzPerRow,\n                // We need to fill in with some spare empty topics.\n                Kactive = newKactive;\n                while (Kactive < nnzPerRow) {\n                    int k = spareActiveTopics_d(Kactive - newKactive);\n                    activeTopics_d(Kactive) = k;\n                    Kactive++;\n                }\n            } else {\n                for (int a = 0; a < Kactive; a++) {\n                    int k = activeTopics_d(a);\n                    prevTopicCount_d(k) = topicCount_d(k);\n                }\n            }\n        }\n        assert(Kactive >= nnzPerRow);\n        assert(Kactive <= K);\n        if (nnzPerRow == 1 || doReviseActiveSet) {\n            totalLogSumResp = updateAssignments_ActiveOnly(\n                ElogLik_d, wc_d, alphaEbeta, activeTopics_d,\n                topicCount_d, ElogProb_d,\n                logScores_n, tempScores_n,\n                spResp_data, spResp_colids,\n                N, K, Kactive, nnzPerRow, \n                iter, initProbsToEbeta, doTrackELBO\n                );\n        } else {\n            totalLogSumResp = updateAssignments_FixPerTokenActiveSet(\n                ElogLik_d, wc_d, alphaEbeta, activeTopics_d,\n                topicCount_d, ElogProb_d,\n                logScores_n,\n                spResp_data, spResp_colids,\n                N, K, Kactive, nnzPerRow, \n                doTrackELBO\n                );\n        }\n\n        if (doTrackELBO) {\n            elboVec(iter) = calcELBOForSingleDoc_V1(\n                alphaEbeta, topicCount_d, ElogProb_d, activeTopics_d,\n                totalLogSumResp, sum_gammalnalphaEbeta, Kactive);\n            /*\n            double elboV2 = calcELBOForSingleDoc_V2(\n                alphaEbeta, topicCount_d, spResp_data, spResp_colids,\n                ElogLik_d, K, N, nnzPerRow);\n            \n            double elboV1 = calcELBOForSingleDoc_V1(\n                alphaEbeta, topicCount_d, ElogProb_d, activeTopics_d,\n                totalLogSumResp, sum_gammalnalphaEbeta, Kactive);\n            printf(\" V1: %.6f\\n V2: %.6f\\n\", elboV2, elboV1);\n            */\n        }\n\n        if (verbose > 1) {\n            printf(\"end of iter %3d Kactive %3d maxDiff %10.6f\\n\", \n                iter, Kactive, maxDiff);\n            for (int ka = 0; ka < Kactive; ka++) {\n                int k = activeTopics_d(ka);\n                printf(\"%d:%6.1f \", k, topicCount_d(k));\n            }\n            printf(\"\\n\");\n        }\n\n        // END ITERATION. Decide whether to quit early\n        if (iter > 0 && iter % 5 == 0) {\n            double absDiff_k = 0.0;\n            maxDiff = 0.0;\n            for (int ka = 0; ka < Kactive; ka++) {\n                int k = activeTopics_d(ka);\n                absDiff_k = abs(prevTopicCount_d(k) - topicCount_d(k));\n                if (absDiff_k > maxDiff) {\n                    maxDiff = absDiff_k;\n                }\n            }\n            if (maxDiff <= convThrLP) {\n                break;\n            }\n        }\n    }\n\n    // Figure out which topics are eligible for sparse restarts\n    double smallThr = 1e-6;\n    double curELBO = 0.0;\n    for (int riter = 0; riter < numRestarts; riter++) {\n        if (riter == 0) {\n            totalLogSumResp = updateAssignments_ActiveOnly(\n                ElogLik_d, wc_d, alphaEbeta, activeTopics_d,\n                topicCount_d, ElogProb_d,\n                logScores_n, tempScores_n,\n                spResp_data, spResp_colids,\n                N, K, Kactive, nnzPerRow, \n                0, 0, 1);\n            curELBO = calcELBOForSingleDoc_V1(\n                alphaEbeta, topicCount_d, ElogProb_d, activeTopics_d,\n                totalLogSumResp, sum_gammalnalphaEbeta, Kactive);\n            // Remember the best-known topic-count vector!\n            for (int k = 0; k < K; k++) {\n                prevTopicCount_d(k) = topicCount_d(k);\n            }\n        }\n        // SEARCH FOR SMALLEST TOPIC HAVE NOT YET TRIED YET\n        int numAboveThr = 0;\n        double minVal = N + 1.0; // topicCount_d must never have this value\n        int minLoc = 0;\n        for (int ka = 0; ka < Kactive; ka++) {\n            int k = activeTopics_d(ka);\n            if (topicCount_d(k) > smallThr) {\n                numAboveThr += 1;\n                if (topicCount_d(k) < minVal) {\n                    minVal = topicCount_d(k);\n                    minLoc = k;\n                }\n            }\n        }\n        if (numAboveThr == 1) {\n            break;\n        }\n\n        if (verbose) {\n            printf(\"START: best known counts. ELBO=%.5e \\n\", curELBO);\n            for (int ka = 0; ka < Kactive; ka++) {\n                int k = activeTopics_d(ka);\n                printf(\"%02d:%06.2f \", k, topicCount_d(k));\n            }\n            printf(\"\\n\");\n        }\n        smallThr = minVal;\n        topicCount_d(minLoc) = 0.0;\n        if (verbose) {        \n            printf(\n                \"RESTART: Set index %d to zero (%d left)\\n\", \n                minLoc, numAboveThr - 1);\n            for (int ka = 0; ka < Kactive; ka++) {\n                int k = activeTopics_d(ka);\n                printf(\"%02d:%06.2f \", k, topicCount_d(k));\n            }\n            printf(\"\\n\");\n        }\n        int NSTEP = 2;\n        for (int step = 0; step < NSTEP; step++) {        \n            totalLogSumResp = updateAssignments_ActiveOnly(\n                ElogLik_d, wc_d, alphaEbeta, activeTopics_d,\n                topicCount_d, ElogProb_d,\n                logScores_n, tempScores_n,\n                spResp_data, spResp_colids,\n                N, K, Kactive, nnzPerRow, \n                step, 0, step == NSTEP-1);\n        }\n        // If the change is small, abandon this\n        double propELBO;\n        if (abs(prevTopicCount_d(minLoc) -topicCount_d(minLoc)) < 1e-6) {\n            propELBO = curELBO;\n        } else {\n            propELBO = calcELBOForSingleDoc_V1(\n                alphaEbeta, topicCount_d, ElogProb_d, activeTopics_d,\n                totalLogSumResp, sum_gammalnalphaEbeta, Kactive);\n        }\n\n        if (verbose) {\n            for (int ka = 0; ka < Kactive; ka++) {\n                int k = activeTopics_d(ka);\n                printf(\"%02d:%06.2f \", k, topicCount_d(k));\n            }\n            printf(\"\\n\");\n            printf(\"propELBO % .6e\\n\", propELBO);\n            printf(\" curELBO % .6e\\n\", curELBO);\n            if (propELBO > curELBO) {\n                printf(\"beforeCount: %.6f\\n\", prevTopicCount_d(minLoc));\n                printf(\" afterCount: %.6f\\n\", topicCount_d(minLoc));\n                printf(\"gainELBO % .6e  *** ACCEPTED \\n\", propELBO - curELBO);\n            } else {\n                printf(\"gainELBO % .6e      rejected \\n\", propELBO - curELBO);\n            }\n        }\n        // If accepted, set current best doc-topic counts to latest proposal\n        // Otherwise, reset the starting point for the next proposal.\n        if (propELBO > curELBO) {\n            curELBO = propELBO;\n            for (int ka = 0; ka < Kactive; ka++) {\n                int k = activeTopics_d(ka);\n                prevTopicCount_d(k) = topicCount_d(k);\n            }\n            rAcceptVec(0) += 1;\n        } else {\n            for (int ka = 0; ka < Kactive; ka++) {\n                int k = activeTopics_d(ka);\n                topicCount_d(k) = prevTopicCount_d(k);\n            }\n        }\n        rTrialVec(0) += 1;\n    }\n    if (numRestarts > 0) {\n        for (int ka = 0; ka < Kactive; ka++) {\n            int k = activeTopics_d(ka);\n            topicCount_d(k) = prevTopicCount_d(k);\n        }\n        // Final update! Make sure spResp reflects best topicCounts found\n        updateAssignments_ActiveOnly(\n            ElogLik_d, wc_d, alphaEbeta, activeTopics_d,\n            topicCount_d, ElogProb_d,\n            logScores_n, tempScores_n,\n            spResp_data, spResp_colids,\n            N, K, Kactive, nnzPerRow, \n            0, 0, 0);\n    }\n    maxDiffVec(d) = maxDiff;\n    numIterVec(d) = iter; // will already have +1 from last iter of for loop\n}\n\n\nvoid sparseLocalStepSingleDoc(\n        double* ElogLik_d_IN,\n        double* alphaEbeta_IN,\n        int nnzPerRow,\n        int N,\n        int K,\n        int nCoordAscentIterLP,\n        double convThrLP,\n        int initProbsToEbeta,\n        double* topicCount_d_OUT,\n        double* spResp_data_OUT,\n        int* spResp_colids_OUT,\n        int d,\n        int D,\n        int* numIterVec_OUT,\n        double* maxDiffVec_OUT\n        )\n{\n    // Unpack inputs, treated as fixed constants\n    ExtArr2D_d ElogLik_d (ElogLik_d_IN, N, K);\n    ExtArr1D_d alphaEbeta (alphaEbeta_IN, K);\n    // Unpack outputs\n    ExtArr1D_d spResp_data (spResp_data_OUT, N * nnzPerRow);\n    ExtArr1D_i spResp_colids (spResp_colids_OUT, N * nnzPerRow);\n    ExtArr1D_d topicCount_d (topicCount_d_OUT, K);\n\n    ExtArr1D_i numIterVec (numIterVec_OUT, D);\n    ExtArr1D_d maxDiffVec (maxDiffVec_OUT, D);\n\n    // Temporary storage\n    Arr1D_d ElogProb_d (K);\n    Arr1D_d prevTopicCount_d (K);\n    Arr1D_d logScores_n (K);\n    Arr1D_d tempScores_n (K);\n\n    prevTopicCount_d.fill(-1);\n    double maxDiff = N;\n    int iter = 0;\n\n    for (iter = 0; iter < nCoordAscentIterLP + initProbsToEbeta; iter++) {\n\n        if (iter == 0 and initProbsToEbeta == 1) {\n            for (int k = 0; k < K; k++) {\n                ElogProb_d(k) = log(alphaEbeta(k));\n            }\n        } else {\n            for (int k = 0; k < K; k++) {\n                ElogProb_d(k) = boost::math::digamma(\n                    topicCount_d(k) + alphaEbeta(k));\n            }\n        }\n    \n        topicCount_d.fill(0);\n        // Step over each data atom\n        for (int n = 0; n < N; n++) {\n            int m = n * nnzPerRow;\n            int argmax_n = 0;\n            logScores_n(0) = ElogProb_d(0) + ElogLik_d(n,0);\n            double maxScore_n = logScores_n(0);\n            for (int k = 1; k < K; k++) {\n                logScores_n(k) = ElogProb_d(k) + ElogLik_d(n,k);\n                if (logScores_n(k) > maxScore_n) {\n                    maxScore_n = logScores_n(k);\n                    argmax_n = k;\n                }\n            }\n            if (nnzPerRow == 1) {\n                spResp_data(m) = 1.0;\n                spResp_colids(m) = argmax_n;\n                // Update topicCount_d\n                topicCount_d(argmax_n) += 1.0;\n            } else {\n                // Find the top L entries in logScores_n\n                // Copy current row over into a temp buffer\n                std::copy(\n                    logScores_n.data(),\n                    logScores_n.data() + K,\n                    tempScores_n.data());\n                // Sort the data in the temp buffer (in place)\n                std::nth_element(\n                    tempScores_n.data(),\n                    tempScores_n.data() + K - nnzPerRow,\n                    tempScores_n.data() + K);\n                // Walk thru this row and find the top \"nnzPerRow\" positions\n                double pivotScore = tempScores_n(K - nnzPerRow);\n                int nzk = 0;\n                double sumResp_n = 0.0;\n                for (int k = 0; k < K; k++) {\n                    if (logScores_n(k) >= pivotScore) {\n                        spResp_data(m + nzk) = \\\n                            exp(logScores_n(k) - maxScore_n);\n                        spResp_colids(m + nzk) = k;\n                        sumResp_n += spResp_data(m + nzk);\n                        nzk += 1;\n                    }\n                }\n                // Normalize for doc-topic counts\n                for (int nzk = 0; nzk < nnzPerRow; nzk++) {\n                    spResp_data(m + nzk) /= sumResp_n;\n                    topicCount_d(spResp_colids(m + nzk)) += \\\n                        spResp_data(m + nzk);\n                }\n            }\n        }\n        // END ITERATION. Decide whether to quit early\n        if (iter > 0 && iter % 5 == 0) {\n            double absDiff_k = 0.0;\n            maxDiff = 0.0;\n            for (int k = 0; k < K; k++) {\n                absDiff_k = abs(prevTopicCount_d(k) - topicCount_d(k));\n                if (absDiff_k > maxDiff) {\n                    maxDiff = absDiff_k;\n                }\n                prevTopicCount_d(k) = topicCount_d(k); // copy over\n            }\n            if (maxDiff <= convThrLP) {\n                break;\n            }\n        }\n    }\n    maxDiffVec(d) = maxDiff;\n    numIterVec(d) = iter + 1;\n}\n\n\nvoid sparseLocalStepSingleDocWithWordCounts(\n        double* wordcounts_d_IN,\n        double* ElogLik_d_IN,\n        double* alphaEbeta_IN,\n        int nnzPerRow,\n        int N,\n        int K,\n        int nCoordAscentIterLP,\n        double convThrLP,\n        int initProbsToEbeta,\n        double* topicCount_d_OUT,\n        double* spResp_data_OUT,\n        int* spResp_colids_OUT\n        )\n{\n    // Unpack inputs, treated as fixed constants\n    ExtArr1D_d wc_d (wordcounts_d_IN, N);\n    ExtArr2D_d ElogLik_d (ElogLik_d_IN, N, K);\n    ExtArr1D_d alphaEbeta (alphaEbeta_IN, K);\n    // Unpack outputs\n    ExtArr1D_d spResp_data (spResp_data_OUT, N * nnzPerRow);\n    ExtArr1D_i spResp_colids (spResp_colids_OUT, N * nnzPerRow);\n    ExtArr1D_d topicCount_d (topicCount_d_OUT, K);\n    // Temporary storage\n    VectorXd ElogProb_d (K);\n    VectorXd prevTopicCount_d (K);\n    VectorXd logScores_n (K);\n    VectorXd tempScores_n (K);\n    prevTopicCount_d.fill(-1);\n    int iter = 0;\n    double maxDiff = 0.0;\n    for (iter = 0; iter < nCoordAscentIterLP + initProbsToEbeta; iter++) {\n\n        if (iter == 0 and initProbsToEbeta == 1) {\n            for (int k = 0; k < K; k++) {\n                ElogProb_d(k) = log(alphaEbeta(k));\n            }\n        } else {\n            for (int k = 0; k < K; k++) {\n                ElogProb_d(k) = boost::math::digamma(\n                    topicCount_d(k) + alphaEbeta(k));\n            }\n        }\n    \n        topicCount_d.fill(0);\n        // Step over each data atom\n        for (int n = 0; n < N; n++) {\n            int m = n * nnzPerRow;\n            int argmax_n = 0;\n            logScores_n(0) = ElogProb_d(0) + ElogLik_d(n,0);\n            double maxScore_n = logScores_n(0);\n            for (int k = 1; k < K; k++) {\n                logScores_n(k) = ElogProb_d(k) + ElogLik_d(n,k);\n                if (logScores_n(k) > maxScore_n) {\n                    maxScore_n = logScores_n(k);\n                    argmax_n = k;\n                }\n            }\n            if (nnzPerRow == 1) {\n                spResp_data(m) = 1.0;\n                spResp_colids(m) = argmax_n;\n                // Update topicCount_d\n                topicCount_d(argmax_n) += wc_d(n);\n            } else {\n                // Find the top L entries in logScores_n\n                // Copy current row over into a temp buffer\n                std::copy(\n                    logScores_n.data(),\n                    logScores_n.data() + K,\n                    tempScores_n.data());\n                // Sort the data in the temp buffer (in place)\n                std::nth_element(\n                    tempScores_n.data(),\n                    tempScores_n.data() + K - nnzPerRow,\n                    tempScores_n.data() + K);\n                // Walk thru this row and find the top \"nnzPerRow\" positions\n                double pivotScore = tempScores_n(K - nnzPerRow);\n                int nzk = 0;\n                double sumResp_n = 0.0;\n                for (int k = 0; k < K; k++) {\n                    if (logScores_n(k) >= pivotScore) {\n                        spResp_data(m + nzk) = \\\n                            exp(logScores_n(k) - maxScore_n);\n                        spResp_colids(m + nzk) = k;\n                        sumResp_n += spResp_data(m + nzk);\n                        nzk += 1;\n                    }\n                }\n                // Normalize for doc-topic counts\n                for (int nzk = 0; nzk < nnzPerRow; nzk++) {\n                    spResp_data(m + nzk) /= sumResp_n;\n                    topicCount_d(spResp_colids(m + nzk)) += \\\n                        wc_d(n) * spResp_data(m + nzk);\n                }\n            }\n        }\n        // END ITERATION. Decide whether to quit early\n        if (iter > 0 && iter % 5 == 0) {\n            double absDiff_k = 0.0;\n            maxDiff = 0.0;\n            for (int k = 0; k < K; k++) {\n                absDiff_k = abs(prevTopicCount_d(k) - topicCount_d(k));\n                if (absDiff_k > maxDiff) {\n                    maxDiff = absDiff_k;\n                }\n                prevTopicCount_d(k) = topicCount_d(k); // copy over\n            }\n            if (maxDiff <= convThrLP) {\n                break;\n            }\n        }\n    }\n}\n\n\n\n", "meta": {"hexsha": "1aec3cf6d91cd3b5a13a308d1cfbe1edd4c9d6c7", "size": 29394, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bnpy/util/lib/sparseResp/TopicModelLocalStepCPPX.cpp", "max_stars_repo_name": "jun2tong/bnp-anomaly", "max_stars_repo_head_hexsha": "c7fa106b5bb29ed6688a3d91e3f302a0a130b896", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 184.0, "max_stars_repo_stars_event_min_datetime": "2016-12-13T21:05:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T11:47:23.000Z", "max_issues_repo_path": "bnpy/util/lib/sparseResp/TopicModelLocalStepCPPX.cpp", "max_issues_repo_name": "jun2tong/bnp-anomaly", "max_issues_repo_head_hexsha": "c7fa106b5bb29ed6688a3d91e3f302a0a130b896", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2016-12-18T14:07:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T10:58:14.000Z", "max_forks_repo_path": "bnpy/util/lib/sparseResp/TopicModelLocalStepCPPX.cpp", "max_forks_repo_name": "jun2tong/bnp-anomaly", "max_forks_repo_head_hexsha": "c7fa106b5bb29ed6688a3d91e3f302a0a130b896", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 50.0, "max_forks_repo_forks_event_min_datetime": "2017-01-25T19:44:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T10:22:01.000Z", "avg_line_length": 34.0602549247, "max_line_length": 79, "alphanum_fraction": 0.5104443084, "num_tokens": 8106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2854221884228205}}
{"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_DISCRETIZATIONS_BLOCK_SWIPDG_HH\n#define DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BLOCK_SWIPDG_HH\n\n#include <memory>\n#include <algorithm>\n#include <vector>\n#include <map>\n#include <set>\n#include <cmath>\n#include <limits>\n#include <type_traits>\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <dune/stuff/common/disable_warnings.hh>\n# if HAVE_EIGEN\n#   include <Eigen/Eigenvalues>\n# endif\n\n# include <dune/common/timer.hh>\n# include <dune/common/dynmatrix.hh>\n\n# if HAVE_ALUGRID\n#   include <dune/grid/alugrid.hh>\n# endif\n\n# include <dune/geometry/quadraturerules.hh>\n#include <dune/stuff/common/reenable_warnings.hh>\n\n#include <dune/grid/multiscale/provider.hh>\n\n#include <dune/stuff/common/logging.hh>\n#include <dune/stuff/common/configuration.hh>\n#include <dune/stuff/common/float_cmp.hh>\n#include <dune/stuff/common/fixed_map.hh>\n#include <dune/stuff/grid/layers.hh>\n#include <dune/stuff/grid/boundaryinfo.hh>\n#include <dune/stuff/functions/constant.hh>\n#include <dune/stuff/functions/interfaces.hh>\n#include <dune/stuff/la/container.hh>\n#include <dune/stuff/la/solver.hh>\n#include <dune/stuff/grid/walker.hh>\n\n#include <dune/pymor/common/exceptions.hh>\n\n#include <dune/gdt/spaces/discontinuouslagrange.hh>\n#include <dune/gdt/playground/spaces/block.hh>\n#include <dune/gdt/playground/localevaluation/swipdg.hh>\n#include <dune/gdt/discretefunction/default.hh>\n#include <dune/gdt/operators/oswaldinterpolation.hh>\n#include <dune/gdt/operators/projections.hh>\n#include <dune/gdt/playground/spaces/finitevolume/default.hh>\n#include <dune/gdt/playground/spaces/raviartthomas/pdelab.hh>\n#include <dune/gdt/playground/operators/fluxreconstruction.hh>\n#include <dune/gdt/playground/products/swipdgpenalty.hh>\n#include <dune/gdt/products/boundaryl2.hh>\n#include <dune/gdt/products/l2.hh>\n#include <dune/gdt/products/h1.hh>\n#include <dune/gdt/products/elliptic.hh>\n#include <dune/gdt/assembler/system.hh>\n\n#include <dune/hdd/linearelliptic/problems/default.hh>\n#include <dune/hdd/linearelliptic/problems/zero-boundary.hh>\n\n#include \"base.hh\"\n#include \"swipdg.hh\"\n\nnamespace Dune {\nnamespace HDD {\nnamespace LinearElliptic {\nnamespace Discretizations {\n\n\n// forward, needed in the Traits\ntemplate< class GridImp, class RangeFieldImp, int rangeDim, int polynomialOrder = 1\n        , Stuff::LA::ChooseBackend la_backend = Stuff::LA::default_sparse_backend >\nclass BlockSWIPDG;\n\n\nnamespace internal {\n\n\ntemplate< class GridType, class RangeFieldType, int dimRange, int polOrder, Stuff::LA::ChooseBackend la_backend >\nclass LocalDiscretizationsContainer\n{\n  typedef grid::Multiscale::ProviderInterface< GridType > GridProviderType;\npublic:\n  typedef SWIPDG< GridType, Stuff::Grid::ChooseLayer::local, RangeFieldType, dimRange\n                , polOrder, GDT::ChooseSpaceBackend::fem, la_backend > DiscretizationType;\n  typedef SWIPDG< GridType, Stuff::Grid::ChooseLayer::local_oversampled, RangeFieldType, dimRange\n                , polOrder, GDT::ChooseSpaceBackend::fem, la_backend > OversampledDiscretizationType;\n  typedef typename DiscretizationType::ProblemType     ProblemType;\n  typedef typename DiscretizationType::TestSpaceType   TestSpaceType;\n  typedef typename DiscretizationType::AnsatzSpaceType AnsatzSpaceType;\n\nprivate:\n  typedef Problems::ZeroBoundary< ProblemType > FakeProblemType;\n  typedef typename DiscretizationType::GridViewType::Intersection IntersectionType;\n\npublic:\n  LocalDiscretizationsContainer(const GridProviderType& grid_provider,\n                                const ProblemType& prob,\n                                const std::vector< std::string >& only_these_products)\n    : zero_boundary_problem_(prob)\n    , all_dirichlet_boundary_config_(Stuff::Grid::BoundaryInfos::AllDirichlet< IntersectionType >::default_config())\n    , all_neumann_boundary_config_(Stuff::Grid::BoundaryInfos::AllNeumann< IntersectionType >::default_config())\n    , multiscale_boundary_config_(Stuff::Grid::BoundaryInfoConfigs::IdBased::default_config())\n    , local_discretizations_(grid_provider.num_subdomains(), nullptr)\n    , oversampled_discretizations_dirichlet_(grid_provider.num_subdomains(), nullptr)\n    , oversampled_discretizations_neumann_(grid_provider.num_subdomains(), nullptr)\n    , local_test_spaces_(grid_provider.num_subdomains(), nullptr)\n    , local_ansatz_spaces_(grid_provider.num_subdomains(), nullptr)\n  {\n    multiscale_boundary_config_[\"neumann\"] = \"7\";\n    for (size_t ss = 0; ss < grid_provider.num_subdomains(); ++ss) {\n      local_discretizations_[ss] = std::make_shared< DiscretizationType >(grid_provider,\n                                                                          all_neumann_boundary_config_,\n                                                                          zero_boundary_problem_,\n                                                                          ss,\n                                                                          only_these_products);\n      local_test_spaces_[ss] = local_discretizations_[ss]->test_space();\n      local_ansatz_spaces_[ss] = local_discretizations_[ss]->ansatz_space();\n    }\n  }\n\nprotected:\n  const FakeProblemType zero_boundary_problem_;\n  const Stuff::Common::Configuration all_dirichlet_boundary_config_;\n  const Stuff::Common::Configuration all_neumann_boundary_config_;\n  Stuff::Common::Configuration multiscale_boundary_config_;\n  std::vector< std::shared_ptr< DiscretizationType > > local_discretizations_;\n  mutable std::vector< std::shared_ptr< OversampledDiscretizationType > > oversampled_discretizations_dirichlet_;\n  mutable std::vector< std::shared_ptr< OversampledDiscretizationType > > oversampled_discretizations_neumann_;\n  std::vector< std::shared_ptr< const TestSpaceType > > local_test_spaces_;\n  std::vector< std::shared_ptr< const AnsatzSpaceType > > local_ansatz_spaces_;\n}; // class LocalDiscretizationsContainer\n\n\ntemplate< class GridImp, class RangeFieldImp, int rangeDim, int polynomialOrder, Stuff::LA::ChooseBackend la_backend >\nclass BlockSWIPDGTraits\n  : public ContainerBasedDefaultTraits< typename Stuff::LA::Container< RangeFieldImp, la_backend >::MatrixType,\n                                        typename Stuff::LA::Container< RangeFieldImp, la_backend >::VectorType >\n{\npublic:\n  typedef BlockSWIPDG< GridImp, RangeFieldImp, rangeDim, polynomialOrder, la_backend > derived_type;\n  typedef GridImp GridType;\n  typedef RangeFieldImp     RangeFieldType;\n  static const unsigned int dimRange = rangeDim;\n  static const unsigned int polOrder = polynomialOrder;\nprivate:\n  friend class BlockSWIPDG< GridImp, RangeFieldImp, rangeDim, polynomialOrder, la_backend >;\n  typedef grid::Multiscale::ProviderInterface< GridType > GridProviderType;\n  typedef LocalDiscretizationsContainer< GridType, RangeFieldType, dimRange, polOrder, la_backend >\n      LocalDiscretizationsContainerType;\n  typedef typename LocalDiscretizationsContainerType::TestSpaceType   LocalTestSpaceType;\n  typedef typename LocalDiscretizationsContainerType::AnsatzSpaceType LocalAnsatzSpaceType;\npublic:\n  typedef GDT::Spaces::Block< LocalTestSpaceType >   TestSpaceType;\n  typedef GDT::Spaces::Block< LocalAnsatzSpaceType > AnsatzSpaceType;\n  typedef typename TestSpaceType::GridViewType GridViewType;\n}; // class BlockSWIPDGTraits\n\n\n} // namespace internal\n\n\n/**\n * \\attention The given problem is replaced by a Problems::ZeroBoundary.\n * \\attention The given boundary info config is replaced by a Stuff::Grid::BoundaryInfos::AllDirichlet.\n * \\attention The boundary info for the local oversampled discretizations is hardwired to dirichlet zero atm!\n */\ntemplate< class GridImp, class RangeFieldImp, int rangeDim, int polynomialOrder, Stuff::LA::ChooseBackend la_backend >\nclass BlockSWIPDG\n  : internal::LocalDiscretizationsContainer< GridImp, RangeFieldImp, rangeDim, polynomialOrder, la_backend >\n  , public ContainerBasedDefault< internal::BlockSWIPDGTraits< GridImp, RangeFieldImp, rangeDim\n                                                             , polynomialOrder, la_backend > >\n\n{\n  typedef internal::LocalDiscretizationsContainer< GridImp, RangeFieldImp, rangeDim, polynomialOrder, la_backend >\n    LocalDiscretizationsBaseType;\n  typedef ContainerBasedDefault< internal::BlockSWIPDGTraits< GridImp, RangeFieldImp, rangeDim\n                                                            , polynomialOrder, la_backend > > BaseType;\n  typedef BlockSWIPDG< GridImp, RangeFieldImp, rangeDim, polynomialOrder, la_backend >        ThisType;\npublic:\n  typedef internal::BlockSWIPDGTraits< GridImp, RangeFieldImp, rangeDim, polynomialOrder, la_backend > Traits;\n  typedef typename BaseType::ProblemType     ProblemType;\n  typedef typename BaseType::GridViewType    GridViewType;\n  typedef typename BaseType::TestSpaceType   TestSpaceType;\n  typedef typename BaseType::AnsatzSpaceType AnsatzSpaceType;\n  typedef typename BaseType::EntityType      EntityType;\n  typedef typename BaseType::DomainFieldType DomainFieldType;\n  typedef typename BaseType::RangeFieldType  RangeFieldType;\n  typedef typename BaseType::MatrixType      MatrixType;\n  typedef typename BaseType::VectorType      VectorType;\n  typedef typename BaseType::OperatorType    OperatorType;\n  typedef typename BaseType::ProductType     ProductType;\n  typedef typename BaseType::FunctionalType  FunctionalType;\n\n  static const unsigned int dimDomain = BaseType::dimDomain;\n  static const unsigned int dimRange  = BaseType::dimRange;\n\n  typedef grid::Multiscale::ProviderInterface< GridImp > GridProviderType;\n  typedef typename GridProviderType::GridType   GridType;\n  typedef typename GridProviderType::MsGridType MsGridType;\n\n  typedef typename Traits::LocalDiscretizationsContainerType::DiscretizationType            LocalDiscretizationType;\n  typedef typename Traits::LocalDiscretizationsContainerType::OversampledDiscretizationType OversampledDiscretizationType;\n  typedef typename TestSpaceType::PatternType PatternType;\n\nprivate:\n  using typename BaseType::AffinelyDecomposedMatrixType;\n  using typename BaseType::AffinelyDecomposedVectorType;\n  typedef Pymor::LA::AffinelyDecomposedConstContainer< MatrixType > AffinelyDecomposedConstMatrixType;\n  typedef Pymor::LA::AffinelyDecomposedConstContainer< VectorType > AffinelyDecomposedConstVectorType;\n\npublic:\n  typedef typename LocalDiscretizationType::ProblemType LocalProblemType;\n  typedef typename LocalDiscretizationType::ProductType LocalProductType;\n\n  static std::string static_id()\n  {\n    return DiscretizationInterface< Traits >::static_id() + \".block-swipdg\";\n  }\n\n  BlockSWIPDG(const GridProviderType& grid_provider,\n              const Stuff::Common::Configuration& /*bound_inf_cfg*/,\n              const ProblemType& prob,\n              const std::vector< std::string >& only_these_products = {})\n    : LocalDiscretizationsBaseType(grid_provider, prob, only_these_products)\n    , BaseType(std::make_shared< TestSpaceType >(grid_provider.ms_grid(), this->local_test_spaces_),\n               std::make_shared< AnsatzSpaceType >(grid_provider.ms_grid(), this->local_ansatz_spaces_),\n               this->all_dirichlet_boundary_config_,\n               this->zero_boundary_problem_)\n    , grid_provider_(grid_provider)\n    , ms_grid_(grid_provider.ms_grid())\n    , only_these_products_(only_these_products)\n    , pattern_(BaseType::test_space()->mapper().size())\n    , local_matrices_(ms_grid_->size())\n    , local_vectors_(ms_grid_->size())\n    , inside_outside_patterns_(ms_grid_->size())\n    , outside_inside_patterns_(ms_grid_->size())\n    , inside_outside_matrices_(ms_grid_->size())\n    , outside_inside_matrices_(ms_grid_->size())\n  {\n    // in case of parametric diffusion tensor everything is too complicated\n    if (this->problem_.diffusion_tensor()->parametric())\n      DUNE_THROW(NotImplemented, \"The diffusion tensor must not be parametric!\");\n    if (!this->problem_.diffusion_tensor()->has_affine_part())\n      DUNE_THROW(Stuff::Exceptions::wrong_input_given, \"The diffusion tensor must not be empty!\");\n  } // BlockSWIPDG(...)\n\n  const std::vector< std::shared_ptr< LocalDiscretizationType > >& local_discretizations() const\n  {\n    return this->local_discretizations_;\n  }\n\n  void init(std::ostream& out = Stuff::Common::Logger().devnull(), const std::string prefix = \"\")\n  {\n    if (!this->container_based_initialized_) {\n      const size_t subdomains = ms_grid_->size();\n      // walk the subdomains for the first time\n      //   * to initialize the coupling pattern,\n      //   * to finalize the global sparsity pattern\n      out << prefix << \"walking subdomains for the first time... \" << std::flush;\n      Dune::Timer timer;\n      for (size_t ss = 0; ss < subdomains; ++ss) {\n        // init the local discretizations (assembles matrices and patterns)\n        this->local_discretizations_[ss]->init();\n        // and create the local containers\n        // * the matrices\n        //   * just copy those from the local discretizations\n        const auto local_operator = this->local_discretizations_[ss]->get_operator();\n        local_matrices_[ss] = std::make_shared< AffinelyDecomposedMatrixType >();\n        //   * we take the affine part only if the diffusion has one, otherwise it contains only the dirichlet rows,\n        //     thus it is empty, since the local problems are purely neumann\n        if (this->problem().diffusion_factor()->has_affine_part()) {\n          if (!local_operator.has_affine_part())\n            DUNE_THROW(Stuff::Exceptions::internal_error, \"The local operator is missing the affine part!\");\n          local_matrices_[ss]->register_affine_part(new MatrixType(*(local_operator.affine_part().container())));\n        }\n        if (local_operator.num_components() < this->problem().diffusion_factor()->num_components())\n          DUNE_THROW(Stuff::Exceptions::requirements_not_met,\n                     \"The local operator should have \" << this->problem().diffusion_factor()->num_components()\n                     << \" components (but has only \" << local_operator.num_components() << \")!\");\n        for (DUNE_STUFF_SSIZE_T qq = 0; qq < this->problem().diffusion_factor()->num_components(); ++qq)\n          local_matrices_[ss]->register_component(new MatrixType(\n              local_operator.component(qq).container()->backend()),\n              this->problem().diffusion_factor()->coefficient(qq));\n        // * and the vectors\n        const auto local_functional = this->local_discretizations_[ss]->get_rhs();\n        local_vectors_[ss] = std::make_shared< AffinelyDecomposedVectorType >();\n        for (size_t qq = 0; qq < boost::numeric_cast< size_t >(local_functional.num_components()); ++qq)\n          local_vectors_[ss]->register_component(new VectorType(*(local_functional.component(qq).container())),\n                                                 new Pymor::ParameterFunctional(local_functional.coefficient(qq)));\n        if (local_functional.has_affine_part())\n          local_vectors_[ss]->register_affine_part(new VectorType(*(local_functional.affine_part().container())));\n\n        // create and copy the local patterns\n        add_local_to_global_pattern(this->local_discretizations_[ss]->pattern(), ss, ss, pattern_);\n        const auto& inner_test_space = *(this->local_discretizations_[ss]->test_space());\n        const auto& inner_ansatz_space = *(this->local_discretizations_[ss]->ansatz_space());\n        // walk the neighbors\n        for (const size_t& nn : ms_grid_->neighborsOf(ss)) {\n          // visit each coupling only once (assemble primally)\n          if (ss < nn) {\n            const auto& outer_test_space = *(this->local_discretizations_[nn]->test_space());\n            const auto& outer_ansatz_space = *(this->local_discretizations_[nn]->ansatz_space());\n            const auto inside_outside_grid_part = ms_grid_->couplingGridPart(ss, nn);\n            const auto outside_inside_grid_part = ms_grid_->couplingGridPart(nn, ss);\n            // create the coupling patterns\n            auto inside_outside_pattern = std::make_shared< PatternType >(\n                  inner_test_space.compute_face_pattern(inside_outside_grid_part, outer_ansatz_space));\n            inside_outside_patterns_[ss].insert(std::make_pair(nn, inside_outside_pattern));\n            auto outside_inside_pattern = std::make_shared< PatternType >(\n                  outer_test_space.compute_face_pattern(outside_inside_grid_part, inner_ansatz_space));\n            outside_inside_patterns_[nn].insert(std::make_pair(ss, outside_inside_pattern));\n            // and copy them\n            add_local_to_global_pattern(*inside_outside_pattern,  ss, nn, pattern_);\n            add_local_to_global_pattern(*outside_inside_pattern,  nn, ss, pattern_);\n          } // visit each coupling only once (assemble primaly)\n        } // walk the neighbors\n      } // walk the subdomains for the first time\n      out<< \"done (took \" << timer.elapsed() << \" sek)\" << std::endl;\n\n      // walk the subdomains for the second time\n      //   * to assemble the boundary matrices and vectors and\n      //   * to assemble the coupling matrices\n      out << prefix << \"walking subdomains for the second time... \" << std::flush;\n      for (size_t ss = 0; ss < ms_grid_->size(); ++ss) {\n        const auto& inner_test_mapper = this->local_discretizations_[ss]->test_space()->mapper();\n        const auto& inner_ansatz_mapper = this->local_discretizations_[ss]->ansatz_space()->mapper();\n        if (ms_grid_->boundary(ss))\n          assemble_boundary_contributions(ss);\n        // walk the neighbors\n        for (const size_t& nn : ms_grid_->neighborsOf(ss)) {\n          // visit each coupling only once (assemble primaly)\n          if (ss < nn) {\n            const auto& outer_test_mapper = this->local_discretizations_[nn]->test_space()->mapper();\n            const auto& outer_ansatz_mapper = this->local_discretizations_[nn]->ansatz_space()->mapper();\n            // get the patterns\n            const auto in_out_result = inside_outside_patterns_[ss].find(nn);\n            if (in_out_result == inside_outside_patterns_[ss].end())\n              DUNE_THROW(Stuff::Exceptions::internal_error, \"subdomain \" << ss << \", neighbour \" << nn);\n            const auto& inside_outside_pattern = *(in_out_result->second);\n            const auto out_in_result = outside_inside_patterns_[nn].find(ss);\n            if (out_in_result == outside_inside_patterns_[nn].end())\n              DUNE_THROW(Stuff::Exceptions::internal_error, \"subdomain \" << ss << \", neighbour \" << nn);\n            const auto& outside_inside_pattern = *(out_in_result->second);\n            // create the coupling matrices\n            auto inside_outside_matrix = std::make_shared< AffinelyDecomposedMatrixType >();\n            auto outside_inside_matrix = std::make_shared< AffinelyDecomposedMatrixType >();\n            if (this->problem().diffusion_factor()->has_affine_part()) {\n              inside_outside_matrix->register_affine_part(new MatrixType(inner_test_mapper.size(),\n                                                                         outer_ansatz_mapper.size(),\n                                                                         inside_outside_pattern));\n              outside_inside_matrix->register_affine_part(new MatrixType(outer_test_mapper.size(),\n                                                                         inner_ansatz_mapper.size(),\n                                                                         outside_inside_pattern));\n            }\n            for (DUNE_STUFF_SSIZE_T qq = 0; qq < this->problem().diffusion_factor()->num_components(); ++qq) {\n              inside_outside_matrix->register_component(new MatrixType(inner_test_mapper.size(),\n                                                                       outer_ansatz_mapper.size(),\n                                                                       inside_outside_pattern),\n                                                        this->problem().diffusion_factor()->coefficient(qq));\n              outside_inside_matrix->register_component(new MatrixType(outer_test_mapper.size(),\n                                                                       inner_ansatz_mapper.size(),\n                                                                       outside_inside_pattern),\n                                                        this->problem().diffusion_factor()->coefficient(qq));\n            }\n            // and assemble them\n            assemble_coupling_contributions(ss, nn,\n                                            *(local_matrices_[ss]),\n                                            *(inside_outside_matrix),\n                                            *(outside_inside_matrix),\n                                            *(local_matrices_[nn]));\n            inside_outside_matrices_[ss].insert(std::make_pair(nn, inside_outside_matrix));\n            outside_inside_matrices_[nn].insert(std::make_pair(ss, outside_inside_matrix));\n          } // visit each coupling only once\n        } // walk the neighbors\n      } // walk the subdomains for the second time\n      out<< \"done (took \" << timer.elapsed() << \" sek)\" << std::endl;\n\n      // build global containers\n      pattern_.sort();\n      build_global_containers();\n\n      // products\n      typedef typename MsGridType::GlobalGridPartType::GridViewType GlobalGridViewType;\n      const auto global_grid_part = ms_grid_->globalGridPart();\n      const auto global_grid_view = global_grid_part.gridView();\n      GDT::SystemAssembler< TestSpaceType, GlobalGridViewType, AnsatzSpaceType > system_assembler(*this->test_space(),\n                                                                                                  *this->ansatz_space(),\n                                                                                                  global_grid_view);\n      const size_t over_integrate = 2;\n      // * L2\n      typedef GDT::Products::L2Assemblable< MatrixType, TestSpaceType, GlobalGridViewType, AnsatzSpaceType >\n          L2ProductType;\n      std::unique_ptr< L2ProductType > l2_product;\n      auto l2_product_matrix = std::make_shared< AffinelyDecomposedMatrixType >();\n      if (std::find(only_these_products_.begin(), only_these_products_.end(), \"l2\") != only_these_products_.end()) {\n        l2_product_matrix->register_affine_part(this->test_space()->mapper().size(),\n                                                this->ansatz_space()->mapper().size(),\n                                                L2ProductType::pattern(*this->test_space(),\n                                                                       *this->ansatz_space()));\n        l2_product = DSC::make_unique< L2ProductType >(*(l2_product_matrix->affine_part()),\n                                                       *this->test_space(),\n                                                       global_grid_view,\n                                                       *this->ansatz_space(),\n                                                       over_integrate);\n        system_assembler.add(*l2_product);\n      }\n      // * H1 semi\n      typedef GDT::Products::H1SemiAssemblable< MatrixType, TestSpaceType, GlobalGridViewType, AnsatzSpaceType >\n          H1ProductType;\n      std::unique_ptr< H1ProductType > h1_product;\n      auto h1_product_matrix = std::make_shared< AffinelyDecomposedMatrixType >();\n      if (std::find(only_these_products_.begin(), only_these_products_.end(), \"h1_semi\") != only_these_products_.end()) {\n        h1_product_matrix->register_affine_part(this->test_space()->mapper().size(),\n                                                this->ansatz_space()->mapper().size(),\n                                                H1ProductType::pattern(*this->test_space(),\n                                                                       *this->ansatz_space()));\n        h1_product = DSC::make_unique< H1ProductType >(*(h1_product_matrix->affine_part()),\n                                                       *this->test_space(),\n                                                       global_grid_view,\n                                                       *this->ansatz_space(),\n                                                       over_integrate);\n        system_assembler.add(*h1_product);\n      }\n      // * elliptic\n      typedef typename ProblemType::DiffusionFactorType::NonparametricType DiffusionFactorType;\n      typedef typename ProblemType::DiffusionTensorType::NonparametricType DiffusionTensorType;\n      const auto diffusion_factor = this->problem().diffusion_factor();\n      const auto diffusion_tensor = this->problem().diffusion_tensor();\n      assert(!diffusion_tensor->parametric());\n      typedef GDT::Products::EllipticAssemblable< MatrixType, DiffusionFactorType, TestSpaceType, GlobalGridViewType,\n                                                  AnsatzSpaceType, RangeFieldType, DiffusionTensorType >\n          EllipticProductType;\n      std::vector< std::unique_ptr< EllipticProductType > > elliptic_products;\n      auto elliptic_product_matrix = std::make_shared< AffinelyDecomposedMatrixType >();\n      if (std::find(only_these_products_.begin(), only_these_products_.end(), \"elliptic\") != only_these_products_.end()) {\n        for (DUNE_STUFF_SSIZE_T qq = 0; qq < diffusion_factor->num_components(); ++qq) {\n          const auto id = elliptic_product_matrix->register_component(diffusion_factor->coefficient(qq),\n                                                                      this->test_space()->mapper().size(),\n                                                                      this->ansatz_space()->mapper().size(),\n                                                                      EllipticProductType::pattern(*this->test_space(),\n                                                                                                   *this->ansatz_space()));\n          elliptic_products.emplace_back(new EllipticProductType(*elliptic_product_matrix->component(id),\n                                                                 *this->test_space(),\n                                                                 global_grid_view,\n                                                                 *this->ansatz_space(),\n                                                                 *diffusion_factor->component(qq),\n                                                                 *diffusion_tensor->affine_part(),\n                                                                 over_integrate));\n        }\n        if (diffusion_factor->has_affine_part()) {\n          elliptic_product_matrix->register_affine_part(this->test_space()->mapper().size(),\n                                                        this->ansatz_space()->mapper().size(),\n                                                        EllipticProductType::pattern(*this->test_space(),\n                                                                                     *this->ansatz_space()));\n          elliptic_products.emplace_back(new EllipticProductType(*elliptic_product_matrix->affine_part(),\n                                                                 *this->test_space(),\n                                                                 global_grid_view,\n                                                                 *this->ansatz_space(),\n                                                                 *diffusion_factor->affine_part(),\n                                                                 *diffusion_tensor->affine_part(),\n                                                                 over_integrate));\n        }\n        for (auto& product : elliptic_products)\n          system_assembler.add(*product);\n      }\n      // * boundary L2\n      typedef GDT::Products::BoundaryL2Assemblable< MatrixType, TestSpaceType, GlobalGridViewType, AnsatzSpaceType >\n          BoundaryL2ProductType;\n      std::unique_ptr< BoundaryL2ProductType > boundary_l2_product;\n      auto boundary_l2_product_matrix = std::make_shared< AffinelyDecomposedMatrixType >();\n      if (std::find(only_these_products_.begin(), only_these_products_.end(), \"boundary_l2\") != only_these_products_.end()) {\n        boundary_l2_product_matrix->register_affine_part(this->test_space()->mapper().size(),\n                                                         this->ansatz_space()->mapper().size(),\n                                                         BoundaryL2ProductType::pattern(*this->test_space(),\n                                                                                        *this->ansatz_space()));\n        boundary_l2_product = DSC::make_unique< BoundaryL2ProductType >(*(boundary_l2_product_matrix->affine_part()),\n                                                                        *this->test_space(),\n                                                                        global_grid_view,\n                                                                        *this->ansatz_space(),\n                                                                        over_integrate);\n        system_assembler.add(*boundary_l2_product);\n      }\n      // * penalty term\n      typedef GDT::Products::SwipdgPenaltyAssemblable\n          < MatrixType, DiffusionFactorType, DiffusionTensorType, TestSpaceType > PenaltyProductType;\n      std::vector< std::unique_ptr< PenaltyProductType > > penalty_products;\n      auto penalty_product_matrix = std::make_shared< AffinelyDecomposedMatrixType >();\n      if (std::find(only_these_products_.begin(), only_these_products_.end(), \"penalty\") != only_these_products_.end()) {\n        for (DUNE_STUFF_SSIZE_T qq = 0; qq < diffusion_factor->num_components(); ++qq) {\n          const auto id = penalty_product_matrix->register_component(diffusion_factor->coefficient(qq),\n                                                                     this->test_space()->mapper().size(),\n                                                                     this->ansatz_space()->mapper().size(),\n                                                                     PenaltyProductType::pattern(*this->test_space(),\n                                                                                                 *this->ansatz_space()));\n          penalty_products.emplace_back(new PenaltyProductType(*penalty_product_matrix->component(id),\n                                                               *this->test_space(),\n                                                               global_grid_view,\n                                                               *this->ansatz_space(),\n                                                               *diffusion_factor->component(qq),\n                                                               *diffusion_tensor->affine_part(),\n                                                               over_integrate));\n        }\n        if (diffusion_factor->has_affine_part()) {\n          penalty_product_matrix->register_affine_part(this->test_space()->mapper().size(),\n                                                       this->ansatz_space()->mapper().size(),\n                                                       PenaltyProductType::pattern(*this->test_space(),\n                                                                                   *this->ansatz_space()));\n          penalty_products.emplace_back(new PenaltyProductType(*penalty_product_matrix->affine_part(),\n                                                               *this->test_space(),\n                                                               global_grid_view,\n                                                               *this->ansatz_space(),\n                                                               *diffusion_factor->affine_part(),\n                                                               *diffusion_tensor->affine_part(),\n                                                               over_integrate));\n        }\n        for (auto& product : penalty_products)\n          system_assembler.add(*product);\n      }\n\n      // do the actual work\n      system_assembler.assemble();\n\n      // finalize\n      this->inherit_parameter_type(*(this->matrix_), \"lhs\");\n      this->inherit_parameter_type(*(this->rhs_), \"rhs\");\n      if (std::find(only_these_products_.begin(), only_these_products_.end(), \"l2\") != only_these_products_.end())\n        this->products_.insert(std::make_pair(\"l2\", l2_product_matrix));\n      if (std::find(only_these_products_.begin(), only_these_products_.end(), \"h1_semi\") != only_these_products_.end())\n        this->products_.insert(std::make_pair(\"h1_semi\", h1_product_matrix));\n      if (std::find(only_these_products_.begin(), only_these_products_.end(), \"elliptic\") != only_these_products_.end())\n        this->products_.insert(std::make_pair(\"elliptic\", elliptic_product_matrix));\n      if (std::find(only_these_products_.begin(), only_these_products_.end(), \"boundary_l2\") != only_these_products_.end())\n        this->products_.insert(std::make_pair(\"boundary_l2\", boundary_l2_product_matrix));\n      if (std::find(only_these_products_.begin(), only_these_products_.end(), \"penalty\") != only_these_products_.end())\n        this->products_.insert(std::make_pair(\"penalty\", penalty_product_matrix));\n      if (std::find(only_these_products_.begin(), only_these_products_.end(), \"energy\") != only_these_products_.end())\n        this->products_.insert(std::make_pair(\"energy\",\n                                              std::make_shared< AffinelyDecomposedMatrixType >(this->matrix_->copy())));\n      this->container_based_initialized_ = true;\n    } // if (!this->container_based_initialized_)\n  } // ... init(...)\n\n  DUNE_STUFF_SSIZE_T num_subdomains() const\n  {\n    return ms_grid_->size();\n  }\n\n  std::vector< DUNE_STUFF_SSIZE_T > neighbouring_subdomains(const DUNE_STUFF_SSIZE_T ss) const\n  {\n    if (ss < 0 || ss >= num_subdomains())\n      DUNE_THROW(Stuff::Exceptions::index_out_of_range,\n                 \"0 <= ss < num_subdomains() = \" << num_subdomains() << \" is not true for ss = \" << ss << \"!\");\n    const auto set_of_neighbours = ms_grid_->neighborsOf(ss);\n    return std::vector< DUNE_STUFF_SSIZE_T >(set_of_neighbours.begin(), set_of_neighbours.end());\n  }\n\n  VectorType localize_vector(const VectorType& global_vector, const size_t ss) const\n  {\n    if ((std::make_signed< size_t >::type)(ss) >= num_subdomains())\n      DUNE_THROW(Stuff::Exceptions::index_out_of_range,\n                 \"0 <= ss < num_subdomains() = \" << num_subdomains() << \" is not true for ss = \" << ss << \"!\");\n    if (global_vector.size() != this->ansatz_space()->mapper().size())\n      DUNE_THROW(Stuff::Exceptions::index_out_of_range,\n                 \"The size() of global_vector (\" << global_vector.dim()\n                 << \") does not match the size() of the ansatz space (\" << this->ansatz_space()->mapper().size() << \")!\");\n    assert(ss < this->local_discretizations_.size());\n    VectorType local_vector = this->local_discretizations_[ss]->create_vector();\n    for (size_t ii = 0; ii < local_vector.size(); ++ii)\n      local_vector.set_entry(ii, global_vector.get_entry(this->ansatz_space()->mapper().mapToGlobal(ss, ii)));\n    return local_vector;\n  } // ... localize_vetor(...)\n\n  VectorType globalize_vectors(const std::vector< VectorType >& local_vectors) const\n  {\n    if (local_vectors.size() != boost::numeric_cast< size_t >(num_subdomains()))\n      DUNE_THROW(Stuff::Exceptions::wrong_input_given,\n                 \"Given local_vectors has wrong size (is \" << local_vectors.size() << \", should be \"\n                 << num_subdomains() << \")!\");\n    VectorType ret(this->ansatz_space()->mapper().size());\n    for (size_t ss = 0; ss < boost::numeric_cast< size_t >(num_subdomains()); ++ss) {\n      const auto& local_vector = local_vectors[ss];\n      if (local_vector.size() != this->local_discretizations_[ss]->ansatz_space()->mapper().size())\n        DUNE_THROW(Stuff::Exceptions::wrong_input_given,\n                   \"Given local_vectors[\" << ss << \"] has wrong size (is \"\n                   << local_vector.size() << \", should be \"\n                   << this->local_discretizations_[ss]->ansatz_space()->mapper().size() << \")!\");\n      copy_local_to_global_vector(local_vector, ss, ret);\n    }\n    return ret;\n  }\n\n  VectorType* globalize_vectors_and_return_ptr(const std::vector< VectorType >& local_vectors) const\n  {\n    return new VectorType(globalize_vectors(local_vectors));\n  }\n\n  VectorType* localize_vector_and_return_ptr(const VectorType& global_vector, const DUNE_STUFF_SSIZE_T ss) const\n  {\n    return new VectorType(localize_vector(global_vector, boost::numeric_cast< size_t >(ss)));\n  }\n\n  ProductType get_local_product(const size_t ss, const std::string id) const\n  {\n    if (boost::numeric_cast< DUNE_STUFF_SSIZE_T >(ss) >= num_subdomains())\n      DUNE_THROW(Stuff::Exceptions::index_out_of_range,\n                 \"0 <= ss < num_subdomains() = \" << num_subdomains() << \" is not true for ss = \" << ss << \"!\");\n    return this->local_discretizations_[ss]->get_product(id);\n  }\n\n  ProductType* get_local_product_and_return_ptr(const DUNE_STUFF_SSIZE_T ss, const std::string id) const\n  {\n    return new ProductType(get_local_product(boost::numeric_cast< size_t >(ss), id));\n  }\n\n  OperatorType get_local_operator(const size_t ss) const\n  {\n    if (boost::numeric_cast< DUNE_STUFF_SSIZE_T >(ss) >= num_subdomains())\n      DUNE_THROW(Stuff::Exceptions::index_out_of_range,\n                 \"0 <= ss < num_subdomains() = \" << num_subdomains() << \" is not true for ss = \" << ss << \"!\");\n    assert(ss < local_matrices_.size());\n    return OperatorType(*(local_matrices_[ss]));\n  }\n\n  OperatorType* get_local_operator_and_return_ptr(const DUNE_STUFF_SSIZE_T ss) const\n  {\n    return new OperatorType(get_local_operator(boost::numeric_cast< size_t >(ss)));\n  }\n\n  OperatorType get_coupling_operator(const size_t ss, const size_t nn) const\n  {\n    if (ss >= boost::numeric_cast< size_t >(num_subdomains()))\n      DUNE_THROW(Stuff::Exceptions::index_out_of_range,\n                 \"0 <= ss < num_subdomains() = \" << num_subdomains() << \" is not true for ss = \" << ss << \"!\");\n    const auto neighbours = ms_grid_->neighborsOf(ss);\n    if (neighbours.count(nn) == 0)\n      DUNE_THROW(Stuff::Exceptions::index_out_of_range,\n                 \"Subdomain \" << nn << \" is not a neighbour of subdomain \" << ss\n                 << \" (call neighbouring_subdomains(\" << ss << \") to find out)!\");\n    if (ss < nn) {\n      // we need to look for this coupling operator in the inside/outside context\n      const auto result_inside_outside_matrix = inside_outside_matrices_[ss].find(nn);\n      if (result_inside_outside_matrix == inside_outside_matrices_[ss].end())\n        DUNE_THROW(Stuff::Exceptions::internal_error,\n                   \"The coupling matrix for subdomain \" << ss << \" and neighbour \" << nn << \" is missing!\");\n      const auto inside_outside_matrix = result_inside_outside_matrix->second;\n      return OperatorType(*inside_outside_matrix);\n    } else if (nn < ss) {\n      // we need to look for this coupling operator in the outside/inside context\n      const auto result_outside_inside_matrix = outside_inside_matrices_[ss].find(nn);\n      if (result_outside_inside_matrix == outside_inside_matrices_[ss].end())\n        DUNE_THROW(Stuff::Exceptions::internal_error,\n                   \"The coupling matrix for neighbour \" << nn << \" and subdomain \" << ss << \" is missing!\");\n      const auto outside_inside_matrix = result_outside_inside_matrix->second;\n      return OperatorType(*outside_inside_matrix);\n    } else {\n      // the above exception should have cought this\n      DUNE_THROW(Stuff::Exceptions::internal_error,\n                 \"The multiscale grid is corrupted! Subdomain \" << ss << \" must not be its own neighbour!\");\n    }\n  } // ... get_coupling_operator(...)\n\n  OperatorType* get_coupling_operator_and_return_ptr(const DUNE_STUFF_SSIZE_T ss, const DUNE_STUFF_SSIZE_T nn) const\n  {\n    return new OperatorType(get_coupling_operator(boost::numeric_cast< size_t >(ss),\n                                                  boost::numeric_cast< size_t >(nn)));\n  }\n\n  FunctionalType get_local_functional(const size_t ss) const\n  {\n    if (ss >= boost::numeric_cast< size_t >(num_subdomains()))\n      DUNE_THROW(Stuff::Exceptions::index_out_of_range,\n                 \"0 <= ss < num_subdomains() = \" << num_subdomains() << \" is not true for ss = \" << ss << \"!\");\n    assert(ss < local_vectors_.size());\n    return FunctionalType(*(local_vectors_[ss]));\n  }\n\n  FunctionalType* get_local_functional_and_return_ptr(const DUNE_STUFF_SSIZE_T ss) const\n  {\n    return new FunctionalType(get_local_functional(boost::numeric_cast< size_t >(ss)));\n  }\n\n  VectorType solve_for_local_correction(const std::vector< VectorType >& local_vectors,\n                                        const size_t subdomain,\n                                        const Pymor::Parameter mu = Pymor::Parameter()) const\n  {\n    DUNE_THROW(Stuff::Exceptions::internal_error, \"Do not call this method, I do not trust it!\");\n    using namespace GDT;\n\n    if (mu.type() != this->parameter_type())\n      DUNE_THROW(Pymor::Exceptions::wrong_parameter_type,\n                 \"mu is \" << mu.type() << \", should be \" << this->parameter_type() << \"!\");\n    if (local_vectors.size() != ms_grid_->size())\n      DUNE_THROW(Stuff::Exceptions::wrong_input_given,\n                 \"local_vectors is of size \" << local_vectors.size() << \" and should be of size \" << ms_grid_->size());\n    VectorType vector(this->ansatz_space()->mapper().size());\n    for (size_t ss = 0; ss < ms_grid_->size(); ++ss) {\n      if (local_vectors[ss].size() != this->local_discretizations_[ss]->ansatz_space()->mapper().size())\n        DUNE_THROW(Stuff::Exceptions::wrong_input_given,\n                   \"local_vectors[\" << ss << \"] is of size \" << local_vectors[ss].size() << \" and should be of size \"\n                   << this->local_discretizations_[ss]->ansatz_space()->mapper().size());\n      if (!local_vectors[ss].valid())\n        DUNE_THROW(Stuff::Exceptions::wrong_input_given, \"local_vectors[\" << ss << \"] contains NaN or INF!\");\n      copy_local_to_global_vector(local_vectors[ss], ss, vector);\n    }\n\n//    const std::string prefix = \"subdomain_\" + DSC::toString(subdomain) + \"_\";\n\n    const ConstDiscreteFunction< AnsatzSpaceType, VectorType > current_global_solution(*this->ansatz_space(), vector);\n//    current_global_solution.visualize(prefix + \"current_solution_global\");\n\n    typedef SWIPDG< typename MsGridType::GridType, Stuff::Grid::ChooseLayer::local_oversampled, RangeFieldType, dimRange\n                  , 1, GDT::ChooseSpaceBackend::fem, la_backend > OversampledDiscretizationType;\n    OversampledDiscretizationType oversampled_discretization(grid_provider_,\n                                                             this->multiscale_boundary_config_,\n                                                             this->problem(),\n                                                             boost::numeric_cast< int >(subdomain));\n    oversampled_discretization.init();\n\n    DiscreteFunction< typename OversampledDiscretizationType::AnsatzSpaceType, VectorType >\n        current_oversampled_solution(*oversampled_discretization.ansatz_space());\n    const Operators::Projection< typename OversampledDiscretizationType::GridViewType >\n        oversampled_projection_operator(oversampled_discretization.grid_view());\n    oversampled_projection_operator.apply(current_global_solution, current_oversampled_solution);\n//    current_oversampled_solution.visualize(prefix + \"current_solution_oversampled\");\n\n    if (!oversampled_discretization.rhs()->has_affine_part())\n      oversampled_discretization.rhs()->register_affine_part(oversampled_discretization.test_space()->mapper().size());\n    if (oversampled_discretization.system_matrix()->parametric()) {\n      const auto oversampled_system_matrix = oversampled_discretization.system_matrix()->freeze_parameter(mu);\n      *(oversampled_discretization.rhs()->affine_part())\n          -= oversampled_system_matrix * current_oversampled_solution.vector();\n    } else {\n      const auto& oversampled_system_matrix = *(oversampled_discretization.system_matrix()->affine_part());\n      *(oversampled_discretization.rhs()->affine_part())\n          -= oversampled_system_matrix * current_oversampled_solution.vector();\n    }\n\n    oversampled_discretization.solve(current_oversampled_solution.vector(), mu);\n//    current_oversampled_solution.visualize(prefix + \"correction_oversampled\");\n\n    DiscreteFunction< typename LocalDiscretizationType::AnsatzSpaceType, VectorType >\n        local_solution(*this->local_discretizations_[subdomain]->ansatz_space());\n    const Operators::Projection< typename LocalDiscretizationType::GridViewType >\n        local_projection_operator(this->local_discretizations_[subdomain]->grid_view());\n    local_projection_operator.apply(current_oversampled_solution, local_solution);\n//    local_solution.visualize(prefix + \"correction_local\");\n\n    return local_solution.vector();\n  } // ... solve_for_local_correction(...)\n\n  LocalDiscretizationType get_local_discretization(const size_t subdomain) const\n  {\n    if (subdomain >= this->grid_provider_.num_subdomains())\n      DUNE_THROW(Stuff::Exceptions::index_out_of_range,\n                 \"Given subdomain \" << subdomain << \" too large (has to be smaller than \"\n                 << this->grid_provider_.num_subdomains() << \"!\");\n    return *(this->local_discretizations_[subdomain]);\n  } // ... get_local_discretization(...)\n\n  LocalDiscretizationType* pb_get_local_discretization(const ssize_t subdomain) const\n  {\n    size_t ss = std::numeric_limits< size_t >::max();\n    try {\n      ss = boost::numeric_cast< size_t >(subdomain);\n    } catch (boost::bad_numeric_cast& ee) {\n      DUNE_THROW(Stuff::Exceptions::index_out_of_range,\n                 \"There was an error in boost converting \" << subdomain << \" to \"\n                 << Stuff::Common::Typename< size_t >::value() << \":\\n\\n\" << ee.what());\n    }\n    return new LocalDiscretizationType(get_local_discretization(ss));\n  } // ... pb_get_local_discretization(...)\n\n  OversampledDiscretizationType get_oversampled_discretization(const size_t subdomain,\n                                                               const std::string boundary_value_type) const\n  {\n    if (subdomain >= this->grid_provider_.num_subdomains())\n      DUNE_THROW(Stuff::Exceptions::index_out_of_range,\n                 \"Given subdomain \" << subdomain << \" too large (has to be smaller than \"\n                 << this->grid_provider_.num_subdomains() << \"!\");\n    if (boundary_value_type == \"dirichlet\") {\n      if (!this->oversampled_discretizations_dirichlet_[subdomain]) {\n        this->oversampled_discretizations_dirichlet_[subdomain] = std::make_shared< OversampledDiscretizationType >(\n                                                                    grid_provider_,\n                                                                    this->all_dirichlet_boundary_config_,\n                                                                    this->zero_boundary_problem_,\n                                                                    subdomain,\n                                                                    only_these_products_);\n        this->oversampled_discretizations_dirichlet_[subdomain]->init();\n      }\n      return *(this->oversampled_discretizations_dirichlet_[subdomain]);\n    } else if (boundary_value_type == \"neumann\") {\n      if (!this->oversampled_discretizations_neumann_[subdomain]) {\n        this->oversampled_discretizations_neumann_[subdomain] = std::make_shared< OversampledDiscretizationType >(\n                                                                  grid_provider_,\n                                                                  this->all_neumann_boundary_config_,\n                                                                  this->zero_boundary_problem_,\n                                                                  subdomain,\n                                                                  only_these_products_);\n        this->oversampled_discretizations_neumann_[subdomain]->init();\n      }\n      return *(this->oversampled_discretizations_neumann_[subdomain]);\n    } else {\n      DUNE_THROW(Stuff::Exceptions::wrong_input_given,\n                 \"Unknown boundary_value_type given (has to be dirichlet or neumann): \" << boundary_value_type);\n      return *(this->oversampled_discretizations_dirichlet_[subdomain]);\n    }\n  } // ... get_oversampled_discretization(...)\n\n  OversampledDiscretizationType* pb_get_oversampled_discretization(const ssize_t subdomain,\n                                                                   const std::string boundary_value_type) const\n  {\n    size_t ss = std::numeric_limits< size_t >::max();\n    try {\n      ss = boost::numeric_cast< size_t >(subdomain);\n    } catch (boost::bad_numeric_cast& ee) {\n      DUNE_THROW(Stuff::Exceptions::index_out_of_range,\n                 \"There was an error in boost converting \" << subdomain << \" to \"\n                 << Stuff::Common::Typename< size_t >::value() << \":\\n\\n\" << ee.what());\n    }\n    return new OversampledDiscretizationType(get_oversampled_discretization(ss, boundary_value_type));\n  } // ... pb_get_local_discretization(...)\n\n  OversampledDiscretizationType* pb_get_oversampled_discretization(const ssize_t subdomain,\n                                                                   const std::string boundary_value_type,\n                                                                   const VectorType& boundary_values) const\n  {\n    size_t ss = std::numeric_limits< size_t >::max();\n    try {\n      ss = boost::numeric_cast< size_t >(subdomain);\n    } catch (boost::bad_numeric_cast& ee) {\n      DUNE_THROW(Stuff::Exceptions::index_out_of_range,\n                 \"There was an error in boost converting \" << subdomain << \" to \"\n                 << Stuff::Common::Typename< size_t >::value() << \":\\n\\n\" << ee.what());\n    }\n    return new OversampledDiscretizationType(get_oversampled_discretization(ss, boundary_value_type, boundary_values));\n  } // ... pb_get_local_discretization(...)\n\nprivate:\n  class CouplingAssembler\n  {\n    typedef Dune::DynamicMatrix< RangeFieldType > LocalMatrixType;\n    typedef Dune::DynamicVector< RangeFieldType > LocalVectorType;\n    typedef std::vector< std::vector< LocalMatrixType > > LocalMatricesContainerType;\n    typedef std::vector< std::vector< LocalVectorType > > LocalVectorsContainerType;\n    typedef std::vector< Dune::DynamicVector< size_t > > IndicesContainer;\n\n    typedef typename LocalDiscretizationType::TestSpaceType LocalTestSpaceType;\n    typedef typename LocalDiscretizationType::AnsatzSpaceType LocalAnsatzSpaceType;\n    typedef typename MsGridType::CouplingGridPartType CouplingGridPartType;\n\n    class LocalCodim1MatrixAssemblerApplication\n    {\n    public:\n      virtual ~LocalCodim1MatrixAssemblerApplication(){}\n\n      virtual void apply(const LocalTestSpaceType& /*inner_test_space*/,\n                         const LocalAnsatzSpaceType& /*inner_ansatz_space*/,\n                         const LocalTestSpaceType& /*outer_test_space*/,\n                         const LocalAnsatzSpaceType& /*outer_ansatz_space*/,\n                         const typename CouplingGridPartType::IntersectionType& /*_intersection*/,\n                         LocalMatricesContainerType& /*_localMatricesContainer*/,\n                         IndicesContainer& /*indicesContainer*/) const = 0;\n\n      virtual std::vector< size_t > numTmpObjectsRequired() const = 0;\n    };\n\n    template< class LocalAssemblerType, class M >\n    class LocalCodim1MatrixAssemblerWrapper\n      : public LocalCodim1MatrixAssemblerApplication\n    {\n    public:\n      LocalCodim1MatrixAssemblerWrapper(const LocalAssemblerType& localAssembler,\n                                        Dune::Stuff::LA::MatrixInterface< M >& in_in_matrix,\n                                        Dune::Stuff::LA::MatrixInterface< M >& in_out_matrix,\n                                        Dune::Stuff::LA::MatrixInterface< M >& out_in_matrix,\n                                        Dune::Stuff::LA::MatrixInterface< M >& out_out_matrix)\n        : localMatrixAssembler_(localAssembler)\n        , in_in_matrix_(in_in_matrix)\n        , out_out_matrix_(out_out_matrix)\n        , in_out_matrix_(in_out_matrix)\n        , out_in_matrix_(out_in_matrix)\n      {}\n\n      virtual void apply(const LocalTestSpaceType& inner_test_space,\n                         const LocalAnsatzSpaceType& inner_ansatz_space,\n                         const LocalTestSpaceType& outer_test_space,\n                         const LocalAnsatzSpaceType& outer_ansatz_space,\n                         const typename CouplingGridPartType::IntersectionType& intersection,\n                         LocalMatricesContainerType& localMatricesContainer,\n                         IndicesContainer& indicesContainer) const\n      {\n        localMatrixAssembler_.assembleLocal(inner_test_space, inner_ansatz_space,\n                                            outer_test_space, outer_ansatz_space,\n                                            intersection,\n                                            in_in_matrix_, out_out_matrix_, in_out_matrix_, out_in_matrix_,\n                                            localMatricesContainer, indicesContainer);\n      }\n\n      virtual std::vector< size_t > numTmpObjectsRequired() const\n      {\n        return localMatrixAssembler_.numTmpObjectsRequired();\n      }\n\n    private:\n      const LocalAssemblerType& localMatrixAssembler_;\n      Dune::Stuff::LA::MatrixInterface< M >& in_in_matrix_;\n      Dune::Stuff::LA::MatrixInterface< M >& out_out_matrix_;\n      Dune::Stuff::LA::MatrixInterface< M >& in_out_matrix_;\n      Dune::Stuff::LA::MatrixInterface< M >& out_in_matrix_;\n    }; // class LocalCodim1MatrixAssemblerWrapper\n\n  public:\n    CouplingAssembler(const LocalTestSpaceType& inner_test_space,\n                      const LocalAnsatzSpaceType& inner_ansatz_space,\n                      const LocalTestSpaceType& outer_test_space,\n                      const LocalAnsatzSpaceType& outer_ansatz_space,\n                      const CouplingGridPartType& grid_part)\n      : innerTestSpace_(inner_test_space)\n      , innerAnsatzSpace_(inner_ansatz_space)\n      , outerTestSpace_(outer_test_space)\n      , outerAnsatzSpace_(outer_ansatz_space)\n      , grid_part_(grid_part)\n    {}\n\n    ~CouplingAssembler()\n    {\n      clearLocalAssemblers();\n    }\n\n    void clearLocalAssemblers()\n    {\n      for (auto& element: localCodim1MatrixAssemblers_)\n        delete element;\n    }\n\n    template< class L, class M >\n    void addLocalAssembler(const GDT::LocalAssembler::Codim1CouplingMatrix< L >& localAssembler,\n                           Dune::Stuff::LA::MatrixInterface< M >& in_in_matrix,\n                           Dune::Stuff::LA::MatrixInterface< M >& in_out_matrix,\n                           Dune::Stuff::LA::MatrixInterface< M >& out_in_matrix,\n                           Dune::Stuff::LA::MatrixInterface< M >& out_out_matrix)\n    {\n      assert(in_in_matrix.rows() == innerTestSpace_.mapper().size());\n      assert(in_in_matrix.cols() == innerAnsatzSpace_.mapper().size());\n      assert(in_out_matrix.rows() == innerTestSpace_.mapper().size());\n      assert(in_out_matrix.cols() == outerAnsatzSpace_.mapper().size());\n      assert(out_in_matrix.rows() == outerTestSpace_.mapper().size());\n      assert(out_in_matrix.cols() == innerAnsatzSpace_.mapper().size());\n      assert(out_out_matrix.rows() == outerTestSpace_.mapper().size());\n      assert(out_out_matrix.cols() == outerAnsatzSpace_.mapper().size());\n      localCodim1MatrixAssemblers_.push_back(\n            new LocalCodim1MatrixAssemblerWrapper< GDT::LocalAssembler::Codim1CouplingMatrix< L >, M >(\n              localAssembler, in_in_matrix, in_out_matrix, out_in_matrix, out_out_matrix));\n    }\n\n    void assemble() const\n    {\n      // only do something, if there are local assemblers\n      if (localCodim1MatrixAssemblers_.size() > 0) {\n        // common tmp storage for all entities\n        // * for the matrix assemblers\n        std::vector< size_t > numberOfTmpMatricesNeeded(2, 0);\n        for (auto& localCodim1MatrixAssembler : localCodim1MatrixAssemblers_) {\n          const auto tmp = localCodim1MatrixAssembler->numTmpObjectsRequired();\n          assert(tmp.size() == 2);\n          numberOfTmpMatricesNeeded[0] = std::max(numberOfTmpMatricesNeeded[0], tmp[0]);\n          numberOfTmpMatricesNeeded[1] = std::max(numberOfTmpMatricesNeeded[1], tmp[1]);\n        }\n        const size_t maxLocalSize = std::max(innerTestSpace_.mapper().maxNumDofs(),\n                                             std::max(innerAnsatzSpace_.mapper().maxNumDofs(),\n                                                      std::max(outerTestSpace_.mapper().maxNumDofs(),\n                                                               outerAnsatzSpace_.mapper().maxNumDofs())));\n        std::vector< LocalMatrixType > tmpLocalAssemblerMatrices( numberOfTmpMatricesNeeded[0],\n                                                                  LocalMatrixType(maxLocalSize,\n                                                                                  maxLocalSize,\n                                                                                  RangeFieldType(0)));\n        std::vector< LocalMatrixType > tmpLocalOperatorMatrices(numberOfTmpMatricesNeeded[1],\n                                                                LocalMatrixType(maxLocalSize,\n                                                                                maxLocalSize,\n                                                                                RangeFieldType(0)));\n        std::vector< std::vector< LocalMatrixType > > tmpLocalMatricesContainer;\n        tmpLocalMatricesContainer.push_back(tmpLocalAssemblerMatrices);\n        tmpLocalMatricesContainer.push_back(tmpLocalOperatorMatrices);\n        // * for the global indices\n        std::vector< Dune::DynamicVector< size_t > > tmpIndices = {\n            Dune::DynamicVector< size_t >(maxLocalSize)\n          , Dune::DynamicVector< size_t >(maxLocalSize)\n          , Dune::DynamicVector< size_t >(maxLocalSize)\n          , Dune::DynamicVector< size_t >(maxLocalSize)\n        };\n\n        // walk the grid\n        const auto entityEndIt = grid_part_.template end< 0 >();\n        for(auto entityIt = grid_part_.template begin< 0 >(); entityIt != entityEndIt; ++entityIt ) {\n          const auto& entity = *entityIt;\n          // walk the intersections\n          const auto intersectionEndIt = grid_part_.iend(entity);\n          for (auto intersectionIt = grid_part_.ibegin(entity);\n               intersectionIt != intersectionEndIt;\n               ++intersectionIt) {\n            const auto& intersection = *intersectionIt;\n            // for a coupling grid part, we can be sure to only get the inner coupling intersetcions\n            // so no further check neccesarry than\n            assert(intersection.neighbor() && !intersection.boundary());\n            // call local matrix assemblers\n            for (auto& localCodim1MatrixAssembler : localCodim1MatrixAssemblers_) {\n              localCodim1MatrixAssembler->apply(innerTestSpace_, innerAnsatzSpace_,\n                                                outerTestSpace_, outerAnsatzSpace_,\n                                                intersection,\n                                                tmpLocalMatricesContainer, tmpIndices);\n            }\n          } // walk the intersections\n        } // walk the grid\n      } // only do something, if there are local assemblers\n    } // void assemble() const\n\n  private:\n    const LocalTestSpaceType& innerTestSpace_;\n    const LocalAnsatzSpaceType& innerAnsatzSpace_;\n    const LocalTestSpaceType& outerTestSpace_;\n    const LocalAnsatzSpaceType& outerAnsatzSpace_;\n    const CouplingGridPartType grid_part_;\n    std::vector< LocalCodim1MatrixAssemblerApplication* > localCodim1MatrixAssemblers_;\n  }; // class CouplingAssembler\n\n  void add_local_to_global_pattern(const PatternType& local,\n                                   const size_t test_subdomain,\n                                   const size_t ansatz_subdomain,\n                                   PatternType& global) const\n  {\n    for (size_t local_ii = 0; local_ii < local.size(); ++local_ii) {\n      const size_t global_ii = this->test_space()->mapper().mapToGlobal(test_subdomain, local_ii);\n      const auto& local_rows = local.inner(local_ii);\n      for (const auto& local_jj : local_rows) {\n        const size_t global_jj = this->ansatz_space()->mapper().mapToGlobal(ansatz_subdomain, local_jj);\n        global.insert(global_ii, global_jj);\n      }\n    }\n  } // ... add_local_to_global_pattern(...)\n\n  void copy_local_to_global_matrix(const AffinelyDecomposedConstMatrixType& local_matrix,\n                                   const PatternType& local_pattern,\n                                   const size_t subdomain,\n                                   const size_t neighbor,\n                                   AffinelyDecomposedMatrixType& global_matrix) const\n  {\n    for (size_t qq = 0; qq < boost::numeric_cast< size_t >(local_matrix.num_components()); ++qq) {\n      const auto coefficient = local_matrix.coefficient(qq);\n      ssize_t comp = find_component(global_matrix, *coefficient);\n      if (comp < 0)\n        comp = global_matrix.register_component(coefficient,\n                                                this->test_space()->mapper().size(),\n                                                this->ansatz_space()->mapper().size(),\n                                                pattern_);\n      assert(comp >= 0);\n      copy_local_to_global_matrix(*(local_matrix.component(qq)),\n                                  local_pattern,\n                                  subdomain,\n                                  neighbor,\n                                  *(global_matrix.component(comp)));\n    }\n    if (local_matrix.has_affine_part()) {\n      if (!global_matrix.has_affine_part())\n        global_matrix.register_affine_part(this->test_space_->mapper().size(),\n                                    this->ansatz_space_->mapper().size(),\n                                    pattern_);\n      copy_local_to_global_matrix(*(local_matrix.affine_part()),\n                                  local_pattern,\n                                  subdomain,\n                                  neighbor,\n                                  *(global_matrix.affine_part()));\n    }\n  } // copy_local_to_global_matrix(...)\n\n  template< class ML, class MG >\n  void copy_local_to_global_matrix(const Stuff::LA::MatrixInterface< ML >& local_matrix,\n                                   const PatternType& local_pattern,\n                                   const size_t test_subdomain,\n                                   const size_t ansatz_subdomain,\n                                   Stuff::LA::MatrixInterface< MG >& global_matrix) const\n  {\n    for (size_t local_ii = 0; local_ii < local_pattern.size(); ++local_ii) {\n      const size_t global_ii = this->test_space()->mapper().mapToGlobal(test_subdomain, local_ii);\n      for (const size_t& local_jj : local_pattern.inner(local_ii)) {\n        const size_t global_jj = this->ansatz_space()->mapper().mapToGlobal(ansatz_subdomain, local_jj);\n        global_matrix.add_to_entry(global_ii, global_jj, local_matrix.get_entry(local_ii, local_jj));\n      }\n    }\n  } // ... copy_local_to_global_matrix(...)\n\n  void copy_local_to_global_vector(const AffinelyDecomposedConstVectorType& local_vector,\n                                   const size_t subdomain,\n                                   AffinelyDecomposedVectorType& global_vector) const\n  {\n    for (size_t qq = 0; qq < boost::numeric_cast< size_t >(local_vector.num_components()); ++qq) {\n      const auto coefficient = local_vector.coefficient(qq);\n      ssize_t comp = find_component(global_vector, *coefficient);\n      if (comp < 0)\n        comp = global_vector.register_component(coefficient,\n                                                this->test_space()->mapper().size());\n      assert(comp >= 0);\n      copy_local_to_global_vector(*(local_vector.component(qq)),\n                                  subdomain,\n                                  *(global_vector.component(comp)));\n    }\n    if (local_vector.has_affine_part()) {\n      if (!global_vector.has_affine_part())\n        global_vector.register_affine_part(this->test_space()->mapper().size());\n      copy_local_to_global_vector(*(local_vector.affine_part()),\n                                  subdomain,\n                                  *(global_vector.affine_part()));\n    }\n  } // copy_local_to_global_vector(...)\n\n  template< class VL, class VG >\n  void copy_local_to_global_vector(const Stuff::LA::VectorInterface< VL >& local_vector,\n                                   const size_t subdomain,\n                                   Stuff::LA::VectorInterface< VG >& global_vector) const\n  {\n    for (size_t local_ii = 0; local_ii < local_vector.size(); ++local_ii) {\n      const size_t global_ii = this->test_space()->mapper().mapToGlobal(subdomain, local_ii);\n      global_vector.add_to_entry(global_ii, local_vector.get_entry(local_ii));\n    }\n  } // ... copy_local_to_global_vector(...)\n\n  void assemble_boundary_contributions(const size_t subdomain) const\n  {\n    typedef typename MsGridType::BoundaryGridPartType BoundaryGridPartType;\n    typedef typename LocalDiscretizationType::TestSpaceType   LocalTestSpaceType;\n    typedef typename LocalDiscretizationType::AnsatzSpaceType LocalAnsatzSpaceType;\n    const LocalTestSpaceType&   local_test_space   = *(this->local_discretizations_[subdomain]->test_space());\n    const LocalAnsatzSpaceType& local_ansatz_space = *(this->local_discretizations_[subdomain]->ansatz_space());\n    typedef GDT::SystemAssembler< LocalTestSpaceType, BoundaryGridPartType, LocalAnsatzSpaceType > BoundaryAssemblerType;\n    BoundaryAssemblerType boundary_assembler(local_test_space,\n                                             local_ansatz_space,\n                                             ms_grid_->boundaryGridPart(subdomain));\n\n    auto& local_matrix = *(local_matrices_[subdomain]);\n    auto& local_vector = *(local_vectors_[subdomain]);\n\n    // lhs\n    // * dirichlet boundary terms\n    typedef typename ProblemType::DiffusionFactorType::NonparametricType DiffusionFactorType;\n    typedef typename ProblemType::DiffusionTensorType::NonparametricType DiffusionTensorType;\n    const auto& diffusion_tensor = *(this->problem().diffusion_tensor());\n    assert(!diffusion_tensor.parametric());\n    assert(diffusion_tensor.has_affine_part());\n    typedef GDT::LocalOperator::Codim1BoundaryIntegral< GDT::LocalEvaluation::SWIPDG::BoundaryLHS< DiffusionFactorType, DiffusionTensorType > >\n        DirichletOperatorType;\n    typedef GDT::LocalAssembler::Codim1BoundaryMatrix< DirichletOperatorType > DirichletMatrixAssemblerType;\n    std::vector< DirichletOperatorType* > dirichlet_operators;\n    std::vector< DirichletMatrixAssemblerType* > dirichlet_matrix_assemblers;\n    for (DUNE_STUFF_SSIZE_T qq = 0; qq < this->problem().diffusion_factor()->num_components(); ++qq) {\n      dirichlet_operators.push_back(new DirichletOperatorType(*(this->problem().diffusion_factor()->component(qq)),\n                                                              *(diffusion_tensor.affine_part())));\n      dirichlet_matrix_assemblers.push_back(new DirichletMatrixAssemblerType(*(dirichlet_operators[qq])));\n      boundary_assembler.add(*(dirichlet_matrix_assemblers[qq]),\n                             *(local_matrix.component(qq)),\n                             new Stuff::Grid::ApplyOn::DirichletIntersections< BoundaryGridPartType >(this->boundary_info()));\n    }\n    if (this->problem().diffusion_factor()->has_affine_part()) {\n      dirichlet_operators.push_back(new DirichletOperatorType(*(this->problem().diffusion_factor()->affine_part()),\n                                                              *(diffusion_tensor.affine_part())));\n      dirichlet_matrix_assemblers.push_back(new DirichletMatrixAssemblerType(*(\n          dirichlet_operators[dirichlet_operators.size() - 1])));\n      boundary_assembler.add(*(dirichlet_matrix_assemblers[dirichlet_matrix_assemblers.size() - 1]),\n                             *(local_matrix.affine_part()),\n                             new Stuff::Grid::ApplyOn::DirichletIntersections< BoundaryGridPartType >(this->boundary_info()));\n    }\n\n    // rhs\n    // * neumann boundary terms\n    typedef typename ProblemType::FunctionType::NonparametricType NeumannType;\n    typedef GDT::LocalFunctional::Codim1Integral< GDT::LocalEvaluation::Product< NeumannType > > NeumannFunctionalType;\n    typedef GDT::LocalAssembler::Codim1Vector< NeumannFunctionalType > NeumannVectorAssemblerType;\n    std::vector< NeumannFunctionalType* > neumann_functionals;\n    std::vector< NeumannVectorAssemblerType* > neumann_vector_assemblers;\n    for (DUNE_STUFF_SSIZE_T qq = 0; qq < this->problem().neumann()->num_components(); ++qq) {\n      neumann_functionals.push_back(new NeumannFunctionalType(*(this->problem().neumann()->component(qq))));\n      neumann_vector_assemblers.push_back(new NeumannVectorAssemblerType(*(neumann_functionals[qq])));\n      boundary_assembler.add(*(neumann_vector_assemblers[qq]),\n                             *(local_vector.component(this->problem().force()->num_components() + qq)),\n                             new Stuff::Grid::ApplyOn::NeumannIntersections< BoundaryGridPartType >(this->boundary_info()));\n    }\n    if (this->problem().neumann()->has_affine_part()) {\n      neumann_functionals.push_back(new NeumannFunctionalType(*(this->problem().neumann()->affine_part())));\n      neumann_vector_assemblers.push_back(new NeumannVectorAssemblerType(*(\n          neumann_functionals[neumann_functionals.size() - 1])));\n      boundary_assembler.add(*(neumann_vector_assemblers[neumann_vector_assemblers.size() - 1]),\n                             *(local_vector.affine_part()),\n                             new Stuff::Grid::ApplyOn::NeumannIntersections< BoundaryGridPartType >(this->boundary_info()));\n    }\n\n    // * dirichlet boundary terms\n    typedef typename ProblemType::FunctionType::NonparametricType  DirichletType;\n    typedef GDT::LocalFunctional::Codim1Integral< GDT::LocalEvaluation::SWIPDG::BoundaryRHS< DiffusionFactorType,\n                                                                                             DirichletType,\n                                                                                             DiffusionTensorType > >\n        DirichletFunctionalType;\n    typedef GDT::LocalAssembler::Codim1Vector< DirichletFunctionalType > DirichletVectorAssemblerType;\n    std::vector< DirichletFunctionalType* > dirichlet_functionals;\n    std::vector< DirichletVectorAssemblerType* > dirichlet_vector_assemblers;\n    size_t component_index = this->problem().force()->num_components() + this->problem().neumann()->num_components();\n    if (this->problem().diffusion_factor()->has_affine_part()) {\n      for (DUNE_STUFF_SSIZE_T qq = 0; qq < this->problem().dirichlet()->num_components(); ++qq) {\n        dirichlet_functionals.push_back(new DirichletFunctionalType(*(this->problem().diffusion_factor()->affine_part()),\n                                                                    *(diffusion_tensor.affine_part()),\n                                                                    *(this->problem().dirichlet()->component(qq))));\n        dirichlet_vector_assemblers.push_back(new DirichletVectorAssemblerType(*(\n            dirichlet_functionals[dirichlet_functionals.size() - 1])));\n        boundary_assembler.add(*(dirichlet_vector_assemblers[dirichlet_vector_assemblers.size() - 1]),\n                               *(local_vector.component(component_index)),\n                               new Stuff::Grid::ApplyOn::DirichletIntersections< BoundaryGridPartType >(this->boundary_info()));\n        ++component_index;\n      }\n    }\n    if (this->problem().dirichlet()->has_affine_part()) {\n      for (DUNE_STUFF_SSIZE_T qq = 0; qq < this->problem().diffusion_factor()->num_components(); ++qq) {\n        dirichlet_functionals.push_back(new DirichletFunctionalType(*(this->problem().diffusion_factor()->component(qq)),\n                                                                    *(diffusion_tensor.affine_part()),\n                                                                    *(this->problem().dirichlet()->affine_part())));\n        dirichlet_vector_assemblers.push_back(new DirichletVectorAssemblerType(*(\n            dirichlet_functionals[dirichlet_functionals.size() - 1])));\n        boundary_assembler.add(*(dirichlet_vector_assemblers[dirichlet_vector_assemblers.size() - 1]),\n                               *(local_vector.component(component_index)),\n                               new Stuff::Grid::ApplyOn::DirichletIntersections< BoundaryGridPartType >(this->boundary_info()));\n        ++component_index;\n      }\n    }\n    for (DUNE_STUFF_SSIZE_T pp = 0; pp < this->problem().diffusion_factor()->num_components(); ++ pp) {\n      for (DUNE_STUFF_SSIZE_T qq = 0; qq < this->problem().dirichlet()->num_components(); ++qq) {\n        dirichlet_functionals.push_back(new DirichletFunctionalType(*(this->problem().diffusion_factor()->component(pp)),\n                                                                    *(diffusion_tensor.affine_part()),\n                                                                    *(this->problem().dirichlet()->component(qq))));\n        dirichlet_vector_assemblers.push_back(new DirichletVectorAssemblerType(*(\n            dirichlet_functionals[dirichlet_functionals.size() - 1])));\n        boundary_assembler.add(*(dirichlet_vector_assemblers[dirichlet_vector_assemblers.size() - 1]),\n                               *(local_vector.component(component_index)),\n                               new Stuff::Grid::ApplyOn::DirichletIntersections< BoundaryGridPartType >(this->boundary_info()));\n        ++component_index;\n      }\n    } // dirichlet boundary terms\n\n    // do the actual work\n    boundary_assembler.assemble();\n\n    // clean up\n    for (auto& element : dirichlet_vector_assemblers) delete element;\n    for (auto& element : dirichlet_functionals)       delete element;\n    for (auto& element : neumann_vector_assemblers)   delete element;\n    for (auto& element : neumann_functionals)         delete element;\n    for (auto& element : dirichlet_matrix_assemblers) delete element;\n    for (auto& element : dirichlet_operators)         delete element;\n  } // ... assemble_boundary_contributions(...)\n\n  /**\n   * \\note  We take the matrices as input here becaus we would have to look them up in the maps otherwise. Since that\n   *        has already been done above we save a little.\n   */\n  void assemble_coupling_contributions(const size_t subdomain,\n                                       const size_t neighbour,\n                                       AffinelyDecomposedMatrixType& inside_inside_matrix,\n                                       AffinelyDecomposedMatrixType& inside_outside_matrix,\n                                       AffinelyDecomposedMatrixType& outside_inside_matrix,\n                                       AffinelyDecomposedMatrixType& outside_outside_matrix) const\n  {\n    typedef typename LocalDiscretizationType::TestSpaceType   LocalTestSpaceType;\n    typedef typename LocalDiscretizationType::AnsatzSpaceType LocalAnsatzSpaceType;\n    const LocalTestSpaceType&   inner_test_space   = *(this->local_discretizations_[subdomain]->test_space());\n    const LocalAnsatzSpaceType& inner_ansatz_space = *(this->local_discretizations_[subdomain]->ansatz_space());\n    const LocalTestSpaceType&   outer_test_space   = *(this->local_discretizations_[neighbour]->test_space());\n    const LocalAnsatzSpaceType& outer_ansatz_space = *(this->local_discretizations_[neighbour]->ansatz_space());\n    CouplingAssembler coupling_assembler(inner_test_space, inner_ansatz_space,\n                                         outer_test_space, outer_ansatz_space,\n                                         ms_grid_->couplingGridPart(subdomain, neighbour));\n\n    typedef typename ProblemType::DiffusionFactorType::NonparametricType DiffusionFactorType;\n    typedef typename ProblemType::DiffusionTensorType::NonparametricType DiffusionTensorType;\n    const auto& diffusion_tensor = *(this->problem().diffusion_tensor());\n    assert(!diffusion_tensor.parametric());\n    assert(diffusion_tensor.has_affine_part());\n    typedef GDT::LocalOperator::Codim1CouplingIntegral< GDT::LocalEvaluation::SWIPDG::Inner< DiffusionFactorType,\n                                                                                             DiffusionTensorType > >\n        CouplingOperatorType;\n    typedef GDT::LocalAssembler::Codim1CouplingMatrix< CouplingOperatorType > CouplingMatrixAssemblerType;\n    std::vector< CouplingOperatorType* > coupling_operators;\n    std::vector< CouplingMatrixAssemblerType* > coupling_matrix_assemblers;\n    for (DUNE_STUFF_SSIZE_T qq = 0; qq < this->problem().diffusion_factor()->num_components(); ++qq) {\n      coupling_operators.push_back(new CouplingOperatorType(*(this->problem().diffusion_factor()->component(qq)),\n                                                            *(diffusion_tensor.affine_part())));\n      coupling_matrix_assemblers.push_back(new CouplingMatrixAssemblerType(*(coupling_operators[qq])));\n      coupling_assembler.addLocalAssembler(*(coupling_matrix_assemblers[qq]),\n                                           *(inside_inside_matrix.component(qq)),\n                                           *(inside_outside_matrix.component(qq)),\n                                           *(outside_inside_matrix.component(qq)),\n                                           *(outside_outside_matrix.component(qq)));\n    }\n    if (this->problem().diffusion_factor()->has_affine_part()) {\n      coupling_operators.push_back(new CouplingOperatorType(*(this->problem().diffusion_factor()->affine_part()),\n                                                            *(diffusion_tensor.affine_part())));\n      coupling_matrix_assemblers.push_back(new CouplingMatrixAssemblerType(*(\n          coupling_operators[coupling_operators.size() - 1])));\n      coupling_assembler.addLocalAssembler(*(coupling_matrix_assemblers[coupling_matrix_assemblers.size() - 1]),\n                                           *(inside_inside_matrix.affine_part()),\n                                           *(inside_outside_matrix.affine_part()),\n                                           *(outside_inside_matrix.affine_part()),\n                                           *(outside_outside_matrix.affine_part()));\n    }\n\n    // do the actual work\n    coupling_assembler.assemble();\n\n    // clean up\n    for (auto& element : coupling_matrix_assemblers)  delete element;\n    for (auto& element : coupling_operators)          delete element;\n  } // ... assemble_coupling_contributions(...)\n\n  void build_global_containers()\n  {\n    // walk the subdomains\n    for (size_t ss = 0; ss < ms_grid_->size(); ++ss) {\n\n      copy_local_to_global_matrix(*(local_matrices_[ss]),\n                                  this->local_discretizations_[ss]->pattern(),\n                                  ss,\n                                  ss,\n                                  *(this->matrix_));\n      copy_local_to_global_vector(*(local_vectors_[ss]),\n                                  ss,\n                                  *(this->rhs_));\n\n      // walk the neighbours\n      for (const size_t& nn : ms_grid_->neighborsOf(ss)) {\n        if (ss < nn) {\n          // get the coupling patterns\n          const auto result_inside_outside_pattern = inside_outside_patterns_[ss].find(nn);\n          if (result_inside_outside_pattern == inside_outside_patterns_[ss].end())\n            DUNE_THROW(Stuff::Exceptions::internal_error,\n                       \"The coupling pattern for subdomain \" << ss << \" and neighbour \" << nn << \"is missing!\");\n          const auto& inside_outside_pattern = *(result_inside_outside_pattern->second);\n          const auto result_outside_inside_pattern = outside_inside_patterns_[nn].find(ss);\n          if (result_outside_inside_pattern == outside_inside_patterns_[nn].end())\n            DUNE_THROW(Stuff::Exceptions::internal_error,\n                       \"The coupling pattern for neighbour \" << nn << \" and subdomain \" << ss << \"is missing!\");\n          const auto& outside_inside_pattern = *(result_outside_inside_pattern->second);\n          // and the coupling matrices\n          auto result_inside_outside_matrix = inside_outside_matrices_[ss].find(nn);\n          if (result_inside_outside_matrix == inside_outside_matrices_[ss].end())\n            DUNE_THROW(Stuff::Exceptions::internal_error,\n                       \"The coupling matrix for subdomain \" << ss << \" and neighbour \" << nn << \"is missing!\");\n          auto& inside_outside_matrix = *(result_inside_outside_matrix->second);\n          auto result_outside_inside_matrix = outside_inside_matrices_[nn].find(ss);\n          if (result_outside_inside_matrix == outside_inside_matrices_[nn].end())\n            DUNE_THROW(Stuff::Exceptions::internal_error,\n                       \"The coupling matrix for neighbour \" << nn << \" and subdomain \" << ss << \"is missing!\");\n          auto& outside_inside_matrix = *(result_outside_inside_matrix->second);\n          // and copy them into the global matrix\n          copy_local_to_global_matrix(inside_outside_matrix,\n                                      inside_outside_pattern,\n                                      ss, nn,\n                                      *(this->matrix_));\n          copy_local_to_global_matrix(outside_inside_matrix,\n                                      outside_inside_pattern,\n                                      nn, ss,\n                                      *(this->matrix_));\n        }\n      } // walk the neighbours\n    } // walk the subdomains\n  } // ... build_global_containers(...)\n\n  template< class AffinelyDecomposedContainerType >\n  ssize_t find_component(const AffinelyDecomposedContainerType& container,\n                         const Pymor::ParameterFunctional& coefficient) const\n  {\n    for (size_t qq = 0; qq < boost::numeric_cast< size_t >(container.num_components()); ++qq)\n      if (*(container.coefficient(qq)) == coefficient)\n        return qq;\n    return -1;\n  } // ... find_component(...)\n\n  const GridProviderType& grid_provider_;\n  std::shared_ptr< const MsGridType > ms_grid_;\n  const std::vector< std::string > only_these_products_;\n  PatternType pattern_;\n  std::vector< std::shared_ptr< AffinelyDecomposedMatrixType > > local_matrices_;\n  std::vector< std::shared_ptr< AffinelyDecomposedVectorType > > local_vectors_;\n  std::vector< std::map< size_t, std::shared_ptr< PatternType > > > inside_outside_patterns_;\n  std::vector< std::map< size_t, std::shared_ptr< PatternType > > > outside_inside_patterns_;\n  std::vector< std::map< size_t, std::shared_ptr< AffinelyDecomposedMatrixType > > > inside_outside_matrices_;\n  std::vector< std::map< size_t, std::shared_ptr< AffinelyDecomposedMatrixType > > > outside_inside_matrices_;\n}; // BlockSWIPDG\n\n\n} // namespace Discretizations\n} // namespace LinearElliptic\n} // namespace HDD\n} // namespace Dune\n\n#endif // DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BLOCK_SWIPDG_HH\n", "meta": {"hexsha": "dce21ca9902f1b11d0ac2a48b770edf14afd659c", "size": 83889, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/hdd/linearelliptic/discretizations/block-swipdg.hh", "max_stars_repo_name": "tobiasleibner/dune-hdd", "max_stars_repo_head_hexsha": "35a122c1c6fd019aebbdbb8ee1eb8a36ae2f2b26", "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/hdd/linearelliptic/discretizations/block-swipdg.hh", "max_issues_repo_name": "tobiasleibner/dune-hdd", "max_issues_repo_head_hexsha": "35a122c1c6fd019aebbdbb8ee1eb8a36ae2f2b26", "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/hdd/linearelliptic/discretizations/block-swipdg.hh", "max_forks_repo_name": "tobiasleibner/dune-hdd", "max_forks_repo_head_hexsha": "35a122c1c6fd019aebbdbb8ee1eb8a36ae2f2b26", "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": 59.4957446809, "max_line_length": 143, "alphanum_fraction": 0.6198667287, "num_tokens": 17421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2852681691480611}}
{"text": "// graph-tool -- a general graph modification and manipulation thingy\n//\n// Copyright (C) 2006-2018 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#ifndef GRAPH_REWIRING_HH\n#define GRAPH_REWIRING_HH\n\n#include <tuple>\n#include <iostream>\n#include <boost/functional/hash.hpp>\n\n#include \"graph.hh\"\n#include \"graph_filtering.hh\"\n#include \"graph_util.hh\"\n#include \"sampler.hh\"\n\n#include \"random.hh\"\n\n#include \"hash_map_wrap.hh\"\n\nnamespace graph_tool\n{\nusing namespace std;\nusing namespace boost;\n\ntemplate <class Graph>\ntypename graph_traits<Graph>::vertex_descriptor\nsource(const pair<size_t, bool>& e,\n       const vector<typename graph_traits<Graph>::edge_descriptor>& edges,\n       const Graph& g)\n{\n    if (e.second)\n        return target(edges[e.first], g);\n    else\n        return source(edges[e.first], g);\n}\n\ntemplate <class Graph>\ntypename graph_traits<Graph>::vertex_descriptor\ntarget(const pair<size_t, bool>& e,\n       const vector<typename graph_traits<Graph>::edge_descriptor>& edges,\n       const Graph& g)\n{\n    if (e.second)\n        return source(edges[e.first], g);\n    else\n        return target(edges[e.first], g);\n}\n\n\ntemplate <class Nmap, class Graph>\nvoid add_count(size_t s, size_t t, Nmap& nvmap, Graph& g)\n{\n    if (!graph_tool::is_directed(g) && s > t)\n        std::swap(s, t);\n    auto& nmap = nvmap[s];\n    nmap[t]++;\n}\n\ntemplate <class Nmap, class Graph>\nvoid remove_count(size_t s, size_t t, Nmap& nvmap, Graph& g)\n{\n    if (!graph_tool::is_directed(g) && s > t)\n        std::swap(s, t);\n    auto& nmap = nvmap[s];\n    auto iter = nmap.find(t);\n    iter->second--;\n    if (iter->second == 0)\n        nmap.erase(iter);\n}\n\ntemplate <class Nmap, class Graph>\nsize_t get_count(size_t s, size_t t, Nmap& nvmap, Graph& g)\n{\n    if (!graph_tool::is_directed(g) && s > t)\n        std::swap(s, t);\n    auto& nmap = nvmap[s];\n    auto iter = nmap.find(t);\n    if (iter == nmap.end())\n        return 0;\n    return iter->second;\n    // if (s != t)\n    //     return iter->second;\n    // else\n    //     return iter->second / 2;\n}\n\n// this functor will swap the source of the edge e with the source of edge se\n// and the target of edge e with the target of te\nstruct swap_edge\n{\n    template <class Nmap, class Graph>\n    static bool\n    parallel_check_target (const pair<size_t, bool>& e,\n                           const pair<size_t, bool>& te,\n                           vector<typename graph_traits<Graph>::edge_descriptor>& edges,\n                           Nmap& nmap,\n                           const Graph &g)\n    {\n        // We want to check that if we swap the target of 'e' with the target of\n        // 'te', as such\n        //\n        //  (s)    -e--> (t)          (s)    -e--> (nt)\n        //  (te_s) -te-> (nt)   =>    (te_s) -te-> (t)\n        //\n        // no parallel edges are introduced.\n\n        typename graph_traits<Graph>::vertex_descriptor\n            s = source(e, edges, g),          // current source\n            t = target(e, edges, g),          // current target\n            nt = target(te, edges, g),        // new target\n            te_s = source(te, edges, g);      // target edge source\n\n        if (get_count(s,  nt, nmap, g) > 0)\n            return true; // e would clash with an existing edge\n        if (get_count(te_s, t, nmap, g) > 0)\n            return true; // te would clash with an existing edge\n        return false; // no parallel edges\n    }\n\n    template <class Graph>\n    static void swap_target\n        (const pair<size_t, bool>& e,\n         const pair<size_t, bool>& te,\n         vector<typename graph_traits<Graph>::edge_descriptor>& edges,\n         Graph& g)\n    {\n        // swap the target of the edge 'e' with the target of edge 'te', as\n        // such:\n        //\n        //  (s)    -e--> (t)          (s)    -e--> (nt)\n        //  (te_s) -te-> (nt)   =>    (te_s) -te-> (t)\n\n        if (e.first == te.first)\n            return;\n\n        // new edges which will replace the old ones\n        typename graph_traits<Graph>::edge_descriptor ne, nte;\n        typename graph_traits<Graph>::vertex_descriptor\n            s_e = source(e, edges, g),\n            t_e = target(e, edges, g),\n            s_te = source(te, edges, g),\n            t_te = target(te, edges, g);\n        remove_edge(edges[e.first], g);\n        remove_edge(edges[te.first], g);\n\n        if (graph_tool::is_directed(g) || !e.second)\n            ne = add_edge(s_e, t_te, g).first;\n        else // keep invertedness (only for undirected graphs)\n            ne = add_edge(t_te, s_e, g).first;\n        edges[e.first] = ne;\n        if (graph_tool::is_directed(g) || !te.second)\n            nte = add_edge(s_te, t_e, g).first;\n        else // keep invertedness (only for undirected graphs)\n            nte = add_edge(t_e, s_te,  g).first;\n        edges[te.first] = nte;\n    }\n\n};\n\n// used for verbose display\nvoid print_progress(size_t i, size_t n_iter, size_t current, size_t total,\n                    stringstream& str)\n{\n    size_t atom = (total > 200) ? total / 100 : 1;\n    if ( ( (current+1) % atom == 0) || (current + 1) == total)\n    {\n        size_t size = str.str().length();\n        for (size_t j = 0; j < str.str().length(); ++j)\n            cout << \"\\b\";\n        str.str(\"\");\n        str << \"(\" << i + 1 << \" / \" << n_iter << \") \"\n            << current + 1 << \" of \" << total << \" (\"\n            << (current + 1) * 100 / total << \"%)\";\n        for (int j = 0; j < int(size - str.str().length()); ++j)\n            str << \" \";\n        cout << str.str() << flush;\n    }\n}\n\n//select blocks based on in/out degrees\nclass DegreeBlock\n{\npublic:\n    typedef pair<size_t, size_t> block_t;\n\n    template <class Graph>\n    block_t get_block(typename graph_traits<Graph>::vertex_descriptor v,\n                      const Graph& g) const\n    {\n        return make_pair(in_degreeS()(v, g), out_degree(v, g));\n    }\n};\n\n//select blocks based on property map\ntemplate <class PropertyMap>\nclass PropertyBlock\n{\npublic:\n    typedef typename property_traits<PropertyMap>::value_type block_t;\n\n    PropertyBlock(PropertyMap p): _p(p) {}\n\n    template <class Graph>\n    block_t get_block(typename graph_traits<Graph>::vertex_descriptor v,\n                      const Graph&) const\n    {\n        return get(_p, v);\n    }\n\nprivate:\n    PropertyMap _p;\n};\n\n// select an appropriate \"null\" key for densehash\ntemplate <class Type>\nstruct get_null_key\n{\n    Type operator()() const\n    {\n        return numeric_limits<Type>::max();\n    }\n};\n\ntemplate <>\nstruct get_null_key<string>\n{\n    string operator()() const\n    {\n        return lexical_cast<string>(get_null_key<size_t>()());\n    }\n};\n\ntemplate <>\nstruct get_null_key<boost::python::object>\n{\n    boost::python::object operator()() const\n    {\n        return boost::python::object();\n    }\n};\n\ntemplate <class Type>\nstruct get_null_key<vector<Type>>\n{\n    vector<Type> operator()() const\n    {\n        vector<Type> v(1);\n        v[0] = get_null_key<Type>()();\n        return v;\n    }\n};\n\ntemplate <class Type1, class Type2>\nstruct get_null_key<pair<Type1, Type2>>\n{\n    pair<Type1, Type2> operator()() const\n    {\n        return make_pair(get_null_key<Type1>()(),\n                         get_null_key<Type2>()());\n    }\n};\n\n\n// main rewire loop\ntemplate <template <class Graph, class EdgeIndexMap, class CorrProb,\n                    class BlockDeg>\n          class RewireStrategy>\nstruct graph_rewire\n{\n\n    template <class Graph, class EdgeIndexMap, class CorrProb,\n              class BlockDeg, class PinMap>\n    void operator()(Graph& g, EdgeIndexMap edge_index, CorrProb corr_prob,\n                    PinMap pin, bool self_loops, bool parallel_edges,\n                    bool configuration, pair<size_t, bool> iter_sweep,\n                    std::tuple<bool, bool, bool> cache_verbose, size_t& pcount,\n                    rng_t& rng, BlockDeg bd) const\n    {\n        typedef typename graph_traits<Graph>::edge_descriptor edge_t;\n        bool persist = std::get<0>(cache_verbose);\n        bool cache = std::get<1>(cache_verbose);\n        bool verbose = std::get<2>(cache_verbose);\n\n        vector<edge_t> edges;\n        vector<size_t> edge_pos;\n        typename graph_traits<Graph>::edge_iterator e, e_end;\n        for (tie(e, e_end) = boost::edges(g); e != e_end; ++e)\n        {\n            if (pin[*e])\n                continue;\n            edges.push_back(*e);\n            edge_pos.push_back(edge_pos.size());\n        }\n\n        typedef random_permutation_iterator<typename vector<size_t>::iterator,\n                                            rng_t>\n            random_edge_iter;\n\n        RewireStrategy<Graph, EdgeIndexMap, CorrProb, BlockDeg>\n            rewire(g, edge_index, edges, corr_prob, bd, cache, rng,\n                   parallel_edges, configuration);\n\n        size_t niter;\n        bool no_sweep;\n        tie(niter, no_sweep) = iter_sweep;\n        pcount = 0;\n        if (verbose)\n            cout << \"rewiring edges: \";\n        stringstream str;\n        for (size_t i = 0; i < niter; ++i)\n        {\n            random_edge_iter\n                ei_begin(edge_pos.begin(), edge_pos.end(), rng),\n                ei_end(edge_pos.end(), edge_pos.end(), rng);\n\n            for (random_edge_iter ei = ei_begin; ei != ei_end; ++ei)\n            {\n                size_t e_pos = ei - ei_begin;\n                if (verbose)\n                    print_progress(i, niter, e_pos, no_sweep ? 1 : edges.size(),\n                                   str);\n\n                size_t e = *ei;\n\n                bool success = false;\n                do\n                {\n                    success = rewire(e, self_loops, parallel_edges);\n                }\n                while(persist && !success);\n\n                if (!success)\n                    ++pcount;\n\n                if (no_sweep)\n                    break;\n            }\n        }\n        if (verbose)\n            cout << endl;\n    }\n\n    template <class Graph, class EdgeIndexMap, class CorrProb, class PinMap>\n    void operator()(Graph& g, EdgeIndexMap edge_index, CorrProb corr_prob,\n                    PinMap pin, bool self_loops, bool parallel_edges,\n                    bool configuration, pair<size_t, bool> iter_sweep,\n                    std::tuple<bool, bool, bool> cache_verbose, size_t& pcount,\n                    rng_t& rng) const\n    {\n        operator()(g, edge_index, corr_prob, pin, self_loops, parallel_edges,\n                   configuration, iter_sweep, cache_verbose, pcount, rng,\n                   DegreeBlock());\n    }\n};\n\n\n// this will rewire the edges so that the resulting graph will be entirely\n// random (i.e. Erdos-Renyi)\ntemplate <class Graph, class EdgeIndexMap, class CorrProb, class BlockDeg>\nclass ErdosRewireStrategy\n{\npublic:\n    typedef typename graph_traits<Graph>::edge_descriptor edge_t;\n    typedef typename EdgeIndexMap::value_type index_t;\n\n    ErdosRewireStrategy(Graph& g, EdgeIndexMap edge_index,\n                        vector<edge_t>& edges, CorrProb, BlockDeg,\n                        bool, rng_t& rng, bool, bool configuration)\n        : _g(g), _edge_index(edge_index), _edges(edges),\n          _vertices(HardNumVertices()(g)), _rng(rng),\n          _configuration(configuration),\n          _nmap(get(vertex_index, g), num_vertices(g))\n    {\n        decltype(_vertices.begin()) viter = _vertices.begin();\n        typename graph_traits<Graph>::vertex_iterator v, v_end;\n        for (tie(v, v_end) = vertices(_g); v != v_end; ++v)\n            *(viter++) = *v;\n\n        if (!configuration)\n        {\n            for (size_t i = 0; i < edges.size(); ++i)\n                add_count(source(edges[i], g), target(edges[i], g), _nmap, g);\n        }\n    }\n\n    bool operator()(size_t ei, bool self_loops, bool parallel_edges)\n    {\n        size_t e_s = source(_edges[ei], _g);\n        size_t e_t = target(_edges[ei], _g);\n\n        if (!graph_tool::is_directed(_g) && e_s > e_t)\n            std::swap(e_s, e_t);\n\n        //try randomly drawn pairs of vertices\n        std::uniform_int_distribution<size_t> sample(0, _vertices.size() - 1);\n        typename graph_traits<Graph>::vertex_descriptor s, t;\n        while (true)\n        {\n            s = sample(_rng);\n            t = sample(_rng);\n            if (s == t)\n            {\n                if (!self_loops) // reject self-loops if not allowed\n                    continue;\n\n            }\n            else if (!graph_tool::is_directed(_g) && self_loops)\n            {\n                // sample self-loops w/ correct probability for undirected\n                // graphs\n                std::bernoulli_distribution reject(.5);\n                if (reject(_rng))\n                    continue;\n            }\n            break;\n        }\n\n        if (!graph_tool::is_directed(_g) && s > t)\n            std::swap(s, t);\n\n        if (s == e_s && t == e_t)\n            return false;\n\n        // reject parallel edges if not allowed\n        if (!parallel_edges && is_adjacent(s, t, _g))\n            return false;\n\n        if (!_configuration)\n        {\n            size_t m = get_count(s, t, _nmap, _g);\n            size_t m_e = get_count(e_s, e_t, _nmap, _g);\n\n            double a = (m + 1) / double(m_e);\n\n            std::bernoulli_distribution accept(std::min(a, 1.));\n            if (!accept(_rng))\n                return false;\n        }\n\n        remove_edge(_edges[ei], _g);\n        edge_t ne = add_edge(s, t, _g).first;\n        _edges[ei] = ne;\n\n        if (!_configuration)\n        {\n            remove_count(e_s, e_t, _nmap, _g);\n            add_count(s, t, _nmap, _g);\n        }\n\n        return true;\n    }\n\nprivate:\n    Graph& _g;\n    EdgeIndexMap _edge_index;\n    vector<edge_t>& _edges;\n    vector<typename graph_traits<Graph>::vertex_descriptor> _vertices;\n    rng_t& _rng;\n    bool _configuration;\n    typedef gt_hash_map<size_t, size_t> nmapv_t;\n    typedef typename property_map_type::apply<nmapv_t,\n                                              typename property_map<Graph, vertex_index_t>::type>\n        ::type::unchecked_t nmap_t;\n    nmap_t _nmap;\n};\n\n\n\n// this is the mother class for edge-based rewire strategies\n// it contains the common loop for finding edges to swap, so different\n// strategies need only to specify where to sample the edges from.\ntemplate <class Graph, class EdgeIndexMap, class RewireStrategy>\nclass RewireStrategyBase\n{\npublic:\n    typedef typename graph_traits<Graph>::edge_descriptor edge_t;\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\n\n    typedef typename EdgeIndexMap::value_type index_t;\n\n    RewireStrategyBase(Graph& g, EdgeIndexMap edge_index, vector<edge_t>& edges,\n                       rng_t& rng, bool parallel_edges, bool configuration)\n        : _g(g), _edge_index(edge_index), _edges(edges), _rng(rng),\n          _nmap(get(vertex_index, g), num_vertices(g)),\n          _configuration(configuration)\n    {\n        if (!parallel_edges || !configuration)\n        {\n            for (size_t i = 0; i < edges.size(); ++i)\n                add_count(source(edges[i], g), target(edges[i], g), _nmap, g);\n        }\n    }\n\n    bool operator()(size_t ei, bool self_loops, bool parallel_edges)\n    {\n        RewireStrategy& self = *static_cast<RewireStrategy*>(this);\n\n        // try randomly drawn pairs of edges and check if they satisfy all the\n        // consistency checks\n\n        pair<size_t, bool> e = make_pair(ei, false);\n\n        // rewire target\n        pair<size_t, bool> et = self.get_target_edge(e, parallel_edges);\n\n        if (et.first == ei)\n            return false;\n\n        auto s = source(e,  _edges, _g);\n        auto t = target(e,  _edges, _g);\n        auto ts = source(et,  _edges, _g);\n        auto tt = target(et,  _edges, _g);\n\n        if (!self_loops) // reject self-loops if not allowed\n        {\n            if(s == tt || ts == t)\n                return false;\n        }\n\n        // reject parallel edges if not allowed\n        if (!parallel_edges && (et.first != e.first))\n        {\n            if (swap_edge::parallel_check_target(e, et, _edges, _nmap, _g))\n                return false;\n        }\n\n        double a = 0;\n\n        if (!graph_tool::is_directed(_g))\n        {\n            a -= log(2 + (s == t) + (ts == tt));\n            a += log(2 + (s == tt) + (ts == t));\n        }\n\n        if (!_configuration)\n        {\n            map<std::pair<size_t, size_t>, int> delta;\n\n            delta[std::make_pair(s, t)] -= 1;\n            delta[std::make_pair(ts, tt)] -= 1;\n            delta[std::make_pair(s, tt)] += 1;\n            delta[std::make_pair(ts, t)] += 1;\n\n            for (auto& e_d : delta)\n            {\n                auto u = e_d.first.first;\n                auto v = e_d.first.second;\n                int d = e_d.second;\n                size_t m = get_count(u,  v,  _nmap, _g);\n                a -= lgamma(m + 1) - lgamma((m + 1) + d);\n                if (!graph_tool::is_directed(_g) && u == v)\n                    a += d * log(2);\n            }\n\n        }\n\n        std::bernoulli_distribution accept(std::min(exp(a), 1.));\n        if (!accept(_rng))\n            return false;\n\n        self.update_edge(e.first, false);\n        self.update_edge(et.first, false);\n\n        if (!parallel_edges || !_configuration)\n        {\n            remove_count(source(e, _edges, _g), target(e, _edges, _g), _nmap, _g);\n            remove_count(source(et, _edges, _g), target(et, _edges, _g), _nmap, _g);\n        }\n\n        swap_edge::swap_target(e, et, _edges, _g);\n\n        self.update_edge(e.first, true);\n        self.update_edge(et.first, true);\n\n        if (!parallel_edges || !_configuration)\n        {\n            add_count(source(e, _edges, _g), target(e, _edges, _g), _nmap, _g);\n            add_count(source(et, _edges, _g), target(et, _edges, _g), _nmap, _g);\n        }\n\n        return true;\n    }\n\nprotected:\n    Graph& _g;\n    EdgeIndexMap _edge_index;\n    vector<edge_t>& _edges;\n    rng_t& _rng;\n\n    typedef gt_hash_map<size_t, size_t> nmapv_t;\n    typedef typename property_map_type::apply<nmapv_t,\n                                              typename property_map<Graph, vertex_index_t>::type>\n        ::type::unchecked_t nmap_t;\n    nmap_t _nmap;\n    bool _configuration;\n};\n\n// this will rewire the edges so that the combined (in, out) degree distribution\n// will be the same, but all the rest is random\ntemplate <class Graph, class EdgeIndexMap, class CorrProb, class BlockDeg>\nclass RandomRewireStrategy:\n    public RewireStrategyBase<Graph, EdgeIndexMap,\n                              RandomRewireStrategy<Graph, EdgeIndexMap,\n                                                   CorrProb, BlockDeg> >\n{\npublic:\n    typedef RewireStrategyBase<Graph, EdgeIndexMap,\n                               RandomRewireStrategy<Graph, EdgeIndexMap,\n                                                    CorrProb, BlockDeg> >\n        base_t;\n\n    typedef Graph graph_t;\n    typedef EdgeIndexMap edge_index_t;\n\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\n    typedef typename graph_traits<Graph>::edge_descriptor edge_t;\n    typedef typename EdgeIndexMap::value_type index_t;\n\n    struct hash_index {};\n    struct random_index {};\n\n    RandomRewireStrategy(Graph& g, EdgeIndexMap edge_index,\n                         vector<edge_t>& edges, CorrProb, BlockDeg,\n                         bool, rng_t& rng, bool parallel_edges,\n                         bool configuration)\n        : base_t(g, edge_index, edges, rng, parallel_edges, configuration),\n          _g(g) {}\n\n    pair<size_t,bool> get_target_edge(pair<size_t,bool>& e, bool)\n    {\n        std::uniform_int_distribution<> sample(0, base_t::_edges.size() - 1);\n        pair<size_t, bool> et = make_pair(sample(base_t::_rng), false);\n        if (!graph_tool::is_directed(_g))\n        {\n            std::bernoulli_distribution coin(0.5);\n            et.second = coin(base_t::_rng);\n            e.second = coin(base_t::_rng);\n        }\n        return et;\n    }\n\n    void update_edge(size_t, bool) {}\n\nprivate:\n    Graph& _g;\n    EdgeIndexMap _edge_index;\n};\n\n\n// this will rewire the edges so that the (in,out) degree distributions and the\n// (in,out)->(in,out) correlations will be the same, but all the rest is random\ntemplate <class Graph, class EdgeIndexMap, class CorrProb, class BlockDeg>\nclass CorrelatedRewireStrategy:\n    public RewireStrategyBase<Graph, EdgeIndexMap,\n                              CorrelatedRewireStrategy<Graph, EdgeIndexMap,\n                                                       CorrProb, BlockDeg> >\n{\npublic:\n    typedef RewireStrategyBase<Graph, EdgeIndexMap,\n                               CorrelatedRewireStrategy<Graph, EdgeIndexMap,\n                                                        CorrProb, BlockDeg> >\n        base_t;\n\n    typedef Graph graph_t;\n\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\n    typedef typename graph_traits<Graph>::edge_descriptor edge_t;\n\n    typedef typename BlockDeg::block_t deg_t;\n\n    CorrelatedRewireStrategy(Graph& g, EdgeIndexMap edge_index,\n                             vector<edge_t>& edges, CorrProb, BlockDeg blockdeg,\n                             bool, rng_t& rng, bool parallel_edges,\n                             bool configuration)\n        : base_t(g, edge_index, edges, rng, parallel_edges, configuration),\n          _blockdeg(blockdeg), _g(g)\n    {\n        for (size_t ei = 0; ei < base_t::_edges.size(); ++ei)\n        {\n            // For undirected graphs, there is no difference between source and\n            // target, and each edge will appear _twice_ in the list below,\n            // once for each different ordering of source and target.\n            edge_t& e = base_t::_edges[ei];\n\n            vertex_t t = target(e, _g);\n            deg_t tdeg = get_deg(t, _g);;\n            _edges_by_target[tdeg].push_back(make_pair(ei, false));\n\n            if (!graph_tool::is_directed(_g))\n            {\n                t = source(e, _g);\n                deg_t tdeg = get_deg(t, _g);\n                _edges_by_target[tdeg].push_back(make_pair(ei, true));\n            }\n        }\n    }\n\n    pair<size_t,bool> get_target_edge(pair<size_t, bool>& e, bool)\n    {\n        if (!graph_tool::is_directed(_g))\n        {\n            std::bernoulli_distribution coin(0.5);\n            e.second = coin(base_t::_rng);\n        }\n\n        vertex_t t = target(e, base_t::_edges, _g);\n        deg_t tdeg = get_deg(t, _g);\n        auto& elist = _edges_by_target[tdeg];\n        std::uniform_int_distribution<> sample(0, elist.size() - 1);\n        auto ep = elist[sample(base_t::_rng)];\n        if (get_deg(target(ep, base_t::_edges, _g), _g) != tdeg)\n            ep.second = not ep.second;\n        return ep;\n    }\n\n    void update_edge(size_t, bool) {}\n\n    deg_t get_deg(vertex_t v, const Graph& g)\n    {\n        return _blockdeg.get_block(v, g);\n    }\n\nprivate:\n    BlockDeg _blockdeg;\n\n    typedef std::unordered_map<deg_t,\n                          vector<pair<size_t, bool>>>\n        edges_by_end_deg_t;\n\n    edges_by_end_deg_t _edges_by_target;\n\nprotected:\n    const Graph& _g;\n};\n\n\n// general stochastic blockmodel\n// this version is based on rejection sampling\ntemplate <class Graph, class EdgeIndexMap, class CorrProb, class BlockDeg>\nclass ProbabilisticRewireStrategy:\n    public RewireStrategyBase<Graph, EdgeIndexMap,\n                              ProbabilisticRewireStrategy<Graph, EdgeIndexMap,\n                                                          CorrProb, BlockDeg> >\n{\npublic:\n    typedef RewireStrategyBase<Graph, EdgeIndexMap,\n                               ProbabilisticRewireStrategy<Graph, EdgeIndexMap,\n                                                           CorrProb, BlockDeg> >\n        base_t;\n\n    typedef Graph graph_t;\n    typedef EdgeIndexMap edge_index_t;\n\n    typedef typename BlockDeg::block_t deg_t;\n\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\n    typedef typename graph_traits<Graph>::edge_descriptor edge_t;\n    typedef typename EdgeIndexMap::value_type index_t;\n\n    ProbabilisticRewireStrategy(Graph& g, EdgeIndexMap edge_index,\n                                vector<edge_t>& edges, CorrProb corr_prob,\n                                BlockDeg blockdeg, bool cache, rng_t& rng,\n                                bool parallel_edges, bool configuration)\n        : base_t(g, edge_index, edges, rng, parallel_edges, configuration),\n          _g(g), _corr_prob(corr_prob), _blockdeg(blockdeg)\n    {\n        if (cache)\n        {\n            // cache probabilities\n            _corr_prob.get_probs(_probs);\n\n            if (_probs.empty())\n            {\n                std::unordered_set<deg_t> deg_set;\n                for (size_t ei = 0; ei < base_t::_edges.size(); ++ei)\n                {\n                    edge_t& e = base_t::_edges[ei];\n                    deg_set.insert(get_deg(source(e, g), g));\n                    deg_set.insert(get_deg(target(e, g), g));\n                }\n\n                for (auto s_iter = deg_set.begin(); s_iter != deg_set.end(); ++s_iter)\n                    for (auto t_iter = deg_set.begin(); t_iter != deg_set.end(); ++t_iter)\n                    {\n                        double p = _corr_prob(*s_iter, *t_iter);\n                        _probs[make_pair(*s_iter, *t_iter)] = p;\n                    }\n            }\n\n            for (auto iter = _probs.begin(); iter != _probs.end(); ++iter)\n            {\n                double& p = iter->second;\n                // avoid zero probability to not get stuck in rejection step\n                if (std::isnan(p) || std::isinf(p) || p <= 0)\n                    p = numeric_limits<double>::min();\n                p = log(p);\n            }\n        }\n    }\n\n    double get_prob(const deg_t& s_deg, const deg_t& t_deg)\n    {\n        if (_probs.empty())\n        {\n            double p = _corr_prob(s_deg, t_deg);\n            // avoid zero probability to not get stuck in rejection step\n            if (std::isnan(p) || std::isinf(p) || p <= 0)\n                p = numeric_limits<double>::min();\n            return log(p);\n        }\n        auto k = make_pair(s_deg, t_deg);\n        auto iter = _probs.find(k);\n        if (iter == _probs.end())\n            return log(numeric_limits<double>::min());\n        return iter->second;\n    }\n\n    deg_t get_deg(vertex_t v, Graph& g)\n    {\n        return _blockdeg.get_block(v, g);\n    }\n\n    pair<size_t, bool> get_target_edge(pair<size_t, bool>& e, bool)\n    {\n        if (!graph_tool::is_directed(_g))\n        {\n            std::bernoulli_distribution coin(0.5);\n            e.second = coin(base_t::_rng);\n        }\n\n        deg_t s_deg = get_deg(source(e, base_t::_edges, _g), _g);\n        deg_t t_deg = get_deg(target(e, base_t::_edges, _g), _g);\n\n        std::uniform_int_distribution<> sample(0, base_t::_edges.size() - 1);\n        size_t epi = sample(base_t::_rng);\n        pair<size_t, bool> ep = make_pair(epi, false);\n        if (!graph_tool::is_directed(_g))\n        {\n            // for undirected graphs we must select a random direction\n            std::bernoulli_distribution coin(0.5);\n            ep.second = coin(base_t::_rng);\n        }\n\n        if (source(e, base_t::_edges, _g) == source(ep, base_t::_edges, _g) ||\n            target(e, base_t::_edges, _g) == target(ep, base_t::_edges, _g))\n            return ep; // rewiring is a no-op\n\n        deg_t ep_s_deg = get_deg(source(ep, base_t::_edges, _g), _g);\n        deg_t ep_t_deg = get_deg(target(ep, base_t::_edges, _g), _g);\n\n        double pi = get_prob(s_deg, t_deg) + get_prob(ep_s_deg, ep_t_deg);\n        double pf = get_prob(s_deg, ep_t_deg) + get_prob(ep_s_deg, t_deg);\n\n        if (pf >= pi)\n            return ep;\n\n        double a = exp(pf - pi);\n\n        std::uniform_real_distribution<> rsample(0.0, 1.0);\n        double r = rsample(base_t::_rng);\n        if (r > a)\n            return e; // reject\n        else\n            return ep;\n    }\n\n    void update_edge(size_t, bool) {}\n\nprivate:\n    Graph& _g;\n    EdgeIndexMap _edge_index;\n    CorrProb _corr_prob;\n    BlockDeg _blockdeg;\n\n    typedef std::unordered_map<pair<deg_t, deg_t>, double> prob_map_t;\n    prob_map_t _probs;\n};\n\n\n// general \"traditional\" stochastic blockmodel\n// this version is based on the alias method, and does not keep the degrees fixed\ntemplate <class Graph, class EdgeIndexMap, class CorrProb, class BlockDeg,\n          bool micro>\nclass TradBlockRewireStrategy\n{\npublic:\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\n    typedef typename graph_traits<Graph>::edge_descriptor edge_t;\n    typedef typename EdgeIndexMap::value_type index_t;\n    typedef typename BlockDeg::block_t deg_t;\n\n    TradBlockRewireStrategy(Graph& g, EdgeIndexMap edge_index,\n                            vector<edge_t>& edges, CorrProb corr_prob,\n                            BlockDeg blockdeg, bool, rng_t& rng,\n                            bool parallel_edges, bool configuration)\n\n        : _g(g), _edge_index(edge_index), _edges(edges), _corr_prob(corr_prob),\n          _blockdeg(blockdeg), _rng(rng), _sampler(nullptr),\n          _configuration(configuration),\n          _nmap(get(vertex_index, g), num_vertices(g))\n    {\n        for (auto v : vertices_range(_g))\n        {\n            deg_t d = _blockdeg.get_block(v, g);\n            _vertices[d].push_back(v);\n        }\n\n        if (!micro)\n        {\n            std::unordered_map<pair<deg_t, deg_t>, double> probs;\n            _corr_prob.get_probs(probs);\n\n            vector<double> dprobs;\n            if (probs.empty())\n            {\n                for (auto& s : _vertices)\n                {\n                    for (auto& t : _vertices)\n                    {\n                        double p = _corr_prob(s.first, t.first);\n                        if (std::isnan(p) || std::isinf(p) || p <= 0)\n                            continue;\n\n                        _items.push_back(make_pair(s.first, t.first));\n                        dprobs.push_back(p * s.second.size() * t.second.size());\n                    }\n                }\n            }\n            else\n            {\n                for (auto& stp : probs)\n                {\n                    deg_t s = stp.first.first;\n                    deg_t t = stp.first.second;\n                    double p = stp.second;\n                    // avoid zero probability to not get stuck in rejection step\n                    if (std::isnan(p) || std::isinf(p) || p <= 0)\n                        continue;\n                    _items.push_back(make_pair(s, t));\n                    dprobs.push_back(p * _vertices[s].size() * _vertices[t].size());\n                }\n            }\n\n            if (_items.empty())\n                throw GraphException(\"No connection probabilities larger than zero!\");\n\n            _sampler = new Sampler<pair<deg_t, deg_t> >(_items, dprobs);\n        }\n\n        if (!configuration || !parallel_edges)\n        {\n            for (size_t i = 0; i < edges.size(); ++i)\n                add_count(source(edges[i], g), target(edges[i], g), _nmap, g);\n        }\n    }\n\n    ~TradBlockRewireStrategy()\n    {\n        if (_sampler != nullptr)\n            delete _sampler;\n    }\n\n    bool operator()(size_t ei, bool self_loops, bool parallel_edges)\n    {\n        size_t e_s = source(_edges[ei], _g);\n        size_t e_t = target(_edges[ei], _g);\n\n        typename graph_traits<Graph>::vertex_descriptor s, t;\n\n        pair<deg_t, deg_t> deg;\n        if (micro)\n            deg = {_blockdeg.get_block(e_s, _g),\n                   _blockdeg.get_block(e_t, _g)};\n\n        while (true)\n        {\n            if (!micro)\n                deg = _sampler->sample(_rng);\n\n            vector<vertex_t>& svs = _vertices[deg.first];\n            vector<vertex_t>& tvs = _vertices[deg.second];\n\n            if (svs.empty() || tvs.empty())\n                continue;\n\n            s = uniform_sample(svs, _rng);\n            t = uniform_sample(tvs, _rng);\n\n            if (!graph_tool::is_directed(_g) &&\n                deg.first == deg.second && s != t && self_loops)\n            {\n                // sample self-loops w/ correct probability for undirected\n                // graphs\n                std::bernoulli_distribution reject(.5);\n                if (reject(_rng))\n                    continue;\n            }\n\n            break;\n        }\n\n        // reject self-loops if not allowed\n        if (!self_loops && s == t)\n            return false;\n\n        // reject parallel edges if not allowed\n        if (!parallel_edges && get_count(s, t, _nmap, _g))\n            return false;\n\n        if (!_configuration)\n        {\n            size_t m = get_count(s, t, _nmap, _g);\n            size_t m_e = get_count(e_s, e_t, _nmap, _g);\n\n            double a = (m + 1) / double(m_e);\n\n            std::bernoulli_distribution accept(std::min(a, 1.));\n            if (!accept(_rng))\n                return false;\n        }\n\n        remove_edge(_edges[ei], _g);\n        edge_t ne = add_edge(s, t, _g).first;\n        _edges[ei] = ne;\n\n        if (!_configuration || !parallel_edges)\n        {\n            remove_count(e_s, e_t, _nmap, _g);\n            add_count(s, t, _nmap, _g);\n        }\n\n        return true;\n    }\n\nprivate:\n    Graph& _g;\n    EdgeIndexMap _edge_index;\n    vector<edge_t>& _edges;\n    CorrProb _corr_prob;\n    BlockDeg _blockdeg;\n    rng_t& _rng;\n\n    std::unordered_map<deg_t, vector<vertex_t>> _vertices;\n\n    vector<pair<deg_t, deg_t> > _items;\n    Sampler<pair<deg_t, deg_t> >* _sampler;\n\n    bool _configuration;\n\n    typedef gt_hash_map<size_t, size_t> nmapv_t;\n    typedef typename property_map_type::apply<nmapv_t,\n                                              typename property_map<Graph, vertex_index_t>::type>\n        ::type::unchecked_t nmap_t;\n    nmap_t _nmap;\n};\n\ntemplate <class Graph, class EdgeIndexMap, class CorrProb, class BlockDeg>\nusing CanTradBlockRewireStrategy =\n    TradBlockRewireStrategy<Graph, EdgeIndexMap, CorrProb, BlockDeg, false>;\n\ntemplate <class Graph, class EdgeIndexMap, class CorrProb, class BlockDeg>\nusing MicroTradBlockRewireStrategy =\n    TradBlockRewireStrategy<Graph, EdgeIndexMap, CorrProb, BlockDeg, true>;\n\n} // graph_tool namespace\n\n#endif // GRAPH_REWIRING_HH\n", "meta": {"hexsha": "e40f4773909c316c02ecd60b2f8546299d0120f3", "size": 34730, "ext": "hh", "lang": "C++", "max_stars_repo_path": "graph-tool-2.27/src/graph/generation/graph_rewiring.hh", "max_stars_repo_name": "Znigneering/CSCI-3154", "max_stars_repo_head_hexsha": "bc318efc73d2a80025b98f5b3e4f7e4819e952e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "graph-tool-2.27/src/graph/generation/graph_rewiring.hh", "max_issues_repo_name": "Znigneering/CSCI-3154", "max_issues_repo_head_hexsha": "bc318efc73d2a80025b98f5b3e4f7e4819e952e4", "max_issues_repo_licenses": ["MIT"], "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-2.27/src/graph/generation/graph_rewiring.hh", "max_forks_repo_name": "Znigneering/CSCI-3154", "max_forks_repo_head_hexsha": "bc318efc73d2a80025b98f5b3e4f7e4819e952e4", "max_forks_repo_licenses": ["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.0979667283, "max_line_length": 97, "alphanum_fraction": 0.5553699971, "num_tokens": 8470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.28522023251914713}}
{"text": "//  (C) Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_TOOLS_RATIONAL_HPP\n#define BOOST_MATH_TOOLS_RATIONAL_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <boost/array.hpp>\n#include <boost/math/tools/config.hpp>\n#include <boost/mpl/int.hpp>\n\n#if BOOST_MATH_POLY_METHOD == 1\n#  define BOOST_HEADER() <BOOST_JOIN(boost/math/tools/detail/polynomial_horner1_, BOOST_MATH_MAX_POLY_ORDER).hpp>\n#  include BOOST_HEADER()\n#  undef BOOST_HEADER\n#elif BOOST_MATH_POLY_METHOD == 2\n#  define BOOST_HEADER() <BOOST_JOIN(boost/math/tools/detail/polynomial_horner2_, BOOST_MATH_MAX_POLY_ORDER).hpp>\n#  include BOOST_HEADER()\n#  undef BOOST_HEADER\n#elif BOOST_MATH_POLY_METHOD == 3\n#  define BOOST_HEADER() <BOOST_JOIN(boost/math/tools/detail/polynomial_horner3_, BOOST_MATH_MAX_POLY_ORDER).hpp>\n#  include BOOST_HEADER()\n#  undef BOOST_HEADER\n#endif\n#if BOOST_MATH_RATIONAL_METHOD == 1\n#  define BOOST_HEADER() <BOOST_JOIN(boost/math/tools/detail/rational_horner1_, BOOST_MATH_MAX_POLY_ORDER).hpp>\n#  include BOOST_HEADER()\n#  undef BOOST_HEADER\n#elif BOOST_MATH_RATIONAL_METHOD == 2\n#  define BOOST_HEADER() <BOOST_JOIN(boost/math/tools/detail/rational_horner2_, BOOST_MATH_MAX_POLY_ORDER).hpp>\n#  include BOOST_HEADER()\n#  undef BOOST_HEADER\n#elif BOOST_MATH_RATIONAL_METHOD == 3\n#  define BOOST_HEADER() <BOOST_JOIN(boost/math/tools/detail/rational_horner3_, BOOST_MATH_MAX_POLY_ORDER).hpp>\n#  include BOOST_HEADER()\n#  undef BOOST_HEADER\n#endif\n\n#if 0\n//\n// This just allows dependency trackers to find the headers\n// used in the above PP-magic.\n//\n#include <boost/math/tools/detail/polynomial_horner1_2.hpp>\n#include <boost/math/tools/detail/polynomial_horner1_3.hpp>\n#include <boost/math/tools/detail/polynomial_horner1_4.hpp>\n#include <boost/math/tools/detail/polynomial_horner1_5.hpp>\n#include <boost/math/tools/detail/polynomial_horner1_6.hpp>\n#include <boost/math/tools/detail/polynomial_horner1_7.hpp>\n#include <boost/math/tools/detail/polynomial_horner1_8.hpp>\n#include <boost/math/tools/detail/polynomial_horner1_9.hpp>\n#include <boost/math/tools/detail/polynomial_horner1_10.hpp>\n#include <boost/math/tools/detail/polynomial_horner1_11.hpp>\n#include <boost/math/tools/detail/polynomial_horner1_12.hpp>\n#include <boost/math/tools/detail/polynomial_horner1_13.hpp>\n#include <boost/math/tools/detail/polynomial_horner1_14.hpp>\n#include <boost/math/tools/detail/polynomial_horner1_15.hpp>\n#include <boost/math/tools/detail/polynomial_horner1_16.hpp>\n#include <boost/math/tools/detail/polynomial_horner1_17.hpp>\n#include <boost/math/tools/detail/polynomial_horner1_18.hpp>\n#include <boost/math/tools/detail/polynomial_horner1_19.hpp>\n#include <boost/math/tools/detail/polynomial_horner1_20.hpp>\n#include <boost/math/tools/detail/polynomial_horner2_2.hpp>\n#include <boost/math/tools/detail/polynomial_horner2_3.hpp>\n#include <boost/math/tools/detail/polynomial_horner2_4.hpp>\n#include <boost/math/tools/detail/polynomial_horner2_5.hpp>\n#include <boost/math/tools/detail/polynomial_horner2_6.hpp>\n#include <boost/math/tools/detail/polynomial_horner2_7.hpp>\n#include <boost/math/tools/detail/polynomial_horner2_8.hpp>\n#include <boost/math/tools/detail/polynomial_horner2_9.hpp>\n#include <boost/math/tools/detail/polynomial_horner2_10.hpp>\n#include <boost/math/tools/detail/polynomial_horner2_11.hpp>\n#include <boost/math/tools/detail/polynomial_horner2_12.hpp>\n#include <boost/math/tools/detail/polynomial_horner2_13.hpp>\n#include <boost/math/tools/detail/polynomial_horner2_14.hpp>\n#include <boost/math/tools/detail/polynomial_horner2_15.hpp>\n#include <boost/math/tools/detail/polynomial_horner2_16.hpp>\n#include <boost/math/tools/detail/polynomial_horner2_17.hpp>\n#include <boost/math/tools/detail/polynomial_horner2_18.hpp>\n#include <boost/math/tools/detail/polynomial_horner2_19.hpp>\n#include <boost/math/tools/detail/polynomial_horner2_20.hpp>\n#include <boost/math/tools/detail/polynomial_horner3_2.hpp>\n#include <boost/math/tools/detail/polynomial_horner3_3.hpp>\n#include <boost/math/tools/detail/polynomial_horner3_4.hpp>\n#include <boost/math/tools/detail/polynomial_horner3_5.hpp>\n#include <boost/math/tools/detail/polynomial_horner3_6.hpp>\n#include <boost/math/tools/detail/polynomial_horner3_7.hpp>\n#include <boost/math/tools/detail/polynomial_horner3_8.hpp>\n#include <boost/math/tools/detail/polynomial_horner3_9.hpp>\n#include <boost/math/tools/detail/polynomial_horner3_10.hpp>\n#include <boost/math/tools/detail/polynomial_horner3_11.hpp>\n#include <boost/math/tools/detail/polynomial_horner3_12.hpp>\n#include <boost/math/tools/detail/polynomial_horner3_13.hpp>\n#include <boost/math/tools/detail/polynomial_horner3_14.hpp>\n#include <boost/math/tools/detail/polynomial_horner3_15.hpp>\n#include <boost/math/tools/detail/polynomial_horner3_16.hpp>\n#include <boost/math/tools/detail/polynomial_horner3_17.hpp>\n#include <boost/math/tools/detail/polynomial_horner3_18.hpp>\n#include <boost/math/tools/detail/polynomial_horner3_19.hpp>\n#include <boost/math/tools/detail/polynomial_horner3_20.hpp>\n#include <boost/math/tools/detail/rational_horner1_2.hpp>\n#include <boost/math/tools/detail/rational_horner1_3.hpp>\n#include <boost/math/tools/detail/rational_horner1_4.hpp>\n#include <boost/math/tools/detail/rational_horner1_5.hpp>\n#include <boost/math/tools/detail/rational_horner1_6.hpp>\n#include <boost/math/tools/detail/rational_horner1_7.hpp>\n#include <boost/math/tools/detail/rational_horner1_8.hpp>\n#include <boost/math/tools/detail/rational_horner1_9.hpp>\n#include <boost/math/tools/detail/rational_horner1_10.hpp>\n#include <boost/math/tools/detail/rational_horner1_11.hpp>\n#include <boost/math/tools/detail/rational_horner1_12.hpp>\n#include <boost/math/tools/detail/rational_horner1_13.hpp>\n#include <boost/math/tools/detail/rational_horner1_14.hpp>\n#include <boost/math/tools/detail/rational_horner1_15.hpp>\n#include <boost/math/tools/detail/rational_horner1_16.hpp>\n#include <boost/math/tools/detail/rational_horner1_17.hpp>\n#include <boost/math/tools/detail/rational_horner1_18.hpp>\n#include <boost/math/tools/detail/rational_horner1_19.hpp>\n#include <boost/math/tools/detail/rational_horner1_20.hpp>\n#include <boost/math/tools/detail/rational_horner2_2.hpp>\n#include <boost/math/tools/detail/rational_horner2_3.hpp>\n#include <boost/math/tools/detail/rational_horner2_4.hpp>\n#include <boost/math/tools/detail/rational_horner2_5.hpp>\n#include <boost/math/tools/detail/rational_horner2_6.hpp>\n#include <boost/math/tools/detail/rational_horner2_7.hpp>\n#include <boost/math/tools/detail/rational_horner2_8.hpp>\n#include <boost/math/tools/detail/rational_horner2_9.hpp>\n#include <boost/math/tools/detail/rational_horner2_10.hpp>\n#include <boost/math/tools/detail/rational_horner2_11.hpp>\n#include <boost/math/tools/detail/rational_horner2_12.hpp>\n#include <boost/math/tools/detail/rational_horner2_13.hpp>\n#include <boost/math/tools/detail/rational_horner2_14.hpp>\n#include <boost/math/tools/detail/rational_horner2_15.hpp>\n#include <boost/math/tools/detail/rational_horner2_16.hpp>\n#include <boost/math/tools/detail/rational_horner2_17.hpp>\n#include <boost/math/tools/detail/rational_horner2_18.hpp>\n#include <boost/math/tools/detail/rational_horner2_19.hpp>\n#include <boost/math/tools/detail/rational_horner2_20.hpp>\n#include <boost/math/tools/detail/rational_horner3_2.hpp>\n#include <boost/math/tools/detail/rational_horner3_3.hpp>\n#include <boost/math/tools/detail/rational_horner3_4.hpp>\n#include <boost/math/tools/detail/rational_horner3_5.hpp>\n#include <boost/math/tools/detail/rational_horner3_6.hpp>\n#include <boost/math/tools/detail/rational_horner3_7.hpp>\n#include <boost/math/tools/detail/rational_horner3_8.hpp>\n#include <boost/math/tools/detail/rational_horner3_9.hpp>\n#include <boost/math/tools/detail/rational_horner3_10.hpp>\n#include <boost/math/tools/detail/rational_horner3_11.hpp>\n#include <boost/math/tools/detail/rational_horner3_12.hpp>\n#include <boost/math/tools/detail/rational_horner3_13.hpp>\n#include <boost/math/tools/detail/rational_horner3_14.hpp>\n#include <boost/math/tools/detail/rational_horner3_15.hpp>\n#include <boost/math/tools/detail/rational_horner3_16.hpp>\n#include <boost/math/tools/detail/rational_horner3_17.hpp>\n#include <boost/math/tools/detail/rational_horner3_18.hpp>\n#include <boost/math/tools/detail/rational_horner3_19.hpp>\n#include <boost/math/tools/detail/rational_horner3_20.hpp>\n#endif\n\nnamespace boost{ namespace math{ namespace tools{\n\n//\n// Forward declaration to keep two phase lookup happy:\n//\ntemplate <class T, class U>\nU evaluate_polynomial(const T* poly, U const& z, std::size_t count);\n\nnamespace detail{\n\ntemplate <class T, class V, class Tag>\ninline V evaluate_polynomial_c_imp(const T* a, const V& val, const Tag*)\n{\n   return evaluate_polynomial(a, val, Tag::value);\n}\n\n} // namespace detail\n\n//\n// Polynomial evaluation with runtime size.\n// This requires a for-loop which may be more expensive than\n// the loop expanded versions above:\n//\ntemplate <class T, class U>\ninline U evaluate_polynomial(const T* poly, U const& z, std::size_t count)\n{\n   BOOST_ASSERT(count > 0);\n   U sum = static_cast<U>(poly[count - 1]);\n   for(int i = static_cast<int>(count) - 2; i >= 0; --i)\n   {\n      sum *= z;\n      sum += static_cast<U>(poly[i]);\n   }\n   return sum;\n}\n//\n// Compile time sized polynomials, just inline forwarders to the\n// implementations above:\n//\ntemplate <std::size_t N, class T, class V>\ninline V evaluate_polynomial(const T(&a)[N], const V& val)\n{\n   typedef mpl::int_<N> tag_type;\n   return detail::evaluate_polynomial_c_imp(static_cast<const T*>(a), val, static_cast<tag_type const*>(0));\n}\n\ntemplate <std::size_t N, class T, class V>\ninline V evaluate_polynomial(const boost::array<T,N>& a, const V& val)\n{\n   typedef mpl::int_<N> tag_type;\n   return detail::evaluate_polynomial_c_imp(static_cast<const T*>(a.data()), val, static_cast<tag_type const*>(0));\n}\n//\n// Even polynomials are trivial: just square the argument!\n//\ntemplate <class T, class U>\ninline U evaluate_even_polynomial(const T* poly, U z, std::size_t count)\n{\n   return evaluate_polynomial(poly, z*z, count);\n}\n\ntemplate <std::size_t N, class T, class V>\ninline V evaluate_even_polynomial(const T(&a)[N], const V& z)\n{\n   return evaluate_polynomial(a, z*z);\n}\n\ntemplate <std::size_t N, class T, class V>\ninline V evaluate_even_polynomial(const boost::array<T,N>& a, const V& z)\n{\n   return evaluate_polynomial(a, z*z);\n}\n//\n// Odd polynomials come next:\n//\ntemplate <class T, class U>\ninline U evaluate_odd_polynomial(const T* poly, U z, std::size_t count)\n{\n   return poly[0] + z * evaluate_polynomial(poly+1, z*z, count-1);\n}\n\ntemplate <std::size_t N, class T, class V>\ninline V evaluate_odd_polynomial(const T(&a)[N], const V& z)\n{\n   typedef mpl::int_<N-1> tag_type;\n   return a[0] + z * detail::evaluate_polynomial_c_imp(static_cast<const T*>(a) + 1, z*z, static_cast<tag_type const*>(0));\n}\n\ntemplate <std::size_t N, class T, class V>\ninline V evaluate_odd_polynomial(const boost::array<T,N>& a, const V& z)\n{\n   typedef mpl::int_<N-1> tag_type;\n   return a[0] + z * detail::evaluate_polynomial_c_imp(static_cast<const T*>(a.data()) + 1, z*z, static_cast<tag_type const*>(0));\n}\n\ntemplate <class T, class U, class V>\nV evaluate_rational(const T* num, const U* denom, const V& z_, std::size_t count);\n\nnamespace detail{\n\ntemplate <class T, class U, class V, class Tag>\ninline V evaluate_rational_c_imp(const T* num, const U* denom, const V& z, const Tag*)\n{\n   return boost::math::tools::evaluate_rational(num, denom, z, Tag::value);\n}\n\n}\n//\n// Rational functions: numerator and denominator must be\n// equal in size.  These always have a for-loop and so may be less\n// efficient than evaluating a pair of polynomials. However, there\n// are some tricks we can use to prevent overflow that might otherwise\n// occur in polynomial evaluation, if z is large.  This is important\n// in our Lanczos code for example.\n//\ntemplate <class T, class U, class V>\nV evaluate_rational(const T* num, const U* denom, const V& z_, std::size_t count)\n{\n   V z(z_);\n   V s1, s2;\n   if(z <= 1)\n   {\n      s1 = static_cast<V>(num[count-1]);\n      s2 = static_cast<V>(denom[count-1]);\n      for(int i = (int)count - 2; i >= 0; --i)\n      {\n         s1 *= z;\n         s2 *= z;\n         s1 += num[i];\n         s2 += denom[i];\n      }\n   }\n   else\n   {\n      z = 1 / z;\n      s1 = static_cast<V>(num[0]);\n      s2 = static_cast<V>(denom[0]);\n      for(unsigned i = 1; i < count; ++i)\n      {\n         s1 *= z;\n         s2 *= z;\n         s1 += num[i];\n         s2 += denom[i];\n      }\n   }\n   return s1 / s2;\n}\n\ntemplate <std::size_t N, class T, class U, class V>\ninline V evaluate_rational(const T(&a)[N], const U(&b)[N], const V& z)\n{\n   return detail::evaluate_rational_c_imp(a, b, z, static_cast<const mpl::int_<N>*>(0));\n}\n\ntemplate <std::size_t N, class T, class U, class V>\ninline V evaluate_rational(const boost::array<T,N>& a, const boost::array<U,N>& b, const V& z)\n{\n   return detail::evaluate_rational_c_imp(a.data(), b.data(), z, static_cast<mpl::int_<N>*>(0));\n}\n\n} // namespace tools\n} // namespace math\n} // namespace boost\n\n#endif // BOOST_MATH_TOOLS_RATIONAL_HPP\n\n\n\n\n", "meta": {"hexsha": "b49d5c815df7e96db2daf7c1efd110777264e596", "size": 13303, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/math/tools/rational.hpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2016-04-23T04:55:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-19T10:26:27.000Z", "max_issues_repo_path": "lshkit/trunk/3rd-party/boost/boost/math/tools/rational.hpp", "max_issues_repo_name": "mrfarhadi/BinClone", "max_issues_repo_head_hexsha": "035c20ab27ec00935c12ce54fe9c52bba4aaeff2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-12-26T21:49:18.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-11T04:03:44.000Z", "max_forks_repo_path": "lshkit/trunk/3rd-party/boost/boost/math/tools/rational.hpp", "max_forks_repo_name": "mrfarhadi/BinClone", "max_forks_repo_head_hexsha": "035c20ab27ec00935c12ce54fe9c52bba4aaeff2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T13:16:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T06:13:14.000Z", "avg_line_length": 39.8293413174, "max_line_length": 130, "alphanum_fraction": 0.7652409231, "num_tokens": 3521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.285220232519147}}
{"text": "// smooth_feedback: Control theory on Lie groups\n// https://github.com/pettni/smooth_feedback\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef SMOOTH__FEEDBACK__MESH_FUNCTION_HPP_\n#define SMOOTH__FEEDBACK__MESH_FUNCTION_HPP_\n\n/**\n * @file\n * @brief Evaluate transform-like functions and derivatives on collocation points.\n */\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n#include <smooth/diff.hpp>\n\n#include \"mesh.hpp\"\n#include \"smooth/feedback/utils/sparse.hpp\"\n\nnamespace smooth::feedback {\n\ntemplate<uint8_t Deriv>\nstruct MeshValue;\n\n/**\n * @brief Result of Mesh function.\n *\n * A generic function is a mapping (t0, tf, q, X, U) -> R^M\n *\n * The function variables are\n * NAME     SIZE\n *   t0        1\n *   tf        1\n *    X nx*(N+1)\n *    U     nu*N\n *\n * Let the total number of variables be K = 2 + nq + nx*(N+1) + nu*N.\n */\ntemplate<>\nstruct MeshValue<0>\n{\n  /// @brief Function value (size M)\n  Eigen::VectorXd F;\n\n  /// @brief If set to true correct allocation is assumed, and no allocation is performed.\n  bool allocated{false};\n};\n\n/**\n * @brief Result and first derivative of Mesh function.\n *\n * @see MeshValue<0>\n */\ntemplate<>\nstruct MeshValue<1> : public MeshValue<0>\n{\n  /// @brief Size M x numVar\n  Eigen::SparseMatrix<double> dF;\n};\n\n/**\n * @brief Result, first, and second derivatives w.r.t. collocation variables\n *\n * @see MeshValue<0>, MeshValue<1>\n */\ntemplate<>\nstruct MeshValue<2> : public MeshValue<1>\n{\n  /// @brief Multipliers (must be set before)\n  Eigen::VectorXd lambda;\n\n  /// @brief Size numVar x numVar\n  Eigen::SparseMatrix<double> d2F;\n};\n\n/**\n * @brief Reset MeshValue to zeros.\n *\n * If sparse matrices are compressed the coefficients are set to zero, otherwise coefficients are\n * removed but memory is kept.\n */\ntemplate<uint8_t Deriv>\nvoid set_zero(MeshValue<Deriv> & mv)\n{\n  mv.F.setZero();\n  if constexpr (Deriv >= 1) { set_zero(mv.dF); }\n  if constexpr (Deriv >= 2) { set_zero(mv.d2F); }\n}\n\n/**\n * @brief Evaluate function over a mesh.\n *\n * @tparam Deriv differentiation order (0, 1, or 2)\n * @tparam DT inner differentiation method (used to differentiate f)\n *\n * Computes the expression\n * \\f[\n *  \\begin{bmatrix}\n *    f(t_0 + (t_f - t_0) \\tau_0, x_0, u_0) \\\\\n *    f(t_0 + (t_f - t_0) \\tau_1, x_1, u_1) \\\\\n *    \\vdots \\\\\n *    f(t_{N-1} + (t_f - t_0) \\tau_{N-1}, x_{N-1}, u_{N-1})\n *  \\end{bmatrix}.\n * \\f]\n *\n * If DT > 0 derivatives w.r.t. t0, tf, {xi} and {ui} are returned.\n *\n * @param out result structure\n * @param m mesh\n * @param f integrand\n * @param t0 initial time parameter\n * @param tf final time parameter\n * @param xs state parameters {xi}\n * @param us input parameters {ui}\n * @param scale scale values with quadrature weights\n */\ntemplate<uint8_t Deriv, diff::Type DT = diff::Type::Default>\n  requires(Deriv <= 2)\nvoid mesh_eval(\n  MeshValue<Deriv> & out,\n  const MeshType auto & m,\n  auto & f,\n  const double t0,\n  const double tf,\n  std::ranges::range auto && xs,\n  std::ranges::range auto && us,\n  bool scale = false)\n{\n  using utils::zip, std::views::iota;\n  using X = PlainObject<std::decay_t<std::ranges::range_value_t<decltype(xs)>>>;\n  using U = PlainObject<std::decay_t<std::ranges::range_value_t<decltype(us)>>>;\n\n  static constexpr auto nx = Dof<X>;\n  static constexpr auto nu = Dof<U>;\n  static constexpr auto nf = Dof<std::invoke_result_t<decltype(f), double, X, U>>;\n\n  static_assert(nx > -1, \"State dimension must be static\");\n  static_assert(nu > -1, \"Input dimension must be static\");\n  static_assert(nf > -1, \"Output size must be static\");\n\n  const auto N = m.N_colloc();\n\n  const Eigen::Index numOuts = nf * N;\n  const Eigen::Index numVars = 2 + nx * (N + 1) + nu * N;\n\n  // ALLOCATION\n\n  if (!out.allocated) {\n    out.F.resize(numOuts);\n\n    if constexpr (Deriv >= 1) {\n      Eigen::VectorXi pattern = Eigen::VectorXi::Zero(numVars);\n      pattern.segment(0, 1).setConstant(numOuts);                 // t0 is dense\n      pattern.segment(1, 1).setConstant(numOuts);                 // tf is dense\n      pattern.segment(2, nx * N).setConstant(nf);                 // block diagonal, last x not used\n      pattern.segment(2 + nx * (N + 1), nu * N).setConstant(nf);  // block diagonal\n\n      out.dF.resize(numOuts, numVars);\n      out.dF.reserve(pattern);\n    }\n\n    if constexpr (Deriv >= 2u) {\n      Eigen::VectorXi pattern = Eigen::VectorXi::Zero(numVars);\n      pattern.segment(0, 1).setConstant(1);  // t0\n      pattern.segment(1, 1).setConstant(2);  // t0, tf\n      for (auto i = 0u; i < N; ++i) {\n        for (auto j = 0u; j < nx; ++j) {\n          pattern(2 + nx * i + j) = 2 + (j + 1);  // t0, tf, x upper diag\n        }\n      }\n      for (auto i = 0u; i < N; ++i) {\n        for (auto j = 0u; j < nu; ++j) {\n          pattern(2 + nx * (N + 1) + nu * i + j) = 2 + nx + (j + 1);  // t0, tf, x, u upper diag\n        }\n      }\n      out.d2F.resize(numVars, numVars);\n      out.d2F.reserve(pattern);\n    }\n\n    out.allocated = true;\n  }\n\n  set_zero(out);\n\n  for (const auto & [i, tau, w_quad, x, u] :\n       zip(iota(0u, N), m.all_nodes(), m.all_weights(), xs, us)) {\n    const double ti = t0 + (tf - t0) * tau;\n    const X xi      = x;\n    const U ui      = u;\n\n    const double mtau = 1. - tau;\n    const double w    = scale ? w_quad : 1.;\n\n    const auto fvals = diff::dr<Deriv, DT>(f, wrt(ti, xi, ui));\n\n    out.F.segment(i * nf, nf) = w * std::get<0>(fvals);\n\n    if constexpr (Deriv >= 1u) {\n      const auto & df = std::get<1>(fvals);\n      const auto row0 = nf * i;\n\n      block_add(out.dF, row0, 0, df.middleCols(0, 1), w * mtau);\n      block_add(out.dF, row0, 1, df.middleCols(0, 1), w * tau);\n      block_add(out.dF, row0, 2 + i * nx, df.middleCols(1, nx), w);\n      block_add(out.dF, row0, 2 + nx * (N + 1) + nu * i, df.middleCols(1 + nx, nu), w);\n\n      if constexpr (Deriv >= 2u) {\n        assert(out.lambda.size() == numOuts);\n\n        const auto & d2f = std::get<2>(fvals);\n\n        for (auto j = 0u; j < nf; ++j) {\n          const double wl = w * out.lambda(row0 + j);\n\n          // destination block locations\n          const auto t0_d = 0;\n          const auto tf_d = 1;\n          const auto x_d  = 2 + i * nx;\n          const auto u_d  = 2 + (N + 1) * nx + i * nu;\n\n          // source block locations\n          const auto b_s = (1 + nx + nu) * j;\n          const auto t_s = 0;\n          const auto x_s = 1;\n          const auto u_s = 1 + nx;\n\n          // clang-format off\n          // t0 row\n          block_add(out.d2F, t0_d, t0_d, d2f.block(t_s, b_s + t_s, 1, 1 ), wl * mtau * mtau, true);\n          block_add(out.d2F, t0_d, tf_d, d2f.block(t_s, b_s + t_s, 1, 1 ), wl * mtau * tau, true);\n          block_add(out.d2F, t0_d,  x_d, d2f.block(t_s, b_s + x_s, 1, nx), wl * mtau, true);\n          block_add(out.d2F, t0_d,  u_d, d2f.block(t_s, b_s + u_s, 1, nu), wl * mtau, true);\n\n          // tf row\n          block_add(out.d2F, tf_d, tf_d, d2f.block(t_s, b_s + t_s, 1, 1 ), wl * tau * tau, true);\n          block_add(out.d2F, tf_d,  x_d, d2f.block(t_s, b_s + x_s, 1, nx), wl * tau, true);\n          block_add(out.d2F, tf_d,  u_d, d2f.block(t_s, b_s + u_s, 1, nu), wl * tau, true);\n\n          // x row\n          block_add(out.d2F, x_d,  x_d, d2f.block(x_s, b_s + x_s, nx, nx), wl, true);\n          block_add(out.d2F, x_d,  u_d, d2f.block(x_s, b_s + u_s, nx, nu), wl, true);\n\n          // u row\n          block_add(out.d2F, u_d,  u_d, d2f.block(u_s, b_s + u_s, nu, nu), wl, true);\n          // clang-format on\n        }\n      }\n    }\n  }\n}\n\n/**\n * @brief Evaluate integral over a mesh.\n *\n * @tparam Deriv differentiation order (0, 1, or 2)\n * @tparam DT inner differentiation method (used to differentiate f)\n\n * This function approximates the integral\n * \\f[\n *   \\int_{t_0}^{t_f} f(s, x(s), u(s)) \\mathrm{d} s.\n * \\f]\n * by computing the quadrature\n * \\f[\n *    (t_f - t_0) \\sum_{i = 0}^N w_i f(t_0 + (t_f - t_0) \\tau_i, x_i, u_i).\n * \\f]\n *\n * If DT > 0 derivatives w.r.t. t0, tf, {xi} and {ui} are returned.\n *\n * @param out result structure\n * @param m mesh\n * @param f integrand\n * @param t0 initial time parameter\n * @param tf final time parameter\n * @param xs state parameters {xi}\n * @param us input parameters {ui}\n */\ntemplate<uint8_t Deriv, diff::Type DT = diff::Type::Default>\n  requires(Deriv <= 2)\nvoid mesh_integrate(\n  MeshValue<Deriv> & out,\n  const MeshType auto & m,\n  auto & f,\n  const double t0,\n  const double tf,\n  std::ranges::range auto && xs,\n  std::ranges::range auto && us)\n{\n  using utils::zip, std::views::iota;\n  using X = PlainObject<std::decay_t<std::ranges::range_value_t<decltype(xs)>>>;\n  using U = PlainObject<std::decay_t<std::ranges::range_value_t<decltype(us)>>>;\n\n  static constexpr auto nx = Dof<X>;\n  static constexpr auto nu = Dof<U>;\n  static constexpr auto nf = Dof<std::invoke_result_t<decltype(f), double, X, U>>;\n\n  static_assert(nx > -1, \"State dimension must be static\");\n  static_assert(nu > -1, \"Input dimension must be static\");\n  static_assert(nf > -1, \"Output size must be static\");\n\n  const auto N = m.N_colloc();\n\n  const Eigen::Index numOuts = nf;\n  const Eigen::Index numVars = 2 + nx * (N + 1) + nu * N;\n\n  // ALLOCATION\n\n  if (!out.allocated) {\n    out.F.resize(numOuts);\n\n    if constexpr (Deriv >= 1) {\n      Eigen::VectorXi pattern = Eigen::VectorXi::Constant(numVars, numOuts);  // dense\n      pattern.segment(2 + nx * N, nx).setZero();\n\n      out.dF.resize(numOuts, numVars);\n      out.dF.reserve(pattern);\n    }\n\n    if constexpr (Deriv >= 2) {\n      Eigen::VectorXi pattern = Eigen::VectorXi::Zero(numVars);  // dense\n      pattern(0)              = 1;                               // t0 dense\n      pattern(1)              = 2;                               // tf dense\n      for (auto i = 0u; i < N; ++i) {\n        for (auto j = 0u; j < nx; ++j) {\n          pattern(2 + nx * i + j) = 2 + (j + 1);  // t0, tf, x upper diag\n        }\n      }\n      for (auto i = 0u; i < N; ++i) {\n        for (auto j = 0u; j < nu; ++j) {\n          pattern(2 + nx * (N + 1) + nu * i + j) = 2 + nx + (j + 1);  // t0, tf, x, u upper diag\n        }\n      }\n\n      out.d2F.resize(numVars, numVars);\n      out.d2F.reserve(pattern.replicate(numOuts, 1).reshaped());\n    }\n\n    out.allocated = true;\n  }\n\n  set_zero(out);\n\n  for (const auto & [i, tau, w, x, u] : zip(iota(0u, N), m.all_nodes(), m.all_weights(), xs, us)) {\n    const double ti = t0 + (tf - t0) * tau;\n    const X xi      = x;\n    const U ui      = u;\n\n    const double mtau = 1. - tau;\n\n    const auto fvals = diff::dr<Deriv, DT>(f, wrt(ti, xi, ui));\n\n    const auto & fval = std::get<0>(fvals);\n    out.F.noalias() += w * (tf - t0) * fval;\n\n    if constexpr (Deriv >= 1u) {\n      const auto & df = std::get<1>(fvals);\n      // t0\n      block_add(out.dF, 0, 0, df.middleCols(0, 1), w * (tf - t0) * mtau);\n      block_add(out.dF, 0, 0, fval, -w);\n      // tf\n      block_add(out.dF, 0, 1, df.middleCols(0, 1), w * (tf - t0) * tau);\n      block_add(out.dF, 0, 1, fval, w);\n      // x\n      block_add(out.dF, 0, 2 + i * nx, df.middleCols(1, nx), w * (tf - t0));\n      // u\n      block_add(out.dF, 0, 2 + nx * (N + 1) + nu * i, df.middleCols(1 + nx, nu), w * (tf - t0));\n\n      if constexpr (Deriv >= 2u) {\n        assert(out.lambda.size() == numOuts);\n\n        const auto & d2f = std::get<2>(fvals);\n\n        for (auto j = 0u; j < nf; ++j) {\n          const double wl = w * out.lambda(j);\n\n          // source block locations\n          const auto b_s = (1 + nx + nu) * j;  // horizontal block\n          const auto t_s = 0;                  // t\n          const auto x_s = 1;                  // x\n          const auto u_s = 1 + nx;             // u\n\n          // destination block locations\n          const auto t0_d = 0;                          // t0\n          const auto tf_d = 1;                          // tf\n          const auto x_d  = 2 + nx * i;                 // x[i]\n          const auto u_d  = 2 + nx * (N + 1) + nu * i;  // u[i]\n\n          // clang-format off\n          // t0t0\n          block_add(out.d2F, t0_d, t0_d, d2f.block(t_s, b_s + t_s, 1,  1), wl * (tf - t0) * mtau * mtau, true);\n          block_add(out.d2F, t0_d, t0_d,  df.block(j,         t_s, 1,  1), -wl * 2 * mtau, true);\n          // t0tf\n          block_add(out.d2F, t0_d, tf_d, d2f.block(t_s, b_s + t_s, 1,  1), wl * (tf - t0) * mtau * tau, true);\n          block_add(out.d2F, t0_d, tf_d,  df.block(j,         t_s, 1,  1), wl * (1 - 2 * tau), true);\n          // t0x\n          block_add(out.d2F, t0_d, x_d,  d2f.block(t_s, b_s + x_s, 1, nx), wl * (tf - t0) * mtau, true);\n          block_add(out.d2F, t0_d, x_d,   df.block(j,         x_s, 1, nx), -wl, true);\n          // t0u\n          block_add(out.d2F, t0_d, u_d,  d2f.block(t_s, b_s + u_s, 1, nu), wl * (tf - t0) * mtau, true);\n          block_add(out.d2F, t0_d, u_d,   df.block(j,         u_s, 1, nu), -wl, true);\n\n          // tftf\n          block_add(out.d2F, tf_d, tf_d, d2f.block(t_s, b_s + t_s, 1,  1), wl * (tf - t0) * tau * tau, true);\n          block_add(out.d2F, tf_d, tf_d,  df.block(j,         t_s, 1,  1), wl * 2 * tau, true);\n          // tfx\n          block_add(out.d2F, tf_d, x_d,  d2f.block(t_s, b_s + x_s, 1, nx), wl * (tf - t0) * tau, true);\n          block_add(out.d2F, tf_d, x_d,   df.block(j,         x_s, 1, nx), wl, true);\n          // tfu\n          block_add(out.d2F, tf_d, u_d,  d2f.block(t_s, b_s + u_s, 1, nu), wl * (tf - t0) * tau, true);\n          block_add(out.d2F, tf_d, u_d,   df.block(j,         u_s, 1, nu), wl, true);\n\n          // xx\n          block_add(out.d2F, x_d, x_d,  d2f.block(x_s, b_s + x_s, nx, nx), wl * (tf - t0), true);\n          // xu\n          block_add(out.d2F, x_d, u_d,  d2f.block(x_s, b_s + u_s, nx, nu), wl * (tf - t0), true);\n\n          // uu\n          block_add(out.d2F, u_d, u_d,  d2f.block(u_s, b_s + u_s, nu, nu), wl * (tf - t0), true);\n          // clang-format on\n        }\n      }\n    }\n  }\n}\n\n/**\n * @brief Evaluate dynamic constraints over a mesh (differentiation version).\n *\n * @tparam Deriv differentiation order (0, 1, or 2)\n * @tparam DT inner differentiation method (used to differentiate f)\n *\n * For interval \\f$j\\f$ with nodes \\f$\\tau_i\\f$ and weights \\f$w_i\\f$ the corresponding dynamic\n * constraints are a block of the form\n * \\f[\n *   \\begin{bmatrix}\n *     w_0 \\left( f\\left(t_0 + (t_f - t_0) \\tau_0, x_0, u_0\\right) - \\sum_{k=0}^{N_j} D_{k, 0} x_k\n * \\right) \\\\\n *     \\vdots  \\\\\n *     w_{N_j-1} \\left( f\\left(t_0 + (t_f - t_0) \\tau_{N_j-1}, x_{N_j - 1}, u_{N_j - 1}\\right) -\n * \\sum_{k=0}^{N_j} D_{k, N_j-1} x_k \\right) \\end{bmatrix}, \\f] where \\f$D\\f$ is the interval\n * differentiation matrix (see interval_diffmat() in Mesh).\n *\n * This function returnes all such blocks stacked into a 1D vector.\n *\n * If DT > 0 derivatives w.r.t. t0, tf, {xi} and {ui} are returned.\n *\n * @param out result structure\n * @param m mesh\n * @param f right-hand side of dynamics\n * @param t0 initial time parameter\n * @param tf final time parameter\n * @param xs state parameters {xi}\n * @param us input parameters {ui}\n */\ntemplate<uint8_t Deriv, diff::Type DT = diff::Type::Default>\n  requires(Deriv <= 2)\nvoid mesh_dyn(\n  MeshValue<Deriv> & out,\n  const MeshType auto & m,\n  auto & f,\n  const double t0,\n  const double tf,\n  std::ranges::range auto && xs,\n  std::ranges::range auto && us)\n{\n  using utils::zip, std::views::iota;\n  using X = PlainObject<std::decay_t<std::ranges::range_value_t<decltype(xs)>>>;\n  using U = PlainObject<std::decay_t<std::ranges::range_value_t<decltype(us)>>>;\n\n  static constexpr auto nx = Dof<X>;\n  static constexpr auto nu = Dof<U>;\n  static constexpr auto nf = Dof<std::invoke_result_t<decltype(f), double, X, U>>;\n\n  static_assert(nx > -1, \"State dimension must be static\");\n  static_assert(nu > -1, \"Input dimension must be static\");\n  static_assert(nf > -1, \"Output size must be static\");\n  static_assert(nx == nf, \"Output dimension must be same as state dimension\");\n\n  const auto N               = m.N_colloc();\n  const Eigen::Index numOuts = nx * N;\n  const Eigen::Index numVars = 2 + nx * (N + 1) + nu * N;\n\n  // ALLOCATION\n\n  if (!out.allocated) {\n    out.F.resize(numOuts);\n\n    if constexpr (Deriv >= 1) {\n      Eigen::VectorXi pattern = Eigen::VectorXi::Zero(numVars);\n      pattern(0)              = numOuts;  // t0 dense\n      pattern(1)              = numOuts;  // tf dense\n\n      // x has blocks depending on mesh size\n      auto idx0 = 2u;\n      for (auto ival = 0u; ival < m.N_ivals(); ++ival) {\n        const std::size_t K = m.N_colloc_ival(ival);\n        pattern.segment(idx0, K * nx) += Eigen::VectorXi::Constant(K * nx, nx + K - 1);\n        pattern.segment(idx0 + K * nx, nx) += Eigen::VectorXi::Constant(nx, K);\n        idx0 += K * nx;\n      }\n\n      // u is block diagonal with small blocks\n      pattern.segment(2 + nx * (N + 1), nu * N).setConstant(nx);\n\n      out.dF.resize(numOuts, numVars);\n      out.dF.reserve(pattern);\n    }\n\n    if constexpr (Deriv >= 2) {\n      Eigen::VectorXi pattern = Eigen::VectorXi::Zero(numVars);\n      pattern(0)              = 1;\n      pattern(1)              = 2;\n      for (auto i = 0u; i < N; ++i) {\n        for (auto j = 0u; j < nx; ++j) {\n          pattern(2 + nx * i + j) = 2 + (j + 1);  // t0, tf, x upper diag\n        }\n      }\n      for (auto i = 0u; i < N; ++i) {\n        for (auto j = 0u; j < nu; ++j) {\n          pattern(2 + nx * (N + 1) + nu * i + j) = 2 + nx + (j + 1);  // t0, tf, x, u upper diag\n        }\n      }\n\n      out.d2F.resize(numVars, numVars);\n      out.d2F.reserve(pattern);\n    }\n\n    out.allocated = true;\n  }\n\n  set_zero(out);\n\n  // We build the constraint through two loops over xi:\n  //   - the first loop adds wk * f(tk, xk, uk)\n  //   - the second loop adds -wk * [x0 ... Xni] * dk\n\n  // ADD FIRST PART\n\n  for (const auto & [i, tau, w, x, u] : zip(iota(0u, N), m.all_nodes(), m.all_weights(), xs, us)) {\n    const double ti = t0 + (tf - t0) * tau;\n    const X xi      = x;\n    const U ui      = u;\n\n    const auto row0   = nx * i;\n    const double mtau = 1. - tau;\n\n    const auto fvals = diff::dr<Deriv, DT>(f, wrt(ti, xi, ui));\n    const auto fval  = std::get<0>(fvals);\n\n    out.F.segment(row0, nx) += w * (tf - t0) * fval;\n\n    if constexpr (Deriv >= 1) {\n      const auto & df = std::get<1>(fvals);\n\n      // clang-format off\n      // dF/dt0 = -f + (tf - t0) * df/dti * (1-tau)\n      block_add(out.dF, row0, 0, fval, -w);\n      block_add(out.dF, row0, 0, df.col(0), w * (tf - t0) * mtau);\n      // dF/dtf = f + (tf - t0) * df/dti * tau\n      block_add(out.dF, row0, 1, fval, w);\n      block_add(out.dF, row0, 1, df.col(0), w * (tf - t0) * tau);\n      // dF/dx\n      block_add(out.dF, row0, 2 + nx * i, df.middleCols(1, nx), w * (tf - t0));\n      // dF/du\n      block_add(out.dF, row0, 2 + nx * (N + 1) + nu * i, df.middleCols(1 + nx, nu), w * (tf - t0));\n      // clang-format on\n\n      if constexpr (Deriv >= 2) {\n        assert(out.lambda.size() == numOuts);\n\n        const auto & d2f = std::get<2>(fvals);\n\n        for (auto j = 0u; j < nx; ++j) {\n          const double wl = w * out.lambda(row0 + j);\n\n          // destination block locations\n          const auto t0_d = 0;\n          const auto tf_d = 1;\n          const auto x_d  = 2 + i * nx;\n          const auto u_d  = 2 + (N + 1) * nx + i * nu;\n\n          // source block locations\n          const auto b_s = (1 + nx + nu) * j;\n          const auto t_s = 0;\n          const auto x_s = 1;\n          const auto u_s = 1 + nx;\n\n          // clang-format off\n          // t0t0\n          block_add(out.d2F, t0_d, t0_d, d2f.block(t_s, b_s + t_s, 1, 1 ), wl * (tf - t0) * mtau * mtau, true);\n          block_add(out.d2F, t0_d, t0_d,  df.block(j,         t_s, 1, 1 ), -wl * 2 * mtau, true);\n          // t0tf\n          block_add(out.d2F, t0_d, tf_d, d2f.block(t_s, b_s + t_s, 1, 1 ), wl * (tf - t0) * mtau * tau, true);\n          block_add(out.d2F, t0_d, tf_d,  df.block(j,         t_s, 1, 1 ), wl * (1. - 2 * tau), true);\n          // t0x\n          block_add(out.d2F, t0_d, x_d, d2f.block(t_s, b_s + x_s, 1, nx), wl * (tf - t0) * mtau, true);\n          block_add(out.d2F, t0_d, x_d,  df.block(j,         x_s, 1, nx), -wl, true);\n          // t0u\n          block_add(out.d2F, t0_d, u_d, d2f.block(t_s, b_s + u_s, 1, nu), wl * (tf - t0) * mtau, true);\n          block_add(out.d2F, t0_d, u_d,  df.block(j,         u_s, 1, nu), -wl, true);\n\n          // tftf\n          block_add(out.d2F, tf_d, tf_d, d2f.block(t_s, b_s + t_s, 1,  1), wl * (tf - t0) * tau * tau, true);\n          block_add(out.d2F, tf_d, tf_d,  df.block(j,         t_s, 1,  1), wl * 2 * tau, true);\n          // tfx\n          block_add(out.d2F, tf_d, x_d,  d2f.block(t_s, b_s + x_s, 1, nx), wl * (tf - t0) * tau, true);\n          block_add(out.d2F, tf_d, x_d,   df.block(j,         x_s, 1, nx), wl, true);\n          // tfu\n          block_add(out.d2F, tf_d, u_d,  d2f.block(t_s, b_s + u_s, 1, nu), wl * (tf - t0) * tau, true);\n          block_add(out.d2F, tf_d, u_d,   df.block(j,         u_s, 1, nu), wl, true);\n\n          // xx\n          block_add(out.d2F, x_d, x_d,  d2f.block(x_s, b_s + x_s, nx, nx), wl * (tf - t0), true);\n          // xu\n          block_add(out.d2F, x_d, u_d,  d2f.block(x_s, b_s + u_s, nx, nu), wl * (tf - t0), true);\n\n          // uu\n          block_add(out.d2F, u_d, u_d,  d2f.block(u_s, b_s + u_s, nu, nu), wl * (tf - t0), true);\n          // clang-format on\n        }\n      }\n    }\n  }\n\n  // ADD SECOND PART (LINEAR IN X, NO SECOND DERIVATIVE..)\n\n  auto ival      = 0u;  // current interval index\n  auto ival_idx0 = 0u;  // node start index of current interval\n  auto Nival     = m.N_colloc_ival(ival);\n\n  for (const auto & [i, x] : zip(iota(0u, N + 1), xs)) {\n    if (i == ival_idx0 + Nival) {\n      // jumping to new interval --- add overlap to current interval before switching\n      const auto [alpha, Dus] = m.interval_diffmat_unscaled(ival);\n      for (const auto & [j, w] : zip(iota(0u, Nival), m.interval_weights(ival))) {\n        const auto row0   = (ival_idx0 + j) * nx;\n        const double coef = -w * alpha * Dus(i - ival_idx0, j);\n\n        out.F.segment(row0, nx) += coef * x;\n\n        if constexpr (Deriv >= 1) {\n          // add diagonal matrix\n          for (auto k = 0u; k < nx; ++k) { out.dF.coeffRef(row0 + k, 2 + nx * i + k) += coef; }\n        }\n      }\n\n      // update interval\n      ++ival;\n      if (ival < m.N_ivals()) {\n        ival_idx0 += Nival;\n        Nival = m.N_colloc_ival(ival);\n      }\n    }\n\n    if (i < N) {\n      const auto [alpha, Dus] = m.interval_diffmat_unscaled(ival);\n      for (const auto & [j, w] : zip(iota(0u, Nival), m.interval_weights(ival))) {\n        const auto row0   = (ival_idx0 + j) * nx;\n        const double coef = -w * alpha * Dus(i - ival_idx0, j);\n\n        out.F.segment(row0, nx) += coef * x;\n\n        if constexpr (Deriv >= 1) {\n          // add diagonal matrix\n          for (auto k = 0u; k < nx; ++k) { out.dF.coeffRef(row0 + k, 2 + nx * i + k) += coef; }\n        }\n      }\n    }\n  }\n}\n\n}  // namespace smooth::feedback\n\n#endif  // SMOOTH__FEEDBACK__MESH_FUNCTION_HPP_\n", "meta": {"hexsha": "3f8c1ec9e808453fa51dfbe64e0e3d1284f2e003", "size": 24086, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/feedback/collocation/mesh_function.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/collocation/mesh_function.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/collocation/mesh_function.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.6063218391, "max_line_length": 111, "alphanum_fraction": 0.5531844225, "num_tokens": 8106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.285220232519147}}
{"text": "/***********************************************************************************************************************\n *  OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. 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\n *  following 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\n *  products 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\n *  works may not use the \"OpenStudio\" trademark, \"OS\", \"os\", or any other confusingly similar designation without\n *  specific prior written permission from Alliance for Sustainable Energy, LLC.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 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, THE UNITED STATES GOVERNMENT, OR ANY CONTRIBUTORS BE LIABLE FOR\n *  ANY DIRECT, 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) HOWEVER CAUSED\n *  AND ON ANY THEORY OF LIABILITY, WHETHER IN 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 POSSIBILITY OF SUCH DAMAGE.\n **********************************************************************************************************************/\n\n#ifndef UTILITIES_GEOMETRY_INTERSECTION_HPP\n#define UTILITIES_GEOMETRY_INTERSECTION_HPP\n\n#include \"../UtilitiesAPI.hpp\"\n\n#include \"Point3d.hpp\"\n\n#include <vector>\n#include <boost/optional.hpp>\n\nnamespace openstudio{\n\n  /** IntersectionResult contains detailed information about an intersection. */\n  class UTILITIES_API IntersectionResult {\n  public:\n    IntersectionResult(const std::vector<Point3d>& polygon1,\n                       const std::vector<Point3d>& polygon2,\n                       const std::vector< std::vector<Point3d> >& newPolygons1,\n                       const std::vector< std::vector<Point3d> >& newPolygons2);\n\n    // vertices of first polygon after intersection\n    std::vector<Point3d> polygon1() const;\n\n    // vertices of second polygon after intersection\n    std::vector<Point3d> polygon2() const;\n\n    // new polygons generated from the first surface\n    std::vector< std::vector<Point3d> > newPolygons1() const;\n\n    // new polygons generated from the second surface\n    std::vector< std::vector<Point3d> > newPolygons2() const;\n\n  private:\n    std::vector<Point3d> m_polygon1;\n    std::vector<Point3d> m_polygon2;\n    std::vector< std::vector<Point3d> > m_newPolygons1;\n    std::vector< std::vector<Point3d> > m_newPolygons2;\n  };\n\n  /// removes spikes from a polygon, requires that all vertices are in clockwise order on the z = 0 plane (i.e. in face coordinates but reversed)\n  UTILITIES_API std::vector<Point3d> removeSpikes(const std::vector<Point3d>& polygon, double tol);\n\n  /// returns true if point is inside polygon, requires that all vertices are in clockwise order on the z = 0 plane (i.e. in face coordinates but reversed)\n  UTILITIES_API bool pointInPolygon(const Point3d& point, const std::vector<Point3d>& polygon, double tol);\n\n  /// compute the union of two overlapping polygons, requires that all vertices are in clockwise order on the z = 0 plane (i.e. in face coordinates but reversed)\n  UTILITIES_API boost::optional<std::vector<Point3d> > join(const std::vector<Point3d>& polygon1, const std::vector<Point3d>& polygon2, double tol);\n\n  /// compute the union of many polygons, requires that all vertices are in clockwise order on the z = 0 plane (i.e. in face coordinates but reversed)\n  UTILITIES_API std::vector<std::vector<Point3d> > joinAll(const std::vector<std::vector<Point3d> >& polygons, double tol);\n\n  /// intersect two polygons, requires that all vertices are in clockwise order on the z = 0 plane (i.e. in face coordinates but reversed)\n  UTILITIES_API boost::optional<IntersectionResult> intersect(const std::vector<Point3d>& polygon1, const std::vector<Point3d>& polygon2, double tol);\n\n  /// subtract all holes from polygon, requires that all vertices are in clockwise order on the z = 0 plane (i.e. in face coordinates but reversed)\n  UTILITIES_API std::vector<std::vector<Point3d> > subtract(const std::vector<Point3d>& polygon, const std::vector<std::vector<Point3d> >& holes, double tol);\n\n  /// returns true polygon intersects iteself, requires that all vertices are in clockwise order on the z = 0 plane (i.e. in face coordinates but reversed)\n  /// returns false if polygon has less than three vertices\n  UTILITIES_API bool selfIntersects(const std::vector<Point3d>& polygon, double tol);\n\n  /// returns true if polygon1 intersects polygon2, requires that all vertices are in clockwise order on the z = 0 plane (i.e. in face coordinates but reversed)\n  /// returns false if either polygon has less than three vertices\n  UTILITIES_API bool intersects(const std::vector<Point3d>& polygon1, const std::vector<Point3d>& polygon2, double tol);\n\n  /// returns true if geometry1 is completely within polygon2, requires that all vertices are in clockwise order on the z = 0 plane (i.e. in face coordinates but reversed)\n  /// geometry1 can be a point or a polygon\n  /// currently only tests that all points of geometry1 are within polygon2, better support when upgrade to boost 1.57\n  UTILITIES_API bool within(const Point3d& point1, const std::vector<Point3d>& polygon2, double tol);\n  UTILITIES_API bool within(const std::vector<Point3d>& geometry1, const std::vector<Point3d>& polygon2, double tol);\n\n  /// simplify a list of vertices\n  UTILITIES_API std::vector<Point3d> simplify(const std::vector<Point3d>& vertices, bool removeCollinear, double tol);\n\n} // openstudio\n\n#endif //UTILITIES_GEOMETRY_INTERSECTION_HPP\n", "meta": {"hexsha": "0eda718a6877d17ca1a6b72169772d4d41ba450b", "size": 6614, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3DViewer/src/utilities/geometry/Intersection.hpp", "max_stars_repo_name": "nschrader/floorspace.js", "max_stars_repo_head_hexsha": "236da0deecdb98fde2f4c79e6f55873b3113df58", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2017-12-21T20:40:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T14:08:11.000Z", "max_issues_repo_path": "3DViewer/src/utilities/geometry/Intersection.hpp", "max_issues_repo_name": "nschrader/floorspace.js", "max_issues_repo_head_hexsha": "236da0deecdb98fde2f4c79e6f55873b3113df58", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 139.0, "max_issues_repo_issues_event_min_datetime": "2017-12-06T22:24:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T01:51:14.000Z", "max_forks_repo_path": "3DViewer/src/utilities/geometry/Intersection.hpp", "max_forks_repo_name": "nschrader/floorspace.js", "max_forks_repo_head_hexsha": "236da0deecdb98fde2f4c79e6f55873b3113df58", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2018-05-02T21:33:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T09:58:04.000Z", "avg_line_length": 62.3962264151, "max_line_length": 171, "alphanum_fraction": 0.7242213487, "num_tokens": 1469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.285220232519147}}
{"text": "// Copyright (c) 2017 Jeffrey Ichnowski\n// All rights reserved.\n//\n// BSD 3 Clause\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// 1. Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n//    notice, this list of conditions and the following disclaimer in the\n//    documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the copyright holder nor the names of its\n//    contributors may be used to endorse or promote products derived\n//    from this software without specific prior written permission.\n// \n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\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#pragma once\n#ifndef UNC_ROBOTICS_KDTREE_SPACES_HPP\n#define UNC_ROBOTICS_KDTREE_SPACES_HPP\n\n#include <Eigen/Dense>\n#include <tuple>\n#include <functional>\n#include <utility>\n#include <type_traits>\n#include <ratio>\n#include \"_tuple.hpp\"\n\nnamespace unc {\nnamespace robotics {\nnamespace kdtree {\n\nnamespace detail {\ntemplate <typename _Scalar, int _dimensions>\nclass L2SpaceBase {\npublic:\n    typedef _Scalar Distance;\n    typedef Eigen::Matrix<_Scalar, _dimensions, 1> State;\n\n    template <typename _Derived>\n    bool isValid(const Eigen::MatrixBase<_Derived>& q) const {\n        return q.rows() == _dimensions && q.cols() == 1 && q.allFinite();\n    }\n\n    template <typename _DerivedA, typename _DerivedB>\n    constexpr Distance distance(\n        const Eigen::MatrixBase<_DerivedA>& a,\n        const Eigen::MatrixBase<_DerivedB>& b) const\n    {\n        return (a - b).norm();\n    }\n\n    template <typename _DerivedA, typename _DerivedB>\n    constexpr State interpolate(\n        const Eigen::MatrixBase<_DerivedA>& from,\n        const Eigen::MatrixBase<_DerivedB>& to,\n        Distance t) const\n    {\n        return from + (to - from) * t;\n    }\n};\n}\n\ntemplate <typename _Scalar, int _dimensions>\nclass L2Space : public detail::L2SpaceBase<_Scalar, _dimensions> {\npublic:\n    L2Space(unsigned dimensions = _dimensions) {\n        assert(dimensions == _dimensions);\n    }\n\n    constexpr unsigned dimensions() const { return _dimensions; }\n\n    template <typename _Derived>\n    bool isValid(const Eigen::MatrixBase<_Derived>& q) const {\n        return q.rows() == _dimensions && detail::L2SpaceBase<_Scalar, _dimensions>::isValid(q);\n    }\n};\n\ntemplate <typename _Scalar>\nclass L2Space<_Scalar, Eigen::Dynamic> : public detail::L2SpaceBase<_Scalar, Eigen::Dynamic> {\n    unsigned dimensions_;\n    \npublic:\n    L2Space(unsigned dimensions)\n        : dimensions_(dimensions)\n    {\n    }\n\n    constexpr unsigned dimensions() const {\n        return dimensions_;\n    }\n\n    template <typename _Derived>\n    bool isValid(const Eigen::MatrixBase<_Derived>& q) const {\n        return q.rows() == dimensions_ && detail::L2SpaceBase<_Scalar, Eigen::Dynamic>::isValid(q);\n    }\n};\n\ntemplate <typename _Scalar, int _dimensions>\nclass BoundedL2Space : public L2Space<_Scalar, _dimensions> {\n    Eigen::Array<_Scalar, _dimensions, 2> bounds_;\n    \n    typedef typename Eigen::Array<_Scalar, _dimensions, 2>::Index Index;\n\n    void checkBounds() {\n        assert((bounds_.col(0) < bounds_.col(1)).all());\n        assert((bounds_.col(1) - bounds_.col(0)).allFinite());\n    }\n\npublic:\n    using typename L2Space<_Scalar, _dimensions>::State;\n\n    template <typename _Derived>\n    BoundedL2Space(const Eigen::DenseBase<_Derived>& bounds)\n        : L2Space<_Scalar, _dimensions>(bounds.rows()),\n          bounds_(bounds)\n    {\n        checkBounds();\n    }\n\n    template <typename _DerivedMin, typename _DerivedMax>\n    BoundedL2Space(\n        const Eigen::DenseBase<_DerivedMin>& min,\n        const Eigen::DenseBase<_DerivedMax>& max)\n        : L2Space<_Scalar, _dimensions>(min.rows())\n    {\n        bounds_.col(0) = min;\n        bounds_.col(1) = max;\n    }\n\n    template <typename _Derived>\n    bool isValid(const Eigen::MatrixBase<_Derived>& q) const {\n        return L2Space<_Scalar, _dimensions>::isValid(q)\n            && (bounds_.col(0) <= q).all()\n            && (bounds_.col(1) >= q).all();\n    }\n\n    const Eigen::Array<_Scalar, _dimensions, 2>& bounds() const {\n        return bounds_;\n    }\n\n    _Scalar bounds(Index dim, Index j) const {\n        return bounds_(dim, j);\n    }\n};\n\ntemplate <typename _Scalar>\nclass SO3Space {\npublic:\n    typedef _Scalar Distance;\n    typedef Eigen::Quaternion<_Scalar> State;\n\n    constexpr unsigned dimensions() const { return 3; }\n\n    template <typename _Derived>\n    bool isValid(const Eigen::QuaternionBase<_Derived>& q) const {\n        return std::abs(1 - q.coeffs().squaredNorm()) <= 1e-5;\n    }\n\n    template <typename _DerivedA, typename _DerivedB>\n    inline Distance distance(\n        const Eigen::QuaternionBase<_DerivedA>& a,\n        const Eigen::QuaternionBase<_DerivedB>& b) const\n    {\n        Distance dot = std::abs(a.coeffs().matrix().dot(b.coeffs().matrix()));\n        return dot < 0 ? M_PI_2 : dot > 1 ? 0 : std::acos(dot);\n    }\n\n    template <typename _DerivedA, typename _DerivedB>\n    constexpr State interpolate(\n        const Eigen::QuaternionBase<_DerivedA>& from,\n        const Eigen::QuaternionBase<_DerivedB>& to,\n        Distance t) const\n    {\n        Distance dq = from.coeffs().matrix().dot(to.coeffs().matrix());\n        if (std::abs(dq) >= 1)\n            return from;\n        \n        Distance theta = std::acos(std::abs(dq));            \n        Distance d = 1 / std::sin(theta);\n        Distance s0 = std::sin((1 - t) * theta);\n        Distance s1 = std::sin(t * theta);\n\n        if (dq < 0)\n            s1 = -s1;\n\n        return State(d * (from.coeffs() * s0 + to.coeffs() * s1));\n    }\n};\n\ntemplate <typename _Scalar>\nclass SO3AltSpace {\npublic:\n    typedef _Scalar Distance;\n    typedef Eigen::Quaternion<_Scalar> State;\n\n    constexpr unsigned dimensions() const { return 3; }\n\n    template <typename _Derived>\n    bool isValid(const Eigen::QuaternionBase<_Derived>& q) const {\n        return std::abs(1 - q.coeffs().squaredNorm()) <= 1e-5;\n    }\n\n    template <typename _DerivedA, typename _DerivedB>\n    inline Distance distance(\n        const Eigen::QuaternionBase<_DerivedA>& a,\n        const Eigen::QuaternionBase<_DerivedB>& b) const\n    {\n        Distance dot = std::abs(a.coeffs().matrix().dot(b.coeffs().matrix()));\n        return dot < 0 ? M_PI_2 : dot > 1 ? 0 : std::acos(dot);\n    }\n};\n\ntemplate <typename _Scalar>\nclass SO3RLSpace {\npublic:\n    typedef _Scalar Distance;\n    typedef Eigen::Quaternion<_Scalar> State;\n\n    constexpr unsigned dimensions() const { return 4; }\n\n    template <typename _Derived>\n    bool isValid(const Eigen::QuaternionBase<_Derived>& q) const {\n        return std::abs(1 - q.coeffs().squaredNorm()) <= 1e-5;\n    }\n\n    template <typename _DerivedA, typename _DerivedB>\n    inline Distance distance(\n        const Eigen::QuaternionBase<_DerivedA>& a,\n        const Eigen::QuaternionBase<_DerivedB>& b) const\n    {\n        Distance dot = std::abs(a.coeffs().matrix().dot(b.coeffs().matrix()));\n        return dot < 0 ? M_PI_2 : dot > 1 ? 0 : std::acos(dot);\n    }\n};\n\ntemplate <typename _Space, typename _Ratio = std::ratio<1>>\nclass RatioWeightedSpace : public _Space {\npublic:\n    typedef _Ratio Ratio;\n\n    static constexpr std::intmax_t num = Ratio::num;\n    static constexpr std::intmax_t den = Ratio::den;\n\n    // inherit constructor\n    using _Space::_Space;\n\n    // RatioWeightedSpace() {}\n\n    RatioWeightedSpace(const _Space& space)\n        : _Space(space)\n    {\n    }\n\n    RatioWeightedSpace(_Space&& space)\n        : _Space(std::forward<_Space>(space))\n    {\n    }\n\n    template <typename _A, typename _B>\n    inline typename _Space::Distance distance(const _A& a, const _B& b) const {\n        return _Space::distance(a, b) * num / den;\n    }\n};\n\ntemplate <std::intmax_t num, std::intmax_t den = 1, typename _Space>\nauto makeRatioWeightedSpace(_Space&& space) {\n    return RatioWeightedSpace<_Space, std::ratio<num, den>>(std::forward<_Space>(space));\n}\n\ntemplate <typename _Space>\nclass WeightedSpace : public _Space {\npublic:\n    using typename _Space::Distance;\n\nprivate:\n    Distance weight_;\n\npublic:\n    WeightedSpace(Distance weight, const _Space& space = _Space())\n        : _Space(space), weight_(weight)\n    {\n    }\n\n    WeightedSpace(Distance weight, _Space&& space)\n        : _Space(std::forward<_Space>(space)), weight_(weight)\n    {\n    }\n\n    template <typename ... _Args>\n    WeightedSpace(Distance weight, _Args&& ... args)\n        : _Space(std::forward<_Args>(args)...),\n          weight_(weight)\n    {\n    }\n\n    constexpr Distance weight() const {\n        return weight_;\n    }\n\n    template <typename _A, typename _B>\n    constexpr Distance distance(const _A& a, const _B& b) const {\n        return _Space::distance(a, b) * weight_;\n    }    \n};\n\ntemplate <typename ... _Spaces>\nclass CompoundSpace {\n    typedef std::tuple<_Spaces...> Spaces;\n\n    Spaces spaces_;\n\n    static_assert(sizeof...(_Spaces) > 1, \"compound space must have two or more subspaces\");\n\npublic:\n    typedef std::tuple<typename _Spaces::State...> State;\n    typedef typename detail::SumResultType<typename _Spaces::Distance...>::type Distance;\n\n    explicit CompoundSpace() {\n    }\n    \n    explicit CompoundSpace(const _Spaces& ... args)\n        : spaces_(args...)\n    {\n    }\n\n    template <typename ... _Args>\n    explicit CompoundSpace(_Args&& ... args)\n        : spaces_(std::forward<_Args>(args)...)\n    {\n    }\n\n    template <std::size_t I>\n    constexpr typename std::tuple_element<I, Spaces>::type& get() {\n        return std::get<I>(spaces_);\n    }\n\n    template <std::size_t I>\n    constexpr typename std::tuple_element<I, Spaces>::type const& get() const {\n        return std::get<I>(spaces_);\n    }\n\n    inline constexpr unsigned dimensions() const {\n        using namespace detail;\n        return sum(map([](const auto& space) { return space.dimensions(); }, spaces_));\n    }\n\n    template <typename _State>\n    bool isValid(_State&& q) const {\n        using namespace detail;\n        // TODO: return reduce(std::logical_and<bool>(), zip([](auto&& subs, auto&& subq) { return subs.isValid(subq); }, spaces_, q));\n        assert(false);\n        return false;\n    }\n\n    template <typename _StateA, typename _StateB>\n    inline Distance distance(_StateA&& a, _StateB&& b) const {\n        using namespace detail;\n        return sum(zip([](auto&& subs, auto&& suba, auto&& subb) {\n                    return subs.distance(suba, subb);\n                }, spaces_, a, b));\n    }\n\nprivate:\n    template <typename _StateA, typename _StateB, std::size_t ... I>\n    constexpr State interpolate(\n        const _StateA& from,\n        const _StateB& to,\n        Distance t,\n        std::index_sequence<I...>) const\n    {\n        return State(std::get<I>(spaces_).interpolate(std::get<I>(from), std::get<I>(to), t)...);\n    }\n\npublic:\n    template <typename _StateA, typename _StateB>\n    constexpr State interpolate(\n        const _StateA& from,\n        const _StateB& to,\n        Distance t) const\n    {\n        return interpolate(from, to, t, std::make_index_sequence<sizeof...(_Spaces)>{});\n    }\n\n};\n\ntemplate <typename ... _Spaces>\nconstexpr auto makeCompoundSpace(_Spaces&&... args) {\n    return CompoundSpace<typename std::decay<_Spaces>::type...>(std::forward<_Spaces>(args)...);\n}\n\ntemplate <typename _Space>\nconstexpr auto makeWeightedSpace(\n    typename _Space::Distance weight,\n    _Space&& space = _Space())\n{\n    return WeightedSpace<_Space>(weight, std::forward<_Space>(space));\n}\n\ntemplate <typename _Scalar, std::intmax_t _qWeight = 1, std::intmax_t _tWeight = 1>\nusing SE3Space = CompoundSpace<\n    RatioWeightedSpace<SO3Space<_Scalar>, std::ratio<_qWeight>>,\n    RatioWeightedSpace<L2Space<_Scalar, 3>, std::ratio<_tWeight>>>;\n\ntemplate <typename _Scalar, std::intmax_t _qWeight = 1, std::intmax_t _tWeight = 1>\nusing BoundedSE3Space = CompoundSpace<\n    RatioWeightedSpace<SO3Space<_Scalar>, std::ratio<_qWeight>>,\n    RatioWeightedSpace<BoundedL2Space<_Scalar, 3>, std::ratio<_tWeight>>>;\n\n}\n}\n}\n\nnamespace std {\n\ntemplate <std::size_t I, class ... _Spaces>\nclass tuple_element<I, unc::robotics::kdtree::CompoundSpace<_Spaces...>> {\npublic:\n    typedef typename std::tuple_element<I, std::tuple<_Spaces...>>::type type;\n};\n\ntemplate <std::size_t I, class ... _Spaces>\nconstexpr typename std::tuple_element<I, std::tuple<_Spaces...>>::type&\nget(unc::robotics::kdtree::CompoundSpace<_Spaces...>& space) {\n    return space.template get<I>();\n}\n\ntemplate <std::size_t I, class ... _Spaces>\nconstexpr typename std::tuple_element<I, std::tuple<_Spaces...>>::type const&\nget(const unc::robotics::kdtree::CompoundSpace<_Spaces...>& space) {\n    return space.template get<I>();\n}\n\n\n}\n\n#endif // UNC_ROBOTICS_KDTREE_SPACES_HPP\n", "meta": {"hexsha": "616a1e70aa37786f85e8072fbef871cef29cc125", "size": 13648, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/_spaces.hpp", "max_stars_repo_name": "jeffi/kdtree", "max_stars_repo_head_hexsha": "35115fd89e31d0d90f9a228a56a077a8818104aa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T23:22:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T18:53:21.000Z", "max_issues_repo_path": "src/_spaces.hpp", "max_issues_repo_name": "jeffi/kdtree", "max_issues_repo_head_hexsha": "35115fd89e31d0d90f9a228a56a077a8818104aa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/_spaces.hpp", "max_forks_repo_name": "jeffi/kdtree", "max_forks_repo_head_hexsha": "35115fd89e31d0d90f9a228a56a077a8818104aa", "max_forks_repo_licenses": ["BSD-3-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.2616407982, "max_line_length": 135, "alphanum_fraction": 0.6589976553, "num_tokens": 3387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.28486679150201294}}
{"text": "///////////////////////////////////////////////////////////////////////////\n//\n// Copyright (c) 1998-2011, Industrial Light & Magic, a division of Lucas\n// Digital Ltd. LLC\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 are\n// 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 disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// *       Neither the name of Industrial Light & Magic nor the names of\n// its 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 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//\n///////////////////////////////////////////////////////////////////////////\n\n#include \"PyIlmBaseConfigInternal.h\"\n\n#include <Python.h>\n#include <boost/python.hpp>\n#include <boost/python/make_constructor.hpp>\n#include <boost/format.hpp>\n#include <ImathVec.h>\n#include <ImathQuat.h>\n#include <ImathEuler.h>\n#include <ImathFun.h>\n#include <ImathMatrixAlgo.h>\n\n#include <PyIexExport.h>\n#include \"PyImathFixedArray.h\"\n#include \"PyImath.h\"\n#include \"PyImathExport.h\"\n#include \"PyImathBasicTypes.h\"\n#include \"PyImathVec.h\"\n#include \"PyImathMatrix.h\"\n#include \"PyImathBox.h\"\n#include \"PyImathFun.h\"\n#include \"PyImathQuat.h\"\n#include \"PyImathEuler.h\"\n#include \"PyImathColor.h\"\n#include \"PyImathFrustum.h\"\n#include \"PyImathPlane.h\"\n#include \"PyImathLine.h\"\n#include \"PyImathRandom.h\"\n#include \"PyImathShear.h\"\n#include \"PyImathMathExc.h\"\n#include \"PyImathAutovectorize.h\"\n#include \"PyImathStringArrayRegister.h\"\n#include <PyIex.h>\n\nusing namespace boost::python;\n\nnamespace {\n\ntemplate <typename T>\nIMATH_NAMESPACE::Box<IMATH_NAMESPACE::Vec3<T> >\ncomputeBoundingBox(const PyImath::FixedArray<IMATH_NAMESPACE::Vec3<T> >& position)\n{\n    IMATH_NAMESPACE::Box<IMATH_NAMESPACE::Vec3<T> > bounds;\n    int len = position.len();\n    for (int i = 0; i < len; ++i)\n        bounds.extendBy(position[i]);\n    return bounds;\n}\n\nIMATH_NAMESPACE::M44d\nprocrustes1 (PyObject* from_input, \n             PyObject* to_input,\n             PyObject* weights_input = 0,\n             bool doScale = false)\n{\n    // Verify the sequences:\n    if (!PySequence_Check (from_input))\n    {\n        PyErr_SetString (PyExc_TypeError, \"Expected a sequence type for 'from'\");\n        boost::python::throw_error_already_set();\n    }\n        \n    if (!PySequence_Check (to_input))\n    {\n        PyErr_SetString (PyExc_TypeError, \"Expected a sequence type for 'to'\");\n        boost::python::throw_error_already_set();\n    }\n\n    bool useWeights = PySequence_Check (weights_input);\n\n    // Now verify the lengths:\n    const Py_ssize_t n = PySequence_Length (from_input);\n    if (n != PySequence_Length (to_input) ||\n        (useWeights && n != PySequence_Length (weights_input)))\n    {\n        PyErr_SetString (PyExc_TypeError, \"'from, 'to', and 'weights' should all have the same lengths.\");\n        boost::python::throw_error_already_set();\n    }\n\n    std::vector<IMATH_NAMESPACE::V3d> from;  from.reserve (n);\n    std::vector<IMATH_NAMESPACE::V3d> to;    to.reserve (n);\n    std::vector<double> weights;   weights.reserve (n);\n\n    for (Py_ssize_t i = 0; i < n; ++i)\n    {\n        PyObject* f = PySequence_GetItem (from_input, i);\n        PyObject* t = PySequence_GetItem (to_input, i);\n        PyObject* w = 0;\n        if (useWeights)\n            w = PySequence_GetItem (weights_input, i);\n\n        if (f == 0 || t == 0 || (useWeights && w == 0))\n        {\n            PyErr_SetString (PyExc_TypeError,\n                             \"Missing element in array\");\n            boost::python::throw_error_already_set();\n        }\n\n        from.push_back (boost::python::extract<IMATH_NAMESPACE::V3d> (f));\n        to.push_back (boost::python::extract<IMATH_NAMESPACE::V3d> (t));\n        if (useWeights)\n            weights.push_back (boost::python::extract<double> (w));\n    }\n\n    if (useWeights)\n        return IMATH_NAMESPACE::procrustesRotationAndTranslation (&from[0], &to[0], &weights[0], n, doScale);\n    else\n        return IMATH_NAMESPACE::procrustesRotationAndTranslation (&from[0], &to[0], n, doScale);\n}\n\nPyImath::FixedArray2D<int> rangeX(int sizeX, int sizeY)\n{\n    PyImath::FixedArray2D<int> f(sizeX, sizeY);\n    for (int j=0; j<sizeY; j++)\n        for (int i=0; i<sizeX; i++)\n            f(i,j) = i;\n    return f;\n}\n\nPyImath::FixedArray2D<int> rangeY(int sizeX, int sizeY)\n{\n    PyImath::FixedArray2D<int> f(sizeX, sizeY);\n    for (int j=0; j<sizeY; j++)\n        for (int i=0; i<sizeX; i++)\n            f(i,j) = j;\n    return f;\n}\n\n} // namespace\n\nnamespace PyImath {\n\nvoid register_all()\n{\n    scope().attr(\"__doc__\") = \"Imath module\";\n\n    register_basicTypes();\n\n    class_<IntArray2D> iclass2D = IntArray2D::register_(\"IntArray2D\",\"Fixed length array of ints\");\n    add_arithmetic_math_functions(iclass2D);\n    add_mod_math_functions(iclass2D);\n    add_comparison_functions(iclass2D);\n    add_ordered_comparison_functions(iclass2D);\n    add_explicit_construction_from_type<float>(iclass2D);\n    add_explicit_construction_from_type<double>(iclass2D);\n\n    class_<IntMatrix> imclass = IntMatrix::register_(\"IntMatrix\",\"Fixed size matrix of ints\");\n    add_arithmetic_math_functions(imclass);\n\n    class_<FloatArray2D> fclass2D = FloatArray2D::register_(\"FloatArray2D\",\"Fixed length 2D array of floats\");\n    add_arithmetic_math_functions(fclass2D);\n    add_pow_math_functions(fclass2D);\n    add_comparison_functions(fclass2D);\n    add_ordered_comparison_functions(fclass2D);\n    add_explicit_construction_from_type<int>(fclass2D);\n    add_explicit_construction_from_type<double>(fclass2D);\n\n    class_<FloatMatrix> fmclass = FloatMatrix::register_(\"FloatMatrix\",\"Fixed size matrix of floats\");\n    add_arithmetic_math_functions(fmclass);\n    add_pow_math_functions(fmclass);\n\n    class_<DoubleArray2D> dclass2D = DoubleArray2D::register_(\"DoubleArray2D\",\"Fixed length array of doubles\");\n    add_arithmetic_math_functions(dclass2D);\n    add_pow_math_functions(dclass2D);\n    add_comparison_functions(dclass2D);\n    add_ordered_comparison_functions(dclass2D);\n    add_explicit_construction_from_type<int>(dclass2D);\n    add_explicit_construction_from_type<float>(dclass2D);\n\n    class_<DoubleMatrix> dmclass = DoubleMatrix::register_(\"DoubleMatrix\",\"Fixed size matrix of doubles\");\n    add_arithmetic_math_functions(dmclass);\n    add_pow_math_functions(dmclass);\n\n    def(\"rangeX\", &rangeX);\n    def(\"rangeY\", &rangeY);\n\n    //\n    //  Vec2\n    //\n    register_Vec2<short>();\n    register_Vec2<int>();\n    register_Vec2<float>();\n    register_Vec2<double>();\n    class_<FixedArray<IMATH_NAMESPACE::V2s> > v2s_class = register_Vec2Array<short>();\n    class_<FixedArray<IMATH_NAMESPACE::V2i> > v2i_class = register_Vec2Array<int>();\n    class_<FixedArray<IMATH_NAMESPACE::V2f> > v2f_class = register_Vec2Array<float>();\n    class_<FixedArray<IMATH_NAMESPACE::V2d> > v2d_class = register_Vec2Array<double>();\n    add_explicit_construction_from_type<IMATH_NAMESPACE::V2f>(v2i_class);\n    add_explicit_construction_from_type<IMATH_NAMESPACE::V2d>(v2i_class);\n    add_explicit_construction_from_type<IMATH_NAMESPACE::V2i>(v2f_class);\n    add_explicit_construction_from_type<IMATH_NAMESPACE::V2d>(v2f_class);\n    add_explicit_construction_from_type<IMATH_NAMESPACE::V2i>(v2d_class);\n    add_explicit_construction_from_type<IMATH_NAMESPACE::V2f>(v2d_class);\n\n\n    //\n    //  Vec3\n    //\n    register_Vec3<unsigned char>();\n    register_Vec3<short>();\n    register_Vec3<int>();\n    register_Vec3<float>();\n    register_Vec3<double>();\n    class_<FixedArray<IMATH_NAMESPACE::V3s> > v3s_class = register_Vec3Array<short>();\n    class_<FixedArray<IMATH_NAMESPACE::V3i> > v3i_class = register_Vec3Array<int>();\n    class_<FixedArray<IMATH_NAMESPACE::V3f> > v3f_class = register_Vec3Array<float>();\n    class_<FixedArray<IMATH_NAMESPACE::V3d> > v3d_class = register_Vec3Array<double>();\n    add_explicit_construction_from_type<IMATH_NAMESPACE::V3f>(v3i_class);\n    add_explicit_construction_from_type<IMATH_NAMESPACE::V3d>(v3i_class);\n    add_explicit_construction_from_type<IMATH_NAMESPACE::V3i>(v3f_class);\n    add_explicit_construction_from_type<IMATH_NAMESPACE::V3d>(v3f_class);\n    add_explicit_construction_from_type<IMATH_NAMESPACE::V3i>(v3d_class);\n    add_explicit_construction_from_type<IMATH_NAMESPACE::V3f>(v3d_class);\n\n    //\n    //  Vec4\n    //\n    register_Vec4<unsigned char>();\n    register_Vec4<short>();\n    register_Vec4<int>();\n    register_Vec4<float>();\n    register_Vec4<double>();\n    class_<FixedArray<IMATH_NAMESPACE::V4s> > v4s_class = register_Vec4Array<short>();\n    class_<FixedArray<IMATH_NAMESPACE::V4i> > v4i_class = register_Vec4Array<int>();\n    class_<FixedArray<IMATH_NAMESPACE::V4f> > v4f_class = register_Vec4Array<float>();\n    class_<FixedArray<IMATH_NAMESPACE::V4d> > v4d_class = register_Vec4Array<double>();\n    add_explicit_construction_from_type<IMATH_NAMESPACE::V4f>(v4i_class);\n    add_explicit_construction_from_type<IMATH_NAMESPACE::V4d>(v4i_class);\n    add_explicit_construction_from_type<IMATH_NAMESPACE::V4i>(v4f_class);\n    add_explicit_construction_from_type<IMATH_NAMESPACE::V4d>(v4f_class);\n    add_explicit_construction_from_type<IMATH_NAMESPACE::V4i>(v4d_class);\n\n    //\n    //  Quat\n    //\n    register_Quat<float>();\n    register_Quat<double>();\n    class_<FixedArray<IMATH_NAMESPACE::Quatf> > quatf_class = register_QuatArray<float>();\n    class_<FixedArray<IMATH_NAMESPACE::Quatd> > quatd_class = register_QuatArray<double>();\n    add_explicit_construction_from_type<IMATH_NAMESPACE::Quatd>(quatf_class);\n    add_explicit_construction_from_type<IMATH_NAMESPACE::Quatf>(quatd_class);\n\n    //\n    // Euler\n    //\n    register_Euler<float>();\n    register_Euler<double>();\n    class_<FixedArray<IMATH_NAMESPACE::Eulerf> > eulerf_class = register_EulerArray<float>();\n    class_<FixedArray<IMATH_NAMESPACE::Eulerd> > eulerd_class = register_EulerArray<double>();\n    add_explicit_construction_from_type<IMATH_NAMESPACE::Eulerd>(eulerf_class);\n    add_explicit_construction_from_type<IMATH_NAMESPACE::Eulerf>(eulerd_class);\n\n    //\n    // Box2\n    //\n    register_Box2<IMATH_NAMESPACE::V2s>();\n    register_Box2<IMATH_NAMESPACE::V2i>();\n    register_Box2<IMATH_NAMESPACE::V2f>();\n    register_Box2<IMATH_NAMESPACE::V2d>();\n    class_<FixedArray<IMATH_NAMESPACE::Box2s> > b2s_class = register_BoxArray<IMATH_NAMESPACE::V2s>();\n    class_<FixedArray<IMATH_NAMESPACE::Box2i> > b2i_class = register_BoxArray<IMATH_NAMESPACE::V2i>();\n    class_<FixedArray<IMATH_NAMESPACE::Box2f> > b2f_class = register_BoxArray<IMATH_NAMESPACE::V2f>();\n    class_<FixedArray<IMATH_NAMESPACE::Box2d> > b2d_class = register_BoxArray<IMATH_NAMESPACE::V2d>();\n\n    //\n    // Box3\n    //\n    register_Box3<IMATH_NAMESPACE::V3s>();\n    register_Box3<IMATH_NAMESPACE::V3i>();\n    register_Box3<IMATH_NAMESPACE::V3f>();\n    register_Box3<IMATH_NAMESPACE::V3d>();\n    class_<FixedArray<IMATH_NAMESPACE::Box3s> > b3s_class = register_BoxArray<IMATH_NAMESPACE::V3s>();\n    class_<FixedArray<IMATH_NAMESPACE::Box3i> > b3i_class = register_BoxArray<IMATH_NAMESPACE::V3i>();\n    class_<FixedArray<IMATH_NAMESPACE::Box3f> > b3f_class = register_BoxArray<IMATH_NAMESPACE::V3f>();\n    class_<FixedArray<IMATH_NAMESPACE::Box3d> > b3d_class = register_BoxArray<IMATH_NAMESPACE::V3d>();\n\n    //\n    // Matrix22/33/44\n    //\n    register_Matrix22<float>();\n    register_Matrix22<double>();\n    register_Matrix33<float>();\n    register_Matrix33<double>();\n    register_Matrix44<float>();\n    register_Matrix44<double>();\n\n    //\n    // M22/M33/44Array\n    //\n    class_<FixedArray<IMATH_NAMESPACE::M44d> > m44d_class = register_M44Array<double>();\n    class_<FixedArray<IMATH_NAMESPACE::M44f> > m44f_class = register_M44Array<float>();\n    add_explicit_construction_from_type< IMATH_NAMESPACE::Matrix44<double> >(m44d_class);\n    add_explicit_construction_from_type< IMATH_NAMESPACE::Matrix44<float> > (m44f_class);\n\n    class_<FixedArray<IMATH_NAMESPACE::M33d> > m33d_class = register_M33Array<double>();\n    class_<FixedArray<IMATH_NAMESPACE::M33f> > m33f_class = register_M33Array<float>();\n    add_explicit_construction_from_type< IMATH_NAMESPACE::Matrix33<double> >(m33d_class);\n    add_explicit_construction_from_type< IMATH_NAMESPACE::Matrix33<float> > (m33f_class);\n\n    class_<FixedArray<IMATH_NAMESPACE::M22d> > m22d_class = register_M22Array<double>();\n    class_<FixedArray<IMATH_NAMESPACE::M22f> > m22f_class = register_M22Array<float>();\n    add_explicit_construction_from_type< IMATH_NAMESPACE::Matrix22<double> >(m22d_class);\n    add_explicit_construction_from_type< IMATH_NAMESPACE::Matrix22<float> > (m22f_class);\n\n    //\n    // String Array\n    //\n    register_StringArrays();\n\n    //\n    // Color3/4\n    //\n    register_Color3<unsigned char>();\n    register_Color3<float>();\n    register_Color4<unsigned char>();\n    register_Color4<float>();\n\n    //\n    // C3/4Array\n    //\n    class_<FixedArray<IMATH_NAMESPACE::Color3f> > c3f_class = register_Color3Array<float>();\n    class_<FixedArray<IMATH_NAMESPACE::Color3c> > c3c_class = register_Color3Array<unsigned char>();\n    add_explicit_construction_from_type<IMATH_NAMESPACE::V3f>(c3f_class);\n    add_explicit_construction_from_type<IMATH_NAMESPACE::V3d>(c3f_class);\n\n    class_<FixedArray<IMATH_NAMESPACE::Color4f> > c4f_class = register_Color4Array<float>();\n    class_<FixedArray<IMATH_NAMESPACE::Color4c> > c4c_class = register_Color4Array<unsigned char>();\n\n    //\n    // Color4Array\n    //\n    register_Color4Array2D<float>();\n    register_Color4Array2D<unsigned char>();\n\n    //\n    // Frustum\n    //\n    register_Frustum<float>();\n    register_Frustum<double>();\n    register_FrustumTest<float>();\n    register_FrustumTest<double>();\n\n    //\n    // Plane\n    //\n    register_Plane<float>();\n    register_Plane<double>();\n\n    //\n    // Line\n    //\n    register_Line<float>();\n    register_Line<double>();\n\n    //\n    // Shear\n    //\n    register_Shear<float>();\n    register_Shear<double>();\n\n    //\n    // Utility Functions\n    //\n    register_functions();\n   \n\n    def(\"procrustesRotationAndTranslation\", procrustes1, \n        args(\"fromPts\", \"toPts\", \"weights\", \"doScale\"),  // Can't use 'from' and 'to' because 'from' is a reserved keywork in Python\n        \"Computes the orthogonal transform (consisting only of rotation and translation) mapping the \"\n        \"'fromPts' points as close as possible to the 'toPts' points in the least squares norm.  The 'fromPts' and \"\n        \"'toPts' lists must be the same length or the function will error out.  If weights \"\n        \"are provided, then the points are weighted (that is, some points are considered more important \"\n        \"than others while computing the transform).  If the 'doScale' parameter is True, then \"\n        \"the resulting matrix is also allowed to have a uniform scale.\");\n\n    //\n    // Rand\n    //\n    register_Rand32();\n    register_Rand48();\n    \n    //\n    // Initialize constants\n    //\n\n    scope().attr(\"EULER_XYZ\")    = IMATH_NAMESPACE::Eulerf::XYZ;\n    scope().attr(\"EULER_XZY\")    = IMATH_NAMESPACE::Eulerf::XZY;\n    scope().attr(\"EULER_YZX\")    = IMATH_NAMESPACE::Eulerf::YZX;\n    scope().attr(\"EULER_YXZ\")    = IMATH_NAMESPACE::Eulerf::YXZ;\n    scope().attr(\"EULER_ZXY\")    = IMATH_NAMESPACE::Eulerf::ZXY;\n    scope().attr(\"EULER_ZYX\")    = IMATH_NAMESPACE::Eulerf::ZYX;\n    scope().attr(\"EULER_XZX\")    = IMATH_NAMESPACE::Eulerf::XZX;\n    scope().attr(\"EULER_XYX\")    = IMATH_NAMESPACE::Eulerf::XYX;\n    scope().attr(\"EULER_YXY\")    = IMATH_NAMESPACE::Eulerf::YXY;\n    scope().attr(\"EULER_YZY\")    = IMATH_NAMESPACE::Eulerf::YZY;\n    scope().attr(\"EULER_ZYZ\")    = IMATH_NAMESPACE::Eulerf::ZYZ;\n    scope().attr(\"EULER_ZXZ\")    = IMATH_NAMESPACE::Eulerf::ZXZ;\n    scope().attr(\"EULER_XYZr\")   = IMATH_NAMESPACE::Eulerf::XYZr;\n    scope().attr(\"EULER_XZYr\")   = IMATH_NAMESPACE::Eulerf::XZYr;\n    scope().attr(\"EULER_YZXr\")   = IMATH_NAMESPACE::Eulerf::YZXr;\n    scope().attr(\"EULER_YXZr\")   = IMATH_NAMESPACE::Eulerf::YXZr;\n    scope().attr(\"EULER_ZXYr\")   = IMATH_NAMESPACE::Eulerf::ZXYr;\n    scope().attr(\"EULER_ZYXr\")   = IMATH_NAMESPACE::Eulerf::ZYXr;\n    scope().attr(\"EULER_XZXr\")   = IMATH_NAMESPACE::Eulerf::XZXr;\n    scope().attr(\"EULER_XYXr\")   = IMATH_NAMESPACE::Eulerf::XYXr;\n    scope().attr(\"EULER_YXYr\")   = IMATH_NAMESPACE::Eulerf::YXYr;\n    scope().attr(\"EULER_YZYr\")   = IMATH_NAMESPACE::Eulerf::YZYr;\n    scope().attr(\"EULER_ZYZr\")   = IMATH_NAMESPACE::Eulerf::ZYZr;\n    scope().attr(\"EULER_ZXZr\")   = IMATH_NAMESPACE::Eulerf::ZXZr;\n    scope().attr(\"EULER_X_AXIS\") = IMATH_NAMESPACE::Eulerf::X;\n    scope().attr(\"EULER_Y_AXIS\") = IMATH_NAMESPACE::Eulerf::Y;\n    scope().attr(\"EULER_Z_AXIS\") = IMATH_NAMESPACE::Eulerf::Z;\n    \n    scope().attr(\"INT_MIN\")      = IMATH_NAMESPACE::limits<int>::min();\n    scope().attr(\"INT_MAX\")      = IMATH_NAMESPACE::limits<int>::max();\n    scope().attr(\"INT_SMALLEST\") = IMATH_NAMESPACE::limits<int>::smallest();\n    scope().attr(\"INT_EPS\")      = IMATH_NAMESPACE::limits<int>::epsilon();\n\n    scope().attr(\"FLT_MIN\")      = IMATH_NAMESPACE::limits<float>::min();\n    scope().attr(\"FLT_MAX\")      = IMATH_NAMESPACE::limits<float>::max();\n    scope().attr(\"FLT_SMALLEST\") = IMATH_NAMESPACE::limits<float>::smallest();\n    scope().attr(\"FLT_EPS\")      = IMATH_NAMESPACE::limits<float>::epsilon();\n\n    scope().attr(\"DBL_MIN\")      = IMATH_NAMESPACE::limits<double>::min();\n    scope().attr(\"DBL_MAX\")      = IMATH_NAMESPACE::limits<double>::max();\n    scope().attr(\"DBL_SMALLEST\") = IMATH_NAMESPACE::limits<double>::smallest();\n    scope().attr(\"DBL_EPS\")      = IMATH_NAMESPACE::limits<double>::epsilon();\n    \n    //\n    // Register Exceptions\n    //\n    PyIex::registerExc<IMATH_NAMESPACE::NullVecExc,IEX_NAMESPACE::MathExc>(\"NullVecExc\",\"imath\");\n    PyIex::registerExc<IMATH_NAMESPACE::NullQuatExc,IEX_NAMESPACE::MathExc>(\"NullQuatExc\",\"imath\");\n    PyIex::registerExc<IMATH_NAMESPACE::SingMatrixExc,IEX_NAMESPACE::MathExc>(\"SingMatrixExc\",\"imath\");\n    PyIex::registerExc<IMATH_NAMESPACE::ZeroScaleExc,IEX_NAMESPACE::MathExc>(\"ZeroScaleExc\",\"imath\");\n    PyIex::registerExc<IMATH_NAMESPACE::IntVecNormalizeExc,IEX_NAMESPACE::MathExc>(\"IntVecNormalizeExc\",\"imath\");\n\n    def(\"computeBoundingBox\", &computeBoundingBox<float>,\n        \"computeBoundingBox(position) -- computes the bounding box from the position array.\");\n\n    def(\"computeBoundingBox\", &computeBoundingBox<double>,\n        \"computeBoundingBox(position) -- computes the bounding box from the position array.\");\n}\n\n} // namespace PyImath\n", "meta": {"hexsha": "baa3f513707980d1833b1cf625b90cefc70c3f6c", "size": 19615, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PyIlmBase/PyImath/PyImathAll.cpp", "max_stars_repo_name": "marza-animation-planet/openexr", "max_stars_repo_head_hexsha": "f5a7034ec7a1670ea050b1d455680b05507ce841", "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": "PyIlmBase/PyImath/PyImathAll.cpp", "max_issues_repo_name": "marza-animation-planet/openexr", "max_issues_repo_head_hexsha": "f5a7034ec7a1670ea050b1d455680b05507ce841", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PyIlmBase/PyImath/PyImathAll.cpp", "max_forks_repo_name": "marza-animation-planet/openexr", "max_forks_repo_head_hexsha": "f5a7034ec7a1670ea050b1d455680b05507ce841", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-05-14T08:03:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T07:52:44.000Z", "avg_line_length": 40.8645833333, "max_line_length": 132, "alphanum_fraction": 0.7012490441, "num_tokens": 5284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.28476365755531274}}
{"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\n#include <boost/noncopyable.hpp>\n#include <comma/base/exception.h>\n#include <snark/math/gaussian_process/gaussian_process.h>\n\nnamespace snark{ \n\ngaussian_process::gaussian_process( const Eigen::MatrixXd& domains\n                                , const Eigen::VectorXd& targets\n                                , const gaussian_process::covariance& covariance\n                                , double self_covariance )\n    : domains_( domains )\n    , targets_( targets )\n    , covariance_( covariance )\n    , self_covariance_( self_covariance )\n    , offset_( targets.sum() / targets.rows() )\n    , K_( domains.rows(), domains.rows() )\n{\n    if( domains.rows() != targets.rows() ) { COMMA_THROW( comma::exception, \"expected \" << domains.rows() << \" row(s) in targets, got \" << targets.rows() << \" row(s)\" ); }\n    targets_.array() -= offset_; // normalise\n    //use m_K as Kxx + variance*I, then invert it\n    //fill Kxx with values from covariance function\n    //for elements r,c in upper triangle\n    for( std::size_t r = 0; r < std::size_t( domains.rows() ); ++r )\n    {\n        K_( r, r ) = self_covariance_;\n        const Eigen::VectorXd& row = domains.row( r );\n        for( std::size_t c = r + 1; c < std::size_t( domains.rows() ); ++c )\n        {\n            K_( c, r ) = K_( r, c ) = covariance_( row, domains.row( c ) );\n        }\n    }\n    L_.compute( K_ ); // invert Kxx + variance * I to become (by definition) B\n    alpha_ = L_.solve( targets_ );\n}\n\nstd::pair< double, double > gaussian_process::evaluate( const Eigen::MatrixXd& domain ) const\n{\n    if( domain.rows() != 1 ) { COMMA_THROW( comma::exception, \"expected 1 row in domain, got \" << domain.rows() << \" rows\" ); }\n    Eigen::VectorXd means( 1 );\n    Eigen::VectorXd variances( 1 );\n    evaluate( domain, means, variances );\n    return std::make_pair( means( 0 ), variances( 0 ) );\n}\n\nvoid gaussian_process::evaluate( const Eigen::MatrixXd& domains, Eigen::VectorXd& means, Eigen::VectorXd& variances ) const\n{\n    if( domains.cols() != domains_.cols() ) { COMMA_THROW( comma::exception, \"expected \" << domains_.cols() << \" column(s) in domains, got \" << domains.cols() << std::endl ); }\n    Eigen::MatrixXd Kxsx = Eigen::MatrixXd::Zero( domains.rows(), domains_.rows() );\n    for( std::size_t r = 0; r < std::size_t( domains.rows() ); ++r )\n    {\n        const Eigen::VectorXd& row = domains.row( r );\n        for( std::size_t c = 0; c < std::size_t( domains_.rows() ); ++c )\n        {\n            Kxsx( r, c ) = covariance_( row, domains_.row( c ) );\n        }\n    }\n    means = Kxsx * alpha_;\n    means.array() += offset_;\n    Eigen::MatrixXd Kxxs = Kxsx.transpose();\n    L_.matrixL().solveInPlace( Kxxs );\n    Eigen::MatrixXd& variance = Kxxs;\n    variance = variance.array() * variance.array();\n    variances = variance.colwise().sum();\n    // for each diagonal variance, set v(r) = -v(r,r) + Kxsxs\n    for( std::size_t r = 0; r < std::size_t( domains.rows() ); ++r )\n    {\n        variances( r ) = -variances( r ) + self_covariance_;\n    }\n}\n\n}  // namespace snark{ \n", "meta": {"hexsha": "6f5f98649ff991186fc06e48a9571ece64d09c07", "size": 4810, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math/gaussian_process/gaussian_process.cpp", "max_stars_repo_name": "jackiecx/snark", "max_stars_repo_head_hexsha": "492c1b6f26b9e3e8ea6fc66ad1a8c7f997f90ec6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-14T15:21:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-14T15:21:24.000Z", "max_issues_repo_path": "math/gaussian_process/gaussian_process.cpp", "max_issues_repo_name": "jackiecx/snark", "max_issues_repo_head_hexsha": "492c1b6f26b9e3e8ea6fc66ad1a8c7f997f90ec6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math/gaussian_process/gaussian_process.cpp", "max_forks_repo_name": "jackiecx/snark", "max_forks_repo_head_hexsha": "492c1b6f26b9e3e8ea6fc66ad1a8c7f997f90ec6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.1568627451, "max_line_length": 176, "alphanum_fraction": 0.6561330561, "num_tokens": 1194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.2846499133109315}}
{"text": "#include <pybind11/pybind11.h>\n\n#include <boost/lexical_cast.hpp>\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Constrained_Delaunay_triangulation_2.h>\n#include <CGAL/Delaunay_mesh_face_base_2.h>\n#include <CGAL/Delaunay_mesh_vertex_base_2.h>\n#include <CGAL/Delaunay_mesher_2.h>\n#include <CGAL/Delaunay_mesh_size_criteria_2.h>\n#include <CGAL/Triangulation_conformer_2.h>\n#include <CGAL/lloyd_optimize_mesh_2.h>\n\n\n\n\n#include <type_traits>\n#include <typeinfo>\n#ifndef _MSC_VER\n#   include <cxxabi.h>\n#endif\n#include <memory>\n#include <string>\n#include <cstdlib>\n\n#include <functional>\n\ntemplate <typename...> struct hash;\n\ntemplate<typename T>\nstruct hash<T>\n        : public std::hash<T>\n{\n    using std::hash<T>::hash;\n};\n\n\ntemplate <typename T, typename... Rest>\nstruct hash<T, Rest...>\n{\n    inline std::size_t operator()(const T& v, const Rest&... rest) {\n        std::size_t seed = hash<Rest...>{}(rest...);\n        seed ^= hash<T>{}(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n        return seed;\n    }\n};\n\ntemplate <class T>\nstd::string\ntype_name()\n{\n    typedef typename std::remove_reference<T>::type TR;\n    std::unique_ptr<char, void(*)(void*)> own\n            (\n            nullptr,\n            std::free\n    );\n    std::string r = own != nullptr ? own.get() : typeid(TR).name();\n    if (std::is_const<TR>::value)\n        r += \" const\";\n    if (std::is_volatile<TR>::value)\n        r += \" volatile\";\n    if (std::is_lvalue_reference<T>::value)\n        r += \"&\";\n    else if (std::is_rvalue_reference<T>::value)\n        r += \"&&\";\n    return r;\n}\n\nnamespace py = pybind11;\n\nusing K = CGAL::Exact_predicates_inexact_constructions_kernel;\nusing Vb = CGAL::Delaunay_mesh_vertex_base_2<K>;\nusing Fb = CGAL::Delaunay_mesh_face_base_2<K>;\nusing Tds = CGAL::Triangulation_data_structure_2<Vb, Fb>;\nusing CDT = CGAL::Constrained_Delaunay_triangulation_2<K, Tds>;\nusing Point = CDT::Point;\nusing Vertex_handle = CDT::Vertex_handle;\nusing Criteria = CGAL::Delaunay_mesh_size_criteria_2<CDT>;\nusing Mesher = CGAL::Delaunay_mesher_2<CDT, Criteria>;\n\ntemplate <typename T>\nclass TypedInputIterator\n{\npublic:\n    using iterator_category = std::input_iterator_tag;\n    using difference_type = std::ptrdiff_t;\n    using value_type = T;\n    using pointer = T*;\n    using reference = T&;\n\n    explicit TypedInputIterator(py::iterator& py_iter) :\n            py_iter_(py_iter)\n    {\n    }\n\n    explicit TypedInputIterator(py::iterator&& py_iter) :\n            py_iter_(py_iter)\n    {\n    }\n\n    value_type operator*()\n    {\n        return (*py_iter_).template cast<value_type>();\n    }\n\n    TypedInputIterator operator++(int)\n    {\n        auto copy = *this;\n        ++py_iter_;\n        return copy;\n    }\n\n    TypedInputIterator& operator++()\n    {\n        ++py_iter_;\n        return *this;\n    }\n\n    bool operator!=(TypedInputIterator &rhs)\n    {\n        return py_iter_ != rhs.py_iter_;\n    }\n\n    bool operator==(TypedInputIterator &rhs)\n    {\n        return py_iter_ == rhs.py_iter_;\n    }\n\nprivate:\n    py::iterator py_iter_;\n};\n\nPYBIND11_MODULE(daidalus, m)\n{\n\n    py::class_<Point>(m, \"Point\")\n        .def(py::init<int, int>(),  py::arg(\"x\"), py::arg(\"y\"))\n        .def(py::init<double, double>(), py::arg(\"x\"), py::arg(\"y\"))\n        .def_property_readonly(\"x\", &Point::x)\n        .def_property_readonly(\"y\", &Point::y)\n        .def(\"__repr__\",\n             [](const Point &p) {\n                 std::string r(\"Point(\");\n                 r += boost::lexical_cast<std::string>(p.x());\n                 r += \", \";\n                 r += boost::lexical_cast<std::string>(p.y());\n                 r += \")\";\n                 return r;\n             })\n        .def(\"__hash__\",\n             [](const Point &p) {\n                 std::hash<double> double_hash;\n                 auto x_hash = double_hash(p.x());\n                 auto y_hash = double_hash(p.y());\n                 return y_hash ^ x_hash + 0x9e3779b9 + (y_hash << 6) + (y_hash >> 2);\n             }\n        )\n        .def(\"__eq__\",\n            [](const Point &p, const Point & q) {\n                return p == q;\n            }\n        )\n        ;\n\n    py::class_<Vertex_handle>(m, \"VertexHandle\")\n        .def_property_readonly(\n            \"point\",\n            [](const Vertex_handle& vertex_handle)\n            {\n                return vertex_handle->point();\n            })\n            ;\n\n    py::class_<CDT::Finite_vertices_iterator::value_type>(m, \"Vertex\")\n            .def_property_readonly(\n                \"point\", [](CDT::Finite_vertices_iterator::value_type& vertex)\n                {\n                    return vertex.point();\n                }\n            )\n            ;\n\n    py::class_<CDT::Finite_faces_iterator::value_type>(m, \"Face\")\n            .def(\"vertex_handle\",\n                [](CDT::Finite_faces_iterator::value_type& face, int index)\n                {\n                    return face.vertex(index);\n                },\n                py::arg(\"index\")\n            )\n            ;\n\n    m.def(\"print_faces_iterator_value_type\", [](){\n        std::cout << type_name<CDT::Finite_faces_iterator::value_type>();\n    });\n\n    py::class_<CDT>(m, \"ConstrainedDelaunayTriangulation\")\n        .def(py::init())\n        .def(\"insert\", [](CDT & cdt, const Point & p) { return cdt.insert(p); })\n        .def(\"insert_constraint\",\n             [](CDT & cdt, Vertex_handle a, Vertex_handle b)\n             {\n                 cdt.insert_constraint(a, b);\n             })\n        .def(\"number_of_vertices\", &CDT::number_of_vertices)\n        .def(\"number_of_faces\", &CDT::number_of_faces)\n        .def(\"finite_vertices\", [](CDT & cdt) -> py::iterator\n        {\n            return py::make_iterator(cdt.finite_vertices_begin(), cdt.finite_vertices_end());\n        })\n        .def(\"finite_faces\", [](CDT & cdt) -> py::iterator\n        {\n            return py::make_iterator(cdt.finite_faces_begin(), cdt.finite_faces_end());\n        })\n        ;\n\n    py::class_<Criteria>(m, \"Criteria\")\n            .def(py::init<double, double>(),\n                 py::arg(\"aspect_bound\") = 0.125,\n                 py::arg(\"size_bound\") = 0.0)\n            .def_property(\"size_bound\", &Criteria::size_bound, &Criteria::set_size_bound)\n            .def_property(\"aspect_bound\",\n                          [](const Criteria & c) { c.bound(); },\n                          [](Criteria & c, double bound) { c.set_bound(bound); })\n            ;\n\n    py::class_<Mesher>(m, \"Mesher\")\n        .def(py::init<CDT&>())\n        .def(\"seeds_from\", [](Mesher & mesher, py::iterable iterable)\n        {\n            py::iterator iterator = py::iter(iterable);\n            TypedInputIterator<Point> points_begin(iterator);\n            TypedInputIterator<Point> points_end(py::iterator::sentinel());\n            mesher.set_seeds(points_begin, points_end);\n        })\n        .def(\"refine_mesh\", &Mesher::refine_mesh)\n        .def_property(\n                \"criteria\",\n                &Mesher::get_criteria,\n                [](Mesher& mesher, const Criteria & criteria)\n                {\n                    mesher.set_criteria(criteria);\n                }\n        )\n        ;\n\n    m.def(\"make_conforming_delaunay\",\n          &CGAL::make_conforming_Delaunay_2<CDT>,\n          py::arg(\"cdt\")\n    );\n\n    m.def(\"make_conforming_gabriel\",\n          &CGAL::make_conforming_Gabriel_2<CDT>,\n          py::arg(\"cdt\")\n    );\n\n    m.def(\"lloyd_optimize\", [](\n                  CDT& cdt,\n                  int max_iteration_number,\n                  double time_limit,\n                  double convergence,\n                  double freeze_bound)\n          {\n              CGAL::lloyd_optimize_mesh_2(cdt,\n                                          CGAL::parameters::max_iteration_number = max_iteration_number,\n                                          CGAL::parameters::time_limit = time_limit,\n                                          CGAL::parameters::convergence = convergence,\n                                          CGAL::parameters::freeze_bound = freeze_bound\n              );\n          },\n          py::arg(\"cdt\"),\n          py::arg(\"max_iteration_number\") = 0,\n          py::arg(\"time_limit\") = 0.0,\n          py::arg(\"convergence\") = 0.001,\n          py::arg(\"freeze_bound\") = 0.001\n    );\n\n}\n", "meta": {"hexsha": "6ab2cb28ccdee77bd7d4b3929f9277f5126b3102", "size": 8254, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CoreSystem/src/wrapper/daidalus.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/src/wrapper/daidalus.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/src/wrapper/daidalus.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": 29.4785714286, "max_line_length": 104, "alphanum_fraction": 0.5392536952, "num_tokens": 2061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.63341024983754, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2846499008714737}}
{"text": "#include <Eigen/Eigen>\n#include <ndt_registration/ndt_matcher_d2d_feature.h>\n#include <boost/bind.hpp>\n#include <sys/time.h>\n\nnamespace perception_oru\n{\n\nbool\nNDTMatcherFeatureD2D::covariance( NDTMap& targetNDT,\n        NDTMap& sourceNDT,\n        Eigen::Transform<double,3,Eigen::Affine,Eigen::ColMajor>& T,\n        Eigen::Matrix<double,6,6> &cov)\n{\n    assert(false);\n};\n\n//DEPRECATED???\ndouble\nNDTMatcherFeatureD2D::scoreNDT(std::vector<NDTCell*> &sourceNDT, NDTMap &targetNDT,\n        Eigen::Transform<double,3,Eigen::Affine,Eigen::ColMajor>& T)\n{\n    NUMBER_OF_ACTIVE_CELLS = 0;\n    double score_here = 0;\n    double det = 0;\n    bool exists = false;\n    NDTCell *cell;\n    Eigen::Matrix3d covCombined, icov;\n    Eigen::Vector3d meanFixed;\n    Eigen::Vector3d meanMoving;\n    Eigen::Matrix3d R = T.rotation();\n    std::vector<std::pair<unsigned int, double> > scores;\n    for(unsigned int j=0; j<_corr.size(); j++)\n    {\n        unsigned int i = _corr[j].second;\n        if (_corr[j].second >= (int)sourceNDT.size())\n        {\n            std::cout << \"second correspondance : \" << _corr[j].second << \", \" << sourceNDT.size() << std::endl;\n        }\n        if (sourceNDT[i] == NULL)\n        {\n            std::cout << \"sourceNDT[i] == NULL!\" << std::endl;\n        }\n        meanMoving = T*sourceNDT[i]->getMean();\n\n        cell = targetNDT.getCellIdx(_corr[j].first);\n        {\n\n            if(cell == NULL)\n            {\n                std::cout << \"cell== NULL!!!\" << std::endl;\n            }\n            else\n            {\n                if(cell->hasGaussian_)\n                {\n                    meanFixed = cell->getMean();\n                    covCombined = cell->getCov() + R.transpose()*sourceNDT[i]->getCov()*R;\n                    covCombined.computeInverseAndDetWithCheck(icov,det,exists);\n                    if(!exists) continue;\n                    double l = (meanMoving-meanFixed).dot(icov*(meanMoving-meanFixed));\n                    if(l*0 != 0) continue;\n                    if(l > 120) continue;\n\n                    double sh = -lfd1*(exp(-lfd2*l/2));\n\n                    if(fabsf(sh) > 1e-10)\n                    {\n                        NUMBER_OF_ACTIVE_CELLS++;\n                    }\n                    scores.push_back(std::pair<unsigned int, double>(j, sh));\n                    score_here += sh;\n                    //score_here += l;\n                }\n            }\n        }\n    }\n\n    if (_trimFactor == 1.)\n    {\n        return score_here;\n    }\n    else\n    {\n        // Determine the score value\n        if (scores.empty()) // TODO, this happens(!), why??!??\n            return score_here;\n\n        score_here = 0.;\n        unsigned int index = static_cast<unsigned int>(_trimFactor * (scores.size() - 1));\n        //\tstd::nth_element (scores.begin(), scores.begin()+index, scores.end(), sort_scores()); //boost::bind(&std::pair<unsigned int, double>::second, _1) < boost::bind(&std::pair<unsigned int, double>::second, _2));\n        std::nth_element (scores.begin(), scores.begin()+index, scores.end(), boost::bind(&std::pair<unsigned int, double>::second, _1) < boost::bind(&std::pair<unsigned int, double>::second, _2));\n        std::fill(_goodCorr.begin(), _goodCorr.end(), false);\n        //\tstd::cout << \"_goodCorr.size() : \" << _goodCorr.size() << \" scores.size() : \" << scores.size() << \" index : \" << index << std::endl;\n        for (unsigned int i = 0; i < _goodCorr.size(); i++)\n        {\n            if (i <= index)\n            {\n                score_here += scores[i].second;\n                _goodCorr[scores[i].first] = true;\n            }\n        }\n        return score_here;\n    }\n}\n\ndouble\nNDTMatcherFeatureD2D::derivativesNDT( \n    const std::vector<NDTCell*> &sourceNDT,\n    const NDTMap &targetNDT,\n    Eigen::MatrixXd &score_gradient,\n    Eigen::MatrixXd &Hessian,\n    bool computeHessian\n)\n{\n\n    struct timeval tv_start, tv_end;\n    double score_here = 0;\n\n    gettimeofday(&tv_start,NULL);\n    NUMBER_OF_ACTIVE_CELLS = 0;\n    score_gradient.setZero();\n    Hessian.setZero();\n\n    pcl::PointXYZ point;\n    Eigen::Vector3d transformed;\n    Eigen::Vector3d meanMoving, meanFixed;\n    Eigen::Matrix3d CMoving, CFixed, CSum, Cinv, R;\n    NDTCell *cell;\n    bool exists = false;\n    double det = 0;\n    for (unsigned int j = 0; j < _corr.size(); j++)\n    {\n        if (!_goodCorr[j])\n            continue;\n\n        unsigned int i = _corr[j].second;\n        if (i >= sourceNDT.size())\n        {\n            std::cout << \"sourceNDT.size() : \" << sourceNDT.size() << \", i: \" << i << std::endl;\n        }\n        assert(i < sourceNDT.size());\n        \n\tmeanMoving = sourceNDT[i]->getMean();\n        CMoving= sourceNDT[i]->getCov();\n        \n\tthis->computeDerivatives(meanMoving, CMoving, computeHessian);\n\n        point.x = meanMoving(0);\n        point.y = meanMoving(1);\n        point.z = meanMoving(2);\n       \n        cell = targetNDT.getCellIdx(_corr[j].first);\n\tif(cell == NULL)\n\t{\n\t    continue;\n\t}\n\tif(cell->hasGaussian_)\n\t{\n\t    transformed = meanMoving - cell->getMean();\n\t    CFixed = cell->getCov();\n\t    CSum = (CFixed+CMoving);\n\t    CSum.computeInverseAndDetWithCheck(Cinv,det,exists);\n\t    if(!exists)\n\t    {\n\t\t//delete cell;\n\t\tcontinue;\n\t    }\n\t    double l = (transformed).dot(Cinv*(transformed));\n\t    if(l*0 != 0)\n\t    {\n\t\t//delete cell;\n\t\tcontinue;\n\t    }\n\t    double sh = -lfd1*(exp(-lfd2*l/2));\n\t    //std::cout<<\"m1 = [\"<<meanMoving.transpose()<<\"]';\\n m2 = [\"<<cell->getMean().transpose()<<\"]';\\n\";\n\t    //std::cout<<\"C1 = [\"<<CMoving<<\"];\\n C2 = [\"<<CFixed<<\"];\\n\";\n\t    //update score gradient\n\t    if(!this->update_gradient_hessian(score_gradient,Hessian,transformed, Cinv, sh, computeHessian))\n\t    {\n\t\tcontinue;\n\t    }\n\t    score_here += sh;\n\t    cell = NULL;\n\t}\n    }\n    gettimeofday(&tv_end,NULL);\n\n    //double time_load = (tv_end.tv_sec-tv_start.tv_sec)*1000.+(tv_end.tv_usec-tv_start.tv_usec)/1000.;\n    //std::cout<<\"time derivatives took is: \"<<time_load<<std::endl;\n    return score_here;\n\n}\n\n}\n", "meta": {"hexsha": "785b4aa6ae8922229f52c51d1d8ad8f8e11b0854", "size": 5991, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "perception_oru-port-kinetic/ndt_registration/src/ndt_matcher_d2d_feature.cpp", "max_stars_repo_name": "lllray/ndt-loam", "max_stars_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-14T08:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-14T08:21:13.000Z", "max_issues_repo_path": "perception_oru-port-kinetic/ndt_registration/src/ndt_matcher_d2d_feature.cpp", "max_issues_repo_name": "lllray/ndt-loam", "max_issues_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-28T04:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T04:47:56.000Z", "max_forks_repo_path": "perception_oru-port-kinetic/ndt_registration/src/ndt_matcher_d2d_feature.cpp", "max_forks_repo_name": "lllray/ndt-loam", "max_forks_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-18T11:25:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T12:59:59.000Z", "avg_line_length": 30.5663265306, "max_line_length": 218, "alphanum_fraction": 0.5476548156, "num_tokens": 1624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185944046238982, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2846123681341741}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2010 Sebastian Schlenkrich\n*/\n\n/*! \\file bondoptionengine.cpp\n    \\brief engine for bond options with Hull White model\n*/\n\n\n#include <time.h>\n#include <boost/lexical_cast.hpp>\n\n#include <ql/settings.hpp>\n#include <ql/experimental/templatemodels/hullwhite/fixedratebondoption.hpp>\n#include <ql/experimental/templatemodels/hullwhite/bondoptionengine.hpp>\n#include <ql/cashflows/coupon.hpp>\n#include <ql/cashflows/fixedratecoupon.hpp>\n#include <ql/cashflows/simplecashflow.hpp>\n\nnamespace QuantLib {\n\n    // calibrate model based on given swaptions\n    void BondOptionEngine::calibrateModel( std::vector< ext::shared_ptr<Swaption> >          swaptions,\n                                           const bool                                        contTenorSpread,\n                                           const Real                                        tolVola) {\n        std::sort(swaptions.begin(), swaptions.end(), lessByExerciseFirstDate);\n        // set up inputs for model calibration\n        std::vector<Real>                  exercTimes, strikeVals, b76Prices;\n        std::vector< std::vector<Real> >   startTimes, payTimes, cashFlows;\n        std::vector<Option::Type>          callOrPut;\n        // get discount curve and conventions from model\n        Handle<YieldTermStructure> discCurve = model_->termStructure();\n        DayCounter                 dc        = model_->termStructure()->dayCounter();\n        Date                       today     = model_->termStructure()->referenceDate();\n        // iterate swaptions...\n        referenceSwaptions_.clear();\n        for (Size k=0; k<swaptions.size(); ++k) {\n            // skip swaptions with equal exercise date since we calibrate by bootstrapping\n            if ( (k>0) && (swaptions[k]->exercise()->date(0)==swaptions[k-1]->exercise()->date(0)) ) continue;\n            // save reference swaption\n            referenceSwaptions_.push_back(swaptions[k]);\n            // build an equivalent bond option\n            FixedRateBondOption bondOption(swaptions[k], discCurve, contTenorSpread);\n            // extract option details\n            exercTimes.push_back(dc.yearFraction(today,bondOption.exerciseDates()[0]));\n            strikeVals.push_back(bondOption.dirtyStrikeValues()[0]);\n            b76Prices.push_back(swaptions[k]->NPV());  // assume we have an engine and market data attached\n            callOrPut.push_back(bondOption.callOrPut());\n            // extract underlying details\n            std::vector<Real> bondStartTimes, bondPayTimes;\n            for (Size i=0; i<bondOption.cashflowValues().size(); ++i) {\n                bondStartTimes.push_back( dc.yearFraction(today,bondOption.startDates()[i]) );\n                bondPayTimes.push_back( dc.yearFraction(today,bondOption.payDates()[i]) );\n            }\n            startTimes.push_back(bondStartTimes);\n            payTimes.push_back(bondPayTimes);\n            cashFlows.push_back(bondOption.cashflowValues());\n        }\n        // calibrate Hull White model\n        model_->BermudanCalibration(exercTimes, strikeVals, b76Prices, startTimes, payTimes, cashFlows, callOrPut, tolVola);\n    }\n\n    void BondOptionEngine::calculate() const {\n        std::vector<Time> startTimes;\n        std::vector<Time> payTimes;\n        std::vector<Real> cashFlowValues;\n        std::vector<Time> exerciseTimes;\n        std::vector<Real> strikeValues;\n        DayCounter dayCounter = model_->termStructure()->dayCounter();\n        Date today = model_->termStructure()->referenceDate();\n        Date startDate;\n        ext::shared_ptr<Coupon> coupon;\n        // set up cash flows\n        for (Size i=0; i<arguments_.cashflows.size(); ++i) {\n            coupon = ext::dynamic_pointer_cast<Coupon>(arguments_.cashflows[i]);\n            if (coupon) { // cast is ok\n                startDate = coupon->accrualStartDate();\n            }\n            else { // cash flow is no coupon, assume redemption payment, startDate = payDate\n                startDate = arguments_.cashflows[i]->date();\n            }\n            if (startDate>today) { // consider only coupons with startDate later than today\n                startTimes.push_back(dayCounter.yearFraction(today,startDate));\n                payTimes.push_back(dayCounter.yearFraction(today,arguments_.cashflows[i]->date()));\n                cashFlowValues.push_back(arguments_.cashflows[i]->amount());\n            }\n        }\n        // set up exercises\n        Size Nexc = std::min(arguments_.exerciseDates.size(), arguments_.dirtyStrikeValues.size());\n        for (Size i=0; i<Nexc; ++i) {\n            if (arguments_.exerciseDates[i]>today) { // consider only exercises later than today\n                exerciseTimes.push_back(dayCounter.yearFraction(today,arguments_.exerciseDates[i]));\n                strikeValues.push_back(arguments_.dirtyStrikeValues[i]);\n            }\n        }\n        // do not calibrate in pricing engine unless there is a calibrator\n\n        // evaluate Bermudan bond option\n        clock_t start_clock = clock();\n        results_.value = model_->BermudanBondOption(exerciseTimes,strikeValues,\n            startTimes,payTimes,cashFlowValues,arguments_.callOrPut,dimension_,gridRadius_,bermudanTolerance_);\n        clock_t end_clock = clock();\n        // report additional results here ...\n        results_.additionalResults[\"runtime\"] = (Real)(end_clock - start_clock)/CLOCKS_PER_SEC;\n        std::vector<Real> europeansAnalytical = model_->europeansAnalytical();\n        std::vector<Real> europeansNumerical  = model_->europeansNumerical();\n        // (absolute) error is estimated by corresponding European prices\n        Real errorEstimate = 0.0;\n        for (Size i=0; i<std::min(europeansAnalytical.size(),europeansNumerical.size()); ++i) {\n            errorEstimate = std::max(errorEstimate,fabs(europeansNumerical[i]-europeansAnalytical[i]));\n        }\n        results_.errorEstimate = errorEstimate;\n        // report adittional results for\n        for (Size i=0; i<referenceSwaptions_.size(); ++i) {\n            std::string name = \"black76price_\";\n            name += boost::lexical_cast<std::string>( i+1 );\n            results_.additionalResults[name] = referenceSwaptions_[i]->NPV();\n        }\n        for (Size i=0; i<referenceSwaptions_.size(); ++i) {\n            std::string name = \"black76vola_\";\n            name += boost::lexical_cast<std::string>( i+1 );\n            std::map<std::string,boost::any>::const_iterator stDev = referenceSwaptions_[i]->additionalResults().find(\"stdDev\");\n            if (stDev!=referenceSwaptions_[i]->additionalResults().end()) {\n                results_.additionalResults[name] = \n                    boost::any_cast<Real>(stDev->second) / std::sqrt(model_->termStructure()->dayCounter().yearFraction(today,referenceSwaptions_[i]->exercise()->dates()[0]));\n            }\n        }\n        for (Size i=0; i<referenceSwaptions_.size(); ++i) {\n            std::string name = \"black76vega_\";\n            name += boost::lexical_cast<std::string>( i+1 );\n            std::map<std::string,boost::any>::const_iterator vega = referenceSwaptions_[i]->additionalResults().find(\"vega\");\n            if (vega!=referenceSwaptions_[i]->additionalResults().end()) {\n                results_.additionalResults[name] = \tboost::any_cast<Real>(vega->second);\n            }\n        }\n        // if we have an AD-enabeled model report vega(s) here...\n        ext::shared_ptr<MinimADHullWhiteModel> amodel = ext::dynamic_pointer_cast<MinimADHullWhiteModel>(model_);\n        if (amodel) {\n            // derivative of Bermudan price w.r.t. short rate vola\n            std::vector<QuantLib::Real> vegas = amodel->bermudanVega();\n            // differentiate calibration; short rate vola w.r.t. B76 prices\n            for (Size j=vegas.size(); j>0; --j) {\n                for (Size i=j; i<vegas.size(); ++i) vegas[j-1] -= vegas[i]*amodel->calibrationJacobian()[i][j-1];\n                vegas[j-1] /= amodel->calibrationJacobian()[j-1][j-1];\n            }\n            // finally differentiate reference prices w.r.t. Black'76 volas\n            for (Size i=0; i<std::min(vegas.size(),referenceSwaptions_.size()); ++i) {\n                std::map<std::string,boost::any>::const_iterator vega = referenceSwaptions_[i]->additionalResults().find(\"vega\");\n                if (vega!=referenceSwaptions_[i]->additionalResults().end()) {\n                    vegas[i] *= boost::any_cast<Real>(vega->second);\n                }\n            }\n            // the sum of vegas represents the sensitivity w.r.t. to a parallel shift of the B76 vola surface\n            QuantLib::Real vega=0.0;\n            for (Size i=0; i<vegas.size(); ++i) vega += vegas[i];\n            // store Bermudan and reference European vega\n            results_.additionalResults[\"vega\"] = vega;\n            results_.additionalResults[\"vegas_size\"] = (1.0*vegas.size());\n            for (Size i=0; i<vegas.size(); ++i) {\n                std::string name = \"vegas_\";\n                name += boost::lexical_cast<std::string>( i+1 );\n                results_.additionalResults[name] = vegas[i]; \n            }\n        }\n    }\n\n}\n\n", "meta": {"hexsha": "c0141c716635b901d2f9e56b472b1f832a325948", "size": 9200, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/templatemodels/hullwhite/bondoptionengine.cpp", "max_stars_repo_name": "sschlenkrich/quantlib", "max_stars_repo_head_hexsha": "ff39ad2cd03d06d185044976b2e26ce34dca470c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ql/experimental/templatemodels/hullwhite/bondoptionengine.cpp", "max_issues_repo_name": "sschlenkrich/quantlib", "max_issues_repo_head_hexsha": "ff39ad2cd03d06d185044976b2e26ce34dca470c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ql/experimental/templatemodels/hullwhite/bondoptionengine.cpp", "max_forks_repo_name": "sschlenkrich/quantlib", "max_forks_repo_head_hexsha": "ff39ad2cd03d06d185044976b2e26ce34dca470c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.8011695906, "max_line_length": 175, "alphanum_fraction": 0.607826087, "num_tokens": 2180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2845996318304377}}
{"text": "#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <iomanip>\n#include <string>\n#include <algorithm>\n#include <iterator>\n#include <numeric>\n#include <ext/numeric>\n#include <boost/program_options.hpp>\n#include <boost/filesystem.hpp>\n\n#include <stdlib.h>\n#include <math.h>\n#include <assert.h>\n\n#include \"mpi_kmeans.h\"\n\nnamespace po = boost::program_options;\n\nstatic void write_assignment(const std::string& output_filename,\n\t\t\t\t\t\t\t\t  const std::vector<int> labels) {\n\t\n\tstd::cout << \"Writing cluster centers to \\\"\"\n\t\t\t  << output_filename << \"\\\"\" << std::endl;\n\n\tstd::ofstream wout(output_filename.c_str());\n\tif (wout.fail()) {\n\t\tstd::cerr << \"Failed to open \\\"\" << output_filename\n\t\t\t\t  << \"\\\" for writing.\" << std::endl;\n\t\tstd::cerr << \"Try mpi_assign --help\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\twout << std::setprecision(1);\n\tfor (unsigned int m=0; m < labels.size(); ++m) {\n\t\twout << labels[m] << std::endl;\n\t}\n\twout.close();\n\n\treturn;\n}\n\n\nstatic int read_problem_data(const std::string& filename,\n\t\t\t\t\t\t\t  std::vector<std::vector<double> >& data) {\n\tdata.clear();\n\n\tstd::ifstream in(filename.c_str());\n\tif (in.fail()) {\n\t\tstd::cerr << \"Failed to open file \\\"\"\n\t\t\t\t  << filename << \"\\\" for reading.\" << std::endl;\n\t\tstd::cerr << \"Try mpi_assign --help\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tstd::string line;\n\tunsigned int ndims = 0;\n\twhile (in.eof() == false) {\n\t\tstd::getline(in,line);\n\t\tif (line.size() == 0)\n\t\t\tcontinue; // skip over empty lines\n\t\n\t\t// remove trailing whitespaces\n\t\tline.erase(line.find_last_not_of(\" \")+1);\n\n\t\tstd::vector<double> current_data;\t\n\t\tstd::istringstream is(line);\n\t\twhile (is.eof() == false) {\n\t\t\tdouble value;\n\t\t\tis >> value;\n\t\t\tcurrent_data.push_back(value);\n\t\t}\n\t\t\n\t\t// Ensure the same number of dimensions for each point\n\t\tif (ndims == 0)\n\t\t\tndims = current_data.size();\t\n\t\tassert(ndims == current_data.size());\n\t\tdata.push_back(current_data);\n\t}\n\tin.close();\n\t\n\tif (data.size() == 0) {\n\t\tstd::cerr << \"No points read from file \\\"\" << filename\n\t\t\t\t  << \"\\\"\" << std::endl;\n\t\tstd::cerr << \"Try mpi_assign --help\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\treturn(data.size());\n\n}\n\n\nint main(int argc, char* argv[]) {\n\n\tstd::string data_filename;\n\tstd::string cluster_filename;\n\tstd::string assignment_filename;\n\n\t// Set Program options\n\tpo::options_description generic(\"Generic Options\");\n\tgeneric.add_options()\n\t\t(\"help\",\"Produce help message\")\n\t\t(\"verbose\",\"Verbose output\")\n\t\t;\n\n\tpo::options_description input_options(\"Input/Output Options\");\n\tinput_options.add_options()\n\t\t(\"data\",po::value<std::string>\n\t\t (&data_filename)->default_value(\"data.txt\"),\n\t\t \"Data file, one datum per line\")\n\t\t(\"cluster\",po::value<std::string>\n\t\t (&cluster_filename)->default_value(\"clustercenter.txt\"),\n\t\t \"Output file, one cluster center per line\")\n\t\t(\"assignment\",po::value<std::string>\n\t\t (&assignment_filename)->default_value(\"assignment.txt\"),\n\t\t \"Output file, one cluster center per line\")\n\t\t;\n\n\tpo::options_description all_options;\n\tall_options.add(generic).add(input_options);\n\tpo::variables_map vm;\n\tpo::store(po::command_line_parser(argc,argv).options(all_options).run(), vm);\n\tpo::notify(vm);\n\n\tbool verbose = vm.count(\"verbose\");\n\n\tif (vm.count(\"help\")) {\n\t\tstd::cerr << \"Assigning points to cluster center\" << std::endl;\n\t\tstd::cerr << all_options << std::endl;\n\t\tstd::cerr << std::endl;\n\t\tstd::cerr << \"Example:\" << std::endl;\n\t\tstd::cerr << \"  mpi_assign --data example.txt --cluster clusters.txt --assignment assignment.txt\" << std::endl;\n\t\texit(EXIT_SUCCESS);\n\t}\n\n\t// read in the data\n\tstd::cout << \"Input file: \" << data_filename << std::endl;\n\tstd::vector<std::vector<double> > data_X;\t\n\tint nof_points = read_problem_data(data_filename,data_X);\n\tassert(nof_points>0);\n\n\n\t// read in the clusters\n\tstd::cout << \"Clustercenter file: \" << cluster_filename << std::endl;\n\tstd::vector<std::vector<double> > data_CX;\t\n\tint nof_clusters = read_problem_data(cluster_filename,data_CX);\n\tassert(nof_clusters>0);\n\n\tunsigned int dims = data_X[0].size();\n\tassert(dims>0);\n\tif (data_X[0].size() != data_CX[0].size()) {\n\t\tstd::cerr << \"Dimension mismatch between points and clusters\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\t// convert clusters to double*\n\tdouble *CX = (double *)malloc(nof_clusters * dims * sizeof(double));\n\tunsigned int cntr = 0;\n\tfor (unsigned int m=0; m < data_CX.size() ; ++m) {\n\t\tfor (unsigned int n=0; n < data_CX[m].size() ; ++n) {\n\t\t\tCX[cntr] = data_CX[m][n];\n\t\t\tcntr += 1;\n\t\t}\n\t}\n\t\n\t// start K-Means\n\tstd::cout << \"Starting Assignment ...\" << std::endl;\n\tstd::cout << \" ... with \" << nof_points << \" training points \" <<std::endl;\n\tstd::cout << \" ... for \" << nof_clusters << \" clusters \" <<std::endl;\n\tstd::cout << \" ... in \" << dims << \" dimensions \" <<std::endl;\n\n\tstd::vector<int> labels;\n\tdouble *x = (double *)malloc(dims * sizeof(double));\n\tfor (unsigned int i=0; i < nof_points ; i++ ) {\n\t\tfor (unsigned int n=0; n<data_X[i].size() ; ++n)\n\t\t\tx[n] = data_X[i][n];\n\t\tlabels.push_back(1+assign_point_to_cluster_ordinary(x,CX,dims,nof_clusters));\n\t}\n\n\tstd::cout << \"Done!\" << std::endl;\n\n\t// write the clusters\n\twrite_assignment(assignment_filename,labels);\n\n\t// done\n\texit(EXIT_SUCCESS);\n}\n", "meta": {"hexsha": "60c63c7286ebd40b559f6f26f9a906acd13ae231", "size": 5171, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "server/intrinsic/algorithm/gehler2011/lib/mpi_kmeans-1.6/mpi_assign_main.cxx", "max_stars_repo_name": "paulu/opensurfaces", "max_stars_repo_head_hexsha": "7f3e987560faa62cd37f821760683ccd1e053c7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-02-19T00:00:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T03:56:01.000Z", "max_issues_repo_path": "server/intrinsic/algorithm/gehler2011/lib/mpi_kmeans-1.6/mpi_assign_main.cxx", "max_issues_repo_name": "paulu/opensurfaces", "max_issues_repo_head_hexsha": "7f3e987560faa62cd37f821760683ccd1e053c7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T23:39:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-19T11:40:55.000Z", "max_forks_repo_path": "server/intrinsic/algorithm/gehler2011/lib/mpi_kmeans-1.6/mpi_assign_main.cxx", "max_forks_repo_name": "paulu/opensurfaces", "max_forks_repo_head_hexsha": "7f3e987560faa62cd37f821760683ccd1e053c7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 49.0, "max_forks_repo_forks_event_min_datetime": "2015-02-09T15:21:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T14:22:33.000Z", "avg_line_length": 27.2157894737, "max_line_length": 113, "alphanum_fraction": 0.6501643783, "num_tokens": 1406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2845983252697499}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2007-2014 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Copyright (c) 2013-2014 Adam Wulkiewicz, Lodz, Poland.\r\n\r\n// This file was modified by Oracle on 2014, 2016, 2017.\r\n// Modifications copyright (c) 2014-2017, Oracle and/or its affiliates.\r\n\r\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\r\n\r\n// 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_CARTESIAN_INTERSECTION_HPP\r\n#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_INTERSECTION_HPP\r\n\r\n#include <algorithm>\r\n\r\n#include <boost/geometry/core/exception.hpp>\r\n\r\n#include <boost/geometry/geometries/concepts/point_concept.hpp>\r\n#include <boost/geometry/geometries/concepts/segment_concept.hpp>\r\n\r\n#include <boost/geometry/arithmetic/determinant.hpp>\r\n#include <boost/geometry/algorithms/detail/assign_values.hpp>\r\n#include <boost/geometry/algorithms/detail/assign_indexed_point.hpp>\r\n#include <boost/geometry/algorithms/detail/equals/point_point.hpp>\r\n#include <boost/geometry/algorithms/detail/recalculate.hpp>\r\n\r\n#include <boost/geometry/util/math.hpp>\r\n#include <boost/geometry/util/promote_integral.hpp>\r\n#include <boost/geometry/util/select_calculation_type.hpp>\r\n\r\n#include <boost/geometry/strategies/cartesian/area_surveyor.hpp>\r\n#include <boost/geometry/strategies/cartesian/distance_pythagoras.hpp>\r\n#include <boost/geometry/strategies/cartesian/envelope_segment.hpp>\r\n#include <boost/geometry/strategies/cartesian/point_in_poly_winding.hpp>\r\n#include <boost/geometry/strategies/cartesian/side_by_triangle.hpp>\r\n#include <boost/geometry/strategies/covered_by.hpp>\r\n#include <boost/geometry/strategies/intersection.hpp>\r\n#include <boost/geometry/strategies/intersection_result.hpp>\r\n#include <boost/geometry/strategies/side.hpp>\r\n#include <boost/geometry/strategies/side_info.hpp>\r\n#include <boost/geometry/strategies/within.hpp>\r\n\r\n#include <boost/geometry/policies/robustness/robust_point_type.hpp>\r\n#include <boost/geometry/policies/robustness/segment_ratio_type.hpp>\r\n\r\n\r\n#if defined(BOOST_GEOMETRY_DEBUG_ROBUSTNESS)\r\n#  include <boost/geometry/io/wkt/write.hpp>\r\n#endif\r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\n\r\nnamespace strategy { namespace intersection\r\n{\r\n\r\n\r\n/*!\r\n    \\see http://mathworld.wolfram.com/Line-LineIntersection.html\r\n */\r\ntemplate\r\n<\r\n    typename CalculationType = void\r\n>\r\nstruct cartesian_segments\r\n{\r\n    typedef side::side_by_triangle<CalculationType> side_strategy_type;\r\n\r\n    static inline side_strategy_type get_side_strategy()\r\n    {\r\n        return side_strategy_type();\r\n    }\r\n\r\n    template <typename Geometry1, typename Geometry2>\r\n    struct point_in_geometry_strategy\r\n    {\r\n        typedef strategy::within::cartesian_winding\r\n            <\r\n                typename point_type<Geometry1>::type,\r\n                typename point_type<Geometry2>::type,\r\n                CalculationType\r\n            > type;\r\n    };\r\n\r\n    template <typename Geometry1, typename Geometry2>\r\n    static inline typename point_in_geometry_strategy<Geometry1, Geometry2>::type\r\n        get_point_in_geometry_strategy()\r\n    {\r\n        typedef typename point_in_geometry_strategy\r\n            <\r\n                Geometry1, Geometry2\r\n            >::type strategy_type;\r\n        return strategy_type();\r\n    }\r\n\r\n    template <typename Geometry>\r\n    struct area_strategy\r\n    {\r\n        typedef area::surveyor\r\n            <\r\n                typename point_type<Geometry>::type,\r\n                CalculationType\r\n            > type;\r\n    };\r\n\r\n    template <typename Geometry>\r\n    static inline typename area_strategy<Geometry>::type get_area_strategy()\r\n    {\r\n        typedef typename area_strategy<Geometry>::type strategy_type;\r\n        return strategy_type();\r\n    }\r\n\r\n    template <typename Geometry>\r\n    struct distance_strategy\r\n    {\r\n        typedef distance::pythagoras\r\n            <\r\n                CalculationType\r\n            > type;\r\n    };\r\n\r\n    template <typename Geometry>\r\n    static inline typename distance_strategy<Geometry>::type get_distance_strategy()\r\n    {\r\n        typedef typename distance_strategy<Geometry>::type strategy_type;\r\n        return strategy_type();\r\n    }\r\n\r\n    typedef envelope::cartesian_segment<CalculationType>\r\n        envelope_strategy_type;\r\n\r\n    static inline envelope_strategy_type get_envelope_strategy()\r\n    {\r\n        return envelope_strategy_type();\r\n    }\r\n\r\n    template <typename CoordinateType, typename SegmentRatio>\r\n    struct segment_intersection_info\r\n    {\r\n        typedef typename select_most_precise\r\n            <\r\n                CoordinateType, double\r\n            >::type promoted_type;\r\n\r\n        promoted_type comparable_length_a() const\r\n        {\r\n            return dx_a * dx_a + dy_a * dy_a;\r\n        }\r\n\r\n        promoted_type comparable_length_b() const\r\n        {\r\n            return dx_b * dx_b + dy_b * dy_b;\r\n        }\r\n\r\n        template <typename Point, typename Segment1, typename Segment2>\r\n        void assign_a(Point& point, Segment1 const& a, Segment2 const& ) const\r\n        {\r\n            assign(point, a, dx_a, dy_a, robust_ra);\r\n        }\r\n        template <typename Point, typename Segment1, typename Segment2>\r\n        void assign_b(Point& point, Segment1 const& , Segment2 const& b) const\r\n        {\r\n            assign(point, b, dx_b, dy_b, robust_rb);\r\n        }\r\n\r\n        template <typename Point, typename Segment>\r\n        void assign(Point& point, Segment const& segment, CoordinateType const& dx, CoordinateType const& dy, SegmentRatio const& ratio) const\r\n        {\r\n            // Calculate the intersection point based on segment_ratio\r\n            // Up to now, division was postponed. Here we divide using numerator/\r\n            // denominator. In case of integer this results in an integer\r\n            // division.\r\n            BOOST_GEOMETRY_ASSERT(ratio.denominator() != 0);\r\n\r\n            typedef typename promote_integral<CoordinateType>::type promoted_type;\r\n\r\n            promoted_type const numerator\r\n                = boost::numeric_cast<promoted_type>(ratio.numerator());\r\n            promoted_type const denominator\r\n                = boost::numeric_cast<promoted_type>(ratio.denominator());\r\n            promoted_type const dx_promoted = boost::numeric_cast<promoted_type>(dx);\r\n            promoted_type const dy_promoted = boost::numeric_cast<promoted_type>(dy);\r\n\r\n            set<0>(point, get<0, 0>(segment) + boost::numeric_cast\r\n                <\r\n                    CoordinateType\r\n                >(numerator * dx_promoted / denominator));\r\n            set<1>(point, get<0, 1>(segment) + boost::numeric_cast\r\n                <\r\n                    CoordinateType\r\n                >(numerator * dy_promoted / denominator));\r\n        }\r\n\r\n        CoordinateType dx_a, dy_a;\r\n        CoordinateType dx_b, dy_b;\r\n        SegmentRatio robust_ra;\r\n        SegmentRatio robust_rb;\r\n    };\r\n\r\n    template <typename D, typename W, typename ResultType>\r\n    static inline void cramers_rule(D const& dx_a, D const& dy_a,\r\n        D const& dx_b, D const& dy_b, W const& wx, W const& wy,\r\n        // out:\r\n        ResultType& d, ResultType& da)\r\n    {\r\n        // Cramers rule\r\n        d = geometry::detail::determinant<ResultType>(dx_a, dy_a, dx_b, dy_b);\r\n        da = geometry::detail::determinant<ResultType>(dx_b, dy_b, wx, wy);\r\n        // Ratio is da/d , collinear if d == 0, intersecting if 0 <= r <= 1\r\n        // IntersectionPoint = (x1 + r * dx_a, y1 + r * dy_a)\r\n    }\r\n\r\n\r\n    // Relate segments a and b\r\n    template\r\n    <\r\n        typename Segment1,\r\n        typename Segment2,\r\n        typename Policy,\r\n        typename RobustPolicy\r\n    >\r\n    static inline typename Policy::return_type\r\n        apply(Segment1 const& a, Segment2 const& b,\r\n              Policy const& policy, RobustPolicy const& robust_policy)\r\n    {\r\n        // type them all as in Segment1 - TODO reconsider this, most precise?\r\n        typedef typename geometry::point_type<Segment1>::type point_type;\r\n\r\n        typedef typename geometry::robust_point_type\r\n            <\r\n                point_type, RobustPolicy\r\n            >::type robust_point_type;\r\n\r\n        point_type a0, a1, b0, b1;\r\n        robust_point_type a0_rob, a1_rob, b0_rob, b1_rob;\r\n\r\n        detail::assign_point_from_index<0>(a, a0);\r\n        detail::assign_point_from_index<1>(a, a1);\r\n        detail::assign_point_from_index<0>(b, b0);\r\n        detail::assign_point_from_index<1>(b, b1);\r\n\r\n        geometry::recalculate(a0_rob, a0, robust_policy);\r\n        geometry::recalculate(a1_rob, a1, robust_policy);\r\n        geometry::recalculate(b0_rob, b0, robust_policy);\r\n        geometry::recalculate(b1_rob, b1, robust_policy);\r\n\r\n        return apply(a, b, policy, robust_policy, a0_rob, a1_rob, b0_rob, b1_rob);\r\n    }\r\n\r\n    // The main entry-routine, calculating intersections of segments a / b\r\n    // NOTE: Robust* types may be the same as Segments' point types\r\n    template\r\n    <\r\n        typename Segment1,\r\n        typename Segment2,\r\n        typename Policy,\r\n        typename RobustPolicy,\r\n        typename RobustPoint1,\r\n        typename RobustPoint2\r\n    >\r\n    static inline typename Policy::return_type\r\n        apply(Segment1 const& a, Segment2 const& b,\r\n              Policy const&, RobustPolicy const& /*robust_policy*/,\r\n              RobustPoint1 const& robust_a1, RobustPoint1 const& robust_a2,\r\n              RobustPoint2 const& robust_b1, RobustPoint2 const& robust_b2)\r\n    {\r\n        BOOST_CONCEPT_ASSERT( (concepts::ConstSegment<Segment1>) );\r\n        BOOST_CONCEPT_ASSERT( (concepts::ConstSegment<Segment2>) );\r\n\r\n        using geometry::detail::equals::equals_point_point;\r\n        bool const a_is_point = equals_point_point(robust_a1, robust_a2);\r\n        bool const b_is_point = equals_point_point(robust_b1, robust_b2);\r\n\r\n        if(a_is_point && b_is_point)\r\n        {\r\n            return equals_point_point(robust_a1, robust_b2)\r\n                ? Policy::degenerate(a, true)\r\n                : Policy::disjoint()\r\n                ;\r\n        }\r\n\r\n        side_info sides;\r\n        sides.set<0>(side_strategy_type::apply(robust_b1, robust_b2, robust_a1),\r\n                     side_strategy_type::apply(robust_b1, robust_b2, robust_a2));\r\n\r\n        if (sides.same<0>())\r\n        {\r\n            // Both points are at same side of other segment, we can leave\r\n            return Policy::disjoint();\r\n        }\r\n\r\n        sides.set<1>(side_strategy_type::apply(robust_a1, robust_a2, robust_b1),\r\n                     side_strategy_type::apply(robust_a1, robust_a2, robust_b2));\r\n        \r\n        if (sides.same<1>())\r\n        {\r\n            // Both points are at same side of other segment, we can leave\r\n            return Policy::disjoint();\r\n        }\r\n\r\n        bool collinear = sides.collinear();\r\n\r\n        typedef typename select_most_precise\r\n            <\r\n                typename geometry::coordinate_type<RobustPoint1>::type,\r\n                typename geometry::coordinate_type<RobustPoint2>::type\r\n            >::type robust_coordinate_type;\r\n\r\n        typedef typename segment_ratio_type\r\n            <\r\n                typename geometry::point_type<Segment1>::type, // TODO: most precise point?\r\n                RobustPolicy\r\n            >::type ratio_type;\r\n\r\n        segment_intersection_info\r\n            <\r\n                typename select_calculation_type<Segment1, Segment2, CalculationType>::type,\r\n                ratio_type\r\n            > sinfo;\r\n\r\n        sinfo.dx_a = get<1, 0>(a) - get<0, 0>(a); // distance in x-dir\r\n        sinfo.dx_b = get<1, 0>(b) - get<0, 0>(b);\r\n        sinfo.dy_a = get<1, 1>(a) - get<0, 1>(a); // distance in y-dir\r\n        sinfo.dy_b = get<1, 1>(b) - get<0, 1>(b);\r\n\r\n        robust_coordinate_type const robust_dx_a = get<0>(robust_a2) - get<0>(robust_a1);\r\n        robust_coordinate_type const robust_dx_b = get<0>(robust_b2) - get<0>(robust_b1);\r\n        robust_coordinate_type const robust_dy_a = get<1>(robust_a2) - get<1>(robust_a1);\r\n        robust_coordinate_type const robust_dy_b = get<1>(robust_b2) - get<1>(robust_b1);\r\n\r\n        // r: ratio 0-1 where intersection divides A/B\r\n        // (only calculated for non-collinear segments)\r\n        if (! collinear)\r\n        {\r\n            robust_coordinate_type robust_da0, robust_da;\r\n            robust_coordinate_type robust_db0, robust_db;\r\n\r\n            cramers_rule(robust_dx_a, robust_dy_a, robust_dx_b, robust_dy_b,\r\n                get<0>(robust_a1) - get<0>(robust_b1),\r\n                get<1>(robust_a1) - get<1>(robust_b1),\r\n                robust_da0, robust_da);\r\n\r\n            cramers_rule(robust_dx_b, robust_dy_b, robust_dx_a, robust_dy_a,\r\n                get<0>(robust_b1) - get<0>(robust_a1),\r\n                get<1>(robust_b1) - get<1>(robust_a1),\r\n                robust_db0, robust_db);\r\n\r\n            math::detail::equals_factor_policy<robust_coordinate_type>\r\n                policy(robust_dx_a, robust_dy_a, robust_dx_b, robust_dy_b);\r\n            robust_coordinate_type const zero = 0;\r\n            if (math::detail::equals_by_policy(robust_da0, zero, policy)\r\n             || math::detail::equals_by_policy(robust_db0, zero, policy))\r\n            {\r\n                // If this is the case, no rescaling is done for FP precision.\r\n                // We set it to collinear, but it indicates a robustness issue.\r\n                sides.set<0>(0,0);\r\n                sides.set<1>(0,0);\r\n                collinear = true;\r\n            }\r\n            else\r\n            {\r\n                sinfo.robust_ra.assign(robust_da, robust_da0);\r\n                sinfo.robust_rb.assign(robust_db, robust_db0);\r\n            }\r\n        }\r\n\r\n        if (collinear)\r\n        {\r\n            std::pair<bool, bool> const collinear_use_first\r\n                    = is_x_more_significant(geometry::math::abs(robust_dx_a),\r\n                                            geometry::math::abs(robust_dy_a),\r\n                                            geometry::math::abs(robust_dx_b),\r\n                                            geometry::math::abs(robust_dy_b),\r\n                                            a_is_point, b_is_point);\r\n\r\n            if (collinear_use_first.second)\r\n            {\r\n                // Degenerate cases: segments of single point, lying on other segment, are not disjoint\r\n                // This situation is collinear too\r\n\r\n                if (collinear_use_first.first)\r\n                {\r\n                    return relate_collinear<0, Policy, ratio_type>(a, b,\r\n                            robust_a1, robust_a2, robust_b1, robust_b2,\r\n                            a_is_point, b_is_point);\r\n                }\r\n                else\r\n                {\r\n                    // Y direction contains larger segments (maybe dx is zero)\r\n                    return relate_collinear<1, Policy, ratio_type>(a, b,\r\n                            robust_a1, robust_a2, robust_b1, robust_b2,\r\n                            a_is_point, b_is_point);\r\n                }\r\n            }\r\n        }\r\n\r\n        return Policy::segments_crosses(sides, sinfo, a, b);\r\n    }\r\n\r\nprivate:\r\n    // first is true if x is more significant\r\n    // second is true if the more significant difference is not 0\r\n    template <typename RobustCoordinateType>\r\n    static inline std::pair<bool, bool>\r\n        is_x_more_significant(RobustCoordinateType const& abs_robust_dx_a,\r\n                              RobustCoordinateType const& abs_robust_dy_a,\r\n                              RobustCoordinateType const& abs_robust_dx_b,\r\n                              RobustCoordinateType const& abs_robust_dy_b,\r\n                              bool const a_is_point,\r\n                              bool const b_is_point)\r\n    {\r\n        //BOOST_GEOMETRY_ASSERT_MSG(!(a_is_point && b_is_point), \"both segments shouldn't be degenerated\");\r\n\r\n        // for degenerated segments the second is always true because this function\r\n        // shouldn't be called if both segments were degenerated\r\n\r\n        if (a_is_point)\r\n        {\r\n            return std::make_pair(abs_robust_dx_b >= abs_robust_dy_b, true);\r\n        }\r\n        else if (b_is_point)\r\n        {\r\n            return std::make_pair(abs_robust_dx_a >= abs_robust_dy_a, true);\r\n        }\r\n        else\r\n        {\r\n            RobustCoordinateType const min_dx = (std::min)(abs_robust_dx_a, abs_robust_dx_b);\r\n            RobustCoordinateType const min_dy = (std::min)(abs_robust_dy_a, abs_robust_dy_b);\r\n            return min_dx == min_dy ?\r\n                    std::make_pair(true, min_dx > RobustCoordinateType(0)) :\r\n                    std::make_pair(min_dx > min_dy, true);\r\n        }\r\n    }\r\n\r\n    template\r\n    <\r\n        std::size_t Dimension,\r\n        typename Policy,\r\n        typename RatioType,\r\n        typename Segment1,\r\n        typename Segment2,\r\n        typename RobustPoint1,\r\n        typename RobustPoint2\r\n    >\r\n    static inline typename Policy::return_type\r\n        relate_collinear(Segment1 const& a,\r\n                         Segment2 const& b,\r\n                         RobustPoint1 const& robust_a1, RobustPoint1 const& robust_a2,\r\n                         RobustPoint2 const& robust_b1, RobustPoint2 const& robust_b2,\r\n                         bool a_is_point, bool b_is_point)\r\n    {\r\n        if (a_is_point)\r\n        {\r\n            return relate_one_degenerate<Policy, RatioType>(a,\r\n                get<Dimension>(robust_a1),\r\n                get<Dimension>(robust_b1), get<Dimension>(robust_b2),\r\n                true);\r\n        }\r\n        if (b_is_point)\r\n        {\r\n            return relate_one_degenerate<Policy, RatioType>(b,\r\n                get<Dimension>(robust_b1),\r\n                get<Dimension>(robust_a1), get<Dimension>(robust_a2),\r\n                false);\r\n        }\r\n        return relate_collinear<Policy, RatioType>(a, b,\r\n                                get<Dimension>(robust_a1),\r\n                                get<Dimension>(robust_a2),\r\n                                get<Dimension>(robust_b1),\r\n                                get<Dimension>(robust_b2));\r\n    }\r\n\r\n    /// Relate segments known collinear\r\n    template\r\n    <\r\n        typename Policy,\r\n        typename RatioType,\r\n        typename Segment1,\r\n        typename Segment2,\r\n        typename RobustType1,\r\n        typename RobustType2\r\n    >\r\n    static inline typename Policy::return_type\r\n        relate_collinear(Segment1 const& a, Segment2 const& b,\r\n                         RobustType1 oa_1, RobustType1 oa_2,\r\n                         RobustType2 ob_1, RobustType2 ob_2)\r\n    {\r\n        // Calculate the ratios where a starts in b, b starts in a\r\n        //         a1--------->a2         (2..7)\r\n        //                b1----->b2      (5..8)\r\n        // length_a: 7-2=5\r\n        // length_b: 8-5=3\r\n        // b1 is located w.r.t. a at ratio: (5-2)/5=3/5 (on a)\r\n        // b2 is located w.r.t. a at ratio: (8-2)/5=6/5 (right of a)\r\n        // a1 is located w.r.t. b at ratio: (2-5)/3=-3/3 (left of b)\r\n        // a2 is located w.r.t. b at ratio: (7-5)/3=2/3 (on b)\r\n        // A arrives (a2 on b), B departs (b1 on a)\r\n\r\n        // If both are reversed:\r\n        //         a2<---------a1         (7..2)\r\n        //                b2<-----b1      (8..5)\r\n        // length_a: 2-7=-5\r\n        // length_b: 5-8=-3\r\n        // b1 is located w.r.t. a at ratio: (8-7)/-5=-1/5 (before a starts)\r\n        // b2 is located w.r.t. a at ratio: (5-7)/-5=2/5 (on a)\r\n        // a1 is located w.r.t. b at ratio: (7-8)/-3=1/3 (on b)\r\n        // a2 is located w.r.t. b at ratio: (2-8)/-3=6/3 (after b ends)\r\n\r\n        // If both one is reversed:\r\n        //         a1--------->a2         (2..7)\r\n        //                b2<-----b1      (8..5)\r\n        // length_a: 7-2=+5\r\n        // length_b: 5-8=-3\r\n        // b1 is located w.r.t. a at ratio: (8-2)/5=6/5 (after a ends)\r\n        // b2 is located w.r.t. a at ratio: (5-2)/5=3/5 (on a)\r\n        // a1 is located w.r.t. b at ratio: (2-8)/-3=6/3 (after b ends)\r\n        // a2 is located w.r.t. b at ratio: (7-8)/-3=1/3 (on b)\r\n        RobustType1 const length_a = oa_2 - oa_1; // no abs, see above\r\n        RobustType2 const length_b = ob_2 - ob_1;\r\n\r\n        RatioType ra_from(oa_1 - ob_1, length_b);\r\n        RatioType ra_to(oa_2 - ob_1, length_b);\r\n        RatioType rb_from(ob_1 - oa_1, length_a);\r\n        RatioType rb_to(ob_2 - oa_1, length_a);\r\n\r\n        // use absolute measure to detect endpoints intersection\r\n        // NOTE: it'd be possible to calculate bx_wrt_a using ax_wrt_b values\r\n        int const a1_wrt_b = position_value(oa_1, ob_1, ob_2);\r\n        int const a2_wrt_b = position_value(oa_2, ob_1, ob_2);\r\n        int const b1_wrt_a = position_value(ob_1, oa_1, oa_2);\r\n        int const b2_wrt_a = position_value(ob_2, oa_1, oa_2);\r\n        \r\n        // fix the ratios if necessary\r\n        // CONSIDER: fixing ratios also in other cases, if they're inconsistent\r\n        // e.g. if ratio == 1 or 0 (so IP at the endpoint)\r\n        // but position value indicates that the IP is in the middle of the segment\r\n        // because one of the segments is very long\r\n        // In such case the ratios could be moved into the middle direction\r\n        // by some small value (e.g. EPS+1ULP)\r\n        if (a1_wrt_b == 1)\r\n        {\r\n            ra_from.assign(0, 1);\r\n            rb_from.assign(0, 1);\r\n        }\r\n        else if (a1_wrt_b == 3)\r\n        {\r\n            ra_from.assign(1, 1);\r\n            rb_to.assign(0, 1);\r\n        } \r\n\r\n        if (a2_wrt_b == 1)\r\n        {\r\n            ra_to.assign(0, 1);\r\n            rb_from.assign(1, 1);\r\n        }\r\n        else if (a2_wrt_b == 3)\r\n        {\r\n            ra_to.assign(1, 1);\r\n            rb_to.assign(1, 1);\r\n        }\r\n\r\n        if ((a1_wrt_b < 1 && a2_wrt_b < 1) || (a1_wrt_b > 3 && a2_wrt_b > 3))\r\n        //if ((ra_from.left() && ra_to.left()) || (ra_from.right() && ra_to.right()))\r\n        {\r\n            return Policy::disjoint();\r\n        }\r\n\r\n        bool const opposite = math::sign(length_a) != math::sign(length_b);\r\n\r\n        return Policy::segments_collinear(a, b, opposite,\r\n                                          a1_wrt_b, a2_wrt_b, b1_wrt_a, b2_wrt_a,\r\n                                          ra_from, ra_to, rb_from, rb_to);\r\n    }\r\n\r\n    /// Relate segments where one is degenerate\r\n    template\r\n    <\r\n        typename Policy,\r\n        typename RatioType,\r\n        typename DegenerateSegment,\r\n        typename RobustType1,\r\n        typename RobustType2\r\n    >\r\n    static inline typename Policy::return_type\r\n        relate_one_degenerate(DegenerateSegment const& degenerate_segment,\r\n                              RobustType1 d, RobustType2 s1, RobustType2 s2,\r\n                              bool a_degenerate)\r\n    {\r\n        // Calculate the ratios where ds starts in s\r\n        //         a1--------->a2         (2..6)\r\n        //              b1/b2      (4..4)\r\n        // Ratio: (4-2)/(6-2)\r\n        RatioType const ratio(d - s1, s2 - s1);\r\n\r\n        if (!ratio.on_segment())\r\n        {\r\n            return Policy::disjoint();\r\n        }\r\n\r\n        return Policy::one_degenerate(degenerate_segment, ratio, a_degenerate);\r\n    }\r\n\r\n    template <typename ProjCoord1, typename ProjCoord2>\r\n    static inline int position_value(ProjCoord1 const& ca1,\r\n                                     ProjCoord2 const& cb1,\r\n                                     ProjCoord2 const& cb2)\r\n    {\r\n        // S1x  0   1    2     3   4\r\n        // S2       |---------->\r\n        return math::equals(ca1, cb1) ? 1\r\n             : math::equals(ca1, cb2) ? 3\r\n             : cb1 < cb2 ?\r\n                ( ca1 < cb1 ? 0\r\n                : ca1 > cb2 ? 4\r\n                : 2 )\r\n              : ( ca1 > cb1 ? 0\r\n                : ca1 < cb2 ? 4\r\n                : 2 );\r\n    }\r\n};\r\n\r\n\r\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\nnamespace services\r\n{\r\n\r\ntemplate <typename CalculationType>\r\nstruct default_strategy<cartesian_tag, CalculationType>\r\n{\r\n    typedef cartesian_segments<CalculationType> type;\r\n};\r\n\r\n} // namespace services\r\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\n\r\n\r\n}} // namespace strategy::intersection\r\n\r\nnamespace strategy\r\n{\r\n\r\nnamespace within { namespace services\r\n{\r\n\r\ntemplate <typename Geometry1, typename Geometry2, typename AnyTag1, typename AnyTag2>\r\nstruct default_strategy<Geometry1, Geometry2, AnyTag1, AnyTag2, linear_tag, linear_tag, cartesian_tag, cartesian_tag>\r\n{\r\n    typedef strategy::intersection::cartesian_segments<> type;\r\n};\r\n\r\ntemplate <typename Geometry1, typename Geometry2, typename AnyTag1, typename AnyTag2>\r\nstruct default_strategy<Geometry1, Geometry2, AnyTag1, AnyTag2, linear_tag, polygonal_tag, cartesian_tag, cartesian_tag>\r\n{\r\n    typedef strategy::intersection::cartesian_segments<> type;\r\n};\r\n\r\ntemplate <typename Geometry1, typename Geometry2, typename AnyTag1, typename AnyTag2>\r\nstruct default_strategy<Geometry1, Geometry2, AnyTag1, AnyTag2, polygonal_tag, linear_tag, cartesian_tag, cartesian_tag>\r\n{\r\n    typedef strategy::intersection::cartesian_segments<> type;\r\n};\r\n\r\ntemplate <typename Geometry1, typename Geometry2, typename AnyTag1, typename AnyTag2>\r\nstruct default_strategy<Geometry1, Geometry2, AnyTag1, AnyTag2, polygonal_tag, polygonal_tag, cartesian_tag, cartesian_tag>\r\n{\r\n    typedef strategy::intersection::cartesian_segments<> type;\r\n};\r\n\r\n}} // within::services\r\n\r\nnamespace covered_by { namespace services\r\n{\r\n\r\ntemplate <typename Geometry1, typename Geometry2, typename AnyTag1, typename AnyTag2>\r\nstruct default_strategy<Geometry1, Geometry2, AnyTag1, AnyTag2, linear_tag, linear_tag, cartesian_tag, cartesian_tag>\r\n{\r\n    typedef strategy::intersection::cartesian_segments<> type;\r\n};\r\n\r\ntemplate <typename Geometry1, typename Geometry2, typename AnyTag1, typename AnyTag2>\r\nstruct default_strategy<Geometry1, Geometry2, AnyTag1, AnyTag2, linear_tag, polygonal_tag, cartesian_tag, cartesian_tag>\r\n{\r\n    typedef strategy::intersection::cartesian_segments<> type;\r\n};\r\n\r\ntemplate <typename Geometry1, typename Geometry2, typename AnyTag1, typename AnyTag2>\r\nstruct default_strategy<Geometry1, Geometry2, AnyTag1, AnyTag2, polygonal_tag, linear_tag, cartesian_tag, cartesian_tag>\r\n{\r\n    typedef strategy::intersection::cartesian_segments<> type;\r\n};\r\n\r\ntemplate <typename Geometry1, typename Geometry2, typename AnyTag1, typename AnyTag2>\r\nstruct default_strategy<Geometry1, Geometry2, AnyTag1, AnyTag2, polygonal_tag, polygonal_tag, cartesian_tag, cartesian_tag>\r\n{\r\n    typedef strategy::intersection::cartesian_segments<> type;\r\n};\r\n\r\n}} // within::services\r\n\r\n} // strategy\r\n\r\n}} // namespace boost::geometry\r\n\r\n\r\n#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_INTERSECTION_HPP\r\n", "meta": {"hexsha": "8b3c31fe466b72a02be271bbe331b8e77f662266", "size": 26938, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "trunk/src/include/boost/geometry/strategies/cartesian/intersection.hpp", "max_stars_repo_name": "SnailTowardThesun/face-detect", "max_stars_repo_head_hexsha": "4f02115684898a41564bbe7fc766b76e9e417ac9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T06:33:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T06:33:58.000Z", "max_issues_repo_path": "trunk/src/include/boost/geometry/strategies/cartesian/intersection.hpp", "max_issues_repo_name": "SnailTowardThesun/face-detect", "max_issues_repo_head_hexsha": "4f02115684898a41564bbe7fc766b76e9e417ac9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-10-12T02:43:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-14T06:08:53.000Z", "max_forks_repo_path": "3rdparty/include/boost/geometry/strategies/cartesian/intersection.hpp", "max_forks_repo_name": "gradinkov/nheqminer-gradinkov", "max_forks_repo_head_hexsha": "6422e0cc3eff7fcab30561a57c1339fbe0107b62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-10T03:18:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:52:12.000Z", "avg_line_length": 37.7812061711, "max_line_length": 143, "alphanum_fraction": 0.5925829683, "num_tokens": 6466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2845490086209969}}
{"text": "/*\nCopyright (c) 2016 Bastien Durix\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n\n/**\n *  \\file VoronoiSkeleton2D.cpp\n *  \\brief Defines functions to compute 2d skeleton with voronoi algorithm\n *  \\author Bastien Durix\n */\n\n#include \"VoronoiSkeleton2D.h\"\n#include <voro++/voro++.hh>\n#include <Eigen/Dense>\n#include <mathtools/affine/Point.h>\n\n#include <algorithm/graphoperation/ConnectedComponents.h>\n\ntemplate<typename Model>\nvoid VoronoiOrtho(typename skeleton::GraphCurveSkeleton<Model>::Ptr skel_int, const boundary::DiscreteBoundary<2>::Ptr disbnd, const mathtools::affine::Frame<2>::Ptr frame)\n{\n\ttypename skeleton::GraphCurveSkeleton<Model>::Ptr grskel(new skeleton::GraphCurveSkeleton<Model>(skel_int->getModel()));\n\n\tstd::vector<mathtools::affine::Point<2> > bndpts(0);\n\tdisbnd->getVerticesPoint(bndpts);\n\tstd::vector<Eigen::Vector2d> bndvec(bndpts.size());\n\t\n\t/**\n\t *  Get the points coordinates in skeleton frame\n\t */\n\tdouble xinf = 0;\n\tdouble xsup = 0;\n\tdouble yinf = 0;\n\tdouble ysup = 0;\n\tfor(unsigned int i=0; i< bndpts.size(); i++)\n\t{\n\t\tbndvec[i] = bndpts[i].getCoords(frame);\n\t\tif(xinf>bndvec[i](0) || i==0)\n\t\t\txinf=bndvec[i](0);\n\t\tif(yinf>bndvec[i](1) || i==0)\n\t\t\tyinf=bndvec[i](1);\n\t\tif(xsup<bndvec[i](0) || i==0)\n\t\t\txsup=bndvec[i](0);\n\t\tif(ysup<bndvec[i](1) || i==0)\n\t\t\tysup=bndvec[i](1);\n\t}\n\t\n\tdouble xsize = xsup-xinf;\n\tdouble ysize = ysup-yinf;\n\t\n\txinf -= xsize*10;\n\txsup += xsize*10;\n\tyinf -= ysize*10;\n\tysup += ysize*10;\n\n\t\n\t/*\n\t *  Build Voronoi container\n\t */\n\tvoro::container vorocont(xinf,xsup,\n\t\t\t\t\t\t\t yinf,ysup,\n\t\t\t\t\t\t\t -1.0, 1.0,\n\t\t\t\t\t\t\t 6,6,6,\n\t\t\t\t\t\t\t false,false,false,\n\t\t\t\t\t\t\t 8);\n\t\n\t/*\n\t *  Put points in voronoi container\n\t */\n\tfor(unsigned int i=0;i<bndpts.size();i++)\n\t{\n\t\tvorocont.put(i,bndvec[i](0),bndvec[i](1),0.0);\n\t}\n\n\t/*\n\t *  Loop on cells (with neighbor information)\n\t */\n\tvoro::c_loop_all voroloopall(vorocont);\n\t\n\t/*\n\t *  Nodes that are inside the skeleton\n\t */\n\tstd::list<unsigned int> v_intsph;\n\t\n\t/*\n\t *  Added nodes\n\t */\n\tstd::map<unsigned int,Eigen::Vector3d> v_added;\n\n\tif(voroloopall.start())\n\t{\n\t\tdo\n\t\t{\n\t\t\tvoro::voronoicell_neighbor voroneigh;\n\t\t\tif(vorocont.compute_cell(voroneigh,voroloopall))/*For each cell*/\n\t\t\t{\n\t\t\t\t/*Put cell corners in skeleton*/\n\t\t\t\tdouble x,y,z;\n\t\t\t\tvoroloopall.pos(x,y,z);\n\t\t\t\t\n\t\t\t\tstd::vector<double> vert;\n\t\t\t\tvoroneigh.vertices(x,y,z,vert);\n\t\t\t\t\n\t\t\t\tEigen::Vector2d center(x,y);\n\t\t\t\t\n\t\t\t\tstd::vector<unsigned int> indices(voroneigh.p);\n\t\t\t\t\n\t\t\t\tfor(unsigned int i=0;i<(unsigned int)voroneigh.p;i++)\n\t\t\t\t{\n\t\t\t\t\tif(vert[i*3+2]==1.0)\n\t\t\t\t\t{\n\t\t\t\t\t\tEigen::Vector3d corner(vert[i*3],vert[i*3+1],0.0);\n\t\t\t\t\t\tcorner(2) = (corner.block<2,1>(0,0)-center).norm();\n\t\t\t\t\t\tbool isin=false;\n\t\t\t\t\t\tfor(std::map<unsigned int,Eigen::Vector3d>::iterator it = v_added.begin(); it != v_added.end() & !isin; it++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(it->second.isApprox(corner,std::numeric_limits<float>::epsilon()))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tisin=true;\n\t\t\t\t\t\t\t\tindices[i] = it->first;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(!isin)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tindices[i] = grskel->addNode(corner);\n\t\t\t\t\t\t\tv_added[indices[i]] = corner;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t/*\n\t\t\t\t * Then link each corner to its neighbors\n\t\t\t\t * Except if there is a link between the two cells\n\t\t\t\t */\n\t\t\t\tfor(unsigned int i=0;i<(unsigned int)voroneigh.p;i++)\n\t\t\t\t{\n\t\t\t\t\tif(vert[i*3+2]==1.0)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor(int j=0;j<voroneigh.nu[i];j++) //nu : corner order (number of edge from this corner)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint ind_j = voroneigh.ed[i][j];\n\t\t\t\t\t\t\tif(vert[ind_j*3+2]==1.0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tbool found=false;\n\t\t\t\t\t\t\t\tunsigned int ind_neigh=0;\n\t\t\t\t\t\t\t\t/*Test if there is a link between the two cells*/\n\t\t\t\t\t\t\t\tfor(int k=0;k<voroneigh.nu[i] && !found;k++)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tif(voroneigh.ne[i][k] >=0 )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tint face = voroneigh.ne[i][k];\n\t\t\t\t\t\t\t\t\t\tfor(int l=0;l<voroneigh.nu[ind_j] && !found;l++)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tif(face == voroneigh.ne[ind_j][l])\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tfound=true;\n\t\t\t\t\t\t\t\t\t\t\t\tind_neigh=face;\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif(!found)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tgrskel->addEdge(indices[i],indices[ind_j]);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse if(disbnd->getNext(voroloopall.pid())!=ind_neigh && disbnd->getNext(ind_neigh)!=(unsigned int)voroloopall.pid())\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tgrskel->addEdge(indices[i],indices[ind_j]);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse if(disbnd->getNext(ind_neigh)==(unsigned int)voroloopall.pid() && disbnd->getFrame()->getBasis()->isDirect())\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tEigen::Matrix2d mat;\n\t\t\t\t\t\t\t\t\tmat.block<2,1>(0,0) = bndpts[ind_neigh].getCoords() - bndpts[voroloopall.pid()].getCoords();\n\t\t\t\t\t\t\t\t\tmat.block<2,1>(0,1) = grskel->getNode(indices[ind_j]).template block<2,1>(0,0) - grskel->getNode(indices[i]).template block<2,1>(0,0);\n\n\t\t\t\t\t\t\t\t\tif(mat.determinant()<0)\n\t\t\t\t\t\t\t\t\t\tv_intsph.push_back(indices[ind_j]);\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\tv_intsph.push_back(indices[i]);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse if(disbnd->getNext((unsigned int)voroloopall.pid())==ind_neigh && !disbnd->getFrame()->getBasis()->isDirect())\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tEigen::Matrix2d mat;\n\t\t\t\t\t\t\t\t\tmat.block<2,1>(0,0) = bndpts[ind_neigh].getCoords() - bndpts[voroloopall.pid()].getCoords();\n\t\t\t\t\t\t\t\t\tmat.block<2,1>(0,1) = grskel->getNode(indices[ind_j]).template block<2,1>(0,0) - grskel->getNode(indices[i]).template block<2,1>(0,0);\n\n\t\t\t\t\t\t\t\t\tif(mat.determinant()>0)\n\t\t\t\t\t\t\t\t\t\tv_intsph.push_back(indices[ind_j]);\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\tv_intsph.push_back(indices[i]);\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\t\t\t}\n\t\t}while(voroloopall.inc());\n\t}\n\t\n\tv_intsph.sort();\n\tv_intsph.unique();\n\n\t/*\n\t *  Separation into connected components (internal and external)\n\t */\n\tstd::list<typename skeleton::GraphCurveSkeleton<Model>::Ptr> list_comp = algorithm::graphoperation::SeparateComponents(grskel);\n\n\tfor(typename std::list<typename skeleton::GraphCurveSkeleton<Model>::Ptr>::iterator it = list_comp.begin(); it!=list_comp.end(); it++)\n\t{\n\t\tstd::list<unsigned int> list_ver;\n\t\t(*it)->getAllNodes(list_ver);\n\n\t\tbool intern = false;\n\t\tfor(std::list<unsigned int>::iterator itl = v_intsph.begin(); itl != v_intsph.end() && !intern; itl++)\n\t\t{\n\t\t\tif( std::find(list_ver.begin(),list_ver.end(),*itl) != list_ver.end() )\n\t\t\t{\n\t\t\t\tintern=true;\n\t\t\t}\n\t\t}\n\n\t\tif(intern)\n\t\t{\n\t\t\tskel_int->insertExactSkel(*it);\n\t\t}\n\t}\n}\n\nskeleton::GraphSkel2d::Ptr algorithm::skeletonization::VoronoiSkeleton2d(const boundary::DiscreteBoundary<2>::Ptr disbnd)\n{\n\tskeleton::model::Classic<2>::Ptr model(new skeleton::model::Classic<2>(disbnd->getFrame()));\n\tskeleton::GraphSkel2d::Ptr grskel(new skeleton::GraphSkel2d(model));\n\t\n\tVoronoiOrtho<skeleton::model::Classic<2> >(grskel,disbnd,model->getFrame());\n\n\treturn grskel;\n}\n", "meta": {"hexsha": "2ac29276423e99c84e0681891f40ed4d9750b930", "size": 7563, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lib/algorithm/skeletonization/voronoi/VoronoiSkeleton2D.cpp", "max_stars_repo_name": "Ibujah/propagatedskeleton", "max_stars_repo_head_hexsha": "56a583e6f9907e68a388eec6ad179ad671ca156e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-03-29T08:40:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-30T11:06:46.000Z", "max_issues_repo_path": "src/lib/algorithm/skeletonization/voronoi/VoronoiSkeleton2D.cpp", "max_issues_repo_name": "Ibujah/propagatedskeleton", "max_issues_repo_head_hexsha": "56a583e6f9907e68a388eec6ad179ad671ca156e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib/algorithm/skeletonization/voronoi/VoronoiSkeleton2D.cpp", "max_forks_repo_name": "Ibujah/propagatedskeleton", "max_forks_repo_head_hexsha": "56a583e6f9907e68a388eec6ad179ad671ca156e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4280155642, "max_line_length": 172, "alphanum_fraction": 0.6313632157, "num_tokens": 2294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.28453683910644834}}
{"text": "/*    Copyright (c) 2010-2015, Delft University of Technology\n *    All rights reserved.\n *\n *    Redistribution and use in source and binary forms, with or without modification, are\n *    permitted provided that the following conditions are met:\n *      - Redistributions of source code must retain the above copyright notice, this list of\n *        conditions and the following disclaimer.\n *      - Redistributions in binary form must reproduce the above copyright notice, this list of\n *        conditions and the following disclaimer in the documentation and/or other materials\n *        provided with the distribution.\n *      - Neither the name of the Delft University of Technology nor the names of its contributors\n *        may be used to endorse or promote products derived from this software without specific\n *        prior written permission.\n *\n *    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS\n *    OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n *    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *    COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n *    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n *    GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n *    AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n *    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n *    OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *    Changelog\n *      YYMMDD    Author            Comment\n *      101125    D. Dirkx          First version of file\n *      110127    D. Dirkx          Finalized for code check.\n *      110206    J. Melman         Minor formatting issues.\n *      110905    S. Billemont      Reorganized includes.\n *                                  Moved (con/de)structors and getter/setters to header.\n *      120323    D. Dirkx          Removed set functions; moved functionality to constructor,\n *                                  removed raw pointer arrays\n *    References\n *      An example of a heritage code which uses such a mesh is found in:\n *          The Mark IV Supersonic-Hypersonic Arbitrary Body Program, Volume\n *          II-Program Formulation, Douglas Aircraft Company, AFFDL-TR-73-159,\n *          Volume II.\n *\n *    Notes\n *      The numberOfLines_ and numberOfPoints_ member variables denote the number of mesh points.\n *      The number of panels in the mesh will be numberOfLines_ - 1 by numberOfPoints_ - 1.\n *\n */\n\n#include <boost/multi_array.hpp>\n#include <limits>\n#include <Eigen/Geometry>\n\n#include \"Tudat/Mathematics/GeometricShapes/quadrilateralMeshedSurfaceGeometry.h\"\n\nnamespace tudat\n{\nnamespace geometric_shapes\n{\n\n//! Calculate panel characteristics.\nvoid QuadrilateralMeshedSurfaceGeometry::performPanelCalculations( )\n{\n    // Allocate memory for panel properties.\n    panelCentroids_.resize(boost::extents[ numberOfLines_ - 1 ][ numberOfPoints_ - 1 ]);\n    panelSurfaceNormals_.resize(boost::extents[ numberOfLines_ - 1 ][ numberOfPoints_ - 1 ]);\n    panelAreas_.resize(boost::extents[ numberOfLines_ - 1 ][ numberOfPoints_ - 1 ]);\n\n    // Declare local variables for normal and area determination.\n    Eigen::Vector3d crossVector1;\n    Eigen::Vector3d crossVector2;\n\n    // Reset total area.\n    totalArea_ = 0.0;\n\n    // Loop over all panels to determine properties.\n    for ( int i = 0; i < numberOfLines_ - 1; i++ )\n    {\n        for ( int j = 0; j < numberOfPoints_ - 1; j++ )\n        {\n            // Set panel centroid.\n            panelCentroids_[ i ][ j ] = ( meshPoints_[ i ][ j ] +\n                                          meshPoints_[ i + 1 ][ j ] +\n                                          meshPoints_[ i ][ j + 1 ] +\n                                          meshPoints_[ i + 1 ][ j + 1 ] ) / 4;\n\n            // Set panel cross vectors.\n            crossVector1 = meshPoints_[ i + 1 ][ j + 1 ] - meshPoints_[ i ][ j ];\n            crossVector2 = meshPoints_[ i + 1 ][ j ] - meshPoints_[ i ][ j + 1 ];\n\n            // Set panel normal (not yet normalized).\n            panelSurfaceNormals_[ i ][ j ] = crossVector1.cross( crossVector2 );\n\n            // Set panel area (not yet correct size).\n            panelAreas_[ i ][ j ] = panelSurfaceNormals_[ i ][ j ].norm( );\n            if ( panelAreas_[ i ][ j ] < std::numeric_limits< double >::epsilon( ) )\n            {\n                std::cerr << \"WARNING panel area is zero in part at panel\" << i\n                          << \", \" << j << std::endl;\n            }\n\n            // Normalize panel normal and, if necessary, invert normal direction.\n            panelSurfaceNormals_[ i ][ j ] *= reversalOperator_;\n            panelSurfaceNormals_[ i ][ j ].normalize( );\n\n            // Set panel area to correct size.\n            panelAreas_[ i ][ j ] *= 0.5;\n\n            // Add panel area to total area.\n            totalArea_ += panelAreas_[ i ][ j ];\n        }\n    }\n}\n\n//! Set reversal operator.\nvoid QuadrilateralMeshedSurfaceGeometry::setReversalOperator( const bool isMeshInverted )\n{\n    if ( isMeshInverted == 0 )\n    {\n        reversalOperator_ = 1;\n    }\n\n    else\n    {\n        reversalOperator_ = -1;\n    }\n}\n\n//! Get boolean denoting if the mesh is inverted.\nbool QuadrilateralMeshedSurfaceGeometry::getReversalOperator( )\n{\n    bool isMeshInverted;\n    if ( reversalOperator_ == 1 )\n    {\n        isMeshInverted = 0;\n    }\n\n    else\n    {\n        isMeshInverted = 1;\n    }\n\n    return isMeshInverted;\n}\n\n//! Overload ostream to print class information.\nstd::ostream& operator<<( std::ostream& stream,\n                          QuadrilateralMeshedSurfaceGeometry& quadrilateralMeshedSurfaceGeometry )\n{\n    stream << \"This is a quadrilateral meshed surface geometry\"\n           << \" of a single part.\" << std::endl;\n    stream << \"The number of lines ( contours ) is: \"\n           << quadrilateralMeshedSurfaceGeometry.numberOfLines_ << std::endl;\n    stream << \"The number of points per line is: \"\n           << quadrilateralMeshedSurfaceGeometry.numberOfPoints_ << std::endl;\n\n    // Return stream.\n    return stream;\n}\n\n} // namespace geometric_shapes\n} // namespace tudat\n", "meta": {"hexsha": "241d32acb828e8816690bf17ef4a685db25ef57a", "size": 6357, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/GeometricShapes/quadrilateralMeshedSurfaceGeometry.cpp", "max_stars_repo_name": "JPelamatti/ThesisTUDAT", "max_stars_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Mathematics/GeometricShapes/quadrilateralMeshedSurfaceGeometry.cpp", "max_issues_repo_name": "JPelamatti/ThesisTUDAT", "max_issues_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Mathematics/GeometricShapes/quadrilateralMeshedSurfaceGeometry.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": 39.9811320755, "max_line_length": 99, "alphanum_fraction": 0.6274972471, "num_tokens": 1445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.284249300964024}}
{"text": "/* ========================================================================= */\n/* === umf4 ================================================================ */\n/* ========================================================================= */\n\n/* ------------------------------------------------------------------------- */\n/* UMFPACK Version 4.1 (Apr. 30, 2003), Copyright (c) 2003 by Timothy A.     */\n/* Davis.  All Rights Reserved.  See ../README for License.                  */\n/* email: davis@cise.ufl.edu    CISE Department, Univ. of Florida.           */\n/* web: http://www.cise.ufl.edu/research/sparse/umfpack                      */\n/* ------------------------------------------------------------------------- */\n\n\n/***********************************************************************/\n/*         UMFPACK Copyright, License and Availability                 */\n/***********************************************************************/\n/*\n *\n * UMFPACK Version 4.1 (Apr. 30, 2003),  Copyright (c) 2003 by Timothy A.\n * Davis.  All Rights Reserved.\n *\n * UMFPACK License:\n *\n *   Your use or distribution of UMFPACK or any modified version of\n *   UMFPACK implies that you agree to this License.\n *\n *   THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY\n *   EXPRESSED OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.\n *\n *   Permission is hereby granted to use or copy this program, provided\n *   that the Copyright, this License, and the Availability of the original\n *   version is retained on all copies.  User documentation of any code that\n *   uses UMFPACK or any modified version of UMFPACK code must cite the\n *   Copyright, this License, the Availability note, and \"Used by permission.\"\n *   Permission to modify the code and to distribute modified code is granted,\n *   provided the Copyright, this License, and the Availability note are\n *   retained, and a notice that the code was modified is included.  This\n *   software was developed with support from the National Science Foundation,\n *   and is provided to you free of charge.\n *\n * Availability:\n *\n *   http://www.cise.ufl.edu/research/sparse/umfpack\n *\n */\n\n/* Used by permission. */ \n\n\n/* modified by Kresimir Fresl, 2003              */\n\n/* UMFPACK bindings \n * ublas::compressed_matrix<> or ublas::coordinate_matrix<>\n * ... to use coordinate_matrix<> define COORDINATE\n */\n\n\n/* Demo program for UMFPACK v4.1.  \n *\n * Reads in a triplet-form matrix and right-hand side vector. \n * Input file format:\n *   num_rows_of_A  num_cols_of_A\n *   num_nonzeros_in_A\n *   row col val\n *   row col val\n *   ...\n *   num_nonzeros_in_B\n *   idx val\n *   ...\n *\n * Then calls UMFPACK to analyze, factor, and solve the system.\n *\n * Syntax:\n *\n *\tumf4\t\tdefault \"auto\" strategy, 1-norm row scaling\n *\tumf4 a\t\tdefault \"auto\" strategy, 1-norm row scaling\n *\tumf4 u\t\tunsymmetric strategy, 1-norm row scaling\n *\tumf4 s\t\tsymmetric strategy, 1-norm row scaling\n *\tumf4 2\t\t2-by-2 strategy, maxnorm row scaling\n *\tumf4 A\t\tdefault \"auto\" strategy, maxnorm row scaling\n *\tumf4 U\t\tunsymmetric strategy, maxnorm row scaling\n *\tumf4 S\t\tsymmetric strategy, maxnorm row scaling\n *\tumf4 T\t\t2-by-2 strategy , maxnorm row scaling\n *      umf4 ?n         ? can be in [aus2AUST], n: no aggressive absorption \n */\n\n\n#include <iostream>\n#include <fstream> \n#include <cstdlib>\n#include <string> \n#include <algorithm> \n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector.hpp>\n#include <boost/numeric/bindings/traits/ublas_sparse.hpp>\n#include <boost/numeric/bindings/umfpack/umfpack.hpp>\n\nusing std::max;\nusing std::cout;\nusing std::cin;\nusing std::endl; \nusing std::string; \nusing std::ifstream;\nusing std::ofstream;\nusing std::exit;\n\nnamespace ublas = boost::numeric::ublas; \nnamespace umf = boost::numeric::bindings::umfpack; \nnamespace traits = boost::numeric::bindings::traits; \n\n#ifndef COORDINATE\ntypedef ublas::compressed_matrix<double, ublas::column_major, 0,\n  ublas::unbounded_array<int>, ublas::unbounded_array<double> > cm_t; \n#else\ntypedef ublas::coordinate_matrix<double, ublas::column_major, 0,\n  ublas::unbounded_array<int>, ublas::unbounded_array<double> > cm_t; \n#endif \ntypedef ublas::vector<double> v_t; \n\n\n// wait for 'y'  \n\nvoid wait4y() {\n  char yes = 'n'; \n  while (1) {\n    cout << \"Continue (y/n) -> \"; \n    cin >> yes; \n    if (yes == 'y') break;\n    if (yes == 'n') exit (0);\n  }\n} \n\n// resid: compute the relative residual, ||Ax-b||/||b|| \n\ntemplate <typename M, typename V> \ndouble resid (M const& m, V const& x, V const& b, V& r) {\n\n  int const* Ap = traits::spmatrix_index1_storage (m);\n  int const* Ai = traits::spmatrix_index2_storage (m);\n  double const* Ax = traits::spmatrix_value_storage (m);\n\n  double rnorm, bnorm, absr, absb;\n\n  int n = traits::vector_size (r); \n\n  r = prod (m, x); \n\n#if 0\n  if (transpose) {\n    int i; \n    for (int j = 0; j < n; j++) \n      for (int p = Ap [j]; p < Ap [j+1]; p++) {\n        i = Ai [p];\n        r [j] += Ax [p] * x [i];\n      }\n  } else {\n    int i; \n    for (int j = 0; j < n; j++)\n      for (int p = Ap [j]; p < Ap [j+1]; p++) {\n        i = Ai [p];\n        r [i] += Ax [p] * x [j];\n      }\n  }\n#endif \n\n  \n\n  for (int i = 0; i < n; i++)\n    r [i] -= b [i];\n\n  rnorm = 0.;\n  bnorm = 0.;\n  for (int i = 0; i < n; i++) {\n    if ((boost::math::isnan) (r [i])){\n      rnorm = r [i];\n      break;\n    }\n    absr = fabs (r [i]);\n    rnorm = max (rnorm, absr);\n  }\n  for (int i = 0; i < n; i++) {\n    if ((boost::math::isnan) (b [i])){\n      bnorm = b [i];\n      break;\n    }\n    absb = fabs (b [i]);\n    bnorm = max (bnorm, absb);\n  }\n  if (bnorm == 0)\n    bnorm = 1;\n  return (rnorm / bnorm);\n}\n\n\n////////////////////////////////////////////////////////////////\n// main program                                                       \n\nint main (int argc, char **argv) {\n\n  cout << \"\\n===========================================================\\n\"\n       << \"=== UMFPACK v4.1 ==========================================\\n\"\n       << \"===========================================================\\n\"\n       << endl; \n\n  // set controls                                                      \n\n  umf::control_type<> Control; \n  Control [UMFPACK_PRL] = 3;\n  Control [UMFPACK_BLOCK_SIZE] = 32;\n\n  if (argc > 1) {\n    char *s = argv [1];\n    // get the strategy \n    if (s [0] == 'u') \n      Control [UMFPACK_STRATEGY] = UMFPACK_STRATEGY_UNSYMMETRIC;\n    else if (s [0] == 'a')\n      Control [UMFPACK_STRATEGY] = UMFPACK_STRATEGY_AUTO;\n    else if (s [0] == 's')\n      Control [UMFPACK_STRATEGY] = UMFPACK_STRATEGY_SYMMETRIC;\n    else if (s [0] == '2')\n      Control [UMFPACK_STRATEGY] = UMFPACK_STRATEGY_2BY2;\n    else if (s [0] == 'U') {\n      Control [UMFPACK_STRATEGY] = UMFPACK_STRATEGY_UNSYMMETRIC;\n      Control [UMFPACK_SCALE] = UMFPACK_SCALE_MAX;\n    }\n    else if (s [0] == 'A') {\n      Control [UMFPACK_STRATEGY] = UMFPACK_STRATEGY_AUTO;\n      Control [UMFPACK_SCALE] = UMFPACK_SCALE_MAX;\n    }\n    else if (s [0] == 'S') {\n      Control [UMFPACK_STRATEGY] = UMFPACK_STRATEGY_SYMMETRIC;\n      Control [UMFPACK_SCALE] = UMFPACK_SCALE_MAX;\n    }\n    else if (s [0] == 'T') {\n      Control [UMFPACK_STRATEGY] = UMFPACK_STRATEGY_2BY2;\n      Control [UMFPACK_SCALE] = UMFPACK_SCALE_MAX;\n    }\n    else\n      printf (\"unrecognized strategy: %s\\n\", argv [1]);\n\n    if (s [1] == 'n')\n      // no aggressive absorption \n      Control [UMFPACK_AGGRESSIVE] = 0;\n  }\n  bool call_wait4y = true;\n  string ifs_name; \n  if (argc > 2) {\n    call_wait4y = false;\n    ifs_name = argv [2];\n  }\n\n  umf::report_control (Control);\n\n  // open the matrix file \n  if (ifs_name.empty()) {\n    cout << \"input file -> \";\n    cin >> ifs_name; \n  }\n  ifstream f (ifs_name.c_str()); \n  if (!f) {\n    cout << \"unable to open file\" << endl; \n    exit (1);\n  }\n\n  // initialize matrix A \n  cout << \"reading A\" << endl; \n  int nrow, ncol, nz; \n  f >> nrow >> ncol >> nz; \n  cm_t A (nrow, ncol, nz); \n  int r, c;\n  for (int i = 0; i < nz; ++i) {\n    f >> r >> c;\n    double val;\n    f >> val;\n    A (r, c) = val;\n  }\n  Control[UMFPACK_PRL] = (nz > 20) ? 4 : 5; \n  cout << \"matrix A: \"; \n  umf::report_matrix (A, Control);\n\n  if (call_wait4y) wait4y(); \n\n  // symbolic factorization \n  umf::info_type<> Info; \n  umf::symbolic_type<> Symbolic; \n\n  int status = umf::symbolic (A, Symbolic, Control, Info);\n\n  cout << \"symbolic status:\" << endl; \n  umf::report_status (Control, status);\n  if (status != UMFPACK_OK) {\n    umf::report_info (Control, Info);\n    cout << \"umf::symbolic failed\" << endl; \n    exit (1);\n  }\n  umf::report_symbolic (Symbolic, Control);\n\n  if (call_wait4y) wait4y(); \n\n  // numeric factorization \n  umf::numeric_type<> Numeric; \n\n  status = umf::numeric (A, Symbolic, Numeric, Control, Info);\n\n  cout << \"numeric status:\" << endl; \n  umf::report_status (Control, status);\n  if (status < UMFPACK_OK) {\n    umf::report_info (Control, Info);\n    cout << \"umf::numeric failed\" << endl; \n    exit (1);\n  }\n  umf::report_numeric (Numeric, Control);\n\n  if (call_wait4y) wait4y(); \n\n  // solve Ax=b \n  if (nrow == ncol && status == UMFPACK_OK) {\n    \n    // create right-hand side vector B \n    v_t B (ncol), X (ncol), R (ncol); \n    cout << \"reading B\" << endl; \n    int m2, ii; \n    f >> m2; \n    for (int i = 0; i < m2; ++i) {\n      f >> ii; \n      f >> B[ii];\n    }\n    cout << \"vector B: \"; \n    umf::report_vector (B, Control); \n\n    status = umf::solve (A, X, B, Numeric, Control, Info);\n\n    cout << \"solve status:\" << endl; \n    umf::report_status (Control, status);\n    umf::report_info (Control, Info);\n    if (status < UMFPACK_OK) {\n      cout << \"umf::solve failed\" << endl;\n      exit (1);\n    }\n    cout << \"solution vector X: \"; \n    umf::report_vector (X, Control);\n\n    cout << \"relative maxnorm of residual, ||Ax-b||/||b||: \"\n\t << resid (A, X, B, R) << endl; \n\n  } else {\n\n    cout << \"system not solved\" << endl; \n    umf::report_info (Control, Info);\n\n  }\n\n  cout << endl; \n\n}\n", "meta": {"hexsha": "9eda8c4d9912bdd560b7ef181780777c5c7bce98", "size": 9950, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/umfpack/test/umf4.cc", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/umfpack/test/umf4.cc", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/umfpack/test/umf4.cc", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0281690141, "max_line_length": 79, "alphanum_fraction": 0.5475376884, "num_tokens": 2942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.28424930096402395}}
{"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#ifndef STATE_ESTIMATION__NOISE_MODEL__UNIFORM_NOISE_HPP_\n#define STATE_ESTIMATION__NOISE_MODEL__UNIFORM_NOISE_HPP_\n\n#include <state_estimation/noise_model/noise_interface.hpp>\n#include <state_estimation/visibility_control.hpp>\n\n#include <Eigen/Core>\n\n#include <algorithm>\n#include <array>\n#include <chrono>\n#include <type_traits>\n#include <vector>\n\nnamespace autoware\n{\nnamespace common\n{\nnamespace state_estimation\n{\n\n///\n/// @brief      This class contains the logic for a uniform noise model.\n///\n/// @tparam     StateT  State vector type for which this noise model is created.\n///\ntemplate<typename StateT>\nclass STATE_ESTIMATION_PUBLIC UniformNoise : public NoiseInterface<UniformNoise<StateT>>\n{\n  using Scalar = typename StateT::Scalar;\n  using Matrix = typename StateT::Matrix;\n  template<typename OtherScalarT>\n  using VarianceVector = Eigen::Matrix<OtherScalarT, StateT::size(), 1>;\n\npublic:\n  /// A convenience typedef for the state for which this noise model is to be used.\n  using State = StateT;\n\n  ///\n  /// @brief      Create the noise model from an existing covariance matrix.\n  ///\n  /// @param[in]  covariance  The covariance\n  ///\n  explicit UniformNoise(const Matrix & covariance) noexcept\n  : m_covariance{covariance} {}\n\n  ///\n  /// @brief      Create the noise model from an array\n  ///\n  /// @param[in]  variances     The values for variances, i.e., values for σ (not squared)\n  ///\n  /// @tparam     OtherScalarT  Some scalar type.\n  ///\n  template<typename OtherScalarT>\n  explicit UniformNoise(\n    const std::array<OtherScalarT, State::size()> & variances) noexcept\n  : m_covariance{\n      Eigen::Map<const VarianceVector<OtherScalarT>>(variances.data())\n      .template cast<Scalar>().array().square().matrix().asDiagonal()} {}\n\n  ///\n  /// @brief      Create the noise model from a vector\n  ///\n  /// @param[in]  variances     The values for variances, i.e., values for σ (not squared)\n  ///\n  /// @throws     std::runtime_error  if the vector is of a wrong size.\n  ///\n  /// @tparam     OtherScalarT  Some scalar type.\n  ///\n  template<typename OtherScalarT>\n  explicit UniformNoise(const std::vector<OtherScalarT> & variances)\n  {\n    if (variances.size() != static_cast<std::size_t>(State::size())) {\n      throw std::runtime_error(\n              \"There must be \" + std::to_string(State::size()) +\n              \" variances for initializing the uniform noise model, but \" +\n              std::to_string(variances.size()) + \" provided\");\n    }\n    m_covariance =\n      Eigen::Map<const VarianceVector<OtherScalarT>>(variances.data())\n      .template cast<Scalar>().array().square().matrix().asDiagonal();\n  }\n\n\n  ///\n  /// @brief      Create noise model from variances directly.\n  ///\n  /// @param[in]  variance    The first variance, i.e., value for σ (not squared)\n  /// @param[in]  variances   The variances for all the other variables\n  ///\n  /// @tparam     VarianceTs  Types for other variances.\n  ///\n  template<typename ... VarianceTs>\n  explicit UniformNoise(const Scalar variance, const VarianceTs ... variances)\n  : UniformNoise{std::array<Scalar, State::size()> {variance, variances ...}}\n  {\n    static_assert(\n      sizeof...(VarianceTs) + 1 == State::size(),\n      \"Wrong number of variances passed into the UniformNoise constructor\");\n  }\n\nprotected:\n  /// Allow the interface to access the protected and private members to visually encapsulate the\n  /// implementation.\n  friend NoiseInterface<UniformNoise<StateT>>;\n\n  ///\n  /// @brief      A CRTP-called covariance getter.\n  ///\n  /// @return     A covariance of the noise process over a given time span.\n  ///\n  Matrix crtp_covariance(const std::chrono::nanoseconds & dt) const noexcept\n  {\n    return m_covariance * std::chrono::duration_cast<std::chrono::duration<Scalar>>(dt).count();\n  }\n\nprivate:\n  /// Store the covariance matrix internally.\n  Matrix m_covariance{};\n};\n\n}  // namespace state_estimation\n}  // namespace common\n}  // namespace autoware\n\n#endif  // STATE_ESTIMATION__NOISE_MODEL__UNIFORM_NOISE_HPP_\n", "meta": {"hexsha": "d0945cfa77d5a990a99fb208f1ac999811400c55", "size": 4669, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/common/state_estimation/include/state_estimation/noise_model/uniform_noise.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/include/state_estimation/noise_model/uniform_noise.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/include/state_estimation/noise_model/uniform_noise.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": 32.6503496503, "max_line_length": 97, "alphanum_fraction": 0.6928678518, "num_tokens": 1118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.2842493009640239}}
{"text": "#include <vector>\n\n#include <boost/shared_ptr.hpp>\n#include <gflags/gflags.h>\n#include <glog/logging.h>\n\n#include <cmath>\n#include <fstream>\n\n#include \"caffe/blob.hpp\"\n#include \"caffe/common.hpp\"\n#include \"caffe/ultinous/projective_matrix_layer.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n\nnamespace caffe\n{\nnamespace ultinous\n{\n\ntemplate<typename Dtype>\nvoid ProjectiveMatrixLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype> *> &bottom,\n                                              const vector<Blob<Dtype> *> &top)\n{\n\n  CHECK(bottom[0]->channels() == 9);\n\n  m_base_scale = this->layer_param_.proj_matrix_param().base_scale();\n  m_base_f = this->layer_param_.proj_matrix_param().base_f();\n  m_base_tz = this->layer_param_.proj_matrix_param().base_tz();\n\n  m_min_scale = this->layer_param_.proj_matrix_param().min_scale();\n  m_max_scale = this->layer_param_.proj_matrix_param().max_scale();\n  m_min_f = this->layer_param_.proj_matrix_param().min_f();\n  m_max_f = this->layer_param_.proj_matrix_param().max_f();\n  m_min_alpha = this->layer_param_.proj_matrix_param().min_alpha();\n  m_max_alpha = this->layer_param_.proj_matrix_param().max_alpha();\n  m_min_beta = this->layer_param_.proj_matrix_param().min_beta();\n  m_max_beta = this->layer_param_.proj_matrix_param().max_beta();\n  m_min_gamma = this->layer_param_.proj_matrix_param().min_gamma();\n  m_max_gamma = this->layer_param_.proj_matrix_param().max_gamma();\n\n  m_min_tx = this->layer_param_.proj_matrix_param().min_tx();\n  m_max_tx = this->layer_param_.proj_matrix_param().max_tx();\n  m_min_ty = this->layer_param_.proj_matrix_param().min_ty();\n  m_max_ty = this->layer_param_.proj_matrix_param().max_ty();\n  m_min_tz = this->layer_param_.proj_matrix_param().min_tz();\n  m_max_tz = this->layer_param_.proj_matrix_param().max_tz();\n\n  m_bias_scale = this->layer_param_.proj_matrix_param().bias_scale();\n  m_bias_U = this->layer_param_.proj_matrix_param().bias_u();\n\n  m_max_diff = this->layer_param_.proj_matrix_param().max_diff();\n  m_boundary_violation_step = 0.1;\n  m_iter = 0;\n\n  if (this->blobs_.size() > 0)\n  {\n    LOG(INFO) << \"Skipping parameter initialization\";\n  }\n  else\n  {\n    this->blobs_.resize(1);\n    vector<int> sz;\n    sz.push_back(bottom[0]->channels());\n\n    this->blobs_[0].reset(new Blob<Dtype>(sz));\n    caffe_set(this->blobs_[0]->count(), Dtype(0),\n              this->blobs_[0]->mutable_cpu_data());\n  }\n\n  std::vector<int> top_shape(2);\n  top_shape[0] = bottom[0]->num();\n  top_shape[1] = 9;\n  top[0]->Reshape(top_shape);\n}\n\ntemplate<typename Dtype>\nvoid ProjectiveMatrixLayer<Dtype>::Reshape(const vector<Blob<Dtype> *> &bottom,\n                                           const vector<Blob<Dtype> *> &top)\n{\n  std::vector<int> top_shape(2);\n  top_shape[0] = bottom[0]->num();\n  top_shape[1] = 9;\n  top[0]->Reshape(top_shape);\n}\n\ntemplate<typename Dtype>\nvoid ProjectiveMatrixLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype> *> &bottom,\n                                               const vector<Blob<Dtype> *> &top)\n{\n  ++m_iter;\n  if (this->phase_ == TRAIN && (m_iter % 100) == 0)\n  {\n    Dtype const *bias = this->blobs_[0]->cpu_data();\n    std::cout << \"Bias:\";\n    for (int c = 0; c < 9; ++c)\n      std::cout << \" \" << bias[c];\n    std::cout << std::endl;\n  }\n\n/**\n  Original matrix:\n  H = [ cos(gamma)*cos(beta)*S*f  (-sin(gamma)*cos(alpha)+cos(gamma)*sin(beta)*sin(alpha))*S*f  U*f;\n      sin(gamma)*cos(beta)*S*f  (cos(gamma)*cos(alpha)+sin(gamma)*sin(beta)*sin(alpha))*S*f   V*f;\n    -sin(beta)*S             cos(beta)*sin(alpha)*S                                     W+f];\n*/\n\n/** Non-uniform scaling:\n  Original matrix:\n  H = [ cos(gamma)*cos(beta)*Sx*f  (-sin(gamma)*cos(alpha)+cos(gamma)*sin(beta)*sin(alpha))*Sx*f  U*f*Sx;\n      sin(gamma)*cos(beta)*Sy*f  (cos(gamma)*cos(alpha)+sin(gamma)*sin(beta)*sin(alpha))*Sy*f   V*f*Sy;\n    -sin(beta)             cos(beta)*sin(alpha)                                     W+f];\n*/\n\n\n  for (int n = 0; n < bottom[0]->num(); ++n)\n  {\n    Dtype const *bottom_data = bottom[0]->cpu_data() + 9 * n;\n\n    Dtype Sx = m_base_scale + bottom_data[0];\n    Dtype Sy = m_base_scale + bottom_data[1];\n    Dtype f = m_base_f + bottom_data[2];\n    Dtype alpha = bottom_data[3];\n    Dtype beta = bottom_data[4];\n    Dtype gamma = bottom_data[5];\n    Dtype U = bottom_data[6];\n    Dtype V = bottom_data[7];\n    Dtype W = m_base_tz + bottom_data[8];\n\n    Dtype const *bias = this->blobs_[0]->cpu_data();\n    if (m_bias_scale)\n    {\n      Sx += bias[0];\n      Sy += bias[1];\n    }\n    if (m_bias_U)\n    {\n      U += bias[6];\n    }\n\n\n\n    Dtype *top_data = top[0]->mutable_cpu_data() + 9 * n;\n    top_data[0] = cos(gamma)*cos(beta)*Sx*f;\n    top_data[1] = (-sin(gamma)*cos(alpha)+cos(gamma)*sin(beta)*sin(alpha))*Sx*f;\n    top_data[2] = U*f*Sx;\n\n    top_data[3] = sin(gamma)*cos(beta)*Sy*f;\n    top_data[4] = (cos(gamma)*cos(alpha)+sin(gamma)*sin(beta)*sin(alpha))*Sy*f;\n    top_data[5] = V*f*Sy;\n\n    top_data[6] = -sin(beta);\n    top_data[7] = cos(beta)*sin(alpha);\n    top_data[8] = W+f;\n  }\n\n}\n\ntemplate<typename Dtype>\nvoid ProjectiveMatrixLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype> *> &top,\n                                                const vector<bool> &propagate_down,\n                                                const vector<Blob<Dtype> *> &bottom)\n{\n\n  if (!propagate_down[0]) return;\n\n\n  for (int n = 0; n < bottom[0]->num(); ++n)\n  {\n    Dtype const *bottom_data = bottom[0]->cpu_data() + 9 * n;\n\n    Dtype Sx = m_base_scale + bottom_data[0];\n    Dtype Sy = m_base_scale + bottom_data[1];\n    Dtype f = m_base_f + bottom_data[2];\n    Dtype alpha = bottom_data[3];\n    Dtype beta = bottom_data[4];\n    Dtype gamma = bottom_data[5];\n    Dtype U = bottom_data[6];\n    Dtype V = bottom_data[7];\n    Dtype W = m_base_tz + bottom_data[8];\n\n    Dtype const *bias = this->blobs_[0]->cpu_data();\n    if (m_bias_scale)\n    {\n      Sx += bias[0];\n      Sy += bias[1];\n    }\n    if (m_bias_U)\n    {\n      U += bias[6];\n    }\n\n    Dtype *bottom_diff = bottom[0]->mutable_cpu_diff() + 9 * n;\n    Dtype const *top_diff = top[0]->cpu_diff() + 9 * n;\n\n\n    if (Sx < m_min_scale)\n      bottom_diff[0] = (Sx - m_min_scale) * m_boundary_violation_step;\n    else if (Sx > m_max_scale)\n      bottom_diff[0] = (Sx - m_max_scale) * m_boundary_violation_step;\n    else\n      bottom_diff[0] = top_diff[0] * (cos(gamma)*cos(beta)*f)\n                       +top_diff[1] * ( (-sin(gamma)*cos(alpha)+cos(gamma)*sin(beta)*sin(alpha))*f)\n                      + top_diff[2] * U*f;\n\n\n    if (Sy < m_min_scale)\n      bottom_diff[1] = (Sy - m_min_scale) * m_boundary_violation_step;\n    else if (Sy > m_max_scale)\n      bottom_diff[1] = (Sy - m_max_scale) * m_boundary_violation_step;\n    else\n      bottom_diff[1] = top_diff[3] * ( sin(gamma)*cos(beta)*f )\n                       +top_diff[4] * (  (cos(gamma)*cos(alpha)+sin(gamma)*sin(beta)*sin(alpha))*f )\n                      + top_diff[5] * V*f;\n\n\n\n    if (f < m_min_f)\n      bottom_diff[2] = (f - m_min_f) * m_boundary_violation_step;\n    else if (f > m_max_f)\n      bottom_diff[2] = (f - m_max_f) * m_boundary_violation_step;\n    else\n      bottom_diff[2] =  top_diff[0] * (cos(gamma)*cos(beta)*Sx)\n                        +top_diff[1] * ( (-sin(gamma)*cos(alpha)+cos(gamma)*sin(beta)*sin(alpha))*Sx)\n                         +top_diff[2] * ( U * Sx )\n                        +top_diff[3] * ( sin(gamma)*cos(beta)*Sy )\n                        +top_diff[4] * (  (cos(gamma)*cos(alpha)+sin(gamma)*sin(beta)*sin(alpha))*Sy )\n                        +top_diff[5] * ( V * Sy)\n                        +top_diff[8] * ( 1 );\n\n\n\n    if (alpha < m_min_alpha)\n      bottom_diff[3] = (alpha - m_min_alpha) * m_boundary_violation_step;\n    else if (alpha > m_max_alpha)\n      bottom_diff[3] = (alpha - m_max_alpha) * m_boundary_violation_step;\n    else\n      bottom_diff[3] = top_diff[1] * ( (-sin(gamma)*-sin(alpha)+cos(gamma)*sin(beta)*cos(alpha))*Sx*f )\n                      + top_diff[4] * ((cos(gamma)*-sin(alpha)+sin(gamma)*sin(beta)*cos(alpha))*Sy*f)\n                      + top_diff[7] * (cos(beta)*cos(alpha));\n\n\n    if (beta < m_min_beta)\n      bottom_diff[4] = (beta - m_min_beta) * m_boundary_violation_step;\n    else if (beta > m_max_beta)\n      bottom_diff[4] = (beta - m_max_beta) * m_boundary_violation_step;\n    else\n      bottom_diff[4] = top_diff[0] * (cos(gamma)*-sin(beta)*Sx*f)\n                  + top_diff[1] * ( (-sin(gamma)*cos(alpha)+cos(gamma)*cos(beta)*sin(alpha))*Sx*f)\n              + top_diff[3] * (sin(gamma)*-sin(beta)*Sy*f)\n            + top_diff[4] * ( (cos(gamma)*cos(alpha)+sin(gamma)*cos(beta)*sin(alpha))*Sy*f)\n            + top_diff[6] * (-cos(beta))\n            + top_diff[7] * (-sin(beta)*sin(alpha));\n\n    if (gamma < m_min_gamma)\n      bottom_diff[5] = (gamma - m_min_gamma) * m_boundary_violation_step;\n    else if (gamma > m_max_gamma)\n      bottom_diff[5] = (gamma - m_max_gamma) * m_boundary_violation_step;\n    else\n      bottom_diff[5] = top_diff[0] * (-sin(gamma)*cos(beta)*Sx*f)\n              + top_diff[1] * ((-cos(gamma)*cos(alpha)+-sin(gamma)*sin(beta)*sin(alpha))*Sx*f)\n                + top_diff[3] * (cos(gamma)*cos(beta)*Sy*f)\n                  + top_diff[4] * ((-sin(gamma)*cos(alpha)+cos(gamma)*sin(beta)*sin(alpha))*Sy*f);\n\n    if (U < m_min_tx)\n      bottom_diff[6] = (U - m_min_tx) * m_boundary_violation_step;\n    else if (U > m_max_tx)\n      bottom_diff[6] = (U - m_max_tx) * m_boundary_violation_step;\n    else\n      bottom_diff[6] = top_diff[2]*f*Sx;\n\n    if (V < m_min_ty)\n      bottom_diff[7] = (V - m_min_ty) * m_boundary_violation_step;\n    else if (V > m_max_ty)\n      bottom_diff[7] = (V - m_max_ty) * m_boundary_violation_step;\n    else\n      bottom_diff[7] = top_diff[5]*f*Sy;\n\n    if (W < m_min_tz)\n      bottom_diff[8] = (W - m_min_tz) * m_boundary_violation_step;\n    else if (W > m_max_tz)\n      bottom_diff[8] = (W - m_max_tz) * m_boundary_violation_step;\n    else\n      bottom_diff[8] = top_diff[8] * (1);\n\n\n\n\n    if (m_max_diff != 0)\n      for (int i = 0; i < 9; i++)\n        bottom_diff[i] = std::max(-m_max_diff, std::min(m_max_diff, bottom_diff[i]));\n\n    // Bias - only on specific params\n    Dtype *bias_diff = this->blobs_[0]->mutable_cpu_diff();\n    if (m_bias_scale)\n    {\n      bias_diff[0] += bottom_diff[0]; // scaleX\n      bias_diff[1] += bottom_diff[1]; // scaleY\n    }\n    if (m_bias_U)\n    {\n      bias_diff[6] += bottom_diff[6]; // // U\n    }\n\n\n  }\n}\n\n#ifdef CPU_ONLY\n//STUB_GPU(ProjectiveMatrixLayer);\n#endif\n\nINSTANTIATE_CLASS(ProjectiveMatrixLayer);\n\nREGISTER_LAYER_CLASS(ProjectiveMatrix);\n\n}  // namespace ultinous\n}  // namespace caffe\n", "meta": {"hexsha": "36d0546efd2e7c310c6f7bb201f3ecb517fb549b", "size": 10602, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/ultinous/projective_matrix_layer.cpp", "max_stars_repo_name": "Ultinous/caffe", "max_stars_repo_head_hexsha": "6b26a5889f6ea9681c4981daafe55d7530cf53ca", "max_stars_repo_licenses": ["Intel", "BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-05T15:54:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-05T15:54:16.000Z", "max_issues_repo_path": "src/caffe/ultinous/projective_matrix_layer.cpp", "max_issues_repo_name": "Ultinous/caffe", "max_issues_repo_head_hexsha": "6b26a5889f6ea9681c4981daafe55d7530cf53ca", "max_issues_repo_licenses": ["Intel", "BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-25T12:58:01.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-25T12:58:01.000Z", "max_forks_repo_path": "src/caffe/ultinous/projective_matrix_layer.cpp", "max_forks_repo_name": "Ultinous/caffe", "max_forks_repo_head_hexsha": "6b26a5889f6ea9681c4981daafe55d7530cf53ca", "max_forks_repo_licenses": ["Intel", "BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2351097179, "max_line_length": 105, "alphanum_fraction": 0.5963969062, "num_tokens": 3199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.2842363671782048}}
{"text": "//****************************************************************************\n// (c) 2008, 2009 by the openOR Team\n//****************************************************************************\n// The contents of this file are available under the GPL v2.0 license\n// or under the openOR comercial license. see\n//   /Doc/openOR_free_license.txt or\n//   /Doc/openOR_comercial_license.txt\n// for Details.\n//****************************************************************************\n//! OPENOR_INTERFACE_FILE(openOR_core)\n//****************************************************************************\n//!\n//! @file\n//! @ingroup openOR_core\n\n#ifndef openOR_core_Math_ublasvector_hpp\n#define openOR_core_Math_ublasvector_hpp\n\n#if defined(_MSC_VER)\n#  pragma warning(disable:4172)\n#endif\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#if defined(_MSC_VER)\n#  pragma warning(default:4172)\n#endif \n\n#include <openOR/Math/traits.hpp>\n#include <openOR/Math/vectorconcept.hpp>\n#include <openOR/Math/vector_types.hpp>\n\n\nnamespace openOR {\n   namespace Math {\n\n      //----------------------------------------------------------------------------\n      // Adapting the corresponding traits\n      //---------------------------------------------------------------------------- \n      \n      template<typename VectorType>\n      struct UBLASVectorAccess {\n         typedef typename VectorType::reference AccessType;\n         typedef typename VectorType::const_reference ConstAccessType;\n\n         template <int I, typename PP> static \n            typename if_const<PP, ConstAccessType, AccessType>::\n         type get(PP& p) {\n            assert(I < p.size());\n            return p(I);\n         }\n      };\n\n      template<typename Value, std::size_t d>\n      struct VectorTraits<boost::numeric::ublas::bounded_vector<Value, d> > {\n         typedef boost::numeric::ublas::bounded_vector<Value, d> VectorType;\n         typedef boost::numeric::ublas::bounded_vector<typename ScalarTraits<Value>::RealType, d>  RealVectorType;\n         typedef Value ValueType;\n         typedef boost::numeric::ublas::bounded_vector<Value, 3> Vector3Type;\n         typedef boost::numeric::ublas::bounded_vector<Value, 2> Vector2Type;\n         typedef boost::mpl::int_<d> Dimension;\n         typedef UBLASVectorAccess<VectorType> Access;\n         typedef boost::mpl::true_ IsVector;\n\n         static VectorType ZEROS;\n      };\n\n\n      template<typename Value, std::size_t d>\n      typename VectorTraits< boost::numeric::ublas::bounded_vector<Value, d> >::VectorType\n      VectorTraits< boost::numeric::ublas::bounded_vector<Value, d> >::ZEROS = boost::numeric::ublas::zero_vector<Value>(d);\n\n\n      template<typename E>\n      struct UBLASVectorExpressionTraits {\n         typedef E VectorType;\n         typedef typename E::value_type ValueType;\n         typedef boost::numeric::ublas::bounded_vector<typename E::value_type, 3> Vector3Type;\n         typedef boost::numeric::ublas::bounded_vector<typename E::value_type, 2> Vector2Type;\n         typedef boost::mpl::int_<0> Dimension;\n         typedef UBLASVectorAccess<E> Access;\n         typedef boost::mpl::true_ IsVector;\n      };\n\n      template<class E>\n      struct VectorTraits<boost::numeric::ublas::vector_expression<E> > : VectorTraits<E> {};\n\n      template<class C>\n      struct VectorTraits<boost::numeric::ublas::vector_container<C> > : UBLASVectorExpressionTraits<boost::numeric::ublas::vector_container<C> > {};\n\n      template<class T, class A>\n      struct VectorTraits<boost::numeric::ublas::vector<T, A> > : UBLASVectorExpressionTraits<boost::numeric::ublas::vector<T, A> > {};\n\n      template<class E>\n      struct VectorTraits<boost::numeric::ublas::vector_reference<E> > : UBLASVectorExpressionTraits<boost::numeric::ublas::vector_reference<E> > {};\n\n      template<typename E, typename F>\n      struct VectorTraits<boost::numeric::ublas::vector_unary<E, F> > : UBLASVectorExpressionTraits<boost::numeric::ublas::vector_unary<E, F> > {};\n\n      template<typename E1, typename E2, typename F>\n      struct VectorTraits<boost::numeric::ublas::vector_binary<E1, E2, F> > : UBLASVectorExpressionTraits<boost::numeric::ublas::vector_binary<E1, E2, F> > {};\n\n      template<typename E1, typename E2, typename F>\n      struct VectorTraits<boost::numeric::ublas::vector_binary_scalar1<E1, E2, F> > : UBLASVectorExpressionTraits<boost::numeric::ublas::vector_binary_scalar1<E1, E2, F> > {};\n\n      template<typename E1, typename E2, typename F>\n      struct VectorTraits<boost::numeric::ublas::vector_binary_scalar2<E1, E2, F> > : UBLASVectorExpressionTraits<boost::numeric::ublas::vector_binary_scalar2<E1, E2, F> > {};\n\n\n      //----------------------------------------------------------------------------\n      //! @brief \n      //! @ingroup openOR_core\n      //---------------------------------------------------------------------------- \n      template <class E>\n         inline typename boost::numeric::ublas::vector_scalar_unary_traits<E, boost::numeric::ublas::vector_norm_2<E> >::\n      result_type norm(const boost::numeric::ublas::vector_expression<E>& e) {\n         return boost::numeric::ublas::norm_2(e);\n      }\n\n\n      //----------------------------------------------------------------------------\n      //! @brief \n      //! @ingroup openOR_core\n      //---------------------------------------------------------------------------- \n      template <class E1, class E2>\n         inline typename boost::numeric::ublas::vector_scalar_binary_traits < E1, E2, \n                  boost::numeric::ublas::vector_inner_prod < E1, E2,\n                  typename boost::numeric::ublas::promote_traits < typename E1::value_type,\n                  typename E2::value_type >::promote_type > >::\n      result_type dot(  const boost::numeric::ublas::vector_expression<E1> &e1,\n                        const boost::numeric::ublas::vector_expression<E2> &e2) \n      {\n         return boost::numeric::ublas::inner_prod(e1, e2);\n      }\n\n   }\n}\n\n//namespace boost {\n//   namespace numeric {\n//      namespace ublas {\n//\n//         template<class E1, class E2>\n//         BOOST_UBLAS_INLINE\n//            typename vector_scalar_binary_traits < E1, E2, vector_inner_prod < E1, E2,\n//                        typename promote_traits < typename E1::value_type,\n//                        typename E2::value_type >::promote_type > >::\n//         result_type operator% ( const vector_expression<E1> &e1,\n//                                 const vector_expression<E2> &e2) \n//         {\n//            typedef typename vector_scalar_binary_traits < E1, E2, vector_inner_prod < E1, E2,\n//                                 typename promote_traits < typename E1::value_type,\n//                                 typename E2::value_type >::promote_type > >::expression_type expression_type;\n//            return expression_type(e1(), e2());\n//         }\n//\n//      }\n//   }\n//}\n\n#endif\n", "meta": {"hexsha": "c6fd8779ab68558e384b04ec1a769fc2007b9a61", "size": 6926, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/include/openOR/Math/ublasvector.hpp", "max_stars_repo_name": "avinfinity/UnmanagedCodeSnippets", "max_stars_repo_head_hexsha": "2bd848db88d7b271209ad30017c8f62307319be3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/include/openOR/Math/ublasvector.hpp", "max_issues_repo_name": "avinfinity/UnmanagedCodeSnippets", "max_issues_repo_head_hexsha": "2bd848db88d7b271209ad30017c8f62307319be3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/include/openOR/Math/ublasvector.hpp", "max_forks_repo_name": "avinfinity/UnmanagedCodeSnippets", "max_forks_repo_head_hexsha": "2bd848db88d7b271209ad30017c8f62307319be3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.490797546, "max_line_length": 175, "alphanum_fraction": 0.5771007797, "num_tokens": 1526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.28421475809295166}}
{"text": "//\n// Created by Mamba on 2020/2/18.\n//\n// #define R_BUILD\n// #define TEST\n\n#ifdef R_BUILD\n#include <Rcpp.h>\n#include <RcppEigen.h>\nusing namespace Rcpp;\n// [[Rcpp::depends(RcppEigen)]]\n#else\n\n#include <Eigen/Eigen>\n#include \"List.h\"\n\n#endif\n\n#include <iostream>\n#include \"Data.h\"\n#include \"Algorithm.h\"\n#include \"Metric.h\"\n#include \"abess.h\"\n\nusing namespace Eigen;\nusing namespace std;\n\n// int sign(double a)\n// {\n//   if (a > 0)\n//   {\n//     return 1;\n//   }\n//   else if (a < 0)\n//   {\n//     return -1;\n//   }\n//   else\n//   {\n//     return 0;\n//   }\n// }\n\n// double det(double a[], double b[])\n// {\n//   return a[0] * b[1] - a[1] * b[0];\n// }\n\n// calculate the intersection of two lines\n// if parallal, need_flag = false.\n// void line_intersection(double line1[2][2], double line2[2][2], double intersection[], bool &need_flag)\n// {\n//   double xdiff[2], ydiff[2], d[2];\n//   double div;\n\n//   xdiff[0] = line1[0][0] - line1[1][0];\n//   xdiff[1] = line2[0][0] - line2[1][0];\n//   ydiff[0] = line1[0][1] - line1[1][1];\n//   ydiff[1] = line2[0][1] - line2[1][1];\n\n//   div = det(xdiff, ydiff);\n//   if (div == 0)\n//   {\n//     need_flag = false;\n//     return;\n//   }\n//   else\n//   {\n//     d[0] = det(line1[0], line1[1]);\n//     d[1] = det(line2[0], line2[1]);\n\n//     intersection[0] = det(d, xdiff) / div;\n//     intersection[1] = det(d, ydiff) / div;\n//     need_flag = true;\n//     return;\n//   }\n// }\n\n// // boundary: s=smin, s=max, lambda=lambda_min, lambda_max\n// // line: crosses p and is parallal to u\n// // calculate the intersections between boundary and line\n// void cal_intersections(double p[], double u[], int s_min, int s_max, double lambda_min, double lambda_max, double a[], double b[])\n// {\n//   double line0[2][2], line_set[4][2][2], intersections[4][2];\n//   bool need_flag[4];\n//   int i, j;\n\n//   line0[0][0] = double(p[0]);\n//   line0[0][1] = double(p[1]);\n//   line0[1][0] = double(p[0] + u[0]);\n//   line0[1][1] = double(p[1] + u[1]);\n\n//   line_set[0][0][0] = double(s_min);\n//   line_set[0][0][1] = double(lambda_min);\n//   line_set[0][1][0] = double(s_min);\n//   line_set[0][1][1] = double(lambda_max);\n\n//   line_set[1][0][0] = double(s_max);\n//   line_set[1][0][1] = double(lambda_min);\n//   line_set[1][1][0] = double(s_max);\n//   line_set[1][1][1] = double(lambda_max);\n\n//   line_set[2][0][0] = double(s_min);\n//   line_set[2][0][1] = double(lambda_min);\n//   line_set[2][1][0] = double(s_max);\n//   line_set[2][1][1] = double(lambda_min);\n\n//   line_set[3][0][0] = double(s_min);\n//   line_set[3][0][1] = double(lambda_max);\n//   line_set[3][1][0] = double(s_max);\n//   line_set[3][1][1] = double(lambda_max);\n\n//   for (i = 0; i < 4; i++)\n//   {\n//     line_intersection(line0, line_set[i], intersections[i], need_flag[i]);\n//   }\n\n//   // delete intersections beyond boundary\n//   for (i = 0; i < 4; i++)\n//   {\n//     if (need_flag[i])\n//     {\n//       if ((intersections[i][0] < s_min - 0.0001) | (intersections[i][0] > s_max + 0.0001) | (intersections[i][1] < lambda_min - 0.001) | (intersections[i][1] > lambda_max + 0.001))\n//       {\n//         need_flag[i] = false;\n//       }\n//     }\n//   }\n\n//   // delecte repetitive intersections\n//   for (i = 0; i < 4; i++)\n//   {\n//     if (need_flag[i])\n//     {\n//       for (j = i + 1; j < 4; j++)\n//       {\n//         if (need_flag[j])\n//         {\n//           if (abs(intersections[i][0] - intersections[j][0]) < 0.0001 && abs(intersections[i][1] - intersections[j][1]) < 0.0001)\n//           {\n//             need_flag[j] = false;\n//           }\n//         }\n//       }\n//     }\n//   }\n\n//   j = 0;\n//   for (i = 0; i < 4; i++)\n//   {\n//     if (need_flag[i])\n//     {\n//       if (j == 2)\n//       {\n//         j += 1;\n//       }\n//       if (j == 1)\n//       {\n//         b[0] = intersections[i][0];\n//         b[1] = intersections[i][1];\n//         j += 1;\n//       }\n//       if (j == 0)\n//       {\n//         a[0] = intersections[i][0];\n//         a[1] = intersections[i][1];\n//         j += 1;\n//       }\n//     }\n//   }\n\n//   if (j != 2)\n//   {\n// #ifdef R_BUILD\n//     Rcpp::Rcout << \"---------------------------\" << endl;\n//     Rcpp::Rcout << \"j: \" << j << endl;\n//     Rcpp::Rcout << \"inetrsection numbers wrong\" << j << endl;\n//     Rcpp::Rcout << \"p\" << p[0] << \",\" << p[1] << endl;\n//     Rcpp::Rcout << \"u\" << u[0] << \",\" << u[1] << endl;\n//     Rcpp::Rcout << \"s_min\" << s_min << endl;\n//     Rcpp::Rcout << \"s_max\" << s_max << endl;\n//     Rcpp::Rcout << \"lambda_min\" << lambda_min << endl;\n//     Rcpp::Rcout << \"lambda_max\" << lambda_max << endl;\n//     Rcpp::Rcout << \"intersections[0]\" << intersections[0][0] << \",\" << intersections[0][1] << endl;\n//     Rcpp::Rcout << \"intersections[1]\" << intersections[1][0] << \",\" << intersections[1][1] << endl;\n//     Rcpp::Rcout << \"intersections[2]\" << intersections[2][0] << \",\" << intersections[2][1] << endl;\n//     Rcpp::Rcout << \"intersections[3]\" << intersections[3][0] << \",\" << intersections[3][1] << endl;\n//     Rcpp::Rcout << \"need_flag[0]\" << need_flag[0] << endl;\n//     Rcpp::Rcout << \"need_flag[1]\" << need_flag[1] << endl;\n//     Rcpp::Rcout << \"need_flag[2]\" << need_flag[2] << endl;\n//     Rcpp::Rcout << \"need_flag[3]\" << need_flag[3] << endl;\n// #else\n//     cout << \"---------------------------\" << endl;\n//     cout << \"j: \" << j << endl;\n//     cout << \"inetrsection numbers wrong\" << j << endl;\n//     cout << \"p\" << p[0] << \",\" << p[1] << endl;\n//     cout << \"u\" << u[0] << \",\" << u[1] << endl;\n//     cout << \"s_min\" << s_min << endl;\n//     cout << \"s_max\" << s_max << endl;\n//     cout << \"lambda_min\" << lambda_min << endl;\n//     cout << \"lambda_max\" << lambda_max << endl;\n//     cout << \"intersections[0]\" << intersections[0][0] << \",\" << intersections[0][1] << endl;\n//     cout << \"intersections[1]\" << intersections[1][0] << \",\" << intersections[1][1] << endl;\n//     cout << \"intersections[2]\" << intersections[2][0] << \",\" << intersections[2][1] << endl;\n//     cout << \"intersections[3]\" << intersections[3][0] << \",\" << intersections[3][1] << endl;\n//     cout << \"need_flag[0]\" << need_flag[0] << endl;\n//     cout << \"need_flag[1]\" << need_flag[1] << endl;\n//     cout << \"need_flag[2]\" << need_flag[2] << endl;\n//     cout << \"need_flag[3]\" << need_flag[3] << endl;\n// #endif\n//   }\n\n//   return;\n// }\n\n// void golden_section_search(Data &data, Algorithm *algorithm, Metric *metric, double p[], double u[], int s_min, int s_max, double log_lambda_min, double log_lambda_max, double best_arg[],\n//                            Eigen::VectorXd &beta1, double &coef01, double &train_loss1, double &ic1, Eigen::MatrixXd &ic_sequence)\n// {\n//     int n = data.get_n();\n//     Eigen::VectorXi full_mask(n);\n//     for (int i = 0; i < n; i++)\n//     {\n//         full_mask(i) = int(i);\n//     }\n//     vector<Eigen::MatrixXd> full_group_XTX = group_XTX(data.x, data.g_index, data.g_size, data.n, data.p, data.g_num, algorithm->model_type);\n\n//     Eigen::VectorXd beta_init = Eigen::VectorXd::Zero(data.get_p());\n//     Eigen::VectorXd beta_temp1 = Eigen::VectorXd::Zero(data.get_p());\n//     Eigen::VectorXd beta_temp2 = Eigen::VectorXd::Zero(data.get_p());\n//     double train_loss_temp1, train_loss_temp2;\n//     double coef0_temp1, coef0_temp2;\n//     double coef0_init = 0.0;\n//     int ic_row, ic_col;\n//     double d_lambda = (log_lambda_max - log_lambda_min) / 99;\n\n//     double invphi, invphi2, closs, dloss;\n//     double a[2], b[2], c[2], d[2], h[2];\n\n//     // stop condiction\n//     double s_tol = 2;\n//     double log_lambda_tol = (log_lambda_max - log_lambda_min) / 200;\n\n//     invphi = (pow(5, 0.5) - 1.0) / 2.0;\n//     invphi2 = (3.0 - pow(5, 0.5)) / 2.0;\n//     cal_intersections(p, u, s_min, s_max, log_lambda_min, log_lambda_max, a, b);\n\n//     h[0] = b[0] - a[0];\n//     h[1] = b[1] - a[1];\n\n//     c[0] = a[0] + invphi2 * h[0];\n//     c[1] = a[1] + invphi2 * h[1];\n//     d[0] = a[0] + invphi * h[0];\n//     d[1] = a[1] + invphi * h[1];\n\n//     if (h[0] > 0.0001)\n//     {\n//         c[0] = int(c[0]);\n//         d[0] = ceil(d[0]);\n//     }\n//     else if (h[0] < -0.0001)\n//     {\n//         c[0] = ceil(c[0]);\n//         d[0] = int(d[0]);\n//     }\n//     else\n//     {\n//         c[0] = round(c[0]);\n//         d[0] = round(d[0]);\n//     }\n\n//     algorithm->update_train_mask(full_mask);\n//     algorithm->update_sparsity_level(int(c[0]));\n//     algorithm->update_lambda_level(exp(c[1]));\n//     algorithm->update_beta_init(beta_init);\n//     algorithm->update_coef0_init(coef0_init);\n//     algorithm->update_group_XTX(full_group_XTX);\n//     algorithm->fit();\n//     if (algorithm->warm_start)\n//     {\n//         beta_init = algorithm->get_beta();\n//         coef0_init = algorithm->get_coef0();\n//     }\n//     closs = metric->ic(algorithm, data);\n//     coef0_temp1 = algorithm->get_coef0();\n//     beta_temp1 = algorithm->get_beta();\n//     train_loss_temp1 = metric->train_loss(algorithm, data);\n\n//     ic_row = int(c[0]);\n//     ic_col = floor((c[1] - log_lambda_min) / d_lambda);\n//     if (std::isnan(ic_sequence(ic_row, ic_col)))\n//     {\n//         ic_sequence(ic_row, ic_col) = closs;\n//     }\n//     else\n//     {\n//         ic_sequence(ic_row, ic_col) = (ic_sequence(ic_row, ic_col) > closs) ? closs : ic_sequence(ic_row, ic_col);\n//     }\n\n//     algorithm->update_train_mask(full_mask);\n//     algorithm->update_sparsity_level(int(d[0]));\n//     algorithm->update_lambda_level(exp(d[1]));\n//     algorithm->update_beta_init(beta_init);\n//     algorithm->update_coef0_init(coef0_init);\n//     algorithm->update_group_XTX(full_group_XTX);\n//     algorithm->fit();\n//     if (algorithm->warm_start)\n//     {\n//         beta_init = algorithm->get_beta();\n//         coef0_init = algorithm->get_coef0();\n//     }\n\n//     dloss = metric->ic(algorithm, data);\n//     coef0_temp2 = algorithm->get_coef0();\n//     beta_temp2 = algorithm->get_beta();\n//     train_loss_temp2 = metric->train_loss(algorithm, data);\n//     ic_row = int(d[0]);\n//     ic_col = floor((d[1] - log_lambda_min) / d_lambda);\n//     if (std::isnan(ic_sequence(ic_row, ic_col)))\n//     {\n//         ic_sequence(ic_row, ic_col) = dloss;\n//     }\n//     else\n//     {\n//         ic_sequence(ic_row, ic_col) = (ic_sequence(ic_row, ic_col) > dloss) ? dloss : ic_sequence(ic_row, ic_col);\n//     }\n\n//     if (abs((invphi2 - invphi) * h[0]) <= s_tol && abs((invphi2 - invphi) * h[1]) < log_lambda_tol)\n//     {\n//         double min_loss;\n//         double tmp_loss;\n//         if (closs < dloss)\n//         {\n//             best_arg[0] = c[0];\n//             best_arg[1] = c[1];\n//             min_loss = closs;\n\n//             beta1 = beta_temp1;\n//             coef01 = coef0_temp1;\n//             ic1 = closs;\n//             train_loss1 = train_loss_temp1;\n//         }\n//         else\n//         {\n//             best_arg[0] = d[0];\n//             best_arg[1] = d[1];\n//             min_loss = dloss;\n\n//             beta1 = beta_temp2;\n//             coef01 = coef0_temp2;\n//             ic1 = dloss;\n//             train_loss1 = train_loss_temp2;\n//         }\n//         for (int i = 1; i < abs((invphi2 - invphi) * h[0]); i++)\n//         {\n//             algorithm->update_train_mask(full_mask);\n//             algorithm->update_sparsity_level(int(c[0] + sign(h[0]) * i));\n//             algorithm->update_lambda_level(exp(c[1]));\n//             algorithm->update_beta_init(beta_init);\n//             algorithm->update_coef0_init(coef0_init);\n//             algorithm->update_group_XTX(full_group_XTX);\n//             algorithm->fit();\n//             if (algorithm->warm_start)\n//             {\n//                 beta_init = algorithm->get_beta();\n//                 coef0_init = algorithm->get_coef0();\n//             }\n\n//             tmp_loss = metric->ic(algorithm, data);\n//             ic_row = int(c[0]);\n//             ic_col = floor((c[1] - log_lambda_min) / d_lambda);\n//             if (std::isnan(ic_sequence(ic_row, ic_col)))\n//             {\n//                 ic_sequence(ic_row, ic_col) = tmp_loss;\n//             }\n//             else\n//             {\n//                 ic_sequence(ic_row, ic_col) = (ic_sequence(ic_row, ic_col) > tmp_loss) ? tmp_loss : ic_sequence(ic_row, ic_col);\n//             }\n//             if (tmp_loss < min_loss)\n//             {\n//                 best_arg[0] = c[0] + sign(h[0]) * i;\n//                 best_arg[1] = c[1];\n//                 min_loss = tmp_loss;\n\n//                 beta1 = algorithm->get_beta();\n//                 coef01 = algorithm->get_coef0();\n//                 train_loss1 = metric->train_loss(algorithm, data);\n//                 ic1 = min_loss;\n//             }\n//         }\n//         return;\n//     }\n//     int tt = 0;\n//     while (tt < 100)\n//     {\n//         tt++;\n//         if (closs < dloss)\n//         {\n//             b[0] = d[0];\n//             b[1] = d[1];\n//             d[0] = c[0];\n//             d[1] = c[1];\n//             dloss = closs;\n//             h[0] = b[0] - a[0];\n//             h[1] = b[1] - a[1];\n\n//             c[0] = a[0] + invphi2 * h[0];\n//             c[1] = a[1] + invphi2 * h[1];\n//             if (h[0] > 0.0001)\n//             {\n//                 c[0] = int(c[0]);\n//             }\n//             else if (h[0] < -0.0001)\n//             {\n//                 c[0] = ceil(c[0]);\n//             }\n//             else\n//             {\n//                 c[0] = round(c[0]);\n//             }\n\n//             algorithm->update_train_mask(full_mask);\n//             algorithm->update_sparsity_level(int(c[0]));\n//             algorithm->update_lambda_level(exp(c[1]));\n//             algorithm->update_beta_init(beta_init);\n//             algorithm->update_coef0_init(coef0_init);\n//             algorithm->update_group_XTX(full_group_XTX);\n//             algorithm->fit();\n//             if (algorithm->warm_start)\n//             {\n//                 beta_init = algorithm->get_beta();\n//                 coef0_init = algorithm->get_coef0();\n//             }\n//             closs = metric->ic(algorithm, data);\n//             coef0_temp1 = algorithm->get_coef0();\n//             beta_temp1 = algorithm->get_beta();\n//             train_loss_temp1 = metric->train_loss(algorithm, data);\n//             ic_row = int(c[0]);\n//             ic_col = floor((c[1] - log_lambda_min) / d_lambda);\n//             if (std::isnan(ic_sequence(ic_row, ic_col)))\n//             {\n//                 ic_sequence(ic_row, ic_col) = closs;\n//             }\n//             else\n//             {\n//                 ic_sequence(ic_row, ic_col) = (ic_sequence(ic_row, ic_col) > closs) ? closs : ic_sequence(ic_row, ic_col);\n//             }\n//         }\n\n//         else\n//         {\n//             a[0] = c[0];\n//             a[1] = c[1];\n//             c[0] = d[0];\n//             c[1] = d[1];\n//             closs = dloss;\n//             h[0] = b[0] - a[0];\n//             h[1] = b[1] - a[1];\n\n//             d[0] = a[0] + invphi * h[0];\n//             d[1] = a[1] + invphi * h[1];\n\n//             if (h[0] > 0.0001)\n//             {\n//                 d[0] = ceil(d[0]);\n//             }\n//             else if (h[0] < -0.0001)\n//             {\n//                 d[0] = int(d[0]);\n//             }\n//             else\n//             {\n//                 d[0] = round(d[0]);\n//             }\n\n//             algorithm->update_train_mask(full_mask);\n//             algorithm->update_sparsity_level(int(d[0]));\n//             algorithm->update_lambda_level(exp(d[1]));\n//             algorithm->update_beta_init(beta_init);\n//             algorithm->update_coef0_init(coef0_init);\n//             algorithm->update_group_XTX(full_group_XTX);\n//             algorithm->fit();\n//             if (algorithm->warm_start)\n//             {\n//                 beta_init = algorithm->get_beta();\n//                 coef0_init = algorithm->get_coef0();\n//             }\n\n//             dloss = metric->ic(algorithm, data);\n//             coef0_temp2 = algorithm->get_coef0();\n//             beta_temp2 = algorithm->get_beta();\n//             train_loss_temp2 = metric->train_loss(algorithm, data);\n//             ic_row = int(d[0]);\n//             ic_col = floor((d[1] - log_lambda_min) / d_lambda);\n//             if (std::isnan(ic_sequence(ic_row, ic_col)))\n//             {\n//                 ic_sequence(ic_row, ic_col) = dloss;\n//             }\n//             else\n//             {\n//                 ic_sequence(ic_row, ic_col) = (ic_sequence(ic_row, ic_col) > dloss) ? dloss : ic_sequence(ic_row, ic_col);\n//             }\n//         }\n\n//         if ((abs((invphi2 - invphi) * h[0]) <= s_tol && abs((invphi2 - invphi) * h[1]) < log_lambda_tol) || tt == 50)\n//         {\n//             double min_loss;\n//             double tmp_loss;\n//             if (closs < dloss)\n//             {\n//                 best_arg[0] = c[0];\n//                 best_arg[1] = c[1];\n//                 min_loss = closs;\n\n//                 beta1 = beta_temp1;\n//                 coef01 = coef0_temp1;\n//                 ic1 = closs;\n//                 train_loss1 = train_loss_temp1;\n//             }\n//             else\n//             {\n//                 best_arg[0] = d[0];\n//                 best_arg[1] = d[1];\n//                 min_loss = dloss;\n\n//                 beta1 = beta_temp2;\n//                 coef01 = coef0_temp2;\n//                 ic1 = dloss;\n//                 train_loss1 = train_loss_temp2;\n//             }\n//             for (int i = 1; i < abs((invphi2 - invphi) * h[0]); i++)\n//             {\n//                 algorithm->update_train_mask(full_mask);\n//                 algorithm->update_sparsity_level(int(c[0] + sign(h[0]) * i));\n//                 algorithm->update_lambda_level(exp(c[1]));\n//                 algorithm->update_beta_init(beta_init);\n//                 algorithm->update_coef0_init(coef0_init);\n//                 algorithm->update_group_XTX(full_group_XTX);\n//                 algorithm->fit();\n//                 if (algorithm->warm_start)\n//                 {\n//                     beta_init = algorithm->get_beta();\n//                     coef0_init = algorithm->get_coef0();\n//                 }\n//                 tmp_loss = metric->ic(algorithm, data);\n\n//                 ic_row = int(c[0]);\n//                 ic_col = floor((c[1] - log_lambda_min) / d_lambda);\n//                 if (std::isnan(ic_sequence(ic_row, ic_col)))\n//                 {\n//                     ic_sequence(ic_row, ic_col) = tmp_loss;\n//                 }\n//                 else\n//                 {\n//                     ic_sequence(ic_row, ic_col) = (ic_sequence(ic_row, ic_col) > tmp_loss) ? tmp_loss : ic_sequence(ic_row, ic_col);\n//                 }\n//                 if (tmp_loss < min_loss)\n//                 {\n//                     best_arg[0] = c[0] + sign(h[0]) * i;\n//                     best_arg[1] = c[1];\n//                     min_loss = tmp_loss;\n\n//                     beta1 = algorithm->get_beta();\n//                     coef01 = algorithm->get_coef0();\n//                     train_loss1 = metric->train_loss(algorithm, data);\n//                     ic1 = min_loss;\n//                 }\n//             }\n//             return;\n//         }\n//     }\n// }\n\n// int GDC(int a, int b)\n// {\n//   int Max, Min;\n//   Max = a > b ? a : b;\n//   if (a == Max)\n//     Min = b;\n//   else\n//     Min = a;\n//   int z = Min;\n//   while (Max % Min != 0)\n//   {\n//     z = Max % Min;\n//     Max = Min;\n//     Min = z;\n//   }\n//   return z;\n// }\n\n// void seq_search(Data &data, Algorithm *algorithm, Metric *metric, double p[], double u[], int s_min, int s_max, double log_lambda_min, double log_lambda_max, double best_arg[],\n//                 Eigen::VectorXd &beta1, double &coef01, double &train_loss1, double &ic1, int nlambda, Eigen::MatrixXd &ic_sequence)\n// {\n//     vector<Eigen::MatrixXd> full_group_XTX = group_XTX(data.x, data.g_index, data.g_size, data.n, data.p, data.g_num, algorithm->model_type);\n\n//     int n = data.get_n();\n//     Eigen::VectorXi full_mask(n);\n//     for (int i = 0; i < n; i++)\n//     {\n//         full_mask(i) = int(i);\n//     }\n//     Eigen::VectorXd beta_init = Eigen::VectorXd::Zero(data.get_p());\n//     double coef0_init = 0.0;\n//     Eigen::VectorXd beta_warm(data.get_p());\n//     double coef0_warm = 0.0;\n\n//     double d_lambda = (log_lambda_max - log_lambda_min) / (nlambda - 1);\n//     int k_lambda = abs(round(u[1] / d_lambda));\n//     cout << \"d_lambda: \" << d_lambda << \", k_lambda: \" << k_lambda << \", u[1]: \" << u[1] << \", u[0]: \" << u[0] << endl;\n//     if (abs(u[0]) != 1 && k_lambda != 1)\n//     {\n//         if (k_lambda == 0 && u[0] != 0)\n//         {\n//             u[0] = u[0] / abs(u[0]);\n//         }\n//         else if (u[0] == 0 && k_lambda != 0)\n//         {\n//             u[1] = u[1] / k_lambda;\n//         }\n//         else\n//         {\n//             int gdc;\n//             gdc = GDC(k_lambda, abs(int(u[0])));\n//             if (gdc)\n//             {\n//                 u[0] = round(u[0] / gdc);\n//                 u[1] = u[1] / gdc;\n//             }\n//         }\n//     }\n//     cout << \"u[0]: \" << u[0] << \", u[1]: \" << u[1] << endl;\n\n//     int i = 0;\n//     int j = 0;\n//     int ic_row, ic_col;\n//     Eigen::MatrixXd beta_all_1 = Eigen::MatrixXd::Zero(data.get_p(), (s_max - s_min + 1) * nlambda);\n//     Eigen::MatrixXd beta_all_2 = Eigen::MatrixXd::Zero(data.get_p(), (s_max - s_min + 1) * nlambda);\n//     Eigen::VectorXd coef0_all_1 = Eigen::VectorXd::Zero((s_max - s_min + 1) * nlambda);\n//     Eigen::VectorXd coef0_all_2 = Eigen::VectorXd::Zero((s_max - s_min + 1) * nlambda);\n//     Eigen::VectorXd train_loss_1 = Eigen::VectorXd::Zero((s_max - s_min + 1) * nlambda);\n//     Eigen::VectorXd train_loss_2 = Eigen::VectorXd::Zero((s_max - s_min + 1) * nlambda);\n//     Eigen::VectorXd ic_sequence_1 = Eigen::VectorXd::Zero((s_max - s_min + 1) * nlambda);\n//     Eigen::VectorXd ic_sequence_2 = Eigen::VectorXd::Zero((s_max - s_min + 1) * nlambda);\n//     beta_warm.setZero();\n\n//     algorithm->update_train_mask(full_mask);\n//     algorithm->update_sparsity_level(p[0] + i * u[0]);\n//     algorithm->update_lambda_level(exp(p[1] + i * u[1]));\n//     algorithm->update_beta_init(beta_init);\n//     algorithm->update_coef0_init(coef0_init);\n//     algorithm->update_group_XTX(full_group_XTX);\n\n//     algorithm->fit();\n//     if (algorithm->warm_start)\n//     {\n//         beta_init = algorithm->get_beta();\n//         coef0_init = algorithm->get_coef0();\n//     }\n//     ic_sequence_1(i) = metric->ic(algorithm, data);\n//     beta_all_1.col(i) = algorithm->get_beta();\n//     coef0_all_1(i) = algorithm->get_coef0();\n//     train_loss_1(i) = metric->train_loss(algorithm, data);\n\n//     ic_sequence_2(j) = ic_sequence_1(i);\n//     beta_all_2.col(j) = beta_all_1.col(i);\n//     coef0_all_2(j) = coef0_all_1(i);\n//     train_loss_2(j) = train_loss_1(i);\n\n//     ic_row = p[0] + i * u[0] - s_min;\n//     ic_col = (p[1] + i * u[1] - log_lambda_min) / d_lambda;\n//     if (std::isnan(ic_sequence(ic_row, ic_col)))\n//     {\n//         ic_sequence(ic_row, ic_col) = ic_sequence_1(i);\n//     }\n//     else\n//     {\n//         ic_sequence(ic_row, ic_col) = ic_sequence(ic_row, ic_col) > ic_sequence_1(i) ? ic_sequence_1(i) : ic_sequence(ic_row, ic_col);\n//     }\n//     cout << \"i: \" << i << \", ic_sequence(\" << ic_row << \",\" << ic_col << \"): \" << ic_sequence(ic_row, ic_col) << endl;\n\n//     i++;\n//     j++;\n//     beta_warm = beta_init;\n//     coef0_warm = coef0_init;\n//     cout << \"s_max: \" << s_max << \", s_min: \" << s_min << \", log_lambda_max + d_lambda * 1e-4:\" << log_lambda_max + d_lambda * 1e-4 << \", log_lambda_min - d_lambda * 1e-4: \" << log_lambda_min - d_lambda * 1e-4 << endl;\n//     while ((p[0] + i * u[0] <= s_max) && (p[1] + i * u[1] <= log_lambda_max + d_lambda * 1e-4) && (p[0] + i * u[0] >= s_min) && (p[1] + i * u[1] >= log_lambda_min - d_lambda * 1e-4))\n//     {\n//         cout << \"i:\" << i << \", p[0]: \" << p[0] << \", u[0]: \" << u[0] << \", p[0] + i * u[0]: \" << p[0] + i * u[0] << \", p[1]\" << p[1] << \", u[1]: \" << u[1] << \", p[1] + i * u[1] : \" << p[1] + i * u[1] << endl;\n//         algorithm->update_train_mask(full_mask);\n//         algorithm->update_sparsity_level(p[0] + i * u[0]);\n//         algorithm->update_lambda_level(exp(p[1] + i * u[1]));\n//         algorithm->update_beta_init(beta_init);\n//         algorithm->update_coef0_init(coef0_init);\n//         algorithm->update_group_XTX(full_group_XTX);\n\n//         algorithm->fit();\n//         if (algorithm->warm_start)\n//         {\n//             beta_init = algorithm->get_beta();\n//             coef0_init = algorithm->get_coef0();\n//         }\n//         ic_sequence_1(i) = metric->ic(algorithm, data);\n//         beta_all_1.col(i) = algorithm->get_beta();\n//         coef0_all_1(i) = algorithm->get_coef0();\n//         train_loss_1(i) = metric->train_loss(algorithm, data);\n//         ic_row = p[0] + i * u[0] - s_min;\n//         ic_col = round((p[1] + i * u[1] - log_lambda_min) / d_lambda);\n//         if (std::isnan(ic_sequence(ic_row, ic_col)))\n//         {\n//             ic_sequence(ic_row, ic_col) = ic_sequence_1(i);\n//         }\n//         else\n//         {\n//             ic_sequence(ic_row, ic_col) = ic_sequence(ic_row, ic_col) > ic_sequence_1(i) ? ic_sequence_1(i) : ic_sequence(ic_row, ic_col);\n//         }\n//         cout << \"i: \" << i << \", ic_sequence(\" << ic_row << \",\" << ic_col << \"): \" << ic_sequence(ic_row, ic_col) << \", ic_sequence_1(i): \" << ic_sequence_1(i) << endl;\n//         i++;\n//     }\n//     cout << \"out: i:\" << i << \", p[0] - i * u[0]: \" << p[0] - i * u[0] << \", p[1] - i * u[1] : \" << p[1] - i * u[1] << endl;\n\n//     beta_init = beta_warm;\n//     coef0_init = coef0_warm;\n\n//     while ((p[0] - j * u[0] <= s_max) && (p[1] - j * u[1] <= log_lambda_max + d_lambda * 1e-4) && (p[0] - j * u[0] >= s_min) && (p[1] - j * u[1] >= log_lambda_min - d_lambda * 1e-4))\n//     {\n//         cout << \"j:\" << j << \", p[0]: \" << p[0] << \", u[0]: \" << u[0] << \", p[0] - j * u[0]: \" << p[0] - j * u[0] << \", p[1]\" << p[1] << \", u[1]: \" << u[1] << \", p[1] - j * u[1]\" << p[1] - j * u[1] << endl;\n//         algorithm->update_train_mask(full_mask);\n//         algorithm->update_sparsity_level(p[0] - j * u[0]);\n//         algorithm->update_lambda_level(exp(p[1] - j * u[1]));\n//         algorithm->update_beta_init(beta_init);\n//         algorithm->update_coef0_init(coef0_init);\n//         algorithm->update_group_XTX(full_group_XTX);\n\n//         algorithm->fit();\n//         if (algorithm->warm_start)\n//         {\n//             beta_init = algorithm->get_beta();\n//             coef0_init = algorithm->get_coef0();\n//         }\n//         ic_sequence_2(j) = metric->ic(algorithm, data);\n//         beta_all_2.col(j) = algorithm->get_beta();\n//         coef0_all_2(j) = algorithm->get_coef0();\n//         train_loss_2(j) = metric->train_loss(algorithm, data);\n//         ic_row = p[0] - j * u[0] - s_min;\n//         ic_col = round((p[1] - j * u[1] - log_lambda_min) / d_lambda);\n//         if (std::isnan(ic_sequence(ic_row, ic_col)))\n//         {\n//             ic_sequence(ic_row, ic_col) = ic_sequence_2(j);\n//         }\n//         else\n//         {\n//             ic_sequence(ic_row, ic_col) = ic_sequence(ic_row, ic_col) > ic_sequence_2(j) ? ic_sequence_2(j) : ic_sequence(ic_row, ic_col);\n//         }\n//         cout << \"j: \" << j << \", ic_sequence(\" << ic_row << \",\" << ic_col << \"): \" << ic_sequence(ic_row, ic_col) << \"ic_sequence_2(j): \" << ic_sequence_2(j) << endl;\n\n//         j++;\n//     }\n//     cout << \"out: j:\" << j << \", p[0] - j * u[0]: \" << p[0] - j * u[0] << \", p[1] - j * u[1] : \" << p[1] - j * u[1] << endl;\n//     int minPosition_1, minPosition_2;\n//     ic_sequence_1 = ic_sequence_1.head(i).eval();\n//     ic_sequence_2 = ic_sequence_2.head(j).eval();\n//     ic_sequence_1.minCoeff(&minPosition_1);\n//     ic_sequence_2.minCoeff(&minPosition_2);\n//     cout << \"minPosition_1: \" << minPosition_1 << \", minPosition_2: \" << minPosition_2 << \",  ic_sequence_1.minCoeff(&minPosition_1): \" << ic_sequence_1(minPosition_1) << \", ic_sequence_2.minCoeff(&minPosition_2): \" << ic_sequence_2(minPosition_2) << endl;\n//     cout << \"ic_sequence_2(minPosition_2): \" << ic_sequence_2(minPosition_2) << \", ic_sequence_2(minPosition_2+1): \" << ic_sequence_2(minPosition_2 + 1) << \", ic_sequence_2(minPosition_2+1)< ic_sequence_2(minPosition_2): \" << (ic_sequence_2(minPosition_2 + 1) < ic_sequence_2(minPosition_2)) << endl;\n//     int minPosition;\n//     if (ic_sequence_1(minPosition_1) < ic_sequence_2(minPosition_2))\n//     {\n//         minPosition = minPosition_1;\n//         ic1 = ic_sequence_1(minPosition);\n//         train_loss1 = train_loss_1(minPosition);\n//         beta1 = beta_all_1.col(minPosition);\n//         coef01 = coef0_all_1(minPosition);\n//     }\n//     else\n//     {\n//         minPosition = -minPosition_2;\n//         ic1 = ic_sequence_2(minPosition_2);\n//         train_loss1 = train_loss_2(minPosition_2);\n//         beta1 = beta_all_2.col(minPosition_2);\n//         coef01 = coef0_all_2(minPosition_2);\n//     }\n//     best_arg[0] = p[0] + (minPosition)*u[0];\n//     best_arg[1] = p[1] + (minPosition)*u[1];\n//     cout << \"minPosition :\" << minPosition << \",  best_arg[0]:\" << best_arg[0] << \" best_arg[1]: \" << best_arg[1] << \", p[1] + (minPosition)*u[1]= \" << p[1] << \"+\" << minPosition << \"* \" << u[1] << \"= \" << p[1] + (minPosition)*u[1] << \", (minPosition)*u[1]: \" << (minPosition)*u[1] << endl;\n//     return;\n// }\n\n// List pgs_path(Data &data, Algorithm *algorithm, Metric *metric, int s_min, int s_max, double log_lambda_min, double log_lambda_max, int powell_path, int nlambda)\n// {\n//     int n = data.get_n();\n//     Eigen::VectorXi full_mask(n);\n//     vector<Eigen::MatrixXd> full_group_XTX = group_XTX(data.x, data.g_index, data.g_size, data.n, data.p, data.g_num, algorithm->model_type);\n//     for (int i = 0; i < n; i++)\n//     {\n//         full_mask(i) = i;\n//     }\n//     Eigen::MatrixXd beta_all = Eigen::MatrixXd::Zero(data.get_p(), 100);\n//     Eigen::VectorXd coef0_all = Eigen::VectorXd::Zero(100);\n//     Eigen::VectorXd train_loss_all = Eigen::VectorXd::Zero(100);\n//     Eigen::VectorXd ic_all = Eigen::VectorXd::Zero(100);\n//     Eigen::VectorXd lambda_chosen = Eigen::VectorXd::Zero(100);\n\n//     Eigen::VectorXd beta_temp = Eigen::VectorXd::Zero(data.get_p());\n//     double coef0_temp;\n//     double train_loss_temp;\n//     double ic_temp;\n//     //double lambda_temp;\n\n//     if (powell_path == 1)\n//         nlambda = 100;\n//     Eigen::MatrixXd ic_sequence = NAN * Eigen::MatrixXd::Ones(s_max - s_min + 1, nlambda);\n\n//     double P[3][3], U[2][2];\n//     int i;\n\n//     P[0][0] = double(s_min);\n//     P[0][1] = log_lambda_min;\n\n//     U[1][0] = 1.; //search directions\n//     U[1][1] = 0.;\n//     U[0][0] = 0.;\n//     U[0][1] = (log_lambda_max - log_lambda_min) / (nlambda - 1);\n\n//     int ttt = 0;\n//     if (powell_path == 1)\n//         golden_section_search(data, algorithm, metric, P[0], U[1], s_min, s_max, log_lambda_min, log_lambda_max, P[0], beta_temp, coef0_temp, train_loss_temp, ic_temp, ic_sequence);\n//     else\n//         seq_search(data, algorithm, metric, P[0], U[1], s_min, s_max, log_lambda_min, log_lambda_max, P[0], beta_temp, coef0_temp, train_loss_temp, ic_temp, nlambda, ic_sequence);\n//     beta_all.col(ttt) = beta_temp;\n//     coef0_all(ttt) = coef0_temp;\n//     train_loss_all(ttt) = train_loss_temp;\n//     ic_all(ttt) = ic_temp;\n//     lambda_chosen(ttt) = exp(P[0][1]);\n\n//     while (ttt < 11)\n//     {\n//         ttt++;\n//         for (i = 0; i < 2; i++)\n//         {\n//             if (powell_path == 1)\n//                 golden_section_search(data, algorithm, metric, P[i], U[i], s_min, s_max, log_lambda_min, log_lambda_max, P[i + 1], beta_temp, coef0_temp, train_loss_temp, ic_temp, ic_sequence);\n//             else\n//                 seq_search(data, algorithm, metric, P[i], U[i], s_min, s_max, log_lambda_min, log_lambda_max, P[i + 1], beta_temp, coef0_temp, train_loss_temp, ic_temp, nlambda, ic_sequence);\n//             beta_all.col(ttt) = beta_temp;\n//             coef0_all(ttt) = coef0_temp;\n//             train_loss_all(ttt) = train_loss_temp;\n//             ic_all(ttt) = ic_temp;\n//             lambda_chosen(ttt) = exp(P[i + 1][1]);\n//             ttt++;\n//         }\n//         U[0][0] = U[1][0];\n//         U[0][1] = U[1][1];\n//         U[1][0] = P[2][0] - P[0][0];\n//         U[1][1] = P[2][1] - P[0][1];\n//         if ((!(abs(U[1][0]) <= 0.0001 && abs(U[1][1]) <= 0.0001)) && ttt < 11)\n//         {\n//             if (powell_path == 1)\n//                 golden_section_search(data, algorithm, metric, P[0], U[1], s_min, s_max, log_lambda_min, log_lambda_max, P[0], beta_temp, coef0_temp, train_loss_temp, ic_temp, ic_sequence);\n//             else\n//                 seq_search(data, algorithm, metric, P[0], U[1], s_min, s_max, log_lambda_min, log_lambda_max, P[0], beta_temp, coef0_temp, train_loss_temp, ic_temp, nlambda, ic_sequence);\n//             beta_all.col(ttt) = beta_temp;\n//             coef0_all(ttt) = coef0_temp;\n//             train_loss_all(ttt) = train_loss_temp;\n//             ic_all(ttt) = ic_temp;\n//             lambda_chosen(ttt) = exp(P[0][1]);\n//         }\n//         else\n//         {\n//             // P[0] is the best parameter.\n//             algorithm->update_train_mask(full_mask);\n//             algorithm->update_sparsity_level(int(P[0][0]));\n//             algorithm->update_lambda_level(exp(P[0][1]));\n//             algorithm->update_group_XTX(full_group_XTX);\n//             algorithm->fit();\n\n//             Eigen::VectorXd best_beta = algorithm->get_beta();\n//             double best_coef0 = algorithm->get_coef0();\n//             double best_train_loss = metric->train_loss(algorithm, data);\n//             double best_ic = metric->ic(algorithm, data);\n\n//             beta_all.col(ttt) = best_beta;\n//             coef0_all(ttt) = best_coef0;\n//             train_loss_all(ttt) = best_train_loss;\n//             ic_all(ttt) = best_ic;\n//             lambda_chosen(ttt) = exp(P[0][1]);\n\n//             ttt++;\n//             beta_all = beta_all.leftCols(ttt).eval();\n//             coef0_all = coef0_all.head(ttt).eval();\n//             train_loss_all = train_loss_all.head(ttt).eval();\n//             ic_all = ic_all.head(ttt).eval();\n//             lambda_chosen = lambda_chosen.head(ttt).eval();\n\n//             if (data.is_normal)\n//             {\n//                 if (algorithm->model_type == 1)\n//                 {\n//                     for (int k = 0; k < ttt; k++)\n//                     {\n//                         beta_all.col(k) = sqrt(double(n)) * beta_all.col(k).cwiseQuotient(data.x_norm);\n//                         coef0_all(k) = data.y_mean - beta_all.col(k).dot(data.x_mean);\n//                     }\n//                 }\n\n//                 else if (data.data_type == 2)\n//                 {\n//                     for (int k = 0; k < ttt; k++)\n//                     {\n//                         beta_all.col(k) = sqrt(double(n)) * beta_all.col(k).cwiseQuotient(data.x_norm);\n//                         coef0_all(k) = coef0_all(k) - beta_all.col(k).dot(data.x_mean);\n//                     }\n//                 }\n//                 else\n//                 {\n//                     for (int k = 0; k < ttt; k++)\n//                     {\n//                         beta_all.col(k) = sqrt(double(n)) * beta_all.col(k).cwiseQuotient(data.x_norm);\n//                     }\n//                 }\n//             }\n//             int min_ic_index = 0;\n//             double min_ic = ic_all.minCoeff(&min_ic_index);\n//             if (min_ic == ic_all(ttt - 1))\n//             {\n//                 min_ic_index = ttt - 1;\n//             }\n// #ifdef R_BUILD\n//             return List::create(Named(\"beta\") = beta_all.col(min_ic_index).eval(), Named(\"coef0\") = coef0_all(min_ic_index),\n//                                 Named(\"train_loss\") = train_loss_all(min_ic_index), Named(\"ic\") = ic_all(min_ic_index),\n//                                 Named(\"lambda\") = lambda_chosen(min_ic_index),\n//                                 Named(\"beta_all\") = beta_all, Named(\"coef0_all\") = coef0_all,\n//                                 Named(\"train_loss_all\") = train_loss_all,\n//                                 Named(\"ic_all\") = ic_all,\n//                                 Named(\"lambda_all\") = lambda_chosen,\n//                                 Named(\"ic_mat\") = ic_sequence);\n// #else\n//             List mylist;\n//             mylist.add(\"beta\", beta_all.col(min_ic_index).eval());\n//             mylist.add(\"coef0\", coef0_all(min_ic_index));\n//             mylist.add(\"train_loss\", train_loss_all(min_ic_index));\n//             mylist.add(\"ic\", ic_all(min_ic_index));\n//             mylist.add(\"lambda\", lambda_chosen(min_ic_index));\n//             return mylist;\n// #endif\n//         }\n//     }\n// #ifdef R_BUILD\n//     Rcpp::Rcout << \"powell end wrong\" << endl;\n// #else\n//     cout << \"powell end wrong\" << endl;\n// #endif\n// #ifdef R_BUILD\n//     return List::create(Named(\"beta\") = 0);\n// #else\n//     List mylist;\n//     return mylist;\n// #endif\n// }", "meta": {"hexsha": "7d1847e6c119abc016e8d79a97a89248de801e2c", "size": 37151, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/path.cpp", "max_stars_repo_name": "adaizjx/abess", "max_stars_repo_head_hexsha": "a4374abaa56573c5ebf6ca51b641a1e8548fd554", "max_stars_repo_licenses": ["CNRI-Python", "CECILL-B"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-06T08:06:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T08:06:13.000Z", "max_issues_repo_path": "src/path.cpp", "max_issues_repo_name": "adaizjx/abess", "max_issues_repo_head_hexsha": "a4374abaa56573c5ebf6ca51b641a1e8548fd554", "max_issues_repo_licenses": ["CNRI-Python", "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/path.cpp", "max_forks_repo_name": "adaizjx/abess", "max_forks_repo_head_hexsha": "a4374abaa56573c5ebf6ca51b641a1e8548fd554", "max_forks_repo_licenses": ["CNRI-Python", "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": 38.6989583333, "max_line_length": 303, "alphanum_fraction": 0.4896503459, "num_tokens": 11178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.2842147580929516}}
{"text": "/*\n * Copyright (c) 2011-2021, The DART development contributors\n * All rights reserved.\n *\n * The list of contributors can be found at:\n *   https://github.com/dartsim/dart/blob/master/LICENSE\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#ifndef DART_OPTIMIZATION_GENERICMULTIOBJECTIVEPROBLEM_HPP_\n#define DART_OPTIMIZATION_GENERICMULTIOBJECTIVEPROBLEM_HPP_\n\n#include <cstddef>\n#include <vector>\n\n#include <Eigen/Dense>\n\n#include \"dart/optimization/Function.hpp\"\n#include \"dart/optimization/MultiObjectiveProblem.hpp\"\n\nnamespace dart {\nnamespace optimization {\n\nclass GenericMultiObjectiveProblem : public MultiObjectiveProblem\n{\npublic:\n  /// Constructor\n  explicit GenericMultiObjectiveProblem(\n      std::size_t dim, std::size_t integerDim = 0u);\n\n  /// Destructor\n  ~GenericMultiObjectiveProblem() override = default;\n\n  /// \\{ \\name Objectives\n\n  // Documentation inherited.\n  std::size_t getObjectiveDimension() const override;\n\n  /// Sets objective functions to be minimized.\n  void setObjectiveFunctions(const std::vector<FunctionPtr>& objectives);\n\n  /// Adds a minimum objective function\n  void addObjectiveFunction(FunctionPtr objective);\n\n  /// Returns the number objective functions.\n  std::size_t getNumObjectiveFunctions() const;\n\n  /// Returns objective functions\n  const std::vector<FunctionPtr>& getObjectiveFunctions() const;\n\n  /// Removes an objective function\n  void removeObjectiveFunction(FunctionPtr function);\n\n  /// Removes all objective functions\n  void removeAllObjectiveFunctions();\n\n  /// \\}\n\n  /// \\{ \\name Equality Constraints\n\n  // Documentation inherited.\n  std::size_t getEqConstraintDimension() const override;\n\n  /// Adds equality constraint\n  void addEqConstraintFunction(FunctionPtr eqConst);\n\n  /// Returns number of equality constraints\n  std::size_t getNumEqualityConstraintFunctions() const;\n\n  /// Returns equality constraint\n  FunctionPtr getEqConstraintFunction(std::size_t index) const;\n\n  /// Removes equality constraint\n  void removeEqConstraintFunction(FunctionPtr eqConst);\n\n  /// Removes all equality constraints\n  void removeAllEqConstraintFunctions();\n\n  /// \\}\n\n  /// \\{ \\name Inequality Constraints\n\n  // Documentation inherited.\n  std::size_t getIneqConstraintDimension() const override;\n\n  /// Adds inequality constraint. Inequality constraints must evaluate\n  /// to LESS THAN or equal to zero (within some tolerance) to be satisfied.\n  void addIneqConstraintFunction(FunctionPtr ineqConst);\n\n  /// Returns number of inequality constraints\n  std::size_t getNumIneqConstraintFunctions() const;\n\n  /// Returns inequality constraint\n  FunctionPtr getIneqConstraintFunction(std::size_t index) const;\n\n  /// Removes inequality constraint\n  void removeIneqConstraintFunction(FunctionPtr ineqConst);\n\n  /// Removes all inequality constraints\n  void removeAllIneqConstraintFunctions();\n\n  /// \\}\n\n  /// \\{ \\name Evaluations\n\n  /// Evaluates objectives\n  Eigen::VectorXd evaluateObjectives(const Eigen::VectorXd& x) const override;\n\n  /// Evaluates equality constraints\n  Eigen::VectorXd evaluateEqConstraints(\n      const Eigen::VectorXd& x) const override;\n\n  /// Evaluates inequality constraints\n  Eigen::VectorXd evaluateIneqConstraints(\n      const Eigen::VectorXd& x) const override;\n\n  /// Return dimension of fitness\n  std::size_t getFitnessDimension() const;\n\n  /// Evaluates fitness, which is [objectives, equality constraints, inequality\n  /// constraints].\n  Eigen::VectorXd evaluateFitness(const Eigen::VectorXd& x) const;\n\n  /// \\}\n\nprotected:\n  /// Objective functions\n  std::vector<FunctionPtr> mObjectiveFunctions;\n\n  /// Equality constraint functions\n  std::vector<FunctionPtr> mEqConstraintFunctions;\n\n  /// Inequality constraint functions\n  std::vector<FunctionPtr> mIneqConstraintFunctions;\n\nprivate:\n  /// Cache for objective dimension\n  std::size_t mObjectiveDimension;\n\n  /// Cache for equality constraint dimension\n  std::size_t mEqConstraintDimension;\n\n  /// Cache for inequality constraint dimension\n  std::size_t mIneqConstraintDimension;\n};\n\n} // namespace optimization\n} // namespace dart\n\n#endif // DART_OPTIMIZATION_GENERICMULTIOBJECTIVEPROBLEM_HPP_\n", "meta": {"hexsha": "157e6dab06fea7b62f4a4b067ac0712adeb0e193", "size": 5512, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dart/optimization/GenericMultiObjectiveProblem.hpp", "max_stars_repo_name": "PowerOlive/dart", "max_stars_repo_head_hexsha": "31fb4ea3897cf26788aa16facda4e90f3fbab473", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-06T05:24:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-06T05:24:54.000Z", "max_issues_repo_path": "dart/optimization/GenericMultiObjectiveProblem.hpp", "max_issues_repo_name": "PowerOlive/dart", "max_issues_repo_head_hexsha": "31fb4ea3897cf26788aa16facda4e90f3fbab473", "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/optimization/GenericMultiObjectiveProblem.hpp", "max_forks_repo_name": "PowerOlive/dart", "max_forks_repo_head_hexsha": "31fb4ea3897cf26788aa16facda4e90f3fbab473", "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.6781609195, "max_line_length": 79, "alphanum_fraction": 0.7583454282, "num_tokens": 1176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.2842147580929516}}
{"text": "/* transfer_function.cc\n   Jeremy Barnes, 4 November 2009\n   Copyright (c) 2009 Jeremy Barnes.  All rights reserved.\n\n   Transfer function implementation.\n*/\n\n#include \"transfer_function.h\"\n#include <cmath>\n#include \"jml/db/persistent.h\"\n#include \"jml/boosting/registry.h\"\n#include \"jml/utils/smart_ptr_utils.h\"\n\n#include <boost/static_assert.hpp>\n\n\nusing namespace ML::DB;\nusing namespace std;\n\nnamespace ML {\n\n/*****************************************************************************/\n/* RANGE_TYPE                                                                */\n/*****************************************************************************/\n\n\n/*****************************************************************************/\n/* RANGE                                                                     */\n/*****************************************************************************/\n\n\n/*****************************************************************************/\n/* TRANSFER_FUNCTION                                                         */\n/*****************************************************************************/\n\nvoid\nTransfer_Function::\npoly_serialize(DB::Store_Writer & store) const\n{\n    Registry<Transfer_Function>::singleton().serialize(store, this);\n}\n\nstd::shared_ptr<Transfer_Function>\nTransfer_Function::\npoly_reconstitute(DB::Store_Reader & store)\n{\n    return Registry<Transfer_Function>::singleton().reconstitute(store);\n}\n\ndistribution<float>\nTransfer_Function::\ntransfer(const distribution<float> & activation) const\n{\n    int no = activation.size();\n    distribution<float> output(no);\n    transfer(&activation[0], &output[0], no);\n    return output;\n}\n\ndistribution<double>\nTransfer_Function::\ntransfer(const distribution<double> & activation) const\n{\n    int no = activation.size();\n    distribution<double> output(no);\n    transfer(&activation[0], &output[0], no);\n    return output;\n}\n\ndistribution<float>\nTransfer_Function::\nderivative(const distribution<float> & outputs) const\n{\n    int no = outputs.size();\n    distribution<float> result(no);\n    derivative(&outputs[0], &result[0], no);\n    return result;\n}\n\ndistribution<double>\nTransfer_Function::\nderivative(const distribution<double> & outputs) const\n{\n    int no = outputs.size();\n    distribution<double> result(no);\n    derivative(&outputs[0], &result[0], no);\n    return result;\n}\n\ndistribution<float>\nTransfer_Function::\nsecond_derivative(const distribution<float> & outputs) const\n{\n    int no = outputs.size();\n    distribution<float> result(no);\n    second_derivative(&outputs[0], &result[0], no);\n    return result;\n}\n\ndistribution<double>\nTransfer_Function::\nsecond_derivative(const distribution<double> & outputs) const\n{\n    int no = outputs.size();\n    distribution<double> result(no);\n    second_derivative(&outputs[0], &result[0], no);\n    return result;\n}\n\n\n/*****************************************************************************/\n/* STANDARD_TRANSFER_FUNCTION                                                */\n/*****************************************************************************/\n\nStandard_Transfer_Function::\nStandard_Transfer_Function(Transfer_Function_Type transfer_function)\n    : transfer_function(transfer_function)\n{\n}\n\nstd::string\nStandard_Transfer_Function::\nprint() const\n{\n    return ML::print(transfer_function);\n}\n\nRange\nStandard_Transfer_Function::\nrange() const\n{\n    static Range ranges[5] = {\n        { -INFINITY, INFINITY, 0.0, false, false, RT_PM_INF },  /* TF_LOGSIG */\n        { -1.0,      1.0,      0.0, true,  true,  RT_PM_ONE },  /* TF_TANH */\n        { -1.7159,   1.7159,   0.0, true,  true,  RT_OTHER  },  /* TF_TANHS */\n        { -INFINITY, INFINITY, 0.0, false, false, RT_PM_INF }, /* TF_IDENTITY */\n        { 0.0,       1.0,      0.5, true,  true,  RT_PROB   }  /* TF_SOFTMAX */};\n\n    BOOST_STATIC_ASSERT(TF_LOGSIG   == 0);\n    BOOST_STATIC_ASSERT(TF_TANH     == 1);\n    BOOST_STATIC_ASSERT(TF_TANHS    == 2);\n    BOOST_STATIC_ASSERT(TF_IDENTITY == 3);\n    BOOST_STATIC_ASSERT(TF_SOFTMAX  == 4);\n    \n    if (transfer_function <= TF_SOFTMAX)\n        return ranges[transfer_function];\n    \n    throw Exception(\"Standard_Transfer_Function::range(): non-standard\");\n}\n\nstd::pair<float, float>\nStandard_Transfer_Function::\ntargets(float maximum) const\n{\n    switch (transfer_function) {\n    case TF_TANH:\n    case TF_IDENTITY: return std::make_pair(-maximum, maximum);\n    case TF_TANHS: return make_pair(-1.0, 1.0);\n    case TF_SOFTMAX:\n    case TF_LOGSIG: return std::make_pair(0.0f, maximum);\n    default:\n        throw Exception(\"Layer::targets(): invalid transfer_function\");\n    }\n}\n\nvoid\nStandard_Transfer_Function::\nserialize(DB::Store_Writer & store) const\n{\n    store << (char)0 // version\n          << transfer_function;\n}\n\nvoid\nStandard_Transfer_Function::\nreconstitute(DB::Store_Reader & store)\n{\n    char version;\n    store >> version;\n    if (version != 0)\n        throw Exception(\"Standard_Transfer_Function::reconstitute(): \"\n                        \"unknown version\");\n    store >> transfer_function;\n}\n\nstd::string\nStandard_Transfer_Function::\nclass_id() const\n{\n    return \"Standard\";\n}\n\nbool\nStandard_Transfer_Function::\nequal(const Transfer_Function & other) const\n{\n    const Standard_Transfer_Function * other_cast\n        = dynamic_cast<const Standard_Transfer_Function *>(&other);\n    if (!other_cast)\n        return false;  // not a standard transfer function...\n\n    return transfer_function == other_cast->transfer_function;\n}\n\ntemplate<typename FloatIn>\nvoid\nStandard_Transfer_Function::\ntransfer(const FloatIn * activation, FloatIn * outputs, int nvals,\n         Transfer_Function_Type transfer_function)\n{\n    switch (transfer_function) {\n    case TF_IDENTITY:\n        std::copy(activation, activation + nvals, outputs);\n        return;\n        \n    case TF_LOGSIG:\n        for (unsigned i = 0;  i < nvals;  ++i) {\n            // See https://bugzilla.redhat.com/show_bug.cgi?id=521190\n            // for why we use double version of exp\n            outputs[i] = 1.0 / (1.0 + exp((double)-activation[i]));\n        }\n        break;\n        \n    case TF_TANH:\n        for (unsigned i = 0;  i < nvals;  ++i)\n            outputs[i] = tanh(activation[i]);\n        break;\n        \n    case TF_TANHS:\n        for (unsigned i = 0;  i < nvals;  ++i)\n            outputs[i] = 1.7159 * tanh(0.66666666666666666666 * activation[i]);\n        break;\n        \n    case TF_SOFTMAX: {\n        double total = 0.0;\n        \n        for (unsigned i = 0;  i < nvals;  ++i) {\n            // See https://bugzilla.redhat.com/show_bug.cgi?id=521190\n            // for why we use double version of exp\n            total += (outputs[i] = exp((double)activation[i]));\n        }\n\n        double factor = 1.0 / total;\n\n        for (unsigned i = 0;  i < nvals;  ++i)\n            outputs[i] *= factor;\n\n        break;\n    }\n\n    default:\n        throw Exception(\"Standard_Transfer_Function::transfer(): invalid transfer_function\");\n    }\n}\n\nvoid\nStandard_Transfer_Function::\ntransfer(const float * activation, float * outputs, size_t n) const\n{\n    transfer(activation, outputs, n, transfer_function);\n}\n\nvoid\nStandard_Transfer_Function::\ntransfer(const double * activation, double * outputs, size_t n) const\n{\n    transfer(activation, outputs, n, transfer_function);\n}\n\ntemplate<typename FloatIn>\nvoid\nStandard_Transfer_Function::\nderivative(const FloatIn * outputs, FloatIn * deriv, int nvals,\n           Transfer_Function_Type transfer_function)\n{\n    switch (transfer_function) {\n\n    case TF_IDENTITY:\n        std::fill(deriv, deriv + nvals, 1.0);\n        break;\n        \n    case TF_LOGSIG:\n        for (unsigned i = 0;  i < nvals;  ++i)\n            deriv[i] = outputs[i] * (1.0 - outputs[i]);\n        break;\n        \n    case TF_TANH:\n        for (unsigned i = 0;  i < nvals;  ++i)\n            deriv[i] = 1.0 - (outputs[i] * outputs[i]);\n        break;\n\n    case TF_TANHS:\n        for (unsigned i = 0;  i < nvals;  ++i)\n            deriv[i] = 1.7159 * 0.6666666666666\n                * (1.0 - (outputs[i] * outputs[i]));\n        break;\n\n    case TF_SOFTMAX:\n        for (unsigned i = 0;  i < nvals;  ++i)\n            deriv[i] = 1.0 / outputs[i];\n        break;\n        \n    default:\n        throw Exception(\"Standard_Transfer_Function::transfer(): invalid transfer_function\");\n    }\n}\n\nvoid\nStandard_Transfer_Function::\nderivative(const float * outputs, float * derivatives, size_t n) const\n{\n    derivative(outputs, derivatives, n, transfer_function);\n}\n\nvoid\nStandard_Transfer_Function::\nderivative(const double * outputs, double * derivatives, size_t n) const\n{\n    derivative(outputs, derivatives, n, transfer_function);\n}\n\ntemplate<typename FloatIn>\nvoid\nStandard_Transfer_Function::\nsecond_derivative(const FloatIn * outputs, FloatIn * deriv, int nvals,\n                  Transfer_Function_Type transfer_function)\n{\n    switch (transfer_function) {\n\n    case TF_IDENTITY:\n        std::fill(deriv, deriv + nvals, 0.0);\n        break;\n        \n    case TF_TANH:\n        for (unsigned i = 0;  i < nvals;  ++i)\n            deriv[i] = -2.0 * outputs[i] * (1.0 - (outputs[i] * outputs[i]));\n        break;\n\n    case TF_TANHS:\n        for (unsigned i = 0;  i < nvals;  ++i)\n            deriv[i] = 1.7159 * 0.6666666666666 * 0.6666666666666\n                * -2.0 * outputs[i] * (1.0 - (outputs[i] * outputs[i]));\n        break;\n\n    case TF_LOGSIG:\n        for (unsigned i = 0;  i < nvals;  ++i)\n            deriv[i] = outputs[i] * (1 - outputs[i]) * (1 - 2 * outputs[i]);\n        break;\n      \n#if 0  \n    case TF_SOFTMAX:\n        for (unsigned i = 0;  i < nvals;  ++i)\n            deriv[i] = ...;\n        break;\n#endif\n        \n    default:\n        throw Exception(\"Standard_Transfer_Function::transfer(): second derivative not implemented \"\n                        \"for this transfer_function \"\n                        + ML::print(transfer_function));\n    }\n}\n\nvoid\nStandard_Transfer_Function::\nsecond_derivative(const float * outputs, float * second_derivatives,\n                  size_t n) const\n{\n    second_derivative(outputs, second_derivatives, n, transfer_function);\n}\n\nvoid\nStandard_Transfer_Function::\nsecond_derivative(const double * outputs, double * second_derivatives,\n                  size_t n) const\n{\n    second_derivative(outputs, second_derivatives, n, transfer_function);\n}\n\nnamespace {\n\nRegister_Factory<Transfer_Function, Standard_Transfer_Function>\n    STF_REGISTER(\"Standard\");\n\n} // file scope\n\n\n\n/*****************************************************************************/\n/* FACTORY                                                                   */\n/*****************************************************************************/\n\nstd::shared_ptr<Transfer_Function>\ncreate_transfer_function(const Transfer_Function_Type & function)\n{\n    return make_sp(new Standard_Transfer_Function(function));\n}\n\nstd::shared_ptr<Transfer_Function>\ncreate_transfer_function(const std::string & name)\n{\n    throw Exception(\"create_transfer_function(name): not implemented\");\n}\n\n\n} // namespace ML\n", "meta": {"hexsha": "228e5c57646478532a285f9fe38ca05379237627", "size": 11083, "ext": "cc", "lang": "C++", "max_stars_repo_path": "jml/neural/transfer_function.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/neural/transfer_function.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/neural/transfer_function.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": 27.230958231, "max_line_length": 100, "alphanum_fraction": 0.5796264549, "num_tokens": 2518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2842121796482642}}
{"text": "/* Copyright (C) 2012,2013 IBM Corp.\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.\n * See the 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 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n#include \"matrix.h\"\n#include <NTL/ZZ.h>\n#include <NTL/lzz_pXFactoring.h>\n#include <cassert>\n#include <cstdio>\n\n\n\n\ntemplate<class type> \nclass SingleBlockMatrix : public  PlaintextBlockMatrixInterface<type> {\npublic:\n  PA_INJECT(type) \n\nprivate:\n  const EncryptedArray& ea;\n\n  Mat<R> data;\n\npublic:\n  SingleBlockMatrix(const EncryptedArray& _ea, const vector<ZZX>& vec) : ea(_ea) { \n    long d = ea.getDegree();\n\n    RBak bak; bak.save(); ea.getContext().alMod.restoreContext();\n\n    data.SetDims(d, d);\n    for (long i = 0; i < d; i++) \n      for (long j = 0; j < d; j++) \n         conv(data[i][j], coeff(vec[i], j));\n  }\n\n  virtual const EncryptedArray& getEA() const {\n    return ea;\n  }\n\n  virtual bool get(Mat<R>& out, long i, long j) const {\n    assert(i >= 0 && i < ea.size());\n    assert(j >= 0 && j < ea.size());\n    if (i != j) return true;\n    out = data;\n    return false;\n  }\n\n};\n\n\n\nPlaintextBlockMatrixBaseInterface *buildSingleBlockMatrix(const EncryptedArray& ea,\n                                                          const vector<ZZX>& vec)\n{\n  switch (ea.getTag()) {\n    case PA_GF2_tag: {\n      return new SingleBlockMatrix<PA_GF2>(ea, vec);\n    }\n\n    case PA_zz_p_tag: {\n      return new SingleBlockMatrix<PA_zz_p>(ea, vec);\n    }\n\n    default: return 0;\n  }\n}\n\n\n\n\n\ntemplate<class type> \nclass MultiBlockMatrix : public  PlaintextBlockMatrixInterface<type> {\npublic:\n  PA_INJECT(type) \n\nprivate:\n  const EncryptedArray& ea;\n\n  Vec< Mat<R> > data;\n\npublic:\n  MultiBlockMatrix(const EncryptedArray& _ea, const vector< vector<ZZX> >& vec) : ea(_ea) { \n    long n = ea.size();\n    long d = ea.getDegree();\n\n    RBak bak; bak.save(); ea.getContext().alMod.restoreContext();\n\n    data.SetLength(n);\n    for (long k = 0; k < n; k++) {\n      data[k].SetDims(d, d);\n      for (long i = 0; i < d; i++) \n        for (long j = 0; j < d; j++) \n           conv(data[k][i][j], coeff(vec[k][i], j));\n    }\n  }\n\n  virtual const EncryptedArray& getEA() const {\n    return ea;\n  }\n\n  virtual bool get(Mat<R>& out, long i, long j) const {\n    assert(i >= 0 && i < ea.size());\n    assert(j >= 0 && j < ea.size());\n    if (i != j) return true;\n    out = data[i];\n    return false;\n  }\n};\n\nPlaintextBlockMatrixBaseInterface *buildMultiBlockMatrix(const EncryptedArray& ea,\n                                                          const vector< vector<ZZX> >& vec)\n{\n  switch (ea.getTag()) {\n    case PA_GF2_tag: {\n      return new MultiBlockMatrix<PA_GF2>(ea, vec);\n    }\n\n    case PA_zz_p_tag: {\n      return new MultiBlockMatrix<PA_zz_p>(ea, vec);\n    }\n\n    default: return 0;\n  }\n}\n\n\n\nvoid  TestIt(long m, long p, long r, long d)\n{\n  cout << \"\\n\\n******** TestIt\" << (isDryRun()? \"(dry run):\" : \":\")\n       << \" m=\" << m \n       << \", p=\" << p\n       << \", r=\" << r\n       << \", d=\" << d\n       << endl;\n\n  FHEcontext context(m, p, r);\n  buildModChain(context, /*L=*/10, /*c=*/2);\n  context.zMStar.printout();\n  cout << endl;\n\n  cout << \"generating keys and key-switching matrices... \" << std::flush;\n  FHESecKey secretKey(context);\n  const FHEPubKey& publicKey = secretKey;\n  secretKey.GenSecKey(/*w=*/64);// A Hamming-weight-w secret key\n  addSome1DMatrices(secretKey); // compute key-switching matrices that we need\n  addFrbMatrices(secretKey); // compute key-switching matrices that we need\n  cout << \"done\\n\";\n\n  ZZX G;\n  if (d == 0) {\n    G = context.alMod.getFactorsOverZZ()[0];\n    d = deg(G);\n  }\n  else\n    G = makeIrredPoly(p, d);\n  cout << \"G = \" << G << \"\\n\";\n  cout << \"computing masks and tables for rotation... \" << std::flush;\n  EncryptedArray ea(context, G);\n  cout << \"done\\n\";\n\n  long nslots = ea.size();\n\n  PlaintextArray p0(ea);\n  PlaintextArray pp0(ea);\n\n  Ctxt c0(publicKey), cc0(publicKey);\n\n  cout << \"\\nTest #1: Apply the same linear transformation to all slots\\n\";\n  {\n  vector<ZZX> LM(d); // LM selects even coefficients\n  for (long j = 0; j < d; j++) \n    if (j % 2 == 0) LM[j] = ZZX(j, 1);\n\n  // \"building\" the linearized-polynomial coefficients\n  vector<ZZX> C;\n  ea.buildLinPolyCoeffs(C, LM);\n\n  p0.random();  \n  ea.encrypt(c0, publicKey, p0);\n  ea.encrypt(cc0, publicKey, p0);\n\n  applyLinPoly1(ea, c0, C);\n  ea.decrypt(c0, secretKey, p0);\n\n  shared_ptr<PlaintextBlockMatrixBaseInterface> mat(buildSingleBlockMatrix(ea, LM));\n  free_mat_mul(ea, cc0, *mat);\n  ea.decrypt(cc0, secretKey, pp0);\n\n  if (pp0.equals(p0))\n    cout << \"GOOD\\n\";\n  else\n    cout << \"BAD\\n\";\n  }\n\n\n  cout << \"\\nTest #2: Apply different transformations to the different slots\\n\";\n  {\n  vector< vector<ZZX> > LM(nslots); \n  // LM[i] rotates the coefficients in the i'th slot by (i % d)\n  for (long i = 0; i < nslots; i++) {\n    LM[i].resize(d);\n    for (long j = 0; j < d; j++)  {\n      long jj = (i+j) % d;\n      LM[i][j] = ZZX(jj, 1);\n    }\n  }\n\n  // \"building\" the linearized-polynomial coefficients\n  vector< vector<ZZX> > C(nslots);\n  for (long i = 0; i < nslots; i++)\n    ea.buildLinPolyCoeffs(C[i], LM[i]);\n\n  p0.random();\n  ea.encrypt(c0, publicKey, p0);\n  ea.encrypt(cc0, publicKey, p0);\n\n  applyLinPolyMany(ea, c0, C); // apply the linearized polynomials\n  ea.decrypt(c0, secretKey, p0);\n\n  shared_ptr<PlaintextBlockMatrixBaseInterface> mat(buildMultiBlockMatrix(ea, LM));\n  free_mat_mul(ea, cc0, *mat);\n  ea.decrypt(cc0, secretKey, pp0);\n\n  if (pp0.equals(p0))\n    cout << \"GOOD\\n\";\n  else\n    cout << \"BAD\\n\";\n  }\n\n  cout << \"\\nTest #3: Testing low-level (cached) implementation\\n\";\n  {\n  vector< vector<ZZX> > LM(nslots); \n  // LM[i] adds coefficients (i % d) and (i+1 % d) in the i'th slot\n  for (long i = 0; i < nslots; i++) {\n    LM[i].resize(d);\n    for (long j = 0; j < d; j++)  {\n      if ( j == (i % d) || j == ((i+1)%d) )\n\tLM[i][j] = conv<ZZX>(1L);\n    }\n  }\n\n  // \"building\" the linearized-polynomial coefficients\n  vector< vector<ZZX> > C(nslots);\n  for (long i = 0; i < nslots; i++)\n    ea.buildLinPolyCoeffs(C[i], LM[i]);\n\n  // \"encoding\" the linearized-polynomial coefficients\n  vector<ZZX> encodedC(d);\n  for (long j = 0; j < d; j++) {\n    vector<ZZX> v(nslots);\n    for (long i = 0; i < nslots; i++) v[i] = C[i][j];\n    ea.encode(encodedC[j], v);\n  }\n\n  p0.random();  \n  ea.encrypt(c0, publicKey, p0);\n  ea.encrypt(cc0, publicKey, p0);\n\n  applyLinPolyLL(c0, encodedC, ea.getDegree()); // apply linearized polynomials\n  ea.decrypt(c0, secretKey, p0);\n\n  shared_ptr<PlaintextBlockMatrixBaseInterface> mat(buildMultiBlockMatrix(ea, LM));\n  free_mat_mul(ea, cc0, *mat);\n  ea.decrypt(cc0, secretKey, pp0);\n\n  if (pp0.equals(p0))\n    cout << \"GOOD\\n\";\n  else\n    cout << \"BAD\\n\";\n  }\n}\n\n\nint main(int argc, char *argv[]) \n{\n  ArgMapping amap;\n\n  bool dry = false;\n  amap.arg(\"dry\", dry, \"dry=1 for a dry-run\");\n\n  long m=91;\n  amap.arg(\"m\", m, \"use specified value as modulus\");\n\n  long p=2;\n  amap.arg(\"p\", p, \"plaintext base\");\n\n  long r=1;\n  amap.arg(\"r\", r,  \"lifting\");\n\n  long d=0;\n  amap.arg(\"d\", d, \"degree of the field extension\");\n  amap.note(\"d == 0 => factors[0] defines extension\");\n\n  amap.parse(argc, argv);\n\n  long repeat = 2;\n  setTimersOn();\n  setDryRun(dry);\n  for (long repeat_cnt = 0; repeat_cnt < repeat; repeat_cnt++) {\n    TestIt(m, p, r, d);\n  }\n\n}\n", "meta": {"hexsha": "9db0139a3369d75a049ce19c9ae1c807508f2118", "size": 7858, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/src/HElib/tlp.cpp", "max_stars_repo_name": "fionser/CODA", "max_stars_repo_head_hexsha": "db234a1e9761d379fb96ae17eef3b77254f8781c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2017-02-24T19:28:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-05T04:40:47.000Z", "max_issues_repo_path": "core/src/HElib/tlp.cpp", "max_issues_repo_name": "fionser/CODA", "max_issues_repo_head_hexsha": "db234a1e9761d379fb96ae17eef3b77254f8781c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-15T03:41:18.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-24T09:06:15.000Z", "max_forks_repo_path": "core/src/HElib/tlp.cpp", "max_forks_repo_name": "fionser/CODA", "max_forks_repo_head_hexsha": "db234a1e9761d379fb96ae17eef3b77254f8781c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-05-14T10:12:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-07T03:50:56.000Z", "avg_line_length": 24.7886435331, "max_line_length": 92, "alphanum_fraction": 0.6044795113, "num_tokens": 2442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.2841456971744161}}
{"text": "#pragma once\n\n#include <algorithm>\n#include <cstddef>\n#include <functional>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include <boost/functional/hash.hpp>\n\nnamespace pyqubo {\n  enum class expression_type {\n    add_operator,\n    mul_operator,\n    binary_variable,\n    spin_variable,\n    place_holder_variable,\n    sub_hamiltonian,\n    constraint,\n    with_penalty,\n    user_defined_expression,\n    numeric_literal\n  };\n\n  class expression {\n  public:\n    virtual ~expression() {\n      ;\n    }\n\n    virtual pyqubo::expression_type expression_type() const noexcept = 0;\n\n    virtual std::string to_string() const noexcept = 0;\n\n    virtual std::size_t hash() const noexcept = 0;\n\n    virtual bool equals(const std::shared_ptr<const expression>& other) const noexcept {\n      return expression_type() == other->expression_type();\n    };\n\n    friend std::hash<expression>;\n  };\n}\n\nnamespace std {\n  template <>\n  struct hash<pyqubo::expression> {\n    auto operator()(const pyqubo::expression& expression) const noexcept {\n      return expression.hash();\n    }\n  };\n}\n\nnamespace pyqubo {\n  class add_operator final : public expression {\n    std::vector<std::shared_ptr<const expression>> _children;\n\n  public:\n    add_operator(const std::shared_ptr<const expression>& lhs, const std::shared_ptr<const expression>& rhs) noexcept : _children{lhs, rhs} {\n      ;\n    }\n\n    const auto& children() const noexcept {\n      return _children;\n    }\n\n    auto add_child(const std::shared_ptr<const expression>& expression) noexcept {\n      _children.emplace_back(expression);\n    }\n\n    pyqubo::expression_type expression_type() const noexcept override {\n      return expression_type::add_operator;\n    }\n\n    std::string to_string() const noexcept override {\n      return \"(\" +\n             std::accumulate(std::begin(_children), std::end(_children), std::string(), [](const auto& acc, const auto& child) {\n               return acc + (std::size(acc) > 0 ? \" + \" : \"\") + child->to_string();\n             }) +\n             \")\";\n    }\n\n    std::size_t hash() const noexcept override {\n      auto result = static_cast<std::size_t>(0);\n\n      boost::hash_combine(result, \"+\");\n\n      for (const auto& child : _children) {\n        boost::hash_combine(result, std::hash<expression>()(*child));\n      }\n\n      return result;\n    }\n\n    bool equals(const std::shared_ptr<const expression>& other) const noexcept override {\n      if (!expression::equals(other)) {\n        return false;\n      }\n\n      const auto& other_add_operator = std::static_pointer_cast<const add_operator>(other);\n\n      if (std::size(_children) != std::size(other_add_operator->_children)) {\n        return false;\n      }\n\n      for (auto i = 0; i < static_cast<int>(std::size(_children)); ++i) {\n        if (!_children[i]->equals(other_add_operator->_children[i])) {\n          return false;\n        }\n      }\n\n      return true;\n    }\n  };\n\n  class mul_operator final : public expression {\n    std::shared_ptr<const expression> _lhs;\n    std::shared_ptr<const expression> _rhs;\n\n  public:\n    mul_operator(const std::shared_ptr<const expression>& lhs, const std::shared_ptr<const expression>& rhs) noexcept : _lhs(lhs), _rhs(rhs) {\n      ;\n    }\n\n    const auto& lhs() const noexcept {\n      return _lhs;\n    }\n\n    const auto& rhs() const noexcept {\n      return _rhs;\n    }\n\n    pyqubo::expression_type expression_type() const noexcept override {\n      return expression_type::mul_operator;\n    }\n\n    std::string to_string() const noexcept override {\n      return \"(\" + lhs()->to_string() + \" * \" + rhs()->to_string() + \")\";\n    }\n\n    std::size_t hash() const noexcept override {\n      auto result = static_cast<std::size_t>(0);\n\n      boost::hash_combine(result, \"*\");\n      boost::hash_combine(result, std::hash<expression>()(*_lhs));\n      boost::hash_combine(result, std::hash<expression>()(*_rhs));\n\n      return result;\n    }\n\n    bool equals(const std::shared_ptr<const expression>& other) const noexcept override {\n      return expression::equals(other) && _lhs->equals(std::static_pointer_cast<const mul_operator>(other)->_lhs) && _rhs->equals(std::static_pointer_cast<const mul_operator>(other)->_rhs);\n    }\n  };\n\n  class variable : public expression {\n    std::string _name;\n\n  protected:\n    variable(const std::string& name) noexcept : _name(name) {\n      ;\n    }\n\n  public:\n    const auto& name() const noexcept {\n      return _name;\n    }\n\n    std::size_t hash() const noexcept override {\n      return std::hash<std::string>()(_name);\n    }\n\n    bool equals(const std::shared_ptr<const expression>& other) const noexcept override {\n      return expression::equals(other) && _name == std::static_pointer_cast<const variable>(other)->_name;\n    }\n  };\n\n  class binary_variable final : public variable {\n  public:\n    binary_variable(const std::string& name) noexcept : variable(name) {\n      ;\n    }\n\n    pyqubo::expression_type expression_type() const noexcept override {\n      return expression_type::binary_variable;\n    }\n\n    std::string to_string() const noexcept override {\n      return \"Binary('\" + name() + \"')\";\n    }\n\n    std::size_t hash() const noexcept override {\n      auto result = variable::hash();\n\n      boost::hash_combine(result, \"binary_variable\");\n\n      return result;\n    }\n  };\n\n  class spin_variable final : public variable {\n  public:\n    spin_variable(const std::string& name) noexcept : variable(name) {\n      ;\n    }\n\n    pyqubo::expression_type expression_type() const noexcept override {\n      return expression_type::spin_variable;\n    }\n\n    std::string to_string() const noexcept override {\n      return \"Spin('\" + name() + \"')\";\n    }\n\n    std::size_t hash() const noexcept override {\n      auto result = variable::hash();\n\n      boost::hash_combine(result, \"spin_variable\");\n\n      return result;\n    }\n  };\n\n  class placeholder_variable final : public variable {\n  public:\n    placeholder_variable(const std::string& name) noexcept : variable(name) {\n      ;\n    }\n\n    pyqubo::expression_type expression_type() const noexcept override {\n      return expression_type::place_holder_variable;\n    }\n\n    std::string to_string() const noexcept override {\n      return \"Placeholder('\" + name() + \"')\";\n    }\n\n    std::size_t hash() const noexcept override {\n      auto result = variable::hash();\n\n      boost::hash_combine(result, \"placeholder_variable\");\n\n      return result;\n    }\n  };\n\n  class sub_hamiltonian : public variable {\n    std::shared_ptr<const expression> _expression;\n\n  public:\n    sub_hamiltonian(const std::shared_ptr<const pyqubo::expression>& expression, const std::string& name) noexcept : variable(name), _expression(expression) {\n      ;\n    }\n\n    const auto& expression() const noexcept {\n      return _expression;\n    }\n\n    pyqubo::expression_type expression_type() const noexcept override {\n      return expression_type::sub_hamiltonian;\n    }\n\n    std::string to_string() const noexcept override {\n      return \"SubH(\" + _expression->to_string() + \", '\" + name() + \"')\";\n    }\n\n    std::size_t hash() const noexcept override {\n      auto result = variable::hash();\n\n      boost::hash_combine(result, \"sub_hamiltonian\");\n      boost::hash_combine(result, std::hash<pyqubo::expression>()(*_expression));\n\n      return result;\n    }\n\n    bool equals(const std::shared_ptr<const pyqubo::expression>& other) const noexcept override {\n      return variable::equals(other) && _expression->equals(std::static_pointer_cast<const sub_hamiltonian>(other)->_expression);\n    }\n  };\n\n  class constraint final : public sub_hamiltonian {\n    std::function<bool(double)> _condition;\n\n  public:\n    constraint(\n        const std::shared_ptr<const pyqubo::expression>& expression, const std::string& name, const std::function<bool(double)>& condition) noexcept : sub_hamiltonian(expression, name), _condition(condition) {\n      ;\n    }\n\n    const auto& condition() const noexcept {\n      return _condition;\n    }\n\n    pyqubo::expression_type expression_type() const noexcept override {\n      return expression_type::constraint;\n    }\n\n    std::string to_string() const noexcept override {\n      return \"Constraint(\" + expression()->to_string() + \", '\" + name() + \"')\"; // conditionは文字列化できない……。\n    }\n\n    std::size_t hash() const noexcept override {\n      auto result = variable::hash();\n\n      boost::hash_combine(result, \"constraint\");\n\n      return result;\n    }\n  };\n\n  class with_penalty : public sub_hamiltonian {\n    std::shared_ptr<const pyqubo::expression> _penalty;\n\n  public:\n    with_penalty(const std::shared_ptr<const pyqubo::expression>& expression, const std::shared_ptr<const pyqubo::expression>& penalty, const std::string& name) noexcept : sub_hamiltonian(expression, name), _penalty(penalty) {\n      ;\n    }\n\n    const auto& penalty() const noexcept {\n      return _penalty;\n    }\n\n    pyqubo::expression_type expression_type() const noexcept override {\n      return expression_type::with_penalty;\n    }\n\n    std::string to_string() const noexcept override {\n      return \"WithPenalty(\" + expression()->to_string() + \", \" + _penalty->to_string() + \", '\" + name() + \"')\";\n    }\n\n    std::size_t hash() const noexcept override {\n      auto result = sub_hamiltonian::hash();\n\n      boost::hash_combine(result, \"with_penalty\");\n      boost::hash_combine(result, std::hash<pyqubo::expression>()(*_penalty));\n\n      return result;\n    }\n\n    bool equals(const std::shared_ptr<const pyqubo::expression>& other) const noexcept override {\n      return sub_hamiltonian::equals(other) && _penalty->equals(std::static_pointer_cast<const with_penalty>(other)->_penalty);\n    }\n  };\n\n  class user_defined_expression : public expression {\n    std::shared_ptr<const expression> _expression;\n\n  public:\n    user_defined_expression(const std::shared_ptr<const pyqubo::expression>& expression) noexcept : _expression(expression) {\n      ;\n    }\n\n    auto expression() const noexcept {\n      return _expression;\n    }\n\n    pyqubo::expression_type expression_type() const noexcept override {\n      return expression_type::user_defined_expression;\n    }\n\n    std::string to_string() const noexcept override {\n      return _expression->to_string();\n    }\n\n    std::size_t hash() const noexcept override {\n      return std::hash<pyqubo::expression>()(*_expression);\n    }\n\n    bool equals(const std::shared_ptr<const pyqubo::expression>& other) const noexcept override {\n      return expression::equals(other) && _expression->equals(std::static_pointer_cast<const user_defined_expression>(other)->_expression);\n    }\n  };\n\n  class numeric_literal final : public expression {\n    double _value;\n\n  public:\n    numeric_literal(double value) noexcept : _value(value) {\n      ;\n    }\n\n    auto value() const noexcept {\n      return _value;\n    }\n\n    pyqubo::expression_type expression_type() const noexcept override {\n      return expression_type::numeric_literal;\n    }\n\n    std::string to_string() const noexcept override {\n      return std::to_string(_value);\n    }\n\n    std::size_t hash() const noexcept override {\n      return std::hash<double>()(_value);\n    }\n\n    bool equals(const std::shared_ptr<const expression>& other) const noexcept override {\n      return expression::equals(other) && _value == std::static_pointer_cast<const numeric_literal>(other)->_value;\n    }\n  };\n\n  inline std::shared_ptr<const expression> operator+(const std::shared_ptr<const expression>& lhs, const std::shared_ptr<const expression>& rhs) noexcept {\n    if (lhs->expression_type() == expression_type::numeric_literal && rhs->expression_type() == expression_type::numeric_literal) {\n      return std::make_shared<numeric_literal>(std::static_pointer_cast<const numeric_literal>(lhs)->value() + std::static_pointer_cast<const numeric_literal>(rhs)->value());\n    }\n\n    if (lhs->expression_type() == expression_type::numeric_literal && std::static_pointer_cast<const numeric_literal>(lhs)->value() == 0) {\n      return rhs;\n    }\n\n    if (rhs->expression_type() == expression_type::numeric_literal && std::static_pointer_cast<const numeric_literal>(rhs)->value() == 0) {\n      return lhs;\n    }\n\n    return std::make_shared<const add_operator>(lhs, rhs);\n  }\n\n  inline std::shared_ptr<const expression> operator*(const std::shared_ptr<const expression>& lhs, const std::shared_ptr<const expression>& rhs) noexcept {\n    if (lhs->expression_type() == expression_type::numeric_literal && rhs->expression_type() == expression_type::numeric_literal) {\n      return std::make_shared<numeric_literal>(std::static_pointer_cast<const numeric_literal>(lhs)->value() * std::static_pointer_cast<const numeric_literal>(rhs)->value());\n    }\n\n    if (lhs->expression_type() == expression_type::numeric_literal && std::static_pointer_cast<const numeric_literal>(lhs)->value() == 1) {\n      return rhs;\n    }\n\n    if (rhs->expression_type() == expression_type::numeric_literal && std::static_pointer_cast<const numeric_literal>(rhs)->value() == 1) {\n      return lhs;\n    }\n\n    return std::make_shared<const mul_operator>(lhs, rhs);\n  }\n\n  template <typename Result, typename Functor>\n  Result visit(Functor& functor, const std::shared_ptr<const expression>& expression) noexcept {\n    switch (expression->expression_type()) {\n    case expression_type::add_operator:\n      return functor(std::static_pointer_cast<const add_operator>(expression));\n\n    case expression_type::mul_operator:\n      return functor(std::static_pointer_cast<const mul_operator>(expression));\n\n    case expression_type::binary_variable:\n      return functor(std::static_pointer_cast<const binary_variable>(expression));\n\n    case expression_type::spin_variable:\n      return functor(std::static_pointer_cast<const spin_variable>(expression));\n\n    case expression_type::place_holder_variable:\n      return functor(std::static_pointer_cast<const placeholder_variable>(expression));\n\n    case expression_type::sub_hamiltonian:\n      return functor(std::static_pointer_cast<const sub_hamiltonian>(expression));\n\n    case expression_type::constraint:\n      return functor(std::static_pointer_cast<const constraint>(expression));\n\n    case expression_type::with_penalty:\n      return functor(std::static_pointer_cast<const with_penalty>(expression));\n\n    case expression_type::user_defined_expression:\n      return functor(std::static_pointer_cast<const user_defined_expression>(expression));\n\n    case expression_type::numeric_literal:\n      return functor(std::static_pointer_cast<const numeric_literal>(expression));\n\n    default:\n      throw std::runtime_error(\"invalid expression type.\"); // ここには絶対に来ないはず。\n    }\n  }\n}\n", "meta": {"hexsha": "d4df0de2732c4698adf23bbee37511ac45fe1255", "size": 14594, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/abstract_syntax_tree.hpp", "max_stars_repo_name": "tail-island/pyqubo", "max_stars_repo_head_hexsha": "29974dbef0b14a4fcf26bc9b4669045eaf374186", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 124.0, "max_stars_repo_stars_event_min_datetime": "2018-09-21T06:50:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T07:56:49.000Z", "max_issues_repo_path": "src/abstract_syntax_tree.hpp", "max_issues_repo_name": "tail-island/pyqubo", "max_issues_repo_head_hexsha": "29974dbef0b14a4fcf26bc9b4669045eaf374186", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 107.0, "max_issues_repo_issues_event_min_datetime": "2018-09-21T16:45:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T10:34:55.000Z", "max_forks_repo_path": "src/abstract_syntax_tree.hpp", "max_forks_repo_name": "tail-island/pyqubo", "max_forks_repo_head_hexsha": "29974dbef0b14a4fcf26bc9b4669045eaf374186", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2018-09-21T19:51:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T20:45:31.000Z", "avg_line_length": 30.7890295359, "max_line_length": 226, "alphanum_fraction": 0.6760312457, "num_tokens": 3239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.2841456971744161}}
{"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#ifndef MTL_OPERATION_EXTENDED_COMPLEX_INCLUDE\n#define MTL_OPERATION_EXTENDED_COMPLEX_INCLUDE\n\n#include <complex>\n#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits/is_unsigned.hpp>\n#include <boost/numeric/mtl/utility/different_non_complex.hpp>\n#include <boost/numeric/mtl/utility/extended_complex.hpp>\n\n\n// Now we dare writing in the standard namespace\nnamespace std {\n\n// ========\n// Addition\n// ========\n\ntemplate <typename T, typename U>\ntypename mtl::traits::extended_complex<T, U>::type // implicit enable_if\ninline operator+(const T& x, const complex<U>& y)\n{\n    typedef typename mtl::traits::extended_complex<T, U>::type type;\n    return type(x + real(y), imag(y));\n}\n\ntemplate <typename T, typename U>\ntypename mtl::traits::extended_complex<T, U>::type // implicit enable_if\ninline operator+(const complex<T>& x, const U& y)\n{\n    typedef typename mtl::traits::extended_complex<T, U>::type type;\n    return type(real(x) + y, imag(x));\n}\n\ntemplate <typename T, typename U>\ntypename mtl::traits::extended_complex<T, U>::type // implicit enable_if\ninline operator+(const complex<T>& x, const complex<U>& y)\n{\n    typedef typename mtl::traits::extended_complex<T, U>::type type;\n    return type(real(x) + real(y), imag(x) + imag(y));\n}\n\n// ===========\n// Subtraction\n// ===========\n\nnamespace detail {\n    \n    // To avoid stupid warnings on unary - for unsigned int specialize it\n    template <typename T>\n    typename boost::disable_if<boost::is_unsigned<T>, T>::type\n    inline negate_helper(const T& x) \n    { return -x; }\n\n    template <typename T>\n    typename boost::enable_if<boost::is_unsigned<T>, T>::type\n    inline negate_helper(const T& x) \n    { return T(0) - x; }\n}\n\ntemplate <typename T, typename U>\ntypename mtl::traits::extended_complex<T, U>::type // implicit enable_if\ninline operator-(const T& x, const complex<U>& y)\n{\n    typedef typename mtl::traits::extended_complex<T, U>::type type;\n    return type(x - real(y), detail::negate_helper(imag(y))); // see above for helper\n}\n\ntemplate <typename T, typename U>\ntypename mtl::traits::extended_complex<T, U>::type // implicit enable_if\ninline operator-(const complex<T>& x, const U& y)\n{\n    typedef typename mtl::traits::extended_complex<T, U>::type type;\n    return type(real(x) - y, imag(x));\n}\n\ntemplate <typename T, typename U>\ntypename mtl::traits::extended_complex<T, U>::type // implicit enable_if\ninline operator-(const complex<T>& x, const complex<U>& y)\n{\n    typedef typename mtl::traits::extended_complex<T, U>::type type;\n    return type(real(x) - real(y), imag(x) - imag(y));\n}\n\n// ==============\n// Multiplication\n// ==============\n\ntemplate <typename T, typename U>\ntypename mtl::traits::extended_complex<T, U>::type // implicit enable_if\ninline operator*(const T& x, const complex<U>& y)\n{\n    typedef typename mtl::traits::extended_complex<T, U>::type type;\n    return type(x * real(y), x * imag(y));\n}\n\ntemplate <typename T, typename U>\ntypename mtl::traits::extended_complex<T, U>::type // implicit enable_if\ninline operator*(const complex<T>& x, const U& y)\n{\n    typedef typename mtl::traits::extended_complex<T, U>::type type;\n    return type(real(x) * y, imag(x) * y);\n}\n\ntemplate <typename T, typename U>\ntypename mtl::traits::extended_complex<T, U>::type // implicit enable_if\ninline operator*(const complex<T>& x, const complex<U>& y)\n{\n    typedef typename mtl::traits::extended_complex<T, U>::type type;\n    return type(real(x) * real(y) - imag(x) * imag(y),\n\t\treal(x) * imag(y) + imag(x) * real(y));\n}\n\n// ========\n// Division\n// ========\n// Not necessarily the most efficient implementations\n// Dealing primarily with types\n\ntemplate <typename T, typename U>\ntypename mtl::traits::extended_complex<T, U>::type // implicit enable_if\ninline operator/(const T& x, const complex<U>& y)\n{\n    typedef typename mtl::traits::extended_complex<T, U>::type type;\n    type r(x);\n    return r/= type(real(y), imag(y));    \n}\n\ntemplate <typename T, typename U>\ntypename mtl::traits::extended_complex<T, U>::type // implicit enable_if\ninline operator/(const complex<T>& x, const U& y)\n{\n    typedef typename mtl::traits::extended_complex<T, U>::type type;\n    return type(real(x) / y, imag(x) / y);\n}\n\ntemplate <typename T, typename U>\ntypename mtl::traits::extended_complex<T, U>::type // implicit enable_if\ninline operator/(const complex<T>& x, const complex<U>& y)\n{\n    typedef typename mtl::traits::extended_complex<T, U>::type type;\n    type r(real(x), imag(x));\n    return r/= type(real(y), imag(y));    \n}\n\n     \n// ==========\n// Comparison\n// ==========\n\ntemplate <typename T, typename U>\ntypename boost::enable_if<mtl::traits::different_non_complex<T, U>, bool>::type\ninline operator==(const complex<T>& x, const U& y)\n{\n    return real(x) == y && imag(x) == T(0);\n}\n\ntemplate <typename T, typename U>\ntypename boost::enable_if<mtl::traits::different_non_complex<T, U>, bool>::type\ninline operator==(const T& x, const complex<U>& y)\n{\n    return x == real(y) && imag(y) == T(0);\n}\n\ntemplate <typename T, typename U>\ntypename boost::enable_if<mtl::traits::different_non_complex<T, U>, bool>::type\ninline operator==(const complex<T>& x, const complex<U>& y)\n{\n    return real(x) == real(y) && imag(x) == imag(y);\n}\n\ntemplate <typename T, typename U>\ntypename boost::enable_if<mtl::traits::different_non_complex<T, U>, bool>::type\ninline operator!=(const complex<T>& x, const U& y)\n{\n    return real(x) != y || imag(x) != T(0);\n}\n\ntemplate <typename T, typename U>\ntypename boost::enable_if<mtl::traits::different_non_complex<T, U>, bool>::type\ninline operator!=(const T& x, const complex<U>& y)\n{\n    return x != real(y) || imag(y) != T(0);\n}\n\ntemplate <typename T, typename U>\ntypename boost::enable_if<mtl::traits::different_non_complex<T, U>, bool>::type\ninline operator!=(const complex<T>& x, const complex<U>& y)\n{\n    return real(x) != real(y) || imag(x) != imag(y);\n}\n\n} // namespace std\n\n#endif // MTL_OPERATION_EXTENDED_COMPLEX_INCLUDE\n", "meta": {"hexsha": "2b79001c3b81a9593238614681f075560bc20df5", "size": 6409, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/extended_complex.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/mtl/operation/extended_complex.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/mtl/operation/extended_complex.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": 30.961352657, "max_line_length": 94, "alphanum_fraction": 0.6771727259, "num_tokens": 1667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.28414568103132615}}
{"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#include \"AlgebraTools.hpp\"\n#include \"SiconosMatrix.hpp\"\n#include <boost/numeric/ublas/io.hpp>\n#include \"expm.hpp\"\n\nnamespace Siconos {\n  namespace algebra {\n    namespace tools {\n\n      void expm(SiconosMatrix& A, SiconosMatrix& Exp, bool computeAndAdd)\n      {\n        // Implemented only for dense matrices.\n        // Note FP : Maybe it works for others but it has not been\n        // tested here --> to be done\n        // Do not work with sparse.\n        A.resetLU();\n        Exp.resetLU();\n        assert(Exp.num() == 1 || A.num() == 1);\n        if(computeAndAdd)\n          *Exp.dense() += expm_pad(*A.dense());\n        else\n          *Exp.dense() = expm_pad(*A.dense());\n      }\n    } // namespace tools\n  } // namespace algebra\n} // namespace Siconos\n", "meta": {"hexsha": "33d297001bed6094878db29599025f1c324b92f3", "size": 1451, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosAlgebra/AlgebraTools.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/utils/SiconosAlgebra/AlgebraTools.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/utils/SiconosAlgebra/AlgebraTools.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": 32.2444444444, "max_line_length": 75, "alphanum_fraction": 0.6623018608, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2840632645836593}}
{"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 <vector>\n#include <string>\n#include <map>\n\n#include <boost/lexical_cast.hpp>\n\n#include \"main.hpp\"\n\n#include <hashclash/timer.hpp>\n#include <hashclash/saveload_bz2.hpp>\n#include <hashclash/sha1detail.hpp>\n#include <hashclash/sha1differentialpath.hpp>\n#include <hashclash/booleanfunction.hpp>\n\n\nusing namespace hashclash;\nusing namespace std;\n\nbooleanfunction* sha1bf(unsigned t)\n{\n\tif (t < 20) return &SHA1_F1_data;\n\telse if (t < 40) return &SHA1_F2_data;\n\telse if (t < 60) return &SHA1_F3_data;\n\treturn &SHA1_F4_data;\n}\n\n#define CHECK_TUNNEL_BITCONDITION(tc,pc) \\\n\tif (tc != bc_constant) { \\\n\t\tif (tc == bc_one && (pc == bc_zero || pc == bc_plus)) continue; \\\n\t\tif (tc == bc_zero && (pc == bc_one || pc == bc_minus)) continue; \\\n\t}\n\t\ninline void connect_helper(unsigned val, unsigned diff, bitcondition& cond, uint32& out, uint32 in, unsigned b)\n{\n\tif (val == 0) {\n\t\tif (diff) {\n\t\t\tcond = bc_minus;\n\t\t\tout = in + (1<<b);\n\t\t} else {\n\t\t\tcond = bc_constant;\n\t\t\tout = in;\n\t\t}\n\t} else {\n\t\tcond = bc_plus;\n\t\tout = in - (1<<b);\n\t}\n}\ninline void connect_helper(unsigned val, unsigned diff, uint32& out, uint32 in, unsigned b)\n{\n\tif (val == 0) {\n\t\tif (diff)\n\t\t\tout = in + (1<<b);\n\t\telse\n\t\t\tout = in;\n\t} else\n\t\tout = in - (1<<b);\n}\ninline bitcondition connect_helper(unsigned val, unsigned diff)\n{\n\tif (val == 0) {\n\t\tif (diff)\n\t\t\treturn bc_minus;\n\t\telse\n\t\t\treturn bc_constant;\n\t} else\n\t\treturn bc_plus;\n}\n\n\ntemplate<int steps, bool storefdata, bool storenewconds, bool compmincond>\nvoid sha1_connect_thread::connectbits_01234(const pair<connect_bitdata,unsigned>& in2, map<connect_bitdata,unsigned>& out, \n\t\t\t\t unsigned b, const sha1differentialpath& lower, const sha1differentialpath& upper, \n\t\t\t\t vector< pair<byteconditions,byteconditions> >& newconds, vector<connect_bitdata>& outdata, vector<unsigned>& outmincond)\n{\n\tconst connect_bitdata& in = in2.first;\n\tconst unsigned b0 = b;\n\tconst unsigned b1 = (b+30)&31;\n\tconst unsigned b2 = (b+28)&31;\n\tconst unsigned b3 = (b+26)&31;\n\tconst unsigned b4 = (b+24)&31;\n/*\t connect_bitdata result;\n\t bf_outcome bfo0, bfo1, bfo2, bfo3, bfo4;\n\t bf_conditions bfc0, bfc1, bfc2, bfc3, bfc4;\n\t bitcondition Qtm3b, Qtm2b, Qtm1b, Qtb, Qtp1b, Qtp2b, Qtp3b;\n\t uint32 dft, dftp1, dftp2, dftp3, dftp4;\n\t pair<byteconditions,byteconditions> newcond;\n\t bitcondition Ttm3b, Ttm2b, Ttm1b, Ttb, Ttp1b, Ttp2b, Ttp3b;\n*/\tTtm3b = tbc(t-3,(b0+2)&31);\n\tTtm2b = tbc(t-2,(b0+2)&31);\n\tTtm1b = tbc(t-1,b0);\n\tTtb = tbc(t, b1);\n\tTtp1b = tbc(t+1, b2);\n\tTtp2b = tbc(t+2, b3);\n\tTtp3b = tbc(t+3, b4);\n\t\n\t//update the running bitconditions\n\tresult = in;\n\tresult.rqtm2[1] = result.rqtm2[0];\n\tresult.rqtm1[1] = result.rqtm1[0];\n\tresult.rqt[1] = result.rqt[0];\n\tresult.rqtp1[1] = result.rqtp1[0];\n\n\tQtm3b = lower(t-3,(b0+2)&31);\n\tQtm2b = lower(t-2,(b0+2)&31);\n\tQtp2b = upper(t+2,b3); if (Qtp2b == bc_prev) { Qtp2b = bc_constant; } //if (storenewconds) throw; }\n\tQtp3b = upper(t+3,b4); if (Qtp3b == bc_prev) { Qtp3b = bc_constant; } //if (storenewconds) throw; }\n\tunsigned dQtm1bit = (in.dQtm1>>b0)&1;\n\tunsigned dQtbit = (in.dQt>>b1)&1;\n\tunsigned dQtp1bit = (in.dQtp1>>b2)&1;\n\tunsigned mmtbit = (mmaskt>>b0)&1;\n\tunsigned mmtp1bit = (mmasktp1>>b1)&1;\n\tunsigned mmtp2bit = (mmasktp2>>b2)&1;\n\tunsigned mmtp3bit = (mmasktp3>>b3)&1;\n\tunsigned mmtp4bit = (mmasktp4>>b4)&1;\n\tfor (unsigned dqtm1 = 0; dqtm1 <= dQtm1bit; ++dqtm1) {\n\t\tconnect_helper(dqtm1, dQtm1bit, Qtm1b, result.dQtm1, in.dQtm1, b0);\n\t\tif (b0 == 1 && result.dQtm1 != dQtm1b2b31) continue;\n\t\tif (b0 == 26 && result.dQtm1 != dQtm1b27b31) continue;\n\t\tif (b0 == 31 && (Qtm1b == Qtm1b31not || Qtm1b == Qtm1b31not2)) continue;\n\t\tif (b0 == 31)\n\t\t\tbfo0 = msb_bf_outcome(*Ft, Qtm1b, Qtm2b, Qtm3b);\n\t\telse\n\t\t\tbfo0 = Ft->outcome(Qtm1b, Qtm2b, Qtm3b);\t\t\t\n\t\tfor (unsigned bfo0index = 0; bfo0index < bfo0.size(); ++bfo0index) {\n\t\t\tdft = in.dFt - bfo0(bfo0index, b0);\n\t\t\tfor (unsigned mmt = 0; mmt <= mmtbit; ++mmt) {\n\t\t\t\tif (mmt == 1 && b0 == 31) continue;\n\t\t\t\tconnect_helper(mmt, mmtbit, result.dFt, dft, b0);\n\t\t\t\tif (result.dFt & (1<<b0)) continue;\n\t\t\t\tif (b0 == 31)\n\t\t\t\t\tbfc0 = msb_bf_forwardconditions(*Ft, Qtm1b, Qtm2b, Qtm3b, bfo0[bfo0index]);\n\t\t\t\telse\n\t\t\t\t\tbfc0 = Ft->forwardconditions(Qtm1b, Qtm2b, Qtm3b, bfo0[bfo0index]);\n\t\t\t\tif ((Qtm1freemask & (1<<b0)) && bfc0.first != bc_constant) continue;\n\t\t\t\tif ((Qtm2freemask & (1<<((b0+2)&31))) && bfc0.second != bc_constant) continue;\n\t\t\t\tif ((Qtm3freemask & (1<<((b0+2)&31))) && bfc0.third != bc_constant) continue;\n\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttm3b,bfc0.third);\n\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttm2b,bfc0.second);\n\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttm1b,bfc0.first);\n\t\t\t\tresult.rqtm2[0] = bfc0.second;\t\t\t\t\n\t\t\t\tif (steps == 1) {\n\t\t\t\t\tif (storefdata) result.fqtm1[b0] = bfc0.first;\n\t\t\t\t\tif (storenewconds) {\n\t\t\t\t\t\tnewcond.first.set(bc_constant, bc_constant, bc_constant, bc_constant, bc_constant, bc_constant, bfc0.third);\n\t\t\t\t\t\tnewcond.second.set(bc_constant, bc_constant, bc_constant, bc_constant, connect_helper(mmt, mmtbit) );\n\t\t\t\t\t\tnewconds.push_back(newcond);\n\t\t\t\t\t\toutdata.push_back(result);\n\t\t\t\t\t\tunsigned curcond = in2.second + (bfc0.third==bc_constant?0:1);\n\t\t\t\t\t\toutmincond.push_back(curcond);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tif (compmincond)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tunsigned curcond = in2.second + (bfc0.third==bc_constant?0:1);\n\t\t\t\t\t\t\tauto itb = out.insert(make_pair(result,curcond));\n\t\t\t\t\t\t\tif (!itb.second && curcond < itb.first->second)\n\t\t\t\t\t\t\t\titb.first->second = curcond;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tout[result];\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tusedFtp1 = true;\n\t\t\t\tfor (unsigned dqt = 0; dqt <= dQtbit; ++dqt) {\n\t\t\t\t\tconnect_helper(dqt, dQtbit, Qtb, result.dQt, in.dQt, b1);\n\t\t\t\t\tif (b1 == 1 && result.dQt != dQtb2b31) continue;\n\t\t\t\t\tif (b1 == 26 && result.dQt != dQtb27b31) continue;\n\t\t\t\t\tif (b1 == 31 && (Qtb == Qtb31not || Qtb == Qtb31not2)) continue;\n\t\t\t\t\tif (b1 == 31) \n\t\t\t\t\t\tbfo1 = msb_bf_outcome(*Ftp1, Qtb, bfc0.first, in.rqtm2[1]);\n\t\t\t\t\telse\n\t\t\t\t\t\tbfo1 = Ftp1->outcome(Qtb, bfc0.first, in.rqtm2[1]);\n\t\t\t\t\tfor (unsigned bfo1index = 0; bfo1index < bfo1.size(); ++bfo1index) {\n\t\t\t\t\t\tdftp1 = in.dFtp1 - bfo1(bfo1index, b1);\n\t\t\t\t\t\tfor (unsigned mmtp1 = 0; mmtp1 <= mmtp1bit; ++mmtp1) {\n\t\t\t\t\t\t\tconnect_helper(mmtp1, mmtp1bit, result.dFtp1, dftp1, b1);\n\t\t\t\t\t\t\tif (mmtp1 == 1 && b1 == 31) continue;\n\t\t\t\t\t\t\tif (result.dFtp1 & (1<<b1)) continue;\n\t\t\t\t\t\t\tif (b1 == 31)\n\t\t\t\t\t\t\t\tbfc1 = msb_bf_forwardconditions(*Ftp1, Qtb, bfc0.first, in.rqtm2[1], bfo1[bfo1index]);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tbfc1 = Ftp1->forwardconditions(Qtb, bfc0.first, in.rqtm2[1], bfo1[bfo1index]);\n\t\t\t\t\t\t\tif ((Qtfreemask & (1<<b1)) && bfc1.first != bc_constant) continue;\n\t\t\t\t\t\t\tif ((Qtm1freemask & (1<<b0)) && bfc1.second != bc_constant) continue;\n\t\t\t\t\t\t\tif ((Qtm2freemask & (1<<b0)) && bfc1.third != bc_constant) continue;\n\t\t\t\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttm1b,bfc1.second);\n\t\t\t\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttb,bfc1.first);\n\t\t\t\t\t\t\tresult.rqtm1[0] = bfc1.second;\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (steps == 2) {\n\t\t\t\t\t\t\t\tif (storefdata) result.fqt[b1] = bfc1.first;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif (storenewconds) \n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tnewcond.first.set(bc_constant, bc_constant, bc_constant, bc_constant, bc_constant, bfc1.third, bfc0.third);\n\t\t\t\t\t\t\t\t\tnewcond.second.set(bc_constant, bc_constant, bc_constant, connect_helper(mmtp1, mmtp1bit), connect_helper(mmt, mmtbit) );\n\t\t\t\t\t\t\t\t\tnewconds.push_back(newcond);\n\t\t\t\t\t\t\t\t\toutdata.push_back(result);\n\t\t\t\t\t\t\t\t\tunsigned curcond = in2.second + (bfc0.third==bc_constant?0:1) + (bfc1.third==bc_constant?0:1);\n\t\t\t\t\t\t\t\t\toutmincond.push_back(curcond);\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\tif (compmincond)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tunsigned curcond = in2.second + (bfc0.third==bc_constant?0:1) + (bfc1.third==bc_constant?0:1);\n\t\t\t\t\t\t\t\t\t\tauto itb = out.insert(make_pair(result,curcond));\n\t\t\t\t\t\t\t\t\t\tif (!itb.second && curcond < itb.first->second)\n\t\t\t\t\t\t\t\t\t\t\titb.first->second = curcond;\n\t\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t\t\telse \n\t\t\t\t\t\t\t\t\t\tout[result];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\t\t\t\t\t\t\t\n\n\t\t\t\t\t\t\tusedFtp2 = true;\n\t\t\t\t\t\t\tfor (unsigned dqtp1 = 0; dqtp1 <= dQtp1bit; ++dqtp1) {\n\t\t\t\t\t\t\t\tconnect_helper(dqtp1, dQtp1bit, Qtp1b, result.dQtp1, in.dQtp1, b2);\n\t\t\t\t\t\t\t\tif (b2 == 1 && result.dQtp1 != dQtp1b2b31) continue;\n\t\t\t\t\t\t\t\tif (b2 == 26 && result.dQtp1 != dQtp1b27b31) continue;\n\t\t\t\t\t\t\t\tif (b2 == 31 && (Qtp1b == Qtp1b31not || Qtp1b == Qtp1b31not2)) continue;\n\t\t\t\t\t\t\t\tif (b2 == 31)\n\t\t\t\t\t\t\t\t\tbfo2 = msb_bf_outcome(*Ftp2, Qtp1b, bfc1.first, in.rqtm1[1]);\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tbfo2 = Ftp2->outcome(Qtp1b, bfc1.first, in.rqtm1[1]);\n\t\t\t\t\t\t\t\tfor (unsigned bfo2index = 0; bfo2index < bfo2.size(); ++bfo2index) {\n\t\t\t\t\t\t\t\t\tdftp2 = in.dFtp2 - bfo2(bfo2index, b2);\n\t\t\t\t\t\t\t\t\tfor (unsigned mmtp2 = 0; mmtp2 <= mmtp2bit; ++mmtp2) {\n\t\t\t\t\t\t\t\t\t\tif (mmtp2 == 1 && b2 == 31) continue;\n\t\t\t\t\t\t\t\t\t\tconnect_helper(mmtp2, mmtp2bit, result.dFtp2, dftp2, b2);\n\t\t\t\t\t\t\t\t\t\tif (result.dFtp2 & (1<<b2)) continue;\n\t\t\t\t\t\t\t\t\t\tif (b2 == 31)\n\t\t\t\t\t\t\t\t\t\t\tbfc2 = msb_bf_forwardconditions(*Ftp2, Qtp1b, bfc1.first, in.rqtm1[1], bfo2[bfo2index]);\n\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\tbfc2 = Ftp2->forwardconditions(Qtp1b, bfc1.first, in.rqtm1[1], bfo2[bfo2index]);\n\t\t\t\t\t\t\t\t\t\tif ((Qtp1freemask & (1<<b2)) && bfc2.first != bc_constant) continue;\n\t\t\t\t\t\t\t\t\t\tif ((Qtfreemask & (1<<b1)) && bfc2.second != bc_constant) continue;\n\t\t\t\t\t\t\t\t\t\tif ((Qtm1freemask & (1<<b1)) && bfc2.third != bc_constant) continue;\n\t\t\t\t\t\t\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttb,bfc2.second);\n\t\t\t\t\t\t\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttp1b,bfc2.first);\n\t\t\t\t\t\t\t\t\t\tresult.rqt[0] = bfc2.second;\n\t\t\t\t\t\t\t\t\t\tif (steps == 3) {\n\t\t\t\t\t\t\t\t\t\t\tif (storefdata) result.fqtp1[b2] = bfc2.first;\n\t\t\t\t\t\t\t\t\t\t\tif (storenewconds) \n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tnewcond.first.set(bc_constant, bc_constant, bc_constant, bc_constant, bfc2.third, bfc1.third, bfc0.third);\n\t\t\t\t\t\t\t\t\t\t\t\tnewcond.second.set(bc_constant, bc_constant, connect_helper(mmtp2, mmtp2bit), \n\t\t\t\t\t\t\t\t\t\t\t\t\tconnect_helper(mmtp1, mmtp1bit), connect_helper(mmt, mmtbit) );\n\t\t\t\t\t\t\t\t\t\t\t\tnewconds.push_back(newcond);\n\t\t\t\t\t\t\t\t\t\t\t\toutdata.push_back(result);\n\t\t\t\t\t\t\t\t\t\t\t\tunsigned curcond = in2.second + (bfc0.third==bc_constant?0:1) + (bfc1.third==bc_constant?0:1) + (bfc2.third==bc_constant?0:1);\n\t\t\t\t\t\t\t\t\t\t\t\toutmincond.push_back(curcond);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tif (compmincond)\n\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned curcond = in2.second + (bfc0.third==bc_constant?0:1) + (bfc1.third==bc_constant?0:1) + (bfc2.third==bc_constant?0:1);\n\t\t\t\t\t\t\t\t\t\t\t\t\tauto itb = out.insert(make_pair(result,curcond));\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (!itb.second && curcond < itb.first->second)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\titb.first->second = curcond;\n\t\t\t\t\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t\t\t\t\t\telse \n\t\t\t\t\t\t\t\t\t\t\t\t\tout[result];\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tusedFtp3 = true;\n\t\t\t\t\t\t\t\t\t\tif (b3 == 31)\n\t\t\t\t\t\t\t\t\t\t\tbfo3 = msb_bf_outcome(*Ftp3, Qtp2b, bfc2.first, in.rqt[1]);\n\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\tbfo3 = Ftp3->outcome(Qtp2b, bfc2.first, in.rqt[1]);\n\t\t\t\t\t\t\t\t\t\tfor (unsigned bfo3index = 0; bfo3index < bfo3.size(); ++bfo3index) {\n\t\t\t\t\t\t\t\t\t\t\tdftp3 = in.dFtp3 - bfo3(bfo3index, b3);\n\t\t\t\t\t\t\t\t\t\t\tfor (unsigned mmtp3 = 0; mmtp3 <= mmtp3bit; ++mmtp3) {\n\t\t\t\t\t\t\t\t\t\t\t\tif (mmtp3 == 1 && b3 == 31) continue;\n\t\t\t\t\t\t\t\t\t\t\t\tconnect_helper(mmtp3, mmtp3bit, result.dFtp3, dftp3, b3);\n\t\t\t\t\t\t\t\t\t\t\t\tif (result.dFtp3 & (1<<b3)) continue;\n\t\t\t\t\t\t\t\t\t\t\t\tif (b3 == 31)\n\t\t\t\t\t\t\t\t\t\t\t\t\tbfc3 = msb_bf_forwardconditions(*Ftp3, Qtp2b, bfc2.first, in.rqt[1], bfo3[bfo3index]);\n\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\tbfc3 = Ftp3->forwardconditions(Qtp2b, bfc2.first, in.rqt[1], bfo3[bfo3index]);\n\t\t\t\t\t\t\t\t\t\t\t\tif ((Qtp2freemask & (1<<b3)) && bfc3.first != bc_constant) continue;\n\t\t\t\t\t\t\t\t\t\t\t\tif ((Qtp1freemask & (1<<b2)) && bfc3.second != bc_constant) continue;\n\t\t\t\t\t\t\t\t\t\t\t\tif ((Qtfreemask & (1<<b2)) && bfc3.third != bc_constant) continue;\n\t\t\t\t\t\t\t\t\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttp1b,bfc3.second);\n\t\t\t\t\t\t\t\t\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttp2b,bfc3.first);\n\t\t\t\t\t\t\t\t\t\t\t\tresult.rqtp1[0] = bfc3.second;\n\t\t\t\t\t\t\t\t\t\t\t\tif (steps == 4) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (storefdata) result.fqtp2[b3] = bfc3.first;\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (storenewconds) \n\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tnewcond.first.set(bc_constant, bc_constant, bc_constant, bfc3.third, bfc2.third, bfc1.third, bfc0.third);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tnewcond.second.set(bc_constant, connect_helper(mmtp3, mmtp3bit),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconnect_helper(mmtp2, mmtp2bit), connect_helper(mmtp1, mmtp1bit), connect_helper(mmt, mmtbit) );\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tnewconds.push_back(newcond);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\toutdata.push_back(result);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned curcond = in2.second + (bfc0.third==bc_constant?0:1) + (bfc1.third==bc_constant?0:1) + (bfc2.third==bc_constant?0:1)  + (bfc3.third==bc_constant?0:1);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\toutmincond.push_back(curcond);\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (compmincond)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned curcond = in2.second + (bfc0.third==bc_constant?0:1) + (bfc1.third==bc_constant?0:1) + (bfc2.third==bc_constant?0:1)  + (bfc3.third==bc_constant?0:1);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tauto itb = out.insert(make_pair(result,curcond));\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!itb.second && curcond < itb.first->second)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\titb.first->second = curcond;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t\t\t\t\t\t\t\telse \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tout[result];\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\n\n\t\t\t\t\t\t\t\t\t\t\t\tusedFtp4 = true;\n\t\t\t\t\t\t\t\t\t\t\t\tif (b4 == 31)\n\t\t\t\t\t\t\t\t\t\t\t\t\tbfo4 = msb_bf_outcome(*Ftp4, Qtp3b, bfc3.first, in.rqtp1[1]);\n\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\tbfo4 = Ftp4->outcome(Qtp3b, bfc3.first, in.rqtp1[1]);\n\t\t\t\t\t\t\t\t\t\t\t\tfor (unsigned bfo4index = 0; bfo4index < bfo4.size(); ++bfo4index) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tdftp4 = in.dFtp4 - bfo4(bfo4index, b4);\n\t\t\t\t\t\t\t\t\t\t\t\t\tfor (unsigned mmtp4 = 0; mmtp4 <= mmtp4bit; ++mmtp4) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (mmtp4 == 1 && b4 == 31) continue;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconnect_helper(mmtp4, mmtp4bit, result.dFtp4, dftp4, b4);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (result.dFtp4 & (1<<b4)) continue;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (b4 == 31)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbfc4 = msb_bf_forwardconditions(*Ftp4, Qtp3b, bfc3.first, in.rqtp1[1], bfo4[bfo4index]);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbfc4 = Ftp4->forwardconditions(Qtp3b, bfc3.first, in.rqtp1[1], bfo4[bfo4index]);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif ((Qtp3freemask & (1<<b4)) && bfc4.first != bc_constant) continue;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif ((Qtp2freemask & (1<<b3)) && bfc4.second != bc_constant) continue;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif ((Qtp1freemask & (1<<b3)) && bfc4.third != bc_constant) continue;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttp2b,bfc4.second);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttp3b,bfc4.first);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (storenewconds) \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnewcond.first.set(bfc4.first, bfc4.second, bfc4.third, bfc3.third, bfc2.third, bfc1.third, bfc0.third);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnewcond.second.set( connect_helper(mmtp4, mmtp4bit), connect_helper(mmtp3, mmtp3bit),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconnect_helper(mmtp2, mmtp2bit), connect_helper(mmtp1, mmtp1bit), connect_helper(mmt, mmtbit) );\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnewconds.push_back(newcond);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\toutdata.push_back(result);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned curcond = in2.second + (bfc0.third==bc_constant?0:1) + (bfc1.third==bc_constant?0:1) + (bfc2.third==bc_constant?0:1) + (bfc3.third==bc_constant?0:1)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t + (bfc4.first==bc_constant?0:1) + (bfc4.second==bc_constant?0:1) + (bfc4.third==bc_constant?0:1);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\toutmincond.push_back(curcond);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (compmincond)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned curcond = in2.second + (bfc0.third==bc_constant?0:1) + (bfc1.third==bc_constant?0:1) + (bfc2.third==bc_constant?0:1) + (bfc3.third==bc_constant?0:1)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t + (bfc4.first==bc_constant?0:1) + (bfc4.second==bc_constant?0:1) + (bfc4.third==bc_constant?0:1);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tauto itb = out.insert(make_pair(result,curcond));\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!itb.second && curcond < itb.first->second)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\titb.first->second = curcond;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tout[result];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\ntemplate<bool storenewconds>\nvoid sha1_connect_thread::connectbits_1234(const pair<connect_bitdata,unsigned>& in2, map<connect_bitdata,unsigned>& out, \n\t\t\t\t unsigned b, const sha1differentialpath& lower, const sha1differentialpath& upper, \n\t\t\t\t vector< pair<byteconditions,byteconditions> >& newconds, vector<connect_bitdata>& outdata, vector<unsigned>& outmincond)\n{\n\tconst connect_bitdata& in = in2.first;\n\tconst unsigned b0 = b&31;\n\tconst unsigned b1 = (b+30)&31;\n\tconst unsigned b2 = (b+28)&31;\n\tconst unsigned b3 = (b+26)&31;\n\tconst unsigned b4 = (b+24)&31;\n/*\t connect_bitdata result;\n\t bf_outcome bfo1, bfo2, bfo3, bfo4;\n\t bf_conditions bfc1, bfc2, bfc3, bfc4;\n\t bitcondition Qtm2b, Qtb, Qtp1b, Qtp2b, Qtp3b;\n\t uint32 dftp1, dftp2, dftp3, dftp4;\n\t pair<byteconditions,byteconditions> newcond;\n\t bitcondition Ttm1b, Ttb, Ttp1b, Ttp2b, Ttp3b;\n*/\n\tTtm1b = tbc(t-1,b0);\n\tTtb = tbc(t, b1);\n\tTtp1b = tbc(t+1, b2);\n\tTtp2b = tbc(t+2, b3);\n\tTtp3b = tbc(t+3, b4);\n\n\t//update the running bitconditions\n\tresult = in;\n\tresult.rqtm2[1] = result.rqtm2[0];\n\tresult.rqtm1[1] = result.rqtm1[0];\n\tresult.rqt[1] = result.rqt[0];\n\tresult.rqtp1[1] = result.rqtp1[0];\n\n\tQtm2b = lower(t-2,(b0+2)&31);\n\tQtp2b = upper(t+2,b3); if (Qtp2b == bc_prev) { Qtp2b = bc_constant; } // if (storenewconds) throw; }\n\tQtp3b = upper(t+3,b4); if (Qtp3b == bc_prev) { Qtp3b = bc_constant; } // if (storenewconds) throw; }\n\tunsigned dQtbit = (in.dQt>>b1)&1;\n\tunsigned dQtp1bit = (in.dQtp1>>b2)&1;\n\tunsigned mmtp1bit = (mmasktp1>>b1)&1;\n\tunsigned mmtp2bit = (mmasktp2>>b2)&1;\n\tunsigned mmtp3bit = (mmasktp3>>b3)&1;\n\tunsigned mmtp4bit = (mmasktp4>>b4)&1;\n\n\tresult.rqtm2[0] = bc_constant;\n\n\tusedFtp1 = true;\n\tif (b0 != 0 && b0 != 1) throw;\n\tfor (unsigned dqt = 0; dqt <= dQtbit; ++dqt) {\n\t\tconnect_helper(dqt, dQtbit, Qtb, result.dQt, in.dQt, b1);\n\t\tif (b1 == 1 && result.dQt != dQtb2b31) continue;\n\t\tif (b1 == 26 && result.dQt != dQtb27b31) continue;\n\t\tif (b1 == 31 && (Qtb == Qtb31not || Qtb == Qtb31not2)) continue;\n\t\tif (b1 == 31)\n\t\t\tbfo1 = msb_bf_outcome(*Ftp1, Qtb, in.fqtm1[b0], in.rqtm2[1]);\n\t\telse\n\t\t\tbfo1 = Ftp1->outcome(Qtb, in.fqtm1[b0], in.rqtm2[1]);\n\t\tfor (unsigned bfo1index = 0; bfo1index < bfo1.size(); ++bfo1index) {\n\t\t\tdftp1 = in.dFtp1 - bfo1(bfo1index, b1);\n\t\t\tfor (unsigned mmtp1 = 0; mmtp1 <= mmtp1bit; ++mmtp1) {\n\t\t\t\tif (mmtp1 == 1 && b1 == 31) continue;\n\t\t\t\tconnect_helper(mmtp1, mmtp1bit, result.dFtp1, dftp1, b1);\n\t\t\t\tif (result.dFtp1 & (1<<b1)) continue;\n\t\t\t\tif (b1 == 31)\n\t\t\t\t\tbfc1 = msb_bf_forwardconditions(*Ftp1, Qtb, in.fqtm1[b0], in.rqtm2[1], bfo1[bfo1index]);\n\t\t\t\telse\n\t\t\t\t\tbfc1 = Ftp1->forwardconditions(Qtb, in.fqtm1[b0], in.rqtm2[1], bfo1[bfo1index]);\n\t\t\t\tif ((Qtfreemask & (1<<b1)) && bfc1.first != bc_constant) continue;\n\t\t\t\tif ((Qtm1freemask & (1<<b0)) && bfc1.second != bc_constant) continue;\n\t\t\t\tif ((Qtm2freemask & (1<<b0)) && bfc1.third != bc_constant) continue;\n\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttm1b,bfc1.second);\n\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttb,bfc1.first);\n\t\t\t\tresult.rqtm1[0] = bfc1.second;\t\t\t\t\t\t\t\n\n\t\t\t\tusedFtp2 = true;\n\t\t\t\tfor (unsigned dqtp1 = 0; dqtp1 <= dQtp1bit; ++dqtp1) {\n\t\t\t\t\tconnect_helper(dqtp1, dQtp1bit, Qtp1b, result.dQtp1, in.dQtp1, b2);\n\t\t\t\t\tif (b2 == 1 && result.dQtp1 != dQtp1b2b31) continue;\n\t\t\t\t\tif (b2 == 26 && result.dQtp1 != dQtp1b27b31) continue;\n\t\t\t\t\tif (b2 == 31 && (Qtp1b == Qtp1b31not || Qtp1b == Qtp1b31not2)) continue;\n\t\t\t\t\tif (b2 == 31)\n\t\t\t\t\t\tbfo2 = msb_bf_outcome(*Ftp2, Qtp1b, bfc1.first, in.rqtm1[1]);\n\t\t\t\t\telse\n\t\t\t\t\t\tbfo2 = Ftp2->outcome(Qtp1b, bfc1.first, in.rqtm1[1]);\n\t\t\t\t\tfor (unsigned bfo2index = 0; bfo2index < bfo2.size(); ++bfo2index) {\n\t\t\t\t\t\tdftp2 = in.dFtp2 - bfo2(bfo2index, b2);\n\t\t\t\t\t\tfor (unsigned mmtp2 = 0; mmtp2 <= mmtp2bit; ++mmtp2) {\n\t\t\t\t\t\t\tif (mmtp2 == 1 && b2 == 31) continue;\n\t\t\t\t\t\t\tconnect_helper(mmtp2, mmtp2bit, result.dFtp2, dftp2, b2);\n\t\t\t\t\t\t\tif (result.dFtp2 & (1<<b2)) continue;\n\t\t\t\t\t\t\tif (b2 == 31)\n\t\t\t\t\t\t\t\tbfc2 = msb_bf_forwardconditions(*Ftp2, Qtp1b, bfc1.first, in.rqtm1[1], bfo2[bfo2index]);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tbfc2 = Ftp2->forwardconditions(Qtp1b, bfc1.first, in.rqtm1[1], bfo2[bfo2index]);\n\t\t\t\t\t\t\tif ((Qtp1freemask & (1<<b2)) && bfc2.first != bc_constant) continue;\n\t\t\t\t\t\t\tif ((Qtfreemask & (1<<b1)) && bfc2.second != bc_constant) continue;\n\t\t\t\t\t\t\tif ((Qtm1freemask & (1<<b1)) && bfc2.third != bc_constant) continue;\n\t\t\t\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttb,bfc2.second);\n\t\t\t\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttp1b,bfc2.first);\n\t\t\t\t\t\t\tresult.rqt[0] = bfc2.second;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tusedFtp3 = true;\n\t\t\t\t\t\t\tif (b3 == 31)\n\t\t\t\t\t\t\t\tbfo3 = msb_bf_outcome(*Ftp3, Qtp2b, bfc2.first, in.rqt[1]);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tbfo3 = Ftp3->outcome(Qtp2b, bfc2.first, in.rqt[1]);\n\t\t\t\t\t\t\tfor (unsigned bfo3index = 0; bfo3index < bfo3.size(); ++bfo3index) {\n\t\t\t\t\t\t\t\tdftp3 = in.dFtp3 - bfo3(bfo3index, b3);\n\t\t\t\t\t\t\t\tfor (unsigned mmtp3 = 0; mmtp3 <= mmtp3bit; ++mmtp3) {\n\t\t\t\t\t\t\t\t\tif (mmtp3 == 1 && b3 == 31) continue;\n\t\t\t\t\t\t\t\t\tconnect_helper(mmtp3, mmtp3bit, result.dFtp3, dftp3, b3);\n\t\t\t\t\t\t\t\t\tif (result.dFtp3 & (1<<b3)) continue;\n\t\t\t\t\t\t\t\t\tif (b3 == 31)\n\t\t\t\t\t\t\t\t\t\tbfc3 = msb_bf_forwardconditions(*Ftp3, Qtp2b, bfc2.first, in.rqt[1], bfo3[bfo3index]);\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\tbfc3 = Ftp3->forwardconditions(Qtp2b, bfc2.first, in.rqt[1], bfo3[bfo3index]);\n\t\t\t\t\t\t\t\t\tif ((Qtp2freemask & (1<<b3)) && bfc3.first != bc_constant) continue;\n\t\t\t\t\t\t\t\t\tif ((Qtp1freemask & (1<<b2)) && bfc3.second != bc_constant) continue;\n\t\t\t\t\t\t\t\t\tif ((Qtfreemask & (1<<b2)) && bfc3.third != bc_constant) continue;\n\t\t\t\t\t\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttp1b,bfc3.second);\n\t\t\t\t\t\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttp2b,bfc3.first);\n\t\t\t\t\t\t\t\t\tresult.rqtp1[0] = bfc3.second;\n\n\t\t\t\t\t\t\t\t\tusedFtp4 = true;\n\t\t\t\t\t\t\t\t\tif (b4 == 31)\n\t\t\t\t\t\t\t\t\t\tbfo4 = msb_bf_outcome(*Ftp4, Qtp3b, bfc3.first, in.rqtp1[1]);\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\tbfo4 = Ftp4->outcome(Qtp3b, bfc3.first, in.rqtp1[1]);\n\t\t\t\t\t\t\t\t\tfor (unsigned bfo4index = 0; bfo4index < bfo4.size(); ++bfo4index) {\n\t\t\t\t\t\t\t\t\t\tdftp4 = in.dFtp4 - bfo4(bfo4index, b4);\n\t\t\t\t\t\t\t\t\t\tfor (unsigned mmtp4 = 0; mmtp4 <= mmtp4bit; ++mmtp4) {\n\t\t\t\t\t\t\t\t\t\t\tif (mmtp4 == 1 && b4 == 31) continue;\n\t\t\t\t\t\t\t\t\t\t\tconnect_helper(mmtp4, mmtp4bit, result.dFtp4, dftp4, b4);\n\t\t\t\t\t\t\t\t\t\t\tif (result.dFtp4 & (1<<b4)) continue;\n\t\t\t\t\t\t\t\t\t\t\t\tif (b4 == 31)\n\t\t\t\t\t\t\t\t\t\t\t\t\tbfc4 = msb_bf_forwardconditions(*Ftp4, Qtp3b, bfc3.first, in.rqtp1[1], bfo4[bfo4index]);\n\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\tbfc4 = Ftp4->forwardconditions(Qtp3b, bfc3.first, in.rqtp1[1], bfo4[bfo4index]);\n\t\t\t\t\t\t\t\t\t\t\t\tif ((Qtp3freemask & (1<<b4)) && bfc4.first != bc_constant) continue;\n\t\t\t\t\t\t\t\t\t\t\t\tif ((Qtp2freemask & (1<<b3)) && bfc4.second != bc_constant) continue;\n\t\t\t\t\t\t\t\t\t\t\t\tif ((Qtp1freemask & (1<<b3)) && bfc4.third != bc_constant) continue;\n\t\t\t\t\t\t\t\t\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttp2b,bfc4.second);\n\t\t\t\t\t\t\t\t\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttp3b,bfc4.first);\n\t\t\t\t\t\t\t\t\t\t\tunsigned curcond = in2.second + (bfc1.third==bc_constant?0:1) + (bfc2.third==bc_constant?0:1) + (bfc3.third==bc_constant?0:1)\n\t\t\t\t\t\t\t\t\t\t\t\t\t + (bfc4.first==bc_constant?0:1) + (bfc4.second==bc_constant?0:1) + (bfc4.third==bc_constant?0:1);\n\t\t\t\t\t\t\t\t\t\t\tif (storenewconds) \n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tnewcond.first.set(bfc4.first, bfc4.second, bfc4.third, bfc3.third, bfc2.third, bfc1.third);\n\t\t\t\t\t\t\t\t\t\t\t\tnewcond.second.set( connect_helper(mmtp4, mmtp4bit), connect_helper(mmtp3, mmtp3bit),\n\t\t\t\t\t\t\t\t\t\t\t\t\tconnect_helper(mmtp2, mmtp2bit), connect_helper(mmtp1, mmtp1bit));\n\t\t\t\t\t\t\t\t\t\t\t\tnewconds.push_back(newcond);\n\t\t\t\t\t\t\t\t\t\t\t\toutdata.push_back(result);\n\t\t\t\t\t\t\t\t\t\t\t\toutmincond.push_back(curcond);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tauto itb = out.insert(make_pair(result,curcond));\n\t\t\t\t\t\t\t\t\t\t\t\tif (!itb.second && curcond < itb.first->second)\n\t\t\t\t\t\t\t\t\t\t\t\t\titb.first->second = curcond;\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\ntemplate<bool storenewconds>\nvoid sha1_connect_thread::connectbits_234(const pair<connect_bitdata,unsigned>& in2, map<connect_bitdata,unsigned>& out, \n\t\t\t\t unsigned b, const sha1differentialpath& lower, const sha1differentialpath& upper, \n\t\t\t\t vector< pair<byteconditions,byteconditions> >& newconds, vector<connect_bitdata>& outdata, vector<unsigned>& outmincond)\n{\n\tconst connect_bitdata& in = in2.first;\n\tconst unsigned b0 = b&31;\n\tconst unsigned b1 = (b+30)&31;\n\tconst unsigned b2 = (b+28)&31;\n\tconst unsigned b3 = (b+26)&31;\n\tconst unsigned b4 = (b+24)&31;\n/*\t connect_bitdata result;\n\t bf_outcome bfo2, bfo3, bfo4;\n\t bf_conditions bfc2, bfc3, bfc4;\n\t bitcondition Qtp1b, Qtp2b, Qtp3b;\n\t uint32 dftp2, dftp3, dftp4;\n\t pair<byteconditions,byteconditions> newcond;\n\t bitcondition Ttb, Ttp1b, Ttp2b, Ttp3b;\n*/\n\tTtb = tbc(t, b1);\n\tTtp1b = tbc(t+1, b2);\n\tTtp2b = tbc(t+2, b3);\n\tTtp3b = tbc(t+3, b4);\n\t//update the running bitconditions\n\tresult = in;\n\tresult.rqtm2[1] = result.rqtm2[0];\n\tresult.rqtm1[1] = result.rqtm1[0];\n\tresult.rqt[1] = result.rqt[0];\n\tresult.rqtp1[1] = result.rqtp1[0];\n\n\tQtp2b = upper(t+2,b3); if (Qtp2b == bc_prev) { Qtp2b = bc_constant; } // if (storenewconds) throw; }\n\tQtp3b = upper(t+3,b4); if (Qtp3b == bc_prev) { Qtp3b = bc_constant; } // if (storenewconds) throw; }\n\tunsigned dQtp1bit = (in.dQtp1>>b2)&1;\n\tunsigned mmtp2bit = (mmasktp2>>b2)&1;\n\tunsigned mmtp3bit = (mmasktp3>>b3)&1;\n\tunsigned mmtp4bit = (mmasktp4>>b4)&1;\n\n\tresult.rqtm2[0] = bc_constant;\n\tresult.rqtm1[0] = bc_constant;\n\n\tusedFtp2 = true;\n\tif (b1 != 0 && b1 != 1) throw;\n\tfor (unsigned dqtp1 = 0; dqtp1 <= dQtp1bit; ++dqtp1) {\n\t\tconnect_helper(dqtp1, dQtp1bit, Qtp1b, result.dQtp1, in.dQtp1, b2);\n\t\tif (b2 == 1 && result.dQtp1 != dQtp1b2b31) continue;\n\t\tif (b2 == 26 && result.dQtp1 != dQtp1b27b31) continue;\n\t\tif (b2 == 31 && (Qtp1b == Qtp1b31not || Qtp1b == Qtp1b31not2)) continue;\n\t\tif (b2 == 31)\n\t\t\tbfo2 = msb_bf_outcome(*Ftp2, Qtp1b, in.fqt[b1], in.rqtm1[1]);\n\t\telse\n\t\t\tbfo2 = Ftp2->outcome(Qtp1b, in.fqt[b1], in.rqtm1[1]);\n\t\tfor (unsigned bfo2index = 0; bfo2index < bfo2.size(); ++bfo2index) {\n\t\t\tdftp2 = in.dFtp2 - bfo2(bfo2index, b2);\n\t\t\tfor (unsigned mmtp2 = 0; mmtp2 <= mmtp2bit; ++mmtp2) {\n\t\t\t\tif (mmtp2 == 1 && b2 == 31) continue;\n\t\t\t\tconnect_helper(mmtp2, mmtp2bit, result.dFtp2, dftp2, b2);\n\t\t\t\tif (result.dFtp2 & (1<<b2)) continue;\n\t\t\t\tif (b2 == 31)\n\t\t\t\t\tbfc2 = msb_bf_forwardconditions(*Ftp2, Qtp1b, in.fqt[b1], in.rqtm1[1], bfo2[bfo2index]);\n\t\t\t\telse\n\t\t\t\t\tbfc2 = Ftp2->forwardconditions(Qtp1b, in.fqt[b1], in.rqtm1[1], bfo2[bfo2index]);\n\t\t\t\tif ((Qtp1freemask & (1<<b2)) && bfc2.first != bc_constant) continue;\n\t\t\t\tif ((Qtfreemask & (1<<b1)) && bfc2.second != bc_constant) continue;\n\t\t\t\tif ((Qtm1freemask & (1<<b1)) && bfc2.third != bc_constant) continue;\n\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttb,bfc2.second);\n\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttp1b,bfc2.first);\n\t\t\t\tresult.rqt[0] = bfc2.second;\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\tusedFtp3 = true;\n\t\t\t\tif (b3 == 31)\n\t\t\t\t\tbfo3 = msb_bf_outcome(*Ftp3, Qtp2b, bfc2.first, in.rqt[1]);\n\t\t\t\telse\n\t\t\t\t\tbfo3 = Ftp3->outcome(Qtp2b, bfc2.first, in.rqt[1]);\n\t\t\t\tfor (unsigned bfo3index = 0; bfo3index < bfo3.size(); ++bfo3index) {\n\t\t\t\t\tdftp3 = in.dFtp3 - bfo3(bfo3index, b3);\n\t\t\t\t\tfor (unsigned mmtp3 = 0; mmtp3 <= mmtp3bit; ++mmtp3) {\n\t\t\t\t\t\tif (mmtp3 == 1 && b3 == 31) continue;\n\t\t\t\t\t\tconnect_helper(mmtp3, mmtp3bit, result.dFtp3, dftp3, b3);\n\t\t\t\t\t\tif (result.dFtp3 & (1<<b3)) continue;\n\t\t\t\t\t\tif (b3 == 31)\n\t\t\t\t\t\t\tbfc3 = msb_bf_forwardconditions(*Ftp3, Qtp2b, bfc2.first, in.rqt[1], bfo3[bfo3index]);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tbfc3 = Ftp3->forwardconditions(Qtp2b, bfc2.first, in.rqt[1], bfo3[bfo3index]);\n\t\t\t\t\t\tif ((Qtp2freemask & (1<<b3)) && bfc3.first != bc_constant) continue;\n\t\t\t\t\t\tif ((Qtp1freemask & (1<<b2)) && bfc3.second != bc_constant) continue;\n\t\t\t\t\t\tif ((Qtfreemask & (1<<b2)) && bfc3.third != bc_constant) continue;\n\t\t\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttp1b,bfc3.second);\n\t\t\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttp2b,bfc3.first);\n\t\t\t\t\t\tresult.rqtp1[0] = bfc3.second;\n\n\t\t\t\t\t\tusedFtp4 = true;\n\t\t\t\t\t\tif (b4 == 31)\n\t\t\t\t\t\t\tbfo4 = msb_bf_outcome(*Ftp4, Qtp3b, bfc3.first, in.rqtp1[1]);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tbfo4 = Ftp4->outcome(Qtp3b, bfc3.first, in.rqtp1[1]);\n\t\t\t\t\t\tfor (unsigned bfo4index = 0; bfo4index < bfo4.size(); ++bfo4index) {\n\t\t\t\t\t\t\tdftp4 = in.dFtp4 - bfo4(bfo4index, b4);\n\t\t\t\t\t\t\tfor (unsigned mmtp4 = 0; mmtp4 <= mmtp4bit; ++mmtp4) {\n\t\t\t\t\t\t\t\tif (mmtp4 == 1 && b4 == 31) continue;\n\t\t\t\t\t\t\t\tconnect_helper(mmtp4, mmtp4bit, result.dFtp4, dftp4, b4);\n\t\t\t\t\t\t\t\tif (result.dFtp4 & (1<<b4)) continue;\n\t\t\t\t\t\t\t\t\tif (b4 == 31)\n\t\t\t\t\t\t\t\t\t\tbfc4 = msb_bf_forwardconditions(*Ftp4, Qtp3b, bfc3.first, in.rqtp1[1], bfo4[bfo4index]);\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\tbfc4 = Ftp4->forwardconditions(Qtp3b, bfc3.first, in.rqtp1[1], bfo4[bfo4index]);\n\t\t\t\t\t\t\t\t\tif ((Qtp3freemask & (1<<b4)) && bfc4.first != bc_constant) continue;\n\t\t\t\t\t\t\t\t\tif ((Qtp2freemask & (1<<b3)) && bfc4.second != bc_constant) continue;\n\t\t\t\t\t\t\t\t\tif ((Qtp1freemask & (1<<b3)) && bfc4.third != bc_constant) continue;\n\t\t\t\t\t\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttp2b,bfc4.second);\n\t\t\t\t\t\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttp3b,bfc4.first);\n\t\t\t\t\t\t\t\tunsigned curcond = in2.second + (bfc2.third==bc_constant?0:1) + (bfc3.third==bc_constant?0:1)\n\t\t\t\t\t\t\t\t\t\t + (bfc4.first==bc_constant?0:1) + (bfc4.second==bc_constant?0:1) + (bfc4.third==bc_constant?0:1);\n\t\t\t\t\t\t\t\tif (storenewconds) \n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tnewcond.first.set(bfc4.first, bfc4.second, bfc4.third, bfc3.third, bfc2.third);\n\t\t\t\t\t\t\t\t\tnewcond.second.set( connect_helper(mmtp4, mmtp4bit), connect_helper(mmtp3, mmtp3bit),\n\t\t\t\t\t\t\t\t\t\tconnect_helper(mmtp2, mmtp2bit));\n\t\t\t\t\t\t\t\t\tnewconds.push_back(newcond);\n\t\t\t\t\t\t\t\t\toutdata.push_back(result);\n\t\t\t\t\t\t\t\t\toutmincond.push_back(curcond);\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\tauto itb = out.insert(make_pair(result,curcond));\n\t\t\t\t\t\t\t\t\tif (!itb.second && curcond < itb.first->second)\n\t\t\t\t\t\t\t\t\t\titb.first->second = curcond;\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\t\t\t}\n\t\t}\n\t}\n}\n\ntemplate<bool storenewconds>\nvoid sha1_connect_thread::connectbits_34(const pair<connect_bitdata,unsigned>& in2, map<connect_bitdata,unsigned>& out, \n\t\t\t\t unsigned b, const sha1differentialpath& lower, const sha1differentialpath& upper, \n\t\t\t\t vector< pair<byteconditions,byteconditions> >& newconds, vector<connect_bitdata>& outdata, vector<unsigned>& outmincond)\n{\n\tconst connect_bitdata& in = in2.first;\n\tconst unsigned b0 = b&31;\n\tconst unsigned b1 = (b+30)&31;\n\tconst unsigned b2 = (b+28)&31;\n\tconst unsigned b3 = (b+26)&31;\n\tconst unsigned b4 = (b+24)&31;\n/*\t connect_bitdata result;\n\t bf_outcome bfo3, bfo4;\n\t bf_conditions bfc3, bfc4;\n\t bitcondition Qtp2b, Qtp3b;\n\t uint32 dftp3, dftp4;\n\t pair<byteconditions,byteconditions> newcond;\n\t bitcondition Ttp1b, Ttp2b, Ttp3b;\n*/\n\tTtp1b = tbc(t+1, b2);\n\tTtp2b = tbc(t+2, b3);\n\tTtp3b = tbc(t+3, b4);\n\t//update the running bitconditions\n\tresult = in;\n\tresult.rqtm2[1] = result.rqtm2[0];\n\tresult.rqtm1[1] = result.rqtm1[0];\n\tresult.rqt[1] = result.rqt[0];\n\tresult.rqtp1[1] = result.rqtp1[0];\n\n\tQtp2b = upper(t+2,b3); if (Qtp2b == bc_prev) { Qtp2b = bc_constant; } // if (storenewconds) throw; }\n\tQtp3b = upper(t+3,b4); if (Qtp3b == bc_prev) { Qtp3b = bc_constant; } // if (storenewconds) throw; }\n\tunsigned mmtp3bit = (mmasktp3>>b3)&1;\n\tunsigned mmtp4bit = (mmasktp4>>b4)&1;\n\n\tresult.rqtm2[0] = bc_constant;\n\tresult.rqtm1[0] = bc_constant;\n\tresult.rqt[0] = bc_constant;\n\n\tusedFtp3 = true;\n\tif (b2 != 0 && b2 != 1) throw;\n\tif (b3 == 31)\n\t\tbfo3 = msb_bf_outcome(*Ftp3, Qtp2b, in.fqtp1[b2], in.rqt[1]);\n\telse\n\t\tbfo3 = Ftp3->outcome(Qtp2b, in.fqtp1[b2], in.rqt[1]);\n\tfor (unsigned bfo3index = 0; bfo3index < bfo3.size(); ++bfo3index) {\n\t\tdftp3 = in.dFtp3 - bfo3(bfo3index, b3);\n\t\tfor (unsigned mmtp3 = 0; mmtp3 <= mmtp3bit; ++mmtp3) {\n\t\t\tif (mmtp3 == 1 && b3 == 31) continue;\n\t\t\tconnect_helper(mmtp3, mmtp3bit, result.dFtp3, dftp3, b3);\n\t\t\tif (result.dFtp3 & (1<<b3)) continue;\n\t\t\tif (b3 == 31)\n\t\t\t\tbfc3 = msb_bf_forwardconditions(*Ftp3, Qtp2b, in.fqtp1[b2], in.rqt[1], bfo3[bfo3index]);\n\t\t\telse\n\t\t\t\tbfc3 = Ftp3->forwardconditions(Qtp2b, in.fqtp1[b2], in.rqt[1], bfo3[bfo3index]);\n\t\t\tif ((Qtp2freemask & (1<<b3)) && bfc3.first != bc_constant) continue;\n\t\t\tif ((Qtp1freemask & (1<<b2)) && bfc3.second != bc_constant) continue;\n\t\t\tif ((Qtfreemask & (1<<b2)) && bfc3.third != bc_constant) continue;\n\t\t\tCHECK_TUNNEL_BITCONDITION(Ttp1b,bfc3.second);\n\t\t\tCHECK_TUNNEL_BITCONDITION(Ttp2b,bfc3.first);\n\t\t\tresult.rqtp1[0] = bfc3.second;\n\n\t\t\tusedFtp4 = true;\n\t\t\tif (b4 == 31)\n\t\t\t\tbfo4 = msb_bf_outcome(*Ftp4, Qtp3b, bfc3.first, in.rqtp1[1]);\n\t\t\telse\n\t\t\t\tbfo4 = Ftp4->outcome(Qtp3b, bfc3.first, in.rqtp1[1]);\n\t\t\tfor (unsigned bfo4index = 0; bfo4index < bfo4.size(); ++bfo4index) {\n\t\t\t\tdftp4 = in.dFtp4 - bfo4(bfo4index, b4);\n\t\t\t\tfor (unsigned mmtp4 = 0; mmtp4 <= mmtp4bit; ++mmtp4) {\n\t\t\t\t\tif (mmtp4 == 1 && b4 == 31) continue;\n\t\t\t\t\tconnect_helper(mmtp4, mmtp4bit, result.dFtp4, dftp4, b4);\n\t\t\t\t\tif (result.dFtp4 & (1<<b4)) continue;\n\t\t\t\t\t\tif (b4 == 31)\n\t\t\t\t\t\t\tbfc4 = msb_bf_forwardconditions(*Ftp4, Qtp3b, bfc3.first, in.rqtp1[1], bfo4[bfo4index]);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tbfc4 = Ftp4->forwardconditions(Qtp3b, bfc3.first, in.rqtp1[1], bfo4[bfo4index]);\n\t\t\t\t\t\tif ((Qtp3freemask & (1<<b4)) && bfc4.first != bc_constant) continue;\n\t\t\t\t\t\tif ((Qtp2freemask & (1<<b3)) && bfc4.second != bc_constant) continue;\n\t\t\t\t\t\tif ((Qtp1freemask & (1<<b3)) && bfc4.third != bc_constant) continue;\n\t\t\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttp2b,bfc4.second);\n\t\t\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttp3b,bfc4.first);\n\t\t\t\t\tunsigned curcond = in2.second + (bfc3.third==bc_constant?0:1)\n\t\t\t\t\t\t\t + (bfc4.first==bc_constant?0:1) + (bfc4.second==bc_constant?0:1) + (bfc4.third==bc_constant?0:1);\n\t\t\t\t\tif (storenewconds) \n\t\t\t\t\t{\n\t\t\t\t\t\tnewcond.first.set(bfc4.first, bfc4.second, bfc4.third, bfc3.third);\n\t\t\t\t\t\tnewcond.second.set( connect_helper(mmtp4, mmtp4bit), connect_helper(mmtp3, mmtp3bit));\n\t\t\t\t\t\tnewconds.push_back(newcond);\n\t\t\t\t\t\toutdata.push_back(result);\n\t\t\t\t\t\toutmincond.push_back(curcond);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tauto itb = out.insert(make_pair(result,curcond));\n\t\t\t\t\t\tif (!itb.second && curcond < itb.first->second)\n\t\t\t\t\t\t\titb.first->second = curcond;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\ntemplate<bool storenewconds>\nvoid sha1_connect_thread::connectbits_4(const pair<connect_bitdata,unsigned>& in2, map<connect_bitdata,unsigned>& out, \n\t\t\t\t unsigned b, const sha1differentialpath& lower, const sha1differentialpath& upper, \n\t\t\t\t vector< pair<byteconditions,byteconditions> >& newconds, vector<connect_bitdata>& outdata, vector<unsigned>& outmincond)\n{\n\tconst connect_bitdata& in = in2.first;\n\tconst unsigned b0 = b&31;\n\tconst unsigned b1 = (b+30)&31;\n\tconst unsigned b2 = (b+28)&31;\n\tconst unsigned b3 = (b+26)&31;\n\tconst unsigned b4 = (b+24)&31;\n/*\tconnect_bitdata result;\n\tbf_outcome bfo4;\n\tbf_conditions bfc4;\n\tbitcondition Qtp2b, Qtp3b;\n\tuint32 dftp4;\n\tpair<byteconditions,byteconditions> newcond;\n\tbitcondition Ttp2b, Ttp3b;\n*/\n\tTtp2b = tbc(t+2, b3);\n\tTtp3b = tbc(t+3, b4);\n\t//update the running bitconditions\n\tresult = in;\n\tresult.rqtm2[1] = result.rqtm2[0];\n\tresult.rqtm1[1] = result.rqtm1[0];\n\tresult.rqt[1] = result.rqt[0];\n\tresult.rqtp1[1] = result.rqtp1[0];\n\n\tQtp2b = upper(t+2,b3); if (Qtp2b == bc_prev) { Qtp2b = bc_constant; } // if (storenewconds) throw; }\n\tQtp3b = upper(t+3,b4); if (Qtp3b == bc_prev) { Qtp3b = bc_constant; } // if (storenewconds) throw; }\n\tunsigned mmtp4bit = (mmasktp4>>b4)&1;\n\n\tresult.rqtm2[0] = bc_constant;\n\tresult.rqtm1[0] = bc_constant;\n\tresult.rqt[0] = bc_constant;\n\tresult.rqtp1[0] = bc_constant;\n\n\tusedFtp4 = true;\n\tif (b3 != 0 && b3 != 1) throw;\n\tif (b4 == 31)\n\t\tbfo4 = msb_bf_outcome(*Ftp4, Qtp3b, in.fqtp2[b3], in.rqtp1[1]);\n\telse\n\t\tbfo4 = Ftp4->outcome(Qtp3b, in.fqtp2[b3], in.rqtp1[1]);\n\tfor (unsigned bfo4index = 0; bfo4index < bfo4.size(); ++bfo4index) {\n\t\tdftp4 = in.dFtp4 - bfo4(bfo4index, b4);\n\t\tfor (unsigned mmtp4 = 0; mmtp4 <= mmtp4bit; ++mmtp4) {\n\t\t\tif (mmtp4 == 1 && b4 == 31) continue;\n\t\t\tconnect_helper(mmtp4, mmtp4bit, result.dFtp4, dftp4, b4);\n\t\t\tif (result.dFtp4 & (1<<b4)) continue;\n\t\t\t\tif (b4 == 31)\n\t\t\t\t\tbfc4 = msb_bf_forwardconditions(*Ftp4, Qtp3b, in.fqtp2[b3], in.rqtp1[1], bfo4[bfo4index]);\n\t\t\t\telse\n\t\t\t\t\tbfc4 = Ftp4->forwardconditions(Qtp3b, in.fqtp2[b3], in.rqtp1[1], bfo4[bfo4index]);\n\t\t\t\tif ((Qtp3freemask & (1<<b4)) && bfc4.first != bc_constant) continue;\n\t\t\t\tif ((Qtp2freemask & (1<<b3)) && bfc4.second != bc_constant) continue;\n\t\t\t\tif ((Qtp1freemask & (1<<b3)) && bfc4.third != bc_constant) continue;\n\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttp2b,bfc4.second);\n\t\t\t\tCHECK_TUNNEL_BITCONDITION(Ttp3b,bfc4.first);\n\t\t\tunsigned curcond = in2.second\n\t\t\t\t\t + (bfc4.first==bc_constant?0:1) + (bfc4.second==bc_constant?0:1) + (bfc4.third==bc_constant?0:1);\n\t\t\tif (storenewconds) \n\t\t\t{\n\t\t\t\tnewcond.first.set(bfc4.first, bfc4.second, bfc4.third);\n\t\t\t\tnewcond.second.set( connect_helper(mmtp4, mmtp4bit) );\n\t\t\t\tnewconds.push_back(newcond);\n\t\t\t\toutdata.push_back(result);\n\t\t\t\toutmincond.push_back(curcond);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tauto itb = out.insert(make_pair(result,curcond));\n\t\t\t\tif (!itb.second && curcond < itb.first->second)\n\t\t\t\t\titb.first->second = curcond;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid set_sdr_bit(sdr& bsdr, unsigned b, bitcondition bc) {\n\tswitch (bc) {\n\t\tcase bc_constant:\n\t\t\tbsdr.mask &= ~uint32(1<<b);\n\t\t\tbsdr.sign &= bsdr.mask;\n\t\t\tbreak;\n\t\tcase bc_plus:\n\t\t\tbsdr.mask |= 1<<b;\n\t\t\tbsdr.sign |= 1<<b;\n\t\t\tbreak;\n\t\tcase bc_minus:\n\t\t\tbsdr.mask |= 1<<b;\n\t\t\tbsdr.sign &= ~uint32(1<<b);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow;\n\t}\n}\n\nunsigned sha1_connect_thread::connect_paths(const sha1differentialpath& lowerpath, const sha1differentialpath& upperpath, connect_bitdata& startdata, path_container& container, bool returnb40)\n{\n/*\tstatic vector<connect_bitdata> bitdataresults[41];\n\tstatic vector<connect_bitdata> bitdatastart[40];\n\tstatic vector<connect_bitdata> bitdataend[40];\n\tstatic vector< unsigned > bitdatamincond[40];\n\tstatic vector< pair<byteconditions,byteconditions> >  bitdatanewcond[40];\n\tstatic vector< unsigned > bitdatanewcondhw[40];\n\tstatic vector< unsigned > mincond[41];\t\n*/\n\n\tbitdataresults[0].clear();\n\tbitdataresults[0][startdata];\n\n\tunsigned b = 0;\n\twhile (b < 32) {\n\t\tbitdataresults[b+1].clear();\n\t\tusedFtp1 = usedFtp2 = usedFtp3 = usedFtp4 = false;\n\t\tif (b < 2)\n\t\t\tfor (auto it = bitdataresults[b].begin(); it != bitdataresults[b].end(); ++it)\n\t\t\t\tconnectbits_01234<1,false,false,false>(*it, bitdataresults[b+1], b, lowerpath, upperpath, bitdatanewcond[b], bitdataend[b], bitdatamincond[b]);\n\t\telse if (b < 4)\n\t\t\tfor (auto it = bitdataresults[b].begin(); it != bitdataresults[b].end(); ++it)\n\t\t\t\tconnectbits_01234<2,false,false,false>(*it, bitdataresults[b+1], b, lowerpath, upperpath, bitdatanewcond[b], bitdataend[b], bitdatamincond[b]);\n\t\telse if (b < 6)\n\t\t\tfor (auto it = bitdataresults[b].begin(); it != bitdataresults[b].end(); ++it)\n\t\t\t\tconnectbits_01234<3,false,false,false>(*it, bitdataresults[b+1], b, lowerpath, upperpath, bitdatanewcond[b], bitdataend[b], bitdatamincond[b]);\n\t\telse if (b < 8)\n\t\t\tfor (auto it = bitdataresults[b].begin(); it != bitdataresults[b].end(); ++it)\n\t\t\t\tconnectbits_01234<4,false,false,false>(*it, bitdataresults[b+1], b, lowerpath, upperpath, bitdatanewcond[b], bitdataend[b], bitdatamincond[b]);\n\t\telse if (b < 32)\n\t\t\tfor (auto it = bitdataresults[b].begin(); it != bitdataresults[b].end(); ++it)\n\t\t\t\tconnectbits_01234<5,false,false,false>(*it, bitdataresults[b+1], b, lowerpath, upperpath, bitdatanewcond[b], bitdataend[b], bitdatamincond[b]);\n\t\telse throw;\n\t\t\n\t\tif (bitdataresults[b+1].size() == 0) \n\t\t\treturn b;\n\t\t// remove results that have more conditions than our current limit\n//\t\tfor (auto it = bitdataresults[b+1].begin(); it != bitdataresults[b+1].end(); )\n//\t\t\tif (it->second > container.bestpathcond)\n//\t\t\t\tit = bitdataresults[b+1].erase(it);\n//\t\t\telse\n//\t\t\t\t++it;\n\t\t\t\n\t\t++b;\n\t}\n\n\tunsigned mincond0 = 0;\n\tfor (int k = lowerpath.tbegin(); k < t-3 && k < lowerpath.tend(); ++k)\n\t\tmincond0 += lowerpath[k].hw();\n\tfor (int k = t+4; k < upperpath.tend(); ++k)\n\t\tmincond0 += upperpath[k].hw();\n\tbitdataresults[0].clear();\n\tbitdataresults[0][startdata]=mincond0;\n\n\tb = 0;\n\twhile (b < 32+8) {\t\t\n\t\tbitdataresults[b+1].clear();\n\t\tusedFtp1 = usedFtp2 = usedFtp3 = usedFtp4 = false;\n\t\tif (b < 2)\n\t\t\tfor (auto it = bitdataresults[b].begin(); it != bitdataresults[b].end(); ++it)\n\t\t\t\tconnectbits_01234<1,true,false,true>(*it, bitdataresults[b+1], b, lowerpath, upperpath, bitdatanewcond[b], bitdataend[b], bitdatamincond[b]);\n\t\telse if (b < 4)\n\t\t\tfor (auto it = bitdataresults[b].begin(); it != bitdataresults[b].end(); ++it)\n\t\t\t\tconnectbits_01234<2,true,false,true>(*it, bitdataresults[b+1], b, lowerpath, upperpath, bitdatanewcond[b], bitdataend[b], bitdatamincond[b]);\n\t\telse if (b < 6)\n\t\t\tfor (auto it = bitdataresults[b].begin(); it != bitdataresults[b].end(); ++it)\n\t\t\t\tconnectbits_01234<3,true,false,true>(*it, bitdataresults[b+1], b, lowerpath, upperpath, bitdatanewcond[b], bitdataend[b], bitdatamincond[b]);\n\t\telse if (b < 8)\n\t\t\tfor (auto it = bitdataresults[b].begin(); it != bitdataresults[b].end(); ++it)\n\t\t\t\tconnectbits_01234<4,true,false,true>(*it, bitdataresults[b+1], b, lowerpath, upperpath, bitdatanewcond[b], bitdataend[b], bitdatamincond[b]);\n\t\telse if (b < 32)\n\t\t\tfor (auto it = bitdataresults[b].begin(); it != bitdataresults[b].end(); ++it)\n\t\t\t\tconnectbits_01234<5,true,false,true>(*it, bitdataresults[b+1], b, lowerpath, upperpath, bitdatanewcond[b], bitdataend[b], bitdatamincond[b]);\n\t\telse if (b < 34)\n\t\t\tfor (auto it = bitdataresults[b].begin(); it != bitdataresults[b].end(); ++it)\n\t\t\t\tconnectbits_1234<false>(*it, bitdataresults[b+1], b, lowerpath, upperpath, bitdatanewcond[b], bitdataend[b], bitdatamincond[b]);\n\t\telse if (b < 36)\n\t\t\tfor (auto it = bitdataresults[b].begin(); it != bitdataresults[b].end(); ++it)\n\t\t\t\tconnectbits_234<false>(*it, bitdataresults[b+1], b, lowerpath, upperpath, bitdatanewcond[b], bitdataend[b], bitdatamincond[b]);\n\t\telse if (b < 38)\n\t\t\tfor (auto it = bitdataresults[b].begin(); it != bitdataresults[b].end(); ++it)\n\t\t\t\tconnectbits_34<false>(*it, bitdataresults[b+1], b, lowerpath, upperpath, bitdatanewcond[b], bitdataend[b], bitdatamincond[b]);\n\t\telse if (b < 40)\n\t\t\tfor (auto it = bitdataresults[b].begin(); it != bitdataresults[b].end(); ++it)\n\t\t\t\tconnectbits_4<false>(*it, bitdataresults[b+1], b, lowerpath, upperpath, bitdatanewcond[b], bitdataend[b], bitdatamincond[b]);\n\t\telse throw;\n\t\tif (bitdataresults[b+1].size() == 0)\n\t\t\tbreak;\n\n\t\t// remove results that have more conditions than our current limit\n\t\tfor (auto it = bitdataresults[b+1].begin(); it != bitdataresults[b+1].end(); )\n\t\t\tif (it->second > container.bestpathcond)\n\t\t\t\tit = bitdataresults[b+1].erase(it);\n\t\t\telse\n\t\t\t\t++it;\n\t\t\t\n\t\t++b;\n\t}\n\tif (b < 32+8) return b;\n\tif (returnb40) return 40;\n\t\n\tunsigned overalmincond = bitdataresults[40].begin()->second;\n\t\n//\tmincond[0].clear();\n//\tmincond[0].push_back(mincond0);\n\n\tfor (b = 0; b < 40; ++b)\n\t{\n\t\tbitdatastart[b].clear();\n\t\tbitdataend[b].clear();\n\t\tbitdatamincond[b].clear();\n\t\tbitdatanewcond[b].clear();\n\t\tbitdatanewcondhw[b].clear();\n\t\tmap<connect_bitdata,unsigned> tmpmap;\n//\t\tmincond[b+1].clear();\n//\t\tmincond[b+1].resize(bitdataresults[b+1].size(),262144);\n\t\tif (b < 2)\n\t\t\tfor (auto it = bitdataresults[b].begin(); it != bitdataresults[b].end(); ++it)\n\t\t\t{\n\t\t\t\ttmpmap.clear();\n\t\t\t\tconnectbits_01234<1,true,true>(*it, tmpmap, b, lowerpath, upperpath, bitdatanewcond[b], bitdataend[b], bitdatamincond[b]);\n\t\t\t\tif (bitdatanewcond[b].size() != bitdataend[b].size()) { cerr << \"#bitdatanewcond!=#bitdataend @ b=\" << b << endl; throw; }\n\t\t\t\tbitdatastart[b].resize(bitdataend[b].size(), it->first);\n\t\t\t}\n\t\telse if (b < 4)\n\t\t\tfor (auto it = bitdataresults[b].begin(); it != bitdataresults[b].end(); ++it)\n\t\t\t{\n\t\t\t\ttmpmap.clear();\n\t\t\t\tconnectbits_01234<2,true,true>(*it, tmpmap, b, lowerpath, upperpath, bitdatanewcond[b], bitdataend[b], bitdatamincond[b]);\n\t\t\t\tif (bitdatanewcond[b].size() != bitdataend[b].size()) { cerr << \"#bitdatanewcond!=#bitdataend @ b=\" << b << endl; throw; }\n\t\t\t\tbitdatastart[b].resize(bitdataend[b].size(), it->first);\n\t\t\t}\n\t\telse if (b < 6)\n\t\t\tfor (auto it = bitdataresults[b].begin(); it != bitdataresults[b].end(); ++it)\n\t\t\t{\n\t\t\t\ttmpmap.clear();\n\t\t\t\tconnectbits_01234<3,true,true>(*it, tmpmap, b, lowerpath, upperpath, bitdatanewcond[b], bitdataend[b], bitdatamincond[b]);\n\t\t\t\tif (bitdatanewcond[b].size() != bitdataend[b].size()) { cerr << \"#bitdatanewcond!=#bitdataend @ b=\" << b << endl; throw; }\n\t\t\t\tbitdatastart[b].resize(bitdataend[b].size(), it->first);\n\t\t\t}\n\t\telse if (b < 8)\n\t\t\tfor (auto it = bitdataresults[b].begin(); it != bitdataresults[b].end(); ++it) {\n\t\t\t\ttmpmap.clear();\n\t\t\t\tconnectbits_01234<4,true,true>(*it, tmpmap, b, lowerpath, upperpath, bitdatanewcond[b], bitdataend[b], bitdatamincond[b]);\n\t\t\t\tif (bitdatanewcond[b].size() != bitdataend[b].size()) { cerr << \"#bitdatanewcond!=#bitdataend @ b=\" << b << endl; throw; }\n\t\t\t\tbitdatastart[b].resize(bitdataend[b].size(), it->first);\n\t\t\t}\n\t\telse if (b < 32)\n\t\t\tfor (auto it = bitdataresults[b].begin(); it != bitdataresults[b].end(); ++it) {\n\t\t\t\ttmpmap.clear();\n\t\t\t\tconnectbits_01234<5,true,true>(*it, tmpmap, b, lowerpath, upperpath, bitdatanewcond[b], bitdataend[b], bitdatamincond[b]);\n\t\t\t\tif (bitdatanewcond[b].size() != bitdataend[b].size()) { cerr << \"#bitdatanewcond!=#bitdataend @ b=\" << b << endl; throw; }\n\t\t\t\tbitdatastart[b].resize(bitdataend[b].size(), it->first);\n\t\t\t}\n\t\telse if (b < 34)\n\t\t\tfor (auto it = bitdataresults[b].begin(); it != bitdataresults[b].end(); ++it) {\n\t\t\t\ttmpmap.clear();\n\t\t\t\tconnectbits_1234<true>(*it, tmpmap, b, lowerpath, upperpath, bitdatanewcond[b], bitdataend[b], bitdatamincond[b]);\n\t\t\t\tif (bitdatanewcond[b].size() != bitdataend[b].size()) { cerr << \"#bitdatanewcond!=#bitdataend @ b=\" << b << endl; throw; }\n\t\t\t\tbitdatastart[b].resize(bitdataend[b].size(), it->first);\n\t\t\t}\n\t\telse if (b < 36)\n\t\t\tfor (auto it = bitdataresults[b].begin(); it != bitdataresults[b].end(); ++it) {\n\t\t\t\ttmpmap.clear();\n\t\t\t\tconnectbits_234<true>(*it, tmpmap, b, lowerpath, upperpath, bitdatanewcond[b], bitdataend[b], bitdatamincond[b]);\n\t\t\t\tif (bitdatanewcond[b].size() != bitdataend[b].size()) { cerr << \"#bitdatanewcond!=#bitdataend @ b=\" << b << endl; throw; }\n\t\t\t\tbitdatastart[b].resize(bitdataend[b].size(), it->first);\n\t\t\t}\n\t\telse if (b < 38)\n\t\t\tfor (auto it = bitdataresults[b].begin(); it != bitdataresults[b].end(); ++it) {\n\t\t\t\ttmpmap.clear();\n\t\t\t\tconnectbits_34<true>(*it, tmpmap, b, lowerpath, upperpath, bitdatanewcond[b], bitdataend[b], bitdatamincond[b]);\n\t\t\t\tif (bitdatanewcond[b].size() != bitdataend[b].size()) { cerr << \"#bitdatanewcond!=#bitdataend @ b=\" << b << endl; throw; }\n\t\t\t\tbitdatastart[b].resize(bitdataend[b].size(), it->first);\n\t\t\t}\n\t\telse if (b < 40)\n\t\t\tfor (auto it = bitdataresults[b].begin(); it != bitdataresults[b].end(); ++it) {\n\t\t\t\ttmpmap.clear();\n\t\t\t\tconnectbits_4<true>(*it, tmpmap, b, lowerpath, upperpath, bitdatanewcond[b], bitdataend[b], bitdatamincond[b]);\n\t\t\t\tif (bitdatanewcond[b].size() != bitdataend[b].size()) { cerr << \"#bitdatanewcond!=#bitdataend @ b=\" << b << endl; throw; }\n\t\t\t\tbitdatastart[b].resize(bitdataend[b].size(), it->first);\n\t\t\t}\n\t\tbitdatanewcondhw[b].resize(bitdatanewcond[b].size());\n\t\tfor (unsigned k = 0; k < bitdatanewcond[b].size(); ++k)\n\t\t\tbitdatanewcondhw[b][k] = bitdatanewcond[b][k].first.hw();\n\t\tif (bitdatastart[b].size() != bitdataend[b].size()\n\t\t\t|| bitdataend[b].size() != bitdatanewcond[b].size())\n\t\t\tthrow;\n\t}\n//\tunsigned overalmincond = mincond[40][0];\n\tif (container.determinelowestcond) {\n\t\tif (overalmincond < container.bestpathcond) {\n\t\t\tcontainer.bestpathcond = overalmincond;\n\t\t\tcout << \"Best path: totcond=\" << container.bestpathcond << \" count=?\" << endl;\n\t\t}\n\t\treturn 40;\n\t}\n\tif (overalmincond > container.bestpathcond) \n\t\treturn 40;\n\tunsigned bestcond2 = 262144;\n\n\t/*static*/ sha1differentialpath newpath2;\n\tnewpath2 = lowerpath;\n\tfor (int k = upperpath.tbegin(); k < upperpath.tend(); ++k) {\n\t\tnewpath2[k] = upperpath[k];\n\t\tnewpath2.getme(k) = upperpath.getme(k);\n\t}\n\tunsigned bindex[40];\n\tunsigned bcond[40];\n\tunsigned bit = 39;\n\tbindex[bit] = 0;\n\tbcond[bit] = 0;\n\t//static uint64 badcnt = 0, okcnt = 0;\n\twhile (bit <= 39)\n\t{\n\t\tif (bindex[bit] < bitdataend[bit].size())\n\t\t{\t\t\t\n\t\t\t// check and update # conds\n//\t\t\tif (bcond[bit] + bitdatamincond[bit][bindex[bit]] > container.bestpathcond) {\n//\t\t\t\t--bit;\n//\t\t\t\tbindex[bit] = bitdataend[bit].size();\n//\t\t\t\tcontinue;\n//\t\t\t}\n\t\t\tbcond[bit-1] = bcond[bit] + bitdatanewcondhw[bit][bindex[bit]];\n\t\t\t// set bitconditions for committed bit\n\t\t\tif (bit < 32) {\n\t\t\t\tnewpath2.setbitcondition(t-3,(bit+2)&31,bitdatanewcond[bit][bindex[bit]].first[6]);\n\t\t\t\tset_sdr_bit(newpath2.getme(t),(bit+0)&31,bitdatanewcond[bit][bindex[bit]].second[4]);\n\t\t\t}\n\t\t\tif (bit >= 2 && bit < 32+2) {\n\t\t\t\tnewpath2.setbitcondition(t-2,(bit+0)&31,bitdatanewcond[bit][bindex[bit]].first[5]);\n\t\t\t\tset_sdr_bit(newpath2.getme(t+1),(bit+30)&31,bitdatanewcond[bit][bindex[bit]].second[3]);\n\t\t\t}\n\t\t\tif (bit >= 4 && bit < 32+4) {\n\t\t\t\tnewpath2.setbitcondition(t-1,(bit+30)&31,bitdatanewcond[bit][bindex[bit]].first[4]);\n\t\t\t\tset_sdr_bit(newpath2.getme(t+2),(bit+28)&31,bitdatanewcond[bit][bindex[bit]].second[2]);\n\t\t\t}\n\t\t\tif (bit >= 6 && bit < 32+6) {\n\t\t\t\tnewpath2.setbitcondition(t+0,(bit+28)&31,bitdatanewcond[bit][bindex[bit]].first[3]);\n\t\t\t\tset_sdr_bit(newpath2.getme(t+3),(bit+26)&31,bitdatanewcond[bit][bindex[bit]].second[1]);\n\t\t\t}\n\t\t\tif (bit >= 8 && bit < 32+8) {\n\t\t\t\tnewpath2.setbitcondition(t+3,(bit+24)&31,bitdatanewcond[bit][bindex[bit]].first[0]);\n\t\t\t\tnewpath2.setbitcondition(t+2,(bit+26)&31,bitdatanewcond[bit][bindex[bit]].first[1]);\n\t\t\t\tnewpath2.setbitcondition(t+1,(bit+26)&31,bitdatanewcond[bit][bindex[bit]].first[2]);\n\t\t\t\tset_sdr_bit(newpath2.getme(t+4),(bit+24)&31,bitdatanewcond[bit][bindex[bit]].second[0]);\n\t\t\t}\n\n\t\t\t--bit;\n\t\t\t// if bit==0 then create path\n\t\t\tif (bit != 0) {\n\t\t\t\tbindex[bit] = bitdataend[bit].size();\n\t\t\t\tfor (unsigned k = 0; k < bitdataend[bit].size(); ++k)\n\t\t\t\t\tif (bitdataend[bit][k] == bitdatastart[bit+1][bindex[bit+1]])\n\t\t\t\t\t{\n\t\t\t\t\t\tbindex[bit] = k;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (unsigned k = 0; k < bitdataend[0].size(); ++k)\n\t\t\t\t\tif (bitdataend[0][k] == bitdatastart[1][bindex[1]])\n\t\t\t\t\t{ // we have a full path !!!\n\t\t\t\t\t\tif (bcond[0] + bitdatanewcondhw[0][k] + mincond0 > container.bestpathcond) continue;\n\t\t\t\t\t\tbindex[0] = k;\n\t\t\t\t\t\tfor (unsigned b = 0; b < 1; ++b)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (b < 32) {\n\t\t\t\t\t\t\t\tnewpath2.setbitcondition(t-3,(b+2)&31,bitdatanewcond[b][bindex[b]].first[6]);\n\t\t\t\t\t\t\t\tset_sdr_bit(newpath2.getme(t),(b+0)&31,bitdatanewcond[b][bindex[b]].second[4]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (b >= 2 && b < 32+2) {\n\t\t\t\t\t\t\t\tnewpath2.setbitcondition(t-2,(b+0)&31,bitdatanewcond[b][bindex[b]].first[5]);\n\t\t\t\t\t\t\t\tset_sdr_bit(newpath2.getme(t+1),(b+30)&31,bitdatanewcond[b][bindex[b]].second[3]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (b >= 4 && b < 32+4) {\n\t\t\t\t\t\t\t\tnewpath2.setbitcondition(t-1,(b+30)&31,bitdatanewcond[b][bindex[b]].first[4]);\n\t\t\t\t\t\t\t\tset_sdr_bit(newpath2.getme(t+2),(b+28)&31,bitdatanewcond[b][bindex[b]].second[2]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (b >= 6 && b < 32+6) {\n\t\t\t\t\t\t\t\tnewpath2.setbitcondition(t+0,(b+28)&31,bitdatanewcond[b][bindex[b]].first[3]);\n\t\t\t\t\t\t\t\tset_sdr_bit(newpath2.getme(t+3),(b+26)&31,bitdatanewcond[b][bindex[b]].second[1]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (b >= 8 && b < 32+8) {\n\t\t\t\t\t\t\t\tnewpath2.setbitcondition(t+3,(b+24)&31,bitdatanewcond[b][bindex[b]].first[0]);\n\t\t\t\t\t\t\t\tnewpath2.setbitcondition(t+2,(b+26)&31,bitdatanewcond[b][bindex[b]].first[1]);\n\t\t\t\t\t\t\t\tnewpath2.setbitcondition(t+1,(b+26)&31,bitdatanewcond[b][bindex[b]].first[2]);\n\t\t\t\t\t\t\t\tset_sdr_bit(newpath2.getme(t+4),(b+24)&31,bitdatanewcond[b][bindex[b]].second[0]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontainer.push_back(newpath2);\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\tbindex[bit] = bitdataend[bit].size();\n\t\t\t}\n\t\t} else\n\t\t{\n\t\t\t++bit;\n\t\t\tif (bit <= 39)\n\t\t\t{\n\t\t\t\t++bindex[bit];\n\t\t\t\tif (bit < 39)\n\t\t\t\t{\n\t\t\t\t\twhile (bindex[bit] < bitdataend[bit].size()\n\t\t\t\t\t\t&& ((bitdataend[bit][bindex[bit]]) != (bitdatastart[bit+1][bindex[bit+1]])))\n\t\t\t\t\t\t++bindex[bit];\n\t\t\t\t\tif (bindex[bit] < bitdataend[bit].size())\n\t\t\t\t\t\tbcond[bit] = bcond[bit+1] + bitdatanewcond[bit+1][bindex[bit+1]].first.hw();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn 40;\n}\n\nvoid sha1_connect_thread::sha1_connect(const sha1differentialpath& lowerpath\n\t\t\t\t , const vector<sha1differentialpath>& upperpaths\n\t\t\t\t , path_container& container, unsigned prev_eq_b)\n{\n\tif (lowerpath.path.size() == 0) {\n\t\tcout << \"lowerpath empty!\" << endl;\n\t\treturn;\n\t}\n\tif (dpFt.size() == 0) {\n\t\tt = container.t;\n\t\tmmaskt = container.m_mask[t];\n\t\tmmasktp1 = container.m_mask[t+1];\n\t\tmmasktp2 = container.m_mask[t+2];\n\t\tmmasktp3 = container.m_mask[t+3];\n\t\tmmasktp4 = container.m_mask[t+4];\n\n\t\tFt = sha1bf(t);\n\t\tFtp1 = sha1bf(t+1);\n\t\tFtp2 = sha1bf(t+2);\n\t\tFtp3 = sha1bf(t+3);\n\t\tFtp4 = sha1bf(t+4);\n\n\t\tdpFt.resize(upperpaths.size());\n\t\tdpFtp1.resize(upperpaths.size());\n\t\tdpFtp2.resize(upperpaths.size());\n\t\tdpFtp3.resize(upperpaths.size());\n\t\tdpFtp4.resize(upperpaths.size());\n\t\tdQtp1.resize(upperpaths.size());\n\t\tfor (unsigned i = 0; i < upperpaths.size(); ++i) {\n\t\t\tdpFt[i] = upperpaths[i][t+1].diff();\n\t\t\tdpFtp1[i] = upperpaths[i][t+2].diff() - upperpaths[i][t+1].getsdr().rotate_left(5).adddiff();\n\t\t\tdpFtp2[i] = upperpaths[i][t+3].diff() - upperpaths[i][t+2].getsdr().rotate_left(5).adddiff();\n\t\t\tdpFtp3[i] = upperpaths[i][t+4].diff() - upperpaths[i][t+3].getsdr().rotate_left(5).adddiff();\n\t\t\tdpFtp4[i] = upperpaths[i][t+5].diff() - upperpaths[i][t+4].getsdr().rotate_left(5).adddiff();\n\t\t\tdQtp1[i] = upperpaths[i][t+1].diff();\n\t\t}\n\t\tprevb.resize(upperpaths.size(),40);\n\n\t\ttbc = container.tunnelconditions;\n\t\ttbc.get(t-3); tbc.get(t+3);\n\t\tQtm3freemask = Qtm2freemask = Qtm1freemask = Qtfreemask = Qtp1freemask = Qtp2freemask = Qtp3freemask = 0;\n\t\tfor (unsigned b = 0; b < 32; ++b) {\n\t\t\tif (container.tunnelconditions(t-3,b) == bc_plus || container.tunnelconditions(t-3,b) == bc_minus) Qtm3freemask |= 1<<b;\n\t\t\tif (container.tunnelconditions(t-2,b) == bc_plus || container.tunnelconditions(t-2,b) == bc_minus) Qtm2freemask |= 1<<b;\n\t\t\tif (container.tunnelconditions(t-1,b) == bc_plus || container.tunnelconditions(t-1,b) == bc_minus) Qtm1freemask |= 1<<b;\n\t\t\tif (container.tunnelconditions(t,b) == bc_plus || container.tunnelconditions(t,b) == bc_minus) Qtfreemask |= 1<<b;\n\t\t\tif (container.tunnelconditions(t+1,b) == bc_plus || container.tunnelconditions(t+1,b) == bc_minus) Qtp1freemask |= 1<<b;\n\t\t\tif (container.tunnelconditions(t+2,b) == bc_plus || container.tunnelconditions(t+2,b) == bc_minus) Qtp2freemask |= 1<<b;\n\t\t\tif (container.tunnelconditions(t+3,b) == bc_plus || container.tunnelconditions(t+3,b) == bc_minus) Qtp3freemask |= 1<<b;\n\t\t}\n\t}\n\tuint32 dlFt = 0 - lowerpath[t].getsdr().rotate_left(5).adddiff() - lowerpath[t-4].getsdr().rotate_left(30).adddiff();\n\tuint32 dlFtp1 = 0 - lowerpath[t-3].getsdr().rotate_left(30).adddiff();\n\tuint32 dlFtp2 = 0 - lowerpath[t-2].getsdr().rotate_left(30).adddiff();\n\tuint32 dlFtp3 = 0 - lowerpath[t-1].getsdr().rotate_left(30).adddiff();\n\tuint32 dlFtp4 = 0 - lowerpath[t].getsdr().rotate_left(30).adddiff();\n\n\tuint32 dQtm1 = lowerpath[t-1].diff();\n\tuint32 dQt = lowerpath[t].diff();\n\n\tvector<connect_bitdata> bitdataresults[41];\n\tconnect_bitdata startdata;\n\tstartdata.dQtm1 = dQtm1;\n\tstartdata.dQt = dQt;\n\tfor (unsigned j = 0; j < 2; ++j)\n\t{\n\t\tstartdata.rqtm2[j] = startdata.rqtm1[j] = startdata.rqt[j] = startdata.rqtp1[j] = bc_constant;\n\t\tstartdata.fqtm1[j] = startdata.fqt[j] = startdata.fqtp1[j] = startdata.fqtp2[j] = bc_constant;\n\t}\n\n\tQtm1b31not = Qtb31not = bc_plus;\n\tQtm1b31not2 = Qtb31not2 = bc_constant;\n\tfor (unsigned b = 27; b <= 31; ++b) {\n\t\tif (lowerpath(t-1,b) == bc_minus) Qtm1b31not = bc_plus;\n\t\tif (lowerpath(t-1,b) == bc_plus) Qtm1b31not = bc_minus;\n\t\tif (lowerpath(t,b) == bc_minus) Qtb31not = bc_plus;\n\t\tif (lowerpath(t,b) == bc_plus) Qtb31not = bc_minus;\n\t}\n\tif (lowerpath(t-1,31) == bc_constant) Qtm1b31not2 = Qtm1b31not;\n\tif (lowerpath(t,31) == bc_constant) Qtb31not2 = Qtb31not;\n\tsdr sdrQtm1 = lowerpath[t-1].getsdr();\n\tsdrQtm1.mask &= uint32(0)-uint32(1<<2); sdrQtm1.sign &= sdrQtm1.mask;\t\n\tdQtm1b2b31 = sdrQtm1.adddiff();\n\tsdrQtm1.mask &= uint32(0)-uint32(1<<27); sdrQtm1.sign &= sdrQtm1.mask;\n\tdQtm1b27b31 = sdrQtm1.adddiff();\n\tsdr sdrQt = lowerpath[t].getsdr();\n\tsdrQt.mask &= uint32(0)-uint32(1<<2); sdrQt.sign &= sdrQt.mask;\t\n\tdQtb2b31 = sdrQt.adddiff();\n\tsdrQt.mask &= uint32(0)-uint32(1<<27); sdrQt.sign &= sdrQt.mask;\n\tdQtb27b31 = sdrQt.adddiff();\n\n\tbool connected = false;\n\tunsigned i = 0;\n\tunsigned testcount = 0;\n\tunsigned highestb = 0;\n\t/*static vector<uint64> bcnt(41,0);*/\n\twhile (i < upperpaths.size()) {\n\t\tQtp1b31not = bc_plus;\n\t\tQtp1b31not2 = bc_constant;\n\t\tfor (unsigned b = 27; b <= 31; ++b) {\n\t\t\tif (upperpaths[i](t+1,b) == bc_minus) Qtp1b31not = bc_plus;\n\t\t\tif (upperpaths[i](t+1,b) == bc_plus) Qtp1b31not = bc_minus;\n\t\t}\n\t\tif (upperpaths[i](t+1,31) == bc_constant) Qtp1b31not2 = Qtp1b31not;\n\t\tsdr sdrQtp1 = upperpaths[i][t+1].getsdr();\n\t\tsdrQtp1.mask &= uint32(0)-uint32(1<<2); sdrQtp1.sign &= sdrQtp1.mask;\t\n\t\tdQtp1b2b31 = sdrQtp1.adddiff();\n\t\tsdrQtp1.mask &= uint32(0)-uint32(1<<27); sdrQtp1.sign &= sdrQtp1.mask;\n\t\tdQtp1b27b31 = sdrQtp1.adddiff();\n\n\t\tbitdataresults[0].clear();\n\t\tstartdata.dQtp1 = dQtp1[i];\n\t\tstartdata.dFt = dpFt[i] + dlFt;\n\t\tstartdata.dFtp1 = dpFtp1[i] + dlFtp1;\n\t\tstartdata.dFtp2 = dpFtp2[i] + dlFtp2;\n\t\tstartdata.dFtp3 = dpFtp3[i] + dlFtp3;\n\t\tstartdata.dFtp4 = dpFtp4[i] + dlFtp4;\n\t\tunsigned b = prevb[i];\n\t\tif (b >= prev_eq_b)\n\t\t\tb = connect_paths(lowerpath, upperpaths[i], startdata, container, false);\n\t\tprevb[i] = b;\n\t\tif (0) { //b == 40) {\n\t\t\tcout << \"?\" << flush; \n\t\t\tmmaskt = container.m_mask[t];\n\t\t\tmmasktp1 = container.m_mask[t+1];\n\t\t\tmmasktp2 = container.m_mask[t+2];\n\t\t\tmmasktp3 = container.m_mask[t+3];\n\t\t\tmmasktp4 = container.m_mask[t+4];\n\t\t\tb = connect_paths(lowerpath, upperpaths[i], startdata, container, false);\n\t\t\tmmaskt = mmasktp1 = mmasktp2 = mmasktp3 = mmasktp4 = 0;\n\t\t}\n\t\tif (b < 32+8) {\t\t\t\n\t\t\tunsigned j = i+1;\n\t\t\tuint32 ftmask = ~uint32(0); if (b < 32) ftmask >>= (31-b);\n\t\t\tuint32 ftp1mask = ~uint32(0); \n\t\t\tif (b < 2) ftp1mask = 0; else if (b-2 < 32) { ftp1mask >>=(31-(b-2)); if (!usedFtp1) ftp1mask >>=1; }\n\t\t\tuint32 qtp1mask = ~uint32(0); \n\t\t\tif (b < 4) qtp1mask = 0; else if (b-4 < 32) { qtp1mask >>=(31-(b-4)); if (!usedFtp2) qtp1mask >>=1; }\n\t\t\tuint32 ftp2mask = ~uint32(0); \n\t\t\tif (b < 4) ftp2mask = 0; else if (b-4 < 32) { ftp2mask >>=(31-(b-4)); if (!usedFtp2) ftp2mask >>=1; }\n\t\t\tunsigned qtp2bits = 32; \n\t\t\tif (b < 6) qtp2bits = 0; else if (b-6 < 32) { qtp2bits = b-5; if (!usedFtp3) qtp2bits -= 1; }\n\t\t\tuint32 ftp3mask = ~uint32(0); \n\t\t\tif (b < 6) ftp3mask = 0; else if (b-6 < 32) { ftp3mask >>=(31-(b-6)); if (!usedFtp3) ftp3mask >>=1; }\n\t\t\tunsigned qtp3bits = 32; \n\t\t\tif (b < 8) qtp3bits = 0; else if (b-8 < 32) { qtp3bits = b-7; if (!usedFtp4) qtp3bits -= 1; }\n\t\t\tuint32 ftp4mask = ~uint32(0); \n\t\t\tif (b < 8) ftp4mask = 0; else if (b-8 < 32) { ftp4mask >>=(31-(b-8)); if (!usedFtp4) ftp4mask >>=1; }\n\t\t\t\n\t\t\twhile (j < upperpaths.size()) {\n\t\t\t\tif ((dpFt[i]^dpFt[j])&ftmask) break;\n\t\t\t\tif ((dpFtp1[i]^dpFtp1[j])&ftp1mask) break;\n\t\t\t\tif ((dQtp1[i]^dQtp1[j])&qtp1mask) break;\n\t\t\t\tif ((dpFtp2[i]^dpFtp2[j])&ftp2mask) break;\n\t\t\t\tif ((dpFtp3[i]^dpFtp3[j])&ftp3mask) break;\n\t\t\t\tif ((dpFtp4[i]^dpFtp4[j])&ftp4mask) break;\n\t\t\t\tbool bcok = true;\n\t\t\t\tfor (unsigned k = 0; bcok && k < qtp2bits; ++k)\n\t\t\t\t\tif (upperpaths[i](t+2,k) != upperpaths[j](t+2,k))\n\t\t\t\t\t\tbcok = false;\n\t\t\t\tfor (unsigned k = 0; bcok && k < qtp3bits; ++k)\n\t\t\t\t\tif (upperpaths[i](t+3,k) != upperpaths[j](t+3,k))\n\t\t\t\t\t\tbcok = false;\n\t\t\t\tif (!bcok) break;\n\t\t\t\tprevb[j]=b;\n\t\t\t\t++j;\n\t\t\t}\n\t\t\ti = j;\n\t\t} else {\n\t\t\t++i;\n\t\t\tconnected = true;\n\t\t}\n\t\tif (b > highestb) highestb = b;\n\t\t++bcnt[b];\n\t}\n\tif (connected)\n\t\tcout << \"+\" << flush;\n\t/*static timer sw(true);*/\n\tif (container.showstats && sw.time() > 3600) {\n\t\tcout << endl;\n\t\tfor (unsigned i = 0; i < bcnt.size(); ++i)\n\t\t\tcout << i << \": \" << bcnt[i] << endl;\n\t\tsw.start();\n\t}\n\t/*static timer sw2(true);*/\n\tif (sw2.time() > 600) {\n\t\tcontainer.save_bestpaths();\n\t\tsw2.start();\n\t}\n}\n", "meta": {"hexsha": "31dcf4e71c92201cd1af216d67df9dd4375ea410", "size": 60348, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sha1connect/connect.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/sha1connect/connect.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/sha1connect/connect.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": 42.8607954545, "max_line_length": 192, "alphanum_fraction": 0.6219758733, "num_tokens": 21949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.28404213515451826}}
{"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 <Eigen/Geometry>\n#include <visualization_msgs/Marker.h>\n#include <arc_utilities/eigen_helpers.hpp>\n#include <arc_utilities/voxel_grid.hpp>\n#include <sdf_tools/SDF.h>\n\n#ifndef SDF_HPP\n#define SDF_HPP\n\ninline std::vector<uint8_t> FloatToBinary(float value)\n{\n    uint32_t binary_value = 0;\n    memcpy(&binary_value, &value, sizeof(uint32_t));\n    std::vector<uint8_t> binary(4);\n    // Copy byte 1, least-significant byte\n    binary[3] = binary_value & 0x000000ff;\n    // Copy byte 2\n    binary_value = binary_value >> 8;\n    binary[2] = binary_value & 0x000000ff;\n    // Copy byte 3\n    binary_value = binary_value >> 8;\n    binary[1] = binary_value & 0x000000ff;\n    // Copy byte 4, most-significant byte\n    binary_value = binary_value >> 8;\n    binary[0] = binary_value & 0x000000ff;\n    return binary;\n}\n\ninline float FloatFromBinary(std::vector<uint8_t>& binary)\n{\n    if (binary.size() != 4)\n    {\n        std::cerr << \"Binary value is not 4 bytes\" << std::endl;\n        return NAN;\n    }\n    else\n    {\n        uint32_t binary_value = 0;\n        // Copy in byte 4, most-significant byte\n        binary_value = binary_value | binary[0];\n        binary_value = binary_value << 8;\n        // Copy in byte 3\n        binary_value = binary_value | binary[1];\n        binary_value = binary_value << 8;\n        // Copy in byte 2\n        binary_value = binary_value | binary[2];\n        binary_value = binary_value << 8;\n        // Copy in byte 1, least-significant byte\n        binary_value = binary_value | binary[3];\n        // Convert binary to float and store\n        float field_value = 0.0;\n        memcpy(&field_value, &binary_value, sizeof(float));\n        return field_value;\n    }\n}\n\nnamespace sdf_tools\n{\n    class SignedDistanceField\n    {\n    protected:\n\n        VoxelGrid::VoxelGrid<float> distance_field_;\n        std::string frame_;\n        bool initialized_;\n        bool locked_;\n\n        std::vector<uint8_t> GetInternalBinaryRepresentation(const std::vector<float> &field_data);\n\n        std::vector<float> UnpackFieldFromBinaryRepresentation(std::vector<uint8_t>& binary);\n\n        /*\n         * You *MUST* provide valid indices to this function, hence why it is protected (there are safe wrappers available - use them!)\n         */\n        void FollowGradientsToLocalMaximaUnsafe(VoxelGrid::VoxelGrid<Eigen::Vector3d>& watershed_map, const int64_t x_index, const int64_t y_index, const int64_t z_index) const;\n\n    public:\n\n        EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n        inline SignedDistanceField(std::string frame, double resolution, double x_size, double y_size, double z_size, float OOB_value) : initialized_(true), locked_(false)\n        {\n            frame_ = frame;\n            VoxelGrid::VoxelGrid<float> new_field(resolution, x_size, y_size, z_size, OOB_value);\n            distance_field_ = new_field;\n        }\n\n        inline SignedDistanceField(Eigen::Affine3d origin_transform, std::string frame, double resolution, double x_size, double y_size, double z_size, float OOB_value) : initialized_(true), locked_(false)\n        {\n            frame_ = frame;\n            VoxelGrid::VoxelGrid<float> new_field(origin_transform, resolution, x_size, y_size, z_size, OOB_value);\n            distance_field_ = new_field;\n        }\n\n        inline SignedDistanceField() : initialized_(false), locked_(false) {}\n\n        inline bool IsInitialized() const\n        {\n            return initialized_;\n        }\n\n        inline bool IsLocked() const\n        {\n            return locked_;\n        }\n\n        inline void Lock()\n        {\n            locked_ = true;\n        }\n\n        inline void Unlock()\n        {\n            locked_ = false;\n        }\n\n        inline float Get(const double x, const double y, const double z) const\n        {\n            return distance_field_.GetImmutable(x, y, z).first;\n        }\n\n        inline float Get3d(const Eigen::Vector3d& location) const\n        {\n            return distance_field_.GetImmutable3d(location).first;\n        }\n\n        inline float Get4d(const Eigen::Vector4d& location) const\n        {\n            return distance_field_.GetImmutable4d(location).first;\n        }\n\n        inline float Get(const int64_t x_index, const int64_t y_index, const int64_t z_index) const\n        {\n            return distance_field_.GetImmutable(x_index, y_index, z_index).first;\n        }\n\n        inline std::pair<float, bool> GetSafe(const double x, const double y, const double z) const\n        {\n            return distance_field_.GetImmutable(x, y, z);\n        }\n\n        inline std::pair<float, bool> GetSafe3d(const Eigen::Vector3d& location) const\n        {\n            return distance_field_.GetImmutable3d(location);\n        }\n\n        inline std::pair<float, bool> GetSafe4d(const Eigen::Vector4d& location) const\n        {\n            return distance_field_.GetImmutable4d(location);\n        }\n\n        inline std::pair<float, bool> GetSafe(const int64_t x_index, const int64_t y_index, const int64_t z_index) const\n        {\n            return distance_field_.GetImmutable(x_index, y_index, z_index);\n        }\n\n        /*\n         * Setter functions MUST be used carefully - If you arbitrarily change SDF values, it is not a proper SDF any more!\n         *\n         * Use of these functions can be prevented by calling SignedDistanceField::Lock() on the SDF, at which point these functions\n         * will fail with a warning printed to std_err.\n         */\n        inline bool Set(const double x, const double y, const double z, float value)\n        {\n            if (!locked_)\n            {\n                return distance_field_.SetValue(x, y, z, value);\n            }\n            else\n            {\n                std::cerr << \"Attempt to set value in locked SDF\" << std::endl;\n                return false;\n            }\n        }\n\n        inline bool Set3d(const Eigen::Vector3d& location, float value)\n        {\n            if (!locked_)\n            {\n                return distance_field_.SetValue3d(location, value);\n            }\n            else\n            {\n                std::cerr << \"Attempt to set value in locked SDF\" << std::endl;\n                return false;\n            }\n        }\n\n        inline bool Set4d(const Eigen::Vector4d& location, float value)\n        {\n            if (!locked_)\n            {\n                return distance_field_.SetValue4d(location, value);\n            }\n            else\n            {\n                std::cerr << \"Attempt to set value in locked SDF\" << std::endl;\n                return false;\n            }\n        }\n\n        inline bool Set(const int64_t x_index, const int64_t y_index, const int64_t z_index, const float value)\n        {\n            if (!locked_)\n            {\n                return distance_field_.SetValue(x_index, y_index, z_index, value);\n            }\n            else\n            {\n                std::cerr << \"Attempt to set value in locked SDF\" << std::endl;\n                return false;\n            }\n        }\n\n        inline bool Set(const VoxelGrid::GRID_INDEX& index, const float value)\n        {\n            if (!locked_)\n            {\n                return distance_field_.SetValue(index, value);\n            }\n            else\n            {\n                std::cerr << \"Attempt to set value in locked SDF\" << std::endl;\n                return false;\n            }\n        }\n\n        inline bool CheckInBounds3d(const Eigen::Vector3d& location) const\n        {\n            return distance_field_.GetImmutable3d(location).second;\n        }\n\n        inline bool CheckInBounds4d(const Eigen::Vector4d& location) const\n        {\n            return distance_field_.GetImmutable4d(location).second;\n        }\n\n        inline bool CheckInBounds(const double x, const double y, const double z) const\n        {\n            return distance_field_.GetImmutable(x, y, z).second;\n        }\n\n        inline bool CheckInBounds(const VoxelGrid::GRID_INDEX& index) const\n        {\n            return distance_field_.GetImmutable(index.x, index.y, index.z).second;\n        }\n\n        inline bool CheckInBounds(const int64_t x_index, const int64_t y_index, const int64_t z_index) const\n        {\n            return distance_field_.GetImmutable(x_index, y_index, z_index).second;\n        }\n\n        inline double GetXSize() const\n        {\n            return distance_field_.GetXSize();\n        }\n\n        inline double GetYSize() const\n        {\n            return distance_field_.GetYSize();\n        }\n\n        inline double GetZSize() const\n        {\n            return distance_field_.GetZSize();\n        }\n\n        inline double GetResolution() const\n        {\n            return distance_field_.GetCellSizes()[0];\n        }\n\n        inline float GetOOBValue() const\n        {\n            return distance_field_.GetDefaultValue();\n        }\n\n        inline int64_t GetNumXCells() const\n        {\n            return distance_field_.GetNumXCells();\n        }\n\n        inline int64_t GetNumYCells() const\n        {\n            return distance_field_.GetNumYCells();\n        }\n\n        inline int64_t GetNumZCells() const\n        {\n            return distance_field_.GetNumZCells();\n        }\n\n    protected:\n\n        inline std::pair<Eigen::Vector3d, double> GetPrimaryComponentsVector(const Eigen::Vector3d& raw_vector) const\n        {\n            if (std::abs(raw_vector.x()) > std::abs(raw_vector.y()) && std::abs(raw_vector.x()) > std::abs(raw_vector.z()))\n            {\n                if (raw_vector.x() >= 0.0)\n                {\n                    return std::make_pair(Eigen::Vector3d(GetResolution() * 0.5, 0.0, 0.0), GetResolution() * 0.5);\n                }\n                else\n                {\n                    return std::make_pair(Eigen::Vector3d(GetResolution() * -0.5, 0.0, 0.0), GetResolution() * 0.5);\n                }\n            }\n            else if (std::abs(raw_vector.y()) > std::abs(raw_vector.x()) && std::abs(raw_vector.y()) > std::abs(raw_vector.z()))\n            {\n                if (raw_vector.y() >= 0.0)\n                {\n                    return std::make_pair(Eigen::Vector3d(0.0, GetResolution() * 0.5, 0.0), GetResolution() * 0.5);\n                }\n                else\n                {\n                    return std::make_pair(Eigen::Vector3d(0.0, GetResolution() * -0.5, 0.0), GetResolution() * 0.5);\n                }\n            }\n            else if (std::abs(raw_vector.z()) > std::abs(raw_vector.x()) && std::abs(raw_vector.z()) > std::abs(raw_vector.y()))\n            {\n                if (raw_vector.z() >= 0.0)\n                {\n                    return std::make_pair(Eigen::Vector3d(0.0, 0.0, GetResolution() * 0.5), GetResolution() * 0.5);\n                }\n                else\n                {\n                    return std::make_pair(Eigen::Vector3d(0.0, 0.0, GetResolution() * -0.5), GetResolution() * 0.5);\n                }\n            }\n            else if (std::abs(raw_vector.x()) == std::abs(raw_vector.y()))\n            {\n                const Eigen::Vector3d temp_vector(raw_vector.x(), raw_vector.y(), 0.0);\n                return std::make_pair((temp_vector / (temp_vector.norm())) * std::sqrt((GetResolution() * GetResolution() * 0.25) * 2.0), std::sqrt((GetResolution() * GetResolution() * 0.25) * 2.0));\n            }\n            else if (std::abs(raw_vector.y()) == std::abs(raw_vector.z()))\n            {\n                const Eigen::Vector3d temp_vector(0.0, raw_vector.y(), raw_vector.x());\n                return std::make_pair((temp_vector / (temp_vector.norm())) * std::sqrt((GetResolution() * GetResolution() * 0.25) * 2.0), std::sqrt((GetResolution() * GetResolution() * 0.25) * 2.0));\n            }\n            else if (std::abs(raw_vector.x()) == std::abs(raw_vector.z()))\n            {\n                const Eigen::Vector3d temp_vector(raw_vector.x(), 0.0, raw_vector.z());\n                return std::make_pair((temp_vector / (temp_vector.norm())) * std::sqrt((GetResolution() * GetResolution() * 0.25) * 2.0), std::sqrt((GetResolution() * GetResolution() * 0.25) * 2.0));\n            }\n            else\n            {\n                return std::make_pair((raw_vector / (raw_vector.norm())) * std::sqrt((GetResolution() * GetResolution() * 0.25) * 3.0), std::sqrt((GetResolution() * GetResolution() * 0.25) * 3.0));\n            }\n        }\n\n        inline double ComputeAxisMatch(const double axis_value, const double check_value) const\n        {\n            if ((axis_value >= 0.0) == (check_value >= 0.0))\n            {\n                return std::abs(check_value - axis_value);\n            }\n            else\n            {\n                return -std::abs(check_value - axis_value);\n            }\n        }\n\n        inline Eigen::Vector3d GetBestMatchSurfaceVector(const Eigen::Vector3d& possible_surfaces_vector, const Eigen::Vector3d& center_to_location_vector) const\n        {\n            const Eigen::Vector3d location_rejected_on_possible = EigenHelpers::VectorRejection(possible_surfaces_vector, center_to_location_vector);\n            // Find the axis with the best-match components\n            const double x_axis_match = ComputeAxisMatch(possible_surfaces_vector.x(), location_rejected_on_possible.x());\n            const double y_axis_match = ComputeAxisMatch(possible_surfaces_vector.y(), location_rejected_on_possible.y());\n            const double z_axis_match = ComputeAxisMatch(possible_surfaces_vector.z(), location_rejected_on_possible.z());\n            if ((x_axis_match > y_axis_match) && (x_axis_match > z_axis_match))\n            {\n                return Eigen::Vector3d(possible_surfaces_vector.x(), 0.0, 0.0);\n            }\n            else if ((y_axis_match > x_axis_match) && (y_axis_match > z_axis_match))\n            {\n                return Eigen::Vector3d(0.0, possible_surfaces_vector.y(), 0.0);\n            }\n            else if ((z_axis_match > x_axis_match) && (z_axis_match > y_axis_match))\n            {\n                return Eigen::Vector3d(0.0, 0.0, possible_surfaces_vector.z());\n            }\n            else\n            {\n                assert(false);\n                return possible_surfaces_vector;\n            }\n        }\n\n        /**\n         * @brief GetPrimaryEntrySurfaceVector Estimates the real distance of the provided point, comparing it with the cell center location and gradient vector\n         * @param boundary_direction_vector\n         * @param center_to_location_vector\n         * @return vector from center of voxel to primary entry surface, and magnitude of that vector\n         */\n        inline std::pair<Eigen::Vector3d, double> GetPrimaryEntrySurfaceVector(const Eigen::Vector3d& boundary_direction_vector, const Eigen::Vector3d& center_to_location_vector) const\n        {\n            if (boundary_direction_vector.squaredNorm() > std::numeric_limits<double>::epsilon())\n            {\n                const std::pair<Eigen::Vector3d, double> primary_components_vector_query = GetPrimaryComponentsVector(boundary_direction_vector);\n                // If the cell is on a surface\n                if (primary_components_vector_query.second == (GetResolution() * 0.5))\n                {\n                    return primary_components_vector_query;\n                }\n                // If the cell is on an edge or surface\n                else\n                {\n                    // Pick the best-match of the two/three exposed surfaces\n                    return std::make_pair(GetBestMatchSurfaceVector(primary_components_vector_query.first, center_to_location_vector), GetResolution() * 0.5);\n                }\n            }\n            else\n            {\n                return GetPrimaryComponentsVector(center_to_location_vector);\n            }\n        }\n\n        inline double EstimateDistanceInternal(const double x, const double y, const double z, const int64_t x_idx, const int64_t y_idx, const int64_t z_idx) const\n        {\n            const std::vector<double> cell_center = GridIndexToLocation(x_idx, y_idx, z_idx);\n            const Eigen::Vector3d cell_center_to_location_vector(x - cell_center[0], y - cell_center[1], z - cell_center[2]);\n            const double nominal_sdf_distance = (double)distance_field_.GetImmutable(x_idx, y_idx, z_idx).first;\n\n            // Determine vector from \"entry surface\" to center of voxel\n            // TODO: Needs special handling if there's no gradient to work with\n            const std::vector<double> raw_gradient = GetGradient(x_idx, y_idx, z_idx, true);\n            const Eigen::Vector3d gradient = EigenHelpers::StdVectorDoubleToEigenVector3d(raw_gradient);\n            const Eigen::Vector3d direction_to_boundary = (nominal_sdf_distance >= 0.0) ? -gradient : gradient;\n            const std::pair<Eigen::Vector3d, double> entry_surface_information = GetPrimaryEntrySurfaceVector(direction_to_boundary, cell_center_to_location_vector);\n            const Eigen::Vector3d& entry_surface_vector = entry_surface_information.first;\n            const double minimum_distance_magnitude = entry_surface_information.second;\n\n            // Adjust for calculating distance to boundary of voxels instead of center of voxels\n            const double center_adjusted_nominal_distance = (nominal_sdf_distance >= 0.0) ? nominal_sdf_distance - (GetResolution() * 0.5) : nominal_sdf_distance + (GetResolution() * 0.5);\n            const double minimum_adjusted_distance = arc_helpers::SpreadValue(center_adjusted_nominal_distance, -minimum_distance_magnitude, 0.0, minimum_distance_magnitude);\n\n            // Account for target location being not at the exact center of the voxel\n            const double raw_distance_adjustment = EigenHelpers::VectorProjection(entry_surface_vector, cell_center_to_location_vector).norm();\n            const double real_distance_adjustment = (minimum_adjusted_distance >= 0.0) ? -raw_distance_adjustment: raw_distance_adjustment;\n            const double final_adjusted_distance = minimum_adjusted_distance + real_distance_adjustment;\n\n            // Perform minimum distance thresholding and error checking\n            // TODO: do we need to address this magic number somehow?\n            if (std::abs(final_adjusted_distance) < GetResolution() * 0.001)\n            {\n                return 0.0;\n            }\n            if ((minimum_adjusted_distance >= 0.0) == (final_adjusted_distance >= 0.0))\n            {\n                return final_adjusted_distance;\n            }\n            else\n            {\n                std::cerr << \"Center adjusted nominal distance \" << minimum_adjusted_distance << \" final adjusted_distance \" << final_adjusted_distance << std::endl;\n                assert(false && \"Mismatched minimum and final adjusted distance signs\");\n            }\n        }\n\n    public:\n\n        inline std::pair<double, bool> EstimateDistance(const double x, const double y, const double z) const\n        {\n            return EstimateDistance4d(Eigen::Vector4d(x, y, z, 1.0));\n        }\n\n        inline std::pair<double, bool> EstimateDistance3d(const Eigen::Vector3d& location) const\n        {\n            const std::vector<int64_t> indices = LocationToGridIndex3d(location);\n            if (indices.size() == 3)\n            {\n                return std::make_pair(EstimateDistanceInternal(location.x(), location.y(), location.z(), indices[0], indices[1], indices[2]), true);\n            }\n            else\n            {\n                return std::make_pair((double)distance_field_.GetOOBValue(), false);\n            }\n        }\n\n        inline std::pair<double, bool> EstimateDistance4d(const Eigen::Vector4d& location) const\n        {\n            const std::vector<int64_t> indices = LocationToGridIndex4d(location);\n            if (indices.size() == 3)\n            {\n                return std::make_pair(EstimateDistanceInternal(location(0), location(1), location(2), indices[0], indices[1], indices[2]), true);\n            }\n            else\n            {\n                return std::make_pair((double)distance_field_.GetOOBValue(), false);\n            }\n        }\n\n        inline std::vector<double> GetGradient(const double x, const double y, const double z, const bool enable_edge_gradients=false) const\n        {\n            return GetGradient4d(Eigen::Vector4d(x, y, z, 1.0), enable_edge_gradients);\n        }\n\n        inline std::vector<double> GetGradient3d(const Eigen::Vector3d& location, const bool enable_edge_gradients=false) const\n        {\n            const std::vector<int64_t> indices = LocationToGridIndex3d(location);\n            if (indices.size() == 3)\n            {\n                return GetGradient(indices[0], indices[1], indices[2], enable_edge_gradients);\n            }\n            else\n            {\n                return std::vector<double>();\n            }\n        }\n\n        inline std::vector<double> GetGradient4d(const Eigen::Vector4d& location, const bool enable_edge_gradients=false) const\n        {\n            const std::vector<int64_t> indices = LocationToGridIndex4d(location);\n            if (indices.size() == 3)\n            {\n                return GetGradient(indices[0], indices[1], indices[2], enable_edge_gradients);\n            }\n            else\n            {\n                return std::vector<double>();\n            }\n        }\n\n        inline std::vector<double> GetGradient(const VoxelGrid::GRID_INDEX& index, const bool enable_edge_gradients=false) const\n        {\n            return GetGradient(index.x, index.y, index.z, enable_edge_gradients);\n        }\n\n        inline std::vector<double> GetGradient(const int64_t x_index, const int64_t y_index, const int64_t z_index, const bool enable_edge_gradients=false) const\n        {\n            // Make sure the index is inside bounds\n            if ((x_index >= 0) && (y_index >= 0) && (z_index >= 0) && (x_index < GetNumXCells()) && (y_index < GetNumYCells()) && (z_index < GetNumZCells()))\n            {\n                // Make sure the index we're trying to query is one cell in from the edge\n                if ((x_index > 0) && (y_index > 0) && (z_index > 0) && (x_index < (GetNumXCells() - 1)) && (y_index < (GetNumYCells() - 1)) && (z_index < (GetNumZCells() - 1)))\n                {\n                    double inv_twice_resolution = 1.0 / (2.0 * GetResolution());\n                    double gx = (Get(x_index + 1, y_index, z_index) - Get(x_index - 1, y_index, z_index)) * inv_twice_resolution;\n                    double gy = (Get(x_index, y_index + 1, z_index) - Get(x_index, y_index - 1, z_index)) * inv_twice_resolution;\n                    double gz = (Get(x_index, y_index, z_index + 1) - Get(x_index, y_index, z_index - 1)) * inv_twice_resolution;\n                    return std::vector<double>{gx, gy, gz};\n                }\n                // If we're on the edge, handle it specially\n                else if (enable_edge_gradients)\n                {\n                    // Get the \"best\" indices we can use\n                    int64_t low_x_index = std::max((int64_t)0, x_index - 1);\n                    int64_t high_x_index = std::min(GetNumXCells() - 1, x_index + 1);\n                    int64_t low_y_index = std::max((int64_t)0, y_index - 1);\n                    int64_t high_y_index = std::min(GetNumYCells() - 1, y_index + 1);\n                    int64_t low_z_index = std::max((int64_t)0, z_index - 1);\n                    int64_t high_z_index = std::min(GetNumZCells() - 1, z_index + 1);\n                    // Compute the axis increments\n                    double x_increment = (high_x_index - low_x_index) * GetResolution();\n                    double y_increment = (high_y_index - low_y_index) * GetResolution();\n                    double z_increment = (high_z_index - low_z_index) * GetResolution();\n                    // Compute the gradients for each axis - by default these are zero\n                    double gx = 0.0;\n                    double gy = 0.0;\n                    double gz = 0.0;\n                    // Only if the increments are non-zero do we compute the gradient of an axis\n                    if (x_increment > 0.0)\n                    {\n                        double inv_x_increment = 1.0 / x_increment;\n                        double high_x_value = Get(high_x_index, y_index, z_index);\n                        double low_x_value = Get(low_x_index, y_index, z_index);\n                        // Compute the gradient\n                        gx = (high_x_value - low_x_value) * inv_x_increment;\n                    }\n                    if (y_increment > 0.0)\n                    {\n                        double inv_y_increment = 1.0 / y_increment;\n                        double high_y_value = Get(x_index, high_y_index, z_index);\n                        double low_y_value = Get(x_index, low_y_index, z_index);\n                        // Compute the gradient\n                        gy = (high_y_value - low_y_value) * inv_y_increment;\n                    }\n                    if (z_increment > 0.0)\n                    {\n                        double inv_z_increment = 1.0 / z_increment;\n                        double high_z_value = Get(x_index, y_index, high_z_index);\n                        double low_z_value = Get(x_index, y_index, low_z_index);\n                        // Compute the gradient\n                        gz = (high_z_value - low_z_value) * inv_z_increment;\n                    }\n                    // Assemble and return the computed gradient\n                    return std::vector<double>{gx, gy, gz};\n                }\n                // Edge gradients disabled, return no gradient\n                else\n                {\n                    return std::vector<double>();\n                }\n            }\n            // If we're out of bounds, return no gradient\n            else\n            {\n                return std::vector<double>();\n            }\n        }\n\n        inline Eigen::Vector3d ProjectOutOfCollision(const double x, const double y, const double z, const double stepsize_multiplier = 1.0 / 10.0) const\n        {\n            const Eigen::Vector4d result = ProjectOutOfCollision4d(Eigen::Vector4d(x, y, z, 1.0), stepsize_multiplier);\n            return result.head<3>();\n        }\n\n        inline Eigen::Vector3d ProjectOutOfCollisionToMinimumDistance(const double x, const double y, const double z, const double minimum_distance, const double stepsize_multiplier = 1.0 / 10.0) const\n        {\n            const Eigen::Vector4d result = ProjectOutOfCollisionToMinimumDistance4d(Eigen::Vector4d(x, y, z, 1.0), minimum_distance, stepsize_multiplier);\n            return result.head<3>();\n        }\n\n        inline Eigen::Vector3d ProjectOutOfCollision3d(const Eigen::Vector3d& location, const double stepsize_multiplier = 1.0 / 10.0) const\n        {\n            return ProjectOutOfCollision(location.x(), location.y(), location.z(), stepsize_multiplier);\n        }\n\n        inline Eigen::Vector3d ProjectOutOfCollisionToMinimumDistance3d(const Eigen::Vector3d& location, const double minimum_distance, const double stepsize_multiplier = 1.0 / 10.0) const\n        {\n            return ProjectOutOfCollisionToMinimumDistance(location.x(), location.y(), location.z(), minimum_distance, stepsize_multiplier);\n        }\n\n        inline Eigen::Vector4d ProjectOutOfCollision4d(const Eigen::Vector4d& location, const double stepsize_multiplier = 1.0 / 10.0) const\n        {\n            return ProjectOutOfCollisionToMinimumDistance4d(location, 0.0, stepsize_multiplier);\n        }\n\n        inline Eigen::Vector4d ProjectOutOfCollisionToMinimumDistance4d(const Eigen::Vector4d& location, const double minimum_distance, const double stepsize_multiplier = 1.0 / 10.0) const\n        {\n            Eigen::Vector4d mutable_location = location;\n            const bool enable_edge_gradients = true;\n\n            double sdf_dist = EstimateDistance4d(mutable_location).first;\n            if (sdf_dist < minimum_distance && CheckInBounds4d(location))\n            {\n                while (sdf_dist < minimum_distance)\n                {\n                    const std::vector<double> gradient = GetGradient4d(mutable_location, enable_edge_gradients);\n                    const Eigen::Vector3d grad_eigen = EigenHelpers::StdVectorDoubleToEigenVector3d(gradient);\n\n                    assert(grad_eigen.norm() > GetResolution() / 4.0); // Sanity check\n                    mutable_location.head<3>() += grad_eigen.normalized() * GetResolution() * stepsize_multiplier;\n\n                    sdf_dist = EstimateDistance4d(mutable_location).first;\n                }\n            }\n\n            return mutable_location;\n        }\n\n        inline const Eigen::Affine3d& GetOriginTransform() const\n        {\n            return distance_field_.GetOriginTransform();\n        }\n\n        inline const Eigen::Affine3d& GetInverseOriginTransform() const\n        {\n            return distance_field_.GetInverseOriginTransform();\n        }\n\n        inline std::string GetFrame() const\n        {\n            return frame_;\n        }\n\n        inline std::vector<int64_t> LocationToGridIndex3d(const Eigen::Vector3d& location) const\n        {\n            return distance_field_.LocationToGridIndex3d(location);\n        }\n\n        inline std::vector<int64_t> LocationToGridIndex4d(const Eigen::Vector4d& location) const\n        {\n            return distance_field_.LocationToGridIndex4d(location);\n        }\n\n        inline std::vector<int64_t> LocationToGridIndex(const double x, const double y, const double z) const\n        {\n            return distance_field_.LocationToGridIndex(x, y, z);\n        }\n\n        inline std::vector<double> GridIndexToLocation(const VoxelGrid::GRID_INDEX& index) const\n        {\n            return distance_field_.GridIndexToLocation(index);\n        }\n\n        inline std::vector<double> GridIndexToLocation(const int64_t x_index, const int64_t y_index, const int64_t z_index) const\n        {\n            return distance_field_.GridIndexToLocation(x_index, y_index, z_index);\n        }\n\n        inline std::vector<double> GridIndexToLocation(std::vector<int64_t> index) const\n        {\n            return distance_field_.GridIndexToLocation(index[0], index[1], index[2]);\n        }\n\n        bool SaveToFile(const std::string& filepath);\n\n        bool LoadFromFile(const std::string& filepath);\n\n        sdf_tools::SDF GetMessageRepresentation();\n\n        bool LoadFromMessageRepresentation(sdf_tools::SDF& message);\n\n        visualization_msgs::Marker ExportForDisplay(float alpha = 0.01f) const;\n\n        visualization_msgs::Marker ExportForDisplayCollisionOnly(float alpha = 0.01f) const;\n\n        visualization_msgs::Marker ExportForDebug(float alpha = 0.5f) const;\n\n        /*\n         * The following function can be *VERY EXPENSIVE* to compute, since it performs gradient ascent across the SDF\n         */\n        VoxelGrid::VoxelGrid<Eigen::Vector3d> ComputeLocalMaximaMap() const;\n\n        inline bool GradientIsEffectiveFlat(const Eigen::Vector3d& gradient) const\n        {\n            // A gradient is at a local maxima if the absolute value of all components (x,y,z) are less than 1/2 SDF resolution\n            double half_resolution = GetResolution() * 0.5;\n            if (fabs(gradient.x()) <= half_resolution && fabs(gradient.y()) <= half_resolution && fabs(gradient.z()) <= half_resolution)\n            {\n                return true;\n            }\n            else\n            {\n                return false;\n            }\n        }\n\n        inline VoxelGrid::GRID_INDEX GetNextFromGradient(const VoxelGrid::GRID_INDEX& index, const Eigen::Vector3d& gradient) const\n        {\n            // Given the gradient, pick the \"best fit\" of the 26 neighboring points\n            VoxelGrid::GRID_INDEX next_index = index;\n            double half_resolution = GetResolution() * 0.5;\n            if (gradient.x() > half_resolution)\n            {\n                next_index.x++;\n            }\n            else if (gradient.x() < -half_resolution)\n            {\n                next_index.x--;\n            }\n            if (gradient.y() > half_resolution)\n            {\n                next_index.y++;\n            }\n            else if (gradient.y() < -half_resolution)\n            {\n                next_index.y--;\n            }\n            if (gradient.z() > half_resolution)\n            {\n                next_index.z++;\n            }\n            else if (gradient.z() < -half_resolution)\n            {\n                next_index.z--;\n            }\n            return next_index;\n        }\n    };\n}\n\n#endif // SDF_HPP\n", "meta": {"hexsha": "0a0cee58a7de78d52f06e2b17459f90d31bc62cf", "size": 32567, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Btraj/third_party/sdf_tools/include/sdf_tools/sdf.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/sdf_tools/include/sdf_tools/sdf.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/sdf_tools/include/sdf_tools/sdf.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.2399481193, "max_line_length": 205, "alphanum_fraction": 0.5812632419, "num_tokens": 7354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.2840421274806909}}
{"text": "/*\n * Copyright (C) 2012-2014, Computing Systems Laboratory (CSLab), NTUA.\n * Copyright (C) 2012-2014, Athena Elafrou\n * All rights reserved.\n *\n * This file is distributed under the BSD License. See LICENSE.txt for details.\n */\n\n/**\n * \\file Rcm.hpp\n * \\brief Reverse Cuthill-Mckee Ordering Interface\n *\n * \\author Computing Systems Laboratory (CSLab), NTUA\n * \\date 2011&ndash;2014\n * \\copyright This file is distributed under the BSD License. See LICENSE.txt\n * for details.\n */\n\n#ifndef SPARSEX_INTERNALS_RCM_HPP\n#define SPARSEX_INTERNALS_RCM_HPP\n\n#include <sparsex/internals/Csr.hpp>\n#include <sparsex/internals/Mmf.hpp>\n#include <sparsex/internals/logger/Logger.hpp>\n#include <boost/config.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/cuthill_mckee_ordering.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/bandwidth.hpp>\n\nusing namespace sparsex::io;\n\nnamespace sparsex {\n  namespace utilities {\n\n    using namespace boost;\n\n#define bad_reorder 0\n\n    typedef pair<size_t, size_t> Pair;\n    typedef adjacency_list<vecS, vecS, undirectedS,\n\t\t\t   property<vertex_color_t, default_color_type,\n\t\t\t\t    property<vertex_degree_t,int> > > Graph;\n    typedef graph_traits<Graph>::vertex_descriptor Vertex;\n    typedef graph_traits<Graph>::vertices_size_type size_type;\n\n    template<typename IndexType, typename ValueType>\n    struct ColumnCompare {\n    public:\n      bool operator() (const pair<IndexType, ValueType> &lhs,\n\t\t       const pair<IndexType, ValueType> &rhs) const\n      {\n\tif (lhs.first < rhs.first) return true;\n\tif (lhs.first > rhs.first) return false;\n\treturn false;\n      }\n    };\n\n    /**\n     *  @return perm      permutation from the old ordering to the new one.\n     *  @return inv_perm  permutation from the new ordering to the old one.\n     *  @param  graph     the incidence graph of the matrix.\n     */\n    void FindPerm(vector<size_t>& perm, vector<size_t>& inv_perm, Graph& graph);\n\n    /**\n     *  Loads matrix from an MMF file and applies the reverse Cuthill-Mckee\n     *  reordering algorithm\n     *\n     *  @param file_name   name of the file where the matrix is kept.\n     *  @param rt_config   runtime configuration.\n     *  @param mat         handler of MMF class.\n     *  @param graph       the incidence graph of the matrix.\n     *  @param perm        permutation from the old ordering to the new one.\n     *  @return            spm class object with the characteristics of the\n     *                     matrix.\n     */\n    template<typename IndexType, typename ValueType>\n    void ReorderMat_MMF(MMF<IndexType, ValueType>& mat,\n\t\t\tconst vector<size_t>& perm);\n    template<typename IndexType, typename ValueType>\n    Graph& ConstructGraph_MMF(Graph& graph, MMF<IndexType, ValueType>& mat);\n    template<typename IndexType, typename ValueType>\n    void DoReorder_RCM(MMF<IndexType, ValueType>& mat, vector<size_t>& perm);\n\n    /**\n     *  Loads matrix from CSR format and applies the reverse Cuthill-Mckee\n     *  reordering algorithm\n     *\n     *  @param rowptr      array \"rowptr\" of CSR format.\n     *  @param colind      array \"colind\" of CSR format.\n     *  @param values      array \"values\" of CSR format.\n     *  @param nr_rows     number of rows.\n     *  @param nr_cols     number of columns.\n     *  @param zero_based  indexing.\n     *  @param rt_config   runtime configuration.\n     *  @param perm        permutation from the old ordering to the new one.\n     *  @param inv_perm    permutation from the new ordering to the old one.\n     *  @param graph       the incidence graph of the matrix.\n     *  @return            spm class object with the characteristics of the\n     *                     matrix.\n     */\n    template<typename IndexType, typename ValueType>\n    void ReorderMat_CSR(CSR<IndexType, ValueType>& mat,\n\t\t\tconst vector<size_t>& perm,\n\t\t\tvector<size_t>& inv_perm);\n    template<typename IterT>\n    Graph& ConstructGraph_CSR(Graph& graph, IterT& iter, const IterT& iter_end,\n\t\t\t      size_t nr_nzeros, bool symmetric);\n    template<typename IndexType, typename ValueType>\n    void DoReorder_RCM(CSR<IndexType, ValueType>& mat, vector<size_t>& perm);\n\n    /*\n     * Implementation of RCM interface\n     */\n    void FindPerm(vector<size_t>& perm, vector<size_t>& invperm, Graph& graph)\n    {\n      graph_traits<Graph>::vertex_iterator ui, ui_end;\n      property_map<Graph,vertex_degree_t>::type deg = get(vertex_degree, graph);\n      for (boost::tie(ui, ui_end) = vertices(graph); ui != ui_end; ++ui) {\n        deg[*ui] = degree(*ui, graph);\n      }\n\n      // Original ordering\n      property_map<Graph, vertex_index_t>::type\n        index_map = get(vertex_index, graph);\n\n      size_t ob = bandwidth(graph);\n      LOG_INFO << \"Original Bandwidth: \" << ob << \"\\n\";\n\n      vector<Vertex> inv_perm(num_vertices(graph));\n      perm.resize(num_vertices(graph));\n      invperm.reserve(num_vertices(graph));\n\n      // Reverse Cuthill Mckee Ordering\n      cuthill_mckee_ordering(graph, inv_perm.rbegin(), get(vertex_color, graph),\n\t\t\t     make_degree_map(graph));\n\n      for (size_t i = 0; i != inv_perm.size(); ++i) {\n        perm[index_map[inv_perm[i]]] = i;\n        invperm.push_back(inv_perm[i]);\n      }\n\n      // cout << \"Permutation: \";\n      // for (size_t i = 0; i < inv_perm.size(); i++) {\n      //     cout << inv_perm[i] << \" \";\n      // }\n      // cout << endl;\n\n      size_t nb = bandwidth(graph, make_iterator_property_map\n\t\t\t    (&perm[0], index_map, perm[0]));\n      LOG_INFO << \"Final Bandwidth: \" << nb << \"\\n\";\n    }\n\n    template<typename IndexType, typename ValueType>\n    Graph& ConstructGraph_MMF(Graph& graph, MMF<IndexType, ValueType>& mat)\n    {\n      // The flag must be set before using the MMF iterator\n      mat.SetReordered(true);\n\n      // Make a pessimistic guess for nr_edges\n      size_t nr_edges;\n      if (mat.IsSymmetric()) {\n        // If main diagonal is full (nr_nzeros - nr_rows) / 2\n        nr_edges = mat.GetNrNonzeros() / 2;\n      } else {\n        nr_edges = mat.GetNrNonzeros();\n      }\n\n      Pair *edges = new Pair[nr_edges];\n\n      typename MMF<IndexType, ValueType>::iterator iter = mat.begin();\n      typename MMF<IndexType, ValueType>::iterator iter_end = mat.end();\n      size_t index = 0;\n      if (!mat.IsSymmetric() && !mat.IsColWise()) {\n        mat.InitMatrix(mat.GetNrNonzeros());\n        for (; iter != iter_end; ++iter) {\n\t  mat.InsertElement(*iter);\n\t  if ((*iter).GetRow() != (*iter).GetCol())\n\t    edges[index++] = make_pair((*iter).GetRow() - 1,\n\t\t\t\t       (*iter).GetCol() - 1);\n        }\n      } else {\n        for (;iter != iter_end; ++iter)\n\t  if ((*iter).GetRow() < (*iter).GetCol())\n\t    edges[index++] = make_pair((*iter).GetRow() - 1,\n\t\t\t\t       (*iter).GetCol() - 1);\n      }\n\n      // index -> actual nr_edges\n      assert(index <= nr_edges);\n      if (index == 0) {\n        LOG_WARNING << \"no reordering available for this matrix\\n\";\n        delete[] edges;\n        throw bad_reorder;\n      }\n\n      for (size_t i = 0; i < index; ++i) {\n        add_edge(edges[i].first, edges[i].second, graph);\n      }\n\n      delete[] edges;\n      return graph;\n    }\n\n    template<typename IndexType, typename ValueType>\n    void ReorderMat_MMF(MMF<IndexType, ValueType>& mat,\n\t\t\tconst vector<size_t>& perm)\n    {\n      for (size_t i = 0; i < mat.GetNrNonzeros(); i++) {\n        pair<IndexType, ValueType> coord = mat.GetCoordinates(i);\n        mat.SetCoordinates(i, perm[coord.first-1] + 1,\n                           perm[coord.second-1] + 1);\n      }\n\n      mat.Sort();\n    }\n\n    template<typename IndexType, typename ValueType>\n    void DoReorder_RCM(MMF<IndexType, ValueType>& mat, vector<size_t> &perm)\n    {\n      vector<size_t> inv_perm;\n\n      LOG_INFO << \"Reordering input matrix...\\n\";\n      // Construct graph\n      Graph graph(mat.GetNrRows());\n      try {\n        graph = ConstructGraph_MMF(graph, mat);\n      } catch (int e) {\n        mat.ResetStream();\n        mat.SetReordered(false);\n        LOG_WARNING << \"reordering failed\\n\";\n        return;\n      }\n      // Find permutation\n      FindPerm(perm, inv_perm, graph);\n      // Reorder original matrix\n      ReorderMat_MMF(mat, perm);\n      LOG_INFO << \"Reordering complete\\n\";\n    }\n\n    template<typename IterT>\n    Graph& ConstructGraph_CSR(Graph& graph, IterT& iter, const IterT& iter_end,\n\t\t\t      size_t nr_nzeros, bool symmetric)\n    {\n      // make a pessimistic guess for nr_edges\n      size_t nr_edges;\n      if (symmetric) {    //if main diagonal is full (nr_nzeros - nr_rows) / 2\n        nr_edges = nr_nzeros / 2;\n      } else {\n        nr_edges = nr_nzeros;\n      }\n\n      Pair *edges = new Pair[nr_edges];\n      size_t index = 0;\n      if (symmetric) {\n        for (;iter != iter_end; ++iter) {\n\t  if ((*iter).GetRow() < (*iter).GetCol()) {\n\t    edges[index++] = make_pair(((*iter).GetRow()) - 1,\n\t\t\t\t       ((*iter).GetCol()) - 1);\n\t  }\n        }\n      } else {\n        for (;iter != iter_end; ++iter) {\n\t  if ((*iter).GetRow() != (*iter).GetCol()) {\n\t    edges[index++] = make_pair(((*iter).GetRow()) - 1,\n\t\t\t\t       ((*iter).GetCol()) - 1);\n\t  }\n        }\n      }\n\n      // index -> actual nr_edges\n      assert(index <= nr_edges);\n\n      if (index == 0) {\n        LOG_WARNING << \"no reordering available for this matrix\\n\";\n        delete[] edges;\n        throw bad_reorder;\n      }\n\n      for (size_t i = 0; i < index; i++) {\n        add_edge(edges[i].first, edges[i].second, graph);\n      }\n\n      delete[] edges;\n      return graph;\n    }\n\n    template<typename IndexType, typename ValueType>\n    void ReorderMat_CSR(CSR<IndexType, ValueType>& mat,\n\t\t\tconst vector<size_t>& perm,\n\t\t\tvector<size_t>& inv_perm)\n    {\n      // Have to work on a copy of colind and values if CSR structures are not\n      // be shared\n      IndexType *new_colind = new IndexType[mat.GetNrNonzeros()];\n      ValueType *new_values = new ValueType[mat.GetNrNonzeros()];\n      memcpy(new_values, mat.values_, sizeof(ValueType) * mat.GetNrNonzeros());\n\n      // Apply permutation only to colind\n      for (size_t i = 0; i < mat.GetNrNonzeros(); i++) {\n        new_colind[i] = perm[mat.colind_[i] - !mat.IsZeroBased()] +\n\t  !mat.IsZeroBased();\n      }\n\n      mat.colind_ = new_colind;\n      mat.values_ = new_values;\n\n      // Simultaneously sort colind and values per row\n      for (size_t i = 0; i < mat.GetNrRows(); i++) {\n        sort(mat.row_begin(i), mat.row_end(i),\n             ColumnCompare<IndexType, ValueType>());\n      }\n      mat.SetReordered(inv_perm);\n      //assert(inv_perm.capacity() == 0);\n    }\n\n    template<typename IndexType, typename ValueType>\n    void DoReorder_RCM(CSR<IndexType, ValueType>& mat, vector<size_t>& perm)\n    {\n      typename CSR<IndexType, ValueType>::iterator iter = mat.begin();\n      typename CSR<IndexType, ValueType>::iterator iter_end = mat.end();\n      vector<size_t> inv_perm;\n\n      LOG_INFO << \"Reordering input matrix...\\n\";\n      // Construct graph\n      Graph graph(mat.GetNrRows());\n      try {\n        graph = ConstructGraph_CSR(graph, iter, iter_end, mat.GetNrNonzeros(),\n                                   mat.IsSymmetric());\n      } catch (int e) {\n        LOG_INFO << \"reordering failed\\n\";\n        return;\n      }\n      // Find permutation\n      FindPerm(perm, inv_perm, graph);\n      // Reorder original matrix\n      ReorderMat_CSR<IndexType, ValueType>(mat, perm, inv_perm);\n      LOG_INFO << \"Reordering complete\\n\";\n    }\n\n  } // end of namespace utilities\n} // end of namespace sparsex\n\n#endif // SPARSEX_INTERNALS_RCM_HPP\n", "meta": {"hexsha": "461a880f540612a678c7f308f8cb9a192e74fc4e", "size": 11511, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sparsex/internals/Rcm.hpp", "max_stars_repo_name": "Baltoli/sparsex", "max_stars_repo_head_hexsha": "36145d9c47e40dbd7da71ba5a75b7644e2eda5d8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2015-02-03T13:19:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T15:46:11.000Z", "max_issues_repo_path": "include/sparsex/internals/Rcm.hpp", "max_issues_repo_name": "Baltoli/sparsex", "max_issues_repo_head_hexsha": "36145d9c47e40dbd7da71ba5a75b7644e2eda5d8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-06-19T06:41:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-10T09:51:17.000Z", "max_forks_repo_path": "include/sparsex/internals/Rcm.hpp", "max_forks_repo_name": "Baltoli/sparsex", "max_forks_repo_head_hexsha": "36145d9c47e40dbd7da71ba5a75b7644e2eda5d8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T16:06:59.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-01T12:30:04.000Z", "avg_line_length": 33.2687861272, "max_line_length": 80, "alphanum_fraction": 0.6152375988, "num_tokens": 2934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.2839041234137523}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2002-2012 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#ifndef ALGORITHM_HIERARCHIC_ERROR_ESTIMATOR_HH\n#define ALGORITHM_HIERARCHIC_ERROR_ESTIMATOR_HH\n\n#include <algorithm>\n#include <iostream>\n#include <utility>\n#include <vector>\n\n#include <boost/timer/timer.hpp>\n#include <boost/fusion/include/at_c.hpp>\n\n#include \"algorithm/newton_bridge.hh\"\n#include \"linalg/jacobiPreconditioner.hh\"\n#include \"fem/hierarchicErrorEstimator.hh\"\n#include \"fem/variables.hh\"\n#include \"linalg/direct.hh\"\n#include \"linalg/tcg.hh\"\n#include \"utilities/enums.hh\"\n\n// forward declarations\nnamespace Dune\n{\n  struct InverseOperatorResult;\n  template <class,int> class FieldVector;\n}\n\nnamespace Kaskade\n{\n  namespace HierarchicErrorEstimator_Detail{\n    bool biggerThanAbs(const std::pair<double,int>& x1, const std::pair<double,int>&  x2)\n    {\n      return fabs(x1.first)>fabs(x2.first);\n    }\n\n    double add(const double& x1, const std::pair<double,int>&  x2)\n    {\n      return x1+x2.first;\n    }\n  }\n\n  template <class CorrectionVector>\n  struct LeaveRHS\n  {\n    explicit LeaveRHS(CorrectionVector const&) {}\n\n    template <class RhsVector>\n    void operator()(RhsVector& rhs)\n    {}    \n  };\n\n  template <class CorrectionVector>\n  struct SubstractCorrection\n  {\n    explicit SubstractCorrection(CorrectionVector const& cor_) \n    : cor(cor_)\n    {}\n\n    template <class RhsVector>\n    void operator()(RhsVector& rhs)\n    {\n      rhs -= cor;\n    }\n\n  private:\n    CorrectionVector const& cor;\n  };\n\n\n  template <class Functional, /*class LF,*/ class ExtensionVariableSetDescription, class ExtensionSpace, class NormFunctional=Functional, template <class> class AdjustRHS=LeaveRHS>\n  class HierarchicalBasisErrorEstimator : public AbstractHierarchicalErrorEstimator\n  {\n    static constexpr int yId = 1, uId = 0, pId = 2;\n    static constexpr int noOfVariables = ExtensionVariableSetDescription::noOfVariables;\n    //    typedef typename LF::AnsatzVars LVars;\n  public:\n    typedef typename Functional::Scalar Scalar;\n    typedef typename Functional::AnsatzVars::VariableSet VariableSet;\n    static constexpr int dim = VariableSet::Descriptions::Grid::dimension;\n    typedef HierarchicErrorEstimator<LinearizationAt<Functional>,ExtensionVariableSetDescription,ExtensionVariableSetDescription,HierarchicErrorEstimatorDetail::TakeAllD2<LinearizationAt<Functional> > > ErrorEstimator;\n    typedef VariationalFunctionalAssembler<ErrorEstimator> Assembler;\n    typedef typename ExtensionVariableSetDescription::template CoefficientVectorRepresentation<0,2>::type CoefficientVector02;\n    typedef typename ExtensionVariableSetDescription::template CoefficientVectorRepresentation<0,noOfVariables>::type CoefficientVector;\n    typedef typename ExtensionVariableSetDescription::GridView::template Codim<0>::Iterator CellIterator;\n\n    //    HierarchicalBasisErrorEstimator(Functional& f_, LF& lf_, LVars& lvars, ExtensionVariableSetDescription& extensionVariableSetDescription_, ExtensionSpace& extensionSpace_, Scalar fraction=0.7, bool verbose_=false)\n    //    : f(f_), lf(lf_), normFunctional(f_), extensionVariableSetDescription(extensionVariableSetDescription_), extensionSpace(extensionSpace_), assembler(extensionVariableSetDescription.spaces),\n    //    squaredFraction(fraction*fraction), verbose(verbose_)\n    //    {}\n\n    HierarchicalBasisErrorEstimator(Functional& f_, /*LF& lf_,*/ /*LVars& lvars_,*/ NormFunctional& normFunctional_, ExtensionVariableSetDescription& extensionVariableSetDescription_, \n        ExtensionSpace& extensionSpace_, Scalar fraction=0.7, bool verbose_=false)\n    : f(f_), /*lf(lf_), lvars(lvars_),*/ normFunctional(normFunctional_), extensionVariableSetDescription(extensionVariableSetDescription_), extensionSpace(extensionSpace_), assembler(extensionVariableSetDescription.spaces),\n      squaredFraction(fraction*fraction), verbose(verbose_)\n    {}\n\n    virtual ~HierarchicalBasisErrorEstimator(){}\n\n    void operator()(AbstractVector const& x_, AbstractVector const& dx_, int step, AbstractVector const& lowerOrderRhs)\n    {\n      if(verbose) std::cout << \"ERROR ESTIMATOR: Start.\" << std::endl;\n      Bridge::Vector<VariableSet> const& x = dynamic_cast<const Bridge::Vector<VariableSet>&>(x_);\n      Bridge::Vector<VariableSet> const& dx = dynamic_cast<const Bridge::Vector<VariableSet>&>(dx_);\n      //    Bridge::Vector<VariableSet> const& loRhs = dynamic_cast<const Bridge::Vector<VariableSet>&>(lowerOrderRhs);\n\n\n      boost::timer::cpu_timer atimer;\n      assembler.assemble(ErrorEstimator(LinearizationAt<Functional>(f,x.get()),dx.get()));\n      if(verbose) std::cout << \"ERROR ESTIMATOR: assembly time: \" << boost::timer::format(atimer.elapsed(), 2, \"%t\") << \"s\" << std::endl;\n\n      typedef AssembledGalerkinOperator<Assembler> Operator;\n      typedef AssembledGalerkinOperator<Assembler,0,2,0,2> CorrectionOperator;\n      typedef typename Functional::AnsatzVars::template CoefficientVectorRepresentation<0,2>::type CorrectionVector;\n\n      Operator op(assembler);\n      //      CorrectionOperator(assembler);\n\n      CoefficientVector estRhs(assembler.rhs());\n      std::vector<Scalar> tmpRepVec;\n      IstlInterfaceDetail::toVector(estRhs,tmpRepVec);\n      //estRhs = Bridge::getImpl<VariableSet>(lowerOrderRhs);\n      std::cout << \"rhs entries:\" << std::endl;\n      Scalar maxRhs=std::numeric_limits<Scalar>::min(), minRhs=std::numeric_limits<Scalar>::max(), rhsSum=0;\n      for(size_t i=0; i<tmpRepVec.size(); ++i){\n        if(std::isnan(tmpRepVec[i])) std::cout << \"nan at \" << i << std::endl;\n\n        Scalar val = tmpRepVec[i];\n        if(val < minRhs) minRhs = val;\n        if(val > maxRhs) maxRhs = val;\n        rhsSum += val*val;\n      }\n      std::cout << \"max rhs: \" << maxRhs << std::endl;\n      std::cout << \"min rhs: \" << minRhs << std::endl;\n      std::cout << \"sum: \" << rhsSum << std::endl;\n      // possible adjustment of rhs\n      //adjustRHS(estRhs);\n\n      boost::timer::cpu_timer timer;\n      CoefficientVector estSol(ExtensionVariableSetDescription::template CoefficientVectorRepresentation<0,noOfVariables>::init(extensionVariableSetDescription));\n\n      directInverseOperator(op,DirectType::UMFPACK,MatrixProperties::GENERAL).apply(estRhs,estSol);\n\n\n      if(verbose) std::cout << \"ERROR ESTIMATOR: computation time: \" << boost::timer::format(timer.elapsed(), 2, \"%t\") << \"s\" << std::endl;\n      typename ExtensionVariableSetDescription::VariableSet mySol(extensionVariableSetDescription);\n      mySol = estSol;\n      using namespace boost::fusion;\n\n      Scalar maxVal = std::numeric_limits<Scalar>::min(),\n          minVal = std::numeric_limits<Scalar>::max(),\n          sum = 0;\n\n      if(verbose)\n      {\n        for(int i=0; i<at_c<yId>(mySol.data).size();  ++i)\n        {\n          for(int j=0; j<at_c<yId>(mySol.data).coefficients()[i].size; ++j)\n          {\n            Scalar val = at_c<yId>(mySol.data).coefficients()[i][j];\n            sum += val*val;\n            if(val > maxVal) maxVal = val;\n            if(val < minVal) minVal = val;\n          }\n        }\n        std::cout << \"y: minimal value: \" << minVal << std::endl;\n        std::cout << \"y: maximal value: \" << maxVal << std::endl;\n        std::cout << \"y: l2-sum: \" << sum << std::endl;\n        Scalar tmpMax = maxVal, tmpMin = minVal, tmpSum = sum;\n        maxVal = std::numeric_limits<Scalar>::min();\n        minVal = std::numeric_limits<Scalar>::max();\n        sum = 0;\n\n        for(int i=0; i<at_c<uId>(mySol.data).size();  ++i)\n        {\n          for(int j=0; j<at_c<uId>(mySol.data).coefficients()[i].size; ++j)\n          {\n            Scalar val = at_c<uId>(mySol.data).coefficients()[i][0];\n            sum += val*val;\n            if(val > maxVal) maxVal = val;\n            if(val < minVal) minVal = val;\n          }\n        }\n        std::cout << \"u: minimal value: \" << minVal << std::endl;\n        std::cout << \"u: maximal value: \" << maxVal << std::endl;\n        std::cout << \"u: l2-sum: \" << sum << std::endl;\n        tmpMax = std::max(tmpMax,maxVal), tmpMin = std::min(tmpMin,minVal), tmpSum += sum;\n        maxVal = std::numeric_limits<Scalar>::min();\n        minVal = std::numeric_limits<Scalar>::max();\n        sum = 0;\n\n        for(int i=0; i<at_c<pId>(mySol.data).size();  ++i)\n        {\n          for(int j=0; j<at_c<pId>(mySol.data).coefficients()[i].size; ++j)\n          {\n            Scalar val = at_c<pId>(mySol.data).coefficients()[i][j];\n            sum += val*val;\n            if(val > maxVal) maxVal = val;\n            if(val < minVal) minVal = val;\n          }\n        }\n        std::cout << \"p: minimal value: \" << minVal << std::endl;\n        std::cout << \"p: maximal value: \" << maxVal << std::endl;\n        std::cout << \"p: l2-sum: \" << sum << std::endl;\n\n        tmpSum += sum;\n        std::cout << \"minimal value: \" << std::min(tmpMin,minVal) << std::endl;\n        std::cout << \"maximal value: \" << std::max(tmpMax,maxVal) << std::endl;\n        std::cout << \"l2-sum: \" << tmpSum << std::endl;\n      }\n      // Transfer error indicators to cells.\n      auto const& is = extensionSpace.gridManager().grid().leafIndexSet();\n      errorDistribution.clear();\n      errorDistribution.resize(is.size(0),std::make_pair(0.0,0));\n      Scalar errLevel(0.0), minRefine(0.2);\n\n      typedef ErrorDistribution<NormFunctional,ExtensionVariableSetDescription> EnergyError;\n      EnergyError energyError(normFunctional,x.get(),mySol);\n      typedef VariationalFunctionalAssembler<LinearizationAt<EnergyError> > EnergyErrorAssembler;\n      EnergyErrorAssembler eeAssembler(extensionSpace.gridManager(), energyError.getSpaces());\n\n      eeAssembler.assemble(linearization(energyError,x.get()), EnergyErrorAssembler::RHS);\n      typename EnergyError::ErrorVector distError( eeAssembler.rhs() );\n      typename EnergyError::AnsatzVars::VariableSet mde( energyError.getVariableSetDescription() );\n      mde = distError;\n\n      if(verbose)\n      {\n        std::string name = \"errorDistribution_\";\n        name += boost::lexical_cast<std::string>(step);\n        writeVTKFile(mde.descriptions.gridView,mde.descriptions,mde,name);\n      }\n      // Fehler bzgl L_xx : ( sum_i estSol_i * (L_xx * estSol)_i )^{1/2}  (nur die x - Komponente, nicht p)\n      // Lokalisierung: einfachste Idee: v_i = estSol_i * (L_xx * estSol)_i\n      // Aufteilen von v_i auf die einzelnen Zellen\n      CellIterator cend = extensionVariableSetDescription.gridView.template end<0>();\n      for (CellIterator ci=extensionVariableSetDescription.gridView.template begin<0>(); ci!=cend; ++ci)\n        errorDistribution[is.index(*ci)] = std::make_pair( fabs(boost::fusion::at_c<0>(mde.data).value(*ci,Dune::FieldVector<Scalar,dim>(0.3))) , is.index(*ci));\n\n      totalErrorSquared = std::accumulate(errorDistribution.begin(), errorDistribution.end(), 0.0, HierarchicErrorEstimator_Detail::add);\n    }\n\n    void refineGrid()\n    {\n      //      int lastIndexForDoubleRefinement = -1;\n      std::sort(errorDistribution.begin(), errorDistribution.end(), HierarchicErrorEstimator_Detail::biggerThanAbs);\n\n      Scalar bulkCriterionTolerance = squaredFraction*totalErrorSquared;\n      if(verbose)\n      {\n        std::cout << \"ERROR ESTIMATOR: totalErrorSquared: \" << totalErrorSquared << std::endl;\n        std::cout << \"ERROR ESTIMATOR: bulkCriterionTolerance: \" << bulkCriterionTolerance << std::endl;\n      }\n      Scalar bulkErrorSquared = 0;\n\n      std::vector<std::pair<Scalar,size_t> > bulkErrorDistribution;\n      auto const& is = extensionSpace.gridManager().grid().leafIndexSet();\n      CellIterator cend = extensionVariableSetDescription.gridView.template end<0>();\n\n      while(bulkErrorSquared < bulkCriterionTolerance)\n      {\n        bulkErrorDistribution.push_back(errorDistribution[bulkErrorDistribution.size()]);\n        bulkErrorSquared += bulkErrorDistribution.back().first;\n      }\n\n      if(verbose) std::cout << \"ERROR ESTIMATOR: number of candidates for refinement: \" << bulkErrorDistribution.size() << std::endl;\n\n      //      size_t lastIndex = bulkErrorDistribution.size()-1;\n      //      size_t firstIndex = 0;\n\n      /*while(firstIndex+3 < lastIndex)\n      {\n        if(bulkErrorDistribution.size() > 4)\n        {\n          Scalar firstContribution = bulkErrorDistribution[firstIndex].first;\n          firstContribution *= 15.0/256.0;\n\n          Scalar lastContributions = bulkErrorDistribution[lastIndex--].first;\n          lastContributions += bulkErrorDistribution[lastIndex--].first;\n          lastContributions += bulkErrorDistribution[lastIndex].first;\n          lastContributions *= 15.0/16.0;\n\n          if(lastContributions < firstContribution)\n          {\n            ++lastIndexForDoubleRefinement;\n            ++firstIndex;\n            --lastIndex;\n            bulkErrorDistribution.erase(bulkErrorDistribution.end()-3, bulkErrorDistribution.end());\n          }\n          else break;\n        }\n      }*/\n\n\n      // Refine mesh.\n      for (CellIterator ci=extensionVariableSetDescription.gridView.template begin<0>(); ci!=cend; ++ci) // iterate over cells\n      {\n        for(int i=0; i<bulkErrorDistribution.size(); ++i) // iterate over chosen part of the error distribution\n          if(is.index(*ci) == bulkErrorDistribution[i].second)\n          {\n            //            if(i <= lastIndexForDoubleRefinement) {\n            //              extensionSpace.gridManager().mark(2,*ci);\n            //            }\n            //            else{\n            extensionSpace.gridManager().mark(1,*ci);\n            //            }\n          }\n      }\n\n      extensionSpace.gridManager().adaptAtOnce();\n    }\n\n    double estimatedAbsoluteError() const final\n        {\n      return sqrt(fabs(totalErrorSquared));\n        }\n\n    size_t gridSize() const final\n        {\n      return extensionSpace.gridManager().grid().size(0);\n        }\n\n  private:\n    Functional& f;\n    //    LF& lf;\n    //    LVars& lvars;\n    NormFunctional& normFunctional;\n    ExtensionVariableSetDescription& extensionVariableSetDescription;\n    ExtensionSpace& extensionSpace;\n    Assembler assembler;\n    Scalar squaredFraction;\n    Scalar totalErrorSquared;\n    std::vector<std::pair<double,int> > errorDistribution;\n    bool verbose;\n    // AdjustRHS<CoefficientVector> adjustRHS;\n  };\n}\n\n#endif\n", "meta": {"hexsha": "0348e5aadb83ac793600ee367b1bc907d8df2455", "size": 15036, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/algorithm/hierarchicErrorEstimator.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/algorithm/hierarchicErrorEstimator.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/algorithm/hierarchicErrorEstimator.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 42.96, "max_line_length": 224, "alphanum_fraction": 0.6347432828, "num_tokens": 3680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.28381603367073477}}
{"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#ifndef MTL_MAT_VEC_MULT_INCLUDE\n#define MTL_MAT_VEC_MULT_INCLUDE\n\n#include <cassert>\n// #include <iostream>\n#include <boost/mpl/bool.hpp>\n\n#include <boost/numeric/mtl/config.hpp>\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/utility/category.hpp>\n#include <boost/numeric/mtl/utility/property_map.hpp>\n#include <boost/numeric/mtl/utility/range_generator.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/utility/is_static.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/utility/enable_if.hpp>\n#include <boost/numeric/mtl/utility/multi_tmp.hpp>\n#include <boost/numeric/mtl/utility/static_assert.hpp>\n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n#include <boost/numeric/mtl/utility/omp_size_type.hpp>\n#include <boost/numeric/mtl/operation/set_to_zero.hpp>\n#include <boost/numeric/mtl/operation/update.hpp>\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/meta_math/loop.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n\nnamespace mtl { namespace matrix {\n\nnamespace impl {\n\n    template <std::size_t Index0, std::size_t Max0, std::size_t Index1, std::size_t Max1, typename Assign>\n    struct fully_unroll_mat_cvec_mult\n      : public meta_math::loop2<Index0, Max0, Index1, Max1>\n    {\n\ttypedef meta_math::loop2<Index0, Max0, Index1, Max1>                              base;\n\ttypedef fully_unroll_mat_cvec_mult<base::next_index0, Max0, base::next_index1, Max1, Assign>  next_t;\n\n\ttemplate <typename Matrix, typename VectorIn, typename VectorOut>\n\tstatic inline void apply(const Matrix& A, const VectorIn& v, VectorOut& w)\n\t{\n\t    Assign::update(w[base::index0], A[base::index0][base::index1] * v[base::index1]);\n\t    next_t::apply(A, v, w);\n\t}   \n    };\n\n    // need specialization here for not going back to column 0 but column 1\n    template <std::size_t Index0, std::size_t Max0, std::size_t Max1, typename Assign>\n    struct fully_unroll_mat_cvec_mult<Index0, Max0, Max1, Max1, Assign>\n      : public meta_math::loop2<Index0, Max0, Max1, Max1>\n    {\n\ttypedef meta_math::loop2<Index0, Max0, Max1, Max1>                              base;\n\ttypedef fully_unroll_mat_cvec_mult<base::next_index0, Max0, 2, Max1, Assign>  next_t;\n\n\ttemplate <typename Matrix, typename VectorIn, typename VectorOut>\n\tstatic inline void apply(const Matrix& A, const VectorIn& v, VectorOut& w)\n\t{\n\t    Assign::update(w[base::index0], A[base::index0][base::index1] * v[base::index1]);\n\t    next_t::apply(A, v, w);\n\t}   \n    };\n\n    template <std::size_t Max0, std::size_t Max1, typename Assign>\n    struct fully_unroll_mat_cvec_mult<Max0, Max0, Max1, Max1, Assign>\n      : public meta_math::loop2<Max0, Max0, Max1, Max1>\n    {\n\ttypedef meta_math::loop2<Max0, Max0, Max1, Max1>                              base;\n\n\ttemplate <typename Matrix, typename VectorIn, typename VectorOut>\n\tstatic inline void apply(const Matrix& A, const VectorIn& v, VectorOut& w)\n\t{\n\t    Assign::update(w[base::index0], A[base::index0][base::index1] * v[base::index1]);\n\t}   \n    };\n\n    struct noop\n    {\n\ttemplate <typename Matrix, typename VectorIn, typename VectorOut>\n\tstatic inline void apply(const Matrix&, const VectorIn&, VectorOut&) {}\n    };\n} // impl\n\n// Dense matrix vector multiplication with run-time matrix size\ntemplate <typename Matrix, typename VectorIn, typename VectorOut, typename Assign>\ninline void dense_mat_cvec_mult(const Matrix& A, const VectorIn& v, VectorOut& w, Assign, boost::mpl::true_)\n{\n    vampir_trace<3017> tracer;\n    typedef typename static_num_rows<Matrix>::type size_type;\n    static const size_type rows_a= static_num_rows<Matrix>::value, cols_a= static_num_cols<Matrix>::value;\n\n    assert(rows_a > 0 && cols_a > 0);\n    // w= A[all][0] * v[0];  N.B.: 1D is unrolled by the compiler faster (at least on gcc)\n    for (size_type i= 0; i < rows_a; i++) \n\tAssign::first_update(w[i], A[i][0] * v[0]);\n\t\n    // corresponds to w+= A[all][1:] * v[1:]; if necessary\n    typedef impl::fully_unroll_mat_cvec_mult<1, rows_a, 2, cols_a, Assign>  f2;\n    typedef typename boost::mpl::if_c<(cols_a > 1), f2, impl::noop>::type   f3;\n    f3::apply(A, v, w);\n}\n\t\ntemplate <unsigned Index, unsigned Size>\nstruct init_ptrs\n{\n    template <typename Matrix, typename Ptrs>\n    inline static void apply(const Matrix& A, Ptrs& ptrs)\n    {\n\tptrs.value= &A[Index][0];\n\tinit_ptrs<Index+1, Size>::apply(A, ptrs.sub);\n    }\n};\n\ntemplate <unsigned Size>\nstruct init_ptrs<Size, Size>\n{\n    template <typename Matrix, typename Ptrs>\n    inline static void apply(const Matrix&, Ptrs&) {}\n};\n\ntemplate <unsigned Index, unsigned Size>\nstruct square_cvec_mult_rows\n{\n    template <typename Tmps, typename Ptrs, typename ValueIn>\n    inline static void compute(Tmps& tmps, Ptrs& ptrs, ValueIn vi)\n    {\n\ttmps.value+= *ptrs.value++ * vi;\n\tsquare_cvec_mult_rows<Index+1, Size>::compute(tmps.sub, ptrs.sub, vi);\n    }\n\n    template <typename As, typename VectorOut, typename Tmps>\n    inline static void update(As, VectorOut& w, const Tmps& tmps)\n    {\n\tAs::first_update(w[Index], tmps.value);\n\tsquare_cvec_mult_rows<Index+1, Size>::update(As(), w, tmps.sub);\n    }\n};\n\ntemplate <unsigned Size>\nstruct square_cvec_mult_rows<Size, Size>\n{\n    template <typename Tmps, typename Ptrs, typename ValueIn>\n    inline static void compute(Tmps&, Ptrs&, ValueIn) {}\n\n    template <typename As, typename VectorOut, typename Tmps>\n    inline static void update(As, VectorOut&, const Tmps&) {}\n};\n\ntemplate <unsigned Index, unsigned Size>\nstruct square_cvec_mult_cols\n{    \n    template <typename Tmps, typename Ptrs, typename VPtr>\n    inline static void compute(Tmps& tmps, Ptrs& ptrs, VPtr vp)\n    {\n\tsquare_cvec_mult_rows<0, Size>::compute(tmps, ptrs, *vp);\n\tsquare_cvec_mult_cols<Index+1, Size>::compute(tmps, ptrs, ++vp);\n    }\n};\n\ntemplate <unsigned Size>\nstruct square_cvec_mult_cols<Size, Size>\n{    \n    template <typename Tmps, typename Ptrs, typename VPtr>\n    inline static void compute(Tmps&, Ptrs&, VPtr) {}\n};\n\n\n// Dense matrix vector multiplication with run-time matrix size\ntemplate <unsigned Size, typename MValue, typename MPara, typename ValueIn, typename ParaIn, \n\t  typename VectorOut, typename Assign>\ninline void square_cvec_mult(const dense2D<MValue, MPara>& A, const mtl::vector::dense_vector<ValueIn, ParaIn>& v, VectorOut& w, Assign)\n{\n    // vampir_trace<3067> tracer;\n    MTL_STATIC_ASSERT((mtl::traits::is_row_major<MPara>::value), \"Only row-major matrices supported in this function.\");\n\n    typedef typename Collection<VectorOut>::value_type value_type;    \n    multi_tmp<Size, value_type> tmps(math::zero(w[0]));\n\n    multi_tmp<Size, const MValue*>    ptrs;\n    init_ptrs<0, Size>::apply(A, ptrs);\n\n    const ValueIn* vp= &v[0];\n\n    square_cvec_mult_cols<0, Size>::compute(tmps, ptrs, vp); // outer loop over columns\n    square_cvec_mult_rows<0, Size>::update(Assign(), w, tmps);         // update rows\n}\n\n\n// Dense matrix vector multiplication with run-time matrix size\ntemplate <typename MValue, typename MPara, typename ValueIn, typename ParaIn, typename VectorOut, typename Assign>\ntypename boost::enable_if<mtl::traits::is_row_major<MPara> >::type\ninline dense_mat_cvec_mult(const dense2D<MValue, MPara>& A, const mtl::vector::dense_vector<ValueIn, ParaIn>& v, VectorOut& w, Assign, boost::mpl::false_)\n{\n    // vampir_trace<3066> tracer;\n\n    using math::zero; \n    if (mtl::vector::size(w) == 0) return;\n\n    typedef typename Collection<VectorOut>::value_type value_type;\n    // typedef ValueIn                                    value_in_type;\n    typedef typename MPara::size_type                  size_type;\n\n    const size_type  nr= num_rows(A), nc= num_cols(A);\n    if (nr == nc && nr <= 8) \n\tswitch (nr) {\n\t  case 1: Assign::first_update(w[0], A[0][0] * v[0]); return;\n\t  case 2: square_cvec_mult<2>(A, v, w, Assign()); return;\n\t  case 3: square_cvec_mult<3>(A, v, w, Assign()); return;\n\t  case 4: square_cvec_mult<4>(A, v, w, Assign()); return;\n\t  case 5: square_cvec_mult<5>(A, v, w, Assign()); return;\n\t  case 6: square_cvec_mult<6>(A, v, w, Assign()); return;\n\t  case 7: square_cvec_mult<7>(A, v, w, Assign()); return;\n\t  case 8: square_cvec_mult<8>(A, v, w, Assign()); return;\n\t}\n\n\n    const size_type  nrb= nr / 4 * 4;\n    const value_type z(math::zero(w[0]));\n\n    for (size_type i= 0; i < nrb; i+= 4) {\n\tvalue_type      tmp0(z), tmp1(z), tmp2(z), tmp3(z);\n\tconst MValue *p0= &A[i][0], *pe= p0 + nc, *p1= &A[i+1][0], *p2= &A[i+2][0], *p3= &A[i+3][0];\n\tconst ValueIn* vp= &v[0];\n\tfor (; p0 != pe; ) {\n\t    const ValueIn vj= *vp++;\n\t    tmp0+= *p0++ * vj;\n\t    tmp1+= *p1++ * vj;\n\t    tmp2+= *p2++ * vj;\n\t    tmp3+= *p3++ * vj;\n\t}\n\tAssign::first_update(w[i], tmp0);\n\tAssign::first_update(w[i+1], tmp1);\n\tAssign::first_update(w[i+2], tmp2);\n\tAssign::first_update(w[i+3], tmp3);\n    }\n\n    for (size_type i= nrb; i < nr; i++) {\n\tvalue_type tmp= z;\n\tconst ValueIn* vp= &v[0];\n\tfor (const MValue *p0= &A[i][0], *pe= p0 + nc; p0 != pe; ) \n\t    tmp+= *p0++ * *vp++;\n\tAssign::first_update(w[i], tmp);\n    }\n}\n\n\n// Dense matrix vector multiplication with run-time matrix size\ntemplate <typename Matrix, typename VectorIn, typename VectorOut, typename Assign>\ninline void dense_mat_cvec_mult(const Matrix& A, const VectorIn& v, VectorOut& w, Assign, boost::mpl::false_)\n{\n    vampir_trace<3018> tracer;\n    // Naive implementation, will be moved to a functor and complemented with more efficient ones\n\n    using math::zero; \n    if (mtl::vector::size(w) == 0) return;\n    // std::cout << \"Bin in richtiger Funktion\\n\";\n\n    // if (Assign::init_to_zero) set_to_zero(w); // replace update with first_update insteda\n\n    typedef typename Collection<VectorOut>::value_type value_type;\n    typedef typename Collection<VectorIn>::value_type  value_in_type;\n    typedef typename Collection<Matrix>::size_type     size_type;\n\n    const value_type z(math::zero(w[0]));\n    const size_type nr= num_rows(A), nrb= nr / 4 * 4, nc= num_cols(A);\n\n    for (size_type i= 0; i < nrb; i+= 4) {\n\tvalue_type      tmp0(z), tmp1(z), tmp2(z), tmp3(z);\n\tfor (size_type j= 0; j < nc; j++) {\n\t    const value_in_type vj= v[j];\n\t    tmp0+= A[i][j] * vj;\n\t    tmp1+= A[i+1][j] * vj;\n\t    tmp2+= A[i+2][j] * vj;\n\t    tmp3+= A[i+3][j] * vj;\n\t}\n\tAssign::first_update(w[i], tmp0);\n\tAssign::first_update(w[i+1], tmp1);\n\tAssign::first_update(w[i+2], tmp2);\n\tAssign::first_update(w[i+3], tmp3);\n    }\n\n    for (size_type i= nrb; i < nr; i++) {\n\tvalue_type tmp= z;\n\tfor (size_type j= 0; j < nc; j++) \n\t    tmp+= A[i][j] * v[j];\n\tAssign::first_update(w[i], tmp);\n    }\n}\n\n// Dense matrix vector multiplication\ntemplate <typename Matrix, typename VectorIn, typename VectorOut, typename Assign>\ninline void mat_cvec_mult(const Matrix& A, const VectorIn& v, VectorOut& w, Assign, tag::flat<tag::dense>)\n{\n# ifdef MTL_NOT_UNROLL_FSIZE_MAT_VEC_MULT\n    boost::mpl::false_        selector;\n# else\n\tmtl::traits::is_static<Matrix> selector;\n# endif\n    dense_mat_cvec_mult(A, v, w, Assign(), selector);\n}\n\n// Element structure vector multiplication\ntemplate <typename Matrix, typename VectorIn, typename VectorOut, typename Assign>\ninline void mat_cvec_mult(const Matrix& A, const VectorIn& v, VectorOut& w, Assign, tag::flat<tag::element_structure>)\n{\n    vampir_trace<3048> tracer;\n    if (mtl::vector::size(w) == 0) return;\n\n    typedef typename Collection<VectorOut>::value_type value_type;\n    typedef typename Collection<VectorIn>::value_type  value_in_type;\n\n    value_in_type varray[1024];\n    value_type    warray[1024];\n\n    if (Assign::init_to_zero) set_to_zero(w);\n    for(int elmi= 0; elmi < A.m_total_elements; elmi++){\n\tconst typename Matrix::element_type& elementi= A.m_elements[elmi];\n\tconst typename Matrix::element_type::index_type& indices= elementi.get_indices();\n\tunsigned int n(size(indices));\n\n\tif (n <= 1024) {\n\t    VectorIn vtmp(n, varray);\n\t    for (unsigned int i= 0; i < n; i++)\n\t\tvtmp[i]= v[indices[i]];\n\t    VectorOut wtmp(n, warray);\n\t    wtmp= elementi.get_values() * vtmp;\n\t    for (unsigned int i= 0; i < n; i++)\n\t\tAssign::update(w[indices[i]], wtmp[i]);\n\t} else {\n\t    VectorIn vtmp(n);\n\t    for (unsigned int i= 0; i < n; i++)\n\t\tvtmp[i]= v[indices[i]];\n\t    VectorOut wtmp(elementi.get_values() * vtmp);\n\t    for (unsigned int i= 0; i < n; i++)\n\t\tAssign::update(w[indices[i]], wtmp[i]);\n\t}\n    }\n}\n\n// Multi-vector vector multiplication (tag::multi_vector is derived from dense)\ntemplate <typename Matrix, typename VectorIn, typename VectorOut, typename Assign>\ninline void mat_cvec_mult(const Matrix& A, const VectorIn& v, VectorOut& w, Assign, tag::flat<tag::multi_vector>)\n{\n    vampir_trace<3019> tracer;\n    if (Assign::init_to_zero) set_to_zero(w);\n    for (unsigned i= 0; i < num_cols(A); i++)\n\tAssign::update(w, A.vector(i) * v[i]);\n}\n\n// Transposed multi-vector vector multiplication (tag::transposed_multi_vector is derived from dense)\ntemplate <typename TransposedMatrix, typename VectorIn, typename VectorOut, typename Assign>\ninline void mat_cvec_mult(const TransposedMatrix& A, const VectorIn& v, VectorOut& w, Assign, tag::flat<tag::transposed_multi_vector>)\n{\n    vampir_trace<3020> tracer;\n    typename TransposedMatrix::const_ref_type B= A.ref; // Referred matrix\n\n    if (Assign::init_to_zero) set_to_zero(w);\n    for (unsigned i= 0; i < num_cols(B); i++)\n\tAssign::update(w[i], dot_real(B.vector(i), v));\n}\n\n// Hermitian multi-vector vector multiplication (tag::hermitian_multi_vector is derived from dense)\ntemplate <typename HermitianMatrix, typename VectorIn, typename VectorOut, typename Assign>\ninline void mat_cvec_mult(const HermitianMatrix& A, const VectorIn& v, VectorOut& w, Assign, tag::flat<tag::hermitian_multi_vector>)\n{\n    vampir_trace<3021> tracer;\n    typename HermitianMatrix::const_ref_type B= A.const_ref(); // Referred matrix\n\n    if (Assign::init_to_zero) set_to_zero(w);\n    for (unsigned i= 0; i < num_cols(B); i++)\n\tAssign::update(w[i], dot(B.vector(i), v));\n}\n\n\n\n// Sparse row-major matrix vector multiplication\ntemplate <typename Matrix, typename VectorIn, typename VectorOut, typename Assign>\ninline void smat_cvec_mult(const Matrix& A, const VectorIn& v, VectorOut& w, Assign, tag::row_major)\n{\n    vampir_trace<3022> tracer;\n    using namespace tag; \n    using mtl::traits::range_generator;  \n    using math::zero;\n    using mtl::vector::set_to_zero;\n\n    typedef typename range_generator<row, Matrix>::type       a_cur_type;    \n    typedef typename range_generator<nz, a_cur_type>::type    a_icur_type;            \n    typename mtl::traits::col<Matrix>::type                   col_a(A); \n    typename mtl::traits::const_value<Matrix>::type           value_a(A); \n\n    if (Assign::init_to_zero) set_to_zero(w);\n\n    typedef typename Collection<VectorOut>::value_type        value_type;\n    a_cur_type ac= begin<row>(A), aend= end<row>(A);\n    for (unsigned i= 0; ac != aend; ++ac, ++i) {\n\tvalue_type tmp= zero(w[i]);\n\tfor (a_icur_type aic= begin<nz>(ac), aiend= end<nz>(ac); aic != aiend; ++aic) \n\t    tmp+= value_a(*aic) * v[col_a(*aic)];\t\n\tAssign::update(w[i], tmp);\n    }\n}\n\n// Row-major compressed2D with very few entries (i.e. Very Sparse MATrix) times vector\ntemplate <typename MValue, typename MPara, typename VectorIn, typename VectorOut, typename Assign>\ninline void vsmat_cvec_mult(const compressed2D<MValue, MPara>& A, const VectorIn& v, VectorOut& w, Assign, tag::row_major)\n{\n    vampir_trace<3064> tracer;\n    using math::zero;\n\n    typedef compressed2D<MValue, MPara>                       Matrix;\n    typedef typename Collection<Matrix>::size_type            size_type; \n    typedef typename Collection<VectorOut>::value_type        value_type;\n\n    if (size(w) == 0) return;\n    const value_type z(math::zero(w[0]));\n\n    // std::cout << \"very sparse: nnz = \" << A.nnz() << \", num_rows = \" << num_rows(A) << '\\n';\n\n    size_type nr= num_rows(A);\n    for (size_type i1= 0, i2= std::min<size_type>(1024, nr); i1 < i2; i1= i2, i2= std::min<size_type>(i2 + 1024, nr)) {\n\t// std::cout << \"range = \" << i1 << \" .. \" << i2 << \"\\n\";\n\tif (A.ref_major()[i1] < A.ref_major()[i2])\n\t    for (size_type i= i1; i < i2; ++i) {\n\t\tconst size_type cj0= A.ref_major()[i], cj1= A.ref_major()[i+1];\n\t\tvalue_type      tmp0(z);\n\t\tfor (size_type j0= cj0; j0 != cj1; ++j0)\n\t\t    tmp0+= A.data[j0] * v[A.ref_minor()[j0]];\n\t\tAssign::first_update(w[i], tmp0);\n\t    }\n    }\n}\n\n#ifdef MTL_CRS_CVEC_MULT_TUNING\ntemplate <unsigned Index, unsigned BSize, typename SizeType>\nstruct crs_cvec_mult_block\n{\n    template <typename Matrix, typename VectorIn, typename CBlock, typename TBlock>\n    void operator()(const Matrix& A, const VectorIn& v, const CBlock& cj, TBlock& tmp) const\n    {\n\tfor (SizeType j= cj.value; j != cj.sub.value; ++j) // cj is one index larger\n\t    tmp.value+= A.data[j] * v[A.ref_minor()[j]];\n\tsub(A, v, cj.sub, tmp.sub);\n    }\n\n    template <typename VectorOut, typename TBlock, typename Assign>\n    void first_update(VectorOut& w, SizeType i, const TBlock& tmp, Assign as) const\n    { \n\tAssign::first_update(w[i + Index], tmp.value);\n\tsub.first_update(w, i, tmp.sub, as);\n    }\n    \n    crs_cvec_mult_block<Index+1, BSize, SizeType> sub;\n};\n\n\ntemplate <unsigned BSize, typename SizeType>\nstruct crs_cvec_mult_block<BSize, BSize, SizeType>\n{\n    template <typename Matrix, typename VectorIn, typename CBlock, typename TBlock>\n    void operator()(const Matrix& A, const VectorIn& v, const CBlock& cj, TBlock& tmp) const\n    {\n\tfor (SizeType j= cj.value; j != cj.sub.value; ++j)// cj is one index larger\n\t    tmp.value+= A.data[j] * v[A.ref_minor()[j]];\n    }\n\n    template <typename VectorOut, typename TBlock, typename Assign>\n    void first_update(VectorOut& w, SizeType i, const TBlock& tmp, Assign) const\n    { \n\tAssign::first_update(w[i + BSize], tmp.value);\n    }\n};\n\n\n// Row-major compressed2D vector multiplication\ntemplate <unsigned BSize, typename MValue, typename MPara, typename VectorIn, typename VectorOut, typename Assign>\ninline void smat_cvec_mult(const compressed2D<MValue, MPara>& A, const VectorIn& v, VectorOut& w, Assign as, tag::row_major)\n{\n    vampir_trace<3049> tracer;\n    using math::zero;\n\n    if (A.nnz() < num_rows(A)) {\n\tvsmat_cvec_mult(A, v, w, as, tag::row_major());\n\treturn;\n    }\n\n    typedef compressed2D<MValue, MPara>                       Matrix;\n    typedef typename Collection<VectorOut>::value_type        value_type;\n    typedef typename mtl::traits::omp_size_type<typename Collection<Matrix>::size_type>::type size_type;\n\n    if (size(w) == 0) return;\n    const value_type z(math::zero(w[0]));\n\n    size_type nr= num_rows(A), nrb= nr / BSize * BSize;\n\n    #ifdef MTL_WITH_OPENMP\n    #   pragma omp parallel\n    #endif\n    {\n    \t#ifdef MTL_WITH_OPENMP\n\t    vampir_trace<8004> tracer;\n    \t#   pragma omp for\n    \t#endif\n\tfor (size_type i= 0; i < nrb; i+= BSize) {\n\t    multi_constant_from_array<0, BSize+1, size_type> cj(A.ref_major(), i);\n\t    multi_tmp<BSize, value_type>                     tmp(z);\n\t    crs_cvec_mult_block<0, BSize-1, size_type>       block;\n\n\t    block(A, v, cj, tmp);\n\t    block.first_update(w, i, tmp, as);\n\t}\n    }\n\n    for (size_type i= nrb; i < nr; ++i) {\n\tconst size_type cj0= A.ref_major()[i], cj1= A.ref_major()[i+1];\n\tvalue_type      tmp0(z);\n\tfor (size_type j0= cj0; j0 != cj1; ++j0)\n\t    tmp0+= A.data[j0] * v[A.ref_minor()[j0]];\n\tAssign::first_update(w[i], tmp0);\n    }\n}\n\ntemplate <typename MValue, typename MPara, typename VectorIn, typename VectorOut, typename Assign>\ntypename mtl::traits::enable_if_scalar<typename Collection<VectorOut>::value_type>::type\ninline smat_cvec_mult(const compressed2D<MValue, MPara>& A, const VectorIn& v, VectorOut& w, Assign, tag::row_major)\n{\n    smat_cvec_mult<crs_cvec_mult_block_size>(A, v, w, Assign(), tag::row_major());\n}\n#endif\n\n\n#if !defined(MTL_CRS_CVEC_MULT_NO_ACCEL) && !defined(MTL_CRS_CVEC_MULT_TUNING)\n\ntemplate <typename MValue, typename MPara, typename VectorIn, typename VectorOut, typename Assign>\ntypename mtl::traits::enable_if_scalar<typename Collection<VectorOut>::value_type>::type\ninline adapt_crs_cvec_mult(const compressed2D<MValue, MPara>& A, const VectorIn& v, VectorOut& w, Assign)\n{\n    vampir_trace<3065> tracer;\n    using math::zero;\n    assert(!Assign::init_to_zero);\n\n    typedef compressed2D<MValue, MPara>                       Matrix;\n    typedef typename Collection<Matrix>::size_type            size_type; \n    typedef typename Collection<VectorOut>::value_type        value_type;\n\n    const value_type z(math::zero(w[0]));\n    size_type nr= num_rows(A), nrb= nr / 4 * 4, nrb2= nr / 64 * 64;\n\n    for (size_type i1= 0; i1 < nrb2; i1+= 64) \n\tif (A.ref_major()[i1] != A.ref_major()[i1 + 64])\n\t    for (size_type i2= i1, i2e= i1+64; i2 < i2e; i2+= 16)\n\t\tif (A.ref_major()[i2] != A.ref_major()[i2 + 16])\n\t\t    for (size_type i= i2, i3e= i2+16; i < i3e; i+= 4) \n\t\t\tif (A.ref_major()[i] != A.ref_major()[i + 4]) {\n\t\t\t    const size_type cj0= A.ref_major()[i], cj1= A.ref_major()[i+1], cj2= A.ref_major()[i+2], \n\t\t\t\tcj3= A.ref_major()[i+3], cj4= A.ref_major()[i+4];\n\t\t\t    value_type      tmp0(z), tmp1(z), tmp2(z), tmp3(z);\n\t\t\t    for (size_type j0= cj0; j0 != cj1; ++j0)\n\t\t\t\ttmp0+= A.data[j0] * v[A.ref_minor()[j0]];\n\t\t\t    for (size_type j1= cj1; j1 != cj2; ++j1)\n\t\t\t\ttmp1+= A.data[j1] * v[A.ref_minor()[j1]];\n\t\t\t    for (size_type j2= cj2; j2 != cj3; ++j2)\n\t\t\t\ttmp2+= A.data[j2] * v[A.ref_minor()[j2]];\n\t\t\t    for (size_type j3= cj3; j3 != cj4; ++j3)\n\t\t\t\ttmp3+= A.data[j3] * v[A.ref_minor()[j3]];\n\n\t\t\t    Assign::first_update(w[i], tmp0);\n\t\t\t    Assign::first_update(w[i+1], tmp1);\n\t\t\t    Assign::first_update(w[i+2], tmp2);\n\t\t\t    Assign::first_update(w[i+3], tmp3);\n\t\t\t}\n\n    for (size_type i= nrb2; i < nrb; i+= 4) \n\tif (A.ref_major()[i] != A.ref_major()[i + 4])  {\n\t    const size_type cj0= A.ref_major()[i], cj1= A.ref_major()[i+1], cj2= A.ref_major()[i+2], \n\t\tcj3= A.ref_major()[i+3], cj4= A.ref_major()[i+4];\n\t    value_type      tmp0(z), tmp1(z), tmp2(z), tmp3(z);\n\t    for (size_type j0= cj0; j0 != cj1; ++j0)\n\t\ttmp0+= A.data[j0] * v[A.ref_minor()[j0]];\n\t    for (size_type j1= cj1; j1 != cj2; ++j1)\n\t\ttmp1+= A.data[j1] * v[A.ref_minor()[j1]];\n\t    for (size_type j2= cj2; j2 != cj3; ++j2)\n\t\ttmp2+= A.data[j2] * v[A.ref_minor()[j2]];\n\t    for (size_type j3= cj3; j3 != cj4; ++j3)\n\t\ttmp3+= A.data[j3] * v[A.ref_minor()[j3]];\n\n\t    Assign::first_update(w[i], tmp0);\n\t    Assign::first_update(w[i+1], tmp1);\n\t    Assign::first_update(w[i+2], tmp2);\n\t    Assign::first_update(w[i+3], tmp3);\n\t}\n\n    for (size_type i= nrb; i < nr; ++i) {\n\tconst size_type cj0= A.ref_major()[i], cj1= A.ref_major()[i+1];\n\tvalue_type      tmp0(z);\n\tfor (size_type j0= cj0; j0 != cj1; ++j0)\n\t    tmp0+= A.data[j0] * v[A.ref_minor()[j0]];\n\tAssign::first_update(w[i], tmp0);\n    }\n}\n\n// Row-major compressed2D vector multiplication\ntemplate <typename MValue, typename MPara, typename VectorIn, typename VectorOut, typename Assign>\ntypename mtl::traits::enable_if_scalar<typename Collection<VectorOut>::value_type>::type\ninline smat_cvec_mult(const compressed2D<MValue, MPara>& A, const VectorIn& v, VectorOut& w, Assign as, tag::row_major)\n{\n    vampir_trace<3049> tracer;\n    // vampir_trace<5056> tttracer;\n    using math::zero;\n\n    if (A.nnz() < num_rows(A) && !as.init_to_zero) {\n\tvsmat_cvec_mult(A, v, w, as, tag::row_major());\n\treturn;\n    }\n\n    typedef compressed2D<MValue, MPara>                       Matrix;\n    typedef typename Collection<VectorOut>::value_type        value_type;\n    typedef typename mtl::traits::omp_size_type<typename Collection<Matrix>::size_type>::type size_type;\n\n    if (size(w) == 0) return;\n    const value_type z(math::zero(w[0]));\n\n    size_type nr= num_rows(A), nrb= nr / 4 * 4;\n    if (nr > 10) {\n\tsize_type nh= nr / 2, nq= nr / 4, nt= nr - nq;\n\tif (!as.init_to_zero &&\n\t    (A.ref_major()[1] == A.ref_major()[0] \n\t     || A.ref_major()[nq] == A.ref_major()[nq+1]\n\t     || A.ref_major()[nh] == A.ref_major()[nh+1]\n\t     || A.ref_major()[nt] == A.ref_major()[nt+1]\n\t     || A.ref_major()[nr-1] == A.ref_major()[nr])) {\n\t    adapt_crs_cvec_mult(A, v, w, as);\n\t    return;\n\t}\n    }\n\n    #ifdef MTL_WITH_OPENMP\n    #   pragma omp parallel\n    #endif\n    {\n    \t#ifdef MTL_WITH_OPENMP\n\t    vampir_trace<8004> tracer;\n    \t#   pragma omp for\n    \t#endif\n\t    for (size_type i= 0; i < nrb; i+= 4) {\n\t\tconst size_type cj0= A.ref_major()[i], cj1= A.ref_major()[i+1], cj2= A.ref_major()[i+2], \n\t\t    cj3= A.ref_major()[i+3], cj4= A.ref_major()[i+4];\n\t\tvalue_type      tmp0(z), tmp1(z), tmp2(z), tmp3(z);\n\t\tfor (size_type j0= cj0; j0 != cj1; ++j0)\n\t\t    tmp0+= A.data[j0] * v[A.ref_minor()[j0]];\n\t\tfor (size_type j1= cj1; j1 != cj2; ++j1)\n\t\t    tmp1+= A.data[j1] * v[A.ref_minor()[j1]];\n\t\tfor (size_type j2= cj2; j2 != cj3; ++j2)\n\t\t    tmp2+= A.data[j2] * v[A.ref_minor()[j2]];\n\t\tfor (size_type j3= cj3; j3 != cj4; ++j3)\n\t\t    tmp3+= A.data[j3] * v[A.ref_minor()[j3]];\n\n\t\tAssign::first_update(w[i], tmp0);\n\t\tAssign::first_update(w[i+1], tmp1);\n\t\tAssign::first_update(w[i+2], tmp2);\n\t\tAssign::first_update(w[i+3], tmp3);\n\t    }\n    }\n\n    for (size_type i= nrb; i < nr; ++i) {\n\tconst size_type cj0= A.ref_major()[i], cj1= A.ref_major()[i+1];\n\tvalue_type      tmp0(z);\n\tfor (size_type j0= cj0; j0 != cj1; ++j0)\n\t    tmp0+= A.data[j0] * v[A.ref_minor()[j0]];\n\tAssign::first_update(w[i], tmp0);\n    }\n}\n#endif\n\n// Row-major ell_matrix vector multiplication\ntemplate <typename MValue, typename MPara, typename VectorIn, typename VectorOut, typename Assign>\ntypename mtl::traits::enable_if_scalar<typename Collection<VectorOut>::value_type>::type\ninline smat_cvec_mult(const ell_matrix<MValue, MPara>& A, const VectorIn& v, VectorOut& w, Assign, tag::row_major)\n{\n    typedef typename MPara::size_type size_type;\n\n    const size_type stride= A.stride(), slots= A.slots();\n    for (size_type r= 0; r < A.dim1(); ++r) {\n\tMValue s(0);\n\tfor (size_type k= r, i= 0; i < slots; ++i, k+= stride)\n\t    s+= A.ref_data()[k] * v[A.ref_minor()[k]];\n\tAssign::first_update(w[r], s);\n    }\n }\n\n\n// Row-major sparse_banded vector multiplication\ntemplate <typename MValue, typename MPara, typename VectorIn, typename VectorOut, typename Assign>\ntypename mtl::traits::enable_if_scalar<typename Collection<VectorOut>::value_type>::type\ninline smat_cvec_mult(const sparse_banded<MValue, MPara>& A, const VectorIn& v, VectorOut& w, Assign, tag::row_major)\n{\n    vampir_trace<3069> tracer;\n    typedef sparse_banded<MValue, MPara>                      Matrix;\n    typedef typename Collection<VectorOut>::value_type        value_type;\n    typedef typename Matrix::band_size_type                   band_size_type;\n    typedef typename MPara::size_type                         size_type;\n    typedef mtl::vector::dense_vector<band_size_type, vector::parameters<> > vector_type;\n\n    if (size(w) == 0) return;\n    const value_type z(math::zero(w[0]));\n\n    size_type nr= num_rows(A), nc= num_cols(A), nb= A.ref_bands().size();\n    if (nb == size_type(0) && Assign::init_to_zero) {\n\tset_to_zero(w);\n\treturn;\n    }\n\n    vector_type bands(A.ref_bands()), begin_rows(max(0, -bands)), end_rows(min(nr, nc - bands));\n    assert(end_rows[nb-1] > 0);\n\n    // std::cout << \"bands = \" << bands << \", begin_rows = \" << begin_rows << \", end_rows = \" << end_rows << \"\\n\";\n    size_type begin_pos= 0, end_pos= nb - 1;\n\n    // find lowest diagonal in row 0\n    while (begin_pos < nb && begin_rows[begin_pos] > 0) begin_pos++;\n    // if at the end, the first rows are empty\n    if (begin_pos == nb && Assign::init_to_zero) {\n\tw[irange(begin_rows[--begin_pos])]= z;\n\t// std::cout << \"w[0..\" << begin_rows[begin_pos] << \"] <- 0\\n\";\n    }\n\n    band_size_type from= begin_rows[begin_pos];\n    // find first entry with same value\n    while (begin_pos > 0 && begin_rows[begin_pos - 1] == from) {\n\tassert(from == 0); // should only happen when multiple bands start in row 0\n\tbegin_pos--;\n    }\n    for (bool active= true; active; ) {\n\t// search backwards for the next-largest entry\n\tband_size_type to= begin_pos > 0 && begin_rows[begin_pos - 1] <= end_rows[end_pos] ? begin_rows[begin_pos - 1] : end_rows[end_pos];\n\n\t// std::cout << \"rows \" << from << \"..\" << to << \": with bands \";\n\t// for (size_type i= begin_pos; i <= end_pos; i++)\n\t//     std::cout << bands[i] << (i < end_pos ? \", \" : \"\\n\");\n\n\tconst MValue* Aps= A.ref_data() + (from * nb + begin_pos);\n\n\tconst band_size_type blocked_to= ((to - from) & -4) + from; \n\tassert((blocked_to - from) % 4 == 0 && blocked_to >= band_size_type(from) && blocked_to <= band_size_type(to));\n\tfor (band_size_type r= from; r < blocked_to; r+= 4) {\n\t    value_type     tmp0(z), tmp1(z), tmp2(z), tmp3(z);\n\t    const MValue   *Ap0= Aps, *Ap1= Aps + nb, *Ap2= Ap1 + nb, *Ap3= Ap2 + nb;\n\t    for (size_type b= begin_pos; b <= end_pos; ++b, ++Ap0, ++Ap1, ++Ap2, ++Ap3) {\n\t\ttmp0+= *Ap0 * v[r + bands[b]];\n\t\ttmp1+= *Ap1 * v[r + bands[b] + 1];\n\t\ttmp2+= *Ap2 * v[r + bands[b] + 2];\n\t\ttmp3+= *Ap3 * v[r + bands[b] + 3];\n\t    }\n\t    Assign::first_update(w[r], tmp0);\n\t    Assign::first_update(w[r+1], tmp1);\n\t    Assign::first_update(w[r+2], tmp2);\n\t    Assign::first_update(w[r+3], tmp3);\n\t    Aps+= 4 * nb;\n\t}\n\n\tfor (band_size_type r= blocked_to; r < band_size_type(to); r++) {\n\t    value_type     tmp(z);\n\t    const MValue*  Ap= Aps;\n\t    for (size_type b= begin_pos; b <= end_pos; ++b, ++Ap)\n\t\ttmp+= *Ap * v[r + bands[b]];\n\t    Assign::first_update(w[r], tmp);\n\t    Aps+= nb;\n\t}\n    \n\tif (begin_pos > 0) {\n\t    if (begin_rows[begin_pos-1] == to)\n\t\tbegin_pos--;\n\t    if (end_rows[end_pos] == to)\n\t\tend_pos--;\n\t} else { // begin == 0 -> decrement end_pos or finish\n\t    if (end_rows[0] == to) {\n\t\tactive= false;\n\t\tassert(end_rows[0] = end_rows[end_pos]);\n\t    } else {\n\t\tassert(end_pos > 0);\n\t\tend_pos--;\n\t    }\n\t}\n\tassert(begin_pos <= end_pos);\n\tfrom= to;\n    }\n\n    if (size_type(end_rows[0]) < nr  && Assign::init_to_zero) {\n\tw[irange(end_rows[0], nr)]= z;\n\t// std::cout << \"w[\" << end_rows[0] << \"..\" << nr << \"] <- 0\\n\";\n    }\n}\n\n// Sparse column-major matrix vector multiplication\ntemplate <typename Matrix, typename VectorIn, typename VectorOut, typename Assign>\ninline void smat_cvec_mult(const Matrix& A, const VectorIn& v, VectorOut& w, Assign, tag::col_major)\n{\n    vampir_trace<3023> tracer;\n    using namespace tag; namespace traits = mtl::traits;\n    using traits::range_generator;  \n    using mtl::vector::set_to_zero;\n    typedef typename range_generator<col, Matrix>::type       a_cur_type;             \n    typedef typename range_generator<nz, a_cur_type>::type    a_icur_type;            \n\n    typename traits::row<Matrix>::type                        row_a(A); \n    typename traits::const_value<Matrix>::type                value_a(A); \n\n    if (Assign::init_to_zero) set_to_zero(w);\n\n    unsigned rv= 0; // traverse all rows of v\n    for (a_cur_type ac= begin<col>(A), aend= end<col>(A); ac != aend; ++ac, ++rv) {\n\ttypename Collection<VectorIn>::value_type    vv= v[rv]; \n\tfor (a_icur_type aic= begin<nz>(ac), aiend= end<nz>(ac); aic != aiend; ++aic) \n\t    Assign::update(w[row_a(*aic)], value_a(*aic) * vv);\n    }\n}\n\n// Sparse matrix vector multiplication\ntemplate <typename Matrix, typename VectorIn, typename VectorOut, typename Assign>\ninline void mat_cvec_mult(const Matrix& A, const VectorIn& v, VectorOut& w, Assign, tag::flat<tag::sparse>)\n{\n    smat_cvec_mult(A, v, w, Assign(), typename OrientedCollection<Matrix>::orientation());\n}\n\n\n\n}} // namespace mtl::matrix\n\n\n\n\n#endif // MTL_MAT_VEC_MULT_INCLUDE\n\n", "meta": {"hexsha": "184cd648fba97a6dfdbd4328ace314f4030375d4", "size": 31775, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/operation/mat_vec_mult.hpp", "max_stars_repo_name": "spraetor/amdis2", "max_stars_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T16:44:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T07:26:27.000Z", "max_issues_repo_path": "lib/mtl4/boost/numeric/mtl/operation/mat_vec_mult.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/mtl4/boost/numeric/mtl/operation/mat_vec_mult.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6481042654, "max_line_length": 154, "alphanum_fraction": 0.6529346971, "num_tokens": 9644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604274, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2837317437382898}}
{"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_METROPOLISFLIPT_HPP\n#define NETKET_METROPOLISFLIPT_HPP\n\n#include <mpi.h>\n#include <Eigen/Dense>\n#include <iostream>\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 changes\n// Parallel tempering is also used\nclass MetropolisLocalPt : public AbstractSampler {\n  AbstractMachine& psi_;\n\n  const AbstractHilbert& hilbert_;\n\n  // number of visible units\n  const int nv_;\n\n  // states of visible units\n  // for each sampled temperature\n  std::vector<Eigen::VectorXd> v_;\n\n  Eigen::VectorXd accept_;\n  Eigen::VectorXd moves_;\n\n  int mynode_;\n  int totalnodes_;\n\n  // clusters to do updates\n  std::vector<std::vector<int>> clusters_;\n\n  // Look-up tables\n  std::vector<typename AbstractMachine::LookupType> lt_;\n\n  int nrep_;\n\n  std::vector<double> beta_;\n\n  int nstates_;\n  std::vector<double> localstates_;\n\n public:\n  // Constructor with one replica by default\n  explicit MetropolisLocalPt(AbstractMachine& psi, int nreplicas = 1)\n      : psi_(psi),\n        hilbert_(psi.GetHilbert()),\n        nv_(hilbert_.Size()),\n        nrep_(nreplicas) {\n    Init();\n  }\n\n  void Init() {\n    MPI_Comm_size(MPI_COMM_WORLD, &totalnodes_);\n    MPI_Comm_rank(MPI_COMM_WORLD, &mynode_);\n\n    nstates_ = hilbert_.LocalSize();\n    localstates_ = hilbert_.LocalStates();\n\n    SetNreplicas(nrep_);\n\n    InfoMessage() << \"Metropolis sampler with parallel tempering is ready \"\n                  << std::endl;\n    InfoMessage() << \"Nreplicas is equal to \" << nrep_ << std::endl;\n  }\n\n  void SetNreplicas(int nrep) {\n    nrep_ = nrep;\n    v_.resize(nrep_);\n    for (int i = 0; i < nrep_; i++) {\n      v_[i].resize(nv_);\n    }\n\n    for (int i = 0; i < nrep_; i++) {\n      beta_.push_back(1. - double(i) / double(nrep_));\n    }\n\n    lt_.resize(nrep_);\n\n    accept_.resize(2 * nrep_);\n    moves_.resize(2 * nrep_);\n\n    Reset(true);\n  }\n\n  void Reset(bool initrandom = false) override {\n    if (initrandom) {\n      for (int i = 0; i < nrep_; i++) {\n        hilbert_.RandomVals(v_[i], this->GetRandomEngine());\n      }\n    }\n\n    for (int i = 0; i < nrep_; i++) {\n      psi_.InitLookup(v_[i], lt_[i]);\n    }\n\n    accept_ = Eigen::VectorXd::Zero(2 * nrep_);\n    moves_ = Eigen::VectorXd::Zero(2 * nrep_);\n  }\n\n  // Exchange sweep at given temperature\n  void LocalSweep(int rep) {\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(this->GetRandomEngine());\n      assert(si < nv_);\n      tochange[0] = si;\n\n      // picking a random state\n      int newstate = diststate(this->GetRandomEngine());\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_[rep](si)) <\n             std::numeric_limits<double>::epsilon()) {\n        newstate = diststate(this->GetRandomEngine());\n        newconf[0] = localstates_[newstate];\n      }\n\n      const auto lvd = psi_.LogValDiff(v_[rep], tochange, newconf, lt_[rep]);\n      double ratio = std::norm(std::exp(beta_[rep] * lvd));\n\n#ifndef NDEBUG\n      const auto psival1 = psi_.LogVal(v_[rep]);\n      if (std::abs(\n              std::exp(psi_.LogVal(v_[rep]) - psi_.LogVal(v_[rep], lt_[rep])) -\n              1.) > 1.0e-8) {\n        std::cerr << psi_.LogVal(v_[rep]) << \"  and LogVal with Lt is \"\n                  << psi_.LogVal(v_[rep], lt_[rep]) << std::endl;\n        std::abort();\n      }\n#endif\n      // Metropolis acceptance test\n      if (ratio > distu(this->GetRandomEngine())) {\n        accept_(rep) += 1;\n\n        psi_.UpdateLookup(v_[rep], tochange, newconf, lt_[rep]);\n        hilbert_.UpdateConf(v_[rep], tochange, newconf);\n\n#ifndef NDEBUG\n        const auto psival2 = psi_.LogVal(v_[rep]);\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_[rep], lt_[rep]) << std::endl;\n          std::abort();\n        }\n#endif\n      }\n      moves_(rep) += 1;\n    }\n  }\n\n  void Sweep() override {\n    // First we do local sweeps\n    for (int i = 0; i < nrep_; i++) {\n      LocalSweep(i);\n    }\n\n    // Tempearture exchanges\n    std::uniform_real_distribution<double> distribution(0, 1);\n\n    for (int r = 1; r < nrep_; r += 2) {\n      if (ExchangeProb(r, r - 1) > distribution(this->GetRandomEngine())) {\n        Exchange(r, r - 1);\n        accept_(nrep_ + r) += 1.;\n        accept_(nrep_ + r - 1) += 1;\n      }\n      moves_(nrep_ + r) += 1.;\n      moves_(nrep_ + r - 1) += 1;\n    }\n\n    for (int r = 2; r < nrep_; r += 2) {\n      if (ExchangeProb(r, r - 1) > distribution(this->GetRandomEngine())) {\n        Exchange(r, r - 1);\n        accept_(nrep_ + r) += 1.;\n        accept_(nrep_ + r - 1) += 1;\n      }\n      moves_(nrep_ + r) += 1.;\n      moves_(nrep_ + r - 1) += 1;\n    }\n  }\n\n  // computes the probability to exchange two replicas\n  double ExchangeProb(int r1, int r2) {\n    const double lf1 = 2 * std::real(psi_.LogVal(v_[r1], lt_[r1]));\n    const double lf2 = 2 * std::real(psi_.LogVal(v_[r2], lt_[r2]));\n\n    return std::exp((beta_[r1] - beta_[r2]) * (lf2 - lf1));\n  }\n\n  void Exchange(int r1, int r2) {\n    std::swap(v_[r1], v_[r2]);\n    std::swap(lt_[r1], lt_[r2]);\n  }\n\n  Eigen::VectorXd Visible() override { return v_[0]; }\n\n  void SetVisible(const Eigen::VectorXd& v) override { v_[0] = v; }\n\n  AbstractMachine& 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 < acc.size(); i++) {\n      acc(i) /= moves_(i);\n    }\n    return acc;\n  }\n};\n\n}  // namespace netket\n\n#endif\n", "meta": {"hexsha": "c8343a194bcac34ab42486a456390e8aa2c2bcd9", "size": 6760, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NetKet/Sampler/metropolis_local_pt.hpp", "max_stars_repo_name": "flatironinstitute/netket", "max_stars_repo_head_hexsha": "888a4b56b6242d62b45d32eda43e10066c65fdf9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T19:00:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T01:03:15.000Z", "max_issues_repo_path": "NetKet/Sampler/metropolis_local_pt.hpp", "max_issues_repo_name": "flatironinstitute/netket", "max_issues_repo_head_hexsha": "888a4b56b6242d62b45d32eda43e10066c65fdf9", "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_pt.hpp", "max_forks_repo_name": "flatironinstitute/netket", "max_forks_repo_head_hexsha": "888a4b56b6242d62b45d32eda43e10066c65fdf9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-23T01:04:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T01:04:00.000Z", "avg_line_length": 27.7049180328, "max_line_length": 79, "alphanum_fraction": 0.6053254438, "num_tokens": 1967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.28369912704295597}}
{"text": "/*\n * Grid.h\n *\n *  Created on: Nov 5, 2012\n *      Author: petr\n */\n#pragma once\n#ifndef GRID_H_\n#define GRID_H_\n\n#include <cmath>\n#include <vector>\n#include <string>\n#include <sstream>\n#include <petscdmda.h>\n#include <Eigen/Dense>\n#include \"BoundingBox.hpp\"\n\n/**\n * @brief GridData holds all information about grid distribution.\n * \n * The information is hold for all nodes. This waste space, however all\n * other manipulation is faster and easier\n * \n */\nstruct GridData {\n\n    double minx[3]; ///< global ower left corner of the grid\n    double maxx[3]; ///< global upper right corner of the grid\n\n    double lminx[3]; ///< local lower left corner of the grid\n    double lmaxx[3]; ///< local upper right corner of the grid\n    \n    double glminx[3]; ///< local ghosted lower left corner of the grid\n    double glmaxx[3]; ///< local ghosted upper right corner of the grid\n    \n    \n    int pm; ///< number of processors m\n    int pn; ///< number of processors n\n    int pp; ///< number of processors p\n    \n    \n    int m; ///< number of gridcells m\n    int n; ///< number of gridcells n\n    int p; ///< number of gridcells p\n\n    \n    int ghosts; ///< number of ghost cells\n\n    \n    int lm; ///< local number of gridcells m\n    int ln; ///< local number of gridcells n\n    int lp; ///< local number of gridcells p\n    \n    int glm; ///< local number of ghosted gridcells m\n    int gln; ///< local number of ghosted gridcells n\n    int glp; ///< local number of ghosted gridcells p\n\n\n    static void createType(MPI_Datatype* type) {\n        const int    nitems = 2;\n        int          blocklengths[2] = {18,\n                                        13};\n\n        MPI_Datatype types[2] = {MPI_DOUBLE,\n                                 MPI_INT};\n\n        MPI_Aint offsets[2], extent;\n\n        offsets[0] = 0;\n\n        MPI_Type_extent(MPI_DOUBLE, &extent);\n        offsets[1] = blocklengths[0] * extent;\n\n        MPI_Type_create_struct(nitems, blocklengths, offsets, types, type);\n        MPI_Type_commit(type);\n    }\n\n    /**\n     * @brief Return bounding box of the whole grid\n     * @return grid bounding box\n     */\n    Box<double, 3> getBB() {\n        return Box<double, 3>(minx, maxx);\n    }\n};\n\n\n\n\n\n/**\n * @brief Grid class wrapping PETSc DMDA grid\n * @tparam type int or double\n * @tparam dim grid dimension\n */\ntemplate <typename type, PetscInt dim>\nclass Grid {\n\n    MPI_Datatype mpi_grid_type;\n\n    GridData* globalGridLayout; ///< Stores information about the global grid distribution\n\n    // grid step size, with appropriate length\n    type dx[dim]; ///< deprecated, todo remove\n\n    // no shit Sherlock, yes it is stencil size\n    type  stencilSize;\n\n    // lower left corner of the grid\n    type minX[dim]; ///< deprecated, todo remove\n\n    // upper right corner of the grid\n    type maxX[dim]; ///< deprecated, todo remove\n\n    // store number of grid cells for each dimension - global data\n    long int  numberOfGridCells[dim]; ///< deprecated, todo remove\n\n    // store number of ghosted grid cells for each dimension - global data\n    long int  numberOfGhostedGridCells[dim]; ///< deprecated, todo remove\n\n    // store the local minimum of grid - ghosted one\n    type localMinX[dim]; ///< deprecated, todo remove\n\n    // store the local maximum of the grid - ghosted one\n    type localMaxX[dim]; ///< deprecated, todo remove\n\n    // store the local minimum of grid - ghosted one\n    type localGhostedMinX[dim]; ///< deprecated, todo remove\n\n    // store the local maximum of the grid - ghosted one\n    type localGhostedMaxX[dim]; ///< deprecated, todo remove\n\n    // holds the information about length domains\n    type nodeSpan[dim]; ///< deprecated, todo remove\n\n    // number of level sets on the grid\n    int dof; ///< deprecated, todo remove\n\n    // processor layout in each direction\n    int pm, pn, pp; ///< deprecated, todo remove\n\n\n\n    //========================\n    // Petsc data structures\n    //========================\n\n    // grid associated with this object\n    DM da; ///< internally stored DMDA grid\n\n    // distribution and stuff\n    DMDALocalInfo localInfo; ///< internally stored DMDA grid info, it is somehow redundant to GridData\n\n    // duplicate info for storing type of the boundary (NONE, GHOSTED, MIRRORED, PERIODIC)\n    DMDABoundaryType boundaryType;\n\n\n    //==========================\n    // Private helper function\n    //==========================\n\n    /** Initializes the grid class and prepare Petsc data stuctures\n    *\n    * \\param *minX array containing lower point of the grid\n    * \\param *maxX array containing upper point of the grid\n    * \\param *M    array with number of grid cells in each direction\n    * \\param *NP   array with number of slices in each direction\n    */\n    void init(PetscReal* minX, PetscReal* maxX, PetscInt* M, PetscInt* NP);\n\n    /**\n     * \\brief Friend ostream operator for debug print\n     */\n    template <typename T, int d>\n    friend std::ostream& operator<< (std::ostream& os, const Grid<T, d>& gr);\n\n\npublic:\n\n    GridData gr_layout;\n    int processID, nProcs;\n\n\n    /// Constructor for old interface, utilizes array pointers\n    ///\n    /// \\param *minX array containing lower point of the grid\n    /// \\param *maxX array containing upper point of the grid\n    /// \\param *M    array with number of grid cells in each direction\n    /// \\param *NP   arrat with number of slices in each direction\n    Grid(PetscReal* minX, PetscReal* maxX, PetscInt* M, PetscInt* NP);\n\n\n    /// Constructor for new interface, utilizes Eigen classes\n    ///\n    /// \\param minX array containing lower point of the grid\n    /// \\param maxX array containing upper point of the grid\n    /// \\param M    array with number of grid cells in each direction\n    Grid(const Eigen::Array<type, dim, 1>& minX, const Eigen::Array<type, dim, 1>& maxX, const Eigen::Array<int, dim, 1>& M);\n\n\n    /// Constructor used to create equidistant grids\n    ///\n    /// \\param minX array containing lower point of the grid\n    /// \\param maxX array containing upper point of the grid\n    /// \\param M    number of grid cells in first dimension, the rest is computed accoringly to supply equidistant dx\n    Grid(const Eigen::Array<type, dim, 1>& minX, const Eigen::Array<type, dim, 1>& maxX, int M);\n\n\n    /// Constructor used to create equidistant grids\n    ///\n    /// \\param gridSpan bounding box to set the grid span\n    /// \\param M number of grid cells in each direction\n//  Grid(const Box<type, dim>& gridSpan, int M);\n\n    /// Destructor\n    ~Grid();\n\n    const DMDALocalInfo* getLocalInfo() const;\n\n    const DM getDA() const {return this->da;};\n\n\n    /// returns minimum coordinate of the grid for asked dimension number\n    PetscReal getMin(PetscInt dimNum) const;\n\n    /// returns maximim coordinate of the grid for asked dimension number\n    PetscReal getMax(PetscInt dimNum) const;\n\n    /// return spacing between grid points for asked dimension number\n    PetscReal getDx(PetscInt dimNum) const;\n\n    /// return local minimum coordinate\n    PetscReal getLocalMin(PetscInt dimNum) const;\n\n    /// return local maximum coordinate\n    PetscReal getLocalMax(PetscInt dimNum) const;\n\n    /// returns local ghpsted minimum coordinate of the grid for asked dimension number\n    PetscReal getLocalGhostedMin(PetscInt dimNum) const;\n\n    /// returns local ghosted maximim coordinate of the grid for asked dimension number\n    PetscReal getLocalGhostedMax(PetscInt dimNum)const;\n\n    /// returns a ghosted bounding box for local region covered by this computational node\n    Box<double, 3> getLocalGhostedRegion();\n\n\n    PetscReal getStencilSize() const;\n\n    /// return real world coordinate for given dimension and axis index\n    PetscReal getCoordinate(PetscInt dimNum, PetscInt ind) const;\n\n    /// return linear index from passed matrix indices (linear index is defined in row wise manner)\n    long int getLinearIndex(PetscInt* ind) const;\n\n    /// return linear index from passed matrix indices (linear index is defined in row wise manner)\n    long int getLinearIndex(std::vector<PetscInt> ind) const;\n\n    /// get coordinate from indices\n    inline Eigen::Vector3d getCoord(const Eigen::Vector3i& ind) const;\n\n    /// get coordinate from indices\n    const std::vector<PetscReal> getLocalCoord(std::vector<PetscInt> ind) const;\n\n    /// get local coordinate from indices\n    Eigen::Vector3d getLocalCoord(PetscInt* ind, int procID) const;\n\n    /// get local coordinates from indices\n    const std::vector<PetscReal> getLocalCoord(PetscInt* ind) const;\n\n    long int getNumberOfCells() const;\n\n    long int getNumberOfLocalCells() const;\n\n    PetscInt getM(PetscInt dimNum) const;\n\n    PetscInt getLocalM(PetscInt dimNum) const;\n\n    PetscReal getMaxDist() const;\n\n    /// method that transform coordinate values to indices in the grid. Not sure if this is done in PETSc and\n    Box<PetscInt, dim>& getPointSpan(const std::vector<PetscReal>& coord, Box<PetscInt, dim>& prealloc);\n\n    /// trasfoms coordinate box into indices box\n    Box<PetscInt, dim> getGlobalBoxIndices(const Box<type, dim>& bb) const;\n\n    Box<PetscInt, 3> locateBoxIndices(const Box<PetscReal, 3>& bb);\n\n    int getDataPosition(const type point[dim]);\n\n    std::list<int> getProcessSpan(const Box<double, dim>& indBox) const;\n\n    Box<double, dim> getNodeSpan(int indices[dim]) const;\n\n    Box<double, dim> getNodeSpan() const;\n\n    Box<double, dim> getNodeSpan(int procID) const;\n\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > getNodeBoundaryCells(int procID, int boundaries) const;\n};\n\n\n\n\n\n///==================================\n///         Implementation\n///==================================\n\n\ntemplate <typename type, int dim>\nvoid Grid<type, dim>::init(PetscReal* minX, PetscReal* maxX, PetscInt* M, PetscInt* NP) {\n\n    GridData::createType(&mpi_grid_type);\n\n    PetscErrorCode ierr;\n\n    this->boundaryType = DMDA_BOUNDARY_GHOSTED;\n\n    // values setup for dim > N are ommited\n    for (int i = 0; i < dim; ++i) {\n        this->numberOfGridCells[i] = M[i];\n        this->dx[i]                = (maxX[i] - minX[i])/ (M[i] - 1);\n        this->minX[i]              = minX[i];\n        this->maxX[i]              = maxX[i];\n    }\n\n    this->stencilSize = 1;\n\n    //  this WILL alwasy be 1 because the data is stored in other class\n    //  and changing this would corrupt it all. The petsc way is interleave the data\n    //  this is not exactly what we are going to do.\n    this->dof = 1;\n\n    switch (dim) {\n        case 1:\n            break;\n        case 2:\n            break;\n        case 3:\n            // To make petsc work correctly, we need to convert number of gridcells to number of nodes => M[.] = M[.] + 1\n            ierr = DMDACreate3d(PETSC_COMM_WORLD, boundaryType, boundaryType, boundaryType, DMDA_STENCIL_BOX,\n                                    M[0], M[1], M[2], NP[0], NP[1], NP[2], dof, stencilSize,\n                                    PETSC_NULL, PETSC_NULL, PETSC_NULL, &da);\n            ierr = DMDASetUniformCoordinates(da, minX[0], maxX[0], minX[1], maxX[1], minX[2], maxX[2]);\n\n            // very stupid way to get back the process layout\n            ierr = DMDAGetInfo(da,\n                               PETSC_NULL,\n                               PETSC_NULL, PETSC_NULL, PETSC_NULL,\n                               &pm, &pn, &pp,\n                               PETSC_NULL,\n                               PETSC_NULL,\n                               PETSC_NULL, PETSC_NULL, PETSC_NULL,\n                               PETSC_NULL);\n\n            nodeSpan[0] = (maxX[0] - minX[0]) / (pm);\n            nodeSpan[1] = (maxX[1] - minX[1]) / (pn);\n            nodeSpan[2] = (maxX[2] - minX[2]) / (pp);\n\n            break;\n        default:\n            break;\n    }\n\n    if (PetscUnlikely(ierr)) {\n        // some error handling add lated here :)\n    }\n\n    ierr = DMDAGetLocalInfo(da, &localInfo);\n\n    MPI_Comm_rank(PETSC_COMM_WORLD, &processID);\n    MPI_Comm_size(PETSC_COMM_WORLD, &nProcs);\n\n\n\n\n    // for convenience this part defines local chunks of grid, so user do not need to recompute\n    // it every time he needs it\n    switch (dim) {\n        case 1:\n            break;\n        case 2:\n            break;\n        case 3:\n            localMinX[0]        = minX[0] +  localInfo.xs * dx[0];\n            localMaxX[0]        = minX[0] + (localInfo.xs + localInfo.xm - 1) * dx[0];\n            localGhostedMinX[0] = minX[0] +  localInfo.gxs * dx[0];\n            localGhostedMaxX[0] = minX[0] + (localInfo.gxs + localInfo.gxm - 1) * dx[0];\n\n            localMinX[1]        = minX[1] +  localInfo.ys * dx[1];\n            localMaxX[1]        = minX[1] + (localInfo.ys + localInfo.ym - 1) * dx[1];\n            localGhostedMinX[1] = minX[1] +  localInfo.gys * dx[1];\n            localGhostedMaxX[1] = minX[1] + (localInfo.gys + localInfo.gym - 1) * dx[1];\n\n            localMinX[2]        = minX[2] +  localInfo.zs * dx[2];\n            localMaxX[2]        = minX[2] + (localInfo.zs + localInfo.zm - 1) * dx[2];\n            localGhostedMinX[2] = minX[2] +  localInfo.gzs * dx[2];\n            localGhostedMaxX[2] = minX[2] + (localInfo.gzs + localInfo.gzm -1) * dx[2];\n\n            numberOfGhostedGridCells[0] = localInfo.gxm;\n            numberOfGhostedGridCells[1] = localInfo.gym;\n            numberOfGhostedGridCells[2] = localInfo.gzm;\n\n            break;\n    }\n\n\n    for (int i = 0; i < 3; ++i) {\n\n        gr_layout.lminx[i] = localMinX[i];\n        gr_layout.lmaxx[i] = localMaxX[i];\n        gr_layout.glminx[i] = localGhostedMinX[i];\n        gr_layout.glmaxx[i] = localGhostedMaxX[i];\n\n    }\n\n    gr_layout.glm = localInfo.gxm;\n    gr_layout.gln = localInfo.gym;\n    gr_layout.glp = localInfo.gzm;\n\n    gr_layout.lm  = localInfo.mx;\n    gr_layout.ln  = localInfo.my;\n    gr_layout.lp  = localInfo.mz;\n\n    gr_layout.m   = M[0];\n    gr_layout.n   = M[1];\n    gr_layout.p   = M[2];\n\n    gr_layout.minx[0] = minX[0];\n    gr_layout.minx[1] = minX[1];\n    gr_layout.minx[2] = minX[2];\n\n    gr_layout.maxx[0] = maxX[0];\n    gr_layout.maxx[1] = maxX[1];\n    gr_layout.maxx[2] = maxX[2];\n\n    gr_layout.ghosts = 1;\n\n\n    globalGridLayout = new GridData[nProcs]; // do not forget to delete this little shit\n\n\n    MPI_Allgather(&gr_layout, 1, mpi_grid_type, globalGridLayout, 1, mpi_grid_type, MPI_COMM_WORLD);\n\n    std::stringstream ss;\n    \n    ss << \"====================\" << std::endl;\n    ss << \"procid : \" << processID << std::endl;\n    ss << \"min: \" << gr_layout.glminx[0] << \", \" << gr_layout.glminx[1] << \", \" << gr_layout.glminx[2] << std::endl;\n    ss << \"max: \" << gr_layout.glmaxx[0] << \", \" << gr_layout.glmaxx[1] << \", \" << gr_layout.glmaxx[2] << std::endl;\n    ss << \"====================\" << std::endl;\n     for (int i = 0; i < nProcs; ++i) {\n        ss << \"global proc id : \" << i << std::endl;\n        ss << \"min: \" << globalGridLayout[i].glminx[0] << \", \" << globalGridLayout[i].glminx[1] << \", \" << globalGridLayout[i].glminx[2] << std::endl;\n        ss << \"max: \" << globalGridLayout[i].glmaxx[0] << \", \" << globalGridLayout[i].glmaxx[1] << \", \" << globalGridLayout[i].glmaxx[2] << std::endl;\n     }\n    ss << \"====================\" << std::endl;\n\n    std::string s = ss.str();\n//    PetscSynchronizedPrintf(PETSC_COMM_WORLD, s.c_str());\n //   PetscSynchronizedFlush(PETSC_COMM_WORLD);\n    // create indexing for the data so, because we will need fast acces for inicialization computations\n\n\n\n\n}\n\ntemplate <typename type, int dim>\nGrid<type, dim>::Grid(const Eigen::Array<type, dim, 1>& minX, const Eigen::Array<type, dim, 1>& maxX, const Eigen::Array<int, dim, 1>& M) {\n\n    int            m[3] = {M[0], M[1], M[2]},\n                  np[3] = {0, 0, 0};\n    type         min[3] = {minX[0], minX[1], minX[2]},\n                 max[3] = {maxX[0], maxX[1], maxX[2]};\n\n    init(min, max, m, np);\n\n}\n\ntemplate <typename type, int dim>\nGrid<type, dim>::Grid(const Eigen::Array<type, dim, 1>& minX, const Eigen::Array<type, dim, 1>& maxX, int M) {\n\n    Eigen::Array<type, dim, 1> len   = maxX - minX;\n    Eigen::Array<type, dim, 1> maxX_;   // new maximum size of the grid, possibly expanded a bit\n    Eigen::Array<type, dim, 1> M_float; // stores array with accoring number of cells\n\n    M_float[0] = M;\n\n    type dx = len[0] / (M - 1); // size of one cell on dim = 0\n\n//  std::cout << dx << std::endl;\n\n    M_float[1] = std::ceil( len[1] / dx + 1);\n    M_float[2] = std::ceil( len[2] / dx + 1);\n\n    Eigen::Array<type, dim, 1> newLen = dx * (M_float - 1);\n    Eigen::Array<type, dim, 1> diff   = newLen - len;\n\n    maxX_ = maxX + diff;\n\n    Eigen::Array<int, dim, 1> M_int = M_float.template cast<int>();\n\n//  std::cout << M_int << std::endl;\n\n    int  m[3]   = {M_int[0], M_int[1], M_int[2]},\n         np[3]  = {0, 0, 0};\n    type min[3] = {minX[0], minX[1], minX[2]},\n         max[3] = {maxX_[0], maxX_[1], maxX_[2]};\n\n    init(min, max, m, np);\n\n}\n\ntemplate <typename type, int dim>\nGrid<type, dim>::Grid(PetscReal* minX, PetscReal* maxX, PetscInt* M, PetscInt* NP) {\n    // this constructor version has one huge problem. There is now way of checking if user passed\n    // the inicialized values or just some random stuff.\n\n    init(minX, maxX, M, NP);\n\n}\n\n\n\ntemplate <typename type, int dim>\nGrid<type, dim>::~Grid() {\n    // definitely is nice to clean\n//  std::cout << \"call destructor in grid\" << std::endl;\n    PetscBool finalized;\n    PetscFinalized(&finalized);\n\n    delete [] globalGridLayout;\n\n    if (!finalized) {\n        DMDestroy(&da);\n    } // else I am not really sure what happen, will the object stay hanging?\n    else {\n        std::cout << \"already finalized\" << std::endl;\n    }\n\n}\n\n\n\n// this should be removed !!!!!!!!!!!!!\ntemplate <typename type, int dim>\nconst DMDALocalInfo* Grid<type, dim>::getLocalInfo() const{\n\n    return &localInfo;\n\n}\n\n\n\n//=====================//\n//      Getters        //\n//=====================//\n\ntemplate <typename type, int dim>\ninline PetscReal Grid<type, dim>::getMin(PetscInt dimNum) const {\n    return minX[dimNum];\n}\n\ntemplate <typename type, int dim>\ninline PetscReal Grid<type, dim>::getMax(PetscInt dimNum) const {\n    return maxX[dimNum];\n}\n\ntemplate <typename type, int dim>\ninline PetscReal Grid<type, dim>::getDx(PetscInt dimNum) const {\n    return dx[dimNum];\n}\n\ntemplate <typename type, int dim>\ninline PetscReal Grid<type, dim>::getLocalMin(PetscInt dimNum) const {\n    return localMinX[dimNum];\n}\n\ntemplate <typename type, int dim>\ninline PetscReal Grid<type, dim>::getLocalMax(PetscInt dimNum) const {\n    return localMaxX[dimNum];\n}\n\ntemplate <typename type, int dim>\ninline PetscReal Grid<type, dim>::getLocalGhostedMin(PetscInt dimNum) const {\n    return localGhostedMinX[dimNum];\n}\n\ntemplate <typename type, int dim>\ninline PetscReal Grid<type, dim>::getLocalGhostedMax(PetscInt dimNum) const {\n    return localGhostedMaxX[dimNum];\n}\n\ntemplate <typename type, int dim>\ninline PetscReal Grid<type, dim>::getStencilSize() const {\n    return stencilSize;\n}\n\ntemplate <typename type, int dim>\ninline PetscReal Grid<type, dim>::getCoordinate(PetscInt dimNum, PetscInt ind) const {\n    return localMinX[dimNum] + dx[dimNum]*ind;\n}\n\ntemplate <typename type, int dim>\ninline long int Grid<type, dim>::getLinearIndex(PetscInt* ind) const {\n    if (dim == 2) {\n        return ind[1]*localInfo.gxm + ind[0];\n    } else if (dim == 3) {\n        return ind[2]*localInfo.gxm*localInfo.gym + ind[1]*localInfo.gxm + ind[0];\n    }\n    return -1;\n}\n\ntemplate <typename type, int dim>\ninline long int Grid<type, dim>::getLinearIndex(std::vector<PetscInt> ind) const {\n    if (dim == 2) {\n        return ind[1]*localInfo.gxm + ind[0];\n    } else if (dim == 3) {\n        return ind[2]*localInfo.gxm*localInfo.gym + ind[1]*localInfo.gxm + ind[0];\n    }\n    return -1;\n}\n\ntemplate <typename type, int dim>\ninline Eigen::Vector3d Grid<type, dim>::getCoord(const Eigen::Vector3i& ind) const {\n    Eigen::Vector3d x_lo(minX), x_dx(dx);\n\n    return x_lo + x_dx.cwiseProduct( ind.cast<double>() );\n}\n\n\ntemplate <typename type, int dim>\ninline const std::vector<PetscReal> Grid<type, dim>::getLocalCoord(PetscInt* ind) const {\n    std::vector<PetscReal> coord;\n    for (int i = 0; i < dim; ++i) {\n        coord.push_back( localGhostedMinX[i] + ind[i]*dx[i] );\n    }\n\n    return coord;\n}\n\ntemplate <typename type, int dim>\ninline Eigen::Vector3d Grid<type, dim>::getLocalCoord(PetscInt* ind, int procID) const {\n    Eigen::Vector3d coord;\n    for (int i = 0; i < dim; ++i) {\n        coord[i] = globalGridLayout[procID].glminx[i] + ind[i]*dx[i];\n    }\n\n    return coord;\n}\n\ntemplate <typename type, int dim>\ninline const std::vector<PetscReal> Grid<type, dim>::getLocalCoord(std::vector<PetscInt> ind) const {\n    std::vector<PetscReal> coord;\n    for (int i = 0; i < ind.size(); ++i) {\n        coord.push_back( localGhostedMinX[i] + ind[i]*dx[i] );\n    }\n\n    return coord;\n}\n\ntemplate <typename type, int dim>\ninline long int Grid<type, dim>::getNumberOfCells() const {\n    long int numberOfCells = 1;\n    for (int i = 0; i < dim; ++i) {\n        numberOfCells *= numberOfGridCells[i];\n    }\n    return numberOfCells;\n}\n\ntemplate <typename type, int dim>\ninline long int Grid<type, dim>::getNumberOfLocalCells() const {\n    long int numberOfCells = 1;\n    if (dim >= 1) {\n        numberOfCells *= localInfo.gxm;\n    }\n    if (dim >= 2) {\n        numberOfCells *= localInfo.gym;\n    }\n    if (dim == 3) {\n        numberOfCells *= localInfo.gzm;\n    }\n\n    return numberOfCells;\n}\n\n\ntemplate <typename type, int dim>\ninline PetscInt Grid<type, dim>::getM(PetscInt dimNum) const {\n    return numberOfGridCells[dimNum];\n}\n\n\ntemplate <typename type, int dim>\ninline PetscInt Grid<type, dim>::getLocalM(PetscInt dimNum) const {\n    switch (dimNum) {\n        case 0:\n            return localInfo.gxm;\n            break;\n        case 1:\n            return localInfo.gym;\n            break;\n        case 2:\n            return localInfo.gzm;\n            break;\n        default:\n            return -1;\n            break;\n    }\n}\n\n\ntemplate <typename type, int dim>\ninline Box<double, 3> Grid<type, dim>::getLocalGhostedRegion() {\n\n    return Box<double, 3>(localGhostedMinX, localGhostedMaxX);\n\n}\n\n\ntemplate <typename type, int dim>\ninline PetscReal Grid<type, dim>::getMaxDist() const {\n//  return sqrt( (localGhostedMaxX[0] - localGhostedMinX[0])*(localGhostedMaxX[0] - localGhostedMinX[0]) +\n//               (localGhostedMaxX[1] - localGhostedMinX[1])*(localGhostedMaxX[1] - localGhostedMinX[1]) +\n//               (localGhostedMaxX[2] - localGhostedMinX[2])*(localGhostedMaxX[2] - localGhostedMinX[2])   );\n    return     ( (maxX[0] - minX[0])*(maxX[0] - minX[0]) +\n                 (maxX[1] - minX[1])*(maxX[1] - minX[1]) +\n                 (maxX[2] - minX[2])*(maxX[2] - minX[2])   );\n\n}\n\n\n\ntemplate <typename type, int dim>\nBox<PetscInt, dim>& Grid<type, dim>::getPointSpan(const std::vector<PetscReal>& coord, Box<PetscInt, dim>& prealloc) {\n// method that transform coordinate values to indices in the grid. Not sure if this is done in PETSc and\n// I have no time to go through the doucmentation.\n// TODO: resolve this in future :)\n\n    int       bandSize = 3;\n    int       indRow[dim];\n\n    for (PetscInt i = 0; i < dim; ++i) {\n\n        PetscInt ind = round( (coord[i] - localGhostedMinX[i]) / dx[i] );\n        indRow[i] = ind;\n\n    }\n\n\n    if (dim == 1) {\n// pass\n    } if (dim == 2) {\n// pass\n    } if (dim == 3) {\n\n        int k_low  = (indRow[2] - bandSize) <  0         ? 0                       : (indRow[2] - bandSize);\n        int k_high = (indRow[2] + bandSize) >= localInfo.gzm ? (localInfo.gzm - 1) : (indRow[2] + bandSize);\n\n        int j_low  = (indRow[1] - bandSize) <  0         ? 0                       : (indRow[1] - bandSize);\n        int j_high = (indRow[1] + bandSize) >= localInfo.gym ? (localInfo.gym - 1) : (indRow[1] + bandSize);\n\n        int i_low  = (indRow[0] - bandSize) <  0         ? 0                       : (indRow[0] - bandSize);\n        int i_high = (indRow[0] + bandSize) >= localInfo.gxm ? (localInfo.gxm - 1) : (indRow[0] + bandSize);\n\n\n        int minx[3] = {i_low, j_low, k_low};\n        int maxx[3] = {i_high, j_high, k_high};\n\n        prealloc.updateFromMinMax(minx, maxx);\n\n    }\n\n    return prealloc;\n\n}\n\ntemplate <typename type, int dim>\nBox<PetscInt, dim> Grid<type, dim>::getGlobalBoxIndices(const Box<type, dim>& bb) const {\n    \n    PetscInt padding = 2;\n    PetscInt gMin[dim], gMax[dim];\n\n    for (int i = 0; i < dim; ++i) {\n\n        gMin[i] = floor( (bb.minX(i) - this->minX[i]) / dx[i] ) - padding;\n        gMax[i] = ceil(  (bb.maxX(i) - this->minX[i]) / dx[i] ) + padding;\n\n        gMin[i] = (gMin[i] < 0)                     ? 0                        : gMin[i];\n        gMax[i] = (gMax[i] >= numberOfGridCells[i]) ? (numberOfGridCells[i]-1) : gMax[i];\n\n    }\n\n//  std::cout << \"gmin : \" << gMin[0] << \", \" << gMin[1] << \", \" << gMin[2] << std::endl;\n//  std::cout << \"gmax : \" << gMax[0] << \", \" << gMax[1] << \", \" << gMax[2] << std::endl;\n\n    return Box<PetscInt, dim>(gMin, gMax);\n\n}\n\ntemplate <typename type, int dim>\nBox<PetscInt, 3> Grid<type, dim>::locateBoxIndices(const Box<PetscReal, 3>& bb) {\n    // method that transform coordinate values to indices in the grid. Not sure if this is done in PETSc and\n    // I have no time to go through the documentation.\n    // TODO: resolve this in future :)\n\n    PetscInt padding = 2;\n    PetscInt minx[dim], maxx[dim];\n\n    for (int i = 0; i < dim; ++i) {\n\n        minx[i] = floor( (bb.minX(i) - localGhostedMinX[i]) / dx[i] ) - padding;\n        maxx[i] = ceil(  (bb.maxX(i) - localGhostedMinX[i]) / dx[i] ) + padding;\n\n        minx[i] = (minx[i] < 0)                            ? 0                               : minx[i];\n        maxx[i] = (maxx[i] >= numberOfGhostedGridCells[i]) ? (numberOfGhostedGridCells[i]-1) : maxx[i];\n\n\n    }\n\n    return Box<PetscInt, dim>(minx, maxx);\n\n}\n\n\n// Returns physical position of the data in question\ntemplate <typename type, int dim>\nint Grid<type, dim>::getDataPosition(const type point[dim]) {\n    Eigen::Array<type, dim, 1> x_lo(minX), p(point), span(nodeSpan), x_hi(maxX);\n    Eigen::Array<int, dim, 1> procs;\n\n    procs << 1, pm, pm*pn;\n\n    auto pos_cor = ((p - x_lo) / span).template cast<int>();\n\n    return (pos_cor*procs).sum();\n\n}\n\ntemplate <typename type, int dim>\nstd::list<int> Grid<type, dim>::getProcessSpan(const Box<double, dim>& indBox) const {\n    Eigen::Array<type, dim, 1> x_lo(minX), span(nodeSpan), x_hi(maxX);\n    Eigen::Array<int, dim, 1> procs;\n    std::list<int> processes;\n    double eps = 1E-10; // this is purely local epsilon need to be machine eps\n\n    procs << 1, pm, pm*pn;\n\n    auto pos_cor_bl = ((indBox.bl() - x_lo - eps) / span).template cast<int>();\n    auto pos_cor_tr = ((indBox.tr() - x_lo - eps) / span).template cast<int>();\n\n    for (int k = pos_cor_bl[2]; k <= pos_cor_tr[2]; ++k) {\n        for (int j = pos_cor_bl[1]; j <= pos_cor_tr[1]; ++j) {\n            for (int i = pos_cor_bl[0]; i <= pos_cor_tr[0]; ++i) {\n                processes.push_back( (Eigen::Array3i(i,j,k)*procs).sum() );\n            }\n        }\n    }\n\n    return processes;\n\n}\n\n\ntemplate <typename type, int dim>\nBox<double, dim> Grid<type, dim>::getNodeSpan(int indices[dim]) const {\n\n    Eigen::Array<type, dim, 1> x_lo(minX), span(nodeSpan);\n    Eigen::Array<int, dim, 1> inds(indices);\n\n\n    Eigen::Array<double, dim, 1> c = x_lo + (0.5*span)*(inds+1).template cast<double>();\n    Eigen::Array<double, dim, 1> e = 0.5*span;\n\n\n    return Box<double, 3>( c.data(), e.data() );\n\n}\n\ntemplate <typename type, int dim>\nBox<double, dim> Grid<type, dim>::getNodeSpan() const {\n\n    return Box<double, 3>(globalGridLayout[processID].glminx, globalGridLayout[processID].glmaxx);\n\n}\n\ntemplate <typename type, int dim>\nBox<double, dim> Grid<type, dim>::getNodeSpan(int procID) const {\n    std::stringstream ss;\n    ss << \"ProcID = \" << procID << std::endl;\n    ss << globalGridLayout[procID].glminx[0] << \", \" << globalGridLayout[procID].glminx[1] << \", \" << globalGridLayout[procID].glminx[2] << std::endl;\n    ss << globalGridLayout[procID].glmaxx[0] << \", \" << globalGridLayout[procID].glmaxx[1] << \", \" << globalGridLayout[procID].glmaxx[2] << std::endl;\n    std::string s = ss.str();\n    PetscSynchronizedPrintf(PETSC_COMM_WORLD, s.c_str());\n    PetscSynchronizedFlush(PETSC_COMM_WORLD);\n    return Box<double, 3>(globalGridLayout[procID].glminx, globalGridLayout[procID].glmaxx);\n\n}\n\ntemplate <typename type, int dim>\nstd::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > Grid<type, dim>::getNodeBoundaryCells(int procID, int boundaries) const {\n\n    // std::cout << \"proc: \" << procID << \" , boundaries : \" << boundaries << std::endl;\n\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > cellList;\n    long int reserveSize = (globalGridLayout[procID].glm + globalGridLayout[procID].gln + globalGridLayout[procID].glp) / 3;\n    reserveSize          = reserveSize*reserveSize*4;\n\n    cellList.reserve( reserveSize );\n\n    if ( boundaries & 1 ) {\n        // this means lets initialize left side\n        for (int i = 0; i < globalGridLayout[procID].ghosts; ++i) {\n            for (int j = 0; j < globalGridLayout[procID].gln; ++j) {\n                for (int k = 0; k < globalGridLayout[procID].glp; ++k) {\n\n                    PetscInt inds[dim]    = {i, j, k};\n                    Eigen::Vector3d coord  = getLocalCoord(inds, procID);\n                    cellList.push_back(coord);\n\n                }\n            }\n        }\n    }\n    if ( boundaries & 2 ) {\n        // this means lets initialize right side\n        for (int i = 0; i < globalGridLayout[procID].ghosts; ++i) {\n            for (int j = 0; j < globalGridLayout[procID].gln; ++j) {\n                for (int k = 0; k < globalGridLayout[procID].glp; ++k) {\n\n                    PetscInt inds[dim]    = {( globalGridLayout[procID].glm - 1) - i, j, k};\n                    Eigen::Vector3d coord  = getLocalCoord(inds, procID);\n                    cellList.push_back(coord);\n\n                }\n            }\n        }\n    }\n    if ( boundaries & 4 ) {\n        // this means initialize the bottom side\n        for (int j = 0; j < globalGridLayout[procID].ghosts; ++j) {\n            for (int i = 0; i < globalGridLayout[procID].glm; ++i) {\n                for (int k = 0; k < globalGridLayout[procID].glp; ++k) {\n\n                    PetscInt inds[dim]           = {i, j, k};\n                    Eigen::Vector3d coord = getLocalCoord(inds, procID);\n                    cellList.push_back(coord);\n\n                }\n            }\n        }\n    }\n    if ( boundaries & 8 ) {\n        // this means initialize the top side\n        for (int j = 0; j < globalGridLayout[procID].ghosts; ++j) {\n            for (int i = 0; i < globalGridLayout[procID].glm; ++i) {\n                for (int k = 0; k < globalGridLayout[procID].glp; ++k) {\n\n                    PetscInt inds[dim]           = {i, (globalGridLayout[procID].gln-1) - j, k};\n                    Eigen::Vector3d coord = getLocalCoord(inds, procID);\n                    cellList.push_back(coord);\n\n                }\n            }\n        }\n    }\n    if ( boundaries & 16 ) {\n        // this means initialize the front side\n        for (int k = 0; k < globalGridLayout[procID].ghosts; ++k) {\n            for (int i = 0; i < globalGridLayout[procID].glm; ++i) {\n                for (int j = 0; j < globalGridLayout[procID].gln; ++j) {\n\n                    PetscInt inds[dim]   = {i, j, k};\n                    Eigen::Vector3d coord = getLocalCoord(inds, procID);\n                    cellList.push_back(coord);\n\n\n\n                }\n            }\n        }\n    }\n    if ( boundaries & 32 ) {\n        // this means initialize the far side\n        for (int k = 0; k < globalGridLayout[procID].ghosts; ++k) {\n            for (int i = 0; i < globalGridLayout[procID].glm; ++i) {\n                for (int j = 0; j < globalGridLayout[procID].gln; ++j) {\n\n                    PetscInt inds[dim]           = {i, j, (globalGridLayout[procID].glp-1) - k};\n                    Eigen::Vector3d coord = getLocalCoord(inds, procID);\n                    cellList.push_back(coord);\n\n                }\n            }\n        }\n    }\n\n    return cellList;\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n///////////////////////////////////////\n/// Ostream operator for debug print\n///////////////////////////////////////\n\n\n\n\ntemplate <typename T, int d>\nstd::ostream& operator<< (std::ostream& os, const Grid<T, d>& gr) {\n\n    os << \"Grid info for process: \" << gr.processID << std::endl;\n    os << \"-------------------------------------------------------------------------------------\" << std::endl;\n    if (gr.processID == 0) {\n        os << \"Global grid size: \" << \"X: \" << gr.minX[0] << \" -- \" << gr.maxX[0] << std::endl <<\n              \"                  \" << \"Y: \" << gr.minX[1] << \" -- \" << gr.maxX[1] << std::endl <<\n              \"                  \" << \"Z: \" << gr.minX[2] << \" -- \" << gr.maxX[2] << std::endl <<\n              \"Global number of grid points: \" << \"[X, Y, Z] : [\" << gr.numberOfGridCells[0] << \", \" << gr.numberOfGridCells[1] << \", \" << gr.numberOfGridCells[2] << \"]\" << std::endl <<\n              \"Resolution for the grid is: \" << \"[dx, dy, dz] : [\" << gr.dx[0] << \", \" << gr.dx[1] << \", \" << gr.dx[2] << \"]\" << std::endl;\n        os << \"-------------------------------------------------------------------------------------\" << std::endl;\n    }\n    os <<  \"Local grid size: \" << \"X: \" << gr.localMinX[0] << \" -- \" << gr.localMaxX[0] << std::endl <<\n           \"                 \" << \"Y: \" << gr.localMinX[1] << \" -- \" << gr.localMaxX[1] << std::endl <<\n           \"                 \" << \"Z: \" << gr.localMinX[2] << \" -- \" << gr.localMaxX[2] << std::endl <<\n           \"Local ghosted grid size: \" << \"X: \" << gr.localGhostedMinX[0] << \" -- \" << gr.localGhostedMaxX[0] << std::endl <<\n           \"                         \" << \"Y: \" << gr.localGhostedMinX[1] << \" -- \" << gr.localGhostedMaxX[1] << std::endl <<\n           \"                         \" << \"Z: \" << gr.localGhostedMinX[2] << \" -- \" << gr.localGhostedMaxX[2] << std::endl <<\n           \"Local grid numbering: \" << \"X: \" << gr.localInfo.xs << \" -- \" << gr.localInfo.xs + gr.localInfo.xm - 1 << std::endl <<\n           \"                      \" << \"Y: \" << gr.localInfo.ys << \" -- \" << gr.localInfo.ys + gr.localInfo.ym - 1 << std::endl <<\n           \"                      \" << \"Z: \" << gr.localInfo.zs << \" -- \" << gr.localInfo.zs + gr.localInfo.zm - 1 << std::endl <<\n           \"Local ghosted grid numbering: \" << \"X: \" << gr.localInfo.gxs << \" -- \" << gr.localInfo.gxs + gr.localInfo.gxm - 1 << std::endl <<\n           \"                              \" << \"Y: \" << gr.localInfo.gys << \" -- \" << gr.localInfo.gys + gr.localInfo.gym - 1 << std::endl <<\n           \"                              \" << \"Z: \" << gr.localInfo.gzs << \" -- \" << gr.localInfo.gzs + gr.localInfo.gzm - 1 << std::endl;\n    os << \"-------------------------------------------------------------------------------------\" << std::endl;\n\n    return os;\n\n}\n\n\n\n\n\n\n\n#endif /* GRID_H_ */\n", "meta": {"hexsha": "c53313b715e0ef8ea84a8cef19d9c26fd4de0d6d", "size": 35027, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Grid.hpp", "max_stars_repo_name": "petrkotas/libLS", "max_stars_repo_head_hexsha": "eb57365bfb0be486a4e8c564ff831ad358993268", "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/Grid.hpp", "max_issues_repo_name": "petrkotas/libLS", "max_issues_repo_head_hexsha": "eb57365bfb0be486a4e8c564ff831ad358993268", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grid.hpp", "max_forks_repo_name": "petrkotas/libLS", "max_forks_repo_head_hexsha": "eb57365bfb0be486a4e8c564ff831ad358993268", "max_forks_repo_licenses": ["BSD-3-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.8892018779, "max_line_length": 185, "alphanum_fraction": 0.5737859366, "num_tokens": 9974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.28369912028222705}}
{"text": "// --------------------------------------------------------------------------\n//                   OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2015.\n//\n// This software is released under a three-clause BSD license:\n//  * Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n//  * Redistributions in binary form must reproduce the above copyright\n//    notice, this list of conditions and the following disclaimer in the\n//    documentation and/or other materials provided with the distribution.\n//  * Neither the name of any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\n// --------------------------------------------------------------------------\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: George Rosenberger $\n// $Authors: George Rosenberger, Hannes Roest $\n// --------------------------------------------------------------------------\n\n#include <OpenMS/ANALYSIS/OPENSWATH/MRMRTNormalizer.h>\n#include <OpenMS/MATH/STATISTICS/LinearRegression.h>\n#include <OpenMS/CONCEPT/LogStream.h> // LOG_DEBUG\n#include <OpenMS/MATH/MISC/RANSAC.h> // RANSAC algorithm\n\n#include <numeric>\n#include <boost/math/special_functions/erf.hpp>\n#include <algorithm>\n\nnamespace OpenMS\n{\n\n  std::vector<std::pair<double, double> > MRMRTNormalizer::removeOutliersRANSAC(\n      std::vector<std::pair<double, double> >& pairs, double rsq_limit,\n      double coverage_limit, size_t max_iterations, double max_rt_threshold, size_t sampling_size)\n  {\n    size_t n = sampling_size;\n    size_t k = (size_t)max_iterations;\n    double t = max_rt_threshold*max_rt_threshold;\n    size_t d = (size_t)(coverage_limit*pairs.size());\n\n    if (n < 5)\n    {\n      throw Exception::UnableToFit(__FILE__, __LINE__, __PRETTY_FUNCTION__,\n          \"UnableToFit-LinearRegression-RTNormalizer\", \"WARNING: RANSAC: \" + \n          boost::lexical_cast<std::string>(n) + \" sampled RT peptides is below limit of 5 peptides required for the RANSAC outlier detection algorithm.\");\n    }\n\n    if (pairs.size() < 30)\n    {\n      throw Exception::UnableToFit(__FILE__, __LINE__, __PRETTY_FUNCTION__,\n          \"UnableToFit-LinearRegression-RTNormalizer\", \"WARNING: RANSAC: \" + \n          boost::lexical_cast<std::string>(pairs.size()) + \" input RT peptides is below limit of 30 peptides required for the RANSAC outlier detection algorithm.\");\n    }\n\n    std::vector<std::pair<double, double> > new_pairs = Math::RANSAC::ransac(pairs, n, k, t, d);\n    double bestrsq = Math::RANSAC::llsm_rsq(new_pairs);\n\n    if (bestrsq < rsq_limit)\n    {\n      throw Exception::UnableToFit(__FILE__, __LINE__, __PRETTY_FUNCTION__,\n          \"UnableToFit-LinearRegression-RTNormalizer\", \"WARNING: rsq: \" +\n          boost::lexical_cast<std::string>(bestrsq) + \" is below limit of \" +\n          boost::lexical_cast<std::string>(rsq_limit) +\n          \". Validate assays for RT-peptides and adjust the limit for rsq or coverage.\");\n    }\n\n    if (new_pairs.size() < d)\n    {\n      throw Exception::UnableToFit(__FILE__, __LINE__, __PRETTY_FUNCTION__,\n          \"UnableToFit-LinearRegression-RTNormalizer\", \"WARNING: number of data points: \" +\n          boost::lexical_cast<std::string>(new_pairs.size()) +\n          \" is below limit of \" + boost::lexical_cast<std::string>(d) +\n          \". Validate assays for RT-peptides and adjust the limit for rsq or coverage.\");\n    }\n\n    return new_pairs;\n  }\n\n  int MRMRTNormalizer::jackknifeOutlierCandidate_(std::vector<double>& x, std::vector<double>& y)\n  {\n    // Returns candidate outlier: A linear regression and rsq is calculated for\n    // the data points with one removed pair. The combination resulting in\n    // highest rsq is considered corresponding to the outlier candidate. The\n    // corresponding iterator position is then returned.\n    std::vector<double> x_tmp, y_tmp, rsq_tmp;\n\n    for (Size i = 0; i < x.size(); i++)\n    {\n      x_tmp = x;\n      y_tmp = y;\n      x_tmp.erase(x_tmp.begin() + i);\n      y_tmp.erase(y_tmp.begin() + i);\n\n      Math::LinearRegression lin_reg;\n      lin_reg.computeRegression(0.95, x_tmp.begin(), x_tmp.end(), y_tmp.begin());\n\n      rsq_tmp.push_back(lin_reg.getRSquared());\n    }\n    return max_element(rsq_tmp.begin(), rsq_tmp.end()) - rsq_tmp.begin();\n  }\n\n  int MRMRTNormalizer::residualOutlierCandidate_(std::vector<double>& x, std::vector<double>& y)\n  {\n    // Returns candidate outlier: A linear regression and residuals are calculated for\n    // the data points. The one with highest residual error is selected as the outlier candidate. The\n    // corresponding iterator position is then returned.\n    Math::LinearRegression lin_reg;\n    lin_reg.computeRegression(0.95, x.begin(), x.end(), y.begin());\n\n    std::vector<double> residuals;\n\n    for (Size i = 0; i < x.size(); i++)\n    {\n      double residual = fabs(y[i] - (lin_reg.getIntercept() + (lin_reg.getSlope() * x[i])));\n      residuals.push_back(residual);\n    }\n\n    return max_element(residuals.begin(), residuals.end()) - residuals.begin();\n  }\n\n  std::vector<std::pair<double, double> > MRMRTNormalizer::removeOutliersIterative(\n      std::vector<std::pair<double, double> >& pairs, double rsq_limit,\n      double coverage_limit, bool use_chauvenet, std::string method)\n  {\n    if (pairs.size() < 2)\n    {\n      throw Exception::IllegalArgument(__FILE__, __LINE__, __PRETTY_FUNCTION__,\n        \"Need at least 2 points for the regression.\");\n    }\n\n    // Removes outliers from vector of pairs until upper rsq and lower coverage limits are reached.\n    std::vector<double> x, y;\n    double confidence_interval = 0.95;\n\n    std::vector<std::pair<double, double> > pairs_corrected;\n\n    for (std::vector<std::pair<double, double> >::iterator it = pairs.begin(); it != pairs.end(); ++it)\n    {\n      x.push_back(it->first);\n      y.push_back(it->second);\n      LOG_DEBUG << \"RT Normalization pairs: \" << it->first << \" : \" << it->second << std::endl;\n    }\n\n    double rsq;\n    rsq = 0;\n\n    while (x.size() >= coverage_limit * pairs.size() && rsq < rsq_limit)\n    {\n      Math::LinearRegression lin_reg;\n      lin_reg.computeRegression(confidence_interval, x.begin(), x.end(), y.begin());\n\n      rsq = lin_reg.getRSquared();\n\n      std::cout << \"rsq: \" << rsq << \" points: \" << x.size() << std::endl;\n\n      if (rsq < rsq_limit)\n      {\n        std::vector<double> residuals;\n\n        // calculate residuals\n        for (std::vector<std::pair<double, double> >::iterator it = pairs.begin(); it != pairs.end(); ++it)\n        {\n          double intercept = lin_reg.getIntercept();\n          double slope = (double)lin_reg.getSlope();\n          residuals.push_back(abs(it->second - (intercept + it->first * slope)));\n          LOG_DEBUG << \" RT Normalization residual is \" << residuals.back() << std::endl;\n        }\n\n        int pos;\n\n        if (method == \"iter_jackknife\")\n        {\n          // get candidate outlier: removal of which datapoint results in best rsq?\n          pos = jackknifeOutlierCandidate_(x, y);\n        }\n        else if (method == \"iter_residual\")\n        {\n          // get candidate outlier: removal of datapoint with largest residual?\n          pos = residualOutlierCandidate_(x, y);\n        }\n        else\n        {\n          throw Exception::IllegalArgument(__FILE__, __LINE__, __PRETTY_FUNCTION__,\n            String(\"Method \") + method + \" is not a valid method for removeOutliersIterative\");\n        }\n\n        // remove if residual is an outlier according to Chauvenet's criterion\n        // or if testing is turned off\n        LOG_DEBUG << \" Got outlier candidate \" << pos << \"(\" << x[pos] << \" / \" << y[pos] << std::endl;\n        if (!use_chauvenet || chauvenet(residuals, pos))\n        {\n          x.erase(x.begin() + pos);\n          y.erase(y.begin() + pos);\n        }\n        else\n        {\n          break;\n        }\n      }\n      else\n      {\n        break;\n      }\n    }\n\n    if (rsq < rsq_limit)\n    {\n      // If the rsq is below the limit, this is an indication that something went wrong!\n      throw Exception::UnableToFit(__FILE__, __LINE__, __PRETTY_FUNCTION__,\n          \"UnableToFit-LinearRegression-RTNormalizer\", \"WARNING: rsq: \" +\n          boost::lexical_cast<std::string>(rsq) + \" is below limit of \" +\n          boost::lexical_cast<std::string>(rsq_limit) +\n          \". Validate assays for RT-peptides and adjust the limit for rsq or coverage.\");\n    }\n\n    for (Size i = 0; i < x.size(); i++)\n    {\n      pairs_corrected.push_back(std::make_pair(x[i], y[i]));\n    }\n\n#ifdef DEBUG_MRMRTNORMALIZER\n    std::cout << \"=======STARTPOINTS=======\" << std::endl;\n    for (std::vector<std::pair<double, double> >::iterator it = pairs_corrected.begin(); it != pairs_corrected.end(); ++it)\n    {\n      std::cout << it->first << \"\\t\" << it->second << std::endl;\n    }\n    std::cout << \"=======ENDPOINTS=======\" << std::endl;\n#endif\n\n    return pairs_corrected;\n  }\n\n  bool MRMRTNormalizer::chauvenet(std::vector<double>& residuals, int pos)\n  {\n    double criterion = 1.0 / (2 * residuals.size());\n    double prob = MRMRTNormalizer::chauvenet_probability(residuals, pos);\n\n    LOG_DEBUG << \" Chauvinet testing \" << prob << \" < \" << criterion << std::endl;\n    if (prob < criterion)\n    {\n      return true;\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n  double MRMRTNormalizer::chauvenet_probability(std::vector<double>& residuals, int pos)\n  {\n    double mean = std::accumulate(residuals.begin(), residuals.end(), 0.0) / residuals.size();\n    double stdev = std::sqrt(\n        std::inner_product(residuals.begin(), residuals.end(), residuals.begin(), 0.0\n          ) / residuals.size() - mean * mean);\n\n    double d = fabs(residuals[pos] - mean) / stdev;\n    d /= pow(2.0, 0.5);\n    double prob = boost::math::erfc(d);\n\n    return prob;\n  }\n\n}\n", "meta": {"hexsha": "433569b603f797d221599c0fdafd694ad5928e74", "size": 10985, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openms/source/ANALYSIS/OPENSWATH/MRMRTNormalizer.cpp", "max_stars_repo_name": "tomas-pluskal/openms", "max_stars_repo_head_hexsha": "136ec9057435f6d45d65a8e1465b2a6cff9621a8", "max_stars_repo_licenses": ["Zlib", "Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/openms/source/ANALYSIS/OPENSWATH/MRMRTNormalizer.cpp", "max_issues_repo_name": "tomas-pluskal/openms", "max_issues_repo_head_hexsha": "136ec9057435f6d45d65a8e1465b2a6cff9621a8", "max_issues_repo_licenses": ["Zlib", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/openms/source/ANALYSIS/OPENSWATH/MRMRTNormalizer.cpp", "max_forks_repo_name": "tomas-pluskal/openms", "max_forks_repo_head_hexsha": "136ec9057435f6d45d65a8e1465b2a6cff9621a8", "max_forks_repo_licenses": ["Zlib", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3727598566, "max_line_length": 164, "alphanum_fraction": 0.6273099681, "num_tokens": 2644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6654105454764746, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.28367888344542486}}
{"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_DRGRAPH_HPP\n#define FILECOIN_STORAGE_PROOFS_CORE_DRGRAPH_HPP\n\n#include <boost/graph/directed_graph.hpp>\n\n#include <nil/crypto3/random/chacha.hpp>\n\n#include <nil/crypto3/hash/sha2.hpp>\n#include <nil/crypto3/hash/algorithm/hash.hpp>\n\n#include <nil/filecoin/storage/proofs/core/utilities.hpp>\n#include <nil/filecoin/storage/proofs/core/parameter_cache.hpp>\n\n#include <nil/filecoin/storage/proofs/core/crypto/domain_seed.hpp>\n\nnamespace nil {\n    namespace filecoin {\n        constexpr static const bool PARALLEL_MERKLE = true;\n\n        /// The base degree used for all DRG graphs. One degree from this value is used to ensure that a\n        /// given node always has its immediate predecessor as a parent, thus ensuring unique topological\n        /// ordering of the graph nodes.\n        constexpr static const std::size_t BASE_DEGREE = 6;\n\n        std::array<std::uint8_t, 28> derive_drg_seed(const std::array<std::uint8_t, 32> &porep_id) {\n            std::array<std::uint8_t, 28> drg_seed {};\n            std::array<std::uint8_t, 32> raw_seed = derive_porep_domain_seed(DRSAMPLE_DST, porep_id);\n            std::copy(raw_seed.begin(), raw_seed.begin() + 28, drg_seed.begin());\n            return drg_seed;\n        }\n\n        template<std::size_t Arity>\n        std::size_t graph_height(std::size_t number_of_leafs) {\n            return merkletree::merkle::get_merkle_tree_row_count(number_of_leafs, Arity);\n        }\n\n        /// A depth robust graph.\n        template<typename Hash, typename KeyType>\n        struct Graph {\n            typedef KeyType key_type;\n            typedef Hash hash_type;\n\n            /// Returns the expected size of all nodes in the graph.\n            virtual std::size_t expected_size() const {\n                return size() * NODE_SIZE;\n            }\n\n            /// Returns the merkle tree depth.\n            virtual std::uint64_t merkle_tree_depth() const {\n                return graph_height<PoseidonArity>(size());\n            }\n\n            /// Returns a sorted list of all parents of this node. The parents may be repeated.\n            ///\n            /// If a node doesn't have any parents, then this vector needs to return a vector where\n            /// the first element is the requested node. This will be used as indicator for nodes\n            /// without parents.\n            ///\n            /// The `parents` parameter is used to store the result. This is done fore performance\n            /// reasons, so that the vector can be allocated outside this call.\n            virtual void parents(std::size_t node, std::vector<std::uint32_t> &parents) const = 0;\n\n            /// Returns the size of the graph (number of nodes).\n            virtual std::size_t size() const = 0;\n\n            /// Returns the number of parents of each node in the graph.\n            virtual std::size_t degree() const = 0;\n\n            virtual std::array<std::uint8_t, 28> seed() const = 0;\n\n            /// Creates the encoding key.\n            /// The algorithm for that is `Sha256(id | encodedParentNode1 | encodedParentNode1 | ...)`.\n            virtual key_type create_key(const typename hash_type::digest_type &id, std::size_t node,\n                                        const std::vector<std::uint32_t> &parents,\n                                        const std::vector<std::uint8_t> &parents_data,\n                                        const std::vector<std::uint8_t> &exp_parents_data) = 0;\n        };\n\n        template<typename Hash, typename ParentsHash = crypto3::hashes::sha2<256>>\n        struct BucketGraph : public parameter_set_metadata, public Graph<Hash, typename Hash::digest_type> {\n            typedef typename Graph<Hash, typename Hash::digest_type>::hash_type hash_type;\n            typedef typename Graph<Hash, typename Hash::digest_type>::key_type key_type;\n\n            BucketGraph(size_t nodes, size_t base_degree, size_t expansion_degree,\n                        const std::array<uint8_t, 32> &porep_id) :\n                nodes(nodes),\n                base_degree(base_degree) {\n                BOOST_ASSERT_MSG(expansion_degree == 0, \"Expansion degree must be zero.\");\n\n                // The number of metagraph nodes must be less than `2u64^54` as to not incur rounding errors\n                // when casting metagraph node indexes from `std::uint64_t` to `double` during parent generation.\n                std::size_t m_prime = base_degree - 1;\n                std::size_t n_metagraph_nodes = nodes * m_prime;\n                BOOST_ASSERT_MSG(n_metagraph_nodes <= 1ULL << 54,\n                                 \"The number of metagraph nodes must be precisely castable to `double`\");\n\n                seed = derive_drg_seed(porep_id);\n            }\n\n            virtual size_t expected_size() const override {\n                return Graph<Hash, typename Hash::digest_type>::expected_size();\n            }\n            virtual uint64_t merkle_tree_depth() const override {\n                return Graph<Hash, typename Hash::digest_type>::merkle_tree_depth();\n            }\n            inline virtual void parents(std::size_t node, std::vector<uint32_t> &parents) const override {\n                std::size_t m = degree();\n\n                if (node == 0 || node == 1) {\n                    // There are special cases for the first and second node: the first node self\n                    // references, the second node only references the first node.\n                    // Use the degree of the current graph (`m`) as `parents.len()` might be bigger than\n                    // that (that's the case for Stacked Graph).\n                    for (auto parent = parents.begin(); parent < parents.begin() + m; ++parent) {\n                        *parent = 0;\n                    }\n                } else {\n                    // DRG node indexes are guaranteed to fit within a `u32`.\n                    std::array<std::uint8_t, 32> s32;\n                    boost::copy(seed, s32);\n                    crypto3::detail::pack_to<crypto3::stream_endian::little_octet_big_bit>({node}, seed);\n                    crypto3::random::chacha rng(seed);\n\n                    std::size_t m_prime = m - 1;\n                    // Large sector sizes require that metagraph node indexes are `u64`.\n                    std::size_t metagraph_node = node * m_prime;\n                    std::size_t n_buckets = std::ceil(std::log2(static_cast<double>(metagraph_node)));\n\n                    for (typename std::vector<uint32_t>::iterator parent = parents.begin();\n                         parent < parents.begin() + m_prime;\n                         ++parent) {\n                        std::uint64_t bucket_index = (rng() % n_buckets) + 1;\n                        std::size_t largest_distance_in_bucket = std::min(metagraph_node, 1UL << bucket_index);\n                        std::size_t smallest_distance_in_bucket = std::max(2UL, largest_distance_in_bucket >> 1UL);\n\n                        // Add 1 becuase the number of distances in the bucket is inclusive.\n                        std::size_t n_distances_in_bucket =\n                            largest_distance_in_bucket - smallest_distance_in_bucket + 1;\n\n                        std::size_t distance = smallest_distance_in_bucket + (rng() % n_distances_in_bucket);\n\n                        std::uint32_t metagraph_parent = metagraph_node - distance;\n\n                        // Any metagraph node mapped onto the DRG can be safely cast back to `u32`.\n                        std::uint32_t mapped_parent = (metagraph_parent / m_prime);\n\n                        if (mapped_parent == node) {\n                            *parent = node - 1;\n                        } else {\n                            *parent = mapped_parent;\n                        }\n                    }\n\n                    parents[m_prime] = node - 1;\n                }\n            }\n            virtual size_t size() const override {\n                return 0;\n            }\n            virtual size_t degree() const override {\n                return 0;\n            }\n            virtual key_type create_key(const typename hash_type::digest_type &id, std::size_t node,\n                                        const std::vector<uint32_t> &parents, const std::vector<uint8_t> &parents_data,\n                                        const std::vector<uint8_t> &exp_parents_data) override {\n                using namespace nil::crypto3;\n                accumulator_set<ParentsHash> acc;\n                hash<ParentsHash>(id, acc);\n\n                // The hash is about the parents, hence skip if a node doesn't have any parents\n                if (node != parents[0]) {\n                    for (std::uint32_t parent : parents) {\n                        std::size_t offset = data_at_node_offset(parent);\n                        hash<ParentsHash>(parents_data.begin(), parents_data.begin() + NODE_SIZE, acc);\n                    }\n                }\n\n                typename ParentsHash::digest_type hash = accumulators::extract::hash<ParentsHash>(acc);\n                return bytes_into_fr_repr_safe(hash);\n            }\n\n            virtual std::string identifier() const override {\n                return std::string();\n            }\n            virtual size_t sector_size() const override {\n                return nodes * NODE_SIZE;\n            }\n\n            std::size_t nodes;\n            std::size_t base_degree;\n            std::array<std::uint8_t, 28> seed;\n        };\n    }    // namespace filecoin\n}    // namespace nil\n\n#endif\n", "meta": {"hexsha": "6b5b29b4f68c2fb0f0f0875b2101034e2c53e5d7", "size": 10928, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/storage/include/nil/filecoin/storage/proofs/core/drgraph.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/drgraph.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/drgraph.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": 49.0044843049, "max_line_length": 119, "alphanum_fraction": 0.5770497804, "num_tokens": 2276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.28362128250373736}}
{"text": "/*\nCopyright 2009-2021 Nicolas Colombe\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#pragma once\n\n#include <gen/pattern.hpp>\n#include <core/randomsetwalk.hpp>\n#include <boost/optional.hpp>\n\nnamespace eXl\n{\n  class Random;\n\n  template <unsigned int N>\n  struct NearestPow2;\n\n  template <>\n  struct NearestPow2<1>\n  {\n    static const unsigned int Pow = 1;\n  };\n\n  template <unsigned int N>\n  struct NearestPow2\n  {\n    static const unsigned int Pow = NearestPow2<N / 2>::Pow + 1;\n  };\n\n  template <unsigned int N, unsigned int Size>\n  struct CompactStorage\n  {\n    static const unsigned int ArraySize = (NearestPow2<N>::Pow * Size) / 32 + ((NearestPow2<N>::Pow * Size) % 32 == 0 ? 0 : 1);\n    unsigned int Data[ArraySize];\n\n    void Build(Pattern<unsigned int> const& iSample);\n    void Extract(Pattern<unsigned int>& oSample) const;\n  };\n\n  template <unsigned int N, unsigned int FieldSize, bool UseDictionnary = false>\n  class ConvChains\n  {\n  public:\n\n    static const unsigned int GridSize = FieldSize * FieldSize;\n    typedef CompactStorage<N - 1, GridSize> Storage;\n\n    struct iequal_to : std::binary_function<Storage,Storage, bool>\n    {\n      bool operator()(Storage const& x, Storage const& y) const;\n    };\n\n    struct ihash : std::unary_function<Storage, std::size_t>\n    {\n      std::size_t operator()(Storage const& x) const;\n    };\n\n    ConvChains(bool iToroidal = false) : m_Toroidal(iToroidal) \n    {\n      if(UseDictionnary)\n      {\n        m_Dict.push_back(0xFFFFFFFF);\n        m_RevDict[0xFFFFFFFF] = 0;\n      }\n    }\n\n    ConvChains(Pattern<unsigned int> const& iSample, bool iToroidal = false) : m_Toroidal(iToroidal) \n    { \n      if(UseDictionnary)\n      {\n        m_Dict.push_back(0xFFFFFFFF);\n        m_RevDict[0xFFFFFFFF] = 0;\n      }\n      AddPattern(iSample); \n    }\n\n    void AddPattern(Pattern<unsigned int> const& iSample, bool iRotateSym = true);\n\n    void Generate(Pattern<unsigned int>& ioResult, Random& iRand, float iTemperature, int iIterations, bool iInitRand = false, Pattern<float> const* iTemp = nullptr);\n\n    void Evaluate(Pattern<unsigned int> const& iPattern, Vector<double>& oRef, Vector<double>& oScore, bool iRotateSym = true) const;\n    \n    struct PatternInfo\n    {\n      uint32_t weight = 0;\n      bool isBorder = false;\n    };\n\n    typedef UnorderedMap<Storage, PatternInfo, ihash, iequal_to> WeightsMap;\n\n\n    struct WaveState\n    {\n      struct CellState\n      { \n        Vector<uint32_t> comp[4];\n        Vector<bool> possible;\n\n        int sumOfOnes;\n        float sumOfWeights;\n        float sumOfWeightsLogWeight;\n        float entropy;\n      };\n\n      bool Outside(Vector2i& ioPos)\n      {\n        auto const& wkAreaSize = m_State.GetSize();\n\n        if(m_Toroidal)\n        {\n          Vector2i coord((ioPos.X() + wkAreaSize.X()) % wkAreaSize.X(), \n            (ioPos.Y() + wkAreaSize.Y()) % wkAreaSize.Y());\n          ioPos = coord;\n          return false;\n        }\n        else\n        {\n          if(ioPos.X() < 0 || ioPos.X() >= (wkAreaSize.X() /*- FieldSize*/)\n          || ioPos.Y() < 0 || ioPos.Y() >= (wkAreaSize.Y() /*- FieldSize*/))\n          {\n            return true;\n          }\n          return false;\n        }\n      }\n\n      void InitPropagator()\n      {\n        auto agrees = [](Pattern<uint32_t> const& iP1, Pattern<uint32_t> const& iP2, int dx, int dy)\n        {\n          int xmin = dx < 0 ? 0 : dx;\n          int xmax = dx < 0 ? dx + FieldSize : FieldSize;\n          int ymin = dy < 0 ? 0 : dy;\n          int ymax = dy < 0 ? dy + FieldSize : FieldSize;\n          for (int y = ymin; y < ymax; y++) \n          {\n            for (int x = xmin; x < xmax; x++) \n            {\n              if (iP1[Vector2i(x, y)] != iP2[Vector2i(x - dx, (y - dy))]) \n              {\n                return false;\n              }\n            }\n          }\n          return true;\n        };\n\n        int DX[4] = {1, -1, 0, 0};\n        int DY[4] = {0, 0, 1, -1};\n\n        Vector<Pattern<uint32_t>> extracted(numSymbols, Pattern<uint32_t> (Vector2i(FieldSize, FieldSize)));\n\n        for (int sym = 0; sym < numSymbols; ++sym)\n        {\n          m_PatternDict[sym]->first.Extract(extracted[sym]);\n        }\n\n        for (int d = 0; d < 4; d++)\n        {\n          for (int sym = 0; sym < numSymbols; ++sym)\n          {\n            Pattern<uint32_t> const& p1 = extracted[sym];\n            //List<int> list = new List<int>();\n            Vector<uint32_t> list;\n            uint32_t count = 0;\n            for (int sym2 = 0; sym2 < numSymbols; ++sym2) \n            {\n              Pattern<uint32_t> const& p2 = extracted[sym2];\n\n              if (agrees(p1, p2, DX[d], DY[d]))\n              {\n                ++count;\n                list.push_back(sym2);\n              }\n            }\n            //propagator[d][t] = new int[list.Count];\n            //for (int c = 0; c < list.Count; c++) \n            //{\n            //  propagator[d][t][c] = list[c];\n            //}\n            m_Propagator[d][sym] = std::move(list);\n          }\n        }\n      }\n\n\n      void Init(ConvChains const& iMem, Vector2i const& iSize)\n      {\n        m_Toroidal = iMem.m_Toroidal;\n\n        numSymbols = iMem.m_WeightsMap.size();\n\n        CellState defaultCell;\n        defaultCell.possible.resize(numSymbols, true);\n        for(uint32_t i = 0; i<4; ++i)\n        {\n          defaultCell.comp[i].resize(numSymbols, 0);\n          m_Propagator[i].resize(numSymbols);\n        }\n\n\n        m_State.SetSize(iSize, defaultCell);\n        m_CollapsedState.SetSize(iSize, numSymbols);\n\n      \n        for(auto iter = iMem.m_WeightsMap.begin(); iter != iMem.m_WeightsMap.end(); ++iter)\n        {\n          m_PatternDict.push_back(iter);\n\n          m_SumOfWeights += iter->second.weight;\n          m_WeightLogWeights.push_back(iter->second.weight * log(iter->second.weight));\n          m_SumOfWeightLogWeights += m_WeightLogWeights.back();\n        }\n\n        InitPropagator();\n\n        m_StartingEntropy = log(m_SumOfWeights) - m_SumOfWeightLogWeights / m_SumOfWeights;\n\n      }\n\n      boost::optional<bool> Observe(Random& iRand)\n      {\n        uint32_t const stateSize = m_State.GetSize().X() * m_State.GetSize().Y();\n\n        float min = 1.0e3;\n        int argmin = -1;\n        Vector2i selectedPos;\n        uint32_t offset = 0;\n        for (int y = 0; y < m_State.GetSize().Y(); ++y)\n        {\n          for (int x = 0; x < m_State.GetSize().X(); ++x)\n          {\n            if (Outside(Vector2i(x, y)))\n            {\n              ++offset;\n              continue;\n            }\n\n            auto const& cellState = m_State[offset];\n\n            int amount = cellState.sumOfOnes;\n\n            if (amount == 0) \n            {\n              return false;\n            }\n\n            float entropy = cellState.entropy;\n            if (amount > 1 && entropy <= min)\n            {\n              double noise = 1.0e-11 * (iRand() % 10000);\n              if (entropy + noise < min)\n              {\n                min = entropy + noise;\n                selectedPos = Vector2i(x, y);\n                argmin = offset;\n              }\n            }\n            ++offset;\n          }\n        }\n\n        //if (argmin == -1)\n        {\n          for (int i = 0; i < stateSize; ++i) \n          {\n            for (int sym = 0; sym < numSymbols; ++sym) \n            {\n              if (m_State.GetBitmap()[i].possible[sym]) \n              { \n                m_CollapsedState.GetBitmap()[i] = sym; \n                break; \n              }\n            }\n          }\n          if (argmin == -1)\n          {\n            return true;\n          }\n        }\n\n        float distTotSum = 0;\n        Multimap<float, uint32_t> distribution;\n        for (int sym = 0; sym < numSymbols; sym++)\n        {\n          if(m_State.GetBitmap()[argmin].possible[sym])\n          {\n            distribution.insert(std::make_pair(m_PatternDict[sym]->second.weight, sym));\n            distTotSum += m_PatternDict[sym]->second.weight;\n          }\n        }\n\n        eXl_ASSERT(!distribution.empty());\n\n        uint32_t selectedSym = distribution.begin()->second;\n        //int r = distribution.Random(random.NextDouble());\n        float val = (float(iRand() % 1000) / 1000.0) * distTotSum;\n        for(auto revIter = distribution.rbegin(); revIter != distribution.rend(); ++revIter)\n        {\n          if(revIter->first > val)\n          {\n            selectedSym = revIter->second;\n            break;\n          }\n          else\n          {\n            val -= revIter->first;\n          }\n        }\n\n        auto const& possibilities = m_State.GetBitmap()[argmin].possible;\n        for (int sym = 0; sym < numSymbols; sym++)\n        {\n          if (possibilities[sym] != (sym == selectedSym)) \n          {\n            Ban(selectedPos, sym);\n          }\n        }\n\n        return boost::none;\n      }\n\n      void Ban(Vector2i pos, uint32_t sym)\n      {\n        auto& cellState = m_State[pos];\n        cellState.possible[sym] = false;\n        \n        for (int dir = 0; dir < 4; dir++)\n        {\n          cellState.comp[dir][sym] = 0;\n        }\n\n        m_Stack.push_back(std::make_pair(pos, sym));\n\n        cellState.sumOfOnes -= 1;\n        if(cellState.sumOfOnes == 0)\n        {\n          printf(\"Termination reached at (%i,%i)\", pos.X(), pos.Y());\n        }\n        cellState.sumOfWeights -= m_PatternDict[sym]->second.weight;\n        cellState.sumOfWeightsLogWeight -= m_WeightLogWeights[sym];\n\n        float sum = cellState.sumOfWeights;\n        cellState.entropy = log(sum) - cellState.sumOfWeightsLogWeight / sum;\n      }\n\n      void Propagate()\n      {\n        while (!m_Stack.empty())\n        {\n          auto cell = m_Stack.back();\n          m_Stack.pop_back();\n\n          Vector2i const& pos = cell.first;\n\n          uint32_t const& sym = cell.second;\n\n          for (int dim = 0; dim < 2; ++dim)\n          {\n            for (int signIdx = 0; signIdx < 2; ++signIdx)\n            {\n              Vector2i otherPos = pos;\n              otherPos.m_Data[dim] += 1 - 2*signIdx;\n\n              if(Outside(otherPos))\n              {\n                continue;\n              }\n              else\n              {\n                //int i2 = x2 + y2 * FMX;\n\n                uint32_t dirIdx = dim * 2 + signIdx;\n\n                auto& p = m_Propagator[dirIdx][sym];\n\n                CellState& otherCell = m_State[otherPos];\n\n                for (uint32_t otherSym : p)\n                {\n                  uint32_t& comp = otherCell.comp[dirIdx][otherSym];\n\n                  comp--;\n\n                  if (comp == 0)\n                  {\n                    Ban(otherPos, otherSym);\n                  }\n                }\n              }\n            }\n          }\n        }\n      }\n\n      void Clear()\n      {\n        uint32_t localOffset = 0;\n        for (int y = 0; y < m_State.GetSize().Y(); ++y)\n        {\n          for (int x = 0; x < m_State.GetSize().X(); ++x)\n          {\n            CellState& state = m_State.GetBitmap()[localOffset];\n\n            for (int sym = 0; sym < numSymbols; ++sym)\n            {\n              state.possible[sym] = true;\n\n              for (int d = 0; d < 4; d++)\n              {\n                state.comp[d][sym] = state.possible[sym] ? m_Propagator[s_Opposite[d]][sym].size() : 0;\n              }\n\n            }\n\n            state.sumOfOnes = numSymbols;\n            state.sumOfWeights = m_SumOfWeights;\n            state.sumOfWeightsLogWeight = m_SumOfWeightLogWeights;\n            state.entropy = m_StartingEntropy;\n\n            ++localOffset;\n          }\n        }\n        if(!m_Toroidal)\n        {\n          for (int y = 0; y < (int)m_State.GetSize().Y() - FieldSize; ++y)\n          {\n            for (int x = 0; x < (int)m_State.GetSize().X() - FieldSize; ++x)\n            {\n              for (int sym = 0; sym < numSymbols; ++sym)\n              {\n                if(m_PatternDict[sym]->second.isBorder)\n                {\n                  Ban(Vector2i(x,y), sym);\n                }\n              }\n            }\n          }\n          Propagate();\n        }\n      }\n\n      uint32_t s_Opposite[4] = {1, 0, 3, 2};\n\n      Vector<Vector<uint32_t>> m_Propagator[4];\n\n      Pattern<CellState> m_State;\n      Pattern<uint32_t> m_CollapsedState;\n\n      Vector<double> m_WeightLogWeights;\n\n      uint32_t numSymbols;\n      bool m_Toroidal;\n      \n      float m_SumOfWeights = 0;\n      float m_SumOfWeightLogWeights = 0;\n      float m_StartingEntropy = 0;\n\n      uint32_t m_RestartCounter = 0;\n\n      Vector<typename WeightsMap::const_iterator> m_PatternDict;\n      Vector<std::pair<Vector2i, uint32_t>> m_Stack;\n    };\n\n    void Wave(Pattern<unsigned int>& ioResult, Random& iRand, uint32_t numIter, WaveState& ioState, bool iInit = false)\n    {\n      if(iInit)\n      {\n        ioState.Clear();\n      }\n\n      eXl_ASSERT(ioResult.GetSize() == ioState.m_State.GetSize());\n\n      for (uint32_t l = 0; l < numIter; l++)\n      {\n        auto result = ioState.Observe(iRand);\n        if (!result)\n        {\n          ioState.Propagate();\n        }\n        else if(!result.get())\n        {\n          ioState.Clear();\n          ioState.m_RestartCounter++;\n          printf(\"Restarted %i \\n\", ioState.m_RestartCounter);\n        }\n      }\n\n      uint32_t globOffset = 0;\n      for (int y = 0; y < ioState.m_State.GetSize().Y(); ++y)\n      {\n        for (int x = 0; x < ioState.m_State.GetSize().X(); ++x)\n        {\n          Vector2i curPos(x,y);\n\n          uint32_t sym = ioState.m_CollapsedState.GetBitmap()[globOffset];\n          if(sym != ioState.numSymbols)\n          {\n            Pattern<uint32_t> pattern(Vector2i(FieldSize, FieldSize));\n            ioState.m_PatternDict[sym]->first.Extract(pattern);\n            //ioResult[curPos] = m_Dict[pattern[Vector2i::ZERO]];\n            for (int ly = 0; ly < FieldSize; ++ly) \n            {\n              for (int lx = 0; lx < FieldSize; ++lx) \n              {\n                Vector2i localPos(lx, ly);\n                Vector2i otherPos = curPos;\n                otherPos += Vector2i (lx, ly);\n                if(otherPos.X() >=0 && otherPos.X() < ioState.m_State.GetSize().X()\n                && otherPos.Y() >=0 && otherPos.Y() < ioState.m_State.GetSize().Y())\n                {\n                  ioResult[otherPos] = m_Dict[pattern[localPos]];\n                }\n              }\n            }\n          }\n\n          ++globOffset;\n        }\n      }\n\n      //return true;\n    }\n\n    Image GetPatternImage()\n    {\n      uint32_t dimX = Mathf::Round(sqrt(m_WeightsMap.size()));\n      uint32_t dimY = m_WeightsMap.size() / dimX;\n      if(m_WeightsMap.size() % dimX != 0)\n      {\n        ++dimX;\n      }\n\n      Image::Size imageSize(dimX * (FieldSize + 1) - 1, dimY * (FieldSize + 1) - 1);\n\n      Vector<WeightsMap::iterator> patternDict;\n      Multimap<uint32_t, uint32_t> patternSort;\n      \n      for(auto iter = m_WeightsMap.begin(); iter != m_WeightsMap.end(); ++iter)\n      {\n        patternDict.push_back(iter);\n        patternSort.insert(std::make_pair(iter->second.weight, patternDict.size() - 1));\n      }\n\n      Image outImg(nullptr, imageSize, Image::RGBA, Image::Char, 1);\n      memset(outImg.GetImageData(), 0, outImg.GetByteSize());\n\n      Vector2i curPos;\n\n      Pattern<uint32_t> pattern(Vector2i::ONE * FieldSize);\n      for(auto rIter = patternSort.rbegin(); rIter != patternSort.rend(); ++rIter)\n      {\n        patternDict[rIter->second]->first.Extract(pattern);\n\n        for(uint32_t y = 0; y<FieldSize; ++y)\n        {\n          for(uint32_t x = 0; x<FieldSize; ++x)\n          {\n            Vector2i locPos(x,y);\n            Vector2i globPos = curPos + locPos;\n            *((uint32_t*)outImg.GetPixel(globPos.Y(), globPos.X())) = pattern[locPos] == 1 ? 0 : 0xFFFFFFFF;\n          }\n        }\n\n        if(curPos.X() + FieldSize < imageSize.X())\n        {\n          curPos.X() += FieldSize + 1;\n        }\n        else\n        {\n          curPos.X() = 0;\n          curPos.Y() += FieldSize + 1;\n        }\n      }\n\n      return outImg;\n    }\n\n  protected:\n\n    Vector<unsigned int> m_TempBuffer;\n\n    WeightsMap m_WeightsMap;\n\n    void _AddPattern(Pattern<unsigned int> const& iSample, bool iRotateSym);\n    \n    unsigned int GetValue(unsigned int iOldValue, Random& iRand);\n\n    void ComputePatternReceptor(Pattern<unsigned int>& oPattern, Pattern<unsigned int> const& iSample, Vector2i const& iCoord) const;\n\n    typename WeightsMap::iterator ComputeReceptorIndex(Pattern<unsigned int> const& iReceptor, bool iCreate);\n\n    typename WeightsMap::iterator ComputeReceptorIndex(Pattern<unsigned int> const& iReceptor) const;\n\n    double ComputeEnergy(Pattern<unsigned int>& temp, Pattern<unsigned int> const& iSample, Vector2i const& iCoord);\n    \n    Vector<unsigned int> m_Dict;\n    Map<unsigned int, unsigned int> m_RevDict;\n    bool m_Toroidal;\n\n  };\n\n#include <gen/convchains.inl>\n\n}", "meta": {"hexsha": "f4c486aa8adf26fb147fe17dee8d49d3e13000e4", "size": 17742, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/gen/convchains.hpp", "max_stars_repo_name": "eXl-Nic/eXl", "max_stars_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_stars_repo_licenses": ["MIT"], "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/gen/convchains.hpp", "max_issues_repo_name": "eXl-Nic/eXl", "max_issues_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_issues_repo_licenses": ["MIT"], "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/gen/convchains.hpp", "max_forks_repo_name": "eXl-Nic/eXl", "max_forks_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_forks_repo_licenses": ["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.0376432079, "max_line_length": 460, "alphanum_fraction": 0.5300417089, "num_tokens": 4575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.28356581563841254}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\r\n/*   Files: mpi_main.cpp clusters.cpp  clusters.h utils.h utils.cpp          */\r\n/*   \t\t\tdbscan.cpp dbscan.h kdtree2.cpp kdtree2.hpp          */\r\n/*\t\t\tgeometric_partitioning.h geometric_partitioning.cpp  */\r\n/*\t\t    \t\t\t\t\t\t             */\r\n/*   Description: an mpi implementation of dbscan clustering algorithm       */\r\n/*\t\t\t\tusing the disjoint set data structure        */\r\n/*                                                                           */\r\n/*   Author:  Md. Mostofa Ali Patwary                                        */\r\n/*            EECS Department, Northwestern University                       */\r\n/*            email: mpatwary@eecs.northwestern.edu                          */\r\n/*                                                                           */\r\n/*   Copyright, 2012, Northwestern University                                */\r\n/*   See COPYRIGHT notice in top-level directory.                            */\r\n/*                                                                           */\r\n/*   Please cite the following publication if you use this package \t     */\r\n/* \t\t\t\t\t\t\t\t\t     */\r\n/*   Md. Mostofa Ali Patwary, Diana Palsetia, Ankit Agrawal, Wei-keng Liao,  */\r\n/*   Fredrik Manne, and Alok Choudhary, \"A New Scalable Parallel DBSCAN      */\r\n/*   Algorithm Using the Disjoint Set Data Structure\", Proceedings of the    */\r\n/*   International Conference on High Performance Computing, Networking,     */\r\n/*   Storage and Analysis (Supercomputing, SC'12), pp.62:1-62:11, 2012.\t     */\r\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\r\n\r\n#include \"geometric_partitioning.h\"\r\n//#include <boost/foreach.hpp>\r\n\r\nnamespace NWUClustering\r\n{\r\n\tvoid get_extra_points(ClusteringAlgo& dbs)\r\n\t{\r\n\t\t#ifdef _DEBUG_GP\r\n\t\tMPI_Barrier(MPI_COMM_WORLD);\r\n\t\tdouble end, start = MPI_Wtime();\r\n\t\t#endif\r\n\r\n\t\tint k, rank, nproc, i, j;\r\n        \tMPI_Comm_rank(MPI_COMM_WORLD, &rank);\r\n        \tMPI_Comm_size(MPI_COMM_WORLD, &nproc);\r\n\r\n        \t#ifdef _DEBUG\r\n        \tif(rank == proc_of_interest) cout << \"extra point time part 0 strating \" << endl;\r\n        \t#endif\r\n\t\t\r\n\t\tinterval* local_box = new interval[dbs.m_pts->m_i_dims];\r\n\t\tcompute_local_bounding_box(dbs, local_box);\r\n\r\n\t\t// extend the box\r\n\t\t//cout << \"proc \" << rank << \" org: upper \"<< local_box[0].upper << \" lower \" << local_box[0].lower << endl;\r\n\t\tfloat eps = sqrt(dbs.m_epsSquare);\r\n\r\n\t\tfor(i = 0; i < dbs.m_pts->m_i_dims; i++)\r\n\t\t{\r\n\t\t\tlocal_box[i].upper += eps;\r\n\t\t\tlocal_box[i].lower -= eps; \r\n\t\t}\r\n\r\n\t\t//cout << \"proc \" << rank << \" ext: upper \"<< local_box[0].upper << \" lower \" << local_box[0].lower << endl;\t\r\n\t\r\n\t\t// all together all the extending bounding box\r\n\t\tinterval* gather_local_box = new interval[dbs.m_pts->m_i_dims * nproc];\r\n\r\n        \t// gather the local bounding box first\r\n        \tMPI_Allgather(local_box, sizeof(interval) * dbs.m_pts->m_i_dims, MPI_BYTE, gather_local_box,\r\n        \t\t\t\t\t\tsizeof(interval) * dbs.m_pts->m_i_dims, MPI_BYTE, MPI_COMM_WORLD);\r\n\r\n\t\t/*#ifdef _DEBUG_GP\r\n\t\tif(rank == proc_of_interest)\r\n\t\t{\r\n\t\t\tfor(i = 0; i < dbs.m_pts->m_i_dims * nproc; i++)\r\n\t\t\t{\r\n\t\t\t\t\tif(i % dbs.m_pts->m_i_dims == 0)\r\n\t\t\t\t\t\tcout << \"\\nproc \" << i / dbs.m_pts->m_i_dims << \" bbox: \";\r\n\t\t\t\t\t\r\n\t\t\t\t\tif(i % dbs.m_pts->m_i_dims == dbs.m_pts->m_i_dims - 1)\r\n                \t\tcout << \"(\" << gather_local_box[i].upper << \", \" << gather_local_box[i].lower << \")\";\r\n            \t\telse\r\n                \t\tcout << \"(\" << gather_local_box[i].upper << \", \" << gather_local_box[i].lower << \"), \";\t\t\t\t\r\n\t\t\t}\r\n\t\t\tcout << endl;\r\n\t\t}\r\n\t\t#endif\r\n\t\t*/\r\n\r\n\t\tbool if_inside, overlap;\r\n\t\tint count = 0, gcount;\r\n\r\n\t\tvector <float> empty;\r\n\t\tvector <vector <float> > send_buf;\r\n\t\tvector <vector <float> > recv_buf;\r\n\t\tsend_buf.resize(nproc, empty);\r\n\t\trecv_buf.resize(nproc, empty);\r\n\r\n\t        vector <int> empty_i;\r\n        \tvector <vector <int> > send_buf_ind;\r\n        \tvector <vector <int> > recv_buf_ind;\r\n        \tsend_buf_ind.resize(nproc, empty_i);\r\n        \trecv_buf_ind.resize(nproc, empty_i);\r\n\r\n\t\t#ifdef _DEBUG_GP\r\n\t\tMPI_Barrier(MPI_COMM_WORLD);\r\n\t\tend = MPI_Wtime();\r\n\t\t#ifdef _DEBUG\r\n\t\tif(rank == proc_of_interest) cout << \"extra point time part 1: \" << end - start << endl;\t\r\n\t\t#endif\r\n\t\tstart = end;\r\n\t\t#endif\r\n\r\n\t\tfor(k = 0; k < nproc; k++)\r\n\t\t{\r\n\t\t\tif(k == rank) // self\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\t// check the two extended bounding box of proc rank and k. If they don't overlap, there must be no points \r\n\t\t\t// SHOULD SUBTRACT EPS\t\t\t\r\n\r\n\t\t\toverlap = true;\r\n\t\t\tfor(j = 0; j < dbs.m_pts->m_i_dims; j++)\r\n\t\t\t{\r\n\t\t\t\tif(gather_local_box[rank * dbs.m_pts->m_i_dims + j].lower < gather_local_box[k * dbs.m_pts->m_i_dims +j].lower)\r\n\t\t\t\t{\r\n\t\t\t\t\t//if(gather_local_box[rank * dbs.m_pts->m_i_dims + j].upper < gather_local_box[k * dbs.m_pts->m_i_dims + j].lower)\r\n\t\t\t\t\tif(gather_local_box[rank * dbs.m_pts->m_i_dims + j].upper - gather_local_box[k * dbs.m_pts->m_i_dims + j].lower < eps)\t\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\toverlap = false;\r\n\t                    \t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n                    \t\t\t//if(gather_local_box[k * dbs.m_pts->m_i_dims + j].upper < gather_local_box[rank * dbs.m_pts->m_i_dims + j].lower)\r\n                    \t\t\tif(gather_local_box[k * dbs.m_pts->m_i_dims + j].upper - gather_local_box[rank * dbs.m_pts->m_i_dims + j].lower < eps)\r\n\t\t\t\t\t{\r\n                        \t\t\toverlap = false;\r\n                        \t\t\tbreak;\r\n                    \t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t// the two bouding boxes are different, so continue to the next processors\r\n\t\t\tif(overlap == false)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\t// get the overlapping regions\r\n\t\t\tfor(i = 0; i < dbs.m_pts->m_i_num_points; i++)\r\n\t\t\t{\r\n\t\t\t\tif_inside = true;\r\n\t\t\t\tfor(j = 0; j < dbs.m_pts->m_i_dims; j++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif(dbs.m_pts->m_points[i][j] < gather_local_box[k * dbs.m_pts->m_i_dims + j].lower || \r\n\t\t\t\t\t\tdbs.m_pts->m_points[i][j] > gather_local_box[k * dbs.m_pts->m_i_dims + j].upper)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif_inside = false;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif(if_inside == true)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor(j = 0; j < dbs.m_pts->m_i_dims; j++)\r\n\t\t\t\t\t\tsend_buf[k].push_back(dbs.m_pts->m_points[i][j]);\r\n\t\t\t\t\t\r\n\t\t\t\t\tsend_buf_ind[k].push_back(i);\r\n\t\t\t\t\tcount++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n        \t#ifdef _DEBUG_GP\r\n\t\tMPI_Barrier(MPI_COMM_WORLD);\r\n        \tend = MPI_Wtime();\r\n        \t#ifdef _DEBUG\r\n        \tif(rank == proc_of_interest) cout << \"extra point time part 2: \" << end - start << endl;        \r\n        \t#endif\r\n        \tstart = end;\r\n        \t#endif\r\n\r\n\t\t// now send buf have all the points. Send the size first to everyone\r\n\t\tvector <int> send_buf_size, recv_buf_size;\r\n\t\tsend_buf_size.resize(nproc, 0);\r\n\t\trecv_buf_size.resize(nproc, 0);\r\n\r\n\t\t\r\n\t\t/*int tid, irecv[nproc], isend[nproc];\r\n\t\tMPI_Request s_req_recv[nproc], s_req_send[nproc], d_req_send[nproc], d_req_recv[nproc]; // better to malloc the memory\r\n        MPI_Status  s_stat, d_stat_send[nproc], d_stat;\r\n\r\n\t\tdouble start, stop;\r\n\t    MPI_Barrier(MPI_COMM_WORLD);\r\n        start = MPI_Wtime();\r\n\r\n        for(tid = 0; tid < nproc; tid++)\r\n        \tMPI_Irecv(&irecv[tid], 1, MPI_INT, tid, 1000, MPI_COMM_WORLD, &s_req_recv[tid]);\r\n\r\n        //int scount = 0, pos;\r\n        int pos;\r\n        for(tid = 0; tid < nproc; tid++)\r\n        {\t\r\n\t\t\tisend[tid] = send_buf[tid].size();\r\n            MPI_Isend(&isend[tid], 1, MPI_INT, tid, 1000, MPI_COMM_WORLD, &s_req_send[tid]);\r\n       \t} \r\n\r\n        for(tid = 0; tid < nproc; tid++)\r\n        {\r\n                MPI_Waitany(nproc, &s_req_recv[0], &pos, &s_stat);\r\n\t\t}\r\n\r\n\t\tMPI_Barrier(MPI_COMM_WORLD);\r\n\r\n\t\tif(rank == proc_of_interest) \r\n\t\t{\r\n\t\t    stop = MPI_Wtime();\r\n\t\t\tcout << \"Size sending time ISIR \" << stop - start << endl;\r\n\t\t}\r\n\r\n\t\tMPI_Barrier(MPI_COMM_WORLD);\r\n\t\tstart = MPI_Wtime();\r\n\t\t*/\r\n\r\n\t\tfor(i = 0; i < nproc; i++)\r\n\t\t\tsend_buf_size[i] = send_buf[i].size();\r\n\t\r\n\t\tMPI_Alltoall(&send_buf_size[0], 1, MPI_INT, &recv_buf_size[0], 1, MPI_INT, MPI_COMM_WORLD);\r\n\t\t/*MPI_Barrier(MPI_COMM_WORLD);\r\n\r\n\t\t#ifdef _DEBUG\r\n\t\tif(rank == proc_of_interest) cout << \"Size sending time AtA \" << MPI_Wtime() - start << endl;\r\n\t\t#endif\r\n\t\t*/\r\n\r\n\t\t//return;\r\n\t\tint tag = 200, send_count, recv_count;\r\n\t\tMPI_Request req_send[2 * nproc], req_recv[2 * nproc];\r\n\t\tMPI_Status stat_send[2 * nproc], stat_recv;\r\n\r\n\t\trecv_count = 0;\r\n\t\tfor(i = 0; i < nproc; i++)\r\n\t\t{\r\n\t\t\tif(recv_buf_size[i] > 0)\r\n\t\t\t{\r\n\t\t\t\trecv_buf[i].resize(recv_buf_size[i], 0);\r\n\t\t\t\trecv_buf_ind[i].resize(recv_buf_size[i] / dbs.m_pts->m_i_dims, -1);\r\n\r\n\t\t\t\tMPI_Irecv(&recv_buf[i][0], recv_buf_size[i], MPI_FLOAT, i, tag, MPI_COMM_WORLD, &req_recv[recv_count++]);\r\n\t\t\t\tMPI_Irecv(&recv_buf_ind[i][0], recv_buf_size[i] / dbs.m_pts->m_i_dims, MPI_INT, i, tag + 1, MPI_COMM_WORLD, &req_recv[recv_count++]);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tsend_count = 0;\r\n        \tfor(i = 0; i < nproc; i++)\r\n        \t{\r\n            \t\tif(send_buf_size[i] > 0)\r\n            \t\t{\r\n                \t\tMPI_Isend(&send_buf[i][0], send_buf_size[i], MPI_FLOAT, i, tag, MPI_COMM_WORLD, &req_send[send_count++]);\r\n\t\t\t\tMPI_Isend(&send_buf_ind[i][0], send_buf_size[i] / dbs.m_pts->m_i_dims, MPI_INT, i, tag + 1, MPI_COMM_WORLD, &req_send[send_count++]);\r\n\t\t\t}\r\n        \t}\r\n\r\n\t\tint rtag, rsource, rpos;\r\n\r\n\t\t#if _GET_PARTION_STAT == 0\r\n\t\tdbs.allocate_outer(dbs.m_pts->m_i_dims);\r\n\t\t#endif\r\n\r\n\t\t//cout << \"proc \" << rank << \" recv_count \" << recv_count << endl;\r\n\r\n\t\tfor(i = 0; i < recv_count; i++)\r\n\t\t{\r\n\t\t\tMPI_Waitany(recv_count, &req_recv[0], &rpos, &stat_recv);\r\n\t\t\r\n\t\t\trtag = stat_recv.MPI_TAG;\r\n\t\t\trsource = stat_recv.MPI_SOURCE;\r\n\t\t\r\n\t\t\tif(rtag == tag)\r\n\t\t\t{\r\n\t\t\t\t// process the request\r\n\t\t\t\t//cout << \"proc \" << rank << \" add points called \" << endl;\r\n\t\t\t\t#if _GET_EXTRA_POINT_STAT == 0  // WHY THIS IS HERE??????????????????????????????????????????????????????????????\r\n\t\t\t\tdbs.addPoints(rsource, recv_buf_size[rsource], dbs.m_pts->m_i_dims, recv_buf[rsource]);\r\n\t\t\t\t#endif\r\n\t\t\t\trecv_buf[rsource].clear();\r\n\t\t\t}\r\n\t\t\telse if(rtag == tag + 1)\r\n\t\t\t{\r\n\t\t\t\t// postpond this computation and call update points later\r\n\t\t\t\t// processing immediately might lead to invalid computation\r\n\t\t\t}\r\n\t\t}\t\r\n\r\n\t\t//cout << \"proc \" << rank << \" send_count \" << send_count << endl;\r\n\t\t\r\n\t\t// MAY NOT NEED THIS\r\n\t\tif(send_count > 0)\r\n\t\t\tMPI_Waitall(send_count, &req_send[0], &stat_send[0]);\r\n\r\n        \t#ifdef _DEBUG_GP\r\n\t\tMPI_Barrier(MPI_COMM_WORLD);\r\n        \tend = MPI_Wtime();\r\n\t        #ifdef _DEBUG\r\n        \tif(rank == proc_of_interest) cout << \"extra point time part 3: \" << end - start << endl;        \r\n        \t#endif\r\n        \tstart = end;\r\n        \t#endif\r\n\r\n\t\t// got all the points\r\n\t\t// now update the indices of the outer points\r\n\r\n\t\t#if _GET_EXTRA_POINT_STAT == 0 // WHY THIS IS HERE??????????????????????????????????????????????????????????????\r\n\t\tdbs.updatePoints(recv_buf_ind);\r\n\t\t#endif\r\n\r\n\t\t/*if(rank == 3)\r\n\t\t{\r\n\t\t\tcout << \"proc \" << rank << \" recv \";\r\n\t\t\tfor(i = 0; i < nproc; i++)\r\n\t\t\t{\r\n\t\t\t\tcout << recv_buf_size[i] << \" \";\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tcout << endl;\r\n\t\t}\r\n\t\t*/\r\n\r\n\t\t//#ifdef _DEBUG\r\n\t\tMPI_Reduce(&count, &gcount, 1, MPI_INT, MPI_SUM, proc_of_interest, MPI_COMM_WORLD);\r\n\t\t\r\n\t\t//dbs.m_extra_point_per_processor = gcount/nproc; // save extra point per processor for future use if needed\r\n\t\t#ifdef _DEBUG\r\n\t\tif(rank == proc_of_interest)\r\n\t\t{\r\n\t\t\tcout << \"Total extra point \" << gcount << endl;\r\n\t\t\tcout << \"Extra point per processor \" << gcount/nproc << endl;\r\n\t\t}\r\n\t\t#endif\r\n\r\n        \t#ifdef _DEBUG_GP\r\n\t\tMPI_Barrier(MPI_COMM_WORLD);\r\n        \tend = MPI_Wtime();\r\n\t        #ifdef _DEBUG\r\n\t\tif(rank == proc_of_interest) cout << \"extra point time part 4: \" << end - start << endl;        \r\n        \t#endif\r\n        \tstart = end;\r\n        \t#endif\r\n\r\n\t\tempty.clear();\r\n\t\tsend_buf.clear();\r\n\t\trecv_buf.clear();\r\n\t\tsend_buf_size.clear();\r\n\t\trecv_buf_size.clear();\r\n\t\tsend_buf_ind.clear();\r\n\t\trecv_buf_ind.clear();\r\n\r\n        \tdelete [] gather_local_box;\r\n\t\tdelete [] local_box;\r\n\t}\r\n\r\n\tvoid start_partitioning(ClusteringAlgo& dbs)\r\n\t{\r\n\t\tint r_count, s_count, rank, nproc, i, j, k;\r\n\t\tMPI_Comm_rank(MPI_COMM_WORLD, &rank);\r\n\t\tMPI_Comm_size(MPI_COMM_WORLD, &nproc);\r\n\r\n\t\t// compute the local bouding box for each dimention\r\n\t\tinterval* box = new interval[dbs.m_pts->m_i_dims];\r\n\t\t//compute_local_bounding_box(dbs, box);\r\n\t\t// we don't need to compute as we have stored this while reading\r\n\t\t\r\n\t\tfor(i = 0; i < dbs.m_pts->m_i_dims; i++)\r\n\t\t{\t\r\n\t\t\tbox[i].upper = dbs.m_pts->m_box[i].upper;\r\n\t\t\tbox[i].lower = dbs.m_pts->m_box[i].lower;\r\n\t\t}\r\n\r\n\t\t// compute the global bouding box for each dimention\r\n\t\tinterval* gbox = new interval[dbs.m_pts->m_i_dims];\r\n\t\tcompute_global_bounding_box(dbs, box, gbox, nproc);\r\n\r\n\t\t//delete [] box;\r\n\t\t//delete [] gbox;\r\n\t\t//return;\r\n\r\n\t\t#ifdef _DEBUG\r\n        \tif(rank == proc_of_interest) cout << \"Partitioning: Pos 1\" << endl;\r\n        \t#endif\r\n\r\n\t\t// find the loop count for nproc processors\r\n\t\tint internal_nodes, partner_rank, loops, b, color, sub_rank, d, max, sub_nprocs;\r\n\t\t//MPI_Comm new_comm;\r\n\t\tMPI_Status status;\r\n\r\n\t\tloops = 0;\r\n\t\ti = nproc;\r\n\t\tinternal_nodes = 1;\r\n\t\twhile((i = i >> 1) > 0)\r\n\t\t{\r\n\t\t\tloops++;\r\n\t\t\tinternal_nodes = internal_nodes << 1;\r\n\t\t}\r\n\t\t\r\n\t\tinternal_nodes = internal_nodes << 1;\r\n\t\t\r\n\t\t//gbox for each node in the tree [ONLY upto to reaching each processor]\r\n\t\tinterval** nodes_gbox = new interval*[internal_nodes];\r\n\t\tfor(i = 0; i < internal_nodes; i++)\r\n\t\t\tnodes_gbox[i] = new interval[dbs.m_pts->m_i_dims];\r\n\t\t\r\n\t\tcopy_global_box_to_each_node(dbs, nodes_gbox, gbox, internal_nodes);\r\n\t\t// now each node in the tree has gbox\r\n\r\n\t\t/*\r\n \t\t#ifdef _DEBUG\r\n\t\tif(rank == proc_of_interest)\r\n\t\t{\tcout << \"proc \" << rank << \" nodes \" << internal_nodes << \" loops \"<< loops << endl;\t\t\r\n\t\t\tprint_points(dbs, rank);\r\n\t\t}\r\n\t\t#endif\r\n\t\t*/\r\n\r\n\t       \t#ifdef _DEBUG\r\n        \tif(rank == proc_of_interest) cout << \"Partitioning: Pos 2\" << endl;\r\n        \t#endif\r\n\t\r\n\t\tvector <float> send_buf;\r\n\t\tvector <int>   invalid_pos_as;\r\n\t\tvector <float> recv_buf;\r\n\t\t\t\t\r\n\t\tint pow2_i;\r\n\t\tfloat median;\r\n\r\n\t\tfor(i = 0; i < loops; i++)\r\n\t\t{\r\n\t\t\tpow2_i = POW2(i);\r\n\t\t\tb  = nproc - (int) (nproc / pow2_i);\r\n\t\t\tcolor = (int)((rank & b) / POW2(loops - i ));\r\n\t\t\tpartner_rank = rank ^ (int)(nproc/POW2(i + 1));\r\n\r\n\t\t\tMPI_Comm new_comm;\r\n            \t\tMPI_Comm_split(MPI_COMM_WORLD, color, rank, &new_comm);\r\n           \t\tMPI_Comm_rank(new_comm, &sub_rank);\r\n\t\r\n\t\t\t//\tcout << \"i \" << i << \" proc \" << rank << \" b \" << b << \" color \" << color << \" partner_rank \" << partner_rank << \" sub_rank \" << sub_rank << \" pow_2i \" << pow2_i << endl;\r\n\t\t\t\r\n\t\t\tif(sub_rank == 0)\r\n\t\t\t{\r\n\t\t\t\td = 0;\r\n\t\t\t\tfor(j = 1; j < dbs.m_pts->m_i_dims; j++)\r\n\t\t\t\t{\r\n\t\t\t\t\t\r\n\t\t\t\t\tif(nodes_gbox[pow2_i + color][j].upper - nodes_gbox[pow2_i + color][j].lower > \r\n\t\t\t\t\t\t\tnodes_gbox[pow2_i + color][d].upper - nodes_gbox[pow2_i + color][d].lower)\r\n\t\t\t\t\t\td = j;\r\n\t\t\t\t}\r\n\t\t\t}\t\r\n\t\r\n\t\t\tMPI_Bcast(&d, 1, MPI_INT, 0, new_comm);\r\n\r\n            \t\t//#ifdef _DEBUG\r\n\t\t\t//MPI_Barrier(MPI_COMM_WORLD);\r\n            \t\t//if(rank == proc_of_interest) cout << \"At before starting median - round \" << i << endl;\r\n            \t\t//#endif\r\n\r\n\t\t\t// compute the median in this dimension\r\n\t\t\tfloat median  = get_median(dbs, d, new_comm);\t\t\r\n\r\n\t        \t//#ifdef _DEBUG\r\n    \t    \t\t//if(rank == proc_of_interest) cout << \"median \" << median << \" round \" << i << endl;\t\r\n\t\t\t//#endif\r\n\r\n\t\t\ts_count = get_points_to_send(dbs, send_buf, invalid_pos_as, median, d, rank, partner_rank);\r\n\r\n\t\t\tif (rank < partner_rank)\r\n\t\t\t{\r\n\t\t\t\tMPI_Sendrecv(&s_count, 1, MPI_INT, partner_rank, 4, &r_count, 1, MPI_INT, partner_rank, 5, MPI_COMM_WORLD, &status);\r\n\t\t\t\trecv_buf.resize(r_count * dbs.m_pts->m_i_dims, 0.0);\r\n\t\t\t    \tMPI_Sendrecv(&send_buf[0], s_count * dbs.m_pts->m_i_dims, MPI_FLOAT, partner_rank, 2,\r\n\t\t\t\t\t\t\t&recv_buf[0], r_count * dbs.m_pts->m_i_dims, MPI_FLOAT, partner_rank, 3, MPI_COMM_WORLD, &status);\r\n\t\t\t\tsend_buf.clear();\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tMPI_Sendrecv(&s_count, 1, MPI_INT, partner_rank, 5, &r_count, 1, MPI_INT, partner_rank, 4, MPI_COMM_WORLD, &status);\r\n\t\t\t\trecv_buf.resize(r_count * dbs.m_pts->m_i_dims, 0.0);\r\n\t\t\t\tMPI_Sendrecv(&send_buf[0], s_count * dbs.m_pts->m_i_dims, MPI_FLOAT, partner_rank, 3, \r\n\t\t\t\t\t\t\t&recv_buf[0], r_count * dbs.m_pts->m_i_dims, MPI_FLOAT, partner_rank, 2, MPI_COMM_WORLD, &status);\r\n\t\t\t\tsend_buf.clear();\r\n\t\t\t}\r\n\t\r\n\t\t\t//#ifdef _DEBUG\r\n\t\t\t//MPI_Barrier(MPI_COMM_WORLD);\r\n    \t    \t\t//if(rank == proc_of_interest) cout << \"AT before update points - round \" << i << endl;\t\r\n\t\t\t//#endif\r\n\t\t\r\n\t\t\tupdate_points(dbs, s_count, invalid_pos_as, recv_buf);\r\n\t\t\trecv_buf.clear();\r\n\t\t\t\t\t\t\r\n\t\t\t//#ifdef _DEBUG\r\n\t\t\t//MPI_Barrier(MPI_COMM_WORLD);\r\n    \t    \t\t//if(rank == proc_of_interest) cout << \"AT after update points - round \" << i << endl;\t\r\n\t\t\t//#endif\r\n\t\r\n\t\t\t/*\r\n\t\t\t#ifdef _DEBUG\r\n\t\t\tif(rank == proc_of_interest)\r\n\t\t\t{\r\n\t\t\t\tcout << \"proc \" << rank << \" sub proc \" << sub_rank << \" median \" << median << \" of dimension \" << d << \" points to recv \" << r_count << \" points to send \" << s_count << \" partner \" << partner_rank << endl;\t\t\t\r\n\t\t\t\t\r\n\t\t\t\tprint_points(dbs, rank);\r\n\t\t\t}\r\n\t\t\t#endif\r\n\r\n\t\t\t#ifdef _DEBUG\r\n\t\t\tcout << \"proc \" << rank << \" round \" << i << \" points \" << dbs.m_pts->m_i_num_points << endl; \r\n\t\t\t#endif\r\n\t\t\t*/\r\n\t\t\t\r\n\t\t\t//#ifdef _DEBUG\r\n\t\t\t//MPI_Barrier(MPI_COMM_WORLD);\r\n    \t    \t\t//if(rank == proc_of_interest) cout << \"AT before copying box - round \" << i << endl;\t\r\n\t\t\t//#endif\r\n\t\r\n\t\t\tcopy_box(dbs, nodes_gbox[LOWER(pow2_i+color)], nodes_gbox[pow2_i+color]);\r\n\t\t\tnodes_gbox[LOWER(pow2_i+color)][d].upper =  median;\r\n\t\t\tcopy_box(dbs, nodes_gbox[UPPER(pow2_i+color)], nodes_gbox[pow2_i+color]);\r\n\t\t\tnodes_gbox[UPPER(pow2_i+color)][d].lower =  median;\t\r\n\r\n            \t\t/*\r\n  \t\t\t#ifdef _DEBUG\r\n\t\t\tMPI_Barrier(MPI_COMM_WORLD);\r\n            \t\tif(rank == proc_of_interest) cout << \"AT after copying box - round \" << i << \" rank \" << rank << endl;  \r\n            \t\t#endif\r\n\r\n\t\t\t#ifdef _DEBUG \r\n\t\t\tcout << \"proc \" << rank << \" round \" << i << \" points \" << dbs.m_pts->m_i_num_points << endl;\r\n\t\t\t#endif\r\n\t\t\t*/\r\n\t\t\tMPI_Comm_free(&new_comm);\r\n\t\t}\r\n        \r\n\t\t#ifdef _DEBUG\r\n        \tif(rank == proc_of_interest) cout << \"Partitioning: Pos 3\" << endl;\r\n        \t#endif\r\n\t\r\n\t\t/*#ifdef _DEBUG\r\n       \t\tcout << \"proc \" << rank << \" points \" << dbs.m_pts->m_i_num_points << endl;\r\n        \t#endif\r\n\t\t*/\r\n\r\n\t\t/*compute_local_bounding_box(dbs, box);\r\n\r\n\t\t#ifdef _DEBUG\r\n\t\tif(rank == proc_of_interest)\r\n\t\t{\r\n\t\t\tprint_box(dbs, rank, box);\r\n\t\t}\r\n\t\t#endif\r\n\t\t*/\r\n\r\n\t\t// free the allocated memory\r\n\t\tfor(i = 0; i < nproc; i++)\r\n\t\t\tdelete [] nodes_gbox[i];\r\n\r\n\t\tdelete [] nodes_gbox;\r\n\t\tdelete [] gbox;\r\n\t\tdelete [] box;\r\n\r\n\t\t// free communicator\r\n\t\t //MPI_Comm_free(&new_comm);\r\n\t}\r\n\r\n\tvoid update_points(ClusteringAlgo& dbs, int s_count, vector <int>& invalid_pos_as, vector <float>& recv_buf)\r\n\t{\r\n\t\tint i, j, k, l, r_count = recv_buf.size() / dbs.m_pts->m_i_dims;\r\n\r\n\t\t//cout << \"r_count \" << r_count << \" s_count \" << s_count << endl;\r\n\t\r\n\t\tif(r_count >= s_count)\r\n\t\t{\r\n\t\t\t//invalid_pos_as.reserve(dbs.m_pts->m_i_num_points + r_count - s_count);\r\n\t\t\tinvalid_pos_as.resize(dbs.m_pts->m_i_num_points + r_count - s_count, 1);\r\n\r\n\t\t\t//dbs.m_pts->m_points.reserve(dbs.m_pts->m_i_num_points + r_count - s_count);\r\n\t\t\t//dbs.m_pts->m_points.resize(extents[dbs.m_pts->m_i_num_points + r_count - s_count][dbs.m_pts->m_i_dims]);\r\n\t\t\t\r\n\t\t\t//allocate memory for the points\r\n                \tdbs.m_pts->m_points.resize(dbs.m_pts->m_i_num_points + r_count - s_count);\r\n                \tfor(int ll = 0; ll < dbs.m_pts->m_i_num_points + r_count - s_count; ll++)\r\n                \t\tdbs.m_pts->m_points[ll].resize(dbs.m_pts->m_i_dims);\r\n\r\n\t\r\n\t\t\tj = 0;\r\n\t\t\tfor(i = 0; i < invalid_pos_as.size(); i++)\r\n\t\t\t{\r\n\t\t\t\tif(invalid_pos_as[i] == 1)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor(k = 0; k < dbs.m_pts->m_i_dims; k++)\r\n\t\t\t\t\t\tdbs.m_pts->m_points[i][k] = recv_buf[j++];\r\n\t\t\t\t}\r\n\t\t\t}\t\t\t\r\n\r\n\t\t\tdbs.m_pts->m_i_num_points = dbs.m_pts->m_i_num_points + r_count - s_count;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tj = 0;\r\n\t\t\ti = 0;\t\r\n\t\t\tif(recv_buf.size() > 0)\r\n\t\t\t{\r\n\t\t\t\tfor(i = 0; i < dbs.m_pts->m_i_num_points; i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif(invalid_pos_as[i] == 1)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfor(k = 0; k < dbs.m_pts->m_i_dims; k++)\r\n\t\t\t\t\t\t\tdbs.m_pts->m_points[i][k] = recv_buf[j++];\r\n\t\t\t\t\t\r\n\t\t\t\t\t\tif(j == recv_buf.size())\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\ti++;\r\n\t\t\t\t\t\t\tbreak;\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\t\r\n\t\t\tl = dbs.m_pts->m_i_num_points;\r\n\t\t\tfor( ; i < invalid_pos_as.size(); i++)\r\n\t\t\t{\r\n\t\t\t\tif(invalid_pos_as[i] == 1)\r\n\t\t\t\t{\r\n\t\t\t\t\twhile(l > i)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tl--;\r\n\t\t\t\t\t\tif(invalid_pos_as[l] == 0)\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif(invalid_pos_as[l] == 0)\t\r\n\t\t\t\t\t\tfor(k = 0; k < dbs.m_pts->m_i_dims; k++)\r\n\t\t\t\t\t\t\tdbs.m_pts->m_points[i][k] = dbs.m_pts->m_points[l][k];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t//dbs.m_pts->m_points.resize(extents[dbs.m_pts->m_i_num_points + r_count - s_count][dbs.m_pts->m_i_dims]);\r\n\r\n\t\t\t//allocate memory for the points\r\n                \tdbs.m_pts->m_points.resize(dbs.m_pts->m_i_num_points + r_count - s_count);\r\n                \tfor(int ll = 0; ll < dbs.m_pts->m_i_num_points + r_count - s_count; ll++)\r\n                \t\tdbs.m_pts->m_points[ll].resize(dbs.m_pts->m_i_dims);\r\n\r\n\t\t\tdbs.m_pts->m_i_num_points = dbs.m_pts->m_i_num_points + r_count - s_count;\r\n\t\t}\t\t\r\n\t}\r\n\r\n\tint get_points_to_send(ClusteringAlgo& dbs, vector <float>& send_buf, vector <int>& invalid_pos_as, float median, int d, int rank, int partner_rank)\r\n\t{\r\n\t\tint i, count = 0, j;\r\n\t\tsend_buf.reserve(dbs.m_pts->m_i_num_points * dbs.m_pts->m_i_dims);\r\n\t\tinvalid_pos_as.clear();\r\n\t\tinvalid_pos_as.resize(dbs.m_pts->m_i_num_points, 0);\r\n\r\n\t\tfor(i = 0; i < dbs.m_pts->m_i_num_points; i++)\r\n\t\t{\r\n\t\t\tif (rank < partner_rank)\r\n\t\t\t{\r\n\t\t\t\tif(dbs.m_pts->m_points[i][d] > median)\r\n\t\t\t\t{\r\n\t\t\t\t\tinvalid_pos_as[i] = 1;\r\n\t\t\t\t\tcount++;\r\n\t\t\t\t\tfor(j = 0; j < dbs.m_pts->m_i_dims; j++)\r\n\t\t\t\t\t\tsend_buf.push_back(dbs.m_pts->m_points[i][j]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n                if(dbs.m_pts->m_points[i][d] <= median)\r\n                {\r\n                    invalid_pos_as[i] = 1;\r\n                    count++;\r\n                    for(j = 0; j < dbs.m_pts->m_i_dims; j++)\r\n                        send_buf.push_back(dbs.m_pts->m_points[i][j]);\r\n                }\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn count;\r\n\t}\t\r\n\r\n\tfloat get_median(ClusteringAlgo& dbs, int d, MPI_Comm& new_comm)\r\n\t{\t\r\n\t\t/*\r\n\t\tdouble sum, g_sum;\r\n\t\t//float sum, g_sum;\r\n\r\n\t\tsum = 0.0;\r\n\t\tg_sum = 0.0;\r\n\r\n    \tfor (int k = 0; k < dbs.m_pts->m_i_num_points; k++) \r\n      \t\tsum += dbs.m_pts->m_points[k][d];\r\n\r\n\t\t//MPI_Allreduce(&sum, &g_sum, 1, MPI_FLOAT, MPI_SUM, new_comm);\r\n\t\tMPI_Allreduce(&sum, &g_sum, 1, MPI_DOUBLE, MPI_SUM, new_comm);\r\n\r\n\t\tint g_point_count = 0;\r\n\t\tMPI_Allreduce(&dbs.m_pts->m_i_num_points, &g_point_count, 1, MPI_INT, MPI_SUM, new_comm);\r\n\r\n\t\t//return g_sum / static_cast<float>(g_point_count);\r\n\t\treturn g_sum / static_cast<double>(g_point_count);\r\n\t\t*/\r\n\r\n\r\n\r\n\t\t// ADDITIONAL CODE\r\n\t\tfloat median;\r\n\t\t\r\n\t\tvector <float> data;\r\n\t\tdata.reserve(dbs.m_pts->m_i_num_points);\r\n\t\tdata.resize(dbs.m_pts->m_i_num_points, 0);\r\n\r\n\t\tfor (int k=0; k < dbs.m_pts->m_i_num_points; k++)\r\n\t      \t//data.push_back(dbs.m_pts->m_points[k][d]);\r\n\t      \tdata[k] = dbs.m_pts->m_points[k][d];\r\n\r\n\t\t/*\r\n       \t#ifdef _DEBUG\r\n\t\tint rank;\r\n\t\tMPI_Comm_rank(MPI_COMM_WORLD, &rank);\r\n        //MPI_Barrier(new_comm);\r\n        MPI_Barrier(MPI_COMM_WORLD);\r\n       \t//if(rank == proc_of_interest) \r\n       \tcout << \"AT median Pos 0 - rank \" << rank << \" data size \" << data.size() << endl;\r\n        #endif\r\n\t\t*/\r\n\t\r\n\t\tmedian = findKMedian(data, data.size()/2);\r\n\t\tdata.clear();\r\n\t\t\r\n\t\t#ifdef _DEBUG\r\n\t\tint rank;\r\n\t\tMPI_Comm_rank(MPI_COMM_WORLD, &rank);\r\n\t\tif(rank == proc_of_interest) cout << \"Median VALUE \" << median << endl;\r\n\t\t#endif\r\n\t\r\n       \t/*#ifdef _DEBUG\r\n\t\t//int rank;\r\n\t\tMPI_Comm_rank(MPI_COMM_WORLD, &rank);\r\n        //MPI_Barrier(new_comm);\r\n        MPI_Barrier(MPI_COMM_WORLD);\r\n       \t//if(rank == proc_of_interest) \r\n\t\tcout << \"AT median Pos 1 - rank \" << rank << \" data size \" << data.size() << endl;\r\n        #endif\r\n\t\t*/\r\n\r\n\r\n\t\tint proc_count;\r\n\t\tMPI_Comm_size(new_comm, &proc_count);\r\n\r\n\t    //#ifdef _DEBUG\r\n\t\t//int rank;\r\n\t\t//MPI_Comm_rank(new_comm, &rank);\r\n    \t//if(rank == proc_of_interest) cout << \"proc_count \" << proc_count << endl;\t\r\n\t\t//#endif\r\n\r\n\t\t//cout << \"proc count \" << proc_count << endl;\r\n\r\n\t\tvector <float> all_medians;\r\n\t\tall_medians.resize(proc_count, 0);\r\n\r\n\t\tMPI_Allgather(&median, sizeof(int), MPI_BYTE, &all_medians[0], sizeof(int), MPI_BYTE, new_comm);\t\r\n\r\n  \t\tmedian = findKMedian(all_medians, all_medians.size()/2); \r\n\t\tall_medians.clear();\r\n\t\t\r\n\t\treturn median;\t\r\n\t}\r\n\r\n\tvoid compute_local_bounding_box(ClusteringAlgo& dbs, interval* box)\r\n\t{\r\n\t\tint i, j;\r\n\r\n\t\t//we assume each processor has at least one point\r\n\t\t//if(dbs.m_pts->m_i_num_points > 0)\r\n\t\t{\r\n\t\t\t\r\n\t\t\tfor(i = 0; i < dbs.m_pts->m_i_dims; i++)\r\n\t\t\t{\r\n\t\t\t\tbox[i].upper = dbs.m_pts->m_points[0][i];\r\n\t\t\t\tbox[i].lower = dbs.m_pts->m_points[0][i];\r\n\t\t\t}\r\n\t\t\r\n\t\t\tfor(i = 0; i < dbs.m_pts->m_i_dims; i++)\r\n\t\t\t{\r\n\t\t\t\tfor(j = 1; j < dbs.m_pts->m_i_num_points; j++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif(box[i].lower > dbs.m_pts->m_points[j][i])\r\n\t\t\t\t\t\tbox[i].lower = dbs.m_pts->m_points[j][i];\r\n\t\t\t\t\telse if(box[i].upper < dbs.m_pts->m_points[j][i])\r\n                \t    box[i].upper = dbs.m_pts->m_points[j][i];\r\n\t\t\t\t}\r\n\t\t\t\t//if(rank == 0)\r\n    \t    \t\t//  cout << \"proc \" << rank << \" upper \" << box[i].upper << \" lower \" << box[i].lower << endl;\r\n\t\t\t}\r\n\t\t}\r\n\t\t/*else\r\n\t\t{\r\n\t\t\t// WHAT TO DO IF THERE IS NO POINTS\r\n\t\t\t// FOR THE TIME BEING set 0 \r\n\t\t\tfor(i = 0; i < dbs.m_pts->m_i_dims; i++)\r\n\t\t\t{\r\n\t\t\t\tbox[i].upper = 0;\r\n\t\t\t\tbox[i].lower = 0;\r\n\t\t\t}\r\n\t\t}*/\r\n\t}\r\n\r\n\tvoid compute_global_bounding_box(ClusteringAlgo& dbs, interval* box, interval* gbox, int nproc)\r\n\t{\r\n\t\tint i, j, k;\r\n\t\r\n\t\tinterval* gather_local_box = new interval[dbs.m_pts->m_i_dims * nproc];\r\n\t\r\n\t\t// gather the local bounding box first\r\n\t\tMPI_Allgather(box, sizeof(interval) * dbs.m_pts->m_i_dims, MPI_BYTE, gather_local_box, \r\n\t\t\t\t\tsizeof(interval) * dbs.m_pts->m_i_dims, MPI_BYTE, MPI_COMM_WORLD);\r\n\r\n\t\t// compute the global bounding box\r\n\t\tfor(i = 0; i < dbs.m_pts->m_i_dims; i++)\r\n\t\t{\r\n\t\t\tgbox[i].lower = gather_local_box[i].lower;\r\n\t\t\tgbox[i].upper = gather_local_box[i].upper;\r\n\t\t\t\r\n\t\t\tk = i;\r\n\t\t\tfor(j = 0; j < nproc; j++, k += dbs.m_pts->m_i_dims)\r\n\t\t\t{\r\n\t\t\t\tif(gbox[i].lower > gather_local_box[k].lower)\r\n\t\t\t\t\tgbox[i].lower = gather_local_box[k].lower;\r\n\t\t\t\t\r\n\t\t\t\tif(gbox[i].upper < gather_local_box[k].upper)\r\n                    gbox[i].upper = gather_local_box[k].upper;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tdelete [] gather_local_box;\r\n\t}\r\n\r\n\tvoid copy_global_box_to_each_node(ClusteringAlgo& dbs, interval** nodes_gbox, interval* gbox, int internal_nodes)\r\n\t{\r\n        int i, j;\r\n        for(i = 0; i < internal_nodes; i++)\r\n        {\r\n            for(j = 0; j < dbs.m_pts->m_i_dims; j++)\r\n            {\r\n                nodes_gbox[i][j].upper = gbox[j].upper;\r\n                nodes_gbox[i][j].lower = gbox[j].lower;\r\n            }\r\n        }\r\n\t}\r\n\t\r\n\tvoid copy_box(ClusteringAlgo& dbs, interval* target_box, interval* source_box)\r\n\t{\r\n\t\t\tfor(int j = 0; j < dbs.m_pts->m_i_dims; j++)\r\n\t\t\t{\r\n\t\t\t\ttarget_box[j].upper = source_box[j].upper;\r\n\t\t\t\ttarget_box[j].lower = source_box[j].lower;\r\n\t\t\t}\r\n\t}\r\n\r\n\tvoid print_points(ClusteringAlgo& dbs, int rank)\r\n\t{\r\n\t\tcout << \"proc \" << rank << \" owned points: \" << dbs.m_pts->m_points.size() << \" verify \" << dbs.m_pts->m_i_num_points << endl;\r\n\t\tint u, v;\r\n\r\n\t\t/*\r\n\t\tfor(u = 0; u < dbs.m_pts->m_i_num_points; u++)\r\n        {\r\n        \tfor(v = 0; v < dbs.m_pts->m_i_dims; v++)\r\n            \tcout << dbs.m_pts->m_points[u][v] << \" \";\r\n            cout << endl;\r\n        }\r\n\t\t*/\r\n\r\n\t\tcout << \"proc \" << rank << \" outer points: \" << dbs.m_pts_outer->m_points.size() << \" verify \" << dbs.m_pts_outer->m_i_num_points << endl;\r\n\r\n\t\t/*\r\n\t\tfor(u = 0; u < dbs.m_pts_outer->m_i_num_points; u++)\r\n        {\r\n            for(v = 0; v < dbs.m_pts_outer->m_i_dims; v++)\r\n                cout << dbs.m_pts_outer->m_points[u][v] << \" \";\r\n            cout << endl;\r\n        }\r\n\t\t*/\r\n\t}\r\n\r\n    void print_box(ClusteringAlgo& dbs, int rank, interval* box)\r\n    {\r\n        cout << \"proc \" << rank << \" bbox: \";\r\n\r\n\t\tfor(int v = 0; v < dbs.m_pts->m_i_dims; v++)\r\n\t\t{\r\n        \tif(v == dbs.m_pts->m_i_dims - 1)\r\n\t\t\t\tcout << \"(\" << box[v].upper << \", \" << box[v].lower << \")\";\r\n\t\t\telse\r\n\t\t\t\tcout << \"(\" << box[v].upper << \", \" << box[v].lower << \"), \";\r\n\t\t}\r\n\r\n        cout << endl;\r\n    }\r\n};\r\n\r\n", "meta": {"hexsha": "8466a56688f2a7e53acd7b6d561dafb0c8c1d588", "size": 28294, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SCANVariants/other-projects/dbscan-v1.0.0/parallel_mpi/geometric_partitioning.cpp", "max_stars_repo_name": "CheYulin/ScanOptimizing", "max_stars_repo_head_hexsha": "691b39309da1c6b5df46b264b5a300a35d644f70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2019-05-22T13:17:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-26T11:42:08.000Z", "max_issues_repo_path": "SCANVariants/other-projects/dbscan-v1.0.0/parallel_mpi/geometric_partitioning.cpp", "max_issues_repo_name": "CheYulin/ScanOptimizing", "max_issues_repo_head_hexsha": "691b39309da1c6b5df46b264b5a300a35d644f70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-08-15T05:00:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-16T06:09:42.000Z", "max_forks_repo_path": "SCANVariants/other-projects/dbscan-v1.0.0/parallel_mpi/geometric_partitioning.cpp", "max_forks_repo_name": "CheYulin/ScanOptimizing", "max_forks_repo_head_hexsha": "691b39309da1c6b5df46b264b5a300a35d644f70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-12-20T10:09:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-26T11:42:10.000Z", "avg_line_length": 31.1607929515, "max_line_length": 214, "alphanum_fraction": 0.5566551212, "num_tokens": 8499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.28352507187085135}}
{"text": "#ifdef _WIN32\n#pragma warning(disable:4503)\n#pragma warning(push)\n#pragma warning(disable:4996 4251 4275 4800)\n#endif\n#include <opencv2/imgproc.hpp>\n#include <vector>\n#include <boost/lexical_cast.hpp>\n#ifdef _WIN32\n#pragma warning(pop)\n#endif\n\n#include \"Block.h\"\n#include \"ParamValidator.h\"\n#include \"OpenCV_filter.h\"\n#include \"Convertor.h\"\nusing namespace charliesoft;\nusing std::vector;\nusing boost::lexical_cast;\nusing std::string;\nusing cv::Mat;\n\nnamespace charliesoft\n{\n  BLOCK_BEGIN_INSTANTIATION(BinarizeBlock);\n  //You can add methods, re implement needed functions... \n  BLOCK_END_INSTANTIATION(BinarizeBlock, AlgoType::mathOperator, BLOCK__BINARIZE_NAME);\n\n  BEGIN_BLOCK_INPUT_PARAMS(BinarizeBlock);\n  //Add parameters, with following parameters:\n  //default visibility, type of parameter, name (key of internationalizor), helper...\n  ADD_PARAMETER(toBeLinked, Matrix, \"BLOCK__BINARIZE_IN_IMAGE\", \"BLOCK__BINARIZE_IN_IMAGE_HELP\");\n  ADD_PARAMETER_FULL(userConstant, ListBox, \"BLOCK__BINARIZE_IN_METHOD\", \"BLOCK__BINARIZE_IN_METHOD_HELP\", 0);\n  END_BLOCK_PARAMS();\n\n  BEGIN_BLOCK_OUTPUT_PARAMS(BinarizeBlock);\n  ADD_PARAMETER(toBeLinked, AnyType, \"BLOCK__BINARIZE_OUT_IMAGE\", \"BLOCK__BINARIZE_OUT_IMAGE_HELP\");//output type is defined by inputs\n  END_BLOCK_PARAMS();\n\n  BEGIN_BLOCK_SUBPARAMS_DEF(BinarizeBlock);\n  ADD_PARAMETER_FULL(notUsed, Float, \"BLOCK__BINARIZE_IN_METHOD.Simple threshold.threshold\", \"threshold\", 128.);\n  ADD_PARAMETER_FULL(notUsed, Float, \"BLOCK__BINARIZE_IN_METHOD.Adaptative.threshold\", \"threshold\", 10);\n  ADD_PARAMETER_FULL(notUsed, Int, \"BLOCK__BINARIZE_IN_METHOD.Adaptative.window size\", \"window size\", 7);\n  ADD_PARAMETER_FULL(notUsed, Float, \"BLOCK__BINARIZE_IN_METHOD.Sauvola.threshold\", \"threshold\", 0.3);\n  ADD_PARAMETER_FULL(notUsed, Int, \"BLOCK__BINARIZE_IN_METHOD.Sauvola.window size\", \"window size\", 9);\n  END_BLOCK_PARAMS();\n\n  BinarizeBlock::BinarizeBlock() :Block(\"BLOCK__BINARIZE_NAME\", true){\n    _myInputs[\"BLOCK__BINARIZE_IN_IMAGE\"].addValidator({ new ValNeeded() });\n  };\n\n  cv::Mat binarizeSauvolaIntegral(cv::Mat gray_image, int whalf, double k)\n  {\n    cv::Mat out(gray_image.size(), CV_8UC1);\n    int w = whalf * 2 + 1;\n\n    if (k < 0.02 || k > 0.95)\n      k = 0.2;\n    if (w < 2)\n      w = 15;\n\n    int image_width = gray_image.cols;\n    int image_height = gray_image.rows;\n\n    // Calculate the integral image, and integral of the squared image\n    cv::Mat integral_image(gray_image.size(), CV_64FC1), rowsum_image(gray_image.size(), CV_64FC1);\n    cv::Mat integral_sqimg(gray_image.size(), CV_64FC1), rowsum_sqimg(gray_image.size(), CV_64FC1);\n\n    int xmin, ymin, xmax, ymax;\n    double diagsum, idiagsum, diff, sqdiagsum, sqidiagsum, sqdiff, area;\n    double mean, std, threshold;\n\n    cv::integral(gray_image, integral_image, integral_sqimg, CV_64F);\n    //Calculate the mean and standard deviation using the integral image\n\n    for (int i = 0; i < image_width; i++){\n      for (int j = 0; j < image_height; j++){\n        xmin = cv::max(0, i - whalf);\n        ymin = cv::max(0, j - whalf);\n        xmax = cv::min(image_width - 1, i + whalf);\n        ymax = cv::min(image_height - 1, j + whalf);\n        xmin++; ymin++; xmax++; ymax++;//first column/row is empty...\n        area = (xmax - xmin + 1)*(ymax - ymin + 1);\n        if (xmin <= 1 && ymin <= 1){ // Point at origin\n          diff = integral_image.at<double>(ymax, xmax);\n          sqdiff = integral_sqimg.at<double>(ymax, xmax);\n        }\n        else if (xmin <= 1 && ymin > 1){ // first column\n          diff = integral_image.at<double>(ymax, xmax) - integral_image.at<double>(ymin - 1, xmax);\n          sqdiff = integral_sqimg.at<double>(ymax, xmax) - integral_sqimg.at<double>(ymin - 1, xmax);\n        }\n        else if (xmin > 1 && ymin <= 1){ // first row\n          diff = integral_image.at<double>(ymax, xmax) - integral_image.at<double>(ymax, xmin - 1);\n          sqdiff = integral_sqimg.at<double>(ymax, xmax) - integral_sqimg.at<double>(ymax, xmin - 1);\n        }\n        else{ // rest of the image\n          diagsum = integral_image.at<double>(ymax, xmax) + integral_image.at<double>(ymin - 1, xmin - 1);\n          idiagsum = integral_image.at<double>(ymin - 1, xmax) + integral_image.at<double>(ymax, xmin - 1);\n          diff = diagsum - idiagsum;\n          sqdiagsum = integral_sqimg.at<double>(ymax, xmax) + integral_sqimg.at<double>(ymin - 1, xmin - 1);\n          sqidiagsum = integral_sqimg.at<double>(ymin - 1, xmax) + integral_sqimg.at<double>(ymax, xmin - 1);\n          sqdiff = sqdiagsum - sqidiagsum;\n        }\n\n        mean = diff / area;\n        double var = (sqdiff - (diff*diff / area)) / area;\n        if (var < 0)\n          var = 0;\n        std = sqrt(var);\n        threshold = mean*(1.0 + k*((std / 128.0) - 1.0));\n\n        if (gray_image.at<uchar>(j, i) <= threshold)\n          out.at<uchar>(j, i) = 0;\n        else\n          out.at<uchar>(j, i) = 254;\n      }\n    }\n    return out;\n  }\n\n  bool BinarizeBlock::run(bool oneShot){\n    if (_myInputs[\"BLOCK__BINARIZE_IN_IMAGE\"].isDefaultValue())\n      return false;\n\n    cv::Mat mat = _myInputs[\"BLOCK__BINARIZE_IN_IMAGE\"].get<cv::Mat>();\n    if (!mat.empty())\n    {\n      cv::Mat output = MatrixConvertor::adjustChannels(mat.clone(), 1);\n      double threshold = 128;\n      int winSize = 15;\n      switch (_myInputs[\"BLOCK__BINARIZE_IN_METHOD\"].get<int>())\n      {\n      case 1://Otsu\n        cv::threshold(output, output, 128, 255, cv::THRESH_OTSU);\n        break;\n      case 2://Adaptative\n        cv::adaptiveThreshold(output, output, 255, cv::ADAPTIVE_THRESH_MEAN_C, cv::THRESH_BINARY,\n          _mySubParams[\"BLOCK__BINARIZE_IN_METHOD.Adaptative.window size\"].get<int>(),\n          _mySubParams[\"BLOCK__BINARIZE_IN_METHOD.Adaptative.threshold\"].get<double>()\n          );\n        break;\n      case 3://Sauvola\n        output = binarizeSauvolaIntegral(output, _mySubParams[\"BLOCK__BINARIZE_IN_METHOD.Sauvola.window size\"].get<int>(),\n          _mySubParams[\"BLOCK__BINARIZE_IN_METHOD.Sauvola.threshold\"].get<double>()\n          );\n        break;\n      default://Simple threshold\n        threshold = _mySubParams[\"BLOCK__BINARIZE_IN_METHOD.Simple threshold.threshold\"].get<double>();\n        cv::threshold(output, output, threshold, 255, cv::THRESH_BINARY);\n      }\n\n      _myOutputs[\"BLOCK__BINARIZE_OUT_IMAGE\"] = output;\n    }\n    return !mat.empty();\n  };\n};", "meta": {"hexsha": "141b5b667cd3730494995f0444fe37fc6ccc9742", "size": 6365, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Sources/blocks/Binarization.cpp", "max_stars_repo_name": "Petititi/imGraph", "max_stars_repo_head_hexsha": "068890ffe2f8fa1fb51bc95b8d9296cc79737fac", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T11:27:45.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-25T18:24:38.000Z", "max_issues_repo_path": "Sources/blocks/Binarization.cpp", "max_issues_repo_name": "Petititi/imGraph", "max_issues_repo_head_hexsha": "068890ffe2f8fa1fb51bc95b8d9296cc79737fac", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2015-01-07T11:59:07.000Z", "max_issues_repo_issues_event_max_datetime": "2015-04-24T13:02:01.000Z", "max_forks_repo_path": "Sources/blocks/Binarization.cpp", "max_forks_repo_name": "Petititi/imGraph", "max_forks_repo_head_hexsha": "068890ffe2f8fa1fb51bc95b8d9296cc79737fac", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-20T12:18:18.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-20T12:18:18.000Z", "avg_line_length": 40.8012820513, "max_line_length": 134, "alphanum_fraction": 0.6636292223, "num_tokens": 1791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2835250718708513}}
{"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\n#include <eigen3/Eigen/Core>\n#include <eigen3/Eigen/Dense>\n#include <eigen3/Eigen/Geometry>\n\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\n#include <kdl_parser/kdl_parser.hpp>\n\n\n#include <urdf/model.h>\n\n\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <cstdlib>\n#include <string>\n\n\n#include <cmath>\n#include <ctime>\n#include <time.h>\n\n#include \"pseudo_inverse.h\"\n\n\n\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace KDL;\n\n\n\n\n\n\n\n// take it from yaml file\nint n_rows;\nint n_cols;\nint quality_index;\nstring relative_path_file;\nstring file_name;\nstd::vector<double> Quality;\nint n_c_max = 19; // number of contact point, assumed that 1 contact point for each phalanx \n\n\n\n\n\nint main (int argc, char **argv)\n{\n\n\tros::init(argc, argv, \"Hand_Jacobian\");\t// ROS node\n\tros::NodeHandle nh;\n\n\n  \n\n\n  nh.param<int>(\"n_rows_file\",n_rows,108);\n  nh.param<int>(\"n_cols_file\",n_cols,86);\n  nh.param<int>(\"quality_index\",quality_index,0);\n  nh.param<std::string>(\"file_name\", relative_path_file, \"/db/box_db_2.csv\" );\n\n  std::string path = ros::package::getPath(\"grasp_learning\");\n  file_name = path + relative_path_file ;\n  ifstream file(file_name); \n\n\n  std::cout << \"file: \" << file_name.c_str() << \" is \" << (file.is_open() == true ? \"already\" : \"not\") << \" open\" << std::endl;\n  if(!file.is_open())\n  return 0;\n\n\n\n  ////////////////////////////////////////////////////////////////////////////////////\n\t /////////////////////////////////////////////////////////////////////////\n\n  //\tTAKE DATA_BASE : load a file .csv and put the values into Eigen::MatrixXd\n\n  ////////////////////////////////////////////////////////////////////////////////////\n\t /////////////////////////////////////////////////////////////////////////\n\n\n\n  int count_row = 0;\n  int count_col = 0;\n\n  bool count_cols_only_one = true;\n\n\n  for(std::string line; getline ( file, line, '\\n' ); ) // ciclo sulla riga\n  {\n    count_row++;\n    std::istringstream iss_line(line);  \n\n    if(count_cols_only_one)\n    { \n\n      for(std::string value; getline(iss_line, value, ',' ); )\n          count_col++;\n      \n      count_cols_only_one = false;\n    } \n  }\n\n  cout << \"ROWS : \" << count_row << endl; // 40\n  cout << \"COLS : \" << count_col << endl; // 189\n\n\n\n  Eigen::MatrixXd data_set(count_row,count_col);\n\n\n\tint i = 0;\n\tint j = 0;\n\n\n\n\tfor(std::string line; getline( file, line, '\\n' ); ) // ciclo sulla riga\n\t{\n\n    std::istringstream iss_line(line);\t\n    for(std::string value; getline(iss_line, value, ',' ); )\n    {\n    \tdata_set(i,j) = stod(value);\n    \tj++;\n    }\n\n    //cout << endl;\n    j=0;\n    i++;\n\t}\n\n\n\tfile.close();\n\n\n\n\n\n//\tcout << \" DATA_SET\" << data_set << endl;\n\n\n\n///////////////////////////// \t\tEND\t\t///////////////////////////////////////////\n\t/////////////////////////////////////////////////////////////////////////\n\n\t\t\n\n\n\n////////////////////////////////////////////////////////////////////////////////////\n\t/////////////////////////////////////////////////////////////////////////\n\n//\t\t\t\t\t\t\t\tTAKE SOFT_HAND\n\n////////////////////////////////////////////////////////////////////////////////////\n\t/////////////////////////////////////////////////////////////////////////\n\n\n\n  KDL::Tree hand_tree;\n\n  std::string robot_desc_string;\n  nh.param(\"robot_description\", robot_desc_string, string());  // robot description is the name in the launch file \n  if (!kdl_parser::treeFromString(robot_desc_string, hand_tree))\n  { ROS_ERROR(\"Failed to construct kdl tree\"); return false;}\n\n\n  KDL::Chain chains_hand_finger[5];\n  KDL::Jacobian hand_jacob[5];\n\n  \n  //std::string root_name = \"right_hand_softhand_base\";\n  //std::string root_name = \"right_hand_palm_link\";\n  std::string root_name = \"world\";\n  std::string end_chain_name[5];\n  end_chain_name[0] = \"right_hand_thumb_distal_link\";\n  end_chain_name[1] = \"right_hand_index_distal_link\";\n  end_chain_name[2] = \"right_hand_middle_distal_link\";\n  end_chain_name[3] = \"right_hand_ring_distal_link\";\n  end_chain_name[4] = \"right_hand_little_distal_link\";\n\n\n  hand_tree.getChain(root_name, end_chain_name[0], chains_hand_finger[0]);      //thumb\n  hand_tree.getChain(root_name, end_chain_name[1], chains_hand_finger[1]);      //index\n  hand_tree.getChain(root_name, end_chain_name[2], chains_hand_finger[2]);      //middle\n  hand_tree.getChain(root_name, end_chain_name[3], chains_hand_finger[3]);      //ring\n  hand_tree.getChain(root_name, end_chain_name[4], chains_hand_finger[4]);      //little\n\n\n  int nq_hand = hand_tree.getNrOfJoints();  // 34\n  int ns_hand = hand_tree.getNrOfSegments(); // 39\n\n\n  cout << \"number_of_joint_in_hand : \" << nq_hand << endl;\n  cout << \"number_of_segment_in_hand : \" << ns_hand << endl;\n\n\n\n\n///////////////////////////// \t\tEND\t\t  ///////////////////////////////////////////\n\t/////////////////////////////////////////////////////////////////////////\n\n\t\t\n\t\t\n////////////////////////////////////////////////////////////////////////////////////\n\t/////////////////////////////////////////////////////////////////////////\n\n//\t\t\tCALCULATE THE GRASP_MATRIX AND HAND_JACOBIAN FOR EACH ROW\n//\tI supposed to have 19 joint variables and a single point of contact for each phalanx\n\n////////////////////////////////////////////////////////////////////////////////////\n\t/////////////////////////////////////////////////////////////////////////\n\n\n\n\tunsigned int nj_0 = chains_hand_finger[0].getNrOfJoints();  // 5\n  unsigned int nj_1 = chains_hand_finger[1].getNrOfJoints();  // 7\n  unsigned int nj_2 = chains_hand_finger[2].getNrOfJoints();  // 7\n  unsigned int nj_3 = chains_hand_finger[3].getNrOfJoints();  // 7\n  unsigned int nj_4 = chains_hand_finger[4].getNrOfJoints();  // 7 \n\n\n\n  KDL::JntArray q_thumb = JntArray(nj_0);    // thumb\n  KDL::JntArray q_index = JntArray(nj_1);    // forefinger\n  KDL::JntArray q_middle = JntArray(nj_2);   // middlefinger\n  KDL::JntArray q_ring = JntArray(nj_3);     // ringfinger\n  KDL::JntArray q_little = JntArray(nj_4);   // littlefinger\n\n\n  cout << \"nj_0 : \" << nj_0 << endl;\n  cout << \"nj_1 : \" << nj_1 << endl;\n  cout << \"nj_2 : \" << nj_2 << endl;\n  cout << \"nj_3 : \" << nj_3 << endl;\n  cout << \"nj_4 : \" << nj_4 << endl;\n\n\n\n\n\n  boost::scoped_ptr<KDL::ChainJntToJacSolver> jnt_to_jac_solver_0;\n  boost::scoped_ptr<KDL::ChainJntToJacSolver> jnt_to_jac_solver_1;\n  boost::scoped_ptr<KDL::ChainJntToJacSolver> jnt_to_jac_solver_2;\n  boost::scoped_ptr<KDL::ChainJntToJacSolver> jnt_to_jac_solver_3;\n  boost::scoped_ptr<KDL::ChainJntToJacSolver> jnt_to_jac_solver_4;\n\n\n  // constructs the kdl solvers in non-realtime\n  jnt_to_jac_solver_0.reset(new KDL::ChainJntToJacSolver(chains_hand_finger[0]));\n  jnt_to_jac_solver_1.reset(new KDL::ChainJntToJacSolver(chains_hand_finger[1]));\n  jnt_to_jac_solver_2.reset(new KDL::ChainJntToJacSolver(chains_hand_finger[2]));\n  jnt_to_jac_solver_3.reset(new KDL::ChainJntToJacSolver(chains_hand_finger[3]));\n  jnt_to_jac_solver_4.reset(new KDL::ChainJntToJacSolver(chains_hand_finger[4]));\n\n\n\n\n\n   \t\t\n\n\n  // resizes the joint state vectors in non-realtime\n  q_thumb.resize(chains_hand_finger[0].getNrOfJoints());\n  q_index.resize(chains_hand_finger[1].getNrOfJoints());\n  q_middle.resize(chains_hand_finger[2].getNrOfJoints());\n  q_ring.resize(chains_hand_finger[3].getNrOfJoints());\n  q_little.resize(chains_hand_finger[4].getNrOfJoints());\n\n  hand_jacob[0].resize(chains_hand_finger[0].getNrOfJoints());\n  hand_jacob[1].resize(chains_hand_finger[1].getNrOfJoints());\n  hand_jacob[2].resize(chains_hand_finger[2].getNrOfJoints());\n \thand_jacob[3].resize(chains_hand_finger[3].getNrOfJoints());\n  hand_jacob[4].resize(chains_hand_finger[4].getNrOfJoints());\n\n\n\n\n\tfor(int r = 0; r < n_rows ; r++)  // for each row calculation the grasp matrix and hand jacobian\n\t{\n\t\t//take the value of joints from data\t\t\n\t\t// initialize jntarray then be able to calculate the Jacobian to that point of contact\n\n\n\t\tq_thumb(0) = data_set(r,10);\n\n\t\tq_thumb(1) = data_set(r,11) / 2;\n\t\tq_thumb(2) = data_set(r,11) / 2;\n\n\t\tq_thumb(3) = data_set(r,12) / 2;\n\t\tq_thumb(4) = data_set(r,12) / 2;\n\n\n\n\t\tq_index(0) = data_set(r,13);\n\n\t\tq_index(1) = data_set(r,14) / 2;\n\t\tq_index(2) = data_set(r,14) / 2;\n\n\t\tq_index(3) = data_set(r,15) / 2;\n\t\tq_index(4) = data_set(r,15) / 2;\n\n\t\tq_index(5) = data_set(r,16) / 2;\n\t\tq_index(6) = data_set(r,16) / 2;\n\n\n\n\t\tq_middle(0) = data_set(r,17);\n\n\t\tq_middle(1) = data_set(r,18) / 2;\n\t\tq_middle(2) = data_set(r,18) / 2;\n\n\t\tq_middle(3) = data_set(r,19) / 2;\n\t\tq_middle(4) = data_set(r,19) / 2;\n\n\t\tq_middle(5) = data_set(r,20) / 2;\n\t\tq_middle(6) = data_set(r,20) / 2;\n\n\n\n\t\tq_ring(0) = data_set(r,21);\n\n\t\tq_ring(1) = data_set(r,22) / 2;\n\t\tq_ring(2) = data_set(r,22) / 2;\n\n\t\tq_ring(3) = data_set(r,23) / 2;\n\t\tq_ring(4) = data_set(r,23) / 2;\n\n\t\tq_ring(5) = data_set(r,24) / 2;\n\t\tq_ring(6) = data_set(r,24) / 2;\n\n\n\n\n\n\t\tq_little(0) = data_set(r,25);\n\n\t\tq_little(1) = data_set(r,26) / 2;\n\t\tq_little(2) = data_set(r,26) / 2;\n\n\t\tq_little(3) = data_set(r,27) / 2;\n\t\tq_little(4) = data_set(r,27) / 2;\n\n\t\tq_little(5) = data_set(r,28) / 2;\n\t\tq_little(6) = data_set(r,28) / 2;\n\n\n\n\n\n\n\t\tEigen::MatrixXd Contacts(n_c_max,3); // I build a matrix of contact points for convenience only\n\t\t\t\t\t\t\t\t\t\t // each row is a contact point\n\t\t\t\t\t\t\t\t\t\t // row 0, 1, 2 for thumb\n\t\t\t\t\t\t\t\t\t\t // row 3, 4, 5, 6 for index\n\t\t\t\t\t\t\t\t\t\t // row 7, 8, 9, 10 for middle\n\t\t\t\t\t\t\t\t\t\t // row 11, 12, 13, 14 for ring\n\t\t\t\t\t\t\t\t\t\t // row 15, 16, 17, 18 for little\n\t\t\t\t\t\t\t\t\t\t // n_c = 19 ( number of contact)\n\n\n\n\t\t\n\t int start = 29; // the first value for the position of the joint variables\n\t int gap_point_coordinate = 0;\n\n\t\tfor(int i = 0; i < n_c_max; i++)\n\t\t{\t\n\t\t\tfor(int j = 0; j < 3; j++ )\n\t\t\t\tContacts(i,j) = data_set(r, start + gap_point_coordinate + j);  // check if it is correct\n\n\t\t\tgap_point_coordinate += 3;\n\t\t}\n\n\n    cout << \"Contacts : \" << Contacts << endl;\n\n\n\n\n\n\n\t\t\n    //for each contact point \n\t\tstd::vector<Eigen::MatrixXd> Grasp_Matrix_ ;  \n    std::vector<Eigen::MatrixXd> Hand_Jacobian_ ;\n\n\n    int k = 1;\n\n\n    for(int i = 0 ; i < n_c_max ; i++) //calc the grasp_matrix and hand_jacobian for each contact point\n    {\n\n      if(Contacts(i,0) != 9999) //9999 similar to NaN in dataset\n      {\t\n\n        Eigen::MatrixXd Grasp_Matrix(6,6);  \n \t\t\t\tEigen::MatrixXd Skew_Matrix(3,3);\n  \t\t\tEigen::MatrixXd Rotation(3,3);\n\n  \t\t\tRotation <<  MatrixXd::Identity(3,3); \n\n\n  \t\t\t\t\n        //check if the values ​​of the skew matrix are expressed in the correct reference system\n      \tSkew_Matrix(0,0) = Skew_Matrix(1,1) = Skew_Matrix(2,2) = 0;\n        Skew_Matrix(0,1) = - Contacts(i,2); // -rz    \n        Skew_Matrix(0,2) = Contacts(i,1);   // ry\n        Skew_Matrix(1,0) = Contacts(i,2);   // rz\n        Skew_Matrix(2,0) = - Contacts(i,1); // -ry\n        Skew_Matrix(1,2) = - Contacts(i,0); // -rx\n        Skew_Matrix(2,1) = Contacts(i,0);   // rx\n\n\n\n        Grasp_Matrix.block<3,3>(0,0) = Rotation;\n        Grasp_Matrix.block<3,3>(3,3) = Rotation;\n        Grasp_Matrix.block<3,3>(0,3) = Skew_Matrix * Rotation;\n        Grasp_Matrix.block<3,3>(3,0) = MatrixXd::Zero(3,3);\n\n\n        cout << \"Grasp_Matrix\" << endl;\n        cout << Grasp_Matrix << endl;\n\n\n        Grasp_Matrix_.push_back(Grasp_Matrix);\n\n\n\n        jnt_to_jac_solver_0->JntToJac(q_thumb, hand_jacob[0], 0);\n      \tjnt_to_jac_solver_1->JntToJac(q_index, hand_jacob[1], 0);\n      \tjnt_to_jac_solver_2->JntToJac(q_middle, hand_jacob[2], 0);\n      \tjnt_to_jac_solver_3->JntToJac(q_ring, hand_jacob[3], 0);\n   \t\t\tjnt_to_jac_solver_4->JntToJac(q_little, hand_jacob[4], 0);\n\n   \t\t\tcout << \"Hand_Jacobian_ THUMB\" << endl;\n      \tcout <<  hand_jacob[0].data << endl;\n      \tcout << \"Hand_Jacobian_ INDEX\" << endl;\n    \t\tcout <<  hand_jacob[1].data << endl;\n  \t\t\tcout << \"Hand_Jacobian_ MIDDLE\"<< endl;\n   \t\t\tcout <<  hand_jacob[2].data << endl;\n      \tcout << \"Hand_Jacobian_ RING\"  << endl;\n    \t\tcout <<  hand_jacob[3].data << endl;\n  \t\t\tcout << \"Hand_Jacobian_ LITTLE\"<< endl;\n  \t\t\tcout <<  hand_jacob[4].data << endl;\n\n\n\n      \tint which_finger = 0;\n        int which_falange = 0;\n            \t\n\n\n        if((0 <= i) && (i <= 2)){ which_finger = 0; which_falange = i+k; k++; if(i==2) k = 1;} // control flag which_falange there may be some error\n        if((3 <= i) && (i <= 6)){ which_finger = 1; which_falange = i-3+k; k++; if(i==6) k = 1;}\n        if((7 <= i) && (i <= 10)){ which_finger = 2; which_falange = i-7+k; k++; if(i==10) k = 1;}\n        if((11 <= i) && (i <= 14)){ which_finger = 3; which_falange = i-11+k; k++; if(i==14) k = 1;}\n        if((15 <= i) && (i <= 18)){ which_finger = 4; which_falange = i-15+k; k++; if(i==18) k = 1;}\n\n\n\n        cout << \"i : \" << i << endl;\n        cout << \"which_finger : \" << which_finger << endl;\n        cout << \"which_falange : \" << which_falange << endl;\n\n\n        switch(which_finger)\n        {\n          case 0: // thumb\n      \t\t\t\t\t\tjnt_to_jac_solver_0->JntToJac(q_thumb, hand_jacob[0], which_falange);\n      \t\t\t\t\t\tbreak;\n\n\t  \t\t\tcase 1: // index\n      \t\t\t\t\t\tjnt_to_jac_solver_1->JntToJac(q_index, hand_jacob[1], which_falange);\n      \t\t\t\t\t\tbreak;\n\n\t  \t\t\tcase 2: // middle\n\t\t\t\t\t\t\tjnt_to_jac_solver_2->JntToJac(q_middle, hand_jacob[2], which_falange);\n      \t\t\t\t\t\tbreak;\n\n\t  \t\t\tcase 3: // ring\n      \t\t\t\t\t\tjnt_to_jac_solver_3->JntToJac(q_ring, hand_jacob[3], which_falange);\n\t  \t\t\t\t\t\tbreak;\n\n\t  \t\t\tcase 4: // little\n      \t\t\t\t\t\tjnt_to_jac_solver_4->JntToJac(q_little, hand_jacob[4], which_falange);\n\t  \t\t\t\t\t\tbreak;\n\t  \t\t}// end switch\n\n\t  \t\tcout << \" Jacobian thumb \" << hand_jacob[0].data << endl ;\n\t  \t\tcout << \" Jacobian index \" << hand_jacob[1].data << endl ;\n\t  \t  cout << \" Jacobian middle \" << hand_jacob[2].data << endl ;\n\t\t\t  cout << \" Jacobian ring \" << hand_jacob[3].data << endl ;\n\t\t\t  cout << \" Jacobian little \" << hand_jacob[4].data << endl ;\n\n\n\n\n\n\t  \t\tHand_Jacobian_.push_back(hand_jacob[0].data); // 5\n\t  \t\tHand_Jacobian_.push_back(hand_jacob[1].data); // 7\n\t \t\t  Hand_Jacobian_.push_back(hand_jacob[2].data); // 7\n\t  \t\tHand_Jacobian_.push_back(hand_jacob[3].data); // 7\n\t  \t\tHand_Jacobian_.push_back(hand_jacob[4].data); // 7\n\n\n\n\n      }// end if  contact\n        \t\n\t\t\n\n\n      }\t// end for contact\n\n\n      cout << \" Dim of the vectors of the matrices grasp \" << Grasp_Matrix_.size() << endl;\n      cout << \" Dim of the hand jacobian \" << Hand_Jacobian_.size() << endl;\n\n\n      int n_c_eff = Grasp_Matrix_.size();\n\n      \n        \n      Eigen::MatrixXd Hand_Jacobian_Contact(6*n_c_eff,nq_hand-1);\n      Eigen::MatrixXd Grasp_Matrix_Contact(6,6*n_c_eff);\n\n\n\n      int s = 0; // dimension \n      int s_ = 0;\n\n\n      for(int i = 0; i < n_c_eff; i++)\n      {\n\n        Grasp_Matrix_Contact.block<6,6>(0,s) = Grasp_Matrix_[i];\n        \t\n        cout << \"i : \" << i << endl;\n\n      \tHand_Jacobian_Contact.block<6,5>(s,0) = Hand_Jacobian_[s_];\n      \tHand_Jacobian_Contact.block<6,7>(s,5) = Hand_Jacobian_[s_+1];\n      \tHand_Jacobian_Contact.block<6,7>(s,12) = Hand_Jacobian_[s_+2];\n      \tHand_Jacobian_Contact.block<6,7>(s,19) = Hand_Jacobian_[s_+3];\n      \tHand_Jacobian_Contact.block<6,7>(s,26) = Hand_Jacobian_[s_+4];\n\t\t\t\n  \t\t\ts_+=5;\n       \ts+=6;\n      }\n\n/*\n        file_output << \"Grasp_Matrix_Contact : \" << endl;\n        file_output <<  Grasp_Matrix_Contact << endl;\n        file_output << \"__________________________________________________\" << endl;\n        file_output << \"Hand_Jacobian_Contact : \" << endl;\n        file_output << Hand_Jacobian_Contact << endl;\n*/\n\n        // GRASP JACOBIAN\n\n\n      Eigen::MatrixXd GRASP_Jacobian(6,nq_hand-1);\n      Eigen::MatrixXd Grasp_Matrix_pseudo(Grasp_Matrix_Contact.rows(),Grasp_Matrix_Contact.cols()) ;\n      pseudo_inverse(Grasp_Matrix_Contact,Grasp_Matrix_pseudo);\n\n      GRASP_Jacobian = Grasp_Matrix_pseudo.transpose() * Hand_Jacobian_Contact;\n\n\n      cout << \"GRASP_Jacobian : \" << endl;\n      cout << GRASP_Jacobian << endl;\n\n\n      int quality_ = 9999;\n      Eigen::VectorXd Singular;\n      double sigma_min ;\n\t\t  double sigma_max ;\n\n\n\n      switch(quality_index) \n      {\n        \n        case 0: // \"minimum_singular_value_of_G\"  Q = sigma_min(G)\n\t\t\t\t      {\n        \t   \t\tJacobiSVD<MatrixXd> svd0(Grasp_Matrix_Contact, ComputeThinU | ComputeThinV);  \n        \t\t\t\tSingular = svd0.singularValues();\n\n\t\t\t\t    \t\tQuality.push_back(Singular[Singular.size()-1]);\n\t\t\t\t      } \n        \t\t  break;\n\n\n        case 1: // \"Volume of the ellipsoid in the wrench space\"  Q = K sqrt(det(GG.t)) = k ( sigma_0 **** sigma_d)\n        \t\t  {\n                Eigen::MatrixXd G_G_t = Grasp_Matrix_Contact * Grasp_Matrix_Contact.transpose();\n\t\t\t\t\t      JacobiSVD<MatrixXd> svd1(G_G_t, ComputeThinU | ComputeThinV);  \n\t\t\t\t\t      Singular = svd1.singularValues();\n\n\t\t\t\t        for(int i = 0 ; i < Singular.size() ; i++)\n\t\t\t\t\t\t        quality_ *= Singular[i];\n\n\t\t\t\t\t     Quality.push_back(quality_);\n\t\t\t\t      }\n        \t\t  break;\n\n\n        case 2: // \"Grasp isotropy index\" Q = sigma_min(G) / sigma_max(G) \n        \t\t {\n        \t\t\t  JacobiSVD<MatrixXd> svd2(Grasp_Matrix_Contact, ComputeThinU | ComputeThinV);  \n\t\t\t\t\t      Singular = svd2.singularValues();\n                sigma_min = Singular[Singular.size()-1];\n\t\t\t\t\t      sigma_max = Singular[0];\n\n\t\t\t\t\t      Quality.push_back(sigma_min/sigma_max);\n\t\t\t\t      }\n\t\t\t\t      break;\n\n\n\n\t\t\tcase 3: // \"Distance to singular configuration\" Q = sigma_min(H) H = G.pseudo_inverse.transpose * J\n\t\t\t\t    {\n\t\t\t\t\t    JacobiSVD<MatrixXd> svd3(GRASP_Jacobian, ComputeThinU | ComputeThinV);  \n\t\t\t\t\t    Singular = svd3.singularValues();\n            \n              Quality.push_back(Singular[Singular.size()-1]);\n\t\t\t\t    }\n\t\t\t\t    break;\n\n\n\n\t\t\tcase 4: // \"Volume of manipulability ellipsoid\" \n\t\t\t\t{\n\t\t\t\t\tEigen::MatrixXd H_H_t = GRASP_Jacobian * GRASP_Jacobian.transpose();\n\n\t\t\t\t\tJacobiSVD<MatrixXd> svd4(H_H_t, ComputeThinU | ComputeThinV);  \n\n        \t\t\n\t\t\t\t\tSingular = svd4.singularValues();\n\n\t\t\t\t\t\n\t\t\t\t\tfor(int i = 0 ; i < Singular.size() ; i++)\n\t\t\t\t\t\tquality_ *= Singular[i];\n\n\n\t\t\t\t\tQuality.push_back(quality_);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\n\t\t\tcase 5: // \"Uniformity of transformations\"\n\t\t\t\t{\n\t\t\t\t\tJacobiSVD<MatrixXd> svd5(GRASP_Jacobian, ComputeThinU | ComputeThinV);  \n\n        \t\t\t\n\t\t\t\t\tSingular = svd5.singularValues();\n\n\t\t\t\t\tsigma_min = Singular[Singular.size()-1];\n\t\t\t\t\tsigma_max = Singular[0];\n\n\t\t\t\t\tQuality.push_back(sigma_min/sigma_max);\n\t\t\t\t}\n\t\t\t\tbreak;\n      }//end switch\n\n        \n    cout << \"Quality : \" << endl;\n\n\n    for(int i = 0; i < Quality.size(); i++)\n\t\t\tcout << Quality[i] << ' '; \n    cout << endl;\n\t} \n  // end for each row\n\n\n  \n\n  cout << \" YEAH ENJOY \" << endl;\n  cout << \"   fine   \" << endl;\n\n\n\tros::spin();\n\treturn 0;\n}", "meta": {"hexsha": "a83c5d9ff1a3af309ee6d9282ad6ff9af5dc8f49", "size": 20413, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/grasp_quality_.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/grasp_quality_.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/grasp_quality_.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": 27.5479082321, "max_line_length": 148, "alphanum_fraction": 0.5985891344, "num_tokens": 5950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.28341134638352194}}
{"text": "/*\n * Copyright (c) 2011-2017, The DART development contributors\n * All rights reserved.\n *\n * The list of contributors can be found at:\n *   https://github.com/dartsim/dart/blob/master/LICENSE\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#ifndef DART_MATH_CONFIGURATIONSPACE_HPP_\n#define DART_MATH_CONFIGURATIONSPACE_HPP_\n\n#include <Eigen/Dense>\n#include \"dart/math/MathTypes.hpp\"\n#include \"dart/math/Geometry.hpp\"\n\nnamespace dart {\nnamespace math {\n\n//==============================================================================\ntemplate <std::size_t Dimension>\nstruct RealVectorSpace\n{\n  static constexpr std::size_t NumDofs = Dimension;\n  static constexpr int NumDofsEigen = static_cast<int>(Dimension);\n\n  using TangentSpace = RealVectorSpace<NumDofs>;\n\n  using Point          = Eigen::Matrix<double, NumDofs, 1>;\n  using EuclideanPoint = Eigen::Matrix<double, NumDofs, 1>;\n  using Vector         = Eigen::Matrix<double, NumDofs, 1>;\n  using Matrix         = Eigen::Matrix<double, NumDofs, NumDofs>;\n  using JacobianMatrix = Eigen::Matrix<double, 6, NumDofs>;\n};\n\n//==============================================================================\n//\n// These namespace-level definitions are required to enable ODR-use of static\n// constexpr member variables.\n//\n// See this StackOverflow answer: http://stackoverflow.com/a/14396189/111426\n//\ntemplate <std::size_t Dimension>\nconstexpr std::size_t RealVectorSpace<Dimension>::NumDofs;\ntemplate <std::size_t Dimension>\nconstexpr int RealVectorSpace<Dimension>::NumDofsEigen;\n\nusing NullSpace = RealVectorSpace<0u>;\nusing R1Space = RealVectorSpace<1u>;\nusing R2Space = RealVectorSpace<2u>;\nusing R3Space = RealVectorSpace<3u>;\n\n//==============================================================================\nstruct SO3Space\n{\n  static constexpr std::size_t NumDofs = 3u;\n  static constexpr int NumDofsEigen = 3;\n\n  using TangentSpace = RealVectorSpace<NumDofs>;\n\n  using Point          = Eigen::Matrix3d;\n  using EuclideanPoint = Eigen::Vector3d;\n  using Vector         = Eigen::Vector3d;\n  using Matrix         = Eigen::Matrix3d;\n  using JacobianMatrix = Eigen::Matrix<double, 6, NumDofs>;\n};\n\n//==============================================================================\nstruct SE3Space\n{\n  static constexpr std::size_t NumDofs = 6u;\n  static constexpr int NumDofsEigen = 6;\n\n  using TangentSpace = RealVectorSpace<NumDofs>;\n\n  using Point          = Eigen::Isometry3d;\n  using EuclideanPoint = Eigen::Vector6d;\n  using Vector         = Eigen::Vector6d;\n  using Matrix         = Eigen::Matrix6d;\n  using JacobianMatrix = Eigen::Matrix6d;\n};\n\nstruct MapsToManifoldPoint {};\n\n//==============================================================================\ntemplate <typename SpaceT>\ntypename SpaceT::Matrix inverse(const typename SpaceT::Matrix& mat);\n\n//==============================================================================\ntemplate <typename SpaceT>\ntypename SpaceT::EuclideanPoint\ntoEuclideanPoint(const typename SpaceT::Point& point);\n\n//==============================================================================\ntemplate <typename SpaceT>\ntypename SpaceT::Point\ntoManifoldPoint(const typename SpaceT::EuclideanPoint& point);\n\n//==============================================================================\ntemplate <typename SpaceT>\ntypename SpaceT::Point integratePosition(\n    const typename SpaceT::Point& pos,\n    const typename SpaceT::Vector& vel,\n    double dt);\n\n//==============================================================================\ntemplate <typename SpaceT>\ntypename SpaceT::Vector integrateVelocity(\n    const typename SpaceT::Vector& vel,\n    const typename SpaceT::Vector& acc,\n    double dt);\n\n} // namespace math\n} // namespace dart\n\n#include \"dart/math/detail/ConfigurationSpace.hpp\"\n\n#endif // DART_MATH_CONFIGURATIONSPACE_HPP_\n", "meta": {"hexsha": "dc53eef0b3e86e47f6af1e58a3a9febecc93809f", "size": 5210, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dart/math/ConfigurationSpace.hpp", "max_stars_repo_name": "malasiot/dart-vsim-octomap", "max_stars_repo_head_hexsha": "d7afcacdcdcf7da688fb61caf1761b1309888ffe", "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": "dart/math/ConfigurationSpace.hpp", "max_issues_repo_name": "malasiot/dart-vsim-octomap", "max_issues_repo_head_hexsha": "d7afcacdcdcf7da688fb61caf1761b1309888ffe", "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/math/ConfigurationSpace.hpp", "max_forks_repo_name": "malasiot/dart-vsim-octomap", "max_forks_repo_head_hexsha": "d7afcacdcdcf7da688fb61caf1761b1309888ffe", "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.6901408451, "max_line_length": 80, "alphanum_fraction": 0.6387715931, "num_tokens": 1090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.2834113463835219}}
{"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_GSTMERC_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_GSTMERC_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_phi2.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_tsfn.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 gstmerc\r\n    {\r\n            template <typename T>\r\n            struct par_gstmerc\r\n            {\r\n                T lamc;\r\n                T phic;\r\n                T c;\r\n                T n1;\r\n                T n2;\r\n                T XS;\r\n                T YS;\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_gstmerc_spheroid\r\n                : public base_t_fi<base_gstmerc_spheroid<T, Parameters>, T, Parameters>\r\n            {\r\n                par_gstmerc<T> m_proj_parm;\r\n\r\n                inline base_gstmerc_spheroid(const Parameters& par)\r\n                    : base_t_fi<base_gstmerc_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                    T L, Ls, sinLs1, Ls1;\r\n\r\n                    L= this->m_proj_parm.n1*lp_lon;\r\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));\r\n                    sinLs1= sin(L)/cosh(Ls);\r\n                    Ls1= log(pj_tsfn(-1.0*asin(sinLs1),0.0,0.0));\r\n                    xy_x= (this->m_proj_parm.XS + this->m_proj_parm.n2*Ls1)*this->m_par.ra;\r\n                    xy_y= (this->m_proj_parm.YS + this->m_proj_parm.n2*atan(sinh(Ls)/cos(L)))*this->m_par.ra;\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 const& xy_x, T const& xy_y, T& lp_lon, T& lp_lat) const\r\n                {\r\n                    T L, LC, sinC;\r\n\r\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));\r\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);\r\n                    LC= log(pj_tsfn(-1.0*asin(sinC),0.0,0.0));\r\n                    lp_lon= L/this->m_proj_parm.n1;\r\n                    lp_lat= -1.0*pj_phi2(exp((LC-this->m_proj_parm.c)/this->m_proj_parm.n1),this->m_par.e);\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"gstmerc_spheroid\";\r\n                }\r\n\r\n            };\r\n\r\n            // Gauss-Schreiber Transverse Mercator (aka Gauss-Laborde Reunion)\r\n            template <typename Parameters, typename T>\r\n            inline void setup_gstmerc(Parameters& par, par_gstmerc<T>& proj_parm)\r\n            {\r\n                proj_parm.lamc= par.lam0;\r\n                proj_parm.n1= sqrt(T(1)+par.es*math::pow(cos(par.phi0),4)/(T(1)-par.es));\r\n                proj_parm.phic= asin(sin(par.phi0)/proj_parm.n1);\r\n                proj_parm.c= log(pj_tsfn(-1.0*proj_parm.phic,0.0,0.0))\r\n                           - proj_parm.n1*log(pj_tsfn(-1.0*par.phi0,-1.0*sin(par.phi0),par.e));\r\n                proj_parm.n2= par.k0*par.a*sqrt(1.0-par.es)/(1.0-par.es*sin(par.phi0)*sin(par.phi0));\r\n                proj_parm.XS= 0;/* -par.x0 */\r\n                proj_parm.YS= -1.0*proj_parm.n2*proj_parm.phic;/* -par.y0 */\r\n            }\r\n\r\n    }} // namespace detail::gstmerc\r\n    #endif // doxygen\r\n\r\n    /*!\r\n        \\brief Gauss-Schreiber Transverse Mercator (aka Gauss-Laborde Reunion) 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 Projection parameters\r\n         - lat_0: Latitude of origin\r\n         - lon_0: Central meridian\r\n         - k_0: Scale factor\r\n        \\par Example\r\n        \\image html ex_gstmerc.gif\r\n    */\r\n    template <typename T, typename Parameters>\r\n    struct gstmerc_spheroid : public detail::gstmerc::base_gstmerc_spheroid<T, Parameters>\r\n    {\r\n        template <typename Params>\r\n        inline gstmerc_spheroid(Params const& , Parameters const& par)\r\n            : detail::gstmerc::base_gstmerc_spheroid<T, Parameters>(par)\r\n        {\r\n            detail::gstmerc::setup_gstmerc(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_gstmerc, gstmerc_spheroid, gstmerc_spheroid)\r\n\r\n        // Factory entry(s)\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(gstmerc_entry, gstmerc_spheroid)\r\n        \r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_BEGIN(gstmerc_init)\r\n        {\r\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(gstmerc, gstmerc_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_GSTMERC_HPP\r\n\r\n", "meta": {"hexsha": "4fa9d7f4f4b76157d6ec3e42548f68a1645d9752", "size": 7792, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "externals/boost/boost/geometry/srs/projections/proj/gstmerc.hpp", "max_stars_repo_name": "YuukiTsuchida/v8_embeded", "max_stars_repo_head_hexsha": "c6e18f4e91fcc50607f8e3edc745a3afa30b2871", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 995.0, "max_stars_repo_stars_event_min_datetime": "2018-06-22T10:39:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T01:22:14.000Z", "max_issues_repo_path": "externals/boost/boost/geometry/srs/projections/proj/gstmerc.hpp", "max_issues_repo_name": "YuukiTsuchida/v8_embeded", "max_issues_repo_head_hexsha": "c6e18f4e91fcc50607f8e3edc745a3afa30b2871", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2018-06-23T14:19:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T10:20:37.000Z", "max_forks_repo_path": "externals/boost/boost/geometry/srs/projections/proj/gstmerc.hpp", "max_forks_repo_name": "YuukiTsuchida/v8_embeded", "max_forks_repo_head_hexsha": "c6e18f4e91fcc50607f8e3edc745a3afa30b2871", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 172.0, "max_forks_repo_forks_event_min_datetime": "2018-06-22T11:12:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:44:33.000Z", "avg_line_length": 42.347826087, "max_line_length": 171, "alphanum_fraction": 0.6162731006, "num_tokens": 1936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.28338103653116503}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// cross_validation::k_fold::partition.hpp                                  //\n//                                                                          //\n//  (C) Copyright 2009 Erwann Rogard                                        //\n//  Use, modification and distribution are subject to the                   //\n//  Boost Software License, Version 1.0. (See accompanying file             //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)        //\n//////////////////////////////////////////////////////////////////////////////\n#ifndef  BOOST_STATISTICS_DETAIL_CROSS_VALIDATION_DATA_K_FOLD_PARTITION_HPP_ER_2009\n#define  BOOST_STATISTICS_DETAIL_CROSS_VALIDATION_DATA_K_FOLD_PARTITION_HPP_ER_2009\n#include <stdexcept>\n#include <iterator>\n#include <vector>\n#include <ostream>\n#include <boost/mpl/assert.hpp>\n#include <boost/mpl/bool.hpp>\n#include <boost/range.hpp>\n#include <boost/format.hpp>\n#include <boost/utility.hpp>\n#include <boost/circular_buffer.hpp>\n#include <boost/iterator/iterator_traits.hpp>\n\n#include <boost/statistics/detail/cross_validation/extractor/meta_range.hpp>\n//#include <boost/statistics/detail/tuple/meta/include.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace cross_validation{\nnamespace k_fold{\n\n\n    // k = 4\n    // train     test\n    // [0][1][2] (3)    j = 3\n    // -------------\n    // [1][2][3] (0)    j = 0\n    // [2][3][0] (1)    j = 1\n    // [3][0][1] (2)    j = 2\n    // [0][1][2] (3)    j = 3\n\n    // Partitions a dataset into 2 disjoint subsets, of size n(k-1) and n.\n    // \n    // U is the type of one observation unit, u, which must contain enough \n    // information to train and test an estimator. For example, t = (x,y) \n    // is needed to train a regression estimator, x is the input to the \n    // predictor, and y is a value against which the output is compared\n    // Each of t, x, and y are extracted from u using instances\n    // of Ft, Fi, and Fo, respectively.\n\n\n    template<\n        typename U,\n        typename Ft = extractor::identity,\n        typename Fi = extractor::identity,\n        typename Fo = extractor::identity\n    >\n    class partition{\n\n        // Warning:\n        // Since the dataset is kept internally, U must not be a reference or \n        // contain a reference\n    \n        typedef std::string str_;\n        public:\n        typedef boost::circular_buffer<U>                       subset1_type;\n        typedef std::vector<U>                                  subset2_type;\n        typedef long int                                        int_;\n        \n        struct meta_training_range \n            : extractor::meta::range<Ft,const subset1_type>{};\n        struct meta_input_range    \n            : extractor::meta::range<Fi,const subset2_type>{};\n        struct meta_output_range   \n            : extractor::meta::range<Fo,const subset2_type>{};\n                                                    \n        partition();\n        template<typename It>\n        partition(int_ k, It b,It e); \n        template<typename It>\n        partition(\n            const Ft& ft,\n            const Fi& fi,\n            const Fo& fo,\n            int_ k, It b,It e\n        ); \n        partition(const partition&); \n        partition& operator=(const partition&);\n\n        template<typename It> \n        void initialize(int_ k, It b,It e); // j = 0\n        void initialize(); //restores state to j = 0\n        void increment(); // ++j\n\n        // Access\n        const subset1_type& subset1()const;\n        const subset2_type& subset2()const;\n        \n        typename meta_training_range::type   training_range()const;\n        typename meta_input_range::type      input_range()const;\n        typename meta_output_range::type     output_range()const;\n\n\n        static str_ description_header;\n\n        const int_& n_test()const{ return this->n(); }      \n        const int_& index()const{ return this->j(); }\n        const int_& n_folds()const{ return this->k(); }     \n\n        int_ n_training()const{ return this->n() * (this->k()-1); }\n\n        protected:\n        const int_& n()const;      // size of test data\n        const int_& j()const;      // index of current iteration\n        const int_& k()const;      // number of iterations\n\n        int_ k_;\n        int_ j_;\n        int_ n_;\n        subset1_type subset1_;\n        subset2_type subset2_;\n        Ft ft_;\n        Fi fi_;\n        Fo fo_;\n    };\n    template<typename U,typename Ft,typename Fi,typename Fo>\n    typename partition<U,Ft,Fi,Fo>::str_\n    partition<U,Ft,Fi,Fo>::description_header =\"(n_test,n_index,n_folds)\";\n\n    template<typename U,typename Ft,typename Fi,typename Fo>\n    std::ostream& operator<<(\n        std::ostream& out,const partition<U,Ft,Fi,Fo>& that){\n        format f(\"partition(%1%,%2%,%3%)\");\n        f % that.n_test() % that.index() % that.n_folds();\n        return (out << f.str());\n    }\n\n    // Implementation //\n\n    template<typename U,typename Ft,typename Fi,typename Fo>\n    partition<U,Ft,Fi,Fo>::partition()\n    :k_(0),j_(0),n_(0){}\n    \n    template<typename U,typename Ft,typename Fi,typename Fo>\n        template<typename It>\n    partition<U,Ft,Fi,Fo>::partition(int_ k, It b,It e)\n    {\n        this->initialize(k,b,e);\n    } \n    \n    template<typename U,typename Ft,typename Fi,typename Fo>    \n    template<typename It>\n    partition<U,Ft,Fi,Fo>::partition(\n        const Ft& ft,\n        const Fi& fi,\n        const Fo& fo,\n        int_ k, It b,It e\n    )\n    :ft_(ft),fi_(fi),fo_(fo)\n    {\n        this->initialize(k,b,e);\n    } \n\n    template<typename U,typename Ft,typename Fi,typename Fo>\n    partition<U,Ft,Fi,Fo>::partition(const partition& that)\n    :k_(that.k_),j_(that.j_),n_(that.n_),\n    subset1_(that.subset1_),\n    subset2_(that.subset2_),\n    ft_(that.ft_),\n    fi_(that.fi_),\n    fo_(that.fo_){}\n    \n    template<typename U,typename Ft,typename Fi,typename Fo>\n    partition<U,Ft,Fi,Fo>& partition<U,Ft,Fi,Fo>::operator=(const partition& that)\n    {\n        this->k_ = that.k_;\n        this->j_ = that.j_;\n        this->n_ = that.n_;\n        this->subset1_ = that.subset1_;\n        this->subset2_  = that.subset2_;\n        this->ft_ = that.ft_;\n        this->fi_ = that.fi_;\n        this->fo_ = that.fo_;\n    }\n\n    template<typename U,typename Ft,typename Fi,typename Fo>\n        template<typename It>\n    void partition<U,Ft,Fi,Fo>::initialize(int_ k,It b,It e)\n    {\n        BOOST_ASSERT(k>1);\n        typedef typename iterator_difference<It>::type  diff_;\n        this->k_ = k;\n        this->j_ = -1;\n        diff_ d = std::distance( b, e);\n        if(d % this->k() != 0){\n            static const str_ msg \n                = str_(\"k_fold_estimate : distance(b,e)\") \n                    + \"%1% not a multiple of k = %2%\";\n            throw std::runtime_error( ( format(msg) % d % k ).str() );    \n        }\n        this->n_ = d / this->k(); \n\n        It i = boost::next( b, this->n() * (k-1) ); \n        this->subset2_.clear();\n        this->subset2_.reserve(this->n());\n        std::copy(\n            i,\n            e,\n            std::back_inserter(this->subset2_)\n        );\n        this->subset1_.assign(\n            this->n() * (k-1),\n            b, \n            i\n        );\n        this->increment();\n    }\n\n    template<typename U,typename Ft,typename Fi,typename Fo>\n    void partition<U,Ft,Fi,Fo>::initialize()\n    {\n        while(this->j()<this->k()){\n            this->increment();\n        }\n        this->j_ = 0;\n    }\n\n    template<typename U,typename Ft,typename Fi,typename Fo>\n    void partition<U,Ft,Fi,Fo>::increment(){\n        static subset2_type tmp;\n        if( !( this->j()<this->k() ) )\n        {\n            static const char* msg = \"partition: !j<k=%1%\";\n            throw std::runtime_error(\n                ( format( msg ) % this->k() ).str()\n            );\n        }\n        tmp.clear();\n        std::copy(\n            boost::begin(this->subset1()),\n            boost::next( \n                boost::begin(this->subset1()), \n                this->n() \n            ),\n            std::back_inserter(tmp)\n        );\n        this->subset1_.insert(\n            boost::end( this->subset1_ ),\n            boost::begin( this->subset2() ),\n            boost::end( this->subset2() )\n        );\n        this->subset2_ = tmp;\n        ++this->j_;\n    }\n\n    // Access\n    template<typename U,typename Ft,typename Fi,typename Fo>\n    const typename partition<U,Ft,Fi,Fo>::subset1_type& \n    partition<U,Ft,Fi,Fo>::subset1()const\n    {\n        return this->subset1_;\n    }\n\n    template<typename U,typename Ft,typename Fi,typename Fo>\n    const typename partition<U,Ft,Fi,Fo>::subset2_type& \n    partition<U,Ft,Fi,Fo>::subset2()const\n    {\n        return this->subset2_;\n    }\n\n    template<typename U,typename Ft,typename Fi,typename Fo>\n    typename partition<U,Ft,Fi,Fo>::meta_training_range::type\n    partition<U,Ft,Fi,Fo>::training_range()const\n    {\n        return meta_training_range::make(\n            this->ft_,\n            boost::begin(this->subset1()),\n            boost::end(this->subset1())\n        );\n    }\n\n    template<typename U,typename Ft,typename Fi,typename Fo>\n    typename partition<U,Ft,Fi,Fo>::meta_input_range::type\n    partition<U,Ft,Fi,Fo>::input_range()const\n    {\n        return meta_input_range::make(\n            this->fi_,\n            boost::begin(this->subset2()),\n            boost::end(this->subset2())\n        );\n    }\n\n    template<typename U,typename Ft,typename Fi,typename Fo>\n    typename partition<U,Ft,Fi,Fo>::meta_output_range::type\n    partition<U,Ft,Fi,Fo>::output_range()const\n    {\n        return meta_output_range::make(\n            this->fo_,\n            boost::begin(this->subset2()),\n            boost::end(this->subset2())\n        );\n    }\n\n    template<typename U,typename Ft,typename Fi,typename Fo>\n    const typename partition<U,Ft,Fi,Fo>::int_& \n    partition<U,Ft,Fi,Fo>::n()const\n    {\n        return this->n_;\n    }\n\n    template<typename U,typename Ft,typename Fi,typename Fo>\n    const typename partition<U,Ft,Fi,Fo>::int_& \n    partition<U,Ft,Fi,Fo>::j()const\n    {\n        return this->j_;\n    }\n    \n    template<typename U,typename Ft,typename Fi,typename Fo>\n    const typename partition<U,Ft,Fi,Fo>::int_& \n    partition<U,Ft,Fi,Fo>::k()const\n    {\n        return this->k_;\n    }\n    \n}// k_fold\n}// cross_validation\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "5ce212cb9234895aff372aceec61f90245805fa2", "size": 10454, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cross_validation/boost/statistics/detail/cross_validation/k_fold/partition.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cross_validation/boost/statistics/detail/cross_validation/k_fold/partition.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cross_validation/boost/statistics/detail/cross_validation/k_fold/partition.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.583081571, "max_line_length": 83, "alphanum_fraction": 0.5477329252, "num_tokens": 2630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.2832842077228008}}
{"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 quadruple-precision <cmath> support.\r\n\r\n#ifndef BOOST_MATH_CSTDFLOAT_CMATH_2014_02_15_HPP_\r\n#define BOOST_MATH_CSTDFLOAT_CMATH_2014_02_15_HPP_\r\n\r\n#include <boost/math/cstdfloat/cstdfloat_types.hpp>\r\n#include <boost/math/cstdfloat/cstdfloat_limits.hpp>\r\n\r\n#if defined(BOOST_CSTDFLOAT_HAS_INTERNAL_FLOAT128_T) && defined(BOOST_MATH_USE_FLOAT128) && !defined(BOOST_CSTDFLOAT_NO_LIBQUADMATH_SUPPORT)\r\n\r\n#include <cmath>\r\n#include <stdexcept>\r\n#include <iostream>\r\n#include <boost/cstdint.hpp>\r\n#include <boost/static_assert.hpp>\r\n#include <boost/throw_exception.hpp>\r\n#include <boost/core/enable_if.hpp>\r\n#include <boost/type_traits/is_same.hpp>\r\n#include <boost/type_traits/is_convertible.hpp>\r\n#include <boost/scoped_array.hpp>\r\n\r\n#if defined(_WIN32) && defined(__GNUC__)\r\n  // Several versions of Mingw and probably cygwin too have broken\r\n  // libquadmath implementations that segfault as soon as you call\r\n  // expq or any function that depends on it.\r\n#define BOOST_CSTDFLOAT_BROKEN_FLOAT128_MATH_FUNCTIONS\r\n#endif\r\n\r\n// Here is a helper function used for raising the value of a given\r\n// floating-point type to the power of n, where n has integral type.\r\nnamespace boost {\r\n   namespace math {\r\n      namespace cstdfloat {\r\n         namespace detail {\r\n\r\n            template<class float_type, class integer_type>\r\n            inline float_type pown(const float_type& x, const integer_type p)\r\n            {\r\n               const bool isneg = (x < 0);\r\n               const bool isnan = (x != x);\r\n               const bool isinf = ((!isneg) ? bool(+x > (std::numeric_limits<float_type>::max)())\r\n                  : bool(-x > (std::numeric_limits<float_type>::max)()));\r\n\r\n               if (isnan) { return x; }\r\n\r\n               if (isinf) { return std::numeric_limits<float_type>::quiet_NaN(); }\r\n\r\n               const bool       x_is_neg = (x < 0);\r\n               const float_type abs_x = (x_is_neg ? -x : x);\r\n\r\n               if (p < static_cast<integer_type>(0))\r\n               {\r\n                  if (abs_x < (std::numeric_limits<float_type>::min)())\r\n                  {\r\n                     return (x_is_neg ? -std::numeric_limits<float_type>::infinity()\r\n                        : +std::numeric_limits<float_type>::infinity());\r\n                  }\r\n                  else\r\n                  {\r\n                     return float_type(1) / pown(x, static_cast<integer_type>(-p));\r\n                  }\r\n               }\r\n\r\n               if (p == static_cast<integer_type>(0))\r\n               {\r\n                  return float_type(1);\r\n               }\r\n               else\r\n               {\r\n                  if (p == static_cast<integer_type>(1)) { return x; }\r\n\r\n                  if (abs_x > (std::numeric_limits<float_type>::max)())\r\n                  {\r\n                     return (x_is_neg ? -std::numeric_limits<float_type>::infinity()\r\n                        : +std::numeric_limits<float_type>::infinity());\r\n                  }\r\n\r\n                  if (p == static_cast<integer_type>(2)) { return  (x * x); }\r\n                  else if (p == static_cast<integer_type>(3)) { return ((x * x) * x); }\r\n                  else if (p == static_cast<integer_type>(4)) { const 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                     float_type result(((p % integer_type(2)) != integer_type(0)) ? x : float_type(1));\r\n                     float_type xn(x);\r\n\r\n                     integer_type p2 = p;\r\n\r\n                     while (integer_type(p2 /= 2) != integer_type(0))\r\n                     {\r\n                        // Square xn for each binary power.\r\n                        xn *= xn;\r\n\r\n                        const bool has_binary_power = (integer_type(p2 % integer_type(2)) != integer_type(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         }\r\n      }\r\n   }\r\n} // boost::math::cstdfloat::detail\r\n\r\n// We will now define preprocessor symbols representing quadruple-precision <cmath> functions.\r\n#if defined(BOOST_INTEL)\r\n#define BOOST_CSTDFLOAT_FLOAT128_LDEXP  __ldexpq\r\n#define BOOST_CSTDFLOAT_FLOAT128_FREXP  __frexpq\r\n#define BOOST_CSTDFLOAT_FLOAT128_FABS   __fabsq\r\n#define BOOST_CSTDFLOAT_FLOAT128_FLOOR  __floorq\r\n#define BOOST_CSTDFLOAT_FLOAT128_CEIL   __ceilq\r\n#if !defined(BOOST_CSTDFLOAT_FLOAT128_SQRT)\r\n#define BOOST_CSTDFLOAT_FLOAT128_SQRT   __sqrtq\r\n#endif\r\n#define BOOST_CSTDFLOAT_FLOAT128_TRUNC  __truncq\r\n#define BOOST_CSTDFLOAT_FLOAT128_EXP    __expq\r\n#define BOOST_CSTDFLOAT_FLOAT128_EXPM1  __expm1q\r\n#define BOOST_CSTDFLOAT_FLOAT128_POW    __powq\r\n#define BOOST_CSTDFLOAT_FLOAT128_LOG    __logq\r\n#define BOOST_CSTDFLOAT_FLOAT128_LOG10  __log10q\r\n#define BOOST_CSTDFLOAT_FLOAT128_SIN    __sinq\r\n#define BOOST_CSTDFLOAT_FLOAT128_COS    __cosq\r\n#define BOOST_CSTDFLOAT_FLOAT128_TAN    __tanq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ASIN   __asinq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ACOS   __acosq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ATAN   __atanq\r\n#define BOOST_CSTDFLOAT_FLOAT128_SINH   __sinhq\r\n#define BOOST_CSTDFLOAT_FLOAT128_COSH   __coshq\r\n#define BOOST_CSTDFLOAT_FLOAT128_TANH   __tanhq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ASINH  __asinhq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ACOSH  __acoshq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ATANH  __atanhq\r\n#define BOOST_CSTDFLOAT_FLOAT128_FMOD   __fmodq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ATAN2  __atan2q\r\n#define BOOST_CSTDFLOAT_FLOAT128_LGAMMA __lgammaq\r\n#define BOOST_CSTDFLOAT_FLOAT128_TGAMMA __tgammaq\r\n//   begin more functions\r\n#define BOOST_CSTDFLOAT_FLOAT128_REMAINDER   __remainderq\r\n#define BOOST_CSTDFLOAT_FLOAT128_REMQUO      __remquoq\r\n#define BOOST_CSTDFLOAT_FLOAT128_FMA         __fmaq\r\n#define BOOST_CSTDFLOAT_FLOAT128_FMAX        __fmaxq\r\n#define BOOST_CSTDFLOAT_FLOAT128_FMIN        __fminq\r\n#define BOOST_CSTDFLOAT_FLOAT128_FDIM        __fdimq\r\n#define BOOST_CSTDFLOAT_FLOAT128_NAN         __nanq\r\n//#define BOOST_CSTDFLOAT_FLOAT128_EXP2      __exp2q\r\n#define BOOST_CSTDFLOAT_FLOAT128_LOG2        __log2q\r\n#define BOOST_CSTDFLOAT_FLOAT128_LOG1P       __log1pq\r\n#define BOOST_CSTDFLOAT_FLOAT128_CBRT        __cbrtq\r\n#define BOOST_CSTDFLOAT_FLOAT128_HYPOT       __hypotq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ERF         __erfq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ERFC        __erfcq\r\n#define BOOST_CSTDFLOAT_FLOAT128_LLROUND     __llroundq\r\n#define BOOST_CSTDFLOAT_FLOAT128_LROUND      __lroundq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ROUND       __roundq\r\n#define BOOST_CSTDFLOAT_FLOAT128_NEARBYINT   __nearbyintq\r\n#define BOOST_CSTDFLOAT_FLOAT128_LLRINT      __llrintq\r\n#define BOOST_CSTDFLOAT_FLOAT128_LRINT       __lrintq\r\n#define BOOST_CSTDFLOAT_FLOAT128_RINT        __rintq\r\n#define BOOST_CSTDFLOAT_FLOAT128_MODF        __modfq\r\n#define BOOST_CSTDFLOAT_FLOAT128_SCALBLN     __scalblnq\r\n#define BOOST_CSTDFLOAT_FLOAT128_SCALBN      __scalbnq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ILOGB       __ilogbq\r\n#define BOOST_CSTDFLOAT_FLOAT128_LOGB        __logbq\r\n#define BOOST_CSTDFLOAT_FLOAT128_NEXTAFTER   __nextafterq\r\n//#define BOOST_CSTDFLOAT_FLOAT128_NEXTTOWARD  __nexttowardq\r\n#define BOOST_CSTDFLOAT_FLOAT128_COPYSIGN     __copysignq\r\n#define BOOST_CSTDFLOAT_FLOAT128_SIGNBIT      __signbitq\r\n//#define BOOST_CSTDFLOAT_FLOAT128_FPCLASSIFY __fpclassifyq\r\n//#define BOOST_CSTDFLOAT_FLOAT128_ISFINITE   __isfiniteq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ISINF        __isinfq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ISNAN        __isnanq\r\n//#define BOOST_CSTDFLOAT_FLOAT128_ISNORMAL   __isnormalq\r\n//#define BOOST_CSTDFLOAT_FLOAT128_ISGREATER  __isgreaterq\r\n//#define BOOST_CSTDFLOAT_FLOAT128_ISGREATEREQUAL __isgreaterequalq\r\n//#define BOOST_CSTDFLOAT_FLOAT128_ISLESS         __islessq\r\n//#define BOOST_CSTDFLOAT_FLOAT128_ISLESSEQUAL    __islessequalq\r\n//#define BOOST_CSTDFLOAT_FLOAT128_ISLESSGREATER  __islessgreaterq\r\n//#define BOOST_CSTDFLOAT_FLOAT128_ISUNORDERED    __isunorderedq\r\n//   end more functions\r\n#elif defined(__GNUC__)\r\n#define BOOST_CSTDFLOAT_FLOAT128_LDEXP  ldexpq\r\n#define BOOST_CSTDFLOAT_FLOAT128_FREXP  frexpq\r\n#define BOOST_CSTDFLOAT_FLOAT128_FABS   fabsq\r\n#define BOOST_CSTDFLOAT_FLOAT128_FLOOR  floorq\r\n#define BOOST_CSTDFLOAT_FLOAT128_CEIL   ceilq\r\n#if !defined(BOOST_CSTDFLOAT_FLOAT128_SQRT)\r\n#define BOOST_CSTDFLOAT_FLOAT128_SQRT   sqrtq\r\n#endif\r\n#define BOOST_CSTDFLOAT_FLOAT128_TRUNC  truncq\r\n#define BOOST_CSTDFLOAT_FLOAT128_POW    powq\r\n#define BOOST_CSTDFLOAT_FLOAT128_LOG    logq\r\n#define BOOST_CSTDFLOAT_FLOAT128_LOG10  log10q\r\n#define BOOST_CSTDFLOAT_FLOAT128_SIN    sinq\r\n#define BOOST_CSTDFLOAT_FLOAT128_COS    cosq\r\n#define BOOST_CSTDFLOAT_FLOAT128_TAN    tanq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ASIN   asinq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ACOS   acosq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ATAN   atanq\r\n#define BOOST_CSTDFLOAT_FLOAT128_FMOD   fmodq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ATAN2  atan2q\r\n#define BOOST_CSTDFLOAT_FLOAT128_LGAMMA lgammaq\r\n#if !defined(BOOST_CSTDFLOAT_BROKEN_FLOAT128_MATH_FUNCTIONS)\r\n#define BOOST_CSTDFLOAT_FLOAT128_EXP    expq\r\n#define BOOST_CSTDFLOAT_FLOAT128_EXPM1  expm1q\r\n#define BOOST_CSTDFLOAT_FLOAT128_SINH   sinhq\r\n#define BOOST_CSTDFLOAT_FLOAT128_COSH   coshq\r\n#define BOOST_CSTDFLOAT_FLOAT128_TANH   tanhq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ASINH  asinhq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ACOSH  acoshq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ATANH  atanhq\r\n#define BOOST_CSTDFLOAT_FLOAT128_TGAMMA tgammaq\r\n#else // BOOST_CSTDFLOAT_BROKEN_FLOAT128_MATH_FUNCTIONS\r\n#define BOOST_CSTDFLOAT_FLOAT128_EXP    expq_patch\r\n#define BOOST_CSTDFLOAT_FLOAT128_SINH   sinhq_patch\r\n#define BOOST_CSTDFLOAT_FLOAT128_COSH   coshq_patch\r\n#define BOOST_CSTDFLOAT_FLOAT128_TANH   tanhq_patch\r\n#define BOOST_CSTDFLOAT_FLOAT128_ASINH  asinhq_patch\r\n#define BOOST_CSTDFLOAT_FLOAT128_ACOSH  acoshq_patch\r\n#define BOOST_CSTDFLOAT_FLOAT128_ATANH  atanhq_patch\r\n#define BOOST_CSTDFLOAT_FLOAT128_TGAMMA tgammaq_patch\r\n#endif // BOOST_CSTDFLOAT_BROKEN_FLOAT128_MATH_FUNCTIONS\r\n//   begin more functions\r\n#define BOOST_CSTDFLOAT_FLOAT128_REMAINDER   remainderq\r\n#define BOOST_CSTDFLOAT_FLOAT128_REMQUO      remquoq\r\n#define BOOST_CSTDFLOAT_FLOAT128_FMA         fmaq\r\n#define BOOST_CSTDFLOAT_FLOAT128_FMAX        fmaxq\r\n#define BOOST_CSTDFLOAT_FLOAT128_FMIN        fminq\r\n#define BOOST_CSTDFLOAT_FLOAT128_FDIM        fdimq\r\n#define BOOST_CSTDFLOAT_FLOAT128_NAN         nanq\r\n//#define BOOST_CSTDFLOAT_FLOAT128_EXP2      exp2q\r\n#define BOOST_CSTDFLOAT_FLOAT128_LOG2        log2q\r\n#define BOOST_CSTDFLOAT_FLOAT128_LOG1P       log1pq\r\n#define BOOST_CSTDFLOAT_FLOAT128_CBRT        cbrtq\r\n#define BOOST_CSTDFLOAT_FLOAT128_HYPOT       hypotq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ERF         erfq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ERFC        erfcq\r\n#define BOOST_CSTDFLOAT_FLOAT128_LLROUND     llroundq\r\n#define BOOST_CSTDFLOAT_FLOAT128_LROUND      lroundq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ROUND       roundq\r\n#define BOOST_CSTDFLOAT_FLOAT128_NEARBYINT   nearbyintq\r\n#define BOOST_CSTDFLOAT_FLOAT128_LLRINT      llrintq\r\n#define BOOST_CSTDFLOAT_FLOAT128_LRINT       lrintq\r\n#define BOOST_CSTDFLOAT_FLOAT128_RINT        rintq\r\n#define BOOST_CSTDFLOAT_FLOAT128_MODF        modfq\r\n#define BOOST_CSTDFLOAT_FLOAT128_SCALBLN     scalblnq\r\n#define BOOST_CSTDFLOAT_FLOAT128_SCALBN      scalbnq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ILOGB       ilogbq\r\n#define BOOST_CSTDFLOAT_FLOAT128_LOGB        logbq\r\n#define BOOST_CSTDFLOAT_FLOAT128_NEXTAFTER   nextafterq\r\n//#define BOOST_CSTDFLOAT_FLOAT128_NEXTTOWARD nexttowardq\r\n#define BOOST_CSTDFLOAT_FLOAT128_COPYSIGN    copysignq\r\n#define BOOST_CSTDFLOAT_FLOAT128_SIGNBIT     signbitq\r\n//#define BOOST_CSTDFLOAT_FLOAT128_FPCLASSIFY fpclassifyq\r\n//#define BOOST_CSTDFLOAT_FLOAT128_ISFINITE   isfiniteq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ISINF        isinfq\r\n#define BOOST_CSTDFLOAT_FLOAT128_ISNAN        isnanq\r\n//#define BOOST_CSTDFLOAT_FLOAT128_ISNORMAL   isnormalq\r\n//#define BOOST_CSTDFLOAT_FLOAT128_ISGREATER  isgreaterq\r\n//#define BOOST_CSTDFLOAT_FLOAT128_ISGREATEREQUAL isgreaterequalq\r\n//#define BOOST_CSTDFLOAT_FLOAT128_ISLESS         islessq\r\n//#define BOOST_CSTDFLOAT_FLOAT128_ISLESSEQUAL    islessequalq\r\n//#define BOOST_CSTDFLOAT_FLOAT128_ISLESSGREATER  islessgreaterq\r\n//#define BOOST_CSTDFLOAT_FLOAT128_ISUNORDERED    isunorderedq\r\n//   end more functions\r\n#endif\r\n\r\n// Implement quadruple-precision <cmath> functions in the namespace\r\n// boost::math::cstdfloat::detail. Subsequently inject these into the\r\n// std namespace via *using* directive.\r\n\r\n// Begin with some forward function declarations. Also implement patches\r\n// for compilers that have broken float128 exponential functions.\r\n\r\nextern \"C\" int quadmath_snprintf(char*, std::size_t, const char*, ...) throw();\r\n\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_LDEXP(boost::math::cstdfloat::detail::float_internal128_t, int) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_FREXP(boost::math::cstdfloat::detail::float_internal128_t, int*) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_FABS(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_FLOOR(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_CEIL(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_SQRT(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_TRUNC(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_POW(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_LOG(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_LOG10(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_SIN(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_COS(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_TAN(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_ASIN(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_ACOS(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_ATAN(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_FMOD(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_ATAN2(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_LGAMMA(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\n\r\n//   begin more functions\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_REMAINDER(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_REMQUO(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t, int*) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_FMA(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_FMAX(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_FMIN(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_FDIM(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_NAN(const char*) throw();\r\n//extern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_EXP2         (boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_LOG2(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_LOG1P(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_CBRT(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_HYPOT(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_ERF(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_ERFC(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" long long int                                BOOST_CSTDFLOAT_FLOAT128_LLROUND(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" long int                                   BOOST_CSTDFLOAT_FLOAT128_LROUND(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_ROUND(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_NEARBYINT(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" long long int                                BOOST_CSTDFLOAT_FLOAT128_LLRINT(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" long int                                   BOOST_CSTDFLOAT_FLOAT128_LRINT(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_RINT(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_MODF(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t*) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_SCALBLN(boost::math::cstdfloat::detail::float_internal128_t, long int) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_SCALBN(boost::math::cstdfloat::detail::float_internal128_t, int) throw();\r\nextern \"C\" int                                      BOOST_CSTDFLOAT_FLOAT128_ILOGB(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_LOGB(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_NEXTAFTER(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\r\n//extern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_NEXTTOWARD   (boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_COPYSIGN(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" int                                                  BOOST_CSTDFLOAT_FLOAT128_SIGNBIT(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\n//extern \"C\" int                                                BOOST_CSTDFLOAT_FLOAT128_FPCLASSIFY   (boost::math::cstdfloat::detail::float_internal128_t) throw();\r\n//extern \"C\" int                                                BOOST_CSTDFLOAT_FLOAT128_ISFINITE      (boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" int                                                  BOOST_CSTDFLOAT_FLOAT128_ISINF(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\nextern \"C\" int                                                  BOOST_CSTDFLOAT_FLOAT128_ISNAN(boost::math::cstdfloat::detail::float_internal128_t) throw();\r\n//extern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_ISNORMAL   (boost::math::cstdfloat::detail::float_internal128_t) throw();\r\n//extern \"C\" int                                                BOOST_CSTDFLOAT_FLOAT128_ISGREATER   (boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\r\n//extern \"C\" int                                                BOOST_CSTDFLOAT_FLOAT128_ISGREATEREQUAL(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\r\n//extern \"C\" int                                                BOOST_CSTDFLOAT_FLOAT128_ISLESS      (boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\r\n//extern \"C\" int                                                BOOST_CSTDFLOAT_FLOAT128_ISLESSEQUAL   (boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\r\n//extern \"C\" int                                                BOOST_CSTDFLOAT_FLOAT128_ISLESSGREATER(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\r\n//extern \"C\" int                                                BOOST_CSTDFLOAT_FLOAT128_ISUNORDERED   (boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\r\n //   end more functions\r\n\r\n#if !defined(BOOST_CSTDFLOAT_BROKEN_FLOAT128_MATH_FUNCTIONS)\r\n\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_EXP(boost::math::cstdfloat::detail::float_internal128_t x) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_EXPM1(boost::math::cstdfloat::detail::float_internal128_t x) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_SINH(boost::math::cstdfloat::detail::float_internal128_t x) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_COSH(boost::math::cstdfloat::detail::float_internal128_t x) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_TANH(boost::math::cstdfloat::detail::float_internal128_t x) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_ASINH(boost::math::cstdfloat::detail::float_internal128_t x) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_ACOSH(boost::math::cstdfloat::detail::float_internal128_t x) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_ATANH(boost::math::cstdfloat::detail::float_internal128_t x) throw();\r\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_TGAMMA(boost::math::cstdfloat::detail::float_internal128_t x) throw();\r\n \r\n#else // BOOST_CSTDFLOAT_BROKEN_FLOAT128_MATH_FUNCTIONS\r\n\r\n// Forward declaration of the patched exponent function, exp(x).\r\ninline boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_EXP(boost::math::cstdfloat::detail::float_internal128_t x);\r\n\r\ninline boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_EXPM1(boost::math::cstdfloat::detail::float_internal128_t x)\r\n{\r\n   // Compute exp(x) - 1 for x small.\r\n\r\n   // Use an order-36 polynomial approximation of the exponential function\r\n   // in the range of (-ln2 < x < ln2). Scale the argument to this range\r\n   // and subsequently multiply the result by 2^n accordingly.\r\n\r\n   // Derive the polynomial coefficients with Mathematica(R) by generating\r\n   // a table of high-precision values of exp(x) in the range (-ln2 < x < ln2)\r\n   // and subsequently applying the built-in *Fit* function.\r\n\r\n   // Table[{x, Exp[x] - 1}, {x, -Log[2], Log[2], 1/180}]\r\n   // N[%, 120]\r\n   // Fit[%, {x, x^2, x^3, x^4, x^5, x^6, x^7, x^8, x^9, x^10, x^11, x^12,\r\n   //         x^13, x^14, x^15, x^16, x^17, x^18, x^19, x^20, x^21, x^22,\r\n   //         x^23, x^24, x^25, x^26, x^27, x^28, x^29, x^30, x^31, x^32,\r\n   //         x^33, x^34, x^35, x^36}, x]\r\n\r\n   typedef boost::math::cstdfloat::detail::float_internal128_t float_type;\r\n\r\n   float_type sum;\r\n\r\n   if (x > BOOST_FLOAT128_C(0.693147180559945309417232121458176568075500134360255))\r\n   {\r\n      sum = ::BOOST_CSTDFLOAT_FLOAT128_EXP(x) - float_type(1);\r\n   }\r\n   else\r\n   {\r\n      // Compute the polynomial approximation of exp(alpha).\r\n      sum = ((((((((((((((((((((((((((((((((((((float_type(BOOST_FLOAT128_C(2.69291698127774166063293705964720493864630783729857438187365E-42))  * x\r\n         + float_type(BOOST_FLOAT128_C(9.70937085471487654794114679403710456028986572118859594614033E-41))) * x\r\n         + float_type(BOOST_FLOAT128_C(3.38715585158055097155585505318085512156885389014410753080500E-39))) * x\r\n         + float_type(BOOST_FLOAT128_C(1.15162718532861050809222658798662695267019717760563645440433E-37))) * x\r\n         + float_type(BOOST_FLOAT128_C(3.80039074689434663295873584133017767349635602413675471702393E-36))) * x\r\n         + float_type(BOOST_FLOAT128_C(1.21612504934087520075905434734158045947460467096773246215239E-34))) * x\r\n         + float_type(BOOST_FLOAT128_C(3.76998762883139753126119821241037824830069851253295480396224E-33))) * x\r\n         + float_type(BOOST_FLOAT128_C(1.13099628863830344684998293828608215735777107850991029729440E-31))) * x\r\n         + float_type(BOOST_FLOAT128_C(3.27988923706982293204067897468714277771890104022419696770352E-30))) * x\r\n         + float_type(BOOST_FLOAT128_C(9.18368986379558482800593745627556950089950023355628325088207E-29))) * x\r\n         + float_type(BOOST_FLOAT128_C(2.47959626322479746949155352659617642905315302382639380521497E-27))) * x\r\n         + float_type(BOOST_FLOAT128_C(6.44695028438447337900255966737803112935639344283098705091949E-26))) * x\r\n         + float_type(BOOST_FLOAT128_C(1.61173757109611834904452725462599961406036904573072897122957E-24))) * x\r\n         + float_type(BOOST_FLOAT128_C(3.86817017063068403772269360016918092488847584660382953555804E-23))) * x\r\n         + float_type(BOOST_FLOAT128_C(8.89679139245057328674891109315654704307721758924206107351744E-22))) * x\r\n         + float_type(BOOST_FLOAT128_C(1.95729410633912612308475595397946731738088422488032228717097E-20))) * x\r\n         + float_type(BOOST_FLOAT128_C(4.11031762331216485847799061511674191805055663711439605760231E-19))) * x\r\n         + float_type(BOOST_FLOAT128_C(8.22063524662432971695598123977873600603370758794431071426640E-18))) * x\r\n         + float_type(BOOST_FLOAT128_C(1.56192069685862264622163643500633782667263448653185159383285E-16))) * x\r\n         + float_type(BOOST_FLOAT128_C(2.81145725434552076319894558300988749849555291507956994126835E-15))) * x\r\n         + float_type(BOOST_FLOAT128_C(4.77947733238738529743820749111754320727153728139716409114011E-14))) * x\r\n         + float_type(BOOST_FLOAT128_C(7.64716373181981647590113198578807092707697416852226691068627E-13))) * x\r\n         + float_type(BOOST_FLOAT128_C(1.14707455977297247138516979786821056670509688396295740818677E-11))) * x\r\n         + float_type(BOOST_FLOAT128_C(1.60590438368216145993923771701549479323291461578567184216302E-10))) * x\r\n         + float_type(BOOST_FLOAT128_C(2.08767569878680989792100903212014323125428376052986408239620E-09))) * x\r\n         + float_type(BOOST_FLOAT128_C(2.50521083854417187750521083854417187750523408006206780016659E-08))) * x\r\n         + float_type(BOOST_FLOAT128_C(2.75573192239858906525573192239858906525573195144226062684604E-07))) * x\r\n         + float_type(BOOST_FLOAT128_C(2.75573192239858906525573192239858906525573191310049321957902E-06))) * x\r\n         + float_type(BOOST_FLOAT128_C(0.00002480158730158730158730158730158730158730158730149317774)))     * x\r\n         + float_type(BOOST_FLOAT128_C(0.00019841269841269841269841269841269841269841269841293575920)))     * x\r\n         + float_type(BOOST_FLOAT128_C(0.00138888888888888888888888888888888888888888888888889071045)))     * x\r\n         + float_type(BOOST_FLOAT128_C(0.00833333333333333333333333333333333333333333333333332986595)))     * x\r\n         + float_type(BOOST_FLOAT128_C(0.04166666666666666666666666666666666666666666666666666664876)))     * x\r\n         + float_type(BOOST_FLOAT128_C(0.16666666666666666666666666666666666666666666666666666669048)))     * x\r\n         + float_type(BOOST_FLOAT128_C(0.50000000000000000000000000000000000000000000000000000000006)))     * x\r\n         + float_type(BOOST_FLOAT128_C(0.99999999999999999999999999999999999999999999999999999999995)))     * x);\r\n   }\r\n\r\n   return sum;\r\n}\r\ninline boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_EXP(boost::math::cstdfloat::detail::float_internal128_t x)\r\n{\r\n   // Patch the expq() function for a subset of broken GCC compilers\r\n   // like GCC 4.7, 4.8 on MinGW.\r\n\r\n   // Use an order-36 polynomial approximation of the exponential function\r\n   // in the range of (-ln2 < x < ln2). Scale the argument to this range\r\n   // and subsequently multiply the result by 2^n accordingly.\r\n\r\n   // Derive the polynomial coefficients with Mathematica(R) by generating\r\n   // a table of high-precision values of exp(x) in the range (-ln2 < x < ln2)\r\n   // and subsequently applying the built-in *Fit* function.\r\n\r\n   // Table[{x, Exp[x] - 1}, {x, -Log[2], Log[2], 1/180}]\r\n   // N[%, 120]\r\n   // Fit[%, {x, x^2, x^3, x^4, x^5, x^6, x^7, x^8, x^9, x^10, x^11, x^12,\r\n   //         x^13, x^14, x^15, x^16, x^17, x^18, x^19, x^20, x^21, x^22,\r\n   //         x^23, x^24, x^25, x^26, x^27, x^28, x^29, x^30, x^31, x^32,\r\n   //         x^33, x^34, x^35, x^36}, x]\r\n\r\n   typedef boost::math::cstdfloat::detail::float_internal128_t float_type;\r\n\r\n   // Scale the argument x to the range (-ln2 < x < ln2).\r\n   BOOST_CONSTEXPR_OR_CONST float_type one_over_ln2 = float_type(BOOST_FLOAT128_C(1.44269504088896340735992468100189213742664595415299));\r\n   const float_type x_over_ln2 = x * one_over_ln2;\r\n\r\n   boost::int_fast32_t n;\r\n\r\n   if (x != x)\r\n   {\r\n      // The argument is NaN.\r\n      return std::numeric_limits<float_type>::quiet_NaN();\r\n   }\r\n   else if (::BOOST_CSTDFLOAT_FLOAT128_FABS(x) > BOOST_FLOAT128_C(+0.693147180559945309417232121458176568075500134360255))\r\n   {\r\n      // The absolute value of the argument exceeds ln2.\r\n      n = static_cast<boost::int_fast32_t>(::BOOST_CSTDFLOAT_FLOAT128_FLOOR(x_over_ln2));\r\n   }\r\n   else if (::BOOST_CSTDFLOAT_FLOAT128_FABS(x) < BOOST_FLOAT128_C(+0.693147180559945309417232121458176568075500134360255))\r\n   {\r\n      // The absolute value of the argument is less than ln2.\r\n      n = static_cast<boost::int_fast32_t>(0);\r\n   }\r\n   else\r\n   {\r\n      // The absolute value of the argument is exactly equal to ln2 (in the sense of floating-point equality).\r\n      return float_type(2);\r\n   }\r\n\r\n   // Check if the argument is very near an integer.\r\n   const float_type floor_of_x = ::BOOST_CSTDFLOAT_FLOAT128_FLOOR(x);\r\n\r\n   if (::BOOST_CSTDFLOAT_FLOAT128_FABS(x - floor_of_x) < float_type(BOOST_CSTDFLOAT_FLOAT128_EPS))\r\n   {\r\n      // Return e^n for arguments very near an integer.\r\n      return boost::math::cstdfloat::detail::pown(BOOST_FLOAT128_C(2.71828182845904523536028747135266249775724709369996), static_cast<boost::int_fast32_t>(floor_of_x));\r\n   }\r\n\r\n   // Compute the scaled argument alpha.\r\n   const float_type alpha = x - (n * BOOST_FLOAT128_C(0.693147180559945309417232121458176568075500134360255));\r\n\r\n   // Compute the polynomial approximation of expm1(alpha) and add to it\r\n   // in order to obtain the scaled result.\r\n   const float_type scaled_result = ::BOOST_CSTDFLOAT_FLOAT128_EXPM1(alpha) + float_type(1);\r\n\r\n   // Rescale the result and return it.\r\n   return scaled_result * boost::math::cstdfloat::detail::pown(float_type(2), n);\r\n}\r\ninline boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_SINH(boost::math::cstdfloat::detail::float_internal128_t x)\r\n{\r\n   // Patch the sinhq() function for a subset of broken GCC compilers\r\n   // like GCC 4.7, 4.8 on MinGW.\r\n   typedef boost::math::cstdfloat::detail::float_internal128_t float_type;\r\n\r\n   // Here, we use the following:\r\n   // Set: ex  = exp(x)\r\n   // Set: em1 = expm1(x)\r\n   // Then\r\n   // sinh(x) = (ex - 1/ex) / 2         ; for |x| >= 1\r\n   // sinh(x) = (2em1 + em1^2) / (2ex)  ; for |x| < 1\r\n\r\n   const float_type ex = ::BOOST_CSTDFLOAT_FLOAT128_EXP(x);\r\n\r\n   if (::BOOST_CSTDFLOAT_FLOAT128_FABS(x) < float_type(+1))\r\n   {\r\n      const float_type em1 = ::BOOST_CSTDFLOAT_FLOAT128_EXPM1(x);\r\n\r\n      return ((em1 * 2) + (em1 * em1)) / (ex * 2);\r\n   }\r\n   else\r\n   {\r\n      return (ex - (float_type(1) / ex)) / 2;\r\n   }\r\n}\r\ninline boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_COSH(boost::math::cstdfloat::detail::float_internal128_t x)\r\n{\r\n   // Patch the coshq() function for a subset of broken GCC compilers\r\n   // like GCC 4.7, 4.8 on MinGW.\r\n   typedef boost::math::cstdfloat::detail::float_internal128_t float_type;\r\n   const float_type ex = ::BOOST_CSTDFLOAT_FLOAT128_EXP(x);\r\n   return (ex + (float_type(1) / ex)) / 2;\r\n}\r\ninline boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_TANH(boost::math::cstdfloat::detail::float_internal128_t x)\r\n{\r\n   // Patch the tanhq() function for a subset of broken GCC compilers\r\n   // like GCC 4.7, 4.8 on MinGW.\r\n   typedef boost::math::cstdfloat::detail::float_internal128_t float_type;\r\n   const float_type ex_plus = ::BOOST_CSTDFLOAT_FLOAT128_EXP(x);\r\n   const float_type ex_minus = (float_type(1) / ex_plus);\r\n   return (ex_plus - ex_minus) / (ex_plus + ex_minus);\r\n}\r\ninline boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_ASINH(boost::math::cstdfloat::detail::float_internal128_t x) throw()\r\n{\r\n   // Patch the asinh() function since quadmath does not have it.\r\n   typedef boost::math::cstdfloat::detail::float_internal128_t float_type;\r\n   return ::BOOST_CSTDFLOAT_FLOAT128_LOG(x + ::BOOST_CSTDFLOAT_FLOAT128_SQRT((x * x) + float_type(1)));\r\n}\r\ninline boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_ACOSH(boost::math::cstdfloat::detail::float_internal128_t x) throw()\r\n{\r\n   // Patch the acosh() function since quadmath does not have it.\r\n   typedef boost::math::cstdfloat::detail::float_internal128_t float_type;\r\n   const float_type zp(x + float_type(1));\r\n   const float_type zm(x - float_type(1));\r\n\r\n   return ::BOOST_CSTDFLOAT_FLOAT128_LOG(x + (zp * ::BOOST_CSTDFLOAT_FLOAT128_SQRT(zm / zp)));\r\n}\r\ninline boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_ATANH(boost::math::cstdfloat::detail::float_internal128_t x) throw()\r\n{\r\n   // Patch the atanh() function since quadmath does not have it.\r\n   typedef boost::math::cstdfloat::detail::float_internal128_t float_type;\r\n   return (::BOOST_CSTDFLOAT_FLOAT128_LOG(float_type(1) + x)\r\n      - ::BOOST_CSTDFLOAT_FLOAT128_LOG(float_type(1) - x)) / 2;\r\n}\r\ninline boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_TGAMMA(boost::math::cstdfloat::detail::float_internal128_t x) throw()\r\n{\r\n   // Patch the tgammaq() function for a subset of broken GCC compilers\r\n   // like GCC 4.7, 4.8 on MinGW.\r\n   typedef boost::math::cstdfloat::detail::float_internal128_t float_type;\r\n\r\n   if (x > float_type(0))\r\n   {\r\n      return ::BOOST_CSTDFLOAT_FLOAT128_EXP(::BOOST_CSTDFLOAT_FLOAT128_LGAMMA(x));\r\n   }\r\n   else if (x < float_type(0))\r\n   {\r\n      // For x < 0, compute tgamma(-x) and use the reflection formula.\r\n      const float_type positive_x = -x;\r\n      float_type gamma_value = ::BOOST_CSTDFLOAT_FLOAT128_TGAMMA(positive_x);\r\n      const float_type floor_of_positive_x = ::BOOST_CSTDFLOAT_FLOAT128_FLOOR(positive_x);\r\n\r\n      // Take the reflection checks (slightly adapted) from <boost/math/gamma.hpp>.\r\n      const bool floor_of_z_is_equal_to_z = (positive_x == ::BOOST_CSTDFLOAT_FLOAT128_FLOOR(positive_x));\r\n\r\n      BOOST_CONSTEXPR_OR_CONST float_type my_pi = BOOST_FLOAT128_C(3.14159265358979323846264338327950288419716939937511);\r\n\r\n      if (floor_of_z_is_equal_to_z)\r\n      {\r\n         const bool is_odd = ((boost::int32_t(floor_of_positive_x) % boost::int32_t(2)) != boost::int32_t(0));\r\n\r\n         return (is_odd ? -std::numeric_limits<float_type>::infinity()\r\n            : +std::numeric_limits<float_type>::infinity());\r\n      }\r\n\r\n      const float_type sinpx_value = x * ::BOOST_CSTDFLOAT_FLOAT128_SIN(my_pi * x);\r\n\r\n      gamma_value *= sinpx_value;\r\n\r\n      const bool result_is_too_large_to_represent = ((::BOOST_CSTDFLOAT_FLOAT128_FABS(gamma_value) < float_type(1))\r\n         && (((std::numeric_limits<float_type>::max)() * ::BOOST_CSTDFLOAT_FLOAT128_FABS(gamma_value)) < my_pi));\r\n\r\n      if (result_is_too_large_to_represent)\r\n      {\r\n         const bool is_odd = ((boost::int32_t(floor_of_positive_x) % boost::int32_t(2)) != boost::int32_t(0));\r\n\r\n         return (is_odd ? -std::numeric_limits<float_type>::infinity()\r\n            : +std::numeric_limits<float_type>::infinity());\r\n      }\r\n\r\n      gamma_value = -my_pi / gamma_value;\r\n\r\n      if ((gamma_value > float_type(0)) || (gamma_value < float_type(0)))\r\n      {\r\n         return gamma_value;\r\n      }\r\n      else\r\n      {\r\n         // The value of gamma is too small to represent. Return 0.0 here.\r\n         return float_type(0);\r\n      }\r\n   }\r\n   else\r\n   {\r\n      // Gamma of zero is complex infinity. Return NaN here.\r\n      return std::numeric_limits<float_type>::quiet_NaN();\r\n   }\r\n}\r\n#endif // BOOST_CSTDFLOAT_BROKEN_FLOAT128_MATH_FUNCTIONS\r\n\r\n// Define the quadruple-precision <cmath> functions in the namespace boost::math::cstdfloat::detail.\r\n\r\nnamespace boost {\r\n   namespace math {\r\n      namespace cstdfloat {\r\n         namespace detail {\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t ldexp(boost::math::cstdfloat::detail::float_internal128_t x, int n) { return ::BOOST_CSTDFLOAT_FLOAT128_LDEXP(x, n); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t frexp(boost::math::cstdfloat::detail::float_internal128_t x, int* pn) { return ::BOOST_CSTDFLOAT_FLOAT128_FREXP(x, pn); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t fabs(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_FABS(x); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t abs(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_FABS(x); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t floor(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_FLOOR(x); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t ceil(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_CEIL(x); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t sqrt(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_SQRT(x); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t trunc(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_TRUNC(x); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t exp(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_EXP(x); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t expm1(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_EXPM1(x); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t pow(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t a) { return ::BOOST_CSTDFLOAT_FLOAT128_POW(x, a); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t pow(boost::math::cstdfloat::detail::float_internal128_t x, int a) { return ::BOOST_CSTDFLOAT_FLOAT128_POW(x, boost::math::cstdfloat::detail::float_internal128_t(a)); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t log(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_LOG(x); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t log10(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_LOG10(x); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t sin(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_SIN(x); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t cos(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_COS(x); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t tan(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_TAN(x); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t asin(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ASIN(x); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t acos(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ACOS(x); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t atan(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ATAN(x); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t sinh(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_SINH(x); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t cosh(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_COSH(x); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t tanh(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_TANH(x); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t asinh(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ASINH(x); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t acosh(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ACOSH(x); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t atanh(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ATANH(x); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t fmod(boost::math::cstdfloat::detail::float_internal128_t a, boost::math::cstdfloat::detail::float_internal128_t b) { return ::BOOST_CSTDFLOAT_FLOAT128_FMOD(a, b); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t atan2(boost::math::cstdfloat::detail::float_internal128_t y, boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ATAN2(y, x); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t lgamma(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_LGAMMA(x); }\r\n            inline   boost::math::cstdfloat::detail::float_internal128_t tgamma(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_TGAMMA(x); }\r\n            //   begin more functions\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  remainder(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y) { return ::BOOST_CSTDFLOAT_FLOAT128_REMAINDER(x, y); }\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  remquo(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y, int* z) { return ::BOOST_CSTDFLOAT_FLOAT128_REMQUO(x, y, z); }\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  fma(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y, boost::math::cstdfloat::detail::float_internal128_t z) { return BOOST_CSTDFLOAT_FLOAT128_FMA(x, y, z); }\r\n\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  fmax(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y) { return ::BOOST_CSTDFLOAT_FLOAT128_FMAX(x, y); }\r\n            template <class T>\r\n            inline typename boost::enable_if_c<\r\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\r\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\r\n               fmax(boost::math::cstdfloat::detail::float_internal128_t x, T y) { return ::BOOST_CSTDFLOAT_FLOAT128_FMAX(x, y); }\r\n            template <class T>\r\n            inline typename boost::enable_if_c<\r\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\r\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\r\n               fmax(T x, boost::math::cstdfloat::detail::float_internal128_t y) { return ::BOOST_CSTDFLOAT_FLOAT128_FMAX(x, y); }\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  fmin(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y) { return ::BOOST_CSTDFLOAT_FLOAT128_FMIN(x, y); }\r\n            template <class T>\r\n            inline typename boost::enable_if_c<\r\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\r\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\r\n               fmin(boost::math::cstdfloat::detail::float_internal128_t x, T y) { return ::BOOST_CSTDFLOAT_FLOAT128_FMIN(x, y); }\r\n            template <class T>\r\n            inline typename boost::enable_if_c<\r\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\r\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\r\n               fmin(T x, boost::math::cstdfloat::detail::float_internal128_t y) { return ::BOOST_CSTDFLOAT_FLOAT128_FMIN(x, y); }\r\n\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  fdim(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y) { return ::BOOST_CSTDFLOAT_FLOAT128_FDIM(x, y); }\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  nanq(const char* x) { return ::BOOST_CSTDFLOAT_FLOAT128_NAN(x); }\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  exp2(boost::math::cstdfloat::detail::float_internal128_t x)\r\n            {\r\n               return ::BOOST_CSTDFLOAT_FLOAT128_POW(boost::math::cstdfloat::detail::float_internal128_t(2), x);\r\n            }\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  log2(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_LOG2(x); }\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  log1p(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_LOG1P(x); }\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  cbrt(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_CBRT(x); }\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  hypot(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y, boost::math::cstdfloat::detail::float_internal128_t z) { return ::BOOST_CSTDFLOAT_FLOAT128_SQRT(x*x + y * y + z * z); }\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  hypot(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y) { return ::BOOST_CSTDFLOAT_FLOAT128_HYPOT(x, y); }\r\n            template <class T>\r\n            inline typename boost::enable_if_c<\r\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\r\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\r\n               hypot(boost::math::cstdfloat::detail::float_internal128_t x, T y) { return ::BOOST_CSTDFLOAT_FLOAT128_HYPOT(x, y); }\r\n            template <class T>\r\n            inline typename boost::enable_if_c<\r\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\r\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\r\n               hypot(T x, boost::math::cstdfloat::detail::float_internal128_t y) { return ::BOOST_CSTDFLOAT_FLOAT128_HYPOT(x, y); }\r\n\r\n\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  erf(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ERF(x); }\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  erfc(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ERFC(x); }\r\n            inline long long int                                        llround(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_LLROUND(x); }\r\n            inline long int                                             lround(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_LROUND(x); }\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  round(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ROUND(x); }\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  nearbyint(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_NEARBYINT(x); }\r\n            inline long long int                                        llrint(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_LLRINT(x); }\r\n            inline long int                                             lrint(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_LRINT(x); }\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  rint(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_RINT(x); }\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  modf(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t* y) { return ::BOOST_CSTDFLOAT_FLOAT128_MODF(x, y); }\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  scalbln(boost::math::cstdfloat::detail::float_internal128_t x, long int y) { return ::BOOST_CSTDFLOAT_FLOAT128_SCALBLN(x, y); }\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  scalbn(boost::math::cstdfloat::detail::float_internal128_t x, int y) { return ::BOOST_CSTDFLOAT_FLOAT128_SCALBN(x, y); }\r\n            inline int                                                  ilogb(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ILOGB(x); }\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  logb(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_LOGB(x); }\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  nextafter(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y) { return ::BOOST_CSTDFLOAT_FLOAT128_NEXTAFTER(x, y); }\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  nexttoward(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y) { return -(::BOOST_CSTDFLOAT_FLOAT128_NEXTAFTER(-x, -y)); }\r\n            inline boost::math::cstdfloat::detail::float_internal128_t  copysign   BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y) { return ::BOOST_CSTDFLOAT_FLOAT128_COPYSIGN(x, y); }\r\n            inline bool                                                 signbit   BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_SIGNBIT(x); }\r\n            inline int                                                  fpclassify BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x)\r\n            {\r\n               if (::BOOST_CSTDFLOAT_FLOAT128_ISNAN(x))\r\n                  return FP_NAN;\r\n               else if (::BOOST_CSTDFLOAT_FLOAT128_ISINF(x))\r\n                  return FP_INFINITE;\r\n               else if (x == BOOST_FLOAT128_C(0.0))\r\n                  return FP_ZERO;\r\n\r\n               if (::BOOST_CSTDFLOAT_FLOAT128_FABS(x) < BOOST_CSTDFLOAT_FLOAT128_MIN)\r\n                  return FP_SUBNORMAL;\r\n               else\r\n                  return FP_NORMAL;\r\n            }\r\n            inline bool                                      isfinite   BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x)\r\n            {\r\n               return !::BOOST_CSTDFLOAT_FLOAT128_ISNAN(x) && !::BOOST_CSTDFLOAT_FLOAT128_ISINF(x);\r\n            }\r\n            inline bool                                      isinf      BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ISINF(x); }\r\n            inline bool                                      isnan      BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ISNAN(x); }\r\n            inline bool                                      isnormal   BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x) { return boost::math::cstdfloat::detail::fpclassify BOOST_PREVENT_MACRO_SUBSTITUTION(x) == FP_NORMAL; }\r\n            inline bool                                      isgreater      BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y)\r\n            {\r\n               if (isnan BOOST_PREVENT_MACRO_SUBSTITUTION(x) || isnan BOOST_PREVENT_MACRO_SUBSTITUTION(y))\r\n                  return false;\r\n               return x > y;\r\n            }\r\n            template <class T>\r\n            inline typename boost::enable_if_c<\r\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\r\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\r\n               isgreater BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, T y) { return isgreater BOOST_PREVENT_MACRO_SUBSTITUTION(x, (boost::math::cstdfloat::detail::float_internal128_t)y); }\r\n            template <class T>\r\n            inline typename boost::enable_if_c<\r\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\r\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\r\n               isgreater BOOST_PREVENT_MACRO_SUBSTITUTION(T x, boost::math::cstdfloat::detail::float_internal128_t y) { return isgreater BOOST_PREVENT_MACRO_SUBSTITUTION((boost::math::cstdfloat::detail::float_internal128_t)x, y); }\r\n\r\n            inline bool                                      isgreaterequal BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y)\r\n            {\r\n               if (isnan BOOST_PREVENT_MACRO_SUBSTITUTION(x) || isnan BOOST_PREVENT_MACRO_SUBSTITUTION(y))\r\n                  return false;\r\n               return x >= y;\r\n            }\r\n            template <class T>\r\n            inline typename boost::enable_if_c<\r\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\r\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\r\n               isgreaterequal BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, T y) { return isgreaterequal BOOST_PREVENT_MACRO_SUBSTITUTION(x, (boost::math::cstdfloat::detail::float_internal128_t)y); }\r\n            template <class T>\r\n            inline typename boost::enable_if_c<\r\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\r\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\r\n               isgreaterequal BOOST_PREVENT_MACRO_SUBSTITUTION(T x, boost::math::cstdfloat::detail::float_internal128_t y) { return isgreaterequal BOOST_PREVENT_MACRO_SUBSTITUTION((boost::math::cstdfloat::detail::float_internal128_t)x, y); }\r\n\r\n            inline bool                                      isless      BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y)\r\n            {\r\n               if (isnan BOOST_PREVENT_MACRO_SUBSTITUTION(x) || isnan BOOST_PREVENT_MACRO_SUBSTITUTION(y))\r\n                  return false;\r\n               return x < y;\r\n            }\r\n            template <class T>\r\n            inline typename boost::enable_if_c<\r\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\r\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\r\n               isless BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, T y) { return isless BOOST_PREVENT_MACRO_SUBSTITUTION(x, (boost::math::cstdfloat::detail::float_internal128_t)y); }\r\n            template <class T>\r\n            inline typename boost::enable_if_c<\r\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\r\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\r\n               isless BOOST_PREVENT_MACRO_SUBSTITUTION(T x, boost::math::cstdfloat::detail::float_internal128_t y) { return isless BOOST_PREVENT_MACRO_SUBSTITUTION((boost::math::cstdfloat::detail::float_internal128_t)x, y); }\r\n\r\n\r\n            inline bool                                      islessequal   BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y)\r\n            {\r\n               if (isnan BOOST_PREVENT_MACRO_SUBSTITUTION(x) || isnan BOOST_PREVENT_MACRO_SUBSTITUTION(y))\r\n                  return false;\r\n               return x <= y;\r\n            }\r\n            template <class T>\r\n            inline typename boost::enable_if_c<\r\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\r\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\r\n               islessequal BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, T y) { return islessequal BOOST_PREVENT_MACRO_SUBSTITUTION(x, (boost::math::cstdfloat::detail::float_internal128_t)y); }\r\n            template <class T>\r\n            inline typename boost::enable_if_c<\r\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\r\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\r\n               islessequal BOOST_PREVENT_MACRO_SUBSTITUTION(T x, boost::math::cstdfloat::detail::float_internal128_t y) { return islessequal BOOST_PREVENT_MACRO_SUBSTITUTION((boost::math::cstdfloat::detail::float_internal128_t)x, y); }\r\n\r\n\r\n            inline bool                                      islessgreater   BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y)\r\n            {\r\n               if (isnan BOOST_PREVENT_MACRO_SUBSTITUTION(x) || isnan BOOST_PREVENT_MACRO_SUBSTITUTION(y))\r\n                  return false;\r\n               return (x < y) || (x > y);\r\n            }\r\n            template <class T>\r\n            inline typename boost::enable_if_c<\r\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\r\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\r\n               islessgreater BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, T y) { return islessgreater BOOST_PREVENT_MACRO_SUBSTITUTION(x, (boost::math::cstdfloat::detail::float_internal128_t)y); }\r\n            template <class T>\r\n            inline typename boost::enable_if_c<\r\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\r\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\r\n               islessgreater BOOST_PREVENT_MACRO_SUBSTITUTION(T x, boost::math::cstdfloat::detail::float_internal128_t y) { return islessgreater BOOST_PREVENT_MACRO_SUBSTITUTION((boost::math::cstdfloat::detail::float_internal128_t)x, y); }\r\n\r\n\r\n            inline bool                                      isunordered   BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y) { return ::BOOST_CSTDFLOAT_FLOAT128_ISNAN(x) || ::BOOST_CSTDFLOAT_FLOAT128_ISNAN(y); }\r\n            template <class T>\r\n            inline typename boost::enable_if_c<\r\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\r\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\r\n               isunordered BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, T y) { return isunordered BOOST_PREVENT_MACRO_SUBSTITUTION(x, (boost::math::cstdfloat::detail::float_internal128_t)y); }\r\n            template <class T>\r\n            inline typename boost::enable_if_c<\r\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\r\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\r\n               isunordered BOOST_PREVENT_MACRO_SUBSTITUTION(T x, boost::math::cstdfloat::detail::float_internal128_t y) { return isunordered BOOST_PREVENT_MACRO_SUBSTITUTION((boost::math::cstdfloat::detail::float_internal128_t)x, y); }\r\n\r\n\r\n            //   end more functions\r\n         }\r\n      }\r\n   }\r\n} // boost::math::cstdfloat::detail\r\n\r\n// We will now inject the quadruple-precision <cmath> functions\r\n// into the std namespace. This is done via *using* directive.\r\nnamespace std\r\n{\r\n   using boost::math::cstdfloat::detail::ldexp;\r\n   using boost::math::cstdfloat::detail::frexp;\r\n   using boost::math::cstdfloat::detail::fabs;\r\n\r\n#if !(defined(_GLIBCXX_USE_FLOAT128) && defined(__GNUC__) && (__GNUC__ >= 7))\r\n   using boost::math::cstdfloat::detail::abs;\r\n#endif\r\n\r\n   using boost::math::cstdfloat::detail::floor;\r\n   using boost::math::cstdfloat::detail::ceil;\r\n   using boost::math::cstdfloat::detail::sqrt;\r\n   using boost::math::cstdfloat::detail::trunc;\r\n   using boost::math::cstdfloat::detail::exp;\r\n   using boost::math::cstdfloat::detail::expm1;\r\n   using boost::math::cstdfloat::detail::pow;\r\n   using boost::math::cstdfloat::detail::log;\r\n   using boost::math::cstdfloat::detail::log10;\r\n   using boost::math::cstdfloat::detail::sin;\r\n   using boost::math::cstdfloat::detail::cos;\r\n   using boost::math::cstdfloat::detail::tan;\r\n   using boost::math::cstdfloat::detail::asin;\r\n   using boost::math::cstdfloat::detail::acos;\r\n   using boost::math::cstdfloat::detail::atan;\r\n   using boost::math::cstdfloat::detail::sinh;\r\n   using boost::math::cstdfloat::detail::cosh;\r\n   using boost::math::cstdfloat::detail::tanh;\r\n   using boost::math::cstdfloat::detail::asinh;\r\n   using boost::math::cstdfloat::detail::acosh;\r\n   using boost::math::cstdfloat::detail::atanh;\r\n   using boost::math::cstdfloat::detail::fmod;\r\n   using boost::math::cstdfloat::detail::atan2;\r\n   using boost::math::cstdfloat::detail::lgamma;\r\n   using boost::math::cstdfloat::detail::tgamma;\r\n\r\n   //   begin more functions\r\n   using boost::math::cstdfloat::detail::remainder;\r\n   using boost::math::cstdfloat::detail::remquo;\r\n   using boost::math::cstdfloat::detail::fma;\r\n   using boost::math::cstdfloat::detail::fmax;\r\n   using boost::math::cstdfloat::detail::fmin;\r\n   using boost::math::cstdfloat::detail::fdim;\r\n   using boost::math::cstdfloat::detail::nanq;\r\n   using boost::math::cstdfloat::detail::exp2;\r\n   using boost::math::cstdfloat::detail::log2;\r\n   using boost::math::cstdfloat::detail::log1p;\r\n   using boost::math::cstdfloat::detail::cbrt;\r\n   using boost::math::cstdfloat::detail::hypot;\r\n   using boost::math::cstdfloat::detail::erf;\r\n   using boost::math::cstdfloat::detail::erfc;\r\n   using boost::math::cstdfloat::detail::llround;\r\n   using boost::math::cstdfloat::detail::lround;\r\n   using boost::math::cstdfloat::detail::round;\r\n   using boost::math::cstdfloat::detail::nearbyint;\r\n   using boost::math::cstdfloat::detail::llrint;\r\n   using boost::math::cstdfloat::detail::lrint;\r\n   using boost::math::cstdfloat::detail::rint;\r\n   using boost::math::cstdfloat::detail::modf;\r\n   using boost::math::cstdfloat::detail::scalbln;\r\n   using boost::math::cstdfloat::detail::scalbn;\r\n   using boost::math::cstdfloat::detail::ilogb;\r\n   using boost::math::cstdfloat::detail::logb;\r\n   using boost::math::cstdfloat::detail::nextafter;\r\n   using boost::math::cstdfloat::detail::nexttoward;\r\n   using boost::math::cstdfloat::detail::copysign;\r\n   using boost::math::cstdfloat::detail::signbit;\r\n   using boost::math::cstdfloat::detail::fpclassify;\r\n   using boost::math::cstdfloat::detail::isfinite;\r\n   using boost::math::cstdfloat::detail::isinf;\r\n   using boost::math::cstdfloat::detail::isnan;\r\n   using boost::math::cstdfloat::detail::isnormal;\r\n   using boost::math::cstdfloat::detail::isgreater;\r\n   using boost::math::cstdfloat::detail::isgreaterequal;\r\n   using boost::math::cstdfloat::detail::isless;\r\n   using boost::math::cstdfloat::detail::islessequal;\r\n   using boost::math::cstdfloat::detail::islessgreater;\r\n   using boost::math::cstdfloat::detail::isunordered;\r\n   //   end more functions\r\n\r\n   //\r\n   // Very basic iostream operator:\r\n   //\r\n   inline std::ostream& operator << (std::ostream& os, __float128 m_value)\r\n   {\r\n      std::streamsize digits = os.precision();\r\n      std::ios_base::fmtflags f = os.flags();\r\n      std::string s;\r\n\r\n      char buf[100];\r\n      boost::scoped_array<char> buf2;\r\n      std::string format = \"%\";\r\n      if (f & std::ios_base::showpos)\r\n         format += \"+\";\r\n      if (f & std::ios_base::showpoint)\r\n         format += \"#\";\r\n      format += \".*\";\r\n      if (digits == 0)\r\n         digits = 36;\r\n      format += \"Q\";\r\n      if (f & std::ios_base::scientific)\r\n         format += \"e\";\r\n      else if (f & std::ios_base::fixed)\r\n         format += \"f\";\r\n      else\r\n         format += \"g\";\r\n\r\n      int v = quadmath_snprintf(buf, 100, format.c_str(), digits, m_value);\r\n\r\n      if ((v < 0) || (v >= 99))\r\n      {\r\n         int v_max = v;\r\n         buf2.reset(new char[v + 3]);\r\n         v = quadmath_snprintf(&buf2[0], v_max + 3, format.c_str(), digits, m_value);\r\n         if (v >= v_max + 3)\r\n         {\r\n            BOOST_THROW_EXCEPTION(std::runtime_error(\"Formatting of float128_type failed.\"));\r\n         }\r\n         s = &buf2[0];\r\n      }\r\n      else\r\n         s = buf;\r\n      std::streamsize ss = os.width();\r\n      if (ss > static_cast<std::streamsize>(s.size()))\r\n      {\r\n         char fill = os.fill();\r\n         if ((os.flags() & std::ios_base::left) == std::ios_base::left)\r\n            s.append(static_cast<std::string::size_type>(ss - s.size()), fill);\r\n         else\r\n            s.insert(static_cast<std::string::size_type>(0), static_cast<std::string::size_type>(ss - s.size()), fill);\r\n      }\r\n\r\n      return os << s;\r\n   }\r\n\r\n\r\n} // namespace std\r\n\r\n// We will now remove the preprocessor symbols representing quadruple-precision <cmath>\r\n// functions from the preprocessor.\r\n\r\n#undef BOOST_CSTDFLOAT_FLOAT128_LDEXP\r\n#undef BOOST_CSTDFLOAT_FLOAT128_FREXP\r\n#undef BOOST_CSTDFLOAT_FLOAT128_FABS\r\n#undef BOOST_CSTDFLOAT_FLOAT128_FLOOR\r\n#undef BOOST_CSTDFLOAT_FLOAT128_CEIL\r\n#undef BOOST_CSTDFLOAT_FLOAT128_SQRT\r\n#undef BOOST_CSTDFLOAT_FLOAT128_TRUNC\r\n#undef BOOST_CSTDFLOAT_FLOAT128_EXP\r\n#undef BOOST_CSTDFLOAT_FLOAT128_EXPM1\r\n#undef BOOST_CSTDFLOAT_FLOAT128_POW\r\n#undef BOOST_CSTDFLOAT_FLOAT128_LOG\r\n#undef BOOST_CSTDFLOAT_FLOAT128_LOG10\r\n#undef BOOST_CSTDFLOAT_FLOAT128_SIN\r\n#undef BOOST_CSTDFLOAT_FLOAT128_COS\r\n#undef BOOST_CSTDFLOAT_FLOAT128_TAN\r\n#undef BOOST_CSTDFLOAT_FLOAT128_ASIN\r\n#undef BOOST_CSTDFLOAT_FLOAT128_ACOS\r\n#undef BOOST_CSTDFLOAT_FLOAT128_ATAN\r\n#undef BOOST_CSTDFLOAT_FLOAT128_SINH\r\n#undef BOOST_CSTDFLOAT_FLOAT128_COSH\r\n#undef BOOST_CSTDFLOAT_FLOAT128_TANH\r\n#undef BOOST_CSTDFLOAT_FLOAT128_ASINH\r\n#undef BOOST_CSTDFLOAT_FLOAT128_ACOSH\r\n#undef BOOST_CSTDFLOAT_FLOAT128_ATANH\r\n#undef BOOST_CSTDFLOAT_FLOAT128_FMOD\r\n#undef BOOST_CSTDFLOAT_FLOAT128_ATAN2\r\n#undef BOOST_CSTDFLOAT_FLOAT128_LGAMMA\r\n#undef BOOST_CSTDFLOAT_FLOAT128_TGAMMA\r\n\r\n//   begin more functions\r\n#undef BOOST_CSTDFLOAT_FLOAT128_REMAINDER\r\n#undef BOOST_CSTDFLOAT_FLOAT128_REMQUO\r\n#undef BOOST_CSTDFLOAT_FLOAT128_FMA\r\n#undef BOOST_CSTDFLOAT_FLOAT128_FMAX\r\n#undef BOOST_CSTDFLOAT_FLOAT128_FMIN\r\n#undef BOOST_CSTDFLOAT_FLOAT128_FDIM\r\n#undef BOOST_CSTDFLOAT_FLOAT128_NAN\r\n#undef BOOST_CSTDFLOAT_FLOAT128_EXP2\r\n#undef BOOST_CSTDFLOAT_FLOAT128_LOG2\r\n#undef BOOST_CSTDFLOAT_FLOAT128_LOG1P\r\n#undef BOOST_CSTDFLOAT_FLOAT128_CBRT\r\n#undef BOOST_CSTDFLOAT_FLOAT128_HYPOT\r\n#undef BOOST_CSTDFLOAT_FLOAT128_ERF\r\n#undef BOOST_CSTDFLOAT_FLOAT128_ERFC\r\n#undef BOOST_CSTDFLOAT_FLOAT128_LLROUND\r\n#undef BOOST_CSTDFLOAT_FLOAT128_LROUND\r\n#undef BOOST_CSTDFLOAT_FLOAT128_ROUND\r\n#undef BOOST_CSTDFLOAT_FLOAT128_NEARBYINT\r\n#undef BOOST_CSTDFLOAT_FLOAT128_LLRINT\r\n#undef BOOST_CSTDFLOAT_FLOAT128_LRINT\r\n#undef BOOST_CSTDFLOAT_FLOAT128_RINT\r\n#undef BOOST_CSTDFLOAT_FLOAT128_MODF\r\n#undef BOOST_CSTDFLOAT_FLOAT128_SCALBLN\r\n#undef BOOST_CSTDFLOAT_FLOAT128_SCALBN\r\n#undef BOOST_CSTDFLOAT_FLOAT128_ILOGB\r\n#undef BOOST_CSTDFLOAT_FLOAT128_LOGB\r\n#undef BOOST_CSTDFLOAT_FLOAT128_NEXTAFTER\r\n#undef BOOST_CSTDFLOAT_FLOAT128_NEXTTOWARD\r\n#undef BOOST_CSTDFLOAT_FLOAT128_COPYSIGN\r\n#undef BOOST_CSTDFLOAT_FLOAT128_SIGNBIT\r\n#undef BOOST_CSTDFLOAT_FLOAT128_FPCLASSIFY\r\n#undef BOOST_CSTDFLOAT_FLOAT128_ISFINITE\r\n#undef BOOST_CSTDFLOAT_FLOAT128_ISINF\r\n#undef BOOST_CSTDFLOAT_FLOAT128_ISNAN\r\n#undef BOOST_CSTDFLOAT_FLOAT128_ISNORMAL\r\n#undef BOOST_CSTDFLOAT_FLOAT128_ISGREATER\r\n#undef BOOST_CSTDFLOAT_FLOAT128_ISGREATEREQUAL\r\n#undef BOOST_CSTDFLOAT_FLOAT128_ISLESS\r\n#undef BOOST_CSTDFLOAT_FLOAT128_ISLESSEQUAL\r\n#undef BOOST_CSTDFLOAT_FLOAT128_ISLESSGREATER\r\n#undef BOOST_CSTDFLOAT_FLOAT128_ISUNORDERED\r\n//   end more functions\r\n\r\n#endif // Not BOOST_CSTDFLOAT_NO_LIBQUADMATH_SUPPORT (i.e., the user would like to have libquadmath support)\r\n\r\n#endif // BOOST_MATH_CSTDFLOAT_CMATH_2014_02_15_HPP_\r\n\r\n", "meta": {"hexsha": "34c4712a9f55c7e6159a5725789b26cc6e879e5f", "size": 75282, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/math/cstdfloat/cstdfloat_cmath.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/cstdfloat/cstdfloat_cmath.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/cstdfloat/cstdfloat_cmath.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": 68.7506849315, "max_line_length": 308, "alphanum_fraction": 0.7109136314, "num_tokens": 20594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.28321653636286415}}
{"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 \"maxwell_3d_single_layer_boundary_operator.hpp\"\n\n#include \"context.hpp\"\n#include \"general_elementary_local_operator_imp.hpp\"\n#include \"general_elementary_singular_integral_operator_imp.hpp\"\n#include \"general_hypersingular_integral_operator_imp.hpp\"\n#include \"helmholtz_3d_single_layer_boundary_operator.hpp\"\n#include \"sanitized_context.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/modified_maxwell_3d_single_layer_boundary_operator_kernel_functor.hpp\"\n#include \"../fiber/modified_maxwell_3d_single_layer_boundary_operator_kernel_interpolated_functor.hpp\"\n#include \"../fiber/modified_maxwell_3d_single_layer_operators_transformation_functor.hpp\"\n#include \"../fiber/modified_maxwell_3d_single_layer_boundary_operator_integrand_functor.hpp\"\n#include \"../fiber/hdiv_function_value_functor.hpp\"\n#include \"../fiber/scalar_function_value_functor.hpp\"\n#include \"../fiber/simple_test_trial_integrand_functor.hpp\"\n#include \"../fiber/single_component_test_trial_integrand_functor.hpp\"\n#include \"../fiber/surface_div_3d_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 \"../grid/max_distance.hpp\"\n\n#include <boost/type_traits/is_complex.hpp>\n\nnamespace Bempp {\n\ntemplate <typename BasisFunctionType>\nBoundaryOperator<BasisFunctionType,\n                 typename ScalarTraits<BasisFunctionType>::ComplexType>\nmaxwell3dSyntheticSingleLayerBoundaryOperator(\n    const shared_ptr<const Context<\n        BasisFunctionType,\n        typename ScalarTraits<BasisFunctionType>::ComplexType>> &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    typename ScalarTraits<BasisFunctionType>::ComplexType waveNumber,\n    std::string label, int internalSymmetry, bool useInterpolation,\n    int interpPtsPerWavelength) {\n  typedef typename ScalarTraits<BasisFunctionType>::ComplexType KernelType;\n  typedef typename ScalarTraits<BasisFunctionType>::ComplexType ResultType;\n  typedef typename ScalarTraits<BasisFunctionType>::RealType CoordinateType;\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        \"maxwell3dSyntheticSingleLayerBoundaryOperator(): \"\n        \"domain, range and dualToRange must not be null\");\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      domain->discontinuousSpace(domain);\n  shared_ptr<const Space<BasisFunctionType>> internalTestSpace =\n      dualToRange->discontinuousSpace(dualToRange);\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  const ResultType kappa = waveNumber / ResultType(0, 1);\n  const ResultType invKappa = static_cast<CoordinateType>(1.) / kappa;\n\n  if (label.empty())\n    label =\n        AbstractBoundaryOperator<BasisFunctionType, ResultType>::uniqueLabel();\n\n  BoundaryOperator<BasisFunctionType, ResultType> slp =\n      helmholtz3dSingleLayerBoundaryOperator<BasisFunctionType>(\n          internalContext, internalTrialSpace,\n          internalTestSpace /* or whatever */, internalTestSpace, waveNumber,\n          \"(\" + label + \")_internal_helmholtz_SLP\", internalSymmetry,\n          useInterpolation, interpPtsPerWavelength);\n\n  typedef Fiber::ScalarFunctionValueFunctor<CoordinateType> ScalarValueFunctor;\n  typedef Fiber::SurfaceDiv3dFunctor<CoordinateType> DivFunctor;\n  typedef Fiber::HdivFunctionValueFunctor<CoordinateType> VectorValueFunctor;\n  typedef Fiber::SingleComponentTestTrialIntegrandFunctor<\n      BasisFunctionType, ResultType> Term0IntegrandFunctor;\n  typedef Fiber::SimpleTestTrialIntegrandFunctor<BasisFunctionType, ResultType>\n  Term1IntegrandFunctor;\n\n  // symmetry of the decomposition\n  size_t syntheseSymmetry = 0;\n  if (domain == dualToRange && internalTrialSpace == internalTestSpace)\n    syntheseSymmetry =\n        HERMITIAN | (boost::is_complex<BasisFunctionType>() ? 0 : SYMMETRIC);\n\n  std::vector<BoundaryOperator<BasisFunctionType, ResultType>> testLocalOps;\n  std::vector<BoundaryOperator<BasisFunctionType, ResultType>> trialLocalOps;\n  testLocalOps.resize(dimWorld);\n  for (size_t i = 0; i < dimWorld; ++i)\n    testLocalOps[i] = BoundaryOperator<BasisFunctionType, ResultType>(\n        auxContext, boost::make_shared<LocalOp>(\n                        internalTestSpace, range, dualToRange,\n                        (\"(\" + label + \")_test_\") + xyz[i], NO_SYMMETRY,\n                        VectorValueFunctor(), ScalarValueFunctor(),\n                        Term0IntegrandFunctor(i, 0)));\n\n  if (!syntheseSymmetry) {\n    trialLocalOps.resize(dimWorld);\n    for (size_t i = 0; i < dimWorld; ++i)\n      trialLocalOps[i] = BoundaryOperator<BasisFunctionType, ResultType>(\n          auxContext,\n          boost::make_shared<LocalOp>(\n              domain, internalTrialSpace /* or whatever */, internalTrialSpace,\n              (\"(\" + label + \")_trial_\") + xyz[i], NO_SYMMETRY,\n              ScalarValueFunctor(), VectorValueFunctor(),\n              Term0IntegrandFunctor(0, i)));\n  }\n  // It might be more prudent to distinguish between the symmetry of the total\n  // operator and the symmetry of the decomposition\n  BoundaryOperator<BasisFunctionType, ResultType> term0(\n      context, boost::make_shared<SyntheticOp>(\n                   testLocalOps, kappa * slp, trialLocalOps,\n                   \"(\" + label + \")_term_1\", syntheseSymmetry));\n\n  testLocalOps.resize(1);\n  testLocalOps[0] = BoundaryOperator<BasisFunctionType, ResultType>(\n      auxContext, boost::make_shared<LocalOp>(\n                      internalTestSpace, range, dualToRange,\n                      (\"(\" + label + \")_test_div\"), NO_SYMMETRY, DivFunctor(),\n                      ScalarValueFunctor(), Term1IntegrandFunctor()));\n  if (!syntheseSymmetry) {\n    trialLocalOps.resize(1);\n    trialLocalOps[0] = BoundaryOperator<BasisFunctionType, ResultType>(\n        auxContext,\n        boost::make_shared<LocalOp>(\n            domain, internalTrialSpace /* or whatever */, internalTrialSpace,\n            (\"(\" + label + \")_trial_div\"), NO_SYMMETRY, ScalarValueFunctor(),\n            DivFunctor(), Term1IntegrandFunctor()));\n  } else\n    trialLocalOps.clear();\n  BoundaryOperator<BasisFunctionType, ResultType> term1(\n      context, boost::make_shared<SyntheticOp>(\n                   testLocalOps, invKappa * slp, trialLocalOps,\n                   \"(\" + label + \")_term_2\", syntheseSymmetry));\n\n  return term0 + term1;\n}\n\ntemplate <typename BasisFunctionType>\nBoundaryOperator<BasisFunctionType,\n                 typename ScalarTraits<BasisFunctionType>::ComplexType>\nmaxwell3dSingleLayerBoundaryOperator(\n    const shared_ptr<const Context<\n        BasisFunctionType,\n        typename ScalarTraits<BasisFunctionType>::ComplexType>> &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    typename ScalarTraits<BasisFunctionType>::ComplexType waveNumber,\n    const std::string &label, int symmetry, bool useInterpolation,\n    int interpPtsPerWavelength) {\n  typedef typename ScalarTraits<BasisFunctionType>::ComplexType KernelType;\n  typedef typename ScalarTraits<BasisFunctionType>::ComplexType ResultType;\n  typedef typename ScalarTraits<BasisFunctionType>::RealType CoordinateType;\n\n  shared_ptr<const Context<BasisFunctionType, ResultType>> usedContext =\n      sanitizedContext(context, true, // LOCAL_ASSEMBLY is supported\n                       false,         // but HYBRID_ASSEMBLY is not\n                       \"maxwell3dSingleLayerBoundaryOperator()\");\n\n  const AssemblyOptions &assemblyOptions = usedContext->assemblyOptions();\n  if (assemblyOptions.assemblyMode() == AssemblyOptions::ACA &&\n      assemblyOptions.acaOptions().mode == AcaOptions::LOCAL_ASSEMBLY)\n    return maxwell3dSyntheticSingleLayerBoundaryOperator(\n        context, domain, range, dualToRange, waveNumber, label, symmetry,\n        useInterpolation, interpPtsPerWavelength);\n\n  typedef Fiber::ModifiedMaxwell3dSingleLayerBoundaryOperatorKernelFunctor<\n      KernelType> KernelFunctor;\n  typedef Fiber::\n      ModifiedMaxwell3dSingleLayerBoundaryOperatorKernelInterpolatedFunctor<\n          KernelType> KernelInterpolatedFunctor;\n  typedef Fiber::ModifiedMaxwell3dSingleLayerOperatorsTransformationFunctor<\n      CoordinateType> TransformationFunctor;\n  typedef Fiber::ModifiedMaxwell3dSingleLayerBoundaryOperatorIntegrandFunctor<\n      BasisFunctionType, KernelType, ResultType> IntegrandFunctor;\n\n  typedef GeneralElementarySingularIntegralOperator<BasisFunctionType,\n                                                    KernelType, ResultType> Op;\n  if (useInterpolation)\n    return BoundaryOperator<BasisFunctionType, ResultType>(\n        usedContext,\n        boost::make_shared<Op>(\n            domain, range, dualToRange, label, symmetry,\n            KernelInterpolatedFunctor(\n                waveNumber / KernelType(0., 1.),\n                1.1 * maxDistance(*domain->grid(), *dualToRange->grid()),\n                interpPtsPerWavelength),\n            TransformationFunctor(), TransformationFunctor(),\n            IntegrandFunctor()));\n  else\n    return BoundaryOperator<BasisFunctionType, ResultType>(\n        usedContext,\n        boost::make_shared<Op>(domain, range, dualToRange, label, symmetry,\n                               KernelFunctor(waveNumber / KernelType(0., 1.)),\n                               TransformationFunctor(), TransformationFunctor(),\n                               IntegrandFunctor()));\n}\n\n#define INSTANTIATE_NONMEMBER_CONSTRUCTOR(BASIS)                               \\\n  template BoundaryOperator<BASIS, ScalarTraits<BASIS>::ComplexType>           \\\n  maxwell3dSingleLayerBoundaryOperator(                                        \\\n      const shared_ptr<                                                        \\\n          const Context<BASIS, ScalarTraits<BASIS>::ComplexType>> &,           \\\n      const shared_ptr<const Space<BASIS>> &,                                  \\\n      const shared_ptr<const Space<BASIS>> &,                                  \\\n      const shared_ptr<const Space<BASIS>> &,                                  \\\n      ScalarTraits<BASIS>::ComplexType, const std::string &, int, bool, int)\nFIBER_ITERATE_OVER_BASIS_TYPES(INSTANTIATE_NONMEMBER_CONSTRUCTOR);\n\n} // namespace Bempp\n", "meta": {"hexsha": "5f2aafb138a16eee858598026d0e13d51ac60820", "size": 12263, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/assembly/maxwell_3d_single_layer_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/maxwell_3d_single_layer_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/maxwell_3d_single_layer_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": 49.2489959839, "max_line_length": 102, "alphanum_fraction": 0.7195629128, "num_tokens": 2724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.28319905457886346}}
{"text": "#include \"hgd.hh\"\n\n#include <NTL/RR.h>\n\nusing namespace std;\nusing namespace NTL;\n\nstatic RR\nAFC(const RR &I)\n{\n    /*\n     * FUNCTION TO EVALUATE LOGARITHM OF THE FACTORIAL I\n     * IF (I .GT. 7), USE STIRLING'S APPROXIMATION\n     * OTHERWISE,  USE TABLE LOOKUP\n     */\n    double AL[8] =\n    { 0.0, 0.0, 0.6931471806, 1.791759469, 3.178053830, 4.787491743,\n      6.579251212, 8.525161361 };\n\n    if (I <= 7) {\n        return to_RR(AL[to_int(round(I))]);\n    } else {\n        RR LL = log(I);\n        return (I+0.5) * LL - I + 0.399089934;\n    }\n}\n\nstatic RR\nRAND(PRNG *prng, long precision)\n{\n    ZZ div = to_ZZ(1) << precision;\n    ZZ rzz = prng->rand_zz_mod(div);\n    return to_RR(rzz) / to_RR(div);\n}\n\nZZ\nHGD(const ZZ &KK, const ZZ &NN1, const ZZ &NN2, PRNG *prng)\n{\n    /*\n     * XXX\n     * NTL is single-threaded by design: there is a global precision\n     * setting, which gets switched back and forth all over the place\n     * (see NTL's RR.c).  We should hold a lock around any RR usage,\n     * or re-implement the relevant parts of NTL::RR with a scoped\n     * precision parameter..\n     */\n    long precision = NumBits(NN1 + NN2 + KK) + 10;\n    RR::SetPrecision(precision);\n\n    RR JX;      // the result\n    RR TN, N1, N2, K;\n    RR P, U, V, A, IX, XL, XR, M;\n    RR KL, KR, LAMDL, LAMDR, NK, NM, P1, P2, P3;\n\n    bool REJECT;\n    RR MINJX, MAXJX;\n\n    double CON = 57.56462733;\n    double DELTAL = 0.0078;\n    double DELTAU = 0.0034;\n    double SCALE = 1.0e25;\n\n    /*\n     * CHECK PARAMETER VALIDITY\n     */\n    if ((NN1 < 0) || (NN2 < 0) || (KK < 0) || (KK > NN1 + NN2))\n        throw_c(false);\n\n    /*\n     * INITIALIZE\n     */\n    REJECT = true;\n\n    if (NN1 >= NN2) {\n        N1 = to_RR(NN2);\n        N2 = to_RR(NN1);\n    } else {\n        N1 = to_RR(NN1);\n        N2 = to_RR(NN2);\n    }\n\n    TN = N1 + N2;\n\n    if (to_RR(KK + KK) >= TN)  {\n        K = TN - to_RR(KK);\n    } else {\n        K = to_RR(KK);\n    }\n\n    M = (K+1) * (N1+1) / to_RR(TN+2);\n\n    if (K-N2 < 0) {\n        MINJX = 0;\n    } else {\n        MINJX = K-N2;\n    }\n\n    if (N1 < K) {\n        MAXJX = N1;\n    } else {\n        MAXJX = K;\n    }\n\n    /*\n     * GENERATE RANDOM VARIATE\n     */\n    if (MINJX == MAXJX)  {\n        /*\n         * ...DEGENERATE DISTRIBUTION...\n         */\n        IX = MAXJX;\n    } else if (M-MINJX < 10) {\n        /*\n         * ...INVERSE TRANSFORMATION...\n         * Shouldn't really happen in OPE because M will be on the order of N1.\n         * In practice, this does get invoked.\n         */\n        RR W;\n        if (K < N2) {\n            W = exp(CON + AFC(N2) + AFC(N1+N2-K) - AFC(N2-K) - AFC(N1+N2));\n        } else {\n            W = exp(CON + AFC(N1) + AFC(K) - AFC(K-N2) - AFC(N1+N2));\n        }\n\n label10:\n        P  = W;\n        IX = MINJX;\n        U  = RAND(prng, precision) * SCALE;\n\n label20:\n        if (U > P) {\n            U  = U - P;\n            P  = P * (N1-IX)*(K-IX);\n            IX = IX + 1;\n            P  = P / IX / (N2-K+IX);\n            if (IX > MAXJX)\n                goto label10;\n            goto label20;\n        }\n    } else {\n        /*\n         * ...H2PE...\n         */\n        RR S;\n        SqrRoot(S, (TN-K) * K * N1 * N2 / (TN-1) / TN /TN);\n\n        /*\n         * ...REMARK:  D IS DEFINED IN REFERENCE WITHOUT INT.\n         * THE TRUNCATION CENTERS THE CELL BOUNDARIES AT 0.5\n         */\n        RR D = trunc(1.5*S) + 0.5;\n        XL = trunc(M - D + 0.5);\n        XR = trunc(M + D + 0.5);\n        A = AFC(M) + AFC(N1-M) + AFC(K-M) + AFC(N2-K+M);\n        RR expon = A - AFC(XL) - AFC(N1-XL)- AFC(K-XL) - AFC(N2-K+XL);\n\n        KL = exp(expon);\n        KR = exp(A - AFC(XR-1) - AFC(N1-XR+1) - AFC(K-XR+1) - AFC(N2-K+XR-1));\n        LAMDL = -log(XL * (N2-K+XL) / (N1-XL+1) / (K-XL+1));\n        LAMDR = -log((N1-XR+1) * (K-XR+1) / XR / (N2-K+XR));\n        P1 = 2*D;\n        P2 = P1 + KL / LAMDL;\n        P3 = P2 + KR / LAMDR;\n\n label30:\n        U = RAND(prng, precision) * P3;\n        V = RAND(prng, precision);\n\n        if (U < P1)  {\n            /* ...RECTANGULAR REGION... */\n            IX    = XL + U;\n        } else if  (U <= P2)  {\n            /* ...LEFT TAIL... */\n            IX = XL + log(V)/LAMDL;\n            if (IX < MINJX) {\n                goto label30;\n            }\n            V = V * (U-P1) * LAMDL;\n        } else  {\n            /* ...RIGHT TAIL... */\n            IX = XR - log(V)/LAMDR;\n            if (IX > MAXJX)  {\n                goto label30;\n            }\n            V = V * (U-P2) * LAMDR;\n        }\n\n        /*\n         * ...ACCEPTANCE/REJECTION TEST...\n         */\n        RR F;\n        if ((M < 100) || (IX <= 50))  {\n            /* ...EXPLICIT EVALUATION... */\n            F = to_RR(1.0);\n            if (M < IX) {\n                for (RR I = M+1; I < IX; I++) {\n                    /*40*/ F = F * (N1-I+1) * (K-I+1) / (N2-K+I) / I;\n                }\n            } else if (M > IX) {\n                for (RR I = IX+1; I < M; I++) {\n                    /*50*/ F = F * I * (N2-K+I) / (N1-I) / (K-I);\n                }\n            }\n            if (V <= F)  {\n                REJECT = false;\n            }\n        } else {\n            /* ...SQUEEZE USING UPPER AND LOWER BOUNDS... */\n\n            RR Y   = IX;\n            RR Y1  = Y + 1.;\n            RR YM  = Y - M;\n            RR YN  = N1 - Y + 1.;\n            RR YK  = K - Y + 1.;\n            NK     = N2 - K + Y1;\n            RR R   = -YM / Y1;\n            S      = YM / YN;\n            RR T   = YM / YK;\n            RR E   = -YM / NK;\n            RR G   = YN * YK / (Y1*NK) - 1.;\n            RR DG  = to_RR(1.0);\n            if (G < 0)  { DG = 1.0 + G; }\n            RR GU  = G * (1.+G*(-0.5+G/3.0));\n            RR GL  = GU - 0.25 * sqr(sqr(G)) / DG;\n            RR XM  = M + 0.5;\n            RR XN  = N1 - M + 0.5;\n            RR XK  = K - M + 0.5;\n            NM     = N2 - K + XM;\n            RR UB  = Y * GU - M * GL + DELTAU +\n                     XM * R * (1.+R*(-.5+R/3.)) +\n                     XN * S * (1.+S*(-.5+S/3.)) +\n                     XK * T * (1.+T*(-.5+T/3.)) +\n                     NM * E * (1.+E*(-.5+E/3.));\n\n            /* ...TEST AGAINST UPPER BOUND... */\n\n            RR ALV = log(V);\n            if (ALV > UB) {\n                REJECT = true;\n            } else {\n                /* ...TEST AGAINST LOWER BOUND... */\n\n                RR DR = XM * sqr(sqr(R));\n                if (R < 0) {\n                    DR = DR / (1.+R);\n                }\n                RR DS = XN * sqr(sqr(S));\n                if (S < 0) {\n                    DS = DS / (1.+S);\n                }\n                RR DT = XK * sqr(sqr(T));\n                if (T < 0) {\n                    DT = DT / (1.+T);\n                }\n                RR DE = NM * sqr(sqr(E));\n                if (E < 0) {\n                    DE = DE / (1.+E);\n                }\n                if (ALV < UB-0.25*(DR+DS+DT+DE) + (Y+M)*(GL-GU) - DELTAL) {\n                    REJECT = false;\n                } else {\n                    /* ...STIRLING'S FORMULA TO MACHINE ACCURACY... */\n\n                    if (ALV <=\n                        (A - AFC(IX) -\n                         AFC(N1-IX)  - AFC(K-IX) - AFC(N2-K+IX)) ) {\n                        REJECT = false;\n                    } else {\n                        REJECT = true;\n                    }\n                }\n            }\n        }\n        if (REJECT)  {\n            goto label30;\n        }\n    }\n\n    /*\n     * RETURN APPROPRIATE VARIATE\n     */\n\n    if (KK + KK >= to_ZZ(TN)) {\n        if (NN1 > NN2) {\n            IX = to_RR(KK - NN2) + IX;\n        } else {\n            IX = to_RR(NN1) - IX;\n        }\n    } else {\n        if (NN1 > NN2) {\n            IX = to_RR(KK) - IX;\n        }\n    }\n    JX = IX;\n    return to_ZZ(JX);\n}\n", "meta": {"hexsha": "2611a1e65c93bc2c7014fa0c7bb35afcb3f0ccbf", "size": 7696, "ext": "cc", "lang": "C++", "max_stars_repo_path": "ope-from-cryptodb/lib/hgd.cc", "max_stars_repo_name": "xietian1/mpkix-judgement", "max_stars_repo_head_hexsha": "2cca8b509d2804c85bb39abc397f34ad4f2666b1", "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": "ope-from-cryptodb/lib/hgd.cc", "max_issues_repo_name": "xietian1/mpkix-judgement", "max_issues_repo_head_hexsha": "2cca8b509d2804c85bb39abc397f34ad4f2666b1", "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": "ope-from-cryptodb/lib/hgd.cc", "max_forks_repo_name": "xietian1/mpkix-judgement", "max_forks_repo_head_hexsha": "2cca8b509d2804c85bb39abc397f34ad4f2666b1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9124579125, "max_line_length": 79, "alphanum_fraction": 0.362006237, "num_tokens": 2590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2831664417534449}}
{"text": "#include \"ros/ros.h\"\n\n#include <tf/transform_listener.h>\n// #include <tf_conversions/tf_eigen.h>\n#include <geometry_msgs/Twist.h>\n\n#include <tf2/LinearMath/Quaternion.h>\n#include <tf2/LinearMath/Matrix3x3.h>\n\n#include <sstream>\n#include <fstream>\n#include <chrono>\n\n#include <termios.h>\n#include <stdio.h>\n#include <iostream>\n\n/* crazyflie_driver */\n#include \"crazyflie_driver/AddCrazyflie.h\"\n#include \"crazyflie_driver/LogBlock.h\"\n#include \"crazyflie_driver/GenericLogData.h\"\n#include \"crazyflie_driver/UpdateParams.h\"\n#include \"crazyflie_driver/UploadTrajectory.h\"\n#include \"crazyflie_driver/NotifySetpointsStop.h\"\n#undef major\n#undef minor\n#include \"crazyflie_driver/Hover.h\"\n#include \"crazyflie_driver/Takeoff.h\"\n#include \"crazyflie_driver/Land.h\"\n#include \"crazyflie_driver/GoTo.h\"\n#include \"crazyflie_driver/StartTrajectory.h\"\n#include \"crazyflie_driver/SetGroupMask.h\"\n#include \"crazyflie_driver/FullState.h\"\n#include \"crazyflie_driver/Position.h\"\n#include \"crazyflie_driver/VelocityWorld.h\"\n\n/* Includes form iLQR main.cpp */\n#include <unsupported/Eigen/AdolcForward>\n#include <Eigen/Dense>\n#include <adolc/adolc.h>\n#include <adolc/adouble.h>\n#include <vector>\n#include <time.h>\n#include <math.h>\n#include <fstream>\n#include <thread>\n#include <future>\n#include <algorithm>\n#include <iterator>\n#include \"cost.h\"\n#include \"dynamics.h\"\n#include \"iLQR.h\"\n#include \"utils.h\"\n#include <unistd.h>\n\n/* simple moving average filter */\n#define USE_SMA_FILTER 0\n#define SMA_WINDOW_LEN 10\n\n/* first order exponential low-pass filter */\n#define USE_EXP_FILTER 1\n#define EXP_FILT_ALPHA 0.9f\n\n\n// static stateVector prevState_cf1;\n// static stateVector stateWindowBuf_cf1[SMA_WINDOW_LEN];\n\n// static stateVector prevState_cf2;\n// static stateVector stateWindowBuf_cf2[SMA_WINDOW_LEN];\n\nstatic stateVector CFState_cf1;\nstatic stateVector CFState_cf2;\nstatic stateVector CFState_cf3;\nstatic stateVector CFState_cf4;\n\nstatic pose currentPose;\n// static pose prevPose_cf1;\n\n// static pose currentPose_cf2;\n// static pose prevPose_cf2;\n\nstd::ofstream droneDatalogFile;\nstd::ofstream optimizerDatalogFile;\n\nbool first = true;\n\nvoid poseCallback(const tf2_msgs::TFMessage::ConstPtr& msg) {\n\n    /* Collect pose and timestamp information */\n    std::string cf_id = msg->transforms[0].child_frame_id;\n    int secs = msg->transforms[0].header.stamp.sec;\n    int nsecs = msg->transforms[0].header.stamp.nsec;\n    float x = msg->transforms[0].transform.translation.x;\n    float y = msg->transforms[0].transform.translation.y;\n    float z = msg->transforms[0].transform.translation.z;\n    float qx = msg->transforms[0].transform.rotation.x;\n    float qy = msg->transforms[0].transform.rotation.y;\n    float qz = msg->transforms[0].transform.rotation.z;\n    float qw = msg->transforms[0].transform.rotation.w;\n    tf2::Quaternion q(qx, qy, qz, qw);\n\n    /* Quaternion to roll,pitch,yaw conversion */\n    double roll, pitch, yaw;\n    tf2::Matrix3x3 m(q);\n    m.getRPY(roll, pitch, yaw);\n\n    /* Calculate timestamp in nanoseconds*/\n    unsigned long timeStamp = (secs * 1e9) + nsecs;\n    double deltaT = 0.0;\n\n\n    if (cf_id == \"cf1\") {\n        CFState_cf1.x = x;\n        CFState_cf1.y = y;\n        CFState_cf1.z = z;\n        CFState_cf1.roll = roll;\n        CFState_cf1.pitch = pitch;\n        CFState_cf1.yaw = yaw;\n    } else if (cf_id == \"cf2\") {\n        CFState_cf2.x = x;\n        CFState_cf2.y = y;\n        CFState_cf2.z = z;\n        CFState_cf2.roll = roll;\n        CFState_cf2.pitch = pitch;\n        CFState_cf2.yaw = yaw;\n    } else if (cf_id == \"cf3\") {\n        CFState_cf3.x = x;\n        CFState_cf3.y = y;\n        CFState_cf3.z = z;\n        CFState_cf3.roll = roll;\n        CFState_cf3.pitch = pitch;\n        CFState_cf3.yaw = yaw;\n    } else if (cf_id == \"cf4\") {\n        CFState_cf4.x = x;\n        CFState_cf4.y = y;\n        CFState_cf4.z = z;\n        CFState_cf4.roll = roll;\n        CFState_cf4.pitch = pitch;\n        CFState_cf4.yaw = yaw;\n    }\n\n    std::vector<stateVector> states{CFState_cf1, CFState_cf2, CFState_cf3, CFState_cf4};\n\n    logDroneStates(droneDatalogFile, states);\n\n    // std::printf(\"\\n\");\n    // std::printf(\"##### CF1:\\n\");\n    // std::printf(\"X: %f,\\t Y: %f,\\t Z: %f\\t\\n ROLL: %f,\\t PITCH: %f,\\t YAW %f\\n\",\n    //             CFState_cf1.x, CFState_cf1.y, CFState_cf1.z, CFState_cf1.roll, CFState_cf1.pitch, CFState_cf1.yaw);\n    // std::printf(\"X_d: %f\\t, Y_d: %f\\t, Z_d: %f\\t\\nROLL_d: %f\\t, PITCH_d: %f\\t, YAW_d %f\\n\",\n    //             CFState_cf1.x_d, CFState_cf1.y_d, CFState_cf1.z_d, CFState_cf1.roll_d, CFState_cf1.pitch_d, CFState_cf1.yaw_d);\n\n    // std::printf(\"\\n##### CF2:\\n\");\n    // std::printf(\"X: %f,\\t Y: %f,\\t Z: %f\\t\\n ROLL: %f,\\t PITCH: %f,\\t YAW %f\\n\",\n    //             CFState_cf2.x, CFState_cf2.y, CFState_cf2.z, CFState_cf2.roll, CFState_cf2.pitch, CFState_cf2.yaw);\n    // std::printf(\"X_d: %f\\t, Y_d: %f\\t, Z_d: %f\\t\\nROLL_d: %f\\t, PITCH_d: %f\\t, YAW_d %f\\n\",\n    //             CFState_cf2.x_d, CFState_cf2.y_d, CFState_cf2.z_d, CFState_cf2.roll_d, CFState_cf2.pitch_d, CFState_cf2.yaw_d);\n}\n\n/* Modification of getch() to be non-blocking */\nint getch() {\n  static struct termios oldt, newt;\n  tcgetattr( STDIN_FILENO, &oldt);           // save old settings\n  newt = oldt;\n  newt.c_lflag &= ~(ICANON);                 // disable buffering\n  newt.c_cc[VMIN] = 0; newt.c_cc[VTIME] = 0;\n  tcsetattr( STDIN_FILENO, TCSANOW, &newt);  // apply new settings\n  int c = getchar();                         // read character (non-blocking)\n  tcsetattr( STDIN_FILENO, TCSANOW, &oldt);  // restore old settings\n  return c;\n}\n\n\nint main(int argc, char **argv) {\n\n    srand((unsigned int) time(0));\n\n    init_datalog(droneDatalogFile,\n                 \"/home/ayberk/Documents/ACTIONLAB/crazyswarm/ros_ws/src/iLQR/datalog/\",\n                 \"droneStates_2x\");\n\n    init_datalog(optimizerDatalogFile,\n                 \"/home/ayberk/Documents/ACTIONLAB/crazyswarm/ros_ws/src/iLQR/datalog/\",\n                 \"optimizer_2x\");\n\n    ros::init(argc, argv, \"iLQR_Node\");\n\n    ros::NodeHandle n;\n\n    ros::Subscriber state_subscriber = n.subscribe(\"tf\", 1000, poseCallback);\n\n    /* Publisher to cmd_position topic (currently doesn't work) */\n    // ros::Publisher pub = n.advertise<crazyflie_driver::Position>(\"cf1/cmd_position\",1);\n    // crazyflie_driver::Position position_cmd;\n\n    /* Service clients for simple high-level commands */\n    ros::ServiceClient takeoffClient = n.serviceClient<crazyflie_driver::Takeoff>(\"/takeoff\");\n    ros::ServiceClient landClient = n.serviceClient<crazyflie_driver::Land>(\"/land\");\n    ros::ServiceClient GoToClient_cf1 = n.serviceClient<crazyflie_driver::GoTo>(\"/cf1/go_to\");\n    ros::ServiceClient GoToClient_cf2 = n.serviceClient<crazyflie_driver::GoTo>(\"/cf2/go_to\");\n    ros::ServiceClient GoToClient_cf3 = n.serviceClient<crazyflie_driver::GoTo>(\"/cf3/go_to\");\n    ros::ServiceClient GoToClient_cf4 = n.serviceClient<crazyflie_driver::GoTo>(\"/cf4/go_to\");\n\n    /* Wait for <Enter> key press to begin mission */\n    std::cout << \"\\t########## PRESS <Enter> TO BEGIN MISSION ##########\" << std::endl;\n    while (true) {\n        int c = getch();\n            if (c == '\\n') {\n                std::cout << \"\\t########## BEGINNING MISSION ##########\" << std::endl;\n                break;\n            }\n            ros::spinOnce();\n    }\n\n    /* Construct GoTo service once to be used in loop */\n    crazyflie_driver::GoTo srvGoTo_cf1;\n    srvGoTo_cf1.request.groupMask = 0;  // signal all CFs (I think?)\n    crazyflie_driver::GoTo srvGoTo_cf2;\n    srvGoTo_cf2.request.groupMask = 0;\n    crazyflie_driver::GoTo srvGoTo_cf3;\n    srvGoTo_cf3.request.groupMask = 0;\n    crazyflie_driver::GoTo srvGoTo_cf4;\n    srvGoTo_cf4.request.groupMask = 0;\n\n    /* Send takeoff command through /Takeoff service */\n    crazyflie_driver::Takeoff srvTakeoff;\n    srvTakeoff.request.groupMask = 0;\n    srvTakeoff.request.height = 1.0;\n    srvTakeoff.request.duration = ros::Duration(3.0);\n    takeoffClient.call(srvTakeoff);\n    ros::Duration(3.0).sleep();\n\n\n\n\n\n\n\n    // srvGoTo_cf1.request.goal.x = 0.0;\n    // srvGoTo_cf1.request.goal.y = 1.25;\n    // srvGoTo_cf1.request.goal.z = 1.5;\n    // srvGoTo_cf1.request.yaw = 0.0;\n    // srvGoTo_cf1.request.duration = ros::Duration(2.0);\n    // GoToClient_cf1.call(srvGoTo_cf1);\n    // srvGoTo_cf2.request.goal.x = 1.25;\n    // srvGoTo_cf2.request.goal.y = 0.0;\n    // srvGoTo_cf2.request.goal.z = 1.5;\n    // srvGoTo_cf2.request.yaw = 0.0;\n    // srvGoTo_cf2.request.duration = ros::Duration(2.0);\n    // GoToClient_cf2.call(srvGoTo_cf2);\n    // // ros::Duration(2.0).sleep();\n    // srvGoTo_cf3.request.goal.x = 0.0;\n    // srvGoTo_cf3.request.goal.y = 1.0;\n    // srvGoTo_cf3.request.goal.z = 1.0;\n    // srvGoTo_cf3.request.yaw = 0.0;\n    // srvGoTo_cf3.request.duration = ros::Duration(2.0);\n    // GoToClient_cf3.call(srvGoTo_cf3);\n    // srvGoTo_cf4.request.goal.x = 1.5;\n    // srvGoTo_cf4.request.goal.y = 0.0;\n    // srvGoTo_cf4.request.goal.z = 1.0;\n    // srvGoTo_cf4.request.yaw = 0.0;\n    // srvGoTo_cf4.request.duration = ros::Duration(2.0);\n    // GoToClient_cf4.call(srvGoTo_cf4);\n    // ros::Duration(2.0).sleep();\n\n\n//     /* iLQR solver parameters */\n//     constexpr size_t horizon=5;\n//     constexpr int total_steps=300;\n//     unsigned int tag1(1),tag2(2),tag3(3),tag4(4),tag5(5),\n//                  tag6(6),tag7(7),tag8(8),tag9(9);\n//\n//     double time_step=0.2;\n//\n//\n//     /*First Order 2 Drone Simulation*/\n//\n// \tcost<12,12> drone2_running_cost(Drone_First_Order_Cost::running_cost2,tag7);\n// \tcost<12,12> drone2_terminal_cost(Drone_First_Order_Cost::terminal_cost2,tag8);\n// \tdynamics<12,12> drone2_dynamics(Drone_First_Order_Dynamics::dynamics_2,tag9,time_step);\n// \tiLQR<12,12,horizon>::input_trajectory u_init_drone2;\n// \tiLQR<12,12,horizon> drone2_solver(drone2_running_cost,drone2_terminal_cost,drone2_dynamics);\n// \tEigen::Matrix<double,12,1> u_drone2=Eigen::Matrix<double,12,1>::Zero();\n// \tEigen::Matrix<double,12,1> x0_drone2=Eigen::Matrix<double,12,1>::Zero();\n// \tEigen::Matrix<double,12,1> x_goal_drone2;\n// \tiLQR<12,12,horizon>::state_input_trajectory soln_drone2;\n// \tiLQR<12,12,total_steps>::state_input_trajectory soln_drone2_rhc;\n//\n// \t//\tu_drone2=u_drone2*sqrt(Drone_Dynamics::mass*Drone_Dynamics::g/(4*Drone_Dynamics::C_T));\n// \tstd::fill(std::begin(u_init_drone2), std::end(u_init_drone2), u_drone2);\n//     for (auto &item : u_init_drone2)\n//         item = Eigen::Matrix<double,12,1>::Random()*5;\n//\n// //\tiLQR<12*2,4*2,horizon>::state_input_trajectory soln_drone2;\n// //\tiLQR<12*2,4*2,total_steps>::state_input_trajectory soln_drone2_rhc;\n//\n// \tclock_t t_start, t_end;\n//\n//\n// \tdouble seconds;\n// \tdrone2_solver.set_MPC(u_init_drone2);\n// \tint execution_steps=1;\n// \tsoln_drone2_rhc.first[0]=x0_drone2;\n// \t// std::string state_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/states.txt\";\n// \t// std::string input_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/inputs.txt\";\n// \tt_start = clock();\n//\n//     x_goal_drone2 << 1.25, 0.0, 2.5, 0,0,0,\n//                      0.0, 1.25,  2.5, 0,0,0;\n\n    while (ros::ok())\n//     // while (true)\n\t{\n//\n//         ros::spinOnce();\n//\n//\n// \t\tx0_drone2 << CFState_cf1.x, CFState_cf1.y, CFState_cf1.z,\n//                      CFState_cf1.roll, CFState_cf1.pitch, CFState_cf1.yaw,\n//                      CFState_cf2.x, CFState_cf2.y, CFState_cf2.z,\n//                      CFState_cf2.roll, CFState_cf2.pitch, CFState_cf2.yaw;\n//\n//\n// \t\tsoln_drone2=drone2_solver.run_MPC(x0_drone2,\n// \t\t\t\tx_goal_drone2, 50, 2, execution_steps);\n//\n//         /* Optimizer output logging */\n//         std::string data;\n//         for (int i = 0; i < horizon; ++i) {\n//             for (int q = 0; q < 12; ++q) {\n//                 data += std::to_string(soln_drone2.first[i][q]) + \",\";\n//             }\n//\n//         }\n//         const auto p1 = std::chrono::system_clock::now();\n//     \tdata += std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(p1.time_since_epoch()).count()) + \"\\n\";\n//     \toptimizerDatalogFile << data;\n//\n//         int idx_to_use = 3;\n//\n//         std::printf(\"\\n#### SENDING WAYPOINT CF1  \");\n//         std::printf(\"X: %f,\\t Y: %f,\\t Z: %f\\n\", soln_drone2.first[idx_to_use][0], soln_drone2.first[idx_to_use][1], soln_drone2.first[idx_to_use][2]);\n//         std::printf(\"\\n#### SENDING WAYPOINT CF2   \");\n//         std::printf(\"X: %f,\\t Y: %f,\\t Z: %f\\n\", soln_drone2.first[idx_to_use][6], soln_drone2.first[idx_to_use][7], soln_drone2.first[idx_to_use][8]);\n//\n//         srvGoTo_cf1.request.goal.x = soln_drone2.first[idx_to_use][0];\n//         srvGoTo_cf1.request.goal.y = soln_drone2.first[idx_to_use][1];\n//         srvGoTo_cf1.request.goal.z = soln_drone2.first[idx_to_use][2];\n//         srvGoTo_cf1.request.yaw = 0.0;\n//         srvGoTo_cf1.request.duration = ros::Duration(0.8);\n//         GoToClient_cf1.call(srvGoTo_cf1);\n//\n//         srvGoTo_cf2.request.goal.x = soln_drone2.first[idx_to_use][6];\n//         srvGoTo_cf2.request.goal.y = soln_drone2.first[idx_to_use][7];\n//         srvGoTo_cf2.request.goal.z = soln_drone2.first[idx_to_use][8];\n//         srvGoTo_cf2.request.yaw = 0.0;\n//         srvGoTo_cf2.request.duration = ros::Duration(0.8);\n//         GoToClient_cf2.call(srvGoTo_cf2);\n//\n        int c = getch();   // call your non-blocking input function\n        if (c == '\\n') {\n            std::cout << \"########## LANDING ##########\" << std::endl;\n            break;\n        }\n        if (c == 'o') {\n            std::cout << \"########## RETURN TO ORIGIN ##########\" << std::endl;\n            srvGoTo_cf1.request.goal.x = -0.2;\n            srvGoTo_cf1.request.goal.y = 1.1;\n            srvGoTo_cf1.request.goal.z = 1.5;\n            srvGoTo_cf1.request.yaw = 0.0;\n            srvGoTo_cf1.request.duration = ros::Duration(3.0);\n            GoToClient_cf1.call(srvGoTo_cf1);\n            srvGoTo_cf2.request.goal.x = 0.55;\n            srvGoTo_cf2.request.goal.y = 0.3;\n            srvGoTo_cf2.request.goal.z = 0.5;\n            srvGoTo_cf2.request.yaw = 0.0;\n            srvGoTo_cf2.request.duration = ros::Duration(3.0);\n            GoToClient_cf2.call(srvGoTo_cf2);\n            ros::Duration(3.0).sleep();\n            break;\n        }\n//\n//\n\t}\n// \tt_end = clock();\n// ////\n// //////\n// ////////\tsoln_drone=drone_solver.solve_open_loop(X0_drone, X0_drone, 200, u_init_drone, horizon);\n// ////////\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n// \t// write_file<12,12,total_steps>(state_path,input_path, soln_drone2_rhc);\n// ////\n// \tstd::cout<<\"finished\"<<std::endl;\n// \tseconds = 1/((double)(t_end - t_start) / CLOCKS_PER_SEC/total_steps);\n// \tprintf(\"Time: %f s\\n\", seconds);\n\n\n    /*First Order 2 Drone Simulation Ends*/\n\n\n\n\n    crazyflie_driver::Land srvLand;\n    srvLand.request.duration = ros::Duration(3.0);\n    landClient.call(srvLand);\n\n    ros::spin();\n\n    return 0;\n}\n\n/*############################################################################*/\n/*############################################################################*/\n/*############################################################################*/\n\n\n\n// /*First Order Drone Simulation */\n//\n//\n//\n// \tcost<6,6> drone_running_cost(Drone_First_Order_Cost::running_cost,tag7);\n// \tcost<6,6> drone_terminal_cost(Drone_First_Order_Cost::terminal_cost,tag8);\n// \tdynamics<6,6> drone_dynamics(Drone_First_Order_Dynamics::dynamics,tag9,time_step);\n// \tiLQR<6,6,horizon>::input_trajectory u_init_drone;\n// \tiLQR<6,6,horizon> drone_solver(drone_running_cost,drone_terminal_cost,drone_dynamics);\n// \tEigen::Matrix<double,6,1> u_drone=Eigen::Matrix<double,6,1>::Zero();\n// \tEigen::Matrix<double,6,1> x0_drone=Eigen::Matrix<double,6,1>::Zero();\n// \tEigen::Matrix<double,6,1> x_goal_drone;\n// \tiLQR<6,6,horizon>::state_input_trajectory soln_drone;\n// \tiLQR<6,6,total_steps>::state_input_trajectory soln_drone_rhc;\n//\n// \t//\tu_drone2=u_drone2*sqrt(Drone_Dynamics::mass*Drone_Dynamics::g/(4*Drone_Dynamics::C_T));\n// \t\tstd::fill(std::begin(u_init_drone), std::end(u_init_drone), u_drone);\n// \t//\tiLQR<12*2,4*2,horizon>::state_input_trajectory soln_drone2;\n// \t//\tiLQR<12*2,4*2,total_steps>::state_input_trajectory soln_drone2_rhc;\n//\n//\n//\n//\n//\n// \t\tclock_t t_start, t_end;\n// \t//\n// \t////\n// \t\tx0_drone<<0,0,0.5, 0,0,0;\n// \t//\tx0_integrator+=0.1*Eigen::Matrix<double,3,1>::Random();\n// \t\tdouble seconds;\n// \t\tdrone_solver.set_MPC(u_init_drone);\n// \t\tint execution_steps=1;\n// \t\t// soln_drone_rhc.first[0]=x0_drone;\n// \t\t// std::string state_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/states.txt\";\n// \t\t// std::string input_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/inputs.txt\";\n// \t\tt_start = clock();\n// \t\t// for(int i=0;i<total_steps;++i)\n//\n//         x_goal_drone<<1,1,1, 0,0,0;\n//\n//         while (ros::ok())\n// \t\t{\n//             ros::spinOnce();\n//\n// \t//\t\tif (i>total_steps/3)\n// \t//\t\t\tx_goal_integrator<<0,0,0;\n// \t\t\t// std::cout<<\"iteration \"<<i<<std::endl;\n// \t\t\t// double scale=0.01;\n// \t\t\t// auto term1=soln_drone_rhc.first[i]+scale*Eigen::Matrix<double,6,1>::Random();\n// \t\t\t// auto term2=soln_drone_rhc.first[i]+scale*Eigen::Matrix<double,6,1>::Random();\n// //\t\t\tauto term3=soln_drone_rhc.first[i]+scale*Eigen::Matrix<double,6,1>::Random();\n// //\t\t\tauto term4=soln_drone_rhc.first[i]+scale*Eigen::Matrix<double,6,1>::Random();\n// //\t\t\tauto term5=soln_drone_rhc.first[i]+scale*Eigen::Matrix<double,6,1>::Random();\n// //\t\t\tauto term6=soln_drone_rhc.first[i]+scale*Eigen::Matrix<double,6,1>::Random();\n// //\t\t\tauto term7=soln_drone_rhc.first[i]+scale*Eigen::Matrix<double,6,1>::Random();\n// //\t\t\tauto term8=soln_drone_rhc.first[i]+scale*Eigen::Matrix<double,6,1>::Random();\n// //\t\t\tauto term9=soln_drone_rhc.first[i]+scale*Eigen::Matrix<double,6,1>::Random();\n// //\t\t\tauto term10=soln_drone_rhc.first[i]+scale*Eigen::Matrix<double,6,1>::Random();\n// //\t\t\tauto term=(term1+term2+term3+term4+term5+term6+term7+term8+term9+term10)/10;\n//\n//             x0_drone << CFState_cf1.x, CFState_cf1.y, CFState_cf1.z,\n//                         CFState_cf1.roll, CFState_cf1.pitch,  CFState_cf1.yaw;\n//\n// \t\t\tsoln_drone=drone_solver.run_MPC(x0_drone,\n// \t\t\t\t\tx_goal_drone, 5, execution_steps);\n//\n//             int idx_to_use = 1;\n//\n//             std::printf(\"\\n#### SENDING WAYPOINT   \");\n//             std::printf(\"X: %f,\\t Y: %f,\\t Z: %f\\n\", soln_drone.first[idx_to_use][0], soln_drone.first[idx_to_use][1], soln_drone.first[idx_to_use][2]);\n//\n//             srvGoTo_cf1.request.goal.x = soln_drone.first[idx_to_use][0];\n//             srvGoTo_cf1.request.goal.y = soln_drone.first[idx_to_use][1];\n//             srvGoTo_cf1.request.goal.z = soln_drone.first[idx_to_use][2];\n//             srvGoTo_cf1.request.yaw = 0.0;\n//             srvGoTo_cf1.request.duration = ros::Duration(1.0);\n//             // GoToClient_cf1.call(srvGoTo_cf1);\n//\n//             int c = getch();   // call your non-blocking input function\n//             if (c == '\\n') {\n//                 std::cout << \"########## LANDING ##########\" << std::endl;\n//                 break;\n//             }\n//             if (c == 'o') {\n//                 std::cout << \"########## RETURN TO ORIGIN ##########\" << std::endl;\n//                 srvGoTo_cf1.request.goal.x = 0.5;\n//                 srvGoTo_cf1.request.goal.y = 0.5;\n//                 srvGoTo_cf1.request.goal.z = 0.5;\n//                 srvGoTo_cf1.request.yaw = 0.0;\n//                 srvGoTo_cf1.request.duration = ros::Duration(3.0);\n//                 GoToClient_cf1.call(srvGoTo_cf1);\n//                 srvGoTo_cf2.request.goal.x = -0.5;\n//                 srvGoTo_cf2.request.goal.y = -0.5;\n//                 srvGoTo_cf2.request.goal.z = 0.5;\n//                 srvGoTo_cf2.request.yaw = 0.0;\n//                 srvGoTo_cf2.request.duration = ros::Duration(3.0);\n//                 GoToClient_cf2.call(srvGoTo_cf2);\n//                 ros::Duration(3.0).sleep();\n//                 break;\n//             }\n// \t////\n// \t////////\t\tunsigned int microsecond = 1000000;\n// \t////////\t\tusleep(2 * microsecond);\n// \t////\t\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n// \t\t\t// soln_drone_rhc.first[i+1]=soln_drone.first[1];\n// \t\t\t// soln_drone_rhc.second[i]=soln_drone.second[0];\n// \t\t}\n// \t\tt_end = clock();\n// \t////\n// \t//////\n// \t////////\tsoln_drone=drone_solver.solve_open_loop(X0_drone, X0_drone, 200, u_init_drone, horizon);\n// \t////////\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n// \t\t// write_file<6,6,total_steps>(state_path,input_path, soln_drone_rhc);\n// \t////\n// \t\tstd::cout<<\"finished\"<<std::endl;\n// \t\tseconds = 1/((double)(t_end - t_start) / CLOCKS_PER_SEC/total_steps);\n// \t\tprintf(\"Time: %f s\\n\", seconds);\n//\n//\n//\n//\n// /*First Order Drone Simulation Ends*/\n\n\n// /* This part is single drone simulation*/\n//\n//     cost<12,4> running_cost_dr(Drone_Cost::running_cost,tag1);\n//     cost<12,4> terminal_cost_dr(Drone_Cost::terminal_cost,tag2);\n//     dynamics<12,4> dynamics_dr(Drone_Dynamics::dynamics,tag3,time_step);\n//\n//     iLQR<12,4,horizon> drone_solver(running_cost_dr,terminal_cost_dr,dynamics_dr);\n//     Eigen::Matrix<double,4,1> u_drone=Eigen::Matrix<double,4,1>::Ones();\n//     Eigen::Matrix<double,12,1> X0_drone=Eigen::Matrix<double,12,1>::Zero();\n// ////\tX0_drone<<0,-50,10, M_PI/20,0,0, 0,0,0, 0,0,0;\n//     Eigen::Matrix<double,12,1> X_goal_drone;\n//\n//     u_drone=u_drone*sqrt(Drone_Dynamics::mass*Drone_Dynamics::g/(4*Drone_Dynamics::C_T));\n// //\n//     iLQR<12,4,horizon>::input_trajectory u_init_drone;\n//     std::fill(std::begin(u_init_drone), std::end(u_init_drone), u_drone);\n//     iLQR<12,4,horizon>::state_input_trajectory soln_drone;\n//     iLQR<12,4,total_steps>::state_input_trajectory soln_drone_rhc;\n//\n//     clock_t t_start, t_end;\n//\n// //\n//     double seconds;\n//     drone_solver.set_MPC(u_init_drone);\n//     int execution_steps=1;\n//     soln_drone_rhc.first[0]=X0_drone;\n//     // std::string state_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/states.txt\";\n//     // std::string input_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/inputs.txt\";\n//     t_start = clock();\n//     // for(int i=0;i<total_steps;++i)\n//\n//\n//     X_goal_drone<<-1.0,1.0,1.0, 0,0,0, 0,0,0, 0,0,0;\n//\n//\n//     while (ros::ok())\n//     {\n//         // if (i>total_steps/3)\n//         //     X_goal_drone<<0,0,0, 0,0,0, 0,0,0, 0,0,0;\n//         // std::cout<<\"iteration \"<<i<<std::endl;\n//\n//         ros::spinOnce();\n// ////\n//         X0_drone << CFState_cf1.x, CFState_cf1.y, CFState_cf1.z,\n//                     CFState_cf1.roll, CFState_cf1.pitch,  CFState_cf1.yaw,\n//                     CFState_cf1.x_d, CFState_cf1.y_d, CFState_cf1.z_d,\n//                     CFState_cf1.roll_d, CFState_cf1.pitch_d, CFState_cf1.yaw_d;\n//\n//         soln_drone=drone_solver.run_MPC(X0_drone, X_goal_drone, 20, execution_steps);\n//\n//         // ros::Duration(0.5).sleep();\n// //\n// //////\t\tunsigned int microsecond = 1000000;\n// //////\t\tusleep(2 * microsecond);\n// //\t\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n//         // soln_drone_rhc.first[i+1]=soln_drone.first[1];\n//         // soln_drone_rhc.second[i]=soln_drone.second[0];\n//\n//         // std::printf(\"\\n\\n\");\n//         // std::cout << X0_drone << std::endl;\n//         // std::printf(\"X: %f,\\t Y: %f,\\t Z: %f\\n\", soln_drone.first[4][0], soln_drone.first[4][1], soln_drone.first[4][2]);\n//\n//         std::printf(\"\\n#### SENDING WAYPOINT   \");\n//         std::printf(\"X: %f,\\t Y: %f,\\t Z: %f\\n\", soln_drone.first[4][0], soln_drone.first[4][1], soln_drone.first[4][2]);\n//\n//         srvGoTo_cf1.request.goal.x = soln_drone.first[4][0];\n//         srvGoTo_cf1.request.goal.y = soln_drone.first[4][1];\n//         srvGoTo_cf1.request.goal.z = soln_drone.first[4][2];\n//         srvGoTo_cf1.request.yaw = 0.0;\n//         srvGoTo_cf1.request.duration = ros::Duration(3.0);\n//         GoToClient_cf1.call(srvGoTo_cf1);\n//\n//         int c = getch();   // call your non-blocking input function\n//         if (c == '\\n') {\n//             std::cout << \"########## LANDING ##########\" << std::endl;\n//             break;\n//         }\n//\n//         // ros::spinOnce();\n//\n//     }\n//     t_end = clock();\n//\n//\n// ////\n// ////\n// //////\tsoln_drone=drone_solver.solve_open_loop(X0_drone, X0_drone, 200, u_init_drone, horizon);\n// //////\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n//     // write_file<12,4,total_steps>(state_path,input_path, soln_drone_rhc);\n// //\n//     std::cout<<\"finished\"<<std::endl;\n//     seconds = 1/((double)(t_end - t_start) / CLOCKS_PER_SEC/total_steps);\n//     printf(\"Time: %f s\\n\", seconds);\n//\n//\n// /* End of single drone simulation*/\n\n\n// cost<3,3> integrator_running_cost(Single_Integrator_Cost::running_cost,tag7);\n// cost<3,3> integrator_terminal_cost(Single_Integrator_Cost::terminal_cost,tag8);\n// dynamics<3,3> integrator_dynamics(Single_Integrator_3D::dynamics,tag9,time_step);\n// iLQR<3,3,horizon>::input_trajectory u_init_integrator;\n// iLQR<3,3,horizon> integrator_solver(integrator_running_cost,integrator_terminal_cost,integrator_dynamics);\n// Eigen::Matrix<double,3,1> u_integrator=Eigen::Matrix<double,3,1>::Zero();\n// Eigen::Matrix<double,3,1> x0_integrator=Eigen::Matrix<double,3,1>::Zero();\n// Eigen::Matrix<double,3,1> x_goal_integrator;\n// iLQR<3,3,horizon>::state_input_trajectory soln_integrator;\n// iLQR<3,3,total_steps>::state_input_trajectory soln_integrator_rhc;\n//\n// //\tu_drone2=u_drone2*sqrt(Drone_Dynamics::mass*Drone_Dynamics::g/(4*Drone_Dynamics::C_T));\n// //\tstd::fill(std::begin(u_init_drone2), std::end(u_init_drone2), u_drone2);\n// //\tiLQR<12*2,4*2,horizon>::state_input_trajectory soln_drone2;\n// //\tiLQR<12*2,4*2,total_steps>::state_input_trajectory soln_drone2_rhc;\n//\n//\n// clock_t t_start, t_end;\n//\n// double seconds;\n// integrator_solver.set_MPC(u_init_integrator);\n// int execution_steps=1;\n// soln_integrator_rhc.first[0]=x0_integrator;\n// std::string state_path=\"/home/ayberk/Documents/ACTIONLAB/crazyswarm/ros_ws/src/iLQR/datalog/states.txt\";\n// std::string input_path=\"/home/ayberk/Documents/ACTIONLAB/crazyswarm/ros_ws/src/iLQR/datalog/inputs.txt\";\n// t_start = clock();\n//\n// /* Goal position of trajectory */\n// x_goal_integrator << -1.0,1.0,1.0;\n//\n// while (ros::ok())\n// {\n//\n//     /* Spin once for ROS callback to work */\n//     ros::spinOnce();\n//\n//     /* populate state vector with current state */\n//     x0_integrator << CFState_cf1.x, CFState_cf1.y, CFState_cf1.z;\n//\n//     /* run iLQR algorithm */\n// \tsoln_integrator = integrator_solver.run_MPC(x0_integrator,\n// \t\t\t                                    x_goal_integrator,\n//                                                 20,\n//                                                 execution_steps);\n//\n//     /* Write solution to file for debugging */\n//     write_file<3,3,horizon>(state_path, input_path, soln_integrator);\n// \t// soln_integrator_rhc.first[i+1]=soln_integrator.first[1];\n// \t// soln_integrator_rhc.second[i]=soln_integrator.second[0];\n//\n//     // std::printf(\"\\nX0_integrator: \\n\");\n//     // std::cout << x0_integrator << std::endl;\n//\n//     std::printf(\"\\n#### SENDING WAYPOINT\");\n//     std::printf(\"X: %f,\\t Y: %f,\\t Z: %f\\n\", soln_integrator.first[1][0], soln_integrator.first[1][1], soln_integrator.first[1][2]);\n//\n//     /* Populate GoTo command with waypoint and call service */\n//     srvGoTo_cf1.request.goal.x = soln_integrator.first[1][0];\n//     srvGoTo_cf1.request.goal.y = soln_integrator.first[1][1];\n//     srvGoTo_cf1.request.goal.z = soln_integrator.first[1][2];\n//     srvGoTo_cf1.request.yaw = 0.0;\n//     srvGoTo_cf1.request.duration = ros::Duration(1.0);\n//     GoToClient_cf1.call(srvGoTo_cf1);\n//\n//     // srvGoTo_cf2.request.goal.x = soln_integrator.first[4][0];\n//     // srvGoTo_cf2.request.goal.y = soln_integrator.first[4][1];\n//     // srvGoTo_cf2.request.goal.z = soln_integrator.first[4][2];\n//     // srvGoTo_cf2.request.yaw = 0.0;\n//     // srvGoTo_cf2.request.duration = ros::Duration(3.0);\n//     // GoToClient_cf2.call(srvGoTo_cf2);\n//\n//\n//     /* Check if <Enter> key way pressed */\n//     int c = getch();\n//     if (c == '\\n') {\n//         std::cout << \"\\t##### LANDING #####\" << std::endl;\n//         break;\n//     }\n//\n//\n// }\n// t_end = clock();\n//\n//\n// // soln_drone=drone_solver.solve_open_loop(X0_drone, X0_drone, 200, u_init_drone, horizon);\n// // write_file<12,4,horizon>(state_path,input_path, soln_drone);\n// // write_file<3,3,total_steps>(state_path,input_path, soln_integrator_rhc);\n//\n//\n// std::cout<<\"finished\"<<std::endl;\n// seconds = 1/((double)(t_end - t_start) / CLOCKS_PER_SEC/total_steps);\n// printf(\"Time: %f s\\n\", seconds);\n\n\n\n\n// /* This part is single drone simulation*/\n//\n//     cost<12,4> running_cost_dr(Drone_Cost::running_cost,tag1);\n//     cost<12,4> terminal_cost_dr(Drone_Cost::terminal_cost,tag2);\n//     dynamics<12,4> dynamics_dr(Drone_Dynamics::dynamics,tag3,time_step);\n//\n//     iLQR<12,4,horizon> drone_solver(running_cost_dr,terminal_cost_dr,dynamics_dr);\n//     Eigen::Matrix<double,4,1> u_drone=Eigen::Matrix<double,4,1>::Ones();\n//     Eigen::Matrix<double,12,1> X0_drone=Eigen::Matrix<double,12,1>::Zero();\n// ////\tX0_drone<<0,-50,10, M_PI/20,0,0, 0,0,0, 0,0,0;\n//     Eigen::Matrix<double,12,1> X_goal_drone;\n//\n//     u_drone=u_drone*sqrt(Drone_Dynamics::mass*Drone_Dynamics::g/(4*Drone_Dynamics::C_T));\n// //\n//     iLQR<12,4,horizon>::input_trajectory u_init_drone;\n//     std::fill(std::begin(u_init_drone), std::end(u_init_drone), u_drone);\n//     iLQR<12,4,horizon>::state_input_trajectory soln_drone;\n//     iLQR<12,4,total_steps>::state_input_trajectory soln_drone_rhc;\n//\n//     std::cout << \"DEBUG 1\" << std::endl;\n//\n//     clock_t t_start, t_end;\n//\n// //\n//     double seconds;\n//     drone_solver.set_MPC(u_init_drone);\n//     int execution_steps=1;\n//     soln_drone_rhc.first[0]=X0_drone;\n//     // std::string state_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/states.txt\";\n//     // std::string input_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/inputs.txt\";\n//     t_start = clock();\n//     // for(int i=0;i<total_steps;++i)\n//\n//\n//     X_goal_drone<<1.0,1.0,1.5, 0,0,0, 0,0,0, 0,0,0;\n//\n//\n//     while (ros::ok())\n//     {\n//         // if (i>total_steps/3)\n//         //     X_goal_drone<<0,0,0, 0,0,0, 0,0,0, 0,0,0;\n//         // std::cout<<\"iteration \"<<i<<std::endl;\n//\n//         ros::spinOnce();\n// ////\n//         X0_drone << CFState_cf1.x, CFState_cf1.y, CFState_cf1.z,\n//                     CFState_cf1.roll, CFState_cf1.pitch,  CFState_cf1.yaw,\n//                     CFState_cf1.x_d, CFState_cf1.y_d, CFState_cf1.z_d,\n//                     CFState_cf1.roll_d, CFState_cf1.pitch_d, CFState_cf1.yaw_d;\n//\n//         soln_drone=drone_solver.run_MPC(X0_drone, X_goal_drone, 100, execution_steps);\n//\n//         // ros::Duration(0.5).sleep();\n// //\n// //////\t\tunsigned int microsecond = 1000000;\n// //////\t\tusleep(2 * microsecond);\n// //\t\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n//         // soln_drone_rhc.first[i+1]=soln_drone.first[1];\n//         // soln_drone_rhc.second[i]=soln_drone.second[0];\n//\n//         std::printf(\"\\n\\n\");\n//         std::cout << X0_drone << std::endl;\n//         std::printf(\"X: %f,\\t Y: %f,\\t Z: %f\\n\", soln_drone.first[39][0], soln_drone.first[39][1], soln_drone.first[39][2]);\n//\n//         srvGoTo_cf2.request.goal.x = soln_drone.first[39][0];\n//         srvGoTo_cf2.request.goal.y = soln_drone.first[39][1];\n//         srvGoTo_cf2.request.goal.z = soln_drone.first[39][2];\n//         srvGoTo_cf2.request.yaw = 0.0;\n//         srvGoTo_cf2.request.duration = ros::Duration(5.0);\n//         GoToClient_cf1.call(srvGoTo_cf2);\n//\n//         int c = getch();   // call your non-blocking input function\n//         if (c == '\\n') {\n//             std::cout << \"LANDING\" << std::endl;\n//             break;\n//         }\n//\n//         // ros::spinOnce();\n//\n//     }\n//     t_end = clock();\n//\n//\n// ////\n// ////\n// //////\tsoln_drone=drone_solver.solve_open_loop(X0_drone, X0_drone, 200, u_init_drone, horizon);\n// //////\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n//     // write_file<12,4,total_steps>(state_path,input_path, soln_drone_rhc);\n// //\n//     std::cout<<\"finished\"<<std::endl;\n//     seconds = 1/((double)(t_end - t_start) / CLOCKS_PER_SEC/total_steps);\n//     printf(\"Time: %f s\\n\", seconds);\n//\n//\n// /* End of single drone simulation*/\n\n\n/*############################################################################*/\n/*############################################################################*/\n/*############################################################################*/\n\n\n\n// /* Simple moving average filter */\n// #if (USE_SMA_FILTER == 1)\n//\n//     /* Propogate state measurements */\n//     for (int idx = 1; idx < SMA_WINDOW_LEN; ++idx) {\n//         stateWindowBuf_cf1[idx] = stateWindowBuf_cf1[idx-1];\n//         stateWindowBuf_cf2[idx] = stateWindowBuf_cf2[idx-1];\n//     }\n//\n//     /* Append current state to head of buffer */\n//     stateWindowBuf_cf1[0] = CFState_cf1;\n//     stateWindowBuf_cf2[0] = CFState_cf2;\n//\n//     // /* Set all state variables to zero */\n//     // memset(&CFState_cf1, 0x00, sizeof(stateVector));\n//     // memset(&CFState_cf2, 0x00, sizeof(stateVector));\n//\n//     static stateVector tempState_cf1, tempState_cf2;\n//\n//     /* Accumulate state variables */\n//     for (int idx = 0; idx < SMA_WINDOW_LEN; ++idx) {\n//         tempState_cf1.x += stateWindowBuf_cf1[idx].x;\n//     \ttempState_cf1.y += stateWindowBuf_cf1[idx].y;\n//     \ttempState_cf1.z += stateWindowBuf_cf1[idx].z;\n//         tempState_cf1.roll += stateWindowBuf_cf1[idx].roll;\n//     \ttempState_cf1.pitch += stateWindowBuf_cf1[idx].pitch;\n//     \ttempState_cf1.yaw += stateWindowBuf_cf1[idx].yaw;\n//         tempState_cf1.x_d += stateWindowBuf_cf1[idx].x_d;\n//     \ttempState_cf1.y_d += stateWindowBuf_cf1[idx].y_d;\n//     \ttempState_cf1.z_d += stateWindowBuf_cf1[idx].z_d;\n//     \ttempState_cf1.roll_d += stateWindowBuf_cf1[idx].roll_d;\n//     \ttempState_cf1.pitch_d += stateWindowBuf_cf1[idx].pitch_d;\n//     \ttempState_cf1.yaw_d += stateWindowBuf_cf1[idx].yaw_d;\n//\n//         tempState_cf2.x += stateWindowBuf_cf2[idx].x;\n//     \ttempState_cf2.y += stateWindowBuf_cf2[idx].y;\n//     \ttempState_cf2.z += stateWindowBuf_cf2[idx].z;\n//         tempState_cf2.roll += stateWindowBuf_cf2[idx].roll;\n//     \ttempState_cf2.pitch += stateWindowBuf_cf2[idx].pitch;\n//     \ttempState_cf2.yaw += stateWindowBuf_cf2[idx].yaw;\n//         tempState_cf2.x_d += stateWindowBuf_cf2[idx].x_d;\n//     \ttempState_cf2.y_d += stateWindowBuf_cf2[idx].y_d;\n//     \ttempState_cf2.z_d += stateWindowBuf_cf2[idx].z_d;\n//     \ttempState_cf2.roll_d += stateWindowBuf_cf2[idx].roll_d;\n//     \ttempState_cf2.pitch_d += stateWindowBuf_cf2[idx].pitch_d;\n//     \ttempState_cf2.yaw_d += stateWindowBuf_cf2[idx].yaw_d;\n//     }\n//\n//     CFState_cf1.x = tempState_cf1.x / ((float) SMA_WINDOW_LEN);\n//     CFState_cf1.y = tempState_cf1.y / ((float) SMA_WINDOW_LEN);\n//     CFState_cf1.z = tempState_cf1.z / ((float) SMA_WINDOW_LEN);\n//     CFState_cf1.x = tempState_cf1.roll / ((float) SMA_WINDOW_LEN);\n//     CFState_cf1.y = tempState_cf1.pitch / ((float) SMA_WINDOW_LEN);\n//     CFState_cf1.z = tempState_cf1.yaw / ((float) SMA_WINDOW_LEN);\n//     CFState_cf1.x_d = tempState_cf1.x_d / ((float) SMA_WINDOW_LEN);\n//     CFState_cf1.y_d = tempState_cf1.y_d / ((float) SMA_WINDOW_LEN);\n//     CFState_cf1.z_d = tempState_cf1.z_d / ((float) SMA_WINDOW_LEN);\n//     CFState_cf1.roll_d = tempState_cf1.roll_d / ((float) SMA_WINDOW_LEN);\n//     CFState_cf1.pitch_d = tempState_cf1.pitch_d / ((float) SMA_WINDOW_LEN);\n//     CFState_cf1.yaw_d = tempState_cf1.yaw_d / ((float) SMA_WINDOW_LEN);\n//\n//     // CFState_cf2.x = CFState_cf2.x / ((float) SMA_WINDOW_LEN);\n//     // CFState_cf2.y = CFState_cf2.y / ((float) SMA_WINDOW_LEN);\n//     // CFState_cf2.z = CFState_cf2.z / ((float) SMA_WINDOW_LEN);\n//     // CFState_cf2.x = CFState_cf2.roll / ((float) SMA_WINDOW_LEN);\n//     // CFState_cf2.y = CFState_cf2.pitch / ((float) SMA_WINDOW_LEN);\n//     // CFState_cf2.z = CFState_cf2.yaw / ((float) SMA_WINDOW_LEN);\n//     // CFState_cf2.x_d = CFState_cf2.x_d / ((float) SMA_WINDOW_LEN);\n//     // CFState_cf2.y_d = CFState_cf2.y_d / ((float) SMA_WINDOW_LEN);\n//     // CFState_cf2.z_d = CFState_cf2.z_d / ((float) SMA_WINDOW_LEN);\n//     // CFState_cf2.roll_d = CFState_cf2.roll_d / ((float) SMA_WINDOW_LEN);\n//     // CFState_cf2.pitch_d = CFState_cf2.pitch_d / ((float) SMA_WINDOW_LEN);\n//     // CFState_cf2.yaw_d = CFState_cf2.yaw_d / ((float) SMA_WINDOW_LEN);\n//\n// #endif\n\n\n// /* First order exponential low-pass filter */\n// #if (USE_EXP_FILTER == 1)\n\n    // float alpha = 0.9;\n    //\n    // CFState_cf1.x = (prevState_cf1.x * alpha) + (1.0 - alpha) * CFState_cf1.x;\n    // CFState_cf1.y = (prevState_cf1.y * alpha) + (1.0 - alpha) * CFState_cf1.y;\n    // CFState_cf1.z = (prevState_cf1.z * alpha) + (1.0 - alpha) * CFState_cf1.z;\n    // CFState_cf1.roll = (prevState_cf1.roll * alpha) + (1.0 - alpha) * CFState_cf1.roll;\n    // CFState_cf1.pitch = (prevState_cf1.pitch * alpha) + (1.0 - alpha) * CFState_cf1.pitch;\n    // CFState_cf1.yaw = (prevState_cf1.yaw * alpha) + (1.0 - alpha) * CFState_cf1.yaw;\n    // CFState_cf1.x_d = (prevState_cf1.x_d * alpha) + (1.0 - alpha) * CFState_cf1.x_d;\n    // CFState_cf1.y_d = (prevState_cf1.y_d * alpha) + (1.0 - alpha) * CFState_cf1.y_d;\n    // CFState_cf1.z_d = (prevState_cf1.z_d * alpha) + (1.0 - alpha) * CFState_cf1.z_d;\n    // CFState_cf1.roll_d = (prevState_cf1.roll_d * alpha) + (1.0 - alpha) * CFState_cf1.roll_d;\n    // CFState_cf1.pitch_d = (prevState_cf1.pitch_d * alpha) + (1.0 - alpha) * CFState_cf1.pitch_d;\n    // CFState_cf1.yaw_d = (prevState_cf1.yaw_d * alpha) + (1.0 - alpha) * CFState_cf1.yaw_d;\n\n    // CFState_cf2.x = (prevState_cf2.x * EXP_FILT_ALPHA) + (1.0 - EXP_FILT_ALPHA) * CFState_cf2.x;\n    // CFState_cf2.y = (prevState_cf2.y * EXP_FILT_ALPHA) + (1.0 - EXP_FILT_ALPHA) * CFState_cf2.y;\n    // CFState_cf2.z = (prevState_cf2.z * EXP_FILT_ALPHA) + (1.0 - EXP_FILT_ALPHA) * CFState_cf2.z;\n    // CFState_cf2.roll = (prevState_cf2.roll * EXP_FILT_ALPHA) + (1.0 - EXP_FILT_ALPHA) * CFState_cf2.roll;\n    // CFState_cf2.pitch = (prevState_cf2.pitch * EXP_FILT_ALPHA) + (1.0 - EXP_FILT_ALPHA) * CFState_cf2.pitch;\n    // CFState_cf2.yaw = (prevState_cf2.yaw * EXP_FILT_ALPHA) + (1.0 - EXP_FILT_ALPHA) * CFState_cf2.yaw;\n    // CFState_cf2.x_d = (prevState_cf2.x_d * EXP_FILT_ALPHA) + (1.0 - EXP_FILT_ALPHA) * CFState_cf2.x_d;\n    // CFState_cf2.y_d = (prevState_cf2.y_d * EXP_FILT_ALPHA) + (1.0 - EXP_FILT_ALPHA) * CFState_cf2.y_d;\n    // CFState_cf2.z_d = (prevState_cf2.z_d * EXP_FILT_ALPHA) + (1.0 - EXP_FILT_ALPHA) * CFState_cf2.z_d;\n    // CFState_cf2.roll_d = (prevState_cf2.roll_d * EXP_FILT_ALPHA) + (1.0 - EXP_FILT_ALPHA) * CFState_cf2.roll_d;\n    // CFState_cf2.pitch_d = (prevState_cf2.pitch_d * EXP_FILT_ALPHA) + (1.0 - EXP_FILT_ALPHA) * CFState_cf2.pitch_d;\n    // CFState_cf2.yaw_d = (prevState_cf2.yaw_d * EXP_FILT_ALPHA) + (1.0 - EXP_FILT_ALPHA) * CFState_cf2.yaw_d;\n\n    // prevState_cf1 = CFState_cf1;\n    // prevState_cf2 = CFState_cf2;\n\n// #endif\n\n\n\n\n// /* Draw square trajectory */\n//\n// srvGoTo_cf2.request.goal.x = 0.0;\n// srvGoTo_cf2.request.goal.y = 0.0;\n// srvGoTo_cf2.request.goal.z = 2.0;\n// srvGoTo_cf2.request.yaw = 0.0;\n// srvGoTo_cf2.request.duration = ros::Duration(3.0);\n// GoToClient_cf1.call(srvGoTo_cf2);\n//\n// ros::Duration(1.0).sleep();\n//\n// srvGoTo_cf2.request.goal.x = 0.0;\n// srvGoTo_cf2.request.goal.y = 1.0;\n// srvGoTo_cf2.request.goal.z = 2.0;\n// srvGoTo_cf2.request.yaw = 0.0;\n// srvGoTo_cf2.request.duration = ros::Duration(3.0);\n// GoToClient_cf1.call(srvGoTo_cf2);\n//\n// ros::Duration(1.0).sleep();\n//\n// srvGoTo_cf2.request.goal.x = 1.0;\n// srvGoTo_cf2.request.goal.y = 1.0;\n// srvGoTo_cf2.request.goal.z = 2.0;\n// srvGoTo_cf2.request.yaw = 0.0;\n// srvGoTo_cf2.request.duration = ros::Duration(3.0);\n// GoToClient_cf1.call(srvGoTo_cf2);\n//\n// ros::Duration(1.0).sleep();\n//\n// srvGoTo_cf2.request.goal.x = 1.0;\n// srvGoTo_cf2.request.goal.y = 0.0;\n// srvGoTo_cf2.request.goal.z = 2.0;\n// srvGoTo_cf2.request.yaw = 0.0;\n// srvGoTo_cf2.request.duration = ros::Duration(3.0);\n// GoToClient_cf1.call(srvGoTo_cf2);\n//\n// ros::Duration(1.0).sleep();\n//\n// srvGoTo_cf2.request.goal.x = 0.0;\n// srvGoTo_cf2.request.goal.y = 0.0;\n// srvGoTo_cf2.request.goal.z = 2.0;\n// srvGoTo_cf2.request.yaw = 0.0;\n// srvGoTo_cf2.request.duration = ros::Duration(3.0);\n// GoToClient_cf1.call(srvGoTo_cf2);\n//\n// ros::Duration(1.0).sleep();\n\n\n\n\n\n// /* Control loop */\n// while (ros::ok()) {\n//\n//     int c = getch();   // call your non-blocking input function\n//     if (c == '\\n') {\n//         std::cout << \"LANDING\" << std::endl;\n//         break;\n//     }\n//\n//     ros::spinOnce();\n//\n// \t// position_cmd.x = 0;\n// \t// position_cmd.y = 0;\n// \t// position_cmd.z = 2.0;\n// \t// position_cmd.yaw = 0.0;\n// \t// pub.publish(position_cmd);\n//\n//\n// }\n", "meta": {"hexsha": "d63c86330ddfe376ee16c0c0a27d42414b7398f6", "size": 40951, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ros_ws/src/iconlab/src/iLQR_node/iLQR_Node.cpp", "max_stars_repo_name": "labicon/crazyswarm-labicon", "max_stars_repo_head_hexsha": "32a1cd553093a31ed86058c5a9868b5a6a59dfe6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ros_ws/src/iconlab/src/iLQR_node/iLQR_Node.cpp", "max_issues_repo_name": "labicon/crazyswarm-labicon", "max_issues_repo_head_hexsha": "32a1cd553093a31ed86058c5a9868b5a6a59dfe6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ros_ws/src/iconlab/src/iLQR_node/iLQR_Node.cpp", "max_forks_repo_name": "labicon/crazyswarm-labicon", "max_forks_repo_head_hexsha": "32a1cd553093a31ed86058c5a9868b5a6a59dfe6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.9912109375, "max_line_length": 155, "alphanum_fraction": 0.6224268028, "num_tokens": 13101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.28311758277192844}}
{"text": "#pragma once\n\n// deal.II includes -------------------------------------------------------\n#include <deal.II/base/exceptions.h>\n#include <deal.II/base/index_set.h>\n#include <deal.II/base/mpi.h>\n#include <deal.II/base/numbers.h>\n#include <deal.II/base/tensor.h>\n#include <deal.II/base/timer.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_handler.h>\n\n#ifdef DEBUG\n#include <deal.II/base/conditional_ostream.h>\n#endif\n\n// system includes --------------------------------------------------------\n#include <yaml-cpp/yaml.h>\n#include <boost/multi_array.hpp>\n#include <cmath>\n#include <complex>\n#include <cstdio>\n#include <fstream>\n#include <functional>\n#include <limits>\n#include <stdexcept>\n#include <tuple>\n#include <unordered_map>\n// trilinos includes ------------------------------------------------------\n#include <Epetra_Export.h>\n#include <Epetra_Import.h>\n#include <Epetra_Map.h>\n#include <Epetra_Vector.h>\n\n// own includes -----------------------------------------------------------\n#include \"bc_traits.hpp\"\n#include \"grid/dof_mapper_periodic_distributed.hpp\"\n#include \"impl/bd_faces_manager_redist.hpp\"\n#include \"impl/bd_faces_manager_simple.hpp\"\n#include \"quadrature/qhermitew.hpp\"\n#include \"quadrature/qmaxwell.hpp\"\n#include \"spectral/basis/dof_mapper.hpp\"\n#include \"spectral/basis/indexer.hpp\"\n#include \"spectral/basis/spectral_basis_factory_hermite.hpp\"\n#include \"spectral/hermite_to_nodal.hpp\"\n#include \"spectral/polar_to_hermite.hpp\"\n#include \"spectral/rotate_basis.hpp\"\n#include \"base/numbers.hpp\"\n\n\nnamespace boltzmann {\nnamespace local_ {\n// helper struct to keep quadrature rules for inflow rhs\nstruct inflow_bc_quad\n{\n  /**\n   *\n   * @param npts quad. degree\n   * @param Tw   inflow temperature\n   * @param w    basis weight, e.g. exp(-r^2/2) => w=0.5\n   *\n   *\n   * @return\n   */\n  inflow_bc_quad(int npts, double Tw, double w = 0.5);\n\n  inflow_bc_quad() {}\n\n  QHermiteW x_quad;\n  QMaxwell y_quad;\n  // hermite polynomials\n\n  typedef HermiteNW<double> hermw_t;\n  std::shared_ptr<hermw_t> hermwx;\n  std::shared_ptr<hermw_t> hermwy;\n};\n\ninflow_bc_quad::inflow_bc_quad(int npts, double Tw, double w)\n    : x_quad(w + 1. / (2 * Tw), npts)\n    , y_quad(w + 1. / (2 * Tw), npts)\n    , hermwx(std::make_shared<HermiteNW<double> >(npts))\n    , hermwy(std::make_shared<HermiteNW<double> >(npts))\n// 256 digits (mpfr accuracy)\n{\n  hermwx->compute(x_quad.pts());\n\n  std::vector<double> y(npts);\n  for (int i = 0; i < npts; ++i) {\n    y[i] = -y_quad.pts(i);\n  }\n\n  hermwy->compute(y);\n}\n}  // end namespace local_\n\n// -------------------------------------------------------------------------------------\ntemplate <typename METHOD, typename APP, typename BD_FACES_MANAGER>\nclass BoundaryConditions : public BD_FACES_MANAGER\n{\n private:\n  typedef BD_FACES_MANAGER bd_faces_manager_t;\n  typedef dealii::types::global_dof_index size_type;\n  typedef dealii::DoFHandler<2> dh_t;\n  typedef typename METHOD::spectral_basis_t spectral_basis_t;\n  typedef typename traits::DoFMapper<APP::bc_type>::type mapper_t;\n  typedef Indexer<mapper_t> indexer_t;\n  typedef dealii::TrilinosWrappers::MPI::Vector deal_vector_t;\n\n  // boundary id\n  typedef unsigned int bid_t;\n\n public:\n  BoundaryConditions(double dt,\n                     const dh_t& dh,\n                     const spectral_basis_t& spectral_basis,\n                     const indexer_t& indexer,\n                     const YAML::Node& config);\n\n  void apply(deal_vector_t& out, const deal_vector_t& in) const;\n\n  void apply(Epetra_MultiVector& out, const Epetra_MultiVector& in) const;\n\n  /**\n   *  @brief Assemble inflow type boundary conditions into the right hand side\n   *\n   */\n  template <typename VECTOR>\n  void assemble_rhs(VECTOR& dst) const;\n\n private:\n  typedef SpectralBasisFactoryHN::basis_type hermite_basis_t;\n  typedef std::shared_ptr<impl::flux_worker> ptr_flux_worker;\n\n private:\n  double dt_;\n  const dh_t& dh_;\n  const spectral_basis_t& spectral_basis_;\n  const indexer_t& indexer_;\n  const YAML::Node& config_;\n\n  //@{\n  /// spectral basis transformation / rotation operators\n  RotateBasis<spectral_basis_t> R_;\n  hermite_basis_t hermite_basis_;\n  typedef Polar2Hermite<spectral_basis_t, hermite_basis_t> P2H_t;\n  typedef Hermite2Nodal<hermite_basis_t> H2N_t;\n  std::shared_ptr<P2H_t> ptr_P2H_;\n  std::shared_ptr<H2N_t> ptr_H2N_;\n  //@}\n\n  std::map<bid_t, ptr_flux_worker> flux_workers_;\n  std::set<bid_t> periodic_;\n\n  //@{\n  /*  Buffers for Lagrange coefficients\n   *  1p: output from flux_worker for vertex 1\n   *  2p: output from flux_worker for vertex 2\n   */\n  mutable Eigen::MatrixXd L1p_;  // output f (1. trial) for flux worker\n  mutable Eigen::MatrixXd L1_;   // input f  (1. tiral function) ..\n  mutable Eigen::MatrixXd L2p_;  // output f  (2. trial function) ..\n  mutable Eigen::MatrixXd L2_;\n  mutable Eigen::MatrixXd L_;\n  //@}\n\n  /// buffer for hermite coefficients\n  /// ybuffer\n  mutable Eigen::VectorXd ybuf_;\n\n  // polynomial degree\n  int K_ = -1;\n\n  // TODO Epetra Multi vector, Import, Export, Maps\n  // imports from base class\n  using bd_faces_manager_t::relevant_dofs_;\n  using bd_faces_manager_t::get_faces_list;\n  // epetra vectors\n  mutable std::shared_ptr<Epetra_Vector> x_ghosted_;\n  mutable std::shared_ptr<Epetra_Vector> y_ghosted_;\n  mutable std::shared_ptr<Epetra_Import> importer_;\n  mutable std::shared_ptr<Epetra_Export> exporter_;\n};\n\n// --------------------------------------------------------------------------------\ntemplate <typename METHOD, typename APP, typename BD_FACES_MANAGER>\nBoundaryConditions<METHOD, APP, BD_FACES_MANAGER>::BoundaryConditions(\n    double dt,\n    const dh_t& dh,\n    const spectral_basis_t& spectral_basis,\n    const indexer_t& indexer,\n    const YAML::Node& config)\n    : bd_faces_manager_t(dh, spectral_basis, indexer)\n    , dt_(dt)\n    , dh_(dh)\n    , spectral_basis_(spectral_basis)\n    , indexer_(indexer)\n    , config_(config)\n    , R_(spectral_basis)\n{\n  int K_ = config_[\"SpectralBasis\"][\"deg\"].as<int>();\n\n  // initialize hermite basis\n  SpectralBasisFactoryHN::create(hermite_basis_, K_, 2);\n  static QHermiteW hermite_quad(1.0, K_);\n\n  Eigen::VectorXd hw = hermite_quad.vwts<1>();\n  Eigen::VectorXd hx = hermite_quad.vpts<1>();\n\n  // resize buffers\n  L1_.resize(K_, K_);\n  L2_.resize(K_, K_);\n  L1p_.resize(K_, K_);\n  L2p_.resize(K_, K_);\n  L_.resize(K_, K_);\n  ybuf_.resize(spectral_basis_.n_dofs());\n\n  typedef Eigen::MatrixXd mat_t;\n  ptr_P2H_ = std::make_shared<P2H_t>(spectral_basis_, hermite_basis_);\n  ptr_H2N_ = std::make_shared<H2N_t>(\n      hermite_basis_, K_, [K_](mat_t& m1, mat_t& m2) { H2N_1d<>::create(m1, m2, K_); });\n\n  auto node = config_[\"BoundaryDescriptors\"];\n  // TODO: process config\n  for (YAML::const_iterator it = node.begin(); it != node.end(); ++it) {\n    auto entry = it->second;\n    id_t id = it->first.as<id_t>();\n    std::string type = entry[\"type\"].as<std::string>();\n\n    typedef bc_traits<METHOD::lsq_type> bc_traits_t;\n    if (std::strcmp(type.c_str(), \"diffusive reflection\") == 0) {\n      double T = entry[\"T\"].as<double>();\n      double rho = 1.0;\n      if (entry[\"rho\"]) {\n        rho = entry[\"rho\"].as<double>();\n      }\n      if (entry[\"vt\"]) {\n        double vt = entry[\"vt\"].as<double>();\n        flux_workers_[id] =\n            std::make_shared<typename bc_traits_t::DiffusiveReflection>(hw, hx, vt, T, rho);\n      } else {\n        flux_workers_[id] =\n            std::make_shared<typename bc_traits_t::DiffusiveReflection>(hw, hx, 0, T, rho);\n      }\n    } else if (std::strcmp(type.c_str(), \"diffusive reflection x\") == 0) {\n      std::string Tx = entry[\"Tx\"].as<std::string>();\n      if (entry[\"vt\"]) {\n        double vt = entry[\"vt\"].as<double>();\n        flux_workers_[id] =\n            std::make_shared<typename bc_traits_t::DiffusiveReflectionX>(hw, hx, vt, Tx);\n      } else {\n        flux_workers_[id] =\n            std::make_shared<typename bc_traits_t::DiffusiveReflectionX>(hw, hx, 0, Tx);\n      }\n    }\n    else if (std::strcmp(type.c_str(), \"specular reflection\") == 0) {\n      flux_workers_[id] = std::make_shared<typename bc_traits_t::SpecularReflection>(hw, hx);\n    } else if (std::strcmp(type.c_str(), \"inflow\") == 0) {\n      flux_workers_[id] = std::make_shared<typename bc_traits_t::Inflow>(hw, hx);\n\n    } else if (std::strcmp(type.c_str(), \"periodic\") == 0) {\n      periodic_.insert(id);\n    } else {\n      AssertThrow(false, dealii::ExcMessage(\"Unkown boundary condition entry\"));\n    }\n  }\n\n  auto epetra_map = relevant_dofs_.make_trilinos_map(MPI_COMM_WORLD, true);\n\n  x_ghosted_ = std::make_shared<Epetra_Vector>(epetra_map);\n  y_ghosted_ = std::make_shared<Epetra_Vector>(epetra_map);\n}\n\n// --------------------------------------------------------------------------------\ntemplate <typename METHOD, typename APP, typename BD_FACES_MANAGER>\ntemplate <typename VECTOR>\nvoid\nBoundaryConditions<METHOD, APP, BD_FACES_MANAGER>::assemble_rhs(VECTOR& dst) const\n{\n  /* inflow boundary conditions need to be assembled into the rhs vector. this is done in this\n     routine */\n  const int K = spectral::get_max_k(spectral_basis_);\n  std::map<double, local_::inflow_bc_quad> inflow_bc_quad_map;\n  auto& bd_conf = config_[\"BoundaryDescriptors\"];\n  const int npts = 2 * K;\n\n  // --------------------------------------------------\n  // prepare quadrature rules\n  for (YAML::const_iterator it = bd_conf.begin(); it != bd_conf.end(); ++it) {\n    auto entry = it->second;\n    id_t id = it->first.as<id_t>();\n\n    std::string type = entry[\"type\"].as<std::string>();\n    if (std::strcmp(type.c_str(), \"inflow\") == 0) {\n      // currently inflow function g(v), can be of Maxwellian type only\n      if (std::strcmp(entry[\"func\"].as<std::string>().c_str(), \"maxwellian\") == 0) {\n        double Tw = entry[\"T\"].as<double>();\n        // basis exp weight\n        const double basis_alpha = 0.5;\n        inflow_bc_quad_map[Tw] = local_::inflow_bc_quad(npts, Tw, basis_alpha);\n      }\n    }\n  }\n\n  // --------------------------------------------------\n  // prepare deal.II stuff\n  const int dimX = 2;\n  unsigned int N = spectral_basis_.n_dofs();\n  dealii::UpdateFlags update_flags = dealii::update_values | dealii::update_JxW_values |\n                                     dealii::update_quadrature_points |\n                                     dealii::update_normal_vectors;\n\n  dealii::QGauss<dimX - 1> quad(2);\n  int n_qpoints = quad.size();\n\n  auto& fe = dh_.get_fe();\n  const int dofs_per_cell = fe.dofs_per_cell;\n  dealii::FEFaceValues<2> fe_face_values(fe, quad, update_flags);\n  std::vector<size_type> local_dof_indices(fe.dofs_per_cell);\n\n  const auto& faces_list = this->get_faces_list();\n\n  typedef typename VECTOR::size_type size_type;\n  std::vector<size_type> global_indices(N);\n\n  Eigen::VectorXd II(N);\n  Eigen::VectorXd IIp(N);    // buffer to add into trilinos vector\n  Eigen::VectorXd IIloc(N);  // buffer to add into trilinos vector\n\n  // iterate over faces at boundary\n  for (const auto& mypair : faces_list) {\n    const auto& cell = std::get<0>(mypair);\n    int face_idx = std::get<1>(mypair);\n    id_t bd_ind = cell.face(face_idx)->boundary_id();\n\n    // check if bc is periodic.\n    std::string type = config_[\"BoundaryDescriptors\"][bd_ind][\"type\"].as<std::string>();\n    if (periodic_.find(bd_ind) != periodic_.end() || std::strcmp(type.c_str(), \"inflow\") != 0)\n      // bc is periodic: nothing to do\n      continue;\n    // --------------------------------------------------\n    // load parameter\n    auto params = config_[\"BoundaryDescriptors\"][bd_ind];\n\n    std::string func = params[\"func\"].as<std::string>();\n    if (std::strcmp(func.c_str(), \"zero\") == 0) {\n      // nothing to do\n      continue;\n    }\n    // check the inflow function\n    BAssertThrow(std::strcmp(func.c_str(), \"maxwellian\") == 0,\n                 \"BoundaryConditions::assemble_rhs, do not know how to handle boundary type.\\n\" +\n                     \"Type was: \" + func);\n\n    double Tw = params[\"T\"].as<double>();\n\n    auto iter = inflow_bc_quad_map.find(Tw);\n    assert(iter != inflow_bc_quad_map.end());\n    const auto& quad_helper = iter->second;\n    Eigen::Vector2d v0 = {0, 0};\n    if (params[\"v\"]) {\n      double vx = params[\"v\"][0].as<double>();\n      double vy = params[\"v\"][1].as<double>();\n      v0 = {vx, vy};\n    }\n\n    double rho;\n    if (params[\"rho\"])\n      rho = params[\"rho\"].as<double>();\n    else\n      rho = 1;\n\n    typedef dealii::DoFCellAccessor<dealii::DoFHandler<2>, false> accessor_t;\n    typedef dealii::TriaIterator<accessor_t> tria_iterator_t;\n\n    cell.get_dof_indices(local_dof_indices);\n    fe_face_values.reinit(tria_iterator_t(cell), face_idx);\n\n    const double nx = fe_face_values.normal_vector(0)[0];\n    const double ny = fe_face_values.normal_vector(0)[1];\n    // winkel zwischen y-achse und n\n    const double alpha = numbers::PI / 2 - std::atan2(ny, nx);\n\n    std::array<double, 4> B;\n    B.fill(0);\n    for (unsigned int l1 = 0; l1 < fe.dofs_per_cell; ++l1) {\n      double val = 0;\n      for (int q = 0; q < n_qpoints; ++q) {\n        val += fe_face_values.shape_value(l1, q) * fe_face_values.JxW(q);\n      }\n      B[l1] = val;\n    }\n\n    const double v02 = v0.squaredNorm();\n    // hermite basis accessors\n    typedef typename hermite_basis_t::elem_t elem_t;\n    typedef typename boost::mpl::at_c<typename elem_t::types_t, 0>::type hx_t;\n    typedef typename boost::mpl::at_c<typename elem_t::types_t, 1>::type hy_t;\n    typename elem_t::Acc::template get<hx_t> get_hx;\n    typename elem_t::Acc::template get<hy_t> get_hy;\n\n    auto hermwx = quad_helper.hermwx;\n    auto hermwy = quad_helper.hermwy;\n    const auto& xpts = quad_helper.x_quad.pts();\n    const auto& xwts = quad_helper.x_quad.wts();\n    const auto& ypts = quad_helper.y_quad.pts();\n    const auto& ywts = quad_helper.y_quad.wts();\n\n    Eigen::Rotation2D<double> rot2d(alpha);\n    Eigen::Matrix2d rotm = rot2d.toRotationMatrix();\n    auto v0h = rotm * v0;\n    /*\n     *  HINT: about Hermite quad. rule: (used in x-direction) The weights are\n     *     multiplied by e^(x^2/2), which accounts for the factor e^(-x^2/2)\n     *     which is included in the evaluation of the Hermite polynomials (e.g.\n     *     Hermite functions in this case)\n     */\n    for (unsigned int j = 0; j < N; ++j) {\n      // iterate over test functions\n      const auto& elem = hermite_basis_.get_elem(j);\n      const unsigned int jx = get_hx(elem).get_id().k;\n      const unsigned int jy = get_hy(elem).get_id().k;\n      double val = 0;\n      // 2d quadrature\n      for (int qx = 0; qx < npts; ++qx) {\n        for (int qy = 0; qy < npts; ++qy) {\n          Eigen::Vector2d vh = {xpts[qx], -1.0 * ypts[qy]};\n          // inflow => -1.0\n          val -= hermwx->get(jx)[qx] * hermwy->get(jy)[qy] * std::exp(v0h.dot(vh) / Tw) *\n                 (std::exp(-xpts[qx] * xpts[qx] / 2 / Tw) * xwts[qx]) *\n                 (std::exp(vh[1] * vh[1] / 2) * ywts[qy]);\n        }\n      }\n      II(j) = std::exp(-v02 / 2 / Tw) * val * rho / (2 * numbers::PI * Tw);\n    }\n    // transform to polar\n    ptr_P2H_->to_hermite_T(IIp, II);\n    // rotate back\n    R_.apply(IIloc.data(), IIp.data(), -alpha);\n\n    for (unsigned int l1 = 0; l1 < fe.dofs_per_cell; ++l1) {\n      if (std::abs(B[l1]) > 1e-15) {\n        for (unsigned int j = 0; j < N; ++j) {\n          global_indices[j] = indexer_.to_global(local_dof_indices[l1], j);\n        }\n        II = IIloc * B[l1];\n        dst.add(N, global_indices.data(), II.data());\n      }\n    }\n  }\n\n  dst.compress(dealii::VectorOperation::add);\n}\n\n// --------------------------------------------------------------------------------\ntemplate <typename METHOD, typename APP, typename BD_FACES_MANAGER>\nvoid\nBoundaryConditions<METHOD, APP, BD_FACES_MANAGER>::apply(deal_vector_t& out,\n                                                         const deal_vector_t& in) const\n{\n  this->apply(out.trilinos_vector(), in.trilinos_vector());\n}\n\n// --------------------------------------------------------------------------------\ntemplate <typename METHOD, typename APP, typename BD_FACES_MANAGER>\nvoid\nBoundaryConditions<METHOD, APP, BD_FACES_MANAGER>::apply(Epetra_MultiVector& out,\n                                                         const Epetra_MultiVector& in) const\n{\n#ifdef DEBUG\n  out.SetTracebackMode(2);\n  in.SetTracebackMode(2);\n  x_ghosted_->SetTracebackMode(2);\n  y_ghosted_->SetTracebackMode(2);\n#endif\n\n  const int dimX = 2;\n  // ATTENTION: this makes assumptions on deal.II internals\n  static size_type faces_vertex[4][2] = {{0, 2}, {1, 3}, {0, 1}, {2, 3}};\n\n  static dealii::Tensor<2, 2> B;\n\n#ifdef DEBUG\n  const unsigned int pid = dealii::Utilities::MPI::this_mpi_process(MPI_COMM_WORLD);\n  dealii::ConditionalOStream pcout(std::cout, pid == 0);\n#endif\n\n  if (importer_.use_count() == 0) {\n#ifdef DEBUG\n    pcout << \"Importer not set. Initializing\\n\";\n#endif\n    auto& ghosted_map = x_ghosted_->Map();\n    auto& src_map = out.Map();\n    importer_ = std::make_shared<Epetra_Import>(ghosted_map, src_map);\n  }\n\n  if (exporter_.use_count() == 0) {\n#ifdef DEBUG\n    pcout << \"Exporter not set. Initializing\\n\";\n#endif\n    auto& ghosted_map = x_ghosted_->Map();\n    auto& src_map = out.Map();\n    exporter_ = std::make_shared<Epetra_Export>(ghosted_map, src_map);\n  }\n\n  // Import nonlocal elements\n  int ier;\n  ier = x_ghosted_->Import(in, *importer_.get(), Insert);\n  AssertThrow(ier == 0, dealii::ExcTrilinosError(ier));\n  // get pointer to x_ghosted_\n  const double* data_in = x_ghosted_->Values();\n  // reset y_ghosted_\n  std::fill(y_ghosted_->Values(), y_ghosted_->Values() + y_ghosted_->MyLength(), 0);\n\n  double* data_out = y_ghosted_->Values();\n\n  unsigned int N = spectral_basis_.n_dofs();\n  dealii::UpdateFlags update_flags = dealii::update_values | dealii::update_JxW_values |\n                                     dealii::update_quadrature_points |\n                                     dealii::update_normal_vectors;\n\n  dealii::QGauss<dimX - 1> quad(2);\n  int n_qpoints = quad.size();\n\n  auto& fe = dh_.get_fe();\n  dealii::FEFaceValues<2> fe_face_values(fe, quad, update_flags);\n  std::vector<size_type> local_dof_indices(fe.dofs_per_face);\n\n  // transform to lagrange coefficients\n  unsigned int local_size = in.MyLength();\n  const auto& faces_list = this->get_faces_list();\n  // rotated Polar coeffs\n  Eigen::VectorXd cP_rot(N);\n  // Hermite coeffs\n  Eigen::VectorXd cH(N);\n\n  for (const auto& mypair : faces_list) {\n    const auto& cell = std::get<0>(mypair);\n    int face_idx = std::get<1>(mypair);\n    id_t bd_ind = cell.face(face_idx)->boundary_id();\n\n    // this is a periodic boundary and thus requires no further computations\n    // (since it is built into the enumeration of DoFs already)\n    if (periodic_.find(bd_ind) != periodic_.end()) continue;\n\n    auto fentry = flux_workers_.find(bd_ind);\n    if (fentry == flux_workers_.end()) {\n      AssertThrow(false, dealii::ExcMessage(\"unknown boundary type\"));\n    }\n\n    typedef dealii::DoFCellAccessor<dealii::DoFHandler<2>, false> accessor_t;\n    typedef dealii::TriaIterator<accessor_t> tria_iterator_t;\n\n    cell.face(face_idx)->get_dof_indices(local_dof_indices);\n\n    fe_face_values.reinit(tria_iterator_t(cell), face_idx);\n\n#ifdef DEBUG\n    // checking dof indexing\n    std::vector<size_type> ldof_indices(fe.dofs_per_cell);\n    cell.get_dof_indices(ldof_indices);\n    size_type l0 = cell.face(face_idx)->vertex_dof_index(0, 0);\n    size_type l1 = cell.face(face_idx)->vertex_dof_index(1, 0);\n\n    AssertThrow(l0 == ldof_indices[faces_vertex[face_idx][0]],\n                dealii::ExcMessage(\"something with the local dofs is wrong\"));\n    AssertThrow(l1 == ldof_indices[faces_vertex[face_idx][1]],\n                dealii::ExcMessage(\"something with the local dofs is wrong\"));\n    AssertThrow(l0 == local_dof_indices[0],\n                dealii::ExcMessage(\"something with local dofs is wrong\"));\n    AssertThrow(l1 == local_dof_indices[1],\n                dealii::ExcMessage(\"something with local dofs is wrong\"));\n#endif\n    B *= 0;\n    for (int i = 0; i < dimX; ++i) {\n      int l1 = faces_vertex[face_idx][i];\n      for (int j = 0; j < dimX; ++j) {\n        int l2 = faces_vertex[face_idx][j];\n        for (unsigned int q = 0; q < quad.size(); ++q) {\n          B[i][j] += (fe_face_values.shape_value(l1, q) * fe_face_values.shape_value(l2, q) *\n                      fe_face_values.JxW(q));\n        }\n      }\n    }\n\n    Assert(std::abs(B[0][1]) > 0, dealii::ExcMessage(\"something went wrong\"));\n    Assert(std::abs(B[1][1]) > 0, dealii::ExcMessage(\"something went wrong\"));\n    Assert(std::abs(B[0][0]) > 0, dealii::ExcMessage(\"something went wrong\"));\n\n    const double nx = fe_face_values.normal_vector(0)[0];\n    const double ny = fe_face_values.normal_vector(0)[1];\n    // winkel zwischen y-achse und n\n    const double alpha = numbers::PI / 2 - std::atan2(ny, nx);\n\n    typedef dealii::TrilinosWrappers::types::int_type index_t;\n    index_t ig1 =\n        x_ghosted_->Map().LID(static_cast<index_t>(indexer_.to_global(local_dof_indices[0], 0)));\n\n    Assert(ig1 != -1, dealii::ExcMessage(\"global index not found in x_ghosted_!\"));\n\n    index_t ig2 =\n        x_ghosted_->Map().LID(static_cast<index_t>(indexer_.to_global(local_dof_indices[1], 0)));\n    Assert(ig2 != -1, dealii::ExcMessage(\"global index not found in x_ghosted_!\"));\n\n    // *** flux ***\n    R_.apply(cP_rot.data(), data_in + ig1, alpha);\n    ptr_P2H_->to_hermite(cH, cP_rot);\n    ptr_H2N_->to_nodal(L1_, cH);\n    fentry->second->apply(L1p_, L1_, cell.face(face_idx)->vertex(0));\n\n    R_.apply(cP_rot.data(), data_in + ig2, alpha);\n    ptr_P2H_->to_hermite(cH, cP_rot);\n    ptr_H2N_->to_nodal(L2_, cH);\n    fentry->second->apply(L2p_, L2_, cell.face(face_idx)->vertex(1));\n\n    // *** Assemble into y_ghosted_ ***\n    // lfe_idx1-test function => global index ig1, ig1+N\n    L_ = B[0][0] * L1p_ + B[0][1] * L2p_;\n    ptr_H2N_->to_hermite(cH.data(), L_);               // to_hermite = to_nodal^T\n    ptr_P2H_->to_hermite_T(cP_rot, cH);  // to_hermite_T = to_hermite^T\n    // rotate back\n    R_.apply(ybuf_.data(), cP_rot.data(), -alpha);\n    // write to ghosted vector\n    Eigen::Map<Eigen::VectorXd> vout1(data_out + ig1, N);\n    vout1 += ybuf_;\n\n    // lfe_idx2-test function => global index ig2, ig2+N\n    L_ = B[1][0] * L1p_ + B[1][1] * L2p_;\n    ptr_H2N_->to_hermite(cH, L_);               // to_hermite = to_nodal^T\n    ptr_P2H_->to_hermite_T(cP_rot, cH);  // to_hermite_T = to_hermite^T\n    // rotate back\n    R_.apply(ybuf_.data(), cP_rot.data(), -alpha);\n\n    // write to ghosted vector\n    Eigen::Map<Eigen::VectorXd> vout2(data_out + ig2, N);\n    vout2 += ybuf_;\n  }\n\n  // scale y_ghosted_\n  y_ghosted_->Scale(dt_);\n  // *** export y_ghosted_ into global solution vector ***\n  ier = out.Export(*y_ghosted_.get(), *exporter_.get(), Epetra_CombineMode::Epetra_AddLocalAlso);\n  Assert(ier == 0, dealii::ExcMessage(\"Export to global solution vector failed.\"));\n}\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "f3e4da7613a4233c5f6df8eb7aedf7b30e9c0ab4", "size": 22868, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/matrix/bc/boundary_conditions.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/matrix/bc/boundary_conditions.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/matrix/bc/boundary_conditions.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": 35.399380805, "max_line_length": 97, "alphanum_fraction": 0.630269372, "num_tokens": 6515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.28311758277192844}}
{"text": "/**\n * @file esx.hpp\n * @author Leonardo Arcari (leonardo1.arcari@gmail.com)\n * @version 1.0.0\n * @date 2018-10-28\n *\n * @copyright Copyright (c) 2018 Leonardo Arcari\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\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\n#ifndef BOOST_ESX_ALTERNATIVE_ROUTING_HPP\n#define BOOST_ESX_ALTERNATIVE_ROUTING_HPP\n\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/properties.hpp>\n\n#include <arlib/terminators.hpp>\n#include <arlib/type_traits.hpp>\n\n#include <arlib/details/esx_impl.hpp>\n\n#include <queue>\n#include <unordered_set>\n#include <vector>\n\n/**\n * An Alternative-Routing library for Boost.Graph\n */\nnamespace arlib {\n/**\n * An implementation of ESX k-shortest path with limited overlap for\n * Boost::Graph.\n *\n * This implementation refers to the following publication:\n *\n * Theodoros Chondrogiannis, Panagiotis Bouros, Johann Gamper and Ulf Leser,\n * Exact and Approximate Algorithms for Finding k-Shortest Paths with Limited\n * Overlap , In Proc. of the 20th Int. Conf. on Extending Database Technology\n * (EDBT) (2017)\n *\n * @tparam Graph A Boost::VertexAndEdgeListGraph\n * @tparam WeightMap The weight or \"length\" of each edge in the graph. The\n *         weights must all be non-negative, and the algorithm will throw a\n *         negative_edge exception is one of the edges is negative. The type\n *         WeightMap must be a model of Readable Property Map. The edge\n *         descriptor type of the graph needs to be usable as the key type for\n *         the weight map. The value type for this map must be the same as the\n *         value type of the distance map.\n * @tparam MultiPredecessorMap The multi predecessor map records the edges in\n *         the alternative paths from @p s to @p t. Upon completion of the\n *         algorithm, for any vertex `v` on any alternative path `p`, multi\n *         predecessor map stores the predecessor of node `v` on path `p`. If no\n *         predecessor for a node `v'` is reported, then `v'` is not part of any\n *         alternative path or it is the source node @p s. The type of\n *         `MultiPredecessorMap` must be a model of `Read Property Map`. The\n *         vertex descriptor of the input graph @p G must be usable as a key\n *         type for the multi predecessor map. Whereas the value type must\n *         satisfy the `UnorderedAssociativeContainer` concept, where its key is\n *         an `int`, the index/number of alternative path for which it exists a\n *         predecessor of `v`, and where the value type is a vertex descriptor\n *         of input graph @p G.\n * @tparam Vertex The vertex descriptor.\n * @param G The input graph.\n * @param weight The weight map of @p G.\n * @param predecessors The multi predecessor map of @p G.\n * @param s The source node.\n * @param t The target node.\n * @param k The number of alternative paths to compute.\n * @param theta The similarity threshold.\n * @param algorithm The routing kernel to employ. The default is\n *        routing_kernels::astar\n *\n */\ntemplate <typename Graph, typename WeightMap, typename MultiPredecessorMap,\n          typename Terminator = arlib::always_continue,\n          typename Vertex = vertex_of_t<Graph>,\n          typename = std::enable_if_t<std::is_same_v<\n              typename boost::property_traits<MultiPredecessorMap>::key_type,\n              Vertex>>>\nvoid esx(const Graph &G, WeightMap const &weight,\n         MultiPredecessorMap &predecessors, Vertex s, Vertex t, int k,\n         double theta, routing_kernels algorithm = routing_kernels::astar,\n         Terminator &&terminator = Terminator{}) {\n  details::esx_dispatch(G, weight, predecessors, s, t, k, theta, algorithm,\n                        std::forward<Terminator>(terminator));\n}\n\ntemplate <typename Graph, typename WeightMap, typename MultiPredecessorMap,\n          typename EdgeCentralityMap,\n          typename Terminator = arlib::always_continue,\n          typename Vertex = vertex_of_t<Graph>,\n          typename = std::enable_if_t<std::is_same_v<\n              typename boost::property_traits<MultiPredecessorMap>::key_type,\n              Vertex>>>\nvoid esx(const Graph &G, WeightMap const &weight,\n         MultiPredecessorMap &predecessors,\n         EdgeCentralityMap const &edge_centrality, Vertex s, Vertex t, int k,\n         double theta, routing_kernels algorithm = routing_kernels::astar,\n         Terminator &&terminator = Terminator{}) {\n  details::esx_dispatch(G, weight, predecessors, edge_centrality, s, t, k,\n                        theta, algorithm, std::forward<Terminator>(terminator));\n}\n\n/**\n * An implementation of `ESX` k-shortest path with limited overlap for\n * `Boost::Graph`.\n *\n * This overload takes an input graph modeling `PropertyGraph` concept having at\n * least one edge property with tag `boost::edge_weight_t`. Moreover it does not\n * require an explicit `WeightMap` parameter, because it is directly gathered\n * from the `PropertyGraph`.\n *\n * @see esx(const Graph &G, WeightMap const &weight,\n *          MultiPredecessorMap &predecessors, Vertex s, Vertex t, int k,\n *          double theta,\n *          routing_kernels algorithm)\n *\n * @tparam PropertyGraph A Boost::PropertyGraph having at least one edge\n *         property with tag boost::edge_weight_t.\n *\n */\ntemplate <typename PropertyGraph, typename MultiPredecessorMap,\n          typename Terminator = arlib::always_continue,\n          typename Vertex = vertex_of_t<PropertyGraph>,\n          typename = std::enable_if_t<std::is_same_v<\n              typename boost::property_traits<MultiPredecessorMap>::key_type,\n              Vertex>>>\nvoid esx(const PropertyGraph &G, MultiPredecessorMap &predecessors, Vertex s,\n         Vertex t, int k, double theta,\n         routing_kernels algorithm = routing_kernels::astar,\n         Terminator &&terminator = Terminator{}) {\n  using namespace boost;\n  using Edge = typename graph_traits<PropertyGraph>::edge_descriptor;\n\n  BOOST_CONCEPT_ASSERT(\n      (PropertyGraphConcept<PropertyGraph, Edge, edge_weight_t>));\n\n  auto weight = get(edge_weight, G);\n  details::esx_dispatch(G, weight, predecessors, s, t, k, theta, algorithm,\n                        std::forward<Terminator>(terminator));\n}\n\ntemplate <typename PropertyGraph, typename MultiPredecessorMap,\n          typename EdgeCentralityMap,\n          typename Terminator = arlib::always_continue,\n          typename Vertex = vertex_of_t<PropertyGraph>,\n          typename = std::enable_if_t<std::is_same_v<\n              typename boost::property_traits<MultiPredecessorMap>::key_type,\n              Vertex>>>\nvoid esx(const PropertyGraph &G, MultiPredecessorMap &predecessors,\n         EdgeCentralityMap const &edge_centrality, Vertex s, Vertex t, int k,\n         double theta, routing_kernels algorithm = routing_kernels::astar,\n         Terminator &&terminator = Terminator{}) {\n  using namespace boost;\n  using Edge = typename graph_traits<PropertyGraph>::edge_descriptor;\n\n  BOOST_CONCEPT_ASSERT(\n      (PropertyGraphConcept<PropertyGraph, Edge, edge_weight_t>));\n\n  auto weight = get(edge_weight, G);\n  esx(G, weight, predecessors, edge_centrality, s, t, k, theta, algorithm,\n      std::forward<Terminator>(terminator));\n}\n} // namespace arlib\n\n#endif\n", "meta": {"hexsha": "d1f053a21b3b3e08618041a90a16121c7aff0751", "size": 8267, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/arlib/esx.hpp", "max_stars_repo_name": "ashishkashinath/arlib", "max_stars_repo_head_hexsha": "891aa8603a6e07a16aec5700e7129a0d14a40b84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-10-29T17:17:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T02:09:37.000Z", "max_issues_repo_path": "include/arlib/esx.hpp", "max_issues_repo_name": "ashishkashinath/arlib", "max_issues_repo_head_hexsha": "891aa8603a6e07a16aec5700e7129a0d14a40b84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-05T07:27:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-05T07:27:35.000Z", "max_forks_repo_path": "include/arlib/esx.hpp", "max_forks_repo_name": "ashishkashinath/arlib", "max_forks_repo_head_hexsha": "891aa8603a6e07a16aec5700e7129a0d14a40b84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-07-20T09:31:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T12:06:49.000Z", "avg_line_length": 43.9734042553, "max_line_length": 80, "alphanum_fraction": 0.7050925366, "num_tokens": 1921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5, "lm_q1q2_score": 0.28300926759805073}}
{"text": "#include <iostream>\n#include <boost/compute/core.hpp>\n#include <vector>\n#include <boost/concept_check.hpp>\n#include \"../pointsets/Pointset.hpp\"\n#include \"../io/fileIO.hpp\"\n#include \"../io/histogramIO.hpp\"\n\n#include <boost/compute/algorithm/transform.hpp>\n#include <boost/compute/algorithm/sort.hpp>\n#include <boost/compute/algorithm/max_element.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/functional/math.hpp>\n#include <boost/compute/algorithm/count_if.hpp>\n#include <boost/compute/function.hpp>\n\nnamespace compute = boost::compute;\n\n\nconst char source2[] = BOOST_COMPUTE_STRINGIZE_SOURCE(__kernel void computeScoreMinDist(__global const unsigned int* permut_lsb,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__global const unsigned int* permut_msb,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__global const unsigned int* pattern,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__global const float* pcf,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__global float* min_dist,\n                                                                                __global float* score\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//__global unsigned int* debug\n                                                                              )\n\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tuint gid = get_global_id(0);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int permut_x_lsb = permut_lsb[2*gid];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int permut_y_lsb = permut_lsb[2*gid+1];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int permut_x_msb = permut_msb[2*gid];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int permut_y_msb = permut_msb[2*gid+1];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int permutN_lsb[2];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int permutN_msb[2];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutN_lsb[0] = permut_x_lsb;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutN_lsb[1] = permut_y_lsb;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutN_msb[0] = permut_x_msb;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutN_msb[1] = permut_y_msb;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int permutM_lsb[2];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int permutM_msb[2];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutM_lsb[0] = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutM_lsb[1] = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutM_msb[0] = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutM_msb[1] = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tuint tilesize = 64;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tuint LOGK=6;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tuint D=2;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tuint x[5][2];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint d=0; d<D; d++)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint nb_flags = 2;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint orig_lvl = tilesize-2 -1;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint i=1; i<LOGK; i++)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tx[i-1][d] = orig_lvl - (pattern[d]/(tilesize/nb_flags));\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\torig_lvl -= nb_flags;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnb_flags*=2;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tuint xcount[2];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint d=0; d<D; d++)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\txcount[d] = tilesize-LOGK-2; // bitset indexing: 0==least significant bit\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint i=1; i<tilesize-1; i++) { // start form the second i because xpermuts15bits[0].x = xpermuts15bits[0].y = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tuint ind = tilesize-2-i;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint d=0; d<D; d++)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbool isFlag=true;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint i=0; i<(uint)(LOGK-1); i++)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tisFlag &= (ind != x[i][d]);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif( isFlag ) \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(xcount[d] < 32)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint digit_value = ((permutN_lsb[d] >> xcount[d]) & 1);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(ind < 32)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int mask = (unsigned int)((unsigned int)1 << ind);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(digit_value)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutM_lsb[d] |= mask;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutM_lsb[d] &= (unsigned int)~mask;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int mask = (unsigned int)((unsigned int)1 << (ind-32));\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(digit_value)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutM_msb[d] |= mask;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutM_msb[d] &= (unsigned int)~mask;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint digit_value = ((permutN_msb[d] >> (xcount[d]-32)) & 1);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(ind < 32)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int mask = (unsigned int)((unsigned int)1 << ind);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(digit_value)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutM_lsb[d] |= mask;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutM_lsb[d] &= (unsigned int)~mask;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int mask = (unsigned int)((unsigned int)1 << (ind-32));\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(digit_value)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutM_msb[d] |= mask;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutM_msb[d] &= (unsigned int)~mask;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\txcount[d]--;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermut_x_lsb = permutM_lsb[0];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermut_y_lsb = permutM_lsb[1];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermut_x_msb = permutM_msb[0];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermut_y_msb = permutM_msb[1];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int permutted_pattern[128];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tint ind;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int xpermuts_lsb[2];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\txpermuts_lsb[0] = permut_x_lsb;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\txpermuts_lsb[1] = permut_y_lsb;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int xpermuts_msb[2];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\txpermuts_msb[0] = permut_x_msb;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\txpermuts_msb[1] = permut_y_msb;\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tuint NBITS = 6;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tuint PERMUTS_NBITS = tilesize-1;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint ipt=0; ipt<tilesize; ipt++) \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int xresdigits[2];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int thisSobolPt[2];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint d=0; d<2; d++)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tthisSobolPt[d] = pattern[2*ipt+d];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\txresdigits[0] = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\txresdigits[1] = 0;\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint ilevel=0; ilevel<NBITS; ilevel++) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint d=0; d<2; d++)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint power=(1 << ilevel);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tind = (pattern[2*ipt+d] >> (NBITS-ilevel)) + (power-1);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint digit_value_1 = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(PERMUTS_NBITS-ind-1 < 32)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdigit_value_1 =  (xpermuts_lsb[d] >> (PERMUTS_NBITS-ind-1)) & 1;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdigit_value_1 =  (xpermuts_msb[d] >> (PERMUTS_NBITS-ind-1-32)) & 1;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint digit_value_2 =  (thisSobolPt[d] >> (NBITS-ilevel-1)) & 1;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint digit_value = (digit_value_1 ^ digit_value_2);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint digit_pos = NBITS-ilevel-1;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int mask = (unsigned int)((unsigned int)1 << digit_pos);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(digit_value)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\txresdigits[d] |= mask;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\txresdigits[d] &= (unsigned int)~mask;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint d=0; d<2; d++)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutted_pattern[2*ipt+d] = xresdigits[d];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat mindist = 10000.0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor (uint ipts = 0; ipts < tilesize; ipts++) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor (uint ipts_to_compare = ipts+1; ipts_to_compare < tilesize; ipts_to_compare++) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat dist_sq = 0.0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat dx = (float)permutted_pattern[2*ipts]/(float)tilesize - (float)permutted_pattern[2*ipts_to_compare]/(float)tilesize;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdist_sq += dx*dx;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat dy = (float)permutted_pattern[2*ipts+1]/(float)tilesize - (float)permutted_pattern[2*ipts_to_compare+1]/(float)tilesize;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdist_sq += dy*dy;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (dist_sq < mindist) mindist = dist_sq;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tmin_dist[gid] = sqrt(mindist);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tscore[gid]= min_dist[gid];\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n                                                    );\n\nconst char source[] = BOOST_COMPUTE_STRINGIZE_SOURCE(__kernel void computeScorePCF(__global const unsigned int* permut_lsb,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__global const unsigned int* permut_msb,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__global const unsigned int* pattern,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__global const float* pcf,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__global float* min_dist,\n                                                                                __global float* score\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//__global unsigned int* debug\n                                                                              )\n\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tuint gid = get_global_id(0);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int permut_x_lsb = permut_lsb[2*gid];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int permut_y_lsb = permut_lsb[2*gid+1];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int permut_x_msb = permut_msb[2*gid];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int permut_y_msb = permut_msb[2*gid+1];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int permutN_lsb[2];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int permutN_msb[2];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutN_lsb[0] = permut_x_lsb;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutN_lsb[1] = permut_y_lsb;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutN_msb[0] = permut_x_msb;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutN_msb[1] = permut_y_msb;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int permutM_lsb[2];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int permutM_msb[2];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutM_lsb[0] = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutM_lsb[1] = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutM_msb[0] = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutM_msb[1] = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tuint tilesize = 64;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tuint LOGK=6;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tuint D=2;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tuint x[5][2];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint d=0; d<D; d++)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint nb_flags = 2;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint orig_lvl = tilesize-2 -1;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint i=1; i<LOGK; i++)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tx[i-1][d] = orig_lvl - (pattern[d]/(tilesize/nb_flags));\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\torig_lvl -= nb_flags;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnb_flags*=2;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tuint xcount[2];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint d=0; d<D; d++)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\txcount[d] = tilesize-LOGK-2; // bitset indexing: 0==least significant bit\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint i=1; i<tilesize-1; i++) { // start form the second i because xpermuts15bits[0].x = xpermuts15bits[0].y = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tuint ind = tilesize-2-i;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint d=0; d<D; d++)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbool isFlag=true;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint i=0; i<(uint)(LOGK-1); i++)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tisFlag &= (ind != x[i][d]);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif( isFlag ) \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(xcount[d] < 32)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint digit_value = ((permutN_lsb[d] >> xcount[d]) & 1);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(ind < 32)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int mask = (unsigned int)((unsigned int)1 << ind);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(digit_value)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutM_lsb[d] |= mask;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutM_lsb[d] &= (unsigned int)~mask;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int mask = (unsigned int)((unsigned int)1 << (ind-32));\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(digit_value)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutM_msb[d] |= mask;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutM_msb[d] &= (unsigned int)~mask;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint digit_value = ((permutN_msb[d] >> (xcount[d]-32)) & 1);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(ind < 32)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int mask = (unsigned int)((unsigned int)1 << ind);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(digit_value)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutM_lsb[d] |= mask;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutM_lsb[d] &= (unsigned int)~mask;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int mask = (unsigned int)((unsigned int)1 << (ind-32));\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(digit_value)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutM_msb[d] |= mask;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutM_msb[d] &= (unsigned int)~mask;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\txcount[d]--;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermut_x_lsb = permutM_lsb[0];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermut_y_lsb = permutM_lsb[1];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermut_x_msb = permutM_msb[0];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermut_y_msb = permutM_msb[1];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int permutted_pattern[128];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tint ind;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int xpermuts_lsb[2];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\txpermuts_lsb[0] = permut_x_lsb;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\txpermuts_lsb[1] = permut_y_lsb;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int xpermuts_msb[2];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\txpermuts_msb[0] = permut_x_msb;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\txpermuts_msb[1] = permut_y_msb;\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tuint NBITS = 6;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tuint PERMUTS_NBITS = tilesize-1;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint ipt=0; ipt<tilesize; ipt++) \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int xresdigits[2];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int thisSobolPt[2];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint d=0; d<2; d++)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tthisSobolPt[d] = pattern[2*ipt+d];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\txresdigits[0] = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\txresdigits[1] = 0;\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint ilevel=0; ilevel<NBITS; ilevel++) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint d=0; d<2; d++)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint power=(1 << ilevel);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tind = (pattern[2*ipt+d] >> (NBITS-ilevel)) + (power-1);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint digit_value_1 = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(PERMUTS_NBITS-ind-1 < 32)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdigit_value_1 =  (xpermuts_lsb[d] >> (PERMUTS_NBITS-ind-1)) & 1;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdigit_value_1 =  (xpermuts_msb[d] >> (PERMUTS_NBITS-ind-1-32)) & 1;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint digit_value_2 =  (thisSobolPt[d] >> (NBITS-ilevel-1)) & 1;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint digit_value = (digit_value_1 ^ digit_value_2);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint digit_pos = NBITS-ilevel-1;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int mask = (unsigned int)((unsigned int)1 << digit_pos);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(digit_value)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\txresdigits[d] |= mask;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\txresdigits[d] &= (unsigned int)~mask;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint d=0; d<2; d++)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermutted_pattern[2*ipt+d] = xresdigits[d];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat mindist = 10000.0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor (uint ipts = 0; ipts < tilesize; ipts++) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor (uint ipts_to_compare = ipts+1; ipts_to_compare < tilesize; ipts_to_compare++) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat dist_sq = 0.0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat dx = (float)permutted_pattern[2*ipts]/(float)tilesize - (float)permutted_pattern[2*ipts_to_compare]/(float)tilesize;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdist_sq += dx*dx;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat dy = (float)permutted_pattern[2*ipts+1]/(float)tilesize - (float)permutted_pattern[2*ipts_to_compare+1]/(float)tilesize;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdist_sq += dy*dy;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (dist_sq < mindist) mindist = dist_sq;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tmin_dist[gid] = sqrt(mindist);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(min_dist[gid] < 0.07)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tscore[gid] = 0.01;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat norm_dist = 2.0 * sqrt( 1.0 / (2.0*sqrt(3.0)*tilesize) );\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat smoothing = 0.1 * norm_dist;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat ra = 1.5*smoothing;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat rb = 2.5*norm_dist;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat ani_smoothing = 0.01;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat aa = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat ab = 2*M_PI;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tuint nbbins = 20;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat pcf_pattern[20];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat anisotropy_pattern[20];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint pcfid = 0; pcfid < nbbins; ++pcfid)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpcf_pattern[pcfid] = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tanisotropy_pattern[pcfid] = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat bin_size = (rb-ra)/(float)nbbins;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tuint covering = ((2.0*smoothing)/bin_size)+1;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(covering > nbbins)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcovering = nbbins;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat ani_bin_size = (ab-aa)/(float)nbbins;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tuint ani_covering = ((2.0*ani_smoothing)/ani_bin_size)+1;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(ani_covering > nbbins)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tani_covering = nbbins;\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint i=0; i<tilesize; i++)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint j=(i+1); j<tilesize; j++)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat dist_sq = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat dx = (float)permutted_pattern[2*i]/(float)tilesize - (float)permutted_pattern[2*j]/(float)tilesize;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdx*=dx;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdist_sq += dx;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat dy = (float)permutted_pattern[2*i+1]/(float)tilesize - (float)permutted_pattern[2*j+1]/(float)tilesize;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdy*=dy;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdist_sq += dy;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat dxy = dist_sq;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdx=sqrt(dx);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdy=sqrt(dy);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat vector_angle = atan(dy/dx);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint ani_init_bin = vector_angle/bin_size;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tanisotropy_pattern[ani_init_bin] += 1;\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint init_bin = sqrt(dxy)/bin_size;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint ida = init_bin - covering;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint idb = init_bin + covering;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(ida < 0) ida = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(idb > nbbins) idb = nbbins;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint pcfid = ida; pcfid < idb; ++pcfid)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat r = ra + pcfid*(rb - ra) / (float) nbbins;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat dist = r - sqrt(dxy);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat val = ( 1.0/(sqrt(2*M_PI)*smoothing) ) * exp( -0.5*(dist*dist)/(smoothing*smoothing) );\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpcf_pattern[pcfid] += 2*val;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint pcfid = 0; pcfid < nbbins; ++pcfid)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat r = ra + pcfid*(rb - ra) / (float) nbbins;\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat cov = 1.0 - ((2.0*r)/M_PI)*2.0 + ((r*r)/M_PI);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat factor = 2.0*M_PI*r*cov;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfactor = 1.0/factor;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpcf_pattern[pcfid] *= factor;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpcf_pattern[pcfid] /= (tilesize*(tilesize-1));\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tanisotropy_pattern[pcfid] /= 20.0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat linf = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat ani_linf = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(uint i=0; i<nbbins; i++)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(pcf_pattern[i] != 0 && fabs(pcf[i] - pcf_pattern[i]) > linf )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlinf = fabs(pcf[i] - pcf_pattern[i]);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(anisotropy_pattern[i] != 0 && fabs(1 - anisotropy_pattern[i]) > ani_linf )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tani_linf = fabs(1 - anisotropy_pattern[i]);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tscore[gid] = 10 -linf -ani_linf;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n                                                    );\n\n\nbool permutFromNbitsToMbits(uint N, uint M, uint fixed_point[2], unsigned long long int permutN_x, unsigned long long int permutN_y, \n\t\t\t\t\t\t\tunsigned long long int& permutM_x, unsigned long long int& permutM_y)\n{\n\tint tilesize = M+1;\n\tint LOGK=log2(tilesize);\n\tuint D=2;\n\t\n\tstd::vector< std::array<uint, 2> > x;\n\tx.resize(LOGK-1);\n\tfor(uint d=0; d<D; d++)\n\t{\n\t\tint nb_flags = 2;\n\t\tint orig_lvl = tilesize-2 -1;\n\t\tfor(int i=1; i<LOGK; i++)\n\t\t{\n\t\t\tx[i-1][d] = orig_lvl - (fixed_point[d]/(tilesize/nb_flags));\n\t\t\torig_lvl -= nb_flags;\n\t\t\tnb_flags*=2;\n\t\t}\n\t}\n\t\n\tstd::bitset<64> xpermutsNbits[2];\n\txpermutsNbits[0] = permutN_x;\n\txpermutsNbits[1] = permutN_y;\n\t\n\tstd::bitset<64> xpermutsMbits[2];\n\tint xcount[2];\n\tfor(uint d=0; d<D; d++)\n\t\txcount[d] = tilesize-LOGK-2; // bitset indexing: 0==least significant bit\n\tfor(uint i=1; i<(uint)(tilesize-1); i++) { // start form the second i because xpermuts15bits[0].x = xpermuts15bits[0].y = 0;\n\t\tuint ind = tilesize-2-i;\n\t\t\n\t\tfor(uint d=0; d<D; d++)\n\t\t{\n\t\t\tbool isFlag=true;\n\t\t\tfor(int i=0; i<LOGK-1; i++)\n\t\t\t\tisFlag &= (ind != x[i][d]);\n\t\t\t\n\t\t\tif( isFlag ) {\n\t\t\t\txpermutsMbits[d][ind] = xpermutsNbits[d][xcount[d]];\n\t\t\t\txcount[d]--;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpermutM_x = xpermutsMbits[0].to_ullong();\n\tpermutM_y = xpermutsMbits[1].to_ullong();\n\t\n\treturn true;\n}\n\n\n/*void computeScoreCPU(const unsigned int* permut_lsb,\n\t\t\t\t\t\tconst unsigned int* permut_msb,\n\t\t\t\t\t\tconst unsigned int* pattern,\n\t\t\t\t\t\tconst float* pcf,\n\t\t\t\t\t\tfloat* min_dist,\n                        float* score, uint gid)\n{\n\t//Copy OpenCL Kernel Here\n}*/\n\nbool optimizeGPU(utk::Pointset<2, unsigned int, utk::Point<2, unsigned int> > pts, utk::Histogram1dd pcf_data, utk::Vector<2, unsigned long long int>& resulting_permut)\n{\n\tassert(pts.size() == 64);\n\t\n\tsrand48(time(NULL));\n\tfloat max_score= 0;\n\tfloat max_dist = 0;\n\tint max_id=0;\n\t\n\tint t = time(NULL);\n\t\n\t//get default device and setup context\n\tcompute::device device = compute::system::default_device();\n\tcompute::context context(device);\n\tcompute::command_queue queue(context, device);\n\n\tint nbbins = 20;\n\tassert(pcf_data.size() == (uint)nbbins);\t\n\tstd::vector<float> local_pcf;\n\tlocal_pcf.resize(nbbins);\n\tfor(int i=0; i<nbbins; i++)\n\t\tlocal_pcf[i] = pcf_data[i].second;\n\t\n\tstd::cout << \"Local PCF Vector OK\" << std::endl;\n\t\n\t//Send PCF to the device\n\tcompute::vector<float> device_pcf(local_pcf.size(), context);\n\tcompute::copy(local_pcf.begin(), local_pcf.end(), device_pcf.begin(), queue);\n\tstd::cout << \"Device PCF Vector OK\" << std::endl;\n\n\tstd::vector<unsigned int> local_pattern(pts.size()*2, 0);\n\tfor(uint i=0; i<pts.size(); i++)\n\t{\n\t\tlocal_pattern[2*i] = pts[i].pos()[0];\n\t\tlocal_pattern[2*i+1] = pts[i].pos()[1];\n\t}\n\tstd::cout << \"Local Pattern Vector OK\" << std::endl;\n\t\n\t//Send pattern to the device\n\tcompute::vector<unsigned int> device_pattern(pts.size()*2, context);\n\tcompute::copy(local_pattern.begin(), local_pattern.end(), device_pattern.begin(), queue);\n\tstd::cout << \"Device Pattern Vector OK\" << std::endl;\n\t\n\t\n\tuint tilesize=64;\n\tuint N, M;\n\tM = tilesize-1;\n\tN = M - log2(tilesize);\n\tuint zero_pt[2]; zero_pt[0] = local_pattern[0]; zero_pt[1] = local_pattern[1];\n\tint nbfreedigits = 11;\n\tint npermut = (1 << nbfreedigits);\n\n\tint nbbatches=2048;\n\tint batch_size = (npermut*npermut)/nbbatches;\n\t\n\t//Create result vector\n\tcompute::vector<float> device_mindist(batch_size, context);\n\tstd::fill(device_mindist.begin(), device_mindist.end(), 0);\n\tstd::cout << \"Device MinDist Vector OK\" << std::endl;\n\t\n\tcompute::vector<float> device_score(batch_size, context);\n\tstd::fill(device_score.begin(), device_score.end(), 0);\n\tstd::cout << \"Device Result Vector OK\" << std::endl;\n\t\n\tcompute::vector<unsigned int> device_permutations_lsb(batch_size*2, context);\n\tcompute::vector<unsigned int> device_permutations_msb(batch_size*2, context);\n\tstd::vector<float> local_mindist(batch_size);\n\tstd::vector<float> local_score(batch_size);\t\n\t\n\tstd::cout << \"Building Kernel ...\" << std::endl;\n\t\n\t//Create and build the kernels\n\t\n\t//Create and build the kernels\n\tcompute::program m_program;\n\tm_program = compute::program::create_with_source(source, context);\n\ttry\n\t{\n\t\tm_program.build();\n\t}\n\tcatch(boost::compute::opencl_error &e)\n\t{\n\t\tstd::cout << m_program.build_log() << std::endl;\n\t}\n\tcompute::kernel score_kernel;\n\tscore_kernel = m_program.create_kernel(\"computeScorePCF\");\n\tscore_kernel.set_arg(0, device_permutations_lsb.get_buffer());\n\tscore_kernel.set_arg(1, device_permutations_msb.get_buffer());\n\tscore_kernel.set_arg(2, device_pattern.get_buffer());\n\tscore_kernel.set_arg(3, device_pcf.get_buffer());\n\tscore_kernel.set_arg(4, device_mindist.get_buffer());\n\tscore_kernel.set_arg(5, device_score.get_buffer());\n\tstd::cout << \"OK\" << std::endl;\n\n\t\n\tstd::cout << \"Optimizing first \" << nbfreedigits << \" digits ...\" << std::endl;\n\t\n\tstd::vector<unsigned long long int> local_permutations_full(npermut*npermut*2, 0);\n\tfor(int i=0; i<npermut; i++)\n\t{\n\t\tfor(int j=0; j<npermut; j++)\n\t\t{\n\t\t\tlocal_permutations_full[2*(i*npermut+j)] = (unsigned long long int)((unsigned long long int)i << (unsigned long long int)(N-nbfreedigits));\n\t\t\tlocal_permutations_full[2*(i*npermut+j)+1] = (unsigned long long int)((unsigned long long int)j << (unsigned long long int)(N-nbfreedigits));\n\t\t}\n\t}\n\tstd::vector<unsigned int> local_permutations_lsb(npermut*npermut*2, 0);\n\tstd::vector<unsigned int> local_permutations_msb(npermut*npermut*2, 0);\n\tfor(int i=0; i<npermut; i++)\n\tfor(int j=0; j<npermut; j++)\n\t{\n\t\tlocal_permutations_lsb[2*(i*npermut+j)] = (unsigned long long int)((local_permutations_full[2*(i*npermut+j)]) & (unsigned long long int)0xffffff);\n\t\tlocal_permutations_lsb[2*(i*npermut+j)+1] = (unsigned long long int)((local_permutations_full[2*(i*npermut+j)+1]) & (unsigned long long int)0xffffff);\n\t\t\n\t\tlocal_permutations_msb[2*(i*npermut+j)] = ((local_permutations_full[2*(i*npermut+j)]) >> 32);\n\t\tlocal_permutations_msb[2*(i*npermut+j)+1] = ((local_permutations_full[2*(i*npermut+j)+1]) >> 32);\n\t}\n\tstd::cout << \"Local Permut Vector OK\" << std::endl;\n\n\tfor(int batch=0; batch<nbbatches; batch++)\n\t{\n\t\tcompute::copy(local_permutations_lsb.begin()+(2*batch*batch_size), local_permutations_lsb.begin()+(2*(batch+1)*batch_size), device_permutations_lsb.begin(), queue);\n\t\tcompute::copy(local_permutations_msb.begin()+(2*batch*batch_size), local_permutations_msb.begin()+(2*(batch+1)*batch_size), device_permutations_msb.begin(), queue);\n\n\t\t//Go Go go !\n\t\t//std::cout << batch << \"/\" << nbbatches << \"\\r\" << std::flush;\n\t\tqueue.enqueue_1d_range_kernel(score_kernel, 0, batch_size, 0);\n\t\t\n\t\tcompute::copy(device_mindist.begin(), device_mindist.end(), local_mindist.begin(), queue);\n\t\tcompute::copy(device_score.begin(), device_score.end(), local_score.begin(), queue);\n\t\t\n\t\tfor(int i=0; i<batch_size; i++)\n\t\t{\n\t\t\tif( max_score < local_score[i])\n\t\t\t{\n\t\t\t\tmax_dist = local_mindist[i];\n\t\t\t\tmax_id = batch*batch_size+i;\n\t\t\t\tmax_score = local_score[i];\n\t\t\t}\n\t\t}\n\t}\n\t\n\t/*unsigned long long int final_perm_x, final_perm_y;\n\tpermutFromNbitsToMbits(N, M, zero_pt, local_permutations_full[2*max_id], local_permutations_full[2*max_id+1], final_perm_x, final_perm_y);\n\tstd::cout << \"Done [\" << time(NULL) - t << \"s]\" << std::endl;\n\tstd::cout<< \"[DEVICE] Current Best Permut \" << final_perm_x << \",\" << final_perm_y << \" (score \" << max_score << \")\" << \"(dist \" << max_dist << \")\" << std::endl;*/\n\t\n\tstd::cout << \"Optimizing last \" << (N-nbfreedigits) << \" digits ...\" << std::endl;\n\tfor(int i=0; i<npermut; i++)\n\t{\n\t\tfor(int j=0; j<npermut; j++)\n\t\t{\n\t\t\tunsigned long long int randval = (unsigned long long int)(drand48()*((unsigned long long int)1 << (unsigned long long int)(N-nbfreedigits)));\n\t\t\tlocal_permutations_full[2*(i*npermut+j)] = local_permutations_full[2*max_id] + randval;\n\t\t\trandval = drand48()*(1 << (N-nbfreedigits));\n\t\t\tlocal_permutations_full[2*(i*npermut+j)+1] = local_permutations_full[2*max_id+1] + randval;\n\t\t}\n\t}\n\tfor(int i=0; i<npermut; i++)\n\tfor(int j=0; j<npermut; j++)\n\t{\n\t\tlocal_permutations_lsb[2*(i*npermut+j)] = (unsigned long long int)((local_permutations_full[2*(i*npermut+j)]) & (unsigned long long int)0xffffff);\n\t\tlocal_permutations_lsb[2*(i*npermut+j)+1] = (unsigned long long int)((local_permutations_full[2*(i*npermut+j)+1]) & (unsigned long long int)0xffffff);\n\t\t\n\t\tlocal_permutations_msb[2*(i*npermut+j)] = ((local_permutations_full[2*(i*npermut+j)]) >> 32);\n\t\tlocal_permutations_msb[2*(i*npermut+j)+1] = ((local_permutations_full[2*(i*npermut+j)+1]) >> 32);\n\t}\n\tstd::cout << \"Local Permut Vector OK\" << std::endl;\n\t\n\tfor(int batch=0; batch<nbbatches; batch++)\n\t{\n\t\tcompute::copy(local_permutations_lsb.begin()+(2*batch*batch_size), local_permutations_lsb.begin()+(2*(batch+1)*batch_size), device_permutations_lsb.begin(), queue);\n\t\tcompute::copy(local_permutations_msb.begin()+(2*batch*batch_size), local_permutations_msb.begin()+(2*(batch+1)*batch_size), device_permutations_msb.begin(), queue);\n\n\t\t//Go Go go !\n\t\t//std::cout << batch << \"/\" << nbbatches << \"\\r\" << std::flush;\n\t\tqueue.enqueue_1d_range_kernel(score_kernel, 0, batch_size, 0);\n\t\tcompute::copy(device_mindist.begin(), device_mindist.end(), local_mindist.begin(), queue);\n\t\tcompute::copy(device_score.begin(), device_score.end(), local_score.begin(), queue);\n\t\t\n\t\tfor(int i=0; i<batch_size; i++)\n\t\t{\n\t\t\t//computeScoreCPU(&local_permutations_lsb[2*batch*batch_size], &local_permutations_msb[2*batch*batch_size], &local_pattern[0], &local_pcf[0], &local_mindist[0], &local_score[0], i);\n\t\t\t//exit(1);\n\t\t\tif( max_score < local_score[i])\n\t\t\t{\n\t\t\t\tmax_dist = local_mindist[i];\n\t\t\t\tmax_id = batch*batch_size+i;\n\t\t\t\tmax_score = local_score[i];\n\t\t\t}\n\t\t}\n\t}\n\t\n\tresulting_permut[0] = 0; resulting_permut[1] = 0;\n\tpermutFromNbitsToMbits(N, M, zero_pt, local_permutations_full[2*max_id], local_permutations_full[2*max_id+1], resulting_permut[0], resulting_permut[1]);\n\tstd::cout << \"Done [\" << time(NULL) - t << \"s]\" << std::endl;\n\tstd::cout<< \"[DEVICE] Best Permut \" << resulting_permut[0] << \",\" << resulting_permut[1] << \" (score \" << max_score << \")\" << \"(dist \" << max_dist << \")\" << std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "9ed8fef047de259350e302d41d918e5a3b332333", "size": 28658, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/samplers/SamplerBNLDS/SamplerBNLDS_GPU_optim.hpp", "max_stars_repo_name": "FrancoisGaits/utk", "max_stars_repo_head_hexsha": "8c408dd79635f98c46ed075c098f15e23972aad0", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 44.0, "max_stars_repo_stars_event_min_datetime": "2018-01-09T19:56:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T06:38:54.000Z", "max_issues_repo_path": "src/samplers/SamplerBNLDS/SamplerBNLDS_GPU_optim.hpp", "max_issues_repo_name": "FrancoisGaits/utk", "max_issues_repo_head_hexsha": "8c408dd79635f98c46ed075c098f15e23972aad0", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2018-01-29T18:01:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T07:01:09.000Z", "max_forks_repo_path": "src/samplers/SamplerBNLDS/SamplerBNLDS_GPU_optim.hpp", "max_forks_repo_name": "FrancoisGaits/utk", "max_forks_repo_head_hexsha": "8c408dd79635f98c46ed075c098f15e23972aad0", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-03-14T00:24:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T06:40:07.000Z", "avg_line_length": 38.6747638327, "max_line_length": 184, "alphanum_fraction": 0.5109219066, "num_tokens": 7964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2829515696044225}}
{"text": "// Copyright (c) 2022, ETH Zurich and UNC Chapel Hill.\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\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 ETH Zurich and UNC Chapel Hill nor the names of\n//       its 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 HOLDERS OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Author: Johannes L. Schoenberger (jsch-at-demuc-dot-de)\n\n#include \"estimators/homography_matrix.h\"\n\n#include <Eigen/Geometry>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n\n#include \"base/projection.h\"\n#include \"estimators/utils.h\"\n#include \"util/logging.h\"\n\nnamespace colmap {\n\nstd::vector<HomographyMatrixEstimator::M_t> HomographyMatrixEstimator::Estimate(\n    const std::vector<X_t>& points1, const std::vector<Y_t>& points2) {\n  CHECK_EQ(points1.size(), points2.size());\n\n  const size_t N = points1.size();\n\n  // Center and normalize image points for better numerical stability.\n  std::vector<X_t> normed_points1;\n  std::vector<Y_t> normed_points2;\n  Eigen::Matrix3d points1_norm_matrix;\n  Eigen::Matrix3d points2_norm_matrix;\n  CenterAndNormalizeImagePoints(points1, &normed_points1, &points1_norm_matrix);\n  CenterAndNormalizeImagePoints(points2, &normed_points2, &points2_norm_matrix);\n\n  // Setup constraint matrix.\n  Eigen::Matrix<double, Eigen::Dynamic, 9> A = Eigen::MatrixXd::Zero(2 * N, 9);\n\n  for (size_t i = 0, j = N; i < points1.size(); ++i, ++j) {\n    const double s_0 = normed_points1[i](0);\n    const double s_1 = normed_points1[i](1);\n    const double d_0 = normed_points2[i](0);\n    const double d_1 = normed_points2[i](1);\n\n    A(i, 0) = -s_0;\n    A(i, 1) = -s_1;\n    A(i, 2) = -1;\n    A(i, 6) = s_0 * d_0;\n    A(i, 7) = s_1 * d_0;\n    A(i, 8) = d_0;\n\n    A(j, 3) = -s_0;\n    A(j, 4) = -s_1;\n    A(j, 5) = -1;\n    A(j, 6) = s_0 * d_1;\n    A(j, 7) = s_1 * d_1;\n    A(j, 8) = d_1;\n  }\n\n  // Solve for the nullspace of the constraint matrix.\n  Eigen::JacobiSVD<Eigen::Matrix<double, Eigen::Dynamic, 9>> svd(\n      A, Eigen::ComputeFullV);\n\n  const Eigen::VectorXd nullspace = svd.matrixV().col(8);\n  Eigen::Map<const Eigen::Matrix3d> H_t(nullspace.data());\n\n  const std::vector<M_t> models = {points2_norm_matrix.inverse() *\n                                   H_t.transpose() * points1_norm_matrix};\n  return models;\n}\n\nvoid HomographyMatrixEstimator::Residuals(const std::vector<X_t>& points1,\n                                          const std::vector<Y_t>& points2,\n                                          const M_t& H,\n                                          std::vector<double>* residuals) {\n  CHECK_EQ(points1.size(), points2.size());\n\n  residuals->resize(points1.size());\n\n  // Note that this code might not be as nice as Eigen expressions,\n  // but it is significantly faster in various tests.\n\n  const double H_00 = H(0, 0);\n  const double H_01 = H(0, 1);\n  const double H_02 = H(0, 2);\n  const double H_10 = H(1, 0);\n  const double H_11 = H(1, 1);\n  const double H_12 = H(1, 2);\n  const double H_20 = H(2, 0);\n  const double H_21 = H(2, 1);\n  const double H_22 = H(2, 2);\n\n  for (size_t i = 0; i < points1.size(); ++i) {\n    const double s_0 = points1[i](0);\n    const double s_1 = points1[i](1);\n    const double d_0 = points2[i](0);\n    const double d_1 = points2[i](1);\n\n    const double pd_0 = H_00 * s_0 + H_01 * s_1 + H_02;\n    const double pd_1 = H_10 * s_0 + H_11 * s_1 + H_12;\n    const double pd_2 = H_20 * s_0 + H_21 * s_1 + H_22;\n\n    const double inv_pd_2 = 1.0 / pd_2;\n    const double dd_0 = d_0 - pd_0 * inv_pd_2;\n    const double dd_1 = d_1 - pd_1 * inv_pd_2;\n\n    (*residuals)[i] = dd_0 * dd_0 + dd_1 * dd_1;\n  }\n}\n\n}  // namespace colmap\n", "meta": {"hexsha": "1bf70f815b129f904a348a7dac0d8c41d5c6f269", "size": 4924, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/estimators/homography_matrix.cc", "max_stars_repo_name": "ashishd/colmap", "max_stars_repo_head_hexsha": "30521f19de45c1cb2df8809728e780bf95fc8836", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-02-18T04:58:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T04:59:13.000Z", "max_issues_repo_path": "src/estimators/homography_matrix.cc", "max_issues_repo_name": "hyowonha/colmap", "max_issues_repo_head_hexsha": "d908cc37cbf97701b589a047274e3a7fbaf17c54", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/estimators/homography_matrix.cc", "max_forks_repo_name": "hyowonha/colmap", "max_forks_repo_head_hexsha": "d908cc37cbf97701b589a047274e3a7fbaf17c54", "max_forks_repo_licenses": ["BSD-3-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.7462686567, "max_line_length": 80, "alphanum_fraction": 0.6632818846, "num_tokens": 1422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.2829486641347015}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2014 Olga Diamanti <olga.diam@gmail.com>\n//\n// This Source Code Form is subject to the terms of the Mozilla Public License\n// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n// obtain one at http://mozilla.org/MPL/2.0/.\n\n#include <igl/angle_bound_frame_fields.h>\n#include <igl/edge_topology.h>\n#include <igl/local_basis.h>\n#include <igl/sparse.h>\n#include <igl/speye.h>\n#include <igl/slice.h>\n#include <igl/polyroots.h>\n#include <igl/colon.h>\n#include <Eigen/Sparse>\n\n#include <iostream>\n\nnamespace igl {\n\n  template <typename DerivedV, typename DerivedF>\n  class AngleBoundFFSolverData\n  {\n    public:\n      const Eigen::PlainObjectBase<DerivedV> &V; int numV;\n      const Eigen::PlainObjectBase<DerivedF> &F; int numF;\n\n      Eigen::MatrixXi EV; int numE;\n      Eigen::MatrixXi F2E;\n      Eigen::MatrixXi E2F;\n      Eigen::VectorXd K;\n\n      Eigen::VectorXi isBorderEdge;\n      int numInteriorEdges;\n      Eigen::Matrix<int,Eigen::Dynamic,2> E2F_int;\n      Eigen::VectorXi indInteriorToFull;\n      Eigen::VectorXi indFullToInterior;\n\n      DerivedV B1, B2, FN;\n\n      //laplacians\n      Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar>> DDA, DDB;\n\n  private:\n    IGL_INLINE void computeLaplacians();\n    IGL_INLINE void computek();\n    IGL_INLINE void computeCoefficientLaplacian(int n, Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &D);\n    IGL_INLINE void precomputeInteriorEdges();\n\npublic:\n      IGL_INLINE AngleBoundFFSolverData(const Eigen::PlainObjectBase<DerivedV> &_V,\n                                   const Eigen::PlainObjectBase<DerivedF> &_F);\n  };\n\n  template <typename DerivedV, typename DerivedF, typename DerivedO>\n  class AngleBoundFFSolver\n  {\n  public:\n    IGL_INLINE AngleBoundFFSolver(const AngleBoundFFSolverData<DerivedV, DerivedF> &_data,\n                                  const typename DerivedV::Scalar &_thetaMin = 30,\n                                 int _maxIter = 50,\n                                 const typename DerivedV::Scalar &_lambdaInit = 100,\n                                 const typename DerivedV::Scalar &_lambdaMultFactor = 1.01,\n                                const bool _doHardConstraints = false);\n    IGL_INLINE bool solve(const Eigen::VectorXi &isConstrained,\n                          const Eigen::PlainObjectBase<DerivedO> &initialSolution,\n                          Eigen::PlainObjectBase<DerivedO> &output,\n                          typename DerivedV::Scalar *lambdaOut = NULL);\n\n  private:\n\n    const AngleBoundFFSolverData<DerivedV, DerivedF> &data;\n\n    //polyVF data\n    Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> Acoeff, Bcoeff;\n    Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 2> pvU, pvV;\n    typename DerivedV::Scalar lambda;\n\n    //parameters\n    typename DerivedV::Scalar lambdaInit,lambdaMultFactor;\n    int maxIter;\n    typename DerivedV::Scalar thetaMin;\n    bool doHardConstraints;\n\n    typename DerivedV::Scalar computeAngle(const std::complex<typename DerivedV::Scalar> &u,\n                                           const std::complex<typename DerivedV::Scalar> &v);\n//    IGL_INLINE void computeAngles(Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1> &angles);\n\n    IGL_INLINE int getNumOutOfBounds();\n\n    IGL_INLINE void rotateAroundBisector(const std::complex<typename DerivedV::Scalar> &uin,\n                         const std::complex<typename DerivedV::Scalar> &vin,\n                         const typename DerivedV::Scalar theta,\n                         std::complex<typename DerivedV::Scalar> &uout,\n                         std::complex<typename DerivedV::Scalar> &vout);\n\n    IGL_INLINE void localStep();\n\n    IGL_INLINE void globalStep(const Eigen::Matrix<int, Eigen::Dynamic, 1>  &isConstrained,\n                               const Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1>  &Ak,\n                               const Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1>  &Bk);\n\n    IGL_INLINE void minQuadWithKnownMini(const Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &Q,\n                         const Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &f,\n                         const Eigen::VectorXi isConstrained,\n                         const Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> &xknown,\n                                         Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> &x);\n    IGL_INLINE void setFieldFromCoefficients();\n    IGL_INLINE void setCoefficientsFromField();\n\n  };\n}\n\n//Implementation\n/***************************** Data ***********************************/\n\ntemplate <typename DerivedV, typename DerivedF>\nIGL_INLINE igl::AngleBoundFFSolverData<DerivedV, DerivedF>::\nAngleBoundFFSolverData(const Eigen::PlainObjectBase<DerivedV> &_V,\n                  const Eigen::PlainObjectBase<DerivedF> &_F):\nV(_V),\nnumV(_V.rows()),\nF(_F),\nnumF(_F.rows())\n{\n  igl::edge_topology(V,F,EV,F2E,E2F);\n  numE = EV.rows();\n\n  precomputeInteriorEdges();\n\n  igl::local_basis(V,F,B1,B2,FN);\n\n  computek();\n\n  computeLaplacians();\n\n};\n\n\ntemplate <typename DerivedV, typename DerivedF>\nIGL_INLINE void igl::AngleBoundFFSolverData<DerivedV, DerivedF>::computeLaplacians()\n{\n  computeCoefficientLaplacian(2, DDA);\n\n  computeCoefficientLaplacian(4, DDB);\n}\n\ntemplate<typename DerivedV, typename DerivedF>\nIGL_INLINE void igl::AngleBoundFFSolverData<DerivedV, DerivedF>::\nprecomputeInteriorEdges()\n{\n  // Flag border edges\n  numInteriorEdges = 0;\n  isBorderEdge.setZero(numE,1);\n  indFullToInterior = Eigen::VectorXi::Constant(numE,-1);\n\n  for(unsigned i=0; i<numE; ++i)\n  {\n    if ((E2F(i,0) == -1) || ((E2F(i,1) == -1)))\n      isBorderEdge[i] = 1;\n    else\n    {\n      indFullToInterior[i] = numInteriorEdges;\n      numInteriorEdges++;\n    }\n  }\n\n  E2F_int.resize(numInteriorEdges, 2);\n  indInteriorToFull.setZero(numInteriorEdges,1);\n  int ii = 0;\n  for (int k=0; k<numE; ++k)\n  {\n    if (isBorderEdge[k])\n      continue;\n    E2F_int.row(ii) = E2F.row(k);\n    indInteriorToFull[ii] = k;\n    ii++;\n  }\n\n}\n\n\n\ntemplate<typename DerivedV, typename DerivedF>\nIGL_INLINE void igl::AngleBoundFFSolverData<DerivedV, DerivedF>::\ncomputeCoefficientLaplacian(int n, Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &D)\n{\n  std::vector<Eigen::Triplet<std::complex<typename DerivedV::Scalar> >> tripletList;\n\n  // For every non-border edge\n  for (unsigned eid=0; eid<numE; ++eid)\n  {\n    if (!isBorderEdge[eid])\n    {\n      int fid0 = E2F(eid,0);\n      int fid1 = E2F(eid,1);\n\n      tripletList.push_back(Eigen::Triplet<std::complex<typename DerivedV::Scalar> >(fid0,\n                                                                                     fid0,\n                                                                                     std::complex<typename DerivedV::Scalar>(1.)));\n      tripletList.push_back(Eigen::Triplet<std::complex<typename DerivedV::Scalar> >(fid1,\n                                                                                     fid1,\n                                                                                     std::complex<typename DerivedV::Scalar>(1.)));\n      tripletList.push_back(Eigen::Triplet<std::complex<typename DerivedV::Scalar> >(fid0,\n                                                                                     fid1,\n                                                                                     -1.*std::polar(1.,-1.*n*K[eid])));\n      tripletList.push_back(Eigen::Triplet<std::complex<typename DerivedV::Scalar> >(fid1,\n                                                                                     fid0,\n                                                                                     -1.*std::polar(1.,1.*n*K[eid])));\n\n    }\n  }\n  D.resize(numF,numF);\n  D.setFromTriplets(tripletList.begin(), tripletList.end());\n\n\n}\n\ntemplate<typename DerivedV, typename DerivedF>\nIGL_INLINE void igl::AngleBoundFFSolverData<DerivedV, DerivedF>::\ncomputek()\n{\n  K.setZero(numE);\n  // For every non-border edge\n  for (unsigned eid=0; eid<numE; ++eid)\n  {\n    if (!isBorderEdge[eid])\n    {\n      int fid0 = E2F(eid,0);\n      int fid1 = E2F(eid,1);\n\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> N0 = FN.row(fid0);\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> N1 = FN.row(fid1);\n\n      // find common edge on triangle 0 and 1\n      int fid0_vc = -1;\n      int fid1_vc = -1;\n      for (unsigned i=0;i<3;++i)\n      {\n        if (F2E(fid0,i) == eid)\n          fid0_vc = i;\n        if (F2E(fid1,i) == eid)\n          fid1_vc = i;\n      }\n      assert(fid0_vc != -1);\n      assert(fid1_vc != -1);\n\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> common_edge = V.row(F(fid0,(fid0_vc+1)%3)) - V.row(F(fid0,fid0_vc));\n      common_edge.normalize();\n\n      // Map the two triangles in a new space where the common edge is the x axis and the N0 the z axis\n      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> P;\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> o = V.row(F(fid0,fid0_vc));\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> tmp = -N0.cross(common_edge);\n      P << common_edge, tmp, N0;\n      //      P.transposeInPlace();\n\n\n      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> V0;\n      V0.row(0) = V.row(F(fid0,0)) -o;\n      V0.row(1) = V.row(F(fid0,1)) -o;\n      V0.row(2) = V.row(F(fid0,2)) -o;\n\n      V0 = (P*V0.transpose()).transpose();\n\n      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> V1;\n      V1.row(0) = V.row(F(fid1,0)) -o;\n      V1.row(1) = V.row(F(fid1,1)) -o;\n      V1.row(2) = V.row(F(fid1,2)) -o;\n      V1 = (P*V1.transpose()).transpose();\n\n      // compute rotation R such that R * N1 = N0\n      // i.e. map both triangles to the same plane\n      double alpha = -atan2(V1((fid1_vc+2)%3,2),V1((fid1_vc+2)%3,1));\n\n      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> R;\n      R << 1,          0,            0,\n      0, cos(alpha), -sin(alpha) ,\n      0, sin(alpha),  cos(alpha);\n      V1 = (R*V1.transpose()).transpose();\n\n      // measure the angle between the reference frames\n      // k_ij is the angle between the triangle on the left and the one on the right\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> ref0 = V0.row(1) - V0.row(0);\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> ref1 = V1.row(1) - V1.row(0);\n\n      ref0.normalize();\n      ref1.normalize();\n\n      double ktemp = atan2(ref1(1),ref1(0)) - atan2(ref0(1),ref0(0));\n\n      // just to be sure, rotate ref0 using angle ktemp...\n      Eigen::Matrix<typename DerivedV::Scalar, 2, 2> R2;\n      R2 << cos(ktemp), -sin(ktemp), sin(ktemp), cos(ktemp);\n\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 2> tmp1 = R2*(ref0.head(2)).transpose();\n\n      K[eid] = ktemp;\n    }\n  }\n\n}\n\n\n/***************************** Solver ***********************************/\ntemplate <typename DerivedV, typename DerivedF, typename DerivedO>\nIGL_INLINE igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO>::\nAngleBoundFFSolver(const AngleBoundFFSolverData<DerivedV, DerivedF> &_data,\n                   const typename DerivedV::Scalar &_thetaMin,\n                  int _maxIter,\n                  const typename DerivedV::Scalar &_lambdaInit,\n                  const typename DerivedV::Scalar &_lambdaMultFactor,\n                   const bool _doHardConstraints):\ndata(_data),\nlambdaInit(_lambdaInit),\nmaxIter(_maxIter),\nlambdaMultFactor(_lambdaMultFactor),\ndoHardConstraints(_doHardConstraints),\nthetaMin(_thetaMin)\n{\n  Acoeff.resize(data.numF,1);\n  Bcoeff.resize(data.numF,1);\n  pvU.setZero(data.numF, 2);\n  pvV.setZero(data.numF, 2);\n};\n\ntemplate<typename DerivedV, typename DerivedF, typename DerivedO>\nIGL_INLINE void igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO>::\nrotateAroundBisector(const std::complex<typename DerivedV::Scalar> &uin,\n                          const std::complex<typename DerivedV::Scalar> &vin,\n                          const typename DerivedV::Scalar diff,\n                          std::complex<typename DerivedV::Scalar> &uout,\n                          std::complex<typename DerivedV::Scalar> &vout)\n{\n  //rotate 2D complex vectors u and v around their bisector so that their\n  //angle is at least theta\n\n  uout = uin;\n  vout = vin;\n  typename DerivedV::Scalar au = arg(uin);\n  typename DerivedV::Scalar av = arg(vin);\n  if (au<av)\n  {\n    uout = std::polar (1.0,-.5*diff)*uin;\n    vout = std::polar (1.0, .5*diff)*vin;\n  }\n  else\n  {\n    uout = std::polar (1.0, .5*diff)*uin;\n    vout = std::polar (1.0,-.5*diff)*vin;\n  }\n\n}\n\n\ntemplate<typename DerivedV, typename DerivedF, typename DerivedO>\nIGL_INLINE void igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO>::\nlocalStep()\n{\n  for (int j =0; j<data.numF; ++j)\n  {\n\n    std::complex<typename DerivedV::Scalar> u(pvU(j,0),pvU(j,1));\n    std::complex<typename DerivedV::Scalar> v(pvV(j,0),pvV(j,1));\n\n    typename DerivedV::Scalar current_angle = computeAngle(u, v);\n    if (current_angle<thetaMin*M_PI/180)\n    {\n      // bring all to 1st or 4th quarter plane\n      if ((arg(u)>=0.5*M_PI || arg(u)<-0.5*M_PI ))\n        u = -u;\n      if ((arg(v)>=0.5*M_PI || arg(v)<-0.5*M_PI ))\n        v = -v;\n      assert(fabs(computeAngle(u, v) - current_angle)<1e-5);\n\n      if ( fabs(arg(u) - arg(v)) >0.5*M_PI )\n        v = -v;\n      assert(fabs(computeAngle(u, v) - current_angle)<1e-5);\n\n      std::complex<typename DerivedV::Scalar> u1, v1;\n      typename DerivedV::Scalar diff = thetaMin*M_PI/180 - current_angle + 1e-6;\n      rotateAroundBisector(u, v, diff, u1, v1);\n\n//      if (computeAngle(u1, v1)<thetaMin*M_PI/180)\n//      {\n//        std::cerr<<\"u = [\"<<real(u)<<\",\"<<imag(u)<< \"]; v= [\"<<real(v)<<\",\"<<imag(v)<<\"];\"<<std::endl;\n//        std::cerr<<\"u1 = [\"<<real(u1)<<\",\"<<imag(u1)<< \"]; v1= [\"<<real(v1)<<\",\"<<imag(v1)<<\"];\"<<std::endl;\n//        std::cerr<<\"current_angle = \"<<current_angle<<std::endl;\n//        std::cerr<<\"aout = \"<<computeAngle(u1, v1)<< \"; theta= \"<<thetaMin*M_PI/180<<\";\"<<std::endl;\n//      }\n//      assert(computeAngle(u1, v1)>=thetaMin*M_PI/180);\n\n\n      pvU.row(j) << real(u1),imag(u1);\n      pvV.row(j) << real(v1),imag(v1);\n    }\n  }\n\n}\n\n\n//\n//template<typename DerivedV, typename DerivedF, typename DerivedO>\n//IGL_INLINE void igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO>::\n//computeAngles(Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1> &angles)\n//{\n//  angles.resize(data.numF,1);\n//  for (int i =0; i<data.numF; ++i)\n//  {\n//    std::complex<typename DerivedV::Scalar> u(pvU(i,0),pvU(i,1));\n//    std::complex<typename DerivedV::Scalar> v(pvV(i,0),pvV(i,1));\n//    angles[i] = fabs(arg(u) - arg(v));\n//    if (angles[i]>M_PI)\n//      angles[i] = 2*M_PI-angles[i];\n//    if (angles[i]>.5*M_PI)\n//      angles[i] = M_PI-angles[i];\n//  }\n//}\n\ntemplate<typename DerivedV, typename DerivedF, typename DerivedO>\nIGL_INLINE typename DerivedV::Scalar igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO>::\ncomputeAngle(const std::complex<typename DerivedV::Scalar> &u,\n             const std::complex<typename DerivedV::Scalar> &v)\n{\n  typename DerivedV::Scalar angle = std::min(fabs(arg(u*conj(v))), fabs(arg(u*conj(-v))));\n\n//  typename DerivedV::Scalar angle;\n//  typename DerivedV::Scalar a1 = fabs(arg(u*conj(v)));\n//  typename DerivedV::Scalar a2 = fabs(arg(u*conj(-v)));\n//  if (a1 < a2)\n//    angle = a1;\n//  else\n//  {\n//    angle = a2; v = -v;\n//  }\n\n//  typename DerivedV::Scalar angle = fabs(arg(u) - arg(v));\n//  if (angle>M_PI)\n//  {\n//    u = -u;\n//    angle = fabs(arg(u) - arg(v));\n//  };\n//\n//  if (angle>.5*M_PI)\n//  {\n//    v = -v;\n//    angle = fabs(arg(u) - arg(v));\n//  };\n//\n//  assert(fabs(angle-angle1)<1e-6);\n\n//  if (angle>M_PI)\n//    angle = 2*M_PI-angle;\n//  if (angle>.5*M_PI)\n//    angle = M_PI-angle;\n\n//  typename DerivedV::Scalar angle = fabs(arg(u) - arg(v));\n//    if (angle>M_PI)\n//      angle = 2*M_PI-angle;\n//    if (angle>.5*M_PI)\n//      angle = M_PI-angle;\n\n  assert(angle <= .5*M_PI && angle >0);\n\n  return angle;\n}\n\n\ntemplate<typename DerivedV, typename DerivedF, typename DerivedO>\nIGL_INLINE int igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO>::\ngetNumOutOfBounds()\n{\n  Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1> angles;\n//  computeAngles(angles);\n  int numOoB = 0;\n  for (int i =0; i<data.numF; ++i)\n  {\n    std::complex<typename DerivedV::Scalar> u(pvU(i,0),pvU(i,1));\n    std::complex<typename DerivedV::Scalar> v(pvV(i,0),pvV(i,1));\n    typename DerivedV::Scalar angle = computeAngle(u,v);\n//    if (angles[i] <thetaMin*M_PI/180)\n    if (angle <thetaMin*M_PI/180)\n      numOoB ++;\n  }\n  return numOoB;\n}\n\ntemplate<typename DerivedV, typename DerivedF, typename DerivedO>\nIGL_INLINE void igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO>::\nsetCoefficientsFromField()\n{\n  for (int i = 0; i <data.numF; ++i)\n  {\n    std::complex<typename DerivedV::Scalar> u(pvU(i,0),pvU(i,1));\n    std::complex<typename DerivedV::Scalar> v(pvV(i,0),pvV(i,1));\n    Acoeff(i) = u*u+v*v;\n    Bcoeff(i) = u*u*v*v;\n  }\n}\n\n\ntemplate<typename DerivedV, typename DerivedF, typename DerivedO>\nIGL_INLINE void igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO>::\nglobalStep(const Eigen::Matrix<int, Eigen::Dynamic, 1>  &isConstrained,\n           const Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1>  &Ak,\n           const Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1>  &Bk)\n{\n  setCoefficientsFromField();\n\n  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > I;\n  igl::speye(data.numF, data.numF, I);\n  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > QA = data.DDA+lambda*I;\n  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > fA = (-2*lambda*Acoeff).sparseView();\n\n  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > QB = data.DDB+lambda*I;\n  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > fB = (-2*lambda*I*Bcoeff).sparseView();\n\n  if(doHardConstraints)\n  {\n    minQuadWithKnownMini(QA, fA, isConstrained, Ak, Acoeff);\n    minQuadWithKnownMini(QB, fB, isConstrained, Bk, Bcoeff);\n  }\n  else\n  {\n    Eigen::Matrix<int, Eigen::Dynamic, 1>isknown_; isknown_.setZero(data.numF,1);\n    Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> xknown_; xknown_.setZero(0,1);\n    minQuadWithKnownMini(QA, fA, isknown_, xknown_, Acoeff);\n    minQuadWithKnownMini(QB, fB, isknown_, xknown_, Bcoeff);\n  }\n  setFieldFromCoefficients();\n\n}\n\n\ntemplate<typename DerivedV, typename DerivedF, typename DerivedO>\nIGL_INLINE void igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO>::\nsetFieldFromCoefficients()\n{\n  for (int i = 0; i <data.numF; ++i)\n  {\n    //    poly coefficients: 1, 0, -Acoeff, 0, Bcoeff\n    //    matlab code from roots (given there are no trailing zeros in the polynomial coefficients)\n    Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> polyCoeff(5,1);\n    polyCoeff<<1., 0., -Acoeff(i), 0., Bcoeff(i);\n\n    Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> roots;\n    polyRoots<std::complex<typename DerivedV::Scalar>>(polyCoeff,roots);\n\n    std::complex<typename DerivedV::Scalar> u = roots[0];\n    int maxi = -1;\n    float maxd = -1;\n    for (int k =1; k<4; ++k)\n    {\n      float dist = abs(roots[k]+u);\n      if (dist>maxd)\n      {\n        maxd = dist;\n        maxi = k;\n      }\n    }\n    std::complex<typename DerivedV::Scalar> v = roots[maxi];\n    pvU(i,0) = real(u); pvU(i,1) = imag(u);\n    pvV(i,0) = real(v); pvV(i,1) = imag(v);\n  }\n\n}\n\ntemplate<typename DerivedV, typename DerivedF, typename DerivedO>\nIGL_INLINE void igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO>::\nminQuadWithKnownMini(const Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &Q,\n                     const Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &f,\n                     const Eigen::VectorXi isConstrained,\n                     const Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> &xknown,\n                     Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> &x)\n{\n  int N = Q.rows();\n\n  int nc = xknown.rows();\n  Eigen::VectorXi known; known.setZero(nc,1);\n  Eigen::VectorXi unknown; unknown.setZero(N-nc,1);\n\n  int indk = 0, indu = 0;\n  for (int i = 0; i<N; ++i)\n    if (isConstrained[i])\n    {\n      known[indk] = i;\n      indk++;\n    }\n    else\n    {\n      unknown[indu] = i;\n      indu++;\n    }\n\n  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar>> Quu, Quk;\n\n  igl::slice(Q,unknown, unknown, Quu);\n  igl::slice(Q,unknown, known, Quk);\n\n\n  std::vector<typename Eigen::Triplet<std::complex<typename DerivedV::Scalar> > > tripletList;\n\n  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > fu(N-nc,1);\n\n  igl::slice(f,unknown, Eigen::VectorXi::Zero(1,1), fu);\n\n  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > rhs = (Quk*xknown).sparseView()+.5*fu;\n\n  Eigen::SparseLU< Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar>>> solver;\n  solver.compute(-Quu);\n  if(solver.info()!=Eigen::Success)\n  {\n    std::cerr<<\"Decomposition failed!\"<<std::endl;\n    return;\n  }\n  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar>>  b  = solver.solve(rhs);\n  if(solver.info()!=Eigen::Success)\n  {\n    std::cerr<<\"Solving failed!\"<<std::endl;\n    return;\n  }\n\n  indk = 0, indu = 0;\n  x.setZero(N,1);\n  for (int i = 0; i<N; ++i)\n    if (isConstrained[i])\n      x[i] = xknown[indk++];\n    else\n      x[i] = b.coeff(indu++,0);\n\n}\n\n\ntemplate<typename DerivedV, typename DerivedF, typename DerivedO>\nIGL_INLINE bool igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO>::\nsolve(const Eigen::VectorXi &isConstrained,\n      const Eigen::PlainObjectBase<DerivedO> &initialSolution,\n      Eigen::PlainObjectBase<DerivedO> &output,\n      typename DerivedV::Scalar *lambdaOut)\n{\n  int numConstrained = isConstrained.sum();\n  // coefficient values\n  Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> Ak, Bk;\n\n  pvU.resize(data.numF,2);\n  pvV.resize(data.numF,2);\n  for (int fi = 0; fi <data.numF; ++fi)\n  {\n    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &b1 = data.B1.row(fi);\n    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &b2 = data.B2.row(fi);\n    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &u3 = initialSolution.block(fi,0,1,3);\n    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &v3 = initialSolution.block(fi,3,1,3);\n    pvU.row(fi)<< u3.dot(b1), u3.dot(b2);\n    pvV.row(fi)<< v3.dot(b1), v3.dot(b2);\n  }\n  setCoefficientsFromField();\n  Ak.resize(numConstrained,1);\n  Bk.resize(numConstrained,1);\n  int ind = 0;\n  for (int i = 0; i <data.numF; ++i)\n  {\n    if(isConstrained[i])\n    {\n      Ak(ind) = Acoeff[i];\n      Bk(ind) = Bcoeff[i];\n      ind ++;\n    }\n  }\n\n\n\n  typename DerivedV::Scalar smoothnessValue;\n  int oob;\n\n  smoothnessValue = (Acoeff.adjoint()*data.DDA*Acoeff + Bcoeff.adjoint()*data.DDB*Bcoeff).real()[0];\n  printf(\"\\n\\nInitial smoothness: %.5g\\n\",smoothnessValue);\n  oob = getNumOutOfBounds();\n  printf(\"\\n\\nInitial out-of-bounds: %d\\n\",oob);\n  printf(\" %d %.5g %d\\n\",-1, smoothnessValue, oob);\n\n  lambda = lambdaInit;\n  for (int iter = 0; iter<maxIter; ++iter)\n  {\n    printf(\"\\n\\n--- Iteration %d ---\\n\",iter);\n\n    localStep();\n    globalStep(isConstrained, Ak, Bk);\n\n\n    smoothnessValue = (Acoeff.adjoint()*data.DDA*Acoeff + Bcoeff.adjoint()*data.DDB*Bcoeff).real()[0];\n\n    printf(\"Smoothness: %.5g\\n\",smoothnessValue);\n\n    oob = getNumOutOfBounds();\n\n    bool stoppingCriterion = (oob == 0) ;\n    if (stoppingCriterion)\n      break;\n    lambda = lambda*lambdaMultFactor;\n//    printf(\" %d %.5g %d\\n\",iter, smoothnessValue, oob);\n\n  }\n\n  output.setZero(data.numF,6);\n  for (int fi=0; fi<data.numF; ++fi)\n  {\n    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &b1 = data.B1.row(fi);\n    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &b2 = data.B2.row(fi);\n    output.block(fi,0, 1, 3) = pvU(fi,0)*b1 + pvU(fi,1)*b2;\n    output.block(fi,3, 1, 3) = pvV(fi,0)*b1 + pvV(fi,1)*b2;\n  }\n\n  if (lambdaOut)\n    *lambdaOut = lambda;\n\n\n  return (oob==0);\n}\n\n\n\ntemplate <typename DerivedV, typename DerivedF, typename DerivedO>\nIGL_INLINE bool igl::angle_bound_frame_fields(const Eigen::PlainObjectBase<DerivedV> &V,\n                                            const Eigen::PlainObjectBase<DerivedF> &F,\n                                              const typename DerivedV::Scalar &thetaMin,\n                                            const Eigen::VectorXi &isConstrained,\n                                            const Eigen::PlainObjectBase<DerivedO> &initialSolution,\n                                            Eigen::PlainObjectBase<DerivedO> &output,\n                                            int maxIter,\n                                            const typename DerivedV::Scalar &lambdaInit,\n                                            const typename DerivedV::Scalar &lambdaMultFactor,\n                                              const bool doHardConstraints)\n{\n  igl::AngleBoundFFSolverData<DerivedV, DerivedF> csdata(V, F);\n  igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO> cs(csdata, thetaMin, maxIter, lambdaInit, lambdaMultFactor, doHardConstraints);\n  return (cs.solve(isConstrained, initialSolution, output));\n}\n\ntemplate <typename DerivedV, typename DerivedF, typename DerivedO>\nIGL_INLINE bool igl::angle_bound_frame_fields(const igl::AngleBoundFFSolverData<DerivedV, DerivedF> &csdata,\n                                              const typename DerivedV::Scalar &thetaMin,\n                                            const Eigen::VectorXi &isConstrained,\n                                            const Eigen::PlainObjectBase<DerivedO> &initialSolution,\n                                            Eigen::PlainObjectBase<DerivedO> &output,\n                                            int maxIter,\n                                            const typename DerivedV::Scalar &lambdaInit,\n                                            const typename DerivedV::Scalar &lambdaMultFactor,\n                                              const bool doHardConstraints,\n                                            typename DerivedV::Scalar *lambdaOut)\n{\n  igl::AngleBoundFFSolver<DerivedV, DerivedF, DerivedO> cs(csdata, thetaMin, maxIter, lambdaInit, lambdaMultFactor, doHardConstraints);\n  return (cs.solve(isConstrained, initialSolution, output, lambdaOut));\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\n#endif\n", "meta": {"hexsha": "a953be31ccc6940a148e4d06eb414a0ed8424f7e", "size": 26667, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/igl/angle_bound_frame_fields.cpp", "max_stars_repo_name": "rushmash/libwetcloth", "max_stars_repo_head_hexsha": "24f16481c68952c3d2a91acd6e3b74eb091b66bc", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": 199.0, "max_stars_repo_stars_event_min_datetime": "2018-02-26T20:56:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T06:09:52.000Z", "max_issues_repo_path": "include/igl/angle_bound_frame_fields.cpp", "max_issues_repo_name": "rushmash/libwetcloth", "max_issues_repo_head_hexsha": "24f16481c68952c3d2a91acd6e3b74eb091b66bc", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2018-03-20T02:49:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-29T01:13:22.000Z", "max_forks_repo_path": "include/igl/angle_bound_frame_fields.cpp", "max_forks_repo_name": "rushmash/libwetcloth", "max_forks_repo_head_hexsha": "24f16481c68952c3d2a91acd6e3b74eb091b66bc", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2018-02-28T01:33:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T16:06:19.000Z", "avg_line_length": 35.0881578947, "max_line_length": 135, "alphanum_fraction": 0.607042412, "num_tokens": 7436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.28286726234619575}}
{"text": "#include \"vtkTensorLines.h\"\n\n#include \"TensorLines.hh\"\n#include \"utils.hh\"\n\n#include <Eigen/Geometry>\n\n#include <vtkCellIterator.h>\n#include <vtkDataArray.h>\n#include <vtkDataSet.h>\n#include <vtkDataSetAttributes.h>\n#include <vtkDoubleArray.h>\n#include <vtkGenericCell.h>\n#include <vtkIdList.h>\n#include <vtkIntArray.h>\n#include <vtkUnsignedLongLongArray.h>\n#include <vtkPointData.h>\n#include <vtkCellData.h>\n#include <vtkPoints.h>\n#include <vtkPolyData.h>\n#include <vtkSmartPointer.h>\n#include <vtkUnstructuredGrid.h>\n\n#include <vtkCommand.h>\n#include <vtkInformation.h>\n#include <vtkInformationVector.h>\n#include <vtkObjectFactory.h>\n#include <vtkStreamingDemandDrivenPipeline.h>\n\n#include <algorithm>\n#include <array>\n#include <chrono>\n#include <iostream>\n#include <list>\n#include <map>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\nusing namespace cpp_utils;\n\nnamespace\n{\n// vtk Tensors are stored in row major order by convention\nusing Mat3d = Eigen::Matrix<double, 3, 3, Eigen::RowMajor, 3, 3>;\nusing Mat3dm = Eigen::Map<Mat3d>;\nusing Vec3d = tl::Vec3d;\nusing Vec3dm = Eigen::Map<Vec3d>;\n\nstruct TriFace\n{\n    std::array<vtkIdType, 3> points;\n    vtkIdType cellId;\n};\n\n\nstd::vector<TriFace> buildFaceList(vtkDataSet* dataset)\n{\n    auto face_list = std::vector<TriFace>{};\n    auto add_face = [&](vtkIdList* point_ids,\n                        vtkIdType cell_id,\n                        vtkIdType i1,\n                        vtkIdType i2,\n                        vtkIdType i3) {\n        auto tri = TriFace{{point_ids->GetId(i1),\n                            point_ids->GetId(i2),\n                            point_ids->GetId(i3)},\n                           cell_id};\n        face_list.push_back(tri);\n    };\n\n    // Collect faces and remember cell ID\n    auto it = vtkSmartPointer<vtkCellIterator>(dataset->NewCellIterator());\n    for(it->InitTraversal(); !it->IsDoneWithTraversal(); it->GoToNextCell())\n    {\n        if(it->GetCellType() != VTK_TETRA)\n        {\n            std::cout << \"WARNING: Dataset contains non-tet cells, which will \"\n                         \"be ignored.\\n\";\n            continue;\n        }\n\n        auto* point_ids = it->GetPointIds();\n        auto cid = it->GetCellId();\n\n        add_face(point_ids, cid, 0, 1, 2);\n        add_face(point_ids, cid, 1, 3, 2);\n        add_face(point_ids, cid, 0, 3, 1);\n        add_face(point_ids, cid, 0, 2, 3);\n    }\n    return face_list;\n}\n\n\nstd::array<vtkSmartPointer<vtkDoubleArray>, 3>\ncomputeCellDerivatives(vtkDataSet* dataset,\n                       const char* point_data_name)\n{\n    auto point_data = vtkSmartPointer<vtkDataArray>(\n            dataset->GetPointData()->GetArray(point_data_name));\n\n    auto ncomps = point_data->GetNumberOfComponents();\n\n    auto derivs = vtkSmartPointer<vtkDoubleArray>::New();\n    derivs->SetNumberOfComponents(ncomps*3);\n    derivs->SetNumberOfTuples(dataset->GetNumberOfCells());\n\n    auto it = vtkSmartPointer<vtkCellIterator>(dataset->NewCellIterator());\n    for(it->InitTraversal(); !it->IsDoneWithTraversal(); it->GoToNextCell())\n    {\n        // if(it->GetCellType() != VTK_TETRA)\n        // {\n        //     std::cout << \"WARNING: Dataset contains non-tet cells, which will \"\n        //                  \"be ignored.\\n\";\n        //     continue;\n        // }\n\n        auto* point_ids = it->GetPointIds();\n        auto npts = point_ids->GetNumberOfIds();\n        auto cid = it->GetCellId();\n\n        // copy point data to work array\n        auto pt_data =\n                std::vector<double>(as_unsigned(npts * ncomps));\n        for(auto i: range(npts))\n        {\n            point_data->GetTuple(point_ids->GetId(i), &pt_data[as_unsigned(i*ncomps)]);\n        }\n\n        auto cell = vtkSmartPointer<vtkGenericCell>::New();\n        it->GetCell(cell);\n        auto cell_center = std::array<double, 3>{};\n        cell->GetParametricCenter(cell_center.data());\n        auto deriv_data = std::vector<double>(as_unsigned(ncomps*3));\n        cell->Derivatives(0,\n                          cell_center.data(),\n                          pt_data.data(),\n                          ncomps,\n                          deriv_data.data());\n\n        derivs->SetTuple(cid, deriv_data.data());\n    }\n\n    auto dx = vtkSmartPointer<vtkDoubleArray>::New();\n    dx->SetNumberOfComponents(ncomps);\n    dx->SetNumberOfTuples(dataset->GetNumberOfCells());\n    for(auto i: range(ncomps))\n    {\n        dx->CopyComponent(i, derivs, i*3);\n    }\n\n    auto dy = vtkSmartPointer<vtkDoubleArray>::New();\n    dy->SetNumberOfComponents(ncomps);\n    dy->SetNumberOfTuples(dataset->GetNumberOfCells());\n    for(auto i: range(ncomps))\n    {\n        dy->CopyComponent(i, derivs, i*3+1);\n    }\n\n    auto dz = vtkSmartPointer<vtkDoubleArray>::New();\n    dz->SetNumberOfComponents(ncomps);\n    dz->SetNumberOfTuples(dataset->GetNumberOfCells());\n    for(auto i: range(ncomps))\n    {\n        dz->CopyComponent(i, derivs, i*3+2);\n    }\n    return {dx, dy, dz};\n}\n\n\nstd::vector<tl::TLResult> computePEVPoints(const std::vector<TriFace>& faces,\n                                             vtkPoints* points,\n                                             vtkDataArray* array1,\n                                             vtkDataArray* array2,\n                                             vtkAlgorithm* progress_alg,\n                                             const tl::TLOptions& opts)\n{\n    const auto step = 1. / double(faces.size());\n    progress_alg->UpdateProgress(0);\n    auto results = std::vector<tl::TLResult>(faces.size());\n    auto terminate = false;\n#pragma omp parallel for schedule(guided, 1)\n    for(auto i = std::size_t{0}; i < faces.size(); ++i)\n    {\n#pragma omp flush(terminate)\n        if(terminate) continue;\n\n        auto face = faces[i];\n\n        auto p1 = Vec3d{};\n        points->GetPoint(face.points[0], p1.data());\n        auto p2 = Vec3d{};\n        points->GetPoint(face.points[1], p2.data());\n        auto p3 = Vec3d{};\n        points->GetPoint(face.points[2], p3.data());\n\n        auto s1 = Mat3d{};\n        array1->GetTuple(face.points[0], s1.data());\n        auto s2 = Mat3d{};\n        array1->GetTuple(face.points[1], s2.data());\n        auto s3 = Mat3d{};\n        array1->GetTuple(face.points[2], s3.data());\n\n        auto t1 = Mat3d{};\n        array2->GetTuple(face.points[0], t1.data());\n        auto t2 = Mat3d{};\n        array2->GetTuple(face.points[1], t2.data());\n        auto t3 = Mat3d{};\n        array2->GetTuple(face.points[2], t3.data());\n\n        auto points = tl::findParallelEigenvectors(\n                {s1, s2, s3},\n                {t1, t2, t3},\n                {p1, p2, p3},\n                opts);\n        results[i] = points;\n#pragma omp critical(progress)\n        {\n            progress_alg->UpdateProgress(progress_alg->GetProgress() + step);\n            if(progress_alg->GetAbortExecute())\n            {\n                std::cout << \"Terminate request accepted\" << std::endl;\n                terminate = true;\n            }\n        }\n    }\n    return results;\n}\n\n\nstd::vector<tl::TLResult> computeTCLPoints(const std::vector<TriFace>& faces,\n                                             vtkPoints* points,\n                                             vtkDataArray* tensors,\n                                             vtkDataArray* tx,\n                                             vtkDataArray* ty,\n                                             vtkDataArray* tz,\n                                             vtkAlgorithm* progress_alg,\n                                             const tl::TLOptions& opts)\n{\n    const auto step = 1. / double(faces.size());\n    progress_alg->UpdateProgress(0);\n    auto results = std::vector<tl::TLResult>(faces.size());\n    auto terminate = false;\n#pragma omp parallel for\n    for(auto i = std::size_t{0}; i < faces.size(); ++i)\n    {\n#pragma omp flush(terminate)\n        if(terminate) continue;\n\n        auto face = faces[i];\n\n        auto p1 = Vec3d{};\n        points->GetPoint(face.points[0], p1.data());\n        auto p2 = Vec3d{};\n        points->GetPoint(face.points[1], p2.data());\n        auto p3 = Vec3d{};\n        points->GetPoint(face.points[2], p3.data());\n\n        auto s1 = Mat3d{};\n        tensors->GetTuple(face.points[0], s1.data());\n        auto s2 = Mat3d{};\n        tensors->GetTuple(face.points[1], s2.data());\n        auto s3 = Mat3d{};\n        tensors->GetTuple(face.points[2], s3.data());\n\n        auto sx = Mat3d{};\n        tx->GetTuple(face.cellId, sx.data());\n\n        auto sy = Mat3d{};\n        ty->GetTuple(face.cellId, sy.data());\n\n        auto sz = Mat3d{};\n        tz->GetTuple(face.cellId, sz.data());\n\n        auto points = tl::findTensorCoreLines(\n                {s1, s2, s3},\n                {sx, sy, sz},\n                {p1, p2, p3},\n                opts);\n        results[i] = points;\n#pragma omp critical(progress)\n        {\n            progress_alg->UpdateProgress(progress_alg->GetProgress() + step);\n            if(progress_alg->GetAbortExecute())\n            {\n                std::cout << \"Terminate request accepted\" << std::endl;\n                terminate = true;\n            }\n        }\n    }\n    return results;\n}\n\nstd::vector<tl::TLResult> computeTopoPoints(const std::vector<TriFace>& faces,\n                                            vtkPoints* points,\n                                            vtkDataArray* tensors,\n                                            vtkAlgorithm* progress_alg,\n                                            const tl::TLOptions& opts)\n{\n    const auto step = 1. / double(faces.size());\n    progress_alg->UpdateProgress(0);\n    auto results = std::vector<tl::TLResult>(faces.size());\n    auto terminate = false;\n#pragma omp parallel for\n    for(auto i = std::size_t{0}; i < faces.size(); ++i)\n    {\n#pragma omp flush(terminate)\n        if(terminate) continue;\n\n        auto face = faces[i];\n\n        auto p1 = Vec3d{};\n        points->GetPoint(face.points[0], p1.data());\n        auto p2 = Vec3d{};\n        points->GetPoint(face.points[1], p2.data());\n        auto p3 = Vec3d{};\n        points->GetPoint(face.points[2], p3.data());\n\n        auto s1 = Mat3d{};\n        tensors->GetTuple(face.points[0], s1.data());\n        auto s2 = Mat3d{};\n        tensors->GetTuple(face.points[1], s2.data());\n        auto s3 = Mat3d{};\n        tensors->GetTuple(face.points[2], s3.data());\n\n        auto points = tl::findTensorTopology(\n                {s1, s2, s3},\n                {p1, p2, p3},\n                opts);\n        results[i] = points;\n#pragma omp critical(progress)\n        {\n            progress_alg->UpdateProgress(progress_alg->GetProgress() + step);\n            if(progress_alg->GetAbortExecute())\n            {\n                std::cout << \"Terminate request accepted\" << std::endl;\n                terminate = true;\n            }\n        }\n    }\n    return results;\n}\n}\n\n\nvtkStandardNewMacro(vtkTensorLines)\n\n\nvtkTensorLines::vtkTensorLines()\n{\n    this->SetNumberOfInputPorts(1);\n    this->SetNumberOfOutputPorts(1);\n    this->SetInputArrayToProcess(0,\n                                 0,\n                                 0,\n                                 vtkDataObject::FIELD_ASSOCIATION_POINTS,\n                                 vtkDataSetAttributes::TENSORS);\n    this->SetInputArrayToProcess(1,\n                                 0,\n                                 0,\n                                 vtkDataObject::FIELD_ASSOCIATION_POINTS,\n                                 vtkDataSetAttributes::TENSORS);\n}\n\n\nvtkPolyData* vtkTensorLines::GetOutput()\n{\n    return this->GetOutput(0);\n}\n\n\nvtkPolyData* vtkTensorLines::GetOutput(int port)\n{\n    return vtkPolyData::SafeDownCast(this->GetOutputDataObject(port));\n}\n\n\nint vtkTensorLines::ProcessRequest(vtkInformation* request,\n                                   vtkInformationVector** inputVector,\n                                   vtkInformationVector* outputVector)\n{\n    // Create an output object of the correct type.\n    if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA_OBJECT()))\n    {\n        return this->RequestDataObject(request, inputVector, outputVector);\n    }\n    // generate the data\n    if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA()))\n    {\n        return this->RequestData(request, inputVector, outputVector);\n    }\n\n    if(request->Has(vtkStreamingDemandDrivenPipeline::REQUEST_UPDATE_EXTENT()))\n    {\n        return this->RequestUpdateExtent(request, inputVector, outputVector);\n    }\n\n    // execute information\n    if(request->Has(vtkDemandDrivenPipeline::REQUEST_INFORMATION()))\n    {\n        return this->RequestInformation(request, inputVector, outputVector);\n    }\n\n    return this->Superclass::ProcessRequest(request, inputVector, outputVector);\n}\n\n\nint vtkTensorLines::FillOutputPortInformation(int port,\n                                              vtkInformation* info)\n{\n    // now add our info\n    if(port == 0)\n    {\n        info->Set(vtkDataObject::DATA_TYPE_NAME(), \"vtkPolyData\");\n    }\n    // else if(port == 1)\n    // {\n    //     info->Set(vtkDataObject::DATA_TYPE_NAME(), \"vtkPolyData\");\n    // }\n    return 1;\n}\n\n\nint vtkTensorLines::FillInputPortInformation(int vtkNotUsed(port),\n                                             vtkInformation* info)\n{\n    info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkUnstructuredGrid\");\n    return 1;\n}\n\n\nint vtkTensorLines::RequestDataObject(\n        vtkInformation* vtkNotUsed(request),\n        vtkInformationVector** vtkNotUsed(inputVector),\n        vtkInformationVector* outputVector)\n{\n    // RequestDataObject (RDO) is an earlier pipeline pass. During RDO, each\n    // filter is supposed to produce an empty data object of the proper type\n\n    auto* outInfo = outputVector->GetInformationObject(0);\n    auto* output = vtkPolyData::SafeDownCast(\n            outInfo->Get(vtkDataObject::DATA_OBJECT()));\n    // auto* outInfo2 = outputVector->GetInformationObject(1);\n    // auto* output2 = vtkPolyData::SafeDownCast(\n    //         outInfo2->Get(vtkDataObject::DATA_OBJECT()));\n\n    if(!output)\n    {\n        output = vtkPolyData::New();\n        outInfo->Set(vtkDataObject::DATA_OBJECT(), output);\n        output->FastDelete();\n\n        this->GetOutputPortInformation(0)->Set(\n                vtkDataObject::DATA_EXTENT_TYPE(), output->GetExtentType());\n    }\n    // if(!output2)\n    // {\n    //     output2 = vtkPolyData::New();\n    //     outInfo2->Set(vtkDataObject::DATA_OBJECT(), output2);\n    //     output2->FastDelete();\n\n    //     this->GetOutputPortInformation(1)->Set(\n    //             vtkDataObject::DATA_EXTENT_TYPE(), output2->GetExtentType());\n    // }\n\n\n    return 1;\n}\n\n\nint vtkTensorLines::RequestInformation(\n        vtkInformation* vtkNotUsed(request),\n        vtkInformationVector** vtkNotUsed(inputVector),\n        vtkInformationVector* vtkNotUsed(outputVector))\n{\n    return 1;\n}\n\n\nint vtkTensorLines::RequestUpdateExtent(\n        vtkInformation* vtkNotUsed(request),\n        vtkInformationVector** inputVector,\n        vtkInformationVector* vtkNotUsed(outputVector))\n{\n    auto numInputPorts = this->GetNumberOfInputPorts();\n    for(auto i = 0; i < numInputPorts; i++)\n    {\n        auto numInputConnections = this->GetNumberOfInputConnections(i);\n        for(auto j = 0; j < numInputConnections; j++)\n        {\n            auto* inputInfo = inputVector[i]->GetInformationObject(j);\n            inputInfo->Set(vtkStreamingDemandDrivenPipeline::EXACT_EXTENT(), 1);\n        }\n    }\n    return 1;\n}\n\n\nint vtkTensorLines::RequestData(vtkInformation* vtkNotUsed(request),\n                                         vtkInformationVector** inputVector,\n                                         vtkInformationVector* outputVector)\n{\n    using namespace std::chrono;\n    using minutes = duration<double, std::chrono::minutes::period>;\n    using seconds = duration<double, std::chrono::seconds::period>;\n    using milliseconds = duration<double, std::chrono::milliseconds::period>;\n\n    auto* outInfo = outputVector->GetInformationObject(0);\n    auto* output = vtkPolyData::SafeDownCast(\n            outInfo->Get(vtkDataObject::DATA_OBJECT()));\n\n    // auto* outInfo2 = outputVector->GetInformationObject(1);\n    // auto* output2 = vtkPolyData::SafeDownCast(\n    //         outInfo2->Get(vtkDataObject::DATA_OBJECT()));\n\n    auto* inInfo = inputVector[0]->GetInformationObject(0);\n    auto* input = vtkUnstructuredGrid::SafeDownCast(\n            inInfo->Get(vtkDataObject::DATA_OBJECT()));\n\n    // Get the two DataArrays corresponding to the tensor data\n    auto* array1 = this->GetInputArrayToProcess(0, inputVector);\n    auto* array2 = this->GetInputArrayToProcess(1, inputVector);\n\n    if(!array1 ||\n       (_line_type == LineType::ParallelEigenvectors && !array2))\n    {\n        vtkErrorMacro(<< \"Not all input arrays could be found (Maybe you \"\n                         \"specified the wrong name?).\");\n        return 0;\n    }\n\n    // Check if the data arrays have the correct number of components\n    if(array1->GetNumberOfComponents() != 9\n       || (_line_type == LineType::ParallelEigenvectors\n           && array2->GetNumberOfComponents() != 9))\n    {\n        vtkErrorMacro(<< \"All input arrays must be tensors with 9 components.\");\n        return 0;\n    }\n\n    if(this->GetInputArrayInformation(0)->Get(\n               vtkDataObject::FIELD_ASSOCIATION())\n               != vtkDataObject::FIELD_ASSOCIATION_POINTS\n       || (_line_type == LineType::ParallelEigenvectors\n           && this->GetInputArrayInformation(1)->Get(\n                      vtkDataObject::FIELD_ASSOCIATION())\n                      != vtkDataObject::FIELD_ASSOCIATION_POINTS))\n    {\n        vtkErrorMacro(<< \"All input arrays must be point data.\");\n        return 0;\n    }\n\n    // Point and CellArrays for output dataset\n    output->SetPoints(vtkPoints::New());\n    output->SetVerts(vtkCellArray::New());\n    output->SetPolys(vtkCellArray::New());\n\n    // Output arrays for point information\n    auto eig_rank1 = vtkSmartPointer<vtkDoubleArray>::New();\n    eig_rank1->SetName(\"Rank1\");\n    output->GetPointData()->AddArray(eig_rank1);\n    auto eig_rank2 = vtkSmartPointer<vtkDoubleArray>::New();\n    eig_rank2->SetName(\"Rank2\");\n    output->GetPointData()->AddArray(eig_rank2);\n    auto eival1 = vtkSmartPointer<vtkDoubleArray>::New();\n    eival1->SetName(\"Eigenvalue 1\");\n    output->GetPointData()->AddArray(eival1);\n    auto eival2 = vtkSmartPointer<vtkDoubleArray>::New();\n    eival2->SetName(\"Eigenvalue 2\");\n    output->GetPointData()->AddArray(eival2);\n    auto eivec = vtkSmartPointer<vtkDoubleArray>::New();\n    eivec->SetName(\"Eigenvector\");\n    eivec->SetNumberOfComponents(3);\n    output->GetPointData()->SetVectors(eivec);\n    auto imag1 = vtkSmartPointer<vtkDoubleArray>::New();\n    imag1->SetName(\"Imaginary 1\");\n    output->GetPointData()->AddArray(imag1);\n    auto imag2 = vtkSmartPointer<vtkDoubleArray>::New();\n    imag2->SetName(\"Imaginary 2\");\n    output->GetPointData()->AddArray(imag2);\n    auto csize = vtkSmartPointer<vtkUnsignedLongLongArray>::New();\n    csize->SetName(\"Cluster Size\");\n    output->GetPointData()->AddArray(csize);\n    auto pos_unc = vtkSmartPointer<vtkDoubleArray>::New();\n    pos_unc->SetName(\"Position Uncertainty\");\n    output->GetPointData()->AddArray(pos_unc);\n    auto dir_unc = vtkSmartPointer<vtkDoubleArray>::New();\n    dir_unc->SetName(\"Direction Uncertainty\");\n    output->GetPointData()->AddArray(dir_unc);\n    auto stability = vtkSmartPointer<vtkDoubleArray>::New();\n    stability->SetName(\"Line Stability\");\n    output->GetPointData()->AddArray(stability);\n\n    // // List of faces that might have non-line structures in separate output\n    // output2->SetPoints(vtkPoints::New());\n    // output2->GetPoints()->DeepCopy(input->GetPoints());\n    // output2->Allocate();\n\n    // auto direction = vtkSmartPointer<vtkDoubleArray>::New();\n    // direction->SetNumberOfComponents(3);\n    // direction->SetName(\"Direction\");\n    // output2->GetCellData()->AddArray(direction);\n\n    // Copy faces to array for parallel looping\n    auto faces = buildFaceList(input);\n    auto start = high_resolution_clock::now();\n\n    auto opts = tl::TLOptions{this->GetTolerance(),\n                                this->GetClusterEpsilon(),\n                                this->GetMaxCandidates()};\n\n    auto fresults = std::vector<tl::TLResult>{};\n\n    if(_line_type == LineType::TensorCoreLines)\n    {\n        auto derivs = computeCellDerivatives(input, array1->GetName());\n        fresults = computeTCLPoints(faces,\n                                   input->GetPoints(),\n                                   array1,\n                                   derivs[0],\n                                   derivs[1],\n                                   derivs[2],\n                                   this,\n                                   opts);\n    }\n    else if(_line_type == LineType::ParallelEigenvectors)\n    {\n        fresults = computePEVPoints(\n                faces, input->GetPoints(), array1, array2, this, opts);\n    }\n    else if(_line_type == LineType::TensorTopology)\n    {\n        fresults = computeTopoPoints(\n                faces, input->GetPoints(), array1, this, opts);\n    }\n\n    auto end_pointsearch = high_resolution_clock::now();\n\n    // map cell IDs to parallel eigenvector points found on their faces\n    auto cell_map = std::map<vtkIdType, vtkSmartPointer<vtkIdList>>{};\n\n    for(auto i : range(faces.size()))\n    {\n        auto pev_points = fresults[i];\n        auto cid = faces[i].cellId;\n        for(const auto& p : pev_points.points)\n        {\n            auto pid = output->GetPoints()->InsertNextPoint(p.pos.data());\n            eig_rank1->InsertValue(pid, double(p.s_rank));\n            eig_rank2->InsertValue(pid, double(p.t_rank));\n            eival1->InsertValue(pid, p.s_eival);\n            eival2->InsertValue(pid, p.t_eival);\n            eivec->InsertTuple(pid, p.eivec.data());\n            imag1->InsertValue(pid, p.s_has_imaginary ? 1. : 0.);\n            imag2->InsertValue(pid, p.t_has_imaginary ? 1. : 0.);\n            csize->InsertValue(pid, p.cluster_size);\n            pos_unc->InsertValue(pid, p.pos_uncertainty);\n            dir_unc->InsertValue(pid, p.dir_uncertainty);\n            stability->InsertValue(pid, p.line_stability);\n\n            if(!cell_map[cid].Get())\n            {\n                cell_map[cid] = vtkSmartPointer<vtkIdList>::New();\n            }\n            cell_map[cid]->InsertNextId(pid);\n        }\n    }\n\n    output->SetLines(vtkCellArray::New());\n\n    auto cell_points = vtkSmartPointer<vtkIdList>::New();\n\n    for(const auto& c : cell_map)\n    {\n        auto point_list = c.second;\n        auto npoints = point_list->GetNumberOfIds();\n        // For cells with exactly two parallel eigenvector points, connect them\n        // with a line\n        if(npoints == 2)\n        {\n            output->InsertNextCell(VTK_LINE, point_list);\n        }\n        else\n        {\n            // Match points by eigenvector direction\n\n            using Matrix3X = Eigen::Matrix3Xd;\n            using MatrixX = Eigen::MatrixXd;\n\n            // Get eigenvectors of cell points\n            auto eigdirs = Matrix3X(3, npoints).eval();\n            for(auto i : range(npoints))\n            {\n                eigdirs.col(i) = Vec3dm{eivec->GetTuple(point_list->GetId(i))};\n            }\n\n            // Compute pairwise vector deviations\n            auto dist = MatrixX::Ones(npoints, npoints).eval();\n            for(auto i : range(npoints))\n            {\n                for(auto j : range(i + 1, npoints))\n                {\n                    dist(i, j) =\n                            eigdirs.col(i).cross(eigdirs.col(j)).squaredNorm();\n                }\n            }\n\n            // Greedily find closest two vectors and connect\n            auto unlinked = std::unordered_set<vtkIdType>{};\n            for(auto i : range(npoints))\n            {\n                unlinked.insert(i);\n            }\n            if(npoints < 10)\n            {\n                while(dist.sum() < double(npoints * npoints))\n                {\n                    auto row = Matrix3X::Index{};\n                    auto col = Matrix3X::Index{};\n                    dist.minCoeff(&row, &col);\n                    auto line = vtkSmartPointer<vtkIdList>::New();\n                    line->SetNumberOfIds(2);\n                    line->InsertId(0, point_list->GetId(row));\n                    line->InsertId(1, point_list->GetId(col));\n                    output->InsertNextCell(VTK_LINE, line);\n                    dist.col(col).setOnes();\n                    dist.col(row).setOnes();\n                    dist.row(col).setOnes();\n                    dist.row(row).setOnes();\n                    unlinked.erase(row);\n                    unlinked.erase(col);\n                }\n            }\n\n            // Add vertex for last unlinked point if any\n            for(auto i : unlinked)\n            {\n                output->InsertNextCell(\n                        VTK_VERTEX, 1, point_list->GetPointer(i));\n            }\n        }\n    }\n\n    // for(auto i : range(faces.size()))\n    // {\n    //     auto failed_dirs = fresults[i].non_line_dirs;\n    //     auto cellpts = vtkSmartPointer<vtkIdList>::New();\n    //     cellpts->SetNumberOfIds(3);\n    //     cellpts->InsertId(0, faces[i].points[0]);\n    //     cellpts->InsertId(1, faces[i].points[1]);\n    //     cellpts->InsertId(2, faces[i].points[2]);\n    //     for(const auto& f: failed_dirs)\n    //     {\n    //         auto cid = output2->InsertNextCell(VTK_TRIANGLE, cellpts);\n    //         direction->InsertTuple(cid, f.data());\n    //     }\n    // }\n\n    auto end_all = high_resolution_clock::now();\n    auto duration_all = seconds(end_all - start);\n    auto duration_pointsearch = seconds(end_pointsearch - start);\n\n    std::cout << \"Processed dataset in \" << minutes(duration_all).count()\n              << \" minutes\" << std::endl;\n    std::cout << \"Point search time: \" << minutes(duration_pointsearch).count()\n              << \" minutes\" << std::endl;\n    std::cout << \"Postprocessing time: \"\n              << seconds(duration_all - duration_pointsearch).count()\n              << \" seconds\" << std::endl;\n    std::cout << \"Number of faces processed: \" << faces.size() << std::endl;\n    std::cout << \"Average time per face: \"\n              << (milliseconds(duration_pointsearch) / faces.size()).count()\n              << \" milliseconds\" << std::endl;\n\n    this->UpdateProgress(1.);\n\n    return 1;\n}\n", "meta": {"hexsha": "601d6cbc27fda46fa328d26a8e2714ea3a9789f5", "size": 26433, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/src/vtkTensorLines.cc", "max_stars_repo_name": "timo-oster/tensor-lines", "max_stars_repo_head_hexsha": "b4f489452f3ce5b5f48042cc035e53d3fdaa675e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/src/vtkTensorLines.cc", "max_issues_repo_name": "timo-oster/tensor-lines", "max_issues_repo_head_hexsha": "b4f489452f3ce5b5f48042cc035e53d3fdaa675e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/src/vtkTensorLines.cc", "max_forks_repo_name": "timo-oster/tensor-lines", "max_forks_repo_head_hexsha": "b4f489452f3ce5b5f48042cc035e53d3fdaa675e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-13T00:08:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-13T00:08:09.000Z", "avg_line_length": 33.9319640565, "max_line_length": 87, "alphanum_fraction": 0.5683426021, "num_tokens": 6212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.282675944149171}}
{"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// Purpose:  Implementation of the krovak (Krovak) projection.\r\n//           Definition: http://www.ihsenergy.com/epsg/guid7.html#1.4.3\r\n// Author:   Thomas Flemming, tf@ttqv.com\r\n// Copyright (c) 2001, Thomas Flemming, tf@ttqv.com\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_KROVAK_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_KROVAK_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\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace srs { namespace par4\r\n{\r\n    struct krovak {}; // Krovak\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 krovak\r\n    {\r\n            static double epsilon = 1e-15;\r\n            static double S45 = 0.785398163397448;  /* 45 deg */\r\n            static double S90 = 1.570796326794896;  /* 90 deg */\r\n            static double UQ  = 1.04216856380474;   /* DU(2, 59, 42, 42.69689) */\r\n            static double S0  = 1.37008346281555;   /* Latitude of pseudo standard parallel 78deg 30'00\" N */\r\n            /* Not sure at all of the appropriate number for max_iter... */\r\n            static int max_iter = 100;\r\n\r\n            template <typename T>\r\n            struct par_krovak\r\n            {\r\n                T alpha;\r\n                T k;\r\n                T n;\r\n                T rho0;\r\n                T ad;\r\n                int czech;\r\n            };\r\n\r\n            /**\r\n               NOTES: According to EPSG the full Krovak projection method should have\r\n                      the following parameters.  Within PROJ.4 the azimuth, and pseudo\r\n                      standard parallel are hardcoded in the algorithm and can't be\r\n                      altered from outside.  The others all have defaults to match the\r\n                      common usage with Krovak projection.\r\n\r\n              lat_0 = latitude of centre of the projection\r\n\r\n              lon_0 = longitude of centre of the projection\r\n\r\n              ** = azimuth (true) of the centre line passing through the centre of the projection\r\n\r\n              ** = latitude of pseudo standard parallel\r\n\r\n              k  = scale factor on the pseudo standard parallel\r\n\r\n              x_0 = False Easting of the centre of the projection at the apex of the cone\r\n\r\n              y_0 = False Northing of the centre of the projection at the apex of the cone\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_krovak_ellipsoid\r\n                : public base_t_fi<base_krovak_ellipsoid<T, Parameters>, T, Parameters>\r\n            {\r\n                par_krovak<T> m_proj_parm;\r\n\r\n                inline base_krovak_ellipsoid(const Parameters& par)\r\n                    : base_t_fi<base_krovak_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 gfi, u, deltav, s, d, eps, rho;\r\n\r\n                    gfi = math::pow( (T(1) + this->m_par.e * sin(lp_lat)) / (T(1) - this->m_par.e * sin(lp_lat)), this->m_proj_parm.alpha * this->m_par.e / T(2));\r\n\r\n                    u = 2. * (atan(this->m_proj_parm.k * math::pow( tan(lp_lat / T(2) + S45), this->m_proj_parm.alpha) / gfi)-S45);\r\n                    deltav = -lp_lon * this->m_proj_parm.alpha;\r\n\r\n                    s = asin(cos(this->m_proj_parm.ad) * sin(u) + sin(this->m_proj_parm.ad) * cos(u) * cos(deltav));\r\n                    d = asin(cos(u) * sin(deltav) / cos(s));\r\n\r\n                    eps = this->m_proj_parm.n * d;\r\n                    rho = this->m_proj_parm.rho0 * math::pow(tan(S0 / T(2) + S45) , this->m_proj_parm.n) / math::pow(tan(s / T(2) + S45) , this->m_proj_parm.n);\r\n\r\n                    xy_y = rho * cos(eps);\r\n                    xy_x = rho * sin(eps);\r\n\r\n                    xy_y *= this->m_proj_parm.czech;\r\n                    xy_x *= this->m_proj_parm.czech;\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                    T u, deltav, s, d, eps, rho, fi1, xy0;\r\n                    int i;\r\n\r\n                    // TODO: replace with std::swap()\r\n                    xy0 = xy_x;\r\n                    xy_x = xy_y;\r\n                    xy_y = xy0;\r\n\r\n                    xy_x *= this->m_proj_parm.czech;\r\n                    xy_y *= this->m_proj_parm.czech;\r\n\r\n                    rho = sqrt(xy_x * xy_x + xy_y * xy_y);\r\n                    eps = atan2(xy_y, xy_x);\r\n\r\n                    d = eps / sin(S0);\r\n                    s = T(2) * (atan(math::pow(this->m_proj_parm.rho0 / rho, T(1) / this->m_proj_parm.n) * tan(S0 / T(2) + S45)) - S45);\r\n\r\n                    u = asin(cos(this->m_proj_parm.ad) * sin(s) - sin(this->m_proj_parm.ad) * cos(s) * cos(d));\r\n                    deltav = asin(cos(s) * sin(d) / cos(u));\r\n\r\n                    lp_lon = this->m_par.lam0 - deltav / this->m_proj_parm.alpha;\r\n\r\n                    /* ITERATION FOR lp_lat */\r\n                    fi1 = u;\r\n\r\n                    for (i = max_iter; i ; --i) {\r\n                        lp_lat = T(2) * ( atan( math::pow( this->m_proj_parm.k, T(-1) / this->m_proj_parm.alpha)  *\r\n                                              math::pow( tan(u / T(2) + S45) , T(1) / this->m_proj_parm.alpha)  *\r\n                                              math::pow( (T(1) + this->m_par.e * sin(fi1)) / (T(1) - this->m_par.e * sin(fi1)) , this->m_par.e / T(2))\r\n                                            )  - S45);\r\n\r\n                        if (fabs(fi1 - lp_lat) < epsilon)\r\n                            break;\r\n                        fi1 = lp_lat;\r\n                    }\r\n                    if( i == 0 )\r\n                        BOOST_THROW_EXCEPTION( projection_exception(error_non_convergent) );\r\n\r\n                   lp_lon -= this->m_par.lam0;\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"krovak_ellipsoid\";\r\n                }\r\n\r\n            };\r\n\r\n            // Krovak\r\n            template <typename Parameters, typename T>\r\n            inline void setup_krovak(Parameters& par, par_krovak<T>& proj_parm)\r\n            {\r\n                T u0, n0, g;\r\n\r\n                /* we want Bessel as fixed ellipsoid */\r\n                par.a = 6377397.155;\r\n                par.e = sqrt(par.es = 0.006674372230614);\r\n\r\n                /* if latitude of projection center is not set, use 49d30'N */\r\n                if (!pj_param_exists(par.params, \"lat_0\"))\r\n                    par.phi0 = 0.863937979737193;\r\n\r\n                /* if center long is not set use 42d30'E of Ferro - 17d40' for Ferro */\r\n                /* that will correspond to using longitudes relative to greenwich    */\r\n                /* as input and output, instead of lat/long relative to Ferro */\r\n                if (!pj_param_exists(par.params, \"lon_0\"))\r\n                    par.lam0 = 0.7417649320975901 - 0.308341501185665;\r\n\r\n                /* if scale not set default to 0.9999 */\r\n                if (!pj_param_exists(par.params, \"k\"))\r\n                    par.k0 = 0.9999;\r\n\r\n                proj_parm.czech = 1;\r\n                if( !pj_param_exists(par.params, \"czech\") )\r\n                    proj_parm.czech = -1;\r\n\r\n                /* Set up shared parameters between forward and inverse */\r\n                proj_parm.alpha = sqrt(T(1) + (par.es * math::pow(cos(par.phi0), 4)) / (T(1) - par.es));\r\n                u0 = asin(sin(par.phi0) / proj_parm.alpha);\r\n                g = math::pow( (T(1) + par.e * sin(par.phi0)) / (T(1) - par.e * sin(par.phi0)) , proj_parm.alpha * par.e / T(2) );\r\n                proj_parm.k = tan( u0 / 2. + S45) / math::pow(tan(par.phi0 / T(2) + S45) , proj_parm.alpha) * g;\r\n                n0 = sqrt(T(1) - par.es) / (T(1) - par.es * math::pow(sin(par.phi0), 2));\r\n                proj_parm.n = sin(S0);\r\n                proj_parm.rho0 = par.k0 * n0 / tan(S0);\r\n                proj_parm.ad = S90 - UQ;\r\n            }\r\n\r\n    }} // namespace detail::krovak\r\n    #endif // doxygen\r\n\r\n    /*!\r\n        \\brief Krovak 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         - Pseudocylindrical\r\n         - Ellipsoid\r\n        \\par Projection parameters\r\n         - lat_ts: Latitude of true scale (degrees)\r\n         - lat_0: Latitude of origin\r\n         - lon_0: Central meridian\r\n         - k: Scale factor on the pseudo standard parallel\r\n        \\par Example\r\n        \\image html ex_krovak.gif\r\n    */\r\n    template <typename T, typename Parameters>\r\n    struct krovak_ellipsoid : public detail::krovak::base_krovak_ellipsoid<T, Parameters>\r\n    {\r\n        inline krovak_ellipsoid(const Parameters& par) : detail::krovak::base_krovak_ellipsoid<T, Parameters>(par)\r\n        {\r\n            detail::krovak::setup_krovak(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::krovak, krovak_ellipsoid, krovak_ellipsoid)\r\n\r\n        // Factory entry(s)\r\n        template <typename T, typename Parameters>\r\n        class krovak_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                    return new base_v_fi<krovak_ellipsoid<T, Parameters>, T, Parameters>(par);\r\n                }\r\n        };\r\n\r\n        template <typename T, typename Parameters>\r\n        inline void krovak_init(detail::base_factory<T, Parameters>& factory)\r\n        {\r\n            factory.add_to_factory(\"krovak\", new krovak_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_KROVAK_HPP\r\n\r\n", "meta": {"hexsha": "cb3d8f24abb64aece3368a75100f9eaf908ed59e", "size": 12529, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/srs/projections/proj/krovak.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/krovak.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/krovak.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": 42.1851851852, "max_line_length": 163, "alphanum_fraction": 0.548966398, "num_tokens": 3040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2826050157200421}}
{"text": "#include <iostream>\n#include \"source/tessellation/geometry.hpp\"\n#include \"source/tessellation/Delaunay.hpp\"\n#include \"source/misc/simple_io.hpp\"\n#include \"source/newtonian/two_dimensional/geometric_outer_boundaries/SquareBox.hpp\"\n#include \"source/misc/mesh_generator.hpp\"\n#ifdef RICH_MPI\n#include <boost/mpi/environment.hpp>\n#include <boost/mpi/communicator.hpp>\n#endif // RICH_MPI\n#include \"source/newtonian/two_dimensional/hdf5_diagnostics.hpp\"\n#include <boost/foreach.hpp>\n#include \"source/tessellation/VoronoiMesh.hpp\"\n\nusing namespace std;\n\n#ifdef RICH_MPI\nvector<Vector2D> delineate_rectangle\n(const pair<Vector2D,Vector2D>& boundary)\n{\n  vector<Vector2D> res(4);\n  res.at(0) = boundary.first;\n  res.at(1) = Vector2D(boundary.second.x,boundary.first.y);\n  res.at(2) = boundary.second;\n  res.at(3) = Vector2D(boundary.first.x,boundary.second.y);\n  return res;\n}\n\nvector<Vector2D> my_convex_hull\n(const Tessellation& tess,\n int index)\n{\n  vector<Vector2D> res;\n  ConvexHull(res,tess,index);\n  return res;\n}\n\nvector<Vector2D> distribute_grid\n(const vector<Vector2D>& complete_grid,\n const Tessellation& proc_tess)\n{\n  const boost::mpi::communicator world;\n  vector<Vector2D> res;\n  const vector<Vector2D> ch_list =\n    my_convex_hull(proc_tess,world.rank());\n  BOOST_FOREACH(const Vector2D& v, complete_grid)\n    {\n      if(PointInCell(ch_list,v))\n\tres.push_back(v);\n    }\n  return res;\n}\n#endif // RICH_MPI\n\nint main(void)\n{\n#ifdef RICH_MPI\n\n  boost::mpi::environment env;\n  boost::mpi::communicator world;\n  \n  try{\n\n  const SquareBox obc\n    (Vector2D(0,0),\n     Vector2D(1,1));\n  const vector<Vector2D> all_points = \n    RandSquare(1000,\n\t       obc.getBoundary().first.x,\n\t       obc.getBoundary().second.x,\n\t       obc.getBoundary().first.y,\n\t       obc.getBoundary().second.y);\n  if(world.rank()==0){\n    Delaunay tri;\n    tri.build_delaunay\n      (all_points, \n       delineate_rectangle\n       (obc.getBoundary()));\n    tri.BuildBoundary(&obc, obc.GetBoxEdges());\n    WriteDelaunay(tri,string(\"whole.h5\"));\n  }\n  VoronoiMesh super\n    (RandSquare(world.size(),\n\t\tobc.getBoundary().first.x,\n\t\tobc.getBoundary().second.x,\n\t\tobc.getBoundary().first.y,\n\t\tobc.getBoundary().second.y),\n     obc);\n  const vector<Vector2D> local_points =\n    distribute_grid\n    (all_points,\n     super);\n  Delaunay tri;\n  tri.build_delaunay\n    (local_points,\n     delineate_rectangle\n     (obc.getBoundary()));\n  vector<vector<int> > dummy_1;\n  //vector<int> dummy_2;\n  tri.BuildBoundary\n    (&obc,\n     super,\n     dummy_1);\n  WriteDelaunay(tri,string(\"part_\"+int2str(world.rank())+\".h5\"));\n  }\n  catch(const UniversalError& eo){\n    cout << eo.GetErrorMessage() << endl;\n    throw;\n  }\n#else\n\n  write_number(0,\"serial_ignore.txt\");\n\n#endif // RICH_MPI\n  return 0;\n}\n", "meta": {"hexsha": "0729c784e3b434b435044c1a600b6f118667d1d9", "size": 2758, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/tests/tessellation/parallel_delaunay/test.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/tests/tessellation/parallel_delaunay/test.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/tests/tessellation/parallel_delaunay/test.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": 23.5726495726, "max_line_length": 84, "alphanum_fraction": 0.6983321247, "num_tokens": 782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2825035625210455}}
{"text": "/**\n *  Copyright (C) 2012  \n *    Ekaterina Potapova\n *    Automation and Control Institute\n *    Vienna University of Technology\n *    Gusshausstraße 25-29\n *    1040 Vienna, Austria\n *    potapova(at)acin.tuwien.ac.at\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 \"v4r/attention_segmentation/algo.h\"\n\n#include <Eigen/Dense>\n\nnamespace v4r\n{\n\nvoid filterGaussian(cv::Mat &input, cv::Mat &output, cv::Mat &mask)\n{\n  float kernel[5] = {1.0,4.0,6.0,4.0,1.0};\n  \n  cv::Mat temp = cv::Mat_<float>::zeros(input.rows, input.cols);\n  \n  for(int i = 0; i < input.rows; ++i)\n  { \n    for(int j = 0; j < input.cols; j = j+2)\n    {\n      if(mask.at<float>(i,j) > 0)\n      {\n      \n\tfloat value = 0;\n        float kernel_sum = 0;\n      \n        for(int k = 0; k < 5; ++k)\n        {\n\t  int jj = j + (k-2);\n\t  if( (jj >=0) && (jj < input.cols) )\n\t  {\n\t    if(mask.at<float>(i,jj) > 0)\n\t    {\n\t      value += kernel[k] * input.at<float>(i,jj);\n\t      kernel_sum += kernel[k];\n\t    }\n\t  }\n        }\n      \n        if(kernel_sum > 0)\n        {\n\t  temp.at<float>(i,j) = value / kernel_sum;\n        }\n      }\n    }\n  }\n  \n  cv::Mat temp2 = cv::Mat_<float>::zeros(temp.rows, temp.cols);\n  \n  for(int i = 0; i < temp.rows; i = i+2)\n  { \n    for(int j = 0; j < temp.cols; j = j+2)\n    {\n      \n      if(mask.at<float>(i,j) > 0)\n      {\n     \n\tfloat value = 0;\n        float kernel_sum = 0;\n\t\n        for(int k = 0; k < 5; ++k)\n        {\n\t  int ii = i + (k-2);\n\t  if( (ii >=0) && (ii < temp.rows) )\n\t  {\n\t    if(mask.at<float>(ii,j) > 0)\n\t    {\n\t      value += kernel[k] * temp.at<float>(ii,j);\n\t      kernel_sum += kernel[k];\n\t    }\n\t  }\n        }\n      \n        if(kernel_sum > 0)\n        {\n\t  temp2.at<float>(i,j) = value / kernel_sum;\n        }\n      }\n    }\n  }\n  \n  int new_width = input.cols / 2;\n  int new_height = input.rows / 2;\n  \n  cv::Mat mask_output = cv::Mat_<float>::zeros(new_height,new_width);\n  output = cv::Mat_<float>::zeros(new_height,new_width);\n  \n  for(int i = 0; i < new_height; ++i)\n  {\n    for(int j = 0; j < new_width; ++j)\n    {\n      if(mask.at<float>(2*i,2*j) > 0)\n      {\n\tmask_output.at<float>(i,j) = 1.0;\n\toutput.at<float>(i,j) = temp2.at<float>(2*i,2*j);\n      }\n    }\n  }\n  \n  mask_output.copyTo(mask);\n}\n  \nvoid buildDepthPyramid(cv::Mat &image, std::vector<cv::Mat> &pyramid, cv::Mat &mask, unsigned int levelNumber)\n{\n  pyramid.resize(levelNumber+1);\n  image.copyTo(pyramid.at(0));\n  \n  cv::Mat oldMask;\n  mask.copyTo(oldMask);\n  \n  for(unsigned int i = 1; i <= levelNumber; ++i)\n  {\n    cv::Mat tempImage;\n    \n    filterGaussian(pyramid.at(i-1),tempImage,oldMask);    \n    tempImage.copyTo(pyramid.at(i));\n\n  }\n}\n\nvoid createPointCloudPyramid(std::vector<cv::Mat> &pyramidX, std::vector<cv::Mat> &pyramidY, std::vector<cv::Mat> &pyramidZ, \n\t\t\t     std::vector<cv::Mat> &pyramidIndices, std::vector<pcl::PointCloud<pcl::PointXYZRGB>::Ptr > &pyramidCloud)\n{\n  assert( pyramidX.size() == pyramidY.size() );\n  assert( pyramidX.size() == pyramidZ.size() );\n  assert( pyramidX.size() == pyramidIndices.size() );\n  \n  unsigned int num_levels = pyramidX.size();\n  \n  pyramidCloud.resize(num_levels);\n  \n  for(unsigned int idx = 0; idx < num_levels; ++idx)\n  {\n    assert( pyramidX.at(idx).rows == pyramidY.at(idx).rows );\n    assert( pyramidX.at(idx).cols == pyramidY.at(idx).cols );\n    assert( pyramidX.at(idx).rows == pyramidZ.at(idx).rows );\n    assert( pyramidX.at(idx).cols == pyramidZ.at(idx).cols );\n    assert( pyramidX.at(idx).rows == pyramidIndices.at(idx).rows );\n    assert( pyramidX.at(idx).cols == pyramidIndices.at(idx).cols );\n    \n    pyramidCloud.at(idx) = pcl::PointCloud<pcl::PointXYZRGB>::Ptr(new pcl::PointCloud<pcl::PointXYZRGB>() );\n    \n    unsigned int cur_height = pyramidX.at(idx).rows;\n    unsigned int cur_width = pyramidX.at(idx).cols;\n    \n    pyramidCloud.at(idx)->points.resize(cur_height*cur_width);\n    pyramidCloud.at(idx)->width = cur_width;\n    pyramidCloud.at(idx)->height = cur_height;\n    \n//     cv::imshow(\"pyramidZ.at(idx)\",pyramidZ.at(idx));\n//     cv::waitKey(-1);\n    \n    for(unsigned int i = 0 ; i < cur_height; ++i)\n    {\n      for(unsigned int j = 0; j < cur_width; ++j)\n      {\t\n\tpcl::PointXYZRGB p_cur;\n\t\n\t//std::cerr << \"(\" << pyramidIndices.at(idx).at<float>(i,j) << \"-- \" << pyramidX.at(idx).at<float>(i,j) << \",\" << pyramidY.at(idx).at<float>(i,j) << \",\" << pyramidZ.at(idx).at<float>(i,j) << \") \";\n\t\n        //if(pyramidIndices.at(idx).at<float>(i,j) > 0)\n\t//{\n\t  p_cur.x = pyramidX.at(idx).at<float>(i,j);\n\t  p_cur.y = pyramidY.at(idx).at<float>(i,j);\n\t  p_cur.z = pyramidZ.at(idx).at<float>(i,j);\n\t//}\n\t//else\n// \t{\n// \t  p_cur.x = std::numeric_limits<float>::quiet_NaN();\n// \t  p_cur.y = std::numeric_limits<float>::quiet_NaN();\n// \t  p_cur.z = std::numeric_limits<float>::quiet_NaN();\n// \t}\n\t\n\tint p_idx = i*cur_width + j;\n\tpyramidCloud.at(idx)->points.at(p_idx) = p_cur;\n      }\n    }\n    \n    //std::cerr <<  std::endl << std::endl;\n  \n//   cv::imshow(\"output\",output);\n//   cv::waitKey(-1);\n    \n  }\n}\n\nvoid createNormalPyramid(std::vector<cv::Mat> &pyramidNx, std::vector<cv::Mat> &pyramidNy, std::vector<cv::Mat> &pyramidNz, std::vector<cv::Mat> &pyramidIndices, std::vector<pcl::PointCloud<pcl::Normal>::Ptr > &pyramidNormal)\n{\n  assert( pyramidNx.size() == pyramidNy.size() );\n  assert( pyramidNx.size() == pyramidNz.size() );\n  assert( pyramidIndices.size() == pyramidNz.size() );\n  \n  unsigned int num_levels = pyramidNx.size();\n  \n  pyramidNormal.resize(num_levels);\n  \n  for(unsigned int idx = 0; idx < num_levels; ++idx)\n  {\n    assert( pyramidNx.at(idx).rows == pyramidNy.at(idx).rows );\n    assert( pyramidNx.at(idx).cols == pyramidNy.at(idx).cols );\n    assert( pyramidNx.at(idx).rows == pyramidNz.at(idx).rows );\n    assert( pyramidNx.at(idx).cols == pyramidNz.at(idx).cols );\n    assert( pyramidNx.at(idx).rows == pyramidIndices.at(idx).rows );\n    assert( pyramidNx.at(idx).cols == pyramidIndices.at(idx).cols );\n    \n    pyramidNormal.at(idx) = pcl::PointCloud<pcl::Normal>::Ptr(new pcl::PointCloud<pcl::Normal>() );\n    \n    unsigned int cur_height = pyramidNx.at(idx).rows;\n    unsigned int cur_width = pyramidNx.at(idx).cols;\n    \n    pyramidNormal.at(idx)->points.clear();\n    \n    for(unsigned int i = 0 ; i < cur_height; ++i)\n    {\n      for(unsigned int j = 0; j < cur_width; ++j)\n      {\t\n        if(pyramidIndices.at(idx).at<float>(i,j) > 0)\n\t{\n\t  pcl::Normal p_cur;\n\t  p_cur.normal[0] = pyramidNx.at(idx).at<float>(i,j);\n\t  p_cur.normal[1] = pyramidNy.at(idx).at<float>(i,j);\n\t  p_cur.normal[2] = pyramidNz.at(idx).at<float>(i,j);\n\t  \n\t  pyramidNormal.at(idx)->points.push_back(p_cur);\n\t}\n      }\n    }\n    \n    pyramidNormal.at(idx)->width = pyramidNormal.at(idx)->points.size();\n    pyramidNormal.at(idx)->height = 1;\n    \n  }\n}\n\nvoid createIndicesPyramid(std::vector<cv::Mat> &pyramidIndices, std::vector<pcl::PointIndices::Ptr> &pyramidIndiceSets)\n{\n  unsigned int num_levels = pyramidIndices.size();\n  \n  pyramidIndiceSets.resize(num_levels);\n  \n  for(unsigned int idx = 0; idx < num_levels; ++idx)\n  {\n    pyramidIndiceSets.at(idx) = pcl::PointIndices::Ptr(new pcl::PointIndices() );\n    \n    unsigned int cur_height = pyramidIndices.at(idx).rows;\n    unsigned int cur_width = pyramidIndices.at(idx).cols;\n    \n    pyramidIndiceSets.at(idx)->indices.clear();\n    \n    for(unsigned int i = 0 ; i < cur_height; ++i)\n    {\n      for(unsigned int j = 0; j < cur_width; ++j)\n      {\t\n        if(pyramidIndices.at(idx).at<float>(i,j) > 0)\n\t{\n\t  int p_idx = i*cur_width + j;\n\t  pyramidIndiceSets.at(idx)->indices.push_back(p_idx);\n\t}\n      }\n    }\n    \n  }\n}\n\nvoid upscaleImage(cv::Mat &input, cv::Mat &output, unsigned int width, unsigned int height)\n{\n  assert( width >= (unsigned int)(2*input.cols) );\n  assert( height >= (unsigned int)(2*input.rows) );\n \n  output = cv::Mat_<float>::zeros(height, width);\n  \n  for(unsigned int i = 0; i < (unsigned int)input.rows; ++i)\n  {\n    for(unsigned int j = 0; j < (unsigned int)input.cols; ++j)\n    {\n      output.at<float>(2*i,2*j) = input.at<float>(i,j);\n    }\n  }\n  \n  //cv::imshow(\"output\",output);\n  //cv::waitKey(-1);\n  \n  for(unsigned int i = 0; i < (unsigned int)output.rows; i=i+2)\n  {\n    for(unsigned int j = 1; j < (unsigned int)output.cols-1; j=j+2)\n    {\n      output.at<float>(i,j) = ( output.at<float>(i,j-1) + output.at<float>(i,j+1) ) / 2.0;\n    }\n  }\n  for(unsigned int i = 1; i < (unsigned int)output.rows-1; i=i+2)\n  {\n    for(unsigned int j = 0; j < (unsigned int)output.cols; j=j+2)\n    {\n      output.at<float>(i,j) = ( output.at<float>(i-1,j) + output.at<float>(i+1,j) ) / 2.0;\n    }\n  }\n  for(unsigned int i = 1; i < (unsigned int)output.rows-1; i=i+2)\n  {\n    for(unsigned int j = 1; j < (unsigned int)output.cols-1; j=j+2)\n    {\n      output.at<float>(i,j) = ( output.at<float>(i-1,j-1) + output.at<float>(i-1,j+1) + output.at<float>(i+1,j-1) + output.at<float>(i+1,j+1) ) / 4.0;\n    }\n  }\n}\n\nvoid downscaleImage(cv::Mat &input, cv::Mat &output, unsigned int width, unsigned int height)\n{\n  assert( 2*width <= (unsigned int)(input.cols) );\n  assert( 2*height <= (unsigned int)(input.rows) );\n  \n  output = cv::Mat_<float>::zeros(height, width);\n  \n  for(unsigned int i = 0; i < (unsigned int)output.rows; ++i)\n  {\n    for(unsigned int j = 0; j < (unsigned int)output.cols; ++j)\n    {\n      output.at<float>(i,j) = input.at<float>(2*i,2*j);\n    }\n  }\n}\n\nvoid scaleImage(std::vector<cv::Mat> &inputPyramid, cv::Mat &input, cv::Mat &output, int inLevel, int outLevel)\n{\n  assert(input.cols == inputPyramid.at(inLevel).cols);\n  assert(input.rows == inputPyramid.at(inLevel).rows);\n  \n  if( inLevel < outLevel )\n  {\n    input.copyTo(output);\n    for(int l = inLevel+1; l <= outLevel; ++l)\n    {\n      cv::Mat temp;\n      downscaleImage(output,temp,inputPyramid.at(l).cols,inputPyramid.at(l).rows);\n      temp.copyTo(output);\n    }\n  }\n  else if ( inLevel > outLevel )\n  {\n    input.copyTo(output);\n    for(int l = inLevel-1; l >= outLevel; --l)\n    {\n      cv::Mat temp;\n      upscaleImage(output,temp,inputPyramid.at(l).cols,inputPyramid.at(l).rows);\n      temp.copyTo(output);\n    }\n  }\n  else\n  {\n    input.copyTo(output);\n  }\n}\n\nbool inPoly(std::vector<cv::Point> &poly, cv::Point p)\n{\n  cv::Point newPoint;\n  cv::Point oldPoint;\n  cv::Point p1, p2;\n\n  bool inside = false;\n\n  if (poly.size() < 3)\n  {\n    return(false);\n  }\n\n\n  oldPoint = poly.at(poly.size()-1);\n  for(unsigned int i = 0 ; i < poly.size(); i++)\n  {\n    newPoint = poly.at(i);\n    if(newPoint.y > oldPoint.y)\n    {\n      p1 = oldPoint;\n      p2 = newPoint;\n    }\n    else\n    {\n      p1 = newPoint;\n      p2 = oldPoint;\n    }\n\n    if((newPoint.y < p.y) == (p.y <= oldPoint.y)          /* edge \"open\" at one end */\n      && ((long)p.x-(long)p1.x)*(long)(p2.y-p1.y) < ((long)p2.x-(long)p1.x)*(long)(p.y-p1.y))\n    {\n      inside = !inside;\n    }\n    oldPoint = newPoint;\n  }\n  return(inside);\n}\n\nvoid buildPolygonMap(cv::Mat &polygonMap, std::vector<std::vector<cv::Point> > &polygons)\n{\n  for(int i = 0; i < polygonMap.rows; ++i)\n  {\n    for(int j = 0; j < polygonMap.cols; ++j)\n    {\n      unsigned int k = 0;\n      while((polygonMap.at<uchar>(i,j) == 0) && (k < polygons.size()))\n      {\n        if(inPoly(polygons.at(k),cv::Point(j,i)))\n          polygonMap.at<uchar>(i,j) = k+1;\n        k += 1;\n      }\n    }\n  }\n}\n\nvoid buildCountourMap(cv::Mat &polygonMap, std::vector<std::vector<cv::Point> > &polygons, cv::Scalar color)\n{\n  for(unsigned int i = 0; i < polygons.size(); ++i)\n  {\n    for(unsigned int j = 0; j < polygons.at(i).size(); ++j)\n    {\n      cv::line(polygonMap,polygons.at(i).at(j),polygons.at(i).at((j+1)%polygons.at(i).size()),color,2);\n    }\n  }\n}\n\nfloat normPDF(float x, float mean, float stddev)\n{\n  float val = exp(-(x-mean)*(x-mean)/(2*stddev*stddev));\n  val /= sqrt(2*3.14)*stddev;\n  return val;\n}\n\nfloat normPDF(std::vector<float> x, std::vector<float> mean, cv::Mat stddev)\n{\n  int dim = mean.size();\n  \n  EIGEN_ALIGN16 Eigen::MatrixXf _stddev = Eigen::MatrixXf::Zero(dim,dim);\n  EIGEN_ALIGN16 Eigen::VectorXf _x = Eigen::VectorXf::Zero(dim);\n  \n  for(int i = 0; i < dim; ++i)\n  {\n    _x[i] = x.at(i) - mean.at(i);\n    for(int j = 0; j < dim; ++j)\n    {\n      _stddev(i,j) = stddev.at<float>(i,j);\n    }\n  }\n  \n  //std::cerr << \"_x.transpose() = \" << _x.transpose() << std::endl;\n  //std::cerr << \"_stddev = \" << _stddev << std::endl;\n  //std::cerr << \"_x = \" << _x << std::endl;\n  \n  float value = (_x.transpose())*_stddev*_x;\n  value /= -2;\n  value = exp(value);\n  \n  float det = _stddev.determinant();\n  \n  value /= sqrt(pow(2*3.14,dim)*det);\n  \n  return(value);\n  \n}\n\nvoid addNoise(cv::Mat &image, cv::Mat &nImage, cv::RNG &rng,float min, float max)\n{\n  nImage = cv::Mat_<float>::zeros(image.rows, image.cols);\n  for(int i = 0; i < image.rows; ++i)\n  {\n    for(int j = 0; j < image.cols; ++j)\n    {\n      float val = image.at<float>(i,j) + rng.uniform(min,max);\n      nImage.at<float>(i,j) = (val < 0 ? 0 : (val > 1 ? 1 : val));\n    }\n  }\n}\n\nvoid normPDF(cv::Mat &mat, float mean, float stddev, cv::Mat &res)\n{\n  res = cv::Mat_<float>::zeros(mat.rows,mat.cols);\n  res = mat - mean;\n  res = res.mul(res);\n  float b = - 1.0f / (2 * stddev * stddev);\n  res = res * b;\n\n  cv::exp(res,res);\n  float a = 1.0f/(stddev*sqrt(2*M_PI));\n  res = res * a;\n}\n\nvoid normalizeDist(std::vector<float> &dist)\n{\n  float total_sum = 0;\n  for(unsigned int i = 0; i < dist.size(); ++i)\n  {\n    total_sum += dist.at(i);\n  }\n  \n  for(unsigned int i = 0; i < dist.size(); ++i)\n  {\n    dist.at(i) /= total_sum;\n  }\n}\n\nfloat getMean(std::vector<float> dist, float total_num)\n{\n  float mean = 0;\n  for(unsigned int i = 0; i < dist.size(); ++i)\n  {\n    mean += (dist.at(i)/total_num)*i;\n  }\n  return mean;\n}\n\nfloat getStd(std::vector<float> dist, float mean, float total_num)\n{\n  float stdDev = 0;\n  \n  for(unsigned int i = 0; i < dist.size(); ++i)\n  {\n    stdDev += (i-mean)*(i-mean)*(dist.at(i)/total_num);\n  }\n  \n  stdDev = sqrt(stdDev);\n  \n  return stdDev;\n}\n\nlong commulativeFunctionArgValue(float x, std::vector<float> &A)\n{\n  long min = 0;\n  long max = A.size()-1;\n  while(max!=min+1)\n  {\n    long mid = (min+max)/2;\n    if(x <= A.at(mid))\n    {\n      max = mid;\n    }\n    else\n    {\n      min = mid; \n    }\n  }\n  \n  if(A.at(min) >= x)\n    return(min);\n  else\n    return(max);\n}\n\nvoid createContoursFromMasks(std::vector<cv::Mat> &masks, std::vector<std::vector<cv::Point> > &contours)\n{\n  // to extract contours\n  contours.clear();\n  contours.resize(masks.size());\n\n  for(unsigned int i = 0; i < masks.size(); ++i)\n  {\n    std::vector<std::vector<cv::Point> > temp;\n    cv::Mat temp_image;\n    masks.at(i).copyTo(temp_image);\n    cv::findContours(temp_image,temp,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE);\n    if(temp.size())\n    {\n      long totalPointsNum = 0;\n      for(unsigned int j = 0; j < temp.size(); ++j)\n      {\n\ttotalPointsNum += temp.at(j).size();\n      }\n      contours.at(i).resize(totalPointsNum);\n      totalPointsNum = 0;\n      for(unsigned int j = 0; j < temp.size(); ++j)\n      {\n\tfor(unsigned int k = 0; k < temp.at(j).size(); ++k)\n\t{\n\t  contours.at(i).at(totalPointsNum) = temp.at(j).at(k);\n\t  totalPointsNum += 1;\n\t}\n      }\n    }\n  }\n}\n\nuchar Num01Transitions(cv::Mat s, int j, int i)\n{\n\n  uchar p2 = s.at<uchar>(j-1,i);\n  uchar p3 = s.at<uchar>(j-1,i+1);\n  uchar p4 = s.at<uchar>(j,i+1);\n  uchar p5 = s.at<uchar>(j+1,i+1);\n  uchar p6 = s.at<uchar>(j+1,i);\n  uchar p7 = s.at<uchar>(j+1,i-1);\n  uchar p8 = s.at<uchar>(j,i-1);\n  uchar p9 = s.at<uchar>(j-1,i-1);\n\n  uchar Nt = 0;\n  \n  if((p3-p2) == 1)\n    Nt++;\n  if((p4-p3) == 1)\n    Nt++;\n  if((p5-p4) == 1)\n    Nt++;\n  if((p6-p5) == 1)\n    Nt++;\n  if((p7-p6) == 1)\n    Nt++;\n  if((p8-p7) == 1)\n    Nt++;\n  if((p9-p8) == 1)\n    Nt++;\n  if((p2-p9) == 1)\n    Nt++;\n  \n  return Nt;\n}\n\nvoid MConnectivity(cv::Mat &s, uchar *element)\n{\n  for(int i = 1; i < s.rows-1; ++i)\n  {\n    for(int j = 1; j < s.cols-1; ++j)\n    {\n      if(s.at<uchar>(i,j) > 0)\n      {\n\t//s.at<uchar>(i,j) = 0;\n\t\n\tbool remove = true;\n\tfor(int p = 0; p < 8; ++p)\n        {\n          int new_x = j + dx8[p];\n          int new_y = i + dy8[p];\n      \n          uchar value = s.at<uchar>(new_y,new_x);\n\t  \n\t  if(element[p] < 2)\n\t  {\n\t    if(value != element[p])\n\t    {\n\t      remove = false;\n\t    }\n\t  }\n        }\n        \n\tif(remove)\n\t{\n\t  s.at<uchar>(i,j) = 0;\n\t}\n      }\n    }\n  }\n}\n\nV4R_EXPORTS void Skeleton(cv::Mat a, cv::Mat &s)\n{\n  int width  = a.cols;\n  int height = a.rows;\n  \n  a.copyTo(s);\n  \n  cv::Scalar prevsum(0);\n\n  while(true)\n  {\n\n    cv::Mat m = cv::Mat_<uchar>::ones(height,width);\n    \n    for(int j = 1; j < height-1; ++j)\n    {\n      for(int i = 1; i < width-1; ++i)\n      {\n        if (s.at<uchar>(j, i) == 1)\n\t{\n\t  uchar p2 = s.at<uchar>(j-1,i);\n\t  uchar p3 = s.at<uchar>(j-1,i+1);\n\t  uchar p4 = s.at<uchar>(j,i+1);\n\t  uchar p5 = s.at<uchar>(j+1,i+1);\n\t  uchar p6 = s.at<uchar>(j+1,i);\n\t  uchar p7 = s.at<uchar>(j+1,i-1);\n\t  uchar p8 = s.at<uchar>(j,i-1);\n\t  uchar p9 = s.at<uchar>(j-1,i-1);\n\t  \n\t  uchar condA = p2+p3+p4+p5+p6+p7+p8+p9;\n          uchar condB = Num01Transitions(s,j,i);\n          uchar condC = p2 * p4 * p6;\n          uchar condD = p4 * p6 * p8;\n\n          if ((condA >= 2) && (condA <= 6) && (condB == 1) && (condC == 0) && (condD == 0))\n             m.at<uchar>(j, i) = 0;\n\t}\n\n      }\n    }\n\n    for(int j = 1; j < height-1; ++j)\n    {\n      for(int i = 1; i < width-1; ++i)\n      {\n\ts.at<uchar>(j,i) = s.at<uchar>(j,i)*m.at<uchar>(j,i);\n      }\n    }\n\n    m = cv::Mat_<uchar>::ones(height,width);\n    for(int j = 1; j < height-1; ++j)\n    {\n      for(int i = 1; i < width-1; ++i)\n      {\n\n        if (s.at<uchar>(j, i) == 1)\n\t{\n          uchar p2 = s.at<uchar>(j-1,i);\n\t  uchar p3 = s.at<uchar>(j-1,i+1);\n\t  uchar p4 = s.at<uchar>(j,i+1);\n\t  uchar p5 = s.at<uchar>(j+1,i+1);\n\t  uchar p6 = s.at<uchar>(j+1,i);\n\t  uchar p7 = s.at<uchar>(j+1,i-1);\n\t  uchar p8 = s.at<uchar>(j,i-1);\n\t  uchar p9 = s.at<uchar>(j-1,i-1);\n\t  \n\t  uchar condA = p2+p3+p4+p5+p6+p7+p8+p9;\n          uchar condB = Num01Transitions(s,j,i);\n          uchar condC = p2 * p4 * p8;\n          uchar condD = p2 * p6 * p8;\n                \n          if ((condA >= 2) && (condA <= 6) && (condB == 1) && (condC == 0) && (condD == 0))\n            m.at<uchar>(j, i) = 0;\n\t}\n      }\n    }\n\n    for(int j = 1; j < height-1; ++j)\n    {\n      for(int i = 1; i < width-1; ++i)\n      {\n\ts.at<uchar>(j,i) = s.at<uchar>(j,i)*m.at<uchar>(j,i);\n      }\n    }\n\n    cv::Scalar newsum = cv::sum(s);\n\n    if (newsum(0) == prevsum(0))\n      break;\n    \n    prevsum = newsum;\n\n  }\n  \n  prevsum = cv::sum(s);\n  \n  uchar e1[8] = {2,1,2,1,2,0,0,0};\n  uchar e2[8] = {2,1,2,0,0,0,2,1};\n  uchar e3[8] = {0,0,2,1,2,1,2,0};\n  uchar e4[8] = {2,0,0,0,2,1,2,1};\n  \n  while(true)\n  {\n    MConnectivity(s,e1);\n    MConnectivity(s,e2);\n    MConnectivity(s,e3);\n    MConnectivity(s,e4);\n    \n    cv::Scalar newsum = cv::sum(s);\n\n    if (newsum(0) == prevsum(0))\n      break;\n    \n    prevsum = newsum;\n  }\n}\n\nfloat calculateDistance(cv::Point center, cv::Point point)\n{\n  float distance = sqrt((center.x-point.x)*(center.x-point.x) + (center.y-point.y)*(center.y-point.y));\n  return(distance);\n}\n\nfloat calculateDistance(cv::Point center, cv::Point point, float sigma)\n{\n  float distance = (center.x-point.x)*(center.x-point.x) + (center.y-point.y)*(center.y-point.y);\n  distance = exp(-distance/(2*sigma*sigma));\n  return(distance);\n}\n\nvoid calculateObjectCenter(cv::Mat mask, cv::Point &center)\n{\n  assert(mask.type() == CV_8UC1);\n  \n  float x_cen = 0;\n  float y_cen = 0;\n  cv::Scalar area = cv::sum(mask);\n  \n  for(int i = 0; i < mask.rows; ++i)\n  {\n    for(int j = 0; j < mask.cols; ++j)\n    {\n      uchar value = mask.at<uchar>(i,j);\n      if(value > 0)\n      {\n\tx_cen = x_cen + ((float)j)/area(0);\n        y_cen = y_cen + ((float)i)/area(0);\n      }\n    }\n  }\n  \n  if(mask.at<uchar>(y_cen,x_cen) == 0)\n  {\n    // search for closes 4-neighbour point\n    std::list<cv::Point> points;\n    points.push_back(cv::Point(x_cen,y_cen));\n    cv::Mat used = cv::Mat_<uchar>::zeros(mask.rows,mask.cols);\n    used.at<uchar>(y_cen,x_cen) = 1;\n    while(points.size())\n    {\n      cv::Point p = points.front();\n      points.pop_front();\n      if(mask.at<uchar>(p.y,p.x) > 0)\n      {\n        x_cen = p.x;\n\ty_cen = p.y;\n        break;\n      }\n      \n      for(int i = 0; i < 8; ++i)\n      {\n        int new_x = p.x + dx8[i];\n        int new_y = p.y + dy8[i];\n\t    \n\tif((new_x < 0) || (new_y < 0) || (new_x >= used.cols) || (new_y >= used.rows))\n\t  continue;\n\t\n\tif(used.at<uchar>(new_y,new_x) <= 0)\n\t{\n          points.push_back(cv::Point(new_x,new_y));\n\t  used.at<uchar>(new_y,new_x) = 1;\n\t}\n      }\n    }\n  }\n    \n  center.x = x_cen;\n  center.y = y_cen;\n}\n\nvoid calculateObjectCenter(std::vector<cv::Point> contour, cv::Mat mask, cv::Point &center)\n{\n  float x_cen = 0;\n  float y_cen = 0;\n  \n  for(unsigned int i = 0; i < contour.size(); ++i)\n  {\n    x_cen = x_cen + ((float)contour.at(i).x)/contour.size();\n    y_cen = y_cen + ((float)contour.at(i).y)/contour.size();\n  }\n  \n  if(mask.at<uchar>(y_cen,x_cen) == 0)\n  {\n    // search for closes 4-neighbour point\n    std::list<cv::Point> points;\n    points.push_back(cv::Point(x_cen,y_cen));\n    cv::Mat used = cv::Mat_<uchar>::zeros(mask.rows,mask.cols);\n    used.at<uchar>(y_cen,x_cen) = 1;\n    while(points.size())\n    {\n      cv::Point p = points.front();\n      points.pop_front();\n      if(mask.at<uchar>(p.y,p.x) > 0)\n      {\n        x_cen = p.x;\n\ty_cen = p.y;\n        break;\n      }\n      \n      for(int i = 0; i < 8; ++i)\n      {\n        int new_x = p.x + dx8[i];\n        int new_y = p.y + dy8[i];\n\t    \n\tif((new_x < 0) || (new_y < 0) || (new_x >= used.cols) || (new_y >= used.rows))\n\t  continue;\n\t\n\tif(used.at<uchar>(new_y,new_x) <= 0)\n\t{\n          points.push_back(cv::Point(new_x,new_y));\n\t  used.at<uchar>(new_y,new_x) = 1;\n\t}\n      }\n    }\n  }\n    \n  center.x = x_cen;\n  center.y = y_cen;\n}\n\nvoid get2DNeighbors(const cv::Mat &patches, cv::Mat &neighbors, int patchesNumber)\n{\n  neighbors = cv::Mat_<bool>(patchesNumber,patchesNumber);\n  neighbors.setTo(false);\n  \n  //@ep TODO: uncomment?\n//   int dr[4] = {-1,-1, 0, 1};\n//   int dc[4] = { 0,-1,-1,-1};\n  \n  int dr[4] = {-1,0,-1};\n  int dc[4] = { 0,-1,-1};\n  \n  for(int r = 1; r < patches.rows-1; r++) \n  {\n    for(int c = 1; c < patches.cols-1; c++) \n    {\n      // if the patch exist\n      if(patches.at<int>(r,c) != -1) \n      {\n\t\n\tint patchIdx =  patches.at<int>(r,c);\n\t\n\t//@ep: why we did not use 1,-1 shift???\n\tfor(int i = 0; i < 3; ++i) //@ep: TODO 3->4\n\t{\n\t\n\t  int nr = r + dr[i];\n\t  int nc = c + dc[i];\n\t  \n\t  int currentPatchIdx =  patches.at<int>(nr,nc);\n\t  if(currentPatchIdx == -1)\n\t    continue;\n\t  \n\t  if(patchIdx != currentPatchIdx)\n\t  {\n\t    neighbors.at<bool>(currentPatchIdx,patchIdx) = true;\n            neighbors.at<bool>(patchIdx,currentPatchIdx) = true;\n\t  }\n\t}   \n      }\n    }\n  }\n}\n\n} //namespace v4r\n", "meta": {"hexsha": "8d1213a9af7d4849d608432c35ae787f1f4092cc", "size": 23415, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/attention_segmentation/src/algo.cpp", "max_stars_repo_name": "ToMadoRe/v4r", "max_stars_repo_head_hexsha": "7cb817e05cb9d99cb2f68db009c27d7144d07f09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-11-16T14:21:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-09T02:57:33.000Z", "max_issues_repo_path": "modules/attention_segmentation/src/algo.cpp", "max_issues_repo_name": "ToMadoRe/v4r", "max_issues_repo_head_hexsha": "7cb817e05cb9d99cb2f68db009c27d7144d07f09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2015-07-27T15:04:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T10:52:35.000Z", "max_forks_repo_path": "modules/attention_segmentation/src/algo.cpp", "max_forks_repo_name": "ToMadoRe/v4r", "max_forks_repo_head_hexsha": "7cb817e05cb9d99cb2f68db009c27d7144d07f09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T09:26:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-03T01:31:00.000Z", "avg_line_length": 24.5183246073, "max_line_length": 225, "alphanum_fraction": 0.554473628, "num_tokens": 7830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.28250355591467224}}
{"text": "#include <pybind11/pybind11.h>\n#include <pybind11/numpy.h>\n#include <armadillo>\n\nnamespace py = pybind11;\n\nusing namespace arma;\n\n\ntypedef py::array_t<double, py::array::f_style | py::array::forcecast> array_tf;\ntypedef py::array_t<double, py::array::c_style | py::array::forcecast> array_tc;\n\n\ncube array_to_cube(array_tf m) {\n\n    py::buffer_info _m_buff = m.request();\n    int n_rows = _m_buff.shape[0];\n    int n_cols = _m_buff.shape[1];\n    int n_slices = _m_buff.shape[2];\n\n    cube _m_arma((double *)_m_buff.ptr, n_rows, n_cols, n_slices);\n\n    return _m_arma;\n}\n\n\nmat array_to_mat(array_tf m) {\n\n    py::buffer_info _m_buff = m.request();\n    int n_rows = _m_buff.shape[0];\n    int n_cols = _m_buff.shape[1];\n\n    mat _m_arma((double *)_m_buff.ptr, n_rows, n_cols);\n\n    return _m_arma;\n}\n\n\nvec array_to_vec(array_tf m) {\n\n    py::buffer_info _m_buff = m.request();\n    int n_rows = _m_buff.shape[0];\n\n    vec _m_vec((double *)_m_buff.ptr, n_rows);\n\n    return _m_vec;\n}\n\n\narray_tf cube_to_array(cube m) {\n\n    auto _m_array = array_tf({m.n_rows, m.n_cols, m.n_slices});\n\n    py::buffer_info _m_buff = _m_array.request();\n    std::memcpy(_m_buff.ptr, m.memptr(), sizeof(double) * m.n_rows * m.n_cols * m.n_slices);\n\n    return _m_array;\n}\n\n\narray_tf mat_to_array(mat m) {\n\n    auto _m_array = array_tf({m.n_rows, m.n_cols});\n\n    py::buffer_info _m_buff = _m_array.request();\n    std::memcpy(_m_buff.ptr, m.memptr(), sizeof(double) * m.n_rows * m.n_cols);\n\n    return _m_array;\n}\n\n\narray_tf vec_to_array(vec m) {\n\n    auto _m_array = array_tf({m.n_rows});\n\n    py::buffer_info _m_buff = _m_array.request();\n    std::memcpy(_m_buff.ptr, m.memptr(), sizeof(double) * m.n_rows);\n\n    return _m_array;\n}\n\n\npy::tuple backward_pass(array_tf _Cxx, array_tf _cx, array_tf _Cuu,\n                        array_tf _cu, array_tf _Cxu,\n                        array_tf _A, array_tf _B,\n                        double lmbda, int reg,\n                        int dm_state, int dm_act, int nb_steps) {\n\n    // inputs\n    cube Cxx = array_to_cube(_Cxx);\n    mat cx = array_to_mat(_cx);\n    cube Cuu = array_to_cube(_Cuu);\n    mat cu = array_to_mat(_cu);\n    cube Cxu = array_to_cube(_Cxu);\n\n    cube A = array_to_cube(_A);\n    cube B = array_to_cube(_B);\n\n    // outputs\n    cube Q(dm_state + dm_act, dm_state + dm_act, nb_steps);\n    cube Qxx(dm_state, dm_state, nb_steps);\n    cube Qux(dm_act, dm_state, nb_steps);\n    cube Quu(dm_act, dm_act, nb_steps);\n    mat qx(dm_state, nb_steps);\n    mat qu(dm_act, nb_steps);\n\n    cube Qux_reg(dm_act, dm_state, nb_steps);\n    cube Quu_reg(dm_act, dm_act, nb_steps);\n    cube Quu_inv(dm_act, dm_act, nb_steps);\n\n    cube V(dm_state, dm_state, nb_steps + 1);\n    mat v(dm_state, nb_steps + 1);\n    vec dV(2);\n\n    cube V_reg(dm_state, dm_state, nb_steps + 1);\n\n    cube K(dm_act, dm_state, nb_steps);\n    mat kff(dm_act, nb_steps);\n\n    int _diverge = 0;\n\n    // last time step\n    V.slice(nb_steps) = Cxx.slice(nb_steps);\n    v.col(nb_steps) = cx.col(nb_steps);\n\n\tfor(int i = nb_steps - 1; i>= 0; --i)\n\t{\n        Qxx.slice(i) = Cxx.slice(i) + A.slice(i).t() * V.slice(i+1) * A.slice(i);\n        Quu.slice(i) = Cuu.slice(i) + B.slice(i).t() * V.slice(i+1) * B.slice(i);\n        Qux.slice(i) = (Cxu.slice(i) + A.slice(i).t() * V.slice(i+1) * B.slice(i)).t();\n\n        qu.col(i) = cu.col(i) + B.slice(i).t() * v.col(i+1);\n        qx.col(i) = cx.col(i) + A.slice(i).t() * v.col(i+1);\n\n        V_reg.slice(i+1) = V.slice(i+1);\n        if (reg==2)\n            V_reg.slice(i+1) += lmbda * eye(dm_state, dm_state);\n\n        Qux_reg.slice(i) = (Cxu.slice(i) + A.slice(i).t() * V_reg.slice(i+1) * B.slice(i)).t();\n\n        Quu_reg.slice(i) = Cuu.slice(i) + B.slice(i).t() * V_reg.slice(i+1) * B.slice(i);\n        if (reg==1)\n            Quu_reg.slice(i) += lmbda * eye(dm_act, dm_act);\n\n        if (!(Quu_reg.slice(i)).is_sympd()) {\n            _diverge = i;\n            break;\n        }\n\n        Quu_inv.slice(i) = inv(Quu_reg.slice(i));\n        K.slice(i) = - Quu_inv.slice(i) * Qux_reg.slice(i);\n        kff.col(i) = - Quu_inv.slice(i) * qu.col(i);\n\n        dV += join_vert(kff.col(i).t() * qu.col(i), 0.5 * kff.col(i).t() * Quu.slice(i) * kff.col(i));\n\n        v.col(i) = qx.col(i) + K.slice(i).t() * Quu.slice(i) * kff.col(i) +\n                   K.slice(i).t() * qu.col(i) + Qux.slice(i).t() * kff.col(i);\n\n        V.slice(i) = Qxx.slice(i) + K.slice(i).t() * Quu.slice(i) * K.slice(i) +\n                     K.slice(i).t() * Qux.slice(i) + Qux.slice(i).t() * K.slice(i);\n        V.slice(i) = 0.5 * (V.slice(i) + V.slice(i).t());\n\t}\n\n    // transform outputs to numpy\n    array_tf _Qxx = cube_to_array(Qxx);\n    array_tf _Qux = cube_to_array(Qux);\n    array_tf _Quu = cube_to_array(Quu);\n\n    array_tf _qx = mat_to_array(qx);\n    array_tf _qu = mat_to_array(qu);\n\n    array_tf _V = cube_to_array(V);\n    array_tf _v = mat_to_array(v);\n    array_tf _dV = vec_to_array(dV);\n\n    array_tf _K = cube_to_array(K);\n    array_tf _kff = mat_to_array(kff);\n\n    py::tuple output =  py::make_tuple(_Qxx, _Qux, _Quu, _qx, _qu,\n                                       _V, _v, _dV, _K, _kff, _diverge);\n\treturn output;\n}\n\n\nPYBIND11_MODULE(core, m)\n{\n    m.def(\"backward_pass\", &backward_pass);\n}\n", "meta": {"hexsha": "c8a3dd7a8911f214f8513dadc326e3b48d93cfcc", "size": 5212, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "trajopt/ilqr/src/util.cpp", "max_stars_repo_name": "Fitz13009/trajopt", "max_stars_repo_head_hexsha": "e74cf44cfa7d3037d1fccb27ab1e7eebff16c8c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40.0, "max_stars_repo_stars_event_min_datetime": "2019-06-17T11:49:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:30:56.000Z", "max_issues_repo_path": "trajopt/ilqr/src/util.cpp", "max_issues_repo_name": "Fitz13009/trajopt", "max_issues_repo_head_hexsha": "e74cf44cfa7d3037d1fccb27ab1e7eebff16c8c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-12-10T13:40:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-06T09:22:47.000Z", "max_forks_repo_path": "trajopt/ilqr/src/util.cpp", "max_forks_repo_name": "Fitz13009/trajopt", "max_forks_repo_head_hexsha": "e74cf44cfa7d3037d1fccb27ab1e7eebff16c8c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-07-05T11:29:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T12:56:56.000Z", "avg_line_length": 27.5767195767, "max_line_length": 102, "alphanum_fraction": 0.5907521105, "num_tokens": 1670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2824528482608677}}
{"text": "// fontnik\n#include \"glyph_foundry.hpp\"\n\n#include <agg/agg_curves.h>\n#include <agg/agg_curves_impl.hpp>\n\n// boost\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/index/rtree.hpp>\n\n// std\n#include <cmath> // std::sqrt\n\nnamespace bg = boost::geometry;\nnamespace bgm = bg::model;\nnamespace bgi = bg::index;\ntypedef bgm::point<float, 2, bg::cs::cartesian> Point;\ntypedef bgm::box<Point> Box;\ntypedef std::vector<Point> Points;\ntypedef std::vector<Points> Rings;\ntypedef std::pair<Point, Point> SegmentPair;\ntypedef std::pair<Box, SegmentPair> SegmentValue;\ntypedef bgi::rtree<SegmentValue, bgi::rstar<16>> Tree;\n\n\nnamespace sdf_glyph_foundry\n{\n    struct User {\n        Rings rings;\n        Points ring;\n    };\n\n    void CloseRing(Points &ring)\n    {\n        const Point &first = ring.front();\n        const Point &last = ring.back();\n\n        if (first.get<0>() != last.get<0>() ||\n            first.get<1>() != last.get<1>())\n        {\n            ring.push_back(first);\n        }\n    }\n\n    int MoveTo(const FT_Vector *to, void *ptr)\n    {\n        User *user = (User*)ptr;\n        if (!user->ring.empty()) {\n            CloseRing(user->ring);\n            user->rings.push_back(user->ring);\n            user->ring.clear();\n        }\n        user->ring.emplace_back(float(to->x) / 64.0, float(to->y) / 64.0);\n        return 0;\n    }\n\n    int LineTo(const FT_Vector *to, void *ptr)\n    {\n        User *user = static_cast<User*>(ptr);\n        user->ring.emplace_back(float(to->x) / 64.0, float(to->y) / 64.0);\n        return 0;\n    }\n\n    int ConicTo(const FT_Vector *control,\n                const FT_Vector *to,\n                void *ptr)\n    {\n        User *user = static_cast<User*>(ptr);\n\n        if (!user->ring.empty()) {\n            Point const& prev = user->ring.back();\n            auto dx = prev.get<0>();\n            auto dy = prev.get<1>();\n\n            // pop off last point, duplicate of first point in bezier curve\n            // WARNING: pop_back invalidates `prev`\n            // http://en.cppreference.com/w/cpp/container/vector/pop_back\n            user->ring.pop_back();\n\n            agg_fontnik::curve3_div curve(dx,dy,\n                                  float(control->x) / 64, float(control->y) / 64,\n                                  float(to->x) / 64, float(to->y) / 64);\n\n            curve.rewind(0);\n            double x, y;\n            unsigned cmd;\n\n            while (agg_fontnik::path_cmd_stop != (cmd = curve.vertex(&x, &y))) {\n                user->ring.emplace_back(x, y);\n            }\n        }\n\n        return 0;\n    }\n\n    int CubicTo(const FT_Vector *c1,\n                const FT_Vector *c2,\n                const FT_Vector *to,\n                void *ptr)\n    {\n        User *user = static_cast<User*>(ptr);\n\n        if (!user->ring.empty()) {\n\n            Point const& prev = user->ring.back();\n            auto dx = prev.get<0>();\n            auto dy = prev.get<1>();\n\n            // pop off last point, duplicate of first point in bezier curve\n            // WARNING: pop_back invalidates `prev`\n            // http://en.cppreference.com/w/cpp/container/vector/pop_back\n            user->ring.pop_back();\n\n            agg_fontnik::curve4_div curve(dx,dy,\n                                  float(c1->x) / 64, float(c1->y) / 64,\n                                  float(c2->x) / 64, float(c2->y) / 64,\n                                  float(to->x) / 64, float(to->y) / 64);\n\n            curve.rewind(0);\n            double x, y;\n            unsigned cmd;\n\n            while (agg_fontnik::path_cmd_stop != (cmd = curve.vertex(&x, &y))) {\n                user->ring.emplace_back(x, y);\n            }\n        }\n\n        return 0;\n    }\n\n    // point in polygon ray casting algorithm\n    bool PolyContainsPoint(const Rings &rings, const Point &p)\n    {\n        bool c = false;\n\n        for (const Points &ring : rings) {\n            auto p1 = ring.begin();\n            auto p2 = p1 + 1;\n\n            for (; p2 != ring.end(); p1++, p2++) {\n                if (((p1->get<1>() > p.get<1>()) != (p2->get<1>() > p.get<1>())) && (p.get<0>() < (p2->get<0>() - p1->get<0>()) * (p.get<1>() - p1->get<1>()) / (p2->get<1>() - p1->get<1>()) + p1->get<0>())) {\n                    c = !c;\n                }\n            }\n        }\n\n        return c;\n    }\n\n    double SquaredDistance(const Point &v, const Point &w)\n    {\n        const double a = v.get<0>() - w.get<0>();\n        const double b = v.get<1>() - w.get<1>();\n        return a * a + b * b;\n    }\n\n    Point ProjectPointOnLineSegment(const Point &p,\n                                    const Point &v,\n                                    const Point &w)\n    {\n      const double l2 = SquaredDistance(v, w);\n      if (l2 == 0) return v;\n\n      const double t = ((p.get<0>() - v.get<0>()) * (w.get<0>() - v.get<0>()) + (p.get<1>() - v.get<1>()) * (w.get<1>() - v.get<1>())) / l2;\n      if (t < 0) return v;\n      if (t > 1) return w;\n\n      return Point {\n          v.get<0>() + t * (w.get<0>() - v.get<0>()),\n          v.get<1>() + t * (w.get<1>() - v.get<1>())\n      };\n    }\n\n    double SquaredDistanceToLineSegment(const Point &p,\n                                        const Point &v,\n                                        const Point &w)\n    {\n        const Point s = ProjectPointOnLineSegment(p, v, w);\n        return SquaredDistance(p, s);\n    }\n\n    double MinDistanceToLineSegment(const Tree &tree,\n                                    const Point &p,\n                                    int radius)\n    {\n        const int squared_radius = radius * radius;\n\n        std::vector<SegmentValue> results;\n        tree.query(bgi::intersects(\n            Box{\n                Point{p.get<0>() - radius, p.get<1>() - radius},\n                Point{p.get<0>() + radius, p.get<1>() + radius}\n            }),\n            std::back_inserter(results));\n\n        double sqaured_distance = std::numeric_limits<double>::infinity();\n\n        for (const auto &value : results) {\n            const SegmentPair &segment = value.second;\n            const double dist = SquaredDistanceToLineSegment(p,\n                                                             segment.first,\n                                                             segment.second);\n            if (dist < sqaured_distance && dist < squared_radius) {\n                sqaured_distance = dist;\n            }\n        }\n\n        return std::sqrt(sqaured_distance);\n    }\n\n    void RenderSDF(glyph_info &glyph,\n                         int size,\n                         int buffer,\n                         float cutoff,\n                         FT_Face ft_face)\n    {\n\n        if (FT_Load_Glyph (ft_face, glyph.glyph_index, FT_LOAD_NO_HINTING)) {\n            return;\n        }\n\n        int advance = ft_face->glyph->metrics.horiAdvance / 64;\n        int ascender = ft_face->size->metrics.ascender / 64;\n        int descender = ft_face->size->metrics.descender / 64;\n\n        glyph.line_height = ft_face->size->metrics.height;\n        glyph.advance = advance;\n        glyph.ascender = ascender;\n        glyph.descender = descender;\n\n        FT_Outline_Funcs func_interface = {\n            .move_to = &MoveTo,\n            .line_to = &LineTo,\n            .conic_to = &ConicTo,\n            .cubic_to = &CubicTo,\n            .shift = 0,\n            .delta = 0\n        };\n\n        User user;\n\n        if (ft_face->glyph->format == FT_GLYPH_FORMAT_OUTLINE) {\n            // Decompose outline into bezier curves and line segments\n            FT_Outline outline = ft_face->glyph->outline;\n            if (FT_Outline_Decompose(&outline, &func_interface, &user)) return;\n\n            if (!user.ring.empty()) {\n                CloseRing(user.ring);\n                user.rings.push_back(user.ring);\n            }\n\n            if (user.rings.empty()) {\n                return;\n            }\n        } else {\n            return;\n        }\n\n        // Calculate the real glyph bbox.\n        double bbox_xmin = std::numeric_limits<double>::infinity(),\n               bbox_ymin = std::numeric_limits<double>::infinity();\n\n        double bbox_xmax = -std::numeric_limits<double>::infinity(),\n               bbox_ymax = -std::numeric_limits<double>::infinity();\n\n        for (const Points &ring : user.rings) {\n            for (const Point &point : ring) {\n                if (point.get<0>() > bbox_xmax) bbox_xmax = point.get<0>();\n                if (point.get<0>() < bbox_xmin) bbox_xmin = point.get<0>();\n                if (point.get<1>() > bbox_ymax) bbox_ymax = point.get<1>();\n                if (point.get<1>() < bbox_ymin) bbox_ymin = point.get<1>();\n            }\n        }\n\n        bbox_xmin = std::round(bbox_xmin);\n        bbox_ymin = std::round(bbox_ymin);\n        bbox_xmax = std::round(bbox_xmax);\n        bbox_ymax = std::round(bbox_ymax);\n\n        // Offset so that glyph outlines are in the bounding box.\n        for (Points &ring : user.rings) {\n            for (Point &point : ring) {\n                point.set<0>(point.get<0>() + -bbox_xmin + buffer);\n                point.set<1>(point.get<1>() + -bbox_ymin + buffer);\n            }\n        }\n\n        if (bbox_xmax - bbox_xmin == 0 || bbox_ymax - bbox_ymin == 0) return;\n\n        glyph.left = bbox_xmin;\n        glyph.top = bbox_ymax;\n        glyph.width = bbox_xmax - bbox_xmin;\n        glyph.height = bbox_ymax - bbox_ymin;\n\n        Tree tree;\n        float offset = 0.5;\n        int radius = 8;\n        int radius_by_256 = (256 / radius);\n\n        for (const Points &ring : user.rings) {\n            auto p1 = ring.begin();\n            auto p2 = p1 + 1;\n\n            for (; p2 != ring.end(); p1++, p2++) {\n                const int segment_x1 = std::min(p1->get<0>(), p2->get<0>());\n                const int segment_x2 = std::max(p1->get<0>(), p2->get<0>());\n                const int segment_y1 = std::min(p1->get<1>(), p2->get<1>());\n                const int segment_y2 = std::max(p1->get<1>(), p2->get<1>());\n\n                tree.insert(SegmentValue {\n                    Box {\n                        Point {segment_x1, segment_y1},\n                        Point {segment_x2, segment_y2}\n                    },\n                    SegmentPair {\n                        Point {p1->get<0>(), p1->get<1>()},\n                        Point {p2->get<0>(), p2->get<1>()}\n                    }\n                });\n            }\n        }\n\n        // Loop over every pixel and determine the positive/negative distance to the outline.\n        unsigned int buffered_width = glyph.width + 2 * buffer;\n        unsigned int buffered_height = glyph.height + 2 * buffer;\n        unsigned int bitmap_size = buffered_width * buffered_height;\n        glyph.bitmap.resize(bitmap_size);\n\n        for (unsigned int y = 0; y < buffered_height; y++) {\n            for (unsigned int x = 0; x < buffered_width; x++) {\n                unsigned int ypos = buffered_height - y - 1;\n                unsigned int i = ypos * buffered_width + x;\n                Point pt{x + offset, y + offset };\n                double d = MinDistanceToLineSegment(tree, pt, radius) * radius_by_256;\n\n                // Invert if point is inside.\n                const bool inside = PolyContainsPoint(user.rings, pt);\n                if (inside) {\n                    d = -d;\n                }\n\n                // Shift the 0 so that we can fit a few negative values\n                // into our 8 bits.\n                d += cutoff * 256;\n\n                // Clamp to 0-255 to prevent overflows or underflows.\n                int n = d > 255 ? 255 : d;\n                n = n < 0 ? 0 : n;\n\n                glyph.bitmap[i] = static_cast<char>(255 - n);\n            }\n        }\n    }\n\n} // ns sdf_glyph_foundry\n", "meta": {"hexsha": "a04703afc6a4ee7aa2a62fffb7d4ef0701b5aa55", "size": 11761, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mapbox/glyph_foundry_impl.hpp", "max_stars_repo_name": "dpelle/sdf-glyph-foundry", "max_stars_repo_head_hexsha": "522df438a9dd2049b3486f5fdbd2c866ed171ccc", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2017-02-05T13:04:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T16:39:57.000Z", "max_issues_repo_path": "include/mapbox/glyph_foundry_impl.hpp", "max_issues_repo_name": "dpelle/sdf-glyph-foundry", "max_issues_repo_head_hexsha": "522df438a9dd2049b3486f5fdbd2c866ed171ccc", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-03-03T04:52:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T17:18:37.000Z", "max_forks_repo_path": "include/mapbox/glyph_foundry_impl.hpp", "max_forks_repo_name": "dpelle/sdf-glyph-foundry", "max_forks_repo_head_hexsha": "522df438a9dd2049b3486f5fdbd2c866ed171ccc", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2017-04-12T01:25:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-06T09:43:54.000Z", "avg_line_length": 32.8519553073, "max_line_length": 208, "alphanum_fraction": 0.4867783352, "num_tokens": 2901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2824528414032058}}
{"text": "/*\n ============================================================================\n Name        : \tINSIGHTv3.cpp\n Author      : \tJan 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 : \tSequential version of the INSIGHT algorithm. Further details can be found in Lillacci & Khammash 2013\n ============================================================================\n */\n\n#include <ctime>\n#include <vector>\n#include <iostream>\n#include <fstream>\n#include <ostream>\n#include <sstream>\n#include <map>\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 <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n#include <Eigen/Dense>\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 \"InsightIteration.h\"\n#include \"PrevPopReader.h\"\n\nusing namespace INSIGHTv3;\nusing boost::property_tree::ptree;\nusing boost::property_tree::read_json;\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 std::string PARTICLE_INPUT = \"/input\";\nconst static std::string PARTICLE_OUTPUT = \"/output\";\nconst static bool IGNORE_WEIGHTS = false;\nconst static bool VERBOSE = 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;\nconst static double PARTICLE_TOLERANCE = 1.0;\nconst static int NUM_TRAJECTORIES = 10;\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;\nbool verbose; // surporess alloutput\nint print;\ndouble beta;\ndouble tolerance_kolmogorov;\ndouble kappa_kolmogorov;\ndouble tol_kappa_kolmovorog;\ndouble particle_tolerance;\nstd::string particle_in;\nstd::string particle_out;\nint num_trajectories;\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\tint seed = time(NULL);\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\tprintInfo(desc);\n\twriter_ptr writer = boost::make_shared<InsightOutputWriter>(\n\t\t\toutput_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\tsampler_factory_ptr factory =\n\t\t\tboost::make_shared<ScaledUniformSamplerFactory>(boost::ref(rng),\n\t\t\t\t\tdesc.model->num_params, *desc.lower_bounds_parameter,\n\t\t\t\t\t*desc.upper_bounds_parameter, ignore_weights);\n\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\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\n\tInsightIteration iteration(prior_sampler);\n\tToleranceProviderPtr tolerance_provider = boost::make_shared<\n\t\t\tFixedSequenceToleranceProvider>(s, desc.model->model,\n\t\t\tkolmogorov_computer);\n\n\tsampler_ptr first_sampler;\n\tstd::vector<double> prev_acceptance_rates;\n\tstd::vector<double> prev_tolerances;\n\tstd::vector<int> prev_num_simulations;\n\n\n\t//prev_num_simulations.push_back(20); // set to number of iterations\n\n\tif (prev_pop_file.length() > 0) {\n\t\tPrevPopReader prev_pop_reader;\n\t\tParticleSet particle_set;\n\t\tprev_pop_reader.readPreviousPop(prev_pop_file, desc.model->num_params,\n\t\t\t\t&particle_set, &prev_acceptance_rates, &prev_tolerances, &prev_num_simulations);\n\t\tfirst_sampler = factory->createSampler(particle_set,\n\t\t\t\tkolmogorov_computer->getThresholdForS(s), s);\n\t} else {\n\t\tfirst_sampler = prior_sampler;\n\t}\n\tInsightAlgorithm algorithm(iteration, factory, evaluator, writer,\n\t\t\ttolerance_provider, final_tolerance, num_particles,\n\t\t\tdesc.model->num_params, prev_acceptance_rates, prev_tolerances, prev_num_simulations);\n\tIterationLogger logger(print);\n\n\t//algorithm.run(first_sampler, logger);\n\n\talgorithm._updateTolerance(&num_trajectories, &particle_tolerance, &logger);\n\n\n    bool acceptable = 0;\n    parameters particle(desc.model->num_params);\n    //first_sampler->sampleParticle(&particle);\n\n//open particle input file\nstd::ifstream infile (particle_in.c_str());\n\n//open particle output file\nstd::ofstream outfile (particle_out.c_str());\nif (!outfile.is_open())\n    return -1; // error!\n\nstd::string line;\nint particle_count=0;\n\nwhile (std::getline(infile, line)) // parse particles one by one\n{\n\n    //using text file\n    unsigned first = line.find(\"[\");\n    unsigned last = line.find(\"]\");\n    std::string strNew = line.substr (first+1,last-first);\n\n    std::istringstream iss(strNew);\n    char ch;\n\n    double number=2.0;\n    int pcount=0;\n    while (pcount<desc.model->num_params) {\n        iss >> number;\n        iss>>ch; //flush the ,\n        particle(pcount)=number;\n        pcount++;\n    }\n\n    if(verbose)\n        std::cout << \"particle \" << particle_count << \": \" << particle << std::endl;\n\n    acceptable = evaluator->isParticleAcceptable(particle);\n    if(acceptable)\n        outfile << \"1\\n\";\n    else\n        outfile << \"0\\n\";\n}\noutfile.close();\n\n\tclock_t toc = clock();\n\tif(verbose) {\n        std::cout << \"\\n\\nSMC inference complete.\" << std::endl;\n        std::cout << \"\\nElapsed time: \" << ((double) (toc - tic)) / CLOCKS_PER_SEC\n                << \"sec.\" << std::endl;\n\t}\n\treturn 0;\n}\n\nvoid handleOptions(int argc, char * argv[]) {\n\n\tpo::options_description desc(\"Allowed options\");\n    desc.add_options()(\"help\", \"produce help message\")(\"problem_file\",\n            po::value<std::string>(&problem_file_name)->default_value(\n                    PROBLEM_FILE),\n            \"problem file. A problem file must always be provided!\")(\n            \"number_simulations,s\", po::value<int>(&s)->default_value(S),\n            \"starting number of simulations\")(\"final tolerance,e\",\n            po::value<double>(&final_tolerance)->default_value(FINAL_TOLERANCE),\n            \"the final tolerance for the algorithm\")(\"pop_size,n\",\n            po::value<int>(&num_particles)->default_value(NUM_PARTICLES),\n            \"define the population size\")(\"output_file,O\",\n            po::value<std::string>(&output_file_name)->default_value(\n                    OUTPUT_FILE), \"output file\")(\"previous_pop_file,P\",\n            po::value<std::string>(&prev_pop_file)->default_value(\n                    PREVIOUS_POPULATION_FILE), \"previous population file\")(\n            \"ignore_weights,i\",\n            po::value<bool>(&ignore_weights)->default_value(IGNORE_WEIGHTS),\n            \"ignore weights\")(\"print,p\",\n            po::value<int>(&print)->default_value(PRINT),\n            \"define the frequency of print outs\")(\"beta,b\",\n            po::value<double>(&beta)->default_value(BETA),\n            \"the confidence of the kolmogorov test for the rejection rule\")(\n            \"tol_kol,k\",\n            po::value<double>(&tolerance_kolmogorov)->default_value(\n                    TOL_KOLMOGOROV),\n            \"the tolerance for the algorithm to compute the inverse of the kolmogorov distribution\")(\n            \"kappa,K\",\n            po::value<double>(&kappa_kolmogorov)->default_value(\n                    KAPPA_KOLMOGOROV),\n            \"Kappa for the computation of the Kolmogorov distance\")(\n            \"tol_kol_kap,T\",\n            po::value<double>(&tol_kappa_kolmovorog)->default_value(\n                    TOL_KAPPA_KOLMOGOROV),\n            \"the tolerance for the algorithm to compute kappa for the computation of the Kolmogorov distance\")(\"X,X\",\n                    po::value<std::string>(&particle_in)->default_value(PARTICLE_INPUT),\"Particle input file\")(\"o,o\",\n                    po::value<std::string>(&particle_out)->default_value(PARTICLE_OUTPUT),\"Particle output file\")(\"t,t\",\n\t\tpo::value<double>(&particle_tolerance)->default_value(\n             PARTICLE_TOLERANCE),\"Particle tolerance\")(\"N,N\",po::value<int>(&num_trajectories)->default_value(\n                     NUM_TRAJECTORIES),\"Number of trajectories\")(\"v,v\",po::value<bool>(&verbose)->default_value(\n                             VERBOSE),\"Verbose\");\n\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    if(verbose) {\n        std::cout << \"\\nThis is INSIGHT v3.0\\n\" << std::endl;\n        std::cout << \"Problem file path:\" << std::endl;\n        std::cout << problem_file_name << std::endl;\n        std::cout << \"\\nThe new particle population will be saved in:\" << std::endl;\n        std::cout << output_file_name << std::endl;\n\n        std::cout << \"\\nWill estimate \" << desc.model->model_name << \" using \"\n                << num_particles << \" SMC particles.\" << std::endl;\n        std::cout << \"\\nThe data is assumed to have been created using \"\n                << desc.model->num_outputs << \" outputs,\" << std::endl;\n        std::cout << \"measured at \" << desc.times->size() << \" timepoints.\"\n                << std::endl;\n\n        if (prev_pop_file.length() > 0) {\n            std::cout << \"A previous population is loaded from file: \" << std::endl;\n            std::cout << prev_pop_file << std::endl;\n        }\n        std::cout << \"To estimate the density of each population \"\n                << \"Kernel Density Estimation with uniform Kernel\" << std::endl;\n        if (ignore_weights) {\n            std::cout << std::endl << \"Particle weights will be ignored by sampler!\"\n                    << std::endl;\n        }\n        std::cout << \"is used.\" << std::endl;\n        std::cout << \"\\nThe sequential version of the algorithm is used.\"\n                << std::endl << std::endl;\n    }\n}\n", "meta": {"hexsha": "78b931ae8107a0ac200299d677aacecfabd519da", "size": 11646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "container/INSIGHT/src/INSIGHTv3.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.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.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": 35.8338461538, "max_line_length": 120, "alphanum_fraction": 0.6725914477, "num_tokens": 2798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.28235771304224594}}
{"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 PCGSolver.cpp\n * @brief Preconditioned Conjugate Gradient Solver for linear systems\n * @date Feb 14, 2012\n * @author Yong-Dian Jian\n * @author Sungtae An\n */\n\n#include <gtsam/linear/PCGSolver.h>\n#include <gtsam/linear/GaussianFactorGraph.h>\n#include <gtsam/linear/Preconditioner.h>\n#include <gtsam/linear/VectorValues.h>\n\n#include <boost/algorithm/string.hpp>\n\n#include <algorithm>\n#include <iostream>\n#include <stdexcept>\n\nusing namespace std;\n\nnamespace gtsam {\n\n/*****************************************************************************/\nvoid PCGSolverParameters::print(ostream &os) const {\n  Base::print(os);\n  os << \"PCGSolverParameters:\" << endl;\n  preconditioner_->print(os);\n}\n\n/*****************************************************************************/\nPCGSolver::PCGSolver(const PCGSolverParameters &p) {\n  parameters_ = p;\n  preconditioner_ = createPreconditioner(p.preconditioner_);\n}\n\nvoid PCGSolverParameters::setPreconditionerParams(const boost::shared_ptr<PreconditionerParameters> preconditioner) {\n  preconditioner_ = preconditioner;\n}\n\nvoid PCGSolverParameters::print(const std::string &s) const {\n  std::cout << s << std::endl;;\n  std::ostringstream os;\n  print(os);\n  std::cout << os.str() << std::endl;\n}\n\n/*****************************************************************************/\nVectorValues PCGSolver::optimize(const GaussianFactorGraph &gfg,\n    const KeyInfo &keyInfo, const std::map<Key, Vector> &lambda,\n    const VectorValues &initial) {\n  /* build preconditioner */\n  preconditioner_->build(gfg, keyInfo, lambda);\n\n  /* apply pcg */\n  GaussianFactorGraphSystem system(gfg, *preconditioner_, keyInfo, lambda);\n  Vector x0 = initial.vector(keyInfo.ordering());\n  const Vector sol = preconditionedConjugateGradient(system, x0, parameters_);\n\n  return buildVectorValues(sol, keyInfo);\n}\n\n/*****************************************************************************/\nGaussianFactorGraphSystem::GaussianFactorGraphSystem(\n    const GaussianFactorGraph &gfg, const Preconditioner &preconditioner,\n    const KeyInfo &keyInfo, const std::map<Key, Vector> &lambda) :\n    gfg_(gfg), preconditioner_(preconditioner), keyInfo_(keyInfo), lambda_(\n        lambda) {\n}\n\n/*****************************************************************************/\nvoid GaussianFactorGraphSystem::residual(const Vector &x, Vector &r) const {\n  /* implement b-Ax, assume x and r are pre-allocated */\n\n  /* reset r to b */\n  getb(r);\n\n  /* substract A*x */\n  Vector Ax = Vector::Zero(r.rows(), 1);\n  multiply(x, Ax);\n  r -= Ax;\n}\n\n/*****************************************************************************/\nvoid GaussianFactorGraphSystem::multiply(const Vector &x, Vector& AtAx) const {\n  /* implement A^T*(A*x), assume x and AtAx are pre-allocated */\n\n  // Build a VectorValues for Vector x\n  VectorValues vvX = buildVectorValues(x, keyInfo_);\n\n  // VectorValues form of A'Ax for multiplyHessianAdd\n  VectorValues vvAtAx = keyInfo_.x0(); // crucial for performance\n\n  // vvAtAx += 1.0 * A'Ax for each factor\n  gfg_.multiplyHessianAdd(1.0, vvX, vvAtAx);\n\n  // Make the result as Vector form\n  AtAx = vvAtAx.vector(keyInfo_.ordering());\n}\n\n/*****************************************************************************/\nvoid GaussianFactorGraphSystem::getb(Vector &b) const {\n  /* compute rhs, assume b pre-allocated */\n\n  // Get whitened r.h.s (A^T * b) from each factor in the form of VectorValues\n  VectorValues vvb = gfg_.gradientAtZero();\n\n  // Make the result as Vector form\n  b = -vvb.vector(keyInfo_.ordering());\n}\n\n/**********************************************************************************/\nvoid GaussianFactorGraphSystem::leftPrecondition(const Vector &x,\n    Vector &y) const {\n  // For a preconditioner M = L*L^T\n  // Calculate y = L^{-1} x\n  preconditioner_.solve(x, y);\n}\n\n/**********************************************************************************/\nvoid GaussianFactorGraphSystem::rightPrecondition(const Vector &x,\n    Vector &y) const {\n  // For a preconditioner M = L*L^T\n  // Calculate y = L^{-T} x\n  preconditioner_.transposeSolve(x, y);\n}\n\n/**********************************************************************************/\nVectorValues buildVectorValues(const Vector &v, const Ordering &ordering,\n    const map<Key, size_t> & dimensions) {\n  VectorValues result;\n\n  DenseIndex offset = 0;\n  for (size_t i = 0; i < ordering.size(); ++i) {\n    const Key key = ordering[i];\n    map<Key, size_t>::const_iterator it = dimensions.find(key);\n    if (it == dimensions.end()) {\n      throw invalid_argument(\n          \"buildVectorValues: inconsistent ordering and dimensions\");\n    }\n    const size_t dim = it->second;\n    result.emplace(key, v.segment(offset, dim));\n    offset += dim;\n  }\n\n  return result;\n}\n\n/**********************************************************************************/\nVectorValues buildVectorValues(const Vector &v, const KeyInfo &keyInfo) {\n  VectorValues result;\n  for ( const KeyInfo::value_type &item: keyInfo ) {\n    result.emplace(item.first, v.segment(item.second.start, item.second.dim));\n  }\n  return result;\n}\n\n}\n", "meta": {"hexsha": "a7af7d8d8c742e3f9e3b63a30e160e54dade65d1", "size": 5506, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/linear/PCGSolver.cpp", "max_stars_repo_name": "xxiao-1/gtsam", "max_stars_repo_head_hexsha": "8b1516f43ffdf6b5098fc282b566f2ee1edb50f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1402.0, "max_stars_repo_stars_event_min_datetime": "2017-03-28T00:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:28:32.000Z", "max_issues_repo_path": "gtsam/linear/PCGSolver.cpp", "max_issues_repo_name": "xxiao-1/gtsam", "max_issues_repo_head_hexsha": "8b1516f43ffdf6b5098fc282b566f2ee1edb50f6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "gtsam/linear/PCGSolver.cpp", "max_forks_repo_name": "xxiao-1/gtsam", "max_forks_repo_head_hexsha": "8b1516f43ffdf6b5098fc282b566f2ee1edb50f6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 565.0, "max_forks_repo_forks_event_min_datetime": "2017-11-30T16:15:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:53:04.000Z", "avg_line_length": 32.3882352941, "max_line_length": 117, "alphanum_fraction": 0.5737377406, "num_tokens": 1226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.28235770586732567}}
{"text": "\n#include \"NRGclasses.hpp\"\n#include \"NRGfunctions.hpp\"\n\n#include <iostream>\n#include <vector>\n#include <math.h>\n\n#include <boost/timer.hpp>\n\n\n#include \"OneChQS.hpp\"\n\n\n\nint OneChQS_DiagHN( CNRGmatrix Qm1fNQ,\n\t\t    CNRGbasisarray Abasis, CNRGbasisarray SingleSite, \n\t\t    CNRGarray &Aeig, \n\t\t    double eps_N, double chi_N, double Lambda,bool display){\n\n\n\n\n  int NstOld=Aeig.dEn.size();\n\n  double prefactor,auxEl;\n\n  CNRGmatrix HN(Abasis);\n\n  double MyZero=1.0e-15;\n\n  // Check time\n  boost::timer t;\n\n\n\n\n  // Setup HN\n\n  // NEW: Special storage\n\n  HN.UpperTriangular=true;\n\n  int icount=0;\n\n  for (int ii=0;ii<Abasis.NumBlocks();ii++)\n    {\n      double Qi=Abasis.GetQNumber(ii,0);\n      double Si=Abasis.GetQNumber(ii,1);\n\n      int sizebl=Abasis.GetBlockSize(ii);\n\n      HN.MatBlockMap.push_back(ii);\n      HN.MatBlockMap.push_back(ii);\n      HN.MatBlockBegEnd.push_back(icount);\n      // New\n      if (HN.UpperTriangular)\n \ticount+=(sizebl*(sizebl+1))/2;\n      else\n\ticount+=sizebl*sizebl;\n      \n      HN.MatBlockBegEnd.push_back(icount-1);\n\n      //cout << \"  Setting up HN Block : \" << ii ;\n      //cout << \"  size: \" << Abasis.GetBlockSize(ii) << endl;\n\n      int ibl=0;\n      // Start timer\n      t.restart();\n      for (int ist=Abasis.GetBlockLimit(ii,0);\n\t       ist<=Abasis.GetBlockLimit(ii,1);ist++)\n\t{\n\t  int type_i = Abasis.iType[ist];\n\n\t  int jbl=0;\n// \t  for (int jst=Abasis.GetBlockLimit(ii,0);\n// \t           jst<=Abasis.GetBlockLimit(ii,1);jst++)\n\t  int j0;\n\t  // NEW THING! only calculates half of matrix els!\n\t  if (HN.UpperTriangular) j0=ist; \n\t  else j0=Abasis.GetBlockLimit(ii,0);\n\t  for (int jst=j0;\n\t           jst<=Abasis.GetBlockLimit(ii,1);jst++)\n\t    {\n\t      int type_j = Abasis.iType[jst];\n\t      int rold=ij2r(NstOld,Abasis.StCameFrom[ist],\n\t\t\t    Abasis.StCameFrom[jst]);\n\n \t      //cout << \"  Limit in j : \" << Abasis.BlockBegEnd[ii+1];\n \t      //cout << \"  ist : \" << ist << \"  jst : \" << jst;\n \t      //cout << \"  type i : \" << type_i << \" type j : \" << type_j <<endl;\n\t    \n\t      if (ist==jst)\n\t\t{\n\t\t  // Diagonal terms\n\t\t  auxEl=sqrt(Lambda)*Abasis.dEn[ist];\n\t\t  HN.MatEl.push_back(auxEl);\n\t\t  //cout << \" H( = \" << ist <<  \",\" << jst << \") =\" \n\t\t  //     << auxEl << endl;\n\n\t\t}\n\t      else\n\t\t{\n\t\t  // Off-diagonal terms: watch out for the h.c. term\n\t\t  // Nov 07: New off-diag approach, \n\t\t  // valid for two-channel as well\n\t\t  auxEl=Qm1fNQ.GetMatEl(Abasis.StCameFrom[ist],\n\t\t\t\t\tAbasis.StCameFrom[jst]);\n\t\t  int typep=type_i;\n\t\t  int type=type_j;\n\n      \t\t  // if Zero, calculate <i|h.c|j>=<j|fd|i>\n\t\t  // DIAGONAL BLOCKS: Si=Sj\n\t\t  if (fabs(auxEl)<MyZero)\n\t\t    {\n\t\t      auxEl=Qm1fNQ.GetMatEl(Abasis.StCameFrom[jst],\n\t\t\t\t\t    Abasis.StCameFrom[ist]);\n\t\t      typep=type_j;\n\t\t      type=type_i;\n\t\t    }\n\n\t\t  // Find Qcfp, Scfp, Scf, Stildep, Stilde\n\n\t\t  // Qtildep, Qtilde\n\n\t\t  double Qtildep=SingleSite.GetQNumber(typep,0);\n\t\t  double Stildep=SingleSite.GetQNumber(typep,1);\n\t\t  double Sztildep=SingleSite.GetQNumber(typep,2);\n\n\t\t  double Qtilde=SingleSite.GetQNumber(type,0);\n\t\t  double Stilde=SingleSite.GetQNumber(type,1);\n\t\t  double Sztilde=SingleSite.GetQNumber(type,2);\n\n\t\t  // Watch out: fermionic sign: (one for fd_{N+1} f_{N} )\n\t\t  // if using fd_{N}f_{N+1}=-f_{N+1}fd_{N} put a minus sign in front\n\n\t\t  double FermiSign=1.0;\n\t\t  if (dEqual(Qtilde,0.0)) FermiSign=-1.0;\n\n\t\t  double Scfp=Si-Sztildep;\n\t\t  double Scf=Si-Sztilde;\n\n\t\t  // Round-off things\n\t\t  //Stilde=0.5*((int)(2.0*Stilde));\n\n\t\t  \n\n\t\t  //cout << \" fN-1 = \" << auxEl << endl;\n\t\t  //cout << \"Si = \" << Si \n\t\t  //    << \" typep = \" << typep \n\t\t  //    << \" type = \" << type << endl; \n \t\t  //cout << \"Scfp = \" << Scfp \n \t\t  //     << \" Scf = \" << Scf << endl;\n\t\t  //\n \t\t  //cout << \"Stildep = \" << Stildep \n \t\t  //     << \" Stilde = \" << Stilde\n\t\t  //     << \" FermiSign = \" << FermiSign << endl;\n\n\t\t  double CoefMatEl=0.0;\n\t\t  double auxCG[]={0.0,0.0,0.0,0.0};\n\t\t  double siteqnumsp[]={Qtildep,Stildep,Sztildep};\n\t\t  double siteqnums[]={Qtilde,Stilde,Sztilde};\n\t\t  // Sum in Sztilde\n\t\t  for (Sztilde=-Stilde;Sztilde<=Stilde;Sztilde+=1.0)\n\t\t    {\n\t\t      // Sum in sigma: Note that Sztildep=Sztilde+sigma\n\t\t      siteqnums[2]=Sztilde;\n\t\t      int sitestate=SingleSite.GetBlockFromQNumbers(siteqnums);\n\t\t      for (double sigma=-0.5;sigma<=0.5;sigma+=1.0)\n\t\t\t{\n\t\t\t  siteqnumsp[2]=Sztilde+sigma;\n\t\t\t  // Test Find site state\n\t\t\t  int sitestatep=SingleSite.GetBlockFromQNumbers(siteqnumsp);\n\n\t\t\t  //cout << \"Sz~ = \" << Sztilde \n\t\t\t  //   << \" sigma = \" << sigma << endl;\n\t\n\t\t\t  auxCG[0]=CGordan(Scf,Si-Sztilde,\n\t\t\t\t\t   Stilde,Sztilde,Si,Si);\n\t\t\t  //cout << \"CG1( \" << Scf << \",\" << Si-Sztilde << \",\" \n\t\t\t  //              <<Stilde<< \",\" <<Sztilde<< \",\" \n\t\t\t  //              <<Si<< \",\" <<Si<< \") = \" \n\t\t\t  //   << auxCG[0] << endl;\n\t\t\t  auxCG[1]=CGordan(Scfp,Si-Sztilde-sigma,\n\t\t\t\t\t   Stildep,Sztilde+sigma,Si,Si);\n\t\t\t  // cout << \"CG2( \" << Scfp << \",\" << Si-Sztilde-sigma << \",\" \n\t\t\t  //              <<Stildep<< \",\" <<Sztilde+sigma<< \",\" \n\t\t\t  //               <<Si<< \",\" <<Si<< \") = \" \n\t\t\t  //   << auxCG[1] << endl;\n\t\t\t  //cout << \"CG3( \" << Scfp << \",\" << Si-Sztilde-sigma << \",\" \n\t\t\t  //     <<0.5<< \",\" <<sigma<< \",\" \n\t\t\t  //     <<Scf<< \",\" <<Si-Sztilde<< \") = \";\n\t\t\t  auxCG[2]=CGordan(Scfp,Si-Sztilde-sigma,0.5,sigma,Scf,Si-Sztilde);\n\t\t\t  //cout << auxCG[2] << endl;\n\t\t\t  //cout << \"typep = \"<< typep << \"type = \" << type << endl;\n\t\t\t  //cout << \"sitestp = \"<< sitestatep \n\t\t\t  //     << \" sitest = \" << sitestate << endl;\n \n\t\t\t  auxCG[3]=fd_table((int)(sigma/0.5),sitestatep,sitestate);\n\t\t\t  //cout << \"<sitestp|f|sitest> = \" << auxCG[3] << endl;\n\t\t\t  CoefMatEl+=auxCG[0]*auxCG[1]*auxCG[2]*auxCG[3];\n\t\t\t;\t\t\t\n\t\t\t}\n\t\t    }\n\n\t\t  //auxEl*=CoefMatEl;\n\t\t  auxEl*=CoefMatEl*FermiSign;\n\t\t  //cout << \" auxEl = \" << auxEl << endl;\n\t\t  auxEl*=chi_N;\n\t\t  HN.MatEl.push_back(auxEl);\n\t\t}\n\t      // end if ist==jst\n\t      jbl++;\n\t    }\n\t  // end loop in jst\n\t  ibl++;\n\t}\n      // end loop in ist\n      cout << \" Block : \" << ii \n\t   << \" size: \" << sizebl \n\t   <<\"  Time for set-up: \" << t.elapsed() << endl;\n    }\n  // end loop in blocks\n\n   cout << \"Num Blocks in HN     : \" << HN.NumBlocks() << endl;\n\n\n//   cout << \"HN : \" << endl;\n\n//   int jj=0;\n//   for (int ii=0;ii<HN.MatEl.size();ii++)\n//      {\n//        cout << \"Block = \" << HN.MatBlockMap[jj] << \" \" << HN.MatBlockMap[jj+1];\n//        cout << \"  i in block = \" << HN.vec[ii].ibl \n// \t    << \"  j in block = \" << HN.vec[ii].jbl;\n//        cout << \"  i = \" << HN.vec[ii].ist << \"  j = \" << HN.vec[ii].jst;\n//        cout << \"  val = \" << scientific << HN.MatEl[ii] << endl;\n//        jj+=2;\n\n//      }\n\n  // Set FilterMap_BegEnd:\n  // Takes tooo much time!\n  //it will get rid of repetitions \n  //in the block map and set MatBlockBegEnd\n\n//    cout << \"HN MatBlockMap : \";\n//    for (int ii=0;ii<HN.MatBlockMap.size();ii++)\n//      cout << HN.MatBlockMap[ii] << \" \";\n//    cout << endl;\n\n   //HN.FilterMap_SetBegEnd();\n\n//    cout << \"Filtered HN MatBlockMap : \";\n//    for (int ii=0;ii<HN.MatBlockMap.size();ii++)\n//      cout << HN.MatBlockMap[ii] << \" \";\n//    cout << endl;\n//    cout << \"HN MatBlockBegEnd : \";\n//    for (int ii=0;ii<HN.MatBlockBegEnd.size();ii++)\n//      cout << HN.MatBlockBegEnd[ii] << \" \";\n//    cout << endl;\n\n\n\n\n  // Some debugging:\n\n   if (display){\n     cout << \"Basis and HN for Nshell = \" << Abasis.Nshell << endl;\n     for (int ibl=0;ibl<Abasis.NumBlocks();ibl++){\n       Abasis.PrintBlockBasis(ibl);\n       HN.PrintMatBlock(ibl,ibl);\n     }\n   }\n   // end if display\n\n  // Update Aeig\n\n  cout << \" Updating Aeig. \" << endl;\n\n  Aeig.ClearAll();\n\n  // This works!\n  Aeig=HN;\n  \n  Aeig.Nshell=Abasis.Nshell;\n  // Diagonalize blocks\n  Aeig.dEn.clear();\n  Aeig.dEigVec.clear();\n  cout << \"HN eigenvalues for Nshell = \" << Abasis.Nshell << endl;\n  for (int ii=0;ii<HN.NumBlocks();ii++)\n    {\n      HN.DiagBlock(ii, Aeig.dEn, Aeig.dEigVec);\n      if (display){Aeig.PrintBlock(ii);}\n    }\n\n  //Set min to zero\n  Aeig.SetE0zero();\n\n  return(0);\n}\n\n\n// \t\t  if ( ((type_i==1)&&(type_j==2))||\n// \t\t       ((type_i==2)&&(type_j==1))||\n// \t\t       ((type_i==1)&&(type_j==3))||\n// \t\t       ((type_i==3)&&(type_j==1))||\n// \t\t       ((type_i==2)&&(type_j==4))||\n// \t\t       ((type_i==4)&&(type_j==2))||\n// \t\t       ((type_i==3)&&(type_j==4))||\n// \t\t       ((type_i==4)&&(type_j==3)) )\n// \t\t    {\n// \t\t      auxEl=OneChQS_prefactorHN(type_i,type_j,Si)*\n// \t\t       ( Qm1fNQ.GetMatEl(Abasis.StCameFrom[ist],\n// \t\t\t\t\tAbasis.StCameFrom[jst])+\n// \t\t\t Qm1fNQ.GetMatEl(Abasis.StCameFrom[jst],\n// \t\t\t\t\t Abasis.StCameFrom[ist]) );\n// \t\t      auxEl*=chi_N;\n// \t\t      HN.MatEl.push_back(auxEl);\n// \t\t    }\n// \t\t  else  HN.MatEl.push_back(0.0);\n", "meta": {"hexsha": "98be20ad7f173c8bb9921e55c7785e6e412f2718", "size": 8620, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/OneChQS/OneChQS_DiagHN.cpp", "max_stars_repo_name": "lgds/NRG_USP", "max_stars_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-21T20:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-20T01:21:41.000Z", "max_issues_repo_path": "src/OneChQS/OneChQS_DiagHN.cpp", "max_issues_repo_name": "lgds/NRG_USP", "max_issues_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/OneChQS/OneChQS_DiagHN.cpp", "max_forks_repo_name": "lgds/NRG_USP", "max_forks_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_forks_repo_licenses": ["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.7701863354, "max_line_length": 82, "alphanum_fraction": 0.5296983759, "num_tokens": 3035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778403, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.28220298026568136}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2021, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n#ifndef BOOST_GEOMETRY_STRATEGIES_SPHERICAL_CLOSEST_POINTS_CROSS_TRACK_HPP\n#define BOOST_GEOMETRY_STRATEGIES_SPHERICAL_CLOSEST_POINTS_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/coordinate_promotion.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/distance_cross_track.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/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 closest_points\n{\n\ntemplate\n<\n    typename CalculationType = void,\n    typename Strategy = distance::comparable::haversine<double, CalculationType>\n>\nclass cross_track\n{\npublic:\n    template <typename Point, typename PointOfSegment>\n    struct calculation_type\n        : promote_floating_point\n          <\n              typename select_calculation_type\n                  <\n                      Point,\n                      PointOfSegment,\n                      CalculationType\n                  >::type\n          >\n    {};\n\n    using radius_type = typename Strategy::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    template <typename Point, typename PointOfSegment>\n    inline auto apply(Point const& p, \n                      PointOfSegment const& sp1, \n                      PointOfSegment const& sp2) const\n    {\n        using CT = typename calculation_type<Point, PointOfSegment>::type;\n        \n        // http://williams.best.vwh.net/avform.htm#XTE\n        CT 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 sp1;\n        }\n\n        CT d1 = m_strategy.apply(sp1, p);\n        CT d2 = m_strategy.apply(sp2, p);\n\n        auto d_crs_pair = distance::detail::compute_cross_track_pair<CT>::apply(\n            p, sp1, sp2);\n\n        // d1, d2, d3 are in principle not needed, only the sign matters\n        CT projection1 = cos(d_crs_pair.first) * d1 / d3;\n        CT projection2 = cos(d_crs_pair.second) * 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<CT>() << std::endl;\n        std::cout << \"Course \" << dsv(sp1) << \" to \" << dsv(sp2) << \" \"\n                  << crs_AB * geometry::math::r2d<CT>() << std::endl;\n        std::cout << \"Course \" << dsv(sp2) << \" to \" << dsv(sp1) << \" \"\n                  << crs_BA * geometry::math::r2d<CT>() << std::endl;\n        std::cout << \"Course \" << dsv(sp2) << \" to \" << dsv(p) << \" \"\n                  << crs_BD * geometry::math::r2d<CT>() << std::endl;\n        std::cout << \"Projection AD-AB \" << projection1 << \" : \"\n                  << d_crs1 * geometry::math::r2d<CT>() << std::endl;\n        std::cout << \"Projection BD-BA \" << projection2 << \" : \"\n                  << d_crs2 * geometry::math::r2d<CT>() << 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            CT 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            auto distance = distance::detail::compute_cross_track_distance::apply(\n                d_crs_pair.first, d1);\n\n            CT lon1 = geometry::get_as_radian<0>(sp1);\n            CT lat1 = geometry::get_as_radian<1>(sp1);\n            CT lon2 = geometry::get_as_radian<0>(sp2);\n            CT lat2 = geometry::get_as_radian<1>(sp2);\n\n            CT dist = CT(2) * asin(math::sqrt(distance)) * m_strategy.radius();\n            CT dist_d1 = CT(2) * asin(math::sqrt(d1)) * m_strategy.radius();\n            \n            // Note: this is similar to spherical computation in geographic\n            // point_segment_distance formula\n            CT earth_radius = m_strategy.radius();\n            CT cos_frac = cos(dist_d1 / earth_radius) / cos(dist / earth_radius);\n            CT s14_sph = cos_frac >= 1 \n                ? CT(0) : cos_frac <= -1 ? math::pi<CT>() * earth_radius\n                                         : acos(cos_frac) * earth_radius;\n\n            CT a12 = geometry::formula::spherical_azimuth<>(lon1, lat1, lon2, lat2);\n            auto res_direct = geometry::formula::spherical_direct\n                <\n                    true,\n                    false\n                >(lon1, lat1, s14_sph, a12, srs::sphere<CT>(earth_radius));\n\n            model::point\n                <\n                    CT,\n                    dimension<PointOfSegment>::value,\n                    typename coordinate_system<PointOfSegment>::type\n                > cp;\n            \n            geometry::set_from_radian<0>(cp, res_direct.lon2);\n            geometry::set_from_radian<1>(cp, res_direct.lat2);\n\n            return cp;\n        }\n        else\n        {\n#ifdef BOOST_GEOMETRY_DEBUG_CROSS_TRACK\n            std::cout << \"Projection OUTSIDE the segment\" << std::endl;\n#endif\n            return d1 < d2 ? sp1 : sp2;\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 strategy::closest_points\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_SPHERICAL_CLOSEST_POINTS_CROSS_TRACK_HPP\n", "meta": {"hexsha": "c4c9143964e6c64f59eaa1427a7ce25bfdfa776d", "size": 6891, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AqooleEngine/src/main/cpp/boost/boost/geometry/strategies/spherical/closest_points_pt_seg.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/geometry/strategies/spherical/closest_points_pt_seg.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/geometry/strategies/spherical/closest_points_pt_seg.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": 34.2835820896, "max_line_length": 88, "alphanum_fraction": 0.5872877667, "num_tokens": 1714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.28220297409941886}}
{"text": "/* Copyright (C) 2017 IBM Corp.\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, \n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n * either express or implied. See the License for the specific\n * language governing permissions and limitations under the License.\n */\n/*****************************************************************************\n obfus.cpp - implementing NFA obfuscation\n *****************************************************************************/\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <stdexcept>\n#include <sys/stat.h>\n#include <unistd.h>\n\n#include <cmath>\n#include \"DGaussSampler.h\"\n#include \"GGH15.h\"\n#include \"obfus.h\"\n#include \"CRTmatrix.h\"\n#include <NTL/mat_ZZ.h>\n#include <NTL/mat_lzz_p.h>\n#include <NTL/BasicThreadPool.h>\n\nNTL_CLIENT\n\n//#define PRINTDOT\n#ifdef PRINTDOT\n#define printDot cerr << \".\" << std::flush\n#else\n#define printDot\n#endif\n\n//#define DEBUG\n//#define DEBUGPRINT\n\nstatic void prepare4encoding(const NTL::Mat< NTL::Mat<long> >& trans,\n\t\t\t     Mat<GGH15ptxt>& mainGGH15ptxt,\n\t\t\t     Mat<GGH15ptxt>& dummyGGH15ptxt,\n\t\t\t     CRTmatrix& An, TDMatrixParams* params,\n\t\t\t     long nThreads);\nstatic void encodeBranch(const std::string& dirName,\n\t\t\t const Mat<GGH15ptxt>& branch,\n\t\t\t CRTmatrix& An, TDMatrixParams* params,\n\t\t\t SynchronizedPipe<GGH15node*>* inPipe=NULL,\n\t\t\t SynchronizedPipe<encPair>* outPipe=NULL);\nstatic void readNodesPipe(SynchronizedPipe<GGH15node*>& pipe,\n\t\t\t  const Mat<GGH15ptxt>& mainBranch,\n\t\t\t  const Mat<GGH15ptxt>& dummyBranch,\n\t\t\t  TDMatrixParams* params);\nstatic void writeEncodingPipe(SynchronizedPipe<encPair>& pipe);\nstatic GGH15node* getNode(long idx, TDMatrixParams* params);\nstatic void evalBranch(GGH15encoding& mainPathEnc,\n\t\t       const NTL::Vec<int>& indexes,\n\t\t       const NTL::Vec<long>& symbolString,\n\t\t       TDMatrixParams* params);\n\n// Obfuscate the given NFA and store the result in the directory 'name'\nvoid initObfuscateNFA(const std::string& dirName,\n                      const NTL::Mat< NTL::Mat<long> >& trans, long sec,\n\t\t      TDMatrixParams* params, bool bPipe, long threads)\n{\n    FHE_TIMER_START;\n\n    long L = trans.NumRows(); // BP-length, # of edges\n    if (L==0) return; // sanity check, nothing to do\n\n    // compute the parameters if they are not provided by caller\n    TDMatrixParams p;\n    if (params==NULL)\n    {\n        long e = 3;\n        long dim = trans[0][0].NumRows();\n\n#ifdef DEBUG //small parameters in DEBUG mode\n        long k = L;\n        p.init(dim+2, k, e);\n\n#else // \"real\" parameters in non-DEBUG mode\n        GGH15basicParams bp(COMP_GGH15PRMS, dim, L, sec, e);\n        p.init(bp.n, bp.k, bp.e, bp.m);\n#endif // DEBUG\n\n        params = &p; // pointer points to local p\n\n\tcout << \"m=\" << p.m << \", kFactors=\" << p.kFactors\n\t << \", n=\" << p.n << \", e=\" << p.e\n\t << \", sigmaX=\" << p.sigmaX << endl;\n    }\n    if (bPipe) {\n      pipedInit(dirName, *params, 2*L, threads);\n    } else {\n      SetNumThreads(threads);\n      initAllNodes(dirName, *params, 2*L);\n    }\n\n    // do actual obfuscation\n    obfuscateNFASavedNodes(dirName, trans, params, bPipe, threads);\n}\n\n\n// This is called after initAllNodes, so all the nodes are already\n// stored in dirName\nvoid obfuscateNFASavedNodes(const std::string& dirName,\n                            const NTL::Mat< NTL::Mat<long> >& trans,\n\t\t\t    TDMatrixParams* params, bool pipes, long nThreads)\n{\n    FHE_TIMER_START;\n\n    cout << \"obfuscating\\n\" << std::flush;\n\n    char cwdOrig[1024];\n    if (!getcwd(cwdOrig, sizeof(cwdOrig)))\n      throw std::logic_error(\"Cannot get current directory\");\n\n    long ret = chdir(dirName.c_str());  // move into the new directory\n    if (ret != 0) {\n      cout << \"   original directory was \"<<cwdOrig<<endl;\n      throw std::logic_error(\"Cannot change directory\");\n    }\n\n    // Encode each tranition matrix via two encoded randomized matrices\n\n    Mat<GGH15ptxt> mainGGH15ptxt, dummyGGH15ptxt; // main & dummy branches\n    CRTmatrix An;             // The A_n matrix (actually n-by-1 \"matrix\")\n\n    SetNumThreads(3); // For prepare we need 2, for encode we may need 3\n\n    // First randomize the transition matrices and read A_n\n    prepare4encoding(trans,mainGGH15ptxt,dummyGGH15ptxt,An,params,nThreads);\n\n    //Next encode the randomized matrices, one branch at a time\n\n    // FIXME: The piped implemtation below is fragile, relying on the reader\n    // to read the nodes in exactly the right order that the worker expect\n    // them. A more robust implementation would have the worker ask for a\n    // node and then the reader read that node, but it is a lot more work\n    // to implement this more robust solution (with pre-fetching).\n\n    if (pipes) {\n      SynchronizedPipe<GGH15node*> inPipe;\n      SynchronizedPipe<encPair> outPipe;\n      // \"fork\" three threads, reader, worker, and writer\n      EXEC_INDEX(3, index)\n      switch (index) {\n\n      case 0: // The \"reader thread, no multi-threading here\n\treadNodesPipe(inPipe,mainGGH15ptxt,dummyGGH15ptxt,params);\n\tinPipe.end();\n\tbreak;\n\n      case 1: // The \"worker\" thread, can be multi-threaded\n\tSetNumThreads((nThreads>2)? (nThreads-2) : 1);\n\tencodeBranch(dirName, mainGGH15ptxt, An, params, &inPipe, &outPipe);\n\tencodeBranch(dirName, dummyGGH15ptxt, An, params,&inPipe, &outPipe);\n\toutPipe.end();\n\t{GGH15node *tmp; inPipe.receive(tmp);} // clear end-of-pipe signal\n\tbreak;\n\n      case 2: // The \"writer thread\n\twriteEncodingPipe(outPipe);\n\tbreak;\n      }\n      EXEC_INDEX_END\n    }\n    else { // non-piped implementation\n      SetNumThreads(nThreads);\n      encodeBranch(dirName, mainGGH15ptxt, An, params);\n      encodeBranch(dirName, dummyGGH15ptxt, An, params);\n    }\n    // Restore working directory\n    if (!chdir(cwdOrig)) return; // ignore this value\n}\n\n\n//////\n//evalNFA gets a bitstring that defines the path\n//////\nbool evalNFA(const std::string& dirName, const Vec<long>& symbolString,\n             TDMatrixParams* params, long nThreads)\n{\n    FHE_TIMER_START;\n    long nEdges = symbolString.length();\n    assert(nEdges>0); // sanity check\n\n    char cwd[1024];\n    if (!getcwd(cwd, sizeof(cwd))) // store cwd before switching\n      throw std::logic_error(\"Cannot get current directory\");\n    if (chdir(dirName.c_str()) != 0)\n      throw std::logic_error(\"Cannot change directory \" + dirName);\n\n    // read the parameters from file, if not given\n    TDMatrixParams p;\n    if (params==NULL)\n    {\n        params = &p;\n        FILE* handle = fopen(\"params.dat\", \"rb\");\n        params->readFromFile(handle);\n        fclose(handle);\n    }\n\n    // The \"main\" path is 0,1,3,5,...,2*nSymbols-1,\n    // the \"dummy\" path is 0,2,4,..., 2*nSymbols-2, 2*nSymbols-1.\n    // First and last nodes are the same on both paths.\n\n    // Along each path we read the matrices that are determined by the\n    // symbols in symbolString. For example if symbolString is (0,2,1,...)\n    // then on the main path we read 0_1_0, 1_3_2, 3_5_1,...\n    // and on the dummy path we read 0_2_0, 2_4_2, 4_6_1,...\n\n    // Then we multiply the matrices along each path (getting two matrices\n    // relative to 0-to-(2*nSymbols-1)), subtract these matrices off of each\n    // other, and test if the result is a zero-encoding.\n\n    NTL::Vec<int> realIdx(INIT_SIZE, nEdges+1);\n    NTL::Vec<int> dummyIdx(INIT_SIZE, nEdges+1);\n    for (long i = nEdges-1; i>=0; --i) {\n      realIdx[i+1] = 2*i+1;\n      dummyIdx[i+1] = (i==nEdges-1)? (2*i +1) : (2*i +2);\n    }\n    realIdx[0] = dummyIdx[0] = 0;\n\n    // Multiply all matrices, from right to left. Note that rightmost\n    // matrices are m-by-1, middle matrices are m-by-m, and leftmost\n    // matrices are 7-by-m (?), so right-to-left product will always\n    // have a products of m-by-m X m-by-1.\n\n    GGH15encoding mainPathEnc;\n    GGH15encoding dummyPathEnc;\n\n    // No. of threads to allocate each branch\n    if (nThreads>2) nThreads /= 2;\n    else nThreads = 1;\n\n    SetNumThreads(3);\n    EXEC_INDEX(3, index)\n    switch (index) {\n    case 0: break; // Cannot multi-thread theard 0\n    case 1:\n      SetNumThreads(nThreads);\n      evalBranch(mainPathEnc, realIdx, symbolString, params);\n      break;\n    case 2:\n      SetNumThreads(nThreads);\n      evalBranch(dummyPathEnc, dummyIdx, symbolString, params);\n      break;\n    }\n    EXEC_INDEX_END\n\n    // subtract and check for zero encoding\n    mainPathEnc -= dummyPathEnc;\n\n    bool success = (mainPathEnc.fromNode()==0)\n      && (mainPathEnc.toNode()==2*nEdges-1)\n      && mainPathEnc.getData().isSmall();\n\n    if (chdir(cwd) != 0) { // restore working directory\n      cout << \"evalNFA: attempted return to \"<<cwd<<endl;\n      throw std::logic_error(\"Cannot change directory\");\n    }\n    return success;\n}\n\n//pipedInit forks two threads, one \"writer\" thread and the \"producer\" thread, which can be further multi-threaded\nbool pipedInit(const std::string& dirName, TDMatrixParams& p, long n,\n\t       long nThreads)\n{\n\n FHE_TIMER_START;\n\n  bool bsuccess=false;\n  SynchronizedPipe<nodePair> pipe;\n\n  // \"fork\" two thread\n  SetNumThreads(2);\n  EXEC_INDEX(2, index)\n    switch (index) {\n\n    case 0: // The \"writer thread, no multi-threading here\n      writeNodesToFile(pipe);\n      break;\n\n      // NOTE: Starting with NTL v9.10, the current thread\n      // always gets assigned index == 0. This can be convenient to know:\n      // the current thread's thread pool (which is thread_local) is already\n      // in use; however, the other threads' thread pools are not in use.\n      // Thus, if we want, the functions Process1, Process2, Process3 (below)\n      // could each independently call SetNumThreads to work with their own\n      // thread pools.\n\n    case 1:\n      SetNumThreads((nThreads>1)? (nThreads-1): 1);\n      bsuccess=initAllNodes(dirName, p, n, &pipe);\n      pipe.end();\n      // The \"producer\" thread, can be multi-threaded\n      break;\n    }\n  EXEC_INDEX_END\n\n    return bsuccess;\n}\n\n// p1 includes the transition matrix and a few extra random dimensions,\n// p2 includes the same random dimensions as p1 but the identity or\n// part of it instead of the transition matrix\nvoid randomizeTransitions(GGH15ptxt& p1, GGH15ptxt& p2,\n                          const NTL::Mat<long>& transition,\n                          long i, long j, long nSteps, long dim)\n{\n    FHE_TIMER_START;\n    // set the to,from indexes and the tags\n    p1.setFrom((i==0)? (2*i) : (2*i -1));\n    p1.setTo(2*i +1);\n\n    p2.setFrom(2*i);\n    p2.setTo((i==nSteps-1)? (2*i +1) : (2*i +2));\n\n    std::string tag = ToString(j);\n    p1.setTag(tag);\n    p2.setTag(tag);\n\n    // Set the data part of the plaintext\n    long extraDims = dim - transition.NumRows();  // how many extra dimensions\n    mat_l& p1Data = p1.getData();\n    mat_l& p2Data = p2.getData();\n    p1Data.SetDims(transition.NumRows()+extraDims,\n                   transition.NumCols()+extraDims);\n    p2Data.SetDims(transition.NumRows()+extraDims,\n                   transition.NumCols()+extraDims);\n    clear(p1Data);\n    clear(p2Data);\n\n    // Copy the transition matrix to p1\n    for (long ii=0; ii<transition.NumRows(); ii++)\n        for (long jj=0; jj<transition.NumCols(); jj++)\n            p1Data[ii][jj] = (long) transition[ii][jj];\n\n    // Set p2 as the identity or part of it\n    long smallDim = min(transition.NumRows(), transition.NumCols());\n    if (i < nSteps-1) // all but the last step\n        for (long ii=0; ii<smallDim/2; ii++) p2Data[ii][ii] = 1;\n    if (i > 0)      // all but the first step\n        for (long ii=smallDim/2; ii<smallDim; ii++) p2Data[ii][ii] = 1;\n\n    // Choose a small random matrix and store in the extra dimensions of p1,p2\n    mat_l rand;\n    setSmall(rand, extraDims, extraDims, /*sigma=*/256);\n    for (long ii=0; ii<extraDims; ii++) for (long jj=0; jj<extraDims; jj++)\n        {\n            long row = ii + transition.NumRows();\n            long col = jj + transition.NumCols();\n            p1Data[row][col] = p2Data[row][col] = rand[ii][jj];\n        }\n}\n\n/* Function creates a new sub-directory and moves into it. it then creates\n * a binary file \"params.dat\", opens it and writes the values of p into it.\n * At the end, it moves back to the initial directory.\n */\nlong saveParamstoNewDir(const std::string& dirName, TDMatrixParams& p)\n{\n    FHE_TIMER_START;\n#if defined(_WIN32) // Windows mkdir takes only one parameter\n    int ret = mkdir(dirName.c_str());\n#else               // *nix mkdir takes two parameters\n    int ret = mkdir(dirName.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);\n#endif\n\n    char cwdOrig[1024];\n    if (!getcwd(cwdOrig, sizeof(cwdOrig)))\n      throw std::logic_error(\"Cannot get current directory\");\n    ret = chdir(dirName.c_str());  // move into the new directory\n    if (ret != 0) {\n      cout << \"saveParamstoNewDir: attempted chdir to \"<<dirName<<endl;\n      throw std::logic_error(\"Cannot change directory\");\n    }\n    FILE* handle = fopen(\"params.dat\", \"wb\"); // binary file, open for writing\n    long count = p.writeToFile(handle);        // write parameters to file\n    fclose(handle);\n\n    ret = chdir(cwdOrig);\n    if (ret != 0) {\n      cout << \"saveParamstoNewDir: attempted return to \"<<cwdOrig<<endl;\n      throw std::logic_error(\"Cannot change directory\");\n    }\n    return count;\n}\n\n\n//create a random transitions file - for debug purposes,\nlong makeRandomBP(std::string dirName, std::string name, long dim, long sig, long L)\n{\n    Mat< Mat<long> > trans(INIT_SIZE, L, sig);\n    for (long i=0; i<L; i++) for (long iSig=0; iSig<sig; iSig++) {\n\tMat<long>& M = trans[i][iSig];\n\tM.SetDims(dim,dim);\n\tif (NTL::RandomBnd(L)==0) clear(M);\n\telse\n\t  for (long row=0; row<dim; row++) for (long col=0; col<dim; col++) {\n\t      M[row][col] = NTL::RandomBnd(2);\n\t    }\n      }\n\n    // Write the transitions matrices to file\n\n    std::string filename = dirName + \"/\" + name + \"_dim\" + ToString(dim)\n                           + \"_sig\" + ToString(sig) + \"_L\" + ToString(L)\n                           + \".txt\";\n    std::fstream fs;\n    fs.open(filename.c_str(), std::ios::out); // E.g., \"BPs/P_dim2_sig2_L3.txt\"\n    if (!fs.is_open()) {\n        char cwd[1024];\n        if (getcwd(cwd, sizeof(cwd)))\n          throw std::logic_error(\"Cannot get current directory\");\n        std::cout << \"Cannot open input file \"<< filename\n\t\t  << \", working directory=\" << cwd << endl;\n        exit(0);\n    }\n    fs << trans << endl;\n    fs.close();\n\n    return 0;\n}\n\n// Read the A_n matrix from disk and randomize transition matrices\nstatic void prepare4encoding(const NTL::Mat< NTL::Mat<long> >& trans,\n\t\t\t     Mat<GGH15ptxt>& mainGGH15ptxt,\n\t\t\t     Mat<GGH15ptxt>& dummyGGH15ptxt,\n\t\t\t     CRTmatrix& An, TDMatrixParams* params,\n\t\t\t     long nThreads)\n{\n    long L = trans.NumRows(); // # of steps\n    long nLoops = L*trans.NumCols();\n    FILE* handle;\n\n    mainGGH15ptxt.SetDims(L, trans.NumCols()); //main branch\n    dummyGGH15ptxt.SetDims(L,trans.NumCols()); //dummy branch\n\n    // \"fork\" two threads, one for reading An, one for randomizing matrices\n    EXEC_INDEX(2, index)\n    switch (index) {\n\n    case 0: //read An\n      handle = fopen(\"nAn.dat\", \"rb\");\n      if (handle == 0) NTL::Error(\"Cannot read An\");\n      else {\n\tlong nn; // nn not used for anything\n        fread(&nn, sizeof(nn),1, handle);\n\tAn.readFromFile(handle, params);\n\tfclose(handle);\n      }\n      break;\n\n    case 1: // randomize transition matrices, multi-threaded\n      SetNumThreads((nThreads>1)? (nThreads-1) : 1);\n      EXEC_RANGE(nLoops, first, last);\n      for (long iLoop = first; iLoop < last; iLoop++) {\n\n        // represent each transition matrix by two randomized matrices,\n        // one on the main path and the other on the dummy path\n\n        long j = iLoop % trans.NumCols();   //i = step, j = trans.col\n        long i = (iLoop - j) / trans.NumCols();\n\n        GGH15ptxt& p1=mainGGH15ptxt[i][j];\n        GGH15ptxt& p2=dummyGGH15ptxt[i][j];\n\n\t//we chose the from and to in the following manner:\n        p1.setFrom((i==0)? (2*i) : (2*i -1));\n        p1.setTo(2*i +1);\n        p2.setFrom(2*i);\n        p2.setTo((i==L-1)? (2*i +1) : (2*i +2));\n        randomizeTransitions(p1, p2, trans[i][j], i, j, L, params->n);\n      } //create all ptxt matrices\n      EXEC_RANGE_END\n    }\n    EXEC_INDEX_END\n}\n\nstatic void encodeBranch(const std::string& dirName,\n\t\t\t const Mat<GGH15ptxt>& branch,\n\t\t\t CRTmatrix& An, TDMatrixParams* params,\n\t\t\t SynchronizedPipe<GGH15node*>* inPipe,\n\t\t\t SynchronizedPipe<encPair>* outPipe)\n{\n    assert(branch.NumRows()>0 && branch.NumCols()>0);\n\n    GGH15node *toNode=NULL, *fromNode=NULL;\n    TaggedCRTmatrix mat1;\n    GGH15encoding* enc;\n\n    long lastNode = branch[branch.NumRows()-1][0].getTo();\n    for (long i=0; i<branch.NumRows(); i++) {\n      long from = branch[i][0].getFrom();\n      long to = branch[i][0].getTo();\n\n      // Read from disk the next node that's needed for this step\n      if (to >= lastNode) toNode =NULL; // no toNode for last-step encoding\n      else if (inPipe != NULL)\n        assert(inPipe->receive(toNode));// get node from pipe, failure forbidden\n      else\n        toNode = getNode(to, params);   // read it yourself\n\n      // Encode all matrices wrt from -> to, one per alphabet symbol\n      for (long j=0; j<branch.NumCols(); j++) {\n\tenc = new(GGH15encoding);\n\tencodeMatrix(dirName, *enc, branch[i][j].getData(), from, to,\n                     fromNode, toNode, An, &mat1, params, lastNode+1);\n\t// When from==0, encodeMatrix does not use the pointer fromNode\n\n\t// Write the encoded matrices to disk\n\tstd::string FileName = ToString(from)+\"_\"+ToString(to)+\"_\"\n                               + branch[i][j].getTag()+\".dat\";\n\tFILE* handle = fopen((const char*)FileName.c_str(), \"wb\");\n\tif (handle==0) NTL::Error(\"Cannot write encoding to disk\");\n\n\tif (outPipe!=NULL) { // Send matrix over pipe to be written\n\t  encPair ePair(handle,enc);\n\t  outPipe->send(ePair);\n\t} else {             // write it yourself\n\t  enc->writeToFile(handle);\n\t  fclose(handle);\n\t  delete enc;\n\t}\n      }\n      if (fromNode!=NULL) delete fromNode;\n      fromNode = toNode;\n    }\n}\n\nstatic void readNodesPipe(SynchronizedPipe<GGH15node*>& pipe,\n\t\t\t  const Mat<GGH15ptxt>& mainBranch,\n\t\t\t  const Mat<GGH15ptxt>& dummyBranch,\n\t\t\t  TDMatrixParams* params)\n{\n  GGH15node *node;\n  // First read the nodes on the main branch in order\n  long lastNode = mainBranch[mainBranch.NumRows()-1][0].getTo();\n  for (long i=0; i<mainBranch.NumRows(); i++) {\n    long to = mainBranch[i][0].getTo();\n    if (to >= lastNode) break;\n    node = getNode(to, params);\n    pipe.send(node);\n  }\n  // Next read the nodes on the dummy branch in order\n  lastNode = dummyBranch[mainBranch.NumRows()-1][0].getTo();\n  for (long i=0; i<dummyBranch.NumRows(); i++) {\n    long to = dummyBranch[i][0].getTo();\n    if (to >= lastNode) break;\n    node = getNode(to, params);\n    pipe.send(node);\n  }\n}\n\nstatic void writeEncodingPipe(SynchronizedPipe<encPair>& pipe)\n{\n  GGH15encoding* enc;\n  FILE* handle;\n  encPair ePair;\n\n  while (true) {\n    if (!pipe.receive(ePair)) break;\n    handle = ePair.a;\n    enc = ePair.b;\n    enc->writeToFile(handle);\n    delete(enc);\n    fclose(handle);\n  }\n}\n\nstatic GGH15node* getNode(long idx, TDMatrixParams* params)\n{\n  std::string fileName = \"node\"+ToString(idx)+ \".dat\";\n  FILE* handle = fopen(fileName.c_str(), \"rb\");\n  if (handle==0) NTL::Error(\"Cannot open node file on disk\");\n  GGH15node* node = new GGH15node();\n  node->readFromFile(handle, params);\n  fclose(handle);\n  return node;\n}\n\nstatic void evalBranch(GGH15encoding& mainPathEnc,\n\t\t       const NTL::Vec<int>& indexes,\n\t\t       const NTL::Vec<long>& symbolString,\n\t\t       TDMatrixParams* params)\n{\n  long nEdges = indexes.length()-1;\n  for (long i = nEdges-1; i>=0; --i) {\n    GGH15encoding cc;\n\n    long from1 = indexes[i];\n    long to1   = indexes[i+1];\n    std::string fName1 = ToString(from1) + \"_\"\n      + ToString(to1) + \"_\" + ToString(symbolString[i]) + \".dat\";\n\n    // read encodings from files and multiply into the path encodings\n\n    FILE* handle = fopen(fName1.c_str(), \"rb\");\n    if (handle == NULL) // error\n      throw std::logic_error(\"Cannot open file \" + fName1);\n\n    if (i == nEdges-1) // read directly to mainPathEnc\n      mainPathEnc.readFromFile(handle, *params);\n    else {       // multiply into mainPathEnc\n      cc.readFromFile(handle, *params);\n      mainPathEnc.leftMultBy(cc);\n    }\n    fclose(handle);\n  }\n}\n", "meta": {"hexsha": "0e19f0f688a7ad67fe10457e694a12ab23af046a", "size": 20604, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "obfus.cpp", "max_stars_repo_name": "shaih/BPobfus", "max_stars_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-09-25T14:37:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-11T03:19:43.000Z", "max_issues_repo_path": "obfus.cpp", "max_issues_repo_name": "shaih/BPobfus", "max_issues_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "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": "obfus.cpp", "max_forks_repo_name": "shaih/BPobfus", "max_forks_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-12-23T04:03:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-12T07:42:29.000Z", "avg_line_length": 33.3938411669, "max_line_length": 113, "alphanum_fraction": 0.63177053, "num_tokens": 5775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.63341024983754, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2822029740994188}}
{"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/Norm/PAlphaTilde.h\"\n#include \"latbuilder/WeightsDispatcher.h\"\n#include \"latbuilder/Util.h\"\n\n#include \"latticetester/CoordinateSets.h\"\n\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/math/tools/polynomial.hpp>\n#include <vector>\n#include <cmath>\n\nnamespace LatBuilder { namespace Norm {\n\nnamespace SumHelperPAlphaTilde{\n\n   template <typename WEIGHTS>\n   struct SumHelper {\n      Real operator()(\n            const WEIGHTS& weights,\n            Real normType,\n            Real lambda,\n            Dimension dimension,\n            unsigned int alpha\n            ) const\n      {\n         std::cerr << \"warning: using default implementation of SumHelper\" << std::endl;\n         Real val = 0.0;\n         Real mu = pow(2.0, alpha * lambda) / (pow(2.0, alpha * lambda) - 2);\n         LatticeTester::CoordinateSets::FromRanges csets(1, dimension, 0, dimension - 1);\n         for (const auto& proj : csets) {\n            Real weight = weights.getWeight(proj);\n            if (weight)\n               // weights are assumed to already be to the power normType; map\n               // them to power 2\n               val += intPow(mu, proj.size()) * pow(weight, lambda * 2 / normType);\n         }\n         return val;\n      }\n   };\n\n\n#define DECLARE_PALPHA_PLR_SUM(weight_type) \\\n      template <> \\\n      class SumHelper<weight_type> { \\\n      public: \\\n         Real operator()( \\\n               const weight_type& weights, \\\n               Real normType, \\\n               Real lambda, \\\n               Dimension dimension, \\\n               unsigned int alpha \\\n               ) const; \\\n      }\\\n\n   DECLARE_PALPHA_PLR_SUM(LatticeTester::ProjectionDependentWeights);\n   DECLARE_PALPHA_PLR_SUM(LatticeTester::OrderDependentWeights);\n   DECLARE_PALPHA_PLR_SUM(LatticeTester::ProductWeights);\n   DECLARE_PALPHA_PLR_SUM(LatticeTester::PODWeights);\n   DECLARE_PALPHA_PLR_SUM(LatBuilder::CombinedWeights);\n\n#undef DECLARE_PALPHA_PLR_SUM\n\n   //===========================================================================\n   // combined weights\n   //===========================================================================\n\n   // Separating sumCombined() from\n   // SumHelper<LatBuilder::CombinedWeights>::operator() is a workaround for\n   // LLVM/clang++.\n   Real sumCombined(\n         const CombinedWeights& weights,\n         Real normType,\n         Real lambda,\n         Dimension dimension,\n         unsigned int alpha\n         )\n   {\n      Real val = 0.0;\n      for (const auto& w : weights.list())\n         val += WeightsDispatcher::dispatch<SumHelper>(*w, normType, lambda * 2 / normType, dimension, alpha);\n      return val;\n   }\n\n   Real SumHelper<LatBuilder::CombinedWeights>::operator()(\n         const CombinedWeights& weights,\n         Real normType,\n         Real lambda,\n         Dimension dimension,\n         unsigned int alpha\n         ) const\n   {\n      return sumCombined(weights, normType, lambda, dimension, alpha);\n   }\n\n\n   //===========================================================================\n   // projection-dependent weights\n   //===========================================================================\n\n   Real SumHelper<LatticeTester::ProjectionDependentWeights>::operator()(\n         const LatticeTester::ProjectionDependentWeights& weights,\n         Real normType,\n         Real lambda,\n         Dimension dimension,\n         unsigned int alpha\n         ) const\n   {\n      Real val = 0.0;\n      Real mu = pow(2.0, alpha * lambda) / (pow(2.0, alpha * lambda) - 2);\n      for (Dimension largestIndex = 0; largestIndex < dimension; largestIndex++) {\n         // iterate only through projections that have a weight\n         for (const auto& pw : weights.getWeightsForLargestIndex(largestIndex)) {\n            const auto& proj = pw.first;\n            const auto& weight = pw.second;\n            if (weight)\n               // weights are assumed to already be to the power normType; map\n               // them to power 2\n               val += intPow(mu, proj.size()) * pow(weight, lambda * 2 / normType);\n         }\n      }\n      return val;\n   }\n\n\n   //===========================================================================\n   // order-dependent weights\n   //===========================================================================\n\n   Real SumHelper<LatticeTester::OrderDependentWeights>::operator()(\n         const LatticeTester::OrderDependentWeights& weights,\n         Real normType,\n         Real lambda,\n         Dimension dimension,\n         unsigned int alpha\n         ) const\n   {\n      Real val = 0.0;\n      Real mu = pow(2.0, alpha * lambda) / (pow(2.0, alpha * lambda) - 2);\n      for (Dimension order = 1; order <= dimension; order++) {\n         Real weight = weights.getWeightForOrder(order);\n         if (weight)\n               // weights are assumed to already be to the power normType; map\n               // them to power 2\n            val += boost::math::binomial_coefficient<double>((unsigned int)dimension, (unsigned int)order) * std::pow(weight, lambda * 2.0 / normType) * intPow(mu, order);\n      }\n      return val;\n   }\n\n\n   //===========================================================================\n   // product weights\n   //===========================================================================\n\n   Real SumHelper<LatticeTester::ProductWeights>::operator()(\n         const LatticeTester::ProductWeights& weights,\n         Real normType,\n         Real lambda,\n         Dimension dimension,\n         unsigned int alpha\n         ) const\n   {\n      Real val = 1.0;\n      Real mu = pow(2.0, alpha * lambda) / (pow(2.0, alpha * lambda) - 2);\n      for (Dimension coord = 0; coord < dimension; coord++) {\n         Real weight = weights.getWeightForCoordinate(coord);\n         if (weight)\n               // weights are assumed to already be to the power normType; map\n               // them to power 2\n            val *= 1.0 + mu * std::pow(weight, lambda * 2 / normType);\n      }\n      val -= 1.0;\n      return val;\n   }\n\n\n   //===========================================================================\n   // POD weights\n   //===========================================================================\n\n   Real SumHelper<LatticeTester::PODWeights>::operator()(\n         const LatticeTester::PODWeights& weights,\n         Real normType,\n         Real lambda,\n         Dimension dimension,\n         unsigned int alpha\n         ) const\n   {\n      Real mu = pow(2.0, alpha * lambda) / (pow(2.0, alpha * lambda) - 2);\n\n      typedef boost::math::tools::polynomial<double> RealPolynomial;\n\n      RealPolynomial acc{1.0};\n      Real val = 0.0;\n      for(Dimension coord = 0; coord < dimension; ++coord)\n      {\n            acc *= RealPolynomial{{pow(weights.getWeightForCoordinate(coord), lambda * 2 / normType) * mu, 1.0}};\n      }\n      for(Dimension degree = 0; degree < dimension; ++degree)\n      {\n            val += acc[degree] * pow(weights.getWeightForOrder(dimension - degree), lambda * 2 / normType) ;\n      }\n      return val;\n   }\n\n}\n\nPAlphaTilde::PAlphaTilde(unsigned int alpha, const LatticeTester::Weights& weights, Real normType):\n   NormAlphaBase<PAlphaTilde>(alpha, normType),\n   m_weights(weights)\n{}\n\ntemplate <LatticeType LR, EmbeddingType L>\nReal PAlphaTilde::value(\n      Real lambda,\n      const SizeParam<LR, L>& sizeParam,\n      Dimension dimension,\n      Real norm\n      ) const\n{\n   norm = 2.0 / (norm * sizeParam.numPoints());\n   Real val = WeightsDispatcher::dispatch<SumHelperPAlphaTilde::SumHelper>(\n         m_weights,\n         this->normType(),\n         lambda,\n         dimension,\n         alpha()\n         );\n\n   return std::pow(norm * val, 1.0 / lambda);\n}\n\ntemplate Real PAlphaTilde::value<LatticeType::ORDINARY, EmbeddingType::UNILEVEL>(Real, const SizeParam<LatticeType::ORDINARY, EmbeddingType::UNILEVEL>&, Dimension, Real) const;\ntemplate Real PAlphaTilde::value<LatticeType::ORDINARY, EmbeddingType::MULTILEVEL>(Real, const SizeParam<LatticeType::ORDINARY, EmbeddingType::MULTILEVEL>&, Dimension, Real) const;\n\ntemplate Real PAlphaTilde::value<LatticeType::POLYNOMIAL, EmbeddingType::UNILEVEL>(Real, const SizeParam<LatticeType::POLYNOMIAL, EmbeddingType::UNILEVEL>&, Dimension, Real) const;\ntemplate Real PAlphaTilde::value<LatticeType::POLYNOMIAL, EmbeddingType::MULTILEVEL>(Real, const SizeParam<LatticeType::POLYNOMIAL, EmbeddingType::MULTILEVEL>&, Dimension, Real) const;\n\n}}\n", "meta": {"hexsha": "77ea5c57fac2b9096c5077ec34f2b709595916d2", "size": 9130, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/LatBuilder/Norm/PAlphaPLR.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/Norm/PAlphaPLR.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/Norm/PAlphaPLR.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": 35.8039215686, "max_line_length": 184, "alphanum_fraction": 0.573713034, "num_tokens": 2077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.28219201457598425}}
{"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 <boost/python.hpp>\n\n#include \"curve.hpp\"\n#include \"point.hpp\"\n#include \"frechet.hpp\"\n#include \"jl_transform.hpp\"\n#include \"clustering.hpp\"\n#include \"coreset.hpp\"\n#include \"grid.hpp\"\n#include \"simplification.hpp\"\n#include \"dynamic_time_warping.hpp\"\n\nusing namespace boost::python;\nnamespace np = boost::python::numpy;\nnamespace fc = Frechet::Continuous;\nnamespace fd = Frechet::Discrete;\nnamespace ddtw = Dynamic_Time_Warping::Discrete;\n\nconst distance_t default_epsilon = 0.001;\n\nfc::Distance continuous_frechet(const Curve &curve1, const Curve &curve2) { \n    return fc::distance(curve1, curve2);\n}\n\nfd::Distance discrete_frechet(const Curve &curve1, const Curve &curve2) {\n    return fd::distance(curve1, curve2);\n}\n\nddtw::Distance discrete_dynamic_time_warping(const Curve &curve1, const Curve &curve2) {\n    return ddtw::distance(curve1, curve2);\n}\n\nCurves jl_transform(const Curves &in, const double epsilon, const bool empirical_constant = true) {\n    \n    Curves curvesrp = JLTransform::transform_naive(in, epsilon, empirical_constant);\n    \n    return curvesrp;\n}\n\nBOOST_PYTHON_FUNCTION_OVERLOADS(jl_transform_overloads, jl_transform, 2, 3);\n\nvoid set_frechet_epsilon(const double eps) {\n    fc::epsilon = eps;\n}\n\nvoid set_frechet_rounding(const bool round) {\n    fc::round = round;\n}\n\ndistance_t get_frechet_epsilon() {\n    return fc::epsilon;\n}\n\nbool get_frechet_rounding() {\n    return fc::round;\n}\n\nClustering::Clustering_Result dtw_one_median(const Curves &in) {\n    auto result = Clustering::two_two_dtw_one_two_median(in);\n    return result;\n}\n\nClustering::Clustering_Result dtw_one_median_exact(const Curves &in) {\n    auto result = Clustering::two_two_dtw_one_two_median_exact(in);\n    return result;\n}\n\nClustering::Clustering_Result klcenter_multi(const curve_number_t num_centers, const curve_size_t ell, const Curves &in, Clustering::Distance_Matrix &distances, const Curves &center_domain = Curves(), const bool random_start_center = true) {\n    auto result = Clustering::gonzalez(num_centers, ell, in, distances, false, center_domain, random_start_center);\n    return result;\n}\n\nBOOST_PYTHON_FUNCTION_OVERLOADS(klcenter_multi_overloads, klcenter_multi, 4, 6);\n\nClustering::Clustering_Result klcenter(const curve_number_t num_centers, const curve_size_t ell, const Curves &in, const Curves &center_domain = Curves(), const bool random_start_center = true) {\n    Clustering::Distance_Matrix distances;\n    auto result = Clustering::gonzalez(num_centers, ell, in, distances, false, center_domain, random_start_center);\n    return result;\n}\n\nBOOST_PYTHON_FUNCTION_OVERLOADS(klcenter_overloads, klcenter, 3, 5);\n\nClustering::Clustering_Result klmedian_multi(const curve_number_t num_centers, const curve_size_t ell, const Curves &in, Clustering::Distance_Matrix distances, const Curves &center_domain = Curves()) {\n\n    auto result = Clustering::arya(num_centers, ell, in, distances, center_domain);\n    \n    return result;\n}\n\nBOOST_PYTHON_FUNCTION_OVERLOADS(klmedian_multi_overloads, klmedian_multi, 4, 5);\n\nClustering::Clustering_Result klmedian(const curve_number_t num_centers, const curve_size_t ell, const Curves &in, const Curves &center_domain = Curves()) {\n\n    auto distances = Clustering::Distance_Matrix();\n    auto result = Clustering::arya(num_centers, ell, in, distances, center_domain);\n    \n    return result;\n}\n\nBOOST_PYTHON_FUNCTION_OVERLOADS(klmedian_overloads, klmedian, 3, 4);\n\n// Clustering::Clustering_Result onemedian_sampling(const curve_size_t ell,  Curves &in, const double epsilon, const bool with_assignment = false, const Curves &center_domain = Curves()) {\n//     \n//     auto result = Clustering::one_median_sampling(ell, in, epsilon, with_assignment);\n//     \n//     return result;\n// }\n// \n// BOOST_PYTHON_FUNCTION_OVERLOADS(onemedian_sampling_overloads, onemedian_sampling, 3, 5);\n// \n// Clustering::Clustering_Result onemedian_exhaustive(const curve_size_t ell,  Curves &in, const bool with_assignment = false, const Curves &center_domain = Curves()) {\n// \n//     auto result = Clustering::one_median_exhaustive(ell, in, with_assignment);\n//     \n//     return result;\n// }\n// \n// BOOST_PYTHON_FUNCTION_OVERLOADS(onemedian_exhaustive_overloads, onemedian_exhaustive, 2, 4);\n// \n// \n// Coreset::Onemedian_Coreset onemedian_coreset(const Curves &in, const curve_size_t ell, const double epsilon, const double constant = 1) {\n//     return Coreset::Onemedian_Coreset(ell, in, epsilon, constant);\n// }\n// \n// BOOST_PYTHON_FUNCTION_OVERLOADS(onemedian_coreset_overloads, onemedian_coreset, 3, 4);\n\nCurve weak_minimum_error_simplification(const Curve &curve, const curve_size_t l) {\n    Simplification::Subcurve_Shortcut_Graph graph(const_cast<Curve&>(curve));\n    auto scurve = graph.weak_minimum_error_simplification(l);\n    scurve.set_name(\"Simplification of \" + curve.get_name());\n    return scurve;\n}\n\nCurve approximate_weak_minimum_link_simplification(const Curve &curve, const distance_t epsilon) {\n    auto scurve = Simplification::approximate_weak_minimum_link_simplification(curve, epsilon);\n    scurve.set_name(\"Simplification of \" + curve.get_name());\n    return scurve;\n}\n\nCurve approximate_weak_minimum_error_simplification(const Curve &curve, const curve_size_t ell) {\n    auto scurve = Simplification::approximate_weak_minimum_error_simplification(curve, ell);\n    scurve.set_name(\"Simplification of \" + curve.get_name());\n    return scurve;\n}\n\nvoid set_number_threads(std::uint64_t number) {\n    omp_set_dynamic(0);\n    omp_set_num_threads(number);\n}\n\nBOOST_PYTHON_MODULE(backend)\n{\n    Py_Initialize();\n    np::initialize();\n    \n    scope().attr(\"default_epsilon_continuous_frechet\") = default_epsilon;\n    \n    class_<Point>(\"Point\", init<dimensions_t>())\n        .def(\"__len__\", &Point::dimensions)\n        .def(\"__getitem__\", &Point::get)\n        .def(\"__str__\", &Point::str)\n        .def(\"__iter__\", iterator<Point>())\n        .def(\"__repr__\", &Point::repr)\n        .add_property(\"values\", &Point::as_ndarray)\n    ;\n    \n    class_<Points>(\"Points\", init<dimensions_t>())\n        .def(\"__len__\", &Points::number)\n        .def(\"__getitem__\", &Points::get, return_value_policy<reference_existing_object>())\n        .def(\"__str__\", &Points::str)\n        .def(\"__iter__\", iterator<Points>())\n        .def(\"__repr__\", &Points::repr)\n        .add_property(\"values\", &Points::as_ndarray)\n        .add_property(\"centroid\", &Points::centroid)\n    ;\n    \n    class_<Curve>(\"Curve\", init<np::ndarray>())\n        .def(init<np::ndarray, std::string>())\n        .add_property(\"dimensions\", &Curve::dimensions)\n        .add_property(\"complexity\", &Curve::complexity)\n        .add_property(\"name\", &Curve::get_name, &Curve::set_name)\n        .add_property(\"values\", &Curve::as_ndarray)\n        .add_property(\"centroid\", &Curve::centroid)\n        .def(\"__getitem__\", &Curve::get, return_value_policy<reference_existing_object>())\n        .def(\"__pushcoordinate__\", &Curve::push_coordinate)\n        .def(\"__popback__\", &Curve::pop_back)\n        .def(\"__len__\", &Curve::complexity)\n        .def(\"__str__\", &Curve::str)\n        .def(\"__iter__\", iterator<Curve>())\n        .def(\"__repr__\", &Curve::repr)\n    ;\n        \n    class_<Curves>(\"Curves\", init<>())\n        .add_property(\"m\", &Curves::get_m)\n        .def(\"add\", &Curves::add)\n        .def(\"simplify\", &Curves::simplify)\n        .def(\"__getitem__\", &Curves::get, return_value_policy<reference_existing_object>())\n        .def(\"__len__\", &Curves::number)\n        .def(\"__str__\", &Curves::str)\n        .def(\"__iter__\", iterator<Curves>())\n        .def(\"__repr__\", &Curves::repr)\n    ;\n    \n    class_<fc::Distance>(\"Continuous_Frechet_Distance\", init<>())\n        .add_property(\"time_searches\", &fc::Distance::time_searches)\n        .add_property(\"time_bounds\", &fc::Distance::time_bounds)\n        .add_property(\"number_searches\", &fc::Distance::number_searches)\n        .add_property(\"value\", &fc::Distance::value)\n        .def(\"__repr__\", &fc::Distance::repr)\n    ;\n    \n    class_<fd::Distance>(\"Discrete_Frechet_Distance\", init<>())\n        .add_property(\"time\", &fd::Distance::time)\n        .add_property(\"value\", &fd::Distance::value)\n        .def(\"__repr__\", &fd::Distance::repr)\n    ;\n    \n    class_<ddtw::Distance>(\"Discrete_Dynamic_Time_Warping_Distance\", init<>())\n        .add_property(\"time\", &ddtw::Distance::time)\n        .add_property(\"value\", &ddtw::Distance::value)\n        .def(\"__repr__\", &ddtw::Distance::repr)\n    ;\n    \n    class_<Clustering::Distance_Matrix>(\"Distance_Matrix\", init<>());\n    \n    class_<Clustering::Clustering_Result>(\"Clustering_Result\", init<>())\n        .add_property(\"value\", &Clustering::Clustering_Result::value)\n        .add_property(\"time\", &Clustering::Clustering_Result::running_time)\n        .add_property(\"assignment\", &Clustering::Clustering_Result::assignment)\n        .def(\"__getitem__\", &Clustering::Clustering_Result::get, return_value_policy<reference_existing_object>())\n        .def(\"__len__\", &Clustering::Clustering_Result::size)\n        .def(\"__iter__\", range(&Clustering::Clustering_Result::cbegin, &Clustering::Clustering_Result::cend))\n        .def(\"compute_assignment\", &Clustering::Clustering_Result::compute_assignment)\n    ;\n    \n    class_<Clustering::Cluster_Assignment>(\"Cluster_Assignment\", init<>())\n        .def(\"__len__\", &Clustering::Cluster_Assignment::size)\n        .def(\"count\", &Clustering::Cluster_Assignment::count)\n        .def(\"get\", &Clustering::Cluster_Assignment::get)\n    ;\n    \n    /*class_<Coreset::Onemedian_Coreset>(\"Onemedian_coreset\")\n        .add_property(\"lambd\", &Coreset::Onemedian_Coreset::get_lambda)\n        .add_property(\"Lambd\", &Coreset::Onemedian_Coreset::get_Lambda)\n        .add_property(\"cost\", &Coreset::Onemedian_Coreset::get_cost)\n        .def(\"curves\", &Coreset::Onemedian_Coreset::get_curves)\n    ;*/\n    \n    def(\"set_continuous_frechet_epsilon\", set_frechet_epsilon);\n    def(\"set_continuous_frechet_rounding\", set_frechet_rounding);\n    def(\"get_continuous_frechet_epsilon\", get_frechet_epsilon);\n    def(\"get_continuous_frechet_rounding\", get_frechet_rounding);\n    \n    def(\"continuous_frechet\", continuous_frechet);\n    def(\"discrete_frechet\", discrete_frechet);\n    def(\"discrete_dynamic_time_warping\", discrete_dynamic_time_warping);\n    \n    def(\"weak_minimum_error_simplification\", weak_minimum_error_simplification);\n    def(\"approximate_weak_minimum_link_simplification\", approximate_weak_minimum_link_simplification);\n    def(\"approximate_weak_minimum_error_simplification\", approximate_weak_minimum_error_simplification);\n    \n    def(\"dimension_reduction\", jl_transform, jl_transform_overloads());\n\n    def(\"discrete_klcenter\", klcenter, klcenter_overloads());\n    def(\"discrete_klmedian\", klmedian, klmedian_overloads());\n    def(\"discrete_klcenter_multi\", klcenter_multi, klcenter_multi_overloads());\n    def(\"discrete_klmedian_multi\", klmedian_multi, klmedian_multi_overloads());\n    \n    // these are experimental\n    def(\"two_two_dtw_one_two_median\", dtw_one_median);\n    def(\"two_two_dtw_one_two_median_exact\", dtw_one_median_exact);\n    //def(\"discrete_onemedian_sampling\", onemedian_sampling, onemedian_sampling_overloads());\n    //def(\"discrete_onemedian_exhaustive\", onemedian_exhaustive, onemedian_exhaustive_overloads());\n    //def(\"onemedian_coreset\", onemedian_coreset, onemedian_coreset_overloads());\n    \n    \n    def(\"set_maximum_number_threads\", set_number_threads);\n}\n", "meta": {"hexsha": "4723298e645a04f579d94d3bdf3f3be078232b60", "size": 12494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fred_python_wrapper.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/fred_python_wrapper.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/fred_python_wrapper.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": 43.23183391, "max_line_length": 460, "alphanum_fraction": 0.7261085321, "num_tokens": 3125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093882168609, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.28218340624493504}}
{"text": "/*\n\tThis program has been created by Stefan Zwaard, based on the work of Paul Baker. Current version: 0.5, 16-06-2020.\n\tThe (Distributed) Model Training and Aggregation (DMTLA) program allows for training and aggregation of SVM (HOG based) and ERT models.\n\tThe program is part of the EyeBlink Project, and works together with the Image processing and EAR calculation program to proces images using the newly created models.\n\tThe program was also used as a proof of concept and for results gathering for the proposed Mean Weight Matrix Aggregation (MWMA) distributed training for L-SVM models, and Weighted Bin Aggregation (WBA) distributed training of ERT models, \n\tin the paper: \"Privacy-Preserving Algorithms for Object Detection & Localization Using Distributed Machine Learning\".\n\tRunning the resulting program requires opencv_world400.dll to be present in the same folder. In order to compile this code, ensure both the OpenCV and DLib libraries are linked.\n\tAlways use the AVX extended instructions on Release x64 for best preformance of program\n*/\n\n\n#include <dlib/svm_threaded.h>\n#include <dlib/string.h>\n#include <dlib/gui_widgets.h>\n#include <dlib/image_processing.h>\n#include <dlib/data_io.h>\n#include <dlib/cmd_line_parser.h>\n#include <dlib/image_io.h>\n\n#include <iostream>\n#include <fstream>\n#include <stdlib.h>\n#include <stdio.h>\n#include <cstdio>\n#include <math.h>\n#include <string>\n#include <filesystem>\n\n#include \"Window.h\"\n#include \"CERT.h\"\n\n#include <dlib/image_processing/frontal_face_detector.h>\n#include <dlib/image_processing/render_face_detections.h>\n#include <dlib/image_keypoint/draw_surf_points.h>\n#include <opencv2/core/core.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/opencv.hpp>\n#include <dlib/opencv.h>\n\nusing namespace std;\nusing namespace cv;\nusing namespace dlib;\n\n// Define scnaner type for SVM training\ntypedef scan_fhog_pyramid<pyramid_down<6> > image_scanner_type;\n\n// Here follows a few function definitions from DLib for SVM and ERT training\n// ----------------------------------------------------------------------------------------\n\nstd::vector<std::vector<double> > get_interocular_distances(\n\tconst std::vector<std::vector<full_object_detection> >& objects\n);\n\nvoid pick_best_window_size(\n\tconst std::vector<std::vector<dlib::rectangle> >& boxes,\n\tunsigned long& width,\n\tunsigned long& height,\n\tconst unsigned long target_size\n)\n/*!\n\tensures\n\t\t- Finds the average aspect ratio of the elements of boxes and outputs a width\n\t\t  and height such that the aspect ratio is equal to the average and also the\n\t\t  area is equal to target_size.  That is, the following will be approximately true:\n\t\t\t- #width*#height == target_size\n\t\t\t- #width/#height == the average aspect ratio of the elements of boxes.\n!*/\n{\n\t// find the average width and height\n\trunning_stats<double> avg_width, avg_height;\n\tfor (unsigned long i = 0; i < boxes.size(); ++i)\n\t{\n\t\tfor (unsigned long j = 0; j < boxes[i].size(); ++j)\n\t\t{\n\t\t\tavg_width.add(boxes[i][j].width());\n\t\t\tavg_height.add(boxes[i][j].height());\n\t\t}\n\t}\n\n\t// Adjusting the box size sp it is about target_pizels pixels in size \n\tdouble size = avg_width.mean()*avg_height.mean();\n\tdouble scale = std::sqrt(target_size / size);\n\n\twidth = (unsigned long)(avg_width.mean()*scale + 0.5);\n\theight = (unsigned long)(avg_height.mean()*scale + 0.5);\n\t// make sure the width and height never round to zero.\n\tif (width == 0)\n\t\twidth = 1;\n\tif (height == 0)\n\t\theight = 1;\n}\n\n\n\nbool contains_any_boxes(\n\tconst std::vector<std::vector<dlib::rectangle> >& boxes\n)\n{\n\tfor (unsigned long i = 0; i < boxes.size(); ++i)\n\t{\n\t\tif (boxes[i].size() != 0)\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid throw_invalid_box_error_message(\n\tconst std::string& dataset_filename,\n\tconst std::vector<std::vector<dlib::rectangle> >& removed,\n\tconst unsigned long target_size\n)\n{\n\timage_dataset_metadata::dataset data;\n\tload_image_dataset_metadata(data, dataset_filename);\n\n\tstd::ostringstream sout;\n\tsout << \"Error!  An impossible set of object boxes was given for training. \";\n\tsout << \"All the boxes need to have a similar aspect ratio and also not be \";\n\tsout << \"smaller than about \" << target_size << \" pixels in area. \";\n\tsout << \"The following images contain invalid boxes:\\n\";\n\tstd::ostringstream sout2;\n\tfor (unsigned long i = 0; i < removed.size(); ++i)\n\t{\n\t\tif (removed[i].size() != 0)\n\t\t{\n\t\t\tconst std::string imgname = data.images[i].filename;\n\t\t\tsout2 << \"  \" << imgname << \"\\n\";\n\t\t}\n\t}\n\tthrow dlib::error(\"\\n\" + wrap_string(sout.str()) + \"\\n\" + sout2.str());\n}\n\n// ----------------------------------------------------------------------------------------\n\n// General system variables, mostly used for the main GUI window\nbool Start = 0;\nint TrainSVMConfig = 0;\nint AggregateSVMConfig = 0;\nstd::string SVMModelsInPath = \"E:\\\\EyeBlink\\\\Models\\\\ToAggregate.svm\";\nstd::string SVMModelOutPath = \"E:\\\\EyeBlink\\\\Models\\\\NewModel.svm\";\nint TrainERTConfig = 0;\nint AggregateERTConfig = 0;\nstd::string ERTModelsInPath = \"E:\\\\EyeBlink\\\\Models\\\\ToAggregate.dat\";\nstd::string ERTModelOutPath = \"E:\\\\EyeBlink\\\\Models\\\\NewModel.dat\";\nstd::string SVMTrainingDatasetPath = \"E:\\\\EyeBlink\\\\Data\\\\SVMTrainingdata.xml\";\nstd::string SVMTestDatasetPath = \"E:\\\\EyeBlink\\\\Data\\\\SVMTestingdata.xml\";\nstd::string ERTTrainingDatasetPath = \"E:\\\\EyeBlink\\\\Data\\\\ERTTrainingdata.xml\";\nstd::string ERTTestDatasetPath = \"E:\\\\EyeBlink\\\\Data\\\\ERTTestingdata.xml\";\n\n// Variable decleration for SVM training settings, changed and set with the SVM training GUI\nbool SVMDone = 0;\nint SVMThreads = 6;\ndouble C = 100.0;\ndouble eps = 0.01; \nunsigned int num_folds = 3;\nunsigned long target_size = 80 * 80;\nunsigned long upsample_amount = 2;\n\n// Variable decleration for ERT training settings, changed and set with the ERT training GUI\nbool ERTDone = 0;\nunsigned int ERTThreads = 6;\nunsigned long oversampling_amount = 20; // Random deformations of input data to help overcome generalization\ndouble nu = 0.1; // 0,1 for default, the lower the more generalized training, 1 for complete fitting\nunsigned long tree_depth = 5; // Default 2 for normal, 8 for high accuracy, verry slow on higher values, also severly increases model size be extreemly carefull\nunsigned int feature_pool_size = 400; // Number of pixels used for ERT feature processing in each cascade. 400 default\nunsigned int num_test_splits = 20; // Default 50. Changes accuracy of training, but slows training speed\nunsigned int cascade_depth = 10; // Number of iterations\nunsigned long num_trees_per_cascade_level = 500; // Default is 500\ndouble lambda = 0.1; \n\nint main(int argc, char** argv)\n{\n\ttry\n\t{\n\t\t// Showing main GUI\n\t\twin my_window(&Start, &TrainSVMConfig, &AggregateSVMConfig, &SVMModelsInPath, &SVMModelOutPath, &TrainERTConfig, &AggregateERTConfig, &ERTModelsInPath, &ERTModelOutPath, &SVMTrainingDatasetPath, &SVMTestDatasetPath, &ERTTrainingDatasetPath, &ERTTestDatasetPath);\n\t\twhile (true)\n\t\t{\n\t\t\twhile (Start == 0)\n\t\t\t{\n\t\t\t\tsleep(100); // Sleep while system waits for user to start program, Idle running can be implemented here if neeeded\n\t\t\t}\n\t\t\tcout << \"Program has started\" << endl;\n\n\t\t\t// If *.svm or *.dat is used to select more then one model of each type, for either multi model aggregation or testing, each model is seperated into its own file.\n\t\t\tstd::vector<String> VectorSVMInputModelPaths;\n\t\t\tstd::vector<String> VectorERTInputModelPaths; // Keep in mind, this path can also be used to load CERT models for testing only (option 3 in main GUI)\n\t\t\tstd::vector<String> VectorCERTInputModelPaths; // Not used at the moment, could be used later if adding or removing Subdivisions from CERT model using other ERT models is needed. For now the ERT input is used.\n\t\t\tstd::vector < object_detector<image_scanner_type>> SVMModels; // Vector for all loaded SVM models\n\t\t\tstd::vector < shape_predictor> ERTModels; // Vector for all loaded ERT models\n\t\t\tstd::vector < CERT > CERTModels; // Vector for all loaded CERT models\n\n\t\t\tif (AggregateSVMConfig == 1 || AggregateSVMConfig == 2) // Load SVM models from input path if needed\n\t\t\t{\n\t\t\t\tglob(SVMModelsInPath, VectorSVMInputModelPaths); // If a incursive function is wanted, where all subfolders of the target are also searched, add '1' to the arguments\n\t\t\t\tcout << \"Number of .svm models detected on SVM model(s) input path:\" << VectorSVMInputModelPaths.size() << endl;\n\t\t\t\tfor (int i = 0; i < VectorSVMInputModelPaths.size(); i++)\n\t\t\t\t{\n\t\t\t\t\tifstream fin(VectorSVMInputModelPaths[i], ios::binary);\n\t\t\t\t\tif (fin)\n\t\t\t\t\t{\n\t\t\t\t\t\tobject_detector<image_scanner_type> TempDetector;\n\t\t\t\t\t\tcout << \"Loaded .svm file for either multi model aggregation or test only testing, file:\" << VectorSVMInputModelPaths[i] << endl;\n\t\t\t\t\t\tdeserialize(TempDetector, fin);\n\t\t\t\t\t\tSVMModels.push_back(TempDetector);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tcout << \"Error reading .svm file on SVM model(s) input path, file was:\" << VectorSVMInputModelPaths[i] << endl;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (AggregateERTConfig == 1 || AggregateERTConfig == 2) // Load ERT models from input path if needed\n\t\t\t{\n\t\t\t\tglob(ERTModelsInPath, VectorERTInputModelPaths); // If a incursive function is wanted, where all subfolders of the target are also searched, add '1' to the arguments\n\t\t\t\tcout << \"Number of .dat models detected on ERT model(s) input path:\" << VectorERTInputModelPaths.size() << endl;\n\t\t\t\tfor (int i = 0; i < VectorERTInputModelPaths.size(); i++)\n\t\t\t\t{\n\t\t\t\t\tifstream fin(VectorERTInputModelPaths[i], ios::binary);\n\t\t\t\t\tif (fin)\n\t\t\t\t\t{\n\t\t\t\t\t\tshape_predictor TempDetector;\n\t\t\t\t\t\tcout << \"Loaded .dat file for either Weighted Bin Aggregation or test only testing, file:\" << VectorERTInputModelPaths[i] << endl;\n\t\t\t\t\t\tdeserialize(TempDetector, fin);\n\t\t\t\t\t\tERTModels.push_back(TempDetector);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tcout << \"Error reading .dat file on ERT model(s) input path, file was:\" << VectorERTInputModelPaths[i] << endl;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (AggregateERTConfig == 3) // Load CERT models from input path if needed (Uses ERT input path at the moment)\n\t\t\t{\n\t\t\t\tglob(ERTModelsInPath, VectorERTInputModelPaths); // If a incursive function is wanted, where all subfolders of the target are also searched, add '1' to the arguments\n\t\t\t\tcout << \"Number of .CERT models detected on ERT model(s) input path:\" << VectorERTInputModelPaths.size() << endl;\n\t\t\t\tfor (int i = 0; i < VectorERTInputModelPaths.size(); i++)\n\t\t\t\t{\n\t\t\t\t\tifstream fin(VectorERTInputModelPaths[i], ios::binary);\n\t\t\t\t\tif (fin)\n\t\t\t\t\t{\n\t\t\t\t\t\tCERT TempDetector;\n\t\t\t\t\t\tcout << \"Loaded .CERT file for either WBA CERT model only testing, file:\" << VectorERTInputModelPaths[i] << endl;\n\t\t\t\t\t\tTempDetector.deserialize(fin);\n\t\t\t\t\t\tCERTModels.push_back(TempDetector);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tcout << \"Error reading .CERT file on CERT model(s) input path, file was:\" << VectorERTInputModelPaths[i] << endl;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (TrainSVMConfig == 1) // Getting SVM training settings from user if needed\n\t\t\t{\n\t\t\t\tcout << \"Showing SVM model training window now\" << endl;\n\t\t\t\tSVMsettingsWin SVMWindow(&SVMDone, &SVMThreads, &C, &eps, &num_folds, &target_size, &upsample_amount);\n\t\t\t\twhile (SVMDone == 0) \n\t\t\t\t{\n\t\t\t\t\tsleep(100); // Wait while user finishes SVM training input\n\t\t\t\t}\n\t\t\t\tSVMDone = 0;\n\t\t\t\t// Callout settings back to user\n\t\t\t\tcout << \"SVM model training configured, using the following settings:\" << endl;\n\t\t\t\tcout << \"threads:\" << SVMThreads << endl;\n\t\t\t\tcout << \"C:\" << C << endl;\n\t\t\t\tcout << \"eps:\" << eps << endl;\n\t\t\t\tcout << \"num_folds:\" << num_folds << endl;\n\t\t\t\tcout << \"target_size:\" << target_size << endl;\n\t\t\t\tcout << \"upsample_amount\" << upsample_amount << endl;\n\t\t\t}\n\n\t\t\tif (TrainERTConfig == 1) // Getting ERT training settings from user if needed\n\t\t\t{\n\t\t\t\tcout << \"Showing ERT model training window now\" << endl;\n\t\t\t\tERTsettingsWin ERTWindow(&ERTDone, &ERTThreads, &oversampling_amount, &nu, &tree_depth, &feature_pool_size, &num_test_splits, &cascade_depth, &num_trees_per_cascade_level, &lambda);\n\t\t\t\twhile (ERTDone == 0)\n\t\t\t\t{\n\t\t\t\t\tsleep(100); // Wait while user finishes SVM training input\n\t\t\t\t}\n\t\t\t\tERTDone = 0;\n\t\t\t\t// Callout settings back to user\n\t\t\t\tcout << \"ERT model training configured, using the following settings:\" << endl;\n\t\t\t\tcout << \"threads:\" << ERTThreads << endl;\n\t\t\t\tcout << \"oversampling_amount:\" << oversampling_amount << endl;\n\t\t\t\tcout << \"nu:\" << nu << endl;\n\t\t\t\tcout << \"tree_depth:\" << tree_depth << endl;\n\t\t\t\tcout << \"feature_pool_size:\" << feature_pool_size << endl;\n\t\t\t\tcout << \"num_test_splits:\" << num_test_splits << endl;\n\t\t\t\tcout << \"cascade_depth:\" << cascade_depth << endl;\n\t\t\t\tcout << \"num_trees_per_cascade_level:\" << num_trees_per_cascade_level << endl;\n\t\t\t\tcout << \"lambda:\" << lambda << endl;\n\t\t\t}\n\n\t\t\t// SVM Model training if needed (based on default DLib Training)\n\t\t\tobject_detector<image_scanner_type> NewSVMDetector; // Placeholder for the new created SVM model\n\t\t\tif (TrainSVMConfig == 1) // Training new .svm model based on user settings\n\t\t\t{\n\t\t\t\tcout << \"Starting preperations for SVM model training.\" << endl;\n\t\t\t\tdlib::array<array2d<unsigned char> > images;\n\t\t\t\tstd::vector<std::vector<dlib::rectangle> > object_locations, ignore;\n\n\t\t\t\tcout << \"Loading training image dataset from dataset .xml file \" << SVMTrainingDatasetPath << endl;\n\t\t\t\tignore = load_image_dataset(images, object_locations, SVMTrainingDatasetPath);\n\t\t\t\tcout << \"Number of images loaded: \" << images.size() << endl;\n\n\t\t\t\t// Check if there are more folds than there are images.  \n\t\t\t\tif (num_folds > images.size())\n\t\t\t\t\tnum_folds = images.size();\n\n\t\t\t\t// Upsampling if needed\n\t\t\t\tfor (unsigned long i = 0; i < upsample_amount; ++i)\n\t\t\t\t\tupsample_image_dataset<pyramid_down<2> >(images, object_locations, ignore);\n\n\t\t\t\timage_scanner_type scanner;\n\t\t\t\n\t\t\t\tunsigned long width, height;\n\t\t\t\tpick_best_window_size(object_locations, width, height, target_size);\n\t\t\t\tscanner.set_detection_window_size(width, height);\n\t\t\t\tstructural_object_detection_trainer<image_scanner_type> trainer(scanner);\n\n\t\t\t\ttrainer.set_num_threads(SVMThreads);\n\t\t\t\ttrainer.be_verbose(); // This is always set, this gives a progress overview in the CLI during training, remove this is unwanted, or make it depending on user settings.\n\t\t\t\ttrainer.set_c(C);\n\t\t\t\ttrainer.set_epsilon(eps);\n\n\t\t\t\t// Making sure input trainingsdata has boxes usable by detector\n\t\t\t\tstd::vector<std::vector<dlib::rectangle> > removed;\n\t\t\t\tremoved = remove_unobtainable_rectangles(trainer, images, object_locations);\n\t\t\t\t// Error handeling for if a box does not match (this happens a lot if there is no upsampling)\n\t\t\t\tif (contains_any_boxes(removed))\n\t\t\t\t{\n\t\t\t\t\tunsigned long scale = upsample_amount + 1;\n\t\t\t\t\tscale = scale * scale;\n\t\t\t\t\tthrow_invalid_box_error_message(SVMTrainingDatasetPath, removed, target_size / scale);\n\t\t\t\t}\n\t\t\t\tcout << \"Preperations completed. Starting training on new SVM model\" << endl;\n\t\t\t\tNewSVMDetector = trainer.train(images, object_locations, ignore);\n\t\t\t\tcout << \"Training of new SVM  model has completed.\" << endl;\n\t\t\t}\n\n\t\t\t// ERT model training if needed (based on default DLib Training)\n\t\t\tshape_predictor NewERTPredictor; // Placeholder for the new ERT model created\n\t\t\tif (TrainERTConfig == 1) // training new .dat model based on user settings\n\t\t\t{\n\t\t\t\tcout << \"Starting preperations for ERT model training.\" << endl;\n\t\t\t\tcout << \"Loading training image dataset from dataset .xml file \" << ERTTrainingDatasetPath << endl;\n\n\t\t\t\tdlib::array<array2d<unsigned char> > images_train;\n\t\t\t\tstd::vector<std::vector<full_object_detection> > faces_train;\n\t\t\t\tload_image_dataset(images_train, faces_train, ERTTrainingDatasetPath);\n\t\t\t\tcout << \"Number of images loaded: \" << images_train.size() << endl;\n\n\t\t\t\tshape_predictor_trainer trainer;\n\n\t\t\t\t// Applying ERT training settings\n\t\t\t\ttrainer.set_nu(nu);\n\t\t\t\ttrainer.set_tree_depth(tree_depth);\n\t\t\t\ttrainer.set_num_threads(ERTThreads);\n\t\t\t\tif (oversampling_amount > 0)\n\t\t\t\t\ttrainer.set_oversampling_amount(oversampling_amount);\n\t\t\t\ttrainer.set_cascade_depth(cascade_depth);\n\t\t\t\ttrainer.set_feature_pool_size(feature_pool_size);\n\t\t\t\ttrainer.set_num_test_splits(num_test_splits);\n\t\t\t\ttrainer.set_num_trees_per_cascade_level(num_trees_per_cascade_level);\n\t\t\t\ttrainer.set_lambda(lambda);\n\n\t\t\t\ttrainer.be_verbose(); // This is always set, this gives a progress overview in the CLI during training, remove this is unwanted, or make it depending on user settings.\n\n\t\t\t\tcout << \"Preperations completed. Starting training on new ERT model\" << endl;\n\n\t\t\t\tNewERTPredictor = trainer.train(images_train, faces_train);\n\t\t\t\tcout << \"Training of new ERT  model has completed.\" << endl;\n\t\t\t\tcout << endl << \"Number of parts of ERT Model: \" << NewERTPredictor.num_parts();\n\t\t\t\tcout << endl << \"Number of feutures of of ERT Model\" << NewERTPredictor.num_features() << endl;\n\t\t\t}\n\n\t\t\t// SVM Model aggregation if needed, using the Mean Weight Matrix Aggregation (MWMA) algorithm, see paper for detailed explenation\n\t\t\tif (AggregateSVMConfig == 1) // Aggregating new .svm model based on user settings, aggregates any trained .svm model as well\n\t\t\t{\n\t\t\t\tcout << \"Starting SVM multi model aggregation process\" << endl;\n\t\t\t\tcout << \"Loaded \" << SVMModels.size() << \" SVM models from input path for aggregation proces\" << endl;\n\t\t\t\tif (TrainSVMConfig == 1)\n\t\t\t\t\tcout << \"Trained SVM model shall be included in aggregation proces\" << endl;\n\n\t\t\t\tcout << \"Starting SVM multi aggregation\" << endl;\n\n\t\t\t\tmatrix<double, 0, 1> TempW; // MWMA step 1: New temp matrix for aggregation\n\t\t\t\tTempW.set_size((SVMModels[0].get_w()).size());\n\t\t\t\tTempW = SVMModels[0].get_w(); // MWMA step 1: init of w using first model\n\t\t\t\tfor (int i = 1; i < SVMModels.size(); i++)\n\t\t\t\t{\n\t\t\t\t\tTempW += SVMModels[i].get_w(); // MWMA step 2a: Adding all other matrix values\n\t\t\t\t}\n\t\t\t\tif (TrainSVMConfig == 1)\n\t\t\t\t{\n\t\t\t\t\tTempW += NewSVMDetector.get_w(); // MWMA step 2a: Inclusion of trained SVM model in aggregation\n\t\t\t\t\tTempW /= (SVMModels.size() + 1); // MWMA step 2b: averaging all matrix values including trained model\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tTempW /= SVMModels.size(); // MWMA step 2b: averageing all matrix values\n\n\t\t\t\tNewSVMDetector = object_detector<image_scanner_type>(SVMModels[0].get_scanner(), SVMModels[0].get_overlap_tester(), TempW); // MWMA step 3: Feuture extraction transfer and saving\n\t\t\t\tcout << \"SVM Multi aggregation completed\" << endl;\n\t\t\t}\n\n\t\t\t// ERT Model aggregation if needed, using tthe Weighted Bin Aggregation (MWMA) algorithm, this combines several ERT models into a new Comnbined-ERT model (CERT), see paper for detailed explenation\n\t\t\tCERT NewCERT;\n\t\t\tif (AggregateERTConfig == 1) // Aggregating new ERT model based on user settings, aggregates trained .dat model as well\n\t\t\t{\n\t\t\t\tcout << \"Starting ERT Weighted Bin Aggregation process\" << endl;\n\t\t\t\tcout << \"Loaded \" << ERTModels.size() << \" ERT models from input path for aggregation proces\" << endl;\n\t\t\t\tif (TrainERTConfig == 1)\n\t\t\t\t{\n\t\t\t\t\tcout << \"Trained ERT model shall be included in aggregation proces\" << endl;\n\t\t\t\t\tERTModels.push_back(NewERTPredictor);\n\t\t\t\t}\n\n\t\t\t\t// WBA Step 1: Forrest combination\n\t\t\t\tcout << \"ERT WBA: Forrest combination\" << endl;\n\t\t\t\tstd::vector<dlib::shape_predictor> NewSubDivisions;\n\t\t\t\tfor (int i = 0; i < ERTModels.size(); i++)\n\t\t\t\t{\n\t\t\t\t\tNewSubDivisions.push_back(ERTModels[i]);\n\t\t\t\t}\n\n\t\t\t\t// WBA Step 2: Devider calculation\n\t\t\t\tcout << \"ERT WBA: Devider calculation\" << endl;\n\t\t\t\tstd::vector<double> NewDevider; // The devider represents how much the subdevision partakes in the calculation of the end result and should total 1\n\t\t\t\tstd::vector<double> DeviderOffSet; // This vector contains all offset values in order to bias end outcome towards a certain model. This could be filled using user config later, but for now its hardcoded for euqal participation (by filling it with zero's only.\n\t\t\t\tdouble TotalDeviationValue = 0; // This number is needed to determin how the end result index of 1 is reached. If all moddels have equal weight, this is the number of models (to ensure mean average). If a model has more or less weight, then this model should be changed.\n\t\t\t\tfor (int i = 0; i < ERTModels.size(); i++) // Offset calculation\n\t\t\t\t{\n\t\t\t\t\tDeviderOffSet.push_back(1); // Adding ones first always, a 1 means 100% base of this model is used for final weight calculation, so place in vector is filled even if no offset is given, 1's only means all models partake equaly. \n\t\t\t\t\tDeviderOffSet[i] += 0; // Add specific model offset here (later trough GUI settings, but now hardcoded). For 20% more bias towards a model, add 0.2 (this ofcourse also means that other models lose participation value towards this model. Therefore If all models get the same increase in bias, it has no effect; 2's for all modes results in same for 1's in all.\n\t\t\t\t\tTotalDeviationValue += DeviderOffSet[i]; // If a model has increased or decreased weight, the toal deviation should always be changed, to ensure the later total result index always equals 1. \n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < ERTModels.size(); i++) // Final devider calculation, by pushing back the final deviation values now instead of in the first loop, changes can be made depending on the TotalDeviationValue if needed.\n\t\t\t\t{\n\t\t\t\t\tdouble TempBinDeviation;\n\t\t\t\t\tTempBinDeviation = DeviderOffSet[i];\n\t\t\t\t\tNewDevider.push_back(TempBinDeviation);\n\t\t\t\t}\n\n\t\t\t\t// WBA Step 3: Weighted Bins Creation\n\t\t\t\tcout << \"ERT WBA: Weighted bins creation\" << endl;\n\t\t\t\tstd::vector<std::pair<dlib::full_object_detection, double>> NewWeightedBins;\n\t\t\t\tfor (int i = 0; i < ERTModels.size(); i++) // Creation of all bins, one bin for each subdevision, this is used to store sub results and used in combination with the corresponding devider for end result calculation\n\t\t\t\t{\n\t\t\t\t\tdlib::full_object_detection NewBin;\n\t\t\t\t\tstd::pair<dlib::full_object_detection, double> NewWeightedBin(NewBin, NewDevider[i]);\n\t\t\t\t\tNewWeightedBins.push_back(NewWeightedBin);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// WBA step 4: Averaging of init shape model\n\t\t\t\tcout << \"ERT WBA: Aggregating shapes\"<< endl;\n\t\t\t\tmatrix<float, 0, 1> NewShape; // New init Shape for averaging\n\t\t\t\tNewShape.set_size((ERTModels[0].get_shape()).size());\n\t\t\t\tNewShape = ERTModels[0].get_shape();\n\t\t\t\tfor (int i = 1; i < ERTModels.size(); i++)\n\t\t\t\t{\n\t\t\t\t\tNewShape += ERTModels[i].get_shape();\n\n\t\t\t\t}\n\t\t\t\tNewShape /= ERTModels.size(); // Averageing all matrix values\n\n\t\t\t\tNewCERT = CERT(NewSubDivisions, TotalDeviationValue, NewWeightedBins, NewShape); // Creation of new combi ERT model\n\n\t\t\t\tcout << \"ERT WBA completed\" << endl;\n\t\t\t}\n\n\t\t\t// Model testing and saving\n\t\t\tif (AggregateSVMConfig == 1  || TrainSVMConfig == 1) // Saving and testing new .svm model if one has been created\n\t\t\t{\n\t\t\t\tcout << \"Saving newly created SVM model to disk.\" << endl;\n\t\t\t\tserialize(SVMModelOutPath) << NewSVMDetector; // saving new SVM file to disk\n\n\t\t\t\t// Testing newly created SVM model\n\t\t\t\tdlib::array<array2d<unsigned char> > images;\n\t\t\t\tstd::vector<std::vector<dlib::rectangle> > object_locations, ignore;\n\t\t\t\tcout << \"Loading Test image dataset from dataset.xml file \" << SVMTestDatasetPath << endl;\n\t\t\t\tignore = load_image_dataset(images, object_locations, SVMTestDatasetPath);\n\t\t\t\tcout << \"Number of images loaded: \" << images.size() << endl;\n\t\t\t\tcout << \"Testing new SVM model on specified test dataset.\" << endl;\n\t\t\t\tcout << \"Accuracy of SVM model (precision,recall,AP): \" << test_object_detection_function(NewSVMDetector, images, object_locations, ignore) << endl;\n\t\t\t}\n\n\t\t\tif (AggregateSVMConfig == 2) // Testing selected input .svm models if test only mode is used\n\t\t\t{\n\t\t\t\tdlib::array<array2d<unsigned char> > images;\n\t\t\t\tstd::vector<std::vector<dlib::rectangle> > object_locations, ignore;\n\t\t\t\tcout << \"Loading SVM Test image dataset from dataset.xml file \" << SVMTestDatasetPath << endl;\n\t\t\t\tignore = load_image_dataset(images, object_locations, SVMTestDatasetPath);\n\t\t\t\tcout << \"Number of images loaded: \" << images.size() << endl;\n\n\t\t\t\tcout << \"Testing:\" << SVMModels.size() << \" SVM model(s) on specified test dataset.\" << endl;\n\t\t\t\tfor (int i = 0; i < SVMModels.size(); i++)\n\t\t\t\t{\n\t\t\t\t\tcout << \"Testing SVM model:\" << VectorSVMInputModelPaths[i] << endl;\n\t\t\t\t\tcout << \"Accuracy of SVM model  (precision,recall,AP): \" << test_object_detection_function(SVMModels[i], images, object_locations, ignore) << endl;\n\t\t\t\t}\n\t\t\t\tcout << \"Testing of SVM models completed.\" << endl;\n\t\t\t}\n\n\t\t\tif (TrainERTConfig == 1) // Saving and testing new .dat model if one has been trained\n\t\t\t{\n\t\t\t\tcout << \"Saving newly trained ERT model to disk.\" << endl;\n\t\t\t\tserialize(ERTModelOutPath) << NewERTPredictor; // saving new .dat file to disk\n\n\t\t\t\tcout << \"Loading ERT Test image dataset from dataset.xml file \" << ERTTestDatasetPath << endl;\n\t\t\t\tdlib::array<array2d<unsigned char> > images_test;\n\t\t\t\tstd::vector<std::vector<full_object_detection> > faces_test;\n\t\t\t\tload_image_dataset(images_test, faces_test, ERTTestDatasetPath);\n\t\t\t\tcout << \"Number of images loaded: \" << images_test.size() << endl;\n\n\t\t\t\tcout << \"Mean testing error of new ERT model: \" <<\n\t\t\t\t\ttest_shape_predictor(NewERTPredictor, images_test, faces_test, get_interocular_distances(faces_test)) << endl;  // Test ERT model using internal test software\n\t\t\t}\n\n\t\t\tif (AggregateERTConfig == 1) // Saving and testing new .CERT model if one has been created\n\t\t\t{\n\t\t\t\tcout << \"Saving newly aggregated CERT model to disk.\" << endl;\n\t\t\t\tofstream fout(ERTModelOutPath, ios::binary);\n\t\t\t\tif (fout)\n\t\t\t\t{\n\t\t\t\t\tNewCERT.serialize(fout);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tcout << \"Error saving CERT model. Model output path was:\" << ERTModelOutPath << endl;\n\n\t\t\t\tcout << \"Loading ERT Test image dataset from dataset.xml file \" << ERTTestDatasetPath << endl;\n\t\t\t\tdlib::array<array2d<unsigned char> > images_test;\n\t\t\t\tstd::vector<std::vector<full_object_detection> > faces_test;\n\t\t\t\tload_image_dataset(images_test, faces_test, ERTTestDatasetPath);\n\t\t\t\tcout << \"Number of images loaded: \" << images_test.size() << endl;\n\n\t\t\t\tconst std::vector<std::vector<double> > scales = get_interocular_distances(faces_test);\n\t\t\t\trunning_stats<double> rs;\n\t\t\t\tfor (unsigned long i = 0; i < faces_test.size(); ++i)\n\t\t\t\t{\n\t\t\t\t\tfor (unsigned long j = 0; j < faces_test[i].size(); ++j)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst double scale = scales.size() == 0 ? 1 : scales[i][j]; // Scale needed for testing\n\t\t\t\t\t    full_object_detection Shape = NewCERT.PredictFinalShape(images_test[i], faces_test[i][j].get_rect()); // This provides a full_object_detection from a CERT model, use this function if a CERT model is used where normaly a ERT model is used.  \n\t\t\t\t\t\tfor (unsigned long k = 0; k < Shape.num_parts(); k++) // The new CERT model has no internal test function like the default ERT code from DLib, therefore the Mean Error Rate is calculated here below.\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdouble score = length(Shape.part(k) - faces_test[i][j].part(k)) / scale; \n\t\t\t\t\t\t\trs.add(score);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcout << \"Mean testing error of new ERT model: \" << rs.mean() << endl;\n\t\t\t\t\t\n\t\t\t}\n\n\t\t\tif (AggregateERTConfig == 2) // Testing selected input .dat models if test only mode is used. This tests ERT models, not the Combined-ERT models, can be used to see most suitable models for aggregation\n\t\t\t{\n\t\t\t\tcout << \"Loading ERT Test image dataset from dataset.xml file \" << ERTTestDatasetPath << endl;\n\t\t\t\tdlib::array<array2d<unsigned char> > images_test;\n\t\t\t\tstd::vector<std::vector<full_object_detection> > faces_test;\n\t\t\t\tload_image_dataset(images_test, faces_test, ERTTestDatasetPath);\n\t\t\t\tcout << \"Number of images loaded: \" << images_test.size() << endl;\n\n\t\t\t\tcout << \"Testing:\" << ERTModels.size() << \" ERT model(s) on specified test dataset.\" << endl;\n\n\t\t\t\tfor (int i = 0; i < ERTModels.size(); i++) \n\t\t\t\t{\n\t\t\t\t\tcout << \"Testing ERT model:\" << VectorERTInputModelPaths[i] << endl;\n\t\t\t\t\tcout << \"Mean testing error of ERT model: \" << test_shape_predictor(ERTModels[i], images_test, faces_test, get_interocular_distances(faces_test)) << endl; // Test ERT model using internal test software\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif (AggregateERTConfig == 3) // Testing selected input CERT .dat models if test only mode is used\n\t\t\t{\n\t\t\t\tcout << \"Loading ERT Test image dataset from dataset.xml file \" << ERTTestDatasetPath << endl;\n\t\t\t\tdlib::array<array2d<unsigned char> > images_test;\n\t\t\t\tstd::vector<std::vector<full_object_detection> > faces_test;\n\t\t\t\tload_image_dataset(images_test, faces_test, ERTTestDatasetPath);\n\t\t\t\tcout << \"Number of images loaded: \" << images_test.size() << endl;\n\n\t\t\t\tcout << \"Testing:\" << CERTModels.size() << \" CERT model(s) on specified test dataset.\" << endl;\n\n\t\t\t\tfor (int m = 0; m < CERTModels.size(); m++)\n\t\t\t\t{\n\t\t\t\t\tcout << \"Testing CERT model:\" << VectorERTInputModelPaths[m] << endl;\n\t\t\t\t\tconst std::vector<std::vector<double> > scales = get_interocular_distances(faces_test);\n\t\t\t\t\trunning_stats<double> rs;\n\t\t\t\t\tfor (unsigned long i = 0; i < faces_test.size(); ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (unsigned long j = 0; j < faces_test[i].size(); ++j)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst double scale = scales.size() == 0 ? 1 : scales[i][j]; // Scale needed for testing\n\t\t\t\t\t\t\tfull_object_detection Shape = CERTModels[m].PredictFinalShape(images_test[i], faces_test[i][j].get_rect()); // This provides a full_object_detection from a CERT model, use this function if a CERT model is used where normaly a ERT model is used.  \n\t\t\t\t\t\t\tfor (unsigned long k = 0; k < Shape.num_parts(); k++) // The new CERT model has no internal test function like the default ERT code from DLib, therefore the Mean Error Rate is calculated here below.\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tdouble score = length(Shape.part(k) - faces_test[i][j].part(k)) / scale;\n\t\t\t\t\t\t\t\trs.add(score);\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\tcout << \"Mean testing error of CERT model: \" << rs.mean() << endl;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tStart = 0; // System is done and shall await next usage\n\t\t\tcout << \"Program has completed task, a new task can now be started using the start button, please change settings where needed.\" << endl;\n\t\t}\n\t}\n\tcatch (exception& e)\n\t{\n\t\tcout << \"\\nexception thrown!\" << endl;\n\t\tcout << e.what() << endl;\n\t\tcout << \"Restart of program needed, close window or terminate program from CLI.\" << endl;\n\t}\n}\n\n\n// Implementaiton of remaining DLib functions for testing and training of ERT models, needed to calculate the scale\n// ----------------------------------------------------------------------------------------\n\n\ndouble interocular_distance(\n\tconst full_object_detection& det\n)\n{\n\tdlib::vector<double, 2> l, r;\n\tdouble cnt = 0;\n\t// Find the center of the left eye by averaging the points around \n\t// the eye.\n\tfor (unsigned long i = 36; i <= 41; ++i)\n\t{\n\t\tl += det.part(i);\n\t\t++cnt;\n\t}\n\tl /= cnt;\n\n\t// Find the center of the right eye by averaging the points around \n\t// the eye.\n\tcnt = 0;\n\tfor (unsigned long i = 42; i <= 47; ++i)\n\t{\n\t\tr += det.part(i);\n\t\t++cnt;\n\t}\n\tr /= cnt;\n\n\t// Now return the distance between the centers of the eyes\n\treturn length(l - r);\n}\n\nstd::vector<std::vector<double> > get_interocular_distances(\n\tconst std::vector<std::vector<full_object_detection> >& objects\n)\n{\n\tstd::vector<std::vector<double> > temp(objects.size());\n\tfor (unsigned long i = 0; i < objects.size(); ++i)\n\t{\n\t\tfor (unsigned long j = 0; j < objects[i].size(); ++j)\n\t\t{\n\t\t\ttemp[i].push_back(interocular_distance(objects[i][j]));\n\t\t}\n\t}\n\treturn temp;\n}\n\n", "meta": {"hexsha": "48bb9d7c760fa9c9f820f3efa1eb67f244a0e3cd", "size": 31234, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ModelTrainingAndAggregation.cpp", "max_stars_repo_name": "SLWZwaard/DMT", "max_stars_repo_head_hexsha": "3395d5d3be212b3d6e692bb5e3c7d9112b07b453", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-01T10:43:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-01T10:43:22.000Z", "max_issues_repo_path": "ModelTrainingAndAggregation.cpp", "max_issues_repo_name": "SLWZwaard/DMT", "max_issues_repo_head_hexsha": "3395d5d3be212b3d6e692bb5e3c7d9112b07b453", "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": "ModelTrainingAndAggregation.cpp", "max_forks_repo_name": "SLWZwaard/DMT", "max_forks_repo_head_hexsha": "3395d5d3be212b3d6e692bb5e3c7d9112b07b453", "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.8275862069, "max_line_length": 364, "alphanum_fraction": 0.6943074854, "num_tokens": 8152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091673, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2821370731239544}}
{"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 <vector>\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n#include <boost/math/distributions/chi_squared.hpp>\n#include \"genfile/Error.hpp\"\n#include \"genfile/ToGP.hpp\"\n#include \"genfile/VariantDataReader.hpp\"\n#include \"metro/likelihood/Multinomial.hpp\"\n#include \"components/SNPSummaryComponent/SNPHWE.hpp\"\n#include \"components/SNPSummaryComponent/SNPSummaryComputation.hpp\"\n#include \"components/SNPSummaryComponent/HWEComputation.hpp\"\n#include \"components/SNPSummaryComponent/IntensitySummaryComputation.hpp\"\n#include \"components/SNPSummaryComponent/ClusterFitComputation.hpp\"\n\n// #define DEBUG_SNP_SUMMARY_COMPUTATION 1\n\nnamespace snp_summary_component {\n\t\n\tnamespace {\n\t\tstruct AlleleCountClient: public genfile::VariantDataReader::PerSampleSetter {\n\t\t\tAlleleCountClient( std::vector< double >* counts ):\n\t\t\t\tm_counts( counts ),\n\t\t\t\tm_number_of_alleles( 0 )\n\t\t\t{\n\t\t\t\tassert( counts != 0 ) ;\n\t\t\t}\n\n\t\t\t~AlleleCountClient() throw() {}\n\t\t\t\n\t\t\tvoid set_counts( std::vector< double >* counts ) {\n\t\t\t\tassert( counts != 0 ) ;\n\t\t\t\tm_counts = counts ;\n\t\t\t}\n\t\t\t\n\t\t\tvoid initialise( std::size_t number_of_samples, std::size_t number_of_alleles ) {\n\t\t\t\tm_number_of_alleles = number_of_alleles ;\n\t\t\t\tassert( m_counts->size() == number_of_alleles ) ;\n\t\t\t}\n\t\t\t\n\t\t\tbool set_sample( std::size_t i ) {\n\t\t\t\tm_ploidy = 0 ;\n\t\t\t\tm_table = 0 ;\n\t\t\t\treturn true ;\n\t\t\t}\n\t\t\t\n\t\t\tvoid set_number_of_entries( uint32_t ploidy, std::size_t n, OrderType const order_type, ValueType const value_type ) {\n\t\t\t\tassert( order_type == genfile::ePerUnorderedGenotype ) ;\n\t\t\t\tassert( value_type == genfile::eProbability ) ;\n\t\t\t\t\n\t\t\t\tstd::map< uint32_t, genfile::impl::Enumeration >::iterator where = m_tables.find( ploidy ) ;\n\t\t\t\tif( where == m_tables.end() ) {\n\t\t\t\t\tstd::pair< std::map< uint32_t, genfile::impl::Enumeration >::iterator, bool >\n\t\t\t\t\t\tresult = m_tables.insert( std::make_pair( ploidy, genfile::impl::enumerate_unphased_genotypes( ploidy ) )) ;\n\t\t\t\t\tassert( result.second ) ;\n\t\t\t\t\twhere = result.first ;\n\t\t\t\t}\n\t\t\t\tm_ploidy = ploidy ;\n\t\t\t\tm_table = &(where->second) ;\n\t\t\t}\n\t\t\t\n\t\t\tvoid set_value( std::size_t value_i, genfile::MissingValue const value ) {\n\t\t\t\tset_value( value_i, 0.0 ) ;\n\t\t\t}\n\n\t\t\tvoid set_value( std::size_t value_i, double const value ) {\n\t\t\t\tassert( value_i <= std::size_t( std::numeric_limits< uint16_t >::max() )) ;\n\t\t\t\tgenfile::impl::Enumeration const& enumeration = *m_table ;\n\t\t\t\tstd::size_t const& maxAlleles = enumeration.first.second ;\n\t\t\t\tassert( m_number_of_alleles <= maxAlleles ) ;\n\t\t\t\tuint16_t const encodedGenotype = enumeration.second.second[ uint16_t( value_i ) ] ;\n\t\t\t\tuint32_t const bitsPerAllele = enumeration.first.first ;\n\t\t\t\tuint16_t mask = uint16_t( 0xFFFF ) >> ( 16 - bitsPerAllele ) ;\n\t\t\t\t// Dosage of the 1st allele in the genotype is not encoded directly.\n\t\t\t\t// We compute it as the ploidy minus the dosage of other alleles.\n\t\t\t\tuint16_t dosage_of_nonref_alleles = 0 ;\n\t\t\t\tfor( std::size_t allele = 1; allele < m_number_of_alleles; ++allele ) {\n\t\t\t\t\tuint16_t const dosage = ( encodedGenotype >> ( (allele-1) * bitsPerAllele )) & mask ;\n\t\t\t\t\t(*m_counts)[allele] += value * dosage ;\n\t\t\t\t\tdosage_of_nonref_alleles += dosage ;\n\t\t\t\t}\n\t\t\t\t(*m_counts)[0] += value * (m_ploidy - dosage_of_nonref_alleles) ;\n\t\t\t}\n\t\t\t\n\t\t\tvoid finalise() {}\n\t\tprivate:\n\t\t\tstd::vector< double >* m_counts ;\n\t\t\tstd::size_t m_number_of_alleles ;\n\t\t\tuint32_t m_ploidy ;\n\t\t\tstd::map< uint32_t, genfile::impl::Enumeration > m_tables ;\n\t\t\tgenfile::impl::Enumeration* m_table ;\n\t\t} ;\n\t}\n\n\tstruct AlleleCountComputation: public SNPSummaryComputation {\n\tpublic:\n\t\t\n\t\tAlleleCountComputation():\n\t\t\tm_counter( &m_counts )\n\t\t{}\n\n\t\tvoid list_variables( NameCallback callback ) const {\n\t\t\tusing genfile::string_utils::to_string ;\n\t\t\t// By default we list 10 alleles\n\t\t\tcallback( \"number_of_alleles\" ) ;\n\t\t\tfor( std::size_t i = 0; i < 10; ++i ) {\n\t\t\t\tcallback( \"allele\" + to_string(i+1) + \"_count\" ) ;\n\t\t\t}\n\t\t}\n\n\t\tvoid operator()(\n\t\t\tVariantIdentifyingData const& snp,\n\t\t\tGenotypes const& genotypes,\n\t\t\tPloidy const& ploidy,\n\t\t\tgenfile::VariantDataReader& data_reader,\n\t\t\tResultCallback callback\n\t\t) {\n\t\t\tusing genfile::string_utils::to_string ;\n\t\t\tm_counts = std::vector< double >( snp.number_of_alleles(), 0.0 ) ;\n\t\t\tm_counter.set_counts( &m_counts ) ;\n\t\t\tcallback( \"number_of_alleles\", int64_t( snp.number_of_alleles() )) ;\n\t\t\tdata_reader.get( \":genotypes:\", genfile::to_GP_unphased( m_counter ) ) ;\n\t\t\tstd::size_t i = 0 ;\n\t\t\tfor( ; i < snp.number_of_alleles(); ++i ) {\n\t\t\t\tcallback( \"allele\" + to_string(i+1) + \"_count\", m_counts[i] ) ;\n\t\t\t}\n\t\t\tfor( ; i < 10; ++i ) {\n\t\t\t\tcallback( \"allele\" + to_string(i+1) + \"_count\", genfile::MissingValue() ) ;\n\t\t\t}\n\t\t}\n\t\t\n\t\tstd::string get_summary( std::string const& prefix, std::size_t column_width ) const {\n\t\t\treturn prefix + \"AlleleCountComputation\" ;\n\t\t}\n\tprivate:\n\t\tstd::vector< double > m_counts ;\n\t\tAlleleCountClient m_counter ;\n\t} ;\n\n\tstruct AlleleFrequencyComputation: public SNPSummaryComputation\n\t{\n\t\tAlleleFrequencyComputation( std::string const& what ):\n\t\t\tm_compute_counts( what == \"everything\" || what == \"counts\" ),\n\t\t\tm_compute_frequencies( what == \"everything\" )\n\t\t{\n\t\t\tassert( what == \"counts\" || what == \"everything\" ) ;\n\t\t}\n\t\tvoid operator()(\n\t\t\tVariantIdentifyingData const& snp,\n\t\t\tGenotypes const& genotypes,\n\t\t\tPloidy const& ploidy,\n\t\t\tgenfile::VariantDataReader&,\n\t\t\tResultCallback callback\n\t\t) {\n\t\t\tgenfile::Chromosome const& chromosome = snp.get_position().chromosome() ;\n\t\t\tif( snp.number_of_alleles() == 2 ) {\n\t\t\t\tbool const allDiploid = ( ploidy.array() == 2 ).cast< int >().sum() == ploidy.size() ;\n\t\t\t\tif( allDiploid ) {\n\t\t\t\t\tcompute_autosomal_frequency( snp, genotypes, callback ) ;\n\t\t\t\t} else {\n\t\t\t\t\tcompute_sex_chromosome_frequency( snp, genotypes, ploidy, callback ) ;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tvoid compute_sex_chromosome_frequency(\n\t\t\tVariantIdentifyingData const& snp,\n\t\t\tGenotypes const& genotypes,\n\t\t\tPloidy const& ploidy,\n\t\t\tResultCallback callback\n\t\t) {\n\t\t\tGenotypes haploid_genotypes = genotypes ;\n\t\t\tGenotypes diploid_genotypes = genotypes ;\n\t\t\tassert( std::size_t( genotypes.rows() ) == ploidy.size() ) ;\n\n\t\t\tfor( int i = 0; i < genotypes.rows(); ++i ) {\n\t\t\t\tif( ploidy(i) != 1 ) {\n\t\t\t\t\thaploid_genotypes.row(i).setZero() ;\n\t\t\t\t}\n\t\t\t\tif( ploidy(i) != 2 ) {\n\t\t\t\t\tdiploid_genotypes.row(i).setZero() ;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tdouble const a_allele_count = haploid_genotypes.col(0).sum()\n\t\t\t\t+ ( ( 2.0 * diploid_genotypes.col(0).sum() ) + diploid_genotypes.col(1).sum() ) ;\n\t\t\tdouble const b_allele_count = haploid_genotypes.col(1).sum()\n\t\t\t\t+ ( ( 2.0 * diploid_genotypes.col(2).sum() ) + diploid_genotypes.col(1).sum() ) ;\n\n\t\t\tif( m_compute_counts ) {\n\t\t\t\tcallback( \"alleleA_count\", a_allele_count ) ;\n\t\t\t\tcallback( \"alleleB_count\", b_allele_count ) ;\n\t\t\t}\n\n\t\t\tif( m_compute_frequencies ) {\n\t\t\t\tdouble const total_allele_count = ( haploid_genotypes.sum() + 2.0 * diploid_genotypes.sum() ) ;\n\t\t\t\tdouble const a_allele_freq = a_allele_count / total_allele_count ;\n\t\t\t\tdouble const b_allele_freq = b_allele_count / total_allele_count ;\n\n\t\t\t\tcallback( \"alleleA_frequency\", a_allele_freq ) ;\n\t\t\t\tcallback( \"alleleB_frequency\", b_allele_freq ) ;\n\n\t\t\t\tif( a_allele_freq < b_allele_freq ) {\n\t\t\t\t\tcallback( \"minor_allele_frequency\", a_allele_freq ) ;\n\t\t\t\t\tcallback( \"minor_allele\", snp.get_allele(0) ) ;\n\t\t\t\t\tcallback( \"major_allele\", snp.get_allele(1) ) ;\n\t\t\t\t}\n\t\t\t\telse if( a_allele_freq > b_allele_freq ) {\n\t\t\t\t\tcallback( \"minor_allele_frequency\", b_allele_freq ) ;\n\t\t\t\t\tcallback( \"minor_allele\", snp.get_allele(1) ) ;\n\t\t\t\t\tcallback( \"major_allele\", snp.get_allele(0) ) ;\n\t\t\t\t} else {\n\t\t\t\t\tcallback( \"minor_allele_frequency\", a_allele_freq ) ;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvoid compute_autosomal_frequency( VariantIdentifyingData const& snp, Genotypes const& genotypes, ResultCallback callback ) {\n\t\t\tdouble const a_allele_count = ( 2.0 * genotypes.col(0).sum() ) + genotypes.col(1).sum() ;\n\t\t\tdouble const b_allele_count = ( 2.0 * genotypes.col(2).sum() ) + genotypes.col(1).sum() ;\n\n\t\t\tif( m_compute_counts ) {\n\t\t\t\tcallback( \"alleleA_count\", a_allele_count ) ;\n\t\t\t\tcallback( \"alleleB_count\", b_allele_count ) ;\n\t\t\t}\n\t\t\t\n\t\t\tif( m_compute_frequencies ) {\n\t\t\t\tdouble const total_allele_count = ( 2.0 * genotypes.sum() ) ;\n\t\t\t\tdouble const a_allele_freq = a_allele_count / total_allele_count ;\n\t\t\t\tdouble const b_allele_freq = b_allele_count / total_allele_count ;\n\n\t\t\t\tcallback( \"alleleA_frequency\", a_allele_freq ) ;\n\t\t\t\tcallback( \"alleleB_frequency\", b_allele_freq ) ;\n\n\t\t\t\tif( a_allele_freq < b_allele_freq ) {\n\t\t\t\t\tcallback( \"minor_allele_frequency\", a_allele_freq ) ;\n\t\t\t\t\tcallback( \"minor_allele\", snp.get_allele(0) ) ;\n\t\t\t\t\tcallback( \"major_allele\", snp.get_allele(1) ) ;\n\t\t\t\t}\n\t\t\t\telse if( a_allele_freq > b_allele_freq ) {\n\t\t\t\t\tcallback( \"minor_allele_frequency\", b_allele_freq ) ;\n\t\t\t\t\tcallback( \"minor_allele\", snp.get_allele(1) ) ;\n\t\t\t\t\tcallback( \"major_allele\", snp.get_allele(0) ) ;\n\t\t\t\t} else {\n\t\t\t\t\tcallback( \"minor_allele_frequency\", a_allele_freq ) ;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tstd::string get_summary( std::string const& prefix, std::size_t column_width ) const {\n\t\t\treturn prefix + \"AlleleFrequencyComputation\" ;\n\t\t}\n\tprivate:\n\t\tbool const m_compute_counts ;\n\t\tbool const m_compute_frequencies ;\n\t} ;\n\n\t// What proportion of the mass on a genotype is due to high-confidence calls?\n\tstruct CallMassComputation: public SNPSummaryComputation\n\t{\n\t\t\n\t\tCallMassComputation( double const threshhold = 0.9 ):\n\t\t\tm_threshhold(threshhold)\n\t\t{}\n\n\t\tvoid operator()( VariantIdentifyingData const& snp, Genotypes const& genotypes, Ploidy const& ploidy, genfile::VariantDataReader&, ResultCallback callback ) {\n\t\t\tgenfile::Chromosome const& chromosome = snp.get_position().chromosome() ;\n\t\t\tbool const allDiploid = ( ploidy.array() == 2 ).cast< int >().sum() == ploidy.size() ;\n\t\t\tif( allDiploid ) {\n\t\t\t\tcompute_autosomal_call_mass( snp, genotypes, callback ) ;\n\t\t\t} else {\n\t\t\t\treturn ;\n\t\t\t}\n\t\t}\n\t\t\n\t\tvoid compute_autosomal_call_mass( VariantIdentifyingData const& snp, Genotypes const& genotypes, ResultCallback callback ) {\n\t\t\tEigen::VectorXd const masses = genotypes.colwise().sum() ;\n\t\t\tm_hcGenotypes = ( genotypes.array() > m_threshhold ).cast< double >()  * genotypes.array() ;\t\n\t\t\tEigen::VectorXd const hcMasses = m_hcGenotypes.colwise().sum() ; \n\n\t\t\tcallback( \"AA_mass_propn\", hcMasses(0)/masses(0) ) ;\n\t\t\tcallback( \"AB_mass_propn\", hcMasses(1)/masses(1) ) ;\n\t\t\tcallback( \"BB_mass_propn\", hcMasses(2)/masses(2) ) ;\n\n\t\t\tcallback( \"non-AA-mass_propn\", (hcMasses(1)+hcMasses(2))/(masses(1)+masses(2))) ;\n\t\t\tcallback( \"non-BB-mass_propn\", (hcMasses(1)+hcMasses(0))/(masses(1)+masses(0))) ;\n\t\t}\n\t\t\n\t\tstd::string get_summary( std::string const& prefix, std::size_t column_width ) const {\n\t\t\treturn prefix + \"CallMassComputation\" ;\n\t\t}\n\tprivate:\n\t\tdouble const m_threshhold ;\n\t\tGenotypes m_hcGenotypes ;\n\t} ;\n\t\n\tstruct MissingnessComputation: public SNPSummaryComputation {\n\t\tMissingnessComputation( double call_threshhold = 0.9 ): m_call_threshhold( call_threshhold ) {}\n\t\tvoid operator()(\n\t\t\tVariantIdentifyingData const& snp,\n\t\t\tGenotypes const& genotypes,\n\t\t\tPloidy const& ploidy,\n\t\t\tgenfile::VariantDataReader&,\n\t\t\tResultCallback callback\n\t\t) {\n\t\t\tassert( std::size_t( genotypes.rows() ) == ploidy.size() ) ;\n\n\t\t\tdouble missingness = double( genotypes.rows() ) - genotypes.array().sum() ;\n\t\t\tcallback( \"missing_proportion\", missingness / double( genotypes.rows() ) ) ;\n\n\t\t\tbool const allDiploid = ( ploidy.array() == 2 ).cast< int >().sum() == ploidy.size() ;\n\t\t\tif( allDiploid ) {\n\t\t\t\tcallback( \"A\", 0 ) ;\n\t\t\t\tcallback( \"B\", 0 ) ;\n\t\t\t\tif( snp.number_of_alleles() == 2 ) {\n\t\t\t\t\tcallback( \"AA\", genotypes.col(0).sum() ) ;\n\t\t\t\t\tcallback( \"AB\", genotypes.col(1).sum() ) ;\n\t\t\t\t\tcallback( \"BB\", genotypes.col(2).sum() ) ;\n\t\t\t\t}\n\t\t\t\tcallback( \"NULL\", genotypes.rows() - genotypes.sum() ) ;\n\t\t\t} else {\n\t\t\t\tcompute_haploid_diploid_counts( snp, genotypes, ploidy, callback ) ;\n\t\t\t}\n\t\t\tcallback( \"total\", genfile::VariantEntry::Integer( genotypes.rows() )) ;\n\t\t}\n\t\t\n\t\tvoid compute_haploid_diploid_counts(\n\t\t\tVariantIdentifyingData const& snp,\n\t\t\tGenotypes const& genotypes,\n\t\t\tPloidy const& ploidy,\n\t\t\tResultCallback callback\n\t\t) {\n\t\t\tstd::map< int, Eigen::VectorXd > counts ;\n\t\t\tstd::map< int, double > null_counts ;\n\t\t\tcounts[ -1 ] = Eigen::VectorXd::Zero( 3 ) ;\n\t\t\tcounts[ 0 ] = Eigen::VectorXd::Zero( 3 ) ;\n\t\t\tcounts[ 1 ] = Eigen::VectorXd::Zero( 3 ) ;\n\t\t\tcounts[ 2 ] = Eigen::VectorXd::Zero( 3 ) ;\n\t\t\tchar countKey[5] = { '.', '.', 'm', 'f', '.' } ;\n\t\t\tstd::map< int, std::size_t > sample_counts ;\n\n\t\t\tfor( std::size_t i = 0; i < ploidy.size(); ++i ) {\n\t\t\t\tcounts[ ploidy(i) ] += genotypes.row( i ) ;\n\t\t\t\tnull_counts[ ploidy(i) ] += ( 1 - genotypes.row(i).sum() ) ;\n\t\t\t\t++sample_counts[ ploidy(i) ] ;\n#if DEBUG_SNP_SUMMARY_COMPUTATION\n\t\t\t\tif( ploidy(i) == 1 && genotypes(i,2) != 0 ) {\n\t\t\t\t\tstd::cerr << \"! ( MissingnessComputation::compute_sex_chromosome_counts() ): individual \" << (i+1) << \"is male but has genotype \" << genotypes.row(i) << \"!!\\n\" ;\n\t\t\t\t}\n#endif\n\t\t\t}\n\t\t\t\n\t\t\tcallback( \"A\", counts[ 1 ]( 0 ) ) ;\n\t\t\tcallback( \"B\", counts[ 1 ]( 1 ) ) ;\n\t\t\tcallback( \"AA\", counts[ 2 ]( 0 ) ) ;\n\t\t\tcallback( \"AB\", counts[ 2 ]( 1 ) ) ;\n\t\t\tcallback( \"BB\", counts[ 2 ]( 2 ) ) ;\n\t\t\tcallback( \"NULL\", null_counts[ 'm' ] + null_counts[ 'f' ] ) ;\n\t\t\tcallback( \"unknown_ploidy\", counts[ -1 ].sum() + null_counts[ -1 ] ) ;\n\t\t\tassert( counts[ 1 ]( 2 ) == 0 ) ;\n\t\t}\n\t\t\n\t\tstd::string get_summary( std::string const& prefix = \"\", std::size_t column_width = 20 ) const { return prefix + \"MissingnessComputation\" ; }\n\tprivate:\n\t\tdouble const m_call_threshhold ;\n\t} ;\n\n\tstruct InfoComputation: public SNPSummaryComputation {\n\t\tvoid operator()(\n\t\t\tVariantIdentifyingData const& snp,\n\t\t\tGenotypes const& genotypes,\n\t\t\tPloidy const& ploidy,\n\t\t\tgenfile::VariantDataReader&,\n\t\t\tResultCallback callback\n\t\t) {\n\t\t\tif( snp.number_of_alleles() == 2 ) {\n\t\t\t\tbool const allDiploid = ( ploidy.array() == 2 ).cast< int >().sum() == ploidy.size() ;\n\t\t\t\tif( allDiploid ) {\n\t\t\t\t\tcompute_autosomal_info( snp, genotypes, callback ) ;\n\t\t\t\t} else {\n\t\t\t\t\tcompute_sex_chromosome_info( snp, genotypes, ploidy, callback ) ;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// we don't compute for multiallelics currently\n\t\t\t}\n\t\t}\n\t\t\n\t\tvoid compute_autosomal_info( VariantIdentifyingData const& snp, Genotypes const& genotypes, ResultCallback callback ) {\n\t\t\tdouble const theta_mle = ( genotypes.col( 1 ).sum() + 2.0 * genotypes.col( 2 ).sum() ) / ( 2.0 * genotypes.sum() ) ;\n\t\t\tdouble const theta_est = theta_mle ;\n\t\t\t\n\t\t\tEigen::VectorXd const impute_fallback_distribution = Eigen::VectorXd::Zero( 3 ) ;\n\t\t\tEigen::VectorXd fallback_distribution = Eigen::VectorXd::Zero( 3 ) ;\n\t\t\tfallback_distribution( 0 ) = ( 1 - theta_est ) * ( 1 - theta_est ) ;\n\t\t\tfallback_distribution( 1 ) = 2.0 * theta_est * ( 1 - theta_est ) ;\n\t\t\tfallback_distribution( 2 ) = theta_est * theta_est ;\n\t\t\t\n\t\t\t//std::cerr << \"theta = \" << theta_est << \", fallback_distribution = \" << fallback_distribution.transpose() << \".\\n\" ;\n\t\t\t\n\t\t\tEigen::VectorXd const levels = Eigen::VectorXd::LinSpaced( 3, 0, 2 ) ;\n\n\t\t\tdouble const info = 1.0 - (\n\t\t\t\tcompute_sum_of_variances( levels, genotypes, fallback_distribution )\n\t\t\t\t/ ( genotypes.rows() * 2.0 * theta_est * ( 1 - theta_est ) )\n\t\t\t) ;\n\n\t\t\tdouble const impute_info = 1.0 - (\n\t\t\t\tcompute_sum_of_variances( levels, genotypes, impute_fallback_distribution )\n\t\t\t\t/ ( genotypes.sum() * 2.0 * theta_mle * ( 1 - theta_mle ) )\n\t\t\t) ;\n\t\t\n\t\t\tcallback( \"info\", info ) ;\n\t\t\tcallback( \"impute_info\", impute_info ) ;\n\t\t}\n\n\t\tvoid compute_sex_chromosome_info(\n\t\t\tVariantIdentifyingData const& snp,\n\t\t\tGenotypes const& genotypes,\n\t\t\tPloidy const& ploidy,\n\t\t\tResultCallback callback\n\t\t) {\n\t\t\tEigen::MatrixXd hap_or_diploid( genotypes.rows(), 2 ) ;\n\t\t\tfor( std::size_t i = 0; i < ploidy.size(); ++i ) {\n\t\t\t\tif( ploidy(i) == 1 ) {\n\t\t\t\t\thap_or_diploid(i,0) = 1 ;\n\t\t\t\t\thap_or_diploid(i,1) = 0 ;\n\t\t\t\t}\n\t\t\t\telse if( ploidy[ i ] == 2 ) {\n\t\t\t\t\thap_or_diploid(i,0) = 0 ;\n\t\t\t\t\thap_or_diploid(i,1) = 1 ;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// Don't understand, so treat ploidy as missing.\n\t\t\t\t\t// individuals with missing sex do not contribute to the computation.\n\t\t\t\t\t// I think this is the least surprising thing to do.\n\t\t\t\t\thap_or_diploid(i,0) = 0 ;\n\t\t\t\t\thap_or_diploid(i,1) = 0 ;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdouble const a_allele_count_diploid = (\n\t\t\t\t\t( genotypes.col( 1 ) + 2.0 * genotypes.col( 0 ) ).array() * ( hap_or_diploid.col(1).array() )\n\t\t\t\t).sum() ;\n\t\t\tdouble const b_allele_count_diploid = (\n\t\t\t\t\t( genotypes.col( 1 ) + 2.0 * genotypes.col( 2 ) ).array() * ( hap_or_diploid.col(1).array() )\n\t\t\t\t).sum() ;\n\t\t\tdouble const a_allele_count_haploid = \t(\n\t\t\t\t\tgenotypes.col( 0 ).array() * hap_or_diploid.col(0).array() \n\t\t\t\t).sum() ;\n\t\t\tdouble const b_allele_count_haploid = \t(\n\t\t\t\t\tgenotypes.col( 1 ).array() * hap_or_diploid.col(0).array() \n\t\t\t\t).sum() ;\n\t\t\t\n\t\t\t// MLE estimate of allele frequency\n\t\t\tdouble const theta_mle = ( b_allele_count_diploid + b_allele_count_haploid )\n\t\t\t\t/ ( a_allele_count_diploid + b_allele_count_diploid + a_allele_count_haploid + b_allele_count_haploid ) ;\n\n\t\t\t// For the new info measure, could regularise by data augmentation, adding one allele of each type.\n\t\t\t// This makes info better behaved at low frequencies.\n\t\t\t// Note adding one of each allele constitutes minimal prior information that the variant is polymorphic.\n\t\t\t// double const theta_est = ( b_allele_count_diploid + b_allele_count_haploid + 1 )\n\t\t\t//\t/ ( a_allele_count_diploid + b_allele_count_diploid + a_allele_count_haploid + b_allele_count_haploid + 2 ) ;\n\t\t\t\n\t\t\t// ...but don't actually do that; it is less conservative at rare SNPs.\n\t\t\tdouble const theta_est = theta_mle ;\n\n\t\t\tEigen::VectorXd diploid_fallback_distribution = Eigen::VectorXd::Zero( 3 ) ;\n\t\t\tdiploid_fallback_distribution( 0 ) = ( 1 - theta_est ) * ( 1 - theta_est ) ;\n\t\t\tdiploid_fallback_distribution( 1 ) = 2.0 * theta_est * ( 1 - theta_est ) ;\n\t\t\tdiploid_fallback_distribution( 2 ) = theta_est * theta_est ;\n\t\t\t\n\t\t\tEigen::VectorXd haploid_fallback_distribution = Eigen::VectorXd::Zero( 3 ) ;\n\t\t\thaploid_fallback_distribution( 0 ) = 1 - theta_est ;\n\t\t\thaploid_fallback_distribution( 1 ) = theta_est ;\n\t\t\t\n\t\t\t//std::cerr << \"theta = \" << theta_mle << \", fallback_distribution = \" << fallback_distribution.transpose() << \".\\n\" ;\n\t\t\t\n\t\t\tEigen::VectorXd const levels = Eigen::VectorXd::LinSpaced( 3, 0, 2 ) ;\n\t\t\t\n\t\t\tdouble info = 0.0 ;\n\t\t\tEigen::VectorXd const haploids = ( hap_or_diploid.col( 0 ).array() == 1 ).cast< double >() ;\n\t\t\tEigen::VectorXd const diploids = ( hap_or_diploid.col( 1 ).array() == 1 ).cast< double >() ;\n\t\t\t{\n\t\t\t\tif( haploids.sum() > 0 ) {\n\t\t\t\t\tinfo -= compute_sum_of_variances( levels, genotypes, haploid_fallback_distribution, haploids )\n\t\t\t\t\t\t/ ( theta_est * ( 1 - theta_est ) ) ;\n\t\t\t\t}\n\n\t\t\t\tif( diploids.sum() > 0 ) {\n\t\t\t\t\tinfo -= compute_sum_of_variances( levels, genotypes, diploid_fallback_distribution, diploids )\n\t\t\t\t\t\t/ ( 2.0 * theta_est * ( 1 - theta_est ) ) ;\n\t\t\t\t}\n\n\t\t\t\tdouble const totalProb = (\n\t\t\t\t\t( genotypes.block( 0, 0, genotypes.rows(), 2 ).rowwise().sum().array() * haploids.array() ).sum()\n\t\t\t\t\t+ ( genotypes.rowwise().sum().array() * diploids.array() ).sum() \n\t\t\t\t) ;\n\n\t\t\t\tinfo = 1.0 + (info / (haploids.sum() + diploids.sum() )) ;\n\t\t\t}\n\t\t\t\n\t\t\t{\n\t\t\t\t// IMPUTE-style MLE, treat all samples as diploid ignoring gender.\n\t\t\t\t// Haploids are encoded in the 0/1 columns here so we have to reverse-engineer the\n\t\t\t\t// original info computation to allow for this.\n\t\t\t\tdouble const autosomal_theta_mle = (\n\t\t\t\t\t( 2.0 * genotypes.col( 1 ).array() * haploids.array() )\n\t\t\t\t\t+ (( genotypes.col( 1 ) + 2.0 * genotypes.col( 2 ) ).array() * ( 1.0 - haploids.array() ))\n\t\t\t\t).sum() / ( 2.0 * genotypes.sum() ) ;\n\n#if DEBUG\n\t\t\t\tstd::cerr << \"autosomal_theta_mle  = \" << std::setprecision(10) << autosomal_theta_mle << \".\\n\" ;\n\t\t\t\tstd::cerr << genotypes << \".\\n\" ;\n#endif\n\t\t\t\tEigen::VectorXd haploidLevels = Eigen::VectorXd::Zero(3) ;\n\t\t\t\thaploidLevels(1) = 2 ;\n\t\t\t\tdouble const impute_info = 1.0 - (\n\t\t\t\t\t(\n\t\t\t\t\t\tcompute_sum_of_variances( haploidLevels, genotypes, Eigen::VectorXd::Zero( 3 ), haploids )\n\t\t\t\t\t\t+ compute_sum_of_variances( levels, genotypes, Eigen::VectorXd::Zero( 3 ), 1.0 - haploids.array() )\n\t\t\t\t\t) / ( genotypes.sum() * 2.0 * autosomal_theta_mle * ( 1 - autosomal_theta_mle ) )\n\t\t\t\t) ;\n\t\t\t\n\t\t\t\tcallback( \"info\", info ) ;\n\t\t\t\tcallback( \"impute_info\", impute_info ) ;\n\t\t\t}\n\t\t}\n\n\t\tstd::string get_summary( std::string const& prefix = \"\", std::size_t column_width = 20 ) const { return prefix + \"InfoComputation\" ; }\n\t\t\n\tprivate:\n\t\tdouble compute_sum_of_variances( Eigen::VectorXd const& levels, Eigen::MatrixXd const& probabilities, Eigen::VectorXd const& fallback ) const {\n\t\t\treturn compute_sum_of_variances( levels, probabilities, fallback, Eigen::VectorXd::Constant( probabilities.rows(), 1 ) ) ;\n\t\t}\n\t\t\n\t\t// treat the rows of the probabilities matrix as probabilities.\n\t\t// distribution for individual i is taken as a mixture of the distribution given by row i of probabilities,\n\t\t// and the fallback distribution if the sum of row i < 1, appropriately weighted.\n\t\t// Only individuals with inclusion = 1 are used.\n\t\tdouble compute_sum_of_variances( Eigen::VectorXd const& levels, Eigen::MatrixXd const& probabilities, Eigen::VectorXd const& fallback, Eigen::VectorXd const& inclusion ) const {\n\t\t\tassert( levels.size() == fallback.size() ) ;\n\t\t\tassert( levels.size() == probabilities.cols() ) ;\n\t\t\tassert( inclusion.size() == probabilities.rows() ) ;\n\t\t\tEigen::VectorXd levels_squared = ( levels.array() * levels.array() ) ;\n\n\t\t\tdouble result = 0.0 ;\n\t\t\tfor( int i = 0; i < probabilities.rows(); ++i ) {\n\t\t\t\tif( inclusion( i ) == 1 ) {\n\t\t\t\t\tdouble const c = probabilities.row( i ).sum() ;\n\t\t\t\t\tresult += compute_variance( levels, levels_squared, probabilities.row( i ).transpose() + ( 1 - c ) * fallback ) ;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result ;\n\t\t}\n\t\t\n\t\tdouble compute_variance( Eigen::VectorXd const& levels, Eigen::VectorXd const& levels_squared, Eigen::VectorXd const& probs ) const {\n\t\t\tdouble const mean = ( probs.transpose() * levels )(0) ;\n\t\t\tdouble const variance = ( probs.transpose() * levels_squared )(0) - ( mean * mean ) ;\n\t\t\t// std::cerr << \"compute_variance: levels = \" << levels.transpose() << \", levels_squared = \" << levels_squared.transpose() << \", probs = \" << probs.transpose() << \", variance = \" << variance << \".\\n\" ;\n\t\t\treturn variance ;\n\t\t}\n\t} ;\n}\n\nSNPSummaryComputation::UniquePtr SNPSummaryComputation::create(\n\tstd::string const& name\n) {\n\tUniquePtr result ;\n\tif( name == \"allele-frequencies\" ) { result.reset( new snp_summary_component::AlleleFrequencyComputation( \"everything\" )) ; }\n\telse if( name == \"allele-counts\" ) { result.reset( new snp_summary_component::AlleleFrequencyComputation( \"counts\" )) ; }\n\telse if( name == \"HWE\" ) { result.reset( new snp_summary_component::HWEComputation()) ; }\n\telse if( name == \"missingness\" ) { result.reset( new snp_summary_component::MissingnessComputation()) ; }\n\telse if( name == \"info\" ) { result.reset( new snp_summary_component::InfoComputation()) ; }\n\telse if( name == \"call-mass-proportion\" ) { result.reset( new snp_summary_component::CallMassComputation()) ; }\n\telse if( name == \"intensity-stats\" ) { result.reset( new snp_summary_component::IntensitySummaryComputation() ) ; }\n\telse if( name == \"multi-allele-counts\" ) { result.reset( new snp_summary_component::AlleleCountComputation() ) ; }\n\telse {\n\t\tthrow genfile::BadArgumentError( \"SNPSummaryComputation::create()\", \"name=\\\"\" + name + \"\\\"\" ) ;\n\t}\n\treturn result ;\n}\n", "meta": {"hexsha": "749f7b56d016fad7b3dc8be3f6e8c41ac51c9495", "size": 23602, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "components/SNPSummaryComponent/src/SNPSummaryComputation.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": "components/SNPSummaryComponent/src/SNPSummaryComputation.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": "components/SNPSummaryComponent/src/SNPSummaryComputation.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": 40.1394557823, "max_line_length": 204, "alphanum_fraction": 0.661765952, "num_tokens": 7140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.28213707312395436}}
{"text": "/*****************************************************************************\n*\n*     Program: EPTlib\n*     Author: Alessandro Arduino <a.arduino@inrim.it>\n*\n*  MIT License\n*\n*  Copyright (c) 2020-2021  Alessandro Arduino\n*  Istituto Nazionale di Ricerca Metrologica (INRiM)\n*  Strada delle cacce 91, 10135 Torino\n*  ITALY\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\n#include \"eptlib/ept_convreact.h\"\n\n#include <complex>\n#include <limits>\n\n#include <iostream>\n#include <fstream>\n\n#include <Eigen/Sparse>\n\nusing namespace eptlib;\n\nnamespace {\n\tstatic double nand = std::numeric_limits<double>::quiet_NaN();\n\tstatic std::complex<double> nancd = std::complex<double>(nand,nand);\n}\n\n// EPTConvReact constructor\nEPTConvReact::\nEPTConvReact(const double freq, const std::array<int,NDIM> &nn,\n    const std::array<double,NDIM> &dd, const Shape &shape) :\n    EPTInterface(freq,nn,dd, 1,1), dir_epsr_(1.0), dir_sigma_(0.0),\n    plane_idx_(nn[2]/2), is_volume_(false), diff_coeff_(0.0),\n    thereis_diff_(false), fd_filter_(shape),\n    solver_iterations_(0), solver_residual_(0.0) {\n    return;\n}\n\n// EPTConvReact destructor\nEPTConvReact::\n~EPTConvReact() {\n    return;\n}\n\n// EPTConvReact run\nEPTlibError EPTConvReact::\nRun() {\n    if (thereis_tx_sens_.all()) {\n        thereis_epsr_ = true;\n        if (is_volume_) {\n            epsr_ = Image<double>(nn_[0],nn_[1],nn_[2]);\n        } else {\n            epsr_ = Image<double>(nn_[0],nn_[1]);\n        }\n    }\n    if (thereis_trx_phase_.all()) {\n        thereis_sigma_ = true;\n        if (is_volume_) {\n            sigma_ = Image<double>(nn_[0],nn_[1],nn_[2]);\n        } else {\n            sigma_ = Image<double>(nn_[0],nn_[1]);\n        }\n    } else {\n        return EPTlibError::MissingData;\n    }\n    if (thereis_epsr_) {\n        // ...complete convection-reaction EPT\n        return CompleteEPTConvReact();\n    } else {\n        // ...phase-based convection-reaction EPT\n        return PhaseEPTConvReact();\n    }\n    return EPTlibError::Success;\n}\n\n// EPTConvReact set volume tomography\nbool EPTConvReact::\nToggle3D() {\n    is_volume_ = !is_volume_;\n    return is_volume_;\n}\n\n// EPTConvReact set the selected plane index\nEPTlibError EPTConvReact::\nSelectSlice(const int slice_idx) {\n    int r2 = fd_filter_.GetShape().GetSize()[2]/2;\n    if (slice_idx<r2||slice_idx>nn_[2]-1-r2) {\n        return EPTlibError::OutOfRange;\n    }\n    plane_idx_ = slice_idx;\n    return EPTlibError::Success;\n}\n\n// EPTConvReact set the dirichlet boundary condition\nEPTlibError EPTConvReact::\nSetDirichlet(const double dir_epsr, const double dir_sigma) {\n    if (dir_epsr<1.0||dir_sigma<0.0) {\n        return EPTlibError::WrongDataFormat;\n    }\n    dir_epsr_ = dir_epsr;\n    dir_sigma_ = dir_sigma;\n    return EPTlibError::Success;\n}\n\n// EPTConvReact set artificial diffusion\nvoid EPTConvReact::\nSetArtificialDiffusion(const double diff_coeff) {\n    diff_coeff_ = diff_coeff;\n    thereis_diff_ = true;\n    return;\n}\n// EPTConvReact unset artificial diffusion\nvoid EPTConvReact::\nUnsetArtificialDiffusion() {\n    thereis_diff_ = false;\n    return;\n}\n\n// EPTConvReact get the number of iterations\nint EPTConvReact::\nGetSolverIterations() {\n    return solver_iterations_;\n}\n// EPTConvReact get estimated error\ndouble EPTConvReact::\nGetSolverResidual() {\n    return solver_residual_;\n}\n\nnamespace { // details\n    template <typename T>\n    void FillDoF(std::vector<int> *dof, int *idx_dof, int *n_dof, int *n_dop,\n        const int n_dim, const int i2, const std::array<int,NDIM> &step,\n        const std::vector<T> &beta) {\n        int idx = step[2]*i2;\n        for (int idx_out = 0; idx_out<step[2]; ++idx_out) {\n            if (beta[idx]==beta[idx]) {\n                // if beta is not a NaN, it could be a DoF...\n                (*dof)[(*idx_dof)++] = ++(*n_dof);\n                for (int d = 0; d<n_dim; ++d) {\n                    if (beta[idx+step[d]]!=beta[idx+step[d]] || beta[idx-step[d]]!=beta[idx-step[d]]) {\n                        // ...unless it is near to a NaN\n                        (*dof)[*idx_dof-1] = --(*n_dop);\n                        --(*n_dof);\n                        break;\n                    }\n                }\n            } else {\n                (*dof)[(*idx_dof)++] = --(*n_dop);\n            }\n            ++idx;\n        }\n        return;\n    }\n}  // namespace\n\n// EPTConvReact complete EPT\nEPTlibError EPTConvReact::\nCompleteEPTConvReact() {\n    const std::array<int,NDIM> step{1,nn_[0],nn_[0]*nn_[1]};\n    int n_dim = is_volume_?NDIM:NDIM-1;\n    int n_out = is_volume_?n_vox_:step[2];\n    std::complex<double> dir_x = 1.0/std::complex<double>(dir_epsr_*EPS0,-dir_sigma_/omega_);\n    // compute the gradient\n    std::vector<std::complex<double> > tx_sens_c(n_vox_);\n    std::array<std::vector<std::complex<double> >,NDIM> beta;\n    for (int idx = 0; idx<n_vox_; ++idx) {\n        tx_sens_c[idx] = (*tx_sens_[0])[idx]*std::exp(std::complex<double>(0.0,0.5*(*trx_phase_[0])[idx]));\n    }\n    for (int d = 0; d<n_dim; ++d) {\n        beta[d].resize(n_vox_,std::numeric_limits<double>::quiet_NaN());\n        DifferentialOperator diff_op = static_cast<DifferentialOperator>(d);\n        EPTlibError error = fd_filter_.Apply(diff_op,beta[d].data(),tx_sens_c.data(),nn_,dd_);\n        if (error!=EPTlibError::Success) {\n            return error;\n        }\n    }\n    for (int idx = 0; idx<n_vox_; ++idx) {\n        beta[0][idx] = beta[0][idx] - std::complex<double>(0.0,1.0)*beta[1][idx];\n        beta[1][idx] = std::complex<double>(0.0,1.0)*beta[0][idx];\n    }\n    if (!is_volume_) {\n        beta[2].resize(n_vox_,std::numeric_limits<double>::quiet_NaN());\n        DifferentialOperator diff_op = DifferentialOperator::GradientZZ;\n        EPTlibError error = fd_filter_.Apply(diff_op,beta[2].data(),tx_sens_c.data(),nn_,dd_);\n        if (error!=EPTlibError::Success) {\n            return error;\n        }\n    }\n    // select the degrees of freedom\n    std::vector<int> dof(n_out);\n    int idx_dof = 0;\n    int n_dof = 0;\n    int n_dop = 0;\n    if (is_volume_) {\n        for (int i2 = 0; i2<nn_[2]; ++i2) {\n            ::FillDoF(&dof,&idx_dof,&n_dof,&n_dop, n_dim,i2,step,beta[0]);\n        }\n    } else {\n        ::FillDoF(&dof,&idx_dof,&n_dof,&n_dop, n_dim,plane_idx_,step,beta[0]);\n    }\n    // build coefficient matrix and forcing term\n    Eigen::SparseMatrix<std::complex<double> > A(n_dof,n_dof);\n    std::vector<Eigen::Triplet<std::complex<double> > > A_trip(0);\n    Eigen::VectorXcd b(n_dof);\n    for (int idx_out = 0; idx_out<n_out; ++idx_out) {\n        int idx = is_volume_?idx_out:idx_out+step[2]*plane_idx_;\n        int idof = dof[idx_out];\n        if (idof > 0) {\n            b[idof-1] = 0.0;\n            // coefficient matrix\n            for (int d = 0; d<n_dim; ++d) {\n                if (thereis_diff_) {\n                    A_trip.push_back(Eigen::Triplet<std::complex<double> >(idof-1,idof-1,2.0*diff_coeff_/dd_[d]/dd_[d]));\n                }\n                int jdx_out = idx_out+step[d];\n                int jdx = idx+step[d];\n                int jdof = dof[jdx_out];\n                if (jdof > 0) {\n                    A_trip.push_back(Eigen::Triplet<std::complex<double> >(idof-1,jdof-1,beta[d][jdx]/2.0/dd_[d]));\n                    if (thereis_diff_) {\n                        A_trip.push_back(Eigen::Triplet<std::complex<double> >(idof-1,jdof-1,-diff_coeff_/dd_[d]/dd_[d]));\n                    }\n                } else {\n                    b[idof-1] += -dir_x*beta[d][jdx]/2.0/dd_[d];\n                    if (thereis_diff_) {\n                        b[idof-1] += dir_x*diff_coeff_/dd_[d]/dd_[d];\n                    }\n                }\n                jdx_out = idx_out-step[d];\n                jdx = idx-step[d];\n                jdof = dof[jdx_out];\n                if (jdof > 0) {\n                    A_trip.push_back(Eigen::Triplet<std::complex<double> >(idof-1,jdof-1,-beta[d][jdx]/2.0/dd_[d]));\n                    if (thereis_diff_) {\n                        A_trip.push_back(Eigen::Triplet<std::complex<double> >(idof-1,jdof-1,-diff_coeff_/dd_[d]/dd_[d]));\n                    }\n                } else {\n                    b[idof-1] += dir_x*beta[d][jdx]/2.0/dd_[d];\n                    if (thereis_diff_) {\n                        b[idof-1] += dir_x*diff_coeff_/dd_[d]/dd_[d];\n                    }\n                }\n            }\n            if (!is_volume_) {\n                A_trip.push_back(Eigen::Triplet<std::complex<double> >(idof-1,idof-1,beta[2][idx]));\n            }\n            // forcing term\n            b[idof-1] += -omega_*omega_*MU0*tx_sens_c[idx];\n        }\n    }\n    A.setFromTriplets(A_trip.begin(),A_trip.end());\n    A.makeCompressed();\n    // Solve the linear system\n    Eigen::BiCGSTAB<Eigen::SparseMatrix<std::complex<double> > > solver;\n    solver.compute(A);\n    Eigen::VectorXcd x = solver.solve(b);\n    solver_iterations_ = solver.iterations();\n    solver_residual_ = solver.error();\n    // Extract the electric properties from the result\n    for (int idx = 0; idx<n_out; ++idx) {\n        int idof = dof[idx];\n        if (idof > 0) {\n            std::complex<double> epsc = 1.0/x[idof-1];\n            epsr_[idx] = epsc.real()/EPS0;\n            sigma_[idx] = -epsc.imag()*omega_;\n        } else {\n            epsr_[idx] = ::nand;\n            sigma_[idx] = ::nand;\n        }\n    }\n    return EPTlibError::Success;\n}\n\n// EPTConvReact phase-based EPT\nEPTlibError EPTConvReact::\nPhaseEPTConvReact() {\n    const std::array<int,NDIM> step{1,nn_[0],nn_[0]*nn_[1]};\n    int n_dim = is_volume_?NDIM:NDIM-1;\n    int n_out = is_volume_?n_vox_:step[2];\n    double dir_x = 1.0/dir_sigma_;\n    // compute the gradient\n    std::array<std::vector<double>,NDIM> beta;\n    for (int d = 0; d<n_dim; ++d) {\n        beta[d].resize(n_vox_,std::numeric_limits<double>::quiet_NaN());\n        DifferentialOperator diff_op = static_cast<DifferentialOperator>(d);\n        EPTlibError error;\n        if (PhaseIsWrapped()) {\n            error = WrappedPhaseDerivative(diff_op,beta[d].data(),trx_phase_[0]->GetData().data(),nn_,dd_,fd_filter_);\n        } else {\n            error = fd_filter_.Apply(diff_op,beta[d].data(),trx_phase_[0]->GetData().data(),nn_,dd_);\n        }\n        if (error!=EPTlibError::Success) {\n            return error;\n        }\n    }\n    if (!is_volume_) {\n        beta[2].resize(n_vox_,std::numeric_limits<double>::quiet_NaN());\n        DifferentialOperator diff_op = DifferentialOperator::GradientZZ;\n        EPTlibError error;\n        if (PhaseIsWrapped()) {\n            error = WrappedPhaseDerivative(diff_op,beta[2].data(),trx_phase_[0]->GetData().data(),nn_,dd_,fd_filter_);\n        } else {\n            error = fd_filter_.Apply(diff_op,beta[2].data(),trx_phase_[0]->GetData().data(),nn_,dd_);\n        }\n        if (error!=EPTlibError::Success) {\n            return error;\n        }\n    }\n    // select the degrees of freedom\n    std::vector<int> dof(n_out);\n    int idx_dof = 0;\n    int n_dof = 0;\n    int n_dop = 0;\n    if (is_volume_) {\n        for (int i2 = 0; i2<nn_[2]; ++i2) {\n            ::FillDoF(&dof,&idx_dof,&n_dof,&n_dop, n_dim,i2,step,beta[0]);\n        }\n    } else {\n        ::FillDoF(&dof,&idx_dof,&n_dof,&n_dop, n_dim,plane_idx_,step,beta[0]);\n    }\n    // build coefficient matrix and forcing term\n    Eigen::SparseMatrix<double> A(n_dof,n_dof);\n    std::vector<Eigen::Triplet<double> > A_trip(0);\n    Eigen::VectorXd b(n_dof);\n    for (int idx_out = 0; idx_out<n_out; ++idx_out) {\n        int idx = is_volume_?idx_out:idx_out+step[2]*plane_idx_;\n        int idof = dof[idx_out];\n        if (idof > 0) {\n            b[idof-1] = 0.0;\n            // coefficient matrix\n            for (int d = 0; d<n_dim; ++d) {\n                // diffusion (central term)\n                if (thereis_diff_) {\n                    A_trip.push_back(Eigen::Triplet<double>(idof-1,idof-1,2.0*diff_coeff_/dd_[d]/dd_[d]));\n                }\n                std::array<int,2> sides{+1,-1};\n                for (int s = 0; s<2; ++s) {\n                    int jdx_out = idx_out+sides[s]*step[d];\n                    int jdx = idx+sides[s]*step[d];\n                    int jdof = dof[jdx_out];\n                    // convection\n                    if (beta[d][idx]*beta[d][jdx]>0) {\n                        if (sides[s]*beta[d][idx]>0) {\n                            double A_tmp = sides[s]*beta[d][idx]/dd_[d];\n                            A_trip.push_back(Eigen::Triplet<double>(idof-1,idof-1,A_tmp));\n                        } else {\n                            double A_tmp = sides[s]*beta[d][jdx]/dd_[d];\n                            if (jdof > 0) {\n                                A_trip.push_back(Eigen::Triplet<double>(idof-1,jdof-1,A_tmp));\n                            } else {\n                                b[idof-1] += -dir_x*A_tmp;\n                            }\n                        }\n                    } else {\n                        double A_tmp = sides[s]*beta[d][idx]/dd_[d]/2.0;\n                        A_trip.push_back(Eigen::Triplet<double>(idof-1,idof-1,A_tmp));\n                        A_tmp = sides[s]*beta[d][jdx]/dd_[d]/2.0;\n                        if (jdof > 0) {\n                            A_trip.push_back(Eigen::Triplet<double>(idof-1,jdof-1,A_tmp));\n                        } else {\n                            b[idof-1] += -dir_x*A_tmp;\n                        }\n                    }\n                    // diffusion\n                    if (thereis_diff_) {\n                        if (jdof > 0) {\n                            A_trip.push_back(Eigen::Triplet<double>(idof-1,jdof-1,-diff_coeff_/dd_[d]/dd_[d]));\n                        } else {\n                            b[idof-1] += dir_x*diff_coeff_/dd_[d]/dd_[d];\n                        }\n                    }\n                }\n            }\n            if (!is_volume_) {\n                A_trip.push_back(Eigen::Triplet<double>(idof-1,idof-1,beta[2][idx]));\n            }\n            // forcing term\n            b[idof-1] += 2*omega_*MU0;\n        }\n    }\n    A.setFromTriplets(A_trip.begin(),A_trip.end());\n    A.makeCompressed();\n    // Solve the linear system\n    Eigen::BiCGSTAB<Eigen::SparseMatrix<double> > solver;\n    solver.compute(A);\n    Eigen::VectorXd x = solver.solve(b);\n    solver_iterations_ = solver.iterations();\n    solver_residual_ = solver.error();\n    // Extract the electric properties from the result\n    for (int idx = 0; idx<n_out; ++idx) {\n        int idof = dof[idx];\n        if (idof > 0) {\n            sigma_[idx] = 1.0/x[idof-1];\n        } else {\n            sigma_[idx] = ::nand;\n        }\n    }\n    return EPTlibError::Success;\n}\n", "meta": {"hexsha": "b3ef343f1a661b5ceb1dddc3a736c5297039662a", "size": 15652, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/ept_convreact.cc", "max_stars_repo_name": "EPTlib/eptlib", "max_stars_repo_head_hexsha": "55610dd9d48f6598cb31de6bc9a913b845c62727", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-05-04T22:34:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T00:00:54.000Z", "max_issues_repo_path": "src/ept_convreact.cc", "max_issues_repo_name": "EPTlib/eptlib", "max_issues_repo_head_hexsha": "55610dd9d48f6598cb31de6bc9a913b845c62727", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ept_convreact.cc", "max_forks_repo_name": "EPTlib/eptlib", "max_forks_repo_head_hexsha": "55610dd9d48f6598cb31de6bc9a913b845c62727", "max_forks_repo_licenses": ["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.0023640662, "max_line_length": 122, "alphanum_fraction": 0.5475977511, "num_tokens": 4372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2821370731239543}}
{"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/termstructures/optionletstripper2.hpp>\n#include <qle/termstructures/spreadedoptionletvolatility.hpp>\n\n#include <ql/instruments/makecapfloor.hpp>\n#include <ql/math/solvers1d/brent.hpp>\n#include <ql/pricingengines/capfloor/bacheliercapfloorengine.hpp>\n#include <ql/pricingengines/capfloor/blackcapfloorengine.hpp>\n#include <ql/termstructures/volatility/optionlet/strippedoptionletadapter.hpp>\n\n#include <boost/make_shared.hpp>\n\nnamespace QuantExt {\n\nOptionletStripper2::OptionletStripper2(const boost::shared_ptr<QuantExt::OptionletStripper>& optionletStripper,\n                                       const Handle<QuantLib::CapFloorTermVolCurve>& atmCapFloorTermVolCurve,\n                                       const Handle<YieldTermStructure>& discount, const VolatilityType type,\n                                       const Real displacement)\n    : OptionletStripper(optionletStripper->termVolSurface(), optionletStripper->iborIndex(), discount,\n                        optionletStripper->volatilityType(), optionletStripper->displacement()),\n      stripper_(optionletStripper), atmCapFloorTermVolCurve_(atmCapFloorTermVolCurve),\n      dc_(stripper_->termVolSurface()->dayCounter()), nOptionExpiries_(atmCapFloorTermVolCurve->optionTenors().size()),\n      atmCapFloorStrikes_(nOptionExpiries_), atmCapFloorPrices_(nOptionExpiries_), spreadsVolImplied_(nOptionExpiries_),\n      caps_(nOptionExpiries_), maxEvaluations_(10000), accuracy_(1.e-6), inputVolatilityType_(type),\n      inputDisplacement_(displacement) {\n\n    registerWith(stripper_);\n    registerWith(atmCapFloorTermVolCurve_);\n\n    QL_REQUIRE(dc_ == atmCapFloorTermVolCurve->dayCounter(), \"different day counters provided\");\n}\n\nvoid OptionletStripper2::performCalculations() const {\n\n    // optionletStripper data\n    optionletDates_ = stripper_->optionletFixingDates();\n    optionletPaymentDates_ = stripper_->optionletPaymentDates();\n    optionletAccrualPeriods_ = stripper_->optionletAccrualPeriods();\n    optionletTimes_ = stripper_->optionletFixingTimes();\n    atmOptionletRate_ = stripper_->atmOptionletRates();\n    for (Size i = 0; i < optionletTimes_.size(); ++i) {\n        optionletStrikes_[i] = stripper_->optionletStrikes(i);\n        optionletVolatilities_[i] = stripper_->optionletVolatilities(i);\n    }\n\n    // atmCapFloorTermVolCurve data\n    const vector<Period>& optionExpiriesTenors = atmCapFloorTermVolCurve_->optionTenors();\n    const vector<Time>& optionExpiriesTimes = atmCapFloorTermVolCurve_->optionTimes();\n\n    // discount curve\n    const Handle<YieldTermStructure>& discountCurve =\n        discount_.empty() ? iborIndex_->forwardingTermStructure() : discount_;\n\n    for (Size j = 0; j < nOptionExpiries_; ++j) {\n        // Dummy strike, doesn't get used for ATM curve\n        Volatility atmOptionVol = atmCapFloorTermVolCurve_->volatility(optionExpiriesTimes[j], 33.3333);\n\n        // Create a cap for each pillar point on ATM curve and attach relevant pricing engine i.e. Black if\n        // quotes are shifted lognormal and Bachelier if quotes are normal\n        boost::shared_ptr<PricingEngine> engine;\n        if (inputVolatilityType_ == ShiftedLognormal) {\n            engine = boost::make_shared<BlackCapFloorEngine>(discountCurve, atmOptionVol, dc_, inputDisplacement_);\n        } else if (inputVolatilityType_ == Normal) {\n            engine = boost::make_shared<BachelierCapFloorEngine>(discountCurve, atmOptionVol, dc_);\n        } else {\n            QL_FAIL(\"unknown volatility type: \" << volatilityType_);\n        }\n\n        // Using Null<Rate>() as strike => strike will be set to ATM rate. However, to calculate ATM rate, QL requires\n        // a BlackCapFloorEngine to be set (not a BachelierCapFloorEngine)! So, need a temp BlackCapFloorEngine with a\n        // dummy vol to calculate ATM rate. Needs to be fixed in QL.\n        boost::shared_ptr<PricingEngine> tempEngine = boost::make_shared<BlackCapFloorEngine>(discountCurve, 0.01);\n        caps_[j] = MakeCapFloor(CapFloor::Cap, optionExpiriesTenors[j], iborIndex_, Null<Rate>(), 0 * Days)\n                       .withPricingEngine(tempEngine);\n\n        // Now set correct engine and get the ATM rate and the price\n        caps_[j]->setPricingEngine(engine);\n        atmCapFloorStrikes_[j] = caps_[j]->atmRate(**discountCurve);\n        atmCapFloorPrices_[j] = caps_[j]->NPV();\n    }\n\n    spreadsVolImplied_ = spreadsVolImplied(discountCurve);\n\n    StrippedOptionletAdapter adapter(stripper_);\n    adapter.enableExtrapolation();\n\n    Volatility unadjustedVol, adjustedVol;\n    for (Size j = 0; j < nOptionExpiries_; ++j) {\n        for (Size i = 0; i < optionletVolatilities_.size(); ++i) {\n            if (i <= caps_[j]->floatingLeg().size()) {\n                unadjustedVol = adapter.volatility(optionletTimes_[i], atmCapFloorStrikes_[j]);\n                adjustedVol = unadjustedVol + spreadsVolImplied_[j];\n\n                // insert adjusted volatility\n                vector<Rate>::const_iterator previous =\n                    lower_bound(optionletStrikes_[i].begin(), optionletStrikes_[i].end(), atmCapFloorStrikes_[j]);\n                Size insertIndex = previous - optionletStrikes_[i].begin();\n\n                optionletStrikes_[i].insert(optionletStrikes_[i].begin() + insertIndex, atmCapFloorStrikes_[j]);\n                optionletVolatilities_[i].insert(optionletVolatilities_[i].begin() + insertIndex, adjustedVol);\n            }\n        }\n    }\n}\n\nvector<Volatility> OptionletStripper2::spreadsVolImplied(const Handle<YieldTermStructure>& discount) const {\n\n    Brent solver;\n    vector<Volatility> result(nOptionExpiries_);\n    Volatility guess = 0.0001, minSpread = -0.1, maxSpread = 0.1;\n    for (Size j = 0; j < nOptionExpiries_; ++j) {\n        ObjectiveFunction f(stripper_, caps_[j], atmCapFloorPrices_[j], discount);\n        solver.setMaxEvaluations(maxEvaluations_);\n        Volatility root = solver.solve(f, accuracy_, guess, minSpread, maxSpread);\n        result[j] = root;\n    }\n    return result;\n}\n\nvector<Volatility> OptionletStripper2::spreadsVol() const {\n    calculate();\n    return spreadsVolImplied_;\n}\n\nvector<Rate> OptionletStripper2::atmCapFloorStrikes() const {\n    calculate();\n    return atmCapFloorStrikes_;\n}\n\nvector<Real> OptionletStripper2::atmCapFloorPrices() const {\n    calculate();\n    return atmCapFloorPrices_;\n}\n\n// OptionletStripper2::ObjectiveFunction\nOptionletStripper2::ObjectiveFunction::ObjectiveFunction(\n    const boost::shared_ptr<QuantExt::OptionletStripper>& optionletStripper, const boost::shared_ptr<CapFloor>& cap,\n    Real targetValue, const Handle<YieldTermStructure>& discount)\n    : cap_(cap), targetValue_(targetValue), discount_(discount) {\n    boost::shared_ptr<OptionletVolatilityStructure> adapter(new StrippedOptionletAdapter(optionletStripper));\n    adapter->enableExtrapolation();\n\n    // set an implausible value, so that calculation is forced\n    // at first operator()(Volatility x) call\n    spreadQuote_ = boost::shared_ptr<SimpleQuote>(new SimpleQuote(-1.0));\n\n    boost::shared_ptr<OptionletVolatilityStructure> spreadedAdapter(\n        new SpreadedOptionletVolatility(Handle<OptionletVolatilityStructure>(adapter), Handle<Quote>(spreadQuote_)));\n\n    // Use the same volatility type as optionletStripper\n    // Anything else would not make sense\n    boost::shared_ptr<PricingEngine> engine;\n    if (optionletStripper->volatilityType() == ShiftedLognormal) {\n        engine = boost::make_shared<BlackCapFloorEngine>(\n            discount_, Handle<OptionletVolatilityStructure>(spreadedAdapter), optionletStripper->displacement());\n    } else if (optionletStripper->volatilityType() == Normal) {\n        engine = boost::make_shared<BachelierCapFloorEngine>(discount_,\n                                                             Handle<OptionletVolatilityStructure>(spreadedAdapter));\n    } else {\n        QL_FAIL(\"Unknown volatility type: \" << optionletStripper->volatilityType());\n    }\n\n    cap_->setPricingEngine(engine);\n}\n\nReal OptionletStripper2::ObjectiveFunction::operator()(Volatility s) const {\n    if (s != spreadQuote_->value())\n        spreadQuote_->setValue(s);\n    return cap_->NPV() - targetValue_;\n}\n} // namespace QuantExt\n", "meta": {"hexsha": "37b092661e28460d8b095148a06fbde4031da89f", "size": 8943, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/termstructures/optionletstripper2.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/optionletstripper2.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/optionletstripper2.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": 47.3174603175, "max_line_length": 120, "alphanum_fraction": 0.7132953148, "num_tokens": 2177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2821370667749739}}
{"text": "//| This file is a part of the sferes2 framework.\n//| Copyright 2009, ISIR / Universite Pierre et Marie Curie (UPMC)\n//| Main contributor(s): Jean-Baptiste Mouret, mouret@isir.fr\n//|\n//| This software is a computer program whose purpose is to facilitate\n//| experiments in evolutionary computation and evolutionary robotics.\n//|\n//| This software is governed by the CeCILL license under French law\n//| and abiding by the rules of distribution of free software.  You\n//| can use, modify and/ or redistribute the software under the terms\n//| of the CeCILL license as circulated by CEA, CNRS and INRIA at the\n//| following URL \"http://www.cecill.info\".\n//|\n//| As a counterpart to the access to the source code and rights to\n//| copy, modify and redistribute granted by the license, users are\n//| provided only with a limited warranty and the software's author,\n//| the holder of the economic rights, and the successive licensors\n//| have only limited liability.\n//|\n//| In this respect, the user's attention is drawn to the risks\n//| associated with loading, using, modifying and/or developing or\n//| reproducing the software by the user in light of its specific\n//| status of free software, that may mean that it is complicated to\n//| manipulate, and that also therefore means that it is reserved for\n//| developers and experienced professionals having in-depth computer\n//| knowledge. Users are therefore encouraged to load and test the\n//| software's suitability as regards their requirements in conditions\n//| enabling the security of their systems and/or data to be ensured\n//| and, more generally, to use and operate it in the same conditions\n//| as regards security.\n//|\n//| The fact that you are presently reading this means that you have\n//| had knowledge of the CeCILL license and that you accept its terms.\n\n#ifndef MODIFIER_NOVELTY_HPP\n#define MODIFIER_NOVELTY_HPP\n\n#include <Eigen/Core>\n#include \"sferes/parallel.hpp\"\n#include <boost/uuid/uuid.hpp>            // uuid class\n\n//#include <boost/accumulators/accumulators.hpp>\n//#include <boost/accumulators/statistics/stats.hpp>\n//\n//// Headers specifics to the computations we need\n//#include <boost/accumulators/statistics/max.hpp>\n//#include <boost/accumulators/statistics/min.hpp>\n\nnamespace sferes {\n  namespace modif {\n    namespace novelty {\n\n      // compute the matrix of distances\n      template<typename Phen>\n      struct _distance_f {\n        typedef std::vector<boost::shared_ptr<Phen> > pop_t;\n        const pop_t& _pop;\n        const pop_t& _archive;\n        Eigen::MatrixXf& distances;\n\n        ~_distance_f() { }\n        _distance_f(const pop_t& pop, const pop_t& archive, Eigen::MatrixXf& d) :\n          _pop(pop), _archive(archive), distances(d) {}\n        _distance_f(const _distance_f& ev) :\n          _pop(ev._pop), _archive(ev._archive), distances(ev.distances) {}\n\n        void operator() (const parallel::range_t& r) const {\n          for (size_t i = r.begin(); i != r.end(); ++i) {\n            for (size_t j = 0; j < _archive.size(); ++j)\n            {\n            \tfloat d = 0;\n\n            \t// Check if they are not the same image\n            \tif ((_pop[i] != _archive[j]) && (_pop[i]->id() != _archive[j]->id()))\n            \t{\n#ifdef EUCLIDEAN_DISTANCE\n            \t\t// Euclidean distance\n            \t\td = _pop[i]->dist(*_archive[j]);\n\n            \t\t#else\n            \t\t// Regular distance\n            \t\td = _pop[i]->fit().dist(*_archive[j]);\n#endif\n            \t}\n\n              distances(i, j) = d;\n            }\n          }\n        }\n      };\n    }\n\n    // The novelty score will be stored in the last objective 'slot'\n    // If there is only one objective (this->objs().size() == 1), then\n    // this modifiers is a standard Novelty search algorithm [1]\n    // otherwise, it is a \"novelty-based multi-objectivization\" [2]\n    // See [2] for more explanations of the differences between\n    // novelty search, multi-objective novelty search, and behavioral diversity\n    //\n    // * References\n    // [1] Lehman, Joel, and Kenneth O. Stanley. \"Abandoning objectives:\n    // Evolution through the search for novelty alone.\"\n    // Evolutionary computation 19.2 (2011): 189-223.\n    //\n    // [2] Mouret, Jean-Baptiste. \"Novelty-based multiobjectivization.\"\n    // New Horizons in Evolutionary Robotics. Springer Berlin Heidelberg,\n    // 2011. 139-154.\n    template<typename Phen, typename Params, typename Exact = stc::Itself>\n    class Novelty {\n     public:\n      typedef boost::shared_ptr<Phen> phen_t;\n      typedef std::vector<phen_t> pop_t;\n      Novelty() : _rho_min(Params::novelty::rho_min_init), _not_added(0) {}\n\n      template<typename Ea>\n      void apply(Ea& ea)\n      {\n//      \tboost::accumulators::accumulator_set<double, boost::accumulators::stats<boost::accumulators::tag::max> > acc_max;\n//      \tboost::accumulators::accumulator_set<double, boost::accumulators::stats<boost::accumulators::tag::min> > acc_min;\n\n        SFERES_CONST size_t k = Params::novelty::k;\n        // merge the population and the archive in a single archive\n        pop_t archive = _archive;\n        archive.insert(archive.end(), ea.pop().begin(), ea.pop().end());\n\n        // we compute all the distances from pop(i) to archive(j) and store them\n        Eigen::MatrixXf distances(ea.pop().size(), archive.size());\n        novelty::_distance_f<Phen> f(ea.pop(), archive, distances);\n        parallel::init();\n        parallel::p_for(parallel::range_t(0, ea.pop().size()), f);\n\n        // compute the sparseness of each individual of the population\n        // and potentially add to the archive\n        int added = 0;\n\n        for (size_t i = 0; i < ea.pop().size(); ++i) {\n          size_t nb_objs = ea.pop()[i]->fit().objs().size();\n          Eigen::VectorXf vd = distances.row(i);\n\n          // Get the k-nearest neighbors\n          double n = 0.0;\n          std::partial_sort(vd.data(),\n                            vd.data() + k,\n                            vd.data() + vd.size());\n\n          // Sum up the total of distances from k-nearest neighbors\n          // This is the novelty score\n          n = vd.head<k>().sum() / k;\n\n          // Set the novelty score to the last objective in the array of objectives\n          ea.pop()[i]->fit().set_obj(nb_objs - 1, n);\n\n//          std::cout << \"rho = \" << _rho_min << \"; n = \" << n << \"\\n\";\n//          acc_max(n);\n//          acc_min(n);\n\n          // Check if this individual is already in the archive\n          if (!in_archive_already(ea.pop()[i]->id()) &&\n          \t\t(n > _rho_min\t\t\t// Check if the novelty score passes the threshold\n              || misc::rand<float>() < Params::novelty::add_to_archive_prob))\n          {\n          \t// Add this individual to the permanent archive\n          \t_archive.push_back(ea.pop()[i]);\n\n          \t// Print this indiv just added\n//            std::cout << \"----> n = \" << n << \"; label = \" << ea.pop()[i]->fit().label() << \"; score = \" << ea.pop()[i]->fit().score() << \"; id = \" << ea.pop()[i]->id()  <<\"\\n\";\n//          \tstd::cout << \"----> n = \" << n << \"; label = \" << \"; id = \" << ea.pop()[i]->id()  <<\"\\n\";\n\n            _not_added = 0;\n            ++added;\n          } else {\n          \t// Do not add this individual to the archive\n            ++_not_added;\n          }\n        } // end for all individuals\n\n        // update rho_min\n        if (_not_added > Params::novelty::stalled_tresh)//2500\n        {\n          _rho_min *= 0.95;\t// Lower rho_min\n          _not_added = 0;\t\t// After lowering the stalled threshold, we need to reset the _not_added count\n        }\n        if (_archive.size() > Params::novelty::k && added > Params::novelty::adding_tresh)//4\n        {\n          _rho_min *= 1.05f;\t// Increase rho_min\n        }\n\n        std::cout<<\"a size:\"<<_archive.size()<<std::endl;\n\n        // DEBUG\n//        std::cout << \"a size:\"<<_archive.size()\n//        \t\t<< \"; max: \" << boost::accumulators::max(acc_max)\n//        \t\t<< \"; min: \" << boost::accumulators::min(acc_min)\n//        \t\t<< std::endl;\n\n      }\n\n      /*\n\t\t\t * Check if this individual is already in the archive.\n\t\t\t */\n\t\t\tconst bool in_archive_already ( const boost::uuids::uuid& id )\n\t\t\t{\n\t\t\t\t/* Comment out to save computation time\n\t\t\t\tfor (int i = 0; i < _archive.size(); ++i)\n\t\t\t\t{\n\t\t\t\t\t// Check if this id is found in the archive.\n\t\t\t\t\tif (_archive[i]->id() == id)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\t*/\n\n\t\t\t\treturn false;\n\t\t\t}\n\n      /*\n       * Getter of archive.\n       *\n       * This function is created for statistics class to save the archive down to gen file.\n       * 2015-01-21\n       */\n      const pop_t& archive() const\n      {\n      \treturn _archive;\n      }\n\n      /*\n       * Setter of archive.\n       *\n       * This function is created for statistics class to save the archive down to gen file.\n       * 2015-01-21\n       */\n      void set_archive(const pop_t& archive)\n      {\n      \t_archive.clear();\n\n      \t// Assign items to archive\n      \t_archive.insert(_archive.end(), archive.begin(), archive.end());\n      }\n\n     protected:\n      pop_t _archive;\n      float _rho_min;\n      size_t _not_added;\n    };\n  } // modif\n} // sferes\n\n#endif\n", "meta": {"hexsha": "da6080bd34586f698782c5573605dd72433c89f2", "size": 9139, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sferes/sferes/modif/novelty.hpp", "max_stars_repo_name": "Evolving-AI-Lab/innovation-engine", "max_stars_repo_head_hexsha": "58c7fcc3cbe3d6f8f59f87d95bdb5f2302f425ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2015-09-20T03:03:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T06:50:20.000Z", "max_issues_repo_path": "sferes/sferes/modif/novelty.hpp", "max_issues_repo_name": "Evolving-AI-Lab/innovation-engine", "max_issues_repo_head_hexsha": "58c7fcc3cbe3d6f8f59f87d95bdb5f2302f425ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-08-11T07:24:50.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-17T01:19:57.000Z", "max_forks_repo_path": "sferes/sferes/modif/novelty.hpp", "max_forks_repo_name": "Evolving-AI-Lab/innovation-engine", "max_forks_repo_head_hexsha": "58c7fcc3cbe3d6f8f59f87d95bdb5f2302f425ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-11-15T01:52:25.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-11T23:42:58.000Z", "avg_line_length": 36.2658730159, "max_line_length": 179, "alphanum_fraction": 0.5957982274, "num_tokens": 2310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.28213706677497385}}
{"text": "// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.\n\n/* separation_stats.cc\n   Jeremy Barnes, 14 June 2011\n   Copyright (c) 2011 mldb.ai inc.  All rights reserved.\n\n*/\n\n#include \"separation_stats.h\"\n#include \"mldb/arch/exception.h\"\n#include \"mldb/base/exc_assert.h\"\n#include <boost/utility.hpp>\n#include \"mldb/vfs/filter_streams.h\"\n\n\nusing namespace std;\n\nnamespace MLDB {\n\n/*****************************************************************************/\n/* BINARY STATS                                                              */\n/*****************************************************************************/\n\ndouble\nBinaryStats::\nrocAreaSince(const BinaryStats & other) const\n{\n    double tp1 = other.truePositiveRate(), fp1 = other.falsePositiveRate();\n    double tp2 = truePositiveRate(), fp2 = falsePositiveRate();\n\n    double result = (fp2 - fp1) * (tp1 + tp2) * 0.5;\n\n    //cerr << \"tp1 = \" << tp1 << \" tp2 = \" << tp2 << \" fp1 = \" << fp1\n    //     << \" fp2 = \" << fp2 << \" area = \" << result << endl;\n\n    return result;\n}\n\nvoid\nBinaryStats::\nadd(const BinaryStats & other, double weight)\n{\n    auto addCounts = [&] (      Array2D & local,\n                          const Array2D & other,\n                                       float w)\n\n    {\n        local[0][0] += w * other[0][0];\n        local[0][1] += w * other[0][1];\n        local[1][0] += w * other[1][0];\n        local[1][1] += w * other[1][1];\n    };\n\n    addCounts(counts, other.counts, weight);\n    addCounts(unweighted_counts, other.unweighted_counts, 1);\n\n    threshold += weight * other.threshold;\n}\n\nJson::Value\nBinaryStats::\ntoJson() const\n{\n    Json::Value result;\n    result[\"population\"][\"included\"] = includedPopulation();\n    result[\"population\"][\"excluded\"] = excludedPopulation();\n    result[\"pr\"][\"accuracy\"] = accuracy();\n    result[\"pr\"][\"precision\"] = precision();\n    result[\"pr\"][\"recall\"] = recall();\n    result[\"pr\"][\"f1Score\"] = f();\n    result[\"mcc\"] = mcc();\n    result[\"gain\"] = gain();\n    result[\"counts\"][\"truePositives\"] = truePositives();\n    result[\"counts\"][\"falsePositives\"] = falsePositives();\n    result[\"counts\"][\"trueNegatives\"] = trueNegatives();\n    result[\"counts\"][\"falseNegatives\"] = falseNegatives();\n    result[\"threshold\"] = threshold;\n    return result;\n}\n\n\n/*****************************************************************************/\n/* SCORED STATS                                                              */\n/*****************************************************************************/\n\nScoredStats::\nScoredStats()\n    : auc(1.0), isSorted(true)\n{\n}\n\nBinaryStats\nScoredStats::\natThreshold(float threshold) const\n{\n    struct FindThreshold {\n        bool operator () (const BinaryStats & e1, const BinaryStats & e2) const\n        {\n            return e1.threshold > e2.threshold;\n        }\n\n        bool operator () (const BinaryStats & e1, float e2) const\n        {\n            return e1.threshold > e2;\n        }\n\n        bool operator () (float e1, const BinaryStats & e2) const\n        {\n            return e1 > e2.threshold;\n        }\n    };\n\n    if (!std::is_sorted(stats.begin(), stats.end(), FindThreshold()))\n        throw Exception(\"stats not sorted on input\");\n\n    if (stats.empty())\n        throw Exception(\"stats is empty\");\n\n    // Lower bound means strictly above\n    auto lower\n        = std::lower_bound(stats.begin(), stats.end(), threshold,\n                           FindThreshold());\n    \n    if (lower == stats.end())\n        return stats.back();\n\n    return *lower;\n}\n\nBinaryStats\nScoredStats::\natPercentile(float percentile) const\n{\n    struct FindPercentile {\n        bool operator () (const BinaryStats & e1, const BinaryStats & e2) const\n        {\n            return e1.proportionOfPopulation() < e2.proportionOfPopulation();\n        }\n\n        bool operator () (const BinaryStats & e1, float e2) const\n        {\n            return e1.proportionOfPopulation() < e2;\n        }\n\n        bool operator () (float e1, const BinaryStats & e2) const\n        {\n            return e1 < e2.proportionOfPopulation();\n        }\n    };\n\n    for (unsigned i = 1;  i < stats.size();  ++i) {\n        if (stats[i -1].proportionOfPopulation() > stats[i].proportionOfPopulation()) {\n            cerr << \"i = \" << i << endl;\n            cerr << \"prev = \" << stats[i - 1].toJson() << endl;\n            cerr << \"ours = \" << stats[i].toJson() << endl;\n            throw MLDB::Exception(\"really not sorted on input\");\n        }\n    }\n\n    if (!std::is_sorted(stats.begin(), stats.end(), FindPercentile()))\n        throw Exception(\"stats not sorted on input\");\n\n    if (stats.empty())\n        throw Exception(\"stats is empty\");\n\n    // Lower bound means strictly above\n    auto it\n        = std::lower_bound(stats.begin(), stats.end(), percentile,\n                           FindPercentile());\n\n    if (it == stats.begin())\n        return *it;\n\n    if (it == stats.end())\n        return stats.back();\n\n    BinaryStats upper = *it, lower = *std::prev(it);\n\n    // Do an interpolation\n    double atUpper = upper.proportionOfPopulation(),\n           atLower = lower.proportionOfPopulation(),\n           range = atUpper - atLower;\n\n    ExcAssertLessEqual(percentile, atUpper);\n    ExcAssertGreaterEqual(percentile, atLower);\n    ExcAssertGreater(range, 0);\n\n    double weight1 = (atUpper - percentile) / range;\n    double weight2 = (percentile - atLower) / range;\n\n    //cerr << \"atUpper = \" << atUpper << \" atLower = \" << atLower\n    //     << \" range = \" << range << \" weight1 = \" << weight1\n    //     << \" weight2 = \" << weight2 << endl;\n\n    BinaryStats result;\n    result.add(upper, weight2);\n    result.add(lower, weight1);\n    \n    //cerr << \"result prop = \" << result.proportionOfPopulation() << endl;\n\n    return result;\n}\n\nvoid\nScoredStats::\nsort()\n{\n    // Go from highest to lowest score\n    std::sort(entries.begin(), entries.end());\n    isSorted = true;\n}\n\nvoid\nScoredStats::\ncalculate()\n{\n    BinaryStats current;\n    \n    for (unsigned i = 0;  i < entries.size();  ++i)\n        current.counts[entries[i].label][false] += entries[i].weight;\n\n    if (!isSorted)\n        sort();\n\n    bestF = current;\n    bestMcc = current;\n\n    double totalAuc = 0.0;\n\n    stats.clear();\n\n    // take the all point\n    stats.push_back(BinaryStats(current, INFINITY));\n\n    for (unsigned i = 0;  i < entries.size();  ++i) {\n        const ScoredStats::ScoredEntry & entry = entries[i];\n\n        if (i > 0 && entries[i - 1].score != entry.score) {\n            totalAuc += current.rocAreaSince(stats.back());\n            stats.push_back\n                (BinaryStats(current, entries[i - 1].score, entry.key));\n\n            if (current.f() > bestF.f())\n                bestF = stats.back();\n            if (current.mcc() > bestMcc.mcc())\n                bestMcc = stats.back();\n            if (current.specificity() > bestSpecificity.specificity())\n                bestSpecificity = stats.back();\n\n            \n#if 0\n            cerr << \"entry \" << i << \": score \" << entries[i - 1].score\n                 << \" p \" << current.precision() << \" r \" << current.recall()\n                 << \" f \" << current.f() << \" mcc \" << current.mcc() << endl;\n#endif\n        }\n\n        bool label = entry.label;\n\n        // We transfer from a false positive to a true negative, or a\n        // true positive to a false negative\n\n        double weight = entry.weight;\n\n        current.counts[label][false] -= weight;\n        current.counts[label][true] += weight;\n\n        current.unweighted_counts[label][false] -= 1;\n        current.unweighted_counts[label][true] += 1;\n\n    }\n    \n    totalAuc += current.rocAreaSince(stats.back());\n\n    if (!entries.empty())\n        stats.push_back(BinaryStats(current, entries.back().score));\n\n    auc = totalAuc;\n}\n\nvoid\nScoredStats::\nadd(const ScoredStats & other)\n{\n    if (!isSorted)\n        throw MLDB::Exception(\"attempt to add to non-sorted separation stats\");\n    if (!other.isSorted)\n        throw MLDB::Exception(\"attempt to add non-sorted separation stats\");\n\n    size_t split = entries.size();\n    entries.insert(entries.end(), other.entries.begin(), other.entries.end());\n    std::inplace_merge(entries.begin(), entries.begin() + split,\n                       entries.end());\n\n    // If we had already calculated, we recalculate\n    if (!stats.empty())\n        calculate();\n}\n\nvoid\nScoredStats::\ndumpRocCurveJs(std::ostream & stream) const\n{\n    if (stats.empty())\n        throw MLDB::Exception(\"can't dump ROC curve without calling calculate()\");\n\n    stream << \"this.data = {\" << endl;\n    stream << MLDB::format(\"  \\\"aroc\\\": %8.05f , \", auc) << endl;\n    stream << \"  \\\"model\\\":{\";\n    for(unsigned i = 0;  i < stats.size();  ++i) {\n        const BinaryStats & x = stats[i];\n        stream << MLDB::format(\"\\n  \\\"%8.05f\\\": { \", x.threshold);\n        stream << MLDB::format(\"\\n  tpr : %8.05f,\", x.recall());\n        stream << MLDB::format(\"\\n  accuracy : %8.05f,\", x.accuracy());\n        stream << MLDB::format(\"\\n  precision : %8.05f,\", x.precision());\n        stream << MLDB::format(\"\\n  fscore : %8.05f,\", x.f());\n        stream << MLDB::format(\"\\n  fpr : %8.05f,\", x.falsePositiveRate());\n        stream << MLDB::format(\"\\n  tp : %8.05f,\", x.truePositives());\n        stream << MLDB::format(\"\\n  fp : %8.05f,\", x.falsePositives());\n        stream << MLDB::format(\"\\n  fn : %8.05f,\", x.falseNegatives());\n        stream << MLDB::format(\"\\n  tn : %8.05f,\", x.trueNegatives());\n        stream << MLDB::format(\"}\");\n        stream << \",\";\n    }\n    stream << \"\\n}\";\n    stream << \"};\";\n}\n\nvoid\nScoredStats::\nsaveRocCurveJs(const std::string & filename) const\n{\n    filter_ostream stream(filename);\n    dumpRocCurveJs(stream);\n}\n\nJson::Value\nScoredStats::\ngetRocCurveJson() const\n{\n    if (stats.empty())\n        throw MLDB::Exception(\"can't dump ROC curve without calling calculate()\");\n\n    Json::Value modelJs;\n    for(unsigned i = 0;  i < stats.size();  ++i) {\n        const BinaryStats & x = stats[i];\n        modelJs[MLDB::format(\"%8.05f\", x.threshold)] = x.toJson();\n    }\n\n    Json::Value js;\n    js[\"aroc\"] = auc;\n    js[\"model\"] = modelJs;\n    js[\"bestF1Score\"] = bestF.toJson();\n    js[\"bestMcc\"] = bestMcc.toJson();\n\n    return js;\n}\n\nvoid\nScoredStats::\nsaveRocCurveJson(const std::string & filename) const\n{\n    filter_ostream stream(filename);\n    stream << getRocCurveJson().toStyledString() << endl;\n}\n\nJson::Value\nScoredStats::\ntoJson() const\n{\n    Json::Value result;\n    result[\"auc\"] = auc;\n    result[\"bestF1Score\"] = bestF.toJson();\n    result[\"bestMcc\"] = bestMcc.toJson();\n    return result;\n}\n\n} // namespace MLDB\n", "meta": {"hexsha": "2ef57acf851a622159e34d53535dfb172d25b23e", "size": 10625, "ext": "cc", "lang": "C++", "max_stars_repo_path": "plugins/jml/separation_stats.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/separation_stats.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/separation_stats.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": 28.0343007916, "max_line_length": 87, "alphanum_fraction": 0.5479529412, "num_tokens": 2653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.28213706042599335}}
{"text": "/*\n * This file belongs to the Galois project, a C++ library for exploiting\n * parallelism. The code is being released under the terms of the 3-Clause BSD\n * License (a copy is located in LICENSE.txt at the top-level directory).\n *\n * Copyright (C) 2018, The University of Texas at Austin. All rights reserved.\n * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS\n * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF\n * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF\n * DEALING OR USAGE OF TRADE.  NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH\n * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances\n * shall University be liable for incidental, special, indirect, direct or\n * consequential damages or loss of profits, interruption of business, or\n * related expenses which may arise from use of Software or Documentation,\n * including but not limited to those resulting from defects in Software and/or\n * Documentation, or loss or inaccuracy of data of any kind.\n */\n\n/**********************************************************************************************/\n/*  This program is part of the Barcelona OpenMP Tasks Suite */\n/*  Copyright (C) 2009 Barcelona Supercomputing Center - Centro Nacional de\n * Supercomputacion  */\n/*  Copyright (C) 2009 Universitat Politecnica de Catalunya */\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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301\n * USA            */\n/**********************************************************************************************/\n\n#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <libgen.h>\n#include \"bots.h\"\n#include \"sparselu.h\"\n\n#include \"galois/Galois.h\"\n#include \"galois/Timer.h\"\n#include \"galois/LargeArray.h\"\n#include \"galois/graphs/FileGraph.h\"\n#include \"galois/runtime/KDGtwoPhase.h\"\n#include <boost/iterator/transform_iterator.hpp>\n#include <boost/iterator/counting_iterator.hpp>\n\nextern char bots_arg_file[256];\n\n/***********************************************************************\n * checkmat:\n **********************************************************************/\nint checkmat(float* M, float* N) {\n  int i, j;\n  float r_err;\n\n  for (i = 0; i < bots_arg_size_1; i++) {\n    for (j = 0; j < bots_arg_size_1; j++) {\n      r_err = M[i * bots_arg_size_1 + j] - N[i * bots_arg_size_1 + j];\n      if (r_err == 0.0)\n        continue;\n\n      if (r_err < 0.0)\n        r_err = -r_err;\n\n      if (M[i * bots_arg_size_1 + j] == 0) {\n        bots_message(\"Checking failure: A[%d][%d]=%f  B[%d][%d]=%f; \\n\", i, j,\n                     M[i * bots_arg_size_1 + j], i, j,\n                     N[i * bots_arg_size_1 + j]);\n        return FALSE;\n      }\n      r_err = r_err / M[i * bots_arg_size_1 + j];\n      if (r_err > EPSILON) {\n        bots_message(\n            \"Checking failure: A[%d][%d]=%f  B[%d][%d]=%f; Relative Error=%f\\n\",\n            i, j, M[i * bots_arg_size_1 + j], i, j, N[i * bots_arg_size_1 + j],\n            r_err);\n        return FALSE;\n      }\n    }\n  }\n  return TRUE;\n}\n\n/***********************************************************************\n * genmat:\n **********************************************************************/\nstatic void synthetic_genmat(float* M[]) {\n  int null_entry, init_val, i, j, ii, jj;\n  float* p;\n  int a = 0, b = 0;\n\n  init_val = 1325;\n\n  /* generating the structure */\n  for (ii = 0; ii < bots_arg_size; ii++) {\n    for (jj = 0; jj < bots_arg_size; jj++) {\n      /* computing null entries */\n      null_entry = FALSE;\n      if ((ii < jj) && (ii % 3 != 0))\n        null_entry = TRUE;\n      if ((ii > jj) && (jj % 3 != 0))\n        null_entry = TRUE;\n      if (ii % 2 == 1)\n        null_entry = TRUE;\n      if (jj % 2 == 1)\n        null_entry = TRUE;\n      if (ii == jj)\n        null_entry = FALSE;\n      if (ii == jj - 1)\n        null_entry = FALSE;\n      if (ii - 1 == jj)\n        null_entry = FALSE;\n      /* allocating matrix */\n      if (null_entry == FALSE) {\n        a++;\n        M[ii * bots_arg_size + jj] =\n            (float*)malloc(bots_arg_size_1 * bots_arg_size_1 * sizeof(float));\n        if (M[ii * bots_arg_size + jj] == NULL) {\n          bots_message(\"Error: Out of memory\\n\");\n          exit(101);\n        }\n        /* initializing matrix */\n        p = M[ii * bots_arg_size + jj];\n        for (i = 0; i < bots_arg_size_1; i++) {\n          for (j = 0; j < bots_arg_size_1; j++) {\n            init_val = (3125 * init_val) % 65536;\n            (*p)     = (float)((init_val - 32768.0) / 16384.0);\n            p++;\n          }\n        }\n      } else {\n        b++;\n        M[ii * bots_arg_size + jj] = NULL;\n      }\n    }\n  }\n  bots_debug(\"allo = %d, no = %d, total = %d, factor = %f\\n\", a, b, a + b,\n             (float)((float)a / (float)(a + b)));\n}\n\n// From symmetric matrix\nstatic void structure_from_file_genmat(float* M[]) {\n  int ii, jj;\n  int a = 0, b;\n  galois::graphs::FileGraph g;\n  int num_blocks;\n  unsigned max_id;\n\n  g.fromFile(bots_arg_file);\n  memset(M, 0, bots_arg_size * bots_arg_size * sizeof(*M));\n\n  num_blocks = (g.size() + bots_arg_size_1 - 1) / bots_arg_size_1;\n  max_id     = bots_arg_size_1 * bots_arg_size;\n\n  printf(\"full size: %d\\n\", num_blocks);\n\n  /* generating the structure */\n  for (auto ii : g) {\n    if (ii >= max_id)\n      break;\n    int bii = ii / bots_arg_size_1;\n    for (auto edge : g.out_edges(ii)) {\n      /* computing null entries */\n      int jj = g.getEdgeDst(edge);\n      if (jj >= max_id)\n        continue;\n      int bjj = jj / bots_arg_size_1;\n      if (M[bii * bots_arg_size + bjj] == NULL) {\n        a++;\n        M[bii * bots_arg_size + bjj] =\n            (float*)malloc(bots_arg_size_1 * bots_arg_size_1 * sizeof(float));\n        memset(M[bii * bots_arg_size + bjj], 0,\n               bots_arg_size_1 * bots_arg_size_1 * sizeof(float));\n      }\n      if (M[bii * bots_arg_size + bjj] == NULL) {\n        bots_message(\"Error: Out of memory\\n\");\n        exit(101);\n      }\n      if (M[bjj * bots_arg_size + bii] == NULL) {\n        a++;\n        M[bjj * bots_arg_size + bii] =\n            (float*)malloc(bots_arg_size_1 * bots_arg_size_1 * sizeof(float));\n        memset(M[bjj * bots_arg_size + bii], 0,\n               bots_arg_size_1 * bots_arg_size_1 * sizeof(float));\n      }\n      if (M[bjj * bots_arg_size + bii] == NULL) {\n        bots_message(\"Error: Out of memory\\n\");\n        exit(101);\n      }\n      M[bii * bots_arg_size + bjj]\n       [(ii % bots_arg_size_1) * bots_arg_size_1 + (jj % bots_arg_size_1)] =\n           g.getEdgeData<float>(edge);\n      M[bjj * bots_arg_size + bii]\n       [(jj % bots_arg_size_1) * bots_arg_size_1 + (ii % bots_arg_size_1)] =\n           g.getEdgeData<float>(edge);\n    }\n  }\n  // Add identity diagonal as necessary\n  for (ii = 0; ii < bots_arg_size; ++ii) {\n    if (M[ii * bots_arg_size + ii] == NULL) {\n      a++;\n      M[ii * bots_arg_size + ii] =\n          (float*)malloc(bots_arg_size_1 * bots_arg_size_1 * sizeof(float));\n      memset(M[ii * bots_arg_size + ii], 0,\n             bots_arg_size_1 * bots_arg_size_1 * sizeof(float));\n    }\n    for (jj = 0; jj < bots_arg_size_1; ++jj) {\n      if (M[ii * bots_arg_size + ii][jj * bots_arg_size_1 + jj] == 0.0)\n        M[ii * bots_arg_size + ii][jj * bots_arg_size_1 + jj] = 1.0;\n    }\n  }\n  b = num_blocks * num_blocks - a;\n  bots_debug(\"allo = %d, no = %d, total = %d, factor = %f\\n\", a, b, a + b,\n             (float)((float)a / (float)(a + b)));\n}\n\nvoid genmat(float* M[]) {\n  if (strlen(bots_arg_file) == 0)\n    synthetic_genmat(M);\n  else\n    structure_from_file_genmat(M);\n}\n\n/***********************************************************************\n * print_structure:\n **********************************************************************/\nvoid print_structure(char* name, float* M[]) {\n  int ii, jj;\n  bots_message(\"Structure for matrix %s @ 0x%p\\n\", name, M);\n  for (ii = 0; ii < bots_arg_size; ii++) {\n    for (jj = 0; jj < bots_arg_size; jj++) {\n      if (M[ii * bots_arg_size + jj] != NULL) {\n        bots_message(\"x\");\n      } else\n        bots_message(\" \");\n    }\n    bots_message(\"\\n\");\n  }\n  bots_message(\"\\n\");\n}\n/***********************************************************************\n * allocate_clean_block:\n **********************************************************************/\nfloat* allocate_clean_block() {\n  int i, j;\n  float *p, *q;\n\n  p = (float*)malloc(bots_arg_size_1 * bots_arg_size_1 * sizeof(float));\n  q = p;\n  if (p != NULL) {\n    for (i = 0; i < bots_arg_size_1; i++)\n      for (j = 0; j < bots_arg_size_1; j++) {\n        (*p) = 0.0;\n        p++;\n      }\n\n  } else {\n    bots_message(\"Error: Out of memory\\n\");\n    exit(101);\n  }\n  return (q);\n}\n\n/***********************************************************************\n * lu0:\n **********************************************************************/\nvoid lu0(float* diag) {\n  int i, j, k;\n\n  for (k = 0; k < bots_arg_size_1; k++)\n    for (i = k + 1; i < bots_arg_size_1; i++) {\n      diag[i * bots_arg_size_1 + k] =\n          diag[i * bots_arg_size_1 + k] / diag[k * bots_arg_size_1 + k];\n      for (j = k + 1; j < bots_arg_size_1; j++)\n        diag[i * bots_arg_size_1 + j] =\n            diag[i * bots_arg_size_1 + j] -\n            diag[i * bots_arg_size_1 + k] * diag[k * bots_arg_size_1 + j];\n    }\n}\n\n/***********************************************************************\n * bdiv:\n **********************************************************************/\nvoid bdiv(float* diag, float* row) {\n  int i, j, k;\n  for (i = 0; i < bots_arg_size_1; i++)\n    for (k = 0; k < bots_arg_size_1; k++) {\n      row[i * bots_arg_size_1 + k] =\n          row[i * bots_arg_size_1 + k] / diag[k * bots_arg_size_1 + k];\n      for (j = k + 1; j < bots_arg_size_1; j++)\n        row[i * bots_arg_size_1 + j] =\n            row[i * bots_arg_size_1 + j] -\n            row[i * bots_arg_size_1 + k] * diag[k * bots_arg_size_1 + j];\n    }\n}\n/***********************************************************************\n * bmod:\n **********************************************************************/\nvoid bmod(float* row, float* col, float* inner) {\n  int i, j, k;\n  for (i = 0; i < bots_arg_size_1; i++)\n    for (j = 0; j < bots_arg_size_1; j++)\n      for (k = 0; k < bots_arg_size_1; k++)\n        inner[i * bots_arg_size_1 + j] =\n            inner[i * bots_arg_size_1 + j] -\n            row[i * bots_arg_size_1 + k] * col[k * bots_arg_size_1 + j];\n}\n/***********************************************************************\n * fwd:\n **********************************************************************/\nvoid fwd(float* diag, float* col) {\n  int i, j, k;\n  for (j = 0; j < bots_arg_size_1; j++)\n    for (k = 0; k < bots_arg_size_1; k++)\n      for (i = k + 1; i < bots_arg_size_1; i++)\n        col[i * bots_arg_size_1 + j] =\n            col[i * bots_arg_size_1 + j] -\n            diag[i * bots_arg_size_1 + k] * col[k * bots_arg_size_1 + j];\n}\n\nstatic galois::LargeArray<galois::runtime::Lockable> locks;\n\nvoid sparselu_init(float*** pBENCH, char* pass) {\n  galois::setActiveThreads(bots_arg_size_2);\n  galois::substrate::getThreadPool().burnPower(bots_arg_size_2);\n  galois::preAlloc(5 * bots_arg_size_2);\n  galois::reportPageAlloc(\"MeminfoPre\");\n  *pBENCH = (float**)malloc(bots_arg_size * bots_arg_size * sizeof(float*));\n  genmat(*pBENCH);\n  print_structure(pass, *pBENCH);\n  // locks.allocateInterleaved(bots_arg_size*bots_arg_size); XXX\n  locks.allocateLocal(bots_arg_size * bots_arg_size);\n  locks.construct();\n}\n\nvoid sparselu_seq_call(float** BENCH) {\n  int ii, jj, kk;\n\n  for (kk = 0; kk < bots_arg_size; kk++) {\n    lu0(BENCH[kk * bots_arg_size + kk]);\n    for (jj = kk + 1; jj < bots_arg_size; jj++)\n      if (BENCH[kk * bots_arg_size + jj] != NULL) {\n        fwd(BENCH[kk * bots_arg_size + kk], BENCH[kk * bots_arg_size + jj]);\n      }\n    for (ii = kk + 1; ii < bots_arg_size; ii++)\n      if (BENCH[ii * bots_arg_size + kk] != NULL) {\n        bdiv(BENCH[kk * bots_arg_size + kk], BENCH[ii * bots_arg_size + kk]);\n      }\n    for (ii = kk + 1; ii < bots_arg_size; ii++)\n      if (BENCH[ii * bots_arg_size + kk] != NULL)\n        for (jj = kk + 1; jj < bots_arg_size; jj++)\n          if (BENCH[kk * bots_arg_size + jj] != NULL) {\n            if (BENCH[ii * bots_arg_size + jj] == NULL)\n              BENCH[ii * bots_arg_size + jj] = allocate_clean_block();\n            bmod(BENCH[ii * bots_arg_size + kk], BENCH[kk * bots_arg_size + jj],\n                 BENCH[ii * bots_arg_size + jj]);\n          }\n  }\n}\n\nstruct FwdBdiv {\n  typedef int tt_does_not_need_aborts;\n\n  float** BENCH;\n  int kk;\n\n  enum { SEEK, FWD, BDIV };\n\n  struct Task {\n    int type;\n    int arg;\n  };\n\n  struct Initializer : public std::unary_function<int, Task> {\n    Task operator()(int arg) const { return {SEEK, arg}; }\n  };\n\n  void doSeek(const Task& t, galois::UserContext<Task>& ctx) {\n    int jj = t.arg;\n    if (BENCH[kk * bots_arg_size + jj] != NULL)\n      ctx.push(Task{FWD, jj});\n    int ii = t.arg;\n    if (BENCH[ii * bots_arg_size + kk] != NULL)\n      ctx.push(Task{BDIV, ii});\n  }\n\n  void doFwd(const Task& t, galois::UserContext<Task>& ctx) {\n    int jj = t.arg;\n    fwd(BENCH[kk * bots_arg_size + kk], BENCH[kk * bots_arg_size + jj]);\n  }\n\n  void doBdiv(const Task& t, galois::UserContext<Task>& ctx) {\n    int ii = t.arg;\n    bdiv(BENCH[kk * bots_arg_size + kk], BENCH[ii * bots_arg_size + kk]);\n  }\n\n  void operator()(const Task& t, galois::UserContext<Task>& ctx) {\n    switch (t.type) {\n    case SEEK:\n      return doSeek(t, ctx);\n    case FWD:\n      return doFwd(t, ctx);\n    case BDIV:\n      return doBdiv(t, ctx);\n    default:\n      abort();\n    }\n  }\n};\n\nstruct Bmod {\n  typedef int tt_does_not_need_aborts;\n\n  float** BENCH;\n  int kk;\n\n  enum { SEEK, BMOD };\n\n  struct Task {\n    int type;\n    int arg1;\n    int arg2;\n  };\n\n  struct Initializer : public std::unary_function<int, Task> {\n    Task operator()(int arg) const { return {SEEK, arg, arg}; }\n  };\n\n  void doSeek(const Task& t, galois::UserContext<Task>& ctx) {\n    int ii = t.arg1;\n    if (BENCH[ii * bots_arg_size + kk] != NULL)\n      for (int jj = kk + 1; jj < bots_arg_size; jj++)\n        if (BENCH[kk * bots_arg_size + jj] != NULL)\n          ctx.push(Task{BMOD, ii, jj});\n  }\n\n  void doBmod(const Task& t, galois::UserContext<Task>& ctx) {\n    int ii = t.arg1;\n    int jj = t.arg2;\n    if (BENCH[ii * bots_arg_size + jj] == NULL)\n      BENCH[ii * bots_arg_size + jj] = allocate_clean_block();\n    bmod(BENCH[ii * bots_arg_size + kk], BENCH[kk * bots_arg_size + jj],\n         BENCH[ii * bots_arg_size + jj]);\n  }\n\n  void operator()(const Task& t, galois::UserContext<Task>& ctx) {\n    switch (t.type) {\n    case SEEK:\n      return doSeek(t, ctx);\n    case BMOD:\n      return doBmod(t, ctx);\n    default:\n      abort();\n    }\n  }\n};\n\nstruct FwdBdivBmod {\n  enum { LU0 = 0, FWD = 1, BDIV = 2, BMOD = 3 };\n\n  struct Task {\n    int type;\n    int kk;\n    int arg0;\n    int arg1;\n  };\n\n  struct Initializer : public std::unary_function<int, Task> {\n    Task operator()(int kk) const { return {LU0, kk, 0, 0}; }\n  };\n\n  struct Comparator {\n    bool operator()(const Task& t1, const Task& t2) const {\n      // Lexicographic (kk, type, arg0, arg1)\n      if (t1.kk == t2.kk)\n        if (t1.type == t2.type)\n          if (t1.arg0 == t2.arg0)\n            return t1.arg1 < t2.arg1;\n          else\n            return t1.arg0 < t2.arg0;\n        else\n          return t1.type < t2.type;\n      else\n        return t1.kk < t2.kk;\n    }\n  };\n\n  struct NeighborhoodVisitor {\n    static const unsigned CHUNK_SIZE = 4;\n    float** BENCH;\n\n    typedef int tt_does_not_need_push;\n\n    void acquire(int ii, int jj) {\n      galois::runtime::acquire(&locks[ii * bots_arg_size + jj],\n                               galois::MethodFlag::WRITE);\n    }\n\n    void operator()(const Task& t, galois::UserContext<Task>&) {\n      int ii, jj, kk = t.kk;\n      switch (t.type) {\n      case LU0:\n        acquire(kk, kk);\n        for (jj = kk + 1; jj < bots_arg_size; jj++) {\n          if (BENCH[kk * bots_arg_size + jj] != NULL) {\n            acquire(kk, jj);\n          }\n        }\n        for (ii = kk + 1; ii < bots_arg_size; ii++) {\n          if (BENCH[ii * bots_arg_size + kk] != NULL) {\n            acquire(ii, kk);\n          }\n        }\n        for (ii = kk + 1; ii < bots_arg_size; ii++) {\n          if (BENCH[ii * bots_arg_size + kk] != NULL) {\n            acquire(ii, kk);\n            for (jj = kk + 1; jj < bots_arg_size; jj++) {\n              if (BENCH[kk * bots_arg_size + jj] != NULL) {\n                acquire(kk, jj);\n                acquire(ii, jj);\n              }\n            }\n          }\n        }\n        return;\n      case FWD:\n        acquire(kk, t.arg0);\n        for (ii = kk + 1; ii < bots_arg_size; ii++) {\n          if (BENCH[ii * bots_arg_size + kk] != NULL) {\n            acquire(ii, t.arg0);\n          }\n        }\n        return;\n      case BDIV:\n        acquire(t.arg0, kk);\n        for (jj = kk + 1; jj < bots_arg_size; jj++) {\n          if (BENCH[kk * bots_arg_size + jj] != NULL) {\n            acquire(t.arg0, jj);\n          }\n        }\n        return;\n      case BMOD:\n        acquire(t.arg0, t.arg1);\n        return;\n      }\n    }\n  };\n\n  struct Process {\n    static const int CHUNK_SIZE = 1;\n\n    typedef int tt_does_not_need_aborts;\n\n    float** BENCH;\n\n    void operator()(const Task& t, galois::UserContext<Task>& ctx) {\n      int ii, jj, kk = t.kk;\n\n      switch (t.type) {\n      case LU0:\n        lu0(BENCH[kk * bots_arg_size + kk]);\n        for (ii = kk + 1; ii < bots_arg_size; ii++) {\n          if (BENCH[ii * bots_arg_size + kk] != NULL) {\n            ctx.push(Task{BDIV, kk, ii, 0});\n          }\n        }\n        for (jj = kk + 1; jj < bots_arg_size; jj++) {\n          if (BENCH[kk * bots_arg_size + jj] != NULL) {\n            ctx.push(Task{FWD, kk, jj, 0});\n          }\n        }\n        for (ii = kk + 1; ii < bots_arg_size; ii++) {\n          if (BENCH[ii * bots_arg_size + kk] != NULL) {\n            for (jj = kk + 1; jj < bots_arg_size; jj++) {\n              if (BENCH[kk * bots_arg_size + jj] != NULL) {\n                if (BENCH[ii * bots_arg_size + jj] == NULL)\n                  BENCH[ii * bots_arg_size + jj] = allocate_clean_block();\n                ctx.push(Task{BMOD, kk, ii, jj});\n              }\n            }\n          }\n        }\n        return;\n      case FWD:\n        return fwd(BENCH[kk * bots_arg_size + kk],\n                   BENCH[kk * bots_arg_size + t.arg0]);\n      case BDIV:\n        return bdiv(BENCH[kk * bots_arg_size + kk],\n                    BENCH[t.arg0 * bots_arg_size + kk]);\n      case BMOD:\n        return bmod(BENCH[t.arg0 * bots_arg_size + kk],\n                    BENCH[kk * bots_arg_size + t.arg1],\n                    BENCH[t.arg0 * bots_arg_size + t.arg1]);\n      }\n    }\n  };\n};\n\nstatic void bs_algo(float** BENCH) {\n  int ii, jj, kk;\n\n  namespace ww = galois::worklists;\n  typedef ww::StableIterator<>::with_container<ww::PerSocketChunkLIFO<1>>::type\n      WL;\n\n  for (kk = 0; kk < bots_arg_size; kk++) {\n    lu0(BENCH[kk * bots_arg_size + kk]);\n\n    galois::for_each(\n        boost::transform_iterator<FwdBdiv::Initializer,\n                                  boost::counting_iterator<int>>(kk + 1),\n        boost::transform_iterator<FwdBdiv::Initializer,\n                                  boost::counting_iterator<int>>(bots_arg_size),\n        FwdBdiv{BENCH, kk}, galois::wl<WL>());\n\n    galois::for_each(\n        boost::transform_iterator<Bmod::Initializer,\n                                  boost::counting_iterator<int>>(kk + 1),\n        boost::transform_iterator<Bmod::Initializer,\n                                  boost::counting_iterator<int>>(bots_arg_size),\n        Bmod{BENCH, kk}, galois::wl<WL>());\n  }\n}\n\nstatic void ikdg_algo(float** BENCH) {\n  int kk;\n  typedef boost::transform_iterator<FwdBdivBmod::Initializer,\n                                    boost::counting_iterator<int>>\n      TI;\n\n  galois::setDoAllImpl(galois::DOALL_COUPLED);\n  if (galois::getDoAllImpl() != galois::DOALL_COUPLED) {\n    std::abort();\n  }\n\n  galois::runtime::for_each_ordered_ikdg(\n      galois::runtime::makeStandardRange(TI(0), TI(bots_arg_size)),\n      FwdBdivBmod::Comparator{}, FwdBdivBmod::NeighborhoodVisitor{BENCH},\n      FwdBdivBmod::Process{BENCH},\n      std::make_tuple(galois::loopname(\"sparselu-ikdg\")));\n}\n\nvoid sparselu_par_call(float** BENCH) {\n  galois::StatManager manager;\n  galois::StatTimer T;\n\n  T.start();\n  bots_message(\n      \"Computing SparseLU Factorization (%dx%d matrix with %dx%d blocks) \",\n      bots_arg_size, bots_arg_size, bots_arg_size_1, bots_arg_size_1);\n  if (bots_app_cutoff_value_1 == 0)\n    bs_algo(BENCH);\n  else\n    ikdg_algo(BENCH);\n  bots_message(\" completed!\\n\");\n  galois::reportPageAlloc(\"MeminfoPost\");\n  T.stop();\n}\n\nvoid sparselu_fini(float** BENCH, char* pass) {\n  galois::substrate::getThreadPool().beKind();\n  print_structure(pass, BENCH);\n  locks.destroy();\n  locks.deallocate();\n}\n\nint sparselu_check(float** SEQ, float** BENCH) {\n  int ii, jj, ok = 1;\n\n  for (ii = 0; ((ii < bots_arg_size) && ok); ii++) {\n    for (jj = 0; ((jj < bots_arg_size) && ok); jj++) {\n      if (SEQ[ii * bots_arg_size + jj] == NULL &&\n          BENCH[ii * bots_arg_size + jj] != NULL)\n        ok = FALSE;\n      if (SEQ[ii * bots_arg_size + jj] != NULL &&\n          BENCH[ii * bots_arg_size + jj] == NULL)\n        ok = FALSE;\n      if (SEQ[ii * bots_arg_size + jj] != NULL &&\n          BENCH[ii * bots_arg_size + jj] != NULL)\n        ok = checkmat(SEQ[ii * bots_arg_size + jj],\n                      BENCH[ii * bots_arg_size + jj]);\n    }\n  }\n  if (ok)\n    return BOTS_RESULT_SUCCESSFUL;\n  else\n    return BOTS_RESULT_UNSUCCESSFUL;\n}\n", "meta": {"hexsha": "10816605b78be7ea8b5ecb85ae3233b4781266d1", "size": 22689, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lonestar/experimental/ordered/sparselu/gsparselu_for/sparselu.cpp", "max_stars_repo_name": "lineagech/Galois", "max_stars_repo_head_hexsha": "5c7c0abaf7253cb354e35a3836147a960a37ad5b", "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": "lonestar/experimental/ordered/sparselu/gsparselu_for/sparselu.cpp", "max_issues_repo_name": "lineagech/Galois", "max_issues_repo_head_hexsha": "5c7c0abaf7253cb354e35a3836147a960a37ad5b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lonestar/experimental/ordered/sparselu/gsparselu_for/sparselu.cpp", "max_forks_repo_name": "lineagech/Galois", "max_forks_repo_head_hexsha": "5c7c0abaf7253cb354e35a3836147a960a37ad5b", "max_forks_repo_licenses": ["BSD-3-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.3666191155, "max_line_length": 96, "alphanum_fraction": 0.5243069329, "num_tokens": 6372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.28211478544317137}}
{"text": "// Enable C++11 via this plugin (Rcpp 0.10.3 or later)\n// [[Rcpp::plugins(cpp11)]]\n\n// [[Rcpp::depends(BH)]]\n\n#include <Rcpp.h>\nusing namespace Rcpp;\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n\n#include <random>\n#include <cmath>\n#include <iostream>\n#include <algorithm>\n#include <functional>\n#include <iterator>\n#include <string>\n#include <unordered_map>\n#include <boost/functional/hash.hpp>\n\ntypedef std::vector<int> sequence;\n\nsequence subseq(const sequence &x, unsigned int first, unsigned int last) {\n  if (last >= x.size() || last < first) {\n    stop(\"invalid subsequence indices\");\n  }\n  int n = 1 + last - first;\n  sequence res(n);\n  for (int j = 0; j < n; j ++) {\n    res[j] = x[j + first];\n  }\n  return(res);\n}\n\nsequence last_n (const sequence &x, int n) {\n  if (n < 0) {\n    stop(\"n cannot be less than 0\");\n  }\n  int original_length = static_cast<int>(x.size());\n  if (n > original_length) {\n    stop(\"cannot excise more elements than the sequence contains\");\n  }\n  if (n == 0) {\n    sequence res(0);\n    return res;\n  } else {\n    sequence res(n);\n    for (int i = 0; i < n; i ++) {\n      res[i] = x[i + original_length - n];\n    }\n    return res;\n  }\n}\n\nvoid print(const sequence &x) {\n  for (unsigned int j = 0; j < x.size(); j ++) {\n    if (j > 0) {\n      Rcout << \" \";\n    }\n    Rcout << x[j];\n  }\n  Rcout << \"\\n\";\n}\n\nvoid print(const std::vector<double> &x) {\n  for (unsigned int j = 0; j < x.size(); j ++) {\n    if (j > 0) {\n      Rcout << \" \";\n    }\n    Rcout << x[j];\n  }\n  Rcout << \"\\n\";\n}\n\nvoid print(const std::vector<bool> &x) {\n  for (unsigned int j = 0; j < x.size(); j ++) {\n    if (j > 0) {\n      Rcout << \" \";\n    }\n    if (x[j]) {\n      Rcout << \"True\";\n    } else {\n      Rcout << \"False\";\n    }\n  }\n  Rcout << \"\\n\";\n}\n\nRObject list_to_tibble(List x) {\n  Environment pkg = Environment::namespace_env(\"tibble\");\n  Function f = pkg[\"as_tibble\"];\n  return(f(x));\n}\n\nNumericVector as_numeric_vector(std::vector<double> x) {\n  int size = x.size();\n  NumericVector res = NumericVector(size);\n  for (int i = 0; i < size; i ++) {\n    res[i] = x[i];\n  }\n  return res;\n}\n\ntemplate <typename Container> // we can make this generic for any container [1]\nstruct container_hash {\n  std::size_t operator() (Container const& c) const {\n    return boost::hash_range(c.begin(), c.end());\n  }\n};\n\nclass record {\n  \n};\n\nclass record_simple: public record {\npublic: \n  long int full_count = 0;\n  long int up_ex_count = 0;\n  \n  record_simple() {};\n  \n  void add_1(bool full_only) {\n    if (full_count >= LONG_MAX || up_ex_count >= LONG_MAX) {\n      stop(\"cannot increment this record count any higher\");\n    }\n    full_count ++;\n    if (!full_only) {\n      up_ex_count ++;\n    }\n  }\n};\n\ndouble compute_entropy(std::vector<double> x) {\n  int n = x.size();\n  double counter = 0;\n  for (int i = 0; i < n; i ++) {\n    double p = x[i];\n    counter -= p * log2(p);\n  }\n  return counter;\n}\n\nstd::vector<double> normalise_distribution(std::vector<double> &x) {\n  double total = 0;\n  int n = static_cast<int>(x.size());\n  for (int i = 0; i < n; i ++) {\n    total += x[i];\n  }\n  for (int i = 0; i < n; i ++) {\n    x[i] = x[i] / total;\n  }\n  return x;\n}\n\nclass record_decay: public record {\npublic:\n  record_decay() {}\n  std::vector<int> pos;\n  // std::vector<double> time;\n  void insert(int pos_, double time_) {\n    pos.push_back(pos_);\n    // time.push_back(time_);\n  }\n};\n\nclass symbol_prediction {\npublic:\n  int symbol;\n  int pos;\n  double time;\n  int model_order;\n  std::vector<double> distribution;\n  double information_content;\n  \n  symbol_prediction(int symbol_, \n                    int pos_, \n                    double time_, \n                    int model_order_,\n                    const std::vector<double> &distribution_) {\n    int dist_size_ = distribution_.size();\n    if (symbol_ > dist_size_) {\n      Rcout << \"symbol = \" << symbol_ << \", distribution(n) = \" << distribution_.size() << \"\\n\";\n      stop(\"observed symbol not compatible with distribution dimensions\");\n    }\n    \n    symbol = symbol_;\n    pos = pos_;\n    time = time_;\n    model_order = model_order_;\n    distribution = distribution_;\n    information_content = - log2(distribution[symbol]);\n  }\n};\n\nclass sequence_prediction {\npublic: \n  bool return_distribution;\n  bool return_entropy;\n  bool decay;\n  \n  std::vector<int> symbol;\n  std::vector<int> pos;\n  std::vector<double> time;\n  std::vector<int> model_order;\n  std::vector<double> information_content;\n  std::vector<double> entropy;\n  std::vector<std::vector<double>> distribution;\n  \n  sequence_prediction(bool return_distribution_,\n                      bool return_entropy_,\n                      bool decay_) {\n    return_distribution = return_distribution_;\n    return_entropy = return_entropy_;\n    decay = decay_;\n  }\n  \n  void insert(const symbol_prediction &x) {\n    symbol.push_back(x.symbol);\n    model_order.push_back(x.model_order);\n    information_content.push_back(x.information_content);\n    if (return_entropy) {\n      entropy.push_back(compute_entropy(x.distribution));\n    }\n    if (return_distribution) {\n      distribution.push_back(x.distribution);\n    }\n    if (decay) {\n      pos.push_back(x.pos);\n      time.push_back(x.time);\n    }\n  }\n  \n  List as_list() {\n    List x = List::create(Named(\"symbol\") = symbol);\n    if (decay) {\n      x.push_back(pos, \"pos\");\n      x.push_back(time, \"time\");\n    }\n    x.push_back(model_order, \"model_order\");\n    x.push_back(information_content, \"information_content\");\n    if (return_entropy) {\n      x.push_back(entropy, \"entropy\");\n    }\n    if (return_distribution) {\n      x.push_back(distribution, \"distribution\");\n    }\n    return(x);\n  }\n  \n  RObject as_tibble() {\n    return(list_to_tibble(this->as_list()));\n  }\n};\n\nclass model_order {\npublic:\n  int chosen;\n  int longest_available;\n  bool deterministic_any;\n  int deterministic_shortest;\n  bool deterministic_is_selected;\n  \n  model_order(int chosen_,\n              int longest_available_,\n              bool deterministic_any_,\n              int deterministic_shortest_, \n              bool deterministic_is_selected_) {\n    chosen = chosen_;\n    longest_available = longest_available_;\n    deterministic_any = deterministic_any_;\n    deterministic_shortest = deterministic_shortest_;\n    deterministic_is_selected = deterministic_is_selected_;\n  }\n};\n\nclass ppm {\npublic:\n  int alphabet_size;\n  int order_bound;\n  bool shortest_deterministic;\n  bool exclusion;\n  bool update_exclusion;\n  std::string escape;\n  double k;\n  bool decay;\n  bool sub_n_from_m1_dist;\n  bool lambda_uses_zero_weight_symbols;\n  bool debug_smooth;\n  CharacterVector alphabet_levels;\n  \n  int num_observations = 0;\n  std::vector<double> all_time;\n  \n  ppm(int alphabet_size_,\n      int order_bound_,\n      bool shortest_deterministic_,\n      bool exclusion_,\n      bool update_exclusion_,\n      std::string escape_,\n      bool decay_,\n      bool sub_n_from_m1_dist_,\n      bool lambda_uses_zero_weight_symbols_,\n      CharacterVector alphabet_levels_\n  ) {\n    if (alphabet_size_ <= 0) {\n      stop(\"alphabet size must be greater than 0\");\n    }\n    \n    alphabet_size = alphabet_size_;\n    order_bound = order_bound_;\n    shortest_deterministic = shortest_deterministic_;\n    exclusion = exclusion_;\n    update_exclusion = update_exclusion_;\n    escape = escape_;\n    k = this->get_k(escape);\n    decay = decay_;\n    sub_n_from_m1_dist = sub_n_from_m1_dist_;\n    lambda_uses_zero_weight_symbols = lambda_uses_zero_weight_symbols_;\n    alphabet_levels = alphabet_levels_;\n  }\n  \n  virtual ~ ppm() {};\n  \n  // returns true if the n_gram already existed in the memory bank\n  virtual bool insert(sequence x, int pos, double time, bool full_only) {\n    stop(\"this shouldn't happen (1)\");\n    return true;\n  };\n  \n  virtual double get_weight(const sequence &n_gram, \n                            int pos, \n                            double time, \n                            bool update_excluded) {\n    return 0.0;\n  };\n  \n  double get_num_observed_symbols(int pos, double time) {\n    int res = 0;\n    for (int i = 0; i < this->alphabet_size; i ++) {\n      sequence symbol(1, i);\n      double weight = get_weight(symbol, pos, time, false);\n      if (weight > 0.0) res ++;\n    }\n    return res;\n  }\n  \n  double get_context_count(const std::vector<double> &counts, \n                           const std::vector<bool> &excluded) {\n    double context_count = 0;\n    for (int i = 0; i < this->alphabet_size; i ++) {\n      if (!excluded[i]) {\n        context_count += counts[i];\n      }\n    }\n    return context_count; \n  }\n  \n  sequence_prediction model_seq(sequence x,\n                                NumericVector time = NumericVector(0),\n                                bool train = true,\n                                bool predict = true,\n                                bool return_distribution = true,\n                                bool return_entropy = true,\n                                bool generate = false) {\n    int n = x.size();\n    if (this->decay && \n        (static_cast<unsigned int>(x.size()) != \n        static_cast<unsigned int>(time.size()))) {\n      stop(\"time must either have length 0 or have length equal to x\");\n    }\n    if (this->all_time.size() > 0 && time.size() > 0 && time[0] < this->all_time.back()) {\n      stop(\"a sequence may not begin before the previous sequence finished\");\n    }\n    \n    sequence_prediction result(return_distribution,\n                               return_entropy,\n                               this->decay);\n    \n    for (int i = 0; i < n; i ++) {\n      int pos_i = num_observations;\n      double time_i = this->decay? time[i] : 0;\n      // Predict\n      if (predict) {\n        sequence context = (i < 1 || order_bound < 1) ? sequence() :\n        subseq(x,\n               std::max(0, i - order_bound),\n               i - 1);\n        symbol_prediction pred = predict_symbol(x[i], context, pos_i, time_i, generate);\n        result.insert(pred);\n        if (generate) {\n          x[i] = pred.symbol;\n        }\n      }\n      // Train\n      if (train) {\n        if (decay) this->all_time.push_back(time_i);\n        bool full_only = false;\n        for (int h = std::max(0, i - order_bound); h <= i; h ++) {\n          full_only = this->insert(subseq(x, h, i), pos_i, time_i, full_only);\n        }\n        num_observations ++;\n      }\n    }\n    return(result);\n  }\n  \n  symbol_prediction predict_symbol(\n      int symbol, \n      const sequence &context,\n      int pos, \n      double time,\n      bool generate\n    ) {\n    if (!generate) { \n      if (symbol < 0) {\n        stop(\"symbols must be greater than or equal to 0\");\n      }\n      if (symbol > alphabet_size - 1) {\n        stop(\"symbols cannot exceed (alphabet_size - 1)\");\n      }\n    }\n    \n    model_order model_order = this->get_model_order(context, pos, time);\n    std::vector<double> dist = get_probability_distribution(context,\n                                                            model_order,\n                                                            pos,\n                                                            time);\n    \n    if (generate) {\n      int n_samples = 1;\n      bool replace = false;\n      NumericVector probs = as_numeric_vector(dist);\n      bool one_indexed = false;\n      symbol = Rcpp::sample(alphabet_size, n_samples, replace, probs, one_indexed)[0];\n    }\n  \n    symbol_prediction out(symbol, pos, time, model_order.chosen, dist);\n    return(out);\n  } \n  \n  std::vector<double> get_probability_distribution(const sequence &context,\n                                                   model_order model_order,\n                                                   int pos, \n                                                   double time) {\n    std::vector<bool> excluded(alphabet_size, false);\n    std::vector<double> dist = get_smoothed_distribution(\n      context,\n      model_order,\n      model_order.chosen,\n      pos,\n      time,\n      excluded\n    );\n    return normalise_distribution(dist);\n  }\n  \n  std::vector<double> get_smoothed_distribution(const sequence &context,\n                                                model_order model_order, \n                                                int order,\n                                                int pos, \n                                                double time,\n                                                std::vector<bool> &excluded) {\n    if (order == -1) {\n      return get_order_minus_1_distribution(pos, time);\n    } else {\n      bool update_excluded = this->update_exclusion;\n      if (order == model_order.chosen &&\n          this->shortest_deterministic &&\n          this->update_exclusion &&\n          model_order.deterministic_is_selected) {\n        update_excluded = false;\n      }\n      \n      std::vector<int> n_gram = last_n(context, order);\n      n_gram.resize(order + 1);\n      \n      std::vector<double> counts(this->alphabet_size);\n      int num_distinct_symbols = 0;\n      std::vector<bool> predicted(this->alphabet_size);\n      \n      for (int i = 0; i < this->alphabet_size; i ++) {\n        n_gram[order] = i;\n        counts[i] = this->get_weight(n_gram, pos, time, update_excluded);\n        if (counts[i] > 0.0) {\n          predicted[i] = true;\n          num_distinct_symbols += 1;\n        } else {\n          predicted[i] = false;\n        }\n        counts[i] = this->modify_count(counts[i]);\n      }\n      \n      // Rcout << \"counts: \";\n      // print(counts);\n      \n      double context_count = get_context_count(counts, excluded);\n      double lambda = get_lambda(counts, context_count, num_distinct_symbols);\n      \n      std::vector<double> alphas = get_alphas(lambda, counts, context_count);\n      \n      if (this->debug_smooth) {\n        Rcout << \"\\n*** order = \" << order << \" ***\\n\";\n        Rcout << \"pos = \" << pos << \"\\n\";\n        Rcout << \"time = \" << time << \"\\n\";\n        Rcout << \"model_order.chosen = \" << model_order.chosen << \"\\n\";\n        // Rcout << \"this->shortest_deterministic = \" << this->shortest_deterministic << \"\\n\";\n        // Rcout << \"this->update_exclusion = \" << this->update_exclusion << \"\\n\";\n        // Rcout << \"model_order.deterministic_is_selected = \" << model_order.deterministic_is_selected << \"\\n\";\n        Rcout << \"context = \";\n        print(last_n(context, order));\n        // Rcout << \"update_excluded = \" << update_excluded << \"\\n\";\n        Rcout << \"counts = \";\n        print(counts);\n        Rcout << \"context_count = \" << context_count << \"\\n\";\n        Rcout << \"lambda = \" << lambda << \"\\n\";\n        Rcout << \"alphas = \";\n        print(alphas);\n      }\n      \n      if (this->exclusion) {\n        for (int i = 0; i < alphabet_size; i ++) {\n          // There is a choice here:\n          // do we exclude symbols that have alphas greater than 0\n          // (i.e. their counts survive addition of k),\n          // or do we exclude any symbol that is present in the tree at all,\n          // even if adding k takes it down to 0?\n          //\n          // Since decay-based models don't have exclusion,\n          // we only have to think about normal PPM models.\n          // All of these models apart from PPM-B have k > -1,\n          // in which case there is no difference between the strategies.\n          // We only have to worry for PPM-B.\n          //\n          // Following Bunton (1996) and Pearce (2005)'s implementation,\n          // we adopt the latter strategy, excluding symbols even \n          // if their alphas are equal to 0, as long as they were present\n          // in the tree.\n          \n          if (predicted[i]) {\n            excluded[i] = true;\n          }\n        }\n        if (this->debug_smooth) {\n          Rcout << \"new excluded = \";\n          print(excluded);\n        }\n      }\n      \n      std::vector<double> lower_order_distribution = get_smoothed_distribution(\n        context, model_order, order - 1, pos, time, excluded);\n      \n      std::vector<double> res(this->alphabet_size);\n      for (int i = 0; i < this->alphabet_size; i ++) {\n        res[i] = alphas[i] + (1 - lambda) * lower_order_distribution[i];\n      }\n      \n      if (this->debug_smooth) {\n        Rcout << \"order \" << order << \" \";\n        Rcout << \"probability distribution = \";\n        print(res);\n      }\n      \n      return res;\n    }\n  }\n  \n  std::vector<double>get_alphas(double lambda, \n                                const std::vector<double> &counts, \n                                double context_count) {\n    if (lambda > 0) {\n      std::vector<double> res(this->alphabet_size);\n      for (int i = 0; i < this->alphabet_size; i ++) {\n        res[i] = lambda * counts[i] / context_count;\n      }\n      return res;\n    } else {\n      std::vector<double> res(this->alphabet_size, 0);\n      return res;\n    }\n  }\n  \n  // The need to capture situations where the context_count is 0 is\n  // introduced by Pearce (2005)'s decision to introduce exclusion\n  // (see 6.2.3.3), though the thesis does not mention\n  // this explicitly.\n  virtual double get_lambda(const std::vector<double> &counts, double context_count, int num_distinct_symbols) {\n    stop(\"this virtual get_lambda method should never be called directly\");\n    return 0.0;\n  }\n  \n  double get_k(const std::string &e) {\n    if (e == \"a\") {\n      return 0;\n    } else if (e == \"b\") {\n      return - 1;\n    } else if (e == \"c\") {\n      return 0;\n    } else if (e == \"d\") {\n      return - 0.5;\n    } else if (e == \"ax\") {\n      return 0;\n    } else {\n      stop(\"unrecognised escape method\");\n    }\n  }\n  \n  double get_effective_distinct_symbols(int num_distinct_symbols, \n                                        const std::vector<double> &counts) {\n    if (this->lambda_uses_zero_weight_symbols) {\n      return num_distinct_symbols;\n    } else {\n      return this->count_positive_values(counts);\n    }\n  }\n  \n  double lambda_a(const std::vector<double> &counts, double context_count, int num_distinct_symbols) {\n    if (this->debug_smooth) {\n      Rcout << \"lambda_a, context_count = \" << context_count << \"\\n\";\n    }\n    return context_count / (context_count + 1.0);\n  }\n  \n  double lambda_b(const std::vector<double> &counts, double context_count, int num_distinct_symbols) {\n    double effective_distinct_symbols = \n      this->get_effective_distinct_symbols(num_distinct_symbols,\n                                           counts);\n    \n    return static_cast<double>(context_count) /\n      static_cast<double>(context_count + effective_distinct_symbols);\n  }\n  \n  double lambda_c(const std::vector<double> &counts, double context_count, int num_distinct_symbols) {\n    double effective_distinct_symbols = \n      this->get_effective_distinct_symbols(num_distinct_symbols,\n                                           counts);\n    \n    return static_cast<double>(context_count) /\n      static_cast<double>(context_count + effective_distinct_symbols);\n  }\n  \n  double lambda_d(const std::vector<double> &counts, double context_count, int num_distinct_symbols) {\n    double effective_distinct_symbols = \n      this->get_effective_distinct_symbols(num_distinct_symbols,\n                                           counts);\n    \n    return static_cast<double>(context_count) /\n      (static_cast<double>(context_count + effective_distinct_symbols / 2.0));\n  }\n  \n  double lambda_ax(const std::vector<double> &counts, double context_count, int num_distinct_symbols) {\n    // Note - there is a mistake in the reference papers, \n    // Pearce & Wiggins (2004), also Pearce (2005);\n    // the 1.0 is missing from the equation.\n    // Our version is consistent with the context literature though,\n    // and consistent with Pearce's LISP implementation.\n    //\n    // We generalise the definition of singletons to decayed counts between\n    // 0 and 1. This is a bit hacky though, and the escape method\n    // should ultimately be reconfigured for new decay functions.\n    return static_cast<double>(context_count) /\n      static_cast<double>(context_count + num_singletons(counts) + 1.0);\n  }\n  \n  int num_singletons(const std::vector<double> &x) {\n    int n = static_cast<int>(x.size());\n    int res = 0;\n    for (int i = 0; i < n; i ++) {\n      if (x[i] > 0 && x[i] <= 1) {\n        res ++;\n      }\n    }\n    return res;\n  }\n  \n  double modify_count(double count) {\n    if (this->k == 0 || count == 0) {\n      return count;\n    } else {\n      double x = count + this->k;\n      if (x > 0) {\n        return x;\n      } else {\n        return 0;\n      }\n    }\n  }\n  \n  int count_positive_values(const std::vector<double> &x) {\n    int n = static_cast<int>(x.size());\n    int res = 0;\n    for (int i = 0; i < n; i ++) {\n      if (x[i] > 0) {\n        res ++;\n      }\n    }\n    return res;\n  }\n  \n  std::vector<double> get_order_minus_1_distribution(int pos, double time) {\n    \n    // See Bunton (1996, p. 82): alpha(s0) comes from the 3-arg version of count(),\n    // which does not include exclusion or subtraction \n    // of the k parameter (see escape method).\n    // It instead corresponds to the number of symbols that the model \n    // has ever seen.\n    \n    //// Old version:\n    // int num_observed_symbols = 0;\n    // for (int i = 0; i < this->alphabet_size; i ++) {\n    //   if (excluded[i]) {\n    //     num_observed_symbols ++;\n    //   } \n    // }\n    \n    double denominator = this->alphabet_size + 1;\n    \n    if (this->sub_n_from_m1_dist) {\n      // This is disabled for decay-based models\n      double num_observed_symbols = this->get_num_observed_symbols(pos, time);\n      denominator -= num_observed_symbols;\n    }\n    \n    double p = 1.0 / denominator;\n    std::vector<double> res(this->alphabet_size, p);\n    \n    if (this->debug_smooth) {\n      Rcout << \"order minus 1 distribution = \";\n      print(res);\n      Rcout << \"\\n\";\n    }\n    return res;\n  }\n  \n  model_order get_model_order(const sequence &context, int pos, double time) {\n    const int longest_available = this->get_longest_context(context, pos, time);\n    int chosen = longest_available;\n    \n    int det_shortest = - 1;\n    int det_any = false;\n    int det_is_selected = false;\n    \n    if (shortest_deterministic) {\n      int det_shortest = this->get_shortest_deterministic_context(context,\n                                                                  pos,\n                                                                  time);\n      bool det_any = det_shortest >= 0;\n      if (det_any) {\n        if (det_shortest < longest_available) {\n          det_is_selected = true;\n          chosen = det_shortest;\n        }\n      }\n    }\n    \n    return(model_order(chosen, longest_available,\n                       det_any, det_shortest, det_is_selected));\n  }\n  \n  virtual int get_longest_context(sequence context, int pos, double time) {\n    stop(\"this shouldn't happen (2)\");\n    return 0;\n  }\n  \n  int get_shortest_deterministic_context(const sequence &context, int pos, double time) {\n    int len = static_cast<int>(context.size());\n    int res = -1;\n    for (int order = 0; order <= std::min(len, order_bound); order ++) {\n      sequence effective_context = order == 0 ? sequence() : subseq(context, \n                                                         len - order, len - 1);\n      if (is_deterministic_context(effective_context, pos, time)) {\n        res = order;\n        break;\n      }\n    }\n    return(res);\n  }\n  \n  bool is_deterministic_context(const sequence &context, int pos, double time) {\n    int num_continuations = 0;\n    for (int i = 0; i < alphabet_size; i ++) {\n      sequence n_gram = context;\n      n_gram.push_back(i);\n      double weight = this->get_weight(n_gram, \n                                       pos, \n                                       time, \n                                       false); // update exclusion\n      if (weight > 0) {\n        num_continuations ++;\n        if (num_continuations > 1) {\n          break;\n        }\n      }\n    }\n    return num_continuations == 1;\n  }\n};\n\nclass ppm_simple: public ppm {\npublic:\n  std::unordered_map<sequence, \n                     record_simple,\n                     container_hash<sequence>> data;\n  \n  ppm_simple(\n    int alphabet_size_,\n    int order_bound_,\n    bool shortest_deterministic_,\n    bool exclusion_,\n    bool update_exclusion_,\n    std::string escape_,\n    CharacterVector alphabet_levels_\n  ) : ppm(\n      alphabet_size_,\n      order_bound_, \n      shortest_deterministic_, \n      exclusion_, \n      update_exclusion_, \n      escape_,\n      false, // decay\n      true, // sub_n_from_m1_dist\n      true, // lambda_uses_zero_weight_symbols\n      alphabet_levels_\n      ) { \n    data = {};\n  }\n  \n  ~ ppm_simple() {};\n  \n  bool insert(sequence x, int pos, double time, bool full_only) {\n    std::unordered_map<sequence, record_simple, container_hash<sequence>>::const_iterator target = data.find(x);\n    if (target == data.end()) {\n      record_simple record;\n      record.add_1(full_only);\n      data[x] = record;\n      return false;\n    } else {\n      data[x].add_1(full_only);\n      return true;\n    }\n  }\n  \n  int get_longest_context(sequence context, int pos, double time) {\n    // Rcout << \"get_longest_context...\\n\";\n    int context_len = static_cast<int>(context.size());\n    int upper_bound = std::min(order_bound, context_len);\n    \n    for (int order = upper_bound; order >= 0; order --) {\n      // Rcout << \"Checking order = \" << order << \"\\n\";\n      sequence x = order == 0 ? sequence() : subseq(context,\n                                         context_len - order,\n                                         context_len - 1);\n      // Rcout << \"Truncated context = \";\n      // print(x);\n      // Skip this iteration if the context doesn't exist in the tree\n      if (order > 0 && // we don't store 0-grams in the tree\n          this->get_weight(x, \n                           0, // pos - irrelevant for non-decay-based models\n                           0, // time - irrelevant for non-decay-based models\n                           false) // update exclusion\n            == 0.0) {\n        // Rcout << \"Couldn't find context in the tree\\n\";\n        continue;\n      }\n      // Skip this iteration if we can't find a continuation for that context\n      bool any_continuation = false;\n      x.resize(order + 1);\n      for (int i = 0; i < this->alphabet_size; i ++) {\n        x[order] = i;\n        if (this->get_weight(x, 0, 0, false) > 0.0) {\n          any_continuation = true;\n          break;\n        }\n      }\n      if (! any_continuation) {\n        // Rcout << \"Couldn't find any continuations for this context\\n\";\n        continue;\n      }\n      // Rcout << \"Couldn't find a problem with this context\\n\";\n      return(order);\n    }\n    // Rcout << \"Escaped to order = -1\\n\";\n    return(- 1);\n  }\n  \n  \n  double get_weight(const sequence &n_gram, \n                    int pos, \n                    double time,\n                    bool update_excluded) {\n    return static_cast<double>(this->get_count(n_gram, update_excluded));\n  };\n  \n  long int get_count(const sequence &x, bool update_excluded) {\n    std::unordered_map<sequence, record_simple, container_hash<sequence>>::const_iterator target = data.find(x);\n    if (target == data.end()) {\n      return(0);\n    } else if (update_excluded) {\n      return target->second.up_ex_count;\n    } else {\n      return target->second.full_count;\n    }\n  }\n  \n  // The need to capture situations where the context_count is 0 is\n  // introduced by Pearce (2005)'s decision to introduce exclusion\n  // (see 6.2.3.3), though the thesis does not mention\n  // this explicitly.\n  double get_lambda(const std::vector<double> &counts, double context_count, int num_distinct_symbols) {\n    if (this->debug_smooth) {\n      Rcout << \"calling ppm_simple.get_lambda()\\n\";\n    }\n    std::string e = this->escape;\n    if (context_count <= 0.0) {\n      return 0.0;\n    } else if (e == \"a\") {\n      return this->lambda_a(counts, context_count, num_distinct_symbols);\n    } else if (e == \"b\") {\n      return this->lambda_b(counts, context_count, num_distinct_symbols);\n    } else if (e == \"c\") {\n      return this->lambda_c(counts, context_count, num_distinct_symbols);\n    } else if (e == \"d\") {\n      return this->lambda_d(counts, context_count, num_distinct_symbols);\n    } else if (e == \"ax\") {\n      return this->lambda_ax(counts, context_count, num_distinct_symbols);\n    } else {\n      stop(\"unrecognised escape method\");\n    }\n  }\n  \n  List as_list() {\n    int n = data.size();\n    List n_gram(n);\n    NumericVector full_count(n); // NumericVector deals better with v long ints\n    NumericVector up_ex_count(n);\n    \n    int i = 0;\n    for(auto kv : data) {\n      n_gram[i] = kv.first;\n      full_count[i] = kv.second.full_count;\n      up_ex_count[i] = kv.second.up_ex_count;\n      i ++;\n    } \n    \n    List x = List::create(Named(\"n_gram\") = n_gram,\n                          Named(\"full_count\") = full_count,\n                          Named(\"up_ex_count\") = up_ex_count);\n    return(x);\n  }\n  \n  RObject as_tibble() {\n    return(list_to_tibble(this->as_list()));\n  }\n  \n};\n\nclass ppm_decay: public ppm {\npublic:\n  std::unordered_map<sequence, record_decay, container_hash<sequence>> data;\n  \n  double buffer_length_time;\n  int buffer_length_items;\n  double buffer_weight;\n  bool only_learn_from_buffer;\n  bool only_predict_from_buffer;\n  double stm_weight;\n  double stm_duration;\n  double stm_half_life; // computed from stm_weight, ltm_weight, and stm_duration\n  double ltm_weight;\n  double ltm_half_life;\n  double ltm_asymptote;\n  double noise;\n  double noise_mean;\n  bool disable_noise;\n  int seed;\n  bool debug_decay;\n  \n  std::mt19937 random_engine;\n  std::normal_distribution<> noise_generator;\n  // std::bernoulli_distribution noise_generator;\n  // std::uniform_int_distribution<> alphabet_sampler;\n  \n  ppm_decay(\n    int alphabet_size_,\n    int order_bound_,\n    List decay_par,\n    int seed,\n    CharacterVector alphabet_levels_\n  ) : ppm (\n      alphabet_size_,\n      order_bound_,\n      false, // shortest_deterministic\n      false, // exclusion\n      false, // update_exclusion\n      \"a\", // escape,\n      true, // decay\n      false, // sub_n_from_m1_dist\n      false, // lambda_uses_zero_weight_symbols\n      alphabet_levels_\n  ) {\n    data = {};\n    buffer_length_time = decay_par[\"buffer_length_time\"];\n    buffer_length_items = decay_par[\"buffer_length_items\"];\n    buffer_weight = decay_par[\"buffer_weight\"];\n    only_learn_from_buffer = decay_par[\"only_learn_from_buffer\"];\n    only_predict_from_buffer = decay_par[\"only_predict_from_buffer\"];\n    stm_weight = decay_par[\"stm_weight\"];\n    stm_duration = decay_par[\"stm_duration\"];\n    ltm_weight = decay_par[\"ltm_weight\"];\n    ltm_half_life = decay_par[\"ltm_half_life\"];\n    ltm_asymptote = decay_par[\"ltm_asymptote\"];\n    noise = decay_par[\"noise\"];\n    disable_noise = false;\n    debug_decay = false;\n    \n    stm_half_life = (log(2.0) * stm_duration) / (log(stm_weight / ltm_weight));\n    \n    // if (noise < 0.0) {\n    //   stop(\"noise must be greater than or equal to zero\");\n    // }\n    \n    if (ltm_weight > stm_weight)\n      stop(\"ltm_weight cannot be greater than stm_weight\");\n    \n    if (ltm_weight <= 0.0)\n      stop(\"ltm_weight must be positive\");\n    \n    if (stm_weight <= 0.0)\n      stop(\"stm_weight must be positive\");\n    \n    if (stm_duration < 0)\n      stop(\"stm_duration cannot be negative\");\n      \n    if (ltm_half_life <= 0)\n      stop(\"ltm_half_life must be positive\");\n    \n    if (ltm_asymptote < 0)\n      stop(\"ltm_asymptote must be non-negative\");\n    \n    if (ltm_asymptote > ltm_weight)\n      stop(\"ltm_asymptote cannot be greater than ltm_weight\");\n    \n    if (escape != \"a\") \n      stop(\"escape method must be 'a' for decay-based models\");\n    \n    if (only_learn_from_buffer && buffer_length_items - 1 < order_bound) \n      stop(\"if only_learn_from_buffer is TRUE, order bound cannot be greater than buffer_length_items - 1\");\n    \n    noise_mean = noise * sqrt(2.0 / M_PI); // mean of abs(normal distribution)\n    \n    // std::random_device rd;\n    std::mt19937 engine(seed);\n    std::normal_distribution<> gen{0.0, noise};\n    // std::bernoulli_distribution gen_bernoulli(noise);\n    // std::uniform_int_distribution<int> gen_uniform_int(0, this->alphabet_size - 1);\n    \n    random_engine = engine;\n    noise_generator = gen;\n    // alphabet_sampler = gen_uniform_int;\n  }\n  \n  ~ ppm_decay() {};\n  \n  bool insert(sequence x, int pos, double time, bool full_only) {\n    // Rcout << \"Original sequence: \";\n    // print(x);\n    // sequence noisy_x = x;\n    // for (unsigned int i = 0; i < x.size(); i ++) {\n    //   if (this->noise_generator(this->random_engine)) {\n    //     noisy_x[i] = this->alphabet_sampler(this->random_engine);\n    //   }\n    // } \n    // Rcout << \"New sequence: \";\n    // print(noisy_x);\n    \n    // Only insert the n-gram if it fit completely within the buffer.\n    // Rcout << \"pos_n_gram_begin = \" << pos_n_gram_begin << \"\\n\";\n    \n    if (this->only_learn_from_buffer) {\n      // We skip the n-gram insertion if we find that the n-gram\n      // doesn't fit in the buffer.\n      // Note that we only have to check the temporal constraint;\n      // the positional constraint was checked when the \n      // model's order bound was originally specified.\n      int n_gram_length = x.size();\n      int pos_n_gram_begin = pos - n_gram_length + 1;\n      double time_n_gram_begin = this->all_time.at(pos_n_gram_begin);\n      if (time - time_n_gram_begin >= this->buffer_length_time)\n        return true;\n    }\n    std::unordered_map<sequence, \n                       record_decay, \n                       container_hash<sequence>>::const_iterator target = data.find(x);\n    if (target == data.end()) {\n      record_decay record;\n      record.insert(pos, time);\n      data[x] = record;\n      return false;\n    } else {\n      data[x].insert(pos, time);\n      return true;\n    }\n  }\n  \n  int get_longest_context(sequence context, int pos, double time) {\n    int max_context_size = context.size();\n    if (max_context_size > this->order_bound) stop(\"this shouldn't happen (3)\");\n    if (this->only_predict_from_buffer) {\n      for (int context_size = max_context_size; \n           context_size > 0;\n           context_size --) {\n        // Rcout << \"context_size = \" << context_size << \"\\n\";\n        int pos_context_begin = pos - context_size;\n        // Rcout << \"pos_context_begin = \" << pos_context_begin << \"\\n\";\n        // Rcout << \"all_time = \" << \"\\n\";\n        // print(this->all_time);\n        double time_context_begin = this->all_time.at(pos_context_begin);\n        // Rcout << \"time_context_begin = \" << time_context_begin << \"\\n\";\n        // Rcout << \"pos = \" << pos << \"\\n\";\n        // Rcout << \"time = \" << time << \"\\n\";\n        if (time - time_context_begin <= this->buffer_length_time)\n          return context_size;\n      }\n      return 0;\n    } else {\n      return max_context_size;\n    }\n  } \n  \n  double get_weight(const sequence &n_gram, \n                    int pos, \n                    double time,\n                    bool update_excluded) {\n    record_decay data = this->get(n_gram);\n    \n    int N = static_cast<int>(this->all_time.size());\n    int n = static_cast<int>(data.pos.size());\n    \n    double weight = 0.0;\n    for (int i = 0; i < n; i ++) {\n      if (this->debug_decay) {\n        Rcout << \"\\n\\nobserving from pos = \" << pos << \", time = \" << time << \"\\n\";\n        Rcout << \"memory \" << i << \"/\" << n << \"\\n\";\n      }\n      \n      if (data.pos[i] > pos) {\n        stop(\"tried to predict using training data from the future\");\n      }\n      if (data.pos[i] < 0) {\n        stop(\"data.pos cannot be less than 0\");\n      }\n      \n      // Original buffer version\n      // int pos_item_buffer_fails = data.pos[i] + this->buffer_length_items;\n      // double temporal_buffer_fail_time = data.time[i] + this->buffer_length_time;\n      \n      int pos_item_buffer_fails = data.pos[i] + \n        std::max(0, this->buffer_length_items - static_cast<int>(n_gram.size()) + 1);\n      if (this->debug_decay) Rcout << \"pos_item_buffer_fails = \" << pos_item_buffer_fails << \"\\n\";\n      \n      // Rcout << \"pos = \" << pos << \", N = \" << N << \"\\n\";\n      \n      bool item_buffer_failed = pos_item_buffer_fails <= N - 1; // <= pos;\n      if (this->debug_decay) Rcout << \"item_buffer_failed = \" << item_buffer_failed << \"\\n\";\n      int pos_n_gram_began = data.pos[i] - static_cast<int>(n_gram.size()) + 1;\n      \n      double temporal_buffer_fail_time = \n        this->all_time.at(pos_n_gram_began) + this->buffer_length_time;\n      if (this->debug_decay) Rcout << \"temporal_buffer_fail_time = \" << temporal_buffer_fail_time << \"\\n\";\n      \n      double buffer_fail_time; \n      \n      // Rcout << \"temporal_buffer_fail_time = \" << temporal_buffer_fail_time << \"\\n\";\n      // Rcout << \"pos_item_buffer_fails = \" << pos_item_buffer_fails << \"\\n\";\n      \n      if (item_buffer_failed) {\n        double time_when_item_buffer_failed = this->all_time.at(pos_item_buffer_fails);\n        if (this->debug_decay) Rcout << \"time_when_item_buffer_failed = \" << time_when_item_buffer_failed << \"\\n\";\n        buffer_fail_time = std::min(time_when_item_buffer_failed,\n                                    temporal_buffer_fail_time);\n      } else {\n        buffer_fail_time = temporal_buffer_fail_time;\n      }\n      \n      double time_since_buffer_fail = time - buffer_fail_time;\n      \n      if (this->debug_decay) {\n        Rcout << \"buffer_fail_time = \" << buffer_fail_time << \"\\n\";\n        Rcout << \"time_since_buffer_fail = \" << time_since_buffer_fail << \"\\n\";\n      }\n      \n      double weight_increment;\n      \n      if (time_since_buffer_fail < 0) {\n        if (this->debug_decay) Rcout << \"buffer didn't fail\\n\";\n        weight_increment = this->buffer_weight;\n      } else {\n        if (this->debug_decay) Rcout << \"buffer failed\\n\";\n        weight_increment = this->decay_stm_ltm(time_since_buffer_fail);\n      }\n      \n      if (this->debug_decay) Rcout << \"weight_increment = \" << weight_increment << \"\\n\";\n      \n      weight += weight_increment;\n    }\n    \n    if (!this->disable_noise) {\n      // Rcout << \"original weight = \" << noise << \"\\n\";\n      double noise = fabs(this->noise_generator(this->random_engine));\n      // Rcout << \"noise = \" << noise << \"\\n\\n\";\n      weight += noise;\n      // return std::max(0.0, weight);\n    }\n    \n    if (this->debug_decay) {\n      Rcout << \"\\ntotal weight = \" << weight << \"\\n\";\n    }\n    \n    return weight;\n  }; \n  \n  double decay_stm_ltm(double elapsed_time) {\n    bool stm = elapsed_time < this->stm_duration;\n    double res;\n    if (stm) {\n      res =  decay_exp(this->stm_weight, \n                       elapsed_time, \n                       this->stm_half_life,\n                       0.0);\n    } else {\n      res =  decay_exp(this->ltm_weight,\n                       elapsed_time - this->stm_duration,\n                       this->ltm_half_life,\n                       this->ltm_asymptote);\n    }\n    // if (this->debug_decay) Rcout << \"elapsed_time = \" << elapsed_time << \", fraction = \" << res << \"\\n\";\n    return res;\n  }\n  \n  double decay_exp(double start, \n                   double elapsed_time,\n                   double half_life,\n                   double asymptote) {\n    if (half_life <= 0.0) stop(\"half life must be positive\");\n    return \n      asymptote + (start - asymptote) * std::pow(2.0, - elapsed_time / half_life);\n  }\n\n  double get_lambda(const std::vector<double> &counts, double context_count, int num_distinct_symbols) {\n    if (this->debug_smooth) {\n      Rcout << \"calling ppm_decay.get_lambda()\\n\";\n    }\n    double total_expected_noise;\n    if (this->disable_noise) {\n      total_expected_noise = 0.0;\n    } else {\n      total_expected_noise = this->noise_mean * this->alphabet_size;\n    }\n    double adj_context_count = std::max(context_count - total_expected_noise,\n                                        0.0);\n    \n    // Rcout << \"original context count = \" << context_count << \"\\n\";\n    // Rcout << \"total_expected_noise = \" << total_expected_noise << \"\\n\";\n    // Rcout << \"adj_context_count = \" << adj_context_count << \"\\n\\n\";\n    \n    if (context_count <= 0.0) { \n      if (this->debug_smooth) {\n        // this should actually be adj_context_count, but does it matter?\n        // no, because adj_context_count always <= context_count\n        Rcout << \"context_count <= 0.0 so lambda = 0.0\\n\";\n      }\n      return 0.0;\n    } else {\n      if (this->debug_smooth) {\n        Rcout << \"calling lambda_a...\\n\";\n      }\n      return this->lambda_a(counts, adj_context_count, -99); // last parameter ignored\n    }\n  }\n  \n  record_decay get(const sequence &x) {\n    std::unordered_map<sequence, \n                       record_decay, \n                       container_hash<sequence>>::const_iterator target = data.find(x);\n    if (target == data.end()) {\n      record_decay blank;\n      return(blank);\n    } else {\n      return(target->second);\n    }\n  } \n  \n  List as_list() {\n    int n = data.size();\n    List n_gram(n);\n    List pos(n);\n    List time(n);\n    \n    int i = 0;\n    for(auto kv : data) {\n      n_gram[i] = kv.first;\n      pos[i] = kv.second.pos;\n      time[i] = this->all_time[pos[i]];\n      i ++;\n    } \n    \n    List x = List::create(Named(\"n_gram\") = n_gram,\n                          Named(\"pos\") = pos,\n                          Named(\"time\") = time);\n    return(x);\n  }\n  \n  RObject as_tibble() {\n    return(list_to_tibble(this->as_list()));\n  }\n  \n};\n\n// ppm test_ppm() {\n//   escape_a esc;\n//   return ppm(10, // alphabet size\n//              10, // order bound\n//              true, //shortest deterministic\n//              true, // exclusion\n//              true, // update_exclusion\n//              esc);\n// }\n\nRCPP_EXPOSED_CLASS(record_decay)\n  RCPP_EXPOSED_CLASS(ppm)\n  RCPP_EXPOSED_CLASS(ppm_simple)\n  RCPP_EXPOSED_CLASS(ppm_decay)\n  RCPP_EXPOSED_CLASS(symbol_prediction)\n  RCPP_EXPOSED_CLASS(sequence_prediction)\n  \n  RCPP_MODULE(ppm) {\n    class_<sequence_prediction>(\"sequence_prediction\")\n    .field(\"information_content\", &sequence_prediction::information_content)\n    .field(\"entropy\", &sequence_prediction::entropy)\n    .field(\"distribution\", &sequence_prediction::distribution)\n    .method(\"as_tibble\", &sequence_prediction::as_tibble)\n    ;\n    \n    class_<ppm>(\"ppm\")\n      // ppm class cannot be instantiated directly in R\n      // .constructor<int, int, bool, bool, bool, std::string>()\n         .field(\"alphabet_size\", &ppm::alphabet_size)\n         .field(\"order_bound\", &ppm::order_bound)\n         .field(\"shortest_deterministic\", &ppm::shortest_deterministic)\n         .field(\"exclusion\", &ppm::exclusion)\n         .field(\"update_exclusion\", &ppm::update_exclusion)\n         .field(\"escape\", &ppm::escape)\n         .field(\"all_time\", &ppm::all_time)\n         .field(\"sub_n_from_m1_dist\", &ppm::sub_n_from_m1_dist)\n         .field(\"lambda_uses_zero_weight_symbols\", &ppm::lambda_uses_zero_weight_symbols)\n         .field(\"debug_smooth\", &ppm::debug_smooth)\n         .field(\"alphabet_levels\", &ppm::alphabet_levels)\n         .method(\"model_seq\", &ppm::model_seq)\n      // .method(\"insert\", &ppm::insert)\n         .method(\"get_weight\", &ppm::get_weight)\n      ;\n    \n    class_<ppm_simple>(\"ppm_simple\")\n      .derives<ppm>(\"ppm\")\n      .constructor<int, int, bool, bool, bool, std::string, CharacterVector>()\n      .method(\"get_count\", &ppm_simple::get_count)\n      .method(\"as_tibble\", &ppm_simple::as_tibble)\n    ;\n    \n    class_<ppm_decay>(\"ppm_decay\")\n      .derives<ppm>(\"ppm\")\n      .constructor<int, int, List, int, CharacterVector>()\n      .method(\"get\", &ppm_decay::get)\n      .method(\"as_tibble\", &ppm_decay::as_tibble)\n      .method(\"as_list\", &ppm_decay::as_list)\n      .field(\"buffer_length_time\", &ppm_decay::buffer_length_time)\n      .field(\"buffer_length_items\", &ppm_decay::buffer_length_items)\n      .field(\"buffer_weight\", &ppm_decay::buffer_weight)\n      .field(\"only_learn_from_buffer\", &ppm_decay::only_learn_from_buffer)\n      .field(\"only_predict_from_buffer\", &ppm_decay::only_predict_from_buffer)\n      .field(\"stm_weight\", &ppm_decay::stm_weight)\n      .field(\"stm_duration\", &ppm_decay::stm_duration)\n      .field(\"stm_half_life\", &ppm_decay::stm_half_life)\n      .field(\"ltm_weight\", &ppm_decay::ltm_weight)\n      .field(\"ltm_half_life\", &ppm_decay::ltm_half_life)\n      .field(\"ltm_asymptote\", &ppm_decay::ltm_asymptote)\n      .field(\"noise\", &ppm_decay::noise)\n      .field(\"noise_mean\", &ppm_decay::noise_mean)\n      .field(\"disable_noise\", &ppm_decay::disable_noise)\n      .field(\"seed\", &ppm_decay::seed)\n      .field(\"debug_decay\", &ppm_decay::debug_decay)\n    ;\n    \n    class_<record_decay>(\"record_decay\")\n      .constructor()\n      .field(\"pos\", &record_decay::pos)\n    // .field(\"time\", &record_decay::   time)\n       .method(\"insert\", &record_decay::insert)\n    ;\n  }\n\n", "meta": {"hexsha": "e7bf60f29e61c6862d6b872866c9d13ab72decd7", "size": 44795, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ppm.cpp", "max_stars_repo_name": "pmcharrison/ppm", "max_stars_repo_head_hexsha": "d58e7598e02a6df8a4ef013f5e19987311295196", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-12-28T16:03:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-02T07:59:17.000Z", "max_issues_repo_path": "src/ppm.cpp", "max_issues_repo_name": "pmcharrison/ppm", "max_issues_repo_head_hexsha": "d58e7598e02a6df8a4ef013f5e19987311295196", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ppm.cpp", "max_forks_repo_name": "pmcharrison/ppm", "max_forks_repo_head_hexsha": "d58e7598e02a6df8a4ef013f5e19987311295196", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-09-15T10:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T21:36:44.000Z", "avg_line_length": 31.9507845934, "max_line_length": 114, "alphanum_fraction": 0.5837258623, "num_tokens": 11160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.28211478544317137}}
{"text": "/*ckwg +29\n * Copyright 2013-2015 by Kitware, 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 *  * 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 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 name of Kitware, Inc. nor the names of any contributors may be used\n *    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''\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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR\n * 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/**\n * \\file\n * \\brief Implementation of \\link kwiver::vital::camera_intrinsics_\n *        camera_intrinsics_<T> \\endlink class\n *        for \\c T = { \\c float, \\c double }\n */\n\n#include <vital/types/camera_intrinsics.h>\n#include <vital/io/eigen_io.h>\n#include <vital/math_constants.h>\n#include <Eigen/Dense>\n\n#include <cmath>\n#include <iomanip>\n\nnamespace kwiver {\nnamespace vital {\n\n\n/// Convert to a 3x3 calibration matrix\nmatrix_3x3d\ncamera_intrinsics\n::as_matrix() const\n{\n  matrix_3x3d K;\n  const double f = this->focal_length();\n  const vector_2d pp = this->principal_point();\n  K << f, this->skew(), pp.x(),\n    0, f / this->aspect_ratio(), pp.y(),\n    0, 0, 1;\n  return K;\n}\n\n\n/// Map normalized image coordinates into actual image coordinates\nvector_2d\ncamera_intrinsics\n::map( const vector_2d& point ) const\n{\n  // apply radial and tangential distortion if coefficients are provided\n  const vector_2d pt = this->distort( point );\n  const vector_2d pp = this->principal_point();\n  const double f = this->focal_length();\n\n  return vector_2d( pt.x() * f + pt.y() * this->skew() + pp.x(),\n                    pt.y() * f / this->aspect_ratio() + pp.y() );\n}\n\n\n/// Map a 3D point in camera coordinates into actual image coordinates\nvector_2d\ncamera_intrinsics\n::map( const vector_3d& norm_hpt ) const\n{\n  return this->map( vector_2d( norm_hpt[0] / norm_hpt[2],\n                               norm_hpt[1] / norm_hpt[2] ) );\n}\n\n\n/// Unmap actual image coordinates back into normalized image coordinates\nvector_2d\ncamera_intrinsics\n::unmap( const vector_2d& pt ) const\n{\n  const double f = this->focal_length();\n  const vector_2d p0 = pt - this->principal_point();\n  const double y = p0.y() * this->aspect_ratio() / f;\n  const double x = ( p0.x() - y * this->skew() ) / f;\n\n  return this->undistort( vector_2d( x, y ) );\n}\n\n\n/// Check if a 3D point in camera coordinates can map into image coordinates\nbool\ncamera_intrinsics\n::is_map_valid(const vector_3d& norm_hpt) const\n{\n  return this->is_map_valid(vector_2d(norm_hpt[0] / norm_hpt[2],\n                                      norm_hpt[1] / norm_hpt[2]));\n}\n\n\nnamespace // anonymous namespace\n{\n\n\n/// Compute the radial distortion scaling\n/** Distortion scaling is a function of the squared radius \\p r2\n *  and the distortion parameters \\p d\n */\ntemplate < typename T >\nT\nradial_distortion_scale( const T                r2,\n                         const Eigen::VectorXd&  d )\n{\n  T scale = T( 1 );\n\n  if ( d.rows() > 0 )\n  {\n    scale += r2 * d[0];\n    if ( d.rows() > 1 )\n    {\n      const T r4 = r2 * r2;\n      scale += r4 * d[1];\n      if ( d.rows() > 4 )\n      {\n        const T r6 = r2 * r4;\n        scale += r6 * d[4];\n        if ( d.rows() > 7 )\n        {\n          scale /= T( 1 ) + r2 * d[5] + r4 * d[6] + r6 * d[7];\n        }\n      }\n    }\n  }\n  return scale;\n}\n\n\n/// Compute radial distortion as a scaling and offset\n/** For a point \\p pt and distortion coefficients \\p d compute\n *  a scale and offset such that distortion can be applied as\n *  \\code\n *    distorted_pt = pt * scale + offset;\n *  \\endcode\n */\ntemplate < typename T >\nvoid\ndistortion_scale_offset( const Eigen::Matrix< T, 2, 1 >& pt,\n                         const Eigen::VectorXd& d,\n                         T& scale, Eigen::Matrix< T, 2, 1 >& offset )\n{\n  const T x2 = pt.x() * pt.x();\n  const T y2 = pt.y() * pt.y();\n  const T r2 = x2 + y2;\n\n  scale = radial_distortion_scale( r2, d );\n  offset = Eigen::Matrix< T, 2, 1 > ( T( 0 ), T( 0 ) );\n  if ( d.rows() > 3 )\n  {\n    const T two_xy = 2 * pt.x() * pt.y();\n    offset = Eigen::Matrix< T, 2, 1 > ( d[2] * two_xy + d[3] * ( r2 + 2 * x2 ),\n                                        d[3] * two_xy + d[2] * ( r2 + 2 * y2 ) );\n  }\n}\n\n\n/// Compute the derivative of the radial distortion as a function of \\p r2\ntemplate < typename T >\nT\nradial_distortion_deriv( const T                r2,\n                         const Eigen::VectorXd&  d )\n{\n  T deriv = T( 0 );\n\n  if ( d.rows() > 0 )\n  {\n    deriv += d[0];\n    if ( d.rows() > 1 )\n    {\n      deriv += 2 * d[1] * r2;\n      if ( d.rows() > 4 )\n      {\n        const T r4 = r2 * r2;\n        deriv += 3 * d[4] * r4;\n        if ( d.rows() > 7 )\n        {\n          const T r6 = r4 * r2;\n          const T a1 = T( 1 ) / ( d[5] * r2 + d[6] * r4 + d[7] * r6 + T( 1 ) );\n          const T a2 = d[5] + 2 * d[6] * r2 + 3 * d[7] * r4;\n          deriv -= a2 * a1 * ( d[0] * r2 + d[1] * r4 + d[4] * r6 + T( 1 ) );\n          deriv *= a1;\n        }\n      }\n    }\n  }\n  return deriv;\n}\n\n\n/// Compute the Jacobian of the distortion at a point\ntemplate < typename T >\nEigen::Matrix< T, 2, 2 >\ndistortion_jacobian( const Eigen::Matrix< T, 2, 1 >& pt,\n                     const Eigen::VectorXd& d )\n{\n  const T x2 = pt.x() * pt.x();\n  const T y2 = pt.y() * pt.y();\n  const T xy = pt.x() * pt.y();\n  const T r2 = x2 + y2;\n  const T d_scale = 2 * radial_distortion_deriv( r2, d );\n  const T scale = radial_distortion_scale( r2, d );\n  Eigen::Matrix< T, 2, 2 > J;\n\n  J << d_scale * x2 + scale, d_scale * xy,\n    d_scale * xy, d_scale * y2 + scale;\n  // add tangential distortion jacobian\n  if ( d.rows() > 3 )\n  {\n    const T axy = 2 * ( d[2] * pt.x() + d[3] * pt.y() );\n    const T ay = 2 * d[2] * pt.y();\n    const T ax = 2 * d[3] * pt.x();\n    J( 0, 0 ) += ay + 3 * ax;\n    J( 0, 1 ) += axy;\n    J( 1, 0 ) += axy;\n    J( 0, 0 ) += 3 * ay + ax;\n  }\n  return J;\n}\n\n\n} // end anonymous namespace\n\n\n/// Constructor - from a calibration matrix\nsimple_camera_intrinsics\n::simple_camera_intrinsics( const matrix_3x3d& K,\n                            const vector_t& d )\n  : focal_length_( K( 0, 0 ) ),\n  principal_point_( K( 0, 2 ), K( 1, 2 ) ),\n  aspect_ratio_( K( 0, 0 ) / K( 1, 1 ) ),\n  skew_( K( 0, 1 ) ),\n  dist_coeffs_( d ),\n  max_distort_radius_sq_(compute_max_distort_radius_sq())\n{\n}\n\n\n/// Map normalized image coordinates into distorted coordinates\nvector_2d\nsimple_camera_intrinsics\n::distort( const vector_2d& norm_pt ) const\n{\n  double scale;\n  vector_2d offset;\n\n  distortion_scale_offset( norm_pt, dist_coeffs_, scale, offset );\n  return scale * norm_pt + offset;\n}\n\n\n/// Unnap distorted normalized coordinates into normalized coordinates\nvector_2d\nsimple_camera_intrinsics\n::undistort( const vector_2d& dist_pt ) const\n{\n  double scale;\n  vector_2d offset, residual;\n  vector_2d norm_pt = dist_pt;\n\n  // iteratively solve for the undistorted point\n  for ( unsigned int i = 0; i < 5; ++i )\n  {\n    distortion_scale_offset( norm_pt, dist_coeffs_, scale, offset );\n    // This is a Gauss-Newton update\n    // an alternative is a fixed point iteration as used by OpenCV:\n    //   norm_pt = (dist_pt - offset) / scale;\n    // Gauss-Newton seems to have faster convergence\n    matrix_2x2d J = distortion_jacobian( norm_pt, dist_coeffs_ );\n    residual = norm_pt * scale + offset - dist_pt;\n    // check the maximum absolution residual to test convergence\n    if ( residual.cwiseAbs().maxCoeff() < 1e-12 )\n    {\n      break;\n    }\n    norm_pt -= J.ldlt().solve( residual );\n  }\n  return norm_pt;\n}\n\n/// Check if a normalized image coordinate can map into image coordinates\nbool\nsimple_camera_intrinsics\n::is_map_valid(const vector_2d& norm_pt) const\n{\n  return norm_pt.squaredNorm() < this->max_distort_radius_sq_;\n}\n\n\n/// Compute the maximum distortion radius from dist_coeffs_\ndouble\nsimple_camera_intrinsics\n::compute_max_distort_radius_sq() const\n{\n  double a = 0.0;\n  double b = 0.0;\n  double c = 0.0;\n  if (dist_coeffs_.rows() > 0)\n  {\n    a = dist_coeffs_[0];\n    if (dist_coeffs_.rows() > 1)\n    {\n      b = dist_coeffs_[1];\n      if (dist_coeffs_.rows() > 4)\n      {\n        c = dist_coeffs_[4];\n        if (dist_coeffs_.rows() > 5)\n        {\n          // the rational polynomial case is not yet handled\n          // TODO: implement something or throw a warning\n        }\n      }\n    }\n  }\n  return max_distort_radius_sq(a, b, c);\n}\n\n\n/// Compute the maximum radius for radial distortion given coefficients\ndouble\nsimple_camera_intrinsics\n::max_distort_radius_sq(double a, double b, double c)\n{\n  constexpr double inf = std::numeric_limits<double>::infinity();\n  using kwiver::vital::pi;\n  // this function finds the smallest positive root of\n  //   (1 + a r^2 + b r^4 + c r^6) r\n  // the derivative with respect to r is\n  //   1 + 3 a r^2 + 5 b r^4 + 7 c r^6\n  // substituting x = r^2 we can solve this cubic polynomial\n  //   1 + 3 a x + 5 b x^2 + 7 c r^3\n  // taking the square root of the smallest positive x gives r\n\n  // fold the constants from the derivative into a, b, and c\n  a *= 3;\n  b *= 5;\n  c *= 7;\n\n  // if all non-negative there is no root\n  if (a >= 0.0 && b >= 0.0 && c >= 0.0)\n  {\n    return inf;\n  }\n  // general solution for non-zero cubic term\n  if (c != 0.0)\n  {\n    // an array for the three possible solutions\n    double solns[3] = { inf, inf, inf };\n    // precompute commonly used terms (boc is \"b over c\")\n    double boc = b / c;\n    double boc2 = boc * boc;\n    double t1 = (9 * a * boc - 2 * b * boc2 - 27) / c;\n    double t2 = 3 * a / c - boc2;\n    double discrim = t1 * t1 + 4 * t2 * t2 * t2;\n    if (discrim > 0.0)\n    {\n      discrim = std::cbrt((std::sqrt(discrim) + t1) / 2.0);\n      solns[0] = (discrim - (t2 / discrim) - boc) / 3;\n    }\n    else\n    {\n      double theta = (std::atan2(std::sqrt(-discrim), t1)) / 3;\n      constexpr double twothirdpi = 2.0 * pi / 3.0;\n      // by construction, if discrim < 0 then t2 < 0, so the sqrt is safe\n      double t3 = 2 * std::sqrt(-t2);\n      solns[0] = (t3 * std::cos(theta) - boc) / 3;\n      solns[1] = (t3 * std::cos(theta + twothirdpi) - boc) / 3;\n      solns[2] = (t3 * std::cos(theta - twothirdpi) - boc) / 3;\n    }\n    // find the minimum positive solution\n    double min_soln = inf;\n    for (auto const& s : solns)\n    {\n      if (s > 0.0 && s < min_soln)\n      {\n        min_soln = s;\n      }\n    }\n    return min_soln;\n  }\n  // simplified solution for the quadratic case\n  else if (b != 0.0)\n  {\n    double discrim = a * a - 4 * b;\n    // if less than zero both solutions are not real\n    if (discrim >= 0.0)\n    {\n      // we only need the smaller of the two possible solutions\n      // solutions must be either both positive or both negative\n      discrim = std::sqrt(discrim) - a;\n      // if less than zero both solutions are negative\n      if (discrim > 0.0)\n      {\n        return 2.0 / discrim;\n      }\n    }\n  }\n  // simple linear case for b = c = 0\n  else if (a < 0.0)\n  {\n    return 1.0 / -a;\n  }\n  return inf;\n}\n\n\n/// output stream operator for a base class camera_intrinsics\nstd::ostream&\noperator<<( std::ostream& s, const camera_intrinsics& k )\n{\n  using std::setprecision;\n  std::vector<double> d = k.dist_coeffs();\n  // if no distortion coefficients, create a zero entry as a place holder\n  if ( d.empty() )\n  {\n    d.push_back(0.0);\n  }\n  s << setprecision( 12 ) << k.as_matrix() << \"\\n\\n\";\n  for(unsigned i=0; i<d.size(); ++i)\n  {\n    s << setprecision( 12 ) << d[i] << \" \";\n  }\n  s << \"\\n\";\n\n  return s;\n}\n\n\n/// input stream operator for a camera intrinsics\nstd::istream&\noperator>>( std::istream& s, simple_camera_intrinsics& k )\n{\n  matrix_3x3d K;\n  Eigen::VectorXd d;\n\n  s >> K >> d;\n  // a single 0 in d is used as a place holder,\n  // if a single 0 was loaded then clear d\n  if ( ( d.rows() == 1 ) && ( d[0] == 0.0 ) )\n  {\n    d.resize( 0 );\n  }\n  k = simple_camera_intrinsics( K, d );\n  return s;\n}\n\n\n} } // end namespace\n", "meta": {"hexsha": "6d3199258bb9d5c0f626ac2b57f3088c0ea26643", "size": 12939, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "vital/types/camera_intrinsics.cxx", "max_stars_repo_name": "neal-siekierski/kwiver", "max_stars_repo_head_hexsha": "1c97ad72c8b6237cb4b9618665d042be16825005", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-14T18:22:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-14T18:22:42.000Z", "max_issues_repo_path": "vital/types/camera_intrinsics.cxx", "max_issues_repo_name": "neal-siekierski/kwiver", "max_issues_repo_head_hexsha": "1c97ad72c8b6237cb4b9618665d042be16825005", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vital/types/camera_intrinsics.cxx", "max_forks_repo_name": "neal-siekierski/kwiver", "max_forks_repo_head_hexsha": "1c97ad72c8b6237cb4b9618665d042be16825005", "max_forks_repo_licenses": ["BSD-3-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.529787234, "max_line_length": 81, "alphanum_fraction": 0.6011283716, "num_tokens": 3946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.28211478544317137}}
{"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_TRIGONOMETRIC_CONSTANTS_PIO_2LO_HPP_INCLUDED\n#define NT2_TRIGONOMETRIC_CONSTANTS_PIO_2LO_HPP_INCLUDED\n\n#include <nt2/include/functor.hpp>\n#include <boost/simd/constant/hierarchy.hpp>\n#include <boost/simd/constant/register.hpp>\nnamespace nt2\n{\n  namespace tag\n  {\n   /*!\n     @brief Pio_2lo generic tag\n\n     Represents the Pio_2lo constant in generic contexts.\n\n     @par Models:\n        Hierarchy\n   **/\n    BOOST_SIMD_CONSTANT_REGISTER( Pio_2lo, double\n                                , 0, 0xb33bbd2eUL\n                                , 0x3c91a62633145c07ULL\n                                )\n  }\n  namespace ext\n  {\n   template<class Site, class... Ts>\n   BOOST_FORCEINLINE generic_dispatcher<tag::Pio_2lo, Site> dispatching_Pio_2lo(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)\n   {\n     return generic_dispatcher<tag::Pio_2lo, Site>();\n   }\n   template<class... Args>\n   struct impl_Pio_2lo;\n  }\n  /*!\n    This constant is such that, for pairs of types (T, Tup)\n    (namely (float,  double) and (double, long double)) the sum:\n\n    abs(Tup(Pio_2lo<T>())+Tup(Pio_2<T>())-Pio_2<Tup>()) is  lesser than\n    a few Eps<Tup>().\n\n\n    This is used to improve accurracy when computing sums of the kind\n    \\f$\\pi/2 + x\\f$ with x small,  by replacing them by\n    Pio_2 + (Pio_2lo + x)\n\n    @par Semantic:\n\n    For type T0:\n\n    @code\n    T r = Pio_2lo<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    if T is double\n      r = 6.123233995736766e-17\n    else if T is float\n      r = -4.3711388e-08\n    @endcode\n\n    @return a value of type T0\n  **/\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(tag::Pio_2lo, Pio_2lo);\n}\n\n#endif\n\n", "meta": {"hexsha": "2d6e09f64b6378444fa0a1041d25cb986b1e1b16", "size": 2185, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/pio_2lo.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/pio_2lo.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/trigonometric/include/nt2/trigonometric/constants/pio_2lo.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0128205128, "max_line_length": 170, "alphanum_fraction": 0.5821510297, "num_tokens": 616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.28211478544317137}}
{"text": "#include <cryptopp/eccrypto.h>\n#include <cryptopp/ecpoint.h>\n#include <cryptopp/asn.h>\n#include <cryptopp/crc.h>\n#include <cryptopp/oids.h>\n#include <cryptopp/osrng.h>\n#include <cryptopp/drbg.h>\n#include <cryptopp/modes.h>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <set>\n#include <thread>\n#include <string>\n#include <sstream>\n#include <boost/tokenizer.hpp>\n\nconst CryptoPP::ECPPoint G(CryptoPP::Integer(\"362dc3caf8a0e8afd06f454a6da0cdce6e539bc3f15e79a15af8aa842d7e3ec2h\"),\n                           CryptoPP::Integer(\"b9f8addb295b0fd4d7c49a686eac7b34a9a11ed2d6d243ad065282dc13bce575h\"));\n\nconst CryptoPP::ECPPoint H(CryptoPP::Integer(\"a3cf0a4b6e1d9146c73e9a82e4bfdc37ee1587bc2bf3b0c19cb159ae362e38beh\"),\n                           CryptoPP::Integer(\"db4369fabd3d770dd4c19d81ac69a1749963d69c687d7c4e12d186548b94cb2ah\"));\n\nstd::mutex mut;\n\nunsigned NUM_THREADS = 6;\n\nuint32_t num_values = 256;\nstd::vector<std::vector<CryptoPP::ECPPoint>> testMatrix(num_values);\n\nint main() {\n    CryptoPP::AutoSeededRandomPool PRNG;\n    CryptoPP::DL_GroupParameters_EC<CryptoPP::ECP> ec_group;\n    ec_group.Initialize(CryptoPP::ASN1::secp256k1());\n\n    auto start = std::chrono::high_resolution_clock::now();\n    std::vector<CryptoPP::ECPPoint> test;\n    test.reserve(10000);\n    for(uint32_t i = 0; i < 8864; i++) {\n        CryptoPP::Integer exponent(PRNG, CryptoPP::Integer::One(), ec_group.GetMaxExponent());\n        CryptoPP::ECPPoint testPoint = ec_group.GetCurve().ScalarMultiply(G, exponent);\n        test.push_back(std::move(testPoint));\n    }\n    auto finish = std::chrono::high_resolution_clock::now();\n\n    std::chrono::duration<double> duration = finish - start;\n\n    std::cout << \"Duration: \" << duration.count() << std::endl;\n    /*\n    for(;;) {\n        CryptoPP::Integer d(PRNG, CryptoPP::Integer::One(), ec_group.GetMaxExponent());\n        CryptoPP::Integer r(PRNG, CryptoPP::Integer::One(), ec_group.GetMaxExponent());\n        CryptoPP::Integer z(PRNG, CryptoPP::Integer::One(), ec_group.GetMaxExponent());\n\n        CryptoPP::Integer w = r * z + d;\n        w = w.Modulo(ec_group.GetSubgroupOrder());\n\n        CryptoPP::Integer rz = r * z;\n        rz = rz.Modulo(ec_group.GetSubgroupOrder());\n\n        CryptoPP::ECPPoint wG = ec_group.GetCurve().ScalarMultiply(G, w);\n\n        CryptoPP::ECPPoint rzG = ec_group.GetCurve().ScalarMultiply(G, rz);\n        CryptoPP::ECPPoint dG = ec_group.GetCurve().ScalarMultiply(G, d);\n\n        CryptoPP::ECPPoint rzG_dG = ec_group.GetCurve().Add(rzG, dG);\n\n        std::cout << \"wG\" << std::endl;\n        std::cout << std::hex << wG.x << std::endl;\n        std::cout << std::hex << wG.y << std::endl;\n\n        std::cout << \"rzG + dG\" << std::endl;\n        std::cout << std::hex << rzG_dG.x << std::endl;\n        std::cout << std::hex << rzG_dG.y << std::endl;\n\n        if ((wG.x != rzG_dG.x) || (wG.y != rzG_dG.y))\n            break;\n\n        CryptoPP::Integer r_(PRNG, CryptoPP::Integer::One(), ec_group.GetMaxExponent());\n        CryptoPP::Integer x(PRNG, CryptoPP::Integer::One(), ec_group.GetMaxExponent());\n\n        CryptoPP::Integer rr_ = r + r_;\n\n        CryptoPP::ECPPoint rG = ec_group.GetCurve().ScalarMultiply(G, r);\n        CryptoPP::ECPPoint r_G = ec_group.GetCurve().ScalarMultiply(G, r_);\n\n        CryptoPP::ECPPoint xH = ec_group.GetCurve().ScalarMultiply(H, x);\n\n        CryptoPP::ECPPoint rr_G = ec_group.GetCurve().ScalarMultiply(G, rr_);\n\n        CryptoPP::ECPPoint C = ec_group.GetCurve().Add(rG, xH);\n\n        CryptoPP::ECPPoint C_ = ec_group.GetCurve().Add(rr_G, xH);\n\n        CryptoPP::ECPPoint Cr_G = ec_group.GetCurve().Add(C, r_G);\n\n        CryptoPP::ECPPoint CC_ = ec_group.GetCurve().Add(C_, ec_group.GetCurve().Inverse(C));\n\n        std::cout << \"C:\" << std::endl;\n        std::cout << std::hex << C.x << std::endl;\n        std::cout << std::hex << C.y << std::endl;\n\n        std::cout << \"C_:\" << std::endl;\n        std::cout << std::hex << C_.x << std::endl;\n        std::cout << std::hex << C_.y << std::endl;\n\n        std::cout << \"Cr_G:\" << std::endl;\n        std::cout << std::hex << Cr_G.x << std::endl;\n        std::cout << std::hex << Cr_G.y << std::endl;\n\n        std::cout << \"r_G:\" << std::endl;\n        std::cout << std::hex << r_G.x << std::endl;\n        std::cout << std::hex << r_G.y << std::endl;\n\n        std::cout << \"CC_:\" << std::endl;\n        std::cout << std::hex << CC_.x << std::endl;\n        std::cout << std::hex << CC_.y << std::endl;\n\n        if ((CC_.x != r_G.x) || (CC_.y != r_G.y))\n            break;\n    }\n    */\n    return 0;\n}\n", "meta": {"hexsha": "d08294ca3b48c4013e6f1d183d94e59216e64860", "size": 4552, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/CryptoTest.cpp", "max_stars_repo_name": "vs-uulm/3p3-evaluation", "max_stars_repo_head_hexsha": "ca6683acd0d4cc20ce65035e5eea34409b73a712", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test/CryptoTest.cpp", "max_issues_repo_name": "vs-uulm/3p3-evaluation", "max_issues_repo_head_hexsha": "ca6683acd0d4cc20ce65035e5eea34409b73a712", "max_issues_repo_licenses": ["MIT"], "max_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/CryptoTest.cpp", "max_forks_repo_name": "vs-uulm/3p3-evaluation", "max_forks_repo_head_hexsha": "ca6683acd0d4cc20ce65035e5eea34409b73a712", "max_forks_repo_licenses": ["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.416, "max_line_length": 115, "alphanum_fraction": 0.6151142355, "num_tokens": 1404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.28209250001140973}}
{"text": "/*\n * Copyright (c) 2016, Georgia Tech Research Corporation\n * All rights reserved.\n *\n * Author(s): Michael X. Grey <mxgrey@gatech.edu>\n *\n * Georgia Tech Graphics Lab and AMBER Lab\n *\n * Directed by Prof. C. Karen Liu and Prof. Aaron Ames\n * <karenliu@cc.gatech.edu> <ames@gatech.edu>\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#ifndef HUBO_UTILS_HPP\n#define HUBO_UTILS_HPP\n\n#include <Eigen/Geometry>\n\nnamespace hubo {\n\nconst double DefaultIsometryTolerance = 1e-6;\nconst double DefaultVectorTolerance = 1e-6;\n\n//==============================================================================\nstatic inline bool checkDist(Eigen::Vector3d& p, double a, double b)\n{\n  double d = p.norm();\n  double dmax = a+b;\n  double dmin = fabs(a-b);\n\n  if (d > dmax)\n  {\n    p *= dmax/d;\n    return false;\n  }\n  else if (d < dmin)\n  {\n    p *= dmin/d;\n    return false;\n  }\n  else\n  {\n    return true;\n  }\n}\n\n//==============================================================================\nstatic inline void clamp_sincos(double& sincos, bool& valid)\n{\n  if (sincos < -1)\n  {\n    valid = false;\n    sincos = -1;\n  }\n  else if (sincos > 1)\n  {\n    valid = false;\n    sincos = 1;\n  }\n}\n\n//==============================================================================\nstatic inline Eigen::Vector3d flipEuler3Axis(const Eigen::Vector3d& u)\n{\n  Eigen::Vector3d v;\n  v[0] = u[0] - M_PI;\n  v[1] = M_PI - u[1];\n  v[2] = u[2] - M_PI;\n  return v;\n}\n\n//==============================================================================\ninline double diff(const Eigen::Isometry3d& tf0,\n                   const Eigen::Isometry3d& tf1)\n{\n  double cost = (tf0.translation() - tf1.translation()).norm();\n  Eigen::AngleAxisd aa(tf0.linear().transpose()*tf1.linear());\n  cost += aa.angle();\n\n  return cost;\n}\n\n//==============================================================================\ninline bool equal(const Eigen::Isometry3d& tf0,\n                  const Eigen::Isometry3d& tf1,\n                  const double tolerance = DefaultIsometryTolerance)\n{\n  return (diff(tf0, tf1) < tolerance);\n}\n\n//==============================================================================\ninline bool equal(const Eigen::VectorXd& v0,\n                  const Eigen::VectorXd& v1,\n                  const double tolerance = DefaultVectorTolerance)\n{\n  return ((v1-v0).norm() < tolerance);\n}\n\n//==============================================================================\ninline Eigen::AngleAxisd findRotation(\n    const Eigen::Vector3d& x1, const Eigen::Vector3d& x0)\n{\n  Eigen::Vector3d N = x1.cross(x0);\n  double s = N.norm();\n  double theta = asin(s);\n  // Deal with numerical imprecision issues\n  if(s < -1.1 || 1.1 < s)\n  {\n    std::cout << \"[findRotation] Strange value for s: \" << s\n              << \" | Results in theta: \" << theta << std::endl;\n    return Eigen::AngleAxisd(0, Eigen::Vector3d::UnitZ());\n  }\n  else if(1.0 <= s)\n  {\n    theta = M_PI/2.0;\n  }\n  else if(s <= -1.0)\n  {\n    theta = -M_PI/2.0;\n  }\n\n  N.normalize();\n\n  const double wrap = x1.dot(x0);\n  if(wrap < 0)\n    theta = M_PI - theta;\n\n  if(std::abs(theta-M_PI) < 1e-4\n     || std::abs(theta+M_PI) < 1e-4)\n    return Eigen::AngleAxisd(M_PI, Eigen::Vector3d::UnitZ());\n\n  return Eigen::AngleAxisd(theta, N);\n}\n\n\n\n} // namespace hubo\n\n#endif // HUBO_UTILS_HPP\n", "meta": {"hexsha": "260a9df6b92de62c25800c648341926244136db6", "size": 4674, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "hubo/utils.hpp", "max_stars_repo_name": "mxgrey/protoHuboGUI", "max_stars_repo_head_hexsha": "3384c5e40c544bd472199da9cd6e90e28321a77f", "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": "hubo/utils.hpp", "max_issues_repo_name": "mxgrey/protoHuboGUI", "max_issues_repo_head_hexsha": "3384c5e40c544bd472199da9cd6e90e28321a77f", "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": "hubo/utils.hpp", "max_forks_repo_name": "mxgrey/protoHuboGUI", "max_forks_repo_head_hexsha": "3384c5e40c544bd472199da9cd6e90e28321a77f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6748466258, "max_line_length": 80, "alphanum_fraction": 0.5761660248, "num_tokens": 1163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.28202905051303323}}
{"text": "// TRENTO: Reduced Thickness Event-by-event Nuclear Topology\n// Copyright 2015 Jonah E. Bernhard, J. Scott Moreland\n// MIT License\n\n#include \"nucleon.h\"\n\n#include <cmath>\n#include <limits>\n#include <random>\n#include <stdexcept>\n\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/expint.hpp>\n#include <boost/math/tools/roots.hpp>\n#include <boost/program_options/variables_map.hpp>\n#include <boost/math/special_functions/erf.hpp>\n#include <boost/filesystem.hpp>\n\n\n#include \"fwd_decl.h\"\n\nnamespace trento {\n\nnamespace {\n\n// These constants define distances in terms of the width of the nucleon profile\n// Gaussian thickness function.\n\n// Truncation radius of the thickness function.\nconstexpr double max_radius_widths = 5.;\n\n// Maximum impact parameter for participation.\nconstexpr double max_impact_widths = 6.;\n// Create ctor parameters for unit mean std::gamma_distribution.\n//   mean = alpha*beta == 1  ->  beta = 1/alpha\n// Used below in NucleonProfile ctor initializer list.\n\ntemplate <typename RealType> using param_type =\n  typename std::gamma_distribution<RealType>::param_type;\n\ntemplate <typename RealType>\nparam_type<RealType> gamma_param_unit_mean(RealType alpha = 1.) {\n  return param_type<RealType>{alpha, 1./alpha};\n}\n\n// Return appropriate path to temporary file directory.\n// Used to store cross section parameter \\sigma_partonic.\nfs::path get_data_home() {\n  const auto data_path = std::getenv(\"XDG_DATA_HOME\");\n  if(data_path == nullptr)\n    return fs::path{std::getenv(\"HOME\")} / \".local/share\";\n  return data_path;\n}\n\n// Test approximate cross section parameter equality.\nbool almost_equal(double a, double b) {\n  return fabs(a - b) < 1e-6;\n}\n\n// Calculate constituent position sampling width from CL arguments\ndouble calc_sampling_width(const VarMap& var_map) {\n  auto nucleon_width = var_map[\"nucleon-width\"].as<double>();\n  auto constituent_width = var_map[\"constit-width\"].as<double>();\n  auto constituent_number = var_map[\"constit-number\"].as<int>();\n\n  auto one_constituent = (constituent_number == 1);\n  auto same_size = (nucleon_width - constituent_width < 1e-6);\n\n  if (one_constituent || same_size)\n    return 0.0;\n  else {\n    auto num = sqr(nucleon_width) - sqr(constituent_width);\n    auto denom = 1. - 1./constituent_number;\n    return std::sqrt(num / denom);\n  }\n}\n\n// Determine cross section parameter for sampling nucleon participants.\n// This semi-analytic method is only valid for one constituent.\ndouble analytic_partonic_cross_section(const VarMap& var_map) {\n  // Read parameters from the configuration.\n  auto sigma_nn = var_map[\"cross-section\"].as<double>();\n  auto width = var_map[\"nucleon-width\"].as<double>();\n\n  // TODO: automatically set from beam energy\n  // if (sigma_nn < 0.) {\n  //   auto sqrt_s = var_map[\"beam-energy\"].as<double>();\n  // }\n\n  // Initialize arguments for boost root finding function.\n\n  // Bracket min and max.\n  auto a = -10.;\n  auto b = 20.;\n\n  // Tolerance function.\n  // Require 3/4 of double precision.\n  math::tools::eps_tolerance<double> tol{\n    (std::numeric_limits<double>::digits * 3) / 4};\n\n  // Maximum iterations.\n  // This is overkill -- in testing only 10-20 iterations were required\n  // (but no harm in overestimating).\n  boost::uintmax_t max_iter = 1000;\n\n  // The right-hand side of the equation.\n  auto rhs = sigma_nn / (4 * math::double_constants::pi * sqr(width));\n\n  // This quantity appears a couple times in the equation.\n  auto c = sqr(max_impact_widths) / 4;\n\n  try {\n    auto result = math::tools::toms748_solve(\n      [&rhs, &c](double x) {\n        using std::exp;\n        using math::expint;\n        return c - expint(-exp(x)) + expint(-exp(x-c)) - rhs;\n      },\n      a, b, tol, max_iter);\n\n    auto cross_section_param = .5*(result.first + result.second);\n    return std::exp(cross_section_param) * 4 * math::double_constants::pi * sqr(width);\n  }\n  catch (const std::domain_error&) {\n    // Root finding fails for very small nucleon widths, w^2/sigma_nn < ~0.01.\n    throw std::domain_error{\n      \"unable to fit cross section -- nucleon width too small?\"};\n  }\n}\n\n// Determine cross section parameter for sampling nucleon participants.\n// This Monte Carlo numeric method is used for more than one constituent.\ndouble numeric_partonic_cross_section(const VarMap& var_map) {\n  MonteCarloCrossSection mc_cross_section(var_map);\n  auto sigma_nn = var_map[\"cross-section\"].as<double>();\n  auto width = var_map[\"constit-width\"].as<double>();\n\n  // Bracket min and max.\n  auto a = -10.;\n  auto b = 20.;\n\n  // Tolerance function.\n  math::tools::eps_tolerance<double> tol{8};\n\n  // Maximum iterations.\n  boost::uintmax_t max_iter = 20;\n\n  // Dimensional constant [fm^-1] used to rescale sigma_partonic\n  auto c = 4 * math::double_constants::pi * sqr(width);\n\n  try {\n    auto result = math::tools::toms748_solve(\n      [&sigma_nn, &mc_cross_section, &c](double cross_section_param) {\n        auto x = std::exp(cross_section_param) * c;\n        return mc_cross_section(x) - sigma_nn;\n      },\n      a, b, tol, max_iter);\n\n    auto cross_section_param = .5*(result.first + result.second);\n    return std::exp(cross_section_param) * c;\n  }\n  catch (const std::domain_error&) {\n    // Root finding fails for very small nucleon widths, w^2/sigma_nn < ~0.01.\n    throw std::domain_error{\n      \"unable to fit cross section -- nucleon and/or constituent width too small?\"};\n  }\n}\n\n// Determine the cross section parameter given the nucleon_width,\n// constituent_width, constituent number, and inelastic cross section.\ndouble partonic_cross_section(const VarMap& var_map) {\n  // Read parameters from the configuration.\n  auto nucleon_width = var_map[\"nucleon-width\"].as<double>();\n  auto constituent_width = var_map[\"constit-width\"].as<double>();\n  auto constituent_number = var_map[\"constit-number\"].as<int>();\n  auto sigma_nn = var_map[\"cross-section\"].as<double>();\n\n  // Cross section parameters\n  double nucleon_width_;\n  double constituent_width_;\n  int constituent_number_;\n  double sigma_nn_;\n  double sigma_partonic;\n\n  // Establish trento cache path\n  auto cache_dir = get_data_home() / \"trento\";\n  auto cache_path = cache_dir / \"cross_section.dat\";\n  fs::create_directory(cache_dir);\n\n  // Check if cache exists\n  if (fs::exists(cache_path.string())){\n\n    // Open cache read only\n    std::fstream cache_read(cache_path.string(), std::ios_base::in);\n\n    // Check cache for previously tabulated cross section parameters\n    while(!cache_read.eof()) {\n      cache_read >> constituent_number_ >> nucleon_width_ >>\n        constituent_width_ >> sigma_nn_ >> sigma_partonic;\n      if (almost_equal(nucleon_width, nucleon_width_) &&\n          almost_equal(constituent_width, constituent_width_) &&\n          almost_equal(sigma_nn, sigma_nn_) &&\n          (constituent_number == constituent_number_)) {\n        return sigma_partonic;\n      }\n    }\n\n    // Close read-only file stream\n    cache_read.close();\n  }\n\n  // Open cache with write access\n  std::fstream cache_write(cache_path.string(),\n      std::ios_base::out | std::ios_base::app);\n\n  // Use numeric method to determine sigma_partonic if there is nucleon\n  // substructure, otherwise use semi-analytic method.\n  if (constituent_number > 1)\n    sigma_partonic = numeric_partonic_cross_section(var_map);\n  else\n    sigma_partonic = analytic_partonic_cross_section(var_map);\n\n  // Save new cross section parameters to cache\n  using std::fixed;\n  using std::setprecision;\n  using std::setw;\n  using std::scientific;\n  using std::endl;\n\n  cache_write << setprecision(6)\n              << std::left << setw(4) << fixed << constituent_number\n              << std::right << setw(10) << fixed << nucleon_width\n              << std::right << setw(10) << fixed << constituent_width\n              << std::right << setw(10) << fixed << sigma_nn\n              << std::right << setw(14) << scientific << sigma_partonic\n              << endl;\n\n  return sigma_partonic;\n}\n\n}  // unnamed namespace\n\nNucleonCommon::NucleonCommon(const VarMap& var_map)\n    : fast_exp_(-.5*sqr(max_radius_widths), 0., 1000),\n      nucleon_width_(var_map[\"nucleon-width\"].as<double>()),\n      constituent_width_(var_map[\"constit-width\"].as<double>()),\n      constituent_number_(std::size_t(var_map[\"constit-number\"].as<int>())),\n      sampling_width_(calc_sampling_width(var_map)),\n      max_impact_sq_(sqr(max_impact_widths*nucleon_width_)),\n      constituent_width_sq_(sqr(constituent_width_)),\n      constituent_radius_sq_(sqr(max_radius_widths*constituent_width_)),\n      sigma_partonic_(partonic_cross_section(var_map)),\n      prefactor_(math::double_constants::one_div_two_pi/constituent_width_sq_/constituent_number_),\n      calc_ncoll_(var_map[\"ncoll\"].as<bool>()),\n      participant_fluctuation_dist_(gamma_param_unit_mean(var_map[\"fluctuation\"].as<double>())),\n      constituent_position_dist_(0, sampling_width_)\n{}\n\nMonteCarloCrossSection::MonteCarloCrossSection(const VarMap& var_map)\n  : nucleon_width_(var_map[\"nucleon-width\"].as<double>()),\n    constituent_width_(var_map[\"constit-width\"].as<double>()),\n    constituent_number_(std::size_t(var_map[\"constit-number\"].as<int>())),\n    sampling_width_(calc_sampling_width(var_map)),\n    max_impact_(max_impact_widths*nucleon_width_),\n    constituent_width_sq_(sqr(constituent_width_)),\n    prefactor_(math::double_constants::one_div_two_pi/constituent_width_sq_/constituent_number_)\n{}\n\ndouble MonteCarloCrossSection::operator() (const double sigma_partonic) const {\n\n  random::CyclicNormal<> cyclic_normal{\n    0., sampling_width_, cache_size, n_loops\n  };\n\n  struct Constituent {\n    double x, y;\n  };\n\n  std::vector<Constituent> nucleonA(constituent_number_);\n  std::vector<Constituent> nucleonB(constituent_number_);\n\n  auto max_impact_sq_ = sqr(max_impact_);\n  double ref_cross_section = 0.;\n  double prob_miss = 0.;\n  int pass_tolerance = 0;\n\n  for (std::size_t n = 0; n < n_max; ++n) {\n    // Sample b from P(b)db = 2*pi*b.\n    auto b = max_impact_ * std::sqrt(random::canonical<double>());\n\n    for (auto&& q : nucleonA) {\n      q.x = cyclic_normal(random::engine);\n      q.y = cyclic_normal(random::engine);\n    }\n\n    for (auto&& q : nucleonB) {\n      q.x = cyclic_normal(random::engine);\n      q.y = cyclic_normal(random::engine);\n    }\n\n    auto overlap = 0.;\n    for (auto&& qA : nucleonA) {\n      for (auto&& qB : nucleonB) {\n        auto distance_sq = sqr(qA.x - qB.x + b) + sqr(qA.y - qB.y);\n        overlap += std::exp(-.25*distance_sq/constituent_width_sq_);\n      }\n    }\n\n    prob_miss +=\n      std::exp(-sigma_partonic * prefactor_/(2.*constituent_number_) * overlap);\n\n    auto prob_hit = 1. - (prob_miss/n);\n    auto cross_section = M_PI*max_impact_sq_*prob_hit;\n\n    auto update_difference = std::abs(cross_section - ref_cross_section);\n\n    if (update_difference < tolerance) {\n      ++pass_tolerance;\n    } else {\n      pass_tolerance = 0;\n      ref_cross_section = cross_section;\n    }\n\n    if (pass_tolerance > n_pass){\n      return cross_section;\n    }\n  }\n\n  throw std::out_of_range{\n    \"Partonic cross section failed to converge \\\n      -- check nucleon width, constituent width, and constituent number\"};\n}\n\n}  // namespace trento\n", "meta": {"hexsha": "08577d9e5e32104c22682d89f2bedd4527adbeb5", "size": 11255, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/nucleon.cxx", "max_stars_repo_name": "morelandjs/trento-partons", "max_stars_repo_head_hexsha": "03732e1761f11dfe7fd5184f2acf0ebf17848c83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/nucleon.cxx", "max_issues_repo_name": "morelandjs/trento-partons", "max_issues_repo_head_hexsha": "03732e1761f11dfe7fd5184f2acf0ebf17848c83", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nucleon.cxx", "max_forks_repo_name": "morelandjs/trento-partons", "max_forks_repo_head_hexsha": "03732e1761f11dfe7fd5184f2acf0ebf17848c83", "max_forks_repo_licenses": ["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.1029411765, "max_line_length": 99, "alphanum_fraction": 0.6960462017, "num_tokens": 2868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.2820012819764954}}
{"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_ADAMAX_HPP\n#define NETKET_ADAMAX_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <cassert>\n#include <cmath>\n#include <complex>\n#include <iostream>\n#include \"abstract_optimizer.hpp\"\n\nnamespace netket {\n\nclass AdaMax : public AbstractOptimizer {\n  int npar_;\n\n  double alpha_;\n  double beta1_;\n  double beta2_;\n\n  Eigen::VectorXd ut_;\n  Eigen::VectorXd mt_;\n\n  double niter_;\n  double niter_reset_;\n\n  double epscut_;\n\n  const Complex I_;\n\n public:\n  explicit AdaMax(double alpha = 0.001, double beta1 = 0.9,\n                  double beta2 = 0.999, double epscut = 1.0e-7)\n      : alpha_(alpha), beta1_(beta1), beta2_(beta2), epscut_(epscut), I_(0, 1) {\n    npar_ = -1;\n    niter_ = 0;\n    niter_reset_ = -1;\n\n    PrintParameters();\n  }\n\n  // TODO remove\n  // Json constructor\n  explicit AdaMax(const json &pars) : I_(0, 1) {\n    npar_ = -1;\n    niter_ = 0;\n    niter_reset_ = -1;\n\n    from_json(pars);\n    PrintParameters();\n  }\n\n  void PrintParameters() {\n    InfoMessage() << \"Adamax optimizer initialized with these parameters :\"\n                  << std::endl;\n    InfoMessage() << \"Alpha = \" << alpha_ << std::endl;\n    InfoMessage() << \"Beta1 = \" << beta1_ << std::endl;\n    InfoMessage() << \"Beta2 = \" << beta2_ << std::endl;\n    InfoMessage() << \"Epscut = \" << epscut_ << std::endl;\n  }\n\n  void Init(const Eigen::VectorXd &pars) override {\n    npar_ = pars.size();\n    ut_.setZero(npar_);\n    mt_.setZero(npar_);\n\n    niter_ = 0;\n  }\n\n  void Init(const Eigen::VectorXcd &pars) override {\n    npar_ = 2 * pars.size();\n    ut_.setZero(npar_);\n    mt_.setZero(npar_);\n\n    niter_ = 0;\n  }\n\n  void Update(const Eigen::VectorXd &grad, Eigen::VectorXd &pars) override {\n    assert(npar_ > 0);\n\n    mt_ = beta1_ * mt_ + (1. - beta1_) * grad;\n\n    for (int i = 0; i < npar_; i++) {\n      ut_(i) = std::max(std::max(std::abs(grad(i)), beta2_ * ut_(i)), epscut_);\n    }\n    niter_ += 1.;\n    if (niter_reset_ > 0) {\n      if (niter_ > niter_reset_) {\n        niter_ = 1;\n      }\n    }\n\n    double eta = alpha_ / (1. - std::pow(beta1_, niter_));\n    for (int i = 0; i < npar_; i++) {\n      pars(i) -= eta * mt_(i) / ut_(i);\n    }\n  }\n\n  void Update(const Eigen::VectorXcd &grad, Eigen::VectorXd &pars) override {\n    Update(Eigen::VectorXd(grad.real()), pars);\n  }\n\n  void Update(const Eigen::VectorXcd &grad, Eigen::VectorXcd &pars) override {\n    assert(npar_ == 2 * pars.size());\n\n    for (int i = 0; i < pars.size(); i++) {\n      mt_(2 * i) = beta1_ * mt_(2 * i) + (1. - beta1_) * grad(i).real();\n      mt_(2 * i + 1) = beta1_ * mt_(2 * i + 1) + (1. - beta1_) * grad(i).imag();\n    }\n\n    for (int i = 0; i < pars.size(); i++) {\n      ut_(2 * i) = std::max(\n          std::max(std::abs(grad(i).real()), beta2_ * ut_(2 * i)), epscut_);\n      ut_(2 * i + 1) = std::max(\n          std::max(std::abs(grad(i).imag()), beta2_ * ut_(2 * i + 1)), epscut_);\n    }\n\n    niter_ += 1.;\n    if (niter_reset_ > 0) {\n      if (niter_ > niter_reset_) {\n        niter_ = 1;\n      }\n    }\n\n    double eta = alpha_ / (1. - std::pow(beta1_, niter_));\n    for (int i = 0; i < pars.size(); i++) {\n      pars(i) -= eta * mt_(2 * i) / ut_(2 * i);\n      pars(i) -= eta * I_ * mt_(2 * i + 1) / ut_(2 * i + 1);\n    }\n  }\n\n  void Reset() override {\n    ut_ = Eigen::VectorXd::Zero(npar_);\n    mt_ = Eigen::VectorXd::Zero(npar_);\n    niter_ = 0;\n  }\n\n  void SetResetEvery(double niter_reset) { niter_reset_ = niter_reset; }\n\n  void from_json(const json &pars) {\n    // DEPRECATED (to remove for v2.0.0)\n    std::string section = \"Optimizer\";\n    if (!FieldExists(pars, section)) {\n      section = \"Learning\";\n    }\n\n    alpha_ = FieldOrDefaultVal(pars[section], \"Alpha\", 0.001);\n    beta1_ = FieldOrDefaultVal(pars[section], \"Beta1\", 0.9);\n    beta2_ = FieldOrDefaultVal(pars[section], \"Beta2\", 0.999);\n    epscut_ = FieldOrDefaultVal(pars[section], \"Epscut\", 1.0e-7);\n  }\n};\n\n}  // namespace netket\n\n#endif\n", "meta": {"hexsha": "601b2f4fda9c91f57caa9e226f57a94c04a3c847", "size": 4532, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NetKet/Optimizer/ada_max.hpp", "max_stars_repo_name": "flatironinstitute/netket", "max_stars_repo_head_hexsha": "888a4b56b6242d62b45d32eda43e10066c65fdf9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T19:00:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T01:03:15.000Z", "max_issues_repo_path": "NetKet/Optimizer/ada_max.hpp", "max_issues_repo_name": "flatironinstitute/netket", "max_issues_repo_head_hexsha": "888a4b56b6242d62b45d32eda43e10066c65fdf9", "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/Optimizer/ada_max.hpp", "max_forks_repo_name": "flatironinstitute/netket", "max_forks_repo_head_hexsha": "888a4b56b6242d62b45d32eda43e10066c65fdf9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-23T01:04:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T01:04:00.000Z", "avg_line_length": 26.5029239766, "max_line_length": 80, "alphanum_fraction": 0.592674316, "num_tokens": 1425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.28198139768053615}}
{"text": "#include \"drake/solvers/unrevised_lemke_solver.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <functional>\n#include <iostream>\n#include <limits>\n#include <memory>\n#include <sstream>\n#include <stdexcept>\n#include <utility>\n#include <vector>\n\n#include <Eigen/LU>\n\n#include \"drake/common/autodiff.h\"\n#include \"drake/common/default_scalars.h\"\n#include \"drake/common/drake_assert.h\"\n#include \"drake/common/never_destroyed.h\"\n#include \"drake/common/text_logging.h\"\n#include \"drake/common/unused.h\"\n\nusing drake::log;\n\nnamespace drake {\nnamespace solvers {\n\nnamespace {\n\n// A linear system solver that accommodates the inability of the LU\n// factorization to be AutoDiff'd (true in Eigen 3, at least). For double types,\n// the faster LU factorization and solve is used. For other types, QR\n// factorization and solve is used.\ntemplate <class T>\nclass LinearSolver {\n public:\n  explicit LinearSolver(const MatrixX<T>& m);\n\n  VectorX<T> Solve(const VectorX<T>& v) const;\n\n private:\n  Eigen::ColPivHouseholderQR<MatrixX<T>> qr_;\n  Eigen::PartialPivLU<MatrixX<double>> lu_;\n};\n\ntemplate <class T>\nLinearSolver<T>::LinearSolver(const MatrixX<T>& M) {\n  if (M.rows() > 0)\n    qr_ = Eigen::ColPivHouseholderQR<MatrixX<T>>(M);\n}\n\ntemplate <>\nLinearSolver<double>::LinearSolver(\n    const MatrixX<double>& M) {\n  if (M.rows() > 0)\n    lu_ = Eigen::PartialPivLU<MatrixX<double>>(M);\n}\n\ntemplate <class T>\nVectorX<T> LinearSolver<T>::Solve(\n    const VectorX<T>& v) const {\n  if (v.rows() == 0) {\n    DRAKE_DEMAND(qr_.rows() == 0);\n    return VectorX<T>(0);\n  }\n  return qr_.solve(v);\n}\n\ntemplate <>\nVectorX<double> LinearSolver<double>::Solve(\n    const VectorX<double>& v) const {\n  if (v.rows() == 0) {\n    DRAKE_DEMAND(lu_.rows() == 0);\n    return VectorX<double>(0);\n  }\n  return lu_.solve(v);\n}\n}  // anonymous namespace\n\ntemplate <>\nvoid UnrevisedLemkeSolver<AutoDiffXd>::DoSolve(\n    const MathematicalProgram&, const Eigen::VectorXd&,\n    const SolverOptions&, MathematicalProgramResult*) const {\n  throw std::logic_error(\n      \"UnrevisedLemkeSolver cannot yet be used in a \"\n      \"MathematicalProgram while templatized as an AutoDiff\");\n}\n\ntemplate <typename T>\nvoid UnrevisedLemkeSolver<T>::DoSolve(\n    const MathematicalProgram& prog,\n    const Eigen::VectorXd& initial_guess,\n    const SolverOptions& merged_options,\n    MathematicalProgramResult* result) const {\n  if (!prog.GetVariableScaling().empty()) {\n    static const logging::Warn log_once(\n      \"UnrevisedLemkeSolver doesn't support the feature of variable scaling.\");\n  }\n\n  unused(initial_guess);\n  unused(merged_options);\n\n  // Solve each individual LCP, writing the result back to the decision\n  // variables through the binding and returning true iff all LCPs are\n  // feasible.\n  //\n  // If any is infeasible, returns false and does not alter the decision\n  // variables.\n\n  // Create a dummy variable for the number of pivots used.\n  int num_pivots = 0;\n  const auto& bindings = prog.linear_complementarity_constraints();\n  Eigen::VectorXd x_sol(prog.num_vars());\n  for (const auto& binding : bindings) {\n    Eigen::VectorXd constraint_solution(binding.GetNumElements());\n    const std::shared_ptr<LinearComplementarityConstraint> constraint =\n        binding.evaluator();\n    bool solved = SolveLcpLemke(\n        constraint->M(), constraint->q(), &constraint_solution, &num_pivots);\n    if (!solved) {\n      result->set_solution_result(SolutionResult::kUnknownError);\n      return;\n    }\n    for (int i = 0; i < binding.evaluator()->num_vars(); ++i) {\n      const int variable_index =\n          prog.FindDecisionVariableIndex(binding.variables()(i));\n      x_sol(variable_index) = constraint_solution(i);\n    }\n  }\n  result->set_optimal_cost(0.0);\n  result->set_x_val(x_sol);\n  result->set_solution_result(SolutionResult::kSolutionFound);\n}\n\n// Utility function for copying an r-dimensional column vector v (designated by\n// the indices in row_indices and col_index) from a matrix M to a target\n// vector, `out`. Let M be the matrix `in` augmented with a single column of\n// ones (i.e., the \"covering vector\"); put another way, M = | in 1 |, where \"in\"\n// refers the n × m-dimensional matrix `in` and 1 is a column of ones (so M is\n// n × (m+1)-dimensional). Let R be a r × n \"row selection\" matrix, constructed\n// using `row_indices`. R is constructed using r = `row_indices.size()` as\n// follows:\n//\n// Rᵢⱼ = { 1  if j = row_indices[i], ∀i ∈ 0..r-1, ∀j ∈ 0..n-1\n//       { 0  otherwise\n//\n// Consider the following example with `in` set to the 3 × 3 identity matrix,\n// `row_indices = { 2, 0}` and `col_index = 1`. This would make:\n// R =  | 0 0 1 |      and R⋅M = | 0 0 1 1 |\n//      | 1 0 0 |                | 1 0 0 1 |\n//\n// The second column (`col_index = 1`) of R⋅M is v = | 0 |\n//                                                   | 0 |\n//\n// `row_indices` need not be in sorted order, and `out` need not be properly\n// sized on entry (it will be resized as necessary). However, this method aborts\n// if any element of `row_indices` is out of range, `col_index` is out of range,\n// *or* if there are any duplicated elements in `row_indices`.\ntemplate <class T>\nvoid UnrevisedLemkeSolver<T>::SelectSubColumnWithCovering(\n    const MatrixX<T>& in,\n    const std::vector<int>& row_indices,\n    int col_index, VectorX<T>* out) {\n  DRAKE_ASSERT(ValidateIndices(row_indices, in.rows()));\n\n  const int num_rows = row_indices.size();\n  out->resize(num_rows);\n\n  // Look for the covering vector first.\n  if (col_index == in.cols()) {\n    out->setOnes();\n    return;\n  }\n\n  DRAKE_DEMAND(0 <= col_index && col_index < in.cols());\n  const auto in_column = in.col(col_index);\n  for (int i = 0; i < num_rows; i++) {\n    DRAKE_ASSERT(row_indices[i] < in_column.size());\n    (*out)[i] = in_column[row_indices[i]];\n  }\n}\n\n// Utility function for copying an r-dimensional column vector v (designated by\n// the indices in `row_indices`) from n-dimensional vector `in` to a target\n// vector, `out`. Let R be a r × n \"row selection\" matrix, constructed using\n// r = `row_indices.size()` as follows:\n//\n// Rᵢⱼ = { 1  if j = row_indices[i], ∀i ∈ 0..r-1, ∀j ∈ 0..n-1\n//       { 0  otherwise\n//\n// Consider the following example with `in` set to the vector [ 1 2 3 ]ᵀ,\n// and `row_indices = { 2, 0}`. This would make:\n// R =  | 0 0 1 |      and v = R⋅`in` = | 3 |\n//      | 1 0 0 |                       | 1 |\n//\n// `row_indices` need not be in sorted order, and `out` need not be properly\n// sized on entry (it will be resized as necessary). However, this method aborts\n// if any element of `row_indices` is out of range  *or* if there are any\n// duplicated elements in `row_indices`.\ntemplate <class T>\nvoid UnrevisedLemkeSolver<T>::SelectSubVector(const VectorX<T>& in,\n    const std::vector<int>& row_indices, VectorX<T>* out) {\n  DRAKE_ASSERT(ValidateIndices(row_indices, in.size()));\n\n  const int num_rows = row_indices.size();\n  out->resize(num_rows);\n  for (int i = 0; i < num_rows; i++) {\n    DRAKE_ASSERT(row_indices[i] < in.rows());\n    (*out)(i) = in(row_indices[i]);\n  }\n}\n\n// Utility function for copying an r-dimensional column vector v (designated by\n// the indices in `row_indices`) into n-dimensional vector `out`. Let R be the\n// r × n \"row selection\" matrix defined in the documentation of\n// SelectSubVector(). Then, the result of the operation is:\n// `out` = `out` + Rᵀ⋅(`v` - R⋅`out`)\n//\n// Consider the following example with `v` set to the vector [ 3 1 ]ᵀ,\n// `row_indices = { 2, 0}`, and `out` set to the vector [ 4 5 6 ]. This would\n// make:\n// R =  | 0 0 1 |      and `out` + Rᵀ⋅(`v` - R⋅`out`) = | 1 |\n//      | 1 0 0 |                                       | 5 |\n//                                                      | 3 |\n//\n// `row_indices` need not be in sorted order. This method aborts if any element\n// of `row_indices` is out of the range of `out`, if `row_indices` is not the\n// same size as `v`, or if there are any duplicated elements in `row_indices`.\ntemplate <class T>\nvoid UnrevisedLemkeSolver<T>::SetSubVector(const VectorX<T>& v,\n    const std::vector<int>& row_indices, VectorX<T>* out) {\n  DRAKE_DEMAND(row_indices.size() == static_cast<size_t>(v.size()));\n  DRAKE_ASSERT(ValidateIndices(row_indices, out->size()));\n  for (size_t i = 0; i < row_indices.size(); ++i)\n    (*out)[row_indices[i]] = v[i];\n}\n\n// Function for checking whether a set of indices that specify a view into\n// a vector is valid. Returns `true` if row_indices are unique and each element\n// lies in [0, vector_size-1] and `false` otherwise.\ntemplate <class T>\nbool UnrevisedLemkeSolver<T>::ValidateIndices(\n    const std::vector<int>& row_indices, int vector_size) {\n  // Don't check anything for empty vectors.\n  if (row_indices.empty())\n    return true;\n\n  // Sort the vector first.\n  std::vector<int> sorted_row_indices = row_indices;\n  std::sort(sorted_row_indices.begin(), sorted_row_indices.end());\n\n  // Validate the maximum and minimum elements.\n  if (sorted_row_indices.back() >= vector_size)\n    return false;\n  if (sorted_row_indices.front() < 0)\n    return false;\n\n  // Make sure that the vector is unique.\n  return std::unique(sorted_row_indices.begin(), sorted_row_indices.end()) ==\n         sorted_row_indices.end();\n}\n\n// Function for checking whether a set of indices that specify a view into\n// a matrix is valid. Returns `true` if each element of row_indices is unique\n// lies in [0, num_rows-1] and if each element of col_indices is unique and\n// lies in [0, num_cols-1]. Returns `false` otherwise.\ntemplate <class T>\nbool UnrevisedLemkeSolver<T>::ValidateIndices(\n    const std::vector<int>& row_indices,\n    const std::vector<int>& col_indices, int num_rows, int num_cols) {\n  return ValidateIndices(row_indices, num_rows) &&\n         ValidateIndices(col_indices, num_cols);\n}\n\n// Utility function for copying an r × c dimensional submatrix S (designated by\n// the indices in row_indices and col_indices) from a matrix M to a target\n// matrix, `out`. Let M be the matrix `in` augmented with a single column of\n// ones (i.e., the \"covering vector\"); put another way, M = | in 1 |, where \"in\"\n// refers the n × m-dimensional matrix `in` and 1 is a column of ones (so M is\n// n × (m+1)-dimensional). Let R be a r × n \"row selection\" matrix, constructed\n// using `row_indices` and C be a (m+1) × c-dimensional \"column selection\"\n// matrix constructed using `col_indices`. R and C are constructed using\n// r = `row_indices.size()` and c = `col_indices.size()` as follows:\n//\n// Rᵢⱼ = { 1  if j = row_indices[i], ∀i ∈ 0..r-1, ∀j ∈ 0..n-1\n//       { 0  otherwise\n// Cᵢⱼ = { 1  if col_indices[j] = i, ∀i ∈ 0..m, ∀j ∈ 0..c-1\n//       { 0  otherwise\n//\n// Consider the following example with `in` set to the 3 × 3 identity matrix,\n// `row_indices = { 2, 1, 0}` and `col_indices = { 1, 2, 3 }`. This would make:\n// R =  | 0 0 1 |      C = | 0 0 0 |   and  R⋅M⋅C = | 0 1 1 |\n//      | 0 1 0 |          | 1 0 0 |                | 1 0 1 |\n//      | 1 0 0 |          | 0 1 0 |                | 0 0 1 |\n//                         | 0 0 1 |\n// `row_indices` and `col_indices` need not be in sorted order, and `out` need\n// not be properly sized on entry (it will be resized as necessary). However,\n// this method aborts if any element of `row_indices` or `col_indices` is out\n// of range *or* if there are any duplicated elements.\ntemplate <class T>\nvoid UnrevisedLemkeSolver<T>::SelectSubMatrixWithCovering(\n    const MatrixX<T>& in,\n    const std::vector<int>& row_indices,\n    const std::vector<int>& col_indices, MatrixX<T>* out) {\n  const int num_rows = row_indices.size();\n  const int num_cols = col_indices.size();\n  DRAKE_ASSERT(\n      ValidateIndices(row_indices, col_indices, in.rows(), in.cols() + 1));\n  out->resize(num_rows, num_cols);\n\n  for (int i = 0; i < num_rows; i++) {\n    const auto row_in = in.row(row_indices[i]);\n\n    // `row_out` is a \"view\" into `out`: any modifications to row_out are\n    // reflected in `out`.\n    auto row_out = out->row(i);\n    for (int j = 0; j < num_cols; j++) {\n      if (col_indices[j] < in.cols()) {\n        DRAKE_ASSERT(col_indices[j] >= 0);\n        row_out(j) = row_in(col_indices[j]);\n      } else {\n        DRAKE_ASSERT(col_indices[j] == in.cols());\n        row_out(j) = 1.0;\n      }\n    }\n  }\n}\n\n// Determines the various index sets defined in Section 1.1 of [Dai 2018].\ntemplate <class T>\nvoid UnrevisedLemkeSolver<T>::DetermineIndexSets() const {\n  // Helper for determining index sets.\n  auto DetermineIndexSetsHelper = [this](\n      const std::vector<LCPVariable>& variables, bool is_z,\n      std::vector<int>* variable_set,\n      std::vector<int>* variable_set_prime) {\n    variable_and_array_indices_.clear();\n    for (int i = 0; i < static_cast<int>(variables.size()); ++i) {\n      if (variables[i].is_z() == is_z)\n        variable_and_array_indices_.emplace_back(variables[i].index(), i);\n    }\n    std::sort(variable_and_array_indices_.begin(),\n              variable_and_array_indices_.end());\n\n    // Construct the set and the primed set.\n    for (const auto& variable_and_array_index_pair :\n        variable_and_array_indices_) {\n      variable_set->push_back(variable_and_array_index_pair.first);\n      variable_set_prime->push_back(variable_and_array_index_pair.second);\n    }\n  };\n\n  // Clear all sets.\n  index_sets_.alpha.clear();\n  index_sets_.alpha_bar.clear();\n  index_sets_.alpha_prime.clear();\n  index_sets_.alpha_bar_prime.clear();\n  index_sets_.beta.clear();\n  index_sets_.beta_bar.clear();\n  index_sets_.beta_prime.clear();\n  index_sets_.beta_bar_prime.clear();\n\n  DetermineIndexSetsHelper(indep_variables_, false,\n      &index_sets_.alpha, &index_sets_.alpha_prime);\n  DetermineIndexSetsHelper(dep_variables_, false,\n      &index_sets_.alpha_bar, &index_sets_.alpha_bar_prime);\n  DetermineIndexSetsHelper(dep_variables_, true,\n                           &index_sets_.beta, &index_sets_.beta_prime);\n  DetermineIndexSetsHelper(indep_variables_, true,\n                           &index_sets_.beta_bar, &index_sets_.beta_bar_prime);\n}\n\n// Verifies that each element of the pivoting set is unique. This is an\n// expensive operation and should only be executed in Debug mode.\ntemplate <class T>\nbool UnrevisedLemkeSolver<T>::IsEachUnique(\n    const std::vector<LCPVariable>& vars) {\n  // Copy the set.\n  std::vector<LCPVariable> vars_copy = vars;\n  std::sort(vars_copy.begin(), vars_copy.end());\n  return (std::unique(vars_copy.begin(), vars_copy.end()) == vars_copy.end());\n}\n\n// Performs the pivoting operation, which is described in [Dai 2018].\n// `M_prime_col` can be null, if the updated column of M' (pivoted version of M)\n// is not needed and the driving_index corresponds to the artificial variable.\ntemplate <typename T>\nbool UnrevisedLemkeSolver<T>::LemkePivot(\n    const MatrixX<T>& M,\n    const VectorX<T>& q,\n    int driving_index,\n    T zero_tol,\n    VectorX<T>* M_prime_col,\n    VectorX<T>* q_prime) const {\n  DRAKE_DEMAND(q_prime);\n\n  const int kArtificial = M.rows();\n  DRAKE_DEMAND(driving_index >= 0 && driving_index <= kArtificial);\n\n  // Verify that each member in the independent and dependent sets is unique.\n  DRAKE_ASSERT(IsEachUnique(indep_variables_));\n  DRAKE_ASSERT(IsEachUnique(dep_variables_));\n\n  // If the driving index does not correspond to the artificial variable,\n  // M_prime_col must be non-null.\n  if (!IsArtificial(indep_variables_[driving_index]))\n    DRAKE_DEMAND(M_prime_col);\n\n  // Determine the sets.\n  DetermineIndexSets();\n\n  // Note: It is feasible to do a low-rank update to the factorization below,\n  // since alpha and beta should change by no more than a single index between\n  // consecutive pivots. Eigen only supports low-rank updates to Cholesky\n  // factorizations at the moment, however.\n\n  // Compute matrix and vector views.\n  SelectSubMatrixWithCovering(M, index_sets_.alpha, index_sets_.beta,\n                              &M_alpha_beta_);\n  SelectSubMatrixWithCovering(M, index_sets_.alpha_bar, index_sets_.beta,\n                  &M_alpha_bar_beta_);\n  SelectSubVector(q, index_sets_.alpha, &q_alpha_);\n  SelectSubVector(q, index_sets_.alpha_bar, &q_alpha_bar_);\n\n  // Equation (2) from [Dai 2018].\n  // Note: this equation, and those below, must be kept up-to-date with\n  // [Dai 2018].\n  LinearSolver<T> fMab(M_alpha_beta_);  // Factorized M_alpha_beta_.\n  q_prime_beta_prime_ = -fMab.Solve(q_alpha_);\n\n  // Check whether the solution is sufficiently close. We need to do this\n  // because partial pivoting LU does not estimate rank (and, from prior\n  // experience in solving LCPs), loss of rank need not lead to errors in\n  // solving the LCP. We assume that if the factorization is good enough to\n  // solve this linear system, it's good enough to solve the subsequent\n  // linear system (below). NOTE: current unit tests do not exercise the\n  // affirmative evaluation of the conditional (meaning that the \"return false\"\n  // never gets called).\n  // @TODO(edrumwri) Institute a unit test that exercises the affirmative\n  //   evaluation branch of the conditional when such a LCP has been\n  //   identified.\n  if ((M_alpha_beta_ * q_prime_beta_prime_ + q_alpha_).norm() > zero_tol)\n    return false;\n\n  // Equation (3) from [Dai 2018].\n  q_prime_alpha_bar_prime_ = M_alpha_bar_beta_ * q_prime_beta_prime_ +\n      q_alpha_bar_;\n\n  // Set the components of q'.\n  SetSubVector(q_prime_beta_prime_, index_sets_.beta_prime, q_prime);\n  SetSubVector(q_prime_alpha_bar_prime_, index_sets_.alpha_bar_prime, q_prime);\n\n  DRAKE_LOGGER_DEBUG(\"q': {}\", q_prime->transpose());\n\n  // If it is not necessary to compute the column of M, quit now.\n  if (!M_prime_col)\n    return true;\n\n  // Examine the driving variable.\n  if (!indep_variables_[driving_index].is_z()) {\n    DRAKE_LOGGER_DEBUG(\"Driving case #1: driving variable from w\");\n    // Case from Section 2.2.1.\n    // Determine gamma by determining the position of the driving variable\n    // in INDEPENDENT W (as defined in [Dai 2018]).\n    const int n = static_cast<int>(indep_variables_.size());\n    int gamma = 0;\n    for (int i = 0; i < n; ++i) {\n      if (!indep_variables_[i].is_z()) {\n        if (indep_variables_[i].index() <\n            indep_variables_[driving_index].index()) {\n          ++gamma;\n        }\n      }\n    }\n\n\n    // From Equation (4) in [Dai 2018].\n    DRAKE_ASSERT(index_sets_.alpha[gamma] ==\n        indep_variables_[driving_index].index());\n\n    // Set the unit vector.\n    e_.setZero(index_sets_.beta.size());\n    e_[gamma] = 1.0;\n\n    // Equation (5).\n    M_prime_driving_beta_prime_ = fMab.Solve(e_);\n\n    // Equation (6).\n    M_prime_driving_alpha_bar_prime_ = M_alpha_bar_beta_ *\n        M_prime_driving_beta_prime_;\n  } else {\n    DRAKE_LOGGER_DEBUG(\"Driving case #2: driving variable from z\");\n\n    // Case from Section 2.2.2 of [Dai 2018].\n    // Determine zeta.\n    const int zeta = indep_variables_[driving_index].index();\n\n    // Compute g_alpha and g_alpha_bar.\n    SelectSubColumnWithCovering(M, index_sets_.alpha, zeta, &g_alpha_);\n    SelectSubColumnWithCovering(M, index_sets_.alpha_bar, zeta, &g_alpha_bar_);\n\n    // Equation (7).\n    M_prime_driving_beta_prime_ = -fMab.Solve(g_alpha_);\n\n    // Equation (8).\n    M_prime_driving_alpha_bar_prime_ = g_alpha_bar_ +\n        M_alpha_bar_beta_ * M_prime_driving_beta_prime_;\n  }\n\n  SetSubVector(M_prime_driving_beta_prime_, index_sets_.beta_prime,\n               M_prime_col);\n  SetSubVector(M_prime_driving_alpha_bar_prime_, index_sets_.alpha_bar_prime,\n               M_prime_col);\n\n  DRAKE_LOGGER_DEBUG(\"M' (driving): {}\", M_prime_col->transpose());\n  return true;\n}\n\n// Checks to see whether a given variable is the artificial variable.\ntemplate <class T>\nbool UnrevisedLemkeSolver<T>::IsArtificial(const LCPVariable& v) const {\n  const int n = static_cast<int>(dep_variables_.size());\n  return v.is_z() && v.index() == n;\n}\n\n// Method for finding the index of the complement of an LCP variable in\n// a tuple (strictly speaking, an unsorted vector) of independent variables.\n// Aborts if the index is not found in the set or the variable is the artificial\n// variable (it never should be).\ntemplate <class T>\nint UnrevisedLemkeSolver<T>::FindComplementIndex(\n    const LCPVariable& query) const {\n  // Verify that the query is not the artificial variable.\n  DRAKE_DEMAND(!IsArtificial(query));\n\n  const auto iter = indep_variables_indices_.find(query.Complement());\n  DRAKE_DEMAND(iter != indep_variables_indices_.end());\n  return iter->second;\n}\n\n// Computes the solution using the current index sets. `z` must simply be\n// non-null; it will be resized as necessary. Returns `true` if able to\n// construct the solution and `false` if unable to find the solution to a\n// necessary system of linear equations. Aborts (in LemkePivot()) if\n// `artificial_index` does not correspond to the index of the artificial\n// variable in the vector of independent_variables.\n// @pre The artificial variable was the blocking variable, indicating that the\n//      solution to the LCP can be obtained after a final pivoting operation.\n// @pre `artificial_index` corresponds to the index of the artificial variable\n//      in the vector of independent variables.\ntemplate <class T>\nbool UnrevisedLemkeSolver<T>::ConstructLemkeSolution(\n    const MatrixX<T>& M,\n    const VectorX<T>& q,\n    int artificial_index,\n    T zero_tol,\n    VectorX<T>* z) const {\n  DRAKE_DEMAND(z);\n  const int n = q.rows();\n\n  // Compute the solution by pivoting the artificial variable, which was just\n  // identified as the blocking variable, from the set of dependent variables\n  // to the set of independent variables.\n  VectorX<T> q_prime(n);\n  if (!LemkePivot(M, q, artificial_index, zero_tol, nullptr, &q_prime))\n    return false;\n\n  z->setZero(n);\n  for (int i = 0; i < static_cast<int>(dep_variables_.size()); ++i) {\n    if (dep_variables_[i].is_z())\n      (*z)[dep_variables_[i].index()] = q_prime[i];\n  }\n  return true;\n}\n\n// Computes the blocking index using the minimum ratio test. Returns `true`\n// if successful, `false` if not (due to, e.g., the driving variable being\n// \"unblocked\" or a cycle being detected). If `false`, `blocking_index` will\n// set to -1 on return.\ntemplate <typename T>\nbool UnrevisedLemkeSolver<T>::FindBlockingIndex(\n    const T& zero_tol, const VectorX<T>& matrix_col, const VectorX<T>& ratios,\n    int* blocking_index) const {\n  DRAKE_DEMAND(blocking_index);\n  DRAKE_DEMAND(ratios.size() == matrix_col.size());\n  DRAKE_DEMAND(zero_tol > 0);\n\n  const int n = matrix_col.size();\n  T min_ratio = std::numeric_limits<double>::infinity();\n  *blocking_index = -1;\n  for (int i = 0; i < n; ++i) {\n    if (matrix_col[i] < -zero_tol) {\n      DRAKE_LOGGER_DEBUG(\"Ratio for index {}: {}\", i, ratios[i]);\n      if (ratios[i] < min_ratio) {\n        min_ratio = ratios[i];\n        *blocking_index = i;\n      }\n    }\n  }\n\n  if (*blocking_index < 0) {\n    DRAKE_LOGGER_DEBUG(\"driving variable is unblocked- algorithm failed\");\n    return false;\n  }\n\n  // Determine all variables within the zero tolerance of the minimum ratio,\n  // while simultaneously looking for the presence of the artificial variable\n  // among the (possible multiple) minima.\n  std::vector<int> blocking_indices;\n  for (int i = 0; i < n; ++i) {\n    if (matrix_col[i] < -zero_tol) {\n      DRAKE_LOGGER_DEBUG(\"Ratio for index {}: {}\", i, ratios[i]);\n      if (ratios[i] < min_ratio + zero_tol) {\n        if (IsArtificial(dep_variables_[i])) {\n          // *Always* select the artificial variable, if multiple choices are\n          // possible ([Cottle 1992] p. 280).\n          *blocking_index = i;\n          return true;\n        }\n        blocking_indices.push_back(i);\n      }\n    }\n  }\n\n  // If there are multiple blocking variables, replace the blocking index with\n  // the cycling selection.\n  if (blocking_indices.size() > 1) {\n    auto& index = selections_[indep_variables_];\n\n    // Verify that we have not run out of indices to select, which means that\n    // cycling would be occurring, in spite of cycling prevention.\n    if (index >= static_cast<int>(blocking_indices.size())) {\n      DRAKE_LOGGER_DEBUG(\"Cycling detected- indicating failure.\");\n      *blocking_index = -1;\n      return false;\n    }\n    *blocking_index = blocking_indices[index];\n    ++index;\n  }\n\n  return true;\n}\n\ntemplate <typename T>\nbool UnrevisedLemkeSolver<T>::IsSolution(\n    const MatrixX<T>& M, const VectorX<T>& q, const VectorX<T>& z,\n    T zero_tol) {\n  using std::abs;\n\n  const T mod_zero_tol = (zero_tol > 0) ? zero_tol : ComputeZeroTolerance(M);\n\n  // Find the minima of z and w.\n  const T min_z = z.minCoeff();\n  const auto w = M * z + q;\n  const T min_w = w.minCoeff();\n\n  // Compute the dot product of z and w.\n  const T dot = w.dot(z);\n  const int n = q.size();\n  return (min_z > -mod_zero_tol && min_w > -mod_zero_tol &&\n          abs(dot) < 10 * n * mod_zero_tol);\n}\n\n// Note: maintainers should read Section 4.4 - 4.4.5 of [Cottle 1992] to\n// understand Lemke's Algorithm (and this function).\ntemplate <typename T>\nbool UnrevisedLemkeSolver<T>::SolveLcpLemke(const MatrixX<T>& M,\n                                     const VectorX<T>& q, VectorX<T>* z,\n                                     int* num_pivots,\n                                     const T& zero_tol) const {\n  using std::max;\n  using std::abs;\n  DRAKE_DEMAND(num_pivots);\n\n  DRAKE_LOGGER_DEBUG(\n      \"UnrevisedLemkeSolver::SolveLcpLemke() entered, M: {}, \"\n      \"q: {}, \", M, q.transpose());\n\n  const int n = q.size();\n  const int max_pivots = 50 * n;  // O(n) pivots expected for solvable problems.\n\n  if (M.rows() != n || M.cols() != n)\n    throw std::logic_error(\"M's dimensions do not match that of q.\");\n\n  // Update the pivots.\n  *num_pivots = 0;\n\n  // Look for immediate exit.\n  if (n == 0) {\n    DRAKE_LOGGER_DEBUG(\"-- LCP is zero dimensional\");\n    z->resize(0);\n    return true;\n  }\n\n  // Denote the index of the artificial variable (i.e., the variable denoted\n  // z₀ in [Cottle 1992], p. 266). Because z₀ is prone to being confused with\n  // the first dimension of z in 0-indexed languages like C++, we refer to the\n  // artificial variable as zₙ in this implementation (it is denoted zₙ₊₁ in\n  // [Dai 2018], as that document uses the 1-indexing prevalent in algorithmic\n  // descriptions).\n  const int kArtificial = n;\n\n  // Compute a sensible value for zero tolerance if none is given.\n  T mod_zero_tol = zero_tol;\n  if (mod_zero_tol <= 0)\n    mod_zero_tol = ComputeZeroTolerance(M);\n\n  // Checks to see whether the trivial solution z = 0 to the LCP w = Mz + q\n  // solves the LCP. This must be the case if q is non-negative, as w would then\n  // be non-negative, z would be non-negative (zero), and w'z = 0.\n  if (q.minCoeff() > -mod_zero_tol) {\n    z->setZero(q.size());\n    DRAKE_LOGGER_DEBUG(\" -- trivial solution found\");\n    DRAKE_LOGGER_DEBUG(\"UnrevisedLemkeSolver::SolveLcpLemke() exited\");\n    return true;\n  }\n\n  // Clear the cycling selections.\n  selections_.clear();\n\n  // If 'n' is identical to the size of the last problem solved, try using the\n  // indices from the last problem solved.\n  if (static_cast<size_t>(n) == dep_variables_.size()) {\n    // Verify that the last call found a solution (indicated by the presence\n    // of the artificial variable (zn) in the independent set).\n    int zn_index = -1;\n    for (int i = 0;\n         i < static_cast<int>(indep_variables_.size()) && zn_index < 0; ++i) {\n      if (IsArtificial(indep_variables_[i]))\n        zn_index = i;\n    }\n\n    if (zn_index >= 0) {\n      // Compute the candidate solution.\n      if (ConstructLemkeSolution(M, q, zn_index, mod_zero_tol, z)) {\n        if (IsSolution(M, q, *z, mod_zero_tol)) {\n          // If z truly is the solution, return now, indicating only one pivot\n          // (in the solution construction) was performed.\n          ++(*num_pivots);\n          return true;\n        }\n      } else {\n        DRAKE_LOGGER_DEBUG(\n            \"Failed to solve linear system implied by last solution\");\n      }\n    }\n  }\n\n  // Set the LCP variables. Start with all z variables independent and all w\n  // variables dependent.\n  indep_variables_.resize(n+1);\n  dep_variables_.resize(n);\n  for (int i = 0; i < n; ++i) {\n    dep_variables_[i] = LCPVariable(false, i);\n    indep_variables_[i] = LCPVariable(true, i);\n  }\n  // z needs one more variable (the artificial variable), whose index we\n  // denote as n to keep it from corresponding to any actual vector index.\n  indep_variables_[n] = LCPVariable(true, n);\n\n  // Compute zn*, the smallest value of the artificial variable zn for which\n  // w = q + zn >= 0. Let blocking denote a component of w that equals\n  // zero when zn = zn*.\n  int blocking_index = -1;\n  bool blocking_index_found = FindBlockingIndex(\n      mod_zero_tol, q, q, &blocking_index);\n  DRAKE_DEMAND(blocking_index_found);\n\n  // Pivot blocking, artificial. Note that we rely upon the dependent variables\n  // being ordered sequentially in both arrays.\n  LCPVariable blocking = dep_variables_[blocking_index];\n  int driving_index = blocking.index();\n  std::swap(dep_variables_[blocking_index], indep_variables_[kArtificial]);\n  DRAKE_LOGGER_DEBUG(\"First blocking variable {}{}\",\n                     ((blocking.is_z()) ? \"z\" : \"w\"), blocking.index());\n  DRAKE_LOGGER_DEBUG(\"First driving variable (artificial)\");\n\n  // Initialize the independent variable indices. We do this after the initial\n  // variable swap for simplicity.\n  for (int i = 0; i < static_cast<int>(indep_variables_.size()); ++i)\n    indep_variables_indices_[indep_variables_[i]] = i;\n\n  // Output the independent and dependent variable tuples.\n  auto to_string = [](const std::vector<LCPVariable>& vars) -> std::string {\n    std::ostringstream oss;\n    for (int i = 0; i < static_cast<int>(vars.size()); ++i)\n      oss << ((vars[i].is_z()) ? \"z\" : \"w\") << vars[i].index() << \" \";\n    return oss.str();\n  };\n  unused(to_string);  // ... when in release mode.\n  DRAKE_LOGGER_DEBUG(\"Independent set variables: {}\",\n      to_string(indep_variables_));\n  DRAKE_LOGGER_DEBUG(\"Dependent set variables: {}\",\n      to_string(dep_variables_));\n\n  // Pivot up to the maximum number of times.\n  VectorX<T> q_prime(n), M_prime_col(n);\n  while (++(*num_pivots) < max_pivots) {\n    DRAKE_LOGGER_DEBUG(\"New driving variable {}{}\",\n                       ((indep_variables_[driving_index].is_z()) ? \"z\" : \"w\"),\n                       indep_variables_[driving_index].index());\n\n    // Compute the permuted q and driving column of the permuted M matrix.\n    if (!LemkePivot(\n        M, q, driving_index, mod_zero_tol, &M_prime_col, &q_prime)) {\n      DRAKE_LOGGER_DEBUG(\"Linear system solve failed.\");\n      z->setZero(n);\n      return false;\n    }\n\n    // Find the blocking variable.\n    if (!FindBlockingIndex(\n        mod_zero_tol, M_prime_col,\n        -(q_prime.array() / M_prime_col.array()).matrix(), &blocking_index)) {\n      z->setZero(n);\n      return false;\n    }\n    blocking = dep_variables_[blocking_index];\n    DRAKE_LOGGER_DEBUG(\"Blocking variable {}{}\",\n                       ((blocking.is_z()) ? \"z\" : \"w\"), blocking.index());\n\n    // See whether the artificial variable blocks the driving variable.\n    if (blocking.index() == kArtificial) {\n      DRAKE_DEMAND(blocking.is_z());\n\n      // Pivot zn with the driving variable.\n      std::swap(dep_variables_[blocking_index],\n                indep_variables_[driving_index]);\n\n      // Compute the permuted q, and convert it into a solution.\n      if (ConstructLemkeSolution(M, q, driving_index, mod_zero_tol, z)) {\n        if (IsSolution(M, q, *z))\n          return true;\n\n        DRAKE_LOGGER_DEBUG(\"Solution not computed to requested tolerance\");\n        z->setZero(n);\n        return false;\n      }\n\n      // Otherwise, indicate failure.\n      DRAKE_LOGGER_DEBUG(\n          \"Linear system solver failed to construct Lemke solution\");\n      z->setZero(n);\n      return false;\n    }\n\n    // Pivot the blocking variable and the driving variable.\n    std::swap(dep_variables_[blocking_index],\n              indep_variables_[driving_index]);\n\n    // Update the index map.\n    auto indep_variables_indices_iter = indep_variables_indices_.find(\n        dep_variables_[blocking_index]);\n    indep_variables_indices_.erase(indep_variables_indices_iter);\n    indep_variables_indices_[indep_variables_[driving_index]] =\n        driving_index;\n\n    // Make the driving variable the complement of the blocking variable.\n    driving_index = FindComplementIndex(blocking);\n\n    DRAKE_LOGGER_DEBUG(\"Independent set variables: {}\",\n        to_string(indep_variables_));\n    DRAKE_LOGGER_DEBUG(\"Dependent set variables: {}\",\n        to_string(dep_variables_));\n  }\n\n  // If here, the maximum number of pivots has been exceeded.\n  z->setZero(n);\n  DRAKE_LOGGER_DEBUG(\"Maximum number of pivots exceeded\");\n  return false;\n}\n\ntemplate <typename T>\nUnrevisedLemkeSolver<T>::UnrevisedLemkeSolver()\n    : SolverBase(&id, &is_available, &is_enabled,\n                 &ProgramAttributesSatisfied) {}\n\ntemplate <typename T>\nUnrevisedLemkeSolver<T>::~UnrevisedLemkeSolver() = default;\n\nSolverId UnrevisedLemkeSolverId::id() {\n  static const never_destroyed<SolverId> singleton{\"Unrevised Lemke\"};\n  return singleton.access();\n}\n\ntemplate <typename T>\nSolverId UnrevisedLemkeSolver<T>::id() {\n  return UnrevisedLemkeSolverId::id();\n}\n\ntemplate <typename T>\nbool UnrevisedLemkeSolver<T>::is_available() {\n  return true;\n}\n\ntemplate <typename T>\nbool UnrevisedLemkeSolver<T>::is_enabled() {\n  return true;\n}\n\ntemplate <typename T>\nbool UnrevisedLemkeSolver<T>::ProgramAttributesSatisfied(\n    const MathematicalProgram& prog) {\n  // This solver imposes restrictions that its problem:\n  //\n  // (1) Contains only linear complementarity constraints,\n  // (2) Has no element of any decision variable appear in more than one\n  //     constraint, and\n  // (3) Has every element of every decision variable in a constraint.\n  //\n  // Restriction 1 could reasonably be relaxed by reformulating other\n  // constraint types that can be expressed as LCPs (eg, convex QLPs),\n  // although this would also entail adding an output stage to convert\n  // the LCP results back to the desired form.  See eg. @RussTedrake on\n  // how to convert a linear equality constraint of n elements to an\n  // LCP of 2n elements.\n  //\n  // There is no obvious way to relax restriction 2.\n  //\n  // Restriction 3 could reasonably be relaxed to simply let unbound\n  // variables sit at 0.\n  if (prog.required_capabilities() != ProgramAttributes({\n        ProgramAttribute::kLinearComplementarityConstraint})) {\n    return false;\n  }\n\n  // Check that the available LCPs cover the program and no two LCPs cover the\n  // same variable.\n  const auto& bindings = prog.linear_complementarity_constraints();\n  for (int i = 0; i < static_cast<int>(prog.num_vars()); ++i) {\n    int coverings = 0;\n    for (const auto& binding : bindings) {\n      if (binding.ContainsVariable(prog.decision_variable(i))) {\n        coverings++;\n      }\n    }\n    if (coverings != 1) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\n}  // namespace solvers\n}  // namespace drake\n\nDRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_NONSYMBOLIC_SCALARS(\n    class ::drake::solvers::UnrevisedLemkeSolver)\n", "meta": {"hexsha": "a5995aca06efe7d620236d311fa592b57da234e8", "size": 35144, "ext": "cc", "lang": "C++", "max_stars_repo_path": "solvers/unrevised_lemke_solver.cc", "max_stars_repo_name": "RobotLocomotion/drake-python3.7", "max_stars_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:01:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T04:52:04.000Z", "max_issues_repo_path": "solvers/unrevised_lemke_solver.cc", "max_issues_repo_name": "RobotLocomotion/drake-python3.7", "max_issues_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solvers/unrevised_lemke_solver.cc", "max_forks_repo_name": "RobotLocomotion/drake-python3.7", "max_forks_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T12:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T12:05:39.000Z", "avg_line_length": 36.9936842105, "max_line_length": 80, "alphanum_fraction": 0.6730594127, "num_tokens": 9431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2819813976805361}}
{"text": "//\n// Created by AIYOJ on 2019-03-02.\n//\n\n#include \"log/algocomp_log.h\"\n#include \"calibration/isotonic_regression.h\"\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n\n\nnamespace algocomp {\n    IsotonicRegression::IsotonicRegression() {\n        _logger = spdlog::get(ACLog::_logger_name);\n        _logger->info(\"Initialize Isotonic Regression.\");\n    }\n\n    IsotonicRegression::~IsotonicRegression() {\n        _logger->info(\"Leave Isotonic Regression.\");\n    }\n\n    std::vector<float> IsotonicRegression::calibrate(const std::vector<float> &scores) {\n        std::vector<float> calibrated_scores;\n        for (int i = 0; i < scores.size(); ++i) {\n            auto calibrated_score = get(scores[i], _search_type);\n            calibrated_scores.push_back(calibrated_score);\n        }\n\n        return calibrated_scores;\n    }\n\n    float IsotonicRegression::calibrate(float score) {\n        float calibrated_score = get(score, _search_type);\n        return calibrated_score;\n    }\n\n    std::unique_ptr<IsotonicRegression> IsotonicRegression::load(const std::string &path) {\n        auto logger = spdlog::get(ACLog::_logger_name);\n\n        try {\n            std::ifstream file;\n            file.open(path);\n            if (file.is_open()) {\n                std::unique_ptr<IsotonicRegression> output_calibration = std::unique_ptr<IsotonicRegression>(\n                        new IsotonicRegression());\n                std::string line;\n                float pre = 0;\n                bool order = true;\n                std::vector<std::pair<float, float >> tmp_bins;\n                while (!file.eof()) {\n                    std::getline(file, line);\n                    line = boost::algorithm::trim_copy(line);\n                    if (line.length() == 0) {\n                        continue;\n                    }\n\n                    std::vector<std::string> splits;\n                    boost::algorithm::split(splits, line, boost::algorithm::is_any_of(\" \"));\n\n                    if (splits.size() != 2) {\n                        logger->error(\"Invalid isotonic regression coef {}\", line);\n                        continue;\n                    }\n\n                    float bin = boost::lexical_cast<float>(splits[0]);\n                    float value = boost::lexical_cast<float>(splits[1]);\n\n                    if (bin > pre) {\n                        order = true;\n                        pre = bin;\n                    } else if (bin < pre) {\n                        order = false;\n                        pre = bin;\n                    } else {\n                        logger->error(\"the same bin: {}\", bin);\n                        break;\n                    }\n\n                    tmp_bins.push_back(std::make_pair(bin, value));\n                }\n\n                if (order) {\n                    output_calibration->update(tmp_bins);\n                } else {\n                    // sort\n                    std::sort(tmp_bins.begin(), tmp_bins.end(),\n                              [](const std::pair<float, float> &a, const std::pair<float, float> &b) {\n                                  return a.first < b.first;\n                              });\n                    output_calibration->update(tmp_bins);\n                }\n                if (file.is_open()) {\n                    file.close();\n                }\n                if (output_calibration) {\n                    logger->info(\"Natively loaded isotonic regression from {}.\", path);\n                    return output_calibration;\n                } else {\n                    logger->error(\"Fail to read calibration file when natively loading isotonic regression from {}.\",\n                                  path);\n                }\n            } else {\n                logger->error(\n                        \"Fail to open isotonic regression file when natively loading isotonic regression from {}.\",\n                        path);\n            }\n\n        } catch (std::exception &ex) {\n            logger->error(\"Fail to natively load isotonic regression from {}, detail: {}.\", path, ex.what());\n        }\n        return nullptr;\n    }\n\n    void IsotonicRegression::update(const std::vector<std::pair<float, float>> &bins) {\n        _bins.clear();\n        _bins = bins;\n    }\n\n    float IsotonicRegression::get(float bin, const SearchType search_type) {\n        // upper bound\n        auto upper_bound = [this](float key) {\n            int first = 0;\n            int len = _bins.size() - 1;\n            int half, middle;\n\n            while (len > 0) {\n                half = len >> 1;\n                middle = first + half;\n                // The median is greater than the key and is looked up in the left half of the sequence containing last.\n                if (_bins[middle].first > key) {\n                    len = half;\n                } else {  // The median is less than or equal to the key and is looked up in the right half of the sequence.\n                    first = middle + 1;\n                    len = len - half - 1;\n                }\n            }\n            return first;\n        };\n\n        // lower bound\n        auto lower_bound = [this](float key) {\n            int first = 0, middle;\n            int half, len;\n            len = _bins.size();\n\n            while (len > 0) {\n                half = len >> 1;\n                middle = first + half;\n                if (_bins[middle].first < key) {\n                    first = middle + 1;\n                    len = len - half - 1;\n                } else {\n                    len = half;\n                }\n            }\n            return first;\n        };\n\n        // search type\n        if (search_type == SearchType::UPPERBOUND) {\n            auto index = upper_bound(bin);\n            return _bins[index].second;\n        } else if (search_type == SearchType::LOWERBOUND) {\n            auto index = lower_bound(bin);\n            return _bins[index].second;\n        } else {\n            _logger->error(\"Unknown Search Type.\");\n        }\n    }\n}\n", "meta": {"hexsha": "dd38df0b13d89e355e159412c0896936d09473d5", "size": 6022, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/src/calibration/isotonic_regression.cpp", "max_stars_repo_name": "qf6101/algorithm-components", "max_stars_repo_head_hexsha": "f7307e4bd9697ee473d5763e0a61df7891b699f6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T11:43:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-09T09:21:23.000Z", "max_issues_repo_path": "core/src/calibration/isotonic_regression.cpp", "max_issues_repo_name": "qf6101/algorithm-components", "max_issues_repo_head_hexsha": "f7307e4bd9697ee473d5763e0a61df7891b699f6", "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": "core/src/calibration/isotonic_regression.cpp", "max_forks_repo_name": "qf6101/algorithm-components", "max_forks_repo_head_hexsha": "f7307e4bd9697ee473d5763e0a61df7891b699f6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-16T18:54:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-24T07:52:24.000Z", "avg_line_length": 35.216374269, "max_line_length": 124, "alphanum_fraction": 0.4701095981, "num_tokens": 1214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2819240931480263}}
{"text": "/**\n * @file cape.cpp\n *\n */\n\n#include \"cape.h\"\n#include \"logger.h\"\n#include \"numerical_functions.h\"\n#include \"plugin_factory.h\"\n#include \"util.h\"\n#include <boost/lexical_cast.hpp>\n#include <boost/thread.hpp>\n#include <future>\n\n#include \"fetcher.h\"\n#include \"hitool.h\"\n#include \"radon.h\"\n\n#include \"cape.cuh\"\n\nconst unsigned char FCAPE = (1 << 2);\nconst unsigned char FCAPE3km = (1 << 0);\n\nusing namespace std;\nusing namespace himan::plugin;\n\n#ifdef DEBUG\n#define DumpVector(A, B) himan::util::DumpVector(A, B)\n#else\n#define DumpVector(A, B)\n#endif\n\nextern mutex dimensionMutex;\n\nconst himan::param LCLTParam(\"LCL-K\", 4, 0, 0, 0);\nconst himan::param LCLPParam(\"LCL-HPA\", 4720, 0, 3, 0);\nconst himan::param LCLZParam(\"LCL-M\", 4726, 0, 3, 6);\nconst himan::param LFCTParam(\"LFC-K\", 4, 0, 0, 0);\nconst himan::param LFCPParam(\"LFC-HPA\", 4721, 0, 3, 0);\nconst himan::param LFCZParam(\"LFC-M\", 4727, 0, 3, 6);\nconst himan::param ELTParam(\"EL-K\", 4, 0, 0, 0);\nconst himan::param ELPParam(\"EL-HPA\", 4722, 0, 3, 0);\nconst himan::param ELZParam(\"EL-M\", 4728, 0, 3, 6);\nconst himan::param CAPEParam(\"CAPE-JKG\", 4723, 0, 7, 6);\nconst himan::param CAPE1040Param(\"CAPE1040-JKG\", 4729, 0, 7, 6);\nconst himan::param CAPE3kmParam(\"CAPE3KM-JKG\", 4724, 0, 7, 6);\nconst himan::param CINParam(\"CIN-JKG\", 4725, 0, 7, 7);\n\nconst himan::level SURFACE(himan::kHeight, 0);\nconst himan::level M500(himan::kHeightLayer, 500, 0);\nconst himan::level UNSTABLE(himan::kMaximumThetaE, 0);\n\ndouble Max(const vector<double>& vec)\n{\n\tdouble ret = -1e38;\n\n\tfor (const double& val : vec)\n\t{\n\t\tif (val != himan::kFloatMissing && val > ret) ret = val;\n\t}\n\n\tif (ret == -1e38) ret = himan::kFloatMissing;\n\n\treturn ret;\n}\n\nvoid MultiplyWith(vector<double>& vec, double multiplier)\n{\n\tfor (double& val : vec)\n\t{\n\t\tif (val != himan::kFloatMissing) val *= multiplier;\n\t}\n}\n\nstring PrintMean(const vector<double>& vec)\n{\n\tdouble min = 1e38, max = -1e38, sum = 0;\n\tsize_t count = 0, missing = 0;\n\n\tfor (const double& val : vec)\n\t{\n\t\tif (val == himan::kFloatMissing)\n\t\t{\n\t\t\tmissing++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tmin = (val < min) ? val : min;\n\t\tmax = (val > max) ? val : max;\n\t\tcount++;\n\t\tsum += val;\n\t}\n\n\tdouble mean = numeric_limits<double>::quiet_NaN();\n\n\tif (count > 0)\n\t{\n\t\tmean = sum / static_cast<double>(count);\n\t}\n\n\tstring minstr = (min == 1e38) ? \"nan\" : to_string(static_cast<int>(min));\n\tstring maxstr = (max == -1e38) ? \"nan\" : to_string(static_cast<int>(max));\n\tstring meanstr = (mean != mean) ? \"nan\" : to_string(static_cast<int>(mean));\n\n\treturn \"min \" + minstr + \" max \" + maxstr + \" mean \" + meanstr + \" missing \" + to_string(missing);\n}\n\nvoid MoistLift(const double* Piter, const double* Titer, const double* Penv, double* Tparcel, size_t size)\n{\n\t// Split MoistLift (integration of a saturated air parcel upwards in atmosphere)\n\t// to several threads since it is very CPU intensive\n\n\tvector<future<void>> futures;\n\n\tsize_t workers = 6;\n\n\tif (size % workers != 0)\n\t{\n\t\tworkers = 4;\n\t\tif (size % workers != 0)\n\t\t{\n\t\t\tworkers = 3;\n\t\t\tif (size % workers != 0)\n\t\t\t{\n\t\t\t\tworkers = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst size_t splitSize = static_cast<size_t>(floor(size / workers));\n\n\tfor (size_t num = 0; num < workers; num++)\n\t{\n\t\tconst size_t start = num * splitSize;\n\t\tfutures.push_back(async(launch::async,\n\t\t                        [&](size_t start) {\n\t\t\t                        himan::metutil::MoistLiftA(&Piter[start], &Titer[start], &Penv[start],\n\t\t\t                                                   &Tparcel[start], splitSize);\n\t\t\t                    },\n\t\t                        start));\n\t}\n\n\tfor (auto& future : futures)\n\t{\n\t\tfuture.get();\n\t}\n}\n\ncape::cape() : itsBottomLevel(kHybrid, kHPMissingInt)\n{\n\titsLogger = logger(\"cape\");\n}\n\nvoid cape::Process(std::shared_ptr<const plugin_configuration> conf)\n{\n\tcompiled_plugin_base::Init(conf);\n\n\tauto r = GET_PLUGIN(radon);\n\n\titsBottomLevel = level(kHybrid, stoi(r->RadonDB().GetProducerMetaData(itsConfiguration->SourceProducer().Id(),\n\t                                                                      \"last hybrid level number\")));\n\n#ifdef HAVE_CUDA\n\tcape_cuda::itsBottomLevel = itsBottomLevel;\n#endif\n\n\tvector<param> theParams;\n\tvector<string> sourceDatas;\n\n\tif (itsConfiguration->Exists(\"source_data\"))\n\t{\n\t\tsourceDatas = itsConfiguration->GetValueList(\"source_data\");\n\t}\n\n\tif (sourceDatas.size() == 0)\n\t{\n\t\tsourceDatas.push_back(\"surface\");\n\t\tsourceDatas.push_back(\"500m mix\");\n\t\tsourceDatas.push_back(\"most unstable\");\n\t}\n\n\ttheParams.push_back(LCLTParam);\n\ttheParams.push_back(LCLPParam);\n\ttheParams.push_back(LCLZParam);\n\ttheParams.push_back(LFCTParam);\n\ttheParams.push_back(LFCPParam);\n\ttheParams.push_back(LFCZParam);\n\ttheParams.push_back(ELTParam);\n\ttheParams.push_back(ELPParam);\n\ttheParams.push_back(ELZParam);\n\ttheParams.push_back(CAPEParam);\n\ttheParams.push_back(CAPE1040Param);\n\ttheParams.push_back(CAPE3kmParam);\n\ttheParams.push_back(CINParam);\n\n\tfor (const auto& source : sourceDatas)\n\t{\n\t\tif (source == \"surface\")\n\t\t{\n\t\t\titsSourceLevels.push_back(SURFACE);\n\t\t}\n\t\telse if (source == \"500m mix\")\n\t\t{\n\t\t\titsSourceLevels.push_back(M500);\n\t\t}\n\t\telse if (source == \"most unstable\")\n\t\t{\n\t\t\titsSourceLevels.push_back(UNSTABLE);\n\t\t}\n\t}\n\n\t// disregard the level information provided by user\n\n\titsConfiguration->Info()->Levels(itsSourceLevels);\n\n\tSetParams(theParams);\n\n\tStart();\n}\n\nvoid cape::Calculate(shared_ptr<info> myTargetInfo, unsigned short threadIndex)\n{\n\t/*\n\t * Algorithm:\n\t *\n\t * 1) Find suitable T and TD values of an air parcel\n\t *\n\t * 2) Lift this air parcel to LCL height dry adiabatically\n\t *\n\t * 3) Continue lifting the particle to LFC height moist adiabatically.\n\t *\n\t * This is done by lifting the parcel a certain height at a time (500 Pa),\n\t * and calculating the new temperature from the lifted height. If parcel\n\t * temperature is larger than environment temperature, we have reached LFC.\n\t * Environment temperature is therefore fetched every iteration of integration\n\t * algorithm.\n\t *\n\t * 4) Integrate from LFC to EL\n\t *\n\t * 5) Integrate from surface to LFC to find CIN\n\t */\n\n\tauto sourceLevel = myTargetInfo->Level();\n\n\tauto mySubThreadedLogger = logger(\"siThread#\" + boost::lexical_cast<string>(threadIndex) + \"Version\" +\n\t                                  boost::lexical_cast<string>(static_cast<int>(sourceLevel.Type())));\n\n\tmySubThreadedLogger.Info(\"Calculating source level type \" + HPLevelTypeToString.at(sourceLevel.Type()) +\n\t                         \" for time \" + static_cast<string>(myTargetInfo->Time().ValidDateTime()));\n\n\t// 1.\n\n\ttimer aTimer;\n\taTimer.Start();\n\n\tcape_source sourceValues;\n\n\tswitch (sourceLevel.Type())\n\t{\n\t\tcase kHeight:\n\t\t\tsourceValues = GetSurfaceValues(myTargetInfo);\n\t\t\tbreak;\n\n\t\tcase kHeightLayer:\n\t\t\tsourceValues = Get500mMixingRatioValues(myTargetInfo);\n\t\t\tbreak;\n\n\t\tcase kMaximumThetaE:\n\t\t\tsourceValues = GetHighestThetaEValues(myTargetInfo);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tthrow runtime_error(\"Invalid source level: \" + static_cast<std::string>(sourceLevel));\n\t\t\tbreak;\n\t}\n\n\tmyTargetInfo->Level(sourceLevel);\n\n\tif (get<0>(sourceValues).empty()) return;\n\n\taTimer.Stop();\n\n\tmySubThreadedLogger.Info(\"Source data calculated in \" + boost::lexical_cast<string>(aTimer.GetTime()) + \" ms\");\n\n\tmySubThreadedLogger.Debug(\"Source temperature: \" + ::PrintMean(get<0>(sourceValues)));\n\tmySubThreadedLogger.Debug(\"Source dewpoint: \" + ::PrintMean(get<1>(sourceValues)));\n\tmySubThreadedLogger.Debug(\"Source pressure: \" + ::PrintMean(get<2>(sourceValues)));\n\n\t// 2.\n\n\taTimer.Start();\n\n\tauto LCL = GetLCL(myTargetInfo, sourceValues);\n\n\taTimer.Stop();\n\n\tmySubThreadedLogger.Info(\"LCL calculated in \" + boost::lexical_cast<string>(aTimer.GetTime()) + \" ms\");\n\n\tmySubThreadedLogger.Debug(\"LCL temperature: \" + ::PrintMean(LCL.first));\n\tmySubThreadedLogger.Debug(\"LCL pressure: \" + ::PrintMean(LCL.second));\n\n\tmyTargetInfo->Param(LCLTParam);\n\tmyTargetInfo->Data().Set(LCL.first);\n\n\tmyTargetInfo->Param(LCLPParam);\n\tmyTargetInfo->Data().Set(LCL.second);\n\n\tauto h = GET_PLUGIN(hitool);\n\th->Configuration(itsConfiguration);\n\th->Time(myTargetInfo->Time());\n\th->ForecastType(myTargetInfo->ForecastType());\n\th->HeightUnit(kHPa);\n\n\tauto height = h->VerticalValue(param(\"HL-M\"), LCL.second);\n\n\tmyTargetInfo->Param(LCLZParam);\n\tmyTargetInfo->Data().Set(height);\n\n\t// 3.\n\n\taTimer.Start();\n\n\tauto LFC = GetLFC(myTargetInfo, LCL.first, LCL.second);\n\n\taTimer.Stop();\n\n\tmySubThreadedLogger.Info(\"LFC calculated in \" + boost::lexical_cast<string>(aTimer.GetTime()) + \" ms\");\n\n\tif (LFC.first.empty())\n\t{\n\t\treturn;\n\t}\n\n\tmySubThreadedLogger.Debug(\"LFC temperature: \" + ::PrintMean(LFC.first));\n\tmySubThreadedLogger.Debug(\"LFC pressure: \" + ::PrintMean(LFC.second));\n\n\tmyTargetInfo->Param(LFCTParam);\n\tmyTargetInfo->Data().Set(LFC.first);\n\n\tmyTargetInfo->Param(LFCPParam);\n\tmyTargetInfo->Data().Set(LFC.second);\n\n\theight = h->VerticalValue(param(\"HL-M\"), LFC.second);\n\n\tmyTargetInfo->Param(LFCZParam);\n\tmyTargetInfo->Data().Set(height);\n\n\t// 4. & 5.\n\n\taTimer.Start();\n\n\tauto capeInfo = make_shared<info>(*myTargetInfo);\n\tboost::thread t1(&cape::GetCAPE, this, boost::ref(capeInfo), LFC, ELTParam, ELPParam, ELZParam, CAPEParam,\n\t                 CAPE1040Param, CAPE3kmParam);\n\n\tauto cinInfo = make_shared<info>(*myTargetInfo);\n\tboost::thread t2(&cape::GetCIN, this, boost::ref(cinInfo), get<0>(sourceValues), get<2>(sourceValues), LCL.first,\n\t                 LCL.second, LFC.second, CINParam);\n\n\tt1.join();\n\tt2.join();\n\n\taTimer.Stop();\n\n\tmySubThreadedLogger.Info(\"CAPE and CIN calculated in \" + boost::lexical_cast<string>(aTimer.GetTime()) + \" ms\");\n\n\t// Sometimes CAPE area is infinitely small -- so that CAPE is zero but LFC is found. In this case set all derivative\n\t// parameters missing.\n\n\tcapeInfo->Param(LFCZParam);\n\tauto& lfcz_ = VEC(capeInfo);\n\tcapeInfo->Param(LFCPParam);\n\tauto& lfcp_ = VEC(capeInfo);\n\tcapeInfo->Param(LFCTParam);\n\tauto& lfct_ = VEC(capeInfo);\n\tcinInfo->Param(CINParam);\n\tauto& cin_ = VEC(cinInfo);\n\tcapeInfo->Param(ELZParam);\n\tauto elz_ = VEC(capeInfo);\n\tcapeInfo->Param(CAPEParam);\n\tauto cape_ = VEC(capeInfo);\n\n\tfor (size_t i = 0; i < lfcz_.size(); i++)\n\t{\n\t\tif (cape_[i] == 0 && elz_[i] == kFloatMissing && lfcz_[i] != kFloatMissing)\n\t\t{\n\t\t\tcin_[i] = 0;\n\t\t\tlfcz_[i] = kFloatMissing;\n\t\t\tlfcp_[i] = kFloatMissing;\n\t\t\tlfct_[i] = kFloatMissing;\n\t\t}\n\t}\n\n#ifdef DEBUG\n\tassert(lfcz_.size() == elz_.size());\n\tassert(cape_.size() == elz_.size());\n\tassert(cin_.size() == elz_.size());\n\n\tfor (size_t i = 0; i < lfcz_.size(); i++)\n\t{\n\t\t// Check:\n\t\t// * If LFC is missing, EL is missing\n\t\t// * If LFC is present, EL is present\n\t\t// * If both are present, LFC must be below EL\n\t\t// * CAPE must be zero or positive real value\n\t\t// * CIN must be zero or negative real value\n\t\tassert((lfcz_[i] == kFloatMissing && elz_[i] == kFloatMissing) ||\n\t\t       ((lfcz_[i] != kFloatMissing && elz_[i] != kFloatMissing) && (lfcz_[i] < elz_[i])));\n\t\tassert(cape_[i] >= 0);\n\t\tassert(cin_[i] <= 0);\n\t}\n#endif\n\n\t// Do smoothening for CAPE & CIN parameters\n\tmySubThreadedLogger.Trace(\"Smoothening\");\n\n\thiman::matrix<double> filter_kernel(3, 3, 1, kFloatMissing, 1. / 9.);\n\n\tcapeInfo->Param(CAPEParam);\n\thiman::matrix<double> filtered = numerical_functions::Filter2D(capeInfo->Data(), filter_kernel);\n\tcapeInfo->Grid()->Data(filtered);\n\n\tcapeInfo->Param(CAPE1040Param);\n\tfiltered = numerical_functions::Filter2D(capeInfo->Data(), filter_kernel);\n\tcapeInfo->Grid()->Data(filtered);\n\n\tcapeInfo->Param(CAPE3kmParam);\n\tfiltered = numerical_functions::Filter2D(capeInfo->Data(), filter_kernel);\n\tcapeInfo->Grid()->Data(filtered);\n\n\tcapeInfo->Param(CINParam);\n\tfiltered = numerical_functions::Filter2D(capeInfo->Data(), filter_kernel);\n\tcapeInfo->Grid()->Data(filtered);\n\n\tcapeInfo->Param(CAPEParam);\n\tmySubThreadedLogger.Debug(\"CAPE: \" + ::PrintMean(VEC(capeInfo)));\n\tcapeInfo->Param(CAPE1040Param);\n\tmySubThreadedLogger.Debug(\"CAPE1040: \" + ::PrintMean(VEC(capeInfo)));\n\tcapeInfo->Param(CAPE3kmParam);\n\tmySubThreadedLogger.Debug(\"CAPE3km: \" + ::PrintMean(VEC(capeInfo)));\n\tcinInfo->Param(CINParam);\n\tmySubThreadedLogger.Debug(\"CIN: \" + ::PrintMean(VEC(cinInfo)));\n}\n\nvoid cape::GetCIN(shared_ptr<info> myTargetInfo, const vector<double>& Tsource, const vector<double>& Psource,\n                  const vector<double>& TLCL, const vector<double>& PLCL, const vector<double>& PLFC, param CINParam)\n{\n#ifdef HAVE_CUDA\n\tif (itsConfiguration->UseCuda())\n\t{\n\t\tcape_cuda::GetCINGPU(itsConfiguration, myTargetInfo, Tsource, Psource, TLCL, PLCL, PLFC, CINParam);\n\t}\n\telse\n#endif\n\t{\n\t\tGetCINCPU(myTargetInfo, Tsource, Psource, TLCL, PLCL, PLFC, CINParam);\n\t}\n}\n\nvoid cape::GetCINCPU(shared_ptr<info> myTargetInfo, const vector<double>& Tsource, const vector<double>& Psource,\n                     const vector<double>& TLCL, const vector<double>& PLCL, const vector<double>& PLFC, param CINParam)\n{\n\tauto h = GET_PLUGIN(hitool);\n\th->Configuration(itsConfiguration);\n\th->Time(myTargetInfo->Time());\n\th->ForecastType(myTargetInfo->ForecastType());\n\th->HeightUnit(kHPa);\n\n\tvector<bool> found(Tsource.size(), false);\n\n\tfor (size_t i = 0; i < found.size(); i++)\n\t{\n\t\tif (PLFC[i] == kFloatMissing)\n\t\t{\n\t\t\tfound[i] = true;\n\t\t}\n\t}\n\n\tforecast_time ftime = myTargetInfo->Time();\n\tforecast_type ftype = myTargetInfo->ForecastType();\n\n\t/*\n\t * Modus operandi:\n\t *\n\t * 1. Integrate from source level to LCL dry adiabatically\n\t *\n\t * This can be done always since LCL is known at all grid points\n\t * (that have source data values defined).\n\t *\n\t * 2. Integrate from LCL to LFC moist adiabatically\n\t *\n\t * Note! For some points integration will fail (no LFC found)\n\t *\n\t * We stop integrating at first time CAPE area is found!\n\t */\n\n\t// Get LCL and LFC heights in meters\n\n\tauto ZLCL = h->VerticalValue(param(\"HL-M\"), PLCL);\n\tauto ZLFC = h->VerticalValue(param(\"HL-M\"), PLFC);\n\n\tlevel curLevel = itsBottomLevel;\n\n\tauto prevZenvInfo = Fetch(ftime, curLevel, param(\"HL-M\"), ftype, false);\n\tauto prevTenvInfo = Fetch(ftime, curLevel, param(\"T-K\"), ftype, false);\n\tauto prevPenvInfo = Fetch(ftime, curLevel, param(\"P-HPA\"), ftype, false);\n\n\tstd::vector<double> cinh(PLCL.size(), 0);\n\n\tsize_t foundCount = count(found.begin(), found.end(), true);\n\n\tauto Piter = Psource;\n\t::MultiplyWith(Piter, 100);\n\n\tauto PLCLPa = PLCL;\n\t::MultiplyWith(PLCLPa, 100);\n\n\tauto Titer = Tsource;\n\tauto prevTparcelVec = Tsource;\n\n\tcurLevel.Value(curLevel.Value() - 1);\n\n\tauto hPa100 = h->LevelForHeight(myTargetInfo->Producer(), 100.);\n\n\twhile (curLevel.Value() > hPa100.first.Value() && foundCount != found.size())\n\t{\n\t\tauto ZenvInfo = Fetch(ftime, curLevel, param(\"HL-M\"), ftype, false);\n\t\tauto TenvInfo = Fetch(ftime, curLevel, param(\"T-K\"), ftype, false);\n\t\tauto PenvInfo = Fetch(ftime, curLevel, param(\"P-HPA\"), ftype, false);\n\n\t\tvector<double> TparcelVec(Piter.size(), kFloatMissing);\n\n\t\t// Convert pressure to Pa since metutil-library expects that\n\t\tauto PenvVec = PenvInfo->Data().Values();\n\t\t::MultiplyWith(PenvVec, 100);\n\n\t\tmetutil::LiftLCL(&Piter[0], &Titer[0], &PLCLPa[0], &PenvVec[0], &TparcelVec[0], TparcelVec.size());\n\n\t\tint i = -1;\n\n\t\tauto& cinhref = cinh;\n\n\t\tfor (auto&& tup : zip_range(cinhref, VEC(TenvInfo), VEC(prevTenvInfo), VEC(PenvInfo), VEC(prevPenvInfo),\n\t\t                            VEC(ZenvInfo), VEC(prevZenvInfo), TparcelVec, prevTparcelVec, Psource))\n\t\t{\n\t\t\ti++;\n\n\t\t\tif (found[i]) continue;\n\n\t\t\tdouble& cin = tup.get<0>();\n\n\t\t\tdouble Tenv = tup.get<1>();  // K\n\t\t\tassert(Tenv >= 100.);\n\n\t\t\tdouble prevTenv = tup.get<2>();\n\n\t\t\tdouble Penv = tup.get<3>();  // hPa\n\t\t\tassert(Penv < 1200.);\n\n\t\t\tdouble prevPenv = tup.get<4>();\n\n\t\t\tdouble Zenv = tup.get<5>();      // m\n\t\t\tdouble prevZenv = tup.get<6>();  // m\n\n\t\t\tdouble Tparcel = tup.get<7>();  // K\n\t\t\tassert(Tparcel >= 100.);\n\n\t\t\tdouble prevTparcel = tup.get<8>();  // K\n\n\t\t\tdouble Psrc = tup.get<9>();\n\n\t\t\tif (Penv > Psrc)\n\t\t\t{\n\t\t\t\t// Have not reached source level yet\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse if (Penv <= PLFC[i])\n\t\t\t{\n\t\t\t\t// reached max height\n\n\t\t\t\tfound[i] = true;\n\n\t\t\t\tif (prevTparcel == kFloatMissing || prevPenv == kFloatMissing || prevTenv == kFloatMissing)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Integrate the final piece from previous level to LFC level\n\n\t\t\t\t// First get LFC height in meters\n\t\t\t\tZenv = himan::numerical_functions::interpolation::Linear(PLFC[i], prevPenv, Penv, prevZenv, Zenv);\n\n\t\t\t\t// LFC environment temperature value\n\t\t\t\tTenv = himan::numerical_functions::interpolation::Linear(PLFC[i], prevPenv, Penv, prevTenv, Tenv);\n\n\t\t\t\t// LFC T parcel value\n\t\t\t\tTparcel =\n\t\t\t\t    himan::numerical_functions::interpolation::Linear(PLFC[i], prevPenv, Penv, prevTparcel, Tparcel);\n\n\t\t\t\tPenv = PLFC[i];\n\t\t\t\tassert(Zenv > prevZenv);\n\t\t\t}\n\n\t\t\tif (Tparcel == kFloatMissing)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (Penv < PLCL[i])\n\t\t\t{\n\t\t\t\t// Above LCL, switch to virtual temperature\n\t\t\t\tTparcel = metutil::VirtualTemperature_(Tparcel, Penv * 100);\n\t\t\t\tTenv = metutil::VirtualTemperature_(Tenv, Penv * 100);\n\t\t\t}\n\n\t\t\tcin += CAPE::CalcCIN(Tenv, prevTenv, Tparcel, prevTparcel, Penv, prevPenv, Zenv, prevZenv);\n\t\t\tassert(cin <= 0);\n\t\t}\n\n\t\tfoundCount = count(found.begin(), found.end(), true);\n\n\t\titsLogger.Trace(\"CIN read for \" + boost::lexical_cast<string>(foundCount) + \"/\" +\n\t\t                boost::lexical_cast<string>(found.size()) + \" gridpoints\");\n\n\t\tcurLevel.Value(curLevel.Value() - 1);\n\n\t\tprevZenvInfo = ZenvInfo;\n\t\tprevTenvInfo = TenvInfo;\n\t\tprevPenvInfo = PenvInfo;\n\t\tprevTparcelVec = TparcelVec;\n\n\t\tfor (size_t i = 0; i < Titer.size(); i++)\n\t\t{\n\t\t\tif (TparcelVec[i] != kFloatMissing && PenvVec[i] != kFloatMissing)\n\t\t\t{\n\t\t\t\tTiter[i] = TparcelVec[i];\n\t\t\t\tPiter[i] = PenvVec[i];\n\t\t\t}\n\n\t\t\tif (found[i]) Titer[i] = kFloatMissing;  // by setting this we prevent MoistLift to integrate particle\n\t\t}\n\t}\n\n\tmyTargetInfo->Param(CINParam);\n\tmyTargetInfo->Data().Set(cinh);\n}\n\nvoid cape::GetCAPE(shared_ptr<info> myTargetInfo, const pair<vector<double>, vector<double>>& LFC, param ELTParam,\n                   param ELPParam, param ELZParam, param CAPEParam, param CAPE1040Param, param CAPE3kmParam)\n{\n#ifdef HAVE_CUDA\n\tif (itsConfiguration->UseCuda())\n\t{\n\t\tcape_cuda::GetCAPEGPU(itsConfiguration, myTargetInfo, LFC.first, LFC.second, ELTParam, ELPParam, CAPEParam,\n\t\t                      CAPE1040Param, CAPE3kmParam);\n\t}\n\telse\n#endif\n\t{\n\t\tGetCAPECPU(myTargetInfo, LFC.first, LFC.second, ELTParam, ELPParam, CAPEParam, CAPE1040Param, CAPE3kmParam);\n\t}\n\n\tauto h = GET_PLUGIN(hitool);\n\n\th->Configuration(itsConfiguration);\n\th->Time(myTargetInfo->Time());\n\th->ForecastType(myTargetInfo->ForecastType());\n\th->HeightUnit(kHPa);\n\n\tmyTargetInfo->Param(ELPParam);\n\tauto height = h->VerticalValue(param(\"HL-M\"), VEC(myTargetInfo));\n\n\tmyTargetInfo->Param(ELZParam);\n\tmyTargetInfo->Data().Set(height);\n}\n\nvoid cape::GetCAPECPU(shared_ptr<info> myTargetInfo, const vector<double>& T, const vector<double>& P, param ELTParam,\n                      param ELPParam, param CAPEParam, param CAPE1040Param, param CAPE3kmParam)\n{\n\tassert(T.size() == P.size());\n\n\tauto h = GET_PLUGIN(hitool);\n\n\th->Configuration(itsConfiguration);\n\th->Time(myTargetInfo->Time());\n\th->ForecastType(myTargetInfo->ForecastType());\n\th->HeightUnit(kHPa);\n\n\t// Found count determines if we have calculated all three CAPE variation for a single grid point\n\tvector<unsigned char> found(T.size(), 0);\n\n\tvector<double> CAPE(T.size(), 0);\n\tvector<double> CAPE1040(T.size(), 0);\n\tvector<double> CAPE3km(T.size(), 0);\n\tvector<double> ELT(T.size(), kFloatMissing);\n\tvector<double> ELP(T.size(), kFloatMissing);\n\n\t// Unlike LCL, LFC is *not* found for all grid points\n\n\tsize_t foundCount = 0;\n\n\tfor (size_t i = 0; i < P.size(); i++)\n\t{\n\t\tif (P[i] == kFloatMissing)\n\t\t{\n\t\t\tfound[i] |= FCAPE;\n\t\t\tfoundCount++;\n\t\t}\n\t}\n\n\t// For each grid point find the hybrid level that's below LFC and then pick the lowest level\n\t// among all grid points\n\n\tauto levels = h->LevelForHeight(myTargetInfo->Producer(), ::Max(P));\n\n\tlevel curLevel = levels.first;\n\n\tauto prevZenvInfo = Fetch(myTargetInfo->Time(), curLevel, param(\"HL-M\"), myTargetInfo->ForecastType(), false);\n\tauto prevTenvInfo = Fetch(myTargetInfo->Time(), curLevel, param(\"T-K\"), myTargetInfo->ForecastType(), false);\n\tauto prevPenvInfo = Fetch(myTargetInfo->Time(), curLevel, param(\"P-HPA\"), myTargetInfo->ForecastType(), false);\n\n\tcurLevel.Value(curLevel.Value());\n\n\tauto Piter = P, Titer = T;  // integration variables\n\tauto prevTparcelVec = Titer;\n\n\t// Convert pressure to Pa since metutil-library expects that\n\t::MultiplyWith(Piter, 100);\n\n\tinfo_t TenvInfo, PenvInfo, ZenvInfo;\n\n\tauto hPa100 = h->LevelForHeight(myTargetInfo->Producer(), 100.);\n\n\twhile (curLevel.Value() > hPa100.first.Value() && foundCount != found.size())\n\t{\n\t\t// Get environment temperature, pressure and height values for this level\n\t\tPenvInfo = Fetch(myTargetInfo->Time(), curLevel, param(\"P-HPA\"), myTargetInfo->ForecastType(), false);\n\t\tTenvInfo = Fetch(myTargetInfo->Time(), curLevel, param(\"T-K\"), myTargetInfo->ForecastType(), false);\n\t\tZenvInfo = Fetch(myTargetInfo->Time(), curLevel, param(\"HL-M\"), myTargetInfo->ForecastType(), false);\n\n\t\t// Convert pressure to Pa since metutil-library expects that\n\t\tauto PenvVec = PenvInfo->Data().Values();\n\t\t::MultiplyWith(PenvVec, 100);\n\n\t\tvector<double> TparcelVec(P.size(), kFloatMissing);\n\n\t\t::MoistLift(&Piter[0], &Titer[0], &PenvVec[0], &TparcelVec[0], TparcelVec.size());\n\n\t\tint i = -1;\n\t\tfor (auto&& tup : zip_range(VEC(PenvInfo), VEC(ZenvInfo), VEC(prevZenvInfo), VEC(prevTenvInfo),\n\t\t                            VEC(prevPenvInfo), VEC(TenvInfo), TparcelVec, prevTparcelVec))\n\t\t{\n\t\t\ti++;\n\n\t\t\tdouble Tenv = tup.get<5>();  // K\n\t\t\tassert(Tenv > 100.);\n\n\t\t\tdouble prevTenv = tup.get<3>();  // K\n\t\t\tassert(prevTenv > 100.);\n\n\t\t\tdouble Penv = tup.get<0>();  // hPa\n\t\t\tassert(Penv < 1200.);\n\n\t\t\tdouble prevPenv = tup.get<4>();  // hPa\n\t\t\tassert(prevPenv < 1200.);\n\n\t\t\tdouble Zenv = tup.get<1>();      // m\n\t\t\tdouble prevZenv = tup.get<2>();  // m\n\n\t\t\tdouble Tparcel = tup.get<6>();  // K\n\t\t\tassert(Tparcel > 100. || Tparcel == kFloatMissing);\n\n\t\t\tdouble prevTparcel = tup.get<7>();  // K\n\t\t\tassert(prevTparcel > 100. || Tparcel == kFloatMissing);\n\n\t\t\tif (found[i] & FCAPE)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse if (Penv == kFloatMissing || Tenv == kFloatMissing || Zenv == kFloatMissing ||\n\t\t\t         prevZenv == kFloatMissing || Tparcel == kFloatMissing || Penv > P[i])\n\t\t\t{\n\t\t\t\t// Missing data or current grid point is below LFC\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// When rising above LFC, get accurate value of Tenv at that level so that even small amounts of CAPE\n\t\t\t// (and EL!) values can be determined.\n\n\t\t\tif (prevTparcel == kFloatMissing && Tparcel != kFloatMissing)\n\t\t\t{\n\t\t\t\tprevTenv = himan::numerical_functions::interpolation::Linear(P[i], prevPenv, Penv, prevTenv, Tenv);\n\t\t\t\tprevZenv = himan::numerical_functions::interpolation::Linear(P[i], prevPenv, Penv, prevZenv, Zenv);\n\t\t\t\tprevPenv = P[i];     // LFC pressure\n\t\t\t\tprevTparcel = T[i];  // LFC temperature\n\n\t\t\t\t// If LFC was found close to lower hybrid level, the linear interpolation and moist lift will result\n\t\t\t\t// to same values. In this case CAPE integration fails as there is no area formed between environment\n\t\t\t\t// and parcel temperature. The result for this is that LFC is found but EL is not found. To prevent\n\t\t\t\t// this, warm the parcel value just slightly so that a miniscule CAPE area is formed and EL is found.\n\n\t\t\t\tif (fabs(prevTparcel - prevTenv) < 0.0001)\n\t\t\t\t{\n\t\t\t\t\tprevTparcel += 0.0001;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (curLevel.Value() < 85 && (Tenv - Tparcel) > 25.)\n\t\t\t{\n\t\t\t\t// Temperature gap between environment and parcel too large --> abort search.\n\t\t\t\t// Only for values higher in the atmosphere, to avoid the effects of inversion\n\n\t\t\t\tfound[i] |= FCAPE;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (prevZenv >= 3000. && Zenv >= 3000.)\n\t\t\t{\n\t\t\t\tfound[i] |= FCAPE3km;\n\t\t\t}\n\n\t\t\tif ((found[i] & FCAPE3km) == 0)\n\t\t\t{\n\t\t\t\tdouble C = CAPE::CalcCAPE3km(Tenv, prevTenv, Tparcel, prevTparcel, Penv, prevPenv, Zenv, prevZenv);\n\n\t\t\t\tCAPE3km[i] += C;\n\n\t\t\t\tassert(CAPE3km[i] < 3000.);  // 3000J/kg, not 3000m\n\t\t\t\tassert(CAPE3km[i] >= 0);\n\t\t\t}\n\n\t\t\tdouble C = CAPE::CalcCAPE1040(Tenv, prevTenv, Tparcel, prevTparcel, Penv, prevPenv, Zenv, prevZenv);\n\n\t\t\tCAPE1040[i] += C;\n\n\t\t\tassert(CAPE1040[i] < 5000.);\n\t\t\tassert(CAPE1040[i] >= 0);\n\n\t\t\tdouble CAPEval, ELTval, ELPval;\n\n\t\t\tCAPE::CalcCAPE(Tenv, prevTenv, Tparcel, prevTparcel, Penv, prevPenv, Zenv, prevZenv, CAPEval, ELTval,\n\t\t\t               ELPval);\n\n\t\t\tCAPE[i] += CAPEval;\n\n\t\t\tassert(CAPEval >= 0.);\n\t\t\tassert(CAPE[i] < 8000);\n\n\t\t\tif (ELTval != kFloatMissing)\n\t\t\t{\n\t\t\t\tELT[i] = ELTval;\n\t\t\t\tELP[i] = ELPval;\n\t\t\t}\n\t\t}\n\n\t\tcurLevel.Value(curLevel.Value() - 1);\n\n\t\tfoundCount = 0;\n\t\tfor (auto& val : found)\n\t\t{\n\t\t\tif (val & FCAPE) foundCount++;\n\t\t}\n\n\t\titsLogger.Trace(\"CAPE read for \" + boost::lexical_cast<string>(foundCount) + \"/\" +\n\t\t                boost::lexical_cast<string>(found.size()) + \" gridpoints\");\n\t\tprevZenvInfo = ZenvInfo;\n\t\tprevTenvInfo = TenvInfo;\n\t\tprevPenvInfo = PenvInfo;\n\t\tprevTparcelVec = TparcelVec;\n\t}\n\n\t// If the CAPE area is continued all the way to level 60 and beyond, we don't have an EL for that\n\t// (since integration is forcefully stopped)\n\t// In this case level 60 = EL\n\n\tfor (size_t i = 0; i < CAPE.size(); i++)\n\t{\n\t\tif (CAPE[i] > 0 && ELT[i] == kFloatMissing)\n\t\t{\n\t\t\tTenvInfo->LocationIndex(i);\n\t\t\tPenvInfo->LocationIndex(i);\n\n\t\t\tELT[i] = TenvInfo->Value();\n\t\t\tELP[i] = PenvInfo->Value();\n\t\t}\n\t}\n\n\tmyTargetInfo->Param(ELTParam);\n\tmyTargetInfo->Data().Set(ELT);\n\n\tmyTargetInfo->Param(ELPParam);\n\tmyTargetInfo->Data().Set(ELP);\n\n\tmyTargetInfo->Param(CAPEParam);\n\tmyTargetInfo->Data().Set(CAPE);\n\n\tmyTargetInfo->Param(CAPE1040Param);\n\tmyTargetInfo->Data().Set(CAPE1040);\n\n\tmyTargetInfo->Param(CAPE3kmParam);\n\tmyTargetInfo->Data().Set(CAPE3km);\n}\n\npair<vector<double>, vector<double>> cape::GetLFC(shared_ptr<info> myTargetInfo, vector<double>& T, vector<double>& P)\n{\n\tauto h = GET_PLUGIN(hitool);\n\n\tassert(T.size() == P.size());\n\n\th->Configuration(itsConfiguration);\n\th->Time(myTargetInfo->Time());\n\th->ForecastType(myTargetInfo->ForecastType());\n\th->HeightUnit(kHPa);\n\n\titsLogger.Trace(\"Searching environment temperature for starting pressure\");\n\n\tvector<double> TenvLCL;\n\n\ttry\n\t{\n\t\tTenvLCL = h->VerticalValue(param(\"T-K\"), P);\n\t}\n\tcatch (const HPExceptionType& e)\n\t{\n\t\tif (e == kFileDataNotFound)\n\t\t{\n\t\t\treturn make_pair(vector<double>(), vector<double>());\n\t\t}\n\n\t\tthrow;\n\t}\n\n#ifdef HAVE_CUDA\n\tif (itsConfiguration->UseCuda())\n\t{\n\t\treturn cape_cuda::GetLFCGPU(itsConfiguration, myTargetInfo, T, P, TenvLCL);\n\t}\n\telse\n#endif\n\t{\n\t\treturn GetLFCCPU(myTargetInfo, T, P, TenvLCL);\n\t}\n}\n\npair<vector<double>, vector<double>> cape::GetLFCCPU(shared_ptr<info> myTargetInfo, vector<double>& T,\n                                                     vector<double>& P, vector<double>& TenvLCL)\n{\n\tauto h = GET_PLUGIN(hitool);\n\n\tassert(T.size() == P.size());\n\n\th->Configuration(itsConfiguration);\n\th->Time(myTargetInfo->Time());\n\th->ForecastType(myTargetInfo->ForecastType());\n\th->HeightUnit(kHPa);\n\n\tauto Piter = P, Titer = T;  // integration variables\n\n\t// Convert pressure to Pa since metutil-library expects that\n\t::MultiplyWith(Piter, 100);\n\n\tvector<bool> found(T.size(), false);\n\n\tvector<double> LFCT(T.size(), kFloatMissing);\n\tvector<double> LFCP(T.size(), kFloatMissing);\n\n\tfor (size_t i = 0; i < TenvLCL.size(); i++)\n\t{\n\t\t// Require dry lifted parcel to be just a fraction higher\n\t\t// than environment to be accepted as LFC level.\n\t\t// This requirement is important later when CAPE integration\n\t\t// starts.\n\n\t\tif ((T[i] - TenvLCL[i]) > 0.001)\n\t\t{\n\t\t\tfound[i] = true;\n\t\t\tLFCT[i] = T[i];\n\t\t\tLFCP[i] = P[i];\n\t\t\tPiter[i] = kFloatMissing;\n\t\t}\n\t}\n\n\tsize_t foundCount = count(found.begin(), found.end(), true);\n\n\titsLogger.Debug(\"Found \" + boost::lexical_cast<string>(foundCount) + \" gridpoints that have LCL=LFC\");\n\n\t// For each grid point find the hybrid level that's below LCL and then pick the lowest level\n\t// among all grid points; most commonly it's the lowest hybrid level\n\n\tauto levels = h->LevelForHeight(myTargetInfo->Producer(), ::Max(P));\n\tlevel curLevel = levels.first;\n\n\tauto prevPenvInfo = Fetch(myTargetInfo->Time(), curLevel, param(\"P-HPA\"), myTargetInfo->ForecastType(), false);\n\tauto prevTenvInfo = Fetch(myTargetInfo->Time(), curLevel, param(\"T-K\"), myTargetInfo->ForecastType(), false);\n\n\tcurLevel.Value(curLevel.Value() - 1);\n\n\tauto hPa150 = h->LevelForHeight(myTargetInfo->Producer(), 150.);\n\tauto hPa450 = h->LevelForHeight(myTargetInfo->Producer(), 450.);\n\tvector<double> prevTparcelVec(P.size(), kFloatMissing);\n\n\twhile (curLevel.Value() > hPa150.first.Value() && foundCount != found.size())\n\t{\n\t\t// Get environment temperature and pressure values for this level\n\t\tauto TenvInfo = Fetch(myTargetInfo->Time(), curLevel, param(\"T-K\"), myTargetInfo->ForecastType(), false);\n\t\tauto PenvInfo = Fetch(myTargetInfo->Time(), curLevel, param(\"P-HPA\"), myTargetInfo->ForecastType(), false);\n\n\t\t// Convert pressure to Pa since metutil-library expects that\n\t\tauto PenvVec = PenvInfo->Data().Values();\n\t\t::MultiplyWith(PenvVec, 100);\n\n\t\t// Lift the particle from previous level to this level. In the first revolution\n\t\t// of this loop the starting level is LCL. If target level level is below current level\n\t\t// (ie. we would be lowering the particle) missing value is returned.\n\n\t\tvector<double> TparcelVec(P.size(), kFloatMissing);\n\n\t\t::MoistLift(&Piter[0], &Titer[0], &PenvVec[0], &TparcelVec[0], TparcelVec.size());\n\n\t\tdouble scale = 1;\n\t\tif (prevPenvInfo->Param().Name() == \"P-PA\") scale = 0.01;\n\n\t\tint i = -1;\n\t\tfor (auto&& tup : zip_range(VEC(TenvInfo), VEC(PenvInfo), VEC(prevPenvInfo), VEC(prevTenvInfo), TparcelVec,\n\t\t                            prevTparcelVec, LFCT, LFCP))\n\t\t{\n\t\t\ti++;\n\n\t\t\tif (found[i]) continue;\n\n\t\t\tdouble Tenv = tup.get<0>();  // K\n\t\t\tassert(Tenv > 100.);\n\n\t\t\tdouble Penv = tup.get<1>();  // hPa\n\t\t\tassert(Penv < 1200.);\n\t\t\tassert(P[i] < 1200.);\n\n\t\t\tdouble prevPenv = tup.get<2>() * scale;\n\t\t\tassert(prevPenv < 1200.);\n\n\t\t\tdouble prevTenv = tup.get<3>();  // K\n\t\t\tassert(prevTenv > 100.);\n\n\t\t\tdouble Tparcel = tup.get<4>();  // K\n\t\t\tassert(Tparcel > 100.);\n\n\t\t\tdouble prevTparcel = tup.get<5>();  // K\n\t\t\tassert(Tparcel > 100.);\n\n\t\t\tdouble& Tresult = tup.get<6>();\n\t\t\tdouble& Presult = tup.get<7>();\n\n\t\t\tif (Tparcel == kFloatMissing || Penv > P[i] + 30)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (Tparcel > Tenv)\n\t\t\t{\n\t\t\t\t// Parcel is now warmer than environment, we have found LFC and entering CAPE zone\n\n\t\t\t\tfound[i] = true;\n\n\t\t\t\tif (prevTparcel == kFloatMissing)\n\t\t\t\t{\n\t\t\t\t\t// Previous value is unknown: perhaps LFC is found very close to ground?\n\t\t\t\t\t// Use LCL for previous value.\n\t\t\t\t\tprevTparcel = T[i];\n\t\t\t\t}\n\n\t\t\t\tif (fabs(prevTparcel - prevTenv) < 0.0001)\n\t\t\t\t{\n\t\t\t\t\tTresult = Tparcel;\n\t\t\t\t\tPresult = Penv;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tauto intersection =\n\t\t\t\t\t    CAPE::GetPointOfIntersection(point(Tenv, Penv), point(prevTenv, prevPenv), point(Tparcel, Penv),\n\t\t\t\t\t                                 point(prevTparcel, prevPenv));\n\t\t\t\t\tTresult = intersection.X();\n\t\t\t\t\tPresult = intersection.Y();\n\n\t\t\t\t\tif (Tresult == kFloatMissing)\n\t\t\t\t\t{\n\t\t\t\t\t\t// Intersection not found, use exact level value\n\t\t\t\t\t\tTresult = Tenv;\n\t\t\t\t\t\tPresult = Penv;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tassert(Tresult != kFloatMissing);\n\t\t\t\tassert(Presult != kFloatMissing);\n\t\t\t}\n\t\t\telse if (curLevel.Value() < hPa450.first.Value() && (Tenv - Tparcel) > 30.)\n\t\t\t{\n\t\t\t\t// Temperature gap between environment and parcel too large --> abort search.\n\t\t\t\t// Only for values higher in the atmosphere, to avoid the effects of inversion\n\n\t\t\t\tfound[i] = true;\n\t\t\t}\n\t\t}\n\n\t\tcurLevel.Value(curLevel.Value() - 1);\n\n\t\tfoundCount = count(found.begin(), found.end(), true);\n\t\titsLogger.Trace(\"LFC processed for \" + boost::lexical_cast<string>(foundCount) + \"/\" +\n\t\t                boost::lexical_cast<string>(found.size()) + \" grid points\");\n\n\t\tprevPenvInfo = PenvInfo;\n\t\tprevTenvInfo = TenvInfo;\n\n\t\tfor (size_t i = 0; i < Titer.size(); i++)\n\t\t{\n\t\t\tif (found[i]) Titer[i] = kFloatMissing;  // by setting this we prevent MoistLift to integrate particle\n\t\t}\n\n\t\tprevTparcelVec = TparcelVec;\n\t}\n\n\treturn make_pair(LFCT, LFCP);\n}\n\npair<vector<double>, vector<double>> cape::GetLCL(shared_ptr<info> myTargetInfo, const cape_source& sourceValues)\n{\n\tvector<double> TLCL(get<0>(sourceValues).size(), kFloatMissing);\n\tvector<double> PLCL = TLCL;\n\n\t// Need surface pressure\n\n\tdouble Pscale = 100.;  // P should be Pa\n\n\tfor (auto&& tup : zip_range(get<0>(sourceValues), get<1>(sourceValues), get<2>(sourceValues), TLCL, PLCL))\n\t{\n\t\tdouble T = tup.get<0>();\n\t\tdouble TD = tup.get<1>();\n\t\tdouble P = tup.get<2>() * Pscale;  // Pa\n\t\tdouble& Tresult = tup.get<3>();\n\t\tdouble& Presult = tup.get<4>();\n\n\t\tauto lcl = metutil::LCLA_(P, T, TD);\n\n\t\tTresult = lcl.T;  // K\n\n\t\tif (lcl.P != kFloatMissing)\n\t\t{\n\t\t\tPresult = 0.01 * ((lcl.P > P) ? P : lcl.P);  // hPa\n\t\t}\n\t}\n\n\tfor (auto& val : PLCL)\n\t{\n\t\tval = fmax(val, 250.);\n\t}\n\n\treturn make_pair(TLCL, PLCL);\n}\n\ncape_source cape::GetSurfaceValues(shared_ptr<info> myTargetInfo)\n{\n\t/*\n\t * 1. Get temperature and relative humidity from lowest hybrid level.\n\t * 2. Calculate dewpoint\n\t * 3. Return temperature and dewpoint\n\t */\n\n\tauto TInfo = Fetch(myTargetInfo->Time(), itsBottomLevel, param(\"T-K\"), myTargetInfo->ForecastType(), false);\n\tauto RHInfo = Fetch(myTargetInfo->Time(), itsBottomLevel, param(\"RH-PRCNT\"), myTargetInfo->ForecastType(), false);\n\tauto PInfo = Fetch(myTargetInfo->Time(), itsBottomLevel, param(\"P-HPA\"), myTargetInfo->ForecastType(), false);\n\n\tif (!TInfo || !RHInfo || !PInfo)\n\t{\n\t\treturn make_tuple(vector<double>(), vector<double>(), vector<double>());\n\t}\n\n\tauto T = VEC(TInfo);\n\tauto RH = VEC(RHInfo);\n\n\tvector<double> TD(T.size(), kFloatMissing);\n\n\tfor (size_t i = 0; i < TD.size(); i++)\n\t{\n\t\tif (T[i] != kFloatMissing && RH[i] != kFloatMissing)\n\t\t{\n\t\t\tTD[i] = metutil::DewPointFromRH_(T[i], RH[i]);\n\t\t}\n\t}\n\n\treturn make_tuple(T, TD, VEC(PInfo));\n}\n\ncape_source cape::Get500mMixingRatioValues(shared_ptr<info> myTargetInfo)\n{\n/*\n * 1. Calculate potential temperature and mixing ratio for vertical profile\n *    0...500m for every 2 hPa\n * 2. Take an average from all values\n * 3. Calculate temperature from potential temperature, and dewpoint temperature\n *    from temperature and mixing ratio\n * 4. Return the two calculated values\n */\n\n#ifdef HAVE_CUDA\n\tif (itsConfiguration->UseCuda())\n\t{\n\t\treturn cape_cuda::Get500mMixingRatioValuesGPU(itsConfiguration, myTargetInfo);\n\t}\n\telse\n#endif\n\t{\n\t\treturn Get500mMixingRatioValuesCPU(myTargetInfo);\n\t}\n}\n\ncape_source cape::Get500mMixingRatioValuesCPU(shared_ptr<info> myTargetInfo)\n{\n\tmodifier_mean tp, mr;\n\tlevel curLevel = itsBottomLevel;\n\n\tauto h = GET_PLUGIN(hitool);\n\n\th->Configuration(itsConfiguration);\n\th->Time(myTargetInfo->Time());\n\th->ForecastType(myTargetInfo->ForecastType());\n\n\ttp.HeightInMeters(false);\n\tmr.HeightInMeters(false);\n\n\tauto PInfo = Fetch(myTargetInfo->Time(), curLevel, param(\"P-HPA\"), myTargetInfo->ForecastType(), false);\n\n\tif (!PInfo)\n\t{\n\t\treturn make_tuple(vector<double>(), vector<double>(), vector<double>());\n\t}\n\telse\n\t{\n\t\t// Himan specialty: empty data grid\n\n\t\tsize_t miss = 0;\n\t\tfor (auto& val : VEC(PInfo))\n\t\t{\n\t\t\tif (val == kFloatMissing) miss++;\n\t\t}\n\n\t\tif (PInfo->Data().MissingCount() == PInfo->Data().Size())\n\t\t{\n\t\t\treturn make_tuple(vector<double>(), vector<double>(), vector<double>());\n\t\t}\n\t}\n\n\tauto P = PInfo->Data().Values();\n\n\tauto P500m = h->VerticalValue(param(\"P-HPA\"), 500.);\n\n\th->HeightUnit(kHPa);\n\n\ttp.LowerHeight(P);\n\tmr.LowerHeight(P);\n\n\ttp.UpperHeight(P500m);\n\tmr.UpperHeight(P500m);\n\n\tvector<bool> found(myTargetInfo->Data().Size(), false);\n\tsize_t foundCount = 0;\n\n\twhile (foundCount != found.size())\n\t{\n\t\tauto T = h->VerticalValue(param(\"T-K\"), P);\n\t\tauto RH = h->VerticalValue(param(\"RH-PRCNT\"), P);\n\n\t\tvector<double> Tpot(T.size(), kFloatMissing);\n\t\tvector<double> MR(T.size(), kFloatMissing);\n\n\t\tfor (size_t i = 0; i < T.size(); i++)\n\t\t{\n\t\t\tif (found[i]) continue;\n\t\t\tif (T[i] == kFloatMissing || P[i] == kFloatMissing || RH[i] == kFloatMissing) continue;\n\n\t\t\tassert(T[i] > 150 && T[i] < 350);\n\t\t\tassert(P[i] > 100 && P[i] < 1500);\n\t\t\tassert(RH[i] > 0 && RH[i] < 102);\n\n\t\t\tTpot[i] = metutil::Theta_(T[i], 100 * P[i]);\n\t\t\tMR[i] = metutil::smarttool::MixingRatio_(T[i], RH[i], 100 * P[i]);\n\t\t}\n\n\t\ttp.Process(Tpot, P);\n\t\tmr.Process(MR, P);\n\n\t\tfoundCount = tp.HeightsCrossed();\n\n\t\tassert(tp.HeightsCrossed() == mr.HeightsCrossed());\n\n\t\titsLogger.Debug(\"Data read \" + boost::lexical_cast<string>(foundCount) + \"/\" +\n\t\t                boost::lexical_cast<string>(found.size()) + \" gridpoints\");\n\n\t\tfor (size_t i = 0; i < found.size(); i++)\n\t\t{\n\t\t\tassert((P[i] > 100 && P[i] < 1500) || P[i] == kFloatMissing);\n\n\t\t\tif (found[i])\n\t\t\t{\n\t\t\t\tP[i] = kFloatMissing;  // disable processing of this\n\t\t\t}\n\t\t\telse if (P[i] != kFloatMissing)\n\t\t\t{\n\t\t\t\tP[i] -= 2.0;\n\t\t\t}\n\t\t}\n\t}\n\n\tauto Tpot = tp.Result();\n\tauto MR = mr.Result();\n\n\tauto Psurf = Fetch(myTargetInfo->Time(), itsBottomLevel, param(\"P-HPA\"), myTargetInfo->ForecastType(), false);\n\tP = Psurf->Data().Values();\n\n\tvector<double> T(Tpot.size(), kFloatMissing);\n\n\tfor (size_t i = 0; i < Tpot.size(); i++)\n\t{\n\t\tassert((P[i] > 100 && P[i] < 1500) || P[i] == kFloatMissing);\n\t\tif (Tpot[i] != kFloatMissing && P[i] != kFloatMissing)\n\t\t{\n\t\t\tT[i] = Tpot[i] * pow((P[i] / 1000.), 0.2854);\n\t\t}\n\t}\n\n\tvector<double> TD(T.size(), kFloatMissing);\n\n\tfor (size_t i = 0; i < MR.size(); i++)\n\t{\n\t\tif (T[i] != kFloatMissing && MR[i] != kFloatMissing && P[i] != kFloatMissing)\n\t\t{\n\t\t\tdouble Es = metutil::Es_(T[i]);  // Saturated water vapor pressure\n\t\t\tdouble E = metutil::E_(MR[i], 100 * P[i]);\n\n\t\t\tdouble RH = E / Es * 100;\n\t\t\tTD[i] = metutil::DewPointFromRH_(T[i], RH);\n\t\t}\n\t}\n\n\treturn make_tuple(T, TD, P);\n}\n\ncape_source cape::GetHighestThetaEValues(shared_ptr<info> myTargetInfo)\n{\n/*\n * 1. Calculate equivalent potential temperature for all hybrid levels\n *    below 600hPa\n * 2. Take temperature and relative humidity from the level that had\n *    highest theta e\n * 3. Calculate dewpoint temperature from temperature and relative humidity.\n * 4. Return temperature and dewpoint\n */\n\n#ifdef HAVE_CUDA\n\tif (itsConfiguration->UseCuda())\n\t{\n\t\treturn cape_cuda::GetHighestThetaEValuesGPU(itsConfiguration, myTargetInfo);\n\t}\n\telse\n#endif\n\t{\n\t\treturn GetHighestThetaEValuesCPU(myTargetInfo);\n\t}\n}\n\ncape_source cape::GetHighestThetaEValuesCPU(shared_ptr<info> myTargetInfo)\n{\n\tvector<bool> found(myTargetInfo->Data().Size(), false);\n\n\tvector<double> maxThetaE(myTargetInfo->Data().Size(), -1);\n\tvector<double> Ttheta(myTargetInfo->Data().Size(), kFloatMissing);\n\tauto TDtheta = Ttheta;\n\tauto Ptheta = Ttheta;\n\n\tlevel curLevel = itsBottomLevel;\n\n\tinfo_t prevTInfo, prevRHInfo, prevPInfo;\n\n\twhile (true)\n\t{\n\t\tauto TInfo = Fetch(myTargetInfo->Time(), curLevel, param(\"T-K\"), myTargetInfo->ForecastType(), false);\n\t\tauto RHInfo = Fetch(myTargetInfo->Time(), curLevel, param(\"RH-PRCNT\"), myTargetInfo->ForecastType(), false);\n\t\tauto PInfo = Fetch(myTargetInfo->Time(), curLevel, param(\"P-HPA\"), myTargetInfo->ForecastType(), false);\n\n\t\tif (!TInfo || !RHInfo || !PInfo)\n\t\t{\n\t\t\treturn make_tuple(vector<double>(), vector<double>(), vector<double>());\n\t\t}\n\n\t\tint i = -1;\n\n\t\tfor (auto&& tup : zip_range(VEC(TInfo), VEC(RHInfo), VEC(PInfo), maxThetaE, Ttheta, TDtheta, Ptheta))\n\t\t{\n\t\t\ti++;\n\n\t\t\tif (found[i]) continue;\n\n\t\t\tdouble T = tup.get<0>();\n\t\t\tdouble RH = tup.get<1>();\n\t\t\tdouble P = tup.get<2>();\n\t\t\tdouble& refThetaE = tup.get<3>();\n\t\t\tdouble& Tresult = tup.get<4>();\n\t\t\tdouble& TDresult = tup.get<5>();\n\t\t\tdouble& Presult = tup.get<6>();\n\n\t\t\tif (P == kFloatMissing)\n\t\t\t{\n\t\t\t\tfound[i] = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (P < 600.)\n\t\t\t{\n\t\t\t\tfound[i] = true;  // Make sure this is the last time we access this grid point\n\n\t\t\t\tif (!prevPInfo || !prevTInfo || !prevRHInfo)\n\t\t\t\t{\n\t\t\t\t\t// Lowest grid point located above 600hPa, hmm...\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Cut search if reach level 600hPa\n\t\t\t\tprevPInfo->LocationIndex(i);\n\t\t\t\tprevTInfo->LocationIndex(i);\n\t\t\t\tprevRHInfo->LocationIndex(i);\n\n\t\t\t\t// Linearly interpolate temperature and humidity values to 600hPa, to check\n\t\t\t\t// if highest theta e is found there\n\n\t\t\t\tT = himan::numerical_functions::interpolation::Linear(600., P, prevPInfo->Value(), T,\n\t\t\t\t                                                      prevTInfo->Value());\n\t\t\t\tRH = himan::numerical_functions::interpolation::Linear(600., P, prevPInfo->Value(), RH,\n\t\t\t\t                                                       prevRHInfo->Value());\n\n\t\t\t\tP = 600.;\n\t\t\t}\n\n\t\t\tdouble TD = metutil::DewPointFromRH_(T, RH);\n\t\t\tdouble ThetaE = metutil::smarttool::ThetaE_(T, RH, P * 100);\n\t\t\tassert(ThetaE >= 0);\n\n\t\t\tif (ThetaE >= refThetaE)\n\t\t\t{\n\t\t\t\trefThetaE = ThetaE;\n\t\t\t\tTresult = T;\n\t\t\t\tTDresult = TD;\n\t\t\t\tPresult = P;\n\n\t\t\t\tassert(TDresult > 100);\n\t\t\t}\n\t\t}\n\n\t\tsize_t foundCount = count(found.begin(), found.end(), true);\n\n\t\tif (foundCount == found.size())\n\t\t{\n\t\t\tbreak;\n\t\t}\n\n\t\titsLogger.Trace(\"Max ThetaE processed for \" + boost::lexical_cast<string>(foundCount) + \"/\" +\n\t\t                boost::lexical_cast<string>(found.size()) + \" grid points\");\n\n\t\tcurLevel.Value(curLevel.Value() - 1);\n\n\t\tprevPInfo = PInfo;\n\t\tprevTInfo = TInfo;\n\t\tprevRHInfo = RHInfo;\n\t}\n\n\treturn make_tuple(Ttheta, TDtheta, Ptheta);\n}\n", "meta": {"hexsha": "02d2c510cbb026dc8a9bb15ece6d79e1a2a2c5ed", "size": 40963, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "himan-plugins/source/cape.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/cape.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/cape.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": 27.7715254237, "max_line_length": 120, "alphanum_fraction": 0.6565192979, "num_tokens": 12330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.2819090798488639}}
{"text": "#include \"polyFFT.h\"\n#include <cryptoTools/Common/Log.h>\n#include <cryptoTools/Common/Timer.h>\n#include <cryptoTools/Crypto/RandomOracle.h>\n#include <vector>\n#include <thread>\n#include <NTL/BasicThreadPool.h>\n#include <omp.h>\n//#define fftTest\n\nnamespace osuCrypto\n{\n#define LEFT(X) (2*X+1)\n#define RIGHT(X) (2*X+2)\n#define PAPA(X) ((X-1)/2)\n\n\n\n\t\n\n\n\n\tvoid print_poly(ZZ_pX& P)\n\t{\n\t\tlong degree = deg(P);\n\t\tif (-1 == degree) {\n\t\t\tcout << \"0\";\n\t\t\treturn;\n\t\t}\n\t\tfor (long i = 0; i <= degree; i++) {\n\t\t\tcout << coeff(P, i);\n\t\t\tif (i == 1)\n\t\t\t\tcout << \"X\";\n\t\t\telse if (i > 1)\n\t\t\t\tcout << \"X^\" << i;\n\t\t\tif (i < degree) {\n\t\t\t\tcout << \" + \";\n\t\t\t}\n\t\t}\n\t\t//    cout << endl << \"random poly:\" << endl << P << endl;\n\t}\n\n\n\n\tvoid build_tree(ZZ_pX* tree, ZZ_p* points, unsigned int tree_size, int numThreads, ZZ &prime) {\n\n\t\tZZ_p negated;\n\t\tunsigned int point_index;\n\n\t\t//build all leaves whose index starts at treesize/2 => tree[i]= x-xi\t\n\t\tfor (u32 i = tree_size / 2; i< tree_size; i++) {\n\t\t\tpoint_index = i - (tree_size - 1) / 2;\n\t\t\tNTL::negate(negated, points[point_index]); //get -xi\n\t\t\tSetCoeff(tree[i], 0, negated);\n\t\t\tSetCoeff(tree[i], 1, 1);\n\t\t}\n\n\t\tvector<vector<int>> subs(numThreads);\n\t\tgenerateSubTreeArrays(subs, tree_size / 2, numThreads - 1);\n\n\t\tvector<thread> threads(numThreads);\n\n\t\tfor (int t = 0; t < numThreads; t++) \n\t\t\tthreads[t] = thread(&buildSubTree, tree, ref(subs[t]), ref(prime));\n\n\t\tfor (int t = 0; t < numThreads; t++) \n\t\t\tthreads[t].join();\n\n\n\n\t\tvector<thread> threadsLastPart(numThreads * 2);\n\n\t\tfor (int i = log2(numThreads) - 1; i >= 1; i--) {\n\t\t\t//cout<<\"layer \"<<i<< \" : \" <<endl;\n\t\t\tfor (int j = pow(2, i) - 1; j <= pow(2, i + 1) - 2; j++) {\n\t\t\t\t//cout<<\" index to process is \"<< j<<endl;\n\n\t\t\t\tthreadsLastPart[j] = thread(&buildTreeSpecific, tree, j, ref(prime));\n\t\t\t}\n\n\t\t\tfor (int j = pow(2, i) - 1; j <= pow(2, i + 1) - 2; j++) {\n\t\t\t\t//cout<<\" index join to process is \"<< j<<endl;\n\t\t\t\tthreadsLastPart[j].join();\n\t\t\t}\n\t\t}\n\n\t\ttree[0] = tree[LEFT(0)] * tree[RIGHT(0)];\n\n\t}\n\n\n\n\tvoid generateSubTreeArrays(vector<vector<int>> &subArrays, int totalNodes, int firstIndex) {\n\n\t\tint numOfSubTrees = subArrays.size();\n\n\t\t//generate subtree array\n\t\tint maxElement = totalNodes;\n\n\t\tfor (int i = 0; i < numOfSubTrees; i++) {\n\t\t\tsubArrays[i].resize(maxElement);//this is overkill, but will be reduces later\n\t\t\tsubArrays[i][0] = firstIndex + i;\n\t\t}\n\n\t\tfor (int i = 0; i < numOfSubTrees; i++) {\n\t\t\tfor (int j = 1; j < totalNodes; j++) {\n\n\t\t\t\tif (j % 2 == 1)\n\t\t\t\t\tsubArrays[i][j] = LEFT(subArrays[i][PAPA(j)]);\n\t\t\t\telse\n\t\t\t\t\tsubArrays[i][j] = RIGHT(subArrays[i][PAPA(j)]);\n\n\n\t\t\t\tif (subArrays[i][j] >= maxElement) {\n\t\t\t\t\tsubArrays[i].resize(j);\n\t\t\t\t\t//cout << \"j is in first loop \" << j << endl;\n\t\t\t\t\tbreak;\n\n\t\t\t\t}\n\n\t\t\t\t//cout << subArrays[i][j] << \"-\";\n\t\t\t}\n\t\t\t//cout << \"size of \"<<i<<\" array\" << subArrays[i].size() << endl;\n\t\t\t//cout << \"-------------------\" << endl;\n\n\t\t}\n\n\t}\n\n\tvoid buildSubTree(ZZ_pX* tree, vector<int> &subTree, ZZ &prime) {\n\t\t\n\t\tZZ_p::init(prime);\n\t\tint index;\n\t\tfor (int i = subTree.size() - 1; i >= 0; i--) {\n\t\t\tindex = subTree[i];\n\n#ifdef fftTest\n\t\t\tFFTMul(tree[index], tree[LEFT(index)], tree[RIGHT(index)]);\n#else\n\t\t\ttree[index] = tree[LEFT(index)] * tree[RIGHT(index)];\n#endif // fftTest\n\n\t\t\t//\n\t\t\t\n\t\t}\n\t}\n\n\tvoid interSubTree(ZZ_pX* temp, ZZ_pX* M, vector<int> &subTree, ZZ &prime) {\n\n\n\t\t//cout<<\"Thread indices\";\n\t\n\n\t\tZZ_p::init(prime);\n\t\tint index;\n\t\tfor (int i = subTree.size() - 1; i >= 0; i--) {\n\t\t\tindex = subTree[i];\n\t\t\t//cout<<\"--\"<<index;\n#ifdef fftTest\n\t\t\tZZ_pX tempfft1;\n\t\t\tFFTMul(tempfft1, temp[LEFT(index)], M[RIGHT(index)]);\n\n\t\t\tZZ_pX tempfft2;\n\t\t\tFFTMul(tempfft2, temp[RIGHT(index)], M[LEFT(index)]);\n\n\t\t\ttemp[index] = tempfft1 + tempfft2;\n#else\n\t\t\ttemp[index] = temp[LEFT(index)] * M[RIGHT(index)] + temp[RIGHT(index)] * M[LEFT(index)];\n#endif // fftTest\n\n\t\t\t\n\n\t\t}\n\n\t}\n\n\tvoid evalSubTree(ZZ_pX* reminders, ZZ_pX* tree, vector<int> &subTree, ZZ &prime) {\n\n\n\t\t//cout<<\"Thread indices\";\n\t\tZZ_p::init(prime);\n\t\tint index;\n\n\t\tunsigned int i = 1;\n\t\tfor (i = 0; i < subTree.size(); i++) {\n\t\t\tindex = subTree[i];\n\t\t\t//        cout << \"i=\"<<i <<\": \";\n\t\t\t//\n#ifdef fftTest\n\t\t\tFFTRem(reminders[index], reminders[PAPA(index)], tree[index]);\n#else\n\t\t\treminders[index] = reminders[PAPA(index)] % tree[index];\n#endif\n\t\t}\n\n\t}\n\n\tvoid test_tree(ZZ_pX& final_polynomial, ZZ_p* points, unsigned int npoints) {\n\t\tZZ_p result;\n\t\tbool error = false;\n\t\tfor (unsigned int i = 0; i < npoints; i++) {\n\t\t\tresult = eval(final_polynomial, points[i]);\n\t\t\tif (0 != result) {\n\t\t\t\tcout << \"FATAL ERROR: polynomials tree is incorrect!\" << endl;\n\t\t\t\terror = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!error)\n\t\t\tcout << \"polynomials tree is correct.\" << endl;\n\t}\n\n\tvoid evaluate_main(ZZ_pX& P, ZZ_pX* tree, ZZ_pX* reminders, unsigned int tree_size, ZZ_p* results) {\n\n\t\treminders[0] = P%tree[0];\n\n\t\tunsigned int i = 1;\n\t\tfor (; i < tree_size / 2; i++) {\n\t\t\treminders[i] = reminders[PAPA(i)] % tree[i];\n\t\t}\n\n\t\tunsigned int result_index;\n\t\tfor (; i < tree_size; i++) {\n\t\t\treminders[i] = reminders[PAPA(i)] % tree[i];\n\t\t\tresult_index = i - (tree_size - 1) / 2;\n\t\t\tresults[result_index] = coeff(reminders[i], 0);\n\t\t}\n\t}\n\n\n\tvoid evaluate(ZZ_pX& P, ZZ_pX* tree, ZZ_pX* reminders, unsigned int tree_size, ZZ_p* results, int numThreads, ZZ &prime) {\n\n\t\tauto begin1 = steady_clock::now();\n\t\t//set the reminder of the root\n\t\t//reminders[0] = P%tree[0];\n\t\treminders[0] = P;\n\t\treminders[1] = P;\n\t\treminders[2] = P;\n\n\n\t\tauto end1 = steady_clock::now();\n\t\t//cout << \"eval - not paralleled \"<<\" threads \" << duration_cast<milliseconds>(end1 - begin1).count() << \" ms\" << endl;\n\n\t\t//    print_poly(tree[0]);\n\t\t//\n\t\t//    cout<<endl<<\"---Reminder\"<<endl;\n\t\t//    print_poly(reminders[0]);\n\t\t//\n\t\t//    cout<<endl<<\"---P\"<<endl;\n\t\t//    print_poly(P);\n\n\n\t\tbegin1 = steady_clock::now();\n\t\tvector<vector<int>> subs(numThreads);\n\t\tgenerateSubTreeArrays(subs, tree_size, numThreads - 1);\n\t\tend1 = steady_clock::now();\n\t\t//cout << \"eval - generate sub trees: \" << duration_cast<milliseconds>(end1 - begin1).count() << \" ms\" << endl;\n\n\n\t\tbegin1 = steady_clock::now();\n\t\tvector<thread> threadsFirstPart(numThreads * 2);\n\n\t\tfor (int i = 2; i < log2(numThreads); i++) {\n\t\t\t//cout<<\"layer \"<<i<< \" : \" <<endl;\n\t\t\tfor (int j = pow(2, i) - 1; j <= pow(2, i + 1) - 2; j++) {\n\t\t\t\t//cout<<\" index to process is \"<< j<<endl;\n\n\t\t\t\tthreadsFirstPart[j] = thread(&evalReminder, tree, reminders, j, ref(prime));\n\n\t\t\t}\n\n\t\t\tfor (int j = pow(2, i) - 1; j <= pow(2, i + 1) - 2; j++) {\n\t\t\t\t//cout<<\" index join to process is \"<< j<<endl;\n\t\t\t\tthreadsFirstPart[j].join();\n\t\t\t}\n\t\t}\n\n\n\t\tend1 = steady_clock::now();\n\t\t//cout << \"eval - first part for max \"<< numThreads/2<<\" threads \" << duration_cast<milliseconds>(end1 - begin1).count() << \" ms\" << endl;\n\n\n\t\tbegin1 = steady_clock::now();\n\t\tvector<thread> threads(numThreads);\n\n\t\tfor (int t = 0; t < numThreads; t++) {\n\n\t\t\tthreads[t] = thread(&evalSubTree, reminders, tree, ref(subs[t]), ref(prime));\n\n\n\t\t}\n\n\n\t\tfor (int t = 0; t < numThreads; t++) {\n\t\t\tthreads[t].join();\n\t\t}\n\n\t\tend1 = steady_clock::now();\n\t\t//cout << \"eval - thread part for \"<< numThreads<<\" threads \" << duration_cast<milliseconds>(end1 - begin1).count() << \" ms\" << endl;\n\n\t\tbegin1 = steady_clock::now();\n\t\tunsigned int result_index;\n\t\tfor (int i = tree_size / 2; i < tree_size; i++) {\n\t\t\tresult_index = i - (tree_size - 1) / 2;\n\t\t\tresults[result_index] = coeff(reminders[i], 0);\n\t\t}\n\n\t\tend1 = steady_clock::now();\n\t\t//cout << \"eval - assign last part: \" << duration_cast<milliseconds>(end1 - begin1).count() << \" ms\" << endl;\n\n\t}\n\n\tvoid evalReminder(ZZ_pX *tree, ZZ_pX *reminders, int i, ZZ &prime) {\n\t\tZZ_p::init(prime);\n#ifdef fftTest\n\t\tFFTRem(reminders[i], reminders[PAPA(i)], tree[i]);\n#else\n\t\treminders[i] = reminders[PAPA(i)] % tree[i];\n#endif\n\n\t\t\n\t}\n\n\tvoid interSpecific(ZZ_pX *temp, ZZ_pX *M, int i, ZZ &prime) {\n\t\tZZ_p::init(prime);\n\n#ifdef fftTest\n\t\tZZ_pX tempfft1;\n\t\tFFTMul(tempfft1, temp[LEFT(i)], M[RIGHT(i)]);\n\n\t\tZZ_pX tempfft2;\n\t\tFFTMul(tempfft2, temp[RIGHT(i)], M[LEFT(i)]);\n\n\t\ttemp[i] = tempfft1 + tempfft2;\n#else\n\t\ttemp[i] = temp[LEFT(i)] * M[RIGHT(i)] + temp[RIGHT(i)] * M[LEFT(i)];\n#endif // fftTest\n\n\t\t\n\n\t}\n\n\tvoid buildTreeSpecific(ZZ_pX *tree, int i, ZZ &prime) {\n\t\tZZ_p::init(prime);\n\t\t\n#ifdef fftTest\n\t\tFFTMul(tree[i], tree[LEFT(i)], tree[RIGHT(i)]);\n#else\n\t\ttree[i] = tree[LEFT(i)] * tree[RIGHT(i)];\n#endif\n\t}\n\n\n\tvoid test_evaluate(ZZ_pX& P, ZZ_p* points, ZZ_p* results, unsigned int npoints) {\n\t\tbool error = false;\n\t\tfor (unsigned int i = 0; i < npoints; i++) {\n\t\t\tZZ_p y = eval(P, points[i]);\n\t\t\tif (y != results[i]) {\n\t\t\t\tcout << \"y=\" << y << \" and results[i]=\" << results[i] << endl;\n\t\t\t\terror = true;\n\t\t\t}\n\t\t}\n\t\tif (error)\n\t\t\tcout << \"ERROR: evaluation results do not match real evaluation!\" << endl;\n\t\telse\n\t\t\tcout << \"All evaluation results computed correctly!\" << endl;\n\t}\n\n\n\tvoid multipoint_evaluate_zp(ZZ_pX& P, ZZ_p* x, ZZ_p* y, long degree, int numThreads, ZZ &prime)\n\t{\n\t\t//    cout << \"P:\" <<endl; print_poly(P); cout << endl;\n\t\t// we want to evaluate P on 'degree+1' values.\n\t\tZZ_pX* p_tree = new ZZ_pX[degree * 2 + 1];\n\t\tsteady_clock::time_point begin1 = steady_clock::now();\n\t\tbuild_tree(p_tree, x, degree * 2 + 1, numThreads, prime);\n\t\tsteady_clock::time_point end1 = steady_clock::now();\n\t\t//test_tree(p_tree[0], x, degree+1);\n\n\t\tZZ_pX* reminders = new ZZ_pX[degree * 2 + 1];\n\t\tsteady_clock::time_point begin2 = steady_clock::now();\n\t\tevaluate(P, p_tree, reminders, degree * 2 + 1, y, numThreads, prime);\n\t\tchrono::steady_clock::time_point end2 = steady_clock::now();\n\n\n\t\t//cout << \"Building tree: \" << duration_cast<milliseconds>(end1 - begin1).count() << \" ms\" << endl;\n\t\t//cout << \"Evaluating points: \" << duration_cast<milliseconds>(end2 - begin2).count() << \" ms\" << endl;\n\t\t//cout << \"Total: \" << duration_cast<milliseconds>(end1 - begin1).count()+ duration_cast<milliseconds>(end2 - begin2).count() << \" ms\" << endl;\n\n\n\t\t//test_evaluate(P,x,y,10);\n\t}\n\n\n\tvoid test_multipoint_eval_zp(ZZ prime, long degree, int numThreads)\n\t{\n\t\t// init underlying prime field\n\t\tZZ_p::init(ZZ(prime));\n\n\t\t// the given polynomial\n\t\tZZ_pX P;\n\t\trandom(P, degree + 1);\n\t\tSetCoeff(P, degree, random_ZZ_p());\n\n\t\t// evaluation points:\n\t\tZZ_p* x = new ZZ_p[degree + 1];\n\t\tZZ_p* y = new ZZ_p[degree + 1];\n\n\t\tfor (unsigned int i = 0; i <= degree; i++) {\n\t\t\trandom(x[i]);\n\t\t}\n\n\t\tmultipoint_evaluate_zp(P, x, y, degree, numThreads, prime);\n\t}\n\n\n\n\n\t/*\n\t* expects an \"empty\" polynomial 'resultP'\n\t*/\n\tvoid iterative_interpolate_zp_main(ZZ_pX& resultP, ZZ_pX* temp, ZZ_p* y, ZZ_p* a, ZZ_pX* M, unsigned int tree_size)\n\t{\n\t\tint i = tree_size - 1;\n\t\tZZ_p inv_a;\n\t\tunsigned int y_index;\n\t\tfor (; i >= tree_size / 2; i--) {\n\t\t\ty_index = i - (tree_size - 1) / 2;\n\t\t\tinv(inv_a, a[y_index]); // inv_a = 1/a[y_index]\n\t\t\tSetCoeff(temp[i], 0, y[y_index] * inv_a);\n\t\t}\n\n\t\tfor (; i >= 0; i--) {\n\t\t\ttemp[i] = temp[LEFT(i)] * M[RIGHT(i)] + temp[RIGHT(i)] * M[LEFT(i)];\n\t\t}\n\n\t\tresultP = temp[LEFT(0)] * M[RIGHT(0)] + temp[RIGHT(0)] * M[LEFT(0)];\n\t}\n\n\tvoid iterative_interpolate_zp(ZZ_pX& resultP, ZZ_pX* temp, ZZ_p* y, ZZ_p* a, ZZ_pX* M, unsigned int tree_size, int numThreads, ZZ &prime)\n\t{\n\t\tunsigned int i = tree_size - 1;\n\t\tZZ_p inv_a;\n\t\tunsigned int y_index;\n\t\tfor (; i >= tree_size / 2; i--) {\n\t\t\ty_index = i - (tree_size - 1) / 2;\n\t\t\tinv(inv_a, a[y_index]); // inv_a = 1/a[y_index]\n\t\t\tSetCoeff(temp[i], 0, y[y_index] * inv_a);\n\t\t}\n\n\t\tauto begin1 = steady_clock::now();\n\t\tvector<vector<int>> subs(numThreads);\n\t\tgenerateSubTreeArrays(subs, tree_size / 2, numThreads - 1);\n\t\tauto end1 = steady_clock::now();\n\t\t//cout << \"inter - generate sub trees: \" << duration_cast<milliseconds>(end1 - begin1).count() << \" ms\" << endl;\n\n\n\t\tbegin1 = steady_clock::now();\n\t\tvector<thread> threads(numThreads);\n\n\t\tfor (int t = 0; t < numThreads; t++) {\n\n\t\t\tthreads[t] = thread(&interSubTree, temp, M, ref(subs[t]), ref(prime));\n\n\n\t\t}\n\n\n\t\tfor (int t = 0; t < numThreads; t++) {\n\t\t\tthreads[t].join();\n\t\t}\n\n\t\tend1 = steady_clock::now();\n\t\t//cout << \"interpolate - threads part: \" << duration_cast<milliseconds>(end1 - begin1).count() << \" ms\" << endl;\n\n\n\t\t//    begin1 = steady_clock::now();\n\t\t//    for(int i=numThreads-2; i>0; i--)\n\t\t//        temp[i] = temp[LEFT(i)] * M[RIGHT(i)] + temp[RIGHT(i)] * M[LEFT(i)] ;\n\t\t//\n\t\t//    end1 = steady_clock::now();\n\t\t//    cout << \"inter - first part SERIAL \"<< duration_cast<milliseconds>(end1 - begin1).count() << \" ms\" << endl;\n\t\t//\n\n\n\t\tbegin1 = steady_clock::now();\n\t\tvector<thread> threadsLastPart(numThreads * 2);\n\n\t\tfor (int i = log2(numThreads) - 1; i >= 1; i--) {\n\t\t\t//cout<<\"layer \"<<i<< \" : \" <<endl;\n\t\t\tfor (int j = pow(2, i) - 1; j <= pow(2, i + 1) - 2; j++) {\n\t\t\t\t//cout<<\" index to process is \"<< j<<endl;\n\n\t\t\t\tthreadsLastPart[j] = thread(&interSpecific, temp, M, j, ref(prime));\n\t\t\t}\n\n\t\t\tfor (int j = pow(2, i) - 1; j <= pow(2, i + 1) - 2; j++) {\n\t\t\t\t//cout<<\" index join to process is \"<< j<<endl;\n\t\t\t\tthreadsLastPart[j].join();\n\t\t\t}\n\t\t}\n\n\n\t\tend1 = steady_clock::now();\n\t\t//cout << \"inter - last part for max \"<< numThreads/2<<\" threads \" << duration_cast<milliseconds>(end1 - begin1).count() << \" ms\" << endl;\n\n\n\t\tbegin1 = steady_clock::now();\n\t\t//last iteration\n\t\tresultP = temp[LEFT(0)] * M[RIGHT(0)] + temp[RIGHT(0)] * M[LEFT(0)];\n\n\t\tend1 = steady_clock::now();\n\t\t//cout << \"interpolate - last iteration for root: \" << duration_cast<milliseconds>(end1 - begin1).count() << \" ms\" << endl;\n\n\t}\n\n\n\tvoid interpolate_zp(ZZ_pX& resultP, ZZ_p* x, ZZ_p* y, long degree, int numThreads, ZZ &prime)\n\t{\n\t\tsystem_clock::time_point begin[4];\n\t\tsystem_clock::time_point end[4];\n\t\tZZ_pX *M = new ZZ_pX[degree * 2 + 1];;\n\t\tZZ_p *a = new ZZ_p[degree + 1];;\n\n\t\tprepareForInterpolate(x, degree, M, a, numThreads, prime);\n\n\t\t//now we can apply the formula\n\t\tZZ_pX* temp = new ZZ_pX[degree * 2 + 1];\n\t\titerative_interpolate_zp(resultP, temp, y, a, M, degree * 2 + 1, numThreads, prime);\n\n\n\t\t//cout << \"Interpolation: \" << duration_cast<milliseconds>(end[4] - begin[4]).count() << \" ms\" << endl;\n\t\t//cout << \"Total: \" << duration_cast<milliseconds>(end[1]-begin[1] + end[2]-begin[2] + end[3]-begin[3] + end[4]-begin[4]).count() << \" ms\" << endl;\n\t}\n\n\tvoid prepareForInterpolate(ZZ_p *x, long degree, ZZ_pX *M, ZZ_p *a, int numThreads, ZZ &prime) {\n\n\t\tsystem_clock::time_point begin[4];\n\t\tsystem_clock::time_point end[4];\n\t\tbegin[1] = system_clock::now();\n\t\tbuild_tree(M, x, degree * 2 + 1, numThreads, prime);\n\t\tend[1] = system_clock::now();\n\n\t\tZZ_pX D;\n\t\t//we construct a preconditioned global structure for the a_k for all 1<=k<=(degree+1)ZZ_pX D;\n\t\tbegin[2] = system_clock::now();\n\t\tdiff(D, M[0]);\n\t\tend[2] = system_clock::now();\n\n\t\t//evaluate d(x) to obtain the results in the array a\n\t\tZZ_pX* reminders = new ZZ_pX[degree * 2 + 1];\n\t\tbegin[3] = system_clock::now();\n\t\tevaluate(D, M, reminders, degree * 2 + 1, a, numThreads, prime);\n\t\tend[3] = system_clock::now();\n\t\t//    test_evaluate(D,x,a,degree+1);\n\n\t\t/*cout << \"Building tree: \" << duration_cast<milliseconds>(end[1] - begin[1]).count() << \" ms\" << endl;\n\t\tcout << \"Differentiate: \" << duration_cast<milliseconds>(end[2] - begin[2]).count() << \" ms\" << endl;\n\t\tcout << \"Evaluate diff: \" << duration_cast<milliseconds>(end[3] - begin[3]).count() << \" ms\" << endl;*/\n\n\t}\n\n\n\tvoid test_interpolation_result_zp(ZZ_pX& P, ZZ_p* x, ZZ_p* y, long degree)\n\t{\n\t\tcout << \"Testing result polynomial\" << endl;\n\t\tZZ_p res;\n\t\tfor (long i = 0; i < degree + 1; i++) {\n\t\t\teval(res, P, x[i]);\n\t\t\tif (res != y[i]) {\n\t\t\t\tcout << \"Error! x = \" << x[i] << \", y = \" << y[i] << \", res = \" << res << endl;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tcout << \"Polynomial is interpolated correctly!\" << endl;\n\t}\n\n\tvoid test_interpolate_zp(ZZ prime, long degree, int numThreads)\n\t{\n\t\t// init underlying prime field\n\t\tZZ_p::init(ZZ(prime));\n\n\t\t// interpolation points:\n\t\tZZ_p* x = new ZZ_p[degree + 1];\n\t\tZZ_p* y = new ZZ_p[degree + 1];\n\t\tfor (unsigned int i = 0; i <= degree; i++) {\n\t\t\trandom(x[i]);\n\t\t\trandom(y[i]);\n\t\t}\n\n\t\tZZ_pX P;\n\t\tinterpolate_zp(P, x, y, degree, numThreads, prime);\n\t\t//cout << \"P: \"; print_poly(P); cout << endl;\n\t\t//test_interpolation_result_zp(P, x, y, degree);\n\t}\n\n\n\tvoid BytesToZZ_px(unsigned char *bytesArr, ZZ_pX& poly, long numOfElements, long sizeOfElement) {\n\n\t\t//turn each byte to zz_p element in a vector\n\n\t\tvec_ZZ repFromBytes;\n\t\trepFromBytes.SetLength(numOfElements);\n\n\t\tfor (int i = 0; i < numOfElements; i++) {\n\n\t\t\tZZ zz;\n\n\t\t\t//translate the bytes into a ZZ element\n\t\t\tZZFromBytes(zz, bytesArr + i*sizeOfElement, sizeOfElement);\n\n\t\t\trepFromBytes[i] = zz;\n\t\t}\n\n\n\t\t//turn the vec_zzp to the polynomial\n\n\t\tpoly = to_ZZ_pX(to_vec_ZZ_p(repFromBytes));\n\n\n\t}\n\tvoid ZZ_pxToBytes(ZZ_pX& poly, unsigned char *bytesArr, long numOfElements, long sizeOfElement) {\n\n\t\t//get the zz_p vector\n\n\t\tfor (int i = 0; i < numOfElements; i++) {\n\n\t\t\tBytesFromZZ(bytesArr + i*sizeOfElement, rep(poly.rep[i]), sizeOfElement);\n\t\t}\n\n\n\t}\n}\n", "meta": {"hexsha": "9827f3aab6409813829d3fb03a81978e60460e6b", "size": 16770, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libPaXoS/Poly/polyFFT.cpp", "max_stars_repo_name": "Zhenhanyijiu/psi3_github", "max_stars_repo_head_hexsha": "9ce9eb47fc927dc0d7261672a9550fe35c0c282a", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-23T10:06:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T11:10:02.000Z", "max_issues_repo_path": "libPaXoS/Poly/polyFFT.cpp", "max_issues_repo_name": "Zhenhanyijiu/psi3_github", "max_issues_repo_head_hexsha": "9ce9eb47fc927dc0d7261672a9550fe35c0c282a", "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": "libPaXoS/Poly/polyFFT.cpp", "max_forks_repo_name": "Zhenhanyijiu/psi3_github", "max_forks_repo_head_hexsha": "9ce9eb47fc927dc0d7261672a9550fe35c0c282a", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-15T05:44:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T05:44:29.000Z", "avg_line_length": 26.4511041009, "max_line_length": 149, "alphanum_fraction": 0.6007155635, "num_tokens": 5717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2818573482576779}}
{"text": "/*\n\tCopyright (c) 2019,\tMobile Robots Laboratory:\n\t-Jan Wietrzykowski (jan.wietrzykowski@put.poznan.pl).\n\tPoznan University of Technology\n\tAll rights reserved.\n\n\tRedistribution and use in source and binary forms, with or without modification,\n\tare permitted provided that the following conditions are met:\n\n\t1. Redistributions of source code must retain the above copyright notice,\n\tthis list of conditions and the following disclaimer.\n\n\t2. Redistributions in binary form must reproduce the above copyright notice,\n\tthis list of conditions and the following disclaimer in the documentation\n\tand/or other materials provided with the distribution.\n\n\tTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\tAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\tTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\tARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\tFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\tDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\tLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n\tAND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\tOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\tOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#include <iostream>\n#include <thread>\n#include <random>\n#include <chrono>\n#include <string>\n#include <fstream>\n\n#include <boost/serialization/serialization.hpp>\n#include <boost/serialization/vector.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n\n#include \"pgm/ParamEstSGD.h\"\n#include \"pgm/Exceptions.h\"\n#include \"pgm/Inference.h\"\n\nusing namespace std;\n\nstd::vector<double> ParamEstSGD::estimate(std::shared_ptr<PgmCreator> pgmCreator,\n\t\t\t\t\t\t\t\t\t\tParams estParams,\n\t\t\t\t\t\t\t\t\t\tconst std::vector<double>& initParams)\n{\n\tstatic const int maxThreads = 4;\n\n\tstd::default_random_engine randGen;\n\n\tint m = pgmCreator->getM();\n\n\t//generate random permutation\n\tvector<int> perm;\n\tfor(int i = 0; i < m; ++i){\n\t\tperm.push_back(i);\n\t}\n\tfor(int i = 0; i < m - 1; ++i){\n\t\tstd::uniform_int_distribution<int> dist(i, m - 1);\n\t\tint swapIdx = dist(randGen);\n\t\tint tmp = perm[i];\n\t\tperm[i] = perm[swapIdx];\n\t\tperm[swapIdx] = tmp;\n\t}\n\n\tint mVal = estParams.valSetFrac * perm.size();\n\tvector<int> permVal = vector<int>(perm.begin(), perm.begin() + mVal);\n\n\tint mTrain = perm.size() - mVal;\n\tvector<int> permTrain = vector<int>(perm.begin() + mVal, perm.end());\n\n\tvector<double> curParams = initParams;\n\n\tvector<double> paramsGrad;\n\n\tint iter = 0;\n\tbool stopFlag = false;\n\twhile(!stopFlag){\n\t\tcout << \"iteration \" << iter << endl;\n\t\tcout << \"curParams = \" << curParams << endl;\n\n\t\tdouble curLearnRate = 1 / ((estParams.sigma * estParams.sigma) * (estParams.learnRateM0 + iter));\n\t\tcout << \"curLearnRate = \" << curLearnRate << endl;\n\n\t\t//generate random permutation\n\t\tvector<int> curPerm = permTrain;\n\n\t\tfor(int i = 0; i < mTrain - 1; ++i){\n\t\t\tstd::uniform_int_distribution<int> dist(i, mTrain - 1);\n\t\t\tint swapIdx = dist(randGen);\n\t\t\tint tmp = curPerm[i];\n\t\t\tcurPerm[i] = curPerm[swapIdx];\n\t\t\tcurPerm[swapIdx] = tmp;\n\t\t}\n\n\t\tvector<double> lhoodNumers;\n\t\tvector<double> lhoodDenoms;\n\t\tvector<vector<double>> Efis;\n\t\tvector<vector<double>> Eds;\n\n\t\t//take first n samples\n\t\tevaluateSamples(vector<int>(curPerm.begin(), curPerm.begin() + estParams.n),\n\t\t\t\t\t\tmaxThreads,\n\t\t\t\t\t\tpgmCreator,\n\t\t\t\t\t\tcurParams,\n\t\t\t\t\t\tlhoodNumers,\n\t\t\t\t\t\tlhoodDenoms,\n\t\t\t\t\t\tEfis,\n\t\t\t\t\t\tEds);\n\n\t\tvector<double> curGrad(curParams.size(), 0.0);\n\t\t// compute current gradient\n\t\tfor(int i = 0; i < Efis.size(); ++i){\n\t\t\tfor(int p = 0; p < curGrad.size(); ++p){\n\t\t\t\tcurGrad[p] = Eds[i][p] - Efis[i][p];\n\t\t\t}\n\t\t}\n\t\tfor(int p = 0; p < curGrad.size(); ++p){\n\t\t\tcurGrad[p] /= Efis.size();\n\t\t}\n\t\tfor(int p = 0; p < curGrad.size(); ++p){\n\t\t\tcurGrad[p] -= curParams[p] / (estParams.sigma * estParams.sigma);\n\t\t}\n\n\t\tcout << \"curGrad = \" << curGrad << endl;\n\n\t\t// if it is first iteration and previous gradient is empty\n\t\tif(paramsGrad.empty()){\n\t\t\tparamsGrad = curGrad;\n\t\t}\n\n\t\tfor(int p = 0; p < paramsGrad.size(); ++p){\n\t\t\tparamsGrad[p] = curLearnRate * (paramsGrad[p]*estParams.momentum + curGrad[p]);\n\t\t}\n\n\t\tfor(int p = 0; p < curParams.size(); ++p){\n\t\t\tcurParams[p] += paramsGrad[p];\n\t\t}\n\n\n\t\t//evaluate on validation set\n\t\tif(iter % 10 == 0){\n\t\t\tdouble scoreVal = 0.0;\n\n\t\t\tvector<double> lhoodNumers;\n\t\t\tvector<double> lhoodDenoms;\n\t\t\tvector<vector<double>> Efis;\n\t\t\tvector<vector<double>> Eds;\n\n\t\t\t//take first n samples\n\t\t\tevaluateSamples(permVal,\n\t\t\t\t\t\t\tmaxThreads,\n\t\t\t\t\t\t\tpgmCreator,\n\t\t\t\t\t\t\tcurParams,\n\t\t\t\t\t\t\tlhoodNumers,\n\t\t\t\t\t\t\tlhoodDenoms,\n\t\t\t\t\t\t\tEfis,\n\t\t\t\t\t\t\tEds);\n\n\t\t\tfor(int i = 0; i < lhoodNumers.size(); ++i){\n\t\t\t\tcout << \"scoreVal += \" << lhoodNumers[i] << \" - \" << lhoodDenoms[i] << endl;\n\t\t\t\tscoreVal += lhoodNumers[i] - lhoodDenoms[i];\n\t\t\t}\n\t\t\tscoreVal /= lhoodNumers.size();\n\n\t\t\tcout << endl << endl << \"scoreVal = \" << scoreVal << endl << endl << endl;\n\n\t\t\t//saving a snapshot\n\t\t\t{\n\t\t\t\tofstream paramsFile(string(\"log/params_\") + to_string(iter));\n\t\t\t\tboost::archive::text_oarchive paramsArch(paramsFile);\n\t\t\t\tparamsArch << curParams;\n\t\t\t}\n\t\t\t{\n\t\t\t\tofstream gradFile(string(\"log/grad_\") + to_string(iter));\n\t\t\t\tboost::archive::text_oarchive gradArch(gradFile);\n\t\t\t\tgradArch << curGrad;\n\t\t\t}\n\t\t\t{\n\t\t\t\tofstream scoreFile(string(\"log/score\"), ios::app);\n\t\t\t\tscoreFile << iter << \" \" << scoreVal << endl;\n\t\t\t}\n\t\t}\n\n\t\t//stop condition\n\t\t//TODO use better stop condition\n\t\tif(curLearnRate < 0.005){\n\t\t\tstopFlag = true;\n\t\t}\n\n\t\titer++;\n\t}\n\n\treturn curParams;\n}\n\nvoid ParamEstSGD::evaluateSamples(const std::vector<int>& sampIdxs,\n\t\t\t\t\t\t\tint maxThreads,\n\t\t\t\t\t\t\tstd::shared_ptr<PgmCreator> pgmCreator,\n\t\t\t\t\t\t\tconst std::vector<double>& curParams,\n\t\t\t\t\t\t\tstd::vector<double>& lhoodNumers,\n\t\t\t\t\t\t\tstd::vector<double>& lhoodDenoms,\n\t\t\t\t\t\t\tstd::vector<std::vector<double>>& Efis,\n\t\t\t\t\t\t\tstd::vector<std::vector<double>>& Eds)\n{\n\tint threadCnt = 0;\n\tvector<shared_ptr<ParamEstSGD::EvaluateThread>> threads(sampIdxs.size());\n\tvector<shared_ptr<Pgm>> pgms(sampIdxs.size());\n\tvector<shared_ptr<vector<double>>> obsVecs(sampIdxs.size());\n\tvector<shared_ptr<vector<double>>> varVals(sampIdxs.size());\n\tvector<shared_ptr<vector<int>>> varIds(sampIdxs.size());\n\tvector<shared_ptr<vector<double>>> paramVals(sampIdxs.size());\n\tlhoodNumers.resize(sampIdxs.size());\n\tlhoodDenoms.resize(sampIdxs.size());\n\tEfis.resize(sampIdxs.size());\n\tEds.resize(sampIdxs.size());\n\n\t//take first n elements from permutation\n\tfor(int i = 0; i < sampIdxs.size(); ++i){\n\t\twhile(threadCnt == maxThreads){\n\t\t\tendThreadIfAny(threadCnt,\n\t\t\t\t\t\t\tthreads,\n\t\t\t\t\t\t\tpgms,\n\t\t\t\t\t\t\tobsVecs,\n\t\t\t\t\t\t\tvarVals,\n\t\t\t\t\t\t\tvarIds,\n\t\t\t\t\t\t\tparamVals);\n\n\t\t\tstd::this_thread::sleep_for(chrono::milliseconds(50));\n\t\t}\n\n\t\tpgms[i] = shared_ptr<Pgm>(new Pgm);\n\t\tobsVecs[i] = shared_ptr<vector<double>>(new vector<double>());\n\t\tvarVals[i] = shared_ptr<vector<double>>(new vector<double>());\n\t\tvarIds[i] = shared_ptr<vector<int>>(new vector<int>());\n\t\tparamVals[i] = shared_ptr<vector<double>>(new vector<double>(curParams));\n\t\tlhoodNumers[i] = 0.0;\n\t\tlhoodDenoms[i] = 0.0;\n\t\tEfis[i] = vector<double>(curParams.size(), 0.0);\n\t\tEds[i] = vector<double>(curParams.size(), 0.0);\n\n\t\tpgmCreator->create(sampIdxs[i],\n\t\t\t\t\t\t*pgms[i],\n\t\t\t\t\t\t*obsVecs[i],\n\t\t\t\t\t\t*varVals[i],\n\t\t\t\t\t\t*varIds[i]);\n\n//\t\tfor(int j = 0; j < Efis.size(); ++j){\n//\t\t\tcout << \"Efis[\" << j << \"].data() = \" << Efis[j].data() << endl;\n//\t\t\tcout << \"&Efis[\" << j << \"] = \" << &Efis[j] << endl;\n//\t\t}\n\n\t\tthreads[i] = shared_ptr<EvaluateThread>(new EvaluateThread(pgms[i],\n\t\t\t\t\t\t\t\t\t\t\t\tobsVecs[i],\n\t\t\t\t\t\t\t\t\t\t\t\tvarVals[i],\n\t\t\t\t\t\t\t\t\t\t\t\tvarIds[i],\n\t\t\t\t\t\t\t\t\t\t\t\tparamVals[i],\n\t\t\t\t\t\t\t\t\t\t\t\tlhoodNumers[i],\n\t\t\t\t\t\t\t\t\t\t\t\tlhoodDenoms[i],\n\t\t\t\t\t\t\t\t\t\t\t\tEfis[i],\n\t\t\t\t\t\t\t\t\t\t\t\tEds[i]));\n\t\t++threadCnt;\n\t}\n\n\twhile(threadCnt > 0){\n\t\tendThreadIfAny(threadCnt,\n\t\t\t\t\t\tthreads,\n\t\t\t\t\t\tpgms,\n\t\t\t\t\t\tobsVecs,\n\t\t\t\t\t\tvarVals,\n\t\t\t\t\t\tvarIds,\n\t\t\t\t\t\tparamVals);\n\t\tstd::this_thread::sleep_for(chrono::milliseconds(50));\n\t}\n}\n\n\nvoid ParamEstSGD::endThreadIfAny(int& threadCnt,\n\t\t\t\t\t\tstd::vector<std::shared_ptr<ParamEstSGD::EvaluateThread>>& threads,\n\t\t\t\t\t\tstd::vector<std::shared_ptr<Pgm>>& pgms,\n\t\t\t\t\t\tstd::vector<std::shared_ptr<std::vector<double>>>& obsVecs,\n\t\t\t\t\t\tstd::vector<std::shared_ptr<std::vector<double>>>& varVals,\n\t\t\t\t\t\tstd::vector<std::shared_ptr<std::vector<int>>>& varIds,\n\t\t\t\t\t\tstd::vector<std::shared_ptr<std::vector<double>>>& paramVals)\n{\n\tfor(int t = 0; t < threads.size(); ++t){\n\t\tif(threads[t]){\n\t\t\tif(threads[t]->hasFinished()){\n\t\t\t\tcout << \"Ending thread \" << t << endl;\n\t\t\t\tthreads[t].reset();\n\t\t\t\tpgms[t].reset();\n\t\t\t\tobsVecs[t].reset();\n\t\t\t\tvarVals[t].reset();\n\t\t\t\tvarIds[t].reset();\n\t\t\t\tparamVals[t].reset();\n\n\t\t\t\t--threadCnt;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nParamEstSGD::EvaluateThread::EvaluateThread(std::shared_ptr<Pgm> ipgm,\n\t\t\t\t\t\t\t\t\t\tstd::shared_ptr<const std::vector<double>> iobsVec,\n\t\t\t\t\t\t\t\t\t\tstd::shared_ptr<const std::vector<double>> ivarVals,\n\t\t\t\t\t\t\t\t\t\tstd::shared_ptr<const std::vector<int>> ivarIds,\n\t\t\t\t\t\t\t\t\t\tstd::shared_ptr<const std::vector<double>> iparamVals,\n\t\t\t\t\t\t\t\t\t\tdouble& ilhoodNumer,\n\t\t\t\t\t\t\t\t\t\tdouble& ilhoodDenom,\n\t\t\t\t\t\t\t\t\t\tstd::vector<double>& iEfi,\n\t\t\t\t\t\t\t\t\t\tstd::vector<double>& iEd)\n\t\t: pgm(ipgm),\n\t\t  obsVec(iobsVec),\n\t\t  varVals(ivarVals),\n\t\t  varIds(ivarIds),\n\t\t  paramVals(iparamVals),\n\t\t  lhoodNumer(ilhoodNumer),\n\t\t  lhoodDenom(ilhoodDenom),\n\t\t  Efi(iEfi),\n\t\t  Ed(iEd),\n\t\t  finishedFlag(false)\n{\n//\tcout << \"Efi.data() constr = \" << Efi.data() << \", this = \" << this << endl;\n//\tcout << \"&Efi constr = \" << &Efi << \", this = \" << this << endl;\n\trunThread = thread(&ParamEstSGD::EvaluateThread::run, this);\n}\n\nParamEstSGD::EvaluateThread::~EvaluateThread()\n{\n\tif(runThread.joinable()){\n\t\trunThread.join();\n\t}\n}\n\nbool ParamEstSGD::EvaluateThread::hasFinished()\n{\n\treturn finishedFlag;\n}\n\nvoid ParamEstSGD::EvaluateThread::run()\n{\n\t// inference without clamped variables - denominator and model expectation\n\t{\n//\t\tcout << \"Efi.data() 1 = \" << Efi.data() << \", this = \" << this <<  endl;\n//\t\tcout << \"&Efi 1 = \" << &Efi << \", this = \" << this << endl;\n\n\t\tvector<vector<double>> marg;\n\t\tvector<vector<vector<double>>> msgs;\n\t\tdouble logPartFunc;\n\n//\t\tcout << \"Efi.data() 2 = \" << Efi.data() << \", this = \" << this << endl;\n\t\tbool calibrated = Inference::compMarginalsParam(*pgm, marg, logPartFunc, msgs, *paramVals, *obsVec);\n//\t\tcout << \"Efi.data() 3 = \" << Efi.data() << endl;\n\n\t\tif(!calibrated){\n\t\t\tcout << \"Warning - inference without clamped variables didn't calibrate\" << endl;\n\t\t}\n\n\t\tlhoodDenom = logPartFunc;\n\t\tcout << \"loodDenom = \" << lhoodDenom << endl;\n\n\t\tfor(int c = 0; c < (int)pgm->constClusters().size(); ++c){\n//\t\t\tcout << \"Cluster \" << c << endl;\n\t\t\tstd::shared_ptr<Cluster> curCluster = pgm->clusters()[c];\n//\t\t\tcout << \"curCluster->id() = \" << curCluster->id() << endl;\n\t\t\tconst vector<vector<double> >& curClustMsgs = msgs[curCluster->id()];\n//\t\t\tcout << \"curClustMsgs = \" << curClustMsgs << endl;\n\t\t\tvector<double> curEfi = curCluster->compSumModelExpectation(curClustMsgs, *paramVals, *obsVec);\n//\t\t\tcout << \"Efi.size() = \" << Efi.size() << \", curEfi.size() = \" << curEfi.size() << endl;\n\n\t\t\tfor(int f = 0; f < (int)curCluster->feats().size(); ++f){\n//\t\t\t\tcout << \"f = \" << f << endl;\n\t\t\t\tint paramNum = curCluster->feats()[f]->paramNum();\n//\t\t\t\tcout << \"paramNum = \" << paramNum << endl;\n\t\t\t\tEfi[paramNum] += curEfi[f];\n\t\t\t}\n\t\t}\n\t}\n\n\t// clamping variables\n//\tcout << \"clamping variables\" << endl;\n\tint posRv = 0;\n\tfor(int v = 0; v < varIds->size(); ++v){\n\t\tbool stopFlag = false;\n\t\twhile(!stopFlag && posRv < pgm->randVars().size() - 1){\n\t\t\tif(pgm->randVars()[posRv]->id() < varIds->at(v)){\n\t\t\t\t++posRv;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tstopFlag = true;\n\t\t\t}\n\t\t}\n\t\tif(pgm->randVars()[posRv]->id() == varIds->at(v)){\n\t\t\tpgm->randVars()[posRv]->makeObserved(varVals->at(v));\n\t\t}\n\t\telse{\n\t\t\tcout << \"pgm->randVars()[posRv]->id() = \" << pgm->randVars()[posRv]->id() << endl;\n\t\t\tcout << \"varIds->at(v) = \" << varIds->at(v) << endl;\n\t\t\tthrow PGM_EXCEPTION(\"Rand var not found\");\n\t\t}\n\t}\n//\tcout << \"end clamping variables\" << endl;\n\n\t// inference with clamped variables - numerator and distribution expectation\n\t{\n\t\tvector<vector<double>> margClamp;\n\t\tvector<vector<vector<double>>> msgsClamp;\n\t\tdouble logPartFuncClamp;\n\n\t\tbool calibratedClamp = Inference::compMarginalsParam(*pgm, margClamp, logPartFuncClamp, msgsClamp, *paramVals, *obsVec);\n\n\t\tif(!calibratedClamp){\n\t\t\tcout << \"Warning - inference with clamped variables didn't calibrate\" << endl;\n\t\t}\n\n\t\tlhoodNumer = logPartFuncClamp;\n\t\tcout << \"loodNumer = \" << lhoodNumer << endl;\n\n\t\t// a model expectation with clamped variables is a distribution expectation\n\t\tfor(int c = 0; c < (int)pgm->constClusters().size(); ++c){\n//\t\t\tcout << \"Cluster \" << c << endl;\n\t\t\tstd::shared_ptr<Cluster> curCluster = pgm->clusters()[c];\n\t\t\tconst vector<vector<double> >& curClustMsgs = msgsClamp[curCluster->id()];\n\t\t\tvector<double> curEfi = curCluster->compSumModelExpectation(curClustMsgs, *paramVals, *obsVec);\n\n\t\t\tfor(int f = 0; f < (int)curCluster->feats().size(); ++f){\n\t\t\t\tint paramNum = curCluster->feats()[f]->paramNum();\n\t\t\t\tEd[paramNum] += curEfi[f];\n\t\t\t}\n\t\t}\n\t}\n\n\tfinishedFlag = true;\n}\n\n", "meta": {"hexsha": "1eb3bb96db7954a60c0843b7b36df69b54c531af", "size": 13251, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pgm/ParamEstSGD.cpp", "max_stars_repo_name": "LRMPUT/wifiSeq", "max_stars_repo_head_hexsha": "f6137839b1967075b98758fda1178af55c24048d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-10-27T07:03:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T10:14:48.000Z", "max_issues_repo_path": "src/pgm/ParamEstSGD.cpp", "max_issues_repo_name": "LRMPUT/wifiSeq", "max_issues_repo_head_hexsha": "f6137839b1967075b98758fda1178af55c24048d", "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/pgm/ParamEstSGD.cpp", "max_forks_repo_name": "LRMPUT/wifiSeq", "max_forks_repo_head_hexsha": "f6137839b1967075b98758fda1178af55c24048d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-09-23T15:31:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T10:28:24.000Z", "avg_line_length": 30.0476190476, "max_line_length": 122, "alphanum_fraction": 0.6388951777, "num_tokens": 3877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2817549391638546}}
{"text": "//  Copyright John Maddock 2008.\n//  Copyright Paul A. Bristow 2016\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#ifdef _MSC_VER\n#  pragma warning (disable : 4127) // conditional expression is constant\n#  pragma warning (disable : 4180) // qualifier applied to function type has no meaning; ignored\n#  pragma warning (disable : 4503) // decorated name length exceeded, name was truncated\n#  pragma warning (disable : 4512) // assignment operator could not be generated\n#  pragma warning (disable : 4224) // nonstandard extension used : formal parameter 'function_ptr' was previously defined as a type\n#endif\n\n// #define BOOST_SVG_DIAGNOSTICS // define to provide diagnostic output from plotting.\n\n#include <boost/math/special_functions.hpp>\n#include <boost/math/tools/roots.hpp>\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\n#include <list>\n#include <map>\n#include <string>\n#include <boost/svg_plot/svg_2d_plot.hpp>\n#include <boost/svg_plot/show_2d_settings.hpp>\n\nclass function_arity1_plotter\n{\npublic:\n   function_arity1_plotter() : m_min_x(0), m_max_x(0), m_min_y(0), m_max_y(0), m_has_legend(false) {}\n\n   //! Add a function to the plotter, compute the axes using range a to b and compute & add data points to map. \n  \n   void add(boost::function<double(double)> f, double x_lo, double x_hi, const std::string& name)\n   {\n     std::cout << \"Adding function \" << name << \", x range \" << x_lo << \" to \" << x_hi << std::endl;\n      if(name.size())\n         m_has_legend = true;\n      //\n      // Now set our x-axis limits:\n      if(m_max_x == m_min_x)\n      {\n         m_max_x = x_hi;\n         m_min_x = x_lo;\n      }\n      else\n      {\n         if(x_lo < m_min_x)\n            m_min_x = x_lo;\n         if(x_hi > m_max_x)\n            m_max_x = x_hi;\n      }\n      m_points.push_back(std::pair<std::string, std::map<double,double> >(name, std::map<double,double>()));\n      std::map<double,double>& points = m_points.rbegin()->second;\n      double interval = (x_hi - x_lo) / 200;\n      for(double x = x_lo; x <= x_hi; x += interval)\n      {\n         double y = f(x); // Evaluate the function.\n         // Set the Y axis limits if needed.\n         if((m_min_y == m_max_y) && (m_min_y == 0))\n            m_min_y = m_max_y = y;\n         if(m_min_y > y)\n            m_min_y = y;\n         if(m_max_y < y)\n            m_max_y = y;\n         points[x] = y; // Store the pair of points values.\n      } // for x\n\n#ifdef BOOST_SVG_DIAGNOSTICS\n  std::cout << \"Added function \" << name \n    << \", x range \" << x_lo << \" to \" << x_hi \n    << \", x min = \" << m_min_x << \", x max = \" << m_max_x\n    << \", y min = \" << m_min_y << \", y max = \" << m_max_y\n    << \", interval = \" << interval\n    << std::endl;\n#endif\n   } // void add(boost::function<double(double)> f, double a, double b, const std::string& name)\n\n   //! Compute x and y min and max from a map of pre-computed data points.\n   void add(const std::map<double, double>& m, const std::string& name)\n   {\n     if (name.size() != 0)\n     {\n       m_has_legend = true;\n     }\n      m_points.push_back(std::pair<std::string, std::map<double,double> >(name, m));\n\n      std::map<double, double>::const_iterator i = m.begin();\n      while(i != m.end())\n      {\n         if((m_min_x == m_min_y) && (m_min_y == 0))\n         {\n            m_min_x = m_max_x = i->first;\n         }\n         if(i->first < m_min_x)\n         {\n            m_min_x = i->first;\n         }\n         if(i->first > m_max_x)\n         {\n            m_max_x = i->first;\n         }\n\n         if((m_min_y == m_max_y) && (m_min_y == 0))\n         {\n            m_min_y = m_max_y = i->second;\n         }\n         if(i->second < m_min_y)\n         {\n            m_min_y = i->second;\n         }\n         if(i->second > m_max_y)\n         {\n            m_max_y = i->second;\n         }\n\n         ++i;\n      }\n   } // void add(const std::map<double, double>& m, const std::string& name)\n\n   //! Plot pre-computed m_points data for function.\n   void plot(const std::string& title, const std::string& file,\n      const std::string& x_lable = std::string(), const std::string& y_lable = std::string())\n   {\n      using namespace boost::svg;\n\n      static const svg_color colors[5] = \n      { // Colors for plot curves, used in turn.\n         darkblue,\n         darkred,\n         darkgreen,\n         darkorange,\n         chartreuse\n      };\n\n      std::cout << \"Plotting Special Function \" << title << \" to file \" << file << std::endl;\n\n      svg_2d_plot plot;\n      plot.image_x_size(600);\n      plot.image_y_size(400);\n      plot.copyright_holder(\"John Maddock\").copyright_date(\"2008\").boost_license_on(true);\n      plot.coord_precision(4); // Could be 3 for smaller plots?\n      plot.title(title).title_font_size(20).title_on(true);\n      plot.legend_on(m_has_legend);\n\n      double x_delta = (m_max_x - m_min_x) / 50;\n      double y_delta = (m_max_y - m_min_y) / 50;\n      plot.x_range(m_min_x, m_max_x + x_delta)\n         .y_range(m_min_y, m_max_y + y_delta);\n      plot.x_label_on(true).x_label(x_lable);\n      plot.y_label_on(true).y_label(y_lable);\n      plot.y_major_grid_on(false).x_major_grid_on(false);\n      plot.x_num_minor_ticks(3);\n      plot.y_num_minor_ticks(3);\n      //\n      // Work out axis tick intervals:\n      double l = std::floor(std::log10((m_max_x - m_min_x) / 10) + 0.5);\n      double interval = std::pow(10.0, (int)l);\n      if(((m_max_x - m_min_x) / interval) > 10)\n         interval *= 5;\n      plot.x_major_interval(interval);\n      l = std::floor(std::log10((m_max_y - m_min_y) / 10) + 0.5);\n      interval = std::pow(10.0, (int)l);\n      if(((m_max_y - m_min_y) / interval) > 10)\n         interval *= 5;\n      plot.y_major_interval(interval);\n      plot.plot_window_on(true);\n      plot.plot_border_color(lightslategray)\n          .background_border_color(lightslategray)\n          .legend_border_color(lightslategray)\n          .legend_background_color(white);\n\n      int color_index = 0; // Cycle through the colors for each curve.\n\n      for(std::list<std::pair<std::string, std::map<double,double> > >::const_iterator i = m_points.begin();\n         i != m_points.end(); ++i)\n      {\n         plot.plot(i->second, i->first)\n            .line_on(true)\n            .line_color(colors[color_index])\n            .line_width(1.)\n            .shape(none);\n         if(i->first.size())\n            ++color_index;\n         color_index = color_index % (sizeof(colors)/sizeof(colors[0]));\n      }\n      plot.write(file);\n   } //    void plot(const std::string& title, const std::string& file,\n\n   void clear()\n   {\n      m_points.clear();\n      m_min_x = m_min_y = m_max_x = m_max_y = 0;\n      m_has_legend = false;\n   } // clear\n\nprivate:\n   std::list<std::pair<std::string, std::map<double, double> > > m_points;\n   double m_min_x, m_max_x, m_min_y, m_max_y;\n   bool m_has_legend;\n};\n\ntemplate <class F>\nstruct location_finder\n{\n   location_finder(F _f, double t, double x0) : f(_f), target(t), x_off(x0){}\n\n   double operator()(double x)\n   {\n      try\n      {\n         return f(x + x_off) - target;\n      }\n      catch(const std::overflow_error&)\n      {\n         return boost::math::tools::max_value<double>();\n      }\n      catch(const std::domain_error&)\n      {\n         if(x + x_off == x_off)\n            return f(x_off + boost::math::tools::epsilon<double>() * x_off);\n         throw;\n      }\n   }\n\nprivate:\n   F f;\n   double target;\n   double x_off;\n};\n\ntemplate <class F>\ndouble find_end_point(F f, double x0, double target, bool rising, double x_off = 0)\n{\n   boost::math::tools::eps_tolerance<double> tol(50);\n   boost::uintmax_t max_iter = 1000;\n   return x_off + boost::math::tools::bracket_and_solve_root(\n      location_finder<F>(f, target, x_off), \n      x0, \n      1.5, \n      rising, \n      tol, \n      max_iter).first;\n}\n\ndouble sqrt1pm1(double x)\n{\n   return boost::math::sqrt1pm1(x);\n}\n\ndouble lbeta(double a, double b)\n{\n   return std::log(boost::math::beta(a, b));\n}\n\nint main()\n{\n  try\n  {\n    function_arity1_plotter plot;\n\n    // Functions may have varying numbers and types of parameters.\n    // plot.add calls must use the appropriate function type.\n    // Not all function types may be used, so can ignore any warning like \n    // \"C4101: 'f4': unreferenced local variable\"\n    double(*f)(double); // Simplest function type, suits most functions.\n    double(*f2)(double, double);\n    double(*f2u)(unsigned, double);\n    double(*f2i)(int, double);\n    double(*f3)(double, double, double);\n    double(*f4)(double, double, double, double);\n    double max_val; // Hold evaluated value of function for use in find_end_point.\n\n       f = boost::math::zeta;\n       plot.add(f, find_end_point(f, 0.1, 40.0, false, 1.0), 10, \"\");\n       plot.add(f, -20, find_end_point(f, -0.1, -40.0, false, 1.0), \"\");\n       plot.plot(\"Zeta Function Over [-20,10]\", \"zeta1.svg\", \"z\", \"zeta(z)\");\n\n       plot.clear();\n       plot.add(f, -14, 0, \"\");\n       plot.plot(\"Zeta Function Over [-14,0]\", \"zeta2.svg\", \"z\", \"zeta(z)\");\n\n       f = boost::math::tgamma;\n       max_val = f(6);\n       plot.clear();\n       plot.add(f, find_end_point(f, 0.1, max_val, false), 6, \"\");\n       plot.add(f, find_end_point(f, 0.1, -max_val, true, -1), find_end_point(f, -0.1, -max_val, false), \"\");\n       plot.add(f, find_end_point(f, 0.1, max_val, false, -2), find_end_point(f, -0.1, max_val, true, -1), \"\");\n       plot.add(f, find_end_point(f, 0.1, -max_val, true, -3), find_end_point(f, -0.1, -max_val, false, -2), \"\");\n       plot.add(f, find_end_point(f, 0.1, max_val, false, -4), find_end_point(f, -0.1, max_val, true, -3), \"\");\n       plot.plot(\"tgamma\", \"tgamma.svg\", \"z\", \"tgamma(z)\");\n\n       f = boost::math::lgamma;\n       max_val = f(10);\n       plot.clear();\n       plot.add(f, find_end_point(f, 0.1, max_val, false), 10, \"\");\n       plot.add(f, find_end_point(f, 0.1, max_val, false, -1), find_end_point(f, -0.1, max_val, true), \"\");\n       plot.add(f, find_end_point(f, 0.1, max_val, false, -2), find_end_point(f, -0.1, max_val, true, -1), \"\");\n       plot.add(f, find_end_point(f, 0.1, max_val, false, -3), find_end_point(f, -0.1, max_val, true, -2), \"\");\n       plot.add(f, find_end_point(f, 0.1, max_val, false, -4), find_end_point(f, -0.1, max_val, true, -3), \"\");\n       plot.add(f, find_end_point(f, 0.1, max_val, false, -5), find_end_point(f, -0.1, max_val, true, -4), \"\");\n       plot.plot(\"lgamma\", \"lgamma.svg\", \"z\", \"lgamma(z)\");\n\n       f = boost::math::digamma;\n       max_val = 10;\n       plot.clear();\n       plot.add(f, find_end_point(f, 0.1, -max_val, true), 10, \"\");\n       plot.add(f, find_end_point(f, 0.1, -max_val, true, -1), find_end_point(f, -0.1, max_val, true), \"\");\n       plot.add(f, find_end_point(f, 0.1, -max_val, true, -2), find_end_point(f, -0.1, max_val, true, -1), \"\");\n       plot.add(f, find_end_point(f, 0.1, -max_val, true, -3), find_end_point(f, -0.1, max_val, true, -2), \"\");\n       plot.add(f, find_end_point(f, 0.1, -max_val, true, -4), find_end_point(f, -0.1, max_val, true, -3), \"\");\n      plot.plot(\"digamma\", \"digamma.svg\", \"z\", \"digamma(z)\");\n     \n\n      f = boost::math::erf;\n      plot.clear();\n      plot.add(f, -3, 3, \"erf\");\n      plot.plot(\"erf\", \"erf.svg\", \"z\", \"erf(z)\");\n\n      f = boost::math::erfc;\n      plot.clear();\n      plot.add(f, -3, 3, \"erfc\");\n      plot.plot(\"erfc\", \"erfc.svg\", \"z\", \"erfc(z)\");\n\n    f = boost::math::erf_inv;\n    plot.clear();\n    plot.add(f, find_end_point(f, 0.1, -3, true, -1), find_end_point(f, -0.1, 3, true, 1), \"\");\n    plot.plot(\"erf_inv\", \"erf_inv.svg\", \"z\", \"erf_inv(z)\");\n    f = boost::math::erfc_inv;\n    plot.clear();\n    plot.add(f, find_end_point(f, 0.1, 3, false), find_end_point(f, -0.1, -3, false, 2), \"\");\n    plot.plot(\"erfc_inv\", \"erfc_inv.svg\", \"z\", \"erfc_inv(z)\");\n\n    f = boost::math::log1p;\n    plot.clear();\n    plot.add(f, find_end_point(f, 0.1, -10, true, -1), 10, \"\");\n    plot.plot(\"log1p\", \"log1p.svg\", \"z\", \"log1p(z)\");\n\n    f = boost::math::expm1;\n    plot.clear();\n    plot.add(f, -4, 2, \"\");\n    plot.plot(\"expm1\", \"expm1.svg\", \"z\", \"expm1(z)\");\n\n    f = boost::math::cbrt;\n    plot.clear();\n    plot.add(f, -10, 10, \"\");\n    plot.plot(\"cbrt\", \"cbrt.svg\", \"z\", \"cbrt(z)\");\n\n    f = sqrt1pm1;\n    plot.clear();\n    plot.add(f, find_end_point(f, 0.1, -10, true, -1), 5, \"\");\n    plot.plot(\"sqrt1pm1\", \"sqrt1pm1.svg\", \"z\", \"sqrt1pm1(z)\");\n\n    f2 = boost::math::powm1;\n    plot.clear();\n    plot.add(boost::bind(f2, 0.0001, _1), find_end_point(boost::bind(f2, 0.0001, _1), -1, 10, false), 5, \"a=0.0001\");\n    plot.add(boost::bind(f2, 0.001, _1), find_end_point(boost::bind(f2, 0.001, _1), -1, 10, false), 5, \"a=0.001\");\n    plot.add(boost::bind(f2, 0.01, _1), find_end_point(boost::bind(f2, 0.01, _1), -1, 10, false), 5, \"a=0.01\");\n    plot.add(boost::bind(f2, 0.1, _1), find_end_point(boost::bind(f2, 0.1, _1), -1, 10, false), 5, \"a=0.1\");\n    plot.add(boost::bind(f2, 0.75, _1), -5, 5, \"a=0.75\");\n    plot.add(boost::bind(f2, 1.25, _1), -5, 5, \"a=1.25\");\n    plot.plot(\"powm1\", \"powm1.svg\", \"z\", \"powm1(a, z)\");\n\n    f = boost::math::sinc_pi;\n    plot.clear();\n    plot.add(f, -10, 10, \"\");\n    plot.plot(\"sinc_pi\", \"sinc_pi.svg\", \"z\", \"sinc_pi(z)\");\n\n    f = boost::math::sinhc_pi;\n    plot.clear();\n    plot.add(f, -5, 5, \"\");\n    plot.plot(\"sinhc_pi\", \"sinhc_pi.svg\", \"z\", \"sinhc_pi(z)\");\n\n    f = boost::math::acosh;\n    plot.clear();\n    plot.add(f, 1, 10, \"acosh\");\n    plot.plot(\"acosh\", \"acosh.svg\", \"z\", \"acosh(z)\");\n\n    f = boost::math::asinh;\n    plot.clear();\n    plot.add(f, -10, 10, \"\");\n    plot.plot(\"asinh\", \"asinh.svg\", \"z\", \"asinh(z)\");\n\n    f = boost::math::atanh;\n    plot.clear();\n    plot.add(f, find_end_point(f, 0.1, -5, true, -1), find_end_point(f, -0.1, 5, true, 1), \"\");\n    plot.plot(\"atanh\", \"atanh.svg\", \"z\", \"atanh(z)\");\n\n    f2 = boost::math::tgamma_delta_ratio;\n    plot.clear();\n    plot.add(boost::bind(f2, _1, -0.5), 1, 40, \"delta = -0.5\");\n    plot.add(boost::bind(f2, _1, -0.2), 1, 40, \"delta = -0.2\");\n    plot.add(boost::bind(f2, _1, -0.1), 1, 40, \"delta = -0.1\");\n    plot.add(boost::bind(f2, _1, 0.1), 1, 40, \"delta = 0.1\");\n    plot.add(boost::bind(f2, _1, 0.2), 1, 40, \"delta = 0.2\");\n    plot.add(boost::bind(f2, _1, 0.5), 1, 40, \"delta = 0.5\");\n    plot.add(boost::bind(f2, _1, 1.0), 1, 40, \"delta = 1.0\");\n    plot.plot(\"tgamma_delta_ratio\", \"tgamma_delta_ratio.svg\", \"z\", \"tgamma_delta_ratio(delta, z)\");\n\n    f2 = boost::math::gamma_p;\n    plot.clear();\n    plot.add(boost::bind(f2, 0.5, _1), 0, 20, \"a = 0.5\");\n    plot.add(boost::bind(f2, 1.0, _1), 0, 20, \"a = 1.0\");\n    plot.add(boost::bind(f2, 5.0, _1), 0, 20, \"a = 5.0\");\n    plot.add(boost::bind(f2, 10.0, _1), 0, 20, \"a = 10.0\");\n    plot.plot(\"gamma_p\", \"gamma_p.svg\", \"z\", \"gamma_p(a, z)\");\n\n    f2 = boost::math::gamma_q;\n    plot.clear();\n    plot.add(boost::bind(f2, 0.5, _1), 0, 20, \"a = 0.5\");\n    plot.add(boost::bind(f2, 1.0, _1), 0, 20, \"a = 1.0\");\n    plot.add(boost::bind(f2, 5.0, _1), 0, 20, \"a = 5.0\");\n    plot.add(boost::bind(f2, 10.0, _1), 0, 20, \"a = 10.0\");\n    plot.plot(\"gamma_q\", \"gamma_q.svg\", \"z\", \"gamma_q(a, z)\");\n\n    f2 = lbeta;\n    plot.clear();\n    plot.add(boost::bind(f2, 0.5, _1), 0.00001, 5, \"a = 0.5\");\n    plot.add(boost::bind(f2, 1.0, _1), 0.00001, 5, \"a = 1.0\");\n    plot.add(boost::bind(f2, 5.0, _1), 0.00001, 5, \"a = 5.0\");\n    plot.add(boost::bind(f2, 10.0, _1), 0.00001, 5, \"a = 10.0\");\n    plot.plot(\"beta\", \"beta.svg\", \"z\", \"log(beta(a, z))\");\n\n    f = boost::math::expint;\n    max_val = f(4);\n    plot.clear();\n    plot.add(f, find_end_point(f, 0.1, -max_val, true), 4, \"\");\n    plot.add(f, -3, find_end_point(f, -0.1, -max_val, false), \"\");\n    plot.plot(\"Exponential Integral Ei\", \"expint_i.svg\", \"z\", \"expint(z)\");\n\n    f2u = boost::math::expint;\n    max_val = 1;\n    plot.clear();\n    plot.add(boost::bind(f2u, 1, _1), find_end_point(boost::bind(f2u, 1, _1), 0.1, max_val, false), 2, \"n = 1 \");\n    plot.add(boost::bind(f2u, 2, _1), find_end_point(boost::bind(f2u, 2, _1), 0.1, max_val, false), 2, \"n = 2 \");\n    plot.add(boost::bind(f2u, 3, _1), 0, 2, \"n = 3 \");\n    plot.add(boost::bind(f2u, 4, _1), 0, 2, \"n = 4 \");\n    plot.plot(\"Exponential Integral En\", \"expint2.svg\", \"z\", \"expint(n, z)\");\n\n    f3 = boost::math::ibeta;\n    plot.clear();\n    plot.add(boost::bind(f3, 9, 1, _1), 0, 1, \"a = 9, b = 1\");\n    plot.add(boost::bind(f3, 7, 2, _1), 0, 1, \"a = 7, b = 2\");\n    plot.add(boost::bind(f3, 5, 5, _1), 0, 1, \"a = 5, b = 5\");\n    plot.add(boost::bind(f3, 2, 7, _1), 0, 1, \"a = 2, b = 7\");\n    plot.add(boost::bind(f3, 1, 9, _1), 0, 1, \"a = 1, b = 9\");\n    plot.plot(\"ibeta\", \"ibeta.svg\", \"z\", \"ibeta(a, b, z)\");\n\n    f2i = boost::math::legendre_p;\n    plot.clear();\n    plot.add(boost::bind(f2i, 1, _1), -1, 1, \"l = 1\");\n    plot.add(boost::bind(f2i, 2, _1), -1, 1, \"l = 2\");\n    plot.add(boost::bind(f2i, 3, _1), -1, 1, \"l = 3\");\n    plot.add(boost::bind(f2i, 4, _1), -1, 1, \"l = 4\");\n    plot.add(boost::bind(f2i, 5, _1), -1, 1, \"l = 5\");\n    plot.plot(\"Legendre Polynomials\", \"legendre_p.svg\", \"x\", \"legendre_p(l, x)\");\n\n    f2u = boost::math::legendre_q;\n    plot.clear();\n    plot.add(boost::bind(f2u, 1, _1), -0.95, 0.95, \"l = 1\");\n    plot.add(boost::bind(f2u, 2, _1), -0.95, 0.95, \"l = 2\");\n    plot.add(boost::bind(f2u, 3, _1), -0.95, 0.95, \"l = 3\");\n    plot.add(boost::bind(f2u, 4, _1), -0.95, 0.95, \"l = 4\");\n    plot.add(boost::bind(f2u, 5, _1), -0.95, 0.95, \"l = 5\");\n    plot.plot(\"Legendre Polynomials of the Second Kind\", \"legendre_q.svg\", \"x\", \"legendre_q(l, x)\");\n\n    f2u = boost::math::laguerre;\n    plot.clear();\n    plot.add(boost::bind(f2u, 0, _1), -5, 10, \"n = 0\");\n    plot.add(boost::bind(f2u, 1, _1), -5, 10, \"n = 1\");\n    plot.add(boost::bind(f2u, 2, _1), \n       find_end_point(boost::bind(f2u, 2, _1), -2, 20, false), \n       find_end_point(boost::bind(f2u, 2, _1), 4, 20, true), \n       \"n = 2\");\n    plot.add(boost::bind(f2u, 3, _1), \n       find_end_point(boost::bind(f2u, 3, _1), -2, 20, false), \n       find_end_point(boost::bind(f2u, 3, _1), 1, 20, false, 8), \n       \"n = 3\");\n    plot.add(boost::bind(f2u, 4, _1), \n       find_end_point(boost::bind(f2u, 4, _1), -2, 20, false), \n       find_end_point(boost::bind(f2u, 4, _1), 1, 20, true, 8), \n       \"n = 4\");\n    plot.add(boost::bind(f2u, 5, _1), \n       find_end_point(boost::bind(f2u, 5, _1), -2, 20, false), \n       find_end_point(boost::bind(f2u, 5, _1), 1, 20, true, 8), \n       \"n = 5\");\n    plot.plot(\"Laguerre Polynomials\", \"laguerre.svg\", \"x\", \"laguerre(n, x)\");\n\n    f2u = boost::math::hermite;\n    plot.clear();\n    plot.add(boost::bind(f2u, 0, _1), -1.8, 1.8, \"n = 0\");\n    plot.add(boost::bind(f2u, 1, _1), -1.8, 1.8, \"n = 1\");\n    plot.add(boost::bind(f2u, 2, _1), -1.8, 1.8, \"n = 2\");\n    plot.add(boost::bind(f2u, 3, _1), -1.8, 1.8, \"n = 3\");\n    plot.add(boost::bind(f2u, 4, _1), -1.8, 1.8, \"n = 4\");\n    plot.plot(\"Hermite Polynomials\", \"hermite.svg\", \"x\", \"hermite(n, x)\");\n\n    f2 = boost::math::cyl_bessel_j;\n    plot.clear();\n    plot.add(boost::bind(f2, 0, _1), -20, 20, \"v = 0\");\n    plot.add(boost::bind(f2, 1, _1), -20, 20, \"v = 1\");\n    plot.add(boost::bind(f2, 2, _1), -20, 20, \"v = 2\");\n    plot.add(boost::bind(f2, 3, _1), -20, 20, \"v = 3\");\n    plot.add(boost::bind(f2, 4, _1), -20, 20, \"v = 4\");\n    plot.plot(\"Bessel J\", \"cyl_bessel_j.svg\", \"x\", \"cyl_bessel_j(v, x)\");\n\n    f2 = boost::math::cyl_neumann;\n    plot.clear();\n    plot.add(boost::bind(f2, 0, _1), find_end_point(boost::bind(f2, 0, _1), 0.1, -5, true), 20, \"v = 0\");\n    plot.add(boost::bind(f2, 1, _1), find_end_point(boost::bind(f2, 1, _1), 0.1, -5, true), 20, \"v = 1\");\n    plot.add(boost::bind(f2, 2, _1), find_end_point(boost::bind(f2, 2, _1), 0.1, -5, true), 20, \"v = 2\");\n    plot.add(boost::bind(f2, 3, _1), find_end_point(boost::bind(f2, 3, _1), 0.1, -5, true), 20, \"v = 3\");\n    plot.add(boost::bind(f2, 4, _1), find_end_point(boost::bind(f2, 4, _1), 0.1, -5, true), 20, \"v = 4\");\n    plot.plot(\"Bessel Y\", \"cyl_neumann.svg\", \"x\", \"cyl_neumann(v, x)\");\n\n    f2 = boost::math::cyl_bessel_i;\n    plot.clear();\n    plot.add(boost::bind(f2, 0, _1), find_end_point(boost::bind(f2, 0, _1), -0.1, 20, false), find_end_point(boost::bind(f2, 0, _1), 0.1, 20, true), \"v = 0\");\n    plot.add(boost::bind(f2, 2, _1), find_end_point(boost::bind(f2, 2, _1), -0.1, 20, false), find_end_point(boost::bind(f2, 2, _1), 0.1, 20, true), \"v = 2\");\n    plot.add(boost::bind(f2, 5, _1), find_end_point(boost::bind(f2, 5, _1), -0.1, -20, true), find_end_point(boost::bind(f2, 5, _1), 0.1, 20, true), \"v = 5\");\n    plot.add(boost::bind(f2, 7, _1), find_end_point(boost::bind(f2, 7, _1), -0.1, -20, true), find_end_point(boost::bind(f2, 7, _1), 0.1, 20, true), \"v = 7\");\n    plot.add(boost::bind(f2, 10, _1), find_end_point(boost::bind(f2, 10, _1), -0.1, 20, false), find_end_point(boost::bind(f2, 10, _1), 0.1, 20, true), \"v = 10\");\n    plot.plot(\"Bessel I\", \"cyl_bessel_i.svg\", \"x\", \"cyl_bessel_i(v, x)\");\n\n    f2 = boost::math::cyl_bessel_k;\n    plot.clear();\n    plot.add(boost::bind(f2, 0, _1), find_end_point(boost::bind(f2, 0, _1), 0.1, 10, false), 10, \"v = 0\");\n    plot.add(boost::bind(f2, 2, _1), find_end_point(boost::bind(f2, 2, _1), 0.1, 10, false), 10, \"v = 2\");\n    plot.add(boost::bind(f2, 5, _1), find_end_point(boost::bind(f2, 5, _1), 0.1, 10, false), 10, \"v = 5\");\n    plot.add(boost::bind(f2, 7, _1), find_end_point(boost::bind(f2, 7, _1), 0.1, 10, false), 10, \"v = 7\");\n    plot.add(boost::bind(f2, 10, _1), find_end_point(boost::bind(f2, 10, _1), 0.1, 10, false), 10, \"v = 10\");\n    plot.plot(\"Bessel K\", \"cyl_bessel_k.svg\", \"x\", \"cyl_bessel_k(v, x)\");\n\n    f2u = boost::math::sph_bessel;\n    plot.clear();\n    plot.add(boost::bind(f2u, 0, _1), 0, 20, \"v = 0\");\n    plot.add(boost::bind(f2u, 2, _1), 0, 20, \"v = 2\");\n    plot.add(boost::bind(f2u, 5, _1), 0, 20, \"v = 5\");\n    plot.add(boost::bind(f2u, 7, _1), 0, 20, \"v = 7\");\n    plot.add(boost::bind(f2u, 10, _1), 0, 20, \"v = 10\");\n    plot.plot(\"Bessel j\", \"sph_bessel.svg\", \"x\", \"sph_bessel(v, x)\");\n\n    f2u = boost::math::sph_neumann;\n    plot.clear();\n    plot.add(boost::bind(f2u, 0, _1), find_end_point(boost::bind(f2u, 0, _1), 0.1, -5, true), 20, \"v = 0\");\n    plot.add(boost::bind(f2u, 2, _1), find_end_point(boost::bind(f2u, 2, _1), 0.1, -5, true), 20, \"v = 2\");\n    plot.add(boost::bind(f2u, 5, _1), find_end_point(boost::bind(f2u, 5, _1), 0.1, -5, true), 20, \"v = 5\");\n    plot.add(boost::bind(f2u, 7, _1), find_end_point(boost::bind(f2u, 7, _1), 0.1, -5, true), 20, \"v = 7\");\n    plot.add(boost::bind(f2u, 10, _1), find_end_point(boost::bind(f2u, 10, _1), 0.1, -5, true), 20, \"v = 10\");\n    plot.plot(\"Bessel y\", \"sph_neumann.svg\", \"x\", \"sph_neumann(v, x)\");\n\n    f4 = boost::math::ellint_rj;\n    plot.clear();\n    plot.add(boost::bind(f4, _1, _1, _1, _1), find_end_point(boost::bind(f4, _1, _1, _1, _1), 0.1, 10, false), 4, \"RJ\");\n    f3 = boost::math::ellint_rf;\n    plot.add(boost::bind(f3, _1, _1, _1), find_end_point(boost::bind(f3, _1, _1, _1), 0.1, 10, false), 4, \"RF\");\n    plot.plot(\"Elliptic Integrals\", \"ellint_carlson.svg\", \"x\", \"\");\n\n    f2 = boost::math::ellint_1;\n    plot.clear();\n    plot.add(boost::bind(f2, _1, 0.5), -0.9, 0.9, \"&#x3C6;=0.5\");\n    plot.add(boost::bind(f2, _1, 0.75), -0.9, 0.9, \"&#x3C6;=0.75\");\n    plot.add(boost::bind(f2, _1, 1.25), -0.9, 0.9, \"&#x3C6;=1.25\");\n    plot.add(boost::bind(f2, _1, boost::math::constants::pi<double>() / 2), -0.9, 0.9, \"&#x3C6;=&#x3C0;/2\");\n    plot.plot(\"Elliptic Of the First Kind\", \"ellint_1.svg\", \"k\", \"ellint_1(k, phi)\");\n\n    f2 = boost::math::ellint_2;\n    plot.clear();\n    plot.add(boost::bind(f2, _1, 0.5), -1, 1, \"&#x3C6;=0.5\");\n    plot.add(boost::bind(f2, _1, 0.75), -1, 1, \"&#x3C6;=0.75\");\n    plot.add(boost::bind(f2, _1, 1.25), -1, 1, \"&#x3C6;=1.25\");\n    plot.add(boost::bind(f2, _1, boost::math::constants::pi<double>() / 2), -1, 1, \"&#x3C6;=&#x3C0;/2\");\n    plot.plot(\"Elliptic Of the Second Kind\", \"ellint_2.svg\", \"k\", \"ellint_2(k, phi)\");\n\n    f3 = boost::math::ellint_3;\n    plot.clear();\n    plot.add(boost::bind(f3, _1, 0, 1.25), -1, 1, \"n=0 &#x3C6;=1.25\");\n    plot.add(boost::bind(f3, _1, 0.5, 1.25), -1, 1, \"n=0.5 &#x3C6;=1.25\");\n    plot.add(boost::bind(f3, _1, 0.25, boost::math::constants::pi<double>() / 2), \n       find_end_point(\n          boost::bind(f3, _1, 0.25, boost::math::constants::pi<double>() / 2), \n          0.5, 4, false, -1), \n       find_end_point(\n          boost::bind(f3, _1, 0.25, boost::math::constants::pi<double>() / 2), \n          -0.5, 4, true, 1), \"n=0.25 &#x3C6;=&#x3C0;/2\");\n    plot.add(boost::bind(f3, _1, 0.75, boost::math::constants::pi<double>() / 2), \n       find_end_point(\n          boost::bind(f3, _1, 0.75, boost::math::constants::pi<double>() / 2), \n          0.5, 4, false, -1), \n       find_end_point(\n          boost::bind(f3, _1, 0.75, boost::math::constants::pi<double>() / 2), \n          -0.5, 4, true, 1), \"n=0.75 &#x3C6;=&#x3C0;/2\");\n    plot.plot(\"Elliptic Of the Third Kind\", \"ellint_3.svg\", \"k\", \"ellint_3(k, n, phi)\");\n\n    f2 = boost::math::jacobi_sn;\n    plot.clear();\n    plot.add(boost::bind(f2, 0, _1), -10, 10, \"k=0\");\n    plot.add(boost::bind(f2, 0.5, _1), -10, 10, \"k=0.5\");\n    plot.add(boost::bind(f2, 0.75, _1), -10, 10, \"k=0.75\");\n    plot.add(boost::bind(f2, 0.95, _1), -10, 10, \"k=0.95\");\n    plot.add(boost::bind(f2, 1, _1), -10, 10, \"k=1\");\n    plot.plot(\"Jacobi Elliptic sn\", \"jacobi_sn.svg\", \"k\", \"jacobi_sn(k, u)\");\n\n    f2 = boost::math::jacobi_cn;\n    plot.clear();\n    plot.add(boost::bind(f2, 0, _1), -10, 10, \"k=0\");\n    plot.add(boost::bind(f2, 0.5, _1), -10, 10, \"k=0.5\");\n    plot.add(boost::bind(f2, 0.75, _1), -10, 10, \"k=0.75\");\n    plot.add(boost::bind(f2, 0.95, _1), -10, 10, \"k=0.95\");\n    plot.add(boost::bind(f2, 1, _1), -10, 10, \"k=1\");\n    plot.plot(\"Jacobi Elliptic cn\", \"jacobi_cn.svg\", \"k\", \"jacobi_cn(k, u)\");\n\n    f2 = boost::math::jacobi_dn;\n    plot.clear();\n    plot.add(boost::bind(f2, 0, _1), -10, 10, \"k=0\");\n    plot.add(boost::bind(f2, 0.5, _1), -10, 10, \"k=0.5\");\n    plot.add(boost::bind(f2, 0.75, _1), -10, 10, \"k=0.75\");\n    plot.add(boost::bind(f2, 0.95, _1), -10, 10, \"k=0.95\");\n    plot.add(boost::bind(f2, 1, _1), -10, 10, \"k=1\");\n    plot.plot(\"Jacobi Elliptic dn\", \"jacobi_dn.svg\", \"k\", \"jacobi_dn(k, u)\");\n\n    f2 = boost::math::jacobi_cd;\n    plot.clear();\n    plot.add(boost::bind(f2, 0, _1), -10, 10, \"k=0\");\n    plot.add(boost::bind(f2, 0.5, _1), -10, 10, \"k=0.5\");\n    plot.add(boost::bind(f2, 0.75, _1), -10, 10, \"k=0.75\");\n    plot.add(boost::bind(f2, 0.95, _1), -10, 10, \"k=0.95\");\n    plot.add(boost::bind(f2, 1, _1), -10, 10, \"k=1\");\n    plot.plot(\"Jacobi Elliptic cd\", \"jacobi_cd.svg\", \"k\", \"jacobi_cd(k, u)\");\n\n    f2 = boost::math::jacobi_cs;\n    plot.clear();\n    plot.add(boost::bind(f2, 0, _1), 0.1, 3, \"k=0\");\n    plot.add(boost::bind(f2, 0.5, _1), 0.1, 3, \"k=0.5\");\n    plot.add(boost::bind(f2, 0.75, _1), 0.1, 3, \"k=0.75\");\n    plot.add(boost::bind(f2, 0.95, _1), 0.1, 3, \"k=0.95\");\n    plot.add(boost::bind(f2, 1, _1), 0.1, 3, \"k=1\");\n    plot.plot(\"Jacobi Elliptic cs\", \"jacobi_cs.svg\", \"k\", \"jacobi_cs(k, u)\");\n\n    f2 = boost::math::jacobi_dc;\n    plot.clear();\n    plot.add(boost::bind(f2, 0, _1), -10, 10, \"k=0\");\n    plot.add(boost::bind(f2, 0.5, _1), -10, 10, \"k=0.5\");\n    plot.add(boost::bind(f2, 0.75, _1), -10, 10, \"k=0.75\");\n    plot.add(boost::bind(f2, 0.95, _1), -10, 10, \"k=0.95\");\n    plot.add(boost::bind(f2, 1, _1), -10, 10, \"k=1\");\n    plot.plot(\"Jacobi Elliptic dc\", \"jacobi_dc.svg\", \"k\", \"jacobi_dc(k, u)\");\n\n    f2 = boost::math::jacobi_ds;\n    plot.clear();\n    plot.add(boost::bind(f2, 0, _1), 0.1, 3, \"k=0\");\n    plot.add(boost::bind(f2, 0.5, _1), 0.1, 3, \"k=0.5\");\n    plot.add(boost::bind(f2, 0.75, _1), 0.1, 3, \"k=0.75\");\n    plot.add(boost::bind(f2, 0.95, _1), 0.1, 3, \"k=0.95\");\n    plot.add(boost::bind(f2, 1, _1), 0.1, 3, \"k=1\");\n    plot.plot(\"Jacobi Elliptic ds\", \"jacobi_ds.svg\", \"k\", \"jacobi_ds(k, u)\");\n\n    f2 = boost::math::jacobi_nc;\n    plot.clear();\n    plot.add(boost::bind(f2, 0, _1), -5, 5, \"k=0\");\n    plot.add(boost::bind(f2, 0.5, _1), -5, 5, \"k=0.5\");\n    plot.add(boost::bind(f2, 0.75, _1), -5, 5, \"k=0.75\");\n    plot.add(boost::bind(f2, 0.95, _1), -5, 5, \"k=0.95\");\n    plot.add(boost::bind(f2, 1, _1), -5, 5, \"k=1\");\n    plot.plot(\"Jacobi Elliptic nc\", \"jacobi_nc.svg\", \"k\", \"jacobi_nc(k, u)\");\n\n    f2 = boost::math::jacobi_ns;\n    plot.clear();\n    plot.add(boost::bind(f2, 0, _1), 0.1, 4, \"k=0\");\n    plot.add(boost::bind(f2, 0.5, _1), 0.1, 4, \"k=0.5\");\n    plot.add(boost::bind(f2, 0.75, _1), 0.1, 4, \"k=0.75\");\n    plot.add(boost::bind(f2, 0.95, _1), 0.1, 4, \"k=0.95\");\n    plot.add(boost::bind(f2, 1, _1), 0.1, 4, \"k=1\");\n    plot.plot(\"Jacobi Elliptic ns\", \"jacobi_ns.svg\", \"k\", \"jacobi_ns(k, u)\");\n\n    f2 = boost::math::jacobi_nd;\n    plot.clear();\n    plot.add(boost::bind(f2, 0, _1), -2, 2, \"k=0\");\n    plot.add(boost::bind(f2, 0.5, _1), -2, 2, \"k=0.5\");\n    plot.add(boost::bind(f2, 0.75, _1), -2, 2, \"k=0.75\");\n    plot.add(boost::bind(f2, 0.95, _1), -2, 2, \"k=0.95\");\n    plot.add(boost::bind(f2, 1, _1), -2, 2, \"k=1\");\n    plot.plot(\"Jacobi Elliptic nd\", \"jacobi_nd.svg\", \"k\", \"jacobi_nd(k, u)\");\n\n    f2 = boost::math::jacobi_sc;\n    plot.clear();\n    plot.add(boost::bind(f2, 0, _1), -5, 5, \"k=0\");\n    plot.add(boost::bind(f2, 0.5, _1), -5, 5, \"k=0.5\");\n    plot.add(boost::bind(f2, 0.75, _1), -5, 5, \"k=0.75\");\n    plot.add(boost::bind(f2, 0.95, _1), -5, 5, \"k=0.95\");\n    plot.add(boost::bind(f2, 1, _1), -5, 5, \"k=1\");\n    plot.plot(\"Jacobi Elliptic sc\", \"jacobi_sc.svg\", \"k\", \"jacobi_sc(k, u)\");\n\n    f2 = boost::math::jacobi_sd;\n    plot.clear();\n    plot.add(boost::bind(f2, 0, _1), -2.5, 2.5, \"k=0\");\n    plot.add(boost::bind(f2, 0.5, _1), -2.5, 2.5, \"k=0.5\");\n    plot.add(boost::bind(f2, 0.75, _1), -2.5, 2.5, \"k=0.75\");\n    plot.add(boost::bind(f2, 0.95, _1), -2.5, 2.5, \"k=0.95\");\n    plot.add(boost::bind(f2, 1, _1), -2.5, 2.5, \"k=1\");\n    plot.plot(\"Jacobi Elliptic sd\", \"jacobi_sd.svg\", \"k\", \"jacobi_sd(k, u)\");\n\n    plot.clear();\n    f2 = boost::math::jacobi_theta1;\n    plot.add(boost::bind(f2, _1, 0.15), 0.0, boost::math::constants::two_pi<double>(), \"\\u03B8\\u2081\");\n    f2 = boost::math::jacobi_theta2;\n    plot.add(boost::bind(f2, _1, 0.15), 0.0, boost::math::constants::two_pi<double>(), \"\\u03B8\\u2082\");\n    f2 = boost::math::jacobi_theta3;\n    plot.add(boost::bind(f2, _1, 0.15), 0.0, boost::math::constants::two_pi<double>(), \"\\u03B8\\u2083\");\n    f2 = boost::math::jacobi_theta4;\n    plot.add(boost::bind(f2, _1, 0.15), 0.0, boost::math::constants::two_pi<double>(), \"\\u03B8\\u2084\");\n    plot.plot(\"Jacobi Theta Functions\", \"jacobi_theta.svg\", \"x\", \"jacobi_theta(x, q=0.15)\");\n\n    f2 = boost::math::jacobi_theta1;\n    plot.clear();\n    plot.add(boost::bind(f2, _1, 0.05), 0.0, boost::math::constants::two_pi<double>(), \"q=0.05\");\n    plot.add(boost::bind(f2, _1, 0.5), 0.0, boost::math::constants::two_pi<double>(), \"q=0.5\");\n    plot.add(boost::bind(f2, _1, 0.7), 0.0, boost::math::constants::two_pi<double>(), \"q=0.7\");\n    plot.add(boost::bind(f2, _1, 0.9), 0.0, boost::math::constants::two_pi<double>(), \"q=0.9\");\n    plot.plot(\"Jacobi Theta Function \\u03B8\\u2081\", \"jacobi_theta1.svg\", \"x\", \"jacobi_theta1(x, q)\");\n\n    f2 = boost::math::jacobi_theta2;\n    plot.clear();\n    plot.add(boost::bind(f2, _1, 0.05), 0.0, boost::math::constants::two_pi<double>(), \"q=0.05\");\n    plot.add(boost::bind(f2, _1, 0.5), 0.0, boost::math::constants::two_pi<double>(), \"q=0.5\");\n    plot.add(boost::bind(f2, _1, 0.7), 0.0, boost::math::constants::two_pi<double>(), \"q=0.7\");\n    plot.add(boost::bind(f2, _1, 0.9), 0.0, boost::math::constants::two_pi<double>(), \"q=0.9\");\n    plot.plot(\"Jacobi Theta Function \\u03B8\\u2082\", \"jacobi_theta2.svg\", \"x\", \"jacobi_theta2(x, q)\");\n\n    f2 = boost::math::jacobi_theta3;\n    plot.clear();\n    plot.add(boost::bind(f2, _1, 0.05), 0.0, boost::math::constants::two_pi<double>(), \"q=0.05\");\n    plot.add(boost::bind(f2, _1, 0.5), 0.0, boost::math::constants::two_pi<double>(), \"q=0.5\");\n    plot.add(boost::bind(f2, _1, 0.7), 0.0, boost::math::constants::two_pi<double>(), \"q=0.7\");\n    plot.add(boost::bind(f2, _1, 0.9), 0.0, boost::math::constants::two_pi<double>(), \"q=0.9\");\n    plot.plot(\"Jacobi Theta Function \\u03B8\\u2083\", \"jacobi_theta3.svg\", \"x\", \"jacobi_theta3(x, q)\");\n\n    f2 = boost::math::jacobi_theta4;\n    plot.clear();\n    plot.add(boost::bind(f2, _1, 0.05), 0.0, boost::math::constants::two_pi<double>(), \"q=0.05\");\n    plot.add(boost::bind(f2, _1, 0.5), 0.0, boost::math::constants::two_pi<double>(), \"q=0.5\");\n    plot.add(boost::bind(f2, _1, 0.7), 0.0, boost::math::constants::two_pi<double>(), \"q=0.7\");\n    plot.add(boost::bind(f2, _1, 0.9), 0.0, boost::math::constants::two_pi<double>(), \"q=0.9\");\n    plot.plot(\"Jacobi Theta Function \\u03B8\\u2084\", \"jacobi_theta4.svg\", \"x\", \"jacobi_theta4(x, q)\");\n\n    f = boost::math::airy_ai;\n    plot.clear();\n    plot.add(f, -20, 20, \"\");\n    plot.plot(\"Ai\", \"airy_ai.svg\", \"z\", \"airy_ai(z)\");\n\n    f = boost::math::airy_bi;\n    plot.clear();\n    plot.add(f, -20, 3, \"\");\n    plot.plot(\"Bi\", \"airy_bi.svg\", \"z\", \"airy_bi(z)\");\n\n    f = boost::math::airy_ai_prime;\n    plot.clear();\n    plot.add(f, -20, 20, \"\");\n    plot.plot(\"Ai'\", \"airy_aip.svg\", \"z\", \"airy_ai_prime(z)\");\n\n    f = boost::math::airy_bi_prime;\n    plot.clear();\n    plot.add(f, -20, 3, \"\");\n    plot.plot(\"Bi'\", \"airy_bip.svg\", \"z\", \"airy_bi_prime(z)\");\n\n    f = boost::math::trigamma;\n    max_val = 30;\n    plot.clear();\n    plot.add(f, find_end_point(f, 0.1, max_val, false), 5, \"\");\n    plot.add(f, find_end_point(f, 0.1, max_val, false, -1), find_end_point(f, -0.1, max_val, true), \"\");\n    plot.add(f, find_end_point(f, 0.1, max_val, false, -2), find_end_point(f, -0.1, max_val, true, -1), \"\");\n    plot.add(f, find_end_point(f, 0.1, max_val, false, -3), find_end_point(f, -0.1, max_val, true, -2), \"\");\n    plot.add(f, find_end_point(f, 0.1, max_val, false, -4), find_end_point(f, -0.1, max_val, true, -3), \"\");\n    plot.add(f, find_end_point(f, 0.1, max_val, false, -5), find_end_point(f, -0.1, max_val, true, -4), \"\");\n    plot.plot(\"Trigamma\", \"trigamma.svg\", \"x\", \"trigamma(x)\");\n\n    f2i = boost::math::polygamma;\n    max_val = -50;\n    plot.clear();\n    plot.add(boost::bind(f2i, 2, _1), find_end_point(boost::bind(f2i, 2, _1), 0.1, max_val, true), 5, \"\");\n    plot.add(boost::bind(f2i, 2, _1), find_end_point(boost::bind(f2i, 2, _1), 0.1, max_val, true, -1), find_end_point(boost::bind(f2i, 2, _1), -0.1, -max_val, true), \"\");\n    plot.add(boost::bind(f2i, 2, _1), find_end_point(boost::bind(f2i, 2, _1), 0.1, max_val, true, -2), find_end_point(boost::bind(f2i, 2, _1), -0.1, -max_val, true, -1), \"\");\n    plot.add(boost::bind(f2i, 2, _1), find_end_point(boost::bind(f2i, 2, _1), 0.1, max_val, true, -3), find_end_point(boost::bind(f2i, 2, _1), -0.1, -max_val, true, -2), \"\");\n    plot.add(boost::bind(f2i, 2, _1), find_end_point(boost::bind(f2i, 2, _1), 0.1, max_val, true, -4), find_end_point(boost::bind(f2i, 2, _1), -0.1, -max_val, true, -3), \"\");\n    plot.add(boost::bind(f2i, 2, _1), find_end_point(boost::bind(f2i, 2, _1), 0.1, max_val, true, -5), find_end_point(boost::bind(f2i, 2, _1), -0.1, -max_val, true, -4), \"\");\n    plot.add(boost::bind(f2i, 2, _1), find_end_point(boost::bind(f2i, 2, _1), 0.1, max_val, true, -6), find_end_point(boost::bind(f2i, 2, _1), -0.1, -max_val, true, -5), \"\");\n    plot.plot(\"Polygamma\", \"polygamma2.svg\", \"x\", \"polygamma(2, x)\");\n\n    max_val = 800;\n    plot.clear();\n    plot.add(boost::bind(f2i, 3, _1), find_end_point(boost::bind(f2i, 3, _1), 0.1, max_val, false), 5, \"\");\n    plot.add(boost::bind(f2i, 3, _1), find_end_point(boost::bind(f2i, 3, _1), 0.1, max_val, false, -1), find_end_point(boost::bind(f2i, 3, _1), -0.1, max_val, true), \"\");\n    plot.add(boost::bind(f2i, 3, _1), find_end_point(boost::bind(f2i, 3, _1), 0.1, max_val, false, -2), find_end_point(boost::bind(f2i, 3, _1), -0.1, max_val, true, -1), \"\");\n    plot.add(boost::bind(f2i, 3, _1), find_end_point(boost::bind(f2i, 3, _1), 0.1, max_val, false, -3), find_end_point(boost::bind(f2i, 3, _1), -0.1, max_val, true, -2), \"\");\n    plot.add(boost::bind(f2i, 3, _1), find_end_point(boost::bind(f2i, 3, _1), 0.1, max_val, false, -4), find_end_point(boost::bind(f2i, 3, _1), -0.1, max_val, true, -3), \"\");\n    plot.add(boost::bind(f2i, 3, _1), find_end_point(boost::bind(f2i, 3, _1), 0.1, max_val, false, -5), find_end_point(boost::bind(f2i, 3, _1), -0.1, max_val, true, -4), \"\");\n    plot.add(boost::bind(f2i, 3, _1), find_end_point(boost::bind(f2i, 3, _1), 0.1, max_val, false, -6), find_end_point(boost::bind(f2i, 3, _1), -0.1, max_val, true, -5), \"\");\n    plot.plot(\"Polygamma\", \"polygamma3.svg\", \"x\", \"polygamma(3, x)\");\n\n\n  }\n  catch (const std::exception& ex)\n  {\n    std::cout << ex.what() << std::endl;\n  }\n   return 0;\n}\n\n", "meta": {"hexsha": "290ea4e288a6df8879668270c6ecf1b4cb910498", "size": 36768, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/doc/graphs/sf_graphs.cpp", "max_stars_repo_name": "anarthal/boost-unix-mirror", "max_stars_repo_head_hexsha": "8c34eb2fe471d6c3113c680c1fbef29e7a8063a0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T15:15:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-28T15:15:28.000Z", "max_issues_repo_path": "libs/math/doc/graphs/sf_graphs.cpp", "max_issues_repo_name": "anarthal/boost-unix-mirror", "max_issues_repo_head_hexsha": "8c34eb2fe471d6c3113c680c1fbef29e7a8063a0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-10-21T12:42:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T08:41:31.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/doc/graphs/sf_graphs.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 45.3925925926, "max_line_length": 174, "alphanum_fraction": 0.5649749782, "num_tokens": 14216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.2817549316167985}}
{"text": "/** Copyright (c) 2011, Edgar Solomonik, all rights reserved.\n  * \\addtogroup benchmarks\n  * @{ \n  * \\addtogroup bench_redistributions\n  * @{ \n  * \\brief Benchmarks arbitrary NS redistribution\n  */\n\n//#include <boost/math/distributions/normal.hpp>\n//\n//boost::math::normal dist(0.0, 1.0);\n//\n//// 95% of distribution is below q:\n//double q = quantile(dist, 0.95);\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <string>\n#include <math.h>\n#include <assert.h>\n#include <algorithm>\n#include <ctf.hpp>\n#include <iostream>\n#include <fstream>\n#include \"../src/shared/util.h\"\n\nusing namespace CTF;\n\nvoid bench_redistribution(int          niter,\n                          World &      dw,\n                          int          order,\n                          int const *  lens,\n                          char const * idx,\n                          int          prl1_ord,\n                          int const *  prl1_lens,\n                          char const * prl1_idx,\n                          int          prl2_ord,\n                          int const *  prl2_lens,\n                          char const * prl2_idx,\n                          int          blk1_ord,\n                          int const *  blk1_lens,\n                          char const * blk1_idx,\n                          int          blk2_ord,\n                          int const *  blk2_lens,\n                          char const * blk2_idx){\n\n  int rank, num_pes;\n  \n  MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n  MPI_Comm_size(MPI_COMM_WORLD, &num_pes);\n\n  int sym[order];\n  int64_t N = 1;\n  for (int i=0; i<order; i++){\n    N*=lens[i];\n    sym[i] = NS;\n  }\n\n  Partition prl1(prl1_ord, prl1_lens);\n  Partition prl2(prl2_ord, prl2_lens);\n  Partition blk1(blk1_ord, blk1_lens);\n  Partition blk2(blk2_ord, blk2_lens);\n  \n  Tensor<> A(order, lens, sym, dw, idx, prl1[prl1_idx], blk1[blk1_idx], \"A\", 1);\n\n  A.fill_random(-.5, .5);\n\n  double t = 0.0;\n  double t_min;\n  double t_max;\n\n  double btime;\n  MPI_Barrier(MPI_COMM_WORLD);\n  btime = MPI_Wtime();\n  MPI_Barrier(MPI_COMM_WORLD);\n  btime -= MPI_Wtime();\n    \n  double * data_ref = A.read(idx, prl2[prl2_idx], blk2[blk2_idx]);\n\n#ifdef USE_FOMPI\n  int N_DGTOG = 6;\n#else\n  int N_DGTOG = 5;\n#endif\n\n  std::ofstream f;\n  if (rank == 0){\n    char fname[1000];\n    sprintf(fname, \"bench_redist.p%d.o%d.N%d.pst-%s.vst-%s.ped-%s.ved-%s.dat\", num_pes, order, lens[0], prl1_idx, blk1_idx, prl2_idx, blk2_idx);\n    f.open(fname);\n  }\n \n  std::vector<double> times[N_DGTOG];\n  for (int D=0; D<N_DGTOG; D++){\n    DGTOG_SWITCH = D;\n    char const * str_name;\n    switch (D){\n      case 0:\n        str_name = \"NAIVE\";\n        break;\n      case 1:\n        str_name = \"ROR\";\n        break;\n      case 2:\n        str_name = \"ROR_ISR\";\n        break;\n      case 3:\n        str_name = \"ROR_PUT\";\n        break;\n      case 4:\n        str_name = \"ROR_ISR_ANY\";\n        break;\n      case 5:\n        str_name = \"ROR_PUT_ANY\";\n        break;\n    }\n    if (rank == 0) printf(\"Testing redistribution via kernel %s\\n\", str_name);\n\n    double * data = A.read(idx, prl2[prl2_idx], blk2[blk2_idx]);\n    int pass = 1;\n    for (int64_t j=0; j<N/num_pes; j++){\n      if (data[j] != data_ref[j]){ \n        pass = 0;\n        printf(\"[%d] Incorrect! data[%ld] = %lf instead of %lf\\n\",rank,j, data[j],data_ref[j]);\n      }\n    }\n    free(data);\n    MPI_Allreduce(MPI_IN_PLACE, &pass, 1, MPI_INT, MPI_MIN, MPI_COMM_WORLD);\n    if (pass){\n      if (rank == 0) printf(\"Correctness test passed.\\n\");\n      MPI_Barrier(MPI_COMM_WORLD);\n      Timer_epoch te(str_name);\n      te.begin();\n      for (int i=0; i<niter; i++){\n        double t_st = MPI_Wtime();\n        double * data = A.read(idx, prl2[prl2_idx], blk2[blk2_idx]);\n        MPI_Barrier(MPI_COMM_WORLD);\n        times[D].push_back(MPI_Wtime() - t_st - btime);\n        free(data);\n      }\n      te.end();\n      std::sort(&times[D][0], &times[D][0]+niter);\n      if (rank == 0){\n        printf(\"Performed %d redistributions via kernel %s sec/iter: median = %lf (median effective end-to-end bandwidth, N/(t*p) = %lf GB/s), range = [%lf, %lf]\\n\",\n                niter, str_name, times[D][niter/2], 1.E-9*N*sizeof(double)/(num_pes*times[D][niter/2]), times[D][0], times[D][niter-1]);\n        f << str_name << \" \";\n        for (int i=0; i<niter; i++){\n          f << times[D][i] << \" \";\n        }\n        f << \"\\n\";\n      }\n    }\n  }\n  if (rank == 0){\n    printf(\"Data line kernel * [min, median max]:\\n\");\n    for (int D=0; D<N_DGTOG; D++){\n      printf(\"%lf %lf %lf \", times[D][0], times[D][niter/2], times[D][niter-1]);\n    }\n    printf(\"\\n\");\n  }\n  if (rank == 0){\n    f.close();\n  }\n\n  free(data_ref); \n/*  if (rank == 0)\n    printf(\"Performed %d redistributions in %lf time/iter %lf mem GB/sec\\n\",\n            niter, (end_time-st_time)/niter, (2*N*1.E-9/((end_time-st_time)/niter))/num_pes);*/\n} \n\nchar* getCmdOption(char ** begin,\n                   char ** end,\n                   const   std::string & option){\n  char ** itr = std::find(begin, end, option);\n  if (itr != end && ++itr != end){\n    return *itr;\n  }\n  return 0;\n}\n\n\nint main(int argc, char ** argv){\n  int rank, np, niter, n, phase;\n  int const in_num = argc;\n  char ** input_str = argv;\n  char const * idx;\n  char const * prl1_idx;\n  char const * prl2_idx;\n  char const * blk1_idx;\n  char const * blk2_idx;\n  int64_t prl1, prl2, blk1, blk2;\n  int order;\n  int prl1_ord;\n  int prl2_ord;\n  int blk1_ord;\n  int blk2_ord;\n  int * lens;\n  int * prl1_lens;\n  int * prl2_lens;\n  int * blk1_lens;\n  int * blk2_lens;\n\n  MPI_Init(&argc, &argv);\n  MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n  MPI_Comm_size(MPI_COMM_WORLD, &np);\n\n  if (getCmdOption(input_str, input_str+in_num, \"-n\")){\n    n = atoi(getCmdOption(input_str, input_str+in_num, \"-n\"));\n    if (n < 0) n = 4;\n  } else n = 4;\n\n  if (getCmdOption(input_str, input_str+in_num, \"-phase\")){\n    phase = atoi(getCmdOption(input_str, input_str+in_num, \"-phase\"));\n    if (phase < 0) phase = 10;\n  } else phase = 10;\n\n  if (getCmdOption(input_str, input_str+in_num, \"-prl1\")){\n    prl1 = atoi(getCmdOption(input_str, input_str+in_num, \"-prl1\"));\n    if (prl1 < 0) prl1 = np;\n  } else prl1 = np;\n\n  if (getCmdOption(input_str, input_str+in_num, \"-prl2\")){\n    prl2 = atoi(getCmdOption(input_str, input_str+in_num, \"-prl2\"));\n    if (prl2 < 0) prl2 = np;\n  } else prl2 = np;\n\n  if (getCmdOption(input_str, input_str+in_num, \"-blk1\")){\n    blk1 = atoi(getCmdOption(input_str, input_str+in_num, \"-blk1\"));\n    if (blk1 < 0) blk1 = np;\n  } else blk1 = np;\n\n  if (getCmdOption(input_str, input_str+in_num, \"-blk2\")){\n    blk2 = atoi(getCmdOption(input_str, input_str+in_num, \"-blk2\"));\n    if (blk2 < 0) blk2 = np;\n  } else blk2 = np;\n\n  if (getCmdOption(input_str, input_str+in_num, \"-niter\")){\n    niter = atoi(getCmdOption(input_str, input_str+in_num, \"-niter\"));\n    if (niter < 0) niter = 3;\n  } else niter = 3;\n\n  if (getCmdOption(input_str, input_str+in_num, \"-idx\")){\n    idx = getCmdOption(input_str, input_str+in_num, \"-idx\");\n  } else idx = \"ij\";\n  if (getCmdOption(input_str, input_str+in_num, \"-prl1_idx\")){\n    prl1_idx = getCmdOption(input_str, input_str+in_num, \"-prl1_idx\");\n  } else prl1_idx = \"i\";\n  if (getCmdOption(input_str, input_str+in_num, \"-prl2_idx\")){\n    prl2_idx = getCmdOption(input_str, input_str+in_num, \"-prl2_idx\");\n  } else prl2_idx = \"j\";\n  if (getCmdOption(input_str, input_str+in_num, \"-blk1_idx\")){\n    blk1_idx = getCmdOption(input_str, input_str+in_num, \"-blk1_idx\");\n  } else blk1_idx = \"\";\n  if (getCmdOption(input_str, input_str+in_num, \"-blk2_idx\")){\n    blk2_idx = getCmdOption(input_str, input_str+in_num, \"-blk2_idx\");\n  } else blk2_idx = \"\";\n  \n  order = strlen(idx);\n  prl1_ord = strlen(prl1_idx);\n  prl2_ord = strlen(prl2_idx);\n  blk1_ord = strlen(blk1_idx);\n  blk2_ord = strlen(blk2_idx);\n\n  if (rank==0){\n    printf(\"Redistributing order %d tensor with all dims %d and idx %s from order %d proc grid with dims %ld and idx %s, to order %d proc grid with dims %ld and idx %s\\n\", order, n, idx, prl1_ord, prl1, prl1_idx, prl2_ord, prl2, prl2_idx);\n    printf(\"Initial blocking order %d dims %ld and idx %s, to final blocking order %d dims %ld and idx %s\\n\", blk1_ord, blk1, blk1_idx, blk2_ord, blk2, blk2_idx);\n  }\n\n\n  lens = (int*)malloc(order*sizeof(int));\n  for (int i=0; i<order; i++){\n    lens[i] = n;\n  }\n  prl1_lens = (int*)malloc(prl1_ord*sizeof(int));\n  for (int i=0; i<prl1_ord; i++){\n    prl1_lens[prl1_ord-i-1] = prl1%phase;\n    prl1 = prl1/phase;\n  }\n  if (rank == 0){ \n    printf(\"start topology:\");\n    for (int i=0; i<prl1_ord; i++){\n      printf(\" %d\", prl1_lens[i]);\n    }\n    printf(\"\\n\");\n  }\n  prl2_lens = (int*)malloc(prl2_ord*sizeof(int));\n  for (int i=0; i<prl2_ord; i++){\n    prl2_lens[prl2_ord-i-1] = prl2%phase;\n    prl2 = prl2/phase;\n  }\n  if (rank == 0){ \n    printf(\"end topology:\");\n    for (int i=0; i<prl2_ord; i++){\n      printf(\" %d\", prl2_lens[i]);\n    }\n    printf(\"\\n\");\n  }\n\n  blk1_lens = (int*)malloc(blk1_ord*sizeof(int));\n  for (int i=0; i<blk1_ord; i++){\n    blk1_lens[blk1_ord-i-1] = blk1%phase;\n    blk1 = blk1/phase;\n  }\n  if (rank == 0){ \n    printf(\"start blocking:\");\n    for (int i=0; i<blk1_ord; i++){\n      printf(\" %d\", blk1_lens[i]);\n    }\n    printf(\"\\n\");\n  }\n\n  blk2_lens = (int*)malloc(blk2_ord*sizeof(int));\n  for (int i=0; i<blk2_ord; i++){\n    blk2_lens[blk2_ord-i-1] = blk2%phase;\n    blk2 = blk2/phase;\n  }\n  if (rank == 0){ \n    printf(\"end blocking:\");\n    for (int i=0; i<blk2_ord; i++){\n      printf(\" %d\", blk2_lens[i]);\n    }\n    printf(\"\\n\");\n  }\n\n\n  {\n    CTF_World dw(argc, argv);\n    bench_redistribution(niter, dw, order, lens, idx,\n                         prl1_ord, prl1_lens, prl1_idx,\n                         prl2_ord, prl2_lens, prl2_idx,\n                         blk1_ord, blk1_lens, blk1_idx,\n                         blk2_ord, blk2_lens, blk2_idx);\n  }\n\n\n  MPI_Finalize();\n  return 0;\n}\n/**\n * @} \n * @}\n */\n\n\n", "meta": {"hexsha": "31b2915ba439dc83c0bfeda19b12b8e2a2d5bf16", "size": 9894, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "bench/bench_redistribution.cxx", "max_stars_repo_name": "LinjianMa/ctf", "max_stars_repo_head_hexsha": "06a50b6ea4be2eeb7f3d6c43f05a0befae94f08e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 108.0, "max_stars_repo_stars_event_min_datetime": "2018-01-01T21:29:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T17:51:15.000Z", "max_issues_repo_path": "bench/bench_redistribution.cxx", "max_issues_repo_name": "LinjianMa/ctf", "max_issues_repo_head_hexsha": "06a50b6ea4be2eeb7f3d6c43f05a0befae94f08e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 91.0, "max_issues_repo_issues_event_min_datetime": "2017-12-27T04:28:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T09:14:43.000Z", "max_forks_repo_path": "bench/bench_redistribution.cxx", "max_forks_repo_name": "LinjianMa/ctf", "max_forks_repo_head_hexsha": "06a50b6ea4be2eeb7f3d6c43f05a0befae94f08e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 45.0, "max_forks_repo_forks_event_min_datetime": "2017-12-26T21:15:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T11:16:40.000Z", "avg_line_length": 28.5953757225, "max_line_length": 239, "alphanum_fraction": 0.5684253083, "num_tokens": 3201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.28175493161679843}}
{"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#ifndef SLICE_SAMPLER_HPP\n#define SLICE_SAMPLER_HPP\n\n#include <cstdlib>\n#include <climits>\n#include <cfloat>\n#include \"basic_lot.hpp\"\n#include \"probability_distribution.hpp\"\n#include \"xprobdist.hpp\"\n#include <boost/shared_ptr.hpp>\n#include <boost/weak_ptr.hpp>\n#if defined(PYTHON_ONLY)\n#\tinclude <boost/python/call_method.hpp>\n#endif\ntypedef std::pair<double, double> ParamAndLnProb;\ntypedef std::pair<double, double> SliceInterval;\n\nnamespace phycas\n{\n\nstruct SliceStats\n\t{\n\tSliceStats() : nsamples(0), value(0.0), width(0.0), diff(0.0), failed(0.0), evals(0.0) {}\n\n\tunsigned nsamples;\n\tdouble value;\n\tdouble width;\n\tdouble diff;\n\tdouble failed;\n\tdouble evals;\n\t};\n\n// Note: AdHocDensity is defined in probablity_distribution.hpp\ntypedef boost::shared_ptr<AdHocDensity> FuncToSampleShPtr;\n\n#undef WEAK_FUNCTOSAMPLE\n#if defined(WEAK_FUNCTOSAMPLE)\ntypedef boost::weak_ptr<AdHocDensity> FuncToSampleWkPtr;\n#endif\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tImplements the univariate slice sampler described in Neal, Radford M. 2003. Slice sampling. Annals of Statistics\n|\t31:705-741.\n*/\nclass SliceSampler\n\t{\n\tpublic:\n\t\t\t\t\t\t\t\tSliceSampler();\n#if defined(WEAK_FUNCTOSAMPLE)\n\t\t\t\t\t\t\t\tSliceSampler(LotShPtr rnd, FuncToSampleWkPtr f);\n#else\n\t\t\t\t\t\t\t\tSliceSampler(LotShPtr rnd, FuncToSampleShPtr f);\n#endif\n\t\tvirtual\t\t\t\t\t~SliceSampler();\n\n\t\tdouble\t\t\t\t\tSample();\n\t\tstd::vector<double>\t\t\t\t\tDebugSample();\n\n\t\tdouble\t\t\t\t\tOverrelaxedSample();\n\t\tstd::vector<double>\t\t\t\t\tDebugOverrelaxedSample();\n\n#if defined(WEAK_FUNCTOSAMPLE)\n\t\tvoid\t\t\t\t\tAttachFunc(FuncToSampleWkPtr f);\n#else\n\t\tvoid\t\t\t\t\tAttachFunc(FuncToSampleShPtr f);\n#endif\n\t\tvoid\t\t\t\t\tAttachRandomNumberGenerator(LotShPtr rnd);\n\n\t\tvoid\t\t\t\t\tSetXValue(double x);\n\t\tvoid\t\t\t\t\tSetMaxUnits(unsigned umax);\n\n\t\tvoid\t\t\t\t\tSetSliceUnitWidth(double uwidth);\n\t\tdouble\t\t\t\t\tGetSliceUnitWidth() const;\n\n\t\tdouble\t\t\t\t\tAdaptSimple(double multiplier);\n\t\tdouble\t\t\t\t\tAdaptNeal(double multiplier);\n\t\tvoid\t\t\t\t\tAdaptYConditional(double from_ends, double multiplier);\n\t\tSliceInterval\t\t\tFindSliceInterval(ParamAndLnProb x0, const double ln_y0, double tol, unsigned max_steps = UINT_MAX) const;\n\t\tdouble\t\t\t\t\tCalcW(double y0) const;\n\n\t\tdouble\t\t\t\t\tGetMode() const;\n\t\tdouble\t\t\t\t\tGetLnDensityAtMode() const;\n\n\t\tdouble\t\t\t\t\tGetLastSampledXValue();\n\t\tdouble\t\t\t\t\tGetLastSampledYValue();\n\t\tdouble\t\t\t\t\tGetSliceYValue();\n\n\t\tdouble\t\t\t\t\tGetLnZero() const {return -DBL_MAX;}\n        void                    UseDoublingMethod(bool d);\n\n\t\t// For diagnosing inefficiency\n\t\t//\n\t\tdouble\t\t\t\t\tGetMinX();\n\t\tdouble\t\t\t\t\tGetMaxX();\n\t\tdouble\t\t\t\t\tGetOrigLeftEdgeOfSlice();\n\t\tdouble\t\t\t\t\tGetOrigRightEdgeOfSlice();\n\t\tdouble\t\t\t\t\tGetLeftEdgeOfSlice();\n\t\tdouble\t\t\t\t\tGetRightEdgeOfSlice();\n\t\tunsigned\t\t\t\tGetNumFuncEvals();\n\t\tunsigned\t\t\t\tGetNumFailedSamples();\n\t\tunsigned\t\t\t\tGetNumUnitsRequired();\n\t\tunsigned\t\t\t\tGetNumSamples();\n\n\t\tSliceStats\t\t\t\tSummarizeDiagnostics();\n\t\tvoid\t\t\t\t\tResetDiagnostics();\n\n\tprotected:\n\n\t\tvoid\t\t\t\t\tInit();\n\t\tParamAndLnProb\t\t\tGetNextSample(const ParamAndLnProb);\n\t\tParamAndLnProb\t\t\tGetNextOverrelaxedSample(const ParamAndLnProb);\n\t\tSliceInterval\t\t\tBisectionSqueeze(double left, double lnf_left, double right, double lnf_right, const double ln_y0, double tol, unsigned max_steps) const;\n\n#if defined(WEAK_FUNCTOSAMPLE)\n\t\tFuncToSampleWkPtr\t\tfunc;\t\t\t\t/**< is a functor representing the probability distribution to be sampled */\n#else\n\t\tFuncToSampleShPtr\t\tfunc;\t\t\t\t/**< is a functor representing the probability distribution to be sampled */\n#endif\n\t\tLotShPtr\t\t\t\tr;\t\t\t\t\t/**< is the random number generator */\n\t\tParamAndLnProb\t\t\tlastSampled;\t\t/**< most recent valid sample and its relative density */\n\t\tdouble\t\t\t\t\tw;\t\t\t\t\t/**< unit size for interval I */\n\t\tunsigned\t\t\t\tmaxUnits;\t\t\t/**< maximum number of units of size w to use for interval I (set to UINT_MAX for unlimited) */\n\n\t\t// These quantities are used for diagnostic purposes in GetNextSample()\n\t\t//\n\t\tdouble\t\t\t\t\torig_left_edge;\t\t/**< x coordinate of left edge of most recent slice (before cropping) */\n\t\tdouble\t\t\t\t\torig_right_edge;\t/**< x coordinate of right edge of most recent slice (before cropping) */\n\t\tdouble\t\t\t\t\tleft_edge;\t\t\t/**< x coordinate of left edge of most recent slice (after cropping) */\n\t\tdouble\t\t\t\t\tright_edge;\t\t\t/**< x coordinate of right edge of most recent slice (after cropping) */\n\t\tdouble\t\t\t\t\tln_y;\t\t\t\t/**< log of f(x) representing most recent slice */\n\n\t\t// For diagnosing inefficiency, all reset with call to ResetDiagnostics()\n\t\t//\n\t\tdouble\t\t\t\t\tmin_x;\t\t\t\t/**< minimum x value tried */\n\t\tdouble\t\t\t\t\tmax_x;\t\t\t\t/**< maximum x value tried */\n\t\tdouble\t\t\t\t\tsumValues;\t\t\t/**< sum of last `num_samples' sampled values */\n\t\tdouble\t\t\t\t\tsumWidths;\t\t\t/**< sum of last `num_samples' cropped slice widths (where slice width = right_edge - left_edge) */\n\t\tdouble\t\t\t\t\tsumDiffs;\t\t\t/**< sum of last `num_samples' differences between successively sampled values */\n\t\tunsigned\t\t\t\tfunc_evals;\t\t\t/**< counts number of function evaluations */\n\t\tunsigned\t\t\t\tfailed_samples;\t\t/**< counts number of samples that failed because they were not in the slice */\n\t\tunsigned\t\t\t\trealized_m;\t\t\t/**< counts number of units, each of size w, that were required to bracket the slice */\n\t\tunsigned\t\t\t\tnum_samples;\t\t/**< counts number of times GetNextSample called */\n\t\tstd::vector<ParamAndLnProb>\tmost_recent;\t/**< vector of all (x, lnx) pairs evaluated in most recent sampling effort */\n\n\t\t// These are needed for y-conditional adaptation\n\t\tbool\t\t\t\t\tycond_on;\t\t\t/**< if true, w chosen anew for each sample based on y-coordinate of slice */\n\t\tdouble\t\t\t\t\tycond_a;\n\t\tdouble\t\t\t\t\tycond_b;\n\t\tdouble\t\t\t\t\tycond_multiplier;\n\t\tParamAndLnProb\t\t\tmode;\n\n\t\t// These are for overrelaxed sampling\n\t\tunsigned\t\t\t\tnum_overrelaxed_samples;\t/**< counts number of times GetNextOverrelaxedSample called */\n\n        bool                    doubling;           /**< if true, doubling method will be used to increase slice interval */\n\t};\n\ntypedef boost::shared_ptr<SliceSampler> SliceSamplerShPtr;\n\n} // namespace phycas\n\n#endif\n", "meta": {"hexsha": "df5ec870a4670d37f9767f7abc2f9e1b6d129b7d", "size": 7470, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cpp/slice_sampler.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/slice_sampler.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/slice_sampler.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": 41.043956044, "max_line_length": 155, "alphanum_fraction": 0.6464524766, "num_tokens": 1767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.28175492406974234}}
{"text": "/*--\n    Combiner.cpp  \n\n    This file is part of the Cornucopia curve sketching library.\n    Copyright (C) 2010 Ilya Baran (baran37@gmail.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\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#include \"Combiner.h\"\n#include \"GraphConstructor.h\"\n#include \"PrimitiveFitter.h\"\n#include \"PrimitiveSequence.h\"\n#include \"PathFinder.h\"\n#include \"Preprocessing.h\"\n#include \"Resampler.h\"\n#include \"Polyline.h\"\n#include \"Solver.h\"\n#include \"ErrorComputer.h\"\n#include \"Fitter.h\"\n#include \"Oversketcher.h\"\n#include \"PiecewiseLinearUtils.h\"\n\n#include <iterator>\n#include <cstdio>\n\n#include <Eigen/LU>\n#include <Eigen/Cholesky>\n\nusing namespace std;\nusing namespace Eigen;\nNAMESPACE_Cornu\n\n#define SPARSE 1\n\nclass MulticurveDenseEvalData : public LSEvalData\n{\npublic:\n    //overrides\n    double error() const { return _con.squaredNorm(); }\n\n    void solveForDelta(double damping, Eigen::VectorXd &out, std::set<LSBoxConstraint> &constraints)\n    {\n        size_t vars = _errDer.cols();\n\n        size_t size = vars + _con.size() + constraints.size();\n        MatrixXd lhs = MatrixXd::Zero(size, size);\n        VectorXd rhs = VectorXd::Zero(size);\n\n        lhs.block(0, 0, vars, vars) = _errDer.transpose() * _errDer;\n        rhs.segment(0, vars) = -_errDer.transpose() * _err;\n\n        lhs.block(vars, 0, _conDer.rows(), _conDer.cols()) = _conDer;\n        lhs.block(0, vars, _conDer.cols(), _conDer.rows()) = _conDer.transpose();\n        rhs.segment(vars, _con.size()) = -_con;\n\n        int cnt = 0;\n        for(set<LSBoxConstraint>::const_iterator it = constraints.begin(); it != constraints.end(); ++it, ++cnt)\n            lhs(vars + _conDer.rows() + cnt, it->index) = lhs(it->index, vars + _conDer.rows() + cnt) = 1.;\n\n        //lhs += damping * MatrixXd::Identity(size, size);\n        lhs.block(0, 0, vars, vars) += damping * MatrixXd::Identity(vars, vars);\n        VectorXd result = lhs.lu().solve(rhs);\n\n        out = result.segment(0, vars);\n\n#if 0\n        printf(\"Solve err = %lf\\n\", (lhs * result - rhs).norm());\n        if(_conDer.size() > 0)\n            printf(\"Con Solve err = %lf\\n\", (_conDer * out + _con).norm());\n#endif\n\n        //check which constraints we don't need\n        cnt = 0;\n        for(set<LSBoxConstraint>::iterator it = constraints.begin(); it != constraints.end(); ++cnt)\n        {\n            set<LSBoxConstraint>::iterator next = it;\n            ++next;\n            if(result(vars + _conDer.rows() + cnt) * it->sign > 0)\n            {\n                //printf(\"Unsetting constraint on variable at index %d\\n\", it->index);\n                constraints.erase(it);\n            }\n            it = next;\n        }\n    }\n\n    //for derivative verification, combine error and constraints\n    VectorXd errVec() const\n    {\n        VectorXd out(_err.size() + _con.size());\n        out << _err, _con;\n        return out;\n    }\n\n    MatrixXd errVecDer() const\n    {\n        MatrixXd out(_err.size() + _con.size(), _errDer.cols());\n        out << _errDer, _conDer;\n        return out;\n    }\n\n    VectorXd &errVectorRef() { return _err; }\n    MatrixXd &errDerRef() { return _errDer; }\n\n    VectorXd &conVectorRef() { return _con; }\n    MatrixXd &conDerRef() { return _conDer; }\n\nprivate:\n    Eigen::VectorXd _err;\n    Eigen::MatrixXd _errDer;\n    Eigen::VectorXd _con;\n    Eigen::MatrixXd _conDer;\n};\n\nclass MulticurveSparseEvalData : public LSEvalData\n{\npublic:\n    typedef Matrix<double, Dynamic, Dynamic, 0, 6, 6> BlockType;\n    typedef vector<BlockType, aligned_allocator<BlockType> > BlockVectorType;\n    typedef LLT<BlockType> BlockCholType;\n    typedef vector<BlockCholType, aligned_allocator<BlockCholType> > BlockCholVectorType;\n\n    //overrides\n    double error() const { return _con.squaredNorm(); }\n\n    void solveForDelta(double damping, Eigen::VectorXd &out, std::set<LSBoxConstraint> &constraints)\n    {\n        _computeIndices();\n\n        size_t vars = _blockIndices.back();\n        size_t cons = _con.size() + constraints.size();\n\n        size_t size = vars + cons;\n        VectorXd rhs = VectorXd::Zero(size);\n        rhs.segment(0, vars) = _err;\n        rhs.segment(vars, _con.size()) = -_con;\n\n        BlockCholVectorType cholBlocks(_errDerBlocks.size());\n        for(size_t i = 0; i < cholBlocks.size(); ++i)\n            cholBlocks[i] = BlockCholType(_errDerBlocks[i] + damping * MatrixXd::Identity(_blockSizes[i], _blockSizes[i]));\n\n        MatrixXd C = MatrixXd::Zero(cons, vars);\n        C.block(0, 0, _con.size(), vars) = _conDer;\n\n        int cnt = 0;\n        for(set<LSBoxConstraint>::const_iterator it = constraints.begin(); it != constraints.end(); ++it, ++cnt)\n            C(_conDer.rows() + cnt, it->index) = 1.;\n\n        MatrixXd K(C.cols(), C.rows());\n        _solveCholL(K, cholBlocks, C.transpose());\n        LLT<MatrixXd> CholK(K.transpose() * K);\n\n        VectorXd mid(size), result(size);\n\n        //solve for mid\n        _solveCholL(mid.segment(0, vars), cholBlocks, rhs.segment(0, vars));\n        mid.segment(vars, cons) = CholK.matrixL().solve(rhs.segment(vars, cons) - K.adjoint() * mid.segment(0, vars));\n\n        //solve for result\n        result.segment(vars, cons) = -CholK.matrixU().solve(mid.segment(vars, cons));\n        _solveCholU(result.segment(0, vars), cholBlocks, mid.segment(0, vars) - K * result.segment(vars, cons));\n\n        out = result.segment(0, vars);\n#if 0\n        if(_conDer.size() > 0)\n            printf(\"Con Solve err = %lf\\n\", (_conDer * out + _con).norm());\n#endif\n\n        //check which constraints we don't need\n        cnt = 0;\n        for(set<LSBoxConstraint>::iterator it = constraints.begin(); it != constraints.end(); ++cnt)\n        {\n            set<LSBoxConstraint>::iterator next = it;\n            ++next;\n            if(result(vars + _conDer.rows() + cnt) * it->sign > 0)\n            {\n                //printf(\"Unsetting constraint on variable at index %d\\n\", it->index);\n                constraints.erase(it);\n            }\n            it = next;\n        }\n    }\n\n    VectorXd &errVectorRef() { return _err; }\n    BlockVectorType &errDerBlocksRef() { return _errDerBlocks; }\n\n    VectorXd &conVectorRef() { return _con; }\n    MatrixXd &conDerRef() { return _conDer; }\n\nprivate:\n    void _computeIndices()\n    {\n        _blockIndices.resize(_errDerBlocks.size() + 1);\n        _blockSizes.resize(_errDerBlocks.size());\n        _blockIndices[0] = 0;\n\n        for(int i = 0; i < (int)_errDerBlocks.size(); ++i)\n        {\n            _blockSizes[i] = _errDerBlocks[i].rows();\n            _blockIndices[i + 1] = _blockIndices[i] + _blockSizes[i];\n        }\n    }\n\n    MatrixXd _blocksToMatrix(const BlockVectorType &blocks)\n    {\n        size_t sz = _blockIndices.back();\n        MatrixXd out = MatrixXd::Zero(sz, sz);\n\n        for(int i = 0; i < (int)blocks.size(); ++i)\n            out.block(_blockIndices[i], _blockIndices[i], _blockSizes[i], _blockSizes[i]) = blocks[i];\n\n        return out;\n    }\n\n    template<class M1, class M2> void _solveCholL(const M1 &out, const BlockCholVectorType &chols, const M2 &rhs)\n    {\n        for(int i = 0; i < (int)chols.size(); ++i)\n            const_cast<M1 &>(out).block(_blockIndices[i], 0, _blockSizes[i], out.cols()) =\n                chols[i].matrixL().solve(rhs.block(_blockIndices[i], 0, _blockSizes[i], rhs.cols()));\n    }\n\n    template<class M1, class M2> void _solveCholU(const M1 &out, const BlockCholVectorType &chols, const M2 &rhs)\n    {\n        for(int i = 0; i < (int)chols.size(); ++i)\n            const_cast<M1 &>(out).block(_blockIndices[i], 0, _blockSizes[i], out.cols()) =\n                chols[i].matrixU().solve(rhs.block(_blockIndices[i], 0, _blockSizes[i], rhs.cols()));\n    }\n\n    vector<size_t> _blockIndices, _blockSizes;\n    BlockVectorType _errDerBlocks;\n\n    Eigen::VectorXd _err;\n    Eigen::VectorXd _con;\n    Eigen::MatrixXd _conDer;\n};\n\nclass MulticurveProblem : public LSProblem\n{\npublic:\n    MulticurveProblem(const Fitter &fitter)\n        : _primitives(fitter.output<PRIMITIVE_FITTING>()->primitives), _iter(0)\n    {\n        smart_ptr<const AlgorithmOutput<GRAPH_CONSTRUCTION> > graph = fitter.output<GRAPH_CONSTRUCTION>();\n        const vector<int> &path = fitter.output<PATH_FINDING>()->path;\n        _errorComputer = fitter.output<ERROR_COMPUTER>()->errorComputer;\n        _closed = fitter.output<CURVE_CLOSING>()->closed;\n        _inflectionAccounting = fitter.params().get(Parameters::INFLECTION_COST) > 0.;\n\n        for(int i = 0; i < (int)path.size(); ++i)\n        {\n            _primIdcs.push_back(graph->edges[path[i]].startVtx);\n            _continuities.push_back(graph->edges[path[i]].continuity);\n        }\n        if(!_closed)\n            _primIdcs.push_back(graph->edges[path.back()].endVtx);\n        \n        _curves = VectorC<CurvePrimitivePtr>((int)_primIdcs.size(), _closed ? CIRCULAR : NOT_CIRCULAR);\n        _curveRanges = VectorC<pair<int, int> >((int)_primIdcs.size(), _curves.circular());\n        for(int i = 0; i < (int)_primIdcs.size(); ++i)\n        {\n            _curveRanges[i] = make_pair(_primitives[_primIdcs[i]].startIdx, _primitives[_primIdcs[i]].endIdx);\n            _curves[i] = _primitives[_primIdcs[i]].curve->clone();\n        }\n\n        //trim curves and ranges\n        const int sampledPts = fitter.output<RESAMPLING>()->output->pts().size();\n        for(int i = 0; i < (int)_continuities.size(); ++i)\n        {\n            if(_continuities[i] == 0)\n                continue;\n\n            //trim\n            Vector2d trimPt = 0.5 * (_curves[i]->endPos() + _curves[i + 1]->startPos());\n            if(!_primitives[_primIdcs[i]].isFixed())\n                _curves[i]->trim(0, _curves[i]->project(trimPt));\n            if(_curves.circular() || !_primitives[_primIdcs[i + 1]].isFixed())\n                _curves[i + 1]->trim(_curves[i + 1]->project(trimPt), _curves[i + 1]->length());\n\n            //the ranges over which error is computed should not overlap\n            if(_continuities[i] == 1)\n                swap(_curveRanges[i].second, _curveRanges[i + 1].first); //they overlap by 1 originally\n            if(_continuities[i] == 2) //they overlap by 2\n            {\n                _curveRanges[i + 1].first = (_curveRanges[i + 1].first + 2) % sampledPts;\n                _curveRanges[i].second = (_curveRanges[i].second + sampledPts - 2) % sampledPts;\n            }\n        }\n    }\n\n    vector<LSBoxConstraint> getConstraints() const\n    {\n        vector<LSBoxConstraint> out;\n        VectorXd curParams = params();\n\n        int curVar = 0;\n        for(int i = 0; i < _curves.size(); ++i)\n        {\n            int primIdx = _primIdcs[i];\n            if(_primitives[primIdx].isFixed())\n            {\n                int n = _curves[i]->numParams();\n                for(int j = 0; j < n; ++j, ++curVar)\n                    out.push_back(LSBoxConstraint(curVar, curParams[curVar], 0));\n\n                continue;\n            }\n\n            //length must be at least half initial\n            out.push_back(LSBoxConstraint(curVar + CurvePrimitive::LENGTH, _curves[i]->length() * 0.5, 1));\n\n            //inflections\n            //Debugging::get()->printf(\"idx = %d Type = %d, startSign = %d, endSign = %d\", i, _curves[i]->getType(), _primitives[primIdx].startCurvSign, _primitives[primIdx].endCurvSign);\n            if(_inflectionAccounting && _curves[i]->getType() >= CurvePrimitive::ARC)\n            {\n                int pi = _curves.toLinearIdx(i - 1);\n                int ni = _curves.toLinearIdx(i + 1);\n                bool c2toPrev = (pi >= 0 && _continuities[pi] == 2);\n                bool c2toNext = (ni < _curves.size() && _continuities[i] == 2);\n                bool line2Prev = c2toPrev && _curves[pi]->getType() == CurvePrimitive::LINE;\n                bool line2Next = c2toNext && _curves[ni]->getType() == CurvePrimitive::LINE;\n\n                int startSign = _primitives[primIdx].startCurvSign;\n                int endSign = _primitives[primIdx].endCurvSign;\n\n                if(!c2toPrev || (endSign == _primitives[_primIdcs[pi]].startCurvSign && startSign == endSign && !line2Prev))\n                    out.push_back(LSBoxConstraint(curVar + CurvePrimitive::CURVATURE, 0., startSign));\n                \n                if(c2toPrev && c2toNext && startSign != endSign) //constrain the \"easier one\" of the endpoints\n                {\n                    double startViolation = -_curves[i]->startCurvature() * startSign;\n                    double endViolation = -_curves[i]->endCurvature() * endSign;\n\n                    //if we're C2 with a line, don't constrain that curvature\n                    if(line2Prev)\n                        startViolation = Parameters::infinity;\n                    if(line2Next)\n                        endViolation = Parameters::infinity;\n\n                    if(startViolation < endViolation)\n                        out.push_back(LSBoxConstraint(curVar + CurvePrimitive::CURVATURE, 0., startSign));\n                    else\n                        out.push_back(LSBoxConstraint(curVar + CurvePrimitive::DCURVATURE, 0., endSign));\n                }\n\n                if(!c2toNext && _curves[i]->getType() == CurvePrimitive::CLOTHOID)\n                    out.push_back(LSBoxConstraint(curVar + CurvePrimitive::DCURVATURE, 0., endSign));\n            }\n\n            curVar += _curves[i]->numParams();\n        }\n\n        return out;\n    }\n\n#if SPARSE\n    typedef MulticurveSparseEvalData EvalDataType;\n#else\n    typedef MulticurveDenseEvalData EvalDataType;\n#endif\n\n    int _iter;\n    LSEvalData *createEvalData() { return new EvalDataType(); }\n    void eval(const Eigen::VectorXd &x, LSEvalData *data)\n    {\n        setParams(x);\n        EvalDataType *evalData = static_cast<EvalDataType *>(data);\n        _evalError(evalData);\n        _evalConstraints(evalData);\n        //printf(\"Err: obj = %lf con = %lf\\n\", evalData->errVectorRef().norm(), evalData->conVectorRef().norm()); \n    }\n\n    void setParams(const Eigen::VectorXd &x)\n    {\n        int curIdx = 0;\n        for(int i = 0; i < (int)_curves.size(); ++i)\n        {\n            if(_curves[i]->getType() != CurvePrimitive::CLOTHOID)\n            {\n                _curves[i]->setParams(x.segment(curIdx, _curves[i]->numParams()));\n            }\n            else\n            {\n                VectorXd xm = x.segment(curIdx, _curves[i]->numParams());\n                xm(CurvePrimitive::DCURVATURE) = (xm(CurvePrimitive::DCURVATURE) - xm(CurvePrimitive::CURVATURE)) / xm(CurvePrimitive::LENGTH);\n                _curves[i]->setParams(xm);\n            }\n            curIdx += _curves[i]->numParams();\n        }\n\n        if(false)\n        {\n            char name[100];\n            sprintf(name, \"Out%d\", _iter);\n            for(int i = 0; i < _curves.size(); ++i)\n                Debugging::get()->drawPrimitive(_curves[i], name, i, 2.);\n        }\n\n        ++_iter;\n    }\n\n    VectorXd params() const\n    {\n        int totParams = 0;\n        for(int i = 0; i < (int)_curves.size(); ++i)\n            totParams += _curves[i]->numParams();\n\n        VectorXd out(totParams);\n\n        int curIdx = 0;\n        for(int i = 0; i < (int)_curves.size(); ++i)\n        {\n            if(_curves[i]->getType() != CurvePrimitive::CLOTHOID)\n            {\n                out.segment(curIdx, _curves[i]->numParams()) = _curves[i]->params();\n            }\n            else\n            {\n                VectorXd xm = _curves[i]->params(); \n                xm(CurvePrimitive::DCURVATURE) = xm(CurvePrimitive::CURVATURE) + xm(CurvePrimitive::DCURVATURE) * xm(CurvePrimitive::LENGTH);\n                out.segment(curIdx, _curves[i]->numParams()) = xm;\n            }\n            curIdx += _curves[i]->numParams();\n        }\n\n        return out;\n    }\n\n    VectorC<CurvePrimitiveConstPtr> curves() const\n    {\n        VectorC<CurvePrimitiveConstPtr> out;\n        copy(_curves.begin(), _curves.end(), back_inserter(out));\n        return out;\n    }\n\n    double objective() const\n    {\n        double out = 0;\n\n        for(int i = 0; i < (int)_curves.size(); ++i)\n        {\n            int csz = (int)_continuities.size();\n            bool firstCorner = (!_closed && i == 0) || (_continuities[(i + csz - 1) % csz] == 0);\n            bool lastCorner = (!_closed && i + 1 == (int)_curves.size()) || (_continuities[i] == 0);\n\n            out += _errorComputer->computeError(_curves[i], _curveRanges[i].first, _curveRanges[i].second, firstCorner, lastCorner);\n        }\n\n        return out;\n    }\n\nprivate:\n    void _evalError(EvalDataType *evalData)\n    {\n        vector<VectorXd> errVecs(_curves.size());\n        vector<MatrixXd> errVecDers(_curves.size());\n\n        size_t numErr = 0, numVar = 0;\n        for(int i = 0; i < (int)_curves.size(); ++i)\n        {\n            int csz = (int)_continuities.size();\n            bool firstCorner = (!_closed && i == 0) || (_continuities[(i + csz - 1) % csz] == 0);\n            bool lastCorner = (!_closed && i + 1 == (int)_curves.size()) || (_continuities[i] == 0);\n\n            _errorComputer->computeErrorVector(_curves[i], _curveRanges[i].first, _curveRanges[i].second,\n                errVecs[i], &(errVecDers[i]), firstCorner, lastCorner);\n            \n            _curves[i]->toEndCurvatureDerivative(errVecDers[i]);\n\n            numErr += errVecs[i].size();\n            numVar += _curves[i]->numParams();\n        }\n\n        VectorXd &outErr = evalData->errVectorRef();\n\n#if SPARSE\n        EvalDataType::BlockVectorType &outErrDerBlocks = evalData->errDerBlocksRef();\n        outErrDerBlocks.resize(_curves.size());\n        outErr = VectorXd::Zero(numVar);\n#else\n        outErr = VectorXd::Zero(numErr);\n        MatrixXd &outErrDer = evalData->errDerRef();\n        outErrDer = MatrixXd::Zero(numErr, numVar);\n#endif\n\n        size_t curErr = 0, curVar = 0;\n        for(int i = 0; i < (int)_curves.size(); ++i)\n        {\n            size_t nErr = errVecs[i].size();\n            size_t nVar = errVecDers[i].cols();\n#if SPARSE\n            outErrDerBlocks[i] = errVecDers[i].transpose() * errVecDers[i];\n            outErr.segment(curVar, nVar) = -errVecDers[i].transpose() * errVecs[i];\n#else\n            outErrDer.block(curErr, curVar, nErr, nVar) = errVecDers[i];\n            outErr.segment(curErr, nErr) = errVecs[i];\n#endif\n            curErr += nErr;\n            curVar += nVar;\n        }\n    }\n\n    void _evalConstraints(EvalDataType *evalData)\n    {\n        VectorXd &outCon = evalData->conVectorRef();\n        MatrixXd &outConDer = evalData->conDerRef();\n\n        vector<VectorXd> conVecs(_continuities.size());\n        vector<MatrixXd> conVecDers(_continuities.size());\n\n        CurvePrimitive::EndDer endDer;\n\n        size_t numCon = 0, numVar = 0;\n        for(int i = 0; i < (int)_continuities.size(); ++i)\n        {\n            conVecs[i].resize(2 + _continuities[i]);\n            conVecs[i].head<2>() = _curves[i]->endPos() - _curves[i + 1]->startPos();\n            if(_continuities[i] >= 1)\n                conVecs[i][2] = AngleUtils::toRange(_curves[i]->endAngle() - _curves[i + 1]->startAngle(), -PI);\n            if(_continuities[i] == 2)\n                conVecs[i][3] = _curves[i]->endCurvature() - _curves[i + 1]->startCurvature();\n\n            _curves[i]->derivativeAtEnd(_continuities[i], endDer);\n            conVecDers[i] = endDer;\n            _curves[i]->toEndCurvatureDerivative(conVecDers[i]);\n\n            numCon += conVecs[i].size();\n            numVar += _curves[i]->numParams();\n        }\n\n        if(!_closed)\n            numVar += _curves.back()->numParams();\n\n        outCon = VectorXd::Zero(numCon);\n        outConDer = MatrixXd::Zero(numCon, numVar);\n\n        size_t curCon = 0, curVar = 0;\n        for(int i = 0; i < (int)_continuities.size(); ++i)\n        {\n            size_t nCon = conVecs[i].size();\n            size_t nVar = conVecDers[i].cols();\n            outCon.segment(curCon, nCon) = conVecs[i];\n            outConDer.block(curCon, curVar, nCon, nVar) = conVecDers[i];\n\n            //now the derivatives for the second curve\n            outConDer(curCon + 0, (curVar + nVar + CurvePrimitive::X) % numVar) = -1.;\n            outConDer(curCon + 1, (curVar + nVar + CurvePrimitive::Y) % numVar) = -1.;\n            if(nCon > 2)\n                outConDer(curCon + 2, (curVar + nVar + CurvePrimitive::ANGLE) % numVar) = -1.;\n            if(nCon > 3 && _curves[i + 1]->getType() != CurvePrimitive::LINE)\n                outConDer(curCon + 3, (curVar + nVar + CurvePrimitive::CURVATURE) % numVar) = -1.;\n\n            curCon += nCon;\n            curVar += nVar;\n        }\n    }\n\n    VectorC<CurvePrimitivePtr> _curves;\n    const vector<FitPrimitive> &_primitives;\n    vector<int> _primIdcs;\n    vector<int> _continuities; //continuity[i] is between curves i and i + 1\n    VectorC<pair<int, int> > _curveRanges;\n    bool _closed;\n    ErrorComputerConstPtr _errorComputer;\n    bool _inflectionAccounting;\n};\n\nclass DefaultCombiner : public Algorithm<COMBINING>\n{\npublic:\n    string name() const { return \"Default\"; }\n\nprotected:\n    void _run(const Fitter &fitter, AlgorithmOutput<COMBINING> &out)\n    {\n        smart_ptr<const AlgorithmOutput<GRAPH_CONSTRUCTION> > graph = fitter.output<GRAPH_CONSTRUCTION>();\n        const vector<FitPrimitive> &primitives = fitter.output<PRIMITIVE_FITTING>()->primitives;\n        const vector<int> &path = fitter.output<PATH_FINDING>()->path;\n        bool closed = fitter.output<CURVE_CLOSING>()->closed;\n\n        if(path.empty())\n            return; //no path\n\n        VectorC<CurvePrimitiveConstPtr> outV;\n\n        //if a single primitive\n        if(graph->edges[path[0]].continuity == -1)\n        {\n            outV = VectorC<CurvePrimitiveConstPtr>(1, NOT_CIRCULAR);\n            outV[0] = primitives[graph->edges[path[0]].startVtx].curve;\n        }\n        else //solve the nonlinear problem\n        {\n            MulticurveProblem problem(fitter);\n            vector<LSBoxConstraint> constraints = problem.getConstraints();\n            LSSolver solver(&problem, constraints);\n            solver.setDefaultDamping(fitter.params().get(Parameters::COMBINE_DAMPING));\n            solver.setMaxIter(50);\n            solver.setIncreaseDampingAfter(5);\n            solver.setDampingIncreaseFactor(1.5);\n\n            VectorXd result = solver.solve(problem.params());\n            problem.setParams(result);\n            Debugging::get()->printf(\"Final objective = %lf\", sqrt(problem.objective()));\n\n            outV = problem.curves();\n        }\n\n        //==== track what happens to parameters ====\n        out.parameters = fitter.output<RESAMPLING>()->parameters;\n        PolylineConstPtr resampledCurve = fitter.output<RESAMPLING>()->output;\n        const VectorC<Vector2d> &resampled = resampledCurve->pts();\n\n        vector<int> finalPrimitives; //gather the indices of the graph vertices corresponding to the primitives\n        for(int i = 0; i < (int)path.size(); ++i)\n            finalPrimitives.push_back(graph->edges[path[i]].startVtx);\n        if(outV.size() > (int)finalPrimitives.size())\n            finalPrimitives.push_back(graph->edges[path.back()].endVtx);\n\n        assert(outV.size() == finalPrimitives.size());\n\n        vector<double> idxToParam(resampled.size()); //idx is the index into the resampled array\n        vector<double> idxToDistSq(resampled.size(), 1e10);\n\n        double lenSoFar = 0;\n        for(int i = 0; i < outV.size(); ++i) //for each primitive see what projects to it\n        {\n            const FitPrimitive &primitive = primitives[graph->vertices[finalPrimitives[i]].primitiveIdx];\n            for(int j = primitive.startIdx; ; ++j) //project each associated resampled point onto this primitive\n            {\n                if(j == (int)resampled.size()) //be careful with starts and ends of oversketched primitives\n                {\n                    if(closed) j = 0;\n                    else\n                        break;\n                }\n\n                if(j < 0)\n                    continue;\n\n                double proj = outV[i]->project(resampled[j]);\n                double distSq = (resampled[j] - outV[i]->pos(proj)).squaredNorm();\n                if(distSq < idxToDistSq[j])\n                {\n                    idxToDistSq[j] = distSq;\n                    idxToParam[j] = proj + lenSoFar;\n                }\n\n                if(j == primitive.endIdx)\n                    break;\n            }\n            lenSoFar += outV[i]->length();\n        }\n        double outputLength = lenSoFar;\n\n        if(!closed)\n        {\n            idxToParam[0] = 0;\n            idxToParam.back() = outputLength;\n        }\n\n        int minParamSample = min_element(idxToParam.begin(), idxToParam.end()) - idxToParam.begin();\n\n        PiecewiseLinearMonotone prevToFinal(PiecewiseLinearMonotone::POSITIVE);\n        //populate prevToFinal -- don't forget duplicating first point if closed\n        prevToFinal.add(0, idxToParam[minParamSample]);\n        lenSoFar = 0;\n        for(VectorC<Vector2d>::Circulator ci = resampled.circulator(minParamSample + 1); !ci.done(); ++ci)\n        {            \n            lenSoFar += (*ci - *(ci - 1)).norm();\n            double finalParam = 0;\n            if(ci.index() == minParamSample)\n                finalParam += outputLength;\n            else\n                idxToParam[ci.index()] = max(idxToParam[ci.index()], idxToParam[(ci - 1).index()]); //ensure monotonicity\n            finalParam += idxToParam[ci.index()];\n            prevToFinal.add(lenSoFar, finalParam);\n        }\n        //adjust parameters into range\n        for(int i = 0; i < (int)out.parameters.size(); ++i)\n        {\n            out.parameters[i] -= resampledCurve->idxToParam(minParamSample);\n            if(out.parameters[i] < 0)\n                out.parameters[i] += resampledCurve->length();\n        }\n        prevToFinal.batchEval(out.parameters);\n\n        //==== combine with what needs to be done w.r.t. oversketching ====\n        smart_ptr<const AlgorithmOutput<OVERSKETCHING> > osOutput = fitter.output<OVERSKETCHING>();\n        VectorC<CurvePrimitiveConstPtr> outFinal(0, osOutput->finallyClose ? CIRCULAR : NOT_CIRCULAR);\n\n        if(osOutput->toPrepend)\n        {\n            outFinal.insert(outFinal.end(), osOutput->toPrepend->primitives().begin(), osOutput->toPrepend->primitives().end() - 1);\n            for(int i = 0; i < (int)out.parameters.size(); ++i)\n                out.parameters[i] += (osOutput->toPrepend->length() - osOutput->toPrepend->primitives().back()->length());\n        }\n        outFinal.insert(outFinal.end(), outV.begin(), outV.end());\n\n        if(osOutput->toAppend)\n        {\n            if(!osOutput->finallyClose)\n            {\n                outFinal.insert(outFinal.end(), osOutput->toAppend->primitives().begin() + 1, osOutput->toAppend->primitives().end());\n            }\n            else\n            {\n                if(osOutput->toAppend->primitives().size() >= 2)\n                {\n                    outFinal.insert(outFinal.end(), osOutput->toAppend->primitives().begin() + 1, osOutput->toAppend->primitives().end() - 1);\n                }\n                else //start and end curve is the same curve -- its original length is the one toAppend curve\n                {\n                    //get rid of last curve and possibly extend the first one\n                    double lastCurveLen = outFinal.back()->length();\n                    double firstCurveLen = outFinal[0]->length();\n                    double origLen = osOutput->toAppend->primitives()[0]->length();\n                    outFinal.pop_back();\n                    //now extend the first curve to the combined length\n                    outFinal[0] = outFinal[0]->trimmed(origLen - lastCurveLen, firstCurveLen);\n                    for(int i = 0; i < (int)out.parameters.size(); ++i)\n                        out.parameters[i] -= (origLen - lastCurveLen);\n                }\n            }\n        }\n\n        out.output = new PrimitiveSequence(outFinal);\n\n#if 1\n        for(int i = 0; i < (int)out.parameters.size(); ++i)\n        {\n            double paramOrig = fitter.originalSketch()->idxToParam(i);\n            Debugging::get()->drawLine(fitter.originalSketch()->pts()[i], out.output->pos(out.parameters[i]), Vector3d(1, 0, 1), \"Correspondence\");\n        }\n#endif\n\n    }\n};\n\nvoid Algorithm<COMBINING>::_initialize()\n{\n    new DefaultCombiner();\n}\n\nEND_NAMESPACE_Cornu\n\n\n", "meta": {"hexsha": "e2d40d90c17acd97313f30b988cda777aac8bab2", "size": 28828, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/Cornucopia/Combiner.cpp", "max_stars_repo_name": "davepagurek/StrokeStrip", "max_stars_repo_head_hexsha": "c9ae2ebac9ecbc6461952df58a05288bccc571a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40.0, "max_stars_repo_stars_event_min_datetime": "2021-05-02T04:22:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T10:07:26.000Z", "max_issues_repo_path": "external/Cornucopia/Combiner.cpp", "max_issues_repo_name": "davepagurek/StrokeStrip", "max_issues_repo_head_hexsha": "c9ae2ebac9ecbc6461952df58a05288bccc571a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-08-17T03:14:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-17T03:15:35.000Z", "max_forks_repo_path": "external/Cornucopia/Combiner.cpp", "max_forks_repo_name": "davepagurek/StrokeStrip", "max_forks_repo_head_hexsha": "c9ae2ebac9ecbc6461952df58a05288bccc571a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2021-05-15T16:04:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T04:34:21.000Z", "avg_line_length": 37.9815546772, "max_line_length": 187, "alphanum_fraction": 0.5744762037, "num_tokens": 7522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2817012370948748}}
{"text": "//    Copyright 2017 Rainer Gemulla\n// \n//    Licensed under the Apache License, Version 2.0 (the \"License\");\n//    you may not use this file except in compliance with the License.\n//    You may obtain a copy of the License at\n// \n//        http://www.apache.org/licenses/LICENSE-2.0\n// \n//    Unless required by applicable law or agreed to in writing, software\n//    distributed under the License is distributed on an \"AS IS\" BASIS,\n//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//    See the License for the specific language governing permissions and\n//    limitations under the License.\n/** \\file\n *\n * Illustrates matrix factorization with parallel SGD. We first create factors and then a data matrix\n * from these factors. This process ensures that we know the best factorization of the input.\n * These matrices are distributed across a cluster. We then try to reconstruct the factors\n * using PSGD.\n */\n#include <iostream>\n#include <sstream>\n\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <mf/matrix/io/generateDistributedMatrix.h>\n\n#include <util/evaluation.h>\n\n#include <mpi2/mpi2.h>\n#include <mf/mf.h>\n\nlog4cxx::LoggerPtr logger(log4cxx::Logger::getLogger(\"main\"));\n\nusing namespace std;\nusing namespace mf;\nusing namespace mpi2;\nusing namespace rg;\nusing namespace boost::numeric::ublas;\n\n// type of SGD\ntypedef UpdateTruncate<UpdateNzslL2> Update;\ntypedef RegularizeNone Regularize;\ntypedef SumLoss<NzslLoss, L2Loss> Loss;\ntypedef NzslLoss TestLoss;\n\nint main(int argc, char* argv[]) {\n\tusing namespace boost::program_options;\n\t// initialize mf library and mpi2\n\tboost::mpi::communicator& world = mfInit(argc, argv);\n\n\tmfStart();\n\n\tif (world.rank() == 0)\n\t{\n#ifndef NDEBUG\n\t\tLOG4CXX_WARN(logger, \"Warning: Debug mode activated (runtimes may be slow).\");\n#endif\n\t\t//data\n\t\tmf_size_type epochs;\n\t\tstring inputSampleMatrixFile;\n\t\tstring inputMatrixFile;\n\t\tstring inputRowFacFile;\n\t\tstring inputColFacFile;\n\t\tstring outputRowFacFile;\n\t\tstring outputColFacFile;\n\t\tstring inputTestMatrixFile;\n\t\tstring traceFile,traceVar;\n\t\tstring shuffleStr;\n\n\t\tdouble lambda = 50;\n\t\tdouble eps0 = 0.01;\n\t\t// parameters for distribution\n\t\tint tasks;\n\n\n\t\toptions_description desc(\"Options\");\n\t\tdesc.add_options()\n\t\t\t\t(\"help\", \"produce help message\")\n\t\t\t\t(\"epochs\", value<mf_size_type>(&epochs)->default_value(10), \"number of epochs to run [10]\")\n\t\t\t\t(\"lambda\", value<double>(&lambda)->default_value(50), \"lambda\")\n\t\t\t\t(\"eps0\", value<double>(&eps0)->default_value(0.01), \"initial step size for BoldDriver\")\n\t\t\t\t(\"tasks-per-rank\", value<int>(&tasks)->default_value(1), \"number of concurrent tasks [1]\")\n\t\t\t\t(\"trace\", value<string>(&traceFile)->default_value(\"trace.R\"), \"filename of trace [trace.R]\")\n\t\t\t\t(\"traceVar\", value<string>(&traceVar)->default_value(\"trace\"), \"variable name for trace [traceVar]\")\n\t\t\t\t(\"input-file\", value<string>(&inputMatrixFile), \"input matrix\")\n\t\t\t\t(\"input-test-file\", value<string>(&inputTestMatrixFile), \"input test matrix\")\n\t\t\t    (\"input-row-file\", value<string>(&inputRowFacFile), \"input initial row factor\")\n\t\t\t    (\"input-col-file\", value<string>(&inputColFacFile), \"input initial column factor\")\n\t\t\t    (\"output-row-file\", value<string>(&outputRowFacFile), \"output initial row factor\")\n\t\t\t    (\"output-col-file\", value<string>(&outputColFacFile), \"output initial column factor\")\n\t\t\t    (\"shuffle\",value<string>(&shuffleStr)->default_value(\"seq\"),\"shuffle method eg seq, par, parAdd\")\n\t\t\t\t;\n\n\t\tpositional_options_description pdesc;\n\t\tpdesc.add(\"input-file\", 1);\n\t\tpdesc.add(\"input-test-file\", 2);\n\t\tpdesc.add(\"input-sample-matrix-file\", 3);\n\t\tpdesc.add(\"input-row-file\", 4);\n\t\tpdesc.add(\"input-col-file\", 5);\n\n\t\tvariables_map vm;\n\t\tstore(command_line_parser(argc, argv).options(desc).positional(pdesc).run(), vm);\n\t\tnotify(vm);\n\n\t\tif (vm.count(\"help\") || vm.count(\"input-file\")==0) {\n\t\t\tcout << \"psgd with L2 NoLock (Hogwild-style) [options] <input-file> \" << endl << endl;\n\t\t\tcout << desc << endl;\n\t\t\treturn 1;\n\t\t}\n\n\t\tLOG4CXX_INFO(logger, \"Using \" << tasks << \" parallel tasks\");\n\n\t\tPsgdShuffle shuffle;\n\t\tif (shuffleStr.compare(\"seq\") == 0)\n\t\t\tshuffle= PSGD_SHUFFLE_SEQ;\n\t\telse if (shuffleStr.compare(\"par\") == 0)\n\t\t\tshuffle= PSGD_SHUFFLE_PARALLEL;\n\t\telse\n\t\t\tshuffle= PSGD_SHUFFLE_PARALLEL_ADDITIONAL_TASK;\n\n\t\tLOG4CXX_INFO(logger, \"Using \" << shuffle);\n\n\n\n\t\t// Read matrices\n\t\tRandom32 random;\n// \t\tSparseMatrix v,vTest;\n// \t\tDenseMatrix w;\n// \t\tDenseMatrixCM h;\n// \t\treadMatrix(inputMatrixFile,v);\n// \t\treadMatrix(inputTestMatrixFile,vTest);\n// \t\treadMatrix(inputRowFacFile,w);\n// \t\treadMatrix(inputColFacFile,h);\n\t\t\n\t\tTimer t;\n\t\tt.start();\n\t\tstd::vector<DistributedSparseMatrix> dataVector=getDataMatrices<SparseMatrix>(inputMatrixFile,\"V\",true,\n\t\t\t\ttasks, 1, 1, 1, true, false, &inputTestMatrixFile);\n\n\t\tSparseMatrix& v = *mpi2::env().get<SparseMatrix>(dataVector[0].blocks()(0,0).var());\n\t\tSparseMatrix& vTest = *mpi2::env().get<SparseMatrix>(dataVector[1].blocks()(0,0).var());\n\n\t  \t\n\t\tstd::pair<DistributedDenseMatrix, DistributedDenseMatrixCM> factorsPair= getFactors(inputRowFacFile,\n\t\t\tinputColFacFile,  tasks, 1, 1, 1, true);\n\t\t\n\t\tt.stop();\n\t\tLOG4CXX_INFO(logger, \"Total time for loading matrices: \" << t);\n\t\t\n\t\tDenseMatrix w = *mpi2::env().get<DenseMatrix>(factorsPair.first.blocks()(0,0).var());\n\t\tDenseMatrixCM h = *mpi2::env().get<DenseMatrixCM>(factorsPair.second.blocks()(0,0).var());\n\n\t\t// parameters for SGD\n\t\tSgdOrder order = SGD_ORDER_WOR;\n\t\tUpdate update = Update(UpdateNzslL2(lambda), -100, 100); // truncate for numerical stability\n\t\tRegularize regularize;\n\t\tLoss loss((NzslLoss()), L2Loss(lambda));\n\t\tTestLoss testLoss;\n\t\tBalanceType balanceType = BALANCE_NONE;\n\t\tBalanceMethod balanceMethod = BALANCE_OPTIMAL;\n\n\t\t// initialize the DSGD\n\t\t\n\t\tPsgdRunner psgdRunner(random);\n\t\tPsgdJob<Update,Regularize> psgdJob(v, w, h, update, regularize, order, tasks, shuffle);\n\t\tBoldDriver decay(eps0);\n\t\tTrace trace;\n\n\n\t\ttrace.addField(\"Loss\", \"L2\");\n\t\ttrace.addField(\"Shuffle_method\", shuffle);\n\t\ttrace.addField(\"input_file\", inputMatrixFile);\n\t\ttrace.addField(\"sample_matrix\", inputSampleMatrixFile);\n\t\ttrace.addField(\"tasks\", tasks);\n\n\t\t// print the test loss\n\t\tFactorizationData<> testData(vTest, w, h);\n\t\tLOG4CXX_INFO(logger, \"Initial test loss: \" << testLoss(testData));\n\n\t\t// run HogwildSGD to try to reconstruct the original factors\n\t\tt.start();\n\t\tpsgdRunner.run(psgdJob, loss, epochs, decay, trace, balanceType, balanceMethod, &testData, &testLoss);\n\n\t\tt.stop();\n\t\tLOG4CXX_INFO(logger, \"Total time: \" << t);\n\n\t\t// print the test loss\n\t\tLOG4CXX_INFO(logger, \"Final test loss: \" << testLoss(testData));\n\n\t\t// write trace to an R file\n\t\tLOG4CXX_INFO(logger, \"Writing trace to \" << traceFile);\n\t\ttrace.toRfile(traceFile, traceVar);\n\t\t\n\t\t\t\t\t// write computed factors to file\n\t\t\t\tif (outputRowFacFile.length() > 0) {\n\t\t\t\t\tLOG4CXX_INFO(logger, \"Writing row factors to \" << outputRowFacFile);\n\t\t\t\t\t//DenseMatrix w0;\n\t\t\t\t\t//unblock(dw, w0);\n\t\t\t\t\twriteMatrix(outputRowFacFile, w);\n\t\t\t\t}\n\t\t\t\tif (outputColFacFile.length() > 0) {\n\t\t\t\t\tLOG4CXX_INFO(logger, \"Writing column factors to \" << outputColFacFile);\n\t\t\t\t\t//DenseMatrixCM h0;\n\t\t\t\t\t//unblock(dh, h0);\n\t\t\t\t\twriteMatrix(outputColFacFile, h);\n\t\t\t\t}\n\t}\n\n\tmfStop();\n\tmfFinalize();\n\n\treturn 0;\n}\n", "meta": {"hexsha": "b13c0f64d792522a3421b184bc7fd8431017d3d7", "size": 7418, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tools/psgdL2NoLock.cc", "max_stars_repo_name": "wangshusen/DSGDpp", "max_stars_repo_head_hexsha": "d2b037f64f91e89800d12baff3c5d5aa57dbaa29", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2017-01-10T11:39:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-02T23:03:55.000Z", "max_issues_repo_path": "tools/psgdL2NoLock.cc", "max_issues_repo_name": "uma-pi1/DSGDpp", "max_issues_repo_head_hexsha": "d2b037f64f91e89800d12baff3c5d5aa57dbaa29", "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": "tools/psgdL2NoLock.cc", "max_forks_repo_name": "uma-pi1/DSGDpp", "max_forks_repo_head_hexsha": "d2b037f64f91e89800d12baff3c5d5aa57dbaa29", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-10-27T18:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T15:10:56.000Z", "avg_line_length": 33.7181818182, "max_line_length": 105, "alphanum_fraction": 0.7050417902, "num_tokens": 2053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.281571640036764}}
{"text": "/*\n * Copyright (c) 2020. Mohit Deshpande.\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 * 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 \"ekf/ekf_node.h\"\n\n#include <chrono>\n\n#include <ros/ros.h>\n#include <tf2_geometry_msgs/tf2_geometry_msgs.h>\n#include <tf2/utils.h>\n#include <sensor_msgs/Imu.h>\n#include <geometry_msgs/PoseWithCovarianceStamped.h>\n#include <laser_geometry/laser_geometry.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <pcl_ros/point_cloud.h>\n\n#include <std_msgs/Float32.h>\n\n#include \"ekf/ekf.h\"\n#include \"ekf/utils.h\"\n#include \"ekf/scan_matcher.h\"\n\n#include <Eigen/Eigen>\n\n#include <robot_config/robot_config.h>\n\nstatic constexpr auto kOdometryTopic = \"/wheels/encoders\";\nstatic constexpr auto kImuTopic = \"/camera/imu\";\nstatic constexpr auto kScanTopic = \"/scan\";\n\nstatic constexpr auto UPDATE_RATE = 40;\nstatic constexpr auto STATE_SIZE = 5;\n// motors can't go this fast and no one is going to move it this fast\n// still WIP on why the MCU occasionally produces really high counts\nstatic constexpr auto V_MAX_SANITY = 2.0;\nstatic constexpr auto W_MAX_SANITY = M_2_PI;\n\nnamespace ekf {\n\nEkfNode::EkfNode()\n        : prev_cloud_(new pcl::PointCloud<pcl::PointXYZ>),\n        tf_listener_(tf_buffer_) {\n    ros::NodeHandle nh;\n\n    odometry_sub_ = nh.subscribe(kOdometryTopic, 1, &EkfNode::ReceiveOdometry, this);\n    imu_sub_ = nh.subscribe(kImuTopic, 1, &EkfNode::ReceiveImu, this);\n    scan_sub_ = nh.subscribe(kScanTopic, 1, &EkfNode::ReceiveScan, this);\n\n    imu_H_ = Eigen::MatrixXd::Zero(1, 5);\n    imu_H_(0, 4) = 1;\n    imu_R_ = Eigen::MatrixXd::Identity(1, 1) * 0.1;\n\n    odom_H_ = Eigen::MatrixXd::Zero(1, 5);\n    odom_H_(0, 3) = 1;\n    odom_R_ = Eigen::MatrixXd::Identity(1, 1) * 0.1;\n\n    scan_H_ = Eigen::MatrixXd::Zero(2, 5);\n    scan_H_(0, 0) = 1;\n    scan_H_(1, 1) = 1;\n    scan_R_ = Eigen::MatrixXd::Identity(2, 2) * 0.1;\n\n    // [x, y, theta, v, w]\n    Eigen::VectorXd initial_state = Eigen::VectorXd::Zero(STATE_SIZE);\n    Eigen::MatrixXd initial_covariance = Eigen::MatrixXd::Identity(initial_state.size(), initial_state.size());\n    ekf_.state = initial_state;\n    ekf_.covariance = initial_covariance;\n\n    // publishers\n    pose_pub_ = nh.advertise<geometry_msgs::PoseWithCovarianceStamped>(\"/pose/odom\", 1);\n    last_imu_stamp_ = ros::Time::now();\n    last_odom_stamp_ = ros::Time::now();\n}\n\nvoid EkfNode::ReceiveImu(const sensor_msgs::ImuConstPtr& imu) {\n    if (first_imu_msg) {\n        first_imu_msg = false;\n        last_imu_stamp_ = imu->header.stamp;\n        return;\n    }\n\n    geometry_msgs::TransformStamped camera_link;\n    try {\n        camera_link = tf_buffer_.lookupTransform(\"camera_link\", imu->header.frame_id, imu->header.stamp);\n    } catch (const std::exception& e) {\n        ROS_ERROR_STREAM(e.what());\n        return;\n    }\n\n    geometry_msgs::Vector3 transformed_angular_velocity;\n    tf2::doTransform(imu->angular_velocity, transformed_angular_velocity, camera_link);\n\n    double dt = (imu->header.stamp - last_imu_stamp_).toSec();\n    auto w = transformed_angular_velocity.z;\n\n    // sanity checking on velocity\n    if (w > W_MAX_SANITY) {\n        ROS_WARN_STREAM(\"Impossible angular velocity!: \" << w << \"rad/s\");\n        return;\n    }\n\n    Eigen::VectorXd z(1);\n    z(0) = w;\n\n    if (!Update(ekf_, z, imu_H_, imu_R_)) {\n        ROS_ERROR(\"Not updating state! S is singular!\");\n        return;\n    }\n    Predict(ekf_, dt);\n\n    last_imu_stamp_ = imu->header.stamp;\n}\n\nvoid EkfNode::ReceiveOdometry(const motion_controller_msgs::WheelEncodersConstPtr& odometry) {\n    if (first_odom_msg) {\n        first_odom_msg = false;\n        last_odom_stamp_ = odometry->header.stamp;\n        return;\n    }\n\n    double dt = (odometry->header.stamp - last_odom_stamp_).toSec();\n    double counts = 0.5 * (odometry->left + odometry->right);\n    double v = counts * robot_config::DISTANCE_PER_COUNT / dt;\n\n    // sanity checking on velociy\n    if (v > V_MAX_SANITY) {\n        ROS_WARN_STREAM(\"Impossible velocity!: \" << v << \"m/s (l=\"\n            << odometry->left << \", r=\" << odometry->right << \")\");\n        return;\n    }\n\n    Eigen::VectorXd z(1);\n    z(0) = v;\n\n    if (!Update(ekf_, z, odom_H_, odom_R_)) {\n        ROS_ERROR(\"Not updating state! S is singular!\");\n        return;\n    }\n\n    Predict(ekf_, dt);\n\n    last_odom_stamp_ = odometry->header.stamp;\n}\n\nvoid EkfNode::ReceiveScan(const sensor_msgs::LaserScanConstPtr& scan) {\n    if (first_scan_msg) {\n        sensor_msgs::PointCloud2 cloud;\n        laser_projector_.transformLaserScanToPointCloud(\"base_link\", *scan, cloud, tf_buffer_);\n        pcl::moveFromROSMsg(cloud, *prev_cloud_);\n        prev_scan_ekf_ = ekf_;\n        first_scan_msg = false;\n        return;\n    }\n\n    sensor_msgs::PointCloud2 cloud;\n    laser_projector_.transformLaserScanToPointCloud(\"base_link\", *scan, cloud, tf_buffer_);\n    pcl::PointCloud<pcl::PointXYZ>::Ptr current_cloud(new pcl::PointCloud<pcl::PointXYZ>);\n    pcl::moveFromROSMsg(cloud, *current_cloud);\n\n    Eigen::Affine3d transform(ScanMatch({}, prev_cloud_, current_cloud));\n\n    Eigen::Vector2d z = Eigen::Vector2d::Zero();\n    z(0) = transform.translation()(0) + prev_scan_ekf_.state(0);\n    z(1) = transform.translation()(1) + prev_scan_ekf_.state(1);\n\n    if (!Update(ekf_, z, scan_H_, scan_R_)) {\n        ROS_ERROR(\"Not updating state! S is singular!\");\n    }\n\n    prev_cloud_ = current_cloud;\n    prev_scan_ekf_ = ekf_;\n}\n\nvoid EkfNode::Run() {\n    ros::Rate rate(UPDATE_RATE);\n    while (ros::ok()) {\n        geometry_msgs::PoseWithCovarianceStamped pose;\n        pose.header.frame_id = \"odom\";\n        pose.header.stamp = ros::Time::now();\n        pose.pose.pose.position.x = ekf_.state(0);\n        pose.pose.pose.position.y = ekf_.state(1);\n        pose.pose.pose.position.z = 0;\n        tf2::Quaternion orientation;\n        orientation.setRPY(0, 0, ekf_.state(2));\n        pose.pose.pose.orientation = tf2::toMsg(orientation);\n        pose.pose.covariance = toRos(ekf_.covariance);\n        ROS_INFO_STREAM(\"x=\" << pose.pose.pose.position.x\n            << \", y=\" << pose.pose.pose.position.y\n            << \", theta=\" << tf2::getYaw(pose.pose.pose.orientation));\n        pose_pub_.publish(pose);\n\n        geometry_msgs::TransformStamped transform;\n        transform.transform.translation.x = pose.pose.pose.position.x;\n        transform.transform.translation.y = pose.pose.pose.position.y;\n        transform.transform.translation.z = pose.pose.pose.position.z;\n        transform.transform.rotation = tf2::toMsg(orientation);\n        transform.header.stamp = ros::Time::now();\n        transform.header.frame_id = \"odom\";\n        transform.child_frame_id = \"base_link\";\n        tf_broadcaster_.sendTransform(transform);\n\n        rate.sleep();\n        ros::spinOnce();\n    }\n}\n\n}\n\nint main(int argc, char** argv) {\n    ros::init(argc, argv, \"ekf\");\n    ros::NodeHandle nh;\n\n    ekf::EkfNode slam;\n    slam.Run();\n\n    return 0;\n}\n\n", "meta": {"hexsha": "bcfe8404b518de5ecafdc3e54f070a005b46e8ef", "size": 7883, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ekf/src/ekf_node.cpp", "max_stars_repo_name": "mohitd/hcr", "max_stars_repo_head_hexsha": "ca63462aa3bf7b3a4ddaa52720bc4147b17c3aab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ekf/src/ekf_node.cpp", "max_issues_repo_name": "mohitd/hcr", "max_issues_repo_head_hexsha": "ca63462aa3bf7b3a4ddaa52720bc4147b17c3aab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ekf/src/ekf_node.cpp", "max_forks_repo_name": "mohitd/hcr", "max_forks_repo_head_hexsha": "ca63462aa3bf7b3a4ddaa52720bc4147b17c3aab", "max_forks_repo_licenses": ["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.4025423729, "max_line_length": 111, "alphanum_fraction": 0.673220855, "num_tokens": 2085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.28157164003676394}}
{"text": "#pragma once\n#include <Eigen/Dense>\n#include <memory>\n#include <tuple>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include \"../datastructures/multi_tree_vector.hpp\"\n#include \"basis.hpp\"\n#include \"sparse_vector.hpp\"\n\nnamespace Time {\n\ntemplate <template <typename, typename> class Operator, typename I_in,\n          typename I_out>\nclass BilinearForm {\n public:\n  using WaveletBasisIn =\n      std::remove_pointer_t<std::tuple_element_t<0, typename I_in::TupleNodes>>;\n  using WaveletBasisOut = std::remove_pointer_t<\n      std::tuple_element_t<0, typename I_out::TupleNodes>>;\n  using ScalingBasisIn = typename FunctionTrait<WaveletBasisIn>::Scaling;\n  using ScalingBasisOut = typename FunctionTrait<WaveletBasisOut>::Scaling;\n\n  // Create a stateful BilinearForm.\n  BilinearForm(I_in *root_vec_in, I_out *root_vec_out);\n\n  void Apply() {\n    InitializeInput();\n    auto [_, f] = ApplyRecur(0, {}, {});\n    FinalizeOutput(f);\n  }\n\n  void ApplyUpp() {\n    InitializeInput();\n    auto [_, f] = ApplyUppRecur(0, {}, {});\n    FinalizeOutput(f);\n  }\n\n  void ApplyLow() {\n    InitializeInput();\n    auto f = ApplyLowRecur(0, {});\n    FinalizeOutput(f);\n  }\n\n  auto Transpose() const {\n    auto transpose = BilinearForm<Operator, I_out, I_in>();\n    transpose.vec_in_ = vec_out_;\n    transpose.vec_out_ = vec_in_;\n    transpose.nodes_vec_in_ = nodes_vec_out_;\n    transpose.nodes_vec_out_ = nodes_vec_in_;\n    transpose.InitializeOutput();\n    return transpose;\n  }\n\n  // Debug function, O(n^2).\n  Eigen::MatrixXd ToMatrix();\n\n protected:\n  // Protected constructor, and give transpose operator access.\n  BilinearForm() : vec_in_(nullptr), vec_out_(nullptr) {}\n  friend BilinearForm<Operator, I_out, I_in>;\n\n  // Roots of the treeviews we are considering.\n  I_in *vec_in_;\n  I_out *vec_out_;\n\n  // A flattened (levelwise) view of input/output vectors.\n  std::shared_ptr<std::vector<std::vector<I_in *>>> nodes_vec_in_;\n  std::shared_ptr<std::vector<std::vector<I_out *>>> nodes_vec_out_;\n\n  // Another flattened (levelwise) view of the vectors, in another data format.\n  std::vector<SparseVector<WaveletBasisIn>> lvl_vec_in_;\n  std::vector<SparseIndices<WaveletBasisOut>> lvl_ind_out_;\n\n  // Helper variables.\n  SparseVector<WaveletBasisIn> empty_vec_in_;\n  SparseIndices<WaveletBasisOut> empty_ind_out_;\n\n  // Helper function to set the levelwise input/output vector.\n  void InitializeOutput();\n  void InitializeInput();\n  void FinalizeOutput(const SparseVector<WaveletBasisOut> &f);\n\n  // Recursive apply.\n  std::pair<SparseVector<ScalingBasisOut>, SparseVector<WaveletBasisOut>>\n  ApplyRecur(size_t l, SparseIndices<ScalingBasisOut> &&Pi_out,\n             const SparseVector<ScalingBasisIn> &d);\n\n  // Recursive apply upper part.\n  std::pair<SparseVector<ScalingBasisOut>, SparseVector<WaveletBasisOut>>\n  ApplyUppRecur(size_t l, SparseIndices<ScalingBasisOut> &&Pi_out,\n                const SparseVector<ScalingBasisIn> &d);\n\n  // Recursive apply lower part.\n  SparseVector<WaveletBasisOut> ApplyLowRecur(\n      size_t l, const SparseVector<ScalingBasisIn> &d);\n\n  // Index sets.\n  std::pair<SparseIndices<ScalingBasisOut>, SparseIndices<ScalingBasisOut>>\n  ConstructPiOut(SparseIndices<ScalingBasisOut> &&Pi_out,\n                 bool construct_Pi_A_out = true);\n\n  SparseIndices<ScalingBasisIn> ConstructPiBIn(\n      SparseIndices<ScalingBasisIn> &&Pi_in,\n      const SparseIndices<ScalingBasisOut> &Pi_B_out);\n};\n\n// Helper functions .\ntemplate <template <typename, typename> class Operator, typename I_in,\n          typename I_out>\nBilinearForm<Operator, I_in, I_out> CreateBilinearForm(I_in *root_vec_in,\n                                                       I_out *root_vec_out) {\n  return BilinearForm<Operator, I_in, I_out>(root_vec_in, root_vec_out);\n}\n\n// Helper functions .\ntemplate <template <typename, typename> class Operator, typename WaveletBasisIn,\n          typename WaveletBasisOut>\nBilinearForm<Operator, datastructures::NodeVector<WaveletBasisIn>,\n             datastructures::NodeVector<WaveletBasisOut>>\nCreateBilinearForm(const datastructures::TreeVector<WaveletBasisIn> &vec_in,\n                   const datastructures::TreeVector<WaveletBasisOut> &vec_out) {\n  return {vec_in.root(), vec_out.root()};\n}\n\n}  // namespace Time\n\n#include \"bilinear_form.ipp\"\n", "meta": {"hexsha": "1b9837b20a72003c574eac90abe8b369ddb19c8a", "size": 4299, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/time/bilinear_form.hpp", "max_stars_repo_name": "rvanvenetie/spacetime", "max_stars_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/time/bilinear_form.hpp", "max_issues_repo_name": "rvanvenetie/spacetime", "max_issues_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/time/bilinear_form.hpp", "max_forks_repo_name": "rvanvenetie/spacetime", "max_forks_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_forks_repo_licenses": ["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.8167938931, "max_line_length": 80, "alphanum_fraction": 0.7197022563, "num_tokens": 1109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2815666804993119}}
{"text": "#ifndef MBA_MBA_HPP\n#define MBA_MBA_HPP\n\n/*\nThe MIT License\n\nCopyright (c) 2015 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   mba/mba.hpp\n * \\author Denis Demidov <dennis.demidov@gmail.com>\n * \\brief  Multilevel B-spline interpolation.\n */\n\n#include <iostream>\n#include <iomanip>\n#include <map>\n#include <list>\n#include <utility>\n#include <algorithm>\n#include <array>\n#include <memory>\n#include <functional>\n\n#include <boost/container/flat_map.hpp>\n#include <boost/multi_array.hpp>\n#include <type_traits>\n#include <boost/io/ios_state.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\nnamespace mba {\nnamespace detail {\n\ntemplate <size_t N, size_t M>\nstruct power : std::integral_constant<size_t, N * power<N, M-1>::value> {};\n\ntemplate <size_t N>\nstruct power<N, 0> : std::integral_constant<size_t, 1> {};\n\n/// N-dimensional grid iterator (nested loop with variable depth).\ntemplate <unsigned NDim>\nclass grid_iterator {\n    public:\n        typedef std::array<size_t, NDim> index;\n\n        explicit grid_iterator(const std::array<size_t, NDim> &dims)\n            : N(dims), idx(0)\n        {\n            std::fill(i.begin(), i.end(), 0);\n            done = (i == N);\n        }\n\n        explicit grid_iterator(size_t dim) : idx(0) {\n            std::fill(N.begin(), N.end(), dim);\n            std::fill(i.begin(), i.end(), 0);\n            done = (0 == dim);\n        }\n\n        size_t operator[](size_t d) const {\n            return i[d];\n        }\n\n        const index& operator*() const {\n            return i;\n        }\n\n        size_t position() const {\n            return idx;\n        }\n\n        grid_iterator& operator++() {\n            done = true;\n            for(size_t d = NDim; d--; ) {\n                if (++i[d] < N[d]) {\n                    done = false;\n                    break;\n                }\n                i[d] = 0;\n            }\n\n            ++idx;\n\n            return *this;\n        }\n\n        operator bool() const { return !done; }\n\n    private:\n        index N, i;\n        bool  done;\n        size_t idx;\n};\n\ntemplate <typename T, size_t N>\nstd::array<T, N> operator+(std::array<T, N> a, const std::array<T, N> &b) {\n    std::transform(a.begin(), a.end(), b.begin(), a.begin(), std::plus<T>());\n    return a;\n}\n\ntemplate <typename T, size_t N>\nstd::array<T, N> operator-(std::array<T, N> a, T b) {\n    std::transform(a.begin(), a.end(), a.begin(), std::bind2nd(std::minus<T>(), b));\n    return a;\n}\n\ntemplate <typename T, size_t N>\nstd::array<T, N> operator*(std::array<T, N> a, T b) {\n    std::transform(a.begin(), a.end(), a.begin(), std::bind2nd(std::multiplies<T>(), b));\n    return a;\n}\n\n// Value of k-th B-Spline basic function at t.\ninline double Bspline(size_t k, double 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            return t * t * t / 6;\n        default:\n            return 0;\n    }\n}\n\n// Checks if p is between lo and hi\ntemplate <typename T, size_t N>\nbool boxed(const std::array<T,N> &lo, const std::array<T,N> &p, const std::array<T,N> &hi) {\n    for(unsigned i = 0; i < N; ++i) {\n        if (p[i] < lo[i] || p[i] > hi[i]) return false;\n    }\n    return true;\n}\n\ninline double safe_divide(double a, double b) {\n    return b == 0.0 ? 0.0 : a / b;\n}\n\ntemplate <unsigned NDim>\nclass control_lattice {\n    public:\n        typedef std::array<size_t, NDim> index;\n        typedef std::array<double, NDim> point;\n\n        virtual ~control_lattice() {}\n\n        virtual double operator()(const point &p) const = 0;\n\n        virtual void report(std::ostream&) const = 0;\n\n        template <class CooIter, class ValIter>\n        double residual(CooIter coo_begin, CooIter coo_end, ValIter val_begin) const {\n            double res = 0.0;\n\n            CooIter p = coo_begin;\n            ValIter v = val_begin;\n\n            for(; p != coo_end; ++p, ++v) {\n                (*v) -= (*this)(*p);\n                res = std::max(res, std::abs(*v));\n            }\n\n            return res;\n        }\n};\n\ntemplate <unsigned NDim>\nclass initial_approximation : public control_lattice<NDim> {\n    public:\n        typedef typename control_lattice<NDim>::point point;\n\n        initial_approximation(std::function<double(const point&)> f)\n            : f(f) {}\n\n        double operator()(const point &p) const {\n            return f(p);\n        }\n\n        void report(std::ostream &os) const {\n            os << \"initial approximation\";\n        }\n    private:\n        std::function<double(const point&)> f;\n};\n\ntemplate <unsigned NDim>\nclass control_lattice_dense : public control_lattice<NDim> {\n    public:\n        typedef typename control_lattice<NDim>::index index;\n        typedef typename control_lattice<NDim>::point point;\n\n        template <class CooIter, class ValIter>\n        control_lattice_dense(\n                const point &coo_min, const point &coo_max, index grid_size,\n                CooIter coo_begin, CooIter coo_end, ValIter val_begin\n                ) : cmin(coo_min), cmax(coo_max), grid(grid_size)\n        {\n            for(unsigned i = 0; i < NDim; ++i) {\n                hinv[i] = (grid[i] - 1) / (cmax[i] - cmin[i]);\n                cmin[i] -= 1 / hinv[i];\n                grid[i] += 2;\n            }\n\n            boost::multi_array<double, NDim> delta(grid);\n            boost::multi_array<double, NDim> omega(grid);\n\n            std::fill(delta.data(), delta.data() + delta.num_elements(), 0.0);\n            std::fill(omega.data(), omega.data() + omega.num_elements(), 0.0);\n\n            CooIter p = coo_begin;\n            ValIter v = val_begin;\n\n            for(; p != coo_end; ++p, ++v) {\n                if (!boxed(coo_min, *p, coo_max)) continue;\n\n                index i;\n                point s;\n\n                for(unsigned d = 0; d < NDim; ++d) {\n                    double u = ((*p)[d] - cmin[d]) * hinv[d];\n                    i[d] = floor(u) - 1;\n                    s[d] = u - floor(u);\n                }\n\n                std::array< double, power<4, NDim>::value > w;\n                double sum_w2 = 0.0;\n\n                for(grid_iterator<NDim> d(4); d; ++d) {\n                    double prod = 1.0;\n                    for(unsigned k = 0; k < NDim; ++k) prod *= Bspline(d[k], s[k]);\n\n                    w[d.position()] = prod;\n                    sum_w2 += prod * prod;\n                }\n\n                for(grid_iterator<NDim> d(4); d; ++d) {\n                    double w1  = w[d.position()];\n                    double w2  = w1 * w1;\n                    double phi = (*v) * w1 / sum_w2;\n\n                    index j = i + (*d);\n\n                    delta(j) += w2 * phi;\n                    omega(j) += w2;\n                }\n            }\n\n            phi.resize(grid);\n\n            std::transform(\n                    delta.data(), delta.data() + delta.num_elements(),\n                    omega.data(), phi.data(), safe_divide\n                    );\n        }\n\n        double operator()(const point &p) const {\n            index i;\n            point s;\n\n            for(unsigned d = 0; d < NDim; ++d) {\n                double u = (p[d] - cmin[d]) * hinv[d];\n                i[d] = floor(u) - 1;\n                s[d] = u - floor(u);\n            }\n\n            double f = 0;\n\n            for(grid_iterator<NDim> d(4); d; ++d) {\n                double w = 1.0;\n                for(unsigned k = 0; k < NDim; ++k) w *= Bspline(d[k], s[k]);\n\n                f += w * phi(i + (*d));\n            }\n\n            return f;\n        }\n\n        void report(std::ostream &os) const {\n            boost::io::ios_all_saver stream_state(os);\n\n            os << \"dense  [\" << grid[0];\n            for(unsigned i = 1; i < NDim; ++i)\n                os << \", \" << grid[i];\n            os << \"] (\" << phi.num_elements() * sizeof(double) << \" bytes)\";\n        }\n\n        void append_refined(const control_lattice_dense &r) {\n            static const std::array<double, 5> s = {\n                0.125, 0.500, 0.750, 0.500, 0.125\n            };\n\n            for(grid_iterator<NDim> i(r.grid); i; ++i) {\n                double f = r.phi(*i);\n\n                if (f == 0.0) continue;\n\n                for(grid_iterator<NDim> d(5); d; ++d) {\n                    index j;\n                    bool skip = false;\n                    for(unsigned k = 0; k < NDim; ++k) {\n                        j[k] = 2 * i[k] + d[k] - 3;\n                        if (j[k] >= grid[k]) {\n                            skip = true;\n                            break;\n                        }\n                    }\n\n                    if (skip) continue;\n\n                    double c = 1.0;\n                    for(unsigned k = 0; k < NDim; ++k) c *= s[d[k]];\n\n                    phi(j) += f * c;\n                }\n            }\n        }\n\n        double fill_ratio() const {\n            size_t total    = phi.num_elements();\n            size_t nonzeros = total - std::count(phi.data(), phi.data() + total, 0.0);\n\n            return static_cast<double>(nonzeros) / total;\n        }\n\n    private:\n        point cmin, cmax, hinv;\n        index grid;\n\n        boost::multi_array<double, NDim> phi;\n\n};\n\ntemplate <unsigned NDim>\nclass control_lattice_sparse : public control_lattice<NDim> {\n    public:\n        typedef typename control_lattice<NDim>::index index;\n        typedef typename control_lattice<NDim>::point point;\n\n        template <class CooIter, class ValIter>\n        control_lattice_sparse(\n                const point &coo_min, const point &coo_max, index grid_size,\n                CooIter coo_begin, CooIter coo_end, ValIter val_begin\n                ) : cmin(coo_min), cmax(coo_max), grid(grid_size)\n        {\n            for(unsigned i = 0; i < NDim; ++i) {\n                hinv[i] = (grid[i] - 1) / (cmax[i] - cmin[i]);\n                cmin[i] -= 1 / hinv[i];\n                grid[i] += 2;\n            }\n\n            std::map<index, two_doubles> dw;\n\n            CooIter p = coo_begin;\n            ValIter v = val_begin;\n\n            for(; p != coo_end; ++p, ++v) {\n                if (!boxed(coo_min, *p, coo_max)) continue;\n\n                index i;\n                point s;\n\n                for(unsigned d = 0; d < NDim; ++d) {\n                    double u = ((*p)[d] - cmin[d]) * hinv[d];\n                    i[d] = floor(u) - 1;\n                    s[d] = u - floor(u);\n                }\n\n                std::array< double, power<4, NDim>::value > w;\n                double sum_w2 = 0.0;\n\n                for(grid_iterator<NDim> d(4); d; ++d) {\n                    double prod = 1.0;\n                    for(unsigned k = 0; k < NDim; ++k) prod *= Bspline(d[k], s[k]);\n\n                    w[d.position()] = prod;\n                    sum_w2 += prod * prod;\n                }\n\n                for(grid_iterator<NDim> d(4); d; ++d) {\n                    double w1  = w[d.position()];\n                    double w2  = w1 * w1;\n                    double phi = (*v) * w1 / sum_w2;\n\n                    two_doubles delta_omega = {w2 * phi, w2};\n\n                    append(dw[i + (*d)], delta_omega);\n                }\n            }\n\n            phi.insert(//boost::container::ordered_unique_range,\n                    boost::make_transform_iterator(dw.begin(), delta_over_omega),\n                    boost::make_transform_iterator(dw.end(),   delta_over_omega)\n                    );\n        }\n\n        double operator()(const point &p) const {\n            index i;\n            point s;\n\n            for(unsigned d = 0; d < NDim; ++d) {\n                double u = (p[d] - cmin[d]) * hinv[d];\n                i[d] = floor(u) - 1;\n                s[d] = u - floor(u);\n            }\n\n            double f = 0;\n\n            for(grid_iterator<NDim> d(4); d; ++d) {\n                double w = 1.0;\n                for(unsigned k = 0; k < NDim; ++k) w *= Bspline(d[k], s[k]);\n\n                f += w * get_phi(i + (*d));\n            }\n\n            return f;\n        }\n\n        void report(std::ostream &os) const {\n            boost::io::ios_all_saver stream_state(os);\n\n            size_t grid_size = grid[0];\n\n            os << \"sparse [\" << grid[0];\n            for(unsigned i = 1; i < NDim; ++i) {\n                os << \", \" << grid[i];\n                grid_size *= grid[i];\n            }\n\n            size_t bytes = phi.size() * sizeof(std::pair<index, double>);\n            size_t dense_bytes = grid_size * sizeof(double);\n\n            double compression = static_cast<double>(bytes) / dense_bytes;\n            os << \"] (\" << bytes << \" bytes, compression: \"\n                << std::fixed << std::setprecision(2) << compression << \")\";\n        }\n    private:\n        point cmin, cmax, hinv;\n        index grid;\n\n        typedef boost::container::flat_map<index, double> sparse_grid;\n        sparse_grid phi;\n\n        typedef std::array<double, 2> two_doubles;\n\n        static std::pair<index, double> delta_over_omega(const std::pair<index, two_doubles> &dw) {\n            return std::make_pair(dw.first, safe_divide(dw.second[0], dw.second[1]));\n        }\n\n        static void append(two_doubles &a, const two_doubles &b) {\n            std::transform(a.begin(), a.end(), b.begin(), a.begin(), std::plus<double>());\n        }\n\n        double get_phi(const index &i) const {\n            typename sparse_grid::const_iterator c = phi.find(i);\n            return c == phi.end() ? 0.0 : c->second;\n        }\n};\n\n} // namespace detail\n\ntemplate <unsigned NDim>\nclass linear_approximation {\n    public:\n        typedef typename detail::control_lattice<NDim>::point point;\n\n        template <class CooIter, class ValIter>\n        linear_approximation(CooIter coo_begin, CooIter coo_end, ValIter val_begin)\n        {\n            namespace ublas = boost::numeric::ublas;\n\n            size_t n = std::distance(coo_begin, coo_end);\n\n            if (n <= NDim) {\n                // Not enough points to get a unique plane\n                std::fill(C.begin(), C.end(), 0.0);\n                C[NDim] = std::accumulate(val_begin, val_begin + n, 0.0) / n;\n                return;\n            }\n\n            ublas::matrix<double> A(NDim+1, NDim+1); A.clear();\n            ublas::vector<double> f(NDim+1);         f.clear();\n\n            CooIter p = coo_begin;\n            ValIter v = val_begin;\n\n            double sum_val = 0.0;\n\n            // Solve least-squares problem to get approximation with a plane.\n            for(; p != coo_end; ++p, ++v, ++n) {\n                std::array<double, NDim+1> x;\n                std::copy(p->begin(), p->end(), boost::begin(x));\n                x[NDim] = 1.0;\n\n                for(unsigned i = 0; i <= NDim; ++i) {\n                    for(unsigned j = 0; j <= NDim; ++j) {\n                        A(i,j) += x[i] * x[j];\n                    }\n                    f(i) += x[i] * (*v);\n                }\n\n                sum_val += (*v);\n            }\n\n            ublas::permutation_matrix<size_t> pm(NDim+1);\n            ublas::lu_factorize(A, pm);\n\n            bool singular = false;\n            for(unsigned i = 0; i <= NDim; ++i) {\n                if (A(i,i) == 0.0) {\n                    singular = true;\n                    break;\n                }\n            }\n\n            if (singular) {\n                std::fill(C.begin(), C.end(), 0.0);\n                C[NDim] = sum_val / n;\n            } else {\n                ublas::lu_substitute(A, pm, f);\n                for(unsigned i = 0; i <= NDim; ++i) C[i] = f(i);\n            }\n        }\n\n        double operator()(const point &p) const {\n            double f = C[NDim];\n\n            for(unsigned i = 0; i < NDim; ++i)\n                f += C[i] * p[i];\n\n            return f;\n        }\n    private:\n        std::array<double, NDim+1> C;\n};\n\ntemplate <unsigned NDim>\nclass MBA {\n    public:\n        typedef std::array<size_t, NDim> index;\n        typedef std::array<double, NDim> point;\n\n        template <class CooIter, class ValIter>\n        MBA(\n                const point &coo_min, const point &coo_max, index grid,\n                CooIter coo_begin, CooIter coo_end, ValIter val_begin,\n                unsigned max_levels = 8, double tol = 1e-8, double min_fill = 0.5,\n                std::function<double(point)> initial = std::function<double(point)>()\n           )\n        {\n            init(\n                    coo_min, coo_max, grid,\n                    coo_begin, coo_end, val_begin,\n                    max_levels, tol, min_fill, initial\n                );\n        }\n\n        template <class CooRange, class ValRange>\n        MBA(\n                const point &coo_min, const point &coo_max, index grid,\n                CooRange coo, ValRange val,\n                unsigned max_levels = 8, double tol = 1e-8, double min_fill = 0.5,\n                std::function<double(point)> initial = std::function<double(point)>()\n           )\n        {\n            init(\n                    coo_min, coo_max, grid,\n                    boost::begin(coo), boost::end(coo), boost::begin(val),\n                    max_levels, tol, min_fill, initial\n                );\n        }\n\n        double operator()(const point &p) const {\n            double f = 0.0;\n\n            for(const auto &psi : cl) {\n                f += (*psi)(p);\n            }\n\n            return f;\n        }\n\n        friend std::ostream& operator<<(std::ostream &os, const MBA &h) {\n            size_t level = 0;\n            for(const auto &psi : h.cl) {\n                os << \"level \" << ++level << \": \";\n                psi->report(os);\n                os << std::endl;\n            }\n            return os;\n        }\n\n    private:\n        typedef detail::control_lattice<NDim>        lattice;\n        typedef detail::initial_approximation<NDim>  initial_approximation;\n        typedef detail::control_lattice_dense<NDim>  dense_lattice;\n        typedef detail::control_lattice_sparse<NDim> sparse_lattice;\n\n\n        std::list< std::shared_ptr<lattice> > cl;\n\n        template <class CooIter, class ValIter>\n        void init(\n                const point &cmin, const point &cmax, index grid,\n                CooIter coo_begin, CooIter coo_end, ValIter val_begin,\n                unsigned max_levels, double tol, double min_fill,\n                std::function<double(point)> initial\n                )\n        {\n            using namespace mba::detail;\n\n            const ptrdiff_t n = std::distance(coo_begin, coo_end);\n            std::vector<double> val(val_begin, val_begin + n);\n\n            double res, eps = 0.0;\n            for(ptrdiff_t i = 0; i < n; ++i)\n                eps = std::max(eps, std::abs(val[i]));\n            eps *= tol;\n\n            if (initial) {\n                // Start with the given approximation.\n                cl.push_back(std::make_shared<initial_approximation>(initial));\n                res = cl.back()->residual(coo_begin, coo_end, val.begin());\n                if (res <= eps) return;\n            }\n\n            size_t lev = 1;\n            // Create dense head of the hierarchy.\n            {\n                auto psi = std::make_shared<dense_lattice>(\n                        cmin, cmax, grid, coo_begin, coo_end, val.begin());\n\n                res = psi->residual(coo_begin, coo_end, val.begin());\n                double fill = psi->fill_ratio();\n\n                for(; (lev < max_levels) && (res > eps) && (fill > min_fill); ++lev) {\n                    grid = grid * 2ul - 1ul;\n\n                    auto f = std::make_shared<dense_lattice>(\n                            cmin, cmax, grid, coo_begin, coo_end, val.begin());\n\n                    res = f->residual(coo_begin, coo_end, val.begin());\n                    fill = f->fill_ratio();\n\n                    f->append_refined(*psi);\n                    psi.swap(f);\n                }\n\n                cl.push_back(psi);\n            }\n\n            // Create sparse tail of the hierrchy.\n            for(; (lev < max_levels) && (res > eps); ++lev) {\n                grid = grid * 2ul - 1ul;\n\n                cl.push_back(std::make_shared<sparse_lattice>(\n                        cmin, cmax, grid, coo_begin, coo_end, val.begin()));\n\n                res = cl.back()->residual(coo_begin, coo_end, val.begin());\n            }\n        }\n};\n\n} // namespace mba\n\n#endif\n", "meta": {"hexsha": "99366370382f30541d887ad160222042f9a4f116", "size": 21369, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/mpi/mba.hpp", "max_stars_repo_name": "moyner/amgcl", "max_stars_repo_head_hexsha": "a551614040f0a7b793b41a4a63386675ca61d8da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-11-07T08:31:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-25T20:35:28.000Z", "max_issues_repo_path": "examples/mpi/mba.hpp", "max_issues_repo_name": "moyner/amgcl", "max_issues_repo_head_hexsha": "a551614040f0a7b793b41a4a63386675ca61d8da", "max_issues_repo_licenses": ["MIT"], "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/mpi/mba.hpp", "max_forks_repo_name": "moyner/amgcl", "max_forks_repo_head_hexsha": "a551614040f0a7b793b41a4a63386675ca61d8da", "max_forks_repo_licenses": ["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.9247467438, "max_line_length": 99, "alphanum_fraction": 0.4819598484, "num_tokens": 5388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.28156667302213134}}
{"text": "/*\n  Copyright (c) 2012, 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 \"OSFilter.hxx\"\n\n#include <iostream>\n#include <string.h>\n#include <fftw3.h>\n#include <math.h>\n#include <boost/format.hpp>\n\nstatic unsigned int ipow(unsigned int x, unsigned int y)\n{\n  unsigned int ret;\n  ret = 1;\n  unsigned int i;\n\n  for(i = 0; i < y; i++) {\n    ret *= x; \n  }\n\n  return ret; \n}\n\nSoDa::OSFilter::OSFilter(float * filter_impulse_response,\n\t\t\t unsigned int filter_length,\n\t\t\t float filter_gain, \n\t\t\t unsigned int inout_buffer_length,\n\t\t\t OSFilter * cascade, \n\t\t\t unsigned int suggested_transform_length)\n{\n  // these are the salient dimensions for this Overlap/Save\n  // widget (for terminology, see Lyons pages 719ff\n  Q = filter_length; // to start with. \n  M = inout_buffer_length;\n\n  if((cascade != NULL) && (cascade->M != M)) cascade = NULL;\n\n  if(M < 4 * Q) {\n    std::cerr << \"Warning -- OSFilter asked to implement a long filter against a short buffer.\" << std::endl;\n  }\n  \n  // now find N.\n  if(suggested_transform_length > (M + Q - 1)) {\n    N = suggested_transform_length; \n  }\n  else {\n    N = guessN(); \n  }\n  \n  // now that we have N, we can back-calculate Q.\n  Q = N - M;\n\n  tail_index = M - (Q - 1);\n\n  // now build the transform image for the filter.\n  std::complex<float> * filter_in = (std::complex<float> *) fftwf_malloc(sizeof(std::complex<float>) * N);\n  filter_fft = (std::complex<float> *) fftwf_malloc(sizeof(std::complex<float>) * N);\n  \n  // create a temporary plan\n  fftwf_plan tplan = fftwf_plan_dft_1d(N, (fftwf_complex*) filter_in, (fftwf_complex*) filter_fft,\n\t\t\t\t       FFTW_FORWARD, FFTW_ESTIMATE);\n  \n  // now build the filter\n  // fill with zeros\n  unsigned int i; \n  for(i = 0; i < N; i++) filter_in[i] = std::complex<float>(0.0,0.0);\n  // fill in the impulse response\n  float gain_corr = 1.0 / ((float) N) * filter_gain;\n  for(i = 0; i < filter_length; i++) filter_in[i] = std::complex<float>(filter_impulse_response[i] * gain_corr, 0.0);\n  \n  // transform the filter. \n  fftwf_execute(tplan);\n\n  // and forget the plan. \n  fftwf_destroy_plan(tplan);\n\n  // filter lengths must be equal too\n  if((cascade != NULL) && (cascade->N != N)) cascade = NULL;\n\n  // if there is a cascaded filter, multiply our filter coeffs by the cascaded filter coeffs\n  if(cascade != NULL) {\n    for(i = 0; i < N; i++) {\n      std::complex<double> a = filter_fft[i];\n      std::complex<double> b = cascade->filter_fft[i];\n      std::complex<double> ff = a * b * ((double) N); \n      filter_fft[i] = std::complex<float>(ff.real(), ff.imag()); \n    }\n  }\n  \n  \n  // setup the fft buffers\n  setupFFT();\n}\n\nSoDa::OSFilter::OSFilter(float low_cutoff,\n\t\t\t float low_pass_edge,\n\t\t\t float high_pass_edge,\n\t\t\t float high_cutoff,\n\n\t\t\t unsigned int filter_length,\n\t\t\t float filter_gain,\n\t\t\t float sample_rate, \n\n\t\t\t unsigned int inout_buffer_length,\n\t\t\t unsigned int suggested_transform_length)\n{\n  // remember our edges\n  low_edge = (double) low_pass_edge;\n  high_edge = (double) high_pass_edge;\n  \n  // first find our buffer sizes.\n  Q = filter_length;\n  M = inout_buffer_length;\n  if(M < 4 * Q) {\n    std::cerr << \"Warning -- OSFilter asked to implement a long filter against a short buffer.\" << std::endl;\n  }\n  \n  // now find N.\n  if(suggested_transform_length > (M + Q - 1)) {\n    N = suggested_transform_length; \n  }\n  else {\n    N = guessN(); \n  }\n\n  // now back calculate the actual filter length\n  Q = N - M;\n\n  tail_index = M - (Q - 1);\n\n  // OK.  now we build the filter.\n  // First, build an allpass filter with the appropriate delay\n  std::complex<float> * filter_in = (std::complex<float> *) fftwf_malloc(sizeof(std::complex<float>) * N);\n  filter_fft = (std::complex<float> *) fftwf_malloc(sizeof(std::complex<float>) * N);\n\n  unsigned int i, j;\n  for(i = 0; i < N; i++) filter_in[i] = std::complex<float>(0.0,0.0);\n  filter_in[Q/2] = std::complex<float>(1.0, 0.0);\n  // we'll use the image of this filter for the phase part of our filter.\n  \n  fftwf_plan fplan = fftwf_plan_dft_1d(N, (fftwf_complex *) filter_in, (fftwf_complex *) filter_fft,\n\t\t\t\t       FFTW_FORWARD, FFTW_ESTIMATE);\n  fftwf_plan ifplan = fftwf_plan_dft_1d(N, (fftwf_complex *) filter_fft, (fftwf_complex *) filter_in,\n\t\t\t\t       FFTW_BACKWARD, FFTW_ESTIMATE);\t\t\t\t\t\n\n  // create an image that we can fill in.\n  fftwf_execute(fplan);\n\n  float freq_step = sample_rate / ((float) N);\n  float fr; \n  // now setup the filter image;\n  for(fr = 0.0, i = 0, j = (N - 1); i < N/2; i++, j--, fr += freq_step) {\n    if(fr < low_cutoff) {\n      filter_fft[i] = std::complex<float>(0.0,0.0);\n      filter_fft[j] = std::complex<float>(0.0,0.0);\n    }\n    else if(fr < low_pass_edge) {\n      float mult = (fr - low_cutoff) / (low_pass_edge - low_cutoff);\n      filter_fft[i] = filter_fft[i] * std::complex<float>(mult, 0.0);\n      filter_fft[j] = filter_fft[j] * std::complex<float>(mult, 0.0);\n    }\n    else if(fr < high_pass_edge) {\n      // keep the all pass value\n    }\n    else if(fr < high_cutoff) {\n      float mult = 1.0 - ((fr - high_pass_edge) / (high_cutoff - high_pass_edge));\n      filter_fft[i] = filter_fft[i] * std::complex<float>(mult, 0.0);\n      filter_fft[j] = filter_fft[j] * std::complex<float>(mult, 0.0);\n    }\n    else {\n      filter_fft[i] = std::complex<float>(0.0,0.0);\n      filter_fft[j] = std::complex<float>(0.0,0.0);\n    }\n  }\n\n  // inverse transform the filter image\n  fftwf_execute(ifplan);\n\n  // now we've got a FIR filter, but it needs to be windowed before we can trust it.\n  for(i = 0; i < Q/2; i++) {\n    int ii = (Q/2) - i;\n    float ang = 2.0 * M_PI * ((float) ii) / ((float) Q); \n    std::complex<float> wf(0.5 + 0.5 * cos(ang), 0.0);\n    filter_in[i] = filter_in[i] * wf; \n    filter_in[Q - i] = filter_in[Q - i] * wf; \n  }\n  for(i = Q; i < N; i++) {\n    filter_in[i] = std::complex<float>(0.0, 0.0); \n  }\n\n  // now create the filter image\n  fftwf_execute(fplan);\n\n  // now we need to normalize the envelope so that we get the specified gain.\n  float maxval = 0.0;\n  for(i = 0; i < N; i++) {\n    float v = abs(filter_fft[i]);\n    if(v > maxval) maxval = v; \n  }\n\n  std::complex<float> normalize(filter_gain / (((float) N) * maxval), 0.0);\n\n  for(i = 0; i < N; i++) {\n    filter_fft[i] = filter_fft[i] * normalize; \n  }\n\n  // and destroy the plans\n  fftwf_destroy_plan(fplan); \n  fftwf_destroy_plan(ifplan); \n\n  // and free the impulse response\n  fftwf_free(filter_in);\n  \n  // and setup the FFT buffers\n  setupFFT(); \n}\n\n\n\nint SoDa::OSFilter::guessN()\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  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  return N_best; \n}\n\nvoid SoDa::OSFilter::setupFFT()\n{\n  unsigned int i; \n  // now allocate all the storage vectors\n  fft_input = (std::complex<float> *) fftwf_malloc(sizeof(std::complex<float>) * N);\n  fft_output = (std::complex<float> *) fftwf_malloc(sizeof(std::complex<float>) * N);\n  ifft_output = (std::complex<float> *) fftwf_malloc(sizeof(std::complex<float>) * N);\n  \n  // and create the plans\n  forward_plan = fftwf_plan_dft_1d(N,\n\t\t\t\t   (fftwf_complex *) fft_input,\n\t\t\t\t   (fftwf_complex *) fft_output,\n\t\t\t\t   FFTW_FORWARD, FFTW_ESTIMATE);\n  backward_plan = fftwf_plan_dft_1d(N,\n\t\t\t\t    (fftwf_complex *) fft_output,\n\t\t\t\t    (fftwf_complex *) ifft_output,\n\t\t\t\t    FFTW_BACKWARD, FFTW_ESTIMATE);\n\n  // zero out the start of the fft_input buffer for the first iteration.\n  for(i = 0; i < Q-1; i++) fft_input[i] = std::complex<float>(0.0,0.0);\n\n}\n\nunsigned int SoDa::OSFilter::apply(float * inbuf, float * outbuf, float outgain, int instride, int outstride)\n{\n  unsigned int i, j;\n  // copy the input buffer.\n  for(i = 0, j = Q-1; i < (M * instride); i += instride, j++) {\n    fft_input[j] = std::complex<float>(inbuf[i], 0.0); \n  }\n  \n  // now do the forward FFT on the input\n  fftwf_execute(forward_plan);\n\n  // save the last bits of the input buffer to the Q-1 side of the FFT input vector\n  // Do this now incase in buf and outbuf are the same buffers.  (we're going to\n  // over-write most of outbuf with the memcpy at the bottom.... )\n  for(i = (tail_index * instride), j = 0; j < Q-1; i += instride, j++) {\n    fft_input[j] = std::complex<float>(inbuf[i], 0.0);\n  }\n\n  // apply the filter.\n  for(i = 0; i < N; i++) {\n    fft_output[i] = (fft_output[i] * filter_fft[i]) * outgain; \n  }\n  \n  // now do the backward FFT on the result\n  fftwf_execute(backward_plan);\n\n\n  // and copy the result to the output buffer, but discard the\n  // first Q-1 chunks\n  for(i = 0, j = Q-1; i < (M * outstride); i += outstride, j++) {\n    outbuf[i] = ifft_output[j].real();\n  }\n\n  return M; \n}\n\nunsigned int SoDa::OSFilter::apply(std::complex<float> * inbuf, std::complex<float> * outbuf, float outgain)\n{\n  // This is the overlap-save FFT filter technique described in Lyons pages 719ff.\n  // first we need to copy the input buffer to the M side of the FFT input vector.\n  memcpy(&(fft_input[Q-1]), inbuf, sizeof(std::complex<float>) * M);\n\n  // now do the forward FFT on the input\n  fftwf_execute(forward_plan);\n\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're going to\n  // over-write most of outbuf with the memcpy at the bottom.... )\n  memcpy(fft_input, &(inbuf[tail_index]), sizeof(std::complex<float>) * (Q-1));\n\n  // apply the filter.\n  unsigned int i;\n  for(i = 0; i < N; i++) {\n    fft_output[i] = (fft_output[i] * filter_fft[i]) * outgain; \n  }\n  \n  // now do the backward FFT on the result\n  fftwf_execute(backward_plan);\n\n  // and copy the result to the output buffer, but discard the\n  // first Q-1 chunks\n  memcpy(outbuf, &(ifft_output[Q-1]), sizeof(std::complex<float>) * M);\n\n  return M; \n}\n\nvoid SoDa::OSFilter::dump(std::ostream & os)\n{\n  unsigned int i;\n  os << \"# idx  real   imag   abs   arg\" << std::endl; \n  for(i = 0; i < N; i++) {\n    float mag = abs(filter_fft[i]);\n    float phase = arg(filter_fft[i]); \n    os << i << \" \" << filter_fft[i].real() << \" \" << filter_fft[i].imag() << \" \" << mag << \" \" << phase << std::endl;\n  }\n}\n", "meta": {"hexsha": "7ba1f9fde985f5f828b09ff6459295a49bf6de10", "size": 11858, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/OSFilter.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/OSFilter.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/OSFilter.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": 31.876344086, "max_line_length": 117, "alphanum_fraction": 0.6418451678, "num_tokens": 3534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723316860482762, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.28150319901031107}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 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_DETAIL_IMPLODER_HPP\n#define CRYPTO3_DETAIL_IMPLODER_HPP\n\n#include <boost/crypto3/detail/stream_endian.hpp>\n#include <boost/crypto3/detail/unbounded_shift.hpp>\n#include <boost/crypto3/detail/reverser.hpp>\n\n#include <boost/static_assert.hpp>\n\nnamespace boost {\n    namespace crypto3 {\n        namespace detail {\n\n            // By definition, for all imploders, InputValueBits < OutputValueBits,\n            // so we're taking many smaller values and combining them into one value\n\n            /*!\n             * @defgroup imploder Imploder functions\n             */\n\n            /*!\n             * @brief imploder_shift trait is used to determine whether the input elements are packed into\n             * an output element in reverse order. Since the input and output types are integral now, this\n             * trait contains the shift indicating the position of input element in the output element when\n             * k input bits have already been processed.\n             *\n             * @ingroup imploder\n             *\n             * @tparam OutputEndianness\n             * @tparam UnitBits\n             * @tparam InputBits\n             * @tparam OutputBits\n             * @tparam k\n             * @tparam IsLittleUnit\n             */\n            template<typename OutputEndianness, int UnitBits, int InputBits, int OutputBits, int k,\n                     bool IsLittleUnit = is_little_unit<OutputEndianness, UnitBits>::value>\n            struct imploder_shift;\n\n            template<typename OutputEndianness, int UnitBits, int InputBits, int OutputBits, int k>\n            struct imploder_shift<OutputEndianness, UnitBits, InputBits, OutputBits, k, false> {\n                constexpr static int const value = OutputBits - (InputBits + k);\n            };\n\n            template<typename OutputEndianness, int UnitBits, int InputBits, int OutputBits, int k>\n            struct imploder_shift<OutputEndianness, UnitBits, InputBits, OutputBits, k, true> {\n                constexpr static int const value = k;\n            };\n\n            /*!\n             * @brief imploder_step packs an input value represented in InputEndianness endianness\n             * into an output value represented in OutputEndianness endianness when k input bits\n             * have already been processed. It uses unit_reverser and bit_reverser to deal with the\n             * order of units and bits in the input value, respectively. Shift constant is determined\n             * by the imploder_shift trait.\n             *\n             * @ingroup imploder\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam UnitBits\n             * @tparam InputBits\n             * @tparam OutputBits\n             * @tparam k\n             */\n            template<typename InputEndianness, typename OutputEndianness, int UnitBits, int InputBits, int OutputBits,\n                     int k>\n            struct imploder_step {\n                constexpr static int const shift =\n                    imploder_shift<OutputEndianness, UnitBits, InputBits, OutputBits, k>::value;\n\n                template<typename InputValue, typename OutputValue>\n                inline static void step(InputValue &in, OutputValue &out) {\n                    InputValue tmp = in;\n                    unit_reverser<InputEndianness, OutputEndianness, UnitBits>::reverse(tmp);\n                    bit_reverser<InputEndianness, OutputEndianness, UnitBits>::reverse(tmp);\n                    out |= unbounded_shl<shift>(low_bits<InputBits>(OutputValue(tmp)));\n                }\n            };\n\n            /*!\n             * @brief imploder processes a sequence of input values represented in InputEndianness endianness\n             * into an output value represented in OutputEndianness endianness. The function implode is\n             * invoked recursively, and the parameter k is used to track the number of already processed\n             * input values packed into the output value. The recursion ends when all elements the output\n             * value can hold have already been processed, i.e. when k == OutputBits.\n             *\n             * @ingroup imploder\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam InputBits\n             * @tparam OutputBits\n             * @tparam k\n             */\n            template<typename InputEndianness, typename OutputEndianness, int InputBits, int OutputBits, int k = 0>\n            struct imploder;\n\n            template<template<int> class InputEndian, template<int> class OutputEndian, int UnitBits, int InputBits,\n                     int OutputBits, int k>\n            struct imploder<InputEndian<UnitBits>, OutputEndian<UnitBits>, InputBits, OutputBits, k> {\n\n                // To keep the implementation managable, input and output sizes must\n                // be multiples or factors of the unit size.\n                // If one of these is firing, you may want a bit-only stream_endian\n                // rather than one that mentions bytes or octets.\n                BOOST_STATIC_ASSERT(!(InputBits % UnitBits && UnitBits % InputBits));\n                BOOST_STATIC_ASSERT(!(OutputBits % UnitBits && UnitBits % OutputBits));\n\n                typedef InputEndian<UnitBits> InputEndianness;\n                typedef OutputEndian<UnitBits> OutputEndianness;\n                typedef imploder_step<InputEndianness, OutputEndianness, UnitBits, InputBits, OutputBits, k> step_type;\n                typedef imploder<InputEndianness, OutputEndianness, InputBits, OutputBits, k + InputBits> next_type;\n\n                template<typename InIter, typename OutputValue>\n                inline static void implode(InIter &in, OutputValue &x) {\n                    step_type::step(*in++, x);\n                    next_type::implode(in, x);\n                }\n            };\n\n            template<template<int> class InputEndian, template<int> class OutputEndian, int UnitBits, int InputBits,\n                     int OutputBits>\n            struct imploder<InputEndian<UnitBits>, OutputEndian<UnitBits>, InputBits, OutputBits, OutputBits> {\n                template<typename InIter, typename OutputValue>\n                inline static void implode(InIter &, OutputValue &) {\n                }\n            };\n\n        }    // namespace detail\n    }        // namespace crypto3\n}    // namespace boost\n\n#endif    // CRYPTO3_DETAIL_IMPLODER_HPP", "meta": {"hexsha": "9feafecb5d279d8923d63bc3d64e5fe95990d1e6", "size": 6913, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/crypto3/detail/imploder.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/detail/imploder.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/detail/imploder.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": 48.3426573427, "max_line_length": 119, "alphanum_fraction": 0.598437726, "num_tokens": 1403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.4493926344647596, "lm_q1q2_score": 0.28137559350670727}}
{"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\n//     Barend Gehrels (Geodan, Amsterdam)\n//     Adam Wulkiewicz\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/dpar.hpp>\n#include <boost/geometry/srs/projections/impl/pj_datum_set.hpp>\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#include <boost/geometry/srs/projections/spar.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\ntemplate <typename T>\ninline T pj_ell_b_to_es(T const& a, T const& b)\n{\n    return 1. - (b * b) / (a * a);\n}\n\n/************************************************************************/\n/*                          pj_ell_init_ellps()                         */\n/************************************************************************/\n\n// Originally a part of pj_ell_set()\ntemplate <typename T>\ninline bool pj_ell_init_ellps(srs::detail::proj4_parameters const& params, T &a, T &b)\n{\n    /* check if ellps present and temporarily append its values to pl */\n    std::string name = pj_get_param_s(params, \"ellps\");\n    if (! name.empty())\n    {\n        const pj_ellps_type<T>* pj_ellps = pj_get_ellps<T>().first;\n        const int n = pj_get_ellps<T>().second;\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(error_unknown_ellp_param) );\n        }\n\n        pj_ellps_type<T> const& pj_ellp = pj_ellps[index];\n        a = pj_ellp.a;\n        b = pj_ellp.b;\n\n        return true;\n    }\n\n    return false;\n}\n\ntemplate <typename T>\ninline bool pj_ell_init_ellps(srs::dpar::parameters<T> const& params, T &a, T &b)\n{\n    /* check if ellps present and temporarily append its values to pl */\n    typename srs::dpar::parameters<T>::const_iterator\n        it = pj_param_find(params, srs::dpar::ellps);\n    if (it != params.end())\n    {\n        if (it->template is_value_set<int>())\n        {\n            const pj_ellps_type<T>* pj_ellps = pj_get_ellps<T>().first;\n            const int n = pj_get_ellps<T>().second;\n            int i = it->template get_value<int>();\n        \n            if (i < 0 || i >= n) {\n                BOOST_THROW_EXCEPTION( projection_exception(error_unknown_ellp_param) );\n            }\n\n            pj_ellps_type<T> const& pj_ellp = pj_ellps[i];\n            a = pj_ellp.a;\n            b = pj_ellp.b;\n        }\n        else if (it->template is_value_set<T>())\n        {\n            a = it->template get_value<T>();\n            b = a;\n        }\n        else if (it->template is_value_set<srs::spheroid<T> >())\n        {\n            srs::spheroid<T> const& s = it->template get_value<srs::spheroid<T> >();\n            a = geometry::get_radius<0>(s);\n            b = geometry::get_radius<2>(s);\n        }\n        else\n        {\n            BOOST_THROW_EXCEPTION( projection_exception(error_unknown_ellp_param) );\n        }\n\n        return true;\n    }\n\n    return false;\n}\n\ntemplate\n<\n    typename Params,\n    int I = srs::spar::detail::tuples_find_index_if\n        <\n            Params,\n            srs::spar::detail::is_param_tr<srs::spar::detail::ellps_traits>::pred\n        >::value,\n    int N = boost::tuples::length<Params>::value\n>\nstruct pj_ell_init_ellps_static\n{\n    template <typename T>\n    static bool apply(Params const& params, T &a, T &b)\n    {\n        typedef typename boost::tuples::element<I, Params>::type param_type;\n        typedef srs::spar::detail::ellps_traits<param_type> traits_type;\n        typedef typename traits_type::template model_type<T>::type model_type;\n\n        param_type const& param = boost::tuples::get<I>(params);\n        model_type const& model = traits_type::template model<T>(param);\n\n        a = geometry::get_radius<0>(model);\n        b = geometry::get_radius<2>(model);\n\n        return true;\n    }\n};\ntemplate <typename Params, int N>\nstruct pj_ell_init_ellps_static<Params, N, N>\n{\n    template <typename T>\n    static bool apply(Params const& , T & , T & )\n    {\n        return false;\n    }\n};\n\ntemplate <typename T, BOOST_GEOMETRY_PROJECTIONS_DETAIL_TYPENAME_PX>\ninline bool pj_ell_init_ellps(srs::spar::parameters<BOOST_GEOMETRY_PROJECTIONS_DETAIL_PX> const& params,\n                              T &a, T &b)\n{\n    return pj_ell_init_ellps_static\n        <\n            srs::spar::parameters<BOOST_GEOMETRY_PROJECTIONS_DETAIL_PX>\n        >::apply(params, a, b);\n}\n\n/************************************************************************/\n/*                             pj_ell_init()                            */\n/************************************************************************/\n\n/* initialize geographic shape parameters */\n// This function works differently than the original pj_ell_set().\n// It doesn't push parameters defined in ellps into params list.\n// Instead it tries to use size (a, R) and shape (es, e, rf, f, b) parameters\n// and then if needed falls back to ellps, then to datum and then to the default WGS84\ntemplate <typename Params, typename T>\ninline void pj_ell_init(Params const& params, T &a, T &es)\n{\n    /* check for varying forms of ellipsoid input */\n    a = es = 0.;\n\n    /* R takes precedence */\n    if (pj_param_f<srs::spar::r>(params, \"R\", srs::dpar::r, a)) {\n        /* empty */\n    } else { /* probable elliptical figure */\n\n        // Set ellipsoid's size parameter\n        a = pj_get_param_f<T, srs::spar::a>(params, \"a\", srs::dpar::a);\n        bool is_a_set = a != 0.0;\n\n        // Set ellipsoid's shape parameter\n        T b = 0.0;\n        bool is_ell_set = false;\n        if (pj_param_f<srs::spar::es>(params, \"es\", srs::dpar::es, es)) {/* eccentricity squared */\n            /* empty */\n            is_ell_set = true;\n        } else if (pj_param_f<srs::spar::e>(params, \"e\", srs::dpar::e, es)) { /* eccentricity */\n            es = es * es;\n            is_ell_set = true;\n        } else if (pj_param_f<srs::spar::rf>(params, \"rf\", srs::dpar::rf, es)) { /* recip flattening */\n            if (es == 0.0) {\n                BOOST_THROW_EXCEPTION( projection_exception(error_rev_flattening_is_zero) );\n            }    \n            es = 1./ es;\n            es = es * (2. - es);\n            is_ell_set = true;\n        } else if (pj_param_f<srs::spar::f>(params, \"f\", srs::dpar::f, es)) { /* flattening */\n            es = es * (2. - es);\n            is_ell_set = true;\n        } else if (pj_param_f<srs::spar::b>(params, \"b\", srs::dpar::b, b)) { /* minor axis */\n            es = pj_ell_b_to_es(a, b);\n            is_ell_set = true;\n        } /* else es == 0. and sphere of radius a */\n\n        // NOTE: Below when ellps is used to initialize a and es\n        // b is not set because it only has sense together with a\n        // but a could have been set separately before, e.g. consider passing:\n        // a=1 ellps=airy (a=6377563.396 b=6356256.910)\n        // after setting size parameter a and shape parameter from ellps\n        // b has to be recalculated\n\n        // If ellipsoid's parameters are not set directly\n        //   use ellps parameter\n        if (! is_a_set || ! is_ell_set) {\n            T ellps_a = 0, ellps_b = 0;\n            if (pj_ell_init_ellps(params, ellps_a, ellps_b)) {\n                if (! is_a_set) {\n                    a = ellps_a;\n                    is_a_set = true;\n                }\n                if (! is_ell_set) {\n                    es = pj_ell_b_to_es(ellps_a, ellps_b);\n                    is_ell_set = true;\n                }\n            }\n        }\n\n        // If ellipsoid's parameters are not set\n        //   use ellps defined by datum parameter\n        if (! is_a_set || ! is_ell_set)\n        {\n            const pj_datums_type<T>* datum = pj_datum_find_datum<T>(params);\n            if (datum != NULL)\n            {\n                pj_ellps_type<T> const& pj_ellp = pj_get_ellps<T>().first[datum->ellps];\n                if (! is_a_set) {\n                    a = pj_ellp.a;\n                    is_a_set = true;\n                }\n                if (! is_ell_set) {\n                    es = pj_ell_b_to_es(pj_ellp.a, pj_ellp.b);\n                    is_ell_set = true;\n                }\n            }\n        }\n\n        // If ellipsoid's parameters are still not set\n        //   use default WGS84\n        if ((! is_a_set || ! is_ell_set)\n         && ! pj_get_param_b<srs::spar::no_defs>(params, \"no_defs\", srs::dpar::no_defs))\n        {\n            pj_ellps_type<T> const& pj_ellp = pj_get_ellps<T>().first[srs::dpar::ellps_wgs84];\n            if (! is_a_set) {\n                a = pj_ellp.a;\n                is_a_set = true;\n            }\n            if (! is_ell_set) {\n                es = pj_ell_b_to_es(pj_ellp.a, pj_ellp.b);\n                is_ell_set = true;\n            }\n        }\n\n        if (b == 0.0)\n            b = a * sqrt(1. - es);\n\n        /* following options turn ellipsoid into equivalent sphere */\n        if (pj_get_param_b<srs::spar::r_au>(params, \"R_A\", srs::dpar::r_au)) { /* sphere--area of ellipsoid */\n            a *= 1. - es * (SIXTH<T>() + es * (RA4<T>() + es * RA6<T>()));\n            es = 0.;\n        } else if (pj_get_param_b<srs::spar::r_v>(params, \"R_V\", srs::dpar::r_v)) { /* sphere--vol. of ellipsoid */\n            a *= 1. - es * (SIXTH<T>() + es * (RV4<T>() + es * RV6<T>()));\n            es = 0.;\n        } else if (pj_get_param_b<srs::spar::r_a>(params, \"R_a\", srs::dpar::r_a)) { /* sphere--arithmetic mean */\n            a = .5 * (a + b);\n            es = 0.;\n        } else if (pj_get_param_b<srs::spar::r_g>(params, \"R_g\", srs::dpar::r_g)) { /* sphere--geometric mean */\n            a = sqrt(a * b);\n            es = 0.;\n        } else if (pj_get_param_b<srs::spar::r_h>(params, \"R_h\", srs::dpar::r_h)) { /* sphere--harmonic mean */\n            a = 2. * a * b / (a + b);\n            es = 0.;\n        } else {\n            T tmp;\n            bool i = pj_param_r<srs::spar::r_lat_a>(params, \"R_lat_a\", srs::dpar::r_lat_a, tmp);\n            if (i || /* sphere--arith. */\n                pj_param_r<srs::spar::r_lat_g>(params, \"R_lat_g\", srs::dpar::r_lat_g, tmp)) { /* or geom. mean at latitude */\n\n                tmp = sin(tmp);\n                if (geometry::math::abs(tmp) > geometry::math::half_pi<T>()) {\n                    BOOST_THROW_EXCEPTION( projection_exception(error_ref_rad_larger_than_90) );\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(error_es_less_than_zero) );\n    }\n    if (a <= 0.) {\n        BOOST_THROW_EXCEPTION( projection_exception(error_major_axis_not_given) );\n    }\n}\n\ntemplate <typename Params>\nstruct static_srs_tag_check_nonexpanded\n{\n    typedef typename boost::mpl::if_c\n        <\n            srs::spar::detail::tuples_exists_if\n                <\n                    Params, srs::spar::detail::is_param_t<srs::spar::r>::pred\n                >::value\n         || srs::spar::detail::tuples_exists_if\n                <\n                    Params, srs::spar::detail::is_param<srs::spar::r_au>::pred\n                >::value\n         || srs::spar::detail::tuples_exists_if\n                <\n                    Params, srs::spar::detail::is_param<srs::spar::r_v>::pred\n                >::value\n         || srs::spar::detail::tuples_exists_if\n                <\n                    Params, srs::spar::detail::is_param<srs::spar::r_a>::pred\n                >::value\n         || srs::spar::detail::tuples_exists_if\n                <\n                    Params, srs::spar::detail::is_param<srs::spar::r_g>::pred\n                >::value\n         || srs::spar::detail::tuples_exists_if\n                <\n                    Params, srs::spar::detail::is_param<srs::spar::r_h>::pred\n                >::value\n         || srs::spar::detail::tuples_exists_if\n                <\n                    Params, srs::spar::detail::is_param_t<srs::spar::r_lat_a>::pred\n                >::value\n         || srs::spar::detail::tuples_exists_if\n                <\n                    Params, srs::spar::detail::is_param_t<srs::spar::r_lat_g>::pred\n                >::value,\n            srs_sphere_tag,\n            // NOTE: The assumption here is that if the user defines either one of:\n            // b, es, e, f, rf parameters then he wants to define spheroid, not sphere\n            typename boost::mpl::if_c\n                <\n                    srs::spar::detail::tuples_exists_if\n                        <\n                            Params, srs::spar::detail::is_param_t<srs::spar::b>::pred\n                        >::value\n                 || srs::spar::detail::tuples_exists_if\n                        <\n                            Params, srs::spar::detail::is_param_t<srs::spar::es>::pred\n                        >::value\n                 || srs::spar::detail::tuples_exists_if\n                        <\n                            Params, srs::spar::detail::is_param_t<srs::spar::e>::pred\n                        >::value\n                 || srs::spar::detail::tuples_exists_if\n                        <\n                            Params, srs::spar::detail::is_param_t<srs::spar::rf>::pred\n                        >::value\n                 || srs::spar::detail::tuples_exists_if\n                        <\n                            Params, srs::spar::detail::is_param_t<srs::spar::f>::pred\n                        >::value,\n                    srs_spheroid_tag,\n                    void\n                >::type\n        >::type type;\n};\n\ntemplate <typename Params>\nstruct static_srs_tag_check_ellps\n{\n    typedef typename geometry::tag\n        <\n            typename srs::spar::detail::ellps_traits\n                <\n                    typename srs::spar::detail::tuples_find_if\n                        <\n                            Params,\n                            srs::spar::detail::is_param_tr<srs::spar::detail::ellps_traits>::pred\n                        >::type\n                >::template model_type<double>::type // dummy type\n        >::type type;\n};\n\ntemplate <typename Params>\nstruct static_srs_tag_check_datum\n{\n    typedef typename geometry::tag\n        <\n            typename srs::spar::detail::ellps_traits\n                <\n                    typename srs::spar::detail::datum_traits\n                        <\n                            typename srs::spar::detail::tuples_find_if\n                                <\n                                    Params,\n                                    srs::spar::detail::is_param_tr<srs::spar::detail::datum_traits>::pred\n                                >::type\n                        >::ellps_type\n                >::template model_type<double>::type // dummy type\n        >::type type;\n};\n\ntemplate\n<\n    typename Params,\n    typename NonExpandedTag = typename static_srs_tag_check_nonexpanded\n                                <\n                                    Params\n                                >::type,\n    typename EllpsTag = typename static_srs_tag_check_ellps\n                            <\n                                Params\n                            >::type,\n    typename DatumTag = typename static_srs_tag_check_datum\n                            <\n                                Params\n                            >::type\n>\nstruct static_srs_tag\n{\n    // User passed one of the non-ellps, non-datum parameters\n    typedef NonExpandedTag type;\n};\n\ntemplate <typename Params, typename EllpsTag, typename DatumTag>\nstruct static_srs_tag<Params, void, EllpsTag, DatumTag>\n{\n    // User didn't pass neither one of the non-ellps, non-datum parameters\n    // but passed ellps\n    typedef EllpsTag type;\n};\n\ntemplate <typename Params, typename DatumTag>\nstruct static_srs_tag<Params, void, void, DatumTag>\n{\n    // User didn't pass neither one of the non-ellps, non-datum parameters\n    // nor ellps parameter but passed datum parameter\n    typedef DatumTag type;\n};\n\ntemplate <typename Params>\nstruct static_srs_tag<Params, void, void, void>\n{\n    // User didn't pass any parameter defining model\n    // so use default or generate error\n    typedef typename boost::mpl::if_c\n        <\n            srs::spar::detail::tuples_exists_if\n                <\n                    Params, srs::spar::detail::is_param<srs::spar::no_defs>::pred\n                >::value,\n            void,\n            srs_spheroid_tag // WGS84\n        >::type type;\n\n    static const bool is_found = ! boost::is_same<type, void>::value;\n    BOOST_MPL_ASSERT_MSG((is_found), UNKNOWN_ELLP_PARAM, (Params));\n};\n\n\ntemplate <typename T>\ninline void pj_calc_ellipsoid_params(parameters<T> & p, T const& a, T const& es) {\n/****************************************************************************************\n    Calculate a large number of ancillary ellipsoidal parameters, in addition to\n    the two traditional PROJ defining parameters: Semimajor axis, a, and the\n    eccentricity squared, es.\n\n    Most of these parameters are fairly cheap to compute in comparison to the overall\n    effort involved in initializing a PJ object. They may, however, take a substantial\n    part of the time taken in computing an individual point transformation.\n\n    So by providing them up front, we can amortize the (already modest) cost over all\n    transformations carried out over the entire lifetime of a PJ object, rather than\n    incur that cost for every single transformation.\n\n    Most of the parameter calculations here are based on the \"angular eccentricity\",\n    i.e. the angle, measured from the semiminor axis, of a line going from the north\n    pole to one of the foci of the ellipsoid - or in other words: The arc sine of the\n    eccentricity.\n\n    The formulae used are mostly taken from:\n\n    Richard H. Rapp: Geometric Geodesy, Part I, (178 pp, 1991).\n    Columbus, Ohio:  Dept. of Geodetic Science\n    and Surveying, Ohio State University.\n\n****************************************************************************************/\n\n    p.a = a;\n    p.es = es;\n\n    /* Compute some ancillary ellipsoidal parameters */\n    if (p.e==0)\n        p.e = sqrt(p.es);  /* eccentricity */\n    //p.alpha = asin (p.e);  /* angular eccentricity */\n\n    /* second eccentricity */\n    //p.e2  = tan (p.alpha);\n    //p.e2s = p.e2 * p.e2;\n\n    /* third eccentricity */\n    //p.e3    = (0!=p.alpha)? sin (p.alpha) / sqrt(2 - sin (p.alpha)*sin (p.alpha)): 0;\n    //p.e3s = p.e3 * p.e3;\n\n    /* flattening */\n    //if (0==p.f)\n    //    p.f  = 1 - cos (p.alpha);   /* = 1 - sqrt (1 - PIN->es); */\n    //p.rf = p.f != 0.0 ? 1.0/p.f: HUGE_VAL;\n\n    /* second flattening */\n    //p.f2  = (cos(p.alpha)!=0)? 1/cos (p.alpha) - 1: 0;\n    //p.rf2 = p.f2 != 0.0 ? 1/p.f2: HUGE_VAL;\n\n    /* third flattening */\n    //p.n  = pow (tan (p.alpha/2), 2);\n    //p.rn = p.n != 0.0 ? 1/p.n: HUGE_VAL;\n\n    /* ...and a few more */\n    //if (0==p.b)\n    //    p.b  = (1 - p.f)*p.a;\n    //p.rb = 1. / p.b;\n    p.ra = 1. / p.a;\n\n    p.one_es = 1. - p.es;\n    if (p.one_es == 0.) {\n        BOOST_THROW_EXCEPTION( projection_exception(error_eccentricity_is_one) );\n    }\n\n    p.rone_es = 1./p.one_es;\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": "2dac28b9271bd9a29d959bee98bd5a7455351b65", "size": 22036, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/srs/projections/impl/pj_ell_set.hpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/geometry/srs/projections/impl/pj_ell_set.hpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/geometry/srs/projections/impl/pj_ell_set.hpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 36.8494983278, "max_line_length": 125, "alphanum_fraction": 0.5465601743, "num_tokens": 5627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.28135931178618545}}
{"text": "#include <iostream>\n#include <cassert>\n#include <vector>\n#include <map>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/depth_first_search.hpp>\n\nconst int debug_level = 0;\n\n#define DEBUG(min_level, x)      \\\n  if (debug_level >= min_level)  \\\n  {                              \\\n    std::cerr << x << std::endl; \\\n  }\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS> Graph;\n\nclass DfsVisitor : public boost::default_dfs_visitor\n{\npublic:\n  DfsVisitor(std::vector<std::vector<int>> &jump_pointers_by_node) : jump_pointers_by_node(jump_pointers_by_node){};\n\n  void discover_vertex(int node, const Graph &G)\n  {\n    for (int i = 1; i <= int(path.size()); i = i << 1)\n    {\n      jump_pointers_by_node.at(node).push_back(path.at(path.size() - i));\n    }\n    path.push_back(node);\n  }\n\n  void finish_vertex(int node, const Graph &G)\n  {\n    assert(!path.empty() && path.back() == node);\n    path.pop_back();\n  }\n\nprivate:\n  std::vector<int> path;\n  std::vector<std::vector<int>> &jump_pointers_by_node;\n};\n\nvoid testcase()\n{\n  int n, q;\n  std::cin >> n >> q;\n  assert(n >= 1 && n <= 5e4 && q >= 1 && q <= 5e4);\n\n  std::map<std::string, int> species_by_name;\n  std::vector<std::string> names_by_node(n);\n  std::vector<int> age_by_node(n);\n  for (int i = 0; i < n; i++)\n  {\n    std::string name;\n    int age;\n    std::cin >> name >> age;\n    assert(name.size() >= 1 && name.size() <= 10 && age >= 0 && age <= 1e9);\n    species_by_name[name] = i;\n    names_by_node.at(i) = name;\n    age_by_node.at(i) = age;\n  }\n\n  Graph G(n);\n  std::vector<bool> has_parent_by_node(n, false);\n  for (int i = 1; i < n; i++)\n  {\n    std::string name_s, name_p;\n    std::cin >> name_s >> name_p;\n    const int s = species_by_name.at(name_s), p = species_by_name.at(name_p);\n    assert(age_by_node.at(s) <= age_by_node.at(p));\n    boost::add_edge(p, s, G);\n    assert(!has_parent_by_node.at(s));\n    has_parent_by_node.at(s) = true;\n  }\n\n  const int root = std::find(has_parent_by_node.begin(), has_parent_by_node.end(), false) - has_parent_by_node.begin();\n  std::vector<std::vector<int>> jump_pointers_by_node(n);\n  boost::depth_first_search(G, boost::root_vertex(root).visitor(DfsVisitor(jump_pointers_by_node)));\n\n  for (int i = 0; i < q; i++)\n  {\n    std::string name_s;\n    int b;\n    std::cin >> name_s >> b;\n    assert(b >= 0 && b <= 1e9);\n    const int s = species_by_name.at(name_s);\n    assert(age_by_node.at(s) <= b);\n\n    int cursor = s;\n    int j = std::numeric_limits<int>::max();\n    while (true)\n    {\n      j = std::min(int(jump_pointers_by_node.at(cursor).size() - 1), j);\n      if (j < 0)\n      {\n        break;\n      }\n      const int p = jump_pointers_by_node.at(cursor).at(j);\n      if (age_by_node.at(p) > b)\n      {\n        j--;\n        continue;\n      }\n      cursor = p;\n    }\n\n    if (i > 0)\n    {\n      std::cout << \" \";\n    }\n    std::cout << names_by_node.at(cursor);\n  }\n  std::cout << \"\\n\";\n}\n\nint main()\n{\n  std::ios_base::sync_with_stdio(false);\n\n  int t;\n  std::cin >> t;\n  for (int i = 0; i < t; i++)\n  {\n    testcase();\n    DEBUG(1, \"\");\n  }\n\n  return 0;\n}", "meta": {"hexsha": "6935520c5f0c42185f2eaf6fc6a3287d5ffa29a3", "size": 3107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "week-13/evolution/src/main.cpp", "max_stars_repo_name": "tehwalris/algolab", "max_stars_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-17T08:21:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-17T08:21:32.000Z", "max_issues_repo_path": "week-13/evolution/src/main.cpp", "max_issues_repo_name": "tehwalris/algolab", "max_issues_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week-13/evolution/src/main.cpp", "max_forks_repo_name": "tehwalris/algolab", "max_forks_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0852713178, "max_line_length": 119, "alphanum_fraction": 0.5864177663, "num_tokens": 943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.28134441761855017}}
{"text": "#include <iostream>\n#include <math.h>\n#include \"properties.hpp\"\n#include \"constants.hpp\"\n#include \"bomd_rescale.hpp\"\n#include \"qm_qchem.hpp\"\n//\n#include <armadillo>\n//\n\n\nvoid\nRescaleBomd::get_reader_data(ConfigBlockReader& reader) {\n//    reader.get_data(\"additional_energy\", additional_energy);\n//    reader.get_data(\"step\", step);\n//    reader.get_data(\"dE\", dE);\n    (void) reader;\n};\n\n\nConfigBlockReader\nRescaleBomd::setup_reader() {\n    //using types = ConfigBlockReader::types;\n    std::cout << \"Setup Rescale BOMD\\n\";\n    ConfigBlockReader reader{\"bomd-rescale\"};\n    //\n    //reader.add_entry(\"active_state\", 0);\n    /*\n    reader.add_entry(\"additional_energy\", 1.0);\n    reader.add_entry(\"dE\", 0.01);\n    reader.add_entry(\"step\", 1);\n    */\n    return reader;\n};\n\ndouble \nRescaleBomd::update_gradient()\n{\n    qm->update();\n\n    /*\n    PropMap props{};\n    props.emplace(QMProperty::qmgradient, &qm_grd);\n    props.emplace(QMProperty::mmgradient, &mm_grd);\n    props.emplace(QMProperty::energies, &energy);\n    //\n\n    qm->get_properties(props);\n    */\n    //\n    qm_grd.fill(0.0);\n    mm_grd.fill(0.0);\n    //\n    double ene = 0.0; //energy[0];\n    if (additional_energy > 0.0) {\n       ene += additional_energy;\n    }\n    total_energy = ene;\n    return ene;\n};\n\ndouble\nkinetic_energy(arma::mat &velocities, arma::vec &masses) {\n    double ekin = 0.0;\n    for (arma::uword i=0; i<masses.n_elem; ++i) {\n        for (arma::uword j=0; j<3; ++j) {\n            ekin += 0.5 * velocities(j, i) * velocities(j, i)  * masses[i];\n        }\n    }\n    return ekin;\n}\n\nbool RescaleBomd::rescale_velocities(arma::mat &velocities, arma::vec &masses, arma::mat &total_gradient, double e_drift) {\n  static int ncall = 1;\n  bool retval = false;\n\n  (void) total_gradient;\n  (void) e_drift;\n\n  const double ekin = kinetic_energy(velocities, masses); \n  const double factor = 1.0 + dE/ekin;\n  //\n  if ((ncall % step) == 0) {\n    std::cout << \"Rescale kinetic energy \\n\";\n    std::cout << \"factor: \" << factor << \"\\n\";\n    if (additional_energy > dE) {\n        std::cout << \"we actually scale!\\n\";\n        velocities *= sqrt(factor);\n        additional_energy -= dE;\n    }\n    retval = true;\n  }\n  ncall += 1;\n  std::cout << \"Total energy \" << total_energy << \"au \" << \" ekin = \" << ekin << \"\\n\";\n  return retval;\n};\n", "meta": {"hexsha": "fb23100a4a8f204f3c068f93653987b62e358018", "size": 2304, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gifs_src/bomd_rescale.cpp", "max_stars_repo_name": "farajilab/gifs_release", "max_stars_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "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": "gifs_src/bomd_rescale.cpp", "max_issues_repo_name": "farajilab/gifs_release", "max_issues_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gifs_src/bomd_rescale.cpp", "max_forks_repo_name": "farajilab/gifs_release", "max_forks_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-08T00:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T00:11:00.000Z", "avg_line_length": 23.7525773196, "max_line_length": 123, "alphanum_fraction": 0.6080729167, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.28117924928204835}}
{"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///\n/// Code implementing isotopic scattering according to Tamura's\n/// formula:\n/// S.-I. Tamura, Isotope scattering of dispersive phonons in Ge,\n///    Phys. Rev. B 27 (1983) 858–866\n/// A. Kundu, N. Mingo, D.A. Broido, D.A. Stewart, Role of light and\n///    heavy embedded nanoparticles on the thermal conductivity of SiGe\n///    alloys, Phys. Rev. B 84 (2011) 125426.\n/// The same method is used for alloys in the virtual crystal\n/// approximation.\n/// The classes and functions in this file are modelled after those\n/// declared in processes.hpp. There are, however, some differences.\n/// The most important aspects are:\n/// - Conservation of momentum is not enforced for two-phonon\n/// processes.\n/// - The Gaussian factor of each process is computed when the object\n/// is built.\n/// - The matrix element of each process is not stored in the object.\n\n#include <cstddef>\n#include <cmath>\n#include <array>\n#include <vector>\n#include <boost/mpi.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/serialization/array.hpp>\n#include <structures.hpp>\n#include <qpoint_grid.hpp>\n#include <boost/math/distributions/normal.hpp>\n\n// Forward declarations of elements documented later on.\n// Note that serialization of std::vectors of objects without\n// a default constructor is broken in Boost version 1.58.0. See:\n// http://stackoverflow.com/a/30437359/85371\n// https://svn.boost.org/trac/boost/ticket/11342\n// This will prevent ALMA from compiling. We check for that\n// specific version in our cmake configuration.\n\nnamespace alma {\n/// Compute the 25th and 75th percentiles of log(sigma)\n///\n/// @param[in] sigma an Eigen array with all broadening parameters\n/// @return an array containing the 25th and 75th percentiles\nstd::array<double, 2> calc_percentiles_log(\n    const Eigen::Ref<const Eigen::ArrayXXd>& sigma);\n/// Representation of a elastic two-phonon process.\nclass Twoph_process {\nprivate:\n    friend class boost::serialization::access;\n\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    /// Deviation from the conservation of energy.\n    double domega;\n    /// Standard deviation of the Gaussian.\n    double sigma;\n    /// Gaussian factor of the process, coming from the\n    /// regularized Dirac delta.\n    double gaussian;\n\n\n    /// serialization function\n    template <class Archive>\n    void serialize(Archive& ar, const unsigned int version) {\n        ar & this->domega;\n        ar & this->sigma;\n        ar & this->gaussian;\n        ar & this->c;\n        ar & this->q;\n        ar & this->alpha;\n    }\n\n\npublic:\n    /// Equivalence class of the first phonon.\n    std::size_t c;\n    /// q point indices of each of the two phonons involved.\n    std::array<std::size_t, 2> q;\n    /// Mode indices of the two phonons involved.\n    std::array<std::size_t, 2> alpha;\n    /// Default constructor\n    Twoph_process(){};\n    /// Basic constructor.\n    Twoph_process(std::size_t _c,\n                  const std::array<std::size_t, 2>& _q,\n                  const std::array<std::size_t, 2>& _alpha,\n                  double _domega,\n                  double _sigma)\n        : domega(_domega), sigma(_sigma),\n          gaussian(boost::math::pdf(boost::math::normal(0., sigma), domega)),\n          c(_c), q(std::move(_q)), alpha(std::move(_alpha)) {\n    }\n\n\n    /// Copy constructor.\n    Twoph_process(const Twoph_process& original)\n        : domega(original.domega), sigma(original.sigma),\n          gaussian(original.gaussian), c(original.c), q(original.q),\n          alpha(original.alpha) {\n    }\n    /// Copy assignement operator\n    Twoph_process& operator=(const Twoph_process& rhs) {\n        using std::swap;\n        this->domega = rhs.domega;\n        this->sigma = rhs.sigma;\n        this->gaussian = rhs.gaussian;\n        this->c = rhs.c;\n        this->q = rhs.q;\n        this->alpha = rhs.alpha;\n        return *this;\n    }\n\n\n    /// Move constructor:\n    Twoph_process(Twoph_process&& rhs) {\n        using std::swap;\n        swap(this->domega, rhs.domega);\n        swap(this->sigma, rhs.sigma);\n        swap(this->gaussian, rhs.gaussian);\n        swap(this->c, rhs.c);\n        swap(this->q, rhs.q);\n        swap(this->alpha, rhs.alpha);\n    }\n\n    /// Swap to enable swap semmantics\n    void swap(Twoph_process& lhs, Twoph_process& rhs) {\n        using std::swap;\n        swap(this->domega, rhs.domega);\n        swap(this->sigma, rhs.sigma);\n        swap(this->gaussian, rhs.gaussian);\n        swap(this->c, rhs.c);\n        swap(this->q, rhs.q);\n        swap(this->alpha, rhs.alpha);\n    }\n\n\n    /// Move assignement operator\n    Twoph_process& operator=(Twoph_process&& rhs) {\n        using std::swap;\n        swap(this->domega, rhs.domega);\n        swap(this->sigma, rhs.sigma);\n        swap(this->gaussian, rhs.gaussian);\n        swap(this->c, rhs.c);\n        swap(this->q, rhs.q);\n        swap(this->alpha, rhs.alpha);\n        return *this;\n    }\n\n    /// Explicit constructor used when deserializing objects of\n    /// this class. Save time by avoiding the calculatio of\n    /// this->gaussian.\n    Twoph_process(std::size_t _c,\n                  const std::array<std::size_t, 2>& _q,\n                  const std::array<std::size_t, 2>& _alpha,\n                  double _domega,\n                  double _sigma,\n                  double _gaussian)\n        : domega(_domega), sigma(_sigma), gaussian(_gaussian), c(_c),\n          q(std::move(_q)), alpha(std::move(_alpha)) {\n    }\n\n\n    /// Get the \"partial scattering rate\" Gamma for this process.\n    ///\n    /// @param[in] cell - description of the unit cell\n    /// @param[in] grid - regular grid with phonon spectrum\n    /// @return Gamma, the partial scattering rate\n    double compute_gamma(const Crystal_structure& cell,\n                         const Gamma_grid& grid) const;\n\n    /// Get the \"partial scattering rate\" Gamma for this process.\n    /// using a custom set of g factors.\n    ///\n    /// @param[in] cell - description of the unit cell\n    /// @param[in] gfactors - Pearson deviation coefficient of the mass\n    /// at each site.\n    /// @param[in] grid - regular grid with phonon spectrum\n    /// @return Gamma, the partial scattering rate\n    double compute_gamma(const Crystal_structure& cell,\n                         const Eigen::Ref<const Eigen::VectorXd>& gfactors,\n                         const Gamma_grid& grid) const;\n};\n/// Look for allowed two-phonon processes in a regular grid.\n///\n/// Iterate over part of the irreducible q points in the grid\n/// (trying to evenly split the equivalence classes over processes)\n/// and look for allowed two-phonon processes involving one phonon\n/// from that part and another phonon from anywhere in the grid.\n/// @param[in] grid - a regular grid containing Gamma\n/// @param[in] communicator - MPI communicator to use\n/// @param[in] scalebroad - factor modulating all the broadenings\n/// @return a vector of Twoph_process objects\nstd::vector<Twoph_process> find_allowed_twoph(\n    const Gamma_grid& grid,\n    const boost::mpi::communicator& communicator,\n    double scalebroad = 1.0);\n\n/// Compute and the two-phonon contribution to the RTA\n/// scattering rates for all vibrational modes on a grid.\n///\n/// @param[in] cell - a description of the crystal structure\n/// @param[in] grid - phonon spectrum on a regular grid\n/// @param[in] processes - a vector of allowed two-phonon processes\n/// @param[in] comm - an mpi communicator\n/// @return a set of scattering rates\nEigen::ArrayXXd calc_w0_twoph(const Crystal_structure& cell,\n                              const alma::Gamma_grid& grid,\n                              const std::vector<alma::Twoph_process>& processes,\n                              const boost::mpi::communicator& comm);\n\n/// Compute and the two-phonon contribution to the RTA\n/// scattering rates for all vibrational modes on a grid, with a custom\n/// set of g factors.\n///\n/// @param[in] cell - a description of the crystal structure\n/// @param[in] grid - phonon spectrum on a regular grid\n/// @param[in] gfactors - Pearson deviation coefficient of the mass\n/// at each site.\n/// @param[in] processes - a vector of allowed two-phonon processes\n/// @param[in] comm - an mpi communicator\n/// @return a set of scattering rates\nEigen::ArrayXXd calc_w0_twoph(const Crystal_structure& cell,\n                              const Eigen::Ref<const Eigen::VectorXd>& gfactors,\n                              const alma::Gamma_grid& grid,\n                              const std::vector<alma::Twoph_process>& processes,\n                              const boost::mpi::communicator& comm);\n} // namespace alma\n", "meta": {"hexsha": "5ca1df880fe753bda5993abd1ce70ff90d7563a2", "size": 9961, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/isotopic_scattering.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/isotopic_scattering.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/isotopic_scattering.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": 38.6085271318, "max_line_length": 80, "alphanum_fraction": 0.6362814978, "num_tokens": 2313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2811390451248276}}
{"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#include \"rbm_multival.hpp\"\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <map>\n#include <vector>\n#include \"Utils/all_utils.hpp\"\n#include \"Utils/lookup.hpp\"\n#include \"abstract_machine.hpp\"\n#include \"rbm_spin.hpp\"\n\nnamespace netket {\n\nRbmMultival::RbmMultival(std::shared_ptr<const AbstractHilbert> hilbert,\n                         int nhidden, int alpha, bool usea, bool useb)\n    : AbstractMachine(hilbert),\n      nv_(hilbert->Size()),\n      ls_(hilbert->LocalSize()),\n      usea_(usea),\n      useb_(useb) {\n  nh_ = std::max(nhidden, alpha * nv_);\n  Init();\n}\n\nvoid RbmMultival::Init() {\n  W_.resize(nv_ * ls_, nh_);\n  a_.resize(nv_ * ls_);\n  b_.resize(nh_);\n\n  thetas_.resize(nh_);\n  lnthetas_.resize(nh_);\n  thetasnew_.resize(nh_);\n  lnthetasnew_.resize(nh_);\n\n  npar_ = nv_ * nh_ * ls_;\n\n  if (usea_) {\n    npar_ += nv_ * ls_;\n  } else {\n    a_.setZero();\n  }\n\n  if (useb_) {\n    npar_ += nh_;\n  } else {\n    b_.setZero();\n  }\n\n  auto localstates = GetHilbert().LocalStates();\n\n  localconfs_.resize(nv_ * ls_);\n  for (int i = 0; i < nv_ * ls_; i += ls_) {\n    for (int j = 0; j < ls_; j++) {\n      localconfs_(i + j) = localstates[j];\n    }\n  }\n\n  mask_.resize(nv_ * ls_, nv_);\n  mask_.setZero();\n\n  for (int i = 0; i < nv_ * ls_; i++) {\n    mask_(i, i / ls_) = 1;\n  }\n\n  for (int i = 0; i < ls_; i++) {\n    confindex_[localstates[i]] = i;\n  }\n\n  vtilde_.resize(nv_ * ls_);\n\n  InfoMessage() << \"RBM Multival Initizialized with nvisible = \" << nv_\n                << \" and nhidden = \" << nh_ << std::endl;\n  InfoMessage() << \"Using visible bias = \" << usea_ << std::endl;\n  InfoMessage() << \"Using hidden bias  = \" << useb_ << std::endl;\n  InfoMessage() << \"Local size is      = \" << ls_ << std::endl;\n}\n\nint RbmMultival::Nvisible() const { return nv_; }\n\nint RbmMultival::Npar() const { return npar_; }\n\nvoid RbmMultival::InitRandomPars(int seed, double sigma) {\n  VectorType par(npar_);\n\n  netket::RandomGaussian(par, seed, sigma);\n\n  SetParameters(par);\n}\n\nvoid RbmMultival::InitLookup(VisibleConstType v, LookupType &lt) {\n  if (lt.VectorSize() == 0) {\n    lt.AddVector(b_.size());\n  }\n  if (lt.V(0).size() != b_.size()) {\n    lt.V(0).resize(b_.size());\n  }\n  ComputeTheta(v, lt.V(0));\n}\n\nvoid RbmMultival::UpdateLookup(VisibleConstType v,\n                               const std::vector<int> &tochange,\n                               const std::vector<double> &newconf,\n                               LookupType &lt) {\n  if (tochange.size() != 0) {\n    for (std::size_t s = 0; s < tochange.size(); s++) {\n      const int sf = tochange[s];\n      const int oldtilde = confindex_[v[sf]];\n      const int newtilde = confindex_[newconf[s]];\n\n      lt.V(0) -= W_.row(ls_ * sf + oldtilde);\n      lt.V(0) += W_.row(ls_ * sf + newtilde);\n    }\n  }\n}\n\nRbmMultival::VectorType RbmMultival::DerLog(VisibleConstType v) {\n  LookupType ltnew;\n  InitLookup(v, ltnew);\n  return DerLog(v, ltnew);\n}\n\nRbmMultival::VectorType RbmMultival::DerLog(VisibleConstType v,\n                                            const LookupType &lt) {\n  VectorType der(npar_);\n  der.setZero();\n\n  ComputeVtilde(v, vtilde_);\n\n  int k = 0;\n\n  if (usea_) {\n    for (; k < nv_ * ls_; k++) {\n      der(k) = vtilde_(k);\n    }\n  }\n\n  RbmSpin::tanh(lt.V(0), lnthetas_);\n\n  if (useb_) {\n    for (int p = 0; p < nh_; p++) {\n      der(k) = lnthetas_(p);\n      k++;\n    }\n  }\n\n  for (int i = 0; i < nv_ * ls_; i++) {\n    for (int j = 0; j < nh_; j++) {\n      der(k) = lnthetas_(j) * vtilde_(i);\n      k++;\n    }\n  }\n  return der;\n}\n\nRbmMultival::VectorType RbmMultival::GetParameters() {\n  VectorType pars(npar_);\n\n  int k = 0;\n\n  if (usea_) {\n    for (; k < nv_ * ls_; k++) {\n      pars(k) = a_(k);\n    }\n  }\n\n  if (useb_) {\n    for (int p = 0; p < nh_; p++) {\n      pars(k) = b_(p);\n      k++;\n    }\n  }\n\n  for (int i = 0; i < nv_ * ls_; i++) {\n    for (int j = 0; j < nh_; j++) {\n      pars(k) = W_(i, j);\n      k++;\n    }\n  }\n\n  return pars;\n}\n\nvoid RbmMultival::SetParameters(VectorConstRefType pars) {\n  int k = 0;\n\n  if (usea_) {\n    for (; k < nv_ * ls_; k++) {\n      a_(k) = pars(k);\n    }\n  }\n\n  if (useb_) {\n    for (int p = 0; p < nh_; p++) {\n      b_(p) = pars(k);\n      k++;\n    }\n  }\n\n  for (int i = 0; i < nv_ * ls_; i++) {\n    for (int j = 0; j < nh_; j++) {\n      W_(i, j) = pars(k);\n      k++;\n    }\n  }\n}\n\n// Value of the logarithm of the wave-function\nComplex RbmMultival::LogVal(VisibleConstType v) {\n  ComputeTheta(v, thetas_);\n  RbmSpin::lncosh(thetas_, lnthetas_);\n\n  return (vtilde_.dot(a_) + lnthetas_.sum());\n}\n\n// Value of the logarithm of the wave-function\n// using pre-computed look-up tables for efficiency\nComplex RbmMultival::LogVal(VisibleConstType v, const LookupType &lt) {\n  RbmSpin::lncosh(lt.V(0), lnthetas_);\n\n  ComputeVtilde(v, vtilde_);\n  return (vtilde_.dot(a_) + lnthetas_.sum());\n}\n\n// Difference between logarithms of values, when one or more visible variables\n// are being changed\nRbmMultival::VectorType RbmMultival::LogValDiff(\n    VisibleConstType v, const std::vector<std::vector<int>> &tochange,\n    const std::vector<std::vector<double>> &newconf) {\n  const std::size_t nconn = tochange.size();\n  VectorType logvaldiffs = VectorType::Zero(nconn);\n\n  ComputeTheta(v, thetas_);\n  RbmSpin::lncosh(thetas_, lnthetas_);\n\n  Complex logtsum = lnthetas_.sum();\n\n  for (std::size_t k = 0; k < nconn; k++) {\n    if (tochange[k].size() != 0) {\n      thetasnew_ = thetas_;\n\n      for (std::size_t s = 0; s < tochange[k].size(); s++) {\n        const int sf = tochange[k][s];\n        const int oldtilde = confindex_[v[sf]];\n        const int newtilde = confindex_[newconf[k][s]];\n\n        logvaldiffs(k) -= a_(ls_ * sf + oldtilde);\n        logvaldiffs(k) += a_(ls_ * sf + newtilde);\n\n        thetasnew_ -= W_.row(ls_ * sf + oldtilde);\n        thetasnew_ += W_.row(ls_ * sf + newtilde);\n      }\n\n      RbmSpin::lncosh(thetasnew_, lnthetasnew_);\n      logvaldiffs(k) += lnthetasnew_.sum() - logtsum;\n    }\n  }\n  return logvaldiffs;\n}\n\n// Difference between logarithms of values, when one or more visible variables\n// are being changed Version using pre-computed look-up tables for efficiency\n// on a small number of local changes\nComplex RbmMultival::LogValDiff(VisibleConstType v,\n                                const std::vector<int> &tochange,\n                                const std::vector<double> &newconf,\n                                const LookupType &lt) {\n  Complex logvaldiff = 0.;\n\n  if (tochange.size() != 0) {\n    RbmSpin::lncosh(lt.V(0), lnthetas_);\n\n    thetasnew_ = lt.V(0);\n\n    for (std::size_t s = 0; s < tochange.size(); s++) {\n      const int sf = tochange[s];\n      const int oldtilde = confindex_[v[sf]];\n      const int newtilde = confindex_[newconf[s]];\n\n      logvaldiff -= a_(ls_ * sf + oldtilde);\n      logvaldiff += a_(ls_ * sf + newtilde);\n\n      thetasnew_ -= W_.row(ls_ * sf + oldtilde);\n      thetasnew_ += W_.row(ls_ * sf + newtilde);\n    }\n\n    RbmSpin::lncosh(thetasnew_, lnthetasnew_);\n    logvaldiff += (lnthetasnew_.sum() - lnthetas_.sum());\n  }\n  return logvaldiff;\n}\n\n#if 0\n// Computhes the values of the theta pseudo-angles\ninline void RbmMultival::ComputeTheta(VisibleConstType v, VectorType &theta) {\n  ComputeVtilde(v, vtilde_);\n  theta = (W_.transpose() * vtilde_ + b_);\n}\n\ninline void RbmMultival::ComputeVtilde(VisibleConstType v,\n                                       Eigen::VectorXd &vtilde) {\n  auto t = (localconfs_.array() == (mask_ * v).array());\n  vtilde = t.template cast<double>();\n}\n#endif\n\nvoid RbmMultival::Save(const std::string &filename) const {\n  json state;\n  state[\"Name\"] = \"RbmMultival\";\n  state[\"Nvisible\"] = nv_;\n  state[\"Nhidden\"] = nh_;\n  state[\"LocalSize\"] = ls_;\n  state[\"UseVisibleBias\"] = usea_;\n  state[\"UseHiddenBias\"] = useb_;\n  state[\"a\"] = a_;\n  state[\"b\"] = b_;\n  state[\"W\"] = W_;\n  WriteJsonToFile(state, filename);\n}\n\nvoid RbmMultival::Load(const std::string &filename) {\n  auto const pars = ReadJsonFromFile(filename);\n  if (pars.at(\"Name\") != \"RbmMultival\") {\n    throw InvalidInputError(\n        \"Error while constructing RbmMultival from Json input\");\n  }\n\n  if (FieldExists(pars, \"Nvisible\")) {\n    nv_ = pars[\"Nvisible\"];\n  }\n\n  if (nv_ != GetHilbert().Size()) {\n    throw InvalidInputError(\n        \"Loaded wave-function has incompatible Hilbert space\");\n  }\n\n  if (FieldExists(pars, \"LocalSize\")) {\n    ls_ = pars[\"LocalSize\"];\n  }\n  if (ls_ != GetHilbert().LocalSize()) {\n    throw InvalidInputError(\n        \"Loaded wave-function has incompatible Hilbert space\");\n  }\n\n  if (FieldExists(pars, \"Nhidden\")) {\n    nh_ = FieldVal(pars, \"Nhidden\");\n  } else {\n    nh_ = nv_ * double(FieldVal(pars, \"Alpha\"));\n  }\n\n  usea_ = FieldOrDefaultVal(pars, \"UseVisibleBias\", true);\n  useb_ = FieldOrDefaultVal(pars, \"UseHiddenBias\", true);\n\n  Init();\n\n  // Loading parameters, if defined in the input\n  if (FieldExists(pars, \"a\")) {\n    a_ = pars[\"a\"];\n  } else {\n    a_.setZero();\n  }\n\n  if (FieldExists(pars, \"b\")) {\n    b_ = pars[\"b\"];\n  } else {\n    b_.setZero();\n  }\n  if (FieldExists(pars, \"W\")) {\n    W_ = pars[\"W\"];\n  }\n}\n\nbool RbmMultival::IsHolomorphic() const noexcept { return true; }\n\n}  // namespace netket\n", "meta": {"hexsha": "0889a599922e4a9a687f18550ba07e8043dca34b", "size": 9741, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Sources/Machine/rbm_multival.cc", "max_stars_repo_name": "tvieijra/netket", "max_stars_repo_head_hexsha": "ef3ff32b242f25b6a6ae0f08db1aada85775a2ea", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-11-29T02:51:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-14T18:52:33.000Z", "max_issues_repo_path": "Sources/Machine/rbm_multival.cc", "max_issues_repo_name": "tvieijra/netket", "max_issues_repo_head_hexsha": "ef3ff32b242f25b6a6ae0f08db1aada85775a2ea", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-11-04T14:38:01.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-08T16:56:10.000Z", "max_forks_repo_path": "Sources/Machine/rbm_multival.cc", "max_forks_repo_name": "tvieijra/netket", "max_forks_repo_head_hexsha": "ef3ff32b242f25b6a6ae0f08db1aada85775a2ea", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-12-02T07:29:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-04T21:55:21.000Z", "avg_line_length": 25.0411311054, "max_line_length": 78, "alphanum_fraction": 0.5954214146, "num_tokens": 3041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.28113903951804775}}
{"text": "#include <iostream>\n#include <string>\n\n#include <boost/program_options.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n\n\n#include <amgcl/backend/builtin.hpp>\n#include <amgcl/relaxation/runtime.hpp>\n#include <amgcl/coarsening/runtime.hpp>\n#include <amgcl/coarsening/rigid_body_modes.hpp>\n#include <amgcl/solver/runtime.hpp>\n#include <amgcl/preconditioner/runtime.hpp>\n#include <amgcl/deflated_solver.hpp>\n#include <amgcl/amg.hpp>\n#include <amgcl/adapter/crs_tuple.hpp>\n#include <amgcl/adapter/reorder.hpp>\n#include <amgcl/io/mm.hpp>\n#include <amgcl/io/binary.hpp>\n\n#include <amgcl/profiler.hpp>\n\nnamespace amgcl { profiler<> prof; }\nusing amgcl::prof;\nusing amgcl::precondition;\n\n//---------------------------------------------------------------------------\nint main(int argc, char *argv[]) {\n    namespace po = boost::program_options;\n    namespace io = amgcl::io;\n\n    using amgcl::prof;\n    using std::vector;\n    using std::string;\n\n    po::options_description desc(\"Options\");\n\n    desc.add_options()\n        (\"help,h\", \"Show this help.\")\n        (\"prm-file,P\",\n         po::value<string>(),\n         \"Parameter file in json format. \"\n        )\n        (\n         \"prm,p\",\n         po::value< vector<string> >()->multitoken(),\n         \"Parameters specified as name=value pairs. \"\n         \"May be provided multiple times. Examples:\\n\"\n         \"  -p solver.tol=1e-3\\n\"\n         \"  -p precond.coarse_enough=300\"\n        )\n        (\"matrix,A\",\n         po::value<string>()->required(),\n         \"System matrix in the MatrixMarket format.\"\n        )\n        (\n         \"rhs,f\",\n         po::value<string>(),\n         \"The RHS vector in the MatrixMarket format. \"\n         \"When omitted, a vector of ones is used by default. \"\n         \"Should only be provided together with a system matrix. \"\n        )\n        (\n         \"scale,s\",\n         po::bool_switch()->default_value(false),\n         \"Scale the matrix so that the diagonal is unit. \"\n        )\n        (\n         \"null,N\",\n         po::value<string>(),\n         \"Starting null-vectors in the MatrixMarket format. \"\n        )\n        (\n         \"numvec,n\",\n         po::value<int>()->default_value(3),\n         \"The number of near nullspace vectors to search for. \"\n        )\n        (\n         \"binary,B\",\n         po::bool_switch()->default_value(false),\n         \"When specified, treat input files as binary instead of as MatrixMarket. \"\n         \"It is assumed the files were converted to binary format with mm2bin utility. \"\n        )\n        (\n         \"output,o\",\n         po::value<string>(),\n         \"Output the computed nullspace to the MatrixMarket file.\"\n        )\n        ;\n\n    po::positional_options_description p;\n    p.add(\"prm\", -1);\n\n    po::variables_map vm;\n    po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\")) {\n        std::cout << desc << std::endl;\n        return 0;\n    }\n\n    for (int i = 0; i < argc; ++i) {\n        if (i) std::cout << \" \";\n        std::cout << argv[i];\n    }\n    std::cout << std::endl;\n\n    boost::property_tree::ptree prm;\n    if (vm.count(\"prm-file\")) {\n        read_json(vm[\"prm-file\"].as<string>(), prm);\n    }\n\n    if (vm.count(\"prm\")) {\n        for(const string &v : vm[\"prm\"].as<vector<string> >()) {\n            amgcl::put(prm, v);\n        }\n    }\n\n    ptrdiff_t rows, nv = 0, numvec = vm[\"numvec\"].as<int>();\n    vector<ptrdiff_t> ptr, col;\n    vector<double> val, rhs;\n    std::list<std::vector<double>> Z;\n\n    {\n        auto t = prof.scoped_tic(\"read\");\n\n        string Afile  = vm[\"matrix\"].as<string>();\n        bool   binary = vm[\"binary\"].as<bool>();\n\n        if (binary) {\n            io::read_crs(Afile, rows, ptr, col, val);\n        } else {\n            ptrdiff_t cols;\n            std::tie(rows, cols) = io::mm_reader(Afile)(ptr, col, val);\n            precondition(rows == cols, \"Non-square system matrix\");\n        }\n\n        if (vm.count(\"rhs\")) {\n            string bfile = vm[\"rhs\"].as<string>();\n\n            ptrdiff_t n, m;\n\n            if (binary) {\n                io::read_dense(bfile, n, m, rhs);\n            } else {\n                std::tie(n, m) = io::mm_reader(bfile)(rhs);\n            }\n\n            precondition(n == rows && m == 1, \"The RHS vector has wrong size\");\n        } else {\n            rhs.resize(rows, 1.0);\n        }\n\n        if (vm.count(\"null\")) {\n            string nfile = vm[\"null\"].as<string>();\n\n            std::vector<double> null;\n            ptrdiff_t m;\n\n            if (binary) {\n                io::read_dense(nfile, m, nv, null);\n            } else {\n                std::tie(m, nv) = io::mm_reader(nfile)(null);\n            }\n\n            precondition(m == rows, \"Near null-space vectors have wrong size\");\n\n            for(ptrdiff_t i = 0; i < nv; ++i) {\n                Z.emplace_back(rows);\n                for(ptrdiff_t j = 0; j < rows; ++j) {\n                    Z.back()[j] = null[j * nv + i];\n                }\n            }\n        }\n    }\n\n    if (vm[\"scale\"].as<bool>()) {\n        auto t = prof.scoped_tic(\"scaling\");\n        std::vector<double> dia(rows, 1.0);\n\n        for (ptrdiff_t i = 0; i < static_cast<ptrdiff_t>(rows); ++i) {\n            double d = 1.0;\n            for(ptrdiff_t j = ptr[i], e = ptr[i+1]; j < e; ++j) {\n                if (col[j] == i) {\n                    d = 1 / sqrt(val[j]);\n                }\n            }\n            if (!std::isnan(d)) dia[i] = d;\n        }\n\n        for (ptrdiff_t i = 0; i < static_cast<ptrdiff_t>(rows); ++i) {\n            rhs[i] *= dia[i];\n            for(ptrdiff_t j = ptr[i], e = ptr[i+1]; j < e; ++j) {\n                val[j] *= dia[i] * dia[col[j]];\n            }\n        }\n    }\n\n    typedef amgcl::backend::builtin<double> Backend;\n    typedef amgcl::make_solver<\n        amgcl::amg<\n            Backend,\n            amgcl::runtime::coarsening::wrapper,\n            amgcl::runtime::relaxation::wrapper\n            >,\n        amgcl::runtime::solver::wrapper<Backend>\n        > Solver;\n\n    std::mt19937 rng;\n    std::uniform_real_distribution<double> rnd(-1, 1);\n    std::vector<double> x(rows), zero(rows, 0.0);\n\n    auto A = std::tie(rows, ptr, col, val);\n\n    prm.put(\"solver.ns_search\", true);\n\n    prof.tic(\"search\");\n    for(int k = nv; k < numvec; ++k) {\n        auto t = prof.scoped_tic(std::string(\"vector \") + std::to_string(k));\n        std::vector<double> N;\n\n        if (k) {\n            N.resize(k * rows);\n            int j = 0;\n            for(const auto &z : Z) {\n                for(ptrdiff_t i = 0; i < rows; ++i) {\n                    N[i * k + j] = z[i];\n                }\n                ++j;\n            }\n\n            prm.put(\"precond.coarsening.nullspace.rows\", rows);\n            prm.put(\"precond.coarsening.nullspace.cols\", k);\n            prm.put(\"precond.coarsening.nullspace.B\", N.data());\n        }\n\n        prof.tic(\"setup\");\n        Solver S(A, prm);\n        prof.toc(\"setup\");\n\n        std::cout << std::endl\n                  << \"-------------------------\" << std::endl\n                  << \"-- Searching for vector \" << k << std::endl\n                  << \"-------------------------\" << std::endl\n                  << S << std::endl;\n\n        for(auto &v : x) v = rnd(rng);\n\n        int iters;\n        double error;\n\n        prof.tic(\"solve\");\n        std::tie(iters, error) = S(zero, x);\n        prof.toc(\"solve\");\n\n        std::cout << \"Iterations: \" << iters << std::endl\n                  << \"Error:      \" << error << std::endl;\n\n        // Orthonormalize the new vector\n        for(const auto &z : Z) {\n            double c = amgcl::backend::inner_product(x,z) / amgcl::backend::inner_product(z,z);\n            amgcl::backend::axpby(-c, z, 1, x);\n        }\n\n        double nx = sqrt(amgcl::backend::inner_product(x, x));\n        for(auto &v : x) v /= nx;\n        Z.push_back(x);\n    }\n    prof.toc(\"search\");\n\n    // Solve the system using the near nullspace vectors:\n    std::vector<double> N(numvec * rows);\n    {\n        auto t = prof.scoped_tic(\"apply\");\n\n        int j = 0;\n        for(const auto &z : Z) {\n            for(ptrdiff_t i = 0; i < rows; ++i) {\n                N[i * numvec + j] = z[i];\n            }\n            ++j;\n        }\n\n        prm.put(\"precond.coarsening.nullspace.rows\", rows);\n        prm.put(\"precond.coarsening.nullspace.cols\", numvec);\n        prm.put(\"precond.coarsening.nullspace.B\", N.data());\n\n        prof.tic(\"setup\");\n        Solver S(A, prm);\n        prof.toc(\"setup\");\n\n        std::cout << std::endl\n                  << \"-------------------------\" << std::endl\n                  << \"-- Solving the system \" << std::endl\n                  << \"-------------------------\" << std::endl\n                  << S << std::endl;\n\n        amgcl::backend::clear(x);\n\n        int iters;\n        double error;\n\n        prof.tic(\"solve\");\n        std::tie(iters, error) = S(rhs, x);\n        prof.toc(\"solve\");\n\n        std::cout << \"Iterations: \" << iters << std::endl\n            << \"Error:      \" << error << std::endl;\n    }\n\n    if (vm.count(\"output\")) {\n        auto t = prof.scoped_tic(\"write\");\n        amgcl::io::mm_write(vm[\"output\"].as<string>(), N.data(), rows, numvec);\n    }\n\n    std::cout << prof << std::endl;\n}\n", "meta": {"hexsha": "cd2a74066b6ccbf4d1f1fa0ed24c83c9586257d0", "size": 9266, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/ns_search.cpp", "max_stars_repo_name": "tenglongcong/amgcl", "max_stars_repo_head_hexsha": "61948e1a49c1cbc9fdb68c92d532c8b70e021516", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 504.0, "max_stars_repo_stars_event_min_datetime": "2015-03-11T13:50:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:08:55.000Z", "max_issues_repo_path": "examples/ns_search.cpp", "max_issues_repo_name": "tenglongcong/amgcl", "max_issues_repo_head_hexsha": "61948e1a49c1cbc9fdb68c92d532c8b70e021516", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 209.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T19:13:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T06:44:12.000Z", "max_forks_repo_path": "examples/ns_search.cpp", "max_forks_repo_name": "tenglongcong/amgcl", "max_forks_repo_head_hexsha": "61948e1a49c1cbc9fdb68c92d532c8b70e021516", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 92.0, "max_forks_repo_forks_event_min_datetime": "2015-01-04T06:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T09:49:12.000Z", "avg_line_length": 28.95625, "max_line_length": 95, "alphanum_fraction": 0.4831642564, "num_tokens": 2411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5, "lm_q1q2_score": 0.28108825044289903}}
{"text": "// The MIT License (MIT)\n//\n// Copyright (c) 2014-2016 Darrell Wright\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 <boost/scoped_array.hpp>\n#include <iostream>\n#include <limits>\n#include <stdexcept>\n#include <string>\n#include <Wt/WApplication>\n\n#include \"channelcombiner.h\"\n#include <daw/grayscale_filter/genericimage.h>\n#include \"largepixeldata.h\"\n\nnamespace daw { namespace imaging {\n\tnamespace {\n\t\tfloat too_gs_small( float const & R, float const & G, float const & B ) {\n\t\t\treturn 0.299f*R + 0.587f*G + 0.114f*B;\n\t\t}\n\n\t\tfloat round( float const & value ) {\n\t\t\treturn floor( value + 0.5f );\n\t\t}\n\n\t\tuint8_t max( rgb3 lpd ) {\n\t\t\tint ret = lpd.red;\n\t\t\tif( lpd.green > ret ) {\n\t\t\t\tret = lpd.green;\n\t\t\t}\n\t\t\tif( lpd.blue > ret ) {\n\t\t\t\tret = lpd.blue;\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tauto max3( T value1, T const & value2, T const & value3 ) {\n\t\t\tif( value2 > value1 ) {\n\t\t\t\tvalue1 = value2;\n\t\t\t}\n\t\t\tif( value3 > value1 ) {\n\t\t\t\tvalue1 = value3;\n\t\t\t}\n\t\t\treturn value1;\n\t\t}\n\n\t\tauto max3( LargePixelData const & pd ) {\n\t\t\treturn max3( pd.R, pd.G, pd.B );\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tauto min3( T value1, T const & value2, T const & value3 ) {\n\t\t\tif( value2 < value1 ) {\n\t\t\t\tvalue1 = value2;\n\t\t\t}\n\t\t\tif( value3 < value1 ) {\n\t\t\t\tvalue1 = value3;\n\t\t\t}\n\t\t\treturn value1;\n\t\t}\n\n\t\tauto min3( LargePixelData const & pd ) {\n\t\t\treturn min3( pd.R, pd.G, pd.B );\n\t\t}\n\n\t\tvoid clampvalue( int &value, int const min, int const max ) {\n\t\t\tif( value < min ) {\n\t\t\t\tWt::log( \"info\" ) << \"Had to clamp value from from \" << value << \" to \" << min;\n\t\t\t\tvalue = min;\n\t\t\t} else if( value > max ) {\n\t\t\t\tWt::log( \"info\" ) << \"Had to clamp value from from \" << value << \" to \" << max;\n\t\t\t\tvalue = max;\n\t\t\t}\n\t\t}\n\n\t\tvoid clampvalue( LargePixelData &value, int const min, int const max ) {\n\t\t\tclampvalue( value.R, min, max );\n\t\t\tclampvalue( value.G, min, max );\n\t\t\tclampvalue( value.B, min, max );\n\t\t}\n\n\t\tfloat colform( const rgb3 c, float const R, float const G, float const B ) {\n\t\t\treturn R*(float)c.red + G*(float)c.green + B*(float)c.blue;\n\t\t}\n\t}\n\tGenericImage<rgb3> ChannelCombiner::runfilter( GenericImage<rgb3> const & image_y, GenericImage<rgb3> const & image_u, GenericImage<rgb3> const & image_v ) const {\n\t\tif( !((image_y.size( ) == image_v.size( )) && (image_y.size( ) == image_v.size( ))) ) {\n\t\t\tconst std::string msg = \"Images are not the same size in channel filter\";\n\t\t\tWt::log( \"error\" ) << msg;\n\t\t\tthrow std::runtime_error( msg );\n\t\t}\n\n\t\tboost::scoped_array<LargePixelData> output_lpdimg( new LargePixelData[image_y.size( )] );\t//output_lpdimg\n\t\tfor( size_t n=0; n<image_y.size( ); ++n ) {\n\t\t\tfloat const Y = (float)image_y[n].red;\n\t\t\tfloat const U = (float)image_u[n].red;\n\t\t\tfloat const V = (float)image_v[n].red;\t\t\t\n\t\t\toutput_lpdimg[n] = LargePixelData( (int)(Y + 1.14f*V), (int)(Y - 0.395f*U - 0.581f*V), (int)(Y + 2.032f*U) );\n\t\t}\n\n\t\tLargePixelData pd_min( std::numeric_limits<int>::max( ), std::numeric_limits<int>::max( ), std::numeric_limits<int>::max( ) );\n\t\tLargePixelData pd_max( std::numeric_limits<int>::min( ), std::numeric_limits<int>::min( ), std::numeric_limits<int>::min( ) );\n\n\t\t// Do not parallelize without accounting for shared data\n\t\tfor( size_t n=0; n<image_y.size( ); ++n ) {\n\t\t\tLargePixelData::min( output_lpdimg[n], pd_min );\n\t\t\tLargePixelData::max( output_lpdimg[n], pd_max );\n\t\t}\n\n\t\tauto const max_all = max3( pd_max );\n\t\tauto const min_all = min3( pd_min );\n\t\tauto const range_all = static_cast<float>(max_all - min_all);\n\n\t\tGenericImage<rgb3> output_image{ image_y.width( ), image_y.height( ) };\n\n\t\t//#pragma omp parallel for\n\t\tfor( int n=0; n<(int)image_y.size( ); ++n ) {\n\t\t\tLargePixelData cur_value;\n\t\t\tcur_value.R = (int)((float)(output_lpdimg[n].R-pd_min.R)*(255.0f/range_all));\n\t\t\tcur_value.G = (int)((float)(output_lpdimg[n].G-pd_min.G)*(255.0f/range_all));\n\t\t\tcur_value.B = (int)((float)(output_lpdimg[n].B-pd_min.B)*(255.0f/range_all));\n\t\t\tclampvalue( cur_value, 0, 255 );\n\t\t\toutput_image[n] = rgb3( (unsigned char)cur_value.R, (unsigned char)cur_value.G, (unsigned char)cur_value.B );\n\n\t\t}\n\n\n\t\treturn output_image;\n\t}\n}}\n", "meta": {"hexsha": "3692c453157505cb36a8cc27a09d67e364f55ac5", "size": 5107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "channelcombiner.cpp", "max_stars_repo_name": "beached/weboldnewphoto", "max_stars_repo_head_hexsha": "f760ebf53b42492d5f8e20e985009ccf51b24003", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "channelcombiner.cpp", "max_issues_repo_name": "beached/weboldnewphoto", "max_issues_repo_head_hexsha": "f760ebf53b42492d5f8e20e985009ccf51b24003", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "channelcombiner.cpp", "max_forks_repo_name": "beached/weboldnewphoto", "max_forks_repo_head_hexsha": "f760ebf53b42492d5f8e20e985009ccf51b24003", "max_forks_repo_licenses": ["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.821192053, "max_line_length": 164, "alphanum_fraction": 0.6594869787, "num_tokens": 1550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2810882431075317}}
{"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_SOMERC_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_SOMERC_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#include <boost/geometry/srs/projections/impl/aasincos.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace srs { namespace par4\n{\n    struct somerc {}; // Swiss. Obl. Mercator\n\n}} //namespace srs::par4\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace somerc\n    {\n            static const double epsilon = 1.e-10;\n            static const int n_iter = 6;\n\n            template <typename T>\n            struct par_somerc\n            {\n                T K, c, hlf_e, kR, cosp0, sinp0;\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename T, typename Parameters>\n            struct base_somerc_ellipsoid\n                : public base_t_fi<base_somerc_ellipsoid<T, Parameters>, T, Parameters>\n            {\n                par_somerc<T> m_proj_parm;\n\n                inline base_somerc_ellipsoid(const Parameters& par)\n                    : base_t_fi<base_somerc_ellipsoid<T, Parameters>, T, Parameters>(*this, par)\n                {}\n\n                // FORWARD(e_forward)\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 fourth_pi = detail::fourth_pi<T>();\n                    static const T half_pi = detail::half_pi<T>();\n\n                    T phip, lamp, phipp, lampp, sp, cp;\n\n                    sp = this->m_par.e * sin(lp_lat);\n                    phip = 2.* atan( exp( this->m_proj_parm.c * (\n                        log(tan(fourth_pi + 0.5 * lp_lat)) - this->m_proj_parm.hlf_e * log((1. + sp)/(1. - sp)))\n                        + this->m_proj_parm.K)) - half_pi;\n                    lamp = this->m_proj_parm.c * lp_lon;\n                    cp = cos(phip);\n                    phipp = aasin(this->m_proj_parm.cosp0 * sin(phip) - this->m_proj_parm.sinp0 * cp * cos(lamp));\n                    lampp = aasin(cp * sin(lamp) / cos(phipp));\n                    xy_x = this->m_proj_parm.kR * lampp;\n                    xy_y = this->m_proj_parm.kR * log(tan(fourth_pi + 0.5 * phipp));\n                }\n\n                // INVERSE(e_inverse)  ellipsoid & 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 fourth_pi = detail::fourth_pi<T>();\n\n                    T phip, lamp, phipp, lampp, cp, esp, con, delp;\n                    int i;\n\n                    phipp = 2. * (atan(exp(xy_y / this->m_proj_parm.kR)) - fourth_pi);\n                    lampp = xy_x / this->m_proj_parm.kR;\n                    cp = cos(phipp);\n                    phip = aasin(this->m_proj_parm.cosp0 * sin(phipp) + this->m_proj_parm.sinp0 * cp * cos(lampp));\n                    lamp = aasin(cp * sin(lampp) / cos(phip));\n                    con = (this->m_proj_parm.K - log(tan(fourth_pi + 0.5 * phip)))/this->m_proj_parm.c;\n                    for (i = n_iter; i ; --i) {\n                        esp = this->m_par.e * sin(phip);\n                        delp = (con + log(tan(fourth_pi + 0.5 * phip)) - this->m_proj_parm.hlf_e *\n                            log((1. + esp)/(1. - esp)) ) *\n                            (1. - esp * esp) * cos(phip) * this->m_par.rone_es;\n                        phip -= delp;\n                        if (fabs(delp) < epsilon)\n                            break;\n                    }\n                    if (i) {\n                        lp_lat = phip;\n                        lp_lon = lamp / this->m_proj_parm.c;\n                    } else {\n                        BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\n                    }\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"somerc_ellipsoid\";\n                }\n\n            };\n\n            // Swiss. Obl. Mercator\n            template <typename Parameters, typename T>\n            inline void setup_somerc(Parameters& par, par_somerc<T>& proj_parm)\n            {\n                static const T fourth_pi = detail::fourth_pi<T>();\n\n                T cp, phip0, sp;\n\n                proj_parm.hlf_e = 0.5 * par.e;\n                cp = cos(par.phi0);\n                cp *= cp;\n                proj_parm.c = sqrt(1 + par.es * cp * cp * par.rone_es);\n                sp = sin(par.phi0);\n                proj_parm.cosp0 = cos( phip0 = aasin(proj_parm.sinp0 = sp / proj_parm.c) );\n                sp *= par.e;\n                proj_parm.K = log(tan(fourth_pi + 0.5 * phip0)) - proj_parm.c * (\n                    log(tan(fourth_pi + 0.5 * par.phi0)) - proj_parm.hlf_e *\n                    log((1. + sp) / (1. - sp)));\n                proj_parm.kR = par.k0 * sqrt(par.one_es) / (1. - sp * sp);\n            }\n\n    }} // namespace detail::somerc\n    #endif // doxygen\n\n    /*!\n        \\brief Swiss. Obl. Mercator 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         - Ellipsoid\n         - For CH1903\n        \\par Example\n        \\image html ex_somerc.gif\n    */\n    template <typename T, typename Parameters>\n    struct somerc_ellipsoid : public detail::somerc::base_somerc_ellipsoid<T, Parameters>\n    {\n        inline somerc_ellipsoid(const Parameters& par) : detail::somerc::base_somerc_ellipsoid<T, Parameters>(par)\n        {\n            detail::somerc::setup_somerc(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::par4::somerc, somerc_ellipsoid, somerc_ellipsoid)\n\n        // Factory entry(s)\n        template <typename T, typename Parameters>\n        class somerc_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<somerc_ellipsoid<T, Parameters>, T, Parameters>(par);\n                }\n        };\n\n        template <typename T, typename Parameters>\n        inline void somerc_init(detail::base_factory<T, Parameters>& factory)\n        {\n            factory.add_to_factory(\"somerc\", new somerc_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_SOMERC_HPP\n", "meta": {"hexsha": "70dee94072d937934a5f3df454fa68aed3bce61a", "size": 8987, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/boost/geometry/srs/projections/proj/somerc.hpp", "max_stars_repo_name": "Bpowers4/turicreate", "max_stars_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "src/external/boost/boost_1_68_0/boost/geometry/srs/projections/proj/somerc.hpp", "max_issues_repo_name": "Bpowers4/turicreate", "max_issues_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "src/external/boost/boost_1_68_0/boost/geometry/srs/projections/proj/somerc.hpp", "max_forks_repo_name": "Bpowers4/turicreate", "max_forks_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 40.3004484305, "max_line_length": 115, "alphanum_fraction": 0.5770557472, "num_tokens": 2161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2808199081714713}}
{"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_MUL_MUL_TEMPORARY_HPP\n#define AMA_TENSOR_MUL_MUL_TEMPORARY_HPP 1\n\n#include <ama/tensor/iexp/index_reorder.hpp>\n#include <ama/tensor/iexp/iexp_base.hpp>\n#include <ama/tensor/mul/mul_calculator.hpp>\n#include <boost/mpl/bool.hpp>\n#include <boost/mpl/plus.hpp>\n\n/* this class is used to store a temporary expression before the reduction */\n\nnamespace ama\n{\n  namespace tensor_\n  {\n\n    /* forward declaration */\n    template <typename LEFT, typename RIGHT> class mul_temporary;\n\n\n    /* specialization of iexp traits */\n    template <typename LEFT, typename RIGHT>\n    struct iexp_traits< mul_temporary<LEFT, RIGHT> >\n    {\n      typedef typename LEFT::value_type value_type;\n\n      typedef typename LEFT::dimension_type dimension_type;\n\n      typedef typename mul_index<LEFT, RIGHT>::controvariant_list controvariant_list;\n      typedef typename mul_index<LEFT, RIGHT>::covariant_list covariant_list;\n\n      typedef ::boost::mpl::false_ is_assignable;\n    };\n\n\n    /* class declaration */\n    template <typename LEFT, typename RIGHT>\n    class mul_temporary:\n        public iexp_base< mul_temporary<LEFT, RIGHT> >\n    {\n    protected:\n      typedef iexp_base< mul_temporary<LEFT, RIGHT> > base_type;\n\n      typedef LEFT left_operand;\n      typedef RIGHT right_operand;\n\n    public:\n      /* constructor */\n      mul_temporary(left_operand const & left,\n                    right_operand const & right)\n          : m_left(left),\n            m_right(right) { }\n\n    public:\n      typedef typename base_type::value_type value_type;\n\n      /* retrieve the value */\n      template <typename IMAP>\n      value_type at() const\n      {\n        return m_left.template at<IMAP>() * m_right.template at<IMAP>();\n      }\n\n    protected:\n      left_operand const m_left;\n      right_operand const m_right;\n    };\n\n\n  }\n}\n\n#endif /* AMA_TENSOR_MUL_MUL_TEMPORARY_HPP */\n", "meta": {"hexsha": "982fc1571f48255d526fcee9e62738387ce4dcce", "size": 3503, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ama/tensor/mul/mul_temporary.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/mul/mul_temporary.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/mul/mul_temporary.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": 34.3431372549, "max_line_length": 85, "alphanum_fraction": 0.7170996289, "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2807983099404514}}
{"text": "#include <algorithm>\n#include <functional>\n#include <string>\n#include <random>\n\n#include <boost/math/constants/constants.hpp>\n#include <Euclid/Util/Assert.h>\n\nnamespace Euclid\n{\n\nnamespace _impl\n{\n\ninline void mask_filter(const RTCFilterFunctionNArguments* args)\n{\n    EASSERT(args->N == 1);\n    auto mask = reinterpret_cast<uint8_t*>(args->geometryUserPtr);\n    EASSERT(mask != nullptr);\n\n    auto primid = RTCHitN_primID(args->hit, 1, 0);\n    if (mask[primid] != 1) { args->valid[0] = 0; }\n}\n\n} // namespace _impl\n\ninline RayCamera::RayCamera(const Vec3& position,\n                            const Vec3& focus,\n                            const Vec3& up,\n                            float tnear,\n                            float tfar)\n    : Camera(position, focus, up, tnear, tfar)\n{}\n\ninline PerspRayCamera::PerspRayCamera(const Vec3& position,\n                                      const Vec3& focus,\n                                      const Vec3& up,\n                                      float vfov,\n                                      float aspect,\n                                      float tnear,\n                                      float tfar)\n    : RayCamera(position, focus, up, tnear, tfar)\n{\n    auto fov = vfov * boost::math::float_constants::degree;\n    this->film.height = 2.0f * std::tan(fov * 0.5f);\n    this->film.width = aspect * this->film.height;\n}\n\ninline PerspRayCamera::PerspRayCamera(const Vec3& position,\n                                      const Vec3& focus,\n                                      const Vec3& up,\n                                      float vfov,\n                                      unsigned width,\n                                      unsigned height,\n                                      float tnear,\n                                      float tfar)\n    : RayCamera(position, focus, up, tnear, tfar)\n{\n    auto fov = vfov * boost::math::float_constants::degree;\n    auto aspect = static_cast<float>(width) / height;\n    this->film.height = 2.0f * std::tan(fov * 0.5f);\n    this->film.width = aspect * film.height;\n}\n\ninline PerspRayCamera::~PerspRayCamera() = default;\n\ninline void PerspRayCamera::set_aspect(float aspect)\n{\n    this->film.width = aspect * this->film.height;\n}\n\ninline void PerspRayCamera::set_aspect(unsigned width, unsigned height)\n{\n    auto aspect = static_cast<float>(width) / height;\n    this->film.width = aspect * this->film.height;\n}\n\ninline void PerspRayCamera::set_fov(float vfov)\n{\n    auto fov = vfov * boost::math::float_constants::degree;\n    auto aspect = this->film.width / this->film.height;\n    this->film.height = 2.0f * std::tan(fov * 0.5f);\n    this->film.width = aspect * this->film.height;\n}\n\ninline RTCRayHit PerspRayCamera::gen_ray(float s, float t) const\n{\n    RTCRayHit rayhit;\n    Eigen::Vector3f view = -this->dir + (s - 0.5f) * this->film.width * u +\n                           (t - 0.5f) * this->film.height * v;\n    EASSERT(view.dot(this->dir) < 0.0f);\n\n    rayhit.ray.org_x = this->pos(0);\n    rayhit.ray.org_y = this->pos(1);\n    rayhit.ray.org_z = this->pos(2);\n    rayhit.ray.dir_x = view(0);\n    rayhit.ray.dir_y = view(1);\n    rayhit.ray.dir_z = view(2);\n    rayhit.ray.tnear = this->tnear;\n    rayhit.ray.tfar = this->tfar;\n    rayhit.ray.flags = 0;\n    rayhit.hit.geomID = RTC_INVALID_GEOMETRY_ID;\n    return rayhit;\n}\n\ninline OrthoRayCamera::OrthoRayCamera(const Vec3& position,\n                                      const Vec3& focus,\n                                      const Vec3& up,\n                                      float xextent,\n                                      float yextent,\n                                      float tnear,\n                                      float tfar)\n    : RayCamera(position, focus, up, tnear, tfar)\n{\n    this->film.width = xextent;\n    this->film.height = yextent;\n}\n\ninline OrthoRayCamera::~OrthoRayCamera() = default;\n\ninline void OrthoRayCamera::set_extent(float xextent, float yextent)\n{\n    this->film.width = xextent;\n    this->film.height = yextent;\n}\n\ninline RTCRayHit OrthoRayCamera::gen_ray(float s, float t) const\n{\n    RTCRayHit rayhit;\n    Eigen::Vector3f origin = this->pos + (s - 0.5f) * this->film.width * u +\n                             (t - 0.5f) * this->film.height * v;\n\n    rayhit.ray.org_x = origin(0);\n    rayhit.ray.org_y = origin(1);\n    rayhit.ray.org_z = origin(2);\n    rayhit.ray.dir_x = -this->dir(0);\n    rayhit.ray.dir_y = -this->dir(1);\n    rayhit.ray.dir_z = -this->dir(2);\n    rayhit.ray.tnear = this->tnear;\n    rayhit.ray.tfar = this->tfar;\n    rayhit.ray.flags = 0;\n    rayhit.hit.geomID = RTC_INVALID_GEOMETRY_ID;\n    return rayhit;\n}\n\ninline RayTracer::RayTracer(int threads)\n{\n    std::string cfg(\"threads=\");\n    cfg.append(std::to_string(threads));\n    _device = rtcNewDevice(cfg.c_str());\n    if (!_device) {\n        auto err = rtcGetDeviceError(_device);\n        std::string err_str(\"Embree device creation error: \");\n        err_str.append(std::to_string(err));\n        throw std::runtime_error(err_str);\n    }\n\n    _scene = rtcNewScene(_device);\n    if (!_scene) {\n        auto err = rtcGetDeviceError(_device);\n        std::string err_str(\"Embree scene creation error: \");\n        err_str.append(std::to_string(err));\n        throw std::runtime_error(err_str);\n    }\n\n    _material.ambient << 0.1f, 0.1f, 0.1f;\n    _material.diffuse << 0.7f, 0.7f, 0.7f;\n}\n\ninline RayTracer::~RayTracer()\n{\n    release_buffers();\n    rtcReleaseScene(_scene);\n    rtcReleaseDevice(_device);\n}\n\n// TODO: add generic type support\ninline void RayTracer::attach_geometry_buffers(\n    const std::vector<float>& positions,\n    const std::vector<unsigned>& indices)\n{\n    if (positions.empty() || indices.empty()) {\n        EWARNING(\"Input geometry is empty.\");\n        return;\n    }\n    if (positions.size() % 3 != 1) {\n        throw std::invalid_argument(\"The last element of the positions buffer \"\n                                    \"is not padded to 16 bytes. Add \"\n                                    \"one more 0.0f to your positions buffer.\");\n    }\n    if (indices.size() % 3 != 0) {\n        throw std::invalid_argument(\"Size of input indices is not divisible by \"\n                                    \"3, thus not a valid triangle mesh.\");\n    }\n\n    release_buffers();\n\n    _geometry = rtcNewGeometry(_device, RTC_GEOMETRY_TYPE_TRIANGLE);\n    rtcSetSharedGeometryBuffer(_geometry,\n                               RTC_BUFFER_TYPE_VERTEX,\n                               0,\n                               RTC_FORMAT_FLOAT3,\n                               positions.data(),\n                               0,\n                               3 * sizeof(float),\n                               positions.size() / 3);\n    rtcSetSharedGeometryBuffer(_geometry,\n                               RTC_BUFFER_TYPE_INDEX,\n                               0,\n                               RTC_FORMAT_UINT3,\n                               indices.data(),\n                               0,\n                               3 * sizeof(unsigned),\n                               indices.size() / 3);\n    rtcCommitGeometry(_geometry);\n    _geom_id = rtcAttachGeometry(_scene, _geometry);\n    rtcCommitScene(_scene);\n}\n\ninline void RayTracer::attach_color_buffer(const std::vector<float>* colors,\n                                           bool vertex_color)\n{\n    if (colors && colors->empty()) {\n        EWARNING(\"Input geometry is empty.\");\n        return;\n    }\n    if (colors && vertex_color && colors->size() % 3 != 1) {\n        throw std::invalid_argument(\"The last element of the colors buffer \"\n                                    \"is not padded to 16 bytes. Add \"\n                                    \"one more 0.0f to your colors buffer.\");\n    }\n\n    // ! vertex color -> vertex color\n    if (!(_colors && _vertex_color) && (colors && vertex_color)) {\n        rtcSetGeometryVertexAttributeCount(_geometry, 1);\n        rtcSetSharedGeometryBuffer(_geometry,\n                                   RTC_BUFFER_TYPE_VERTEX_ATTRIBUTE,\n                                   0,\n                                   RTC_FORMAT_FLOAT3,\n                                   colors->data(),\n                                   0,\n                                   3 * sizeof(float),\n                                   colors->size() / 3);\n        rtcCommitGeometry(_geometry);\n    }\n    // vertex color -> ! vertex color\n    else if ((_colors && _vertex_color) && !(colors && vertex_color)) {\n        rtcSetGeometryVertexAttributeCount(_geometry, 0);\n        rtcCommitGeometry(_geometry);\n    }\n    // vertex color -> vertex color\n    else if ((_colors && _vertex_color) && (colors && vertex_color)) {\n        rtcSetSharedGeometryBuffer(_geometry,\n                                   RTC_BUFFER_TYPE_VERTEX_ATTRIBUTE,\n                                   0,\n                                   RTC_FORMAT_FLOAT3,\n                                   colors->data(),\n                                   0,\n                                   3 * sizeof(float),\n                                   colors->size() / 3);\n        rtcCommitGeometry(_geometry);\n    }\n\n    _colors = colors;\n    _vertex_color = vertex_color;\n}\n\ninline void RayTracer::attach_face_mask_buffer(const std::vector<uint8_t>* mask)\n{\n    // no mask -> mask\n    if (!_face_mask && mask) {\n        rtcSetGeometryIntersectFilterFunction(_geometry, _impl::mask_filter);\n    }\n    // mask -> no mask\n    else if (_face_mask && !mask) {\n        rtcSetGeometryIntersectFilterFunction(_geometry, nullptr);\n    }\n\n    uint8_t* buffer = nullptr;\n    if (mask) { buffer = const_cast<uint8_t*>(mask->data()); }\n    rtcSetGeometryUserData(_geometry, buffer);\n    rtcCommitGeometry(_geometry);\n    _face_mask = mask;\n}\n\ninline void RayTracer::release_buffers()\n{\n    if (_geom_id != -1) {\n        rtcDetachGeometry(_scene, _geom_id);\n        _geom_id = -1;\n        _colors = nullptr;\n        _face_mask = nullptr;\n        rtcReleaseGeometry(_geometry);\n    }\n}\n\ninline void RayTracer::set_material(const Material& material)\n{\n    _material = material;\n}\n\ninline void RayTracer::set_background(\n    const Eigen::Ref<const Eigen::Array3f>& color)\n{\n    _background = color;\n}\n\ninline void RayTracer::set_background(float r, float g, float b)\n{\n    _background << r, g, b;\n}\n\ninline void RayTracer::enable_light(bool on)\n{\n    _lighting = on;\n}\n\ninline void RayTracer::render_shaded(std::vector<uint8_t>& pixels,\n                                     const RayCamera& camera,\n                                     int width,\n                                     int height,\n                                     bool interleaved)\n{\n    pixels.resize(3 * width * height);\n    auto diffuse_color = _select_diffuse_color();\n\n    RTCIntersectContext context;\n    rtcInitIntersectContext(&context);\n\n#pragma omp parallel for schedule(dynamic)\n    for (int y = 0; y < height; ++y) {\n        for (int x = 0; x < width; ++x) {\n            Eigen::Array3f color(0.0f, 0.0f, 0.0f);\n            auto u = static_cast<float>(x) / width;\n            auto v = static_cast<float>(y) / height;\n            auto rayhit = camera.gen_ray(u, v);\n            rtcIntersect1(_scene, &context, &rayhit);\n\n            if (rayhit.hit.geomID != RTC_INVALID_GEOMETRY_ID) {\n                Eigen::Array3f ambient = _material.ambient;\n                Eigen::Array3f diffuse = diffuse_color(rayhit.hit);\n                if (_lighting) {\n                    Eigen::Vector3f normal = Eigen::Vector3f(rayhit.hit.Ng_x,\n                                                             rayhit.hit.Ng_y,\n                                                             rayhit.hit.Ng_z)\n                                                 .normalized();\n                    // // Point light at the view position\n                    Eigen::Vector3f lightdir = Eigen::Vector3f(rayhit.ray.dir_x,\n                                                               rayhit.ray.dir_y,\n                                                               rayhit.ray.dir_z)\n                                                   .normalized();\n                    diffuse *= std::abs(normal.dot(-lightdir));\n                }\n                color += ambient + diffuse;\n            }\n            else {\n                color += _background;\n            }\n            color(0) = std::min(color(0), 1.0f);\n            color(1) = std::min(color(1), 1.0f);\n            color(2) = std::min(color(2), 1.0f);\n            color *= 255;\n            auto r = static_cast<uint8_t>(color(0));\n            auto g = static_cast<uint8_t>(color(1));\n            auto b = static_cast<uint8_t>(color(2));\n            if (interleaved) {\n                pixels[3 * ((height - y - 1) * width + x) + 0] = r;\n                pixels[3 * ((height - y - 1) * width + x) + 1] = g;\n                pixels[3 * ((height - y - 1) * width + x) + 2] = b;\n            }\n            else {\n                pixels[(height - y - 1) * width + x] = r;\n                pixels[width * height + (height - y - 1) * width + x] = g;\n                pixels[2 * width * height + (height - y - 1) * width + x] = b;\n            }\n        }\n    }\n}\n\ninline void RayTracer::render_shaded(std::vector<uint8_t>& pixels,\n                                     const RayCamera& camera,\n                                     int width,\n                                     int height,\n                                     int samples,\n                                     bool interleaved)\n{\n    pixels.resize(3 * width * height);\n    auto diffuse_color = _select_diffuse_color();\n\n    RTCIntersectContext context;\n    rtcInitIntersectContext(&context);\n    std::random_device rd;\n    std::minstd_rand rd_gen(rd());\n    std::uniform_real_distribution<> rd_number(0.0f, 1.0f);\n    const float rcpr_samples = 1.0f / samples;\n\n#pragma omp parallel for schedule(dynamic)\n    for (int y = 0; y < height; ++y) {\n        for (int x = 0; x < width; ++x) {\n            Eigen::Array3f color(0.0f, 0.0f, 0.0f);\n            for (int s = 0; s < samples; ++s) {\n                auto u = static_cast<float>(x + rd_number(rd_gen)) / width;\n                auto v = static_cast<float>(y + rd_number(rd_gen)) / height;\n                auto rayhit = camera.gen_ray(u, v);\n                rtcIntersect1(_scene, &context, &rayhit);\n\n                if (rayhit.hit.geomID != RTC_INVALID_GEOMETRY_ID) {\n                    Eigen::Array3f ambient = _material.ambient;\n                    Eigen::Array3f diffuse = diffuse_color(rayhit.hit);\n                    if (_lighting) {\n                        Eigen::Vector3f normal =\n                            Eigen::Vector3f(rayhit.hit.Ng_x,\n                                            rayhit.hit.Ng_y,\n                                            rayhit.hit.Ng_z)\n                                .normalized();\n                        // // Point light at the view position\n                        Eigen::Vector3f lightdir =\n                            Eigen::Vector3f(rayhit.ray.dir_x,\n                                            rayhit.ray.dir_y,\n                                            rayhit.ray.dir_z)\n                                .normalized();\n                        diffuse *= std::abs(normal.dot(-lightdir));\n                    }\n                    color += ambient + diffuse;\n                }\n                else {\n                    color += _background;\n                }\n            }\n            color *= rcpr_samples;\n            color(0) = std::min(color(0), 1.0f);\n            color(1) = std::min(color(1), 1.0f);\n            color(2) = std::min(color(2), 1.0f);\n            color *= 255;\n            auto r = static_cast<uint8_t>(color(0));\n            auto g = static_cast<uint8_t>(color(1));\n            auto b = static_cast<uint8_t>(color(2));\n            if (interleaved) {\n                pixels[3 * ((height - y - 1) * width + x) + 0] = r;\n                pixels[3 * ((height - y - 1) * width + x) + 1] = g;\n                pixels[3 * ((height - y - 1) * width + x) + 2] = b;\n            }\n            else {\n                pixels[(height - y - 1) * width + x] = r;\n                pixels[width * height + (height - y - 1) * width + x] = g;\n                pixels[2 * width * height + (height - y - 1) * width + x] = b;\n            }\n        }\n    }\n}\n\ninline void RayTracer::render_depth(std::vector<uint8_t>& pixels,\n                                    const RayCamera& camera,\n                                    int width,\n                                    int height)\n{\n    pixels.resize(width * height);\n    std::vector<float> depths(width * height, -1.0f);\n    float min_depth = std::numeric_limits<float>::max();\n    float max_depth = -1.0f;\n    RTCIntersectContext context;\n    rtcInitIntersectContext(&context);\n#pragma omp parallel for schedule(dynamic)\n    for (int y = 0; y < height; ++y) {\n        for (int x = 0; x < width; ++x) {\n            auto u = static_cast<float>(x) / width;\n            auto v = static_cast<float>(y) / height;\n            auto rayhit = camera.gen_ray(u, v);\n            rtcIntersect1(_scene, &context, &rayhit);\n            if (rayhit.hit.geomID != RTC_INVALID_GEOMETRY_ID) {\n                auto depth = rayhit.ray.tfar * camera.dir.norm();\n                depths[(height - y - 1) * width + x] = depth;\n                if (depth < min_depth) min_depth = depth;\n                if (depth > max_depth) max_depth = depth;\n            }\n        }\n    }\n    float denom = 1.0f / (max_depth - min_depth);\n    for (size_t i = 0; i < depths.size(); ++i) {\n        if (depths[i] == -1.0f) { pixels[i] = 0; }\n        else {\n            pixels[i] =\n                static_cast<uint8_t>((max_depth - depths[i]) * denom * 255);\n        }\n    }\n}\n\ninline void RayTracer::render_depth(std::vector<float>& values,\n                                    const RayCamera& camera,\n                                    int width,\n                                    int height)\n{\n    values.resize(width * height);\n    RTCIntersectContext context;\n    rtcInitIntersectContext(&context);\n#pragma omp parallel for schedule(dynamic)\n    for (int y = 0; y < height; ++y) {\n        for (int x = 0; x < width; ++x) {\n            auto u = static_cast<float>(x) / width;\n            auto v = static_cast<float>(y) / height;\n            auto rayhit = camera.gen_ray(u, v);\n            rtcIntersect1(_scene, &context, &rayhit);\n            if (rayhit.hit.geomID != RTC_INVALID_GEOMETRY_ID) {\n                auto depth = rayhit.ray.tfar * camera.dir.norm();\n                values[(height - y - 1) * width + x] = depth;\n            }\n            else {\n                values[(height - y - 1) * width + x] = -1.0f;\n            }\n        }\n    }\n}\n\ninline void RayTracer::render_silhouette(std::vector<uint8_t>& pixels,\n                                         const RayCamera& camera,\n                                         int width,\n                                         int height)\n{\n    pixels.resize(width * height);\n    RTCIntersectContext context;\n    rtcInitIntersectContext(&context);\n#pragma omp parallel for schedule(dynamic)\n    for (int y = 0; y < height; ++y) {\n        for (int x = 0; x < width; ++x) {\n            auto u = static_cast<float>(x) / width;\n            auto v = static_cast<float>(y) / height;\n            auto rayhit = camera.gen_ray(u, v);\n            rtcOccluded1(_scene, &context, &(rayhit.ray));\n            if (rayhit.ray.tfar <= 0.0f) {\n                pixels[(height - y - 1) * width + x] = 255;\n            }\n            else {\n                pixels[(height - y - 1) * width + x] = 0;\n            }\n        }\n    }\n}\n\ninline void RayTracer::render_index(std::vector<uint8_t>& pixels,\n                                    const RayCamera& camera,\n                                    int width,\n                                    int height,\n                                    bool interleaved)\n{\n    pixels.resize(3 * width * height);\n    RTCIntersectContext context;\n    rtcInitIntersectContext(&context);\n#pragma omp parallel for schedule(dynamic)\n    for (int y = 0; y < height; ++y) {\n        for (int x = 0; x < width; ++x) {\n            auto u = static_cast<float>(x) / width;\n            auto v = static_cast<float>(y) / height;\n            auto rayhit = camera.gen_ray(u, v);\n            rtcIntersect1(_scene, &context, &rayhit);\n            uint32_t index;\n            if (rayhit.hit.geomID != RTC_INVALID_GEOMETRY_ID) {\n                index = rayhit.hit.primID + 1;\n            }\n            else {\n                index = 0;\n            }\n            uint8_t r = index & 0x000000FF;\n            uint8_t g = (index >> 8) & 0x000000FF;\n            uint8_t b = (index >> 16) & 0x000000FF;\n            if (interleaved) {\n                pixels[3 * ((height - y - 1) * width + x) + 0] = r;\n                pixels[3 * ((height - y - 1) * width + x) + 1] = g;\n                pixels[3 * ((height - y - 1) * width + x) + 2] = b;\n            }\n            else {\n                pixels[(height - y - 1) * width + x] = r;\n                pixels[width * height + (height - y - 1) * width + x] = g;\n                pixels[2 * width * height + (height - y - 1) * width + x] = b;\n            }\n        }\n    }\n}\n\ninline void RayTracer::render_index(std::vector<uint32_t>& indices,\n                                    const RayCamera& camera,\n                                    int width,\n                                    int height)\n{\n    indices.resize(width * height);\n    RTCIntersectContext context;\n    rtcInitIntersectContext(&context);\n#pragma omp parallel for schedule(dynamic)\n    for (int y = 0; y < height; ++y) {\n        for (int x = 0; x < width; ++x) {\n            auto u = static_cast<float>(x) / width;\n            auto v = static_cast<float>(y) / height;\n            auto rayhit = camera.gen_ray(u, v);\n            rtcIntersect1(_scene, &context, &rayhit);\n            uint32_t index;\n            if (rayhit.hit.geomID != RTC_INVALID_GEOMETRY_ID) {\n                index = rayhit.hit.primID + 1;\n            }\n            else {\n                index = 0;\n            }\n            indices[(height - y - 1) * width + x] = index;\n        }\n    }\n}\n\ninline std::function<Eigen::Array3f(const RTCHit&)>\nRayTracer::_select_diffuse_color()\n{\n    if (_colors && _vertex_color) {\n        return std::bind(\n            &RayTracer::_diffuse_vertex_color, this, std::placeholders::_1);\n    }\n    else if (_colors && !_vertex_color) {\n        return std::bind(\n            &RayTracer::_diffuse_face_color, this, std::placeholders::_1);\n    }\n    else {\n        return std::bind(\n            &RayTracer::_diffuse_material, this, std::placeholders::_1);\n    }\n}\n\ninline Eigen::Array3f RayTracer::_diffuse_material(const RTCHit& hit)\n{\n    (void)hit;\n    return _material.diffuse;\n}\n\ninline Eigen::Array3f RayTracer::_diffuse_face_color(const RTCHit& hit)\n{\n    Eigen::Array3f diffuse;\n    diffuse << (*_colors)[3 * hit.primID], (*_colors)[3 * hit.primID + 1],\n        (*_colors)[3 * hit.primID + 2];\n    return diffuse;\n}\n\ninline Eigen::Array3f RayTracer::_diffuse_vertex_color(const RTCHit& hit)\n{\n    float buffer[4];\n    RTCInterpolateArguments args;\n    args.geometry = _geometry;\n    args.primID = hit.primID;\n    args.u = hit.u;\n    args.v = hit.v;\n    args.bufferType = RTC_BUFFER_TYPE_VERTEX_ATTRIBUTE;\n    args.bufferSlot = 0;\n    args.valueCount = 3;\n    args.P = buffer;\n    args.dPdu = nullptr;\n    args.dPdv = nullptr;\n    args.ddPdudu = nullptr;\n    args.ddPdvdv = nullptr;\n    args.ddPdudv = nullptr;\n    rtcInterpolate(&args);\n\n    Eigen::Array3f diffuse;\n    diffuse << buffer[0], buffer[1], buffer[2];\n    return diffuse;\n}\n\n} // namespace Euclid\n", "meta": {"hexsha": "0cdad5b4e44930e74f4c7cdfbf1458e66d98916a", "size": 23654, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Euclid/Render/src/RayTracer.cpp", "max_stars_repo_name": "unclejimbo/euclid", "max_stars_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2017-05-02T07:04:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T10:00:01.000Z", "max_issues_repo_path": "include/Euclid/Render/src/RayTracer.cpp", "max_issues_repo_name": "unclejimbo/euclid", "max_issues_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Euclid/Render/src/RayTracer.cpp", "max_forks_repo_name": "unclejimbo/euclid", "max_forks_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-07-02T17:59:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-18T07:01:17.000Z", "avg_line_length": 35.7311178248, "max_line_length": 80, "alphanum_fraction": 0.4982244018, "num_tokens": 5649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.2807983026769544}}
{"text": "/* MIT License\n\nCopyright (c) 2020 FORNO\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#include <cmath>\n#include <cstddef>\n#include <filesystem>\n#include <iostream>\n#include <limits>\n#include <utility>\n\n#include <boost/optional.hpp>\n#include <boost/program_options.hpp>\n#include <boost/property_tree/ini_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/tokenizer.hpp>\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\nconstexpr std::size_t marker_count {29};\n\nstruct index_holder\n{\n  std::size_t left_asis;\n  std::size_t right_asis;\n  std::size_t v_sacral;\n};\n\nindex_holder read_indexies(std::filesystem::path path);\n\nint main(int argc, char** argv)\n{\n  std::ios::sync_with_stdio(false);\n  std::cin.tie(nullptr);\n  std::cout << std::fixed;\n\n  namespace po = boost::program_options;\n\n  po::options_description description(\"Options\");\n  description.add_options()\n    (\"header,h\", po::value<bool>()->default_value(true), \"Dose the CSV has header?\")\n    (\"config,c\", po::value<std::string>(), \"Config file path\")\n    (\"l2w,l\", po::value<bool>()->default_value(false), \"Local to World flag\")\n    (\"help,H\", \"Help\")\n    ;\n\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, description), vm);\n  po::notify(vm);\n\n  if (argc < 2 || vm.count(\"help\")) {\n    std::cerr << \"Usage: \" << *argv << \" --config config/Cooking < cooking.csv\\n\";\n    return 1;\n  }\n\n  try {\n    const auto config_path = vm[\"config\"].as<std::string>();\n    const auto indexies {read_indexies(config_path)};\n    if (vm[\"header\"].as<bool>()) {\n      std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n    }\n    if (!vm[\"l2w\"].as<bool>()) {\n      for (std::string line; std::getline(std::cin, line);) {\n        boost::tokenizer<boost::escaped_list_separator<char>> tokens(line);\n        Eigen::Matrix<float, marker_count, 3, Eigen::RowMajor> values;\n        {\n          auto it = tokens.begin();\n          for (std::size_t i {0}; i < marker_count * 3; ++i) {\n            try {\n              values(i) = std::stof(*it);\n            } catch (std::invalid_argument&) {\n              values(i) = std::numeric_limits<float>::quiet_NaN();\n            }\n            ++it;\n          }\n        }\n\n        const Eigen::Vector3f center_asis = values.row(indexies.left_asis) / 2 + values.row(indexies.right_asis) / 2;\n        for (std::size_t i {0}; i < marker_count; ++i) {\n          values.row(i) -= center_asis;\n        }\n\n        const Eigen::Vector3f forward = -values.row(indexies.v_sacral);\n        const auto w2l_rotation = Eigen::Quaternionf::FromTwoVectors(forward, Eigen::Vector3f{0, 0, 1.f});\n\n        for (std::size_t i {0}; i < marker_count; ++i) {\n          values.row(i) = w2l_rotation * values.row(i);\n        }\n\n        auto is_first {true};\n        for (std::size_t i {0}; i < static_cast<std::size_t>(values.size()); ++i) {\n          if (!std::exchange(is_first, false)) {\n            std::cout.put(',');\n          }\n          if (!isnan(values(i))) {\n            std::cout << values(i);\n          }\n        }\n        const auto l2w_translation {-center_asis};\n        for (std::size_t i {0}; i < static_cast<std::size_t>(l2w_translation.size()); ++i) {\n          std::cout << ',' << l2w_translation(i);\n        }\n        const auto l2w_rotation {w2l_rotation.inverse()};\n        const auto& l2w_coeffs {l2w_rotation.coeffs()};\n        for (std::size_t i {0}; i < static_cast<std::size_t>(l2w_coeffs.size()); ++i) {\n          std::cout << ',' << l2w_coeffs(i);\n        }\n        std::cout.put('\\n');\n      }\n    } else {\n      for (std::string line; std::getline(std::cin, line);) {\n        Eigen::Matrix<float, marker_count, 3, Eigen::RowMajor> values;\n        Eigen::Vector3f translation;\n        Eigen::Quaternionf rotation;\n        {\n          boost::tokenizer<boost::escaped_list_separator<char>> tokens(line);\n          auto it = tokens.begin();\n          for (std::size_t i {0}; i < static_cast<std::size_t>(values.size()); ++i) {\n            try {\n              values(i) = std::stof(*it);\n            } catch (std::invalid_argument&) {\n              values(i) = std::numeric_limits<float>::quiet_NaN();\n            }\n            ++it;\n          }\n          for (std::size_t i {0}; i < static_cast<std::size_t>(translation.size()); ++i) {\n            try {\n              translation(i) = std::stof(*it);\n            } catch (std::invalid_argument&) {\n              translation(i) = std::numeric_limits<float>::quiet_NaN();\n            }\n            ++it;\n          }\n          Eigen::Vector4f rotation_coeffs ;\n          for (std::size_t i {0}; i < static_cast<std::size_t>(rotation_coeffs.size()); ++i) {\n            try {\n              rotation_coeffs(i) = std::stof(*it);\n            } catch (std::invalid_argument&) {\n              rotation_coeffs(i) = std::numeric_limits<float>::quiet_NaN();\n            }\n            ++it;\n          }\n          rotation = Eigen::Quaternionf(rotation_coeffs);\n        }\n        for (std::size_t i {0}; i < marker_count; ++i) {\n          values.row(i) = rotation * values.row(i) + translation;\n        }\n        auto is_first {true};\n        for (std::size_t i {0}; i < static_cast<std::size_t>(values.size()); ++i) {\n          if (!std::exchange(is_first, false)) {\n            std::cout.put(',');\n          }\n          if (!isnan(values(i))) {\n            std::cout << values(i);\n          }\n        }\n        std::cout.put('\\n');\n      }\n    }\n  } catch (boost::wrapexcept<boost::property_tree::ptree_bad_path>& e) {\n    std::cerr << \"Invalid indexies format: \" << e.what() << '\\n';\n    return 1;\n  } catch (boost::wrapexcept<boost::property_tree::ini_parser::ini_parser_error>& e) {\n    std::cerr << \"Invalid indexies file: \" << e.what() << '\\n';\n    return 1;\n  }\n\n  return 0;\n}\n\nindex_holder read_indexies(std::filesystem::path path)\n{\n  using namespace boost::property_tree;\n  ptree pt;\n  read_ini(path.native(), pt);\n  return index_holder {pt.get<std::size_t>(\"Indexies.LeftAsis\"), pt.get<std::size_t>(\"Indexies.RightAsis\"), pt.get<std::size_t>(\"Indexies.VSacral\")};\n}\n", "meta": {"hexsha": "3e6de0bdd9c03e0008533a75ad30595d707e32dd", "size": 7030, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "Shotaro-Yoshinaga/HHMCoordinateConverter", "max_stars_repo_head_hexsha": "038c42ef9dbd58f38b0835e2678f28323e0ffa2f", "max_stars_repo_licenses": ["MIT"], "max_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": "Shotaro-Yoshinaga/HHMCoordinateConverter", "max_issues_repo_head_hexsha": "038c42ef9dbd58f38b0835e2678f28323e0ffa2f", "max_issues_repo_licenses": ["MIT"], "max_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": "Shotaro-Yoshinaga/HHMCoordinateConverter", "max_forks_repo_head_hexsha": "038c42ef9dbd58f38b0835e2678f28323e0ffa2f", "max_forks_repo_licenses": ["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.6852791878, "max_line_length": 149, "alphanum_fraction": 0.5982930299, "num_tokens": 1780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.28076885850161}}
{"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_UNIT_HPP_INCLUDED\n#define BOOST_UNITS2_UNIT_HPP_INCLUDED\n\n#include <boost/units2/detail/merge.hpp>\n#include <boost/mp11/algorithm.hpp>\n#include <boost/mp11/utility.hpp>\n#include <boost/integer/common_factor_ct.hpp>\n#include <type_traits>\n#include <limits>\n#include <cstdint>\n#include <cmath>\n\n// Design goals:\n// - Can represent any unit.\n// - Can convert between any units with the same dimensions.\n// - New units can be defined in terms of any existing units.\n//   Which unit is the base unit and which unit is the derived\n//   unit shall not change the behavior of any user code outside\n//   the definition itself.\n// - The set of dimensions shall be extensible.\n// - Every unit shall be represented by one and only one type.\n// - To the maximum extent possible, conversions shall not\n//   lose precision.\n// - The raw type of a unit should be (somewhat) intelligible.\n//\n// Implementation Notes:\n// - All units are ultimately seen as a scaled combination of base units.\n// - There is exactly one base unit for each dimension.\n// - Conversions reduce both sides to the base form.\n// - To avoid loss-of-precision, all conversion factors\n//   are tracked and identical components are combined/canceled\n//   before any evaluation is done.  In addition, all calculations\n//   are carried out using exact (rational) arithmetic wherever possible.\n// - The struct that a user defines is a unit, with no wrapping required.\n// - All units are reduced to normalized form after every operation.\n// - The different types of units can be processed using a visitor via the\n//   alias _boost_units2_apply.\n//\n// Possible improvements:\n// - Allow floating point scaling to have greater precision than double.\n//   This also means passing the value_type through all the conversion logic.\n\nnamespace boost {\nnamespace units2 {\n\n/*\n * Base class for scales\n */\nstruct scale_base {\n    /// INTERNAL ONLY\n    using _boost_units2_is_scale = void;\n};\n\n/**\n * Base class for all units.\n */\ntemplate<class Derived>\nstruct unit_base {\n    /// INTERNAL ONLY\n    /// Tag for use with SFINAE\n    using _boost_units2_is_unit = void;\n    /// INTERNAL ONLY\n    /// visitor to help code that needs to switch on the kind of unit\n    template<class F, class T>\n    using _boost_units2_apply = typename F::template apply_base<T>;\n    /// INTERNAL ONLY\n    using _boost_units2_type = Derived;\n    /// INTERNAL ONLY\n    auto operator<=>(const unit_base&) const = default;\n};\n\n/**\n * Represents a unit that is a scaled version of another unit.\n * \\pre Base is a Unit\n * \\pre Scale is either a std::ratio or a type with a nested static constexpr double value();\n */\ntemplate<class Base, class Scale>\nstruct scaled_unit : unit_base<scaled_unit<Base, Scale> > {\n    /// INTERNAL ONLY\n    template<class F, class T>\n    using _boost_units2_apply = typename F::template apply_scaled<Base, Scale>;\n    /// INTERNAL ONLY\n    auto operator<=>(const scaled_unit&) const = default;\n};\n\n/**\n * Represents a unit that is a combination of other units.\n * \\pre All the elements of P must be specializations of dim\n */\ntemplate<class... P>\nstruct compound_unit : unit_base<compound_unit<P...>> {\n    /// INTERNAL ONLY\n    auto operator<=>(const compound_unit&) const = default;\n};\n\n/// INTERNAL ONLY\n/// Specializations to make compound_unit useable with merge.\ntemplate<>\nstruct compound_unit<> : unit_base<compound_unit<>> {\n    static constexpr const bool empty = true;\n    template<class F, class T>\n    using _boost_units2_apply = typename F::template apply_compound<>;\n    /// INTERNAL ONLY\n    auto operator<=>(const compound_unit&) const = default;\n};\n/// INTERNAL ONLY\ntemplate<class P0, class... P>\nstruct compound_unit<P0, P...> : unit_base<compound_unit<P0,P...>> {\n    static constexpr const bool empty = false;\n    using front = P0;\n    using pop_front = compound_unit<P...>;\n    template<class F, class T>\n    using _boost_units2_apply = typename F::template apply_compound<P0, P...>;\n    /// INTERNAL ONLY\n    auto operator<=>(const compound_unit&) const = default;\n};\n\nnamespace detail {\n\ntemplate<class F, class T>\nusing visit = typename T::template _boost_units_apply2<F, T>;\n\nconstexpr int const_strcmp(const char * lhs, const char * rhs)\n{\n    return (*lhs && *rhs) ?\n        (*lhs == *rhs ? const_strcmp(lhs+1, rhs+1) : (*lhs < *rhs ? -1 : 1)) :\n        ((!*lhs && !*rhs) ? 0 : (!*lhs ? -1 : 1));\n}\n\ntemplate<class T, class U>\nstruct scale_compare {\n    static constexpr const int value = T::value() < U::value?-1:(T::value()>U::value()?1:0);\n};\ntemplate<class T, long long N, long long D>\nstruct scale_compare<T,std::ratio<N,D>>\n{\n    static const constexpr int value = 1;\n};\ntemplate<class T, long long N, long long D>\nstruct scale_compare<std::ratio<N,D>,T>\n{\n    static const constexpr int value = -1;\n};\ntemplate<long long N1, long long D1, long long N2, long long D2>\nstruct scale_compare<std::ratio<N1,D1>,std::ratio<N2,D2>>\n{\n    static const constexpr int value = std::ratio_less<std::ratio<N1,D1>,std::ratio<N2,D2>>::value?-1:\n        (std::ratio_less<std::ratio<N2,D2>,std::ratio<N1,D1>>::value?1:0);\n};\n\n// For two user-defined units, compare by name\ntemplate<class T, class U>\nstruct unit_compare_impl {\n    static constexpr const int value = const_strcmp(T::name, U::name);\n    static_assert(std::is_same<T, U>::value || value != 0, \"Different units cannot have the same name.\");\n};\n\n// Compare compond units lexicographically\ntemplate<class T0, class... T, class U0, class... U>\nstruct unit_compare_impl<compound_unit<T0, T...>, compound_unit<U0, U...> >\n{\n    static constexpr const int value = unit_compare_impl<typename T0::base, typename U0::base>::value?\n        unit_compare_impl<typename T0::base, typename U0::base>::value:\n        (std::ratio_less<typename T0::exponent, typename U0::exponent>::value?-1:1);\n};\ntemplate<class T0, class... T, class... U>\nstruct unit_compare_impl<compound_unit<T0, T...>, compound_unit<T0, U...> >\n{\n    static constexpr const int value = unit_compare_impl<compound_unit<T...>, compound_unit<U...>>::value;\n};\ntemplate<class... T>\nstruct unit_compare_impl<compound_unit<T...>, compound_unit<> >\n{\n    static constexpr const int value = 1;\n};\ntemplate<class... T>\nstruct unit_compare_impl<compound_unit<>, compound_unit<T...> >\n{\n    static constexpr const int value = -1;\n};\ntemplate<>\nstruct unit_compare_impl<compound_unit<>, compound_unit<> >\n{\n    static constexpr const int value = 0;\n};\n\n// For scaled_unit compare the base first, then the exponent\ntemplate<class B1, class E1, class B2, class E2>\nstruct unit_compare_impl<scaled_unit<B1, E1>, scaled_unit<B2, E2> >\n{\n    static const constexpr int value = (unit_compare_impl<B1, B2>::value != 0)?\n        (unit_compare_impl<B1, B2>::value != 0):\n        scale_compare<E1, E2>::value;\n};\n\n// cross type comparisons\n// user-defined unit < scaled_unit < compound_unit\ntemplate<class... T, class U>\nstruct unit_compare_impl<compound_unit<T...>, U>\n{\n    static const constexpr int value = 1;\n};\ntemplate<class T, class... U>\nstruct unit_compare_impl<T, compound_unit<U...>>\n{\n    static const constexpr int value = -1;\n};\ntemplate<class... T, class B, class E>\nstruct unit_compare_impl<compound_unit<T...>, scaled_unit<B,E> >\n{\n    static const constexpr int value = 1;\n};\ntemplate<class B, class E, class... U>\nstruct unit_compare_impl<scaled_unit<B, E>, compound_unit<U...>>\n{\n    static const constexpr int value = -1;\n};\ntemplate<class T, class B, class E>\nstruct unit_compare_impl<T, scaled_unit<B,E> >\n{\n    static const constexpr int value = -1;\n};\ntemplate<class B, class E, class U>\nstruct unit_compare_impl<scaled_unit<B, E>, U>\n{\n    static const constexpr int value = 1;\n};\n\n// pre: T and U are both compound_units\ntemplate<class T, class U>\nusing compound_unit_multiply = detail::merge<unit_compare_impl, compound_unit, T, U>;\n\n// Wrap any class in a compound_unit iff it is not already a compound_unit.\ntemplate<class T>\nstruct as_compound_unit_impl { typedef compound_unit<dim<T, std::ratio<1, 1> > > type; };\ntemplate<class... T>\nstruct as_compound_unit_impl<compound_unit<T...> > { typedef compound_unit<T...> type; };\ntemplate<class T>\nusing as_compound_unit = typename as_compound_unit_impl<T>::type;\n\n// Unwrap any compound units of the form U^1.\n// Folds scaled_units that use std::ratio.\n// May perform other normalization as needed in the future.\n// Note: It is assumed that this normalization is applied\n// consistently, so we never need to fix more than the outer layer.\ntemplate<class T>\nstruct simplify_unit_impl { using type = T; };\ntemplate<class T>\nstruct simplify_unit_impl<compound_unit<dim<T, std::ratio<1, 1> > > > { using type = T; };\ntemplate<class T, std::intmax_t N1, std::intmax_t D1, std::intmax_t N2, std::intmax_t D2>\nstruct simplify_unit_impl<scaled_unit<scaled_unit<T, std::ratio<N1,D1>>,std::ratio<N2,D2>>> {\n    using new_scale = std::ratio_multiply<std::ratio<N1,D1>,std::ratio<N2,D2>>;\n    using type = boost::mp11::mp_if_c<(new_scale::num==1&&new_scale::den==1), T, scaled_unit<T, new_scale> >;\n};\ntemplate<class T>\nstruct simplify_unit_impl<scaled_unit<T,std::ratio<1,1>>> { using type = T; };\n// resolve ambiguity\ntemplate<class T, std::intmax_t N, std::intmax_t D>\nstruct simplify_unit_impl<scaled_unit<scaled_unit<T,std::ratio<N,D>>,std::ratio<1,1>>> {\n    using type = scaled_unit<T,std::ratio<N,D>>;\n};\ntemplate<class T>\nusing simplify_unit = typename simplify_unit_impl<T>::type;\n\n// The result of multiplying two units\ntemplate<class T, class U>\nusing unit_multiply = simplify_unit<compound_unit_multiply<as_compound_unit<T>, as_compound_unit<U> > >;\n\ntemplate<class T, class E>\nstruct unit_pow_impl;\ntemplate<class... T, class... E, class R>\nstruct unit_pow_impl<compound_unit<dim<T, E>...>, R> {\n    using type = compound_unit<dim<T, std::ratio_multiply<E, R> >...>;\n};\ntemplate<class... T, class... E>\nstruct unit_pow_impl<compound_unit<dim<T, E>...>, std::ratio<0>> {\n    using type = compound_unit<>;\n};\ntemplate<class T, class E>\nusing unit_pow = simplify_unit<typename unit_pow_impl<as_compound_unit<T>, E>::type>;\n\ntemplate<class T, class U>\nusing unit_divide = unit_multiply<T, unit_pow<U, std::ratio<-1>>>;\n\n// determine whether a type is a unit\ntemplate<class T>\nusing requires_unit = typename T::_boost_units2_is_unit;\n\ntemplate<class T, class E = void>\nstruct is_unit_impl {\n    using type = std::false_type;\n};\ntemplate<class T>\nstruct is_unit_impl<T, requires_unit<T>> {\n    using type = std::true_type;\n};\n\n// A scale must either be a std::ratio or inherit from scale_base\n// This only handles the latter.\ntemplate<class T>\nusing requires_scale = typename T::_boost_units2_is_scale;\n\n} // namespace detail\n\ntemplate<class T, class U, class = detail::requires_unit<T>, class = detail::requires_unit<U> >\nconstexpr auto operator*(T, U) -> detail::unit_multiply<T, U>\n{ return {}; }\n\ntemplate<class T, class U, class = detail::requires_unit<T>, class = detail::requires_unit<U> >\nconstexpr auto operator/(T, U) -> detail::unit_divide<T, U>\n{ return {}; }\n\n// multiplying a unit by a std::ratio creates a scaled_unit\ntemplate<class T, long long N, long long D, class = detail::requires_unit<T>>\nconstexpr auto operator*(T, std::ratio<N,D>) -> detail::simplify_unit<scaled_unit<T, typename std::ratio<N,D>::type>>\n{ return {}; }\ntemplate<class T, long long N, long long D, class = detail::requires_unit<T>>\nconstexpr auto operator*(std::ratio<N,D>, T) -> detail::simplify_unit<scaled_unit<T, typename std::ratio<N,D>::type>>\n{ return {}; }\n\n// multiplying a unit by any scale gives a scaled unit\ntemplate<class T, class U, class = detail::requires_unit<T>, class = detail::requires_scale<U> >\nconstexpr auto operator*(T, U) -> detail::simplify_unit<scaled_unit<T, U>>\n{ return {}; }\ntemplate<class T, class U, class = detail::requires_scale<T>, class = detail::requires_unit<U> >\nconstexpr auto operator*(T, U) -> detail::simplify_unit<scaled_unit<U,T>>\n{ return {}; }\n\ntemplate<std::intmax_t N, class T, class = detail::requires_unit<T>>\nconstexpr auto pow(T) -> detail::unit_pow<T, std::ratio<N>>\n{ return {}; }\n\n    template<class T, std::intmax_t N, std::intmax_t D, class = detail::requires_unit<T>>\nconstexpr auto pow(T, std::ratio<N,D>) -> detail::unit_pow<T, std::ratio<N,D>>\n{ return {}; }\n\n// Conversion support\n\nnamespace detail {\n\ntemplate<class... D>\nstruct scale_list;\n\ntemplate<>\nstruct scale_list<> {\n    static const constexpr bool empty = true;\n};\n\ntemplate<class D0, class... D>\nstruct scale_list<D0, D...> {\n    static const constexpr bool empty = false;\n    using front = D0;\n    using pop_front = scale_list<D...>;\n};\n\ntemplate<class T, class E>\nstruct scale_list_pow_impl;\ntemplate<class... T, class... E, class R>\nstruct scale_list_pow_impl<scale_list<dim<T, E>...>, R> {\n    using type = scale_list<dim<T, std::ratio_multiply<E, R> >...>;\n};\ntemplate<class T, class E>\nusing scale_list_pow = typename scale_list_pow_impl<T, E>::type;\n\ntemplate<class T, class U>\nusing scale_list_multiply = detail::merge<scale_compare, scale_list, T, U>;\n\nstruct flatten_scale_impl;\ntemplate<class T>\nusing flatten_scale = visit<flatten_scale_impl, T>;\nstruct flatten_scale_impl\n{\n    template<class T>\n    using apply_base = scale_list<>;\n\n    template<class Base, class Scale>\n    using apply_scaled = scale_list_multiply<flatten_scale<Base>, scale_list<dim<Scale, std::ratio<1>>>>;\n\n    template<class... T>\n    using apply_compound = boost::mp11::mp_fold<boost::mp11::mp_list<scale_list_pow<flatten_scale<typename T::base>, typename T::exponent>...>, scale_list<>, scale_list_multiply>;\n};\n\nstruct dimension_check_impl;\ntemplate<class T>\nusing dimension_check = visit<dimension_check_impl, T>;\nstruct dimension_check_impl\n{\n    template<class T>\n    using apply_base = typename T::_boost_units2_type;\n\n    template<class Base, class Scale>\n    using apply_scaled = dimension_check<Base>;\n\n    template<class... T>\n    using apply_compound = ::boost::mp11::mp_fold< boost::mp11::mp_list<unit_pow<dimension_check<typename T::base>, typename T::exponent>...>, compound_unit<>, unit_multiply>;\n};\n\ntemplate<class T>\nconstexpr double get_value(T) { return T::value(); }\ntemplate<long long N, long long D>\nconstexpr double get_value(std::ratio<N, D>) { return static_cast<double>(N)/D; }\n\ntemplate<class T, class U>\nstruct multiplier {\n    static constexpr double value() { return ::boost::units2::detail::get_value(T()) * ::boost::units2::detail::get_value(U()); }\n};\n\ntemplate<class B, class E>\nstruct power {\n    static /*constexpr*/ double value() { return ::std::pow(::boost::units2::detail::get_value(B()), ::boost::units2::detail::get_value(E())); }\n};\n\n// Returns 0 if overflow would happen\n// precondition: all ratios are positive\ntemplate<class T, class U>\nstruct safe_ratio_multiply\n{\n    static const constexpr long long gcd1 = ::boost::integer::static_gcd<T::num, U::den>::value;\n    static const constexpr long long gcd2 = ::boost::integer::static_gcd<U::num, T::den>::value;\n    static const constexpr bool overflow =\n        (std::numeric_limits<long long>::max()/(T::num/gcd1) > (U::num/gcd2)) ||\n        (std::numeric_limits<long long>::max()/(T::den/gcd1) > (U::den/gcd1));\n    using type = std::ratio<\n        overflow?0:(T::num/gcd1)*(U::num/gcd2),\n        overflow?1:(T::den/gcd1)*(U::den/gcd1)>;\n};\n\nconstexpr long long safe_multiply(long long lhs, long long rhs)\n{\n    return (std::numeric_limits<long long>::max)()/lhs >= rhs? lhs*rhs : 0;\n}\nconstexpr long long safe_square(long long arg)\n{\n    return safe_multiply(arg, arg);\n}\nconstexpr long long safe_power(long long base, long long exponent) {\n    return exponent == 1? base : safe_multiply(safe_square(safe_power(base, exponent/2)), (exponent%2?base:1));\n}\n\ntemplate<class B, long long E>\nstruct safe_ratio_pow {\n    static const constexpr long long abs_exponent = E < 0? -E : E;\n    static const constexpr long long num = safe_power(E<0?B::den:B::num, abs_exponent);\n    static const constexpr long long den = safe_power(E<0?B::num:B::den, abs_exponent);\n    static const constexpr bool overflow = num==0||den==0;\n    using type = std::ratio<overflow?0:num,overflow?1:den>;\n};\n\ntemplate<class T, class U>\nstruct fold_conversion_impl { using type = multiplier<T, U>; };\n\ntemplate<long long N1, long long D1, long long N2, long long D2>\nstruct fold_conversion_impl<std::ratio<N1,D1>,std::ratio<N2,D2>>\n{\n    using result1 = typename safe_ratio_multiply<std::ratio<N1, D1>, std::ratio<N2, D2> >::type;\n    using type = ::boost::mp11::mp_if_c<result1::num!=0, result1, multiplier<std::ratio<N1,D1>,std::ratio<N2,D2> > >;\n};\n\ntemplate<class T>\nstruct evaluate_power;\ntemplate<class Base, class Exponent>\nstruct evaluate_power<dim<Base, Exponent> >\n{\n    using type = power<Base, Exponent>;\n};\ntemplate<long long N, long long D, long long E>\nstruct evaluate_power<dim<std::ratio<N,D>, std::ratio<E> > >\n{\n    using result1 = typename safe_ratio_pow<std::ratio<N,D>, E>::type;\n    using type = ::boost::mp11::mp_if_c<result1::num!=0, result1, power<std::ratio<N,D>, std::ratio<E> > >;\n};\n\ntemplate<class T, class U>\nusing conversion_fold_op = typename fold_conversion_impl<T,U>::type;\n\ntemplate<class... T>\nstruct fold_conversion;\ntemplate<class... T>\nstruct fold_conversion<scale_list<T...>> {\n    using type = boost::mp11::mp_fold<boost::mp11::mp_list<typename evaluate_power<T>::type...>,std::ratio<1>,conversion_fold_op>;\n};\n\ntemplate<class T, class U>\nvoid check_conversion() {\n    static_assert(std::is_same<T, U>::value,\n        \"Cannot convert units with different dimensions.\");\n}\n\n} // namespace detail\n\ntemplate<class T, class U, class = detail::requires_unit<T>, class = detail::requires_unit<U>>\nconstexpr bool has_same_dimension(T, U)\n{\n    return std::is_same<detail::dimension_check<T>, detail::dimension_check<U>>::value;\n}\n\ntemplate<class T, class U, class = detail::requires_unit<T>, class = detail::requires_unit<U>>\nconstexpr double conversion_factor(T, U)\n{\n    // Indirection to make sure that the reduced dimensions appear\n    // in the template backtrace.\n    detail::check_conversion<detail::dimension_check<T>, detail::dimension_check<U>>();\n    return ::boost::units2::detail::get_value(typename detail::fold_conversion<detail::flatten_scale<detail::unit_divide<T, U>>>::type());\n}\n\n}\n}\n\n#endif\n", "meta": {"hexsha": "94e3fdeca77154c7b2b5bb865c73b24ea3f7c839", "size": 18474, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/units2/unit.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/unit.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/unit.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": 35.8023255814, "max_line_length": 179, "alphanum_fraction": 0.7076431742, "num_tokens": 4740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.28069760311557074}}
{"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 \"CompareDVH.h\"\n\n#include <boost/make_shared.hpp>\n\nnamespace rttb\n{\n\n\tnamespace testing\n\t{\n\n\t\tbool checkEqualDVH(DVHPointer aDVH1, DVHPointer aDVH2)\n\t\t{\n\n\t\t\tbool result;\n\t\t\tconst double errorConstantDVH = 1e-4;\n\t\t\tresult = lit::AreClose(aDVH1->getDeltaD(), aDVH2->getDeltaD(), errorConstantDVH);\n\t\t\tresult = result && lit::AreClose(aDVH1->getDeltaV(), aDVH2->getDeltaV(), errorConstantDVH);\n\t\t\tresult = result && (aDVH1->getDoseID() == aDVH2->getDoseID());\n\t\t\tresult = result && (aDVH1->getStructureID() == aDVH2->getStructureID());\n\t\t\tresult = result && lit::AreClose(aDVH1->getMaximum(), aDVH2->getMaximum(), errorConstantDVH);\n\t\t\tresult = result && lit::AreClose(aDVH1->getMinimum(), aDVH2->getMinimum(), errorConstantDVH);\n\t\t\tresult = result && lit::AreClose(aDVH1->getMean(), aDVH2->getMean(), errorConstantDVH);\n\t\t\tresult = result && (aDVH1->getDataDifferential().size() == aDVH2->getDataDifferential().size());\n\n\t\t\tfor (size_t i = 0; i < aDVH1->getDataDifferential().size(); i++)\n\t\t\t{\n\t\t\t\tresult = result\n\t\t\t\t         && lit::AreClose(aDVH1->getDataDifferential().at(i), aDVH2->getDataDifferential().at(i),\n\t\t\t\t\t\t\t errorConstantDVH);\n\t\t\t}\n\n\t\t\treturn result;\n\n\t\t}\n\n        rttb::testing::DVHPointer computeDiffDVH(DVHPointer aDVH1, DVHPointer aDVH2)\n        {\n            if (aDVH1->getDeltaD() == aDVH2->getDeltaD() && aDVH1->getDeltaV() == aDVH2->getDeltaV()){\n\n                rttb::core::DVH::DataDifferentialType dvhData1 = aDVH1->getDataDifferential();\n                rttb::core::DVH::DataDifferentialType dvhData2 = aDVH2->getDataDifferential();\n                rttb::core::DVH::DataDifferentialType dvhDataDifference;\n\n                auto it1 = dvhData1.cbegin();\n                auto it2 = dvhData2.cbegin();\n\n                while (it1 != dvhData1.cend() && it2 != dvhData2.cend())\n                {\n                    dvhDataDifference.push_back(*it1-*it2);\n                    ++it1;\n                    ++it2;\n                }\n\n                auto differenceDVH = ::boost::make_shared<core::DVH>(dvhDataDifference, aDVH1->getDeltaD(), aDVH1->getDeltaV(), aDVH1->getStructureID(), aDVH1->getDoseID());\n                return differenceDVH;\n            }\n            else {\n                return aDVH1;\n            }\n        }\n\n    }//testing\n}//rttb\n\n", "meta": {"hexsha": "b0929165ba30fb72501b1051056e2e24195d877a", "size": 2950, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testing/io/other/CompareDVH.cpp", "max_stars_repo_name": "MIC-DKFZ/RTTB", "max_stars_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2018-04-19T12:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T17:43:02.000Z", "max_issues_repo_path": "testing/io/other/CompareDVH.cpp", "max_issues_repo_name": "MIC-DKFZ/RTTB", "max_issues_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/io/other/CompareDVH.cpp", "max_forks_repo_name": "MIC-DKFZ/RTTB", "max_forks_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-06-24T21:09:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T09:30:49.000Z", "avg_line_length": 36.875, "max_line_length": 173, "alphanum_fraction": 0.5983050847, "num_tokens": 819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.4765796510636759, "lm_q1q2_score": 0.2806525764565248}}
{"text": "// Copyright (c) Microsoft Corporation.\r\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\r\n\r\n#include <cerrno>\r\n#include <cmath>\r\n#include <limits>\r\n#include <type_traits>\r\n#include <utility>\r\n\r\n#pragma warning(push)\r\n#pragma warning(disable : 4619) // #pragma warning: there is no warning number '%d'\r\n#pragma warning(disable : 4643) // Forward declaring '%s' in namespace std is not permitted by the C++ Standard\r\n#pragma warning(disable : 4702) // unreachable code\r\n#pragma warning(disable : 5219) // implicit conversion from '%s' to '%s', possible loss of data\r\n\r\n#define BOOST_CHRONO_HEADER_ONLY\r\n#define BOOST_CONFIG_SUPPRESS_OUTDATED_MESSAGE\r\n#define BOOST_MATH_DOMAIN_ERROR_POLICY   errno_on_error\r\n#define BOOST_MATH_OVERFLOW_ERROR_POLICY ignore_error\r\n\r\n// Using headers from Boost.Math\r\n#include <boost/math/special_functions/bessel.hpp>\r\n#include <boost/math/special_functions/beta.hpp>\r\n#include <boost/math/special_functions/ellint_1.hpp>\r\n#include <boost/math/special_functions/ellint_2.hpp>\r\n#include <boost/math/special_functions/ellint_3.hpp>\r\n#include <boost/math/special_functions/expint.hpp>\r\n#include <boost/math/special_functions/hermite.hpp>\r\n#include <boost/math/special_functions/laguerre.hpp>\r\n#include <boost/math/special_functions/legendre.hpp>\r\n#include <boost/math/special_functions/spherical_harmonic.hpp>\r\n#include <boost/math/special_functions/zeta.hpp>\r\n#include <boost/math/tools/config.hpp>\r\n#include <boost/math/tools/precision.hpp>\r\n\r\n#pragma warning(pop)\r\n\r\nnamespace {\r\n    template <class _Func>\r\n    _NODISCARD auto _Boost_call(const _Func& _Fn) noexcept {\r\n        _TRY_BEGIN\r\n        return _Fn();\r\n        _CATCH_ALL\r\n        errno     = EDOM;\r\n        using _Ty = _STD decay_t<decltype(_Fn())>;\r\n        return _STD numeric_limits<_Ty>::quiet_NaN();\r\n        _CATCH_END\r\n    }\r\n} // unnamed namespace\r\n\r\n_EXTERN_C\r\n_CRT_SATELLITE_2 _NODISCARD double __stdcall __std_smf_assoc_laguerre(\r\n    const unsigned int _Pn, const unsigned int _Pm, const double _Px) noexcept {\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::laguerre(_Pn, _Pm, _Px); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD float __stdcall __std_smf_assoc_laguerref(\r\n    const unsigned int _Pn, const unsigned int _Pm, const float _Px) noexcept {\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::laguerre(_Pn, _Pm, _Px); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD double __stdcall __std_smf_assoc_legendre(\r\n    const unsigned int _Pl, const unsigned int _Pm, const double _Px) noexcept {\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] {\r\n        auto _Result = ::boost::math::legendre_p(_Pl, _Pm, _Px);\r\n        // Boost includes the Condon-Shortley phase term (-1)^m, std does not\r\n        if ((_Pm & 1u) != 0) {\r\n            _Result = -_Result;\r\n        }\r\n        return _Result;\r\n    });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD float __stdcall __std_smf_assoc_legendref(\r\n    const unsigned int _Pl, const unsigned int _Pm, const float _Px) noexcept {\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] {\r\n        auto _Result = ::boost::math::legendre_p(_Pl, _Pm, _Px);\r\n        // Boost includes the Condon-Shortley phase term (-1)^m, std does not\r\n        if ((_Pm & 1u) != 0) {\r\n            _Result = -_Result;\r\n        }\r\n        return _Result;\r\n    });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD double __stdcall __std_smf_beta(const double _Px, const double _Py) noexcept {\r\n    return _Boost_call([=] { return ::boost::math::beta(_Px, _Py); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD float __stdcall __std_smf_betaf(const float _Px, const float _Py) noexcept {\r\n    return _Boost_call([=] { return ::boost::math::beta(_Px, _Py); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD double __stdcall __std_smf_comp_ellint_1(const double _Pk) noexcept {\r\n    return _Boost_call([=] { return ::boost::math::ellint_1(_Pk); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD float __stdcall __std_smf_comp_ellint_1f(const float _Pk) noexcept {\r\n    return _Boost_call([=] { return ::boost::math::ellint_1(_Pk); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD double __stdcall __std_smf_comp_ellint_2(const double _Pk) noexcept {\r\n    if (_STD isnan(_Pk)) {\r\n        return _Pk;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::ellint_2(_Pk); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD float __stdcall __std_smf_comp_ellint_2f(const float _Pk) noexcept {\r\n    if (_STD isnan(_Pk)) {\r\n        return _Pk;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::ellint_2(_Pk); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD double __stdcall __std_smf_comp_ellint_3(const double _Pk, const double _Pnu) noexcept {\r\n    if (_STD isnan(_Pk)) {\r\n        return _Pk;\r\n    }\r\n\r\n    if (_STD isnan(_Pnu)) {\r\n        return _Pnu;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::ellint_3(_Pk, _Pnu); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD float __stdcall __std_smf_comp_ellint_3f(const float _Pk, const float _Pnu) noexcept {\r\n    if (_STD isnan(_Pk)) {\r\n        return _Pk;\r\n    }\r\n\r\n    if (_STD isnan(_Pnu)) {\r\n        return _Pnu;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::ellint_3(_Pk, _Pnu); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD double __stdcall __std_smf_cyl_bessel_i(const double _Pnu, const double _Px) noexcept {\r\n    if (_STD isnan(_Pnu)) {\r\n        return _Pnu;\r\n    }\r\n\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::cyl_bessel_i(_Pnu, _Px); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD float __stdcall __std_smf_cyl_bessel_if(const float _Pnu, const float _Px) noexcept {\r\n    if (_STD isnan(_Pnu)) {\r\n        return _Pnu;\r\n    }\r\n\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::cyl_bessel_i(_Pnu, _Px); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD double __stdcall __std_smf_cyl_bessel_j(const double _Pnu, const double _Px) noexcept {\r\n    if (_STD isnan(_Pnu)) {\r\n        return _Pnu;\r\n    }\r\n\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::cyl_bessel_j(_Pnu, _Px); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD float __stdcall __std_smf_cyl_bessel_jf(const float _Pnu, const float _Px) noexcept {\r\n    if (_STD isnan(_Pnu)) {\r\n        return _Pnu;\r\n    }\r\n\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::cyl_bessel_j(_Pnu, _Px); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD double __stdcall __std_smf_cyl_bessel_k(const double _Pnu, const double _Px) noexcept {\r\n    if (_STD isnan(_Pnu)) {\r\n        return _Pnu;\r\n    }\r\n\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::cyl_bessel_k(_Pnu, _Px); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD float __stdcall __std_smf_cyl_bessel_kf(const float _Pnu, const float _Px) noexcept {\r\n    if (_STD isnan(_Pnu)) {\r\n        return _Pnu;\r\n    }\r\n\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::cyl_bessel_k(_Pnu, _Px); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD double __stdcall __std_smf_cyl_neumann(const double _Pnu, const double _Px) noexcept {\r\n    if (_STD isnan(_Pnu)) {\r\n        return _Pnu;\r\n    }\r\n\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::cyl_neumann(_Pnu, _Px); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD float __stdcall __std_smf_cyl_neumannf(const float _Pnu, const float _Px) noexcept {\r\n    if (_STD isnan(_Pnu)) {\r\n        return _Pnu;\r\n    }\r\n\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::cyl_neumann(_Pnu, _Px); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD double __stdcall __std_smf_ellint_1(const double _Pk, const double _Pphi) noexcept {\r\n    if (_STD isnan(_Pk)) {\r\n        return _Pk;\r\n    }\r\n\r\n    if (_STD isnan(_Pphi)) {\r\n        return _Pphi;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::ellint_1(_Pk, _Pphi); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD float __stdcall __std_smf_ellint_1f(const float _Pk, const float _Pphi) noexcept {\r\n    if (_STD isnan(_Pk)) {\r\n        return _Pk;\r\n    }\r\n\r\n    if (_STD isnan(_Pphi)) {\r\n        return _Pphi;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::ellint_1(_Pk, _Pphi); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD double __stdcall __std_smf_ellint_2(const double _Pk, const double _Pphi) noexcept {\r\n    if (_STD isnan(_Pk)) {\r\n        return _Pk;\r\n    }\r\n\r\n    if (_STD isnan(_Pphi)) {\r\n        return _Pphi;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::ellint_2(_Pk, _Pphi); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD float __stdcall __std_smf_ellint_2f(const float _Pk, const float _Pphi) noexcept {\r\n    if (_STD isnan(_Pk)) {\r\n        return _Pk;\r\n    }\r\n\r\n    if (_STD isnan(_Pphi)) {\r\n        return _Pphi;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::ellint_2(_Pk, _Pphi); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD double __stdcall __std_smf_ellint_3(\r\n    const double _Pk, const double _Pnu, const double _Pphi) noexcept {\r\n    if (_STD isnan(_Pk)) {\r\n        return _Pk;\r\n    }\r\n\r\n    if (_STD isnan(_Pnu)) {\r\n        return _Pnu;\r\n    }\r\n\r\n    if (_STD isnan(_Pphi)) {\r\n        return _Pphi;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::ellint_3(_Pk, _Pnu, _Pphi); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD float __stdcall __std_smf_ellint_3f(\r\n    const float _Pk, const float _Pnu, const float _Pphi) noexcept {\r\n    if (_STD isnan(_Pk)) {\r\n        return _Pk;\r\n    }\r\n\r\n    if (_STD isnan(_Pnu)) {\r\n        return _Pnu;\r\n    }\r\n\r\n    if (_STD isnan(_Pphi)) {\r\n        return _Pphi;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::ellint_3(_Pk, _Pnu, _Pphi); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD double __stdcall __std_smf_expint(const double _Px) noexcept {\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::expint(_Px); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD float __stdcall __std_smf_expintf(const float _Px) noexcept {\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::expint(_Px); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD double __stdcall __std_smf_hermite(const unsigned int _Pn, const double _Px) noexcept {\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::hermite(_Pn, _Px); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD float __stdcall __std_smf_hermitef(const unsigned int _Pn, const float _Px) noexcept {\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::hermite(_Pn, _Px); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD double __stdcall __std_smf_laguerre(const unsigned int _Pn, const double _Px) noexcept {\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::laguerre(_Pn, _Px); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD float __stdcall __std_smf_laguerref(const unsigned int _Pn, const float _Px) noexcept {\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::laguerre(_Pn, _Px); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD double __stdcall __std_smf_legendre(const unsigned int _Pl, const double _Px) noexcept {\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::legendre_p(_Pl, _Px); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD float __stdcall __std_smf_legendref(const unsigned int _Pl, const float _Px) noexcept {\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::legendre_p(_Pl, _Px); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD double __stdcall __std_smf_riemann_zeta(const double _Px) noexcept {\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::zeta(_Px); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD float __stdcall __std_smf_riemann_zetaf(const float _Px) noexcept {\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::zeta(_Px); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD double __stdcall __std_smf_sph_bessel(const unsigned int _Pn, const double _Px) noexcept {\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::sph_bessel(_Pn, _Px); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD float __stdcall __std_smf_sph_besself(const unsigned int _Pn, const float _Px) noexcept {\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::sph_bessel(_Pn, _Px); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD double __stdcall __std_smf_sph_legendre(\r\n    const unsigned int _Pl, const unsigned int _Pm, const double _Ptheta) noexcept {\r\n    if (_STD isnan(_Ptheta)) {\r\n        return _Ptheta;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::spherical_harmonic_r(_Pl, _Pm, _Ptheta, 0.0); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD float __stdcall __std_smf_sph_legendref(\r\n    const unsigned int _Pl, const unsigned int _Pm, const float _Ptheta) noexcept {\r\n    if (_STD isnan(_Ptheta)) {\r\n        return _Ptheta;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::spherical_harmonic_r(_Pl, _Pm, _Ptheta, 0.0f); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD double __stdcall __std_smf_sph_neumann(const unsigned int _Pn, const double _Px) noexcept {\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::sph_neumann(_Pn, _Px); });\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD float __stdcall __std_smf_sph_neumannf(const unsigned int _Pn, const float _Px) noexcept {\r\n    if (_STD isnan(_Px)) {\r\n        return _Px;\r\n    }\r\n\r\n    return _Boost_call([=] { return ::boost::math::sph_neumann(_Pn, _Px); });\r\n}\r\n_END_EXTERN_C\r\n\r\nnamespace {\r\n    template <class _Ty>\r\n    _NODISCARD _Ty _Hypot3(_Ty _Dx, _Ty _Dy, _Ty _Dz) noexcept { // type-oblivious backend for 3-arg hypot\r\n        static_assert(_STD is_floating_point_v<_Ty>);\r\n        _Dx = _STD abs(_Dx);\r\n        _Dy = _STD abs(_Dy);\r\n        _Dz = _STD abs(_Dz);\r\n\r\n        constexpr _Ty _Inf = _STD numeric_limits<_Ty>::infinity();\r\n        if (_Dx == _Inf || _Dy == _Inf || _Dz == _Inf) {\r\n            return _Inf;\r\n        }\r\n\r\n        if (_Dy > _Dx) {\r\n            _STD swap(_Dx, _Dy);\r\n        }\r\n\r\n        if (_Dz > _Dx) {\r\n            _STD swap(_Dx, _Dz);\r\n        }\r\n\r\n        constexpr _Ty _Eps = ::boost::math::tools::epsilon<_Ty>();\r\n        if (_Dx * _Eps >= _Dy && _Dx * _Eps >= _Dz) {\r\n            return _Dx;\r\n        }\r\n\r\n        const auto _DyDx = _Dy / _Dx;\r\n        const auto _DzDx = _Dz / _Dx;\r\n\r\n        return _Dx * _STD sqrt(1 + _DyDx * _DyDx + _DzDx * _DzDx);\r\n    }\r\n} // unnamed namespace\r\n\r\n_EXTERN_C\r\n_CRT_SATELLITE_2 _NODISCARD double __stdcall __std_smf_hypot3(\r\n    const double _Dx, const double _Dy, const double _Dz) noexcept {\r\n    return _Hypot3(_Dx, _Dy, _Dz);\r\n}\r\n\r\n_CRT_SATELLITE_2 _NODISCARD float __stdcall __std_smf_hypot3f(\r\n    const float _Dx, const float _Dy, const float _Dz) noexcept {\r\n    return _Hypot3(_Dx, _Dy, _Dz);\r\n}\r\n_END_EXTERN_C\r\n", "meta": {"hexsha": "105b54b268a57398b6601d5189c4cdc359202f50", "size": 15397, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "stl/src/special_math.cpp", "max_stars_repo_name": "hikmatfarhat-ndu/STL", "max_stars_repo_head_hexsha": "f357e2c3cb7b36c4322ce620a3942aea7a0fd909", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-14T21:36:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-19T18:13:03.000Z", "max_issues_repo_path": "stl/src/special_math.cpp", "max_issues_repo_name": "hikmatfarhat-ndu/STL", "max_issues_repo_head_hexsha": "f357e2c3cb7b36c4322ce620a3942aea7a0fd909", "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": "stl/src/special_math.cpp", "max_forks_repo_name": "hikmatfarhat-ndu/STL", "max_forks_repo_head_hexsha": "f357e2c3cb7b36c4322ce620a3942aea7a0fd909", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-04-24T05:04:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-17T22:48:58.000Z", "avg_line_length": 30.1311154599, "max_line_length": 120, "alphanum_fraction": 0.6424628174, "num_tokens": 4789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2806525764565248}}
{"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\n// number of dimensions (must be 2 or 3)\nconst int D = 2;\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;\n\n// boost is used for its spatial index\nusing BoostPoint = boost::geometry::model::point<\n    double, D, boost::geometry::cs::cartesian>;\n\nusing IndexValue = std::pair<BoostPoint, int>;\n\nusing Index = boost::geometry::index::rtree<\n    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 std::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 std::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 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\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 std::mt19937 gen(\n        std::chrono::high_resolution_clock::now().time_since_epoch().count());\n    std::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// 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(0) {}\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    // 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(std::make_pair(p.ToBoost(), id));\n        m_Points.push_back(p);\n        m_JoinAttempts.push_back(0);\n        m_BoundingRadius = std::max(\n            m_BoundingRadius, p.Length() + m_AttractionDistance);\n        std::cout\n            << id << \",\" << parent << \",\"\n            << p.X() << \",\" << p.Y() << \",\" << p.Z() << std::endl;\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    // 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            // check if close enough to join\n            if (d < m_AttractionDistance) {\n                if (!ShouldJoin(p, parent)) {\n                    // push particle away a bit\n                    p = Lerp(m_Points[parent], p,\n                        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, parent);\n                return;\n            }\n\n            // move randomly\n            const double m = std::max(\n                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\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    std::vector<Vector> m_Points;\n\n    // m_JoinAttempts tracks how many times other particles have attempted to\n    // join with each finalized particle\n    std::vector<int> m_JoinAttempts;\n\n    // m_Index is the spatial index used to accelerate nearest neighbor queries\n    Index m_Index;\n};\n\nint main() {\n    // create the model\n    Model model;\n\n    // add seed point(s)\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 = std::cos(a) * r;\n    //         const double y = std::sin(a) * r;\n    //         model.Add(Vector(x, y, 0));\n    //     }\n    // }\n\n    // run diffusion-limited aggregation\n    for (int i = 0; i < 100000; i++) {\n        model.AddParticle();\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "e9500a483af04825562ffbc177be132da35efd1e", "size": 9346, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlaf.cpp", "max_stars_repo_name": "fogleman/dlaf", "max_stars_repo_head_hexsha": "fc684bdb7900b23744c11bdd2fff93056f16bfbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 170.0, "max_stars_repo_stars_event_min_datetime": "2019-02-07T20:53:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T06:57:50.000Z", "max_issues_repo_path": "dlaf.cpp", "max_issues_repo_name": "fogleman/dlaf", "max_issues_repo_head_hexsha": "fc684bdb7900b23744c11bdd2fff93056f16bfbf", "max_issues_repo_licenses": ["MIT"], "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": "fogleman/dlaf", "max_forks_repo_head_hexsha": "fc684bdb7900b23744c11bdd2fff93056f16bfbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-02-09T07:41:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-31T05:59:38.000Z", "avg_line_length": 29.4826498423, "max_line_length": 79, "alphanum_fraction": 0.6026107426, "num_tokens": 2278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297745935070808, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.28058318182494557}}
{"text": "/**\t\\file gridmap.h\n * \\brief Implementation an occupancymap updated from laser range scans for mobile robot. \n * The included is an Astar pathfinder, such that optimal obstacle-free paths can be \n * generated from the robots location to any goal location. OpenCV and Eigen are required.\n *\n * \\author Hjalte Bested Møller\n * \\date 4. April 2018\t\n *\n*/\n\n#ifndef GRIDMAP_H\n#define GRIDMAP_H\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/highgui/highgui.hpp>\n\n#define ASTAR_USE_OPENCV\n#include \"astar.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace cv;\n\n\n/*\n#ifndef USE_CV_DISTANCE_TRANSFORM\n%define USE_CV_DISTANCE_TRANSFORM\n#endif\n*/\n\n\n/** Class representing a laser scanner:\n* It contains data structures for maintaining the laser scan data and the scanners pose in the inertial frame, \n* functions for doing various coordinate systems transformations, and also implements \n* a simulated laser scanner that facilitates development \n*/\nclass LaserScanner {\npublic:\n    /** Construct LaserScanner object */\n    LaserScanner() { \n        // Laser Parameters\n        this->maxDistance = 4.0f;\n        this->resolDeg = 0.36f;\n        this->fov = 180.0f;\n        this->init();\n    } \n\n    /**  Max Distance (Laser Measurement Range) in meters - If points are detected further from the scanner than this value, the point is ignored */\n    float maxDistance;  \n    /** Minimum Distance (Laser Measurement Range) in meters - If points are detected closer to the scanner than this value, the point is ignored */\n    float minDistance; \n    /** Laser Scanner Resolution in Deg (Only Used By Simulator) */\n    float resolDeg;     \n    /** Laser Scanner Resolution in Rad (Only Used By Simulator) */\n    float resolRad;   \n    /** Laser Scanner Field-of-view in Deg (Only Used By Simulator) */\n    float fov;         \n\n    /** Number of scanning lines (deduced from scan width and resolution in case of ) */\n    int nScanLines;     \n\n    /** Matrix for holding the laser scan data format is scanData(2,nScanLines), where phi(i) = scanData(0,i), r(i) = scanData(1,i) */\n    MatrixXd scanData;  \n\n    /** Matrix for holding the laser scan data format is scanCart(2,nScanLines), where x^s(i) = scanData(0,i), y^s(i) = scanData(1,i) */\n    MatrixXd scanCart;\n\n    /** Matrix for holding the laser scan data format is scanWorld(2,nScanLines), where x^i(i) = scanData(0,i), y^i(i) = scanData(1,i) */\n    MatrixXd scanWorld;\n\n    /** Initialise LaserScanner: Calculate the resolution in radian and determine the number of scanning lines nScanLines */\n    void init(){\n        this->resolRad = resolDeg*M_PI/180.0;\n        this->nScanLines = round(fov/resolDeg+1);\n    }\n\n    /** Scan Pose in world coordinates (x,y,theta) */\n    Vector3f pose;  \n\n    /** Set Scan Pose in world coordinates (x,y,theta) */\n    void setPose(Vector3f const& newpose){ \n        pose = newpose;\n    }\n    /** Set Scan Pose in world coordinates (x,y,theta) */\n    void setPose(float x, float y, float th){ \n        pose << x,y,th; \n    }\n\n    /** Return pose */\n    Vector3f getPose(){ \n        return pose; \n    }\n\n    /** Convert polar coordinates to cartesian coordinates */\n    MatrixXd polarToCart(MatrixXd const& scanPolar){\n        const int nScanLines = scanPolar.cols();\n        scanCart.resize(2,nScanLines);\n        for(int i=0; i<nScanLines; i++){\n            double const& phi = scanPolar(0,i);\n            double const& rho = scanPolar(1,i);\n            double x = rho * cos(phi);\n            double y = rho * sin(phi);\n            scanCart(0,i) = x;\n            scanCart(1,i) = y;\n        }\n        return scanCart;\n    }\n\n    /** Convert cartesian coordinates in the scanner frame to cartesian coordinates in the world frame */\n    MatrixXd cartToWorld(MatrixXd const& scanCart, Vector3f const& pose){\n        const int& nScanLines = scanCart.cols();\n        scanWorld.resize(2,nScanLines);\n        double const& x = pose(0);\n        double const& y = pose(1);\n        double const& th = pose(2);\n        double costh = cos(th);\n        double sinth = sin(th);\n\n        // Transform all the coordinates and store them in scanWorld\n        for(int i=0; i<nScanLines; i++){\n            double const& xs = scanCart(0,i);\n            double const& ys = scanCart(1,i);\n            double xw = xs*costh - ys*sinth + x;\n            double yw = ys*costh + xs*sinth + y;\n            scanWorld(0,i) = xw;\n            scanWorld(1,i) = yw;\n        }\n        return scanWorld;\n    }\n\n    /** Convert polar coordinates in the scanner frame to cartesian coordinates in the world frame directly */\n    inline MatrixXd polarToWorld(MatrixXd const& scanPolar, Vector3f const& pose){\n        return cartToWorld(polarToCart(scanPolar),pose);\n    }\n\n    /** Overloaded convinience method: Convert cartesian coordinates in the scanner frame to cartesian coordinates in the world frame */\n    inline MatrixXd cartToWorld(MatrixXd const& scanCart){\n        return cartToWorld(scanCart, this->pose);\n    }\n\n    /** Overloaded convinience method: Convert polar coordinates in the scanner frame to cartesian coordinates in the world frame directly */\n    inline MatrixXd polarToWorld(MatrixXd const& scanPolar){\n        return polarToWorld(scanPolar,pose);\n    }\n\n    /** Return scan in polar (default) coordinates */\n    inline MatrixXd getScanPolar(){\n        return scanData;\n    }\n\n    /** Return scan in Laser local cartesian coordinates */\n    inline MatrixXd getScanCart(){\n        return polarToCart(scanData);\n    }\n\n    /** Return scan in world cartesian coordinates, based on the internal pose */\n    inline MatrixXd getScanCartWorld(){\n        return polarToWorld(scanData, pose);\n    }\n\n    /** Resize MatrixXd scanData such that it has two rows and nScanLines columns */\n    void resize(int nScanLines){\n        this->nScanLines = nScanLines;\n        scanData.resize(2,nScanLines);\n    }\n\n    /** When working with a real laserscanner this is the way to fill the in the scanData */\n    void setScanPoint(int i, double phi, double r){\n        scanData(0,i) = phi;\n        scanData(1,i) = r;\n    }\n\n    /** Simulate a laser scan - The lines are defined as a matrix where each column represents a line and the rows are [x1, y1, x2, y2] */\n    MatrixXd simScan(Vector3f const& pose, MatrixXd const& lines){\n        int nLines = lines.cols();\n        double x = pose(0);\n        double y = pose(1);\n        double th = pose(2);\n        double costh = cos(th);\n        double sinth = sin(th);\n        // cout << \"th=\" << th << endl;\n\n        /* ----------------------------------------\n         * ---- Pre-allocate the memory needs -----\n         * --------------------------------------*/\n\n        // Global system coordinates\n        VectorXd xStart(nLines);\n        VectorXd yStart(nLines);\n        VectorXd xEnd(nLines);\n        VectorXd yEnd(nLines);\n\n        // Laser scanner local system coordinates\n        VectorXd xStartTrans(nLines);\n        VectorXd yStartTrans(nLines);\n        VectorXd xEndTrans(nLines);\n        VectorXd yEndTrans(nLines);\n\n        // Parameters for the line equations of the form: a*x+ b*y=c \n        VectorXd a(nLines);\n        VectorXd b(nLines);\n        VectorXd c(nLines);\n\n        // Rezise the scanData matrix, if the size is correct already, Eigen \n        // ensures that this is a no-operation\n        scanData.resize(2,nScanLines); \n\n        /* ------------------------------------------------------------------------\n         * --- Conversion of the lines from global frame to scanner local frame ---\n         * --------------------------------------------------------------------- */\n\n        // For each line:\n        // cout << \"nLines\" << nLines << endl;\n\n        for(int i=0; i<nLines; i++){\n            // Start and end values for the lines ending points.\n            xStart(i) = lines(0,i);\n            yStart(i) = lines(1,i);\n            xEnd(i)   = lines(2,i);\n            yEnd(i)   = lines(3,i);\n            // cout << \"Line = (\" << xStart(i) << \",\" << yStart(i) << \",\" << xEnd(i) << \",\" << yEnd(i) << \")\" << endl;\n\n            // Transformation of the lines to the laser scanner's coordinate system.\n            // Lines are converted to the new coordinate system.\n            xStartTrans(i) = (xStart(i)-x)*costh + (yStart(i)-y)*sinth;\n            yStartTrans(i) = (yStart(i)-y)*costh - (xStart(i)-x)*sinth; \n            xEndTrans(i) = (xEnd(i)-x)*costh   + (yEnd(i)-y)*sinth;\n            yEndTrans(i) = (yEnd(i)-y)*costh   - (xEnd(i)-x)*sinth;\n            // cout << \"LineTrans = (\" << xStartTrans(i) << \",\" << yStartTrans(i) << \",\" << xEndTrans(i) << \",\" << yEndTrans(i) << \")\" << endl;\n\n            // Starting and ending points are swapped if the x value of the \n            // starting point is bigger than the x value of the ending point.\n            if( xStartTrans(i) > xEndTrans(i)){\n                double temp = xStartTrans(i);\n                xStartTrans(i) = xEndTrans(i);\n                xEndTrans(i) = temp;\n                temp = yStartTrans(i);\n                yStartTrans(i) = yEndTrans(i);\n                yEndTrans(i) = temp;\n            }\n\n            if( xStartTrans(i) == xEndTrans(i)){\n                xEndTrans(i) += 1e-6;\n            }\n            // cout << \"LineTrans = (\" << xStartTrans(i) << \",\" << yStartTrans(i) << \",\" << xEndTrans(i) << \",\" << yEndTrans(i) << \")\" << endl;\n\n            // The line equations are calculated \n            // a*x+ b*y=c - IMPORTANT: Variables related to the line equations must \n            // be double precition to avoid numerical issues!\n            a(i) = yStartTrans(i)-yEndTrans(i);\n            b(i) = xEndTrans(i)-xStartTrans(i);\n            double a2 = a(i)*a(i);\n            double b2 = b(i)*b(i);\n            double l = sqrt(a2+b2);\n            a(i) = a(i)/l;\n            b(i) = b(i)/l;\n            c(i) = a(i)*xStartTrans(i)+b(i)*yStartTrans(i);\n            // cout << \"Line \" << i << \": \" << a(i) << \"x + \" << b(i) << \"y = \" << c(i)<< endl;\n        }\n\n        /* -------------------------------------------------------------------\n         * Conversion of what the laser scanner sees to polar coordinates.\n         * -------------------------------------------------------------------*/\n\n        // For each laser scanner angle:\n        for(int i=0; i<nScanLines; i++){\n            // Laser scanner maximum measured distance maxDistance(in meters)\n            // Closest distance from the laser scanner.\n            double min_dist = maxDistance;\n\n            // Current laser scanner angle \n            double phi = i*resolRad-fov/2.0*M_PI/180.0; \n            // Find distance from the lines to laser scanner in the current angle\n            double cosphi = cos(phi);\n            double sinphi = sin(phi);\n            // cout << \"cos(phi)=\" << cosphi << \", sin(phi)=\" << sinphi << endl;\n            for(int j=0; j<nLines; j++){\n                double temp = a(j)*cosphi + b(j)*sinphi;\n                if(abs(temp) > 1e-8){\n                    double t = c(j)/temp;\n                    if(t>0 && t<min_dist){\n                        if(abs(xStartTrans(j)-xEndTrans(j)) > 1e-8){\n                            if(t*cosphi < xEndTrans(j) && t*cosphi > xStartTrans(j)) min_dist=t;\n                        else \n                            if(yEndTrans(j) > yStartTrans(j)){\n                                if(t*sinphi < yEndTrans(j) && t*sinphi > yStartTrans(j)) min_dist=t; \n                            } else {\n                                if(t*sinphi > yEndTrans(j) && t*sinphi < yStartTrans(j)) min_dist=t; \n                            }\n                            \n                        }\n                    }\n                }    \n            }\n\n            // The polar coordinates returned\n            scanData(0,i) = phi;\n            scanData(1,i) = min_dist;\n        }\n        return scanData;\n    }\n\n    /** Simulate a laser scan - The lines are defined as a matrix where each column represents a line and the rows are [x1, y1, x2, y2] */\n    inline MatrixXd simScan(MatrixXd const& lines){\n        return simScan(pose,lines);\n    }\n};\n\n/** Implementation an occupancy grid-map updated from laser range scans including path finder for mobile robot. \n * The included is an Astar pathfinder, such that optimal obstacle-free paths can be \n * generated from the robots location to any goal location.\n * OpenCV and Eigen are required. \n */\nclass GridMap {\npublic:\n    /** The raw map data: -1:Unknown, 0: Free, 1:Obstacle */\n    Mat mapData;\n    /** The dialated map data: -1:Unknown, 0: Free, 1:Obstacle */\n    Mat dialatedMap;\n    /** OpenCV Structuring Element used for map dilation.  */\n    Mat strel;\n\n    #ifdef USE_CV_DISTANCE_TRANSFORM\n    /** The inverse of the dialated map, used for distance transform */\n    Mat invDialatedMap;\n    /** The distance transformed map as a 32bit float */\n    Mat distanceMap_32F;\n    /** The distance transformed map as char */\n    Mat distanceMap;\n    #endif\n\n    /** If wrapMap = true, the map can wrap around the edges such that the map can be used locally */\n    bool wrapMap = true;\n\n    /** The size of the map cells in square meters */\n    float cellSize = 1;\n    /** The with of the map in pixels */\n    unsigned long width = 0;\n    /** The height of the map in pixels */\n    unsigned long height = 0;\n    /** The size of the map in pixels, i.e. width*height */\n    unsigned long size = 0;\n\n    /** The position of x=0 in the map, specified in meters */\n    float xoffset = 0;\n    /** The position of y=0 in the map, specified in meters */\n    float yoffset = 0;\n\n    /** Flag that determines how cells are set to occupied in the map */\n    int fillMode = -1;\n    /** Flag that determines how cells are set to free in the map */\n    int clearMode = 0; \n\n    /** A* search algorithm */\n    Astar astar;        \n    /** The current cell position of the LaserScanner */\n    Point scanPosCell;\n\n    /** Construct an uninitialized GridMap object */\n    GridMap() { }\n    /** Construct an initialized GridMap object */\n    GridMap(float widthInMeters, float heightInMeters, float cellSize) {\n        this->resize(widthInMeters, heightInMeters, cellSize);\n    }\n\n    /** Resize the and all the related data structures */\n    void resize(float widthInMeters, float heightInMeters, float cellSize){\n        this->cellSize = cellSize;\n        this->height = ceil(heightInMeters/cellSize);\n        this->width  = ceil(widthInMeters/cellSize);\n        this->size = width * height;\n        this->setOffset(widthInMeters/2.0,heightInMeters/2.0);\n        mapData.create(height,width,CV_8SC1);\n        dialatedMap.create(height,width,CV_8SC1);\n        #ifdef USE_CV_DISTANCE_TRANSFORM\n        invDialatedMap.create(height,width,CV_8SC1);\n        distanceMap_32F.create(height,width,CV_32F);\n        distanceMap.create(height,width,CV_8SC1);\n        #endif \n        astar.resize(height, width);\n        astar.wrapMap = wrapMap;\n        this->clear();\n    }\n\n    /** Clear the map */\n    void clear(){\n        mapData.setTo(-1);\n        dialatedMap.setTo(0);\n        #ifdef USE_CV_DISTANCE_TRANSFORM\n        distanceMap.setTo(0);\n        #endif\n        astar.clearAll();\n    }\n    \n    /** Return the width of the map in meters, i.e. width*cellSize */\n    float widthInMeters() {\n        return width*cellSize;\n    }\n    /** Return the height of the map in meters, i.e. height*cellSize */\n    float heightInMeters() {\n        return height*cellSize;\n    }\n\n    /** Set the position of (x=0,y=0) in the map, specified in meters */\n    void setOffset(float xoffset, float yoffset){\n        this->xoffset = xoffset;\n        this->yoffset = yoffset;\n    }\n\n    /** If wrapMap is enabled the map is wrapped around the edges. This allows the map to be used in a more local sence. */\n    void setWrapMap(bool wrapMap){\n        this->wrapMap = wrapMap;\n        astar.wrapMap = wrapMap;\n    }\n\n    /** Make Structuring Element for Map dilation - Dilates as circle by default */\n    void makeStrel(float width, int dialation_type = MORPH_ELLIPSE){\n        int dilationSize = round(0.5*(width-cellSize)/cellSize);\n        cout << \"dilationSize=\" << dilationSize << endl;\n        strel = getStructuringElement( \n            dialation_type,\n            Size( 2*dilationSize+1, 2*dilationSize+1 ),\n            Point( dilationSize, dilationSize ) );\n    }\n\n    /** An implementation of Bresenham's line algorithm, see http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm */\n    vector<Point> bresenhamPoints(int x0, int y0, int x1, int y1){\n        Point point;\n        vector<Point> points;\n        int ystep = -1;\n\n        bool steep=abs(y1-y0)>abs(x1-x0);\n\n        if(steep){ // slope more than 1\n            int tempx0=x0; x0 = y0; y0 = tempx0; // Swapping\n            int tempx1=x1; x1 = y1; y1 = tempx1; // Swapping\n        }\n        if(x0>x1){ // line goes to the left\n            int tempx0=x0; x0=x1; x1=tempx0; // Swapping\n            int tempy0=y0; y0=y1; y1=tempy0; // Swapping\n        }\n\n        int deltaX = x1-x0;\n        int deltaY = abs(y1-y0);\n        int N = deltaX+1;\n        float error=-N/2;\n\n        int x=x0;\n        int y=y0;\n\n        if(y0<y1) ystep=1;\n\n        for(int i=0; i<N; i++){\n            if(steep){\n                point.x = y;\n                point.y = x;\n            } else {\n                point.x = x;\n                point.y = y;\n            }\n            x++;\n            error=error+deltaY;\n            if(error >= 0){\n                y=y+ystep;\n                error=error-deltaX;\n            }\n            points.push_back(point);\n        }   \n        return points;\n    }\n    \n    /** Round towards zero */\n    int fix(float val){\n        if(val > 0) return floor(val);\n        if(val < 0) return ceil(val);\n        return val;\n    }\n\n    /** Convert a point from world coordinates to map cell coordinates */\n    inline Point worldToCell(float x, float y){\n        int& rows = mapData.rows;\n        x = x+xoffset;\n        y = y+yoffset;\n        Point cell;\n        cell.x = x/cellSize;\n        cell.y = rows - floor(y/cellSize + 1);\n        return cell;\n    }\n\n    /** Convert a point from world coordinates to map cell coordinates */\n    inline Point worldToCell(Point2f world){\n        return worldToCell(world.x,world.y);\n    }\n\n    /** Convert a point from map cell coordinates to world coordinates */\n    inline Point2f cellToWorld(int x, int y){\n        Point2f world;\n        // Translate from map coordinates to world coordinates (center of cell)\n        world.x =  (x+0.5) * cellSize - xoffset;\n        world.y =  (mapData.rows-y-0.5) * cellSize - yoffset;\n        return world;\n    }\n\n    /** Convert a point from map cell coordinates to world coordinates */\n    inline Point2f cellToWorld(Point cell){\n        return cellToWorld(cell.x,cell.y);\n    }\n\n    /** wrap a point around the edges of the map. */\n    inline Point wrap(Point cell){\n        // Wrapping the map\n        while(cell.x < 0)               cell.x += mapData.cols;\n        while(cell.x >= mapData.cols)   cell.x -= mapData.cols;\n        while(cell.y < 0)               cell.y += mapData.rows;    \n        while(cell.y >= mapData.rows)   cell.y -= mapData.rows;\n        return cell;\n    }\n\n    /** wrap an x-coordinate around the edges of the map. If wrapMap is false this is a no-operation. */\n    inline int wx(int x){\n        if(wrapMap){ // Wrapping the map\n            while(x < 0)                x += mapData.cols;\n            while(x >= mapData.cols)    x -= mapData.cols;\n        }   \n        return x;\n    }\n    /** wrap an y-coordinate around the edges of the map. If wrapMap is false this is a no-operation. */\n    inline int wy(int y){\n        if(wrapMap){ // Wrapping the map\n            while(y < 0)                y += mapData.rows;    \n            while(y >= mapData.rows)    y -= mapData.rows;\n        }\n        return y;\n    } \n\n    /** Reset a MapNode in the Astar instance and set its (x,y) and type this is needed for wrapMap to work */\n    inline void resetMapNode(int x, int y, char value){\n        MapNode*node = astar.mapAt(x,y);\n        if(node != NULL){\n            node->x = x;\n            node->y = y;\n            node->clear(value);\n        }\n    }\n\n    /** Set a cell to a new value (nodetype) */\n    void setCell(int const& x, int const& y, char const& value, int const& mode){\n        int rows = mapData.rows;\n        int cols = mapData.cols;\n        int xm = wx(x);\n        int ym = wy(y);\n\n        if((0 <= xm && xm < cols) && (0 <= ym && ym < rows)){\n            resetMapNode(x,y,value);\n            mapData.at<char>(ym,xm) = value;\n\n            int xm1=wx(xm-1); int xp1=wx(xm+1); int ym1=wy(ym-1); int yp1=wy(ym+1);\n            if(value > 0 && mode == -1){\n                if(0 <= xm1   && mapData.at<char>(ym,xm1)<0){  mapData.at<char>(ym,xm1) = value; resetMapNode(x-1,y,value);}\n                if(xp1 < cols && mapData.at<char>(ym,xp1)<0){  mapData.at<char>(ym,xp1) = value; resetMapNode(x+1,y,value);}\n                if(0 <= ym1   && mapData.at<char>(ym1,xm)<0){  mapData.at<char>(ym1,xm) = value; resetMapNode(x,y-1,value);}\n                if(yp1 < rows && mapData.at<char>(yp1,xm)<0){  mapData.at<char>(yp1,xm) = value; resetMapNode(x,y+1,value);}\n                if(0 <= xm1   && 0 <= ym1   && mapData.at<char>(ym1,xm1)<0){ mapData.at<char>(ym1,xm1)=value; resetMapNode(x-1,y-1,value);}\n                if(0 <= xm1   && yp1 < rows && mapData.at<char>(yp1,xm1)<0){ mapData.at<char>(yp1,xm1)=value; resetMapNode(x-1,y+1,value);}\n                if(xp1 < cols && 0 <= ym-1  && mapData.at<char>(ym1,xp1)<0){ mapData.at<char>(ym1,xp1)=value; resetMapNode(x+1,y-1,value);}\n                if(xp1 < cols && yp1 < rows && mapData.at<char>(yp1,xp1)<0){ mapData.at<char>(yp1,xp1)=value; resetMapNode(x+1,y+1,value);}\n            }\n            \n            if(mode > 0){\n                xm1=wx(xm-1); xp1=wx(xm+1); ym1=wy(ym-1); yp1=wy(ym+1);\n                if(0 <= xm1){    mapData.at<char>(ym,xm1) = value; resetMapNode(x-1,y,value);}\n                if(xp1 < cols){  mapData.at<char>(ym,xp1) = value; resetMapNode(x+1,y,value);}\n                if(0 <= ym1){    mapData.at<char>(ym1,xm) = value; resetMapNode(x,y-1,value);}\n                if(yp1 < rows){  mapData.at<char>(yp1,xm) = value; resetMapNode(x,y+1,value);}\n            }\n            if(mode > 1){\n                if(0 <= xm1 && 0 <= ym1){    mapData.at<char>(ym1,xm1)=value;  resetMapNode(x-1,y-1,value);}\n                if(0 <= xm1 && yp1 < rows){  mapData.at<char>(yp1,xm1)=value;  resetMapNode(x-1,y+1,value);}\n                if(xp1 < cols && 0 <= ym1){  mapData.at<char>(ym1,xp1)=value;  resetMapNode(x+1,y-1,value);}\n                if(xp1 < cols && yp1 < rows){mapData.at<char>(yp1,xp1)=value;  resetMapNode(x+1,y+1,value);}\n            }\n            // cout << \"SetCell (\" << x << \",\" << y << \") = \" << int(value) << \",mode=\" << mode << endl;\n        }\n    }\n\n    /** Set cells along a line from (x1,y1) to (x2,y2) to a new value (nodetype) */\n    void setLine(int x1, int y1, int x2, int y2, int value, int mode=0){\n        vector<Point> pointsToSet = bresenhamPoints(x1, y1, x2, y2);\n        for(uint i=0; i<pointsToSet.size(); i++){\n            setCell(pointsToSet[i].x, pointsToSet[i].y, value, mode);\n        }\n    }\n\n    /** Set a square of cells with center point (x,y) to a new value (nodetype) */\n    void setSquare(int x, int y, int size, int value, int mode=0){\n        for(int iy=y-size; iy<=y+size; iy++){\n            for(int ix=x-size; ix<=x+size; ix++){\n                setCell(ix,iy,value, mode);\n                setCell(ix,iy,value, mode);\n            }\n        }\n    }\n\n    /** Return the value of the obstacle map at coordinate (x,y) */\n    inline char mapAt(int x, int y){\n        // Wrapping the map\n        if(wrapMap){\n            while(x < 0)                x += mapData.cols;\n            while(x >= mapData.cols)    x -= mapData.cols;\n            while(y < 0)                y += mapData.rows;    \n            while(y >= mapData.rows)    y -= mapData.rows;\n            return mapData.at<char>(y,x);\n        }\n\n        if((0 <= x && x < mapData.cols) && (0 <= y && y < mapData.rows)){\n            return mapData.at<char>(y,x);\n        }\n\n        return 0;\n    }\n\n    /** Return the value of the dialated map at coordinate (x,y) */\n    inline uchar dialatedMapAt(int x, int y){\n        int& rows = mapData.rows;\n        int& cols = mapData.cols;\n\n        // Wrapping the map\n        if(wrapMap){\n            while(x < 0)       x += cols;\n            while(x >= cols)   x -= cols;\n            while(y < 0)       y += rows;    \n            while(y >= rows)   y -= rows;\n            return dialatedMap.at<uchar>(y,x);\n        }\n\n        if((0 <= x && x < cols) && (0 <= y && y < rows)){\n            return dialatedMap.at<uchar>(y,x);\n        }\n\n        return 0xFF;\n    }\n\n    /** Return the value of the distance map at coordinate (x,y) */\n    #ifdef USE_CV_DISTANCE_TRANSFORM\n    inline uchar distanceMapAt(int x, int y){\n        int& rows = mapData.rows;\n        int& cols = mapData.cols;\n\n        // Wrapping the map\n        if(wrapMap){\n            while(x < 0)       x += cols;\n            while(x >= cols)   x -= cols;\n            while(y < 0)       y += rows;    \n            while(y >= rows)   y -= rows;\n            return distanceMap.at<uchar>(y,x);\n        }\n\n        if((0 <= x && x < cols) && (0 <= y && y < rows)){\n            return distanceMap.at<uchar>(y,x);\n        }\n\n        return 0;\n    }\n    #endif\n\n    /** Update the map. This should be called whenever new laser scan data is available. */\n    void updateMap(LaserScanner *scan, float maxLSDist){\n        // Cell Laser Scanner Position\n        scanPosCell = worldToCell(scan->pose(0),scan->pose(1));\n        // cout << \"scanPosCell = (\" << scanPosCell.x << \",\" << scanPosCell.y << \")\" << endl;\n\n        // Convert polar scan coordinates to laser cartesian coordinates\n        const MatrixXd& scanPolar = scan->getScanPolar();\n        // Convert laser cartesian coordinates to world cartesian coordinates\n        const MatrixXd& scanWorld = scan->getScanCartWorld();\n\n        vector<Point> pointsToFill;\n\n        // For each scanline i\n        for(int i=0; i<scan->nScanLines; i++){\n            // Convert scan from world cartesian coordinates to cell position\n            double const& rho = scanPolar(1,i);\n            if(rho < 0.020) continue;\n            Point cell = worldToCell(scanWorld(0,i), scanWorld(1,i));\n            \n            // Clear cells using bresenham's algorithm\n            // cout << \"ScanPosCell: (\" << scanPosCell.x << \",\" << scanPosCell.y << \"), cell: (\" << cell.x << \",\" << cell.y << \")\" << endl; \n            vector<Point> pointsToClear = bresenhamPoints(scanPosCell.x, scanPosCell.y, cell.x, cell.y);\n            // cout << \"Number of Points To Clear = \" << pointsToClear.size() << endl; \n\n            for(uint ii=0; ii<pointsToClear.size(); ii++){\n                setCell(pointsToClear[ii].x, pointsToClear[ii].y, 0, clearMode);\n            }\n\n            if(0.025 < rho && rho <= maxLSDist) pointsToFill.push_back(cell);\n        }\n\n        for(uint ii=0; ii<pointsToFill.size(); ii++){\n            setCell(pointsToFill[ii].x, pointsToFill[ii].y, 1, fillMode);\n        }\n\n        // cout << \"scanWorldCell:\\n\" << scanWorldCell.transpose() << endl;\n    }\n\n    /** Compute various transformations, i.e. dialatedMap and distanceMap */\n    void transform(){\n        dilate( mapData > 0, dialatedMap, strel);\n        \n        #ifdef USE_CV_DISTANCE_TRANSFORM\n        bitwise_not(dialatedMap, invDialatedMap);\n        distanceTransform(invDialatedMap, distanceMap_32F, CV_DIST_C, 5, CV_32F);\n        distanceMap_32F.convertTo(distanceMap,dialatedMap.type());        \n        #endif\n   }\n\n    /** Determine next waypoint defined as the furthest point seen by the laserscanner which is\n    not occupied in the dialated obstacle map. The search has a preference for scanlines with small angles, which is achieved by \n    iterating from the middle and out and only replacing if a longer distance is found. Thus, small angles are only used in case of ties.*/\n    Point determineNextWaypointCell(LaserScanner *scan, float maxLSDist=1e7){\n        float biggestDistanceInCells = 0;\n        Point mostDistantCell;\n        int nScanLinesHalf = scan->nScanLines/2;\n        \n        // Convert polar scan coordinates to laser cartesian coordinates\n        MatrixXd scanPolar = scan->getScanPolar();\n        \n        // Limit the range of the scan\n        if(maxLSDist < 1e6){\n            for(int i=0; i<scanPolar.cols(); i++){\n                double& rho = scanPolar(1,i);\n                if(rho > maxLSDist) rho = maxLSDist;\n            }\n        }\n        // Convert laser cartesian coordinates to world cartesian coordinates\n        MatrixXd scanWorld = scan->polarToWorld(scanPolar);\n\n        // Convert scan from world cartesian coordinates to cell position\n        for(int i=0; i<=nScanLinesHalf; i++){\n            int k;\n            for(int j=0; j<2; j++){\n                if(j==0)   k = nScanLinesHalf-i;\n                else       k = nScanLinesHalf+i;\n                if(k >= 0 && k < scan->nScanLines){\n                    double& rho = scanPolar(1,k);\n                    double& xs  = scanWorld(0,k);\n                    double& ys  = scanWorld(1,k);\n                    // float& phi = scanPolar(0,k);\n\n                    if(rho < biggestDistanceInCells*cellSize) continue;\n                    Point cell = worldToCell(xs, ys);\n                    // int obstdist = distanceMapAt(cell.x,cell.y);\n\n                    // Clear search for furthest available point using Bresenham's algorithm\n                    Point closestOccupiedPoint;\n                    vector<Point> points = bresenhamPoints(scanPosCell.x, scanPosCell.y, cell.x, cell.y);                    \n\n                    // cout << \"Diff:\" <<scanPosCell-cell << endl;\n                    for(uint ii=0; ii<points.size(); ii++){\n                        Point point = points[ii];\n                        float dx = point.x - scanPosCell.x;\n                        float dy = point.y - scanPosCell.y;\n                        float celldist = sqrt(dx*dx+dy*dy);\n                        if(celldist > biggestDistanceInCells && dialatedMapAt(point.x,point.y) == 0){\n                            biggestDistanceInCells = celldist;\n                            mostDistantCell = point;\n                        }\n                    }\n                }\n            }\n        }\n  \n        return mostDistantCell;\n    }\n\n    /** Determine next waypoint defined as the furthest point seen by the laserscanner, \n    not occupied in the dialated map, with preference for scanlines with small angles, achieved by \n    iterating from the middle and out and only replacing if a longer distance is found. */\n    inline Point2f determineNextWaypoint(LaserScanner *scan, float maxLSDist=1e8){\n        return cellToWorld(determineNextWaypointCell(scan));\n    }\n\n    /** Determine next waypoint defined as the furthest point seen by the laserscanner which is\n    not occupied in the dialated obstacle map. The search has a preference for scanlines with small angles, which is achieved by \n    iterating from the middle and out and only replacing if a longer distance is found. Thus, small angles are only used in case of ties.*/\n    Point determineNextWaypointCellB(LaserScanner *scan, float maxLSDist=1e4){\n        float biggestDistanceInCells = 0;\n        Point mostDistantCell;\n        int nScanLinesHalf = scan->nScanLines/2;\n        \n        // Convert polar scan coordinates to laser cartesian coordinates\n        MatrixXd scanPolar = scan->getScanPolar();\n        \n        // Limit the range of the scan\n        if(maxLSDist < 1e3){\n            for(int i=0; i<scanPolar.cols(); i++){\n                double& rho = scanPolar(1,i);\n                if(rho > maxLSDist) rho = maxLSDist;\n            }\n        }\n        // Convert laser cartesian coordinates to world cartesian coordinates\n        MatrixXd scanWorld = scan->polarToWorld(scanPolar);\n\n        // Convert scan from world cartesian coordinates to cell position\n        for(int i=0; i<=nScanLinesHalf; i++){\n            int k;\n            for(int j=0; j<2; j++){\n                if(j==0)   k = nScanLinesHalf-i;\n                else       k = nScanLinesHalf+i;\n                if(k >= 0 && k < scan->nScanLines){\n                    double& rho = scanPolar(1,k);\n                    double& xs  = scanWorld(0,k);\n                    double& ys  = scanWorld(1,k);\n                    // float& phi = scanPolar(0,k);\n\n                    if(rho <= biggestDistanceInCells*cellSize) continue;\n                    Point cell = worldToCell(xs, ys);\n                    // int obstdist = distanceMapAt(cell.x,cell.y);\n\n                    // Clear search for furthest available point using Bresenham's algorithm\n                    Point closestOccupiedPoint;\n                    vector<Point> points = bresenhamPoints(scanPosCell.x, scanPosCell.y, cell.x, cell.y);\n                    if(scanPosCell != points[0]) reverse(points.begin(), points.end());\n                    \n                    #if (0)\n                    cout << \"Scan:(\" << scanPosCell.x << \",\" << scanPosCell.y << \")\";\n                    for(int p=0; p<points.size(); p++){\n                    \tcout << \"->(\" << points[p].x << \",\" << points[p].y << \")\";\n                    }\n                    cout << endl;\n\t\t\t\t\t#endif\n\n                    // cout << \"Diff:\" <<scanPosCell-cell << endl;\n                    uint ii=1;\n                    while(ii<points.size()){\n                        Point point = points[ii];\n                        if(dialatedMapAt(point.x,point.y) != 0) break;\n                        float dx = point.x - scanPosCell.x;\n                        float dy = point.y - scanPosCell.y;\n                        float celldist = sqrt(dx*dx+dy*dy);\n                        if(celldist > biggestDistanceInCells){\n                            biggestDistanceInCells = celldist;\n                            mostDistantCell = point;\n                        }\n                        ii++;\n                    }\n                }\n            }\n        }\n  \n        return mostDistantCell;\n    }\n\n    /** Determine next waypoint defined as the furthest point seen by the laserscanner, \n    not occupied in the dialated map, with preference for scanlines with small angles, achieved by \n    iterating from the middle and out and only replacing if a longer distance is found. */\n    inline Point2f determineNextWaypointB(LaserScanner *scan, float maxLSDist=1e8){\n        return cellToWorld(determineNextWaypointCellB(scan));\n    }\n\n    /** This function will find the minimal cost path from the starting cell to the target cell. \n    The function uses the A* search algorithm with tie-breaker and an additional cost related to \n    the obstacle distance implemented as an obstacle repulsive potential. */\n    vector<MapNode *> findpath(int xStart, int yStart, int xTarget, int yTarget, unsigned long maxIter = 10000){\n        // vector<MapNode *> path;\n        astar.clear();\n        for (uint y = 0; y < mapData.rows; y++) {\n            for (uint x = 0; x < mapData.cols; x++) {\n                MapNode *node = astar.mapAt(x,y);\n                if(dialatedMapAt(x,y) > 0) node->type = NODE_TYPE_OBSTACLE;\n                else if(mapAt(x,y) == -1)  node->type = NODE_TYPE_UNKNOWN;\n                else node->type = NODE_TYPE_ZERO;\n\n                #ifdef USE_CV_DISTANCE_TRANSFORM\n                    node->obstdist = distanceMapAt(x,y);\n                #else\n                    node->obstdist = -1; // -1 means that the distance is still unknown, and thus it will be calculated by astar during node expansion.\n                #endif\n            }\n        }\n        return astar.findpath(xStart, yStart, xTarget, yTarget, maxIter);\n    }\n\n    /** Wrap a value into the [-pi,pi) range */\n    inline float wrapToPi(float angle){\n        float TWO_PI = 2*M_PI;\n        while(angle > M_PI)     angle -= TWO_PI;\n        while(angle <= -M_PI)   angle += TWO_PI;\n        return angle;\n    }\n    \n    /** Simplify the path by removing points along straight line segments, keeping only the corner points. */\n    inline vector<MapNode *> simplifyPath(vector<MapNode *> path){\n        const bool DEBUG = false;\n\n        vector<MapNode *> newpath;\n        path = astar.simplifyPath(path);\n        //return path;\n        \n        newpath.push_back(path.front());\n        for(int i=1; i<(path.size()-1); i++){\n            MapNode * P0 = path[i-1];\n            MapNode * P1 = path[i];\n            MapNode * P2 = path[i+1];\n            int dx01 = P1->x - P0->x;\n            int dy01 = P1->y - P0->y;\n            int dx12 = P2->x - P1->x;\n            int dy12 = P2->y - P1->y;\n            if(abs(dx12) == 1 && abs(dy12) == 1)  continue;\n            if(dx01 == dx12 && dy01 == dy12) continue;\n            newpath.push_back(P1);\n        }\n        newpath.push_back(path.back());\n\n        if(DEBUG){\n            cout << \"newpath2:--\";\n            for(int i=0; i<newpath.size(); i++){\n                cout << \"->(\" << newpath[i]->x << \",\" << newpath[i]->y << \")\";\n            }\n            cout << endl;\n        }\n        \n        return newpath;\n    }\n\n    /** Convert a path consisting of a vector of MapNode pointers to a vector of world coordinate waypoints */\n    vector<Point2f> pathToWorld(vector<MapNode *> const& path){\n        vector<Point2f> waypoints;\n        for(int i=0; i<path.size(); i++){\n            waypoints.push_back(cellToWorld(path[i]->x,path[i]->y));\n        }\n        \n        /*\n        cout << \"wayPoints:\";\n        for(int i=0; i<waypoints.size(); i++){\n            cout << \"->(\" << waypoints[i].x << \",\" << waypoints[i].y << \")\";\n        }\n        cout << endl;\n        */\n        return waypoints;\n    }\n\n    inline vector<Point2f> findpathAsWaypoints(int const&  xStart, int const& yStart, int const& xTarget, int const& yTarget){\n        return pathToWorld(simplifyPath(findpath(xStart, yStart, xTarget, yTarget)));\n    }\n\n};\n\n\n\n#endif\n\n", "meta": {"hexsha": "1419d7843d8caa78494920d52421b4d879d12aa6", "size": 38107, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/GridMap.hpp", "max_stars_repo_name": "HjalteBested/GridMap", "max_stars_repo_head_hexsha": "8af232989ebafbee6397e031fbcafc318dd70dfd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-06T04:43:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-06T04:43:15.000Z", "max_issues_repo_path": "src/GridMap.hpp", "max_issues_repo_name": "HjalteBested/GridMap", "max_issues_repo_head_hexsha": "8af232989ebafbee6397e031fbcafc318dd70dfd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GridMap.hpp", "max_forks_repo_name": "HjalteBested/GridMap", "max_forks_repo_head_hexsha": "8af232989ebafbee6397e031fbcafc318dd70dfd", "max_forks_repo_licenses": ["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.902617801, "max_line_length": 151, "alphanum_fraction": 0.5499514525, "num_tokens": 9637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.28048543763195605}}
{"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\n#include <cmath>\n#include <Eigen/Eigen>\n#include \"covariance.h\"\n\nnamespace snark{ \n\nsquared_exponential_covariance::squared_exponential_covariance( double length_scale\n                                                              , double signal_variance\n                                                              , double data_variance )\n    : signal_variance_( signal_variance )\n    , data_variance_( data_variance )\n    , factor_( -1.0 / ( 2.0 * std::sqrt( length_scale ) ) )\n    , self_covariance_( signal_variance + data_variance )\n{\n}\n\ndouble squared_exponential_covariance::covariance( const Eigen::VectorXd& v, const Eigen::VectorXd& w ) const\n{\n    const Eigen::VectorXd& diff = v - w;\n    return signal_variance_ * std::exp( factor_ * diff.dot( diff ) );\n}\n\ndouble squared_exponential_covariance::self_covariance() const { return self_covariance_; }\n\n} // namespace snark{ { namespace Robotics {\n", "meta": {"hexsha": "908858e31b9abcddfd63b420c88de00cff295209", "size": 2675, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math/gaussian_process/covariance.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": 63.0, "max_stars_repo_stars_event_min_datetime": "2015-01-14T14:38:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T09:56:03.000Z", "max_issues_repo_path": "math/gaussian_process/covariance.cpp", "max_issues_repo_name": "NEU-LC/snark", "max_issues_repo_head_hexsha": "db890f73f4c4bbe679405f3a607fd9ea373deb2c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 39.0, "max_issues_repo_issues_event_min_datetime": "2015-01-21T00:57:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-22T04:22:35.000Z", "max_forks_repo_path": "math/gaussian_process/covariance.cpp", "max_forks_repo_name": "NEU-LC/snark", "max_forks_repo_head_hexsha": "db890f73f4c4bbe679405f3a607fd9ea373deb2c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 36.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T04:17:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T17:13:35.000Z", "avg_line_length": 47.7678571429, "max_line_length": 109, "alphanum_fraction": 0.7256074766, "num_tokens": 555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244837, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2804747213261158}}
{"text": "/** \n * @file upsc.cpp\n * @brief implementation of hdm upscaling\n * @author Alina Yapparova\n * @version \n * @date 2012-20-02\n */\n\n#include <iomanip>\n#include <iostream>\n\n#include <list>\n#include <map>\n\n#include \"bs_kernel.h\"\n#include \"bs_misc.h\"\n\n#include \"upsc.h\"\n#include \"conf.h\"\n\n\nusing namespace boost;\n\n#ifdef BSPY_EXPORTING_PLUGIN\n\n#include <boost/python.hpp>\nusing namespace boost::python;\n\n#endif //BSPY_EXPORTING_PLUGIN\n\n\nnamespace blue_sky\n{\n\n  upsc::upsc (bs_type_ctor_param) \n    {\n    \n      sp_prop = BS_KERNEL.create_object (\"prop\");\n      if (!sp_prop)\n        {\n          bs_throw_exception (\"Type (prop) not refractered\");\n        }\n      \n    }\n  upsc::upsc (const upsc& rhs) \n        : bs_refcounter ()\n    {\n      *this = rhs;\n    }\n  void\n  upsc::init_prop ()\n    {\n\n    }\n\nspv_float upsc::upscale_grid_zcolumn ( t_long Nx, t_long Ny, t_long Nz, spv_float zcorn_, spv_uint layers_ )\n{   \n    t_int k1, k2, new_k;\n    t_long new_Nz, new_zcorn_size, layer_size;\n    v_uint& layers = *layers_;\n    v_uint::iterator lit, lit_next;\n    v_float& zcorn = *zcorn_;\n    \n    new_Nz = layers.size(); \n    new_zcorn_size = 8*Nx*Ny*new_Nz; \n    layer_size = 4*Nx*Ny; \n    \n    spv_float new_zcorn = BS_KERNEL.create_object(v_float::bs_type());\n    new_zcorn->resize(new_zcorn_size);\n    \n    new_k = 0;\n\n    for (lit=layers.begin();lit!=layers.end();lit++)\n        {\n            k1 = (*lit);\n            lit_next = lit + 1;\n            if (lit_next!=layers.end())\n                k2 = (*lit_next);\n            else\n                k2 = Nz;\n            std::copy ( &zcorn[2*k1*layer_size], &zcorn[(2*k1+1)*layer_size], &(*new_zcorn)[(new_k++)*layer_size] );\n            std::copy ( &zcorn[(2*k2-1)*layer_size], &zcorn[2*k2*layer_size], &(*new_zcorn)[(new_k++)*layer_size] );\n        }\n\n   return new_zcorn; \n}\n\nbp::tuple upsc::upscale_grid ( t_long Nx, t_long Ny, t_long Nz, t_long ux, t_long uy, \n                               spv_float coord_, spv_float zcorn_, spv_uint layers_ )\n{   \n    t_int i, j, n, k1, k2, k, ind;\n    t_long new_Nx, new_Ny, new_Nz, new_coord_size, new_zcorn_size, layer_size;\n    v_uint& layers = *layers_;\n    v_uint::iterator lit, lit_next;\n    v_float& coord = *coord_;\n    v_float& zcorn = *zcorn_;\n    \n    new_Nx = ceil(double(Nx)/double(ux));\n    new_Ny = ceil(double(Ny)/double(uy));\n    new_Nz = layers.size(); \n    new_coord_size = 6*(new_Nx+1)*(new_Ny+1);\n    new_zcorn_size = 8*new_Nx*new_Ny*new_Nz; \n    layer_size = 4*Nx*Ny;\n    \n    spv_float new_coord = BS_KERNEL.create_object(v_float::bs_type());\n    new_coord->resize(new_coord_size);\n    spv_float new_zcorn = BS_KERNEL.create_object(v_float::bs_type());\n    new_zcorn->resize(new_zcorn_size);\n\n    n = 0;\n    for (j=0; j<new_Ny; j++)\n        {\n            for (i=0; i<new_Nx; i++)\n                {\n                    std::copy ( &coord[6*(uy*j*(Nx+1)+ux*i)], &coord[6*(uy*j*(Nx+1)+ux*i+1)], &(*new_coord)[n] );\n                    n += 6;\n                }\n            std::copy ( &coord[6*(uy*j*(Nx+1)+Nx)], &coord[6*(uy*j*(Nx+1)+Nx+1)], &(*new_coord)[n] );\n            n += 6;\n        }\n    for (i=0; i<new_Nx; i++)\n        {\n            std::copy ( &coord[6*(Ny*(Nx+1)+ux*i)], &coord[6*(Ny*(Nx+1)+ux*i+1)], &(*new_coord)[n] );\n            n += 6;\n        }\n    std::copy ( &coord[6*(Ny*(Nx+1)+Nx)], &coord[6*(Ny*(Nx+1)+Nx+1)], &(*new_coord)[n] );\n\n    k = 0;\n    for (lit=layers.begin();lit!=layers.end();lit++)\n        {\n            k1 = (*lit);\n            lit_next = lit + 1;\n            if (lit_next!=layers.end())\n                k2 = (*lit_next);\n            else\n                k2 = Nz;\n\n            // tops\n            for (j=0; j<new_Ny-1; j++)\n                {\n                    for (i=0; i<new_Nx-1; i++)\n                        {\n                            ind = 2*k1*layer_size + 4*uy*j*Nx;\n                            (*new_zcorn)[(k++)] = zcorn[ind + 2*ux*i];\n                            (*new_zcorn)[(k++)] = zcorn[ind + 2*ux*(i+1) - 1];\n                        }\n                    ind = 2*k1*layer_size + 4*uy*j*Nx;\n                    (*new_zcorn)[(k++)] = zcorn[ind + 2*ux*(new_Nx-1)];\n                    (*new_zcorn)[(k++)] = zcorn[ind + 2*Nx - 1];\n                    \n                    for (i=0; i<new_Nx-1; i++)\n                        {\n                            ind = 2*k1*layer_size + (2*uy*(j+1)-1)*2*Nx;\n                            (*new_zcorn)[(k++)] = zcorn[ind + 2*ux*i];\n                            (*new_zcorn)[(k++)] = zcorn[ind + 2*ux*(i+1) - 1];\n                        }\n                    ind = 2*k1*layer_size + (2*uy*(j+1)-1)*2*Nx;\n                    (*new_zcorn)[(k++)] = zcorn[ind + 2*ux*(new_Nx-1)];\n                    (*new_zcorn)[(k++)] = zcorn[ind + 2*Nx - 1];\n                }\n            \n            for (i=0; i<new_Nx-1; i++)\n                {\n                    ind = 2*k1*layer_size + 4*uy*(new_Ny-1)*Nx;\n                    (*new_zcorn)[(k++)] = zcorn[ind + 2*ux*i];\n                    (*new_zcorn)[(k++)] = zcorn[ind + 2*ux*(i+1) - 1];\n                }\n            ind = 2*k1*layer_size + 4*uy*(new_Ny-1)*Nx;\n            (*new_zcorn)[(k++)] = zcorn[ind + 2*ux*(new_Nx-1)];\n            (*new_zcorn)[(k++)] = zcorn[ind + 2*Nx - 1];\n            \n            for (i=0; i<new_Nx-1; i++)\n                {\n                    ind = 2*k1*layer_size + (2*Ny-1)*2*Nx;\n                    (*new_zcorn)[(k++)] = zcorn[ind + 2*ux*i];\n                    (*new_zcorn)[(k++)] = zcorn[ind + 2*ux*(i+1) - 1];\n                }\n            ind = 2*k1*layer_size + (2*Ny-1)*2*Nx;\n            (*new_zcorn)[(k++)] = zcorn[ind + 2*ux*(new_Nx - 1)];\n            (*new_zcorn)[(k++)] = zcorn[ind + 2*Nx - 1];\n            \n            // bottoms\n            for (j=0; j<new_Ny-1; j++)\n                {\n                    for (i=0; i<new_Nx-1; i++)\n                        {\n                            ind = (2*k2-1)*layer_size + 4*uy*j*Nx;\n                            (*new_zcorn)[(k++)] = zcorn[ind + 2*ux*i];\n                            (*new_zcorn)[(k++)] = zcorn[ind + 2*ux*(i+1) - 1];\n                        }\n                    ind = (2*k2-1)*layer_size + 4*uy*j*Nx;\n                    (*new_zcorn)[(k++)] = zcorn[ind + 2*ux*(new_Nx-1)];\n                    (*new_zcorn)[(k++)] = zcorn[ind + 2*Nx - 1];\n                    \n                    for (i=0; i<new_Nx-1; i++)\n                        {\n                            ind = (2*k2-1)*layer_size + (2*uy*(j+1)-1)*2*Nx;\n                            (*new_zcorn)[(k++)] = zcorn[ind + 2*ux*i];\n                            (*new_zcorn)[(k++)] = zcorn[ind + 2*ux*(i+1) - 1];\n                        }\n                    ind = (2*k2-1)*layer_size + (2*uy*(j+1)-1)*2*Nx;\n                    (*new_zcorn)[(k++)] = zcorn[ind + 2*ux*(new_Nx-1)];\n                    (*new_zcorn)[(k++)] = zcorn[ind + 2*Nx - 1];\n                }\n            \n            for (i=0; i<new_Nx-1; i++)\n                {\n                    ind = (2*k2-1)*layer_size + 4*uy*(new_Ny-1)*Nx;\n                    (*new_zcorn)[(k++)] = zcorn[ind + 2*ux*i];\n                    (*new_zcorn)[(k++)] = zcorn[ind + 2*ux*(i+1) - 1];\n                }\n            ind = (2*k2-1)*layer_size + 4*uy*(new_Ny-1)*Nx;\n            (*new_zcorn)[(k++)] = zcorn[ind + 2*ux*(new_Nx-1)];\n            (*new_zcorn)[(k++)] = zcorn[ind + 2*Nx - 1];\n            \n            for (i=0; i<new_Nx-1; i++)\n                {\n                    ind = (2*k2-1)*layer_size + (2*Ny-1)*2*Nx;\n                    (*new_zcorn)[(k++)] = zcorn[ind + 2*ux*i];\n                    (*new_zcorn)[(k++)] = zcorn[ind + 2*ux*(i+1) - 1];\n                }\n            ind = (2*k2-1)*layer_size + (2*Ny-1)*2*Nx;\n            (*new_zcorn)[(k++)] = zcorn[ind + 2*ux*(new_Nx - 1)];\n            (*new_zcorn)[(k++)] = zcorn[ind + 2*Nx - 1];\n        }\n   return bp::make_tuple (new_coord, new_zcorn); \n}\n\nt_double upsc::calc_sum_dW ( t_long k1, t_long k2, t_long Nx, t_long Ny, \n                                          spv_float vol_, spv_float ntg_, spv_float poro_, spv_float permx_ )\n{\n    v_float& vol = *vol_;\n    v_float& ntg = *ntg_;\n    v_float& poro = *poro_;\n    v_float& permx = *permx_;\n    \n    t_long i, j, n, z1, z2, layer_size;\n    t_long index[2];\n    t_double p[2];\n    t_double dW, sum_dW = 0, sum_vol;\n    \n    layer_size = Nx*Ny;\n    z1 = k1*layer_size;\n    z2 = k2*layer_size;\n    \n\n    for (j = 0; j < Ny; j++)\n      {\n        for (i = 0; i < Nx; i++)\n          {\n            index[0] = i + j * Nx + z1;\n            index[1] = i + j * Nx + z2;\n            \n            for (n = 0; n < 2; n++)\n                {\n                    if (poro[index[n]  != 0])\n                        p[n] = ntg[index[n]] * permx[index[n]] / poro[index[n]];\n                    else\n                        p[n] = 0;\n                }\n            \n            sum_vol = (vol[index[0]] + vol[index[1]]);\n            if (sum_vol != 0)\n                dW = (p[0] - p[1]) * (p[0] - p[1]) * vol[index[0]] * vol[index[1]] / sum_vol;\n            else\n                dW = 0;\n            sum_dW += dW;\n          }\n      }\n    return sum_dW;\n}\n\nspv_float upsc::upscale_saturation_cube (t_long Nx, t_long Ny, t_long Nz, t_long Nz_upsc,\n                                         spv_uint layers_, spv_float vol_, spv_float ntg_, spv_float poro_, spv_float sat_)\n{\n    t_int i, j, k, n, k1, k2, ind, z;\n    t_long layer_size, new_cube_size;\n    t_double sum_sat_poro_ntg_vol, sum_poro_ntg_vol;\n\n    v_uint& layers = *layers_;\n    v_float& vol = *vol_;\n    v_float& ntg = *ntg_;\n    v_float& poro = *poro_;\n    v_float& sat = *sat_;\n    \n    spv_float new_sat = BS_KERNEL.create_object(v_float::bs_type());\n    \n    // important: XYZ order\n    // index <-- (i, j, k)\n    // index = i + j*Nx + k*Nx*Ny;\n    \n    layer_size = Nx * Ny;\n\n    for (n = 0; n < Nz_upsc; ++n)\n        {\n            k1 = layers[n];\n\n            if (n == Nz_upsc-1)\n                k2 = Nz;\n            else\n                k2 = layers[n+1];\n\n            if (k1 != k2)\n            for (j = 0; j < Ny; ++j)\n                for (i = 0; i < Nx; ++i)\n                    {\n                        sum_sat_poro_ntg_vol = 0;\n                        sum_poro_ntg_vol = 0;\n\n                        for (k = k1; k < k2; ++k)\n                            {\n                                z = k*layer_size;\n                                ind = i + j * Nx + z;\n                                sum_sat_poro_ntg_vol += sat[ind]*poro[ind]*ntg[ind]*vol[ind];\n                                sum_poro_ntg_vol += poro[ind]*ntg[ind]*vol[ind];\n                            }\n                        ind = i + j * Nx + k1 * layer_size;\n                        if (sum_sat_poro_ntg_vol != 0)\n                            sat[ind] = sum_sat_poro_ntg_vol/sum_poro_ntg_vol;\n                        else\n                            sat[ind] = 0;\n                    }\n\n        }\n    \n    new_cube_size = Nz_upsc*layer_size;\n    new_sat->resize(new_cube_size);\n\n    i = 0;\n    for ( k = 0; k < Nz_upsc; ++k)\n        {\n            std::copy ( &sat[k*layer_size], &sat[(k+1)*layer_size], &(*new_sat)[i*layer_size] );\n            i++;\n        }\n\n    return new_sat;\n}\n\nspv_float upsc::upscale_sat_cube_xy (t_long Nx, t_long Ny, t_long ux, t_long uy, t_long Nz, \n                                     spv_uint layers_, spv_float vol_, spv_float ntg_, spv_float poro_, spv_float sat_)\n{\n    t_int i, j, ii, jj, k, new_k, n, k1, k2, index, ind, new_ind;\n    t_long new_Nx, new_Ny, new_Nz;\n    t_long layer_size, new_layer_size, new_cube_size;\n    t_double sum_sat_poro_ntg_vol, sum_poro_ntg_vol;\n\n    v_uint& layers = *layers_;\n    v_float& vol = *vol_;\n    v_float& ntg = *ntg_;\n    v_float& poro = *poro_;\n    v_float& sat = *sat_;\n    \n    t_int rx, ry;\n    rx = Nx % ux;\n    ry = Ny % uy;\n    new_Nx = ceil(double(Nx)/double(ux));\n    new_Ny = ceil(double(Ny)/double(uy));\n    new_Nz = layers.size(); \n    \n    spv_float new_sat = BS_KERNEL.create_object(v_float::bs_type());\n    new_cube_size = new_Nx*new_Ny*new_Nz;\n    new_sat->resize(new_cube_size);\n    \n    // important: XYZ order\n    // index <-- (i, j, k)\n    // index = i + j*Nx + k*Nx*Ny;\n    \n    layer_size = Nx * Ny;\n    new_layer_size = new_Nx * new_Ny;\n\n    new_k = 0;\n    for (n = 0; n < new_Nz; ++n)\n      {\n        k1 = layers[n];\n\n        if (n == new_Nz-1)\n            k2 = Nz;\n        else\n            k2 = layers[n+1];\n\n        for (j = 0; j < new_Ny-1; ++j)\n          {\n            for (i = 0; i < new_Nx-1; ++i)\n              {\n                index  = ux*i + uy*j*Nx + k1*layer_size;\n                new_ind = i + j*new_Nx + new_k*new_layer_size;\n                \n                sum_sat_poro_ntg_vol = 0;\n                sum_poro_ntg_vol = 0;\n        \n                for (k = 0; k < (k2-k1); ++k)\n                  {\n                    for (jj = 0; jj < uy; jj++)\n                      {\n                        for (ii = 0; ii < ux; ii++)\n                          {\n                            ind = index + ii + jj*Nx + k*layer_size;\n                            sum_sat_poro_ntg_vol += sat[ind]*poro[ind]*ntg[ind]*vol[ind];\n                            sum_poro_ntg_vol += poro[ind]*ntg[ind]*vol[ind];\n                          }\n                      }\n                  }\n\n                if (sum_sat_poro_ntg_vol != 0)\n                    (*new_sat)[new_ind] = sum_sat_poro_ntg_vol/sum_poro_ntg_vol;\n                else\n                    (*new_sat)[new_ind] = 0;\n              }\n\n            index  = ux*(new_Nx-1) + uy*j*Nx + k1*layer_size;\n            new_ind = new_Nx-1 + j*new_Nx + new_k*new_layer_size;\n            \n            sum_sat_poro_ntg_vol = 0;\n            sum_poro_ntg_vol = 0;\n    \n            for (k = 0; k < (k2-k1); ++k)\n              {\n                for (jj = 0; jj < uy; jj++)\n                  {\n                    for (ii = 0; ii < rx; ii++)\n                      {\n                        ind = index + ii + jj*Nx + k*layer_size;\n                        sum_sat_poro_ntg_vol += sat[ind]*poro[ind]*ntg[ind]*vol[ind];\n                        sum_poro_ntg_vol += poro[ind]*ntg[ind]*vol[ind];\n                      }\n                  }\n              }\n            \n            if (sum_sat_poro_ntg_vol != 0)\n                (*new_sat)[new_ind] = sum_sat_poro_ntg_vol/sum_poro_ntg_vol;\n            else\n                (*new_sat)[new_ind] = 0;\n          }\n        \n        for (i = 0; i < new_Nx-1; ++i)\n          {\n            index  = ux*i + uy*(new_Ny-1)*Nx + k1*layer_size;\n            new_ind = i + (new_Ny-1)*new_Nx + new_k*new_layer_size;\n            \n            sum_sat_poro_ntg_vol = 0;\n            sum_poro_ntg_vol = 0;\n    \n            for (k = 0; k < (k2-k1); ++k)\n              {\n                for (jj = 0; jj < ry; jj++)\n                  {\n                    for (ii = 0; ii < ux; ii++)\n                      {\n                        ind = index + ii + jj*Nx + k*layer_size;\n                        sum_sat_poro_ntg_vol += sat[ind]*poro[ind]*ntg[ind]*vol[ind];\n                        sum_poro_ntg_vol += poro[ind]*ntg[ind]*vol[ind];\n                      }\n                  }\n              }\n            if (sum_sat_poro_ntg_vol != 0)\n                (*new_sat)[new_ind] = sum_sat_poro_ntg_vol/sum_poro_ntg_vol;\n            else\n                (*new_sat)[new_ind] = 0;\n          }\n\n        index  = ux*(new_Nx-1) + uy*(new_Ny-1)*Nx + k1*layer_size;\n        new_ind = new_Nx-1 + (new_Ny-1)*new_Nx + new_k*new_layer_size;\n        \n        sum_sat_poro_ntg_vol = 0;\n        sum_poro_ntg_vol = 0;\n\n        for (k = 0; k < (k2-k1); ++k)\n          {\n            for (jj = 0; jj < ry; jj++)\n              {\n                for (ii = 0; ii < rx; ii++)\n                  {\n                    ind = index + ii + jj*Nx + k*layer_size;\n                    sum_sat_poro_ntg_vol += sat[ind]*poro[ind]*ntg[ind]*vol[ind];\n                    sum_poro_ntg_vol += poro[ind]*ntg[ind]*vol[ind];\n                  }\n              }\n          }  \n        if (sum_sat_poro_ntg_vol != 0)\n            (*new_sat)[new_ind] = sum_sat_poro_ntg_vol/sum_poro_ntg_vol;\n        else\n            (*new_sat)[new_ind] = 0;\n\n        new_k ++;\n      }\n\n    return new_sat;\n}\n\nint upsc::upscale_cubes ( t_long k1, t_long k2, t_long Nx, t_long Ny, \n                          spv_float vol_, spv_float ntg_, spv_float poro_, spv_float permx_ )\n{\n    v_float& vol = *vol_;\n    v_float& ntg = *ntg_;\n    v_float& poro = *poro_;\n    v_float& permx = *permx_;\n    \n    t_long i, j, index[2], z1, z2, layer_size;\n    t_double vol_sum, ntg_vol_sum, poro_ntg_vol_sum, permx_ntg_vol_sum;\n\n    layer_size = Nx*Ny;\n    z1 = k1*layer_size;\n    z2 = k2*layer_size;\n\n    for (j = 0;j < Ny; j++)\n      {\n        for (i = 0;i < Nx; i++)\n          {\n            index[0] = i + j * Nx + z1;\n            index[1] = i + j * Nx + z2;\n\n            vol_sum = vol[index[0]] + vol[index[1]];\n            ntg_vol_sum = ntg[index[0]]*vol[index[0]] +  ntg[index[1]]*vol[index[1]];\n            poro_ntg_vol_sum = poro[index[0]]*ntg[index[0]]*vol[index[0]] + poro[index[1]]*ntg[index[1]]*vol[index[1]];\n            permx_ntg_vol_sum = permx[index[0]]*ntg[index[0]]*vol[index[0]] + permx[index[1]]*ntg[index[1]]*vol[index[1]];\n            \n            vol[index[0]] = vol_sum;\n            if (vol_sum != 0)\n                ntg[index[0]] = ntg_vol_sum/vol_sum;\n            else\n                ntg[index[0]] = 0;\n            \n            if (ntg_vol_sum != 0)\n                {\n                    poro[index[0]] = poro_ntg_vol_sum/ntg_vol_sum;\n                    permx[index[0]] = permx_ntg_vol_sum/ntg_vol_sum;\n                }\n            else\n                {\n                    poro[index[0]] = 0;\n                    permx[index[0]] = 0;\n                }\n            \n          }\n      }\n\n    return 0;\n}\n\nbp::tuple upsc::upscale_cubes_xy ( t_long Nx, t_long Ny, t_long Nz, t_long ux, t_long uy,\n                                   spv_float vol_, spv_float ntg_, spv_float poro_)\n{\n    v_float& vol = *vol_;\n    v_float& ntg = *ntg_;\n    v_float& poro = *poro_;\n    \n    spv_float new_vol = BS_KERNEL.create_object(v_float::bs_type());\n    spv_float new_ntg = BS_KERNEL.create_object(v_float::bs_type());\n    spv_float new_poro = BS_KERNEL.create_object(v_float::bs_type());\n\n    t_long new_cube_size, new_Nx, new_Ny;\n    t_int rx, ry;\n    new_Nx = ceil(double(Nx)/double(ux));\n    new_Ny = ceil(double(Ny)/double(uy));\n    rx = Nx % ux;\n    ry = Ny % uy;\n    new_cube_size = new_Nx*new_Ny*Nz;\n    \n    new_vol->resize(new_cube_size);\n    new_ntg->resize(new_cube_size);\n    new_poro->resize(new_cube_size);\n    \n    t_long i, j, ii, jj, k, layer_size, new_layer_size;\n    t_long ind, index, new_ind;\n    t_double vol_sum, ntg_vol_sum, poro_ntg_vol_sum;\n    layer_size = Nx*Ny;\n    new_layer_size = new_Nx*new_Ny;\n\n    for (k = 0; k < Nz; k++)\n      {\n        for (j = 0; j < new_Ny-1; j++)\n          {\n            for (i = 0; i < new_Nx-1; i++)\n              {\n                ind  = ux*i + uy*j*Nx + k*layer_size;\n                new_ind = i + j*new_Nx + k*new_layer_size;\n\n                vol_sum = 0;\n                ntg_vol_sum = 0;\n                poro_ntg_vol_sum = 0; \n\n                for (jj = 0; jj < uy; jj++)\n                  {\n                    for (ii = 0; ii < ux; ii++)\n                      {\n                        index = ind + ii;\n                        vol_sum += vol[index];\n                        ntg_vol_sum += ntg[index]*vol[index];\n                        poro_ntg_vol_sum += poro[index]*ntg[index]*vol[index];\n                      }\n                    ind  += Nx;\n                  }\n                (*new_vol)[new_ind] = vol_sum;\n                \n                if (vol_sum != 0)\n                    (*new_ntg)[new_ind] = ntg_vol_sum/vol_sum;\n                else\n                    (*new_ntg)[new_ind] = 0;\n                \n                if (ntg_vol_sum != 0)\n                  {\n                    (*new_poro)[new_ind] = poro_ntg_vol_sum/ntg_vol_sum;\n                  }\n                else\n                  {\n                    (*new_poro)[new_ind] = 0;\n                  }\n              }\n            \n            ind  = ux*(new_Nx-1) + uy*j*Nx + k*layer_size;\n            new_ind = new_Nx-1 + j*new_Nx + k*new_layer_size;\n\n            vol_sum = 0;\n            ntg_vol_sum = 0;\n            poro_ntg_vol_sum = 0; \n\n            for (jj = 0; jj < uy; jj++)\n              {\n                for (ii = 0; ii < rx; ii++)\n                  {\n                    index = ind + ii;\n                    vol_sum += vol[index];\n                    ntg_vol_sum += ntg[index]*vol[index];\n                    poro_ntg_vol_sum += poro[index]*ntg[index]*vol[index];\n                  }\n                ind  += Nx;\n              }\n            (*new_vol)[new_ind] = vol_sum;\n            \n            if (vol_sum != 0)\n                (*new_ntg)[new_ind] = ntg_vol_sum/vol_sum;\n            else\n                (*new_ntg)[new_ind] = 0;\n            \n            if (ntg_vol_sum != 0)\n              {\n                (*new_poro)[new_ind] = poro_ntg_vol_sum/ntg_vol_sum;\n              }\n            else\n              {\n                (*new_poro)[new_ind] = 0;\n              }\n          }\n        \n        for (i = 0; i < new_Nx-1; i++)\n          {\n            ind  = ux*i + uy*(new_Ny-1)*Nx + k*layer_size;\n            new_ind = i + (new_Ny-1)*new_Nx + k*new_layer_size;\n\n            vol_sum = 0;\n            ntg_vol_sum = 0;\n            poro_ntg_vol_sum = 0; \n\n            for (jj = 0; jj < ry; jj++)\n              {\n                for (ii = 0; ii < ux; ii++)\n                  {\n                    index = ind + ii;\n                    vol_sum += vol[index];\n                    ntg_vol_sum += ntg[index]*vol[index];\n                    poro_ntg_vol_sum += poro[index]*ntg[index]*vol[index];\n                  }\n                ind  += Nx;\n              }\n            (*new_vol)[new_ind] = vol_sum;\n            \n            if (vol_sum != 0)\n                (*new_ntg)[new_ind] = ntg_vol_sum/vol_sum;\n            else\n                (*new_ntg)[new_ind] = 0;\n            \n            if (ntg_vol_sum != 0)\n              {\n                (*new_poro)[new_ind] = poro_ntg_vol_sum/ntg_vol_sum;\n              }\n            else\n              {\n                (*new_poro)[new_ind] = 0;\n              }\n          }\n        \n        ind  = ux*(new_Nx-1) + uy*(new_Ny-1)*Nx + k*layer_size;\n        new_ind = new_Nx-1 + (new_Ny-1)*new_Nx + k*new_layer_size;\n\n        vol_sum = 0;\n        ntg_vol_sum = 0;\n        poro_ntg_vol_sum = 0; \n\n        for (jj = 0; jj < ry; jj++)\n          {\n            for (ii = 0; ii < rx; ii++)\n              {\n                index = ind + ii;\n                vol_sum += vol[index];\n                ntg_vol_sum += ntg[index]*vol[index];\n                poro_ntg_vol_sum += poro[index]*ntg[index]*vol[index];\n              }\n            ind  += Nx;\n          }\n        (*new_vol)[new_ind] = vol_sum;\n        \n        if (vol_sum != 0)\n            (*new_ntg)[new_ind] = ntg_vol_sum/vol_sum;\n        else\n            (*new_ntg)[new_ind] = 0;\n        \n        if (ntg_vol_sum != 0)\n          {\n            (*new_poro)[new_ind] = poro_ntg_vol_sum/ntg_vol_sum;\n          }\n        else\n          {\n            (*new_poro)[new_ind] = 0;\n          }\n      }\n\n    return bp::make_tuple(new_ntg, new_poro);\n}\n\nt_double upsc::solve_pressure_zcolumn (t_long Ny, t_long Nz, t_long i, t_long j, t_long k1, t_long k2, BS_SP(rs_mesh_iface) sp_mesh_iface)\n{\n    t_long size, k, n, index, ext_ind[2];\n    plane_t plane[2];\n    mesh_element3d element[2];\n    fpoint3d_t center[2];\n\n    t_double tz;\n    t_double p_left = 1, p_right = 0;\n    t_double dl, dL, dp, dP, K;\n\n    spv_double p = BS_KERNEL.create_object(v_double::bs_type());\n    spv_double rhs = BS_KERNEL.create_object(v_double::bs_type());\n    spv_float tran_vals = BS_KERNEL.create_object(v_float::bs_type());\n    sp_dens_mtx_t tran = BS_KERNEL.create_object(\"dens_matrix\");\n    sp_blu_solver_t solver = BS_KERNEL.create_object(\"blu_solver\");\n\n    size = k2 - k1 +1;\n    \n    p->resize(size);\n    rhs->resize(size);\n\n    tran->init(size, size, 60);\n    tran_vals = tran->get_values();\n    \n    v_float& A = *tran_vals;  \n    v_double& b = *rhs;\n\n    smart_ptr<bs_mesh_grdecl> sp_mesh(sp_mesh_iface, bs_static_cast());\n    mesh_grdecl mesh = sp_mesh->get_wrapped();\n    \n    // important: ZYX order\n    // direction dir along_dim1->X (along_dim2->Y, along_dim3->Z) \n\n    // k = k1 //////////////////////////////////////////////////////////////////////////////////////////\n    ext_ind[0] = k1 + j * Nz + i * Ny * Nz;\n    mesh.calc_element (i, j, k1, element[0]);\n    center[0] = element[0].get_center();\n    element[0].get_plane (z_axis_minus, plane[0]);\n    tz = mesh.calc_tran_boundary (ext_ind[0], plane[0], center[0], along_dim3);\n\n    // FIXME\n    b[0] = -tz*p_left;\n    A[0] -= tz;          \n    \n    // k1 < k < k2 /////////////////////////////////////////////////////////////////////////////////////\n    for (k = k1; k < k2; ++k)\n        {\n            ext_ind[0] = k + j * Nz + i * Ny * Nz;\n            mesh.calc_element (i, j, k, element[0]);\n            center[0] = element[0].get_center();\n            \n            ext_ind[1] = ext_ind[0] + 1;\n            mesh.calc_element (i, j, k + 1, element[1]);\n            element[0].get_plane (z_axis_plus, plane[0]);\n            \n            //element[1].get_plane (z_axis_minus, plane[1]);\n            \n            center[1] = element[1].get_center();\n            // don't pass plane[1] to calc_tran\n            // because zcolumn cells are always fully adjacent\n            //tz = mesh.calc_tran(ext_ind[0], ext_ind[1], plane[0], center[0], center[1], along_dim3, &plane[1]);\n            tz = mesh.calc_tran(ext_ind[0], ext_ind[1], plane[0], center[0], center[1], along_dim3);\n            \n            n = k - k1; \n            // Z-\n            index = n + (n+1)*size;\n            A[index] = tz;\n            index += 1;\n            A[index] -= tz;\n            \n            // Z+\n            index = (n+1) + n*size;\n            A[index] = tz;\n            index -= 1;\n            A[index] -= tz;\n        }\n    \n    // k = k2 //////////////////////////////////////////////////////////////////////////////////////////\n    ext_ind[0] = k2 + j * Nz + i * Ny * Nz;\n    mesh.calc_element (i, j, k2, element[0]);\n    center[0] = element[0].get_center();\n    element[0].get_plane (z_axis_plus, plane[0]);\n    tz = mesh.calc_tran_boundary (ext_ind[0], plane[0], center[0], along_dim3);\n    \n    b[size-1] = -tz*p_right;\n    index  =  size*size - 1;\n    A[index] -= tz;          \n\n    // solve system, find pressure\n    solver->setup (tran);\n    solver->solve (tran, rhs, p);\n\n    dp = (p_left - (*p)[0]);\n    dP = ( (p_left + (*p)[0])/2 - ((*p)[size-1] + p_right)/2 );\n    \n    mesh.calc_element (i, j, k1, element[0]);\n    element[0].get_plane (z_axis_minus, plane[0]);\n    center[1] = element[0].get_center ();\n    get_plane_center (plane[0],  center[0]);\n    \n    dl = get_len(center[0], center[1])*2;\n        \n    mesh.calc_element (i, j, k2, element[1]);\n    element[1].get_plane (z_axis_plus, plane[1]);\n    get_plane_center (plane[1],  center[1]);\n    \n    dL = get_len(center[0], center[1]);\n    \n    if (dl < 10*EPSILON)\n        {\n            dl = 2*EPSILON;\n            dL += EPSILON;\n        }\n\n    K = (dp/dl)/(dP/dL);\n\n    return K;\n}\n\nt_double upsc::solve_pressure_block (t_int direction, t_long Ny, t_long Nz, t_long i1, t_long i2, t_long j1, t_long j2, t_long k1, t_long k2, spv_float ntg_, BS_SP(rs_mesh_iface) sp_mesh_iface)\n{\n    const t_double cdarcy = 0.008640;\n    t_long size, i, j, k, ind[2], ext_ind[2], index, ny, nz;\n    plane_t plane[2];\n    mesh_element3d element[2];\n    fpoint3d_t center[2];\n\n    t_double tz, ty, tx;\n    t_double p_left = 1, p_right = 0;\n    t_double dL, dP, S, K, Q;\n\n    spv_double p = BS_KERNEL.create_object(v_double::bs_type());\n    spv_double rhs = BS_KERNEL.create_object(v_double::bs_type());\n    spv_float tran_vals = BS_KERNEL.create_object(v_float::bs_type());\n    sp_dens_mtx_t tran = BS_KERNEL.create_object(\"dens_matrix\");\n    sp_blu_solver_t solver = BS_KERNEL.create_object(\"blu_solver\");\n\n    size = (i2-i1)*(j2-j1)*(k2-k1);\n    ny = j2 - j1;\n    nz = k2 - k1;\n    \n    p->resize(size);\n    rhs->resize(size);\n\n    tran->init(size, size, 60);\n    tran_vals = tran->get_values();\n    \n    v_float& A = *tran_vals;\n    v_double& b = *rhs;\n    v_float& ntg = *ntg_;\n\n    smart_ptr<bs_mesh_grdecl> sp_mesh(sp_mesh_iface, bs_static_cast());\n    mesh_grdecl mesh = sp_mesh->get_wrapped();\n    \n    // important: ZYX order\n\n    // direction dir along_dim1->X (2->Y, 3->Z) \n \n    for (i = i1; i < i2; ++i)\n        for (j = j1; j < j2; ++j)\n            for (k = k1; k < k2; ++k)\n              {\n                ext_ind[0] = k + j * Nz + i * Ny * Nz;\n                ind[0] = (k-k1) + (j-j1)*nz + (i-i1)*ny*nz;\n                mesh.calc_element (i, j, k, element[0]);\n                center[0] = element[0].get_center();\n                \n                // TRANZ /////////////////////////////////////////////////////////////////////////////////////////////\n                if (k!=k2-1)\n                    {\n                        ext_ind[1] = ext_ind[0] + 1;\n                        ind[1] = ind[0] + 1;\n                        mesh.calc_element (i, j, k + 1, element[1]);\n                        element[0].get_plane (z_axis_plus, plane[0]);\n                        element[1].get_plane (z_axis_minus, plane[1]);\n                        center[1] = element[1].get_center();\n                        tz = mesh.calc_tran(ext_ind[0], ext_ind[1], plane[0], center[0], center[1], along_dim3, &plane[1]);\n                        \n                        // Z-\n                        index = ind[0] + ind[1]*size;\n                        A[index] = tz;\n                        index += 1;\n                        A[index] -= tz;\n                        \n                        // Z+\n                        index = ind[1] + ind[0]*size;\n                        A[index] = tz;\n                        index -= 1;\n                        A[index] -= tz;\n                    }\n                \n                // TRANY /////////////////////////////////////////////////////////////////////////////////////////////\n                if (j != j2-1)\n                    {\n                        ext_ind[1] = ext_ind[0] + Nz;\n                        ind[1] = ind[0] + nz;\n                        mesh.calc_element (i, j + 1, k, element[1]);\n                        element[0].get_plane (y_axis_plus, plane[0]);\n                        element[1].get_plane (y_axis_minus, plane[1]);\n                        center[1] = element[1].get_center();\n                        ty = mesh.calc_tran(ext_ind[0], ext_ind[1], plane[0], center[0], center[1], along_dim2, &plane[1]);          \n                        \n                        // Y- \n                        index = ind[0] + ind[1]*size;\n                        A[index] = ty;\n                        index += nz;\n                        A[index] -= ty;\n                        \n                        // Y+\n                        index = ind[1] + ind[0]*size;\n                        A[index] = ty;\n                        index -= nz;\n                        A[index] -= ty;\n                    }\n\n                // TRANX /////////////////////////////////////////////////////////////////////////////////////////////\n                if (i != i2-1)\n                    {\n                        ext_ind[1] = ext_ind[0] + Ny * Nz;\n                        ind[1] = ind[0] + ny*nz;\n                        mesh.calc_element (i + 1, j, k, element[1]);\n                        element[0].get_plane (x_axis_plus, plane[0]);\n                        element[1].get_plane (x_axis_minus, plane[1]);\n                        center[1] = element[1].get_center();\n                        tx = mesh.calc_tran(ext_ind[0], ext_ind[1], plane[0], center[0], center[1], along_dim1, &plane[1]);\n                        \n                        // X-\n                        index = ind[0] + ind[1]*size;\n                        A[index] = tx;\n                        index += ny*nz;\n                        A[index] -= tx;\n                                                \n                        // X+\n                        index = ind[1] + ind[0]*size;\n                        A[index] = tx;\n                        index -= ny*nz;\n                        A[index] -= tx;\n\n                    }\n               // Boundary Conditions /////////////////////////////////////////////////////////////////////////////////\n               if (direction == 1)\n                 {\n                    if (i == i1)\n                        {\n                           element[0].get_plane (x_axis_minus, plane[0]);\n                           tx = mesh.calc_tran_boundary (ext_ind[0], plane[0], center[0], along_dim1);\n                           b[ind[0]] = -tx*p_left;\n                           index  =  ind[0] + ind[0]*size;\n                           A[index] -= tx;          \n                        }\n                    if (i == i2-1)\n                        {  \n                           element[0].get_plane (x_axis_plus, plane[0]);\n                           tx = mesh.calc_tran_boundary (ext_ind[0], plane[0], center[0], along_dim1);\n                           b[ind[0]] = -tx*p_right;\n                           index  =  ind[0] + ind[0]*size;\n                           A[index] -= tx;          \n                        }\n                 }\n               else if (direction == 2)\n                 {\n                    if (j == j1)\n                        {\n                           element[0].get_plane (y_axis_minus, plane[0]);\n                           ty = mesh.calc_tran_boundary (ext_ind[0], plane[0], center[0], along_dim2);\n                           b[ind[0]] = -ty*p_left;\n                           index  =  ind[0] + ind[0]*size;\n                           A[index] -= ty;          \n                        }\n                    if (j == j2-1)\n                        {  \n                           element[0].get_plane (y_axis_plus, plane[0]);\n                           ty = mesh.calc_tran_boundary (ext_ind[0], plane[0], center[0], along_dim2);\n                           b[ind[0]] = -ty*p_right;\n                           index  =  ind[0] + ind[0]*size;\n                           A[index] -= ty;          \n                        }\n                 }\n               else if (direction == 3)\n                 {\n                    if (k == k1)\n                        {\n                           element[0].get_plane (z_axis_minus, plane[0]);\n                           tz = mesh.calc_tran_boundary (ext_ind[0], plane[0], center[0], along_dim3);\n                           b[ind[0]] = -tz*p_left;\n                           index  =  ind[0] + ind[0]*size;\n                           A[index] -= tz;          \n                        }\n                    if (k == k2-1)\n                        {  \n                           element[0].get_plane (z_axis_plus, plane[0]);\n                           tz = mesh.calc_tran_boundary (ext_ind[0], plane[0], center[0], along_dim3);\n                           b[ind[0]] = -tz*p_right;\n                           index  =  ind[0] + ind[0]*size;\n                           A[index] -= tz;          \n                        }\n                 }\n\n              }\n\n    solver->setup (tran);\n    solver->solve (tran, rhs, p);\n\n    // Q=sum(q) q=T*dp\n    // Q=k*S*dP/dL\n    // for permx and permy don't forget NTG! \n    \n    Q = 0;\n    S = 0;\n    \n    if (direction == 1)\n      {\n        i = i1;\n        for (j = j1; j < j2; ++j)\n            for (k = k1; k < k2; ++k)\n              {\n                mesh.calc_element (i, j, k, element[0]);\n                element[0].get_plane (x_axis_minus, plane[0]);\n                center[0] = element[0].get_center ();\n                get_plane_center (plane[0],  center[1]);\n                \n                index = k + j * Nz + i * Ny * Nz;\n                S += ntg[index]*find_area_of_side (plane[0][0], plane[0][1], plane[0][2], plane[0][3]);\n                tx = mesh.calc_tran_boundary (index, plane[0], center[0], along_dim1);\n\n                index = (k-k1) + (j-j1)*nz + (i-i1)*ny*nz;\n                dP = (p_left - (*p)[index]);\n                Q += tx*dP;\n              }\n      }\n    else if (direction == 2)\n      {\n        j = j1;\n        for (i = i1; i < i2; ++i)\n            for (k = k1; k < k2; ++k)\n              {\n                mesh.calc_element (i, j, k, element[0]);\n                element[0].get_plane (y_axis_minus, plane[0]);\n                center[0] = element[0].get_center ();\n                get_plane_center (plane[0],  center[1]);\n                \n                index = k + j * Nz + i * Ny * Nz;\n                S += ntg[index]*find_area_of_side (plane[0][0], plane[0][1], plane[0][2], plane[0][3]);\n                ty = mesh.calc_tran_boundary (index, plane[0], center[0], along_dim2);\n                \n                index = (k-k1) + (j-j1)*nz + (i-i1)*ny*nz;\n                dP = (p_left - (*p)[index]);\n                Q += ty*dP;\n              }\n      }\n    else if (direction == 3)\n      {\n        k = k1;\n        for (i = i1; i < i2; ++i)\n            for (j = j1; j < j2; ++j)\n              {\n                mesh.calc_element (i, j, k, element[0]);\n                element[0].get_plane (z_axis_minus, plane[0]);\n                center[0] = element[0].get_center ();\n                get_plane_center (plane[0],  center[1]);\n                \n                index = k + j * Nz + i * Ny * Nz;\n                S += find_area_of_side (plane[0][0], plane[0][1], plane[0][2], plane[0][3]);\n                tz = mesh.calc_tran_boundary (index, plane[0], center[0], along_dim3);\n                \n                index = (k-k1) + (j-j1)*nz + (i-i1)*ny*nz;\n                dP = (p_left - (*p)[index]);\n                Q += tz*dP;\n              }\n      }\n\n    i = i1; j = j1; k = k1;\n    if (direction == 1)\n      {\n        mesh.calc_element (i, j, k, element[0]);\n        element[0].get_plane (x_axis_minus, plane[0]);\n        get_plane_center (plane[0],  center[0]);\n        \n        index = (k-k1) + (j-j1)*nz + (i-i1)*ny*nz;\n        dP = (p_left + (*p)[index])/2;\n        \n        i = i2-1;\n        mesh.calc_element (i, j, k, element[1]);\n        element[1].get_plane (x_axis_plus, plane[1]);\n        get_plane_center (plane[1],  center[1]);\n        \n        index = (k-k1) + (j-j1)*nz + (i-i1)*ny*nz;\n        dP -= ((*p)[index] + p_right)/2;\n      }\n    else if (direction == 2)\n      {\n        mesh.calc_element (i, j, k, element[0]);\n        element[0].get_plane (y_axis_minus, plane[0]);\n        get_plane_center (plane[0],  center[0]);\n        \n        index = (k-k1) + (j-j1)*nz + (i-i1)*ny*nz;\n        dP = (p_left + (*p)[index])/2;\n        \n        j = j2-1; \n        mesh.calc_element (i, j, k, element[1]);\n        element[1].get_plane (y_axis_plus, plane[1]);\n        get_plane_center (plane[1],  center[1]);\n        \n        index = (k-k1) + (j-j1)*nz + (i-i1)*ny*nz;\n        dP -= ((*p)[index] + p_right)/2;\n      }\n    else if (direction == 3)\n      {\n        mesh.calc_element (i, j, k, element[0]);\n        element[0].get_plane (z_axis_minus, plane[0]);\n        get_plane_center (plane[0],  center[0]);\n        \n        index = (k-k1) + (j-j1)*nz + (i-i1)*ny*nz;\n        dP = (p_left + (*p)[index])/2;\n        \n        k = k2-1;\n        mesh.calc_element (i, j, k, element[1]);\n        element[1].get_plane (z_axis_plus, plane[1]);\n        get_plane_center (plane[1],  center[1]);\n        \n        index = (k-k1) + (j-j1)*nz + (i-i1)*ny*nz;\n        dP -= ((*p)[index] + p_right)/2;\n      }\n\n    dL = get_len(center[0], center[1]);\n    if (S < EPSILON || dP < EPSILON)\n        K = 0;\n    else\n        K = Q*dL/(cdarcy*S*dP);\n    \n    return K;\n\n}\n\nspv_float upsc::upscale_permz_zcolumn (t_long Nx, t_long Ny, t_long Nz, spv_uint layers_, spv_float permz_, spv_uint actnum_, BS_SP(rs_mesh_iface) sp_mesh_iface)\n  {\n    t_int i, j, k, n, Nz_upsc, k1, k2, z1, ind, index;\n    t_long layer_size, new_cube_size;\n\n    t_double upsc_factor;\n    \n    spv_float new_permz = BS_KERNEL.create_object(v_float::bs_type());\n    v_float& permz = *permz_;\n    v_uint& actnum = *actnum_;\n    v_uint& layers = *layers_;\n    \n    smart_ptr<bs_mesh_grdecl> sp_mesh(sp_mesh_iface, bs_static_cast());\n    mesh_grdecl mesh = sp_mesh->get_wrapped();\n    \n    Nz_upsc = layers.size();\n    layer_size = Nx*Ny;\n    \n    // important: XYZ order\n    // index <-- (i, j, k)\n    // index = i + j*Nx + k*Nx*Ny;\n    \n    for (n = 0; n < Nz_upsc; ++n)\n        {\n            k1 = layers[n];\n\n            if (n == Nz_upsc-1)\n                k2 = Nz - 1;\n            else\n                k2 = layers[n+1] - 1;\n\n            if (k1 != k2)\n                {\n                    z1 = k1*layer_size;\n                    for (j = 0; j < Ny; ++j)\n                        for (i = 0; i < Nx; ++i)\n                            {\n                                index = i + j * Nx + z1;\n\n                                // in general case call function that finds isolated bodies\n                                for (k = k1; k <= k2; k++)\n                                    {\n                                        ind = i + j * Nx + k * Nx * Ny;\n                                        if (!actnum [ind])\n                                            {\n                                                permz[index] = 0;\n                                                break;\n                                            }\n                                    }\n                                if (permz[index])\n                                    {\n                                        upsc_factor = solve_pressure_zcolumn (Ny, Nz, i, j, k1, k2, sp_mesh_iface);\n                                        permz[index] *= upsc_factor;\n                                    }\n\n                            }\n                }   \n        }  \n\n    new_cube_size = Nz_upsc*layer_size;\n    new_permz->resize(new_cube_size);\n    \n    i = 0;\n    for ( n = 0; n < Nz_upsc; n++)\n        {\n            k = layers[n];\n            std::copy ( &permz[k*layer_size], &permz[(k+1)*layer_size], &(*new_permz)[i*layer_size] );\n            i++;\n        }\n\n    return new_permz;\n  }\n\nspv_float upsc::upscale_perm_block (t_int dir, t_long Nx, t_long Ny, t_long ux, t_long uy, t_long Nz, spv_uint layers_, spv_float ntg_, spv_uint actnum_, BS_SP(rs_mesh_iface) sp_mesh_iface)\n  {\n    t_int i, j, n, i1, i2, j1, j2, k1, k2, new_k, new_ind;\n    t_long new_Nx, new_Ny, new_Nz;\n    t_long new_layer_size, new_cube_size;\n\n    spv_float new_perm = BS_KERNEL.create_object(v_float::bs_type());\n    v_uint& actnum = *actnum_;\n    v_uint& layers = *layers_;\n    \n    smart_ptr<bs_mesh_grdecl> sp_mesh(sp_mesh_iface, bs_static_cast());\n    mesh_grdecl mesh = sp_mesh->get_wrapped();\n    \n    t_int rx, ry;\n    rx = Nx % ux;\n    ry = Ny % uy;\n    new_Nx = ceil(double(Nx)/double(ux));\n    new_Ny = ceil(double(Ny)/double(uy));\n    new_Nz = layers.size(); \n    new_layer_size = new_Nx * new_Ny;\n    new_cube_size = new_Nx*new_Ny*new_Nz;\n    new_perm->resize(new_cube_size);\n    \n    // important: XYZ order\n    // index <-- (i, j, k)\n    // index = i + j*Nx + k*Nx*Ny;\n    \n    // FIXME: call function that finds isolated bodies\n\n    new_k = 0;\n    for (n = 0; n < new_Nz; ++n)\n      {\n        k1 = layers[n];\n\n        if (n == new_Nz-1)\n            k2 = Nz;\n        else\n            k2 = layers[n+1] - 1;\n\n        for (j = 0; j < new_Ny-1; ++j)\n          {\n            for (i = 0; i < new_Nx-1; ++i)\n              {\n                i1 = ux*i;\n                i2 = i1 + ux;\n                j1 = uy*j;\n                j2 = j1 + uy;\n                new_ind = i + j*new_Nx + new_k*new_layer_size;\n                (*new_perm)[new_ind] = solve_pressure_block (dir, Ny, Nz, i1, i2, j1, j2, k1, k2, ntg_, sp_mesh_iface);\n              }\n            \n            if (rx)\n              {\n                i1 = ux*(new_Nx-1);\n                i2 = i1 + rx;\n                j1 = uy*j;\n                j2 = j1 + uy;\n                new_ind = new_Nx-1 + j*new_Nx + new_k*new_layer_size;\n                (*new_perm)[new_ind] = solve_pressure_block (dir, Ny, Nz, i1, i2, j1, j2, k1, k2, ntg_, sp_mesh_iface);\n              }\n          }\n           \n        if (ry)\n          {\n            for (i = 0; i < new_Nx-1; ++i)\n              {\n                i1 = ux*i;\n                i2 = i1 + ux;\n                j1 = uy*(new_Ny-1);\n                j2 = j1 + ry;\n                new_ind = i + (new_Ny-1)*new_Nx + new_k*new_layer_size;\n                (*new_perm)[new_ind] = solve_pressure_block (dir, Ny, Nz, i1, i2, j1, j2, k1, k2, ntg_, sp_mesh_iface);\n\n              }\n\n            if (rx)\n              {\n                i1 = ux*(new_Nx-1);\n                i2 = i1 + rx;\n                j1 = uy*(new_Ny-1);\n                j2 = j1 + ry;\n                new_ind = new_Nx-1 + (new_Ny-1)*new_Nx + new_k*new_layer_size;\n                (*new_perm)[new_ind] = solve_pressure_block (dir, Ny, Nz, i1, i2, j1, j2, k1, k2, ntg_, sp_mesh_iface);\n              }\n          }\n\n        new_k ++;\n      }\n    \n    return new_perm;\n  }\n\n\n  bp::tuple\n  upsc::king_method (t_long Nx, t_long Ny, t_long Nz, t_long Nz_upsc,\n                            spv_float vol_, spv_float ntg_, spv_float poro_, spv_float permx_)\n  {\n    t_int i, k, n, k0, k1, k2, k3;\n    t_long layer_size, new_cube_size;\n    t_float sum_dW;\n    \n    v_float& vol = *vol_;\n    v_float& ntg = *ntg_;\n    v_float& poro = *poro_;\n    v_float& permx = *permx_;\n\n    std::list <t_int> layers;\n    std::list <t_int>::iterator lit, tmp_it;\n\n    layer_mmap_t sum_dW2layer;\n    layer_mmap_it_t mit;\n    layer_map_t layer2mmap_it;\n    layer_map_it_t lmit;\n    \n    spv_float new_vol = BS_KERNEL.create_object(v_float::bs_type());\n    spv_float new_ntg = BS_KERNEL.create_object(v_float::bs_type());\n    spv_float new_poro = BS_KERNEL.create_object(v_float::bs_type());\n    spv_float new_permx = BS_KERNEL.create_object(v_float::bs_type());\n    spv_uint layers_v = BS_KERNEL.create_object(v_uint::bs_type());\n\n    layer_size = Nx*Ny;\n\n    for (i = 0;i < Nz; i++)\n        layers.push_back(i);\n\n    // important: XYZ order\n    // index <-- (i, j, k)\n    // index = i + j*Nx + k*Nx*Ny;\n\n    // calculate sum_dW for every pair of adjacent layers\n    // and store it in sumdw2layer multimap (sum_dW -> k) sorted in increasing order\n    // and in layer2mmapit map (k -> mmap_it) \n    for (k = 0; k < Nz-1; k++)\n    {\n        sum_dW = calc_sum_dW ( k, k+1,  Nx, Ny, vol_, ntg_, poro_, permx_ );\n        mit = sum_dW2layer.insert(std::make_pair(sum_dW, k));\n        layer2mmap_it[k] = mit;\n    }\n\n    k0 = 0;\n    k3 = Nz-1;\n\n    for (n=Nz;n>Nz_upsc;n--)\n    {\n        // [k0, k1, k2, k3] - indices of 4 consequentive layers\n        // [k1, k2]  - indices of 2 layers to be united\n        k1 = (*sum_dW2layer.begin()).second;\n        lit = find(layers.begin(), layers.end(), k1);\n        tmp_it = lit;\n        tmp_it ++;\n        k2 = (*tmp_it);\n\n        // upscaling of cubes\n        upscale_cubes (k1, k2, Nx, Ny, vol_, ntg_, poro_, permx_ );\n        \n        // erase sum_dW for (k1; k2) pair of layers\n        mit = layer2mmap_it[k1];\n        sum_dW2layer.erase(mit);\n        layer2mmap_it.erase(k1);\n        \n        // if k2 isn't the last layer\n        if (k2 != layers.back())\n            {\n                // erase sum_dW for (k2; k3) pair of layers\n                mit = layer2mmap_it[k2];\n                sum_dW2layer.erase(mit);\n                layer2mmap_it.erase(k2);\n                \n                tmp_it ++;\n                k3 = (*tmp_it);\n                tmp_it --;\n\n                // add sum_dW for (k1; k3) pair of layers\n                sum_dW = calc_sum_dW ( k1, k3, Nx, Ny, vol_, ntg_, poro_, permx_ );\n                mit = sum_dW2layer.insert ( std::make_pair(sum_dW, k1) );\n                layer2mmap_it[k1] = mit;\n            }\n        \n        // delete k2 layer\n        layers.erase(tmp_it);\n\n        // if k1 isn't the first layer\n        if (k1 != 0)\n            {\n                tmp_it = lit;\n                tmp_it --;\n                k0 = (*tmp_it);\n                \n                // erase sum_dW for (k0; k1) pair of layers\n                mit = layer2mmap_it[k0];\n                sum_dW2layer.erase(mit);\n                layer2mmap_it.erase(k0);\n\n                // add sum_dW for (k0; k1) pair of layers\n                sum_dW = calc_sum_dW ( k0, k1, Nx, Ny, vol_, ntg_, poro_, permx_ );\n                mit = sum_dW2layer.insert ( std::make_pair(sum_dW, k0) );\n                layer2mmap_it[k0] = mit;\n            }\n\n    }\n    \n    new_cube_size = Nz_upsc*layer_size;\n\n    new_vol->resize(new_cube_size);\n    new_ntg->resize(new_cube_size);\n    new_poro->resize(new_cube_size);\n    new_permx->resize(new_cube_size);\n    layers_v->resize(Nz_upsc);\n\n    i = 0;\n    for (lit=layers.begin();lit!=layers.end();lit++)\n        {\n            k = (*lit);\n            std::copy ( &vol[k*layer_size], &vol[(k+1)*layer_size], &(*new_vol)[i*layer_size] );\n            std::copy ( &ntg[k*layer_size], &ntg[(k+1)*layer_size], &(*new_ntg)[i*layer_size] );\n            std::copy ( &poro[k*layer_size], &poro[(k+1)*layer_size], &(*new_poro)[i*layer_size] );\n            std::copy ( &permx[k*layer_size], &permx[(k+1)*layer_size], &(*new_permx)[i*layer_size] );\n            i++;\n        }\n\n    std::copy ( layers.begin(), layers.end(), &(*layers_v)[0] );\n    \n    return bp::make_tuple (layers_v, new_vol, new_ntg, new_poro, new_permx) ;\n  }\n\n#ifdef BSPY_EXPORTING_PLUGIN\n  std::string \n  upsc::py_str () const\n    {\n      std::stringstream s;\n      s << wstr2str (sp_prop->py_str ()) << \"\\n\";\n      return s.str ();\n    }\n#endif //BSPY_EXPORTING_PLUGIN\n/////////////////////////////////BS Register\n/////////////////////////////////Stuff//////////////////////////\n\n  BLUE_SKY_TYPE_STD_CREATE (upsc);\n  BLUE_SKY_TYPE_STD_COPY (upsc);\n\n  BLUE_SKY_TYPE_IMPL(upsc,  upsc_iface, \"upsc\", \"upscaling\", \"hdm upscaling\");\n\n}  // blue_sky namespace\n", "meta": {"hexsha": "33e97d0359bfc1c0324982143a1c561c5d2c6096", "size": 50102, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bs_mesh/src/upsc.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_mesh/src/upsc.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_mesh/src/upsc.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": 34.0598232495, "max_line_length": 193, "alphanum_fraction": 0.426949024, "num_tokens": 14456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.28047471413508634}}
{"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 \"spin_system.h\"\n\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/format.hpp>\n\nnamespace ssl {\nnamespace spinsys {\nspin_system::spin_system(const std::string &filename) : inter_(comp_) {\n\n  sol::state lua;\n  lua.script_file(filename);\n  sol::table t = lua[\"sys\"];\n  set_sys(t);\n}\nspin_system::spin_system(const sol::table &t) : inter_(comp_) {\n  set_sys(t);\n}\nspin_system::~spin_system() {\n}\nvoid spin_system::set_sys(const sol::table &t) {\n  if (!t.valid() || t.empty())\n    throw std::runtime_error(\"invalid 'spin_system' table parameters (nil or empty).\");\n\n  //try {\n//  std::string str = retrieve_table(\"B0\", t).as<std::string>();\n//  boost::to_lower(str);\n//  std::vector<std::string> str_vec;\n//  boost::split(str_vec, str, boost::is_any_of(\", \"), boost::token_compress_on);\n//  double val_B0 = boost::lexical_cast<double>(str_vec[0]);\n//  if (str_vec[1] == \"tesla\" || str_vec[1] == \"t\")\n//    set_magnet_field(val_B0);\n//  if (str_vec[1] == \"mhz\")\n//    set_proton_freq(val_B0);\n\n  if (g_B0_ < 0) {\n    throw std::runtime_error(\"static magnetic field not set yet!\");\n  }\n\n  comp_.B0_ = g_B0_;\n\n  set_isotopes(retrieve_table(\"spin\", t).as<std::string>());\n  //setBasis();\n  inter_.alloc();\n\n  if (is_retrievable(\"zeeman\", t))\n    inter_.set_zeeman(retrieve_table(\"zeeman\", t).as<std::string>());\n\n  if (is_retrievable(\"jcoupling\", t))\n    inter_.set_Jcoupling(retrieve_table(\"jcoupling\", t).as<std::string>());\n\n  if (is_retrievable(\"coord\", t))\n    inter_.set_Jcoupling_coords(retrieve_table(\"coord\", t).as<sol::table>());\n\n  if (is_retrievable(\"relaxation\", t))\n    inter_.set_relaxation(retrieve_table(\"relaxation\", t).as<std::string>());\n\n  inter_.init();\n  inter_.set_assumption(\"nmr\");\n  /*} catch (const std::runtime_error& e) {\n      std::string s = str(boost::format(\"%s\\n\") % std::string(e.what()));\n      ssl_color_text(\"err\", s);\n  }*/\n}\n\nvoid spin_system::set_isotopes(const std::string list) {\n  std::vector<std::string> symbol_vec;\n  boost::split(symbol_vec, list, boost::is_any_of(\"\\t, \"), boost::token_compress_on);\n  for (size_t i = 0; i < symbol_vec.size(); i++)\n    comp_.add_spin(isotope(symbol_vec[i]));\n#ifdef SSL_OUTPUT_ENABLE\n  std::string s = str(boost::format(\"%s %s.\\n\") % \"isotopes set to be\" % list);\n  ssl_color_text(\"info\", s);\n#endif\n  comp_.init();\n}\n\nvoid spin_system::set_magnet_field(double tesla) {\n  comp_.B0_ = tesla;\n#ifdef SSL_OUTPUT_ENABLE\n  std::string s = str(boost::format(\"%s %.3f Tesla.\\n\") % \"magnet field set to be\" % tesla);\n  ssl_color_text(\"info\", s);\n#endif\n}\n\nvoid spin_system::set_proton_freq(double MHz) {\n  isotope proton(\"1H\");\n  double tesla = MHz * 2 * _pi / proton.gamma() * 1e6;\n#ifdef SSL_OUTPUT_ENABLE\n  std::string s = str(boost::format(\"%s %.3f MHz.\\n\") % \"proton resonance frequency set to be\" % MHz);\n  ssl_color_text(\"info\", s);\n#endif\n  set_magnet_field(tesla);\n}\ndouble spin_system::get_proton_freq() const {\n  return comp_.get_proton_freq();\n}\nsp_mat spin_system::op(const std::string &list) const {\n  return op(list, kComm);\n}\nsp_mat spin_system::op(const sol::table &t) const {\n  return op(t, kComm);\n}\nsp_mat spin_system::op(const std::string &list, op_side type) const {\n  return comp_.op(list, type);\n}\nsp_mat spin_system::op(const sol::table &t, op_side type) const {\n  if (!t.valid() || t.empty())\n    throw std::runtime_error(\"invalid 'op' table parameters (nil or empty).\");\n\n  std::vector<std::string> s;\n  for (size_t i = 0; i < t.size(); i++) {\n    sol::object val = t[i + 1];\n    std::string item;\n    switch (val.get_type()) {\n      case sol::type::number:item = boost::lexical_cast<std::string>(val.as<int>());\n        break;\n      case sol::type::string:item = val.as<std::string>();\n        break;\n      default:break;\n    }\n    s.push_back(item);\n  }\n  std::string list = boost::algorithm::join(s, \" \");\n  return comp_.op(list, type);\n}\n\nsp_cx_vec spin_system::equilibrium_state() const {\n  return inter_.equilibrium_state();\n  }\n\nsp_cx_mat spin_system::smart_op(const std::string expr) const {\n  state_par s = state_evaluate(expr);\n  int num = s.coeff.size();\n  sp_cx_mat result = s.coeff[0] * op(s.expr[0]);\n  for (int i = 1; i < num; i++)\n    result += s.coeff[i] * op(s.expr[i]);\n  return result;\n}\n\nsp_cx_vec spin_system::smart_state(const std::string expr) const {\n  state_par s = state_evaluate(expr);\n  int num = s.coeff.size();\n  sp_cx_vec result = s.coeff[0] * state(s.expr[0]);\n  for (int i = 1; i < num; i++)\n    result += s.coeff[i] * state(s.expr[i]);\n  return result;\n}\n\nstd::map<std::string, sp_cx_vec> spin_system::cartesian_basis_states() const {\n  std::string base_expr = \"(1+Ix+Iy+Iz)\";\n  int nspins = comp_.nspins();\n  std::string expr_in;\n  boost::regex reg(\"I(\\\\w)\");\n  std::vector<std::string> exprs(nspins);\n  for (int i = 0; i < nspins; i++) {\n    exprs[i] = base_expr;\n    std::string id = boost::lexical_cast<std::string>(i + 1);\n    std::string rep = \"I\" + id + \"$1\";\n    std::string s = boost::regex_replace(exprs[i], reg, rep);\n    exprs[i] = s;\n    //std::cout << rep<<\" \"<<exprs[i] << \"\\n\";\n  }\n\n  expr_in = exprs[0];\n  for (int i = 1; i < nspins; i++)\n    expr_in += \"*\" + exprs[i];\n\n  expr_in = \"Simplify(\" + expr_in + \")\";\n  //std::cout << expr_in<<\"\\n\";\n  std::string expr_out = yacas_evaluate(expr_in);\n  boost::erase_all(expr_out, \";\");\n  //std::cout << expr_out << \"\\n\";\n  //boost::replace_all(expr_out, \"J\", \"I\");\n  //std::vector<std::string> expr_vec;\n  std::vector<std::string> expr;\n  boost::algorithm::split(expr, expr_out, boost::is_any_of(\"+\"));\n  expr.pop_back(); // !!! remove 1.\n  std::map<std::string, sp_cx_vec> basis;\n  for (size_t i = 0; i < expr.size(); i++) {\n    boost::erase_all(expr[i], \"*\");\n    //std::cout << i + 1 << \" \" << expr[i] << \"\\n\";\n    basis.insert(std::pair<std::string, sp_cx_vec>(expr[i], smart_state(expr[i])));\n  }\n  /*std::map<std::string, sp_cx_vec>::iterator iter;\n  for (iter = basis.begin(); iter != basis.end(); iter++) {\n      std::string label = iter->first;\n      sp_cx_vec val = iter->second;\n      std::cout << label << \"\\n\" << val << \"\\n\";\n  }*/\n  return basis;\n}\n\nsp_cx_vec spin_system::state(const std::string &list) const {\n  return comp_.state(list);\n}\nsp_cx_vec spin_system::state(const sol::table &t) const {\n  if (!t.valid() || t.empty())\n    throw std::runtime_error(\"invalid 'op' table parameters (nil or empty).\");\n  std::vector<std::string> s;\n  for (size_t i = 0; i < t.size(); i++) {\n    sol::object val = t[i + 1];\n    std::string item;\n    switch (val.get_type()) {\n      case sol::type::number:item = boost::lexical_cast<std::string>(val.as<int>());\n        break;\n      case sol::type::string:item = val.as<std::string>();\n        break;\n      default:break;\n    }\n    s.push_back(item);\n  }\n  std::string list = boost::algorithm::join(s, \" \");\n  return comp_.state(list);\n}\n\nham_op spin_system::hamiltonian(const op_side type, bool build_aniso) const {\n  return inter_.hamiltonian(type, build_aniso);\n}\n\nsp_cx_mat spin_system::free_hamiltonian() const {\n  return hamiltonian(kComm, 0).isotropic;\n}\n\nstd::vector<sp_cx_mat> spin_system::free_hamiltonians() {\n  std::vector<sp_cx_mat> L0s;\n  std::vector<std::vector<cs_par>> result_cs = inter_.parsing_zeeman_broadband();\n  std::vector<std::vector<jcoup_par>> result_jcoup = inter_.parsing_Jcoupling_broadband();\n  if (result_cs.size())\n    std::cout << \"chemical shifts num: \" << result_cs.size() << \"\\n\";\n  if (result_jcoup.size())\n    std::cout << \"j-coupling num: \" << result_jcoup.size() << \"\\n\";\n  // zeeman case.\n  std::vector<double> scalars = inter_.zeeman_.scalars; // backup.\n  mat scalar = inter_.coupling_.scalar;\n  if (result_cs.size()&&result_jcoup.size()==0)\n  for (size_t i = 0; i < result_cs.size(); i++) {\n    for (size_t j = 0; j < result_cs[i].size(); j++) {\n      const cs_par &cur = result_cs[i][j];\n      //std::cout << (cur.id + 1) << \" \" << inter_.zeeman_.scalars[cur.id] << \" \";\n      inter_.zeeman_.scalars[cur.id] += cur.val;\n      //std::cout << (cur.id + 1) << \" \" << inter_.zeeman_.scalars[cur.id] << \" \";\n    }\n    //std::cout << \"\\n\";\n    inter_.init_broadband();\n    L0s.push_back(free_hamiltonian());\n    inter_.zeeman_.scalars = scalars; // recover to original pars for the next L0 calculation.\n  }\n  // J-coupling case.\n    if (result_cs.size()==0&&result_jcoup.size())\n  for (size_t i = 0; i < result_jcoup.size(); i++) {\n    for (size_t j = 0; j < result_jcoup[i].size(); j++) {\n      const jcoup_par &cur = result_jcoup[i][j];\n      int id1 = cur.id1;\n      int id2 = cur.id2;\n      inter_.coupling_.scalar(id1, id2) += cur.val;\n      if (id1 != id2)\n        inter_.coupling_.scalar(id2, id1) += cur.val;\n      //std::cout << (cur.id1 + 1) << \" \" << (cur.id2 + 1) << \" \" << inter_.coupling_.scalar(id1, id2) << \" \";\n    }\n    //std::cout << \"\\n\";\n    inter_.init_broadband();\n    L0s.push_back(free_hamiltonian());\n    inter_.coupling_.scalar = scalar;\n  }\n\t//omp_set_num_threads(omp_core_num);\n\tif(result_cs.size()&&result_jcoup.size()) {\n    //#pragma omp parallel for    \n    for (size_t i = 0; i < result_cs.size(); i++) {\n      if (i % 100 == 0) std::cout << i << \"==>\\n\";\n\n      for (size_t j = 0; j < result_cs[i].size(); j++) {\n        const cs_par &cur = result_cs[i][j];\n        inter_.zeeman_.scalars[cur.id] += cur.val;\n      }\n\n      for (size_t ii = 0; ii < result_jcoup.size(); ii++) {\n\n        for (size_t jj = 0; jj < result_jcoup[ii].size(); jj++) {\n          const jcoup_par &cur = result_jcoup[ii][jj];\n          int id1 = cur.id1;\n          int id2 = cur.id2;\n          inter_.coupling_.scalar(id1, id2) += cur.val;\n          if (id1 != id2) inter_.coupling_.scalar(id2, id1) += cur.val;\n        }\n\n        inter_.init_broadband();\n        L0s.push_back(free_hamiltonian());\n\n        inter_.coupling_.scalar = scalar;\n      }\n      inter_.zeeman_.scalars = scalars;  // recover to original pars for the next L0 calculation.\n    }\n\t}\n  return L0s;\n}\n\nsol::object spin_system::free_hamiltonians(sol::this_state s) {\n  sol::state_view lua(s);\n  sol::table t = lua.create_table();\n  std::vector<sp_cx_mat> L0s = free_hamiltonians();\n  for (size_t i = 0; i < L0s.size(); i++)\n    t.add(L0s[i]);\n  return t;\n}\nsp_cx_mat spin_system::relaxation() const {\n  return inter_.relaxation();\n}\n\nsp_cx_mat spin_system::total_hamiltonian() const {\n  return free_hamiltonian() + ci * relaxation();\n}\nrf_ham spin_system::rf_hamiltonian() const {\n  rf_ham rf_ctrl;\n  rf_ctrl.init(channels());\n  for (size_t i = 0; i < rf_ctrl.channels; i++) {\n    // Get the control operators\n    std::string list_plus = rf_ctrl.chs[i] + \" I+\";\n    std::string list_minus = rf_ctrl.chs[i] + \" I-\";\n    sp_mat Lp = op(list_plus);\n    sp_mat Lm = op(list_minus);\n    rf_ctrl.Lx[i] = 0.5 * (Lp + Lm).cast<cd>();  // cx\n    rf_ctrl.Ly[i] = -0.5 * ci * (Lp - Lm).cast<cd>();  // cy\n  }\n  return rf_ctrl;\n}\nvec spin_system::nominal_broadband() {\n  if (inter_.zeeman_.bb_scalars.size())\n    return inter_.zeeman_.bb_scalars[0].nominal_offset;\n  if (inter_.coupling_.bb_scalars.size())\n    return inter_.coupling_.bb_scalars[0].nominal_offset;\n  return vec(1);\n}\n\n}\n}\n", "meta": {"hexsha": "1d799eb4ec941daddcd0725c4b62cc31c75c235c", "size": 11756, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/kernel/spinsys/spin_system.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/spinsys/spin_system.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/spinsys/spin_system.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": 33.6848137536, "max_line_length": 110, "alphanum_fraction": 0.6276794828, "num_tokens": 3590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.28047471413508634}}
{"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_TRIGONOMETRIC_CONSTANTS_PIO2_2_HPP_INCLUDED\n#define NT2_TRIGONOMETRIC_CONSTANTS_PIO2_2_HPP_INCLUDED\n\n#include <nt2/include/functor.hpp>\n#include <boost/simd/constant/hierarchy.hpp>\n#include <boost/simd/constant/register.hpp>\nnamespace nt2\n{\n  namespace tag\n  {\n   /*!\n     @brief Pio2_2 generic tag\n\n     Represents the Pio2_2 constant in generic contexts.\n\n     @par Models:\n        Hierarchy\n   **/\n    //6.07710050630396597660e-11\n    BOOST_SIMD_CONSTANT_REGISTER( Pio2_2, double\n                                , 0, 0x37354400\n                                , 0x3DD0B4611A600000ll\n                                )\n  }\n  namespace ext\n  {\n   template<class Site, class... Ts>\n   BOOST_FORCEINLINE generic_dispatcher<tag::Pio2_2, Site> dispatching_Pio2_2(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)\n   {\n     return generic_dispatcher<tag::Pio2_2, Site>();\n   }\n   template<class... Args>\n   struct impl_Pio2_2;\n  }\n  /*!\n    Constant used in modular computation involving \\f$\\pi\\f$\n\n    @par Semantic:\n\n    For type T0:\n\n    @code\n    T0 r = Pio2_2<T0>();\n    @endcode\n\n    @return a value of type T0\n  **/\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(tag::Pio2_2, Pio2_2);\n}\n\n#endif\n\n", "meta": {"hexsha": "c4af538355b987ea36a7c9faa875362a64ee30dc", "size": 1749, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/pio2_2.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/pio2_2.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/trigonometric/include/nt2/trigonometric/constants/pio2_2.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6721311475, "max_line_length": 168, "alphanum_fraction": 0.5791881075, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.28047471413508634}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2008 Andreas Gaida\n Copyright (C) 2008, 2009 Ralph Schreyer\n Copyright (C) 2008, 2009 Klaus Spanderen\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <ql/pricingengines/barrier/fdhestonbarrierengine.hpp>\n#include <ql/methods/finitedifferences/stepconditions/fdmstepconditioncomposite.hpp>\n#include <ql/methods/finitedifferences/utilities/fdmdividendhandler.hpp>\n#include <ql/methods/finitedifferences/meshers/fdmhestonvariancemesher.hpp>\n#include <ql/methods/finitedifferences/utilities/fdmdirichletboundary.hpp>\n#include <ql/methods/finitedifferences/utilities/fdminnervaluecalculator.hpp>\n#include <ql/methods/finitedifferences/operators/fdmlinearoplayout.hpp>\n#include <ql/methods/finitedifferences/meshers/fdmmeshercomposite.hpp>\n#include <ql/methods/finitedifferences/meshers/fdmblackscholesmesher.hpp>\n#include <ql/pricingengines/barrier/fdhestonrebateengine.hpp>\n#include <ql/pricingengines/vanilla/fdhestonvanillaengine.hpp>\n#include <boost/make_shared.hpp>\n\nnamespace QuantLib {\n\n    FdHestonBarrierEngine::FdHestonBarrierEngine(\n            const boost::shared_ptr<HestonModel>& model,\n            Size tGrid, Size xGrid, Size vGrid, Size dampingSteps,\n            const FdmSchemeDesc& schemeDesc,\n            const boost::shared_ptr<LocalVolTermStructure>& leverageFct)\n    : GenericModelEngine<HestonModel,\n                        DividendBarrierOption::arguments,\n                        DividendBarrierOption::results>(model),\n      tGrid_(tGrid), xGrid_(xGrid), \n      vGrid_(vGrid), dampingSteps_(dampingSteps),\n      schemeDesc_(schemeDesc),\n      leverageFct_(leverageFct) {\n    }\n\n    void FdHestonBarrierEngine::calculate() const {\n\n        // 1. Mesher\n        const boost::shared_ptr<HestonProcess>& process = model_->process();\n        const Time maturity = process->time(arguments_.exercise->lastDate());\n\n        // 1.1 The variance mesher\n        const Size tGridMin = 5;\n        const boost::shared_ptr<FdmHestonVarianceMesher> varianceMesher(\n\t\t\tboost::make_shared<FdmHestonVarianceMesher>(vGrid_, process, maturity,\n                                        std::max(tGridMin, tGrid_/50)));\n\n        // 1.2 The equity mesher\n        const boost::shared_ptr<StrikedTypePayoff> payoff =\n            boost::dynamic_pointer_cast<StrikedTypePayoff>(arguments_.payoff);\n\n        Real xMin=Null<Real>();\n        Real xMax=Null<Real>();\n        if (   arguments_.barrierType == Barrier::DownIn\n            || arguments_.barrierType == Barrier::DownOut) {\n            xMin = std::log(arguments_.barrier);\n        }\n        if (   arguments_.barrierType == Barrier::UpIn\n            || arguments_.barrierType == Barrier::UpOut) {\n            xMax = std::log(arguments_.barrier);\n        }\n\n        const boost::shared_ptr<Fdm1dMesher> equityMesher(\n            new FdmBlackScholesMesher(\n                xGrid_,\n                FdmBlackScholesMesher::processHelper(\n                    process->s0(), process->dividendYield(),\n                    process->riskFreeRate(), varianceMesher->volaEstimate()),\n                maturity, payoff->strike(),\n                xMin, xMax, 0.0001, 1.5,\n                std::make_pair(Null<Real>(), Null<Real>()),\n                arguments_.cashFlow));\n\n        const boost::shared_ptr<FdmMesher> mesher (\n\t\t\tboost::make_shared<FdmMesherComposite>(equityMesher, varianceMesher));\n\n        // 2. Calculator\n        boost::shared_ptr<FdmInnerValueCalculator> calculator(\n\t\t\tboost::make_shared<FdmLogInnerValue>(payoff, mesher, 0));\n\n        // 3. Step conditions\n        std::list<boost::shared_ptr<StepCondition<Array> > > stepConditions;\n        std::list<std::vector<Time> > stoppingTimes;\n\n        // 3.1 Step condition if discrete dividends\n        boost::shared_ptr<FdmDividendHandler> dividendCondition(\n\t\t\tboost::make_shared<FdmDividendHandler>(arguments_.cashFlow, mesher,\n                                   process->riskFreeRate()->referenceDate(),\n                                   process->riskFreeRate()->dayCounter(), 0));\n\n        if(!arguments_.cashFlow.empty()) {\n            stepConditions.push_back(dividendCondition);\n            stoppingTimes.push_back(dividendCondition->dividendTimes());\n        }\n\n        QL_REQUIRE(arguments_.exercise->type() == Exercise::European,\n                   \"only european style option are supported\");\n\n        boost::shared_ptr<FdmStepConditionComposite> conditions(\n\t\t\tboost::make_shared<FdmStepConditionComposite>(stoppingTimes, stepConditions));\n\n        // 4. Boundary conditions\n        FdmBoundaryConditionSet boundaries;\n        if (   arguments_.barrierType == Barrier::DownIn\n            || arguments_.barrierType == Barrier::DownOut) {\n            boundaries.push_back(\n\t\t\t\tboost::make_shared<FdmDirichletBoundary>(mesher, arguments_.rebate, 0,\n                                         FdmDirichletBoundary::Lower));\n\n        }\n        if (   arguments_.barrierType == Barrier::UpIn\n            || arguments_.barrierType == Barrier::UpOut) {\n            boundaries.push_back(\n\t\t\t\tboost::make_shared<FdmDirichletBoundary>(mesher, arguments_.rebate, 0,\n                                         FdmDirichletBoundary::Upper));\n        }\n\n        // 5. Solver\n        FdmSolverDesc solverDesc = { mesher, boundaries, conditions,\n                                     calculator, maturity,\n                                     tGrid_, dampingSteps_ };\n\n        boost::shared_ptr<FdmHestonSolver> solver(boost::make_shared<FdmHestonSolver>(\n                    Handle<HestonProcess>(process), solverDesc, schemeDesc_,\n                    Handle<FdmQuantoHelper>(), leverageFct_));\n\n        const Real spot = process->s0()->value();\n        results_.value = solver->valueAt(spot, process->v0());\n        results_.delta = solver->deltaAt(spot, process->v0());\n        results_.gamma = solver->gammaAt(spot, process->v0());\n        results_.theta = solver->thetaAt(spot, process->v0());\n\n        // 6. Calculate vanilla option and rebate for in-barriers\n        if (   arguments_.barrierType == Barrier::DownIn\n            || arguments_.barrierType == Barrier::UpIn) {\n            // Cast the payoff\n            boost::shared_ptr<StrikedTypePayoff> payoff =\n                    boost::dynamic_pointer_cast<StrikedTypePayoff>(\n                                                            arguments_.payoff);\n            // Calculate the vanilla option\n            boost::shared_ptr<DividendVanillaOption> vanillaOption(\n\t\t\t\tboost::make_shared<DividendVanillaOption>(payoff,arguments_.exercise,\n                                          dividendCondition->dividendDates(), \n                                          dividendCondition->dividends()));\n            vanillaOption->setPricingEngine(boost::shared_ptr<PricingEngine>(\n\t\t\t\tboost::make_shared<FdHestonVanillaEngine>(*model_, tGrid_, xGrid_,\n                                              vGrid_, dampingSteps_,\n                                              schemeDesc_)));\n            // Calculate the rebate value\n            boost::shared_ptr<DividendBarrierOption> rebateOption(\n\t\t\t\tboost::make_shared<DividendBarrierOption>(arguments_.barrierType,\n                                          arguments_.barrier,\n                                          arguments_.rebate,\n                                          payoff, arguments_.exercise,\n                                          dividendCondition->dividendDates(), \n                                          dividendCondition->dividends()));\n            const Size xGridMin = 20;\n            const Size vGridMin = 10;\n            const Size rebateDampingSteps \n                = (dampingSteps_ > 0) ? std::min(Size(1), dampingSteps_/2) : 0; \n            rebateOption->setPricingEngine(\n\t\t\t\tboost::make_shared<FdHestonRebateEngine>(*model_, tGrid_,\n                                             std::max(xGridMin, xGrid_/4), \n                                             std::max(vGridMin, vGrid_/4),\n                                             rebateDampingSteps,\n                                             schemeDesc_));\n\n            results_.value = vanillaOption->NPV()   + rebateOption->NPV()\n                                                    - results_.value;\n            results_.delta = vanillaOption->delta() + rebateOption->delta()\n                                                    - results_.delta;\n            results_.gamma = vanillaOption->gamma() + rebateOption->gamma()\n                                                    - results_.gamma;\n            results_.theta = vanillaOption->theta() + rebateOption->theta()\n                                                    - results_.theta;\n        }\n    }\n}\n", "meta": {"hexsha": "9c99539faf856cfc9e1d1eac17e8f75442228e4f", "size": 9386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/pricingengines/barrier/fdhestonbarrierengine.cpp", "max_stars_repo_name": "TheOnlyDyson/QuantLib", "max_stars_repo_head_hexsha": "78a144bbc5030c9e417e810e44ee48cffe40cf70", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ql/pricingengines/barrier/fdhestonbarrierengine.cpp", "max_issues_repo_name": "TheOnlyDyson/QuantLib", "max_issues_repo_head_hexsha": "78a144bbc5030c9e417e810e44ee48cffe40cf70", "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/pricingengines/barrier/fdhestonbarrierengine.cpp", "max_forks_repo_name": "TheOnlyDyson/QuantLib", "max_forks_repo_head_hexsha": "78a144bbc5030c9e417e810e44ee48cffe40cf70", "max_forks_repo_licenses": ["BSD-3-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.381443299, "max_line_length": 86, "alphanum_fraction": 0.6021734498, "num_tokens": 2059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2803739584116058}}
{"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\n#include \"Tudat/Astrodynamics/Gravitation/tabulatedGravityFieldVariations.h\"\n\nnamespace tudat\n{\n\nnamespace gravitation\n{\n\n//! Class constructor\nTabulatedGravityFieldVariations::TabulatedGravityFieldVariations(\n        const std::map< double, Eigen::MatrixXd >& cosineCoefficientCorrections,\n        const std::map< double, Eigen::MatrixXd >& sineCoefficientCorrections,\n        const int minimumDegree, const int minimumOrder,\n        const std::shared_ptr< interpolators::InterpolatorSettings >interpolatorType ):\n    GravityFieldVariations( minimumDegree, minimumOrder,\n                            minimumDegree + cosineCoefficientCorrections.begin( )->second.rows( ) - 1,\n                            minimumOrder + cosineCoefficientCorrections.begin( )->second.cols( ) - 1 ),\n    interpolatorType_( interpolatorType )\n{\n    // Create interpolator for tabulated coefficients.\n    resetCoefficientInterpolator( cosineCoefficientCorrections, sineCoefficientCorrections );\n}\n\n//! Function to (re)set the tabulated spherical harmonic coefficients.\nvoid TabulatedGravityFieldVariations::resetCoefficientInterpolator(\n        const std::map< double, Eigen::MatrixXd >& cosineCoefficientCorrections,\n        const std::map< double, Eigen::MatrixXd >& sineCoefficientCorrections )\n{\n    // Set current coefficient tables.\n    cosineCoefficientCorrections_ = cosineCoefficientCorrections;\n    sineCoefficientCorrections_ = sineCoefficientCorrections;\n\n    // Check consistency of map sizes.\n    if( cosineCoefficientCorrections_.size( ) != sineCoefficientCorrections_.size( ) )\n    {\n        throw std::runtime_error( \"Error when resetting tabulated gravity field corrections, sine and cosine data size incompatible\" );\n    }\n\n    // Create iterators over maps.\n    std::map< double, Eigen::MatrixXd >::iterator cosineIterator =\n            cosineCoefficientCorrections_.begin( );\n    std::map< double, Eigen::MatrixXd >::iterator sineIterator =\n            sineCoefficientCorrections_.begin( );\n\n    // Declare map to store concatenated (horizontally) [cosine|sine] coefficients for\n    // given discrete times.\n    std::map< double, Eigen::MatrixXd > sineCosinePairMap;\n\n    // Declare matrix to set concatenated (horizontally) [cosine|sine] coefficients at\n    // current time in loop.\n    Eigen::MatrixXd currentCoefficients = Eigen::MatrixXd::Zero( numberOfDegrees_, 2 * numberOfOrders_ );\n\n    // Iterate over all times in correction maps.\n    for( unsigned int i = 0; i < cosineCoefficientCorrections_.size( ); i++ )\n    {\n        // Check whether input times are consistent\n        if( cosineIterator->first != sineIterator->first )\n        {\n            std::string errorMessage = \"Error when resetting tabulated gravity field corrections, sine and cosine data time differ by\" +\n                    std::to_string(  cosineIterator->first - sineIterator->first );\n            throw std::runtime_error( errorMessage );\n        }\n        // Check whether matrix sizes are consistent.\n        if( ( cosineIterator->second.rows( ) != numberOfDegrees_ ) ||\n                ( sineIterator->second.rows( ) != numberOfDegrees_ ) ||\n                ( cosineIterator->second.cols( ) != numberOfOrders_ ) ||\n                ( sineIterator->second.cols( ) != numberOfOrders_ ) )\n        {\n            std::string errorMessage = \"Error when resetting tabulated gravity field corrections, sine and cosine blocks of inconsistent size\";\n            throw std::runtime_error( errorMessage );\n        }\n\n        // Concatenate cosine and sine matrices\n        currentCoefficients.block( 0, 0, numberOfDegrees_, numberOfOrders_ ) =\n                cosineIterator->second;\n        currentCoefficients.block( 0, numberOfOrders_, numberOfDegrees_, numberOfOrders_ ) =\n                sineIterator->second;\n\n        // Set as entry in map of concatenated matrices\n        sineCosinePairMap[ cosineIterator->first ] = currentCoefficients;\n\n        // Increment iterators.\n        cosineIterator++;\n        sineIterator++;\n    }\n\n    // Create interpolator\n    variationInterpolator_ =\n            interpolators::createOneDimensionalInterpolator< double, Eigen::MatrixXd >(\n                sineCosinePairMap, interpolatorType_ );\n}\n\n//! Function for calculating corrections by interpolating tabulated corrections.\nstd::pair< Eigen::MatrixXd, Eigen::MatrixXd > TabulatedGravityFieldVariations::\ncalculateSphericalHarmonicsCorrections(\n        const double time )\n{\n    // Interpolate corrections\n    Eigen::MatrixXd cosineSinePair = variationInterpolator_->interpolate( time );\n\n    // Split interpolated concatenated matrix and return.\n    return std::make_pair( cosineSinePair.block( 0, 0, numberOfDegrees_, numberOfOrders_ ),\n                           cosineSinePair.block( 0, numberOfOrders_, numberOfDegrees_, numberOfOrders_ ) );\n}\n\n} // namespace gravitation\n\n} // namespace tudat\n", "meta": {"hexsha": "0432a6b0e9e23edd1a2b3568844abf831b9d4fe0", "size": 5329, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Gravitation/tabulatedGravityFieldVariations.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/Gravitation/tabulatedGravityFieldVariations.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/Gravitation/tabulatedGravityFieldVariations.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": 44.041322314, "max_line_length": 143, "alphanum_fraction": 0.6975042222, "num_tokens": 1117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.28017857384694794}}
{"text": "#include \"check_particle.h\"\r\n#include \"opic_fwd.h\"\r\n#include \"config.h\"\r\n#include \"io_utilities.h\"\r\n#include \"grid.h\"\r\n#include \"particles.h\"\r\n#include \"gather_scatter.h\"\r\n#include \"call_lua_function.h\"\r\n\r\n#include <boost/format.hpp>\r\n#include <omp.h>\r\n#include <stdexcept>\r\n\r\n /*********************************************************\r\n * Check if particle is active.                           *\r\n * equation of motion is solved for active particles only *\r\n * return true if particles is active, otherwise - false  *\r\n *********************************************************/\r\n\r\nbool is_particle_can_scatter(Particles& particles, index_t p, const Grid& grid, const DblVector& dr)\r\n{\r\n    if (particles.is_inactive(p))\r\n        return false;\r\n\r\n    const Particle& particle = particles[p];\r\n    const double h = PIC::Config::h();\r\n    const index_t pi = static_cast<index_t>(floor((particle.r.x + dr.x)/h));\r\n    const index_t pj = static_cast<index_t>(floor((particle.r.y + dr.y)/h));\r\n    const index_t pk = static_cast<index_t>(floor((particle.r.z + dr.z)/h));\r\n    const PIC::CellState home_cell_state = grid(pi, pj, pk).state();\r\n\r\n    if (pi < 1 || pi > grid.size_x() - 2 ||\r\n        pj < 1 || pj > grid.size_y() - 2 ||\r\n        pk < 1 || pk > grid.size_z() - 2 ||\r\n        home_cell_state == PIC::cs_absorptive)\r\n    {\r\n        particles.remove_later(p);\r\n        return false;\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nbool is_particle_can_move(Particles& particles, index_t p, const Grid& grid)\r\n{\r\n    if (!is_particle_can_scatter(particles, p, grid, DblVector()))\r\n        return false;\r\n\r\n    Particle& particle = particles[p];\r\n    const double h = PIC::Config::h();\r\n    const index_t pi = static_cast<index_t>(floor(particle.r.x/h));\r\n    const index_t pj = static_cast<index_t>(floor(particle.r.y/h));\r\n    const index_t pk = static_cast<index_t>(floor(particle.r.z/h));\r\n    const PIC::CellState home_cell_state = grid(pi,pj,pk).state();\r\n\r\n    if (home_cell_state == PIC::cs_active)\r\n        return true;\r\n\r\n    if (home_cell_state == PIC::cs_custom)\r\n        return lua_validate_particle(particle);\r\n\r\n    // never reach here\r\n    return false;\r\n}\r\n\r\nbool check_particle_move(const Particle& particle, const Grid& grid, const DblVector& dr)\r\n{\r\n    if (PIC::Config::CFL_severity() == PIC::Ignore)\r\n        return true;\r\n\r\n    const double h = PIC::Config::h();\r\n    const double h_2 = PIC::Config::h_2();\r\n\r\n    if (fabs(dr.x) > h_2 || fabs(dr.y) > h_2 || fabs(dr.z) > h_2)\r\n    {\r\n        const index_t step = PIC::Config::current_time_step();\r\n\r\n        Grid::NodeType point_val;\r\n        PIC::from_grid_to_point(grid, particle.r, point_val);\r\n\r\n        const index_t pi = static_cast<index_t>(particle.r.x/h);\r\n        const index_t pj = static_cast<index_t>(particle.r.y/h);\r\n        const index_t pk = static_cast<index_t>(particle.r.z/h);\r\n\r\n        const std::string msg = boost::str(boost::format(\"Step = %1%:\\n\\tError CFL, particle shift dr should be  < h/2:\"\r\n                                                  \"\\n\\tparticle's home cell = (%2%, %3%, %4%);\"\r\n                                                  \"\\n\\tgrid size = (%5% x %6% x %7%);\"\r\n                                                  \"\\n\\tdr = (%8%, %9%, %10%),\\n\\tdr.abs() = %11%; h/2 = %12%;\"\r\n                                                  \"\\n\\tparticle [%13%] at (%14%, %15%, %16%)\"\r\n                                                  \"\\n\\tgrid values at particle position:\"\r\n                                                  \"\\n\\t\\t B = %17%, Bx = %18%, By = %19%, Bz = %20%\"\r\n                                                  \"\\n\\t\\t E = %21%, Ex = %22%, Ey = %23%, Ez = %24%\"\r\n                                                  \"\\n\\t\\t NP = %25%, UPx = %26%, UPy = %27%, UPz = %28%\"\r\n                                                  \"\\n\\t\\t UEx = %29%, UEy = %30%, UEz = %31%\"\r\n                                                  \"\\n\\t\\t cell state = %32% (0 - active, 1 - absorptive, 2 - custom)\")\r\n                                                  % step\r\n                                                  % pi % pj % pk\r\n                                                  % grid.size_x() % grid.size_y() % grid.size_z()\r\n                                                  % dr.x % dr.y % dr.z % (dr.abs())\r\n                                                  % h_2\r\n                                                  % particle.group_name\r\n                                                  % particle.r.x % particle.r.y % particle.r.z\r\n                                                  % point_val.B.abs() % point_val.B.x % point_val.B.y % point_val.B.z\r\n                                                  % point_val.E.abs() % point_val.E.x % point_val.E.y % point_val.E.z\r\n                                                  % point_val.NP % point_val.UP.x % point_val.UP.y % point_val.UP.z\r\n                                                  % point_val.UE.x % point_val.UE.y % point_val.UE.z\r\n                                                  % grid(pi,pj,pk).state());\r\n\r\n        const int tid = omp_get_thread_num();\r\n        const std::string log_file_name = str(boost::format(\"opic_thread_%1%_check_particle_move_err.log\") % tid);\r\n        std::ofstream ofs_log(log_file_name.c_str(), std::ios_base::app);\r\n        ofs_log << msg << std::endl;\r\n        return false;\r\n    }\r\n\r\n    return true;\r\n}\r\n", "meta": {"hexsha": "963d7cb137a076704bde412e201620291f918955", "size": 5392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/check_particle.cpp", "max_stars_repo_name": "dozzes/open-pic", "max_stars_repo_head_hexsha": "017b6c07e0020e984175c1e04a9f2d51eefd482c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2015-02-22T15:48:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-25T03:15:47.000Z", "max_issues_repo_path": "src/check_particle.cpp", "max_issues_repo_name": "dozzes/open-pic", "max_issues_repo_head_hexsha": "017b6c07e0020e984175c1e04a9f2d51eefd482c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/check_particle.cpp", "max_forks_repo_name": "dozzes/open-pic", "max_forks_repo_head_hexsha": "017b6c07e0020e984175c1e04a9f2d51eefd482c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-12T10:15:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-17T05:15:49.000Z", "avg_line_length": 45.6949152542, "max_line_length": 121, "alphanum_fraction": 0.4664317507, "num_tokens": 1230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.280143708943101}}
{"text": "// -*- C++ -*-\n\n// The MIT License (MIT)\n//\n// Copyright (c) 2017 Alexander Samoilov\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//  FDLIB, CFDLAB, BEMLIB\n//\n//  Copyright by C. Pozrikidis, 1999\n//  All rights reserved.\n//\n//  This program is to be used only under the\n//  stipulations of the licensing agreement.\n// ==========================================\n//\n// ---------------------------------------------------\n//  Axisymmetric streaming (uniform)\n//  potential flow past a stationary body.\n//\n//  This program solves\n//  an integral equation of the second kind\n//  for the disturbance harmonic potential\n//  over the body contour\n//  and computes streamlines\n//\n//  The contour of the body in the xy upper half-plane\n//  consists of a Number of SeGments (NSG)\n//\n//  The segments may be straight lines or circular arcs.\n//\n//  Each segment is discretized into a number of elements\n//\n//\n//  Symbols:\n//  --------\n//\n//  NSG: Number of segments defining the body contour\n//\n//  NE(i): Number of elements on the ith segment\n//\n//  RT(i): Stretch ratio of elements on ith segment\n//\n//  Itp(i): Index for shape of the ith segment:\n//          1 for a straight segment\n//          2 for a circular arc\n//\n//  (Xe, Ye):  end-nodes of elements on a segment\n//  (Xm, Ym):  mid-nodes of elements on a segment\n//  (Xw, Yw):  end-nodes of elements on all segments\n//\n//  (X0, Y0):  coordinates of collocation points\n//\n//  T0(i): angle subtended from the center of a circular element\n//         at ith collocation point\n//\n//  arel(i):  axisymmetric surface area of ith element\n//\n//  phi: disturbance potential at collocation points\n//\n//  dphidn0: normal derivative of disturbance potential\n//                  at collocation points\n//\n//  dphids0: tangential derivative of potential\n//                  at collocation points\n//\n//  cp:      pressure coefficient at collocation points\n//\n//  NGL: Number of Gaussian points for integration\n//       over each element\n//\n//  Icross: Index for stopping the computation of the streamlines\n//          Default value is 0\n//          If Icross = 1, computation stops when a streamline\n//          crosses the yz plane\n//\n//  Notes:\n//  ------\n//\n//  Normal vector points into the flow\n//\n// ----------------------------\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <chrono>\n#include <boost/program_options.hpp>\n#include \"parameters.hpp\"\n#include \"program_options.hpp\"\n#include \"lin_alg_types.hpp\"\n#include \"body_ax_geo.hpp\"\n#include \"body_ax_sdlp.tcc\"\n#include \"body_ax_vel.tcc\"\n\nprogram_options parse_command_line(int argc, char** argv)\n{\n    namespace po = boost::program_options;\n    po::options_description desc(\"allowed options\");\n    desc.add_options()\n            (\"help\",                   \"describe arguments\")\n            (\"verbose\",                \"be verbose\")\n            (\"flow_type\",              po::value<int>(), \"legacy Fortran constants for flow type, 50 for sphere, 51 for torus\")\n            (\"input_data\",             po::value<std::string>(), \"name of the input file e.g. `sphere.dat`, `torus_trgl.dat`\")\n            (\"asy_name\",               po::value<std::string>(), \"dump streamlines to vector `.asy` file if name is given\");\n    try\n    {\n        po::variables_map vm;\n        po::store(po::parse_command_line(argc, argv, desc), vm);\n        po::notify(vm);\n        program_options popt;\n\n        if (vm.count(\"help\")) {\n            std::cout << desc << std::endl;\n            std::exit(1);\n        }\n\n        popt.verbose = vm.count(\"verbose\");\n        if (vm.count(\"flow_type\")) {\n            popt.flow_type = vm[\"flow_type\"].as<int>();\n        }\n        if (vm.count(\"input_data\")) {\n            popt.input_data = vm[\"input_data\"].as<std::string>();\n        }\n        if (vm.count(\"asy_name\")) {\n            popt.asy_name = vm[\"asy_name\"].as<std::string>();\n        }\n\n        return popt;\n    }\n    catch(const std::exception& e)\n    {\n        std::cerr << e.what() << std::endl;\n        std::cout << desc << std::endl;\n        std::exit(-1);\n    }\n}\n\nusing Time = std::chrono::high_resolution_clock;\nusing ms = std::chrono::milliseconds;\nusing fsec = std::chrono::duration<float>;\n\nint main(int argc, char **argv)\n{\n    auto popt = parse_command_line(argc, argv);\n    if (popt.verbose) {\n        std::cout << popt;\n    }\n\n    matg_t<FLOATING_TYPE> phi;\n    vecg_t<FLOATING_TYPE> velt, veln, cp;\n    matg_t<FLOATING_TYPE> al;      // for the linear system\n    vecg_t<FLOATING_TYPE> bl, sol; // ditto\n\n    auto const& run_params = body_ax_geo<FLOATING_TYPE>(popt);\n    if (popt.verbose) {\n        std::cout << \"-I- ngl: \" << run_params.ngl << \"\\n\";\n        std::cout << \"-I- vx: \" << run_params.vx << \"\\n\";\n        std::cout << \"-I- cr: \" << run_params.cr << \"\\n\";\n        std::cout << \"-I- ne[0]: \" << run_params.ne[0] << \"\\n\";\n        std::cout << \"-I- xwmin: \" << run_params.xwmin << \"\\n\";\n        std::cout << \"-I- ywmin: \" << run_params.ywmin << \"\\n\";\n    }\n\n    // ...\n\n    //---------------------------------------------\n    // Generate the linear system\n    // for the potential at the collocation points\n    //\n    // Generate the influence matrix\n    // consisting of integrals of the\n    // single-layer potential\n    //\n    // Compute the rhs by evaluating the dlp\n    //-------------------------------------------------------\n\n    // resizing\n    al.resize(run_params.ncl, run_params.ncl);\n    bl.resize(run_params.ncl);\n    // stiffness matrix and rhs\n    for (int i = 0; i < run_params.ncl; ++i) {           // loop over collocation points\n        bl(i) = ZERO<FLOATING_TYPE>;\n        int j = -1;\n        for (int k = 0; k < run_params.nsg; ++k) {       // loop over segments\n            FLOATING_TYPE rad = NaN<FLOATING_TYPE>, xcnt = NaN<FLOATING_TYPE>, ycnt = NaN<FLOATING_TYPE>;\n            if (run_params.itp[k] == 2) {\n                rad  = run_params.actis[k];\n                xcnt = run_params.xcntr[k];\n                ycnt = run_params.ycntr[k];\n            }\n            for (int l = 0; l < run_params.ne[k]; ++l) { // loop over elements\n                FLOATING_TYPE x1 = run_params.xw(k,l);\n                FLOATING_TYPE y1 = run_params.yw(k,l);\n                FLOATING_TYPE t1 = run_params.tw(k,l);\n\n                FLOATING_TYPE x2 = run_params.xw(k,l+1);\n                FLOATING_TYPE y2 = run_params.yw(k,l+1);\n                FLOATING_TYPE t2 = run_params.tw(k,l+1);\n\n                j = j+1;\n                bool ising = (i == j);\n                FLOATING_TYPE qqq, www;\n                body_ax_sdlp (run_params.x0[i], run_params.y0[i], run_params.t0[i],\n                              x1, y1, t1, x2, y2, t2, run_params.gl, ising,\n                              run_params.itp[k], rad,xcnt,ycnt,\n                              qqq, www);\n\n                al(i, j) = www;\n                bl(i) += qqq * run_params.dphidn0[j];\n\n            }\n\n        }\n        al(i, i) -= HALF<FLOATING_TYPE>;\n\n    }\n\n    auto t0 = Time::now();\n    //------------------------\n    // Solve the linear system\n    //------------------------\n    sol = al.lu().solve(bl.transpose());\n    auto t1 = Time::now();\n    fsec fs = t1 - t0;\n    ms d = std::chrono::duration_cast<ms>(fs);\n    std::cout << \"linear system solution took \" << fs.count() << \"s\\n\";\n    std::cout <<  \"linear system solution took \" << d.count() << \"ms\\n\";\n\n    if (popt.verbose) {\n        for (size_t i = 0; i < run_params.ncl; ++i) {\n            std::cout << \"sol(\" << i << \") : \" << sol(i) << std::endl;\n        }\n    }\n\n    //------------------------\n    // Distribute the solution\n    //------------------------\n\n    size_t max_elems = run_params.ne.maxCoeff();\n    phi.resize(run_params.nsg, max_elems);\n    velt.resize(run_params.nsg * max_elems);\n    veln.resize(run_params.nsg * max_elems);\n    cp.resize(run_params.nsg * max_elems);\n\n    size_t k = 0;        // counter\n    for (size_t i = 0; i < run_params.nsg; ++i) {\n        for (size_t j = 0; j < run_params.ne[i]; ++j) {\n            phi(i, j) = sol(k++);\n        }\n    }\n\n    //------------------------------------------------\n    // Compute the tangential disturbance velocity\n    //             by taking tangential derivative of \\phi\n    //\n    // Compute the pressure coefficient cp\n    //             drag force\n    //------------------------------------------------\n \n    FLOATING_TYPE forcex = ZERO<FLOATING_TYPE>, dphids0;\n    k = 0;        // counter\n    for (size_t i = 0; i < run_params.nsg; ++i) {\n        for (size_t j = 0; j < run_params.ne[i]; ++j) {\n            //--------------------------------\n            // tangential disturbance velocity\n            // computed by differentiating phi\n            //--------------------------------\n            if (j == 0) {                          // forward differencing\n                dphids0 = (phi(i,j+1)-phi(i,j))/(run_params.s0(k+1)-run_params.s0(k));\n            } else if(j == run_params.ne(i) - 1) { // backward differencing\n                dphids0 = (phi(i,j)-phi(i,j-1))/(run_params.s0(k)-run_params.s0(k-1));\n            } else {                               // second-order differencing\n                FLOATING_TYPE g1 = phi(i,j-1);\n                FLOATING_TYPE g2 = phi(i,j);\n                FLOATING_TYPE g3 = phi(i,j+1);\n                FLOATING_TYPE h1 = run_params.s0(k-1);\n                FLOATING_TYPE h2 = run_params.s0(k);\n                FLOATING_TYPE h3 = run_params.s0(k+1);\n                FLOATING_TYPE aa = ((g3-g2)/(h3-h2)-(g1-g2)/(h1-h2))/(h3-h1);\n                FLOATING_TYPE bb = (g3-g2)/(h3-h2)-aa*(h3-h2);\n                dphids0 = bb;\n            }\n            //---------------\n            // total velocity\n            //---------------\n\n            FLOATING_TYPE velx = run_params.dphidn0(k)*run_params.vnx0(k)+dphids0*run_params.tnx0(k);\n            FLOATING_TYPE vely = run_params.dphidn0(k)*run_params.vny0(k)+dphids0*run_params.tny0(k);\n\n            velx = velx + run_params.vx;        // add incident flow\n\n            //---\n            // add line vortex ring\n            //---\n\n            int iopt = 1;\n            FLOATING_TYPE ulvr, vlvr, psi;\n            lvr_fs<FLOATING_TYPE>(iopt, run_params.x0[k], run_params.y0[k], run_params.xlvr, run_params.ylvr, ulvr, vlvr, psi);\n \n            velx = velx + run_params.cr*ulvr;\n            vely = vely + run_params.cr*vlvr;\n\n            //-------------------------------\n            // tangential and normal velocity\n            // and pressure coefficient\n            //-------------------------------\n\n            // ...\n            velt(k) = velx*run_params.tnx0(k)+vely*run_params.tny0(k);\n            veln(k) = velx*run_params.vnx0(k)+vely*run_params.vny0(k);\n\n            //------------\n            // axial force\n            //------------\n\n            cp(k) = ONE<FLOATING_TYPE> - (velt(k)*velt(k)) / (run_params.vx*run_params.vx);\n\n            forcex = forcex + cp(k)*run_params.vnx0(k)*run_params.arel(k);\n            if (popt.verbose) {\n                std::cout << \"velt(\" << k << \"): \" << velt(k) << \" veln(\" << k << \"): \" << veln(k)\n                          << \" cp(\" << k << \"): \" << cp(k) << std::endl;\n            }\n\n            ++k;\n        }\n    }\n\n    std::cout << \"Axial Force: \" << forcex << std::endl;\n\n    //-------------------\n    // print the solution\n    //-------------------\n    std::ofstream sol_out(\"body_ax.out\");\n    if (sol_out) {\n        k = 0;\n        for (size_t i = 0; i < run_params.nsg; ++i) {\n            sol_out << run_params.ne[i] << std::endl;\n            for (size_t j = 0; j < run_params.ne[i]; ++j) {\n                sol_out << j << \" \"\n                        << run_params.x0(k) << \" \"\n                        << run_params.y0(k) << \" \"\n                        << run_params.s0(k) << \" \"\n                        << phi(i, j) << \" \" << velt(k) << \" \" << veln(k) << \" \" << cp(k) << std::endl;\n            \n                ++k;\n            }\n        }\n    }\n    sol_out << 0 << std::endl;\n    sol_out.close();\n\n    bool detailed_iso = true; //false;\n    FLOATING_TYPE dl, ux1, uy1, ux2, uy2;\n    int irk;\n\n    if (detailed_iso) {\n        dl    = static_cast<FLOATING_TYPE>(0.05) * static_cast<FLOATING_TYPE>(0.125);\n        irk   = 4;   // Runge-Kutta 4th order\n    } else {\n        dl    = static_cast<FLOATING_TYPE>(0.05);\n        irk   = 2;\n    }\n\n    //--------------------------\n    // prepare for crossing test\n    //--------------------------\n    bool icross;\n    if (popt.flow_type == to_underlying(FlowType::SPHERE)) {\n        icross = true;\n    } else if (popt.flow_type == to_underlying(FlowType::THORUS)) {\n        icross = false;\n    }\n\n    //--------------------------\n    // begin drawing streamlines\n    //--------------------------\n    std::ofstream fstr;\n    fstr.open(\"body_ax.asy\");\n    if (fstr) {\n        fstr <<\n                \"import graph;\\n\"\n                \"import patterns;\\n\"\n                \"size(350,350,IgnoreAspect);\\n\"\n                \"add(\\\"crosshatch\\\",crosshatch(3mm));\\n\"\n                \"\\n\"\n                \"pair reflect_y(pair pt)\\n\"\n                \"{\\n\"\n                \"  return (pt.x, -pt.y);\\n\"\n                \"}\\n\"\n                \"\\n\"\n                \"pair[] reflect_y(pair[] pts)\\n\"\n                \"{\\n\"\n                \"  pair[] ret;\\n\"\n                \"  for (int i = 0; i < pts.length; ++i) {\\n\"\n                \"    ret.push((pts[i].x, -pts[i].y));\\n\"\n                \"  }\\n\"\n                \"  return ret;\\n\"\n                \"}\\n\"\n                \"\\n\"\n                \"pair[][] toru = {\\n\";\n\n        for (size_t i = 0; i < run_params.nsg; ++i) {\n            fstr << \"  {\\n\";\n            for (size_t j = 0; j < run_params.ne[i]; ++j) {\n                fstr << \"(\" << run_params.xw(i,j) << \",\"  << run_params.yw(i,j) << \"),\\n\";\n            }\n            fstr << \"  },\\n\";\n        }\n\n        fstr << \"};\\n\"\n                \"pair[][] stream_lines = {\\n\";\n    }\n\n                \n\n    size_t n_streamlines = run_params.x00.size();\n    constexpr size_t mstr = 1200;\n    std::vector<FLOATING_TYPE> xstr, ystr; // for streamlines\n    xstr.reserve(mstr);\n    ystr.reserve(mstr);\n    for (size_t i = 0; i < n_streamlines; ++i) {\n        FLOATING_TYPE x00s = run_params.x00[i], y00s = run_params.y00[i];\n        FLOATING_TYPE xcross = x00s;   // to be used for crossing check\n\n        //------\n        xstr.clear();\n        ystr.clear();\n        for (size_t k = 0; k < mstr; ++k) {\n\n            xstr.push_back(x00s);\n            ystr.push_back(y00s);\n\n            //---------------\n            // integrate ODEs\n            //---------------\n\n            velocity<FLOATING_TYPE>(run_params, phi, run_params.dphidn0, x00s,y00s, ux1,uy1);\n\n            FLOATING_TYPE step = dl / std::sqrt(ux1*ux1 + uy1*uy1);     // set the frozen-time step\n\n            FLOATING_TYPE xsv = x00s;  // save\n            FLOATING_TYPE ysv = y00s;  // save\n\n            //----------------------\n            if (irk == 2) {\n            //----------------------\n\n                FLOATING_TYPE steph = HALF<FLOATING_TYPE> * step;\n\n                x00s = xsv + step * ux1;\n                y00s = ysv + step * uy1;\n\n                velocity<FLOATING_TYPE>(run_params, phi, run_params.dphidn0, x00s,y00s, ux2,uy2);\n\n                x00s = xsv + steph * (ux1 + ux2);\n                y00s = ysv + steph * (uy1 + uy2);\n\n            //---------------------------\n            } else if (irk == 4) {\n            //---------------------------\n\n                FLOATING_TYPE steph = HALF<FLOATING_TYPE> * step, ux3, uy3, ux4, uy4;\n                FLOATING_TYPE step6 = step / FLOATING_TYPE(6.0);\n\n                x00s = xsv + steph * ux1;\n                y00s = ysv + steph * uy1;\n\n                velocity<FLOATING_TYPE>(run_params, phi, run_params.dphidn0, x00s,y00s, ux2,uy2);\n\n                x00s = xsv + steph * ux2;\n                y00s = ysv + steph * uy2;\n\n                velocity<FLOATING_TYPE>(run_params, phi, run_params.dphidn0, x00s,y00s, ux3,uy3);\n\n                x00s = xsv + step * ux3;\n                y00s = ysv + step * uy3;\n\n                velocity<FLOATING_TYPE>(run_params, phi, run_params.dphidn0, x00s,y00s, ux4,uy4);\n\n                x00s = xsv + step/FLOATING_TYPE(6.0) * (ux1+FLOATING_TYPE(2.0)*ux2+FLOATING_TYPE(2.0)*ux3+ux4);\n                y00s = ysv + step/FLOATING_TYPE(6.0) * (uy1+FLOATING_TYPE(2.0)*uy2+FLOATING_TYPE(2.0)*uy3+uy4);\n\n            //-----------\n            }\n            //-----------\n\n            //---------------------------\n            // test for x=0 plane crossing\n            //---------------------------\n\n            if (icross) {\n                auto test = xcross*x00s;\n                if (test < ZERO<FLOATING_TYPE>) {\n                    std::cout << \" Crossed the x=0 plane: I will stop\\n\";\n                    break; // to the next streamline\n                }\n            }\n\n            //-------------------------\n            // test for sphere crossing\n            //-------------------------\n            if (icross) {\n                FLOATING_TYPE crosss = std::hypot(x00s-run_params.xcntr[0], y00s-run_params.ycntr[0]);\n                if (crosss < run_params.actis[0]) {\n                    xstr.pop_back();\n                    ystr.pop_back();\n                    goto finish_streamline;\n                }\n            }\n\n            //-----------------------\n            // window crossing checks\n            //-----------------------\n\n            if (x00s < run_params.xwmin) break;\n            if (x00s > run_params.xwmax) break;\n            if (y00s < run_params.ywmin) break;\n            if (y00s > run_params.ywmax) break;\n\n\n        } // k loop\n\n        xstr.push_back(x00s);\n        ystr.push_back(y00s);\n\nfinish_streamline:;\n        std::cout << \" One streamline with \" << xstr.size() << \" points completed\\n\";\n        if (fstr) {\n            fstr << \"{\\n\";\n            for (size_t i = 0; i < xstr.size(); ++i) {\n                fstr << '(' << xstr[i] << ',' << ystr[i] << \"),\\n\";\n            }\n            fstr << \"},\\n\";\n        }\n    }\n\n    if (fstr) {\n        fstr <<\n            \"};\\n\"\n            \"\\n\"\n            \"filldraw((toru[0][0]--toru[1][0]--toru[2][0]--cycle),magenta+0.7);\\n\"\n            \"filldraw((reflect_y(toru[0][0])--reflect_y(toru[1][0])--reflect_y(toru[2][0])--cycle),magenta+0.7);\\n\"\n            \"\\n\"\n            \"for (int i = 0; i < stream_lines.length; ++i) {\\n\"\n            \"  draw(graph(stream_lines[i]),            heavygreen+0.2);\\n\"\n            \"  draw(graph(reflect_y(stream_lines[i])), heavygreen+0.2);\\n\"\n            \"}\\n\"\n            \"\\n\"\n            \"real ticks[] = {-2,-1.5,-1,-0.5,0,0.5,1,1.5,2};\\n\"\n            \"\\n\"\n            \"xaxis(\\\"X\\\", BottomTop, LeftTicks(Label(fontsize(6pt)), ticks));\\n\"\n            \"yaxis(rotate(90)*\\\"Y\\\", LeftRight, RightTicks(Label(fontsize(6pt)), ticks));\\n\";\n    }\n\n}\n\n", "meta": {"hexsha": "eb4713b7b261e33df2446f76b8947ea8a3a22ac4", "size": 19847, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "body_ax/src/body_ax.cpp", "max_stars_repo_name": "alsam/cpp-samples", "max_stars_repo_head_hexsha": "abb14634b32dec9cfdfa8090ebee3df5e8479e6a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-04-14T15:42:59.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-18T10:51:29.000Z", "max_issues_repo_path": "body_ax/src/body_ax.cpp", "max_issues_repo_name": "alsam/cpp-samples", "max_issues_repo_head_hexsha": "abb14634b32dec9cfdfa8090ebee3df5e8479e6a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "body_ax/src/body_ax.cpp", "max_forks_repo_name": "alsam/cpp-samples", "max_forks_repo_head_hexsha": "abb14634b32dec9cfdfa8090ebee3df5e8479e6a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-29T13:57:21.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-29T13:57:21.000Z", "avg_line_length": 34.4565972222, "max_line_length": 127, "alphanum_fraction": 0.4818360457, "num_tokens": 5252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.280143708943101}}
{"text": "#define BIORBD_API_EXPORTS\n#include \"Utils/Quaternion.h\"\n\n#include <Eigen/Dense>\n#include <rbdl/Quaternion.h>\n\nbiorbd::utils::Quaternion::Quaternion () :\n    RigidBodyDynamics::Math::Quaternion(),\n    m_Kstab(100)\n{\n\n}\n\nbiorbd::utils::Quaternion::Quaternion (const Eigen::Vector4d &vec4) :\n    RigidBodyDynamics::Math::Quaternion(vec4),\n    m_Kstab(100)\n{\n\n}\n\nbiorbd::utils::Quaternion::Quaternion (\n        double x,\n        double y,\n        double z,\n        double w) :\n    RigidBodyDynamics::Math::Quaternion(x, y, z, w),\n    m_Kstab(100)\n{\n\n}\n\nbiorbd::utils::Quaternion::Quaternion (\n        const Eigen::Vector3d &vec4,\n        double w) :\n    RigidBodyDynamics::Math::Quaternion(vec4(0), vec4(1), vec4(2), w),\n    m_Kstab(100)\n{\n\n}\n\nbiorbd::utils::Quaternion& biorbd::utils::Quaternion::operator=(\n        const Eigen::Vector4d& vec4)\n{\n    if (this==&vec4) // check for self-assigment\n        return *this;\n\n    *this = vec4;\n    return *this;\n}\n\n\ndouble biorbd::utils::Quaternion::w() const\n{\n    return (*this)(3);\n}\ndouble biorbd::utils::Quaternion::x() const\n{\n    return (*this)(0);\n}\ndouble biorbd::utils::Quaternion::y() const\n{\n    return (*this)(1);\n}\ndouble biorbd::utils::Quaternion::z() const\n{\n    return (*this)(2);\n}\n\nvoid biorbd::utils::Quaternion::derivate(\n        const Eigen::VectorXd &w)\n{\n\n    // Création du quaternion de \"préproduit vectoriel\"\n    double qw = (*this)(3);\n    double qx = (*this)(0);\n    double qy = (*this)(1);\n    double qz = (*this)(2);\n    Eigen::Matrix4d Q;\n    Q <<    qw, -qx, -qy, -qz,\n            qx,  qw, -qz,  qy,\n            qy,  qz,  qw, -qx,\n            qz, -qy,  qx,  qw;\n\n    // Ajout du paramètre de stabilisation\n    Eigen::Vector4d w_tp (m_Kstab*w.norm()*(1-this->norm()), w(0), w(1), w(2));\n    biorbd::utils::Quaternion quatDot(0.5 * Q * w_tp);\n    biorbd::utils::Quaternion quatDot_tp(Eigen::Vector4d(quatDot(1), quatDot(2), quatDot(3), quatDot(0)));\n    *this =  quatDot_tp; // Le quaternion est tourné à cause de la facon dont est faite la multiplication\n}\n", "meta": {"hexsha": "995469e4967c2c1d6d1aaef968876ae5aa6ccb13", "size": 2030, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Quaternion.cpp", "max_stars_repo_name": "vincentdelpech/biorbd", "max_stars_repo_head_hexsha": "0d7968e75e182f067a4d4c24cc15fa9a331ca792", "max_stars_repo_licenses": ["MIT"], "max_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/Quaternion.cpp", "max_issues_repo_name": "vincentdelpech/biorbd", "max_issues_repo_head_hexsha": "0d7968e75e182f067a4d4c24cc15fa9a331ca792", "max_issues_repo_licenses": ["MIT"], "max_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/Quaternion.cpp", "max_forks_repo_name": "vincentdelpech/biorbd", "max_forks_repo_head_hexsha": "0d7968e75e182f067a4d4c24cc15fa9a331ca792", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5555555556, "max_line_length": 106, "alphanum_fraction": 0.6108374384, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.4610167793123158, "lm_q1q2_score": 0.28014291746307246}}
{"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#ifndef ITL_ITL_FWD_INCLUDE\n#define ITL_ITL_FWD_INCLUDE\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n\nnamespace itl {\n\n    template <class Real>                class basic_iteration;\n    template <class Real, class OStream> class cyclic_iteration;\n    template <class Real, class OStream> class noisy_iteration;\n\n    template <typename Solver, typename VectorIn, bool trans> class solver_proxy;\n\n    namespace pc {\n\n\ttemplate <typename PC, typename Vector, bool> struct solver;\n\ttemplate <typename Matrix, typename Value> class identity;\n\t// template <typename Matrix, typename Value, typename Vector> Vector solve(const identity<Matrix>&, const Vector& x);\t\n\t// template <typename Matrix, typename Vector> Vector adjoint_solve(const identity<Matrix>&, const Vector& x);\n\n\ttemplate <typename Matrix, typename Value> class diagonal;\n\t// template <typename Matrix, typename Vector> Vector solve(const diagonal<Matrix>& P, const Vector& x);\n\t// template <typename Matrix, typename Vector> Vector adjoint_solve(const diagonal<Matrix>& P, const Vector& x);\n\n\ttemplate <typename Matrix, typename Factorizer, typename Value> class ilu;\n\ttemplate <typename Matrix, typename Value> class ilu_0; // Maybe we should declare the default here???\n\ttemplate <typename Matrix, typename Value> class ilut; // Maybe we should declare the default here???\n\t// template <typename Matrix, typename Vector> Vector solve(const ilu_0<Matrix>& P, const Vector& x);\n\t// template <typename Matrix, typename Vector> Vector adjoint_solve(const ilu_0<Matrix>& P, const Vector& x);\n\n\ttemplate <typename Matrix, typename Value> class ic_0; // Maybe we should declare the default here???\n\t// template <typename Matrix, typename Vector> Vector solve(const ic_0<Matrix>& P, const Vector& x);\n\t// template <typename Matrix, typename Value, typename Vector> Vector adjoint_solve(const ic_0<Matrix, Value>& P, const Vector& x);\n\n    } //  namespace pc\n\n    template < typename LinearOperator, typename HilbertSpaceX, typename HilbertSpaceB, \n\t       typename Preconditioner, typename Iteration >\n    int cg(const LinearOperator& A, HilbertSpaceX& x, const HilbertSpaceB& b, \n\t   const Preconditioner& M, Iteration& iter);\n\n    template < typename LinearOperator, typename Preconditioner= pc::identity<LinearOperator, double>, \n\t       typename RightPreconditioner= pc::identity<LinearOperator, double> >\n    class cg_solver;\n\n\n    template < typename LinearOperator, typename Vector, \n\t       typename Preconditioner, typename Iteration >\n    int bicg(const LinearOperator &A, Vector &x, const Vector &b,\n\t     const Preconditioner &M, Iteration& iter);\n\n    template < class LinearOperator, class HilbertSpaceX, class HilbertSpaceB, \n\t       class Preconditioner, class Iteration >\n    int bicgstab(const LinearOperator& A, HilbertSpaceX& x, const HilbertSpaceB& b, \n\t\t const Preconditioner& M, Iteration& iter);\n\n    template < class LinearOperator, class HilbertSpaceX, class HilbertSpaceB, \n\t       class Preconditioner, class Iteration >\n    int bicgstab_2(const LinearOperator& A, HilbertSpaceX& x, const HilbertSpaceB& b, \n\t\t   const Preconditioner& M, Iteration& iter);\n\n    template < typename LinearOperator, typename Vector, \n\t       typename LeftPreconditioner, typename RightPreconditioner, \n\t       typename Iteration >\n    int bicgstab_ell(const LinearOperator &A, Vector &x, const Vector &b,\n\t\t     const LeftPreconditioner &L, const RightPreconditioner &R, \n\t\t     Iteration& iter, size_t l);\n\n    template < typename LinearOperator, typename Preconditioner= pc::identity<LinearOperator, double>, \n\t       typename RightPreconditioner= pc::identity<LinearOperator, double> >\n    class bicgstab_ell_solver;\n\n    template <typename Solver, unsigned N, bool Stored= false>\n    class repeating_solver;\n\n} // namespace itl\n\n#endif // ITL_ITL_FWD_INCLUDE\n", "meta": {"hexsha": "15ddadbd2c5af1c16a356b3f0ef7518daffefd4a", "size": 4279, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/itl/itl_fwd.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/itl/itl_fwd.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/itl/itl_fwd.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": 47.021978022, "max_line_length": 132, "alphanum_fraction": 0.7396587988, "num_tokens": 1015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5273165233795672, "lm_q1q2_score": 0.28011547995408764}}
{"text": "#include <iostream>\n#include <fstream>\n#include <queue>\n#include <vector>\n#include <utility>\n#include <stdlib.h>\n#include <unordered_set>\n#include <boost/graph/adjacency_list.hpp>\n// #include <boost/graph/vf2_sub_graph_iso.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <boost/graph/subgraph.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include \"metis.h\"\n\ntemplate <class Edge>\nstruct myhash\n{\n    std::size_t operator()(Edge const& e) const\n    {\n        return _h(e.idx);\n    }\n};\n\n\nusing namespace std;\nusing namespace boost;\n\n// global declarations\nconst int K = 2;                                            // TODO: Change this to main param\nidx_t ncon = 1;                                             // default METIS tuning param\nidx_t nparts = K;                                           // set num partition to K\n\n\nint main(int argc, char* argv[])\n{\n    // error check\n    if (argc != 3)\n    {\n        cout << \"usage: main.exe inputFile outputFile\" << endl;\n        cout << \"inputFile must be in graphviz dot file format.\" << endl;\n        return 1;\n    }\n    \n    //********************************** Declarations **********************************\n\t\n    // typedef declarations for templates\n    typedef subgraph< adjacency_list<vecS, vecS, undirectedS, uint32_t,\n        property< edge_index_t, int > > > graph_type;\n    typedef graph_traits<graph_type>::vertex_iterator vertex_iter;\n    typedef graph_traits<graph_type>::edge_iterator edge_iter;\n    typedef graph_traits<graph_type>::out_edge_iterator out_edge_iter;\n    typedef std::pair<vertex_iter, vertex_iter> vrange_t;\n    typedef graph_traits<graph_type>::adjacency_iterator adj_iter;\n    typedef std::pair<adj_iter, adj_iter> adjrange_t;\n    typedef property_map<graph_type, vertex_index_t>::type IndexMap;\n    typedef graph_traits<graph_type>::vertex_descriptor v_descriptor;\n    typedef graph_traits<graph_type>::edge_descriptor e_descriptor;\n    typedef std::vector<v_descriptor> vert_vec;\n    typedef std::pair< v_descriptor, int > hop_pair_t;\n    typedef std::vector<hop_pair_t> avt_vector_t;\n    typedef std::queue<hop_pair_t> vert_que;\n    typedef std::vector<bool> colormap;\n    typedef std::vector<int> score_vec;\n    typedef std::pair<v_descriptor, bool> found_t;\n    //typedef std::unordered_set<e_descriptor, typename myhash> u_set_t;\n    typedef std::set<e_descriptor> u_set_t;\n\n    //*** variable declarations ***\n\n    // The root graph\n    graph_type graph1(0);\n\n    // subgraphs from the root\n    graph_type *subgraph_vect = new graph_type[K];\n\n    // METIS library args\n    idx_t nvert;\n    int nedge;\n    idx_t *xadj;\n    idx_t *adjncy;\n    idx_t objval;\n    idx_t *part;\n    idx_t options[METIS_NOPTIONS];\n\n    // The graphviz dot file\n    ifstream inputFile;\n    \n    // Output graphviz dot file\n    ofstream outputFile;\n    // ostream& os = cout;\n\n    // iterators\n    vrange_t vpair;\n    int i = 0;\n    int j = 0;\n    graph_type::children_iterator ci;\n    graph_type::children_iterator ci_end;\n    vertex_iter v;\n    vertex_iter v_end;\n    //    vertex_iter v_next_col;\n    edge_iter e;\n    edge_iter e_end;\n    out_edge_iter child_e;\n    out_edge_iter child_e_end;\n    out_edge_iter parent_e;\n    out_edge_iter parent_e_end;\n    adj_iter vi;\n    adj_iter vi_end;\n\n    // index for random access\n    IndexMap index;\n\n    // Alignment Vertex table\n    vert_vec *avt = new vert_vec[K];\n    int *avt_lookup;\n    avt_vector_t *avt_unmatched = new avt_vector_t[K];      // to store intermediate results\n    v_descriptor *avtrow = new v_descriptor[K];             // the initial row\n    int avtRows;                                            // number of rows in table\n    int hopcount;\n    int degrees;\n    int score;\n    int bestscore;\n    int pos_right;\n    int best_position;\n    int maxlength;\n    score_vec *score_table = new score_vec[K];\n    v_descriptor bestV;\n    hop_pair_t hopPair;\n    \n    // colormap & que used in BFS\n    colormap *clr_arr = new colormap[K];\n    vert_que *vque_arr = new vert_que[K];\n    \n    // edge copy\n    u_set_t edge_set;\n    u_set_t added_edge_set;\n    found_t found;\n    int from;\n    int to;\n\n    // descriptors\n    v_descriptor vLocalID;\n    v_descriptor vGlobalID;\n    v_descriptor orig_source;\n    v_descriptor orig_target;\n    v_descriptor copy_source;\n    v_descriptor copy_target;\n    e_descriptor eLocalID;\n    e_descriptor eGlobalID;\n    \n    \n    \n    //********************************** Reading and Building Graph **********************************\n    // Read in the graph from disk\n    inputFile.open(argv[1]);\n    dynamic_properties dp(ignore_other_properties);\n    read_graphviz(inputFile, graph1, dp);\n    inputFile.close();\n\n    //Initialize Graph-Dependent Variables\n    nvert = num_vertices(graph1);\n    nedge = num_edges(graph1);\n    xadj = new idx_t[nvert + 1];\n    adjncy = new idx_t[nedge * 2];\n    part = new idx_t[nvert];\n    index = get(vertex_index, graph1);\n    \n\t\n    //********************************** Partition the graph with METIS algorithm **********************************\n    // initialise\n    METIS_SetDefaultOptions(options);\n    xadj[0] = 0;\n\n    // Transform the adjacency list into the Compressed Storage Format\n    // TODO: consider using tie function - syntactic sugar\n    for(vpair = vertices(graph1); vpair.first != vpair.second; ++vpair.first)\n    {\n        xadj[i+1] = xadj[i] + out_degree(*vpair.first, graph1);\n        adjrange_t adjpair = adjacent_vertices(*vpair.first, graph1);\n        j = xadj[i];\n        for(adjpair.first; adjpair.first != adjpair.second; ++adjpair.first)\n        {\n            adjncy[j] = *adjpair.first;\n            ++j;\n        }\n        ++i;\n    }\n\n    // Print out to verify\n    cout << \"METIS partitioning: \" << endl;\n    for(i = 0; i < nvert + 1; ++i)\n    {\n        cout << xadj[i] << ' ';\n    }\n    cout << endl;\n    for(i = 0; i < nedge * 2; ++i)\n    {\n        cout << adjncy[i] << ' ';\n    }\n    cout << endl;\n\n    // Use k-way graph partition algorithm\n    objval = 0;\n    METIS_PartGraphKway(&nvert, &ncon, xadj, adjncy, NULL, NULL, NULL, &nparts, NULL, NULL, NULL, &objval, part);\n\n    // Print out the partition vector\n    for(i=0; i < nvert; ++i)\n    {\n        cout << part[i] << ' ';\n    }\n    cout << endl;\n\n\t//********************************** Create Subgraphs based on METIS result **********************************\n    // Create induced subgraphs based on partition vector\n    for (i=0; i<K; ++i)\n    {\n        subgraph_vect[i] = graph1.create_subgraph();\n    }\n    for (i=0; i < nvert; ++i)\n    {\n        cout << \"Mapping \" << index[i] << \" to subgraph \" << part[i] << endl;\n        add_vertex(index[i], subgraph_vect[part[i]]);\n    }\n\t\n\t// print for testing\n\n    //This will print out the global vertex IDs from the root graph\n    cout << \"root:\" << endl;\n    print_graph(graph1, get(vertex_index, graph1));\n    cout << endl;\n    for (i=0; i < K; ++i)\n    {\n        cout << \"subgraph \" << i << \":\" << endl;\n        cout << \"vertices = \";\n        for (boost::tie(v, v_end) = vertices(subgraph_vect[i]); v != v_end; ++v)\n        {\n            cout << subgraph_vect[i].local_to_global(*v) << \", \";\n        }\n        cout << endl;\n        cout << \"edges = \";\n        for (boost::tie(e, e_end) = edges(subgraph_vect[i]); e != e_end; ++e)\n        {\n            cout << subgraph_vect[i].local_to_global(*e) << \", \";\n        }\n        cout << endl;\n    }\n\n    \n    //********************************** Building the AVT **********************************\n    // Start to build the AVT\n    // Each vector will represent a column in the table\n    // Each column in the table represents a subgraph\n\n    // Build colormap\n    // First step is to create the initial row\n    for (i=0; i < K; ++i)\n    {\n        int maxdegree = 0;\n        v_descriptor vertID = 0;\n        // cout << \"cp4\" << endl;\n\n        for (boost::tie(v, v_end) = vertices(subgraph_vect[i]); v != v_end; ++v)\n        {\n            int temp = out_degree(*v, subgraph_vect[i]);\n            if (temp > maxdegree)\n            {\n                maxdegree = temp;\n                vertID = *v;\n                avtrow[i] = vertID;\n            }\n            // cout << \"maxdegree = \" << maxdegree << endl;\n            // while we are processing every vertex in each subgraph\n            // initialise the colormap\n            clr_arr[i].push_back(false) ;\n        }\n    }\n\n    //Print out the color array\n    cout << std::boolalpha;\n    for(i=0; i<K; ++i)\n    {\n        for(j=0; j < clr_arr[i].size(); ++j)\n        {\n            cout << clr_arr[i][j] << ' ';\n        }\n        cout << endl;\n    }\n\n    // Print out the starting point of AVT\n    cout << endl << \"AVT:\" <<endl;\n    for (i=0; i<K; ++i)\n    {\n        cout << subgraph_vect[i].local_to_global(avtrow[i]) << ' ';\n    }\n    cout << endl;\n    \n    // Load in the first row\n    for(i=0; i<K; ++i)\n    {\n        avt_unmatched[i].push_back(std::make_pair(avtrow[i], 0));\n    }\n\n    // build ques for BFS\n    for(i=0; i<K; ++i)\n    {\n        vque_arr[i].push(std::make_pair(avtrow[i], 0));\n    }\n\n    // Process using BFS\n    // Mark all starting nodes as visited\n    for (i=0; i < K; ++i)\n    {\n        index = get(vertex_index, subgraph_vect[i]);\n\n        clr_arr[i][index[avtrow[i]]] = true;\n    }\n\n    // Print  out the color array\n    cout << std::boolalpha;\n    for(i=0; i<K; ++i)\n    {\n        for(j=0; j < clr_arr[i].size(); ++j)\n        {\n            cout << clr_arr[i][j] << ' ';\n        }\n        cout << endl;\n    }\n\n    // Process the que\n\t//*** Breadth First Search ***\n    for(i=0; i < K; ++i)\n    {\n        while (vque_arr[i].empty()==false)\n        {\n            //  v_descriptor vGlobalID = vque_arr[i].front();\n            //  v_descriptor vLocalID = subgraph_vect[i].global_to_local(vGlobalID);\n            hopPair = vque_arr[i].front();\n\n            vLocalID = hopPair.first;\n            hopcount = hopPair.second;\n            //  cout << \"Processing BFS node: \" << vLocalID << endl;\n            cout << \"Processing BFS node: \" << index[vLocalID] << endl;\n            index = get(vertex_index, subgraph_vect[i]);\n            vque_arr[i].pop();\n            for(boost::tie(vi, vi_end) = adjacent_vertices(vLocalID, subgraph_vect[i]); vi != vi_end; ++vi)\n            {\n                //  cout << subgraph_vect[i][*vi] << endl;\n                //  cout << graph1[*vi] << endl;\n                if(clr_arr[i][index[*vi]] == false)\n                {\n                    cout << \"Processing adjacent node: \" << index[*vi] << endl;\n                    vque_arr[i].push(std::make_pair(*vi, hopcount+1));\n                    avt_unmatched[i].push_back(std::make_pair(*vi, hopcount+1));\n                    clr_arr[i][index[*vi]] = true;\n                    // Print out the color map as updated\n                    for(int z=0; z<K; ++z)\n                    {\n                        for(j=0; j < clr_arr[z].size(); ++j)\n                        {\n                            cout << clr_arr[z][j] << ' ';\n                        }\n                        cout << endl;\n                    }\n                }\n            }\n        }\n    }\n    \n    // Print out the AVT\n    cout << endl << \"AVT (unmatched - UNbalanced) <read this sideways>:\" << endl;\n    for(i=0; i < K; ++i)\n    {\n        avtRows = avt_unmatched[i].size();\n        for(j=0; j < avtRows; ++j)\n        {\n            cout << subgraph_vect[i].local_to_global(avt_unmatched[i][j].first) << '(' << avt_unmatched[i][j].second << \") \";\n        }\n        cout << endl;\n    }\n    cout << endl;\n\n    // balance out the table if odd number of vertices\n    // find the max length column\n    maxlength = 0;\n    for (i=0; i<K; ++i)\n    {\n        if (avt_unmatched[i].size() > maxlength)\n        {\n            maxlength = avt_unmatched[i].size();\n        }\n    }\n\t\n    //Add vertices until all columns are maxlength\n    for (i=0; i<K; ++i)\n    {\n\t\twhile (avt_unmatched[i].size() < maxlength)\n    \t{\n\t    \tvLocalID = add_vertex(subgraph_vect[i]);\n\t\t\tavt_unmatched[i].push_back(std::make_pair(vLocalID, 99));\n\t\t\tclr_arr[i].push_back(false);\n    \t}\n    }\n\n\t\n    // Print out the AVT\n    cout << endl << \"AVT (unmatched - balanced) <read this sideways>:\" << endl;\n    for(i=0; i < K; ++i)\n    {\n        avtRows = avt_unmatched[i].size();\n        for(j=0; j < avtRows; ++j)\n        {\n            cout << subgraph_vect[i].local_to_global(avt_unmatched[i][j].first) << '(' << avt_unmatched[i][j].second << \") \";\n        }\n        cout << endl;\n    }\n    cout << endl;\n    \n    \n    //********************************** using local scores **********************************\n    \n    // use colormap for tracking matches\n    // initialise\n    for(i=0; i<K; ++i)\n    {\n        for(j=0; j < clr_arr[i].size(); ++j)\n        {\n            if(j==0)\n            {\n                clr_arr[i][j] = true;\n            }\n            else\n            {\n                clr_arr[i][j] = false;\n            }\n        }\n    }\n    \n    // Print  out the color array\n    for(i=0; i<K; ++i)\n    {\n        for(j=0; j < clr_arr[i].size(); ++j)\n        {\n            cout << clr_arr[i][j] << ' ';\n        }\n        cout << endl;\n    }\n    \n    // create the avt_lookup table\n    // We used a 2d array flattened to 1d\n    // The values in this table are the index positions in the avt\n    // Every time we push into avt we update avt_lookup\n    avt_lookup = new int[K * avt_unmatched[0].size()];\n    \n    // copy the first column as is\n    \n    //use index to index into avt_lookup\n    index = get(vertex_index, subgraph_vect[0]);\n    for (i=0; i < avt_unmatched[0].size(); ++i)\n    {\n        avt[0].push_back(avt_unmatched[0][i].first);\n        avt_lookup[index[avt_unmatched[0][i].first]] = i;\n    }\n    // match from left to right by score\n    // score of 0 is considered a perfect match\n    // as in same degree and same distance from hub\n    \n    // for each column, fill in next column row by row\n    for (i=0; i < K-1; ++i)\n    {\n        // copy the first row as is\n        avt[i+1].push_back(avt_unmatched[i+1][0].first);\n        // get new index for each subgraph\n        index = get(vertex_index, subgraph_vect[i]);\n        avt_lookup[(i+1) * avt_unmatched[0].size() + (index[avt_unmatched[i+1][0].first])] = i;\n        \n        // for each item in left column, match against items in right column\n        // skip over first iteration so j=1\n        for(j=1; j < avt[0].size(); ++j)\n        {\n            cout << \"avt size=\" << avt[i].size() << endl;\n            bestscore = 10000;  // initialise to silly high number; track best score so far\n            pos_right = 0;      // current position of item on right\n            best_position = 0;  // save position of best match\n            // for each item in right column see if that item is a good match\n            for(auto v_next_col = avt_unmatched[i+1].begin(); v_next_col != avt_unmatched[i+1].end(); ++v_next_col)\n            {\n                if(clr_arr[i+1][pos_right] == false)\n                {\n                    int dleft = out_degree(avt_unmatched[i][j].first, subgraph_vect[i]);\n                    int dright = out_degree(v_next_col->first, subgraph_vect[i+1]);\n                    cout << \"comparing \" << subgraph_vect[i].local_to_global(avt_unmatched[i][j].first) << \" to \" << subgraph_vect[i+1].local_to_global(v_next_col->first) << endl;\n                    cout << \"degree left: \" << dleft\n                        << \" degree right: \" << dright\n                        << endl;\n                    degrees = std::abs(dleft - dright);\n                    hopcount = std::abs(avt_unmatched[i][j].second - v_next_col->second);\n                    score = degrees + hopcount;  // can change to weighted score\n                    cout << \"degree diff: \" << degrees << \" hopcount diff: \" << hopcount << \" score: \" << score << endl;\n                    if(score < bestscore)\n                    {\n                        bestscore = score;\n                        vLocalID = v_next_col->first;\n                        best_position = pos_right;\n                    }\n                }\n                ++pos_right;\n            }\n            \n            // update the colormap, push in to avt, update lookup table\n            clr_arr[i+1][best_position] = true;\n            avt[i+1].push_back(vLocalID);\n            avt_lookup[(i + 1) * avt_unmatched[i+1].size() + (index[avt_unmatched[i+1][best_position].first])] = j;\n        }\n        \n    }\n    \n    // Print out the lookup table\n    for(i = 0; i < avt[0].size() * K; ++i)\n    {\n       if(i % avt[0].size() == 0)\n       {\n           cout << endl;\n       }\n       cout << avt_lookup[i] << ' ';\n    }\n    cout << endl;\n\n    // Print  out the color array\n    for(i=0; i<K; ++i)\n    {\n        for(j=0; j < clr_arr[i].size(); ++j)\n        {\n            cout << clr_arr[i][j] << ' ';\n        }\n        cout << endl;\n    }\n\n    // Print out the AVT\n    cout << endl << \"AVT <read this sideways>:\" << endl;\n    for(i=0; i < K; ++i)\n    {\n        avtRows = avt[i].size();\n        for(j=0; j < avtRows; ++j)\n        {\n            cout << subgraph_vect[i].local_to_global(avt[i][j]) << ' ';\n        }\n        cout << endl;\n    }\n    cout << endl;\n\t\n\t//********************************** Perform Block Alignment **********************************\n\n\t//*** First add all edges to the first column ***\n\t//*** first column will become the rolemodel ***\n\tadj_iter one;\n\tadj_iter one_end;\n\tadj_iter two;\n\tadj_iter two_end;\n\tbool matchFound;\n\t//*** Make the first column the rolemodel with all edges copied ***\n\tfor(i = 0; i < avt[0].size(); ++i)\n\t{\n\t\tfor(j = 1; j < K; ++j)\n\t\t{\n\t\t\tindex = get(vertex_index ,subgraph_vect[j]);\n\t\t\tfor(boost::tie(two, two_end) = adjacent_vertices(avt[j][i], subgraph_vect[j]); two != two_end; ++two)\n\t\t\t{\n\t\t\t\t//find pair to vertex in column one\n\t\t\t\tv_descriptor pair_vertex = index[avt[0][avt_lookup[j * avt[0].size() + (*two)]]];\n\t\t\t\tmatchFound = false;\n\t\t\t\tfor(boost::tie(one, one_end) = adjacent_vertices(avt[0][i], subgraph_vect[0]); one != one_end; ++one)\n\t\t\t\t{\n\t\t\t\t\tif(pair_vertex == *one)\n\t\t\t\t\t{\n\t\t\t\t\t\tmatchFound = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(matchFound == false)\n\t\t\t\t\tadd_edge(avt[0][i], pair_vertex, subgraph_vect[0]);\n\t\t\t}\n\t\t}\n\t}\n\t//*** compare all other columns to the rolemodel column and add edges ***\n\tfor(i = 0; i < avt[0].size(); ++i)\n\t{\n\t\tfor(j = 1; j < K; ++j)\n\t\t{\n\t\t\tindex = get(vertex_index ,subgraph_vect[0]);\n\t\t\tfor(boost::tie(one, one_end) = adjacent_vertices(avt[0][i], subgraph_vect[0]); one != one_end; ++one)\n\t\t\t{\n\t\t\t\tv_descriptor pair_vertex = index[avt[j][avt_lookup[*one]]];\n\t\t\t\tmatchFound = false;\n\t\t\t\tfor(boost::tie(two, two_end) = adjacent_vertices(avt[j][i], subgraph_vect[j]); two != two_end; ++two)\n\t\t\t\t{\n\t\t\t\t\tif(pair_vertex == *two)\n\t\t\t\t\t{\n\t\t\t\t\t\tmatchFound = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(matchFound == false)\n\t\t\t\t\tadd_edge(avt[j][i], pair_vertex, subgraph_vect[j]);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t// print results of block alignment\n    cout << \"root:\" << endl;\n    print_graph(graph1, get(vertex_index, graph1));\n    cout << endl;\n    for (i=0; i < K; ++i)\n    {\n        cout << \"subgraph \" << i << \":\" << endl;\n        cout << \"vertices = \";\n        for (boost::tie(v, v_end) = vertices(subgraph_vect[i]); v != v_end; ++v)\n        {\n            cout << subgraph_vect[i].local_to_global(*v) << \", \";\n        }\n        cout << endl;\n        cout << \"edges = \";\n        for (boost::tie(e, e_end) = edges(subgraph_vect[i]); e != e_end; ++e)\n        {\n            cout << subgraph_vect[i].local_to_global(*e) << \", \";\n        }\n        cout << endl;\n    }\n\t\n\t//********************************** Perform Edge Copy **********************************\n    // for each child subgraph\n    for (i=0; i < K; ++i)\n    {\n        cout << \"cp1\" << endl;\n        // for each vertex in subgraph, compare degree to parent vertex\n        for(boost::tie(v, v_end) = vertices(subgraph_vect[i]); v != v_end; ++v)\n        {\n            // if degrees don't match then there is at least one crossing edge\n            cout << \"comparing subgraph \" << i << ' ' << *v << \" to \" << subgraph_vect[i].local_to_global(*v) << endl;\n            if (out_degree(*v, subgraph_vect[i]) != out_degree(subgraph_vect[i].local_to_global(*v), graph1))\n            {\n                cout << \"Detected a crossing edge from vertex: \" << subgraph_vect[i].local_to_global(*v) << endl;\n                // for each child edge, load into hash table\n                edge_set.clear();\n                for(boost::tie(child_e, child_e_end) = out_edges(*v, subgraph_vect[i]); child_e != child_e_end; ++child_e)\n                {\n                    eGlobalID = subgraph_vect[i].local_to_global(*child_e);\n                    edge_set.insert(eGlobalID);\n                }\n                // for each edge of parent vertex, check if it's in hash table\n                for(boost::tie(parent_e, parent_e_end) = out_edges(subgraph_vect[i].local_to_global(*v), graph1); parent_e != parent_e_end; ++ parent_e)\n                {\n                    if(edge_set.find(*parent_e) == edge_set.end()\n                        && added_edge_set.find(*parent_e) == added_edge_set.end())\n                    {\n                        // do edge copy\n                        // get the source & target of the edge\n                        orig_source = source(*parent_e, graph1);\n                        orig_target = target(*parent_e, graph1);\n                        cout << \"edge source \" << orig_source << \" target \" << orig_target << endl;\n                        // find them in the avt\n                        // use avt_lookup to find the index of the source\n                        index = get(vertex_index, subgraph_vect[i]);\n                        vLocalID = subgraph_vect[i].global_to_local(orig_source);\n                        from = avt_lookup[i * avt[0].size() + index[vLocalID]];\n                        // find the subgraph of the target & get it's local ID\n                        for (j=0; j < K; ++j)\n                        {\n                            found = subgraph_vect[j].find_vertex(orig_target);\n                            if(found.second)\n                            {\n                                // do lookup of the target\n                                index = get(vertex_index, subgraph_vect[j]);\n                                vLocalID = found.first;\n                                to = avt_lookup[j * avt[0].size() + index[vLocalID]];\n                                copy_source = subgraph_vect[j].local_to_global(avt[j][from]);\n                                copy_target = subgraph_vect[i].local_to_global(avt[i][to]);\n                                cout << \"i=\" << i << \" j=\" << j << \" from=\" << from << \" to=\" << to << endl;\n                                if(edge(copy_source, copy_target, graph1).second == false)\n                                {\n                                    add_edge(copy_source, copy_target, graph1);\n                                    added_edge_set.insert(eGlobalID);\n                                }\n                                break;\n                            }\n                        }\n                        \n                    }\n                }\n            }\n        }\n    }\n    \n    // *******End***********\n    \n    cout << endl;\n    // Dump the output to file\n    outputFile.open(argv[2]);\n    write_graphviz_dp(outputFile, graph1, dp.property(\"node_id\", get(boost::vertex_index, graph1)));\n    // uncomment this to print dot file to std out\n    //write_graphviz_dp(cout, graph1, dp.property(\"node_id\", get(boost::vertex_index, graph1)));\n    outputFile.close();\n    // also print out to std out\n    cout << \"root:\" << endl;\n    print_graph(graph1, get(vertex_index, graph1));\n    cout << endl;\n    for (i=0; i < K; ++i)\n    {\n        cout << \"subgraph \" << i << \":\" << endl;\n        cout << \"vertices = \";\n        for (boost::tie(v, v_end) = vertices(subgraph_vect[i]); v != v_end; ++v)\n        {\n            cout << subgraph_vect[i].local_to_global(*v) << \", \";\n        }\n        cout << endl;\n        cout << \"edges = \";\n        for (boost::tie(e, e_end) = edges(subgraph_vect[i]); e != e_end; ++e)\n        {\n            cout << subgraph_vect[i].local_to_global(*e) << \", \";\n        }\n        cout << endl;\n    }\n    \n    \n    //cleanup\n    // TODO: move these higher\n    delete[] xadj;\n    delete[] adjncy;\n    delete[] part;\n    delete[] subgraph_vect;\n    delete[] avt;\n    delete[] avt_lookup;\n    delete[] avtrow;\n    delete[] clr_arr;\n    delete[] vque_arr;\n    delete[] avt_unmatched;\n    delete[] score_table;\n    xadj = NULL;\n    adjncy = NULL;\n    part = NULL;\n    subgraph_vect = NULL;\n    avt = NULL;\n    avtrow = NULL;\n    clr_arr = NULL;\n    vque_arr = NULL;\n    avt_unmatched = NULL;\n    score_table = NULL;\n    avt_lookup = NULL;\n\n    return 0;\n}\n", "meta": {"hexsha": "80265da779cd75a341f69b5fa3cd6279cdfbff54", "size": 24715, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test_main.cpp", "max_stars_repo_name": "McFlip/k-automorphic-graph", "max_stars_repo_head_hexsha": "c161e57c411f690af6da3ef5bf1dafd282aba544", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T03:43:29.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-10T03:43:29.000Z", "max_issues_repo_path": "test_main.cpp", "max_issues_repo_name": "McFlip/k-automorphic-graph", "max_issues_repo_head_hexsha": "c161e57c411f690af6da3ef5bf1dafd282aba544", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test_main.cpp", "max_forks_repo_name": "McFlip/k-automorphic-graph", "max_forks_repo_head_hexsha": "c161e57c411f690af6da3ef5bf1dafd282aba544", "max_forks_repo_licenses": ["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.997329773, "max_line_length": 179, "alphanum_fraction": 0.5111875379, "num_tokens": 6379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.2801154799540876}}
{"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/iborcoupon.hpp>\n#include <ql/indexes/iborindex.hpp>\n#include <ql/math/solvers1d/brent.hpp>\n#include <qle/pricingengines/analyticlgmswaptionengine.hpp>\n\n#include <boost/bind.hpp>\n\nnamespace QuantExt {\n\nAnalyticLgmSwaptionEngine::AnalyticLgmSwaptionEngine(const boost::shared_ptr<LinearGaussMarkovModel>& model,\n                                                     const Handle<YieldTermStructure>& discountCurve,\n                                                     const FloatSpreadMapping floatSpreadMapping)\n    : GenericEngine<Swaption::arguments, Swaption::results>(), p_(model->parametrization()),\n      c_(discountCurve.empty() ? p_->termStructure() : discountCurve), floatSpreadMapping_(floatSpreadMapping),\n      caching_(false) {\n    registerWith(model);\n    registerWith(c_);\n}\n\nAnalyticLgmSwaptionEngine::AnalyticLgmSwaptionEngine(const boost::shared_ptr<CrossAssetModel>& model, const Size ccy,\n                                                     const Handle<YieldTermStructure>& discountCurve,\n                                                     const FloatSpreadMapping floatSpreadMapping)\n    : GenericEngine<Swaption::arguments, Swaption::results>(), p_(model->irlgm1f(ccy)),\n      c_(discountCurve.empty() ? p_->termStructure() : discountCurve), floatSpreadMapping_(floatSpreadMapping),\n      caching_(false) {\n    registerWith(model);\n    registerWith(c_);\n}\n\nAnalyticLgmSwaptionEngine::AnalyticLgmSwaptionEngine(const boost::shared_ptr<IrLgm1fParametrization> irlgm1f,\n                                                     const Handle<YieldTermStructure>& discountCurve,\n                                                     const FloatSpreadMapping floatSpreadMapping)\n    : GenericEngine<Swaption::arguments, Swaption::results>(), p_(irlgm1f),\n      c_(discountCurve.empty() ? p_->termStructure() : discountCurve), floatSpreadMapping_(floatSpreadMapping),\n      caching_(false) {\n    registerWith(c_);\n}\n\nvoid AnalyticLgmSwaptionEngine::enableCache(const bool lgm_H_constant, const bool lgm_alpha_constant) {\n    caching_ = true;\n    lgm_H_constant_ = lgm_H_constant;\n    lgm_alpha_constant_ = lgm_alpha_constant;\n    clearCache();\n}\n\nvoid AnalyticLgmSwaptionEngine::clearCache() {\n    S_.clear();             // indicates that H / alpha independent variables are not yet computed\n    Hj_.clear();            // indicates that H dependent variables not not yet computed\n    zetaex_ = Null<Real>(); // indicates that alpha dependent variables are not yet computed\n}\n\nvoid AnalyticLgmSwaptionEngine::calculate() const {\n\n    QL_REQUIRE(arguments_.settlementType == Settlement::Physical, \"cash-settled swaptions are not supported ...\");\n\n    Date reference = p_->termStructure()->referenceDate();\n\n    Date expiry = arguments_.exercise->dates().back();\n\n    if (expiry <= reference) {\n        // swaption is expired, possibly generated swap is not\n        // valued by this engine, so we set the npv to zero\n        results_.value = 0.0;\n        return;\n    }\n\n    if (!caching_ || S_.empty()) {\n\n        Option::Type type = arguments_.type == VanillaSwap::Payer ? Option::Call : Option::Put;\n        const Schedule& fixedSchedule = arguments_.swap->fixedSchedule();\n        const Schedule& floatSchedule = arguments_.swap->floatingSchedule();\n\n        j1_ = std::lower_bound(fixedSchedule.dates().begin(), fixedSchedule.dates().end(), expiry) -\n              fixedSchedule.dates().begin();\n        k1_ = std::lower_bound(floatSchedule.dates().begin(), floatSchedule.dates().end(), expiry) -\n              floatSchedule.dates().begin();\n\n        // compute S_i, i.e. equivalent fixed rate spreads compensating for\n        // a) a possibly non-zero float spread and\n        // b) a spread between the ibor indices forwarding curve and the\n        //     discounting curve\n        // here, we do not work with a spread corrections directly, but\n        // with this multiplied by the nominal and accrual basis,\n        // so S_i is really an amount correction.\n\n        S_.resize(arguments_.fixedCoupons.size() - j1_);\n        for (Size i = 0; i < S_.size(); ++i) {\n            S_[i] = 0.0;\n        }\n        S_m1 = 0.0;\n        Size ratio = static_cast<Size>(static_cast<Real>(arguments_.floatingCoupons.size()) /\n                                           static_cast<Real>(arguments_.fixedCoupons.size()) +\n                                       0.5);\n        QL_REQUIRE(ratio >= 1, \"floating leg's payment frequency must be equal or \"\n                               \"higher than fixed leg's payment frequency in \"\n                               \"analytic lgm swaption engine\");\n\n        Size k = k1_;\n        // The method reduces the problem to a one curve configuration w.r.t. the discount curve and\n        // apply a correction for the discount curve / forwarding curve spread. Furthermore the method\n        // assumes that no historical fixings are present in the floating rate coupons.\n        auto index = arguments_.swap->iborIndex();\n        for (Size j = j1_; j < arguments_.fixedCoupons.size(); ++j) {\n            Real sum1 = 0.0, sum2 = 0.0;\n            for (Size rr = 0; rr < ratio && k < arguments_.floatingCoupons.size(); ++rr, ++k) {\n                Real amount = arguments_.floatingCoupons[k];\n                Real lambda1 = 0.0, lambda2 = 1.0;\n                if (floatSpreadMapping_ == proRata) {\n                    // we do not use the exact pay dates but the ratio to determine\n                    // the distance to the adjacent payment dates\n                    lambda2 = static_cast<Real>(rr + 1) / static_cast<Real>(ratio);\n                    lambda1 = 1.0 - lambda2;\n                }\n                if (amount != Null<Real>()) {\n                    Real flatAmount;\n                    if (IborCoupon::usingAtParCoupons()) {\n                        // if par coupons are used, we mimick the fixing estimation in IborCoupon; we make\n                        // sure that the estimation period does not start in the past and we do not use\n                        // historical fixings\n                        Date fixingValueDate = index->fixingCalendar().advance(arguments_.floatingFixingDates[k],\n                                                                               index->fixingDays(), Days);\n                        fixingValueDate = std::max(fixingValueDate, reference);\n                        auto cpn = boost::dynamic_pointer_cast<Coupon>(arguments_.swap->floatingLeg()[k]);\n                        QL_REQUIRE(cpn, \"AnalyticalLgmSwaptionEngine::calculate(): coupon expected on underlying swap \"\n                                        \"floating leg, could not cast\");\n                        Date nextFixingDate = index->fixingCalendar().advance(\n                            cpn->accrualEndDate(), -static_cast<Integer>(index->fixingDays()), Days);\n                        Date fixingEndDate = index->fixingCalendar().advance(nextFixingDate, index->fixingDays(), Days);\n                        fixingEndDate = std::max(fixingEndDate, fixingValueDate + 1);\n                        Real spanningTime = index->dayCounter().yearFraction(fixingValueDate, fixingEndDate);\n                        DiscountFactor disc1 = c_->discount(fixingValueDate);\n                        DiscountFactor disc2 = c_->discount(fixingEndDate);\n                        Real fixing = (disc1 / disc2 - 1.0) / spanningTime;\n                        flatAmount = fixing * arguments_.floatingAccrualTimes[k] * arguments_.nominal;\n                    } else {\n                        // if indexed coupons are used, we use a proper fixing, but make sure that the fixing date\n                        // is not in the past and we do not use a historical fixing for \"today\"\n                        auto flatIbor = boost::make_shared<IborIndex>(\n                            index->familyName() + \" (no fixings)\", index->tenor(), index->fixingDays(),\n                            index->currency(), index->fixingCalendar(), index->businessDayConvention(),\n                            index->endOfMonth(), index->dayCounter(), c_);\n                        Date fixingDate =\n                            flatIbor->fixingCalendar().adjust(std::max(arguments_.floatingFixingDates[k], reference));\n                        flatAmount =\n                            flatIbor->fixing(fixingDate) * arguments_.floatingAccrualTimes[k] * arguments_.nominal;\n                    }\n                    Real correction = (amount - flatAmount) * c_->discount(arguments_.floatingPayDates[k]);\n                    sum1 += lambda1 * correction;\n                    sum2 += lambda2 * correction;\n                } else {\n                    // if no amount is given, we do not need a spread correction\n                    // due to different forward / discounting curves since then\n                    // no curve is attached to the swap's ibor index and so we\n                    // assume a one curve setup;\n                    // but we can still have a float spread that has to be converted\n                    // into a fixed leg's payment\n                    Real correction = arguments_.nominal * arguments_.floatingSpreads[k] *\n                                      arguments_.floatingAccrualTimes[k] * c_->discount(arguments_.floatingPayDates[k]);\n                    sum1 += lambda1 * correction;\n                    sum2 += lambda2 * correction;\n                }\n            }\n            if (j > j1_) {\n                S_[j - j1_ - 1] += sum1 / c_->discount(arguments_.fixedPayDates[j - 1]);\n            } else {\n                S_m1 += sum1 / c_->discount(arguments_.floatingResetDates[k1_]);\n            }\n            S_[j - j1_] += sum2 / c_->discount(arguments_.fixedPayDates[j]);\n        }\n\n        w_ = type == Option::Call ? -1.0 : 1.0;\n        D0_ = c_->discount(arguments_.floatingResetDates[k1_]);\n        Dj_.resize(arguments_.fixedCoupons.size() - j1_);\n        for (Size j = j1_; j < arguments_.fixedCoupons.size(); ++j) {\n            Dj_[j - j1_] = c_->discount(arguments_.fixedPayDates[j - j1_]);\n        }\n    }\n\n    if (!caching_ || !lgm_H_constant_ || Hj_.empty()) {\n        // it is a requirement that H' does not change its sign,\n        // with u = -1.0 we handle the case H' < 0\n        u_ = p_->Hprime(0.0) > 0.0 ? 1.0 : -1.0;\n\n        H0_ = p_->H(p_->termStructure()->timeFromReference(arguments_.floatingResetDates[k1_]));\n        Hj_.resize(arguments_.fixedCoupons.size() - j1_);\n        for (Size j = j1_; j < arguments_.fixedCoupons.size(); ++j) {\n            Hj_[j - j1_] = p_->H(p_->termStructure()->timeFromReference(arguments_.fixedPayDates[j]));\n        }\n    }\n\n    if (!caching_ || !lgm_alpha_constant_ || zetaex_ == Null<Real>()) {\n        zetaex_ = p_->zeta(p_->termStructure()->timeFromReference(expiry));\n    }\n\n    Brent b;\n    Real yStar;\n    try {\n        yStar = b.solve(boost::bind(&AnalyticLgmSwaptionEngine::yStarHelper, this, _1), 1.0E-6, 0.0, 0.01);\n    } catch (const std::exception& e) {\n        QL_FAIL(\"AnalyticLgmSwaptionEngine, failed to compute yStar, \" << e.what());\n    }\n\n    CumulativeNormalDistribution N;\n    Real sqrt_zetaex = std::sqrt(zetaex_);\n    Real sum = 0.0;\n    for (Size j = j1_; j < arguments_.fixedCoupons.size(); ++j) {\n        sum += w_ * (arguments_.fixedCoupons[j] - S_[j - j1_]) * Dj_[j - j1_] *\n               N(u_ * w_ * (yStar + (Hj_[j - j1_] - H0_) * zetaex_) / sqrt_zetaex);\n    }\n    sum += -w_ * S_m1 * D0_ * N(u_ * w_ * yStar / sqrt_zetaex);\n    sum += w_ * (arguments_.nominal * Dj_.back() * N(u_ * w_ * (yStar + (Hj_.back() - H0_) * zetaex_) / sqrt_zetaex) -\n                 arguments_.nominal * D0_ * N(u_ * w_ * yStar / sqrt_zetaex));\n    results_.value = sum;\n\n    results_.additionalResults[\"fixedAmountCorrectionSettlement\"] = S_m1;\n    results_.additionalResults[\"fixedAmountCorrections\"] = S_;\n\n} // calculate\n\nReal AnalyticLgmSwaptionEngine::yStarHelper(const Real y) const {\n    Real sum = 0.0;\n    for (Size j = j1_; j < arguments_.fixedCoupons.size(); ++j) {\n        sum += (arguments_.fixedCoupons[j] - S_[j - j1_]) * Dj_[j - j1_] *\n               std::exp(-(Hj_[j - j1_] - H0_) * y - 0.5 * (Hj_[j - j1_] - H0_) * (Hj_[j - j1_] - H0_) * zetaex_);\n    }\n    sum += -S_m1 * D0_;\n    sum += Dj_.back() * arguments_.nominal *\n           std::exp(-(Hj_.back() - H0_) * y - 0.5 * (Hj_.back() - H0_) * (Hj_.back() - H0_) * zetaex_);\n    sum -= D0_ * arguments_.nominal;\n    return sum;\n}\n\n} // namespace QuantExt\n", "meta": {"hexsha": "41ab234e0743b71950da5655f4b00eb5b57d0fb1", "size": 13203, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/pricingengines/analyticlgmswaptionengine.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/analyticlgmswaptionengine.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/analyticlgmswaptionengine.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": 52.3928571429, "max_line_length": 120, "alphanum_fraction": 0.5899416799, "num_tokens": 3143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.28005809774636825}}
{"text": "/**\n * @file \tmain.cpp\n * @author \tFabian Wegscheider\n * @date \tJul 14, 2017\n */\n\n\n#include <iostream>\n#include <boost/program_options.hpp>\n#include <boost/timer/timer.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include \"GraphParser.h\"\n#include \"PrimeNumbers.h\"\n#include \"SteinerTreeHeuristic.h\"\n\nusing std::string;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing namespace boost;\nnamespace po = boost::program_options;\n\nusing Graph = adjacency_list<vecS, vecS, undirectedS,\n\t\tno_property, property<edge_weight_t, double>>;\n\n\n/**\n * The main function which reads in a graph from a .gph file, considers all\n * vertices with prime indices as terminals and calculates a steiner tree\n * using the an improved shortest-path-heuristic based on Dijkstra\n * @param numargs number of inputs on command line\n * @param args array of inputs on command line\n * @return whether the program operated successfully\n */\nint main(int numargs, char* args[]) {\n\n\ttimer::cpu_timer overallTimer;\n\n\tstring input;\n\tbool printTreeSelected;\n\tint root = 1;\n\n\t/*parsing command line options*/\n\tpo::options_description desc(\"Allowed options\");\n\tdesc.add_options()\n\t\t\t(\"help,h\", \"produce help message\")\n\t\t\t(\"showtree,s\", \"print tree\")\n\t\t\t(\"root,r\", po::value<int>(&root)->default_value(1),\n\t\t\t\t\t\"set root node (prime number)\")\n\t\t\t(\"input-file\", po::value<string>(), \"input file\");\n\tpo::positional_options_description p;\n\tp.add(\"input-file\", -1);\n\tpo::variables_map vm;\n\tpo::store(po::command_line_parser(numargs, args).\n\t\t\toptions(desc).positional(p).run(), vm);\n\tpo::notify(vm);\n\n\tif (vm.count(\"help\")) {\n\t\tcout << desc << \"\\n\";\n\t\texit(EXIT_SUCCESS);\n\t}\n\n\tif (vm.count(\"input-file\")) {\n\t\tinput = vm[\"input-file\"].as< string >();\n\t} else {\n\t\tcerr << \"please specify an input file in the .gph format\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tprintTreeSelected = vm.count(\"showtree\");\n\t/*end of parsing command line options*/\n\n\n\tint numVertices;\n\tint numEdges;\n\n\n\tGraphParser parser(input);\n\tif (!parser.openedSuccessfully) {\n\t\tcerr << \"file could not be read\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\t//first line is read to get number of vertices and edges\n\tif (!parser.readFirstLine(numVertices, numEdges)) {\n\t\tcerr << \"error while reading file, not the right format\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tEdge* edges = new Edge[numEdges];\n\tdouble* weights = new double[numEdges];\n\n\t//rest of the file is read and parsed to a graph\n\tif (!parser.readEdgeData(edges, weights)) {\n\t\tcerr << \"error while reading file, not the right format\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\t//undirected graph is constructed with all edges and their weights\n\tGraph g(edges, edges + numEdges , weights, numVertices);\n\n\t//In this array the steiner tree is implicitly stored by remembering the predecessor\n\t//of each vertex. A -1 means that the vertex is not contained in the tree\n\tint* treePredecessors = new int[numVertices];\n\n\t//all primes in {2,...,numVertices} are considered to be terminals\n\tvector<int> terminals = PrimeNumbers::findPrimes(numVertices);\n\n\ttimer::cpu_timer algoTimer;\n\n\t//here the steiner tree is finally constructed\n\tdouble objectiveValue = SteinerTreeHeuristic::computeSteinerTree(g, numVertices,\n\t\t\ttreePredecessors, terminals, root);\n\n\tif (objectiveValue == -1) {\n\t\tcerr << \"the root you selected is not a valid prime number\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tstring algoTime = algoTimer.format(3, \"%w\");\n\n\t//to this string all edges in the tree are printed if user chose option -s\n\tstring edgeString;\n\tif (printTreeSelected) {\n\t\tassert(SteinerTreeHeuristic::testAndPrintTree(g, numVertices, treePredecessors,\n\t\t\tterminals, root, edgeString));\n\t} else {\n\t\tassert(SteinerTreeHeuristic::testTree(g, numVertices, treePredecessors,\n\t\t\tterminals, root));\n\t}\n\n\n\tcout << \"TLEN: \" << objectiveValue << endl;\n\tif (printTreeSelected) cout << \"TREE: \" << edgeString << endl;\n\tcout << \"TIME: \" << overallTimer.format(3, \"%t\") << endl;\n\tcout << \"WALL: \" << algoTime << endl;\n\tcout << endl;\n\n\tdelete[] edges;\n\tdelete[] weights;\n\tdelete[] treePredecessors;\n\n\texit(EXIT_SUCCESS);\n}\n\n\n\n\n", "meta": {"hexsha": "d86ad9a43051e69a38c8c5003917ba36213444d5", "size": 4048, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Wegscheider/ex9/main.cpp", "max_stars_repo_name": "appfs/appfs", "max_stars_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T11:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T20:25:18.000Z", "max_issues_repo_path": "Wegscheider/ex9/main.cpp", "max_issues_repo_name": "appfs/appfs", "max_issues_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2017-04-26T09:30:38.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-01T11:31:21.000Z", "max_forks_repo_path": "Wegscheider/ex9/main.cpp", "max_forks_repo_name": "appfs/appfs", "max_forks_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2017-04-20T16:16:11.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-19T12:53:01.000Z", "avg_line_length": 27.1677852349, "max_line_length": 85, "alphanum_fraction": 0.7065217391, "num_tokens": 1047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521307073646, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.280013267302429}}
{"text": "/*\n  Copyright (c) 2010 Toru Tamaki\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\n#include <iostream>\n\n#include <boost/shared_array.hpp>\n\n#include <flann/flann.hpp>\n\n\n// uncomment if you do not use the viewer.\n//#define NOVIEWER\n\n#include \"3dregistration.h\"\n\n\nextern \"C\" {\n  int sgemm_(const char *transa, const char *transb, const int *m, const int *n, const int *k,\n             const float *alpha, const float *a, const int *lda, const float *b, const int *ldb,\n             const float *beta, float *c, const int *ldc);\n}\n\ninline static float\ndistanceSquare(float x1, float y1, float z1,\n\t       float x2, float y2, float z2){\n\n  float tmpx = (x1 - x2);\n  float tmpy = (y1 - y2);\n  float tmpz = (z1 - z2);\n\n  return tmpx*tmpx + tmpy*tmpy + tmpz*tmpz;\n}\n\ninline static float\ndistanceSquareRT(float x1, float y1, float z1,\n\t\t float x2, float y2, float z2, float* h_R, float* h_t){\n\n  return distanceSquare(x1, y1, z1,\n\t\t\t(h_R[0]*x2 + h_R[1]*y2 + h_R[2]*z2) + h_t[0],\n\t\t\t(h_R[3]*x2 + h_R[4]*y2 + h_R[5]*z2) + h_t[1],\n\t\t\t(h_R[6]*x2 + h_R[7]*y2 + h_R[8]*z2) + h_t[2]);\n\n}\n\n\n\n#if 1\nstatic void\nfindCenter(const float* h_X, const int Xsize,\n\t   float* h_Xc){\n\n  const float* h_Xx = &h_X[Xsize*0];\n  const float* h_Xy = &h_X[Xsize*1];\n  const float* h_Xz = &h_X[Xsize*2];\n  \n  double Xcx = 0.0f, Xcy = 0.0f, Xcz = 0.0f;\n\n#pragma omp parallel for reduction (+:Xcx,Xcy,Xcz)\n  for(int i = 0; i < Xsize; i++){\n    Xcx += h_Xx[i];\n    Xcy += h_Xy[i];\n    Xcz += h_Xz[i];\n  }\n\n  h_Xc[0] = Xcx / Xsize;\n  h_Xc[1] = Xcy / Xsize;\n  h_Xc[2] = Xcz / Xsize;\n\n}\n\n#else\nstatic void\nfindCenter(const float* h_X, const int Xsize,\n\t   float* h_Xc){\n\n  const float* h_Xx = &h_X[Xsize*0];\n  const float* h_Xy = &h_X[Xsize*1];\n  const float* h_Xz = &h_X[Xsize*2];\n  \n  h_Xc[0] = h_Xc[1] = h_Xc[2] = 0.0f;\n\n  for(int i = 0; i < Xsize; i++){\n    h_Xc[0] += h_Xx[i];\n    h_Xc[1] += h_Xy[i];\n    h_Xc[2] += h_Xz[i];\n  }\n\n  h_Xc[0] /= Xsize;\n  h_Xc[1] /= Xsize;\n  h_Xc[2] /= Xsize;\n\n}\n#endif\n\n\n\n\n\nvoid icp(const pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_target, \n\t const pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_source,\n\t float* h_R, float* h_t, \n\t const registrationParameters &param)\n{\n  \n  \n  int Xsize, Ysize;\n  boost::shared_array<float> h_X, h_Y;\n  cloud2data(cloud_target, h_X, Xsize);\n  cloud2data(cloud_source, h_Y, Ysize);\n  \n  \n  \n  //\n  // initialize paramters\n  //\n  int maxIteration = param.maxIteration;\n\n\n  //\n  // memory allocation\n  //\n  \n  \n  float* h_Xx = h_X.get() + Xsize*0;\n  float* h_Xy = h_X.get() + Xsize*1;\n  float* h_Xz = h_X.get() + Xsize*2;\n  \n  float* h_Yx = h_Y.get() + Ysize*0;\n  float* h_Yy = h_Y.get() + Ysize*1;\n  float* h_Yz = h_Y.get() + Ysize*2;\n\n  boost::shared_array<float> h_Xcorr ( new float[Ysize*3] ); // points in X corresponding to Y\n\n\n  float h_S[9];\n  float h_Xc[3];\n  float h_Yc[3];\n\n  findCenter(h_Y.get(), Ysize, h_Yc);\n\n\n\n  // building flann index\n  boost::shared_array<float> m_X ( new float [Xsize*3] );\n  for (int i = 0; i < Xsize; i++)\n  {\n    m_X[i*3 + 0] = h_Xx[i];\n    m_X[i*3 + 1] = h_Xy[i];\n    m_X[i*3 + 2] = h_Xz[i];\n  }\n  flann::Matrix<float> mat_X(m_X.get(), Xsize, 3); // Xsize rows and 3 columns\n  flann::Index< flann::L2<float> > index( mat_X, flann::KDTreeIndexParams() );\n  index.buildIndex();   \n\n  boost::shared_array<float> m_Y ( new float [Ysize*3] );\n  float* h_Xcorrx = h_Xcorr.get() + Ysize*0;\n  float* h_Xcorry = h_Xcorr.get() + Ysize*1;\n  float* h_Xcorrz = h_Xcorr.get() + Ysize*2;\n  \n  \n  boost::shared_array<float> h_Ycentered ( new float [Ysize*3] );\n  {\n    float* h_Ycenteredx = h_Ycentered.get() + Ysize*0;\n    float* h_Ycenteredy = h_Ycentered.get() + Ysize*1;\n    float* h_Ycenteredz = h_Ycentered.get() + Ysize*2;\n    for(int i = 0; i < Ysize; i++){\n      h_Ycenteredx[i] = h_Yx[i] - h_Yc[0];\n      h_Ycenteredy[i] = h_Yy[i] - h_Yc[1];\n      h_Ycenteredz[i] = h_Yz[i] - h_Yc[2];\n    }    \n  }\n  \n    \n  // ICP main loop\n\n  for(int iter=0; iter < maxIteration; iter++){\n\n\n    // find closest points\n    \n\n    #pragma omp parallel for\n    for (int i = 0; i < Ysize; i++)\n    {\n      m_Y[i*3 + 0] = (h_R[0]*h_Yx[i] + h_R[1]*h_Yy[i] + h_R[2]*h_Yz[i]) + h_t[0];\n      m_Y[i*3 + 1] = (h_R[3]*h_Yx[i] + h_R[4]*h_Yy[i] + h_R[5]*h_Yz[i]) + h_t[1];\n      m_Y[i*3 + 2] = (h_R[6]*h_Yx[i] + h_R[7]*h_Yy[i] + h_R[8]*h_Yz[i]) + h_t[2];\n    }\n    flann::Matrix<float> mat_Y(m_Y.get(), Ysize, 3); // Ysize rows and 3 columns\n    \n    \n    std::vector< std::vector<size_t> > indices(Ysize);\n    std::vector< std::vector<float> >  dists(Ysize);\n    \n    index.knnSearch(mat_Y,\n\t\t    indices,\n\t\t    dists,\n\t\t    1, // k of knn\n\t\t    flann::SearchParams() );\n\n\n    \n    #pragma omp parallel for\n    for(int i = 0; i < Ysize; i++){\n      // put the closest point to Ycorr\n      h_Xcorrx[i] = h_Xx[indices[i][0]];\n      h_Xcorry[i] = h_Xy[indices[i][0]];\n      h_Xcorrz[i] = h_Xz[indices[i][0]];\n    }\n    \n    findCenter(h_Xcorr.get(), Ysize, h_Xc);\n    \n    #pragma omp parallel for\n    for(int i = 0; i < Ysize; i++){\n      // put the closest point to Ycorr\n      h_Xcorrx[i] -= h_Xc[0];\n      h_Xcorry[i] -= h_Xc[1];\n      h_Xcorrz[i] -= h_Xc[2];\n    }    \n\n    // compute S\n\n    {\n      // SGEMM(TRANSA,TRANSB,M,N,K,ALPHA,A,LDA,B,LDB,BETA,C,LDC)\n      //  C := alpha*op( A )*op( B ) + beta*C\n      // \n      //  h_X^T * h_Y => S\n      //  m*k     k*n    m*n\n      int three = 3;\n      float one = 1.0f, zero = 0.0f;\n      sgemm_((char*)\"t\", (char*)\"n\", \n\t     &three, &three, &Ysize, // m,n,k\n\t     &one, h_Xcorr.get(), &Ysize, // alpha, op(A), lda\n\t     h_Ycentered.get(), &Ysize,  // op(B), ldb\n\t     &zero, h_S, &three);  // beta, C, ldc\n    }\n    \n  \n\n\n\n\n    // find RT from S\n\n    findRTfromS(h_Xc, h_Yc, h_S, h_R, h_t);\n\n\n#ifndef NOVIEWER\n    if(!param.noviewer){\n      Eigen::Matrix4f transformation;\n      transformation <<\n      \t\t\th_R[0], h_R[1], h_R[2], h_t[0],\n\t\t\th_R[3], h_R[4], h_R[5], h_t[1],\n\t\t\th_R[6], h_R[7], h_R[8], h_t[2],\n\t\t\t0, 0, 0, 1;\n      pcl::transformPointCloud ( *param.cloud_source, *param.cloud_source_trans, transformation );\n      param.viewer->updatePointCloud ( param.cloud_source_trans, *param.source_trans_color, \"source trans\" );\n      param.viewer->spinOnce();\n    }\n#endif\n\n\n  }\n\n\n}\n\n\n", "meta": {"hexsha": "f0c6309503036215b9d55f0800a9da808ec5d6c5", "size": 7186, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/icp.cpp", "max_stars_repo_name": "chinacat567/cuda_emicp_softassign", "max_stars_repo_head_hexsha": "ecce949136d72e9fe299b23119c5a19016e195ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 58.0, "max_stars_repo_stars_event_min_datetime": "2015-01-19T04:13:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T06:12:03.000Z", "max_issues_repo_path": "src/icp.cpp", "max_issues_repo_name": "chinacat567/cuda_emicp_softassign", "max_issues_repo_head_hexsha": "ecce949136d72e9fe299b23119c5a19016e195ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-09-30T09:01:43.000Z", "max_issues_repo_issues_event_max_datetime": "2015-12-04T12:21:23.000Z", "max_forks_repo_path": "src/icp.cpp", "max_forks_repo_name": "chinacat567/cuda_emicp_softassign", "max_forks_repo_head_hexsha": "ecce949136d72e9fe299b23119c5a19016e195ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2015-06-16T15:57:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T03:19:11.000Z", "avg_line_length": 24.6095890411, "max_line_length": 109, "alphanum_fraction": 0.6001948233, "num_tokens": 2561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.27991112031852666}}
{"text": "// The MIT License (MIT)\n\n// Copyright (c) 2014 Mohammad Dashti\n// (www.mdashti.com - mohammad.dashti [at] epfl [dot] ch - mdashti [at] gmail [dot] com)\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef KDOUBLE_H\n#define KDOUBLE_H\n#include <cmath>\n#include <iostream>\n// #include <boost/multiprecision/cpp_dec_float.hpp>\n\n// typedef boost::multiprecision::number<boost::multiprecision::cpp_dec_float<1000, long long> > cpp_dec_float_1000;\n\n#define DOUBLE_TYPE_STD_DOUBLE 1\n#define DOUBLE_TYPE_KAHAN_DOUBLE 2\n#define DOUBLE_TYPE_STD_LONG_DOUBLE 3\n#define DOUBLE_TYPE_BOOST 4\n\n// #ifndef DOUBLE_TYPE\n\n//   //you can change the value of DOUBLE_TYPE_SYM\n//   //to change the double type. Choices are:\n//   // - DOUBLE_TYPE_STD_DOUBLE\n//   // - DOUBLE_TYPE_KAHAN_DOUBLE\n//   // - DOUBLE_TYPE_STD_LONG_DOUBLE\n//   // - DOUBLE_TYPE_BOOST\n//   #define DOUBLE_TYPE_SYM DOUBLE_TYPE_STD_DOUBLE\n\n//   #if DOUBLE_TYPE_SYM == DOUBLE_TYPE_KAHAN_DOUBLE\n//     #define DOUBLE_TYPE KDouble\n//   #elif DOUBLE_TYPE_SYM == DOUBLE_TYPE_BOOST\n//     #define DOUBLE_TYPE cpp_dec_float_1000\n//   #elif DOUBLE_TYPE_SYM == DOUBLE_TYPE_STD_LONG_DOUBLE\n//     #define DOUBLE_TYPE long double\n//   #else\n//     #define DOUBLE_TYPE double\n//   #endif //DOUBLE_TYPE_SYM == DOUBLE_TYPE_KAHAN_DOUBLE\n// #endif //DOUBLE_TYPE\n\nnamespace dbtoaster {\n\nclass KDouble\n{\npublic:\n  static double diff_p;\n#if DOUBLE_TYPE_SYM == DOUBLE_TYPE_KAHAN_DOUBLE\nprivate:\n  double sum;\n  double c;\n\nprotected:\n  //friends\n  friend bool operator==(const double, const KDouble &);\n  friend bool operator!=(const double, const KDouble &);\n  friend bool operator<(const double, const KDouble &);\n  friend bool operator<=(const double, const KDouble &);\n  friend bool operator>(const double, const KDouble &);\n  friend bool operator>=(const double, const KDouble &);\n  friend KDouble acos(const KDouble &);\n  friend KDouble atan2(const KDouble &, const KDouble &);\n  friend KDouble sqrt(const KDouble &);\n  friend KDouble pow(const KDouble &, const KDouble &);\n  // friend size_t hash_value(KDouble const &v);\n  template <class T>\n  friend void hash_combine(std::size_t& seed, const T& v);\n  friend KDouble abs(const KDouble &dbl);\n\npublic:\n  KDouble() : sum(0.0), c(0.0)\n  {\n  }\n\n  KDouble(const KDouble &init) : sum(init.sum), c(init.c)\n  {\n  }\n\n  KDouble(const double &init) : sum(init), c(0.0)\n  {\n  }\n\n  ~KDouble()\n  {\n  }\n\n  inline KDouble &operator=(const KDouble &other) { sum = other.sum; c = other.c; return *this; }\n  inline KDouble &operator=(const double &other) { sum = other; c = 0.0; return *this; }\n  inline KDouble &operator-=(const KDouble &other) {\n    double y = -other.sum-c;\n    double t = sum+y;\n    c = static_cast<double>(t-sum)-y;\n    sum = t;\n    return *this;\n  }\n  inline KDouble &operator-=(const double &other) {\n    double y = -other-c;\n    double t = sum+y;\n    c = static_cast<double>(t-sum)-y;\n    sum = t;\n    return *this;\n  }\n  inline KDouble &operator+=(const KDouble &other) {\n    double y = other.sum-c;\n    double t = sum+y;\n    c = static_cast<double>(t-sum)-y;\n    sum = t;\n    return *this;\n  }\n  inline KDouble &operator+=(const double &other) {\n    double y = other-c;\n    double t = sum+y;\n    c = static_cast<double>(t-sum)-y;\n    sum = t;\n    return *this;\n  }\n\n  //TODO Is this the right implementation?\n  inline KDouble &operator*=(const KDouble &other) { sum *= other.sum; c *= other.sum; return *this; }\n  inline KDouble &operator*=(const double &other) { sum *= other; c *= other; return *this; }\n  inline KDouble &operator/=(const KDouble &other) { sum /= other.sum; c /= other.sum; return *this; }\n  inline KDouble &operator/=(const double &other) { sum /= other; c /= other; return *this; }\n\n  friend std::ostream &operator<<(std::ostream &out, const KDouble &kd) {\n      return out << kd.sum;\n  }\n\n  //inline operator double() const { return sum; }\n  // operator int() const { return static_cast<int>(sum); }\n  // operator long() const { return static_cast<long>(sum); }\n\n  inline bool operator==(const KDouble &other) const\n  {\n    return abs(sum-other.sum) < diff_p;\n  }\n\n  inline bool operator!=(const KDouble &other) const\n  {\n    return abs(sum-other.sum) >= diff_p;\n  }\n\n  // inline bool operator==(const double &other)\n  // {\n  //   return abs(sum-other) < diff_p;\n  // }\n\n  // inline bool operator!=(const double &other)\n  // {\n  //   return abs(sum-other) >= diff_p;\n  // }\n\n  inline bool operator<(const KDouble &other) const\n  {\n    return sum < other.sum;\n  }\n\n  inline bool operator<=(const KDouble &other) const\n  {\n    return sum <= other.sum;\n  }\n\n  inline bool operator>(const KDouble &other) const\n  {\n    return sum > other.sum;\n  }\n\n  inline bool operator>=(const KDouble &other) const\n  {\n    return sum >= other.sum;\n  }\n#endif //DOUBLE_TYPE_SYM == DOUBLE_TYPE_KAHAN_DOUBLE\n};\n\n#if DOUBLE_TYPE_SYM == DOUBLE_TYPE_KAHAN_DOUBLE\n\n  inline bool operator==(const double sum, const KDouble & other)\n  {\n    return abs(sum-other.sum) < KDouble::diff_p;\n  }\n  inline bool operator!=(const double sum, const KDouble & other)\n  {\n    return abs(sum-other.sum) >= KDouble::diff_p;\n  }\n\n  inline bool operator<(const double sum, const KDouble &other)\n  {\n    return sum < other.sum;\n  }\n\n  inline bool operator<=(const double sum, const KDouble &other)\n  {\n    return sum <= other.sum;\n  }\n\n  inline bool operator>(const double sum, const KDouble &other)\n  {\n    return sum > other.sum;\n  }\n\n  inline bool operator>=(const double sum, const KDouble &other)\n  {\n    return sum >= other.sum;\n  }\n\n  inline KDouble operator-(const KDouble &g1, const KDouble &g2)\n  {\n      KDouble result(g1);\n      result -= g2;\n      return result;\n  }\n\n  inline KDouble operator+(const KDouble &g1, const KDouble &g2)\n  {\n      KDouble result(g1);\n      result += g2;\n      return result;\n  }\n\n  inline KDouble operator*(const KDouble &g1, const KDouble &g2)\n  {\n      KDouble result(g1);\n      result *= g2;\n      return result;\n  }\n\n  inline KDouble operator/(const KDouble &g1, const KDouble &g2)\n  {\n      KDouble result(g1);\n      result /= g2;\n      return result;\n  }\n\n  inline KDouble operator-(const double &g1, const KDouble &g2)\n  {\n      KDouble result(g1);\n      result -= g2;\n      return result;\n  }\n\n  inline KDouble operator+(const double &g1, const KDouble &g2)\n  {\n      KDouble result(g1);\n      result += g2;\n      return result;\n  }\n\n  inline KDouble operator/(const double &g1, const KDouble &g2)\n  {\n      KDouble result(g1);\n      result /= g2;\n      return result;\n  }\n\n  inline KDouble operator-(const long &g1, const KDouble &g2)\n  {\n      KDouble result(g1);\n      result -= g2;\n      return result;\n  }\n\n  inline KDouble operator+(const long &g1, const KDouble &g2)\n  {\n      KDouble result(g1);\n      result += g2;\n      return result;\n  }\n\n  inline KDouble operator/(const long &g1, const KDouble &g2)\n  {\n      KDouble result(g1);\n      result /= g2;\n      return result;\n  }\n\n  inline KDouble operator-(const int &g1, const KDouble &g2)\n  {\n      KDouble result(g1);\n      result -= g2;\n      return result;\n  }\n\n  inline KDouble operator+(const int &g1, const KDouble &g2)\n  {\n      KDouble result(g1);\n      result += g2;\n      return result;\n  }\n\n  inline KDouble operator*(const int &g1, const KDouble &g2)\n  {\n      KDouble result(g1);\n      result *= g2;\n      return result;\n  }\n\n  inline KDouble operator/(const int &g1, const KDouble &g2)\n  {\n      KDouble result(g1);\n      result /= g2;\n      return result;\n  }\n\n  inline KDouble operator-(const KDouble &g1, const double &g2)\n  {\n      KDouble result(g1);\n      result -= g2;\n      return result;\n  }\n\n  inline KDouble operator+(const KDouble &g1, const double &g2)\n  {\n      KDouble result(g1);\n      result += g2;\n      return result;\n  }\n\n  inline KDouble operator*(const KDouble &g1, const double &g2)\n  {\n      KDouble result(g1);\n      result *= g2;\n      return result;\n  }\n\n  inline KDouble operator/(const KDouble &g1, const double &g2)\n  {\n      KDouble result(g1);\n      result /= g2;\n      return result;\n  }\n\n  inline KDouble operator-(const KDouble &g1, const long &g2)\n  {\n      KDouble result(g1);\n      result -= g2;\n      return result;\n  }\n\n  inline KDouble operator+(const KDouble &g1, const long &g2)\n  {\n      KDouble result(g1);\n      result += g2;\n      return result;\n  }\n\n  inline KDouble operator*(const KDouble &g1, const long &g2)\n  {\n      KDouble result(g1);\n      result *= g2;\n      return result;\n  }\n\n  inline KDouble operator/(const KDouble &g1, const long &g2)\n  {\n      KDouble result(g1);\n      result /= g2;\n      return result;\n  }\n\n  inline KDouble operator-(const KDouble &g1, const int &g2)\n  {\n      KDouble result(g1);\n      result -= g2;\n      return result;\n  }\n\n  inline KDouble operator+(const KDouble &g1, const int &g2)\n  {\n      KDouble result(g1);\n      result += g2;\n      return result;\n  }\n\n  inline KDouble operator*(const KDouble &g1, const int &g2)\n  {\n      KDouble result(g1);\n      result *= g2;\n      return result;\n  }\n\n  inline KDouble operator/(const KDouble &g1, const int &g2)\n  {\n      KDouble result(g1);\n      result /= g2;\n      return result;\n  }\n\n  inline KDouble abs(const KDouble &dbl)\n  {\n      KDouble result(dbl);\n      if(result.sum < 0.0) result.sum = -result.sum;\n      return result;\n  }\n\n  inline KDouble acos(const KDouble &dbl)\n  {\n      return KDouble(acos(dbl.sum));\n  }\n\n  inline KDouble atan2(const KDouble &g1, const KDouble &g2)\n  {\n    return KDouble(atan2(g1.sum,g2.sum));\n  }\n\n  inline KDouble sqrt(const KDouble &dbl)\n  {\n    return KDouble(sqrt(dbl.sum));\n  }\n\n  inline KDouble pow(const KDouble &g1, const KDouble &g2)\n  {\n    return KDouble(pow(g1.sum, g2.sum));\n  }\n#endif //DOUBLE_TYPE_SYM == DOUBLE_TYPE_KAHAN_DOUBLE\n}\n#endif //KDOUBLE_H", "meta": {"hexsha": "c99bed5702066303f9cf2afc20b5b82391ebde1a", "size": 10759, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "runtime/tpcc/pardisgen/include/hpds/KDouble.hpp", "max_stars_repo_name": "erlfilho/dbtoaster-backend", "max_stars_repo_head_hexsha": "26df37bb73b06136b88ff53ef5f703e2029c0831", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2017-09-29T08:12:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T03:56:20.000Z", "max_issues_repo_path": "runtime/tpcc/pardisgen/include/hpds/KDouble.hpp", "max_issues_repo_name": "erlfilho/dbtoaster-backend", "max_issues_repo_head_hexsha": "26df37bb73b06136b88ff53ef5f703e2029c0831", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2018-04-05T02:42:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-18T02:13:57.000Z", "max_forks_repo_path": "runtime/tpcc/pardisgen/include/hpds/KDouble.hpp", "max_forks_repo_name": "erlfilho/dbtoaster-backend", "max_forks_repo_head_hexsha": "26df37bb73b06136b88ff53ef5f703e2029c0831", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2017-09-29T08:16:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T04:22:29.000Z", "avg_line_length": 24.9628770302, "max_line_length": 116, "alphanum_fraction": 0.6506180872, "num_tokens": 2949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.27991112031852666}}
{"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\nint main(int argc, char ** argv) {\n    MPI_Init(&argc, &argv);\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], odir[1024];\n    PS::F64 rcrit;\n    PS::S64 ibgn, iend;\n    FILE * fp = fopen(argv[1], \"r\");\n    fscanf(fp, \"%s\", idir);\n    fscanf(fp, \"%s\", odir);\n    fscanf(fp, \"%lf\", &rcrit);\n    fscanf(fp, \"%lld%lld\", &ibgn, &iend);\n    fclose(fp);\n\n    char ofile[1024];\n    sprintf(ofile, \"%s/axis.dat\", odir);\n    FILE * fout = fopen(ofile, \"w\");\n    fprintf(fout, \"# idir: %s\\n\", idir);\n    fprintf(fout, \"# crit: %+e\\n\", rcrit);\n    fprintf(fout, \"# time, Ixx, Iyy, Izz, Ixx, Iyy, Izz\\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        assert(fp);\n        sph.readParticleAscii(sfile);\n        fclose(fp);\n        fp = fopen(bfile, \"r\");\n        assert(fp);\n        bhns.readParticleAscii(bfile);\n        fclose(fp);\n\n        PS::F64mat qq[2] = {0., 0.};\n        for(PS::S64 i = 0; i < sph.getNumberOfParticleLocal(); i++) {\n            PS::F64mat qtemp = sph[i].calcMomentOfInertia(bhns[0].pos);\n            qq[0] = qq[0] + qtemp;\n            PS::F64vec dx = sph[i].pos - bhns[0].pos;\n            PS::F64    r2 = dx * dx;\n            if(r2 < rcrit * rcrit) {\n                qq[1] = qq[1] + qtemp;\n            }\n        }\n\n        fprintf(fout, \"%5d\", itime);\n        Eigen::Matrix3d MomentOfInertia[2];\n        for(PS::S64 k = 0; k < 2; k++) {\n            MomentOfInertia[k] <<\n                qq[k].xx, qq[k].xy, qq[k].xz,\n                qq[k].xy, qq[k].yy, qq[k].yz,\n                qq[k].xz, qq[k].yz, qq[k].zz;\n            Eigen::EigenSolver<Eigen::Matrix3d> es(MomentOfInertia[k], false);\n            std::vector<PS::F64> ev;\n            ev.push_back(es.eigenvalues()[0].real());\n            ev.push_back(es.eigenvalues()[1].real());\n            ev.push_back(es.eigenvalues()[2].real());\n            std::sort(ev.begin(), ev.end());\n            fprintf(fout, \" %+e %+e %+e\", ev[0], ev[1], ev[2]);\n        }\n        fprintf(fout, \"\\n\");\n        fflush(fout);\n\n    }\n    fclose(fout);\n\n    MPI_Finalize();\n\n    return 0;\n}\n", "meta": {"hexsha": "26459f9ea19da8638710357fd81f1d8f1005e667", "size": 6866, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tool.hgas/calcMoI/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.hgas/calcMoI/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.hgas/calcMoI/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": 34.33, "max_line_length": 89, "alphanum_fraction": 0.4849985435, "num_tokens": 2342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2798607276250578}}
{"text": "// Copyright (C) 2017  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n#include \"opaque_types.h\"\n#include <dlib/python.h>\n#include <dlib/global_optimization.h>\n#include <dlib/matrix.h>\n\n\nusing namespace dlib;\nusing namespace std;\nnamespace py = pybind11;\n\n// ----------------------------------------------------------------------------------------\n\nstd::vector<bool> list_to_bool_vector(\n    const py::list& l\n)\n{\n    std::vector<bool> result(len(l));\n    for (long i = 0; i < result.size(); ++i)\n    {\n        result[i] = l[i].cast<bool>();\n    }\n    return result;\n}\n\nmatrix<double,0,1> list_to_mat(\n    const py::list& l\n)\n{\n    matrix<double,0,1> result(len(l));\n    for (long i = 0; i < result.size(); ++i)\n        result(i) = l[i].cast<double>();\n    return result;\n}\n\npy::list mat_to_list (\n    const matrix<double,0,1>& m\n)\n{\n    py::list l;\n    for (long i = 0; i < m.size(); ++i)\n        l.append(m(i));\n    return l;\n}\n\nsize_t num_function_arguments(py::object f)\n{\n    if (hasattr(f,\"func_code\"))\n        return f.attr(\"func_code\").attr(\"co_argcount\").cast<std::size_t>();\n    else\n        return f.attr(\"__code__\").attr(\"co_argcount\").cast<std::size_t>();\n}\n\ndouble call_func(py::object f, const matrix<double,0,1>& args)\n{\n    const auto num = num_function_arguments(f);\n    DLIB_CASSERT(num == args.size(), \n        \"The function being optimized takes a number of arguments that doesn't agree with the size of the bounds lists you provided to find_max_global()\");\n    DLIB_CASSERT(0 < num && num < 15, \"Functions being optimized must take between 1 and 15 scalar arguments.\");\n\n#define CALL_WITH_N_ARGS(N) case N: return dlib::gopt_impl::_cwv(f,args,typename make_compile_time_integer_range<N>::type()).cast<double>(); \n    switch (num)\n    {\n        CALL_WITH_N_ARGS(1)\n        CALL_WITH_N_ARGS(2)\n        CALL_WITH_N_ARGS(3)\n        CALL_WITH_N_ARGS(4)\n        CALL_WITH_N_ARGS(5)\n        CALL_WITH_N_ARGS(6)\n        CALL_WITH_N_ARGS(7)\n        CALL_WITH_N_ARGS(8)\n        CALL_WITH_N_ARGS(9)\n        CALL_WITH_N_ARGS(10)\n        CALL_WITH_N_ARGS(11)\n        CALL_WITH_N_ARGS(12)\n        CALL_WITH_N_ARGS(13)\n        CALL_WITH_N_ARGS(14)\n        CALL_WITH_N_ARGS(15)\n\n        default:\n            DLIB_CASSERT(false, \"oops\");\n            break;\n    }\n}\n\n// ----------------------------------------------------------------------------------------\n\npy::tuple py_find_max_global (\n    py::object f,\n    py::list bound1,\n    py::list bound2,\n    py::list is_integer_variable,\n    unsigned long num_function_calls,\n    double solver_epsilon = 0\n)\n{\n    DLIB_CASSERT(len(bound1) == len(bound2));\n    DLIB_CASSERT(len(bound1) == len(is_integer_variable));\n\n    auto func = [&](const matrix<double,0,1>& x)\n    {\n        return call_func(f, x);\n    };\n\n    auto result = find_max_global(func, list_to_mat(bound1), list_to_mat(bound2),\n        list_to_bool_vector(is_integer_variable), max_function_calls(num_function_calls),\n        solver_epsilon);\n\n    return py::make_tuple(mat_to_list(result.x),result.y);\n}\n\npy::tuple py_find_max_global2 (\n    py::object f,\n    py::list bound1,\n    py::list bound2,\n    unsigned long num_function_calls,\n    double solver_epsilon = 0\n)\n{\n    DLIB_CASSERT(len(bound1) == len(bound2));\n\n    auto func = [&](const matrix<double,0,1>& x)\n    {\n        return call_func(f, x);\n    };\n\n    auto result = find_max_global(func, list_to_mat(bound1), list_to_mat(bound2), max_function_calls(num_function_calls), solver_epsilon);\n\n    return py::make_tuple(mat_to_list(result.x),result.y);\n}\n\n// ----------------------------------------------------------------------------------------\n\npy::tuple py_find_min_global (\n    py::object f,\n    py::list bound1,\n    py::list bound2,\n    py::list is_integer_variable,\n    unsigned long num_function_calls,\n    double solver_epsilon = 0\n)\n{\n    DLIB_CASSERT(len(bound1) == len(bound2));\n    DLIB_CASSERT(len(bound1) == len(is_integer_variable));\n\n    auto func = [&](const matrix<double,0,1>& x)\n    {\n        return call_func(f, x);\n    };\n\n    auto result = find_min_global(func, list_to_mat(bound1), list_to_mat(bound2),\n        list_to_bool_vector(is_integer_variable), max_function_calls(num_function_calls),\n        solver_epsilon);\n\n    return py::make_tuple(mat_to_list(result.x),result.y);\n}\n\npy::tuple py_find_min_global2 (\n    py::object f,\n    py::list bound1,\n    py::list bound2,\n    unsigned long num_function_calls,\n    double solver_epsilon = 0\n)\n{\n    DLIB_CASSERT(len(bound1) == len(bound2));\n\n    auto func = [&](const matrix<double,0,1>& x)\n    {\n        return call_func(f, x);\n    };\n\n    auto result = find_min_global(func, list_to_mat(bound1), list_to_mat(bound2), max_function_calls(num_function_calls), solver_epsilon);\n\n    return py::make_tuple(mat_to_list(result.x),result.y);\n}\n\n// ----------------------------------------------------------------------------------------\n\nvoid bind_global_optimization(py::module& m)\n{\n    /*!\n        requires\n            - len(bound1) == len(bound2) == len(is_integer_variable)\n            - for all valid i: bound1[i] != bound2[i]\n            - solver_epsilon >= 0\n            - f() is a real valued multi-variate function.  It must take scalar real\n              numbers as its arguments and the number of arguments must be len(bound1).\n        ensures\n            - This function performs global optimization on the given f() function.\n              The goal is to maximize the following objective function:\n                 f(x)\n              subject to the constraints:\n                min(bound1[i],bound2[i]) <= x[i] <= max(bound1[i],bound2[i])\n                if (is_integer_variable[i]) then x[i] is an integer.\n            - find_max_global() runs until it has called f() num_function_calls times.\n              Then it returns the best x it has found along with the corresponding output\n              of f().  That is, it returns (best_x_seen,f(best_x_seen)).  Here best_x_seen\n              is a list containing the best arguments to f() this function has found.\n            - find_max_global() uses a global optimization method based on a combination of\n              non-parametric global function modeling and quadratic trust region modeling\n              to efficiently find a global maximizer.  It usually does a good job with a\n              relatively small number of calls to f().  For more information on how it\n              works read the documentation for dlib's global_function_search object.\n              However, one notable element is the solver epsilon, which you can adjust.\n\n              The search procedure will only attempt to find a global maximizer to at most\n              solver_epsilon accuracy.  Once a local maximizer is found to that accuracy\n              the search will focus entirely on finding other maxima elsewhere rather than\n              on further improving the current local optima found so far.  That is, once a\n              local maxima is identified to about solver_epsilon accuracy, the algorithm\n              will spend all its time exploring the function to find other local maxima to\n              investigate.  An epsilon of 0 means it will keep solving until it reaches\n              full floating point precision.  Larger values will cause it to switch to pure\n              global exploration sooner and therefore might be more effective if your\n              objective function has many local maxima and you don't care about a super\n              high precision solution.\n            - Any variables that satisfy the following conditions are optimized on a log-scale:\n                - The lower bound on the variable is > 0\n                - The ratio of the upper bound to lower bound is > 1000\n                - The variable is not an integer variable\n              We do this because it's common to optimize machine learning models that have\n              parameters with bounds in a range such as [1e-5 to 1e10] (e.g. the SVM C\n              parameter) and it's much more appropriate to optimize these kinds of\n              variables on a log scale.  So we transform them by applying log() to\n              them and then undo the transform via exp() before invoking the function\n              being optimized.  Therefore, this transformation is invisible to the user\n              supplied functions.  In most cases, it improves the efficiency of the\n              optimizer.\n    !*/\n    {\n    m.def(\"find_max_global\", &py_find_max_global, \n\"requires \\n\\\n    - len(bound1) == len(bound2) == len(is_integer_variable) \\n\\\n    - for all valid i: bound1[i] != bound2[i] \\n\\\n    - solver_epsilon >= 0 \\n\\\n    - f() is a real valued multi-variate function.  It must take scalar real \\n\\\n      numbers as its arguments and the number of arguments must be len(bound1). \\n\\\nensures \\n\\\n    - This function performs global optimization on the given f() function. \\n\\\n      The goal is to maximize the following objective function: \\n\\\n         f(x) \\n\\\n      subject to the constraints: \\n\\\n        min(bound1[i],bound2[i]) <= x[i] <= max(bound1[i],bound2[i]) \\n\\\n        if (is_integer_variable[i]) then x[i] is an integer. \\n\\\n    - find_max_global() runs until it has called f() num_function_calls times. \\n\\\n      Then it returns the best x it has found along with the corresponding output \\n\\\n      of f().  That is, it returns (best_x_seen,f(best_x_seen)).  Here best_x_seen \\n\\\n      is a list containing the best arguments to f() this function has found. \\n\\\n    - find_max_global() uses a global optimization method based on a combination of \\n\\\n      non-parametric global function modeling and quadratic trust region modeling \\n\\\n      to efficiently find a global maximizer.  It usually does a good job with a \\n\\\n      relatively small number of calls to f().  For more information on how it \\n\\\n      works read the documentation for dlib's global_function_search object. \\n\\\n      However, one notable element is the solver epsilon, which you can adjust. \\n\\\n \\n\\\n      The search procedure will only attempt to find a global maximizer to at most \\n\\\n      solver_epsilon accuracy.  Once a local maximizer is found to that accuracy \\n\\\n      the search will focus entirely on finding other maxima elsewhere rather than \\n\\\n      on further improving the current local optima found so far.  That is, once a \\n\\\n      local maxima is identified to about solver_epsilon accuracy, the algorithm \\n\\\n      will spend all its time exploring the function to find other local maxima to \\n\\\n      investigate.  An epsilon of 0 means it will keep solving until it reaches \\n\\\n      full floating point precision.  Larger values will cause it to switch to pure \\n\\\n      global exploration sooner and therefore might be more effective if your \\n\\\n      objective function has many local maxima and you don't care about a super \\n\\\n      high precision solution. \\n\\\n    - Any variables that satisfy the following conditions are optimized on a log-scale: \\n\\\n        - The lower bound on the variable is > 0 \\n\\\n        - The ratio of the upper bound to lower bound is > 1000 \\n\\\n        - The variable is not an integer variable \\n\\\n      We do this because it's common to optimize machine learning models that have \\n\\\n      parameters with bounds in a range such as [1e-5 to 1e10] (e.g. the SVM C \\n\\\n      parameter) and it's much more appropriate to optimize these kinds of \\n\\\n      variables on a log scale.  So we transform them by applying log() to \\n\\\n      them and then undo the transform via exp() before invoking the function \\n\\\n      being optimized.  Therefore, this transformation is invisible to the user \\n\\\n      supplied functions.  In most cases, it improves the efficiency of the \\n\\\n      optimizer.\" \n        , \n\tpy::arg(\"f\"), py::arg(\"bound1\"), py::arg(\"bound2\"), py::arg(\"is_integer_variable\"), py::arg(\"num_function_calls\"), py::arg(\"solver_epsilon\")=0\n    );\n    }\n\n    {\n    m.def(\"find_max_global\", &py_find_max_global2, \n        \"This function simply calls the other version of find_max_global() with is_integer_variable set to False for all variables.\", \n\tpy::arg(\"f\"), py::arg(\"bound1\"), py::arg(\"bound2\"), py::arg(\"num_function_calls\"), py::arg(\"solver_epsilon\")=0\n    );\n    }\n\n\n\n    {\n    m.def(\"find_min_global\", &py_find_min_global, \n      \"This function is just like find_max_global(), except it performs minimization rather than maximization.\" \n        , \n\tpy::arg(\"f\"), py::arg(\"bound1\"), py::arg(\"bound2\"), py::arg(\"is_integer_variable\"), py::arg(\"num_function_calls\"), py::arg(\"solver_epsilon\")=0\n    );\n    }\n\n    {\n    m.def(\"find_min_global\", &py_find_min_global2, \n        \"This function simply calls the other version of find_min_global() with is_integer_variable set to False for all variables.\", \n\tpy::arg(\"f\"), py::arg(\"bound1\"), py::arg(\"bound2\"), py::arg(\"num_function_calls\"), py::arg(\"solver_epsilon\")=0\n    );\n    }\n\n}\n\n", "meta": {"hexsha": "7411266916d8d1dceabb7f31f21737202d24da78", "size": 12951, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/python/src/global_optimization.cpp", "max_stars_repo_name": "abhishekkumardwivedi/dlib", "max_stars_repo_head_hexsha": "4c2d1fe06c36026d75d6e981f1135594efc54215", "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": "tools/python/src/global_optimization.cpp", "max_issues_repo_name": "abhishekkumardwivedi/dlib", "max_issues_repo_head_hexsha": "4c2d1fe06c36026d75d6e981f1135594efc54215", "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": "tools/python/src/global_optimization.cpp", "max_forks_repo_name": "abhishekkumardwivedi/dlib", "max_forks_repo_head_hexsha": "4c2d1fe06c36026d75d6e981f1135594efc54215", "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.3769968051, "max_line_length": 155, "alphanum_fraction": 0.6414176511, "num_tokens": 3084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117165898111865, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.2797749826532368}}
{"text": "/*\n * ----------------- BEGIN LICENSE BLOCK ---------------------------------\n *\n * Copyright (C) 2019-2021 Intel Corporation\n *\n * SPDX-License-Identifier: MIT\n *\n * ----------------- END LICENSE BLOCK -----------------------------------\n */\n\n#include \"opendrive/geometry/CenterLine.hpp\"\n#include <boost/array.hpp>\n#include <boost/math/tools/rational.hpp>\n#include <cmath>\n#include <iostream>\n#include <spdlog/spdlog.h>\n#include \"opendrive/geometry/GeometryGenerator.hpp\"\n#include \"opendrive/geometry/LaneUtils.hpp\"\n\nnamespace opendrive {\nnamespace geometry {\n\ndouble laneHeight(ElevationProfileSet const &elevationSet, double s)\n{\n  return evalPoly3(elevationSet, s);\n}\n\ngeometry::DirectedPoint CenterLine::eval(double s, bool applyLateralOffset) const\n{\n  if (s < 0.)\n  {\n    // as the curve is only defined betwen the range [0 , length], we return the line evaluated at s = 0\n    return eval(0.);\n  }\n\n  for (auto it = geometry.rbegin(); it != geometry.rend(); it++)\n  {\n    if (s >= (*it)->GetStartOffset())\n    {\n      auto directedPoint = (*it)->PosFromDist(s - (*it)->GetStartOffset());\n\n      // This is parametrized as the landmarks positions do not take into account the lateral offset\n      if (applyLateralOffset)\n      {\n        directedPoint.ApplyLateralOffset(calculateOffset(s));\n      }\n\n      directedPoint.location.z = laneHeight(elevation, s);\n      return directedPoint;\n    }\n  }\n\n  auto &lastGeometry = geometry.back();\n  auto directed_point = lastGeometry->PosFromDist(s - lastGeometry->GetStartOffset());\n  directed_point.location.z = laneHeight(elevation, s);\n  return directed_point;\n}\n\nstd::list<double> CenterLine::samplingPoints() const\n{\n  std::list<double> points;\n\n  points.push_back(length);\n\n  for (auto it = geometry.rbegin(); it != geometry.rend(); it++)\n  {\n    if ((*it)->GetType() == ::opendrive::GeometryType::ARC)\n    {\n      auto arc = static_cast<::opendrive::geometry::GeometryArc *>((*it).get());\n      double theta = fabs(arc->GetCurvature()) * (*it)->GetLength();\n\n      if (theta < 1e-2)\n      {\n        points.insert(points.begin(), (*it)->GetStartOffset() + 0.5 * (*it)->GetLength());\n      }\n      else\n      {\n        double c = fabs(arc->GetCurvature());\n        double dsmax = 2.0 / c * acos(1.0 - c * Geometry::cMaxSamplingError);\n        int segments = static_cast<int>((*it)->GetLength() / dsmax);\n        for (auto k = segments - 1; k > 0; --k)\n        {\n          double r = static_cast<double>(k) / static_cast<double>(segments);\n          points.insert(points.begin(), (*it)->GetStartOffset() + r * (*it)->GetLength());\n        }\n      }\n    }\n    else\n    {\n      // only start and end point for now\n    }\n\n    points.insert(points.begin(), (*it)->GetStartOffset());\n  }\n\n  auto const maxErrorSquared = Geometry::cMaxSamplingError * Geometry::cMaxSamplingError;\n  // now refine sampling points according to actual points influenced by lateralOffset and elevation\n  auto iter = points.begin();\n  while (iter != points.end())\n  {\n    auto nextIter = iter;\n    nextIter++;\n    if (nextIter == points.end())\n    {\n      break;\n    }\n    auto const startPosition = *iter;\n    auto const endPosition = *nextIter;\n    if (endPosition - startPosition < Geometry::cMaxSamplingError)\n    {\n      // sampling below the maxError longitudinal distance makes no sense\n      ++iter;\n      continue;\n    }\n    auto const centerPosition = 0.5 * startPosition + 0.5 * endPosition;\n\n    auto const start = eval(startPosition).location;\n    auto const end = eval(endPosition).location;\n    auto const centerLinearInterpolated = 0.5 * start + 0.5 * end;\n    auto const centerActual = eval(centerPosition).location;\n    auto errorSquared = (centerActual - centerLinearInterpolated).normSquared();\n    if (errorSquared > maxErrorSquared)\n    {\n      points.insert(nextIter, centerPosition);\n    }\n    else\n    {\n      iter++;\n    }\n  }\n\n  return points;\n}\n\ndouble CenterLine::calculateOffset(double s) const\n{\n  return evalPoly3(laneOffsetSet, s);\n}\n\nbool generateCenterLine(RoadInformation &roadInfo, CenterLine &centerLine)\n{\n  bool ok = true;\n\n  centerLine.geometry.clear();\n  centerLine.length = roadInfo.attributes.length;\n  centerLine.laneOffsetSet = roadInfo.lanes.lane_offset;\n  centerLine.elevation = roadInfo.road_profiles.elevation_profile;\n\n  // Add geometry information\n  for (auto &geometry_attribute : roadInfo.geometry_attributes)\n  {\n    Point start(\n      geometry_attribute->start_position_x, geometry_attribute->start_position_y, geometry_attribute->start_position_z);\n\n    try\n    {\n      switch (geometry_attribute->type)\n      {\n        case ::opendrive::GeometryType::ARC:\n        {\n          auto arc = static_cast<GeometryAttributesArc *>(geometry_attribute.get());\n          centerLine.geometry.emplace_back(std::make_unique<geometry::GeometryArc>(\n            arc->start_position, arc->length, arc->heading, start, arc->curvature));\n          break;\n        }\n        case ::opendrive::GeometryType::LINE:\n        {\n          auto line = static_cast<GeometryAttributesLine *>(geometry_attribute.get());\n          centerLine.geometry.emplace_back(\n            std::make_unique<geometry::GeometryLine>(line->start_position, line->length, line->heading, start));\n          break;\n        }\n        break;\n        case ::opendrive::GeometryType::SPIRAL:\n        {\n          // currently not yet supported\n          spdlog::error(\"generateCenterLine() spirals are currently not supported yet\");\n          ok = false;\n          break;\n        }\n        break;\n        case ::opendrive::GeometryType::POLY3:\n        {\n          auto poly3 = static_cast<GeometryAttributesPoly3 *>(geometry_attribute.get());\n          centerLine.geometry.emplace_back(std::make_unique<geometry::GeometryPoly3>(\n            poly3->start_position, poly3->length, poly3->heading, start, poly3->a, poly3->b, poly3->c, poly3->d));\n          break;\n        }\n        break;\n        case ::opendrive::GeometryType::PARAMPOLY3:\n        {\n          auto paramPoly3 = static_cast<GeometryAttributesParamPoly3 *>(geometry_attribute.get());\n          centerLine.geometry.emplace_back(\n            std::make_unique<geometry::GeometryParamPoly3>(paramPoly3->start_position,\n                                                           paramPoly3->length,\n                                                           paramPoly3->heading,\n                                                           start,\n                                                           paramPoly3->aU,\n                                                           paramPoly3->bU,\n                                                           paramPoly3->cU,\n                                                           paramPoly3->dU,\n                                                           paramPoly3->aV,\n                                                           paramPoly3->bV,\n                                                           paramPoly3->cV,\n                                                           paramPoly3->dV,\n                                                           paramPoly3->p_range == \"normalized\"));\n          break;\n        }\n        break;\n        default:\n          break;\n      }\n    }\n    catch (...)\n    {\n      spdlog::error(\"generateCenterLine() Invalid geometry definition\");\n      ok = false;\n    }\n  }\n\n  return ok;\n}\n} // namespace geometry\n} // namespace opendrive\n", "meta": {"hexsha": "751542c659414216be681fab8561066088169500", "size": 7405, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ad_map_opendrive_reader/src/geometry/CenterLine.cpp", "max_stars_repo_name": "woojinjjang/map-1", "max_stars_repo_head_hexsha": "d12bb410f03d078a995130b4e671746ace8b6287", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2019-12-19T20:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T15:20:51.000Z", "max_issues_repo_path": "ad_map_opendrive_reader/src/geometry/CenterLine.cpp", "max_issues_repo_name": "woojinjjang/map-1", "max_issues_repo_head_hexsha": "d12bb410f03d078a995130b4e671746ace8b6287", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 54.0, "max_issues_repo_issues_event_min_datetime": "2020-04-05T05:32:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T18:42:33.000Z", "max_forks_repo_path": "ad_map_opendrive_reader/src/geometry/CenterLine.cpp", "max_forks_repo_name": "woojinjjang/map-1", "max_forks_repo_head_hexsha": "d12bb410f03d078a995130b4e671746ace8b6287", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2019-12-20T07:37:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T13:06:16.000Z", "avg_line_length": 32.9111111111, "max_line_length": 120, "alphanum_fraction": 0.5762322755, "num_tokens": 1630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.2797286386959738}}
{"text": "//Header for this file\n#include \"modetrack.h\"\n//C System-Headers\n#include <termios.h>  /* POSIX terminal control definitions */\n#include <sys/ioctl.h>\n#include <fcntl.h>//fopen(),fclose()\n#include <unistd.h>//read(), write()\n//C++ System headers\n#include <vector>//vector\n#include <string>//string\n#include <fstream>//iss*\n#include <chrono>// timing functions\n#include <cmath>//sqrt, abs\n#include <iostream>//cout\n#include <typeinfo>//typeid\n#include <algorithm> // transform, find\n#include <functional> // plus/minus\n#include <utility>//std::make_pair\n#include <map>//std::map\n//Boost Headers\n#include <boost/algorithm/string.hpp>//split() and is_any_of for parsing .csv files\n#include <boost/lexical_cast.hpp>//lexical cast (unsurprisingly)\n//Miscellaneous Headers\n#include <omp.h>//OpenMP pragmas\n//Project specific Headers\n//\n\n\nModeTrack::ModeTrack() {\n\n    //initialize best fit curves\n    PopulateBestFitCurves();\n}\n\n\nModeTrack::~ModeTrack() {}\n\ninline void SubtractBackground(std::vector<double>& data,std::vector<double>& background) {\n\n    data.resize(background.size());\n    std::transform(data.begin(), data.end(), background.begin(), data.begin(),std::minus<double>());\n}\n\nstd::vector< data_triple<double> > SubtractBackground(const std::vector< data_triple<double> >& data,\n        const std::vector<double>& background) {\n\n    std::vector< data_triple<double> > new_signal;\n    new_signal.reserve( background.size() );\n\n    for( uint i = 0; i < background.size() ; i++ ) {\n\n        double length = data[i].cavity_length;\n        double frequency = data[i].frequency_MHz;\n        double power = data[i].power_dBm - background[i];\n\n        new_signal.push_back( data_triple< double >( length, frequency, power ) );\n    }\n\n    return new_signal;\n}\n\ndouble ModeTrack::GetPeaks( const std::vector<data_triple<double> >& data_str, int mode_number, Method filter_method ) {\n\n    std::vector< data_triple< double > > clean_signal = SubtractBackground( data_str, background );\n\n    std::vector<double> power_list = data_triples_to_power( clean_signal );\n\n    auto peak_list = FindPeaks( power_list, filter_method) ;\n    std::cout << \"Number of peaks identified: \" << peak_list.size() << std::endl;\n\n    //check to see if any mode were identified\n    //if not return the default value of 'zero'\n\n    if( peak_list.size() >= 1 ) {\n\n        auto identified_peaks = CompareAndFill(peak_list, clean_signal);\n\n        //check to see if requested mode number has been identified\n        //if it has return the frequency at which it was found\n        //if not return zero, which will be interpreted as 'not found'\n        if ( identified_peaks.count(mode_number) == 1 ) {\n            return identified_peaks[mode_number];\n        } else {\n            throw mode_track_failure( \"Requested mode was not identified.\" );\n        }\n    } else {\n        throw mode_track_failure( \"No modes were identified.\" );\n    }\n}\n\ndouble ModeTrack::GetPeaksGauss( const std::vector<data_triple<double> >& data_str, int mode_number ) {\n\n    try {\n        return GetPeaks( data_str, mode_number, Gauss );\n    } catch (const mode_track_failure& e) {\n        throw mode_track_failure( \"Could not identify requested mode in data set\" );\n    }\n//    return GetPeaks( data_str, mode_number, Gauss );\n}\n\ndouble ModeTrack::GetPeaksBiLat( const std::vector<data_triple<double> >& data_str, int mode_number) {\n\n    try {\n        return GetPeaks( data_str, mode_number, BiLat );\n    } catch (const mode_track_failure& e) {\n        throw mode_track_failure( \"Could not identify requested mode in data set\" );\n    }\n\n//    return GetPeaks( data_str, mode_number, BiLat );\n}\n\nvoid ModeTrack::SetLowerBound( double frequency ) {\n    upper_bound = frequency;\n}\n\nvoid ModeTrack::SetUpperBound( double frequency ) {\n    lower_bound = frequency;\n}\n\n\ndouble ModeTrack::GetMaxPeak( const std::vector< data_triple<double> >& data_list ) {\n\n    std::vector<double> power_list = data_triples_to_power( data_list );\n\n    uint peak_index = 0;\n    FindMaxima( power_list );\n\n    try {\n        peak_index = FindMaxima( power_list );\n    } catch (const mode_track_failure& e) {\n        throw mode_track_failure( \"No maxima peak found in data set.\" );\n    }\n\n    data_triple<double> data_entry = data_list.at( peak_index );\n    return data_entry.frequency_MHz;\n}\n\nvoid ModeTrack::SetBackground( const std::vector<data_triple< double > >& background_list ) {\n\n    background = data_triples_to_power( background_list );\n\n}\n\nstd::vector<double> ModeTrack::Derivative( const std::vector<double>& data_list ) {\n\n    std::vector<double> der_list;\n\n    std::deque<double> data_deque (data_list.begin(),data_list.end());\n    //Pad data_list with zeros at front and back\n    for ( unsigned int i=0; i < 2; i++ ) {\n        data_deque.push_front(0.0);\n        data_deque.push_back(0.0);\n    }\n\n    #pragma omp parallel for ordered schedule(dynamic)\n    for( unsigned int n = 2; n < data_list.size() + 2; n++ ) {\n\n        double der = ( -data_deque.at( n + 2 ) + 8.0*data_deque.at( n + 1 ) - 8*data_deque.at( n - 1 )+data_deque.at( n - 2 ) ) / 12.0;\n\n        #pragma omp ordered\n        der_list.push_back(der);\n    }\n    return(der_list);\n}\n\n//sum all enteries in a vector, with optional parameter of raising each entry to a power\n//used by Standard Deviation function\ninline double sum ( const std::vector< double >& data_list, double exponent ) {\n\n    double tot = 0.0;\n\n    for ( const auto& val : data_list ) {\n        tot += std::pow( val, exponent );\n    }\n\n    return tot;\n}\n\n//define a gaussian function with standard deviation sigma and a mean value of zero\n//used in the construction of gaussian kernels\ninline double gaussian ( double x, double sigma ) {\n    return 1.0 / ( std::sqrt(M_PI_2)*sigma )*std::exp( -0.5 * std::pow( x/sigma, 2.0 ) );\n}\n\n//generate a gaussian kernel of radius 'r', suitable for convolutions\n//kernel will have a standard deviation of r/2.\nstd::vector<double> ModeTrack::GaussKernel( int r ) {\n\n    double sigma = static_cast<double>( r )/2.0;\n\n    std::vector<double> vals;\n\n    for( int i = -r; i<= r ; i ++ ) {\n        vals.push_back( gaussian( i, sigma ) );\n    }\n\n    //normalize kernel before returning\n    return Normalize( vals );\n}\n\ndouble ModeTrack::StdDev( const std::vector<double>& data_list ) {\n\n    //compute mean value of data set\n    double sum_x = sum( data_list, 1.0 );\n    double n = static_cast<double>( data_list.size() );\n    double mean = sum_x/n;\n\n    //compute variance taking into account Bessel's correction eg n/(n-1)\n    double sum_x2 = sum( data_list, 2.0 );\n    double sigma_sqr = sum_x2/( n - 1.0 ) - n/( n - 1.0 )*std::pow( mean, 2.0 );\n\n    //return square root of variance\n    return std::sqrt( sigma_sqr );\n}\n\nstd::vector<double> ModeTrack::Normalize( const std::vector<double>& data_list ) {\n\n    double norm_factor = std::sqrt( sum( data_list, 2.0 ) );\n    auto normalized_data = data_list;\n\n    std::transform( normalized_data.begin(), \\\n                    normalized_data.end(), \\\n                    normalized_data.begin(), \\\n                    std::bind1st(std::divides<float>(), norm_factor) );\n\n    return normalized_data;\n}\n\nstd::vector< double > ModeTrack::Convolve( const std::vector<double>& signal, const std::vector<double>& kernel ) {\n\n    int kernel_size = kernel.size();\n    int half_k_size = (kernel_size - 1 )/2;\n\n    int signal_size = signal.size();\n    int signal_max_index = signal_size - 1;\n\n    std::vector< double > output( signal.size(), 0.0 );\n\n    #pragma omp parallel for\n    for ( int i = 0 ; i < signal_size ; i++ ) {\n\n        double conv_elem = 0.0;\n\n        int k_max = ( ( i + half_k_size ) > signal_max_index )?( signal_max_index + half_k_size - i ):(kernel_size);\n        int k_min = ( ( i - half_k_size ) < 0 )?( half_k_size - i ):(0);\n\n        for ( int j = k_min ; j < k_max ; j++ ) {\n\n            conv_elem += signal[ i + j - half_k_size]*kernel[ j ];\n        }\n\n        for ( int j = 0 ; j < k_min ; j++ ) {\n\n            conv_elem += signal[ -i - j + half_k_size ]*kernel[ j ];\n        }\n\n        for ( int j = k_max ; j < kernel_size ; j++ ) {\n\n            conv_elem += signal[ 2*signal_max_index - i - j + half_k_size ]*kernel[ j ];\n\n        }\n\n        output[i] = conv_elem;\n\n    }\n\n    return output;\n}\n\n//Convolve the input list 'data_list' with a gaussian kernel of radius 15\n//serves as a low-pass filter that surpressed noise.\nstd::vector<double> ModeTrack::GaussBlur( const std::vector<double>& data_list ) {\n\n    auto gauss_matrix = GaussKernel( 15 );\n    return Convolve( data_list, gauss_matrix );\n}\n\nstruct RetrieveVal {\n    template <typename T>\n    typename T::first_type operator()(T keyValuePair) const {\n        return keyValuePair.second;\n    }\n};\n\n//copy values stored in std::map to std::vec\n//std::transform(map.begin(), map.end(), std::back_inserter(vec), RetrieveVal());\n\nstd::vector<double> ModeTrack::FindPeaks( const std::vector<double>& data_list, const ModeTrack::Method method ) {\n\n    auto filtered_list = ( method == Gauss )? GaussBlur( data_list ):BilateralFilter( data_list, 10, 2 );\n    auto f_prime = Derivative( filtered_list );\n\n    int f_prime_size = f_prime.size() - 1;\n    int max_size = filtered_list.size();\n\n    double sigma = StdDev( f_prime );\n\n    std::vector< double > peak_list;\n\n    #pragma omp parallel for ordered schedule(dynamic)\n    for( int i = 0; i < f_prime_size; i++ ) {\n\n        bool stat_signifigant = ( f_prime.at(i) < 3*sigma && f_prime.at(i+1) > 3*sigma );\n        bool away_from_edges = ( i+1 < max_size - 4 && i+1 > 4 );\n\n        if( stat_signifigant && away_from_edges ) {\n\n            #pragma omp ordered\n            peak_list.push_back( static_cast<double>( i + 1 ) );\n\n        }\n    }\n\n    return peak_list;\n}\n\nuint ModeTrack::FindMaxima( const std::vector<double>& data_list ) {\n\n    auto g_blur = GaussBlur( data_list );\n    auto f_prime = Derivative( g_blur );\n\n    uint length = data_list.size();\n\n    double sigma = StdDev( f_prime );\n\n    auto result = std::min_element( data_list.begin(), data_list.end() );\n    double min_power = static_cast<double>(*result);\n\n    uint peak_index = 0;\n    double peak_power = min_power;\n\n    bool peak_identified = false;\n\n    for( unsigned int i = 0; i < f_prime.size() - 1; i++ ) {\n\n        //Establish criteria for a maxima peak;\n\n        bool maxima = ( f_prime.at(i) > 0*sigma && f_prime.at(i+1) < 0*sigma );\n        bool away_from_edges = ( i+1 < (length - 5) && i+1 > 5 );\n\n        if( maxima && away_from_edges ) {\n\n            peak_identified |= true;\n\n            std::cout << \"Found peak at: \" << i <<std::endl;\n\n            uint found_index = i;\n            double found_power = data_list.at(i);\n\n            std::cout << \"Power was: \" << found_power <<std::endl;\n\n            //check to see if peak index is already an element in the map\n            //if duplicate is found check which frequency seperation is the smallest\n            //between the current and stored value.\n            if( peak_index != 0 ) {\n                std::cout << \"Duplicate Index Detected\" << std::endl;\n\n                //if stored value is greater than current value, replaced stored value with current\n                if( found_power > peak_power ) {\n                    std::cout << \"Found Peak was Greater.\" << std::endl;\n//                        std::cout<<\"Power was: \"<<found_power<<std::endl;\n                    peak_index = found_index;\n                    peak_power = found_power;\n                    //if stored value is less than current leave stored value unchanged\n                } else {\n                    std::cout << \"Found Peak was Less.\" << std::endl;\n//                        std::cout<<\"Power was: \"<<found_power<<std::endl;\n                }\n            } else { //if no duplicate is found create a new entry\n                peak_index = found_index;\n                peak_power = found_power;\n            }\n\n        }\n    }\n\n    if( !peak_identified ) {\n        throw mode_track_failure( \"No local maxima found.\" );\n    }\n\n    return peak_index;\n}\n\ninline double QuadraticSpline( double a, double b, double c, double x ) {\n    return a*std::pow( x, 2.0 ) + b*x + c;\n}\n\ndouble ModeTrack::GenerateSpline( int mode_number, double length ) {\n\n    double a = std::get<0>(estimated_paths.at(mode_number));\n    double b = std::get<1>(estimated_paths.at(mode_number));\n    double c = std::get<2>(estimated_paths.at(mode_number));\n\n    return QuadraticSpline(a,b,c,length);\n}\n\nvoid ModeTrack::PopulateBestFitCurves() {\n\n    auto mode_one_coeffs = std::make_tuple(47.9998,-1041.54,8950.56);\n    auto mode_two_coeffs = std::make_tuple(44.2758,-1055.35,9610.61);\n    auto mode_three_coeffs = std::make_tuple(45.8298,-1139.8,10626.7);\n    auto mode_four_coeffs = std::make_tuple(37.697,-1038.49,10780.2);\n\n    estimated_paths.push_back(mode_one_coeffs);\n    estimated_paths.push_back(mode_two_coeffs);\n    estimated_paths.push_back(mode_three_coeffs);\n    estimated_paths.push_back(mode_four_coeffs);\n}\n\ntemplate<typename T>\ninline void removeDuplicates(std::vector<T>& vec) {\n    std::sort(vec.begin(), vec.end());\n    vec.erase(std::unique(vec.begin(), vec.end()), vec.end());\n}\n\nbool ModeTrack::CheckBounds(double frequency) {\n    if( upper_bound == 0.0f || lower_bound == 0.0f ) {\n        //if upper or lower bound is not set always return true\n        return true;\n    } else if (frequency >= upper_bound) {\n        return false;\n    } else if (frequency <= lower_bound) {\n        return false;\n    } else {\n        return true;\n    }\n}\n\ntemplate<typename T>\ninline void c_print(T text,int color) {\n\n    switch( color ) {\n    case 0:\n        //red, error text\n        std::cout<<\"\\033[1;31m\"<< text << \"\\033[0m\\n\";\n        break;\n    case 2:\n        //green, positive confirmation\n        std::cout<<\"\\033[32m\"<< text << \"\\033[0m\\n\";\n        break;\n    case 4:\n        //magenta, header\n        std::cout<<\"\\033[35m\"<< text << \"\\033[0m\\n\";\n        break;\n    case 8:\n        //yellow, warning text\n        std::cout<<\"\\033[33m\"<< text << \"\\033[0m\\n\";\n    default:\n        break;\n    }\n}\n\n//peak_list: list of indices (in frequency space) where peaks were found for a particular cavity length\n//comparison_list: of data triples at the same cavity length\nstd::map<uint,double> ModeTrack::CompareAndFill( const std::vector<double>& peak_list,\\\n        const std::vector< data_triple< double > >& comparison_list ) {\n\n    //format is <peak index,<delta_mu,frequency>>\n    //where delta_mu is defined below\n    std::map< uint,std::pair< uint,double> > found_peaks;\n\n    //since the cavity length is identical for each element in the set of data triples\n    //use the length reported by the first element.\n    double g_length = comparison_list.at(0).cavity_length;\n\n    for( const auto& peak_index : peak_list ) {\n\n        std::vector<double> results;\n\n        data_triple<double> data_entry = comparison_list.at(peak_index);\n\n        double frequency = data_entry.frequency_MHz;\n        double length = data_entry.cavity_length;\n\n        for (int i = 0; i < 4 ; i++) {\n            double estimated_frequency = GenerateSpline(i,length);\n\n            std::cout << \"Actual frequency \"\n                      << frequency\n                      << \" estimated frequency of peak \"\n                      << i\n                      << \" \"\n                      << estimated_frequency\n                      << std::endl;\n\n            double delta_mu = std::abs(frequency - estimated_frequency);\n            results.push_back(delta_mu);\n        }\n\n        auto minima = std::min_element(std::begin(results), std::end(results));\n        auto min_val = *minima;\n        auto min_position = std::distance(std::begin(results), minima);\n\n        std::cout<<\"Smallest frequency seperation: \"<<min_val;\n        std::cout<<\" at Peak: \"<<min_position<<std::endl;\n\n        if(min_val >= max_search_radius) {\n            c_print(\"Identified peak was too far from any estimated value.\",0);\n            continue;\n        }\n\n        std::make_pair(min_val,frequency);\n\n        //check to see if peak index is already an element in the map\n        //if duplicate is found check which frequency seperation is the smallest\n        //between the current and stored value.\n        if( found_peaks.count(min_position) != 0 ) {\n//            std::cout<<\"Duplicate Index Detected\"<<std::endl;\n\n            //if stored value is greater than current value, replaced stored value with current\n            if( found_peaks[min_position].first > min_val ) {\n//                std::cout<<\"Found Peak was Greater.\"<<std::endl;\n                found_peaks[min_position] = std::make_pair(min_val,frequency);\n                //if stored value is less than current leave stored value unchanged\n            } else {\n//                std::cout<<\"Found Peak was Less.\"<<std::endl;\n            }\n        } else { //if no duplicate is found create a new entry\n            found_peaks[min_position] = std::make_pair(min_val,frequency);\n        }\n\n    }\n\n    //initalize map to default \"error\" value of all zeros\n    //if this initial value is returned it will caused GetPeaks\n    //to return a value of 0.0f which is interpreted as the\n    //standard error value.\n    if(found_peaks.empty()) {\n        found_peaks[0]=std::make_pair(0,0.0);\n    }\n\n    //create container to hold identified peaks\n    //format is [peak index],frequency\n    std::map<uint,double> identified_peaks;\n\n    //iterate from the first peak index to the last peak index, and all values in between\n    for(uint i = found_peaks.begin()->first ; i <= found_peaks.rbegin()->first ; i ++) {\n\n        //check if the peak index corresponds to a key in the map of found peaks\n        //if peak index is present set frequency for peak using actual data\n        //if peak index is not present assume that the peak was 'missed' and\n        //fill in data using estimated peak position.\n        if( found_peaks.count(i) != 0 ) {\n\n            std::cout<<\"Match for peak: \"<<i<<\", \";\n            double peak_frequency = found_peaks[i].second;\n//            std::cout<<\"Using real value of: \"<<peak_frequency<<std::endl;\n            std::string message_str = \"Using real value of: \"+boost::lexical_cast<std::string>(peak_frequency)+\"MHz\";\n            c_print(message_str,2);\n            identified_peaks[i] = peak_frequency;\n\n        } else {\n            std::cout<<\"No match for peak: \"<<i<<\", \";\n            double peak_frequency = GenerateSpline(i,g_length);\n//            std::cout<<\"Filling with estimate of: \"<<peak_frequency<<std::endl;\n            std::string message_str = \"Filling with estimate of: \"+boost::lexical_cast<std::string>(peak_frequency)+\"MHz\";\n            c_print(message_str,8);\n            identified_peaks[i] = peak_frequency;\n        }\n    }\n\n    return identified_peaks;\n\n}\n\nstd::vector<double> ModeTrack::BilateralFilter( const std::vector<double>& data_list, double sigma_s, double sigma_r ) {\n\n    int list_size = data_list.size();\n\n    int radius = static_cast<int>( ceil( 5.0/2.0*sigma_s ) );\n\n    //Copy data_list into deque to speed up front/back insertions that will be needed\n    //for zero padding\n    std::deque<double> data_deque ( data_list.begin(),data_list.end() );\n    //Pad data_list with zeros at front and back\n    for (int i=1; i<=radius; i++) {\n        data_deque.push_front(0.0);\n        data_deque.push_back(0.0);\n    }\n\n    std::vector<double> convolved_list;\n\n    #pragma omp parallel for ordered schedule(dynamic)\n    for( int p = radius; p < list_size + radius; p++ ) {\n\n        double conv_element = 0.0;\n        double norm_weight = 0.0;\n\n        for(int q = p -radius; q <= p + radius ; q++) {\n\n            double pos_weight = std::abs( p - q );\n            double intens_weight = data_deque.at(p) - data_deque.at(q);\n            double val_sigma_s = gaussian( pos_weight, sigma_s );\n            double val_sigma_r = gaussian( intens_weight, sigma_r );\n            norm_weight += val_sigma_s*val_sigma_r;\n            conv_element += val_sigma_s*val_sigma_r*data_deque.at(q);\n\n        }\n\n        #pragma omp ordered\n        convolved_list.push_back(conv_element/norm_weight);\n    }\n\n    return convolved_list;\n}\n\nstd::vector< double > ModeTrack::data_triples_to_power( const std::vector<data_triple<double> >& data_list ) {\n\n    std::vector< double > power_list;\n    power_list.reserve( data_list.size() );\n\n    for( uint i = 0; i < data_list.size() ; i++ ) {\n        power_list.push_back( data_list[i].power_dBm );\n    }\n\n    return power_list;\n\n}\n", "meta": {"hexsha": "2378357a1c81ae63ed61192894cbb7fd7a40a70c", "size": 20488, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ModeTracker/modetrack.cpp", "max_stars_repo_name": "SashaNullptr/Tiger-Acquire", "max_stars_repo_head_hexsha": "af1de6852e64a8df89a1fa20dfe01e541a84c887", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ModeTracker/modetrack.cpp", "max_issues_repo_name": "SashaNullptr/Tiger-Acquire", "max_issues_repo_head_hexsha": "af1de6852e64a8df89a1fa20dfe01e541a84c887", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ModeTracker/modetrack.cpp", "max_forks_repo_name": "SashaNullptr/Tiger-Acquire", "max_forks_repo_head_hexsha": "af1de6852e64a8df89a1fa20dfe01e541a84c887", "max_forks_repo_licenses": ["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.098546042, "max_line_length": 135, "alphanum_fraction": 0.6251952362, "num_tokens": 5129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.27966548293615906}}
{"text": "/*\n\tThis file contains the primitive type definition, macros and includes shared by other project files\n*/\n#ifndef polyvec_api_h_\n#define polyvec_api_h_\n\n// libc\n#define _USE_MATH_DEFINES\n#include <math.h>\n\n// C++ STL\n#include <stdint.h>\n#include <string>\n#include <memory>\n#include <vector>\n#include <unordered_map>\n#include <unordered_set>\n#include <limits>\n\n#ifndef FLT_MAX\n#define FLT_MAX std::numeric_limits<float>::max()\n#endif\n\n// Eigen\n#include <Eigen/Core>\n\n// Platform specific macros\n#ifdef _MSC_VER\n\n#define break_here throw std::exception()\n#define polyvec_inline __forceinline\n\n#define polyvec_win32 1\n#define polyvec_posix 0\n\n#else\n#define break_here do{assert(0); throw std::runtime_error(\"error\");}while(0)\n#define polyvec_inline __attribute__((always_inline)) inline\n\n#define polyvec_win32 0\n#define polyvec_posix 1\n\n#endif\n\n#ifndef break_here\n#define throw std::exception()\n#endif\n\n// Generic macros\n#ifndef param_unused\n#define param_unused(x) (void)(x)\n#endif\n\n#define result_unused(x) (void)(x)\n\n#ifndef assert_break\n#define assert_break(x) { if (!(x)) { fprintf(stderr, \"\\nFAILED ASSERT \" #x  \"\\n      LOCATION %s:%d\", __FILE__, __LINE__); break_here; } }\n#define assert_break_msg(x, msg) { if (!(x)) { fprintf(stderr, \"\\nFAILED ASSERT %s\"  \"\\n      LOCATION %s:%d\", msg,__FILE__, __LINE__); break_here; } }\n#endif\n\n#define array_len(x) (sizeof(x)/sizeof((x)[0]))\n#ifndef logic_xor // https://benpfaff.org/writings/clc/logical-xor.html\n#define logic_xor(a, b) ((!(a)) != (!(b)))\n#endif\n\n#define polyvec_str(__X)   static_cast<std::ostringstream&>(std::ostringstream().flush() << __X).str()\n#define polyvec_c_str(__X) polyvec_str(__X).c_str()\n\n//\n// Type aliases\nnamespace polyvec {\n\n    using index = std::int64_t;\n    using indexu = std::size_t;\n\n\n    using str = std::string;\n    using hash64 = uint64_t; // let's not confuse this with the other bunch of integers\n\n    template <typename T>\n    using ptr = std::unique_ptr<T>;\n\n    template <typename K, typename V>\n    using umap = std::unordered_map<K, V>;\n\n    template <typename V>\n    using uset = std::unordered_set<V>;\n\n// Matrix aliases\n    using byte4 = Eigen::Matrix<uint8_t, 4, 1>;\n    using real = double;\n    using int2 = Eigen::Vector2i;\n    using int3 = Eigen::Vector3i;\n    using int4 = Eigen::Vector4i;\n    using real2 = Eigen::Vector2d;\n    using real4 = Eigen::Vector4d;\n    using mat2 = Eigen::Matrix2d;\n    using mat3 = Eigen::Matrix3d;\n    using mat4 = Eigen::Matrix4d;\n    using real2xN = Eigen::Matrix2Xd;\n    using real1xN = Eigen::VectorXd;\n\n// Matrix Constants\n    extern const index index_null;\n    extern const hash64 hash64_null;\n    extern const index index_max;\n    extern const int   int_max;\n    extern const uint32_t uint32_max;\n    extern const int32_t int32_max;\n    extern const int64_t int64_max;\n    extern const double real_max;\n    extern const real2 real2_0;\n    extern const real2 real2_1;\n    extern const real2 real2_lo; // lowest\n    extern const real2 real2_hi; // max\n#define            real2_xy(xy) (real2((xy), (xy))) // avoid evaluating twice?\n\n    using real3 = Eigen::Vector3d;\n    extern const real3 real3_0;\n    extern const real3 real3_1;\n    extern const real3 real3_lo; // lowest\n    extern const real3 real3_hi; // max\n\n//\n// Constants\n    namespace constants {\n        static constexpr double PI          = M_PI;\n        static constexpr double PI_inv      = M_1_PI;\n        static constexpr double PI_half     = M_PI_2;\n        static constexpr double PI_half_inv = 1. / PI_half;\n        static constexpr double PI2         = PI * 2;\n        static constexpr double PI3_4       = 3 * M_PI_4;\n        static constexpr double PI_4        = M_PI_4;\n        static constexpr double PIDiv180    = 0.017453292519943295769236907684886;\n\n        static constexpr double SmallEps = 1e-4;\n        static constexpr double BigEps   = 1e-07;\n        static constexpr double Eps      = 1e-10;\n    }\n\n\n\n//\n// Indexing\n// The code works with stricly typed indices that do not allow implicit conversions to other types.\n// Warnings should be set to level4/Wall and stop compilation.\n//\n// Add any overload when required, *keep* in mind that to mantain\n// strict typing:\n// 1. IF conversion operator to `index`        NO non-explicit constructor from `index`\n// 2. IF non-explicit constructor from `index` NO  conversion operator to `index`\n// (1) is better as allows having to overload all integer operations\n//\n// DO NOT COMPARE VALIDITY with -1 as it's a perfectly valid index\n//\n#define define_typed_index(t, i)\\\n    struct t{\\\n        const static t null;\\\n        i _v;\\\n        explicit t(i v = index_null) : _v(v) { }\\\n        operator std::int64_t()const { return _v; }\\\n        explicit operator bool()const { return _v != null; }\\\n        t& operator=(i v) { _v = v; return *this; }\\\n        t& operator=(int v) { _v = (i)v; return *this; }\\\n        bool operator <(i rhs) const { return (i)_v < rhs;}\\\n        t& operator++() { ++_v; return *this; }\\\n        t& operator--() { --_v; return *this; }\\\n    };\\\n    inline t operator-(t lhs, t rhs) { return (t)(lhs._v - rhs._v); }\\\n    inline t operator+(t lhs, t rhs) { return (t)(lhs._v + rhs._v); }\\\n    inline t operator-(t lhs, int rhs) { return (t)(lhs._v - rhs); }\\\n    inline t operator+(t lhs, int rhs) { return (t)(lhs._v + rhs); }\\\n    inline t operator%(t lhs, t rhs) { return (t)(lhs._v % rhs._v); }\\\n    static_assert(sizeof(i) == sizeof(t), \"Replace compiler with less edgy cousin\");\n\n#define define_typed_index_hash(t)\\\n    struct _std_hash_index_##t {\\\n        hash64 operator() (t##_idx i) const {\\\n            return (hash64)i._v;\\\n        }\\\n    };\\\n    struct _std_hash_index_pair_##t {\\\n        hash64 operator() (const std::pair<t##_idx, t##_idx>& p) const {\\\n            return hash_index_pair(p.first._v, p.second._v);\\\n        }\\\n    };\n\n    hash64 hash_index_pair ( index lhs, index rhs );\n    hash64 hash_index_tuple ( index e0, index e1, index e2 );\n\n// Since there are many different buffers around and they also may be circular or not\n// each index has different types to avoid mistakes (naming helps too). It can be used\n// as a normal index, but won't be implicitly converted to other types\n    define_typed_index ( vertex_idx, index );\n    define_typed_index ( corner_idx, index );\n    define_typed_index ( node_idx, index );\n    define_typed_index ( edge_idx, index );\n\n    define_typed_index_hash ( vertex );\n    define_typed_index_hash ( corner );\n    define_typed_index_hash ( node );\n    define_typed_index_hash ( edge );\n\n    struct _std_hash_node {\n        hash64 operator() ( const std::tuple<corner_idx, corner_idx, corner_idx>& t ) const {\n            return hash_index_tuple ( std::get<0> ( t )._v, std::get<1> ( t )._v, std::get<2> ( t )._v );\n        }\n    };\n\n}\n\n// Prevent astyle from indenting namespace; while not touching already written files\n#define NAMESPACE_BEGIN(NAME__) namespace NAME__ {\n#define NAMESPACE_END(NAME__)                    }\n\n#endif // polyvec_api_h_", "meta": {"hexsha": "3ffbee3f5c191e0db8457a40f81d54871fecfe2a", "size": 7001, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/polyvec/api.hpp", "max_stars_repo_name": "ShnitzelKiller/polyfit", "max_stars_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-08-17T17:25:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T05:49:12.000Z", "max_issues_repo_path": "include/polyvec/api.hpp", "max_issues_repo_name": "ShnitzelKiller/polyfit", "max_issues_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-08-26T13:54:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T07:19:22.000Z", "max_forks_repo_path": "include/polyvec/api.hpp", "max_forks_repo_name": "ShnitzelKiller/polyfit", "max_forks_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-08-26T23:26:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-04T09:06:07.000Z", "avg_line_length": 32.412037037, "max_line_length": 151, "alphanum_fraction": 0.6620482788, "num_tokens": 1891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792046, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.2796049527783119}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n * Copyright 2016 Colin Heinzmann                                            *\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 <iostream>\nusing namespace std;\n#include <unistd.h>\n\n#include <QList>\n\n#include <Eigen/Dense>\n\n#include <opencv2/opencv.hpp>\nusing namespace cv;\n\n#include <openbr/plugins/openbr_internal.h>\n#include <openbr/core/common.h>\n#include <openbr/core/eigenutils.h>\n#include <openbr/core/opencvutils.h>\n\n#include <cuda_runtime.h>\n#include <cublas_v2.h>\n#include <cusolverDn.h>\n#include \"cudadefines.hpp\"\n\nnamespace br { namespace cuda { namespace pca {\n  void castFloatToDouble(float* a, int inca, double* b, int incb, int numElems);\n  void castDoubleToFloat(double* a, int inca, float* b, int incb, int numElems);\n}}}\n\nnamespace br\n{\n/*!\n * \\ingroup transforms\n * \\brief Projects input into learned Principal Component Analysis subspace using CUDA. Modified from original PCA plugin.\n * \\author Colin Heinzmann \\cite DepthDeluxe\n *\n * \\br_property float keep Options are: [keep < 0 - All eigenvalues are retained, keep == 0 - No PCA is performed and the eigenvectors form an identity matrix, 0 < keep < 1 - Keep is the fraction of the variance to retain, keep >= 1 - keep is the number of leading eigenvectors to retain] Default is 0.95.\n * \\br_property int drop The number of leading eigen-dimensions to drop.\n * \\br_property bool whiten Whether or not to perform PCA whitening (i.e., normalize variance of each dimension to unit norm)\n */\nclass CUDAPCATransform : public Transform\n{\n    Q_OBJECT\n\nprotected:\n    Q_PROPERTY(float keep READ get_keep WRITE set_keep RESET reset_keep STORED false)\n    Q_PROPERTY(int drop READ get_drop WRITE set_drop RESET reset_drop STORED false)\n    Q_PROPERTY(bool whiten READ get_whiten WRITE set_whiten RESET reset_whiten STORED false)\n\n    BR_PROPERTY(float, keep, 0.95)\n    BR_PROPERTY(int, drop, 0)\n    BR_PROPERTY(bool, whiten, false)\n\n    Eigen::VectorXf mean;\n    Eigen::VectorXf eVals;\n    Eigen::MatrixXf eVecs;\n\n    cublasHandle_t cublasHandle;\n    float* cudaMeanPtr;     // holds the \"keep\" long vector\n    float* cudaEvPtr;       // holds all the eigenvectors\n\npublic:\n    CUDAPCATransform() : keep(0.95), drop(0), whiten(false) {\n      // try to initialize CUBLAS\n      cublasStatus_t status;\n      status = cublasCreate(&cublasHandle);\n      CUBLAS_ERROR_CHECK(status);\n    }\n\n    ~CUDAPCATransform() {\n      // tear down CUBLAS\n      cublasDestroy(cublasHandle);\n    }\n\nprivate:\n    double residualReconstructionError(const Template &src) const\n    {\n        Template proj;\n        project(src, proj);\n\n        Eigen::Map<const Eigen::VectorXf> srcMap(src.m().ptr<float>(), src.m().rows*src.m().cols);\n        Eigen::Map<Eigen::VectorXf> projMap(proj.m().ptr<float>(), keep);\n\n        return (srcMap - mean).squaredNorm() - projMap.squaredNorm();\n    }\n\n    void train(const TemplateList &cudaTrainingSet)\n    {\n      cublasStatus_t cublasStatus;\n      cudaError_t cudaError;\n\n      // put all the data into a single matrix to perform PCA\n      const int instances = cudaTrainingSet.size();\n      const int dimsIn = *(int*)cudaTrainingSet.first().m().ptr<void*>()[1]\n                               * *(int*)cudaTrainingSet.first().m().ptr<void*>()[2];\n\n      // copy the data over\n      double* cudaDataPtr;\n      CUDA_SAFE_MALLOC(&cudaDataPtr, instances*dimsIn*sizeof(cudaDataPtr[0]), &cudaError);\n      for (int i=0; i < instances; i++) {\n        br::cuda::pca::castFloatToDouble(\n          (float*)(cudaTrainingSet[i].m().ptr<void*>()[0]),\n          1,\n          cudaDataPtr+i*dimsIn,\n          1,\n          dimsIn\n        );\n      }\n\n      trainCore(cudaDataPtr, dimsIn, instances);\n\n      CUDA_SAFE_FREE(cudaDataPtr, &cudaError);\n    }\n\n    void project(const Template &src, Template &dst) const\n    {\n      cudaError_t cudaError;\n\n      void* const* srcDataPtr = src.m().ptr<void*>();\n      float* srcGpuMatPtr = (float*)srcDataPtr[0];\n      int rows = *((int*)srcDataPtr[1]);\n      int cols = *((int*)srcDataPtr[2]);\n      int type = *((int*)srcDataPtr[3]);\n\n      if (type != CV_32FC1) {\n        cout << \"ERR: Invalid image type\" << endl;\n        throw 0;\n      }\n\n      // save the destination rows\n      int dstRows = (int)keep;\n\n      Mat dstMat = Mat(src.m().rows, src.m().cols, src.m().type());\n      void** dstDataPtr = dstMat.ptr<void*>();\n      float** dstGpuMatPtrPtr = (float**)dstDataPtr;\n      dstDataPtr[1] = srcDataPtr[1];  *((int*)dstDataPtr[1]) = 1;\n      dstDataPtr[2] = srcDataPtr[2];  *((int*)dstDataPtr[2]) = dstRows;\n      dstDataPtr[3] = srcDataPtr[3];\n\n\n      // allocate the memory and set to zero\n      //cout << \"Allocating destination memory\" << endl;\n      cublasStatus_t status;\n      cudaMalloc(dstGpuMatPtrPtr, dstRows*sizeof(float));\n      cudaMemset(*dstGpuMatPtrPtr, 0, dstRows*sizeof(float));\n\n      {\n        float negativeOne = -1.0f;\n        status = cublasSaxpy(\n          cublasHandle,       // handle\n          dstRows,            // vector length\n          &negativeOne,       // alpha (1)\n          cudaMeanPtr,        // mean\n          1,                  // stride\n          srcGpuMatPtr,       // y, the source\n          1                   // stride\n        );\n        CUBLAS_ERROR_CHECK(status);\n      }\n\n      {\n        float one = 1.0f;\n        float zero = 0.0f;\n        status = cublasSgemv(\n          cublasHandle,       // handle\n          CUBLAS_OP_T,        // normal vector multiplication\n          eVecs.rows(),       // # rows\n          eVecs.cols(),       // # cols\n          &one,               // alpha (1)\n          cudaEvPtr,          // pointer to the matrix\n          eVecs.rows(),       // leading dimension of matrix\n          srcGpuMatPtr,       // vector for multiplication\n          1,                  // stride (1)\n          &zero,              // beta (0)\n          *dstGpuMatPtrPtr,   // vector to store the result\n          1                   // stride (1)\n        );\n        CUBLAS_ERROR_CHECK(status);\n      }\n\n      //cout << \"Saving result\" << endl;\n      dst = dstMat;\n      CUDA_SAFE_FREE(srcGpuMatPtr, &cudaError);\n    }\n\n    void store(QDataStream &stream) const\n    {\n        stream << keep << drop << whiten <<  mean << eVecs;\n    }\n\n    void load(QDataStream &stream)\n    {\n        stream >> keep >> drop >> whiten >> mean >> eVecs;\n\n        //cout << \"Starting load process\" << endl;\n\n        cudaError_t cudaError;\n        cublasStatus_t cublasStatus;\n        CUDA_SAFE_MALLOC(&cudaMeanPtr, mean.rows()*mean.cols()*sizeof(float), &cudaError);\n        CUDA_SAFE_MALLOC(&cudaEvPtr, eVecs.rows()*eVecs.cols()*sizeof(float), &cudaError);\n\n        //cout << \"Setting vector\" << endl;\n        // load the mean vector into GPU memory\n        cublasStatus = cublasSetVector(\n          mean.rows()*mean.cols(),\n          sizeof(float),\n          mean.data(),\n          1,\n          cudaMeanPtr,\n          1\n        );\n        CUBLAS_ERROR_CHECK(cublasStatus);\n\n        //cout << \"Setting the matrix\" << endl;\n        // load the eigenvector matrix into GPU memory\n        cublasStatus = cublasSetMatrix(\n          eVecs.rows(),\n          eVecs.cols(),\n          sizeof(float),\n          eVecs.data(),\n          eVecs.rows(),\n          cudaEvPtr,\n          eVecs.rows()\n        );\n        CUBLAS_ERROR_CHECK(cublasStatus);\n    }\n\nprotected:\n    void trainCore(double* cudaDataPtr, int dimsIn, int instances) {\n      cudaError_t cudaError;\n\n      const bool dominantEigenEstimation = (dimsIn > instances);\n\n      Eigen::MatrixXd allEVals, allEVecs;\n\n      // allocate the eigenvectors\n      if (dominantEigenEstimation) {\n        allEVals = Eigen::MatrixXd(instances, 1);\n        allEVecs = Eigen::MatrixXd(dimsIn, instances);\n      } else {\n        allEVals = Eigen::MatrixXd(dimsIn, 1);\n        allEVecs = Eigen::MatrixXd(dimsIn, dimsIn);\n      }\n\n      if (keep != 0) {\n        performCovarianceSVD(cudaDataPtr, dimsIn, instances, allEVals, allEVecs);\n      } else {\n        // null case\n        mean = Eigen::VectorXf::Zero(dimsIn);\n        allEVecs = Eigen::MatrixXd::Identity(dimsIn, dimsIn);\n        allEVals = Eigen::VectorXd::Ones(dimsIn);\n      }\n\n      // *****************\n      // We have now found the eigenvalues and eigenvectors\n      // *****************\n\n      if (keep <= 0) {\n          keep = dimsIn - drop;\n      } else if (keep < 1) {\n          // Keep eigenvectors that retain a certain energy percentage.\n          const double totalEnergy = allEVals.sum();\n          if (totalEnergy == 0) {\n              keep = 0;\n          } else {\n              double currentEnergy = 0;\n              int i=0;\n              while ((currentEnergy / totalEnergy < keep) && (i < allEVals.rows())) {\n                  currentEnergy += allEVals(i);\n                  i++;\n              }\n              keep = i - drop;\n          }\n      } else {\n          if (keep + drop > allEVals.rows()) {\n              qWarning(\"Insufficient samples, needed at least %d but only got %d.\", (int)keep + drop, (int)allEVals.rows());\n              keep = allEVals.rows() - drop;\n          }\n      }\n\n      // Keep highest energy vectors\n      eVals = Eigen::VectorXf((int)keep, 1);\n      eVecs = Eigen::MatrixXf(allEVecs.rows(), (int)keep);\n      for (int i=0; i<keep; i++) {\n          int index = i+drop;\n          eVals(i) = allEVals(index);\n          eVecs.col(i) = allEVecs.col(index).cast<float>();\n          if (whiten) eVecs.col(i) /= sqrt(eVals(i));\n      }\n\n      // Debug output\n      if (Globals->verbose) qDebug() << \"PCA Training:\\n\\tDimsIn =\" << dimsIn << \"\\n\\tKeep =\" << keep;\n    }\n\n    // computes the covariance matrix and then pulls the eigenvalues+eigenvectors\n    // out of it using SVD of a symmetric matrix\n    void performCovarianceSVD(double* cudaDataPtr, int dimsIn, int instances, Eigen::MatrixXd& allEVals, Eigen::MatrixXd& allEVecs) {\n      cudaError_t cudaError;\n\n      const bool dominantEigenEstimation = (dimsIn > instances);\n\n      // used for temporary storage\n      Eigen::VectorXd meanDouble(dimsIn);\n\n      // compute the mean\n      for (int i=0; i < dimsIn; i++) {\n        cublasDasum(\n          cublasHandle,\n          instances,\n          cudaDataPtr+i,\n          dimsIn,\n          meanDouble.data()+i\n        );\n      }\n\n      // put data back on GPU for further processing\n      double* cudaMeanDoublePtr;\n      CUDA_SAFE_MALLOC(&cudaMeanDoublePtr, dimsIn*sizeof(cudaMeanDoublePtr[0]), &cudaError);\n      cublasSetVector(\n        dimsIn,\n        sizeof(cudaMeanDoublePtr[0]),\n        meanDouble.data(),\n        1,\n        cudaMeanDoublePtr,\n        1\n      );\n\n      // scale to calculate average\n      {\n        double scaleFactor = 1.0/(double)instances;\n        cublasDscal(\n          cublasHandle,\n          dimsIn,\n          &scaleFactor,\n          cudaMeanDoublePtr,\n          1\n        );\n      }\n\n      // subtract mean from data\n      for (int i=0; i < instances; i++) {\n        double negativeOne = -1.0;\n        cublasDaxpy(\n          cublasHandle,\n          dimsIn,\n          &negativeOne,\n          cudaMeanDoublePtr,\n          1,\n          cudaDataPtr+i*dimsIn,\n          1\n        );\n      }\n\n      // convert to float form and copy the data back\n      CUDA_SAFE_MALLOC(&cudaMeanPtr, dimsIn*sizeof(cudaMeanPtr[0]), &cudaError);\n      br::cuda::pca::castDoubleToFloat(cudaMeanDoublePtr, 1, cudaMeanPtr, 1, dimsIn);\n\n      // copy the data back\n      mean = Eigen::VectorXf(dimsIn);\n      cublasGetVector(\n        dimsIn,\n        sizeof(cudaMeanPtr[0]),\n        cudaMeanPtr,\n        1,\n        mean.data(),\n        1\n      );\n\n      // free up the memory\n      CUDA_SAFE_FREE(cudaMeanDoublePtr, &cudaError);\n      CUDA_SAFE_FREE(cudaMeanPtr, &cudaError);\n\n      // allocate space for the covariance matrix\n      double* cudaCovariancePtr;\n      int covRows = allEVals.rows();\n      CUDA_SAFE_MALLOC(&cudaCovariancePtr, covRows*covRows*sizeof(cudaCovariancePtr[0]), &cudaError);\n\n      // compute the covariance matrix\n      if (dominantEigenEstimation) {\n        // cov = data.transpose() * data / (instances-1.0);\n        const double scaleFactor = 1.0/(instances-1.0);\n        const double zero = 0.0;\n        cublasDgemm(\n          cublasHandle,\n          CUBLAS_OP_T,\n          CUBLAS_OP_N,\n          instances,\n          instances,\n          dimsIn,\n          &scaleFactor,\n          cudaDataPtr,\n          dimsIn,\n          cudaDataPtr,\n          dimsIn,\n          &zero,\n          cudaCovariancePtr,\n          covRows\n        );\n      } else {\n        // cov = data * data.transpose() / (instances-1.0);\n        const double scaleFactor = 1.0/(instances-1.0);\n        const double zero = 0.0;\n        cublasDgemm(\n          cublasHandle,\n          CUBLAS_OP_N,\n          CUBLAS_OP_T,\n          dimsIn,\n          dimsIn,\n          instances,\n          &scaleFactor,\n          cudaDataPtr,\n          dimsIn,\n          cudaDataPtr,\n          dimsIn,\n          &zero,\n          cudaCovariancePtr,\n          covRows\n        );\n      }\n\n      cusolverDnHandle_t cusolverHandle;\n      cusolverStatus_t cusolverStatus;\n      cusolverDnCreate(&cusolverHandle);\n\n      // allocate appropriate working space\n      int svdLWork;\n      cusolverDnDgesvd_bufferSize(\n        cusolverHandle,\n        covRows,\n        covRows,\n        &svdLWork\n      );\n      double* cudaSvdWork;\n      CUDA_SAFE_MALLOC(&cudaSvdWork, svdLWork*sizeof(cudaSvdWork[0]), &cudaError);\n\n      double* cudaUPtr;\n      CUDA_SAFE_MALLOC(&cudaUPtr, covRows*covRows*sizeof(cudaUPtr[0]), &cudaError);\n      double* cudaSPtr;\n      CUDA_SAFE_MALLOC(&cudaSPtr, covRows*sizeof(cudaSPtr[0]), &cudaError);\n      double* cudaVTPtr;\n      CUDA_SAFE_MALLOC(&cudaVTPtr, covRows*covRows*sizeof(cudaVTPtr[0]), &cudaError);\n\n      int* cudaSvdDevInfoPtr;\n      CUDA_SAFE_MALLOC(&cudaSvdDevInfoPtr, sizeof(*cudaSvdDevInfoPtr), &cudaError);\n      int svdDevInfo;\n\n      // perform SVD on an n x m matrix, in this case the matrix is the covariance\n      // matrix and is symmetric, meaning the SVD will calculate the eigenvalues\n      // and eigenvectors for us.\n      cusolverStatus = cusolverDnDgesvd(\n        cusolverHandle,\n        'A',                // all columns of unitary matrix\n        'A',                // all columns of array VT\n        covRows,            // m\n        covRows,            // n\n        cudaCovariancePtr,  // decomposing the covariance matrix\n        covRows,            // lda\n        cudaSPtr,           // holds S\n        cudaUPtr,           // holds U\n        covRows,            // ldu\n        cudaVTPtr,          // holds VT\n        covRows,            // ldvt\n        cudaSvdWork,        // work buffer ptr\n        svdLWork,           // length of the work buffer\n        NULL,               // rwork, not used for real data types\n        cudaSvdDevInfoPtr   // devInfo pointer\n      );\n      CUSOLVER_ERROR_CHECK(cusolverStatus);\n\n      // get the eigenvalues and free memory\n      cublasGetVector(\n        covRows,\n        sizeof(cudaSPtr[0]),\n        cudaSPtr,\n        1,\n        allEVals.data(),\n        1\n      );\n      CUDA_SAFE_FREE(cudaSvdWork, &cudaError);\n      CUDA_SAFE_FREE(cudaSPtr, &cudaError);\n      CUDA_SAFE_FREE(cudaVTPtr, &cudaError);\n      CUDA_SAFE_FREE(cudaSvdDevInfoPtr, &cudaError);\n\n      // if this is a dominant eigen estimation, then perform matrix multiplication again\n      // if (dominantEigenEstimation) allEVecs = data * allEVecs;\n      if (dominantEigenEstimation) {\n        double* cudaMultedAllEVecs;\n        CUDA_SAFE_MALLOC(&cudaMultedAllEVecs, dimsIn*instances*sizeof(cudaMultedAllEVecs[0]), &cudaError);\n        const double one = 1.0;\n        const double zero = 0;\n\n        cublasDgemm(\n          cublasHandle,   // handle\n          CUBLAS_OP_N,    // transa\n          CUBLAS_OP_N,    // transb\n          dimsIn,         // m\n          instances,      // n\n          instances,      // k\n          &one,           // alpha\n          cudaDataPtr,    // A\n          dimsIn,         // lda\n          cudaUPtr,       // B\n          instances,      // ldb\n          &zero,          // beta\n          cudaMultedAllEVecs, // C\n          dimsIn          // ldc\n        );\n\n        // normalize result then divide the column by the norm\n        for (int i=0; i < instances; i++) {\n          // compute the norm\n          double norm;\n          cublasDnrm2(\n            cublasHandle,\n            dimsIn,\n            cudaMultedAllEVecs+i*dimsIn,\n            1,\n            &norm\n          );\n\n          // now divide by it\n          norm = 1.0/norm;\n          cublasDscal(\n            cublasHandle,\n            dimsIn,\n            &norm,\n            cudaMultedAllEVecs+i*dimsIn,\n            1\n          );\n        }\n\n        // get the eigenvectors from the multiplied value\n        cublasGetMatrix(\n          dimsIn,\n          instances,\n          sizeof(cudaMultedAllEVecs[0]),\n          cudaMultedAllEVecs,\n          dimsIn,\n          allEVecs.data(),\n          dimsIn\n        );\n\n        // free the memory used for multiplication\n        CUDA_SAFE_FREE(cudaMultedAllEVecs, &cudaError);\n      } else {\n        // normalize result then divide the column by the norm\n        for (int i=0; i < instances; i++) {\n          // compute the norm\n          double norm;\n          cublasDnrm2(\n            cublasHandle,\n            covRows,\n            cudaUPtr+i*covRows,\n            1,\n            &norm\n          );\n\n          // now divide by it\n          norm = 1.0/norm;\n          cublasDscal(\n            cublasHandle,\n            covRows,\n            &norm,\n            cudaUPtr+i*covRows,\n            1\n          );\n        }\n\n\n        // get the eigenvectors straight from the SVD\n        cublasGetMatrix(\n          covRows,\n          covRows,\n          sizeof(cudaUPtr[0]),\n          cudaUPtr,\n          covRows,\n          allEVecs.data(),\n          covRows\n        );\n      }\n\n\n      // free all the memory\n      CUDA_SAFE_FREE(cudaCovariancePtr, &cudaError);\n      CUDA_SAFE_FREE(cudaUPtr, &cudaError);\n      cusolverDnDestroy(cusolverHandle);\n    }\n};\n\nBR_REGISTER(Transform, CUDAPCATransform)\n} // namespace br\n\n#include \"cuda/cudapca.moc\"\n", "meta": {"hexsha": "54546d3cfdf23eec62edcbe84b132d0fa791169d", "size": 19143, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openbr/plugins/cuda/cudapca.cpp", "max_stars_repo_name": "wittayaatt/openbr", "max_stars_repo_head_hexsha": "26cb128f740f46b7c18b346e2bcf2af7a8de29da", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1883.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T07:04:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:33:37.000Z", "max_issues_repo_path": "openbr/plugins/cuda/cudapca.cpp", "max_issues_repo_name": "wittayaatt/openbr", "max_issues_repo_head_hexsha": "26cb128f740f46b7c18b346e2bcf2af7a8de29da", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 272.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T09:53:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T08:04:33.000Z", "max_forks_repo_path": "openbr/plugins/cuda/cudapca.cpp", "max_forks_repo_name": "wittayaatt/openbr", "max_forks_repo_head_hexsha": "26cb128f740f46b7c18b346e2bcf2af7a8de29da", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 718.0, "max_forks_repo_forks_event_min_datetime": "2015-01-02T18:51:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T08:10:53.000Z", "avg_line_length": 31.5370675453, "max_line_length": 305, "alphanum_fraction": 0.5503317139, "num_tokens": 4887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.27960226837805585}}
{"text": "#include <webots/Emitter.hpp>\n#include <webots/Receiver.hpp>\n\n#include <string>\n#include <vector>\n#include <cstdlib>\n#include <iostream>\n#include <cmath>\n#include<limits>\n\n#include <Eigen/Dense>\n\n#include \"tracking.h\"\n#include \"greyWolf.h\"\n\n#define _USE_MATH_DEFINES\n\n\ndouble calculate_euclideanDistance(double x1, double z1, double x2, double z2){\n  return pow(pow(x2 - x1,2)+pow(z2 - z1,2),0.5);\n}\n\n\nGreyWolf::GreyWolf(webots::Emitter *emitter_handle, webots::Receiver *receiver_handle, int timestep, robot_tracking::Position init_pos){\n  emitter = emitter_handle;\n  receiver = receiver_handle;\n  timeStep = timestep;\n  receiver->enable(timeStep);\n  printDebuggingInfo = false;\n  starting_position = init_pos;\n  init_information.clear();\n  event_message.clear();\n  a <<1,1;\n  r1<<1,1;\n  r2<< 1,1;\n  if(printDebuggingInfo){\n    std::cout<<\"_________ROBOT INDEX___________:\"<<robot_index<<\"\\n\";\n    std::cout<<starting_position.x<<starting_position.z<<\"\\n\";    \n  }\n}\n\nvoid GreyWolf::set_swarmSettings(int index, int num_wolves, int num_iterations){\n  robot_index = index;\n  numberOfWolves = num_wolves;\n  num_iter = num_iterations;\n}\n\nvoid GreyWolf::set_boundaries(int x_upper,int x_lower,int z_upper,int z_lower){\n  x_upper_boundary = x_upper;\n  x_lower_boundary = x_lower;\n  z_upper_boundary = z_upper;\n  z_lower_boundary = z_lower;\n}\n\nvoid GreyWolf::set_individualSettings(double explore_factor, double multiplication_factor, int social_number){\n  k_exploration = explore_factor;\n  k_multiplication = multiplication_factor;\n  social_learning_number = social_number;\n}\n\nvoid GreyWolf::emit_currentPosition(int current_iter){\n  message.event_id = current_iter;\n  message.index = robot_index;\n  message.robot_position = my_position;\n  message.event_message.assign(\"Position Update\");\n  emitter->send(&message, sizeof(Event));\n  event_message.push_back(message);\n}\n\nvoid GreyWolf::init_StatusUpdate(robot_tracking::Position starting_position){\n  message.event_id = 0;\n  message.index = robot_index;\n  message.robot_position = my_position;\n  message.event_message.assign(\"Initialisation\");\n  emitter->send(&message, sizeof(Event));\n  init_information.push_back(message);\n}\n\nvoid GreyWolf::update_position(robot_tracking::Position position){\n  prev_position = my_position;\n  my_position = position;\n}\n\nvoid GreyWolf::set_targetPosition(robot_tracking::Position target){\n  target_position = target;\n}\n\nvoid GreyWolf::get_allEvents(int current_iter){\n    event_message.clear();\n    Event *received_event;    \n    while(receiver->getQueueLength() > 0){\n      received_event = (Event *) receiver->getData();\n      if(received_event->event_message.compare(\"Initialisation\") == 0)\n        init_information.push_back(*received_event);\n      else if(received_event->event_message.compare(\"Position Update\") == 0){\n        // if(received_event->event_id == current_iter)\n          event_message.push_back(*received_event);      \n      }\n      receiver->nextPacket();\n    }\n    if(printDebuggingInfo){\n      std::cout<<\"Printing Events\\n\";\n      print_AllEvents();\n    }\n}\n\n\n\nvoid GreyWolf::print_AllEvents(){\n  std::cout<<\"_________ROBOT INDEX___________:\"<<robot_index<<\"\\n\";\n  for(std::vector<Event>::const_iterator i = event_message.begin(); i != event_message.end(); ++i){\n    std::cout<<i->event_id<<\"\\t\"<<i->index<<\"\\t\"<<i->event_message<<\"\\n\";\n    std::cout<<\"Position\"<<\"\\t\"<<i->robot_position.x<<\"\\t\"<<i->robot_position.z<<\"\\t\"<<i->robot_position.heading<<\"\\n\";\n  }\n}\n\nvoid GreyWolf::clear_initInformation(){\n  init_information.clear();\n}\n\nvoid GreyWolf::clear_eventMessage(){\n  event_message.clear();\n}\n\ndouble GreyWolf::calculate_EucDist(robot_tracking::Position P1,robot_tracking::Position P2){\n  return std::pow(std::pow(P1.x - P2.x,2) + std::pow(P1.z - P2.z,2),0.5);\n}\n\ndouble GreyWolf::generateRandomNumber(double lowerLimit, double upperLimit){\n  double rand_num = ((double)rand())/((double)RAND_MAX +1);\n  rand_num = lowerLimit + ((upperLimit - lowerLimit)*rand_num);\n  return rand_num;\n}\n\nvoid GreyWolf::calculate_Constants(int current_iter){\n  double buff = (double)k_exploration*((double)1 - ((double)current_iter/(double)num_iter));\n  // std::cout<<\"Buff\"<<buff;\n  a << buff,buff;\n  // std::cout<<a<<\"\\n\";\n  r1 << generateRandomNumber(0,2),generateRandomNumber(0,2);\n  r2 << generateRandomNumber(0,2),generateRandomNumber(0,2);\n  if(printDebuggingInfo){\n    std::cout<<\"current iter\"<<current_iter<<\" and num iter\"<<num_iter<<\"\\n\";\n    std::cout<<\"_________ROBOT INDEX___________:\"<<robot_index<<\"\\n\";\n    std::cout<<\"R1: \"<<r1[0]<<\"\\t\"<<r1[1]<<\"\\n\";\n    std::cout<<\"R2: \"<<r2[0]<<\"\\t\"<<r2[1]<<\"\\n\";\n    std::cout<<\"A: \"<<a[0]<<\"\\t\"<<a[1]<<\"\\n\";        \n  }\n}\n// bool GreyWolf::compareEvents(Event e1, Event e2){\n  // return (e1.index<e2.index);\n// }\n\n// bool comparePairs(const std::pair<GreyWolf::Event,double> &a, \n              // const std::pair<GreyWolf::Event,double> &b) \n// { \n    // return (a.second < b.second); \n// } \n\ndouble GreyWolf::calculate_fitnessOfWolf(int current_iter, robot_tracking::Position wolfStartingPosition, robot_tracking::Position wolfCurrentPosition){\n    \n    double k_intraSwarmDistance = 1 - (current_iter/num_iter);\n    // double k_intraSwarmDistance = 0;\n    double intraSwarmDistance = 0, \twolf_communicationThreshold = 1;\n    for(std::vector<Event>::const_iterator i = event_message.begin(); i!= event_message.end(); ++i){\n      // if(i->event_id == current_iter && i->index != robot_index){\n      if(i->index != robot_index){      \n        intraSwarmDistance += wolf_communicationThreshold/calculate_EucDist(wolfCurrentPosition,i->robot_position);\n      }\n    }\n  //Calculate individual coverage\n    double coverageIndividual = calculate_EucDist(wolfStartingPosition, wolfCurrentPosition);\n    double k_coverageIndividual = 1 - (current_iter/num_iter);\n  //Calculate distance from the goal\n    double k_distanceFromGoal = 1 + (current_iter/num_iter);\n    double distanceFromGoal = calculate_EucDist(target_position,wolfCurrentPosition); \n    \n    double fitness = (k_coverageIndividual*coverageIndividual) + (k_intraSwarmDistance*intraSwarmDistance) - (k_distanceFromGoal*distanceFromGoal);\n    return fitness;\n}\n\nvoid GreyWolf::calculate_FitnessRanker(int current_iter){\n  // fitnessRanker.clear();\n  std::sort(init_information.begin(), init_information.end(),[](Event e1, Event e2){ \n    return (e1.index < e2.index);\n  });// Fix this!\n  for(std::vector<Event>::const_iterator i = event_message.begin(); i != event_message.end(); ++i){\n    //Get the corresponding starting position for that event\n    robot_tracking::Position startingPosition = init_information[i->index].robot_position;\n    //Made change to the first parameter of the fitness function. \n    //Earlier, the current iter was passed as first argument, now the event id is passed.\n    double fitness = calculate_fitnessOfWolf(i->event_id, startingPosition, i->robot_position);\n    fitnessRanker.push_back(std::make_pair(*i,fitness));\n  }\n  //Sort the fitnessRanker\n  std::sort(fitnessRanker.begin(), fitnessRanker.end(), [](const std::pair<GreyWolf::Event,double> &a, const std::pair<GreyWolf::Event,double> &b){ \n    return (a.second < b.second);\n  });\n}\n\nrobot_tracking::Position GreyWolf::calculateNextPosition(int current_iter){\n  bool isOmega = true;\n  Eigen::Vector2d target(target_position.x, target_position.z);\n  Eigen::Vector2d currentPosition(my_position.x, my_position.z);\n  Eigen::Vector2d nextPosition(0,0);\n  robot_tracking::Position next_pos;\n  fitnessRanker.clear();\n  calculate_FitnessRanker(current_iter);\n  calculate_Constants(current_iter);\n  Eigen::Vector2d A,C,D,buff;\n  \n  \n  \n  for (int i=0;i<social_learning_number;i++){\n    if(fitnessRanker[i].first.index == robot_index)\n      isOmega = false;\n  }\n  //Calculate A\n  A << 2*a[0]*r1[0] , 2*a[1]*r1[1];\n  A -= a;\n  //Calculate C\n  C = 2*r2;\n  \n  if(isOmega){\n    //Calculate D\n    D << C[0]*target[0] , C[1]*target[1];\n    D -= currentPosition; \n    nextPosition << A[0]*D[0] ,A[1]*D[1];\n    nextPosition  = target - nextPosition;\n  } \n  else{\n    for (int j=0;j<social_learning_number;j++){\n      D << C[0]*fitnessRanker[j].first.robot_position.x, C[1]*fitnessRanker[j].first.robot_position.z;\n      D -= currentPosition;\n      buff <<fitnessRanker[j].first.robot_position.x - A[0]*D[0] , fitnessRanker[j].first.robot_position.z - A[1]*D[1];\n      nextPosition+= buff;\n    }\n    nextPosition *= 1/social_learning_number;\n  }\n  \n  nextPosition = currentPosition + k_multiplication*(nextPosition - currentPosition);\n  next_pos.x = nextPosition[0];\n  next_pos.z = nextPosition[1];\n  next_pos.heading = M_PI/3;\n\n  // std::cout<<\"_________POSITION of ROBOT INDEX___________:\"<<robot_index<<\"\\n\";\n  // std::cout<<\"before boundary snap = (\"<<next_pos.x<<\",\"<<next_pos.z<<\",\"<<next_pos.heading*(180/M_PI)<<\")\\n\";\n  \n  if(!check_insideBoundary(next_pos)){\n    // std::cout<<\"Boundary snap called\\n\";\n    next_pos = snapToBoundary(my_position, next_pos);\n  }\n  \n  // std::cout<<\"_________POSITION of ROBOT INDEX___________:\"<<robot_index<<\"\\n\";\n  // std::cout<<\"after boundary snap = (\"<<next_pos.x<<\",\"<<next_pos.z<<\",\"<<next_pos.heading*(180/M_PI)<<\")\\n\";  \n  \n  \n  return next_pos;\n}\n\nrobot_tracking::Position GreyWolf::snapToBoundary(robot_tracking::Position currentPosition, robot_tracking::Position nextPosition){\n  // Set boundary points\n  double x1 = currentPosition.x , z1 = currentPosition.z;\n  double x2 = nextPosition.x , z2 = nextPosition.z;\n  double x3,z3,x4,z4;\n  double ta,tb;\n  double x_new, z_new;\n    \n  // std::cout<<\"_________Before snapping Function of ROBOT INDEX___________:\"<<robot_index<<\"\\n\";\n  // std::cout<<\"X1,Z1= (\"<<x1<<\",\"<<z1<<\")\\n\";\n  // std::cout<<\"X2,Z2= (\"<<x2<<\",\"<<z2<<\")\\n\";    \n\n  if(x1>=x_upper_boundary || x1<=x_lower_boundary)\n    x1 = round(x1);\n  if(z1>=z_upper_boundary || z1<=z_lower_boundary)\n    z1 = round(z1);\n\n\n  //Setup boundaries\n  x3 = x_upper_boundary;\n  z3 = z_upper_boundary;\n  x4 = x_upper_boundary;\n  z4 = z_lower_boundary;\n  //Calculate constants\n  ta = (((z3 - z4)*(x1 - x3)) + ((x4 - x3)*(z1 - z3)))/(((x4 - x3)*(z1 - z2)) - ((x1 - x2)*(z4 - z3)));\n  tb = (((z1 - z2)*(x1 - x3)) + ((x2 - x1)*(z1 - z3)))/(((x4 - x3)*(z1 - z2)) - ((x1 - x2)*(z4 - z3)));\n\n  if(ta>=0 && ta<=1 && tb<=1 && tb>=0){\n    x_new = x1 + ta*(x2 - x1);\n    z_new = z1 + ta*(z2 - z1);\n  }\n  \n  else{\n    //Setup boundaries\n    x3 = x_upper_boundary;\n    z3 = z_upper_boundary;\n    x4 = x_lower_boundary;\n    z4 = z_upper_boundary;\n    //Calculate constants\n    ta = (((z3 - z4)*(x1 - x3)) + ((x4 - x3)*(z1 - z3)))/(((x4 - x3)*(z1 - z2)) - ((x1 - x2)*(z4 - z3)));\n    tb = (((z1 - z2)*(x1 - x3)) + ((x2 - x1)*(z1 - z3)))/(((x4 - x3)*(z1 - z2)) - ((x1 - x2)*(z4 - z3)));\n  \n    if(ta>=0 && ta<=1 && tb<=1 && tb>=0){\n      x_new = x1 + ta*(x2 - x1);\n      z_new = z1 + ta*(z2 - z1);\n    }\n    else{\n      //Setup boundaries\n      x3 = x_lower_boundary;\n      z3 = z_lower_boundary;\n      x4 = x_lower_boundary;\n      z4 = z_upper_boundary;\n      //Calculate constants\n      ta = (((z3 - z4)*(x1 - x3)) + ((x4 - x3)*(z1 - z3)))/(((x4 - x3)*(z1 - z2)) - ((x1 - x2)*(z4 - z3)));\n      tb = (((z1 - z2)*(x1 - x3)) + ((x2 - x1)*(z1 - z3)))/(((x4 - x3)*(z1 - z2)) - ((x1 - x2)*(z4 - z3)));\n    \n      if(ta>=0 && ta<=1 && tb<=1 && tb>=0){\n        x_new = x1 + ta*(x2 - x1);\n        z_new = z1 + ta*(z2 - z1);\n      }\n      else{\n        //Setup boundaries\n        x3 = x_lower_boundary;\n        z3 = z_lower_boundary;\n        x4 = x_upper_boundary;\n        z4 = z_lower_boundary;\n        //Calculate constants\n        ta = (((z3 - z4)*(x1 - x3)) + ((x4 - x3)*(z1 - z3)))/(((x4 - x3)*(z1 - z2)) - ((x1 - x2)*(z4 - z3)));\n        tb = (((z1 - z2)*(x1 - x3)) + ((x2 - x1)*(z1 - z3)))/(((x4 - x3)*(z1 - z2)) - ((x1 - x2)*(z4 - z3)));\n      \n        if(ta>=0 && ta<=1 && tb<=1 && tb>=0){\n          x_new = x1 + ta*(x2 - x1);\n          z_new = z1 + ta*(z2 - z1);\n        }\n        else{\n          x_new = nextPosition.x;\n          z_new = nextPosition.z;\n        }\n      }  \n    }\n  }\n\n  // std::cout<<\"_________Before scaling of ROBOT INDEX___________:\"<<robot_index<<\"\\n\";\n  // std::cout<<\"X_new,Z_new= (\"<<x_new<<\",\"<<z_new<<\")\\n\";\n\n  //Scale next Position so that it always remains inside the boundary\n  //Done to prevent the robot from always flocking to the edges  \n  // std::cout<<\"_________Difference in positions ROBOT INDEX___________:\"<<robot_index<<\"\\n\";\n  // std::cout<<\"X_diff,Z_diff= (\"<<(x_new - currentPosition.x)<<\",\"<<(z_new - currentPosition.z)<<\")\\n\"; \n   \n  robot_tracking::Position newPosition;\n  newPosition.x = x_new;\n  newPosition.z = z_new;\n  newPosition.heading = nextPosition.heading;\n  \n  return newPosition; \n}\n\nrobot_tracking::Position GreyWolf::generateRandomPosition(){\n  robot_tracking::Position newPos;\n  newPos.x = generateRandomNumber(x_lower_boundary,x_upper_boundary);\n  newPos.z = generateRandomNumber(z_lower_boundary,z_upper_boundary);\n  newPos.heading = 0;\n  return newPos; \n}\n\nbool GreyWolf::check_insideBoundary(robot_tracking::Position nextPosition){\n  bool x_insideBoundary = false, z_insideBoundary = false;\n  if(nextPosition.x> x_lower_boundary && nextPosition.x< x_upper_boundary)\n    x_insideBoundary = true;\n  if(nextPosition.z> z_lower_boundary && nextPosition.z< z_upper_boundary)\n    z_insideBoundary = true;\n  \n  return (x_insideBoundary && z_insideBoundary);\n}\n\nrobot_tracking::Position GreyWolf::get_previousPosition(){\n  return prev_position;\n}", "meta": {"hexsha": "1401bb3874ae2cbff2d146eb38e343f7d550491a", "size": 13407, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/greyWolf.cpp", "max_stars_repo_name": "anikethramesh/MappingUsingGWO", "max_stars_repo_head_hexsha": "d5be2697612cf1a1c899cbd9155ae587a834ad49", "max_stars_repo_licenses": ["MIT"], "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/greyWolf.cpp", "max_issues_repo_name": "anikethramesh/MappingUsingGWO", "max_issues_repo_head_hexsha": "d5be2697612cf1a1c899cbd9155ae587a834ad49", "max_issues_repo_licenses": ["MIT"], "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/greyWolf.cpp", "max_forks_repo_name": "anikethramesh/MappingUsingGWO", "max_forks_repo_head_hexsha": "d5be2697612cf1a1c899cbd9155ae587a834ad49", "max_forks_repo_licenses": ["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.3746701847, "max_line_length": 152, "alphanum_fraction": 0.6586857612, "num_tokens": 3819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.27960226837805585}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n//\n// (C) Copyright Alejandro Cabrera 2011.\n// Distributed under the Boost\n// 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// See http://www.boost.org/libs/bloom_filter for documentation.\n//\n//////////////////////////////////////////////////////////////////////////////\n\n#ifndef BOOST_BLOOM_FILTER_DYNAMIC_COUNTING_BLOOM_FILTER_HPP\n#define BOOST_BLOOM_FILTER_DYNAMIC_COUNTING_BLOOM_FILTER_HPP 1\n\n#include <cmath>\n#include <vector>\n\n#include <boost/config.hpp>\n\n#include <boost/static_assert.hpp>\n#include <boost/type_traits/is_integral.hpp>\n#include <boost/type_traits/is_unsigned.hpp>\n\n#include <boost/bloom_filter/detail/twohash_counting_apply_hash.hpp>\n#include <boost/bloom_filter/detail/extenders.hpp>\n#include <boost/bloom_filter/hash/default.hpp>\n#include <boost/bloom_filter/hash/murmurhash3.hpp>\n\nnamespace boost {\n  namespace bloom_filters {\n    template <typename T,\n\t      size_t BitsPerBin = 4,\n\t      size_t HashValues = 2,\n\t      size_t ExpectedInsertionCount = 0,\n\t      class HashFunction1 = boost_hash<T>,\n\t      class HashFunction2 = murmurhash3<T>,\n\t      class ExtensionFunction = detail::square,\n\t      typename Block = size_t,\n\t      typename Allocator = std::allocator<Block> >\n    class twohash_dynamic_counting_bloom_filter {\n\n      // Block needs to be an integral type\n      BOOST_STATIC_ASSERT( boost::is_integral<Block>::value == true);\n\n      // Block needs to be an unsigned type\n      BOOST_STATIC_ASSERT( boost::is_unsigned<Block>::value == true);\n\n      // BitsPerBin needs to be greater than 0\n      BOOST_STATIC_ASSERT( BitsPerBin > 0);\n\n      // it doesn't make sense to ever support using a BitsPerBin value larger\n      // than the number of bits per Block. In that case, the user shouldn't\n      // be using a Bloom filter to represent their data.\n      BOOST_STATIC_ASSERT( (BitsPerBin < (sizeof(Block) * 8) ) );\n\n      // because of the nature of this implementation, the Bloom filter\n      // can have internal fragmentation if the calculation for \n      // bins_per_slot has a remainder. The severity of the  internal\n      // fragmentation is equal to the remainder * the number of slots.\n      // This check prevents internal fragmentation.\n      // This also necessarily limits to bin sizes to one of:\n      // [1,2,4,8,16,32(64-bit system only)] bits\n      BOOST_STATIC_ASSERT( ((sizeof(Block) * 8) % BitsPerBin) == 0);\n\n    public:\n      typedef T value_type;\n      typedef T key_type;\n      typedef HashFunction1 hash_function1_type;\n      typedef HashFunction2 hash_function2_type;\n      typedef ExtensionFunction extension_function_type;\n      typedef Block block_type;\n      typedef Allocator allocator_type;\n      typedef twohash_dynamic_counting_bloom_filter<T, BitsPerBin,\n\t\t\t\t\t\t    HashValues,\n\t\t\t\t\t\t    ExpectedInsertionCount,\n\t\t\t\t\t\t    HashFunction1,\n\t\t\t\t\t\t    HashFunction2,\n\t\t\t\t\t\t    ExtensionFunction,\n\t\t\t\t\t\t    Block, Allocator> this_type;\n\n      typedef std::vector<Block, Allocator> bucket_type;\n      typedef typename bucket_type::iterator bucket_iterator;\n      typedef typename bucket_type::const_iterator bucket_const_iterator;\n\n      static const size_t default_num_bins = 32;\n\n    private:\n      static const size_t slot_bits = sizeof(block_type) * 8;\n\n      size_t bucket_size(const size_t requested_bins) const {\n\tconst size_t bin_bits = requested_bins * BitsPerBin;\n\treturn bin_bits / slot_bits + 1;\n      }\n\n      typedef detail::twohash_counting_apply_hash<HashValues,\n\t\t\t\t\t\t  this_type> apply_hash_type;\n\n    public:\n      //! constructors\n      twohash_dynamic_counting_bloom_filter() \n\t: bits(bucket_size(default_num_bins)),\n\t  _num_bins(default_num_bins)\n      {\n      }\n\n      explicit twohash_dynamic_counting_bloom_filter(const size_t requested_bins)\n\t: bits(bucket_size(requested_bins)),\n\t  _num_bins(requested_bins)\n      {\n      }\n\n      template <typename InputIterator>\n      twohash_dynamic_counting_bloom_filter(const InputIterator start, \n\t\t\t\t\t    const InputIterator end) \n\t: bits(bucket_size(std::distance(start, end) * 4)),\n\t  _num_bins(std::distance(start, end) * 4)\n      {\n\tfor (InputIterator i = start; i != end; ++i)\n\t  this->insert(*i);\n      }\n\n      //! meta functions\n      size_t num_bins() const\n      {\n\treturn this->_num_bins;\n      }\n\n      static BOOST_CONSTEXPR size_t expected_insertion_count()\n      {\n\treturn ExpectedInsertionCount;\n      }\n\n      static BOOST_CONSTEXPR size_t bits_per_bin()\n      {\n\treturn BitsPerBin;\n      }\n\n      static BOOST_CONSTEXPR size_t bins_per_slot()\n      {\n\treturn sizeof(block_type) * 8 / BitsPerBin;\n      }\n\n      static BOOST_CONSTEXPR size_t mask()\n      {\n\treturn static_cast<Block>(0 - 1) >> (sizeof(Block) * 8 - BitsPerBin);\n      }\n\n      size_t bit_capacity() const\n      {\n        return this->num_bins() * BitsPerBin;\n      }\n\n      static BOOST_CONSTEXPR size_t num_hash_functions() \n      {\n        return HashValues;\n      }\n\n      double false_positive_rate() const \n      {\n        const double n = static_cast<double>(this->count());\n        static const double k = static_cast<double>(num_hash_functions());\n        static const double m = static_cast<double>(this->num_bins());\n        static const double e =\n\t  2.718281828459045235360287471352662497757247093699959574966;\n        return std::pow(1 - std::pow(e, -k * n / m), k);\n      }\n\n      //? returns the number of bins that have at least 1 bit set\n      size_t count() const \n      {\n\tsize_t ret = 0;\n\n\tfor (bucket_const_iterator i = this->bits.begin(), \n\t       end = this->bits.end(); \n\t     i != end; ++i) {\n\t  for (size_t bin = 0; bin < this->bins_per_slot(); ++bin) {\n\t    const size_t offset_bits = bin * BitsPerBin;\n\t    const size_t target_bits = (*i >> offset_bits) & this->mask();\n\n\t    if (target_bits > 0)\n\t      ++ret;\n\t  }\n\t}\n\n        return ret;\n      }\n\n      bool empty() const\n      {\n\treturn this->count() == 0;\n      }\n\n      const bucket_type&\n      data() const \n      {\n\treturn this->bits;\n      }\n\n      //! core ops\n      void insert(const T& t)\n      {\n\tapply_hash_type::insert(t, \n\t\t\t\tthis->bits,\n\t\t\t\tthis->num_bins());\n      }\n\n      template <typename InputIterator>\n      void insert(const InputIterator start, const InputIterator end)\n      {\n\tfor (InputIterator i = start; i != end; ++i) {\n\t  this->insert(*i);\n\t}\n      }\n\n      void remove(const T& t)\n      {\n\tapply_hash_type::remove(t, \n\t\t\t\tthis->bits,\n\t\t\t\tthis->num_bins());\n      }\n\n      template <typename InputIterator>\n      void remove(const InputIterator start, const InputIterator end)\n      {\n\tfor (InputIterator i = start; i != end; ++i) {\n\t  this->remove(*i);\n\t}\n      }\n\n      bool probably_contains(const T& t) const\n      {\n\treturn apply_hash_type::contains(t,\n\t\t\t\t\t this->bits,\n\t\t\t\t\t this->num_bins());\n      }\n\n      //! auxiliary ops\n      void clear()\n      {\n\tfor (bucket_iterator i = bits.begin(), end = bits.end();\n\t     i != end; ++i)\n\t  *i = 0;\n      }\n\n      void swap(twohash_dynamic_counting_bloom_filter& other)\n      {\n\ttwohash_dynamic_counting_bloom_filter tmp = other;\n\tother = *this;\n\t*this = tmp;\n      }\n\n      // equality comparison operators\n      template <typename _T, size_t _BitsPerBin,\n\t\tsize_t _HashValues, size_t _ExpectedInsertionCount,\n\t\tclass _HashFn1, class _HashFn2, class _Extender,\n\t\ttypename _Block, class _Allocator>\n      friend bool\n      operator==(const twohash_dynamic_counting_bloom_filter<_T, _BitsPerBin,\n\t\t\t\t\t\t\t     _HashValues,\n\t\t\t\t\t\t\t     _ExpectedInsertionCount,\n\t\t\t\t\t\t\t     _HashFn1,\n\t\t\t\t\t\t\t     _HashFn2,\n\t\t\t\t\t\t\t     _Extender,\n\t\t\t\t\t\t\t     _Block,\n\t\t\t\t\t\t\t     _Allocator>& lhs,\n\t\t const twohash_dynamic_counting_bloom_filter<_T, _BitsPerBin,\n\t\t\t\t\t\t\t     _HashValues,\n\t\t\t\t\t\t\t     _ExpectedInsertionCount,\n\t\t\t\t\t\t\t     _HashFn1,\n\t\t\t\t\t\t\t     _HashFn2,\n\t\t\t\t\t\t\t     _Extender,\n\t\t\t\t\t\t\t     _Block,\n\t\t\t\t\t\t\t     _Allocator>& rhs);\n\n      template <typename _T, size_t _BitsPerBin,\n\t\tsize_t _HashValues, size_t _ExpectedInsertionCount,\n\t\tclass _HashFn1, class _HashFn2, class _Extender,\n\t\ttypename _Block, class _Allocator>\n      friend bool\n      operator!=(const twohash_dynamic_counting_bloom_filter<_T, _BitsPerBin,\n\t\t\t\t\t\t\t     _HashValues,\n\t\t\t\t\t\t\t     _ExpectedInsertionCount,\n\t\t\t\t\t\t\t     _HashFn1,\n\t\t\t\t\t\t\t     _HashFn2,\n\t\t\t\t\t\t\t     _Extender,\n\t\t\t\t\t\t\t     _Block,\n\t\t\t\t\t\t\t     _Allocator>& lhs,\n\t\t const twohash_dynamic_counting_bloom_filter<_T, _BitsPerBin,\n\t\t\t\t\t\t\t     _HashValues,\n\t\t\t\t\t\t\t     _ExpectedInsertionCount,\n\t\t\t\t\t\t\t     _HashFn1,\n\t\t\t\t\t\t\t     _HashFn2,\n\t\t\t\t\t\t\t     _Extender,\n\t\t\t\t\t\t\t     _Block,\n\t\t\t\t\t\t\t     _Allocator>& rhs);\n\n    private:\n      bucket_type bits;\n      size_t _num_bins;\n    };\n\n    template<class T, size_t BitsPerBin, size_t HashValues,\n\t     size_t ExpectedInsertionCount,\n\t     class HashFunction1, class HashFunction2,\n\t     class ExtensionFunction, typename Block,\n\t     class Allocator>\n    void\n    swap(twohash_dynamic_counting_bloom_filter<T, BitsPerBin,\n\t\t\t\t\t       HashValues,\n\t\t\t\t\t       ExpectedInsertionCount,\n\t\t\t\t\t       HashFunction1,\n\t\t\t\t\t       HashFunction2,\n\t\t\t\t\t       ExtensionFunction,\n\t\t\t\t\t       Block,\n\t\t\t\t\t       Allocator>& lhs,\n\t twohash_dynamic_counting_bloom_filter<T, BitsPerBin,\n\t\t\t\t\t       HashValues,\n\t\t\t\t\t       ExpectedInsertionCount,\n\t\t\t\t\t       HashFunction1,\n\t\t\t\t\t       HashFunction2,\n\t\t\t\t\t       ExtensionFunction,\n\t\t\t\t\t       Block,\n\t\t\t\t\t       Allocator>& rhs)\n\n    {\n      lhs.swap(rhs);\n    }\n\n    template<class T, size_t BitsPerBin, size_t HashValues,\n\t     size_t ExpectedInsertionCount,\n\t     class HashFunction1, class HashFunction2,\n\t     class ExtensionFunction, typename Block,\n\t     class Allocator>\n    bool\n    operator==(const twohash_dynamic_counting_bloom_filter<T, BitsPerBin,\n\t\t\t\t\t\t\t   HashValues,\n\t\t\t\t\t\t\t   ExpectedInsertionCount,\n\t\t\t\t\t\t\t   HashFunction1,\n\t\t\t\t\t\t\t   HashFunction2,\n\t\t\t\t\t\t\t   ExtensionFunction,\n\t\t\t\t\t\t\t   Block,\n\t\t\t\t\t\t\t   Allocator>& lhs,\n\t       const twohash_dynamic_counting_bloom_filter<T, BitsPerBin,\n\t\t\t\t\t\t\t   HashValues,\n\t\t\t\t\t\t\t   ExpectedInsertionCount,\n\t\t\t\t\t\t\t   HashFunction1,\n\t\t\t\t\t\t\t   HashFunction2,\n\t\t\t\t\t\t\t   ExtensionFunction,\n\t\t\t\t\t\t\t   Block,\n\t\t\t\t\t\t\t   Allocator>& rhs)\n    {\n      if (lhs.bit_capacity() != rhs.bit_capacity())\n\tthrow detail::incompatible_size_exception();\n\n      return (lhs.bits == rhs.bits);\n    }\n\n    template<class T, size_t BitsPerBin, size_t HashValues,\n\t     size_t ExpectedInsertionCount,\n\t     class HashFunction1, class HashFunction2,\n\t     class ExtensionFunction, typename Block,\n\t     class Allocator>\n    bool\n    operator!=(const twohash_dynamic_counting_bloom_filter<T, BitsPerBin,\n\t\t\t\t\t\t\t   HashValues,\n\t\t\t\t\t\t\t   ExpectedInsertionCount,\n\t\t\t\t\t\t\t   HashFunction1,\n\t\t\t\t\t\t\t   HashFunction2,\n\t\t\t\t\t\t\t   ExtensionFunction,\n\t\t\t\t\t\t\t   Block,\n\t\t\t\t\t\t\t   Allocator>& lhs,\n\t       const twohash_dynamic_counting_bloom_filter<T, BitsPerBin,\n\t\t\t\t\t\t\t   HashValues,\n\t\t\t\t\t\t\t   ExpectedInsertionCount,\n\t\t\t\t\t\t\t   HashFunction1,\n\t\t\t\t\t\t\t   HashFunction2,\n\t\t\t\t\t\t\t   ExtensionFunction,\n\t\t\t\t\t\t\t   Block,\n\t\t\t\t\t\t\t   Allocator>& rhs)\n    {\n      if (lhs.bit_capacity() != rhs.bit_capacity())\n\tthrow detail::incompatible_size_exception();\n\n      return !(lhs == rhs);\n    }\n\n  } // namespace bloom_filter\n} // namespace boost\n#endif\n", "meta": {"hexsha": "73c900672bfb88efb11ac279ff62f50e1570cb6c", "size": 11296, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/bloom_filter/twohash_dynamic_counting_bloom_filter.hpp", "max_stars_repo_name": "tetzank/boost-bloom-filters", "max_stars_repo_head_hexsha": "7c6717f403c041a092187568908f3661782ddb24", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T16:05:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T03:01:42.000Z", "max_issues_repo_path": "boost/bloom_filter/twohash_dynamic_counting_bloom_filter.hpp", "max_issues_repo_name": "tetzank/boost-bloom-filters", "max_issues_repo_head_hexsha": "7c6717f403c041a092187568908f3661782ddb24", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/bloom_filter/twohash_dynamic_counting_bloom_filter.hpp", "max_forks_repo_name": "tetzank/boost-bloom-filters", "max_forks_repo_head_hexsha": "7c6717f403c041a092187568908f3661782ddb24", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2016-04-15T18:17:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-16T06:29:58.000Z", "avg_line_length": 28.8900255754, "max_line_length": 81, "alphanum_fraction": 0.632082153, "num_tokens": 2634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2796022683780558}}
{"text": "// Copyright (c) 2018, Tom Westerhout\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// vim: foldenable foldmethod=marker\n\n#pragma once\n\n#include \"detail/lattice.hpp\"\n#include \"detail/memory.hpp\"\n#include \"detail/utility.hpp\"\n#include <boost/container/small_vector.hpp>\n#include <boost/pool/pool.hpp>\n#include <gsl/gsl-lite.hpp>\n#include <sleef.h>\n#include <memory>\n#include <optional>\n#include <utility>\n#include <vector>\n\n#if !defined(__AVX__)\n#    error \"WTF?\"\n#endif\n\nTCM_NAMESPACE_BEGIN\n\nusing size_t = std::size_t;\n\n/// A tag indicating that a function should not optimise the energy.\nstruct no_optimize_t {};\ninline constexpr no_optimize_t no_optimize{};\n\n#if 0\n/// Let the direction of spin on site `site` be `x`. Denote the spins on the\n/// nearest neighbours of `x` by `{αᵢ}`. Furthermore, let `cᵢ = +1` if\n/// interaction between sites is antiferromagnetic and `cᵢ = -1` if interaction\n/// is ferromagnetic.\n///\n/// Then our goal here is to find `argmin{E(x) | x∈[0, 2π)}` where\n///\n///     E(x) = ∑cᵢcos(x - αᵢ) = ∑cᵢ(sin(x)sin(αᵢ) + cos(x)cos(αᵢ))\n///          = [∑cᵢsin(αᵢ)] * sin(x) + [∑cᵢcos(αᵢ)] * cos(x) .\n///            ^^^^^^^^^^^^            ^^^^^^^^^^^^\n///                := A                    := B\n///\n/// Since `E` is continuously differentiable, let's just compute its derivative\n///\n///     dE/dx = Acos(x) - Bsin(x) .\n///\n/// Now,\n///\n///     dE/dx = 0  <=>  Acos(x) = Bsin(x)  <=>  tan(x) = A/B, if B != 0\n///                                             Acos(x) = 0,  if B == 0\n///\n/// * B != 0: We have a choice between\n///\n///        x₁ = tan⁻¹(A/B) + 2π | mod 2π,   and\n///        x₂ = x₁ + π          | mod 2π\n///\n///   We simply compute `E` for both values and choose the one that results in\n///   lower energy.\n///\n/// * `B == 0 && A != 0`: We have a choice between\n///\n///        x₁ = π/2,    and\n///        x₂ = 3π/2\n///\n///   Again, we compute `E` for both `x`'s and determine the best.\n///\n/// * `B == 0 && A == 0`: `E` is constant, so we can choose arbitrary `x`. For\n/// simplicity, we pick `x = 0`.\n///\ntemplate <class System>\nauto minimise_local_energy(size_t const site, System const& system) -> angle_t\n{\n    // Determines the coefficients cᵢ\n    struct get_c_t {\n        using Lattice = typename System::lattice_type;\n        Lattice const& lattice;\n\n        auto operator()(size_t const i, size_t const j) const TCM_NOEXCEPT\n            -> float\n        {\n            switch (::TCM_NAMESPACE::interaction(lattice, i, j)) {\n            case interaction_t::Ferromagnetic: return -1.0f;\n            case interaction_t::Antiferromagnetic: return 1.0f;\n            } // end switch\n        }\n    } get_c{system.lattice()};\n\n    auto A = 0.0f;\n    auto B = 0.0f;\n    for (int64_t const _i : system.lattice().neighbours[site]) {\n        if (_i >= 0 && !system.is_empty(static_cast<size_t>(_i))) {\n            auto const i = static_cast<size_t>(_i);\n            auto const c = get_c(site, i);\n            // Projection of spin on the y-axis is the sine\n            A += c * system.S_y(i);\n            // Projection of spin on the x-axis is the cosine\n            B += c * system.S_x(i);\n        }\n    }\n\n    auto const E = [A, B](angle_t const x) {\n        auto const v     = Sleef_sincosf_u10(static_cast<float>(x));\n        auto const sin_x = v.x;\n        auto const cos_x = v.y;\n        return A * sin_x + B * cos_x;\n    };\n\n    if (B != 0.0f) {\n        auto x1 = [A, B]() {\n            constexpr auto epsilon = -4.7683716E-7f;\n            constexpr auto two_pi  = detail::two_pi<float>;\n            auto           result  = Sleef_atanf_u10(A / B);\n            if (result < epsilon) { return angle_t{result + two_pi}; }\n            else if (result < 0.0f) {\n                return angle_t{0.0f};\n            }\n            else {\n                return angle_t{result};\n            }\n        }();\n        auto const x2 = x1 + angle_t{detail::pi<float>};\n        return (E(x1) <= E(x2)) ? x1 : x2;\n    }\n    else if (A != 0.0f) {\n        auto const x1 = angle_t{1.5707964f}; // pi / 2\n        auto const x2 = angle_t{4.712389f};  // 3 * pi / 2\n        return (E(x1) <= E(x2)) ? x1 : x2;\n    }\n    else {\n        return angle_t{0.0f};\n    }\n}\n#endif\n\nclass system_base_t;\n\nstruct magnetic_cluster_base_t {\n  public:\n    using unique_ptr = pool_unique_ptr<magnetic_cluster_base_t>;\n\n    /// Information about the connection between this cluster and a child\n    /// cluster.\n    struct child_conn_t {\n        /// The edge which connects this cluster to the child. `edge.first`\n        /// belongs to this cluster and `edge.second` belongs to the child.\n        std::pair<uint32_t, uint32_t> edge;\n        /// The child cluster itself.\n        ///\n        /// \\note Yes, parents own their children. No shared ownership.\n        unique_ptr data;\n    };\n\n    /// Information about the connection between this cluster and its parent.\n    struct parent_conn_t {\n        /// Index in the #_children array of the parent.\n        uint32_t index;\n        /// The edge which connects the parent to this cluster. `edge.first`\n        /// belongs to the parent and `edge.second` belongs to this cluster.\n        std::pair<uint32_t, uint32_t> edge;\n        /// Pointer to the parent node.\n        ///\n        /// \\note The parent owns this cluster so it's safe to store a\n        /// non-owning pointer here.\n        gsl::not_null<magnetic_cluster_base_t*> data;\n    };\n\n  private:\n    /// Connection to the parent node.\n    std::optional<parent_conn_t> _parent;\n    /// Connection to children nodes.\n    boost::container::small_vector<child_conn_t, 1> _children;\n    /// A list of indices of all the sites that belong to this cluster.\n    std::vector<uint32_t> _sites;\n    /// A reference to the global system state\n    system_base_t& _system_state;\n\n  public:\n    /// Constructs a new magnetic cluster consisting of just one site\n    ///\n    /// \\param index Index of the site.\n    /// \\param angle Direction of the spin at site \\p index.\n    /// \\param system A reference to the system state.\n    TCM_FORCEINLINE magnetic_cluster_base_t(uint32_t index, angle_t angle,\n                                            system_base_t& system);\n\n    /// **Deleted** copy constructor.\n    magnetic_cluster_base_t(magnetic_cluster_base_t const&) = delete;\n    /// **Deleted** move constructor.\n    magnetic_cluster_base_t(magnetic_cluster_base_t&&) = delete;\n    /// **Deleted** copy assignment operator.\n    auto operator                   =(magnetic_cluster_base_t const&)\n        -> magnetic_cluster_base_t& = delete;\n    /// **Deleted** move assignment operator.\n    auto operator                   =(magnetic_cluster_base_t &&)\n        -> magnetic_cluster_base_t& = delete;\n\n    /// Attaches a child node.\n    ///\n    /// \\param connection Specifies the child node and the edge connecting it to\n    /// `*this`.\n    ///\n    /// \\throws std::bad_alloc if memory allocation fails.\n    TCM_FORCEINLINE auto attach(child_conn_t connection) -> void;\n\n    /// Detaches the `i`'th child.\n    ///\n    /// \\param i Index of the child to detach. \\p i must be less than\n    /// number_children().\n    /// \\return The child connection.\n    TCM_FORCEINLINE auto detach(size_t i) -> child_conn_t;\n\n    /// Adds site `i` to the cluster.\n    ///\n    /// \\param i     Index of the site.\n    /// \\param angle Direction of the spin.\n    TCM_FORCEINLINE auto insert(uint32_t i, angle_t angle) -> void;\n\n    /// Merges \\p cluster into `*this`.\n    ///\n    /// The merging is done in two steps:\n    ///   -# stealing all the *children* from \\p cluster, and\n    ///   -# stealing all the *sites* from \\p cluster.\n    TCM_FORCEINLINE auto merge(unique_ptr cluster) -> void;\n\n    /// Rotates the subtree (i.e. `*this` and all the children recursively) by\n    /// \\p angle.\n    ///\n    /// Rotation amounts to a simle depth-first search over the subtree.\n    TCM_FORCEINLINE auto rotate(angle_t angle) -> void;\n\n    /// Returns whether the cluster is the root of the geometric cluster.\n    ///\n    /// \\noexcept\n    constexpr auto is_root() const noexcept -> bool;\n\n    /// Returns the index of `*this` in the array of children of its parent.\n    ///\n    /// \\pre `*this` is not the root node, i.e. is_root() returns `false`.\n    /// \\noexcept\n    constexpr auto index_in_parent() const TCM_NOEXCEPT -> uint32_t;\n\n    /// Returns a non-owning pointer to the parent node.\n    ///\n    /// \\pre `*this` has a parent, i.e. is_root() returns `false`.\n    /// \\noexcept\n    constexpr auto parent() const TCM_NOEXCEPT\n        -> gsl::not_null<magnetic_cluster_base_t*>;\n\n    /// Returns a non-owning view of the sites in the cluster.\n    ///\n    /// \\noexcept\n    inline auto sites() const noexcept -> gsl::span<uint32_t const>;\n\n    constexpr auto system() const noexcept -> system_base_t const&;\n    constexpr auto system() noexcept -> system_base_t&;\n\n    /// Returns the number of sites in this cluster.\n    ///\n    /// \\noexcept\n    inline auto number_sites() const noexcept -> size_t;\n\n    /// Returns the number of child nodes.\n    ///\n    /// \\noexcept\n    inline auto number_children() const noexcept -> size_t;\n\n    friend TCM_FORCEINLINE auto\n    move_root_down(magnetic_cluster_base_t::unique_ptr root, size_t child_index)\n        -> magnetic_cluster_base_t::unique_ptr;\n\n    /// Runs Depth-First Search on the subtree applying \\p fn to each node.\n    ///\n    /// \\param fn Function to apply to each node. \\p fn should be callable with\n    /// a reference to magnetic_cluster_t. Return value is ignored.\n    template <class Function> TCM_FORCEINLINE auto dfs(Function&& fn) -> void;\n\n    template <class Lattice>\n    inline auto align_with_parent(Lattice const& lattice) -> void;\n};\n\n#if 0\n\n/// A magnetic cluster, i.e. an irreducible component in our graph.\ntemplate <class System> class magnetic_cluster_t { // {{{\n  public:\n    using system_type = System;\n#    if !defined(DOXYGEN_IS_IN_THE_HOUSE)\n    using unique_ptr =\n        typename System::template unique_ptr<magnetic_cluster_t<System>>;\n#    else\n    using unique_ptr = std::unique_ptr<magnetic_cluster_t<System>>;\n#    endif\n\n  private:\n    /// Information about the connection between this cluster and a child\n    /// cluster.\n    struct child_conn_info_t {\n        /// The edge which connects this cluster to the child. `edge.first`\n        /// belongs to this cluster and `edge.second` belongs to the child.\n        std::pair<size_t, size_t> edge;\n        /// The child cluster itself.\n        ///\n        /// \\note Yes, parents own their children. No shared ownership.\n        unique_ptr data;\n    };\n\n    /// Information about the connection between this cluster and its parent.\n    struct parent_conn_info_t {\n        /// Index in the #_children array of the parent.\n        size_t index;\n        /// The edge which connects the parent to this cluster. `edge.first`\n        /// belongs to the parent and `edge.second` belongs to this cluster.\n        std::pair<size_t, size_t> edge;\n        /// Pointer to the parent node.\n        ///\n        /// \\note The parent owns this cluster so it's safe to store a\n        /// non-owning pointer here.\n        gsl::not_null<magnetic_cluster_t*> data;\n    };\n\n    /// Connection to the parent node.\n    std::optional<parent_conn_info_t> _parent;\n    /// Connection to children nodes.\n    boost::container::small_vector<child_conn_info_t, 1> _children;\n    /// A list of indices of all the sites that belong to this cluster.\n    std::vector<size_t> _sites;\n    /// A reference to the global system state\n    system_type& _system_state;\n\n    // static_assert(sizeof(boost::container::small_vector<child_conn_info_t, 1>)\n    //               == 56);\n\n  public:\n    /// Constructs a new magnetic cluster consisting of just one site\n    ///\n    /// \\param index Index of the site.\n    /// \\param angle Direction of the spin at site \\p index.\n    /// \\param system A reference to the system state.\n    inline magnetic_cluster_t(size_t index, angle_t angle, system_type& system);\n\n    /// **Deleted** copy constructor.\n    magnetic_cluster_t(magnetic_cluster_t const&) = delete;\n    /// **Deleted** move constructor.\n    magnetic_cluster_t(magnetic_cluster_t&&) = delete;\n    /// **Deleted** copy assignment operator.\n    magnetic_cluster_t& operator=(magnetic_cluster_t const&) = delete;\n    /// **Deleted** move assignment operator.\n    magnetic_cluster_t& operator=(magnetic_cluster_t&&) = delete;\n\n    /// Attaches a child node.\n    ///\n    /// \\param connection Specifies the child node and the edge connecting it to\n    /// `*this`.\n    ///\n    /// \\throws std::bad_alloc if memory allocation fails.\n    inline auto attach(child_conn_info_t connection) -> void;\n    // inline auto attach(no_optimize_t, child_conn_info_t /*connection*/) -> void;\n\n    /// Detaches the `i`'th child.\n    ///\n    /// \\param i Index of the child to detach. \\p i must be less than\n    /// number_children().\n    /// \\return The child connection.\n    inline auto detach(size_t i) -> child_conn_info_t;\n\n    /// Adds site `i` to the cluster.\n    ///\n    /// \\param i Index of the site.\n    inline auto insert(size_t i) -> void;\n    // inline auto insert(no_optimize_t, size_t /*site index*/) -> void;\n\n    /// Merges \\p cluster into `*this`.\n    ///\n    /// The merging is done in two steps:\n    ///   -# stealing all the *children* from \\p cluster, and\n    ///   -# stealing all the *sites* from \\p cluster.\n    inline auto merge(unique_ptr cluster) -> void;\n    // auto        merge(no_optimize_t, unique_ptr cluster) -> void;\n\n    /// Rotates the subtree (i.e. `*this` and all the children recursively) by\n    /// \\p angle.\n    ///\n    /// Rotation amounts to a simle depth-first search over the subtree.\n    inline auto rotate(angle_t angle) -> void;\n\n    /// Optimizes the energy of the magnetic cluster assuming that the cluster\n    /// was optimized and then a new site `site` was added.\n    // auto optimize_one(size_t site) -> void;\n\n    /// Optimizes the energy of the magnetic cluster.\n    // TCM_NOINLINE auto optimize_full() -> void;\n\n    /// Returns whether the cluster is the root of the geometric cluster.\n    ///\n    /// \\noexcept\n    constexpr auto is_root() const noexcept { return !_parent.has_value(); }\n\n    /// Returns the index of `*this` in the array of children of its parent.\n    ///\n    /// \\pre `*this` is not the root node, i.e. is_root() returns `false`.\n    /// \\noexcept\n    constexpr auto index_in_parent() const TCM_NOEXCEPT\n    {\n        TCM_ASSERT(!is_root(), \"Root nodes are orphans\");\n        TCM_ASSERT(_parent->index < _parent->data->_children.size(),\n                   \"Index out of bounds\");\n        TCM_ASSERT(_parent->data->_children[_parent->index].data.get() == this,\n                   \"Bug! Invalid index in parent\");\n        return _parent->index;\n    }\n\n    /// Returns a non-owning pointer to the parent node.\n    ///\n    /// \\pre `*this` has a parent, i.e. is_root() returns `false`.\n    /// \\noexcept\n    constexpr auto parent() const TCM_NOEXCEPT\n    {\n        TCM_ASSERT(!is_root(), \"Root nodes are orphans\");\n        return _parent->data;\n    }\n\n    /// Returns a non-owning view of the sites in the cluster.\n    ///\n    /// \\noexcept\n    constexpr auto sites() const noexcept -> gsl::span<size_t const>\n    {\n        return {_sites};\n    }\n\n    constexpr auto system() const noexcept -> system_type const&\n    {\n        return _system_state;\n    }\n\n    constexpr auto system() noexcept -> system_type& { return _system_state; }\n\n    /// Returns the number of sites in this cluster.\n    ///\n    /// \\noexcept\n    auto number_sites() const noexcept -> size_t { return _sites.size(); }\n\n    /// Returns the number of sites in this cluster.\n    ///\n    /// \\noexcept\n    auto size() const noexcept -> size_t { return number_sites(); }\n\n    /// Returns the number of child nodes.\n    ///\n    /// \\noexcept\n    auto number_children() const noexcept -> size_t { return _children.size(); }\n\n    template <class S>\n    friend inline auto\n        move_root_down(typename magnetic_cluster_t<S>::unique_ptr /*root*/,\n                       size_t /*child index*/) ->\n        typename magnetic_cluster_t<S>::unique_ptr;\n\n    /// Runs Depth-First Search on the subtree applying \\p fn to each node.\n    ///\n    /// \\param fn Function to apply to each node. \\p fn should be callable with\n    /// a reference to magnetic_cluster_t. Return value is ignored.\n    template <class Function> TCM_FORCEINLINE auto dfs(Function&& fn)\n    {\n        using container_type =\n            boost::container::small_vector<magnetic_cluster_t*, 10>;\n        using stack_type = std::stack<magnetic_cluster_t*, container_type>;\n        static_assert(sizeof(stack_type) == sizeof(container_type),\n                      \"std::stack is wasting memory\");\n\n        stack_type todo;\n        todo.push(this);\n        while (!todo.empty()) {\n            auto& x = *todo.top();\n            todo.pop();\n            for (auto& child : x._children) {\n                todo.push(child.data.get());\n            }\n            fn(x);\n        }\n    }\n\n  private:\n    /// Aligns `*this` with its parent.\n    ///\n    /// Let `(i, j)` be the edge connecting `*this` to its parent. Site `i`\n    /// belongs to the parent and site `j` belongs to `*this`. If the\n    /// interaction between sites `i` and `j` is of ferromagnetic character, we\n    /// rotate `*this` (and its children) such that sites `i` and `j` become\n    /// aligned.  Otherwise (i.e. if the interaction is of antiferromagnetic\n    /// character) we rotate `*this` such that the angle between `i` and `j`\n    /// becomes *π*.\n    ///\n    /// \\throws std::bad_alloc If dfs() fails to allocate memory.\n    auto align_with_parent() -> void\n    {\n        TCM_ASSERT(_parent.has_value(), \"Can't align an orphan\");\n        auto const delta_angle = [this]() {\n            auto const [i, j] = _parent->edge;\n            switch (\n                ::TCM_NAMESPACE::interaction(_system_state.lattice(), i, j)) {\n            case interaction_t::Ferromagnetic:\n                return _system_state.get_angle(i) - _system_state.get_angle(j);\n            case interaction_t::Antiferromagnetic:\n                return _system_state.get_angle(i) - _system_state.get_angle(j)\n                       + angle_t{detail::pi<float>};\n            } // end switch\n        }();\n        rotate(delta_angle);\n    }\n}; // }}}\n\n// {{{ IMPLEMENTATION: magnetic_cluster_t\ntemplate <class System>\nTCM_FORCEINLINE magnetic_cluster_t<System>::magnetic_cluster_t(\n    size_t const site, angle_t const phase, System& system_state)\n    : _parent{std::nullopt}\n    , _children{}\n    // TODO(twesterhout): Should we reserve some memory in advance?\n    , _sites({site})\n    , _system_state{system_state}\n{\n    _system_state.set_angle(site, phase);\n    _system_state.set_magnetic_cluster(site, *this);\n}\n\ntemplate <class System>\nTCM_FORCEINLINE auto magnetic_cluster_t<System>::insert(size_t const site)\n    -> void\n{\n    _sites.push_back(site);\n    _system_state.set_magnetic_cluster(site, *this);\n    _system_state.set_angle(site, minimise_local_energy(site, _system_state));\n}\n\n#    if 0\ntemplate <class System>\nTCM_FORCEINLINE auto magnetic_cluster_t<System>::insert(size_t const site)\n    -> void\n{\n    TCM_ASSERT(_is_optimised, \"It is assumed that the cluster is optimized\");\n    insert(no_optimize, site);\n    optimize_one(site);\n    _is_optimised = true;\n}\n#    endif\n\n#    if 0\ntemplate <class System>\nTCM_FORCEINLINE auto magnetic_cluster_t<System>::attach(child_conn_info_t child)\n    -> void\n{\n    // TCM_ASSERT(_is_optimised, \"It is assumed that the cluster is optimized\");\n    attach(no_optimize, std::move(child));\n    // _children.back().data->align_with_parent();\n    // _is_optimised = true;\n}\n#    endif\n\ntemplate <class System>\nTCM_FORCEINLINE auto magnetic_cluster_t<System>::attach(child_conn_info_t child)\n    -> void\n{\n    using std::begin, std::end;\n    TCM_ASSERT(child.data != nullptr, \"Can't attach a non-existent cluster\");\n    TCM_ASSERT(!child.data->_parent.has_value(), \"Cluster must be an orphan\");\n    TCM_ASSERT(std::addressof(child.data->_system_state)\n                   == std::addressof(_system_state),\n               \"Cluster must belong to the same system\");\n    TCM_ASSERT(std::count(begin(child.data->_sites), end(child.data->_sites),\n                          child.edge.second)\n                   == 1,\n               \"Invalid child_conn_info_t\");\n    TCM_ASSERT(std::count(begin(_sites), end(_sites), child.edge.first) == 1,\n               \"Invalid child_conn_info_t\");\n\n    // Attach the child\n    child.data->_parent = {_children.size(), child.edge,\n                           gsl::not_null<magnetic_cluster_t*>{this}};\n    _children.emplace_back(std::move(child));\n    _children.back().data->align_with_parent();\n}\n\ntemplate <class System>\nauto magnetic_cluster_t<System>::merge(unique_ptr cluster) -> void\n{\n    using std::begin, std::end;\n    TCM_ASSERT(cluster != nullptr, \"Can't merge with a non-existant cluster\");\n    TCM_ASSERT(!cluster->_parent.has_value(), \"Cluster must be an orphan\");\n    TCM_ASSERT(std::addressof(cluster->_system_state)\n                   == std::addressof(_system_state),\n               \"Cluster must belong to the same system\");\n\n    // Steal children from `cluster`. For each child we have to update its\n    // `parent_conn_info_t.data` to point to this. After that, the child can be\n    // safely moved into `_children`.\n    _children.reserve(_children.size() + cluster->_children.size());\n    for (auto& conn : cluster->_children) {\n        conn.data->_parent->index = _children.size();\n        conn.data->_parent->data  = this;\n        _children.emplace_back(std::move(conn));\n    }\n    // cluster->_children.clear();\n\n    // Now we steal `cluster->_sites`. Each site now belongs to a different\n    // magnetic cluster. This info has to be propagated to the `_system_state`.\n    for (auto const site : cluster->_sites) {\n        _system_state.set_magnetic_cluster(site, *this);\n    }\n    _sites.reserve(_sites.size() + cluster->_sites.size());\n    _sites.insert(end(_sites), begin(cluster->_sites), end(cluster->_sites));\n}\n\n#    if 0\ntemplate <class System>\nTCM_FORCEINLINE auto magnetic_cluster_t<System>::merge(unique_ptr cluster)\n    -> void\n{\n    merge(no_optimize, std::move(cluster));\n    optimize_full();\n}\n#    endif\n\ntemplate <class System>\nauto magnetic_cluster_t<System>::rotate(angle_t const angle) -> void\n{\n    dfs([angle, this](auto& x) {\n        using std::begin, std::end;\n        _system_state.rotate(begin(x._sites), end(x._sites), angle);\n    });\n}\n\ntemplate <class System>\nTCM_FORCEINLINE auto\nmagnetic_cluster_t<System>::detach(size_t const child_index)\n    -> child_conn_info_t\n{\n    using std::swap;\n    TCM_ASSERT(child_index < _children.size(), \"Index out of bounds\");\n\n    if (child_index != _children.size() - 1) {\n        _children.back().data->_parent->index = child_index;\n        swap(_children[child_index], _children.back());\n    }\n    auto conn = std::move(_children.back());\n    _children.pop_back();\n    conn.data->_parent = std::nullopt;\n    return conn;\n}\n\n#    if 0\ntemplate <class System>\nauto magnetic_cluster_t<System>::thermalise(sa_pars_t const& parameters)\n    -> gsl::span<float>\n{\n    auto& sa_buffers = _system_state.sa_buffers();\n    sa_buffers.resize(_sites.size());\n\n    auto& energy_buffers = _system_state.energy_buffers();\n    auto energy_fn = energy_buffers.energy_fn(sites(), _system_state.lattice());\n\n    return optimise(std::move(energy_fn), parameters, sa_buffers,\n                    _system_state.rng_stream(),\n                    [this](auto initial) {\n                        using std::begin, std::end;\n                        std::transform(begin(_sites), end(_sites),\n                                       begin(initial), [this](auto const i) {\n                                           return static_cast<float>(\n                                               _system_state.get_angle(i));\n                                       });\n                    })\n        .buffer;\n}\n\ntemplate <class System>\nauto magnetic_cluster_t<System>::optimize_one(size_t const /*site*/) -> void\n{\n    using std::begin, std::end;\n    sa_pars_t params{/*q_V = */ 2.62f, /*q_A = */ -1.0f, /*t_0 = */ 10.0f,\n                     /*n = */ 1000u};\n\n    auto const angles = thermalise(params);\n\n    if (_parent.has_value()) {\n        auto const delta_angle = [this, &angles]() {\n            auto const [i, j] = _parent->edge;\n            auto const local_j =\n                _system_state.energy_buffers().global_to_local(j);\n            switch (interaction(_system_state.lattice(), i, j)) {\n            case interaction_t::Ferromagnetic:\n                return _system_state.get_angle(i) - angle_t{angles[local_j]};\n            case interaction_t::Antiferromagnetic:\n                return _system_state.get_angle(i) - angle_t{angles[local_j]}\n                       + angle_t{static_cast<float>(M_PI)};\n            } // end switch\n        }();\n\n        std::transform(begin(angles), end(angles), begin(angles),\n                       [delta_angle](auto const x) {\n                           return static_cast<float>(angle_t{x} + delta_angle);\n                       });\n    }\n\n    for (auto i = size_t{0}; i < _sites.size(); ++i) {\n        _system_state.set_angle(_sites[i], angle_t{angles[i]});\n    }\n    for (auto& child_conn : _children) {\n        child_conn.data->align_with_parent();\n    }\n    _is_optimised = true;\n}\n\ntemplate <class System>\nTCM_NOINLINE auto magnetic_cluster_t<System>::optimize_full() -> void\n{\n    using std::begin, std::end;\n    if (_parent.has_value()) {\n        auto const fixed_index = _parent->edge.second;\n        auto const fixed_angle = _system_state.get_angle(fixed_index);\n        TCM_ASSERT(std::find(begin(_sites), end(_sites), fixed_index)\n                       != end(_sites),\n                   \"`fixed_index` must belong to `*this`.\");\n        _system_state.set_angle(begin(_sites), end(_sites), fixed_angle);\n        /*\n        for (auto& conn : _children) {\n            TCM_ASSERT(conn.data->is_optimized(),\n                       \"It makes little sense to align a child which is not \"\n                       \"optimised.\");\n            conn.data->align_with_parent();\n        }\n        */\n    }\n    else {\n        auto const fixed_index = _sites.front();\n        auto const fixed_angle = _system_state.get_angle(fixed_index);\n        _system_state.set_angle(begin(_sites), end(_sites), fixed_angle);\n    }\n    _is_optimised = true;\n}\n#    endif\n\ntemplate <class System>\nTCM_FORCEINLINE auto\nmove_root_down(typename magnetic_cluster_t<System>::unique_ptr root,\n               size_t const                                    child_index) ->\n    typename magnetic_cluster_t<System>::unique_ptr\n{\n    // root->check_index_in_parent();\n    using child_conn_info_t =\n        typename magnetic_cluster_t<System>::child_conn_info_t;\n    TCM_ASSERT(root->is_root(), \"`root` must be the of the tree\");\n    TCM_ASSERT(child_index < root->_children.size(), \"Index out of bounds\");\n\n    // Remove `child_index` from `root`'s list of children\n    auto [edge, new_root] = root->detach(child_index);\n    // Construct the new connection with the direction inverted.\n    auto conn = child_conn_info_t{{edge.second, edge.first}, std::move(root)};\n    // Attach it to the new root\n    // auto const old_state = new_root->_is_optimised;\n    new_root->attach(std::move(conn));\n    // new_root->_is_optimised = old_state;\n    TCM_ASSERT(new_root->is_root(), \"Post-condition violated\");\n    // new_root->check_index_in_parent();\n    return std::move(new_root);\n}\n#endif\n\nTCM_NAMESPACE_END\n", "meta": {"hexsha": "2699a2c239dd218c51cfc3a3861809912961a69c", "size": 29138, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/detail/magnetic_cluster.hpp", "max_stars_repo_name": "twesterhout/percolation", "max_stars_repo_head_hexsha": "f82358ce628c2b48cf7f8435673af17eab08c527", "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/detail/magnetic_cluster.hpp", "max_issues_repo_name": "twesterhout/percolation", "max_issues_repo_head_hexsha": "f82358ce628c2b48cf7f8435673af17eab08c527", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/detail/magnetic_cluster.hpp", "max_forks_repo_name": "twesterhout/percolation", "max_forks_repo_head_hexsha": "f82358ce628c2b48cf7f8435673af17eab08c527", "max_forks_repo_licenses": ["BSD-3-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.651572327, "max_line_length": 83, "alphanum_fraction": 0.6243050312, "num_tokens": 7071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.27958175537640223}}
{"text": "//---------------------------------Spheral++----------------------------------//\n// IvanoviSALEDamageModel\n//\n// The Ivanov damage model, hopefully close to how it's implemented in iSALE.\n// This damage model is most appropriate for rocky materials.\n//\n// Refs:\n// \n// Collins, G. S., Melosh, H. J., & Ivanov, B. A. (2004). Modeling damage and deformation in impact simulations.\n//   Meteoritics & Planetary Science, 39(2), 217–231. http://doi.wiley.com/10.1111/j.1945-5100.2004.tb00337.x\n//\n// Raducan, S. D., Davison, T. M., Luther, R., & Collins, G. S. (2019). The role of asteroid strength, porosity and\n//   internal friction in impact momentum transfer. Icarus. https://doi.org/10.1016/J.ICARUS.2019.03.040\n//\n// Lundborg, N. (1967). The strength-size relation of granite. International Journal of Rock Mechanics and\n//   Mining Sciences & Geomechanics Abstracts, 4(3):269–272.f\n//\n// Created by JMO, Sat Jun 26 11:35:44 PDT 2021\n//----------------------------------------------------------------------------//\n#include \"FileIO/FileIO.hh\"\n#include \"IvanoviSALEDamageModel.hh\"\n#include \"TensorStrainPolicy.hh\"\n#include \"IvanoviSALEDamagePolicy.hh\"\n#include \"YoungsModulusPolicy.hh\"\n#include \"LongitudinalSoundSpeedPolicy.hh\"\n#include \"DamageGradientPolicy.hh\"\n#include \"Strength/SolidFieldNames.hh\"\n#include \"NodeList/SolidNodeList.hh\"\n#include \"DataBase/DataBase.hh\"\n#include \"DataBase/State.hh\"\n#include \"DataBase/StateDerivatives.hh\"\n#include \"DataBase/ReplaceState.hh\"\n#include \"Hydro/HydroFieldNames.hh\"\n#include \"Field/FieldList.hh\"\n#include \"Boundary/Boundary.hh\"\n#include \"Neighbor/Neighbor.hh\"\n#include \"Utilities/mortonOrderIndices.hh\"\n#include \"Utilities/allReduce.hh\"\n#include \"Utilities/uniform_random.hh\"\n\n#include <boost/functional/hash.hpp>  // hash_combine\n\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <limits>\nusing std::vector;\nusing std::string;\nusing std::pair;\nusing std::make_pair;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::min;\nusing std::max;\nusing std::abs;\n\nnamespace Spheral {\n\n//------------------------------------------------------------------------------\n// Constructor.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nIvanoviSALEDamageModel<Dimension>::\nIvanoviSALEDamageModel(SolidNodeList<Dimension>& nodeList,\n                       const TableKernel<Dimension>& W,\n                       const double minPlasticFailure,\n                       const double plasticFailurePressureSlope,\n                       const double plasticFailurePressureOffset,\n                       const double tensileFailureStress,\n                       const double crackGrowthMultiplier,\n                       const DamageCouplingAlgorithm damageCouplingAlgorithm,\n                       const double criticalDamageThreshold,\n                       const Field<Dimension, int>& mask):\n  DamageModel<Dimension>(nodeList, W, crackGrowthMultiplier, damageCouplingAlgorithm),\n  mEpsPfb(minPlasticFailure),\n  mB(plasticFailurePressureSlope),\n  mPc(plasticFailurePressureOffset),\n  mTensileFailureStress(tensileFailureStress),\n  mCriticalDamageThreshold(criticalDamageThreshold),\n  mMask(mask),\n  mYoungsModulus(SolidFieldNames::YoungsModulus, nodeList),\n  mLongitudinalSoundSpeed(SolidFieldNames::longitudinalSoundSpeed, nodeList),\n  mDdamageDt(IvanoviSALEDamagePolicy<Dimension>::prefix() + SolidFieldNames::scalarDamage, nodeList),\n  mStrain(SolidFieldNames::strainTensor, nodeList),\n  mEffectiveStrain(SolidFieldNames::effectiveStrainTensor, nodeList) {\n}\n\n//------------------------------------------------------------------------------\n// Destructor.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nIvanoviSALEDamageModel<Dimension>::\n~IvanoviSALEDamageModel() {\n}\n\n//------------------------------------------------------------------------------\n// Evaluate derivatives.\n//\n// In this model we compute the scalar damage derivative assuming unresolved\n// crack growth for every point. However, that is not applied in the tensor\n// damage update policy unless the flaws are actually activated.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nvoid\nIvanoviSALEDamageModel<Dimension>::\nevaluateDerivatives(const Scalar time,\n                    const Scalar dt,\n                    const DataBase<Dimension>& dataBase,\n                    const State<Dimension>& state,\n                    StateDerivatives<Dimension>& derivs) const {\n\n  // Set the scalar magnitude of the damage evolution.\n  const auto* nodeListPtr = &(this->nodeList());\n  auto&       DDDt = derivs.field(state.buildFieldKey(IvanoviSALEDamagePolicy<Dimension>::prefix() + SolidFieldNames::scalarDamage, nodeListPtr->name()), 0.0);\n  this->computeScalarDDDt(dataBase,\n                          state,\n                          time,\n                          dt,\n                          DDDt);\n}\n\n//------------------------------------------------------------------------------\n// Vote on a time step.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\ntypename IvanoviSALEDamageModel<Dimension>::TimeStepType\nIvanoviSALEDamageModel<Dimension>::\ndt(const DataBase<Dimension>& /*dataBase*/, \n   const State<Dimension>& /*state*/,\n   const StateDerivatives<Dimension>& /*derivs*/,\n   const Scalar /*currentTime*/) const {\n\n  // // Look at how quickly we're trying to change the damage.\n  // double dt = DBL_MAX;\n  // const Field<Dimension, SymTensor>& damage = this->nodeList().damage();\n  // const ConnectivityMap<Dimension>& connectivityMap = dataBase.connectivityMap();\n  // const vector<const NodeList<Dimension>*>& nodeLists = connectivityMap.nodeLists();\n  // const size_t nodeListi = distance(nodeLists.begin(), find(nodeLists.begin(), nodeLists.end(), &(this->nodeList())));\n  // for (typename ConnectivityMap<Dimension>::const_iterator iItr = connectivityMap.begin(nodeListi);\n  //      iItr != connectivityMap.end(nodeListi);\n  //      ++iItr) {\n  //   const int i = *iItr;\n  //   const double D0 = damage(i).Trace() / Dimension::nDim;\n  //   dt = min(dt, 0.8*max(D0, 1.0 - D0)/\n  //            std::sqrt(mDdamageDt(i)*mDdamageDt(i) + 1.0e-20));\n  // }\n  // return TimeStepType(dt, \"Rate of damage change\");\n\n  return TimeStepType(1.0e100, \"Rate of damage change -- NO VOTE.\");\n}\n\n//------------------------------------------------------------------------------\n// Register our state.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nvoid\nIvanoviSALEDamageModel<Dimension>::\nregisterState(DataBase<Dimension>& dataBase,\n              State<Dimension>& state) {\n\n  typedef typename State<Dimension>::PolicyPointer PolicyPointer;\n\n  // Register Youngs modulus and the longitudinal sound speed.\n  PolicyPointer EPolicy(new YoungsModulusPolicy<Dimension>());\n  PolicyPointer clPolicy(new LongitudinalSoundSpeedPolicy<Dimension>());\n  state.enroll(mYoungsModulus, EPolicy);\n  state.enroll(mLongitudinalSoundSpeed, clPolicy);\n\n  // Set the initial values\n  typename StateDerivatives<Dimension>::PackageList dummyPackages;\n  StateDerivatives<Dimension> derivs(dataBase, dummyPackages);\n  EPolicy->update(state.key(mYoungsModulus), state, derivs, 1.0, 0.0, 0.0);\n  clPolicy->update(state.key(mLongitudinalSoundSpeed), state, derivs, 1.0, 0.0, 0.0);\n\n  // Register the strain and effective strain.\n  PolicyPointer effectiveStrainPolicy(new TensorStrainPolicy<Dimension>(TensorStrainAlgorithm::PseudoPlasticStrain));\n  state.enroll(mStrain);\n  state.enroll(mEffectiveStrain, effectiveStrainPolicy);\n\n  // Register the damage and state it requires.\n  // Note we are overriding the default no-op policy for the damage\n  // as originally registered by the SolidSPHHydroBase class.\n  auto& damage = this->nodeList().damage();\n  PolicyPointer damagePolicy(new IvanoviSALEDamagePolicy<Dimension>(mEpsPfb,\n                                                                    mB,\n                                                                    mPc,\n                                                                    mTensileFailureStress));\n  state.enroll(damage, damagePolicy);\n \n  // Mask out nodes beyond the critical damage threshold from setting the timestep.\n  auto maskKey = state.buildFieldKey(HydroFieldNames::timeStepMask, this->nodeList().name());\n  auto& mask = state.field(maskKey, 0);\n  const auto nlocal = this->nodeList().numInternalNodes();\n#pragma omp parallel for\n  for (auto i = 0u; i < nlocal; ++i) {\n    if (damage(i).Trace() > mCriticalDamageThreshold) mask(i) = 0;\n  }\n}\n\n//------------------------------------------------------------------------------\n// Register the derivatives.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nvoid\nIvanoviSALEDamageModel<Dimension>::\nregisterDerivatives(DataBase<Dimension>& /*dataBase*/,\n                    StateDerivatives<Dimension>& derivs) {\n  derivs.enroll(mDdamageDt);\n}\n\n//------------------------------------------------------------------------------\n// Apply the boundary conditions to the ghost nodes.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nvoid\nIvanoviSALEDamageModel<Dimension>::\napplyGhostBoundaries(State<Dimension>& state,\n                     StateDerivatives<Dimension>& /*derivs*/) {\n\n  // Grab this models damage field from the state.\n  typedef typename State<Dimension>::KeyType Key;\n  const Key nodeListName = this->nodeList().name();\n  const Key DKey = state.buildFieldKey(SolidFieldNames::tensorDamage, nodeListName);\n  CHECK(state.registered(DKey));\n  auto& D = state.field(DKey, SymTensor::zero);\n\n  // Apply ghost boundaries to the damage.\n  for (auto boundaryItr = this->boundaryBegin();\n       boundaryItr < this->boundaryEnd();\n       ++boundaryItr) {\n    (*boundaryItr)->applyGhostBoundary(D);\n  }\n}\n\n//------------------------------------------------------------------------------\n// Enforce boundary conditions for the physics specific fields.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nvoid\nIvanoviSALEDamageModel<Dimension>::\nenforceBoundaries(State<Dimension>& state,\n                  StateDerivatives<Dimension>& /*derivs*/) {\n\n  // Grab this models damage field from the state.\n  typedef typename State<Dimension>::KeyType Key;\n  const Key nodeListName = this->nodeList().name();\n  const Key DKey = state.buildFieldKey(SolidFieldNames::tensorDamage, nodeListName);\n  CHECK(state.registered(DKey));\n  auto& D = state.field(DKey, SymTensor::zero);\n\n  // Enforce!\n  for (auto boundaryItr = this->boundaryBegin(); \n       boundaryItr < this->boundaryEnd();\n       ++boundaryItr) {\n    (*boundaryItr)->enforceBoundary(D);\n  }\n}\n\n//------------------------------------------------------------------------------\n// Dump the current state to the given file.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nvoid\nIvanoviSALEDamageModel<Dimension>::\ndumpState(FileIO& file, const string& pathName) const {\n  DamageModel<Dimension>::dumpState(file, pathName);\n  file.write(mStrain, pathName + \"/strain\");\n  file.write(mEffectiveStrain, pathName + \"/effectiveStrain\");\n  file.write(mDdamageDt, pathName + \"/DdamageDt\");\n  file.write(mMask, pathName + \"/mask\");\n}\n\n//------------------------------------------------------------------------------\n// Restore the state from the given file.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nvoid\nIvanoviSALEDamageModel<Dimension>::\nrestoreState(const FileIO& file, const string& pathName) {\n  DamageModel<Dimension>::restoreState(file, pathName);\n  file.read(mStrain, pathName + \"/strain\");\n  file.read(mEffectiveStrain, pathName + \"/effectiveStrain\");\n  file.read(mDdamageDt, pathName + \"/DdamageDt\");\n  file.read(mMask, pathName + \"/mask\");\n}\n\n}\n\n", "meta": {"hexsha": "71f1f3b78673729162322f9cf3b57c66690f2167", "size": 12136, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Damage/IvanoviSALEDamageModel.cc", "max_stars_repo_name": "jmikeowen/Spheral", "max_stars_repo_head_hexsha": "3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4", "max_stars_repo_licenses": ["BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2018-07-31T21:38:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-29T08:58:33.000Z", "max_issues_repo_path": "src/Damage/IvanoviSALEDamageModel.cc", "max_issues_repo_name": "jmikeowen/Spheral", "max_issues_repo_head_hexsha": "3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4", "max_issues_repo_licenses": ["BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2020-09-28T23:14:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T17:01:33.000Z", "max_forks_repo_path": "src/Damage/IvanoviSALEDamageModel.cc", "max_forks_repo_name": "jmikeowen/Spheral", "max_forks_repo_head_hexsha": "3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4", "max_forks_repo_licenses": ["BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T07:00:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-15T21:12:39.000Z", "avg_line_length": 41.8482758621, "max_line_length": 159, "alphanum_fraction": 0.6021753461, "num_tokens": 2575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.27958175537640223}}
{"text": "// This is an advanced implementation of the algorithm described in the\n// following paper:\n//    C. Hertzberg,  R.  Wagner,  U.  Frese,  and  L.  Schroder.  Integratinggeneric   sensor   fusion   algorithms with\n//    sound   state   representationsthrough  encapsulation  of  manifolds. CoRR,  vol.  abs/1107.1119,  2011.[Online].\n//    Available: http://arxiv.org/abs/1107.1119\n\n/*\n *  Copyright (c) 2019--2023, The University of Hong Kong\n *  All rights reserved.\n *\n *  Modifier: Dongjiao HE <hdj65822@connect.hku.hk>\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/*\n *  Copyright (c) 2008--2011, 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 * @file mtk/src/mtkmath.hpp\n * @brief several math utility functions.\n */\n\n#ifndef MTKMATH_H_\n#define MTKMATH_H_\n\n#include <cmath>\n\n#include <boost/math/tools/precision.hpp>\n\n#include \"../types/vect.hpp\"\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\nnamespace MTK {\n\nnamespace internal {\n\ntemplate <class Manifold>\nstruct traits {\n    typedef typename Manifold::scalar scalar;\n    enum { DOF = Manifold::DOF };\n    typedef vect<DOF, scalar> vectorized_type;\n    typedef Eigen::Matrix<scalar, DOF, DOF> matrix_type;\n};\n\ntemplate <>\nstruct traits<float> : traits<Scalar<float> > {};\ntemplate <>\nstruct traits<double> : traits<Scalar<double> > {};\n\n}  // namespace internal\n\n/**\n * \\defgroup MTKMath Mathematical helper functions\n */\n//@{\n\n//! constant @f$ \\pi @f$\nconst double pi = M_PI;\n\ntemplate <class scalar>\ninline scalar tolerance();\n\ntemplate <>\ninline float tolerance<float>() {\n    return 1e-5f;\n}\ntemplate <>\ninline double tolerance<double>() {\n    return 1e-11;\n}\n\n/**\n * normalize @a x to @f$[-bound, bound] @f$.\n *\n * result for @f$ x = bound + 2\\cdot n\\cdot bound @f$ is arbitrary @f$\\pm bound @f$.\n */\ntemplate <class scalar>\ninline scalar normalize(scalar x, scalar bound) {  // not used\n    if (std::fabs(x) <= bound) return x;\n    int r = (int)(x * (scalar(1.0) / bound));\n    return x - ((r + (r >> 31) + 1) & ~1) * bound;\n}\n\n/**\n * Calculate cosine and sinc of sqrt(x2).\n * @param x2 the squared angle must be non-negative\n * @return a pair containing cos and sinc of sqrt(x2)\n */\ntemplate <class scalar>\nstd::pair<scalar, scalar> cos_sinc_sqrt(const scalar& x2) {\n    using std::cos;\n    using std::sin;\n    using std::sqrt;\n    static scalar const taylor_0_bound = boost::math::tools::epsilon<scalar>();\n    static scalar const taylor_2_bound = sqrt(taylor_0_bound);\n    static scalar const taylor_n_bound = sqrt(taylor_2_bound);\n\n    assert(x2 >= 0 && \"argument must be non-negative\");\n\n    // FIXME check if bigger bounds are possible\n    if (x2 >= taylor_n_bound) {\n        // slow fall-back solution\n        scalar x = sqrt(x2);\n        return std::make_pair(cos(x), sin(x) / x);  // x is greater than 0.\n    }\n\n    // FIXME Replace by Horner-Scheme (4 instead of 5 FLOP/term, numerically more stable, theoretically cos and sinc can\n    // be calculated in parallel using SSE2 mulpd/addpd)\n    // TODO Find optimal coefficients using Remez algorithm\n    static scalar const inv[] = {1 / 3., 1 / 4., 1 / 5., 1 / 6., 1 / 7., 1 / 8., 1 / 9.};\n    scalar cosi = 1., sinc = 1;\n    scalar term = -1 / 2. * x2;\n    for (int i = 0; i < 3; ++i) {\n        cosi += term;\n        term *= inv[2 * i];\n        sinc += term;\n        term *= -inv[2 * i + 1] * x2;\n    }\n\n    return std::make_pair(cosi, sinc);\n}\n\ntemplate <typename Base>\nEigen::Matrix<typename Base::scalar, 3, 3> hat(const Base& v) {\n    Eigen::Matrix<typename Base::scalar, 3, 3> res;\n    res << 0, -v[2], v[1], v[2], 0, -v[0], -v[1], v[0], 0;\n    return res;\n}\n\ntemplate <typename Base>\nEigen::Matrix<typename Base::scalar, 3, 3> A_inv_trans(const Base& v) {\n    Eigen::Matrix<typename Base::scalar, 3, 3> res;\n    if (v.norm() > MTK::tolerance<typename Base::scalar>()) {\n        res = Eigen::Matrix<typename Base::scalar, 3, 3>::Identity() + 0.5 * hat<Base>(v) +\n              (1 - v.norm() * std::cos(v.norm() / 2) / 2 / std::sin(v.norm() / 2)) * hat(v) * hat(v) / v.squaredNorm();\n\n    } else {\n        res = Eigen::Matrix<typename Base::scalar, 3, 3>::Identity();\n    }\n\n    return res;\n}\n\ntemplate <typename Base>\nEigen::Matrix<typename Base::scalar, 3, 3> A_inv(const Base& v) {\n    Eigen::Matrix<typename Base::scalar, 3, 3> res;\n    if (v.norm() > MTK::tolerance<typename Base::scalar>()) {\n        res = Eigen::Matrix<typename Base::scalar, 3, 3>::Identity() - 0.5 * hat<Base>(v) +\n              (1 - v.norm() * std::cos(v.norm() / 2) / 2 / std::sin(v.norm() / 2)) * hat(v) * hat(v) / v.squaredNorm();\n\n    } else {\n        res = Eigen::Matrix<typename Base::scalar, 3, 3>::Identity();\n    }\n\n    return res;\n}\n\ntemplate <typename scalar>\nEigen::Matrix<scalar, 2, 3> S2_w_expw_(Eigen::Matrix<scalar, 2, 1> v, scalar length) {\n    Eigen::Matrix<scalar, 2, 3> res;\n    scalar norm = std::sqrt(v[0] * v[0] + v[1] * v[1]);\n    if (norm < MTK::tolerance<scalar>()) {\n        res = Eigen::Matrix<scalar, 2, 3>::Zero();\n        res(0, 1) = 1;\n        res(1, 2) = 1;\n        res /= length;\n    } else {\n        res << -v[0] * (1 / norm - 1 / std::tan(norm)) / std::sin(norm), norm / std::sin(norm), 0,\n            -v[1] * (1 / norm - 1 / std::tan(norm)) / std::sin(norm), 0, norm / std::sin(norm);\n        res /= length;\n    }\n}\n\ntemplate <typename Base>\nEigen::Matrix<typename Base::scalar, 3, 3> A_matrix(const Base& v) {\n    Eigen::Matrix<typename Base::scalar, 3, 3> res;\n    double squaredNorm = v[0] * v[0] + v[1] * v[1] + v[2] * v[2];\n    double norm = std::sqrt(squaredNorm);\n    if (norm < MTK::tolerance<typename Base::scalar>()) {\n        res = Eigen::Matrix<typename Base::scalar, 3, 3>::Identity();\n    } else {\n        res = Eigen::Matrix<typename Base::scalar, 3, 3>::Identity() + (1 - std::cos(norm)) / squaredNorm * hat(v) +\n              (1 - std::sin(norm) / norm) / squaredNorm * hat(v) * hat(v);\n    }\n    return res;\n}\n\ntemplate <class scalar, int n>\nscalar exp(vectview<scalar, n> result, vectview<const scalar, n> vec, const scalar& scale = 1) {\n    scalar norm2 = vec.squaredNorm();\n    std::pair<scalar, scalar> cos_sinc = cos_sinc_sqrt(scale * scale * norm2);\n    scalar mult = cos_sinc.second * scale;\n    result = mult * vec;\n    return cos_sinc.first;\n}\n\n/**\n * Inverse function to @c exp.\n *\n * @param result @c vectview to the result\n * @param w      scalar part of input\n * @param vec    vector part of input\n * @param scale  scale result by this value\n * @param plus_minus_periodicity if true values @f$[w, vec]@f$ and @f$[-w, -vec]@f$ give the same result\n */\ntemplate <class scalar, int n>\nvoid log(vectview<scalar, n> result, const scalar& w, const vectview<const scalar, n> vec, const scalar& scale,\n         bool plus_minus_periodicity) {\n    // FIXME implement optimized case for vec.squaredNorm() <= tolerance() * (w*w) via Rational Remez approximation ~>\n    // only one division\n    scalar nv = vec.norm();\n    if (nv < tolerance<scalar>()) {\n        if (!plus_minus_periodicity && w < 0) {\n            // find the maximal entry:\n            int i;\n            nv = vec.cwiseAbs().maxCoeff(&i);\n            result = scale * std::atan2(nv, w) * vect<n, scalar>::Unit(i);\n            return;\n        }\n        nv = tolerance<scalar>();\n    }\n    scalar s = scale / nv * (plus_minus_periodicity ? std::atan(nv / w) : std::atan2(nv, w));\n\n    result = s * vec;\n}\n\n}  // namespace MTK\n\n#endif /* MTKMATH_H_ */\n", "meta": {"hexsha": "4ab4a22a40e912e7201b1659dc8dff9d8d0eda9b", "size": 10531, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/IKFoM_toolkit/mtk/src/mtkmath.hpp", "max_stars_repo_name": "xiaotaw/faster-lio", "max_stars_repo_head_hexsha": "ff0c9092989da5dc3f1f66e798915d648b31b695", "max_stars_repo_licenses": ["MIT"], "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/IKFoM_toolkit/mtk/src/mtkmath.hpp", "max_issues_repo_name": "xiaotaw/faster-lio", "max_issues_repo_head_hexsha": "ff0c9092989da5dc3f1f66e798915d648b31b695", "max_issues_repo_licenses": ["MIT"], "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/IKFoM_toolkit/mtk/src/mtkmath.hpp", "max_forks_repo_name": "xiaotaw/faster-lio", "max_forks_repo_head_hexsha": "ff0c9092989da5dc3f1f66e798915d648b31b695", "max_forks_repo_licenses": ["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.4394463668, "max_line_length": 120, "alphanum_fraction": 0.6505555028, "num_tokens": 2933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.2795817553764022}}
{"text": "#ifndef STAN_MATH_TORSTEN_ONECTP_HPP\n#define STAN_MATH_TORSTEN_ONECTP_HPP\n\n#include <Eigen/Dense>\n#include <boost/math/tools/promotion.hpp>\n#include <stan/math/torsten/to_array_2d.hpp>\n#include <stan/math/torsten/pmx_solve_ode.hpp>\n#include <stan/math/torsten/pmx_solve_cpt.hpp>\n#include <stan/math/prim/err/check_positive_finite.hpp>\n#include <stan/math/torsten/ev_solver.hpp>\n#include <stan/math/torsten/ev_manager.hpp>\n#include <stan/math/torsten/pmx_onecpt_model.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 analytical solution.\n *\n * @tparam Ts types of parameters, see <code>pmx_solve_cpt</code> for\n *         details. \n * @return a matrix with predicted amount in each compartment \n *         at each event. \n *\n */\n  template <typename... Ts>\n  auto pmx_solve_onecpt(Ts... args) {\n    return PMXSolveCPT<PMXOneCptModel>::solve(args...);\n  }\n\n  // old version\n  template <typename T0, typename T1, typename T2, typename T3, typename T4,\n            typename T5, typename T6>\n  stan::matrix_return_t<T0, T1, T2, T3, T4, T5, T6>\n  PKModelOneCpt(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    auto x = pmx_solve_onecpt(time, amt, rate, ii, evid, cmt, addl, ss,\n                              pMatrix, biovar, tlag);\n    return x.transpose();\n  }\n\n  template <typename T0, typename T1, typename T2, typename T3,\n            typename T_par, typename T_biovar, typename T_tlag,\n            typename = require_any_not_std_vector_t<T_par, T_biovar, T_tlag> >\n  stan::matrix_return_t<T0, T1, T2, T3, T_par, T_biovar, T_tlag>\n  PKModelOneCpt(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<T_par>& pMatrix,\n                   const std::vector<T_biovar>& biovar,\n                   const std::vector<T_tlag>& tlag) {\n    auto x = pmx_solve_onecpt(time, amt, rate, ii, evid, cmt, addl, ss,\n                            pMatrix, biovar, tlag);\n    return x.transpose();\n  }\n\n}\n\n#endif\n", "meta": {"hexsha": "3c02ae50949434331586e8b854bad9049dd01f72", "size": 2840, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pmx_solve_onecpt.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": "pmx_solve_onecpt.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": "pmx_solve_onecpt.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": 37.3684210526, "max_line_length": 78, "alphanum_fraction": 0.6059859155, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2795273458987158}}
{"text": "/*******************************************************************************\n *\n * Data structures for the symbolic manipulation of linear constraints.\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#ifndef IKOS_LINEAR_CONSTRAINTS_HPP\n#define IKOS_LINEAR_CONSTRAINTS_HPP\n\n#include <boost/optional.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/container/flat_map.hpp>\n#include <boost/container/slist.hpp>\n#include <boost/iterator/iterator_facade.hpp>\n#include <boost/functional/hash.hpp>\n#include <crab/common/types.hpp>\n#include <crab/domains/patricia_trees.hpp>\n\nnamespace ikos {\n  \n  template< typename Number, typename VariableName >\n  class linear_expression: public writeable {\n    \n  public:\n    typedef Number number_t;\n    typedef VariableName varname_t;\n    typedef variable< Number, VariableName > variable_t;\n    typedef linear_expression< Number, VariableName > linear_expression_t;\n    typedef std::pair< Number, variable_t > component_t;\n    typedef patricia_tree_set< variable_t > variable_set_t;\n    \n  private:\n    typedef boost::container::flat_map< variable_t, Number > map_t;\n    typedef boost::shared_ptr< map_t > map_ptr;\n    typedef typename map_t::value_type pair_t;\n    \n  private:\n    map_ptr _map;\n    Number _cst;\n    \n  private:\n    linear_expression(map_ptr map, Number cst): \n        _map(map), _cst(cst) { }\n    \n    linear_expression(const map_t& map, Number cst): \n        _map(map_ptr(new map_t)), _cst(cst) {\n      *this->_map = map;\n    }\n    \n    void add(variable_t x, Number n) {\n      typename map_t::iterator it = this->_map->find(x);\n      if (it != this->_map->end()) {\n        Number r = it->second + n;\n        if (r == 0) {\n          this->_map->erase(it);\n        } else {\n          it->second = r;\n        }\n      } else {\n        if (n != 0) {\n          this->_map->insert(pair_t(x, n));\n        }\n      }\n    }\n    \n   public:\n    class iterator: public boost::iterator_facade< iterator,\n                                                   component_t,\n                                                   boost::forward_traversal_tag,\n                                                   component_t> {\n      \n      friend class boost::iterator_core_access;\n      \n     private:\n      typename map_t::const_iterator _it;\n      map_ptr _m;\n      \n     public:\n      iterator(map_ptr m, bool b): _it(b ? m->begin() : m->end()), _m(m) { }\n      \n     private:\n      void increment() { \n        ++this->_it;\n      }\n      \n      bool equal(const iterator& other) const {\n        return (this->_m == other._m && this->_it == other._it);\n      }\n      \n      component_t dereference() const {\n        if (this->_it != this->_m->end()) {\n          return component_t(this->_it->second, this->_it->first);\n        } else {\n          CRAB_ERROR(\"Linear expression: trying to dereference an empty iterator\");\n        }\n      }\n      \n    }; // class iterator\n    \n  public:\n    linear_expression(): \n        _map(map_ptr(new map_t)), _cst(0) { }\n    \n    linear_expression(Number n): \n        _map(map_ptr(new map_t)), _cst(n) { }\n    \n    linear_expression(signed long long int n): \n        _map(map_ptr(new map_t)), _cst(Number(n)) { }\n    \n    linear_expression(variable_t x): \n        _map(map_ptr(new map_t)), _cst(0) {\n      this->_map->insert(pair_t(x, Number(1)));\n    }\n    \n    linear_expression(Number n, variable_t x): \n        _map(map_ptr(new map_t)), _cst(0) {\n      this->_map->insert(pair_t(x, n));\n    }\n\n    linear_expression_t& operator=(const linear_expression_t &e) {\n      if (this != &e) {\n        this->_map = e._map;\n        this->_cst = e._cst;\n      }\n      return *this;\n    }\n    \n    iterator begin() const {\n      return iterator(this->_map, true);\n    }\n\n    iterator end() const {\n      return iterator(this->_map, false);\n    }\n\n    size_t hash () const {\n      size_t res = 0;\n      for (iterator it=begin(), et=end (); it!=et; ++it) {\n        boost::hash_combine (res, std::make_pair((*it).second, (*it).first));\n      }\n      boost::hash_combine (res, _cst);\n      return res;\n    }\n\n    bool is_constant() const {\n      return (this->_map->size() == 0);\n    }\n\n    Number constant() const {\n      return this->_cst;\n    }\n    \n    std::size_t size() const {\n      return this->_map->size();\n    }\n\n    Number operator[](variable_t x) const {\n      typename map_t::const_iterator it = this->_map->find(x);\n      if (it != this->_map->end()) {\n\treturn it->second;\n      } else {\n\treturn 0;\n      }\n    }\n\n    template<typename VarMap>\n    boost::optional<linear_expression_t> rename (const VarMap& map) const {\n      Number cst(this->_cst);\n      linear_expression_t ren_exp(cst);\n      for(auto v : this->variables()) {\n        auto const it = map.find(v);\n        if (it != map.end()) {\n          variable_t v_out ((*it).second);\n          ren_exp = ren_exp + this->operator[](v) * v_out;\n        }\n        else\n          return boost::optional<linear_expression_t>();\n      }\n      return ren_exp;\n    }\n\n    linear_expression_t operator+(Number n) const {\n      linear_expression_t r(this->_map, this->_cst + n);\n      return r;\n    }\n\n    linear_expression_t operator+(int n) const {\n      return this->operator+(Number(n));\n    }\n    \n    linear_expression_t operator+(variable_t x) const {\n      linear_expression_t r(*this->_map, this->_cst);\n      r.add(x, Number(1));\n      return r;\n    }\n    \n    linear_expression_t operator+(const linear_expression_t &e) const {\n      linear_expression_t r(*this->_map, this->_cst + e._cst);\n      for (typename map_t::const_iterator it = e._map->begin(); \n           it != e._map->end(); ++it) {\n        r.add(it->first, it->second);\n      }\n      return r;\n    }\n\n    linear_expression_t operator-(Number n) const {\n      return this->operator+(-n);\n    }\n\n    linear_expression_t operator-(int n) const {\n      return this->operator+(-Number(n));\n    }\n\n    linear_expression_t operator-(variable_t x) const {\n      linear_expression_t r(*this->_map, this->_cst);\n      r.add(x, Number(-1));\n      return r;      \n    }\n\n    linear_expression_t operator-() const {\n      return this->operator*(Number(-1));\n    }\n\n    linear_expression_t operator-(const linear_expression_t &e) const {\n      linear_expression_t r(*this->_map, this->_cst - e._cst);\n      for (typename map_t::const_iterator it = e._map->begin(); \n           it != e._map->end(); ++it) {\n        r.add(it->first, -it->second);\n      }\n      return r;      \n    }\n    \n    linear_expression_t operator*(Number n) const {\n      if (n == 0) {\n        return linear_expression_t();\n      } else {\n        map_ptr map = map_ptr(new map_t);\n        for (typename map_t::const_iterator it = this->_map->begin(); \n             it != this->_map->end(); ++it) {\n          Number c = n * it->second;\n          if (c != 0) {\n            map->insert(pair_t(it->first, c));\n          }\n        }\n        return linear_expression_t(map, n * this->_cst);\n      }\n    }\n    \n    linear_expression_t operator*(int n) const {\n      return operator*(Number(n));\n    }\n    \n    variable_set_t variables() const {\n      variable_set_t variables;\n      for (iterator it = this->begin(); it != this->end(); ++it) {\n\tvariables += it->second;\n      }\n      return variables;\n    }\n\n    boost::optional<variable_t> get_variable() const {\n      if (this->is_constant())\n        return boost::optional<variable_t>();\n      else{\n        if ((this->constant() == 0) && (this->size() == 1)){\n          typename linear_expression_t::iterator it = this->begin();\n          Number coeff = it->first;\n          if (coeff == 1)\n            return boost::optional<variable_t>(it->second);\n        }\n        return boost::optional<variable_t>();\n      }\n    }\n    \n    void write(crab::crab_os& o) {\n      for (typename map_t::iterator it = this->_map->begin(); \n           it != this->_map->end(); ++it) {\n        Number n = it->second;\n        variable_t v = it->first;\n        if (n > 0 && it != this->_map->begin()) {\n          o << \"+\";\n        }\n        if (n == -1) {\n          o << \"-\";\n        } else if (n != 1) {\n          o << n;\n        }\n        o << v;\n      }\n      if (this->_cst > 0 && this->_map->size() > 0) {\n        o << \"+\";\n      }\n      if (this->_cst != 0 || this->_map->size() == 0) {\n        o << this->_cst;\n      }\n    }\n    \n  }; // class linear_expression\n\n  template<typename Number, typename VariableName>\n  inline std::size_t hash_value(const linear_expression<Number,VariableName>& e) {\n    return e.hash ();\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_expression< Number, VariableName > \n  operator*(Number n, variable< Number, VariableName > x) {\n    return linear_expression< Number, VariableName >(n, x);\n  }\n  \n  template< typename Number, typename VariableName >\n  inline linear_expression< Number, VariableName > \n  operator*(int n, variable< Number, VariableName > x) {\n    return linear_expression< Number, VariableName >(Number(n), x);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_expression< Number, VariableName > \n  operator*(variable< Number, VariableName > x, Number n) {\n    return linear_expression< Number, VariableName >(n, x);\n  }\n  \n  template< typename Number, typename VariableName >\n  inline linear_expression< Number, VariableName > \n  operator*(variable< Number, VariableName > x, int n) {\n    return linear_expression< Number, VariableName >(Number(n), x);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_expression< Number, VariableName > \n  operator*(Number n, const linear_expression< Number, VariableName > &e) {\n    return e.operator*(n);\n  }\n  \n  template< typename Number, typename VariableName >\n  inline linear_expression< Number, VariableName > \n  operator*(int n, const linear_expression< Number, VariableName > &e) {\n    return e.operator*(n);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_expression< Number, VariableName > \n  operator+(variable< Number, VariableName > x, Number n) {\n    return linear_expression< Number, VariableName >(x).operator+(n);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_expression< Number, VariableName > \n  operator+(variable< Number, VariableName > x, int n) {\n    return linear_expression< Number, VariableName >(x).operator+(n);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_expression< Number, VariableName > \n  operator+(Number n, variable< Number, VariableName > x) {\n    return linear_expression< Number, VariableName >(x).operator+(n);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_expression< Number, VariableName > \n  operator+(int n, variable< Number, VariableName > x) {\n    return linear_expression< Number, VariableName >(x).operator+(n);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_expression< Number, VariableName > \n  operator+(variable< Number, VariableName > x, \n            variable< Number, VariableName > y) {\n    return linear_expression< Number, VariableName >(x).operator+(y);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_expression< Number, VariableName > \n  operator+(Number n, const linear_expression< Number, VariableName > &e) {\n    return e.operator+(n);\n  }\n  \n  template< typename Number, typename VariableName >\n  inline linear_expression< Number, VariableName > \n  operator+(int n, const linear_expression< Number, VariableName > &e) {\n    return e.operator+(n);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_expression< Number, VariableName > \n  operator+(variable< Number, VariableName > x, \n            const linear_expression< Number, VariableName > &e) {\n    return e.operator+(x);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_expression< Number, VariableName > \n  operator-(variable< Number, VariableName > x, Number n) {\n    return linear_expression< Number, VariableName >(x).operator-(n);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_expression< Number, VariableName > \n  operator-(variable< Number, VariableName > x, int n) {\n    return linear_expression< Number, VariableName >(x).operator-(n);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_expression< Number, VariableName > \n  operator-(Number n, variable< Number, VariableName > x) {\n    return linear_expression< Number, VariableName >(Number(-1), x).operator+(n);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_expression< Number, VariableName > \n  operator-(int n, variable< Number, VariableName > x) {\n    return linear_expression< Number, VariableName >(Number(-1), x).operator+(n);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_expression< Number, VariableName > \n  operator-(variable< Number, VariableName > x, \n            variable< Number, VariableName > y) {\n    return linear_expression< Number, VariableName >(x).operator-(y);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_expression< Number, VariableName > \n  operator-(Number n, const linear_expression< Number, VariableName > &e) {\n    return linear_expression< Number, VariableName >(n).operator-(e);\n  }\n  \n  template< typename Number, typename VariableName >\n  inline linear_expression< Number, VariableName > \n  operator-(int n, const linear_expression< Number, VariableName > &e) {\n    return linear_expression< Number, VariableName >(Number(n)).operator-(e);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_expression< Number, VariableName > \n  operator-(variable< Number, VariableName > x, \n            const linear_expression< Number, VariableName > &e) {\n    return linear_expression< Number, VariableName >(Number(1), x).operator-(e);\n  }\n  \n  template< typename Number, typename VariableName >\n  class linear_constraint: public writeable {\n    \n  public:\n    typedef Number number_t;\n    typedef VariableName varname_t;\n    typedef linear_constraint< Number, VariableName > linear_constraint_t;\n    typedef variable< Number, VariableName > variable_t;\n    typedef linear_expression< Number, VariableName > linear_expression_t;\n    typedef patricia_tree_set< variable_t > variable_set_t;\n    typedef enum {\n      EQUALITY,\n      DISEQUATION,\n      INEQUALITY\n    } kind_t;\n    typedef typename linear_expression_t::iterator iterator;\n    \n  private:\n    kind_t _kind;\n    linear_expression_t _expr;\n\n  public:\n    linear_constraint(): _kind(EQUALITY) { }\n    \n    linear_constraint(const linear_expression_t &expr, \n                      kind_t kind): _kind(kind), _expr(expr) { }    \n\n    static linear_constraint_t get_true () {\n      linear_constraint_t res(linear_expression_t(Number(0)), EQUALITY);\n      return res;\n    }\n\n    static linear_constraint_t get_false () {\n      linear_constraint_t res(linear_expression_t(Number(0)), DISEQUATION);\n      return res;\n    }\n\n    bool is_tautology() const {\n      switch (this->_kind) {\n        case DISEQUATION: \n          return (this->_expr.is_constant() && this->_expr.constant() != 0);\n        case EQUALITY:\n          return (this->_expr.is_constant() && this->_expr.constant() == 0);\n        case INEQUALITY: \n\treturn (this->_expr.is_constant() && this->_expr.constant() <= 0);\n        default: \n          CRAB_ERROR(\"Unreachable\");\n      }\n    }\n    \n    bool is_contradiction() const {\n      switch (this->_kind) {\n        case DISEQUATION: \n          return (this->_expr.is_constant() && this->_expr.constant() == 0);\n        case EQUALITY: \n\treturn (this->_expr.is_constant() && this->_expr.constant() != 0);\n        case INEQUALITY: \n\treturn (this->_expr.is_constant() && this->_expr.constant() > 0);\n        default: \n\tCRAB_ERROR(\"Unreachable\");\n      }\n    }\n\n    bool is_inequality() const {\n      return (this->_kind == INEQUALITY);\n    }\n\n    bool is_equality() const {\n      return (this->_kind == EQUALITY);\n    }\n\n    bool is_disequation() const {\n      return (this->_kind == DISEQUATION);\n    }\n\n    const linear_expression_t& expression() const {\n      return this->_expr;\n    }\n    \n    kind_t kind() const {\n      return this->_kind;\n    }\n\n    iterator begin() const {\n      return this->_expr.begin();\n    }\n\n    iterator end() const {\n      return this->_expr.end();\n    }\n\n    Number constant() const {\n      return -this->_expr.constant();\n    }\n\n    std::size_t size() const {\n      return this->_expr.size();\n    }\n\n    size_t hash () const {\n      size_t res = 0;\n      boost::hash_combine (res, _expr);\n      boost::hash_combine (res, _kind);\n      return res;\n    }\n    \n    Number operator[](variable_t x) const {\n      return this->_expr.operator[](x);\n    }\n\n    variable_set_t variables() const {\n      return this->_expr.variables();\n    }\n\n    linear_constraint_t negate () const {\n      if (is_tautology ())\n         return linear_constraint_t ( linear_expression_t (0) >= linear_expression_t (1));\n      else if (is_contradiction ())\n         return linear_constraint_t ( linear_expression_t (1) >= linear_expression_t (0));\n      else {\n        switch (kind ()) {\n          case INEQUALITY: {\n            linear_expression_t e = -(this->_expr - 1);\n            return linear_constraint_t (e, INEQUALITY);\n          }\n          case EQUALITY:\n            return linear_constraint_t (this->_expr, DISEQUATION);\n          case DISEQUATION: \n            return linear_constraint_t (this->_expr, EQUALITY);\n          default: ;;             \n        }\n      }\n      CRAB_ERROR(\"unreachable\");       \n    }\n\n    template<typename VarMap>\n    boost::optional<linear_constraint_t> rename(const VarMap& map) const {\n\n      boost::optional<linear_expression_t> e = this->_expr.rename(map);\n      if (e) {\n        return linear_constraint_t(*e, this->_kind);\n      } else {\n        return boost::optional<linear_constraint_t>();\n      }\n    }\n\n    \n    void write(crab::crab_os& o) {\n      if (this->is_contradiction()) {\n        o << \"false\";\n      } else if (this->is_tautology()) {\n        o << \"true\";\n      } else {\n        linear_expression_t e = this->_expr - this->_expr.constant();\n        o << e;\n        switch (this->_kind) {\n\tcase INEQUALITY: {\n            o << \" <= \";\n            break;\n          }\n\tcase EQUALITY: {\n            o << \" = \";\n            break;\n          }\n\tcase DISEQUATION: {\n            o << \" != \";\n            break;\n          }\n        }\n        Number c = -this->_expr.constant();\n        o << c;\n      }\n    }\n    \n    \n  }; // class linear_constraint\n\n  template<typename Number, typename VariableName>\n  inline std::size_t hash_value(const linear_constraint<Number,VariableName>& e) {\n    return e.hash ();\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator<=(const linear_expression< Number, VariableName > &e, Number n) {\n    return linear_constraint< Number, VariableName >\n        (e - n, linear_constraint< Number, VariableName >::INEQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator<=(const linear_expression< Number, VariableName > &e, int n) {\n    return linear_constraint< Number, VariableName >\n        (e - n, linear_constraint< Number, VariableName >::INEQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator<=(Number n, const linear_expression< Number, VariableName > &e) {\n    return linear_constraint< Number, VariableName >\n        (n - e, linear_constraint< Number, VariableName >::INEQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator<=(int n, const linear_expression< Number, VariableName > &e) {\n    return linear_constraint< Number, VariableName >\n        (n - e, linear_constraint< Number, VariableName >::INEQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator<=(const linear_expression< Number, VariableName > &e, \n             variable< Number, VariableName > x) {\n    return linear_constraint< Number, VariableName >\n        (e - x, linear_constraint< Number, VariableName >::INEQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator<=(variable< Number, VariableName > x, \n             const linear_expression< Number, VariableName > &e) {\n    return linear_constraint< Number, VariableName >\n        (x - e, linear_constraint< Number, VariableName >::INEQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator<=(variable< Number, VariableName > x, Number n) {\n    return linear_constraint< Number, VariableName >\n        (x - n, linear_constraint< Number, VariableName >::INEQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator<=(variable< Number, VariableName > x, int n) {\n    return linear_constraint< Number, VariableName >\n        (x - n, linear_constraint< Number, VariableName >::INEQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator<=(Number n, variable< Number, VariableName > x) {\n    return linear_constraint< Number, VariableName >\n        (n - x, linear_constraint< Number, VariableName >::INEQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator<=(int n, variable< Number, VariableName > x) {\n    return linear_constraint< Number, VariableName >\n        (n - x, linear_constraint< Number, VariableName >::INEQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator<=(variable< Number, VariableName > x, variable< Number, VariableName > y) {\n    return linear_constraint< Number, VariableName >\n        (x - y, linear_constraint< Number, VariableName >::INEQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator<=(const linear_expression< Number, VariableName >& e1, \n             const linear_expression< Number, VariableName >& e2) {\n    return linear_constraint< Number, VariableName >\n        (e1 - e2, linear_constraint< Number, VariableName >::INEQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator>=(const linear_expression< Number, VariableName > &e, Number n) {\n    return linear_constraint< Number, VariableName >\n        (n - e, linear_constraint< Number, VariableName >::INEQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator>=(const linear_expression< Number, VariableName > &e, int n) {\n    return linear_constraint< Number, VariableName >\n        (n - e, linear_constraint< Number, VariableName >::INEQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator>=(Number n, const linear_expression< Number, VariableName > &e) {\n    return linear_constraint< Number, VariableName >\n        (e - n, linear_constraint< Number, VariableName >::INEQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator>=(int n, const linear_expression< Number, VariableName > &e) {\n    return linear_constraint< Number, VariableName >\n        (e - n, linear_constraint< Number, VariableName >::INEQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator>=(const linear_expression< Number, VariableName > &e, \n             variable< Number, VariableName > x) {\n    return linear_constraint< Number, VariableName >\n        (x - e, linear_constraint< Number, VariableName >::INEQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator>=(variable< Number, VariableName > x,\n             const linear_expression< Number, VariableName > &e) {\n    return linear_constraint< Number, VariableName >\n        (e - x, linear_constraint< Number, VariableName >::INEQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator>=(variable< Number, VariableName > x, Number n) {\n    return linear_constraint< Number, VariableName >\n        (n - x, linear_constraint< Number, VariableName >::INEQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator>=(variable< Number, VariableName > x, int n) {\n    return linear_constraint< Number, VariableName >\n        (n - x, linear_constraint< Number, VariableName >::INEQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator>=(Number n, variable< Number, VariableName > x) {\n    return linear_constraint< Number, VariableName >\n        (x - n, linear_constraint< Number, VariableName >::INEQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator>=(int n, variable< Number, VariableName > x) {\n    return linear_constraint< Number, VariableName >\n        (x - n, linear_constraint< Number, VariableName >::INEQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator>=(variable< Number, VariableName > x, \n             variable< Number, VariableName > y) {\n    return linear_constraint< Number, VariableName >\n        (y - x, linear_constraint< Number, VariableName >::INEQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator>=(const linear_expression< Number, VariableName > &e1, \n             const linear_expression< Number, VariableName > &e2) {\n    return linear_constraint< Number, VariableName >\n        (e2 - e1, linear_constraint< Number, VariableName >::INEQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator==(const linear_expression< Number, VariableName > &e, Number n) {\n    return linear_constraint< Number, VariableName >\n        (e - n, linear_constraint< Number, VariableName >::EQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator==(const linear_expression< Number, VariableName > &e, int n) {\n    return linear_constraint< Number, VariableName >\n        (e - n, linear_constraint< Number, VariableName >::EQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator==(Number n, const linear_expression< Number, VariableName > &e) {\n    return linear_constraint< Number, VariableName >\n        (e - n, linear_constraint< Number, VariableName >::EQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator==(int n, const linear_expression< Number, VariableName > &e) {\n    return linear_constraint< Number, VariableName >\n        (e - n, linear_constraint< Number, VariableName >::EQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator==(const linear_expression< Number, VariableName > &e, \n             variable< Number, VariableName > x) {\n    return linear_constraint< Number, VariableName >\n        (e - x, linear_constraint< Number, VariableName >::EQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator==(variable< Number, VariableName > x, \n             const linear_expression< Number, VariableName > &e) {\n    return linear_constraint< Number, VariableName >\n        (e - x, linear_constraint< Number, VariableName >::EQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator==(variable< Number, VariableName > x, Number n) {\n    return linear_constraint< Number, VariableName >\n        (x - n, linear_constraint< Number, VariableName >::EQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator==(variable< Number, VariableName > x, int n) {\n    return linear_constraint< Number, VariableName >\n        (x - n, linear_constraint< Number, VariableName >::EQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator==(Number n, variable< Number, VariableName > x) {\n    return linear_constraint< Number, VariableName >\n        (x - n, linear_constraint< Number, VariableName >::EQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator==(int n, variable< Number, VariableName > x) {\n    return linear_constraint< Number, VariableName >\n        (x - n, linear_constraint< Number, VariableName >::EQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator==(variable< Number, VariableName > x, \n             variable< Number, VariableName > y) {\n    return linear_constraint< Number, VariableName >\n        (x - y, linear_constraint< Number, VariableName >::EQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator==(const linear_expression< Number, VariableName > &e1, \n             const linear_expression< Number, VariableName > &e2) {\n    return linear_constraint< Number, VariableName >\n        (e1 - e2, linear_constraint< Number, VariableName >::EQUALITY);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator!=(const linear_expression< Number, VariableName > &e, Number n) {\n    return linear_constraint< Number, VariableName >\n        (e - n, linear_constraint< Number, VariableName >::DISEQUATION);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator!=(const linear_expression< Number, VariableName > &e, int n) {\n    return linear_constraint< Number, VariableName >\n        (e - n, linear_constraint< Number, VariableName >::DISEQUATION);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator!=(Number n, const linear_expression< Number, VariableName > &e) {\n    return linear_constraint< Number, VariableName >\n        (e - n, linear_constraint< Number, VariableName >::DISEQUATION);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator!=(int n, const linear_expression< Number, VariableName > &e) {\n    return linear_constraint< Number, VariableName >\n        (e - n, linear_constraint< Number, VariableName >::DISEQUATION);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator!=(const linear_expression< Number, VariableName > &e, \n             variable< Number, VariableName > x) {\n    return linear_constraint< Number, VariableName >\n        (e - x, linear_constraint< Number, VariableName >::DISEQUATION);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator!=(variable< Number, VariableName > x, \n             const linear_expression< Number, VariableName > &e) {\n    return linear_constraint< Number, VariableName >\n        (e - x, linear_constraint< Number, VariableName >::DISEQUATION);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator!=(variable< Number, VariableName > x, Number n) {\n    return linear_constraint< Number, VariableName >\n        (x - n, linear_constraint< Number, VariableName >::DISEQUATION);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator!=(variable< Number, VariableName > x, int n) {\n    return linear_constraint< Number, VariableName >\n        (x - n, linear_constraint< Number, VariableName >::DISEQUATION);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator!=(Number n, variable< Number, VariableName > x) {\n    return linear_constraint< Number, VariableName >\n        (x - n, linear_constraint< Number, VariableName >::DISEQUATION);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator!=(int n, variable< Number, VariableName > x) {\n    return linear_constraint< Number, VariableName >\n        (x - n, linear_constraint< Number, VariableName >::DISEQUATION);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator!=(variable< Number, VariableName > x, \n             variable< Number, VariableName > y) {\n    return linear_constraint< Number, VariableName >\n        (x - y, linear_constraint< Number, VariableName >::DISEQUATION);\n  }\n\n  template< typename Number, typename VariableName >\n  inline linear_constraint< Number, VariableName > \n  operator!=(const linear_expression< Number, VariableName > &e1, \n             const linear_expression< Number, VariableName > &e2) {\n    return linear_constraint< Number, VariableName >\n        (e1 - e2, linear_constraint< Number, VariableName >::DISEQUATION);\n  }\n\n  template< typename Number, typename VariableName >\n  class linear_constraint_system: public writeable {\n\n  public:\n    typedef Number number_t;\n    typedef VariableName varname_t;\n    typedef linear_constraint< Number, VariableName > linear_constraint_t;\n    typedef linear_constraint_system< Number, VariableName > linear_constraint_system_t;\n    typedef variable< Number, VariableName > variable_t;\n    typedef patricia_tree_set< variable_t > variable_set_t;\n\n  private:\n    typedef std::vector< linear_constraint_t > cst_collection_t;\n\n  public:\n    typedef typename cst_collection_t::const_iterator iterator;\n\n  private:\n    cst_collection_t _csts;\n\n  public:\n    linear_constraint_system() { }\n\n    linear_constraint_system(const linear_constraint_t &cst) {\n      _csts.push_back(cst);\n    }\n\n    linear_constraint_system(const linear_constraint_system_t &o)\n        : _csts (o._csts) { }\n\n    linear_constraint_system(linear_constraint_system_t &&o)\n        : _csts (std::move(o._csts)) { }\n\n    linear_constraint_system_t& \n    operator+=(const linear_constraint_t &cst) {\n      this->_csts.push_back(cst);\n      return *this;\n    }\n\n    linear_constraint_system_t& \n    operator+=(const linear_constraint_system_t &s) {\n      for (auto c: s)\n        this->_csts.push_back(c);\n      return *this;\n    }\n\n    linear_constraint_system_t \n    operator+(const linear_constraint_system_t &s) const {\n      linear_constraint_system_t r;\n      r.operator+=(s);\n      r.operator+=(*this);\n      return r;\n    }\n\n    iterator begin() const { return _csts.begin(); }\n\n    iterator end() const { return _csts.end(); }\n\n    variable_set_t variables() const {\n      variable_set_t variables;\n      for (auto c: *this)\n        variables |= c.variables();\n      return variables;\n    }\n\n    // TODO: expensive linear operation.\n    // XXX: We can keep track of whether the system is false in an\n    // incremental manner.\n    bool is_false () const {\n      if (_csts.empty ())\n\treturn false; // empty is considered true\n      \n      for (auto it = this->begin(); it != this->end();) {\n        auto c = *it;\n\tif (!c.is_contradiction ()) {\n\t  return false;\n\t}\n      }\n      return true; // all constraints are false\n    }\n    \n    std::size_t size() const { return _csts.size(); }\n        \n    void write(crab::crab_os& o) {\n      o << \"{\";\n      for (iterator it = this->begin(); it != this->end();) {\n        auto c = *it;\n        o << c;\n        ++it;\n        if (it != end()) {\n        o << \"; \";\n        }\n      }\n      o << \"}\";\n    }\n\n  }; // class linear_constraint_system\n\n\n  // This class contains a disjunction of linear constraints\n  template< typename Number, typename VariableName >\n  class disjunctive_linear_constraint_system: public writeable {\n\n  public:\n    typedef Number number_t;\n    typedef VariableName varname_t;\n    typedef linear_constraint<Number,VariableName> linear_constraint_t;\n    typedef linear_constraint_system<Number,VariableName> linear_constraint_system_t;\n    typedef disjunctive_linear_constraint_system<Number,VariableName> this_type;\n    \n  private:\n    typedef std::vector<linear_constraint_system_t> cst_collection_t;\n    cst_collection_t _csts;\n    bool _is_false;\n\n  public:\n    typedef typename cst_collection_t::const_iterator iterator;\n\n    disjunctive_linear_constraint_system()\n      : _is_false (false) {}\n\n    disjunctive_linear_constraint_system(const linear_constraint_system_t &cst)\n      : _is_false (false) {\n      if (cst.is_false ()) {\n\t_is_false = true;\n      } else {\n\t_csts.push_back(cst);\n      }\n    }\n\n    disjunctive_linear_constraint_system(const this_type &o)\n        : _csts (o._csts) { }\n\n    disjunctive_linear_constraint_system(this_type &&o)\n        : _csts (std::move(o._csts)) { }\n\n    bool is_false () const {\n      return _is_false;\n    }\n    \n    this_type& operator+=(const linear_constraint_system_t &cst) {\n      if (_csts.empty () && cst.is_false ()) {\n\t_is_false = true;\n      } else {\n\t_csts.push_back(cst);\n\t_is_false = false;\n      }\n      return *this;\n    }\n\n    this_type& operator+=(const this_type &s) {\n      if (this->is_false ()) {\n\treturn s;\n      } else if (s.is_false ()) {\n\treturn *this;\n      } else { \n\tfor (auto c: s) {\n\t  _csts.push_back(c);\n\t}\n\treturn *this;\n      }\n    }\n\n    this_type operator+(const this_type &s) const {\n      this_type r;\n      r.operator+=(s);\n      r.operator+=(*this);\n      return r;\n    }\n\n    // To enumerate all the conjunctions\n    iterator begin() const {      \n      if (is_false ())\n\tCRAB_ERROR(\"Disjunctive Linear constraint: trying to call begin() when false\");\n      return _csts.begin();\n    }\n\n    iterator end() const {\n      if (is_false ())\n\tCRAB_ERROR(\"Disjunctive Linear constraint: trying to call end() when false\");      \n      return _csts.end();\n    }\n\n    // Return the number of conjunctions\n    std::size_t size() const { return _csts.size(); }\n        \n    void write(crab::crab_os& o) {\n      if (is_false ()) {\n\to << \"_|_\";\n      } else if (_csts.empty ()) {\n\to << \"{}\";\n      } else if (size () == 1) {\n\to << _csts[0];\n      } else {\n\tassert (size () > 1);\n\tfor (iterator it = this->begin(); it != this->end();) {\n\t  auto c = *it;\n\t  o << c;\n\t  ++it;\n\t  if (it != end()) {\n\t    o << \" or \\n\";\n\t  }\n\t}\n      }\n    }\n  }; \n  \n} // namespace ikos\n\n#endif // IKOS_LINEAR_CONSTRAINTS_HPP\n", "meta": {"hexsha": "e717c0fea4507f0e237104a25cfca123bd5bdfc0", "size": 41352, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/linear_constraints.hpp", "max_stars_repo_name": "satbekmyrza/crab", "max_stars_repo_head_hexsha": "0f71d09f4fa872d6b02f225963c1a960977578f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/crab/domains/linear_constraints.hpp", "max_issues_repo_name": "satbekmyrza/crab", "max_issues_repo_head_hexsha": "0f71d09f4fa872d6b02f225963c1a960977578f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/crab/domains/linear_constraints.hpp", "max_forks_repo_name": "satbekmyrza/crab", "max_forks_repo_head_hexsha": "0f71d09f4fa872d6b02f225963c1a960977578f4", "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.9507389163, "max_line_length": 90, "alphanum_fraction": 0.6559053976, "num_tokens": 9829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819591324418, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.279485141525366}}
{"text": "/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center.\n\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http://www.mitk.org for details.\n\n===================================================================*/\n\n#include \"mitkDiffusionFunctionCollection.h\"\n#include \"mitkNumericTypes.h\"\n\n#include <boost/math/special_functions/legendre.hpp>\n#include <boost/math/special_functions/spherical_harmonic.hpp>\n#include <boost/version.hpp>\n#include <boost/algorithm/string.hpp>\n#include <itkPointShell.h>\n#include \"itkVectorContainer.h\"\n#include \"vnl/vnl_vector.h\"\n#include <vtkBox.h>\n#include <vtkMath.h>\n#include <itksys/SystemTools.hxx>\n#include <itkShToOdfImageFilter.h>\n#include <itkTensorImageToOdfImageFilter.h>\n\n// Intersect a finite line (with end points p0 and p1) with all of the\n// cells of a vtkImageData\nstd::vector< std::pair< itk::Index<3>, double > > mitk::imv::IntersectImage(const itk::Vector<double,3>& spacing, itk::Index<3>& si, itk::Index<3>& ei, itk::ContinuousIndex<float, 3>& sf, itk::ContinuousIndex<float, 3>& ef)\n{\n  std::vector< std::pair< itk::Index<3>, double > > out;\n  if (si == ei)\n  {\n    double d[3];\n    for (int i=0; i<3; ++i)\n      d[i] = static_cast<double>(sf[i]-ef[i])*spacing[i];\n    double len = std::sqrt( d[0]*d[0] + d[1]*d[1] + d[2]*d[2] );\n    out.push_back(  std::pair< itk::Index<3>, double >(si, len) );\n    return out;\n  }\n\n  double bounds[6];\n\n  double entrancePoint[3];\n  double exitPoint[3];\n\n  double startPoint[3];\n  double endPoint[3];\n\n  double t0, t1;\n  for (unsigned int i=0; i<3; ++i)\n  {\n    startPoint[i] = static_cast<double>(sf[i]);\n    endPoint[i] = static_cast<double>(ef[i]);\n\n    if (si[i]>ei[i])\n    {\n      auto t = si[i];\n      si[i] = ei[i];\n      ei[i] = t;\n    }\n  }\n\n  for (auto x = si[0]; x<=ei[0]; ++x)\n    for (auto y = si[1]; y<=ei[1]; ++y)\n      for (auto z = si[2]; z<=ei[2]; ++z)\n      {\n        bounds[0] = static_cast<double>(x) - 0.5;\n        bounds[1] = static_cast<double>(x) + 0.5;\n        bounds[2] = static_cast<double>(y) - 0.5;\n        bounds[3] = static_cast<double>(y) + 0.5;\n        bounds[4] = static_cast<double>(z) - 0.5;\n        bounds[5] = static_cast<double>(z) + 0.5;\n\n        int entryPlane;\n        int exitPlane;\n        int hit = vtkBox::IntersectWithLine(bounds,\n                                            startPoint,\n                                            endPoint,\n                                            t0,\n                                            t1,\n                                            entrancePoint,\n                                            exitPoint,\n                                            entryPlane,\n                                            exitPlane);\n        if (hit)\n        {\n          if (entryPlane>=0 && exitPlane>=0)\n          {\n            double d[3];\n            for (int i=0; i<3; ++i)\n              d[i] = (exitPoint[i] - entrancePoint[i])*spacing[i];\n            double len = std::sqrt( d[0]*d[0] + d[1]*d[1] + d[2]*d[2] );\n\n            itk::Index<3> idx; idx[0] = x; idx[1] = y; idx[2] = z;\n            out.push_back(  std::pair< itk::Index<3>, double >(idx, len) );\n          }\n          else if (entryPlane>=0)\n          {\n            double d[3];\n            for (int i=0; i<3; ++i)\n              d[i] = (static_cast<double>(ef[i]) - entrancePoint[i])*spacing[i];\n            double len = std::sqrt( d[0]*d[0] + d[1]*d[1] + d[2]*d[2] );\n\n            itk::Index<3> idx; idx[0] = x; idx[1] = y; idx[2] = z;\n            out.push_back(  std::pair< itk::Index<3>, double >(idx, len) );\n          }\n          else if (exitPlane>=0)\n          {\n            double d[3];\n            for (int i=0; i<3; ++i)\n              d[i] = (exitPoint[i]-static_cast<double>(sf[i]))*spacing[i];\n            double len = std::sqrt( d[0]*d[0] + d[1]*d[1] + d[2]*d[2] );\n\n            itk::Index<3> idx; idx[0] = x; idx[1] = y; idx[2] = z;\n            out.push_back(  std::pair< itk::Index<3>, double >(idx, len) );\n          }\n        }\n      }\n  return out;\n}\n\n//------------------------- SH-function ------------------------------------\n\ndouble mitk::sh::factorial(int number) {\n  if(number <= 1) return 1;\n  double result = 1.0;\n  for(int i=1; i<=number; i++)\n    result *= i;\n  return result;\n}\n\nvoid mitk::sh::Cart2Sph(double x, double y, double z, double *spherical)\n{\n  double phi, th, rad;\n  rad = sqrt(x*x+y*y+z*z);\n  if( rad < mitk::eps )\n  {\n    th = itk::Math::pi/2;\n    phi = itk::Math::pi/2;\n  }\n  else\n  {\n    th = acos(z/rad);\n    phi = atan2(y, x);\n  }\n  spherical[0] = phi;\n  spherical[1] = th;\n  spherical[2] = rad;\n}\n\nvnl_vector_fixed<double, 3> mitk::sh::Sph2Cart(const double& theta, const double& phi, const double& rad)\n{\n  vnl_vector_fixed<double, 3> dir;\n  dir[0] = rad * sin(theta) * cos(phi);\n  dir[1] = rad * sin(theta) * sin(phi);\n  dir[2] = rad * cos(theta);\n  return dir;\n}\n\ndouble mitk::sh::legendre0(int l)\n{\n  if( l%2 != 0 )\n  {\n    return 0;\n  }\n  else\n  {\n    double prod1 = 1.0;\n    for(int i=1;i<l;i+=2) prod1 *= i;\n    double prod2 = 1.0;\n    for(int i=2;i<=l;i+=2) prod2 *= i;\n    return pow(-1.0,l/2.0)*(prod1/prod2);\n  }\n}\n\ndouble mitk::sh::Yj(int m, int k, float theta, float phi, bool mrtrix)\n{\n  if (!mrtrix)\n  {\n    if (m<0)\n      return sqrt(2.0)*static_cast<double>(::boost::math::spherical_harmonic_r(static_cast<unsigned int>(k), -m, theta, phi));\n    else if (m==0)\n      return static_cast<double>(::boost::math::spherical_harmonic_r(static_cast<unsigned int>(k), m, theta, phi));\n    else\n      return pow(-1.0,m)*sqrt(2.0)*static_cast<double>(::boost::math::spherical_harmonic_i(static_cast<unsigned int>(k), m, theta, phi));\n  }\n  else\n  {\n    double plm = static_cast<double>(::boost::math::legendre_p<float>(k,abs(m),-cos(theta)));\n    double mag = sqrt((2.0*k+1.0)/(4.0*itk::Math::pi)*::boost::math::factorial<double>(k-abs(m))/::boost::math::factorial<double>(k+abs(m)))*plm;\n    if (m>0)\n      return mag*static_cast<double>(cos(m*phi));\n    else if (m==0)\n      return mag;\n    else\n      return mag*static_cast<double>(sin(-m*phi));\n  }\n\n  return 0;\n}\n\nmitk::OdfImage::ItkOdfImageType::Pointer mitk::convert::GetItkOdfFromShImage(mitk::Image::Pointer mitkImage)\n{\n  mitk::ShImage::Pointer mitkShImage = dynamic_cast<mitk::ShImage*>(mitkImage.GetPointer());\n  if (mitkShImage.IsNull())\n    mitkThrow() << \"Input image is not a SH image!\";\n  mitk::OdfImage::ItkOdfImageType::Pointer output;\n  switch (mitkShImage->ShOrder())\n  {\n  case 2:\n  {\n    typedef itk::ShToOdfImageFilter< float, 2 > ShConverterType;\n    typename ShConverterType::InputImageType::Pointer itkvol = ShConverterType::InputImageType::New();\n    mitk::CastToItkImage(mitkImage, itkvol);\n    typename ShConverterType::Pointer converter = ShConverterType::New();\n    converter->SetInput(itkvol);\n    converter->SetToolkit(mitkShImage->GetShConvention());\n    converter->Update();\n    output = converter->GetOutput();\n    break;\n  }\n  case 4:\n  {\n    typedef itk::ShToOdfImageFilter< float, 4 > ShConverterType;\n    typename ShConverterType::InputImageType::Pointer itkvol = ShConverterType::InputImageType::New();\n    mitk::CastToItkImage(mitkImage, itkvol);\n    typename ShConverterType::Pointer converter = ShConverterType::New();\n    converter->SetInput(itkvol);\n    converter->SetToolkit(mitkShImage->GetShConvention());\n    converter->Update();\n    output = converter->GetOutput();\n    break;\n  }\n  case 6:\n  {\n    typedef itk::ShToOdfImageFilter< float, 6 > ShConverterType;\n    typename ShConverterType::InputImageType::Pointer itkvol = ShConverterType::InputImageType::New();\n    mitk::CastToItkImage(mitkImage, itkvol);\n    typename ShConverterType::Pointer converter = ShConverterType::New();\n    converter->SetInput(itkvol);\n    converter->SetToolkit(mitkShImage->GetShConvention());\n    converter->Update();\n    output = converter->GetOutput();\n    break;\n  }\n  case 8:\n  {\n    typedef itk::ShToOdfImageFilter< float, 8 > ShConverterType;\n    typename ShConverterType::InputImageType::Pointer itkvol = ShConverterType::InputImageType::New();\n    mitk::CastToItkImage(mitkImage, itkvol);\n    typename ShConverterType::Pointer converter = ShConverterType::New();\n    converter->SetInput(itkvol);\n    converter->SetToolkit(mitkShImage->GetShConvention());\n    converter->Update();\n    output = converter->GetOutput();\n    break;\n  }\n  case 10:\n  {\n    typedef itk::ShToOdfImageFilter< float, 10 > ShConverterType;\n    typename ShConverterType::InputImageType::Pointer itkvol = ShConverterType::InputImageType::New();\n    mitk::CastToItkImage(mitkImage, itkvol);\n    typename ShConverterType::Pointer converter = ShConverterType::New();\n    converter->SetInput(itkvol);\n    converter->SetToolkit(mitkShImage->GetShConvention());\n    converter->Update();\n    output = converter->GetOutput();\n    break;\n  }\n  case 12:\n  {\n    typedef itk::ShToOdfImageFilter< float, 12 > ShConverterType;\n    typename ShConverterType::InputImageType::Pointer itkvol = ShConverterType::InputImageType::New();\n    mitk::CastToItkImage(mitkImage, itkvol);\n    typename ShConverterType::Pointer converter = ShConverterType::New();\n    converter->SetInput(itkvol);\n    converter->SetToolkit(mitkShImage->GetShConvention());\n    converter->Update();\n    output = converter->GetOutput();\n    break;\n  }\n  default:\n    mitkThrow() << \"SH orders higher than 12 are not supported!\";\n  }\n\n  return output;\n}\n\nmitk::OdfImage::Pointer mitk::convert::GetOdfFromShImage(mitk::Image::Pointer mitkImage)\n{\n  mitk::OdfImage::Pointer image = mitk::OdfImage::New();\n  auto img = GetItkOdfFromShImage(mitkImage);\n  image->InitializeByItk( img.GetPointer() );\n  image->SetVolume( img->GetBufferPointer() );\n  return image;\n}\n\nmitk::OdfImage::ItkOdfImageType::Pointer mitk::convert::GetItkOdfFromTensorImage(mitk::Image::Pointer mitkImage)\n{\n  typedef itk::TensorImageToOdfImageFilter< float, float > FilterType;\n  FilterType::Pointer filter = FilterType::New();\n  filter->SetInput( GetItkTensorFromTensorImage(mitkImage) );\n  filter->Update();\n  return filter->GetOutput();\n}\n\nmitk::TensorImage::ItkTensorImageType::Pointer mitk::convert::GetItkTensorFromTensorImage(mitk::Image::Pointer mitkImage)\n{\n  typedef mitk::ImageToItk< mitk::TensorImage::ItkTensorImageType > CasterType;\n  CasterType::Pointer caster = CasterType::New();\n  caster->SetInput(mitkImage);\n  caster->Update();\n  return caster->GetOutput();\n}\n\nmitk::PeakImage::ItkPeakImageType::Pointer mitk::convert::GetItkPeakFromPeakImage(mitk::Image::Pointer mitkImage)\n{\n  typedef mitk::ImageToItk< mitk::PeakImage::ItkPeakImageType > CasterType;\n  CasterType::Pointer caster = CasterType::New();\n  caster->SetInput(mitkImage);\n  caster->SetCopyMemFlag(true);\n  caster->Update();\n  return caster->GetOutput();\n}\n\nmitk::OdfImage::Pointer mitk::convert::GetOdfFromTensorImage(mitk::Image::Pointer mitkImage)\n{\n  mitk::OdfImage::Pointer image = mitk::OdfImage::New();\n  auto img = GetItkOdfFromTensorImage(mitkImage);\n  image->InitializeByItk( img.GetPointer() );\n  image->SetVolume( img->GetBufferPointer() );\n  return image;\n}\n\nmitk::OdfImage::ItkOdfImageType::Pointer mitk::convert::GetItkOdfFromOdfImage(mitk::Image::Pointer mitkImage)\n{\n  typedef mitk::ImageToItk< mitk::OdfImage::ItkOdfImageType > CasterType;\n  CasterType::Pointer caster = CasterType::New();\n  caster->SetInput(mitkImage);\n  caster->Update();\n  return caster->GetOutput();\n}\n\nvnl_matrix<float> mitk::sh::CalcShBasisForDirections(unsigned int sh_order, vnl_matrix<double> U, bool mrtrix)\n{\n  vnl_matrix<float> sh_basis  = vnl_matrix<float>(U.cols(), (sh_order*sh_order + sh_order + 2)/2 + sh_order );\n  for(unsigned int i=0; i<U.cols(); i++)\n  {\n    double x = U(0,i);\n    double y = U(1,i);\n    double z = U(2,i);\n    double spherical[3];\n    mitk::sh::Cart2Sph(x,y,z,spherical);\n    U(0,i) = spherical[0];\n    U(1,i) = spherical[1];\n    U(2,i) = spherical[2];\n  }\n\n  for(unsigned int i=0; i<U.cols(); i++)\n  {\n    for(int k=0; k<=static_cast<int>(sh_order); k+=2)\n    {\n      for(int m=-k; m<=k; m++)\n      {\n        int j = (k*k + k + 2)/2 + m - 1;\n        double phi = U(0,i);\n        double th = U(1,i);\n        sh_basis(i,j) = mitk::sh::Yj(m,k,th,phi, mrtrix);\n      }\n    }\n  }\n\n  return sh_basis;\n}\n\nunsigned int mitk::sh::ShOrder(int num_coeffs)\n{\n  int c=3, d=2-2*num_coeffs;\n  int D = c*c-4*d;\n  if (D>0)\n  {\n    int s = (-c+static_cast<int>(sqrt(D)))/2;\n    if (s<0)\n      s = (-c-static_cast<int>(sqrt(D)))/2;\n    return static_cast<unsigned int>(s);\n  }\n  else if (D==0)\n    return static_cast<unsigned int>(-c/2);\n  return 0;\n}\n\nfloat mitk::sh::GetValue(const vnl_vector<float> &coefficients, const int &sh_order, const double theta, const double phi, const bool mrtrix)\n{\n  float val = 0;\n  for(int k=0; k<=sh_order; k+=2)\n  {\n    for(int m=-k; m<=k; m++)\n    {\n      unsigned int j = static_cast<unsigned int>((k*k + k + 2)/2 + m - 1);\n      val += coefficients[j] * mitk::sh::Yj(m, k, theta, phi, mrtrix);\n    }\n  }\n\n  return val;\n}\n\nfloat mitk::sh::GetValue(const vnl_vector<float> &coefficients, const int &sh_order, const vnl_vector_fixed<double, 3> &dir, const bool mrtrix)\n{\n  double spherical[3];\n  mitk::sh::Cart2Sph(dir[0], dir[1], dir[2], spherical);\n\n  float val = 0;\n  for(int k=0; k<=sh_order; k+=2)\n  {\n    for(int m=-k; m<=k; m++)\n    {\n      int j = (k*k + k + 2)/2 + m - 1;\n      val += coefficients[j] * mitk::sh::Yj(m, k, spherical[1], spherical[0], mrtrix);\n    }\n  }\n\n  return val;\n}\n\n//------------------------- gradients-function ------------------------------------\n\n\nmitk::gradients::GradientDirectionContainerType::ConstPointer mitk::gradients::ReadBvalsBvecs(std::string bvals_file, std::string bvecs_file, double& reference_bval)\n{\n  mitk::gradients::GradientDirectionContainerType::Pointer directioncontainer = mitk::gradients::GradientDirectionContainerType::New();\n\n  std::vector<float> bvec_entries;\n  if (!itksys::SystemTools::FileExists(bvecs_file))\n    mitkThrow() << \"bvecs file not existing: \" << bvecs_file;\n  else\n  {\n    std::string line;\n    std::ifstream myfile (bvecs_file.c_str());\n    if (myfile.is_open())\n    {\n      while (std::getline(myfile, line))\n      {\n        std::vector<std::string> strs;\n        boost::split(strs,line,boost::is_any_of(\"\\t \\n\"));\n        for (auto token : strs)\n        {\n          if (!token.empty())\n          {\n            try\n            {\n              bvec_entries.push_back(boost::lexical_cast<float>(token));\n            }\n            catch(...)\n            {\n              mitkThrow() << \"Encountered invalid bvecs file entry >\" << token << \"<\";\n            }\n          }\n        }\n      }\n      myfile.close();\n    }\n    else\n    {\n      mitkThrow() << \"bvecs file could not be opened: \" << bvals_file;\n    }\n  }\n\n  reference_bval = -1;\n  std::vector<float> bval_entries;\n  if (!itksys::SystemTools::FileExists(bvals_file))\n    mitkThrow() << \"bvals file not existing: \" << bvals_file;\n  else\n  {\n    std::string line;\n    std::ifstream myfile (bvals_file.c_str());\n    if (myfile.is_open())\n    {\n      while (std::getline(myfile, line))\n      {\n        std::vector<std::string> strs;\n        boost::split(strs,line,boost::is_any_of(\"\\t \\n\"));\n        for (auto token : strs)\n        {\n          if (!token.empty())\n          {\n            try {\n              bval_entries.push_back(boost::lexical_cast<float>(token));\n              if (bval_entries.back()>reference_bval)\n                reference_bval = bval_entries.back();\n            }\n            catch(...)\n            {\n              mitkThrow() << \"Encountered invalid bvals file entry >\" << token << \"<\";\n            }\n          }\n        }\n      }\n      myfile.close();\n    }\n    else\n    {\n      mitkThrow() << \"bvals file could not be opened: \" << bvals_file;\n    }\n  }\n\n  for(unsigned int i=0; i<bval_entries.size(); i++)\n  {\n    double b_val = bval_entries.at(i);\n\n    mitk::gradients::GradientDirectionType vec;\n    vec[0] = bvec_entries.at(i);\n    vec[1] = bvec_entries.at(i+bval_entries.size());\n    vec[2] = bvec_entries.at(i+2*bval_entries.size());\n\n    // Adjust the vector length to encode gradient strength\n    if (reference_bval>0)\n    {\n      double factor = b_val/reference_bval;\n      if(vec.magnitude() > 0)\n      {\n        vec.normalize();\n        vec[0] = sqrt(factor)*vec[0];\n        vec[1] = sqrt(factor)*vec[1];\n        vec[2] = sqrt(factor)*vec[2];\n      }\n    }\n\n    directioncontainer->InsertElement(i,vec);\n  }\n\n  return GradientDirectionContainerType::ConstPointer(directioncontainer);\n}\n\nvoid mitk::gradients::WriteBvalsBvecs(std::string bvals_file, std::string bvecs_file, GradientDirectionContainerType::ConstPointer gradients, double reference_bval)\n{\n  std::ofstream myfile;\n  myfile.open (bvals_file.c_str());\n  for(unsigned int i=0; i<gradients->Size(); i++)\n  {\n    double twonorm = gradients->ElementAt(i).two_norm();\n    myfile << std::round(reference_bval*twonorm*twonorm) << \" \";\n  }\n  myfile.close();\n\n  std::ofstream myfile2;\n  myfile2.open (bvecs_file.c_str());\n  for(int j=0; j<3; j++)\n  {\n    for(unsigned int i=0; i<gradients->Size(); i++)\n    {\n      GradientDirectionType direction = gradients->ElementAt(i);\n      direction.normalize();\n      myfile2 << direction.get(j) << \" \";\n    }\n    myfile2 << std::endl;\n  }\n}\n\nstd::vector<unsigned int> mitk::gradients::GetAllUniqueDirections(const BValueMap & refBValueMap, GradientDirectionContainerType::ConstPointer refGradientsContainer )\n{\n\n  IndiciesVector directioncontainer;\n  auto mapIterator = refBValueMap.begin();\n\n  if(refBValueMap.find(0) != refBValueMap.end() && refBValueMap.size() > 1)\n    mapIterator++; //skip bzero Values\n\n  for( ; mapIterator != refBValueMap.end(); mapIterator++){\n\n    IndiciesVector currentShell = mapIterator->second;\n\n    while(currentShell.size()>0)\n    {\n      unsigned int wntIndex = currentShell.back();\n      currentShell.pop_back();\n\n      auto containerIt = directioncontainer.begin();\n      bool directionExist = false;\n      while(containerIt != directioncontainer.end())\n      {\n        if (fabs(dot_product(refGradientsContainer->ElementAt(*containerIt), refGradientsContainer->ElementAt(wntIndex)))  > 0.9998)\n        {\n          directionExist = true;\n          break;\n        }\n        containerIt++;\n      }\n      if(!directionExist)\n      {\n        directioncontainer.push_back(wntIndex);\n      }\n    }\n  }\n\n  return directioncontainer;\n}\n\n\nbool mitk::gradients::CheckForDifferingShellDirections(const BValueMap & refBValueMap, GradientDirectionContainerType::ConstPointer refGradientsContainer)\n{\n  auto mapIterator = refBValueMap.begin();\n\n  if(refBValueMap.find(0) != refBValueMap.end() && refBValueMap.size() > 1)\n    mapIterator++; //skip bzero Values\n\n  for( ; mapIterator != refBValueMap.end(); mapIterator++){\n\n    auto mapIterator_2 = refBValueMap.begin();\n    if(refBValueMap.find(0) != refBValueMap.end() && refBValueMap.size() > 1)\n      mapIterator_2++; //skip bzero Values\n\n    for( ; mapIterator_2 != refBValueMap.end(); mapIterator_2++){\n\n      if(mapIterator_2 == mapIterator) continue;\n\n      IndiciesVector currentShell = mapIterator->second;\n      IndiciesVector testShell = mapIterator_2->second;\n      for (unsigned int i = 0; i< currentShell.size(); i++)\n        if (fabs(dot_product(refGradientsContainer->ElementAt(currentShell[i]), refGradientsContainer->ElementAt(testShell[i])))  <= 0.9998) { return true; }\n\n    }\n  }\n  return false;\n}\n\nvnl_matrix<double> mitk::gradients::ComputeSphericalFromCartesian(const IndiciesVector & refShell, const GradientDirectionContainerType * refGradientsContainer)\n{\n\n  vnl_matrix<double> Q(3, refShell.size());\n  Q.fill(0.0);\n\n  for(unsigned int i = 0; i < refShell.size(); i++)\n  {\n    GradientDirectionType dir = refGradientsContainer->ElementAt(refShell[i]);\n    double x = dir.normalize().get(0);\n    double y = dir.normalize().get(1);\n    double z = dir.normalize().get(2);\n    double cart[3];\n    mitk::sh::Cart2Sph(x,y,z,cart);\n    Q(0,i) = cart[0];\n    Q(1,i) = cart[1];\n    Q(2,i) = cart[2];\n  }\n  return Q;\n}\n\nvnl_matrix<double> mitk::gradients::ComputeSphericalHarmonicsBasis(const vnl_matrix<double> & QBallReference, const unsigned int & LOrder)\n{\n  vnl_matrix<double> SHBasisOutput(QBallReference.cols(), (LOrder+1)*(LOrder+2)*0.5);\n  SHBasisOutput.fill(0.0);\n  for(unsigned int i=0; i<SHBasisOutput.rows(); i++)\n    for(int k = 0; k <= (int)LOrder; k += 2)\n      for(int m =- k; m <= k; m++)\n      {\n        int j = ( k * k + k + 2 ) / 2.0 + m - 1;\n        double phi = QBallReference(0,i);\n        double th = QBallReference(1,i);\n        double val = mitk::sh::Yj(m,k,th,phi);\n        SHBasisOutput(i,j) = val;\n      }\n  return SHBasisOutput;\n}\n\nmitk::gradients::GradientDirectionContainerType::Pointer mitk::gradients::CreateNormalizedUniqueGradientDirectionContainer(const mitk::gradients::BValueMap & bValueMap,\n                                                                                                                           const GradientDirectionContainerType *origninalGradentcontainer)\n{\n  mitk::gradients::GradientDirectionContainerType::Pointer directioncontainer = mitk::gradients::GradientDirectionContainerType::New();\n  auto mapIterator = bValueMap.begin();\n\n  if(bValueMap.find(0) != bValueMap.end() && bValueMap.size() > 1){\n    mapIterator++; //skip bzero Values\n    vnl_vector_fixed<double, 3> vec;\n    vec.fill(0.0);\n    directioncontainer->push_back(vec);\n  }\n\n  for( ; mapIterator != bValueMap.end(); mapIterator++){\n\n    IndiciesVector currentShell = mapIterator->second;\n\n    while(currentShell.size()>0)\n    {\n      unsigned int wntIndex = currentShell.back();\n      currentShell.pop_back();\n\n      mitk::gradients::GradientDirectionContainerType::Iterator containerIt = directioncontainer->Begin();\n      bool directionExist = false;\n      while(containerIt != directioncontainer->End())\n      {\n        if (fabs(dot_product(containerIt.Value(), origninalGradentcontainer->ElementAt(wntIndex)))  > 0.9998)\n        {\n          directionExist = true;\n          break;\n        }\n        containerIt++;\n      }\n      if(!directionExist)\n      {\n        GradientDirectionType dir(origninalGradentcontainer->ElementAt(wntIndex));\n        directioncontainer->push_back(dir.normalize());\n      }\n    }\n  }\n\n  return directioncontainer;\n}\n", "meta": {"hexsha": "0308e988334e8b86dcbabc5c83d290b897de8e88", "size": 22462, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/DiffusionCore/mitkDiffusionFunctionCollection.cpp", "max_stars_repo_name": "HRS-Navigation/MITK-Diffusion", "max_stars_repo_head_hexsha": "b1bf62d1c76f0d0cc26dd252561cb5d8769b4f87", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2019-07-05T10:55:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T12:09:35.000Z", "max_issues_repo_path": "Modules/DiffusionCore/mitkDiffusionFunctionCollection.cpp", "max_issues_repo_name": "HRS-Navigation/MITK-Diffusion", "max_issues_repo_head_hexsha": "b1bf62d1c76f0d0cc26dd252561cb5d8769b4f87", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-11-04T16:05:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T15:53:31.000Z", "max_forks_repo_path": "Modules/DiffusionCore/mitkDiffusionFunctionCollection.cpp", "max_forks_repo_name": "HRS-Navigation/MITK-Diffusion", "max_forks_repo_head_hexsha": "b1bf62d1c76f0d0cc26dd252561cb5d8769b4f87", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-10-15T14:37:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T03:22:01.000Z", "avg_line_length": 31.4593837535, "max_line_length": 223, "alphanum_fraction": 0.6145490161, "num_tokens": 6449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.2794851415253659}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_DETAIL_SIMD_TRIG_BASE_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_DETAIL_SIMD_TRIG_BASE_HPP_INCLUDED\n\n#include <boost/simd/arch/common/detail/simd/trig_reduction.hpp>\n#include <boost/simd/function/any.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/is_invalid.hpp>\n#include <boost/simd/function/is_eqz.hpp>\n#include <boost/simd/function/is_nez.hpp>\n#include <boost/simd/function/is_flint.hpp>\n#include <boost/simd/function/shift_left.hpp>\n#include <boost/simd/function/shr.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/function/if_nan_else.hpp>\n#include <boost/simd/function/if_allbits_else_zero.hpp>\n#include <boost/simd/function/bitwise_xor.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/bitofsign.hpp>\n#include <boost/simd/function/bitwise_and.hpp>\n#include <boost/simd/function/is_greater.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/function/oneminus.hpp>\n#include <boost/simd/detail/constant/maxleftshift.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/constant/mtwo.hpp>\n#include <boost/simd/constant/signmask.hpp>\n#include <boost/simd/arch/common/detail/tags.hpp>\n#include <boost/simd/meta/as_logical.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/simd/detail/dispatch/meta/scalar_of.hpp>\n\nnamespace boost { namespace simd\n{\n  namespace detail\n  {\n    namespace bd =  boost::dispatch;\n    namespace bs =  boost::simd;\n\n    template < class A0, class unit_tag, class mode>\n    struct trig_base < A0, unit_tag,  tag::simd_type, mode>\n    {\n      typedef typename bs::as_logical_t<A0>                        bA0; // logical type associated to A0\n      typedef trig_reduction<A0,unit_tag, tag::simd_type, mode> redu_t;\n      typedef trig_evaluation<A0,tag::simd_type>                eval_t;\n      typedef typename bd::scalar_of<A0>::type                     sA0; // scalar version of A0\n      typedef typename bd::as_integer<A0, signed>::type       int_type; // signed integer type associated to A0\n      typedef typename bs::as_logical<int_type>::type        bint_type; // logical type associated to int_type\n      typedef typename bd::scalar_of<int_type>::type         sint_type; // scalar version of the associated type\n      typedef typename mode::type                                style;\n\n      // for all functions the scalar algorithm is:\n      // * range reduction\n      // * computation of sign and evaluation selections flags\n      // * evaluations of the two branches and selection using flags\n      // * return with flag based corrections and inf and nan or specific invalid cases inputs considerations\n\n      static BOOST_FORCEINLINE A0 cosa(const A0& a0){ return cosa(a0, style()); }\n      static BOOST_FORCEINLINE A0 sina(const A0& a0){ return sina(a0, style()); }\n      static BOOST_FORCEINLINE A0 tana(const A0& a0){ return tana(a0, style()); }\n      static BOOST_FORCEINLINE A0 cota(const A0& a0){ return cota(a0, style()); }\n      static BOOST_FORCEINLINE std::pair<A0,A0> sincosa(const A0& a0){ return sincosa(a0,style()); }\n\n    private:\n      static BOOST_FORCEINLINE A0 cosa(const A0& a0, const tag::restricted&)\n      {\n        const A0 x =  scale(a0);\n        return  eval_t::cos_eval(sqr(x));\n      }\n\n      static BOOST_FORCEINLINE A0 cosa(const A0& a0, const tag::regular&)\n      {\n        const A0 x = bs::abs(a0);\n        A0 xr = Nan<A0>();\n        A0 n =  redu_t::reduce(x, xr);\n        auto tmp = if_one_else_zero(n >= Two<A0>());\n        auto swap_bit = (fma(Mtwo<A0>(), tmp, n));\n        auto sign_bit = if_else_zero(bitwise_xor(swap_bit, tmp), Signmask<A0>());\n        A0 z = sqr(xr);\n        A0 se = eval_t::sin_eval(z, xr);\n        A0 ce = eval_t::cos_eval(z);\n        A0 z1 = if_else(is_nez(swap_bit), se, ce);\n        return bitwise_xor(z1, sign_bit);\n      }\n\n      static BOOST_FORCEINLINE A0 sina(const A0& a0_n, const tag::restricted&)\n      {\n        A0 x =   scale(a0_n);\n        A0 se = eval_t::sin_eval(sqr(x), x);\n        return se;\n      }\n\n      static BOOST_FORCEINLINE A0 sina(const A0& a0, const tag::regular&)\n      {\n        const A0 x = bs::abs(a0);\n        A0 xr = Nan<A0>();\n        const A0 n = redu_t::reduce(x, xr);\n        auto tmp = if_one_else_zero(n >= Two<A0>());\n        auto swap_bit = (fma(Mtwo<A0>(), tmp, n));\n        auto sign_bit = bitwise_xor(bitofsign(a0), if_else_zero(tmp, Signmask<A0>()));\n        const A0 z = sqr(xr);\n        const A0 se = eval_t::sin_eval(z, xr);\n        const A0 ce = eval_t::cos_eval(z);\n        const A0 z1 = if_else(is_eqz(swap_bit), se, ce);\n        return bitwise_xor(z1, sign_bit);\n      }\n\n      static BOOST_FORCEINLINE A0 tana(const A0& a0, const tag::restricted&)\n      {\n        return eval_t::base_tancot_eval(scale(a0));\n      }\n\n      static BOOST_FORCEINLINE A0 tana(const A0& a0, const tag::regular&)\n      {\n        A0 x =  bs::abs(a0);\n        A0 xr = Nan<A0>();\n        A0 n = redu_t::reduce(x, xr);\n        auto tmp = if_one_else_zero( n >= Two<A0>());\n        auto swap_bit = (fma(Mtwo<A0>(), tmp, n));\n        auto test = is_eqz(swap_bit);\n        const A0 y = eval_t::tan_eval(xr, test);\n        auto testnan = redu_t::tan_invalid(a0);\n        return if_nan_else(testnan, bitwise_xor(y, bitofsign(a0)));\n      }\n\n      static BOOST_FORCEINLINE A0 cota(const A0& a0, const tag::restricted&)\n      {\n        return eval_t::base_tancot_eval(scale(a0));\n      }\n\n      static BOOST_FORCEINLINE A0 cota(const A0& a0, const tag::regular&)\n      {\n        const A0 x = bs::abs(a0);\n        A0 xr = Nan<A0>();\n        const A0 n = redu_t::reduce(x, xr);\n        auto tmp = if_one_else_zero( n >= Two<A0>());\n        auto swap_bit = (fma(Mtwo<A0>(), tmp, n));\n        auto test = is_eqz(swap_bit);\n        const A0 y = eval_t::cot_eval(xr, test);\n        const bA0 testnan = redu_t::cot_invalid(a0);\n        // this if_else is normally not needed but with clang the zero value if erroneous\n        // if not there !\n        return if_else(is_nez(a0), if_nan_else(testnan\n                                              , bitwise_xor(y, bitofsign(a0))), rec(a0));\n      }\n\n      // simultaneous cosa and sina function\n      static BOOST_FORCEINLINE std::pair<A0, A0> sincosa(const A0& a0, const tag::restricted&)\n      {\n        A0 x =  scale(a0);\n        A0 z =  sqr(x);\n        return {eval_t::sin_eval(z, x), eval_t::cos_eval(z)};\n      }\n\n      static BOOST_FORCEINLINE  std::pair<A0, A0> sincosa(const A0& a0, const tag::regular&)\n      {\n        A0 x =  bs::abs(a0);\n        A0 xr = Nan<A0>();\n        A0 n = redu_t::reduce(x, xr);\n        auto tmp = if_one_else_zero(n >= Two<A0>());\n        auto swap_bit = (fma(Mtwo<A0>(), tmp, n));\n        auto cos_sign_bit = if_else_zero(bitwise_xor(swap_bit, tmp), Signmask<A0>());\n        auto sin_sign_bit = bitwise_xor(bitofsign(a0),if_else_zero(tmp, Signmask<A0>()));\n\n        A0 z = bs::sqr(xr);\n        A0 t1 = eval_t::sin_eval(z, xr);\n        A0 t2 = eval_t::cos_eval(z);\n        auto test = is_nez(swap_bit);\n        return { bitwise_xor(if_else(test, t2, t1),sin_sign_bit)\n               , bitwise_xor(if_else(test, t1, t2),cos_sign_bit) };\n      }\n\n      static BOOST_FORCEINLINE A0 scale(const A0& a0)\n      {\n        return if_nan_else(is_greater(bs::abs(a0),\n                              trig_ranges<A0,unit_tag>::max_range()), a0)\n          *trig_ranges<A0,unit_tag>::scale();\n      }\n\n    };\n  }\n} }\n\n\n#endif\n", "meta": {"hexsha": "70bc506bb8a592630977784093c7675a1393e1b5", "size": 7933, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/detail/simd/trig_base.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/arch/common/detail/simd/trig_base.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/detail/simd/trig_base.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": 40.269035533, "max_line_length": 112, "alphanum_fraction": 0.6133871171, "num_tokens": 2090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.27941012376813995}}
{"text": "#include <boost/python/module.hpp>\n#include <boost/python/def.hpp>\n\n#include <cctbx/covariance/covariance.h>\n\nnamespace cctbx { namespace covariance {\n  namespace boost_python {\n\n    void wrap_covariance_matrix() {\n      using namespace boost::python;\n\n      def(\"extract_covariance_matrix_for_sites\", (\n        af::versa<double, af::packed_u_accessor>(*)(\n        af::const_ref<std::size_t> const &,\n        af::const_ref<double, af::packed_u_accessor> const &,\n        cctbx::xray::parameter_map<cctbx::xray::scatterer<double> > const &))\n        extract_covariance_matrix_for_sites,\n        (arg(\"i_seqs\"), arg(\"matrix\"), arg(\"parameter_map\")));\n      def(\"extract_covariance_matrix_for_u_aniso\", (\n        af::versa<double, af::packed_u_accessor>(*)(\n        std::size_t,\n        af::const_ref<double, af::packed_u_accessor> const &,\n        cctbx::xray::parameter_map<cctbx::xray::scatterer<double> > const &))\n        extract_covariance_matrix_for_u_aniso,\n        (arg(\"i_seq\"), arg(\"matrix\"), arg(\"parameter_map\")));\n      def(\"variance_for_u_iso\", (\n        double(*)(\n        std::size_t,\n        af::const_ref<double, af::packed_u_accessor> const &,\n        cctbx::xray::parameter_map<cctbx::xray::scatterer<double> > const &))\n        variance_for_u_iso,\n        (arg(\"i_seq\"), arg(\"matrix\"), arg(\"parameter_map\")));\n      def(\"orthogonalize_covariance_matrix\", (\n        af::versa<double, af::packed_u_accessor>(*)(\n        af::const_ref<double, af::packed_u_accessor> const &,\n        cctbx::uctbx::unit_cell const &,\n        cctbx::xray::parameter_map<cctbx::xray::scatterer<double> > const &))\n        orthogonalize_covariance_matrix,\n        (arg(\"matrix\"), arg(\"unit_cell\"), arg(\"parameter_map\")));\n      def(\"covariance_orthogonalization_matrix\", (\n       scitbx::sparse::matrix<double>(*)(\n        cctbx::uctbx::unit_cell const &,\n        cctbx::xray::parameter_map<cctbx::xray::scatterer<double> > const &))\n        covariance_orthogonalization_matrix,\n        (arg(\"unit_cell\"), arg(\"parameter_map\")));\n    }\n\n    void init_module()\n    {\n      wrap_covariance_matrix();\n    }\n\n\n\n}}} // namespace cctbx::covariance::boost_python\n\nBOOST_PYTHON_MODULE(cctbx_covariance_ext)\n{\n  cctbx::covariance::boost_python::init_module();\n}\n", "meta": {"hexsha": "56bff8f095461b81a1c2d959685b1e5cd2886694", "size": 2248, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cctbx/covariance/boost_python/covariance_ext.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "cctbx/covariance/boost_python/covariance_ext.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "cctbx/covariance/boost_python/covariance_ext.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 36.8524590164, "max_line_length": 77, "alphanum_fraction": 0.6525800712, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.27941012376813995}}
{"text": "#include <stdlib.h>\n#include <iostream>\n#include <functional>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Geometry>\n#include <Eigen/Cholesky>\n#include <type_traits>\n#include <random>\n#include <array>\n#include <map>\n\n#ifdef ENABLE_PARALLEL\n#include <omp.h>\n#endif\n\n#ifndef ARC_HELPERS_HPP\n#define ARC_HELPERS_HPP\n\n// Branch prediction hints\n// Figure out which compiler we have\n#if defined(__clang__)\n    /* Clang/LLVM */\n    #define likely(x) __builtin_expect(!!(x), 1)\n    #define unlikely(x) __builtin_expect(!!(x), 0)\n#elif defined(__ICC) || defined(__INTEL_COMPILER)\n    /* Intel ICC/ICPC */\n    #define likely(x) __builtin_expect(!!(x), 1)\n    #define unlikely(x) __builtin_expect(!!(x), 0)\n#elif defined(__GNUC__) || defined(__GNUG__)\n    /* GNU GCC/G++ */\n    #define likely(x) __builtin_expect(!!(x), 1)\n    #define unlikely(x) __builtin_expect(!!(x), 0)\n#elif defined(_MSC_VER)\n    /* Microsoft Visual Studio */\n    /* MSVC doesn't support branch prediction hints. Use PGO instead. */\n    #define likely(x) (x)\n    #define unlikely(x) (x)\n#endif\n\n// Macro to disable unused parameter compiler warnings\n#define UNUSED(x) (void)(x)\n\nnamespace arc_helpers\n{\n    template <typename T>\n    inline T SetBit(const T current, const uint32_t bit_position, const bool bit_value)\n    {\n        // Safety check on the type we've been called with\n        static_assert((std::is_same<T, uint8_t>::value\n                       || std::is_same<T, uint16_t>::value\n                       || std::is_same<T, uint32_t>::value\n                       || std::is_same<T, uint64_t>::value),\n                      \"Type must be a fixed-size unsigned integral type\");\n        // Do it\n        T update_mask = 1;\n        update_mask = update_mask << bit_position;\n        if (bit_value)\n        {\n            return (current | update_mask);\n        }\n        else\n        {\n            update_mask = (~update_mask);\n            return (current & update_mask);\n        }\n    }\n\n    template <typename T>\n    inline bool GetBit(const T current, const uint32_t bit_position)\n    {\n        const uint32_t mask = arc_helpers::SetBit((T)0, bit_position, true);\n        if ((mask & current) > 0)\n        {\n            return true;\n        }\n        else\n        {\n            return false;\n        }\n    }\n\n    template <class T>\n    inline T ClampValue(const T& val, const T& min, const T& max)\n    {\n        return std::min(max, std::max(min, val));\n    }\n\n    template<typename Datatype, typename Allocator=std::allocator<Datatype>>\n    static Eigen::MatrixXd BuildDistanceMatrix(const std::vector<Datatype, Allocator>& data, const std::function<double(const Datatype&, const Datatype&)>& distance_fn)\n    {\n        Eigen::MatrixXd distance_matrix(data.size(), data.size());\n#ifdef ENABLE_PARALLEL\n        #pragma omp parallel for schedule(guided)\n#endif\n        for (size_t idx = 0; idx < data.size(); idx++)\n        {\n            for (size_t jdx = idx; jdx < data.size(); jdx++)\n            {\n                const double distance = distance_fn(data[idx], data[jdx]);\n                distance_matrix((ssize_t)idx, (ssize_t)jdx) = distance;\n                distance_matrix((ssize_t)jdx, (ssize_t)idx) = distance;\n            }\n        }\n        return distance_matrix;\n    }\n\n    class SplitMix64PRNG\n    {\n    private:\n\n        uint64_t state_; /* The state can be seeded with any value. */\n\n        inline uint64_t next(void)\n        {\n            uint64_t z = (state_ += UINT64_C(0x9E3779B97F4A7C15));\n            z = (z ^ (z >> 30)) * UINT64_C(0xBF58476D1CE4E5B9);\n            z = (z ^ (z >> 27)) * UINT64_C(0x94D049BB133111EB);\n            return z ^ (z >> 31);\n        }\n\n    public:\n\n        inline SplitMix64PRNG(const uint64_t seed_val)\n        {\n            seed(seed_val);\n        }\n\n        static constexpr uint64_t min(void)\n        {\n            return 0u;\n        }\n\n        static constexpr uint64_t max(void)\n        {\n            return std::numeric_limits<uint64_t>::max();\n        }\n\n        inline void seed(const uint64_t seed_val)\n        {\n            state_ = seed_val;\n        }\n\n        inline void discard(const unsigned long long z)\n        {\n            uint64_t temp __attribute__((unused)); // This suppresses \"set but not used\" warnings\n            temp = 0u;\n            for (unsigned long long i = 0; i < z; i++)\n            {\n                temp = next();\n                __asm__ __volatile__(\"\"); // This should prevent the compiler from optimizing out the loop\n            }\n        }\n\n        inline uint64_t operator() (void)\n        {\n            return next();\n        }\n    };\n\n    class XorShift128PlusPRNG\n    {\n    private:\n\n        uint64_t state_1_;\n        uint64_t state_2_;\n\n        inline uint64_t next(void)\n        {\n            uint64_t s1 = state_1_;\n            const uint64_t s0 = state_2_;\n            state_1_ = s0;\n            s1 ^= s1 << 23; // a\n            state_2_ = s1 ^ s0 ^ (s1 >> 18) ^ (s0 >> 5); // b, c\n            return state_2_ + s0;\n        }\n\n    public:\n\n        inline XorShift128PlusPRNG(const uint64_t seed_val)\n        {\n            seed(seed_val);\n        }\n\n        static constexpr uint64_t min(void)\n        {\n            return 0u;\n        }\n\n        static constexpr uint64_t max(void)\n        {\n            return std::numeric_limits<uint64_t>::max();\n        }\n\n        inline void seed(const uint64_t seed_val)\n        {\n            SplitMix64PRNG temp_seed_gen(seed_val);\n            state_1_ = temp_seed_gen();\n            state_2_ = temp_seed_gen();\n        }\n\n        inline void discard(const unsigned long long z)\n        {\n            uint64_t temp __attribute__((unused)); // This suppresses \"set but not used\" warnings\n            temp = 0u;\n            for (unsigned long long i = 0; i < z; i++)\n            {\n                temp = next();\n                __asm__ __volatile__(\"\"); // This should prevent the compiler from optimizing out the loop\n            }\n        }\n\n        inline uint64_t operator() (void)\n        {\n            return next();\n        }\n    };\n\n    class XorShift1024StarPRNG\n    {\n    private:\n\n        std::array<uint64_t, 16> state_;\n        int32_t p;\n\n        inline uint64_t next(void)\n        {\n            const uint64_t s0 = state_[(size_t)p];\n            p = (p + 1) & 15;\n            uint64_t s1 = state_[(size_t)p];\n            s1 ^= s1 << 31; // a\n            state_[(size_t)p] = s1 ^ s0 ^ (s1 >> 11) ^ (s0 >> 30); // b,c\n            return state_[(size_t)p] * UINT64_C(1181783497276652981);\n        }\n\n    public:\n\n        inline XorShift1024StarPRNG(const uint64_t seed_val)\n        {\n            seed(seed_val);\n            p = 0;\n        }\n\n        static constexpr uint64_t min(void)\n        {\n            return 0u;\n        }\n\n        static constexpr uint64_t max(void)\n        {\n            return std::numeric_limits<uint64_t>::max();\n        }\n\n        inline void seed(const uint64_t seed_val)\n        {\n            SplitMix64PRNG temp_seed_gen(seed_val);\n            for (size_t idx = 0u; idx < state_.size(); idx++)\n            {\n                state_[idx] = temp_seed_gen();\n            }\n        }\n\n        inline void discard(const unsigned long long z)\n        {\n            uint64_t temp __attribute__((unused)); // This suppresses \"set but not used\" warnings\n            temp = 0u;\n            for (unsigned long long i = 0; i < z; i++)\n            {\n                temp = next();\n                __asm__ __volatile__(\"\"); // This should prevent the compiler from optimizing out the loop\n            }\n        }\n\n        inline uint64_t operator() (void)\n        {\n            return next();\n        }\n    };\n\n    class TruncatedNormalDistribution\n    {\n    protected:\n\n        double mean_;\n        double stddev_;\n        double std_lower_bound_;\n        double std_upper_bound_;\n\n        enum CASES {TYPE_1, TYPE_2, TYPE_3, TYPE_4, NONE};\n        CASES case_;\n        std::uniform_real_distribution<double> uniform_unit_dist_;\n        std::uniform_real_distribution<double> uniform_range_dist_;\n        std::exponential_distribution<double> exponential_dist_;\n        std::normal_distribution<double> normal_dist_;\n\n        inline bool CheckSimple(const double lower_bound, const double upper_bound) const\n        {\n            // Init Values Used in Inequality of Interest\n            const double val1 = (2 * sqrt(exp(1))) / (lower_bound + sqrt(pow(lower_bound, 2) + 4));\n            const double val2 = exp((pow(lower_bound, 2) - lower_bound * sqrt(pow(lower_bound, 2) + 4)) / (4));\n            if (upper_bound > lower_bound + val1 * val2)\n            {\n                return true;\n            }\n            else\n            {\n                return false;\n            }\n        }\n\n        // Naive Accept-Reject algorithm\n        template<typename Generator>\n        inline double NaiveAcceptReject(const double lower_bound, const double upper_bound, Generator& prng)\n        {\n            while (true)\n            {\n                const double draw = normal_dist_(prng); // Rf_rnorm(0.0, 1.0) ; // Normal distribution (i.e. std::normal_distribution<double>)\n                if ((draw <= upper_bound) && (draw >= lower_bound))\n                {\n                    return draw;\n                }\n            }\n        }\n\n        // Accept-Reject Algorithm\n        template<typename Generator>\n        inline double SimpleAcceptReject(const double lower_bound, Generator& prng)\n        {\n            // Init Values\n            const double alpha = (lower_bound + sqrt(pow(lower_bound, 2) + 4.0)) / (2.0) ;\n            while (true)\n            {\n                const double e = exponential_dist_(prng); // Rf_rexp(1.0) ; // Exponential distribution (i.e. std::exponential_distribution<double>)\n                const double z = lower_bound + e / alpha;\n                const double rho = exp(-pow(alpha - z, 2) / 2);\n                const double u = uniform_unit_dist_(prng); //  Rf_runif(0, 1) ; // Uniform distribution (i.e. std::uniform_real_distribution<double>)\n                if (u <= rho)\n                {\n                    return z;\n                }\n            }\n        }\n\n        // Accept-Reject Algorithm\n        template<typename Generator>\n        inline double ComplexAcceptReject(const double lower_bound, const double upper_bound, Generator& prng)\n        {\n            while (true)\n            {\n                const double z = uniform_range_dist_(prng); // Rf_runif(lower_bound, upper_bound) ; // Uniform distribution (i.e. std::uniform_real_distribution<double>)\n                double rho = 0.0;\n                if (0 < lower_bound)\n                {\n                    rho = exp((pow(lower_bound, 2) - pow(z, 2)) / 2);\n                }\n                else if (upper_bound < 0)\n                {\n                    rho = exp((pow(upper_bound, 2) - pow(z, 2)) / 2);\n                }\n                else if (0 < upper_bound && lower_bound < 0)\n                {\n                    rho = exp(- pow(z, 2) / 2);\n                }\n                const double u = uniform_unit_dist_(prng); // Rf_runif(0, 1) ; // Uniform distribution (i.e. std::uniform_real_distribution<double>)\n                if (u <= rho)\n                {\n                    return z;\n                }\n            }\n        }\n\n        template<typename Generator>\n        inline double Sample(Generator& prng)\n        {\n            if (case_ == TYPE_1)\n            {\n                const double draw = NaiveAcceptReject(std_lower_bound_, std_upper_bound_, prng);\n                return mean_ + stddev_ * draw;\n            }\n            else if (case_ == TYPE_2)\n            {\n                const double draw = SimpleAcceptReject(std_lower_bound_, prng);\n                return mean_ + stddev_ * draw;\n            }\n            else if (case_ == TYPE_3)\n            {\n                while (true)\n                {\n                    const double draw = SimpleAcceptReject(std_lower_bound_, prng); // use the simple algorithm if it is more efficient\n                    if (draw <= std_upper_bound_)\n                    {\n                        return mean_ + stddev_ * draw;\n                    }\n                }\n            }\n            else if (case_ == TYPE_4)\n            {\n                const double draw = ComplexAcceptReject(std_lower_bound_, std_upper_bound_, prng);\n                return mean_ + stddev_ * draw;\n            }\n            else\n            {\n                assert(case_ == NONE);\n                return mean_;\n            }\n        }\n\n    public:\n\n        inline TruncatedNormalDistribution(const double mean, const double stddev, const double lower_bound, const double upper_bound) : uniform_unit_dist_(0.0, 1.0), uniform_range_dist_(lower_bound, upper_bound), exponential_dist_(1.0), normal_dist_(0.0, 1.0)\n        {\n            // Set operating parameters\n            mean_ = mean;\n            stddev_ = stddev;\n            if (fabs(stddev_) == 0.0)\n            {\n                case_ = NONE;\n            }\n            else\n            {\n                // Standardize the lower and upper bounds\n                std_lower_bound_ = (lower_bound - mean_) / stddev_;\n                std_upper_bound_ = (upper_bound - mean_) / stddev_;\n                // Set the operating case - i.e. which sampling method we will use\n                case_ = NONE;\n                if (0.0 <= std_upper_bound_ && 0.0 >= std_lower_bound_)\n                {\n                    case_ = TYPE_1;\n                }\n                if (0.0 < std_lower_bound_ && std_upper_bound_ == INFINITY)\n                {\n                    case_ = TYPE_2;\n                }\n                if (0.0 > std_upper_bound_ && std_lower_bound_ == -INFINITY)\n                {\n                    std_lower_bound_ = -1 * std_upper_bound_;\n                    std_upper_bound_ = INFINITY;\n                    stddev_ = -1 * stddev_;\n                    case_ = TYPE_2;\n                }\n                if ((0.0 > std_upper_bound_ || 0.0 < std_lower_bound_) && !(std_upper_bound_ == INFINITY || std_lower_bound_ == -INFINITY))\n                {\n                    if (CheckSimple(std_lower_bound_, std_upper_bound_))\n                    {\n                        case_ = TYPE_3;\n                    }\n                    else\n                    {\n                        case_ = TYPE_4;\n                    }\n                }\n                assert((case_ == TYPE_1) || (case_ == TYPE_2) || (case_ == TYPE_3) || (case_ == TYPE_4));\n            }\n        }\n\n        template<typename Generator>\n        inline double operator()(Generator& prng)\n        {\n            return Sample(prng);\n        }\n    };\n\n    class MultivariteGaussianDistribution\n    {\n    protected:\n        const Eigen::VectorXd mean_;\n        const Eigen::MatrixXd norm_transform_;\n\n        std::normal_distribution<double> unit_gaussian_dist_;\n\n        template<typename Generator>\n        inline Eigen::VectorXd Sample(Generator& prng)\n        {\n            Eigen::VectorXd draw;\n            draw.resize(mean_.rows());\n\n            for (ssize_t idx = 0; idx < draw.rows(); idx++)\n            {\n                draw(idx) = unit_gaussian_dist_(prng);\n            }\n\n            return norm_transform_ * draw + mean_;\n        }\n\n        static Eigen::MatrixXd CalculateNormTransform(const Eigen::MatrixXd& covariance)\n        {\n            Eigen::MatrixXd norm_transform;\n\n            Eigen::LLT<Eigen::MatrixXd> chol_solver(covariance);\n\n            if (chol_solver.info() == Eigen::Success)\n            {\n                // Use cholesky solver\n                norm_transform = chol_solver.matrixL();\n            }\n            else\n            {\n                // Use eigen solver\n                Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigen_solver(covariance);\n                norm_transform = eigen_solver.eigenvectors() * eigen_solver.eigenvalues().cwiseMax(0.0).cwiseSqrt().asDiagonal();\n            }\n\n            return norm_transform;\n        }\n\n    public:\n        inline MultivariteGaussianDistribution(const Eigen::VectorXd& mean, const Eigen::MatrixXd& covariance) : mean_(mean), norm_transform_(CalculateNormTransform(covariance)), unit_gaussian_dist_(0.0, 1.0)\n        {\n            assert(mean.rows() == covariance.rows());\n            assert(covariance.cols() == covariance.rows());\n\n            assert(!(norm_transform_.unaryExpr([] (const double &val) { return std::isnan(val); })).any() && \"NaN Found in norm_transform in MultivariateGaussianDistribution\");\n            assert(!(norm_transform_.unaryExpr([] (const double &val) { return std::isinf(val); })).any() && \"Inf Found in norm_transform in MultivariateGaussianDistribution\");\n        }\n\n        template<typename Generator>\n        inline Eigen::VectorXd operator()(Generator& prng)\n        {\n            return Sample(prng);\n        }\n    };\n\n    class RandomRotationGenerator\n    {\n    protected:\n\n        std::uniform_real_distribution<double> uniform_unit_dist_;\n\n        // From: \"Uniform Random Rotations\", Ken Shoemake, Graphics Gems III, pg. 124-132\n        template<typename Generator>\n        inline Eigen::Quaterniond GenerateUniformRandomQuaternion(Generator& prng)\n        {\n            const double x0 = uniform_unit_dist_(prng);\n            const double r1 = sqrt(1.0 - x0);\n            const double r2 = sqrt(x0);\n            const double t1 = 2.0 * M_PI * uniform_unit_dist_(prng);\n            const double t2 = 2.0 * M_PI * uniform_unit_dist_(prng);\n            const double c1 = cos(t1);\n            const double s1 = sin(t1);\n            const double c2 = cos(t2);\n            const double s2 = sin(t2);\n            const double x = s1 * r1;\n            const double y = c1 * r1;\n            const double z = s2 * r2;\n            const double w = c2 * r2;\n            return Eigen::Quaterniond(w, x, y, z);\n        }\n\n        // From Effective Sampling and Distance Metrics for 3D Rigid Body Path Planning, by James Kuffner, ICRA 2004\n        template<typename Generator>\n        Eigen::Vector3d GenerateUniformRandomEulerAngles(Generator& prng)\n        {\n            const double roll = M_PI * (-2.0 * uniform_unit_dist_(prng) + 1.0);\n            const double pitch = acos(1.0 - 2.0 * uniform_unit_dist_(prng)) - M_PI_2;\n            const double yaw = M_PI * (-2.0 * uniform_unit_dist_(prng) + 1.0);\n            return Eigen::Vector3d(roll, pitch, yaw);\n        }\n\n    public:\n\n        inline RandomRotationGenerator() : uniform_unit_dist_(0.0, 1.0) {}\n\n        template<typename Generator>\n        inline Eigen::Quaterniond GetQuaternion(Generator& prng)\n        {\n            return GenerateUniformRandomQuaternion(prng);\n        }\n\n        template<typename Generator>\n        inline std::vector<double> GetRawQuaternion(Generator& prng)\n        {\n            const Eigen::Quaterniond quat = GenerateUniformRandomQuaternion(prng);\n            return std::vector<double>{quat.x(), quat.y(), quat.z(), quat.w()};\n        }\n\n        template<typename Generator>\n        inline Eigen::Vector3d GetEulerAngles(Generator& prng)\n        {\n            return GenerateUniformRandomEulerAngles(prng);\n        }\n\n        template<typename Generator>\n        inline std::vector<double> GetRawEulerAngles(Generator& prng)\n        {\n            const Eigen::Vector3d angles = GenerateUniformRandomEulerAngles(prng);\n            return std::vector<double>{angles.x(), angles.y(), angles.z()};\n        }\n    };\n\n    /////////////////////////////////////////////////////////////////////////////////////////////////////////\n    /////                                       PROTOTYPES ONLY                                         /////\n    ///// Specializations for specific types - if you want a specialization for a new type, add it here /////\n    /////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    template<typename T>\n    inline uint64_t SerializeFixedSizePOD(const T& item_to_serialize, std::vector<uint8_t>& buffer);\n\n    template<typename T>\n    inline std::pair<T, uint64_t> DeserializeFixedSizePOD(const std::vector<uint8_t>& buffer, const uint64_t current);\n\n    template<typename T, typename Allocator=std::allocator<T>>\n    inline uint64_t SerializeVector(const std::vector<T, Allocator>& vec_to_serialize, std::vector<uint8_t>& buffer, const std::function<uint64_t(const T&, std::vector<uint8_t>&)>& item_serializer);\n\n    template<typename T, typename Allocator=std::allocator<T>>\n    inline std::pair<std::vector<T, Allocator>, uint64_t> DeserializeVector(const std::vector<uint8_t>& buffer, const uint64_t current, const std::function<std::pair<T, uint64_t>(const std::vector<uint8_t>&, const uint64_t)>& item_deserializer);\n\n    template<typename Key, typename T, typename Compare = std::less<Key>, typename Allocator = std::allocator<std::pair<const Key, T>>>\n    inline uint64_t SerializeMap(const std::map<Key, T, Compare, Allocator>& map_to_serialize, std::vector<uint8_t>& buffer, const std::function<uint64_t(const Key&, std::vector<uint8_t>&)>& key_serializer, const std::function<uint64_t(const T&, std::vector<uint8_t>&)>& value_serializer);\n\n    template<typename Key, typename T, typename Compare = std::less<Key>, typename Allocator = std::allocator<std::pair<const Key, T>>>\n    inline std::pair<std::map<Key, T, Compare, Allocator>, uint64_t> DeserializeMap(const std::vector<uint8_t>& buffer, const uint64_t current, const std::function<std::pair<Key, uint64_t>(const std::vector<uint8_t>&, const uint64_t)>& key_deserializer, const std::function<std::pair<T, uint64_t>(const std::vector<uint8_t>&, const uint64_t)>& value_deserializer);\n\n    template<typename First, typename Second>\n    inline uint64_t SerializePair(const std::pair<First, Second>& pair_to_serialize, std::vector<uint8_t>& buffer, const std::function<uint64_t(const First&, std::vector<uint8_t>&)>& first_serializer, const std::function<uint64_t(const Second&, std::vector<uint8_t>&)>& second_serializer);\n\n    template<typename First, typename Second>\n    inline const std::pair<std::pair<First, Second>, uint64_t> DeserializePair(const std::vector<uint8_t>& buffer, const uint64_t current, const std::function<std::pair<First, uint64_t>(const std::vector<uint8_t>&, const uint64_t)>& first_deserializer, const std::function<std::pair<Second, uint64_t>(const std::vector<uint8_t>&, const uint64_t)>& second_deserializer);\n\n    /////////////////////////////////////////////////////////////////////////////////////////////////////////\n    /////                                   IMPLEMENTATIONS ONLY                                        /////\n    ///// Specializations for specific types - if you want a specialization for a new type, add it here /////\n    /////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    template<typename T>\n    inline uint64_t SerializeFixedSizePOD(const T& item_to_serialize, std::vector<uint8_t>& buffer)\n    {\n        const uint64_t start_buffer_size = buffer.size();\n        // Fixed-size serialization via memcpy\n        std::vector<uint8_t> temp_buffer(sizeof(item_to_serialize), 0x00);\n        memcpy(&temp_buffer[0], &item_to_serialize, sizeof(item_to_serialize));\n        // Move to buffer\n        buffer.insert(buffer.end(), temp_buffer.begin(), temp_buffer.end());\n        // Figure out how many bytes were written\n        const uint64_t end_buffer_size = buffer.size();\n        const uint64_t bytes_written = end_buffer_size - start_buffer_size;\n        return bytes_written;\n    }\n\n    template<typename T>\n    inline std::pair<T, uint64_t> DeserializeFixedSizePOD(const std::vector<uint8_t>& buffer, const uint64_t current)\n    {\n        T temp_item;\n        assert(current <= buffer.size());\n        assert((current + sizeof(temp_item)) <= buffer.size());\n        memcpy(&temp_item, &buffer[current], sizeof(temp_item));\n        return std::make_pair(temp_item, sizeof(temp_item));\n    }\n\n    template<typename T, typename Allocator>\n    inline uint64_t SerializeVector(const std::vector<T, Allocator>& vec_to_serialize, std::vector<uint8_t>& buffer, const std::function<uint64_t(const T&, std::vector<uint8_t>&)>& item_serializer)\n    {\n        const uint64_t start_buffer_size = buffer.size();\n        // First, write a uint64_t size header\n        const uint64_t size = (uint64_t)vec_to_serialize.size();\n        SerializeFixedSizePOD<uint64_t>(size, buffer);\n        // Serialize the contained items\n        for (size_t idx = 0; idx < size; idx++)\n        {\n            const T& current = vec_to_serialize[idx];\n            item_serializer(current, buffer);\n        }\n        // Figure out how many bytes were written\n        const uint64_t end_buffer_size = buffer.size();\n        const uint64_t bytes_written = end_buffer_size - start_buffer_size;\n        return bytes_written;\n    }\n\n    template<typename T, typename Allocator>\n    inline std::pair<std::vector<T, Allocator>, uint64_t> DeserializeVector(const std::vector<uint8_t>& buffer, const uint64_t current, const std::function<std::pair<T, uint64_t>(const std::vector<uint8_t>&, const uint64_t)>& item_deserializer)\n    {\n        // First, try to load the header\n        assert(current < buffer.size());\n        uint64_t current_position = current;\n        // Load the header\n        const std::pair<uint64_t, uint64_t> deserialized_size = DeserializeFixedSizePOD<uint64_t>(buffer, current_position);\n        const uint64_t size = deserialized_size.first;\n        current_position += deserialized_size.second;\n        // Deserialize the items\n        std::vector<T, Allocator> deserialized;\n        deserialized.reserve(size);\n        for (uint64_t idx = 0; idx < size; idx++)\n        {\n            const std::pair<T, uint64_t> deserialized_item = item_deserializer(buffer, current_position);\n            deserialized.push_back(deserialized_item.first);\n            current_position += deserialized_item.second;\n        }\n        // Figure out how many bytes were read\n        const uint64_t bytes_read = current_position - current;\n        return std::make_pair(deserialized, bytes_read);\n    }\n\n    template<typename Key, typename T, typename Compare, typename Allocator>\n    inline uint64_t SerializeMap(const std::map<Key, T, Compare, Allocator>& map_to_serialize, std::vector<uint8_t>& buffer, const std::function<uint64_t(const Key&, std::vector<uint8_t>&)>& key_serializer, const std::function<uint64_t(const T&, std::vector<uint8_t>&)>& value_serializer)\n    {\n        const uint64_t start_buffer_size = buffer.size();\n        // First, write a uint64_t size header\n        const uint64_t size = (uint64_t)map_to_serialize.size();\n        SerializeFixedSizePOD<uint64_t>(size, buffer);\n        // Serialize the contained items\n        typename std::map<Key, T, Compare, Allocator>::const_iterator itr;\n        for (itr = map_to_serialize.begin(); itr != map_to_serialize.end(); ++itr)\n        {\n            SerializePair<Key, T>(*itr, buffer, key_serializer, value_serializer);\n        }\n        // Figure out how many bytes were written\n        const uint64_t end_buffer_size = buffer.size();\n        const uint64_t bytes_written = end_buffer_size - start_buffer_size;\n        return bytes_written;\n    }\n\n    template<typename Key, typename T, typename Compare, typename Allocator>\n    inline std::pair<std::map<Key, T, Compare, Allocator>, uint64_t> DeserializeMap(const std::vector<uint8_t>& buffer, const uint64_t current, const std::function<std::pair<Key, uint64_t>(const std::vector<uint8_t>&, const uint64_t)>& key_deserializer, const std::function<std::pair<T, uint64_t>(const std::vector<uint8_t>&, const uint64_t)>& value_deserializer)\n    {\n        // First, try to load the header\n        assert(current < buffer.size());\n        uint64_t current_position = current;\n        // Load the header\n        const std::pair<uint64_t, uint64_t> deserialized_size = DeserializeFixedSizePOD<uint64_t>(buffer, current_position);\n        const uint64_t size = deserialized_size.first;\n        current_position += deserialized_size.second;\n        // Deserialize the items\n        std::map<Key, T, Compare, Allocator> deserialized;\n        for (uint64_t idx = 0; idx < size; idx++)\n        {\n            std::pair<std::pair<Key, T>, uint64_t> deserialized_pair = DeserializePair(buffer, current_position, key_deserializer, value_deserializer);\n            deserialized.insert(deserialized_pair.first);\n            current_position += deserialized_pair.second;\n        }\n        // Figure out how many bytes were read\n        const uint64_t bytes_read = current_position - current;\n        return std::make_pair(deserialized, bytes_read);\n    }\n\n    template<typename First, typename Second>\n    inline uint64_t SerializePair(const std::pair<First, Second>& pair_to_serialize, std::vector<uint8_t>& buffer, const std::function<uint64_t(const First&, std::vector<uint8_t>&)>& first_serializer, const std::function<uint64_t(const Second&, std::vector<uint8_t>&)>& second_serializer)\n    {\n        const uint64_t start_buffer_size = buffer.size();\n        uint64_t running_total = 0u;\n        // Write each element of the pair into the buffer\n        running_total += first_serializer(pair_to_serialize.first, buffer);\n        running_total += second_serializer(pair_to_serialize.second, buffer);\n        // Figure out how many bytes were written\n        const uint64_t end_buffer_size = buffer.size();\n        const uint64_t bytes_written = end_buffer_size - start_buffer_size;\n        assert(bytes_written == running_total);\n        return bytes_written;\n    }\n\n    template<typename First, typename Second>\n    inline const std::pair<std::pair<First, Second>, uint64_t> DeserializePair(const std::vector<uint8_t>& buffer, const uint64_t current, const std::function<std::pair<First, uint64_t>(const std::vector<uint8_t>&, const uint64_t)>& first_deserializer, const std::function<std::pair<Second, uint64_t>(const std::vector<uint8_t>&, const uint64_t)>& second_deserializer)\n    {\n        assert(current < buffer.size());\n        // Deserialize each item in the pair individually\n        uint64_t current_position = current;\n        const std::pair<First, uint64_t> deserialized_first = first_deserializer(buffer, current_position);\n        current_position += deserialized_first.second;\n        const std::pair<Second, uint64_t> deserialized_second = second_deserializer(buffer, current_position);\n        current_position += deserialized_second.second;\n        // Build the resulting pair\n        // TODO: Why can't I used make_pair here?\n        const std::pair<First, Second> deserialized(deserialized_first.first, deserialized_second.first);\n        // Figure out how many bytes were read\n        const uint64_t bytes_read = current_position - current;\n        return std::make_pair(deserialized, bytes_read);\n    }\n\n    inline void ConditionalPrint(const std::string& msg, const int32_t msg_level, const int32_t print_level)\n    {\n        if (unlikely(msg_level <= print_level))\n        {\n            std::cout << msg << std::endl;\n        }\n    }\n\n    inline bool CheckAllStringsForSubstring(const std::vector<std::string>& strings, const std::string& substring)\n    {\n        for (size_t idx = 0; idx < strings.size(); idx++)\n        {\n            const std::string& candidate_string = strings[idx];\n            const size_t found = candidate_string.find(substring);\n            if (found == std::string::npos)\n            {\n                return false;\n            }\n        }\n        return true;\n    }\n}\n\n#endif // ARC_HELPERS_HPP\n", "meta": {"hexsha": "06eb3e17c50b6d6509b6703d864dc17016910f97", "size": 31586, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "arc_utilities/include/arc_utilities/arc_helpers.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/arc_helpers.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/arc_helpers.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": 39.982278481, "max_line_length": 369, "alphanum_fraction": 0.5811752042, "num_tokens": 7156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2794010886696876}}
{"text": "// smooth_feedback: Control theory on Lie groups\n// https://github.com/pettni/smooth_feedback\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef SMOOTH__FEEDBACK__NLP_HPP_\n#define SMOOTH__FEEDBACK__NLP_HPP_\n\n/**\n * @file\n * @brief Nonlinear program definition.\n */\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\n#include <limits>\n#include <optional>\n\nnamespace smooth::feedback {\n\n/**\n * @brief Nonlinear Programming Problem\n * \\f[\n *  \\begin{cases}\n *   \\min_{x}    & f(x)                    \\\\\n *   \\text{s.t.} & x_l \\leq x \\leq x_u     \\\\\n *               & g_l \\leq g(x) \\leq g_u\n *  \\end{cases}\n * \\f]\n * for \\f$ f : \\mathbb{R}^n \\rightarrow \\mathbb{R} \\f$ and\n * \\f$ g : \\mathbb{R}^n \\rightarrow \\mathbb{R}^m \\f$.\n */\ntemplate<typename T>\nconcept NLP = requires(\n  std::decay_t<T> & nlp,\n  const Eigen::Ref<const Eigen::VectorXd> x,\n  const Eigen::Ref<const Eigen::VectorXd> lambda)\n{\n  // clang-format off\n  {nlp.n()} -> std::convertible_to<std::size_t>;\n  {nlp.m()} -> std::convertible_to<std::size_t>;\n\n  // variable bounds\n  {nlp.xl()} -> std::convertible_to<Eigen::VectorXd>;\n  {nlp.xu()} -> std::convertible_to<Eigen::VectorXd>;\n\n  // objective and its derivatives\n  {nlp.f(x)}     -> std::convertible_to<double>;\n  {nlp.df_dx(x)} -> std::convertible_to<Eigen::SparseMatrix<double>>;\n\n  // constraint, its bounds, and its derivatives\n  {nlp.g(x)}     -> std::convertible_to<Eigen::VectorXd>;\n  {nlp.gl()}     -> std::convertible_to<Eigen::VectorXd>;\n  {nlp.gu()}     -> std::convertible_to<Eigen::VectorXd>;\n  {nlp.dg_dx(x)} -> std::convertible_to<Eigen::SparseMatrix<double>>;\n  // clang-format on\n};\n\n/**\n * @brief Nonlinear Programming Problem with Hessian information\n */\ntemplate<typename T>\nconcept HessianNLP =\n  NLP<T> && requires(std::decay_t<T> & nlp, Eigen::VectorXd x, Eigen::VectorXd lambda)\n{\n  // clang-format off\n  {nlp.d2f_dx2(x)}         -> std::convertible_to<Eigen::SparseMatrix<double>>;\n  {nlp.d2g_dx2(x, lambda)} -> std::convertible_to<Eigen::SparseMatrix<double>>;\n  // clang-format on\n};\n\n/**\n * @brief Solution to a Nonlinear Programming Problem\n */\nstruct NLPSolution\n{\n  /// @brief Solver status\n  enum class Status {\n    Optimal,\n    PrimalInfeasible,\n    DualInfeasible,\n    MaxIterations,\n    MaxTime,\n    Unknown,\n  };\n\n  /// @brief Solver status\n  Status status;\n\n  /// @brief Number of iterations\n  std::size_t iter{0};\n\n  /// @brief Variable values\n  Eigen::VectorXd x;\n\n  ///@{\n  /// @brief Inequality multipliers\n  Eigen::VectorXd zl, zu;\n  ///@}\n\n  /// @brief Constraint multipliers\n  Eigen::VectorXd lambda;\n\n  /// @brief Objective\n  double objective{0};\n};\n\n}  // namespace smooth::feedback\n\n#endif  // SMOOTH__FEEDBACK__NLP_HPP_\n", "meta": {"hexsha": "23307421cba579398a70dee1a33e4de92bf8ffa8", "size": 3831, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/feedback/nlp.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/nlp.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/nlp.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": 29.0227272727, "max_line_length": 86, "alphanum_fraction": 0.6815452884, "num_tokens": 1036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.27930374750832476}}
{"text": "// -----------------------------------------------------------------------\r\n// RTToolbox - DKFZ radiotherapy quantitative evaluation library\r\n//\r\n// Copyright (c) German Cancer Research Center (DKFZ),\r\n// Software development for Integrated Diagnostics and Therapy (SIDT).\r\n// ALL RIGHTS RESERVED.\r\n// See rttbCopyright.txt or\r\n// http://www.dkfz.de/en/sidt/projects/rttb/copyright.html\r\n//\r\n// This software is distributed WITHOUT ANY WARRANTY; without even\r\n// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\r\n// PURPOSE.  See the above copyright notices for more information.\r\n//\r\n//------------------------------------------------------------------------\r\n\r\n#include <boost/make_shared.hpp>\r\n\r\n#include \"rttbDVHCalculator.h\"\r\n#include \"rttbNullPointerException.h\"\r\n#include \"rttbInvalidParameterException.h\"\r\n\r\nnamespace rttb\r\n{\r\n\tnamespace core\r\n\t{\r\n\r\n\t\tDVHCalculator::DVHCalculator(DoseIteratorPointer aDoseIterator, const IDType& aStructureID,\r\n\t\t                             const IDType& aDoseID,\r\n\t\t                             DoseTypeGy aDeltaD, const int aNumberOfBins)\r\n\t\t{\r\n\t\t\tif (aDoseIterator == nullptr)\r\n\t\t\t{\r\n\t\t\t\tthrow NullPointerException(\"aDoseIterator must not be nullptr! \");\r\n\t\t\t}\r\n\r\n\t\t\t_doseIteratorPtr = aDoseIterator;\r\n\t\t\t_structureID = aStructureID;\r\n\t\t\t_doseID = aDoseID;\r\n\r\n\t\t\tif (aNumberOfBins <= 0 || aDeltaD < 0)\r\n\t\t\t{\r\n\t\t\t\tthrow InvalidParameterException(\"aNumberOfBins/aDeltaD must be >0! \");\r\n\t\t\t}\r\n\r\n\t\t\t_numberOfBins = aNumberOfBins;\r\n\t\t\t_deltaD = aDeltaD;\r\n\r\n\t\t\tif (_deltaD == 0)\r\n\t\t\t{\r\n\t\t\t\taDoseIterator->reset();\r\n\t\t\t\tDoseTypeGy max = 0;\r\n\r\n\t\t\t\twhile (aDoseIterator->isPositionValid())\r\n\t\t\t\t{\r\n\t\t\t\t\tDoseTypeGy currentVal = 0;\r\n\t\t\t\t\tcurrentVal = aDoseIterator->getCurrentDoseValue();\r\n\r\n\t\t\t\t\tif (currentVal > max)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tmax = currentVal;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\taDoseIterator->next();\r\n\t\t\t\t}\r\n\r\n\t\t\t\t_deltaD = (max * 1.5 / _numberOfBins);\r\n\r\n\t\t\t\tif (_deltaD == 0)\r\n\t\t\t\t{\r\n\t\t\t\t\t_deltaD = 0.1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\t\tDVHCalculator::~DVHCalculator() = default;\r\n\r\n\t\tDVH::Pointer DVHCalculator::generateDVH()\r\n\t\t{\r\n\r\n\t\t\tstd::deque<DoseCalcType> dataDifferential(_numberOfBins, 0);\r\n\r\n\t\t\t// calculate DVH\r\n\t\t\t_doseIteratorPtr->reset();\r\n\r\n\t\t\twhile (_doseIteratorPtr->isPositionValid())\r\n\t\t\t{\r\n\t\t\t\tDoseTypeGy currentVal = 0;\r\n\t\t\t\tFractionType voxelProportion = _doseIteratorPtr->getCurrentRelevantVolumeFraction();\r\n\t\t\t\tcurrentVal = _doseIteratorPtr->getCurrentDoseValue();\r\n\r\n\t\t\t\tauto dose_bin = static_cast<int>(currentVal / _deltaD);\r\n\r\n\t\t\t\tif (dose_bin < _numberOfBins)\r\n\t\t\t\t{\r\n\t\t\t\t\tdataDifferential[dose_bin] += voxelProportion;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tthrow InvalidParameterException(\"_numberOfBins is too small: dose bin out of bounds! \");\r\n\t\t\t\t}\r\n\r\n\t\t\t\t_doseIteratorPtr->next();\r\n\t\t\t}\r\n\r\n\t\t\tif (boost::dynamic_pointer_cast<MaskedDoseIteratorPointer>(_doseIteratorPtr))\r\n\t\t\t{\r\n\t\t\t\t_dvh = boost::make_shared<DVH>(dataDifferential, _deltaD, _doseIteratorPtr->getCurrentVoxelVolume(),\r\n\t\t\t\t                               _structureID,\r\n\t\t\t\t                               _doseID, _doseIteratorPtr->getVoxelizationID());\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t_dvh = boost::make_shared<DVH>(dataDifferential, _deltaD, _doseIteratorPtr->getCurrentVoxelVolume(),\r\n\t\t\t\t                               _structureID,\r\n\t\t\t\t                               _doseID);\r\n\t\t\t}\r\n\r\n\t\t\treturn _dvh;\r\n\t\t}\r\n\r\n\t}//end namespace core\r\n}//end namespace rttb\r\n\r\n", "meta": {"hexsha": "8c5e2ba25bb514eeb27945cad15844fae2fde6bb", "size": 3391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/core/rttbDVHCalculator.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/core/rttbDVHCalculator.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/core/rttbDVHCalculator.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": 27.128, "max_line_length": 105, "alphanum_fraction": 0.6042465349, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2793037405379424}}
{"text": "/* -*- c++ -*- */\n/*\n * Copyright 2009-2013 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#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include <cstdio>\n#include <cmath>\n#include <algorithm>\n\n#include \"pfb_clock_sync_ccf_impl.h\"\n#include <gnuradio/io_signature.h>\n#include <gnuradio/math.h>\n#include <boost/format.hpp>\n#include <boost/math/special_functions/round.hpp>\n\nnamespace gr {\n  namespace digital {\n\n    pfb_clock_sync_ccf::sptr\n    pfb_clock_sync_ccf::make(double sps, float loop_bw,\n\t\t\t     const std::vector<float> &taps,\n\t\t\t     unsigned int filter_size,\n\t\t\t     float init_phase,\n\t\t\t     float max_rate_deviation,\n\t\t\t     int osps)\n    {\n      return gnuradio::get_initial_sptr\n\t(new pfb_clock_sync_ccf_impl(sps, loop_bw, taps,\n\t\t\t\t     filter_size,\n\t\t\t\t     init_phase,\n\t\t\t\t     max_rate_deviation,\n\t\t\t\t     osps));\n    }\n\n    static int ios[] = {sizeof(gr_complex), sizeof(float), sizeof(float), sizeof(float)};\n    static std::vector<int> iosig(ios, ios+sizeof(ios)/sizeof(int));\n    pfb_clock_sync_ccf_impl::pfb_clock_sync_ccf_impl(double sps, float loop_bw,\n\t\t\t\t\t\t     const std::vector<float> &taps,\n\t\t\t\t\t\t     unsigned int filter_size,\n\t\t\t\t\t\t     float init_phase,\n\t\t\t\t\t\t     float max_rate_deviation,\n\t\t\t\t\t\t     int osps)\n      : block(\"pfb_clock_sync_ccf\",\n\t\t  io_signature::make(1, 1, sizeof(gr_complex)),\n\t\t  io_signature::makev(1, 4, iosig)),\n\td_updated(false), d_nfilters(filter_size),\n\td_max_dev(max_rate_deviation),\n\td_osps(osps), d_error(0), d_out_idx(0)\n    {\n      if(taps.size() == 0)\n        throw std::runtime_error(\"pfb_clock_sync_ccf: please specify a filter.\\n\");\n\n      // Let scheduler adjust our relative_rate.\n      //enable_update_rate(true);\n      set_tag_propagation_policy(TPP_DONT);\n\n      d_nfilters = filter_size;\n      d_sps = floor(sps);\n\n      // Set the damping factor for a critically damped system\n      d_damping = 2*d_nfilters;\n\n      // Set the bandwidth, which will then call update_gains()\n      set_loop_bandwidth(loop_bw);\n\n      // Store the last filter between calls to work\n      // The accumulator keeps track of overflow to increment the stride correctly.\n      // set it here to the fractional difference based on the initial phaes\n      d_k = init_phase;\n      d_rate = (sps-floor(sps))*(double)d_nfilters;\n      d_rate_i = (int)floor(d_rate);\n      d_rate_f = d_rate - (float)d_rate_i;\n      d_filtnum = (int)floor(d_k);\n\n      d_filters = std::vector<kernel::fir_filter_ccf*>(d_nfilters);\n      d_diff_filters = std::vector<kernel::fir_filter_ccf*>(d_nfilters);\n\n      // Create an FIR filter for each channel and zero out the taps\n      std::vector<float> vtaps(1,0);\n      for(int i = 0; i < d_nfilters; i++) {\n\td_filters[i] = new kernel::fir_filter_ccf(1, vtaps);\n\td_diff_filters[i] = new kernel::fir_filter_ccf(1, vtaps);\n      }\n\n      // Now, actually set the filters' taps\n      std::vector<float> dtaps;\n      create_diff_taps(taps, dtaps);\n      set_taps(taps, d_taps, d_filters);\n      set_taps(dtaps, d_dtaps, d_diff_filters);\n\n      d_old_in = 0;\n      d_new_in = 0;\n      d_last_out = 0;\n\n      set_relative_rate((float)d_osps/(float)d_sps);\n    }\n\n    pfb_clock_sync_ccf_impl::~pfb_clock_sync_ccf_impl()\n    {\n      for(int i = 0; i < d_nfilters; i++) {\n\tdelete d_filters[i];\n\tdelete d_diff_filters[i];\n      }\n    }\n\n    bool\n    pfb_clock_sync_ccf_impl::check_topology(int ninputs, int noutputs)\n    {\n      return noutputs == 1 || noutputs == 4;\n    }\n\n    void\n    pfb_clock_sync_ccf_impl::forecast(int noutput_items,\n                                      gr_vector_int &ninput_items_required)\n    {\n      unsigned ninputs = ninput_items_required.size ();\n      for(unsigned i = 0; i < ninputs; i++)\n        ninput_items_required[i] = (noutput_items + history()) * (d_sps/d_osps);\n    }\n\n    void\n    pfb_clock_sync_ccf_impl::update_taps(const std::vector<float> &taps)\n    {\n      d_updated_taps = taps;\n      d_updated = true;\n    }\n\n\n    /*******************************************************************\n     SET FUNCTIONS\n    *******************************************************************/\n\n    void\n    pfb_clock_sync_ccf_impl::set_loop_bandwidth(float bw)\n    {\n      if(bw < 0) {\n\tthrow std::out_of_range(\"pfb_clock_sync_ccf: invalid bandwidth. Must be >= 0.\");\n      }\n\n      d_loop_bw = bw;\n      update_gains();\n    }\n\n    void\n    pfb_clock_sync_ccf_impl::set_damping_factor(float df)\n    {\n      if(df < 0 || df > 1.0) {\n\tthrow std::out_of_range(\"pfb_clock_sync_ccf: invalid damping factor. Must be in [0,1].\");\n      }\n\n      d_damping = df;\n      update_gains();\n    }\n\n    void\n    pfb_clock_sync_ccf_impl::set_alpha(float alpha)\n    {\n      if(alpha < 0 || alpha > 1.0) {\n\tthrow std::out_of_range(\"pfb_clock_sync_ccf: invalid alpha. Must be in [0,1].\");\n      }\n      d_alpha = alpha;\n    }\n\n    void\n    pfb_clock_sync_ccf_impl::set_beta(float beta)\n    {\n      if(beta < 0 || beta > 1.0) {\n\tthrow std::out_of_range(\"pfb_clock_sync_ccf: invalid beta. Must be in [0,1].\");\n      }\n      d_beta = beta;\n    }\n\n    /*******************************************************************\n     GET FUNCTIONS\n    *******************************************************************/\n\n    float\n    pfb_clock_sync_ccf_impl::loop_bandwidth() const\n    {\n      return d_loop_bw;\n    }\n\n    float\n    pfb_clock_sync_ccf_impl::damping_factor() const\n    {\n      return d_damping;\n    }\n\n    float\n    pfb_clock_sync_ccf_impl::alpha() const\n    {\n      return d_alpha;\n    }\n\n    float\n    pfb_clock_sync_ccf_impl::beta() const\n    {\n      return d_beta;\n    }\n\n    float\n    pfb_clock_sync_ccf_impl::clock_rate() const\n    {\n      return d_rate_f;\n    }\n\n    float\n    pfb_clock_sync_ccf_impl::error() const\n    {\n      return d_error;\n    }\n\n    float\n    pfb_clock_sync_ccf_impl::rate() const\n    {\n      return d_rate_f;\n    }\n\n    float\n    pfb_clock_sync_ccf_impl::phase() const\n    {\n      return d_k;\n    }\n\n    /*******************************************************************\n     *******************************************************************/\n\n    void\n    pfb_clock_sync_ccf_impl::update_gains()\n    {\n      float denom = (1.0 + 2.0*d_damping*d_loop_bw + d_loop_bw*d_loop_bw);\n      d_alpha = (4*d_damping*d_loop_bw) / denom;\n      d_beta = (4*d_loop_bw*d_loop_bw) / denom;\n    }\n\n    void\n    pfb_clock_sync_ccf_impl::set_taps(const std::vector<float> &newtaps,\n\t\t\t\t      std::vector< std::vector<float> > &ourtaps,\n\t\t\t\t      std::vector<kernel::fir_filter_ccf*> &ourfilter)\n    {\n      int i,j;\n\n      unsigned int ntaps = newtaps.size();\n      d_taps_per_filter = (unsigned int)ceil((double)ntaps/(double)d_nfilters);\n\n      // Create d_numchan vectors to store each channel's taps\n      ourtaps.resize(d_nfilters);\n\n      // Make a vector of the taps plus fill it out with 0's to fill\n      // each polyphase filter with exactly d_taps_per_filter\n      std::vector<float> tmp_taps;\n      tmp_taps = newtaps;\n      while((float)(tmp_taps.size()) < d_nfilters*d_taps_per_filter) {\n\ttmp_taps.push_back(0.0);\n      }\n\n      // Partition the filter\n      for(i = 0; i < d_nfilters; i++) {\n\t// Each channel uses all d_taps_per_filter with 0's if not enough taps to fill out\n\tourtaps[i] = std::vector<float>(d_taps_per_filter, 0);\n\tfor(j = 0; j < d_taps_per_filter; j++) {\n\t  ourtaps[i][j] = tmp_taps[i + j*d_nfilters];\n\t}\n\n\t// Build a filter for each channel and add it's taps to it\n\tourfilter[i]->set_taps(ourtaps[i]);\n      }\n\n      // Set the history to ensure enough input items for each filter\n      set_history(d_taps_per_filter + d_sps + d_sps);\n\n      // Make sure there is enough output space for d_osps outputs/input.\n      set_output_multiple(d_osps);\n    }\n\n    void\n    pfb_clock_sync_ccf_impl::create_diff_taps(const std::vector<float> &newtaps,\n\t\t\t\t\t      std::vector<float> &difftaps)\n    {\n      std::vector<float> diff_filter(3);\n      diff_filter[0] = -1;\n      diff_filter[1] = 0;\n      diff_filter[2] = 1;\n\n      float pwr = 0;\n      difftaps.clear();\n      difftaps.push_back(0);\n      for(unsigned int i = 0; i < newtaps.size()-2; i++) {\n\tfloat tap = 0;\n\tfor(unsigned int j = 0; j < diff_filter.size(); j++) {\n\t  tap += diff_filter[j]*newtaps[i+j];\n\t}\n\tdifftaps.push_back(tap);\n        pwr += fabsf(tap);\n      }\n      difftaps.push_back(0);\n\n      // Normalize the taps\n      for(unsigned int i = 0; i < difftaps.size(); i++) {\n        difftaps[i] *= d_nfilters/pwr;\n        if(difftaps[i] != difftaps[i]) {\n          throw std::runtime_error(\"pfb_clock_sync_ccf::create_diff_taps produced NaN.\");\n        }\n      }\n    }\n\n    std::string\n    pfb_clock_sync_ccf_impl::taps_as_string() const\n    {\n      int i, j;\n      std::stringstream str;\n      str.precision(4);\n      str.setf(std::ios::scientific);\n\n      str << \"[ \";\n      for(i = 0; i < d_nfilters; i++) {\n\tstr << \"[\" << d_taps[i][0] << \", \";\n\tfor(j = 1; j < d_taps_per_filter-1; j++) {\n\t  str << d_taps[i][j] << \", \";\n\t}\n\tstr << d_taps[i][j] << \"],\";\n      }\n      str << \" ]\" << std::endl;\n\n      return str.str();\n    }\n\n    std::string\n    pfb_clock_sync_ccf_impl::diff_taps_as_string() const\n    {\n      int i, j;\n      std::stringstream str;\n      str.precision(4);\n      str.setf(std::ios::scientific);\n\n      str << \"[ \";\n      for(i = 0; i < d_nfilters; i++) {\n\tstr << \"[\" << d_dtaps[i][0] << \", \";\n\tfor(j = 1; j < d_taps_per_filter-1; j++) {\n\t  str << d_dtaps[i][j] << \", \";\n\t}\n\tstr << d_dtaps[i][j] << \"],\";\n      }\n      str << \" ]\" << std::endl;\n\n      return str.str();\n    }\n\n    std::vector< std::vector<float> >\n    pfb_clock_sync_ccf_impl::taps() const\n    {\n      return d_taps;\n    }\n\n    std::vector< std::vector<float> >\n    pfb_clock_sync_ccf_impl::diff_taps() const\n    {\n      return d_dtaps;\n    }\n\n    std::vector<float>\n    pfb_clock_sync_ccf_impl::channel_taps(int channel) const\n    {\n      std::vector<float> taps;\n      for(int i = 0; i < d_taps_per_filter; i++) {\n\ttaps.push_back(d_taps[channel][i]);\n      }\n      return taps;\n    }\n\n    std::vector<float>\n    pfb_clock_sync_ccf_impl::diff_channel_taps(int channel) const\n    {\n      std::vector<float> taps;\n      for(int i = 0; i < d_taps_per_filter; i++) {\n\ttaps.push_back(d_dtaps[channel][i]);\n      }\n      return taps;\n    }\n\n    int\n    pfb_clock_sync_ccf_impl::general_work(int noutput_items,\n\t\t\t\t\t  gr_vector_int &ninput_items,\n\t\t\t\t\t  gr_vector_const_void_star &input_items,\n\t\t\t\t\t  gr_vector_void_star &output_items)\n    {\n      gr_complex *in = (gr_complex *) input_items[0];\n      gr_complex *out = (gr_complex *) output_items[0];\n\n      if(d_updated) {\n        std::vector<float> dtaps;\n        create_diff_taps(d_updated_taps, dtaps);\n        set_taps(d_updated_taps, d_taps, d_filters);\n        set_taps(dtaps, d_dtaps, d_diff_filters);\n\td_updated = false;\n\treturn 0;\t\t     // history requirements may have changed.\n      }\n\n      float *err = NULL, *outrate = NULL, *outk = NULL;\n      if(output_items.size() == 4) {\n\terr = (float *) output_items[1];\n\toutrate = (float*)output_items[2];\n\toutk = (float*)output_items[3];\n      }\n\n      std::vector<tag_t> tags;\n      get_tags_in_window(tags, 0, 0,\n                        d_sps*noutput_items,\n                        pmt::intern(\"time_est\"));\n\n      int i = 0, count = 0;\n      float error_r, error_i;\n\n      // produce output as long as we can and there are enough input samples\n      while(i < noutput_items) {\n        if(tags.size() > 0) {\n          size_t offset = tags[0].offset-nitems_read(0);\n          if((offset >= (size_t)count) && (offset < (size_t)(count + d_sps))) {\n            float center = (float)pmt::to_double(tags[0].value);\n            d_k = d_nfilters*(center + (offset - count));\n\n            tags.erase(tags.begin());\n          }\n        }\n\n\twhile(d_out_idx < d_osps) {\n\n\t  d_filtnum = (int)floor(d_k);\n\n\t  // Keep the current filter number in [0, d_nfilters]\n\t  // If we've run beyond the last filter, wrap around and go to next sample\n\t  // If we've gone below 0, wrap around and go to previous sample\n\t  while(d_filtnum >= d_nfilters) {\n\t    d_k -= d_nfilters;\n\t    d_filtnum -= d_nfilters;\n\t    count += 1;\n\t  }\n\t  while(d_filtnum < 0) {\n\t    d_k += d_nfilters;\n\t    d_filtnum += d_nfilters;\n\t    count -= 1;\n\t  }\n\n\t  out[i+d_out_idx] = d_filters[d_filtnum]->filter(&in[count+d_out_idx]);\n\t  d_k = d_k + d_rate_i + d_rate_f; // update phase\n\n\n          // Manage Tags\n          std::vector<tag_t> xtags;\n          std::vector<tag_t>::iterator itags;\n          d_new_in = nitems_read(0) + count + d_out_idx + d_sps;\n          get_tags_in_range(xtags, 0, d_old_in, d_new_in);\n          for(itags = xtags.begin(); itags != xtags.end(); itags++) {\n            tag_t new_tag = *itags;\n            //new_tag.offset = d_last_out + d_taps_per_filter/(2*d_sps) - 2;\n            new_tag.offset = d_last_out + d_taps_per_filter/4 - 2;\n            add_item_tag(0, new_tag);\n          }\n          d_old_in = d_new_in;\n          d_last_out = nitems_written(0) + i + d_out_idx;\n\n          d_out_idx++;\n\n\t  if(output_items.size() == 4) {\n\t    err[i] = d_error;\n\t    outrate[i] = d_rate_f;\n\t    outk[i] = d_k;\n\t  }\n\n\t  // We've run out of output items we can create; return now.\n\t  if(i+d_out_idx >= noutput_items) {\n\t    consume_each(count);\n\t    return i;\n\t  }\n\t}\n\n\t// reset here; if we didn't complete a full osps samples last time,\n\t// the early return would take care of it.\n\td_out_idx = 0;\n\n\t// Update the phase and rate estimates for this symbol\n\tgr_complex diff = d_diff_filters[d_filtnum]->filter(&in[count]);\n\terror_r = out[i].real() * diff.real();\n\terror_i = out[i].imag() * diff.imag();\n\td_error = (error_i + error_r) / 2.0;       // average error from I&Q channel\n\n        // Run the control loop to update the current phase (k) and\n        // tracking rate estimates based on the error value\n        // Interpolating here to update rates for ever sps.\n        for(int s = 0; s < d_sps; s++) {\n          d_rate_f = d_rate_f + d_beta*d_error;\n          d_k = d_k + d_rate_f + d_alpha*d_error;\n        }\n\n\t// Keep our rate within a good range\n\td_rate_f = gr::branchless_clip(d_rate_f, d_max_dev);\n\n\ti+=d_osps;\n\tcount += (int)floor(d_sps);\n      }\n\n      consume_each(count);\n      return i;\n    }\n\n    void\n    pfb_clock_sync_ccf_impl::setup_rpc()\n    {\n#ifdef GR_CTRLPORT\n      // Getters\n      add_rpc_variable(\n          rpcbasic_sptr(new rpcbasic_register_get<pfb_clock_sync_ccf, float>(\n\t      alias(), \"error\",\n\t      &pfb_clock_sync_ccf::error,\n\t      pmt::mp(-2.0f), pmt::mp(2.0f), pmt::mp(0.0f),\n\t      \"\", \"Error signal of loop\", RPC_PRIVLVL_MIN,\n              DISPTIME | DISPOPTSTRIP)));\n\n      add_rpc_variable(\n          rpcbasic_sptr(new rpcbasic_register_get<pfb_clock_sync_ccf, float>(\n\t      alias(), \"rate\",\n\t      &pfb_clock_sync_ccf::rate,\n\t      pmt::mp(-2.0f), pmt::mp(2.0f), pmt::mp(0.0f),\n\t      \"\", \"Rate change of phase\", RPC_PRIVLVL_MIN,\n              DISPTIME | DISPOPTSTRIP)));\n\n      add_rpc_variable(\n          rpcbasic_sptr(new rpcbasic_register_get<pfb_clock_sync_ccf, float>(\n\t      alias(), \"phase\",\n\t      &pfb_clock_sync_ccf::phase,\n\t      pmt::mp(0), pmt::mp((int)d_nfilters), pmt::mp(0),\n\t      \"\", \"Current filter phase arm\", RPC_PRIVLVL_MIN,\n              DISPTIME | DISPOPTSTRIP)));\n\n      add_rpc_variable(\n          rpcbasic_sptr(new rpcbasic_register_get<pfb_clock_sync_ccf, float>(\n\t      alias(), \"loop bw\",\n\t      &pfb_clock_sync_ccf::loop_bandwidth,\n\t      pmt::mp(0.0f), pmt::mp(1.0f), pmt::mp(0.0f),\n\t      \"\", \"Loop bandwidth\",\n\t      RPC_PRIVLVL_MIN, DISPNULL)));\n\n      // Setters\n      add_rpc_variable(\n          rpcbasic_sptr(new rpcbasic_register_set<pfb_clock_sync_ccf, float>(\n\t      alias(), \"loop bw\",\n\t      &pfb_clock_sync_ccf::set_loop_bandwidth,\n\t      pmt::mp(0.0f), pmt::mp(1.0f), pmt::mp(0.0f),\n\t      \"\", \"Loop bandwidth\",\n\t      RPC_PRIVLVL_MIN, DISPNULL)));\n#endif /* GR_CTRLPORT */\n    }\n\n  } /* namespace digital */\n} /* namespace gr */\n", "meta": {"hexsha": "6ac39fbcfccc0624774d66f230da3a72a01345e7", "size": 16621, "ext": "cc", "lang": "C++", "max_stars_repo_path": "gnuradio-3.7.13.4/gr-digital/lib/pfb_clock_sync_ccf_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-digital/lib/pfb_clock_sync_ccf_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-digital/lib/pfb_clock_sync_ccf_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": 28.8058925477, "max_line_length": 90, "alphanum_fraction": 0.5967149991, "num_tokens": 4656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.27925873484277425}}
{"text": "#include \"LHCOpticsApproximator.h\"\n#include <vector>\n#include <iostream>\n#include \"TROOT.h\"\n#include \"TMath.h\"\n#include <boost/shared_ptr.hpp>\n#include \"CurrentMemoryUsage.h\"\n\nClassImp(LHCOpticsApproximator);\nClassImp(LHCApertureApproximator);\n\n\nvoid LHCOpticsApproximator::Init()\n{\n  out_polynomials.clear();\n  apertures_.clear();\n  out_polynomials.push_back(&x_parametrisation);\n  out_polynomials.push_back(&theta_x_parametrisation);\n  out_polynomials.push_back(&y_parametrisation);\n  out_polynomials.push_back(&theta_y_parametrisation);\n\n  coord_names.clear();\n  coord_names.push_back(\"x\");\n  coord_names.push_back(\"theta_x\");\n  coord_names.push_back(\"y\");\n  coord_names.push_back(\"theta_y\");\n  coord_names.push_back(\"ksi\");\n\n  s_begin_ = 0.0;\n  s_end_ = 0.0;\n  trained_ = false;\n}\n\n\nLHCOpticsApproximator::LHCOpticsApproximator(std::string name, std::string title, TMultiDimFet::EMDFPolyType polynom_type, std::string beam_direction, double nominal_beam_energy)\n: x_parametrisation(5, polynom_type, \"k\"),\n  theta_x_parametrisation(5, polynom_type, \"k\"),\n  y_parametrisation(5, polynom_type, \"k\"),\n  theta_y_parametrisation(5, polynom_type, \"k\")\n{\n  this->SetName(name.c_str());\n  this->SetTitle(title.c_str());\n  Init();\n\n  if(beam_direction == \"lhcb1\")\n    beam = lhcb1;\n  else if(beam_direction == \"lhcb2\")\n    beam = lhcb2;\n  else\n    beam = lhcb1;\n\n  nominal_beam_energy_ = nominal_beam_energy;\n  nominal_beam_momentum_ = TMath::Sqrt(nominal_beam_energy_*nominal_beam_energy_ - 0.938272029*0.938272029);\n}\n\n\nLHCOpticsApproximator::LHCOpticsApproximator(std::string name, std::string title, TMultiDimFet::EMDFPolyType polynom_type, std::string beam_direction, double nominal_beam_energy,\n  TMultiDimFet *given_x_parametrisation, TMultiDimFet *given_theta_x_parametrisation, TMultiDimFet *given_y_parametrisation, TMultiDimFet *given_theta_y_parametrisation)\n{\n  this->x_parametrisation = *given_x_parametrisation;\n  this->theta_x_parametrisation = *given_theta_x_parametrisation;\n  this->y_parametrisation = *given_y_parametrisation;\n  this->theta_y_parametrisation = *given_theta_y_parametrisation;\n  this->SetName(name.c_str());\n  this->SetTitle(title.c_str());\n  Init();\n\n  if(beam_direction == \"lhcb1\")\n    beam = lhcb1;\n  else if(beam_direction == \"lhcb2\")\n    beam = lhcb2;\n  else\n    beam = lhcb1;\n\n  nominal_beam_energy_ = nominal_beam_energy;\n  nominal_beam_momentum_ = TMath::Sqrt(nominal_beam_energy_*nominal_beam_energy_ - 0.938272029*0.938272029);\n  trained_ = true;\n}\n\n\nLHCOpticsApproximator::LHCOpticsApproximator()\n{\n  Init();\n  beam = lhcb1;\n  nominal_beam_energy_ = 7000;\n  nominal_beam_momentum_ = TMath::Sqrt(nominal_beam_energy_*nominal_beam_energy_ - 0.938272029*0.938272029);\n}\n\n\nbool LHCOpticsApproximator::Transport(double *in, double *out, bool check_apertures)\n{\n  if(in==NULL || out==NULL || !trained_)\n    return false;\n\n  bool res = CheckInputRange(in);\n\n  out[0] = x_parametrisation.Eval(in);\n  out[1] = theta_x_parametrisation.Eval(in);\n  out[2] = y_parametrisation.Eval(in);\n  out[3] = theta_y_parametrisation.Eval(in);\n  out[4] = in[4];\n\n  if(check_apertures)\n  {\n    for(int i=0; i<apertures_.size(); i++)\n    {\n      res = res && apertures_[i].CheckAperture(in);\n    }\n  }\n  return res;\n}\n\nbool LHCOpticsApproximator::Transport_m_GeV(double in_pos[3], double in_momentum[3], double out_pos[3], double out_momentum[3],\n        bool check_apertures, double z2_z1_dist)\n{\n  double in[5];\n  double out[5];\n  double part_mom = 0.0;\n  for(int i=0; i<3; i++)\n    part_mom += in_momentum[i]*in_momentum[i];\n\n  part_mom = TMath::Sqrt(part_mom);\n\n  in[0] = in_pos[0];\n  in[1] = in_momentum[0]/nominal_beam_momentum_;\n  in[2] = in_pos[1];\n  in[3] = in_momentum[1]/nominal_beam_momentum_;\n  in[4] = (part_mom-nominal_beam_momentum_)/nominal_beam_momentum_;\n\n  bool res = Transport(in, out, check_apertures);\n\n  out_pos[0] = out[0];\n  out_pos[1] = out[2];\n  out_pos[2] = in_pos[2] + z2_z1_dist;\n\n  out_momentum[0] = out[1]*nominal_beam_momentum_;\n  out_momentum[1] = out[3]*nominal_beam_momentum_;\n  double part_out_total_mom = (out[4]+1)*nominal_beam_momentum_;\n  out_momentum[2] = TMath::Sqrt(part_out_total_mom*part_out_total_mom - out_momentum[0]*out_momentum[0] - out_momentum[1]*out_momentum[1]);\n  out_momentum[2] = TMath::Sign(out_momentum[2], in_momentum[2]);\n\n  return res;\n}\n\nbool LHCOpticsApproximator::Transport(const MadKinematicDescriptor *in, MadKinematicDescriptor *out, bool check_apertures)\n{\n  if(in==NULL || out==NULL || !trained_)\n    return false;\n\n  Double_t input[5];\n  Double_t output[5];\n  input[0] = in->x;\n  input[1] = in->theta_x;\n  input[2] = in->y;\n  input[3] = in->theta_y;\n  input[4] = in->ksi;\n\n  bool res = Transport(input, output, check_apertures);\n\n  out->x = output[0];\n  out->theta_x = output[1];\n  out->y = output[2];\n  out->theta_y = output[3];\n  out->ksi = output[4];\n\n  return res;\n}\n\n\nLHCOpticsApproximator::LHCOpticsApproximator(const LHCOpticsApproximator &org) : TNamed(org), x_parametrisation(org.x_parametrisation), theta_x_parametrisation(org.theta_x_parametrisation), y_parametrisation(org.y_parametrisation), theta_y_parametrisation(org.theta_y_parametrisation)\n{\n//  std::cout<<\"LHCOpticsApproximator::LHCOpticsApproximator(const LHCOpticsApproximator &org) entered\"<<std::endl;\n    void Init();\n    s_begin_ = org.s_begin_;\n    s_end_ = org.s_end_;\n    trained_ = org.trained_;\n    apertures_ = org.apertures_;\n    beam = org.beam;\n    nominal_beam_energy_ = org.nominal_beam_energy_;\n    nominal_beam_momentum_ = org.nominal_beam_momentum_;\n//  std::cout<<\"LHCOpticsApproximator::LHCOpticsApproximator(const LHCOpticsApproximator &org) left\"<<std::endl;\n}\n\n\ndouble LHCOpticsApproximator::GetBegin(){\n  return s_begin_;\n}\n\n\ndouble LHCOpticsApproximator::GetEnd(){\n  return s_end_;\n}\n\n\nLHCOpticsApproximator & LHCOpticsApproximator::operator=(const LHCOpticsApproximator &org)\n{\n  if(this!=&org)\n  {\n    void Init();\n    TNamed::operator=(org);\n    s_begin_ = org.s_begin_;\n    s_end_ = org.s_end_;\n    trained_ = org.trained_;\n\n    x_parametrisation = org.x_parametrisation;\n    theta_x_parametrisation = org.theta_x_parametrisation;\n    y_parametrisation = org.y_parametrisation;\n    theta_y_parametrisation = org.theta_y_parametrisation;\n    apertures_ = org.apertures_;\n    beam = org.beam;\n    nominal_beam_energy_ = org.nominal_beam_energy_;\n    nominal_beam_momentum_ = org.nominal_beam_momentum_;\n  }\n}\n\n\nvoid LHCOpticsApproximator::Train(TTree *inp_tree, std::string data_prefix, polynomials_selection mode, int max_degree_x, int max_degree_tx, int max_degree_y, int max_degree_ty, bool common_terms, double *prec)\n{\n  if(inp_tree==NULL)\n    return;\n\n  PrintCurrentMemoryUsage(\"Train, begin\");\n\n  InitializeApproximators(mode, max_degree_x, max_degree_tx, max_degree_y, max_degree_ty, common_terms);\n  std::cout<<this->GetName()<<\" is being trained...\"<<std::endl;\n\n  //in-variables\n  //x_in, theta_x_in, y_in, theta_y_in, ksi_in, s_in\n  double in_var[6];\n\n  //out-variables\n  //x_out, theta_x_out, y_out, theta_y_out, ksi_out, s_out, valid_out;\n  double out_var[7];\n\n  //in- out-lables\n  std::string x_in_lab = \"x_in\";\n  std::string theta_x_in_lab = \"theta_x_in\";\n  std::string y_in_lab = \"y_in\";\n  std::string theta_y_in_lab = \"theta_y_in\";\n  std::string ksi_in_lab = \"ksi_in\";\n  std::string s_in_lab = \"s_in\";\n\n  std::string x_out_lab = data_prefix + \"_x_out\";\n  std::string theta_x_out_lab = data_prefix + \"_theta_x_out\";\n  std::string y_out_lab = data_prefix + \"_y_out\";\n  std::string theta_y_out_lab = data_prefix + \"_theta_y_out\";\n  std::string ksi_out_lab = data_prefix + \"_ksi_out\";\n  std::string s_out_lab = data_prefix + \"_s_out\";\n  std::string valid_out_lab = data_prefix + \"_valid_out\";\n\n  //disable not needed branches to speed up the readin\n  inp_tree->SetBranchStatus(\"*\",0);  //disable all branches\n  inp_tree->SetBranchStatus(x_in_lab.c_str(),1);\n  inp_tree->SetBranchStatus(theta_x_in_lab.c_str(),1);\n  inp_tree->SetBranchStatus(y_in_lab.c_str(),1);\n  inp_tree->SetBranchStatus(theta_y_in_lab.c_str(),1);\n  inp_tree->SetBranchStatus(ksi_in_lab.c_str(),1);\n  inp_tree->SetBranchStatus(x_out_lab.c_str(),1);\n  inp_tree->SetBranchStatus(theta_x_out_lab.c_str(),1);\n  inp_tree->SetBranchStatus(y_out_lab.c_str(),1);\n  inp_tree->SetBranchStatus(theta_y_out_lab.c_str(),1);\n  inp_tree->SetBranchStatus(s_out_lab.c_str(),1);\n  inp_tree->SetBranchStatus(ksi_out_lab.c_str(),1);\n  inp_tree->SetBranchStatus(valid_out_lab.c_str(),1);\n\n  //set input data adresses\n  inp_tree->SetBranchAddress(x_in_lab.c_str(), &(in_var[0]) );\n  inp_tree->SetBranchAddress(theta_x_in_lab.c_str(), &(in_var[1]) );\n  inp_tree->SetBranchAddress(y_in_lab.c_str(), &(in_var[2]) );\n  inp_tree->SetBranchAddress(theta_y_in_lab.c_str(), &(in_var[3]) );\n  inp_tree->SetBranchAddress(ksi_in_lab.c_str(), &(in_var[4]) );\n  inp_tree->SetBranchAddress(s_in_lab.c_str(), &(in_var[5]) );\n\n  //set output data adresses\n  inp_tree->SetBranchAddress(x_out_lab.c_str(), &(out_var[0]) );\n  inp_tree->SetBranchAddress(theta_x_out_lab.c_str(), &(out_var[1]) );\n  inp_tree->SetBranchAddress(y_out_lab.c_str(), &(out_var[2]) );\n  inp_tree->SetBranchAddress(theta_y_out_lab.c_str(), &(out_var[3]) );\n  inp_tree->SetBranchAddress(ksi_out_lab.c_str(), &(out_var[4]) );\n  inp_tree->SetBranchAddress(s_out_lab.c_str(), &(out_var[5]) );\n  inp_tree->SetBranchAddress(valid_out_lab.c_str(), &(out_var[6]) );\n\n  Long64_t entries = inp_tree->GetEntries();\n  if(entries>0)\n  {\n    inp_tree->SetBranchStatus(s_in_lab.c_str(),1);\n    inp_tree->SetBranchStatus(s_out_lab.c_str(),1);\n    inp_tree->GetEntry(0);\n    s_begin_ = in_var[5];\n    s_end_ = out_var[5];\n    inp_tree->SetBranchStatus(s_in_lab.c_str(),0);\n    inp_tree->SetBranchStatus(s_out_lab.c_str(),0);\n  }\n\n  PrintCurrentMemoryUsage(\"Train, before setting data\");\n  //set input and output variables for fitting\n  for(Long64_t i=0; i<entries; ++i)\n  {\n    inp_tree->GetEntry(i);\n    if(out_var[6] != 0)  //if out data valid\n    {\n      x_parametrisation.AddRow(in_var, out_var[0], 0);\n      theta_x_parametrisation.AddRow(in_var, out_var[1], 0);\n      y_parametrisation.AddRow(in_var, out_var[2], 0);\n      theta_y_parametrisation.AddRow(in_var, out_var[3], 0);\n    }\n  }\n\n  std::cout<<\"Optical functions parametrizations from \"<<s_begin_<<\" to \"<<s_end_<<std::endl;\n  PrintInputRange();\n  PrintCurrentMemoryUsage(\"Train, before fitting\");\n  for(int i=0; i<4; i++)\n  {\n    double best_precision=0.0;\n    if(prec)\n      best_precision = prec[i];\n    out_polynomials[i]->FindParameterization(best_precision);\n    std::cout<<\"Out variable \"<<coord_names[i]<<\" polynomial\"<<std::endl;\n    out_polynomials[i]->PrintPolynomialsSpecial(\"M\");\n    std::cout<<std::endl;\n  }\n\n  trained_ = true;\n  PrintCurrentMemoryUsage(\"Train, function end\");\n}\n\n\nvoid LHCOpticsApproximator::InitializeApproximators(polynomials_selection mode, int max_degree_x, int max_degree_tx, int max_degree_y, int max_degree_ty, bool common_terms)\n{\n  SetDefaultAproximatorSettings(x_parametrisation, X, max_degree_x);\n  SetDefaultAproximatorSettings(theta_x_parametrisation, THETA_X, max_degree_tx);\n  SetDefaultAproximatorSettings(y_parametrisation, Y, max_degree_y);\n  SetDefaultAproximatorSettings(theta_y_parametrisation, THETA_Y, max_degree_ty);\n\n  if(mode == PREDEFINED)\n  {\n    SetTermsManually(x_parametrisation, X, max_degree_x, common_terms);\n    SetTermsManually(theta_x_parametrisation, THETA_X, max_degree_tx, common_terms);\n    SetTermsManually(y_parametrisation, Y, max_degree_y, common_terms);\n    SetTermsManually(theta_y_parametrisation, THETA_Y, max_degree_ty, common_terms);\n  }\n}\n\n\nvoid LHCOpticsApproximator::SetDefaultAproximatorSettings(TMultiDimFet &approximator, variable_type var_type, int max_degree)\n{\n  if(max_degree<1 || max_degree>20)\n    max_degree = 10;\n\n  if(var_type == X || var_type == THETA_X)\n  {\n    Int_t mPowers[] = { 2, 4, 2, 4, max_degree };\n    approximator.SetMaxPowers (mPowers);\n    approximator.SetMaxFunctions (3000);\n    approximator.SetMaxStudy (3000);\n    approximator.SetMaxTerms (3000);\n    approximator.SetPowerLimit (1.6);\n//    approximator.SetMinAngle (2e-4);\n//    approximator.SetMaxAngle (10);\n    approximator.SetMinRelativeError (1e-13);\n  }\n\n  if(var_type == Y || var_type == THETA_Y)\n  {\n    Int_t mPowers[] = { 2, 4, 2, 4, max_degree };\n    approximator.SetMaxPowers (mPowers);\n    approximator.SetMaxFunctions (3000);\n    approximator.SetMaxStudy (3000);\n    approximator.SetMaxTerms (3000);\n    approximator.SetPowerLimit (1.6);\n//    approximator.SetMinAngle (2e-4);\n//    approximator.SetMaxAngle (10);\n    approximator.SetMinRelativeError (1e-13);\n  }\n}\n\n\nvoid LHCOpticsApproximator::SetTermsManually(TMultiDimFet &approximator, variable_type variable, int max_degree, bool common_terms)\n{\n  if(max_degree<1 || max_degree>20)\n    max_degree = 10;\n\n  //put terms of shape:\n  //1,0,0,0,t    0,1,0,0,t    0,2,0,0,t    0,3,0,0,t    0,0,0,0,t\n  //t: 0,1,...,max_degree\n//  int total_terms = 5*(max_degree+1);\n//  int table_size = total_terms*5;\n//  Int_t powers[table_size];\n\n  std::vector<Int_t> term_literals;\n  term_literals.reserve(5000);\n\n  if(variable == X || variable == THETA_X)\n  {\n    //1,0,0,0,t\n    for(int i=0; i<=max_degree; ++i)\n    {\n      term_literals.push_back(1);\n      term_literals.push_back(0);\n      term_literals.push_back(0);\n      term_literals.push_back(0);\n      term_literals.push_back(i);\n    }\n    //0,1,0,0,t\n    for(int i=0; i<=max_degree; ++i)\n    {\n      term_literals.push_back(0);\n      term_literals.push_back(1);\n      term_literals.push_back(0);\n      term_literals.push_back(0);\n      term_literals.push_back(i);\n    }\n    //0,2,0,0,t\n    for(int i=0; i<=max_degree; ++i)\n    {\n      term_literals.push_back(0);\n      term_literals.push_back(2);\n      term_literals.push_back(0);\n      term_literals.push_back(0);\n      term_literals.push_back(i);\n    }\n    //0,3,0,0,t\n    for(int i=0; i<=max_degree; ++i)\n    {\n      term_literals.push_back(0);\n      term_literals.push_back(3);\n      term_literals.push_back(0);\n      term_literals.push_back(0);\n      term_literals.push_back(i);\n    }\n    //0,0,0,0,t\n    for(int i=0; i<=max_degree; ++i)\n    {\n      term_literals.push_back(0);\n      term_literals.push_back(0);\n      term_literals.push_back(0);\n      term_literals.push_back(0);\n      term_literals.push_back(i);\n    }\n  }\n\n  if(variable == Y || variable == THETA_Y)\n  {\n    //0,0,1,0,t\n    for(int i=0; i<=max_degree; ++i)\n    {\n      term_literals.push_back(0);\n      term_literals.push_back(0);\n      term_literals.push_back(1);\n      term_literals.push_back(0);\n      term_literals.push_back(i);\n    }\n    //0,0,0,1,t\n    for(int i=0; i<=max_degree; ++i)\n    {\n      term_literals.push_back(0);\n      term_literals.push_back(0);\n      term_literals.push_back(0);\n      term_literals.push_back(1);\n      term_literals.push_back(i);\n    }\n    //0,0,0,2,t\n    for(int i=0; i<=max_degree; ++i)\n    {\n      term_literals.push_back(0);\n      term_literals.push_back(0);\n      term_literals.push_back(0);\n      term_literals.push_back(2);\n      term_literals.push_back(i);\n    }\n    //0,0,0,3,t\n    for(int i=0; i<=max_degree; ++i)\n    {\n      term_literals.push_back(0);\n      term_literals.push_back(0);\n      term_literals.push_back(0);\n      term_literals.push_back(3);\n      term_literals.push_back(i);\n    }\n    //0,0,0,0,t\n    for(int i=0; i<=max_degree; ++i)\n    {\n      term_literals.push_back(0);\n      term_literals.push_back(0);\n      term_literals.push_back(0);\n      term_literals.push_back(0);\n      term_literals.push_back(i);\n    }\n  }\n\n  //push common terms\n  if(common_terms)\n  {\n    term_literals.push_back(1), term_literals.push_back(1), term_literals.push_back(0), term_literals.push_back(0), term_literals.push_back(0);\n    term_literals.push_back(1), term_literals.push_back(0), term_literals.push_back(1), term_literals.push_back(0), term_literals.push_back(0);\n    term_literals.push_back(1), term_literals.push_back(0), term_literals.push_back(0), term_literals.push_back(1), term_literals.push_back(0);\n    term_literals.push_back(0), term_literals.push_back(1), term_literals.push_back(1), term_literals.push_back(0), term_literals.push_back(0);\n    term_literals.push_back(0), term_literals.push_back(1), term_literals.push_back(0), term_literals.push_back(1), term_literals.push_back(0);\n    term_literals.push_back(0), term_literals.push_back(0), term_literals.push_back(1), term_literals.push_back(1), term_literals.push_back(0);\n\n    term_literals.push_back(1), term_literals.push_back(1), term_literals.push_back(0), term_literals.push_back(0), term_literals.push_back(1);\n    term_literals.push_back(1), term_literals.push_back(0), term_literals.push_back(1), term_literals.push_back(0), term_literals.push_back(1);\n    term_literals.push_back(1), term_literals.push_back(0), term_literals.push_back(0), term_literals.push_back(1), term_literals.push_back(1);\n    term_literals.push_back(0), term_literals.push_back(1), term_literals.push_back(1), term_literals.push_back(0), term_literals.push_back(1);\n    term_literals.push_back(0), term_literals.push_back(1), term_literals.push_back(0), term_literals.push_back(1), term_literals.push_back(1);\n    term_literals.push_back(0), term_literals.push_back(0), term_literals.push_back(1), term_literals.push_back(1), term_literals.push_back(1);\n\n    term_literals.push_back(1), term_literals.push_back(2), term_literals.push_back(0), term_literals.push_back(0), term_literals.push_back(0);\n    term_literals.push_back(1), term_literals.push_back(0), term_literals.push_back(2), term_literals.push_back(0), term_literals.push_back(0);\n    term_literals.push_back(1), term_literals.push_back(0), term_literals.push_back(0), term_literals.push_back(2), term_literals.push_back(0);\n    term_literals.push_back(2), term_literals.push_back(1), term_literals.push_back(0), term_literals.push_back(0), term_literals.push_back(0);\n    term_literals.push_back(0), term_literals.push_back(1), term_literals.push_back(2), term_literals.push_back(0), term_literals.push_back(0);\n    term_literals.push_back(0), term_literals.push_back(1), term_literals.push_back(0), term_literals.push_back(2), term_literals.push_back(0);\n    term_literals.push_back(2), term_literals.push_back(0), term_literals.push_back(1), term_literals.push_back(0), term_literals.push_back(0);\n    term_literals.push_back(0), term_literals.push_back(2), term_literals.push_back(1), term_literals.push_back(0), term_literals.push_back(0);\n    term_literals.push_back(0), term_literals.push_back(0), term_literals.push_back(1), term_literals.push_back(2), term_literals.push_back(0);\n    term_literals.push_back(2), term_literals.push_back(0), term_literals.push_back(0), term_literals.push_back(1), term_literals.push_back(0);\n    term_literals.push_back(0), term_literals.push_back(2), term_literals.push_back(0), term_literals.push_back(1), term_literals.push_back(0);\n    term_literals.push_back(0), term_literals.push_back(0), term_literals.push_back(2), term_literals.push_back(1), term_literals.push_back(0);\n\n    term_literals.push_back(1), term_literals.push_back(2), term_literals.push_back(0), term_literals.push_back(0), term_literals.push_back(1);\n    term_literals.push_back(1), term_literals.push_back(0), term_literals.push_back(2), term_literals.push_back(0), term_literals.push_back(1);\n    term_literals.push_back(1), term_literals.push_back(0), term_literals.push_back(0), term_literals.push_back(2), term_literals.push_back(1);\n    term_literals.push_back(2), term_literals.push_back(1), term_literals.push_back(0), term_literals.push_back(0), term_literals.push_back(1);\n    term_literals.push_back(0), term_literals.push_back(1), term_literals.push_back(2), term_literals.push_back(0), term_literals.push_back(1);\n    term_literals.push_back(0), term_literals.push_back(1), term_literals.push_back(0), term_literals.push_back(2), term_literals.push_back(1);\n    term_literals.push_back(2), term_literals.push_back(0), term_literals.push_back(1), term_literals.push_back(0), term_literals.push_back(1);\n    term_literals.push_back(0), term_literals.push_back(2), term_literals.push_back(1), term_literals.push_back(0), term_literals.push_back(1);\n    term_literals.push_back(0), term_literals.push_back(0), term_literals.push_back(1), term_literals.push_back(2), term_literals.push_back(1);\n    term_literals.push_back(2), term_literals.push_back(0), term_literals.push_back(0), term_literals.push_back(1), term_literals.push_back(1);\n    term_literals.push_back(0), term_literals.push_back(2), term_literals.push_back(0), term_literals.push_back(1), term_literals.push_back(1);\n    term_literals.push_back(0), term_literals.push_back(0), term_literals.push_back(2), term_literals.push_back(1), term_literals.push_back(1);\n  }\n\n  Int_t powers[term_literals.size()];\n  for(int i=0; i<term_literals.size(); ++i)\n  {\n    powers[i] = term_literals[i];\n  }\n  approximator.SetPowers(powers, term_literals.size()/5);\n}\n\n\nvoid LHCOpticsApproximator::Test(TTree *inp_tree, TFile *f_out, std::string data_prefix, std::string base_out_dir)\n{\n  PrintCurrentMemoryUsage(\"Test, begin\");\n  if(inp_tree==NULL || f_out==NULL)\n    return;\n\n  std::cout<<this->GetName()<<\" is being tested...\"<<std::endl;\n  //in-variables\n  //x_in, theta_x_in, y_in, theta_y_in, ksi_in, s_in\n  double in_var[6];\n\n  //out-variables\n  //x_out, theta_x_out, y_out, theta_y_out, ksi_out, s_out, valid_out;\n  double out_var[7];\n\n  //in- out-lables\n  std::string x_in_lab = \"x_in\";\n  std::string theta_x_in_lab = \"theta_x_in\";\n  std::string y_in_lab = \"y_in\";\n  std::string theta_y_in_lab = \"theta_y_in\";\n  std::string ksi_in_lab = \"ksi_in\";\n  std::string s_in_lab = \"s_in\";\n\n  std::string x_out_lab = data_prefix + \"_x_out\";\n  std::string theta_x_out_lab = data_prefix + \"_theta_x_out\";\n  std::string y_out_lab = data_prefix + \"_y_out\";\n  std::string theta_y_out_lab = data_prefix + \"_theta_y_out\";\n  std::string ksi_out_lab = data_prefix + \"_ksi_out\";\n  std::string s_out_lab = data_prefix + \"_s_out\";\n  std::string valid_out_lab = data_prefix + \"_valid_out\";\n\n  //disable not needed branches to speed up the readin\n  inp_tree->SetBranchStatus(\"*\",0);  //disable all branches\n  inp_tree->SetBranchStatus(x_in_lab.c_str(),1);\n  inp_tree->SetBranchStatus(theta_x_in_lab.c_str(),1);\n  inp_tree->SetBranchStatus(y_in_lab.c_str(),1);\n  inp_tree->SetBranchStatus(theta_y_in_lab.c_str(),1);\n  inp_tree->SetBranchStatus(ksi_in_lab.c_str(),1);\n  inp_tree->SetBranchStatus(x_out_lab.c_str(),1);\n  inp_tree->SetBranchStatus(theta_x_out_lab.c_str(),1);\n  inp_tree->SetBranchStatus(y_out_lab.c_str(),1);\n  inp_tree->SetBranchStatus(theta_y_out_lab.c_str(),1);\n  inp_tree->SetBranchStatus(ksi_out_lab.c_str(),1);\n  inp_tree->SetBranchStatus(s_out_lab.c_str(),1);\n  inp_tree->SetBranchStatus(valid_out_lab.c_str(),1);\n\n  //set input data adresses\n  inp_tree->SetBranchAddress(x_in_lab.c_str(), &(in_var[0]) );\n  inp_tree->SetBranchAddress(theta_x_in_lab.c_str(), &(in_var[1]) );\n  inp_tree->SetBranchAddress(y_in_lab.c_str(), &(in_var[2]) );\n  inp_tree->SetBranchAddress(theta_y_in_lab.c_str(), &(in_var[3]) );\n  inp_tree->SetBranchAddress(ksi_in_lab.c_str(), &(in_var[4]) );\n  inp_tree->SetBranchAddress(s_in_lab.c_str(), &(in_var[5]) );\n\n  //set output data adresses\n  inp_tree->SetBranchAddress(x_out_lab.c_str(), &(out_var[0]) );\n  inp_tree->SetBranchAddress(theta_x_out_lab.c_str(), &(out_var[1]) );\n  inp_tree->SetBranchAddress(y_out_lab.c_str(), &(out_var[2]) );\n  inp_tree->SetBranchAddress(theta_y_out_lab.c_str(), &(out_var[3]) );\n  inp_tree->SetBranchAddress(ksi_out_lab.c_str(), &(out_var[4]) );\n  inp_tree->SetBranchAddress(s_out_lab.c_str(), &(out_var[5]) );\n  inp_tree->SetBranchAddress(valid_out_lab.c_str(), &(out_var[6]) );\n\n  PrintCurrentMemoryUsage(\"Test, before allocating the histograms\");\n  //test histogramms\n  TH1D *err_hists[4];\n  TH2D *err_inp_cor_hists[4][5];\n  TH2D *err_out_cor_hists[4][5];\n\n  AllocateErrorHists(err_hists);\n  AllocateErrorInputCorHists(err_inp_cor_hists);\n  AllocateErrorOutputCorHists(err_out_cor_hists);\n\n  Long64_t entries = inp_tree->GetEntries();\n  //set input and output variables for fitting\n  for(Long64_t i=0; i<entries; ++i)\n  {\n    double errors[4];\n    inp_tree->GetEntry(i);\n\n    errors[0] = out_var[0] - x_parametrisation.Eval(in_var);\n    errors[1] = out_var[1] - theta_x_parametrisation.Eval(in_var);\n    errors[2] = out_var[2] - y_parametrisation.Eval(in_var);\n    errors[3] = out_var[3] - theta_y_parametrisation.Eval(in_var);\n\n    FillErrorHistograms(errors, err_hists);\n    FillErrorDataCorHistograms(errors, in_var, err_inp_cor_hists);\n    FillErrorDataCorHistograms(errors, out_var, err_out_cor_hists);\n  }\n\n  PrintCurrentMemoryUsage(\"Test, before writing the histograms\");\n  WriteHistograms(err_hists, err_inp_cor_hists, err_out_cor_hists, f_out, base_out_dir);\n  std::cout<<\"Histograms have been written.\"<<std::endl;\n\n  DeleteErrorHists(err_hists);\n  DeleteErrorCorHistograms(err_inp_cor_hists);\n  DeleteErrorCorHistograms(err_out_cor_hists);\n  PrintCurrentMemoryUsage(\"Test, end of function\");\n}\n\n\nvoid LHCOpticsApproximator::AllocateErrorHists(TH1D *err_hists[4])\n{\n  std::vector<std::string> error_labels;\n  error_labels.push_back(\"x error\");\n  error_labels.push_back(\"theta_x error\");\n  error_labels.push_back(\"y error\");\n  error_labels.push_back(\"theta_y error\");\n\n  for(int i=0; i<4; ++i)\n  {\n    err_hists[i] = new TH1D(error_labels[i].c_str(), error_labels[i].c_str(), 100, -0.0000000001, 0.0000000001);\n    err_hists[i]->SetXTitle(error_labels[i].c_str());\n    err_hists[i]->SetYTitle(\"counts\");\n    err_hists[i]->SetDirectory(0);\n    err_hists[i]->SetCanExtend(TH1::kAllAxes);\n  }\n}\n\n\nvoid LHCOpticsApproximator::TestAperture(TTree *inp_tree, TTree *out_tree)  //x, theta_x, y, theta_y, ksi, mad_accepted, parametriz_accepted\n{\n  if(inp_tree==NULL || out_tree==NULL)\n    return;\n\n  Long64_t entries = inp_tree->GetEntries();\n  double entry[7];\n  double parametrization_out[5];\n\n  inp_tree->SetBranchAddress(\"x\", &(entry[0]) );\n  inp_tree->SetBranchAddress(\"theta_x\", &(entry[1]) );\n  inp_tree->SetBranchAddress(\"y\", &(entry[2]) );\n  inp_tree->SetBranchAddress(\"theta_y\", &(entry[3]) );\n  inp_tree->SetBranchAddress(\"ksi\", &(entry[4]) );\n  inp_tree->SetBranchAddress(\"mad_accept\", &(entry[5]) );\n  inp_tree->SetBranchAddress(\"par_accept\", &(entry[6]) );\n\n  out_tree->SetBranchAddress(\"x\", &(entry[0]) );\n  out_tree->SetBranchAddress(\"theta_x\", &(entry[1]) );\n  out_tree->SetBranchAddress(\"y\", &(entry[2]) );\n  out_tree->SetBranchAddress(\"theta_y\", &(entry[3]) );\n  out_tree->SetBranchAddress(\"ksi\", &(entry[4]) );\n  out_tree->SetBranchAddress(\"mad_accept\", &(entry[5]) );\n  out_tree->SetBranchAddress(\"par_accept\", &(entry[6]) );\n\n//  int ind=0;\n  for(Long64_t i=0; i<entries; i++)\n  {\n    inp_tree->GetEntry(i);\n//    for(int j=0; j<7; j++)\n//      std::cout<<entry[j]<<\" \";\n//    std::cout<<std::endl;\n\n    bool res = Transport(entry, parametrization_out, true);\n//    for(int j=0; j<5; j++)\n//      std::cout<<parametrization_out[j]<<\" \";\n//    std::cout<<\"TestAperture \"<<res<<std::endl;\n\n    if( res )\n      entry[6] = 1.0;\n    else\n      entry[6] = 0.0;\n\n    out_tree->Fill();\n//    if(ind++>300)\n//      exit(0);\n  }\n}\n\n\nvoid LHCOpticsApproximator::AllocateErrorInputCorHists(TH2D *err_inp_cor_hists[4][5])\n{\n  std::vector<std::string> error_labels;\n  std::vector<std::string> data_labels;\n\n  error_labels.push_back(\"x error\");\n  error_labels.push_back(\"theta_x error\");\n  error_labels.push_back(\"y error\");\n  error_labels.push_back(\"theta_y error\");\n\n  data_labels.push_back(\"x input\");\n  data_labels.push_back(\"theta_x input\");\n  data_labels.push_back(\"y input\");\n  data_labels.push_back(\"theta_y input\");\n  data_labels.push_back(\"ksi input\");\n\n  for(int eri=0; eri<4; ++eri)\n  {\n    for(int dati=0; dati<5; ++dati)\n    {\n      std::string name = error_labels[eri] + \" vs. \" + data_labels[dati];\n      std::string title = name;\n      err_inp_cor_hists[eri][dati] = new TH2D(name.c_str(), title.c_str(), 100,-0.0000000001,0.0000000001,100,-0.0000000001,0.0000000001);\n      err_inp_cor_hists[eri][dati]->SetXTitle(error_labels[eri].c_str());\n      err_inp_cor_hists[eri][dati]->SetYTitle(data_labels[dati].c_str());\n      err_inp_cor_hists[eri][dati]->SetDirectory(0);\n      err_inp_cor_hists[eri][dati]->SetCanExtend(TH2::kAllAxes);\n    }\n  }\n}\n\nvoid LHCOpticsApproximator::AllocateErrorOutputCorHists(TH2D *err_out_cor_hists[4][5])\n{\n  std::vector<std::string> error_labels;\n  std::vector<std::string> data_labels;\n\n  error_labels.push_back(\"x error\");\n  error_labels.push_back(\"theta_x error\");\n  error_labels.push_back(\"y error\");\n  error_labels.push_back(\"theta_y error\");\n\n  data_labels.push_back(\"x output\");\n  data_labels.push_back(\"theta_x output\");\n  data_labels.push_back(\"y output\");\n  data_labels.push_back(\"theta_y output\");\n  data_labels.push_back(\"ksi output\");\n\n  for(int eri=0; eri<4; ++eri)\n  {\n    for(int dati=0; dati<5; ++dati)\n    {\n      std::string name = error_labels[eri] + \" vs. \" + data_labels[dati];\n      std::string title = name;\n      err_out_cor_hists[eri][dati] = new TH2D(name.c_str(), title.c_str(), 100,-0.0000000001,0.0000000001,100,-0.0000000001,0.0000000001);\n      err_out_cor_hists[eri][dati]->SetXTitle(error_labels[eri].c_str());\n      err_out_cor_hists[eri][dati]->SetYTitle(data_labels[dati].c_str());\n      err_out_cor_hists[eri][dati]->SetDirectory(0);\n      err_out_cor_hists[eri][dati]->SetCanExtend(TH2::kAllAxes);\n    }\n  }\n}\n\n\nvoid LHCOpticsApproximator::FillErrorHistograms(double errors[4], TH1D *err_hists[4])\n{\n  for(int i=0; i<4; ++i)\n  {\n    err_hists[i]->Fill(errors[i]);\n  }\n}\n\n\nvoid LHCOpticsApproximator::FillErrorDataCorHistograms(double errors[4], double var[5], TH2D *err_cor_hists[4][5])\n{\n  for(int eri=0; eri<4; ++eri)\n  {\n    for(int dati=0; dati<5; ++dati)\n    {\n      err_cor_hists[eri][dati]->Fill(errors[eri], var[dati]);\n    }\n  }\n}\n\n\nvoid LHCOpticsApproximator::DeleteErrorHists(TH1D *err_hists[4])\n{\n  for(int i=0; i<4; ++i)\n  {\n    delete err_hists[i];\n  }\n}\n\nvoid LHCOpticsApproximator::DeleteErrorCorHistograms(TH2D *err_cor_hists[4][5])\n{\n  for(int eri=0; eri<4; ++eri)\n  {\n    for(int dati=0; dati<5; ++dati)\n    {\n      delete err_cor_hists[eri][dati];\n    }\n  }\n}\n\n\nvoid LHCOpticsApproximator::WriteHistograms(TH1D *err_hists[4], TH2D *err_inp_cor_hists[4][5], TH2D *err_out_cor_hists[4][5], TFile *f_out, std::string base_out_dir)\n{\n  if(f_out==NULL)\n    return;\n\n  f_out->cd();\n  if(!gDirectory->cd(base_out_dir.c_str()))\n    gDirectory->mkdir(base_out_dir.c_str());\n\n  gDirectory->cd(base_out_dir.c_str());\n  gDirectory->mkdir(this->GetName());\n  gDirectory->cd(this->GetName());\n  gDirectory->mkdir(\"x\");\n  gDirectory->mkdir(\"theta_x\");\n  gDirectory->mkdir(\"y\");\n  gDirectory->mkdir(\"theta_y\");\n\n  gDirectory->cd(\"x\");\n  err_hists[0]->Write(\"\", TObject::kWriteDelete);\n  for(int i=0; i<5; i++)\n  {\n    err_inp_cor_hists[0][i]->Write(\"\", TObject::kWriteDelete);\n    err_out_cor_hists[0][i]->Write(\"\", TObject::kWriteDelete);\n  }\n\n  gDirectory->cd(\"..\");\n  gDirectory->cd(\"theta_x\");\n  err_hists[1]->Write(\"\", TObject::kWriteDelete);\n  for(int i=0; i<5; i++)\n  {\n    err_inp_cor_hists[1][i]->Write(\"\", TObject::kWriteDelete);\n    err_out_cor_hists[1][i]->Write(\"\", TObject::kWriteDelete);\n  }\n\n  gDirectory->cd(\"..\");\n  gDirectory->cd(\"y\");\n  err_hists[2]->Write(\"\", TObject::kWriteDelete);\n  for(int i=0; i<5; i++)\n  {\n    err_inp_cor_hists[2][i]->Write(\"\", TObject::kWriteDelete);\n    err_out_cor_hists[2][i]->Write(\"\", TObject::kWriteDelete);\n  }\n\n  gDirectory->cd(\"..\");\n  gDirectory->cd(\"theta_y\");\n  err_hists[3]->Write(\"\", TObject::kWriteDelete);\n  for(int i=0; i<5; i++)\n  {\n    err_inp_cor_hists[3][i]->Write(\"\", TObject::kWriteDelete);\n    err_out_cor_hists[3][i]->Write(\"\", TObject::kWriteDelete);\n  }\n  gDirectory->cd(\"..\");\n  gDirectory->cd(\"..\");\n}\n\nvoid LHCOpticsApproximator::PrintInputRange()\n{\n  const TVectorD* min_var = x_parametrisation.GetMinVariables();\n  const TVectorD* max_var = x_parametrisation.GetMaxVariables();\n\n  std::cout<<\"Covered input parameters range:\"<<std::endl;\n  for(int i=0; i<5; i++)\n  {\n    std::cout<<(*min_var)(i)<<\" < \"<<coord_names[i]<<\" < \"<<(*max_var)(i)<<std::endl;\n  }\n  std::cout<<std::endl;\n}\n\n\nbool LHCOpticsApproximator::CheckInputRange(double *in)  //x, thx, y, thy, ksi\n{\n  const TVectorD* min_var = x_parametrisation.GetMinVariables();\n  const TVectorD* max_var = x_parametrisation.GetMaxVariables();\n  bool res = true;\n\n  for(int i=0; i<5; i++)\n  {\n    res = res && in[i]>=(*min_var)(i) && in[i]<=(*max_var)(i);\n//    std::cout<<\"test ranges: \"<<in[i]<<\" \"<<(*min_var)(i)<<\" \"<<in[i]<<\" \"<<(*max_var)(i)<<std::endl;\n  }\n//  std::cout<<\"result dupa:\"<<res<<std::endl;\n  return res;\n}\n\n\nvoid LHCOpticsApproximator::AddRectEllipseAperture(const LHCOpticsApproximator &in, double rect_x, double rect_y, double r_el_x, double r_el_y)\n{\n  apertures_.push_back(LHCApertureApproximator(in, rect_x, rect_y, r_el_x, r_el_y, LHCApertureApproximator::RECTELLIPSE));\n}\n\n\n//////////////////////////////////////////////////////////////////\n\nLHCApertureApproximator::LHCApertureApproximator()\n{\n  rect_x_ = rect_y_ = r_el_x_ = r_el_y_ = 0.0;\n  ap_type_ = NO_APERTURE;\n}\n\n\nLHCApertureApproximator::LHCApertureApproximator(const LHCOpticsApproximator &in, double rect_x, double rect_y, double r_el_x, double r_el_y,\n        aperture_type type) : LHCOpticsApproximator(in)\n{\n  rect_x_ = rect_x;\n  rect_y_ = rect_y;\n  r_el_x_ = r_el_x;\n  r_el_y_ = r_el_y;\n  ap_type_ = type;\n}\n\nbool LHCApertureApproximator::CheckAperture(double *in)  //x, thx. y, thy, ksi\n{\n  double out[5];\n  bool result = Transport(in, out);\n//  std::cout<<\"in apreture: \"<<out[0]<<\" \"<<out[1]<<\" \"<<out[2]<<\" \"<<out[3]<<\" \"<<out[4]<<std::endl;\n//  std::cout<<rect_x_<<\", \"<<rect_y_<<\", \"<<r_el_x_<<\", \"<<r_el_y_<<\", \"<<ap_type_<<std::endl;\n\n//  std::cout<<\"LHCApertureApproximator::CheckAperture(double *in)  //x, thx. y, thy, ksi\"<<std::endl;\n  if(ap_type_==RECTELLIPSE)\n  {\n//    std::cout<<\"before cond. checked: \"<<result<<std::endl;\n    result = result && out[0]<rect_x_ && out[0]>-rect_x_ && out[2]<rect_y_ && out[2]>-rect_y_ &&\n        ( out[0]*out[0]/(r_el_x_*r_el_x_) + out[2]*out[2]/(r_el_y_*r_el_y_) < 1 );\n//    std::cout<<\"LHCApertureApproximator::CheckAperture(double *in)  //x, thx. y, thy, ksi\"<<std::endl;\n//    std::cout<<\"after cond. checked: \"<<result<<std::endl;\n  }\n  return result;\n}\n\n/*\nbool LHCApertureApproximator::CheckAperture(MadKinematicDescriptor *in)  //x, thx. y, thy, ksi\n{\n  MadKinematicDescriptor out;\n  bool result = Transport(in, &out);\n  if(ap_type_==RECTELLIPSE)\n  {\n\n    result = result && out.x<rect_x_ && out.x>-rect_x_ && out.y<rect_y_ && out.y>-rect_y_ &&\n        ( out.x*out.x/(r_el_x_*r_el_x_) + out.y*out.y/(r_el_y_*r_el_y_) < 1 );\n  }\n  return result;\n}\n*/\n\nvoid LHCOpticsApproximator::PrintOpticalFunctions()\n{\n  std::cout<<std::endl<<\"Linear terms of optical functions:\"<<std::endl;\n  for(int i=0; i<4; i++)\n  {\n    PrintCoordinateOpticalFunctions(*out_polynomials[i], coord_names[i], coord_names);\n  }\n}\n\nvoid LHCOpticsApproximator::PrintCoordinateOpticalFunctions(TMultiDimFet &parametrization, const std::string &coord_name, const std::vector<std::string> &input_vars)\n{\n  double in[5];\n  double out;\n  double d_out_d_in[5];\n  double d_par = 1e-5;\n  double bias = 0;\n\n  for(int j=0; j<5; j++)\n      in[j]=0.0;\n      \n  const TVectorD* min_var = x_parametrisation.GetMinVariables();\n  const TVectorD* max_var = x_parametrisation.GetMaxVariables();\n\n  bias = parametrization.Eval(in);\n\n  for(int i=0; i<5; i++)\n  {\n    for(int j=0; j<5; j++)\n      in[j]=0.0;\n\n    d_par = -((*max_var)[i]-(*min_var)[i])/10.0;\n    in[i] = d_par;\n    d_out_d_in[i] = parametrization.Eval(in);\n    in[i] = 0.0;\n    d_out_d_in[i] = d_out_d_in[i] - parametrization.Eval(in);\n    d_out_d_in[i] = d_out_d_in[i]/d_par;\n  }\n  std::cout<<coord_name<<\" = \"<<bias;\n  for(int i=0; i<5; i++)\n  {\n    std::cout<<\" + \"<<d_out_d_in[i]<<\"*\"<<input_vars[i];\n  }\n  std::cout<<std::endl;\n}\n\n\n\n//real angles in the matrix, MADX convention used only for input\nvoid LHCOpticsApproximator::GetLineariasedTransportMatrixX(\n    double mad_init_x, double mad_init_thx, double mad_init_y, double mad_init_thy, \n    double mad_init_xi, TMatrixD &transp_matrix, double d_mad_x, double d_mad_thx)\n{\n  double MADX_momentum_correction_factor = 1.0 + mad_init_xi;\n  transp_matrix.ResizeTo(2,2);\n  double in[5];\n  in[0] = mad_init_x;\n  in[1] = mad_init_thx;\n  in[2] = mad_init_y;\n  in[3] = mad_init_thy;\n  in[4] = mad_init_xi;\n  \n  double out[5];\n  \n  Transport(in, out);\n  double x1 = out[0];\n  double thx1 = out[1];\n  \n  in[0] = mad_init_x + d_mad_x;\n  Transport(in, out);\n  double x2_dx = out[0];\n  double thx2_dx = out[1];\n  \n  in[0] = mad_init_x;\n  in[1] = mad_init_thx + d_mad_thx;  //?\n  Transport(in, out);\n  double x2_dthx = out[0];\n  double thx2_dthx = out[1];\n  \n//  | dx/dx,   dx/dthx    |\n//  | dthx/dx, dtchx/dthx |\n  \n  transp_matrix(0,0) = (x2_dx-x1)/d_mad_x;\n  transp_matrix(1,0) = (thx2_dx-thx1)/(d_mad_x*MADX_momentum_correction_factor);\n  transp_matrix(0,1) = MADX_momentum_correction_factor*(x2_dthx-x1)/d_mad_thx;\n  transp_matrix(1,1) = (thx2_dthx-thx1)/d_mad_thx;\n}\n\n//real angles in the matrix, MADX convention used only for input\nvoid LHCOpticsApproximator::GetLineariasedTransportMatrixY(\n    double mad_init_x, double mad_init_thx, double mad_init_y, double mad_init_thy, \n    double mad_init_xi, TMatrixD &transp_matrix, double d_mad_y, double d_mad_thy)\n{\n  double MADX_momentum_correction_factor = 1.0 + mad_init_xi;\n  transp_matrix.ResizeTo(2,2);\n  double in[5];\n  in[0] = mad_init_x;\n  in[1] = mad_init_thx;\n  in[2] = mad_init_y;\n  in[3] = mad_init_thy;\n  in[4] = mad_init_xi;\n  \n  double out[5];\n  \n  Transport(in, out);\n  double y1 = out[2];\n  double thy1 = out[3];\n  \n  in[2] = mad_init_y + d_mad_y;\n  Transport(in, out);\n  double y2_dy = out[2];\n  double thy2_dy = out[3];\n  \n  in[2] = mad_init_y;\n  in[3] = mad_init_thy + d_mad_thy;  //?\n  Transport(in, out);\n  double y2_dthy = out[2];\n  double thy2_dthy = out[3];\n  \n//  | dy/dy,   dy/dthy    |\n//  | dthy/dy, dtchy/dthy |\n  \n  transp_matrix(0,0) = (y2_dy-y1)/d_mad_y;\n  transp_matrix(1,0) = (thy2_dy-thy1)/(d_mad_y*MADX_momentum_correction_factor);\n  transp_matrix(0,1) = MADX_momentum_correction_factor*(y2_dthy-y1)/d_mad_thy;\n  transp_matrix(1,1) = (thy2_dthy-thy1)/d_mad_thy;\n}\n\n//MADX convention used only for input\ndouble LHCOpticsApproximator::GetDx(\n    double mad_init_x, double mad_init_thx, double mad_init_y, double mad_init_thy, \n    double mad_init_xi, double d_mad_xi)\n{\n  double in[5];\n  in[0] = mad_init_x;\n  in[1] = mad_init_thx;\n  in[2] = mad_init_y;\n  in[3] = mad_init_thy;\n  in[4] = mad_init_xi;\n  \n  double out[5];\n  \n  Transport(in, out);\n  double x1 = out[0];\n  \n  in[4] = mad_init_xi + d_mad_xi;\n  Transport(in, out);\n  double x2_dxi = out[0];\n  double dispersion = (x2_dxi-x1)/d_mad_xi;\n  \n  return dispersion;\n}\n\n//MADX convention used only for input\n//angular dispersion\ndouble LHCOpticsApproximator::GetDxds(\n    double mad_init_x, double mad_init_thx, double mad_init_y, double mad_init_thy, \n    double mad_init_xi, double d_mad_xi)\n{\n  double MADX_momentum_correction_factor = 1.0 + mad_init_xi;\n  double in[5];\n  in[0] = mad_init_x;\n  in[1] = mad_init_thx;\n  in[2] = mad_init_y;\n  in[3] = mad_init_thy;\n  in[4] = mad_init_xi;\n  \n  double out[5];\n  \n  Transport(in, out);\n  double thx1 = out[1]/MADX_momentum_correction_factor;\n  \n  in[4] = mad_init_xi + d_mad_xi;\n  Transport(in, out);\n  double thx2_dxi = out[1]/MADX_momentum_correction_factor;\n  double dispersion = (thx2_dxi-thx1)/d_mad_xi;\n  \n  return dispersion;\n}\n", "meta": {"hexsha": "46ae1ada5f4461fe0782b54915c14d7f45565bd7", "size": 39620, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/root_classes/src/LHCOpticsApproximator.cc", "max_stars_repo_name": "mucharafal/optics_generator_python", "max_stars_repo_head_hexsha": "c14d4e5f19f921f4dc0a98129bca9d31754b72ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/root_classes/src/LHCOpticsApproximator.cc", "max_issues_repo_name": "mucharafal/optics_generator_python", "max_issues_repo_head_hexsha": "c14d4e5f19f921f4dc0a98129bca9d31754b72ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/root_classes/src/LHCOpticsApproximator.cc", "max_forks_repo_name": "mucharafal/optics_generator_python", "max_forks_repo_head_hexsha": "c14d4e5f19f921f4dc0a98129bca9d31754b72ad", "max_forks_repo_licenses": ["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.7543859649, "max_line_length": 284, "alphanum_fraction": 0.7045683998, "num_tokens": 12179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2791957695792195}}
{"text": "/// @file  triangle.hpp\n/// @brief Declarations for methods based on triangle constraints\n\n#pragma once\n#ifndef OGT_EMBED_TRIANGLE_HPP\n#define OGT_EMBED_TRIANGLE_HPP\n\n#include <ogt/config.hpp>\n#include <ogt/core/collection.hpp>\n#include <ogt/embed/embed.hpp>\n#include <Eigen/Dense>\n#include <iostream>\n#include <json.hpp>\n#include <memory>\n#include <vector>\n\nusing OGT_NAMESPACE::core::Collection;\nusing OGT_NAMESPACE::core::Oracle;\nusing OGT_NAMESPACE::core::Traversal;\n\nnamespace OGT_NAMESPACE {\nnamespace embed {\n\nstruct CmpConstraint; // Forward declaration\n\n/// A triangle with two edges' lengths constrained to be scaled to within some\n/// interval of the length of the third edge.\nstruct TriangleConstraint {\n\n\t/// Initializing constructor\n\tTriangleConstraint(size_t p, size_t x, size_t y, double xmin,\n\t\tdouble xmax, double ymin, double ymax)\n\t\t: p(p), x(x), y(y), xmin(xmin), xmax(xmax), ymin(ymin), ymax(ymax)\n\t{\n\t}\n\n\t/// Initialize from a vector, e.g. loaded from .csv\n\tTriangleConstraint(const Eigen::VectorXd& vec)\n\t\t: p(vec(0)), x(vec(1)), y(vec(2)), xmin(vec(3)), xmax(vec(4))\n\t\t, ymin(vec(5)), ymax(vec(6))\n\t{\n\t}\n\n\t/// Elementwise equality test\n\tbool operator==(const TriangleConstraint& other) const {\n\t\treturn p == other.p && x == other.x && y == other.y\n\t\t\t&& xmin == other.xmin && xmax == other.xmax && ymin == other.ymin\n\t\t\t&& ymax == other.ymax;\n\t}\n\n\t/// Tighten the constraint using the triangle inequality.\n\t///\n\t/// We can update xmin and ymin as follows.\n\t/// ~~~~\n\t/// xy <= px + py <= px + xy * ymax\n\t///    --> px >= xy(1 - ymax)\n\t///    --> px >= xy * max(xmin, 1 - ymax)\n\t///    --> py >= xy * max(ymin, 1 - xmax) (by symmetry)\n\t/// ~~~~\n\tvoid tighten();\n\n\t/// Rotate the constraint to use a different edge as the reference distance.\n\t/// If toX is true, the output's p will be the input's x point. Otherwise,\n\t/// the output's p will be the input's y point.\n\t///\n\t/// The update rule is derived as follows.\n\t/// ~~~~\n\t/// xmin <= px/xy <= xmax\n\t///     --> 1/xmax <= xy/px <= 1/xmin\n\t/// py <= ymax * xy\n\t///    <= ymax * px / xmin\n\t///    --> ymin / xmax <= py/px <= ymax / xmin\n\t/// ~~~~\n\tTriangleConstraint rotate(bool toX, double maxRatio = INFINITY) const;\n\n\t/// The point incident to the two constrained edges.\n\tsize_t p;\n\n\t/// One of the points incident to the reference edge.\n\tsize_t x;\n\n\t/// One of the points incident to the reference edge.\n\tsize_t y;\n\n\t/// A lower bound on the ratio dist(p,x) / dist(x,y)\n\tdouble xmin;\n\n\t/// An upper bound on the ratio dist(p,x) / dist(x,y)\n\tdouble xmax;\n\n\t/// A lower bound on the ratio dist(p,y) / dist(x,y)\n\tdouble ymin;\n\n\t/// An upper bound on the ratio dist(p,y) / dist(x,y)\n\tdouble ymax;\n};\n\n/// Manages distance intervals from a set of constraints.\nstruct DistIntervals {\n\n\t/// Initialize to NaN matrices.\n\tDistIntervals(size_t nObj);\n\n\t/// Set the specified distance and interval width\n\tvoid set(Eigen::Index ii, Eigen::Index jj, double dmin, double dmax);\n\n\t/// Set the appropriate entries from a constraint, if the reference distance\n\t/// is already set. Returns true if successful.\n\tbool setFromCon(const TriangleConstraint& con);\n\n\t/// The center of each interval. Can be used as distance estimates.\n\t/// Uninitialized elements have the value NaN.\n\tEigen::MatrixXd D;\n\n\t/// The width of each interval.\n\t/// Uninitialized elements have the value NaN.\n\tEigen::MatrixXd W;\n};\n\n/// Stream a constraint to output\nstd::ostream& operator<<(std::ostream& os, const TriangleConstraint& con);\n\n/// Sorts constraints into the order needed for embedTrianglesWithSpheres().\n/// Throws std::invalid_argument on failure.\nvoid sortTriangleConstraints(std::vector<TriangleConstraint>& cons, bool prune);\n\n/// Validate the triangle constraints to determine whether they fully specify\n/// an embedding in some dimensionality.\nbool validateTriangleConstraints(const std::vector<TriangleConstraint>& cons,\n\tnlohmann::json* json);\n\n/// The algorithm to use when selecting reference edges for triangle constraints\nenum EdgeMethod {\n\n\t/// Pair farthest edges together\n\tEdgeFarthest,\n\n\t/// Select edges by density\n\tEdgeByDensity,\n\n\t/// Select all edges\n\tEdgeByAll,\n\n\t/// Recurse into local regions based on density rules\n\tEdgeByLocality\n};\n\n/// Find triangular constraints for a collection, using some traversal order to\n/// identify reference edges. The first point on an edge will be selected by the\n/// order, and the second point will be the farthest point from it.\n/// If visitBoth = true, the second point will be visited for each edge.\n/// This is useful for Collection::frftTraversal() and\n/// Collection::stopWhenAffDep(), but not for Collection::stopAfter().\nstd::vector<TriangleConstraint> findTriangleConstraints(\n\tstd::shared_ptr<Collection> coll, Traversal order, size_t nDim,\n\tbool visitBoth, bool basicIntervals, EdgeMethod edges);\n\n/// Find triangular constraints for a collection with reference to some pair.\nstd::vector<TriangleConstraint> findTriangleConstraints(\n\tstd::shared_ptr<Collection> coll, size_t pt1, size_t pt2,\n\tbool basicIntervals);\n\n/// Find triangular constraints using the specified distance matrix.\n/// The constraints will be the correct distances plus/minus eps.\n/// Useful for testing.\nstd::vector<TriangleConstraint> findTriangleConstraints(\n\tconst Eigen::MatrixXd& dists, double eps, size_t nRef);\n\n/// Update triangle constraints using distances from an embedding of a subset\n/// of the objects.\nstd::vector<TriangleConstraint> updateTriangleConstraints(\n\tconst std::vector<TriangleConstraint>& inCons,\n\tstd::shared_ptr<Oracle> ranker, const Eigen::MatrixXd& pos,\n\tconst Eigen::VectorXd& objects);\n\n/// Load triangle constraints from a data file.\nstd::vector<TriangleConstraint> loadTriangleConstraints(std::string path);\n\n/// Count the number of violated triangle constraints.\nsize_t numBadTriangles(const std::vector<TriangleConstraint>& cons,\n\tconst Eigen::MatrixXd& dists);\n\n/// Calculate the loss for a single constraint\ndouble triangleLoss(const TriangleConstraint& con,\n\tconst Eigen::MatrixXd& dists);\n\n/// Calculate the loss for a set of triangle constraints and distances.\ntemplate<class Container>\ndouble triangleLoss(const Container& cons, const Eigen::MatrixXd& dists) {\n\tdouble loss = 0;\n\tfor (const TriangleConstraint& con : cons) {\n\t\tloss += triangleLoss(con, dists);\n\t}\n\treturn loss;\n}\n\n/// Calculate the loss for a set of triangle constraints and distances.\ntemplate<class ForwardIterator>\ndouble triangleLoss(ForwardIterator begin, ForwardIterator end,\n\tconst Eigen::MatrixXd& dists) {\n\tdouble loss = 0;\n\tfor (auto it = begin; it != end; it++) {\n\t\tloss += triangleLoss(*it, dists);\n\t}\n\treturn loss;\n}\n\n/// Sorts constraints into the order needed for embedTrianglesWithSpheres()\n/// and embedTrianglesWithShells().\n/// Throws std::invalid_argument on failure.\nvoid sortConstraints(std::vector<TriangleConstraint>& cons, bool addRotations,\n\tdouble maxRotationRatio);\n\n/// Reduce constraint bounds based on embedded coordinates.\n/// Used for embedTrianglesWithSpheres() and embedTrianglesWithShells().\nstd::vector<TriangleConstraint> tightenConstraints(\n\tconst std::map<size_t,std::vector<const TriangleConstraint*>> conMap,\n\tconst Eigen::MatrixXd& X);\n\n/// Find an embedding in R^nDim consistent with the triangle ratio constraints.\n/// This method may throw EmbedErr on some errors.\n///\n/// This method works by first positioning the reference distances, and then\n/// placing all the other points with respect to them.\n/// It therefore requires that there be an ordering of reference distances such\n/// that the points in each distance are constrained by the prior distances.\n/// The points of the first reference distance are placed, arbitrarily, at the\n/// origin (0, 0, 0, 0, ...) and the first elementary vector (1, 0, 0, 0, ...).\n/// The method will attempt to find an ordering of constraints to satisfy its\n/// needs, and will throw std::invalid_argument when it can't.\n/// The constraints returned by findTriangleConstraints() when it is passed some\n/// traversal order are generally valid input.\nEmbedResult embedTrianglesWithSpheres(\n\tstd::vector<TriangleConstraint> cons, EmbedConfig config);\n\n/// Find an embedding in R^nDim consistent with the triangle ratio constraints.\n/// This method may throw EmbedErr on some errors.\n///\n/// This method works similarly to embedTrianglesWithSpheres(), but takes the\n/// spherical shells into account instead of simply aiming for the center of\n/// each shell.\nEmbedResult embedTrianglesWithShells(\n\tstd::vector<TriangleConstraint> cons, EmbedConfig config);\n\n/// Find an embedding in R^d (d = X0.cols()) consistent with the triangle\n/// ratio constraints.\n/// This approach uses a quasi-newton method (L-BFGS) to minimize a loss\n/// function defined in terms of the constraints.\n/// Returns the embedding and the loss achieved.\nEmbedResult embedTrianglesWithOpt(\n\tstd::vector<TriangleConstraint> cons, const Eigen::MatrixXd& X0,\n\tEmbedConfig config);\n\n/// Find an embedding in R^d consistent with the triangle ratio constraints.\n/// Distances are found to a set of d+1 reference vertices using the triangle\n/// constraints, and then the set is embedded from the distances.\nEmbedResult embedTrianglesWithCM(std::vector<TriangleConstraint> cons,\n\tEmbedConfig config);\n\n/// Embeds a dataset using a mixture of triangles and comparisons.\nEmbedResult embedTrianglesWithMixture(std::vector<TriangleConstraint> tris,\n\tstd::vector<CmpConstraint> cmps, double lambda, const Eigen::MatrixXd& X0,\n\tEmbedConfig config);\n\n} // end namespace embed\n} // end namespace OGT_NAMESPACE\n#endif /* OGT_EMBED_TRIANGLE_HPP */\n", "meta": {"hexsha": "0941f9fbc0712b1a4f8dfee2fce9baf9cfecee21", "size": 9578, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ogt/embed/triangle.hpp", "max_stars_repo_name": "jesand/lloe", "max_stars_repo_head_hexsha": "66235b16fb8cfbb39f72a289c320e701bde94159", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-11T21:31:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-30T09:23:04.000Z", "max_issues_repo_path": "include/ogt/embed/triangle.hpp", "max_issues_repo_name": "jesand/lloe", "max_issues_repo_head_hexsha": "66235b16fb8cfbb39f72a289c320e701bde94159", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ogt/embed/triangle.hpp", "max_forks_repo_name": "jesand/lloe", "max_forks_repo_head_hexsha": "66235b16fb8cfbb39f72a289c320e701bde94159", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-11T21:31:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-27T20:57:26.000Z", "avg_line_length": 35.7388059701, "max_line_length": 80, "alphanum_fraction": 0.7346001253, "num_tokens": 2239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2791634971676872}}
{"text": "#include <Eigen/Dense>\n#include \"mex.h\"\n#include \"math.h\"\n#include <iostream>\n#include <omp.h>\n#include <vector>\n#include \"MinIndexedPQ.h\"\n\nusing namespace std;\n\nusing Eigen::Matrix2d;\nusing Eigen::Vector2d;\nusing Eigen::VectorXd;\nusing Eigen::SelfAdjointEigenSolver;\nusing Eigen::Map;\n\n// To cache the dot products that we need to compute between the\n// query image features and the predictor image features.  Each\n// cachecell is associated with one locaton in the query image\nstruct CacheCell{\n  // stores the locations in the predictor image where the\n  // cache is valid\n  int xmin;\n  int ymin;\n  int xmax;\n  int ymax;\n  // The actual dot products.\n  double* data;\n  CacheCell():xmin(0),ymin(0),xmax(0),ymax(0),data(NULL){}\n};\n\nvector<vector<CacheCell> > cache;\n\n//extern bool mxUnshareArray(const mxArray *pr, const bool noDeepCopy);\n\nmxArray* getfield(mxArray* str, const string& fnam){\n  int field_num = mxGetFieldNumber(str, fnam.c_str());\n  return mxGetFieldByNumber(str, 0, field_num);\n}\n\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {\n  // Note that you should disable the parallel loop\n  // before you enable debugging, or you will get segfaults!\n  const bool DEBUG=false;\n  // TODO: The first thing this mex function does is make a copy of its\n  // input, which is really stupid because the structure of corresp does\n  // not change, and the old values don't need to be kept.  Supposedly\n  // these lines will let you avoid the copy, but I haven't tested it.\n  //mxUnshareArray(const_cast<mxarray*> prhs[1],false);\n  //mxArray* corresp=const_cast<mxarray*>(prhs[1]);\n  mxArray* corresp=mxDuplicateArray(prhs[1]);\n  int maxupdates = (int) mxGetScalar(prhs[3]);\n  const mxArray* hogim = prhs[0];\n  const int* hogimdims=mxGetDimensions(hogim);\n  double* hogdata = mxGetPr(hogim);\n  int ndims=hogimdims[0];\n  int hogrows=hogimdims[1];\n  int hogcols=hogimdims[2];\n  int npyrs=* mxGetDimensions(prhs[2]);\n  int* correspidx=(int *) mxGetData(prhs[4]);\n  bool* inferred=(bool*)mxGetData(prhs[5]);\n  int* inferinds=(int *)mxGetData(prhs[6]);\n  int ntoinfer=*mxGetDimensions(prhs[6]);\n  double* confidences = mxGetPr(prhs[7]);\n  double lambda = mxGetScalar(prhs[8]);\n  bool deleteCache = mxGetScalar(prhs[9])!=0;\n  double* numneighbors = mxGetPr(prhs[10]);\n  double lambdaprime = mxGetScalar(prhs[11]);\n  if(DEBUG){mexPrintf(\"lam2 %f\\n\",lambda);mexEvalString(\"drawnow;\");}\n  if(DEBUG){mexPrintf(\"%d %d\\n\",ntoinfer,npyrs);}\n  double** transf_out = new double*[npyrs];\n  int ntransfs=0;\n  // if deleteCache is 1, we're starting a new image, so clear out all\n  // the cached dot products.\n  if(deleteCache){\n    for(int i = 0; i<cache.size(); ++i){\n      for(int j=0; j<cache[i].size(); ++j){\n        delete cache[i][j].data;\n      }\n    }\n    cache.clear();\n  }\n  if(cache.size()==0){\n    for(int i = 0; i<npyrs; ++i){\n      cache.push_back(vector<CacheCell>(hogrows*hogcols));\n    }\n  }\n  int cachehit=0;\n  int cachemiss=0;\n  string errmsg=\"\";\n  bool error=false;\n  if(DEBUG){mexPrintf(\"start main loop over pyramids\\n\");}\n\n  // Each pyramid's correspondence can be inferred in parallel.\n  #pragma omp parallel for reduction(+:cachehit,cachemiss) shared(error,errmsg)\n  for(int pyridx=0; pyridx<npyrs; ++pyridx){\n    // These help us estimate when we need to return,\n    // first by counting the number of times we've updated a \n    // mu and sigma pair, and second by seeing how long it's\n    // been since something moved a lot.\n    int nupdates=0;\n    int nsincebigmove=0;\n\n    // transf==alpha in the paper.  Figure out which cells need to have an\n    // alpha value inferred before we can start updating mu's and sigmas.  \n    // alpha's aren't kept around between calls to optimizecorresp, so\n    // when we begin we need to infer an alpha for every cell in the \n    // condition region.\n    // \n    // Likewise, cellheap associates with each cell an estimate of how\n    // much that cell will change if it's updated.  We attempt to update\n    // first any cell that seems like it will move a lot; this lets us\n    // focus our computation on the parts of f that make the biggest\n    // difference.\n    vector<int> mustcomptransf;\n    MinIndexedPQ cellheap(hogrows*hogcols);\n    for(int ti = 0; ti<ntoinfer; ++ti){\n      mustcomptransf.push_back(inferinds[ti]);\n      cellheap.insert(inferinds[ti],-1000000);\n    }\n    vector<Matrix2d> transfs(hogrows*hogcols);\n    if(DEBUG){cout<<\"start main optimization loop\\n\";}\n    // On each iteration of this loop, we update one mu and one sigma.\n    while(!error){\n      ++nupdates;\n      ++nsincebigmove;\n\n      // However, we may need to compute updates for many alphas, especially\n      // at the beginning.\n      for(int ti=0; ti<mustcomptransf.size(); ++ti){\n        int infidx=mustcomptransf[ti];\n        int xpos=infidx/hogrows;\n        int ypos=infidx-xpos*hogrows;\n        Matrix2d xsigma=Matrix2d::Zero();\n        Matrix2d ysigma=Matrix2d::Zero();\n        Vector2d xb=Vector2d::Zero();\n        Vector2d yb=Vector2d::Zero();\n        // Iterate over the edges of the lattice that this \\alpha participates\n        // in.  We aggregate statistics for both vertical and horizontal edges\n        // simultaneously.  xsigma/ysigma aggregate the quadratic term\n        // of equation 15, and xb/yb aggregate the linear term.\n        for(int edgex=-2; edgex<=2; ++edgex){\n          for(int edgey=-2; edgey<=2; ++edgey){\n            if(edgex>-2&&edgex+xpos-1>=0&&edgex+xpos<hogcols&&edgey+ypos>=0&&edgey+ypos<hogrows &&\n                  inferred[edgey+ypos+hogrows*(edgex+xpos-1)]&&inferred[edgey+ypos+hogrows*(edgex+xpos)]){\n              mxArray* othcorresp=mxGetCell(corresp,edgey+ypos+(edgex+xpos)*hogrows);\n              mxArray* othcorresp2=mxGetCell(corresp,edgey+ypos+(edgex+xpos-1)*hogrows);\n              Map<Vector2d> othmu(mxGetPr(mxGetFieldByNumber(othcorresp, 0, 0))+2*pyridx);\n              Map<Matrix2d> othcovar(mxGetPr(mxGetFieldByNumber(othcorresp, 0, 1))+4*pyridx);\n              Map<Vector2d> othmu2(mxGetPr(mxGetFieldByNumber(othcorresp2, 0, 0))+2*pyridx);\n              Map<Matrix2d> othcovar2(mxGetPr(mxGetFieldByNumber(othcorresp2, 0, 1))+4*pyridx);\n              xsigma=xsigma+(othcovar.inverse()+othcovar2.inverse());\n              xb=xb+(othcovar.inverse()+othcovar2.inverse())*(othmu-othmu2);\n            }\n            if(edgey>-2&&edgex+xpos>=0&&edgex+xpos<hogcols&&edgey+ypos-1>=0&&edgey+ypos<hogrows &&\n                  inferred[edgey+ypos-1+hogrows*(edgex+xpos)]&&inferred[edgey+ypos+hogrows*(edgex+xpos)]){\n              mxArray* othcorresp=mxGetCell(corresp,edgey+ypos+(edgex+xpos)*hogrows);\n              mxArray* othcorresp2=mxGetCell(corresp,edgey+ypos-1+(edgex+xpos)*hogrows);\n              Map<Vector2d> othmu(mxGetPr(mxGetFieldByNumber(othcorresp, 0, 0))+2*pyridx);\n              Map<Matrix2d> othcovar(mxGetPr(mxGetFieldByNumber(othcorresp, 0, 1))+4*pyridx);\n              Map<Vector2d> othmu2(mxGetPr(mxGetFieldByNumber(othcorresp2, 0, 0))+2*pyridx);\n              Map<Matrix2d> othcovar2(mxGetPr(mxGetFieldByNumber(othcorresp2, 0, 1))+4*pyridx);\n              ysigma=ysigma+(othcovar.inverse()+othcovar2.inverse());\n              yb=yb+(othcovar.inverse()+othcovar2.inverse())*(othmu-othmu2);\n            }\n          }\n        }\n        transfs[ypos+xpos*hogrows].leftCols(1)=(xsigma).colPivHouseholderQr().solve(xb);\n        transfs[ypos+xpos*hogrows].rightCols(1)=(ysigma).colPivHouseholderQr().solve(yb);\n        if(DEBUG){cout<<\"xsig\\n\"<<xsigma<<\"\\nxb\\n\"<<xb<<\"\\ntransfs\\n\"<<transfs[ypos+xpos*hogrows]<<\"\\n\";}\n      }\n      mustcomptransf.clear();\n\n      if(DEBUG){cout<<\"start computing sigma's\\n\";}\n      mxArray *mypyr=getfield(mxGetCell(prhs[2],pyridx),\"features\");\n      // Get the linear index of the next mu/sigma pair to optimize, and store the estimated\n      // change.\n      double heapdist=cellheap.minKey();\n      int infidx=cellheap.deleteMin();\n      mxArray* mycorresp=mxGetCell(corresp,infidx);\n      int edgex=1;\n      int edgey=0;\n      int xpos=infidx/hogrows;\n      int ypos=infidx-xpos*hogrows;\n      if(DEBUG){mexPrintf(\"get predictor feats\\n\");mexEvalString(\"drawnow;\");}\n      if(DEBUG){mexPrintf(\"%f\\n\",mxGetPr(mxGetFieldByNumber(mycorresp,0,2))[pyridx]);}\n      mxArray* othhogarr=mxGetCell(mypyr,mxGetPr(mxGetFieldByNumber(mycorresp,0,2))[pyridx]-1);\n      double* othhog=mxGetPr(othhogarr);\n      const int* othhogdims=mxGetDimensions(othhogarr);\n      int othrows=othhogdims[1];\n      int othcols=othhogdims[2];\n      // relsigma aggregates both Sigma in equation 21 and the outer product in equation 23.\n      Matrix2d relsigma = Matrix2d::Zero();\n      // relsigmainv aggregates inv(Sigma) in equation 21.\n      Matrix2d relsigmainv = Matrix2d::Zero();\n      if(DEBUG){mexPrintf(\"iterate over neighbors\\n\");mexEvalString(\"drawnow;\");}\n      Map<Vector2d> mymu(mxGetPr(mxGetFieldByNumber(mycorresp, 0, 0))+2*pyridx);\n      Map<Matrix2d> mycovar(mxGetPr(mxGetFieldByNumber(mycorresp, 0, 1))+4*pyridx);\n      // We first iterate over edges\n      for(int edgeidx=0; edgeidx<4; ++edgeidx){\n        if(DEBUG){mexPrintf(\"%d %d %d %d %d %d\\n\",edgex, edgey, xpos, ypos, hogrows, hogcols);}\n        if(edgex+xpos>=0&&edgex+xpos<hogcols&&edgey+ypos>=0&&edgey+ypos<hogrows &&\n          inferred[edgey+ypos+hogrows*(edgex+xpos)]){\n          mxArray* othcorresp=mxGetCell(corresp,edgey+ypos+(edgex+xpos)*hogrows);\n          Map<Vector2d> othmu(mxGetPr(mxGetFieldByNumber(othcorresp, 0, 0))+2*pyridx);\n          Map<Matrix2d> othcovar(mxGetPr(mxGetFieldByNumber(othcorresp, 0, 1))+4*pyridx);\n          Vector2d edge;\n          edge << edgex, edgey;\n          Matrix2d relsigmainv2=Matrix2d::Zero();\n          Matrix2d relsigma2=Matrix2d::Zero();\n          double n=0.0;\n          // Then we iterate over the \\alpha's that give us constraints over these edges\n          for(int transfx=max(0,max(xpos,xpos+edgex)-2);transfx<=min(hogcols-1,min(xpos,xpos+edgex)+2); ++transfx){\n            for(int transfy=max(0,max(ypos,ypos+edgey)-2);transfy<=min(hogrows-1,min(ypos,ypos+edgey)+2); ++transfy){\n                if(DEBUG){cout << \"tx \" << transfx << \" ty \" <<transfy << \"\\n\";}\n              if(inferred[transfy+hogrows*(transfx)]){\n                Vector2d mudiff=othmu-mymu-transfs[transfy+(transfx)*hogrows]*edge;\n                if(DEBUG){cout << \"othmu\\n\" << othmu << \"\\n\" << mymu << \"\\n\" << edge << \"\\ntransf\\n\"<<transfs[transfy+(transfx)*hogrows]<<\"\\n\";}\n                relsigma2=relsigma2+(othcovar+mudiff*mudiff.transpose())*lambdaprime;\n                relsigmainv2=relsigmainv2+othcovar.inverse()*lambdaprime;\n                n+=1.0;\n              }\n            }\n          }\n          // n is very nearly a constant and so in the paper I just rolled into lambdaprime.  However,\n          // near the edge n will get smaller, and so dividing by n will give the warping\n          // a little boost near the edge where there are fewer alpha's affecting each\n          // edge.  \n          relsigma=relsigma+relsigma2/n;\n          relsigmainv=relsigmainv+relsigmainv2/n;\n          Vector2d mudiff=othmu-mymu-edge;\n          relsigma=relsigma+(othcovar+mudiff*mudiff.transpose())*lambda;\n          relsigmainv=relsigmainv+othcovar.inverse()*lambda;\n        }\n        // We rotate the edge to get the next edge in the sequence.\n        int tmp=edgey;\n        edgey=edgex;\n        edgex=-tmp;\n      }\n\n      // Next we need to aggregate the unary terms.  We actually do an e-step (equation 13) as we\n      // go along; the values computed on the e-step are not stored.  \n      //\n      // First we need to compute a small region over which we should aggregate our statistics.\n      // we use the same major/minor axis trick that we used in contextpredict to get\n      // the window.\n      SelfAdjointEigenSolver<Matrix2d> eigensolver(mycovar);\n      Matrix2d V=eigensolver.eigenvectors().cwiseAbs();\n      Vector2d D=eigensolver.eigenvalues();\n      double mycovardet=mycovar.determinant();\n      if(DEBUG){mexPrintf(\"computing eigenvalues 1\\n\");mexEvalString(\"drawnow;\");}\n      Matrix2d mycovarinv=mycovar.inverse();\n      double dist=sqrt(fabs(1/(((1/(log(.0001)+log(mycovardet)/2))*(V.block(0,0,2,1).transpose()*mycovarinv*V.block(0,0,2,1)/2))(0))));\n      double dist2=sqrt(fabs(1/(((1/(log(.0001)+log(mycovardet)/2))*(V.block(0,1,2,1).transpose()*mycovarinv*V.block(0,1,2,1)/2))(0))));\n      if(DEBUG){mexPrintf(\"%f %f\\n\",dist,dist2);}\n      Vector2d distvec = dist*V.block(0,0,2,1).cwiseMax(dist2*V.block(0,1,2,1));\n      Map<VectorXd> mydata(hogdata+ndims*ypos+ndims*hogrows*xpos,ndims-1);\n      double myconst = *(hogdata+ndims*ypos+ndims*hogrows*xpos+ndims-1);\n      VectorXd mydatatransf=mydata;\n      double sumprob=0;\n      Matrix2d sumwt = Matrix2d::Zero();\n      if(DEBUG){mexPrintf(\"5\\n\");mexEvalString(\"drawnow;\");}\n      //NOTE: window is in 1-indexed coordinates\n      if(DEBUG){cout << distvec << \"\\n\";}\n      int xmin=floor(mymu(0)-min(distvec(0),30.0));\n      int xmax=ceil(mymu(0)+min(distvec(0),30.0));\n      int ymin=floor(mymu(1)-min(distvec(1),30.0));\n      int ymax=ceil(mymu(1)+min(distvec(1),30.0));\n      if(DEBUG){mexPrintf(\"5.1\\n\");mexEvalString(\"drawnow;\");}\n\n      // Now that we have the window, check to see if we have all the dot\n      // products in that window cached.  We make sure that no more than 1/5\n      // of the region that we need to compute is hanging outside of the\n      // region stored in the cache on each side.\n      CacheCell& mycache=cache[pyridx][hogrows*xpos+ypos];\n      bool createcache=false;\n      double* cachedata;\n      if(DEBUG){mexPrintf(\"5.2\\n\");mexEvalString(\"drawnow;\");}\n      if(mycache.data!=NULL&&mycache.xmin<xmin+(xmax-xmin)/5&&mycache.ymin<ymin+(ymax-ymin)/5&&\n         mycache.xmax>xmin+((xmax-xmin)*4+4)/5&&mycache.ymax>ymin+((ymax-ymin)*4+4)/5){\n         ++cachehit;\n      }else{\n        ++cachemiss;\n        createcache=true;\n        mycache.xmin=xmin;\n        mycache.ymin=ymin;\n        mycache.xmax=xmax;\n        mycache.ymax=ymax;\n        if(mycache.data!=NULL){\n          delete mycache.data;\n        }\n        mycache.data=new double[(ymax-ymin+1)*(xmax-xmin+1)];\n      }\n      if(DEBUG){mexPrintf(\"5.3\\n\");mexEvalString(\"drawnow;\");}\n      cachedata=mycache.data;\n      if(DEBUG){mexPrintf(\"5.4\\n\");mexEvalString(\"drawnow;\");}\n\n      // Loop over the cache or the window, computing the inner products\n      // and summing the total probability as required in equation 19.\n      for(int windowx = max(xmin,mycache.xmin); windowx<=min(xmax,mycache.xmax); ++windowx){\n        for(int windowy = max(ymin,mycache.ymin); windowy<=min(ymax,mycache.ymax); ++windowy){\n          Vector2d window;\n          window << windowx,windowy;\n          Vector2d pt=window-mymu;\n          double prob=1/(2*M_PI*sqrt(mycovardet))*exp((-pt.transpose()*mycovarinv*pt)(0)/2);\n          if(prob!=prob){\n            if(DEBUG){mexPrintf(\"%d\\n\",mycovardet);}\n            errmsg=\"nan prob\";\n            if(DEBUG){mexErrMsgTxt(errmsg.c_str());}\n            error=1;\n            continue;\n          }\n          double tmpprob;\n          if(createcache){\n            int idx=ndims*(min(othrows-1,max(0,windowy-1))+min(othcols-1,max(0,windowx-1))*othrows);\n            Map<VectorXd> othdata(othhog+idx,ndims-1);\n            tmpprob = exp(-(mydatatransf.dot(othdata)+myconst)/2);\n            tmpprob=tmpprob/(tmpprob+.01*(*(othhog+idx+ndims-1)));\n            cachedata[(windowx-xmin)*(ymax-ymin+1)+windowy-ymin]=tmpprob;\n            if(prob!=prob){\n              if(DEBUG){mexPrintf(\"%f %f %f %f\\n\",tmpprob,myconst,mydatatransf.dot(othdata),*(othhog+idx+ndims-1));}\n              if(DEBUG){cout<<\"othdata\\n\"<<othdata<<\"\\nmydata\\n\"<<mydata<<\"\\n\";}\n              errmsg=\"nan prob v2\";\n              if(DEBUG){mexErrMsgTxt(errmsg.c_str());}\n              error=1;\n              continue;\n            }\n          }else{\n            tmpprob=cachedata[(windowx-mycache.xmin)*(mycache.ymax-mycache.ymin+1)+windowy-mycache.ymin];\n          }\n\n          prob=prob*tmpprob;\n          sumprob+=prob;\n          sumwt=sumwt+prob*pt*(pt.transpose());\n        }\n      }\n      if(DEBUG){mexPrintf(\"6\\n\");mexEvalString(\"drawnow;\");}\n      if(DEBUG){mexPrintf(\"sumwt\\n\");mexEvalString(\"drawnow;\");}\n      if(DEBUG){cout << sumwt << \"\\n\" << sumprob << \"\\n\";}\n      if(DEBUG){mexPrintf(\"relsigma\\n\");mexEvalString(\"drawnow;\");}\n      if(DEBUG){cout << relsigma << \"\\n\";}\n      if(DEBUG){mexPrintf(\"sumwt\\n\");mexEvalString(\"drawnow;\");}\n      if(DEBUG){cout << sumwt << \"\\n\";}\n      if(DEBUG){mexPrintf(\"relsigmainv\\n\");mexEvalString(\"drawnow;\");}\n      if(DEBUG){cout << relsigmainv << \"\\n\";}\n      if(DEBUG){mexPrintf(\"mycovarinv\\n\");mexEvalString(\"drawnow;\");}\n      if(DEBUG){cout << mycovarinv << \"\\n\";}\n      double myconfidence = confidences[ypos+hogrows*(xpos)];\n      if(DEBUG){mexPrintf(\"myconfidence\\n\");mexEvalString(\"drawnow;\");}\n      if(DEBUG){cout << myconfidence << \"\\n\";}\n\n      // Finally, put it all together\n      Matrix2d nablasigma=(mycovarinv*(relsigma+sumwt*myconfidence)*mycovarinv-relsigmainv-mycovarinv*sumprob*myconfidence)/2;\n      double covarstepsz=.1;\n      if(nablasigma(0)!=nablasigma(0)){\n        errmsg=\"nans in nablasigma\";\n        if(DEBUG){mexErrMsgTxt(errmsg.c_str());}\n        error=1;\n        continue;\n      }\n      // As is often the case with EM algorithms, we can end up with a covariance matrix shrinking to zero and\n      // causing problems.  The right thing to do is to put a constraint on the algorithm that the determinant\n      // of the inverse covariance must be less than 1, and correctly project onto the constraint set.  The wrong \n      // thing to do is to not take gradient steps when the determinant of the covariance matrix ends up less \n      // than 1.  However, out of sheer laziness I've done the latter.  In practice this happens very rarely.\n      while(-nablasigma(0)*covarstepsz>mycovar(0)||-nablasigma(3)*covarstepsz>mycovar(3)||(mycovar+nablasigma*covarstepsz).determinant()<1){\n        covarstepsz=covarstepsz*.5;\n      }\n      if(DEBUG){mexPrintf(\"nablasigma\\n\");mexEvalString(\"drawnow;\");}\n      if(DEBUG){cout << nablasigma << \"\\n\";}\n      Matrix2d newcovar=mycovar+nablasigma*covarstepsz;\n      if(newcovar(0)>1e4||newcovar(4)>1e4){\n        errmsg=\"exploding sigma\";\n        if(DEBUG){mexErrMsgTxt(errmsg.c_str());}\n        error=1;\n        continue;\n      }\n      Matrix2d newcovarinv=newcovar.inverse();\n      Vector2d constr=Vector2d::Zero();\n      Matrix2d syst=Matrix2d::Zero();\n\n      if(DEBUG){mexPrintf(\"starting mu update\\n\");mexEvalString(\"drawnow;\");}\n      // Just like before, we start off by iterating over edges, this time\n      // aggregating system of linear equations that's defined by taking the \n      // derivative of equation 17 (note that this system also needs to have \n      // some terms from  equation 16 added in, but \n      // we'll add those terms to the system later) and setting it to 0.\n      //\n      // We ultimately end up with an equation of the form syst*mu=constr,\n      // where each term in the sums of equation 17 adds to both syst and constr.\n      edgex=1;\n      edgey=0;\n      for(int edgeidx=0; edgeidx<4; ++edgeidx){\n        if(DEBUG){mexPrintf(\"%d %d %d %d %d %d\\n\",edgex, edgey, xpos, ypos, hogrows, hogcols);mexEvalString(\"drawnow;\");}\n        if(edgex+xpos>=0&&edgex+xpos<hogcols&&edgey+ypos>=0&&edgey+ypos<hogrows &&\n           inferred[edgey+ypos+hogrows*(edgex+xpos)]){\n          mxArray* othcorresp=mxGetCell(corresp,edgey+ypos+(edgex+xpos)*hogrows);\n          Map<Vector2d> othmu(mxGetPr(mxGetFieldByNumber(othcorresp, 0, 0))+2*pyridx);\n          Map<Matrix2d> othcovar(mxGetPr(mxGetFieldByNumber(othcorresp, 0, 1))+4*pyridx);\n          Vector2d edge;\n          edge << edgex, edgey;\n          if(DEBUG){mexPrintf(\"17\\n\");mexEvalString(\"drawnow;\");}\n          if(DEBUG){cout << othcovar << \"\\n\";}\n          if(DEBUG){cout << othmu << \"\\n\";}\n          Matrix2d othinvcovar=othcovar.inverse();\n          Matrix2d syst2=Matrix2d::Zero();\n          Vector2d constr2=Vector2d::Zero();\n          double n=0.0;\n          for(int transfx=max(0,max(xpos,xpos+edgex)-2);transfx<=min(hogcols-1,min(xpos,xpos+edgex)+2); ++transfx){\n            for(int transfy=max(0,max(ypos,ypos+edgey)-2);transfy<=min(hogrows-1,min(ypos,ypos+edgey)+2); ++transfy){\n              if(inferred[transfy+hogrows*(transfx)]){\n                Vector2d mudiff=othmu-transfs[transfy+(transfx)*hogrows]*edge;\n                constr2=constr2+(othinvcovar+newcovarinv)*(mudiff)*lambdaprime;\n                syst2=syst2+(othinvcovar+newcovarinv)*lambdaprime;\n                n+=1.0;\n              }\n            }\n          }\n          // n is very nearly a constant and so in the paper I just rolled it into lambdaprime.  However,\n          // near the edge n will get smaller, and so dividing by n will give the warping\n          // a little boost near the edge where there are fewer alpha's affecting each\n          // edge.  \n          constr=constr+constr2/n;\n          syst=syst+syst2/n;\n\n          Vector2d mudiff=othmu-edge;\n          constr=constr+(othinvcovar+newcovarinv)*(mudiff)*lambda;\n          syst=syst+(othinvcovar+newcovarinv)*lambda;\n        }\n        int tmp=edgey;\n        edgey=edgex;\n        edgex=-tmp;\n      }\n      if(DEBUG){mexPrintf(\"11\\n\");mexEvalString(\"drawnow;\");}\n      if(DEBUG){cout << constr << \"\\n\";}\n      if(DEBUG){cout << syst << \"\\n\";}\n\n      double newcovardet=newcovar.determinant();\n      Vector2d mn = Vector2d::Zero();\n      sumprob=0;\n\n      // Now aggregate the contribution from the system from equation 16.  Computing\n      // all the stuff for the e-step (including the window, the cache, etc.) is the\n      // same as above.\n      xmin=floor(mymu(0)-min(distvec(0),30.0));\n      xmax=ceil(mymu(0)+min(distvec(0),30.0));\n      ymin=floor(mymu(1)-min(distvec(1),30.0));\n      ymax=ceil(mymu(1)+min(distvec(1),30.0));\n      mycache=cache[pyridx][hogrows*xpos+ypos];\n      createcache=false;\n      if(mycache.xmin<xmin+(xmax-xmin)/5&&mycache.ymin<ymin+(ymax-ymin)/5&&\n         mycache.xmax>xmin+((xmax-xmin)*4+4)/5&&mycache.ymax>ymin+((ymax-ymin)*4+4)/5){\n         ++cachehit;\n      }else{\n        ++cachemiss;\n        createcache=true;\n        mycache.xmin=xmin;\n        mycache.ymin=ymin;\n        mycache.xmax=xmax;\n        mycache.ymax=ymax;\n        if(mycache.data!=NULL){\n          delete mycache.data;\n        }\n        mycache.data=new double[(ymax-ymin+1)*(xmax-xmin+1)];\n      }\n      cachedata=mycache.data;\n\n      for(int windowx = max(xmin,mycache.xmin); windowx<=min(xmax,mycache.xmax); ++windowx){\n        for(int windowy = max(ymin,mycache.ymin); windowy<=min(ymax,mycache.ymax); ++windowy){\n          Vector2d window;\n          window << windowx,windowy;\n          Vector2d pt=window-mymu;\n          double prob=1/(2*M_PI*sqrt(newcovardet))*exp((-pt.transpose()*newcovarinv*pt)(0)/2);\n          double tmpprob;\n          if(createcache){\n            int idx=ndims*(min(othrows-1,max(0,windowy-1))+min(othcols-1,max(0,windowx-1))*othrows);\n            Map<VectorXd> othdata(othhog+idx,ndims-1);\n            tmpprob = exp(-(mydatatransf.dot(othdata)+myconst)/2);\n            tmpprob=tmpprob/(tmpprob+.01*(*(othhog+idx+ndims-1)));\n            cachedata[(windowx-xmin)*(ymax-ymin+1)+windowy-ymin]=tmpprob;\n            if(prob!=prob){\n              if(DEBUG){mexPrintf(\"%f %f %f %f\\n\",tmpprob,myconst,mydatatransf.dot(othdata),*(othhog+idx+ndims-1));}\n              if(DEBUG){cout<<\"othdata\\n\"<<othdata<<\"\\nmydata\\n\"<<mydata<<\"\\n\";}\n              errmsg=\"nan prob v3\";\n              if(DEBUG){mexErrMsgTxt(errmsg.c_str());}\n              error=1;\n              continue;\n            }\n          }else{\n            tmpprob=cachedata[(windowx-mycache.xmin)*(mycache.ymax-mycache.ymin+1)+windowy-mycache.ymin];\n          }\n          prob=prob*tmpprob;\n          sumprob+=prob;\n          mn=mn+prob*pt;\n        }\n      }\n      if(DEBUG){cout << mn << \"\\n\" << mymu << \"\\n\";}\n      if(DEBUG){cout << sumprob << \"\\n\";}\n      constr=constr+newcovarinv*(mn+mymu*sumprob)*myconfidence;\n      syst=syst+newcovarinv*sumprob*myconfidence;\n      // Now put it all together.\n      Vector2d newmu=syst.inverse()*constr;\n      if(DEBUG){mexPrintf(\"Computed newmu, saving\\n\");mexEvalString(\"drawnow;\");}\n      if(DEBUG){mexPrintf(\"%f\\n\",infidx);mexEvalString(\"drawnow;\");}\n\n      mxArray* newcorresp=mxGetCell(corresp,infidx);\n      Map<Vector2d> infmu(mxGetPr(mxGetFieldByNumber(newcorresp, 0, 0))+2*pyridx);\n      Map<Matrix2d> infcovar(mxGetPr(mxGetFieldByNumber(newcorresp, 0, 1))+4*pyridx);\n      if(DEBUG){cout << newmu << \"\\n\";}\n      if(DEBUG){cout << newcovar << \"\\n\";}\n      if(DEBUG){mexPrintf(\"%d\\n\",ntransfs);mexEvalString(\"drawnow;\");}\n      if(newmu(0)!=newmu(0)){\n        errmsg=\"nans in newmu\";\n        if(DEBUG){mexErrMsgTxt(errmsg.c_str());}\n        error=1;\n        continue;\n      }\n\n      // At this point, actually updating the mu and sigma is finished. All that's left is to\n      // put this cell back in the queue, and update all the other nodes that it's connected\n      // to by an edge (since when this node moves, it will probably make its neighbors move).\n      // In general, we aim to overestimate. so we don't have to be afraid of thinking we're\n      // converged when we're not.\n      double diff=(infmu-newmu).norm()*myconfidence;\n      infmu=newmu;\n      infcovar=newcovar;\n      // We guess that, next time, the current node will move as much as it did this time.\n      cellheap.insert(infidx,-diff);\n      // Now, for each neighbor, we increment our estimate of how much it will move by the \n      // amount that this node moved, divided by the number of neighbors that node has.\n      // This is in general a pretty bad estimate, but it's far better than just sweeping\n      // over everything.\n      for(int edge=0; edge<4; ++edge){\n        if(DEBUG){mexPrintf(\"%d %d %d %d %d %d\\n\",edgex, edgey, xpos, ypos, hogrows, hogcols);mexEvalString(\"drawnow;\");}\n        if(edgex+xpos>=0&&edgex+xpos<hogcols&&edgey+ypos>=0&&edgey+ypos<hogrows &&\n           inferred[edgey+ypos+hogrows*(edgex+xpos)]){\n             cellheap.decreaseKey(edgey+ypos+hogrows*(edgex+xpos),cellheap.keyOf(edgey+ypos+hogrows*(edgex+xpos))-diff/numneighbors[edgey+ypos+hogrows*(edgex+xpos)]);\n        }\n        int tmp=edgey;\n        edgey=edgex;\n        edgex=-tmp;\n      }\n      // On the next round, re-infer some alphas.  Specifically, only re-infer the alpha\n      // associated with the current node.  There's probably a better way to do this, but\n      // in practice this seems to work well enough.\n      mustcomptransf.push_back(infidx);\n\n      // If we've run out of computation budget or we don't seem to be\n      // moving very much anymore, return.  Copy the set of computed alpha's\n      // from the stack to the heap so we can return them.\n      if(diff>=.1){\n        nsincebigmove=0;\n      }\n      if((nupdates>=maxupdates||nsincebigmove==100)&&heapdist>-100000){\n        if(nlhs>=1){\n          transf_out[pyridx]=new double[hogrows*hogcols*4];\n          ++ntransfs;\n          for(int i=0;i<hogrows*hogcols; ++i){\n            Map<Matrix2d> transf_out_i(transf_out[pyridx]+4*i);\n            transf_out_i=transfs[i];\n          }\n        }\n        break;\n      }\n    }\n  }\n  if(error){\n    mexErrMsgTxt(errmsg.c_str());\n  }\n\n  // Copy the alpha's from the heap to Matlab.\n  plhs[0]=corresp;\n  if(nlhs>=1){\n    mxArray* tout=mxCreateCellMatrix(npyrs,1);\n    for(int i=0; i<npyrs; ++i){\n      int dims[4];\n      dims[0]=2;\n      dims[1]=2;\n      dims[2]=hogrows;\n      dims[3]=hogcols;\n      mxArray* data=mxCreateNumericArray(4, dims, mxDOUBLE_CLASS, mxREAL);\n      double* transf_out2=mxGetPr(data);\n      for(int j=0; j<dims[2]*dims[3]*4; ++j){\n        transf_out2[j]=transf_out[i][j];\n      }\n      mxSetCell(tout,i,data);\n      delete transf_out[i];\n    }\n    plhs[1]=tout;\n  }\n  // Useful for debugging/performance analysis.\n  mexPrintf(\"cache hit %d miss %d\\n\",cachehit,cachemiss);\n  delete transf_out;\n}\n", "meta": {"hexsha": "4c8acf6ee8d5378eba818df4ef658d7273bfd71c", "size": 27956, "ext": "cc", "lang": "C++", "max_stars_repo_path": "optimizecorresp.cc", "max_stars_repo_name": "GinYM/contextprediction", "max_stars_repo_head_hexsha": "c1ab527e6a0b1923c458e3b6ff144a395ac5b68e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "optimizecorresp.cc", "max_issues_repo_name": "GinYM/contextprediction", "max_issues_repo_head_hexsha": "c1ab527e6a0b1923c458e3b6ff144a395ac5b68e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optimizecorresp.cc", "max_forks_repo_name": "GinYM/contextprediction", "max_forks_repo_head_hexsha": "c1ab527e6a0b1923c458e3b6ff144a395ac5b68e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-06T01:37:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-06T01:37:46.000Z", "avg_line_length": 46.9060402685, "max_line_length": 166, "alphanum_fraction": 0.6282730004, "num_tokens": 8522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2790285179895105}}
{"text": "/* CirKit: A circuit toolkit\n * Copyright (C) 2009-2015  University of Bremen\n * Copyright (C) 2015-2016  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 \"enumerate_linear_transformations.hpp\"\n\n#include <fstream>\n#include <iostream>\n#include <unordered_map>\n\n#include <boost/dynamic_bitset.hpp>\n#include <boost/format.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <boost/graph/isomorphism.hpp>\n#include <boost/graph/vf2_sub_graph_iso.hpp>\n\n#include <igraph/igraph.h>\n\n#include <core/utils/bitset_utils.hpp>\n#include <core/utils/graph_utils.hpp>\n#include <core/utils/range_utils.hpp>\n#include <core/utils/string_utils.hpp>\n#include <classical/utils/truth_table_utils.hpp>\n\n#define L(x) { if ( verbose ) { std::cout << x << std::endl; } }\n\nnamespace cirkit\n{\n\n/******************************************************************************\n * Types                                                                      *\n ******************************************************************************/\n\nstruct boolean_square_matrix\n{\npublic:\n  boolean_square_matrix( const boost::dynamic_bitset<>& matrix, unsigned dimension )\n    : matrix( matrix ),\n      dimension( dimension )\n  {\n  }\n\n  boolean_square_matrix( const std::vector<boost::dynamic_bitset<>>& rows )\n  {\n    assert( !rows.empty() );\n\n    dimension = rows.front().size();\n    matrix.resize( dimension * dimension );\n\n    unsigned index = 0u;\n\n    for ( const auto& r : rows )\n    {\n      for ( auto c = 0u; c < dimension; ++c )\n      {\n        matrix[index++] = r[c];\n      }\n    }\n  }\n\n  static boolean_square_matrix identity( unsigned dimension )\n  {\n    std::vector<boost::dynamic_bitset<>> rows( dimension, boost::dynamic_bitset<>( dimension ) );\n    for ( auto c = 0u; c < dimension; ++c )\n    {\n      rows[c].set( c );\n    }\n    return boolean_square_matrix( rows );\n  }\n\n  inline bool at( unsigned row, unsigned column ) const\n  {\n    return matrix.test( row * dimension + column );\n  }\n\n  inline void set( unsigned row, unsigned column, bool value )\n  {\n    matrix.set( row * dimension + column, value );\n  }\n\n  std::vector<boost::dynamic_bitset<>> get_row_vectors() const\n  {\n    std::vector<boost::dynamic_bitset<>> rows( dimension, boost::dynamic_bitset<>( dimension ) );\n\n    for ( auto r = 0u; r < dimension; ++r )\n    {\n      for ( auto c = 0u; c < dimension; ++c )\n      {\n        rows[r][c] = at( r, c );\n      }\n    }\n\n    return rows;\n  }\n\n  boolean_square_matrix get_submatrix_by_removing( unsigned row, unsigned column ) const\n  {\n    boost::dynamic_bitset<> subm( ( dimension - 1u ) * ( dimension - 1u ) );\n\n    unsigned index = 0;\n    for ( auto r = 0u; r < dimension; ++r )\n    {\n      if ( r == row ) continue;\n      for ( auto c = 0u; c < dimension; ++c )\n      {\n        if ( c == column ) continue;\n        subm[index++] = at( r, c );\n      }\n    }\n\n    return boolean_square_matrix( subm, dimension - 1u );\n  }\n\n  bool determinant()\n  {\n    if ( dimension == 2u )\n    {\n      return ( at( 0, 0 ) && at( 1, 1 ) ) != ( at( 0, 1 ) && at( 1, 0 ) );\n    }\n    else\n    {\n      bool result = false;\n      for ( auto c = 0u; c < dimension; ++c )\n      {\n        result = result != ( at( 0u, c ) * get_submatrix_by_removing( 0u, c ).determinant() );\n      }\n      return result;\n    }\n  }\n\n  bool is_sorted()\n  {\n    const auto rows = get_row_vectors();\n\n    auto v = 0u;\n\n    for ( const auto& r : rows )\n    {\n      const auto rv = r.to_ulong();\n      if ( rv < v ) return false;\n      v = rv;\n    }\n\n    return true;\n  }\n\n  unsigned row_sum() const\n  {\n    boost::dynamic_bitset<> sum( dimension );\n    for ( const auto& r : get_row_vectors() )\n    {\n      for ( auto c = 0u; c < dimension; ++c )\n      {\n        sum[c] = sum[c] != r[c];\n      }\n    }\n    return sum.to_ulong();\n  }\n\n  boolean_square_matrix swap( unsigned row1, unsigned row2 ) const\n  {\n    boolean_square_matrix other = *this;\n\n    for ( auto c = 0u; c < dimension; ++c )\n    {\n      other.set( row1, c, at( row2, c ) );\n      other.set( row2, c, at( row1, c ) );\n    }\n\n    return other;\n  }\n\n  boolean_square_matrix add_to( unsigned from_row, unsigned to_row ) const\n  {\n    boolean_square_matrix other = *this;\n\n    for ( auto c = 0u; c < dimension; ++c )\n    {\n      other.set( to_row, c, at( from_row, c ) != at( to_row, c ) );\n    }\n\n    return other;\n  }\n\n  boolean_square_matrix sort() const\n  {\n    auto rows = get_row_vectors();\n\n    std::sort( rows.begin(), rows.end(), []( const boost::dynamic_bitset<>& bs1, const boost::dynamic_bitset<>& bs2 ) { return bs1.to_ulong() < bs2.to_ulong(); } );\n\n    return boolean_square_matrix( rows );\n  }\n\n  /* multiply a column vector */\n  boost::dynamic_bitset<> multiply( const boost::dynamic_bitset<>& v ) const\n  {\n    boost::dynamic_bitset<> y( dimension );\n\n    for ( auto r = 0u; r < dimension; ++r )\n    {\n      auto value = false;\n      for ( auto c = 0u; c < dimension; ++c )\n      {\n        value = value != ( v[c] && at( r, c ) );\n      }\n      y[r] = value;\n    }\n\n    return y;\n  }\n\n  /* other can be sorted, but this must be as we want it\n     we assume it's possible */\n  std::pair<unsigned, unsigned> get_add_to_rows( const boolean_square_matrix& other ) const\n  {\n    const auto vectors = get_row_vectors();\n    const auto ovectors = other.get_row_vectors();\n\n    auto to = 0u, from = 0u;\n    boost::dynamic_bitset<> to_row;\n    boost::dynamic_bitset<> from_row;\n\n    for ( const auto& r : index( vectors ) )\n    {\n      const auto it = std::find( ovectors.begin(), ovectors.end(), r.value );\n      if ( it == ovectors.end() )\n      {\n        to = r.index;\n        to_row = r.value;\n      }\n    }\n\n    for ( const auto& r : ovectors )\n    {\n      const auto it = std::find( vectors.begin(), vectors.end(), r );\n      if ( it == vectors.end() )\n      {\n        from_row = r;\n      }\n    }\n\n    from_row ^= to_row;\n    from = std::distance( vectors.begin(), std::find( vectors.begin(), vectors.end(), from_row ) );\n\n    //std::cout << boost::format( \"[i] added %s [%d] to %s [%d]\" ) % to_string( from_row ) % from % to_string( to_row ) % to << std::endl;\n\n    return {from, to};\n  }\n\n  std::pair<unsigned, unsigned> compute_swap_permutation( const boolean_square_matrix& other ) const\n  {\n    std::vector<unsigned> perm( 1u << dimension ); /* permutation of this matrix */\n    std::vector<unsigned> perm2( 1u << dimension );\n\n    boost::dynamic_bitset<> bs( dimension );\n\n    do\n    {\n      perm[bs.to_ulong()] = multiply( bs ).to_ulong();\n\n      inc( bs );\n    } while ( bs.any() );\n\n    do\n    {\n      perm2[other.multiply( bs ).to_ulong()] = bs.to_ulong();\n\n      inc( bs );\n    } while ( bs.any() );\n\n    unsigned delta = 0u;\n    unsigned theta = 0u;\n\n    for ( auto i = 0u; i < perm.size(); ++i )\n    {\n      const auto j = perm2[perm[i]];\n      if ( i < j )\n      {\n        delta = j - i;\n        theta |= ( 1 << i );\n      }\n    }\n\n    return {delta, theta};\n  }\n\n  inline unsigned long value() const\n  {\n    return matrix.to_ulong();\n  }\n\n  friend std::ostream& operator<<( std::ostream& os, const boolean_square_matrix& m )\n  {\n    for ( auto r = 0u; r < m.dimension; ++r )\n    {\n      for ( auto c = 0u; c < m.dimension; ++c )\n      {\n        if ( c > 0u )\n        {\n          os << \" \";\n        }\n        os << m.at( r, m.dimension - c - 1 );\n      }\n      os << std::endl;\n    }\n\n    return os;\n  }\n\nprivate:\n  boost::dynamic_bitset<> matrix;\n  unsigned                dimension;\n};\n\n/******************************************************************************\n * Private functions                                                          *\n ******************************************************************************/\n\nunsigned factorial( unsigned n )\n{\n  return ( n == 1u || n == 0u ) ? 1u : factorial( n - 1u ) * n;\n}\n\nunsigned compute_order( unsigned n )\n{\n  unsigned order = 1u;\n\n  for ( unsigned i = 0; i < n; ++i )\n  {\n    order *= ( 1 << n ) - ( 1 << i );\n  }\n\n  return order;\n}\n\nint igraph_is_strongly_regular( const igraph_t *graph, igraph_bool_t *res, igraph_integer_t *k, igraph_integer_t *lambda, igraph_integer_t *mu )\n{\n  int err;\n  *lambda = -1;\n  *mu = -1;\n\n  /* check g is undirected */\n  if ( igraph_is_directed( graph ) ) { return IGRAPH_EINVAL; }\n\n  /* special case if empty */\n  if ( igraph_vcount( graph ) == 0u )\n  {\n    *res = 1;\n    return IGRAPH_SUCCESS;\n  }\n\n  /* check same degree property */\n  igraph_vector_t degrees;\n  igraph_vector_init( &degrees, 0 );\n  igraph_vs_t vertices;\n  igraph_vs_all( &vertices );\n  if ( ( err = igraph_degree( graph, &degrees, vertices, IGRAPH_ALL, 0 ) ) != IGRAPH_SUCCESS )\n  {\n    //return err;\n  }\n  igraph_vs_destroy( &vertices );\n\n  *k = VECTOR( degrees )[0];\n  for ( auto i = 1u; i < igraph_vector_size( &degrees ); ++i )\n  {\n    if ( VECTOR( degrees )[i] != *k )\n    {\n      igraph_vector_destroy( &degrees );\n      std::cout << \"[w] not all vertices have same degree\" << std::endl;\n      *res = 0;\n      return IGRAPH_SUCCESS;\n    }\n  }\n\n  igraph_vector_destroy( &degrees );\n\n  /* check that neighbors have the same number of neighbors */\n  for ( auto node = 0; node < igraph_vcount( graph ); ++node )\n  {\n    igraph_vector_t neis;\n    igraph_vector_init( &neis, 0 );\n    if ( ( err = igraph_neighbors( graph, &neis, node, IGRAPH_ALL ) ) != IGRAPH_SUCCESS )\n    {\n      // return err;\n    }\n\n    /* point to the first neighbor */\n    auto cur = 0;\n    auto conn = 0;\n    while ( cur < igraph_vector_size( &neis ) && VECTOR( neis )[cur] < node + 1 ) ++cur;\n\n    for ( auto onode = node + 1; onode < igraph_vcount( graph ); ++onode )\n    {\n      if ( onode == node ) continue;\n\n      if ( cur < igraph_vector_size( &neis ) && VECTOR( neis )[cur] == onode )\n      {\n        /* connected */\n        conn = 1;\n        ++cur;\n      }\n      else\n      {\n        /* not connected */\n        conn = 0;\n      }\n\n      igraph_vector_t oneis;\n      igraph_vector_init( &oneis, 0 );\n      igraph_neighbors( graph, &oneis, onode, IGRAPH_ALL );\n\n      igraph_vector_t inter;\n      igraph_vector_init( &inter, 0 );\n      igraph_vector_intersect_sorted( &neis, &oneis, &inter );\n\n      if ( conn )\n      {\n        if ( *lambda == -1 )\n        {\n          *lambda = igraph_vector_size( &inter );\n        }\n        else if ( *lambda != igraph_vector_size( &inter ) )\n        {\n          igraph_vector_destroy( &inter );\n          igraph_vector_destroy( &oneis );\n          igraph_vector_destroy( &neis );\n\n          std::cout << \"[w] not same lambda\" << std::endl;\n          *res = 0;\n          return IGRAPH_SUCCESS;\n        }\n      }\n      else\n      {\n        if ( *mu == -1 )\n        {\n          *mu = igraph_vector_size( &inter );\n        }\n        else if ( *mu != igraph_vector_size( &inter ) )\n        {\n          igraph_vector_destroy( &inter );\n          igraph_vector_destroy( &oneis );\n          igraph_vector_destroy( &neis );\n\n          std::cout << \"[w] not same mu\" << std::endl;\n          *res = 0;\n          return IGRAPH_SUCCESS;\n        }\n      }\n\n      igraph_vector_destroy( &inter );\n\n      igraph_vector_destroy( &oneis );\n    }\n\n    igraph_vector_destroy( &neis );\n  }\n\n  *res = 1;\n  return IGRAPH_SUCCESS;\n}\n\nstruct enumerate_hamiltonians_is_equivalent\n{\n  enumerate_hamiltonians_is_equivalent( const std::vector<boolean_square_matrix>& node_to_matrix )\n    : node_to_matrix( node_to_matrix )\n  {\n  }\n\n  bool operator()( const vertex_t<graph_t<>>& vs, const vertex_t<graph_t<>>& vl ) const\n  {\n    if ( vs == 0u )\n    {\n      return vl == 0u;\n    }\n    if ( vs < prefix.size() && prefix[vs] != 0 )\n    {\n      return node_to_matrix[vl].row_sum() == prefix[vs];\n    }\n    else\n    {\n      return true;\n    }\n  }\n\nprivate:\n  //const std::vector<unsigned> prefix = {1, 2, 4, 3, 6, 7, 5, 3, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 7};\n  //const std::vector<unsigned> prefix = {1, 2, 4, 3, 6, 7, 5, 3, 2, 4, 7, 1, 5, 6, 5, 4, 6, 1, 3, 7, 2, 7, 4, 1, 3, 5, 2, 6};\n  const std::vector<unsigned> prefix = {7, 6, 5, 2, 4, 1, 3, 5, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 3};\n  const std::vector<boolean_square_matrix>& node_to_matrix;\n};\n\nstruct enumerate_hamiltonians_printer\n{\npublic:\n  enumerate_hamiltonians_printer( const graph_t<>& sg, const std::vector<boolean_square_matrix>& node_to_matrix )\n    : sg( sg ),\n      node_to_matrix( node_to_matrix )\n  {\n  }\n\n  template<typename CorrespondenceMap1To2, typename CorrespondenceMap2To1>\n  bool operator()( const CorrespondenceMap1To2& f, const CorrespondenceMap2To1& g ) const\n  {\n    std::vector<std::vector<unsigned>> parts( 4u, std::vector<unsigned>( 7u ) );\n\n    for ( auto v = 0u; v < boost::num_vertices( sg ); ++v )\n    {\n      parts[v / 7][v % 7] = node_to_matrix[boost::get( f, v )].row_sum();\n    }\n\n    for ( auto& p : parts )\n    {\n      std::sort( p.begin(), p.end() );\n      for ( auto j = 0u; j < 7u; ++j )\n      {\n        if ( p[j] != j + 1 )\n        {\n          return true;\n        }\n      }\n    }\n\n    for ( auto v = 0u; v < boost::num_vertices( sg ); ++v )\n    {\n      std::cout << \" \" << node_to_matrix[boost::get( f, v )].row_sum();\n    }\n    std::cout << std::endl;\n\n    for ( auto v = 0u; v < boost::num_vertices( sg ); ++v )\n    {\n      std::cout << \" \" << boost::get( f, v );\n    }\n    std::cout << std::endl;\n\n    for ( auto i = 0u; i < 4u; ++i )\n    {\n      std::cout << \" \" << node_to_matrix[boost::get( f, 7 * i )].row_sum();\n    }\n    std::cout << std::endl << std::endl;\n\n    return true;\n  }\n\nprivate:\n  const graph_t<>& sg;\n  const std::vector<boolean_square_matrix>& node_to_matrix;\n};\n\nvoid enumerate_hamiltonians( const igraph_t* graph, const std::vector<boolean_square_matrix>& node_to_matrix )\n{\n  graph_t<> g;\n  for ( auto i = 0; i < igraph_vcount( graph ); ++i )\n  {\n    add_vertex( g );\n  }\n\n  igraph_es_t es;\n  igraph_es_all( &es, IGRAPH_EDGEORDER_ID );\n\n  igraph_eit_t eit;\n  igraph_eit_create( graph, es, &eit );\n\n  while ( !IGRAPH_EIT_END( eit ) )\n  {\n    const auto eid = IGRAPH_EIT_GET( eit );\n\n    igraph_integer_t from, to;\n    igraph_edge( graph, eid, &from, &to );\n\n    add_edge( from, to, g );\n\n    IGRAPH_EIT_NEXT( eit );\n  }\n\n  igraph_eit_destroy( &eit );\n  igraph_es_destroy( &es );\n\n  const auto rg = ring_graph( boost::num_vertices( g ) );\n  boost::vf2_subgraph_mono( rg, g,\n                            enumerate_hamiltonians_printer( rg, node_to_matrix ),\n                            boost::vertex_order_by_mult( rg ),\n                            boost::vertices_equivalent( enumerate_hamiltonians_is_equivalent( node_to_matrix ) ) );\n}\n\n/******************************************************************************\n * Public functions                                                           *\n ******************************************************************************/\n\nvoid enumerate_linear_transformations( unsigned n, const properties::ptr& settings, const properties::ptr& statistics )\n{\n  /* settings */\n  const auto abstract    = get( settings, \"abstract\",    true );\n  const auto hamiltonian = get( settings, \"hamiltonian\", false );\n  const auto hamilenum   = get( settings, \"hamilenum\",   false );\n  const auto frompath    = get( settings, \"frompath\",    std::string() );\n  const auto dotname     = get( settings, \"dotname\",     std::string() );\n  const auto verbose     = get( settings, \"verbose\",     false );\n\n  std::vector<boolean_square_matrix> node_to_matrix;\n  std::unordered_map<unsigned long, unsigned> matrix_to_node;\n  std::vector<unsigned> edge_to_operation;\n\n  igraph_t graph, * p_g = &graph;\n\n  auto order = compute_order( n );\n  if ( abstract )\n  {\n    order /= factorial( n );\n  }\n  L( \"[i] order = \" << order );\n  igraph_empty( p_g, order, IGRAPH_UNDIRECTED );\n\n  boost::dynamic_bitset<> bs( n * n );\n\n  /* create vertices */\n  foreach_bitset( n * n, [&matrix_to_node, &node_to_matrix, n, abstract, verbose]( const boost::dynamic_bitset<>& bs ) {\n      boolean_square_matrix m( bs, n );\n      if ( m.determinant() != 0u && ( !abstract || m.is_sorted() ) )\n      {\n        matrix_to_node[m.value()] = node_to_matrix.size();\n        node_to_matrix.push_back( m );\n      }\n    } );\n\n  /* create edges */\n  for ( size_t v = 0; v < node_to_matrix.size(); ++v )\n  {\n    const auto& bm = node_to_matrix[v];\n\n    /* adding */\n    for ( auto from_row = 0u; from_row < n; ++from_row )\n    {\n      for ( auto to_row = 0u; to_row < n; ++to_row )\n      {\n        if ( from_row == to_row ) continue;\n\n        auto other = bm.add_to( from_row, to_row );\n        if ( abstract )\n        {\n          other = other.sort();\n        }\n\n        const auto w = matrix_to_node[other.value()];\n        if ( w > v )\n        {\n          igraph_add_edge( p_g, v, w );\n\n          igraph_integer_t eid;\n          igraph_get_eid( p_g, &eid, v, w, 0, 0 );\n          edge_to_operation.push_back( from_row * 3 + to_row );\n        }\n      }\n    }\n\n    /* swapping */\n    if ( !abstract )\n    {\n      for ( unsigned row2 = 1u; row2 < n; ++row2 )\n      {\n        for ( unsigned row1 = 0u; row1 < row2; ++row1 )\n        {\n          const auto other = bm.swap( row1, row2 );\n          const auto w = matrix_to_node[other.value()];\n          if ( w > v )\n          {\n            igraph_add_edge( p_g, v, w );\n          }\n        }\n      }\n    }\n  }\n\n  /* check some properties */\n  igraph_bool_t b_connected;\n  igraph_is_connected( p_g, &b_connected, IGRAPH_STRONG );\n  L( \"[i] is strongly connected: \" << b_connected );\n\n  igraph_bool_t b_strongly_regular;\n  igraph_integer_t k, lambda, mu;\n  assert( !igraph_is_strongly_regular( p_g, &b_strongly_regular, &k, &lambda, &mu ) );\n  L( \"[i] is strongly regular: \" << b_strongly_regular );\n\n  /* Hamiltonian path */\n  if ( hamiltonian )\n  {\n    igraph_t rgraph, * p_rg = &rgraph;\n    igraph_ring( p_rg, order, 0, 0, 1 );\n\n    igraph_bool_t b_iso;\n    igraph_vector_t map;\n    igraph_vector_init( &map, 0 );\n    igraph_subisomorphic_lad( p_rg, p_g, nullptr, &b_iso, &map, nullptr, 0, 0 );\n    L( \"[i] found isomorphism: \" << b_iso );\n\n    igraph_vector_print( &map );\n    igraph_vector_destroy( &map );\n    igraph_destroy( p_rg );\n  }\n\n  if ( hamilenum )\n  {\n    enumerate_hamiltonians( p_g, node_to_matrix );\n  }\n\n  /* derive delta-swap sequence from path */\n  if ( !frompath.empty() )\n  {\n    std::cout << \"[i] derive delta-swap sequence from path: \" << frompath << std::endl;\n    std::vector<unsigned> path;\n    parse_string_list( path, frompath, \" \" );\n\n    unsigned delta, theta;\n    const auto& swaps = tt_store::i().swaps( n );\n\n    auto curm = node_to_matrix[path[0u]];\n\n    std::cout << curm;\n    for ( auto i = 0u; i < swaps.size(); ++i )\n    {\n      auto nextm = curm.swap( swaps[i], swaps[i] + 1 );\n      std::tie( delta, theta ) = nextm.compute_swap_permutation( curm );\n      std::cout << boost::format( \"[i] swap %d with %d (%d, %d)\" ) % swaps[i] % ( swaps[i] + 1 ) % delta % theta << std::endl;\n      std::cout << nextm;\n      curm = nextm;\n    }\n\n    auto next = 1u;\n    while ( next < path.size() )\n    {\n      // const auto v = std::min( path[next - 1], path[next] );\n      // const auto w = std::max( path[next - 1], path[next] );\n      // igraph_integer_t eid;\n      // igraph_get_eid( p_g, &eid, v, w, 0, 0 );\n      // const auto op = edge_to_operation[eid];\n      // const auto to = op % n;\n      // const auto from = ( op - to ) / n;\n      // std::cout << boost::format( \"[i] add %d to %d\" ) % from % to << std::endl;\n\n      unsigned from_row, to_row;\n      std::tie( from_row, to_row ) = curm.get_add_to_rows( node_to_matrix[path[next]] );\n\n      auto nextm = curm.add_to( from_row, to_row );\n      std::tie( delta, theta ) = nextm.compute_swap_permutation( curm );\n      std::cout << boost::format( \"[i] add %d to %d (%d, %d)\" ) % from_row % to_row % delta % theta << std::endl;\n      std::cout << nextm;\n      curm = nextm;\n\n      for ( auto i = 0u; i < swaps.size(); ++i )\n      {\n        auto nextm = curm.swap( swaps[i], swaps[i] + 1 );\n        std::tie( delta, theta ) = nextm.compute_swap_permutation( curm );\n        std::cout << boost::format( \"[i] swap %d with %d (%d, %d)\" ) % swaps[i] % ( swaps[i] + 1 ) % delta % theta << std::endl;\n        std::cout << nextm;\n        curm = nextm;\n      }\n      ++next;\n    }\n  }\n\n  /* row value inspection */\n  if ( false )\n  {\n    const auto from_sum = 2u;\n    const auto to_sum = 3u;\n    for ( const auto& bm : node_to_matrix )\n    {\n      if ( bm.row_sum() == from_sum )\n      {\n        std::cout << \"[i] matrix with row sum \" << from_sum << \": \" << std::endl << bm;\n        //std::cout << \"[i] adjacent matrices have row sums:\";\n\n        igraph_vector_t neis;\n        igraph_vector_init( &neis, 0 );\n        igraph_neighbors( p_g, &neis, matrix_to_node[bm.value()], IGRAPH_ALL );\n\n        for ( auto i = 0u; i < igraph_vector_size( &neis ); ++i )\n        {\n          const auto& om = node_to_matrix[VECTOR( neis )[i]];\n          if ( om.row_sum() == to_sum )\n          {\n            std::cout << \"[i] connects to: \" << std::endl << om;\n          }\n        }\n        //std::cout << std::endl;\n        igraph_vector_destroy( &neis );\n      }\n    }\n  }\n\n  if ( !dotname.empty() )\n  {\n    auto * fp = fopen( dotname.c_str(), \"w\" );\n    igraph_write_graph_dot( p_g, fp );\n    fclose( fp );\n  }\n\n  igraph_destroy( p_g );\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": "3b8d80eae713632f13987ec93bf7158270bd641d", "size": 22344, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/classical/enumeration/enumerate_linear_transformations.cpp", "max_stars_repo_name": "msoeken/cirkit_addon_igraph", "max_stars_repo_head_hexsha": "9e9572990fe1cd85182746aa8fdd973920fcf83c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-07-02T23:38:45.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-02T23:38:45.000Z", "max_issues_repo_path": "src/classical/enumeration/enumerate_linear_transformations.cpp", "max_issues_repo_name": "msoeken/cirkit_addon_igraph", "max_issues_repo_head_hexsha": "9e9572990fe1cd85182746aa8fdd973920fcf83c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-08-30T08:27:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-31T07:00:08.000Z", "max_forks_repo_path": "src/classical/enumeration/enumerate_linear_transformations.cpp", "max_forks_repo_name": "msoeken/cirkit_addon_igraph", "max_forks_repo_head_hexsha": "9e9572990fe1cd85182746aa8fdd973920fcf83c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-08-30T12:01:33.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-30T12:01:33.000Z", "avg_line_length": 26.9204819277, "max_line_length": 164, "alphanum_fraction": 0.5534819191, "num_tokens": 6401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2790285113400851}}
{"text": "#include \"contour_optimization.h\"\n\n#include \"session_data.h\"\n#include \"frame_data.h\"\n#include \"focal_grid.h\"\n#include \"image_segmentation.h\"\n#include \"model_class.h\"\n\n#include <boost/python.hpp>\n#include <boost/python/numpy.hpp>\n#include <string>\n#include <stdint.h>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <vector>\n#include <list>\n#include <thread>\n#include <chrono>\n#include <algorithm>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <dirent.h>\n#include <opencv2/opencv.hpp>\n#include <opencv2/highgui.hpp>\n#include <armadillo>\n\n#include <nlopt.hpp>\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n#include <CGAL/Boolean_set_operations_2.h>\n#include <CGAL/algorithm.h>\n#include <CGAL/assertions.h>\n#include <CGAL/Polygon_2.h>\n#include <CGAL/Polygon_with_holes_2.h>\n#include <CGAL/Polygon_set_2.h>\n\n\n\n#define PI 3.14159265\n\nusing namespace std;\n\nnamespace p = boost::python;\nnamespace np = boost::python::numpy;\n\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel KI;\n//typedef CGAL::Exact_predicates_exact_constructions_kernel KE;\n\ntypedef KI::Point_2 \t\t\t\t   Point_2;\ntypedef CGAL::Polygon_2<KI>            Polygon_2;\ntypedef CGAL::Polygon_with_holes_2<KI> Polygon_with_holes_2;\ntypedef CGAL::Polygon_set_2<KI> \t   Polygon_set_2;\n\ntypedef struct {\n\tFocalGrid* fg;\n\tContourOpt* opt;\n\tModelClass* mdl;\n\tint N_cam;\n\tconst vector<list<Polygon_with_holes_2>> body_dest;\n\tconst vector<list<Polygon_with_holes_2>> wing_L_dest;\n\tconst vector<list<Polygon_with_holes_2>> wing_R_dest;\n} cost_func_data;\n\ndouble cost_function(const vector<double> &x, vector<double> &grad, void *data) {\n\n\tclock_t start;\n\tdouble duration;\n\n\tstart = clock();\n\n\tcost_func_data *d = reinterpret_cast<cost_func_data*>(data);\n\tFocalGrid* fg = d->fg;\n\tContourOpt* opt = d->opt;\n\tModelClass* mdl = d->mdl;\n\tint N_cam = d->N_cam;\n\t//vector<list<Polygon_with_holes_2>> body_dest = d->body_dest;\n\t//vector<list<Polygon_with_holes_2>> wing_L_dest = d->wing_L_dest;\n\t//vector<list<Polygon_with_holes_2>> wing_R_dest = d->wing_R_dest;\n\n\tvector<double> state_now;\n\tstate_now.push_back(x[0]);\n\tstate_now.push_back(x[1]);\n\tstate_now.push_back(x[2]);\n\tstate_now.push_back(x[3]);\n\tstate_now.push_back(x[4]);\n\tstate_now.push_back(x[5]);\n\tstate_now.push_back(x[6]);\n\tstate_now.push_back(x[7]);\n\tstate_now.push_back(x[8]);\n\tstate_now.push_back(x[9]);\n\tstate_now.push_back(x[10]);\n\tstate_now.push_back(x[11]);\n\tstate_now.push_back(x[12]);\n\tstate_now.push_back(x[13]);\n\tstate_now.push_back(x[14]);\n\n\tvector<list<Polygon_with_holes_2>> body_src;\n\tvector<list<Polygon_with_holes_2>> wing_L_src;\n\tvector<list<Polygon_with_holes_2>> wing_R_src;\n\n\tvector<list<Polygon_with_holes_2>> body_dest; \n\tvector<list<Polygon_with_holes_2>> wing_L_dest; \n\tvector<list<Polygon_with_holes_2>> wing_R_dest;\n\n\t// Convert state x to affine matrix transforms:\n\tcout << \"return src state\" << endl;\n\tvector<double> src_state = mdl->ReturnSRCState(state_now);\n\tcout << \"size src state\" << src_state.size() << endl;\n\n\tcout << \"get src contours\" << endl;\n\tfor (int i=0; i<N_cam; i++) {\n\t\tcout << \"get silhouette\" << endl;\n\t\tvector<Polygon_2> m_silhouette = mdl->ReturnSilhouette2(*fg,src_state,i);\n\t\tcout << \"size silhouette\" << m_silhouette.size() << endl;\n\t\tvector<Polygon_2> m_body;\n\t\tfor (int j=0; j<3; j++) {\n\t\t\tm_body.push_back(m_silhouette[j]);\n\t\t}\n\t\tlist<Polygon_with_holes_2> body_contour_poly = opt->CalcUnion(m_body);\n\t\tbody_src.push_back(body_contour_poly);\n\t\tbody_dest.push_back(d->body_dest[i]);\n\t\tvector<Polygon_2> m_wing_L;\n\t\tm_wing_L.push_back(m_silhouette[3]);\n\t\tlist<Polygon_with_holes_2> wing_L_contour_poly = opt->CalcUnion(m_wing_L);\n\t\tlist<Polygon_with_holes_2> wing_L_complement = opt->CalcComplement(body_contour_poly, wing_L_contour_poly);\n\t\twing_L_src.push_back(wing_L_complement);\n\t\twing_L_dest.push_back(d->wing_L_dest[i]);\n\t\tvector<Polygon_2> m_wing_R;\n\t\tm_wing_R.push_back(m_silhouette[4]);\n\t\tlist<Polygon_with_holes_2> wing_R_contour_poly = opt->CalcUnion(m_wing_R);\n\t\tlist<Polygon_with_holes_2> wing_R_complement = opt->CalcComplement(body_contour_poly, wing_R_contour_poly);\n\t\twing_R_src.push_back(wing_R_complement);\n\t\twing_R_dest.push_back(d->wing_R_dest[i]);\n\t}\n\n\t// Calculate the cost by calculating the symmetric difference per view per polygon list:\n\tdouble cost = 0.0;\n\n\tlist<Polygon_with_holes_2> body_diff;\n\tlist<Polygon_with_holes_2> wing_L_diff;\n\tlist<Polygon_with_holes_2> wing_R_diff;\n\n\tcout << \"body src vec size: \" << body_src.size() << endl;\n\tcout << \"body dest vec size: \" << body_dest.size() << endl;\n\n\tfor (int i=0; i<N_cam; i++) {\n\t\tcout << \"i \" << i << endl;\n\t\tif (body_dest[i].size()>0 && body_src[i].size()>0) {\n\t\t\t//body_diff.clear();\n\t\t\tcout << \"Calc symmetric difference body \" << endl;\n\t\t\tlist<Polygon_with_holes_2> body_diff = opt->CalcSymmetricDifference(body_dest[i],body_src[i]);\n\t\t\tif (body_diff.size() > 0) {\n\t\t\t\tfor (list<Polygon_with_holes_2>::iterator it1 = body_diff.begin(); it1 != body_diff.end(); ++it1) {\n\t\t\t\t\tcout << \"area: \" << it1->outer_boundary().area() << endl;\n\t\t\t\t\t//cost += it->outer_boundary().area();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t/*\n\t\tif (wing_L_dest[i].size()>0 && wing_L_src[i].size()>0) {\n\t\t\t//wing_L_diff.clear();\n\t\t\tcout << \"Calc symmetric difference wing_L \" << endl;\n\t\t\tlist<Polygon_with_holes_2> wing_L_diff = opt->CalcSymmetricDifference(wing_L_dest[i],wing_L_src[i]);\n\t\t\tif (wing_L_diff.size() > 0) {\n\t\t\t\tfor (list<Polygon_with_holes_2>::iterator it2 = wing_L_diff.begin(); it2 != wing_L_diff.end(); ++it2) {\n\t\t\t\t\tcout << \"area: \" << it2->outer_boundary().area() << endl;\n\t\t\t\t\t//cost += it->outer_boundary().area();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcout << \"dest polygons size \" << wing_R_dest[i].size() << endl;\n\t\tcout << \"src polygons size \"<< wing_R_src[i].size() << endl;\n\t\tif (wing_R_dest[i].size()>0 && wing_R_src[i].size()>0) {\n\t\t\t//wing_R_diff.clear();\n\t\t\tcout << \"wing_R_dest\" << endl;\n\t\t\tcout << wing_R_dest[i].front() << endl;\n\t\t\tcout << \"wing_R_src\" << endl;\n\t\t\tcout << wing_R_src[i].front() << endl;\n\t\t\tcout << \"Calc symmetric difference wing_R \" << endl;\n\t\t\tlist<Polygon_with_holes_2> wing_R_diff = opt->CalcSymmetricDifference(wing_R_dest[i],wing_R_src[i]);\n\t\t\tcout << \"wing_R_diff size \" << wing_R_diff.size() << endl;\n\t\t\tif (wing_R_diff.size() > 0) {\n\t\t\t\tfor (list<Polygon_with_holes_2>::iterator it3 = wing_R_diff.begin(); it3 != wing_R_diff.end(); ++it3) {\n\t\t\t\t\tcout << \"area: \" << it3->outer_boundary().area() << endl;\n\t\t\t\t\t//cost += it->outer_boundary().area();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t*/\n\t}\n\n\tcout << \"cost: \" << cost << endl;\n\tduration = ( clock() - start ) / (double) CLOCKS_PER_SEC;\n    cout<<\"printf: \"<< duration <<'\\n';\n\n\treturn cost;\n}\n\ndouble quat_constraint_body(const std::vector<double> &x, std::vector<double> &grad, void *data) {\n\tdouble q_norm = sqrt(pow(x[0],2)+pow(x[1],2)+pow(x[2],2)+pow(x[3],2));\n\treturn (1.0-q_norm);\n}\n\ndouble quat_constraint_wing_L(const std::vector<double> &x, std::vector<double> &grad, void *data) {\n\tdouble q_norm = sqrt(pow(x[7],2)+pow(x[8],2)+pow(x[9],2)+pow(x[10],2));\n\treturn (1.0-q_norm);\n}\n\ndouble quat_constraint_wing_R(const std::vector<double> &x, std::vector<double> &grad, void *data) {\n\tdouble q_norm = sqrt(pow(x[11],2)+pow(x[12],2)+pow(x[13],2)+pow(x[14],2));\n\treturn (1.0-q_norm);\n}\n\n/*\nvoid Optimize(FocalGrid &fg, frame_data &frame_in, ModelClass &mdl, ContourOpt &opt) {\n\n\tint N_cam = frame_in.N_cam;\n\n\tcost_func_data cost_data = {fg, opt, mdl, N_cam, opt.body_dest_polygons, opt.wing_L_dest_polygons, opt.wing_R_dest_polygons};\n\n    vector<double> lb(15);\n    lb[0] = -1.0;\n\tlb[1] = -1.0;\n\tlb[2] = -1.0;\n\tlb[3] = -1.0;\n\tlb[4] = -10.0;\n\tlb[5] = -10.0;\n\tlb[6] = -10.0;\n\tlb[7] = -1.0;\n\tlb[8] = -1.0;\n\tlb[9] = -1.0;\n\tlb[10] = -1.0;\n\tlb[11] = -1.0;\n\tlb[12] = -1.0;\n\tlb[13] = -1.0;\n\tlb[14] = -1.0;\n\n\tvector<double> ub(15);\n\tub[0] = -1.0;\n\tub[1] = -1.0;\n\tub[2] = -1.0;\n\tub[3] = -1.0;\n\tub[4] = -10.0;\n\tub[5] = -10.0;\n\tub[6] = -10.0;\n\tub[7] = -1.0;\n\tub[8] = -1.0;\n\tub[9] = -1.0;\n\tub[10] = -1.0;\n\tub[11] = -1.0;\n\tub[12] = -1.0;\n\tub[13] = -1.0;\n\tub[14] = -1.0;\n\n\tvector<double> x(15);\n\tx[0] = frame_in.init_state(0,0);\n\tx[1] = frame_in.init_state(1,0);\n\tx[2] = frame_in.init_state(2,0);\n\tx[3] = frame_in.init_state(3,0);\n\tx[4] = frame_in.init_state(4,0);\n\tx[5] = frame_in.init_state(5,0);\n\tx[6] = frame_in.init_state(6,0);\n\tx[7] = frame_in.init_state(0,1);\n\tx[8] = frame_in.init_state(1,1);\n\tx[9] = frame_in.init_state(2,1);\n\tx[10] = frame_in.init_state(3,1);\n\tx[11] = frame_in.init_state(0,2);\n\tx[12] = frame_in.init_state(1,2);\n\tx[13] = frame_in.init_state(2,2);\n\tx[14] = frame_in.init_state(3,2);\n\n\tnlopt::opt opt_alg(nlopt::LN_COBYLA, 15);\n\topt_alg.set_lower_bounds(lb);\n\topt_alg.set_upper_bounds(ub);\n\topt_alg.set_min_objective(cost_function, &cost_data);\n\topt_alg.add_equality_constraint(quat_constraint_body, NULL, 1e-6);\n\topt_alg.add_equality_constraint(quat_constraint_wing_L, NULL, 1e-6);\n\topt_alg.add_equality_constraint(quat_constraint_wing_R, NULL, 1e-6);\n\topt_alg.set_xtol_rel(1e-5);\n\n\tcout << \" -------------------- \" << endl;\n\tcout << \"x start: \" << x[0] << \", \" << x[1] << \", \" << x[2] << \", \" << x[3] << \", \" << x[4] \n\t\t<< \", \" << x[5] << \", \" << x[6] << endl;\n\tcout << x[7] << \", \" << x[8] << \", \" << x[9] << \", \" << x[10] << endl;\n\tcout << x[11] << \", \" << x[12] << \", \" << x[13] << \", \" << x[14] << endl;\n\n\tdouble minf;\n\n\tnlopt::result result = opt_alg.optimize(x, minf);\n\n\tcout << \"x opt: \" << x[0] << \", \" << x[1] << \", \" << x[2] << \", \" << x[3] << \", \" << x[4] \n\t\t<< \", \" << x[5] << \", \" << x[6] << endl;\n\tcout << x[7] << \", \" << x[8] << \", \" << x[9] << \", \" << x[10] << endl;\n\tcout << x[11] << \", \" << x[12] << \", \" << x[13] << \", \" << x[14] << endl;\n\n\tcout << \"quaternion norm body: \" << sqrt(pow(x[0],2)+pow(x[1],2)+pow(x[2],2)+pow(x[3],2)) << endl;\n\tcout << \"quaternion norm wing L: \" << sqrt(pow(x[7],2)+pow(x[8],2)+pow(x[9],2)+pow(x[10],2)) << endl;\n\tcout << \"quaternion norm wing R: \" << sqrt(pow(x[11],2)+pow(x[12],2)+pow(x[13],2)+pow(x[14],2)) << endl;\n\tcout << \" -------------------- \" << endl;\n\tcout << endl;\n}\n*/\n\nContourOpt::ContourOpt() {\n\t// Empty\n}\n\nvoid ContourOpt::OptimizeState(FocalGrid &fg, frame_data &frame_in, ModelClass &mdl, ImagSegm &seg) {\n\tContourOpt::FindDestinationContour(fg, frame_in, seg);\n\tContourOpt::FindInitContour(fg, frame_in, mdl, seg);\n\tContourOpt::Optimize(fg, frame_in, mdl);\n}\n\nvoid ContourOpt::Optimize(FocalGrid &fg, frame_data &frame_in, ModelClass &mdl) {\n\n\tint N_cam = frame_in.N_cam;\n\n\tcost_func_data cost_data = {&fg, this, &mdl, N_cam, body_dest_polygons, wing_L_dest_polygons, wing_R_dest_polygons};\n\n    vector<double> lb(15);\n    lb[0] = -1.0;\n\tlb[1] = -1.0;\n\tlb[2] = -1.0;\n\tlb[3] = -1.0;\n\tlb[4] = -10.0;\n\tlb[5] = -10.0;\n\tlb[6] = -10.0;\n\tlb[7] = -1.0;\n\tlb[8] = -1.0;\n\tlb[9] = -1.0;\n\tlb[10] = -1.0;\n\tlb[11] = -1.0;\n\tlb[12] = -1.0;\n\tlb[13] = -1.0;\n\tlb[14] = -1.0;\n\n\tvector<double> ub(15);\n\tub[0] = 1.0;\n\tub[1] = 1.0;\n\tub[2] = 1.0;\n\tub[3] = 1.0;\n\tub[4] = 10.0;\n\tub[5] = 10.0;\n\tub[6] = 10.0;\n\tub[7] = 1.0;\n\tub[8] = 1.0;\n\tub[9] = 1.0;\n\tub[10] = 1.0;\n\tub[11] = 1.0;\n\tub[12] = 1.0;\n\tub[13] = 1.0;\n\tub[14] = 1.0;\n\n\tvector<double> x(15);\n\tx[0] = frame_in.init_state(0,0);\n\tx[1] = frame_in.init_state(1,0);\n\tx[2] = frame_in.init_state(2,0);\n\tx[3] = frame_in.init_state(3,0);\n\tx[4] = frame_in.init_state(4,0);\n\tx[5] = frame_in.init_state(5,0);\n\tx[6] = frame_in.init_state(6,0);\n\tx[7] = frame_in.init_state(0,1);\n\tx[8] = frame_in.init_state(1,1);\n\tx[9] = frame_in.init_state(2,1);\n\tx[10] = frame_in.init_state(3,1);\n\tx[11] = frame_in.init_state(0,2);\n\tx[12] = frame_in.init_state(1,2);\n\tx[13] = frame_in.init_state(2,2);\n\tx[14] = frame_in.init_state(3,2);\n\n\tnlopt::opt opt_alg(nlopt::LN_COBYLA, 15);\n\topt_alg.set_lower_bounds(lb);\n\topt_alg.set_upper_bounds(ub);\n\topt_alg.set_min_objective(cost_function, &cost_data);\n\topt_alg.add_equality_constraint(quat_constraint_body, NULL, 1e-6);\n\topt_alg.add_equality_constraint(quat_constraint_wing_L, NULL, 1e-6);\n\topt_alg.add_equality_constraint(quat_constraint_wing_R, NULL, 1e-6);\n\topt_alg.set_xtol_rel(1e-5);\n\n\tcout << \" -------------------- \" << endl;\n\tcout << \"x start: \" << x[0] << \", \" << x[1] << \", \" << x[2] << \", \" << x[3] << \", \" << x[4] \n\t\t<< \", \" << x[5] << \", \" << x[6] << endl;\n\tcout << x[7] << \", \" << x[8] << \", \" << x[9] << \", \" << x[10] << endl;\n\tcout << x[11] << \", \" << x[12] << \", \" << x[13] << \", \" << x[14] << endl;\n\n\tdouble minf;\n\n\tnlopt::result result = opt_alg.optimize(x, minf);\n\n\tcout << \"x opt: \" << x[0] << \", \" << x[1] << \", \" << x[2] << \", \" << x[3] << \", \" << x[4] \n\t\t<< \", \" << x[5] << \", \" << x[6] << endl;\n\tcout << x[7] << \", \" << x[8] << \", \" << x[9] << \", \" << x[10] << endl;\n\tcout << x[11] << \", \" << x[12] << \", \" << x[13] << \", \" << x[14] << endl;\n\n\tcout << \"quaternion norm body: \" << sqrt(pow(x[0],2)+pow(x[1],2)+pow(x[2],2)+pow(x[3],2)) << endl;\n\tcout << \"quaternion norm wing L: \" << sqrt(pow(x[7],2)+pow(x[8],2)+pow(x[9],2)+pow(x[10],2)) << endl;\n\tcout << \"quaternion norm wing R: \" << sqrt(pow(x[11],2)+pow(x[12],2)+pow(x[13],2)+pow(x[14],2)) << endl;\n\tcout << \" -------------------- \" << endl;\n\tcout << endl;\n}\n\nvoid ContourOpt::FindDestinationContour(FocalGrid &fg, frame_data &frame_in, ImagSegm &seg) {\n\n\tclock_t start;\n\tdouble duration;\n\n\tstart = clock();\n\n\tbody_dest_polygons.clear();\n\twing_L_dest_polygons.clear();\n\twing_R_dest_polygons.clear();\n\tbody_dest_contours.clear();\n\twing_L_dest_contours.clear();\n\twing_R_dest_contours.clear();\n\n\tint N_cam = frame_in.N_cam;\n\n\t// Get the body and wing pointclouds\n\tarma::uvec body_pt_ids   = arma::find(frame_in.body_and_wing_pcls.row(3) == 1.0);\n\tarma::uvec wing_L_pt_ids = arma::find(frame_in.body_and_wing_pcls.row(3) == 2.0);\n\tarma::uvec wing_R_pt_ids = arma::find(frame_in.body_and_wing_pcls.row(3) == 3.0);\n\n\tarma::Mat<double> body_pcl = frame_in.body_and_wing_pcls.cols(body_pt_ids);\n\tarma::Mat<double> wing_L_pcl = frame_in.body_and_wing_pcls.cols(wing_L_pt_ids);\n\tarma::Mat<double> wing_R_pcl = frame_in.body_and_wing_pcls.cols(wing_R_pt_ids);\n\n\t//arma::Mat<double> means = ContourOpt::KMeans(body_pcl, 3, 10);\n\n\t//cout << means << endl;\n\n\tvector<arma::Col<int>> body_proj = fg.FocalGrid::ProjectCloud2Frames(body_pcl);\n\tvector<arma::Col<int>> wing_L_proj = fg.FocalGrid::ProjectCloud2Frames(wing_L_pcl);\n\tvector<arma::Col<int>> wing_R_proj = fg.FocalGrid::ProjectCloud2Frames(wing_R_pcl);\n\n\tvector<vector<arma::Mat<double>>> contour_vec = ContourOpt::FindContours(body_proj, wing_L_proj, wing_R_proj, frame_in, seg);\n\n\tfor (int i=0; i<N_cam; i++) {\n\t\tbody_dest_polygons.push_back(ContourOpt::Convert2PolygonWithHoles(contour_vec[i][0]));\n\t\twing_L_dest_polygons.push_back(ContourOpt::Convert2PolygonWithHoles(contour_vec[i][1]));\n\t\twing_R_dest_polygons.push_back(ContourOpt::Convert2PolygonWithHoles(contour_vec[i][2]));\n\t\tbody_dest_contours.push_back(contour_vec[i][0]);\n\t\twing_L_dest_contours.push_back(contour_vec[i][1]);\n\t\twing_R_dest_contours.push_back(contour_vec[i][2]);\n\t}\n\n\tduration = ( clock() - start ) / (double) CLOCKS_PER_SEC;\n    cout<<\"printf: \"<< duration <<'\\n';\n\n}\n\narma::Mat<double> ContourOpt::KMeans(arma::Mat<double> &pcl_in, int N_clusters, int N_iter) {\n\n\tarma::Mat<double> data = pcl_in.rows(0,2);\n\n\tarma::Mat<double> means;\n\n\tbool status =arma::kmeans(means,data,N_clusters,arma::random_subset,N_iter,false);\n\n\tif (status==false) {\n\t\tcout << \"clustering failed\" << endl;\n\t}\n\n\treturn means;\n}\n\nvoid ContourOpt::FindInitContour(FocalGrid &fg, frame_data &frame_in, ModelClass &mdl, ImagSegm &seg) {\n\n\tclock_t start;\n\tdouble duration;\n\n\tstart = clock();\n\n\tbody_init_contours.clear();\n\twing_L_init_contours.clear();\n\twing_R_init_contours.clear();\n\n\tint N_cam = frame_in.N_cam;\n\n\t// Get model pcl's in initial state:\n\n\tvector<arma::Mat<double>> M_init_vec = mdl.ReturnInitState(frame_in);\n\n\tfor (int i=0; i<N_cam; i++) {\n\t\tvector<Polygon_2> m_silhouette = mdl.ReturnSilhouette(fg, M_init_vec,fg.CalculateViewVector(i),i);\n\t\tvector<Polygon_2> m_body;\n\t\tfor (int j=0; j<3; j++) {\n\t\t\tm_body.push_back(m_silhouette[j]);\n\t\t}\n\t\tlist<Polygon_with_holes_2> body_contour_poly = ContourOpt::CalcUnion(m_body);\n\t\tbody_init_contours.push_back(ContourOpt::ConvertPolygonWithHoles2Mat(body_contour_poly));\n\t\tvector<Polygon_2> m_wing_L;\n\t\tm_wing_L.push_back(m_silhouette[3]);\n\t\tlist<Polygon_with_holes_2> wing_L_contour_poly = ContourOpt::CalcUnion(m_wing_L);\n\t\tlist<Polygon_with_holes_2> wing_L_complement = ContourOpt::CalcComplement(body_contour_poly, wing_L_contour_poly);\n\t\twing_L_init_contours.push_back(ContourOpt::ConvertPolygonWithHoles2Mat(wing_L_complement));\n\t\tvector<Polygon_2> m_wing_R;\n\t\tm_wing_R.push_back(m_silhouette[4]);\n\t\tlist<Polygon_with_holes_2> wing_R_contour_poly = ContourOpt::CalcUnion(m_wing_R);\n\t\tlist<Polygon_with_holes_2> wing_R_complement = ContourOpt::CalcComplement(body_contour_poly, wing_R_contour_poly);\n\t\twing_R_init_contours.push_back(ContourOpt::ConvertPolygonWithHoles2Mat(wing_R_complement));\n\t}\n\n\tduration = ( clock() - start ) / (double) CLOCKS_PER_SEC;\n    cout<<\"printf: \"<< duration <<'\\n';\n}\n\nvector<vector<arma::Mat<double>>> ContourOpt::FindContours(vector<arma::Col<int>> &body_proj, vector<arma::Col<int>> &wing_L_proj, vector<arma::Col<int>> &wing_R_proj, frame_data &frame_in, ImagSegm &seg) {\n\n\tint N_cam = frame_in.N_cam;\n\n\tvector<vector<arma::Mat<double>>> contour_vec_out;\n\n\tvector<arma::Mat<double>> contour_vec_now;\n\n\tarma::Mat<double> contour_now;\n\n\tarma::Col<int> proj_body_img;\n\tarma::Col<int> proj_wing_L_img;\n\tarma::Col<int> proj_wing_R_img;\n\n\tfor (int i=0; i<N_cam; i++) {\n\n\t\tcontour_vec_now.clear();\n\n\t\tint N_row = get<0>(frame_in.image_size[i]);\n\t\tint N_col = get<1>(frame_in.image_size[i]);\n\n\t\tproj_body_img = body_proj[i];\n\t\tproj_wing_L_img = wing_L_proj[i]%(1-body_proj[i]);\n\t\tproj_wing_R_img = wing_R_proj[i]%(1-body_proj[i]);\n\n\t\tcontour_vec_now.push_back(seg.FindContours(proj_body_img,N_row,N_col));\n\t\tcontour_vec_now.push_back(seg.FindContours(proj_wing_L_img,N_row,N_col));\n\t\tcontour_vec_now.push_back(seg.FindContours(proj_wing_R_img,N_row,N_col));\n\n\t\tcontour_vec_out.push_back(contour_vec_now);\n\t}\n\treturn contour_vec_out;\n}\n\narma::Mat<double> ContourOpt::CalculateContour(arma::Mat<double> &pts_in, double d_u, double d_v) {\n\n\tint N_pts = pts_in.n_cols;\n\n\t// find starting point (minimum u index):\n\n\tarma::Col<double> uv_start = pts_in.col(arma::index_min(pts_in.row(0)));\n\n\tarma::Col<double> uv_now = uv_start;\n\n\tarma::Col<double> uv_prev = uv_start;\n\n\tarma::uvec inds_u_plus;\n\tarma::uvec inds_u_min;\n\tarma::uvec inds_v_plus;\n\tarma::uvec inds_v_min;\n\n\tarma::uvec inds_neighbors;\n\n\tdouble theta_now;\n\n\tdouble theta_min;\n\n\tint theta_min_ind;\n\n\tarma::Mat<double> contour_pts;\n\n\tcontour_pts = uv_start;\n\n\tint iter = 0;\n\n\tint N_contour_pts = 0;\n\n\tbool contour_closed = false;\n\n\twhile (iter<N_pts && contour_closed==false) {\n\n\t\tinds_u_plus = arma::find(pts_in.row(0)>(uv_now(0)-d_u));\n\t\tinds_u_min = arma::find(pts_in.row(0)<(uv_now(0)+d_u));\n\t\tinds_v_plus = arma::find(pts_in.row(1)>(uv_now(1)-d_v));\n\t\tinds_v_min = arma::find(pts_in.row(1)<(uv_now(1)+d_v));\n\n\t\tinds_neighbors = arma::intersect(arma::intersect(inds_u_plus,inds_u_min),arma::intersect(inds_v_plus,inds_v_min));\n\n\t\tif (inds_neighbors.n_rows>0) {\n\n\t\t\ttheta_min = 2*PI;\n\t\t\ttheta_min_ind = -1;\n\n\t\t\tfor (int i=0; i<inds_neighbors.n_rows; i++) {\n\t\t\t\ttheta_now = atan2(pts_in(1,inds_neighbors(i))-uv_prev(1),pts_in(0,inds_neighbors(i))-uv_prev(0));\n\t\t\t\tif (isnan(theta_now)==0) {\n\t\t\t\t\tif (theta_now<theta_min) {\n\t\t\t\t\t\ttheta_min = theta_now;\n\t\t\t\t\t\ttheta_min_ind = i;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tuv_prev = uv_now;\n\n\t\t\tuv_now = pts_in.col(inds_neighbors(theta_min_ind));\n\n\t\t\tcontour_pts.insert_cols(N_contour_pts,uv_now);\n\t\t\tN_contour_pts++;\n\t\t\tif (uv_now(0)==uv_start(0) && uv_now(1)==uv_start(1)) {\n\t\t\t\tcontour_closed = true;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\titer = N_pts;\n\t\t\tcout << \"could not close contour\" << endl;\n\t\t}\n\t\titer++;\n\t}\n\n\treturn contour_pts;\n}\n\nlist<Polygon_with_holes_2> ContourOpt::CalcUnion(vector<Polygon_2> &polygons_in) {\n\n\tint N_c = polygons_in.size();\n\n\tPolygon_set_2 S;\n\n\tfor (int i=0; i<N_c; i++) {\n\t\tif (i==0) {\n\t\t\tS.insert(polygons_in[i]);\n\t\t}\n\t\telse {\n\t\t\tS.join(polygons_in[i]);\n\t\t}\n\t}\n\n\t//S.union()\n\n\tlist<Polygon_with_holes_2> res;\n\tS.polygons_with_holes (back_inserter (res));\n\n\treturn res;\n}\n\nlist<Polygon_with_holes_2> ContourOpt::CalcComplement(list<Polygon_with_holes_2> &pol_A, list<Polygon_with_holes_2> &pol_B) {\n\n\tPolygon_set_2 S;\n\n\tint iter_1 =0;\n\tfor (list<Polygon_with_holes_2>::iterator it_1=pol_B.begin(); it_1 !=pol_B.end(); ++it_1) {\n\t\t//cout << \"pol B area \" << it_1->outer_boundary().area() << endl;\n\t\tif (iter_1==0) {\n\t\t\tS.insert(*it_1);\n\t\t}\n\t\telse {\n\t\t\tS.join(*it_1);\n\t\t}\n\t\titer_1++;\n\t}\n\t\n\tint iter_2 = 0;\n\tfor (list<Polygon_with_holes_2>::iterator it_2=pol_A.begin(); it_2 !=pol_A.end(); ++it_2) {\n\t\t//cout << \"pol A area \" << it_2->outer_boundary().area() << endl;\n\t\tS.difference(*it_2);\n\t}\n\n\tlist<Polygon_with_holes_2> res;\n\tS.polygons_with_holes (back_inserter (res));\n\n\treturn res;\n}\n\nlist<Polygon_with_holes_2> ContourOpt::CalcSymmetricDifference(list<Polygon_with_holes_2> &pol_A, list<Polygon_with_holes_2> &pol_B) {\n\n\t/*\n\tPolygon_set_2 S;\n\n\tint iter_1 =0;\n\tfor (list<Polygon_with_holes_2>::iterator it_1=pol_B.begin(); it_1 !=pol_B.end(); ++it_1) {\n\t\tif (iter_1==0) {\n\t\t\tS.insert(*it_1);\n\t\t}\n\t\telse {\n\t\t\tS.join(*it_1);\n\t\t}\n\t\titer_1++;\n\t}\n\t\n\tint iter_2 = 0;\n\tfor (list<Polygon_with_holes_2>::iterator it_2=pol_A.begin(); it_2 !=pol_A.end(); ++it_2) {\n\t\tS.symmetric_difference(*it_2);\n\t}\n\n\tlist<Polygon_with_holes_2> res;\n\tS.polygons_with_holes (back_inserter (res));\n\t*/\n\t//cout << \"caclulating symmetric difference\" << endl;\n\tlist<Polygon_with_holes_2> res_out;\n\n\t//if (!pol_A.empty() && !pol_B.empty()){\n  \tfor (list<Polygon_with_holes_2>::iterator it_1=pol_B.begin(); it_1 !=pol_B.end(); ++it_1) {\n  \t\tfor (list<Polygon_with_holes_2>::iterator it_2=pol_A.begin(); it_2 !=pol_A.end(); ++it_2) {\n  \t\t\t//if (CGAL::do_intersect(*it_1, *it_2)) {\n  \t\t\t//cout << \"do intersect \" << CGAL::do_intersect(*it_1, *it_2) << endl;\n\t\t\t//cout << \"area pol_A \" << it_2->outer_boundary().area() << endl;\n\t\t\t//cout << \"area pol_B \" << it_1->outer_boundary().area() << endl;\n\t\t\tCGAL::symmetric_difference (*it_1, *it_2, back_inserter(res_out));\n\t\t\t//}\n\t\t\t//else {\n\t\t\t//\tcout << \"do not intersect \" << endl;\n\t\t\t//}\n\t\t}\n\t}\n\t//}\n\n\tcout << \"Res size: \" << res_out.size() << endl;\n\n\treturn res_out;\n}\n\narma::Mat<double> ContourOpt::ConvertPolygonWithHoles2Mat(list<Polygon_with_holes_2> &Pol_list_in) {\n\n\tint N_poly = Pol_list_in.size();\n\tint N_v;\n\tarma::Mat<double> mat_out;\n\n\tif (N_poly>0) {\n\t\tint iter = 0;\n\t\tvector<double> output_iterator;\n\t\tfor (list<Polygon_with_holes_2>::iterator it=Pol_list_in.begin(); it !=Pol_list_in.end(); ++it) {\n\t\t\t//cout << it->is_unbounded() << endl;\n\t\t\tN_v = it->outer_boundary().size();\n\t\t\tarma::Mat<double> curr_pol_mat(3,N_v);\n\t\t\tfor (int j=0; j<N_v; j++) {\n\t\t\t\tcurr_pol_mat(0,j) = static_cast<double>(it->outer_boundary().vertex(j).x());\n\t\t\t\tcurr_pol_mat(1,j) = static_cast<double>(it->outer_boundary().vertex(j).y());\n\t\t\t\tcurr_pol_mat(2,j) = iter+1;\n\t\t\t}\n\t\t\tif (iter==0) {\n\t\t\t\tmat_out = curr_pol_mat;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmat_out = arma::join_rows(mat_out, curr_pol_mat);\n\t\t\t}\n\t\t\titer++;\n\t\t}\n\t}\n\telse {\n\t\tmat_out.zeros(3,1);\n\t}\n\n\treturn mat_out;\n}\n\narma::Mat<double> ContourOpt::ConvertPolygon2Mat(Polygon_2 &Pol_in) {\n\n\tint N_v = Pol_in.size();\n\n\tarma::Mat<double> mat_out;\n\tmat_out.zeros(3,N_v);\n\n\t//int k=0;\n\n\t//for (VertexIterator vi = Pol_in.vertices_begin(); vi != Pol_in.vertices_end(); ++vi) {\n\tfor (int i=0; i<N_v; i++) {\n\n\t\tmat_out(0,i) = static_cast<double>(Pol_in.vertex(i).x());\n\t\tmat_out(1,i) = static_cast<double>(Pol_in.vertex(i).y());\n\t\tmat_out(2,i) = 1.0;\n\n\t\t//k++;\n\t}\n\n\treturn mat_out;\n}\n\nlist<Polygon_with_holes_2> ContourOpt::Convert2PolygonWithHoles(arma::Mat<double> &contour_mat) {\n\n\tint N_contours = contour_mat.row(2).max();\n\n\tarma::uvec temp_inds;\n\tarma::Mat<double> temp_mat;\n\n\tlist<Polygon_with_holes_2> poly_list_out;\n\n\tfor (int i=0; i<N_contours; i++) {\n\t\ttemp_inds = arma::find(contour_mat.row(2)==i+1);\n\t\ttemp_mat = contour_mat.cols(temp_inds);\n\t\tPolygon_with_holes_2 t_poly(ContourOpt::Convert2Polygon(temp_mat));\n\t\tpoly_list_out.push_back(t_poly);\n\t}\n\n\treturn poly_list_out;\n}\n\nPolygon_2 ContourOpt::Convert2Polygon(arma::Mat<double> &contour_mat) {\n\n\t// Run through the points and construct a Polygon_2 object:\n\tPolygon_2 P;\n\n\tint N_pts = contour_mat.n_cols;\n\n\t//for (int i=0; i<N_pts; i++) {\n\tfor (int i=(N_pts-1); i>=0; i--) {\n\t\tP.push_back(Point_2 (contour_mat(0,i),contour_mat(1,i)));\n\t}\n\n\treturn P;\n}\n\np::list ContourOpt::ReturnInitContour(int cam_nr) {\n\n\tp::list init_contour_list;\n\n\tarma::Mat<double> body_c = body_init_contours[cam_nr];\n\tarma::Mat<double> wing_L_c = wing_L_init_contours[cam_nr];\n\tarma::Mat<double> wing_R_c = wing_R_init_contours[cam_nr];\n\n\tarma::uvec found_ids;\n\tint N_found;\n\n\tfor (int i=0; i<body_c.row(2).max(); i++) {\n\t\tfound_ids = arma::find(body_c.row(2)==i+1);\n\t\tN_found = found_ids.n_rows;\n\t\tif (N_found>1) {\n\t\t\tp::tuple shape = p::make_tuple(3,N_found);\n\t\t\tnp::dtype dtype = np::dtype::get_builtin<double>();\n\t\t\tnp::ndarray c_array = np::zeros(shape,dtype);\n\t\t\tfor (int j=0; j<N_found; j++) {\n\t\t\t\tc_array[0][j] = body_c(0,found_ids(j));\n\t\t\t\tc_array[1][j] = body_c(1,found_ids(j));\n\t\t\t\tc_array[2][j] = 1;\n\t\t\t}\n\t\t\tinit_contour_list.append(c_array);\n\t\t}\n\t}\n\n\tfor (int i=0; i<wing_L_c.row(2).max(); i++) {\n\t\tfound_ids = arma::find(wing_L_c.row(2)==i+1);\n\t\tN_found = found_ids.n_rows;\n\t\tif (N_found>1) {\n\t\t\tp::tuple shape = p::make_tuple(3,N_found);\n\t\t\tnp::dtype dtype = np::dtype::get_builtin<double>();\n\t\t\tnp::ndarray c_array = np::zeros(shape,dtype);\n\t\t\tfor (int j=0; j<N_found; j++) {\n\t\t\t\tc_array[0][j] = wing_L_c(0,found_ids(j));\n\t\t\t\tc_array[1][j] = wing_L_c(1,found_ids(j));\n\t\t\t\tc_array[2][j] = 2;\n\t\t\t}\n\t\t\tinit_contour_list.append(c_array);\n\t\t}\n\t}\n\n\tfor (int i=0; i<wing_R_c.row(2).max(); i++) {\n\t\tfound_ids = arma::find(wing_R_c.row(2)==i+1);\n\t\tN_found = found_ids.n_rows;\n\t\tif (N_found>1) {\n\t\t\tp::tuple shape = p::make_tuple(3,N_found);\n\t\t\tnp::dtype dtype = np::dtype::get_builtin<double>();\n\t\t\tnp::ndarray c_array = np::zeros(shape,dtype);\n\t\t\tfor (int j=0; j<N_found; j++) {\n\t\t\t\tc_array[0][j] = wing_R_c(0,found_ids(j));\n\t\t\t\tc_array[1][j] = wing_R_c(1,found_ids(j));\n\t\t\t\tc_array[2][j] = 3;\n\t\t\t}\n\t\t\tinit_contour_list.append(c_array);\n\t\t}\n\t}\n\n\treturn init_contour_list;\n}\n\np::list ContourOpt::ReturnDestContour(int cam_nr) {\n\n\tp::list dest_contour_list;\n\n\tarma::Mat<double> body_c = body_dest_contours[cam_nr];\n\tarma::Mat<double> wing_L_c = wing_L_dest_contours[cam_nr];\n\tarma::Mat<double> wing_R_c = wing_R_dest_contours[cam_nr];\n\n\tarma::uvec found_ids;\n\tint N_found;\n\n\tfor (int i=0; i<body_c.row(2).max(); i++) {\n\t\tfound_ids = arma::find(body_c.row(2)==i+1);\n\t\tN_found = found_ids.n_rows;\n\t\tif (N_found>1) {\n\t\t\tp::tuple shape = p::make_tuple(3,N_found);\n\t\t\tnp::dtype dtype = np::dtype::get_builtin<double>();\n\t\t\tnp::ndarray c_array = np::zeros(shape,dtype);\n\t\t\tfor (int j=0; j<N_found; j++) {\n\t\t\t\tc_array[0][j] = body_c(0,found_ids(j));\n\t\t\t\tc_array[1][j] = body_c(1,found_ids(j));\n\t\t\t\tc_array[2][j] = 1;\n\t\t\t}\n\t\t\tdest_contour_list.append(c_array);\n\t\t}\n\t}\n\n\tfor (int i=0; i<wing_L_c.row(2).max(); i++) {\n\t\tfound_ids = arma::find(wing_L_c.row(2)==i+1);\n\t\tN_found = found_ids.n_rows;\n\t\tif (N_found>1) {\n\t\t\tp::tuple shape = p::make_tuple(3,N_found);\n\t\t\tnp::dtype dtype = np::dtype::get_builtin<double>();\n\t\t\tnp::ndarray c_array = np::zeros(shape,dtype);\n\t\t\tfor (int j=0; j<N_found; j++) {\n\t\t\t\tc_array[0][j] = wing_L_c(0,found_ids(j));\n\t\t\t\tc_array[1][j] = wing_L_c(1,found_ids(j));\n\t\t\t\tc_array[2][j] = 2;\n\t\t\t}\n\t\t\tdest_contour_list.append(c_array);\n\t\t}\n\t}\n\n\tfor (int i=0; i<wing_R_c.row(2).max(); i++) {\n\t\tfound_ids = arma::find(wing_R_c.row(2)==i+1);\n\t\tN_found = found_ids.n_rows;\n\t\tif (N_found>1) {\n\t\t\tp::tuple shape = p::make_tuple(3,N_found);\n\t\t\tnp::dtype dtype = np::dtype::get_builtin<double>();\n\t\t\tnp::ndarray c_array = np::zeros(shape,dtype);\n\t\t\tfor (int j=0; j<N_found; j++) {\n\t\t\t\tc_array[0][j] = wing_R_c(0,found_ids(j));\n\t\t\t\tc_array[1][j] = wing_R_c(1,found_ids(j));\n\t\t\t\tc_array[2][j] = 3;\n\t\t\t}\n\t\t\tdest_contour_list.append(c_array);\n\t\t}\n\t}\n\n\treturn dest_contour_list;\n}", "meta": {"hexsha": "27d26fbcabbe92905008767c070398a561829e56", "size": 28042, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "contour_optimization.cpp", "max_stars_repo_name": "jmmelis/DipteraTrack", "max_stars_repo_head_hexsha": "1d267ccd4248635233147f2035b900a433dc4536", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-14T10:19:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-14T10:19:19.000Z", "max_issues_repo_path": "contour_optimization.cpp", "max_issues_repo_name": "jmmelis/DipteraTrack", "max_issues_repo_head_hexsha": "1d267ccd4248635233147f2035b900a433dc4536", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "contour_optimization.cpp", "max_forks_repo_name": "jmmelis/DipteraTrack", "max_forks_repo_head_hexsha": "1d267ccd4248635233147f2035b900a433dc4536", "max_forks_repo_licenses": ["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.0235546039, "max_line_length": 206, "alphanum_fraction": 0.6592254475, "num_tokens": 9614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283033, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.27895681355756097}}
{"text": "#include \"operators_c.h\"\n#include \"operators.h\"\n#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace std;\n\nstatic dfloat_t *to_c(VectorXd &v)\n{\n  dfloat_t *vdata = (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * v.size());\n#if USE_DFLOAT_DOUBLE == 1\n  Eigen::Map<Eigen::VectorXd>(vdata, v.size()) = v.cast<dfloat_t>();\n#else\n  Eigen::Map<Eigen::VectorXf>(vdata, v.size()) = v.cast<dfloat_t>();\n#endif\n  return vdata;\n}\n\nstatic dfloat_t *to_c(MatrixXd &m)\n{\n  dfloat_t *mdata = (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * m.size());\n#if USE_DFLOAT_DOUBLE == 1\n  Eigen::Map<Eigen::MatrixXd>(mdata, m.rows(), m.cols()) = m.cast<dfloat_t>();\n#else\n  Eigen::Map<Eigen::MatrixXf>(mdata, m.rows(), m.cols()) = m.cast<dfloat_t>();\n#endif\n  return mdata;\n}\n\nstatic uintloc_t *to_c(MatrixXu32 &m)\n{\n  uintloc_t *mdata =\n      (uintloc_t *)asd_malloc_aligned(sizeof(uintloc_t) * m.size());\n  Eigen::Map<Eigen::Matrix<uintloc_t, Eigen::Dynamic, Eigen::Dynamic>>(\n      mdata, m.rows(), m.cols()) = m.cast<uintloc_t>();\n  return mdata;\n}\n\nhost_operators_t *host_operators_new_2D(int N, int M, uintloc_t E,\n                                        uintloc_t *EToE, uint8_t *EToF,\n                                        uint8_t *EToO, double *EToVX)\n{\n  host_operators_t *ops =\n      (host_operators_t *)asd_malloc(sizeof(host_operators_t));\n\n  ref_elem_data *ref_data = build_ref_ops_2D(N, M, M);\n\n  VectorXd wq = ref_data->wq;\n\n  // nodal\n  MatrixXd Dr = ref_data->Dr;\n  MatrixXd Ds = ref_data->Ds;\n  MatrixXd Vq = ref_data->Vq;\n\n  VectorXd wfq = ref_data->wfq;\n  VectorXd nrJ = ref_data->nrJ;\n  VectorXd nsJ = ref_data->nsJ;\n  MatrixXd Vfqf = ref_data->Vfqf;\n  MatrixXd Vfq = ref_data->Vfq;\n  MatrixXd Pq = ref_data->Pq;\n\n  MatrixXd MM = Vq.transpose() * wq.asDiagonal() * Vq;\n  MatrixXd MMfq = Vfq.transpose() * wfq.asDiagonal();\n  MatrixXd Lq = mldivide(MM, MMfq);\n  MatrixXd VqLq = Vq * Lq;\n  MatrixXd VqPq = Vq * Pq;\n  MatrixXd VfPq = Vfq * Pq;\n  MatrixXd Drq = Vq * Dr * Pq - .5 * Vq * Lq * nrJ.asDiagonal() * Vfq * Pq;\n  MatrixXd Dsq = Vq * Ds * Pq - .5 * Vq * Lq * nsJ.asDiagonal() * Vfq * Pq;\n\n  ops->dim = 2;\n\n  ops->N = N;\n  ops->M = M;\n\n  ops->Np = (int)ref_data->r.size();\n  ops->Nq = (int)ref_data->rq.size();\n\n  // printf(\"Num cubature points Nq = %d\\n\",ops->Nq);\n\n  ops->Nfp = N + 1;\n  ops->Nfq = (int)ref_data->ref_rfq.size();\n\n  ops->Nfaces = ref_data->Nfaces;\n  ops->Nvgeo = 4;\n  ops->Nfgeo = 3;\n\n  ops->wq = to_c(wq);\n  ops->nrJ = to_c(nrJ);\n  ops->nsJ = to_c(nsJ);\n\n  ops->Drq = to_c(Drq);\n  ops->Dsq = to_c(Dsq);\n\n  ops->Vq = to_c(Vq);\n  ops->Pq = to_c(Pq);\n\n  ops->VqLq = to_c(VqLq);\n  ops->VqPq = to_c(VqPq);\n  ops->VfPq = to_c(VfPq);\n  ops->Vfqf = to_c(Vfqf);\n\n  Map<MatrixXd> EToVXmat(EToVX, 2 * 3, E);\n\n  if (sizeof(uintloc_t) != sizeof(uint32_t))\n  {\n    cerr << \"Need to update build maps to support different integer types\"\n         << endl;\n    std::abort();\n  }\n  Map<MatrixXu32> mapEToE(EToE, 3, E);\n  Map<MatrixXu8> mapEToF(EToF, 3, E);\n  Map<MatrixXu8> mapEToO(EToO, 3, E);\n\n  geo_elem_data *geo_data = build_geofacs_2D(ref_data, EToVXmat);\n  map_elem_data *map_data = build_maps_2D(ref_data, mapEToE, mapEToF, mapEToO);\n\n  const int Nvgeo = ops->Nvgeo;\n  const int Nfgeo = ops->Nfgeo;\n  const int Nfaces = ref_data->Nfaces;\n  const int Nq = ops->Nq;\n  const int Nfq = ops->Nfq;\n\n  ops->xyzq =\n      (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nq * 3 * E);\n  ops->xyzf = (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nfq *\n                                             ops->Nfaces * 3 * E);\n  ops->vgeo =\n      (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nq * Nvgeo * E);\n  ops->vfgeo = (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nfq *\n                                              Nfaces * Nvgeo * E);\n  ops->fgeo = (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nfq *\n                                             Nfgeo * Nfaces * E);\n\n  for (uintloc_t e = 0; e < E; ++e)\n  {\n    for (int n = 0; n < Nq; ++n)\n    {\n      ops->xyzq[n + 0 * Nq + e * Nq * 3] = (dfloat_t)geo_data->xq(n, e);\n      ops->xyzq[n + 1 * Nq + e * Nq * 3] = (dfloat_t)geo_data->yq(n, e);\n      // ops->xyzq[n + 2*Nq + e*Nq*3] = (dfloat_t)geo_data->zq(n,e);\n\n      ops->vgeo[e * Nq * Nvgeo + 0 * Nq + n] = (dfloat_t)geo_data->rxJ(n, e);\n      ops->vgeo[e * Nq * Nvgeo + 1 * Nq + n] = (dfloat_t)geo_data->ryJ(n, e);\n      ops->vgeo[e * Nq * Nvgeo + 2 * Nq + n] = (dfloat_t)geo_data->sxJ(n, e);\n      ops->vgeo[e * Nq * Nvgeo + 3 * Nq + n] = (dfloat_t)geo_data->syJ(n, e);\n    }\n  }\n\n  for (uintloc_t e = 0; e < E; ++e)\n  {\n    for (int n = 0; n < Nfq * Nfaces; ++n)\n    {\n      ops->xyzf[n + 0 * Nfq * Nfaces + e * Nfq * Nfaces * 3] =\n          (dfloat_t)geo_data->xf(n, e);\n      ops->xyzf[n + 1 * Nfq * Nfaces + e * Nfq * Nfaces * 3] =\n          (dfloat_t)geo_data->yf(n, e);\n\n      ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 0 * Nfq * Nfaces + n] =\n          (dfloat_t)geo_data->rxJf(n, e);\n      ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 1 * Nfq * Nfaces + n] =\n          (dfloat_t)geo_data->ryJf(n, e);\n      ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 2 * Nfq * Nfaces + n] =\n          (dfloat_t)geo_data->sxJf(n, e);\n      ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 3 * Nfq * Nfaces + n] =\n          (dfloat_t)geo_data->syJf(n, e);\n\n      ops->fgeo[e * Nfq * Nfaces * Nfgeo + 0 * Nfq * Nfaces + n] =\n          (dfloat_t)geo_data->nxJ(n, e);\n      ops->fgeo[e * Nfq * Nfaces * Nfgeo + 1 * Nfq * Nfaces + n] =\n          (dfloat_t)geo_data->nyJ(n, e);\n      ops->fgeo[e * Nfq * Nfaces * Nfgeo + 2 * Nfq * Nfaces + n] =\n          (dfloat_t)geo_data->sJ(n, e);\n    }\n  }\n\n  ops->Jq = to_c(geo_data->J);\n  ops->mapPq = to_c(map_data->mapPq);\n  //  ops->mapPqNoFields = to_c(map_data->mapPq);  // save\n\n  /*\n  // JC: FIX LATER - only valid for tri2.msh\n  ops->mapPq[0] = 7;\n  ops->mapPq[1] = 6;\n  ops->mapPq[2] = 9;\n  ops->mapPq[3] = 8;\n  ops->mapPq[6] = 1;\n  ops->mapPq[7] = 0;\n  ops->mapPq[8] = 3;\n  ops->mapPq[9] = 2;\n  */\n\n  //  for(int i = 0; i < Nfq*Nfaces*E; ++i){\n  //    printf(\"mapPq(%d) = %d\\n\",i,ops->mapPq[i]);\n  //  }\n  ops->Fmask = to_c(map_data->fmask);\n\n  delete ref_data;\n  delete geo_data;\n  delete map_data;\n\n  return ops;\n}\n\nhost_operators_t *host_operators_new_3D(int N, int M, uintloc_t E,\n                                        uintloc_t *EToE, uint8_t *EToF,\n                                        uint8_t *EToO, double *EToVX)\n{\n  host_operators_t *ops =\n      (host_operators_t *)asd_malloc(sizeof(host_operators_t));\n\n  ref_elem_data *ref_data = build_ref_ops_3D(N, M, M);\n\n  VectorXd wq = ref_data->wq;\n\n  // nodal\n  MatrixXd Dr = ref_data->Dr;\n  MatrixXd Ds = ref_data->Ds;\n  MatrixXd Dt = ref_data->Dt;\n  MatrixXd Vq = ref_data->Vq;\n  MatrixXd Pq = ref_data->Pq;\n  MatrixXd Vfqf = ref_data->Vfqf;\n  MatrixXd Vfq = ref_data->Vfq;\n\n  VectorXd wfq = ref_data->wfq;\n  VectorXd nrJ = ref_data->nrJ;\n  VectorXd nsJ = ref_data->nsJ;\n  VectorXd ntJ = ref_data->ntJ;\n\n  MatrixXd MM = Vq.transpose() * wq.asDiagonal() * Vq;\n  MatrixXd MMfq = Vfq.transpose() * wfq.asDiagonal();\n  MatrixXd Lq = mldivide(MM, MMfq);\n  MatrixXd VqLq = Vq * Lq;\n  MatrixXd VqPq = Vq * Pq;\n  MatrixXd VfPq = Vfq * Pq;\n  MatrixXd Drq = Vq * Dr * Pq - .5 * Vq * Lq * nrJ.asDiagonal() * Vfq * Pq;\n  MatrixXd Dsq = Vq * Ds * Pq - .5 * Vq * Lq * nsJ.asDiagonal() * Vfq * Pq;\n  MatrixXd Dtq = Vq * Dt * Pq - .5 * Vq * Lq * ntJ.asDiagonal() * Vfq * Pq;\n\n  MatrixXd Drstq(Drq.rows(),3*Drq.cols());\n  Drstq << Drq,Dsq,Dtq;\n\n  /*\n  cout << \"VqPq = \" << endl << VqPq << endl;\n  cout << \"VqLq = \" << endl << VqLq << endl;\n  cout << \"VfPq = \" << endl << VfPq << endl;\n\n  cout << \"Drq = \" << endl << Drq << endl;\n  cout << \"nrJ = \" << endl << nrJ << endl;\n  cout << \"Dsq = \" << endl << Dsq << endl;\n  cout << \"nsJ = \" << endl << nsJ << endl;\n  cout << \"Dtq = \" << endl << Dtq << endl;\n  cout << \"ntJ = \" << endl << ntJ << endl;\n  */\n\n  ops->dim = 3;\n\n  ops->N = N;\n  ops->M = M;\n\n  ops->Np = (int)ref_data->r.size();\n  ops->Nq = (int)ref_data->rq.size();\n\n  ops->Nfp = (N + 1) * (N + 2) / 2;\n  ops->Nfq = (int)ref_data->ref_rfq.size();\n\n  ops->Nfaces = ref_data->Nfaces;\n  ops->Nvgeo = 9;\n  ops->Nfgeo = 4;\n\n  ops->wq = to_c(wq);\n  ops->nrJ = to_c(nrJ);\n  ops->nsJ = to_c(nsJ);\n  ops->ntJ = to_c(ntJ);\n\n  ops->Drq = to_c(Drq);\n  ops->Dsq = to_c(Dsq);\n  ops->Dtq = to_c(Dtq);\n\n  ops->Drstq = to_c(Drstq);\n\n  ops->Vq = to_c(Vq);\n  ops->Pq = to_c(Pq);\n\n  ops->VqLq = to_c(VqLq);\n  ops->VqPq = to_c(VqPq);\n  ops->VfPq = to_c(VfPq);\n  ops->Vfqf = to_c(Vfqf);\n\n  Map<MatrixXd> EToVXmat(EToVX, 3 * 4, E);\n\n  if (sizeof(uintloc_t) != sizeof(uint32_t))\n  {\n    cerr << \"Need to update build maps to support different integer types\"\n         << endl;\n    std::abort();\n  }\n  Map<MatrixXu32> mapEToE(EToE, 4, E);\n  Map<MatrixXu8> mapEToF(EToF, 4, E);\n  Map<MatrixXu8> mapEToO(EToO, 4, E);\n\n  geo_elem_data *geo_data = build_geofacs_3D(ref_data, EToVXmat);\n  map_elem_data *map_data = build_maps_3D(ref_data, mapEToE, mapEToF, mapEToO);\n\n  const int Nvgeo = ops->Nvgeo;\n  const int Nfgeo = ops->Nfgeo;\n  const int Nfaces = ref_data->Nfaces;\n  const int Nq = ops->Nq;\n  const int Nfq = ops->Nfq;\n\n  ops->xyzq =\n      (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nq * 3 * E);\n  ops->xyzf = (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nfq *\n                                             ops->Nfaces * 3 * E);\n  ops->vgeo =\n      (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nq * Nvgeo * E);\n  ops->vfgeo = (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nfq *\n                                              Nfaces * Nvgeo * E);\n  ops->fgeo = (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nfq *\n                                             Nfgeo * Nfaces * E);\n\n  for (uintloc_t e = 0; e < E; ++e)\n  {\n    for (int n = 0; n < Nq; ++n)\n    {\n      ops->xyzq[n + 0 * Nq + e * Nq * 3] = (dfloat_t)geo_data->xq(n, e);\n      ops->xyzq[n + 1 * Nq + e * Nq * 3] = (dfloat_t)geo_data->yq(n, e);\n      ops->xyzq[n + 2 * Nq + e * Nq * 3] = (dfloat_t)geo_data->zq(n, e);\n\n      ops->vgeo[e * Nq * Nvgeo + 0 * Nq + n] = (dfloat_t)geo_data->rxJ(n, e);\n      ops->vgeo[e * Nq * Nvgeo + 1 * Nq + n] = (dfloat_t)geo_data->ryJ(n, e);\n      ops->vgeo[e * Nq * Nvgeo + 2 * Nq + n] = (dfloat_t)geo_data->rzJ(n, e);\n      ops->vgeo[e * Nq * Nvgeo + 3 * Nq + n] = (dfloat_t)geo_data->sxJ(n, e);\n      ops->vgeo[e * Nq * Nvgeo + 4 * Nq + n] = (dfloat_t)geo_data->syJ(n, e);\n      ops->vgeo[e * Nq * Nvgeo + 5 * Nq + n] = (dfloat_t)geo_data->szJ(n, e);\n      ops->vgeo[e * Nq * Nvgeo + 6 * Nq + n] = (dfloat_t)geo_data->txJ(n, e);\n      ops->vgeo[e * Nq * Nvgeo + 7 * Nq + n] = (dfloat_t)geo_data->tyJ(n, e);\n      ops->vgeo[e * Nq * Nvgeo + 8 * Nq + n] = (dfloat_t)geo_data->tzJ(n, e);\n    }\n  }\n\n  for (uintloc_t e = 0; e < E; ++e)\n  {\n    for (int n = 0; n < Nfq * Nfaces; ++n)\n    {\n      ops->xyzf[n + 0 * Nfq * Nfaces + e * Nfq * Nfaces * 3] =\n          (dfloat_t)geo_data->xf(n, e);\n      ops->xyzf[n + 1 * Nfq * Nfaces + e * Nfq * Nfaces * 3] =\n          (dfloat_t)geo_data->yf(n, e);\n      ops->xyzf[n + 2 * Nfq * Nfaces + e * Nfq * Nfaces * 3] =\n          (dfloat_t)geo_data->zf(n, e);\n\n      ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 0 * Nfq * Nfaces + n] =\n          (dfloat_t)geo_data->rxJf(n, e);\n      ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 1 * Nfq * Nfaces + n] =\n          (dfloat_t)geo_data->ryJf(n, e);\n      ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 2 * Nfq * Nfaces + n] =\n          (dfloat_t)geo_data->rzJf(n, e);\n      ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 3 * Nfq * Nfaces + n] =\n          (dfloat_t)geo_data->sxJf(n, e);\n      ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 4 * Nfq * Nfaces + n] =\n          (dfloat_t)geo_data->syJf(n, e);\n      ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 5 * Nfq * Nfaces + n] =\n          (dfloat_t)geo_data->szJf(n, e);\n      ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 6 * Nfq * Nfaces + n] =\n          (dfloat_t)geo_data->txJf(n, e);\n      ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 7 * Nfq * Nfaces + n] =\n          (dfloat_t)geo_data->tyJf(n, e);\n      ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 8 * Nfq * Nfaces + n] =\n          (dfloat_t)geo_data->tzJf(n, e);\n\n      ops->fgeo[e * Nfq * Nfaces * Nfgeo + 0 * Nfq * Nfaces + n] =\n        (dfloat_t)geo_data->nxJ(n, e);\n      ops->fgeo[e * Nfq * Nfaces * Nfgeo + 1 * Nfq * Nfaces + n] =\n        (dfloat_t)geo_data->nyJ(n, e);\n      ops->fgeo[e * Nfq * Nfaces * Nfgeo + 2 * Nfq * Nfaces + n] =\n        (dfloat_t)geo_data->nzJ(n, e);\n      ops->fgeo[e * Nfq * Nfaces * Nfgeo + 3 * Nfq * Nfaces + n] =\n        (dfloat_t)geo_data->sJ(n, e);\n      //      if (e==99){\n      //        printf(\"n = %d, nxJ = %f\\n\", n, (dfloat_t) geo_data->nxJ(n,e));\n      //      }\n    }\n  }\n\n  ops->Jq = to_c(geo_data->J);\n\n  ops->mapPq = to_c(map_data->mapPq);\n  ops->Fmask = to_c(map_data->fmask);\n\n  delete ref_data;\n  delete geo_data;\n  delete map_data;\n\n  return ops;\n}\n\nvoid host_operators_free(host_operators_t *ops)\n{\n  asd_free_aligned(ops->vgeo);\n  asd_free_aligned(ops->fgeo);\n  asd_free_aligned(ops->Jq);\n\n  asd_free_aligned(ops->mapPq);\n  asd_free_aligned(ops->Fmask);\n\n  asd_free_aligned(ops->nrJ);\n  asd_free_aligned(ops->nsJ);\n\n  asd_free_aligned(ops->Drq);\n  asd_free_aligned(ops->Dsq);\n\n  if (ops->dim == 3)\n  {\n    asd_free_aligned(ops->ntJ);\n    asd_free_aligned(ops->Dtq);\n  }\n\n  asd_free_aligned(ops->Vq);\n  asd_free_aligned(ops->Pq);\n\n  asd_free_aligned(ops->VqLq);\n  asd_free_aligned(ops->VqPq);\n  asd_free_aligned(ops->VfPq);\n  asd_free_aligned(ops->Vfqf);\n}\n", "meta": {"hexsha": "53fe5e6aeb1f1c44f8f4face1da69d196f13f417", "size": 13467, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "operators_c.cpp", "max_stars_repo_name": "ntan15/scratch_wadge", "max_stars_repo_head_hexsha": "0657069749b9507062c1f7e875c6545076fb85c8", "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": "operators_c.cpp", "max_issues_repo_name": "ntan15/scratch_wadge", "max_issues_repo_head_hexsha": "0657069749b9507062c1f7e875c6545076fb85c8", "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": "operators_c.cpp", "max_forks_repo_name": "ntan15/scratch_wadge", "max_forks_repo_head_hexsha": "0657069749b9507062c1f7e875c6545076fb85c8", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5386416862, "max_line_length": 80, "alphanum_fraction": 0.5568426524, "num_tokens": 5306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.27890705751695793}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2019 Tinko Bartels, Berlin, Germany.\n\n// Contributed and/or modified by Tinko Bartels,\n//   as part of Google Summer of Code 2019 program.\n\n// This file was modified by Oracle on 2021.\n// Modifications copyright (c) 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 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_STRATEGY_CARTESIAN_SIDE_ROBUST_HPP\n#define BOOST_GEOMETRY_STRATEGY_CARTESIAN_SIDE_ROBUST_HPP\n\n#include <boost/geometry/core/config.hpp>\n#include <boost/geometry/strategy/cartesian/side_non_robust.hpp>\n\n#include <boost/geometry/strategies/side.hpp>\n\n#include <boost/geometry/util/select_most_precise.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n#include <boost/geometry/util/precise_math.hpp>\n#include <boost/geometry/util/math.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace side\n{\n\nstruct epsilon_equals_policy\n{\npublic:\n    template <typename Policy, typename T1, typename T2>\n    static bool apply(T1 const& a, T2 const& b, Policy const& policy)\n    {\n        return boost::geometry::math::detail::equals_by_policy(a, b, policy);\n    }\n};\n\nstruct fp_equals_policy\n{\npublic:\n    template <typename Policy, typename T1, typename T2>\n    static bool apply(T1 const& a, T2 const& b, Policy const&)\n    {\n        return a == b;\n    }\n};\n\n\n/*!\n\\brief Adaptive precision predicate to check at which side of a segment a point lies:\n    left of segment (>0), right of segment (< 0), on segment (0).\n\\ingroup strategies\n\\tparam CalculationType \\tparam_calculation (numeric_limits<ct>::epsilon() and numeric_limits<ct>::digits must be supported for calculation type ct)\n\\tparam Robustness std::size_t value from 0 (fastest) to 3 (default, guarantees correct results).\n\\details This predicate determines at which side of a segment a point lies using an algorithm that is adapted from orient2d as described in \"Adaptive Precision Floating-Point Arithmetic and Fast Robust Geometric Predicates\" by Jonathan Richard Shewchuk ( https://dl.acm.org/citation.cfm?doid=237218.237337 ). More information and copies of the paper can also be found at https://www.cs.cmu.edu/~quake/robust.html . It is designed to be adaptive in the sense that it should be fast for inputs that lead to correct results with plain float operations but robust for inputs that require higher precision arithmetics.\n */\ntemplate\n<\n    typename CalculationType = void,\n    typename EqualsPolicy = epsilon_equals_policy,\n    std::size_t Robustness = 3\n>\nstruct side_robust\n{\n\n    template <typename CT>\n    struct epsilon_policy\n    {\n        using Policy = boost::geometry::math::detail::equals_factor_policy<CT>;\n\n        epsilon_policy() {}\n\n        template <typename Type>\n        epsilon_policy(Type const& a, Type const& b, Type const& c, Type const& d)\n            : m_policy(a, b, c, d)\n        {}\n        Policy m_policy;\n\n    public:\n\n        template <typename T1, typename T2>\n        bool apply(T1 a, T2 b) const\n        {\n            return EqualsPolicy::apply(a, b, m_policy);\n        }\n    };\n\npublic:\n\n    typedef cartesian_tag cs_tag;\n\n    //! \\brief Computes the sign of the CCW triangle p1, p2, p\n    template\n    <\n        typename PromotedType,\n        typename P1,\n        typename P2,\n        typename P,\n        typename EpsPolicyInternal,\n        std::enable_if_t<std::is_fundamental<PromotedType>::value, int> = 0\n    >\n    static inline PromotedType side_value(P1 const& p1,\n                                          P2 const& p2,\n                                          P const& p,\n                                          EpsPolicyInternal& eps_policy)\n    {\n        using vec2d = ::boost::geometry::detail::precise_math::vec2d<PromotedType>;\n        vec2d pa;\n        pa.x = get<0>(p1);\n        pa.y = get<1>(p1);\n        vec2d pb;\n        pb.x = get<0>(p2);\n        pb.y = get<1>(p2);\n        vec2d pc;\n        pc.x = get<0>(p);\n        pc.y = get<1>(p);\n        return ::boost::geometry::detail::precise_math::orient2d\n            <PromotedType, Robustness>(pa, pb, pc, eps_policy);\n    }\n\n    template\n    <\n        typename PromotedType,\n        typename P1,\n        typename P2,\n        typename P,\n        typename EpsPolicyInternal,\n        std::enable_if_t<!std::is_fundamental<PromotedType>::value, int> = 0\n    >\n    static inline auto side_value(P1 const& p1, P2 const& p2, P const& p,\n                                  EpsPolicyInternal&)\n    {\n        return side_non_robust<>::apply(p1, p2, p);\n    }\n\n#ifndef DOXYGEN_SHOULD_SKIP_THIS\n    template\n    <\n        typename P1,\n        typename P2,\n        typename P\n    >\n    static inline int apply(P1 const& p1, P2 const& p2, P const& p)\n    {\n        using coordinate_type = typename select_calculation_type_alt\n            <\n                CalculationType,\n                P1,\n                P2,\n                P\n            >::type;\n\n        using promoted_type = typename select_most_precise\n            <\n                coordinate_type,\n                double\n            >::type;\n\n        epsilon_policy<promoted_type> epsp;\n        promoted_type sv = side_value<promoted_type>(p1, p2, p, epsp);\n        promoted_type const zero = promoted_type();\n\n        return epsp.apply(sv, zero) ? 0\n            : sv > zero ? 1\n            : -1;\n    }\n\n#endif\n\n};\n\n}} // namespace strategy::side\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGY_CARTESIAN_SIDE_ROBUST_HPP\n", "meta": {"hexsha": "c8405e9329e11cd8f3c2af2e59d6c59b29fab7c3", "size": 5779, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AqooleEngine/src/main/cpp/boost/boost/geometry/strategy/cartesian/side_robust.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/geometry/strategy/cartesian/side_robust.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/geometry/strategy/cartesian/side_robust.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": 31.0698924731, "max_line_length": 613, "alphanum_fraction": 0.6459595086, "num_tokens": 1425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2789070454488447}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   Utility_AtomUnit.hpp\n//! \\author Alex Robinson\n//! \\brief  The atom unit declaration\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef UTILITY_ATOM_UNIT_HPP\n#define UTILITY_ATOM_UNIT_HPP\n\n// Boost Includes\n#include <boost/units/systems/si/amount.hpp>\n#include <boost/units/base_unit.hpp>\n#include <boost/units/conversion.hpp>\n#include <boost/units/io.hpp>\n\n// FRENSIE Includes\n#include \"Utility_RawPhysicalConstants.hpp\"\n\nnamespace Utility{\n\nnamespace Units{\n\n//! The atom base unit\nstruct AtomBaseUnit : public boost::units::base_unit<AtomBaseUnit, boost::units::amount_dimension,2>\n{\n  static const char* name() { return \"atom\"; }\n  static const char* symbol() { return \"atom\"; }\n};\n\n//! The atom unit\ntypedef AtomBaseUnit::unit_type Atom;\n\nBOOST_UNITS_STATIC_CONSTANT( atom, Atom );\n\n} // end Units namespace\n\n} // end Utility namespace\n\nBOOST_UNITS_DEFINE_CONVERSION_FACTOR( Utility::Units::AtomBaseUnit, boost::units::si::amount, double, 1.0/Utility::RawPhysicalConstants::avogadro_constant );\nBOOST_UNITS_DEFINE_CONVERSION_FACTOR( boost::units::si::amount, Utility::Units::AtomBaseUnit, double, Utility::RawPhysicalConstants::avogadro_constant );\n\nBOOST_UNITS_DEFAULT_CONVERSION( Utility::Units::AtomBaseUnit, boost::units::si::amount );\n\n#endif // end UTILITY_ATOM_UNIT_HPP\n\n//---------------------------------------------------------------------------//\n// end Utility_AtomUnit.hpp\n//---------------------------------------------------------------------------//\n\n", "meta": {"hexsha": "0441c6b2c5071e640bc72338903604017267ce25", "size": 1610, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/utility/core/src/Utility_AtomUnit.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/core/src/Utility_AtomUnit.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/core/src/Utility_AtomUnit.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": 30.9615384615, "max_line_length": 157, "alphanum_fraction": 0.6124223602, "num_tokens": 328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.27889229316299735}}
{"text": "// Copyright 2015 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/// Writes the distribution in files.\n\n#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <boost/filesystem.hpp>\n#include <boost/mpi.hpp>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <cmakevars.hpp>\n#include <constants.hpp>\n#include <utilities.hpp>\n#include <structures.hpp>\n#include <bulk_hdf5.hpp>\n#include <isotopic_scattering.hpp>\n#include <io_utils.hpp>\n#include <msgpack.hpp>\n#include <geometry_2d.hpp>\n#include <boost/math/distributions/gamma.hpp>\n#include <boost/property_tree/xml_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n\n\n///Some alias\nusing gridData = std::unordered_map<std::string,\n        std::unique_ptr<alma::Gamma_grid>>;\nusing cellData = std::unordered_map<std::string,\n        std::unique_ptr<alma::Crystal_structure>>;\n\n/// Probability density function for a Gamma distribution.\n///\n/// @param[in] k - shape parameter\n/// @param[in] theta - scale parameter\n/// @param[in] x - point at which to evaluate the function\n/// @return the value of the pdf\ninline double gamma_pdf(double k, double theta, double x) {\n    return boost::math::gamma_p_derivative(k, x / theta) / theta;\n}\n///To store geometric and input data:\n///Parameters of input file\nstruct input_parameters {\n    \n    ///Geometry\n    std::vector<alma::geometry_2d>\n        system;\n    ///Material data\n    cellData system_cell;\n    gridData system_grid;\n\n    ///Vector of thickness\n    std::vector<double>\n        thicknesses;\n    ///Where to print data\n    std::vector<std::size_t> boxesID;\n    std::vector<double>      dumptimes;    \n    ///nbins\n    std::size_t nbins;\n};\n\n///To read input file:\n///This reads the input file\n///@param[in] filename - input filename with path\n///@param[in] world    - mpi communicator\n///@return structure with input parameters\ninput_parameters \nprocess_input(std::string& filename,\n              boost::mpi::communicator& world\n){\n    // Create empty property tree object\n    boost::property_tree::ptree tree;\n\n    // Parse XML input file into the tree\n    boost::property_tree::read_xml(filename, tree);\n    \n    input_parameters inpars;\n    ///Map to store thickness\n    std::map<std::string,double> zmap;\n    \n    for (const auto& v : tree.get_child(\"beRTAMC2D\")) {\n        ///Reading geometry\n        if (v.first == \"geometry\") {\n            std::string gfname = \n                alma::parseXMLfield<std::string>(v, \"file\");\n            inpars.system = \n                alma::read_geometry_XML(gfname);\n        }\n        if (v.first == \"material\") {\n            std::string name = \n                alma::parseXMLfield<std::string>(v, \"name\");\n            std::string hdf5file = \n                alma::parseXMLfield<std::string>(v, \"database\");\n            double zsize = \n                alma::parseXMLfield<double>(v, \"thickness\");\n            auto data = \n                alma::load_bulk_hdf5(hdf5file.c_str(), world);\n            inpars.system_cell[name] = \n                std::move(std::get<1>(data));\n            inpars.system_grid[name] = \n                std::move(std::get<3>(data));\n            \n            zmap[name] = zsize;\n        }\n        \n        if (v.first == \"spectral\") {\n            for (auto it = v.second.begin(); it != v.second.end(); it++) {\n                if (it->first == \"resolution\") {\n                    inpars.nbins =\n                        alma::parseXMLfield<std::size_t>(*it, \"ticks\");\n                }\n                if (it->first == \"location\") {\n                    inpars.boxesID.push_back(\n                        alma::parseXMLfield<std::size_t>(*it, \"bin\"));\n                }\n                if (it->first == \"time\") {\n                    inpars.dumptimes.push_back(\n                        alma::parseXMLfield<double>(*it, \"t\"));\n                }\n            }\n        }\n        \n    }\n    \n    if (inpars.system_cell.size()>1){\n        std::cout << \"This is currently not supported\\n\";\n        world.abort(1);\n    }\n    \n    /// Fill thicknesses\n    for (std::size_t i=0;i<inpars.system.size();i++) {\n        auto mat = inpars.system[i].material;\n        inpars.thicknesses.push_back(\n            zmap[mat]);\n    }\n    \n    /// Order the times\n    std::sort(inpars.dumptimes.begin(),inpars.dumptimes.end());\n    \n    return inpars;\n}\n\n\n\n\nclass data {\npublic:\n    double time;\n    double Eeff;\n    std::vector<double> temperatures;\n    std::vector<Eigen::VectorXi> histograms;\n    std::vector<std::size_t> nbands;\n    std::vector<std::ofstream> outf;\n    std::vector<std::ofstream> outfvx;\n    std::vector<std::ofstream> outfvy;\n    std::vector<std::ofstream> outfd;\n    \n    data(input_parameters& inpars){\n        temperatures.resize(inpars.system.size());\n        histograms.resize(temperatures.size());\n        nbands.resize(temperatures.size(),0);\n        outf.resize(nbands.size());\n        outfvx.resize(nbands.size());\n        outfvy.resize(nbands.size());\n        outfd.resize(nbands.size());\n        \n        for (auto s : inpars.system) {\n            \n            auto id = s.get_id();\n            \n            if (std::find(inpars.boxesID.begin(),\n                inpars.boxesID.end(),id)==inpars.boxesID.end())\n                continue;\n            \n            outf[id].open(\"deltaT_omega_\"+std::to_string(id)+\".csv\");\n            outfvx[id].open(\"jx_omega_\"+std::to_string(id)+\".csv\");\n            outfvy[id].open(\"jy_omega_\"+std::to_string(id)+\".csv\");\n            outfd[id].open(\"fd_\"+std::to_string(id)+\".csv\");\n            \n            auto mat = inpars.system[id].material;\n            \n            auto nqpoints = inpars.system_grid[mat]->nqpoints;\n            \n            auto nbands_   = inpars.system_grid[mat\n                ]->get_spectrum_at_q(0).omega.size();\n            \n            histograms[id].resize(nbands_*nqpoints);\n            histograms[id].setZero();\n            nbands[id] = nbands_;\n        }\n    }\n    \n    ~data(){\n        for (auto& o : outf) {\n            if(o.is_open())\n                o.close();\n        }\n        for (auto& o : outfvx) {\n            if(o.is_open())\n                o.close();\n        }\n        for (auto& o : outfvy) {\n            if(o.is_open())\n                o.close();\n        }\n        for (auto& o : outfd) {\n            if(o.is_open())\n                o.close();\n        }\n        \n    }\n    \n  // this function is looks like de-serializer, taking an msgpack object\n  // and extracting data from it to the current class fields\n  void msgpack_unpack(msgpack::object o) {\n    \n    // check if received structure is an array\n    if(o.type != msgpack::type::ARRAY) { throw msgpack::type_error(); }\n    \n    o.via.array.ptr[0].convert(time);\n    o.via.array.ptr[1].convert(Eeff);\n    \n    std::cout << \"time \" << time << std::endl;\n    std::cout << \"Eeff \" << Eeff << std::endl;\n    \n    // extract value of second array entry which is array itself:\n    for (std::size_t i = 0; i < temperatures.size() ; i++) {\n      o.via.array.ptr[2].via.array.ptr[i].convert((temperatures[i]));\n    }\n    for (std::size_t i = 0; i < temperatures.size(); i++) {\n        if (nbands[i] == 0)\n            continue;\n        std::size_t nelements;\n        o.via.array.ptr[3+2*i].convert(nelements);\n        \n        std::cout << \"nelements \" << nelements << std::endl;\n        \n        histograms[i].setZero();\n        \n        for (std::size_t j = 0; j < nelements/2; j++) {\n            std::size_t imode;\n            o.via.array.ptr[4+2*i].via.array.ptr[2*j].convert(imode);\n            o.via.array.ptr[4+2*i].via.array.ptr[2*j+1].convert((histograms[i](imode)));\n        }\n    }\n    \n  }\n  \n  // destination of this function is unknown - i've never ran into scenary\n  // what it was called. some explaination/documentation needed.\n  template <typename MSGPACK_OBJECT>\n  void msgpack_object(MSGPACK_OBJECT* o, msgpack::zone* z) const { \n\n  }\n  \n  /// This prints the distribution\n  ///@param[in] inpar - input parameters \n  double print_distribution(input_parameters& inpars){\n      static std::map<std::string,Eigen::ArrayXXd> sigmas;  //Broadening\n      static std::map<std::string,Eigen::ArrayXXd> vx;\n      static std::map<std::string,Eigen::ArrayXXd> vy;\n      static std::map<std::string,Eigen::MatrixXd> qpoints1stBZ; //Q points in the first BZ\n      static std::map<std::string,double> Cvtot;      //specific heat of each material [J/(nm**3 * K)]\n      static std::map<std::string,Eigen::VectorXd> mesh;\n      static std::vector<bool> first(temperatures.size(),true);\n\n      /// If not in list ignore\n      if (std::find_if(inpars.dumptimes.begin(),inpars.dumptimes.end(),[&](double &t_){\n          return alma::almost_equal(time,t_);\t\t\n      })==inpars.dumptimes.end()){\n          return -1.0;\n      }\n      \n      /// Filling tables\n      \n      if (sigmas.empty()) {\n      \n        for (std::size_t ibox = 0; ibox < temperatures.size(); ibox++) {\n            if (nbands[ibox]==0) {\n                continue;\n            }\n            //std::cout << \"Printing \" << ibox << std::endl;\n            auto mat = inpars.system[ibox].material;\n            if (sigmas.count(mat) !=0)\n                    continue;\n            auto tbox = temperatures[ibox];\n            sigmas[mat].resize(nbands[ibox],inpars.system_grid[mat]->nqpoints);\n            vx[mat].resize(nbands[ibox],inpars.system_grid[mat]->nqpoints);\n            vy[mat].resize(nbands[ibox],inpars.system_grid[mat]->nqpoints);\n            qpoints1stBZ[mat].resize(inpars.system_grid[mat]->nqpoints,2);\n            sigmas[mat].setZero();\n            vx[mat].setZero();\n            vy[mat].setZero();\n            qpoints1stBZ[mat].setZero();\n            double maxf = 0.;\n            \n            double prefactor =\n                alma::constants::kB / (inpars.system_cell[mat]->V * inpars.thicknesses[ibox]\n                /inpars.system_cell[mat]->lattvec(2,2)) / inpars.system_grid[mat]->nqpoints;\n            \n            for (std::size_t iq = 0; iq < inpars.system_grid[mat]->nqpoints; ++iq) {\n                    auto spectrum = inpars.system_grid[mat]->get_spectrum_at_q(iq);\n                    \n                    auto q1BZ = inpars.system_cell[mat]->map_to_firstbz(\n                        inpars.system_grid[mat]->get_q(iq));\n                    \n                    qpoints1stBZ[mat](iq,0) = q1BZ.row(0).mean();\n                    qpoints1stBZ[mat](iq,1) = q1BZ.row(1).mean();\n                    \n                    \n                    auto maxomega_mode =\n                        spectrum.omega.maxCoeff();\n                    if (maxomega_mode > maxf)\n                        maxf = maxomega_mode;\n                    \n                    for (std::size_t im = 0; im < nbands[ibox]; ++im) {\n                        auto omega_ = spectrum.omega[im];\n                        \n                        if (alma::almost_equal(omega_,0.))\n                            continue;\n                        \n                        sigmas[mat](im, iq) = inpars.system_grid[\n                            mat]->base_sigma(spectrum.vg.col(im));\n                        ///Get group velocities in m/s\n                        vx[mat](im, iq) = 1.0e+3 * spectrum.vg(0,im);\n                        vy[mat](im, iq) = 1.0e+3 * spectrum.vg(1,im);\n                    }\n            }\n            // And refine them by removing outliers.\n            auto percent = alma::calc_percentiles_log(sigmas[mat]);\n            double lbound = std::exp(percent[0] - 1.5 * (percent[1] - percent[0]));\n            sigmas[mat] = (sigmas[mat] < lbound).select(lbound, sigmas[mat]);\n            \n            mesh[mat] = Eigen::VectorXd::LinSpaced(inpars.nbins,0.,maxf);\n            mesh[mat] = (mesh[mat].array() + mesh[mat](1)/2.0).matrix();\n            \n            /// Filling volumetric heat capacity\n            Cvtot[mat] = 0.;\n            \n            for (std::size_t iq = 0; iq < inpars.system_grid[mat]->nqpoints; ++iq) {\n                auto spectrum = inpars.system_grid[mat]->get_spectrum_at_q(iq);\n                for (std::size_t im = 0; im < nbands[ibox]; ++im) {\n                    auto omega_ = spectrum.omega[im];\n                    \n                    if (alma::almost_equal(0.,omega_))\n                        continue;\n                    \n                    Cvtot[mat] += alma::bose_einstein_kernel(omega_, tbox);\n                }\n            }\n            Cvtot[mat] *= prefactor;\n        }\n      }\n      \n      \n      \n      for (std::size_t ibox = 0; ibox < temperatures.size(); ibox++) {\n          \n          ///If not in print list ignore\n          if (std::find(inpars.boxesID.begin(),\n              inpars.boxesID.end(),ibox)==inpars.boxesID.end())\n              continue;\n          \n          auto mat = inpars.system[ibox].material;\n          if (inpars.system[ibox].reservoir\n              or inpars.system[ibox].reservoir)\n            continue;\n          \n          Eigen::VectorXd d(mesh[mat]), dvx(mesh[mat]), dvy(mesh[mat]);\n          Eigen::VectorXd dfd(inpars.system_grid[mat]->nqpoints); \n          \n          d.setZero();\n          dvx.setZero();\n          dvy.setZero();\n          dfd.setZero();\n          \n          auto vol  = inpars.system[ibox].get_area()*inpars.thicknesses[ibox];\n          double Ebox = 0.;\n          \n          for (std::size_t imode = 0; imode < static_cast<std::size_t>(\n                histograms[ibox].rows()); imode++){\n              auto value = histograms[ibox](imode);\n              if (value == 0) {\n                  continue;\n              }\n              auto ib = imode % nbands[ibox];\n              auto iq = imode / nbands[ibox];\n              auto omega = inpars.system_grid[mat]->get_spectrum_at_q(iq).omega(ib);\n              dfd(iq) += value/omega;\n              auto sigma = sigmas[mat](ib,iq);\n              Eigen::VectorXd v = inpars.system_grid[mat]->get_spectrum_at_q(iq).vg.col(ib).matrix();\n              Ebox  += value;\n              ///If gamma they do not contribute\n              if (alma::almost_equal(omega,0) or alma::almost_equal(sigma,0))\n                  continue;\n              for (int ii = 0; ii < d.rows(); ii++ ) {\n                  double k = omega * omega / sigma;\n                  double theta = sigma / omega;\n                  double valati = value*gamma_pdf(k,theta,mesh[mat](ii));\n                  d(ii)   += valati;\n                  dvx(ii) += valati * 1.0e+3 * v(0);\n                  dvy(ii) += valati * 1.0e+3 * v(1);\n              }\n          }\n          \n          ///Recover the distribution function\n          dfd   *=   Eeff*(inpars.system_cell[mat]->V * inpars.thicknesses[ibox]\n                 / inpars.system_cell[mat]->lattvec(2,2)) * \n                inpars.system_grid[mat]->nqpoints / (1.0e+12*vol*alma::constants::hbar);\n          dvx      *= Eeff * 1.0e+27/vol  ;\n          dvy      *= Eeff * 1.0e+27/vol  ;\n          d        *= Eeff/(vol*Cvtot[mat]);\n          Ebox     *= Eeff/vol;\n          \n          std::cout <<\"Energy density of box \" << ibox << \" is \" << Ebox << std::endl;\n          std::cout <<\"Specific heat \" << Cvtot[mat] * 1.0e+27 << \" J/(m**3 * K)\" << std::endl; \n          \n          auto &myo   = outf[ibox];\n          auto &myox  = outfvx[ibox];\n          auto &myoy  = outfvy[ibox];\n          auto &myofd = outfd[ibox];\n          \n          if (first[ibox]) {\n              myo << -1 << ',';\n              myox << -1 << ',';\n              myoy << -1 << ',';\n              for (int ii = 0; ii < d.rows(); ii++ ) {\n                  myo << mesh[mat](ii);\n                  myox << mesh[mat](ii);\n                  myoy << mesh[mat](ii);\n                  if (ii != d.rows()-1) {\n                    myo  << ',';\n                    myox << ',';  \n                    myoy << ',';  \n                  }\n              }\n              myo << std::endl;\n              myox << std::endl;\n              myoy << std::endl;\n              \n              ///Print coordinates\n              \n              myofd << \"# \";\n              for (int ii = 0; ii < dfd.rows();ii++) {\n                 myofd << qpoints1stBZ[mat](ii,0);\n                 if (ii != dfd.rows()-1) { \n\t\t    myofd << \",\";\n                 }\n              }\n              myofd << std::endl;\n              myofd << \"# \";\n              for (int ii = 0; ii < dfd.rows();ii++) {\n                  myofd << qpoints1stBZ[mat](ii,1);\n                  if (ii != dfd.rows()-1) {\n                    myofd << \",\";\n                 }\n              }\n              myofd << std::endl;\n              \n              \n              first[ibox] = false;\n          }\n          \n          myo  << time << ',';\n          myox << time << ',';\n          myoy << time << ',';\n          myofd << time << ',';\n          for (int ii = 0; ii < d.rows(); ii++ ) {\n            myo  << d(ii);\n            myox << dvx(ii);\n            myoy << dvy(ii);\n              \n            if (ii != d.rows()-1) {\n                myo  << ',';\n                myox << ',';  \n                myoy << ',';  \n            }\n          }\n          \n          for (int ii = 0; ii < dfd.rows();ii++) {\n            myofd << dfd(ii);\n            if (ii != dfd.rows()-1) {\n                myofd << ',';\n            }\n          } \n         \n          myo   << std::endl;\n          myox  << std::endl;\n          myoy  << std::endl;\n          myofd << std::endl;\n          \n      }\n    \n    return time;\n  }\n  \n    \n};\n\n\n\nint main(int argc, char** argv) {\n    boost::mpi::environment env;\n    boost::mpi::communicator world;\n    \n    if (world.size()!=1) {\n        std::cout << \"Error: dist_reader cannot be \" \n                     \"run in more than one MPI-process\"\n                    << std::endl;\n        world.abort(1);\n    }\n    \n    // Reference temperature at which to compute\n    // heat capacities and scattering rates.\n\n    // Path to the HDF5 file.\n    std::string h5filename;\n    std::string inputfilename;\n    std::string msgpackfilename;\n    std::string reader;\n\n    if (argc != 3) {\n        std::cout << \"USAGE: dist_reader <input.xml> <histogram.msgpack.bin> \"\n                  << std::endl;\n        world.abort(1);\n    }\n\n    inputfilename = std::string(argv[1]);\n    msgpackfilename = std::string(argv[2]);\n\n    std::cout << \"***********************************\" << std::endl;\n    std::cout << \"This is ALMA/dist_reader version \" << ALMA_VERSION_MAJOR << \".\"\n              << ALMA_VERSION_MINOR << std::endl;\n    std::cout << \"***********************************\" << std::endl;\n\n    ///Reading geometry and other things\n    std::cout << \"Reading \" << inputfilename << std::endl;\n    \n    auto inpars = process_input(inputfilename,world);\n    \n    ///Processing:\n    std::cout << \"Init data storing\" << std::endl;\n    data simdata(inpars);\n    \n    std::ifstream histdat;\n    \n    boost::filesystem::path msgpack_path{msgpackfilename};\n    \n    if (!(boost::filesystem::exists(msgpack_path))) {\n        std::cout << \"ERROR:\" << std::endl;\n        std::cout << \"msgpack file \" << msgpack_path << \" does not exist.\"\n                  << std::endl;\n        world.abort(1);\n    }\n    \n    histdat.open(msgpackfilename.c_str());\n    \n    std::string sizeline;\n    ///Each \n    std::size_t istep = 0;\n    while(true){\n        std::getline(histdat,sizeline,'#');\n        auto length_block = boost::lexical_cast<std::size_t>(sizeline);\n        if (length_block == 0)\n            break;\n        \n        std::vector<char> dataline(length_block);\n        histdat.read(dataline.data(),length_block);\n        std::cout << \"*Read line \" << istep << std::endl;\n        msgpack::object_handle oh =\n            msgpack::unpack(dataline.data(), dataline.size());\n        simdata.msgpack_unpack(oh.get());\n        double that_time = simdata.print_distribution(inpars);\n        \n        /// Stop if last time has been read\n        if (alma::almost_equal(that_time,inpars.dumptimes.back())){\n            break;\n        }\n        \n        istep++;\n    }\n    \n    histdat.close();\n    \n    \n    return 0;\n}\n", "meta": {"hexsha": "b6ff4e9310939b10fbf2def8286cc66ad5979352", "size": 20489, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dist_reader.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/dist_reader.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/dist_reader.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": 34.0915141431, "max_line_length": 102, "alphanum_fraction": 0.4993899165, "num_tokens": 5140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2788922858849364}}
{"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 <orea/engine/parametricvar.hpp>\n\n#include <orea/engine/riskfilter.hpp>\n#include <orea/scenario/shiftscenariogenerator.hpp>\n#include <ored/utilities/csvfilereader.hpp>\n#include <ored/utilities/log.hpp>\n#include <ored/utilities/parsers.hpp>\n\n#include <qle/math/deltagammavar.hpp>\n\n#include <ql/math/matrixutilities/pseudosqrt.hpp>\n#include <ql/math/matrixutilities/symmetricschurdecomposition.hpp>\n\n#include <boost/regex.hpp>\n\nusing namespace QuantLib;\n\nnamespace ore {\nnamespace analytics {\n\nParametricVarCalculator::ParametricVarCalculator(\n    const std::map<std::string, std::set<string>>& tradePortfolios, const std::string& portfolioFilter,\n    const boost::shared_ptr<SensitivityStream>& sensitivities,\n    const std::map<std::pair<RiskFactorKey, RiskFactorKey>, Real> covariance, const std::vector<Real>& p,\n    const std::string& method, const Size mcSamples, const Size mcSeed, const bool breakdown,\n    const bool salvageCovarianceMatrix)\n    : tradePortfolios_(tradePortfolios), portfolioFilter_(portfolioFilter), sensitivities_(sensitivities),\n      covariance_(covariance), p_(p), method_(method), mcSamples_(mcSamples), mcSeed_(mcSeed), breakdown_(breakdown),\n      salvageCovarianceMatrix_(salvageCovarianceMatrix) {}\n\nvoid ParametricVarCalculator::calculate(ore::data::Report& report) {\n    LOG(\"Parametric VaR calculation started...\");\n\n    // prepare report\n    report.addColumn(\"Portfolio\", string()).addColumn(\"RiskClass\", string()).addColumn(\"RiskType\", string());\n    for (Size i = 0; i < p_.size(); ++i)\n        report.addColumn(\"Quantile_\" + std::to_string(p_[i]), double(), 6);\n\n    // build portfolio filter, if given\n    bool hasFilter = false;\n    boost::regex filter;\n    if (portfolioFilter_ != \"\") {\n        hasFilter = true;\n        filter = boost::regex(portfolioFilter_);\n        LOG(\"Portfolio filter: \" << portfolioFilter_);\n    } else {\n        LOG(\"No portfolio filter will be applied.\");\n    }\n\n    // read sensitivities and preaggregate them per prtfolio\n    LOG(\"Preaggregate sensitivities per portfolio\");\n    std::set<RiskFactorKey> sensiKeysTmp;\n    std::set<std::string> portfoliosTmp;\n    std::map<std::string, std::map<std::pair<RiskFactorKey, RiskFactorKey>, Real>> value1, value2;\n    std::map<std::pair<RiskFactorKey, RiskFactorKey>, Real> value1All, value2All;\n    while (SensitivityRecord sr = sensitivities_->next()) {\n        std::set<std::string> portfolios;\n        auto pn = tradePortfolios_.find(sr.tradeId);\n        if (pn != tradePortfolios_.end()) {\n            if (pn->second.empty())\n                portfolios = {\"(empty)\"};\n            else\n                portfolios = pn->second;\n        } else\n            portfolios = {\"(unknown)\"};\n        RiskFactorKey k1 = sr.key_1;\n        RiskFactorKey k2 = sr.key_2;\n        auto key = std::make_pair(k1, k2);\n        if (k1 != RiskFactorKey())\n            sensiKeysTmp.insert(k1);\n        if (k2 != RiskFactorKey())\n            sensiKeysTmp.insert(k2);\n        bool relevant = false;\n        for (auto const& p : portfolios) {\n            if (!hasFilter || boost::regex_match(p, filter)) {\n                relevant = true;\n                portfoliosTmp.insert(p);\n                if (sr.isCrossGamma()) {\n                    value1[p][key] += sr.gamma;\n                } else {\n                    value1[p][key] += sr.delta;\n                }\n                if (!sr.isCrossGamma()) {\n                    value2[p][key] += sr.gamma;\n                }\n            }\n        }\n        if (relevant) {\n            if (sr.isCrossGamma()) {\n                value1All[key] += sr.gamma;\n            } else {\n                value1All[key] += sr.delta;\n            }\n            if (!sr.isCrossGamma()) {\n                value2All[key] += sr.gamma;\n            }\n        }\n    }\n    std::vector<RiskFactorKey> sensiKeys(sensiKeysTmp.begin(), sensiKeysTmp.end());\n    std::vector<bool> sensiKeyHasNonZeroVariance(sensiKeys.size(), false);\n    std::vector<std::string> portfolios(portfoliosTmp.begin(), portfoliosTmp.end());\n    LOG(\"Have \" << sensiKeys.size() << \" sensitivity keys in \" << portfolios.size() << \" portfolios\");\n\n    // build global covariance matrix\n    Matrix omega(sensiKeys.size(), sensiKeys.size(), 0.0);\n    Size unusedCovariance = 0;\n    for (const auto& c : covariance_) {\n        auto k1 = std::find(sensiKeys.begin(), sensiKeys.end(), c.first.first);\n        auto k2 = std::find(sensiKeys.begin(), sensiKeys.end(), c.first.second);\n        if (k1 != sensiKeys.end() && k2 != sensiKeys.end()) {\n            omega(k1 - sensiKeys.begin(), k2 - sensiKeys.begin()) = c.second;\n            if (k1 == k2)\n                sensiKeyHasNonZeroVariance[k1 - sensiKeys.begin()] = true;\n        } else {\n            ++unusedCovariance;\n        }\n    }\n    LOG(\"Found \" << covariance_.size() << \" covariance matrix entries, \" << unusedCovariance\n                 << \" do not match a portfolio sensitivity and will not be used.\");\n    for (Size i = 0; i < sensiKeyHasNonZeroVariance.size(); ++i) {\n        if (!sensiKeyHasNonZeroVariance[i]) {\n            WLOG(\"Zero variance assigned to sensitivity key \" << sensiKeys[i]);\n        }\n    }\n\n    // make covariance matrix positive semi-definite\n    boost::shared_ptr<QuantExt::CovarianceSalvage> covarianceSalvage;\n    LOG(\"Covariance matrix has dimension \" << sensiKeys.size() << \" x \" << sensiKeys.size());\n    if (salvageCovarianceMatrix_) {\n        LOG(\"Make covariance matrix positive semi-definite using spectral method\");\n        covarianceSalvage = boost::make_shared<QuantExt::SpectralCovarianceSalvage>();\n    } else {\n        LOG(\"Covariance matrix is no salvaged, check for positive semi-definiteness\");\n        SymmetricSchurDecomposition ssd(omega);\n        Real evMin = ssd.eigenvalues().back();\n        QL_REQUIRE(evMin > 0.0 || close_enough(evMin, 0.0),\n                   \"ParametricVar: input covariance matrix is not positive semi-definite, smallest eigenvalue is \"\n                       << evMin);\n        LOG(\"Smallest eigenvalue is \" << evMin);\n        covarianceSalvage = boost::make_shared<QuantExt::NoCovarianceSalvage>();\n    }\n    LOG(\"Done.\");\n\n    // loop over portfolios (index 0 = all portfolios)\n    for (Size i = 0; i <= (!breakdown_ || portfolios.size() == 1 ? 0 : portfolios.size()); ++i) {\n        std::string portfolioName = i == 0 ? (portfolios.size() > 1 ? \"(all)\" : portfolios.front()) : portfolios[i - 1];\n        // build delta and gamma for given portfolio\n        const auto& val1 = (i == 0 ? value1All : value1[portfolios[i - 1]]);\n        const auto& val2 = (i == 0 ? value2All : value2[portfolios[i - 1]]);\n        Array delta(sensiKeys.size(), 0.0);\n        Matrix gamma(sensiKeys.size(), sensiKeys.size(), 0.0);\n        for (auto const& p : val1) {\n            auto k1 = p.first.first;\n            auto k2 = p.first.second;\n            Size idx1 = std::find(sensiKeys.begin(), sensiKeys.end(), k1) - sensiKeys.begin();\n            QL_REQUIRE(idx1 < sensiKeys.size(), \"ParametricVarCalculator::computeVar: key1 \\\"\"\n                                                    << k1 << \"\\\" in value1 not found, this is unexpected.\");\n            if (k2 == RiskFactorKey()) {\n                // delta\n                delta[idx1] += p.second;\n            } else {\n                // cross gamma\n                Size idx2 = std::find(sensiKeys.begin(), sensiKeys.end(), k2) - sensiKeys.begin();\n                QL_REQUIRE(idx2 < sensiKeys.size(), \"ParametricVarCalculator::computeVar: key2 \\\"\"\n                                                        << k2 << \"\\\" in value1 not found, this is unexpected.\");\n                gamma[idx1][idx2] = gamma[idx2][idx1] = p.second;\n            }\n        }\n        for (auto const& p : val2) {\n            // diagonal gamma\n            auto k1 = p.first.first;\n            Size idx1 = std::find(sensiKeys.begin(), sensiKeys.end(), k1) - sensiKeys.begin();\n            QL_REQUIRE(idx1 < sensiKeys.size(), \"ParametricVarCalculator::computeVar: key1 \\\"\"\n                                                    << k1 << \"\\\" in value2 not found, this is unexpected.\");\n            gamma[idx1][idx1] = p.second;\n        }\n        // loop over risk class and type filters (index 0 == all risk types)\n        for (Size j = 0; j < (breakdown_ ? RiskFilter::numberOfRiskClasses() : 1); ++j) {\n            for (Size k = 0; k < (breakdown_ ? RiskFilter::numberOfRiskTypes() : 1); ++k) {\n                // TODO should we rather project on the set of indices with non-zero sensis\n                // instead of copying the initial sensis and setting the non-releveant entries\n                // to zero?\n                Array deltaFiltered(delta);\n                Matrix gammaFiltered(gamma);\n                RiskFilter rf(j, k);\n                LOG(\"Compute parametric var for portfolio \\\"\" << portfolioName << \"\\\"\"\n                                                              << \", risk class \" << rf.riskClassLabel()\n                                                              << \", risk type \" << rf.riskTypeLabel());\n                // set sensis which do not belong to risk type filter to zero\n                for (Size idx = 0; idx < sensiKeys.size(); ++idx) {\n                    if (!rf.allowed(sensiKeys[idx].keytype)) {\n                        deltaFiltered[idx] = 0.0;\n                        for (Size ii = 0; ii < sensiKeys.size(); ++ii) {\n                            gammaFiltered[idx][ii] = gammaFiltered[ii][idx] = 0.0;\n                        }\n                    }\n                }\n                // are all sensis zero, then skip the computation\n                bool zeroSensis = close_enough(QuantExt::detail::absMax(deltaFiltered), 0.0) &&\n                                  close_enough(QuantExt::detail::absMax(gammaFiltered), 0.0);\n                // compute var and write to report\n                std::vector<Real> var = zeroSensis\n                                            ? std::vector<Real>(p_.size(), 0.0)\n                                            : computeVar(omega, deltaFiltered, gammaFiltered, p_, *covarianceSalvage);\n                if (!close_enough(QuantExt::detail::absMax(var), 0.0)) {\n                    report.next();\n                    report.add(portfolioName);\n                    report.add(rf.riskClassLabel());\n                    report.add(rf.riskTypeLabel());\n                    for (auto const& v : var)\n                        report.add(v);\n                }\n            } // for k (risk types)\n        }     // for j (risk classes)\n    }         // for i (portfolios)\n    LOG(\"parametric var computation done.\");\n    report.end();\n\n} // calculate\n\nstd::vector<Real> ParametricVarCalculator::computeVar(const Matrix& omega, const Array& delta, const Matrix& gamma,\n                                                      const std::vector<Real>& p,\n                                                      const QuantExt::CovarianceSalvage& covarianceSalvage) {\n    if (method_ == \"Delta\") {\n        std::vector<Real> res(p.size());\n        for (Size i = 0; i < p.size(); ++i) {\n            res[i] = QuantExt::deltaVar(omega, delta, p[i], covarianceSalvage);\n        }\n        return res;\n    } else if (method_ == \"DeltaGammaNormal\") {\n        std::vector<Real> res(p.size());\n        for (Size i = 0; i < p.size(); ++i) {\n            res[i] = QuantExt::deltaGammaVarNormal(omega, delta, gamma, p[i], covarianceSalvage);\n        }\n        return res;\n    } else if (method_ == \"MonteCarlo\") {\n        QL_REQUIRE(mcSamples_ != Null<Size>(),\n                   \"ParametricVarCalculator::computeVar(): method MonteCarlo requires mcSamples\");\n        QL_REQUIRE(mcSeed_ != Null<Size>(),\n                   \"ParametricVarCalculator::computeVar(): method MonteCarlo requires mcSamples\");\n        return QuantExt::deltaGammaVarMc<PseudoRandom>(omega, delta, gamma, p, mcSamples_, mcSeed_, covarianceSalvage);\n    } else {\n        QL_FAIL(\"ParametricVarCalculator::computeVar(): method \" << method_ << \" not known.\");\n    }\n}\n\nvoid loadCovarianceDataFromCsv(std::map<std::pair<RiskFactorKey, RiskFactorKey>, Real>& data,\n                               const std::string& fileName, const char delim) {\n    LOG(\"Load Covariance Data from file \" << fileName);\n    ore::data::CSVFileReader reader(fileName, false);\n    std::vector<std::string> dummy;\n    while (reader.next()) {\n        data[std::make_pair(*parseRiskFactorKey(reader.get(0), dummy), *parseRiskFactorKey(reader.get(1), dummy))] =\n            ore::data::parseReal(reader.get(2));\n    }\n    LOG(\"Read \" << data.size() << \" valid data lines from file \" << fileName);\n}\n\n} // namespace analytics\n} // namespace ore\n", "meta": {"hexsha": "44b61004cd4ab62be10e312849d651600bc7b207", "size": 13405, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OREAnalytics/orea/engine/parametricvar.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/engine/parametricvar.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/engine/parametricvar.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.0465949821, "max_line_length": 120, "alphanum_fraction": 0.5766505035, "num_tokens": 3198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6654105454764746, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.27860533884368155}}
{"text": "#define _CRT_SECURE_NO_WARNINGS\n\n#if defined(_WIN32) | defined(__WIN32__) | defined(__WIN32) | defined(_WIN64) | defined(__WIN64)\n//#include <windows.h>\n//#include \"win_network_fcns.h\"\n#endif\n\n//#include <winsock2.h>\n//#include <iphlpapi.h>\n//\n//#pragma comment(lib, \"IPHLPAPI.lib\")    // Link with Iphlpapi.lib\n\n// C/C++ includes\n#include <cmath>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <chrono>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <type_traits>\n\n// dlib includes\n#include \"dlib/rand.h\"\n#include \"dlib/matrix.h\"\n#include \"dlib/pixel.h\"\n#include \"dlib/image_io.h\"\n//#include \"dlib/external/libpng/png.h\"\n//#include \"dlib/external/libjpeg/jpeglib.h\"\n//#include \"dlib/external/zlib/zlib.h\"\n#include \"dlib/image_transforms.h\"\n#include <dlib/opencv.h>\n\n// #include \"dlib/xml_parser.h\"\n// #include \"dlib/string.h\"\n\n// OpenCV includes\n#include <opencv2/core/core.hpp>           \n#include <opencv2/highgui/highgui.hpp>     \n#include <opencv2/imgproc/imgproc.hpp> \n#include <opencv2/video/video.hpp>\n\n// custom includes\n//#include \"mmaplib.h\"\n#include \"pg.h\"\n//#include \"mmap.h\"\n#include \"get_current_time.h\"\n#include \"get_platform.h\"\n#include \"num2string.h\"\n#include \"file_parser.h\"\n#include \"read_binary_image.h\" \n#include \"make_dir.h\"\n#include \"ssim.h\"\n#include \"dlib_matrix_threshold.h\"\n#include \"gorgon_capture.h\"\n#include \"modulo.h\"\n\n//#include \"pso.h\"\n//#include \"ycrcb_pixel.h\"\n//#include \"dfd_array_cropper.h\"\n#include \"rot_90.h\"\n//#include \"dlib_srelu.h\"\n//#include \"dlib_elu.h\"\n#include \"center_cropper.h\"\n#include \"dfd_cropper_rw.h\"\n#include \"copy_dlib_net.h\"\n#include \"dlib_set_learning_rates.h\"\n\n// Network includes\n#include \"dfd_net_v14.h\"\n//#include \"dfd_net_v14_pso_01.h\"\n//#include \"dfd_net_rw_v19.h\"\n//#include \"load_dfd_rw_data.h\"\n//#include \"load_dfd_data.h\"\n\n//#include \"cyclic_analysis.h\"\n\nusing namespace std;\n\n// -------------------------------GLOBALS--------------------------------------\n\nextern const uint32_t img_depth;\nextern const uint32_t array_depth = 3;\nextern const uint32_t secondary;\n\n//extern const std::vector<std::pair<uint64_t, uint64_t>> crop_sizes;\nstd::string platform;\nstd::vector<std::array<dlib::matrix<uint16_t>, img_depth>> tr, te, trn_crop, te_crop;\n//std::vector<dlib::matrix<uint16_t>> gt_train, gt_test, gt_crop, gt_te_crop;\n\n//std::string version;\nstd::string net_name = \"dfd_net_\";\nstd::string net_sync_name = \"dfd_sync_\";\nstd::string logfileName = \"dfd_net_\";\nstd::string gorgon_savefile = \"gorgon_dfd_\";\n\ndlib::rand rnd(time(NULL));\n\nusing mnist_net_type = dlib::loss_multiclass_log<\n    dlib::fc<10,\n    dlib::prelu<dlib::fc<84,\n    dlib::prelu<dlib::fc<120,\n    dlib::max_pool<2, 2, 2, 2, dlib::prelu<dlib::con<16, 5, 5, 1, 1,\n    dlib::max_pool<2, 2, 2, 2, dlib::prelu<dlib::con<6, 5, 5, 1, 1,\n    dlib::input<dlib::matrix<unsigned char>>\n    >>>>>>>>>>>>;\n\n//using mnist_net_type = dlib::loss_multiclass_log<\n//    dlib::fc<10,\n//    dlib::htan<dlib::fc<84,\n//    dlib::sig<dlib::con<120, 5, 5, 1, 1,\n//    dlib::sig<dlib::max_pool<2, 2, 2, 2, dlib::con<16, 5, 5, 1, 1,\n//    dlib::sig<dlib::max_pool<2, 2, 2, 2, dlib::con<6, 5, 5, 1, 1,\n//    dlib::input<dlib::matrix<unsigned char>>\n//    >>>>>>>>>>>>;\n\n\nusing test_net_type = dlib::loss_multiclass_log_per_pixel <\n    cbp3_blk<256, \n    dlib::affine<\n    dlib::input<std::array<dlib::matrix<uint16_t>, img_depth>>\n    >>>;\n\n//----------------------------------------------------------------------------------\n\ntemplate <typename net_type>\ndlib::matrix<double, 1, 3> eval_mnist_performance(net_type &net, std::vector<dlib::matrix<unsigned char>> input_images, std::vector<unsigned long> input_labels)\n{\n    std::vector<unsigned long> predicted_labels = net(input_images);\n    int num_right = 0;\n    int num_wrong = 0;\n    // And then let's see if it classified them correctly.\n    for (size_t i = 0; i < input_images.size(); ++i)\n    {\n        if (predicted_labels[i] == input_labels[i])\n            ++num_right;\n        else\n            ++num_wrong;\n\n    }\n    // std::cout << \"training num_right: \" << num_right << std::endl;\n    // std::cout << \"training num_wrong: \" << num_wrong << std::endl;\n    // std::cout << \"training accuracy:  \" << num_right/(double)(num_right+num_wrong) << std::endl;\n\n    dlib::matrix<double, 1, 3> results;\n    results = (double)num_right, (double)num_wrong, (double)num_right / (double)(num_right + num_wrong);\n\n    return results;\n\n}   // end of eval_net_performance\n\n\n\n// ----------------------------------------------------------------------------------------\n/*\n\ntemplate <typename T>\nconst dlib::matrix<T> or(\n    const dlib::matrix<T>& m1,\n    const dlib::matrix<T>& m2\n    )\n{\n\n    dlib::matrix<T> result = dlib::zeros_matrix<T>(m1.nr(), m1.nc());\n    for (uint64_t r = 0; r < m1.nr(); ++r)\n    {\n        for (uint64_t c = 0; c < m1.nc(); ++c)\n        {\n            result(r, c) = (m1(r, c) > 0) | (m2(r, c) > 0);\n        }\n    }\n        return result;\n}\n\n\n// ----------------------------------------------------------------------------------------\ntemplate <typename T>\nconst dlib::matrix<T> and(\n    const dlib::matrix<T>& m1,\n    const dlib::matrix<T>& m2\n    )\n{\n\n    dlib::matrix<T> result = dlib::zeros_matrix<T>(m1.nr(), m1.nc());\n    for (uint64_t r = 0; r < m1.nr(); ++r)\n    {\n        for (uint64_t c = 0; c < m1.nc(); ++c)\n        {\n            result(r, c) = (m1(r, c) > 0) & (m2(r, c) > 0);\n        }\n    }\n    return result;\n}\n*/\n\n// ----------------------------------------------------------------------------------------\n\ntemplate <typename img_type1>\nvoid check_matrix(img_type1 img)\n{\n    if (dlib::is_matrix<img_type1>::value == true)\n        std::cout << \"matrix\" << std::endl;\n}\n\n// ----------------------------------------------------------------------------------------\n/*\ntemplate <typename array_type>\nvoid calc_linkdist(array_type in, dlib::matrix<uint16_t> &d)\n{\n    uint64_t idx, jdx;\n\n    // assume that the vectors are in the rows\n    // i.e. each row in the matrix represents a particular input\n\n    dlib::matrix<uint16_t> one = dlib::ones_matrix<uint16_t>(in.nr(), in.nr());\n    dlib::matrix<uint16_t> links = dlib::zeros_matrix<uint16_t>(in.nr(), in.nr());\n    dlib::matrix<uint16_t> found = dlib::identity_matrix<uint16_t>(in.nr());\n    dlib::matrix<uint16_t> next = dlib::zeros_matrix<uint16_t>(in.nr(), in.nr());\n    dlib::matrix<uint16_t> newfound = dlib::zeros_matrix<uint16_t>(in.nr(), in.nr());\n\n    d.set_size(in.nr(), in.nr());\n    dlib::set_all_elements(d, in.nr());\n\n    d = d - in.nr()*found;\n\n    double s = 0.0;\n\n    // get the links\n    for (idx = 0; idx < in.nr(); ++idx)\n    {\n        for (jdx = 0; jdx < in.nr(); ++jdx)\n        {\n            if (idx != jdx)\n            {\n                s = std::sqrt((double)(dlib::sum(dlib::squared(dlib::rowm(in, idx) - dlib::rowm(in, jdx)))));\n\n                //sum(idx, jdx) = s;\n\n                if (s <= 1)\n                    links(idx, jdx) = 1;\n            }\n        }\n    }\n\n\n    // cycle through the inputs by row\n    for (idx = 0; idx < in.nr(); ++idx)\n    {\n        //nextfound = (found*links) | found;\n        next = dlib::matrix_cast<uint16_t>((found*links));\n        next = or(next, found);\n\n        //newfound = nextfound & ~found;\n        newfound = (one - found);\n        newfound = and(next, newfound);\n\n        for (uint64_t r = 0; r < in.nr(); ++r)\n        {\n            for (uint64_t c = 0; c < in.nr(); ++c)\n            {\n                if (newfound(r, c) == 1)\n                    d(r, c) = idx + 1;\n            }\n        }\n\n        found = next;\n\n\n    }\n\n}\n\n*/\n\n\n// ----------------------------------------------------------------------------------------\n\n\n//template<size_t from, size_t to, typename net_type1, typename net_type2>\n////typename std::enable_if<from >= to>::type\n//void copy_net(net_type1 &in, net_type2 &out)\n//{\n//    dlib::layer<to>(out).layer_details() = dlib::layer<from>(in).layer_details();\n//    //copy_net<from + 1, to>(in, out);\n//}\n\ntemplate<size_t from, size_t to, typename net_type1, typename net_type2>\nvoid copy_layer(net_type1 &from_net, net_type2 &to_net)\n{\n    dlib::layer<to>(to_net).layer_details() = dlib::layer<from>(from_net).layer_details();\n}\n\n/*\nnamespace dlib\n{\n\n    namespace cpnet\n    {\n        template <size_t begin, size_t end, size_t begin2>\n        struct copy_layer_loop\n        {\n            // this version of the recursion templte checks to see if the layer is part of the \"add_layer\" class\n            // layers like tag layers are not\n            template <typename F, typename T>\n            static typename std::enable_if<!is_add_layer<F>::value>::type invoke_functor(F&& from, T&& to)\n            {\n                // intentionally left empty\n                std::cout << \"skipping: layer<\" << begin << \">\" << std::endl;\n            }\n\n            // this version will operate on all layers in the \"add_layer\" class\n            // the layer details will be copied from one layer to another\n            template <typename F, typename T>\n            static typename std::enable_if<is_add_layer<F>::value>::type invoke_functor(F&& from, T&& to)\n            {\n                std::cout << \"copying: layer<\" << begin << \">\" << std::endl;\n                to.layer_details() = from.layer_details();\n            }\n\n            // this is the recursive call\n            template <typename net_type1, typename net_type2>\n            static void visit(\n                net_type1& from_net,\n                net_type2& to_net\n            )\n            {\n                invoke_functor(layer<begin>(from_net), layer<begin2>(to_net));\n\n                copy_layer_loop<begin + 1, end, begin2 + 1>::visit(from_net, to_net);\n            }\n        };\n\n        template <size_t end, size_t begin2>\n        struct copy_layer_loop<end, end, begin2>\n        {\n\n            template <typename F, typename T>\n            static typename std::enable_if<!is_add_layer<F>::value>::type invoke_functor(F&& from, T&& to)\n            {\n                // intentionally left empty\n                std::cout << \"skipping: layer<\" << end << \">\" << std::endl;\n            }\n\n            template <typename F, typename T>\n            static typename std::enable_if<is_add_layer<F>::value>::type invoke_functor(F&& from, T&& to)\n            {\n                std::cout << \"copying: layer<\" << end << \">\" << std::endl;\n                to.layer_details() = from.layer_details();\n            }\n\n            // Base case of recursion, i.e. the last iteration\n            template <typename net_type1, typename net_type2>\n            static void visit(\n                net_type1& from_net,\n                net_type2& to_net\n            )\n            {\n                invoke_functor(layer<end>(from_net), layer<begin2>(to_net));\n                std::cout << \"copying complete!\" << std::endl;\n            }\n        };\n\n    }   // end of cpnet namespace\n\n\n    // this most likely will be the copy net function in the end\n    template <size_t b1, size_t e1, size_t b2, typename net_type1, typename net_type2>\n    void copy_net(net_type1 &from_net, net_type2 &to_net)\n    {\n        // this does a check of the input ranges to determine if they are out of range for the input network\n        static_assert(b1 <= e1, \"Invalid range\");\n        static_assert(e1 <= net_type1::num_layers, \"Invalid range\");\n\n        // begin the layer copying process\n        cpnet::copy_layer_loop<b1, e1, b2>::visit(from_net, to_net);\n    }\n\n}   // end of dlib namespace\n\n*/\n\n//// ----------------------------------------------------------------------------------------\n//\n//namespace dlib\n//{\n//    namespace impl\n//    {\n//        // This is for the cases where begin != end\n//        template <size_t begin, size_t end>\n//        struct vllr_loop\n//        {\n//            // This is where the work gets done.  The odd decltype is used to check if layer contains\n//            // the set_learning_rate_multiplier() fucntion\n//            template<typename net_type>\n//            static decltype(std::declval<net_type>().layer_details().set_learning_rate_multiplier(0))\n//            set_value(net_type &net, double r1, double r2)\n//            {\n//                net.layer_details().set_learning_rate_multiplier(r1);\n//                net.layer_details().set_bias_learning_rate_multiplier(r2);\n//            }\n//\n//            static void set_value(...)\n//            {\n//                // Intentionally left blank.  This handles the layers that don't have a \n//                // set_learning_rate_multiplier() function\n//            }\n//\n//            // This is the fuction to call within the struct \n//            template <typename net_type>\n//            static void visit(net_type &net, double r1, double r2)\n//            {\n//                // set the values for the current layer\n//                set_value(layer<begin>(net), r1, r2);\n//                // move on and increment the begining layer\n//                vllr_loop<begin + 1, end>::visit(net, r1, r2);\n//            }\n//        };\n//\n//        // This is for the cases where begin == end, i.e. the base case for the recursion\n//        template <size_t end>\n//        struct vllr_loop<end,end> \n//        {   \n//\n//            // This is where the work gets done.  The odd decltype is used to check if layer contains\n//            // the set_learning_rate_multiplier() fucntion\n//            template<typename net_type>\n//            static decltype(std::declval<net_type>().layer_details().set_learning_rate_multiplier(0))\n//            set_value(net_type &net, double r1, double r2)\n//            {\n//                net.layer_details().set_learning_rate_multiplier(r1);\n//                net.layer_details().set_bias_learning_rate_multiplier(r2);\n//            }\n//\n//            static void set_value(...)\n//            {\n//                // Intentionally left blank.  This handles the layers that don't have a \n//                // set_learning_rate_multiplier() function\n//            }\n//\n//            // This is the fuction to call within the struct \n//            template <typename net_type>\n//            static void visit(net_type &net, double r1, double r2)\n//            {\n//                // set the values for the current layer\n//                set_value(layer<end>(net), r1, r2);\n//            }\n//        };\n//\n//    }   // end of impl namespace\n//\n//    // This is the main function to call when you want to set the following:\n//    //   - set_learning_rate_multiplier\n//    //   - set_bias_learning_rate_multiplier\n//    // Call it like this: dlib::set_learning_rate<0, 3>(net, r1, r2);\n//    //   - where net is your net and r1,r2 are the learning rate multipliers\n//    template<size_t begin, size_t end, typename net_type>\n//    void set_learning_rate(net_type &net, double r1, double r2)\n//    {\n//        // this does a check of the input ranges to determine if they are out of range for the input network\n//        static_assert(begin <= end, \"Invalid range\");\n//        static_assert(end <= net_type::num_layers, \"Invalid range\");\n//\n//        // begin the process of updating the learning rates\n//        impl::vllr_loop<begin, end>::visit(net, r1, r2);\n//    }\n//\n//}   // end of dlib namespace\n//\n//// ----------------------------------------------------------------------------------------\n\n\n//template<typename net_type>\n//inline decltype(std::declval<net_type>().layer_details().set_learning_rate_multiplier(0))\n//set_learning_rate_impl(net_type &net, double rate)\n//{\n//    net.layer_details().set_learning_rate_multiplier(rate);\n//    net.layer_details().set_bias_learning_rate_multiplier(rate);\n//}\n//\n//inline void set_learning_rate_impl(...)\n//{\n//}\n//\n//template<int from, int to, typename net_type>\n//typename std::enable_if<from == to>::type\n//set_learning_rate(net_type& net, double rate)\n//{\n//    set_learning_rate_impl(dlib::layer<from>(net), rate);\n//}\n//\n//template<int from, int to, typename net_type>\n//typename std::enable_if<from != to>::type\n//set_learning_rate(net_type &net, double rate)\n//{\n//    set_learning_rate_impl(dlib::layer<from>(net), rate);\n//    set_learning_rate<from + 1, to>(net, rate);\n//}\n\n\n\n\n\n// ----------------------------------------------------------------------------------------\n\ntemplate <typename image_type1>\nvoid make_random_cropping_rect(const image_type1& img, dlib::rectangle &rect_im, dlib::chip_dims dims= dlib::chip_dims(32,32))\n{\n    uint64_t x = 0, y = 0;\n\n    rect_im = dlib::resize_rect(rect_im, dims.cols, dims.rows);\n//    rect_gt = dlib::resize_rect(rect_gt, (long)(dims.cols / (double)scale_x), (long)(dims.rows / (double)scale_y));\n\n    if ((unsigned long)img.nc() <= rect_im.width())\n        x = 0;\n    else\n        x = (uint64_t)(rnd.get_integer(img.nc() - rect_im.width()));\n\n    if ((unsigned long)img.nr() <= rect_im.height())\n        y = 0;\n    else\n        y = (uint64_t)(rnd.get_integer(img.nr() - rect_im.height()));\n\n    // randomly shift the box around\n    dlib::point tr_off(x, y);\n    rect_im = dlib::move_rect(rect_im, tr_off);\n\n    //dlib::point gt_off(x, y);\n    //rect_gt = dlib::move_rect(rect_gt, gt_off);\n\n\n}\t// end of make_random_cropping_rect \n\n// ----------------------------------------------------------------------------------------\n\ntemplate <typename img_type, typename T>\nvoid create_mask(img_type src, img_type &mask, T min_value, T max_value)\n{\n    uint64_t nr = src.nr();\n    uint64_t nc = src.nc();\n\n    mask.set_size(nr, nc);\n\n    for (uint64_t r = 0; r < nr; ++r)\n    {\n        for (uint64_t c = 0; c < nc; ++c)\n        {\n            if ((src(r, c) >= min_value) && (src(r,c) <= max_value))\n                mask(r, c) = 1;\n            else\n                mask(r, c) = 0;\n        }\n    }\n\n}   // end of create_mask\n\n// ----------------------------------------------------------------------------------------\n\ntemplate <typename img_type, typename mask_type, typename T>\nvoid apply_mask(img_type src, img_type &dst, mask_type mask, T value)\n{\n    uint64_t nr, nc;\n\n    //if (dlib::is_matrix<img_type>::value == true)\n    //{\n    //    nr = src.nr();\n    //    nc = src.nc();\n\n    //    dst.set_size(nr, nc);\n\n    //    for (uint64_t r = 0; r < nr; ++r)\n    //    {\n    //        for (uint64_t c = 0; c < nc; ++c)\n    //        {\n    //            if (mask(r, c) == 0)\n    //                dst(r, c) = value;\n    //            else\n    //                dst(r, c) = src(r, c);\n    //        }\n    //    }\n\n    //}\n    //else\n    //{\n        nr = src[0].nr();\n        nc = src[0].nc();\n\n        for (uint64_t idx = 0; idx < src.size(); ++idx)\n        {\n            dst[idx].set_size(nr, nc);\n\n            for (uint64_t r = 0; r < nr; ++r)\n            {\n                for (uint64_t c = 0; c < nc; ++c)\n                {\n                    if (mask(r, c) == 0)\n                        dst[idx](r, c) = value;\n                    else\n                        dst[idx](r, c) = src[idx](r, c);\n                }\n            }\n        }\n\n    //}\n\n}   // end of apply_mask\n\n// ----------------------------------------------------------------------------------------\n\n// This block of statements defines the resnet-34 network\n\ntemplate <template <int, template<typename>class, int, typename> class block, int N, template<typename>class BN, typename SUBNET>\nusing residual = dlib::add_prev1<block<N, BN, 1, dlib::tag1<SUBNET>>>;\n\ntemplate <template <int, template<typename>class, int, typename> class block, int N, template<typename>class BN, typename SUBNET>\nusing residual_down = dlib::add_prev2<dlib::avg_pool<2, 2, 2, 2, dlib::skip1<dlib::tag2<block<N, BN, 2, dlib::tag1<SUBNET>>>>>>;\n\ntemplate <int N, template <typename> class BN, int stride, typename SUBNET>\nusing block = BN<dlib::con<N, 3, 3, 1, 1, dlib::relu<BN<dlib::con<N, 3, 3, stride, stride, SUBNET>>>>>;\n\ntemplate <int N, typename SUBNET> using ares = dlib::relu<residual<block, N, dlib::affine, SUBNET>>;\ntemplate <int N, typename SUBNET> using ares_down = dlib::relu<residual_down<block, N, dlib::affine, SUBNET>>;\n\ntemplate <typename SUBNET> using level1 = ares<512, ares<512, ares_down<512, SUBNET>>>;\ntemplate <typename SUBNET> using level2 = ares<256, ares<256, ares<256, ares<256, ares<256, ares_down<256, SUBNET>>>>>>;\ntemplate <typename SUBNET> using level3 = ares<128, ares<128, ares<128, ares_down<128, SUBNET>>>>;\ntemplate <typename SUBNET> using level4 = ares<64, ares<64, ares<64, SUBNET>>>;\n\nusing anet_type = dlib::loss_multiclass_log< dlib::fc<1000, dlib::avg_pool_everything<\n    level1<\n    level2<\n    level3<\n    level4<\n    dlib::max_pool<3, 3, 2, 2, dlib::relu<dlib::affine<dlib::con<64, 7, 7, 2, 2,\n    dlib::input_rgb_image_sized<227>\n    >>>>>>>>>>>;\n\nusing anet_type2 = dlib::loss_mmod<dlib::con<1,9,9,1,1,\n    level1<\n    level2<\n    level3<\n    level4<\n    dlib::max_pool<3, 3, 2, 2, dlib::relu<dlib::affine<dlib::con<64, 7, 7, 2, 2,\n    //dlib::input_rgb_image_pyramid<dlib::pyramid_down<6>>\n    dlib::input<std::array<dlib::matrix<uint8_t>, array_depth>>\n    >>>>>>>>>>;\n\n\n\n// ----------------------------------------------------------------------------------------\n\n\nint main(int argc, char** argv)\n{\n    std::string sdate, stime;\n\n    uint64_t idx=0, jdx=0;\n\n    typedef std::chrono::duration<double> d_sec;\n    auto start_time = chrono::system_clock::now();\n    auto stop_time = chrono::system_clock::now();\n    unsigned long training_duration = 1;  // number of hours to train \n    auto elapsed_time = chrono::duration_cast<d_sec>(stop_time - start_time);\n\n    std::vector<double> stop_criteria;\n    uint64_t num_crops = 0;\n    //std::vector<std::pair<uint64_t, uint64_t>> crop_sizes = { {1,1}, {38,148} };\n    //std::vector<uint32_t> filter_num;\n    //uint64_t max_one_step_count;\n    std::vector<dlib::matrix<unsigned char>> training_images;\n    std::vector<dlib::matrix<unsigned char>> testing_images;\n    std::vector<unsigned long> training_labels;\n    std::vector<unsigned long> testing_labels;\n\n    std::vector<std::vector<std::string>> training_file;\n    std::vector<std::vector<std::string>> test_file;\n\n    std::string data_directory;\n    std::string train_inputfile, test_inputfile;\n    std::vector<std::pair<std::string, std::string>> tr_image_files, te_image_files;\n    std::vector<dlib::matrix<uint16_t>> gt_train, gt_test;\n\n    dlib::matrix<uint16_t> g_crop;\n    dlib::rectangle rect_im, rect_gt;\n\n    //std::array<dlib::matrix<uint16_t>, img_depth> tr_crop;\n\n    std::ofstream DataLogStream;\n    std::string platform;\n    getPlatform(platform);\n    std::cout << \"Platform: \" << platform << std::endl;\n\n    if (platform.compare(0, 6, \"Laptop\") == 0)\n    {\n        std::cout << \"Match!\" << std::endl;\n    }\n\n    try\n    {\n        int bp = 0;\n\n        #if defined(_WIN32) | defined(__WIN32__) | defined(__WIN32) | defined(_WIN64) | defined(__WIN64)\n            \n        #else\n            std::string exe_path = get_linux_path();\n            std::cout << \"Path: \" << exe_path << std::endl;\n        #endif        \n\n        anet_type2 net_34_2;\n\n        std::vector<std::string> labels;\n        anet_type net_34;\n        dlib::deserialize(\"../nets/resnet34_1000_imagenet_classifier.dnn\") >> net_34 >> labels;\n\n\n        std::cout << \"net 34\" << std::endl;\n        std::cout << net_34 << std::endl;\n      \n        std::cout << \"net 34 v2\" << std::endl;\n        std::cout << net_34_2 << std::endl;\n\n        copy_net<138, 143, 137>(net_34, net_34_2);\n\n        //copy_layer<138, 137>(net_34, net_34_2);\n        //copy_layer<139, 138>(net_34, net_34_2);\n        //copy_layer<140, 139>(net_34, net_34_2);\n        //copy_layer<141, 140>(net_34, net_34_2);\n        //copy_layer<142, 141>(net_34, net_34_2);\n        //copy_layer<143, 142>(net_34, net_34_2);\n\n        auto& tmp1 = dlib::layer<138>(net_34).layer_details().get_layer_params();\n        auto& tmp2 = dlib::layer<137>(net_34_2).layer_details().get_layer_params();\n\n        auto& tmp3 = dlib::layer<140>(net_34).layer_details().get_layer_params();\n        auto& tmp4 = dlib::layer<139>(net_34_2).layer_details().get_layer_params();\n\n        auto& tmp5 = dlib::layer<141>(net_34).layer_details().get_layer_params();\n        auto& tmp6 = dlib::layer<140>(net_34_2).layer_details().get_layer_params();\n\n        auto& tmp7 = dlib::layer<142>(net_34).layer_details();\n        auto& tmp8 = dlib::layer<141>(net_34_2).layer_details();\n\n        auto& tmp9 = dlib::layer<143>(net_34).layer_details().get_layer_params();\n        auto& tmp10 = dlib::layer<142>(net_34_2).layer_details().get_layer_params();\n        \n        bp = 3;\n\n        double r1 = 10.0, r2 = 4.0;\n        dlib::set_learning_rate<130, 142>(net_34_2, r1, r2);\n\n        std::cout << \"net 34 v2\" << std::endl;\n        std::cout << net_34_2 << std::endl;\n\n        bp = 4;\n\n        //----------------------------------------------------------------\n        data_directory = \"D:/Projects/MNIST/data\";\n\n        // load the data in using the dlib built in function\n        //dlib::load_mnist_dataset(data_directory, training_images, training_labels, testing_images, testing_labels);\n\n        // get the location of the network\n        std::string net_name;\n        //net_name = \"D:/IUPUI/PhD/Results/dfd_dnn/dnn_reduction/2704823.pbs01_0_nets/nets/dfd_net_v14v_61_U_32_HPC.dat\";\n        //net_name = \"D:/IUPUI/PhD/Results/dfd_dnn/2649400.pbs01_0_nets/nets/dfd_net_v14f_61_U_32_HPC.dat\";\n        //net_name = \"D:/IUPUI/PhD/Results/dfd_dnn/2651620.pbs01_0_nets/nets/dfd_net_v14i_61_U_32_HPC.dat\";\n        //net_name = \"D:/IUPUI/PhD/Results/dfd_dnn/dnn_reduction/2646754.pbs01_0_nets/nets/dfd_net_v14e_61_U_32_HPC.dat\";\n        //net_name = \"D:/Projects/MNIST/nets/mnist_net_L05_100.dat\";\n\n        //declare the network\n        //dfd_net_type net;\n        //mnist_net_type net;\n\n        //// deserialize the network\n        //dlib::deserialize(net_name) >> net;\n\n        //std::cout << net << std::endl;\n\n        bp = 1;\n\n        //----------------------------------------------------------------\n/*\n        DataLogStream.open(\"random_cropper_selection.txt\", ios::out | ios::app);\n\n        train_inputfile = \"D:/IUPUI/DfD/DfD_DNN/dfd_train_data_sm2.txt\";\n\n        // parse through the supplied training csv file\n        parseCSVFile(train_inputfile, training_file);\n\n        // the first line in this file is now the data directory\n        data_directory = training_file[0][0];\n        training_file.erase(training_file.begin());\n\n        std::cout << \"Loading training images...\" << std::endl;\n\n        start_time = chrono::system_clock::now();\n        loadData(training_file, data_directory, tr, gt_train, tr_image_files);\n        stop_time = chrono::system_clock::now();\n\n        elapsed_time = chrono::duration_cast<d_sec>(stop_time - start_time);\n        std::cout << \"Loaded \" << tr.size() << \" training image sets in \" << elapsed_time.count() / 60 << \" minutes.\" << std::endl << std::endl;\n\n        uint32_t crop_num = 32;\n        uint64_t img_index = 0;\n        \n        for (uint32_t kdx = 0; kdx < 63500; ++kdx)\n        {\n            for (uint32_t mdx = 0; mdx < crop_num; ++mdx)\n            {\n                img_index = rnd.get_integer(tr.size());\n                make_random_cropping_rect(tr[img_index][0], rect_im);\n                DataLogStream << img_index << \",\" << tr[img_index][0].nr() << \",\" << tr[img_index][0].nc() << \",\" << rect_im.left() << \",\" << rect_im.top() << std::endl;\n            }\n        }\n\n        DataLogStream.close();\n\n        bp = 3;\n        return 0;\n        */\n        //-------------------------------------------------------------------\n\n        // setup the input image info\n        //data_directory = \"D:/IUPUI/Test_Data/Middlebury_Images_Third/Art/\";\n        //std::string f_img = \"Illum2/Exp1/view1.png\";\n        //std::string d_img = \"Illum2/Exp1/view1_lin_0.32_2.88.png\";\n        //std::string dm_img = \"disp1.png\";\n\n        //// load the images\n        //std::array<dlib::matrix<uint16_t>, img_depth> t, tm;\n        //dlib::matrix<dlib::rgb_pixel> f, f_tmp, d, d_tmp;\n        //dlib::matrix<uint16_t> dm_tmp, dm, mask;\n\n        //dlib::load_image(f_tmp, (data_directory+f_img));\n        //dlib::load_image(d_tmp, (data_directory+d_img));\n        //dlib::load_image(dm_tmp, (data_directory + dm_img));\n\n        ////split_channels(f_tmp, t);\n\n        //// crop the images to the right network size\n        //// get image size\n        //uint64_t rows = 368;// crop_sizes[1].first;\n        //uint64_t cols = 400;// crop_sizes[1].second;\n\n        //f.set_size(rows, cols);\n        //d.set_size(rows, cols);\n        //dm.set_size(rows, cols);\n\n        //// crop the image to fit into the net\n        //dlib::set_subm(f, 0, 0, rows, cols) = dlib::subm(f_tmp, 0, 0, rows, cols);\n        //dlib::set_subm(d, 0, 0, rows, cols) = dlib::subm(d_tmp, 0, 0, rows, cols);\n        //dlib::set_subm(dm, 0, 0, rows, cols) = dlib::subm(dm_tmp, 0, 0, rows, cols);\n\n        //// split the channels and combine\n        //split_channels(f, 0, t);\n        //split_channels(d, 3, t);\n\n        //// test the mask creation\n        //create_mask(dm, mask, 140, 150);\n\n        //// test the mask overlay feature\n        //apply_mask(t, tm, mask, 0);\n\n\n\n\n        bp = 2;\n\n        //dlib::matrix < dlib::rgb_pixel> t3;\n        //merge_channels(t, 0, t3);\n\n        // start looking at how to view the inards\n        //const auto& test = dlib::layer<50>(dfd_net).get_output();\n        //const float *t2 = test.host();\n        //uint64_t n = test.num_samples();\n        //uint64_t k = test.k();\n        //uint64_t nr = test.nr();\n        //uint64_t nc = test.nc();\n        //uint64_t img_size = nr * nc;\n        //uint64_t offset = 0;\n\n        //dlib::matrix<float> o_img(nr, nc);\n        //uint64_t index = 0;\n\n        //for (uint64_t r = 0; r < nr; ++r)\n        //{\n        //    for (uint64_t c = 0; c < nc; ++c)\n        //    {\n        //        o_img(r, c) = *(t2 + (offset*img_size) + index);\n        //        ++index;\n        //    }\n        //}\n\n        std::string save_location;\n        std::string save_name;\n\n//-----------------------------------------------------------------\n// DFD Net\n/*\n        \n        std::cout << \"Loading test images...\" << std::endl;\n\n        test_inputfile = \"D:/IUPUI/DfD/DfD_DNN/dfd_test_data_sm2.txt\";\n        parseCSVFile(test_inputfile, test_file);\n        data_directory = test_file[0][0];\n        test_file.erase(test_file.begin());\n\n        start_time = chrono::system_clock::now();\n        loadData(test_file, data_directory, te, gt_test, te_image_files);\n        stop_time = chrono::system_clock::now();\n\n        elapsed_time = chrono::duration_cast<d_sec>(stop_time - start_time);\n        std::cout << \"Loaded \" << te.size() << \" test image sets in \" << elapsed_time.count() / 60.0 << \" minutes.\" << std::endl << std::endl;\n\n        std::string net_version = \"v14a\";\n\n        save_location = \"D:/IUPUI/PhD/Results/dfd_dnn/dnn_reduction/\" + net_version + \"/\";\n        save_name = \"net_\" + net_version + \"_\";\n        net_name = \"D:/IUPUI/PhD/Results/dfd_dnn/dnn_reduction/\" + net_version + \"/nets/dfd_net_v14a_61_U_32_HPC.dat\";\n\n        dfd_net_type net;\n\n        // deserialize the network\n        dlib::deserialize(net_name) >> net;\n\n        std::cout << net << std::endl;\n\n        std::vector<std::string> data_name = { \"art\",\"books\",\"reindeer\" };\n        std::vector<uint32_t> ti = { 4, 22, 40 };\n\n        for (idx = 0; idx < ti.size(); ++idx)\n        {\n            std::cout << \"Running: \" << data_name[idx] << std::endl;\n            make_dir(save_location, data_name[idx]);\n\n            dlib::matrix<uint16_t> map = net(te[ti[idx]]);\n/*\n            gorgon_capture<50> gc_01(net);\n            gc_01.init((save_location + data_name[idx] + \"/\" + save_name + data_name[idx] + \"_L50\"));\n            gc_01.save_net_output(net);\n            gc_01.close_stream();\n\n            gorgon_capture<46> gc_02(net);\n            gc_02.init((save_location + data_name[idx] + \"/\" + save_name + data_name[idx] + \"_L46\"));\n            gc_02.save_net_output(net);\n            gc_02.close_stream();\n\n            gorgon_capture<44> gc_03(net);\n            gc_03.init((save_location + data_name[idx] + \"/\" + save_name + data_name[idx] + \"_L44\"));\n            gc_03.save_net_output(net);\n            gc_03.close_stream();\n\n            gorgon_capture<42> gc_04(net);\n            gc_04.init((save_location + data_name[idx] + \"/\" + save_name + data_name[idx] + \"_L42\"));\n            gc_04.save_net_output(net);\n            gc_04.close_stream();\n\n            gorgon_capture<38> gc_05(net);\n            gc_05.init((save_location + data_name[idx] + \"/\" + save_name + data_name[idx] + \"_L38\"));\n            gc_05.save_net_output(net);\n            gc_05.close_stream();\n\n            gorgon_capture<36> gc_06(net);\n            gc_06.init((save_location + data_name[idx] + \"/\" + save_name + data_name[idx] + \"_L36\"));\n            gc_06.save_net_output(net);\n            gc_06.close_stream();\n\n            gorgon_capture<34> gc_07(net);\n            gc_07.init((save_location + data_name[idx] + \"/\" + save_name + data_name[idx] + \"_L34\"));\n            gc_07.save_net_output(net);\n            gc_07.close_stream();\n\n            gorgon_capture<30> gc_08(net);\n            gc_08.init((save_location + data_name[idx] + \"/\" + save_name + data_name[idx] + \"_L30\"));\n            gc_08.save_net_output(net);\n            gc_08.close_stream();\n\n            gorgon_capture<28> gc_09(net);\n            gc_09.init((save_location + data_name[idx] + \"/\" + save_name + data_name[idx] + \"_L28\"));\n            gc_09.save_net_output(net);\n            gc_09.close_stream();\n\n            gorgon_capture<27> gc_10(net);\n            gc_10.init((save_location + data_name[idx] + \"/\" + save_name + data_name[idx] + \"_L27\"));\n            gc_10.save_net_output(net);\n            gc_10.close_stream();\n\n            //gorgon_capture<25> gc_10a(net);\n            //gc_10a.init((save_location + data_name[idx] + \"/\" + save_name + data_name[idx] + \"_L25\"));\n            //gc_10a.save_net_output(net);\n            //gc_10a.close_stream();\n\n            gorgon_capture<22> gc_11(net);\n            gc_11.init((save_location + data_name[idx] + \"/\" + save_name + data_name[idx] + \"_L22\"));\n            gc_11.save_net_output(net);\n            gc_11.close_stream();\n\n            gorgon_capture<18> gc_12(net);\n            gc_12.init((save_location + data_name[idx] + \"/\" + save_name + data_name[idx] + \"_L18\"));\n            gc_12.save_net_output(net);\n            gc_12.close_stream();\n\n            gorgon_capture<16> gc_13(net);\n            gc_13.init((save_location + data_name[idx] + \"/\" + save_name + data_name[idx] + \"_L16\"));\n            gc_13.save_net_output(net);\n            gc_13.close_stream();\n\n            gorgon_capture<15> gc_14(net);\n            gc_14.init((save_location + data_name[idx] + \"/\" + save_name + data_name[idx] + \"_L15\"));\n            gc_14.save_net_output(net);\n            gc_14.close_stream();\n\n            //gorgon_capture<13> gc_14a(net);\n            //gc_14a.init((save_location + data_name[idx] + \"/\" + save_name + data_name[idx] + \"_L13\"));\n            //gc_14a.save_net_output(net);\n            //gc_14a.close_stream();\n\n            gorgon_capture<10> gc_15(net);\n            gc_15.init((save_location + data_name[idx] + \"/\" + save_name + data_name[idx] + \"_L10\"));\n            gc_15.save_net_output(net);\n            gc_15.close_stream();\n\n            gorgon_capture<6> gc_16(net);\n            gc_16.init((save_location + data_name[idx] + \"/\" + save_name + data_name[idx] + \"_L06\"));\n            gc_16.save_net_output(net);\n            gc_16.close_stream();\n\n            gorgon_capture<4> gc_17(net);\n            gc_17.init((save_location + data_name[idx] + \"/\" + save_name + data_name[idx] + \"_L04\"));\n            gc_17.save_net_output(net);\n            gc_17.close_stream();\n\n            gorgon_capture<2> gc_18(net);\n            gc_18.init((save_location + data_name[idx] + \"/\" + save_name + data_name[idx] + \"_L02\"));\n            gc_18.save_net_output(net);\n            gc_18.close_stream();\n*/\n/*\n            gorgon_capture<1> gc_19(net);\n            gc_19.init((save_location + data_name[idx] + \"/\" + save_name + data_name[idx] + \"_L01\"));\n            gc_19.save_net_output(net);\n            gc_19.close_stream();\n\n            //gorgon_capture<0> gc_20(net);\n            //gc_20.init((save_location + data_name[idx] + \"/\" + save_name + data_name[idx] + \"_L00\"));\n            //gc_20.save_net_output(net);\n            //gc_20.close_stream();\n\n        }\n\n*/\n//-----------------------------------------------------------------\n// MNIST Net\n/*\n        //net_name = \"D:/Projects/MNIST/nets/mnist_net_05_16_120_84.dat\";\n        //net_name = \"D:/Projects/MNIST/nets/mnist_net_05_15_120_84.dat\";\n        //net_name = \"D:/Projects/MNIST/nets/mnist_net_04_15_120_84.dat\";\n        //net_name = \"D:/Projects/MNIST/nets/mnist_net_06_16_51_55.dat\";\n        net_name = \"D:/Projects/MNIST/nets/mnist_net_04_13_68_55.dat\";\n        //net_name = \"D:/Projects/MNIST/nets/mnist_net_v2_06_16_120_61.dat\";\n        mnist_net_type net;\n\n        // deserialize the network\n        dlib::deserialize(net_name) >> net;\n\n        std::cout << net << std::endl;\n        dlib::matrix<double, 1, 3> training_results = eval_mnist_performance(net, training_images, training_labels);\n        //auto results = net(training_images);\n\n        double avg_train_time = 0.0;\n        for (uint32_t idx = 0; idx < 30; ++idx)\n        {\n            start_time = chrono::system_clock::now();\n            //training_results = eval_net_performance(test_net, training_images, training_labels);\n            net(training_images);\n            stop_time = chrono::system_clock::now();\n            elapsed_time = chrono::duration_cast<d_sec>(stop_time - start_time);\n            avg_train_time += elapsed_time.count();\n            std::cout << \".\";\n        }\n        avg_train_time = avg_train_time / 30.0;\n        std::cout << endl;\n\n        std::cout << \"------------------------------------------------------------------\" << std::endl;\n        std::cout << \"Average run time:   \" << avg_train_time << std::endl;\n        std::cout << \"Training num_right: \" << training_results(0, 0) << std::endl;\n        std::cout << \"Training num_wrong: \" << training_results(0, 1) << std::endl;\n        std::cout << \"Training accuracy:  \" << training_results(0, 2) << std::endl;\n        std::cout << \"------------------------------------------------------------------\" << std::endl;\n\n        save_location = \"D:/Projects/MNIST/results/net_04_15_072_84/\";\n        save_name = \"net_out_\";\n        std::vector<uint32_t> ti = { 0,1,2,3,4,7,8,11,18,61 };//   7, 2, 1, 0, 4, 9, 5, 6, 3, 8\n\n        for (idx = 0; idx < ti.size(); ++idx)\n        {\n            std::cout << \"Running: \" << testing_labels[ti[idx]] << std::endl;\n\n            // run the image through the network\n            unsigned long predicted_labels = net(testing_images[ti[idx]]);\n            std::string number = num2str(testing_labels[ti[idx]], \"%02u/\");\n            make_dir(save_location, number);\n\n            gorgon_capture<11> gc_1(net);\n            gc_1.init((save_location + number + save_name + num2str(testing_labels[ti[idx]], \"%02u_\") + \"L11\"));\n            gc_1.save_net_output(net);\n            gc_1.close_stream();\n\n            //v2\n            //gorgon_capture<10> gc_1a(net);\n            //gc_1a.init((save_location + number + save_name + num2str(testing_labels[ti[idx]], \"%02u_\") + \"L10\"));\n            //gc_1a.save_net_output(net);\n            //gc_1a.close_stream();\n\n            //v1\n            gorgon_capture<9> gc_1a(net);\n            gc_1a.init((save_location + number + save_name + num2str(testing_labels[ti[idx]], \"%02u_\") + \"L09\"));\n            gc_1a.save_net_output(net);\n            gc_1a.close_stream();\n\n            gorgon_capture<8> gc_2(net);\n            gc_2.init((save_location + number + save_name + num2str(testing_labels[ti[idx]], \"%02u_\") + \"L08\"));\n            gc_2.save_net_output(net);\n            gc_2.close_stream();\n\n            //v2\n            //gorgon_capture<7> gc_2a(net);\n            //gc_2a.init((save_location + number + save_name + num2str(testing_labels[ti[idx]], \"%02u_\") + \"L07\"));\n            //gc_2a.save_net_output(net);\n            //gc_2a.close_stream();\n\n            gorgon_capture<6> gc_3(net);\n            gc_3.init((save_location + number + save_name + num2str(testing_labels[ti[idx]], \"%02u_\") + \"L06\"));\n            gc_3.save_net_output(net);\n            gc_3.close_stream();\n\n            //v1\n            gorgon_capture<5> gc_3b(net);\n            gc_3b.init((save_location + number + save_name + num2str(testing_labels[ti[idx]], \"%02u_\") + \"L05\"));\n            gc_3b.save_net_output(net);\n            gc_3b.close_stream();\n\n            gorgon_capture<4> gc_3a(net);\n            gc_3a.init((save_location + number + save_name + num2str(testing_labels[ti[idx]], \"%02u_\") + \"L04\"));\n            gc_3a.save_net_output(net);\n            gc_3a.close_stream();\n\n            //v1\n            gorgon_capture<3> gc_4(net);\n            gc_4.init((save_location + number + save_name + num2str(testing_labels[ti[idx]], \"%02u_\") + \"L03\"));\n            gc_4.save_net_output(net);\n            gc_4.close_stream();\n\n            gorgon_capture<2> gc_4a(net);\n            gc_4a.init((save_location + number + save_name + num2str(testing_labels[ti[idx]], \"%02u_\") + \"L02\"));\n            gc_4a.save_net_output(net);\n            gc_4a.close_stream();\n\n        }\n*/\n        bp = 3;\n    }\n    catch (std::exception &e)\n    {\n        std::cout << e.what() << std::endl;\n//        std::cout << \"Press enter to close the program.\" << std::endl;\n//        std::cin.ignore();\n\n    }\n\n    std::cout << \"Press Enter to close\" << std::endl;\n    std::cin.ignore();\n\treturn 0;\n\n}\t// end of main\n\n", "meta": {"hexsha": "bcedd08387a85280c7f88ec7b3381ca09312e65a", "size": 41742, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/old/pg_v2.cpp", "max_stars_repo_name": "davemers0160/Play_Ground", "max_stars_repo_head_hexsha": "90c5e6ef57c0c2060f0e8f5ecf249826c21cea7c", "max_stars_repo_licenses": ["MIT"], "max_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/pg_v2.cpp", "max_issues_repo_name": "davemers0160/Play_Ground", "max_issues_repo_head_hexsha": "90c5e6ef57c0c2060f0e8f5ecf249826c21cea7c", "max_issues_repo_licenses": ["MIT"], "max_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/pg_v2.cpp", "max_forks_repo_name": "davemers0160/Play_Ground", "max_forks_repo_head_hexsha": "90c5e6ef57c0c2060f0e8f5ecf249826c21cea7c", "max_forks_repo_licenses": ["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.3745762712, "max_line_length": 169, "alphanum_fraction": 0.556130516, "num_tokens": 11424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2784227154813871}}
{"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 \"bool_complex.hpp\"\n\n#include <unordered_set>\n\n#include <boost/dynamic_bitset.hpp>\n#include <boost/format.hpp>\n\n#include <core/utils/program_options.hpp>\n#include <core/utils/range_utils.hpp>\n#include <classical/functions/npn_canonization.hpp>\n\nusing namespace boost::program_options;\n\nnamespace cirkit\n{\n\n/******************************************************************************\n * Types                                                                      *\n ******************************************************************************/\n\n/******************************************************************************\n * Private functions                                                          *\n ******************************************************************************/\n\n/******************************************************************************\n * Public functions                                                           *\n ******************************************************************************/\n\nbool_complex_command::bool_complex_command( const environment::ptr& env )\n  : cirkit_command( env, \"Computes complexities of Boolean functions\" )\n{\n  opts.add_options()\n    ( \"numvars,n\", value_with_default( &numvars ), \"number of variables (n <= 4)\" )\n    ( \"count,c\",                                   \"compute upper bound on size\" )\n    ( \"lengths,l\",                                 \"compute normal lengths\" )\n    ( \"depths,d\",                                  \"compute depths\" )\n    ( \"lengths_maj\",                               \"compute normal lengths (MAJ)\" )\n    ( \"depths_maj\",                                \"compute depths (MAJ)\" )\n    ( \"npn\",                                       \"compute number of NPN classes\" )\n    ;\n  add_positional_option( \"numvars\" );\n}\n\nbool bool_complex_command::execute()\n{\n  if ( is_set( \"count\" ) )\n  {\n    compute_ub_aig();\n  }\n  if ( is_set( \"lengths\" ) )\n  {\n    compute( true );\n  }\n  if ( is_set( \"depths\" ) )\n  {\n    compute( false );\n  }\n  if ( is_set( \"lengths_maj\" ) )\n  {\n    compute_maj( true, is_set( \"npn\" ) );\n  }\n  if ( is_set( \"depths_maj\" ) )\n  {\n    compute_maj( false, is_set( \"npn\" ) );\n  }\n\n  return true;\n}\n\nvoid bool_complex_command::compute( bool length )\n{\n  const auto none = (unsigned)-1;\n  auto count      = 1u << ( ( 1u << numvars ) - 1u );\n\n  std::vector<unsigned>              func_to_length( count, none );\n  std::vector<std::vector<unsigned>> length_to_func;\n\n  /* constant function */\n  func_to_length[0u] = 0u;\n  length_to_func.push_back( {0u} );\n\n  /* one-variable functions */\n  for ( auto k = 0u; k < numvars; ++k )\n  {\n    const auto xk = ((1 << (1 << numvars)) - 1) / ((1 << (1 << (numvars - (k + 1)))) + 1);\n    func_to_length[xk] = 0;\n    length_to_func.back().push_back( xk );\n  }\n\n  count -= ( 1u + numvars );\n  auto current_length = 0u;\n\n  while ( true )\n  {\n    ++current_length;\n\n    length_to_func.push_back( {} );\n\n    int j = 0u;\n    int k = current_length - 1;\n\n    do\n    {\n      for ( auto g = 0u; g < length_to_func[j].size(); ++g )\n      {\n        const auto& fg = length_to_func[j][g];\n        for ( auto h = 0u; h < length_to_func[k].size(); ++h )\n        {\n          const auto& fh = length_to_func[k][h];\n\n          if ( fg == fh ) { continue; }\n\n          for ( const auto& f : { fg & fh, ~fg & fh, fg & ~fh, fg | fh, fg ^ fh } )\n          {\n            if ( func_to_length[f] == none )\n            {\n              func_to_length[f] = current_length;\n              length_to_func.back().push_back( f );\n\n              if ( --count == 0u ) { goto done; }\n            }\n          }\n        }\n      }\n\n      ++j;\n      if ( length ) { --k; }\n    } while ( j <= k );\n  }\n\ndone:\n  for ( const auto& entry : index( length_to_func ) )\n  {\n    std::cout << boost::format( \"[i] %s %3d: %12d\" ) % ( length ? \"length\" : \"depth\" ) % entry.index % ( entry.value.size() << 1u ) << std::endl;\n  }\n}\n\nvoid bool_complex_command::compute_ub()\n{\n  const auto none = (unsigned)-1;\n  auto count      = 1u << ( ( 1u << numvars ) - 1u );\n\n  std::vector<unsigned>              func_to_count( count, none );\n  std::vector<std::vector<unsigned>> count_to_func;\n  std::vector<unsigned>              func_to_footprint( count, 0u );\n\n  /* constant function */\n  func_to_count[0u] = 0u;\n  count_to_func.push_back( {0u} );\n\n  /* one-variable functions */\n  for ( auto k = 0u; k < numvars; ++k )\n  {\n    const auto xk = ((1 << (1 << numvars)) - 1) / ((1 << (1 << (numvars - (k + 1)))) + 1);\n    func_to_count[xk] = 0;\n    count_to_func.back().push_back( xk );\n  }\n\n  /* compute initial footprints */\n  count_to_func.push_back( {} );\n  auto footprint = 0u;\n  for ( auto op = 0u; op < 5u; ++op )\n  {\n    for ( auto i = 0u; i < numvars; ++i )\n    {\n      const auto xi = ((1 << (1 << numvars)) - 1) / ((1 << (1 << (numvars - (i + 1)))) + 1);\n\n      for ( auto j = i + 1u; j < numvars; ++j )\n      {\n\tconst auto xj = ((1 << (1 << numvars)) - 1) / ((1 << (1 << (numvars - (j + 1)))) + 1);\n\tauto f = 0u;\n\n\tswitch ( op )\n\t{\n\tcase 0u:\n\t  f = xi & xj; break;\n\tcase 1u:\n\t  f = ~xi & xj; break;\n\tcase 2u:\n\t  f = xi & ~xj; break;\n\tcase 3u:\n\t  f = xi | xj; break;\n\tcase 4u:\n\t  f = xi ^ xj; break;\n\tdefault: assert( false );\n\t}\n\n\tfunc_to_footprint[f] = 1 << footprint++;\n\tfunc_to_count[f] = 1u;\n\tcount_to_func.back().push_back( f );\n      }\n    }\n  }\n  const auto count_at_one = 5 * ( ( numvars * ( numvars - 1 ) ) / 2 );\n  assert( footprint == count_at_one );\n\n  count -= ( 1u + numvars + count_at_one );\n  auto current_length = 1u;\n\n  while ( count )\n  {\n    ++current_length; /* r */\n    count_to_func.push_back( {} );\n\n    for ( int j = ( current_length - 1 ) / 2; j >= 0; --j )\n    {\n      int k = current_length - 1 - j;\n\n      for ( auto g = 0u; g < count_to_func[j].size(); ++g )\n      {\n\tconst auto& fg = count_to_func[j][g];\n\tfor ( auto h = 0u; h < count_to_func[k].size(); ++h )\n\t{\n\t  const auto& fh = count_to_func[k][h];\n\n\t  if ( fg == fh ) { continue; }\n\n\t  unsigned u{}, v{};\n\t  if ( func_to_footprint[fg] & func_to_footprint[fh] )\n\t  {\n\t    u = current_length - 1;\n\t    v = func_to_footprint[fg] & func_to_footprint[fh];\n\t  }\n\t  else\n\t  {\n\t    u = current_length;\n\t    v = func_to_footprint[fg] | func_to_footprint[fh];\n\t  }\n\n\t  for ( const auto& f : { fg & fh, ~fg & fh, fg & ~fh, fg | fh, fg ^ fh } )\n\t  {\n\t    if ( func_to_count[f] == none )\n\t    {\n\t      func_to_count[f] = u;\n\t      func_to_footprint[f] = v;\n\t      count_to_func[u].push_back( f );\n\n\t      --count;\n\t    }\n\t    else if ( func_to_count[f] > u )\n\t    {\n\t      auto& old_list = count_to_func[func_to_count[f]];\n\t      const auto it = std::find( old_list.begin(), old_list.end(), f );\n\t      assert( it != old_list.end() );\n\t      old_list.erase( it );\n\t      func_to_count[f] = u;\n\t      func_to_footprint[f] = v;\n\t      count_to_func[u].push_back( f );\n\t    }\n\t    else if ( func_to_count[f] == u && func_to_footprint[f] != ( func_to_footprint[f] | v ) )\n\t    {\n\t      func_to_footprint[f] |= v;\n\t    }\n\t  }\n\t}\n      }\n    }\n  }\n\n  for ( const auto& entry : index( count_to_func ) )\n  {\n    std::cout << boost::format( \"[i] count %3d: %12d\" ) % entry.index % ( entry.value.size() << 1u ) << std::endl;\n  }\n}\n\nvoid bool_complex_command::compute_ub_aig()\n{\n  const auto none = (unsigned)-1;\n  auto count      = 1u << ( ( 1u << numvars ) - 1u );\n\n  std::vector<unsigned>              func_to_count( count, none );\n  std::vector<std::vector<unsigned>> count_to_func;\n  std::vector<unsigned>              func_to_footprint( count, 0u );\n\n  /* constant function */\n  func_to_count[0u] = 0u;\n  count_to_func.push_back( {0u} );\n\n  /* one-variable functions */\n  for ( auto k = 0u; k < numvars; ++k )\n  {\n    const auto xk = ((1 << (1 << numvars)) - 1) / ((1 << (1 << (numvars - (k + 1)))) + 1);\n    func_to_count[xk] = 0;\n    count_to_func.back().push_back( xk );\n  }\n\n  /* compute initial footprints */\n  count_to_func.push_back( {} );\n  auto footprint = 0u;\n  for ( auto op = 0u; op < 4u; ++op )\n  {\n    for ( auto i = 0u; i < numvars; ++i )\n    {\n      const auto xi = ((1 << (1 << numvars)) - 1) / ((1 << (1 << (numvars - (i + 1)))) + 1);\n\n      for ( auto j = i + 1u; j < numvars; ++j )\n      {\n\tconst auto xj = ((1 << (1 << numvars)) - 1) / ((1 << (1 << (numvars - (j + 1)))) + 1);\n\tauto f = 0u;\n\n\tswitch ( op )\n\t{\n\tcase 0u:\n\t  f = xi & xj; break;\n\tcase 1u:\n\t  f = ~xi & xj; break;\n\tcase 2u:\n\t  f = xi & ~xj; break;\n\tcase 3u:\n\t  f = xi | xj; break;\n\tdefault: assert( false );\n\t}\n\n\tfunc_to_footprint[f] = 1 << footprint++;\n\tfunc_to_count[f] = 1u;\n\tcount_to_func.back().push_back( f );\n      }\n    }\n  }\n  const auto count_at_one = 4 * ( ( numvars * ( numvars - 1 ) ) / 2 );\n  assert( footprint == count_at_one );\n\n  count -= ( 1u + numvars + count_at_one );\n  auto current_length = 1u;\n\n  while ( count )\n  {\n    ++current_length; /* r */\n    count_to_func.push_back( {} );\n\n    for ( int j = ( current_length - 1 ) / 2; j >= 0; --j )\n    {\n      int k = current_length - 1 - j;\n\n      for ( auto g = 0u; g < count_to_func[j].size(); ++g )\n      {\n\tconst auto& fg = count_to_func[j][g];\n\tfor ( auto h = 0u; h < count_to_func[k].size(); ++h )\n\t{\n\t  const auto& fh = count_to_func[k][h];\n\n\t  if ( fg == fh ) { continue; }\n\n\t  unsigned u{}, v{};\n\t  if ( func_to_footprint[fg] & func_to_footprint[fh] )\n\t  {\n\t    u = current_length - 1;\n\t    v = func_to_footprint[fg] & func_to_footprint[fh];\n\t  }\n\t  else\n\t  {\n\t    u = current_length;\n\t    v = func_to_footprint[fg] | func_to_footprint[fh];\n\t  }\n\n\t  for ( const auto& f : { fg & fh, ~fg & fh, fg & ~fh, fg | fh } )\n\t  {\n\t    if ( func_to_count[f] == none )\n\t    {\n\t      func_to_count[f] = u;\n\t      func_to_footprint[f] = v;\n\t      count_to_func[u].push_back( f );\n\n\t      --count;\n\t    }\n\t    else if ( func_to_count[f] > u )\n\t    {\n\t      auto& old_list = count_to_func[func_to_count[f]];\n\t      const auto it = std::find( old_list.begin(), old_list.end(), f );\n\t      assert( it != old_list.end() );\n\t      old_list.erase( it );\n\t      func_to_count[f] = u;\n\t      func_to_footprint[f] = v;\n\t      count_to_func[u].push_back( f );\n\t    }\n\t    else if ( func_to_count[f] == u && func_to_footprint[f] != ( func_to_footprint[f] | v ) )\n\t    {\n\t      func_to_footprint[f] |= v;\n\t    }\n\t  }\n\t}\n      }\n    }\n  }\n\n  for ( const auto& entry : index( count_to_func ) )\n  {\n    std::cout << boost::format( \"[i] count %3d: %12d\" ) % entry.index % ( entry.value.size() << 1u ) << std::endl;\n  }\n}\n\ninline unsigned maj( unsigned a, unsigned b, unsigned c )\n{\n  return ( a & b ) | ( a & c ) | ( b & c );\n}\n\nvoid bool_complex_command::compute_maj( bool length, bool npn )\n{\n  const auto none = (unsigned)-1;\n  auto count      = 1u << ( ( 1u << numvars ) - 1u );\n\n  std::vector<unsigned>                     func_to_length( count, none );\n  std::vector<std::vector<unsigned>>        length_to_func;\n  std::vector<std::unordered_set<unsigned>> length_to_npn;\n\n  /* constant function */\n  func_to_length[0u] = 0u;\n  length_to_func.push_back( {0u} );\n\n  /* one-variable functions */\n  for ( auto k = 0u; k < numvars; ++k )\n  {\n    const auto xk = ((1 << (1 << numvars)) - 1) / ((1 << (1 << (numvars - (k + 1)))) + 1);\n    func_to_length[xk] = 0;\n    length_to_func.back().push_back( xk );\n  }\n\n  if ( npn )\n  {\n    length_to_npn.push_back( std::unordered_set<unsigned>() );\n    length_to_npn.back().insert( 0u );\n    length_to_npn.back().insert( (1 << (1 << (numvars - 1))) - 1 );\n  }\n\n  count -= ( 1u + numvars );\n  auto current_length = 0u;\n\n  while ( true )\n  {\n    ++current_length;\n\n    length_to_func.push_back( {} );\n\n    if ( npn )\n    {\n      length_to_npn.push_back( std::unordered_set<unsigned>() );\n    }\n\n    auto j = 0u;\n    auto k = 0u;\n    int l = current_length - 1;\n\n    do\n    {\n      for ( auto g = 0u; g < length_to_func[j].size(); ++g )\n      {\n        const auto& fg = length_to_func[j][g];\n        for ( auto h = ( j == k ) ? ( g + 1u ) : 0u; h < length_to_func[k].size(); ++h )\n        {\n          const auto& fh = length_to_func[k][h];\n          if ( fg == fh ) { continue; }\n\n          for ( auto i = ( static_cast<int>( k ) == l ) ? ( h + 1u ) : ( ( static_cast<int>( j ) == l ) ? ( g + 1u ) : 0u ); i < length_to_func[l].size(); ++i )\n          {\n            const auto& fi = length_to_func[l][i];\n            if ( fg == fi || fh == fi ) { continue; }\n\n            for ( const auto& f : { maj( fg, fh, fi ), maj( fg, fh, ~fi ), maj( fg, ~fh, fi ), maj( ~fg, fh, fi ) } )\n            {\n              if ( func_to_length[f] == none )\n              {\n                func_to_length[f] = current_length;\n                length_to_func.back().push_back( f );\n\n                if ( npn )\n                {\n                  boost::dynamic_bitset<> phase;\n                  std::vector<unsigned> perm;\n                  auto tt_npn = exact_npn_canonization( tt( 1u << numvars, f ), phase, perm );\n\n                  length_to_npn.back().insert( tt_npn.to_ulong() );\n                }\n\n                if ( --count == 0u ) { goto done; }\n              }\n            }\n          }\n        }\n      }\n\n      if ( length )\n      {\n        if ( j + k == ( current_length - 1 ) )\n        {\n          ++j;\n          k = j;\n        }\n        else\n        {\n          ++k;\n        }\n        l = current_length - 1 - j - k;\n      }\n      else\n      {\n        if ( k == current_length - 1 )\n        {\n          ++j;\n          k = j;\n        }\n        else\n        {\n          ++k;\n        }\n        if ( j == current_length )\n        {\n          l = -1;\n        }\n      }\n    } while ( l >= 0 );\n  }\n\ndone:\n  for ( const auto& entry : index( length_to_func ) )\n  {\n    std::cout << boost::format( \"[i] %s %3d: %12d\" ) % ( length ? \"length\" : \"depth\" ) % entry.index % ( entry.value.size() << 1u );\n\n    if ( npn )\n    {\n      std::cout << boost::format( \", npn classes: %5d\" ) % length_to_npn[entry.index].size();\n    }\n\n    std::cout << std::endl;\n  }\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": "7d568cfa84ae3cd2d4f565896df87abd2190019e", "size": 15215, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cli/commands/bool_complex.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/cli/commands/bool_complex.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/cli/commands/bool_complex.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": 27.1696428571, "max_line_length": 160, "alphanum_fraction": 0.5041077884, "num_tokens": 4455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.27842270890852233}}
{"text": "﻿#include <iostream>\n#include <fstream>\n#include <regex>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/serialization/vector.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/filesystem/fstream.hpp>\n\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/phoenix.hpp>\n#include <boost/fusion/include/std_pair.hpp>\n#include <boost/iterator/iterator_adaptor.hpp>\n\n#include <tbb/tbb.h>\n\n#include <Eigen/StdVector>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/highgui/highgui_c.h>\n\n#include <pupiltracker/pupiltracker.h>\n\n#include <singleeyefitter/singleeyefitter.h>\n#include <singleeyefitter/fun.h>\n#include <singleeyefitter/projection.h>\n\n#include \"clipper.hpp\"\n\n\nusing namespace singleeyefitter;\n\nstruct fitEyeModel_ret {\n    Sphere<double> est_eye, est_eye_lm, est_eye_contrast;\n    std::vector<Circle3D<double>> est_pupils, est_pupils2, est_pupils_lm, est_pupils_contrast;\n};\n\n\nnamespace detail {\n    using namespace boost::spirit;\n\n    template<class T> struct as_qi;\n    template<> struct as_qi<int> { static const int_type& get() {return int_;} };\n    template<> struct as_qi<double> { static const double_type& get() {return double_;} };\n\n    template<class To>\n    struct parse_helper {\n        template<class From>\n        static To parse(const From& src) {\n            using std::begin;\n            using std::end;\n            To ret;\n            bool success = qi::parse(begin(src), end(src), as_qi<To>::get(), ret);\n            if (!success) {\n                throw std::runtime_error(\"Parse int failed\");\n            }\n            return ret;\n        }\n\n        static To parse(char* src) {\n            To ret;\n            bool success = qi::parse(src, src + strlen(src), as_qi<To>::get(), ret);\n            if (!success) {\n                throw std::runtime_error(\"Parse int failed\");\n            }\n            return ret;\n        }\n\n        static To parse(const char* src) {\n            To ret;\n            bool success = qi::parse(src, src + strlen(src), as_qi<To>::get(), ret);\n            if (!success) {\n                throw std::runtime_error(\"Parse int failed\");\n            }\n            return ret;\n        }\n    };\n}\n\ntemplate<typename T>\nint parse_int(T&& src) {\n    return ::detail::parse_helper<int>::parse(std::forward<T>(src));\n}\ntemplate<typename T>\ndouble parse_double(T&& src) {\n    return ::detail::parse_helper<double>::parse(std::forward<T>(src));\n}\n\n\ncv::Point2f toImgCoord(const cv::Point2f& point, const cv::Mat& m, double scale = 1, int shift = 0) {\n    return cv::Point2f(static_cast<float>((m.cols/2 + scale*point.x) * (1<<shift)),\n        static_cast<float>((m.rows/2 + scale*point.y) * (1<<shift)));\n}\ncv::Point toImgCoord(const cv::Point& point, const cv::Mat& m, double scale = 1, int shift = 0) {\n    return cv::Point(static_cast<int>((m.cols/2 + scale*point.x) * (1<<shift)),\n        static_cast<int>((m.rows/2 + scale*point.y) * (1<<shift)));\n}\ncv::RotatedRect toImgCoord(const cv::RotatedRect& rect, const cv::Mat& m, float scale = 1) {\n    return cv::RotatedRect(toImgCoord(rect.center,m,scale),\n        cv::Size2f(scale*rect.size.width,\n        scale*rect.size.height),\n        rect.angle);\n}\n\nnamespace boost {\n    namespace serialization {\n\n        template<class Archive, class T>\n        inline void serialize(Archive & ar, Ellipse2D<T> & g, const unsigned int version)\n        {\n            ar & g.centre;\n            ar & g.major_radius;\n            ar & g.minor_radius;\n            ar & g.angle;\n        }\n        template<class Archive, typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols>\n        inline void serialize(Archive & ar,\n                              Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> & t,\n                              const unsigned int file_version)\n        {\n            int rows = t.rows(), cols = t.cols();\n            ar & rows;\n            ar & cols;\n            if( rows * cols != t.size() )\n                t.resize( rows, cols );\n\n            for(int i=0; i<t.size(); i++)\n                ar & t.data()[i];\n        }\n        template<class Archive, class T>\n        inline void serialize(Archive & ar, cv::Point_<T> & g, const unsigned int version)\n        {\n            ar & g.x;\n            ar & g.y;\n        }\n\n    } // namespace serializationstd::vector<Eigen::Vector2d>\n} // namespace boost\n\ntemplate <typename T>\nstd::vector<size_t> sort_indexes_impl(const T &v, std::random_access_iterator_tag)\n{\n    static_assert(std::is_same<typename std::iterator_traits<typename T::iterator>::iterator_category, std::random_access_iterator_tag>::value, \"Type matches tag\");\n\n    // initialize original index locations\n    auto idx = fun::range_<std::vector<size_t>>(v.size());\n\n    // sort indexes based on comparing values in v\n    sort(std::begin(idx), std::end(idx), [&](size_t i1, size_t i2){ return v[i1] < v[i2]; });\n\n    return idx;\n}\n\ntemplate <typename T>\nstd::vector<size_t> sort_indexes(const T &v)\n{\n    return sort_indexes_impl(v, typename std::iterator_traits<typename T::iterator>::iterator_category());\n}\n\ntemplate< typename T >\nvoid reorder(std::vector<T>& vals, const std::vector<size_t>& idxs)  {\n    vals = fun::map([&](size_t i){ return vals[i]; }, idxs);\n}\n\nstruct PupilGroundTruth {\n    Eigen::Vector3d gaze_vector;\n    std::vector<Eigen::Vector2d> outline;\n    PupilGroundTruth() {}\n    PupilGroundTruth(\n        Eigen::Vector3d gaze_vector,\n        std::vector<Eigen::Vector2d> outline) :\n            gaze_vector(std::move(gaze_vector)),\n            outline(std::move(outline)) {}\n};\n\ndouble calcEllipseTruthOverlap(const Ellipse2D<double>& ellipse, const std::vector<Eigen::Vector2d>& truth_poly) {\n    ClipperLib::Path truth_path;\n    ClipperLib::Path ellipse_path;\n\n    int N = truth_poly.size();\n    for(int i = 0; i < N; ++i) {\n        auto p = truth_poly[i];\n\n        double theta = (double)i / N * 2 * PI;\n        auto p2 = pointAlongEllipse(ellipse, -theta);\n\n        truth_path.emplace_back(static_cast<int>(std::floor(p.x()*100+0.5)),\n                                static_cast<int>(std::floor(p.y()*100+0.5)));\n        ellipse_path.emplace_back(static_cast<int>(std::floor(p2.x()*100+0.5)),\n                                  static_cast<int>(std::floor(p2.y()*100+0.5)));\n    };\n\n    ClipperLib::Clipper clpr;\n    clpr.AddPolygon(truth_path, ClipperLib::ptSubject);\n    clpr.AddPolygon(ellipse_path, ClipperLib::ptClip);\n\n    ClipperLib::Paths intersection_paths, union_paths;\n    clpr.Execute(ClipperLib::ctIntersection, intersection_paths);\n    clpr.Execute(ClipperLib::ctUnion, union_paths);\n\n    double intersection_area = fun::sum([](const ClipperLib::Path& path){ return ClipperLib::Area(path); }, intersection_paths);\n    double union_area = fun::sum([](const ClipperLib::Path& path){ return ClipperLib::Area(path); }, union_paths);\n\n    return intersection_area / union_area;\n}\n\nvoid writeResults(const std::string& filename,\n                  const std::vector<int> ids,\n                  const std::vector<EyeModelFitter::Pupil>& null_pupils,\n                  const std::vector<EyeModelFitter::Pupil>& simple_pupils,\n                  const std::vector<EyeModelFitter::Pupil>& contrast_pupils,\n                  const std::vector<EyeModelFitter::Pupil>& edge_pupils,\n                  const std::map<int, PupilGroundTruth>& true_pupils,\n                  double focal_length) {\n    std::ofstream of(filename);\n\n    for (int i = 0; i < ids.size(); ++i) {\n        const auto& pupil = null_pupils[i].circle;\n        const auto& pupil2 = simple_pupils[i].circle;\n        const auto& pupil_dlib = contrast_pupils[i].circle;\n        const auto& pupil_lm = edge_pupils[i].circle;\n        const auto& id = ids[i];\n        auto true_pupil_it = true_pupils.find(id);\n        if (true_pupil_it == true_pupils.end())\n            continue;\n\n        const auto& true_pupil = true_pupil_it->second;\n\n        double anglediff = acos(pupil.normal.dot(true_pupil.gaze_vector))*180/PI;\n        double anglediff2 = acos(pupil2.normal.dot(true_pupil.gaze_vector))*180/PI;\n        double anglediff_dlib = acos(pupil_dlib.normal.dot(true_pupil.gaze_vector))*180/PI;\n        double anglediff_lm = acos(pupil_lm.normal.dot(true_pupil.gaze_vector))*180/PI;\n\n        auto true_pupil_outline = true_pupil.outline;\n\n        double ellipdist = calcEllipseTruthOverlap(Ellipse2D<double>(project(pupil, focal_length)), true_pupil_outline);\n        double ellipdist2 = calcEllipseTruthOverlap(Ellipse2D<double>(project(pupil2, focal_length)), true_pupil_outline);\n        double ellipdist_dlib = calcEllipseTruthOverlap(Ellipse2D<double>(project(pupil_dlib, focal_length)), true_pupil_outline);\n        double ellipdist_lm = calcEllipseTruthOverlap(Ellipse2D<double>(project(pupil_lm, focal_length)), true_pupil_outline);\n\n        of << id;\n        of << \"\\t\" << anglediff << \"\\t\" << anglediff2 << \"\\t\" << anglediff_dlib << \"\\t\" << anglediff_lm;\n        of << \"\\t\" << ellipdist << \"\\t\" << ellipdist2 << \"\\t\" << ellipdist_dlib << \"\\t\" << ellipdist_lm;\n        of << std::endl;\n    }\n}\n\nstd::string regex_escape(const std::string& pattern) {\n    return regex_replace(pattern,\n        std::regex(\"[\\\\^\\\\.\\\\$\\\\|\\\\(\\\\)\\\\[\\\\]\\\\*\\\\+\\\\?\\\\/\\\\\\\\]\"),\n        std::string(\"\\\\$&\"));\n}\n\nstruct Key {\n    wchar_t code;\n    bool shift;\n    bool ctrl;\n    bool meta;\n};\n\n#ifdef WIN32\n\nKey cvxWaitKey(int delay) {\n    int code = cv::waitKey(delay);\n    Key key;\n    key.code = code;\n    key.shift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;\n    key.ctrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;\n    key.meta = (GetKeyState(VK_MENU) & 0x8000) != 0;\n    return key;\n}\n\n#else\n\nKey cvxWaitKey(int delay) {\n    int code = cv::waitKey(delay);\n    Key key;\n    if (code >= 'A' && code <= 'Z') {\n        key.code = code + 'a' - 'A';\n        key.shift = true;\n    }\n    else {\n        key.code = code;\n        key.shift = false;\n    }\n    key.ctrl = false;\n    key.meta = false;\n    return key;\n}\n\n#endif\n\nint main(int argc, char* argv[])\n{\n    using boost::math::sign;\n\n    if (argc < 4) {\n        std::cerr << \"USAGE: \" << argv[0] << \" <folder> <filepattern> <fov> [<truthfile> [<init_num_added>]]\" << std::endl;\n        return 1;\n    }\n\n    //try\n    {\n        namespace fs = boost::filesystem;\n\n        std::vector<int> ids;\n        std::vector<cv::Mat> obs_eye_images;\n        std::vector<Ellipse2D<double>> obs_pupil_ellipses;\n        std::vector<std::vector<cv::Point2f>> obs_pupil_inliers;\n\n        fs::path imagedir(argv[1]);\n        std::string filepattern(argv[2]);\n\n        std::smatch filepatternisregex_match;\n        if (regex_match(filepattern, filepatternisregex_match, std::regex(\"/(.*)/\"))) {\n            filepattern = filepatternisregex_match[1].str();\n        } else {\n            filepattern = regex_escape(filepattern);\n            // Converts #### into (\\d\\d\\d\\d\\d*)\n            filepattern = regex_replace(filepattern, std::regex(\"#+\"), std::string(\"($&\\\\d*)\"));\n            filepattern = regex_replace(filepattern, std::regex(\"#\"), std::string(\"\\\\d\"));\n        }\n        std::regex file_regex(filepattern);\n\n        tbb::mutex push_lock;\n\n        tbb::parallel_for_each(fs::directory_iterator(imagedir), fs::directory_iterator(), [&] (fs::path path) {\n            std::smatch path_match;\n            std::string path_str = path.filename().string();\n\n            if (is_regular_file(path) && regex_match(path_str, path_match, file_regex)) {\n                int id = parse_int(path_match[1].str());\n                cv::Mat eye = cv::imread(path.string(), CV_LOAD_IMAGE_GRAYSCALE);\n                Ellipse2D<double> el;\n                std::vector<cv::Point2f> inlier_pts;\n\n                bool cache_valid = false;\n                const int CACHE_VERSION = 8;\n\n                fs::path cache_path = path.parent_path() / fs::path(path.stem().string() + \".cache\");\n\n                if (exists(cache_path)) {\n                    std::ifstream ifs(cache_path.string());\n                    boost::archive::text_iarchive ia(ifs);\n\n                    int ia_cache_version;\n                    ia >> ia_cache_version;\n                    if (CACHE_VERSION == ia_cache_version) {\n                        std::cout << \"Loading \" << cache_path.string() << std::endl;\n\n                        ia >> el;\n                        ia >> inlier_pts;\n\n                        cache_valid = true;\n                    }\n                }\n\n                if (!cache_valid)\n                {\n                    std::cout << \"Pupil tracking \" << path.string() << std::endl;\n\n                    pupiltracker::tracker_log log;\n\n                    pupiltracker::TrackerParams pupil_tracker_params;\n                    pupil_tracker_params.Radius_Min = 20;\n                    pupil_tracker_params.Radius_Max = 70;\n                    pupil_tracker_params.CannyThreshold1 = 20;\n                    pupil_tracker_params.CannyThreshold2 = 40;\n                    pupil_tracker_params.CannyBlur = 1.6;\n                    pupil_tracker_params.EarlyRejection = true;\n                    pupil_tracker_params.EarlyTerminationPercentage = 95;\n                    pupil_tracker_params.PercentageInliers = 20;\n                    pupil_tracker_params.InlierIterations = 2;\n                    pupil_tracker_params.ImageAwareSupport = true;\n                    pupil_tracker_params.StarburstPoints = 0;\n                    //pupil_tracker_params.Seed = 0;\n\n                    pupiltracker::findPupilEllipse_out pupil_tracker_out;\n                    bool found = pupiltracker::findPupilEllipse(pupil_tracker_params, eye, pupil_tracker_out, log);\n\n                    if (found) {\n                        el = toEllipse<double>(pupil_tracker_out.elPupil);\n                        el.centre -= Eigen::Vector2d(eye.cols, eye.rows)/2;\n\n                        for (auto&& inlier : pupil_tracker_out.inliers) {\n                            inlier_pts.push_back(cv::Point2f(pupil_tracker_out.roiPupil.x + inlier.x - eye.cols/2, pupil_tracker_out.roiPupil.y + inlier.y - eye.rows/2));\n                        }\n                    } else {\n                        el = Ellipse2D<double>::Null;\n                    }\n\n                    std::ofstream ofs(cache_path.string());\n                    boost::archive::text_oarchive oa(ofs);\n\n                    oa << CACHE_VERSION;\n                    oa << el;\n                    oa << inlier_pts;\n                }\n\n                {\n                    tbb::mutex::scoped_lock push_guard(push_lock);\n\n                    if (el) {\n                        ids.push_back(id);\n                        obs_eye_images.push_back(eye);\n                        obs_pupil_ellipses.push_back(el);\n                        obs_pupil_inliers.push_back(std::move(inlier_pts));\n                    }\n                }\n            }\n        });\n\n        auto&& idx_sort = sort_indexes(ids);\n        reorder(ids, idx_sort);\n        reorder(obs_eye_images, idx_sort);\n        reorder(obs_pupil_ellipses, idx_sort);\n        reorder(obs_pupil_inliers, idx_sort);\n\n        double fov = parse_double(argv[3]);\n        fov *= PI / 180;\n        double focal_length = (obs_eye_images[0].cols / 2) / std::tan(fov/2);\n\n        bool animate = false;\n\n\n        // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n        // This is where the stuff actually happens\n        // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n        EyeModelFitter null_fitter(focal_length, 5, 0.5);\n        EyeModelFitter simple_fitter(focal_length, 5, 0.5);\n        EyeModelFitter contrast_fitter(focal_length, 5, 0.5);\n        EyeModelFitter edge_fitter(focal_length, 5, 0.5);\n\n        auto N = obs_eye_images.size();\n        if (argc > 5) {\n            int n = parse_int(argv[5]);\n            if (n >= 0 && n < N) {\n                N = n;\n            }\n        }\n\n        for (int i = 0; i < N; ++i) {\n            null_fitter.add_observation(obs_eye_images[i], obs_pupil_ellipses[i], obs_pupil_inliers[i]);\n            simple_fitter.add_observation(obs_eye_images[i], obs_pupil_ellipses[i], obs_pupil_inliers[i]);\n            contrast_fitter.add_observation(obs_eye_images[i], obs_pupil_ellipses[i], obs_pupil_inliers[i]);\n            edge_fitter.add_observation(obs_eye_images[i], obs_pupil_ellipses[i], obs_pupil_inliers[i]);\n        }\n\n        null_fitter.unproject_observations();\n\n        simple_fitter.unproject_observations();\n        simple_fitter.initialise_model();\n\n        contrast_fitter.unproject_observations();\n        contrast_fitter.initialise_model();\n\n        edge_fitter.unproject_observations();\n        edge_fitter.initialise_model();\n\n        Sphere<double> true_eye;\n        std::map<int, PupilGroundTruth> true_pupils;\n\n        if (argc > 4) {\n            using namespace boost::spirit;\n            using boost::phoenix::at_c;\n\n            std::ifstream ground_truth_file((imagedir / argv[4]).string());\n            if (ground_truth_file.is_open()) {\n                std::string str;\n                std::getline(ground_truth_file, str);\n                while(ground_truth_file.good()) {\n                    int id;\n                    PupilGroundTruth true_pupil;\n\n                    /* One day I will understand boost qi enough to do something like this:\n\n                    qi::rule<decltype(begin(str)), Eigen::Vector2d(), qi::ascii::space_type> vec2d =\n                        qi::eps[_val = Eigen::Vector2d()] >>\n                        qi::double_[at_c<0>(_val) = _1] >> ',' >>\n                        qi::double_[at_c<1>(_val) = _1];\n                    qi::rule<decltype(begin(str)), Eigen::Vector3d(), qi::ascii::space_type> vec3d =\n                        qi::eps[qi::_val = Eigen::Vector3d()] >>\n                        qi::double_[at_c<0>(_val) = _1] >> ',' >>\n                        qi::double_[at_c<1>(_val) = _1] >> ',' >>\n                        qi::double_[at_c<2>(_val) = _1];\n\n                    But it is not that day */\n\n                    std::vector<std::pair<double,double>> outlinepoints;\n\n                    int parse_success = qi::phrase_parse(begin(str), end(str),\n                        int_ >> '|' >>\n                        double_ >> ',' >> double_ >> ',' >> double_ >> '|' >>\n                        double_ >> '|' >>\n                        double_ >> ',' >> double_ >> ',' >> double_ >> '|' >>\n                        (double_ >> ',' >> double_) % ',',\n                        ascii::space,\n                        id,\n                        true_eye.centre[0],true_eye.centre[1],true_eye.centre[2],\n                        true_eye.radius,\n                        true_pupil.gaze_vector[0],true_pupil.gaze_vector[1],true_pupil.gaze_vector[2],\n                        outlinepoints\n                    );\n                    if (parse_success) {\n                        true_eye.centre[1] = -true_eye.centre[1];\n                        true_eye.centre[2] = -true_eye.centre[2];\n                        true_pupil.gaze_vector[1] = -true_pupil.gaze_vector[1];\n                        true_pupil.gaze_vector[2] = -true_pupil.gaze_vector[2];\n                        if (std::find(begin(ids), end(ids), id) != ids.end()) {\n                            for (const auto& p : outlinepoints) {\n                                true_pupil.outline.emplace_back(p.first, -p.second);\n                            }\n                            true_pupils[id] = true_pupil;\n                        }\n\n                    } else {\n                        std::cout << \"Failed to parse ground truth: \" << str << std::endl;\n                    }\n\n                    std::getline(ground_truth_file, str);\n                }\n            }\n        }\n\n\n        double displayscale = 1;\n        bool do_display = true;\n        int curr_i = 0;\n\n        namespace acc=boost::accumulators;\n        acc::accumulator_set<double, acc::stats<acc::tag::mean, acc::tag::variance>> acc_ellipdist, acc_ellipdist2, acc_ellipdist_dlib, acc_ellipdist_lm;\n        bool recalc_ellipdist = true;\n\n        bool display_obs_pupil_ellipses = true;\n        bool display_est_pupil_ellipses = true;\n        bool display_est_pupil_ellipses_contrast = true;\n        bool display_est_pupil_ellipses_lm = true;\n        bool display_true_pupil_ellipses = true;\n        bool display_intersection_ellip = false;\n        bool display_intersection_lines = false;\n\n        bool ransac = true;\n        bool use_smoothness = true;\n\n        auto animate_func =\n            [&] (const Sphere<double>& eye, const std::vector<Circle3D<double>>& pupils) {\n                cv::Mat curr = obs_eye_images[curr_i];\n                cv::Mat curr_disp = cvx::resize(cvx::cvtColor(cvx::convert(curr, CV_8U, 255),\n                                                              cv::COLOR_GRAY2BGR),\n                                                displayscale, 0, cv::INTER_CUBIC);\n\n                cv::ellipse(curr_disp, toImgCoord(toRotatedRect(project(eye, focal_length)), curr_disp, displayscale), cvx::rgb(60,0,0), 1, CV_AA);\n                for (const auto& pupil : pupils) {\n                    if (pupil)\n                        cv::ellipse(curr_disp, toImgCoord(toRotatedRect(Ellipse2D<double>(project(pupil, focal_length))), curr_disp, displayscale), cvx::rgb(60,60,0), 1, CV_AA);\n                }\n                if (curr_i < pupils.size() && pupils[curr_i]) {\n                    cv::ellipse(curr_disp, toImgCoord(toRotatedRect(Ellipse2D<double>(project(pupils[curr_i], focal_length))), curr_disp, displayscale), cvx::rgb(60,0,0), 1, CV_AA);\n                }\n                cv::imshow(\"Current Eye\", curr_disp);\n                cv::waitKey(10);\n            };\n\n        //cv::namedWindow(\"Eye\");\n        //cv::createButton(\"Display observed ellipses\", [](int state, void* userdata){*(bool*)userdata = state;}, &display_obs_pupil_ellipses, cv::QT_CHECKBOX, display_obs_pupil_ellipses);\n        //cv::createButton(\"Display initial pupil model\", [](int state, void* userdata){*(bool*)userdata = state;}, &display_est_pupil_ellipses, cv::QT_CHECKBOX, display_est_pupil_ellipses);\n        //cv::createButton(\"Display contrast-optimized pupils\", [](int state, void* userdata){*(bool*)userdata = state;}, &display_est_pupil_ellipses_contrast, cv::QT_CHECKBOX, display_est_pupil_ellipses_contrast);\n\n        cv::VideoWriter recording_writer;\n        while(do_display) {\n            cv::Mat disp = cv::Mat::zeros(displayscale*obs_eye_images[0].rows, displayscale*obs_eye_images[0].cols, CV_8UC3);\n\n\n            cv::Mat curr = obs_eye_images[curr_i];\n            cv::Mat curr_disp = cvx::resize(cvx::cvtColor(curr,\n                                                          cv::COLOR_GRAY2BGR),\n                                            displayscale, 0, cv::INTER_CUBIC);\n\n            cv::Mat curr_edge_disp = cv::Mat::zeros(curr_disp.rows, curr_disp.cols, CV_8UC3);\n\n            for (const auto& inlier : obs_pupil_inliers[curr_i]) {\n                int x = std::floor(curr_edge_disp.cols/2 + inlier.x * displayscale - 0.5);\n                int y = std::floor(curr_edge_disp.rows/2 + inlier.y * displayscale - 0.5);\n                if (x < 0 || x >= curr_edge_disp.cols || y < 0 || y >= curr_edge_disp.rows)\n                    continue;\n\n                curr_edge_disp.at<cv::Vec3b>(y,x) = cv::Vec3b::all(255);\n            }\n\n            if (display_true_pupil_ellipses) {\n                if (true_eye) {\n                    cv::ellipse(disp, toImgCoord(toRotatedRect(project(true_eye, focal_length)), disp, displayscale), cvx::rgb(60,60,60), -1, CV_AA);\n                }\n            }\n\n            if (display_est_pupil_ellipses) {\n                if (simple_fitter.eye) {\n                    cv::ellipse(disp, toImgCoord(toRotatedRect(project(simple_fitter.eye, focal_length)), disp, displayscale), cvx::rgb(60,0,60), 1, CV_AA);\n                    cv::ellipse(curr_disp, toImgCoord(toRotatedRect(project(simple_fitter.eye, focal_length)), curr_disp, displayscale), cvx::rgb(60,0,60), 1, CV_AA);\n                }\n            }\n            if (display_est_pupil_ellipses_contrast) {\n                if (contrast_fitter.eye) {\n                    cv::ellipse(disp, toImgCoord(toRotatedRect(project(contrast_fitter.eye, focal_length)), disp, displayscale), cvx::rgb(0,60,0), 1, CV_AA);\n                    cv::ellipse(curr_disp, toImgCoord(toRotatedRect(project(contrast_fitter.eye, focal_length)), curr_disp, displayscale), cvx::rgb(0,60,0), 1, CV_AA);\n                }\n            }\n            if (display_est_pupil_ellipses_lm) {\n                if (edge_fitter.eye) {\n                    cv::ellipse(disp, toImgCoord(toRotatedRect(project(edge_fitter.eye, focal_length)), disp, displayscale), cvx::rgb(0,60,60), 1, CV_AA);\n                    cv::ellipse(curr_disp, toImgCoord(toRotatedRect(project(edge_fitter.eye, focal_length)), curr_disp, displayscale), cvx::rgb(0,60,60), 1, CV_AA);\n                }\n            }\n            if (display_true_pupil_ellipses) {\n                if (true_eye) {\n                    cv::ellipse(curr_disp, toImgCoord(toRotatedRect(project(true_eye, focal_length)), curr_disp, displayscale), cvx::rgb(60,0,0), 1, CV_AA);\n                }\n            }\n\n            auto display_from = [&] (const std::vector<EyeModelFitter::Pupil>& pupils, double r, double g, double b) {\n                for (const auto& pupil : pupils) {\n                    if (pupil.circle)\n                        cv::ellipse(disp, toImgCoord(toRotatedRect(Ellipse2D<double>(project(pupil.circle, focal_length))), disp, displayscale), cvx::rgb(r,g,b), 1, CV_AA);\n                }\n                if (curr_i < pupils.size() && pupils[curr_i].circle) {\n                    cv::ellipse(curr_disp, toImgCoord(toRotatedRect(Ellipse2D<double>(project(pupils[curr_i].circle, focal_length))), curr_disp, displayscale), cvx::rgb(r,g,b), 1, CV_AA);\n                    cv::ellipse(curr_edge_disp, toImgCoord(toRotatedRect(Ellipse2D<double>(project(pupils[curr_i].circle, focal_length))), curr_edge_disp, displayscale), cvx::rgb(r,g,b), 1, CV_AA);\n                }\n            };\n\n            if (display_obs_pupil_ellipses) {\n                display_from(null_fitter.pupils, 255,0,255);\n            }\n            if (display_est_pupil_ellipses) {\n                display_from(simple_fitter.pupils, 255,255,0);\n            }\n            if (display_est_pupil_ellipses_contrast) {\n                display_from(contrast_fitter.pupils, 0,255,0);\n            }\n            if (display_est_pupil_ellipses_lm) {\n                display_from(edge_fitter.pupils, 0,255,255);\n            }\n            if (display_true_pupil_ellipses) {\n                std::vector<std::vector<cv::Point>> pts;\n                for (auto&& id : ids) {\n                    const auto& true_pupils_id_it = true_pupils.find(id);\n                    if (true_pupils_id_it != true_pupils.end()) {\n                        const auto& true_pupil = true_pupils_id_it->second;\n\n                        auto this_pts = fun::map([&](const Eigen::Vector2d& pt){\n                            auto imgcoord = toImgCoord(cv::Point2f(pt.x(), pt.y()), disp, displayscale, 5);\n                            return cv::Point(imgcoord.x, imgcoord.y);\n                        }, true_pupil.outline);\n                        pts.emplace_back(std::move(this_pts));\n                    }\n                }\n                cv::polylines(disp, pts, true, cvx::rgb(255,0,0), 1, CV_AA, 5);\n\n                const auto& true_pupils_curri_it = true_pupils.find(ids[curr_i]);\n                if (true_pupils_curri_it != true_pupils.end()) {\n                    const auto& true_pupil = true_pupils_curri_it->second;\n\n                    auto this_pts = fun::map([&](const Eigen::Vector2d& pt){\n                        auto imgcoord = toImgCoord(cv::Point2f(pt.x(), pt.y()), curr_disp, displayscale, 5);\n                        return cv::Point(imgcoord.x, imgcoord.y);\n                    }, true_pupil.outline);\n                    cv::polylines(curr_disp, this_pts, true, cvx::rgb(255,0,0), 1, CV_AA, 5);\n                    cv::polylines(curr_edge_disp, this_pts, true, cvx::rgb(255,0,0), 1, CV_AA, 5);\n                }\n            }\n\n            double anglediff_i, anglediff2_i, anglediff_dlib_i, anglediff_lm_i;\n            double ellipdist_i, ellipdist2_i, ellipdist_dlib_i, ellipdist_lm_i;\n\n            acc::accumulator_set<double, acc::stats<acc::tag::mean, acc::tag::variance>> acc_anglediff, acc_anglediff2, acc_anglediff_dlib, acc_anglediff_lm;\n            if (recalc_ellipdist) {\n                acc_ellipdist = acc::accumulator_set<double, acc::stats<acc::tag::mean, acc::tag::variance>>();\n                acc_ellipdist2 = acc::accumulator_set<double, acc::stats<acc::tag::mean, acc::tag::variance>>();\n                acc_ellipdist_dlib = acc::accumulator_set<double, acc::stats<acc::tag::mean, acc::tag::variance>>();\n                acc_ellipdist_lm = acc::accumulator_set<double, acc::stats<acc::tag::mean, acc::tag::variance>>();\n            }\n            for (int i = 0; i < N; ++i) {\n                const EyeModelFitter::Circle& pupil = null_fitter.pupils[i].circle;\n                const EyeModelFitter::Circle& pupil2 = simple_fitter.pupils[i].circle;\n                const EyeModelFitter::Circle& pupil_dlib = contrast_fitter.pupils[i].circle;\n                const EyeModelFitter::Circle& pupil_lm = edge_fitter.pupils[i].circle;\n                const auto& id = ids[i];\n                auto true_pupil_it = true_pupils.find(id);\n                if (true_pupil_it == true_pupils.end())\n                    continue;\n\n                const auto& true_pupil = true_pupil_it->second;\n\n                double anglediff = acos(pupil.normal.dot(true_pupil.gaze_vector))*180/PI;\n                double anglediff2 = acos(pupil2.normal.dot(true_pupil.gaze_vector))*180/PI;\n                double anglediff_dlib = acos(pupil_dlib.normal.dot(true_pupil.gaze_vector))*180/PI;\n                double anglediff_lm = acos(pupil_lm.normal.dot(true_pupil.gaze_vector))*180/PI;\n\n                if (i == curr_i) {\n                    anglediff_i = anglediff;\n                    anglediff2_i = anglediff2;\n                    anglediff_dlib_i = anglediff_dlib;\n                    anglediff_lm_i = anglediff_lm;\n                }\n\n                acc_anglediff(anglediff);\n                acc_anglediff2(anglediff2);\n                acc_anglediff_dlib(anglediff_dlib);\n                acc_anglediff_lm(anglediff_lm);\n\n                auto true_pupil_outline = true_pupil.outline;\n\n                if (recalc_ellipdist || i == curr_i) {\n                    double ellipdist = calcEllipseTruthOverlap(Ellipse2D<double>(project(pupil, focal_length)), true_pupil_outline);\n                    double ellipdist2 = calcEllipseTruthOverlap(Ellipse2D<double>(project(pupil2, focal_length)), true_pupil_outline);\n                    double ellipdist_dlib = calcEllipseTruthOverlap(Ellipse2D<double>(project(pupil_dlib, focal_length)), true_pupil_outline);\n                    double ellipdist_lm = calcEllipseTruthOverlap(Ellipse2D<double>(project(pupil_lm, focal_length)), true_pupil_outline);\n\n                    if (i == curr_i) {\n                        ellipdist_i = ellipdist;\n                        ellipdist2_i = ellipdist2;\n                        ellipdist_dlib_i = ellipdist_dlib;\n                        ellipdist_lm_i = ellipdist_lm;\n                    }\n                    if (recalc_ellipdist) {\n                        acc_ellipdist(ellipdist);\n                        acc_ellipdist2(ellipdist2);\n                        acc_ellipdist_dlib(ellipdist_dlib);\n                        acc_ellipdist_lm(ellipdist_lm);\n                    }\n                }\n            }\n            recalc_ellipdist = false;\n\n            std::stringstream curr_i_ss;\n            curr_i_ss << std::fixed << std::setprecision(4);\n            curr_i_ss << \"obs \" << anglediff_i << \", \";\n            curr_i_ss << \"est \" << anglediff2_i << \", \";\n            curr_i_ss << \"grd \" << anglediff_dlib_i << \", \";\n            curr_i_ss << \"lm \" << anglediff_lm_i << \" | \";\n            curr_i_ss << \"obs \" << ellipdist_i << \", \";\n            curr_i_ss << \"est \" << ellipdist2_i << \", \";\n            curr_i_ss << \"grd \" << ellipdist_dlib_i << \", \";\n            curr_i_ss << \"lm \" << ellipdist_lm_i << \" | \";\n            curr_i_ss << \"Frame \" << curr_i << \" (total \" << obs_eye_images.size() << \")\";\n\n            std::stringstream ss;\n            ss << std::fixed << std::setprecision(4);\n            ss << \"obs \" << acc::mean(acc_anglediff) << \" (\" << acc::variance(acc_anglediff) << \"), \";\n            ss << \"est \" << acc::mean(acc_anglediff2) << \" (\" << acc::variance(acc_anglediff2) << \"), \";\n            ss << \"grd \" << acc::mean(acc_anglediff_dlib) << \" (\" << acc::variance(acc_anglediff_dlib) << \"), \";\n            ss << \"lm \" << acc::mean(acc_anglediff_lm) << \" (\" << acc::variance(acc_anglediff_lm) << \") | \";\n            ss << \"obs \" << acc::mean(acc_ellipdist) << \" (\" << acc::variance(acc_ellipdist) << \"), \";\n            ss << \"est \" << acc::mean(acc_ellipdist2) << \" (\" << acc::variance(acc_ellipdist2) << \"), \";\n            ss << \"grd \" << acc::mean(acc_ellipdist_dlib) << \" (\" << acc::variance(acc_ellipdist_dlib) << \"), \";\n            ss << \"lm \" << acc::mean(acc_ellipdist_lm) << \" (\" << acc::variance(acc_ellipdist_lm) << \")\";\n\n\n            cv::imshow(\"Eye\", disp);\n            cv::imshow(\"Current Eye\", curr_disp);\n            cv::imshow(\"Current Eye Edges\", curr_edge_disp);\n\n            cv::displayStatusBar(\"Eye\", ss.str());\n            cv::displayStatusBar(\"Current Eye\", curr_i_ss.str());\n\n            if (recording_writer.isOpened()) {\n                recording_writer << curr_disp;\n            }\n\n            if (display_intersection_ellip || display_intersection_lines) {\n                cv::Mat disp_invalid_lines = cv::Mat::zeros(displayscale*obs_eye_images[0].rows, displayscale*obs_eye_images[0].cols, CV_32FC1);\n                cv::Mat disp_valid_lines = cv::Mat::zeros(displayscale*obs_eye_images[0].rows, displayscale*obs_eye_images[0].cols, CV_32FC1);\n                cv::Mat disp_ellipses = cv::Mat::zeros(displayscale*obs_eye_images[0].rows, displayscale*obs_eye_images[0].cols, CV_32FC1);\n                for (const auto& pupil : null_fitter.pupils) {\n                    Eigen::Matrix<double,2,1> c_proj = project(pupil.circle.centre, focal_length);\n                    Eigen::Matrix<double,2,1> v_proj = project(pupil.circle.centre+pupil.circle.normal, focal_length) - c_proj;\n                    Eigen::Matrix<double,2,1> start = c_proj - 500*v_proj;\n                    Eigen::Matrix<double,2,1> end = c_proj + 500*v_proj;\n\n                    if (display_intersection_lines) {\n\n                        cv::Mat disp_line = cv::Mat::zeros(displayscale*obs_eye_images[0].rows, displayscale*obs_eye_images[0].cols, CV_8UC1);\n                        cvx::line(disp_line,\n                            cv::Point2f(disp_line.cols/2 + displayscale*start[0], disp_line.rows/2 + displayscale*start[1]),\n                            cv::Point2f(disp_line.cols/2 + displayscale*end[0], disp_line.rows/2 + displayscale*end[1]),\n                            cv::Scalar(25));\n\n                        cv::Mat disp_line_f = cvx::convert(disp_line, CV_32FC1, 1./255, 0);\n\n                        if (pupil.init_valid)\n                            cv::accumulate((disp_line_f).mul(1 - disp_valid_lines), disp_valid_lines);\n                        else\n                            cv::accumulate((disp_line_f).mul(1 - disp_invalid_lines), disp_invalid_lines);\n                    }\n\n                    if (display_intersection_ellip) {\n                        cv::Mat disp_ellipse = cv::Mat::zeros(displayscale*obs_eye_images[0].rows, displayscale*obs_eye_images[0].cols, CV_8UC1);\n                        cv::ellipse(disp_ellipse, toImgCoord(toRotatedRect(Ellipse2D<double>(project(pupil.circle, focal_length))), disp, displayscale), cv::Scalar(50), 1, CV_AA);\n\n                        cv::Mat disp_ellipse_f = cvx::convert(disp_ellipse, CV_32FC1, 1./255, 0);\n                        cv::accumulate((disp_ellipse_f).mul(1 - disp_ellipses), disp_ellipses);\n                    }\n                }\n\n                cv::Mat disp_intersection = cv::Mat(displayscale*obs_eye_images[0].rows, displayscale*obs_eye_images[0].cols, CV_32FC3, cvx::rgb(1,1,1));\n                cv::accumulate(cvx::cvtColor(disp_invalid_lines, cv::COLOR_GRAY2BGR).mul(cvx::rgb(1,0,0) - disp_intersection), disp_intersection);\n                cv::accumulate(cvx::cvtColor(disp_valid_lines, cv::COLOR_GRAY2BGR).mul(cvx::rgb(0,0,1) - disp_intersection), disp_intersection);\n                cv::accumulate(cvx::cvtColor(disp_ellipses, cv::COLOR_GRAY2BGR).mul(cvx::rgb(1,0,1) - disp_intersection), disp_intersection);\n\n                if (display_intersection_lines) {\n                    auto crosspt = toImgCoord(toPoint2f(project(simple_fitter.eye.centre, focal_length)), disp, displayscale);\n                    for (int i = -1; i <= 1; ++i)\n                        for (int j = -1; j <= 1; ++j)\n                            cvx::cross(disp_intersection, crosspt + cv::Point2f(i,j), 10, cvx::rgb(0,0,0), 3);\n                    cvx::cross(disp_intersection, crosspt, 10, cvx::rgb(0,200,0), 3);\n                }\n\n                cv::imshow(\"Intersection\", disp_intersection);\n            }\n\n            Key key = cvxWaitKey(-1);\n\n            switch(key.code) {\n            case 16: // Shift\n                break;\n\n            case '1':\n                display_obs_pupil_ellipses = !display_obs_pupil_ellipses;\n                break;\n            case '2':\n                display_est_pupil_ellipses = !display_est_pupil_ellipses;\n                break;\n            case '3':\n                display_est_pupil_ellipses_contrast = !display_est_pupil_ellipses_contrast;\n                break;\n            case '4':\n                display_est_pupil_ellipses_lm = !display_est_pupil_ellipses_lm;\n                break;\n            case '5':\n                display_true_pupil_ellipses = !display_true_pupil_ellipses;\n                break;\n\n            case 27: // ESC\n            case'q':\n                do_display = false;\n                break;\n            case 'w':\n                writeResults((imagedir / \"result_analysis.txt\").string(),\n                    ids,\n                    null_fitter.pupils,\n                    simple_fitter.pupils,\n                    contrast_fitter.pupils,\n                    edge_fitter.pupils,\n                    true_pupils,\n                    focal_length);\n                break;\n\n            case '+':\n            case '=':\n                displayscale *= 1.1;\n                break;\n            case '-':\n            case '_':\n                displayscale /= 1.1;\n                break;\n            case 'i':\n                display_intersection_ellip = !display_intersection_ellip;\n                break;\n            case 'o':\n                display_intersection_lines = !display_intersection_lines;\n                break;\n\n            case 'a': {\n                if (key.shift) {\n\n                    animate = !animate;\n                    if (animate) {\n                        std::cout << \"Animation enabled\" << std::endl;\n                    } else {\n                        std::cout << \"Animation disabled\" << std::endl;\n                    }\n\n                } else {\n                    int id;\n                    if (N < obs_eye_images.size() - 1) {\n                        id = null_fitter.add_observation(obs_eye_images[N], obs_pupil_ellipses[N], obs_pupil_inliers[N]);\n                        null_fitter.unproject_single_observation(id);\n\n                        id = simple_fitter.add_observation(obs_eye_images[N], obs_pupil_ellipses[N], obs_pupil_inliers[N]);\n                        simple_fitter.unproject_single_observation(id);\n                        simple_fitter.initialise_single_observation(id);\n\n                        id = contrast_fitter.add_observation(obs_eye_images[N], obs_pupil_ellipses[N], obs_pupil_inliers[N]);\n                        contrast_fitter.unproject_single_observation(id);\n                        contrast_fitter.initialise_single_observation(id);\n                        contrast_fitter.refine_single_with_contrast(id);\n\n                        id = edge_fitter.add_observation(obs_eye_images[N], obs_pupil_ellipses[N], obs_pupil_inliers[N]);\n                        edge_fitter.unproject_single_observation(id);\n                        edge_fitter.initialise_single_observation(id);\n                        //edge_fitter.refine_single_with_inliers(id);\n\n                        curr_i = N;\n                        N++;\n                    }\n                }\n                break;\n            }\n\n            case 's':\n                if (key.shift) {\n                    for (int i = 0; i < N; ++i) {\n                        std::cout << i << std::endl;\n                        contrast_fitter.refine_single_with_contrast(i);\n                    }\n                    std::cout << \"Done\" << std::endl;\n                }\n                else {\n                    use_smoothness = !use_smoothness;\n                    if (use_smoothness) {\n                        std::cout << \"Smoothness enabled\" << std::endl;\n                    } else {\n                        std::cout << \"Smoothness disabled\" << std::endl;\n                    }\n                }\n\n                break;\n\n            case 'd':\n                if (key.shift) {\n                    contrast_fitter.refine_single_with_contrast(curr_i);\n                    contrast_fitter.print_single_contrast_metric(curr_i);\n                }\n                else {\n                    if (animate)\n                        contrast_fitter.refine_with_region_contrast(animate_func);\n                    else\n                        contrast_fitter.refine_with_region_contrast();\n                    std::cout << \"Done\" << std::endl;\n                }\n                recalc_ellipdist = true;\n                display_est_pupil_ellipses_contrast = true;\n\n                break;\n\n            case 'g':\n                if (key.shift)\n                {\n                    std::string out_file = (imagedir / \"contrast_sweep.txt\").string();\n                    std::ofstream out_stream(out_file);\n\n                    auto start_params = contrast_fitter.pupils[curr_i].params;\n\n                    for (auto&& theta : fun::linspace(0.0, PI, 100)) {\n                        for (auto&& psi : fun::linspace(0.0, 2*PI, 100)) {\n                            for (auto&& radius : fun::range_<std::vector<double>>(1, 10, 0.1)) {\n                                EyeModelFitter::PupilParams params(theta, psi, radius);\n                                contrast_fitter.pupils[curr_i].params = params;\n                                std::cout << theta << \" \" << psi << \" \" << radius;\n                                auto val = contrast_fitter.single_contrast_metric(curr_i);\n                                std::cout << \" -> \" << val;\n\n                                out_stream << theta << \" \" << psi << \" \" << radius << \" \" << val;\n                            }\n                        }\n                    }\n\n                    contrast_fitter.pupils[curr_i].params = start_params;\n\n                }\n                else\n                {\n                    auto start_params = contrast_fitter.pupils[curr_i].params;\n\n                    auto best_params = start_params;\n                    double best_contrast = contrast_fitter.single_contrast_metric(curr_i);\n\n                    for (auto&& theta : fun::linspace(start_params.theta - 0.1, start_params.theta + 0.1, 6)) {\n                        for (auto&& psi : fun::linspace(start_params.psi - 0.1, start_params.psi + 0.1, 6)) {\n                            for (auto&& radius : fun::linspace(start_params.radius / 1.5, start_params.radius * 1.5, 6)) {\n                                EyeModelFitter::PupilParams params(theta, psi, radius);\n                                contrast_fitter.pupils[curr_i].params = params;\n                                std::cout << theta-start_params.theta << \" \" << psi-start_params.psi << \" \" << radius-start_params.radius;\n                                contrast_fitter.refine_single_with_contrast(curr_i);\n                                auto val = contrast_fitter.single_contrast_metric(curr_i);\n                                std::cout << \" -> \" << val;\n                                if (best_contrast >= val)\n                                {\n                                    best_params = contrast_fitter.pupils[curr_i].params;\n                                    best_contrast = val;\n                                    std::cout << \" *\";\n                                }\n                                std::cout << std::endl;\n                            }\n                        }\n                    }\n\n                    contrast_fitter.pupils[curr_i].params = best_params;\n                    contrast_fitter.pupils[curr_i].circle = contrast_fitter.circleFromParams(best_params);\n\n                    recalc_ellipdist = true;\n                    display_est_pupil_ellipses_contrast = true;\n                }\n\n                break;\n\n            case '[':\n                contrast_fitter.region_band_width--;\n                std::cout << \"Band width = \" << contrast_fitter.region_band_width << std::endl;\n                break;\n\n            case ']':\n                contrast_fitter.region_band_width++;\n                std::cout << \"Band width = \" << contrast_fitter.region_band_width << std::endl;\n                break;\n\n            case ',':\n                contrast_fitter.region_scale/=1.125;\n                std::cout << \"Region scale = \" << contrast_fitter.region_scale << std::endl;\n                break;\n\n            case '.':\n                contrast_fitter.region_scale*=1.125;\n                std::cout << \"Region scale = \" << contrast_fitter.region_scale << std::endl;\n                break;\n\n            case 'n':\n                null_fitter.unproject_observations(1, 20, ransac);\n\n                simple_fitter.unproject_observations(1, 20, ransac);\n                simple_fitter.initialise_model();\n\n                contrast_fitter.unproject_observations(1, 20, ransac);\n                contrast_fitter.initialise_model();\n\n                edge_fitter.unproject_observations(1, 20, ransac);\n                edge_fitter.initialise_model();\n\n                std::cout << \"Model reset\" << std::endl;\n\n                break;\n\n\n            case 'h':\n                if (key.shift) {\n                    contrast_fitter.pupils[curr_i].params.psi -= 0.01;\n                    contrast_fitter.pupils[curr_i].circle = contrast_fitter.circleFromParams(contrast_fitter.pupils[curr_i].params);\n                    std::cout << contrast_fitter.pupils[curr_i].params.theta << \",\" << contrast_fitter.pupils[curr_i].params.psi << \",\" <<  contrast_fitter.pupils[curr_i].params.radius << std::endl;\n                    contrast_fitter.print_single_contrast_metric(curr_i);\n                } else {\n                    curr_i = curr_i == 0 ? obs_eye_images.size() - 1 : curr_i - 1;\n                }\n                break;\n            case 'j':\n                if (key.shift) {\n                    contrast_fitter.pupils[curr_i].params.theta -= 0.01;\n                    contrast_fitter.pupils[curr_i].circle = contrast_fitter.circleFromParams(contrast_fitter.pupils[curr_i].params);\n                    std::cout << contrast_fitter.pupils[curr_i].params.theta << \",\" << contrast_fitter.pupils[curr_i].params.psi << \",\" <<  contrast_fitter.pupils[curr_i].params.radius << std::endl;\n                    contrast_fitter.print_single_contrast_metric(curr_i);\n                }\n                break;\n            case 'k':\n                if (key.shift) {\n                    contrast_fitter.pupils[curr_i].params.theta += 0.01;\n                    contrast_fitter.pupils[curr_i].circle = contrast_fitter.circleFromParams(contrast_fitter.pupils[curr_i].params);\n                    std::cout << contrast_fitter.pupils[curr_i].params.theta << \",\" << contrast_fitter.pupils[curr_i].params.psi << \",\" <<  contrast_fitter.pupils[curr_i].params.radius << std::endl;\n                    contrast_fitter.print_single_contrast_metric(curr_i);\n                }\n                break;\n            case 'l':\n                if (key.shift) {\n                    contrast_fitter.pupils[curr_i].params.psi += 0.01;\n                    contrast_fitter.pupils[curr_i].circle = contrast_fitter.circleFromParams(contrast_fitter.pupils[curr_i].params);\n                    std::cout << contrast_fitter.pupils[curr_i].params.theta << \",\" << contrast_fitter.pupils[curr_i].params.psi << \",\" <<  contrast_fitter.pupils[curr_i].params.radius << std::endl;\n                    contrast_fitter.print_single_contrast_metric(curr_i);\n                } else {\n                    curr_i = (curr_i + 1) % obs_eye_images.size();\n                }\n                break;\n            case ';':\n                if (key.shift) {\n                    contrast_fitter.pupils[curr_i].params.radius /= 1.1;\n                    contrast_fitter.pupils[curr_i].circle = contrast_fitter.circleFromParams(contrast_fitter.pupils[curr_i].params);\n                    std::cout << contrast_fitter.pupils[curr_i].params.theta << \",\" << contrast_fitter.pupils[curr_i].params.psi << \",\" <<  contrast_fitter.pupils[curr_i].params.radius << std::endl;\n                    contrast_fitter.print_single_contrast_metric(curr_i);\n                }\n                break;\n            case '\\'':\n                if (key.shift) {\n                    contrast_fitter.pupils[curr_i].params.radius *= 1.1;\n                    contrast_fitter.pupils[curr_i].circle = contrast_fitter.circleFromParams(contrast_fitter.pupils[curr_i].params);\n                    std::cout << contrast_fitter.pupils[curr_i].params.theta << \",\" << contrast_fitter.pupils[curr_i].params.psi << \",\" <<  contrast_fitter.pupils[curr_i].params.radius << std::endl;\n                    contrast_fitter.print_single_contrast_metric(curr_i);\n                }\n                break;\n\n            case 'e':\n                if (animate)\n                    edge_fitter.refine_with_inliers(animate_func);\n                else\n                    edge_fitter.refine_with_inliers();\n                recalc_ellipdist = true;\n                display_est_pupil_ellipses_lm = true;\n\n                break;\n\n            case 'r':\n                if (key.shift) {\n                    if (!recording_writer.isOpened()) {\n                        int fourcc = CV_FOURCC('M','J','P','G');\n                        std::cout << \"Start recording\" << std::endl;\n                        std::string out_file = (imagedir / \"video.avi\").string();\n                        int done = recording_writer.open(\n                            out_file,\n                            fourcc,\n                            25,\n                            curr_disp.size());\n                        if (!done) {\n                            std::cerr << \"Start failed!\" << std::endl;\n                        }\n                    } else {\n                        std::cout << \"Stop recording\" << std::endl;\n                        recording_writer.release();\n                    }\n                } else {\n                    ransac = !ransac;\n                    if (ransac) {\n                        std::cout << \"RANSAC enabled\" << std::endl;\n                    } else {\n                        std::cout << \"RANSAC disabled\" << std::endl;\n                    }\n                }\n                break;\n            case 'p':\n                std::cout << curr_i << std::endl;\n                std::cout << contrast_fitter.pupils[curr_i].params.theta << \",\" << contrast_fitter.pupils[curr_i].params.psi << \",\" <<  contrast_fitter.pupils[curr_i].params.radius << std::endl;\n                contrast_fitter.print_single_contrast_metric(curr_i);\n                if (curr_i < N) {\n                    /*std::cout << EllipseGoodnessFunction<double>()(\n                        contrast_fitter.eye,\n                        contrast_fitter.pupils[curr_i].params.theta, contrast_fitter.pupils[curr_i].params.psi, contrast_fitter.pupils[curr_i].params.radius,\n                        contrast_fitter.focal_length,\n                        contrast_fitter.pupils[curr_i].observation.image) << std::endl;\n\n                    std::cout << exp(-sq(contrast_fitter.pupils[curr_i].params.radius - 2.5)/sq(1.0)) << std::endl;\n\n                    if (curr_i > 0) {\n                        std::cout << angleDiffGoodness(\n                            contrast_fitter.pupils[curr_i-1].params.theta, contrast_fitter.pupils[curr_i-1].params.psi,\n                            contrast_fitter.pupils[curr_i].params.theta, contrast_fitter.pupils[curr_i].params.psi,\n                            1) << std::endl;\n\n                        std::cout << exp(-sq(contrast_fitter.pupils[curr_i].params.radius-contrast_fitter.pupils[curr_i-1].params.radius)/sq(1.0)) << std::endl;\n                    }*/\n                }\n                break;\n\n            default:\n                std::cout << \"Unknown key code: \" << (int)key.code << \" (ascii \" << std::string(1, key.code) << \")\" << std::endl;\n                break;\n            }\n        }\n    }\n\n    //catch (std::exception& e) {\n    //    std::cerr << e.what() << std::endl;\n    //    while (cv::waitKey(10) == -1) {}\n    //    return 1;\n    //}\n\n    return 0;\n}\n\n", "meta": {"hexsha": "2e242c21cee09063330d43d4f66ea52b9a1c5647", "size": 53884, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmd/SingleEyeFitterCmd.cpp", "max_stars_repo_name": "LeszekSwirski/singleeyefitter", "max_stars_repo_head_hexsha": "024513df0952c6011207070b83c8ee479654c53d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2015-01-28T18:51:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T09:01:39.000Z", "max_issues_repo_path": "cmd/SingleEyeFitterCmd.cpp", "max_issues_repo_name": "LeszekSwirski/singleeyefitter", "max_issues_repo_head_hexsha": "024513df0952c6011207070b83c8ee479654c53d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-06-22T14:24:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-02T15:34:56.000Z", "max_forks_repo_path": "cmd/SingleEyeFitterCmd.cpp", "max_forks_repo_name": "LeszekSwirski/singleeyefitter", "max_forks_repo_head_hexsha": "024513df0952c6011207070b83c8ee479654c53d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2017-05-24T08:45:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T14:51:02.000Z", "avg_line_length": 45.5871404399, "max_line_length": 214, "alphanum_fraction": 0.5355949818, "num_tokens": 12698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175005616829, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.27818444563008443}}
{"text": "/* -*- c++ -*- */\n/*\n * Copyright 2015 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/fec/ldpc_decoder.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#include <gnuradio/fec/decoder.h>\n#include <algorithm>            // for std::reverse\n#include <string.h>             // for memcpy\n#include <gnuradio/fec/maxstar.h>\n\n\nnamespace gr {\n namespace fec {\n\n   generic_decoder::sptr\n   ldpc_decoder::make(std::string alist_file, float sigma,\n                      int max_iterations)\n   {\n     return generic_decoder::sptr\n       (new ldpc_decoder(alist_file, sigma, max_iterations));\n   }\n\n   ldpc_decoder::ldpc_decoder(std::string alist_file, float sigma,\n                              int max_iterations)\n     : generic_decoder(\"ldpc_decoder\")\n   {\n     if(!boost::filesystem::exists( alist_file ))\n       throw std::runtime_error(\"Bad AList file name!\");\n\n     d_list.read(alist_file.c_str());\n     d_code.set_alist(d_list);\n     d_spa.set_alist_sigma(d_list, sigma);\n\n     d_rate = static_cast<double>(d_code.dimension())/static_cast<double>(d_code.get_N());\n     set_frame_size(d_code.dimension());\n\n     d_spa.set_K(d_output_size);\n     d_spa.set_max_iterations(max_iterations);\n   }\n\n   int\n   ldpc_decoder::get_output_size()\n   {\n     return d_output_size;\n   }\n\n   int\n   ldpc_decoder::get_input_size()\n   {\n     return d_input_size;\n   }\n\n   double\n   ldpc_decoder::rate()\n   {\n     return d_rate;\n   }\n\n   bool\n   ldpc_decoder::set_frame_size(unsigned int frame_size)\n   {\n     if(frame_size % d_code.dimension() != 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_code.dimension()));\n       throw std::runtime_error(\"ldpc_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   void\n   ldpc_decoder::generic_work(void *inBuffer, void *outBuffer)\n   {\n     const float *in = (const float *) inBuffer;\n     unsigned char *out = (unsigned char *) outBuffer;\n\n     int j = 0;\n     std::vector<float> rx(d_code.get_N());\n     for(int i = 0; i < d_input_size; i+=d_code.get_N()) {\n       for(int k = 0; k < d_code.get_N(); k++) {\n         rx[k] = in[i+k] * (-1);\n       }\n\n       int n_iterations = 0;\n       std::vector<char> estimate( d_spa.decode(rx, &n_iterations) );\n       std::vector<char> data( d_code.get_systematic_bits(estimate) );\n       memcpy(&out[j], &data[0], d_code.dimension());\n       d_iterations = n_iterations;\n\n       j += d_code.dimension();\n     }\n   }\n\n   int\n   ldpc_decoder::get_input_item_size()\n   {\n     return sizeof(INPUT_DATATYPE);\n   }\n\n   int\n   ldpc_decoder::get_output_item_size()\n   {\n     return sizeof(OUTPUT_DATATYPE);\n   }\n\n   int\n   ldpc_decoder::get_history()\n   {\n     return 0;\n   }\n\n   float\n   ldpc_decoder::get_shift()\n   {\n     return 0.0;\n   }\n\n   const char*\n   ldpc_decoder::get_conversion()\n   {\n     return \"none\";\n   }\n\n   ldpc_decoder::~ldpc_decoder()\n   {\n   }\n\n } // namespace gr\n} // namespace fec\n", "meta": {"hexsha": "55eeac629124e0e1e0212156c316775ed1181894", "size": 4048, "ext": "cc", "lang": "C++", "max_stars_repo_path": "gnuradio-3.7.13.4/gr-fec/lib/ldpc_decoder.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_decoder.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_decoder.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": 25.4591194969, "max_line_length": 90, "alphanum_fraction": 0.6264822134, "num_tokens": 1015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175005616829, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2781844456300844}}
{"text": "/*******************************************************************************\n*\n*  Filename    : KeysCompMgr.cc\n*  Description : Definition of how objects are stored and data is loaded\n*  Author      : Yi-Mu \"Enoch\" Chen [ ensc@hep1.phys.ntu.edu.tw ]\n*\n*******************************************************************************/\n#include \"TstarAnalysis/MassRecoCompare/interface/KeysCompMgr.hpp\"\n\n#include \"TstarAnalysis/Common/interface/GetEventWeight.hpp\"\n#include \"TstarAnalysis/MassRecoCompare/interface/Common.hpp\"\n\n#include \"RooAddPdf.h\"\n#include \"RooBifurGauss.h\"\n#include \"RooConstVar.h\"\n#include \"RooDataSet.h\"\n#include \"RooFFTConvPdf.h\"\n#include \"RooGaussian.h\"\n#include \"RooKeysPdf.h\"\n#include \"RooRealVar.h\"\n#include \"TFile.h\"\n\n#include <boost/format.hpp>\n#include <iostream>\n\nusing namespace std;\nusing namespace mgr;\n\n/*******************************************************************************\n*   Declaring global RooRealVars\n*******************************************************************************/\nvoid\nKeysCompMgr::InitStaticVars()\n{\n  StaticNewVar( \"x\", \"m_{t+jet}\", \"GeV/c^{2}\", 400, 2500 );\n  StaticNewVar( \"w\", \"w\",         \"\",        -1000, 1000 );\n  StaticNewVar( \"n\", \"n\",         \"\",           -1,    7 );\n}\n\n/******************************************************************************/\n\nRooRealVar&\nKeysCompMgr::x(){ return *StaticVar( \"x\" ); }\n\n/******************************************************************************/\n\nRooRealVar&\nKeysCompMgr::w(){ return *StaticVar( \"w\" ); }\n\n/******************************************************************************/\n\nRooRealVar&\nKeysCompMgr::n(){ return *StaticVar( \"n\" );}\n\n/*******************************************************************************\n*   Constructor and data set definition\n*******************************************************************************/\nKeysCompMgr::KeysCompMgr( const std::string& name, const std::string& latexname ) :\n  Named( name ),\n  RooFitMgr( name )\n{\n  SetLatexName( latexname );\n  RooDataSet* set = new RooDataSet(\n    \"\",\n    \"\",\n    RooArgSet( x(), n(), w() ),\n    RooFit::WeightVar( w() )\n    );\n  AddDataSet( set );\n}\n\n\n/******************************************************************************/\n\nKeysCompMgr::~KeysCompMgr()\n{\n  for( const auto& name : VarNameList() ){\n    RooRealVar* var = Var( name );\n    cout << boost::format( \"%-50s %8.4lf %8.4f %8.4f\" )\n      % var->GetName()\n      % var->getVal()\n      % var->getErrorHi()\n      % var->getErrorLo()\n         << endl;\n  }\n\n  for( const auto& name : FuncNameList() ){\n    RooAbsReal* func = Func( name );\n    cout << boost::format( \"%50s %8.1lf\" )\n    % func->GetName()\n    %func->getVal()\n    << endl;\n  }\n}\n\n/*******************************************************************************\n*   Filling by event looping\n*******************************************************************************/\nvoid\nKeysCompMgr::FillDataSet( const std::string& filename )\n{\n  fwlite::Event evt( TFile::Open( filename.c_str() ) );\n  fwlite::Handle<RecoResult> resulthandle;\n\n  for( evt.toBegin(); !evt.atEnd(); ++evt ){\n    resulthandle.getByLabel( evt, Name().c_str(), LabelName( Name() ).c_str(), ProcessName().c_str() );\n\n    const double evtweight = GetEventWeight( evt );\n    const double tstarmass = resulthandle.ref().TstarMass();\n\n    if( tstarmass > x().getMax() ){ continue; }\n    if( tstarmass < x().getMin() ){ continue; }\n    if( evtweight > w().getMax() ){ continue; }\n    if( evtweight < w().getMin() ){ continue; }\n    x() = tstarmass;\n    n() = (double)NumCorrectAssign( resulthandle.ref() );\n    DataSet( \"\" )->add( RooArgSet( x(), n() ), evtweight );\n  }\n\n  cout << \"Done!\" << endl;\n}\n\n\n/******************************************************************************/\n\nvoid\nKeysCompMgr::MakeKeysPdf()\n{\n  RooDataSet& dataset = *( dynamic_cast<RooDataSet*>( DataSet( \"\" ) ) );\n\n  double na = dataset.sigma( x() );\n  double n2 = dataset.sigma( x(), \"n>=3\"  );\n  double n3 = dataset.sigma( x(), \"n>=4\"  );\n  double n4 = dataset.sigma( x(), \"n>=5\"  );\n\n  static const vector<double> rholist = {\n    1.364,\n    1.166,\n    1.660\n  };\n  cout << \"Computed Value: \"\n       << sqrt( na/n2 ) << \" \"\n       << sqrt( na/n3 ) << \" \"\n       << sqrt( na/n4 ) << \" \"\n       << na << endl;\n\n  RooKeysPdf* pdf;\n\n  boost::format nameformat( \"rho%.2lf\" );\n  boost::format titleformat( \"#rho = %.2lf\" );\n\n  for( const auto rho : rholist ){\n    const string name  = str( nameformat % rho );\n    const string title = str( titleformat % rho );\n    pdf = new RooKeysPdf(\n      name.c_str(),\n      title.c_str(),\n      x(),\n      dataset,\n      RooKeysPdf::NoMirror,\n      rho\n      );\n    AddPdf( pdf );\n  }\n}\n\n/******************************************************************************/\n\nvoid\nKeysCompMgr::MakeGauss()\n{\n  RooRealVar* m  = NewVar( \"m\", reconamer.GetInput<int>( \"mass\" ), 400, 3000 );\n  RooRealVar* s  = NewVar( \"s\", 200, 0, 1000 );\n  RooAbsPdf* pdf = new RooGaussian( \"gauss\", \"\", x(), *m, *s );\n  AddPdf( pdf );\n  pdf->fitTo(\n    *DataSet( \"\" ),\n    RooFit::Minimizer( \"Minuit\", \"Migrad\" ),\n    RooFit::Minos( kTRUE ),\n    RooFit::SumW2Error( kTRUE ),\n    RooFit::Verbose( kFALSE ),\n    RooFit::PrintLevel( -1 ),\n    RooFit::PrintEvalErrors( -1 ),\n    RooFit::Warnings( kFALSE )\n    );\n\n  RooRealVar* m1         = NewVar( \"m1\", reconamer.GetInput<int>( \"mass\" ), 400, 3000 );\n  RooRealVar* m2         = NewVar( \"m2\", reconamer.GetInput<int>( \"mass\" )+200, 400, 3000 );\n  RooRealVar* s1         = NewVar( \"s1\", 200, 0, 1000 );\n  RooRealVar* s2         = NewVar( \"s2\", 200, 0, 1000 );\n  RooRealVar* frac       = NewVar( \"frac\", 0.5, 0, 1 );\n  RooAbsPdf* gauss1      = new RooGaussian( \"guass2_1\", \"\", x(), *m1, *s1 );\n  RooAbsPdf* gauss2      = new RooGaussian( \"guass2_2\", \"\", x(), *m2, *s2 );\n  RooAbsPdf* doublegauss = new RooAddPdf( \"doublegauss\", \"\", *gauss1, *gauss2, *frac );\n  AddPdf( doublegauss );\n  doublegauss->fitTo(\n    *DataSet( \"\" ),\n    RooFit::Minimizer( \"Minuit\", \"Migrad\" ),\n    RooFit::Minos( kTRUE ),\n    RooFit::SumW2Error( kTRUE ),\n    RooFit::Verbose( kFALSE ),\n    RooFit::PrintLevel( -1 ),\n    RooFit::PrintEvalErrors( -1 ),\n    RooFit::Warnings( kFALSE )\n    );\n\n}\n\nvoid\nKeysCompMgr::MakeConv()\n{\n  // Single bifurcation\n  RooRealVar* bimean = NewVar( \"bimean\", 1200, 700, 2000 );\n  RooRealVar* bil    = NewVar( \"bil\", 200, 0, 1000 );\n  RooRealVar* bir    = NewVar( \"bir\", 300, 0, 1000 );\n  RooAbsPdf* bipdf   = new RooBifurGauss( \"bigauss\", \"\", x(), *bimean, *bil, *bir );\n\n  RooConstVar* gmean = new RooConstVar( \"convgmean\", \"\", 0 );\n  RooRealVar* gsig   = NewVar( \"convgsig\", 100, 0, 1000 );\n  RooAbsPdf* gpdf    = new RooGaussian( \"convgauss\", \"\", x(), *gmean, *gsig );\n\n  RooAbsPdf* convpdf = new RooFFTConvPdf( \"conv\", \"conv\", x(), *bipdf, *gpdf );\n\n  convpdf->fitTo(// Forcing fit, and setting to constant\n    *DataSet( \"\" ),\n    RooFit::Minimizer( \"Minuit\", \"Migrad\" ),\n    RooFit::Minos( kTRUE ),\n    RooFit::SumW2Error( kTRUE ),\n    RooFit::Verbose( kFALSE ),\n    RooFit::PrintLevel( -1 ),\n    RooFit::PrintEvalErrors( -1 ),\n    RooFit::Warnings( kFALSE )\n    );\n  AddPdf( bipdf );\n  AddPdf( gpdf );\n  AddPdf( convpdf );\n  AddFunc( gmean );\n\n  // Double bifurcation\n  RooRealVar* bimean1 = NewVar( \"bimean1\", 1000, 400, 2000 );\n  RooRealVar* bil1    = NewVar( \"bil1\", 200, 0, 1000 );\n  RooRealVar* bir1    = NewVar( \"bir1\", 300, 0, 1000 );\n  RooAbsPdf* bipdf1   = new RooBifurGauss( \"bigauss1\", \"\", x(), *bimean1, *bil1, *bir1 );\n\n  RooConstVar* gmean1 = new RooConstVar( \"convgmean1\", \"\", 0 );\n  RooRealVar* gsig1   = NewVar( \"convgsig1\", 100, 0, 1000 );\n  RooAbsPdf* gpdf1    = new RooGaussian( \"convgauss1\", \"\", x(), *gmean1, *gsig1 );\n\n  RooAbsPdf* conv1pdf = new RooFFTConvPdf( \"conv1\", \"\", x(), *bipdf1, *gpdf1 );\n\n  RooRealVar* bimean2 = NewVar( \"bimean2\", 1600, 400, 2000 );\n  RooRealVar* bil2    = NewVar( \"bil2\", 100, 0, 1000 );\n  RooRealVar* bir2    = NewVar( \"bir2\", 200, 0, 1000 );\n  RooAbsPdf* bipdf2   = new RooBifurGauss( \"bigauss2\", \"\", x(), *bimean2, *bil2, *bir2 );\n\n  RooConstVar* gmean2 = new RooConstVar( \"convgmean2\", \"\", 0 );\n  RooRealVar* gsig2   = NewVar( \"convgsig2\", 100, 0, 1000 );\n  RooAbsPdf* gpdf2    = new RooGaussian( \"convgauss2\", \"\", x(), *gmean2, *gsig2 );\n\n  RooAbsPdf* conv2pdf = new RooFFTConvPdf( \"conv2\", \"\", x(), *bipdf2, *gpdf2 );\n\n  RooRealVar* bico = NewVar( \"bicoeff2\", 0.6, 0, 1 );\n\n  RooAbsPdf* bisum = new RooAddPdf( \"convsum2\", \"\", *conv1pdf, *conv2pdf, *bico );\n\n  bisum->fitTo(// Forcing fit, and setting to constant\n    *DataSet( \"\" ),\n    RooFit::Minimizer( \"Minuit\", \"Migrad\" ),\n    RooFit::Minos( kTRUE ),\n    RooFit::SumW2Error( kTRUE ),\n    RooFit::Verbose( kFALSE ),\n    RooFit::PrintLevel( -1 ),\n    RooFit::PrintEvalErrors( -1 ),\n    RooFit::Warnings( kFALSE )\n    );\n\n  // make sample claim ownership of pdfs\n\n  AddPdf( bipdf1 );\n  AddPdf( gpdf1 );\n  AddPdf( conv1pdf );\n  AddPdf( bipdf2 );\n  AddPdf( gpdf2 );\n  AddPdf( conv2pdf );\n  AddPdf( bisum );\n\n  AddFunc( gmean1 );\n  AddFunc( gmean2 );\n}\n", "meta": {"hexsha": "f86493919972af956e969aa20b4e01cd01b6ae21", "size": 9018, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MassRecoCompare/src/KeysCompMgr.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": "MassRecoCompare/src/KeysCompMgr.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": "MassRecoCompare/src/KeysCompMgr.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": 31.0965517241, "max_line_length": 103, "alphanum_fraction": 0.5219560878, "num_tokens": 2800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044135, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.27815444374356685}}
{"text": "#include \"bwd_lagrangian.h\"\n\n\n#include <cmath> \n#include <Eigen/Dense>\n\n#include \"../amr/mesh.h\"\n#include \"../amr/numerics.h\"\n#include \"../amr/refiner.h\"\n\n\n\nusing namespace Eigen;\n\n\nnamespace vlv { namespace tools {\ntemplate<typename T>\nT modf(T arg, T* iptr) = delete;\n\ntemplate<>\nfloat modf(float arg, float* iptr) { return modff(arg, iptr); }\n\ntemplate<>\ndouble modf(double arg, double* iptr) { return modf(arg, iptr); }\n\n} }\n\n\ntemplate<typename T, int D, int V>\nvoid vlv::AmrMomentumLagrangianSolver<T,D,V>::solve_mesh( \n        toolbox::AdaptiveMesh<T, 3>& mesh0,\n        toolbox::AdaptiveMesh<T, 3>& mesh1,\n        vec& Einc,\n        vec& Binc,\n        tools::Params<T>& params)\n{\n\n  toolbox::Adapter<T,3> adapter;\n  adapter.cells_to_refine.clear();\n  adapter.cells_to_unrefine.clear();\n\n\n  // empty the target mesh\n  // TODO: is this efficient; should we recycle instead?\n  mesh1.clear();\n\n\n  std::array<uint64_t, 3> index;\n  // std::array<T, 3> grad;\n\n  Vec3E B(Binc.data());  \n  Vec3E E(Einc.data());  \n\n\n  // level zero fill\n  auto val     = T(0);\n  T max_val = mesh0.max_value();\n\n  T refine_indicator, unrefine_indicator;\n  auto len = mesh0.get_size(0);\n\n  // XXX remove higher-dimension updates (compresses inner loops away)\n  // TODO does not work if the fill is not correctly done\n  for(int i = 2; i>V-1; i--) len[i] = 1;\n\n  // normalize\n  //T norm0 = integrate_moment( mesh0,\n  //          [](std::array<T,3>& uvel) -> T { return T(1);}\n  //          );\n\n\n  // cfl bound guards\n  auto cids = mesh0.get_cells(true);\n    \n  // if mesh is empty, bail out\n  if (cids.empty()) { return; }\n\n  auto min_ind = mesh0.get_indices( cids.front() );\n  auto max_ind = mesh0.get_indices( cids.back()  );\n\n  int cfl_halo = 10; // how many CFL steps are allowed in backward substitution\n\n  for(uint64_t t=0; t<len[2]; t++) {\n    index[2] = t;\n    for(uint64_t s=0; s<len[1]; s++) {\n      index[1] = s;\n      for(uint64_t r=0; r<len[0]; r++) {\n        index[0] = r;\n\n        // cfl bound guards\n        if( r < (min_ind[0] - cfl_halo) ) continue;\n        if( r > (max_ind[0] + cfl_halo) ) continue;\n\n        uint64_t cid = mesh1.get_cell_from_indices(index, 0);\n        val = backward_advect(index, 0, mesh0, E, B, params);\n\n        // refinement\n        // TODO specialize to value & gradient instead of just value\n        refine_indicator   = val/max_val;\n        unrefine_indicator = val/max_val;\n        adapter.check_cell(mesh1, cid, refine_indicator, unrefine_indicator);\n\n        mesh1.set(cid, val);\n      }\n    }\n  }\n\n\n\n  // create new leafs\n  // TODO fixme to use max ref. lvl of mesh\n  // for(size_t sweep=1; sweep<=mesh1.maximum_refinement_level; sweep++){\n  for(int sweep=1; sweep<=mesh1.top_refinement_level; sweep++){\n\n    adapter.refine(mesh1);\n\n    // fmt::print(\" sol: cells created {}\\n\", adapter.cells_to_refine.size());\n    // fmt::print(\" sol: cells removed {}\\n\", adapter.cells_removed.size());\n\n    adapter.cells_to_refine.clear();\n    adapter.cells_to_unrefine.clear();\n\n    // next we refine\n    for(auto&& cid : adapter.cells_created) {\n      int rfl = mesh1.get_refinement_level(cid);\n      auto index2 = mesh1.get_indices(cid);\n\n      // fmt::print(\"creating {} at {}\\n\", cid, rfl);\n\n      val = backward_advect(index2, rfl, mesh0, E, B, params);\n      mesh1.set(cid, val);\n\n      refine_indicator   = val/max_val;\n      unrefine_indicator = val/max_val;\n      adapter.check_cell(mesh1, cid, refine_indicator, unrefine_indicator);\n    }\n\n    // now unrefine \n    adapter.unrefine(mesh1);\n\n  }\n\n\n  // normalize back to original weight\n  //T norm1 = integrate_moment( mesh1,\n  //          [](std::array<T,3>& uvel) -> T { return T(1);}\n  //          );\n  //mesh1 *= norm0/norm1;\n\n  }\n\n// backward advected Lorentz force\ntemplate<typename T, int D, int V>\nT vlv::AmrMomentumLagrangianSolver<T,D,V>::backward_advect(\n    std::array<uint64_t, 3>& index,\n    int rfl,\n    const toolbox::AdaptiveMesh<T, 3>& mesh0,\n    //toolbox::AdaptiveMesh<T, 3>& mesh1,\n    Vec3E& E,\n    Vec3E& B,\n    tools::Params<T>& params)\n{\n  T val; // return value\n  vec u    = mesh0.get_center(index, rfl);  // velocity\n  vec du   = mesh0.get_length(rfl);         // box size, i.e., \\Delta u\n  auto len = mesh0.get_size(rfl);\n\n\n  // get shift of the characteristic solution from Lorentz force\n  Vec3E uvel( u.data() );\n  Vec3E F = lorentz_force(uvel, E, B, params.qm, params.cfl);\n\n  // add other forces; default to zero \n  Vec3E Fi = other_forces(uvel, params);\n  F += Fi;\n\n\n  // advection in units of cells \n  // NOTE: We normalize with CFL because velocities are in units \n  // of c and we need them in units of grid speed.\n  // XXX: CHECK\n  std::array<T,3> shift, cell_shift;\n  for(int i=0; i<V; i++) shift[i] = F(i) / du[i];\n\n  // advected tiles\n  std::array<int,3> index_shift;\n  for(int i=0; i<V; i++) index_shift[i] = static_cast<int>( trunc(shift[i]) );\n\n  // advection inside cell\n  T tmp;\n  for(int i=0; i<V; i++) cell_shift[i] = tools::modf<T>(shift[i], &tmp);\n\n  // new grid indices\n  std::array<uint64_t, 3> index_new;\n  for(int i=0;   i<V;   i++) index_new[i] = index[i] + index_shift[i];\n  for(int i = 2; i>V-1; i--) index_new[i] = index[i];\n\n\n  // set boundary conditions (zero outside the grid limits)\n  for(int i=0; i<V; i++){\n    if( (index_new[i] <2) || (index_new[i] >= len[i]-2) ) return T(0);\n  }\n\n  // interpolation branch\n  val = toolbox::interp_cubic<T,V>(mesh0, index_new, cell_shift, rfl);\n  //val = toolbox::interp_linear<T,V>(mesh0, index_new, cell_shift, rfl);\n\n  return val;\n}\n\n/// Relativistic Lorentz force / Electrostatic version\ntemplate<typename T, int D, int V>\ninline typename vlv::AmrMomentumLagrangianSolver<T,D,V>::Vec3E \nvlv::AmrMomentumLagrangianSolver<T,D,V>::lorentz_force(\n  Vec3E& /*uvel*/,\n  Vec3E& E,\n  Vec3E& /*B*/,\n  T qm,\n  T cfl)\n{\n  // electrostatic push\n  //\n  // Boris scheme for b=0 translates to\n  // u = (cfl*u_0 + e + e)/cfl = u_0 + E/cfl\n  //\n  // with halving taken into account in definition of Ex\n  return -qm*E/cfl;\n}\n\n\n\n/// default zero force for to be overloaded by more complicated solvers\ntemplate<typename T, int D, int V>\ninline typename vlv::AmrMomentumLagrangianSolver<T,D,V>::Vec3E \nvlv::AmrMomentumLagrangianSolver<T,D,V>::other_forces(\n    Vec3E& /*uvel*/,\n    tools::Params<T>& /*params*/\n    )\n{\n  Vec3E ret = Vec3E::Zero();\n  return ret;\n}\n\n\n\n//--------------------------------------------------\n// explicit template instantiation\ntemplate class vlv::AmrMomentumLagrangianSolver<Realf, 1, 1>; //1D1V\n\n", "meta": {"hexsha": "3a1cc6de8f3fa7f8c4f775db14d18e74fac24df4", "size": 6480, "ext": "c++", "lang": "C++", "max_stars_repo_path": "vlasov/momentum-solvers/bwd_lagrangian.c++", "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": "vlasov/momentum-solvers/bwd_lagrangian.c++", "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": "vlasov/momentum-solvers/bwd_lagrangian.c++", "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.92, "max_line_length": 79, "alphanum_fraction": 0.625, "num_tokens": 1978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2781544437435668}}
{"text": "/*=========================================================================\n  The Software is copyright (c) Commonwealth Scientific and Industrial Research Organisation (CSIRO)\n  ABN 41 687 119 230.\n  All rights reserved.\n\n  Licensed under the CSIRO BSD 3-Clause License\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License in the file LICENSE.md or at\n\n  https://stash.csiro.au/projects/SMILI/repos/smili/browse/license.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#include \"milxQtDiffusionTensorModel.h\"\n\n#include <time.h>\n\n#include <vtkMath.h>\n#include <vtkLine.h>\n#include <vtkSphereSource.h>\n\n#include <boost/math/special_functions/spherical_harmonic.hpp>\n\nmilxQtDiffusionTensorModel::milxQtDiffusionTensorModel(QWidget *theParent) : milxQtModel(theParent)\n{\n    milxQtWindow::prefix = \"DTI: \";\n\n    createActions();\n\n    createConnections();\n}\n\nmilxQtDiffusionTensorModel::~milxQtDiffusionTensorModel()\n{\n    //dtor\n}\n\nvoid milxQtDiffusionTensorModel::colourByDirection()\n{\n    vtkSmartPointer<vtkPolyData> currentMesh = model.Result();\n\n    typedef double projectionType;\n\n    ///Determine colours based on axes directions\n    vtkSmartPointer<vtkUnsignedCharArray> scalars = vtkSmartPointer<vtkUnsignedCharArray>::New();\n        scalars->SetNumberOfComponents(3);\n        scalars->SetNumberOfTuples(currentMesh->GetNumberOfPoints());\n        scalars->SetName(\"Fibre Colours\");\n        scalars->FillComponent(0, 0);\n        scalars->FillComponent(1, 0);\n        scalars->FillComponent(2, 0);\n    vtkSmartPointer<vtkFloatArray> projections = vtkSmartPointer<vtkFloatArray>::New();\n        projections->SetNumberOfComponents(3);\n        projections->SetNumberOfTuples(currentMesh->GetNumberOfPoints());\n        projections->SetName(\"Fibre Projections\");\n        projections->FillComponent(0, 0.0);\n        projections->FillComponent(1, 0.0);\n        projections->FillComponent(2, 0.0);\n\n    emit working(-1);\n    if(currentMesh->GetNumberOfLines() == 0)\n    {\n        printInfo(\"No lines in model. Computing colours for mesh.\");\n\n        ///Use the dot product in each axis\n        for(size_t j = 0; j < 3; j ++)\n        {\n            projectionType axis[3] = {0.0, 0.0, 0.0};\n            axis[j] = 1.0;\n            cout << \"Computing toward axis \" << j << endl;\n\n            ///Colour based on each of the gradient values in that direction\n            for(vtkIdType k = 0; k < currentMesh->GetNumberOfPoints(); k ++)\n            {\n                coordinate currentProjection(projections->GetTuple3(k)), position(currentMesh->GetPoint(k));\n\n                projectionType projection = vtkMath::Dot(axis, position.data_block()); //project to axis being done,\n                currentProjection[j] = projection; //projection in each direction\n\n                projections->SetTuple3(k, currentProjection[0], currentProjection[1], currentProjection[2]);\n            }\n        }\n\n        ///Colour based on each of the gradient values in that direction\n        for(vtkIdType k = 0; k < currentMesh->GetNumberOfPoints(); k ++)\n        {\n            coordinate currentProjection(projections->GetTuple3(k));\n            coordinate currentProjSquared = element_product(currentProjection, currentProjection);\n            projectionType maxProjection = currentProjSquared.max_value();\n            currentProjSquared /= maxProjection;\n\n            unsigned char colourOfPoint[3] = {0, 0, 0};\n            colourOfPoint[0] = static_cast<unsigned char>( currentProjSquared[0]*255.0 );\n            colourOfPoint[1] = static_cast<unsigned char>( currentProjSquared[1]*255.0 );\n            colourOfPoint[2] = static_cast<unsigned char>( currentProjSquared[2]*255.0 );\n\n            scalars->SetTupleValue(k, colourOfPoint);\n        }\n\n        currentMesh->GetPointData()->SetVectors(projections);\n        currentMesh->GetPointData()->SetScalars(scalars);\n    }\n    else\n    {\n        printInfo(\"Re-colouring lines by axes directions\");\n        //Ensure lines done properly so can colour appropriately\n        currentMesh->GetLines()->InitTraversal();\n        vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();\n        vtkSmartPointer<vtkIdList> idList = vtkSmartPointer<vtkIdList>::New();\n        std::vector<vtkIdType> trackLengths;\n        for(vtkIdType j = 0; j < currentMesh->GetNumberOfLines(); j ++)\n        {\n            currentMesh->GetLines()->GetNextCell(idList);\n            trackLengths.push_back(idList->GetNumberOfIds());\n            for(vtkIdType pointId = 0; pointId < idList->GetNumberOfIds(); pointId ++)\n            {\n    //            std::cout << idList->GetId(pointId) << \" \";\n\n                double position[3];\n                currentMesh->GetPoint(idList->GetId(pointId), position);\n                points->InsertNextPoint(position);\n            }\n        }\n\n        //Re-stitch lines together\n        vtkIdType step = 0;\n        vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New();\n        for(size_t j = 0; j < trackLengths.size(); j ++)\n        {\n            for(vtkIdType k = step; k < trackLengths[j]-1; k ++)\n            {\n                vtkSmartPointer<vtkLine> line = vtkSmartPointer<vtkLine>::New();\n                    line->GetPointIds()->SetId(0, k);\n                    line->GetPointIds()->SetId(1, k+1);\n                lines->InsertNextCell(line);\n            }\n            qDebug() << trackLengths[j] << endl;\n            step += trackLengths[j];\n        }\n\n        vtkSmartPointer<vtkPolyData> linesPolyData = vtkSmartPointer<vtkPolyData>::New();\n            //Add the points to the dataset\n            linesPolyData->SetPoints(points);\n            //Add the lines to the dataset\n            linesPolyData->SetLines(lines);\n            linesPolyData->Modified();\n        model.SetInput(linesPolyData);\n    }\n\n    emit done(-1);\n    generateModel();\n}\n\nvoid milxQtDiffusionTensorModel::harmonics(QString ordersString)\n{\n    bool ok = false;\n    if(ordersString.isEmpty())\n    {\n        ordersString = QInputDialog::getText(this, tr(\"Enter order magnitudes of harmonics separated by spaces\"),\n                                            tr(\"Orders: \"), QLineEdit::Normal,\n                                            \"1 0 0 0 1 1 1 1 1\", &ok);\n    }\n    if (!ok || ordersString.isEmpty())\n        return;\n\n    QStringList orders = ordersString.split(\" \");\n    std::vector<double> sHarmonicCoefficients;\n    for(int i = 0; i < orders.size(); i++)\n        sHarmonicCoefficients.push_back(orders[i].toDouble());\n\n    int n_coefs = sHarmonicCoefficients.size();\n    int l_max   = milxQtDiffusionTensorModel::LforN( n_coefs );\n\n    vtkSmartPointer<vtkSphereSource> sphereSource = vtkSmartPointer<vtkSphereSource>::New();\n        sphereSource->SetThetaResolution( 64 );\n        sphereSource->SetPhiResolution( 64 );\n        sphereSource->SetRadius( 1.0 );\n        sphereSource->Update();\n    vtkSmartPointer<vtkPolyData> glyph = sphereSource->GetOutput();\n\n    ///For every point in sphere mesh\n    double m_x = 0, m_y = 0, m_z = 0;\n    for(int i = 0; i < glyph->GetNumberOfPoints(); i++)\n    {\n        double point_sphere[3];\n        glyph->GetPoint(i, point_sphere);\n        double x_s = point_sphere[0];\n        double y_s = point_sphere[1];\n        double z_s = point_sphere[2];\n\n        double x_g, y_g, z_g;\n\n        ///Compute spherical harmonic amplitude\n        double amplitude = computeAmplitude( sHarmonicCoefficients, x_s, y_s, z_s, l_max );\n\n        if(amplitude < 0)\n            amplitude = 0;\n\n        ///use this to displace sphere points accordingly\n        x_g = x_s * amplitude + m_x;\n        y_g = y_s * amplitude + m_y;\n        z_g = z_s * amplitude + m_z;\n\n        glyph->GetPoints()->SetPoint(i, x_g, y_g, z_g);\n    }\n\n    model.SetInput(glyph);\n    model.GenerateNormals(true);\n\n    generateModel();\n    milxQtRenderWindow::reset();\n}\n\ndouble milxQtDiffusionTensorModel::computeAmplitude(std::vector<double> SH, double x, double y, double z, int lmax)\n{\n    double az = atan2(y, x);\n    double el = acos(z);\n    double val = 0.0;\n    for (int l = 0; l <= lmax; l+=2)\n    {\n        // val += SH[milxQtDiffusionTensorModel::index(l,0)] * boost::math::legendre_p<double>(l, 0, z);\n        val += SH[milxQtDiffusionTensorModel::index(l,0)] * boost::math::spherical_harmonic_r<double>(l, 0, el,az);\n    }\n\n    for (int m = 1; m <= lmax; m++)\n    {\n//        float caz = cos(m*az);\n//        float saz = sin(m*az);\n        for (int l = 2*((m+1)/2); l <= lmax; l+=2)\n        {\n        // float buf = boost::math::legendre_p<double>(l, 0, z);\n        // val += SH[index(l,m)]*buf*caz;\n        // val += SH[index(l,-m)]*buf*saz;\n            val += SH[milxQtDiffusionTensorModel::index(l,m)]*boost::math::spherical_harmonic_r(l,m,el,az);\n            val += SH[milxQtDiffusionTensorModel::index(l,-m)]*boost::math::spherical_harmonic_i(l,m,el,az);\n        }\n    }\n\n    return val;\n}\n\nvoid milxQtDiffusionTensorModel::createActions()\n{\n    colourDirectionAct = new QAction(this);\n        colourDirectionAct->setText(QApplication::translate(\"Model\", \"Colour By Direction\", 0, QApplication::UnicodeUTF8));\n        colourDirectionAct->setShortcut(tr(\"Alt+c\"));\n    harmonicsAct = new QAction(this);\n        harmonicsAct->setText(QApplication::translate(\"Model\", \"Show Spherical Harmonic ...\", 0, QApplication::UnicodeUTF8));\n        harmonicsAct->setShortcut(tr(\"Alt+s\"));\n}\n\nvoid milxQtDiffusionTensorModel::createConnections()\n{\n    //Operations\n    connect(colourDirectionAct, SIGNAL(triggered()), this, SLOT(colourByDirection()));\n    connect(harmonicsAct, SIGNAL(triggered()), this, SLOT(harmonics()));\n\n    //milxQtModel::createConnections();\n}\n\nvoid milxQtDiffusionTensorModel::contextMenuEvent(QContextMenuEvent *currentEvent)\n{\n    contextMenu = milxQtModel::basicContextMenu(); //!< Only exists for the duration of the context selection\n\n    contextMenu->addSeparator()->setText(tr(\"DiffusionTensor\"));\n    contextMenu->addAction(colourDirectionAct);\n    contextMenu->addAction(harmonicsAct);\n    contextMenu->addSeparator()->setText(tr(\"Extensions\"));\n    foreach(QAction *currAct, extActionsToAdd)\n    {\n        contextMenu->addAction(currAct);\n    }\n    contextMenu->addSeparator();\n    ///Dont display extensions\n    contextMenu->addAction(milxQtModel::scaleAct);\n    contextMenu->addAction(milxQtRenderWindow::axesAct);\n    contextMenu->addAction(milxQtRenderWindow::refreshAct);\n\n    contextMenu->exec(currentEvent->globalPos());\n}\n", "meta": {"hexsha": "bb755c2392c559eca41707a42f8bf6ff414e4779", "size": 10828, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "plugin/dti/milxQtDiffusionTensorModel.cpp", "max_stars_repo_name": "aneube/smili-spine", "max_stars_repo_head_hexsha": "3cd8f95077d4bc1f5ac6146bc5356c3131f22e4b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-03-09T19:22:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T20:25:08.000Z", "max_issues_repo_path": "plugin/dti/milxQtDiffusionTensorModel.cpp", "max_issues_repo_name": "aneube/smili-spine", "max_issues_repo_head_hexsha": "3cd8f95077d4bc1f5ac6146bc5356c3131f22e4b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2015-08-20T03:30:15.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-22T12:21:14.000Z", "max_forks_repo_path": "plugin/dti/milxQtDiffusionTensorModel.cpp", "max_forks_repo_name": "aneube/smili-spine", "max_forks_repo_head_hexsha": "3cd8f95077d4bc1f5ac6146bc5356c3131f22e4b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-06-22T00:11:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-26T21:29:52.000Z", "avg_line_length": 37.9929824561, "max_line_length": 125, "alphanum_fraction": 0.6312338382, "num_tokens": 2647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.2780627236632889}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <iomanip>\n#include <Eigen/Eigen>\n#include <glog/logging.h>\n#include <experimental/filesystem>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <dirent.h>\n#include <unistd.h>\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/eigen.hpp>\n\n#include \"json.h\"\n#include \"reprojection_error_cost.h\"\n\nusing json = nlohmann::json;\nnamespace fs = std::experimental::filesystem;\nusing namespace lass;\n\n#define print_var(x) std::cout << #x << \" \" << x << std::endl;\n\nstruct FrameData {\n    FrameData() {\n        K.setIdentity();\n        qcw_gt.setIdentity();\n        qcw.setIdentity();\n        pcw_gt.setZero();\n        pcw.setZero();\n    }\n    Eigen::Quaterniond qcw_gt, qcw;\n    Eigen::Vector3d pcw_gt, pcw;\n    Eigen::Matrix3d K;\n    std::vector<Eigen::Vector3d> landmarks;\n    std::vector<Eigen::Vector2d> keypoints;\n    std::string filename;\n    std::vector<int> inlier_indices;\n};\n\ninline std::vector<std::string> get_filenames(std::string base_dir) {\n    std::vector<std::string> filenames;\n    DIR *dir;\n    struct dirent *entry;\n    if ((dir = opendir(base_dir.c_str())) != NULL) {\n        /* print all the files and directories within directory */\n        while ((entry = readdir(dir)) != NULL) {\n            // ignore files and hidden folders\n            if (entry->d_type == DT_REG && entry->d_name[0] != '.') {\n                filenames.emplace_back(entry->d_name);\n                // printf(\"Find files %s\\n\", entry->d_name);\n            }\n        }\n        closedir(dir);\n    }\n    return filenames;\n}\n\ninline FrameData load_single_from_json(const std::string &filename, std::vector<Eigen::Vector3d> &id2center) {\n    std::ifstream ifs(filename);\n    json j_data;\n    ifs >> j_data;\n    ifs.close();\n    // std::cout << j_data;\n    CHECK(j_data[\"label\"].size() == j_data[\"uv\"].size()) << \"size inconsistency\";\n    FrameData data;\n    Eigen::Matrix3d R;\n    for (int row = 0; row < 3; row++) {\n        for (int col = 0; col < 4; col++) {\n            if (col >= 3) {\n                data.pcw_gt(row) = j_data[\"pose\"][row * 4 + col];\n            } else {\n                R(row, col) = j_data[\"pose\"][row * 4 + col];\n            }\n        }\n    }\n    data.qcw_gt = R;\n    for (int row = 0; row < 3; ++row) {\n        for (int col = 0; col < 3; ++col) {\n            data.K(row, col) = j_data[\"camera_k_matrix\"][row * 3 + col];\n        }\n    }\n    for (int idx = 0; idx < j_data[\"label\"].size(); idx++) {\n        int id = j_data[\"label\"][idx];\n        data.landmarks.push_back(id2center[id]);\n        data.keypoints.emplace_back(j_data[\"uv\"][idx][0], j_data[\"uv\"][idx][1]);\n    }\n    data.filename = filename;\n    // print_var(data.filename);\n    // print_var(data.K);\n    // print_var(data.pcw_gt);\n    // print_var(data.qcw_gt.coeffs());\n    // print_var(data.keypoints.size());\n    // print_var(data.landmarks.size());\n    return data;\n}\n\ninline std::vector<FrameData> load_data_from_json(const std::string &base_dir) {\n    std::ifstream cfs(base_dir + \"/id2centers.json\");\n    json j_centers;\n    cfs >> j_centers;\n    cfs.close();\n    std::vector<Eigen::Vector3d> centers(j_centers.size());\n    for (int idx = 0; idx < j_centers.size(); idx++) {\n        json &j_center = j_centers[idx];\n        centers[idx] = {j_center[0], j_center[1], j_center[2]};\n    }\n\n    auto filenames = get_filenames(base_dir + \"/prediction_json\");\n    std::sort(filenames.begin(), filenames.end());\n    std::vector<FrameData> frames;\n    for (const auto &fn : filenames) {\n        frames.push_back(load_single_from_json(base_dir + \"/prediction_json/\" + fn, centers));\n    }\n    return frames;\n}\n\ndouble compute_reprojection_error(const FrameData &frame) {\n    double rpe_sum = 0;\n    double count = 0;\n    for (const auto &idx : frame.inlier_indices) {\n        Eigen::Vector3d pt_c = frame.qcw * frame.landmarks[idx] + frame.pcw;\n        Eigen::Vector2d pt_2d = pt_c.hnormalized();\n        CHECK(std::abs(frame.K(0, 0) - frame.K(1, 1)) < 1e-5);\n        pt_2d = {frame.K(0, 0) * pt_2d.x() + frame.K(0, 2), frame.K(0, 0) * pt_2d.y() + frame.K(1, 2)};\n        double rpe = (pt_2d - frame.keypoints[idx]).norm();\n        rpe_sum += rpe;\n        count++;\n    }\n    return rpe_sum / count;\n}\n\nvoid solve_pose(FrameData &frame) {\n    // get initial pose and inlier points via opencv solvePnPRansac\n    std::vector<cv::Point2d> image_pts;\n    std::vector<cv::Point3d> world_pts;\n    for (int i = 0; i < frame.landmarks.size(); ++i) {\n        image_pts.emplace_back(frame.keypoints[i].x(), frame.keypoints[i].y());\n        world_pts.emplace_back(frame.landmarks[i].x(), frame.landmarks[i].y(), frame.landmarks[i].z());\n    }\n    cv::Mat K = cv::Mat::eye(cv::Size(3, 3), CV_64F);\n    K.at<double>(0, 0) = frame.K(0, 0);\n    K.at<double>(0, 2) = frame.K(0, 2);\n    K.at<double>(1, 1) = frame.K(1, 1);\n    K.at<double>(1, 2) = frame.K(1, 2);\n    cv::Mat rotation, translation;\n    std::vector<int> inlier_indices;\n    cv::solvePnPRansac(world_pts, image_pts,\n                       K, cv::Mat(),\n                       rotation, translation, false,\n                       200, 8.0, 0.99, inlier_indices,\n                       cv::SOLVEPNP_P3P);\n    cv::Rodrigues(rotation, rotation);\n    Eigen::Matrix3d R;\n    cv::cv2eigen(rotation, R);\n    frame.qcw = R;\n    cv::cv2eigen(translation, frame.pcw);\n    // print_var(rotation);\n    // print_var(translation);\n\n    // check frustum\n    for (auto it = inlier_indices.begin(); it != inlier_indices.end();) {\n        Eigen::Vector3d pt_c = frame.qcw * frame.landmarks[*it] + frame.pcw;\n        bool is_in_frustum = pt_c.z() > 0;\n        Eigen::Vector2d pt_2d = pt_c.hnormalized();\n        pt_2d = {frame.K(0, 0) * pt_2d.x() + frame.K(0, 2), frame.K(0, 0) * pt_2d.y() + frame.K(1, 2)};\n        if (pt_2d.x() < 0 || pt_2d.x() > 480 || pt_2d.y() < 0 || pt_2d.y() > 270) {\n            is_in_frustum = false;\n        }\n        if (!is_in_frustum) {\n            std::cerr << \"find pt not in frustum!\\n\";\n            print_var(pt_c);\n            print_var(pt_2d);\n            it = inlier_indices.erase(it);\n        } else {\n            ++it;\n        }\n    }\n\n    // prepare optimize data\n    if (inlier_indices.size() < 5) {\n        std::cerr << \"inliers not enough! current inlier count \" << inlier_indices.size() << std::endl;\n    }\n\n    frame.inlier_indices = inlier_indices;\n    std::vector<Eigen::Vector3d> inlier_landmarks;\n    std::vector<Eigen::Vector2d> inlier_keypoints;\n    // print_var(inlier_indices.size());\n    for (const auto &idx : inlier_indices) {\n        inlier_keypoints.push_back(frame.keypoints[idx]);\n        inlier_landmarks.push_back(frame.landmarks[idx]);\n    }\n\n    // print_var(frame.qcw_gt.coeffs());\n    // print_var(frame.qcw.coeffs());\n    // print_var(frame.pcw_gt);\n    // print_var(frame.pcw);\n    // print_var(compute_reprojection_error(frame));\n    double rpe_before = compute_reprojection_error(frame);\n\n    // optimize via ceres\n    ceres::Problem problem;\n    std::array<double, 7> camera = {frame.qcw.w(), frame.qcw.x(), frame.qcw.y(), frame.qcw.z(), frame.pcw.x(), frame.pcw.y(), frame.pcw.z()};\n    auto loss_function = new ceres::HuberLoss(1.0);\n    ceres::LocalParameterization *camera_parameterization =\n        new ceres::ProductParameterization(\n            new ceres::QuaternionParameterization(),\n            new ceres::IdentityParameterization(3));\n    problem.AddParameterBlock(camera.data(), 7, camera_parameterization);\n    for (int i = 0; i < inlier_landmarks.size(); ++i) {\n        problem.AddParameterBlock(inlier_landmarks[i].data(), 3);\n        problem.SetParameterBlockConstant(inlier_landmarks[i].data());\n        ceres::CostFunction *cost_function = ReprojectionErrorWithQuaternions::Create(\n            inlier_keypoints[i], frame.K);\n        problem.AddResidualBlock(cost_function, loss_function, camera.data(), inlier_landmarks[i].data());\n    }\n    ceres::Solver::Options solver_options;\n    solver_options.linear_solver_type = ceres::DENSE_SCHUR;\n    solver_options.trust_region_strategy_type = ceres::LEVENBERG_MARQUARDT;\n    solver_options.use_explicit_schur_complement = true;\n    // solver_options.minimizer_progress_to_stdout = true;\n    solver_options.minimizer_progress_to_stdout = false;\n    ceres::Solver::Summary solver_summary;\n    ceres::Solve(solver_options, &problem, &solver_summary);\n    // print_var(camera[0]);\n    // print_var(camera[1]);\n    // print_var(camera[2]);\n    // print_var(camera[3]);\n    // print_var(camera[4]);\n    // print_var(camera[5]);\n    // print_var(camera[6]);\n    // std::cout << solver_summary.BriefReport();\n    // assign valie\n    frame.pcw = {camera[4], camera[5], camera[6]};\n    frame.qcw = Eigen::Quaterniond(camera[0], camera[1], camera[2], camera[3]);\n    double rpe_after = compute_reprojection_error(frame);\n    printf(\"reprojection error : %.4f -> %.4f\\n\", rpe_before, rpe_after);\n}\n\nint main(int argc, char **argv) {\n    std::string base_dir = argv[1];\n    auto frames = load_data_from_json(base_dir);\n    std::vector<double> APEs, AREs;\n\n    for (auto &f : frames) {\n        // solve and optimize\n        solve_pose(f);\n        // evaluate\n        if (f.inlier_indices.empty()) {\n            APEs.push_back(std::numeric_limits<double>::max());\n            AREs.push_back(std::numeric_limits<double>::max());\n            continue;\n        }\n        APEs.push_back((f.pcw - f.pcw_gt).norm() * 1e3);\n        Eigen::Quaterniond q_diff = f.qcw * f.qcw_gt.conjugate();\n        Eigen::AngleAxisd aa(q_diff);\n        AREs.push_back(aa.angle() * 180 / M_PI);\n    }\n    std::sort(APEs.begin(), APEs.end());\n    std::sort(AREs.begin(), AREs.end());\n    printf(\"APE median: %.3f [mm]\\nARE median %.3f[DEG]\\n\", APEs[APEs.size() / 2], AREs[AREs.size() / 2]);\n    return 0;\n}\n", "meta": {"hexsha": "a96bf32209a5c9c8f8d129b47b5a0c93b49ac0f9", "size": 9763, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/exec/test_pnp.cc", "max_stars_repo_name": "asdiuzd/lass", "max_stars_repo_head_hexsha": "a767f8bd68c46dadf8d74703fdf2058da9f17e53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-06T09:04:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T09:04:46.000Z", "max_issues_repo_path": "src/exec/test_pnp.cc", "max_issues_repo_name": "asdiuzd/lass", "max_issues_repo_head_hexsha": "a767f8bd68c46dadf8d74703fdf2058da9f17e53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/exec/test_pnp.cc", "max_forks_repo_name": "asdiuzd/lass", "max_forks_repo_head_hexsha": "a767f8bd68c46dadf8d74703fdf2058da9f17e53", "max_forks_repo_licenses": ["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.9810606061, "max_line_length": 141, "alphanum_fraction": 0.6053467172, "num_tokens": 2761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.27806271582911357}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2021 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n\n\n#include \"Lagrangian2d1DR.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 DEBUG_NOCOLOR\n// #define DEBUG_STDOUT\n// #define DEBUG_MESSAGES\n#include \"siconos_debug.h\"\n\n\nvoid Lagrangian2d1DR::initialize(Interaction& inter)\n{\n  LagrangianR::initialize(inter);\n  //proj_with_q  _jachqProj.reset(new SimpleMatrix(_jachq->size(0),_jachq->size(1)));\n\n  if((inter.getSizeOfDS() !=3) and (inter.getSizeOfDS() !=6))\n  {\n    THROW_EXCEPTION(\"Lagrangian2d1DR::initialize(Interaction& inter). The size of ds must of size 3\");\n  }\n  unsigned int qSize = 3 * (inter.getSizeOfDS() / 3);\n  _jachq.reset(new SimpleMatrix(1, qSize));\n}\n\nvoid Lagrangian2d1DR::computeJachq(const BlockVector& q, BlockVector& z)\n{\n  DEBUG_BEGIN(\"Lagrangian2d1DR::computeJachq(Interaction& inter, SP::BlockVector q0 \\n\");\n\n  double Nx = _Nc->getValue(0);\n  double Ny = _Nc->getValue(1);\n  double Px = _Pc1->getValue(0);\n  double Py = _Pc1->getValue(1);\n  double G1x = q.getValue(0);\n  double G1y = q.getValue(1);\n\n  _jachq->setValue(0,0,Nx);\n  _jachq->setValue(0,1,Ny);\n  _jachq->setValue(0,2,(G1y-Py)*Nx - (G1x-Px)*Ny);\n\n\n  if(q.size() ==6)\n  {\n    DEBUG_PRINT(\"take into account second ds\\n\");\n    double G2x = q.getValue(3);\n    double G2y = q.getValue(4);\n\n    _jachq->setValue(0,3,-Nx);\n    _jachq->setValue(0,4,-Ny);\n    _jachq->setValue(0,5,- ((G2y-Py)*Nx - (G2x-Px)*Ny));\n  }\n  DEBUG_EXPR(_jachq->display(););\n  DEBUG_END(\"Lagrangian2d1DR::computeJachq(Interaction& inter, SP::BlockVector q0) \\n\");\n\n}\n\ndouble Lagrangian2d1DR::distance() const\n{\n  DEBUG_BEGIN(\"Lagrangian2d1DR::distance(...)\\n\")\n  SiconosVector dpc(*_Pc2 - *_Pc1);\n  DEBUG_END(\"Lagrangian2d1DR::distance(...)\\n\")\n  return dpc.norm2() * (inner_prod(*_Nc, dpc) >= 0 ? -1 : 1);\n\n}\n\nvoid Lagrangian2d1DR::computeh(const BlockVector& q, BlockVector& z, SiconosVector& y)\n{\n  DEBUG_BEGIN(\"Lagrangian2d1DR::computeh(...)\\n\");\n  DEBUG_EXPR(q.display());\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 q and relPc1\n\n  double angle= q(2);\n  (*_Pc1)(0) = q(0) + cos(angle) * (*_relPc1)(0)+ sin(angle) * (*_relPc1)(1);\n  (*_Pc1)(1) = q(1) + sin(angle) * (*_relPc1)(0)- cos(angle) * (*_relPc1)(1);\n  if(q.size() == 6)\n  {\n    // To be checked\n    DEBUG_PRINT(\"take into account second ds\\n\");\n    angle = q(5);\n    (*_Pc2)(0) = q(3) + cos(angle) * (*_relPc2)(0)+ sin(angle) * (*_relPc2)(1);\n    (*_Pc2)(1) = q(4) + sin(angle) * (*_relPc2)(0)- cos(angle) * (*_relPc2)(1);\n    (*_Nc)(0) =  cos(angle) * (*_relNc)(0)+ sin(angle) * (*_relNc)(1);\n    (*_Nc)(1) =  sin(angle) * (*_relNc)(0)+ cos(angle) * (*_relNc)(1);\n  }\n  else\n  {\n    *_Pc2 = *_relPc2;\n    *_Nc = *_relNc;\n  }\n\n\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  LagrangianScleronomousR::computeh(q, z, y);\n  y.setValue(0, distance());\n  DEBUG_EXPR(y.display(););\n  DEBUG_EXPR(display(););\n  DEBUG_END(\"Lagrangian2d1DR::computeh(...)\\n\")\n}\nvoid Lagrangian2d1DR::display() const\n{\n  LagrangianR::display();\n\n  std::cout << \" _Pc1 :\" << std::endl;\n  if(_Pc1)\n    _Pc1->display();\n  else\n    std::cout << \" nullptr :\" << std::endl;\n\n  std::cout << \" _Pc2 :\" << std::endl;\n  if(_Pc2)\n    _Pc2->display();\n  else\n    std::cout << \" nullptr :\" << std::endl;\n\n  std::cout << \" _relPc1 :\" << std::endl;\n  if(_relPc1)\n    _relPc1->display();\n  else\n    std::cout << \" nullptr :\" << std::endl;\n\n  std::cout << \" _relPc2 :\" << std::endl;\n  if(_relPc2)\n    _relPc2->display();\n  else\n    std::cout << \" nullptr :\" << std::endl;\n\n  std::cout << \" _Nc :\" << std::endl;\n  if(_Nc)\n    _Nc->display();\n  else\n    std::cout << \" nullptr :\" << std::endl;\n  std::cout << \" _relNc :\" << std::endl;\n  if(_relNc)\n    _relNc->display();\n  else\n    std::cout << \" nullptr :\" << std::endl;\n\n}\n", "meta": {"hexsha": "c9c22c3644500053a4f231b766cc1ef6efbc7195", "size": 5852, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/modelingTools/Lagrangian2d1DR.cpp", "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/modelingTools/Lagrangian2d1DR.cpp", "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/modelingTools/Lagrangian2d1DR.cpp", "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": 29.7055837563, "max_line_length": 102, "alphanum_fraction": 0.6066302119, "num_tokens": 2185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2780240926445292}}
{"text": "/*\n * (C) Copyright 2018-2019 UCAR\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/Core>\n#include <cmath>\n#include <fstream>\n#include <memory>\n#include <random>\n#include <set>\n\n#include \"ufo/ObsBiasCovariance.h\"\n\n#include \"ioda/distribution/Accumulator.h\"\n#include \"ioda/Engines/Factory.h\"\n#include \"ioda/Engines/HH.h\"\n#include \"ioda/Layout.h\"\n#include \"ioda/ObsGroup.h\"\n#include \"ioda/ObsSpace.h\"\n#include \"ioda/ObsVector.h\"\n\n#include \"oops/util/IntSetParser.h\"\n#include \"oops/util/Logger.h\"\n#include \"oops/util/Random.h\"\n\n#include \"ufo/ObsBias.h\"\n#include \"ufo/ObsBiasIncrement.h\"\n#include \"ufo/ObsBiasPreconditioner.h\"\n#include \"ufo/predictors/PredictorBase.h\"\n#include \"ufo/utils/IodaGroupIndices.h\"\n\nnamespace ufo {\n\n// -----------------------------------------------------------------------------\n\nObsBiasCovariance::ObsBiasCovariance(ioda::ObsSpace & odb,\n                                     const Parameters_ & params)\n  : odb_(odb), prednames_(0), vars_(odb.obsvariables()), variances_(),\n    preconditioner_(0),\n    ht_rinv_h_(0), obs_num_(0), analysis_variances_(0), minimal_required_obs_number_(0),\n    rank_(odb.distribution()->rank()) {\n  oops::Log::trace() << \"ObsBiasCovariance::Constructor starting\" << std::endl;\n\n  // Predictor factory\n  for (const PredictorParametersWrapper &wrapper :\n       params.variationalBC.value().predictors.value()) {\n    std::shared_ptr<PredictorBase> pred(PredictorFactory::create(wrapper.predictorParameters,\n                                                                 vars_));\n    prednames_.push_back(pred->name());\n  }\n\n  if (prednames_.size()*vars_.size() > 0) {\n    if (params.covariance.value() == boost::none)\n      throw eckit::UserError(\"obs bias.covariance section missing from the YAML file\");\n    const ObsBiasCovarianceParameters &biasCovParams = *params.covariance.value();\n\n    // Get the minimal required filtered obs number\n    minimal_required_obs_number_ = biasCovParams.minimalRequiredObsNumber;\n\n    // Override the variance range if provided\n    {\n      const std::vector<double> &range = biasCovParams.varianceRange.value();\n      ASSERT(range.size() == 2);\n      smallest_variance_ = range[0];\n      largest_variance_ = range[1];\n    }\n\n    // Override the preconditioning step size if provided\n    step_size_ = biasCovParams.stepSize;\n\n    // Override the largest analysis variance if provided\n    largest_analysis_variance_ = biasCovParams.largestAnalysisVariance;\n\n    // Initialize the variances to upper limit\n    variances_ = Eigen::VectorXd::Constant(prednames_.size()*vars_.size(), largest_variance_);\n\n    // Initialize the hessian contribution to zero\n    ht_rinv_h_.resize(prednames_.size() * vars_.size());\n    std::fill(ht_rinv_h_.begin(), ht_rinv_h_.end(), 0.0);\n\n    // Initialize the preconditioner to default step size\n    preconditioner_.resize(prednames_.size() * vars_.size());\n    std::fill(preconditioner_.begin(), preconditioner_.end(), step_size_);\n\n    // Initialize obs_num_ to ZERO\n    obs_num_.resize(vars_.size());\n    std::fill(obs_num_.begin(), obs_num_.end(), 0);\n\n    // Initialize analysis error variances to the upper limit\n    analysis_variances_.resize(prednames_.size() * vars_.size());\n    std::fill(analysis_variances_.begin(), analysis_variances_.end(), largest_variance_);\n\n    // Initializes from given prior\n    if (biasCovParams.prior.value() != boost::none) {\n      const ObsBiasCovariancePriorParameters &priorParams = *biasCovParams.prior.value();\n\n      // Get default inflation ratio\n      const double inflation_ratio = priorParams.inflation.value().ratio;\n\n      // Check the large inflation ratio when obs number < minimal_required_obs_number\n      const double large_inflation_ratio = priorParams.inflation.value().ratioForSmallDataset;\n\n      // read in Variances prior (analysis_variances_) and number of obs. (obs_num_)\n      // from previous cycle\n      this->read(priorParams);\n\n      // set variances for bias predictor coeff. based on diagonal info\n      // of previous analysis error variance\n      std::size_t ii;\n      for (std::size_t j = 0; j < vars_.size(); ++j) {\n        const double inflation = (obs_num_[j] <= minimal_required_obs_number_) ?\n                                 large_inflation_ratio : inflation_ratio;\n        for (std::size_t p = 0; p < prednames_.size(); ++p) {\n          ii = j*prednames_.size() + p;\n          if (inflation > inflation_ratio)\n            analysis_variances_[ii] = inflation * analysis_variances_[ii] + smallest_variance_;\n          variances_[ii] = inflation * analysis_variances_[ii] + smallest_variance_;\n          if (variances_[ii] > largest_variance_) variances_[ii] = largest_variance_;\n          if (analysis_variances_[ii] > largest_analysis_variance_)\n            analysis_variances_[ii] = largest_analysis_variance_;\n        }\n      }\n    }\n  }\n\n  oops::Log::trace() << \"ObsBiasCovariance::Constructor is done\" << std::endl;\n}\n\n// -----------------------------------------------------------------------------\n\nvoid ObsBiasCovariance::read(const ObsBiasCovariancePriorParameters & params) {\n  oops::Log::trace() << \"ObsBiasCovariance::read from file \" << std::endl;\n\n  if (params.inputFile.value() != boost::none) {\n    // Open an hdf5 file, read only\n    ioda::Engines::BackendNames  backendName = ioda::Engines::BackendNames::Hdf5File;\n    ioda::Engines::BackendCreationParameters backendParams;\n    backendParams.fileName = *params.inputFile.value();\n    backendParams.action   = ioda::Engines::BackendFileActions::Open;\n    backendParams.openMode = ioda::Engines::BackendOpenModes::Read_Only;\n\n    // Create the backend and attach it to an ObsGroup\n    // Use the None DataLyoutPolicy for now to accommodate the current file format\n    ioda::Group backend = constructBackend(backendName, backendParams);\n    ioda::ObsGroup obsgroup = ioda::ObsGroup(backend,\n                   ioda::detail::DataLayoutPolicy::generate(\n                         ioda::detail::DataLayoutPolicy::Policies::None));\n\n    // Read coefficients error variances into the Eigen array\n    ioda::Variable bcerrvar = obsgroup.vars[\"bias_coeff_errors\"];\n    Eigen::ArrayXXf allbcerrors;\n    bcerrvar.readWithEigenRegular(allbcerrors);\n\n    // Read nobs into Eigen array\n    ioda::Variable nobsvar = obsgroup.vars[\"number_obs_assimilated\"];\n    Eigen::ArrayXf nobsassim;\n    nobsvar.readWithEigenRegular(nobsassim);\n\n    // Find indices of predictors and variables/channels that we need in the data read from the file\n    const std::vector<int> pred_idx = getRequiredVariableIndices(obsgroup, \"predictors\",\n                                              prednames_.begin(), prednames_.end());\n    const std::vector<int> var_idx = getRequiredVarOrChannelIndices(obsgroup, vars_);\n\n    // Filter predictors and channels that we need\n    // FIXME: may be possible by indexing allbcerrors(pred_idx, chan_idx) when Eigen 3.4\n    // is available\n    for (size_t jvar = 0; jvar < var_idx.size(); ++jvar) {\n      obs_num_[jvar] = nobsassim(var_idx[jvar]);\n      for (size_t jpred = 0; jpred < pred_idx.size(); ++jpred) {\n        analysis_variances_[jvar*pred_idx.size()+jpred] =\n             allbcerrors(pred_idx[jpred], var_idx[jvar]);\n      }\n    }\n  }\n  oops::Log::trace() << \"ObsBiasCovariance::read is done \" << std::endl;\n}\n\n// -----------------------------------------------------------------------------\n\nvoid ObsBiasCovariance::write(const Parameters_ & params) {\n  // only write files out on the task with MPI rank 0\n  if (rank_ != 0) return;\n\n  oops::Log::trace() << \"ObsBiasCovariance::write to file \" << std::endl;\n  const ObsBiasCovarianceParameters &biasCovParams = *params.covariance.value();\n\n  if (biasCovParams.outputFile.value() != boost::none) {\n    // FIXME: only implemented for channels currently\n    if (vars_.channels().size() == 0) {\n      throw eckit::NotImplemented(\"ObsBiasCovariance::write not implemented for without channels\",\n                                  Here());\n    }\n    // Create a file, overwrite if exists\n    const std::string output_filename = *biasCovParams.outputFile.value();\n    ioda::Group group = ioda::Engines::HH::createFile(output_filename,\n                        ioda::Engines::BackendCreateModes::Truncate_If_Exists);\n\n    // put only variable bias predictors into the predictors vector\n    std::vector<std::string> predictors(prednames_.begin(), prednames_.end());\n    // map coefficients to 2D for saving\n    Eigen::Map<const Eigen::MatrixXd>\n        allbcerrors(variances_.data(), prednames_.size(), vars_.size());\n    const std::vector<int> channels = vars_.channels();\n    std::vector<int> obs_assimilated(obs_num_.begin(), obs_num_.end());\n\n    // dimensions\n    ioda::NewDimensionScales_t dims {\n        ioda::NewDimensionScale<int>(\"npredictors\", predictors.size()),\n        ioda::NewDimensionScale<int>(\"nchannels\", channels.size())\n    };\n    // new ObsGroup\n    ioda::ObsGroup ogrp = ioda::ObsGroup::generate(group, dims);\n\n    // save the predictors\n    ioda::Variable predsVar = ogrp.vars.createWithScales<std::string>(\n                              \"predictors\", {ogrp.vars[\"npredictors\"]});\n    predsVar.write(predictors);\n    // and the variables\n    ioda::Variable chansVar = ogrp.vars.createWithScales<int>(\n                              \"channels\", {ogrp.vars[\"nchannels\"]});\n    chansVar.write(channels);\n\n    // and the number_obs_assimilated\n    ioda::Variable nobsVar = ogrp.vars.createWithScales<int>(\n                             \"number_obs_assimilated\", {ogrp.vars[\"nchannels\"]});\n    nobsVar.write(obs_assimilated);\n\n    // Set up the creation parameters for the bias covariance coefficients variable\n    ioda::VariableCreationParameters float_params;\n    float_params.chunk = true;               // allow chunking\n    float_params.compressWithGZIP();         // compress using gzip\n    float missing_value = util::missingValue(missing_value);\n    float_params.setFillValue<float>(missing_value);\n\n    // Create a variable for bias covariance coefficients,\n    // save bias covariance coeffs to the variable\n    ioda::Variable anvarVar = ogrp.vars.createWithScales<float>(\"bias_coeff_errors\",\n                       {ogrp.vars[\"npredictors\"], ogrp.vars[\"nchannels\"]}, float_params);\n    anvarVar.writeWithEigenRegular(allbcerrors);\n  }\n  oops::Log::trace() << \"ObsBiasCovariance::write is done \" << std::endl;\n}\n\n// -----------------------------------------------------------------------------\n\nvoid ObsBiasCovariance::linearize(const ObsBias & bias, const eckit::Configuration & innerConf) {\n  oops::Log::trace() << \"ObsBiasCovariance::linearize starts\" << std::endl;\n  if (bias) {\n    // Retrieve the QC flags and do statistics from second outer loop\n    const int jouter = innerConf.getInt(\"iteration\");\n    if (jouter >= 1) {\n      std::unique_ptr<ioda::Accumulator<std::vector<size_t>>> obs_num_accumulator =\n          odb_.distribution()->createAccumulator<size_t>(obs_num_.size());\n\n      // Retrieve the QC flags of previous outer loop and recalculate the number of effective obs.\n      const std::string qc_group_name = \"EffectiveQC\" + std::to_string(jouter-1);\n      const std::vector<std::string> vars = odb_.obsvariables().variables();\n      std::vector<int> qc_flags(odb_.nlocs(), 999);\n      for (std::size_t jvar = 0; jvar < vars.size(); ++jvar) {\n        if (odb_.has(qc_group_name, vars[jvar])) {\n          odb_.get_db(qc_group_name, vars[jvar], qc_flags);\n          for (std::size_t jloc = 0; jloc < qc_flags.size(); ++jloc)\n            if (qc_flags[jloc] == 0)\n              obs_num_accumulator->addTerm(jloc, jvar, 1);\n        } else {\n          throw eckit::UserError(\"Unable to find QC flags : \" + vars[jvar] + \"@\" + qc_group_name);\n        }\n      }\n\n      // Sum across the processors\n      obs_num_ = obs_num_accumulator->computeResult();\n\n      const float missing = util::missingValue(missing);\n\n      // compute the hessian contribution from Jo bias terms channel by channel\n      // retrieve the effective error (after QC) for this channel\n      const std::string err_group_name = \"EffectiveError\" + std::to_string(jouter-1);\n      ioda::ObsVector r_inv(odb_, err_group_name);\n\n      // compute \\mathrm{R}^{-1}\n      std::size_t nvars = r_inv.nvars();\n      for (size_t vv = 0; vv < nvars; ++vv) {\n        for (size_t ii = 0; ii < r_inv.nlocs(); ++ii) {\n          if (r_inv[ii*nvars + vv] != missing) {\n            r_inv[ii*nvars + vv] = 1.0f / pow(r_inv[ii*nvars + vv], 2);\n          } else {\n            r_inv[ii*nvars + vv] = 0.0f;\n          }\n        }\n      }\n\n      // compute \\mathrm{H}_\\beta^\\intercal \\mathrm{R}^{-1} \\mathrm{H}_\\beta\n      // -----------------------------------------\n      std::unique_ptr<ioda::Accumulator<std::vector<double>>> ht_rinv_h_accumulator =\n          odb_.distribution()->createAccumulator<double>(ht_rinv_h_.size());\n      for (std::size_t p = 0; p < prednames_.size(); ++p) {\n        // retrieve the predictors\n        const ioda::ObsVector predx(odb_, prednames_[p] + \"Predictor\");\n\n        // for each variable\n        ASSERT(r_inv.nlocs() == predx.nlocs());\n        std::size_t nvars = predx.nvars();\n        // only keep the diagnoal\n        for (size_t vv = 0; vv < nvars; ++vv) {\n          for (size_t ii = 0; ii < predx.nlocs(); ++ii)\n            ht_rinv_h_accumulator->addTerm(ii,\n                                           vv*prednames_.size() + p,\n                                           pow(predx[ii*nvars + vv], 2) * r_inv[ii*nvars + vv]);\n        }\n      }\n\n      // Sum the hessian contributions across the tasks\n      ht_rinv_h_ = ht_rinv_h_accumulator->computeResult();\n    }\n\n    // reset variances for bias predictor coeff. based on current data count\n    for (std::size_t j = 0; j < obs_num_.size(); ++j) {\n      if (obs_num_[j] <= minimal_required_obs_number_) {\n        for (std::size_t p = 0; p < prednames_.size(); ++p)\n          variances_[j*prednames_.size() + p] = smallest_variance_;\n      }\n    }\n\n    // set a coeff. factor for variances of control variables\n    for (std::size_t j = 0; j < vars_.size(); ++j) {\n      for (std::size_t p = 0; p < prednames_.size(); ++p) {\n        const std::size_t index = j*prednames_.size() + p;\n        preconditioner_[index] = step_size_;\n        // L = \\mathrm{A}^{-1}\n        if (obs_num_[j] > 0)\n          preconditioner_[index] = 1.0 / (1.0 / variances_[index] + ht_rinv_h_[index]);\n        if (obs_num_[j] > minimal_required_obs_number_) {\n          if (ht_rinv_h_[index] > 0.0) {\n            analysis_variances_[index] = 1.0 / (1.0 / variances_[index] + ht_rinv_h_[index]);\n          } else {\n            analysis_variances_[index] = largest_analysis_variance_;\n          }\n        }\n      }\n    }\n  }\n  oops::Log::trace() << \"ObsBiasCovariance::linearize is done\" << std::endl;\n}\n\n// -----------------------------------------------------------------------------\n\nvoid ObsBiasCovariance::multiply(const ObsBiasIncrement & dx1,\n                                 ObsBiasIncrement & dx2) const {\n  oops::Log::trace() << \"ObsBiasCovariance::multiply starts\" << std::endl;\n\n  dx2.data().array() = dx1.data().array() * variances_.array();\n\n  oops::Log::trace() << \"ObsBiasCovariance::multiply is done\" << std::endl;\n}\n\n// -----------------------------------------------------------------------------\n\nvoid ObsBiasCovariance::inverseMultiply(const ObsBiasIncrement & dx1,\n                                        ObsBiasIncrement & dx2) const {\n  oops::Log::trace() << \"ObsBiasCovariance::inverseMultiply starts\" << std::endl;\n\n  dx2.data().array() = dx1.data().array() / variances_.array();\n\n  oops::Log::trace() << \"ObsBiasCovariance::inverseMultiply is done\" << std::endl;\n}\n\n// -----------------------------------------------------------------------------\n\nvoid ObsBiasCovariance::randomize(ObsBiasIncrement & dx) const {\n  oops::Log::trace() << \"ObsBiasCovariance::randomize starts\" << std::endl;\n  if (dx) {\n    static util::NormalDistribution<double> dist(variances_.size());\n    for (std::size_t jj = 0; jj < variances_.size(); ++jj) {\n      dx.data()[jj] = dist[jj] * std::sqrt(variances_[jj]);\n    }\n  }\n  oops::Log::trace() << \"ObsBiasCovariance::randomize is done\" << std::endl;\n}\n// -----------------------------------------------------------------------------\n\nstd::unique_ptr<ObsBiasPreconditioner> ObsBiasCovariance::preconditioner() const {\n    return std::make_unique<ObsBiasPreconditioner> (preconditioner_);\n}\n\n\n// -----------------------------------------------------------------------------\n\n}  // namespace ufo\n", "meta": {"hexsha": "81c643e8cb006e5beaf03900b64a810fb36cf79a", "size": 16641, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/ufo/ObsBiasCovariance.cc", "max_stars_repo_name": "NOAA-EMC/ufo", "max_stars_repo_head_hexsha": "3bf1407731b79eab16ceff64129552577d9cfcd0", "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/ufo/ObsBiasCovariance.cc", "max_issues_repo_name": "NOAA-EMC/ufo", "max_issues_repo_head_hexsha": "3bf1407731b79eab16ceff64129552577d9cfcd0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-12-10T22:57:51.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-17T15:57:04.000Z", "max_forks_repo_path": "src/ufo/ObsBiasCovariance.cc", "max_forks_repo_name": "NOAA-EMC/ufo", "max_forks_repo_head_hexsha": "3bf1407731b79eab16ceff64129552577d9cfcd0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-10T18:38:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-11T01:36:37.000Z", "avg_line_length": 42.4515306122, "max_line_length": 100, "alphanum_fraction": 0.6225587405, "num_tokens": 4174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.278024080734104}}
{"text": "\n#include \"db/timeline.hpp\"\n\n#include <exception>\n#include <fstream>\n#include <functional>\n#include <boost/filesystem.hpp>\n\nnamespace fs = boost::filesystem;\n\nnamespace henhouse::db\n{\n    const offset_type ADD_BUCKET_BACK_LIMIT = 60;\n\n    /**\n     * This is the main function to compute the partial sums given previous bucket.\n     * It turns the current non-summed bucket into a summed bucket.\n     *\n     * current.value is assumed to be set to the count in that bucket.\n     *\n     * It computes partial sum(X) and partial sum(X^2) up the current bucket.\n     */\n    void propogate(data_item prev, data_item& current)\n    {\n        const auto v = current.value;\n        current.integral = prev.integral + v;\n        current.second_integral = prev.second_integral + (v  * v);\n    }\n\n    //Adds a count c to the current bucket and updates the partial sum\n    //values of the current bucket. \n    void update_current(data_item prev, data_item& current, count_type c)\n    {\n        current.value += c;\n        propogate(prev, current);\n    }\n\n    /**\n     *\n     * Mean is computing as the (running sum of x) / N.\n     * In addition, variance requires maintaining the running sum of x^2\n     *\n     * mean = sum(x) / N\n     * mean of squared x = sum(x^2) / N\n     *\n     * variance = (sum(x^2) / N) - (sum(x) / N )^2\n     *          = (sum(x^2) / N) - mean^2\n     *          = (mean of squared x) - mean^2\n     *          = (mean of squared x) - (mean squared)\n     */\n    diff_result diff_buckets(\n            const time_type ta,          //time from\n            const time_type tb,          //time to\n            const time_type resolution,  //resolution of time buckets\n            const offset_type index_offset,\n            const data_item a,           //bucket from\n            const data_item b,           //bucket to\n            const count_type n)          //number of buckets\n    {\n        REQUIRE_GREATER(resolution, 0);\n        REQUIRE_GREATER(n, 0);\n\n        //Sum here is the values added within \n        const auto sum = b.integral - a.integral;\n        const auto second_sum = b.second_integral - a.second_integral;\n        const auto mean = static_cast<mean_type>(sum) / n;\n        const auto mean_squared = mean * mean;\n        const auto second_mean = static_cast<mean_type>(second_sum) / n;\n        const auto variance = second_mean - mean_squared;\n\n        return diff_result \n        {\n            ta,\n            tb,\n            resolution,\n            index_offset,\n            sum,\n            mean,\n            variance,\n            n,\n            a,\n            b,\n        };\n    }\n\n    bool timeline::put(time_type t, count_type c)\n    {\n        //We already have data, let's add and index new point.\n        if(index.size() > 0)\n        {\n            const auto last_range = index.cend() - 1;\n\n            //don't add if time is before last range\n            if(t >= last_range->time) \n            {\n                //get last position only because we want to keep \n                //a specific performance profile. This is a deliberate limitation.\n                auto p = index.find_pos_from_range(t, last_range, index.cend());\n                const auto pos = p.pos + p.offset;\n\n                //bucket is current or in the past, no need to index.\n                if(pos < data.size())\n                {\n                    //if we are too far back in the range, skip it,\n                    //otherwise propogate the values up.\n                    //This limitation is to keep performance predictable for\n                    //inserts while providing a buffer for slow inserters\n                    //to catch up.\n                    if(data.size() - pos < ADD_BUCKET_BACK_LIMIT)\n                    {\n                        const auto prev = pos > 0 ? data[pos - 1] : data_item{0, 0, 0};\n                        update_current(prev, data[pos], c);\n                        for(auto p = pos + 1; p < data.size(); p++)\n                            propogate(data[p-1], data[p]);\n                    }\n                    else return false;\n                }\n                //if we move beyond end, append data \n                else\n                {\n                    const auto last_pos = data.size() - 1;\n                    const auto prev = data[last_pos];\n\n                    //don't compute integral and second_integral\n                    //because propogate will overwrite\n                    data_item current{c, 0, 0};\n                    propogate(prev, current);\n                    data.push_back(current);\n\n                    //skip if we have no gaps, otherwise index.\n                    auto new_pos = last_pos + 1;\n                    if(pos == new_pos) return true;\n\n                    //index position\n                    const auto resolution = index.meta().resolution;\n                    CHECK_GREATER(resolution, 0);\n\n                    const auto aliased_time = p.time + (p.offset * resolution);\n                    index_item index_entry = {aliased_time, new_pos};\n\n                    CHECK_LESS_EQUAL(aliased_time, t);\n                    index.push_back(index_entry);\n                }\n            }\n            else return false;\n        }\n        //We have an empty timeline, let's add initial data point and index it.\n        else\n        {\n            CHECK_EQUAL(data.size(), 0);\n\n            data_item v{c, c, c * c};\n            data.push_back(v);\n\n            index_item i = {t, 0};\n            index.push_back(i);\n        }\n\n        return true;\n    }\n\n    summary_result timeline::summary() const  \n    {\n        const auto resolution = index.meta().resolution;\n        CHECK_GREATER(resolution, 0);\n\n        if(index.empty()) return summary_result{0,0,resolution, 0,0,0,0};\n        REQUIRE(!data.empty());\n\n        const auto front = index.front();\n        const auto back = index.back();\n\n        //time of first bucket\n        const auto from = front.time;\n\n        //compute time of last bucket\n        CHECK_GREATER(data.size(), back.pos);\n        auto last_buckets = data.size() - back.pos;\n        auto to = back.time + (last_buckets * resolution);\n\n        CHECK_GREATER(to, from);\n\n        count_type n = (to - from) /  resolution;\n\n        //if we have one bucket then first is empty data item\n        auto first_bucket = data_item{0,0,0};\n        auto last_bucket = data.back();\n\n        //diff the two buckets\n        auto diff = diff_buckets(from, to, resolution, 0, first_bucket, last_bucket, n);\n        return summary_result \n        {\n            from,\n            to,\n            resolution,\n            diff.sum,\n            diff.mean,\n            diff.variance,\n            n\n        };\n    }\n\n    void clamp(pos_result& r, std::size_t size)\n    {\n        REQUIRE_LESS(r.pos, size);\n\n        const auto pos = r.pos + r.offset;\n        if(pos < size) return;\n        r.offset = size - r.pos - 1;\n\n        ENSURE_RANGE(r.pos + r.offset, 0, size);\n    }\n\n    get_result timeline::get(time_type t, const offset_type index_offset) const\n    {\n        auto p = index.find_pos(t, index_offset);\n\n        clamp(p, data.size());\n\n        // zero out data before beginning of collection\n        const bool before_beginning =  t < p.time;\n        const auto dat = before_beginning ? data_item{0,0,0} : data[p.pos + p.offset];\n\n        return get_result \n        { \n            p.index_offset,\n                t,\n                p.time, \n                p.pos,\n                p.offset,\n                dat\n        };\n    }\n\n    diff_result timeline::diff(time_type a, time_type b, const offset_type index_offset) const\n    {\n        const auto resolution = index.meta().resolution;\n        CHECK_GREATER(resolution, 0);\n\n        if(a > b) std::swap(a,b);\n        if(data.size() == 0) return diff_result{ a, b, resolution, 0, 0, 0, 0, 0, {0}, {0}};\n\n        auto ar = get(a, index_offset);\n        auto br = get(b, index_offset);\n\n        b = std::max(br.query_time, br.range_time);\n        a = std::min(ar.query_time, b);\n\n        const auto time_diff = b - a;\n        auto n = time_diff / resolution;\n\n        if(n == 0) return diff_result{ a, b, resolution, 0, 0, 0, 0, 0, ar.value, br.value};\n\n        CHECK_GREATER(n , 0);\n        CHECK_LESS_EQUAL(ar.index_offset, br.index_offset);\n        return diff_buckets(a, b, resolution, ar.index_offset, ar.value, br.value, n);\n    }\n\n    timeline from_directory(const std::string& path, const time_type resolution) \n    {\n        REQUIRE(!path.empty());\n        REQUIRE_GREATER(resolution, 0);\n\n        fs::create_directory(path);\n        if(!fs::is_directory(path))\n            throw std::runtime_error{\"path \" + path + \" is not a directory\"}; \n\n        fs::path root = path;\n\n        timeline t;\n\n        fs::path idx_data = root / \"_.i\";\n        t.index = std::move(index_type{idx_data, resolution});\n\n        fs::path cdata = root / \"_.d\";\n        t.data = std::move(data_type{cdata, DATA_SIZE});\n\n        return t;\n    }\n}\n", "meta": {"hexsha": "2f612154aa3e258693c47a7e0eab800bcb4b5bb6", "size": 8961, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/db/timeline.cpp", "max_stars_repo_name": "FoxComm/henhouse", "max_stars_repo_head_hexsha": "11d1206e954b638f0bd0cf885d0e3cb6e50c3726", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-03-26T05:37:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-25T13:55:55.000Z", "max_issues_repo_path": "src/db/timeline.cpp", "max_issues_repo_name": "FoxComm/henhouse", "max_issues_repo_head_hexsha": "11d1206e954b638f0bd0cf885d0e3cb6e50c3726", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/db/timeline.cpp", "max_forks_repo_name": "FoxComm/henhouse", "max_forks_repo_head_hexsha": "11d1206e954b638f0bd0cf885d0e3cb6e50c3726", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-06T18:42:45.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-06T18:42:45.000Z", "avg_line_length": 31.8896797153, "max_line_length": 94, "alphanum_fraction": 0.5278428747, "num_tokens": 2044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.27799504301458494}}
{"text": "/*\r\n * Copyright (c) 2011 Adrian Michel\r\n * http://www.amichel.com\r\n *\r\n * Permission to use, copy, modify, distribute and sell this \r\n * software and its documentation for any purpose is hereby \r\n * granted without fee, provided that both the above copyright \r\n * notice and this permission notice appear in all copies and in \r\n * the supporting documentation. \r\n *  \r\n * This library is distributed in the hope that it will be \r\n * useful. However, Adrian Michel makes no representations about\r\n * the suitability of this software for any purpose.  It is \r\n * provided \"as is\" without any express or implied warranty. \r\n * \r\n * Should you find this library useful, please email \r\n * info@amichel.com with a link or other reference \r\n * to your work. \r\n*/\r\n\r\n#ifndef DE_CONSTRAINTS_HPP_INCLUDED\r\n#define DE_CONSTRAINTS_HPP_INCLUDED\r\n\r\n// MS compatible compilers support #pragma once\r\n\r\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\r\n#pragma once\r\n#endif\r\n\r\n#include <set>\r\n#include <boost/tokenizer.hpp>\r\n#include <boost/algorithm/string.hpp>\r\n#include <boost/format.hpp>\r\n#include <boost/make_shared.hpp>\r\n#include <boost/lexical_cast.hpp>\r\n\r\n#include \"random_generator.hpp\"\r\n#include \"de_types.hpp\"\r\n\r\nnamespace de\r\n{\r\n\r\n/**\r\n * Exception thrown in case of a constraint error\r\n * \r\n * @author adrian (12/1/2011)\r\n */\r\nclass constraints_exception : public exception\r\n{\r\npublic:\r\n\t/**\r\n\t * constructor that takes the error message as argument\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @param message \r\n\t */\r\n\tconstraints_exception( const std::string& message )\r\n\t: exception( message.c_str() )\r\n\t{\r\n\t}\r\n};\r\n\r\n/**\r\n * Abstract base class for concrete constraint classes \r\n *  \r\n * A constraint class describes certain characteristics and \r\n * limits of the input variables fed to the objective function. \r\n * \r\n * @author adrian (12/1/2011)\r\n */\r\nclass constraint\r\n{\r\npublic:\r\n\tvirtual ~constraint(){}\r\n\r\n\t/**\r\n\t * returns a random value limited to the type and range of the \r\n\t * constraint\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tvirtual double get_rand_value() = 0;\r\n\r\n\t/**\r\n\t * returns a random value limited to the type and range of the \r\n\t * constraint based on a previous value and an origin (see \r\n\t * specific implementation in derived classes) \r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @param value \r\n\t * @param origin \r\n\t * \r\n\t * @return double \r\n\t */\r\n\tvirtual double get_rand_value( double value, double origin ) = 0;\r\n\r\n\t/**\r\n\t * returns the min limit of the range\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tvirtual double min() const = 0;\r\n\r\n\t/**\r\n\t * returns the max limit of the range\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tvirtual double max() const = 0;\r\n\r\n\t/**\r\n\t * Gets a random value within the limits set for the constraint, \r\n\t * but further limited to a range defined by its origin and the \r\n\t * width of the zone around this origin in pct of the total \r\n\t * width \r\n\t * \r\n\t * @author adrian (12/13/2011)\r\n\t * \r\n\t * @param origin the origin (center) of the zone further \r\n\t *  \t\t\t limiting the constraint\r\n\t * @param zonePct the width of the zone in pct of the total \r\n\t *  \t\t\t  width, around the origin\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tvirtual double get_rand_value_in_zone( double origin, double zonePct ) const = 0;\r\n\r\n\t/**\r\n\t * Gets the point midway between min and max - will only work \r\n\t * for range constraints \r\n\t * \r\n\t * @author adrian (12/16/2011)\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tvirtual double get_middle_point() = 0;\r\n};\r\n\r\n/**\r\n * A smart pointer to a Constraint\r\n */\r\ntypedef boost::shared_ptr< constraint > constraint_ptr;\r\n\r\n/**\r\n * Base class for constraints that are range based. Each such \r\n * constraint has a min and a max value \r\n * \r\n * @author adrian (12/1/2011)\r\n */\r\nclass range_constraint : public constraint\r\n{\r\nprivate:\r\n\tdouble m_min;\r\n\tdouble m_max;\r\n\r\npublic:\r\n\r\n\t/**\r\n\t * constructor that takes the min and max limits of the range\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @param min \r\n\t * @param max \r\n\t */\r\n\trange_constraint( double min, double max )\r\n\t: m_min( min ), m_max( max )\r\n\t{\r\n\t\tassert( min <= max );\r\n\t}\r\n\r\n\t/**\r\n\t * returns the min limit of the range\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tdouble min() const { return m_min; }\r\n\r\n\t/**\r\n\t * returns the max limit of the range\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tdouble max() const { return m_max; }\r\n\r\n};\r\n\r\n/**\r\n * A real constraint. Specifies that variables can have any \r\n * double value, whitin the specified limits. \r\n * \r\n * @author adrian (12/1/2011)\r\n */\r\nclass real_constraint : public range_constraint\r\n{\r\npublic:\r\n\r\n\t/**\r\n\t * constructor that takes the min and max limit of the real \r\n\t * constraint \r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @param min \r\n\t * @param max \r\n\t */\r\n\treal_constraint( double min, double max )\r\n\t: range_constraint( min, max )\r\n\t{\r\n\t\tassert( min <= max );\r\n\t}\r\n\r\n\t/**\r\n\t * returns a random value limited to the type and range of the \r\n\t * constraint\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tdouble get_rand_value()\r\n\t{\r\n\t\treturn genrand( range_constraint::min(), range_constraint::max() );\r\n\t}\r\n\r\n\t/**\r\n\t * returns a random value limited to the type and range of the \r\n\t * constraint based on a previous value and an origin\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @param value \r\n\t * @param origin \r\n\t * \r\n\t * @return double \r\n\t */\r\n\tdouble get_rand_value( double value, double origin )\r\n\t{\r\n\t\tdouble ret = value;\r\n\r\n\t\twhile( ret < range_constraint::min() )\r\n\t\t{\r\n\t\t\tret = range_constraint::min() + genrand() * ( origin - range_constraint::min() );\r\n\t\t}\r\n\r\n\t\twhile( ret > range_constraint::max() )\r\n\t\t{\r\n\t\t\tret = range_constraint::max() + genrand() * ( origin - range_constraint::max() );\r\n\t\t}\r\n\r\n\t\treturn ret;\r\n\t}\r\n\r\n\tvirtual double get_rand_value_in_zone( double origin, double zonePct ) const\r\n\t{\r\n\t\tif( origin > max() )\r\n\t\t\tthrow constraints_exception( \"origin coordinate > max\" );\r\n\t\tif( origin < min() )\r\n\t\t\tthrow constraints_exception( \"origin coordinate < min\" );\r\n\r\n\t\tif( zonePct > 100.0 )\r\n\t\t\tthrow constraints_exception( \"zonePct > 100%\" );\r\n\r\n\t\tif( zonePct < 0 )\r\n\t\t\tthrow constraints_exception( \"zonePct < 0%\" );\r\n\r\n\t\tif( zonePct == 0 )\r\n\t\t\tthrow constraints_exception( \"zonePct == 0%\" );\r\n\r\n\t\tdouble zoneSize = ( max() - min() ) * zonePct / 100.0;\r\n\r\n\t\tdouble _min = std::max( min(), origin - zoneSize/2.0 );\r\n\t\tdouble _max = std::min( max(), origin + zoneSize/2.0 );\r\n\r\n\t\treturn genrand( _min, _max );\r\n\t}\r\n\r\n\tvirtual double get_middle_point()\r\n\t{\r\n\t\treturn ( max() + min() )/2.0;\r\n\t}\r\n\r\n};\r\n\r\n/**\r\n * An integer constraint. Specifies that variables can have any \r\n * integer values within the specified limits. \r\n * \r\n * @author adrian (12/1/2011)\r\n */\r\nclass int_constraint : public range_constraint\r\n{\r\npublic:\r\n\t/**\r\n\t * constructor that takes the min and max limit of the integer \r\n\t * constraint \r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @param min \r\n\t * @param max \r\n\t */\r\n\tint_constraint( double min, double max )\r\n\t: range_constraint( min, max )\r\n\t{\r\n\t\tassert( min <= max );\r\n\t}\r\n\r\n\t/**\r\n\t * returns a random value limited to the type and range of the \r\n\t * constraint\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tdouble get_rand_value()\r\n\t{\r\n\t\treturn genintrand( range_constraint::min(), range_constraint::max() );\r\n\t}\r\n\r\n\t/**\r\n\t * returns a random value limited to the type and range of the \r\n\t * constraint based on a previous value and an origin\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @param value \r\n\t * @param origin \r\n\t * \r\n\t * @return double \r\n\t */\r\n\tdouble get_rand_value( double value, double origin )\r\n\t{\r\n\t\tdouble ret = boost::math::round( value );\r\n\r\n\t\twhile( ret < range_constraint::min() )\r\n\t\t{\r\n\t\t\tret = range_constraint::min() + genrand() * ( origin - range_constraint::min() );\r\n\t\t\tret = boost::math::round( ret );\r\n\t\t}\r\n\r\n\t\twhile( ret > range_constraint::max() )\r\n\t\t{\r\n\t\t\tret = range_constraint::max() + genrand() * ( origin - range_constraint::max() );\r\n\t\t\tret = boost::math::round( ret );\r\n\t\t}\r\n\r\n\t\treturn ret;\r\n\t}\r\n\r\n\tvirtual double get_rand_value_in_zone( double origin, double zonePct ) const\r\n\t{\r\n\t\tif ( origin > max() )\r\n\t\t\tthrow constraints_exception( \"origin coordinate > max\" );\r\n\t\tif ( origin < min() )\r\n\t\t\tthrow constraints_exception( \"origin coordinate < min\" );\r\n\r\n\t\tif ( zonePct > 100.0 )\r\n\t\t\tthrow constraints_exception( \"zonePct > 100%\" );\r\n\r\n\t\tif( zonePct < 0 )\r\n\t\t\tthrow constraints_exception( \"zonePct < 0%\" );\r\n\r\n\t\tif( zonePct == 0  )\r\n\t\t\tthrow constraints_exception( \"zonePct == 0%\" );\r\n\r\n\t\tdouble zoneSize = ( max() - min() ) * zonePct/100.0;\r\n\r\n\t\tdouble _min = std::max( min(), origin - zoneSize/2.0 );\r\n\t\tdouble _max = std::min( max(), origin + zoneSize/2.0 );\r\n\r\n\t\tdouble val = boost::math::round( genrand( _min, _max ) );\r\n\r\n\t\tfor ( ;val < _min || val > _max; val = boost::math::round( genrand( _min, _max ) ) );\r\n\r\n\t\treturn val;\r\n\t}\r\n\r\n\tvirtual double get_middle_point()\r\n\t{\r\n\t\treturn boost::math::round( ( max() - min() )/2.0 );\r\n\t}\r\n\r\n\r\n};\r\n\r\n/**\r\n * A set constraint. Specifies that variables can take any \r\n * values from a predefined set. Doesn't require min or max. \r\n *  \r\n * Note that duplicate values will be removed\r\n * \r\n * @author adrian (12/1/2011)\r\n */\r\nclass set_constraint : public constraint\r\n{\r\nprivate:\r\n\tclass unique : public std::unary_function < Double, bool >\r\n\t{\r\n\tpublic:\r\n\t\tbool operator ()( Double d ) const  \r\n\t\t{\r\n\t\t\treturn m_unique.insert( d ).second;\r\n\t\t}\r\n\r\n\tpublic:\r\n\t\tdouble min() const \r\n\t\t{ \r\n\t\t\tif( m_unique.size() > 0 )\r\n\t\t\t\treturn *m_unique.begin(); \r\n\t\t\telse\r\n\t\t\t\tthrow constraints_exception( \"could not get the min value of an empty set constraint\" );\r\n\t\t}\r\n\r\n\t\tdouble max() const \r\n\t\t{ \r\n\t\t\tif( m_unique.size() > 0 )\r\n\t\t\t\treturn *m_unique.rbegin(); \r\n\t\t\telse\r\n\t\t\t\tthrow constraints_exception( \"could not get the max value of an empty set constraint\" );\r\n\t\t}\r\n\r\n\tprivate:\r\n\t\tmutable std::set< Double > m_unique;\r\n\t};\r\nprivate:\r\n\tunique m_unique;\r\n\tde::DVector m_values;\r\n\r\npublic:\r\n\t/**\r\n\t * Constructs the set from a vector of Double values, and \r\n\t * removes duplicates to ensure a uniform distribution for \r\n\t * randomization \r\n\t * \r\n\t * @author adrian (12/10/2011)\r\n\t * \r\n\t * @param values \r\n\t */\r\n\tset_constraint( const de::DVector& values )\r\n\t{\r\n\t\t// making sure the values in the \"set\" are unique\r\n\t\tstd::remove_copy_if (values.begin (), values.end (), std::back_inserter( m_values ), m_unique );\r\n\t}\r\n\r\n\t/**\r\n\t * adds an individual value to the \"set\", won't create duplicate \r\n\t * values. \r\n\t * \r\n\t * @author adrian (12/10/2011)\r\n\t * \r\n\t * @param value \r\n\t */\r\n\tvoid add_value( de::Double value )\r\n\t{\r\n\t\tif( m_unique( value ) )\r\n\t\t\tm_values.push_back( value );\r\n\t}\r\n\r\n\t/**\r\n\t * returns a value randomly chosen from the set of available \r\n\t * values \r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tvirtual double get_rand_value()\r\n\t{\r\n\t\tde::DVector::size_type index( genintrand( 0, m_values.size() - 1 ) );\r\n\r\n\t\treturn m_values[ index ];\r\n\t}\r\n\r\n\t/**\r\n\t * returns a value randomly chosen from the set of available \r\n\t * values \r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tvirtual double get_rand_value(double value, double origin)\r\n\t{\r\n\t\treturn get_rand_value();\r\n\t}\r\n\r\n\t/**\r\n\t * returns the min limit of the range\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tdouble min() const\r\n\t{\r\n\t\treturn m_unique.min();\r\n\t}\r\n\r\n\t/**\r\n\t * returns the max limit of the range\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tdouble max() const\r\n\t{\r\n\t\treturn m_unique.max();\r\n\t}\r\n\r\n\tvirtual double get_rand_value_in_zone( double origin, double zonePct ) const\r\n\t{\r\n\t\tthrow constraints_exception( \"get_rand_value_in_zone only supported for range constraints\" );\r\n\t}\r\n\r\n\tvirtual double get_middle_point()\r\n\t{\r\n\t\tthrow constraints_exception( \"get_middle_point not supported by set constraint\" );\r\n\t}\r\n\r\n};\r\n\r\n/**\r\n * A boolean constraint. Specifies that variables can take a \r\n * boolean value - true or false. \r\n * \r\n * @author adrian (12/1/2011)\r\n */\r\nclass boolean_constraint : public constraint\r\n{\r\npublic:\r\n\t/**\r\n\t * returns a random boolean value\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tvirtual double get_rand_value()\r\n\t{\r\n\t\treturn genrand() < 0.5;\r\n\t}\r\n\r\n\t/**\r\n\t * returns a random boolean value\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tvirtual double get_rand_value(double value, double origin)\r\n\t{\r\n\t\treturn get_rand_value();\r\n\t}\r\n\r\n\t/**\r\n\t * returns the min limit of the range\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tdouble min() const\r\n\t{\r\n\t\treturn 0;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the max limit of the range\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tdouble max() const\r\n\t{\r\n\t\treturn 1;\r\n\t}\r\n\r\n\tvirtual double get_rand_value_in_zone( double origin, double zonePct ) const\r\n\t{\r\n\t\tthrow constraints_exception( \"get_rand_value_in_zone only supported for range constraints\" );\r\n\t}\r\n\r\n\tvirtual double get_middle_point()\r\n\t{\r\n\t\tthrow constraints_exception( \"get_middle_point not supported by bool constraint\" );\r\n\t}\r\n\r\n};\r\n\r\ntypedef std::vector< constraint_ptr > constraints_base;\r\n\r\n/**\r\n * A collection of constraints, implemented as a vector. \r\n *  \r\n * Is used to define the constraints for all variables used \r\n * during an optimization session. \r\n * \r\n * @author adrian (12/1/2011)\r\n */\r\nclass constraints : public constraints_base\r\n{\r\nprivate:\r\n\ttypedef boost::char_separator< char > separator;\r\n\ttypedef boost::tokenizer< separator > tokenizer;\r\n\t\r\n\r\npublic:\r\n\t/**\r\n\t * Initializes a collection of constraints with default values. \r\n\t * All constraints are of type real and have the same default \r\n\t * min and max. \r\n\t * \r\n\t * @author adrian (12/1/2011)\r\n\t * \r\n\t * @param varCount number of constraints\r\n\t * @param defMin default min limit\r\n\t * @param defMax default max limit\r\n\t */\r\n\tconstraints( size_t varCount, double defMin, double defMax )\r\n\t: constraints_base( varCount, boost::make_shared< real_constraint >( defMin, defMax ) )\r\n\t{\r\n\t}\r\n\r\n\t/**\r\n\t * Initializes a collection of constraints from string \r\n\t * descsriptions. Currently used only for range based \r\n\t * constraints. \r\n\t *  \r\n\t * A constraint can be described as \"type;min;max\" where type \r\n\t * can be real or integer and min and max are the range limits.\r\n\t * \r\n\t * @author adrian (12/1/2011)\r\n\t * \r\n\t * @param str a a collection (vector) of constraint description\r\n\t *  \t\t  strings, each string describing constraints for\r\n\t *  \t\t  one variable\r\n\t * @param var_count the total number of variables (can be \r\n\t *  \t\t\t   different than the number of strings). If\r\n\t *  \t\t\t   there are more variables than strings, the\r\n\t *  \t\t\t   extra constraints are set to be real and use\r\n\t *  \t\t\t   the default min and max arguments for the\r\n\t *  \t\t\t   range\r\n\t * @param def_min default min value in case the number of \r\n\t *  \t\t\t variables is higher than the number of\r\n\t *  \t\t\t constraints specified as strings.\r\n\t * @param def_max default max value in case the number of \r\n\t *  \t\t\t variables is higher than the number of\r\n\t *  \t\t\t constraints specified as strings.\r\n\t */\r\n\tconstraints( const std::vector< std::string >& str, size_t var_count , double def_min, double def_max )\r\n\t: constraints_base( var_count, boost::make_shared< real_constraint >( def_min, def_max ) )\r\n\t{\r\n\t\tfor( std::vector< std::string >::size_type i = 0; i < str.size(); ++i )\r\n\t\t{\r\n\t\t\ttokenizer tokens( str[ i ], separator( \";,\" ) );\r\n\r\n\t\t\tstd::string type;\r\n\t\t\tdouble _min;\r\n\t\t\tdouble _max;\r\n\r\n\t\t\tsize_t count( 0 );\r\n\r\n\t\t\tfor( tokenizer::const_iterator j = tokens.begin(); j != tokens.end(); ++j, ++count )\r\n\t\t\t{\r\n\t\t\t\tconst std::string token( boost::trim_copy( *j ) );\r\n\r\n\t\t\t\ttry\r\n\t\t\t\t{\r\n\t\t\t\t\tswitch( count )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcase 0:\r\n\t\t\t\t\t\t\ttype = token;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\tcase 1:\r\n\t\t\t\t\t\t\t_min = boost::lexical_cast< double >( token.c_str() );\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\tcase 2:\r\n\t\t\t\t\t\t\t_max = boost::lexical_cast< double >( token.c_str() );\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\tdefault:\r\n\t\t\t\t\t\t\t// too many fields\r\n\t\t\t\t\t\t\tthrow constraints_exception( ( boost::format( \"wrong variable format in \\\"%1%\\\" - too many fields\" ) % str[ i ] ).str() );\r\n\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tcatch( const boost::bad_lexical_cast& )\r\n\t\t\t\t{\r\n\t\t\t\t\tthrow constraints_exception( ( boost::format( \"wrong floating point number format: %1%\") % token ).str() );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t// too few fields\r\n\t\t\tif( count < 3 )\r\n\t\t\t\tthrow constraints_exception( ( boost::format( \"wrong variable format in \\\"%1%\\\" - too few fields\" ) % str[ i ] ).str() );\r\n\r\n\t\t\tif( i < var_count )\r\n\t\t\t\tconstraints_base::at( i ) = str_to_constraint( type, _min, _max );\r\n\t\t\telse\r\n\t\t\t\tconstraints_base::push_back( str_to_constraint( type, _min, _max ) );\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * returns a random value limited to the type and range of the \r\n\t * constraint\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tdouble get_rand_value( size_t index )\r\n\t{\r\n\t\tif( index < constraints_base::size() )\r\n\t\t\treturn (*this)[ index ]->get_rand_value();\r\n\t\telse\r\n\t\t\tthrow constraints_exception( ( boost::format( \"invalid constraint index: %1%, higher than max number of constraints: %2%\" ) % index % constraints_base::size() ).str() );\r\n\t}\r\n\r\n\t/**\r\n\t * returns a random value limited to the type and range of the \r\n\t * constraint based on a previous value and an origin\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t *  \r\n\t * @param index the constraint index \r\n\t * @param value previous value\r\n\t * @param origin origin\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tdouble get_rand_value( size_t index, double value, double origin )\r\n\t{\r\n\t\tif( index < constraints_base::size() )\r\n\t\t\treturn (*this)[ index ]->get_rand_value( value, origin );\r\n\t\telse\r\n\t\t\tthrow constraints_exception( ( boost::format( \"invalid constraint index: %1%, higher than max number of constraints: %2%\" ) % index % constraints_base::size() ).str() );\r\n\t}\r\n\r\n\t/**\r\n\t * Generates a set of random values within a \"hypercube\" region\r\n\t * defined by an origin and an area expressed as a percentage of \r\n\t * the entire range \r\n\t * \r\n\t * @author adrian (12/13/2011)\r\n\t * \r\n\t * @param origin the origin coordinates of the region\r\n\t * @param sidePct the side of the hypercube in pct of the entire \r\n\t *  \t\t\t  side\r\n\t * \r\n\t * @return DVectorPtr \r\n\t */\r\n\tDVectorPtr get_square_zone_rand_values( const DVectorPtr origin, double sidePct ) const\r\n\t{\r\n\t\tassert( origin );\r\n\t\tassert( sidePct > 0 && sidePct <= 100 );\r\n\r\n\t\tif( origin->size() == constraints_base::size() )\r\n\t\t{\r\n\t\t\tDVectorPtr square( boost::make_shared< DVector >( origin->size() ) );\r\n\r\n\t\t\tfor( constraints_base::size_type n = 0; n < constraints_base::size(); ++n )\r\n\t\t\t\t(*square)[ n ] = (*this)[ n ]->get_rand_value_in_zone( (*origin)[ n ], sidePct );\r\n\r\n\t\t\treturn square;\r\n\r\n\t\t}\r\n\t\telse\r\n\t\t\tthrow constraints_exception( \"The origin vector must have the same number of elements as there are constraints\" );\r\n\t}\r\n\r\n\tDVectorPtr get_middle_point()\r\n\t{\r\n\t\tDVectorPtr r( boost::make_shared< DVector >( constraints_base::size() ) );\r\n\r\n\t\tfor( constraints_base::size_type n = 0; n < constraints_base::size(); ++n )\r\n\t\t\t(*r)[ n ] = (*this)[ n ]->get_middle_point();\r\n\r\n\t\treturn r;\r\n\r\n\t}\r\n\r\n\t/**\r\n\t * Get a set of random values within the limits set by the \r\n\t * constraints \r\n\t * \r\n\t * @author adrian (12/13/2011)\r\n\t * \r\n\t * @return DVectorPtr \r\n\t */\r\n\tDVectorPtr get_rand_values() const\r\n\t{\r\n\t\tDVectorPtr r( boost::make_shared< DVector >( constraints_base::size() ) );\r\n\r\n\t\tfor( constraints_base::size_type n = 0; n < constraints_base::size(); ++n )\r\n\t\t\t(*r)[ n ] = (*this)[ n ]->get_rand_value();\r\n\r\n\t\treturn r;\r\n\t}\r\n\r\n\r\nprivate:\r\n\tconstraint_ptr str_to_constraint( const std::string& type, double min, double max )\r\n\t{\r\n\t\tif( boost::to_lower_copy( type ) == \"real\" )\r\n\t\t\treturn boost::make_shared< real_constraint >( min, max );\r\n\t\telse if( boost::to_lower_copy( type ) == \"int\" || boost::to_lower_copy( type ) == \"integer\" )\r\n\t\t\treturn boost::make_shared< int_constraint >( min, max );\r\n\t\telse\r\n\t\t\tthrow constraints_exception( ( boost::format( \"invalid constraint type \\\"%1%\\\"\" ) % type ).str() );\r\n\t}\r\n};\r\n\r\ntypedef boost::shared_ptr< constraints > constraints_ptr;\r\n\r\n}\r\n\r\n#endif //DE_CONSTRAINTS_HPP_INCLUDED\r\n", "meta": {"hexsha": "25463d470cd755be4e96635e18bd0c2dd30ba344", "size": 20363, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/de/de_constraints.hpp", "max_stars_repo_name": "gchoinka/gpcxx", "max_stars_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2015-05-15T08:01:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T07:28:54.000Z", "max_issues_repo_path": "third_party/de/de_constraints.hpp", "max_issues_repo_name": "gchoinka/gpcxx", "max_issues_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-03-26T23:48:04.000Z", "max_issues_repo_issues_event_max_datetime": "2016-02-29T14:16:37.000Z", "max_forks_repo_path": "third_party/de/de_constraints.hpp", "max_forks_repo_name": "gchoinka/gpcxx", "max_forks_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-02-12T21:39:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-01T05:14:08.000Z", "avg_line_length": 24.4160671463, "max_line_length": 173, "alphanum_fraction": 0.6229926828, "num_tokens": 5473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832354982647, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.2779104904637335}}
{"text": "// 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// this project is translated from this project : digraph [https://github.com/damian0815/digraph]\r\n\r\n//  Author:  MingXing Liu\r\n//  Date:    2017-12-25\r\n//  version:\r\n//  v0.1\r\n//  1.init verion\r\n\r\n#ifndef BOOST_GRAPH_SUGIYAMA_LAYOUT_HPP\r\n#define BOOST_GRAPH_SUGIYAMA_LAYOUT_HPP\r\n\r\n#include <math.h>\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/simple_point.hpp>\r\n#include <boost/graph/circle_layout.hpp>\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/graph/iteration_macros.hpp>\r\n#include <boost/graph/topological_sort.hpp>\r\n#include <boost/static_assert.hpp>\r\n#include <boost/unordered_map.hpp>\r\n#include <boost/property_map/property_map.hpp>\r\n\r\nnamespace boost {\r\n\r\nstatic const int    MAX_SWEEPS = 100;\r\n\r\ntemplate<typename GraphType>\r\nstatic void splitIntoLayers(const GraphType& g,\r\n                            std::vector<std::vector<typename graph_traits<GraphType>::vertex_iterator>> &layers,\r\n                            std::map<typename graph_traits<GraphType>::vertex_iterator, int> &nodemap) {\r\n    typedef typename graph_traits<GraphType>::vertex_iterator   Viter;\r\n    typedef typename graph_traits<GraphType>::vertex_descriptor VertexDescriptor;\r\n    typedef typename graph_traits<GraphType>::out_edge_iterator OutEdgeIter;\r\n\r\n    typedef std::deque< VertexDescriptor > V_VEC;\r\n    V_VEC sorted;\r\n    topological_sort(g, std::front_inserter(sorted));\r\n\r\n    std::map<VertexDescriptor, int> lmap;\r\n    for (typename V_VEC::value_type &vt:sorted){\r\n        lmap[vt] = 0;\r\n    }\r\n\r\n    int h = 1;\r\n    for (typename V_VEC::iterator it = sorted.begin(); it != sorted.end(); ++it )\r\n    {\r\n        VertexDescriptor n1 = *it;\r\n\r\n        OutEdgeIter out, out_end;\r\n        tie(out, out_end) = out_edges(n1, g);\r\n        for(; out != out_end; ++out){\r\n            VertexDescriptor n2=target(*out,g);\r\n\r\n            int inc = 1;\r\n            lmap[n2] = std::max(lmap[n1] + inc, lmap[n2]);\r\n            h = std::max(h, lmap[n2] + 1);\r\n        }\r\n    }\r\n\r\n    //stack_init(h, (int)sorted.size());\r\n    layers.resize(h);\r\n\r\n    Viter n, nend;\r\n    tie(n,nend) = vertices(g);\r\n    for (typename V_VEC::value_type &vt:sorted){\r\n        //stack_add(n+vt, lmap[vt]);\r\n        int layerIndex=lmap[vt];\r\n\r\n        layers[layerIndex].push_back(n+vt);\r\n        nodemap[n+vt] = layerIndex;\r\n    }\r\n}\r\n\r\ntemplate<typename GraphType,typename IndexMap>\r\nstatic void setOrderedIndexes(IndexMap &index,\r\n                       std::vector<typename graph_traits<GraphType>::vertex_iterator>& ln) {\r\n    for (int i = 0; i < ln.size(); i++) {\r\n        index[*(ln[i])]=i;\r\n    }\r\n}\r\n\r\ntemplate<typename GraphType,typename RectMap>\r\nstatic double maxHeight(RectMap &rect,\r\n                 const std::vector<typename graph_traits<GraphType>::vertex_iterator> &ln) {\r\n    typedef typename graph_traits<GraphType>::vertex_iterator   Viter;\r\n\r\n    double mh = 0;\r\n    for (typename std::vector<Viter>::const_iterator it = ln.begin(); it != ln.end(); ++it ) {\r\n        Viter n = (*it);\r\n        mh = std::max(mh, (double)(rect[*n][1]));\r\n    }\r\n    return mh;\r\n}\r\n\r\ntemplate<typename GraphType,typename PositionMap,typename RectMap>\r\nstatic double avgX(PositionMap &position,\r\n            RectMap &rect,\r\n            const std::vector<typename graph_traits<GraphType>::vertex_iterator>& ln) {\r\n    typedef typename graph_traits<GraphType>::vertex_iterator   Viter;\r\n\r\n    double m = 0;\r\n    for (typename std::vector<Viter>::const_iterator it = ln.begin(); it != ln.end(); ++it ) {\r\n        Viter n = *it;\r\n        m += (position[*n][0]+rect[*n][0]/2);\r\n    }\r\n    return m / ln.size();\r\n}\r\n\r\ntemplate<typename GraphType,typename IndexMap>\r\nstatic int barycenter( IndexMap &index,\r\n                const std::vector<typename graph_traits<GraphType>::vertex_iterator>& ln) {\r\n    typedef typename graph_traits<GraphType>::vertex_iterator   Viter;\r\n\r\n    if (ln.size() == 0) {\r\n        return 0;\r\n    }\r\n\r\n    double bc = 0;\r\n    for (typename std::vector<Viter>::const_iterator it = ln.begin(); it != ln.end(); ++it ) {\r\n        Viter n = *it;\r\n\r\n        bc += index[*n];\r\n    }\r\n    return (int) floor((bc / ln.size())+0.5f);\r\n}\r\n\r\ntemplate<typename GraphType>\r\nstd::vector<typename graph_traits<GraphType>::vertex_iterator>\r\nstatic stack_getConnectedTo(const GraphType& g,\r\n                     std::vector<std::vector<typename graph_traits<GraphType>::vertex_iterator>> &layers,\r\n                     typename graph_traits<GraphType>::vertex_iterator n1,\r\n                     int layerIndex) {\r\n    typedef typename graph_traits<GraphType>::vertex_iterator        Viter;\r\n    typedef typename boost::graph_traits<GraphType>::edge_descriptor EdgeDescriptor;\r\n\r\n    std::vector<Viter> ln;\r\n    if (layerIndex < layers.size() && layerIndex >= 0) {\r\n        for (typename std::vector<Viter>::iterator it = layers.at(layerIndex).begin(); it != layers.at(layerIndex).end(); ++it )\r\n        {\r\n            Viter n2 = *it;\r\n            std::pair<EdgeDescriptor, bool> test1 = edge(*n1, *n2, g);\r\n            if (test1.second == true) { // 判断vd1和vd2所指的两节点是否相邻\r\n                ln.push_back(n2);\r\n            }\r\n\r\n            /*std::pair<EdgeDescriptor, bool> test2 = edge( *n2,*n1, g);\r\n              if (test2.second == true) { // 判断vd1和vd2所指的两节点是否相邻\r\n                 ln.push_back(n2);\r\n             }*/\r\n        }\r\n    }\r\n    return ln;\r\n}\r\n\r\ntemplate<typename GraphType,typename IndexMap>\r\nstatic void stack_reduceCrossings2L(const GraphType& g,\r\n                             std::vector<std::vector<typename graph_traits<GraphType>::vertex_iterator>> &layers,\r\n                             IndexMap &index,\r\n                             int staticIndex, int flexIndex) {\r\n    typedef typename graph_traits<GraphType>::vertex_iterator   Viter;\r\n\r\n    assert( flexIndex < layers.size() );\r\n    std::vector<Viter>& flex = layers[flexIndex];\r\n    for (typename std::vector<Viter>::const_iterator it = flex.begin(); it != flex.end(); ++it )\r\n    {\r\n        Viter n = (*it);\r\n        std::vector<Viter> neighbors = stack_getConnectedTo(g,layers,n, staticIndex);\r\n\r\n        index[*n]=barycenter<GraphType>(index,neighbors);\r\n    }\r\n\r\n    sort( flex.begin(), flex.end(),  [&index]( Viter& n1,  Viter& n2 )->bool{\r\n        return index[*n1]< index[*n2];\r\n    });\r\n\r\n    setOrderedIndexes<GraphType>(index,flex);\r\n}\r\n\r\ntemplate<typename GraphType,typename PositionMap,typename RectMap>\r\nstatic void stack_layerHeights(std::vector<std::vector<typename graph_traits<GraphType>::vertex_iterator>> &layers,\r\n                        PositionMap &position,\r\n                        RectMap &rect,\r\n                        int &yspacing) {\r\n    typedef typename graph_traits<GraphType>::vertex_iterator   Viter;\r\n\r\n    double offset = 0;\r\n    for (int l = 0; l < layers.size(); l++) {\r\n        std::vector<Viter>& ln = layers[l];\r\n        double maxh = maxHeight<GraphType>(rect,ln);\r\n        for (typename std::vector<Viter>::iterator it = ln.begin(); it != ln.end(); ++it ) {\r\n            Viter n = (*it);\r\n            //if (n->isVirtual()) {\r\n            if (false) {\r\n                position[*n][1]=offset+maxHeight<GraphType>(rect,ln)/2.0;\r\n            } else {\r\n                position[*n][1]=offset;\r\n            }\r\n        }\r\n        offset += maxh + yspacing;\r\n    }\r\n}\r\n\r\ntemplate<typename GraphType, typename PositionMap,typename RectMap>\r\nstatic void stack_xPosPack(std::vector<std::vector<typename graph_traits<GraphType>::vertex_iterator>> &layers,\r\n                    PositionMap &position,\r\n                    RectMap &rect,\r\n                    int flexIndex,\r\n                    int &xspacing) {\r\n    typedef typename graph_traits<GraphType>::vertex_iterator   Viter;\r\n\r\n    assert( flexIndex < layers.size() );\r\n    std::vector<Viter>& flex = layers[flexIndex];\r\n    double offset = 0;\r\n    for (typename std::vector<Viter>::const_iterator it = flex.begin(); it != flex.end(); ++it ) {\r\n        Viter n = (*it);\r\n        position[*n][0]=offset;\r\n        offset = position[*n][0] + rect[*n][0] + xspacing;\r\n    }\r\n}\r\n\r\ntemplate<typename GraphType, typename PositionMap,typename RectMap>\r\nstatic  void stack_xPosDown(const GraphType& g,\r\n                    PositionMap &position,\r\n                    RectMap &rect,\r\n                    std::vector<std::vector<typename graph_traits<GraphType>::vertex_iterator>> &layers,\r\n                    int staticIndex, int flexIndex,\r\n                    int &xspacing) {\r\n    typedef typename graph_traits<GraphType>::vertex_iterator   Viter;\r\n\r\n    assert( flexIndex < layers.size() );\r\n    std::vector<Viter> flex = layers[flexIndex];\r\n    for (int i = 0; i < flex.size(); i++) {\r\n        Viter n = flex[i];\r\n        std::vector<Viter> neighbors = stack_getConnectedTo(g,layers,n, staticIndex);\r\n        double avg = avgX<GraphType>(position,rect,neighbors);\r\n        double min = (i > 0) ? (position[*(flex[i-1])][0] + rect[*(flex[i-1])][0] + xspacing) : (-std::numeric_limits<double>::max());\r\n        if (!isnan(avg)) {\r\n            position[*n][0]= std::max(min, avg -  rect[*n][0]/2.0);\r\n        }\r\n    }\r\n}\r\n\r\ntemplate<typename GraphType, typename PositionMap,typename RectMap>\r\nstatic  void stack_xPosUp(const GraphType& g,\r\n                  PositionMap &position,\r\n                  RectMap &rect,\r\n                  std::vector<std::vector<typename graph_traits<GraphType>::vertex_iterator>> &layers,\r\n                  int staticIndex, int flexIndex,\r\n                  int &xspacing) {//staticIndex=flexIndex+1\r\n    typedef typename graph_traits<GraphType>::vertex_iterator   Viter;\r\n\r\n    assert( flexIndex < layers.size() );\r\n    std::vector<Viter> flex = layers[flexIndex];\r\n    for (int i = flex.size() - 1; i >= 0; i--) {\r\n        Viter n = flex[i];\r\n        std::vector<Viter> neighbors = stack_getConnectedTo(g,layers,n, staticIndex);\r\n\r\n        //for ( int i=0; i<neighbors.size() ;i++ )\r\n        double avg = avgX<GraphType>(position,rect,neighbors);\r\n        // calculate min, max\r\n        double min = (i>0)?(position[*(flex[i-1])][0] + rect[*(flex[i-1])][0] + xspacing) : -std::numeric_limits<double>::max();\r\n        double max =std::numeric_limits<double>::max();\r\n        if(i<flex.size()-1){\r\n            max=position[*(flex[i+1])][0] - rect[*n][0] - xspacing;\r\n        }\r\n\r\n        if (!isnan(avg)) {\r\n            position[*n][0]=std::max(min, std::min(max, avg - rect[*n][0] / 2.0));\r\n        }\r\n    }\r\n}\r\n\r\n\r\ntemplate<typename GraphType, typename PositionMap,typename RectMap,typename IndexMap>\r\nvoid sugiyama_graph_layout(const GraphType& g,\r\n                           PositionMap &position,\r\n                           RectMap &rect,\r\n                           IndexMap &index,\r\n                           int xspacing=20,\r\n                           int yspacing=30)\r\n{\r\n    BOOST_STATIC_ASSERT (property_traits<PositionMap>::value_type::dimensions >= 2);\r\n    BOOST_STATIC_ASSERT (property_traits<RectMap>::value_type::dimensions >= 2);\r\n\r\n    typedef typename graph_traits<GraphType>::vertex_iterator   Viter;\r\n\r\n    typedef  std::vector<Viter>     Viter_VEC;\r\n    typedef  std::vector<Viter_VEC> Viter_VEC_VEC;\r\n    Viter_VEC_VEC        layers;\r\n    std::map<Viter, int> nodemap;\r\n\r\n    //removeCycles\r\n    //removeCycles();\r\n\r\n    //splitIntoLayers\r\n    splitIntoLayers(g,layers,nodemap);\r\n\r\n    //insertDummies\r\n    //insertDummies();\r\n\r\n    //initIndexes\r\n    for (typename Viter_VEC_VEC::iterator it = layers.begin(); it != layers.end(); ++it )\r\n    {\r\n        Viter_VEC& l = *it;\r\n\r\n        /*sort( l.begin(), l.end(), [&getXYWH]( Viter n1, Viter n2 )->bool{\r\n              return getXYWH[*n1]->id < getXYWH[*n2]->id;\r\n          });*/\r\n        /*\r\n          @todo figure out how to do this\r\n          Collections.sort(l, new Comparator<Viter>() {\r\n              public int compare(Viter n1, Viter n2) {\r\n                  return n1.getIndex() - n2.getIndex();\r\n              }\r\n          });*/\r\n\r\n        setOrderedIndexes<GraphType>(index,l);\r\n    }\r\n\r\n    //reduceCrossings\r\n    for (int round = 0; round < MAX_SWEEPS; round++) {\r\n        if (round % 2 == 0) {\r\n            for (int l = 0; l < layers.size() - 1; l++) {\r\n                stack_reduceCrossings2L(g,layers,index,l, l + 1);\r\n            }\r\n        } else {\r\n            for (int l = layers.size() - 1; l > 0; l--) {\r\n                stack_reduceCrossings2L(g,layers,index,l, l - 1);\r\n            }\r\n        }\r\n    }\r\n\r\n    //undoRemoveCycles\r\n    //undoRemoveCycles();\r\n\r\n    //layerHeights\r\n    stack_layerHeights<GraphType>(layers,position,rect,yspacing);\r\n\r\n    //xPos\r\n    for (int l = 0; l < layers.size(); l++) {\r\n        stack_xPosPack<GraphType>(layers,position,rect,l,xspacing);\r\n    }\r\n\r\n    printf(\"2\\n\");\r\n    for (int l = 0; l < layers.size() - 1; l++) {\r\n        stack_xPosDown(g,position,rect,layers,l, l + 1,xspacing);\r\n    }\r\n    for (int l = layers.size() - 1; l >0; l--) {\r\n        stack_xPosUp(g,position,rect,layers,l, l - 1,xspacing);\r\n    }\r\n}\r\n\r\n\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "8aedaf72605feaf9e9d32dfc51c510d26db5ca44", "size": 13118, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sugiyama_layout.hpp", "max_stars_repo_name": "lokimx88/BGL-sugiyama", "max_stars_repo_head_hexsha": "2d98f97b9d06dd770a846f7b6ad99186457f6da6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-01-10T22:06:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T14:00:29.000Z", "max_issues_repo_path": "sugiyama_layout.hpp", "max_issues_repo_name": "lokimx88/BGL-sugiyama", "max_issues_repo_head_hexsha": "2d98f97b9d06dd770a846f7b6ad99186457f6da6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sugiyama_layout.hpp", "max_forks_repo_name": "lokimx88/BGL-sugiyama", "max_forks_repo_head_hexsha": "2d98f97b9d06dd770a846f7b6ad99186457f6da6", "max_forks_repo_licenses": ["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.3379501385, "max_line_length": 135, "alphanum_fraction": 0.5793566092, "num_tokens": 3285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.2779104828271032}}
{"text": "\n/*\n-------------------------------------------------------------------------\n   This file is part of BayesOpt, an efficient C++ library for \n   Bayesian optimization.\n\n   Copyright (C) 2011-2015 Ruben Martinez-Cantin <rmcantin@unizar.es>\n \n   BayesOpt is free software: you can redistribute it and/or modify it \n   under the terms of the GNU Affero General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   BayesOpt is distributed in the hope that it will be useful, but \n   WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU Affero General Public License for more details.\n\n   You should have received a copy of the GNU Affero General Public License\n   along with BayesOpt.  If not, see <http://www.gnu.org/licenses/>.\n------------------------------------------------------------------------\n*/\n\n\n#include \"bayesopt/bayesopt.hpp\"\n\n#include <boost/bind.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n//#include \"randgen.hpp\"\n#include \"lhs.hpp\"\n#include \"gridsampling.hpp\"\n#include \"log.hpp\"\n\nnamespace bayesopt\n{\n  \n  // DiscreteModel::DiscreteModel(const vecOfvec &validSet):\n  //   BayesOptBase(), mInputSet(validSet)\n  // {} // Constructor\n\n\n  DiscreteModel::DiscreteModel( const vecOfvec &validSet, \n\t\t\t\tParameters parameters):\n    BayesOptBase(validSet[0].size(),parameters), mInputSet(validSet)\n  {    \n    mDims = mInputSet[0].size();    \n  } // Constructor\n\n  DiscreteModel::DiscreteModel(const vectori &categories, \n\t\t\t       Parameters parameters):\n   BayesOptBase(categories.size(),parameters)\n  {    \n    mDims = categories.size();    \n    utils::buildGrid(categories,mInputSet);\n  }\n\n\n  DiscreteModel::~DiscreteModel()\n  {} // Default destructor\n\n\n\n  // PROTECTED\n  vectord DiscreteModel::samplePoint()\n  {   \n    randInt sample(mEngine, intUniformDist(0,mInputSet.size()-1));\n    return mInputSet[sample()];\n  };\n\n  void DiscreteModel::findOptimal(vectord &xOpt)\n  {\n    std::vector<double> critv(mInputSet.size());\n    std::transform(mInputSet.begin(),mInputSet.end(),critv.begin(),\n\t\t   boost::bind(&DiscreteModel::evaluateCriteria,this,_1));\n\n    xOpt = mInputSet[std::distance(critv.begin(),\n\t\t\t std::max_element(critv.begin(),critv.end()))];\n    \n    // xOpt = *mInputSet.begin();\n    // double min = evaluateCriteria(xOpt);\n    \n    // for(vecOfvec::iterator it = mInputSet.begin();\n    // \tit != mInputSet.end(); ++it)\n    //   {\n    // \tdouble current = evaluateCriteria(*it);\n    // \tif (current < min)\n    // \t  {\n    // \t    xOpt = *it;  \n    // \t    min = current;\n    // \t  }\n    //   }\n  }\n\n  //In this case, it is the trivial function\n  vectord DiscreteModel::remapPoint(const vectord& x)\n  { return x; }\n\n  void DiscreteModel::generateInitialPoints(matrixd& xPoints)\n  {\n\n    vecOfvec perms = mInputSet;\n    \n    // By using random permutations, we guarantee that \n    // the same point is not selected twice\n    utils::randomPerms(perms,mEngine);\n    \n    // vectord xPoint(mInputSet[0].size());\n    for(size_t i = 0; i < xPoints.size1(); i++)\n    {\n        const vectord xP = perms[i];\n        row(xPoints,i) = xP;\n    }\n  }\n\n}  // namespace bayesopt\n\n\n", "meta": {"hexsha": "263647f2f9da29b371fe34465b8daa00a58f540b", "size": 3265, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/bayesopt/src/bayesoptdisc.cpp", "max_stars_repo_name": "pchrapka/brain-modelling", "max_stars_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-13T19:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-13T19:37:52.000Z", "max_issues_repo_path": "external/bayesopt/src/bayesoptdisc.cpp", "max_issues_repo_name": "pchrapka/brain-modelling", "max_issues_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/bayesopt/src/bayesoptdisc.cpp", "max_forks_repo_name": "pchrapka/brain-modelling", "max_forks_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-25T12:22:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-25T12:22:05.000Z", "avg_line_length": 27.6694915254, "max_line_length": 75, "alphanum_fraction": 0.6333843798, "num_tokens": 838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.2779104828271032}}
{"text": "﻿// **************************************************************************/\n//  作者: 陈雪飞<chenxuefei_pp@163.com>\n//  日期: 2017年1月15日  14:53:16\n//  工程: OpticalFlow\n//  程序: OpticalFlow\n//  文件: OpticalFlow.cpp\n//  描述: 光流法裂纹检测\n// **************************************************************************/\n\n#include <opencv2/opencv.hpp>\n#include <boost/thread.hpp>\n\n//基本类型定义\n//PI定义\nconst static double  PI = 3.14159265358979323846;\n//特征点个数定义\nconst static uint    FEATURE_MAX_NUM = 600;\n//图像二值化阈值\nconst static double  IMAGE_THRESHOLD = 127.00f;\n\n/**\n* \\brief 创建窗口线程函数，将窗口独立到线程中\n*/\nvoid    output_windows_thread(const std::string &windowname)\n{\n    cv::namedWindow(windowname);\n    cv::waitKeyEx();\n}\n\n/**\n* \\brief 定义平方函数\n* \\tparam _Ty 平方类型\n* \\param a 平方因子\n* \\return\n*/\ntemplate<typename _Ty>\ndouble square(_Ty a)\n{\n    return a * a;\n}\n\n/**\n* \\brief 两点之间线段长度\n* \\param p1 点向量1\n* \\param p2 点向量2\n* \\return 计算出的线段长度\n*/\ndouble  segment_length(const cv::Point & p1, const cv::Point &p2)\n{\n    return std::sqrt(square(p1.x - p2.x) + square(p1.y - p2.y));\n}\n\n\n/**\n* \\brief 定义图像处理函数\n* \\param name 处理方法名\n*/\n#define     DEF_IMG_HANDLER(name)   \\\n    void  name(cv::Mat &in,cv::Mat &out)\n\n/**\n* \\brief 定义处理操作符\n* \\tparam Functor 处理方法\n* \\param img 处理图像\n* \\param f 方法\n* \\return 处理后的图像\n*/\ntemplate <typename Functor>\ncv::Mat  &operator << (cv::Mat &img, Functor f)\n{\n    f(img, img);\n    return img;\n}\n\n/**\n* \\brief 灰度化处理方法\n* \\param in 原图像三通道\n* \\param out 输出图像，灰度图像\n*/\nDEF_IMG_HANDLER(cvtgray)\n{\n    assert(in.channels() == 3);\n    cv::cvtColor(in, out, cv::COLOR_BGR2GRAY);\n}\n\n/**\n* \\brief 灰度图像转彩色图像\n* \\param in 灰度图像，单通道\n* \\param out 彩色图像，三通道\n*/\nDEF_IMG_HANDLER(cvtbgr)\n{\n    assert(in.channels() == 1);\n    cv::cvtColor(in, out, cv::COLOR_GRAY2BGR);\n}\n\n/**\n* \\brief 图像转HSV格式\n* \\param in 源图像\n* \\param out hsv格式图像\n*/\nDEF_IMG_HANDLER(cvthsv)\n{\n    cv::cvtColor(in, out, cv::COLOR_BGR2HSV);\n}\n\n/**\n* \\brief 二值化图像\n* \\param in 传入图像\n* \\param out 二值化图像，单通道\n*/\nDEF_IMG_HANDLER(binary)\n{\n    //cv::threshold(in, out, IMAGE_THRESHOLD, 255.0f, CV_THRESH_BINARY);\n\n    cv::adaptiveThreshold(in, out, 255.0f,\n        cv::AdaptiveThresholdTypes::ADAPTIVE_THRESH_GAUSSIAN_C,\n        cv::ThresholdTypes::THRESH_BINARY, 7, 0.0);\n}\n\n/**\n* \\brief 白平衡处理，均衡化三通道\n* \\param in 输入图像三通道\n* \\param out 输出图像三通道\n*/\nDEF_IMG_HANDLER(whiteblace)\n{\n    assert(in.channels() == 3);\n    using namespace cv;\n    Mat &g_srcImage = in, &dstImage = out;\n    std::vector<Mat> g_vChannels;\n\n    split(g_srcImage, g_vChannels);\n    Mat imageBlueChannel = g_vChannels.at(0);\n    Mat imageGreenChannel = g_vChannels.at(1);\n    Mat imageRedChannel = g_vChannels.at(2);\n\n    double imageBlueChannelAvg = 0;\n    double imageGreenChannelAvg = 0;\n    double imageRedChannelAvg = 0;\n\n    //求各通道的平均值\n    imageBlueChannelAvg = mean(imageBlueChannel)[0];\n    imageGreenChannelAvg = mean(imageGreenChannel)[0];\n    imageRedChannelAvg = mean(imageRedChannel)[0];\n\n    //求出个通道所占增益\n    double K = (imageRedChannelAvg + imageGreenChannelAvg + imageRedChannelAvg) / 3;\n    double Kb = K / imageBlueChannelAvg;\n    double Kg = K / imageGreenChannelAvg;\n    double Kr = K / imageRedChannelAvg;\n\n    //更新白平衡后的各通道BGR值\n    addWeighted(imageBlueChannel, Kb, 0, 0, 0, imageBlueChannel);\n    addWeighted(imageGreenChannel, Kg, 0, 0, 0, imageGreenChannel);\n    addWeighted(imageRedChannel, Kr, 0, 0, 0, imageRedChannel);\n\n    merge(g_vChannels, dstImage);//图像各通道合并 \n}\n\n/**\n* \\brief 灰度直方图均衡化\n* \\param in 输入灰度图\n* \\param out 输出灰度图\n*/\nDEF_IMG_HANDLER(equalizeHist)\n{\n    assert(in.channels() == 1);\n    cv::equalizeHist(in, out);\n}\n\n/**\n* \\brief 图像锐化，拉普拉斯算子\n* \\param in 输入图像\n* \\param out 输出图像\n*/\nDEF_IMG_HANDLER(sharpen)\n{\n    cv::Mat kernela(3, 3, CV_32F, cv::Scalar(0));\n    kernela.at<float>(1, 1) = 5.0;\n    kernela.at<float>(0, 1) = -1.0;\n    kernela.at<float>(2, 1) = -1.0;\n    kernela.at<float>(1, 0) = -1.0;\n    kernela.at<float>(1, 2) = -1.0;\n    filter2D(in, out, in.depth(), kernela);\n}\n\n/**\n* \\brief 对图像进行预处理\n* \\param base_image 待预处理的图像\n*/\nvoid handle_base_out_pre(cv::Mat& base_image)\n{\n    std::vector<cv::Mat> mv;\n\n    //分离红色通道分量\n    cv::split(base_image, mv);\n    auto &red = mv.at(2);\n\n    /// 膨胀操作\n    int dilation_size = 1;\n    auto element = getStructuringElement(cv::MORPH_RECT,\n        cv::Size(2 * dilation_size + 1, 2 * dilation_size + 1),\n        cv::Point(dilation_size, dilation_size));\n    dilate(red, red, element);\n    dilate(red, red, element);\n    dilate(red, red, element);\n    //将分量组合\n    cv::merge(mv, base_image);\n\n    cv::imshow(\"superposition_window\", base_image);\n\n    cv::imwrite(\"叠加膨胀结果.png\", base_image);\n}\n/**\n* \\brief 查找最大连通域\n* \\param base_image\n*/\nvoid handle_base_out_last(const cv::Mat& base_image, cv::Mat & backend_image)\n{\n    //最大面积区域需要显示几个\n    const static  auto area_number = 3;\n\n    cv::Mat\t\tnew_image = backend_image;\n\n    assert(!new_image.empty());//检查是否为空\n\n\n    std::vector<cv::Vec4i>          hierarchy;\n    std::vector<cv::Mat>            contours;\n\n    cv::Mat input;\n    base_image.copyTo(input);\n\n    cv::cvtColor(input, input, cv::COLOR_BGR2GRAY);\n    \n    input << binary;//二值化\n    cv::imwrite(\"二值结果.png\", input);\n\n    cv::findContours(input, contours, hierarchy,\n        cv::RetrievalModes::RETR_CCOMP,\n        cv::ContourApproximationModes::CHAIN_APPROX_SIMPLE);\n\n    //输出查找到的所有轮廓\n    {\n        cv::Mat all_outline;\n        new_image.copyTo(all_outline);\n        cv::drawContours(all_outline, contours, -1, CV_RGB(0, 255, 255), 1 , cv::LINE_AA);\n        cv::imwrite(\"查找到的所有轮廓.png\", all_outline);        \n    }\n\n    /// Find the convex hull object for each contour  \n    std::vector<std::vector<cv::Point2i> >\thull(contours.size()), dest_hull;\n    // Int type hull  \n    std::vector<std::vector<int>>\thullsI(contours.size());\n    // Convexity defects  \n    std::vector<cv::Mat>\t\t\tdefects(contours.size());\n\n    //凹点还原\n    for (size_t i = 0; i < contours.size(); i++)\n    {\n        cv::convexHull(contours[i], hull[i], false);\n        // find int type hull  \n        cv::convexHull(contours[i], hullsI[i], false);\n        // get convexity defects  \n        convexityDefects(contours[i], hullsI[i], defects[i]);\n    }\n\n    //查找最大轮廓\n    for (auto i = 0; i < area_number; ++i)\n    {\n        auto max_contours = std::max_element(hull.begin(), hull.end(), [](const std::vector<cv::Point> &l, const std::vector<cv::Point> &r)->bool\n        {\n            auto area1 = fabs(cv::contourArea(l));\n            auto area2 = fabs(cv::contourArea(r));\n            return area1 < area2;\n        });\n        dest_hull.push_back(*max_contours);\n        hull.erase(max_contours);\n    }\n\n    cv::drawContours(new_image, dest_hull, -1, CV_RGB(0, 255, 255), 1 , cv::LINE_AA);\n\n    //cv::drawContours(base_image, contours ,-1, CV_RGB(255, 0, 0),1,cv::LINE_AA);\n    //根据凹点还原在原图连线，表示出最大连通点\n    //for (size_t i = 0; i< contours.size(); i++)\n    //{\n    //\tcv::Scalar color = CV_RGB(0,255,0);\n    //\tdrawContours(new_image, hull, i, color, 1, 8, std::vector<cv::Vec4i>(), 0, cv::Point2i());\n\n    //\t//auto d = defects[i].begin<cv::Vec4i>();\n    //\t//while (d != defects[i].end<cv::Vec4i>()) {\n    //\t//\tcv::Vec4i& v = (*d);\n    //\t//\t//if(IndexOfBiggestContour == i)  \n    //\t//\t{\n\n    //\t//\t\tint startidx = v[0];\n    //\t//\t\tcv::Point2i ptStart(contours[i].at<cv::Point2i>(startidx)); // point of the contour where the defect begins  \n    //\t//\t\tint endidx = v[1];\n    //\t//\t\tcv::Point2i ptEnd(contours[i].at<cv::Point2i>(endidx)); // point of the contour where the defect ends  \n    //\t//\t\tint faridx = v[2];\n    //\t//\t\tcv::Point2i ptFar(contours[i].at<cv::Point2i>(faridx));// the farthest from the convex hull point within the defect  \n    //\t//\t\tint depth = v[3] / 256; // distance between the farthest point and the convex hull  \n\n    //\t//\t\tif (depth > 20 && depth < 80)\n    //\t//\t\t{\n    //\t//\t\t\t//line(new_image, ptStart, ptFar, CV_RGB(0, 255, 0), 2);\n    //\t//\t\t\t//line(new_image, ptEnd, ptFar, CV_RGB(0, 255, 0), 2);\n    //\t//\t\t\t/*circle(base_image, ptStart, 4, cv::Scalar(255, 0, 100), 2);\n    //\t//\t\t\tcircle(base_image, ptEnd, 4, cv::Scalar(255, 0, 100), 2);\n    //\t//\t\t\tcircle(base_image, ptFar, 4, cv::Scalar(100, 0, 255), 2);*/\n    //\t//\t\t}\n    //\t//\t}\n    //\t//\t++d;\n    //\t//}\n    //}\n    //cv::drawContours(base_image, defects, -1, CV_RGB(0, 255, 0), 1, cv::LINE_AA);\n    cv::imshow(\"output_window\", new_image);\n    cv::imwrite(\"最终结果.png\", new_image);\n}\n/**\n* \\brief 开始绘制运动轨迹 如需要\n* \\param m1 基本矩阵\n* \\param frame1_features 查找到的第一帧特征点\n* \\param frame2_features 查找到的第二帧特征点\n* \\param found_features 特征点错误矩阵\n*/\nvoid    draw_path_on_baseimage(cv::Mat &m1, const cv::Mat &frame1_features, const cv::Mat &frame2_features, const cv::Mat &found_features)\n{\n    const static cv::Scalar line_color = CV_RGB(255, 0, 0);\n\n    for (auto pos = 0; pos < FEATURE_MAX_NUM; ++pos)\n    {\n        /* 如果没找到对应特征点 */\n        if (found_features.at<uchar>(pos) == 0)\n            continue;\n\n        auto p = frame1_features.at<cv::Point2f>(pos);\n        auto q = frame2_features.at<cv::Point2f>(pos);\n\n        if (segment_length(p, q) > 20.0f)\n            return;\n\n        double angle;\n        angle = atan2(static_cast<double>(p.y) - q.y, static_cast<double>(p.x) - q.x);\n        double hypotenuse;\n        hypotenuse = sqrt(square(p.y - q.y) + square(p.x - q.x));\n\n        /*执行缩放*/\n        q.x -= 5 * hypotenuse * cos(angle);\n        q.y -= 5 * hypotenuse * sin(angle);\n\n        /*画箭头主线*/\n        cv::line(m1, p, q, line_color, 1, cv::LineTypes::LINE_AA, 0);\n\n        /* 画箭的头部*/\n        p.x = q.x + 9 * cos(angle + PI / 4);\n        p.y = q.y + 9 * sin(angle + PI / 4);\n        cv::line(m1, p, q, line_color, 1, cv::LineTypes::LINE_AA, 0);\n        p.x = q.x + 9 * cos(angle - PI / 4);\n        p.y = q.y + 9 * sin(angle - PI / 4);\n        cv::line(m1, p, q, line_color, 1, cv::LineTypes::LINE_AA, 0);\n    }\n}\n/**\n* \\brief 将特征点信息绘制到基础背景图像中去\n* \\param base_image 要绘制的图像\n* \\param frame1_features 第一帧特征点\n* \\param frame2_features 第二帧特征点\n* \\param found_features 特征点信息\n*/\nvoid draw_features_in_base_image(cv::Mat& base_image, const cv::Mat& frame1_features, const cv::Mat& frame2_features, const cv::Mat& found_features)\n{\n    const static cv::Scalar area_color = CV_RGB(255, 0, 0);\n\n    for (auto pos = 0; pos < FEATURE_MAX_NUM; ++pos)\n    {\n        /* 如果没找到对应特征点 */\n        if (found_features.at<uchar>(pos) == 0)\n            continue;\n        auto start_p = frame1_features.at<cv::Point2f>(pos);\n        auto end_p = frame2_features.at<cv::Point2f>(pos);\n        //如果线段长度大于某个值，说明不是细微运动则排除该线段\n        if (segment_length(start_p, end_p) > 20.0f)\n            return;\n\n        cv::line(base_image, start_p, end_p, area_color, 3, cv::LINE_AA);\n    }\n}\n/**\n* \\brief 打开视频文件并返回帧数\n* \\param capture 视频句柄\n* \\param filename 文件名\n* \\return 返回帧数\n*/\nint open_video(cv::VideoCapture & capture, const std::string &filename)\n{\n    //打开视频文件\n    capture.open(filename);\n    auto  frame_count = 0; //总帧长\n\n    assert(capture.isOpened());//检查是否打开\n\n    //获取总帧数\n    frame_count = static_cast<int>(capture.get(cv::VideoCaptureProperties::CAP_PROP_FRAME_COUNT));\n\n    //进度条，可以查看处理了多少帧\n    return frame_count;\n}\n\n\n/**\n* \\brief 开始LK光流法算法\n* \\param base_out 叠加输出基本源图像\n*/\nvoid draw_features_by_lk(cv::Mat & base_out, const std::string & in_video_name, const std::string & out_video_name)\n{\n    //打开视频文件并且创建进度条\n    cv::VideoCapture capture{};\n    auto frame_count = open_video(capture, in_video_name);\n    //boost::progress_display progress_bar(frame_count, std::cout, \"当前处理进度\\n\\t\\t\", \"总进度\\t\\t\", \"当前进度\\t\");\n    //打开输出视频文件 如需要\n    cv::VideoWriter writer(out_video_name, CV_FOURCC('X', 'V', 'I', 'D'), 29.0, cv::Size{ 656,488 });\n\n    //如果还有新帧则继续\n    while (capture.grab())\n    {\n        cv::Mat     m1, m2, frame1, frame2;\n        //取出视频两帧\n        capture >> m1;\n        capture >> m2;\n        //如果返回不足两帧则退出\n        if (m1.empty() || m2.empty())\n            break;\n        //复制到新空间\n        frame1 = m1;\n        frame2 = m2;\n        //两帧灰度化\n        frame1 << cvtgray;\n        frame2 << cvtgray;\n\n        //创建两个特征值存储矩阵\n        cv::Mat frame1_features, frame2_features;\n        //开始进行特征值检测，先检测出第一帧特征值\n        cv::goodFeaturesToTrack(frame1, frame1_features, FEATURE_MAX_NUM, .01, .01);\n        //创建查找错误矩阵\n        cv::Mat found_futures, found_err;\n        //创建迭代算子\n        cv::TermCriteria optical_flow_termination_criteria(cv::TermCriteria::Type::MAX_ITER | cv::TermCriteria::Type::EPS, 20, .3);\n        //开始进行LK光流法计算，查找第二个特征值\n        cv::calcOpticalFlowPyrLK(\n            frame1, frame2,\n            frame1_features, frame2_features,\n            found_futures, found_err,\n            cv::Size{ 5,5 }, 5, optical_flow_termination_criteria);\n        //绘制移动轨迹 ， 如需要\n        draw_path_on_baseimage(m1, frame1_features, frame2_features, found_futures);\n        //绘制运动轨迹线到背景矩阵\n        draw_features_in_base_image(base_out, frame1_features, frame2_features, found_futures);\n        \n        //进度条更新\n        //progress_bar += 2;\n\n        //将运动轨迹线展示到窗口，如需要\n        cv::imshow(\"output_window\", m1);\n        cv::imshow(\"superposition_window\", base_out);\n        //将运动轨迹线输出到视频文件 如需要\n        writer << m1;\n        //writer << (out << cvtbgr);\n    }\n\n    writer.release();\n    capture.release();\n}\n\n/**\n* \\brief 主函数\n* \\return\n*/\nint main(int argc, char ** args)\n{\n    if (argc < 3)\n    {\n        std::cout << \"请输入输入视频文件名,输入背景图像文件名,(或者输出视频文件名),按顺序空格分离.\" << std::endl;\n        std::cout << \"Example:\\n\\tOpticalFlow 输入视频.avi 输入背景.jpg [输出视频.avi]\" << std::endl;\n        exit(-1);\n    }\n    std::string input_video_filename = args[1];\n    std::string base_image_filename = args[2];\n    std::string base_output_filename = \"VideoOut.avi\";\n    if (argc == 4)\n        base_output_filename = args[3];\n\n    //创建窗口  \n    auto  output_window_fu = boost::thread(output_windows_thread, \"output_window\");\n    auto  superposition_window_fu = boost::thread(output_windows_thread, \"superposition_window\");\n\n    //boost::thread(output_windows_thread).detach();    \n    //打开背景图像\n    auto            base_image = cv::imread(base_image_filename);\n    //打开是否失败\n    assert(!base_image.empty());\n\n    //创建空白背景图像\n    cv::Mat         base_out{ base_image.rows,base_image.cols,base_image.type() };\n    //cv::Mat          base_out = cv::imread(\"post.png\");\n    //开始进行LK光流算法，将结果图像输出到base out\n    draw_features_by_lk(base_out, input_video_filename, base_output_filename);\n\n    /*\n    * ！！！！此处开始对LK算法处理后的图像进行处理！！！！\n    */\n    //对叠加输出图片进行预处理\n    handle_base_out_pre(base_out);\n    //对预处理图片进行整合处理，边缘过滤，凹点过滤\n    handle_base_out_last(base_out, base_image);\n\n    //等待窗口程序结束\n    superposition_window_fu.join();\n    output_window_fu.join();\n    return 0;\n}\n\n", "meta": {"hexsha": "c0addc37a8bda1e5396a0f8b4d964df7fca6755a", "size": 14495, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CMake/OpticalFlow.cpp", "max_stars_repo_name": "chenxuefei-pp/OpticalFlow", "max_stars_repo_head_hexsha": "7570687d3164f02c6f7f2cd8ca77ca53e3325a78", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-11-14T12:10:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-16T00:45:40.000Z", "max_issues_repo_path": "CMake/OpticalFlow.cpp", "max_issues_repo_name": "stan-chen/OpticalFlow", "max_issues_repo_head_hexsha": "7570687d3164f02c6f7f2cd8ca77ca53e3325a78", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CMake/OpticalFlow.cpp", "max_forks_repo_name": "stan-chen/OpticalFlow", "max_forks_repo_head_hexsha": "7570687d3164f02c6f7f2cd8ca77ca53e3325a78", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-12-31T01:11:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-04T09:53:40.000Z", "avg_line_length": 27.6622137405, "max_line_length": 148, "alphanum_fraction": 0.6072438772, "num_tokens": 5140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.2779104828271032}}
{"text": "/*******************************************************************************\n*\n*  Filename    : PlotSimFitVal.cc\n*  Description : Plotting Pull distribution and others\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/SimFitVal.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 \"ManagerUtils/SampleMgr/interface/SampleMgr.hpp\"\n#include \"TstarAnalysis/Common/interface/PlotStyle.hpp\"\n\n#include <algorithm>\n#include <boost/format.hpp>\n#include <fstream>\n\n#include \"RooDataSet.h\"\n#include \"RooGaussian.h\"\n#include \"RooRealVar.h\"\n#include \"TGraphAsymmErrors.h\"\n#include \"TMultiGraph.h\"\n\nusing namespace std;\nusing namespace mgr;\n\n/*******************************************************************************\n*   Declaring global static variables\n*******************************************************************************/\nstatic RooRealVar p( \"p\", \"p\", 0, -7, 7 );\n\n/*******************************************************************************\n*   Defining datatype\n*******************************************************************************/\nconst unsigned BKG_IDX = 0;\nconst unsigned SIG_IDX = 1;\nconst unsigned P1_IDX  = 2;\nconst unsigned P2_IDX  = 3;\n\n\n\n/*******************************************************************************\n*   Defining main control flows\n*******************************************************************************/\nvoid\nPlotGenFit( const vector<string>& masslist )\n{\n\n  map<int, PullResult> pullresults;\n\n  p.setRange( \"reduce\", -2, 2 );\n\n  for( const auto& masspoint : masslist ){\n    const int mass = GetInt( masspoint );\n    pullresults[mass] = PlotSingleGenFit( masspoint );\n    cout << mass << endl;\n  }\n\n  MakePullComparePlot( pullresults, BKG_IDX, \"bkg\"    );\n  MakePullComparePlot( pullresults, SIG_IDX, \"sig\"    );\n  // MakePullComparePlot( pullresults, P1_IDX ,\"param1\" );\n  // MakePullComparePlot( pullresults, P2_IDX ,\"param2\" );\n\n}\n\n/******************************************************************************/\n\nPullResult\nPlotSingleGenFit( const std::string& masstag )\n{\n  const string strgthtag = SigStrengthTag();\n  const string rhotag    = RhoTag();\n  const string filename  = limnamer.TextFileName( \"valsimfit\", masstag, rhotag, strgthtag );\n  ifstream result( filename );\n\n  RooDataSet bkgset( \"bkg\", \"bkg\", RooArgSet( p ) );\n  RooDataSet sigset( \"sig\", \"sig\", RooArgSet( p ) );\n  RooDataSet p1set( \"p1\", \"p1\", RooArgSet( p ) );\n  RooDataSet p2set( \"p2\", \"p2\", RooArgSet( p ) );\n  RooDataSet signormset( \"signorm\", \"signorm\", RooArgSet( p ) );\n  double bkg_real, sig_real, p1_real, p2_real;\n  double bkg_fit, bkg_fiterr;\n  double sig_fit, sig_fiterr;\n  double p1_fit, p1_fiterr;\n  double p2_fit, p2_fiterr;\n\n  PullResult ans;\n\n  // Begin reading files\n  cout << \"Reading file \" << filename << endl;\n  result >> bkg_real >> sig_real >> p1_real >> p2_real;\n\n  while( result >> bkg_fit >>  bkg_fiterr >> sig_fit >>  sig_fiterr >> p1_fit >>  p1_fiterr >> p2_fit >>  p2_fiterr ){\n\n    // Making pull distribution\n    double bkgpull = ( bkg_fit - bkg_real ) / bkg_fiterr;\n    double sigpull = ( sig_fit - sig_real ) / sig_fiterr;\n    double p1pull  = ( p1_fit  - p1_real  ) / p1_fiterr;\n    double p2pull  = ( p2_fit  - p2_real  ) / p2_fiterr;\n    double signorm = ( sig_fit - sig_real ) / sig_real;\n\n    if(\n      bkgpull < -7 || bkgpull > +7 ||\n      sigpull < -7 || sigpull > +7 ||\n      p1pull  < -7 || p1pull  > +7 ||\n      p2pull  < -7 || p2pull  > +7\n      ){ continue; }\n\n    p = bkgpull;\n    bkgset.add( RooArgSet( p ) );\n    p = sigpull;\n    sigset.add( RooArgSet( p ) );\n    p = p1pull;\n    p1set.add( RooArgSet( p ) );\n    p = p2pull;\n    p2set.add( RooArgSet( p ) );\n    p = signorm;\n    signormset.add( RooArgSet( p ) );\n  }\n\n  ans.fitparm[BKG_IDX] = MakePullPlot( bkgset, masstag, \"bkg\"    );\n  ans.fitparm[SIG_IDX] = MakePullPlot( sigset, masstag, \"sig\"    );\n  ans.fitparm[P1_IDX]  = MakePullPlot( p1set,  masstag, \"param1\" );\n  ans.fitparm[P2_IDX]  = MakePullPlot( p2set,  masstag, \"param2\" );\n\n  return ans;\n}\n\n\n/*******************************************************************************\n*   Plotting functions\n*******************************************************************************/\npair<Parameter, Parameter>\nMakePullPlot( RooDataSet& set, const string& masstag, const string& tag )\n{\n  RooRealVar mean( \"m\", \"m\", 0, -5, 5 );\n  RooRealVar sigma( \"s\", \"s\", 1,  0, 5 );\n  RooGaussian pullfit( \"pull\", \"pull\", p, mean, sigma );\n  RooRealVar smean( \"sm\", \"sm\", 0, -5, 5 );\n  RooRealVar ssigma( \"ss\", \"ss\", 1,  0, 5 );\n  RooGaussian spullfit( \"spull\", \"spull\", p, smean, ssigma );\n  p.setRange( \"reduce\", -2, 2 );\n\n  TCanvas* c = mgr::NewCanvas();\n\n  pullfit.fitTo( set,\n    RooFit::Minimizer( \"Minuit\", \"Migrad\" ),\n    RooFit::Minos( kTRUE ),\n    RooFit::Verbose( kFALSE ),\n    RooFit::PrintLevel( -1 ),\n    RooFit::PrintEvalErrors( -1 ),\n    RooFit::Warnings( kFALSE )\n    );\n\n  spullfit.fitTo( set,\n    RooFit::Minimizer( \"Minuit\", \"Migrad\" ),\n    RooFit::Minos( kTRUE ),\n    RooFit::Verbose( kFALSE ),\n    RooFit::PrintLevel( -1 ),\n    RooFit::PrintEvalErrors( -1 ),\n    RooFit::Warnings( kFALSE ),\n    RooFit::Range( \"reduce\" )// Fitting to sub-range\n    );\n\n  RooPlot* frame  = p.frame();\n  TGraph* setplot = mgr::PlotOn( frame, &set,\n    RooFit::Binning( 39, p.getMin(), p.getMax() ),\n    RooFit::DrawOption( PGS_DATA )\n    );\n  TGraph* fitplot = mgr::PlotOn( frame, &pullfit );\n  TGraph* subplot = mgr::PlotOn( frame, &spullfit, RooFit::Range( \"reduce\" ) );\n  frame->Draw();\n\n  // Styling\n  tstar::SetDataStyle( setplot );\n  fitplot->SetLineColor( KBLUE );\n  subplot->SetLineColor( KRED  );\n\n  const double ymax = mgr::GetYmax( setplot, fitplot, subplot );\n  frame->SetMaximum( ymax * 1.6 );\n  frame->GetYaxis()->SetTitle(\"Events\");\n\n  // Calculation Kolmogorov-Smirnov Goodness-of-Fit Test\n  const double ksres  = KSTest( set, pullfit, p );\n  const double sksres = KSTest( set, spullfit, p, RooFit::CutRange( \"reduce\" ) );\n\n  // Styling plots\n  mgr::SetFrame( frame );\n  mgr::DrawCMSLabelOuter( SIMULATION );\n  mgr::DrawLuminosity( mgr::SampleMgr::TotalLuminosity() );\n\n  // Title Formats\n  boost::format xtitlefmt( \"pull_{%s}\" );\n  boost::format signalfmt( \"Sig. mass = %d GeV/c^{2}\" );\n  boost::format fitfmt(  \"#mu = %.2lf_{#pm%.3lf}  #sigma = %.3lf_{#pm%.3lf}\"  );\n  boost::format sfitfmt( \"#mu' = %.2lf_{#pm%.3lf} #sigma' = %.3lf_{#pm%.3lf}\"  );\n  boost::format ksfmt( \"K = %.3lf\" );\n  boost::format injectfmt( \"signal events %1% %2%\" );\n\n  const string xtitle_s = str( xtitlefmt % tag );\n  const string signal_s = str( signalfmt % GetInt( masstag ) );\n  const string fit_s    = str( fitfmt    % mean.getVal() % mean.getError() % sigma.getVal() % sigma.getError() );\n  const string sfit_s   = str( sfitfmt   % smean.getVal()% smean.getError()%ssigma.getVal() %ssigma.getError() );\n  const string inject_s = limnamer.CheckInput( \"relmag\" ) ? boost::str( injectfmt % 'x' % limnamer.GetInput<double>( \"relmag\" ) ) :\n                          boost::str( injectfmt % '=' % limnamer.GetInput<double>( \"absmag\" ) );\n\n  // Making titles\n  frame->SetTitle( \"\" );\n  frame->GetXaxis()->SetTitle( xtitle_s.c_str() );\n\n  // Legend for marking\n  TLegend* tl = mgr::NewLegend( 0.5, 0.6 );\n  tl->AddEntry( fitplot,        fit_s.c_str(),                     \"l\" );\n  tl->AddEntry( (TObject*)NULL, boost::str( ksfmt%ksres ).c_str(),  \"\" );\n  tl->AddEntry( subplot,       sfit_s.c_str(),                     \"l\" );\n  tl->AddEntry( (TObject*)NULL, boost::str( ksfmt%sksres ).c_str(), \"\" );\n  tl->Draw();\n\n  LatexMgr latex;\n  latex.SetOrigin( PLOT_X_TEXT_MIN, PLOT_Y_TEXT_MAX, TOP_LEFT );\n  latex.WriteLine( limnamer.GetChannelEXT( \"Root Name\" ) );\n  latex.WriteLine( limnamer.GetExt<string>( \"fitfunc\", \"Full Name\" ) );\n  latex.WriteLine( signal_s );\n  latex.WriteLine( inject_s );\n\n\n  mgr::SaveToPDF( c, limnamer.PlotFileName( \"valpulldist\", RhoTag(), masstag,  tag,  SigStrengthTag() ) );\n\n  delete frame;\n  delete c;\n\n  return pair<Parameter, Parameter>( mean, sigma );\n}\n\n\nvoid\nMakePullComparePlot(\n  const map<int, PullResult>& pullresultlist,\n  const unsigned idx,\n  const string& tag\n  )\n{\n  TCanvas* c = mgr::NewCanvas();\n  c->SetLeftMargin( PLOT_X_MIN );\n  c->SetRightMargin( 1 - PLOT_X_MAX );\n  c->SetBottomMargin( PLOT_Y_MIN );\n  c->SetTopMargin( 1 - PLOT_Y_MAX );\n\n  TGraphAsymmErrors* graph   = new TGraphAsymmErrors( pullresultlist.size() );\n  TGraphAsymmErrors* meanerr = new TGraphAsymmErrors( pullresultlist.size() );\n  TGraphAsymmErrors* uperr   = new TGraphAsymmErrors( pullresultlist.size() );\n  TGraphAsymmErrors* lowerr  = new TGraphAsymmErrors( pullresultlist.size() );\n\n  unsigned i = 0;\n\n  for( const auto& resultpair : pullresultlist ){\n    const int mass          = resultpair.first;\n    const PullResult result = resultpair.second;\n    const Parameter fitmean = result.fitparm[idx].first;\n    const Parameter fitsig  = result.fitparm[idx].second;\n\n    graph->SetPoint( i, mass, fitmean.CentralValue() );\n    meanerr->SetPoint( i, mass, fitmean.CentralValue() );\n    uperr->SetPoint( i, mass, fitmean.CentralValue() + fitsig.CentralValue() );\n    lowerr->SetPoint( i, mass, fitmean.CentralValue() - fitsig.CentralValue() );\n\n    graph->SetPointError( i, 0, 0, fitsig.CentralValue(), fitsig.CentralValue() );\n    meanerr->SetPointError( i, 0, 0, fabs( fitmean.AbsLowerError() ), fabs( fitmean.AbsUpperError() ) );\n    uperr->SetPointError( i, 0, 0, fabs( fitsig.AbsLowerError() ), fabs( fitsig.AbsUpperError() ) );\n    lowerr->SetPointError( i, 0, 0, fabs( fitsig.AbsUpperError() ), fabs( fitsig.AbsLowerError() ) );\n    ++i;\n  }\n\n  TMultiGraph* mg = new TMultiGraph();\n  mg->Add( meanerr, \"A3\" );\n  mg->Add( uperr,   \"A3\" );\n  mg->Add( lowerr,  \"A3\" );\n  mg->Add( graph,   \"LP\" );\n\n  mg->Draw( \"A\" );\n  mg->SetTitle( \"\" );\n  mg->GetXaxis()->SetTitle( \"Signal mass (GeV/c^{2})\" );\n  mg->GetYaxis()->SetTitle( ( \"pull_{\"+tag+\"}\" ).c_str() );\n  mg->SetMaximum( 3.25 );\n  mg->SetMinimum( -1.75 );\n  mgr::SetAxis( mg );\n  mgr::DrawCMSLabel( SIMULATION );\n  mgr::DrawLuminosity( mgr::SampleMgr::TotalLuminosity() );\n\n  // Styling graphs\n  graph->SetMarkerStyle( 21 );\n  meanerr->SetFillStyle( 1001 );\n  meanerr->SetFillColor( kBlue );\n  meanerr->SetLineColor( kBlue );\n  uperr->SetFillStyle( 1001 );\n  uperr->SetFillColor( kCyan );\n  uperr->SetFillColor( kCyan );\n  lowerr->SetFillStyle( 1001 );\n  lowerr->SetFillColor( kCyan );\n  lowerr->SetFillColor( kCyan );\n\n\n  const double xmin = mg->GetXaxis()->GetXmin();\n  const double xmax = mg->GetXaxis()->GetXmax();\n  TLine z( xmin, 0, xmax, 0 );\n  TLine hi( xmin, 1, xmax, 1 );\n  TLine lo( xmin, -1, xmax, -1 );\n  z.SetLineColor( kRed );\n  z.SetLineWidth( 3 );\n  z.SetLineStyle( 2 );\n  z.Draw();\n  hi.SetLineColor( kBlue );\n  hi.SetLineWidth( 2 );\n  hi.SetLineStyle( 3 );\n  hi.Draw();\n  lo.SetLineColor( kBlue );\n  lo.SetLineWidth( 2 );\n  lo.SetLineStyle( 3 );\n  lo.Draw();\n\n  boost::format injectfmt( \"signal events %1% %2%\" );\n  const string inject_s\n    = limnamer.CheckInput( \"relmag\" ) ? boost::str( injectfmt % 'x' % limnamer.GetInput<double>( \"relmag\" ) ) :\n      boost::str( injectfmt % '=' % limnamer.GetInput<double>( \"absmag\" ) );\n\n  mgr::LatexMgr latex;\n  latex.SetOrigin( PLOT_X_MIN, PLOT_Y_MAX+TEXT_MARGIN/2, BOTTOM_LEFT )\n  .WriteLine( limnamer.GetChannelEXT( \"Root Name\" ) )\n  .SetOrigin( PLOT_X_TEXT_MAX, PLOT_Y_TEXT_MAX, TOP_RIGHT )\n  .WriteLine( limnamer.GetExt<string>( \"fitfunc\", \"Full Name\" ) )\n  .WriteLine( inject_s );\n\n  mgr::SaveToPDF( c, limnamer.PlotFileName( \"pullvmass\", RhoTag(), tag,  SigStrengthTag() ) );\n\n  delete graph;\n  delete meanerr;\n  delete uperr;\n  delete lowerr;\n  delete mg;\n  delete c;\n}\n", "meta": {"hexsha": "9056e104cd9f3570e685cbc87ac0cdd53e798eb4", "size": 11927, "ext": "cc", "lang": "C++", "max_stars_repo_path": "LimitCalc/src/PlotSimFitVal.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/PlotSimFitVal.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/PlotSimFitVal.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.5710144928, "max_line_length": 131, "alphanum_fraction": 0.5998993879, "num_tokens": 3607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646140788306, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.27781417789028856}}
{"text": "#include <algorithm>\n#include <array>\n#include <map>\n#include <numeric>\n#include <stdexcept>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\n#include <boost/functional/hash.hpp>\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Kernel/global_functions.h>\n#include <Euclid/Util/Assert.h>\n\nnamespace Euclid\n{\n\nnamespace _impl\n{\n\n/** Convert face index order to a canonical form such that\n *  the first index is the smallest.*/\ntemplate<typename T, int N>\nstd::array<T, N> to_canonical(const std::array<T, N>& face)\n{\n    auto iter = std::min_element(face.begin(), face.end());\n    std::array<T, N> canonical;\n    for (size_t i = 0; i < N; ++i) {\n        canonical[i] = *iter++;\n        if (iter == face.end())\n            iter = face.begin();\n    }\n    return canonical;\n}\n\n} // namespace _impl\n\ntemplate<typename T>\nsize_t remove_duplicate_vertices(std::vector<T>& positions)\n{\n    if (positions.empty()) {\n        EWARNING(\"positions is empty.\");\n        return 0;\n    }\n    if (positions.size() % 3 != 0) {\n        throw std::runtime_error(\"Input position size is not divisible by 3\");\n    }\n    using Point = std::array<T, 3>;\n\n    // Find duplicate points\n    std::vector<size_t> marks;\n    std::unordered_set<Point, boost::hash<Point>> unique_points;\n    for (size_t i = 0; i < positions.size(); i += 3) {\n        Point p{ { positions[i], positions[i + 1], positions[i + 2] } };\n        auto [dummy, is_unique] = unique_points.insert(std::move(p));\n        if (!is_unique) {\n            marks.push_back(i);\n        }\n    }\n\n    // Move elements in the back into slots to be removed\n    size_t idx = positions.size() - 3;\n    for (auto iter = marks.rbegin(); iter != marks.rend(); ++iter) {\n        positions[*iter] = positions[idx];\n        positions[*iter + 1] = positions[idx + 1];\n        positions[*iter + 2] = positions[idx + 2];\n        idx -= 3;\n    }\n\n    // Now drop the end\n    positions.erase(positions.begin() + idx + 3, positions.end());\n    positions.shrink_to_fit();\n\n    return marks.size();\n}\n\ntemplate<int N, typename T1, typename T2>\nsize_t remove_duplicate_vertices(std::vector<T1>& positions,\n                                 std::vector<T2>& indices)\n{\n    static_assert(N >= 3);\n    if (positions.empty()) {\n        EWARNING(\"positions is empty.\");\n        return 0;\n    }\n    if (indices.empty()) {\n        remove_duplicate_vertices(positions);\n    }\n    if (positions.size() % 3 != 0) {\n        throw std::runtime_error(\"Input position size is not divisible by 3\");\n    }\n    if (indices.size() % N != 0) {\n        std::string err_str(\"Input index size is not divisible by \");\n        err_str.append(std::to_string(N));\n        throw(err_str);\n    }\n    if (*std::max_element(indices.begin(), indices.end()) >=\n        static_cast<T2>(positions.size() / 3)) {\n        throw std::runtime_error(\n            \"Input indices is out of range of the position vector\");\n    }\n    using Point = std::array<T1, 3>;\n\n    // marks[duplicate] = first\n    // duplicate and first are indices into the position vector\n    std::map<size_t, size_t> marks;\n\n    // unique_points[point] = index\n    // index refers to the position vector\n    std::unordered_map<Point, size_t, boost::hash<Point>> unique_points;\n\n    // Map all the duplicate positions to their first appearance\n    for (size_t i = 0; i < positions.size(); i += 3) {\n        Point p{ { positions[i], positions[i + 1], positions[i + 2] } };\n        auto [iter, is_unique] = unique_points.try_emplace(std::move(p), i);\n        if (!is_unique) {\n            EASSERT(p == iter->first);\n            marks[i] = iter->second;\n        }\n    }\n\n    size_t idx = positions.size() - 3;\n\n    // values in index_swap refers to the index of a Point\n    std::vector<size_t> index_swap(positions.size() / 3);\n    std::iota(index_swap.begin(), index_swap.end(), 0);\n\n    for (auto iter = marks.rbegin(); iter != marks.rend(); ++iter, idx -= 3) {\n        // Replace positions in marks with positions in the back of the vector\n        auto pos = iter->first;\n        positions[pos] = positions[idx];\n        positions[pos + 1] = positions[idx + 1];\n        positions[pos + 2] = positions[idx + 2];\n\n        // Swap indices accordingly\n        std::swap(index_swap[pos / 3], index_swap[idx / 3]);\n    }\n\n    // index_map[old] = new\n    // old and new are indices of Point\n    std::vector<size_t> index_map(positions.size() / 3);\n\n    for (size_t i = 0; i < index_swap.size() - marks.size(); ++i) {\n        EASSERT(marks.find(index_swap[i] * 3) == marks.end());\n        index_map[index_swap[i]] = i;\n    }\n    for (size_t i = index_swap.size() - marks.size(); i < index_swap.size();\n         ++i) {\n        EASSERT(marks.find(index_swap[i] * 3) != marks.end());\n        index_map[index_swap[i]] = index_map[marks[index_swap[i] * 3] / 3];\n    }\n\n    // Now fix indices\n    for (auto& i : indices) {\n        auto new_idx = index_map[i];\n        EASSERT(new_idx < (positions.size() / 3 - marks.size()));\n        i = static_cast<T2>(new_idx);\n    }\n\n    // Now erase garbage values at the tail of the vector\n    positions.erase(positions.begin() + idx + 3, positions.end());\n    positions.shrink_to_fit();\n\n    return marks.size();\n}\n\ntemplate<int N, typename T>\nsize_t remove_duplicate_faces(std::vector<T>& indices)\n{\n    static_assert(N >= 3);\n    if (indices.empty()) {\n        EWARNING(\"indices is empty.\");\n        return 0;\n    }\n    if (indices.size() % N != 0) {\n        std::string err_str(\"Input index size is not divisible by \");\n        err_str.append(std::to_string(N));\n        throw(err_str);\n    }\n    using Face = std::array<T, N>;\n\n    std::unordered_set<Face, boost::hash<Face>> unique_faces;\n    std::vector<size_t> marks;\n    for (size_t i = 0; i < indices.size(); i += N) {\n        Face f;\n        for (size_t j = 0; j < N; ++j) {\n            f[j] = indices[i + j];\n        }\n        auto cf = _impl::to_canonical<T, N>(f);\n        auto [iter, is_unique] = unique_faces.insert(std::move(cf));\n        if (!is_unique) {\n            marks.push_back(i);\n        }\n    }\n\n    size_t idx = indices.size() - N;\n    for (auto iter = marks.rbegin(); iter != marks.rend(); ++iter, idx -= N) {\n        for (size_t i = 0; i < N; ++i) {\n            indices[*iter + i] = indices[idx + i];\n        }\n    }\n\n    indices.erase(indices.begin() + idx + N, indices.end());\n    indices.shrink_to_fit();\n\n    return marks.size();\n}\n\ntemplate<int N, typename T1, typename T2>\nsize_t remove_unreferenced_vertices(std::vector<T1>& positions,\n                                    std::vector<T2>& indices)\n{\n    static_assert(N >= 3);\n    if (positions.empty()) {\n        EWARNING(\"positions is empty.\");\n        return 0;\n    }\n    if (indices.empty()) {\n        EWARNING(\"indices is empty.\");\n        return 0;\n    }\n    if (positions.size() % 3 != 0) {\n        throw std::runtime_error(\"Input position size is not divisible by 3\");\n    }\n    if (indices.size() % N != 0) {\n        std::string err_str(\"Input index size is not divisible by \");\n        err_str.append(std::to_string(N));\n        throw(err_str);\n    }\n    if (*std::max_element(indices.begin(), indices.end()) >=\n        static_cast<T2>(positions.size() / 3)) {\n        throw std::runtime_error(\n            \"Input indices is out of range of the position vector\");\n    }\n\n    std::vector<int> ref_count(positions.size() / 3, 0);\n    for (auto i : indices) {\n        ++ref_count[i];\n    }\n\n    size_t idx = ref_count.size() - 1;\n    std::vector<T2> index_swap(ref_count.size());\n    std::iota(index_swap.begin(), index_swap.end(), 0);\n    for (int i = static_cast<int>(ref_count.size()) - 1; i >= 0; --i) {\n        if (ref_count[i] == 0) {\n            for (auto j = 0; j < 3; ++j) {\n                positions[i * 3 + j] = positions[idx * 3 + j];\n            }\n            std::swap(index_swap[i], index_swap[idx--]);\n        }\n    }\n\n    std::unordered_map<T2, size_t> index_map;\n    for (size_t i = 0; i <= idx; ++i) {\n        index_map[index_swap[i]] = i;\n    }\n\n    for (auto& i : indices) {\n        i = static_cast<T2>(index_map[i]);\n    }\n\n    positions.erase(positions.begin() + (idx + 1) * 3, positions.end());\n    positions.shrink_to_fit();\n\n    return ref_count.size() - idx - 1;\n}\n\ntemplate<int N, typename T1, typename T2>\nsize_t remove_degenerate_faces(const std::vector<T1>& positions,\n                               std::vector<T2>& indices)\n{\n    static_assert(N >= 3);\n    if (positions.empty()) {\n        EWARNING(\"position is empty.\");\n        return 0;\n    }\n    if (indices.empty()) {\n        EWARNING(\"indices is empty.\");\n        return 0;\n    }\n    if (positions.size() % 3 != 0) {\n        throw std::runtime_error(\"Input position size is not divisible by 3\");\n    }\n    if (indices.size() % N != 0) {\n        std::string err_str(\"Input index size is not divisible by \");\n        err_str.append(std::to_string(N));\n        throw(err_str);\n    }\n    if (*std::max_element(indices.begin(), indices.end()) >=\n        static_cast<T2>(positions.size() / 3)) {\n        throw std::runtime_error(\n            \"Input indices is out of range of the position vector\");\n    }\n    using Kernel = CGAL::Simple_cartesian<T1>;\n    using Point_3 = typename Kernel::Point_3;\n\n    std::vector<size_t> marks;\n    for (size_t i = 0; i < indices.size(); i += N) {\n        for (size_t j = 0; j < N - 1; ++j) {\n            auto p0 = indices[i + j] * 3;\n            auto p1 = indices[i + j + 1] * 3;\n            auto p2 = (j == N - 2 ? indices[i] : indices[i + j + 2]) * 3;\n            auto x0 = positions[p0];\n            auto y0 = positions[p0 + 1];\n            auto z0 = positions[p0 + 2];\n            auto x1 = positions[p1];\n            auto y1 = positions[p1 + 1];\n            auto z1 = positions[p1 + 2];\n            auto x2 = positions[p2];\n            auto y2 = positions[p2 + 1];\n            auto z2 = positions[p2 + 2];\n            if (CGAL::collinear<Kernel>(Point_3{ x0, y0, z0 },\n                                        Point_3{ x1, y1, z1 },\n                                        Point_3{ x2, y2, z2 })) {\n                marks.push_back(i);\n                break;\n            }\n        }\n    }\n\n    auto idx = indices.size() - N;\n    for (auto iter = marks.rbegin(); iter != marks.rend(); ++iter, idx -= N) {\n        for (auto i = 0; i < N; ++i) {\n            indices[*iter + i] = indices[idx + i];\n        }\n    }\n\n    indices.erase(indices.begin() + idx + N, indices.end());\n    indices.shrink_to_fit();\n\n    return marks.size();\n}\n\n} // namespace Euclid\n", "meta": {"hexsha": "ba9a398babb32b5a574ae0fb1822cedb27e2a413", "size": 10542, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Euclid/IO/src/InputFixer.cpp", "max_stars_repo_name": "unclejimbo/euclid", "max_stars_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2017-05-02T07:04:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T10:00:01.000Z", "max_issues_repo_path": "include/Euclid/IO/src/InputFixer.cpp", "max_issues_repo_name": "unclejimbo/euclid", "max_issues_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Euclid/IO/src/InputFixer.cpp", "max_forks_repo_name": "unclejimbo/euclid", "max_forks_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-07-02T17:59:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-18T07:01:17.000Z", "avg_line_length": 31.2818991098, "max_line_length": 78, "alphanum_fraction": 0.5561563271, "num_tokens": 2814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.27779216365272413}}
{"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 <vector>\n#include <memory>\n#include <iostream>\n#include <iomanip>\n#include <boost/noncopyable.hpp>\n#include \"Eigen/Core\"\n#include \"Eigen/LU\"\n#include \"metro/regression/Design.hpp\"\n#include \"metro/regression/LogLikelihood.hpp\"\n#include \"metro/regression/IndependentNormalWeightedLogLikelihood.hpp\"\n\n// #define DEBUG_NORMALWEIGHTEDLOGLIKELIHOOD 1\n\nnamespace metro {\n\tnamespace regression {\n\t\tIndependentNormalWeightedLogLikelihood::UniquePtr IndependentNormalWeightedLogLikelihood::create(\n\t\t\tLogLikelihood::UniquePtr ll,\n\t\t\tstd::vector< int > parameter_indices,\n\t\t\tstd::vector< double > means,\n\t\t\tstd::vector< double > variances\n\t\t) {\n\t\t\treturn UniquePtr( new IndependentNormalWeightedLogLikelihood( ll, parameter_indices, means, variances ) ) ;\n\t\t}\n\n\t\tIndependentNormalWeightedLogLikelihood::IndependentNormalWeightedLogLikelihood(\n\t\t\tLogLikelihood::UniquePtr ll,\n\t\t\tstd::vector< int > parameter_indices,\n\t\t\tstd::vector< double > means,\n\t\t\tstd::vector< double > variances\n\t\t):\n\t\t\tm_ll( ll ),\n\t\t\tm_parameter_indices( parameter_indices ),\n\t\t\tm_means( means ),\n\t\t\tm_variances( variances ),\n\t\t\tm_normalisation( eZeroAtMean ),\n\t\t\tm_constant( 0.0 ) // ll when at mean\n\t\t{\n\t\t\tif( m_normalisation == eZeroAtMean ) {\n\t\t\t\tm_constant = 0.0 ;\n\t\t\t} else if( m_normalisation == ePDF ) {\n\t\t\t\tassert(0) ; // This may not be correct yet\n\t\t\t\tm_constant = 0.0 ;\n\t\t\t\tfor( std::size_t i = 0; i < m_parameter_indices.size(); ++i ) {\n\t\t\t\t\tm_constant -= std::log( std::sqrt( 2.0 * 3.14159265358979323846 * m_variances[i] )) ;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tassert(0) ;\n\t\t\t}\n\t\t}\n\n\t\tstd::string IndependentNormalWeightedLogLikelihood::get_parameter_name( std::size_t i ) const {\n\t\t\treturn m_ll->get_parameter_name(i) ;\n\t\t}\n\t\tIndependentNormalWeightedLogLikelihood::IntegerMatrix IndependentNormalWeightedLogLikelihood::identify_parameters() const {\n\t\t\treturn m_ll->identify_parameters() ;\n\t\t}\n\t\t\n\t\tint IndependentNormalWeightedLogLikelihood::number_of_parameters() const {\n\t\t\treturn m_ll->number_of_parameters() ;\n\t\t}\n\n\t\tint IndependentNormalWeightedLogLikelihood::number_of_outcomes() const {\n\t\t\treturn m_ll->number_of_outcomes() ;\n\t\t}\n\t\t\n\t\tvoid IndependentNormalWeightedLogLikelihood::evaluate_at( Point const& parameters, int const numberOfDerivatives ) {\n\t\t\tm_ll->evaluate_at( parameters, numberOfDerivatives ) ;\n\t\t\tevaluate( numberOfDerivatives ) ;\n\t\t}\n\t\t\n\t\tvoid IndependentNormalWeightedLogLikelihood::evaluate( int const numberOfDerivatives ) {\n\t\t\tm_ll->evaluate( numberOfDerivatives ) ;\n\t\t\tVector const& parameters = m_ll->parameters() ;\n\n\t\t\tm_value_of_function = 0.0 ;\n\t\t\tm_value_of_first_derivative.setZero( parameters.size() ) ;\n\t\t\tm_value_of_second_derivative.setZero( parameters.size(), parameters.size() ) ;\n\t\t\tfor( std::size_t i = 0; i < m_parameter_indices.size(); ++i ) {\n\t\t\t\tint const& parameter_index = m_parameter_indices[i] ;\n\t\t\t\tassert( parameter_index >= 0 && parameter_index < parameters.size() ) ;\n\t\t\t\tdouble const centralised = (parameters(parameter_index)-m_means[i]) ;\n\n\t\t\t\tm_value_of_function += -0.5 * (centralised * centralised) / m_variances[i] ;\n\t\t\t\tm_value_of_first_derivative( parameter_index ) = -centralised / m_variances[i] ;\n\t\t\t\tm_value_of_second_derivative( parameter_index, parameter_index )\n\t\t\t\t\t= -1.0 / m_variances[i] ;\n\t\t\t}\n\t\t\tm_value_of_function += m_constant ;\n\t\t}\n\t\t\n\t\tIndependentNormalWeightedLogLikelihood::Vector IndependentNormalWeightedLogLikelihood::get_prior_mode() const {\n\t\t\tVector result = Vector::Zero( m_value_of_first_derivative.size() ) ;\n\t\t\tfor( std::size_t i = 0; i < m_parameter_indices.size(); ++i ) {\n\t\t\t\tresult(i) = m_means[i] ;\n\t\t\t}\n\t\t\treturn result ;\n\t\t}\n\t\n\t\tstd::string IndependentNormalWeightedLogLikelihood::get_summary() const {\n\t\t\tstd::ostringstream ostr ;\n\t\t\tostr << \"independently-normal-weighted:\" << m_ll->get_summary() << \"\\n\" ;\n\t\t\tostr << \"independently-normal-weighted: using the following prior parameters:\\n\" ;\n\t\t\tstd::size_t max_label_length = 0 ;\n\t\t\tint const numberOfParameters = m_ll->identify_parameters().rows() ;\n\t\t\tfor( int i = 0; i < numberOfParameters; ++i ) {\n\t\t\t\tmax_label_length = std::max( max_label_length, m_ll->get_parameter_name(i).size() ) ;\n\t\t\t}\n\t\t\tostr\n\t\t\t\t<< std::setw(3) << \"\" << \"  \"\n\t\t\t\t<< std::setw( max_label_length + 2 ) << \"\"\n\t\t\t\t<< \":\"\n\t\t\t\t<< \" \" << std::setw(5) << \"mean\"\n\t\t\t\t<< \" \" << std::setw(8) << \"variance\"\n\t\t\t\t<< \"\\n\" ;\n\t\t\tfor( std::size_t i = 0; i < m_parameter_indices.size(); ++i ) {\n\t\t\t\tint const parameter_index = m_parameter_indices[i] ;\n\t\t\t\tostr << std::setw(3) << parameter_index\n\t\t\t\t\t<< \": \" << std::setw( max_label_length + 2 ) << m_ll->get_parameter_name(parameter_index) << \":\" ;\n\t\t\t\t\tostr\n\t\t\t\t\t\t<< \" \" << std::setw(5) << m_means[i]\n\t\t\t\t\t\t<< \" \" << std::setw(8) << m_variances[i]\n\t\t\t\t\t\t<< \"\\n\" ;\n\t\t\t}\n\t\t\treturn ostr.str() ;\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "8930294b601ab469fc4cc800d684603da2da935e", "size": 4957, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "metro/src/regression/IndependentNormalWeightedLogLikelihood.cpp", "max_stars_repo_name": "gavinband/qctool", "max_stars_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-21T05:42:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T14:59:43.000Z", "max_issues_repo_path": "metro/src/regression/IndependentNormalWeightedLogLikelihood.cpp", "max_issues_repo_name": "gavinband/qctool", "max_issues_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-09T16:11:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T11:18:56.000Z", "max_forks_repo_path": "metro/src/regression/IndependentNormalWeightedLogLikelihood.cpp", "max_forks_repo_name": "gavinband/qctool", "max_forks_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9925373134, "max_line_length": 125, "alphanum_fraction": 0.6893282227, "num_tokens": 1380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548782017744, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.27768664898855705}}
{"text": "/*\n    This file is part of Mitsuba, a physically based rendering system.\n\n    Copyright (c) 2007-2014 by Wenzel Jakob and others.\n\n    Mitsuba is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License Version 3\n    as published by the Free Software Foundation.\n\n    Mitsuba is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <mitsuba/core/chisquare.h>\n#include <mitsuba/core/quad.h>\n#include <mitsuba/core/timer.h>\n#include <boost/math/distributions/chi_squared.hpp>\n#include <boost/bind.hpp>\n#include <boost/filesystem/fstream.hpp>\n#include <set>\n\nMTS_NAMESPACE_BEGIN\n\n/* Simple ordering for storing vectors in a set */\nstruct VectorOrder {\n    inline int compare(const Vector &v1, const Vector &v2) const {\n        if (v1.x < v2.x) return -1;\n        else if (v1.x > v2.x) return 1;\n        if (v1.y < v2.y) return -1;\n        else if (v1.y > v2.y) return 1;\n        if (v1.z < v2.z) return -1;\n        else if (v1.z > v2.z) return 1;\n        return 0;\n    }\n\n    bool operator()(const Vector &v1, const Vector &v2) const {\n        return compare(v1, v2) < 0;\n    }\n};\n\nChiSquare::ChiSquare(int thetaBins, int phiBins, int numTests,\n        size_t sampleCount) : m_logLevel(EInfo), m_thetaBins(thetaBins),\n          m_phiBins(phiBins), m_numTests(numTests), m_sampleCount(sampleCount) {\n    if (m_phiBins == 0)\n        m_phiBins = 2*m_thetaBins;\n    if (m_sampleCount == 0)\n        m_sampleCount = m_thetaBins * m_phiBins * 1000;\n    m_table = new Float[m_thetaBins*m_phiBins];\n    m_refTable = new Float[m_thetaBins*m_phiBins];\n    m_tolerance = m_sampleCount * 1e-4f;\n}\n\nChiSquare::~ChiSquare() {\n    delete[] m_table;\n    delete[] m_refTable;\n}\n\nvoid ChiSquare::dumpTables(const fs::path &filename) {\n    fs::ofstream out(filename);\n    out << \"tbl_counts = [ \";\n    for (int i=0; i<m_thetaBins; ++i) {\n        for (int j=0; j<m_phiBins; ++j) {\n            out << m_table[i*m_phiBins+j];\n            if (j+1 < m_phiBins)\n                out << \", \";\n        }\n        if (i+1 < m_thetaBins)\n            out << \"; \";\n    }\n    out << \" ];\" << endl\n        << \"tbl_ref = [ \";\n    for (int i=0; i<m_thetaBins; ++i) {\n        for (int j=0; j<m_phiBins; ++j) {\n            out << m_refTable[i*m_phiBins+j];\n            if (j+1 < m_phiBins)\n                out << \", \";\n        }\n        if (i+1 < m_thetaBins)\n            out << \"; \";\n    }\n    out << \" ];\" << endl;\n    out.close();\n}\n\nvoid ChiSquare::fill(\n    const boost::function<boost::tuple<Vector, Float, EMeasure>()> &sampleFn,\n    const boost::function<Float (const Vector &, EMeasure measure)> &pdfFn) {\n    memset(m_table, 0, m_thetaBins*m_phiBins*sizeof(Float));\n    memset(m_refTable, 0, m_thetaBins*m_phiBins*sizeof(Float));\n\n    Log(m_logLevel, \"Accumulating \" SIZE_T_FMT \" samples into a %ix%i\"\n            \" contingency table\", m_sampleCount, m_thetaBins, m_phiBins);\n    Point2 factor(m_thetaBins / M_PI, m_phiBins / (2*M_PI));\n\n    std::set<Vector, VectorOrder> discreteDirections;\n\n    ref<Timer> timer = new Timer();\n    for (size_t i=0; i<m_sampleCount; ++i) {\n        boost::tuple<Vector, Float, EMeasure> sample = sampleFn();\n        Point2 sphCoords = toSphericalCoordinates(boost::get<0>(sample));\n\n        int thetaBin = std::min(std::max(0,\n            math::floorToInt(sphCoords.x * factor.x)), m_thetaBins-1);\n        int phiBin = std::min(std::max(0,\n            math::floorToInt(sphCoords.y * factor.y)), m_phiBins-1);\n        m_table[thetaBin * m_phiBins + phiBin] += boost::get<1>(sample);\n        if (boost::get<1>(sample) > 0 && boost::get<2>(sample) == EDiscrete)\n            discreteDirections.insert(boost::get<0>(sample));\n    }\n\n    if (discreteDirections.size() > 0) {\n        Log(EDebug, \"Incorporating the disrete density over \"\n            SIZE_T_FMT \" direction(s) into the contingency table\", discreteDirections.size());\n        for (std::set<Vector, VectorOrder>::const_iterator it = discreteDirections.begin();\n            it != discreteDirections.end(); ++it) {\n            const Vector &direction = *it;\n            Point2 sphCoords = toSphericalCoordinates(direction);\n            Float pdf = pdfFn(direction, EDiscrete);\n\n            int thetaBin = std::min(std::max(0,\n                math::floorToInt(sphCoords.x * factor.x)), m_thetaBins-1);\n            int phiBin = std::min(std::max(0,\n                math::floorToInt(sphCoords.y * factor.y)), m_phiBins-1);\n\n            m_refTable[thetaBin * m_phiBins + phiBin] += pdf * m_sampleCount;\n        }\n    }\n\n    factor = Point2(M_PI / m_thetaBins, (2*M_PI) / m_phiBins);\n\n    Log(m_logLevel, \"Done, took %i ms. Integrating reference \"\n        \"contingency table ..\", timer->getMilliseconds());\n    timer->reset();\n    Float min[2], max[2];\n    size_t idx = 0;\n\n    NDIntegrator integrator(1, 2, 100000, 0, 1e-6f);\n    Float maxError = 0, integral = 0;\n    for (int i=0; i<m_thetaBins; ++i) {\n        min[0] = i * factor.x;\n        max[0] = (i+1) * factor.x;\n        for (int j=0; j<m_phiBins; ++j) {\n            min[1] = j * factor.y;\n            max[1] = (j+1) * factor.y;\n            Float result, error;\n\n            integrator.integrateVectorized(\n                boost::bind(&ChiSquare::integrand, pdfFn, _1, _2, _3),\n                min, max, &result, &error\n            );\n\n            integral += result;\n            m_refTable[idx++] += result * m_sampleCount;\n            maxError = std::max(maxError, error);\n        }\n    }\n\n    Log(m_logLevel, \"Done, took %i ms (max error = %f, integral=%f).\",\n            timer->getMilliseconds(), maxError, integral);\n}\n\nstruct SortedCell {\n    Float expCount;\n    int idx;\n};\n\nstruct SortedCellFunctor {\n    inline bool operator()(const SortedCell &c1, const SortedCell &c2) const {\n        return c1.expCount < c2.expCount;\n    }\n};\n\nChiSquare::ETestResult ChiSquare::runTest(Float pvalThresh) {\n    /* Compute the chi-square statistic */\n    Float pooledCounts = 0, pooledRef = 0, chsq = 0.0f;\n    int pooledCells = 0, df = 0;\n\n    /* Process cells in order sorted by their expected counts */\n    std::vector<SortedCell> cells(m_thetaBins*m_phiBins);\n    for (int i=0; i<m_thetaBins*m_phiBins; ++i) {\n        cells[i].expCount = m_refTable[i];\n        cells[i].idx = i;\n    }\n\n    std::sort(cells.begin(), cells.end(), SortedCellFunctor());\n\n    std::vector<SortedCell>::iterator it = cells.begin();\n\n    while (it != cells.end()) {\n        int idx = it->idx;\n\n        if (m_refTable[idx] == 0) {\n            if (m_table[idx] > m_tolerance) {\n                /* Special handler for cells with an expected frequency of zero */\n                Log(EWarn, \"Encountered a cell (%i) with an expected frequency of zero, \"\n                    \"where the actual number of observations is %f! Rejecting the \"\n                    \"null hypothesis.\", idx, m_table[idx]);\n                return EReject;\n            }\n        } else if (m_refTable[idx] < CHISQR_MIN_EXP_FREQUENCY) {\n            /* Pool cells with low expected frequencies */\n            pooledCounts += m_table[idx];\n            pooledRef += m_refTable[idx];\n            ++pooledCells;\n        } else if (pooledRef > 0 && pooledRef < CHISQR_MIN_EXP_FREQUENCY) {\n            /* Pool more cells until the merged cell\n               has a sufficiently high frequency */\n            pooledCounts += m_table[idx];\n            pooledRef += m_refTable[idx];\n            ++pooledCells;\n        } else {\n            Float diff = m_table[idx]-m_refTable[idx];\n            chsq += (diff*diff) / m_refTable[idx];\n            ++df;\n        }\n\n        ++it;\n    }\n\n    if (pooledCells > 0) {\n        Log(m_logLevel, \"Pooled %i cells to ensure sufficiently \"\n            \"high expected frequencies (> %f).\", pooledCells,\n            (Float) CHISQR_MIN_EXP_FREQUENCY);\n        Float diff = pooledCounts - pooledRef;\n        chsq += (diff*diff) / pooledRef;\n        ++df;\n    }\n\n    /* All parameters are assumed to be known, so there is no\n       DF reduction due to model parameters */\n    df -= 1;\n\n    Log(m_logLevel, \"Chi-square statistic = %e (df=%i)\", chsq, df);\n\n    if (df <= 0) {\n        Log(m_logLevel, \"The number of degrees of freedom (%i) is too low!\", df);\n        return ELowDoF;\n    }\n\n    /* Probability of obtaining a test statistic at least\n       as extreme as the one observed under the assumption\n       that the distributions match */\n    boost::math::chi_squared chSqDist(df);\n    Float pval = 1 - (Float) boost::math::cdf(chSqDist, chsq);\n\n    /* Apply the Sidak correction for multiple independent hypothesis tests */\n    Float alpha = 1 - std::pow(1 - pvalThresh, 1 / (Float) m_numTests);\n\n    if (pval < alpha) {\n        Log(EWarn, \"Rejected the null hypothesis (P-value = %e, \"\n            \"significance level = %e)\", pval, alpha);\n        return EReject;\n    } else {\n        Log(m_logLevel, \"Accepted the null hypothesis (P-value = %e, \"\n            \"significance level = %e)\", pval, alpha);\n        return EAccept;\n    }\n}\n\nMTS_IMPLEMENT_CLASS(ChiSquare, false, Object)\nMTS_NAMESPACE_END\n", "meta": {"hexsha": "f684e471b450ef94091ea9e28752c2d65720a6c7", "size": 9361, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mitsuba/src/libcore/chisquare.cpp", "max_stars_repo_name": "anadodik/sdmm-mitsuba", "max_stars_repo_head_hexsha": "6103cb8ea36ec4ab0cfb5fcc792c7f1565637d9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-07-07T09:46:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T14:16:27.000Z", "max_issues_repo_path": "mitsuba/src/libcore/chisquare.cpp", "max_issues_repo_name": "anadodik/sdmm-mitsuba", "max_issues_repo_head_hexsha": "6103cb8ea36ec4ab0cfb5fcc792c7f1565637d9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mitsuba/src/libcore/chisquare.cpp", "max_forks_repo_name": "anadodik/sdmm-mitsuba", "max_forks_repo_head_hexsha": "6103cb8ea36ec4ab0cfb5fcc792c7f1565637d9a", "max_forks_repo_licenses": ["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.0599250936, "max_line_length": 94, "alphanum_fraction": 0.5930990279, "num_tokens": 2517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2776401202318738}}
{"text": "#ifndef VIENNACL_LINALG_SVD_HPP\n#define VIENNACL_LINALG_SVD_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/svd.hpp\n    @brief Provides singular value decomposition using a block-based approach.  Experimental.\n\n    Contributed by Volodymyr Kysenko.\n*/\n\n\n// Note: Boost.uBLAS is required at the moment\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\n\n#include <cmath>\n\n#include \"viennacl/matrix.hpp\"\n#include \"viennacl/linalg/opencl/kernels/svd.hpp\"\n#include \"viennacl/linalg/qr-method-common.hpp\"\n\nnamespace viennacl\n{\n  namespace linalg\n  {\n\n    namespace detail\n    {\n\n      template<typename MatrixType, typename VectorType>\n      void givens_prev(MatrixType & matrix,\n                       VectorType & tmp1,\n                       VectorType & tmp2,\n                       int n,\n                       int l,\n                       int k\n                      )\n      {\n        typedef typename MatrixType::value_type                                   ScalarType;\n        typedef typename viennacl::result_of::cpu_value_type<ScalarType>::type    CPU_ScalarType;\n\n        viennacl::ocl::context & ctx = const_cast<viennacl::ocl::context &>(viennacl::traits::opencl_handle(matrix).context());\n        viennacl::ocl::kernel & kernel = ctx.get_kernel(viennacl::linalg::opencl::kernels::svd<CPU_ScalarType>::program_name(), SVD_GIVENS_PREV_KERNEL);\n\n        kernel.global_work_size(0, viennacl::tools::align_to_multiple<vcl_size_t>(viennacl::traits::size1(matrix), 256));\n        kernel.local_work_size(0, 256);\n\n        viennacl::ocl::enqueue(kernel(\n                                      matrix,\n                                      tmp1,\n                                      tmp2,\n                                      static_cast<cl_uint>(n),\n                                      static_cast<cl_uint>(matrix.internal_size1()),\n                                      static_cast<cl_uint>(l + 1),\n                                      static_cast<cl_uint>(k + 1)\n                              ));\n      }\n\n\n      template<typename MatrixType, typename VectorType>\n      void change_signs(MatrixType& matrix, VectorType& signs, int n)\n      {\n        typedef typename MatrixType::value_type                                   ScalarType;\n        typedef typename viennacl::result_of::cpu_value_type<ScalarType>::type    CPU_ScalarType;\n\n        viennacl::ocl::context & ctx = const_cast<viennacl::ocl::context &>(viennacl::traits::opencl_handle(matrix).context());\n        viennacl::ocl::kernel & kernel = ctx.get_kernel(viennacl::linalg::opencl::kernels::svd<CPU_ScalarType>::program_name(), SVD_INVERSE_SIGNS_KERNEL);\n\n        kernel.global_work_size(0, viennacl::tools::align_to_multiple<vcl_size_t>(viennacl::traits::size1(matrix), 16));\n        kernel.global_work_size(1, viennacl::tools::align_to_multiple<vcl_size_t>(viennacl::traits::size2(matrix), 16));\n\n        kernel.local_work_size(0, 16);\n        kernel.local_work_size(1, 16);\n\n        viennacl::ocl::enqueue(kernel(\n                                      matrix,\n                                      signs,\n                                      static_cast<cl_uint>(n),\n                                      static_cast<cl_uint>(matrix.internal_size1())\n                              ));\n      }\n\n      template<typename MatrixType, typename CPU_VectorType>\n      void svd_qr_shift(MatrixType & vcl_u,\n                        MatrixType & vcl_v,\n                        CPU_VectorType & q,\n                        CPU_VectorType & e)\n      {\n        typedef typename MatrixType::value_type                                   ScalarType;\n        typedef typename viennacl::result_of::cpu_value_type<ScalarType>::type    CPU_ScalarType;\n\n        vcl_size_t n = q.size();\n        int m = static_cast<int>(vcl_u.size1());\n\n        detail::transpose(vcl_u);\n        detail::transpose(vcl_v);\n\n        std::vector<CPU_ScalarType> signs_v(n, 1);\n        std::vector<CPU_ScalarType> cs1(n), ss1(n), cs2(n), ss2(n);\n\n        viennacl::vector<CPU_ScalarType> tmp1(n, viennacl::traits::context(vcl_u)), tmp2(n, viennacl::traits::context(vcl_u));\n\n        bool goto_test_conv = false;\n\n        for (int k = static_cast<int>(n) - 1; k >= 0; k--)\n        {\n          // std::cout << \"K = \" << k << std::endl;\n\n          vcl_size_t iter = 0;\n          for (iter = 0; iter < detail::ITER_MAX; iter++)\n          {\n            // test for split\n            int l;\n            for (l = k; l >= 0; l--)\n            {\n              goto_test_conv = false;\n              if (std::fabs(e[vcl_size_t(l)]) <= detail::EPS)\n              {\n                // set it\n                goto_test_conv = true;\n                break;\n              }\n\n              if (std::fabs(q[vcl_size_t(l) - 1]) <= detail::EPS)\n              {\n                // goto\n                break;\n              }\n            }\n\n            if (!goto_test_conv)\n            {\n              CPU_ScalarType c = 0.0;\n              CPU_ScalarType s = 1.0;\n\n              //int l1 = l - 1;\n              //int l2 = k;\n\n              for (int i = l; i <= k; i++)\n              {\n                CPU_ScalarType f = s * e[vcl_size_t(i)];\n                e[vcl_size_t(i)] = c * e[vcl_size_t(i)];\n\n                if (std::fabs(f) <= detail::EPS)\n                {\n                  //l2 = i - 1;\n                  break;\n                }\n\n                CPU_ScalarType g = q[vcl_size_t(i)];\n                CPU_ScalarType h = detail::pythag(f, g);\n                q[vcl_size_t(i)] = h;\n                c = g / h;\n                s = -f / h;\n\n                cs1[vcl_size_t(i)] = c;\n                ss1[vcl_size_t(i)] = s;\n              }\n\n              // std::cout << \"Hitted!\" << l1 << \" \" << l2 << \"\\n\";\n\n              // for (int i = l; i <= l2; i++)\n              // {\n              //   for (int j = 0; j < m; j++)\n              //   {\n              //     CPU_ScalarType y = u(j, l1);\n              //     CPU_ScalarType z = u(j, i);\n              //     u(j, l1) = y * cs1[i] + z * ss1[i];\n              //     u(j, i) = -y * ss1[i] + z * cs1[i];\n              //   }\n              // }\n            }\n\n            CPU_ScalarType z = q[vcl_size_t(k)];\n\n            if (l == k)\n            {\n              if (z < 0)\n              {\n                q[vcl_size_t(k)] = -z;\n\n                signs_v[vcl_size_t(k)] *= -1;\n              }\n\n              break;\n            }\n\n            if (iter >= detail::ITER_MAX - 1)\n              break;\n\n            CPU_ScalarType x = q[vcl_size_t(l)];\n            CPU_ScalarType y = q[vcl_size_t(k) - 1];\n            CPU_ScalarType g = e[vcl_size_t(k) - 1];\n            CPU_ScalarType h = e[vcl_size_t(k)];\n            CPU_ScalarType f = ((y - z) * (y + z) + (g - h) * (g + h)) / (2 * h * y);\n\n            g = detail::pythag<CPU_ScalarType>(f, 1);\n\n            if (f < 0) {\n              f = ((x - z) * (x + z) + h * (y / (f - g) - h)) / x;\n            } else {\n              f = ((x - z) * (x + z) + h * (y / (f + g) - h)) / x;\n            }\n\n            CPU_ScalarType c = 1;\n            CPU_ScalarType s = 1;\n\n            for (vcl_size_t i = static_cast<vcl_size_t>(l) + 1; i <= static_cast<vcl_size_t>(k); i++)\n            {\n              g = e[i];\n              y = q[i];\n              h = s * g;\n              g = c * g;\n              CPU_ScalarType z = detail::pythag(f, h);\n              e[i - 1] = z;\n              c = f / z;\n              s = h / z;\n              f = x * c + g * s;\n              g = -x * s + g * c;\n              h = y * s;\n              y = y * c;\n\n              cs1[i] = c;\n              ss1[i] = s;\n\n              z = detail::pythag(f, h);\n              q[i - 1] = z;\n              c = f / z;\n              s = h / z;\n              f = c * g + s * y;\n              x = -s * g + c * y;\n\n              cs2[i] = c;\n              ss2[i] = s;\n            }\n\n            {\n              viennacl::copy(cs1, tmp1);\n              viennacl::copy(ss1, tmp2);\n\n              givens_prev(vcl_v, tmp1, tmp2, static_cast<int>(n), l, k);\n            }\n\n            {\n              viennacl::copy(cs2, tmp1);\n              viennacl::copy(ss2, tmp2);\n\n              givens_prev(vcl_u, tmp1, tmp2, m, l, k);\n            }\n\n            e[vcl_size_t(l)] = 0.0;\n            e[vcl_size_t(k)] = f;\n            q[vcl_size_t(k)] = x;\n          }\n\n        }\n\n\n        viennacl::copy(signs_v, tmp1);\n        change_signs(vcl_v, tmp1, static_cast<int>(n));\n\n        // transpose singular matrices again\n        detail::transpose(vcl_u);\n        detail::transpose(vcl_v);\n      }\n\n\n      /*template<typename SCALARTYPE, unsigned int ALIGNMENT>\n      bool householder_c(viennacl::matrix<SCALARTYPE, row_major, ALIGNMENT> & A,\n                          viennacl::matrix<SCALARTYPE, row_major, ALIGNMENT> & Q,\n                          viennacl::vector<SCALARTYPE, ALIGNMENT> & D,\n                          vcl_size_t start)\n      {\n\n        vcl_size_t row_start = start;\n        vcl_size_t col_start = start;\n\n        if (row_start + 1 >= A.size1())\n          return false;\n\n        std::vector<SCALARTYPE> tmp(A.size1(), 0);\n\n        copy_vec(A, D, row_start, col_start, true);\n        fast_copy(D.begin(), D.begin() + (A.size1() - row_start), tmp.begin() + row_start);\n\n        detail::householder_vector(tmp, row_start);\n\n        fast_copy(tmp, D);\n\n        viennacl::ocl::kernel & kernel = viennacl::ocl::get_kernel(viennacl::linalg::opencl::kernels::svd<SCALARTYPE>::program_name(), SVD_HOUSEHOLDER_COL_KERNEL);\n\n        //kernel.global_work_size(0, A.size1() << 1);\n\n        viennacl::ocl::enqueue(kernel(\n                                      A,\n                                      Q,\n                                      D,\n                                      static_cast<cl_uint>(row_start),\n                                      static_cast<cl_uint>(col_start),\n                                      static_cast<cl_uint>(A.size1()),\n                                      static_cast<cl_uint>(A.size2()),\n                                      static_cast<cl_uint>(A.internal_size2()),\n                                      static_cast<cl_uint>(Q.internal_size2()),\n                                      viennacl::ocl::local_mem(static_cast<cl_uint>(128 * sizeof(SCALARTYPE)))\n                              ));\n\n        return true;\n      }*/\n\n      template<typename SCALARTYPE, unsigned int ALIGNMENT>\n      bool householder_c(viennacl::matrix<SCALARTYPE, row_major, ALIGNMENT>& A,\n                          viennacl::matrix<SCALARTYPE, row_major, ALIGNMENT>& Q,\n                          viennacl::vector<SCALARTYPE, ALIGNMENT>& D,\n                          vcl_size_t row_start, vcl_size_t col_start)\n      {\n        viennacl::ocl::context & ctx = const_cast<viennacl::ocl::context &>(viennacl::traits::opencl_handle(A).context());\n\n        if (row_start + 1 >= A.size1())\n          return false;\n\n        prepare_householder_vector(A, D, A.size1(), row_start, col_start, row_start, true);\n\n        {\n          viennacl::ocl::kernel& kernel = ctx.get_kernel(viennacl::linalg::opencl::kernels::svd<SCALARTYPE>::program_name(), SVD_HOUSEHOLDER_UPDATE_A_LEFT_KERNEL);\n\n          viennacl::ocl::enqueue(kernel(\n                                        A,\n                                        D,\n                                        static_cast<cl_uint>(row_start),\n                                        static_cast<cl_uint>(col_start),\n                                        static_cast<cl_uint>(A.size1()),\n                                        static_cast<cl_uint>(A.size2()),\n                                        static_cast<cl_uint>(A.internal_size2()),\n                                        viennacl::ocl::local_mem(static_cast<cl_uint>(128 * sizeof(SCALARTYPE)))\n                                ));\n\n        }\n\n        {\n          viennacl::ocl::kernel& kernel = ctx.get_kernel(viennacl::linalg::opencl::kernels::svd<SCALARTYPE>::program_name(), SVD_HOUSEHOLDER_UPDATE_QL_KERNEL);\n\n          viennacl::ocl::enqueue(kernel(\n                                        Q,\n                                        D,\n                                        static_cast<cl_uint>(A.size1()),\n                                      //  static_cast<cl_uint>(A.size2()),\n                                        static_cast<cl_uint>(Q.internal_size2()),\n                                        viennacl::ocl::local_mem(static_cast<cl_uint>(128 * sizeof(SCALARTYPE)))\n                                ));\n\n        }\n\n        return true;\n      }\n\n      /*\n      template<typename SCALARTYPE, unsigned int ALIGNMENT>\n      bool householder_r(viennacl::matrix<SCALARTYPE, row_major, ALIGNMENT>& A,\n                          viennacl::matrix<SCALARTYPE, row_major, ALIGNMENT>& Q,\n                          viennacl::vector<SCALARTYPE, ALIGNMENT>& S,\n                          vcl_size_t start)\n      {\n\n        vcl_size_t row_start = start;\n        vcl_size_t col_start = start + 1;\n\n        if (col_start + 1 >= A.size2())\n          return false;\n\n        std::vector<SCALARTYPE> tmp(A.size2(), 0);\n\n        copy_vec(A, S, row_start, col_start, false);\n        fast_copy(S.begin(),\n                  S.begin() + (A.size2() - col_start),\n                  tmp.begin() + col_start);\n\n        detail::householder_vector(tmp, col_start);\n        fast_copy(tmp, S);\n\n        viennacl::ocl::kernel& kernel = viennacl::ocl::get_kernel(viennacl::linalg::opencl::kernels::svd<SCALARTYPE>::program_name(), SVD_HOUSEHOLDER_ROW_KERNEL);\n\n        viennacl::ocl::enqueue(kernel(\n                                      A,\n                                      Q,\n                                      S,\n                                      static_cast<cl_uint>(row_start),\n                                      static_cast<cl_uint>(col_start),\n                                      static_cast<cl_uint>(A.size1()),\n                                      static_cast<cl_uint>(A.size2()),\n                                      static_cast<cl_uint>(A.internal_size2()),\n                                      static_cast<cl_uint>(Q.internal_size2()),\n                                      viennacl::ocl::local_mem(static_cast<cl_uint>(128 * sizeof(SCALARTYPE)))\n                                ));\n        return true;\n      } */\n\n      template<typename SCALARTYPE, unsigned int ALIGNMENT>\n      bool householder_r(viennacl::matrix<SCALARTYPE, row_major, ALIGNMENT> & A,\n                          viennacl::matrix<SCALARTYPE, row_major, ALIGNMENT> & Q,\n                          viennacl::vector<SCALARTYPE, ALIGNMENT>& D,\n                          vcl_size_t row_start, vcl_size_t col_start)\n      {\n        viennacl::ocl::context & ctx = const_cast<viennacl::ocl::context &>(viennacl::traits::opencl_handle(A).context());\n\n        if (col_start + 1 >= A.size2())\n          return false;\n\n        prepare_householder_vector(A, D, A.size2(), row_start, col_start, col_start, false);\n\n        {\n          viennacl::ocl::kernel& kernel = ctx.get_kernel(viennacl::linalg::opencl::kernels::svd<SCALARTYPE>::program_name(), SVD_HOUSEHOLDER_UPDATE_A_RIGHT_KERNEL);\n\n          viennacl::ocl::enqueue(kernel(\n                                        A,\n                                        D,\n                                        static_cast<cl_uint>(row_start),\n                                        static_cast<cl_uint>(col_start),\n                                        static_cast<cl_uint>(A.size1()),\n                                        static_cast<cl_uint>(A.size2()),\n                                        static_cast<cl_uint>(A.internal_size2()),\n                                        viennacl::ocl::local_mem(static_cast<cl_uint>(128 * sizeof(SCALARTYPE)))\n                                ));\n        }\n\n        {\n          viennacl::ocl::kernel& kernel = ctx.get_kernel(viennacl::linalg::opencl::kernels::svd<SCALARTYPE>::program_name(), SVD_HOUSEHOLDER_UPDATE_QR_KERNEL);\n\n          viennacl::ocl::enqueue(kernel(\n                                        Q,\n                                        D,\n                                        static_cast<cl_uint>(A.size1()),\n                                        static_cast<cl_uint>(A.size2()),\n                                        static_cast<cl_uint>(Q.internal_size2()),\n                                        viennacl::ocl::local_mem(static_cast<cl_uint>(128 * sizeof(SCALARTYPE)))\n                                ));\n        }\n\n        return true;\n      }\n\n      template<typename SCALARTYPE, unsigned int ALIGNMENT>\n      void bidiag(viennacl::matrix<SCALARTYPE, row_major, ALIGNMENT> & Ai,\n                  viennacl::matrix<SCALARTYPE, row_major, ALIGNMENT> & QL,\n                  viennacl::matrix<SCALARTYPE, row_major, ALIGNMENT> & QR)\n      {\n        vcl_size_t row_num = Ai.size1();\n        vcl_size_t col_num = Ai.size2();\n\n        vcl_size_t to = std::min(row_num, col_num);\n        vcl_size_t big_to = std::max(row_num, col_num);\n\n        //for storing householder vector\n        viennacl::vector<SCALARTYPE, ALIGNMENT> hh_vector(big_to, viennacl::traits::context(Ai));\n\n        QL = viennacl::identity_matrix<SCALARTYPE>(QL.size1(), viennacl::traits::context(QL));\n        QR = viennacl::identity_matrix<SCALARTYPE>(QR.size1(), viennacl::traits::context(QR));\n\n        for (vcl_size_t i = 0; i < to; i++)\n        {\n          householder_c(Ai, QL, hh_vector, i, i);\n          householder_r(Ai, QR, hh_vector, i, i+1);\n        }\n      }\n\n    } // namespace detail\n\n\n    /** @brief Computes the singular value decomposition of a matrix A. Experimental in 1.3.x\n     *\n     * @param A     The input matrix. Will be overwritten with a diagonal matrix containing the singular values on return\n     * @param QL    The left orthogonal matrix\n     * @param QR    The right orthogonal matrix\n     */\n    template<typename SCALARTYPE, unsigned int ALIGNMENT>\n    void svd(viennacl::matrix<SCALARTYPE, row_major, ALIGNMENT> & A,\n              viennacl::matrix<SCALARTYPE, row_major, ALIGNMENT> & QL,\n              viennacl::matrix<SCALARTYPE, row_major, ALIGNMENT> & QR)\n    {\n      viennacl::ocl::context & ctx = const_cast<viennacl::ocl::context &>(viennacl::traits::opencl_handle(A).context());\n      viennacl::linalg::opencl::kernels::svd<SCALARTYPE>::init(ctx);\n\n      vcl_size_t row_num = A.size1();\n      vcl_size_t col_num = A.size2();\n\n      vcl_size_t to = std::min(row_num, col_num);\n\n\n      //viennacl::vector<SCALARTYPE, ALIGNMENT> d(to);\n      //viennacl::vector<SCALARTYPE, ALIGNMENT> s(to + 1);\n\n      // first stage\n      detail::bidiag(A, QL, QR);\n\n      // second stage\n      //std::vector<SCALARTYPE> dh(to, 0);\n      //std::vector<SCALARTYPE> sh(to + 1, 0);\n      boost::numeric::ublas::vector<SCALARTYPE> dh = boost::numeric::ublas::scalar_vector<SCALARTYPE>(to, 0);\n      boost::numeric::ublas::vector<SCALARTYPE> sh = boost::numeric::ublas::scalar_vector<SCALARTYPE>(to + 1, 0);\n\n\n      viennacl::linalg::opencl::bidiag_pack_svd(A, dh, sh);\n\n      detail::svd_qr_shift( QL, QR, dh, sh);\n\n      // Write resulting diagonal matrix with singular values to A:\n      boost::numeric::ublas::matrix<SCALARTYPE> h_Sigma(row_num, col_num);\n      h_Sigma.clear();\n\n      for (vcl_size_t i = 0; i < to; i++)\n        h_Sigma(i, i) = dh[i];\n\n      copy(h_Sigma, A);\n    }\n  }\n}\n#endif\n", "meta": {"hexsha": "28595b5a60c1f2b93089b3d82891c9574f7b67f9", "size": 20114, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "viennacl/linalg/svd.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/svd.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/svd.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": 37.6666666667, "max_line_length": 164, "alphanum_fraction": 0.4795664711, "num_tokens": 4854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.27751764800417367}}
{"text": "/*********************************************************************\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2008, Willow Garage, 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\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 Willow Garage 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: Ioan Sucan */\n\n#include \"geometric_shapes/bodies.h\"\n#include \"geometric_shapes/body_operations.h\"\n#include \"geometric_shapes/check_isometry.h\"\n\n#include <console_bridge/console.h>\n\nextern \"C\" {\n#ifdef GEOMETRIC_SHAPES_HAVE_QHULL_2011\n#include <libqhull/libqhull.h>\n#include <libqhull/mem.h>\n#include <libqhull/qset.h>\n#include <libqhull/geom.h>\n#include <libqhull/merge.h>\n#include <libqhull/poly.h>\n#include <libqhull/io.h>\n#include <libqhull/stat.h>\n#else\n#include <qhull/qhull.h>\n#include <qhull/mem.h>\n#include <qhull/qset.h>\n#include <qhull/geom.h>\n#include <qhull/merge.h>\n#include <qhull/poly.h>\n#include <qhull/io.h>\n#include <qhull/stat.h>\n#endif\n}\n\n#include <boost/math/constants/constants.hpp>\n#include <limits>\n#include <cstdio>\n#include <cmath>  // std::fmin, std::fmax\n#include <algorithm>\n#include <Eigen/Geometry>\n#include <unordered_map>\n#include <mutex>\n\nnamespace bodies\n{\nnamespace detail\n{\nstatic const double ZERO = 1e-9;\n\n/** \\brief Compute the square of the distance between a ray and a point\n    Note: this requires 'dir' to be normalized */\nstatic inline double distanceSQR(const Eigen::Vector3d& p, const Eigen::Vector3d& origin, const Eigen::Vector3d& dir)\n{\n  Eigen::Vector3d a = p - origin;\n  double d = dir.normalized().dot(a);\n  return a.squaredNorm() - d * d;\n}\n\n// temp structure for intersection points (used for ordering them)\nstruct intersc\n{\n  intersc(const Eigen::Vector3d& _pt, const double _tm) : pt(_pt), time(_tm)\n  {\n  }\n\n  Eigen::Vector3d pt;\n  double time;\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\n// define order on intersection points\nstruct interscOrder\n{\n  bool operator()(const intersc& a, const intersc& b) const\n  {\n    return a.time < b.time;\n  }\n};\n\n/**\n * \\brief Take intersections points in ipts and add them to intersections, filtering duplicates.\n * \\param ipts The source list of intersections (will be modified (sorted)).\n * \\param intersections The output list of intersection points.\n * \\param count The maximum count of returned intersection points. 0 = return all points.\n */\nvoid filterIntersections(std::vector<detail::intersc>& ipts, EigenSTL::vector_Vector3d* intersections,\n                         const size_t count)\n{\n  if (intersections == nullptr || ipts.empty())\n    return;\n\n  std::sort(ipts.begin(), ipts.end(), interscOrder());\n  const auto n = count > 0 ? std::min<size_t>(count, ipts.size()) : ipts.size();\n\n  for (const auto& p : ipts)\n  {\n    if (intersections->size() == n)\n      break;\n    if (!intersections->empty() && p.pt.isApprox(intersections->back(), ZERO))\n      continue;\n    intersections->push_back(p.pt);\n  }\n}\n\n// HACK: The global map g_triangle_for_plane_ is needed for ABI compatibility with the melodic version of\n// geometric_shapes; in newer releases, it should instead be added as a member to ConvexMesh::MeshData.\nstd::unordered_map<const ConvexMesh*, std::map<size_t, size_t>> g_triangle_for_plane_;\nstd::mutex g_triangle_for_plane_mutex;  //!< Lock this mutex every time you work with g_triangle_for_plane_.\nstatic std::map<size_t, size_t>& getTriangleForPlane(const ConvexMesh* mesh)\n{\n  std::lock_guard<std::mutex> lock(g_triangle_for_plane_mutex);\n  auto it = g_triangle_for_plane_.find(mesh);\n  if (it == detail::g_triangle_for_plane_.end())\n    return detail::g_triangle_for_plane_.emplace(mesh, std::map<size_t, size_t>()).first->second;\n  else\n    return it->second;\n}\n}  // namespace detail\n\ninline Eigen::Vector3d normalize(const Eigen::Vector3d& dir)\n{\n  const double norm = dir.squaredNorm();\n#if EIGEN_VERSION_AT_LEAST(3, 3, 0)\n  return ((norm - 1) > 1e-9) ? (dir / Eigen::numext::sqrt(norm)) : dir;\n#else  // used in kinetic\n  return ((norm - 1) > 1e-9) ? (dir / sqrt(norm)) : dir;\n#endif\n}\n}  // namespace bodies\n\nvoid bodies::Body::setDimensions(const shapes::Shape* shape)\n{\n  setDimensionsDirty(shape);\n  updateInternalData();\n}\n\nbool bodies::Body::samplePointInside(random_numbers::RandomNumberGenerator& rng, unsigned int max_attempts,\n                                     Eigen::Vector3d& result) const\n{\n  BoundingSphere bs;\n  computeBoundingSphere(bs);\n  for (unsigned int i = 0; i < max_attempts; ++i)\n  {\n    result = Eigen::Vector3d(rng.uniformReal(bs.center.x() - bs.radius, bs.center.x() + bs.radius),\n                             rng.uniformReal(bs.center.y() - bs.radius, bs.center.y() + bs.radius),\n                             rng.uniformReal(bs.center.z() - bs.radius, bs.center.z() + bs.radius));\n    if (containsPoint(result))\n      return true;\n  }\n  return false;\n}\n\nbool bodies::Sphere::containsPoint(const Eigen::Vector3d& p, bool /* verbose */) const\n{\n  return (center_ - p).squaredNorm() <= radius2_;\n}\n\nvoid bodies::Sphere::useDimensions(const shapes::Shape* shape)  // radius\n{\n  radius_ = static_cast<const shapes::Sphere*>(shape)->radius;\n}\n\nstd::vector<double> bodies::Sphere::getDimensions() const\n{\n  std::vector<double> d(1, radius_);\n  return d;\n}\n\nvoid bodies::Sphere::updateInternalData()\n{\n  const auto tmpRadiusU = radius_ * scale_ + padding_;\n  if (tmpRadiusU < 0)\n    throw std::runtime_error(\"Sphere radius must be non-negative.\");\n  radiusU_ = tmpRadiusU;\n  radius2_ = radiusU_ * radiusU_;\n  center_ = pose_.translation();\n}\n\nstd::shared_ptr<bodies::Body> bodies::Sphere::cloneAt(const Eigen::Isometry3d& pose, double padding, double scale) const\n{\n  auto s = std::allocate_shared<Sphere>(Eigen::aligned_allocator<Sphere>());\n  s->radius_ = radius_;\n  s->padding_ = padding;\n  s->scale_ = scale;\n  s->pose_ = pose;\n  s->updateInternalData();\n  return s;\n}\n\ndouble bodies::Sphere::computeVolume() const\n{\n  return 4.0 * boost::math::constants::pi<double>() * radiusU_ * radiusU_ * radiusU_ / 3.0;\n}\n\nvoid bodies::Sphere::computeBoundingSphere(BoundingSphere& sphere) const\n{\n  sphere.center = center_;\n  sphere.radius = radiusU_;\n}\n\nvoid bodies::Sphere::computeBoundingCylinder(BoundingCylinder& cylinder) const\n{\n  cylinder.pose = pose_;\n  cylinder.radius = radiusU_;\n  cylinder.length = 2.0 * radiusU_;\n}\n\nvoid bodies::Sphere::computeBoundingBox(bodies::AABB& bbox) const\n{\n  bbox.setEmpty();\n\n  // it's a sphere, so we do not rotate the bounding box\n  Eigen::Isometry3d transform = Eigen::Isometry3d::Identity();\n  transform.translation() = getPose().translation();\n\n  bbox.extendWithTransformedBox(transform, Eigen::Vector3d(2 * radiusU_, 2 * radiusU_, 2 * radiusU_));\n}\n\nbool bodies::Sphere::samplePointInside(random_numbers::RandomNumberGenerator& rng, unsigned int max_attempts,\n                                       Eigen::Vector3d& result) const\n{\n  for (unsigned int i = 0; i < max_attempts; ++i)\n  {\n    const double minX = center_.x() - radiusU_;\n    const double maxX = center_.x() + radiusU_;\n    const double minY = center_.y() - radiusU_;\n    const double maxY = center_.y() + radiusU_;\n    const double minZ = center_.z() - radiusU_;\n    const double maxZ = center_.z() + radiusU_;\n    // we are sampling in a box; the probability of success after 20 attempts is 99.99996% given the ratio of box volume\n    // to sphere volume\n    for (int j = 0; j < 20; ++j)\n    {\n      result = Eigen::Vector3d(rng.uniformReal(minX, maxX), rng.uniformReal(minY, maxY), rng.uniformReal(minZ, maxZ));\n      if (containsPoint(result))\n        return true;\n    }\n  }\n  return false;\n}\n\nbool bodies::Sphere::intersectsRay(const Eigen::Vector3d& origin, const Eigen::Vector3d& dir,\n                                   EigenSTL::vector_Vector3d* intersections, unsigned int count) const\n{\n  // this is faster than always calling dir.normalized() in case the vector is already unit\n  const Eigen::Vector3d dirNorm = normalize(dir);\n\n  if (detail::distanceSQR(center_, origin, dirNorm) > radius2_)\n    return false;\n\n  bool result = false;\n\n  Eigen::Vector3d cp = origin - center_;\n  double dpcpv = cp.dot(dirNorm);\n\n  Eigen::Vector3d w = cp - dpcpv * dirNorm;\n  Eigen::Vector3d Q = center_ + w;\n  double x = radius2_ - w.squaredNorm();\n\n  if (fabs(x) < detail::ZERO)\n  {\n    w = Q - origin;\n    double dpQv = w.dot(dirNorm);\n    if (dpQv > detail::ZERO)\n    {\n      if (intersections)\n        intersections->push_back(Q);\n      result = true;\n    }\n  }\n  else if (x > 0.0)\n  {\n    x = sqrt(x);\n    w = dirNorm * x;\n    Eigen::Vector3d A = Q - w;\n    Eigen::Vector3d B = Q + w;\n    w = A - origin;\n    double dpAv = w.dot(dirNorm);\n    w = B - origin;\n    double dpBv = w.dot(dirNorm);\n\n    if (dpAv > detail::ZERO)\n    {\n      result = true;\n      if (intersections)\n      {\n        intersections->push_back(A);\n        if (count == 1)\n          return result;\n      }\n    }\n\n    if (dpBv > detail::ZERO)\n    {\n      result = true;\n      if (intersections)\n        intersections->push_back(B);\n    }\n  }\n  return result;\n}\n\nbool bodies::Cylinder::containsPoint(const Eigen::Vector3d& p, bool /* verbose */) const\n{\n  Eigen::Vector3d v = p - center_;\n  double pH = v.dot(normalH_);\n\n  if (fabs(pH) > length2_)\n    return false;\n\n  double pB1 = v.dot(normalB1_);\n  double remaining = radius2_ - pB1 * pB1;\n\n  if (remaining < 0.0)\n    return false;\n  else\n  {\n    double pB2 = v.dot(normalB2_);\n    return pB2 * pB2 <= remaining;\n  }\n}\n\nvoid bodies::Cylinder::useDimensions(const shapes::Shape* shape)  // (length, radius)\n{\n  length_ = static_cast<const shapes::Cylinder*>(shape)->length;\n  radius_ = static_cast<const shapes::Cylinder*>(shape)->radius;\n}\n\nstd::vector<double> bodies::Cylinder::getDimensions() const\n{\n  std::vector<double> d(2);\n  d[0] = radius_;\n  d[1] = length_;\n  return d;\n}\n\nvoid bodies::Cylinder::updateInternalData()\n{\n  const auto tmpRadiusU = radius_ * scale_ + padding_;\n  if (tmpRadiusU < 0)\n    throw std::runtime_error(\"Cylinder radius must be non-negative.\");\n  const auto tmpLength2 = scale_ * length_ / 2.0 + padding_;\n  if (tmpLength2 < 0)\n    throw std::runtime_error(\"Cylinder length must be non-negative.\");\n  radiusU_ = tmpRadiusU;\n  length2_ = tmpLength2;\n  radius2_ = radiusU_ * radiusU_;\n  center_ = pose_.translation();\n  radiusBSqr_ = length2_ * length2_ + radius2_;\n  radiusB_ = sqrt(radiusBSqr_);\n\n  ASSERT_ISOMETRY(pose_);\n  Eigen::Matrix3d basis = pose_.linear();\n  normalB1_ = basis.col(0);\n  normalB2_ = basis.col(1);\n  normalH_ = basis.col(2);\n\n  double tmp = -normalH_.dot(center_);\n  d1_ = tmp + length2_;\n  d2_ = tmp - length2_;\n}\n\nbool bodies::Cylinder::samplePointInside(random_numbers::RandomNumberGenerator& rng, unsigned int /* max_attempts */,\n                                         Eigen::Vector3d& result) const\n{\n  // sample a point on the base disc of the cylinder\n  double a = rng.uniformReal(-boost::math::constants::pi<double>(), boost::math::constants::pi<double>());\n  double r = rng.uniformReal(-radiusU_, radiusU_);\n  double x = cos(a) * r;\n  double y = sin(a) * r;\n\n  // sample e height\n  double z = rng.uniformReal(-length2_, length2_);\n\n  result = pose_ * Eigen::Vector3d(x, y, z);\n  return true;\n}\n\nstd::shared_ptr<bodies::Body> bodies::Cylinder::cloneAt(const Eigen::Isometry3d& pose, double padding,\n                                                        double scale) const\n{\n  auto c = std::allocate_shared<Cylinder>(Eigen::aligned_allocator<Cylinder>());\n  c->length_ = length_;\n  c->radius_ = radius_;\n  c->padding_ = padding;\n  c->scale_ = scale;\n  c->pose_ = pose;\n  c->updateInternalData();\n  return c;\n}\n\ndouble bodies::Cylinder::computeVolume() const\n{\n  return 2.0 * boost::math::constants::pi<double>() * radius2_ * length2_;\n}\n\nvoid bodies::Cylinder::computeBoundingSphere(BoundingSphere& sphere) const\n{\n  sphere.center = center_;\n  sphere.radius = radiusB_;\n}\n\nvoid bodies::Cylinder::computeBoundingCylinder(BoundingCylinder& cylinder) const\n{\n  cylinder.pose = pose_;\n  cylinder.radius = radiusU_;\n  cylinder.length = 2 * length2_;\n}\n\nvoid bodies::Cylinder::computeBoundingBox(bodies::AABB& bbox) const\n{\n  bbox.setEmpty();\n\n  // method taken from http://www.iquilezles.org/www/articles/diskbbox/diskbbox.htm\n\n  const auto a = normalH_;\n  const auto e = radiusU_ * (Eigen::Vector3d::Ones() - a.cwiseProduct(a) / a.dot(a)).cwiseSqrt();\n  const auto pa = center_ + length2_ * normalH_;\n  const auto pb = center_ - length2_ * normalH_;\n\n  bbox.extend(pa - e);\n  bbox.extend(pa + e);\n  bbox.extend(pb - e);\n  bbox.extend(pb + e);\n}\n\nbool bodies::Cylinder::intersectsRay(const Eigen::Vector3d& origin, const Eigen::Vector3d& dir,\n                                     EigenSTL::vector_Vector3d* intersections, unsigned int count) const\n{\n  // this is faster than always calling dir.normalized() in case the vector is already unit\n  const Eigen::Vector3d dirNorm = normalize(dir);\n\n  if (detail::distanceSQR(center_, origin, dirNorm) > radiusBSqr_)\n    return false;\n\n  std::vector<detail::intersc> ipts;\n\n  // intersect bases\n  double tmp = normalH_.dot(dirNorm);\n  if (fabs(tmp) > detail::ZERO)\n  {\n    double tmp2 = -normalH_.dot(origin);\n    double t1 = (tmp2 - d1_) / tmp;\n\n    if (t1 > 0.0)\n    {\n      Eigen::Vector3d p1(origin + dirNorm * t1);\n      Eigen::Vector3d v1(p1 - center_);\n      v1 = v1 - normalH_.dot(v1) * normalH_;\n      if (v1.squaredNorm() < radius2_ + detail::ZERO)\n      {\n        if (intersections == nullptr)\n          return true;\n\n        detail::intersc ip(p1, t1);\n        ipts.push_back(ip);\n      }\n    }\n\n    double t2 = (tmp2 - d2_) / tmp;\n    if (t2 > 0.0)\n    {\n      Eigen::Vector3d p2(origin + dirNorm * t2);\n      Eigen::Vector3d v2(p2 - center_);\n      v2 = v2 - normalH_.dot(v2) * normalH_;\n      if (v2.squaredNorm() < radius2_ + detail::ZERO)\n      {\n        if (intersections == nullptr)\n          return true;\n\n        detail::intersc ip(p2, t2);\n        ipts.push_back(ip);\n      }\n    }\n  }\n\n  if (ipts.size() < 2)\n  {\n    // intersect with infinite cylinder\n    Eigen::Vector3d VD(normalH_.cross(dirNorm));\n    Eigen::Vector3d ROD(normalH_.cross(origin - center_));\n    double a = VD.squaredNorm();\n    double b = 2.0 * ROD.dot(VD);\n    double c = ROD.squaredNorm() - radius2_;\n    double d = b * b - 4.0 * a * c;\n    if (d >= 0.0 && fabs(a) > detail::ZERO)\n    {\n      d = sqrt(d);\n      double e = -a * 2.0;\n      double t1 = (b + d) / e;\n      double t2 = (b - d) / e;\n\n      if (t1 > 0.0)\n      {\n        Eigen::Vector3d p1(origin + dirNorm * t1);\n        Eigen::Vector3d v1(center_ - p1);\n\n        if (fabs(normalH_.dot(v1)) < length2_ + detail::ZERO)\n        {\n          if (intersections == nullptr)\n            return true;\n\n          detail::intersc ip(p1, t1);\n          ipts.push_back(ip);\n        }\n      }\n\n      if (t2 > 0.0)\n      {\n        Eigen::Vector3d p2(origin + dirNorm * t2);\n        Eigen::Vector3d v2(center_ - p2);\n\n        if (fabs(normalH_.dot(v2)) < length2_ + detail::ZERO)\n        {\n          if (intersections == nullptr)\n            return true;\n          detail::intersc ip(p2, t2);\n          ipts.push_back(ip);\n        }\n      }\n    }\n  }\n\n  if (ipts.empty())\n    return false;\n\n  // If a ray hits exactly the boundary between a side and a base, it is reported twice.\n  // We want to only return the intersection once, thus we need to filter them.\n  detail::filterIntersections(ipts, intersections, count);\n  return true;\n}\n\nbool bodies::Box::samplePointInside(random_numbers::RandomNumberGenerator& rng, unsigned int /* max_attempts */,\n                                    Eigen::Vector3d& result) const\n{\n  result = pose_ * Eigen::Vector3d(rng.uniformReal(-length2_, length2_), rng.uniformReal(-width2_, width2_),\n                                   rng.uniformReal(-height2_, height2_));\n  return true;\n}\n\nbool bodies::Box::containsPoint(const Eigen::Vector3d& p, bool /* verbose */) const\n{\n  const Eigen::Vector3d aligned = (pose_.linear().transpose() * (p - center_)).cwiseAbs();\n  return aligned[0] <= length2_ && aligned[1] <= width2_ && aligned[2] <= height2_;\n}\n\nvoid bodies::Box::useDimensions(const shapes::Shape* shape)  // (x, y, z) = (length, width, height)\n{\n  const double* size = static_cast<const shapes::Box*>(shape)->size;\n  length_ = size[0];\n  width_ = size[1];\n  height_ = size[2];\n}\n\nstd::vector<double> bodies::Box::getDimensions() const\n{\n  std::vector<double> d(3);\n  d[0] = length_;\n  d[1] = width_;\n  d[2] = height_;\n  return d;\n}\n\nvoid bodies::Box::updateInternalData()\n{\n  double s2 = scale_ / 2.0;\n  const auto tmpLength2 = length_ * s2 + padding_;\n  const auto tmpWidth2 = width_ * s2 + padding_;\n  const auto tmpHeight2 = height_ * s2 + padding_;\n\n  if (tmpLength2 < 0 || tmpWidth2 < 0 || tmpHeight2 < 0)\n    throw std::runtime_error(\"Box dimensions must be non-negative.\");\n\n  length2_ = tmpLength2;\n  width2_ = tmpWidth2;\n  height2_ = tmpHeight2;\n\n  center_ = pose_.translation();\n\n  radius2_ = length2_ * length2_ + width2_ * width2_ + height2_ * height2_;\n  radiusB_ = sqrt(radius2_);\n\n  ASSERT_ISOMETRY(pose_);\n  Eigen::Matrix3d basis = pose_.linear();\n  normalL_ = basis.col(0);\n  normalW_ = basis.col(1);\n  normalH_ = basis.col(2);\n\n  // rotation is intentionally not applied, the corners are used in intersectsRay()\n  const Eigen::Vector3d tmp(length2_, width2_, height2_);\n  corner1_ = center_ - tmp;\n  corner2_ = center_ + tmp;\n}\n\nstd::shared_ptr<bodies::Body> bodies::Box::cloneAt(const Eigen::Isometry3d& pose, double padding, double scale) const\n{\n  auto b = std::allocate_shared<Box>(Eigen::aligned_allocator<Box>());\n  b->length_ = length_;\n  b->width_ = width_;\n  b->height_ = height_;\n  b->padding_ = padding;\n  b->scale_ = scale;\n  b->pose_ = pose;\n  b->updateInternalData();\n  return b;\n}\n\ndouble bodies::Box::computeVolume() const\n{\n  return 8.0 * length2_ * width2_ * height2_;\n}\n\nvoid bodies::Box::computeBoundingSphere(BoundingSphere& sphere) const\n{\n  sphere.center = center_;\n  sphere.radius = radiusB_;\n}\n\nvoid bodies::Box::computeBoundingCylinder(BoundingCylinder& cylinder) const\n{\n  double a, b;\n\n  if (length2_ > width2_ && length2_ > height2_)\n  {\n    cylinder.length = length2_ * 2.0;\n    a = width2_;\n    b = height2_;\n    Eigen::Isometry3d rot(Eigen::AngleAxisd(90.0f * (M_PI / 180.0f), Eigen::Vector3d::UnitY()));\n    cylinder.pose = pose_ * rot;\n  }\n  else if (width2_ > height2_)\n  {\n    cylinder.length = width2_ * 2.0;\n    a = height2_;\n    b = length2_;\n    cylinder.radius = sqrt(height2_ * height2_ + length2_ * length2_);\n    Eigen::Isometry3d rot(Eigen::AngleAxisd(90.0f * (M_PI / 180.0f), Eigen::Vector3d::UnitX()));\n    cylinder.pose = pose_ * rot;\n  }\n  else\n  {\n    cylinder.length = height2_ * 2.0;\n    a = width2_;\n    b = length2_;\n    cylinder.pose = pose_;\n  }\n  cylinder.radius = sqrt(a * a + b * b);\n}\n\nvoid bodies::Box::computeBoundingBox(bodies::AABB& bbox) const\n{\n  bbox.setEmpty();\n\n  bbox.extendWithTransformedBox(getPose(), 2 * Eigen::Vector3d(length2_, width2_, height2_));\n}\n\nbool bodies::Box::intersectsRay(const Eigen::Vector3d& origin, const Eigen::Vector3d& dir,\n                                EigenSTL::vector_Vector3d* intersections, unsigned int count) const\n{\n  // this is faster than always calling dir.normalized() in case the vector is already unit\n  const Eigen::Vector3d dirNorm = normalize(dir);\n\n  // Brian Smits. Efficient bounding box intersection. Ray tracing news 15(1), 2002\n\n  // The implemented method only works for axis-aligned boxes. So we treat ours as such, cancel its rotation, and\n  // rotate the origin and dir instead. corner1_ and corner2_ are corners with canceled rotation.\n  const Eigen::Matrix3d invRot = pose_.linear().transpose();\n  const Eigen::Vector3d o(invRot * (origin - center_) + center_);\n  const Eigen::Vector3d d(invRot * dirNorm);\n\n  Eigen::Vector3d tmpTmin, tmpTmax;\n  tmpTmin = (corner1_ - o).cwiseQuotient(d);\n  tmpTmax = (corner2_ - o).cwiseQuotient(d);\n\n  // In projection to each axis, if the ray has positive direction, it goes from min corner (corner1_) to max corner\n  // (corner2_). If its direction is negative, the first intersection is at max corner and then at min corner.\n  for (size_t i = 0; i < 3; ++i)\n  {\n    if (d[i] < 0)\n      std::swap(tmpTmin[i], tmpTmax[i]);\n  }\n\n  // tmin and tmax are such values of t in \"p = o + t * d\" in which the line intersects the box faces.\n  // The box is viewed projected from all three directions, values of t are computed for each of the projections,\n  // and a final constraint on tmin and tmax is updated by each of these projections. If tmin > tmax, there is no\n  // intersection between the line and the box.\n\n  double tmin, tmax;\n  // use fmax/fmin to handle NaNs which can sneak in when dividing by d in tmpTmin and tmpTmax\n  tmin = std::fmax(tmpTmin.x(), std::fmax(tmpTmin.y(), tmpTmin.z()));\n  tmax = std::fmin(tmpTmax.x(), std::fmin(tmpTmax.y(), tmpTmax.z()));\n\n  // tmin > tmax, there is no intersection between the line and the box\n  if (tmax - tmin < -detail::ZERO)\n    return false;\n\n  // As we're doing intersections with a ray and not a line, cases where tmax is negative mean that the intersection is\n  // with the opposite ray and not the one we are working with.\n  if (tmax < 0)\n    return false;\n\n  if (intersections)\n  {\n    if (tmax - tmin > detail::ZERO)\n    {\n      // tmax > tmin, we have two distinct intersection points\n      if (tmin > detail::ZERO)\n      {\n        // tmin > 0, both intersections lie on the ray\n        intersections->push_back(tmin * dirNorm + origin);\n        if (count == 0 || count > 1)\n          intersections->push_back(tmax * dirNorm + origin);\n      }\n      else\n      {\n        // tmin <= 0 && tmax >= 0, the first intersection point is on the opposite ray and the second one on the correct\n        // ray - this means origin of the ray lies inside the box and we should only report one intersection.\n        intersections->push_back(tmax * dirNorm + origin);\n      }\n    }\n    else\n    {\n      // tmax == tmin, there is exactly one intersection at a corner or edge\n      intersections->push_back(tmax * dirNorm + origin);\n    }\n  }\n\n  return true;\n}\n\nbool bodies::ConvexMesh::containsPoint(const Eigen::Vector3d& p, bool /* verbose */) const\n{\n  if (!mesh_data_)\n    return false;\n  if (bounding_box_.containsPoint(p))\n  {\n    // Transform the point to the \"base space\" of this mesh\n    Eigen::Vector3d ip(i_pose_ * p);\n    return isPointInsidePlanes(ip);\n  }\n  else\n    return false;\n}\n\nvoid bodies::ConvexMesh::correctVertexOrderFromPlanes()\n{\n  for (unsigned int i = 0; i < mesh_data_->triangles_.size(); i += 3)\n  {\n    Eigen::Vector3d d1 =\n        mesh_data_->vertices_[mesh_data_->triangles_[i]] - mesh_data_->vertices_[mesh_data_->triangles_[i + 1]];\n    Eigen::Vector3d d2 =\n        mesh_data_->vertices_[mesh_data_->triangles_[i]] - mesh_data_->vertices_[mesh_data_->triangles_[i + 2]];\n    // expected computed normal from triangle vertex order\n    Eigen::Vector3d tri_normal = d1.cross(d2);\n    tri_normal.normalize();\n    // actual plane normal\n    Eigen::Vector3d normal(mesh_data_->planes_[mesh_data_->plane_for_triangle_[i / 3]].x(),\n                           mesh_data_->planes_[mesh_data_->plane_for_triangle_[i / 3]].y(),\n                           mesh_data_->planes_[mesh_data_->plane_for_triangle_[i / 3]].z());\n    bool same_dir = tri_normal.dot(normal) > 0;\n    if (!same_dir)\n    {\n      std::swap(mesh_data_->triangles_[i], mesh_data_->triangles_[i + 1]);\n    }\n  }\n}\n\nvoid bodies::ConvexMesh::useDimensions(const shapes::Shape* shape)\n{\n  mesh_data_ = std::allocate_shared<MeshData>(Eigen::aligned_allocator<MeshData>());\n  const shapes::Mesh* mesh = static_cast<const shapes::Mesh*>(shape);\n\n  double maxX = -std::numeric_limits<double>::infinity(), maxY = -std::numeric_limits<double>::infinity(),\n         maxZ = -std::numeric_limits<double>::infinity();\n  double minX = std::numeric_limits<double>::infinity(), minY = std::numeric_limits<double>::infinity(),\n         minZ = std::numeric_limits<double>::infinity();\n\n  for (unsigned int i = 0; i < mesh->vertex_count; ++i)\n  {\n    double vx = mesh->vertices[3 * i];\n    double vy = mesh->vertices[3 * i + 1];\n    double vz = mesh->vertices[3 * i + 2];\n\n    if (maxX < vx)\n      maxX = vx;\n    if (maxY < vy)\n      maxY = vy;\n    if (maxZ < vz)\n      maxZ = vz;\n\n    if (minX > vx)\n      minX = vx;\n    if (minY > vy)\n      minY = vy;\n    if (minZ > vz)\n      minZ = vz;\n  }\n\n  if (maxX < minX)\n    maxX = minX = 0.0;\n  if (maxY < minY)\n    maxY = minY = 0.0;\n  if (maxZ < minZ)\n    maxZ = minZ = 0.0;\n\n  mesh_data_->box_size_ = Eigen::Vector3d(maxX - minX, maxY - minY, maxZ - minZ);\n\n  mesh_data_->box_offset_ = Eigen::Vector3d((minX + maxX) / 2.0, (minY + maxY) / 2.0, (minZ + maxZ) / 2.0);\n\n  mesh_data_->planes_.clear();\n  mesh_data_->triangles_.clear();\n  mesh_data_->vertices_.clear();\n  mesh_data_->mesh_radiusB_ = 0.0;\n  mesh_data_->mesh_center_ = Eigen::Vector3d();\n\n  double xdim = maxX - minX;\n  double ydim = maxY - minY;\n  double zdim = maxZ - minZ;\n\n  double pose1;\n  double pose2;\n\n  unsigned int off1;\n  unsigned int off2;\n\n  /* compute bounding cylinder */\n  double cyl_length;\n  double maxdist = -std::numeric_limits<double>::infinity();\n  if (xdim > ydim && xdim > zdim)\n  {\n    off1 = 1;\n    off2 = 2;\n    pose1 = mesh_data_->box_offset_.y();\n    pose2 = mesh_data_->box_offset_.z();\n    cyl_length = xdim;\n  }\n  else if (ydim > zdim)\n  {\n    off1 = 0;\n    off2 = 2;\n    pose1 = mesh_data_->box_offset_.x();\n    pose2 = mesh_data_->box_offset_.z();\n    cyl_length = ydim;\n  }\n  else\n  {\n    off1 = 0;\n    off2 = 1;\n    pose1 = mesh_data_->box_offset_.x();\n    pose2 = mesh_data_->box_offset_.y();\n    cyl_length = zdim;\n  }\n\n  /* compute convex hull */\n  coordT* points = (coordT*)calloc(mesh->vertex_count * 3, sizeof(coordT));\n  for (unsigned int i = 0; i < mesh->vertex_count; ++i)\n  {\n    points[3 * i + 0] = (coordT)mesh->vertices[3 * i + 0];\n    points[3 * i + 1] = (coordT)mesh->vertices[3 * i + 1];\n    points[3 * i + 2] = (coordT)mesh->vertices[3 * i + 2];\n\n    double dista = mesh->vertices[3 * i + off1] - pose1;\n    double distb = mesh->vertices[3 * i + off2] - pose2;\n    double dist = sqrt(((dista * dista) + (distb * distb)));\n    if (dist > maxdist)\n      maxdist = dist;\n  }\n  mesh_data_->bounding_cylinder_.radius = maxdist;\n  mesh_data_->bounding_cylinder_.length = cyl_length;\n\n  static FILE* null = fopen(\"/dev/null\", \"w\");\n\n  char flags[] = \"qhull Tv Qt\";\n  int exitcode = qh_new_qhull(3, mesh->vertex_count, points, true, flags, null, null);\n\n  if (exitcode != 0)\n  {\n    CONSOLE_BRIDGE_logWarn(\"Convex hull creation failed\");\n    qh_freeqhull(!qh_ALL);\n    int curlong, totlong;\n    qh_memfreeshort(&curlong, &totlong);\n    return;\n  }\n\n  int num_facets = qh num_facets;\n\n  int num_vertices = qh num_vertices;\n  mesh_data_->vertices_.reserve(num_vertices);\n  Eigen::Vector3d sum(0, 0, 0);\n\n  // necessary for FORALLvertices\n  std::map<unsigned int, unsigned int> qhull_vertex_table;\n  vertexT* vertex;\n  FORALLvertices\n  {\n    Eigen::Vector3d vert(vertex->point[0], vertex->point[1], vertex->point[2]);\n    qhull_vertex_table[vertex->id] = mesh_data_->vertices_.size();\n    sum += vert;\n    mesh_data_->vertices_.push_back(vert);\n  }\n\n  mesh_data_->mesh_center_ = sum / (double)(num_vertices);\n  for (unsigned int j = 0; j < mesh_data_->vertices_.size(); ++j)\n  {\n    double dist = (mesh_data_->vertices_[j] - mesh_data_->mesh_center_).squaredNorm();\n    if (dist > mesh_data_->mesh_radiusB_)\n      mesh_data_->mesh_radiusB_ = dist;\n  }\n\n  mesh_data_->mesh_radiusB_ = sqrt(mesh_data_->mesh_radiusB_);\n  mesh_data_->triangles_.reserve(num_facets);\n\n  // HACK: only needed for ABI compatibility with melodic\n  std::map<size_t, size_t>& triangle_for_plane = detail::getTriangleForPlane(this);\n  triangle_for_plane.clear();\n\n  // neccessary for qhull macro\n  facetT* facet;\n  FORALLfacets\n  {\n    Eigen::Vector4d planeEquation(facet->normal[0], facet->normal[1], facet->normal[2], facet->offset);\n    if (!mesh_data_->planes_.empty())\n    {\n      // filter equal planes - assuming same ones follow each other\n      if ((planeEquation - mesh_data_->planes_.back()).cwiseAbs().maxCoeff() > 1e-6)  // max diff to last\n        mesh_data_->planes_.push_back(planeEquation);\n    }\n    else\n    {\n      mesh_data_->planes_.push_back(planeEquation);\n    }\n\n    // Needed by FOREACHvertex_i_\n    int vertex_n, vertex_i;\n    FOREACHvertex_i_((*facet).vertices)\n    {\n      mesh_data_->triangles_.push_back(qhull_vertex_table[vertex->id]);\n    }\n\n    mesh_data_->plane_for_triangle_[(mesh_data_->triangles_.size() - 1) / 3] = mesh_data_->planes_.size() - 1;\n    triangle_for_plane[mesh_data_->planes_.size() - 1] = (mesh_data_->triangles_.size() - 1) / 3;\n  }\n  qh_freeqhull(!qh_ALL);\n  int curlong, totlong;\n  qh_memfreeshort(&curlong, &totlong);\n}\n\nstd::vector<double> bodies::ConvexMesh::getDimensions() const\n{\n  return std::vector<double>();\n}\n\nvoid bodies::ConvexMesh::computeScaledVerticesFromPlaneProjections()\n{\n  // compute the scaled vertices, if needed\n  if (padding_ == 0.0 && scale_ == 1.0)\n  {\n    scaled_vertices_ = &mesh_data_->vertices_;\n    return;\n  }\n\n  if (!scaled_vertices_storage_)\n    scaled_vertices_storage_.reset(new EigenSTL::vector_Vector3d());\n  scaled_vertices_ = scaled_vertices_storage_.get();\n  scaled_vertices_storage_->resize(mesh_data_->vertices_.size());\n  // project vertices along the vertex - center line to the scaled and padded plane\n  // take the average of all tri's planes around that vertex as the result\n  // is not unique\n\n  // First figure out, which tris are connected to each vertex\n  std::map<unsigned int, std::vector<unsigned int>> vertex_to_tris;\n  for (unsigned int i = 0; i < mesh_data_->triangles_.size() / 3; ++i)\n  {\n    vertex_to_tris[mesh_data_->triangles_[3 * i + 0]].push_back(i);\n    vertex_to_tris[mesh_data_->triangles_[3 * i + 1]].push_back(i);\n    vertex_to_tris[mesh_data_->triangles_[3 * i + 2]].push_back(i);\n  }\n\n  for (unsigned int i = 0; i < mesh_data_->vertices_.size(); ++i)\n  {\n    Eigen::Vector3d v(mesh_data_->vertices_[i] - mesh_data_->mesh_center_);\n    EigenSTL::vector_Vector3d projected_vertices;\n    for (unsigned int t : vertex_to_tris[i])\n    {\n      const Eigen::Vector4d& plane = mesh_data_->planes_[mesh_data_->plane_for_triangle_[t]];\n      Eigen::Vector3d plane_normal(plane.x(), plane.y(), plane.z());\n      double d_scaled_padded =\n          scale_ * plane.w() - (1 - scale_) * mesh_data_->mesh_center_.dot(plane_normal) - padding_;\n\n      // intersect vert - center with scaled/padded plane equation\n      double denom = v.dot(plane_normal);\n      if (fabs(denom) < 1e-3)\n        continue;\n      double lambda = (-mesh_data_->mesh_center_.dot(plane_normal) - d_scaled_padded) / denom;\n      Eigen::Vector3d vert_on_plane = v * lambda + mesh_data_->mesh_center_;\n      projected_vertices.push_back(vert_on_plane);\n    }\n    if (projected_vertices.empty())\n    {\n      double l = v.norm();\n      scaled_vertices_storage_->at(i) =\n          mesh_data_->mesh_center_ + v * (scale_ + (l > detail::ZERO ? padding_ / l : 0.0));\n    }\n    else\n    {\n      Eigen::Vector3d sum(0, 0, 0);\n      for (const Eigen::Vector3d& vertex : projected_vertices)\n      {\n        sum += vertex;\n      }\n      sum /= projected_vertices.size();\n      scaled_vertices_storage_->at(i) = sum;\n    }\n  }\n}\n\nvoid bodies::ConvexMesh::updateInternalData()\n{\n  if (!mesh_data_)\n    return;\n  Eigen::Isometry3d pose = pose_;\n  pose.translation() = Eigen::Vector3d(pose_ * mesh_data_->box_offset_);\n\n  shapes::Box box_shape(mesh_data_->box_size_.x(), mesh_data_->box_size_.y(), mesh_data_->box_size_.z());\n  bounding_box_.setPoseDirty(pose);\n  // The real effect of padding will most likely be smaller due to the mesh padding algorithm, but in \"worst case\" it\n  // can inflate the primitive bounding box by the padding_ value.\n  bounding_box_.setPaddingDirty(padding_);\n  bounding_box_.setScaleDirty(scale_);\n  bounding_box_.setDimensionsDirty(&box_shape);\n  bounding_box_.updateInternalData();\n\n  i_pose_ = pose_.inverse();\n  center_ = pose_ * mesh_data_->mesh_center_;\n  radiusB_ = mesh_data_->mesh_radiusB_ * scale_ + padding_;\n  radiusBSqr_ = radiusB_ * radiusB_;\n\n  // compute the scaled vertices, if needed\n  if (padding_ == 0.0 && scale_ == 1.0)\n    scaled_vertices_ = &mesh_data_->vertices_;\n  else\n  {\n    if (!scaled_vertices_storage_)\n      scaled_vertices_storage_.reset(new EigenSTL::vector_Vector3d());\n    scaled_vertices_ = scaled_vertices_storage_.get();\n    scaled_vertices_storage_->resize(mesh_data_->vertices_.size());\n    for (unsigned int i = 0; i < mesh_data_->vertices_.size(); ++i)\n    {\n      Eigen::Vector3d v(mesh_data_->vertices_[i] - mesh_data_->mesh_center_);\n      double l = v.norm();\n      scaled_vertices_storage_->at(i) =\n          mesh_data_->mesh_center_ + v * (scale_ + (l > detail::ZERO ? padding_ / l : 0.0));\n    }\n  }\n}\nconst std::vector<unsigned int>& bodies::ConvexMesh::getTriangles() const\n{\n  static const std::vector<unsigned int> empty;\n  return mesh_data_ ? mesh_data_->triangles_ : empty;\n}\n\nconst EigenSTL::vector_Vector3d& bodies::ConvexMesh::getVertices() const\n{\n  static const EigenSTL::vector_Vector3d empty;\n  return mesh_data_ ? mesh_data_->vertices_ : empty;\n}\n\nconst EigenSTL::vector_Vector3d& bodies::ConvexMesh::getScaledVertices() const\n{\n  return scaled_vertices_ ? *scaled_vertices_ : getVertices();\n}\n\nconst EigenSTL::vector_Vector4d& bodies::ConvexMesh::getPlanes() const\n{\n  static const EigenSTL::vector_Vector4d empty;\n  return mesh_data_ ? mesh_data_->planes_ : empty;\n}\n\nstd::shared_ptr<bodies::Body> bodies::ConvexMesh::cloneAt(const Eigen::Isometry3d& pose, double padding,\n                                                          double scale) const\n{\n  auto m = std::allocate_shared<ConvexMesh>(Eigen::aligned_allocator<ConvexMesh>());\n  m->mesh_data_ = mesh_data_;\n  m->padding_ = padding;\n  m->scale_ = scale;\n  m->pose_ = pose;\n  m->updateInternalData();\n  return m;\n}\n\nvoid bodies::ConvexMesh::computeBoundingSphere(BoundingSphere& sphere) const\n{\n  sphere.center = center_;\n  sphere.radius = radiusB_;\n}\n\nvoid bodies::ConvexMesh::computeBoundingCylinder(BoundingCylinder& cylinder) const\n{\n  // the padding contibution might be smaller in reality, but we want to get it right for the worst case\n  cylinder.length = mesh_data_ ? mesh_data_->bounding_cylinder_.length * scale_ + 2 * padding_ : 0.0;\n  cylinder.radius = mesh_data_ ? mesh_data_->bounding_cylinder_.radius * scale_ + padding_ : 0.0;\n  // need to do rotation correctly to get pose, which bounding box does\n  BoundingCylinder cyl;\n  bounding_box_.computeBoundingCylinder(cyl);\n  cylinder.pose = cyl.pose;\n}\n\nvoid bodies::ConvexMesh::computeBoundingBox(bodies::AABB& bbox) const\n{\n  bbox.setEmpty();\n\n  bounding_box_.computeBoundingBox(bbox);\n}\n\nbool bodies::ConvexMesh::isPointInsidePlanes(const Eigen::Vector3d& point) const\n{\n  unsigned int numplanes = mesh_data_->planes_.size();\n  const std::map<size_t, size_t>& triangle_for_plane = detail::getTriangleForPlane(this);\n  for (unsigned int i = 0; i < numplanes; ++i)\n  {\n    const Eigen::Vector4d& plane = mesh_data_->planes_[i];\n    Eigen::Vector3d plane_vec(plane.x(), plane.y(), plane.z());\n    // w() needs to be recomputed from a scaled vertex as normally it refers to the unscaled plane\n    // we also cannot simply subtract padding_ from it, because padding of the points on the plane causes a different\n    // effect than adding padding along this plane's normal (padding effect is direction-dependent)\n    const auto scaled_point_on_plane = scaled_vertices_->at(mesh_data_->triangles_[3 * triangle_for_plane.at(i)]);\n    const double w_scaled_padded = -plane_vec.dot(scaled_point_on_plane);\n    const double dist = plane_vec.dot(point) + w_scaled_padded - detail::ZERO;\n    if (dist > 0.0)\n      return false;\n  }\n  return true;\n}\n\nunsigned int bodies::ConvexMesh::countVerticesBehindPlane(const Eigen::Vector4f& planeNormal) const\n{\n  unsigned int numvertices = mesh_data_->vertices_.size();\n  unsigned int result = 0;\n  for (unsigned int i = 0; i < numvertices; ++i)\n  {\n    Eigen::Vector3d plane_vec(planeNormal.x(), planeNormal.y(), planeNormal.z());\n    double dist = plane_vec.dot(mesh_data_->vertices_[i]) + planeNormal.w() - 1e-6;\n    if (dist > 0.0)\n      result++;\n  }\n  return result;\n}\n\ndouble bodies::ConvexMesh::computeVolume() const\n{\n  double volume = 0.0;\n  if (mesh_data_)\n    for (unsigned int i = 0; i < mesh_data_->triangles_.size() / 3; ++i)\n    {\n      const Eigen::Vector3d& v1 = mesh_data_->vertices_[mesh_data_->triangles_[3 * i + 0]];\n      const Eigen::Vector3d& v2 = mesh_data_->vertices_[mesh_data_->triangles_[3 * i + 1]];\n      const Eigen::Vector3d& v3 = mesh_data_->vertices_[mesh_data_->triangles_[3 * i + 2]];\n      volume += v1.x() * v2.y() * v3.z() + v2.x() * v3.y() * v1.z() + v3.x() * v1.y() * v2.z() -\n                v1.x() * v3.y() * v2.z() - v2.x() * v1.y() * v3.z() - v3.x() * v2.y() * v1.z();\n    }\n  return fabs(volume) / 6.0;\n}\n\nbool bodies::ConvexMesh::intersectsRay(const Eigen::Vector3d& origin, const Eigen::Vector3d& dir,\n                                       EigenSTL::vector_Vector3d* intersections, unsigned int count) const\n{\n  // this is faster than always calling dir.normalized() in case the vector is already unit\n  const Eigen::Vector3d dirNorm = normalize(dir);\n\n  if (!mesh_data_)\n    return false;\n  if (detail::distanceSQR(center_, origin, dirNorm) > radiusBSqr_)\n    return false;\n  if (!bounding_box_.intersectsRay(origin, dirNorm))\n    return false;\n\n  // transform the ray into the coordinate frame of the mesh\n  Eigen::Vector3d orig(i_pose_ * origin);\n  Eigen::Vector3d dr(i_pose_.linear() * dirNorm);\n\n  std::vector<detail::intersc> ipts;\n\n  bool result = false;\n\n  // for each triangle\n  const auto nt = mesh_data_->triangles_.size() / 3;\n  for (size_t i = 0; i < nt; ++i)\n  {\n    Eigen::Vector3d vec(mesh_data_->planes_[mesh_data_->plane_for_triangle_[i]].x(),\n                        mesh_data_->planes_[mesh_data_->plane_for_triangle_[i]].y(),\n                        mesh_data_->planes_[mesh_data_->plane_for_triangle_[i]].z());\n\n    const double tmp = vec.dot(dr);\n    if (fabs(tmp) > detail::ZERO)\n    {\n      // planes_[...].w() corresponds to the unscaled mesh, so we need to compute it ourselves\n      const double w_scaled_padded = vec.dot(scaled_vertices_->at(mesh_data_->triangles_[3 * i]));\n      const double t = -(vec.dot(orig) + w_scaled_padded) / tmp;\n      if (t > 0.0)\n      {\n        const auto i3 = 3 * i;\n        const auto v1 = mesh_data_->triangles_[i3 + 0];\n        const auto v2 = mesh_data_->triangles_[i3 + 1];\n        const auto v3 = mesh_data_->triangles_[i3 + 2];\n\n        const Eigen::Vector3d& a = scaled_vertices_->at(v1);\n        const Eigen::Vector3d& b = scaled_vertices_->at(v2);\n        const Eigen::Vector3d& c = scaled_vertices_->at(v3);\n\n        Eigen::Vector3d cb(c - b);\n        Eigen::Vector3d ab(a - b);\n\n        // intersection of the plane defined by the triangle and the ray\n        Eigen::Vector3d P(orig + dr * t);\n\n        // check if it is inside the triangle\n        Eigen::Vector3d pb(P - b);\n        Eigen::Vector3d c1(cb.cross(pb));\n        Eigen::Vector3d c2(cb.cross(ab));\n        if (c1.dot(c2) < 0.0)\n          continue;\n\n        Eigen::Vector3d ca(c - a);\n        Eigen::Vector3d pa(P - a);\n        Eigen::Vector3d ba(-ab);\n\n        c1 = ca.cross(pa);\n        c2 = ca.cross(ba);\n        if (c1.dot(c2) < 0.0)\n          continue;\n\n        c1 = ba.cross(pa);\n        c2 = ba.cross(ca);\n\n        if (c1.dot(c2) < 0.0)\n          continue;\n\n        result = true;\n        if (intersections)\n        {\n          detail::intersc ip(origin + dirNorm * t, t);\n          ipts.push_back(ip);\n        }\n        else\n          break;\n      }\n    }\n  }\n\n  if (result && intersections)\n  {\n    // If a ray hits exactly the boundary between two triangles, it is reported twice;\n    // We only want return the intersection once; thus we need to filter them.\n    detail::filterIntersections(ipts, intersections, count);\n  }\n\n  return result;\n}\n\nbodies::ConvexMesh::~ConvexMesh()\n{\n  // HACK: only needed for ABI compatibility with melodic\n  {\n    std::lock_guard<std::mutex> lock(detail::g_triangle_for_plane_mutex);\n    detail::g_triangle_for_plane_.erase(this);\n  }\n}\n\nbodies::BodyVector::BodyVector()\n{\n}\n\nbodies::BodyVector::BodyVector(const std::vector<shapes::Shape*>& shapes, const EigenSTL::vector_Isometry3d& poses,\n                               double padding)\n{\n  for (unsigned int i = 0; i < shapes.size(); i++)\n    addBody(shapes[i], poses[i], padding);\n}\n\nbodies::BodyVector::~BodyVector()\n{\n  clear();\n}\n\nvoid bodies::BodyVector::clear()\n{\n  for (auto& body : bodies_)\n    delete body;\n  bodies_.clear();\n}\n\nvoid bodies::BodyVector::addBody(Body* body)\n{\n  bodies_.push_back(body);\n  BoundingSphere sphere;\n  body->computeBoundingSphere(sphere);\n}\n\nvoid bodies::BodyVector::addBody(const shapes::Shape* shape, const Eigen::Isometry3d& pose, double padding)\n{\n  bodies::Body* body = bodies::createBodyFromShape(shape);\n  body->setPoseDirty(pose);\n  body->setPaddingDirty(padding);\n  body->updateInternalData();\n  addBody(body);\n}\n\nstd::size_t bodies::BodyVector::getCount() const\n{\n  return bodies_.size();\n}\n\nvoid bodies::BodyVector::setPose(unsigned int i, const Eigen::Isometry3d& pose)\n{\n  if (i >= bodies_.size())\n  {\n    CONSOLE_BRIDGE_logError(\"There is no body at index %u\", i);\n    return;\n  }\n\n  bodies_[i]->setPose(pose);\n}\n\nconst bodies::Body* bodies::BodyVector::getBody(unsigned int i) const\n{\n  if (i >= bodies_.size())\n  {\n    CONSOLE_BRIDGE_logError(\"There is no body at index %u\", i);\n    return nullptr;\n  }\n  else\n    return bodies_[i];\n}\n\nbool bodies::BodyVector::containsPoint(const Eigen::Vector3d& p, std::size_t& index, bool verbose) const\n{\n  for (std::size_t i = 0; i < bodies_.size(); ++i)\n    if (bodies_[i]->containsPoint(p, verbose))\n    {\n      index = i;\n      return true;\n    }\n  return false;\n}\n\nbool bodies::BodyVector::containsPoint(const Eigen::Vector3d& p, bool verbose) const\n{\n  std::size_t dummy;\n  return containsPoint(p, dummy, verbose);\n}\n\nbool bodies::BodyVector::intersectsRay(const Eigen::Vector3d& origin, const Eigen::Vector3d& dir, std::size_t& index,\n                                       EigenSTL::vector_Vector3d* intersections, unsigned int count) const\n{\n  for (std::size_t i = 0; i < bodies_.size(); ++i)\n    if (bodies_[i]->intersectsRay(origin, dir, intersections, count))\n    {\n      index = i;\n      return true;\n    }\n  return false;\n}\n", "meta": {"hexsha": "0f81bf9ce35b327225ff811f6b056ef39191db0b", "size": 44013, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geometric_shapes/src/bodies.cpp", "max_stars_repo_name": "NateWright/MoveItGrasps", "max_stars_repo_head_hexsha": "10330ff38c72075035a69ed754fa9ed40a7c846b", "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": "geometric_shapes/src/bodies.cpp", "max_issues_repo_name": "NateWright/MoveItGrasps", "max_issues_repo_head_hexsha": "10330ff38c72075035a69ed754fa9ed40a7c846b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geometric_shapes/src/bodies.cpp", "max_forks_repo_name": "NateWright/MoveItGrasps", "max_forks_repo_head_hexsha": "10330ff38c72075035a69ed754fa9ed40a7c846b", "max_forks_repo_licenses": ["BSD-3-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.5731707317, "max_line_length": 120, "alphanum_fraction": 0.657101311, "num_tokens": 12290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2774742166309714}}
{"text": "// Copyright 2020 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 <stdio.h>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/LU>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <assert.h>\n\n#include <vector>\n#define DCHECK_GT(a,b) assert((a)>(b))\n#define DCHECK_EQ(a,b) assert((a)==(b))\n\n#ifdef _WIN32\ntypedef __int64 qp_int64;\n#else\ntypedef long long qp_int64;\n#endif //_WIN32\n\n\nusing Eigen::AngleAxisd;\nusing Eigen::Map;\nusing Eigen::Matrix3d;\nusing Eigen::MatrixXd;\nusing Eigen::Quaterniond;\nusing Eigen::Vector3d;\nusing Eigen::VectorXd;\n#ifdef TDS_ENABLE_QPOASES\n#include \"qpOASES.hpp\"\n#include \"qpOASES/Types.hpp\"\n\nusing qpOASES::QProblem;\n\ntypedef Eigen::Matrix<qpOASES::real_t, Eigen::Dynamic, Eigen::Dynamic,\n                      Eigen::RowMajor>\n    RowMajorMatrixXd;\n\n\n\n#endif //TDS_ENABLE_QPOASES\n\nconstexpr int k3Dim = 3;\nconstexpr double kGravity = 9.8;\nconstexpr double kMaxScale = 10;\nconstexpr double kMinScale = 0.1;\n\n#include \"Eigen/Core\"\n#include \"Eigen/SparseCore\"\n#include \"osqp/include/ctrlc.h\"\n#include \"osqp/include/osqp.h\"\n\n\n\nenum QPSolverName\n{\n  OSQP, QPOASES\n};\n\n#ifdef TDS_ENABLE_QPOASES\n// Auxiliary function for copying data to qpOASES data structure.\nvoid CopyToVec(const Eigen::VectorXd& vec,\n               const std::vector<int> foot_contact_states, int num_legs,\n               int planning_horizon, int blk_size,\n               std::vector<qpOASES::real_t>* out) {\n  int buffer_index = 0;\n  for (int i = 0; i < num_legs * planning_horizon; ++i) {\n    int leg_id = (i % num_legs);\n    if (foot_contact_states[leg_id] == 0) {\n      // skip the block.\n      continue;\n    }\n    // otherwise copy this block.\n    assert(buffer_index < out->size());\n    for (int j = 0; j < blk_size; ++j) {\n      int index = i * blk_size + j;\n      (*out)[buffer_index] = vec[index];\n      ++buffer_index;\n    }\n  }\n}\n\n// Auxiliary function for copying data to qpOASES data structure.\nvoid CopyToMatrix(const Eigen::MatrixXd& input,\n                  const std::vector<int> foot_contact_states, int num_legs,\n                  int planning_horizon, int row_blk_size, int col_blk_size,\n                  bool is_block_diagonal, Eigen::Map<RowMajorMatrixXd>* out) {\n  // the block index in the destination matrix.\n  int row_blk = 0;\n  for (int i = 0; i < planning_horizon * num_legs; ++i) {\n    int leg_id = (i % num_legs);\n    if (foot_contact_states[leg_id] == 0) {\n      // skip the row block.\n      continue;\n    }\n    if (is_block_diagonal) {\n      // just copy the block\n      int col_blk = row_blk;\n      out->block(row_blk * row_blk_size, col_blk * col_blk_size, row_blk_size,\n                 col_blk_size) = input.block(i * row_blk_size, i * col_blk_size,\n                                             row_blk_size, col_blk_size);\n    } else {\n      int col_blk = 0;\n      // Non-diagonal, need to copy all elements.\n      for (int j = 0; j < planning_horizon * num_legs; ++j) {\n        int leg_id = (j % num_legs);\n        if (foot_contact_states[leg_id] == 0) {\n          // skip the col block.\n          continue;\n        }\n        out->block(row_blk * row_blk_size, col_blk * col_blk_size, row_blk_size,\n                   col_blk_size) =\n            input.block(i * row_blk_size, j * col_blk_size, row_blk_size,\n                        col_blk_size);\n        ++col_blk;\n      }\n    }\n    ++row_blk;\n  }\n}\n#endif //TDS_ENABLE_QPOASES\n\n// Converts the roll pitchh yaw angle vector to the corresponding rotation\n// matrix.\nEigen::Matrix3d ConvertRpyToRot(const Eigen::Vector3d& rpy);\n\n// Converts a vector to the skew symmetric matrix form. For an input vector\n// [a, b, c], the output matrix would be:\n//   [ 0, -c,  b]\n//   [ c,  0, -a]\n//   [-b,  a,  0]\nEigen::Matrix3d ConvertToSkewSymmetric(const Eigen::Vector3d& vec);\n\n// The CoM dynamics can be written as:\n//   X_dot = A X + B u\n// where X is the 13-dimensional state vector (r, p, y, x, y, z, r_dot, p_dot,\n// y_dot, vx, vy, vz, -g) constructed from the CoM roll/pitch/yaw/position, and\n// their first order derivatives. 'g' is the gravity constant. This API\n// constructs the A matrix in the formula. Check the MIT paper for details of\n// the formulation.\nvoid CalculateAMat(const Eigen::Vector3d& rpy, Eigen::MatrixXd* a_mat_ptr);\n\n// Constructs the B matrix in the linearized CoM dynamics equation. See the\n// documentation for 'CalculateAMat' for details of the symbol.\nvoid CalculateBMat(double inv_mass, const Eigen::Matrix3d& inv_inertia,\n    const Eigen::MatrixXd& foot_positions,\n    Eigen::MatrixXd* b_mat_ptr);\n\n// Calculates the discretized space-time dynamics. Given the dynamics equation:\n//   X_dot = A X + B u\n// and a timestep dt, we can estimate the snapshot of the state at t + dt by:\n//   X[t + dt] = exp([A, B]dt) [X, u] = A_exp X + B_exp u\nvoid CalculateExponentials(const Eigen::MatrixXd& a_mat,\n    const Eigen::MatrixXd& b_mat, double timestep,\n    Eigen::MatrixXd* ab_mat_ptr,\n    Eigen::MatrixXd* a_exp_ptr,\n    Eigen::MatrixXd* b_exp_ptr);\n\n// Calculates the dense QP formulation of the discretized space time dynamics.\n// Given:\n//   X_k+1 = A_exp X_k + B_exp u_k\n// We can unroll the dynamics in time using a forward pass:\n//   [X_1, X_2,..., X_k+1] = A_qp X_0 + B_qp [u_0, u_1,..., u_k]\nvoid CalculateQpMats(const Eigen::MatrixXd& a_exp, const Eigen::MatrixXd& b_exp,\n    int horizon, Eigen::MatrixXd* a_qp_ptr,\n    Eigen::MatrixXd* b_qp_ptr);\n\nvoid UpdateConstraintsMatrix(std::vector<double>& friction_coeff,\n    int horizon, int num_legs,\n    Eigen::MatrixXd* constraint_ptr);\n\nvoid CalculateConstraintBounds(const Eigen::MatrixXd& contact_state, double fz_max,\n    double fz_min, double friction_coeff, int horizon,\n    Eigen::VectorXd* constraint_lb_ptr,\n    Eigen::VectorXd* constraint_ub_ptr);\n\ndouble EstimateCoMHeightSimple(const Eigen::MatrixXd& foot_positions_world,\n    const std::vector<bool> foot_contact_states);\n\n// The MIT convex mpc implementation as described in this paper:\n//   https://ieeexplore.ieee.org/document/8594448/\n// Computes the optimal feet contact forces given a desired center of mass\n// trajectory and gait pattern.\nclass ConvexMpc {\npublic:\n    static constexpr int kStateDim =\n        13;  // 6 dof pose + 6 dof velocity + 1 gravity.\n\n    // For each foot contact force we use 4-dim cone approximation + 1 for z.\n    static constexpr int kConstraintDim = 5;\n\n    ConvexMpc(double mass, const std::vector<double>& inertia, int num_legs,\n        int planning_horizon, double timestep,\n        const std::vector<double>& qp_weights, double alpha = 1e-5,\n#ifdef TDS_ENABLE_QPOASES\n        QPSolverName qp_solver_name=QPOASES\n#else\n        QPSolverName qp_solver_name=OSQP\n#endif\n    );\n\n    virtual ~ConvexMpc()\n    {\n        osqp_cleanup(workspace_);\n    }\n    // If not explicitly specified, we assume the quantities are measured in a\n    // world frame. Usually we choose the yaw-aligned horizontal frame i.e. an\n    // instanteneous world frame at the time of planning with its origin at CoM\n    // and z axis aligned with gravity. The yaw-alignment means that the CoM\n    // rotation measured in this frame has zero yaw component. Caveat: We expect\n    // the input euler angle roll_pitch_yaw to be in ZYX format, i.e. the rotation\n    // order is X -> Y -> Z, with respect to the extrinsic (fixed) coordinate\n    // frame. In the intrinsic (body-attached) frame the rotation order is Z -> Y'\n    // -> X\".\n    std::vector<double> ComputeContactForces(\n        std::vector<double> com_position,\n        std::vector<double> com_velocity,\n        std::vector<double> com_roll_pitch_yaw,\n        std::vector<double> com_angular_velocity,\n        std::vector<int> foot_contact_states,\n        std::vector<double> foot_positions_body_frame,\n        std::vector<double> foot_friction_coeffs,\n        std::vector<double> desired_com_position,\n        std::vector<double> desired_com_velocity,\n        std::vector<double> desired_com_roll_pitch_yaw,\n        std::vector<double> desired_com_angular_velocity);\n\n    // Reset the solver so that for the next optimization run the solver is\n    // re-initialized.\n    void ResetSolver();\n\nprivate:\n    const double mass_;\n    const double inv_mass_;\n    const Eigen::Matrix3d inertia_;\n    const Eigen::Matrix3d inv_inertia_;\n    const int num_legs_;\n    const int planning_horizon_;\n    const double timestep_;\n    QPSolverName qp_solver_name_;\n\n    // 13 * horizon diagonal matrix.\n    const Eigen::MatrixXd qp_weights_;\n\n    // 13 x 13 diagonal matrix.\n    const Eigen::MatrixXd qp_weights_single_;\n\n    // num_legs * 3 * horizon diagonal matrix.\n    const Eigen::MatrixXd alpha_;\n    const Eigen::MatrixXd alpha_single_;\n    const int action_dim_;\n\n    // The following matrices will be updated for every call. However, their sizes\n    // can be determined at class initialization time.\n    Eigen::VectorXd state_;                 // 13\n    Eigen::VectorXd desired_states_;        // 13 * horizon\n    Eigen::MatrixXd contact_states_;        // horizon x num_legs\n    Eigen::MatrixXd foot_positions_base_;   // num_legs x 3\n    Eigen::MatrixXd foot_positions_world_;  // num_legs x 3\n    Eigen::VectorXd foot_friction_coeff_;   // num_legs\n    Eigen::Matrix3d rotation_;\n    Eigen::Matrix3d inertia_world_;    // rotation x inertia x rotation_transpose\n    Eigen::MatrixXd a_mat_;            // 13 x 13\n    Eigen::MatrixXd b_mat_;            // 13 x (num_legs * 3)\n    Eigen::MatrixXd ab_concatenated_;  // 13 + num_legs * 3 x 13 + num_legs * 3\n    Eigen::MatrixXd a_exp_;            // same dimension as a_mat_\n    Eigen::MatrixXd b_exp_;            // same dimension as b_mat_\n\n    // Contains all the power mats of a_exp_. Consider Eigen::SparseMatrix.\n    Eigen::MatrixXd a_qp_;  // 13 * horizon x 13\n    Eigen::MatrixXd b_qp_;  // 13 * horizon x num_legs * 3 * horizon sparse\n    Eigen::MatrixXd b_qp_transpose_;\n    Eigen::MatrixXd p_mat_;  // num_legs * 3 * horizon x num_legs * 3 * horizon\n    Eigen::VectorXd q_vec_;  // num_legs * 3 * horizon vector\n\n    // Auxiliary containing A^n*B, with n in [0, num_legs * 3)\n    Eigen::MatrixXd anb_aux_;  // 13 * horizon x (num_legs * 3)\n\n    // Contains the constraint matrix and bounds.\n    Eigen::MatrixXd\n        constraint_;  // 5 * num_legs * horizon x 3 * num_legs * horizon\n    Eigen::VectorXd constraint_lb_;  // 5 * num_legs * horizon\n    Eigen::VectorXd constraint_ub_;  // 5 * num_legs * horizon\n\n    std::vector<double> qp_solution_;\n\n    ::OSQPWorkspace* workspace_;\n    // Whether optimizing for the first step\n    bool initial_run_;\n};\n\nconstexpr int ConvexMpc::kStateDim;\n\nMatrix3d ConvertRpyToRot(const Vector3d& rpy) {\n    assert(rpy.size() == k3Dim);\n    const AngleAxisd roll(rpy[0], Vector3d::UnitX());\n    const AngleAxisd pitch(rpy[1], Vector3d::UnitY());\n    const AngleAxisd yaw(rpy[2], Vector3d::UnitZ());\n    Quaterniond q = yaw * pitch * roll;\n\n    return q.matrix();\n}\n\nMatrix3d ConvertToSkewSymmetric(const Vector3d& vec) {\n    Matrix3d skew_symm;\n    skew_symm << 0, -vec(2), vec(1), vec(2), 0, -vec(0), -vec(1), vec(0), 0;\n    return skew_symm;\n}\n\nvoid CalculateAMat(const Vector3d& rpy, MatrixXd* a_mat_ptr) {\n    // The transformation of angular velocity to roll pitch yaw rate. Caveat:\n    // rpy rate is not a proper vector and does not follow the common vector\n    // transformation dicted by the rotation matrix. Here we assume the input\n    // rotation is in X->Y->Z order in the extrinsic/fixed frame, or z->y'->x''\n    // order in the intrinsic frame.\n    const double cos_yaw = cos(rpy[2]);\n    const double sin_yaw = sin(rpy[2]);\n    const double cos_pitch = cos(rpy[1]);\n    const double tan_pitch = tan(rpy[1]);\n    Matrix3d angular_velocity_to_rpy_rate;\n    angular_velocity_to_rpy_rate << cos_yaw / cos_pitch, sin_yaw / cos_pitch, 0,\n        -sin_yaw, cos_yaw, 0, cos_yaw* tan_pitch, sin_yaw* tan_pitch, 1;\n\n    MatrixXd& a_mat = *a_mat_ptr;\n    a_mat.block<3, 3>(0, 6) = angular_velocity_to_rpy_rate;\n    a_mat(3, 9) = 1;\n    a_mat(4, 10) = 1;\n    a_mat(5, 11) = 1;\n    a_mat(11, 12) = 1;\n}\n\nvoid CalculateBMat(double inv_mass, const Matrix3d& inv_inertia,\n    const MatrixXd& foot_positions, MatrixXd* b_mat_ptr) {\n    // b_mat contains non_zero elements only in row 6:12.\n    const int num_legs = foot_positions.rows();\n    MatrixXd& b_mat = *b_mat_ptr;\n    for (int i = 0; i < num_legs; ++i) {\n        b_mat.block<k3Dim, k3Dim>(6, i * k3Dim) =\n            inv_inertia * ConvertToSkewSymmetric(foot_positions.row(i));\n        b_mat(9, i * k3Dim) = inv_mass;\n        b_mat(10, i * k3Dim + 1) = inv_mass;\n        b_mat(11, i * k3Dim + 2) = inv_mass;\n    }\n}\n\nvoid CalculateExponentials(const MatrixXd& a_mat, const MatrixXd& b_mat,\n    double timestep, MatrixXd* ab_mat_ptr,\n    MatrixXd* a_exp_ptr, MatrixXd* b_exp_ptr) {\n    const int state_dim = ConvexMpc::kStateDim;\n    MatrixXd& ab_mat = *ab_mat_ptr;\n    ab_mat.block<state_dim, state_dim>(0, 0) = a_mat * timestep;\n    const int action_dim = b_mat.cols();\n    ab_mat.block(0, state_dim, state_dim, action_dim) = b_mat * timestep;\n\n    // This temporary is inevitable.\n    MatrixXd ab_exp = ab_mat.exp();\n    *a_exp_ptr = ab_exp.block<state_dim, state_dim>(0, 0);\n    *b_exp_ptr = ab_exp.block(0, state_dim, state_dim, action_dim);\n}\n\nvoid CalculateQpMats(const MatrixXd& a_exp, const MatrixXd& b_exp,\n    const MatrixXd& qp_weights_single,\n    const MatrixXd& alpha_single, int horizon,\n    MatrixXd* a_qp_ptr, MatrixXd* anb_aux_ptr,\n    MatrixXd* b_qp_ptr, MatrixXd* p_mat_ptr) {\n    const int state_dim = ConvexMpc::kStateDim;\n    MatrixXd& a_qp = *a_qp_ptr;\n    a_qp.block(0, 0, state_dim, state_dim) = a_exp;\n    for (int i = 1; i < horizon - 1; ++i) {\n        a_qp.block<state_dim, state_dim>(i * state_dim, 0) =\n            a_exp * a_qp.block<state_dim, state_dim>((i - 1) * state_dim, 0);\n    }\n\n    const int action_dim = b_exp.cols();\n\n    MatrixXd& anb_aux = *anb_aux_ptr;\n    anb_aux.block(0, 0, state_dim, action_dim) = b_exp;\n    for (int i = 1; i < horizon; ++i) {\n        anb_aux.block(i * state_dim, 0, state_dim, action_dim) =\n            a_exp * anb_aux.block((i - 1) * state_dim, 0, state_dim, action_dim);\n    }\n\n    MatrixXd& b_qp = *b_qp_ptr;\n    for (int i = 0; i < horizon; ++i) {\n        // Diagonal block.\n        b_qp.block(i * state_dim, i * action_dim, state_dim, action_dim) = b_exp;\n        // Off diagonal Diagonal block = A^(i - j - 1) * B_exp.\n        for (int j = 0; j < i; ++j) {\n            const int power = i - j;\n            b_qp.block(i * state_dim, j * action_dim, state_dim, action_dim) =\n                anb_aux.block(power * state_dim, 0, state_dim, action_dim);\n        }\n    }\n\n    MatrixXd& p_mat = *p_mat_ptr;\n    for (int i = horizon - 1; i >= 0; --i) {\n        p_mat.block(i * action_dim, (horizon - 1) * action_dim, action_dim,\n            action_dim) =\n            anb_aux.block((horizon - i - 1) * state_dim, 0, state_dim, action_dim)\n            .transpose() *\n            qp_weights_single * b_exp;\n        if (i != horizon - 1) {\n            p_mat.block((horizon - 1) * action_dim, i * action_dim, action_dim,\n                action_dim) =\n                p_mat\n                .block(i * action_dim, (horizon - 1) * action_dim, action_dim,\n                    action_dim)\n                .transpose();\n        }\n    }\n\n    for (int i = horizon - 2; i >= 0; --i) {\n        // Diagonal block.\n        p_mat.block(i * action_dim, i * action_dim, action_dim, action_dim) =\n            p_mat.block((i + 1) * action_dim, (i + 1) * action_dim, action_dim,\n                action_dim) +\n            anb_aux.block((horizon - i - 1) * state_dim, 0, state_dim, action_dim)\n            .transpose() *\n            qp_weights_single *\n            anb_aux.block((horizon - i - 1) * state_dim, 0, state_dim,\n                action_dim);\n        // Off diagonal block\n        for (int j = i + 1; j < horizon - 1; ++j) {\n            p_mat.block(i * action_dim, j * action_dim, action_dim, action_dim) =\n                p_mat.block((i + 1) * action_dim, (j + 1) * action_dim, action_dim,\n                    action_dim) +\n                anb_aux.block((horizon - i - 1) * state_dim, 0, state_dim, action_dim)\n                .transpose() *\n                qp_weights_single *\n                anb_aux.block((horizon - j - 1) * state_dim, 0, state_dim,\n                    action_dim);\n            p_mat.block(j * action_dim, i * action_dim, action_dim, action_dim) =\n                p_mat.block(i * action_dim, j * action_dim, action_dim, action_dim)\n                .transpose();\n        }\n    }\n\n    p_mat *= 2.0;\n    for (int i = 0; i < horizon; ++i) {\n        p_mat.block(i * action_dim, i * action_dim, action_dim, action_dim) +=\n            alpha_single;\n    }\n}\n\nvoid UpdateConstraintsMatrix(std::vector<double>& friction_coeff,\n    int horizon, int num_legs,\n    MatrixXd* constraint_ptr) {\n    const int constraint_dim = ConvexMpc::kConstraintDim;\n    MatrixXd& constraint = *constraint_ptr;\n    for (int i = 0; i < horizon * num_legs; ++i) {\n        constraint.block<constraint_dim, k3Dim>(i * constraint_dim, i * k3Dim)\n            << -1,\n            0, friction_coeff[0], 1, 0, friction_coeff[1], 0, -1, friction_coeff[2],\n            0, 1, friction_coeff[3], 0, 0, 1;\n    }\n}\n\nvoid CalculateConstraintBounds(const MatrixXd& contact_state, double fz_max,\n    double fz_min, double friction_coeff,\n    int horizon, VectorXd* constraint_lb_ptr,\n    VectorXd* constraint_ub_ptr) {\n    const int constraint_dim = ConvexMpc::kConstraintDim;\n\n    const int num_legs = contact_state.cols();\n\n    VectorXd& constraint_lb = *constraint_lb_ptr;\n    VectorXd& constraint_ub = *constraint_ub_ptr;\n    for (int i = 0; i < horizon; ++i) {\n        for (int j = 0; j < num_legs; ++j) {\n            const int row = (i * num_legs + j) * constraint_dim;\n            constraint_lb(row) = 0;\n            constraint_lb(row + 1) = 0;\n            constraint_lb(row + 2) = 0;\n            constraint_lb(row + 3) = 0;\n            constraint_lb(row + 4) = fz_min * contact_state(i, j);\n\n            const double friction_ub =\n                (friction_coeff + 1) * fz_max * contact_state(i, j);\n            constraint_ub(row) = friction_ub;\n            constraint_ub(row + 1) = friction_ub;\n            constraint_ub(row + 2) = friction_ub;\n            constraint_ub(row + 3) = friction_ub;\n            constraint_ub(row + 4) = fz_max * contact_state(i, j);\n        }\n    }\n}\n\ndouble EstimateCoMHeightSimple(\n    const MatrixXd& foot_positions_world,\n    const std::vector<int> foot_contact_states) {\n    int legs_in_contact = 0;\n    double com_height = 0;\n    const int z_dim = 2;\n    for (int i = 0; i < foot_contact_states.size(); ++i) {\n        if (foot_contact_states[i]) {\n            com_height += foot_positions_world(i, z_dim);\n            legs_in_contact += 1;\n        }\n    }\n\n    // We don't support jumping in air for now.\n    DCHECK_GT(legs_in_contact, 0);\n    return abs(com_height / legs_in_contact);\n}\n\nMatrixXd AsBlockDiagonalMat(const std::vector<double>& qp_weights,\n    int planning_horizon) {\n    const Eigen::Map<const VectorXd> qp_weights_vec(qp_weights.data(),\n        qp_weights.size());\n    // Directly return the rhs will cause a TSAN failure, probably due to the\n    // asDiagonal not reall copying the memory. Creates the temporary will ensure\n    // copy on return.\n    const MatrixXd qp_weights_mat =\n        qp_weights_vec.replicate(planning_horizon, 1).asDiagonal();\n    return qp_weights_mat;\n}\n\nConvexMpc::ConvexMpc(double mass, const std::vector<double>& inertia,\n    int num_legs, int planning_horizon, double timestep,\n    const std::vector<double>& qp_weights, double alpha,\n      QPSolverName qp_solver_name)\n    : mass_(mass),\n    inv_mass_(1 / mass),\n    inertia_(inertia.data()),\n    inv_inertia_(inertia_.inverse()),\n    num_legs_(num_legs),\n    planning_horizon_(planning_horizon),\n    timestep_(timestep),\n    qp_solver_name_(qp_solver_name),\n    qp_weights_(AsBlockDiagonalMat(qp_weights, planning_horizon)),\n    qp_weights_single_(AsBlockDiagonalMat(qp_weights, 1)),\n    alpha_(alpha* MatrixXd::Identity(num_legs* planning_horizon* k3Dim,\n        num_legs* planning_horizon* k3Dim)),\n    alpha_single_(alpha*\n        MatrixXd::Identity(num_legs* k3Dim, num_legs* k3Dim)),\n    action_dim_(num_legs* k3Dim),\n    state_(kStateDim),\n    desired_states_(kStateDim* planning_horizon),\n    contact_states_(planning_horizon, num_legs),\n    foot_positions_base_(num_legs, k3Dim),\n    foot_positions_world_(num_legs, k3Dim),\n    foot_friction_coeff_(num_legs_),\n    a_mat_(kStateDim, kStateDim),\n    b_mat_(kStateDim, action_dim_),\n    ab_concatenated_(kStateDim + action_dim_, kStateDim + action_dim_),\n    a_exp_(kStateDim, kStateDim),\n    b_exp_(kStateDim, action_dim_),\n    a_qp_(kStateDim* planning_horizon, kStateDim),\n    b_qp_(kStateDim* planning_horizon, action_dim_* planning_horizon),\n    p_mat_(num_legs* planning_horizon* k3Dim,\n        num_legs* planning_horizon* k3Dim),\n    q_vec_(num_legs* planning_horizon* k3Dim),\n    anb_aux_(kStateDim* planning_horizon, action_dim_),\n    constraint_(kConstraintDim* num_legs* planning_horizon,\n        action_dim_* planning_horizon),\n    constraint_lb_(kConstraintDim* num_legs* planning_horizon),\n    constraint_ub_(kConstraintDim* num_legs* planning_horizon),\n    qp_solution_(k3Dim* num_legs* planning_horizon),\n    workspace_(0),\n    initial_run_(true)\n\n{\n    assert(qp_weights.size() == kStateDim);\n    // We assume the input inertia is a 3x3 matrix.\n    assert(inertia.size() == k3Dim * k3Dim);\n    state_.setZero();\n    desired_states_.setZero();\n    contact_states_.setZero();\n    foot_positions_base_.setZero();\n    foot_positions_world_.setZero();\n    foot_friction_coeff_.setZero();\n    a_mat_.setZero();\n    b_mat_.setZero();\n    ab_concatenated_.setZero();\n    a_exp_.setZero();\n    b_exp_.setZero();\n    a_qp_.setZero();\n    b_qp_.setZero();\n    b_qp_transpose_.setZero();\n    constraint_.setZero();\n    constraint_lb_.setZero();\n    constraint_ub_.setZero();\n}\n\nvoid ConvexMpc::ResetSolver() { initial_run_ = true; }\n\nstd::vector<double> ConvexMpc::ComputeContactForces(\n    std::vector<double> com_position,\n    std::vector<double> com_velocity,\n    std::vector<double> com_roll_pitch_yaw,\n    std::vector<double> com_angular_velocity,\n    std::vector<int> foot_contact_states,\n    std::vector<double> foot_positions_body_frame,\n    std::vector<double> foot_friction_coeffs,\n    std::vector<double> desired_com_position,\n    std::vector<double> desired_com_velocity,\n    std::vector<double> desired_com_roll_pitch_yaw,\n    std::vector<double> desired_com_angular_velocity) {\n\n    std::vector<double> error_result;\n\n\n    // First we compute the foot positions in the world frame.\n    DCHECK_EQ(com_roll_pitch_yaw.size(), k3Dim);\n    const Quaterniond com_rotation =\n        AngleAxisd(com_roll_pitch_yaw[0], Vector3d::UnitX()) *\n        AngleAxisd(com_roll_pitch_yaw[1], Vector3d::UnitY()) *\n        AngleAxisd(com_roll_pitch_yaw[2], Vector3d::UnitZ());\n\n    DCHECK_EQ(foot_positions_body_frame.size(), k3Dim * num_legs_);\n    foot_positions_base_ = Eigen::Map<const MatrixXd>(\n        foot_positions_body_frame.data(), k3Dim, num_legs_)\n        .transpose();\n    for (int i = 0; i < num_legs_; ++i) {\n        foot_positions_world_.row(i) = com_rotation * foot_positions_base_.row(i);\n    }\n\n    // Now we can estimate the body height using the world frame foot positions\n    // and contact states. We use simple averges leg height here.\n    DCHECK_EQ(foot_contact_states.size(), num_legs_);\n    const double com_z =\n        com_position.size() == k3Dim\n        ? com_position[2]\n        : EstimateCoMHeightSimple(foot_positions_world_, foot_contact_states);\n\n    // In MPC planning we don't care about absolute position in the horizontal\n    // plane.\n    const double com_x = 0;\n    const double com_y = 0;\n\n    // Prepare the current and desired state vectors of length kStateDim *\n    // planning_horizon.\n    DCHECK_EQ(com_velocity.size(), k3Dim);\n    DCHECK_EQ(com_angular_velocity.size(), k3Dim);\n    state_ << com_roll_pitch_yaw[0], com_roll_pitch_yaw[1], com_roll_pitch_yaw[2],\n        com_x, com_y, com_z, com_angular_velocity[0], com_angular_velocity[1],\n        com_angular_velocity[2], com_velocity[0], com_velocity[1],\n        com_velocity[2], -kGravity;\n\n    for (int i = 0; i < planning_horizon_; ++i) {\n        desired_states_[i * kStateDim + 0] = desired_com_roll_pitch_yaw[0];\n        desired_states_[i * kStateDim + 1] = desired_com_roll_pitch_yaw[1];\n        desired_states_[i * kStateDim + 2] =\n            com_roll_pitch_yaw[2] +\n            timestep_ * (i + 1) * desired_com_angular_velocity[2];\n\n        desired_states_[i * kStateDim + 3] =\n            timestep_ * (i + 1) * desired_com_velocity[0];\n        desired_states_[i * kStateDim + 4] =\n            timestep_ * (i + 1) * desired_com_velocity[1];\n        desired_states_[i * kStateDim + 5] = desired_com_position[2];\n\n        // Prefer to stablize roll and pitch.\n        desired_states_[i * kStateDim + 6] = 0;\n        desired_states_[i * kStateDim + 7] = 0;\n        desired_states_[i * kStateDim + 8] = desired_com_angular_velocity[2];\n\n        desired_states_[i * kStateDim + 9] = desired_com_velocity[0];\n        desired_states_[i * kStateDim + 10] = desired_com_velocity[1];\n        // Prefer to stablize the body height.\n        desired_states_[i * kStateDim + 11] = 0;\n\n        desired_states_[i * kStateDim + 12] = -kGravity;\n    }\n\n    const Vector3d rpy(com_roll_pitch_yaw[0], com_roll_pitch_yaw[1],\n        com_roll_pitch_yaw[2]);\n\n    CalculateAMat(rpy, &a_mat_);\n\n    rotation_ = ConvertRpyToRot(rpy);\n    const Matrix3d inv_inertia_world =\n        rotation_ * inv_inertia_ * rotation_.transpose();\n\n    CalculateBMat(inv_mass_, inv_inertia_world, foot_positions_world_, &b_mat_);\n\n    CalculateExponentials(a_mat_, b_mat_, timestep_, &ab_concatenated_, &a_exp_,\n        &b_exp_);\n\n    CalculateQpMats(a_exp_, b_exp_, qp_weights_single_, alpha_single_,\n        planning_horizon_, &a_qp_, &anb_aux_, &b_qp_, &p_mat_);\n\n    const MatrixXd state_diff = a_qp_ * state_ - desired_states_;\n\n    q_vec_ = 2 * b_qp_.transpose() * (qp_weights_ * state_diff);\n\n    const VectorXd one_vec = VectorXd::Constant(planning_horizon_, 1.0);\n    const VectorXd zero_vec = VectorXd::Zero(planning_horizon_);\n    for (int j = 0; j < foot_contact_states.size(); ++j) {\n        if (foot_contact_states[j]) {\n            contact_states_.col(j) = one_vec;\n        }\n        else {\n            contact_states_.col(j) = zero_vec;\n        }\n    }\n\n    CalculateConstraintBounds(contact_states_, mass_ * kGravity * kMaxScale,\n        mass_ * kGravity * kMinScale,\n        foot_friction_coeffs[0], planning_horizon_,\n        &constraint_lb_, &constraint_ub_);\n\n\n\n    if (qp_solver_name_ == OSQP)\n    {\n      UpdateConstraintsMatrix(foot_friction_coeffs, planning_horizon_, num_legs_,\n          &constraint_);\n      foot_friction_coeff_ << foot_friction_coeffs[0], foot_friction_coeffs[1],\n          foot_friction_coeffs[2], foot_friction_coeffs[3];\n\n\n      Eigen::SparseMatrix<double, Eigen::ColMajor, qp_int64> objective_matrix = p_mat_.sparseView();\n      Eigen::VectorXd objective_vector = q_vec_;\n      Eigen::SparseMatrix<double, Eigen::ColMajor, qp_int64> constraint_matrix = constraint_.sparseView();\n\n      int num_variables = constraint_.cols();\n      int num_constraints = constraint_.rows();\n\n      ::OSQPSettings settings;\n      osqp_set_default_settings(&settings);\n      settings.verbose = false;\n      settings.warm_start = true;\n      settings.polish = true;\n      settings.adaptive_rho_interval = 25;\n      settings.eps_abs = 1e-3;\n      settings.eps_rel = 1e-3;\n\n      assert(p_mat_.cols()== num_variables);\n      assert(p_mat_.rows()== num_variables);\n      assert(q_vec_.size()== num_variables);\n      assert(constraint_lb_.size() == num_constraints);\n      assert(constraint_ub_.size() == num_constraints);\n\n      VectorXd clipped_lower_bounds = constraint_lb_.cwiseMax(-OSQP_INFTY);\n      VectorXd clipped_upper_bounds = constraint_ub_.cwiseMin(OSQP_INFTY);\n\n      ::OSQPData data;\n      data.n = num_variables;\n      data.m = num_constraints;\n\n      Eigen::SparseMatrix<double, Eigen::ColMajor, qp_int64>\n          objective_matrix_upper_triangle =\n          objective_matrix.triangularView<Eigen::Upper>();\n\n      ::csc osqp_objective_matrix = {\n          objective_matrix_upper_triangle.outerIndexPtr()[num_variables],\n          num_variables,\n          num_variables,\n          const_cast<qp_int64*>(objective_matrix_upper_triangle.outerIndexPtr()),\n          const_cast<qp_int64*>(objective_matrix_upper_triangle.innerIndexPtr()),\n          const_cast<double*>(objective_matrix_upper_triangle.valuePtr()),\n          -1 };\n      data.P = &osqp_objective_matrix;\n\n      ::csc osqp_constraint_matrix = {\n          constraint_matrix.outerIndexPtr()[num_variables],\n          num_constraints,\n          num_variables,\n          const_cast<qp_int64*>(constraint_matrix.outerIndexPtr()),\n          const_cast<qp_int64*>(constraint_matrix.innerIndexPtr()),\n          const_cast<double*>(constraint_matrix.valuePtr()),\n          -1 };\n      data.A = &osqp_constraint_matrix;\n\n      data.q = const_cast<double*>(objective_vector.data());\n      data.l = clipped_lower_bounds.data();\n      data.u = clipped_upper_bounds.data();\n\n      const int return_code = 0;\n\n      if (workspace_==0) {\n          osqp_setup(&workspace_, &data, &settings);\n          initial_run_ = false;\n      }\n      else {\n\n          UpdateConstraintsMatrix(foot_friction_coeffs, planning_horizon_,\n              num_legs_, &constraint_);\n          foot_friction_coeff_ << foot_friction_coeffs[0], foot_friction_coeffs[1],\n              foot_friction_coeffs[2], foot_friction_coeffs[3];\n\n          c_int nnzP = objective_matrix_upper_triangle.nonZeros();\n\n          c_int nnzA = constraint_matrix.nonZeros();\n\n          int return_code = osqp_update_P_A(\n              workspace_, objective_matrix_upper_triangle.valuePtr(), OSQP_NULL, nnzP,\n              constraint_matrix.valuePtr(), OSQP_NULL, nnzA);\n\n          return_code =\n              osqp_update_lin_cost(workspace_, objective_vector.data());\n\n\n          return_code = osqp_update_bounds(\n              workspace_, clipped_lower_bounds.data(), clipped_upper_bounds.data());\n      }\n\n      if (osqp_solve(workspace_) != 0) {\n          if (osqp_is_interrupted()) {\n              return error_result;\n          }\n      }\n\n      Map<VectorXd> solution(qp_solution_.data(), qp_solution_.size());\n\n      if (workspace_->info->status_val== OSQP_SOLVED) {\n          solution = -Map<const VectorXd>(workspace_->solution->x, workspace_->data->n);\n      }\n      else {\n          //LOG(WARNING) << \"QP does not converge\";\n          return error_result;\n      }\n\n      return qp_solution_;\n    }\n    else\n    {\n#ifdef TDS_ENABLE_QPOASES\n      // Solve the QP Problem using qpOASES\n    UpdateConstraintsMatrix(foot_friction_coeffs, planning_horizon_, num_legs_,\n                            &constraint_);\n\n    // To use qpOASES, we need to eleminate the zero rows/cols from the\n    // matrices when copy to qpOASES buffer\n    int num_legs_in_contact = 0;\n    for (int i = 0; i < foot_contact_states.size(); ++i) {\n      if (foot_contact_states[i]) {\n        num_legs_in_contact += 1;\n      }\n    }\n\n    const int qp_dim = num_legs_in_contact * k3Dim * planning_horizon_;\n    const int constraint_dim = num_legs_in_contact * 5 * planning_horizon_;\n    std::vector<qpOASES::real_t> hessian(qp_dim * qp_dim, 0);\n    Map<RowMajorMatrixXd> hessian_mat_view(hessian.data(), qp_dim, qp_dim);\n    // Copy to the hessian\n    CopyToMatrix(p_mat_, foot_contact_states, num_legs_, planning_horizon_,\n                 k3Dim, k3Dim, false, &hessian_mat_view);\n\n    std::vector<qpOASES::real_t> g_vec(qp_dim, 0);\n    // Copy the g_vec\n    CopyToVec(q_vec_, foot_contact_states, num_legs_, planning_horizon_, k3Dim,\n              &g_vec);\n\n    std::vector<qpOASES::real_t> a_mat(qp_dim * constraint_dim, 0);\n    Map<RowMajorMatrixXd> a_mat_view(a_mat.data(), constraint_dim, qp_dim);\n    CopyToMatrix(constraint_, foot_contact_states, num_legs_, planning_horizon_,\n                 5, k3Dim, true, &a_mat_view);\n\n    std::vector<qpOASES::real_t> a_lb(constraint_dim, 0);\n    CopyToVec(constraint_lb_, foot_contact_states, num_legs_, planning_horizon_,\n              5, &a_lb);\n\n    std::vector<qpOASES::real_t> a_ub(constraint_dim, 0);\n    CopyToVec(constraint_ub_, foot_contact_states, num_legs_, planning_horizon_,\n              5, &a_ub);\n\n    auto qp_problem = QProblem(qp_dim, constraint_dim, qpOASES::HST_UNKNOWN,\n                               qpOASES::BT_TRUE);\n\n    qpOASES::Options options;\n    options.setToMPC();\n    options.printLevel = qpOASES::PL_NONE;\n    qp_problem.setOptions(options);\n\n    int max_solver_iter = 100;\n\n    qp_problem.init(hessian.data(), g_vec.data(), a_mat.data(), nullptr,\n                    nullptr, a_lb.data(), a_ub.data(), max_solver_iter,\n                    nullptr);\n\n    std::vector<qpOASES::real_t> qp_sol(qp_dim, 0);\n    qp_problem.getPrimalSolution(qp_sol.data());\n    for (auto& force : qp_sol) {\n      force = -force;\n    }\n    Map<VectorXd> qp_sol_vec(qp_sol.data(), qp_sol.size());\n\n    int buffer_index = 0;\n    for (int i = 0; i < num_legs_ * planning_horizon_; ++i) {\n      int leg_id = i % num_legs_;\n      if (foot_contact_states[leg_id] == 0) {\n        qp_solution_[i * k3Dim] = 0;\n        qp_solution_[i * k3Dim + 1] = 0;\n        qp_solution_[i * k3Dim + 2] = 0;\n      } else {\n        qp_solution_[i * k3Dim] = qp_sol[buffer_index * k3Dim];\n        qp_solution_[i * k3Dim + 1] = qp_sol[buffer_index * k3Dim + 1];\n        qp_solution_[i * k3Dim + 2] = qp_sol[buffer_index * k3Dim + 2];\n        ++buffer_index;\n      }\n    }\n#endif //TDS_ENABLE_QPOASES\n    return qp_solution_;\n    }\n}", "meta": {"hexsha": "9cd422405fc5bf472ad5f37114c1d1d2245d6a78", "size": 34385, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/whole_body_control/osqp_mpc_controller.hpp", "max_stars_repo_name": "sgillen/tiny-differentiable-simulator", "max_stars_repo_head_hexsha": "142f3b9e9b7e042c9298bc83ebbc08a9df7527af", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 862.0, "max_stars_repo_stars_event_min_datetime": "2020-05-14T19:22:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T20:23:24.000Z", "max_issues_repo_path": "examples/whole_body_control/osqp_mpc_controller.hpp", "max_issues_repo_name": "sgillen/tiny-differentiable-simulator", "max_issues_repo_head_hexsha": "142f3b9e9b7e042c9298bc83ebbc08a9df7527af", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 82.0, "max_issues_repo_issues_event_min_datetime": "2020-05-26T11:41:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T16:46:00.000Z", "max_forks_repo_path": "examples/whole_body_control/osqp_mpc_controller.hpp", "max_forks_repo_name": "sgillen/tiny-differentiable-simulator", "max_forks_repo_head_hexsha": "142f3b9e9b7e042c9298bc83ebbc08a9df7527af", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 93.0, "max_forks_repo_forks_event_min_datetime": "2020-05-15T05:37:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T09:09:50.000Z", "avg_line_length": 37.8272827283, "max_line_length": 106, "alphanum_fraction": 0.6581939799, "num_tokens": 9273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.27747420964327213}}
{"text": "#ifndef TCM_HERMITIAN_HPP\n#define TCM_HERMITIAN_HPP\n\n#include <cassert>\n#include <limits>\n#include <memory>\n\n#include <boost/core/demangle.hpp>\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <benchmark.hpp>\n#include <detail/lapack_wrapper.hpp>\n#include <detail/utils.hpp>\n\n\n\n// ============================================================================\n// ||                                                                        ||\n// ||                             ? H E E V R                                ||\n// ||                                                                        ||\n// ============================================================================\n\n\nnamespace tcm {\n\nnamespace lapack {\n\n\nnamespace {\n\n\ntemplate< class _Alloc\n        , class _T\n        , class = std::enable_if_t\n                  <    std::is_same<_T, float>()\n                    or std::is_same<_T, double>()\n\t\t          >\n        >\nauto heevr_impl( int const N\n               , _T* A, int const LDA\n               , _T* W\n               , _T* Z, int const LDZ\n               , utils::Type2Type<_T> ) -> void\n{\n\tif (N == 0) return;\n\n\tassert(N > 0);\n\tassert(A != nullptr and LDA >= N);\n\tassert(W != nullptr);\n\tassert(LDZ >= (Z == nullptr) ? 1 : N);\n\n\t/*\n\tusing _Alloc_traits = std::allocator_traits<_Alloc>;\n\ttypename _Alloc_traits::template rebind_alloc<_T>\n\t\t_T_alloc;\n\ttypename _Alloc_traits::template rebind_alloc<int>\n\t\t_int_alloc;\n\t*/\n\tusing size_type = std::make_unsigned_t<int>;\n\n\tchar const JOBZ   = (Z == nullptr) ? 'N' : 'V';\n\tchar const RANGE  = 'A';\n\tchar const UPLO   = 'U';\n\t_T   const VL     { 0.0 };\n\t_T   const VU     { 0.0 };\n\tint  const IL     = 0;\n\tint  const IU     = 0;\n\t_T   const ABSTOL { 0.0 }; //std::numeric_limits<_T>::min();\n\tint        M      = 0;\n\tauto       ISUPPZ = \n\t\ttcm::utils::_Storage<int, _Alloc>{2 * static_cast<size_type>(N)};\n\t// tcm::utils::allocate_workspace(_int_alloc, 2 * N);\n\tint        LWORK  = -1;\n\tint        LIWORK = -1;\n\tint        INFO   = 0;\n\n\t{\n\t\t_T  _work_dummy;\n\t\tint _iwork_dummy;\n\n\t\ttcm::import::heevr<_T>\n\t\t\t( &JOBZ, &RANGE, &UPLO, &N\n\t\t\t, A, &LDA\n\t\t\t, &VL, &VU\n\t\t\t, &IL, &IU\n\t\t\t, &ABSTOL, &M\n\t\t\t, W\n\t\t\t, Z, &LDZ\n\t\t\t, ISUPPZ.data()\n\t\t\t, &_work_dummy, &LWORK\n\t\t\t, &_iwork_dummy, &LIWORK\n\t\t\t, &INFO\n\t\t    );\n\n\t\tLWORK = static_cast<int>(_work_dummy);\n\t\tLIWORK = _iwork_dummy;\n\t}\n\n\tauto       WORK   = \n\t\ttcm::utils::_Storage<_T, _Alloc>{static_cast<size_type>(LWORK)};\n\t// tcm::utils::allocate_workspace(_T_alloc, LWORK);\n\tauto       IWORK  = \n\t\ttcm::utils::_Storage<int, _Alloc>{static_cast<size_type>(LIWORK)};\n\t// allocate_workspace(_int_alloc, LIWORK);\n\n\ttcm::import::heevr<_T>\n\t\t( &JOBZ, &RANGE, &UPLO, &N\n\t\t, A, &LDA\n\t\t, &VL, &VU\n\t\t, &IL, &IU\n\t\t, &ABSTOL, &M\n\t\t, W, Z, &LDZ\n\t\t, ISUPPZ.data()\n\t\t, WORK.data(), &LWORK\n\t\t, IWORK.data(), &LIWORK\n\t\t, &INFO\n\t\t);\n\n\tif (INFO < 0) {\n\t\tthrow std::invalid_argument{ \"Argument #\" + std::to_string(-INFO) \n\t\t                           + \" had an illegal value.\" };\n\t} \n\telse if (INFO > 0) {\n\t\tthrow std::runtime_error{\"Call to ?SYEVR failed.\"};\n\t}\n}\n\n\n\ntemplate< class _Alloc\n        , class _T\n        , class = std::enable_if_t\n                  <    std::is_same<_T, float>()\n                    or std::is_same<_T, double>()\n                  >\n        >\nauto heevr_impl( int const N\n               , std::complex<_T>* A, int const LDA\n               , _T* W\n               , std::complex<_T>* Z, int const LDZ\n               , utils::Type2Type<std::complex<_T>> ) -> void\n{\n\tif (N == 0) return;\n\n\tassert(N > 0);\n\tassert(A != nullptr and LDA >= N);\n\tassert(W != nullptr);\n\tassert(LDZ >= (Z == nullptr) ? 1 : N);\n\n\t/*\n\tusing _Alloc_traits = std::allocator_traits<_Alloc>;\n\ttypename _Alloc_traits::template rebind_alloc<std::complex<_T>>\n\t\t_Cmpl_T_alloc;\n\ttypename _Alloc_traits::template rebind_alloc<_T>\n\t\t_T_alloc;\n\ttypename _Alloc_traits::template rebind_alloc<int>\n\t\t_int_alloc;\n\t*/\n\tusing size_type = std::make_unsigned_t<int>;\n\n\tchar const JOBZ   = (Z == nullptr) ? 'N' : 'V';\n\tchar const RANGE  = 'A';\n\tchar const UPLO   = 'U';\n\t_T   const VL     { 0.0 };\n\t_T   const VU     { 0.0 };\n\tint  const IL     = 0;\n\tint  const IU     = 0;\n\t_T   const ABSTOL { 0.0 }; //std::numeric_limits<T>::min();\n\tint        M      = 0;\n\tauto       ISUPPZ = \n\t\ttcm::utils::_Storage<int, _Alloc>{2 * static_cast<size_type>(N)};\n\t// tcm::utils::allocate_workspace(_int_alloc, 2 * N);\n\t                 // std::make_unique<int[]>(2 * N);\n\tint        LWORK  = -1;\n\tint        LRWORK = -1;\n\tint        LIWORK = -1;\n\tint        INFO   = 0;\n\n\t{\n\t\tstd::complex<_T>   _work_dummy;\n\t\t_T                 _rwork_dummy;\n\t\tint                _iwork_dummy;\n\n\t\ttcm::import::heevr<std::complex<_T>>\n\t\t\t( &JOBZ, &RANGE, &UPLO, &N\n\t\t\t, A, &LDA\n\t\t\t, &VL, &VU\n\t\t\t, &IL, &IU\n\t\t\t, &ABSTOL, &M\n\t\t\t, W\n\t\t\t, Z, &LDZ\n\t\t\t, ISUPPZ.data()\n\t\t\t, &_work_dummy, &LWORK\n\t\t\t, &_rwork_dummy, &LRWORK\n\t\t\t, &_iwork_dummy, &LIWORK\n\t\t\t, &INFO\n\t\t    );\n\n\t\tLWORK  = static_cast<int>(std::real(_work_dummy));\n\t\tLRWORK = static_cast<int>(_rwork_dummy);\n\t\tLIWORK = _iwork_dummy;\n\t}\n\n\tauto       WORK   = \n\t\ttcm::utils::_Storage<std::complex<_T>, _Alloc>{\n\t\t\tstatic_cast<size_type>(LWORK) };\n\t// tcm::utils::allocate_workspace(_Cmpl_T_alloc, LWORK);\n\t                 // std::make_unique<std::complex<_T>[]>(LWORK);\n\tauto       RWORK  = \n\t\ttcm::utils::_Storage<_T, _Alloc>{static_cast<size_type>(LRWORK)};\n\t// tcm::utils::allocate_workspace(_T_alloc, LRWORK);\n\t                 // std::make_unique<_T[]>(LRWORK);\n\tauto       IWORK  = \n\t\ttcm::utils::_Storage<int, _Alloc>{static_cast<size_type>(LIWORK)};\n\t// tcm::utils::allocate_workspace(_int_alloc, LIWORK);\n\t                 // std::make_unique<int[]>(LIWORK);\n\n\ttcm::import::heevr<std::complex<_T>>\n\t\t( &JOBZ, &RANGE, &UPLO, &N\n\t\t, A, &LDA\n\t\t, &VL, &VU\n\t\t, &IL, &IU\n\t\t, &ABSTOL, &M\n\t\t, W, Z, &LDZ\n\t\t, ISUPPZ.data()\n\t\t, WORK.data(), &LWORK\n\t\t, RWORK.data(), &LRWORK\n\t\t, IWORK.data(), &LIWORK\n\t\t, &INFO\n\t\t);\n\n\tif(INFO < 0) {\n\t\tthrow std::invalid_argument{ \"Argument #\" + std::to_string(-INFO) \n\t\t                           + \" had an illegal value.\" };\n\t} \n\telse if(INFO > 0) {\n\t\tthrow std::runtime_error{\"Call to ?HEEVR failed.\"};\n\t}\n}\n\n} // unnamed namespace \n\n\n\ntemplate< class _T\n        , class _Alloc = std::allocator<_T>\n        >\nauto heevr( std::size_t const n\n          , _T* A, std::size_t const lda\n          , utils::Base<_T>* W\n          , _T* Z, std::size_t const ldz ) -> void\n{\n\tTCM_MEASURE(\"heevr<\" + boost::core::demangle(typeid(_T).name()) + \">()\");\n\n\theevr_impl<_Alloc>\n\t\t( boost::numeric_cast<int>(n)\n\t    , A, boost::numeric_cast<int>(lda)\n\t    , W\n\t    , Z, boost::numeric_cast<int>(ldz)\n\t    , utils::Type2Type<_T>{} );\n}\n\n\n\n} // namespace lapack\n\n} // namespace tcm\n\n\n\n\n\n\n\n\n// ============================================================================\n// ||                                                                        ||\n// ||                              ? H E E V                                 ||\n// ||                                                                        ||\n// ============================================================================\n\n\n/*\nnamespace tcm {\n\nnamespace lapack {\n\n\nnamespace {\n\n\ntemplate< class _T\n        , class = std::enable_if_t\n                  <   std::is_same<_T, float>() \n                   or std::is_same<_T, double>()\n                  >\n        >\nauto heev_impl( int const N\n              , _T* A, int const LDA\n              , _T* W\n              , bool compute_eigenvectors\n              , utils::Type2Type<_T> ) -> void\n{\n\tif (N == 0) return;\n\n\tassert(N > 0);\n\tassert(A != nullptr and LDA >= N);\n\tassert(W != nullptr);\n\n\tchar const JOBZ  = compute_eigenvectors ? 'V' : 'N';\n\tchar const UPLO  = 'U';\n\tint        LWORK = -1;\n\tint        INFO;\n\n\t{\n\t\t_T _work_dummy;\n\n\t\ttcm::import::heev<_T>\n\t\t\t( &JOBZ, &UPLO, &N\n\t\t\t, A, &LDA\n\t\t\t, W\n\t\t\t, &_work_dummy,  &LWORK\n\t\t\t, &INFO\n\t\t\t);\n\n\t\tLWORK = static_cast<int>(_work_dummy);\n\t}\n\n\tauto       WORK  = std::make_unique<_T[]>(LWORK);\n\n\ttcm::import::heev<_T>\n\t\t( &JOBZ, &UPLO, &N\n\t\t, A, &LDA\n\t\t, W\n\t\t, WORK.get(), &LWORK\n\t\t, &INFO\n\t\t);\n\n\tif (INFO < 0) {\n\t\tthrow std::invalid_argument{ \"Argument #\" + std::to_string(-INFO) \n\t\t                           + \" had an illegal value.\" };\n\t}\n\telse if (INFO > 0) {\n\t\tthrow std::runtime_error{\"Call to ?SYEV failed.\"};\n\t}\n}\n\n\ntemplate< class _T\n        , class = std::enable_if_t\n                  <   std::is_same<_T, float>() \n                   or std::is_same<_T, double>()\n                  >\n        >\nauto heev_impl( int const N\n              , std::complex<_T>* A, int const LDA\n              , _T* W\n              , bool compute_eigenvectors\n              , utils::Type2Type<std::complex<_T>> ) -> void\n{\n\tif(N == 0) return;\n\n\tassert(N > 0);\n\tassert(A != nullptr and LDA >= N);\n\tassert(W != nullptr);\n\n\tchar const JOBZ  = compute_eigenvectors ? 'V' : 'N';\n\tchar const UPLO  = 'U';\n\tauto       RWORK = std::make_unique<_T[]>(3 * N - 2);\n\tint        LWORK = -1;\n\tint        INFO;\n\n\t{\n\t\tstd::complex<_T> _work_dummy;\n\n\t\ttcm::import::heev<std::complex<_T>>\n\t\t\t( &JOBZ, &UPLO, &N\n\t\t\t, A, &LDA\n\t\t\t, W\n\t\t\t, &_work_dummy, &LWORK\n\t\t\t, RWORK.get()\n\t\t\t, &INFO\n\t\t\t);\n\n\t\tLWORK = static_cast<int>(std::real(_work_dummy));\n\t}\n\t\n\tauto       WORK  = std::make_unique<std::complex<_T>[]>(LWORK);\n\n\ttcm::import::heev<std::complex<_T>>\n\t\t( &JOBZ, &UPLO, &N\n\t\t, A, &LDA\n\t\t, W\n\t\t, WORK.get(),  &LWORK\n\t\t, RWORK.get()\n\t\t, &INFO\n\t\t);\n\n\tif (INFO < 0) {\n\t\tthrow std::invalid_argument{ \"Argument #\" + std::to_string(-INFO) \n\t\t                           + \" had an illegal value.\" };\n\t}\n\telse if (INFO > 0) {\n\t\tthrow std::runtime_error{\"Call to ?HEEV failed.\"};\n\t}\n}\n\n} // unnamed namespace\n\n\ntemplate<class _T>\ninline\nauto heev( std::size_t const n\n         , _T* A, std::ptrdiff_t const lda\n         , utils::Base<_T>* W\n         , bool compute_eigenvectors ) -> void\n{\n\tMEASURE;\n\n\theev_impl( boost::numeric_cast<int>(n)\n\t         , A, boost::numeric_cast<int>(lda)\n\t         , W\n\t         , compute_eigenvectors\n\t         , utils::Type2Type<_T>{} );\n}\n\n\n} // namespace lapack\n\n} // namespace tcm\n*/\n\n\n\n\n#endif // TCM_HERMITIAN_HPP\n", "meta": {"hexsha": "39ddb6a7b35ccdafcd849ae5d2cf90fd4cad64df", "size": 10088, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/detail/hermitian.hpp", "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": "include/detail/hermitian.hpp", "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": "include/detail/hermitian.hpp", "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": 23.0846681922, "max_line_length": 79, "alphanum_fraction": 0.5012886598, "num_tokens": 3143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2774544490319686}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_STEREA_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_STEREA_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// Copyright (c) 2003   Gerald I. Evenden\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#include <boost/geometry/extensions/gis/projections/impl/pj_gauss.hpp>\n\n#include <boost/geometry/extensions/gis/projections/epsg_traits.hpp>\n\nnamespace boost { namespace geometry { namespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace sterea\n    {\n\n            static const double DEL_TOL = 1.e-14;\n            static const int MAX_ITER = 10;\n\n            struct par_sterea\n            {\n                double phic0;\n                double cosc0, sinc0;\n                double R2;\n                gauss::GAUSS en;\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename Geographic, typename Cartesian, typename Parameters>\n            struct base_sterea_ellipsoid : public base_t_fi<base_sterea_ellipsoid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>\n            {\n\n                 typedef double geographic_type;\n                 typedef double cartesian_type;\n\n                par_sterea m_proj_parm;\n\n                inline base_sterea_ellipsoid(const Parameters& par)\n                    : base_t_fi<base_sterea_ellipsoid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>(*this, par) {}\n\n                // FORWARD(e_forward)  ellipsoid\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 cosc, sinc, cosl_, k;\n\n                    detail::gauss::gauss(m_proj_parm.en, lp_lon, lp_lat);\n                    sinc = sin(lp_lat);\n                    cosc = cos(lp_lat);\n                    cosl_ = cos(lp_lon);\n                    k = this->m_par.k0 * this->m_proj_parm.R2 / (1. + this->m_proj_parm.sinc0 * sinc + this->m_proj_parm.cosc0 * cosc * cosl_);\n                    xy_x = k * cosc * sin(lp_lon);\n                    xy_y = k * (this->m_proj_parm.cosc0 * sinc - this->m_proj_parm.sinc0 * cosc * cosl_);\n                }\n\n                // INVERSE(e_inverse)  ellipsoid\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 rho, c, sinc, cosc;\n\n                    xy_x /= this->m_par.k0;\n                    xy_y /= this->m_par.k0;\n                    if((rho = boost::math::hypot(xy_x, xy_y))) {\n                        c = 2. * atan2(rho, this->m_proj_parm.R2);\n                        sinc = sin(c);\n                        cosc = cos(c);\n                        lp_lat = asin(cosc * this->m_proj_parm.sinc0 + xy_y * sinc * this->m_proj_parm.cosc0 / rho);\n                        lp_lon = atan2(xy_x * sinc, rho * this->m_proj_parm.cosc0 * cosc -\n                            xy_y * this->m_proj_parm.sinc0 * sinc);\n                    } else {\n                        lp_lat = this->m_proj_parm.phic0;\n                        lp_lon = 0.;\n                    }\n                    detail::gauss::inv_gauss(m_proj_parm.en, lp_lon, lp_lat);\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"sterea_ellipsoid\";\n                }\n\n            };\n\n            // Oblique Stereographic Alternative\n            template <typename Parameters>\n            void setup_sterea(Parameters& par, par_sterea& proj_parm)\n            {\n                double R;\n\n                proj_parm.en = detail::gauss::gauss_ini(par.e, par.phi0, proj_parm.phic0, R);\n                proj_parm.sinc0 = sin(proj_parm.phic0);\n                proj_parm.cosc0 = cos(proj_parm.phic0);\n                proj_parm.R2 = 2. * R;\n            }\n\n        }} // namespace detail::sterea\n    #endif // doxygen\n\n    /*!\n        \\brief Oblique Stereographic Alternative 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         - Azimuthal\n         - Spheroid\n         - Ellipsoid\n        \\par Example\n        \\image html ex_sterea.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct sterea_ellipsoid : public detail::sterea::base_sterea_ellipsoid<Geographic, Cartesian, Parameters>\n    {\n        inline sterea_ellipsoid(const Parameters& par) : detail::sterea::base_sterea_ellipsoid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::sterea::setup_sterea(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 sterea_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<sterea_ellipsoid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        inline void sterea_init(detail::base_factory<Geographic, Cartesian, Parameters>& factory)\n        {\n            factory.add_to_factory(\"sterea\", new sterea_entry<Geographic, Cartesian, Parameters>);\n        }\n\n    } // namespace detail\n    // Create EPSG specializations\n    // (Proof of Concept, only for some)\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<2036, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef sterea_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=sterea +lat_0=46.5 +lon_0=-66.5 +k=0.999912 +x_0=2500000 +y_0=7500000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m\";\n        }\n    };\n\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<2171, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef sterea_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=sterea +lat_0=50.625 +lon_0=21.08333333333333 +k=0.9998 +x_0=4637000 +y_0=5647000 +ellps=krass +towgs84=33.4,-146.6,-76.3,-0.359,-0.053,0.844,-0.84 +units=m\";\n        }\n    };\n\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<2172, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef sterea_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=sterea +lat_0=53.00194444444445 +lon_0=21.50277777777778 +k=0.9998 +x_0=4603000 +y_0=5806000 +ellps=krass +towgs84=33.4,-146.6,-76.3,-0.359,-0.053,0.844,-0.84 +units=m\";\n        }\n    };\n\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<2173, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef sterea_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=sterea +lat_0=53.58333333333334 +lon_0=17.00833333333333 +k=0.9998 +x_0=3501000 +y_0=5999000 +ellps=krass +towgs84=33.4,-146.6,-76.3,-0.359,-0.053,0.844,-0.84 +units=m\";\n        }\n    };\n\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<2174, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef sterea_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=sterea +lat_0=51.67083333333333 +lon_0=16.67222222222222 +k=0.9998 +x_0=3703000 +y_0=5627000 +ellps=krass +towgs84=33.4,-146.6,-76.3,-0.359,-0.053,0.844,-0.84 +units=m\";\n        }\n    };\n\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<2200, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef sterea_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=sterea +lat_0=46.5 +lon_0=-66.5 +k=0.999912 +x_0=300000 +y_0=800000 +a=6378135 +b=6356750.304921594 +units=m\";\n        }\n    };\n\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<2290, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef sterea_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=sterea +lat_0=47.25 +lon_0=-63 +k=0.999912 +x_0=700000 +y_0=400000 +a=6378135 +b=6356750.304921594 +units=m\";\n        }\n    };\n\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<2291, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef sterea_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=sterea +lat_0=47.25 +lon_0=-63 +k=0.999912 +x_0=400000 +y_0=800000 +a=6378135 +b=6356750.304921594 +units=m\";\n        }\n    };\n\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<2292, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef sterea_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=sterea +lat_0=47.25 +lon_0=-63 +k=0.999912 +x_0=400000 +y_0=800000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m\";\n        }\n    };\n\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<2953, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef sterea_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=sterea +lat_0=46.5 +lon_0=-66.5 +k=0.999912 +x_0=2500000 +y_0=7500000 +ellps=GRS80 +units=m\";\n        }\n    };\n\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<2954, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef sterea_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=sterea +lat_0=47.25 +lon_0=-63 +k=0.999912 +x_0=400000 +y_0=800000 +ellps=GRS80 +units=m\";\n        }\n    };\n\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<3120, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef sterea_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=sterea +lat_0=50.625 +lon_0=21.08333333333333 +k=0.9998 +x_0=4637000 +y_0=5467000 +ellps=krass +towgs84=33.4,-146.6,-76.3,-0.359,-0.053,0.844,-0.84 +units=m\";\n        }\n    };\n\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<3328, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef sterea_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=sterea +lat_0=52.16666666666666 +lon_0=19.16666666666667 +k=0.999714 +x_0=500000 +y_0=500000 +ellps=krass +towgs84=33.4,-146.6,-76.3,-0.359,-0.053,0.844,-0.84 +units=m\";\n        }\n    };\n\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<22780, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef sterea_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=sterea +lat_0=34.2 +lon_0=39.15 +k=0.9995341 +x_0=0 +y_0=0 +a=6378249.2 +b=6356515 +units=m\";\n        }\n    };\n\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<28991, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef sterea_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=sterea +lat_0=52.15616055555555 +lon_0=5.38763888888889 +k=0.9999079 +x_0=0 +y_0=0 +ellps=bessel +units=m\";\n        }\n    };\n\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<28992, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef sterea_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=sterea +lat_0=52.15616055555555 +lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 +y_0=463000 +ellps=bessel +units=m\";\n        }\n    };\n\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<31600, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef sterea_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=sterea +lat_0=45.9 +lon_0=25.39246588888889 +k=0.9996667 +x_0=500000 +y_0=500000 +ellps=intl +units=m\";\n        }\n    };\n\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<31700, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef sterea_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=sterea +lat_0=46 +lon_0=25 +k=0.99975 +x_0=500000 +y_0=500000 +ellps=krass +units=m\";\n        }\n    };\n\n\n    #endif // doxygen\n\n}}} // namespace boost::geometry::projections\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_STEREA_HPP\n\n", "meta": {"hexsha": "81b3d3d436d0ba5514ee9c4b5d97c67eb3399882", "size": 16188, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/sterea.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/sterea.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/sterea.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": 41.0862944162, "max_line_length": 195, "alphanum_fraction": 0.6456634544, "num_tokens": 4317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.27732190407788976}}
{"text": "\n// Copyright 2018 Victor Smirnov\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#pragma once\n\n#include <memoria/core/integer/accumulator_common.hpp>\n#include <memoria/core/tools/uuid.hpp>\n\n#include <boost/multiprecision/integer.hpp>\n#include <boost/predef/other/endian.h>\n\n#include <ostream>\n\nnamespace memoria {\n\nnamespace bmp = boost::multiprecision;\n\nnamespace _ {\n\n    template <typename IntT>\n    using LimbType = std::remove_pointer_t<std::decay_t<decltype(std::declval<IntT>().backend().limbs())>>;\n\n    template <typename T, typename IntT, size_t N = sizeof(T) / sizeof(LimbType<IntT>)> struct UAccCvtHelper;\n\n    template <typename T, typename IntT>\n    struct UAccCvtHelper<T, IntT, 0>\n    {\n        template <typename UAcc, typename BmpInt>\n        static constexpr void to_acc(UAcc& acc, const BmpInt& value) {\n            acc.from_larger_limb_cppint(value);\n        }\n\n        template <typename UAcc, typename BmpInt>\n        static constexpr void to_bmp_int(const UAcc& acc, BmpInt& value) {\n            acc.to_larger_limb_cppint(value);\n        }\n    };\n\n\n    template <typename T, typename IntT>\n    struct UAccCvtHelper<T, IntT, 1>\n    {\n        template <typename UAcc, typename BmpInt>\n        static constexpr void to_acc(UAcc& acc, const BmpInt& value) {\n            acc.from_same_limb_cppint(value);\n        }\n\n        template <typename UAcc, typename BmpInt>\n        static constexpr void to_bmp_int(const UAcc& acc, BmpInt& value) {\n            acc.to_same_limb_cppint(value);\n        }\n    };\n\n    template <typename T, typename IntT>\n    struct UAccCvtHelper<T, IntT, 2>\n    {\n        template <typename UAcc, typename BmpInt>\n        static constexpr void to_acc(UAcc& acc, const BmpInt& value) {\n            acc.from_smaller_limb_cppint(value);\n        }\n\n        template <typename UAcc, typename BmpInt>\n        static constexpr void to_bmp_int(const UAcc& acc, BmpInt& value) {\n            acc.to_smaller_limb_cppint(value);\n        }\n    };\n\n\n    template <unsigned BitLength>\n    using UAccBmpInt = bmp::number<\n        bmp::cpp_int_backend<BitLength, BitLength, bmp::unsigned_magnitude, bmp::unchecked, void>\n    >;\n}\n\n\n\ntemplate <size_t BitLength>\nstruct UnsignedAccumulator {\n    using ValueT = uint64_t;\n\n    static constexpr size_t ValueTBitLength = sizeof(ValueT) * 8;\n\n    static constexpr size_t Size = (BitLength / ValueTBitLength) + (BitLength % ValueTBitLength > 0);\n\n    static constexpr size_t ByteSize = Size * sizeof (ValueT);\n\n    static constexpr size_t AccBitLength = BitLength;\n\n    ValueT value_[Size];\n\n    constexpr UnsignedAccumulator(): value_{} {}\n\n    constexpr UnsignedAccumulator(const UnsignedAccumulator& other) = default;\n\n    template <unsigned BmpBitLength>\n    constexpr UnsignedAccumulator(\n            const _::UAccBmpInt<BmpBitLength>& bmp_value\n    ): value_{}\n    {\n        static_assert(BitLength >= BmpBitLength, \"\");\n\n        _::UAccCvtHelper<ValueT, _::UAccBmpInt<BmpBitLength>>::to_acc(*this, bmp_value);\n    }\n\n    constexpr UnsignedAccumulator(ValueT v): value_{} {\n        value_[0] = v;\n    }\n\n    UnsignedAccumulator(const std::string& digits):\n        UnsignedAccumulator(_::UAccBmpInt<BitLength>(digits))\n    {}\n\n    template <size_t OtherBitLength>\n    constexpr UnsignedAccumulator(const UnsignedAccumulator<OtherBitLength>& other):value_{}\n    {\n        static_assert(BitLength >= OtherBitLength, \"\");\n        for (size_t c = 0; c < other.Size; c++)\n        {\n            value_[c] = other.value_[c];\n        }\n    }\n\n\n    constexpr UnsignedAccumulator(const UUID& uuid): value_{}\n    {\n        static_assert(BitLength >= 128, \"\");\n        value_[0] = uuid.lo();\n        value_[1] = uuid.hi();\n    }\n\n    UUID to_uuid() const\n    {\n        static_assert (BitLength >= 128, \"\");\n        return UUID(value_[1], value_[0]);\n    }\n\n    bool operator<(const UnsignedAccumulator& other) const\n    {\n        for (size_t c = Size - 1; c > 0; c--) {\n            if (value_[c] != other.value_[c]) {\n                return value_[c] < other.value_[c];\n            }\n        }\n\n        return value_[0] < other.value_[0];\n    }\n\n    bool operator<=(const UnsignedAccumulator& other) const\n    {\n        for (size_t c = Size - 1; c > 0; c--) {\n            if (value_[c] != other.value_[c]) {\n                return value_[c] < other.value_[c];\n            }\n        }\n\n        return value_[0] <= other.value_[0];\n    }\n\n    bool operator>(const UnsignedAccumulator& other) const\n    {\n        for (size_t c = Size - 1; c > 0; c--) {\n            if (value_[c] != other.value_[c]) {\n                return value_[c] > other.value_[c];\n            }\n        }\n\n        return value_[0] > other.value_[0];\n    }\n\n    bool operator>=(const UnsignedAccumulator& other) const\n    {\n        for (size_t c = Size - 1; c > 0; c--) {\n            if (value_[c] != other.value_[c]) {\n                return value_[c] > other.value_[c];\n            }\n        }\n\n        return value_[0] >= other.value_[0];\n    }\n\n    bool operator!=(const UnsignedAccumulator& other) const\n    {\n        for (size_t c = 0; c < Size; c++) {\n            if (value_[c] != other.value_[c]) {\n                return true;\n            }\n        }\n\n        return false;\n    }\n\n    MMA_NODISCARD bool operator==(const UnsignedAccumulator& other) const\n    {\n        for (size_t c = 0; c < Size; c++) {\n            if (value_[c] != other.value_[c]) {\n                return false;\n            }\n        }\n\n        return true;\n    }\n\n    template <unsigned BmpBitLength>\n    MMA_NODISCARD bool operator==(const _::UAccBmpInt<BmpBitLength>& other) const\n    {\n        UnsignedAccumulator tmp{other};\n        return tmp == *this;\n    }\n\n    UnsignedAccumulator& operator+=(const UnsignedAccumulator& other)\n    {\n        _::long_add_to(value_, other.value_, Size);\n        return *this;\n    }\n\n    UnsignedAccumulator& operator+=(ValueT other)\n    {\n        ValueT tmp[Size] {};\n        tmp[0] = other;\n\n        _::long_add_to(value_, tmp, Size);\n\n        return *this;\n    }\n\n    template <unsigned BmpBitLength>\n    UnsignedAccumulator& operator+=(const _::UAccBmpInt<BmpBitLength>& other)\n    {\n        UnsignedAccumulator tmp{other};\n        return (*this) += tmp;\n    }\n\n    UnsignedAccumulator& operator-=(const UnsignedAccumulator& other)\n    {\n        _::long_sub_from(value_, other.value_, Size);\n        return *this;\n    }\n\n    UnsignedAccumulator& operator-=(ValueT other)\n    {\n        ValueT tmp[Size] {};\n        tmp[0] = other;\n\n        _::long_sub_from(value_, tmp, Size);\n\n        return *this;\n    }\n\n    template <unsigned BmpBitLength>\n    UnsignedAccumulator& operator-=(const _::UAccBmpInt<BmpBitLength>& other)\n    {\n        UnsignedAccumulator tmp{other};\n        return (*this) -= tmp;\n    }\n\n    UnsignedAccumulator operator++()\n    {\n        UnsignedAccumulator tmp{*this};\n        tmp += 1;\n\n        return tmp;\n    }\n\n    UnsignedAccumulator& operator++(int)\n    {\n        return operator+=(1);\n    }\n\n    UnsignedAccumulator operator--()\n    {\n        UnsignedAccumulator tmp{*this};\n        tmp -= 1;\n        return tmp;\n    }\n\n    UnsignedAccumulator& operator--(int)\n    {\n        return operator-=(1);\n    }\n\n    UnsignedAccumulator operator+(const UnsignedAccumulator& other) const\n    {\n        UnsignedAccumulator tmp{};\n        _::long_add_to(tmp.value_, value_, other.value_, Size);\n\n        return tmp;\n    }\n\n    UnsignedAccumulator operator+(ValueT other) const\n    {\n        UnsignedAccumulator result{};\n        ValueT y[Size] = {};\n        y[0] = other;\n\n        _::long_add_to(result.value_, value_, y, Size);\n        return result;\n    }\n\n\n    UnsignedAccumulator operator-(const UnsignedAccumulator& other) const\n    {\n        UnsignedAccumulator tmp{};\n        _::long_sub_from(tmp.value_, value_, other.value_, Size);\n        return tmp;\n    }\n\n\n    UnsignedAccumulator operator-(ValueT other) const\n    {\n        UnsignedAccumulator result{};\n        ValueT y[Size] = {};\n        y[0] = other;\n\n        _::long_sub_from(result.value_, value_, y, Size);\n        return result;\n    }\n\n\n    UnsignedAccumulator& operator=(const UnsignedAccumulator& other) = default;\n\n    UnsignedAccumulator& operator=(const ValueT& other)\n    {\n        std::memset(value_, 0, BitLength / 8);\n        this->value_[0] = other;\n        return *this;\n    }\n\n    template <unsigned BmpBitLength>\n    UnsignedAccumulator operator=(const _::UAccBmpInt<BmpBitLength>& other)\n    {\n        static_assert(BmpBitLength <= BitLength, \"\");\n        std::memset(value_, 0, BitLength / 8);\n        _::UAccCvtHelper<ValueT, _::UAccBmpInt<BmpBitLength>>::to_acc(*this, other);\n        return *this;\n    }\n\n    template <unsigned BmpBitLength>\n    operator _::UAccBmpInt<BmpBitLength>() const\n    {\n        _::UAccBmpInt<BmpBitLength> bmp_value;\n        _::UAccCvtHelper<ValueT, _::UAccBmpInt<BmpBitLength>>::to_bmp_int(*this, bmp_value);\n\n        return bmp_value;\n    }\n\n\n    _::UAccBmpInt<BitLength> to_bmp() const\n    {\n        _::UAccBmpInt<BitLength> bmp_value;\n        _::UAccCvtHelper<ValueT, _::UAccBmpInt<BitLength>>::to_bmp_int(*this, bmp_value);\n        return bmp_value;\n    }\n\n    template <size_t TgtBitLength>\n    std::enable_if_t<TgtBitLength >= BitLength, UnsignedAccumulator<TgtBitLength>> cast_to() const\n    {\n        UnsignedAccumulator<TgtBitLength> tgt{};\n\n        for (size_t c = 0; c < Size; c++)\n        {\n            tgt.value_[c] = value_[c];\n        }\n\n        return tgt;\n    }\n\n    template <size_t TgtBitLength>\n    std::enable_if_t<TgtBitLength < BitLength, UnsignedAccumulator<TgtBitLength>> cast_to() const\n    {\n        UnsignedAccumulator<TgtBitLength> tgt{};\n\n        for (size_t c = 0; c < UnsignedAccumulator<TgtBitLength>::Size; c++)\n        {\n            tgt.value_[c] = value_[c];\n        }\n\n        return tgt;\n    }\n\nprivate:\n    template <typename T, typename IntT, size_t N> friend struct _::UAccCvtHelper;\n\n    template <unsigned BmpBitLength>\n    constexpr void from_same_limb_cppint(const _::UAccBmpInt<BmpBitLength>& bmp_value)\n    {\n        auto size = bmp_value.backend().size();\n        const auto* limbs = bmp_value.backend().limbs();\n\n        for (size_t c = 0; c < size; c++)\n        {\n            value_[c] = limbs[c];\n        }\n    }\n\n\n    template <unsigned BmpBitLength>\n    constexpr void to_same_limb_cppint(_::UAccBmpInt<BmpBitLength>& bmp_value) const\n    {\n        bmp_value.backend().resize(Size, Size);\n        auto size = bmp_value.backend().size();\n        auto* limbs = bmp_value.backend().limbs();\n\n        for (size_t c = 0; c < size; c++)\n        {\n            limbs[c] = value_[c];\n        }\n\n        bmp_value.backend().normalize();\n    }\n\n\n    template <unsigned BmpBitLength>\n    constexpr void to_smaller_limb_cppint(_::UAccBmpInt<BmpBitLength>& bmp_value) const\n    {\n        bmp_value.backend().resize(Size * 2, Size * 2);\n\n        unsigned size = bmp_value.backend().size();\n        auto* limbs = bmp_value.backend().limbs();\n\n        for (unsigned c = 0; c < size; c += 2)\n        {\n#ifdef BOOST_LITTLE_ENDIAN\n            limbs[c]     = value_[c / 2] & 0xFFFFFFFFull;\n            limbs[c + 1] = (value_[c / 2] >> 32) & 0xFFFFFFFFull;\n#else\n            limbs[c + 1] = value_[c / 2] & 0xFFFFFFFFull;\n            limbs[c]     = (value_[c / 2] >> 32) & 0xFFFFFFFFull;\n#endif\n        }\n\n        bmp_value.backend().normalize();\n    }\n\n\n    template <unsigned BmpBitLength>\n    constexpr void to_larger_limb_cppint(_::UAccBmpInt<BmpBitLength>& bmp_value) const\n    {\n        using LimbT = _::LimbType<_::UAccBmpInt<BmpBitLength>>;\n\n        bmp_value.backend().resize(Size / 2 , Size / 2);\n        auto* limbs = bmp_value.backend().limbs();\n\n        for (unsigned c = 0; c < Size; c += 2)\n        {\n            LimbT v0 = value_[c];\n            LimbT v1 = value_[c + 1];\n\n#ifdef BOOST_LITTLE_ENDIAN\n            limbs[c / 2] = v0 | (v1 << 64);\n#else\n            limbs[c / 2] = v1 | (v0 << 64);\n#endif\n        }\n\n        bmp_value.backend().normalize();\n    }\n\n\n\n    template <unsigned BmpBitLength>\n    constexpr void from_smaller_limb_cppint(const _::UAccBmpInt<BmpBitLength>& bmp_value)\n    {\n        unsigned size = bmp_value.backend().size();\n        const auto* limbs = bmp_value.backend().limbs();\n\n        for (size_t c = 0; c < size; c += 2)\n        {\n            ValueT v0 = limbs[c];\n            ValueT v1 = limbs[c + 1];\n\n#ifdef BOOST_LITTLE_ENDIAN\n            value_[c / 2] = (v1 << 32) | v0;\n#else\n            value_[c / 2] = (v0 << 32) | v1;\n#endif\n        }\n\n        if (size & 0x1)\n        {\n#ifdef BOOST_LITTLE_ENDIAN\n            value_[size / 2] = limbs[size - 1];\n#else\n            value_[size / 2] = ((ValueT)limbs[size - 1]) << 32;\n#endif\n        }\n    }\n\n\n    template <unsigned BmpBitLength>\n    constexpr void from_larger_limb_cppint(const _::UAccBmpInt<BmpBitLength>& bmp_value)\n    {\n        unsigned size = bmp_value.backend().size();\n        const auto* limbs = bmp_value.backend().limbs();\n\n        using LimbT = _::LimbType<_::UAccBmpInt<BmpBitLength>>;\n        for (size_t c = 0; c < Size; c += 2)\n        {\n            LimbT vv = limbs[c / 2];\n\n#ifdef BOOST_LITTLE_ENDIAN\n            value_[c] = vv;\n            value_[c + 1] = vv >> 64;\n#else\n            value_[c + 1] = vv;\n            value_[c] = vv >> 64;\n#endif\n        }\n\n        if (Size & 0x01)\n        {\n            value_[Size - 1] = limbs[size - 1];\n        }\n    }\n};\n\ntemplate <size_t BitLength>\nstd::ostream& operator<<(std::ostream& out, const UnsignedAccumulator<BitLength>& other) {\n    out << other.to_bmp();\n    return out;\n}\n\ntemplate <size_t BitLength>\nstd::istream& operator>>(std::istream& in, UnsignedAccumulator<BitLength>& other) {\n    _::UAccBmpInt<BitLength> bmp_int;\n    in >> bmp_int;\n    other = bmp_int;\n    return in;\n}\n\n\n}\n\nnamespace fmt {\n\ntemplate <size_t BitLength>\nstruct formatter<memoria::UnsignedAccumulator<BitLength>> {\n    constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); }\n\n    template <typename FormatContext>\n    auto format(const memoria::UnsignedAccumulator<BitLength>& d, FormatContext& ctx) {\n        return format_to(ctx.out(), \"{}\", d.to_bmp().str());\n    }\n};\n\ntemplate <size_t BitLength>\nstruct formatter<memoria::_::UAccBmpInt<BitLength>> {\n    constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); }\n\n    template <typename FormatContext>\n    auto format(const memoria::_::UAccBmpInt<BitLength>& d, FormatContext& ctx)\n    {\n        return format_to(ctx.out(), \"{}\", d.str());\n    }\n};\n\ntemplate <>\nstruct formatter<boost::multiprecision::uint256_t> {\n    constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); }\n\n    template <typename FormatContext>\n    auto format(const boost::multiprecision::uint256_t& d, FormatContext& ctx)\n    {\n        return format_to(ctx.out(), \"{}\", d.str());\n    }\n};\n\ntemplate <\n        unsigned MinBits,\n        unsigned MaxBits,\n        boost::multiprecision::cpp_integer_type SignType,\n        boost::multiprecision::cpp_int_check_type Checked,\n        class Allocator\n>\nstruct formatter<\n        boost::multiprecision::number<\n            boost::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>\n        >\n> {\n\n    using IntT = boost::multiprecision::number<\n        boost::multiprecision::cpp_int_backend<\n            MinBits, MaxBits, SignType, Checked, Allocator\n        >\n    >;\n\n    constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); }\n\n    template <typename FormatContext>\n    auto format(const IntT& d, FormatContext& ctx)\n    {\n        return format_to(ctx.out(), \"{}\", d.str());\n    }\n};\n\n}\n", "meta": {"hexsha": "2e8b65ba6f675340c562f4b2a1b3814eb521900c", "size": 16118, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/memoria/core/integer/big_accumulator.hpp", "max_stars_repo_name": "victor-smirnov/memoria", "max_stars_repo_head_hexsha": "c36a957c63532176b042b411b1646c536e71a658", "max_stars_repo_licenses": ["BSL-1.0", "Apache-2.0", "OLDAP-2.8", "BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-30T16:54:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T15:48:17.000Z", "max_issues_repo_path": "include/memoria/core/integer/big_accumulator.hpp", "max_issues_repo_name": "victor-smirnov/memoria", "max_issues_repo_head_hexsha": "c36a957c63532176b042b411b1646c536e71a658", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0", "OLDAP-2.8", "BSD-3-Clause"], "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/memoria/core/integer/big_accumulator.hpp", "max_forks_repo_name": "victor-smirnov/memoria", "max_forks_repo_head_hexsha": "c36a957c63532176b042b411b1646c536e71a658", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0", "OLDAP-2.8", "BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-14T15:15:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T11:26:56.000Z", "avg_line_length": 26.5098684211, "max_line_length": 109, "alphanum_fraction": 0.6001985358, "num_tokens": 4291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.27732190407788976}}
{"text": "// Copyright (c) 2020 CNES\n//\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n#include <Eigen/Dense>\n#include \"astronomic_angle.hpp\"\n#include \"wave.hpp\"\n#include \"math.hpp\"\n\nstd::string Wave::name() const {\n  switch (ident_) {\n    case Wave::kO1:\n      return \"O1\";\n    case Wave::kP1:\n      return \"P1\";\n    case Wave::kK1:\n      return \"K1\";\n    case Wave::k2N2:\n      return \"2N2\";\n    case Wave::kMu2:\n      return \"Mu2\";\n    case Wave::kN2:\n      return \"N2\";\n    case Wave::kNu2:\n      return \"Nu2\";\n    case Wave::kM2:\n      return \"M2\";\n    case Wave::kL2:\n      return \"L2\";\n    case Wave::kT2:\n      return \"T2\";\n    case Wave::kS2:\n      return \"S2\";\n    case Wave::kK2:\n      return \"K2\";\n    case Wave::kM4:\n      return \"M4\";\n    case Wave::kS1:\n      return \"S1\";\n    case Wave::kQ1:\n      return \"Q1\";\n    case Wave::kMm:\n      return \"Mm\";\n    case Wave::kMf:\n      return \"Mf\";\n    case Wave::kMtm:\n      return \"Mtm\";\n    case Wave::kMsqm:\n      return \"Msqm\";\n    case Wave::kEps2:\n      return \"Eps2\";\n    case Wave::kLambda2:\n      return \"Lambda2\";\n    case Wave::kEta2:\n      return \"Eta2\";\n    case Wave::k2Q1:\n      return \"2Q1\";\n    case Wave::kSigma1:\n      return \"Sigma1\";\n    case Wave::kRho1:\n      return \"Rho1\";\n    case Wave::kM11:\n      return \"M11\";\n    case Wave::kM12:\n      return \"M12\";\n    case Wave::kChi1:\n      return \"Chi1\";\n    case Wave::kPi1:\n      return \"Pi1\";\n    case Wave::kPhi1:\n      return \"Phi1\";\n    case Wave::kTheta1:\n      return \"Theta1\";\n    case Wave::kJ1:\n      return \"J1\";\n    case Wave::kOO1:\n      return \"OO1\";\n    case Wave::kM3:\n      return \"M3\";\n    case Wave::kM6:\n      return \"M6\";\n    case Wave::kMN4:\n      return \"MN4\";\n    case Wave::kMS4:\n      return \"MS4\";\n    case Wave::kN4:\n      return \"N4\";\n    case Wave::kR2:\n      return \"R2\";\n    case Wave::kR4:\n      return \"R4\";\n    case Wave::kS4:\n      return \"S4\";\n    case Wave::kMNS2:\n      return \"MNS2\";\n    case Wave::kM13:\n      return \"M13\";\n    case Wave::kMK4:\n      return \"MK4\";\n    case Wave::kSN4:\n      return \"SN4\";\n    case Wave::kSK4:\n      return \"SK4\";\n    case Wave::k2MN6:\n      return \"2MN6\";\n    case Wave::k2MS6:\n      return \"2MS6\";\n    case Wave::k2MK6:\n      return \"2MK6\";\n    case Wave::kMSN6:\n      return \"MSN6\";\n    case Wave::k2SM6:\n      return \"2SM6\";\n    case Wave::kMSK6:\n      return \"MSK6\";\n    case Wave::kMP1:\n      return \"MP1\";\n    case Wave::k2SM2:\n      return \"2SM2\";\n    case Wave::kPsi1:\n      return \"Psi1\";\n    case Wave::k2MS2:\n      return \"2MS2\";\n    case Wave::kMKS2:\n      return \"MKS2\";\n    case Wave::k2MN2:\n      return \"2MN2\";\n    case Wave::kMSN2:\n      return \"MSN2\";\n    case Wave::kMO3:\n      return \"MO3\";\n    case Wave::k2MK3:\n      return \"2MK3\";\n    case Wave::kMK3:\n      return \"MK3\";\n    case Wave::kS6:\n      return \"S6\";\n    case Wave::kM8:\n      return \"M8\";\n    case Wave::kMSf:\n      return \"MSf\";\n    case Wave::kSsa:\n      return \"Ssa\";\n    case Wave::kSa:\n      return \"Sa\";\n    default:\n      return \"unknown\";\n  }\n}\n\nstd::vector<std::string> WaveTable::known_constituents() {\n  return {\"O1\",   \"P1\",   \"K1\",   \"2N2\",  \"Mu2\",     \"N2\",   \"Nu2\",    \"M2\",\n          \"L2\",   \"T2\",   \"S2\",   \"K2\",   \"M4\",      \"S1\",   \"Q1\",     \"Mm\",\n          \"Mf\",   \"Mtm\",  \"Msqm\", \"Eps2\", \"Lambda2\", \"Eta2\", \"2Q1\",    \"Sigma1\",\n          \"Rho1\", \"M11\",  \"M12\",  \"Chi1\", \"Pi1\",     \"Phi1\", \"Theta1\", \"J1\",\n          \"OO1\",  \"M3\",   \"M6\",   \"MN4\",  \"MS4\",     \"N4\",   \"R2\",     \"R4\",\n          \"S4\",   \"MNS2\", \"M13\",  \"MK4\",  \"SN4\",     \"SK4\",  \"2MN6\",   \"2MS6\",\n          \"2MK6\", \"MSN6\", \"2SM6\", \"MSK6\", \"MP1\",     \"2SM2\", \"Psi1\",   \"2MS2\",\n          \"MKS2\", \"2MN2\", \"MSN2\", \"MO3\",  \"2MK3\",    \"MK3\",  \"S6\",     \"M8\",\n          \"MSf\",  \"Ssa\",  \"Sa\"};\n}\n\nstatic std::shared_ptr<Wave> wave_factory(const std::string& name) {\n  if (name == \"O1\") {\n    return std::shared_ptr<Wave>(new O1());\n  } else if (name == \"P1\") {\n    return std::shared_ptr<Wave>(new P1());\n  } else if (name == \"K1\") {\n    return std::shared_ptr<Wave>(new K1());\n  } else if (name == \"2N2\") {\n    return std::shared_ptr<Wave>(new _2N2());\n  } else if (name == \"Mu2\") {\n    return std::shared_ptr<Wave>(new Mu2());\n  } else if (name == \"N2\") {\n    return std::shared_ptr<Wave>(new N2());\n  } else if (name == \"Nu2\") {\n    return std::shared_ptr<Wave>(new Nu2());\n  } else if (name == \"M2\") {\n    return std::shared_ptr<Wave>(new M2());\n  } else if (name == \"L2\") {\n    return std::shared_ptr<Wave>(new L2());\n  } else if (name == \"T2\") {\n    return std::shared_ptr<Wave>(new T2());\n  } else if (name == \"S2\") {\n    return std::shared_ptr<Wave>(new S2());\n  } else if (name == \"K2\") {\n    return std::shared_ptr<Wave>(new K2());\n  } else if (name == \"M4\") {\n    return std::shared_ptr<Wave>(new M4());\n  } else if (name == \"S1\") {\n    return std::shared_ptr<Wave>(new S1());\n  } else if (name == \"Q1\") {\n    return std::shared_ptr<Wave>(new Q1());\n  } else if (name == \"Mm\") {\n    return std::shared_ptr<Wave>(new Mm());\n  } else if (name == \"Mf\") {\n    return std::shared_ptr<Wave>(new Mf());\n  } else if (name == \"Mtm\") {\n    return std::shared_ptr<Wave>(new Mtm());\n  } else if (name == \"Msqm\") {\n    return std::shared_ptr<Wave>(new Msqm());\n  } else if (name == \"Eps2\") {\n    return std::shared_ptr<Wave>(new Eps2());\n  } else if (name == \"Lambda2\") {\n    return std::shared_ptr<Wave>(new Lambda2());\n  } else if (name == \"Eta2\") {\n    return std::shared_ptr<Wave>(new Eta2());\n  } else if (name == \"2Q1\") {\n    return std::shared_ptr<Wave>(new _2Q1());\n  } else if (name == \"Sigma1\") {\n    return std::shared_ptr<Wave>(new Sigma1());\n  } else if (name == \"Rho1\") {\n    return std::shared_ptr<Wave>(new Rho1());\n  } else if (name == \"M11\") {\n    return std::shared_ptr<Wave>(new M11());\n  } else if (name == \"M12\") {\n    return std::shared_ptr<Wave>(new M12());\n  } else if (name == \"Chi1\") {\n    return std::shared_ptr<Wave>(new Chi1());\n  } else if (name == \"Pi1\") {\n    return std::shared_ptr<Wave>(new Pi1());\n  } else if (name == \"Phi1\") {\n    return std::shared_ptr<Wave>(new Phi1());\n  } else if (name == \"Theta1\") {\n    return std::shared_ptr<Wave>(new Theta1());\n  } else if (name == \"J1\") {\n    return std::shared_ptr<Wave>(new J1());\n  } else if (name == \"OO1\") {\n    return std::shared_ptr<Wave>(new OO1());\n  } else if (name == \"M3\") {\n    return std::shared_ptr<Wave>(new M3());\n  } else if (name == \"M6\") {\n    return std::shared_ptr<Wave>(new M6());\n  } else if (name == \"MN4\") {\n    return std::shared_ptr<Wave>(new MN4());\n  } else if (name == \"MS4\") {\n    return std::shared_ptr<Wave>(new MS4());\n  } else if (name == \"N4\") {\n    return std::shared_ptr<Wave>(new N4());\n  } else if (name == \"R2\") {\n    return std::shared_ptr<Wave>(new R2());\n  } else if (name == \"R4\") {\n    return std::shared_ptr<Wave>(new R4());\n  } else if (name == \"S4\") {\n    return std::shared_ptr<Wave>(new S4());\n  } else if (name == \"MNS2\") {\n    return std::shared_ptr<Wave>(new MNS2());\n  } else if (name == \"M13\") {\n    return std::shared_ptr<Wave>(new M13());\n  } else if (name == \"MK4\") {\n    return std::shared_ptr<Wave>(new MK4());\n  } else if (name == \"SN4\") {\n    return std::shared_ptr<Wave>(new SN4());\n  } else if (name == \"SK4\") {\n    return std::shared_ptr<Wave>(new SK4());\n  } else if (name == \"2MN6\") {\n    return std::shared_ptr<Wave>(new _2MN6());\n  } else if (name == \"2MS6\") {\n    return std::shared_ptr<Wave>(new _2MS6());\n  } else if (name == \"2MK6\") {\n    return std::shared_ptr<Wave>(new _2MK6());\n  } else if (name == \"MSN6\") {\n    return std::shared_ptr<Wave>(new MSN6());\n  } else if (name == \"2SM6\") {\n    return std::shared_ptr<Wave>(new _2SM6());\n  } else if (name == \"MSK6\") {\n    return std::shared_ptr<Wave>(new MSK6());\n  } else if (name == \"MP1\") {\n    return std::shared_ptr<Wave>(new MP1());\n  } else if (name == \"2SM2\") {\n    return std::shared_ptr<Wave>(new _2SM2());\n  } else if (name == \"Psi1\") {\n    return std::shared_ptr<Wave>(new Psi1());\n  } else if (name == \"2MS2\") {\n    return std::shared_ptr<Wave>(new _2MS2());\n  } else if (name == \"MKS2\") {\n    return std::shared_ptr<Wave>(new MKS2());\n  } else if (name == \"2MN2\") {\n    return std::shared_ptr<Wave>(new _2MN2());\n  } else if (name == \"MSN2\") {\n    return std::shared_ptr<Wave>(new MSN2());\n  } else if (name == \"MO3\") {\n    return std::shared_ptr<Wave>(new MO3());\n  } else if (name == \"2MK3\") {\n    return std::shared_ptr<Wave>(new _2MK3());\n  } else if (name == \"MK3\") {\n    return std::shared_ptr<Wave>(new MK3());\n  } else if (name == \"S6\") {\n    return std::shared_ptr<Wave>(new S6());\n  } else if (name == \"M8\") {\n    return std::shared_ptr<Wave>(new M8());\n  } else if (name == \"MSf\") {\n    return std::shared_ptr<Wave>(new MSf());\n  } else if (name == \"Ssa\") {\n    return std::shared_ptr<Wave>(new Ssa());\n  } else if (name == \"Sa\") {\n    return std::shared_ptr<Wave>(new Sa());\n  }\n\n  throw std::runtime_error(\"The tidal wave is unknown: \" + name);\n}\n\nWaveTable::WaveTable(const std::vector<std::string>& waves) {\n  const auto& wave_list = waves.empty() ? known_constituents() : waves;\n  for (auto& item : wave_list) {\n    waves_.emplace_back(wave_factory(item));\n  }\n}\n\nvoid Wave::nodal_g(const AstronomicAngle& a) {\n  v_ = argument_[0] * a.t() + argument_[1] * a.s() + argument_[2] * a.h() +\n       argument_[3] * a.p() + argument_[5] * a.p1() +\n       argument_[6] * pi_2<double>();\n  u_ = argument_[7] * a.xi() + argument_[8] * a.nu() +\n       argument_[9] * a.nuprim() + argument_[10] * a.nusec();\n}\n\nEigen::VectorXcd WaveTable::harmonic_analysis(\n    const Eigen::Ref<const Eigen::VectorXd>& h,\n    const Eigen::Ref<const Eigen::MatrixXd>& f,\n    const Eigen::Ref<const Eigen::MatrixXd>& vu) {\n  if (f.rows() != vu.rows() || f.cols() != vu.cols()) {\n    throw std::invalid_argument(\n        \"f and vu could not be broadcast together with shape (\" +\n        std::to_string(f.rows()) + \", \" + std::to_string(f.cols()) + \") (\" +\n        std::to_string(vu.rows()) + \", \" + std::to_string(vu.cols()) + \")\");\n  }\n\n  if (h.rows() != f.cols() || h.rows() != vu.cols()) {\n    throw std::invalid_argument(\n        \"f, vu could not be broadcast with h with shape (\" +\n        std::to_string(f.rows()) + \", \" + std::to_string(f.cols()) + \") (\" +\n        std::to_string(h.cols()) + \")\");\n  }\n  auto w_size = f.rows();\n  auto result = Eigen::VectorXcd(w_size);\n\n  if (h.hasNaN()) {\n    result.fill(std::complex<double>(std::numeric_limits<double>::quiet_NaN(),\n                                     std::numeric_limits<double>::quiet_NaN()));\n    return result;\n  }\n\n  auto H = Eigen::MatrixXd(w_size << 1, h.rows());\n\n  H.topRows(w_size) = f.array() * vu.array().cos();\n  H.bottomRows(w_size) = f.array() * vu.array().sin();\n\n  auto solution = ((H * H.transpose()).inverse() * H) * h;\n  result.real() = solution.topRows(w_size);\n  result.imag() = solution.bottomRows(w_size);\n\n  return result;\n}", "meta": {"hexsha": "0170209633f8cd4f4ac6b9ae3ccaa7bc85d21242", "size": 10944, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pytide/core/wave.cpp", "max_stars_repo_name": "evomassiny/pangeo-pytide", "max_stars_repo_head_hexsha": "34e3b24fe2b4911bbb444f7d3c2f9024fa361aee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-09-27T03:14:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T20:35:38.000Z", "max_issues_repo_path": "src/pytide/core/wave.cpp", "max_issues_repo_name": "evomassiny/pangeo-pytide", "max_issues_repo_head_hexsha": "34e3b24fe2b4911bbb444f7d3c2f9024fa361aee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2019-09-26T14:51:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T05:59:43.000Z", "max_forks_repo_path": "src/pytide/core/wave.cpp", "max_forks_repo_name": "evomassiny/pangeo-pytide", "max_forks_repo_head_hexsha": "34e3b24fe2b4911bbb444f7d3c2f9024fa361aee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-09-26T13:39:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T22:12:05.000Z", "avg_line_length": 30.9152542373, "max_line_length": 80, "alphanum_fraction": 0.5451388889, "num_tokens": 3709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2773218980182812}}
{"text": "#include <iostream>\r\n#include <map>\r\n#include <sstream>\r\n#include <fstream>\r\n#include <glog/logging.h>\r\n#include <omp.h>\r\n#include <float.h>\r\n#include <math.h>\r\n\r\n#include <HFTrain.h>\r\n\r\n#include <boost/math/constants/constants.hpp>\r\n\r\nvoid HFTrain::getTrainSet(TrainSet &train_set, int &number_of_classes, int &feature_vector_length)\r\n{\t\t\t    \r\n\r\n    std::ifstream finput(input_file_.c_str(), std::ios::in | std::ios::binary);\r\n    CHECK(finput) << \"Could not open file \" << input_file_;\r\n\t\r\n    //read number of classes and feature vector length\r\n    finput.read((char*)&number_of_classes, sizeof(int));\r\n    finput.read((char*)&feature_vector_length, sizeof(int));\r\n\r\n    train_set.resize(0);    \r\n\r\n    int num_vec = 0;\r\n    while(true){\r\n\r\n        int class_no;\r\n        float yaw, pitch, roll, x, y, z;\r\n\r\n        finput.read((char*)&class_no,   sizeof(int));\r\n        if(finput.eof())\r\n            break;\r\n\r\n        finput.read((char*)&yaw,        sizeof(float));\r\n        finput.read((char*)&pitch,      sizeof(float));\r\n        finput.read((char*)&roll,       sizeof(float));\r\n        finput.read((char*)&x,          sizeof(float));\r\n        finput.read((char*)&y,          sizeof(float));\r\n        finput.read((char*)&z,          sizeof(float));\r\n\r\n        train_set.push_back(new TrainSample());\r\n        train_set.back()->class_no = class_no;\r\n        train_set.back()->node = 0;\r\n        Eigen::VectorXf dof(6);\r\n        dof(0) = yaw;\r\n        dof(1) = pitch;\r\n        dof(2) = roll;\r\n        dof(3) = x;\r\n        dof(4) = y;\r\n        dof(5) = z;\r\n        train_set.back()->dof = dof;\r\n\r\n        Eigen::VectorXf feature_vector(feature_vector_length);\r\n        for(int i=0; i<feature_vector_length; ++i){\r\n            float f;\r\n            finput.read((char*)&f, sizeof(float));\r\n            feature_vector(i) = f;\r\n        }\r\n\r\n        train_set.back()->feature_vector = feature_vector;\r\n\r\n    }\r\n\r\n    finput.close();\r\n}\r\n\r\n\r\n\r\n//get random train_samples from training set and put them to the front\r\nvoid HFTrain::suffle_training_set(TrainSet &train_set, int train_samples, std::vector<int> &samples_per_class){\r\n\r\n    samples_per_class.resize(number_of_classes_);\r\n    for(int i=0; i<train_samples; ++i){\r\n        int k = rand() % (train_set.size() - i) + i;\r\n        TrainSample *ts;\r\n        ts = train_set[i];\r\n        train_set[i] = train_set[k];\r\n        train_set[k] = ts;\r\n        samples_per_class[train_set[i]->class_no]++;\r\n    }\r\n}\r\n\r\n\r\n//takes input last leaf_id+1, returns the changed value, added the current leaves\r\nvoid HFTrain::make_leafs(TrainSet &train_set, int train_samples, const std::vector<int> &samples_per_class, int &leaf_id){\r\n\r\n\r\n    float degrees_bin_size = 15.0f;\r\n    float coordinates_bin_size = 0.03; //1cm\r\n\r\n    float pi = boost::math::constants::pi<float>();\r\n\r\n    boost::unordered_map<TreeNode*, std::vector<int> > node_class_samples;\r\n    boost::unordered_map<TreeNode*, std::vector< std::vector<Eigen::VectorXf> > > node_class_hough_votes;\r\n//    boost::unordered_map<TreeNode*, std::vector<Hough3DMap> > node_class_houghmap;\r\n//    boost::unordered_map<TreeNode*, std::vector<std::vector<float> > > node_class_mean;\r\n//    boost::unordered_map<TreeNode*, std::vector<std::vector<float> > > node_class_std;\r\n\r\n    omp_set_num_threads(threads_per_tree_);\r\n\r\n#pragma omp parallel\r\n    {\r\n        boost::unordered_map<TreeNode*, std::vector<int> > node_class_samples_local;\r\n        boost::unordered_map<TreeNode*, std::vector< std::vector<Eigen::VectorXf> > > node_class_hough_votes_local;\r\n//        boost::unordered_map<TreeNode*, std::vector<Hough3DMap> > node_class_houghmap_local;\r\n//        boost::unordered_map<TreeNode*, std::vector<std::vector<float> > > node_class_mean_local;\r\n\r\n        #pragma omp for schedule(dynamic)\r\n        for(int i=0; i<train_samples; ++i){\r\n            if(train_set[i]->node->leaf){\r\n                //classification info\r\n                TreeNode *cur_node = train_set[i]->node;\r\n                if(node_class_samples_local.count(cur_node)){\r\n                    node_class_samples_local[cur_node][train_set[i]->class_no]++;\r\n                } else {\r\n                    node_class_samples_local[cur_node] = std::vector<int>(number_of_classes_, 0);\r\n                    node_class_samples_local[cur_node][train_set[i]->class_no]++;\r\n                }\r\n                if(!node_class_hough_votes_local.count(cur_node))\r\n                    node_class_hough_votes_local[cur_node] = std::vector<std::vector<Eigen::VectorXf> >(number_of_classes_);\r\n\r\n                node_class_hough_votes_local[cur_node][train_set[i]->class_no].push_back(train_set[i]->dof);\r\n\r\n            }\r\n        }\r\n\r\n        #pragma omp critical\r\n        {\r\n            //concatenate classification info\r\n            for(boost::unordered_map<TreeNode*, std::vector<int> >::iterator it = node_class_samples_local.begin();\r\n                it != node_class_samples_local.end(); ++it){\r\n                if(node_class_samples.count(it->first)){\r\n                    for(int i=0; i<number_of_classes_; ++i)\r\n                        node_class_samples[it->first][i] += (it->second)[i];\r\n                } else {\r\n                    node_class_samples[it->first] = it->second;\r\n                }\r\n\r\n            }\r\n\r\n            for(boost::unordered_map<TreeNode*, std::vector< std::vector<Eigen::VectorXf> > >::iterator it = node_class_hough_votes_local.begin();\r\n                it != node_class_hough_votes_local.end(); ++it){\r\n\r\n                TreeNode *cur_node = it->first;\r\n                if(!node_class_hough_votes.count(cur_node))\r\n                    node_class_hough_votes[cur_node] = std::vector<std::vector<Eigen::VectorXf> >(number_of_classes_);\r\n                for(int c=0; c<number_of_classes_; ++c)\r\n                    node_class_hough_votes[cur_node][c].insert(node_class_hough_votes[cur_node][c].end(),\r\n                                                               node_class_hough_votes_local[cur_node][c].begin(),\r\n                                                               node_class_hough_votes_local[cur_node][c].end());\r\n\r\n\r\n            }\r\n\r\n        } //critical\r\n\r\n    } //parallel\r\n\r\n    //normalize class probabilities and calc mean\r\n    for(boost::unordered_map<TreeNode*, std::vector<int> >::iterator it = node_class_samples.begin();\r\n        it != node_class_samples.end(); ++it){\r\n\r\n        TreeNode *cur_node = it->first;\r\n        //save id and increase id counter\r\n        cur_node->leaf_id = leaf_id++;\r\n        std::vector<int> *cur_class_samples = &(node_class_samples[cur_node]);\r\n        int total_samples = 0;\r\n        for(int i=0; i<number_of_classes_; ++i)\r\n            total_samples += (*cur_class_samples)[i];\r\n\r\n        //normalize class distribution according to\r\n        //initial number of samples per class\r\n        cur_node->class_prob.resize(number_of_classes_);\r\n        for(int c=0; c<number_of_classes_; ++c){\r\n            float norm = 0;\r\n            for(int i=0; i<number_of_classes_; ++i)\r\n                norm += (float)samples_per_class[c]/(float)samples_per_class[i]*(float)(*cur_class_samples)[i];\r\n            cur_node->class_prob[c] = (float)(*cur_class_samples)[c] / norm ;\r\n        }\r\n\r\n//        //get mean by division with total samples\r\n//        std::vector<std::vector<float> > *cur_node_class_mean = &(node_class_mean[cur_node]);\r\n//        for(int c=0; c<number_of_classes_; ++c){\r\n//            int cur_samples = node_class_samples[cur_node][c];\r\n//            if(cur_samples > 0){\r\n//                for(int f=0; f<feature_vector_length_; ++f)\r\n//                        (*cur_node_class_mean)[c][f] /= (float)cur_samples;\r\n//            }\r\n//        }\r\n    }\r\n\r\n    for(boost::unordered_map<TreeNode*, std::vector< std::vector<Eigen::VectorXf> > >::iterator it = node_class_hough_votes.begin();\r\n        it != node_class_hough_votes.end(); ++it){\r\n\r\n        TreeNode *cur_node = it->first;\r\n        cur_node->hough_votes.resize(number_of_classes_);\r\n        for(int c=0; c<number_of_classes_; ++c)\r\n            cur_node->hough_votes[c].insert(cur_node->hough_votes[c].end(),\r\n                                            node_class_hough_votes[cur_node][c].begin(),\r\n                                            node_class_hough_votes[cur_node][c].end());\r\n\r\n\r\n    }\r\n\r\n}\r\n\r\n\r\n//put non-used training samples at the end and reduce train_samples accordingly\r\nvoid HFTrain::clean_trainset(TrainSet& train_set, int &train_samples){\r\n    int front = 0;\r\n    int back = train_samples - 1;\r\n    while(front < back){\r\n        while(front < train_samples && !train_set[front]->node->leaf)\r\n            front++;\r\n        while(back >= 0 && train_set[back]->node->leaf)\r\n            back--;\r\n        if(front < back){\r\n            TrainSample *t;\r\n            t = train_set[front];\r\n            train_set[front] = train_set[back];\r\n            train_set[back] = t;\r\n        }\r\n    }\r\n    train_samples = front;\r\n}\r\n\r\n\r\n//get random features, set threshold to 0 for now\r\nvoid HFTrain::get_random_features(const std::vector<TreeNode*> &level_nodes,\r\n                                  boost::unordered_map<TreeNode*, std::vector<Test> > &node_tests\r\n                                  )\r\n{\r\n\r\n\r\n    int num_tests = tests_per_node_* thresholds_per_test_;\r\n    for(int i=0; i<level_nodes.size(); ++i)\r\n        node_tests[level_nodes[i]].resize(num_tests);\r\n\r\n    omp_set_num_threads(threads_per_tree_);\r\n\r\n#pragma omp parallel for schedule(dynamic)\r\n    for(int n=0; n<level_nodes.size(); ++n){\r\n        TreeNode *cur_node = level_nodes[n];\r\n        std::vector<Test> *cur_node_tests = &(node_tests[cur_node]);\r\n        for(int t=0; t<tests_per_node_; ++t){\r\n            int mm = rand() % 2;\r\n            int f1 = rand() % feature_vector_length_;\r\n            int f2 = rand() % feature_vector_length_;            \r\n            for(int th=0; th<thresholds_per_test_; ++th){\r\n                (*cur_node_tests)[t*thresholds_per_test_ + th].measure_mode = mm;\r\n                (*cur_node_tests)[t*thresholds_per_test_ + th].feature1 = f1;\r\n                (*cur_node_tests)[t*thresholds_per_test_ + th].feature2 = f2;\r\n                (*cur_node_tests)[t*thresholds_per_test_ + th].threshold = 0;\r\n            }\r\n        }\r\n    }\r\n\r\n//    std::cout << \"random tests: \" << omp_get_wtime() - start << std::endl;\r\n\r\n}\r\n\r\n\r\n//get min-max for each test for each node to constraint thresholds' range\r\n//also get samples per class per node and samples per node because code here is convenient\r\nvoid HFTrain::get_min_max_count_samples(const TrainSet &train_set,\r\n                          int train_samples,\r\n                          const std::vector<TreeNode*> &level_nodes,\r\n                          boost::unordered_map<TreeNode*, std::vector<Test> > &node_tests,\r\n                          boost::unordered_map<TreeNode*, std::vector<float> > &node_test_min,\r\n                          boost::unordered_map<TreeNode*, std::vector<float> > &node_test_max,\r\n                          boost::unordered_map<TreeNode*, std::vector<int> > &node_class_samples,\r\n                          boost::unordered_map<TreeNode*, int> &node_samples\r\n                          )\r\n{\r\n\r\n    int num_tests = tests_per_node_ * thresholds_per_test_;\r\n    for(int i=0; i<level_nodes.size(); ++i){\r\n        node_test_min[level_nodes[i]] = std::vector<float>(num_tests,  FLT_MAX);\r\n        node_test_max[level_nodes[i]] = std::vector<float>(num_tests, -FLT_MAX);\r\n    }\r\n\r\n    for(int i=0; i<level_nodes.size(); ++i){\r\n        node_class_samples[level_nodes[i]] = std::vector<int>(number_of_classes_, 0);\r\n        node_samples[level_nodes[i]] = 0;\r\n    }\r\n\r\n//    double start = omp_get_wtime();\r\n\r\n    omp_set_num_threads(threads_per_tree_);\r\n\r\n#pragma omp parallel\r\n    {\r\n\r\n        boost::unordered_map<TreeNode*, std::vector<float> > node_test_min_local;\r\n        boost::unordered_map<TreeNode*, std::vector<float> > node_test_max_local;\r\n        for(int i=0; i<level_nodes.size(); ++i){\r\n            node_test_min_local[level_nodes[i]] = std::vector<float>(num_tests,  FLT_MAX);\r\n            node_test_max_local[level_nodes[i]] = std::vector<float>(num_tests, -FLT_MAX);\r\n        }\r\n        boost::unordered_map<TreeNode*, std::vector<int> > node_class_samples_local;\r\n        boost::unordered_map<TreeNode*, int> node_samples_local;\r\n        for(int i=0; i<level_nodes.size(); ++i){\r\n            node_class_samples_local[level_nodes[i]] = std::vector<int>(number_of_classes_, 0);\r\n            node_samples_local[level_nodes[i]] = 0;\r\n        }\r\n\r\n        #pragma omp for schedule(dynamic)\r\n        for(int i=0; i<train_samples; ++i){\r\n            TreeNode* cur_node = train_set[i]->node;\r\n            std::vector<float> *min_local = &node_test_min_local[cur_node];\r\n            std::vector<float> *max_local = &node_test_max_local[cur_node];\r\n            std::vector<Test> *cur_node_tests = &node_tests[cur_node];\r\n            for(int t=0; t<num_tests; ++t){\r\n                int f1 = (*cur_node_tests)[t].feature1;\r\n                int f2 = (*cur_node_tests)[t].feature2;\r\n                int mm = (*cur_node_tests)[t].measure_mode;\r\n                float val;\r\n                if(mm == 0)\r\n                    val = train_set[i]->feature_vector(f1) - train_set[i]->feature_vector(f2);\r\n                else if(mm == 1)\r\n                    val = train_set[i]->feature_vector(f1);\r\n\r\n                if(val > (*max_local)[t])\r\n                    (*max_local)[t] = val;\r\n                if(val < (*min_local)[t])\r\n                    (*min_local)[t] = val;\r\n            }\r\n            node_class_samples_local[cur_node][train_set[i]->class_no]++;\r\n            node_samples_local[cur_node]++;\r\n        }\r\n        #pragma omp critical\r\n        {\r\n            for(int n=0; n<level_nodes.size(); ++n){\r\n                std::vector<float> *min_local = &node_test_min_local[level_nodes[n]];\r\n                std::vector<float> *max_local = &node_test_max_local[level_nodes[n]];\r\n                std::vector<float> *min_global = &node_test_min[level_nodes[n]];\r\n                std::vector<float> *max_global = &node_test_max[level_nodes[n]];\r\n                for(int t=0; t<num_tests; ++t){\r\n                    if( (*min_global)[t] > (*min_local)[t] )\r\n                        (*min_global)[t] = (*min_local)[t];\r\n\r\n                    if( (*max_global)[t] < (*max_local)[t])\r\n                        (*max_global)[t] = (*max_local)[t];\r\n\r\n                }\r\n                for(int c=0; c<number_of_classes_; ++c)\r\n                    node_class_samples[level_nodes[n]][c] += node_class_samples_local[level_nodes[n]][c];\r\n\r\n                node_samples[level_nodes[n]] += node_samples_local[level_nodes[n]];\r\n            }\r\n        }\r\n    }\r\n\r\n\r\n//    std::cout << \"min - max: \" << omp_get_wtime() - start << std::endl;\r\n//    std::cout << node_min[level_nodes[0]][0] << \" \" << node_max[level_nodes[0]][0] << std::endl;\r\n\r\n}\r\n\r\n\r\n\r\n//get random tests\r\nvoid HFTrain::get_random_thresholds(const std::vector<TreeNode*> &level_nodes,\r\n                               boost::unordered_map<TreeNode*, std::vector<float> > &node_test_min,\r\n                               boost::unordered_map<TreeNode*, std::vector<float> > &node_test_max,\r\n                               boost::unordered_map<TreeNode*, std::vector<Test> > &node_tests\r\n                               )\r\n{\r\n\r\n\r\n    int num_tests = tests_per_node_* thresholds_per_test_;\r\n\r\n    omp_set_num_threads(threads_per_tree_);\r\n\r\n#pragma omp parallel for schedule(dynamic)\r\n    for(int n=0; n<level_nodes.size(); ++n){\r\n        TreeNode *cur_node = level_nodes[n];\r\n        std::vector<Test> *cur_node_tests = &(node_tests[cur_node]);\r\n        std::vector<float> *cur_node_test_min = &(node_test_min[cur_node]);\r\n        std::vector<float> *cur_node_test_max = &(node_test_max[cur_node]);\r\n        for(int t=0; t<num_tests; ++t){\r\n            float range = (*cur_node_test_max)[t] - (*cur_node_test_min)[t];\r\n            (*cur_node_tests)[t].threshold = (float)rand() / (float)RAND_MAX * range + (*cur_node_test_min)[t];\r\n        }\r\n    }\r\n\r\n//    std::cout << \"random tests: \" << omp_get_wtime() - start << std::endl;\r\n\r\n}\r\n\r\n\r\n\r\n\r\n// ------classification------ //\r\n//if no split found a node is marked as leaf.\r\n//best tests are stored to the node of each training sample\r\nvoid HFTrain::find_classification_split(TrainSet &train_set,\r\n                                        int train_samples,\r\n                                        const std::vector<TreeNode*> &level_nodes,\r\n                                        boost::unordered_map<TreeNode*, std::vector<Test> > &node_tests,\r\n                                        boost::unordered_map<TreeNode*, std::vector<int> > &node_class_samples,\r\n                                        boost::unordered_map<TreeNode*, int> &node_samples\r\n                                        )\r\n{\r\n\r\n    //number of samples per class per test per node that goes to the left child\r\n    //if we apply test\r\n    int num_tests = tests_per_node_* thresholds_per_test_;\r\n    boost::unordered_map<TreeNode*, std::vector< std::vector<int> > > node_test_class_samples_left;\r\n    for(int i=0; i<level_nodes.size(); ++i){\r\n        node_test_class_samples_left[level_nodes[i]].resize(num_tests);\r\n        for(int t=0; t<num_tests; ++t)\r\n            node_test_class_samples_left[level_nodes[i]][t] = std::vector<int>(number_of_classes_, 0);\r\n    }\r\n\r\n//    double start = omp_get_wtime();\r\n\r\n    omp_set_num_threads(threads_per_tree_);\r\n\r\n#pragma omp parallel\r\n    {\r\n\r\n        boost::unordered_map<TreeNode*, std::vector< std::vector<int> > > node_test_class_samples_left_local;\r\n        for(int i=0; i<level_nodes.size(); ++i){\r\n            node_test_class_samples_left_local[level_nodes[i]].resize(num_tests);\r\n            for(int t=0; t<num_tests; ++t)\r\n                node_test_class_samples_left_local[level_nodes[i]][t] = std::vector<int>(number_of_classes_, 0);\r\n        }\r\n\r\n        #pragma omp for schedule(dynamic)\r\n        for(int i=0; i<train_samples; ++i){\r\n            TreeNode *cur_node = train_set[i]->node;\r\n            std::vector< std::vector<int> > *cur_left_local = &node_test_class_samples_left_local[cur_node];\r\n            //apply all tests to current sample\r\n            for(int t=0; t<num_tests; ++t){\r\n                Test cur_test = node_tests[cur_node][t];\r\n                float val;\r\n                if(cur_test.measure_mode == 0)\r\n                    val = train_set[i]->feature_vector(cur_test.feature1) - train_set[i]->feature_vector(cur_test.feature2);\r\n                else if(cur_test.measure_mode == 1)\r\n                    val = train_set[i]->feature_vector(cur_test.feature1);\r\n\r\n                if( val < cur_test.threshold )\r\n                    //go to left, count it\r\n                    (*cur_left_local)[t][train_set[i]->class_no] ++;\r\n            }\r\n\r\n        }\r\n        #pragma omp critical\r\n        {\r\n\r\n            for(int n=0; n<level_nodes.size(); ++n){\r\n                std::vector< std::vector<int> > *cur_left_local = &node_test_class_samples_left_local[level_nodes[n]];\r\n                std::vector< std::vector<int> > *cur_left_global = &node_test_class_samples_left[level_nodes[n]];\r\n                for(int t=0; t<num_tests; ++t)\r\n                    for(int c=0; c<number_of_classes_; ++c)\r\n                        (*cur_left_global)[t][c] += (*cur_left_local)[t][c];\r\n            }\r\n\r\n        }\r\n\r\n    }\r\n\r\n//    std::cout << \"class hist: \" << omp_get_wtime() - start << std::endl;\r\n\r\n    //compute best test via entropy\r\n\r\n#pragma omp parallel\r\n    {\r\n    int num_leaves = 0;\r\n    #pragma omp for schedule(dynamic)\r\n    for(int n=0; n<level_nodes.size(); ++n){\r\n        TreeNode *cur_node = level_nodes[n];\r\n        std::vector< std::vector<int> > *cur_samples_left = &node_test_class_samples_left[cur_node];\r\n        std::vector<int> *cur_class_samples = &node_class_samples[cur_node];\r\n        int cur_samples = node_samples[cur_node];\r\n        float min_entropy = FLT_MAX;\r\n        Test best_test;\r\n        bool found = false;\r\n        for(int t=0; t<num_tests; ++t){\r\n            float entropy_left = 0;\r\n            float entropy_right = 0;\r\n            float entropy = FLT_MAX;\r\n            int total_samples_left = 0;\r\n            for(int c=0; c<number_of_classes_; ++c)\r\n                total_samples_left += (*cur_samples_left)[t][c];\r\n            int total_samples_right = cur_samples - total_samples_left;\r\n            if(total_samples_left != 0 && total_samples_right != 0){\r\n                for(int c=0; c<number_of_classes_; ++c){\r\n                    //add left entropy\r\n                    float p=(float)(*cur_samples_left)[t][c] / (float)total_samples_left;\r\n                    if(p!=0) entropy_left -= p * log(p);\r\n                    //add right entropy\r\n                    p = (float)((*cur_class_samples)[c] - (*cur_samples_left)[t][c]) / (float)total_samples_right;\r\n                    if(p!=0) entropy_right -= p * log(p);\r\n                }\r\n                entropy = (entropy_left * (float)total_samples_left + entropy_right * (float)total_samples_right);\r\n                if(entropy < min_entropy){\r\n                    min_entropy = entropy;\r\n                    best_test = node_tests[cur_node][t];\r\n                    found = true;\r\n                }\r\n            }\r\n\r\n        }\r\n        if(found){\r\n            cur_node->test = best_test;\r\n            cur_node->leaf = false;\r\n            cur_node->left = new TreeNode;\r\n            cur_node->right = new TreeNode;\r\n        }\r\n        else{\r\n            cur_node->leaf = true;            \r\n        }\r\n    }\r\n\r\n    }\r\n\r\n//    std::cout << \"best tests classification: \" << omp_get_wtime() - start << std::endl;\r\n\r\n}\r\n\r\n\r\n\r\n\r\n// ------Regression for x y z------ //\r\n//if no split found a node is marked as leaf.\r\n//best tests are stored to the node of each training sample\r\nvoid HFTrain::find_regression_location_split(TrainSet &train_set,\r\n                                            int train_samples,\r\n                                            const std::vector<TreeNode*> &level_nodes,\r\n                                            boost::unordered_map<TreeNode*, std::vector<Test> > &node_tests,\r\n                                            boost::unordered_map<TreeNode*, std::vector<int> > &node_class_samples,\r\n                                            boost::unordered_map<TreeNode*, int> &node_samples\r\n                                            )\r\n{\r\n\r\n//    double start = omp_get_wtime();\r\n\r\n    //get the mean values for all possible split-childs\r\n\r\n    //[node][test][0-1(left-right)][0-2(x,y,z)] = mean(x, y, z) and 4->samples_of_child per child node per test per node\r\n    int num_tests = tests_per_node_* thresholds_per_test_;\r\n    boost::unordered_map<TreeNode*, std::vector< std::vector< std::vector<float> > > > node_test_child_mean;\r\n    for(int i=0; i<level_nodes.size(); ++i){\r\n        node_test_child_mean[level_nodes[i]].resize(num_tests);\r\n        for(int t=0; t<num_tests; ++t){\r\n            node_test_child_mean[level_nodes[i]][t].resize(2);\r\n            for(int child=0; child<2; ++child){\r\n                node_test_child_mean[level_nodes[i]][t][child] = std::vector<float>(4, 0); //x y z\r\n            }\r\n        }\r\n    }\r\n\r\n    omp_set_num_threads(threads_per_tree_);\r\n\r\n#pragma omp parallel\r\n    {\r\n\r\n        boost::unordered_map<TreeNode*, std::vector< std::vector< std::vector<float> > > > node_test_child_mean_local;\r\n        for(int i=0; i<level_nodes.size(); ++i){\r\n            node_test_child_mean_local[level_nodes[i]].resize(num_tests);\r\n            for(int t=0; t<num_tests; ++t){\r\n                node_test_child_mean_local[level_nodes[i]][t].resize(2);\r\n                for(int child=0; child<2; ++child){\r\n                    node_test_child_mean_local[level_nodes[i]][t][child] = std::vector<float>(4, 0); //x y z child_samples\r\n                }\r\n            }\r\n        }\r\n\r\n        #pragma omp for schedule(dynamic)\r\n        for(int i=0; i<train_samples; ++i){\r\n            TreeNode *cur_node = train_set[i]->node;\r\n            //reduce calls to hash table so to reduce execution time\r\n            std::vector< std::vector< std::vector<float> > > *cur_mean = &(node_test_child_mean_local[cur_node]);\r\n            //apply all tests to current sample\r\n            for(int t=0; t<num_tests; ++t){\r\n                Test cur_test = node_tests[cur_node][t];\r\n                float val;\r\n                if(cur_test.measure_mode == 0)\r\n                    val = train_set[i]->feature_vector(cur_test.feature1) - train_set[i]->feature_vector(cur_test.feature2);\r\n                else if(cur_test.measure_mode == 1)\r\n                    val = train_set[i]->feature_vector(cur_test.feature1);\r\n\r\n                int child;\r\n                if( val < cur_test.threshold )\r\n                    //go to the left child\r\n                    child = 0;\r\n                else\r\n                    //go to the right\r\n                    child = 1;\r\n\r\n                (*cur_mean)[t][child][0] += train_set[i]->dof(3); //x\r\n                (*cur_mean)[t][child][1] += train_set[i]->dof(4); //y\r\n                (*cur_mean)[t][child][2] += train_set[i]->dof(5); //z\r\n                (*cur_mean)[t][child][3]++;                       //count samples\r\n\r\n            }\r\n\r\n        }\r\n        //get child samples in order to calculate mean values\r\n        #pragma omp critical\r\n        {\r\n            for(int n=0; n<level_nodes.size(); ++n){\r\n                std::vector< std::vector< std::vector<float> > > *cur_mean = &(node_test_child_mean[level_nodes[n]]);\r\n                std::vector< std::vector< std::vector<float> > > *cur_mean_local = &(node_test_child_mean_local[level_nodes[n]]);\r\n                for(int t=0; t<num_tests; ++t)\r\n                    for(int child=0; child<2; ++child)\r\n                        (*cur_mean)[t][child][3] +=\r\n                            (*cur_mean_local)[t][child][3];\r\n            }\r\n        }\r\n\r\n        //continue after maen is calculated\r\n        #pragma omp barrier\r\n\r\n        #pragma omp critical\r\n        {\r\n            for(int n=0; n<level_nodes.size(); ++n){\r\n                std::vector< std::vector< std::vector<float> > > *cur_mean = &(node_test_child_mean[level_nodes[n]]);\r\n                std::vector< std::vector< std::vector<float> > > *cur_mean_local = &(node_test_child_mean_local[level_nodes[n]]);\r\n                for(int t=0; t<num_tests; ++t)\r\n                    for(int child=0; child<2; ++child)\r\n                        for(int coord=0; coord<3; ++coord) // x y z only\r\n                            if((*cur_mean)[t][child][3] > 0)\r\n                                (*cur_mean)[t][child][coord] +=\r\n                                    (*cur_mean_local)[t][child][coord] / (*cur_mean)[t][child][3];\r\n            }\r\n\r\n        }\r\n\r\n    }\r\n\r\n\r\n    //get std values for all possible split-childs\r\n\r\n    //[node][test][0-1(left-right)] = std(x) + std(y) + std(z) per child node per test per node\r\n    boost::unordered_map<TreeNode*, std::vector< std::vector<float> > > node_test_child_std;\r\n    for(int i=0; i<level_nodes.size(); ++i){\r\n        node_test_child_std[level_nodes[i]].resize(num_tests);\r\n        for(int t=0; t<num_tests; ++t){\r\n            node_test_child_std[level_nodes[i]][t].resize(2);\r\n            for(int child=0; child<2; ++child){\r\n                node_test_child_std[level_nodes[i]][t][child] = 0;\r\n            }\r\n        }\r\n    }\r\n\r\n\r\n#pragma omp parallel\r\n    {\r\n\r\n        boost::unordered_map<TreeNode*, std::vector< std::vector<float> > > node_test_child_std_local;\r\n        for(int i=0; i<level_nodes.size(); ++i){\r\n            node_test_child_std_local[level_nodes[i]].resize(num_tests);\r\n            for(int t=0; t<num_tests; ++t){\r\n                node_test_child_std_local[level_nodes[i]][t].resize(2);\r\n                for(int child=0; child<2; ++child){\r\n                    node_test_child_std_local[level_nodes[i]][t][child] = 0;\r\n                }\r\n            }\r\n        }\r\n\r\n        #pragma omp for schedule(dynamic)\r\n        for(int i=0; i<train_samples; ++i){\r\n            TreeNode *cur_node = train_set[i]->node;\r\n            std::vector< std::vector< std::vector<float> > > *cur_mean = &(node_test_child_mean[cur_node]);\r\n            std::vector< std::vector<float> > *cur_std_local = &(node_test_child_std_local[cur_node]);\r\n            //apply all tests to current sample\r\n            for(int t=0; t<num_tests; ++t){\r\n                Test cur_test = node_tests[cur_node][t];\r\n                float val;\r\n                if(cur_test.measure_mode == 0)\r\n                    val = train_set[i]->feature_vector(cur_test.feature1) - train_set[i]->feature_vector(cur_test.feature2);\r\n                else if(cur_test.measure_mode == 1)\r\n                    val = train_set[i]->feature_vector(cur_test.feature1);\r\n\r\n                int child;\r\n                if( val < cur_test.threshold )\r\n                    //go to left\r\n                    child = 0;\r\n                else\r\n                    //go to right\r\n                    child = 1;\r\n\r\n                (*cur_std_local)[t][child] +=\r\n                    pow(train_set[i]->dof(3) - (*cur_mean)[t][child][0], 2) +  //x\r\n                    pow(train_set[i]->dof(4) - (*cur_mean)[t][child][1], 2) +  //y\r\n                    pow(train_set[i]->dof(5) - (*cur_mean)[t][child][2], 2);   //z\r\n\r\n            }\r\n\r\n        }\r\n        #pragma omp critical\r\n        {\r\n\r\n            for(int n=0; n<level_nodes.size(); ++n){\r\n                std::vector< std::vector< std::vector<float> > > *cur_mean = &(node_test_child_mean[level_nodes[n]]);\r\n                std::vector< std::vector<float> > *cur_std_local = &(node_test_child_std_local[level_nodes[n]]);\r\n                std::vector< std::vector<float> > *cur_std = &(node_test_child_std[level_nodes[n]]);\r\n                for(int t=0; t<num_tests; ++t)\r\n                    for(int child=0; child<2; ++child)\r\n                        if((*cur_mean)[t][child][3] > 0)\r\n                            (*cur_std)[t][child] +=\r\n                                (*cur_std_local)[t][child] / (*cur_mean)[t][child][3];\r\n            }\r\n\r\n        }\r\n\r\n    }\r\n\r\n    //compute best test using std\r\n\r\n#pragma omp parallel\r\n    {\r\n    int num_leaves = 0;\r\n    #pragma omp for schedule(dynamic)\r\n    for(int n=0; n<level_nodes.size(); ++n){\r\n        TreeNode *cur_node = level_nodes[n];\r\n        std::vector< std::vector< std::vector<float> > > *cur_mean = &(node_test_child_mean[cur_node]);\r\n        std::vector< std::vector<float> > *cur_std = &(node_test_child_std[cur_node]);\r\n        float min_std = FLT_MAX;\r\n        Test best_test;\r\n        bool found = false;\r\n        for(int t=0; t<num_tests; ++t){\r\n            float total_samples_left  = (*cur_mean)[t][0][3];\r\n            float total_samples_right = (*cur_mean)[t][1][3];\r\n            if(total_samples_left > 0.1f && total_samples_right > 0.1f){\r\n                float std = (*cur_std)[t][0]*total_samples_left + (*cur_std)[t][1]*total_samples_right;\r\n                if(std < min_std){\r\n                    min_std = std;\r\n                    best_test = node_tests[cur_node][t];\r\n                    found = true;\r\n                }\r\n            }\r\n\r\n        }\r\n        if(found){\r\n            cur_node->test = best_test;\r\n            cur_node->leaf = false;\r\n            cur_node->left = new TreeNode;\r\n            cur_node->right = new TreeNode;\r\n        }\r\n        else{\r\n            cur_node->leaf = true;            \r\n        }\r\n    }\r\n\r\n    }\r\n\r\n//    std::cout << \"best tests regression: \" << omp_get_wtime() - start << std::endl;\r\n\r\n}\r\n\r\n\r\n\r\n// ------Regression for yaw pitch roll------ //\r\n//if no split found a node is marked as leaf.\r\n//best tests are stored to the node of each training sample\r\nvoid HFTrain::find_regression_pose_split(TrainSet &train_set,\r\n                                            int train_samples,\r\n                                            const std::vector<TreeNode*> &level_nodes,\r\n                                            boost::unordered_map<TreeNode*, std::vector<Test> > &node_tests,\r\n                                            boost::unordered_map<TreeNode*, std::vector<int> > &node_class_samples,\r\n                                            boost::unordered_map<TreeNode*, int> &node_samples\r\n                                            )\r\n{\r\n\r\n//    double start = omp_get_wtime();\r\n\r\n    //get the mean values for all possible split-childs\r\n\r\n    // [node][test][0-1(left-right)][0-2(x,y,z)] =\r\n    // cos(yaw), sin(yaw), cos(pitch), sin(pitch), cos(roll), sin(roll), count samples\r\n    int num_tests = tests_per_node_* thresholds_per_test_;\r\n    boost::unordered_map<TreeNode*, std::vector< std::vector< std::vector<float> > > > node_test_child_mean;\r\n    for(int i=0; i<level_nodes.size(); ++i){\r\n        node_test_child_mean[level_nodes[i]].resize(num_tests);\r\n        for(int t=0; t<num_tests; ++t){\r\n            node_test_child_mean[level_nodes[i]][t].resize(2);\r\n            for(int child=0; child<2; ++child){\r\n                node_test_child_mean[level_nodes[i]][t][child] = std::vector<float>(7, 0);\r\n            }\r\n        }\r\n    }\r\n\r\n    omp_set_num_threads(threads_per_tree_);\r\n\r\n#pragma omp parallel\r\n    {\r\n\r\n        boost::unordered_map<TreeNode*, std::vector< std::vector< std::vector<float> > > > node_test_child_mean_local;\r\n        for(int i=0; i<level_nodes.size(); ++i){\r\n            node_test_child_mean_local[level_nodes[i]].resize(num_tests);\r\n            for(int t=0; t<num_tests; ++t){\r\n                node_test_child_mean_local[level_nodes[i]][t].resize(2);\r\n                for(int child=0; child<2; ++child){\r\n                    node_test_child_mean_local[level_nodes[i]][t][child] = std::vector<float>(7, 0);\r\n                }\r\n            }\r\n        }\r\n\r\n        #pragma omp for schedule(dynamic)\r\n        for(int i=0; i<train_samples; ++i){\r\n            TreeNode *cur_node = train_set[i]->node;\r\n            //reduce calls to hash table so to reduce execution time\r\n            std::vector< std::vector< std::vector<float> > > *cur_mean = &(node_test_child_mean_local[cur_node]);\r\n            //apply all tests to current sample\r\n            for(int t=0; t<num_tests; ++t){\r\n                Test cur_test = node_tests[cur_node][t];\r\n                float val;\r\n                if(cur_test.measure_mode == 0)\r\n                    val = train_set[i]->feature_vector(cur_test.feature1) - train_set[i]->feature_vector(cur_test.feature2);\r\n                else if(cur_test.measure_mode == 1)\r\n                    val = train_set[i]->feature_vector(cur_test.feature1);\r\n\r\n                int child;\r\n                if( val < cur_test.threshold )\r\n                    //go to the left child\r\n                    child = 0;\r\n                else\r\n                    //go to the right\r\n                    child = 1;\r\n\r\n                (*cur_mean)[t][child][0] += cos(train_set[i]->dof(0)); //cos(yaw)\r\n                (*cur_mean)[t][child][1] += sin(train_set[i]->dof(0)); //sin(yaw)\r\n                (*cur_mean)[t][child][2] += cos(train_set[i]->dof(1)); //cos(pitch)\r\n                (*cur_mean)[t][child][3] += sin(train_set[i]->dof(1)); //sin(pitch)\r\n                (*cur_mean)[t][child][4] += cos(train_set[i]->dof(2)); //cos(roll)\r\n                (*cur_mean)[t][child][5] += sin(train_set[i]->dof(2)); //sin(roll)\r\n                (*cur_mean)[t][child][6]++;                            //count samples\r\n\r\n            }\r\n\r\n        }\r\n        //get child samples in order to calculate mean values\r\n        #pragma omp critical\r\n        {\r\n            for(int n=0; n<level_nodes.size(); ++n){\r\n                std::vector< std::vector< std::vector<float> > > *cur_mean = &(node_test_child_mean[level_nodes[n]]);\r\n                std::vector< std::vector< std::vector<float> > > *cur_mean_local = &(node_test_child_mean_local[level_nodes[n]]);\r\n                for(int t=0; t<num_tests; ++t)\r\n                    for(int child=0; child<2; ++child)\r\n                        (*cur_mean)[t][child][6] +=\r\n                            (*cur_mean_local)[t][child][6];\r\n            }\r\n        }\r\n\r\n        //continue after mean is calculated\r\n        #pragma omp barrier\r\n\r\n        #pragma omp critical\r\n        {\r\n            for(int n=0; n<level_nodes.size(); ++n){\r\n                std::vector< std::vector< std::vector<float> > > *cur_mean = &(node_test_child_mean[level_nodes[n]]);\r\n                std::vector< std::vector< std::vector<float> > > *cur_mean_local = &(node_test_child_mean_local[level_nodes[n]]);\r\n                for(int t=0; t<num_tests; ++t)\r\n                    for(int child=0; child<2; ++child)\r\n                        for(int pose=0; pose<6; ++pose)\r\n                            if((*cur_mean)[t][child][6] > 0)\r\n                                (*cur_mean)[t][child][pose] +=\r\n                                    (*cur_mean_local)[t][child][pose] / (*cur_mean)[t][child][6];\r\n            }\r\n\r\n        }\r\n\r\n    }\r\n\r\n\r\n    //get std values for all possible split-childs\r\n\r\n    //[node][test][0-1(left-right)] = std(x) + std(y) + std(z) per child node per test per node\r\n    boost::unordered_map<TreeNode*, std::vector< std::vector<float> > > node_test_child_std;\r\n    for(int i=0; i<level_nodes.size(); ++i){\r\n        node_test_child_std[level_nodes[i]].resize(num_tests);\r\n        for(int t=0; t<num_tests; ++t){\r\n            node_test_child_std[level_nodes[i]][t].resize(2);\r\n            for(int child=0; child<2; ++child){\r\n                node_test_child_std[level_nodes[i]][t][child] = 0;\r\n            }\r\n        }\r\n    }\r\n\r\n\r\n#pragma omp parallel\r\n    {\r\n\r\n        boost::unordered_map<TreeNode*, std::vector< std::vector<float> > > node_test_child_std_local;\r\n        for(int i=0; i<level_nodes.size(); ++i){\r\n            node_test_child_std_local[level_nodes[i]].resize(num_tests);\r\n            for(int t=0; t<num_tests; ++t){\r\n                node_test_child_std_local[level_nodes[i]][t].resize(2);\r\n                for(int child=0; child<2; ++child){\r\n                    node_test_child_std_local[level_nodes[i]][t][child] = 0;\r\n                }\r\n            }\r\n        }\r\n\r\n        #pragma omp for schedule(dynamic)\r\n        for(int i=0; i<train_samples; ++i){\r\n            TreeNode *cur_node = train_set[i]->node;\r\n            std::vector< std::vector< std::vector<float> > > *cur_mean = &(node_test_child_mean[cur_node]);\r\n            std::vector< std::vector<float> > *cur_std_local = &(node_test_child_std_local[cur_node]);\r\n            //apply all tests to current sample\r\n            for(int t=0; t<num_tests; ++t){\r\n                Test cur_test = node_tests[cur_node][t];\r\n                float val;\r\n                if(cur_test.measure_mode == 0)\r\n                    val = train_set[i]->feature_vector(cur_test.feature1) - train_set[i]->feature_vector(cur_test.feature2);\r\n                else if(cur_test.measure_mode == 1)\r\n                    val = train_set[i]->feature_vector(cur_test.feature1);\r\n\r\n                int child;\r\n                if( val < cur_test.threshold )\r\n                    //go to left\r\n                    child = 0;\r\n                else\r\n                    //go to right\r\n                    child = 1;\r\n\r\n                (*cur_std_local)[t][child] +=\r\n                        pow(cos(train_set[i]->dof(0)) - (*cur_mean)[t][child][0], 2) +  //cos(yaw)\r\n                        pow(sin(train_set[i]->dof(0)) - (*cur_mean)[t][child][1], 2) +  //sin(yaw)\r\n                        pow(cos(train_set[i]->dof(1)) - (*cur_mean)[t][child][2], 2) +  //cos(pitch)\r\n                        pow(sin(train_set[i]->dof(1)) - (*cur_mean)[t][child][3], 2) +  //sin(pitch)\r\n                        pow(cos(train_set[i]->dof(2)) - (*cur_mean)[t][child][4], 2) +  //cos(roll)\r\n                        pow(sin(train_set[i]->dof(2)) - (*cur_mean)[t][child][5], 2);   //sin(roll)\r\n\r\n            }\r\n\r\n        }\r\n        #pragma omp critical\r\n        {\r\n\r\n            for(int n=0; n<level_nodes.size(); ++n){\r\n                std::vector< std::vector< std::vector<float> > > *cur_mean = &(node_test_child_mean[level_nodes[n]]);\r\n                std::vector< std::vector<float> > *cur_std_local = &(node_test_child_std_local[level_nodes[n]]);\r\n                std::vector< std::vector<float> > *cur_std = &(node_test_child_std[level_nodes[n]]);\r\n                for(int t=0; t<num_tests; ++t)\r\n                    for(int child=0; child<2; ++child)\r\n                        if((*cur_mean)[t][child][6] > 0)\r\n                            (*cur_std)[t][child] +=\r\n                                (*cur_std_local)[t][child] / (*cur_mean)[t][child][6];\r\n            }\r\n\r\n        }\r\n\r\n    }\r\n\r\n    //compute best test using std\r\n\r\n#pragma omp parallel\r\n    {\r\n    int num_leaves = 0;\r\n    #pragma omp for schedule(dynamic)\r\n    for(int n=0; n<level_nodes.size(); ++n){\r\n        TreeNode *cur_node = level_nodes[n];\r\n        std::vector< std::vector< std::vector<float> > > *cur_mean = &(node_test_child_mean[cur_node]);\r\n        std::vector< std::vector<float> > *cur_std = &(node_test_child_std[cur_node]);\r\n        float min_std = FLT_MAX;\r\n        Test best_test;\r\n        bool found = false;\r\n        for(int t=0; t<num_tests; ++t){\r\n            float total_samples_left  = (*cur_mean)[t][0][6];\r\n            float total_samples_right = (*cur_mean)[t][1][6];\r\n            if(total_samples_left > 0.1f && total_samples_right > 0.1f){\r\n                float std = (*cur_std)[t][0]*total_samples_left + (*cur_std)[t][1]*total_samples_right;\r\n                if(std < min_std){\r\n                    min_std = std;\r\n                    best_test = node_tests[cur_node][t];\r\n                    found = true;\r\n                }\r\n            }\r\n\r\n        }\r\n        if(found){\r\n            cur_node->test = best_test;\r\n            cur_node->leaf = false;\r\n            cur_node->left = new TreeNode;\r\n            cur_node->right = new TreeNode;\r\n        }\r\n        else{\r\n            cur_node->leaf = true;            \r\n        }\r\n    }\r\n\r\n    }\r\n\r\n//    std::cout << \"best tests regression: \" << omp_get_wtime() - start << std::endl;\r\n\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid HFTrain::apply_tests_to_train_samples(TrainSet &train_set, int train_samples, boost::unordered_map<TreeNode*, int> &new_node_samples)\r\n{\r\n    //apply splitting with best test found and count new node samples\r\n\r\n    omp_set_num_threads(threads_per_tree_);\r\n\r\n#pragma omp parallel\r\n    {\r\n        boost::unordered_map<TreeNode*, int> new_node_samples_local;\r\n\r\n        #pragma omp for schedule(dynamic)\r\n        for(int i=0; i<train_samples; ++i){\r\n            if(!train_set[i]->node->leaf){\r\n                //set node number for new level\r\n                Test cur_test = train_set[i]->node->test;\r\n                float val;\r\n                if(cur_test.measure_mode == 0)\r\n                    val = train_set[i]->feature_vector(cur_test.feature1) - train_set[i]->feature_vector(cur_test.feature2);\r\n                else if(cur_test.measure_mode == 1)\r\n                    val = train_set[i]->feature_vector(cur_test.feature1);\r\n\r\n                if(val < cur_test.threshold)\r\n                    train_set[i]->node = train_set[i]->node->left;\r\n                else\r\n                    train_set[i]->node = train_set[i]->node->right;\r\n\r\n                if(new_node_samples_local.count(train_set[i]->node))\r\n                    new_node_samples_local[train_set[i]->node]++;\r\n                else\r\n                    new_node_samples_local[train_set[i]->node] = 1;\r\n\r\n            }\r\n        }\r\n\r\n        #pragma omp critical\r\n        {\r\n\r\n            for(boost::unordered_map<TreeNode*, int>::iterator t = new_node_samples_local.begin(); t != new_node_samples_local.end(); ++t){\r\n                if(new_node_samples.count(t->first))\r\n                    new_node_samples[t->first] += t->second;\r\n                else\r\n                    new_node_samples[t->first] = t->second;\r\n            }\r\n\r\n        }\r\n\r\n    }\r\n\r\n//    std::cout << \"New node samples: \" << new_node_samples[train_set[0]->node] << \" \" << new_node_samples[level_nodes[0]->right] << std::endl;\r\n\r\n}\r\n\r\n\r\n\r\nvoid HFTrain::optimize_level(TrainSet &train_set,\r\n                             int train_samples,                             \r\n                             int cur_level,\r\n                             const std::vector<TreeNode*> &level_nodes,\r\n                             boost::unordered_map<TreeNode*, int> &new_node_samples\r\n                             )\r\n{\r\n\r\n\r\n    std::cout << \"Depth: \" << cur_level << \"  nodes: \" << level_nodes.size() << std::endl;\r\n//    double start = omp_get_wtime();\r\n\r\n    //get random test features, not thresholds yet\r\n    boost::unordered_map<TreeNode*, std::vector<Test> > node_tests;\r\n    get_random_features(level_nodes, node_tests);\r\n\r\n\r\n    //get min-max for each feature for each node to constraint thresholds' range\r\n    boost::unordered_map<TreeNode*, std::vector<float> > node_test_min;\r\n    boost::unordered_map<TreeNode*, std::vector<float> > node_test_max;\r\n    boost::unordered_map<TreeNode*, std::vector<int> > node_class_samples;\r\n    boost::unordered_map<TreeNode*, int> node_samples;\r\n\r\n    get_min_max_count_samples(train_set,\r\n                              train_samples,\r\n                              level_nodes,\r\n                              node_tests,\r\n                              node_test_min,\r\n                              node_test_max,\r\n                              node_class_samples,\r\n                              node_samples);\r\n\r\n    get_random_thresholds(level_nodes, node_test_min, node_test_max, node_tests);\r\n\r\n\r\n    //0->classification\r\n    //1->regression of x,y,z\r\n    //2->refression of yaw,pitch,roll\r\n    int split_method;\r\n    if(cur_level < 4)\r\n        split_method = 0;\r\n    else\r\n        split_method = rand() % 3;\r\n\r\n//    std::cout << \"Before split: \" << omp_get_wtime() - start << std::endl;\r\n\r\n    if(split_method == 0){\r\n        //do classification\r\n        find_classification_split(train_set,\r\n                                  train_samples,\r\n                                  level_nodes,\r\n                                  node_tests,\r\n                                  node_class_samples,\r\n                                  node_samples);\r\n    } else if(split_method == 1){\r\n        //do regression of object coordinates\r\n        find_regression_location_split(train_set,\r\n                                  train_samples,\r\n                                  level_nodes,\r\n                                  node_tests,\r\n                                  node_class_samples,\r\n                                  node_samples);\r\n    } else if(split_method == 2){\r\n        //do regression yaw pitch roll\r\n        find_regression_pose_split(train_set,\r\n                                  train_samples,\r\n                                  level_nodes,\r\n                                  node_tests,\r\n                                  node_class_samples,\r\n                                  node_samples);\r\n    }\r\n\r\n    //apply best tests that were stored to the nodes of each train sample\r\n    apply_tests_to_train_samples(train_set, train_samples, new_node_samples);\r\n\r\n//    std::cout << \"After split \" << split_method << \": \" << omp_get_wtime() - start << std::endl;\r\n\r\n}\r\n\r\n\r\n\r\n//train depth by depth, all nodes together!\r\nvoid HFTrain::train_tree(TreeNode *root, TrainSet& train_set){\r\n\r\n    //every training sample is set to the root\r\n    for(int i=0; i<train_set.size(); ++i)\r\n        train_set[i]->node = root;\r\n\r\n    //get 66.6% of training samples at beginning\r\n    int train_samples = 2.0f/3.0f*(float)train_set.size();\r\n    std::vector<int> samples_per_class;\r\n    suffle_training_set(train_set, train_samples, samples_per_class);\r\n\r\n    //add the root\r\n    std::vector<TreeNode*> cur_level_nodes;\r\n    cur_level_nodes.push_back(root);\r\n\r\n    int cur_level = 0;\r\n    int cur_leaf_id = 0;\r\n    while(cur_level_nodes.size() > 0) {\r\n\r\n        boost::unordered_map<TreeNode*, int> new_node_samples;\r\n        optimize_level(train_set, train_samples, cur_level, cur_level_nodes, new_node_samples);\r\n\r\n        std::vector<TreeNode*> new_level_nodes;\r\n        for(int i=0; i<cur_level_nodes.size(); ++i){\r\n            if(!cur_level_nodes[i]->leaf){\r\n                if(new_node_samples[cur_level_nodes[i]->left] > min_samples_)\r\n                    new_level_nodes.push_back(cur_level_nodes[i]->left);\r\n                else{\r\n                    //make leaf left\r\n                    num_leaves_++;\r\n                    cur_level_nodes[i]->left->leaf = true;                    \r\n                }\r\n                if(new_node_samples[cur_level_nodes[i]->right] > min_samples_)\r\n                    new_level_nodes.push_back(cur_level_nodes[i]->right);\r\n                else{\r\n                    //make leaf right\r\n                    num_leaves_++;\r\n                    cur_level_nodes[i]->right->leaf = true;                    \r\n                }\r\n\r\n            }\r\n        }\r\n//        double start = omp_get_wtime();\r\n        make_leafs(train_set, train_samples, samples_per_class, cur_leaf_id);\r\n//        std::cout << \"Leafs made in: \" << omp_get_wtime() - start << std::endl;\r\n\r\n        //put train samples that belong to leaf nodes to the end and reduce the size\r\n        //of training samples accordingly\r\n        clean_trainset(train_set, train_samples);\r\n//        std::cout << \"Train samples after clean: :\" << train_samples << std::endl;\r\n\r\n        cur_level_nodes = new_level_nodes;\r\n        cur_level++;\r\n//        std::cout << \"Current level: \" << cur_level << std::endl;\r\n//        std::cout << \"Level nodes: \" << cur_level_nodes.size() << std::endl;\r\n//        std::cout << \"Total Leaf nodes: \" << num_leaves_ << std::endl;\r\n\r\n    }\r\n\r\n\r\n}\r\n\r\n\r\n\r\nvoid HFTrain::train()\r\n{\r\n\r\n    omp_set_nested(1);\r\n    omp_set_num_threads(threads_for_parallel_trees_);\r\n    #pragma omp parallel\r\n    {\r\n        //each thread should have different seed\r\n        //otherwise random numbers would be the same in all tress\r\n        srand( int(time(NULL)) ^ omp_get_thread_num() );\r\n\r\n        //each thread should read its own input to avoid confict\r\n        TrainSet train_set;\r\n        int feature_vector_length, number_of_classes;\r\n        std::stringstream msg;\r\n        msg << \"Thread \" << omp_get_thread_num() << \": Reading input...\" << std::endl;\r\n        std::cout << msg.str();\r\n        getTrainSet(train_set, number_of_classes, feature_vector_length);\r\n        msg.str(\"\");\r\n        msg << \"Thread \" << omp_get_thread_num() << \": Finished reading \" << train_set.size() << \" train samples.\" << std::endl;\r\n        std::cout << msg.str();\r\n\r\n        if(omp_get_thread_num() == 0){\r\n            number_of_classes_ = number_of_classes;\r\n            feature_vector_length_ = feature_vector_length;\r\n            //write forest.txt\r\n            std::ofstream finfo((output_folder_ + \"/forest.txt\").c_str());\r\n            finfo << number_of_trees_ << \" \" <<\r\n                     number_of_classes_ << \" \" <<\r\n                     feature_vector_length_ << \" \" <<\r\n                     patch_size_in_voxels_ << \" \" <<\r\n                     voxel_size_in_m_ << std::endl;\r\n            finfo.close();\r\n        }\r\n        //wait until member variables are written\r\n        #pragma omp barrier\r\n\r\n        //start training\r\n        #pragma omp for schedule(dynamic)\r\n        for(int t=start_tree_no_; t< start_tree_no_ + number_of_trees_; ++t){\r\n\r\n            std::stringstream s;\r\n            s << output_folder_ << \"/tree\" << t << \".dat\";\r\n            std::ofstream f(s.str().c_str(), std::ios::out | std::ios::binary);\r\n            CHECK(f) << \"Could not write to file \" << s.str();\r\n\r\n            TreeNode *tree = new TreeNode;\r\n\r\n            msg.str(\"\");\r\n            msg << \"Training tree: \" << t << std::endl;\r\n            std::cout << msg.str();\r\n            double t0 = omp_get_wtime();\r\n            train_tree(tree, train_set);\r\n            double t1 = omp_get_wtime();\r\n\r\n            saveTreeNode(tree, f);\r\n            msg.str(\"\");\r\n            msg << \"Tree \" << t << \" saved - \" << t1-t0 << \"sec\" << std::endl;\r\n            std::cout << msg.str();\r\n\r\n            deleteTreeNode(tree);\r\n            delete tree;\r\n        }\r\n\r\n    } //omp parallel\r\n\t\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "161208379d342a021479c84360a0c10bc03e35c2", "size": 52311, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "HoughForest/src/HFTrain.cpp", "max_stars_repo_name": "Ewenwan/object_detector_6d", "max_stars_repo_head_hexsha": "939a37db28eef9c00ba42ba50bf210321a99d708", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46.0, "max_stars_repo_stars_event_min_datetime": "2017-05-30T10:23:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T06:50:36.000Z", "max_issues_repo_path": "HoughForest/src/HFTrain.cpp", "max_issues_repo_name": "shengwenbo125/object_detector_6d", "max_issues_repo_head_hexsha": "939a37db28eef9c00ba42ba50bf210321a99d708", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-03-03T07:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-05T12:14:29.000Z", "max_forks_repo_path": "HoughForest/src/HFTrain.cpp", "max_forks_repo_name": "shengwenbo125/object_detector_6d", "max_forks_repo_head_hexsha": "939a37db28eef9c00ba42ba50bf210321a99d708", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2017-03-31T23:57:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-03T20:30:55.000Z", "avg_line_length": 41.2547318612, "max_line_length": 147, "alphanum_fraction": 0.5308443731, "num_tokens": 11839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2773218980182812}}
{"text": "/* \n// Copyright 2018 University of Liege\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n//     http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n// Authors:\n// - Adrien Crovato\n*/\n\n//// Interpolation from center to vertices\n// Interpolate linearly surface singularities from adjacent panel centers to panel vertices. If panel is on an edge of a\n// network, linear extrapolation is used instead\n//\n// Inputs:\n// - idG: current panel global index\n// - idC: current panel chordwise index\n// - idS: current panel spanwise index\n// - bPan: body panels (structure)\n//\n// Output:\n// - vis: Matrix of interpolate singularities (row = vertex number; col 0 = doublet, col 1 = source)\n\n#include <iostream>\n#include <Eigen/Dense>\n#include \"interp_ctv.h\"\n#include <interp.h>\n\n#define NDIM 3\n#define NV 4\n\nusing namespace std;\nusing namespace Eigen;\n\nMatrixXd interp_ctv(int idG, int idC, int idS, Network &bPan) {\n\n    //// Initialization\n    // Temporary\n    MatrixXd v; // vertices coordinates\n    v.resize(NV, NDIM);\n    MatrixXi c; // centers (corner of interpolation)\n    c.resize(NV, 4);\n    MatrixXd vis; // interpolated singularities on vertices\n    vis.resize(NV, 2);\n\n    // Store vertices coordinates\n    v.row(0) = bPan.v0.row(idG);\n    v.row(1) = bPan.v1.row(idG);\n    v.row(2) = bPan.v2.row(idG);\n    v.row(3) = bPan.v3.row(idG);\n\n    //// Compute panel center indices\n    // If panel is on the last row/column, linear extrapolation is used\n    if (idS == 0) {\n        if (idC == 0) {\n            c(0,0) = idG;\n            c(0,1) = idG + 1;\n            c(0,2) = idG + 1 + bPan.nC_;\n            c(0,3) = idG + bPan.nC_;\n            c(1,0) = idG;\n            c(1,1) = idG + 1;\n            c(1,2) = idG + 1 + bPan.nC_;\n            c(1,3) = idG + bPan.nC_;\n            c(2,0) = idG;\n            c(2,1) = idG + 1;\n            c(2,2) = idG + 1 + bPan.nC_;\n            c(2,3) = idG + bPan.nC_;\n            c(3,0) = idG;\n            c(3,1) = idG + 1;\n            c(3,2) = idG + 1 + bPan.nC_;\n            c(3,3) = idG + bPan.nC_;\n        }\n        else if (idC == bPan.nC_ - 1) {\n            c(0,0) = idG - 1;\n            c(0,1) = idG;\n            c(0,2) = idG + bPan.nC_;\n            c(0,3) = idG - 1 + bPan.nC_;\n            c(1,0) = idG - 1;\n            c(1,1) = idG;\n            c(1,2) = idG + bPan.nC_;\n            c(1,3) = idG - 1 + bPan.nC_;\n            c(2,0) = idG - 1;\n            c(2,1) = idG;\n            c(2,2) = idG + bPan.nC_;\n            c(2,3) = idG - 1 + bPan.nC_;\n            c(3,0) = idG - 1;\n            c(3,1) = idG;\n            c(3,2) = idG + bPan.nC_;\n            c(3,3) = idG - 1 + bPan.nC_;\n        }\n        else {\n            c(0,0) = idG - 1;\n            c(0,1) = idG;\n            c(0,2) = idG + bPan.nC_;\n            c(0,3) = idG - 1 + bPan.nC_;\n            c(1,0) = idG;\n            c(1,1) = idG + 1;\n            c(1,2) = idG + 1 + bPan.nC_;\n            c(1,3) = idG + bPan.nC_;\n            c(2,0) = idG;\n            c(2,1) = idG + 1;\n            c(2,2) = idG + 1 + bPan.nC_;\n            c(2,3) = idG + bPan.nC_;\n            c(3,0) = idG - 1;\n            c(3,1) = idG;\n            c(3,2) = idG + bPan.nC_;\n            c(3,3) = idG - 1 + bPan.nC_;\n        }\n    }\n    else if (idS == bPan.nS_ - 1) {\n        if (idC == 0) {\n            c(0,0) = idG - bPan.nC_;\n            c(0,1) = idG - bPan.nC_ + 1;\n            c(0,2) = idG + 1;\n            c(0,3) = idG;\n            c(1,0) = idG - bPan.nC_;\n            c(1,1) = idG - bPan.nC_ + 1;\n            c(1,2) = idG + 1;\n            c(1,3) = idG;\n            c(2,0) = idG - bPan.nC_;\n            c(2,1) = idG - bPan.nC_ + 1;\n            c(2,2) = idG + 1;\n            c(2,3) = idG;\n            c(3,0) = idG - bPan.nC_;\n            c(3,1) = idG - bPan.nC_ + 1;\n            c(3,2) = idG + 1;\n            c(3,3) = idG;\n        }\n        else if (idC == bPan.nC_ - 1) {\n            c(0,0) = idG - 1 - bPan.nC_;\n            c(0,1) = idG - bPan.nC_;\n            c(0,2) = idG;\n            c(0,3) = idG - 1;\n            c(1,0) = idG - 1 - bPan.nC_;\n            c(1,1) = idG - bPan.nC_;\n            c(1,2) = idG;\n            c(1,3) = idG - 1;\n            c(2,0) = idG - 1 - bPan.nC_;\n            c(2,1) = idG - bPan.nC_;\n            c(2,2) = idG;\n            c(2,3) = idG - 1;\n            c(3,0) = idG - 1 - bPan.nC_;\n            c(3,1) = idG - bPan.nC_;\n            c(3,2) = idG;\n            c(3,3) = idG - 1;\n        }\n        else {\n            c(0,0) = idG - 1 - bPan.nC_;\n            c(0,1) = idG - bPan.nC_;\n            c(0,2) = idG;\n            c(0,3) = idG - 1;\n            c(1,0) = idG - bPan.nC_;\n            c(1,1) = idG - bPan.nC_ + 1;\n            c(1,2) = idG + 1;\n            c(1,3) = idG;\n            c(2,0) = idG - bPan.nC_;\n            c(2,1) = idG - bPan.nC_ + 1;\n            c(2,2) = idG + 1;\n            c(2,3) = idG;\n            c(3,0) = idG - 1 - bPan.nC_;\n            c(3,1) = idG - bPan.nC_;\n            c(3,2) = idG;\n            c(3,3) = idG - 1;\n        }\n    }\n    else {\n        c(0,0) = idG - 1 - bPan.nC_;\n        c(0,1) = idG - bPan.nC_;\n        c(0,2) = idG;\n        c(0,3) = idG - 1;\n        c(1,0) = idG - bPan.nC_;\n        c(1,1) = idG - bPan.nC_ + 1;\n        c(1,2) = idG + 1;\n        c(1,3) = idG;\n        c(2,0) = idG;\n        c(2,1) = idG + 1;\n        c(2,2) = idG + 1 + bPan.nC_;\n        c(2,3) = idG + bPan.nC_;\n        c(3,0) = idG - 1;\n        c(3,1) = idG;\n        c(3,2) = idG + bPan.nC_;\n        c(3,3) = idG - 1 + bPan.nC_;\n    }\n\n    //// Interpolate each vertex\n    for (int l = 0; l < NV; l++) {\n        vis(l,0) = interp(bPan.CG(c(l,0),0), bPan.CG(c(l,0),1), bPan.CG(c(l,0),2),\n                          bPan.CG(c(l,1),0), bPan.CG(c(l,1),1), bPan.CG(c(l,1),2),\n                          bPan.CG(c(l,2),0), bPan.CG(c(l,2),1), bPan.CG(c(l,2),2),\n                          bPan.CG(c(l,3),0), bPan.CG(c(l,3),1), bPan.CG(c(l,3),2),\n                          bPan.mu(c(l,0)), bPan.mu(c(l,1)), bPan.mu(c(l,2)), bPan.mu(c(l,3)),\n                          v(l,0), v(l,1), v(l,2));\n\n        vis(l,1) = interp(bPan.CG(c(l,0),0), bPan.CG(c(l,0),1), bPan.CG(c(l,0),2),\n                          bPan.CG(c(l,1),0), bPan.CG(c(l,1),1), bPan.CG(c(l,1),2),\n                          bPan.CG(c(l,2),0), bPan.CG(c(l,2),1), bPan.CG(c(l,2),2),\n                          bPan.CG(c(l,3),0), bPan.CG(c(l,3),1), bPan.CG(c(l,3),2),\n                          bPan.tau(c(l,0)), bPan.tau(c(l,1)), bPan.tau(c(l,2)), bPan.tau(c(l,3)),\n                          v(l,0), v(l,1), v(l,2));\n    }\n    return vis;\n}", "meta": {"hexsha": "dde060881671f4349b99f41131ae2fbf8e6a6e18", "size": 6945, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/interp_ctv.cpp", "max_stars_repo_name": "acrovato/aero", "max_stars_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-11-16T15:24:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T09:36:09.000Z", "max_issues_repo_path": "src/interp_ctv.cpp", "max_issues_repo_name": "acrovato/aero", "max_issues_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/interp_ctv.cpp", "max_forks_repo_name": "acrovato/aero", "max_forks_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9146919431, "max_line_length": 120, "alphanum_fraction": 0.4217422606, "num_tokens": 2679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2772827069175985}}
{"text": "\r\n///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright 2018 John Maddock\r\n//  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_MATH_HYPERGEOMETRIC_1F1_CF_HPP\r\n#define BOOST_MATH_HYPERGEOMETRIC_1F1_CF_HPP\r\n\r\n#include <boost/math/tools/fraction.hpp>\r\n\r\n//\r\n// Evaluation of 1F1 by continued fraction\r\n// see http://functions.wolfram.com/HypergeometricFunctions/Hypergeometric1F1/10/0002/\r\n//\r\n// This is not terribly useful, as like the series we're adding a something to 1,\r\n// so only really useful when we know that the result will be > 1.\r\n//\r\n\r\n\r\n  namespace boost { namespace math { namespace detail {\r\n\r\n     template <class T>\r\n     struct hypergeometric_1F1_cf_func\r\n     {\r\n        typedef std::pair<T, T>  result_type;\r\n        hypergeometric_1F1_cf_func(T a_, T b_, T z_) : a(a_), b(b_), z(z_), k(0) {}\r\n        std::pair<T, T> operator()()\r\n        {\r\n           ++k;\r\n           return std::make_pair(-(((a + k) * z) / ((k + 1) * (b + k))), 1 + ((a + k) * z) / ((k + 1) * (b + k)));\r\n        }\r\n        T a, b, z;\r\n        unsigned k;\r\n     };\r\n\r\n     template <class T, class Policy>\r\n     T hypergeometric_1F1_cf(const T& a, const T& b, const T& z, const Policy& pol, const char* function)\r\n     {\r\n        hypergeometric_1F1_cf_func<T> func(a, b, z);\r\n        boost::uintmax_t max_iter = boost::math::policies::get_max_series_iterations<Policy>();\r\n        T result = boost::math::tools::continued_fraction_a(func, boost::math::policies::get_epsilon<T, Policy>(), max_iter);\r\n        boost::math::policies::check_series_iterations<T>(function, max_iter, pol);\r\n        return 1 + a * z / (b * (1 + result));\r\n     }\r\n\r\n  } } } // namespaces\r\n\r\n#endif // BOOST_MATH_HYPERGEOMETRIC_1F1_BESSEL_HPP\r\n", "meta": {"hexsha": "b4b25ef08ec6962f381d2e0345632d2908a4371c", "size": 1880, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/math/special_functions/detail/hypergeometric_1F1_cf.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/detail/hypergeometric_1F1_cf.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/detail/hypergeometric_1F1_cf.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": 36.862745098, "max_line_length": 126, "alphanum_fraction": 0.5962765957, "num_tokens": 526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.27715997716367324}}
{"text": "#include <map>\n#include <exception>\n#include <string>\n#include <cstdint>\n#include <iostream>\n#include <math.h>\n#include <fc/exception/exception.hpp>\n/*\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/rational.hpp>\n\n#include <sg14/fixed_point>\n#include \"fixed.hpp\"\n*/\n\n#include <fc/time.hpp>\n#include <fc/log/logger.hpp>\n\n//#include \"bfp/lib/posit.h\"\n\nusing namespace std;\n\ntypedef long double real_type;\ntypedef double token_type;\n\n\n/*\nstruct margin_position {\n   account_name owner;\n   uint64_t     exchange_id;\n   asset        lent;\n   asset        collateral;\n   uint64_t     open_time;\n\n   uint64_t     primary_key()const{ return owner; }\n   uint256_t    by_owner_ex_lent_collateral()const {\n\n   }\n\n   real_type    by_call_price()const {\n      return collateral.amount / real_type(lent.amount);\n   }\n};\n*/\n\n\n\ntemplate<typename Real>\nReal Abs(Real Nbr)\n{\n if( Nbr >= 0 )\n  return Nbr;\n else\n  return -Nbr;\n}\n\ntemplate<typename Real>\nReal sqrt_safe( const Real Nbr)\n{\n  return sqrt(Nbr);\n// cout << \" \" << Nbr << \"\\n\";;\n Real Number = Nbr / Real(2.0);\n const Real Tolerance = Real(double(1.0e-12));\n //cout << \"tol: \" << Tolerance << \"\\n\";\n\n Real Sq;\n Real Er;\n do {\n  auto tmp = Nbr / Number;\n  tmp += Number;\n  tmp /= real_type(2.0);\n  if( Number == tmp ) break;\n  Number = tmp;\n  Sq = Number * Number;\n  Er = Abs(Sq - Nbr);\n// wdump((Er.getDouble())(1.0e-8)(Tolerance.getDouble()));\n//  wdump(((Er - Tolerance).getDouble()));\n }while( Er >= Tolerance );\n\n return Number;\n}\n\ntypedef __uint128_t uint128_t;\ntypedef string  account_name;\ntypedef string  symbol_type;\n\nstatic const symbol_type exchange_symbol = \"EXC\";\n\nstruct asset {\n   token_type amount;\n   symbol_type symbol;\n};\n\nstruct margin_key {\n   symbol_type lent;\n   symbol_type collat;\n};\n\nstruct margin {\n   asset       lent;\n   symbol_type collateral_symbol;\n   real_type   least_collateralized_rate;\n};\n\nstruct user_margin {\n   asset lent;\n   asset collateral;\n\n   real_type call_price()const {\n      return collateral.amount / real_type(lent.amount);\n   }\n};\n\nstruct exchange_state;\nstruct connector {\n   asset      balance;\n   real_type  weight = 0.5;\n   token_type total_lent; /// lent from maker to users\n   token_type total_borrowed; /// borrowed from users to maker\n   token_type total_available_to_lend; /// amount available to borrow\n   token_type interest_pool; /// total interest earned but not claimed,\n                             /// each user can claim user_lent \n\n   void  borrow( exchange_state& ex, const asset& amount_to_borrow );\n   asset convert_to_exchange( exchange_state& ex, const asset& input );\n   asset convert_from_exchange( exchange_state& ex, const asset& input );\n};\n\n\nstruct balance_key {\n   account_name owner;\n   symbol_type  symbol;\n\n   friend bool operator < ( const balance_key& a, const balance_key& b ) {\n      return std::tie( a.owner, a.symbol ) < std::tie( b.owner, b.symbol );\n   }\n   friend bool operator == ( const balance_key& a, const balance_key& b ) {\n      return std::tie( a.owner, a.symbol ) == std::tie( b.owner, b.symbol );\n   }\n};\n\nreal_type fee = 1;//.9995;\n\n\nint64_t maxtrade = 20000ll;\n\nstruct exchange_state {\n   token_type  supply;\n   symbol_type symbol = exchange_symbol;\n\n   connector  base;\n   connector  quote;\n\n   void transfer( account_name user, asset q ) {\n      output[balance_key{user,q.symbol}] += q.amount;\n   }\n   map<balance_key, token_type> output; \n   vector<margin>               margins;\n};\n\n/*\nvoid  connector::borrow( exchange_state& ex, account_name user, \n                         asset amount_to_borrow, \n                         asset collateral,\n                         user_margin& marg ) {\n   FC_ASSERT( amount_to_borrow.amount < balance.amount, \"attempt to borrow too much\" );\n   lent.amount += amount_to_borrow.amount;\n   balance.amount -= amount_to_borrow.amount;\n   ex.transfer( user, amount_to_borrow ); \n\n   marg.collateral.amount += collateral.amount;\n   marg.lent.amount += amount_to_borrow.amount;\n   auto p = marg.price();\n\n   if( collateral.symbol == ex.symbol ) {\n      if( p > ex_margin.least_collateralized_rate )\n         ex_margin.least_collateralized_rate = p;\n   }\n   else if( collateral.symbol == peer_margin.collateral.symbol ) {\n      if( p > peer_margin.least_collateralized_rate )\n         peer_margin.least_collateralized_rate = p;\n   }\n}\n*/\n\nasset connector::convert_to_exchange( exchange_state& ex, const asset& input ) {\n\n   real_type R(ex.supply);\n   real_type S(balance.amount+input.amount);\n   real_type F(weight);\n   real_type T(input.amount);\n   real_type ONE(1.0);\n\n   auto E = R * (ONE - std::pow( ONE + T / S, F) );\n\n\n   //auto real_issued = real_type(ex.supply) * (sqrt_safe( 1.0 + (real_type(input.amount) / (balance.amount+input.amount))) - 1.0);\n   //auto real_issued = real_type(ex.supply) * (std::pow( 1.0 + (real_type(input.amount) / (balance.amount+input.amount)), weight) - real_type(1.0));\n   //auto real_issued = R * (std::pow( ONE + (T / S), F) - ONE);\n\n   //wdump((double(E))(double(real_issued)));\n   token_type issued = -E; //real_issued;\n   \n\n   ex.supply      += issued;\n   balance.amount += input.amount;\n\n   return asset{ issued, exchange_symbol };\n}\n\nasset connector::convert_from_exchange( exchange_state& ex, const asset& input ) {\n\n   real_type R(ex.supply - input.amount);\n   real_type S(balance.amount);\n   real_type F(weight);\n   real_type E(input.amount);\n   real_type ONE(1.0);\n\n   real_type T = S * (std::pow( ONE + E/R, ONE/F) - ONE);\n\n\n   /*\n   real_type base = real_type(1.0) + ( real_type(input.amount) / real_type(ex.supply-input.amount));\n   auto out = (balance.amount * ( std::pow(base,1.0/weight) - real_type(1.0) ));\n   */\n   auto out = T;\n\n//   edump((double(out-T))(double(out))(double(T)));\n\n   ex.supply -= input.amount;\n   balance.amount -= token_type(out);\n   return asset{ token_type(out), balance.symbol };\n}\n\n\nvoid besio_assert( bool test, const string& msg ) {\n   if( !test ) throw std::runtime_error( msg );\n}\n\nvoid print_state( const exchange_state& e );\n\n\n\n/**\n *  Given the current state, calculate the new state\n */\nexchange_state convert( const exchange_state& current,\n                        account_name user,\n                        asset        input,\n                        asset        min_output,\n                        asset*       out = nullptr) {\n\n  besio_assert( min_output.symbol != input.symbol, \"cannot convert\" );\n\n  exchange_state result(current);\n\n  asset initial_output = input;\n\n  if( input.symbol != exchange_symbol ) {\n     if( input.symbol == result.base.balance.symbol ) {\n        initial_output = result.base.convert_to_exchange( result, input );\n     }\n     else if( input.symbol == result.quote.balance.symbol ) {\n        initial_output = result.quote.convert_to_exchange( result, input );\n     }\n     else besio_assert( false, \"invalid symbol\" );\n  } else {\n     if( min_output.symbol == result.base.balance.symbol ) {\n        initial_output = result.base.convert_from_exchange( result, initial_output );\n     }\n     else if( min_output.symbol == result.quote.balance.symbol ) {\n        initial_output= result.quote.convert_from_exchange( result, initial_output );\n     }\n     else besio_assert( false, \"invalid symbol\" );\n  }\n\n\n\n  asset final_output = initial_output;\n\n//  std::cerr << \"\\n\\nconvert \" << input.amount << \" \"<< input.symbol << \"  =>  \" << final_output.amount << \" \" << final_output.symbol << \"  final: \" << min_output.symbol << \" \\n\";\n\n  result.output[ balance_key{user,final_output.symbol} ] += final_output.amount;\n  result.output[ balance_key{user,input.symbol} ] -= input.amount;\n\n  if( min_output.symbol != final_output.symbol ) {\n    return convert( result, user, final_output, min_output, out );\n  }\n\n  if( out ) *out = final_output;\n  return result;\n}\n\n/*  VALIDATE MARGIN ALGORITHM\n *\n *  Given an initial condition, verify that all margin positions can be filled. \n *\n *  Assume 3 assets, B, Q, and X and the notation LENT-COLLAT we get the following\n *  pairs:\n *\n *  B-X\n *  B-A\n *  A-X\n *  A-B\n *  X-A\n *  X-B\n *  \n *  We assume that pairs of the same lent-type have to be simultainously filled,\n *  as filling one could make it impossible to fill the other.  \n *\n *\nvoid validate_margin( exchange_state& e ) {\n   for( const auto& pos : e.margins ) {\n      token_type min_collat = pos.lent.amount * pos.least_collateralized_rate;\n      asset received;\n      e = convert( e, \"user\", asset{ min_collat, pos.first.collat }, pos.lent, &received );\n      FC_ASSERT( received > pos.lent.amount, \"insufficient collateral\" );\n\n      received.amount -= pos.lent.amount;\n      e = convert( e, \"user\", received, asset{ token_type(0), pos.collateral_symbol} );\n   }\n}\n*/\n\n\n\n\n\n/**\n *  A user has Collateral C and wishes to borrow B, so we give user B \n *  provided that C is enough to buy B back after removing it from market and\n *  that no margin calls would be triggered.  \n */\nexchange_state borrow( const exchange_state& current, account_name user,\n                       asset amount_to_borrow,\n                       asset collateral_provided ) {\n    FC_ASSERT( amount_to_borrow.symbol != collateral_provided.symbol );\n\n    /// lookup the margin position for user\n    ///   update user's margin position\n    ///   update least collateralized margin position on state\n    ///   remove amount_to_borrow from exchange \n    ///   lock collateral for user \n    /// simulate complete margin calls \n    return exchange_state();\n}\n\nexchange_state cover( const exchange_state& current, account_name user,\n                      asset amount_to_cover, asset collateral_to_cover_with )\n{\n   /// lookup existing position for user/debt/collat\n   /// verify collat > collateral_to_cover_with\n   /// sell collateral_to_cover_with for debt on market\n   /// reduce debt by proceeds\n   /// add proceeds to connector\n   //     - if borrowed from user, reduce borrowed from user\n   /// calculate new call price and update least collateralized position\n   /// simulate complete margin calls\n   return exchange_state();\n}\n\nexchange_state lend( const exchange_state& current, account_name lender,\n                     asset asset_to_lend ) {\n   /// add to pool of funds available for lending and buy SHARES in\n   ///  interest pool at current rate.  \n   return exchange_state();\n}\n\nexchange_state unlend( const exchange_state& current, account_name lender,\n                     asset asset_to_lend ) {\n    /// sell shares in interest pool at current rate\n    /// this is permitable so long as total borrowed from users remains less than\n    /// total available to lend. Otherwise, margin is called on the least \n    /// collateralized position.\n   return exchange_state();\n}\n\n\n\nvoid print_state( const exchange_state& e ) {\n   std::cerr << \"\\n-----------------------------\\n\";\n   std::cerr << \"supply: \" <<  e.supply  << \"\\n\";\n   std::cerr << \"base: \" <<  e.base.balance.amount << \" \" << e.base.balance.symbol << \"\\n\";\n   std::cerr << \"quote: \" <<  e.quote.balance.amount << \" \" << e.quote.balance.symbol << \"\\n\";\n\n   for( const auto& item : e.output ) {\n      cerr << item.first.owner << \"  \" << item.second << \" \" << item.first.symbol << \"\\n\";\n   }\n   std::cerr << \"\\n-----------------------------\\n\";\n}\n\n\nint main( int argc, char** argv ) {\n //  std::cerr << \"root: \" << double(root.numerator())/root.denominator() << \"\\n\";\n\n\n   exchange_state state;\n   state.supply = 100000000000ll;\n   //state.base.weight  = state.total_weight / 2.;\n   state.base.balance.amount = 100000000;\n   state.base.balance.symbol = \"USD\";\n   state.base.weight = .49;\n   //state.quote.weight = state.total_weight / 2.;\n   state.quote.balance.amount = state.base.balance.amount;\n   state.quote.balance.symbol = \"BTC\";\n   state.quote.weight = .51;\n\n   print_state( state );\n\n   //state = convert( state, \"dan\", asset{ 100, \"USD\"}, asset{ 0, \"BTC\" } );\n\n   auto start = fc::time_point::now();\n   for( uint32_t i = 0; i < 10000; ++i ) {\n     if( rand() % 2 == 0 )\n        state = convert( state, \"dan\", asset{ token_type(uint32_t(rand())%maxtrade), \"USD\"}, asset{ 0, \"BTC\" } );\n     else\n        state = convert( state, \"dan\", asset{ token_type(uint32_t(rand())%maxtrade), \"BTC\"}, asset{ 0, \"USD\" } );\n   }\n   for( const auto& item : state.output ) {\n      if( item.second > 0 ) {\n         if( item.first.symbol == \"USD\" )\n           state = convert( state, \"dan\", asset{ item.second, item.first.symbol}, asset{ 0, \"BTC\" } );\n         else\n           state = convert( state, \"dan\", asset{ item.second, item.first.symbol}, asset{ 0, \"USD\" } );\n        break;\n      }\n   }\n   print_state( state );\n\n   auto end = fc::time_point::now();\n   wdump((end-start));\n   /*\n   auto new_state = convert( state, \"dan\", asset{ 100, \"USD\"}, asset{ 0, \"BTC\" } );\n        new_state = convert( new_state, \"dan\", asset{ 100, \"USD\"}, asset{ 0, \"BTC\" } );\n        new_state = convert( new_state, \"dan\", asset{ 100, \"USD\"}, asset{ 0, \"BTC\" } );\n        new_state = convert( new_state, \"dan\", asset{ 100, \"USD\"}, asset{ 0, \"BTC\" } );\n        new_state = convert( new_state, \"dan\", asset{ 100, \"USD\"}, asset{ 0, \"BTC\" } );\n        new_state = convert( new_state, \"dan\", asset{ 100, \"USD\"}, asset{ 0, \"BTC\" } );\n        new_state = convert( new_state, \"dan\", asset{ 100, \"USD\"}, asset{ 0, \"BTC\" } );\n        new_state = convert( new_state, \"dan\", asset{ 100, \"USD\"}, asset{ 0, \"BTC\" } );\n        new_state = convert( new_state, \"dan\", asset{ 100, \"USD\"}, asset{ 0, \"BTC\" } );\n\n        new_state = convert( new_state, \"dan\", asset{ 100, \"BTC\"}, asset{ 0, \"USD\" } );\n        new_state = convert( new_state, \"dan\", asset{ 100, \"BTC\"}, asset{ 0, \"USD\" } );\n        new_state = convert( new_state, \"dan\", asset{ 100, \"BTC\"}, asset{ 0, \"USD\" } );\n        new_state = convert( new_state, \"dan\", asset{ 100, \"BTC\"}, asset{ 0, \"USD\" } );\n        new_state = convert( new_state, \"dan\", asset{ 100, \"BTC\"}, asset{ 0, \"USD\" } );\n        new_state = convert( new_state, \"dan\", asset{ 100, \"BTC\"}, asset{ 0, \"USD\" } );\n        new_state = convert( new_state, \"dan\", asset{ 100, \"BTC\"}, asset{ 0, \"USD\" } );\n        new_state = convert( new_state, \"dan\", asset{ 92.5-0.08-.53, \"BTC\"}, asset{ 0, \"USD\" } );\n        new_state = convert( new_state, \"dan\", asset{ 100, \"BTC\"}, asset{ 0, \"USD\" } );\n        */\n\n        //new_state = convert( new_state, \"dan\", asset{ 442+487-733+280+349+4.493+62.9, \"BTC\"}, asset{ 0, \"USD\" } );\n   /*\n   auto new_state = convert( state, \"dan\", asset{ 500, \"USD\"}, asset{ 0, \"BTC\" } );\n        new_state = convert( new_state, \"dan\", asset{ 500, \"USD\"}, asset{ 0, \"BTC\" } );\n        new_state = convert( new_state, \"dan\", asset{ 442+487, \"BTC\"}, asset{ 0, \"USD\" } );\n        */\n        /*\n        new_state = convert( new_state, \"dan\", asset{ 487, \"BTC\"}, asset{ 0, \"USD\" } );\n        new_state = convert( new_state, \"dan\", asset{ 442, \"BTC\"}, asset{ 0, \"USD\" } );\n        */\n        //new_state = convert( new_state, \"dan\", asset{ 526, \"BTC\"}, asset{ 0, \"USD\" } );\n        //new_state = convert( new_state, \"dan\", asset{ 558, \"BTC\"}, asset{ 0, \"USD\" } );\n        //new_state = convert( new_state, \"dan\", asset{ 1746, \"BTC\"}, asset{ 0, \"USD\" } );\n        /*\n        new_state = convert( new_state, \"dan\", asset{ 526, \"BTC\"}, asset{ 0, \"USD\" } );\n        new_state = convert( new_state, \"dan\", asset{ 500, \"USD\"}, asset{ 0, \"EXC\" } );\n        new_state = convert( new_state, \"dan\", asset{ 500, \"BTC\"}, asset{ 0, \"EXC\" } );\n        new_state = convert( new_state, \"dan\", asset{ 10, \"EXC\"}, asset{ 0, \"USD\" } );\n        new_state = convert( new_state, \"dan\", asset{ 10, \"EXC\"}, asset{ 0, \"BTC\" } );\n        new_state = convert( new_state, \"dan\", asset{ 500, \"USD\"}, asset{ 0, \"BTC\" } );\n        new_state = convert( new_state, \"dan\", asset{ 500, \"USD\"}, asset{ 0, \"BTC\" } );\n        new_state = convert( new_state, \"dan\", asset{ 500, \"USD\"}, asset{ 0, \"BTC\" } );\n        new_state = convert( new_state, \"dan\", asset{ 500, \"USD\"}, asset{ 0, \"BTC\" } );\n        new_state = convert( new_state, \"dan\", asset{ 2613, \"BTC\"}, asset{ 0, \"USD\" } );\n        */\n\n\n\n   /*\n   auto new_state = convert( state, \"dan\", asset{ 10, \"EXC\"}, asset{ 0, \"USD\" } );\n\n   print_state( new_state );\n\n   new_state = convert( state, \"dan\", asset{ 10, \"EXC\"}, asset{ 0, \"BTC\" } );\n   print_state( new_state );\n   new_state = convert( new_state, \"dan\", asset{ 10, \"EXC\"}, asset{ 0, \"USD\" } );\n   print_state( new_state );\n\n\n   //new_state = convert( new_state, \"dan\", asset{ 52, \"USD\"}, asset{ 0, \"EXC\" } );\n   */\n\n   return 0;\n}\n\n\n\n#if 0\n\n0. if( margin_fault )\n     Convert Least Collateral\n     if( margin fault ))\n        defer\n\nif( margin_fault ) assert( false, \"busy calling\" );\n\n1. Fill Incoming Order\n2. Check Counter Order  \n3. if( margin fault )\n   Defer Trx to finish margin call\n\n\n#endif \n", "meta": {"hexsha": "f3134ff2be6bb0a4fc93608b8e5e4cf9cac8e91d", "size": 16818, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "contracts/exchange/test_exchange.cpp", "max_stars_repo_name": "apolloaotc/src", "max_stars_repo_head_hexsha": "a4fe59d8322d2ab4eef37a4c7af8db573d230b3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-08-19T09:38:39.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-19T09:38:39.000Z", "max_issues_repo_path": "contracts/exchange/test_exchange.cpp", "max_issues_repo_name": "biteosorg/BitEOS", "max_issues_repo_head_hexsha": "ff717ff5c3684b68472691d28d0d6886469bbc27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-21T01:26:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-21T01:26:08.000Z", "max_forks_repo_path": "contracts/exchange/test_exchange.cpp", "max_forks_repo_name": "apolloaotc/src", "max_forks_repo_head_hexsha": "a4fe59d8322d2ab4eef37a4c7af8db573d230b3d", "max_forks_repo_licenses": ["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.4046242775, "max_line_length": 180, "alphanum_fraction": 0.6190985848, "num_tokens": 4573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2771450623502205}}
{"text": "\n#include <stdio.h>\n#include <rrt_planners/RandomNumbers.h>\n#include <boost/random/lagged_fibonacci.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/thread/mutex.hpp>\n#include <boost/thread/once.hpp>\n#include <boost/scoped_ptr.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <boost/math/constants/constants.hpp>\n\n/// @cond IGNORE\nnamespace\n{\n/// We use a different random number generator for the seeds of the\n/// other random generators. The root seed is from the number of\n/// nano-seconds in the current time, or given by the user.\nclass RNGSeedGenerator\n{\npublic:\n  RNGSeedGenerator()\n    : someSeedsGenerated_(false)\n    , firstSeed_((boost::uint32_t)(boost::posix_time::microsec_clock::universal_time() -\n                                   boost::posix_time::ptime(boost::date_time::min_date_time))\n                     .total_microseconds())\n    , sGen_(firstSeed_)\n    , sDist_(1, 1000000000)\n    , s_(sGen_, sDist_)\n  {\n  }\n\n  boost::uint32_t firstSeed()\n  {\n    boost::mutex::scoped_lock slock(rngMutex_);\n    return firstSeed_;\n  }\n\n  void setSeed(boost::uint32_t seed)\n  {\n    boost::mutex::scoped_lock slock(rngMutex_);\n    if (seed > 0)\n    {\n      if (someSeedsGenerated_)\n      {\n        printf(\"ERROR. Random number generation already started. Changing seed now will not lead to deterministic sampling.\");\n      }\n      else\n      {\n        // In this case, since no seeds have been generated yet, so we remember this seed\n        // as the first one.\n        firstSeed_ = seed;\n      }\n    }\n    else\n    {\n      if (someSeedsGenerated_)\n      {\n        printf(\"WARN. Random generator seed cannot be 0. Ignoring seed.\");\n        return;\n      }\n      else\n      {\n        printf(\"WARN. Random generator seed cannot be 0. Using 1 instead.\");\n        seed = 1;\n      }\n    }\n    sGen_.seed(seed);\n  }\n\n  boost::uint32_t nextSeed()\n  {\n    boost::mutex::scoped_lock slock(rngMutex_);\n    someSeedsGenerated_ = true;\n    return s_();\n  }\n\nprivate:\n  bool someSeedsGenerated_;\n  boost::uint32_t firstSeed_;\n  boost::mutex rngMutex_;\n  boost::lagged_fibonacci607 sGen_;\n  boost::uniform_int<> sDist_;\n  boost::variate_generator<boost::lagged_fibonacci607&, boost::uniform_int<> > s_;\n};\n\nstatic boost::once_flag g_once = BOOST_ONCE_INIT;\nstatic boost::scoped_ptr<RNGSeedGenerator> g_RNGSeedGenerator;\n\nvoid initRNGSeedGenerator()\n{\n  g_RNGSeedGenerator.reset(new RNGSeedGenerator());\n}\n\nRNGSeedGenerator& getRNGSeedGenerator()\n{\n  boost::call_once(&initRNGSeedGenerator, g_once);\n  return *g_RNGSeedGenerator;\n}\n}  // namespace\n/// @endcond\n\nboost::uint32_t RNG::getSeed()\n{\n  return getRNGSeedGenerator().firstSeed();\n}\n\nvoid RNG::setSeed(boost::uint32_t seed)\n{\n  getRNGSeedGenerator().setSeed(seed);\n}\n\nRNG::RNG()\n  : generator_(getRNGSeedGenerator().nextSeed())\n  , uniDist_(0, 1)\n  , normalDist_(0, 1)\n  , uni_(generator_, uniDist_)\n  , normal_(generator_, normalDist_)\n{\n}\n\ndouble RNG::halfNormalReal(double r_min, double r_max, double focus)\n{\n  assert(r_min <= r_max);\n\n  const double mean = r_max - r_min;\n  double v = gaussian(mean, mean / focus);\n\n  if (v > mean)\n    v = 2.0 * mean - v;\n  double r = v >= 0.0 ? v + r_min : r_min;\n  return r > r_max ? r_max : r;\n}\n\nint RNG::halfNormalInt(int r_min, int r_max, double focus)\n{\n  int r = (int)floor(halfNormalReal((double)r_min, (double)(r_max) + 1.0, focus));\n  return (r > r_max) ? r_max : r;\n}\n\n// From: \"Uniform Random Rotations\", Ken Shoemake, Graphics Gems III,\n//       pg. 124-132\nvoid RNG::quaternion(double value[4])\n{\n  double x0 = uni_();\n  double r1 = sqrt(1.0 - x0), r2 = sqrt(x0);\n  double t1 = 2.0 * boost::math::constants::pi<double>() * uni_(),\n         t2 = 2.0 * boost::math::constants::pi<double>() * uni_();\n  double c1 = cos(t1), s1 = sin(t1);\n  double c2 = cos(t2), s2 = sin(t2);\n  value[0] = s1 * r1;\n  value[1] = c1 * r1;\n  value[2] = s2 * r2;\n  value[3] = c2 * r2;\n}\n\n// From Effective Sampling and Distance Metrics for 3D Rigid Body Path Planning, by James\n// Kuffner, ICRA 2004\nvoid RNG::eulerRPY(double value[3])\n{\n  value[0] = boost::math::constants::pi<double>() * (-2.0 * uni_() + 1.0);\n  value[1] = acos(1.0 - 2.0 * uni_()) - boost::math::constants::pi<double>() / 2.0;\n  value[2] = boost::math::constants::pi<double>() * (-2.0 * uni_() + 1.0);\n}\n", "meta": {"hexsha": "80f9619603e1bf0b58bd9ca1fe59baef5a30cfe8", "size": 4284, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rrt_planners/src/RandomNumbers.cpp", "max_stars_repo_name": "Tutorgaming/indires_navigation", "max_stars_repo_head_hexsha": "830097ac0a3e3a64da9026518419939b509bbe71", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 90.0, "max_stars_repo_stars_event_min_datetime": "2019-07-19T13:44:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T21:39:15.000Z", "max_issues_repo_path": "rrt_planners/src/RandomNumbers.cpp", "max_issues_repo_name": "Tutorgaming/indires_navigation", "max_issues_repo_head_hexsha": "830097ac0a3e3a64da9026518419939b509bbe71", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2019-12-02T07:32:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-10T09:38:44.000Z", "max_forks_repo_path": "rrt_planners/src/RandomNumbers.cpp", "max_forks_repo_name": "Tutorgaming/indires_navigation", "max_forks_repo_head_hexsha": "830097ac0a3e3a64da9026518419939b509bbe71", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2019-05-27T14:43:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T21:39:19.000Z", "avg_line_length": 26.1219512195, "max_line_length": 126, "alphanum_fraction": 0.6505602241, "num_tokens": 1263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558604, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.27711612947756287}}
{"text": "#ifndef INHOMOGENOUSCOUPLEDPDEODESOLVER_TEMPLATED_HPP_\n#define INHOMOGENOUSCOUPLEDPDEODESOLVER_TEMPLATED_HPP_\n\n#include \"ChemChasteFeAssemblerCommon.hpp\"\n#include \"ChemChasteVolumeAssembler.hpp\"\n#include \"ChemChasteSurfaceAssembler.hpp\"\n#include \"AbstractAssemblerSolverHybrid.hpp\"\n#include \"AbstractDynamicLinearPdeSolver.hpp\"\n#include \"AbstractLinearParabolicPdeSystemForCoupledOdeSystem.hpp\"\n#include \"TetrahedralMesh.hpp\"\n#include \"BoundaryConditionsContainer.hpp\"\n#include \"AbstractInhomogenousOdeSystemForCoupledPdeSystem.hpp\"\n#include \"InhomogenousParabolicPdeForCoupledOdeSystem_templated.hpp\"\n#include \"AbstractOdeSystemForCoupledPdeSystem.hpp\"\n#include \"CvodeAdaptor.hpp\"\n#include \"BackwardEulerIvpOdeSolver.hpp\"\n#include \"Warnings.hpp\"\n#include \"VtkMeshWriter.hpp\"\n#include \"StateVariableRegister.hpp\"\n\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n\n#include <boost/shared_ptr.hpp>\n\n// Same as other class but the numberOfStateVariables to the ode terms are not all equal.\n// The ode's change on a nodal basis\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM=ELEMENT_DIM, unsigned PROBLEM_DIM=1>\nclass InhomogenousCoupledPdeOdeSolverTemplated\n    : public AbstractAssemblerSolverHybrid<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM, NORMAL>,\n      public AbstractDynamicLinearPdeSolver<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>\n{\nprivate:\n\n    /** Pointer to the mesh. */\n    AbstractTetrahedralMesh<ELEMENT_DIM, SPACE_DIM>* mpMesh;\n\n    /** The PDE system to be solved. */\n    InhomogenousParabolicPdeForCoupledOdeSystemTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>* mpPdeSystem;\n\n    /** Vector of pointers to ODE systems, defined at nodes. */\n    std::vector<AbstractInhomogenousOdeSystemForCoupledPdeSystem*> mOdeSystemsAtNodes;\n\n    /** The values of the ODE system state variables, interpolated at a quadrature point. */\n    std::vector<double> mInterpolatedOdeStateVariables;\n\n    /** The ODE solvers. */\n    std::vector<boost::shared_ptr<AbstractIvpOdeSolver>> mpOdeSolvers;\n\n    /**\n     * A sampling timestep for writing results to file. Set to\n     * PdeSimulationTime::GetPdeTimeStep() in the constructor;\n     * may be overwritten using the SetSamplingTimeStep() method.\n     */\n    double mSamplingTimeStep;\n\n    /** Whether ODE systems are present (if not, then the system comprises coupled PDEs only). */\n    bool mOdeSystemsPresent;\n\n    /** Meta results file for VTK. */\n    out_stream mpVtkMetaFile;\n\n    /**\n     * Whether the output directory should be cleared before solve or not. False by default.\n     * Can be changed when setting the output directory\n     */\n    bool mClearOutputDirectory;\n\n\n    // for calculating the total mass, interpolate the nodal solution and add to sum\n    bool mCalculateTotalMass = true;\n    \n    std::vector<double> mTotalMass = {0.0};\n\n    std::vector<double> mOldTotalMass = {0.0};\n\n\n    bool mInterpolateStateVariable = true;\n\n //   std::vector<double> mValueAtX(PROBLEM_DIM,0.0);\n\n   \n\n    // for calculating the trace over a line segment\n    bool mCalculateSliceMass = true;\n\n    unsigned mInterpolationNodeCount =0;\n\n    unsigned mNodesInElement =3;\n\n    bool mInterpolatePosition=true;\n\n  //  ChastePoint<SPACE_DIM> mX(0,0,0);\n\n    std::vector<std::vector<double>> mSliceMass;\n\n    std::vector<std::vector<double>> mSlicePositions;\n\n\n    /**\n     * Write the current results to mpVtkMetaFile.\n     */\n    void WriteVtkResultsToFile();\n\n    /**\n     * @return the term to be added to the element stiffness matrix.\n     *\n     * @param rPhi The basis functions, rPhi(i) = phi_i, i=1..numBases\n     * @param rGradPhi Basis gradients, rGradPhi(i,j) = d(phi_j)/d(X_i)\n     * @param rX The point in space\n     * @param rU The unknown as a vector, u(i) = u_i\n     * @param rGradU The gradient of the unknown as a matrix, rGradU(i,j) = d(u_i)/d(X_j)\n     * @param pElement Pointer to the element\n     */\n    c_matrix<double, PROBLEM_DIM*(ELEMENT_DIM+1), PROBLEM_DIM*(ELEMENT_DIM+1)> ComputeMatrixTerm(\n        c_vector<double, ELEMENT_DIM+1>& rPhi,\n        c_matrix<double, SPACE_DIM, ELEMENT_DIM+1>& rGradPhi,\n        ChastePoint<SPACE_DIM>& rX,\n        c_vector<double,PROBLEM_DIM>& rU,\n        c_matrix<double, PROBLEM_DIM, SPACE_DIM>& rGradU,\n        Element<ELEMENT_DIM, SPACE_DIM>* pElement);\n\n    /**\n     * @return the term to be added to the element stiffness vector.\n     *\n     * @param rPhi The basis functions, rPhi(i) = phi_i, i=1..numBases\n     * @param rGradPhi Basis gradients, rGradPhi(i,j) = d(phi_j)/d(X_i)\n     * @param rX The point in space\n     * @param rU The unknown as a vector, u(i) = u_i\n     * @param rGradU The gradient of the unknown as a matrix, rGradU(i,j) = d(u_i)/d(X_j)\n     * @param pElement Pointer to the element\n     */\n    c_vector<double, PROBLEM_DIM*(ELEMENT_DIM+1)> ComputeVectorTerm(\n        c_vector<double, ELEMENT_DIM+1>& rPhi,\n        c_matrix<double, SPACE_DIM, ELEMENT_DIM+1>& rGradPhi,\n        ChastePoint<SPACE_DIM>& rX,\n        c_vector<double,PROBLEM_DIM>& rU,\n        c_matrix<double,PROBLEM_DIM,SPACE_DIM>& rGradU,\n        Element<ELEMENT_DIM, SPACE_DIM>* pElement);\n\n    /**\n     * Reset the member variable mInterpolatedOdeStateVariables.\n     */\n    void ResetInterpolatedQuantities();\n\n    /**\n     * Update the member variable mInterpolatedOdeStateVariables by computing the\n     * interpolated value of each ODE state variable at each Gauss point.\n     *\n     * @param phiI\n     * @param pNode pointer to a Node\n     */\n    void IncrementInterpolatedQuantities(double phiI, const Node<SPACE_DIM>* pNode);\n\n    /**\n     * Initialise method: sets up the linear system (using the mesh to\n     * determine the number of unknowns per row to preallocate) if it is not\n     * already set up. Can use an initial solution as PETSc template,\n     * or base it on the mesh size.\n     *\n     * @param initialSolution Initial solution (defaults to NULL) for PETSc to use as a template.\n     */\n    void InitialiseForSolve(Vec initialSolution=NULL);\n\n    /**\n     * Completely set up the linear system that has to be solved each timestep.\n     *\n     * @param currentSolution The current solution which can be used in setting up\n     *  the linear system if needed (NULL if there isn't a current solution)\n     * @param computeMatrix Whether to compute the LHS matrix of the linear system\n     *   (mainly for dynamic solves).\n     */\n    void SetupLinearSystem(Vec currentSolution, bool computeMatrix);\n\npublic:\n\n    /**\n     * Constructor.\n     *\n     * @param pMesh pointer to the mesh\n     * @param pPdeSystem pointer to the PDE system\n     * @param pBoundaryConditions pointer to the boundary conditions.\n     * @param odeSystemsAtNodes optional vector of pointers to ODE systems, defined at nodes\n     * @param pOdeSolver optional pointer to an ODE solver (defaults to NULL)\n     */\n    InhomogenousCoupledPdeOdeSolverTemplated(TetrahedralMesh<ELEMENT_DIM, SPACE_DIM>* pMesh,\n                                    InhomogenousParabolicPdeForCoupledOdeSystemTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>* pPdeSystem,\n                                    BoundaryConditionsContainer<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>* pBoundaryConditions,\n                                    std::vector<AbstractInhomogenousOdeSystemForCoupledPdeSystem*> odeSystemsAtNodes=std::vector<AbstractInhomogenousOdeSystemForCoupledPdeSystem*>(),\n                                    std::vector<boost::shared_ptr<AbstractIvpOdeSolver>> pOdeSolvers=std::vector<boost::shared_ptr<AbstractIvpOdeSolver>>());\n\n    /**\n     * Destructor.\n     * If an ODE system is present, the pointers to the ODE system objects are deleted here.\n     */\n    ~InhomogenousCoupledPdeOdeSolverTemplated();\n\n    /**\n     * Overridden PrepareForSetupLinearSystem() method.\n     * Pass the current solution to the PDE system to the ODE system and solve it over the next timestep.\n     *\n     * @param currentPdeSolution the solution to the PDE system at the current time\n     */\n    void PrepareForSetupLinearSystem(Vec currentPdeSolution);\n\n    /**\n     * Set mOutputDirectory.\n     *\n     * @param outputDirectory the output directory to use\n     * @param clearDirectory whether to clear outputDirectory or not. Note that the actual clearing happens when you call SolveAndWriteResultsToFile().\n     *                       False by default.\n     */\n    void SetOutputDirectory(std::string outputDirectory, bool clearDirectory=false);\n\n    /**\n     * Set mSamplingTimeStep.\n     *\n     * @param samplingTimeStep the sampling timestep to use\n     */\n    void SetSamplingTimeStep(double samplingTimeStep);\n\n    /**\n     * Solve the coupled PDE/ODE system over the pre-specified time interval,\n     * and record results using mSamplingTimeStep.\n     */\n    void SolveAndWriteResultsToFile();\n\n    /**\n     * Write the solution to VTK. Called by SolveAndWriteResultsToFile().\n     *\n     * @param solution the solution of the coupled PDE/ODE system\n     * @param numTimeStepsElapsed the number of timesteps that have elapsed\n     */\n    void WriteVtkResultsToFile(Vec solution, unsigned numTimeStepsElapsed);\n\n    /**\n     * Get a pointer to the ODE system defined at a given node.\n     *\n     * @param index the global index of a node in the mpMesh\n     * @return mOdeSystemsAtNodes[index]\n     */\n    AbstractOdeSystemForCoupledPdeSystem* GetOdeSystemAtNode(unsigned index);\n\n    void ResetInterpolatedQuantitiesOnNewTimeStep();\n\n    void OutputInterpolatedQuantitiesOnTimestep();\n};\n\n///////////////////////////////////////////////////////////////////////////////////\n// Implementation\n///////////////////////////////////////////////////////////////////////////////////\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nc_matrix<double, PROBLEM_DIM*(ELEMENT_DIM+1), PROBLEM_DIM*(ELEMENT_DIM+1)> InhomogenousCoupledPdeOdeSolverTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::ComputeMatrixTerm(\n    c_vector<double, ELEMENT_DIM+1>& rPhi,\n    c_matrix<double, SPACE_DIM, ELEMENT_DIM+1>& rGradPhi,\n    ChastePoint<SPACE_DIM>& rX,\n    c_vector<double,PROBLEM_DIM>& rU,\n    c_matrix<double, PROBLEM_DIM, SPACE_DIM>& rGradU,\n    Element<ELEMENT_DIM, SPACE_DIM>* pElement)\n{\n//std::cout<<\"InhomogenousCoupledPdeOdeSolverTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::ComputeMatrixTerm( - start\"<<std::endl;\n    double timestep_inverse = PdeSimulationTime::GetPdeTimeStepInverse();\n    c_matrix<double, PROBLEM_DIM*(ELEMENT_DIM+1), PROBLEM_DIM*(ELEMENT_DIM+1)> matrix_term = zero_matrix<double>(PROBLEM_DIM*(ELEMENT_DIM+1), PROBLEM_DIM*(ELEMENT_DIM+1));\n\n    // Loop over PDEs and populate matrix_term\n    for (unsigned pde_index=0; pde_index<PROBLEM_DIM; pde_index++)\n    {\n        double this_dudt_coefficient = mpPdeSystem->ComputeDuDtCoefficientFunction(rX, pde_index);\n\n        // in general this should be looking to the domain field to determine diffusion properties, interpolation required?\n\n        c_matrix<double, SPACE_DIM, SPACE_DIM> this_pde_diffusion_term = mpPdeSystem->ComputeDiffusionTerm(rX, pde_index, pElement);\n        \n        c_matrix<double, 1*(ELEMENT_DIM+1), 1*(ELEMENT_DIM+1)> this_stiffness_matrix =\n            prod(trans(rGradPhi), c_matrix<double, SPACE_DIM, ELEMENT_DIM+1>(prod(this_pde_diffusion_term, rGradPhi)) )\n                + timestep_inverse * this_dudt_coefficient * outer_prod(rPhi, rPhi);\n\n        for (unsigned i=0; i<ELEMENT_DIM+1; i++)\n        {\n            for (unsigned j=0; j<ELEMENT_DIM+1; j++)\n            {\n                matrix_term(i*PROBLEM_DIM + pde_index, j*PROBLEM_DIM + pde_index) = this_stiffness_matrix(i,j);\n            }\n        }\n    }\n//std::cout<<\"InhomogenousCoupledPdeOdeSolverTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::ComputeMatrixTerm( - end\"<<std::endl;\n    return matrix_term;\n}\n\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nc_vector<double, PROBLEM_DIM*(ELEMENT_DIM+1)> InhomogenousCoupledPdeOdeSolverTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::ComputeVectorTerm(\n    c_vector<double, ELEMENT_DIM+1>& rPhi,\n    c_matrix<double, SPACE_DIM, ELEMENT_DIM+1>& rGradPhi,\n    ChastePoint<SPACE_DIM>& rX,\n    c_vector<double,PROBLEM_DIM>& rU,\n    c_matrix<double,PROBLEM_DIM,SPACE_DIM>& rGradU,\n    Element<ELEMENT_DIM, SPACE_DIM>* pElement)\n{\n    //std::cout<<\"InhomogenousCoupledPdeOdeSolverTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::ComputeVectorTerm( - start\"<<std::endl;\n    double timestep_inverse = PdeSimulationTime::GetPdeTimeStepInverse();\n    c_vector<double, PROBLEM_DIM*(ELEMENT_DIM+1)> vector_term;\n    vector_term = zero_vector<double>(PROBLEM_DIM*(ELEMENT_DIM+1));\n\n    // Loop over PDEs and populate vector_term\n    for (unsigned pde_index=0; pde_index<PROBLEM_DIM; pde_index++)\n    {\n        // property of the pde not the ode systems\n        double this_dudt_coefficient = mpPdeSystem->ComputeDuDtCoefficientFunction(rX, pde_index);\n\n        // property of the ode systems; returns indexed state of the interpolated state variables, odes already solved\n        double this_source_term = mpPdeSystem->ComputeSourceTerm(rX, rU, mInterpolatedOdeStateVariables, pde_index);\n\n\n        c_vector<double, ELEMENT_DIM+1> this_vector_term;\n        this_vector_term = (this_source_term + timestep_inverse*this_dudt_coefficient*rU(pde_index))* rPhi;\n\n        for (unsigned i=0; i<ELEMENT_DIM+1; i++)\n        {\n            vector_term(i*PROBLEM_DIM + pde_index) = this_vector_term(i);\n        }\n    }\n    //std::cout<<\"InhomogenousCoupledPdeOdeSolverTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::ComputeVectorTerm( - end\"<<std::endl;\n    return vector_term;\n}\n\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nvoid InhomogenousCoupledPdeOdeSolverTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::ResetInterpolatedQuantities()\n{\n    mInterpolatedOdeStateVariables.clear();\n\n    if (mOdeSystemsPresent)\n    {\n        unsigned num_state_variables = mpPdeSystem->GetStateVariableRegister()->GetNumberOfStateVariables();\n        mInterpolatedOdeStateVariables.resize(num_state_variables, 0.0);\n    }\n\n\n    // reset for interpolation of slice mass\n  //  ChastePoint<SPACE_DIM> tempX(0,0,0)\n  //  mX = tempX;\n    mInterpolationNodeCount = 0;\n\n  //  std::vector<double> temp(PROBLEM_DIM,0.0);\n\n   // mValueAtX = temp;\n\n\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nvoid InhomogenousCoupledPdeOdeSolverTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::IncrementInterpolatedQuantities(double phiI, const Node<SPACE_DIM>* pNode)\n{\n    //std::cout<<\"InhomogenousCoupledPdeOdeSolverTemplated::IncrementInterpolatedQuantities\"<<std::endl;\n    if (mOdeSystemsPresent)\n    {   \n        unsigned matchedIndex;\n        unsigned num_state_variables = mpPdeSystem->GetStateVariableRegister()->GetNumberOfStateVariables();\n        std::vector<std::string> pde_variable_register = mpPdeSystem->GetStateVariableRegister() -> GetStateVariableRegisterVector();\n\n        for (unsigned i=0; i<num_state_variables; i++)\n        {\n            // each node may not have the total number of states in the ode system\n            // select using the statevariable registers at the nodes, if state variable isn't present the value is 0\n\n            if(mOdeSystemsAtNodes[pNode->GetIndex()] -> GetStateVariableRegister() -> IsStateVariablePresent(pde_variable_register[i]))\n            {\n                matchedIndex = mOdeSystemsAtNodes[pNode->GetIndex()] -> GetStateVariableRegister() -> RetrieveStateVariableIndex(pde_variable_register[i]);\n\n                //rGetStateVariables() returns the current values of the state variables, index\n                mInterpolatedOdeStateVariables[i] += phiI * mOdeSystemsAtNodes[pNode->GetIndex()]->rGetStateVariables()[matchedIndex];\n                // rGetStateVariables if the value of the ode states variables at the nodes, size < num_state_vars in the pde system\n            }\n                                \n        }\n\n    }\n\n    if(mCalculateTotalMass)\n    {\n        // interpolate the previous timestep solution at nodes\n        // sum the interpolated value \n\n        unsigned num_state_variables = mpPdeSystem->GetStateVariableRegister()->GetNumberOfStateVariables();\n\n        ReplicatableVector current_nodal_values(this->mInitialCondition);\n\n        for (unsigned i=0; i<num_state_variables; i++)\n        {\n            mOldTotalMass[i] += phiI * current_nodal_values[PROBLEM_DIM*pNode->GetIndex()+i];\n        }\n    }\n\n    if(mInterpolatePosition)\n    {\n     //   mX.rGetLocation() += phiI*pNode->rGetLocation();\n    }\n\n    if(mInterpolateStateVariable)\n    {\n    //    ReplicatableVector current_nodal_values(this->mInitialCondition);\n\n    //    for (unsigned i=0; i<num_state_variables; i++)\n     //   {\n      //      mValueAtX[i] += phiI * current_nodal_values[PROBLEM_DIM*pNode->GetIndex()+i];\n       // }\n\n    }\n\n    mInterpolationNodeCount++;\n\n    if(mInterpolationNodeCount == mNodesInElement)\n    {\n        // position and state variable vector are fully known\n        ChastePoint<SPACE_DIM> X = AbstractFeVolumeIntegralAssembler<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM, true, true, NORMAL>::GetPosition();\n\n        c_vector<double,PROBLEM_DIM> U = AbstractFeVolumeIntegralAssembler<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM, true, true, NORMAL>::GetStateVariable();\n\n\n        if(mCalculateTotalMass)\n        {\n            for (unsigned i=0; i<PROBLEM_DIM; i++)\n            {\n                mTotalMass[i] += phiI * U[i];\n            }\n        }\n\n        \n        if(mCalculateSliceMass)\n        {\n            //std::cout<<\"y: \"<<X[1]<<std::endl;\n            if(2.85>X[1] && X[1]>2.8)\n            {\n                // store the x position and the state variable U\n                std::vector<double> thisSlicePosition;\n                std::vector<double> thisSliceMass;\n                \n                for(unsigned i=0; i<SPACE_DIM; i++)\n                {\n                    thisSlicePosition.push_back(X[i]);\n                    //std::cout<<\"x: \"<<X[i]<<std::endl;\n                }\n\n                for(unsigned j=0; j<PROBLEM_DIM; j++)\n                {\n                    thisSliceMass.push_back(U[j]);\n                }\n\n                mSlicePositions.push_back(thisSlicePosition);\n                mSliceMass.push_back(thisSliceMass);\n\n            }\n            // else ignore point\n        }\n\n    }\n\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nvoid InhomogenousCoupledPdeOdeSolverTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::InitialiseForSolve(Vec initialSolution)\n{\n    if (this->mpLinearSystem == NULL)\n    {\n        unsigned preallocation = mpMesh->CalculateMaximumContainingElementsPerProcess() + ELEMENT_DIM;\n        if (ELEMENT_DIM > 1)\n        {\n            // Highest connectivity is closed\n            preallocation--;\n        }\n        preallocation *= PROBLEM_DIM;\n\n        /*\n         * Use the current solution (ie the initial solution) as the\n         * template in the alternative constructor of LinearSystem.\n         * This is to avoid problems with VecScatter.\n         */\n        this->mpLinearSystem = new LinearSystem(initialSolution, preallocation);\n    }\n\n    assert(this->mpLinearSystem);\n    this->mpLinearSystem->SetMatrixIsSymmetric(true);\n    this->mpLinearSystem->SetKspType(\"cg\");\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nvoid InhomogenousCoupledPdeOdeSolverTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::SetupLinearSystem(Vec currentSolution, bool computeMatrix)\n{\n    this->SetupGivenLinearSystem(currentSolution, computeMatrix, this->mpLinearSystem);\n}\n\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nInhomogenousCoupledPdeOdeSolverTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::InhomogenousCoupledPdeOdeSolverTemplated(\n        TetrahedralMesh<ELEMENT_DIM, SPACE_DIM>* pMesh,\n        InhomogenousParabolicPdeForCoupledOdeSystemTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>* pPdeSystem,\n        BoundaryConditionsContainer<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>* pBoundaryConditions,\n        std::vector<AbstractInhomogenousOdeSystemForCoupledPdeSystem*> odeSystemsAtNodes,\n        std::vector<boost::shared_ptr<AbstractIvpOdeSolver>> pOdeSolvers)\n    : AbstractAssemblerSolverHybrid<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM, NORMAL>(pMesh, pBoundaryConditions),\n      AbstractDynamicLinearPdeSolver<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>(pMesh),\n      mpMesh(pMesh),\n      mpPdeSystem(pPdeSystem),\n      mOdeSystemsAtNodes(odeSystemsAtNodes),\n      mpOdeSolvers(pOdeSolvers),\n      mSamplingTimeStep(DOUBLE_UNSET),\n      mOdeSystemsPresent(false),\n      mClearOutputDirectory(false)\n{\n    this->mpBoundaryConditions = pBoundaryConditions;\n    /*\n     * If any ODE systems are passed in to the constructor, then we aren't just\n     * solving a coupled PDE system, in which case the number of ODE system objects\n     * must match the number of nodes in the finite element mesh.\n     */\n    if (!mOdeSystemsAtNodes.empty())\n    {\n        mOdeSystemsPresent = true;\n        assert(mOdeSystemsAtNodes.size() == mpMesh->GetNumNodes());\n\n        /*\n         * In this case, if an ODE solver is not explicitly passed into the \n         * constructor, then we create a default solver.\n         */\n        if (!mpOdeSolvers[0])\n        {\n#ifdef CHASTE_CVODE\n            for(unsigned i=0; i<mpOdeSolvers.size(); i++)\n            {\n                mpOdeSolvers[i].reset(new CvodeAdaptor);\n            }\n            \n#else\n            for(unsigned i=0; i<mOdeSystemsAtNodes.size(); i++)\n            {\n                mpOdeSolvers.push_back(new BackwardEulerIvpOdeSolver(mOdeSystemsAtNodes[i]->GetNumberOfStateVariables()));\n            }\n            \n#endif //CHASTE_CVODE\n        }\n    }\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nInhomogenousCoupledPdeOdeSolverTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::~InhomogenousCoupledPdeOdeSolverTemplated()\n{\n    if (mOdeSystemsPresent)\n    {\n        for (unsigned i=0; i<mOdeSystemsAtNodes.size(); i++)\n        {\n            delete mOdeSystemsAtNodes[i];\n        }\n    }\n    \n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nvoid InhomogenousCoupledPdeOdeSolverTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::PrepareForSetupLinearSystem(Vec currentPdeSolution)\n{   \n    //std::cout<<\"InhomogenousCoupledPdeOdeSolverTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::PrepareForSetupLinearSystem( - start\"<<std::endl;\n    if (mOdeSystemsPresent)\n    {\n        double time = PdeSimulationTime::GetTime();\n        double next_time = PdeSimulationTime::GetNextTime();\n        double dt = PdeSimulationTime::GetPdeTimeStep();\n\n        ReplicatableVector soln_repl(currentPdeSolution);\n        std::vector<double> current_soln_this_node(PROBLEM_DIM);\n\n        // Loop over nodes\n        for (unsigned node_index=0; node_index<mpMesh->GetNumNodes(); node_index++)\n        {   \n            // Store the current solution to the PDE system at this node\n            for (unsigned pde_index=0; pde_index<PROBLEM_DIM; pde_index++)\n            {\n                double current_soln_this_pde_this_node = soln_repl[PROBLEM_DIM*node_index + pde_index];\n\n                current_soln_this_node[pde_index] = current_soln_this_pde_this_node;\n            }\n\n            // Pass it into the ODE system at this node, of full state space dimensions\n            mOdeSystemsAtNodes[node_index]->SetPdeSolution(current_soln_this_node);\n\n            // Solve ODE system at this node\n            mpOdeSolvers[node_index]->SolveAndUpdateStateVariable(mOdeSystemsAtNodes[node_index], time, next_time, dt);\n    \n        }\n    }\n    //std::cout<<\"InhomogenousCoupledPdeOdeSolverTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::PrepareForSetupLinearSystem( - end\"<<std::endl;\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nvoid InhomogenousCoupledPdeOdeSolverTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::SetOutputDirectory(std::string outputDirectory, bool clearDirectory)\n{\n    mClearOutputDirectory = clearDirectory;\n    this->mOutputDirectory = outputDirectory;\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nvoid InhomogenousCoupledPdeOdeSolverTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::SetSamplingTimeStep(double samplingTimeStep)\n{\n    assert(samplingTimeStep >= this->mIdealTimeStep);\n    mSamplingTimeStep = samplingTimeStep;\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nvoid InhomogenousCoupledPdeOdeSolverTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::SolveAndWriteResultsToFile()\n{\n//std::cout<<\"InhomogenousCoupledPdeOdeSolverTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::SolveAndWriteResultsToFile( - start\"<<std::endl;\n    // A number of methods must have been called prior to this method\n    if (this->mOutputDirectory == \"\")\n    {\n        EXCEPTION(\"SetOutputDirectory() must be called prior to SolveAndWriteResultsToFile()\");\n    }\n    if (this->mTimesSet == false)\n    {\n        EXCEPTION(\"SetTimes() must be called prior to SolveAndWriteResultsToFile()\");\n    }\n    if (this->mIdealTimeStep <= 0.0)\n    {\n        EXCEPTION(\"SetTimeStep() must be called prior to SolveAndWriteResultsToFile()\");\n    }\n    if (mSamplingTimeStep == DOUBLE_UNSET)\n    {\n        EXCEPTION(\"SetSamplingTimeStep() must be called prior to SolveAndWriteResultsToFile()\");\n    }\n    if (!this->mInitialCondition)\n    {\n        EXCEPTION(\"SetInitialCondition() must be called prior to SolveAndWriteResultsToFile()\");\n    }\n\n//#ifdef CHASTE_VTK\n    ResetInterpolatedQuantitiesOnNewTimeStep();\n    // Create a .pvd output file\n    //std::cout<<\"outputfilehandeler: \"<<this->mOutputDirectory<<std::endl;\n\n    OutputFileHandler output_file_handler(this->mOutputDirectory, mClearOutputDirectory);\n   \n    mpVtkMetaFile = output_file_handler.OpenOutputFile(\"results.pvd\");\n    *mpVtkMetaFile << \"<?xml version=\\\"1.0\\\"?>\\n\";\n    *mpVtkMetaFile << \"<VTKFile type=\\\"Collection\\\" version=\\\"0.1\\\" byte_order=\\\"LittleEndian\\\" compressor=\\\"vtkZLibDataCompressor\\\">\\n\";\n    *mpVtkMetaFile << \"    <Collection>\\n\";\n\n    std::cout<<\"Get output loc: \"<<output_file_handler.GetChasteTestOutputDirectory()<<std::endl;\n    std::cout<<\"Get output dir full path: \"<<output_file_handler.GetOutputDirectoryFullPath()<<std::endl;\n    std::cout<<\"Get relative path: \"<<output_file_handler.GetRelativePath()<<std::endl;\n\n    // Write initial condition to VTK\n    Vec initial_condition = this->mInitialCondition;\n\n    ReplicatableVector result_repl(this->mInitialCondition);\n\n    WriteVtkResultsToFile(initial_condition, 0);\n\n    // The helper class TimeStepper deals with issues such as small final timesteps so we don't have to\n    TimeStepper stepper(this->mTstart, this->mTend, mSamplingTimeStep);\n\n\n    std::vector<std::string> p_pde_stateVariableNames = mpPdeSystem -> GetStateVariableRegister() ->GetStateVariableRegisterVector();\n    \n    \n    // make a vector of file streams to store slice values per pde dim\n    std::vector<std::shared_ptr<ofstream> > sliceMassFiles;\n    for(unsigned i=0; i<PROBLEM_DIM; i++)\n    {\n    //    std::ofstream sliceMassFile;\n     //   std::string sliceMassFilename = \"/home/chaste/testoutput/\"+this->mOutputDirectory+\"sliceMass_\"+p_pde_stateVariableNames[i]+\".csv\";\n     //   std::cout<<\"sliceMassFilename: \"<<sliceMassFilename<<std::endl;\n     //   sliceMassFile.open(sliceMassFilename);\n     //   sliceMassFiles.push_back(sliceMassFile);\n        std::shared_ptr<std::ofstream> sliceMassFile(new std::ofstream);\n        std::string sliceMassFilename = \"/home/chaste/testoutput/\"+this->mOutputDirectory+\"sliceMass_\"+p_pde_stateVariableNames[i]+\".csv\";\n        std::cout<<\"sliceMassFilename: \"<<sliceMassFilename<<std::endl;\n        sliceMassFile -> open(sliceMassFilename);\n        sliceMassFiles.push_back(sliceMassFile);\n    }\n\n    std::ofstream slicePositionFile;\n    std::string slicePositionFilename = \"/home/chaste/testoutput/\"+this->mOutputDirectory+\"slicePosition.csv\";\n    std::cout<<\"slicePositionFilename: \"<<slicePositionFilename<<std::endl;\n    slicePositionFile.open (slicePositionFilename);\n\n\n    std::ofstream sumCoeffFile;\n    std::string sumCoeffFilename = \"/home/chaste/testoutput/\"+this->mOutputDirectory+\"sumCoeff.csv\";\n    std::cout<<\"sumCoeffFilename: \"<<sumCoeffFilename<<std::endl;\n    sumCoeffFile.open (sumCoeffFilename);\n\n    for(unsigned pde_index=0; pde_index<PROBLEM_DIM; pde_index++)\n    {\n        double sumCoeff=0;\n        for(unsigned node_index=0;node_index<mpMesh->GetNumNodes();node_index++)\n        {\n            sumCoeff += result_repl[PROBLEM_DIM*node_index + pde_index];\n        }\n        sumCoeffFile << sumCoeff<<\",\";\n    }\n    sumCoeffFile <<\"\\n\";\n\n\n    std::ofstream totalMassFile;\n    std::string totalMassFilename = \"/home/chaste/testoutput/\"+this->mOutputDirectory+\"totalMass.csv\";\n    std::cout<<\"totalMassFilename: \"<<totalMassFilename<<std::endl;\n    totalMassFile.open (totalMassFilename);\n\n    std::ofstream totalMassOldFile;\n    std::string totalMassOldFilename = \"/home/chaste/testoutput/\"+this->mOutputDirectory+\"totalMassOld.csv\";\n    std::cout<<\"totalMassFilename: \"<<totalMassOldFilename<<std::endl;\n    totalMassOldFile.open (totalMassOldFilename);\n\n    std::ofstream timeFile;\n    std::string timeFilename = \"/home/chaste/testoutput/\"+this->mOutputDirectory+\"time.csv\";\n    std::cout<<\"timeFilename: \"<<timeFilename<<std::endl;\n    timeFile.open (timeFilename);\n\n\n    if(mCalculateTotalMass)\n    {\n        for(unsigned pdeNum=1; pdeNum<PROBLEM_DIM;pdeNum++)\n        {\n            mTotalMass.push_back(0.0);\n            mOldTotalMass.push_back(0.0);\n        }\n    }\n    \n    \n\n    // Main time loop, interate the stepper\n    while (!stepper.IsTimeAtEnd())\n    {   \n        // Reset start and end times\n        this->SetTimes(stepper.GetTime(), stepper.GetNextTime());\n\n        timeFile << stepper.GetTime()<<\"\\n\";\n        \n\n\n        ResetInterpolatedQuantitiesOnNewTimeStep();\n\n        \n\n        // Solve the system up to the new end time\n        Vec soln = this->Solve();\n        ReplicatableVector result_repl(soln);\n\n        // Reset the initial condition for the next timestep\n        if (this->mInitialCondition != initial_condition)\n        {\n            PetscTools::Destroy(this->mInitialCondition);\n        }\n        this->mInitialCondition = soln;\n\n        // Move forward in time\n        stepper.AdvanceOneTimeStep();\n\n        for(unsigned pde_index=0; pde_index<PROBLEM_DIM; pde_index++)\n        {\n            double sumCoeff=0;\n            for(unsigned node_index=0;node_index<mpMesh->GetNumNodes();node_index++)\n            {\n                sumCoeff += result_repl[PROBLEM_DIM*node_index + pde_index];\n            }\n            sumCoeffFile << sumCoeff<<\",\";\n        }\n        sumCoeffFile << \"\\n\";\n       \n\n\n        for(unsigned pde_index=0; pde_index<PROBLEM_DIM;pde_index++)\n        {\n           totalMassFile << mTotalMass[pde_index]<<\",\";\n        }\n        totalMassFile <<\"\\n\";\n\n        \n        for(unsigned pde_index=0; pde_index<PROBLEM_DIM;pde_index++)\n        {\n           totalMassOldFile << mOldTotalMass[pde_index]<<\",\";\n        }\n        totalMassOldFile <<\"\\n\";\n\n        // for a given timestep output the slice data\n        for(unsigned pos=0; pos<mSlicePositions.size(); pos++)\n        {\n            // take the x value of the position\n            slicePositionFile << mSlicePositions[pos][0]<<\",\";\n            for(unsigned pde_index=0; pde_index<PROBLEM_DIM; pde_index++)\n            {\n                *sliceMassFiles[pde_index] << mSliceMass[pos][pde_index]<<\",\";\n            }\n        }  \n        // set the new line for the next time trace\n        slicePositionFile << \"\\n\";\n        for(unsigned i=0; i<PROBLEM_DIM; i++)\n        {\n            *sliceMassFiles[i] << \"\\n\";\n        }\n\n\n\n\n\n        // Write solution to VTK\n        WriteVtkResultsToFile(soln, stepper.GetTotalTimeStepsTaken());\n    }\n\n\n    // close all files\n    timeFile.close();\n    sumCoeffFile.close();\n    totalMassFile.close();\n    totalMassOldFile.close();\n    slicePositionFile.close();\n    for(unsigned i=0; i<PROBLEM_DIM; i++)\n    {\n        sliceMassFiles[i]->close();\n    }\n\n\n    // Restore saved initial condition to avoid user confusion!\n    if (this->mInitialCondition != initial_condition)\n    {\n        PetscTools::Destroy(this->mInitialCondition);\n    }\n    this->mInitialCondition = initial_condition;\n\n    // Close .pvd output file\n    *mpVtkMetaFile << \"    </Collection>\\n\";\n    *mpVtkMetaFile << \"</VTKFile>\\n\";\n    mpVtkMetaFile->close();\n//#else //CHASTE_VTK\n// LCOV_EXCL_START // We only test this in weekly builds\n//    WARNING(\"VTK is not installed and is required for this functionality\");\n// LCOV_EXCL_STOP\n//#endif //CHASTE_VTK\n//std::cout<<\"InhomogenousCoupledPdeOdeSolverTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::SolveAndWriteResultsToFile( - end\"<<std::endl;\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nvoid InhomogenousCoupledPdeOdeSolverTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::WriteVtkResultsToFile(Vec solution, unsigned numTimeStepsElapsed)\n{\n\n#ifdef CHASTE_VTK\n\n    // Create a new VTK file for this time step\n    std::stringstream time;\n    time << numTimeStepsElapsed;\n    //std::cout<<this->mOutputDirectory<<std::endl;\n    VtkMeshWriter<ELEMENT_DIM, SPACE_DIM> mesh_writer(this->mOutputDirectory, \"results_\"+time.str(), false);\n    // need to ensure StateVariableRegister is defined\n  \n    std::vector<std::string> p_pde_stateVariableNames = mpPdeSystem -> GetStateVariableRegister() ->GetStateVariableRegisterVector();\n    \n    /*\n     * We first loop over PDEs. For each PDE we store the solution\n     * at each node in a vector, then pass this vector to the mesh\n     * writer.\n     */\n    ReplicatableVector solution_repl(solution);\n\n    unsigned num_nodes = mpMesh->GetNumNodes();\n    for (unsigned pde_index=0; pde_index<PROBLEM_DIM; pde_index++)\n    {\n        // Store the solution of this PDE at each node\n        std::vector<double> pde_index_data;\n        pde_index_data.resize(num_nodes, 0.0);\n        for (unsigned node_index=0; node_index<num_nodes; node_index++)\n        {\n            pde_index_data[node_index] = solution_repl[PROBLEM_DIM*node_index + pde_index];\n        }\n\n        // Add this data to the mesh writer\n        std::stringstream data_name;\n        data_name << \"PDE variable \" << p_pde_stateVariableNames[pde_index];\n        mesh_writer.AddPointData(data_name.str(), pde_index_data);\n    }\n\n    if (mOdeSystemsPresent)\n    {\n        /*\n         * We cannot loop over ODEs like PDEs, since the solutions are not\n         * stored in one place. Therefore we build up a large 'vector of\n         * vectors', then pass each component of this vector to the mesh\n         * writer.\n         */\n\n\n        std::vector<std::vector<double> > ode_data;\n        unsigned num_state_vars = mpPdeSystem -> GetStateVariableRegister() ->GetNumberOfStateVariables();\n        ode_data.resize(num_state_vars);\n        for (unsigned state_var_index=0; state_var_index<num_state_vars; state_var_index++)\n        {\n            ode_data[state_var_index].resize(num_nodes, 0.0);\n        }\n\n        for (unsigned node_index=0; node_index<num_nodes; node_index++)\n        {\n            std::vector<double> all_odes_this_node = mOdeSystemsAtNodes[node_index]->rGetStateVariables();\n            // this could be of variable size, is of only the states that the ode modifies\n\n\n            std::vector<std::string> ode_var_names = mOdeSystemsAtNodes[node_index]->GetStateVariableRegister() -> GetStateVariableRegisterVector();\n            for (unsigned ode_index=0; ode_index<ode_var_names.size(); ode_index++)\n            {\n                // for each state variable in the ode system, find and update the corresponding variable in the pde system \n                ode_data[mpPdeSystem -> GetStateVariableRegister() -> RetrieveStateVariableIndex(ode_var_names[ode_index])][node_index] = all_odes_this_node[ode_index];\n                \n            }\n\n        }\n\n        for (unsigned ode_index=0; ode_index<num_state_vars; ode_index++)\n        {\n            // ode_index is the state variable\n            std::vector<double> ode_index_data = ode_data[ode_index];\n\n            // Add this data to the mesh writer\n            std::stringstream data_name;\n            data_name << \"ODE variable \" << p_pde_stateVariableNames[ode_index];\n            mesh_writer.AddPointData(data_name.str(), ode_index_data);\n        }\n    }\n\n    mesh_writer.WriteFilesUsingMesh(*mpMesh);\n    *mpVtkMetaFile << \"        <DataSet timestep=\\\"\";\n    *mpVtkMetaFile << numTimeStepsElapsed;\n    *mpVtkMetaFile << \"\\\" group=\\\"\\\" part=\\\"0\\\" file=\\\"results_\";\n    *mpVtkMetaFile << numTimeStepsElapsed;\n    *mpVtkMetaFile << \".vtu\\\"/>\\n\";\n#endif // CHASTE_VTK\n\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nAbstractOdeSystemForCoupledPdeSystem* InhomogenousCoupledPdeOdeSolverTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::GetOdeSystemAtNode(unsigned index)\n{\n    return mOdeSystemsAtNodes[index];\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nvoid InhomogenousCoupledPdeOdeSolverTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::ResetInterpolatedQuantitiesOnNewTimeStep()\n{\n\n    if(mCalculateTotalMass)\n    {\n        // reset previous timstep value of total mass\n        std::fill(mTotalMass.begin(), mTotalMass.end(), 0.0);\n        \n        std::fill(mOldTotalMass.begin(), mOldTotalMass.end(), 0.0);\n    }\n\n    if(mCalculateSliceMass)\n    {\n        mSliceMass = std::vector<std::vector<double>> ();\n\n        mSlicePositions = std::vector<std::vector<double>> ();\n\n    }\n\n\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nvoid InhomogenousCoupledPdeOdeSolverTemplated<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::OutputInterpolatedQuantitiesOnTimestep()\n{\n\n}\n\n\n#endif\n", "meta": {"hexsha": "b317029f689af4cee75c2178989a50b5f61379db", "size": 37852, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/InhomogenousCoupledPdeOdeSolver_templated.hpp", "max_stars_repo_name": "OSS-Lab/ChemChaste", "max_stars_repo_head_hexsha": "d32c36afa1cd870512fee3cba0753d5c6faf8109", "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/InhomogenousCoupledPdeOdeSolver_templated.hpp", "max_issues_repo_name": "OSS-Lab/ChemChaste", "max_issues_repo_head_hexsha": "d32c36afa1cd870512fee3cba0753d5c6faf8109", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/InhomogenousCoupledPdeOdeSolver_templated.hpp", "max_forks_repo_name": "OSS-Lab/ChemChaste", "max_forks_repo_head_hexsha": "d32c36afa1cd870512fee3cba0753d5c6faf8109", "max_forks_repo_licenses": ["BSD-3-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.7430910952, "max_line_length": 182, "alphanum_fraction": 0.6855648314, "num_tokens": 9382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2771161230586004}}
{"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/// Implements full BTE calculations defined in beyondRTA.hpp.\n\n#include <iostream>\n#include <map>\n#include <Eigen/Dense>\n#include <Eigen/IterativeLinearSolvers>\n#include <utilities.hpp>\n#include <beyondRTA.hpp>\n\nnamespace alma {\nnamespace beyondRTA {\nEigen::MatrixXd calc_kappa(\n    const alma::Crystal_structure& poscar,\n    const alma::Gamma_grid& grid,\n    const alma::Symmetry_operations& syms,\n    const std::vector<alma::Threeph_process>& threeph_procs,\n    const std::vector<alma::Twoph_process>& twoph_procs,\n    const Eigen::Ref<const Eigen::ArrayXXd>& w0,\n    double T,\n    bool iterative,\n    boost::mpi::communicator& comm) {\n    typedef std::array<int, 3> idx_triplet;\n    typedef std::array<int, 2> idx_pair;\n\n    // GATHER INFORMATION FOR FULL BTE SYSTEM AND DECLARE SOME VARIABLES\n\n    int Ngridpoints = grid.nqpoints;\n\n    // determine number of irreducible q-points\n    int Nclasses = grid.get_nequivalences();\n\n    int Nbranches = grid.get_spectrum_at_q(0).omega.size();\n    int Ntot = Nclasses * Nbranches;\n\n    // Unknowns in the linear system\n    // (factor 3: each H unknown is a vector with x,y,z components)\n    Eigen::VectorXd H(3 * Ntot);\n\n    // stores heat capacities of the irreducible points\n    Eigen::VectorXd C(Ntot);\n    C.setConstant(0.0);\n\n    // stores relaxation times of the irreducible points\n    Eigen::VectorXd tau(Ntot);\n    tau.setConstant(0.0);\n\n    // stores phonon frequencies of the irreducible points\n    Eigen::VectorXd omega(Ntot);\n    omega.setConstant(0.0);\n\n    // stores group velocity vectors of the irreducible points\n    Eigen::MatrixXd vg(Ntot, 3);\n    vg.fill(0.0);\n\n    // table that maps a single-index value to the corresponding unknown\n    std::map<int, int> idx_to_unknown;\n\n    // table that maps an unknown to the single-index\n    std::vector<int> unknown_to_idx;\n    unknown_to_idx.resize(Ntot);\n\n    // Gamma coefficients for 3-phonon processes\n    std::map<idx_triplet, double> Gamma_plus;\n    std::map<idx_triplet, double> Gamma_minus;\n\n    // Gamma coefficients for 2-phonon processes\n    std::map<idx_pair, double> Gamma2;\n\n    // GATHER PHONON PROPERTIES FOR IRREDUCIBLE Q-POINTS\n\n    int unknownCounter = 0;\n    double C_factor = 1e27 * alma::constants::kB / Ngridpoints / poscar.V;\n\n    // scan over all equivalence classes in the grid\n\n    for (int nclass = 0; nclass < Nclasses; nclass++) {\n        int nqbase = grid.get_representative(nclass);\n        auto spectrum = grid.get_spectrum_at_q(nqbase);\n\n        for (int nbranch = 0; nbranch < Nbranches; nbranch++) {\n            // register this phonon mode in the mapping tables\n            int single_idx = nbranch * Ngridpoints + nqbase;\n            idx_to_unknown[single_idx] = unknownCounter;\n            unknown_to_idx[unknownCounter] = single_idx;\n\n            // store heat capacity\n            C(unknownCounter) = C_factor * alma::bose_einstein_kernel(\n                                               spectrum.omega[nbranch], T);\n\n            // store relaxation time\n            double mytau =\n                (w0(nbranch, nqbase) == 0.) ? 0. : (1. / w0(nbranch, nqbase));\n            tau(unknownCounter) = mytau;\n\n            // store phonon frequency\n            omega(unknownCounter) = spectrum.omega(nbranch);\n\n            // store group velocity vector\n            Eigen::Vector3d myvg = spectrum.vg.col(nbranch);\n            vg(unknownCounter, 0) = myvg(0);\n            vg(unknownCounter, 1) = myvg(1);\n            vg(unknownCounter, 2) = myvg(2);\n\n            // update unkownCounter\n            unknownCounter++;\n        }\n    }\n\n    // CALCULATE NON-RTA CONDUCTIVITY BY SOLVING LINEAR SYSTEM\n\n    // build the list of Gamma values for 2-phonon processes\n\n    for (std::size_t nproc = 0; nproc < twoph_procs.size(); nproc++) {\n        // retrieve Gamma value\n        alma::Twoph_process myprocess = twoph_procs.at(nproc);\n        double Gamma = myprocess.compute_gamma(poscar, grid);\n\n        // obtain single indices\n        int idx1 = myprocess.alpha[0] * Ngridpoints + myprocess.q[0];\n        int idx2 = myprocess.alpha[1] * Ngridpoints + myprocess.q[1];\n\n        // store Gamma value in the map\n        idx_pair key({{idx1, idx2}});\n        Gamma2[key] = Gamma;\n    } // done scanning over all 2-phonon processes\n\n    // build the list of Gamma values for 3-phonon processes\n\n    for (std::size_t nproc = 0; nproc < threeph_procs.size(); nproc++) {\n        alma::Threeph_process myprocess = threeph_procs.at(nproc);\n        double Gamma = myprocess.compute_gamma(grid, T);\n        bool gammaplus = (myprocess.type == alma::threeph_type::absorption);\n\n        // store Gamma value\n\n        int idx1 = myprocess.alpha[0] * Ngridpoints + myprocess.q[0];\n        int idx2 = myprocess.alpha[1] * Ngridpoints + myprocess.q[1];\n        int idx3 = myprocess.alpha[2] * Ngridpoints + myprocess.q[2];\n\n        idx_triplet key({{idx1, idx2, idx3}});\n\n        if (gammaplus) {\n            Gamma_plus[key] = Gamma;\n        }\n        else {\n            Gamma_minus[key] = Gamma;\n        }\n    } // done scanning over all 3-phonon processes\n\n    // build system of equations \"A*H = B\"\n\n    Eigen::MatrixXd A(3 * Ntot, 3 * Ntot);\n    A.fill(0.0);\n\n    Eigen::VectorXd B(3 * Ntot);\n\n    // x-components of omega*MFP_RTA\n    B.segment(0, Ntot) = omega.array() * tau.array() * vg.col(0).array();\n    // y-components of omega*MFP_RTA\n    B.segment(Ntot, Ntot) = omega.array() * tau.array() * vg.col(1).array();\n    // z-components of omega*MFP_RTA\n    B.segment(2 * Ntot, Ntot) = omega.array() * tau.array() * vg.col(2).array();\n\n    // contributions from 3-phonon absorption processes\n    for (auto& it3 : Gamma_plus) {\n        idx_triplet key = it3.first;\n        double Gamma = it3.second;\n\n        // obtain unknownIndex for the irreducible point\n        int rowBase = idx_to_unknown[key[0]];\n\n        // PROCESS CHILD POINT 1\n\n        // obtain unknownIndex for the parent of the non-irreducible point\n        std::size_t child_nq = key[1] % Ngridpoints;\n        std::size_t mybranch = key[1] / Ngridpoints;\n        std::size_t parent_nq = grid.getParentIdx(child_nq);\n        int colBase = idx_to_unknown[mybranch * Ngridpoints + parent_nq];\n\n        // obtain the rotation matrix that maps the child point to its\n        // irreducible parent\n        std::size_t symmID = grid.getSymIdxToParent(child_nq);\n        std::size_t symmop_idx = symmID / 2;\n        // account for time reversal if needed\n        double sign_correction = (symmID % 2 == 0) ? 1.0 : -1.0; //\n\n        Eigen::Matrix3d ROT_buffer;\n        ROT_buffer.col(0) =\n            syms.rotate_v(Eigen::Vector3d(1.0, 0.0, 0.0), symmop_idx, true);\n        ROT_buffer.col(1) =\n            syms.rotate_v(Eigen::Vector3d(0.0, 1.0, 0.0), symmop_idx, true);\n        ROT_buffer.col(2) =\n            syms.rotate_v(Eigen::Vector3d(0.0, 0.0, 1.0), symmop_idx, true);\n\n        // obtain the rotation matrix R for which H_child = R*H_parent.\n        // This is the inverse of ROT_buffer, being its transpose,\n        // corrected for sign.\n        Eigen::Matrix3d R = sign_correction * ROT_buffer.transpose();\n\n        // register contributions to the linear system\n\n        for (int nRrow = 0; nRrow < 3; nRrow++) {\n            for (int nRcol = 0; nRcol < 3; nRcol++) {\n                A(rowBase + nRrow * Ntot, colBase + nRcol * Ntot) +=\n                    R(nRrow, nRcol) * tau(rowBase) * Gamma;\n            }\n        }\n\n        // PROCESS CHILD POINT 2\n\n        // obtain unknownIndex for the parent of the non-irreducible point\n        child_nq = key[2] % Ngridpoints;\n        mybranch = key[2] / Ngridpoints;\n        parent_nq = grid.getParentIdx(child_nq);\n        colBase = idx_to_unknown[mybranch * Ngridpoints + parent_nq];\n\n        // obtain the rotation matrix that maps the child point to its\n        // irreducible parent\n        symmID = grid.getSymIdxToParent(child_nq);\n        symmop_idx = symmID / 2;\n        // account for time reversal if needed\n        sign_correction = (symmID % 2 == 0) ? 1.0 : -1.0;\n\n        ROT_buffer.col(0) =\n            syms.rotate_v(Eigen::Vector3d(1.0, 0.0, 0.0), symmop_idx, true);\n        ROT_buffer.col(1) =\n            syms.rotate_v(Eigen::Vector3d(0.0, 1.0, 0.0), symmop_idx, true);\n        ROT_buffer.col(2) =\n            syms.rotate_v(Eigen::Vector3d(0.0, 0.0, 1.0), symmop_idx, true);\n\n        // obtain the rotation matrix R for which H_child = R*H_parent.\n        // This is the inverse of ROT_buffer, being its transpose,\n        // corrected for sign.\n        R = sign_correction * ROT_buffer.transpose();\n\n        // register contributions to the linear system\n\n        for (int nRrow = 0; nRrow < 3; nRrow++) {\n            for (int nRcol = 0; nRcol < 3; nRcol++) {\n                A(rowBase + nRrow * Ntot, colBase + nRcol * Ntot) -=\n                    R(nRrow, nRcol) * tau(rowBase) * Gamma;\n            }\n        }\n    }\n\n    // contributions from 3-phonon emission processes\n\n    for (auto& it3 : Gamma_minus) {\n        idx_triplet key = it3.first;\n        double Gamma = it3.second;\n\n        // obtain unknownIndex for the irreducible point\n        int rowBase = idx_to_unknown[key[0]];\n\n        // PROCESS CHILD POINT 1\n\n        // obtain unknownIndex for the parent of the non-irreducible point\n        std::size_t child_nq = key[1] % Ngridpoints;\n        std::size_t mybranch = key[1] / Ngridpoints;\n        std::size_t parent_nq = grid.getParentIdx(child_nq);\n        int colBase = idx_to_unknown[mybranch * Ngridpoints + parent_nq];\n\n        // obtain the rotation matrix that maps the child point to its\n        // irreducible parent\n        std::size_t symmID = grid.getSymIdxToParent(child_nq);\n        std::size_t symmop_idx = symmID / 2;\n        // account for time reversal if needed\n        double sign_correction = (symmID % 2 == 0) ? 1.0 : -1.0;\n\n        Eigen::Matrix3d ROT_buffer;\n        ROT_buffer.col(0) =\n            syms.rotate_v(Eigen::Vector3d(1.0, 0.0, 0.0), symmop_idx, true);\n        ROT_buffer.col(1) =\n            syms.rotate_v(Eigen::Vector3d(0.0, 1.0, 0.0), symmop_idx, true);\n        ROT_buffer.col(2) =\n            syms.rotate_v(Eigen::Vector3d(0.0, 0.0, 1.0), symmop_idx, true);\n\n        // obtain the rotation matrix R for which H_child = R*H_parent.\n        // This is the inverse of ROT_buffer, being its transpose,\n        // corrected for sign.\n        Eigen::Matrix3d R = sign_correction * ROT_buffer.transpose();\n\n        // register contributions to the linear system\n\n        for (int nRrow = 0; nRrow < 3; nRrow++) {\n            for (int nRcol = 0; nRcol < 3; nRcol++) {\n                A(rowBase + nRrow * Ntot, colBase + nRcol * Ntot) -=\n                    0.5 * R(nRrow, nRcol) * tau(rowBase) * Gamma;\n            }\n        }\n\n        // PROCESS CHILD POINT 2\n\n        // obtain unknownIndex for the parent of the non-irreducible point\n        child_nq = key[2] % Ngridpoints;\n        mybranch = key[2] / Ngridpoints;\n        parent_nq = grid.getParentIdx(child_nq);\n        colBase = idx_to_unknown[mybranch * Ngridpoints + parent_nq];\n\n        // obtain the rotation matrix that maps the child point to its\n        // irreducible parent\n        symmID = grid.getSymIdxToParent(child_nq);\n        symmop_idx = symmID / 2;\n        // account for time reversal if needed\n        sign_correction = (symmID % 2 == 0) ? 1.0 : -1.0;\n\n        ROT_buffer.col(0) =\n            syms.rotate_v(Eigen::Vector3d(1.0, 0.0, 0.0), symmop_idx, true);\n        ROT_buffer.col(1) =\n            syms.rotate_v(Eigen::Vector3d(0.0, 1.0, 0.0), symmop_idx, true);\n        ROT_buffer.col(2) =\n            syms.rotate_v(Eigen::Vector3d(0.0, 0.0, 1.0), symmop_idx, true);\n\n        // obtain the rotation matrix R for which H_child = R*H_parent.\n        // This is the inverse of ROT_buffer, being its transpose,\n        // corrected for sign.\n        R = sign_correction * ROT_buffer.transpose();\n\n        // register contributions to the linear system\n\n        for (int nRrow = 0; nRrow < 3; nRrow++) {\n            for (int nRcol = 0; nRcol < 3; nRcol++) {\n                A(rowBase + nRrow * Ntot, colBase + nRcol * Ntot) -=\n                    0.5 * R(nRrow, nRcol) * tau(rowBase) * Gamma;\n            }\n        }\n    }\n\n    // Share the contributions from 3-phonon processes among cores and\n    // add them together.\n    if (comm.size() > 1) {\n        Eigen::MatrixXd my_A(A);\n        A.fill(0.);\n        boost::mpi::all_reduce(\n            comm, my_A.data(), my_A.size(), A.data(), std::plus<double>());\n    }\n\n    // contributions from 2-phonon processes\n    for (auto& it2 : Gamma2) {\n        idx_pair key = it2.first;\n        double Gamma = it2.second;\n\n        // obtain unknownIndex for the irreducible point\n        int rowBase = idx_to_unknown[key[0]];\n\n        // obtain unknownIndex for the parent of the non-irreducible point\n        std::size_t child_nq = key[1] % Ngridpoints;\n        std::size_t mybranch = key[1] / Ngridpoints;\n        std::size_t parent_nq = grid.getParentIdx(child_nq);\n        int colBase = idx_to_unknown[mybranch * Ngridpoints + parent_nq];\n\n        // obtain the rotation matrix that maps the child point to its\n        // irreducible parent\n        std::size_t symmID = grid.getSymIdxToParent(child_nq);\n        std::size_t symmop_idx = symmID / 2;\n        // account for time reversal if needed\n        double sign_correction = (symmID % 2 == 0) ? 1.0 : -1.0;\n\n        Eigen::Matrix3d ROT_buffer;\n        ROT_buffer.col(0) =\n            syms.rotate_v(Eigen::Vector3d(1.0, 0.0, 0.0), symmop_idx, true);\n        ROT_buffer.col(1) =\n            syms.rotate_v(Eigen::Vector3d(0.0, 1.0, 0.0), symmop_idx, true);\n        ROT_buffer.col(2) =\n            syms.rotate_v(Eigen::Vector3d(0.0, 0.0, 1.0), symmop_idx, true);\n\n        // obtain the rotation matrix R for which H_child = R*H_parent.\n        // This is the inverse of ROT_buffer (being its transpose)\n        // corrected for sign.\n        Eigen::Matrix3d R = sign_correction * ROT_buffer.transpose();\n\n        // register contributions to the linear system\n\n        for (int nRrow = 0; nRrow < 3; nRrow++) {\n            for (int nRcol = 0; nRcol < 3; nRcol++) {\n                A(rowBase + nRrow * Ntot, colBase + nRcol * Ntot) -=\n                    R(nRrow, nRcol) * tau(rowBase) * Gamma;\n            }\n        }\n    }\n\n    // diagonal elements in the system\n    for (int diag_idx = 0; diag_idx < 3 * Ntot; diag_idx++) {\n        A(diag_idx, diag_idx) += 1.0;\n    }\n\n    // Normalise each row for better numerical stability\n\n    for (int nrow = 0; nrow < 3 * Ntot; nrow++) {\n        double scale = A.row(nrow).array().abs().maxCoeff();\n        A.row(nrow) /= scale;\n        B(nrow) /= scale;\n    }\n\n    // SOLVE SYSTEM\n\n    if (iterative) {\n        Eigen::BiCGSTAB<Eigen::MatrixXd> solver;\n        solver.compute(A);\n\n        // RTA solution to be used as initial guess\n        Eigen::VectorXd H_guess(3 * Ntot);\n\n        H_guess.segment(0, Ntot) =\n            omega.array() * tau.array() * vg.col(0).array();\n        H_guess.segment(Ntot, Ntot) =\n            omega.array() * tau.array() * vg.col(1).array();\n        H_guess.segment(2 * Ntot, Ntot) =\n            omega.array() * tau.array() * vg.col(2).array();\n\n        H = solver.solveWithGuess(B, H_guess);\n    }\n\n    else {\n        H = A.partialPivLu().solve(B);\n    }\n\n    double rel_err = (A * H - B).norm() / B.norm();\n\n    if (rel_err > 1e-3) {\n        std::cout << \"alma::beyondRTA::calc_kappa > WARNING:\" << std::endl;\n        std::cout << \"solution of linear system might be unstable.\"\n                  << std::endl;\n        std::cout << \"Relative error metric = \" << rel_err << std::endl;\n    }\n\n    // PROCESS THE LINEAR SYSTEM SOLUTION\n\n    // construct \"generalised MFPs\"\n    Eigen::MatrixXd MFP_nonRTA(Ntot, 3);\n    MFP_nonRTA.col(0) = H.segment(0, Ntot).array() / omega.array();\n    MFP_nonRTA.col(1) = H.segment(Ntot, Ntot).array() / omega.array();\n    MFP_nonRTA.col(2) = H.segment(2 * Ntot, Ntot).array() / omega.array();\n\n    // fix potential NaN/Inf problems\n    for (int n = 0; n < Ntot; n++) {\n        if (omega(n) <= 0.0) {\n            MFP_nonRTA(n, 0) = 0.0;\n            MFP_nonRTA(n, 1) = 0.0;\n            MFP_nonRTA(n, 2) = 0.0;\n        }\n    }\n\n    // symmetrise obtained MFP_nonRTA\n\n    for (int nclass = 0; nclass < Nclasses; nclass++) {\n        // obtain the q-index of the class representative\n        std::size_t nq_parent = grid.get_representative(nclass);\n\n        for (int nbranch = 0; nbranch < Nbranches; nbranch++) {\n            int single_idx = nbranch * Ngridpoints + nq_parent;\n            int unknownIndex = idx_to_unknown[single_idx];\n\n            Eigen::Vector3d MFP_parent =\n                MFP_nonRTA.row(unknownIndex).transpose();\n            Eigen::Vector3d MFP_buffer =\n                grid.copy_symmetry(nq_parent, syms, MFP_parent);\n\n            MFP_nonRTA.row(unknownIndex) = MFP_buffer.transpose();\n        }\n    }\n\n    // fix potential NaN/Inf problems\n    for (int n = 0; n < Ntot; n++) {\n        if (omega(n) <= 0.0) {\n            MFP_nonRTA(n, 0) = 0.0;\n            MFP_nonRTA(n, 1) = 0.0;\n            MFP_nonRTA(n, 2) = 0.0;\n        }\n    }\n\n    // CALCULATE NON-RTA CONDUCTIVITY\n\n    Eigen::Matrix3d kappatensor;\n    kappatensor.fill(0.0);\n\n    for (int nclass = 0; nclass < Nclasses; nclass++) {\n        // obtain the q-index of the class representative\n        std::size_t nq_parent = grid.get_representative(nclass);\n\n        for (int nbranch = 0; nbranch < Nbranches; nbranch++) {\n            int single_idx = nbranch * Ngridpoints + nq_parent;\n            int unknownIndex = idx_to_unknown[single_idx];\n\n            Eigen::Vector3d MFP_parent =\n                MFP_nonRTA.row(unknownIndex).transpose();\n\n            for (auto nq_member : grid.get_equivalence(nclass)) {\n                // obtain the group velocity vector of the class member\n                Eigen::Vector3d vg_member =\n                    (grid.get_spectrum_at_q(nq_member)).vg.col(nbranch);\n\n                // obtain the rotation matrix that maps the class member\n                // to its irreducible parent\n                std::size_t symmID = grid.getSymIdxToParent(nq_member);\n                std::size_t symmop_idx = symmID / 2;\n                double sign_correction = (symmID % 2 == 0) ? 1.0 : -1.0;\n\n                Eigen::Matrix3d ROT_buffer;\n                ROT_buffer.col(0) = syms.rotate_v(\n                    Eigen::Vector3d(1.0, 0.0, 0.0), symmop_idx, true);\n                ROT_buffer.col(1) = syms.rotate_v(\n                    Eigen::Vector3d(0.0, 1.0, 0.0), symmop_idx, true);\n                ROT_buffer.col(2) = syms.rotate_v(\n                    Eigen::Vector3d(0.0, 0.0, 1.0), symmop_idx, true);\n\n                // obtain the rotation matrix R for which v_child = R*v_parent.\n                // This is the inverse of ROT_buffer, being its transpose,\n                // corrected for sign.\n                Eigen::Matrix3d R = sign_correction * ROT_buffer.transpose();\n\n                // calculate the non-RTA MFP vector of this mode\n                Eigen::Vector3d MFP_member = R * MFP_parent;\n\n                // obtain conductivity contribution\n                Eigen::Matrix3d outer =\n                    (1e-9 * MFP_member) * (1e3 * vg_member.transpose());\n                kappatensor += C(unknownIndex) * outer;\n            }\n        }\n    }\n\n    // symmetrise kappa tensor\n\n    Eigen::Matrix3d kappa_accumulated;\n    kappa_accumulated.fill(0.0);\n\n    for (std::size_t nsymm = 0; nsymm < syms.get_nsym(); nsymm++) {\n        kappa_accumulated += syms.rotate_m<double>(kappatensor, nsymm, true);\n    }\n\n    kappatensor = kappa_accumulated / static_cast<double>(syms.get_nsym());\n\n    // RETURN RESULT\n\n    return kappatensor;\n} // end of calc_kappa\n} // end of namespace beyondRTA\n} // end of namespace alma\n", "meta": {"hexsha": "f5f778a58c32639434c3b2fabbac70ee79ce852c", "size": 20408, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/beyondRTA.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/beyondRTA.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/beyondRTA.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.7711711712, "max_line_length": 80, "alphanum_fraction": 0.5959427675, "num_tokens": 5750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2771117273239299}}
{"text": "#ifndef H_trex_europa_interv_patch\n# define H_trex_europa_interv_patch\n\n#include <boost/numeric/interval.hpp>\n\nnamespace TREX {\n  namespace europa {\n\n\n    inline bool\n    intersect(EUROPA::Domain& dom, EUROPA::edouble::basis_type lb, EUROPA::edouble::basis_type ub,\n\t      EUROPA::edouble::basis_type decimal_places)\n    {\n      EUROPA::edouble const p_inf = std::numeric_limits<EUROPA::edouble>::infinity();\n      EUROPA::edouble const n_inf = std::numeric_limits<EUROPA::edouble>::minus_infinity();\n      EUROPA::edouble const prec = decimal_places;\n      \n      \n      if( lb>ub || lb>=p_inf || ub<=n_inf ) {\n\tdom.empty();\n\treturn true;\n      } else {\n\tEUROPA::edouble lo = n_inf, hi = p_inf;\n\t\n\t// std::cerr<<dom.toString()<<\" * [\"<<lb<<\", \"<<ub<<\"]\"<<std::flush;\n\t\n\tif( lb>lo ) {\n\t  lo = lb;\n\t  if( lo > dom.getUpperBound() )\n\t    lo -= prec;\n\t}\n\tif( ub<hi ) {\n\t  hi = ub;\n\t  if( hi < dom.getLowerBound() )\n\t    hi += prec;\n\t}\n\tbool ret = dom.intersect(lo, hi);\n\t\n\t// if( dom.isEmpty() )\n\t// \tstd::cerr<<\" EMPTY\"<<std::endl;\n\t// else\n\t// \tstd::cerr<<\" = \"<<dom.toString()<<std::endl;\n\t\n\treturn ret;\n      }\n    }\n\n    inline bool intersect(EUROPA::Domain &dom, EUROPA::edouble lb, EUROPA::edouble ub, \n\t\t   EUROPA::edouble::basis_type decimal_places) {\n      \n      EUROPA::edouble const prec = decimal_places;\n      \n      if( lb>dom.getUpperBound() &&\n\t  lb < std::numeric_limits<EUROPA::edouble>::infinity() )\n\tlb -= prec;\n      if( ub<dom.getLowerBound() &&\n\t  ub > std::numeric_limits<EUROPA::edouble>::minus_infinity() )\n\tub += prec;\n      \n      // std::cerr<<dom.toString()<<\" * [\"<<lb<<\", \"<<ub<<\"]\"<<std::endl;\n      return dom.intersect(lb, ub);\n    }\n  \n\n    /*\n     * A replacement to boost::rounded_arith_opp as it has a bug under clang :\n     *   - the to_int call made in the boost version needed to be replaced by \n     *     Rounding::to_int to allow the compiler know that this static method \n     *     is coming from the base class \n     */\n    template<class T, class Rounding>\n    struct my_rounded_arith_opp: Rounding {\n      void init() { this->upward(); }\n# define BOOST_DN(EXPR)\t\t\t\t\\\n      this->downward();\t\t\t\t\\\n      T r = this->force_rounding(EXPR);\t\t\\\n      this->upward();\t\t\t\t\\\n      return r\n# define BOOST_NR(EXPR)\t\t\t\t\\\n      this->to_nearest();\t\t\t\\\n      T r = this->force_rounding(EXPR);\t\t\\\n      this->upward();\t\t\t\t\\\n      return r\n# define BOOST_UP(EXPR) return this->force_rounding(EXPR)\n# define BOOST_UP_NEG(EXPR) return -this->force_rounding(EXPR)\n      template<class U> T conv_down(U const &v) { BOOST_UP_NEG(-v); }\n      template<class U> T conv_up  (U const &v) { BOOST_UP(v); }\n      T add_down(const T& x, const T& y) { BOOST_UP_NEG((-x) - y); }\n      T sub_down(const T& x, const T& y) { BOOST_UP_NEG(y - x); }\n      T mul_down(const T& x, const T& y) { BOOST_UP_NEG(x * (-y)); }\n      T div_down(const T& x, const T& y) { BOOST_UP_NEG(x / (-y)); }\n      T add_up  (const T& x, const T& y) { BOOST_UP(x + y); }\n      T sub_up  (const T& x, const T& y) { BOOST_UP(x - y); }\n      T mul_up  (const T& x, const T& y) { BOOST_UP(x * y); }\n      T div_up  (const T& x, const T& y) { BOOST_UP(x / y); }\n      T median  (const T& x, const T& y) { BOOST_NR((x + y) / 2); }\n      T sqrt_down(const T& x)\n      { BOOST_NUMERIC_INTERVAL_using_math(sqrt); BOOST_DN(sqrt(x)); }\n      T sqrt_up  (const T& x)\n      { BOOST_NUMERIC_INTERVAL_using_math(sqrt); BOOST_UP(sqrt(x)); }\n      T int_down(const T& x) { return -Rounding::to_int(-x); }\n      T int_up  (const T& x) { return Rounding::to_int(x); }\n# undef BOOST_DN\n# undef BOOST_NR\n# undef BOOST_UP\n# undef BOOST_UP_NEG\n    };\n    \n  }\n}\n\n\n#endif\n", "meta": {"hexsha": "5ccdf4711b35f5fc72697df6c172edf6e36cdd88", "size": 3642, "ext": "hh", "lang": "C++", "max_stars_repo_path": "extra/europa/extensions/interv_patch.hh", "max_stars_repo_name": "miatauro/trex2-agent", "max_stars_repo_head_hexsha": "d896f8335f3194237a8bba49949e86f5488feddb", "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": "extra/europa/extensions/interv_patch.hh", "max_issues_repo_name": "miatauro/trex2-agent", "max_issues_repo_head_hexsha": "d896f8335f3194237a8bba49949e86f5488feddb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extra/europa/extensions/interv_patch.hh", "max_forks_repo_name": "miatauro/trex2-agent", "max_forks_repo_head_hexsha": "d896f8335f3194237a8bba49949e86f5488feddb", "max_forks_repo_licenses": ["BSD-3-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.9473684211, "max_line_length": 98, "alphanum_fraction": 0.5922570016, "num_tokens": 1119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2771117214475442}}
{"text": "/**********************************************************************\n*  Copyright (c) 2008-2016, Alliance for Sustainable Energy.  \n*  All rights reserved.\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 Street, Fifth Floor, Boston, MA  02110-1301  USA\n**********************************************************************/\n\n#include \"Geometry.hpp\"\n#include \"Intersection.hpp\"\n#include \"../data/Matrix.hpp\"\n#include \"../core/Assert.hpp\"\n#include \"../core/Logger.hpp\"\n\n#undef BOOST_UBLAS_TYPE_CHECK\n#include <boost/geometry/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/ring.hpp>\n#include <boost/geometry/multi/geometries/multi_polygon.hpp>\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\n#include <boost/geometry/strategies/cartesian/point_in_poly_franklin.hpp> \n#include <boost/geometry/strategies/cartesian/point_in_poly_crossings_multiply.hpp> \n#include <boost/geometry/algorithms/within.hpp> \n\ntypedef boost::geometry::model::d2::point_xy<double> BoostPoint;\ntypedef boost::geometry::model::polygon<BoostPoint> BoostPolygon;\ntypedef boost::geometry::model::ring<BoostPoint> BoostRing;\ntypedef boost::geometry::model::multi_polygon<BoostPolygon> BoostMultiPolygon;\n\n#include <polypartition/polypartition.h>\n\n#include <list>\n\n// remove_spikes \n// adapted from https://github.com/boostorg/geometry/commits/develop/include/boost/geometry/algorithms/remove_spikes.hpp eb3260708eb241d8da337f4be73b41d69d33cd09\n\n/*\nRemove spikes from a ring/polygon.\nRing (having 8 vertices, including closing vertex)\n+------+\n| |\n| +--+\n| | ^this \"spike\" is removed, can be located outside/inside the ring\n+------+\n(the actual determination if it is removed is done by a strategy)\n\n*/\n\nnamespace openstudio {\n\n  template <typename Point1, typename Point2, typename Point3>\n  static inline bool point_is_spike_or_equal(Point1 const& last_point, Point2 const& segment_a, Point3 const& segment_b)\n  {\n    // adapted from boost\\geometry\\algorithms\\detail\\point_is_spike_or_equal.hpp to include tolerance checking\n\n    // segment_a is at the beginning\n    // segment_b is in the middle\n    // last_point is at the end\n\n    // segment_b is being considered for deletion\n\n    double normTol = 0.001; // 1 mm\n    double tol = 0.001; // relative to 1\n      \n    double diff1_x = last_point.x()-segment_b.x();\n    double diff1_y = last_point.y()-segment_b.y();\n    double norm1 = sqrt(pow(diff1_x, 2) + pow(diff1_y, 2)); \n    if (norm1 > normTol){\n      diff1_x = diff1_x/norm1;\n      diff1_y = diff1_y/norm1;\n    }else{\n      // last point is too close to segment b\n      return true;\n    }\n\n    double diff2_x = segment_b.x()-segment_a.x();\n    double diff2_y = segment_b.y()-segment_a.y();\n    double norm2 = sqrt(pow(diff2_x, 2) + pow(diff2_y, 2));\n    if (norm2 > normTol){\n      diff2_x = diff2_x/norm2;\n      diff2_y = diff2_y/norm2;\n    }else{\n      // segment b is too close to segment a\n      return true;\n    }\n\n    double crossProduct = diff1_x*diff2_y-diff1_y*diff2_x;\n    if (abs(crossProduct) < tol){\n      double dotProduct = diff1_x*diff2_x+diff1_y*diff2_y;\n      if (dotProduct <= -1.0 + tol){\n        // reversal\n        return true;\n      }\n    }\n\n    return false;\n  }\n\n}\n\nnamespace boost { namespace geometry\n{\n\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace remove_spikes\n{\n\n\ntemplate <typename Range>\nstruct range_remove_spikes\n{\n    typedef typename strategy::side::services::default_strategy\n    <\n        typename cs_tag<Range>::type\n    >::type side_strategy;\n\n    typedef typename coordinate_type<Range>::type coordinate_type;\n    typedef typename point_type<Range>::type point_type;\n\n\n    static inline void apply(Range& range)\n    {\n        std::size_t n = boost::size(range);\n        std::size_t const min_num_points = core_detail::closure::minimum_ring_size\n            <\n                geometry::closure<Range>::value\n            >::value;\n        if (n < min_num_points)\n        {\n            return;\n        }\n\n        std::deque<point_type> cleaned;\n        for (typename boost::range_iterator<Range const>::type it = boost::begin(range);\n            it != boost::end(range); ++it)\n        {\n            // Add point\n            cleaned.push_back(*it);\n\n            while(cleaned.size() >= 3\n                    && openstudio::point_is_spike_or_equal(cleaned.back(), *(cleaned.end() - 3), *(cleaned.end() - 2)))\n            {\n                // Remove pen-ultimate point causing the spike (or which was equal)\n                cleaned.erase(cleaned.end() - 2);\n            }\n        }\n\n        // For a closed-polygon, remove closing point, this makes checking first point(s) easier and consistent\n        if (geometry::closure<Range>::value == geometry::closed)\n        {\n            cleaned.pop_back();\n        }\n\n        bool found = false;\n        do\n        {\n            found = false;\n            // Check for spike in first point\n            int const penultimate = 2;\n            while(cleaned.size() > 3 && openstudio::point_is_spike_or_equal(cleaned.front(), *(cleaned.end() - penultimate), cleaned.back()))\n            {\n                cleaned.pop_back();\n                found = true;\n            }\n            // Check for spike in second point\n            while(cleaned.size() > 3 && openstudio::point_is_spike_or_equal(*(cleaned.begin() + 1), cleaned.back(), cleaned.front()))\n            {\n                cleaned.pop_front();\n                found = true;\n            }\n        }\n        while (found);\n\n        // Close if necessary\n        if (geometry::closure<Range>::value == geometry::closed)\n        {\n            cleaned.push_back(cleaned.front());\n        }\n\n        // Copy output\n        geometry::clear(range);\n        std::copy(cleaned.begin(), cleaned.end(), std::back_inserter(range));\n    }\n};\n\n\ntemplate <typename Polygon>\nstruct polygon_remove_spikes\n{\n    static inline void apply(Polygon& polygon)\n    {\n        typedef typename geometry::ring_type<Polygon>::type ring_type;\n\n        typedef range_remove_spikes<ring_type> per_range;\n        per_range::apply(exterior_ring(polygon));\n\n        typename interior_return_type<Polygon>::type rings\n                    = interior_rings(polygon);\n        for (BOOST_AUTO_TPL(it, boost::begin(rings)); it != boost::end(rings); ++it)\n        {\n            per_range::apply(*it);\n        }\n    }\n};\n\n\n}} // namespace detail::remove_spikes\n#endif // DOXYGEN_NO_DETAIL\n\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 remove_spikes\n{\n    static inline void apply(Geometry&)\n    {}\n};\n\n\ntemplate <typename Ring>\nstruct remove_spikes<Ring, ring_tag>\n    : detail::remove_spikes::range_remove_spikes<Ring>\n{};\n\n\n\ntemplate <typename Polygon>\nstruct remove_spikes<Polygon, polygon_tag>\n    : detail::remove_spikes::polygon_remove_spikes<Polygon>\n{};\n\n\n\n} // namespace dispatch\n#endif\n\n\nnamespace resolve_variant {\n\ntemplate <typename Geometry>\nstruct remove_spikes\n{\n    static void apply(Geometry& geometry)\n    {\n        concept::check<Geometry>();\n        dispatch::remove_spikes<Geometry>::apply(geometry);\n    }\n};\n\ntemplate <BOOST_VARIANT_ENUM_PARAMS(typename T)>\nstruct remove_spikes<boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> >\n{\n    struct visitor: boost::static_visitor<void>\n    {\n        template <typename Geometry>\n        void operator()(Geometry& geometry) const\n        {\n            remove_spikes<Geometry>::apply(geometry);\n        }\n    };\n\n    static inline void apply(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)>& geometry)\n    {\n        boost::apply_visitor(visitor(), geometry);\n    }\n};\n\n} // namespace resolve_variant\n\n\n/*!\n\\ingroup remove_spikes\n\\tparam Geometry geometry type\n\\param geometry the geometry to make remove_spikes\n*/\ntemplate <typename Geometry>\ninline void remove_spikes(Geometry& geometry)\n{\n    resolve_variant::remove_spikes<Geometry>::apply(geometry);\n}\n\n\n}} // namespace boost::geometry\n// remove_spikes \n\n\nnamespace openstudio{\n\n  // Private implementation functions\n\n  BoostPolygon removeSpikes(const BoostPolygon& polygon)\n  {\n    BoostPolygon temp(polygon);\n    boost::geometry::remove_spikes(temp);\n    return temp;\n  }\n\n  std::vector<BoostPolygon> removeSpikes(const std::vector<BoostPolygon>& polygons)\n  {\n    std::vector<BoostPolygon> result;\n    for (const BoostPolygon& polygon : polygons){\n      result.push_back(removeSpikes(polygon));\n    }\n    return result;\n  }\n\n  std::vector<BoostPolygon> removeHoles(const BoostPolygon& boostPolygon)\n  {\n    std::vector<BoostPolygon> result;\n\n    // convert to vector of TPPLPoly\n    std::list<TPPLPoly> polys;\n\n    BoostRing outer = boostPolygon.outer();\n    TPPLPoly outerPoly; // must be counter-clockwise\n    outerPoly.Init(outer.size() - 1);\n    outerPoly.SetHole(false);\n    //std::cout << \"outer :\";\n    for(unsigned i = 0; i < outer.size() - 1; ++i){\n      outerPoly[i].x = outer[i].x();\n      outerPoly[i].y = outer[i].y();\n      //std::cout << \"(\" << outer[i].x() << \", \" << outer[i].y() << \") \";\n    }\n    //std::cout << std::endl;\n    outerPoly.SetOrientation(TPPL_CCW);\n    polys.push_back(outerPoly);\n\n    std::vector<BoostRing> inners = boostPolygon.inners();\n    for (const BoostRing& inner : inners){\n      TPPLPoly innerPoly; // must be clockwise\n      innerPoly.Init(inner.size() - 1);\n      innerPoly.SetHole(true);\n      //std::cout << \"inner :\";\n      for(unsigned i = 0; i < inner.size() - 1; ++i){\n        innerPoly[i].x = inner[i].x();\n        innerPoly[i].y = inner[i].y();\n        //std::cout << \"(\" << inner[i].x() << \", \" << inner[i].y() << \") \";\n      }\n      //std::cout << std::endl;\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.ConvexPartition_HM(&polys,&resultPolys);\n    if (test == 0){\n      LOG_FREE(Error, \"utilities.geometry.removeHoles\", \"Failed to partition polygon\");\n      return result;\n    }\n\n    // convert back to BoostPolygon\n    std::list<TPPLPoly>::iterator it, itend;\n    for(it = resultPolys.begin(), itend = resultPolys.end(); it != itend; ++it){\n      BoostPolygon newBoostPolygon;\n      //std::cout << \"result :\";\n      for (long i = 0; i < it->GetNumPoints(); ++i){\n        TPPLPoint point = it->GetPoint(i);\n        boost::geometry::append(newBoostPolygon, boost::make_tuple(point.x, point.y));\n        //std::cout << \"(\" << point.x << \", \" << point.y << \") \";\n      }\n      TPPLPoint point = it->GetPoint(0);\n      boost::geometry::append(newBoostPolygon, boost::make_tuple(point.x, point.y));\n      //std::cout << \"(\" << point.x << \", \" << point.y << \") \";\n      //std::cout << std::endl;\n\n      boost::geometry::correct(newBoostPolygon);\n      result.push_back(newBoostPolygon);\n    }\n\n    return result;\n  }\n\n  std::vector<BoostPolygon> removeHoles(const std::vector<BoostPolygon>& polygons)\n  {\n    std::vector<BoostPolygon> result;\n    for (const BoostPolygon polygon : polygons){\n      if (polygon.inners().empty()){\n        // DLM: might also want to partition if this polygon is self intersecting?\n        result.push_back(polygon);\n      }else{\n        std::vector<BoostPolygon> temp = removeHoles(polygon); \n        result.insert(result.end(), temp.begin(), temp.end());\n      }\n    }\n    return result;\n  }\n\n  // convert a Point3d to a BoostPoint\n  boost::tuple<double, double> boostPointFromPoint3d(const Point3d& point3d, std::vector<Point3d>& allPoints, double tol)\n  {\n    OS_ASSERT(abs(point3d.z()) <= tol);\n\n    // simple method\n    //return boost::make_tuple(point3d.x(), point3d.y());\n\n    // detailed method, try to combine points within tolerance\n    Point3d resultPoint = getCombinedPoint(point3d, allPoints, tol);\n\n    return boost::make_tuple(resultPoint.x(), resultPoint.y());\n  }\n\n  // convert vertices to a boost polygon, all vertices must lie on z = 0 plane\n  boost::optional<BoostPolygon> boostPolygonFromVertices(const std::vector<Point3d>& vertices, std::vector<Point3d>& allPoints, double tol)\n  {\n    if (vertices.size () < 3){\n      return boost::none;\n    }\n\n    BoostPolygon polygon;\n    for (const Point3d& vertex : vertices){\n\n      // should all have zero z coordinate now\n      double z = vertex.z();\n      if (abs(z) > tol){\n        LOG_FREE(Error, \"utilities.geometry.boostPolygonFromVertices\", \"All points must be on z = 0 plane\");\n        return boost::none;\n      }\n\n      // use helper method which combines close points\n      boost::geometry::append(polygon, boostPointFromPoint3d(vertex, allPoints, tol));\n    }\n\n    // close polygon, use helper method which combines close points\n    boost::geometry::append(polygon, boostPointFromPoint3d(vertices[0], allPoints, tol));\n\n    //boost::geometry::correct(polygon);\n\n    boost::optional<double> testArea = boost::geometry::area(polygon);\n    if (!testArea || (*testArea < 0)){\n      // DLM: we could offer to reverse these vertices here but that might not be the best idea\n      return boost::none;\n    }\n\n    return polygon;\n  }\n\n  boost::optional<BoostPolygon> nonIntersectingBoostPolygonFromVertices(const std::vector<Point3d>& polygon, std::vector<Point3d>& allPoints, double tol)\n  {\n    boost::optional<BoostPolygon> result = boostPolygonFromVertices(polygon, allPoints, tol);\n    if (!result){\n      return boost::none;\n    }\n    // check if polygon overlaps itself\n    try{\n      boost::geometry::detail::overlay::has_self_intersections(*result);\n    }catch(const boost::geometry::overlay_invalid_input_exception&){\n      //LOG_FREE(Error, \"utilities.geometry.nonIntersectingBoostPolygonFromVertices\", \"Self intersecting polygon\");\n      return boost::none;\n    }\n    return result;\n  }\n\n  // convert vertices to a boost ring, all vertices must lie on z = 0 plane\n  boost::optional<BoostRing> boostRingFromVertices(const std::vector<Point3d>& vertices, std::vector<Point3d>& allPoints, double tol)\n  {\n    if (vertices.size () < 3){\n      return boost::none;\n    }\n\n    BoostRing ring;\n    for (const Point3d& vertex : vertices){\n\n      // should all have zero z coordinate now\n      double z = vertex.z();\n      if (abs(z) > tol){\n        LOG_FREE(Error, \"utilities.geometry.boostRingFromVertices\", \"All points must be on z = 0 plane\");\n        return boost::none;\n      }\n\n      // use helper method which combines close points\n      boost::geometry::append(ring, boostPointFromPoint3d(vertex, allPoints, tol));\n    }\n\n    // close polygon, use helper method which combines close points\n    boost::geometry::append(ring, boostPointFromPoint3d(vertices[0], allPoints, tol));\n\n    //boost::geometry::correct(ring);\n\n    boost::optional<double> testArea = boost::geometry::area(ring);\n    if (!testArea || (*testArea < 0)){\n      // DLM: we could offer to reverse these vertices here but that might not be the best idea\n      return boost::none;\n    }\n\n    return ring;\n  }\n\n  boost::optional<BoostRing> nonIntersectingBoostRingFromVertices(const std::vector<Point3d>& polygon, std::vector<Point3d>& allPoints, double tol)\n  {\n    boost::optional<BoostRing> result = boostRingFromVertices(polygon, allPoints, tol);\n    if (!result){\n      return boost::none;\n    }\n    // check if polygon overlaps itself\n    try{\n      boost::geometry::detail::overlay::has_self_intersections(*result);\n    }catch(const boost::geometry::overlay_invalid_input_exception&){\n      //LOG_FREE(Error, \"utilities.geometry.nonIntersectingBoostRingFromVertices\", \"Self intersecting polygon\");\n      return boost::none;\n    }\n    return result;\n  }\n\n  // convert a boost polygon to vertices\n  std::vector<Point3d> verticesFromBoostPolygon(const BoostPolygon& polygon, std::vector<Point3d>& allPoints, double tol)\n  {\n    std::vector<Point3d> result;\n\n    BoostRing outer = polygon.outer();\n    if (outer.empty()){\n      return result;\n    }\n    \n    // add point for each vertex except final vertex\n    for(unsigned i = 0; i < outer.size() - 1; ++i){\n      Point3d point3d(outer[i].x(), outer[i].y(), 0.0);\n      \n      // try to combine points within tolerance\n      Point3d resultPoint = getCombinedPoint(point3d, allPoints, tol);\n\n      // don't keep repeated vertices\n      if ((i > 0) && (result.back() == resultPoint)){\n        continue;\n      }\n      result.push_back(resultPoint);\n    }\n\n    OS_ASSERT(polygon.inners().empty());\n\n    result = removeCollinear(result);\n\n    // don't keep repeated vertices\n    if (result.front() == result.back()){\n      result.pop_back();\n    }\n\n    if (result.size() < 3){\n      return std::vector<Point3d>();\n    }\n\n    return result;\n  }\n\n  // convert a boost ring to vertices\n  std::vector<Point3d> verticesFromBoostRing(const BoostRing& ring, std::vector<Point3d>& allPoints, double tol)\n  {\n    std::vector<Point3d> result;\n\n    // add point for each vertex except final vertex\n    for (unsigned i = 0; i < ring.size() - 1; ++i){\n      Point3d point3d(ring[i].x(), ring[i].y(), 0.0);\n\n      // try to combine points within tolerance\n      Point3d resultPoint = getCombinedPoint(point3d, allPoints, tol);\n\n      // don't keep repeated vertices\n      if ((i > 0) && (result.back() == resultPoint)){\n        continue;\n      }\n      result.push_back(resultPoint);\n    }\n\n    result = removeCollinear(result);\n\n    // don't keep repeated vertices\n    if (result.front() == result.back()){\n      result.pop_back();\n    }\n\n    if (result.size() < 3){\n      return std::vector<Point3d>();\n    }\n\n    return result;\n  }\n\n  // struct used to sort polygons in descending order by area\n  struct BoostPolygonAreaGreater{\n    bool operator()(const BoostPolygon& left, const BoostPolygon& right){\n      boost::optional<double> leftA = boost::geometry::area(left);\n      if (!leftA){\n        leftA = 0;\n      }\n      boost::optional<double> rightA = boost::geometry::area(right);\n      if (!rightA){\n        rightA = 0;\n      }\n      return (*leftA > *rightA);\n    }\n  };\n\n  // Public functions\n  \n  IntersectionResult::IntersectionResult(const std::vector<Point3d>& polygon1, \n                                         const std::vector<Point3d>& polygon2, \n                                         const std::vector< std::vector<Point3d> >& newPolygons1, \n                                         const std::vector< std::vector<Point3d> >& newPolygons2)\n    : m_polygon1(polygon1), m_polygon2(polygon2), m_newPolygons1(newPolygons1), m_newPolygons2(newPolygons2)\n  {\n  }\n\n  std::vector<Point3d> IntersectionResult::polygon1() const\n  {\n    return m_polygon1;\n  }\n\n  std::vector<Point3d> IntersectionResult::polygon2() const\n  {\n    return m_polygon2;\n  }\n\n  std::vector< std::vector<Point3d> > IntersectionResult::newPolygons1() const\n  {\n    return m_newPolygons1;\n  }\n\n  std::vector< std::vector<Point3d> > IntersectionResult::newPolygons2() const\n  {\n    return m_newPolygons2;\n  }\n  \n  std::vector<Point3d> removeSpikes(const std::vector<Point3d>& polygon, double tol)\n  {\n    // convert vertices to boost rings\n    std::vector<Point3d> allPoints;\n    \n    boost::optional<BoostPolygon> boostPolygon = boostPolygonFromVertices(polygon, allPoints, tol);\n    if (!boostPolygon){\n      return std::vector<Point3d>();\n    }\n\n    BoostPolygon boostResult = removeSpikes(*boostPolygon);\n\n    std::vector<Point3d> result = verticesFromBoostPolygon(boostResult, allPoints, tol);\n\n    return result;\n  }\n  \n  bool pointInPolygon(const Point3d& point, const std::vector<Point3d>& polygon, double tol)\n  {\n    // convert vertices to boost rings\n    std::vector<Point3d> allPoints;\n    \n    boost::optional<BoostRing> boostPolygon = nonIntersectingBoostRingFromVertices(polygon, allPoints, tol);\n    if (!boostPolygon){\n      return false;\n    }\n\n    if (abs(point.z()) > tol){\n      return false;\n    }\n\n    boost::tuple<double, double> p = boostPointFromPoint3d(point, allPoints, tol);\n    BoostPoint boostPoint(p.get<0>(), p.get<1>());\n\n    //boost::geometry::strategy::within::winding<BoostPoint> strategy;\n    //boost::geometry::strategy::within::franklin<BoostPoint> strategy;\n    //boost::geometry::strategy::within::crossings_multiply<BoostPoint> strategy;\n    //bool result = boost::geometry::within(boostPoint, *boostPolygon, strategy);\n\n    //bool result = boost::geometry::intersects(boostPoint, *boostPolygon);\n\n    //bool result = boost::geometry::overlaps(boostPoint, *boostPolygon);\n\n    double distance = boost::geometry::distance(boostPoint, *boostPolygon);\n    bool result = (distance <= 0.0001);\n\n    return result; \n      \n  }\n\n  boost::optional<std::vector<Point3d> > join(const std::vector<Point3d>& polygon1, const std::vector<Point3d>& polygon2, double tol)\n  {\n    // convert vertices to boost rings\n    std::vector<Point3d> allPoints;\n    \n    boost::optional<BoostRing> boostPolygon1 = nonIntersectingBoostRingFromVertices(polygon1, allPoints, tol);\n    if (!boostPolygon1){\n      return boost::none;\n    }\n\n    boost::optional<BoostRing> boostPolygon2 = nonIntersectingBoostRingFromVertices(polygon2, allPoints, tol);\n    if (!boostPolygon2){\n      return boost::none;\n    }\n\n    // union the points in face coordinates, \n    std::vector<BoostPolygon> unionResult;\n    try{\n      boost::geometry::union_(*boostPolygon1, *boostPolygon2, unionResult);\n    }catch(const boost::geometry::overlay_invalid_input_exception&){\n      LOG_FREE(Error, \"utilities.geometry.join\", \"overlay_invalid_input_exception\");\n      return boost::none;\n    }\n\n    unionResult = removeSpikes(unionResult);\n\n    // should not be any holes, check for that below\n\n    // check that union is ok\n    if (unionResult.empty()){\n      return boost::none;\n    }else if (unionResult.size() > 1){\n      return boost::none;\n    }\n\n    std::vector<Point3d> unionVertices = verticesFromBoostPolygon(unionResult[0], allPoints, tol);\n    boost::optional<double> testArea = boost::geometry::area(unionResult[0]);\n    if (!testArea || unionVertices.empty()){\n      LOG_FREE(Info, \"utilities.geometry.join\", \"Cannot compute area of union\");\n      return boost::none;\n    }else if (*testArea < tol*tol){\n      LOG_FREE(Info, \"utilities.geometry.join\", \"Union has very small area of \" << *testArea << \" m^2\");\n      return boost::none;\n    }\n    try{\n      boost::geometry::detail::overlay::has_self_intersections(unionResult[0]);\n    }catch(const boost::geometry::overlay_invalid_input_exception&){\n      LOG_FREE(Error, \"utilities.geometry.join\", \"Union is self intersecting\");\n      return boost::none;\n    }\n\n    // check for holes\n    if (!unionResult[0].inners().empty()){\n      LOG_FREE(Error, \"utilities.geometry.join\", \"Union has inner loops\");\n      return boost::none;\n    };\n\n    unionVertices = reorderULC(unionVertices);\n    unionVertices = removeCollinear(unionVertices);\n\n    return unionVertices;\n  }\n\n  std::vector<std::vector<Point3d> > joinAll(const std::vector<std::vector<Point3d> >& polygons, double tol)\n  {\n    std::vector<std::vector<Point3d> > result;\n\n    unsigned N = polygons.size();\n    if (N <= 1){\n      return polygons;\n    }\n\n    // compute adjacency matrix\n    Matrix A(N,N,0.0);\n    for (unsigned i = 0; i < polygons.size(); ++i){\n      A(i,i) = 1.0;\n      for (unsigned j = i+1; j < polygons.size(); ++j){\n        if (join(polygons[i], polygons[j], tol)){\n          A(i,j) = 1.0;\n          A(j,i) = 1.0;\n        }\n      }\n    }\n\n    \n\n    std::vector<std::vector<unsigned> > connectedComponents = findConnectedComponents(A);\n    for (const std::vector<unsigned>& component : connectedComponents){\n      std::vector<Point3d> points;\n      for (unsigned i : component){\n        if (points.empty()){\n          points = polygons[i];\n        }else{\n          boost::optional<std::vector<Point3d> > joined = join(points, polygons[i], tol);\n          if (!joined){\n            LOG_FREE(Error, \"utilities.geometry.joinAll\", \"Expected polygons to join together\");\n          }else{\n            points = *joined;\n          }\n        }\n      }\n      result.push_back(points);\n    }\n\n    return result;\n  }\n\n  boost::optional<IntersectionResult> intersect(const std::vector<Point3d>& polygon1, const std::vector<Point3d>& polygon2, double tol)\n  {\n    std::vector<Point3d> resultPolygon1;\n    std::vector<Point3d> resultPolygon2;\n    std::vector< std::vector<Point3d> > newPolygons1;\n    std::vector< std::vector<Point3d> > newPolygons2;\n\n    // convert vertices to boost rings\n    std::vector<Point3d> allPoints;\n    \n    boost::optional<BoostRing> boostPolygon1 = nonIntersectingBoostRingFromVertices(polygon1, allPoints, tol);\n    if (!boostPolygon1){\n      return boost::none;\n    }\n\n    boost::optional<BoostRing> boostPolygon2 = nonIntersectingBoostRingFromVertices(polygon2, allPoints, tol);\n    if (!boostPolygon2){\n      return boost::none;\n    }\n\n    // intersect the points in face coordinates, \n    std::vector<BoostPolygon> intersectionResult;\n    try{\n      boost::geometry::intersection(*boostPolygon1, *boostPolygon2, intersectionResult);\n    }catch(const boost::geometry::overlay_invalid_input_exception&){\n      LOG_FREE(Error, \"utilities.geometry.intersect\", \"overlay_invalid_input_exception\");\n      return boost::none;\n    }\n\n    // check if intersection is empty\n    if (intersectionResult.empty()){\n      //LOG_FREE(Info, \"utilities.geometry.intersect\", \"Intersection is empty\");\n      return boost::none;\n    }\n\n    intersectionResult = removeSpikes(intersectionResult);\n    intersectionResult = removeHoles(intersectionResult);\n\n    // check for multiple intersections\n    if (intersectionResult.size() > 1){\n      LOG_FREE(Info, \"utilities.geometry.intersect\", \"Intersection has \" << intersectionResult.size() << \" elements\");\n      std::sort(intersectionResult.begin(), intersectionResult.end(), BoostPolygonAreaGreater());\n    }\n    \n    // check that largest intersection is ok\n    std::vector<Point3d> intersectionVertices = verticesFromBoostPolygon(intersectionResult[0], allPoints, tol);\n    boost::optional<double> testArea = boost::geometry::area(intersectionResult[0]);\n    if (!testArea || intersectionVertices.empty()){\n      LOG_FREE(Info, \"utilities.geometry.intersect\", \"Cannot compute area of largest intersection\");\n      return boost::none;\n    }else if (*testArea < tol*tol){\n      LOG_FREE(Info, \"utilities.geometry.intersect\", \"Largest intersection has very small area of \" << *testArea << \" m^2\");\n      return boost::none;\n    }\n    try{\n      boost::geometry::detail::overlay::has_self_intersections(intersectionResult[0]);\n    }catch(const boost::geometry::overlay_invalid_input_exception&){\n      LOG_FREE(Error, \"utilities.geometry.intersect\", \"Largest intersection is self intersecting\");\n      return boost::none;\n    }\n    if (!intersectionResult[0].inners().empty()){\n      LOG_FREE(Error, \"utilities.geometry.intersect\", \"Largest intersection has inner loops\");\n      return boost::none;\n    };\n\n    // intersections are the same\n    resultPolygon1 = intersectionVertices;\n    resultPolygon2 = intersectionVertices;\n\n    // create new polygon for each remaining intersection\n    for (unsigned i = 1; i < intersectionResult.size(); ++i){\n\n      std::vector<Point3d> newPolygon = verticesFromBoostPolygon(intersectionResult[i], allPoints, tol);\n\n      testArea = boost::geometry::area(intersectionResult[i]);\n      if (!testArea || newPolygon.empty()){\n        LOG_FREE(Info, \"utilities.geometry.intersect\", \"Cannot compute area of intersection, result will not include this polygon, \" << newPolygon);\n        continue;\n      }else if (*testArea < tol*tol){\n        LOG_FREE(Info, \"utilities.geometry.intersect\", \"Intersection has very small area of \" << *testArea << \" m^2, result will not include this polygon, \" << newPolygon);\n        continue;\n      }\n      try{\n        boost::geometry::detail::overlay::has_self_intersections(intersectionResult[i]);\n      }catch(const boost::geometry::overlay_invalid_input_exception&){\n        LOG_FREE(Error, \"utilities.geometry.intersect\", \"Intersection is self intersecting, result will not include this polygon, \" << newPolygon);\n        continue;\n      }\n      if (!intersectionResult[i].inners().empty()){\n        LOG_FREE(Error, \"utilities.geometry.intersect\", \"Intersection has inner loops, result will not include this polygon, \" << newPolygon);\n        continue;\n      };\n\n      newPolygons1.push_back(newPolygon);\n      newPolygons2.push_back(newPolygon);\n    }\n\n    // polygon1 minus polygon2\n    std::vector<BoostPolygon> differenceResult1;\n    boost::geometry::difference(*boostPolygon1, *boostPolygon2, differenceResult1);\n    differenceResult1 = removeSpikes(differenceResult1);\n    differenceResult1 = removeHoles(differenceResult1);\n    \n    // create new polygon for each difference\n    for (unsigned i = 0; i < differenceResult1.size(); ++i){\n\n      std::vector<Point3d> newPolygon1 = verticesFromBoostPolygon(differenceResult1[i], allPoints, tol);\n\n      testArea = boost::geometry::area(differenceResult1[i]);\n      if (!testArea || newPolygon1.empty()){\n        LOG_FREE(Info, \"utilities.geometry.intersect\", \"Cannot compute area of face difference, result will not include this polygon, \" << newPolygon1);\n        continue;\n      }else if (*testArea < tol*tol){\n        LOG_FREE(Info, \"utilities.geometry.intersect\", \"Face difference has very small area of \" << *testArea << \" m^2, result will not include this polygon, \" << newPolygon1);\n        continue;\n      }\n      try{\n        boost::geometry::detail::overlay::has_self_intersections(differenceResult1[i]);\n      }catch(const boost::geometry::overlay_invalid_input_exception&){\n        LOG_FREE(Error, \"utilities.geometry.intersect\", \"Face difference is self intersecting, result will not include this polygon, \" << newPolygon1);\n        continue;\n      }\n\n      newPolygons1.push_back(newPolygon1);\n    }\n\n    // polygon2 minus polygon1\n    std::vector<BoostPolygon> differenceResult2;\n    boost::geometry::difference(*boostPolygon2, *boostPolygon1, differenceResult2);\n    differenceResult2 = removeSpikes(differenceResult2);\n    differenceResult2 = removeHoles(differenceResult2);\n\n    // create new polygon for each difference\n    for (unsigned i = 0; i < differenceResult2.size(); ++i){\n\n      std::vector<Point3d> newPolygon2 = verticesFromBoostPolygon(differenceResult2[i], allPoints, tol);\n\n      testArea = boost::geometry::area(differenceResult2[i]);\n      if (!testArea || newPolygon2.empty()){\n        LOG_FREE(Info, \"utilities.geometry.intersect\", \"Cannot compute area of face difference, result will not include this polygon, \" << newPolygon2);\n        continue;\n      }else if (*testArea < tol*tol){\n        LOG_FREE(Info, \"utilities.geometry.intersect\", \"Face difference has very small area of \" << *testArea << \" m^2, result will not include this polygon, \" << newPolygon2);\n        continue;\n      }\n      try{\n        boost::geometry::detail::overlay::has_self_intersections(differenceResult2[i]);\n      }catch(const boost::geometry::overlay_invalid_input_exception&){\n        LOG_FREE(Error, \"utilities.geometry.intersect\", \"Face difference is self intersecting, result will not include this polygon, \" << newPolygon2);\n        continue;\n      }\n\n      newPolygons2.push_back(newPolygon2);\n    }\n\n    return IntersectionResult(resultPolygon1, resultPolygon2, newPolygons1, newPolygons2);\n  }\n\n  std::vector<std::vector<Point3d> > subtract(const std::vector<Point3d>& polygon, const std::vector<std::vector<Point3d> >& holes, double tol)\n  {\n    std::vector<std::vector<Point3d> > result;\n\n    // convert vertices to boost rings\n    std::vector<Point3d> allPoints;\n\n    boost::optional<BoostPolygon> initialBoostPolygon = nonIntersectingBoostPolygonFromVertices(polygon, allPoints, tol);\n    if (!initialBoostPolygon){\n      return result;\n    }\n\n    std::vector<BoostPolygon> boostPolygons;\n    boostPolygons.push_back(*initialBoostPolygon);\n\n    std::vector<BoostPolygon> newBoostPolygons;\n    for (const std::vector<Point3d>& hole : holes){\n      boost::optional<BoostPolygon> boostHole = nonIntersectingBoostPolygonFromVertices(hole, allPoints, tol);\n      if (!boostHole){\n        return result;\n      }\n      \n      for (const BoostPolygon& boostPolygon : boostPolygons){\n        std::vector<BoostPolygon> diffResult;\n        boost::geometry::difference(boostPolygon, *boostHole, diffResult);\n        diffResult = removeSpikes(diffResult);\n        diffResult = removeHoles(diffResult);\n        newBoostPolygons.insert(newBoostPolygons.end(), diffResult.begin(), diffResult.end());\n      }\n      boostPolygons.swap(newBoostPolygons);\n    }\n\n    for (const BoostPolygon& boostPolygon : boostPolygons){\n      result.push_back(verticesFromBoostPolygon(boostPolygon, allPoints, tol));\n    }\n\n    return result;\n  }\n\n  bool selfIntersects(const std::vector<Point3d>& polygon, double tol)\n  {\n    // convert vertices to boost rings\n    std::vector<Point3d> allPoints;\n\n    boost::optional<BoostPolygon> bp = nonIntersectingBoostPolygonFromVertices(polygon, allPoints, tol);\n    if (!bp){\n      return false;\n    }\n    return true;\n  }\n\n  bool intersects(const std::vector<Point3d>& polygon1, const std::vector<Point3d>& polygon2, double tol)\n  {\n    // convert vertices to boost rings\n    std::vector<Point3d> allPoints;\n\n    boost::optional<BoostPolygon> bp1 = boostPolygonFromVertices(polygon1, allPoints, tol);\n    boost::optional<BoostPolygon> bp2 = boostPolygonFromVertices(polygon2, allPoints, tol);\n\n    if (bp1 && bp2){\n      return boost::geometry::intersects(*bp1, *bp2);\n    }\n\n    return false;\n  }\n\n  bool within(const Point3d& point1, const std::vector<Point3d>& polygon2, double tol)\n  {\n    std::vector<Point3d> geometry1;\n    geometry1.push_back(point1);\n    return within(geometry1, polygon2, tol);\n  }\n\n  bool within(const std::vector<Point3d>& geometry1, const std::vector<Point3d>& polygon2, double tol)\n  {\n    // convert vertices to boost rings\n    std::vector<Point3d> allPoints;\n\n    if (geometry1.size() == 1){\n      if (geometry1[0].z() > tol){\n        return false;\n      }\n\n      boost::tuple<double, double> p = boostPointFromPoint3d(geometry1[0], allPoints, tol);\n      BoostPoint boostPoint(p.get<0>(), p.get<1>());\n\n      boost::optional<BoostPolygon> bp2 = boostPolygonFromVertices(polygon2, allPoints, tol);\n\n      if (bp2){\n        return boost::geometry::within(boostPoint, *bp2);\n      }\n\n      return false;\n    }\n\n    /*\n    // DLM: this is the better implementation, requires boost 1.57\n    boost::optional<BoostPolygon> bp1 = boostPolygonFromVertices(geometry1, allPoints, tol);\n    boost::optional<BoostPolygon> bp2 = boostPolygonFromVertices(polygon2, allPoints, tol);\n    if (bp1 && bp2){\n      return boost::geometry::within(*bp1, *bp2);\n    }\n    */\n\n    // DLM: temp code\n    if (geometry1.size() < 3){\n      return false;\n    }\n    boost::optional<BoostPolygon> bp2 = boostPolygonFromVertices(polygon2, allPoints, tol);\n    if (bp2){\n      for (const Point3d& point : geometry1)\n      {\n        boost::tuple<double, double> p = boostPointFromPoint3d(point, allPoints, tol);\n        BoostPoint boostPoint(p.get<0>(), p.get<1>());\n\n        if (!boost::geometry::within(boostPoint, *bp2)){\n          return false;\n        }\n      }\n    } else{\n      return false;\n    }\n\n    return true;\n  }\n\n} // openstudio\n", "meta": {"hexsha": "412636137ca27c5c0127593a8149251c0494b41e", "size": 35914, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openstudiocore/src/utilities/geometry/Intersection.cpp", "max_stars_repo_name": "jasondegraw/OpenStudio", "max_stars_repo_head_hexsha": "2ab13f6e5e48940929041444e40ad9d36f80f552", "max_stars_repo_licenses": ["blessing"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-12-29T08:45:03.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-29T08:45:03.000Z", "max_issues_repo_path": "openstudiocore/src/utilities/geometry/Intersection.cpp", "max_issues_repo_name": "jasondegraw/OpenStudio", "max_issues_repo_head_hexsha": "2ab13f6e5e48940929041444e40ad9d36f80f552", "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/utilities/geometry/Intersection.cpp", "max_forks_repo_name": "jasondegraw/OpenStudio", "max_forks_repo_head_hexsha": "2ab13f6e5e48940929041444e40ad9d36f80f552", "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": 33.0091911765, "max_line_length": 176, "alphanum_fraction": 0.6574873308, "num_tokens": 8844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2770372241015032}}
{"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#if USE_CSPICE\n#include \"Tudat/External/SpiceInterface/spiceInterface.h\"\n#endif\n\n#include \"Tudat/Astrodynamics/Gravitation/timeDependentSphericalHarmonicsGravityField.h\"\n#include \"Tudat/Astrodynamics/Gravitation/triAxialEllipsoidGravity.h\"\n#include \"Tudat/SimulationSetup/EnvironmentSetup/createGravityField.h\"\n#include \"Tudat/InputOutput/basicInputOutput.h\"\n\nnamespace tudat\n{\n\nnamespace simulation_setup\n{\n\n//! Get the path of the SH file for a SH model.\nstd::string getPathForSphericalHarmonicsModel( const SphericalHarmonicsModel sphericalHarmonicsModel )\n{\n    switch ( sphericalHarmonicsModel )\n    {\n    case egm96:\n        return input_output::getGravityModelsPath( ) + \"Earth/egm96.txt\";\n    case ggm02c:\n        return input_output::getGravityModelsPath( ) + \"Earth/ggm02c.txt\";\n    case ggm02s:\n        return input_output::getGravityModelsPath( ) + \"Earth/ggm02s.txt\";\n    case glgm3150:\n        return input_output::getGravityModelsPath( ) + \"Moon/glgm3150.txt\";\n    case lpe200:\n        return input_output::getGravityModelsPath( ) + \"Moon/lpe200.txt\";\n    case jgmro120d:\n        return input_output::getGravityModelsPath( ) + \"Mars/jgmro120d.txt\";\n    default:\n        std::cerr << \"No path known for Spherical Harmonics Model \" << sphericalHarmonicsModel << std::endl;\n        throw;\n    }\n}\n\n//! Get the associated reference frame for a SH model.\nstd::string getReferenceFrameForSphericalHarmonicsModel( const SphericalHarmonicsModel sphericalHarmonicsModel )\n{\n    switch ( sphericalHarmonicsModel )\n    {\n    case egm96:\n    case ggm02c:\n    case ggm02s:\n        return \"IAU_Earth\";\n    case glgm3150:\n    case lpe200:\n        return \"IAU_Moon\";\n    case jgmro120d:\n        return \"IAU_Mars\";\n    default:\n        std::cerr << \"No reference frame known for Spherical Harmonics Model \" << sphericalHarmonicsModel << std::endl;\n        throw;\n    }\n}\n\n//! Constructor with custom model.\nFromFileSphericalHarmonicsGravityFieldSettings::FromFileSphericalHarmonicsGravityFieldSettings(\n        const std::string& filePath, const std::string& associatedReferenceFrame,\n        const int maximumDegree, const int maximumOrder,\n        const int gravitationalParameterIndex, const int referenceRadiusIndex,\n        const double gravitationalParameter, const double referenceRadius ) :\n    SphericalHarmonicsGravityFieldSettings( gravitationalParameter, referenceRadius, Eigen::MatrixXd( ),\n                                            Eigen::MatrixXd( ), associatedReferenceFrame ),\n    filePath_( filePath ),\n    maximumDegree_( maximumDegree ),\n    maximumOrder_( maximumOrder ),\n    gravitationalParameterIndex_( gravitationalParameterIndex ),\n    referenceRadiusIndex_( referenceRadiusIndex )\n{\n    std::pair< Eigen::MatrixXd, Eigen::MatrixXd > coefficients;\n    std::pair< double, double > referenceData =\n            readGravityFieldFile( filePath, maximumDegree, maximumOrder, coefficients,\n                                  gravitationalParameterIndex, referenceRadiusIndex );\n    gravitationalParameter_ = gravitationalParameterIndex >= 0 ? referenceData.first : gravitationalParameter;\n    referenceRadius_ = referenceRadiusIndex >= 0 ? referenceData.second : referenceRadius;\n    cosineCoefficients_ = coefficients.first;\n    sineCoefficients_ = coefficients.second;\n}\n\n//! Constructor with model included in Tudat.\nFromFileSphericalHarmonicsGravityFieldSettings::FromFileSphericalHarmonicsGravityFieldSettings(\n        const SphericalHarmonicsModel sphericalHarmonicsModel ) :\n    FromFileSphericalHarmonicsGravityFieldSettings( getPathForSphericalHarmonicsModel( sphericalHarmonicsModel ),\n                                                    getReferenceFrameForSphericalHarmonicsModel( sphericalHarmonicsModel ),\n                                                    50, 50, 0, 1 )\n{\n    sphericalHarmonicsModel_ = sphericalHarmonicsModel;\n}\n\n\n//! Function to read a gravity field file\nstd::pair< double, double  > readGravityFieldFile(\n        const std::string& fileName, const int maximumDegree, const int maximumOrder,\n        std::pair< Eigen::MatrixXd, Eigen::MatrixXd >& coefficients,\n        const int gravitationalParameterIndex, const int referenceRadiusIndex )\n{\n    // Attempt to open gravity file.\n    std::fstream stream( fileName.c_str( ), std::ios::in );\n    if( stream.fail( ) )\n    {\n        throw std::runtime_error( \"Pds gravity field data file could not be opened: \" + fileName );\n    }\n\n    // Declare variables for reading file.\n    std::vector< std::string > vectorOfIndividualStrings;\n    vectorOfIndividualStrings.resize( 4 );\n    std::string line;\n\n\n    double gravitationalParameter = TUDAT_NAN;\n    double referenceRadius = TUDAT_NAN;\n\n    if( ( gravitationalParameterIndex >= 0 ) &&\n            ( referenceRadiusIndex >= 0 ) )\n    {\n        // Get first line of file.\n        std::getline( stream, line );\n\n        // Get reference radius and gravitational parameter from first line of file.\n        boost::algorithm::trim( line );\n        boost::algorithm::split( vectorOfIndividualStrings,\n                                 line,\n                                 boost::algorithm::is_any_of( \"\\t, \" ),\n                                 boost::algorithm::token_compress_on );\n        if( gravitationalParameterIndex >= static_cast< int >( vectorOfIndividualStrings.size( ) ) ||\n                referenceRadiusIndex >= static_cast< int >( vectorOfIndividualStrings.size( ) ) )\n        {\n            throw std::runtime_error( \"Error when reading gravity field file, requested header index exceeds file contents\" );\n        }\n\n        gravitationalParameter = std::stod( vectorOfIndividualStrings[ gravitationalParameterIndex ] );\n        referenceRadius = std::stod( vectorOfIndividualStrings[ referenceRadiusIndex ] );\n    }\n    else if( ( !( gravitationalParameterIndex >= 0 ) &&\n               ( referenceRadiusIndex >= 0 ) ) ||\n             ( ( gravitationalParameterIndex >= 0 ) &&\n               !( referenceRadiusIndex >= 0 ) ) )\n    {\n        throw std::runtime_error( \"Error when reading gravity field file, must retrieve either both or neither of Re and mu\" );\n    }\n\n\n    // Declare variables for reading in cosine and sine coefficients.\n    int currentDegree = 0, currentOrder = 0;\n    Eigen::MatrixXd cosineCoefficients = Eigen::MatrixXd( maximumDegree + 1, maximumOrder + 1 );\n    cosineCoefficients.setZero( );\n    Eigen::MatrixXd sineCoefficients = Eigen::MatrixXd( maximumDegree + 1, maximumOrder + 1 );\n    sineCoefficients.setZero( );\n\n    // Read coefficients up to required maximum degree and order.\n    while ( !stream.fail( ) && !stream.eof( ) &&\n            ( currentDegree <= maximumDegree && currentOrder < maximumOrder )  )\n    {\n        // Read current line\n        std::getline( stream, line );\n\n        // Trim input string (removes all leading and trailing whitespaces).\n        boost::algorithm::trim( line );\n\n        // Split string into multiple strings, each containing one element from a line from the\n        // data file.\n        boost::algorithm::split( vectorOfIndividualStrings,\n                                 line,\n                                 boost::algorithm::is_any_of( \", \" ),\n                                 boost::algorithm::token_compress_on );\n\n        // Check current line for consistency\n        if( vectorOfIndividualStrings.size( ) != 0 )\n        {\n            if( vectorOfIndividualStrings.size( ) < 4 )\n            {\n                std::string errorMessage = \"Error when reading pds gravity field file, number of fields is \" +\n                        std::to_string( vectorOfIndividualStrings.size( ) );\n                throw std::runtime_error( errorMessage );\n            }\n            else\n            {\n                // Read current degree and orde from line.\n                currentDegree = std::stoi( vectorOfIndividualStrings[ 0 ] );\n                currentOrder = std::stoi( vectorOfIndividualStrings[ 1 ] );\n\n                // Set cosine and sine coefficients for current degree and order.\n                if( currentDegree <= maximumDegree && currentOrder <= maximumOrder )\n                {\n                    cosineCoefficients( currentDegree, currentOrder ) =\n                            std::stod( vectorOfIndividualStrings[ 2 ] );\n                    sineCoefficients( currentDegree, currentOrder ) =\n                            std::stod( vectorOfIndividualStrings[ 3 ] );\n                }\n            }\n        }\n    }\n\n    // Set cosine coefficient at (0,0) to 1.\n    cosineCoefficients( 0, 0 ) = 1.0;\n    coefficients = std::make_pair( cosineCoefficients, sineCoefficients );\n\n    return std::make_pair( gravitationalParameter, referenceRadius );\n}\n\n//! Function to create a gravity field model.\nstd::shared_ptr< gravitation::GravityFieldModel > createGravityFieldModel(\n        const std::shared_ptr< GravityFieldSettings > gravityFieldSettings,\n        const std::string& body,\n        const NamedBodyMap& bodyMap,\n        const std::vector< std::shared_ptr< GravityFieldVariationSettings > >& gravityFieldVariationSettings )\n{\n    using namespace tudat::gravitation;\n\n    // Declare return object.\n    std::shared_ptr< GravityFieldModel > gravityFieldModel;\n\n    // Check which type of gravity field model is to be created.\n    switch( gravityFieldSettings->getGravityFieldType( ) )\n    {\n    case central:\n    {\n        // Check whether settings for point mass gravity field model are consistent with its type.\n        std::shared_ptr< CentralGravityFieldSettings > centralFieldSettings =\n                std::dynamic_pointer_cast< CentralGravityFieldSettings >( gravityFieldSettings );\n        if( centralFieldSettings == nullptr )\n        {\n            throw std::runtime_error(\n                        \"Error, expected central field settings when making gravity field model for body \" +\n                        body);\n        }\n        else if( gravityFieldVariationSettings.size( ) != 0 )\n        {\n            throw std::runtime_error( \"Error, requested central gravity field, but field variations settings are not empty.\" );\n        }\n        else\n        {\n            // Create and initialize point mass gravity field model.\n            gravityFieldModel = std::make_shared< GravityFieldModel >(\n                        centralFieldSettings->getGravitationalParameter( ) );\n        }\n        break;\n    }\n#if USE_CSPICE\n    case central_spice:\n    {\n        if( gravityFieldVariationSettings.size( ) != 0 )\n        {\n            throw std::runtime_error( \"Error, requested central gravity field, but field variations settings are not empty.\" );\n        }\n        else\n        {\n            // Create and initialize point mass gravity field model from Spice.\n            gravityFieldModel = std::make_shared< GravityFieldModel >(\n                        spice_interface::getBodyGravitationalParameter( body ) );\n        }\n\n        break;\n    }\n#endif\n    case spherical_harmonic:\n    {\n        // Check whether settings for spherical harmonic gravity field model are consistent with\n        // its type.\n        std::shared_ptr< SphericalHarmonicsGravityFieldSettings > sphericalHarmonicFieldSettings =\n                std::dynamic_pointer_cast< SphericalHarmonicsGravityFieldSettings >(\n                    gravityFieldSettings );\n\n        if( sphericalHarmonicFieldSettings == nullptr )\n        {\n            throw std::runtime_error(\n                        \"Error, expected spherical harmonic field settings when making gravity field model of \"\n                        + body );\n        }\n        else\n        {\n            std::function< void( ) > inertiaTensorUpdateFunction;\n            if( bodyMap.count( body ) == 0 )\n            {\n                inertiaTensorUpdateFunction = std::function< void( ) >( );\n            }\n            else\n            {\n                inertiaTensorUpdateFunction =\n                    std::bind( &Body::setBodyInertiaTensorFromGravityFieldAndExistingMeanMoment, bodyMap.at( body ), true );\n            }\n\n            // Check consistency of cosine and sine coefficients.\n            if( ( sphericalHarmonicFieldSettings->getCosineCoefficients( ).rows( ) !=\n                  sphericalHarmonicFieldSettings->getSineCoefficients( ).rows( ) ) ||\n                    ( sphericalHarmonicFieldSettings->getCosineCoefficients( ).cols( ) !=\n                      sphericalHarmonicFieldSettings->getSineCoefficients( ).cols( ) ) )\n            {\n                throw std::runtime_error(\n                            std::string( \"Error when making spherical harmonic field, sine and \" ) +\n                            std::string( \"cosine matrix  sizes are not equal for body \" ) + body );\n            }\n            else\n            {\n\n                if( gravityFieldVariationSettings.size( ) == 0 &&\n                        sphericalHarmonicFieldSettings->getCreateTimeDependentField( ) == 0 )\n                {\n                    // Create and initialize spherical harmonic gravity field model.\n                    gravityFieldModel = std::make_shared< SphericalHarmonicsGravityField >(\n                                sphericalHarmonicFieldSettings->getGravitationalParameter( ),\n                                sphericalHarmonicFieldSettings->getReferenceRadius( ),\n                                sphericalHarmonicFieldSettings->getCosineCoefficients( ),\n                                sphericalHarmonicFieldSettings->getSineCoefficients( ),\n                                sphericalHarmonicFieldSettings->getAssociatedReferenceFrame( ),\n                                inertiaTensorUpdateFunction );\n                }\n                else\n                {\n                    if( bodyMap.at( body )->getGravityFieldModel( ) != nullptr )\n                    {\n                        std::string errorMessage = \"Warning when making time-dependent gravity field model for body \" + body +\n                                \" existing gravity field is not empty but overwritten in Body! \";\n                        throw std::runtime_error( errorMessage );\n                    }\n\n                    // Create preliminary TimeDependentSphericalHarmonicsGravityField, without actual variation settings.\n                    gravityFieldModel = std::make_shared< TimeDependentSphericalHarmonicsGravityField >(\n                                sphericalHarmonicFieldSettings->getGravitationalParameter( ),\n                                sphericalHarmonicFieldSettings->getReferenceRadius( ),\n                                sphericalHarmonicFieldSettings->getCosineCoefficients( ),\n                                sphericalHarmonicFieldSettings->getSineCoefficients( ),\n                                sphericalHarmonicFieldSettings->getAssociatedReferenceFrame( ),\n                                inertiaTensorUpdateFunction );\n                }\n\n\n            }\n        }\n        break;\n    }\n    default:\n        throw std::runtime_error(\n                    \"Error, did not recognize gravity field model settings type \" +\n                    std::to_string(\n                        gravityFieldSettings->getGravityFieldType( ) ) );\n    }\n\n    return gravityFieldModel;\n}\n\n//! Function to create gravity field settings for a homogeneous triaxial ellipsoid\nstd::shared_ptr< SphericalHarmonicsGravityFieldSettings > createHomogeneousTriAxialEllipsoidGravitySettings(\n        const double axisA, const double axisB, const double axisC, const double ellipsoidDensity,\n        const int maximumDegree, const int maximumOrder,\n        const std::string& associatedReferenceFrame  )\n{\n    // Compute reference quantities\n    double ellipsoidGravitationalParameter = gravitation::calculateTriAxialEllipsoidVolume(\n                axisA, axisB, axisC ) * ellipsoidDensity * physical_constants::GRAVITATIONAL_CONSTANT;\n    double ellipsoidReferenceRadius = gravitation::calculateTriAxialEllipsoidVolume(\n                axisA, axisB, axisC );\n\n    // Compute coefficients\n    std::pair< Eigen::MatrixXd, Eigen::MatrixXd > coefficients =\n            gravitation::createTriAxialEllipsoidNormalizedSphericalHarmonicCoefficients(\n                axisA, axisB, axisC, maximumDegree, maximumOrder );\n\n    return std::make_shared< SphericalHarmonicsGravityFieldSettings >(\n                ellipsoidGravitationalParameter, ellipsoidReferenceRadius, coefficients.first,\n                coefficients.second, associatedReferenceFrame );\n}\n\n} // namespace simulation_setup\n\n} // namespace tudat\n", "meta": {"hexsha": "4f2e729ca40c9a03dcf42f9ab9f6a6c920135650", "size": 17026, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/SimulationSetup/EnvironmentSetup/createGravityField.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/createGravityField.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/createGravityField.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": 44.1088082902, "max_line_length": 127, "alphanum_fraction": 0.632385763, "num_tokens": 3481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.27703721718768454}}
{"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_TRIGONOMETRIC_CONSTANTS_PIO2_1_HPP_INCLUDED\n#define NT2_TRIGONOMETRIC_CONSTANTS_PIO2_1_HPP_INCLUDED\n\n#include <nt2/include/functor.hpp>\n#include <boost/simd/constant/hierarchy.hpp>\n#include <boost/simd/constant/register.hpp>\nnamespace nt2\n{\n  namespace tag\n  {\n   /*!\n     @brief Pio2_1 generic tag\n\n     Represents the Pio2_1 constant in generic contexts.\n\n     @par Models:\n        Hierarchy\n   **/\n    // 1.57079632673412561417e+00\n    BOOST_SIMD_CONSTANT_REGISTER( Pio2_1, double\n                                , 1, 0x3fc90f80\n                                , 0x3FF921FB54400000ll\n                                )\n  }\n  namespace ext\n  {\n   template<class Site, class... Ts>\n   BOOST_FORCEINLINE generic_dispatcher<tag::Pio2_1, Site> dispatching_Pio2_1(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)\n   {\n     return generic_dispatcher<tag::Pio2_1, Site>();\n   }\n   template<class... Args>\n   struct impl_Pio2_1;\n  }\n  /*!\n    Constant used in modular computation involving \\f$\\pi\\f$\n\n    @par Semantic:\n\n    For type T0:\n\n    @code\n    T0 r = Pio2_1<T0>();\n    @endcode\n\n    @return a value of type T0\n  **/\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(tag::Pio2_1, Pio2_1);\n}\n\n#endif\n\n", "meta": {"hexsha": "b89b5cde2c2b1b075a10600ed8b96a885ec03c1d", "size": 1750, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/pio2_1.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/pio2_1.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/trigonometric/include/nt2/trigonometric/constants/pio2_1.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6885245902, "max_line_length": 168, "alphanum_fraction": 0.5788571429, "num_tokens": 460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.2769825694250466}}
{"text": "//\n// Created by Joris on 09/07/2018.\n//\n\n// This code performs an iterative Monte Carlo procedure to obtain a Maximum Entropy\n// model for the chromosome organization of C. crescentus\n\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <vector>\n#include <random>\n#include <chrono>\n#include <fstream>\n#include <unordered_map>\n#include <thread>\n#include \"Initialize.h\"\n#include \"Moves.h\"\nusing namespace Eigen;\n\nconst int number_of_threads = 36;\n\nconst double diameter = 6.4;\nconst int length_cylinder = 21;\nconst int midway = int(ceil(length_cylinder/2));\nconst int cap_length = 2;\n\nconst int pol_length = 1620;\n\nconst long int mc_moves_start = 100000000;\nlong int mc_moves;\nconst int burn_in_time = 20000000;\nconst int update_steps = 30;\nconst double learning_rate = 0.5;\n\nstd::vector<std::vector<Vector3i>> polymer(number_of_threads);\n\nbool boundary_cond = 1; //enforces boundary conditions if 1\nbool orient = 1; //orients the cell such that the origin is always in the left half\n\nstd::vector< std::vector<double>> Interaction_E(pol_length, std::vector<double>(pol_length,0));\n\nstd::uniform_real_distribution<double> unif(0.0,1.0);\nstd::uniform_int_distribution<int> unimove(0,2);\nstd::uniform_int_distribution<int> unisite(0,pol_length-1);\nstd::vector<std::vector<std::vector<double>>> total_contacts(number_of_threads, std::vector< std::vector<double>>(pol_length, std::vector<double>(pol_length, 0)));\nstd::vector<std::vector<double>> final_contacts(pol_length, std::vector<double>(pol_length, 0));\n\nvoid move(std::vector<Vector3i> &polymer,int thread_num, int m){ //performs a single Monte Carlo step\n    int action;\n    int site;\n\n    action = unimove(gen);\n    site = unisite(gen);\n    if (action==0){\n        kink_move(polymer,site, thread_num,m);\n    }\n    else if (action==1){\n        crankshaft_move(polymer,site, thread_num,m);\n    }\n    else if (action==2){\n       loop_move(polymer,site, thread_num,m);\n    }\n}\n\nvoid run_burnin(int thread_num, int mc_moves) { //burns in the polymer configurations\n    for (int m = 1; m < mc_moves; m++) {\n        move(polymer[thread_num], thread_num, m);\n    }\n}\n\nvoid run(int thread_num, int mc_moves) {\n    for (int m = 1; m < mc_moves; m++) {    //performs a forward polymer simulation\n        move(polymer[thread_num], thread_num, m);\n    }\n}\n\n//after each forward run, the polymer interaction energies are updated according to the pairwise difference\n// between model contact frequencies and experimental contact frequencies\nvoid update_energies(std::vector< std::vector<double>> &total_contacts, std::vector< std::vector<double>> &reference_contacts, std::vector< std::vector<double>> &Interaction_E) {\n\n    float checksum = 0;\n    for (int i = 0; i < pol_length/4; i++) {\n        for (int j = i+1; j < pol_length/4; j++) {\n            if ((i != (j+1)%(pol_length/4)) && (j != (i+1)%(pol_length/4))) {\n                Interaction_E[4 * i][4 * j] += learning_rate * sqrt(1/(std::max(reference_contacts[4*i][4*j],0.0001)))*(float(total_contacts[4 * i][4 * j])- reference_contacts[4 * i][4 * j]);\n                checksum += float(total_contacts[4 * i][4 * j])*(pol_length/4);\n                Interaction_E[4 * j][4 * i] = Interaction_E[4 * i][4 * j];\n            }\n        }\n    }\n\n    //calculates the shift of all energies, imposed to ensure a MaxEnt solution is found for the contact frequency scale\n    float shift = 0;\n    for (int i = 0; i < pol_length/4; i++) {\n        for (int j = i + 2; j < pol_length / 4; j++) {\n           shift += 2*(Interaction_E[4 * i][4 * j] * reference_contacts[4 * i][4 * j]) / (pol_length / 4);\n        }\n    }\n\n    std::cout << \"Shift: \" << shift << std::endl;\n    for (int i = 0; i < pol_length/4; i++) {\n        for (int j = i + 2; j < pol_length / 4; j++) {\n            //if ((i != (j + 1) % (pol_length / 2)) && (j != (i + 1) % (pol_length / 2)) && not(i >=0 && i<=30 && j>=150 && j<=220) && not(i >=150 && i <=230 && j>=370 && j<=410) ) {\n            Interaction_E[4 * i][4 * j] -= shift;\n            Interaction_E[4 * j][4 * i] = Interaction_E[4 * i][4 * j];\n            //}\n        }\n    }\n}\n\n//Normalizes model contact frequencies to allow for comparison with experimental data\nvoid normalize() {\n    double sum = 0;\n    for (int i = 0; i < pol_length; i++) {\n        for (int j = 0; j < pol_length; j++) {\n            if (i%4 == 0 && j%4 == 0 && i!=(j+4)%pol_length && j!=(i+4)%pol_length) {\n                sum += final_contacts[i][j];\n            }\n        }\n    }\n    for (int i = 0; i < pol_length; i++) {\n        for (int j = 0; j < pol_length; j++) {\n            final_contacts[i][j] *= double(pol_length)/(8*sum);\n        }\n    }\n}\n\nint main() {\n    auto start = std::chrono::high_resolution_clock::now();\n    std::cout << \"started! \" << std::endl;\n\n    for (int l = 0; l < number_of_threads; l++) {\n        initialize(polymer[l], pol_length, l);\n    }\n    std::cout << \"Initialized \" << std::endl;\n\n    // Read in starting interaction energies\n    std::ifstream couplings;\n    couplings.open(\"/media/joris/raid_data/Chromosome_Maxent/Dataprocess_check_review/Processed_new_r0/Inverse/Energies_Intermediate/energies_intermediate_49.txt\");\n    //couplings.open (\"/media/joris/raid_data/Chromosome_Maxent/Saved_energies/energies_smallcell.txt\");\n    for (int i = 0; i < pol_length; i++) { //read in energies\n        for (int j = 0; j < pol_length; j++) {\n            couplings >> Interaction_E[i][j];\n        }\n    }\n    couplings.close();\n\n    // Read in reference contacts\n    std::vector<std::vector<double>> reference_contacts(pol_length, std::vector<double>(pol_length));\n    std::ifstream input_contacts;\n    input_contacts.open(\"/media/joris/raid_data/Chromosome_Maxent/experimental_data_noisecancel_r1.txt\");\n    for (int i = 0; i < pol_length / 4; i++) { //read in contacts\n        for (int j = 0; j < pol_length / 4; j++) {\n            input_contacts >> reference_contacts[4 * i][4 * j];\n            if (reference_contacts[4*i][4*j] == 0 && i != j && i != (j + 1) % (pol_length / 2) &&\n                j != (i + 1) % (pol_length / 2)) {\n                Interaction_E[4 * i][4 * j] = 10;\n            }\n        }\n    }\n    input_contacts.close();\n\n    // burn in configurations\n    std::vector<std::thread> threads(number_of_threads);\n    for (auto l = 0; l < number_of_threads; l++) {\n        threads[l] = std::thread(run_burnin, l, burn_in_time);\n    }\n    for (auto &&l : threads) {\n        l.join();\n    }\n\n    std::cout << \"Done with burn in \" << std::endl;\n\n    for (int n =0; n<update_steps;n++) { //do iterative update scheme\n        mc_moves = mc_moves_start*sqrt(n+10)/sqrt(10); //number of MC moves grows with each iteration (implicitly converted to long int)\n\n        for (int l = 0; l < number_of_threads; l++) {\n            for (int i = 0; i < pol_length; i++) { //reset contact frequencies before starting new forward round\n                for (int j = 0; j < pol_length; j++) {\n                    total_contacts[l][i][j] = 0;\n                    if (l==0){\n                        final_contacts[i][j] =0;\n                    }\n                }\n\n            }\n            for (auto elem : contacts[l]) { //reset contacts\n                contacts[l][elem.first] = 0;\n            }\n        }\n\n        //run forward simulation\n        for (auto l = 0; l < number_of_threads; l++) {\n            threads[l] = std::thread(run, l, mc_moves);\n        }\n        for (auto &&l : threads) {\n            l.join();\n        }\n        // read in remaining contacts at the end of forward simulation\n        for (auto l = 0; l < number_of_threads; l++) {\n            for (auto elem : contacts[l]) { //add the contacts remaining at the end of the simulation\n                total_contacts[l][elem.first.first][elem.first.second] += mc_moves - elem.second;\n                contacts[l][elem.first] = 0;\n            }\n        }\n\n        //add up contacts from threads\n        for (int i = 0; i < number_of_threads; i++) {\n            for (int j = 0; j < pol_length; j++) {\n                for (int k = 0; k < pol_length; k++) {\n                    final_contacts[j][k] += total_contacts[i][j][k];\n                }\n            }\n        }\n\n        //normalize contact frequencies\n        normalize();\n\n        //update energies\n        update_energies(final_contacts,reference_contacts,Interaction_E);\n\n        //output intermediate results\n        std::ofstream intermediate_energies;\n        intermediate_energies.open (\"/media/joris/raid_data/Chromosome_Maxent/Dataprocess_check_review/Processed_new_r0/Inverse/Energies_Intermediate/energies_intermediate_\" + std::to_string(n) + \".txt\");\n        for(int i = 0; i < pol_length; i++){ //output contact frequencies\n            for(int j = 0; j < pol_length; j++){\n                intermediate_energies << Interaction_E[i][j] << std::endl;\n            }\n        }\n        intermediate_energies.close();\n\n        std::ofstream intermediate_contacts;\n        intermediate_contacts.open (\"/media/joris/raid_data/Chromosome_Maxent/Dataprocess_check_review/Processed_new_r0/Inverse/Contacts_Intermediate/contacts_intermediate_\" + std::to_string(n) + \".txt\");\n        for(int i = 0; i < pol_length; i++){ //output contact frequencies\n            for(int j = 0; j < pol_length; j++){\n                double contact = double(final_contacts[i][j]);\n                intermediate_contacts << contact << std::endl;\n            }\n        }\n        intermediate_contacts.close();\n    }\n\n    std::cout << \"Finished! \"  << std::endl;\n\n    //output final configurations for each thread\n    int n_capture = 0;\n    while (n_capture <number_of_threads) {\n        for (int thread_num = 0; thread_num < number_of_threads; thread_num++) {\n            if (polymer[thread_num][0][2] < 20) {\n                std::ofstream final_configuration;\n                final_configuration.open(\n                        \"/media/joris/raid_data/Chromosome_Maxent/Dataprocess_check_review/Processed_new_r0/Inverse/configuration_init_\" +\n                        std::to_string(n_capture) + \".txt\");\n                for (int i = 0; i < pol_length; i++) { //output contact frequencies\n                    for (int j = 0; j < 3; j++) {\n                        final_configuration << polymer[thread_num][i][j] << std::endl;\n                    }\n                }\n                final_configuration.close();\n                n_capture++;\n            }\n        }\n    }\n\n\n\n    auto finish = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> elapsed = finish - start;\n    std::cout << \"Elapsed time: \" <<  elapsed.count() << \" seconds\\n\";\n    return 0;\n}", "meta": {"hexsha": "647ea4b8190b70bb02b6b1eee76eafb94875e85e", "size": 10594, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Inverse Monte Carlo/main.cpp", "max_stars_repo_name": "JorisJJB/MaxEnt-Chromosome-Caulobacter", "max_stars_repo_head_hexsha": "39e2de4e542e24010c2cd173418306b576c2096e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Inverse Monte Carlo/main.cpp", "max_issues_repo_name": "JorisJJB/MaxEnt-Chromosome-Caulobacter", "max_issues_repo_head_hexsha": "39e2de4e542e24010c2cd173418306b576c2096e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Inverse Monte Carlo/main.cpp", "max_forks_repo_name": "JorisJJB/MaxEnt-Chromosome-Caulobacter", "max_forks_repo_head_hexsha": "39e2de4e542e24010c2cd173418306b576c2096e", "max_forks_repo_licenses": ["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.9485294118, "max_line_length": 204, "alphanum_fraction": 0.586086464, "num_tokens": 2806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.2768264633791512}}
{"text": "#include <algorithm>\n#include <cerrno>\n#include <csignal>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <fstream>\n#include <iostream>\n#include <iterator>\n#include <limits>\n#include <map>\n#include <math.h>\n#include <pthread.h>\n#include <sstream>\n#include <string>\n#include <sys/ptrace.h>\n#include <sys/time.h>\n#include <sys/user.h>\n#include <sys/wait.h>\n#include <thread>\n#include <unistd.h>\n#include <vector>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include \"papi.h\"\n\n#include \"supereasyjson/json.h\"\n#include \"papi-helpers.hpp\"\n\n#ifdef DEBUG\n#define print(...) printf(__VA_ARGS__)\n#else\n#define print(...)\n#endif\n\nusing namespace std;\nusing namespace boost::numeric;\nusing namespace json;\nusing namespace papi;\n\nnamespace{\n\n/*\n * Constants\n */\nconst unsigned kProcStatIdx = 39;\nconst long kDefaultSamplePeriodUsecs = 1000;\nconst long kMicroToBase = 1e6;\nconst long kNanoToBase = 1e9;\nconst char* kDefaultPrefix = \"eaudit\";\nconst string kPackageEnergyName = \"rapl:::PACKAGE_ENERGY:PACKAGE0\";\nconst string kDRAMEnergyName = \"rapl:::DRAM_ENERGY:PACKAGE0\";\nconst string kCoreEnergyName = \"rapl:::PP0_ENERGY:PACKAGE0\";\nconst vector<string> kAllEnergyNames = {kCoreEnergyName, kPackageEnergyName, kDRAMEnergyName};\nconst char* kDefaultModelName = \"default.model\";\nconst int kTotalCoreAssignments = 5;\n\nstruct stats_t {\n  long time; // in microseconds\n  vector<long long> counters;\n  stats_t& operator+=(const stats_t &rhs){\n    time += rhs.time;\n    counters.resize(rhs.counters.size());\n    for(unsigned int i = 0; i < rhs.counters.size(); ++i){\n      counters[i] += rhs.counters[i];\n    }\n    return *this;\n  }\n  // initialize time to 0 for new stats\n  stats_t() : time{0} {}\n};\n\n\nstruct result_stats_t {\n  stats_t per_core_stats;\n  long long estimated_energy;\n  result_stats_t& operator+=(const result_stats_t &rhs){\n    per_core_stats += rhs.per_core_stats;\n    estimated_energy += rhs.estimated_energy;\n    return *this;\n  }\n};\n\n\n/*\n * Global variables\n */\nvolatile bool is_timer_done = false;\n} // end unnamed namespace\n\n\nstruct Model {\n  Model(const string& model_fname) : model_fname_{model_fname} {\n    ifstream in{model_fname_};\n    if(!in.is_open()){\n      cerr << \"Unable to open model file\\n\";\n      exit(-1);\n    }\n    stringstream buffer;\n    buffer << in.rdbuf();\n    json::Value modelval = json::Deserialize(buffer.str());\n    if(modelval.GetType() == json::NULLVal){\n      cerr << \"Unable to parse json from model file\\n\";\n      exit(-1);\n    }\n    json::Object model = modelval.ToObject();\n\n    for(const auto& name : model[\"metric_names\"].ToArray()){\n      input_metrics_.push_back(name.ToString());\n    }\n\n    const auto means = model[\"means\"].ToArray();\n    means_.resize(means.size());\n    for(size_t i = 0; i < means.size(); ++i){\n      means_[i] = means[i].ToDouble();\n    }\n\n    const auto std_devs = model[\"std_devs\"].ToArray();\n    std_deviations_.resize(std_devs.size());\n    for(size_t i = 0; i < std_devs.size(); ++i){\n      std_deviations_[i] = std_devs[i].ToDouble();\n    }\n\n    const auto rot_mat = model[\"rotation_matrix\"].ToArray();\n    const auto n_rot_mat_rows = rot_mat.size();\n    if(n_rot_mat_rows > 0){\n      const auto n_rot_mat_cols = rot_mat[0].ToArray().size();\n      principal_components_.resize(n_rot_mat_rows, n_rot_mat_cols);\n      for(size_t i = 0; i < n_rot_mat_rows; ++i){\n        for(size_t j = 0; j < n_rot_mat_cols; ++j){\n          principal_components_(i,j) = rot_mat[i][j].ToDouble();\n        }\n      }\n    }\n\n    const auto clusters = model[\"clusters\"].ToArray();\n    for(const auto& cluster_val : clusters){\n      const auto& cluster = cluster_val.ToObject();\n      model_t internalized_model;\n\n      const auto center = cluster[\"center\"].ToArray();\n      internalized_model.centroid_.resize(center.size());\n      for(size_t i = 0; i < center.size(); ++i){\n        internalized_model.centroid_[i] = center[i].ToDouble();\n      }\n\n      const auto regressors = cluster[\"regressors\"].ToArray();\n      internalized_model.regressors_.resize(regressors.size());\n      internalized_model.weights_.resize(regressors.size());\n      for(size_t i = 0; i < regressors.size(); ++i){\n        // turn function object into a lambda doing the right thing\n        auto regressor = regressors[i].ToObject();\n        auto regressor_name = regressor[\"function\"].ToString();\n        if(regressor_name == \"identity\"){\n          internalized_model.regressors_[i] = function<double(const ublas::vector<double>&)>(\n                                   [](ublas::vector<double>){ return 1.0; });\n        } else if(regressor_name == \"power\"){\n          auto idx = regressor[\"index\"].ToInt();\n          auto exp = regressor[\"exponent\"].ToDouble();\n          internalized_model.regressors_[i] = function<double(const ublas::vector<double>&)>(\n            [=](const ublas::vector<double>& v) {\n              return v(idx) != 0.0 ? pow(fabs(v(idx)), exp) : 1.0;\n            });\n        } else if(regressor_name == \"product\"){\n          auto first_idx = regressor[\"first_idx\"].ToInt();\n          auto second_idx = regressor[\"second_idx\"].ToInt();\n          internalized_model.regressors_[i] = function<double(const ublas::vector<double>&)>(\n            [=](const ublas::vector<double>& v) {\n              return v(first_idx) * v(second_idx);\n            });\n        } else if(regressor_name == \"sqrt\"){\n          auto idx = regressor[\"index\"].ToInt();\n          internalized_model.regressors_[i] = function<double(const ublas::vector<double>&)>(\n            [=](const ublas::vector<double>& v) {\n              return sqrt(fabs(v(idx)));\n            });\n        } else if(regressor_name == \"log\"){\n          auto idx = regressor[\"index\"].ToInt();\n          internalized_model.regressors_[i] = function<double(const ublas::vector<double>&)>(\n            [=](const ublas::vector<double>& v) {\n              return idx == 0 ? 1.0 : log(fabs(v(idx)))/log(2);\n            });\n        } else {\n          cerr << \"Invalid function name '\" << regressor[\"name\"].ToString() << \"\\n\";\n          exit(-1);\n        }\n        internalized_model.weights_[i] = regressor[\"weight\"].ToDouble();\n      }\n      models_.push_back(internalized_model);\n    }\n  }\n\n  double poll(const vector<long long>& values, const vector<string>& names) const {\n    ublas::vector<double> v = ublas::vector<double>(input_metrics_.size());\n    //vector<string> input_metrics_;\n\n    for(unsigned i = 0; i < v.size(); ++i){\n      for(unsigned j = 0; j < names.size(); ++j){\n        if(names[j] == input_metrics_[j]){\n          v[i] = values[j];\n          break;\n        }\n      }\n    }\n\n    ublas::vector<double> inputs;\n    inputs = prod(v,principal_components_);\n    ublas::vector<double> norm_inputs = element_div(inputs - means_, std_deviations_);\n\n    int closest = 0;\n    double min_distance = numeric_limits<double>::max();\n    for(unsigned k = 0; k < models_.size(); ++k) {\n      //get distance\n      double distance = norm_2(norm_inputs - models_[k].centroid_);\n      if(distance < min_distance) {\n        closest = k;\n        min_distance = distance;\n      }\n    }\n    ublas::vector<double> function_vals =\n      ublas::vector<double>(models_[closest].regressors_.size());\n    int i = 0;\n    for(auto it =\n          begin(models_[closest].regressors_);\n        it != end(models_[closest].regressors_); ++it, ++i) {\n      function_vals(i) = (*it)(inputs);\n    }\n    double final_res = fabs(inner_prod(models_[closest].weights_,function_vals));\n    return final_res;\n  }\n\n  string model_fname_;\n\n  struct model_t {\n    ublas::vector<double> centroid_;\n    ublas::vector<double> weights_;\n    vector<function<double(const ublas::vector<double>&)>> regressors_;\n  };\n\n  ublas::vector<double> means_;\n  ublas::vector<double> std_deviations_;\n  ublas::matrix<double> principal_components_;\n  vector<string> input_metrics_;\n  vector<model_t> models_;\n};\n\n\nvoid overflow(int signum, siginfo_t* info, void* context){\n  (void)info;\n  (void)context;\n  if(signum == SIGALRM){\n    is_timer_done = true;\n  }\n}\n\n\nstats_t read_rapl(const event_info_t& eventsets, long period){\n  stats_t res;\n  res.counters.resize(eventsets.codes.size());\n  int retval=PAPI_stop(eventsets.set, &res.counters[0]);\n  if(retval != PAPI_OK){\n    cerr << \"Error: bad PAPI stop: \";\n    PAPI_perror(NULL);\n    terminate();\n  }\n  retval = PAPI_start(eventsets.set);\n  if(retval != PAPI_OK){\n    cerr << \"Error: bad PAPI stop: \";\n    PAPI_perror(NULL);\n    terminate();\n  }\n  res.time = period;\n  return res;\n}\n\n\n\nvector<long long> modelPerCoreEnergies(const Model& model,\n                                       const vector<stats_t>& core_stats,\n                                       const vector<string>& counter_names,\n                                       long long total_energy) {\n  vector<long long> results(core_stats.size());\n  //double poll(map<string, double> params) const {\n  vector<double> model_vals;\n  model_vals.reserve(core_stats.size());\n  for(const auto& core_stat : core_stats){\n    model_vals.push_back(model.poll(core_stat.counters, counter_names));\n  }\n  double total = accumulate(begin(model_vals), end(model_vals), double{0});\n  for(unsigned i = 0; i < results.size(); ++i){\n    results[i] = model_vals[i] / total * total_energy;\n  }\n  return results;\n}\n\nstruct ProfileValue{\n  double processor_energy, uncore_energy, dram_energy;\n  double time;\n  double instructions;\n  ProfileValue() : processor_energy{0}, uncore_energy(0), dram_energy(0), time{0}, instructions{0} {}\n};\n\nstruct ProfileEntry{\n  string name;\n  double processor_energy, uncore_energy, dram_energy, time, instructions;\n};\n\n\nvoid do_profiling(int profilee_pid, const char* profilee_name,\n                  const long period, const char* prefix,\n                  const Model& proc_model, const Model& uncore_model, const Model& dram_model) {\n  /*\n   * Structures holding profiling data\n   */\n  vector<int> children_pids;\n  vector<map<void*, ProfileValue>> core_profiles;\n  stats_t global_stats;\n  global_stats.counters.resize(3);\n  vector<event_info_t> core_counters;\n  // TODO: assumption here is that hyperthreading is turned on, and that there\n  // are two hardware threads per physical core. We have to make sure we only \n  // run the correct number of threads during auditing, since this assumption\n  // is made.\n  auto ncores = thread::hardware_concurrency() / 2;\n  //auto ncores = 1u;\n  core_profiles.resize(ncores);\n  core_counters.reserve(ncores);\n\n  /*\n   * Initialize PAPI\n   */\n  print(\"Init PAPI\\n\");\n  int retval;\n  if ((retval = PAPI_library_init(PAPI_VER_CURRENT)) != PAPI_VER_CURRENT) {\n    cerr << \"Unable to init PAPI library - \" << PAPI_strerror(retval) << endl;\n    exit(-1);\n  }\n\n  /*\n   * Initialize PAPI measurement of all cores\n   */\n  int inst_counter_idx = 0;\n  // get all the names for all the input counters\n  vector<string> counter_names = proc_model.input_metrics_;\n  counter_names.insert(end(counter_names), begin(uncore_model.input_metrics_), end(uncore_model.input_metrics_));\n  counter_names.insert(end(counter_names), begin(dram_model.input_metrics_), end(dram_model.input_metrics_));\n  // remove all duplicates\n  sort(begin(counter_names), end(counter_names));\n  auto last_elem = unique(begin(counter_names), end(counter_names));\n  counter_names.erase(last_elem, end(counter_names));\n  auto inst_iter = find(begin(counter_names), end(counter_names), \"PAPI_TOT_INS\");\n  if(inst_iter == end(counter_names)){\n    inst_counter_idx = counter_names.size();\n    counter_names.push_back(\"PAPI_TOT_INS\");\n  } else {\n    inst_counter_idx = distance(begin(counter_names), inst_iter);\n  }\n  // setup all core counters\n  for(unsigned int i = 0; i < ncores; ++i){\n    print(\"Creating per-core counters on core %d\\n\", i);\n    core_counters.emplace_back(init_papi_counters(counter_names));\n    auto& counters = core_counters[i];\n    attach_counters_to_core(counters, i);\n    start_counters(counters);\n  }\n  print(\"Creating global counters.\\n\");\n  auto global_counters = init_papi_counters(kAllEnergyNames);\n  start_counters(global_counters);\n\n  /*\n   * Setup tracing of all profilee threads\n   */\n  children_pids.push_back(profilee_pid);\n\n  /*\n   * Set up timer\n   */\n  struct sigaction sa;\n  sa.sa_sigaction = overflow;\n  sa.sa_flags = SA_SIGINFO;\n  if (sigaction(SIGALRM, &sa, nullptr) != 0) {\n    cerr << \"Unable to set up signal handler\\n\";\n    exit(-1);\n  }\n  struct itimerval work_time;\n  time_t sleep_secs = period / kMicroToBase;\n  suseconds_t sleep_usecs = period % kMicroToBase; \n  work_time.it_value.tv_sec = sleep_secs;\n  work_time.it_value.tv_usec = sleep_usecs;\n  work_time.it_interval.tv_sec = sleep_secs;\n  work_time.it_interval.tv_usec = sleep_usecs;\n  setitimer(ITIMER_REAL, &work_time, nullptr);\n\n  /*\n   * Let the profilee run, periodically interrupting to collect profile data.\n   */\n  ptrace(PTRACE_CONT, profilee_pid, nullptr, nullptr); // Allow child to fork\n  int status;\n  wait(&status); // wait for child to begin executing\n  print(\"Start profiling.\\n\");\n  /* Reassert that we want the profilee to stop when it clones */\n  ptrace(PTRACE_SETOPTIONS, profilee_pid, nullptr,\n         PTRACE_O_EXITKILL | PTRACE_O_TRACECLONE | PTRACE_O_TRACEEXIT);\n  ptrace(PTRACE_CONT, profilee_pid, nullptr, nullptr); // Allow child to run!\n  using core_id_t = int;\n  using assignments_left_t = int;\n  map<int, pair<core_id_t, assignments_left_t>> children_cores;\n  // We only want to match child PIDs to processors infrequently, since it \n  // requires a filesystem read. The assumption here is that threads are bound\n  // to cores, and only get created at the beginning of the function\n  // 50 is a magic number derived by running some apps a bunch of times.\n  auto start_time = PAPI_get_real_usec();\n  for (;;) {\n    auto wait_res = waitpid(-1, &status, __WALL);\n    if(wait_res == -1){ // bad wait!\n      if(errno == EINTR && is_timer_done){ // timer expired, do profiling\n        // halt timer\n        work_time.it_value.tv_sec = 0;\n        work_time.it_value.tv_usec = 0;\n        setitimer(ITIMER_REAL, &work_time, nullptr);\n        \n        // kill all the children\n        for(const auto& child : children_pids){\n          kill(child, SIGSTOP);\n        }\n\n        // find last executing core ID for each child\n        for(const auto& child : children_pids){\n          auto core_iter = children_cores.find(child);\n          if(core_iter == end(children_cores)){\n            auto& elem = children_cores[child];\n            elem.second = kTotalCoreAssignments;\n            core_iter = children_cores.find(child);\n          }\n          if(core_iter->second.second > 0){\n            core_iter->second.second--;\n            stringstream proc_fname;\n            proc_fname << \"/proc/\" << child << \"/stat\";\n            ifstream procfile(proc_fname.str());\n            if(!procfile.is_open()){\n              cerr << \"Error: couldn't open proc file!\\n\";\n              exit(-1);\n            }\n            string line;\n            // ignore the first kProcStatIdx lines\n            for(unsigned int i = 0; i < kProcStatIdx; ++i){\n              getline(procfile, line, ' ');\n            }\n            core_iter->second.first = stoi(line);\n          }\n        }\n        \n        // collect stats from cores\n        print(\"EAUDIT collating stats\\n\");\n        // read all rapl counters\n        vector<stats_t> stats(ncores);\n        for(unsigned int i = 0; i < ncores; ++i){\n          stats[i] = read_rapl(core_counters[i], period);\n        }\n        auto cur_global_stats = read_rapl(global_counters, period);\n        global_stats += cur_global_stats;\n        cout << \"p: \" << cur_global_stats.counters[0] << endl;\n        cout << \"u: \" << cur_global_stats.counters[1] << endl;\n        cout << \"m: \" << cur_global_stats.counters[2] << endl;\n\n        // global counter 0 is processor plane energy\n        auto proc_energies = modelPerCoreEnergies(\n          proc_model, stats, counter_names, cur_global_stats.counters[0]);\n\n        // global counter 1 is package energy, including the processor plane\n        // (which we have to remove to calcluate uncore energy\n        auto uncore_energies = modelPerCoreEnergies(\n          uncore_model, stats, counter_names, cur_global_stats.counters[1] - cur_global_stats.counters[0]);\n        // global counter 2 is DRAM energy\n        auto dram_energies = modelPerCoreEnergies(\n          dram_model, stats, counter_names, cur_global_stats.counters[2]);\n\n        // read all the children registers\n        for(const auto& child : children_pids){\n          struct user_regs_struct regs;\n          ptrace(PTRACE_GETREGS, child, nullptr, &regs);\n          void* rip = (void*)regs.rip;\n          auto child_core = children_cores[child].first;\n          // TODO This is a hack to avoid attempting to log threads that \n          // miraculously end up on the second hardware thread of a core.\n          // We try to make sure things are bound appropriately, but there's\n          // no guarantee, so we just ignore things that happen where we don't\n          // want them.\n          if((unsigned)child_core >= ncores) { continue; }\n          auto& profile = core_profiles[child_core][rip];\n          profile.processor_energy += proc_energies[child_core];\n          profile.uncore_energy += uncore_energies[child_core];\n          profile.dram_energy += dram_energies[child_core];\n          profile.time += stats[child_core].time;\n          profile.instructions += stats[child_core].counters[inst_counter_idx];\n        }\n        \n        // resume all children\n        for(const auto& child : children_pids){\n          ptrace(PTRACE_CONT, child, nullptr, nullptr);\n        }\n        is_timer_done = false;\n        // resume timer\n        work_time.it_value.tv_sec = sleep_secs;\n        work_time.it_value.tv_usec = sleep_usecs;\n        setitimer(ITIMER_REAL, &work_time, nullptr);\n      } else {\n        cerr << \"Error: unexpected return from wait - \" << strerror(errno) << \"\\n\";\n        exit(-1);\n      }\n    } else { // good wait, add new thread\n      if(status>>8 == (SIGTRAP | (PTRACE_EVENT_CLONE<<8))) { // new thread created\n        print(\"New thread created.\\n\");\n        unsigned long new_pid;\n        ptrace(PTRACE_GETEVENTMSG, wait_res, nullptr, &new_pid);\n        auto pid_iter = find(begin(children_pids), end(children_pids), new_pid);\n        if(pid_iter != end(children_pids)) {\n          cerr << \"Already have this newly cloned pid: \" << new_pid << \".\\n\";\n          exit(-1);\n        }\n        print(\"Thread ID %lu created from thread ID %d\\n\", new_pid, wait_res);\n        children_pids.push_back(new_pid);\n        ptrace(PTRACE_SETOPTIONS, new_pid, nullptr,\n               PTRACE_O_EXITKILL | PTRACE_O_TRACECLONE | PTRACE_O_TRACEEXIT);\n        ptrace(PTRACE_CONT, wait_res, nullptr, nullptr);\n      } else {\n        if(status>>8 == (SIGTRAP | (PTRACE_EVENT_EXIT<<8))){\n          print(\"Deleting child %d\\n\", wait_res);\n          auto pid_iter = find(begin(children_pids), end(children_pids), wait_res);\n          if(pid_iter == end(children_pids)){\n            cerr << \"Error: Saw exit from pid \" << wait_res << \". We haven't seen before!\\n\";\n            exit(-1);\n          }\n          children_pids.erase(pid_iter);\n          if(children_pids.size() == 0){ // All done, not tracking any more threads\n            break;\n          }\n          print(\"%lu children left\\n\", children_pids.size());\n        }\n        // always let the stopped tracee continue\n        ptrace(PTRACE_CONT, wait_res, nullptr, nullptr);\n      }\n    }\n  }\n  auto elapsed_time = PAPI_get_real_usec() - start_time;\n\n  /*\n   * Done profiling. Convert data to output file.\n   */\n  print(\"Finalize profile.\\n\");\n  auto profile_start_time = PAPI_get_real_usec();\n  for(unsigned int i = 0; i < ncores; ++i){\n    vector<ProfileEntry> profile;\n    // Convert stack IDs into function names.\n    for (auto& core_profile : core_profiles[i]) {\n      stringstream cmd;\n      cmd << \"addr2line -f -s -C -e \" << profilee_name << \" \" << core_profile.first;\n      auto pipe = popen(cmd.str().c_str(), \"r\");  // call command and read output\n      if (!pipe) {\n        cerr << \"Unable to open pipe to call addr2line.\\n\";\n        return;\n      }\n      char buffer[128];\n      string result = \"\";\n      while (!feof(pipe)) {\n        if (fgets(buffer, 128, pipe) != nullptr) {\n          result += buffer;\n        }\n      }\n      pclose(pipe);\n      stringstream resultstream{result};\n      string func_name, file_name;\n      getline(resultstream, func_name);\n      getline(resultstream, file_name);\n      // NOTE: remove the trailing function annotation that says that this \n      // function has been used/called by different threads\n      if(func_name.back() == ']'){\n        auto last_open_bracket_pos = func_name.find_last_of('[');\n        func_name.erase(last_open_bracket_pos - 1);\n      }\n      file_name.erase(file_name.find(':'));\n      string entry_name = func_name + \" at \" + file_name;\n      print(\"Reporting function %s\\n\", entry_name.c_str());\n\n      auto profile_iter =\n          find_if(begin(profile), end(profile),\n                  [&](const ProfileEntry& e) { return e.name == entry_name; });\n      if(profile_iter == end(profile)){\n        ProfileEntry entry;\n        entry.name = entry_name;\n        profile.push_back(entry);\n        profile_iter = end(profile) - 1;\n      }\n      profile_iter->processor_energy += core_profile.second.processor_energy;\n      profile_iter->uncore_energy += core_profile.second.uncore_energy;\n      profile_iter->dram_energy += core_profile.second.dram_energy;\n      profile_iter->time += core_profile.second.time;\n      profile_iter->instructions += core_profile.second.instructions;\n    }\n    sort(begin(profile), end(profile),\n         [&](const ProfileEntry& a, const ProfileEntry& b) {\n           auto a_energy = a.processor_energy + a.uncore_energy + a.dram_energy;\n           auto b_energy = b.processor_energy + b.uncore_energy + b.dram_energy;\n           return a_energy > b_energy;\n         });\n\n    /*\n     * Write profile to file\n     */\n    stringstream namestream;\n    namestream << prefix << \".\" << i << \".tsv\";\n    ofstream outfile{namestream.str()};\n    outfile << \"Name\\tProcessor Energy\\tUncore Energy\\tDRAM Energy\\tTime\\tInstructions\\n\";\n    for(const auto& elem : profile){\n      outfile << elem.name << \"\\t\"\n              << elem.processor_energy / kNanoToBase << \"\\t\"\n              << elem.uncore_energy / kNanoToBase << \"\\t\"\n              << elem.dram_energy / kNanoToBase << \"\\t\"\n              << elem.time / kMicroToBase << \"\\t\"\n              << elem.instructions << \"\\n\";\n    }\n  }\n\n  cout << \"Total Processor Energy:\\t\" << global_stats.counters[0] / (double)kNanoToBase << \" joules\\n\"\n       << \"Total Uncore Energy:\\t\" << (global_stats.counters[1] - global_stats.counters[0]) / (double)kNanoToBase << \" joules\\n\"\n       << \"Total DRAM Energy:\\t\" << global_stats.counters[2] / (double)kNanoToBase << \" joules\\n\"\n       << \"Elapsed Time:\\t\" << elapsed_time / (double)kMicroToBase << \" seconds\\n\";\n\n  auto profile_elapsed = PAPI_get_real_usec() - profile_start_time;\n  cout << \"Profile creation time:\\t\" << profile_elapsed / (double) kMicroToBase << \" seconds\\n\";\n}\n\n\nint main(int argc, char* argv[], char* envp[]) {\n  /*\n   * Check params\n   */\n  auto usage = \n    \"Usage:\\n\"\n    \" eaudit [options] executable\\n\"\n    \"\\n\"\n    \"Options:\\n\"\n    \" -h                  Show this help\\n\"\n    \" -p <microseconds>   Sample period in microseconds, default 1000\\n\"\n    \" -o <prefix>         Prefix to use when writing files, default eaudit\\n\"\n    \" -m <filename>       Model file name, default 'default.model'\\n\"\n    \"\\n\";\n\n  auto period = kDefaultSamplePeriodUsecs;\n  auto proc_model_fname = kDefaultModelName;\n  auto uncore_model_fname = kDefaultModelName;\n  auto dram_model_fname = kDefaultModelName;\n  auto prefix = kDefaultPrefix;\n  int param;\n  while((param = getopt(argc, argv, \"+hp:o:c:u:m:\")) != -1){\n    switch(param){\n      case 'p':\n        period = stol(optarg);\n        break;\n      case 'o':\n        prefix = optarg;\n        break;\n      case 'c':\n        {\n          proc_model_fname = optarg;\n        }\n        break;\n      case 'u':\n        {\n          uncore_model_fname = optarg;\n        }\n        break;\n      case 'm':\n        {\n          dram_model_fname = optarg;\n        }\n        break;\n      case 'h':\n      case '?':\n        cout << usage;\n        exit(0);\n        break;\n      default:\n        cerr << \"Error: bad getopt parse of parameter.\\n\";\n        exit(-1);\n        break;\n    }\n  }\n\n  /*\n   * Make our models\n   */\n  Model proc_model{proc_model_fname};\n  Model uncore_model{uncore_model_fname};\n  Model dram_model{dram_model_fname};\n\n  /*\n   * Fork a process to run the profiled application\n   */\n  auto profilee = fork();\n  if(profilee > 0){ /* parent */\n    // Let's do this.\n    ptrace(PTRACE_SETOPTIONS, profilee, nullptr,\n           PTRACE_O_EXITKILL | PTRACE_O_TRACECLONE | PTRACE_O_TRACEEXIT);\n    do_profiling(profilee, argv[optind], period, prefix, proc_model, uncore_model, dram_model);\n  } else if(profilee == 0){ /* profilee */\n    // prepare for tracing\n    ptrace(PTRACE_TRACEME, 0, nullptr, nullptr);\n    raise(SIGSTOP);\n    // start up client program\n    execve(argv[optind], &argv[optind], envp);\n    cerr << \"Error: profilee couldn't start its program!\\n\";\n    perror(nullptr);\n    exit(-1);\n  } else { /* error */\n    cerr << \"Error: couldn't fork audited program.\\n\";\n    return -1;\n  }\n}\n\n", "meta": {"hexsha": "29fd53498574a51109c928eb21cd8a9543700414", "size": 25436, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tracing/eaudit.cpp", "max_stars_repo_name": "gtcasl/eaudit", "max_stars_repo_head_hexsha": "6240524d47afd961b567dbee1ac4c8f40dc339d1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-10-30T09:12:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T14:44:18.000Z", "max_issues_repo_path": "tracing/eaudit.cpp", "max_issues_repo_name": "gtcasl/eaudit", "max_issues_repo_head_hexsha": "6240524d47afd961b567dbee1ac4c8f40dc339d1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tracing/eaudit.cpp", "max_forks_repo_name": "gtcasl/eaudit", "max_forks_repo_head_hexsha": "6240524d47afd961b567dbee1ac4c8f40dc339d1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-04-28T11:31:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-15T14:44:22.000Z", "avg_line_length": 35.1811894882, "max_line_length": 128, "alphanum_fraction": 0.6308774965, "num_tokens": 6287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.2767862659953361}}
{"text": "//\n// GMOM.cpp\n//\n// Copyright (c) 2017 Shion Hosoda\n//\n// This software is released under the MIT License.\n// http://opensource.org/licenses/mit-license.php\n//\n\n//include{{{\n#include <stdlib.h>\n#include <boost/program_options.hpp>\n#include <boost/mpi/environment.hpp>\n#include <boost/mpi/communicator.hpp>\n#include <boost/mpi/collectives.hpp>\n#include \"include/CsvFileParser.hpp\"\n#include \"include/GibbsSamplerFromGMOM.hpp\"\n//}}}\n\nusing namespace std;\n\nint main(int argc, char *argv[]){\n\n    //Options{{{\n    boost::program_options::options_description opt(\"Options\");\n    opt.add_options()\n    (\"help,h\", \"show help\")\n    (\"otpt,o\", boost::program_options::value<string>()->default_value(\"./\"), \"directory name for output\")\n    (\"itnm,n\", boost::program_options::value<unsigned int>()->default_value(1000), \"the number of iteration\")\n    (\"intr,i\", boost::program_options::value<unsigned int>()->default_value(5), \"sampling interval\")\n    (\"bnin,b\", boost::program_options::value<unsigned int>()->default_value(500), \"burn-in term\")\n    (\"k,k\", boost::program_options::value<double>()->default_value(1.0), \"k value\")\n    (\"theta,t\", boost::program_options::value<double>()->default_value(1.0), \"theta value\")\n    (\"A,A\", boost::program_options::value<double>()->default_value(1000.0), \"A value\")\n    ;\n\n    boost::program_options::positional_options_description pd;\n    pd.add(\"orthologfile\", 1);\n    pd.add(\"microbefile\", 2);\n\n    boost::program_options::options_description hidden(\"hidden\");\n    hidden.add_options()\n        (\"orthologfile\", boost::program_options::value<string>(), \"hidden\")\n        (\"microbefile\", boost::program_options::value<string>(), \"hidden\")\n        ;\n    boost::program_options::options_description cmdline_options;\n    cmdline_options.add(opt).add(hidden);\n\n    boost::program_options::variables_map vm;\n    try{\n        boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(cmdline_options).positional(pd).run(), vm);\n    }catch(const boost::program_options::error_with_option_name& e){\n        cout<<e.what()<<endl;\n    }\n    boost::program_options::notify(vm);\n    string orthologFilename;\n    string microbeFilename;\n    double k, theta, A;\n    unsigned int iterationNumber;\n    unsigned int samplingInterval;\n    unsigned int burnIn;\n    string outputDirectory;\n    string PFilename;\n    string VFilename;\n    string logLikelihoodFilename;\n    if (vm.count(\"help\") || !vm.count(\"orthologfile\") || !vm.count(\"microbefile\")){\n        cout<<\"Usage:\\n GMOM [ortholog file] [microbe file] [-options] \"<<endl;\n        cout<<endl;\n        cout<<opt<<endl;\n        exit(1);\n    }else{\n        orthologFilename = vm[\"orthologfile\"].as<std::string>();\n        microbeFilename = vm[\"microbefile\"].as<std::string>();\n        if(vm.count(\"k\"))k = vm[\"k\"].as<double>();\n        if(vm.count(\"theta\"))theta = vm[\"theta\"].as<double>();\n        if(vm.count(\"A\"))A = vm[\"A\"].as<double>();\n        if(vm.count(\"itnm\"))iterationNumber = vm[\"itnm\"].as<unsigned int>();\n        if(vm.count(\"intr\"))samplingInterval = vm[\"intr\"].as<unsigned int>();\n        if(vm.count(\"bnin\"))burnIn = vm[\"bnin\"].as<unsigned int>();\n        if(vm.count(\"otpt\"))outputDirectory = vm[\"otpt\"].as<std::string>();\n        if(outputDirectory[outputDirectory.size()-1] != '/')outputDirectory.push_back('/');\n        PFilename = outputDirectory + \"P.csv\";\n        VFilename = outputDirectory + \"V.csv\";\n        logLikelihoodFilename = outputDirectory + \"LogLikelihood.csv\";\n    }\n\n    CsvFileParser<double> orthologFile(orthologFilename);\n    CsvFileParser<double> microbeFile(microbeFilename);\n    orthologFile.convertLog();\n    //}}}\n\n//estimation{{{\n    GibbsSamplerFromGMOM *estimator;\n    bmpi::environment env(argc, argv);\n    bmpi::communicator world;\n    estimator = new GibbsSamplerFromGMOM(orthologFile, microbeFile, A, k, theta, iterationNumber, burnIn, samplingInterval, world);\n    estimator->runIteraions();\n    if(world.rank() == 0){\n        estimator->writeParameters(PFilename, VFilename);\n        estimator->writeLogLikelihood(logLikelihoodFilename);\n    }\n    delete estimator;\n//}}}\n    return 0;\n}\n", "meta": {"hexsha": "727bd16bb74367b84e8eeeccc10047b0eca89124", "size": 4148, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/GMOM.cpp", "max_stars_repo_name": "shion-h/GenerativeMicrobialOrthologModel", "max_stars_repo_head_hexsha": "d1a9f1c88386bffc7291d806e901518723ba3286", "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/GMOM.cpp", "max_issues_repo_name": "shion-h/GenerativeMicrobialOrthologModel", "max_issues_repo_head_hexsha": "d1a9f1c88386bffc7291d806e901518723ba3286", "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/GMOM.cpp", "max_forks_repo_name": "shion-h/GenerativeMicrobialOrthologModel", "max_forks_repo_head_hexsha": "d1a9f1c88386bffc7291d806e901518723ba3286", "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.1320754717, "max_line_length": 145, "alphanum_fraction": 0.6656219865, "num_tokens": 1024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2766969109607446}}
{"text": "/** This is free and unencumbered software released into the public domain.\nThe authors of ISIS do not claim copyright on the contents of this file.\nFor more details about the LICENSE terms and the AUTHORS, you will\nfind files of those names at the top level of this repository. **/\n\n/* SPDX-License-Identifier: CC0-1.0 */\n#include \"jama/jama_svd.h\"\n#include \"jama/jama_qr.h\"\n\n#include <armadillo>\n\n#include \"LeastSquares.h\"\n#include \"IException.h\"\n#include \"IString.h\"\n\nnamespace Isis {\n  /**\n   * Creates a LeastSquares Object.\n   *\n   * @param basis A BasisFunction. This parameter allows for the least squares\n   *              fitting to be applied to arbitrary equations.\n   */\n  LeastSquares::LeastSquares(Isis::BasisFunction &basis, bool sparse,\n                             int sparseRows, int sparseCols, bool jigsaw) {\n    p_jigsaw = jigsaw;\n    p_basis = &basis;\n    p_solved = false;\n    p_sparse = sparse;\n    p_sigma0 = 0.;\n\n    p_sparseRows = sparseRows;\n    p_sparseCols = sparseCols;\n\n\n    if (p_sparse) {\n\n      //  make sure sparse nrows/ncols have been set\n      if (sparseRows == 0  ||  sparseCols == 0) {\n        QString msg = \"If solving using sparse matrices, you must enter the \"\n                      \"number of rows/columns\";\n        throw IException(IException::Programmer, msg, _FILEINFO_);\n      }\n\n\n      p_sparseA.set_size(sparseRows, sparseCols);\n      p_normals.set_size(sparseCols, sparseCols);\n      p_ATb.resize(sparseCols, 1);\n      p_xSparse.resize(sparseCols);\n\n      if( p_jigsaw ) {\n        p_epsilonsSparse.resize(sparseCols);\n        std::fill_n(p_epsilonsSparse.begin(), sparseCols, 0.0);\n\n        p_parameterWeights.resize(sparseCols);\n      }\n\n    }\n    p_currentFillRow = -1;\n  }\n\n  //! Destroys the LeastSquares object.\n  LeastSquares::~LeastSquares() {\n  }\n\n  /**\n   * Invoke this method for each set of knowns. Given our example in the\n   * description, we have three knowns and expecteds. They are\n   * @f[\n   * (1,1) = 3\n   * @f]\n   * @f[\n   * (-2,3) = 1\n   * @f]\n   * @f[\n   * (2,-1) = 2\n   * @f]\n   *\n   * @param data A vector of knowns.\n   *\n   * @param result The expected value for the knowns.\n   *\n   * @param weight (Default = 1.0) How strongly to weight this known. Weight less\n   *               than 1 increases residual for this known, while weight greater\n   *               than 1 decreases the residual for this known.\n   *\n   * @throws Isis::IException::Programmer - Number of elements in data does not\n   *                                        match basis requirements\n   *\n   * @internal\n   * @history 2008-04-22  Tracie Sucharski,  Fill sparse matrix.\n   * @history 2009-12-21  Jeannie Walldren,  Modified code to add\n   *          the square root of the weight to the vector\n   *          p_sqrtweight.\n   *\n   */\n  void LeastSquares::AddKnown(const std::vector<double> &data, double result,\n                              double weight) {\n    if((int) data.size() != p_basis->Variables()) {\n      QString msg = \"Number of elements in data does not match basis [\" +\n                        p_basis->Name() + \"] requirements\";\n      throw IException(IException::Programmer, msg, _FILEINFO_);\n    }\n\n    p_expected.push_back(result);\n\n    if (weight == 1) {\n      p_sqrtWeight.push_back(weight);\n    }\n    else {\n      p_sqrtWeight.push_back(sqrt(weight));\n    }\n\n    if(p_sparse) {\n      FillSparseA(data);\n    }\n    else {\n      p_input.push_back(data);\n    }\n  }\n\n\n\n  /**\n   *  Invoke this method for each set of knowns for sparse solutions.  The A\n   *  sparse matrix must be filled as we go or we will quickly run out of memory\n   *  for large solutions. So, expand the basis function, apply weights (which is\n   *  done in the Solve method for the non-sparse case.\n   *\n   * @param data A vector of knowns.\n   *\n   * @internal\n   * @history 2008-04-22  Tracie Sucharski - New method for sparse solutions.\n   * @history 2009-12-21  Jeannie Walldren - Changed variable name\n   *          from p_weight to p_sqrtweight.\n   *\n   */\n  void LeastSquares::FillSparseA(const std::vector<double> &data) {\n\n    p_basis->Expand(data);\n\n    p_currentFillRow++;\n\n    int ncolumns = (int)data.size();\n\n    for(int c = 0;  c < ncolumns; c++) {\n      p_sparseA(p_currentFillRow, c) = p_basis->Term(c) * p_sqrtWeight[p_currentFillRow];\n    }\n  }\n\n\n  /**\n   * This method returns the data at the given row.\n   *\n   * @param row\n   *\n   * @return std::vector<double>\n   */\n  std::vector<double> LeastSquares::GetInput(int row) const {\n    if((row >= Rows()) || (row < 0)) {\n      QString msg = \"Index out of bounds [Given = \" + toString(row) + \"]\";\n      throw IException(IException::Programmer, msg, _FILEINFO_);\n    }\n    return p_input[row];\n  }\n\n  /**\n   * This method returns the expected value at the given row.\n   *\n   * @param row\n   *\n   * @return double\n   */\n  double LeastSquares::GetExpected(int row) const {\n    if((row >= Rows()) || (row < 0)) {\n      QString msg = \"Index out of bounds [Given = \" + toString(row) + \"]\";\n      throw IException(IException::Programmer, msg, _FILEINFO_);\n    }\n    return p_expected[row];\n  }\n\n  /**\n   * This methods returns the number of rows in the matrix.\n   *\n   *\n   * @return int\n   */\n  int LeastSquares::Rows() const {\n    return (int)p_input.size();\n  }\n\n  /**\n   * After all the data has been registered through AddKnown, invoke this\n   * method to solve the system of equations. You can then use the Evaluate\n   * and Residual methods freely.\n   *\n   * @internal\n   * @history  2008-04-16 Debbie Cook / Tracie Sucharski, Added SolveSparse.\n   * @history  2009-04-08 Tracie Sucharski - Added return value which will\n   *                          pass on what is returned from SolveSparse which\n   *                          is a column number of a column that contained\n   *                          all zeros.\n   * @history  2010-12-12 Debbie A. Cook  Fixed \"no data\" test for SPARSE\n   *                          case\n   */\n  int LeastSquares::Solve(Isis::LeastSquares::SolveMethod method) {\n\n    if((method == SPARSE  &&  p_sparseRows == 0)  ||\n       (method != SPARSE  &&  Rows() == 0 )) {\n      p_solved = false;\n      QString msg = \"No solution available because no input data was provided\";\n      throw IException(IException::Unknown, msg, _FILEINFO_);\n    }\n\n    if(method == SVD) {\n      SolveSVD();\n    }\n    else if(method == QRD) {\n      SolveQRD();\n    }\n    else if(method == SPARSE) {\n      int column = SolveSparse();\n      return column;\n    }\n    return 0;\n  }\n\n  /**\n   * After all the data has been registered through AddKnown, invoke this\n   * method to solve the system of equations. You can then use the Evaluate\n   * and Residual methods freely.\n   * @internal\n   * @history 2009-12-21  Jeannie Walldren - Changed variable name\n   *          from p_weight to p_sqrtweight.\n   *\n   */\n  void LeastSquares::SolveSVD() {\n\n    // We are solving Ax=b ... start by creating A\n    TNT::Array2D<double> A(p_input.size(), p_basis->Coefficients());\n    for(int r = 0; r < A.dim1(); r++) {\n      p_basis->Expand(p_input[r]);\n      for(int c = 0; c < A.dim2(); c++) {\n        A[r][c] = p_basis->Term(c) * p_sqrtWeight[r];\n      }\n    }\n\n    // Ok use singular value decomposition to solve for the coefficients\n    // A = [U][S][V']  where [U] is MxN, [S] is NxN, [V'] is NxN transpose\n    // of [V].  We are solving for [A]x=b and need inverse of [A] such\n    // that x = [invA]b. Since inverse may not exist we use the\n    // pseudo-inverse [A+] from SVD which is [A+] = [V][invS][U']\n    // Our coefficents are then x = [A+]b where b is p_b.\n    JAMA::SVD<double> svd(A);\n\n    TNT::Array2D<double> V;\n    svd.getV(V);\n\n    // The inverse of S is the 1 over each diagonal element of S\n    TNT::Array2D<double> invS;\n    svd.getS(invS);\n\n    for(int i = 0; i < invS.dim1(); i++) {\n      if(invS[i][i] != 0.0) invS[i][i] = 1.0 / invS[i][i];\n    }\n\n    // Transpose U\n    TNT::Array2D<double> U;\n    svd.getU(U);\n    TNT::Array2D<double> transU(U.dim2(), U.dim1());\n\n    for(int r = 0; r < U.dim1(); r++) {\n      for(int c = 0; c < U.dim2(); c++) {\n        transU[c][r] = U[r][c];\n      }\n    }\n\n    // Now multiply everything together to get [A+]\n    TNT::Array2D<double> VinvS = TNT::matmult(V, invS);\n    TNT::Array2D<double> Aplus = TNT::matmult(VinvS, transU);\n\n    // Using Aplus and our b we can solve for the coefficients\n    TNT::Array2D<double> b(p_expected.size(), 1);\n\n    for(int r = 0; r < (int)p_expected.size(); r++) {\n      b[r][0] = p_expected[r] * p_sqrtWeight[r];\n    }\n\n    TNT::Array2D<double> coefs = TNT::matmult(Aplus, b);\n\n    // If the rank of the matrix is not large enough we don't\n    // have enough coefficients for the solution\n    if (coefs.dim1() < p_basis->Coefficients()) {\n      QString msg = \"Unable to solve least-squares using SVD method. No \"\n                    \"solution available. Not enough knowns or knowns are \"\n                    \"co-linear ... [Unknowns = \"\n                    + toString(p_basis->Coefficients()) + \"] [Knowns = \"\n                    + toString(coefs.dim1()) + \"]\";\n      throw IException(IException::Unknown, msg, _FILEINFO_);\n    }\n\n    // Set the coefficients in our basis equation\n    std::vector<double> bcoefs;\n    for (int i = 0; i < coefs.dim1(); i++) bcoefs.push_back(coefs[i][0]);\n\n    p_basis->SetCoefficients(bcoefs);\n\n    // Compute the errors\n    for(int i = 0; i < (int)p_input.size(); i++) {\n      double value = p_basis->Evaluate(p_input[i]);\n      p_residuals.push_back(value - p_expected[i]);\n      p_sigma0 += p_residuals[i]*p_residuals[i]*p_sqrtWeight[i]*p_sqrtWeight[i];\n    }\n    // calculate degrees of freedom (or redundancy)\n    // DOF = # observations + # constrained parameters - # unknown parameters\n    p_degreesOfFreedom = p_basis->Coefficients() - coefs.dim1();\n\n    if( p_degreesOfFreedom > 0.0 )  {\n      p_sigma0 = p_sigma0/(double)p_degreesOfFreedom;\n    }\n\n    // check for p_sigma0 < 0\n    p_sigma0 = sqrt(p_sigma0);\n\n    // All done\n    p_solved = true;\n  }\n\n  /**\n   * After all the data has been registered through AddKnown, invoke this\n   * method to solve the system of equations with a QR\n   * decomposition of A = QR. You can then use the Evaluate and\n   * Residual methods freely. The QR decomposition is only slightly\n   * less reliable than the SVD, but much faster.\n   * @internal\n   * @history 2009-12-21  Jeannie Walldren - Changed variable name\n   *          from p_weight to p_sqrtweight.\n   *\n   */\n  void LeastSquares::SolveQRD() {\n\n    // We are solving Ax=b ... start by creating an MxN matrix, A\n    TNT::Array2D<double> A(p_input.size(), p_basis->Coefficients());\n    for(int r = 0; r < A.dim1(); r++) {\n      p_basis->Expand(p_input[r]);\n      for(int c = 0; c < A.dim2(); c++) {\n        A[r][c] = p_basis->Term(c) * p_sqrtWeight[r];\n      }\n    }\n\n    // Ok use  to solve for the coefficients\n    // [A] = [Q][R]  where [Q] is MxN and orthogonal and  [R] is an NxN,\n    // upper triangular matrix.  TNT provides the solve method that inverts\n    // [Q] and backsolves [R] to get the coefficients in the vector x.\n    // That is, we solve the system Rx = Q^T b\n    JAMA::QR<double> qr(A);\n\n    // Using A and our b we can solve for the coefficients\n    TNT::Array1D<double> b(p_expected.size());\n    for(int r = 0; r < (int)p_expected.size(); r++) {\n      b[r] = p_expected[r] * p_sqrtWeight[r];\n    }// by construction, we know the size of b is equal to M, so b is conformant\n\n    // Check to make sure the matrix is full rank before solving\n    // -- rectangular matrices must be full rank in order for the solve method\n    //    to be successful\n    int full = qr.isFullRank();\n    if(full == 0) {\n      QString msg = \"Unable to solve-least squares using QR Decomposition. \"\n                    \"The upper triangular R matrix is not full rank\";\n      throw IException(IException::Unknown, msg, _FILEINFO_);\n    }\n\n    TNT::Array1D<double> coefs = qr.solve(b);\n\n    // Set the coefficients in our basis equation\n    std::vector<double> bcoefs;\n    for(int i = 0; i < coefs.dim1(); i++) {\n      bcoefs.push_back(coefs[i]);\n    }\n    p_basis->SetCoefficients(bcoefs);\n\n    // Compute the errors\n    for(int i = 0; i < (int)p_input.size(); i++) {\n      double value = p_basis->Evaluate(p_input[i]);\n      p_residuals.push_back(value - p_expected[i]);\n    }\n\n    // All done\n    p_solved = true;\n  }\n\n\n\n\n  /**\n   * @brief  Solve using sparse class\n   *\n   * After all the data has been registered through AddKnown, invoke this\n   * method to solve the system of equations Nx = b, where\n   *\n   * N = ATPA\n   * b = ATPl, and\n   *\n   * N is the \"normal equations matrix;\n   * A is the so-called \"design\" matrix;\n   * P is the observation weight matrix (typically diagonal);\n   * l is the \"computed - observed\" column vector;\n   *\n   * The solution is achieved using a sparse matrix formulation of\n   * the LU decomposition of the normal equations.\n   *\n   * You can then use the Evaluate and Residual methods freely.\n   *\n   * @internal\n   * @history  2008-04-16 Debbie Cook / Tracie Sucharski, New method\n   * @history  2008-04-23 Tracie Sucharski,  Fill sparse matrix as we go in\n   *                          AddKnown method rather than in the solve method,\n   *                          otherwise we run out of memory very quickly.\n   * @history  2009-04-08 Tracie Sucharski - Added return value which is a\n   *                          column number of a column that contained all zeros.\n   * @history 2009-12-21  Jeannie Walldren - Changed variable name\n   *                          from p_weight to p_sqrtweight.\n   * @history 2010        Ken Edmundson\n   * @history 2010-11-20  Debbie A. Cook Merged Ken Edmundson verion with system version\n   * @history 2011-03-17  Ken Edmundson Corrected computation of residuals\n   *\n   */\n  int LeastSquares::SolveSparse() {\n\n    // form \"normal equations\" matrix by multiplying ATA\n    p_normals = p_sparseA.t()*p_sparseA;\n\n    // Create the right-hand-side column vector 'b'\n    arma::mat b(p_sparseRows, 1);\n\n    // multiply each element of 'b' by it's associated weight\n    for ( int r = 0; r < p_sparseRows; r++ )\n      b(r,0) = p_expected[r] * p_sqrtWeight[r];\n\n    // form ATb\n    p_ATb = p_sparseA.t()*b;\n\n    // apply parameter weighting if Jigsaw (bundle adjustment)\n    if ( p_jigsaw ) {\n      for( int i = 0; i < p_sparseCols; i++) {\n        double weight = p_parameterWeights[i];\n\n        if( weight <= 0.0 )\n          continue;\n\n        p_normals(i, i) += weight;\n        p_ATb(i, 0) -= p_epsilonsSparse[i]*weight;\n      }\n    }\n\n    bool status = spsolve(p_xSparse, p_normals, p_ATb, \"superlu\");\n\n    if (status == false) {\n      QString msg = \"Could not solve sparse least squares problem.\";\n      throw IException(IException::Unknown, msg, _FILEINFO_);\n    }\n\n    // Set the coefficients in our basis equation\n    p_basis->SetCoefficients(arma::conv_to< std::vector<double> >::from(p_xSparse));\n\n    // if Jigsaw (bundle adjustment)\n    // add corrections into epsilon vector (keeping track of total corrections)\n    if ( p_jigsaw ) {\n      for( int i = 0; i < p_sparseCols; i++ )\n        p_epsilonsSparse[i] += p_xSparse[i];\n    }\n\n    // Compute the image coordinate residuals and sum into Sigma0\n    // (note this is exactly what was being done before, but with less overhead - I think)\n    // ultimately, we should not be using the A matrix but forming the normals\n    // directly. Then we'll have to compute the residuals by back projection\n\n    p_residuals.resize(p_sparseRows);\n    p_residuals = arma::conv_to< std::vector<double> >::from(p_sparseA*p_xSparse);\n    p_sigma0 = 0.0;\n\n    for ( int i = 0; i < p_sparseRows; i++ ) {\n        p_residuals[i] = p_residuals[i]/p_sqrtWeight[i];\n        p_residuals[i] -= p_expected[i];\n        p_sigma0 += p_residuals[i]*p_residuals[i]*p_sqrtWeight[i]*p_sqrtWeight[i];\n    }\n\n    // if Jigsaw (bundle adjustment)\n    // add contibution to Sigma0 from constrained parameters\n    if ( p_jigsaw ) {\n      double constrained_vTPv = 0.0;\n\n      for ( int i = 0; i < p_sparseCols; i++ ) {\n        double weight = p_parameterWeights[i];\n\n        if ( weight <= 0.0 )\n          continue;\n\n        constrained_vTPv += p_epsilonsSparse[i]*p_epsilonsSparse[i]*weight;\n      }\n      p_sigma0 += constrained_vTPv;\n    }\n    // calculate degrees of freedom (or redundancy)\n    // DOF = # observations + # constrained parameters - # unknown parameters\n    p_degreesOfFreedom = p_sparseRows + p_constrainedParameters - p_sparseCols;\n\n    if( p_degreesOfFreedom <= 0.0 ) {\n      p_sigma0 = 1.0;\n    }\n    else {\n      p_sigma0 = p_sigma0/(double)p_degreesOfFreedom;\n    }\n\n    // check for p_sigma0 < 0\n    p_sigma0 = sqrt(p_sigma0);\n\n    // All done\n    p_solved = true;\n    return 0;\n  }\n\n\n  void LeastSquares::Reset ()\n  {\n    if ( p_sparse ) {\n      p_sparseA.zeros();\n      p_ATb.zeros();\n      p_normals.zeros();\n      p_currentFillRow = -1;\n    }\n    else {\n      p_input.clear();\n    }\n      p_sigma0 = 0.;\n    p_residuals.clear();\n    p_expected.clear();\n    p_sqrtWeight.clear();\n    p_solved = false;\n  }\n\n\n\n  /**\n   * Invokes the BasisFunction Evaluate method.\n   *\n   * @param data The input variables to evaluate.\n   *\n   * @return The evaluation for the input variable.\n   *\n   * @throws Isis::IException::Programmer - Unable to evaluate until a\n   *                                        solution has been computed\n   */\n  double LeastSquares::Evaluate(const std::vector<double> &data) {\n    if(!p_solved) {\n      QString msg = \"Unable to evaluate until a solution has been computed\";\n      throw IException(IException::Programmer, msg, _FILEINFO_);\n    }\n    return p_basis->Evaluate(data);\n  }\n\n  /**\n   * Returns a vector of residuals (errors). That is, the difference between the\n   * evaluation of a known with the solution against the expected value.\n   *\n   * @return The vector of residuals.\n   *\n   * @throws Isis::IException::Programmer - Unable to return residuals until a\n   *                                        solution has been computed\n   */\n  std::vector<double> LeastSquares::Residuals() const {\n    if(!p_solved) {\n      QString msg = \"Unable to return residuals until a solution has been computed\";\n      throw IException(IException::Programmer, msg, _FILEINFO_);\n    }\n    return p_residuals;\n  }\n\n  /**\n   * Returns the ith residual. That is, the difference between the evaluation of\n   * a known with the solution against the expected value. There is one residual\n   * for each time AddKnown was invoked.\n   *\n   * @param i The number of times AddKnown was invoked to be evaluated.\n   *\n   * @return The output value of the residual.\n   *\n   * @throws Isis::IException::Programmer - Unable to return residuals until a\n   *                                        solution has been computed\n   */\n  double LeastSquares::Residual(int i) const {\n    if(!p_solved) {\n      QString msg = \"Unable to return residuals until a solution has been computed\";\n      throw IException(IException::Programmer, msg, _FILEINFO_);\n    }\n    return p_residuals[i];\n  }\n\n  /**\n   * Reset the weight for the ith known. This weight will not be used unless\n   * the system is resolved using the Solve method.\n   *\n   * @param index The position in the array to assign the given weight value\n   * @param weight A weight factor to apply to the ith known. A weight less\n   *               than one increase the residual for this known while a\n   *               weight greater than one decrease the residual for this\n   *               known.\n   * @internal\n   * @history 2009-12-21  Jeannie Walldren,  Modified code to add\n   *          the square root of the weight to the vector\n   *          p_sqrtweight.\n   *\n   */\n\n  void LeastSquares::Weight(int index, double weight) {\n    if(weight == 1) {\n      p_sqrtWeight[index] = weight;\n    }\n    else {\n      p_sqrtWeight[index] = sqrt(weight);\n    }\n  }\n\n} // end namespace isis\n", "meta": {"hexsha": "f3a1a406d5749b08b85b8ed006c63e64d8b669b1", "size": 19891, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "isis/src/base/objs/LeastSquares/LeastSquares.cpp", "max_stars_repo_name": "kdl222/ISIS3", "max_stars_repo_head_hexsha": "aab0e63088046690e6c031881825596c1c2cc380", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 134.0, "max_stars_repo_stars_event_min_datetime": "2018-01-18T00:16:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:53:33.000Z", "max_issues_repo_path": "isis/src/base/objs/LeastSquares/LeastSquares.cpp", "max_issues_repo_name": "kdl222/ISIS3", "max_issues_repo_head_hexsha": "aab0e63088046690e6c031881825596c1c2cc380", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 3825.0, "max_issues_repo_issues_event_min_datetime": "2017-12-11T21:27:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:45:20.000Z", "max_forks_repo_path": "isis/src/base/objs/LeastSquares/LeastSquares.cpp", "max_forks_repo_name": "jlaura/isis3", "max_forks_repo_head_hexsha": "2c40e08caed09968ea01d5a767a676172ad20080", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 164.0, "max_forks_repo_forks_event_min_datetime": "2017-11-30T21:15:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T10:22:29.000Z", "avg_line_length": 31.8766025641, "max_line_length": 90, "alphanum_fraction": 0.6132421698, "num_tokens": 5394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.27669690436688293}}
{"text": "//=======================================================================\n// Copyright 2013 University of Warsaw.\n// Authors: 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#ifndef BOOST_GRAPH_AUGMENT_HPP\n#define BOOST_GRAPH_AUGMENT_HPP\n\n#include <boost/graph/filtered_graph.hpp>\n\nnamespace boost\n{\nnamespace detail\n{\n\n    template < class Graph, class ResCapMap >\n    filtered_graph< const Graph, is_residual_edge< ResCapMap > > residual_graph(\n        const Graph& g, ResCapMap residual_capacity)\n    {\n        return filtered_graph< const Graph, is_residual_edge< ResCapMap > >(\n            g, is_residual_edge< ResCapMap >(residual_capacity));\n    }\n\n    template < class Graph, class PredEdgeMap, class ResCapMap,\n        class RevEdgeMap >\n    inline void augment(const Graph& g,\n        typename graph_traits< Graph >::vertex_descriptor src,\n        typename graph_traits< Graph >::vertex_descriptor sink, PredEdgeMap p,\n        ResCapMap residual_capacity, RevEdgeMap reverse_edge)\n    {\n        typename graph_traits< Graph >::edge_descriptor e;\n        typename graph_traits< Graph >::vertex_descriptor u;\n        typedef typename property_traits< ResCapMap >::value_type FlowValue;\n\n        // find minimum residual capacity along the augmenting path\n        FlowValue delta = (std::numeric_limits< FlowValue >::max)();\n        e = get(p, sink);\n        do\n        {\n            BOOST_USING_STD_MIN();\n            delta = min BOOST_PREVENT_MACRO_SUBSTITUTION(\n                delta, get(residual_capacity, e));\n            u = source(e, g);\n            e = get(p, u);\n        } while (u != src);\n\n        // push delta units of flow along the augmenting path\n        e = get(p, sink);\n        do\n        {\n            put(residual_capacity, e, get(residual_capacity, e) - delta);\n            put(residual_capacity, get(reverse_edge, e),\n                get(residual_capacity, get(reverse_edge, e)) + delta);\n            u = source(e, g);\n            e = get(p, u);\n        } while (u != src);\n    }\n\n} // namespace detail\n} // namespace boost\n\n#endif /* BOOST_GRAPH_AUGMENT_HPP */\n", "meta": {"hexsha": "956f274cb4247e137a26a8aa7d2d5b874de8cd6b", "size": 2293, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/graph/detail/augment.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": 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": "ReactNativeFrontend/ios/Pods/boost/boost/graph/detail/augment.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": 157.0, "max_issues_repo_issues_event_min_datetime": "2019-02-06T05:04:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:50:28.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/graph/detail/augment.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": 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.223880597, "max_line_length": 80, "alphanum_fraction": 0.5987788923, "num_tokens": 501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.4610167793123158, "lm_q1q2_score": 0.27669689777302103}}
{"text": "#include <iostream>\n#include <fstream>\n#include <ctime>            \n#include <boost/random/mersenne_twister.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/tokenizer.hpp>\n\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <sys/time.h>\n\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <numeric>\n#include <queue>\n\n#include <math.h>\n#include <matrix.h>\n#include <mex.h>\n\nboost::random::mt19937 gen;\n\nusing namespace std;\n\nint collisions (int &dimx_xp, deque<int> &xist_gene, deque<int> &tsix_gene, \n        int &sum_xp, int &sum_tp, boost::random::uniform_int_distribution<> &dist)\n{\n    int q;\n    for (q=0; q<dimx_xp; q++)\n            {\n            if ((xist_gene[q] + tsix_gene[q])>1) {\n                if (dist(gen)==0) {\n                    xist_gene[q]=0;\n                    sum_xp--;\n                } else {\n                    tsix_gene[q]=0;\n                    sum_tp--;\n                }\n            }\n        }\n}\n\nint elongation (int &dimx_xp, deque<int> &xist_gene, deque<int> &tsix_gene, int &sum_xp, int &sum_tp, \n        bool &xpol_ini, bool &tpol_ini, int &xist_rna, int &tsix_rna, \n        vector<int> &all_xist, int &temp_sum_xr, int &temp_sum_tr, int &temp_sum_xp, int &temp_sum_tp,\n        boost::random::uniform_int_distribution<> &dist, int &step, double &p8)\n{\n    xist_gene.push_front(xpol_ini);\n    sum_xp = sum_xp - xist_gene.back() + xist_gene.front();\n    xist_rna = xist_rna + (int)xist_gene.back();\n    xist_gene.pop_back();\n    if (p8>0) {\n        collisions (dimx_xp, xist_gene, tsix_gene, sum_xp, sum_tp, dist);\n    }   \n    tsix_gene.push_back(tpol_ini);\n    sum_tp = sum_tp - tsix_gene.front() + tsix_gene.back();\n    tsix_rna = tsix_rna + (int)tsix_gene.front();\n    tsix_gene.pop_front();\n    if (p8>0) {\n        collisions (dimx_xp, xist_gene, tsix_gene, sum_xp, sum_tp, dist);\n    }              \n    all_xist[step] = xist_rna;\n                      \n    temp_sum_xr = temp_sum_xr + xist_rna;\n    temp_sum_tr = temp_sum_tr + tsix_rna;\n    temp_sum_xp = temp_sum_xp + sum_xp;\n    temp_sum_tp = temp_sum_tp + sum_tp;\n}\n\nvoid mexFunction(int nhls, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n{\n    \n    //initiate random number generator\n    struct timeval t1;\n    gettimeofday(&t1, NULL);\n    gen.seed(static_cast<unsigned int>(t1.tv_usec * t1.tv_sec));\n    \n\t//declare variables // pointers that point at input and output variables\n\tmxArray *xist_pol, *tsix_pol, *xist_pol2, *tsix_pol2, *par, *const_par;\n    mxArray *time_out, *xist_pol_out, *tsix_pol_out, *xist_rna_out, *tsix_rna_out, \n            *xist_pol_out2, *tsix_pol_out2, *xist_rna_out2, *tsix_rna_out2, *test, *stable_switch_on_out; \n\tconst mwSize *dims;\n\tdouble *xp, *tp, *xr, *tr, *xpr, *xp2, *tp2, *xr2, *tr2, *xpr2, *p, *cp, \n            t, sil_threshold, t_diff, t_before;\n    double *xpo, *tpo, *xro, *tro, *xpro, *xpo2, *tpo2, *xro2, *tro2, *xpro2, \n            *time, v = 1.0/1440.0, out_step, *to, *stable_sw_on, \n            k_adv_sil, k2_red_X1, k2_red_X2, k1_ind_X1, k1_ind_X2, tp_dox;\n\tint dimx_xp, dimx_tp, xist_rna, tsix_rna, xist_prom, xist_rna2, tsix_rna2, xist_prom2;\n\tint n_steps,n_steps_before, n_steps_dox, n_out_steps, n_small_steps, sec_chr, step, sel_rx;\n\t\n\t//associate inputs: first chromosome\n    par = mxDuplicateArray(prhs[0]);\n    const_par = mxDuplicateArray(prhs[1]);\n\txist_pol = mxDuplicateArray(prhs[2]);\n    tsix_pol = mxDuplicateArray(prhs[3]);  \n    xist_rna = mxGetScalar(prhs[4]);\n    tsix_rna = mxGetScalar(prhs[5]);\n    xist_prom = mxGetScalar(prhs[6]);\n              \n\t//associate pointers\n    xp = mxGetPr(xist_pol);\n    tp = mxGetPr(tsix_pol);\n    p = mxGetPr(par);\n    cp = mxGetPr(const_par);\n    t = cp[0];\n    t_before =  cp[1];\n    t_diff =  cp[2];\n    sil_threshold = cp[3];\n    out_step = cp[4];\n    sec_chr = cp[5];\n    k_adv_sil = cp[6];\n    k2_red_X1 = cp[7];\n    k2_red_X2 = cp[8];\n    k1_ind_X1 = cp[9];\n    k1_ind_X2 = cp[10];\n    tp_dox = cp[11];\n    \n    //associate inputs: second chromosome\n   if (sec_chr==1) {\n        xist_pol2 = mxDuplicateArray(prhs[7]);\n        tsix_pol2 = mxDuplicateArray(prhs[8]);  \n        xist_rna2 = mxGetScalar(prhs[9]);\n        tsix_rna2 = mxGetScalar(prhs[10]);\n        xist_prom2 = mxGetScalar(prhs[11]);\n        \n        xp2 = mxGetPr(xist_pol2);\n        tp2 = mxGetPr(tsix_pol2);\n   }\n    \n    n_out_steps = 1+ceil((t_diff+t_before)/out_step);\n    n_small_steps = round(out_step/v);\n    n_steps = (n_out_steps-1)*n_small_steps;\n    n_steps_before = (ceil(t_before/out_step))*n_small_steps;\n    n_steps_dox = (ceil(tp_dox/out_step))*n_small_steps;\n\t\n\t//figure out dimensions and associate output\n\tdims = mxGetDimensions(prhs[2]);\n\tdimx_xp = (int)dims[0];\n    dims = mxGetDimensions(prhs[3]);\n\tdimx_tp = (int)dims[0];\n    \n    //output\n    time_out = plhs[0] = mxCreateDoubleMatrix(n_out_steps, 1, mxREAL);\n    xist_pol_out = plhs[1] = mxCreateDoubleMatrix(n_out_steps, 1, mxREAL);\n    tsix_pol_out = plhs[2] = mxCreateDoubleMatrix(n_out_steps, 1, mxREAL);\n    xist_rna_out = plhs[3] = mxCreateDoubleMatrix(n_out_steps, 1, mxREAL);\n    tsix_rna_out = plhs[4] = mxCreateDoubleMatrix(n_out_steps, 1, mxREAL);\n    xpo = mxGetPr(xist_pol_out);\n    tpo= mxGetPr(tsix_pol_out);\n    xro = mxGetPr(xist_rna_out);\n    tro = mxGetPr(tsix_rna_out);\n    time =   mxGetPr(time_out);\n        \n    xist_pol_out2 = plhs[5] = mxCreateDoubleMatrix(n_out_steps, 1, mxREAL);\n    tsix_pol_out2 = plhs[6] = mxCreateDoubleMatrix(n_out_steps, 1, mxREAL);\n    xist_rna_out2 = plhs[7] = mxCreateDoubleMatrix(n_out_steps, 1, mxREAL);\n    tsix_rna_out2 = plhs[8] = mxCreateDoubleMatrix(n_out_steps, 1, mxREAL);\n    test = plhs[9] = mxCreateDoubleMatrix(n_out_steps, 1, mxREAL);\n    stable_switch_on_out = plhs[10] = mxCreateDoubleMatrix(1, 1, mxREAL);\n        \n    xpo2 = mxGetPr(xist_pol_out2);\n    tpo2= mxGetPr(tsix_pol_out2);\n    xro2 = mxGetPr(xist_rna_out2);\n    tro2 = mxGetPr(tsix_rna_out2);\n    to = mxGetPr(test);\n    stable_sw_on = mxGetPr(stable_switch_on_out);\n    // Initialize\n    stable_sw_on[0] = t_diff+t_before;\n    \n    \n    //write pol mxarray in deque and sum up polymerases\n    deque<int> xist_gene, tsix_gene, xist_gene2, tsix_gene2;\n    int q, sum_xp=0, sum_tp=0, sum_xp2 = 0, sum_tp2 = 0;\n    \n    for (q=0; q<dimx_xp; q++) \n        {\n            xist_gene.push_back (xp[q]);\n            sum_xp = sum_xp + xp[q];\n             if (sec_chr==1) {\n                xist_gene2.push_back (xp2[q]);\n                sum_xp2 = sum_xp2 + xp2[q];\n             }\n        }\n    for (q=0; q<dimx_tp; q++) \n        {\n            tsix_gene.push_back (tp[q]);\n            sum_tp = sum_tp + tp[q];\n            if (sec_chr==1) {\n                tsix_gene2.push_back (tp2[q]);\n                 sum_tp2 = sum_tp2 + tp2[q];\n            }\n        }  \n        \n    bool xpol_ini=0, tpol_ini=0, xpol_ini2=0, tpol_ini2=0;\n    boost::random::uniform_int_distribution<> dist(0, 1);\n    boost::random::uniform_real_distribution<> dist_real(0.0, 1.0);\n    double t_next, r, sum_rx;\n    vector<double> rx(16), cum_rx(16);\n    vector<int> all_xist(n_steps), all_xist2(n_steps);\n    \n    int sil_xa = 0, sil_xa2 = 0, xa_sil_steps = round(p[11]/v), \n            sil_tsix = 0, sil_tsix2 = 0, \n\t    sil_state_xa = 0, sil_state_xa2 = 0, sil_state_tsix = 0, sil_state_tsix2 = 0, stst = 0; \n    double xa = 1, xa2 = 0;\n    if (sec_chr==1) {xa2 = 1;};\n    double temp_sum_xa = xa + xa2;\n    int m = 0, b = 0, temp_sum_xr = 0, temp_sum_tr = 0, temp_sum_xp = 0, temp_sum_tp = 0,\n            temp_sum_xr2 = 0, temp_sum_tr2 = 0, temp_sum_xp2 = 0, temp_sum_tp2 = 0;\n    all_xist[0] = xist_rna;\n    xro[b] = xist_rna;\n    tro[b] = tsix_rna;\n    xpo[b] = sum_xp;\n    tpo[b] = sum_tp;\n    to[b] = temp_sum_xa;\n    if (sec_chr==1) {\n        all_xist2[0] = xist_rna2;\n        xro2[b] = xist_rna2;\n        tro2[b] = tsix_rna2;\n        xpo2[b] = sum_xp2;\n        tpo2[b] = sum_tp2;\n    }\n    //while (act_time<t_max)\n    for (step=0; step<n_steps; step++)\n        { \n\t\t\t// Identify first timepoint at which stable state with 1 Xa and 1 Xi is reached\n\t\t\tif (xist_rna>=sil_threshold & xa ==0 & sil_tsix ==1 & xist_rna2<sil_threshold & xa2==1 & sil_tsix2==0 & stst==0) {stable_sw_on[0] = step*v; stst=1;}\n\t\t\telse { if (xist_rna2>=sil_threshold & xa2 ==0 & sil_tsix2 ==1 & xist_rna<sil_threshold & xa==1 & sil_tsix==0 & stst==0) {stable_sw_on[0] = step*v; stst=1;}\n\t\t\t}\n\t\t\t//Silencing\n\t\t\t//If Tsix silencing has reached final state, Tsix is silenced //p[12]=parameter that determines # of intermediate states until silencing of tsix occurs\n\t\t\tif (sil_state_tsix>=p[12]&xist_rna>=sil_threshold) {sil_tsix=1;} \n\t\t\t//If silencing has not reached the final state but Xist rna level is below threshold system falls back into initial tsix silencing state\n\t\t\telse {\n\t\t\tif (xist_rna<sil_threshold&sil_state_tsix<p[12]) {sil_state_tsix=0; sil_tsix=0;}\n\t\t\t}\n\t\t\t//If XA silencing has reached final state, XA is silenced //p[11]=parameter that determines # of intermediate states until silencing of xa occurs\n\t\t\tif (sil_state_xa>=p[11]&xist_rna>=sil_threshold) {xa=0;} \n\t\t\t//If silencing has not reached the final state but Xist rna level is below threshold system falls back into initial xa silencing state\n\t\t\telse {\n\t\t\tif (xist_rna<sil_threshold&sil_state_xa<p[11]) {sil_state_xa=0; xa=1;}\t\n\t\t\t}  \n\t\t\tif (p[6]==0&tsix_gene.front()==1) \n\t\t        \t{\n\t\t            \txist_prom = 2;\n\t\t\t\t}\n\t\t        if (sec_chr==1) {\n\t\t     \tif (sil_state_tsix2>=p[12]&xist_rna2>=sil_threshold) {sil_tsix2=1;} \n\t\t\telse {\n\t\t\tif (xist_rna2<sil_threshold&sil_state_tsix2<p[12]) {sil_state_tsix2=0; sil_tsix2=0;}\n\t\t\t}\n\t\t\tif (sil_state_xa2>=p[11]&xist_rna2>=sil_threshold) {xa2=0;} \n\t\t\telse {\n\t\t\tif (xist_rna2<sil_threshold&sil_state_xa2<p[11]) {sil_state_xa2=0; xa2=1;}\t\n\t\t\t} \n\t\t\tif (p[6]==0&tsix_gene2.front()==1) \n\t\t\t\t{\n\t\t                \txist_prom2 = 2;\n\t\t\t\t}\n\t\t        }\n        \n\t\t\t//Gillespie reactions\n\t        t_next = 0;\n\t        \n\t        xpol_ini=0, tpol_ini=0, xpol_ini2=0, tpol_ini2=0;  \n\t        while (t_next<v) {\n\t\t\t\t//Xist initiation\n\t            //before induction of diff k1 10 times reduced\n\t            if (step<n_steps_before & step<n_steps_dox) {rx[0] = p[0]*0*(xa+xa2)*(xist_prom==1)*(tsix_gene.front()==0);}\n\t            else {\n\t\t\t\t\tif (step<n_steps_dox) {rx[0] = p[0]*(xa+xa2)*(xist_prom==1)*(tsix_gene.front()==0);}\n\t\t\t\t\t// if Xist is induced with Dox (k1_ind_X1>0) the Xist initiation rate becomes independent of the XA concentration \n\t\t\t\t\telse {\n\t\t\t\t\t\tif (k1_ind_X1==0) {rx[0] = (p[0]*(step>n_steps_before))*(xa+xa2)*(xist_prom==1)*(tsix_gene.front()==0);} \n\t\t\t\t\t\t// If X1 is induced with dox, the Xist initiation rate becomes independent of xa+xa2\n\t\t\t\t\t\telse {rx[0] = (p[0]*(step>n_steps_before)+p[0]*k1_ind_X1)*(xist_prom==1)*(tsix_gene.front()==0);}\n\t\t\t\t\t}\n\t\t\t\t}\n\t            rx[1] = (p[1]-k2_red_X1*p[1])*(sil_tsix<1); //Tsix initiation\n\t            rx[2] = p[7]*(xist_prom==2)*(tsix_gene.front()==0); // turning on the Xist promoter\n\t            rx[3] = p[3]*xist_rna; //Xist degradation\n\t            rx[4] = p[4]*tsix_rna; //Tsix degradation\n\t            \n\t            //second chr\n\t            //Xist initiation\n\t            if (step<n_steps_before & step<n_steps_dox) {rx[5] = (sec_chr==1)*p[0]*0*(xa+xa2)*(xist_prom2==1)*(tsix_gene2.front()==0);}\n\t            else {\n\t\t\t\t\tif (step<n_steps_dox) {rx[5] = (sec_chr==1)*p[0]*(xa+xa2)*(xist_prom2==1)*(tsix_gene2.front()==0);} \n\t\t\t\t\telse {\n\t\t\t\t\t\tif (k1_ind_X2==0) {rx[5] = (sec_chr==1)*(p[0]*(step>n_steps_before))*(xa+xa2)*(xist_prom2==1)*(tsix_gene2.front()==0);}\n\t\t\t\t\t\t// If X2 is induced with dox, the Xist initiation rate becomes independent of xa+xa2\n\t\t\t\t\t\telse {rx[5] = (sec_chr==1)*(p[0]*(step>n_steps_before)+p[0]*k1_ind_X2)*(xist_prom2==1)*(tsix_gene2.front()==0);}\n\t\t\t\t\t}\n\t\t\t\t}\n\t            rx[6] = (sec_chr==1)*(p[1]-k2_red_X2*p[1])*(sil_tsix2<1);   //Tsix initiation\n\t            rx[7] = (sec_chr==1)*(p[7]*(xist_prom2==2))*(tsix_gene2.front()==0); // turning on the Xist promoter\n\t            rx[8] = (sec_chr==1)*p[3]*xist_rna2; //Xist degradation\n\t            rx[9] = (sec_chr==1)*p[4]*tsix_rna2; //Tsix degradation\n\t\n\t\t    //transition between silencing states as Gillespie reaction\n\t\t    ////chromosome 1: now k_adv_sil= rate for transition between silencing states\n\t\t    rx[10] = k_adv_sil*(xist_rna>=sil_threshold)*(sil_state_xa<p[11]|sil_state_tsix<p[12]); //XA and Tsix silencing advance one state\n\t\t    ////if system is in last silencing state of the xa but xist rna fall below the threshold the silencing state can go back to the initial state with rate k[13]\n\t\t    rx[11] = p[13]*(xist_rna<sil_threshold)*(sil_state_xa>=p[11]);\n\t\t    //if system is in last silencing state of tsix but xist rna fall below the threshold the silencing state can go back to the initial state with rate k[14]\n\t\t    rx[12] = p[14]*(xist_rna<sil_threshold)*(sil_state_tsix>=p[12]);\n\t\t    ////second chromosome\n\t\t    rx[13] = (sec_chr==1)*k_adv_sil*(xist_rna2>=sil_threshold)*(sil_state_xa2<p[11]|sil_state_tsix2<p[12]);\n\t\t    rx[14] = (sec_chr==1)*p[13]*(xist_rna2<sil_threshold)*(sil_state_xa2>=p[11]);\n\t\t    rx[15] = (sec_chr==1)*p[14]*(xist_rna2<sil_threshold)*(sil_state_tsix2>=p[12]);\n\t    \n            \n            \n            sum_rx = 0, sel_rx = 100;\n            for (q=0; q<rx.size(); q++) {\n                sum_rx = sum_rx + rx[q];\n                cum_rx[q] = sum_rx;\n            }\n         \n            if (sum_rx>0) {\n                t_next = t_next + (-log(dist_real(gen)))/(sum_rx);\n            } else {t_next=1;}\n            \n            if (t_next<v){\n                // decide which reaction occurs\n                r = dist_real(gen);\n                for (q=0; q<rx.size(); q++) {\n                    if (r<(cum_rx[q]/sum_rx)){\n                        sel_rx = q;\n                        break;\n                    }\n                }\n                //execute reaction\n                \n                switch (sel_rx){\n                    case 0:\n                        xpol_ini = 1; break;\n                    case 1:\n                        tpol_ini = 1; break;\n                    case 2:\n                        xist_prom = 1; break;\n                    case 3:\n                        xist_rna--;\n                         break;\n                    case 4:\n                        tsix_rna--; break;\n\n                                       \n                    //second chr                        \n                      \n                   case 5:\n                        xpol_ini2 = 1; break;\n                    case 6:\n                        tpol_ini2 = 1; break;\n                    case 7:\n                        xist_prom2 = 1; break;\n                    case 8:\n                        xist_rna2--; \n                        break;\n                    case 9:\n                        tsix_rna2--; break;\n\t\t\t\t\tcase 10:\n\t\t\t\t\t\tif (sil_state_xa<p[11]) {sil_state_xa++;}\n\t\t\t\t\t\tif (sil_state_tsix<p[12]) {sil_state_tsix++;}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 11:\n\t\t\t\t\t\tsil_state_xa=0; xa=1; break;\n\t\t\t\t\tcase 12:\n\t\t\t\t\t\tsil_state_tsix=0; sil_tsix=0; break;\n\t\t\t\t\tcase 13:\n\t\t\t\t\t\tif (sil_state_xa2<p[11]) {sil_state_xa2++;}\n\t\t\t\t\t\tif (sil_state_tsix2<p[12]) {sil_state_tsix2++;}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 14:\n\t\t\t\t\t\tsil_state_xa2=0; xa2=1; break;\n\t\t\t\t\tcase 15:\n\t\t\t\t\t\tsil_state_tsix2=0; sil_tsix2=0; break;\n\t\t\t\t\tdefault:\n                        break;\n                }\n            }\n        }\n        temp_sum_xa = temp_sum_xa + xa + xa2;\n        //elongation and collisions       \n        elongation (dimx_xp, xist_gene, tsix_gene, sum_xp, sum_tp, \n            xpol_ini, tpol_ini, xist_rna, tsix_rna, \n            all_xist, temp_sum_xr, temp_sum_tr, temp_sum_xp, temp_sum_tp, dist, step, p[8]);\n        \n               \n        //second chromosome\n        if (sec_chr==1) {\n            elongation (dimx_xp, xist_gene2, tsix_gene2, sum_xp2, sum_tp2, \n            xpol_ini2, tpol_ini2, xist_rna2, tsix_rna2, \n            all_xist2, temp_sum_xr2, temp_sum_tr2, temp_sum_xp2, temp_sum_tp2, dist, step, p[8]);\n            \n        } \n        \n        //write out smoothed variable\n        m++;          \n        if (m==n_small_steps) {\n            b++;\n            xro[b] = temp_sum_xr/n_small_steps;\n            tro[b] = temp_sum_tr/n_small_steps;\n            xpo[b] = temp_sum_xp/n_small_steps;\n            tpo[b] = temp_sum_tp/n_small_steps;\n            to[b] = temp_sum_xa/n_small_steps;\n            time[b] = step*v;\n            temp_sum_xr = 0;\n            temp_sum_tr = 0;\n            temp_sum_xp = 0;\n            temp_sum_tp = 0;\n            temp_sum_xa = 0;\n            if (sec_chr==1) {\n                xro2[b] = temp_sum_xr2/n_small_steps;\n                tro2[b] = temp_sum_tr2/n_small_steps;\n                xpo2[b] = temp_sum_xp2/n_small_steps;\n                tpo2[b] = temp_sum_tp2/n_small_steps;\n                temp_sum_xr2 = 0;\n                temp_sum_tr2 = 0;\n                temp_sum_xp2 = 0;\n                temp_sum_tp2 = 0;\n            }\n            m = 0;\n        }\n        \n        }\n    if (m>0) {\n            b++;\n            xro[b] = temp_sum_xr/m;\n            tro[b] = temp_sum_tr/m;\n            xpo[b] = temp_sum_xp/m;\n            tpo[b] = temp_sum_tp/m;\n            to[b] = temp_sum_xa/n_small_steps;\n            time[b] = step*v;\n            if (sec_chr==1) {\n                xro2[b] = temp_sum_xr2/m;\n                tro2[b] = temp_sum_tr2/m;\n                xpo2[b] = temp_sum_xp2/m;\n                tpo2[b] = temp_sum_tp2/m;\n            }\n    }\n   \t}\n", "meta": {"hexsha": "133ba79bcfb5feeaf4b86c2fd09e34f3332e5977", "size": 17469, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scripts/Fig5_7/reaction_2C_wo_trans_k1XAtdep_MUT_161214_minimal.cpp", "max_stars_repo_name": "EddaSchulz/mutzel_paper", "max_stars_repo_head_hexsha": "a2c699ca9b1c10744f49a2058efbe65bbe36f117", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/Fig5_7/reaction_2C_wo_trans_k1XAtdep_MUT_161214_minimal.cpp", "max_issues_repo_name": "EddaSchulz/mutzel_paper", "max_issues_repo_head_hexsha": "a2c699ca9b1c10744f49a2058efbe65bbe36f117", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/Fig5_7/reaction_2C_wo_trans_k1XAtdep_MUT_161214_minimal.cpp", "max_forks_repo_name": "EddaSchulz/mutzel_paper", "max_forks_repo_head_hexsha": "a2c699ca9b1c10744f49a2058efbe65bbe36f117", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-01T13:56:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-01T13:56:14.000Z", "avg_line_length": 39.4334085779, "max_line_length": 163, "alphanum_fraction": 0.5664319652, "num_tokens": 5609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2766965966962596}}
{"text": "// Copyright (C) 2019-2020 Zilliz. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (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//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software distributed under the License\n// is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n// or implied. See the License for the specific language governing permissions and limitations under the License\n\n#include \"SearchBruteForce.h\"\n#include <vector>\n#include <common/Types.h>\n#include <boost/dynamic_bitset.hpp>\n#include <queue>\n#include \"SubSearchResult.h\"\n\n#include <faiss/utils/distances.h>\n#include <faiss/utils/BinaryDistance.h>\n\nnamespace milvus::query {\n\n// copy from knowhere\n// disable lint to make further migration easier\nstatic void\nraw_search(MetricType metric_type,\n           const uint8_t* xb,  //\n           int64_t ntotal,     //\n           int code_size,      //\n           idx_t n,            // num_queries\n           const uint8_t* x,   //\n           idx_t k,            // topk\n           float* D,\n           idx_t* labels,\n           const BitsetView bitset) {\n    using namespace faiss;  // NOLINT\n    if (metric_type == METRIC_Jaccard || metric_type == METRIC_Tanimoto) {\n        float_maxheap_array_t res = {size_t(n), size_t(k), labels, D};\n        binary_distance_knn_hc(METRIC_Jaccard, &res, x, xb, ntotal, code_size, bitset);\n\n        if (metric_type == METRIC_Tanimoto) {\n            for (int i = 0; i < k * n; i++) {\n                D[i] = Jaccard_2_Tanimoto(D[i]);\n            }\n        }\n\n    } else if (metric_type == METRIC_Hamming) {\n        std::vector<int32_t> int_distances(n * k);\n        int_maxheap_array_t res = {size_t(n), size_t(k), labels, int_distances.data()};\n        binary_distance_knn_hc(METRIC_Hamming, &res, x, xb, ntotal, code_size, bitset);\n        for (int i = 0; i < n * k; ++i) {\n            D[i] = int_distances[i];\n        }\n\n    } else if (metric_type == METRIC_Substructure || metric_type == METRIC_Superstructure) {\n        // only matched ids will be chosen, not to use heap\n        binary_distance_knn_mc(metric_type, x, xb, n, ntotal, k, code_size, D, labels, bitset);\n    } else {\n        PanicInfo(\"unsupported\");\n    }\n}\n\nSubSearchResult\nBinarySearchBruteForceFast(MetricType metric_type,\n                           int64_t dim,\n                           const uint8_t* binary_chunk,\n                           int64_t size_per_chunk,\n                           int64_t topk,\n                           int64_t num_queries,\n                           const uint8_t* query_data,\n                           const faiss::BitsetView& bitset) {\n    SubSearchResult sub_result(num_queries, topk, metric_type);\n    float* result_distances = sub_result.get_values();\n    idx_t* result_labels = sub_result.get_labels();\n\n    int64_t code_size = dim / 8;\n    const idx_t block_size = size_per_chunk;\n\n    raw_search(metric_type, binary_chunk, size_per_chunk, code_size, num_queries, query_data, topk, result_distances,\n               result_labels, bitset);\n\n    return sub_result;\n}\n\nSubSearchResult\nFloatSearchBruteForce(const dataset::SearchDataset& dataset,\n                      const void* chunk_data_raw,\n                      int64_t size_per_chunk,\n                      const faiss::BitsetView& bitset) {\n    auto metric_type = dataset.metric_type;\n    auto num_queries = dataset.num_queries;\n    auto topk = dataset.topk;\n    auto dim = dataset.dim;\n    SubSearchResult sub_qr(num_queries, topk, metric_type);\n    auto query_data = reinterpret_cast<const float*>(dataset.query_data);\n    auto chunk_data = reinterpret_cast<const float*>(chunk_data_raw);\n\n    if (metric_type == MetricType::METRIC_L2) {\n        faiss::float_maxheap_array_t buf{(size_t)num_queries, (size_t)topk, sub_qr.get_labels(), sub_qr.get_values()};\n        faiss::knn_L2sqr(query_data, chunk_data, dim, num_queries, size_per_chunk, &buf, bitset);\n        return sub_qr;\n    } else {\n        faiss::float_minheap_array_t buf{(size_t)num_queries, (size_t)topk, sub_qr.get_labels(), sub_qr.get_values()};\n        faiss::knn_inner_product(query_data, chunk_data, dim, num_queries, size_per_chunk, &buf, bitset);\n        return sub_qr;\n    }\n}\n\nSubSearchResult\nBinarySearchBruteForce(const dataset::SearchDataset& dataset,\n                       const void* chunk_data_raw,\n                       int64_t size_per_chunk,\n                       const faiss::BitsetView& bitset) {\n    // TODO: refactor the internal function\n    auto query_data = reinterpret_cast<const uint8_t*>(dataset.query_data);\n    auto chunk_data = reinterpret_cast<const uint8_t*>(chunk_data_raw);\n    return BinarySearchBruteForceFast(dataset.metric_type, dataset.dim, chunk_data, size_per_chunk, dataset.topk,\n                                      dataset.num_queries, query_data, bitset);\n}\n}  // namespace milvus::query\n", "meta": {"hexsha": "4b29727787be30480dc29e9bb3476f9caa128a2a", "size": 5039, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "internal/core/src/query/SearchBruteForce.cpp", "max_stars_repo_name": "chriswarnock/milvus", "max_stars_repo_head_hexsha": "ff4754a638a491adf7eca9952e1057272ba5d1a4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-09-11T07:45:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T09:58:48.000Z", "max_issues_repo_path": "internal/core/src/query/SearchBruteForce.cpp", "max_issues_repo_name": "chriswarnock/milvus", "max_issues_repo_head_hexsha": "ff4754a638a491adf7eca9952e1057272ba5d1a4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2021-11-01T03:48:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T23:22:09.000Z", "max_forks_repo_path": "internal/core/src/query/SearchBruteForce.cpp", "max_forks_repo_name": "chriswarnock/milvus", "max_forks_repo_head_hexsha": "ff4754a638a491adf7eca9952e1057272ba5d1a4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-07T14:29:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-07T14:29:24.000Z", "avg_line_length": 41.3032786885, "max_line_length": 118, "alphanum_fraction": 0.6455645962, "num_tokens": 1233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2766521740641492}}
{"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 WEINBERG_ANGLE_H\n#define WEINBERG_ANGLE_H\n\n#include <Eigen/Core>\n\nnamespace flexiblesusy {\n\nnamespace weinberg_angle {\n\n/**\n * @class Weinberg_angle\n * @brief Class to calculate the DR-bar weak mixing angle\n */\nclass Weinberg_angle {\npublic:\n   /**\n    * @class Data\n    * @brief Model parameters necessary for calculating weak mixing angle\n    *\n    * @attention The W and Z self-energies are assumed to be\n    * calculated using the top quark pole mass, instead of the top\n    * quark DR-bar mass.\n    */\n   struct Data {\n      Data();\n\n      double scale;                  ///< renormalization scale\n      double alpha_em_drbar;         ///< alpha_em(MZ, DR-bar, SUSY)\n      double fermi_contant;          ///< Fermi constant\n      double self_energy_z_at_mz;    ///< self-energy Z at p = MZ, mt = mt_pole\n      double self_energy_w_at_0;     ///< self-energy W at p = 0, mt = mt_pole\n      double self_energy_w_at_mw;    ///< self-energy W at p = MW, mt = mt_pole\n      double mw_pole;                ///< W pole mass\n      double mz_pole;                ///< Z pole mass\n      double mt_pole;                ///< top quark pole mass\n      double mh_drbar;               ///< lightest CP-even Higgs DR-bar mass\n      double hmix_12;                ///< CP-even Higgs mixing Cos(alpha)\n      double msel_drbar;             ///< left-handed selectron DR-bar mass\n      double msmul_drbar;            ///< left-handed smuon DR-bar mass\n      double msve_drbar;             ///< electron-sneutrino DR-bar mass\n      double msvm_drbar;             ///< muon-sneutrino DR-bar mass\n      Eigen::ArrayXd mn_drbar;       ///< Neutralino DR-bar mass\n      Eigen::ArrayXd mc_drbar;       ///< Chargino DR-bar mass\n      Eigen::MatrixXcd zn;           ///< Neutralino mixing matrix\n      Eigen::MatrixXcd um;           ///< Chargino mixing matrix\n      Eigen::MatrixXcd up;           ///< Chargino mixing matrix\n      double gY;                     ///< U(1)_Y gauge coupling\n      double g2;                     ///< SU(2)_L gauge coupling\n      double g3;                     ///< SU(3)_c gauge coupling\n      double tan_beta;               ///< tan(beta) = vu / vd\n   };\n\n   struct Self_energy_data {\n      Self_energy_data();\n      double scale;                  ///< renormalization scale\n      double mt_pole;                ///< top quark pole mass\n      double mt_drbar;               ///< top quark DR-bar mass\n      double mb_drbar;               ///< bottom quark DR-bar mass\n      double gY;                     ///< U(1)_Y gauge coupling\n      double g2;                     ///< SU(2)_L gauge coupling\n   };\n\n   Weinberg_angle();\n\n   void enable_susy_contributions(); ///< enable susy contributions\n   void disable_susy_contributions(); ///< disable susy contributions\n\n   void set_data(const Data&);       ///< set data necessary for the calculation\n   void set_number_of_iterations(int); ///< maximum number of iterations\n   void set_number_of_loops(int);    ///< set number of loops\n   void set_precision_goal(double);  ///< set precision goal\n   double get_rho_hat() const;       ///< returns the rho parameter\n   double get_sin_theta() const;     ///< returns sin(theta_w)\n\n   /// calculates the sinus of the Weinberg angle\n   int calculate(double rho_start = 1.0, double sin_start = 0.48);\n\n   static double replace_mtop_in_self_energy_z(double, double, const Self_energy_data&);\n   static double replace_mtop_in_self_energy_w(double, double, const Self_energy_data&);\n\nprivate:\n   int number_of_iterations; ///< maximum number of iterations\n   int number_of_loops;      ///< number of loops\n   double precision_goal;         ///< precision goal\n   double rho_hat;                ///< output rho-hat parameter\n   double sin_theta;              ///< output sin(theta)\n   Data data;\n   bool susy_contributions;       ///< model type\n\n   static double calculate_delta_r(double, double, const Data&, bool add_susy_contributions = true, int number_of_loops = 2);\n   static double calculate_delta_rho(double, double, const Data&, bool add_susy_contributions = true, int number_of_loops = 2);\n   static double calculate_delta_vb(double, double, const Data&, bool add_susy_contributions = true);\n   static double calculate_delta_vb_sm(double, double, const Data&);\n   static double calculate_delta_vb_susy(double, const Data&);\n   static double rho_2(double);\n\n   static double calculate_self_energy_z_top(double, double, const Self_energy_data&);\n   static double calculate_self_energy_w_top(double, double, const Self_energy_data&);\n};\n\n} // namespace weinberg_angle\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "a25455fbed0627ce904bba352e5afd0ebf20aac2", "size": 5453, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/src/weinberg_angle.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/weinberg_angle.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/weinberg_angle.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": 43.9758064516, "max_line_length": 127, "alphanum_fraction": 0.6271777003, "num_tokens": 1261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2766521687738848}}
{"text": "// Copyright (c) 2012 libmv 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\n// deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n// sell copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n\n#include \"libmv/simple_pipeline/keyframe_selection.h\"\n\n#include \"libmv/numeric/numeric.h\"\n#include \"ceres/ceres.h\"\n#include \"libmv/logging/logging.h\"\n#include \"libmv/multiview/homography.h\"\n#include \"libmv/multiview/fundamental.h\"\n#include \"libmv/simple_pipeline/intersect.h\"\n#include \"libmv/simple_pipeline/bundle.h\"\n\n#include <Eigen/Eigenvalues>\n\nnamespace libmv {\nnamespace {\n\nMat3 IntrinsicsNormalizationMatrix(const CameraIntrinsics &intrinsics) {\n  Mat3 T = Mat3::Identity(), S = Mat3::Identity();\n\n  T(0, 2) = -intrinsics.principal_point_x();\n  T(1, 2) = -intrinsics.principal_point_y();\n\n  S(0, 0) /= intrinsics.focal_length_x();\n  S(1, 1) /= intrinsics.focal_length_y();\n\n  return S * T;\n}\n\n// P.H.S. Torr\n// Geometric Motion Segmentation and Model Selection\n//\n// http://reference.kfupm.edu.sa/content/g/e/geometric_motion_segmentation_and_model__126445.pdf\n//\n// d is the number of dimensions modeled\n//     (d = 3 for a fundamental matrix or 2 for a homography)\n// k is the number of degrees of freedom in the model\n//     (k = 7 for a fundamental matrix or 8 for a homography)\n// r is the dimension of the data\n//     (r = 4 for 2D correspondences between two frames)\ndouble GRIC(const Vec &e, int d, int k, int r) {\n  int n = e.rows();\n  double lambda1 = log(static_cast<double>(r));\n  double lambda2 = log(static_cast<double>(r * n));\n\n  // lambda3 limits the residual error, and this paper\n  // http://elvera.nue.tu-berlin.de/files/0990Knorr2006.pdf\n  // suggests using lambda3 of 2\n  // same value is used in Torr's Problem of degeneracy in structure\n  // and motion recovery from uncalibrated image sequences\n  // http://www.robots.ox.ac.uk/~vgg/publications/papers/torr99.ps.gz\n  double lambda3 = 2.0;\n\n  // Variance of tracker position. Physically, this is typically about 0.1px,\n  // and when squared becomes 0.01 px^2.\n  double sigma2 = 0.01;\n\n  // Finally, calculate the GRIC score.\n  double gric = 0.0;\n  for (int i = 0; i < n; i++) {\n    gric += std::min(e(i) * e(i) / sigma2, lambda3 * (r - d));\n  }\n  gric += lambda1 * d * n;\n  gric += lambda2 * k;\n  return gric;\n}\n\n// Compute a generalized inverse using eigen value decomposition, clamping the\n// smallest eigenvalues if requested. This is needed to compute the variance of\n// reconstructed 3D points.\n//\n// TODO(keir): Consider moving this into the numeric code, since this is not\n// related to keyframe selection.\nMat PseudoInverseWithClampedEigenvalues(const Mat &matrix,\n                                        int num_eigenvalues_to_clamp) {\n  Eigen::EigenSolver<Mat> eigen_solver(matrix);\n  Mat D = eigen_solver.pseudoEigenvalueMatrix();\n  Mat V = eigen_solver.pseudoEigenvectors();\n\n  // Clamp too-small singular values to zero to prevent numeric blowup.\n  double epsilon = std::numeric_limits<double>::epsilon();\n  for (int i = 0; i < D.cols(); ++i) {\n    if (D(i, i) > epsilon) {\n      D(i, i) = 1.0 / D(i, i);\n    } else {\n      D(i, i) = 0.0;\n    }\n  }\n\n  // Apply the clamp.\n  for (int i = D.cols() - num_eigenvalues_to_clamp; i < D.cols(); ++i) {\n    D(i, i) = 0.0;\n  }\n  return V * D * V.inverse();\n}\n\nvoid FilterZeroWeightMarkersFromTracks(const Tracks &tracks,\n                                       Tracks *filtered_tracks) {\n  vector<Marker> all_markers = tracks.AllMarkers();\n\n  for (int i = 0; i < all_markers.size(); ++i) {\n    Marker &marker = all_markers[i];\n    if (marker.weight != 0.0) {\n      filtered_tracks->Insert(marker.image,\n                              marker.track,\n                              marker.x,\n                              marker.y,\n                              marker.weight);\n    }\n  }\n}\n\n}  // namespace\n\nvoid SelectKeyframesBasedOnGRICAndVariance(const Tracks &_tracks,\n                                           const CameraIntrinsics &intrinsics,\n                                           vector<int> &keyframes) {\n  // Mirza Tahir Ahmed, Matthew N. Dailey\n  // Robust key frame extraction for 3D reconstruction from video streams\n  //\n  // http://www.cs.ait.ac.th/~mdailey/papers/Tahir-KeyFrame.pdf\n\n  Tracks filtered_tracks;\n  FilterZeroWeightMarkersFromTracks(_tracks, &filtered_tracks);\n\n  int max_image = filtered_tracks.MaxImage();\n  int next_keyframe = 1;\n  int number_keyframes = 0;\n\n  // Limit correspondence ratio from both sides.\n  // On the one hand if number of correspondent features is too low,\n  // triangulation will suffer.\n  // On the other hand high correspondence likely means short baseline.\n  // which also will affect om accuracy\n  const double Tmin = 0.8;\n  const double Tmax = 1.0;\n\n  Mat3 N = IntrinsicsNormalizationMatrix(intrinsics);\n  Mat3 N_inverse = N.inverse();\n\n  double Sc_best = std::numeric_limits<double>::max();\n  double success_intersects_factor_best = 0.0f;\n\n  while (next_keyframe != -1) {\n    int current_keyframe = next_keyframe;\n    double Sc_best_candidate = std::numeric_limits<double>::max();\n\n    LG << \"Found keyframe \" << next_keyframe;\n\n    number_keyframes++;\n    next_keyframe = -1;\n\n    for (int candidate_image = current_keyframe + 1;\n         candidate_image <= max_image;\n         candidate_image++) {\n      // Conjunction of all markers from both keyframes\n      vector<Marker> all_markers =\n        filtered_tracks.MarkersInBothImages(current_keyframe,\n                                            candidate_image);\n\n      // Match keypoints between frames current_keyframe and candidate_image\n      vector<Marker> tracked_markers =\n        filtered_tracks.MarkersForTracksInBothImages(current_keyframe,\n                                                     candidate_image);\n\n      // Correspondences in normalized space\n      Mat x1, x2;\n      CoordinatesForMarkersInImage(tracked_markers, current_keyframe, &x1);\n      CoordinatesForMarkersInImage(tracked_markers, candidate_image, &x2);\n\n      LG << \"Found \" << x1.cols()\n         << \" correspondences between \" << current_keyframe\n         << \" and \" << candidate_image;\n\n      // Not enough points to construct fundamental matrix\n      if (x1.cols() < 8 || x2.cols() < 8)\n        continue;\n\n      // STEP 1: Correspondence ratio constraint\n      int Tc = tracked_markers.size();\n      int Tf = all_markers.size();\n      double Rc = static_cast<double>(Tc) / Tf;\n\n      LG << \"Correspondence between \" << current_keyframe\n         << \" and \" << candidate_image\n         << \": \" << Rc;\n\n      if (Rc < Tmin || Rc > Tmax)\n        continue;\n\n      Mat3 H, F;\n\n      // Estimate homography using default options.\n      EstimateHomographyOptions estimate_homography_options;\n      EstimateHomography2DFromCorrespondences(x1,\n                                              x2,\n                                              estimate_homography_options,\n                                              &H);\n\n      // Convert homography to original pixel space.\n      H = N_inverse * H * N;\n\n      EstimateFundamentalOptions estimate_fundamental_options;\n      EstimateFundamentalFromCorrespondences(x1,\n                                             x2,\n                                             estimate_fundamental_options,\n                                             &F);\n\n      // Convert fundamental to original pixel space.\n      F = N_inverse * F * N;\n\n      // TODO(sergey): STEP 2: Discard outlier matches\n\n      // STEP 3: Geometric Robust Information Criteria\n\n      // Compute error values for homography and fundamental matrices\n      Vec H_e, F_e;\n      H_e.resize(x1.cols());\n      F_e.resize(x1.cols());\n      for (int i = 0; i < x1.cols(); i++) {\n        Vec2 current_x1, current_x2;\n\n        intrinsics.NormalizedToImageSpace(x1(0, i), x1(1, i),\n                                          &current_x1(0), &current_x1(1));\n\n        intrinsics.NormalizedToImageSpace(x2(0, i), x2(1, i),\n                                          &current_x2(0), &current_x2(1));\n\n        H_e(i) = SymmetricGeometricDistance(H, current_x1, current_x2);\n        F_e(i) = SymmetricEpipolarDistance(F, current_x1, current_x2);\n      }\n\n      LG << \"H_e: \" << H_e.transpose();\n      LG << \"F_e: \" << F_e.transpose();\n\n      // Degeneracy constraint\n      double GRIC_H = GRIC(H_e, 2, 8, 4);\n      double GRIC_F = GRIC(F_e, 3, 7, 4);\n\n      LG << \"GRIC values for frames \" << current_keyframe\n         << \" and \" << candidate_image\n         << \", H-GRIC: \" << GRIC_H\n         << \", F-GRIC: \" << GRIC_F;\n\n      if (GRIC_H <= GRIC_F)\n        continue;\n\n      // TODO(sergey): STEP 4: PELC criterion\n\n      // STEP 5: Estimation of reconstruction error\n      //\n      // Uses paper Keyframe Selection for Camera Motion and Structure\n      // Estimation from Multiple Views\n      // Uses ftp://ftp.tnt.uni-hannover.de/pub/papers/2004/ECCV2004-TTHBAW.pdf\n      // Basically, equation (15)\n      //\n      // TODO(sergey): separate all the constraints into functions,\n      //               this one is getting to much cluttered already\n\n      // Definitions in equation (15):\n      // - I is the number of 3D feature points\n      // - A is the number of essential parameters of one camera\n\n      EuclideanReconstruction reconstruction;\n\n      // The F matrix should be an E matrix, but squash it just to be sure\n\n      // Reconstruction should happen using normalized fundamental matrix\n      Mat3 F_normal = N * F * N_inverse;\n\n      Mat3 E;\n      FundamentalToEssential(F_normal, &E);\n\n      // Recover motion between the two images. Since this function assumes a\n      // calibrated camera, use the identity for K\n      Mat3 R;\n      Vec3 t;\n      Mat3 K = Mat3::Identity();\n\n      if (!MotionFromEssentialAndCorrespondence(E,\n                                                K, x1.col(0),\n                                                K, x2.col(0),\n                                                &R, &t)) {\n        LG << \"Failed to compute R and t from E and K\";\n        continue;\n      }\n\n      LG << \"Camera transform between frames \" << current_keyframe\n         << \" and \" << candidate_image\n         << \":\\nR:\\n\" << R\n         << \"\\nt:\" << t.transpose();\n\n      // First camera is identity, second one is relative to it\n      reconstruction.InsertCamera(current_keyframe,\n                                  Mat3::Identity(),\n                                  Vec3::Zero());\n      reconstruction.InsertCamera(candidate_image, R, t);\n\n      // Reconstruct 3D points\n      int intersects_total = 0, intersects_success = 0;\n      for (int i = 0; i < tracked_markers.size(); i++) {\n        if (!reconstruction.PointForTrack(tracked_markers[i].track)) {\n          vector<Marker> reconstructed_markers;\n\n          int track = tracked_markers[i].track;\n\n          reconstructed_markers.push_back(tracked_markers[i]);\n\n          // We know there're always only two markers for a track\n          // Also, we're using brute-force search because we don't\n          // actually know about markers layout in a list, but\n          // at this moment this cycle will run just once, which\n          // is not so big deal\n\n          for (int j = i + 1; j < tracked_markers.size(); j++) {\n            if (tracked_markers[j].track == track) {\n              reconstructed_markers.push_back(tracked_markers[j]);\n              break;\n            }\n          }\n\n          intersects_total++;\n\n          if (EuclideanIntersect(reconstructed_markers, &reconstruction)) {\n            LG << \"Ran Intersect() for track \" << track;\n            intersects_success++;\n          } else {\n            LG << \"Filed to intersect track \" << track;\n          }\n        }\n      }\n\n      double success_intersects_factor =\n          (double) intersects_success / intersects_total;\n\n      if (success_intersects_factor < success_intersects_factor_best) {\n        LG << \"Skip keyframe candidate because of \"\n              \"lower successful intersections ratio\";\n\n        continue;\n      }\n\n      success_intersects_factor_best = success_intersects_factor;\n\n      Tracks two_frames_tracks(tracked_markers);\n      PolynomialCameraIntrinsics empty_intrinsics;\n      BundleEvaluation evaluation;\n      evaluation.evaluate_jacobian = true;\n\n      EuclideanBundleCommonIntrinsics(two_frames_tracks,\n                                      BUNDLE_NO_INTRINSICS,\n                                      BUNDLE_NO_CONSTRAINTS,\n                                      &reconstruction,\n                                      &empty_intrinsics,\n                                      &evaluation);\n\n      Mat &jacobian = evaluation.jacobian;\n\n      Mat JT_J = jacobian.transpose() * jacobian;\n      // There are 7 degrees of freedom, so clamp them out.\n      Mat JT_J_inv = PseudoInverseWithClampedEigenvalues(JT_J, 7);\n\n      Mat temp_derived = JT_J * JT_J_inv * JT_J;\n      bool is_inversed = (temp_derived - JT_J).cwiseAbs2().sum() <\n          1e-4 * std::min(temp_derived.cwiseAbs2().sum(),\n                          JT_J.cwiseAbs2().sum());\n\n      LG << \"Check on inversed: \" << (is_inversed ? \"true\" : \"false\" )\n         << \", det(JT_J): \" << JT_J.determinant();\n\n      if (!is_inversed) {\n        LG << \"Ignoring candidature due to poor jacobian stability\";\n        continue;\n      }\n\n      Mat Sigma_P;\n      Sigma_P = JT_J_inv.bottomRightCorner(evaluation.num_points * 3,\n                                           evaluation.num_points * 3);\n\n      int I = evaluation.num_points;\n      int A = 12;\n\n      double Sc = static_cast<double>(I + A) / Square(3 * I) * Sigma_P.trace();\n\n      LG << \"Expected estimation error between \"\n         << current_keyframe << \" and \"\n         << candidate_image << \": \" << Sc;\n\n      // Pairing with a lower Sc indicates a better choice\n      if (Sc > Sc_best_candidate)\n        continue;\n\n      Sc_best_candidate = Sc;\n\n      next_keyframe = candidate_image;\n    }\n\n    // This is a bit arbitrary and main reason of having this is to deal\n    // better with situations when there's no keyframes were found for\n    // current keyframe this could happen when there's no so much parallax\n    // in the beginning of image sequence and then most of features are\n    // getting occluded. In this case there could be good keyframe pair in\n    // the middle of the sequence\n    //\n    // However, it's just quick hack and smarter way to do this would be nice\n    if (next_keyframe == -1) {\n      next_keyframe = current_keyframe + 10;\n      number_keyframes = 0;\n\n      if (next_keyframe >= max_image)\n        break;\n\n      LG << \"Starting searching for keyframes starting from \" << next_keyframe;\n    } else {\n      // New pair's expected reconstruction error is lower\n      // than existing pair's one.\n      //\n      // For now let's store just one candidate, easy to\n      // store more candidates but needs some thoughts\n      // how to choose best one automatically from them\n      // (or allow user to choose pair manually).\n      if (Sc_best > Sc_best_candidate) {\n        keyframes.clear();\n        keyframes.push_back(current_keyframe);\n        keyframes.push_back(next_keyframe);\n        Sc_best = Sc_best_candidate;\n      }\n    }\n  }\n}\n\n}  // namespace libmv\n", "meta": {"hexsha": "241b5600505b644e8acd3ddddfb3719242fa21af", "size": 16095, "ext": "cc", "lang": "C++", "max_stars_repo_path": "modules/sfm/src/libmv_light/libmv/simple_pipeline/keyframe_selection.cc", "max_stars_repo_name": "Nondzu/opencv_contrib", "max_stars_repo_head_hexsha": "0b0616a25d4239ee81fda965818b49b721620f56", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7158.0, "max_stars_repo_stars_event_min_datetime": "2016-07-04T22:19:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:54:32.000Z", "max_issues_repo_path": "modules/sfm/src/libmv_light/libmv/simple_pipeline/keyframe_selection.cc", "max_issues_repo_name": "Nondzu/opencv_contrib", "max_issues_repo_head_hexsha": "0b0616a25d4239ee81fda965818b49b721620f56", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2184.0, "max_issues_repo_issues_event_min_datetime": "2016-07-05T12:04:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T19:10:12.000Z", "max_forks_repo_path": "modules/sfm/src/libmv_light/libmv/simple_pipeline/keyframe_selection.cc", "max_forks_repo_name": "Nondzu/opencv_contrib", "max_forks_repo_head_hexsha": "0b0616a25d4239ee81fda965818b49b721620f56", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5535.0, "max_forks_repo_forks_event_min_datetime": "2016-07-06T12:01:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T03:13:24.000Z", "avg_line_length": 35.6873614191, "max_line_length": 96, "alphanum_fraction": 0.6116806462, "num_tokens": 3800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.27656765458290106}}
{"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_TOOLBOX_ELLIPTIC_FUNCTIONS_SIMD_COMMON_ELLIPKE_HPP_INCLUDED\n#define NT2_TOOLBOX_ELLIPTIC_FUNCTIONS_SIMD_COMMON_ELLIPKE_HPP_INCLUDED\n#include <nt2/toolbox/elliptic/functions/ellipke.hpp>\n#include <nt2/sdk/simd/logical.hpp>\n#include <nt2/sdk/meta/as_floating.hpp>\n#include <boost/fusion/tuple.hpp>\n#include <nt2/include/functions/simd/sqr.hpp>\n#include <nt2/include/functions/simd/logical_or.hpp>\n#include <nt2/include/functions/simd/ldexp.hpp>\n#include <nt2/include/functions/simd/sqrt.hpp>\n#include <nt2/include/functions/simd/sqr.hpp>\n#include <nt2/include/functions/simd/average.hpp>\n#include <nt2/include/functions/simd/oneminus.hpp>\n#include <nt2/include/functions/simd/tofloat.hpp>\n#include <nt2/include/functions/simd/any.hpp>\n#include <nt2/include/functions/simd/maximum.hpp>\n#include <nt2/include/constants/real.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/functions/simd/splat.hpp>\n#include <nt2/include/functions/simd/is_greater.hpp>\n#include <nt2/include/functions/simd/if_allbits_else.hpp>\n#include <nt2/include/functions/simd/if_zero_else.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is arithmetic_\n/////////////////////////////////////////////////////////////////////////////\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION(nt2::tag::ellipke_, tag::cpu_,\n                       (A0)(X),\n                       ((simd_<arithmetic_<A0>,X>))\n                      )\n  {\n    typedef typename meta::as_floating<A0>::type         etype;\n    typedef boost::fusion::tuple<etype, etype> result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      typedef typename meta::scalar_of<etype>::type setype;\n      return ellipke(tofloat(a0), Eps<setype>());\n    }\n  };\n\n  /////////////////////////////////////////////////////////////////////////////\n  //Implementation when type A0 is arithmetic_\n  /////////////////////////////////////////////////////////////////////////////\n  NT2_FUNCTOR_IMPLEMENTATION(nt2::tag::ellipke_, tag::cpu_,\n                             (A0)(A1)(X),\n                             ((simd_<arithmetic_<A0>,X>))\n                             ((scalar_<floating_<A1> >))\n                             )\n  {\n    typedef typename meta::as_floating<A0>::type         etype;\n    typedef boost::fusion::tuple<etype, etype> result_type;\n    NT2_FUNCTOR_CALL(2)\n      {\n        return ellipke(tofloat(a0), a1);\n      }\n  };\n\n  /////////////////////////////////////////////////////////////////////////////\n  // Implementation when type A0 is arithmetic_\n  /////////////////////////////////////////////////////////////////////////////\n  NT2_FUNCTOR_IMPLEMENTATION(nt2::tag::ellipke_, tag::cpu_,\n                             (A0)(A1)(X),\n                             ((simd_<floating_<A0>,X>))\n                             ((scalar_<floating_<A1> >))\n                             )\n  {\n    typedef typename meta::strip<A0>::type              etype;\n    typedef boost::fusion::tuple<etype, etype>    result_type;\n    NT2_FUNCTOR_CALL(2)\n      {\n        result_type res;\n        nt2::ellipke(a0, a1, boost::fusion::at_c<0>(res), boost::fusion::at_c<1>(res));\n        return res;\n      }\n  };\n\n  /////////////////////////////////////////////////////////////////////////////\n  // reference based Implementations 1 input\n  /////////////////////////////////////////////////////////////////////////////\n  NT2_FUNCTOR_IMPLEMENTATION(  nt2::tag::ellipke_, tag::cpu_,\n                               (A0)(A1)(X),\n                               ((simd_<arithmetic_<A0>,X >))\n                               ((simd_<floating_<A1>,X>))\n                               ((simd_<floating_<A1>,X>))\n                               )\n  {\n    typedef void result_type;\n    inline result_type operator()(A0 const& a0,A1 & a1,A1 & a2) const\n      {\n        typedef typename meta::scalar_of<A1>::type sA1;\n        nt2::ellipke(tofloat(a0), Eps<sA1>(), a1, a2);\n      }\n  };\n\n  /////////////////////////////////////////////////////////////////////////////\n  // reference based Implementations 2 inputs\n  /////////////////////////////////////////////////////////////////////////////\n  NT2_FUNCTOR_IMPLEMENTATION_IF(nt2::tag::ellipke_, tag::cpu_,\n                                (A0)(A1)(A2)(X),\n                                (boost::mpl::equal_to < boost::simd::meta::cardinal_of<A0>\n                                                        , boost::simd::meta::cardinal_of<A2>\n                                                        >\n                                ),\n                                ((simd_<arithmetic_<A0>,X >))\n                                ((scalar_<floating_<A1> >))\n                                ((simd_<floating_<A2>,X >))\n                                ((simd_<floating_<A2>,X >))\n                             )\n  {\n    typedef void result_type;\n    inline result_type operator()(A0 const& a0,\n                                  A1 const& a1, A0 & a2,A0 & a3) const\n      {\n        nt2::ellipke(tofloat(a0),a1,a2,a3);\n      }\n  };\n\n  /////////////////////////////////////////////////////////////////////////////\n  // reference based Implementations 2 inputs\n  /////////////////////////////////////////////////////////////////////////////\n  NT2_FUNCTOR_IMPLEMENTATION(  nt2::tag::ellipke_, tag::cpu_,\n                                (A0)(A1)(X),\n                                ((simd_<floating_<A0>,X >))\n                                ((scalar_<floating_<A1> >))\n                                ((simd_<floating_<A0>,X >))\n                                ((simd_<floating_<A0>,X >))\n                                )\n  {\n    typedef void result_type;\n    inline result_type operator()(A0 const& a0,\n                                  A1 const& a1, A0 & a2,A0 & a3) const\n      {\n        typedef typename meta::as_logical<A0>::type bA0;\n        typedef typename meta::as_integer<A0>::type iA0;\n        typedef typename meta::scalar_of<A0>::type sA0;\n        bA0 isnan =  logical_or(is_ltz(a0), gt(a0, One<A0>()));\n        A0 m = if_zero_else(isnan, a0);\n        A0 aa0 = One<A0>();\n        A0 bb0 = sqrt(oneminus(m));\n        A0 s0 = m;\n        int32_t i1 = 0;\n        sA0 mm = One<sA0>();\n        A0 aa1 = Zero<A0>();\n        while (gt(mm, a1))\n          {\n            aa1 = average(aa0, bb0);\n            A0 bb1 = sqrt(aa0*bb0);\n            A0 cc1 = average(aa0, -bb0);\n            ++i1;\n            A0 w1 = ldexp(sqr(cc1), splat<iA0>(i1));\n            mm =  maximum(w1);\n            s0 += w1;\n            aa0 = aa1;\n            bb0 = bb1;\n          };\n        bA0 iseqm1 = eq(m, One<A0>());\n        a2 = if_nan_else(isnan, sel(iseqm1,Inf<A0>(), nt2::Pio_2<A0>()/aa1));\n        a3 = if_nan_else(isnan, sel(iseqm1,One<A0>(), a2*(One<A0>()-s0*Half<A0>())));\n      }\n  };\n\n} }\n#endif\n", "meta": {"hexsha": "c678aa23f2829f0ddc6f74d5ebba347fe59a484a", "size": 7347, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/elliptic/include/nt2/toolbox/elliptic/functions/simd/common/ellipke.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/elliptic/include/nt2/toolbox/elliptic/functions/simd/common/ellipke.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/elliptic/include/nt2/toolbox/elliptic/functions/simd/common/ellipke.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": 42.224137931, "max_line_length": 92, "alphanum_fraction": 0.4479379339, "num_tokens": 1688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2765676409039215}}
{"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/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[NUM_ITERATE];\nVector6d msf_state[200];\nVector3d acc[200];\ndouble dtime[200];\nint Iterate = 0;\nVector6d state;\nint Numimu = 0;\nint Numstate = 0;\nvoid 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}\nvoid gpscallback(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& data) {\n  gps_pose = *data;\n\n  if(Iterate>=NUM_ITERATE) return;\n\n  gps[Iterate][0] = gps_pose.pose.pose.position.x;\n  gps[Iterate][1] = gps_pose.pose.pose.position.y;\n  gps[Iterate][2] = gps_pose.pose.pose.position.z;\n\n  Iterate++;\n\n}\nvoid 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.1;  \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  while(ros::ok())\n    {\n\n      // saytab(\"Iter \");sayend(Iterate);\n      // static int k = 1;\n      ros::spinOnce();\n      r.sleep();\n      cur_time = ros::Time::now()-start_time;\n      dt = (cur_time - prev_time).toSec();\n      if(Iterate >= NUM_ITERATE) {\n        prev_time = cur_time;\n        sayend(\"START\");\n        Optimize_test(dt);\n        sayend(\"END\");\n        Iterate=0;\n        Numimu=0;\n        Numstate = 0;\n        poseop_pub.publish(poseop_msgs);\n      }\n      \n      // saytab(\"cur=\"); saytab(cur_time.toSec());\n      // saytab(\"prev=\");saytab(prev_time.toSec());\n      // saytab(\"dt=\");  sayend(dt);\n    }\n}\n\n\n\n// void Optimize_test(double dt ) {\n//     // Set up the optimiser\n//   SparseOptimizer optimizer;\n//   optimizer.setVerbose(false);\n\n//   // Create the block solver - the dimensions are specified because\n//   // 3D observations marginalise to a 3D estimate\n//   typedef BlockSolver<BlockSolverTraits<3, 3> > BlockSolver_3_3;\n//   BlockSolver_3_3::LinearSolverType* linearSolver\n//       = new LinearSolverCholmod<BlockSolver_3_3::PoseMatrixType>();\n//   BlockSolver_3_3* blockSolver\n//       = new BlockSolver_3_3(linearSolver);\n//   OptimizationAlgorithmGaussNewton* solver\n//     = new OptimizationAlgorithmGaussNewton(blockSolver);\n//   optimizer.setAlgorithm(solver);\n\n//   // Sample the actual location of the target\n//   Vector3d truePoint(0,\n//                      0,\n//                      0);\n\n\n//         // Construct vertex which corresponds to the actual point of the target\n//   VertexPosition3D* position = new VertexPosition3D();\n//   position->setId(0);\n//   optimizer.addVertex(position);\n\n\n//   // Now generate some noise corrupted measurements; for simplicity\n//   // these are uniformly distributed about the true target. These are\n//   // modelled as a unary edge because they do not like to, say,\n//   // another node in the map.\n//   int numMeasurements = Iterate;\n//   double noiseLimit = sqrt(12.);\n//   double noiseSigma = noiseLimit*noiseLimit / 12.0;\n//   double noiseSigma2 = noiseSigma;\n\n//   for (int i = 0; i < numMeasurements; i++)\n//     {\n//         for (int k = 0; k < Numstate; k++)\n//           {\n//             saytab(\"stage2\");\n//             Vector3d measurement2 = msf_state[k];\n//             GPSObservationPosition3DEdge* goe2 = new GPSObservationPosition3DEdge();\n//             goe2->setVertex(0, position);\n//             goe2->setMeasurement(measurement2);\n//             goe2->setInformation(Matrix3d::Identity() / noiseSigma2);\n//             optimizer.addEdge(goe2);\n//             saytab(\"stage3\");\n\n\n//           }\n//       lastposition = position;\n\n//       Vector3d measurement =gps[i];\n//       GPSObservationPosition3DEdge* goe = new GPSObservationPosition3DEdge();\n//       goe->setVertex(0, position);\n//       goe->setMeasurement(measurement);\n//       goe->setInformation(Matrix3d::Identity() / noiseSigma);\n//       optimizer.addEdge(goe);\n\n\n//               // Construct vertex which corresponds to the actual point of the target\n//     VertexPosition3D* position = new VertexPosition3D();\n//     position->setId(i+1);\n//     optimizer.addVertex(position);\n//     }\n\n//   // Configure and set things going\n//   optimizer.initializeOptimization();\n//   optimizer.setVerbose(true);\n//   optimizer.optimize(5);\n  \n//   cout << \"truePoint=\\n\" << truePoint << endl;\n\n//   cerr <<  \"computed estimate=\\n\" << dynamic_cast<VertexPosition3D*>(optimizer.vertices().find(0)->second)->estimate() << endl;\n\n//   //position->setMarginalized(true);\n  \n//   SparseBlockMatrix<MatrixXd> spinv;\n\n//   optimizer.computeMarginals(spinv, position);\n\n\n\n//   //optimizer.solver()->computeMarginals();\n\n//   // covariance\n//   //\n//   cout << \"covariance\\n\" << spinv << endl;\n\n//   cout << spinv.block(0,0) << endl;\n\n\n\n//   Vector3d v =  dynamic_cast<VertexPosition3D*>(optimizer.vertices().find(0)->second)->estimate();\n\n\n\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//        sayend(\"CAL COV\");\n//       // SparseBlockMatrix<MatrixXd> spinv;\n\n//       // optimizer.computeMarginals(spinv, position);\n\n\n\n//       // //optimizer.solver()->computeMarginals();\n\n//       // // covariance\n//       // //\n//       // cout << \"covariance\\n\" << spinv << endl;\n\n//       // 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\n\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.038;\n  const double gpsNoiseSigma = 1;\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  VertexPositionVelocity3D* stateNode = new VertexPositionVelocity3D();\n  stateNode->setEstimate(state);\n  stateNode->setId(0);\n  optimizer.addVertex(stateNode);\n\n  // Set up last estimate\n  VertexPositionVelocity3D* lastStateNode = stateNode;\n\n  // Iterate over the simulation steps\n  for (int k = 0; k < numberOfTimeSteps; ++k)\n    {   \n      for(int j = 0; j < Numstate-1; j++) \n      {\n        saytab(j);saytab(Numstate);saytab(Numimu);sayend(Iterate);\n\n          state = msf_state[j];\n          // Construct vertex which corresponds to the current state of the target\n          VertexPositionVelocity3D* stateNode = new VertexPositionVelocity3D();\n          \n          stateNode->setId((Numstate-1)*k+j+1);\n          stateNode->setEstimate(state);\n          stateNode->setMarginalized(false);\n          optimizer.addVertex(stateNode);\n\n          sayend(\"STEP1\");\n          // Construct the accelerometer measurement\n          Vector3d accelerometerMeasurement = acc[j];\n\n          TargetOdometry3DEdge* toe = new TargetOdometry3DEdge(0.01, 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          sayend(\"STEP2\");\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          sayend(\"STEP3\");\n      }\n      \n        // Construct the GPS observation\n        Vector3d gpsMeasurement = gps[k];\n\n      sayend(\"STEP21\");\n      // Add the GPS observation\n      GPSObservationEdgePositionVelocity3D* goe = new GPSObservationEdgePositionVelocity3D(gpsMeasurement, gpsNoiseSigma);\n      goe->setVertex(0, stateNode);\n      optimizer.addEdge(goe);\n      sayend(\"STEP22\");\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\n       Vector6d v = dynamic_cast<VertexPositionVelocity3D*>(optimizer.vertices().find((std::max)(numberOfTimeSteps-1,0))->second)->estimate();\n\n\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", "meta": {"hexsha": "ad703340ba82db63ee9614ef1c1a16be708e8188", "size": 15580, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "data/crossover_nav/src/gps_tester.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/gps_tester.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/gps_tester.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": 30.790513834, "max_line_length": 142, "alphanum_fraction": 0.6508344031, "num_tokens": 4274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2764595632948938}}
{"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\n#include \"DensityMatrixBuilder.h\"\n#include <Utils/DataStructures/DensityMatrix.h>\n#include <Utils/DataStructures/MolecularOrbitals.h>\n#include <Utils/Scf/LcaoUtils/LcaoUtils.h>\n#include <Eigen/Core>\n#include <cassert>\n#include <cmath>\n\nnamespace Scine {\nnamespace Utils {\n\nnamespace LcaoUtils {\n\nDensityMatrixBuilder::DensityMatrixBuilder(const MolecularOrbitals& coefficientMatrix)\n  : coefficientMatrix_(coefficientMatrix) {\n  assert(coefficientMatrix.isValid());\n}\n\nDensityMatrix DensityMatrixBuilder::generateRestrictedForNumberElectrons(int nElectrons) const {\n  assert(nElectrons >= 0);\n  assert(coefficientMatrix_.isRestricted());\n  const auto& C = coefficientMatrix_.restrictedMatrix();\n  Eigen::MatrixXd P = 2 * calculateDensityMatrix(C, nElectrons / 2);\n\n  if ((nElectrons % 2) != 0) // if odd number of electrons\n    P += calculateSingleOrbitalDensity(C.col(nElectrons / 2));\n\n  DensityMatrix densityMatrix;\n  densityMatrix.setDensity(std::move(P), nElectrons);\n  return densityMatrix;\n}\n\nEigen::MatrixXd DensityMatrixBuilder::calculateDensityMatrix(const Eigen::MatrixXd& coefficientMatrix, int nOccupiedLevels) const {\n  auto nAOs = coefficientMatrix.cols();\n  assert(nAOs >= nOccupiedLevels && \"More electrons than atomic orbitals.\");\n\n  Eigen::MatrixXd P = calculateBlockOrbitalDensity(coefficientMatrix.block(0, 0, nAOs, nOccupiedLevels));\n  return P;\n}\n\nDensityMatrix DensityMatrixBuilder::generateUnrestrictedForNumberElectronsAndMultiplicity(int nElectrons,\n                                                                                          int spinMultiplicity) const {\n  assert(coefficientMatrix_.isUnrestricted());\n  int nAlpha, nBeta;\n  LcaoUtils::getNumberUnrestrictedElectrons(nAlpha, nBeta, nElectrons, spinMultiplicity);\n  return generateUnrestrictedForNumberAlphaAndBetaElectrons(nAlpha, nBeta);\n}\n\nDensityMatrix DensityMatrixBuilder::generateUnrestrictedForNumberAlphaAndBetaElectrons(int nAlpha, int nBeta) const {\n  assert(nAlpha >= 0 && nBeta >= 0);\n  assert(coefficientMatrix_.isUnrestricted());\n  const auto& cA = coefficientMatrix_.alphaMatrix();\n  const auto& cB = coefficientMatrix_.betaMatrix();\n\n  Eigen::MatrixXd alphaMatrix = calculateDensityMatrix(cA, nAlpha);\n  Eigen::MatrixXd betaMatrix = calculateDensityMatrix(cB, nBeta);\n\n  DensityMatrix densityMatrix;\n  densityMatrix.setDensity(std::move(alphaMatrix), std::move(betaMatrix), nAlpha, nBeta);\n  return densityMatrix;\n}\n\nDensityMatrix DensityMatrixBuilder::generateRestrictedForSpecifiedOrbitals(const std::vector<int>& doublyOccupiedOrbitals) const {\n  assert(coefficientMatrix_.isRestricted());\n  const auto& C = coefficientMatrix_.restrictedMatrix();\n  auto nAOs = C.rows();\n  Eigen::MatrixXd P = Eigen::MatrixXd::Zero(nAOs, nAOs);\n\n  for (auto o : doublyOccupiedOrbitals) {\n    assert(o < nAOs && \"Orbital index larger than the number of atomic orbitals.\");\n    P += 2 * calculateSingleOrbitalDensity(C.col(o));\n  }\n\n  DensityMatrix densityMatrix;\n  auto nSpecifiedOrbitals = static_cast<int>(2 * doublyOccupiedOrbitals.size());\n  densityMatrix.setDensity(std::move(P), nSpecifiedOrbitals);\n  return densityMatrix;\n}\n\nDensityMatrix DensityMatrixBuilder::generateUnrestrictedForSpecifiedOrbitals(const std::vector<int>& alphaOrbitals,\n                                                                             const std::vector<int>& betaOrbitals) const {\n  assert(coefficientMatrix_.isUnrestricted());\n  const auto& Ca = coefficientMatrix_.alphaMatrix();\n  const auto& Cb = coefficientMatrix_.betaMatrix();\n  auto nAOs = Ca.rows();\n  Eigen::MatrixXd Pa = Eigen::MatrixXd::Zero(nAOs, nAOs);\n  Eigen::MatrixXd Pb = Eigen::MatrixXd::Zero(nAOs, nAOs);\n\n  for (auto o : alphaOrbitals) {\n    assert(o < nAOs && \"Orbital index larger than the number of atomic orbitals.\");\n    Pa += calculateSingleOrbitalDensity(Ca.col(o));\n  }\n  for (auto o : betaOrbitals) {\n    assert(o < nAOs && \"Orbital index larger than the number of atomic orbitals.\");\n    Pb += calculateSingleOrbitalDensity(Cb.col(o));\n  }\n\n  DensityMatrix densityMatrix;\n  auto nAlpha = static_cast<int>(alphaOrbitals.size());\n  auto nBeta = static_cast<int>(betaOrbitals.size());\n  densityMatrix.setDensity(std::move(Pa), std::move(Pb), nAlpha, nBeta);\n  return densityMatrix;\n}\n\nDensityMatrix\nDensityMatrixBuilder::generateRestrictedWithSwaps(const std::vector<MolecularOrbitalsManipulation::DeprecatedSwap>& swaps,\n                                                  int nElectrons) const {\n  assert(coefficientMatrix_.isRestricted());\n  assert(nElectrons % 2 == 0 && \"The number of electrons is not even.\");\n  const auto& C = coefficientMatrix_.restrictedMatrix();\n  Eigen::MatrixXd P = 2 * calculateDensityMatrix(C, nElectrons / 2);\n  P += 2 * calculateDifferenceSwapDensity(C, swaps, nElectrons / 2 - 1);\n\n  DensityMatrix densityMatrix;\n  densityMatrix.setDensity(std::move(P), nElectrons);\n  return densityMatrix;\n}\n\nDensityMatrix DensityMatrixBuilder::generateUnrestrictedWithSwaps(\n    const std::vector<MolecularOrbitalsManipulation::DeprecatedSwap>& alphaSwaps,\n    const std::vector<MolecularOrbitalsManipulation::DeprecatedSwap>& betaSwaps, int nAlpha, int nBeta) const {\n  assert(coefficientMatrix_.isUnrestricted());\n  const auto& cA = coefficientMatrix_.alphaMatrix();\n  const auto& cB = coefficientMatrix_.betaMatrix();\n\n  Eigen::MatrixXd alphaMatrix = calculateDensityMatrix(cA, nAlpha);\n  Eigen::MatrixXd betaMatrix = calculateDensityMatrix(cB, nBeta);\n\n  alphaMatrix += calculateDifferenceSwapDensity(cA, alphaSwaps, nAlpha - 1);\n  betaMatrix += calculateDifferenceSwapDensity(cB, betaSwaps, nBeta - 1);\n\n  DensityMatrix densityMatrix;\n  densityMatrix.setDensity(std::move(alphaMatrix), std::move(betaMatrix), nAlpha, nBeta);\n  return densityMatrix;\n}\n\nEigen::MatrixXd DensityMatrixBuilder::calculateSingleOrbitalDensity(const Eigen::VectorXd& eigenvector) const {\n  return eigenvector * eigenvector.transpose();\n}\n\nEigen::MatrixXd DensityMatrixBuilder::calculateBlockOrbitalDensity(const Eigen::MatrixXd& eigenvectors) const {\n  return eigenvectors * eigenvectors.transpose();\n}\n\nEigen::MatrixXd\nDensityMatrixBuilder::calculateDifferenceSwapDensity(const Eigen::MatrixXd& coefficientMatrix,\n                                                     const std::vector<MolecularOrbitalsManipulation::DeprecatedSwap>& swaps,\n                                                     int homoIndex) const {\n  auto dim = coefficientMatrix.rows();\n  Eigen::MatrixXd dP = Eigen::MatrixXd::Zero(dim, dim);\n\n  for (auto s : swaps) {\n    auto oldOrbital = homoIndex + 1 + s.lowLyingOrbitalNotToFill_;\n    auto newOrbital = homoIndex + s.highLyingOrbitalToFill_;\n    dP -= calculateSingleOrbitalDensity(coefficientMatrix.col(oldOrbital));\n    dP += calculateSingleOrbitalDensity(coefficientMatrix.col(newOrbital));\n  }\n\n  return dP;\n}\n\nDensityMatrix DensityMatrixBuilder::generateRestrictedForSpecifiedPartlyOccupiedOrbitals(\n    const std::vector<DensityMatrixBuilder::PartlyOccupiedOrbital>& orbitals) {\n  assert(coefficientMatrix_.isRestricted());\n  const auto& C = coefficientMatrix_.restrictedMatrix();\n  auto nAOs = C.rows();\n  DensityMatrix densityMatrix;\n  Eigen::MatrixXd P = Eigen::MatrixXd::Zero(nAOs, nAOs);\n  densityMatrix.setDensity(std::move(P), 0);\n\n  for (auto o : orbitals) {\n    assert(o.first < nAOs && \"Orbital index larger than the number of atomic orbitals.\");\n    densityMatrix += generateRestrictedForSpecifiedOrbitals({o.first}) * (o.second / 2);\n  }\n\n  return densityMatrix;\n}\n\nDensityMatrix DensityMatrixBuilder::generateUnrestrictedForSpecifiedPartlyOccupiedOrbitals(\n    const std::vector<DensityMatrixBuilder::PartlyOccupiedOrbital>& alphaOrbitals,\n    const std::vector<DensityMatrixBuilder::PartlyOccupiedOrbital>& betaOrbitals) {\n  assert(coefficientMatrix_.isUnrestricted());\n  const auto& Ca = coefficientMatrix_.alphaMatrix();\n  auto nAOs = Ca.rows();\n  DensityMatrix densityMatrix;\n  Eigen::MatrixXd Pa = Eigen::MatrixXd::Zero(nAOs, nAOs);\n  Eigen::MatrixXd Pb = Eigen::MatrixXd::Zero(nAOs, nAOs);\n  densityMatrix.setDensity(std::move(Pa), std::move(Pb), 0, 0);\n\n  for (auto o : alphaOrbitals) {\n    assert(o.first < nAOs && \"Orbital index larger than the number of atomic orbitals.\");\n    densityMatrix += generateUnrestrictedForSpecifiedOrbitals({o.first}, {}) * o.second;\n  }\n  for (auto o : betaOrbitals) {\n    assert(o.first < nAOs && \"Orbital index larger than the number of atomic orbitals.\");\n    densityMatrix += generateUnrestrictedForSpecifiedOrbitals({}, {o.first}) * o.second;\n  }\n\n  return densityMatrix;\n}\n\nDensityMatrix\nDensityMatrixBuilder::generateRestrictedWithMixing(const std::vector<MolecularOrbitalsManipulation::DeprecatedMix>& mix,\n                                                   int nElectrons) const {\n  assert(coefficientMatrix_.isRestricted());\n\n  const auto& C = coefficientMatrix_.restrictedMatrix();\n  Eigen::MatrixXd P = 2 * calculateDensityMatrix(C, nElectrons / 2);\n\n  P += 2 * calculateDifferenceMixDensity(C, mix, nElectrons / 2 - 1);\n\n  DensityMatrix densityMatrix;\n  densityMatrix.setDensity(std::move(P), nElectrons);\n  return densityMatrix;\n}\n\nDensityMatrix DensityMatrixBuilder::generateUnrestrictedWithMixing(\n    const std::vector<MolecularOrbitalsManipulation::DeprecatedMix>& alphaMix,\n    const std::vector<MolecularOrbitalsManipulation::DeprecatedMix>& betaMix, int nAlpha, int nBeta) const {\n  assert(coefficientMatrix_.isUnrestricted());\n  const auto& cA = coefficientMatrix_.alphaMatrix();\n  const auto& cB = coefficientMatrix_.betaMatrix();\n\n  Eigen::MatrixXd alphaMatrix = calculateDensityMatrix(cA, nAlpha);\n  Eigen::MatrixXd betaMatrix = calculateDensityMatrix(cB, nBeta);\n\n  alphaMatrix += calculateDifferenceMixDensity(cA, alphaMix, nAlpha - 1);\n  betaMatrix += calculateDifferenceMixDensity(cB, betaMix, nBeta - 1);\n\n  DensityMatrix densityMatrix;\n  densityMatrix.setDensity(std::move(alphaMatrix), std::move(betaMatrix), nAlpha, nBeta);\n  return densityMatrix;\n}\n\nEigen::MatrixXd\nDensityMatrixBuilder::calculateDifferenceMixDensity(const Eigen::MatrixXd& coefficientMatrix,\n                                                    const std::vector<MolecularOrbitalsManipulation::DeprecatedMix>& mix,\n                                                    int homoIndex) const {\n  auto dim = coefficientMatrix.rows();\n  Eigen::MatrixXd dP = Eigen::MatrixXd::Zero(dim, dim);\n\n  for (auto m : mix) {\n    auto oldOrbital = homoIndex + 1 + m.lowLyingOrbitalNotToFill_;\n    auto newOrbital = homoIndex + m.highLyingOrbitalToFill_;\n    dP -= calculateSingleOrbitalDensity(coefficientMatrix.col(oldOrbital));\n    dP += calculateBlockOrbitalDensity(coefficientMatrix.col(oldOrbital) * std::cos(m.angleInRad_) +\n                                       coefficientMatrix.col(newOrbital) * std::sin(m.angleInRad_));\n  }\n\n  return dP;\n}\n\n} // namespace LcaoUtils\n} // namespace Utils\n} // namespace Scine\n", "meta": {"hexsha": "f56bd2ab4e5c5141e37186117f528948c1a5c51d", "size": 11065, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Utils/Scf/LcaoUtils/DensityMatrixBuilder.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/Scf/LcaoUtils/DensityMatrixBuilder.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/Scf/LcaoUtils/DensityMatrixBuilder.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.072243346, "max_line_length": 131, "alphanum_fraction": 0.7297785811, "num_tokens": 2690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.27640286926193675}}
{"text": "/* \n * Copyright (c) 2006-2012 Nicholas Devenish\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n * the Software, 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 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, FITNESS\n * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n * \n */\n\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <ctime>\n#include <vector>\n\n/*\n#include <boost/random.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n*/\n\n#include <boost/thread/mutex.hpp>\n\n#include \"errors.h\"\n#include \"reporters.h\"\n#include \"edmexperiment.h\"\n#include \"particle.h\"\n#include \"container.h\"\n#include \"random.h\"\n\n#include \"electromagnetics.h\"\n\n#include \"variable.h\"\n//#include \"spinpair.h\"\n\n#include \"boost/foreach.hpp\"\n\nusing std::string;\nusing std::runtime_error;\nusing std::ofstream;\n\nusing std::cout;\nusing std::endl;\n\n//using boost::mt11213b;\n\nusing std::vector;\n\nusing nsl::rand_uniform;\n\nusing nsl::variable;\n\n/// Calculate the volume average dbz/dz value, to a specified power\ndataset calc_dbdz(bfield &b, container &cont, long double power = 1.0)\n{\n\t// Let's grab the size of the volume to generate over\n\tcylbounds cyl = cont.getcylinder();\n\t\n\tunsigned long hits = 0, misses = 0, throws = 0;\n\t\n\t//\tlong double x, y, z;\n\tvector3 pos, magfield;\n\tdataset vertgrad;\n\t\n\twhile (1)\n\t{\n\t\t//r = sqrtl(uni()) * cyl.radius;\n\t\tpos.z =(rand_uniform() - 0.5) * cyl.height;\n\t\tpos.x = rand_uniform() * cyl.radius*2. - cyl.radius;\n\t\tpos.y = rand_uniform() * cyl.radius*2. - cyl.radius;\n\t\t\n\t\t// Throw these out if outside test cylinder\n\t\tif (pos.x*pos.x + pos.y*pos.y > cyl.radius *cyl.radius)\n\t\t{\n\t\t\tthrows++;\n\t\t\tcontinue;\n\t\t}\n\t\tpos += cyl.position;\n\t\t\n\t\t//Now, test to see if these points are inside a container\n\t\tif (!cont.isinside(pos))\n\t\t{\n\t\t\t// If it isn't inside a container, this is a miss. This can be used to estimate the volume\n\t\t\tmisses++;\n\t\t\tcontinue;\n\t\t} else {\n\t\t\thits++;\n\t\t\tmagfield = vector3(0.0,0.0,0.0);\n\t\t\tb.getfieldgradient(magfield,pos);\n\t\t\t\n\t\t\tvertgrad += pow(magfield.z, power);\n\t\t}\n\t\t\n\t\tif (hits > 1e6)\n\t\t\tbreak;\n\t}\n\t// Calculate the estimated volume\n\tlong double hitratio = (long double)hits / (long double)(hits+misses);\n\tlong double volumeestimate = hitratio * pi * cyl.radius * cyl.radius * cyl.height;\n\t// Estimate the error on the volume, by culculating the volume estimate change by a\n\t// single hit difference\n\tlong double volumeplushitest = (((long double)(hits+1) / (long double)(hits+misses+1))) * pi * cyl.radius * cyl.height * cyl.radius;\n//\tlong double volerrest = volumeestimate * ((volumeestimate / volumeplushitest) - 1.);\n\t\n\t\n\tcout << \"   <dBz/dz^\" << power << \"> = \" << vertgrad << \" T/(m^\" << (int)power << \")\" << endl;\n//\tcout << \"\tEstimated Volume = \" << volumeestimate << \" +- \" << volerrest << \" m^3\" << endl;\n//\tcout << \n\t//vertgrad /= volumeestimate;\n\t//logger << \"   Average field gradient over volume : \" << vertgrad<< endl;\n\t\n\treturn vertgrad;\n}\n\n// And again, to calculate the magnetic field!\nvariable calc_baverage(bfield &b, container &cont)\n{\n\t// Let's grab the size of the volume to generate over\n\tcylbounds cyl = cont.getcylinder();\n\t\n\tunsigned long hits = 0, misses = 0, throws = 0;\n\t\n\t//\tlong double x, y, z;\n\tvector3 pos, magfield;\n\tdataset b_avg;\n\t\n\twhile (1)\n\t{\n\t\t//r = sqrtl(uni()) * cyl.radius;\n\t\tpos.z =(rand_uniform() - 0.5) * cyl.height;\n\t\tpos.x = rand_uniform() * cyl.radius*2. - cyl.radius;\n\t\tpos.y = rand_uniform() * cyl.radius*2. - cyl.radius;\n\t\t\n\t\t// Throw these out if outside test cylinder\n\t\tif (pos.x*pos.x + pos.y*pos.y > cyl.radius *cyl.radius)\n\t\t{\n\t\t\tthrows++;\n\t\t\tcontinue;\n\t\t}\n\t\tpos += cyl.position;\n\t\t\n\t\t//Now, test to see if these points are inside a container\n\t\tif (!cont.isinside(pos))\n\t\t{\n\t\t\t// If it isn't inside a container, this is a miss. This can be used to estimate the volume\n\t\t\tmisses++;\n\t\t\tcontinue;\n\t\t} else {\n\t\t\thits++;\n\t\t\tmagfield = vector3(0.0,0.0,0.0);\n\t\t\tb.getfield(magfield,pos);\n\t\t\t\n\t\t\tb_avg += magfield.z;\n\t\t}\n\t\t\n\t\tif (hits > 1e6)\n\t\t\tbreak;\n\t}\n\t// Calculate the estimated volume\n\t//long double hitratio = (long double)hits / (long double)(hits+misses);\n\t//long double volumeestimate = hitratio * pi * cyl.radius * cyl.radius * cyl.height;\n\t// Estimate the error on the volume, by culculating the volume estimate change by a\n\t// single hit difference\n\t//long double volumeplushitest = (((long double)(hits+1) / (long double)(hits+misses+1))) * pi * cyl.radius * cyl.height * cyl.radius;\n\t//long double volerrest = volumeestimate * ((volumeestimate / volumeplushitest) - 1.);\n\t\n\tcout << \"   <B>        = \" << b_avg.average() - 1.e-6 << \" +- \" << b_avg.uncert() << \" T (shifted, +1e-6)\" << endl;\n\t\n\treturn variable(b_avg);\n}\n\n\n\nreporter::reporter()\n{\n\toutfile = 0;\n//\treport_count = 0;\n\t\n\tstreamname = \"void\";\n\n\t// Set a default reporting frequency\n\treport_frequency = rfreq_none;\n\n\tobjecttype = \"reporter\";\n\ttypes.push_back(objecttype);\n}\n\nreporter::~reporter()\n{\n\tif (outfile)\n\t\tdelete (ofstream*)outfile;\n}\n\nbool reporter::prepareobject()\n{\n\t// See if we should override the default report frequency for this class\n\tstring runfreq;\n\tif(isset(\"report_frequency\"))\n\t{\n\t\trunfreq = get(\"report_frequency\");\n\t\tif (runfreq == \"none\")\n\t\t\treport_frequency = rfreq_none;\n\t\telse if (runfreq == \"run\")\n\t\t\treport_frequency = rfreq_run;\n\t\telse if (runfreq == \"bounce\")\n\t\t\treport_frequency = rfreq_bounce;\n\t\telse if (runfreq == \"step\")\n\t\t\treport_frequency = rfreq_step;\n\t\telse if (runfreq == \"interval\")\n\t\t\treport_frequency = rfreq_interval;\n\t\telse\n\t\t\tthrow runtime_error(\"Unknown report frequency being set in reporter\");\n\t}\n\t\n\t// Get the output format\n\tstring outfmt;\n\tif (isset(\"output_format\"))\n\t{\n\t\toutfmt = get(\"output_format\");\n\t\tif (outfmt == \"plain\")\n\t\t\toutput_format = format_plain;\n\t\telse\n\t\t\tthrow runtime_error(\"Unknown output format being specified.\");\n\t}\n\t\n\t// Get the output filename\n\tif (!isset(\"output_file\")) {\n\t\toutfile = &(std::cout);\n\t\tstreamname = \"stdout\";\n\t} else {\n\t\tstreamname = get(\"output_file\");\n\t\tstd::cout << \"Logging to stream: \" << streamname << endl;\n\t\t\n\t\toutfile = new ofstream(streamname.c_str());\n\t\t\n\t}\n\t\n\t\t\n\treturn true;\n}\n\nvoid reporter::preparefile( edmexperiment &experiment )\n{\n\t\n\t// Warn the user if no output file being written\n\tlogger << \"Warning: No header being written for output file \" << get(\"output_file\") << endl;\n\t\n\t/*\n\t*outfile << \"Base Data file\" << endl;\n\t\n\t*outfile << experiment.get(\"runtime\") << endl;\n\t*outfile <<  \"---------------------------------\" << endl;\n*/\n\t\n  //printf ( \"Current date and time are: %s\", asctime (timeinfo) );\n  \n\t\n}\n\t\nvoid reporter::closefile( edmexperiment &experiment )\n{/*\n\t*outfile << \"---------------------------------\" << endl;\n\t*outfile << \"End of all data runs at \";\n\t\n\ttime_t rawtime;\n\ttm * timeinfo;\n\ttime ( &rawtime );\n\ttimeinfo = localtime ( &rawtime );\n\t//set(\"runtime\",  asctime(timeinfo));\n\t*outfile << asctime(timeinfo) << endl;*/\n}\n\t\nvoid reporter::report( edmexperiment &experiment )\n{\n\tstatic long stepcount = 0;\n\t\n\t// Enclose this in a block for mutexing, to prevent two threads simultaneously writing out\n\t{\n\t\tstatic boost::mutex output_mutex;\n\t\tboost::mutex::scoped_lock lock(output_mutex);\n\t\t\n\t\t*outfile << \"Report #\" << ++stepcount << endl;\n\t}\n}\n\n/////////////////////////////////////////////////////////\n// Impactreporter - a small class to log impact positions\nimpactreporter::impactreporter() {\n\treport_frequency = rfreq_bounce;\n//\treport_frequency = rfreq_none;\n\tobjecttype = \"impactreporter\";\n\ttypes.push_back(objecttype);\n}\n\nvoid impactreporter::preparefile (edmexperiment &exp)\n{\n\t*outfile << \"# Impact Reporter log file: \" << exp.get(\"runtime\") << endl;\n\t*outfile << \"# Bounce\\tBounce2\\tflytime\\tx\\ty\\tz\\tsum_phase\" << endl;// << \"------------------------------------\" << endl;\n\toutfile->precision(20);\n}\n\nvoid impactreporter::report( edmexperiment &experiment ) {\n\tstatic long bounce = 0;\n\n\t// Enclose this in a block for mutexing, to prevent two threads simultaneously writing out\n\t{\n\t\tstatic boost::mutex output_mutex;\n\t\tboost::mutex::scoped_lock lock(output_mutex);\n\t\t\n\t\t*outfile << bounce++ << \"\\t\" << experiment.particles[0]->bounces << \"\\t\" << experiment.particles[0]->flytime << \"\\t\"\n\t\t\t<< experiment.particles[0]->position.x << \"\\t\"\n\t\t\t<< experiment.particles[0]->position.y << \"\\t\"\n\t\t\t<< experiment.particles[0]->position.z << \"\\t\"\n\t\t\t<< experiment.particles[0]->E_sum_phase << endl;\n\t}\n}\n\n/////////////////////////////////////////////////////////\n// Phasereporter - a small class to output the phase over time\nphasereporter::phasereporter()\n{\n\tobjecttype = \"phasereporter\";\n\ttypes.push_back(objecttype);\n\t\n\treport_frequency = rfreq_step;\n//\treport_frequency = rfreq_none;\n}\n\nvoid phasereporter::preparefile (edmexperiment &exp)\n{\n\t*outfile << \"# Phase progress log file: \" << exp.get(\"runtime\") << endl;\n\t*outfile << \"# #Num, flytime, phase_e+, diff\" << endl << \"------------------------------------\" << endl;\n}\nvoid phasereporter::report ( edmexperiment &ex )\n{\n\tstatic long stepa = 0;\n\t\n\t// Enclose this in a block for mutexing, to prevent two threads simultaneously writing out\n\t{\n\t\tstatic boost::mutex output_mutex;\n\t\tboost::mutex::scoped_lock lock(output_mutex);\n\t\t\n\t\toutfile->precision(20);\n\t\t*outfile << ++stepa << \", \" << ex.particles[0]->flytime \n\t\t\t\t\t//<< \", \" << ex.particles[0]->spinEplus << endl;\n\t\t\n\t\t\t\t\t<< \", \" << ex.particles[0]->E_sum_phase \n\t\t\t\t\t<< \", \" << ex.particles[0]->E_minus_sum_phase\n\t\t\t\t\t<< \", \" << ex.particles[0]->E_sum_phase - ex.particles[0]->E_minus_sum_phase\n\t\t\t\t\t/*<< \", \" << ex.change.average()\n\t\t\t\t\t<< \", \" << ex.tmpld*/\n\t\t\t\t\t<< endl;\n\t}\n}\n\n\n/////////////////////////////////////////////////////////\n// Interval reporter - a simple test of interval reporting\n\nintervalreporter::intervalreporter()\n{\n\tobjecttype = \"intervalreporter\";\n\ttypes.push_back(objecttype);\n\t\n\treport_frequency = rfreq_interval;\n}\n\nvoid intervalreporter::preparefile(edmexperiment &exp)\n{\n\t*outfile << \"# Interval reporter test run \" << endl;\n\t*outfile << \"# List of times at the inteval\" << endl;\n}\n\nvoid intervalreporter::report ( edmexperiment & experiment )\n{\n\tdataset ensemble;\n\t\n\t// calculate the average flytime\n\tBOOST_FOREACH(particle *p, experiment.particles)\n\t{\n\t\tensemble += p->flytime;\n\t}\n\t\n\t// Enclose this in a block for mutexing, to prevent two threads simultaneously writing out\n\t{\n\t\tstatic boost::mutex output_mutex;\n\t\tboost::mutex::scoped_lock lock(output_mutex);\n\t\t\n\t\t*outfile << ensemble.points() << \"\\t\" << ensemble << endl;;\n\t}\n}\n \n/////////////////////////////////////////////////////////\n// edmreporter - The main variational output class\nedmreporter::edmreporter()\n{\n\tobjecttype = \"edmreporter\";\n\ttypes.push_back(objecttype);\n\t\n\treport_frequency = rfreq_run;\n}\n\nvoid edmreporter::preparefile(edmexperiment &exp)\n{\n\t*outfile << \"# Edm loop report: \" << exp.get(\"runtime\") << \"#\" << endl;\n\t*outfile << \"# \" << exp.variation.parameter << \"\\t\" << \"False-EDM\" << \"\\t\" << \"uncert\";\n\t\n\tif (volaverage)\n\t\t*outfile << \"\\t\" << \"volavg-dbzdz\" << \"\\t\" << \"uncert\";\n\t\n\t*outfile << endl;\n}\n\nvoid edmreporter::report ( edmexperiment &experiment )\n{\n\t// Loop over all the particles and generate an average EDM\n\tdataset edmav;\n\tBOOST_FOREACH( particle *part, experiment.particles )\n\t{\n\t\tedmav += part->cumulativeedm;\n\t}\n\n\t// Calculate an average vertical field gradient if required\n\tdataset vergrad;\n\tif (volaverage)\n\t{\n\t\t// Grab pointers to the container and magnetic field\n\t\tcontainer *box = experiment.particlebox;\n\t\tbfield* b = experiment.magfield;\n\t\tvergrad = calc_dbdz(*b, *box);\n\t}\n\t\n\t// Enclose this in a block for mutexing, to prevent two threads simultaneously writing out\n\t{\n\t\tstatic boost::mutex output_mutex;\n\t\tboost::mutex::scoped_lock lock(output_mutex);\n\t\t\n\t\t*outfile << experiment.variation.value << \"\\t\" <<  edmav.average() << \"\\t\" << edmav.uncert();\n\t\tif (volaverage)\n\t\t\t*outfile << \"\\t\" << vergrad.average() << \"\\t\" << vergrad.uncert();\n\t}\n\t\t\n\t*outfile << endl;\n}\n\nbool edmreporter::prepareobject()\n{\n\treporter::prepareobject();\n\t\n\tif (isset(\"volaverage_dbdz\"))\n\t\tvolaverage = true;\n\n\treturn true;\n}\n\n/////////////////////////////////////////////////////////\n// Polarizationrepoter - reports on the polarisation of the particles\n// at an interval step\n\npolreporter::polreporter()\n{\n\tobjecttype = \"polreporter\";\n\ttypes.push_back(objecttype);\n\t\n\treport_frequency = rfreq_interval;\n}\n\nvoid polreporter::preparefile(edmexperiment &exp)\n{\n\t*outfile << \"# Polarization report: \" << exp.get(\"time\") << endl;\n\t*outfile << \"# Flight-time\\t Average_phase\\t Stdev\\t Average_Phase(-E)\\t Stdev\" << endl;\n}\n\nbool polreporter::prepareobject()\n{\n\treporter::prepareobject();\n\t\n\treturn true;\n}\n\nvoid polreporter::report( edmexperiment &exp )\n{\n\t// Firstly, calculate the average cumulative frequencies\n\tdataset cumfreq, cumfreqminus, flighttime;\n\t\n\tBOOST_FOREACH(particle *p, exp.particles)\n\t{\n\t\tcumfreq\t\t+= p->E_sum_phase;\t//long double E_sum_phase, E_minus_sum_phase;\n\t\tcumfreqminus+= p->E_minus_sum_phase;\n\t\tflighttime += p->flytime;\n\t}\n\tif (flighttime.stdev() > 1e-7)\n\t{\n\t\tlogger << \"Flighttime Deviation: Flighttime: \" << flighttime.average() << \" +/- \" << flighttime.stdev() << endl;\n\t\t//throw runtime_error(\"Flight-time of particles do not all agree\");\n\t}\n\t\n\t// Enclose this in a block for mutexing, to prevent two threads simultaneously writing out\n\t{\n\t\tstatic boost::mutex output_mutex;\n\t\tboost::mutex::scoped_lock lock(output_mutex);\n\t\t\n\t\t*outfile << flighttime.average() << \"\\t\" << cumfreq.average() << \"\\t\" << cumfreq.stdev()\n\t\t\t\t << \"\\t\" << cumfreqminus.average() << \"\\t\" << cumfreqminus.stdev();\n\n\t\t*outfile << endl;\n\t}\n}\n\n/////////////////////////////////////////////////////////\n// Poldistreporter - reports on the distribution of particles\n/*\nclass poldistreporter : public reporter {\nprotected:\n\tvoid preparefile( edmexperiment &exp );\n\t\npublic:\n\tpoldistreporter();\n\tvoid report ( edmexperiment &experiment );\n\t\n\tclass Factory : public nslobjectfactory {\n\t\tnslobject *create() { return new poldistreporter; }\n\t};\t\n};*/\npoldistreporter::poldistreporter()\n{\n\tobjecttype = \"poldistreporter\";\n\ttypes.push_back(objecttype);\n\t\n\treport_frequency = rfreq_interval;\n}\n\nbool poldistreporter::prepareobject ( void )\n{\n\treporter::prepareobject();\n\n\tif (isset(\"negphase\"))\n\t\tlogphase = phase_negative;\n\telse\n\t\tlogphase = phase_positive;\n\n\treturn true;\n}\nvoid poldistreporter::preparefile( edmexperiment &exp )\n{\n\t*outfile << \"# Polarization Distribution report: \" << exp.get(\"time\") << endl;\n\t*outfile << \"# Reporting \";\n\tif (logphase == phase_negative)\n\t\t*outfile << \"negative \";\n\telse\t\n\t\t*outfile << \"positive \";\n\t*outfile << \"phase.\" << endl;\n\t*outfile << \"# Flight-time\\tAverage_phase\";\n\tfor (unsigned int i = 0; i < exp.particles.size(); i++)\n\t\t*outfile << \"\\t\" << \"Part_\" << i+1 << \"_phase\";\n\t*outfile << endl;\n}\n\nvoid poldistreporter::report( edmexperiment &exp )\n{\n\tdataset time, phase;\n\t//Grab the elapsed time\n\tBOOST_FOREACH(particle *p, exp.particles)\n\t{\n\t\ttime += p->flytime;\n\t\tif(logphase == phase_positive)\n\t\t\tphase += p->E_sum_phase;\n\t\telse\n\t\t\tphase += p->E_minus_sum_phase;\n\t}\n\t\n\t// Enclose this in a block for mutexing, to prevent two threads simultaneously writing out\n\t{\n\t\tstatic boost::mutex output_mutex;\n\t\tboost::mutex::scoped_lock lock(output_mutex);\n\n\t\toutfile->precision(20);\n\t\t*outfile << time.average() << \"\\t\" << phase.average();\n\t\t\n\t\tBOOST_FOREACH(particle *p, exp.particles)\n\t\t\tif (logphase == phase_positive)\n\t\t\t\t*outfile << \"\\t\" << (p->E_sum_phase-phase.average());\n\t\t\telse \n\t\t\t\t*outfile << \"\\t\" << (p->E_minus_sum_phase-phase.average());\n\t\t\n\t\t*outfile << endl;\n\t}\n}\n\n\n/////////////////////////////////////////////////////////\n// Posreporter - reports on the position of particles\n\nposreporter::posreporter()\n{\n\tobjecttype = \"posreporter\";\n\ttypes.push_back(objecttype);\n\t\n\treport_frequency = rfreq_step;\n}\n\nbool posreporter::prepareobject ( void )\n{\n\treporter::prepareobject();\n\t\n\ttparticle = getint(\"particle\", 0);\n\t\n\treturn true;\n}\nvoid posreporter::preparefile( edmexperiment &exp )\n{\n\t*outfile << \"# Position reporter: \" << exp.get(\"time\") << endl;\n\t*outfile << \"# Flight-time\\tx\\ty\\tz\\t\";\n\t*outfile << endl;\n}\n\nvoid posreporter::report( edmexperiment &exp )\n{\n\n\toutfile->precision(20);\n\tparticle &part = *(exp.particles[0]);\n\t\n\tif ((tparticle+1) > exp.particles.size())\n\t\tthrow runtime_error(\"Particle asked to track does not exist\");\n\t\n\t// Enclose this in a block for mutexing, to prevent two threads simultaneously writing out\n\t{\n\t\tstatic boost::mutex output_mutex;\n\t\tboost::mutex::scoped_lock lock(output_mutex);\n\t\t\n\t\t*outfile << part.flytime << \"\\t\" << part.position.x << \"\\t\" << part.position.y << \"\\t\" << part.position.z << endl;\n\t}\n}\n\n\n/* class alphareporter : public reporter {\nprotected:\nvoid preparefile( edmexperiment &exp );\nbool prepareobject( void );\n\npublic:\nalphareporter();\nvoid report ( edmexperiment &experiment );\n\nclass Factory : public nslobjectfactory {\n\tnslobject *create() { return new alphareporter; }\n};\t\n} */\nalphareporter::alphareporter()\n{\n\tobjecttype = \"alphareporter\";\n\ttypes.push_back(objecttype);\n\t\n\treport_frequency = rfreq_run;\n\t\n\tbouncedecay = 0;\n}\n\nvoid alphareporter::preparefile( edmexperiment &exp )\n{\n\t*outfile << \"# Alpha-visibility reporter: \" << exp.get(\"time\") << endl;\n\t*outfile << \"# \" << exp.variation.parameter << \"\\tRa\\tuncert\\talpha\\tuncert\\tvolume_dbdz\\tuncert\\tvolume_dbdzsq\\tuncert\\tActive_parts\" << endl;\n}\n\nbool alphareporter::prepareobject( void )\n{\n\treporter::prepareobject();\n\t\n\tbouncedecay = getint(\"bounce_decay\",0);\n\tcout << \"Bounce decay: \" << bouncedecay <<endl;\n\treturn true;\n}\n\nvoid alphareporter::report( edmexperiment &exp )\n{\n\tdataset frequencies;\n\t\n\t// We have two jobs - firstly calculate the Ra-1 value, and secondly to calculate the alpha value.\n\t\n\t// Calculate the alpha fringe visibility valuePhenomenology\n\tvariable alpha = calculate_visibility( exp.particles );\n\t\n\t// Calculate the volume averaged b field\n\tvariable bsample = calc_baverage(*exp.magfield, *exp.particlebox);\n\t\n\t// Now calculate the Ra-1 value\n\tvariable Ra = calculate_frequencyratio( exp.particles, bsample );\n\t\n\t// Now count the number of active particles\n\tint activep = 0;\n\tBOOST_FOREACH(particle *p, exp.particles)\n\t{\n\t\tif (p->active)\n\t\t\tactivep++;\n\t}\n\t\n\t// Now calculate the volume average fields\n\tdataset volaverage_dbdz  = calc_dbdz(*exp.magfield, *exp.particlebox);\n\tdataset volaverage_dbdz2 = calc_dbdz(*exp.magfield, *exp.particlebox, 2.0);\n\t\n\t// Mutex the output to prevent the possibility of simultaneous writes\n\t{\n\t\tstatic boost::mutex output_mutex;\n\t\tboost::mutex::scoped_lock lock(output_mutex);\n\t\t\n\t\toutfile->precision(20);\n\t\t*outfile << exp.variation.value << \"\\t\";\n\t\t*outfile << Ra.value << \"\\t\" << Ra.error << \"\\t\";\n\t\t*outfile << alpha.value << \"\\t\" << alpha.error << \"\\t\";\n\t\t*outfile << volaverage_dbdz.average() << \"\\t\" << volaverage_dbdz.uncert() << \"\\t\";\n\t\t*outfile << volaverage_dbdz2.average() << \"\\t\" << volaverage_dbdz2.uncert() << \"\\t\";\n\t\t*outfile << activep;\n\t\t*outfile << endl;\n\t\t\n\t\t// If we are 'run based' give an indication of the total alpha\n\t\tif (report_frequency == rfreq_run)\n\t\t\tlogger << \"   Calculated Alpha: \" << alpha.value << \" +- \" << alpha.error << endl;\n\t}\n\n}\n\n/// Function to calculate the alpha fringe visibility value for a set of particles.\nvariable alphareporter::calculate_visibility( vector<particle*> &particles )\n{\n\tvariable cumPup, cumPdown; // cumulative probability\n\t\n\tdataset averagefreq_plusE; // radians\n\t// Calculate the average frequencies\n\tBOOST_FOREACH(particle *p, particles)\n\t{\n\t\tif (p->active)\n\t\t\taveragefreq_plusE += p->E_sum_phase;\n\t}\n\n\tdataset bounces;\n\t\n\t// Run through every particle accumulating probabilities by calculating the projection of the frequency onto\n\t// this average\n\tBOOST_FOREACH(particle *p, particles)\n\t{\n\t\tif (p->active)\n\t\t{\n\t\t\t// Calculate the difference from the mean\n\t\t\tvariable meandiff; //Radians\n\t\t\tmeandiff.value = p->E_sum_phase - averagefreq_plusE.average();\n\t\t\tmeandiff.error = averagefreq_plusE.uncert();\n\t\t\t\n\t\t\t// calculate the projection of this onto the mean-line\n\t\t\tvariable meanaxis_projection;\n\t\t\tmeanaxis_projection.value = cos(meandiff.value);\n\t\t\tmeanaxis_projection.error = sin(meandiff.value) * meandiff.error;\n\t\t\t\n\t\t\t// Scale this to [0, 1]\n\t\t\tvariable Pup = 0.5 * (meanaxis_projection + 1.);\n\t\t\t//long double PupErr = 0.5 * (meanaxis_projectionerr + 1.);\n\t\t\t\n\t\t\tif (Pup.value < 0.)\n\t\t\t{\n\t\t\t\tcout << \"ERROR: Probability value less than zero.\" << endl;\n\t\t\t\tcout << \"\\tMeandiff:   \" << meandiff.value << endl;\n\t\t\t\tcout << \"\\tMean phase: \" << averagefreq_plusE.average() << endl;\n\t\t\t\tcout << \"\\tProjection: \" << meanaxis_projection.value << endl;\n\t\t\t\tthrow runtime_error(\"Calculated negative probability in polarization reporter\");\n\t\t\t}\n\t\t\t\n\t\t\t// Scale Pup according to the wall-interaction decay.. if it has been set\n\t\t\tlong double decayscale = 1.;\n\t\t\tif (bouncedecay > 0)\n\t\t\t{\n\t//\t\t\tcout << \"Bounces: \" << p->bounces << \", Scalefactor: \" << exp(-(long double)p->bounces / (long double)bouncedecay) << endl;\n\t\t\t\tdecayscale = exp(-(long double)p->bounces / (long double)bouncedecay);\n\t\t\t}\n\t\t\tbounces += p->bounces;\n\t\t\t\n\t\t\tcumPup += Pup * decayscale;\n\n\t\t\tcumPdown += (1. - Pup) * decayscale;\n\t\t} // if p is active\n\t}\n\t\n\t//\n\tif (bouncedecay > 0)\n\t{\n\t\tcout << \"     Average Bounces: \" << bounces.average() << \" +- \" << bounces.stdev() << endl;\n\t\tcout << \"     Average decay: \" << exp(-(long double)bounces.average() / (long double)bouncedecay) << endl;\n\t}\n\t\n\t// Calculate the value\n\tvariable alpha = (cumPup - cumPdown) / (cumPup + cumPdown);\n\t\n\treturn alpha;\n}\n\nvariable alphareporter::calculate_frequencyratio( vector<particle*> &particles, nsl::variable bsample )\n{\n\tdataset freq_ratio;\n\n\t// This B0 value should be replaced by the volume avereraged magnetic field\n\tconst long double B0 = bsample.value; // Tesla\n\t\n\t// Calculate the frequency ratio for each particle, and then average them\n\tBOOST_FOREACH(particle *p, particles)\n\t{\n\t\t// Only count active particles\n\t\tif (p->active)\n\t\t{\n\t\t\tlong double rotfreq = (p->E_sum_phase / p->flytime) / (2 * pi); // Hertz\n\t\t\t// Convert the gamma factor into hertz for our purposes\n\t\t\tlong double newgam  = fabsl(p->gamma * B0) / (2*pi); // Hertz\n\t\t\t//long double ratio = rotfreq / newgam; // Dimensionless\n\t\t\tlong double ratio = ( rotfreq - newgam ) / newgam; // dimensionless\n\t\t\t//ratio -= 1.;\n\t\t\t//long double aval = ratio - ratio2;\n\t\t\tfreq_ratio += ratio;\n\t\t} // active parts\n\t}\n\n\t// Convert this dataset into a variable and return it\n\treturn variable(freq_ratio);\n}\n\n/*\nclass bouncereporter : public reporter {\nprotected:\nvoid preparefile( edmexperiment &exp );\n//\tbool prepareobject( void );\n\npublic:\nbouncereporter();\nvoid report ( edmexperiment &experiment );\n\nclass Factory : public nslobjectfactory {\n\tnslobject *create() { return new bouncereporter; }\n};\t\n};*/\n\nbouncereporter::bouncereporter()\n{\n\tobjecttype = \"bouncereporter\";\n\ttypes.push_back(objecttype);\n\t\n\treport_frequency = rfreq_run;\n}\n\nvoid bouncereporter::preparefile( edmexperiment &exp )\n{\n\t*outfile << \"# bounce-tracking reporter: \" << exp.get(\"time\") << endl;\n\t*outfile << \"# Max_height\\tflytime\\tbounces\" << endl;\n}\n\nvoid bouncereporter::report( edmexperiment &exp )\n{\n\tBOOST_FOREACH(particle *p, exp.particles)\n\t{\n\t\t// Calculate the maximum height that this particle will reach\n\t\tlong double maxz = p->position.z + (p->velocity*p->velocity)/(2*g);\n\t\t*outfile << maxz << \"\\t\" << p->flytime << \"\\t\" << p->bounces << endl;\n\t}\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////\n////////////////////////// Group sampler reporter\n\ngroupsampler::groupsampler()\n{\n\tobjecttype = \"groupsampler\";\n\ttypes.push_back(objecttype);\n\t\n\treport_frequency = rfreq_phase;\n}\n\nvoid groupsampler::preparefile( edmexperiment &exp )\n{\n\t*outfile << \"# Group sampling reporter: \" << exp.get(\"time\") << endl;\n\t*outfile << \"# H\\tsampled_Bz_shift\\taverage_z\\tuncert\\tsampled_dbdz\\tuncert\\tsampled_dbdz2\\tuncert\" << endl;\n}\n\nvoid groupsampler::report( edmexperiment &exp )\n{\n\tcout << \"Running group sampler\" << endl;\n\n\tBOOST_FOREACH(particle *part, exp.particles) {\n\t\t// Calculate the energy group!\n\t\tlong double energygroup = 0.5 * part->velocity * part->velocity / g + part->position.z;\n\t\t/* if (exp.gravity)\n\t\t\tif (energygroup < part->sampleZ.average())\n\t\t\t\tlogger << \"ERROR: Energy group less than average z: \" << energygroup << \"< \" << part->sampleZ.average() << endl;\n\t\t*/\n\n\t\t// Dump out information\n\t\t{\n\t\t\tstatic boost::mutex output_mutex;\n\t\t\tboost::mutex::scoped_lock lock(output_mutex);\n\t\t\t\n\t\t\toutfile->precision(20);\n\t\t\t*outfile << energygroup << \"\\t\" << part->sampleBz.average()-1e-6 << \"\\t\" << part->sampleZ.average() << \"\\t\" << part->sampleZ.uncert() << \"\\t\"\n\t\t\t\t\t<< part->sampledBz.average() << \"\\t\" << part->sampledBz.uncert() << \"\\t\"\n\t\t\t\t\t<< part->sampledBz2.average() << \"\\t\" << part->sampledBz2.uncert() << endl;\n\t\t}\n\t}\n}\n/*\n class groupsampler : public reporter {\nprotected:\n\t void preparefile( edmexperiment &exp );\npublic:\n\t groupsampler();\n\t void report ( edmexperiment &experiment );\n\t \n\t class Factory : public nslobjectfactory {\n\t\t nslobject *create() { return new groupsampler; }\n\t };\t\n }\n*/ \n", "meta": {"hexsha": "887aeb8493b83b542799800af52d5d6804cf8dca", "size": 25888, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/reporters.cpp", "max_stars_repo_name": "ndevenish/nsl", "max_stars_repo_head_hexsha": "03dd69ce39258cad0547b968c062074e4b90fdf0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/reporters.cpp", "max_issues_repo_name": "ndevenish/nsl", "max_issues_repo_head_hexsha": "03dd69ce39258cad0547b968c062074e4b90fdf0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/reporters.cpp", "max_forks_repo_name": "ndevenish/nsl", "max_forks_repo_head_hexsha": "03dd69ce39258cad0547b968c062074e4b90fdf0", "max_forks_repo_licenses": ["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.8665231432, "max_line_length": 144, "alphanum_fraction": 0.6589539555, "num_tokens": 6974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2763774593150688}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*          This file is part of the program and software framework          */\n/*  CMAP-LAP --- Configurable Massively Parallel Solver for Lattice Problems */\n/*                                                                           */\n/*  Copyright Written by Nariaki Tateiwa <n-tateiwa@kyudai.jp>,              */\n/*                       Yuji Shinano <shinano@zib.de>,                      */\n/*            Copyright (C) 2021 by Zuse Institute Berlin,                   */\n/*            licensed under LGPL version 3 or later.                        */\n/*            Commercial licenses are available through <licenses@zib.de>    */\n/*                                                                           */\n/* This code is free software; you can redistribute it and/or                */\n/* modify it under the terms of the GNU Lesser 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 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 this program.  If not, see <http://www.gnu.org/licenses/>.     */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n/**@file    cmapLapParaLattice.cpp\n * @brief   Base class for Lattice.\n * @author  Nariaki Tateiwa, Yuji Shinano\n *\n *\n *\n */\n\n/*---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/\n\n\n#include \"cmapLapParaLattice.h\"\n#include <NTL/tools.h>\n#include <assert.h>\n#include <float.h>\n#include <utility>\n#include <string>\n#include <random>\n#include <fstream>\n#include \"NTL/LLL.h\"\n#include \"NTL/ZZ.h\"\n#include \"NTL/matrix.h\"\n#include <eigen3/Eigen/Core>\n#include \"cmapLapParaDef.h\"\n\n\nnamespace ParaCMapLAP\n{\n\n\n///\n/// @brief constructor\n/// @param[in] latticeBasis basis\n///\ntemplate<typename BasisFloat, typename GSFloat>\nvoid\nLattice<BasisFloat, GSFloat>::constructFromBasis(\n      LatticeBasis<BasisFloat> &latticeBasis\n      )\n{\n   n = latticeBasis.cols();\n   m = latticeBasis.rows();\n   basis = latticeBasis;\n   mu.resize(m, m);\n   B.resize(m);\n   r__.resize(m);\n   setGSO();\n   GH = projectedGH();\n   logVolume = logProjectedVolume();\n   GSOType = 0;\n   MLLLdelta = 0.99;\n}\n\n\n///\n/// @brief constructor\n/// @param[in] basisArray element of basis of RowMajor\n/// @param[in] row   number of rows of basis\n/// @param[in] col   number of columns of basis\n///\ntemplate<typename BasisFloat, typename GSFloat>\nvoid\nLattice<BasisFloat, GSFloat>::constructFromArray(\n      int *basisArray,\n      int row,\n      int col\n      )\n{\n   LatticeBasis<BasisFloat> inBasis;\n   inBasis.resize(row, col);\n   int index = 0;\n   for ( int i = 0; i < row; ++i )\n   {\n      for ( int j = 0; j < col; ++j )\n      {\n         inBasis(i, j) = basisArray[index++];\n      }\n   }\n   constructFromBasis(inBasis);\n}\n\n\n///\n/// @brief read basis from file\n/// @param[in] basisfile basis file path\n///\ntemplate<typename BasisFloat, typename GSFloat>\nvoid\nLattice<BasisFloat, GSFloat>::readFile(\n      std::string basisfile\n      )\n{\n   std::ifstream fin(basisfile);\n   if( !fin.is_open() )\n   {\n      std::cout << \"can not open input file: \" << basisfile << std::endl;\n      exit(0);\n   }\n   NTL::Mat<int> inputBasis;\n   fin >> inputBasis;\n\n   n = inputBasis.NumCols();\n   m = inputBasis.NumRows();\n\n   LatticeBasis<BasisFloat> eigenInputBasis;\n   eigenInputBasis.resize(m, n);\n   for( int row = 0; row < m; ++row )\n   {\n      for( int col = 0; col < n; ++col )\n      {\n         eigenInputBasis(row, col) = inputBasis[row][col];\n      }\n   }\n   constructFromBasis(eigenInputBasis);\n}\n\n\n///\n/// @brief Calculate GH(L') where L' is projected lattice {pi_k(b_k), ..., pi_k(b_l)}\n/// @details GH(L') = (vol(L')/nu(d))**(1/d)\n///          = exp( (log(vol(L')) - log(nu(d))) / d )\n///          where d is dimension of projected lattice (l-k+1).\n///          vol(L') = \\prod_{i=k}^{l} norm(b*i)\n/// @param[in] k index of basis\n/// @param[in] l index of basis\n///\ntemplate<typename BasisFloat, typename GSFloat>\ndouble\nLattice<BasisFloat, GSFloat>::projectedGH(\n      int k,\n      int l\n      )\n{\n   if( l < 0 ) l = m - 1;\n   int d = l-k+1;\n   long double __logProjectedVolume = logProjectedVolume(k, l);\n   long double logUnitSphereVolume = d*std::log(M_PI)*0.5 - std::log(std::tgamma(d*0.5+1.0));\n   return std::exp( (__logProjectedVolume-logUnitSphereVolume)/d );\n}\n\n\n///\n/// @brief log volume of the projected lattice L' = L({pi_k(b_k), ..., pi_k(b_l)})\n/// @return log( vol(L') ) = log( prod( norm(b*i) for k <= i <= l ) )\n///                        = sum( log( norm(b*i) for k <= i <= l ) )\n/// @param[in] k index of basis\n/// @param[in] l index of basis\n///\ntemplate<typename BasisFloat, typename GSFloat>\nlong double\nLattice<BasisFloat, GSFloat>::logProjectedVolume(\n      int k,\n      int l\n      )\n{\n   if( l < 0 ) l = m - 1;\n   long double logVolume__ = 0.0;\n   for( int i = k; i <= l; ++i ){ logVolume__ += std::log( B(i) ); };\n   return logVolume__ * 0.5;\n}\n\n\n///\n/// @brief hash of basis\n/// @retrn hash value\n///\ntemplate<typename BasisFloat, typename GSFloat>\nsize_t\nLattice<BasisFloat, GSFloat>::hash(\n   )\n{\n   size_t seed = 0;\n   for( int i = 0; i < basis.size(); ++i )\n   {\n     BasisFloat elem = *(basis.data() + i);\n     seed ^= std::hash<BasisFloat>()(elem) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n   }\n   return seed;\n}\n\n\n///\n/// @brief compute and set orthogonalised basis\n/// @return\n/// @details set mu to GSO coefficient matrix, and\n///          set B to squared norms of GSO vectors\n///\ntemplate<typename BasisFloat, typename GSFloat>\nbool\nLattice<BasisFloat, GSFloat>::setGSO(\n      int k,\n      int l\n      )\n{\n   if( l == -1 ){ l = m-1; }\n   if( GSOType == 0 )\n      return setGSO_CFA(k, l);\n   else\n      return setMGSO(k, l);\n}\n\n\n///\n/// @brief Calculate coefficients and square norm of\n///        GSO b*k,...,b*l by Cholesky decomposition\n/// @param[in] k index of basis\n/// @param[in] l index of basis\n/// @return\n///\ntemplate<typename BasisFloat, typename GSFloat>\nbool\nLattice<BasisFloat, GSFloat>::setGSO_CFA(\n      int k,\n      int l\n      )\n{\n   int i, j, jj;\n   mu.middleRows(k, l-k+1).setZero();\n   for( i = k; i <= l; ++i )\n      mu(i, i) = 1.0;\n\n   B.segment(k, l-k+1).setZero();\n   for( i = k; i <= l; ++i )\n   {\n      for( j = 0; j < i; ++j )\n      {\n         r__.coeffRef(j) = basis.row(i).dot(basis.row(j));\n         for( jj = 0; jj < j; ++jj )\n         {\n            r__.coeffRef(j) -= mu.coeff(j,jj) * r__.coeff(jj);\n         }\n         mu.coeffRef(i,j) = r__.coeff(j)/B.coeff(j);\n      }\n      B.coeffRef(i) = basis.row(i).squaredNorm();\n      for(j=1;j<=i;++j)\n      {\n         B.coeffRef(i) -= mu.coeff(i,j-1) * r__.coeff(j-1);\n      }\n   }\n   return true;\n}\n\n\n///\n/// @brief Calculate coefficients and square norm of\n///        GSO b*k,...,b*l by Modified Gram-Schmidt Orthogonalization\n/// @param[in] k index of basis\n/// @param[in] l index of basis\n/// @note r(i, j) = <bj, b*i> / norm(b*i) ( i < j )\n///       r(i, i) = norm(b*i)\n///       q.col(i) = b*_i / norm(b*i)\n///                = (bi - sum(<bi, b*j>b*j for 0 <= j <= i-1) ) / norm(b*i)\n///                = (bi - sum(r(j, i)b*j for 0 <= j <= i-1)   ) / norm(b*i)\n/// @return false if it detects error for floating else true\n///\ntemplate<typename BasisFloat, typename GSFloat>\nbool\nLattice<BasisFloat, GSFloat>::setMGSO(\n      int k,\n      int l\n      )\n{\n   int i, j;\n   q__.setZero(n, m);\n   p__.setZero(m, m);\n   mu.middleRows(k, l-k+1).setZero();\n   B.segment(k, l-k+1).setZero();\n\n   for( i = k; i <= l; ++i )\n   {\n      // q__.col(i) = basis.row(i).cast<GSFloat>();\n      for( j = 0; j < n; ++j )\n         q__.coeffRef(j, i) = basis.coeff(i, j);\n      for( j = 0; j < i; ++j )\n      {\n         p__.coeffRef(j, i) = q__.col(j).dot(q__.col(i));\n         q__.col(i) -= p__.coeff(j, i) * q__.col(j);\n      }\n      p__.coeffRef(i, i) = q__.col(i).norm();\n      q__.col(i) /= p__.coeff(i, i);\n   }\n\n   for( i = k; i <= l; ++i )\n   {\n      mu.coeffRef(i, i) = 1.0;\n      B.coeffRef(i) = p__.coeff(i, i) * p__.coeff(i, i);\n      if( B.coeffRef(i) < LDBL_EPSILON )\n      {\n         std::cout << \"Length error in MGSO\" << std::endl;\n         return false;\n      }\n      for( j = 0; j < i; ++j )\n      {\n         mu.coeffRef(i, j) = p__.coeff(j, i) / p__.coeff(j, j);\n      }\n   }\n   return true;\n}\n\n\n///\n/// @brief shortest norm\n///\ntemplate<typename BasisFloat, typename GSFloat>\ndouble\nLattice<BasisFloat, GSFloat>::shortestNorm(\n      )\n{\n   return std::sqrt(B(0));\n}\n\n\n///\n/// @brief Transform b_i so that it is close to being\n///        orthogonal to {b_0, ..., b_{m-1}} with keeping GSO vector.\n/// @param[in] eta 0.501 -- 0.51\n/// @return\n///\ntemplate<typename BasisFloat, typename GSFloat>\nbool\nLattice<BasisFloat, GSFloat>::sizeReduce(\n      double eta\n      )\n{\n   return sizeReduce(m-1, eta);\n}\n\n\n///\n/// @brief Transform b_i so that it is close to being\n///        orthogonal to {b_0, ..., b_{i-1}} with keeping GSO vector.\n/// @param[in] i 0 -- m-1\n/// @param[in] eta 0.501 -- 0.51\n/// @return\n///\ntemplate<typename BasisFloat, typename GSFloat>\nbool\nLattice<BasisFloat, GSFloat>::sizeReduce(\n      int i,\n      double eta\n      )\n{\n   int j, q, k;\n   for( j = i-1; j >= 0; j--)\n   {\n      if( std::abs(mu.coeff(i, j)) > eta )\n      {\n         q = std::round(mu.coeff(i,j));\n         mu.row(i) -= q * mu.row(j);\n         basis.row(i) -= q * basis.row(j);\n      }\n   }\n   return true;\n}\n\n\n///\n/// @brief get approximation factor\n/// @param[in] norm\n/// @param[in] k\n/// @return norm / GH\n///\ntemplate<typename BasisFloat, typename GSFloat>\ndouble\nLattice<BasisFloat, GSFloat>::approxFactor(\n      double norm,\n      int k\n      )\n{\n   assert( k >= 0 );\n   if( k == 0 )\n   {\n      if( norm < 0 ) norm = shortestNorm();\n      return norm / GH;\n   }\n   else\n   {\n      if( norm < 0 ) norm = std::sqrt(B[k]);\n      return norm / projectedGH(k, m-1);\n   }\n}\n\n\n///\n/// @brief get hermite factor\n/// @return norm / ( vol(L)^(1/m) ) = norm / exp( (1/m) log( vol(L) )\n///                                 = exp( log(norm) - (1/m)log( vol(L) ) )\n///\ntemplate<typename BasisFloat, typename GSFloat>\ndouble\nLattice<BasisFloat, GSFloat>::hermiteFactor(\n      double norm\n      )\n{\n   if( norm < 0 ) norm = shortestNorm();\n   return norm / std::exp( logVolume / m );\n}\n\n\n///\n/// @brief get root hermite factor\n/// @return ( hermiteFactor ) ^ (1/m)\n///\ntemplate<typename BasisFloat, typename GSFloat>\ndouble\nLattice<BasisFloat, GSFloat>::rootHermiteFactor(\n      double norm\n      )\n{\n   return std::pow( hermiteFactor(norm), (1.0/m) );\n}\n\n\n///\n/// @brief get logarithm of orthogonality defect\n/// @return prod( norm(bi) for 0 <= i <= m-1 ) / vol(L)\n///         = exp( sum( log(norm(bi)) for 0 <= i <= m-1) - log(vol(L)) )\n///\ntemplate<typename BasisFloat, typename GSFloat>\ndouble\nLattice<BasisFloat, GSFloat>::logOrthogonalityDefect(\n      )\n{\n   double logProdNorm = 0;\n   for( int i = 0; i < m; ++i )\n      logProdNorm += std::log( basis.row(i).squaredNorm() );\n   return logProdNorm * 0.5 - logVolume;\n}\n\n\n///\n/// @brief get enumeration cost of projceted lattice {pi_i(bi), ..., pi_i(bj)}, where i = begin, j = end\n/// @details enumCost = 1/2 * sum( H_l  for 0 <= l <= m-1 ), where\n///          H_l := nu(R, l+1) / vol(\\pi_{m-1-l}(L)),\n///          vol(\\pi_{s}(L)) := prod( norm(b*i) for s <= i <= m-1 ) and\n///          nu(R, s) is the volume of s-dimensional ball with R radius.\n/// @note log(nu(R, s)) = s log(R) + log(nu(1, s)) ( because nu(R, s) = R^{s} * nu(1, s) ) and\n///       log(vol(\\pi_{s}(L))) = sum( log(norm(b*i)) for s <= i <= m-1 ), then we have\n///       log(H_l) = (l+1) log(R) + log(nu(1, (l+1))) - sum( log(norm(b*i)) for m-1-l <= i <= m-1 )\n/// @param[in] R radius; if it is negative, then R is set to shortest norm;\n/// @param[in] begin\n/// @param[in] end\n///\ntemplate<typename BasisFloat, typename GSFloat>\nlong double\nLattice<BasisFloat, GSFloat>::enumCost(\n      double R,\n      int begin,\n      int end\n      )\n{\n   if( R < 0 ) R = std::sqrt(B(0));\n   if( end < 0 ) end = m - 1;\n   long double N = 0.0;\n   long double __logProjectedVolume = 0.0;\n   long double logSphereVolume = 0.0;\n   long double logR = std::log(R);\n   for( int i = m-1; i > m-1-begin ; --i ){ __logProjectedVolume += std::log(B(i)) * 0.5; }\n   for( int l = begin; l <= end; ++l )\n   {\n      __logProjectedVolume += std::log(B(m-l-1)) * 0.5;\n      logSphereVolume = (l+1) * logR + ( (l+1)*std::log(M_PI)*0.5 - std::log(std::tgamma((l+1)*0.5+1.0)) );\n      N += std::exp( logSphereVolume - __logProjectedVolume );\n   }\n   return N * 0.5;\n}\n\n\n///\n/// @brief slope of GSA({(i, log2(squared_norm(b*i))} for 0 <= i <= h })\n/// @param[in] h index of basis; if it is negative, h is set to m\n///\ntemplate<typename BasisFloat, typename GSFloat>\ndouble\nLattice<BasisFloat, GSFloat>::slopeGSA(\n      int h\n      )\n{\n   if( h < 0 ) h = m;\n   VectorB<GSFloat> x(h);\n   double slope = 0.0;\n   for( int i = 0; i < h; ++i ) x(i) = log2(B(i)) * 0.5;\n   for( int i = 0; i < h; ++i ) slope += (2.0*i-h+1)*x(i);\n   slope = (6.0*slope) / (h*(h-1)*(h+1));\n   return slope;\n}\n\n\n///\n/// @brief generate new lattice using basis[:h]\n/// @param[in] h index of basis\n///\ntemplate<typename BasisFloat, typename GSFloat>\nLattice<BasisFloat, GSFloat>\nLattice<BasisFloat, GSFloat>::copy(\n      int h\n      )\n{\n   if( h < 0 ) h = m - 1;\n   LatticeBasis<BasisFloat> basis__ = basis.block(0, 0, h, n);\n   Lattice <BasisFloat, GSFloat> copiedLattice{basis__};\n   return copiedLattice;\n}\n\n\n///\n/// @brief convert basis to NTL::mat_ZZ\n/// @output NTL::mat_ZZ matrix\n///\ntemplate<typename BasisFloat, typename GSFloat>\nNTL::mat_ZZ\nLattice<BasisFloat, GSFloat>::toNLTMat(\n      )\n{\n   NTL::mat_ZZ Mbasis;\n   Mbasis.SetDims(m, n);\n   for( int i = 0; i < m; i++ )\n   {\n      for( int j = 0; j < n; j++ )\n      {\n         Mbasis[i][j] = basis.coeff(i, j);\n      }\n   }\n   return Mbasis;\n}\n\n\n///\n/// @brief load basis from NTL::mat_ZZ\n///\ntemplate<typename BasisFloat, typename GSFloat>\nvoid\nLattice<BasisFloat, GSFloat>::fromNLTMat(\n      NTL::mat_ZZ &Mbasis\n      )\n{\n   // remove zero vectors\n   // row from 0 to zeroIndex are zerovectors\n   int zeroIndex = -1;\n   bool zero = true;\n   int ntlRows = Mbasis.NumRows();\n   int ntlCols = Mbasis.NumCols();\n   for( int i = 0; i < ntlRows; i++ )\n   {\n      for( int j = 0; j < ntlCols; j++ )\n         if( NTL::to_int(Mbasis[i][j]) != 0 ){ zero = false; }\n      if( zero == true )\n         zeroIndex++;\n      else\n         break; // row i is not a zero vector\n   }\n\n   // resize\n   ntlRows -= zeroIndex + 1;\n\n   // check\n   if( (ntlRows != m) || (ntlCols != n) )\n   {\n      std::cout\n         << \"invarid dimension, expected (\" << m << \", \" << n << \"),\"\n         << \"but got (\" << ntlRows << \", \" << ntlCols << \")\"\n         << std::endl;\n      exit(0);\n   }\n\n   for( int i = 0; i < m; i++ )\n   {\n      for( int j = 0; j < n; j++ )\n      {\n         basis.coeffRef(i, j)\n            = NTL::to_int(Mbasis[i+zeroIndex+1][j]);\n      }\n   }\n\n   setGSO();\n}\n\n\n///\n/// @brief resize of lattice basis\n/// @param[in] rows number of resized basis\n///\ntemplate<typename BasisFloat, typename GSFloat>\nvoid\nLattice<BasisFloat, GSFloat>::resize(\n      int rows\n      )\n{\n   assert( rows <= m );\n   if( rows == m ){ return; }\n   m = rows;\n   // error occures when directory resize by basis = basis.topRows(m)\n   LatticeBasis<BasisFloat> __basis = basis;\n   MatrixMu<GSFloat>       __mu     = mu;\n   VectorB<GSFloat>        __B      = B;\n   basis = __basis.topRows(m);\n   mu    = __mu.topLeftCorner(m, m);\n   B     = __B.head(m);\n   // GH = projectedGH();\n   // logVolume = logProjectedVolume();\n}\n\n\n///\n/// @brief randomize basis[begin:end] and execute reduction\n/// @param[in] seed        seed of unimodular randomization\n/// @param[in] begin       index of basis\n/// @param[in] end         index of basis\n///\ntemplate<typename BasisFloat, typename GSFloat>\nbool\nLattice<BasisFloat, GSFloat>::randomize(\n      int seed,\n      int begin,\n      int end\n      )\n{\n   assert( end == -1 || begin <= end );\n   if( begin == end ){ return true; }\n   if( end < 0 ) end = m - 1;\n   int u = end - begin + 1;\n\n   ///\n   /// generate unimodular matrix U\n   ///\n   LatticeBasis<BasisFloat> U(u, u);\n   U.setIdentity();\n   std::uniform_int_distribution<int> uniform{0, u-1};\n   std::mt19937 mt(seed);  ///< randomize generartor\n\n   // 1. permute rows\n   int i, a, b, nIter = 4 * u, scale = 3;\n   for( i = 0; i < nIter; ++i )\n   {\n      a = uniform(mt);\n      b = a;\n      while( b == a ){ b = uniform(mt); }\n      U.row(a).swap(U.row(b));\n   }\n\n   // 2. triangular transformation matrix with coefficnets in -1, 0, 1\n   std::uniform_int_distribution<int> flag{0, 1};\n   for( a = 0; a < u - 2; ++a )\n   {\n      std::uniform_int_distribution<int> uniform_b{a+1, u-1};\n      for( i = 0; i < scale; ++i )\n      {\n         b = uniform_b(mt);\n         if( flag(mt) ){ U.row(a) += U.row(b); }\n         else          { U.row(a) -= U.row(b); }\n      }\n   }\n\n   // unimodular conversion\n   basis.block(end-u+1,0,u,n) = U * basis.block(end-u+1,0,u,n);\n   setGSO();\n   return true;\n}\n\n\n///\n/// @brief MLLL for part of basis matrix {b_j,...,b_k-1,v,b_k,...,b_l}\n/// @param[in] v inserted vector\n/// @param[in] j index of basis\n/// @param[in] k index of basis\n/// @param[in] l index of basis\n///\ntemplate<typename BasisFloat, typename GSFloat>\nbool\nLattice<BasisFloat, GSFloat>::insertMlll(\n      LatticeVector<BasisFloat> &v,\n      int j,\n      int k,\n      int l\n      )\n{\n   int i, ii;\n   NTL::mat_ZZ Mbasis;\n   Mbasis.SetDims(l-j+2, n);\n   for( i = j; i < k; i++ )\n      for( ii = 0; ii < n; ++ii ){ Mbasis[i-j][ii] = basis(i,ii); }\n   for( ii = 0; ii < n; ++ii )   { Mbasis[k-j][ii] = v(ii); }\n   for( i = k; i <= l; i++ )\n      for( ii = 0; ii < n; ++ii ){ Mbasis[i+1-j][ii] = basis(i,ii); }\n\n   NTL::LLL_FP(Mbasis,MLLLdelta,0,0,0);\n\n   // Mbasis[0] is zero vector\n   for( i = j; i <= l; i++ )\n      for( ii = 0; ii < n; ++ii ){ basis(i,ii) = NTL::to_int(Mbasis[i+1-j][ii]); }\n\n   setGSO();\n   return true;\n}\n\n\n///\n/// @brief merge other latice\n/// @param[in] other merged lattice\n/// @remark runningTime and mergeTime are updated in this function\n///\ntemplate<typename BasisFloat, typename GSFloat>\nbool\nLattice<BasisFloat, GSFloat>::merge(\n      Lattice<BasisFloat, GSFloat> &other\n      )\n{\n   assert( n == other.n );\n   VectorB<GSFloat> preSqnorm = B;\n   LatticeVector<BasisFloat> v;\n   for( int i = 0; i < std::min(m, other.m); i++ )\n   {\n      if( basis.row(i) != other.basis.row(i) )\n      {\n         v = other.basis.row(i);\n         insertMlll(v, 0, 0, m-1);\n      }\n   }\n   if( B != preSqnorm )\n      return true;\n   else\n      return false;\n}\n\n\n///\n/// @brief compair two lattice-basis\n/// @details two basis are compared by lexicographic order of (B(0), ..., B(m-1))\n/// @param[in] other lattice\n/// @return bool of ( self <= other )\n/// @note If the number of rows of basis is different, the comparison is done according to the smaller number of rows.\n///\ntemplate<typename BasisFloat, typename GSFloat>\nbool\nLattice<BasisFloat, GSFloat>::isMoreReducedThan(\n      Lattice &other\n      )\n{\n   int h = std::min(m, other.m);\n   for( int i = 0; i < h; ++i )\n   {\n      if( B(i) < other.B(i) - 1.0 )\n      {\n         return true;\n      }\n      if( B(i) > other.B(i) )\n         return false;\n   }\n   return false;\n}\n\n\n///\n/// @brief compair two lattice-basis\n/// @details two basis are compared by lexicographic order of (B(0), ..., B(m-1))\n/// @param[in] other lattice\n/// @param[out] index minimum index {i; B(i) < C(i)} where C is other lattice basis\n/// @return bool of ( self <= other )\n/// @note If the number of rows of basis is different, the comparison is done according to the smaller number of rows.\n///\ntemplate<typename BasisFloat, typename GSFloat>\nbool\nLattice<BasisFloat, GSFloat>::isMoreReducedThan(\n      Lattice &other,\n      int &index\n      )\n{\n   int h = std::min(m, other.m);\n   for( int i = 0; i < h; ++i )\n   {\n      if( B(i) < other.B(i) - 1.0 )\n      {\n         index = i;\n         return true;\n      }\n      if( B(i) > other.B(i) )\n         return false;\n   }\n   return false;\n}\n\n\n///\n/// @brief output basis\n/// @param[in] os\n///\ntemplate<typename BasisFloat, typename GSFloat>\nvoid\nLattice<BasisFloat, GSFloat>::outputBasis(\n      std::ostream *os\n      )\n{\n   *os << toNLTMat();\n}\n\n\n///\n/// @brief write basis into textfile\n/// @param[in] filename write file path\n///\ntemplate<typename BasisFloat, typename GSFloat>\nvoid\nLattice<BasisFloat, GSFloat>::writeBasis(\n      std::string filename\n      )\n{\n   std::ofstream basefile(filename);\n   outputBasis(&basefile);\n}\n\n\n///\n/// @brief stringfy lattice\n///\ntemplate<typename BasisFloat, typename GSFloat>\nstd::string\nLattice<BasisFloat, GSFloat>::toSimpleString(\n      )\n{\n   std::ostringstream s;\n   s << std::endl\n     << \"Shortest vector      : \"\n     << basis.row(0)          << std::endl\n     << \"Shortest norm        : \"\n     << shortestNorm()        << std::endl\n     << \"Approximate factor   : \"\n     << approxFactor()        << std::endl\n     << \"Hermite factor       : \"\n     << hermiteFactor()       << std::endl\n     << \"Root Hermite factor  : \"\n     << rootHermiteFactor()   << std::endl\n     << \"Gaussian Heuristics  : \"\n     << GH                    << std::endl;\n   return s.str();\n}\n\n\n///\n/// instantiation\n///\ntemplate class Lattice<int, double>;\ntemplate class Lattice<int, long double>;\ntemplate class Lattice<long int, double>;\ntemplate class Lattice<long int, long double>;\n\n\n}  // namespace ParaCMapLAP\n", "meta": {"hexsha": "c0803da7a152d90444e6bb2053cf460fc646f02f", "size": 22309, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ug_cmaplap/cmapLapParaLattice.cpp", "max_stars_repo_name": "nariaki3551/cmaplap", "max_stars_repo_head_hexsha": "48e8d4360b751842b01dc874222451bf52abde2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ug_cmaplap/cmapLapParaLattice.cpp", "max_issues_repo_name": "nariaki3551/cmaplap", "max_issues_repo_head_hexsha": "48e8d4360b751842b01dc874222451bf52abde2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ug_cmaplap/cmapLapParaLattice.cpp", "max_forks_repo_name": "nariaki3551/cmaplap", "max_forks_repo_head_hexsha": "48e8d4360b751842b01dc874222451bf52abde2f", "max_forks_repo_licenses": ["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.5251716247, "max_line_length": 123, "alphanum_fraction": 0.5408579497, "num_tokens": 6880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961016, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.27637745216592735}}
{"text": "#ifndef DESCARTES_LIGHT_SOLVERS_BGL_IMPL_BGL_DIJKSTRA_SOLVER_HPP\n#define DESCARTES_LIGHT_SOLVERS_BGL_IMPL_BGL_DIJKSTRA_SOLVER_HPP\n\n#include <descartes_light/solvers/bgl/bgl_dijkstra_solver.h>\n\n#include <descartes_light/descartes_macros.h>\nDESCARTES_IGNORE_WARNINGS_PUSH\n#include <boost/graph/dijkstra_shortest_paths.hpp>\nDESCARTES_IGNORE_WARNINGS_POP\n\nnamespace descartes_light\n{\ntemplate <typename FloatType>\nSearchResult<FloatType> BGLDijkstraSVSESolver<FloatType>::search()\n{\n  // Convenience aliases\n  auto& graph_ = BGLSolverBase<FloatType>::graph_;\n  const auto& source_ = BGLSolverBase<FloatType>::source_;\n  auto& predecessor_map_ = BGLSolverBase<FloatType>::predecessor_map_;\n  const auto& ladder_rungs_ = BGLSolverBase<FloatType>::ladder_rungs_;\n\n  // Internal properties\n  auto index_prop_map = boost::get(boost::vertex_index, graph_);\n  auto weight_prop_map = boost::get(boost::edge_weight, graph_);\n  auto color_prop_map = boost::get(&Vertex<FloatType>::color, graph_);\n  auto distance_prop_map = boost::get(&Vertex<FloatType>::distance, graph_);\n\n  predecessor_map_.clear();\n  boost::associative_property_map<std::map<VertexDesc<FloatType>, VertexDesc<FloatType>>> predecessor_prop_map(\n      predecessor_map_);\n\n  // Perform the search\n  boost::dijkstra_shortest_paths(graph_,\n                                 source_,\n                                 predecessor_prop_map,\n                                 distance_prop_map,\n                                 weight_prop_map,\n                                 index_prop_map,\n                                 std::less<>(),\n                                 std::plus<>(),\n                                 std::numeric_limits<FloatType>::max(),\n                                 static_cast<FloatType>(0.0),\n                                 boost::default_dijkstra_visitor(),\n                                 color_prop_map);\n\n  // Find lowest cost node in last rung\n  auto target = std::min_element(ladder_rungs_.back().begin(),\n                                 ladder_rungs_.back().end(),\n                                 [&](const VertexDesc<FloatType>& a, const VertexDesc<FloatType>& b) {\n                                   return graph_[a].distance < graph_[b].distance;\n                                 });\n\n  SearchResult<FloatType> result;\n\n  // Reconstruct the path from the predecesor map; remove the artificial start state\n  const auto vd_path = BGLSolverBase<FloatType>::reconstructPath(source_, *target);\n  result.trajectory = BGLSolverBase<FloatType>::toStates(vd_path);\n  result.trajectory.erase(result.trajectory.begin());\n\n  result.cost = graph_[*target].distance;\n\n  return result;\n}\n\n/**\n * @brief Visitor for Dijkstra search that terminates the search once a vertex in the last rung has been encountered\n */\ntemplate <typename FloatType>\nclass DijkstraTerminateEarlyVisitor : public boost::default_dijkstra_visitor\n{\npublic:\n  DijkstraTerminateEarlyVisitor(long last_rung_idx) : last_rung_idx_(last_rung_idx) {}\n\n  /**\n   * @brief Hook for introspecting the search when a new vertex is opened by the search.\n   * @details Throws the vertex descriptor that is the termination of the path once the first vertex in the last rung of\n   * the graph is encountered\n   */\n  void examine_vertex(VertexDesc<FloatType> u, const BGLGraph<FloatType>& g)\n  {\n    if (g[u].rung_idx == last_rung_idx_)\n      throw u;\n  }\n\nprivate:\n  const long last_rung_idx_;\n};\n\ntemplate <typename FloatType>\nSearchResult<FloatType> BGLEfficientDijkstraSVSESolver<FloatType>::search()\n{\n  // Convenience aliases\n  auto& graph_ = BGLSolverBase<FloatType>::graph_;\n  const auto& source_ = BGLSolverBase<FloatType>::source_;\n  auto& predecessor_map_ = BGLSolverBase<FloatType>::predecessor_map_;\n  const auto& ladder_rungs_ = BGLSolverBase<FloatType>::ladder_rungs_;\n\n  // Internal properties\n  auto index_prop_map = boost::get(boost::vertex_index, graph_);\n  auto weight_prop_map = boost::get(boost::edge_weight, graph_);\n  auto color_prop_map = boost::get(&Vertex<FloatType>::color, graph_);\n  auto distance_prop_map = boost::get(&Vertex<FloatType>::distance, graph_);\n\n  predecessor_map_.clear();\n  boost::associative_property_map<std::map<VertexDesc<FloatType>, VertexDesc<FloatType>>> predecessor_prop_map(\n      predecessor_map_);\n\n  DijkstraTerminateEarlyVisitor<FloatType> visitor(static_cast<long>(ladder_rungs_.size() - 1));\n\n  // Perform the search\n  try\n  {\n    boost::dijkstra_shortest_paths(graph_,\n                                   source_,\n                                   predecessor_prop_map,\n                                   distance_prop_map,\n                                   weight_prop_map,\n                                   index_prop_map,\n                                   std::less<>(),\n                                   std::plus<>(),\n                                   std::numeric_limits<FloatType>::max(),\n                                   static_cast<FloatType>(0.0),\n                                   visitor,\n                                   color_prop_map);\n  }\n  catch (const VertexDesc<FloatType>& target)\n  {\n    SearchResult<FloatType> result;\n\n    // Reconstruct the path from the predecesor map; remove the artificial start state\n    const auto vd_path = BGLSolverBase<FloatType>::reconstructPath(source_, target);\n    result.trajectory = BGLSolverBase<FloatType>::toStates(vd_path);\n    result.trajectory.erase(result.trajectory.begin());\n\n    result.cost = graph_[target].distance;\n\n    return result;\n  }\n\n  // If the visitor never threw the vertex descriptor, there was an issue with the search\n  throw std::runtime_error(\"Search failed to encounter vertex associated with the last waypoint in the trajectory\");\n}\n\n}  // namespace descartes_light\n\n#endif  // DESCARTES_LIGHT_SOLVERS_BGL_IMPL_BGL_DIJKSTRA_SOLVER_HPP\n", "meta": {"hexsha": "a2e5920ad32464c4f60a904f70da60977890d6df", "size": 5823, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "descartes_light/solvers/include/descartes_light/solvers/bgl/impl/bgl_dijkstra_solver.hpp", "max_stars_repo_name": "DavidMerzJr/descartes_light", "max_stars_repo_head_hexsha": "be69be9f4e497041b2a05bd310dc8dfb1fe023ae", "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": "descartes_light/solvers/include/descartes_light/solvers/bgl/impl/bgl_dijkstra_solver.hpp", "max_issues_repo_name": "DavidMerzJr/descartes_light", "max_issues_repo_head_hexsha": "be69be9f4e497041b2a05bd310dc8dfb1fe023ae", "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": "descartes_light/solvers/include/descartes_light/solvers/bgl/impl/bgl_dijkstra_solver.hpp", "max_forks_repo_name": "DavidMerzJr/descartes_light", "max_forks_repo_head_hexsha": "be69be9f4e497041b2a05bd310dc8dfb1fe023ae", "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.612244898, "max_line_length": 120, "alphanum_fraction": 0.6539584407, "num_tokens": 1238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2761703679267699}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https://www.mrpt.org/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2021, Individual contributors, see AUTHORS file     |\n   | See: https://www.mrpt.org/Authors - All rights reserved.               |\n   | Released under BSD License. See: https://www.mrpt.org/License          |\n   +------------------------------------------------------------------------+ */\n\n#include \"slam-precomp.h\"  // Precompiled headers\n//\n\n// ----------------------------------------------------------------------------------------\n// For the theory behind this implementation, see the technical report in:\n//\n//            https://www.mrpt.org/6D-SLAM\n// ----------------------------------------------------------------------------------------\n\n#include <mrpt/math/ops_containers.h>\n#include <mrpt/math/utils.h>\n#include <mrpt/math/wrap2pi.h>\n#include <mrpt/obs/CActionRobotMovement3D.h>\n#include <mrpt/opengl/CEllipsoid3D.h>\n#include <mrpt/opengl/CSetOfObjects.h>\n#include <mrpt/opengl/stock_objects.h>\n#include <mrpt/poses/CPose3DQuatPDFGaussian.h>\n#include <mrpt/poses/CPosePDF.h>\n#include <mrpt/poses/CPosePDFGaussian.h>\n#include <mrpt/slam/CRangeBearingKFSLAM.h>\n#include <mrpt/system/CTicTac.h>\n#include <mrpt/system/os.h>\n\n#include <Eigen/Dense>\n\nusing namespace mrpt::slam;\nusing namespace mrpt::obs;\nusing namespace mrpt::maps;\nusing namespace mrpt::math;\nusing namespace mrpt::poses;\nusing namespace mrpt::system;\nusing namespace mrpt;\nusing namespace std;\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\t\tConstructor\n  ---------------------------------------------------------------*/\nCRangeBearingKFSLAM::CRangeBearingKFSLAM()\n\t: options(),\n\t  m_action(),\n\t  m_SF(),\n\t  m_IDs(),\n\t  mapPartitioner(),\n\t  m_SFs(),\n\t  m_lastPartitionSet()\n{\n\treset();\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\t\treset\n  ---------------------------------------------------------------*/\nvoid CRangeBearingKFSLAM::reset()\n{\n\tm_action.reset();\n\tm_SF.reset();\n\tm_IDs.clear();\n\tm_SFs.clear();\n\tmapPartitioner.clear();\n\tm_lastPartitionSet.clear();\n\n\t// -----------------------\n\t// INIT KF STATE\n\tm_xkk.assign(get_vehicle_size(), 0);  // State: 6D pose (x,y,z)=(0,0,0)\n\tm_xkk[3] = 1.0;\t // (qr,qx,qy,qz)=(1,0,0,0)\n\n\t// Initial cov:  nullptr diagonal -> perfect knowledge.\n\tm_pkk.setSize(get_vehicle_size(), get_vehicle_size());\n\tm_pkk.setZero();\n\t// -----------------------\n\n\t// Use SF-based matching (faster & easier for bearing-range observations\n\t// with ID).\n\tmapPartitioner.options.simil_method = smOBSERVATION_OVERLAP;\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\t\tDestructor\n  ---------------------------------------------------------------*/\nCRangeBearingKFSLAM::~CRangeBearingKFSLAM() = default;\n/*---------------------------------------------------------------\n\t\t\t\t\t\t\tgetCurrentRobotPose\n  ---------------------------------------------------------------*/\nvoid CRangeBearingKFSLAM::getCurrentRobotPose(\n\tCPose3DQuatPDFGaussian& out_robotPose) const\n{\n\tMRPT_START\n\n\tASSERT_(m_xkk.size() >= 7);\n\n\t// Copy xyz+quat: (explicitly unroll the loop)\n\tout_robotPose.mean.m_coords[0] = m_xkk[0];\n\tout_robotPose.mean.m_coords[1] = m_xkk[1];\n\tout_robotPose.mean.m_coords[2] = m_xkk[2];\n\tout_robotPose.mean.m_quat[0] = m_xkk[3];\n\tout_robotPose.mean.m_quat[1] = m_xkk[4];\n\tout_robotPose.mean.m_quat[2] = m_xkk[5];\n\tout_robotPose.mean.m_quat[3] = m_xkk[6];\n\n\t// and cov:\n\tout_robotPose.cov = m_pkk.blockCopy<7, 7>(0, 0);\n\n\tMRPT_END\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\t\tgetCurrentRobotPoseMean\n  ---------------------------------------------------------------*/\nmrpt::poses::CPose3DQuat CRangeBearingKFSLAM::getCurrentRobotPoseMean() const\n{\n\tCPose3DQuat q(mrpt::math::UNINITIALIZED_QUATERNION);\n\tASSERTDEB_(m_xkk.size() >= 7);\n\t// Copy xyz+quat: (explicitly unroll the loop)\n\tq.m_coords[0] = m_xkk[0];\n\tq.m_coords[1] = m_xkk[1];\n\tq.m_coords[2] = m_xkk[2];\n\tq.m_quat[0] = m_xkk[3];\n\tq.m_quat[1] = m_xkk[4];\n\tq.m_quat[2] = m_xkk[5];\n\tq.m_quat[3] = m_xkk[6];\n\n\treturn q;\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\t\tgetCurrentState\n  ---------------------------------------------------------------*/\nvoid CRangeBearingKFSLAM::getCurrentState(\n\tCPose3DQuatPDFGaussian& out_robotPose,\n\tstd::vector<TPoint3D>& out_landmarksPositions,\n\tstd::map<unsigned int, CLandmark::TLandmarkID>& out_landmarkIDs,\n\tCVectorDouble& out_fullState, CMatrixDouble& out_fullCovariance) const\n{\n\tMRPT_START\n\n\tASSERT_(size_t(m_xkk.size()) >= get_vehicle_size());\n\n\t// Copy xyz+quat: (explicitly unroll the loop)\n\tout_robotPose.mean.m_coords[0] = m_xkk[0];\n\tout_robotPose.mean.m_coords[1] = m_xkk[1];\n\tout_robotPose.mean.m_coords[2] = m_xkk[2];\n\tout_robotPose.mean.m_quat[0] = m_xkk[3];\n\tout_robotPose.mean.m_quat[1] = m_xkk[4];\n\tout_robotPose.mean.m_quat[2] = m_xkk[5];\n\tout_robotPose.mean.m_quat[3] = m_xkk[6];\n\n\t// and cov:\n\tout_robotPose.cov = m_pkk.blockCopy<7, 7>(0, 0);\n\n\t// Landmarks:\n\tASSERT_(((m_xkk.size() - get_vehicle_size()) % get_feature_size()) == 0);\n\tsize_t i, nLMs = (m_xkk.size() - get_vehicle_size()) / get_feature_size();\n\tout_landmarksPositions.resize(nLMs);\n\tfor (i = 0; i < nLMs; i++)\n\t{\n\t\tout_landmarksPositions[i].x =\n\t\t\tm_xkk[get_vehicle_size() + i * get_feature_size() + 0];\n\t\tout_landmarksPositions[i].y =\n\t\t\tm_xkk[get_vehicle_size() + i * get_feature_size() + 1];\n\t\tout_landmarksPositions[i].z =\n\t\t\tm_xkk[get_vehicle_size() + i * get_feature_size() + 2];\n\t}  // end for i\n\n\t// IDs:\n\tout_landmarkIDs = m_IDs.getInverseMap();  // m_IDs_inverse;\n\n\t// Full state:\n\tout_fullState.resize(m_xkk.size());\n\tstd::copy(m_xkk.begin(), m_xkk.end(), out_fullState.begin());\n\t// Full cov:\n\tout_fullCovariance = m_pkk;\n\n\tMRPT_END\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\tprocessActionObservation\n  ---------------------------------------------------------------*/\nvoid CRangeBearingKFSLAM::processActionObservation(\n\tCActionCollection::Ptr& action, CSensoryFrame::Ptr& SF)\n{\n\tMRPT_START\n\n\tm_action = action;\n\tm_SF = SF;\n\n\t// Sanity check:\n\tASSERT_(\n\t\tm_IDs.size() ==\n\t\t(m_pkk.cols() - get_vehicle_size()) / get_feature_size());\n\n\t// ===================================================================================================================\n\t// Here's the meat!: Call the main method for the KF algorithm, which will\n\t// call all the callback methods as required:\n\t// ===================================================================================================================\n\trunOneKalmanIteration();\n\n\t// =============================================================\n\t//  ADD TO SFs SEQUENCE\n\t// =============================================================\n\tCPose3DQuatPDFGaussian q(UNINITIALIZED_QUATERNION);\n\tthis->getCurrentRobotPose(q);\n\tCPose3DPDFGaussian::Ptr auxPosePDF = CPose3DPDFGaussian::Create(q);\n\n\tif (options.create_simplemap)\n\t{ m_SFs.insert(CPose3DPDF::Ptr(auxPosePDF), SF); }\n\n\t// =============================================================\n\t//  UPDATE THE PARTITION GRAPH EXPERIMENT\n\t// =============================================================\n\tif (options.doPartitioningExperiment)\n\t{\n\t\tif (options.partitioningMethod == 0)\n\t\t{\n\t\t\t// Use spectral-graph technique:\n\t\t\tmapPartitioner.addMapFrame(*SF, *auxPosePDF);\n\n\t\t\tvector<std::vector<uint32_t>> partitions;\n\t\t\tmapPartitioner.updatePartitions(partitions);\n\t\t\tm_lastPartitionSet = partitions;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Fixed partitions every K observations:\n\t\t\tvector<std::vector<uint32_t>> partitions;\n\t\t\tstd::vector<uint32_t> tmpCluster;\n\n\t\t\tASSERT_(options.partitioningMethod > 1);\n\t\t\tsize_t N = options.partitioningMethod;\n\n\t\t\tfor (size_t i = 0; i < m_SFs.size(); i++)\n\t\t\t{\n\t\t\t\ttmpCluster.push_back(i);\n\t\t\t\tif ((i % N) == 0)\n\t\t\t\t{\n\t\t\t\t\tpartitions.push_back(tmpCluster);\n\t\t\t\t\ttmpCluster.clear();\n\t\t\t\t\ttmpCluster.push_back(i);  // This observation \"i\" is shared\n\t\t\t\t\t// between both clusters\n\t\t\t\t}\n\t\t\t}\n\t\t\tm_lastPartitionSet = partitions;\n\t\t}\n\n\t\tprintf(\n\t\t\t\"Partitions: %u\\n\",\n\t\t\tstatic_cast<unsigned>(m_lastPartitionSet.size()));\n\t}\n\n\tMRPT_END\n}\n\n/** Return the last odometry, as a pose increment.\n */\nCPose3DQuat CRangeBearingKFSLAM::getIncrementFromOdometry() const\n{\n\tCActionRobotMovement2D::Ptr actMov2D =\n\t\tm_action->getBestMovementEstimation();\n\tCActionRobotMovement3D::Ptr actMov3D =\n\t\tm_action->getActionByClass<CActionRobotMovement3D>();\n\tif (actMov3D && !options.force_ignore_odometry)\n\t{ return CPose3DQuat(actMov3D->poseChange.mean); }\n\telse if (actMov2D && !options.force_ignore_odometry)\n\t{\n\t\tCPose2D estMovMean;\n\t\tactMov2D->poseChange->getMean(estMovMean);\n\t\treturn CPose3DQuat(CPose3D(estMovMean));\n\t}\n\telse\n\t{\n\t\treturn CPose3DQuat();\n\t}\n}\n\n/** Must return the action vector u.\n * \\param out_u The action vector which will be passed to OnTransitionModel\n */\nvoid CRangeBearingKFSLAM::OnGetAction(KFArray_ACT& u) const\n{\n\t// Get odometry estimation:\n\tconst CPose3DQuat theIncr = getIncrementFromOdometry();\n\n\tfor (KFArray_ACT::Index i = 0;\n\t\t i < static_cast<KFArray_ACT::Index>(u.size()); i++)\n\t\tu[i] = theIncr[i];\n}\n\n/** This virtual function musts implement the prediction model of the Kalman\n * filter.\n */\nvoid CRangeBearingKFSLAM::OnTransitionModel(\n\tconst KFArray_ACT& u, KFArray_VEH& xv, bool& out_skipPrediction) const\n{\n\tMRPT_START\n\n\t// Do not update the vehicle pose & its covariance until we have some\n\t// landmarks in the map,\n\t// otherwise, we are imposing a lower bound to the best uncertainty from now\n\t// on:\n\tif (size_t(m_xkk.size()) == get_vehicle_size())\n\t{ out_skipPrediction = true; }\n\n\t// Current pose: copy xyz+quat\n\tCPose3DQuat robotPose = getCurrentRobotPoseMean();\n\n\t// Increment pose: copy xyz+quat (explicitly unroll the loop)\n\tCPose3DQuat odoIncrement(UNINITIALIZED_QUATERNION);\n\todoIncrement.m_coords[0] = u[0];\n\todoIncrement.m_coords[1] = u[1];\n\todoIncrement.m_coords[2] = u[2];\n\todoIncrement.m_quat[0] = u[3];\n\todoIncrement.m_quat[1] = u[4];\n\todoIncrement.m_quat[2] = u[5];\n\todoIncrement.m_quat[3] = u[6];\n\n\t// Pose composition:\n\trobotPose += odoIncrement;\n\n\t// Output:\n\tfor (size_t i = 0; i < xv.SizeAtCompileTime; i++)\n\t\txv[i] = robotPose[i];\n\n\tMRPT_END\n}\n\n/** This virtual function musts calculate the Jacobian F of the prediction\n * model.\n */\nvoid CRangeBearingKFSLAM::OnTransitionJacobian(KFMatrix_VxV& F) const\n{\n\tMRPT_START\n\n\t// Current pose: copy xyz+quat\n\tCPose3DQuat robotPose = getCurrentRobotPoseMean();\n\n\t// Odometry:\n\tconst CPose3DQuat theIncr = getIncrementFromOdometry();\n\n\t// Compute jacobians:\n\tCMatrixDouble77 df_du(UNINITIALIZED_MATRIX);\n\n\tCPose3DQuatPDF::jacobiansPoseComposition(\n\t\trobotPose,\t// x\n\t\ttheIncr,  // u\n\t\tF,\t// df_dx,\n\t\tdf_du);\n\n\tMRPT_END\n}\n\n/** This virtual function musts calculate de noise matrix of the prediction\n * model.\n */\nvoid CRangeBearingKFSLAM::OnTransitionNoise(KFMatrix_VxV& Q) const\n{\n\tMRPT_START\n\n\t// The uncertainty of the 2D odometry, projected from the current position:\n\tCActionRobotMovement2D::Ptr act2D = m_action->getBestMovementEstimation();\n\tCActionRobotMovement3D::Ptr act3D =\n\t\tm_action->getActionByClass<CActionRobotMovement3D>();\n\n\tif (act3D && act2D)\n\t\tTHROW_EXCEPTION(\"Both 2D & 3D odometry are present!?!?\");\n\n\tCPose3DQuatPDFGaussian odoIncr;\n\n\tif ((!act3D && !act2D) || options.force_ignore_odometry)\n\t{\n\t\t// Use constant Q:\n\t\tQ.setZero();\n\t\tASSERT_(size_t(options.stds_Q_no_odo.size()) == size_t(Q.cols()));\n\t\tfor (size_t i = 0; i < get_vehicle_size(); i++)\n\t\t\tQ(i, i) = square(options.stds_Q_no_odo[i]);\n\t\treturn;\n\t}\n\telse\n\t{\n\t\tif (act2D)\n\t\t{\n\t\t\t// 2D odometry:\n\t\t\tCPosePDFGaussian odoIncr2D;\n\t\t\todoIncr2D.copyFrom(*act2D->poseChange);\n\t\t\todoIncr = CPose3DQuatPDFGaussian(CPose3DPDFGaussian(odoIncr2D));\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// 3D odometry:\n\t\t\todoIncr = CPose3DQuatPDFGaussian(act3D->poseChange);\n\t\t}\n\t}\n\n\todoIncr.cov(2, 2) += square(options.std_odo_z_additional);\n\n\t// Current pose: copy xyz+quat\n\tCPose3DQuat robotPose = getCurrentRobotPoseMean();\n\n\t// Transform from odometry increment to \"relative to the robot\":\n\todoIncr.changeCoordinatesReference(robotPose);\n\n\tQ = odoIncr.cov;\n\n\tMRPT_END\n}\n\nvoid CRangeBearingKFSLAM::OnObservationModel(\n\tconst std::vector<size_t>& idx_landmarks_to_predict,\n\tvector_KFArray_OBS& out_predictions) const\n{\n\tMRPT_START\n\n\t// Mean of the prior of the robot pose:\n\tCPose3DQuat robotPose = getCurrentRobotPoseMean();\n\n\t// Get the sensor pose relative to the robot:\n\tCObservationBearingRange::Ptr obs =\n\t\tm_SF->getObservationByClass<CObservationBearingRange>();\n\tASSERTMSG_(\n\t\tobs,\n\t\t\"*ERROR*: This method requires an observation of type \"\n\t\t\"CObservationBearingRange\");\n\tconst CPose3DQuat sensorPoseOnRobot =\n\t\tCPose3DQuat(obs->sensorLocationOnRobot);\n\n\t/* -------------------------------------------\n\t   Equations, obtained using matlab, of the relative 3D position of a\n\t  landmark (xi,yi,zi), relative\n\t\t  to a robot 6D pose (x0,y0,z0,y,p,r)\n\t\tRefer to technical report \"6D EKF derivation...\", 2008\n\n\t\tx0 y0 z0 y p r         % Robot's 6D pose\n\t\tx0s y0s z0s ys ps rs   % Sensor's 6D pose relative to robot\n\t\txi yi zi % Absolute 3D landmark coordinates:\n\n\t\tHx : dh_dxv   -> Jacobian of the observation model wrt the robot pose\n\t\tHy : dh_dyi   -> Jacobian of the observation model wrt each landmark\n\t  mean position\n\n\t\tSizes:\n\t\t h:  Lx3\n\t\t Hx: 3Lx6\n\t\t Hy: 3Lx3\n\n\t\t  L=# of landmarks in the map (ALL OF THEM)\n\t  ------------------------------------------- */\n\n\tconst size_t vehicle_size = get_vehicle_size();\n\t// const size_t  obs_size  = get_observation_size();\n\tconst size_t feature_size = get_feature_size();\n\n\tconst CPose3DQuat sensorPoseAbs = robotPose + sensorPoseOnRobot;\n\n\tconst size_t N = idx_landmarks_to_predict.size();\n\tout_predictions.resize(N);\n\tfor (size_t i = 0; i < N; i++)\n\t{\n\t\tconst size_t row_in = feature_size * idx_landmarks_to_predict[i];\n\n\t\t// Landmark absolute 3D position in the map:\n\t\tconst TPoint3D mapEst(\n\t\t\tm_xkk[vehicle_size + row_in + 0], m_xkk[vehicle_size + row_in + 1],\n\t\t\tm_xkk[vehicle_size + row_in + 2]);\n\n\t\t// Generate Range, yaw, pitch\n\t\t// ---------------------------------------------------\n\t\tsensorPoseAbs.sphericalCoordinates(\n\t\t\tmapEst,\n\t\t\tout_predictions[i][0],\t// range\n\t\t\tout_predictions[i][1],\t// yaw\n\t\t\tout_predictions[i][2]  // pitch\n\t\t);\n\t}\n\n\tMRPT_END\n}\n\nvoid CRangeBearingKFSLAM::OnObservationJacobians(\n\tsize_t idx_landmark_to_predict, KFMatrix_OxV& Hx, KFMatrix_OxF& Hy) const\n{\n\tMRPT_START\n\n\t// Mean of the prior of the robot pose:\n\tconst CPose3DQuat robotPose = getCurrentRobotPoseMean();\n\n\t// Get the sensor pose relative to the robot:\n\tCObservationBearingRange::Ptr obs =\n\t\tm_SF->getObservationByClass<CObservationBearingRange>();\n\tASSERTMSG_(\n\t\tobs,\n\t\t\"*ERROR*: This method requires an observation of type \"\n\t\t\"CObservationBearingRange\");\n\tconst CPose3DQuat sensorPoseOnRobot =\n\t\tCPose3DQuat(obs->sensorLocationOnRobot);\n\n\tconst size_t vehicle_size = get_vehicle_size();\n\t// const size_t  obs_size  = get_observation_size();\n\tconst size_t feature_size = get_feature_size();\n\n\t// Compute the jacobians, needed below:\n\t// const CPose3DQuat  sensorPoseAbs= robotPose + sensorPoseOnRobot;\n\tCPose3DQuat sensorPoseAbs(UNINITIALIZED_QUATERNION);\n\tCMatrixFixed<kftype, 7, 7> H_senpose_vehpose(UNINITIALIZED_MATRIX);\n\tCMatrixFixed<kftype, 7, 7> H_senpose_senrelpose(\n\t\tUNINITIALIZED_MATRIX);\t// Not actually used\n\n\tCPose3DQuatPDF::jacobiansPoseComposition(\n\t\trobotPose, sensorPoseOnRobot, H_senpose_vehpose, H_senpose_senrelpose,\n\t\t&sensorPoseAbs);\n\n\tconst size_t row_in = feature_size * idx_landmark_to_predict;\n\n\t// Landmark absolute 3D position in the map:\n\tconst TPoint3D mapEst(\n\t\tm_xkk[vehicle_size + row_in + 0], m_xkk[vehicle_size + row_in + 1],\n\t\tm_xkk[vehicle_size + row_in + 2]);\n\n\t// The Jacobian wrt the sensor pose must be transformed later on:\n\tKFMatrix_OxV Hx_sensor;\n\tdouble obsData[3];\n\tsensorPoseAbs.sphericalCoordinates(\n\t\tmapEst,\n\t\tobsData[0],\t // range\n\t\tobsData[1],\t // yaw\n\t\tobsData[2],\t // pitch\n\t\t&Hy, &Hx_sensor);\n\n\t// Chain rule: Hx = d sensorpose / d vehiclepose   * Hx_sensor\n\tHx = Hx_sensor * H_senpose_vehpose;\n\n\tMRPT_END\n}\n\n/** This is called between the KF prediction step and the update step, and the\n * application must return the observations and, when applicable, the data\n * association between these observations and the current map.\n *\n * \\param out_z N vectors, each for one \"observation\" of length OBS_SIZE, N\n * being the number of \"observations\": how many observed landmarks for a map, or\n * just one if not applicable.\n * \\param out_data_association An empty vector or, where applicable, a vector\n * where the i'th element corresponds to the position of the observation in the\n * i'th row of out_z within the system state vector (in the range\n * [0,getNumberOfLandmarksInTheMap()-1]), or -1 if it is a new map element and\n * we want to insert it at the end of this KF iteration.\n * \\param in_S The full covariance matrix of the observation predictions (i.e.\n * the \"innovation covariance matrix\"). This is a M·O x M·O matrix with M=length\n * of \"in_lm_indices_in_S\".\n * \\param in_lm_indices_in_S The indices of the map landmarks (range\n * [0,getNumberOfLandmarksInTheMap()-1]) that can be found in the matrix in_S.\n *\n *  This method will be called just once for each complete KF iteration.\n * \\note It is assumed that the observations are independent, i.e. there are NO\n * cross-covariances between them.\n */\nvoid CRangeBearingKFSLAM::OnGetObservationsAndDataAssociation(\n\tvector_KFArray_OBS& Z, std::vector<int>& data_association,\n\tconst vector_KFArray_OBS& all_predictions, const KFMatrix& S,\n\tconst std::vector<size_t>& lm_indices_in_S, const KFMatrix_OxO& R)\n{\n\tMRPT_START\n\n\t// static const size_t vehicle_size = get_vehicle_size();\n\tconstexpr size_t obs_size = get_observation_size();\n\n\t// Z: Observations\n\tCObservationBearingRange::TMeasurementList::const_iterator itObs;\n\n\tCObservationBearingRange::Ptr obs =\n\t\tm_SF->getObservationByClass<CObservationBearingRange>();\n\tASSERTMSG_(\n\t\tobs,\n\t\t\"*ERROR*: This method requires an observation of type \"\n\t\t\"CObservationBearingRange\");\n\n\tconst size_t N = obs->sensedData.size();\n\tZ.resize(N);\n\n\tsize_t row;\n\tfor (row = 0, itObs = obs->sensedData.begin();\n\t\t itObs != obs->sensedData.end(); ++itObs, ++row)\n\t{\n\t\t// Fill one row in Z:\n\t\tZ[row][0] = itObs->range;\n\t\tZ[row][1] = itObs->yaw;\n\t\tZ[row][2] = itObs->pitch;\n\t}\n\n\t// Data association:\n\t// ---------------------\n\tdata_association.assign(N, -1);\t // Initially, all new landmarks\n\n\t// For each observed LM:\n\tstd::vector<size_t> obs_idxs_needing_data_assoc;\n\tobs_idxs_needing_data_assoc.reserve(N);\n\n\t{\n\t\tstd::vector<int>::iterator itDA;\n\t\tfor (row = 0, itObs = obs->sensedData.begin(),\n\t\t\titDA = data_association.begin();\n\t\t\t itObs != obs->sensedData.end(); ++itObs, ++itDA, ++row)\n\t\t{\n\t\t\t// Fill data asociation: Using IDs!\n\t\t\tif (itObs->landmarkID < 0)\n\t\t\t\tobs_idxs_needing_data_assoc.push_back(row);\n\t\t\telse\n\t\t\t{\n\t\t\t\tmrpt::containers::bimap<\n\t\t\t\t\tCLandmark::TLandmarkID, unsigned int>::iterator itID;\n\t\t\t\tif ((itID = m_IDs.find_key(itObs->landmarkID)) != m_IDs.end())\n\t\t\t\t\t*itDA = itID->second;  // This row in Z corresponds to the\n\t\t\t\t// i'th map element in the state\n\t\t\t\t// vector:\n\t\t\t}\n\t\t}\n\t}\n\n\t// ---- Perform data association ----\n\t//  Only for observation indices in \"obs_idxs_needing_data_assoc\"\n\tif (obs_idxs_needing_data_assoc.empty())\n\t{\n\t\t// We don't need to do DA:\n\t\tm_last_data_association = TDataAssocInfo();\n\n\t\t// Save them for the case the external user wants to access them:\n\t\tfor (size_t idxObs = 0; idxObs < data_association.size(); idxObs++)\n\t\t{\n\t\t\tint da = data_association[idxObs];\n\t\t\tif (da >= 0)\n\t\t\t\tm_last_data_association.results.associations[idxObs] =\n\t\t\t\t\tdata_association[idxObs];\n\t\t}\n\t}\n\telse\n\t{\n\t\t// Build a Z matrix with the observations that need dat.assoc:\n\t\tconst size_t nObsDA = obs_idxs_needing_data_assoc.size();\n\n\t\tCMatrixDynamic<kftype> Z_obs_means(nObsDA, obs_size);\n\t\tfor (size_t i = 0; i < nObsDA; i++)\n\t\t{\n\t\t\tconst size_t idx = obs_idxs_needing_data_assoc[i];\n\t\t\tfor (unsigned k = 0; k < obs_size; k++)\n\t\t\t\tZ_obs_means(i, k) = Z[idx][k];\n\t\t}\n\n\t\t// Vehicle uncertainty\n\t\t// KFMatrix_VxV Pxx = m_pkk.extractMatrix<7, 7>(0, 0);\n\n\t\t// Build predictions:\n\t\t// ---------------------------\n\t\tconst size_t nPredictions = lm_indices_in_S.size();\n\t\tm_last_data_association.clear();\n\n\t\t// S is the covariance of the predictions:\n\t\tm_last_data_association.Y_pred_covs = S;\n\n\t\t// The means:\n\t\tm_last_data_association.Y_pred_means.setSize(nPredictions, obs_size);\n\t\tfor (size_t q = 0; q < nPredictions; q++)\n\t\t{\n\t\t\tconst size_t i = lm_indices_in_S[q];\n\t\t\tfor (size_t w = 0; w < obs_size; w++)\n\t\t\t\tm_last_data_association.Y_pred_means(q, w) =\n\t\t\t\t\tall_predictions[i][w];\n\t\t\tm_last_data_association.predictions_IDs.push_back(\n\t\t\t\ti);\t // for the conversion of indices...\n\t\t}\n\n\t\t// Do Dat. Assoc :\n\t\t// ---------------------------\n\t\tif (nPredictions)\n\t\t{\n\t\t\t// CMatrixDouble Z_obs_cov = CMatrixDouble(R);\n\n\t\t\tmrpt::slam::data_association_full_covariance(\n\t\t\t\tZ_obs_means, m_last_data_association.Y_pred_means,\n\t\t\t\tm_last_data_association.Y_pred_covs,\n\t\t\t\tm_last_data_association.results, options.data_assoc_method,\n\t\t\t\toptions.data_assoc_metric, options.data_assoc_IC_chi2_thres,\n\t\t\t\ttrue,  // Use KD-tree\n\t\t\t\tm_last_data_association.predictions_IDs,\n\t\t\t\toptions.data_assoc_IC_metric,\n\t\t\t\toptions.data_assoc_IC_ml_threshold);\n\n\t\t\t// Return pairings to the main KF algorithm:\n\t\t\tfor (auto it = m_last_data_association.results.associations.begin();\n\t\t\t\t it != m_last_data_association.results.associations.end(); ++it)\n\t\t\t\tdata_association[it->first] = it->second;\n\t\t}\n\t}\n\t// ---- End of data association ----\n\n\tMRPT_END\n}\n\n/** This virtual function musts normalize the state vector and covariance matrix\n * (only if its necessary).\n */\nvoid CRangeBearingKFSLAM::OnNormalizeStateVector()\n{\n\tMRPT_START\n\n\t// m_xkk[3:6] must be a normalized quaternion:\n\tconst double T = std::sqrt(\n\t\tsquare(m_xkk[3]) + square(m_xkk[4]) + square(m_xkk[5]) +\n\t\tsquare(m_xkk[6]));\n\tASSERTMSG_(T > 0, \"Vehicle pose quaternion norm is not >0!!\");\n\n\tconst double T_ = (m_xkk[3] < 0 ? -1.0 : 1.0) / T;\t// qr>=0\n\tm_xkk[3] *= T_;\n\tm_xkk[4] *= T_;\n\tm_xkk[5] *= T_;\n\tm_xkk[6] *= T_;\n\n\tMRPT_END\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\tloadOptions\n  ---------------------------------------------------------------*/\nvoid CRangeBearingKFSLAM::loadOptions(const mrpt::config::CConfigFileBase& ini)\n{\n\t// Main\n\toptions.loadFromConfigFile(ini, \"RangeBearingKFSLAM\");\n\tKF_options.loadFromConfigFile(ini, \"RangeBearingKFSLAM_KalmanFilter\");\n\t// partition algorithm:\n\tmapPartitioner.options.loadFromConfigFile(ini, \"RangeBearingKFSLAM\");\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\tloadOptions\n  ---------------------------------------------------------------*/\nvoid CRangeBearingKFSLAM::TOptions::loadFromConfigFile(\n\tconst mrpt::config::CConfigFileBase& source, const std::string& section)\n{\n\tsource.read_vector(section, \"stds_Q_no_odo\", stds_Q_no_odo, stds_Q_no_odo);\n\tASSERT_(stds_Q_no_odo.size() == 7);\n\tstd_sensor_range =\n\t\tsource.read_float(section, \"std_sensor_range\", std_sensor_range);\n\tstd_sensor_yaw = DEG2RAD(source.read_float(\n\t\tsection, \"std_sensor_yaw_deg\", RAD2DEG(std_sensor_yaw)));\n\tstd_sensor_pitch = DEG2RAD(source.read_float(\n\t\tsection, \"std_sensor_pitch_deg\", RAD2DEG(std_sensor_pitch)));\n\n\tstd_odo_z_additional = source.read_float(\n\t\tsection, \"std_odo_z_additional\", std_odo_z_additional);\n\n\tMRPT_LOAD_CONFIG_VAR(doPartitioningExperiment, bool, source, section);\n\tMRPT_LOAD_CONFIG_VAR(partitioningMethod, int, source, section);\n\n\tMRPT_LOAD_CONFIG_VAR(create_simplemap, bool, source, section);\n\n\tMRPT_LOAD_CONFIG_VAR(force_ignore_odometry, bool, source, section);\n\n\tdata_assoc_method = source.read_enum<TDataAssociationMethod>(\n\t\tsection, \"data_assoc_method\", data_assoc_method);\n\tdata_assoc_metric = source.read_enum<TDataAssociationMetric>(\n\t\tsection, \"data_assoc_metric\", data_assoc_metric);\n\tdata_assoc_IC_metric = source.read_enum<TDataAssociationMetric>(\n\t\tsection, \"data_assoc_IC_metric\", data_assoc_IC_metric);\n\n\tMRPT_LOAD_CONFIG_VAR(data_assoc_IC_chi2_thres, double, source, section);\n\tMRPT_LOAD_CONFIG_VAR(data_assoc_IC_ml_threshold, double, source, section);\n\n\tMRPT_LOAD_CONFIG_VAR(quantiles_3D_representation, float, source, section);\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\tConstructor\n  ---------------------------------------------------------------*/\nCRangeBearingKFSLAM::TOptions::TOptions()\n\t: stds_Q_no_odo(get_vehicle_size(), 0),\n\n\t  std_sensor_yaw(DEG2RAD(0.2f)),\n\t  std_sensor_pitch(DEG2RAD(0.2f))\n\n{\n\tstds_Q_no_odo[0] = stds_Q_no_odo[1] = stds_Q_no_odo[2] = 0.10f;\n\tstds_Q_no_odo[3] = stds_Q_no_odo[4] = stds_Q_no_odo[5] = stds_Q_no_odo[6] =\n\t\t0.05f;\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\tdumpToTextStream\n  ---------------------------------------------------------------*/\nvoid CRangeBearingKFSLAM::TOptions::dumpToTextStream(std::ostream& out) const\n{\n\tusing namespace mrpt::typemeta;\n\n\tout << \"\\n----------- [CRangeBearingKFSLAM::TOptions] ------------ \\n\\n\";\n\n\tout << mrpt::format(\n\t\t\"doPartitioningExperiment                = %c\\n\",\n\t\tdoPartitioningExperiment ? 'Y' : 'N');\n\tout << mrpt::format(\n\t\t\"partitioningMethod                      = %i\\n\", partitioningMethod);\n\tout << mrpt::format(\n\t\t\"data_assoc_method                       = %s\\n\",\n\t\tTEnumType<TDataAssociationMethod>::value2name(data_assoc_method)\n\t\t\t.c_str());\n\tout << mrpt::format(\n\t\t\"data_assoc_metric                       = %s\\n\",\n\t\tTEnumType<TDataAssociationMetric>::value2name(data_assoc_metric)\n\t\t\t.c_str());\n\tout << mrpt::format(\n\t\t\"data_assoc_IC_chi2_thres                = %.06f\\n\",\n\t\tdata_assoc_IC_chi2_thres);\n\tout << mrpt::format(\n\t\t\"data_assoc_IC_metric                    = %s\\n\",\n\t\tTEnumType<TDataAssociationMetric>::value2name(data_assoc_IC_metric)\n\t\t\t.c_str());\n\tout << mrpt::format(\n\t\t\"data_assoc_IC_ml_threshold              = %.06f\\n\",\n\t\tdata_assoc_IC_ml_threshold);\n\n\tout << \"\\n\";\n}\n\nvoid CRangeBearingKFSLAM::OnInverseObservationModel(\n\tconst KFArray_OBS& in_z, KFArray_FEAT& yn, KFMatrix_FxV& dyn_dxv,\n\tKFMatrix_FxO& dyn_dhn) const\n{\n\tMRPT_START\n\n\tCObservationBearingRange::Ptr obs =\n\t\tm_SF->getObservationByClass<CObservationBearingRange>();\n\tASSERTMSG_(\n\t\tobs,\n\t\t\"*ERROR*: This method requires an observation of type \"\n\t\t\"CObservationBearingRange\");\n\tconst CPose3DQuat sensorPoseOnRobot =\n\t\tCPose3DQuat(obs->sensorLocationOnRobot);\n\n\t// Mean of the prior of the robot pose:\n\tconst CPose3DQuat robotPose = getCurrentRobotPoseMean();\n\n\t// const CPose3DQuat  sensorPoseAbs= robotPose + sensorPoseOnRobot;\n\tCPose3DQuat sensorPoseAbs(UNINITIALIZED_QUATERNION);\n\tCMatrixFixed<kftype, 7, 7> dsensorabs_dvehpose(UNINITIALIZED_MATRIX);\n\tCMatrixFixed<kftype, 7, 7> dsensorabs_dsenrelpose(\n\t\tUNINITIALIZED_MATRIX);\t// Not actually used\n\n\tCPose3DQuatPDF::jacobiansPoseComposition(\n\t\trobotPose, sensorPoseOnRobot, dsensorabs_dvehpose,\n\t\tdsensorabs_dsenrelpose, &sensorPoseAbs);\n\n\tkftype hn_r = in_z[0];\n\tkftype hn_y = in_z[1];\n\tkftype hn_p = in_z[2];\n\n\tkftype chn_y = cos(hn_y);\n\tkftype shn_y = sin(hn_y);\n\tkftype chn_p = cos(hn_p);\n\tkftype shn_p = sin(hn_p);\n\n\t/* -------------------------------------------\n\t\tsyms H h_range h_yaw h_pitch real;\n\t\tH=[ h_range ; h_yaw ; h_pitch ];\n\n\t\tsyms X xi_ yi_ zi_ real;\n\t\txi_ = h_range * cos(h_yaw) * cos(h_pitch);\n\t\tyi_ = h_range * sin(h_yaw) * cos(h_pitch);\n\t\tzi_ = -h_range * sin(h_pitch);\n\n\t\tX=[xi_ yi_ zi_];\n\t\tjacob_inv_mod=jacobian(X,H)\n\t  ------------------------------------------- */\n\n\t// The new point, relative to the sensor:\n\tconst TPoint3D yn_rel_sensor(\n\t\thn_r * chn_y * chn_p, hn_r * shn_y * chn_p, -hn_r * shn_p);\n\n\t// The Jacobian of the 3D point in the coordinate system of the sensor:\n\t/*\n\t\t[ cos(h_pitch)*cos(h_yaw), -h_range*cos(h_pitch)*sin(h_yaw),\n\t   -h_range*cos(h_yaw)*sin(h_pitch)]\n\t\t[ cos(h_pitch)*sin(h_yaw),  h_range*cos(h_pitch)*cos(h_yaw),\n\t   -h_range*sin(h_pitch)*sin(h_yaw)]\n\t\t[           -sin(h_pitch),                                0,\n\t   -h_range*cos(h_pitch)]\n\t*/\n\tconst kftype values_dynlocal_dhn[] = {\n\t\tchn_p * chn_y,\n\t\t-hn_r * chn_p * shn_y,\n\t\t-hn_r * chn_y * shn_p,\n\t\tchn_p * shn_y,\n\t\thn_r * chn_p * chn_y,\n\t\t-hn_r * shn_p * shn_y,\n\t\t-shn_p,\n\t\t0,\n\t\t-hn_r * chn_p};\n\tconst KFMatrix_FxO dynlocal_dhn(values_dynlocal_dhn);\n\n\tKFMatrix_FxF jacob_dyn_dynrelsensor(UNINITIALIZED_MATRIX);\n\tKFMatrix_FxV jacob_dyn_dsensorabs(UNINITIALIZED_MATRIX);\n\n\tsensorPoseAbs.composePoint(\n\t\tyn_rel_sensor.x, yn_rel_sensor.y,\n\t\tyn_rel_sensor.z,  // yn rel. to the sensor\n\t\tyn[0], yn[1], yn[2],  // yn in global coords\n\t\t&jacob_dyn_dynrelsensor, &jacob_dyn_dsensorabs);\n\n\tdyn_dhn = jacob_dyn_dynrelsensor * dynlocal_dhn;\n\n\t// dyn_dxv =\n\tdyn_dxv = jacob_dyn_dsensorabs * dsensorabs_dvehpose;\n\n\tMRPT_END\n}\n\n/** If applicable to the given problem, do here any special handling of adding a\n * new landmark to the map.\n * \\param in_obsIndex The index of the observation whose inverse sensor is to\n * be computed. It corresponds to the row in in_z where the observation can be\n * found.\n * \\param in_idxNewFeat The index that this new feature will have in the state\n * vector (0:just after the vehicle state, 1: after that,...). Save this number\n * so data association can be done according to these indices.\n * \\sa OnInverseObservationModel\n */\nvoid CRangeBearingKFSLAM::OnNewLandmarkAddedToMap(\n\tconst size_t in_obsIdx, const size_t in_idxNewFeat)\n{\n\tMRPT_START\n\n\tCObservationBearingRange::Ptr obs =\n\t\tm_SF->getObservationByClass<CObservationBearingRange>();\n\tASSERTMSG_(\n\t\tobs,\n\t\t\"*ERROR*: This method requires an observation of type \"\n\t\t\"CObservationBearingRange\");\n\n\t// ----------------------------------------------\n\t// introduce in the lists of ID<->index in map:\n\t// ----------------------------------------------\n\tASSERT_(in_obsIdx < obs->sensedData.size());\n\tif (obs->sensedData[in_obsIdx].landmarkID >= 0)\n\t{\n\t\t// The sensor provides us a LM ID... use it:\n\t\tm_IDs.insert(obs->sensedData[in_obsIdx].landmarkID, in_idxNewFeat);\n\t}\n\telse\n\t{\n\t\t// Features do not have IDs... use indices:\n\t\tm_IDs.insert(in_idxNewFeat, in_idxNewFeat);\n\t}\n\n\tMRPT_END\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\tgetAs3DObject\n  ---------------------------------------------------------------*/\nvoid CRangeBearingKFSLAM::getAs3DObject(\n\tmrpt::opengl::CSetOfObjects::Ptr& outObj) const\n{\n\toutObj->clear();\n\n\t// ------------------------------------------------\n\t//  Add the XYZ corner for the current area:\n\t// ------------------------------------------------\n\toutObj->insert(opengl::stock_objects::CornerXYZ());\n\n\t// 3D ellipsoid for robot pose:\n\tCPointPDFGaussian pointGauss;\n\tpointGauss.mean.x(m_xkk[0]);\n\tpointGauss.mean.y(m_xkk[1]);\n\tpointGauss.mean.z(m_xkk[2]);\n\tpointGauss.cov = m_pkk.blockCopy<3, 3>(0, 0);\n\n\t{\n\t\tauto ellip = opengl::CEllipsoid3D::Create();\n\n\t\tellip->setPose(pointGauss.mean);\n\t\tellip->setCovMatrix(pointGauss.cov);\n\t\tellip->enableDrawSolid3D(false);\n\t\tellip->setQuantiles(options.quantiles_3D_representation);\n\t\tellip->set3DsegmentsCount(10);\n\t\tellip->setColor(1, 0, 0);\n\n\t\toutObj->insert(ellip);\n\t}\n\n\t// 3D ellipsoids for landmarks:\n\tconst size_t nLMs = this->getNumberOfLandmarksInTheMap();\n\tfor (size_t i = 0; i < nLMs; i++)\n\t{\n\t\tpointGauss.mean.x(\n\t\t\tm_xkk[get_vehicle_size() + get_feature_size() * i + 0]);\n\t\tpointGauss.mean.y(\n\t\t\tm_xkk[get_vehicle_size() + get_feature_size() * i + 1]);\n\t\tpointGauss.mean.z(\n\t\t\tm_xkk[get_vehicle_size() + get_feature_size() * i + 2]);\n\n\t\tpointGauss.cov =\n\t\t\tm_pkk.blockCopy<get_feature_size(), get_feature_size()>(\n\t\t\t\tget_vehicle_size() + get_feature_size() * i,\n\t\t\t\tget_vehicle_size() + get_feature_size() * i);\n\n\t\tauto ellip = opengl::CEllipsoid3D::Create();\n\n\t\tellip->setName(format(\"%u\", static_cast<unsigned int>(i)));\n\t\tellip->enableShowName(true);\n\t\tellip->setPose(pointGauss.mean);\n\t\tellip->setCovMatrix(pointGauss.cov);\n\t\tellip->enableDrawSolid3D(false);\n\t\tellip->setQuantiles(options.quantiles_3D_representation);\n\t\tellip->set3DsegmentsCount(10);\n\n\t\tellip->setColor(0, 0, 1);\n\n\t\t// Set color depending on partitions?\n\t\tif (options.doPartitioningExperiment)\n\t\t{\n\t\t\t// This is done for each landmark:\n\t\t\tmap<int, bool> belongToPartition;\n\t\t\tconst CSimpleMap* SFs =\n\t\t\t\t&m_SFs;\t // mapPartitioner.getSequenceOfFrames();\n\n\t\t\tfor (size_t p = 0; p < m_lastPartitionSet.size(); p++)\n\t\t\t{\n\t\t\t\tfor (size_t w = 0; w < m_lastPartitionSet[p].size(); w++)\n\t\t\t\t{\n\t\t\t\t\t// Check if landmark #i is in the SF of\n\t\t\t\t\t// m_lastPartitionSet[p][w]:\n\t\t\t\t\tCLandmark::TLandmarkID i_th_ID = m_IDs.inverse(i);\n\n\t\t\t\t\t// Look for the lm_ID in the SF:\n\t\t\t\t\tCPose3DPDF::Ptr pdf;\n\t\t\t\t\tCSensoryFrame::Ptr SF_i;\n\t\t\t\t\tSFs->get(m_lastPartitionSet[p][w], pdf, SF_i);\n\n\t\t\t\t\tCObservationBearingRange::Ptr obs =\n\t\t\t\t\t\tSF_i->getObservationByClass<CObservationBearingRange>();\n\n\t\t\t\t\tfor (auto& o : obs->sensedData)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (o.landmarkID == i_th_ID)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbelongToPartition[p] = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}  // end for o\n\t\t\t\t}  // end for w\n\t\t\t}  // end for p\n\n\t\t\t// Build label:\n\t\t\tstring strParts(\"[\");\n\n\t\t\tfor (auto it = belongToPartition.begin();\n\t\t\t\t it != belongToPartition.end(); ++it)\n\t\t\t{\n\t\t\t\tif (it != belongToPartition.begin()) strParts += string(\",\");\n\t\t\t\tstrParts += format(\"%i\", it->first);\n\t\t\t}\n\n\t\t\tellip->setName(ellip->getName() + strParts + string(\"]\"));\n\t\t}\n\n\t\toutObj->insert(ellip);\n\t}\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\tgetLastPartitionLandmarks\n  ---------------------------------------------------------------*/\nvoid CRangeBearingKFSLAM::getLastPartitionLandmarksAsIfFixedSubmaps(\n\tsize_t K, std::vector<std::vector<uint32_t>>& landmarksMembership)\n{\n\t// temporary copy:\n\tstd::vector<std::vector<uint32_t>> tmpParts = m_lastPartitionSet;\n\n\t// Fake \"m_lastPartitionSet\":\n\n\t// Fixed partitions every K observations:\n\tvector<std::vector<uint32_t>> partitions;\n\tstd::vector<uint32_t> tmpCluster;\n\n\tfor (size_t i = 0; i < m_SFs.size(); i++)\n\t{\n\t\ttmpCluster.push_back(i);\n\t\tif ((i % K) == 0)\n\t\t{\n\t\t\tpartitions.push_back(tmpCluster);\n\t\t\ttmpCluster.clear();\n\t\t\ttmpCluster.push_back(\n\t\t\t\ti);\t // This observation \"i\" is shared between both clusters\n\t\t}\n\t}\n\tm_lastPartitionSet = partitions;\n\n\t// Call the actual method:\n\tgetLastPartitionLandmarks(landmarksMembership);\n\n\t// Replace copy:\n\tm_lastPartitionSet = tmpParts;\t//-V519\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\tgetLastPartitionLandmarks\n  ---------------------------------------------------------------*/\nvoid CRangeBearingKFSLAM::getLastPartitionLandmarks(\n\tstd::vector<std::vector<uint32_t>>& landmarksMembership) const\n{\n\tlandmarksMembership.clear();\n\n\t// All the computation is made based on \"m_lastPartitionSet\"\n\n\tif (!options.doPartitioningExperiment) return;\n\n\tconst size_t nLMs = this->getNumberOfLandmarksInTheMap();\n\tfor (size_t i = 0; i < nLMs; i++)\n\t{\n\t\tmap<int, bool> belongToPartition;\n\t\tconst CSimpleMap* SFs =\n\t\t\t&m_SFs;\t // mapPartitioner.getSequenceOfFrames();\n\n\t\tfor (size_t p = 0; p < m_lastPartitionSet.size(); p++)\n\t\t{\n\t\t\tfor (size_t w = 0; w < m_lastPartitionSet[p].size(); w++)\n\t\t\t{\n\t\t\t\t// Check if landmark #i is in the SF of\n\t\t\t\t// m_lastPartitionSet[p][w]:\n\t\t\t\tCLandmark::TLandmarkID i_th_ID = m_IDs.inverse(i);\n\n\t\t\t\t// Look for the lm_ID in the SF:\n\t\t\t\tCPose3DPDF::Ptr pdf;\n\t\t\t\tCSensoryFrame::Ptr SF_i;\n\t\t\t\tSFs->get(m_lastPartitionSet[p][w], pdf, SF_i);\n\n\t\t\t\tCObservationBearingRange::Ptr obs =\n\t\t\t\t\tSF_i->getObservationByClass<CObservationBearingRange>();\n\n\t\t\t\tfor (auto& o : obs->sensedData)\n\t\t\t\t{\n\t\t\t\t\tif (o.landmarkID == i_th_ID)\n\t\t\t\t\t{\n\t\t\t\t\t\tbelongToPartition[p] = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}  // end for o\n\t\t\t}  // end for w\n\t\t}  // end for p\n\n\t\t// Build membership list:\n\t\tstd::vector<uint32_t> membershipOfThisLM;\n\n\t\tfor (auto& it : belongToPartition)\n\t\t\tmembershipOfThisLM.push_back(it.first);\n\n\t\tlandmarksMembership.push_back(membershipOfThisLM);\n\t}  // end for i\n}\n\n/*---------------------------------------------------------------\n\t\t\tcomputeOffDiagonalBlocksApproximationError\n  ---------------------------------------------------------------*/\ndouble CRangeBearingKFSLAM::computeOffDiagonalBlocksApproximationError(\n\tconst std::vector<std::vector<uint32_t>>& landmarksMembership) const\n{\n\tMRPT_START\n\n\t// Compute the information matrix:\n\tCMatrixDynamic<kftype> fullCov(m_pkk);\n\tsize_t i;\n\tfor (i = 0; i < get_vehicle_size(); i++)\n\t\tfullCov(i, i) = max(fullCov(i, i), 1e-6);\n\n\tCMatrixDynamic<kftype> H(fullCov.inverse_LLt());\n\tH.array().abs();  // Replace by absolute values:\n\n\tdouble sumOffBlocks = 0;\n\tunsigned int nLMs = landmarksMembership.size();\n\n\tASSERT_(\n\t\tint(get_vehicle_size() + nLMs * get_feature_size()) == fullCov.cols());\n\n\tfor (i = 0; i < nLMs; i++)\n\t{\n\t\tfor (size_t j = i + 1; j < nLMs; j++)\n\t\t{\n\t\t\t// Sum the cross cov. between LM(i) and LM(j)??\n\t\t\t// --> Only if there is no common cluster:\n\t\t\tif (0 ==\n\t\t\t\tmath::countCommonElements(\n\t\t\t\t\tlandmarksMembership[i], landmarksMembership[j]))\n\t\t\t{\n\t\t\t\tsize_t col = get_vehicle_size() + i * get_feature_size();\n\t\t\t\tsize_t row = get_vehicle_size() + j * get_feature_size();\n\t\t\t\tsumOffBlocks += 2 * H.block<2, 2>(row, col).sum();\n\t\t\t}\n\t\t}\n\t}\n\n\treturn sumOffBlocks /\n\t\tH.asEigen()\n\t\t\t.block(\n\t\t\t\tget_vehicle_size(), get_vehicle_size(),\n\t\t\t\tH.rows() - get_vehicle_size(),\n\t\t\t\tH.cols() - get_vehicle_size())\n\t\t\t.sum();\t // Starting (7,7)-end\n\tMRPT_END\n}\n\n/*---------------------------------------------------------------\n\t\t\t  reconsiderPartitionsNow\n  ---------------------------------------------------------------*/\nvoid CRangeBearingKFSLAM::reconsiderPartitionsNow()\n{\n\t// A different buffer for making this\n\t// thread-safe some day...\n\tvector<std::vector<uint32_t>> partitions;\n\tmapPartitioner.updatePartitions(partitions);\n\tm_lastPartitionSet = partitions;\n}\n\n/*---------------------------------------------------------------\n\t\t\t  saveMapAndPathRepresentationAsMATLABFile\n  ---------------------------------------------------------------*/\nvoid CRangeBearingKFSLAM::saveMapAndPath2DRepresentationAsMATLABFile(\n\tconst string& fil, float stdCount, const string& styleLandmarks,\n\tconst string& stylePath, const string& styleRobot) const\n{\n\tFILE* f = os::fopen(fil.c_str(), \"wt\");\n\tif (!f) return;\n\n\tCMatrixDouble cov(2, 2);\n\tCVectorDouble mean(2);\n\n\t// Header:\n\tos::fprintf(\n\t\tf,\n\t\t\"%%--------------------------------------------------------------------\"\n\t\t\"\\n\");\n\tos::fprintf(f, \"%% File automatically generated using the MRPT method:\\n\");\n\tos::fprintf(\n\t\tf,\n\t\t\"%% \"\n\t\t\"'CRangeBearingKFSLAM::saveMapAndPath2DRepresentationAsMATLABFile'\\n\");\n\tos::fprintf(f, \"%%\\n\");\n\tos::fprintf(f, \"%%                        ~ MRPT ~\\n\");\n\tos::fprintf(\n\t\tf, \"%%  Jose Luis Blanco Claraco, University of Malaga @ 2008\\n\");\n\tos::fprintf(f, \"%%      https://www.mrpt.org/     \\n\");\n\tos::fprintf(\n\t\tf,\n\t\t\"%%--------------------------------------------------------------------\"\n\t\t\"\\n\");\n\n\t// Main code:\n\tos::fprintf(f, \"hold on;\\n\\n\");\n\n\tconst size_t nLMs = this->getNumberOfLandmarksInTheMap();\n\n\tfor (size_t i = 0; i < nLMs; i++)\n\t{\n\t\tsize_t idx = get_vehicle_size() + i * get_feature_size();\n\n\t\tcov(0, 0) = m_pkk(idx + 0, idx + 0);\n\t\tcov(1, 1) = m_pkk(idx + 1, idx + 1);\n\t\tcov(0, 1) = cov(1, 0) = m_pkk(idx + 0, idx + 1);\n\n\t\tmean[0] = m_xkk[idx + 0];\n\t\tmean[1] = m_xkk[idx + 1];\n\n\t\t// Command to draw the 2D ellipse:\n\t\tos::fprintf(\n\t\t\tf, \"%s\",\n\t\t\tmath::MATLAB_plotCovariance2D(cov, mean, stdCount, styleLandmarks)\n\t\t\t\t.c_str());\n\t}\n\n\t// Now: the robot path:\n\t// ------------------------------\n\tif (m_SFs.size())\n\t{\n\t\tos::fprintf(f, \"\\nROB_PATH=[\");\n\t\tfor (size_t i = 0; i < m_SFs.size(); i++)\n\t\t{\n\t\t\tCSensoryFrame::Ptr dummySF;\n\t\t\tCPose3DPDF::Ptr pdf3D;\n\t\t\tm_SFs.get(i, pdf3D, dummySF);\n\n\t\t\tCPose3D p;\n\t\t\tpdf3D->getMean(p);\n\n\t\t\tos::fprintf(f, \"%.04f %.04f\", p.x(), p.y());\n\t\t\tif (i < (m_SFs.size() - 1)) os::fprintf(f, \";\");\n\t\t}\n\t\tos::fprintf(f, \"];\\n\");\n\n\t\tos::fprintf(\n\t\t\tf, \"plot(ROB_PATH(:,1),ROB_PATH(:,2),'%s');\\n\", stylePath.c_str());\n\t}\n\n\t// The robot pose:\n\tcov(0, 0) = m_pkk(0, 0);\n\tcov(1, 1) = m_pkk(1, 1);\n\tcov(0, 1) = cov(1, 0) = m_pkk(0, 1);\n\n\tmean[0] = m_xkk[0];\n\tmean[1] = m_xkk[1];\n\n\tos::fprintf(\n\t\tf, \"%s\",\n\t\tmath::MATLAB_plotCovariance2D(cov, mean, stdCount, styleRobot).c_str());\n\n\tos::fprintf(f, \"\\naxis equal;\\n\");\n\tos::fclose(f);\n}\n\n/** Computes A=A-B, which may need to be re-implemented depending on the\n * topology of the individual scalar components (eg, angles).\n */\nvoid CRangeBearingKFSLAM::OnSubstractObservationVectors(\n\tKFArray_OBS& A, const KFArray_OBS& B) const\n{\n\tA -= B;\n\tmrpt::math::wrapToPiInPlace(A[1]);\n\tmrpt::math::wrapToPiInPlace(A[2]);\n}\n\n/** Return the observation NOISE covariance matrix, that is, the model of the\n * Gaussian additive noise of the sensor.\n * \\param out_R The noise covariance matrix. It might be non diagonal, but\n * it'll usually be.\n */\nvoid CRangeBearingKFSLAM::OnGetObservationNoise(KFMatrix_OxO& out_R) const\n{\n\tout_R(0, 0) = square(options.std_sensor_range);\n\tout_R(1, 1) = square(options.std_sensor_yaw);\n\tout_R(2, 2) = square(options.std_sensor_pitch);\n}\n\n/** This will be called before OnGetObservationsAndDataAssociation to allow the\n * application to reduce the number of covariance landmark predictions to be\n * made.\n *  For example, features which are known to be \"out of sight\" shouldn't be\n * added to the output list to speed up the calculations.\n * \\param in_all_prediction_means The mean of each landmark predictions; the\n * computation or not of the corresponding covariances is what we're trying to\n * determined with this method.\n * \\param out_LM_indices_to_predict The list of landmark indices in the map\n * [0,getNumberOfLandmarksInTheMap()-1] that should be predicted.\n * \\note This is not a pure virtual method, so it should be implemented only if\n * desired. The default implementation returns a vector with all the landmarks\n * in the map.\n * \\sa OnGetObservations, OnDataAssociation\n */\nvoid CRangeBearingKFSLAM::OnPreComputingPredictions(\n\tconst vector_KFArray_OBS& prediction_means,\n\tstd::vector<size_t>& out_LM_indices_to_predict) const\n{\n\tCObservationBearingRange::Ptr obs =\n\t\tm_SF->getObservationByClass<CObservationBearingRange>();\n\tASSERTMSG_(\n\t\tobs,\n\t\t\"*ERROR*: This method requires an observation of type \"\n\t\t\"CObservationBearingRange\");\n\n#define USE_HEURISTIC_PREDICTION\n\n#ifdef USE_HEURISTIC_PREDICTION\n\tconst double sensor_max_range = obs->maxSensorDistance;\n\tconst double fov_yaw = obs->fieldOfView_yaw;\n\tconst double fov_pitch = obs->fieldOfView_pitch;\n\n\tconst double max_vehicle_loc_uncertainty =\n\t\t4 * std::sqrt(m_pkk(0, 0) + m_pkk(1, 1) + m_pkk(2, 2));\n#endif\n\n\tout_LM_indices_to_predict.clear();\n\tfor (size_t i = 0; i < prediction_means.size(); i++)\n\t{\n#ifndef USE_HEURISTIC_PREDICTION\n\t\tout_LM_indices_to_predict.push_back(i);\n#else\n\t\t// Heuristic: faster but doesn't work always!\n\t\tif (prediction_means[i][0] <\n\t\t\t\t(15 + sensor_max_range + max_vehicle_loc_uncertainty +\n\t\t\t\t 4 * options.std_sensor_range) &&\n\t\t\tfabs(prediction_means[i][1]) <\n\t\t\t\t(30.0_deg + 0.5 * fov_yaw + 4 * options.std_sensor_yaw) &&\n\t\t\tfabs(prediction_means[i][2]) <\n\t\t\t\t(30.0_deg + 0.5 * fov_pitch + 4 * options.std_sensor_pitch))\n\t\t{ out_LM_indices_to_predict.push_back(i); }\n#endif\n\t}\n}\n", "meta": {"hexsha": "3bfaec828cf9192bac726993db5550f03fe13a83", "size": 43332, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/slam/src/slam/CRangeBearingKFSLAM.cpp", "max_stars_repo_name": "SupraBitKid/mrpt", "max_stars_repo_head_hexsha": "f0647dba071864bf5d83a28a3653126537f6a407", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-01T15:43:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-01T15:43:00.000Z", "max_issues_repo_path": "libs/slam/src/slam/CRangeBearingKFSLAM.cpp", "max_issues_repo_name": "SupraBitKid/mrpt", "max_issues_repo_head_hexsha": "f0647dba071864bf5d83a28a3653126537f6a407", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-11-30T19:51:29.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-01T08:15:36.000Z", "max_forks_repo_path": "libs/slam/src/slam/CRangeBearingKFSLAM.cpp", "max_forks_repo_name": "SupraBitKid/mrpt", "max_forks_repo_head_hexsha": "f0647dba071864bf5d83a28a3653126537f6a407", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-01-12T02:08:10.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-14T23:05:10.000Z", "avg_line_length": 30.9735525375, "max_line_length": 119, "alphanum_fraction": 0.6412812702, "num_tokens": 12385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982043529716, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.27617036212916346}}
{"text": "// Copyright (c) Facebook, Inc. and its affiliates.\n\n// This source code is licensed under the MIT license found in the\n// LICENSE file in the root directory of this source tree.\n#include <fstream>\n#include <string>\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n#include <torch/script.h>\n#include <torch/torch.h>\n\n#include \"dtt.h\"\n#include \"pinocchio_wrapper.hpp\"\n#include \"rotations.hpp\"\n\nextern \"C\" {\n\ntorch::Tensor validTensor(torch::Tensor x) {\n  if (x.dim() < 2) {\n    x = x.unsqueeze(1);\n  }\n  return x.to(torch::kDouble);\n}\n\nEigen::VectorXd matrixToVector(Eigen::MatrixXd A) {\n  return Eigen::VectorXd(\n      Eigen::Map<Eigen::VectorXd>(A.data(), A.cols() * A.rows()));\n}\n\nstruct RobotModelPinocchio : torch::CustomClassHolder {\n  Eigen::VectorXd ik_sol_p_;\n  Eigen::VectorXd ik_sol_v_;\n\n  pinocchio_wrapper::State *pinocchio_state_ = nullptr;\n\n  std::string xml_buffer_;\n  std::string ee_link_name_;\n\n  RobotModelPinocchio(std::string urdf_filename, std::string ee_link_name) {\n    ee_link_name_ = ee_link_name;\n\n    std::ifstream stream(urdf_filename);\n    std::stringstream buffer;\n    buffer << stream.rdbuf();\n    xml_buffer_ = buffer.str();\n\n    initialize();\n  }\n\n  RobotModelPinocchio(std::vector<std::string> serialized_state) {\n    ee_link_name_ = serialized_state[0];\n    xml_buffer_ = serialized_state[1];\n    initialize();\n  }\n\n  ~RobotModelPinocchio() { pinocchio_wrapper::destroy(pinocchio_state_); }\n\n  void initialize() {\n    pinocchio_state_ = pinocchio_wrapper::initialize(ee_link_name_.c_str(),\n                                                     xml_buffer_.c_str());\n  }\n\n  c10::List<torch::Tensor> get_joint_angle_limits(void) {\n    c10::List<torch::Tensor> result;\n    int nq = pinocchio_wrapper::get_nq(pinocchio_state_);\n    torch::Tensor l_result = torch::zeros(nq, torch::kFloat32);\n    torch::Tensor u_result = torch::zeros(nq, torch::kFloat32);\n\n    auto lower_limit =\n        pinocchio_wrapper::get_lower_position_limits(pinocchio_state_);\n    auto upper_limit =\n        pinocchio_wrapper::get_upper_position_limits(pinocchio_state_);\n\n    for (int i = 0; i < nq; i++) {\n      l_result[i] = lower_limit[i];\n      u_result[i] = upper_limit[i];\n    }\n    result.push_back(l_result);\n    result.push_back(u_result);\n\n    return result;\n  }\n\n  torch::Tensor get_joint_velocity_limits(void) {\n    int nq = pinocchio_wrapper::get_nq(pinocchio_state_);\n    torch::Tensor result = torch::zeros(nq, torch::kFloat32);\n    auto velocity_limit =\n        pinocchio_wrapper::get_velocity_limits(pinocchio_state_);\n\n    for (int i = 0; i < nq; i++) {\n      result[i] = velocity_limit[i];\n    }\n\n    return result;\n  }\n\n  c10::List<torch::Tensor> forward_kinematics(torch::Tensor joint_positions) {\n    c10::List<torch::Tensor> result;\n    torch::Tensor pos_result = torch::zeros(3, torch::kFloat32);\n    torch::Tensor quat_result = torch::zeros(4, torch::kFloat32);\n\n    joint_positions = validTensor(joint_positions);\n    auto result_intermediate = pinocchio_wrapper::forward_kinematics(\n        pinocchio_state_,\n        matrixToVector(dtt::libtorch2eigen<double>(joint_positions)));\n\n    for (int i = 0; i < 3; i++) {\n      pos_result[i] = result_intermediate[i];\n    }\n    for (int i = 0; i < 4; i++) {\n      quat_result[i] = result_intermediate[i + 3];\n    }\n\n    result.push_back(pos_result);\n    result.push_back(quat_result);\n\n    return result;\n  }\n\n  torch::Tensor compute_jacobian(torch::Tensor joint_positions) {\n    int nq = pinocchio_wrapper::get_nq(pinocchio_state_);\n    joint_positions = validTensor(joint_positions);\n\n    torch::Tensor result = torch::zeros({6, nq}, torch::kFloat64);\n    Eigen::Map<dtt::MatrixXrm<double>> J(result.data_ptr<double>(),\n                                         result.size(0), result.size(1));\n    pinocchio_wrapper::compute_jacobian(\n        pinocchio_state_,\n        matrixToVector(dtt::libtorch2eigen<double>(joint_positions)), J);\n\n    return result;\n  }\n\n  torch::Tensor inverse_dynamics(torch::Tensor joint_positions,\n                                 torch::Tensor joint_velocities,\n                                 torch::Tensor joint_accelerations) {\n    joint_positions = validTensor(joint_positions);\n    joint_velocities = validTensor(joint_velocities);\n    joint_accelerations = validTensor(joint_accelerations);\n    auto q = matrixToVector(dtt::libtorch2eigen<double>(joint_positions));\n    auto v = matrixToVector(dtt::libtorch2eigen<double>(joint_velocities));\n    auto a = matrixToVector(dtt::libtorch2eigen<double>(joint_accelerations));\n\n    Eigen::Matrix<double, Eigen::Dynamic, 1> tau =\n        pinocchio_wrapper::inverse_dynamics(pinocchio_state_, q, v, a);\n    std::vector<int64_t> dims = {tau.rows()};\n    return torch::from_blob(tau.data(), dims, torch::kFloat64).clone();\n  }\n\n  torch::Tensor inverse_kinematics(torch::Tensor ee_pos, torch::Tensor ee_quat,\n                                   torch::Tensor rest_pose, double eps = 1e-4,\n                                   int64_t max_iters = 1000, double dt = 0.1,\n                                   double damping = 1e-12) {\n    ee_pos = validTensor(ee_pos);\n    Eigen::Vector3d ee_pos_(\n        Eigen::Map<Eigen::Vector3d>(ee_pos.data_ptr<double>(), 3));\n\n    auto quat = tensor4ToQuat(ee_quat);\n    auto ee_quat_ = Eigen::Quaterniond(quat).cast<double>();\n\n    rest_pose = validTensor(rest_pose);\n    ik_sol_p_ = matrixToVector(dtt::libtorch2eigen<double>(rest_pose));\n\n    pinocchio_wrapper::inverse_kinematics(pinocchio_state_, ee_pos_, ee_quat_,\n                                          ik_sol_p_, eps, max_iters, dt,\n                                          damping);\n    std::vector<int64_t> dims = {ik_sol_p_.rows()};\n    return torch::from_blob(ik_sol_p_.data(), dims, torch::kFloat64).clone();\n  }\n};\n\nTORCH_LIBRARY(torchscript_pinocchio, m) {\n  m.class_<RobotModelPinocchio>(\"RobotModelPinocchio\")\n      .def(torch::init<std::string, std::string>())\n      .def(\"get_joint_angle_limits\",\n           &RobotModelPinocchio::get_joint_angle_limits)\n      .def(\"get_joint_velocity_limits\",\n           &RobotModelPinocchio::get_joint_velocity_limits)\n      .def(\"forward_kinematics\", &RobotModelPinocchio::forward_kinematics)\n      .def(\"compute_jacobian\", &RobotModelPinocchio::compute_jacobian)\n      .def(\"inverse_dynamics\", &RobotModelPinocchio::inverse_dynamics)\n      .def(\"inverse_kinematics\", &RobotModelPinocchio::inverse_kinematics)\n      .def_pickle(\n          // __getstate__\n          [](const c10::intrusive_ptr<RobotModelPinocchio> &self)\n              -> std::vector<std::string> {\n            return std::vector<std::string>{self->ee_link_name_,\n                                            self->xml_buffer_};\n          },\n          // __setstate__\n          [](std::vector<std::string> state)\n              -> c10::intrusive_ptr<RobotModelPinocchio> {\n            return c10::make_intrusive<RobotModelPinocchio>(std::move(state));\n          });\n}\n\n} /* extern \"C\" */\n", "meta": {"hexsha": "17aad605688991509150cd55a5cd1c114ee96c2a", "size": 6946, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "polymetis/polymetis/torch_isolation/src/pinocchio.cpp", "max_stars_repo_name": "p-g-krish/droidlet", "max_stars_repo_head_hexsha": "dd4dd335d0c15b64dbf860ce31b5bdced4719da7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "polymetis/polymetis/torch_isolation/src/pinocchio.cpp", "max_issues_repo_name": "p-g-krish/droidlet", "max_issues_repo_head_hexsha": "dd4dd335d0c15b64dbf860ce31b5bdced4719da7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "polymetis/polymetis/torch_isolation/src/pinocchio.cpp", "max_forks_repo_name": "p-g-krish/droidlet", "max_forks_repo_head_hexsha": "dd4dd335d0c15b64dbf860ce31b5bdced4719da7", "max_forks_repo_licenses": ["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.73, "max_line_length": 79, "alphanum_fraction": 0.6549093003, "num_tokens": 1768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.2760780728050361}}
{"text": "/*\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 *\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 Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\n * The Original Code is Copyright (C) 2015 Blender Foundation.\n * All rights reserved.\n */\n\n#ifndef __EIGEN3_SVD_C_API_CC__\n#define __EIGEN3_SVD_C_API_CC__\n\n/* Eigen gives annoying huge amount of warnings here, silence them! */\n#if defined(__GNUC__) && !defined(__clang__)\n#  pragma GCC diagnostic ignored \"-Wlogical-op\"\n#endif\n\n#ifdef __EIGEN3_SVD_C_API_CC__ /* quiet warning */\n#endif\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n\n#include \"svd.h\"\n\nusing Eigen::JacobiSVD;\n\nusing Eigen::NoQRPreconditioner;\n\nusing Eigen::ComputeThinU;\nusing Eigen::ComputeThinV;\n\nusing Eigen::Map;\nusing Eigen::MatrixXf;\nusing Eigen::VectorXf;\n\nusing Eigen::Matrix4f;\n\nvoid EIG_svd_square_matrix(const int size, const float *matrix, float *r_U, float *r_S, float *r_V)\n{\n  /* Since our matrix is squared, we can use thinU/V. */\n  unsigned int flags = (r_U ? ComputeThinU : 0) | (r_V ? ComputeThinV : 0);\n\n  /* Blender and Eigen matrices are both column-major. */\n  JacobiSVD<MatrixXf, NoQRPreconditioner> svd(Map<MatrixXf>((float *)matrix, size, size), flags);\n\n  if (r_U) {\n    Map<MatrixXf>(r_U, size, size) = svd.matrixU();\n  }\n\n  if (r_S) {\n    Map<VectorXf>(r_S, size) = svd.singularValues();\n  }\n\n  if (r_V) {\n    Map<MatrixXf>(r_V, size, size) = svd.matrixV();\n  }\n}\n\n#endif /* __EIGEN3_SVD_C_API_CC__ */\n", "meta": {"hexsha": "bfd7064353dfdae018723c00096d544e5b5d80fe", "size": 2043, "ext": "cc", "lang": "C++", "max_stars_repo_path": "intern/eigen/intern/svd.cc", "max_stars_repo_name": "rotoglup/blender", "max_stars_repo_head_hexsha": "05bf109b52a6e22f69c213b29ba526e7c103e897", "max_stars_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_stars_count": 365.0, "max_stars_repo_stars_event_min_datetime": "2015-02-10T15:10:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T15:50:51.000Z", "max_issues_repo_path": "intern/eigen/intern/svd.cc", "max_issues_repo_name": "rotoglup/blender", "max_issues_repo_head_hexsha": "05bf109b52a6e22f69c213b29ba526e7c103e897", "max_issues_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_issues_count": 45.0, "max_issues_repo_issues_event_min_datetime": "2015-01-09T15:34:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-05T14:44:23.000Z", "max_forks_repo_path": "intern/eigen/intern/svd.cc", "max_forks_repo_name": "rotoglup/blender", "max_forks_repo_head_hexsha": "05bf109b52a6e22f69c213b29ba526e7c103e897", "max_forks_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_forks_count": 172.0, "max_forks_repo_forks_event_min_datetime": "2015-01-25T15:16:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T08:25:36.000Z", "avg_line_length": 28.375, "max_line_length": 99, "alphanum_fraction": 0.7209985316, "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2760657046260359}}
{"text": "#include \"aikido/constraint/dart/TSR.hpp\"\n\n#include <cmath>\n#include <random>\n#include <stdexcept>\n#include <vector>\n\n#include <boost/format.hpp>\n#include <dart/common/Console.hpp>\n#include <dart/math/Geometry.hpp>\n\n#include \"aikido/common/memory.hpp\"\n\nusing aikido::statespace::SE3;\nusing boost::format;\nusing boost::str;\n\nnamespace aikido {\nnamespace constraint {\nnamespace dart {\n\nclass TSRSampleGenerator : public SampleGenerator\n{\npublic:\n  TSRSampleGenerator(const TSRSampleGenerator&) = delete;\n  TSRSampleGenerator(TSRSampleGenerator&& other) = delete;\n  TSRSampleGenerator& operator=(const TSRSampleGenerator& other) = delete;\n  TSRSampleGenerator& operator=(TSRSampleGenerator&& other) = delete;\n  virtual ~TSRSampleGenerator() = default;\n\n  // Documentation inherited.\n  statespace::ConstStateSpacePtr getStateSpace() const override;\n\n  /// Return a transform sampled from this TSR.\n  ///\n  /// This function uses the provided RNG to create a sample `Tw_s` from the\n  /// `Bw` bounds matrix of this TSR, and returns the result:\n  /// `T0_w * Tw_s * Tw_e`.\n  ///\n  /// \\param[in] rng Random number generator from which to sample\n  /// \\return a transform within the bounds of this TSR.\n  bool sample(statespace::StateSpace::State* _state) override;\n\n  // Documentation inherited.\n  bool canSample() const override;\n\n  // Documentation inherited.\n  int getNumSamples() const override;\n\nprivate:\n  // For internal use only.\n  TSRSampleGenerator(\n      std::unique_ptr<common::RNG> _rng,\n      std::shared_ptr<statespace::SE3> _stateSpace,\n      const Eigen::Isometry3d& _T0_w,\n      const Eigen::Matrix<double, 6, 2>& _Bw,\n      const Eigen::Isometry3d& _Tw_e);\n\n  std::unique_ptr<common::RNG> mRng;\n\n  std::shared_ptr<statespace::SE3> mStateSpace;\n\n  /// Transformation from origin frame into \"wiggle\" frame.\n  Eigen::Isometry3d mT0_w;\n\n  /// Bounds on \"wiggling\" in `x, y, z, roll, pitch, yaw`.\n  Eigen::Matrix<double, 6, 2> mBw;\n\n  /// Transformation from \"wiggle\" frame into end frame.\n  Eigen::Isometry3d mTw_e;\n\n  // True for point TSR.\n  bool mPointTSR;\n\n  // True if point TSR and has already been sampled.\n  bool mPointTSRSampled;\n\n  friend class TSR;\n\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\n//==============================================================================\nTSR::TSR(\n    std::unique_ptr<common::RNG> _rng,\n    const Eigen::Isometry3d& _T0_w,\n    const Eigen::Matrix<double, 6, 2>& _Bw,\n    const Eigen::Isometry3d& _Tw_e,\n    double _testableTolerance)\n  : mT0_w(_T0_w)\n  , mBw(_Bw)\n  , mTw_e(_Tw_e)\n  , mTestableTolerance(_testableTolerance)\n  , mRng(std::move(_rng))\n  , mStateSpace(std::make_shared<SE3>())\n{\n  validate();\n}\n\n//==============================================================================\nTSR::TSR(\n    const Eigen::Isometry3d& _T0_w,\n    const Eigen::Matrix<double, 6, 2>& _Bw,\n    const Eigen::Isometry3d& _Tw_e,\n    double _testableTolerance)\n  : mT0_w(_T0_w)\n  , mBw(_Bw)\n  , mTw_e(_Tw_e)\n  , mTestableTolerance(_testableTolerance)\n  , mRng(std::unique_ptr<common::RNG>(\n        new common::RNGWrapper<std::default_random_engine>(0)))\n  , mStateSpace(std::make_shared<SE3>())\n{\n  validate();\n}\n\n//==============================================================================\nTSR::TSR(const TSR& other)\n  : mT0_w(other.mT0_w)\n  , mBw(other.mBw)\n  , mTw_e(other.mTw_e)\n  , mTestableTolerance(other.mTestableTolerance)\n  , mRng(other.mRng->clone())\n  , mStateSpace(std::make_shared<SE3>())\n{\n  validate();\n}\n\n//==============================================================================\nTSR::TSR(TSR&& other)\n  : mT0_w(other.mT0_w)\n  , mBw(other.mBw)\n  , mTw_e(other.mTw_e)\n  , mTestableTolerance(other.mTestableTolerance)\n  , mRng(std::move(other.mRng))\n  , mStateSpace(std::make_shared<SE3>())\n{\n  validate();\n}\n\n//==============================================================================\nTSR& TSR::operator=(const TSR& other)\n{\n\n  mT0_w = other.mT0_w;\n  mBw = other.mBw;\n  mTw_e = other.mTw_e;\n  mTestableTolerance = other.mTestableTolerance;\n  mRng = other.mRng->clone();\n\n  // Intentionally don't assign StateSpace.\n\n  return *this;\n}\n\n//==============================================================================\nTSR& TSR::operator=(TSR&& other)\n{\n  mT0_w = std::move(other.mT0_w);\n  mBw = std::move(other.mBw);\n  mTw_e = std::move(other.mTw_e);\n  mTestableTolerance = other.mTestableTolerance;\n  mRng = std::move(other.mRng);\n  mStateSpace = std::move(other.mStateSpace);\n\n  return *this;\n}\n\n//==============================================================================\nstd::shared_ptr<const statespace::StateSpace> TSR::getStateSpace() const\n{\n  return mStateSpace;\n}\n\n//==============================================================================\nstd::shared_ptr<statespace::SE3> TSR::getSE3() const\n{\n  return mStateSpace;\n}\n\n//==============================================================================\nstd::unique_ptr<SampleGenerator> TSR::createSampleGenerator() const\n{\n  validate();\n\n  if (!mRng)\n    throw std::invalid_argument(\"Random generator is nullptr.\");\n\n  for (int i = 0; i < 6; ++i)\n  {\n    for (int j = 0; j < 2; ++j)\n    {\n      if (!std::isfinite(mBw(i, j)))\n        throw std::invalid_argument(\n            str(format(\"Sampling requires finite bounds. Bw[%d, %d] is %f.\") % i\n                % j % mBw(i, j)));\n    }\n  }\n\n  if (mBw.col(0) == mBw.col(1))\n  {\n    dtwarn << \"[TSR::createSampleGenerator] This is a point TSR that represents\"\n              \" a zero measure set in SE(3). The SampleGenerator<Isometry3d>\"\n              \" returned by this function will sample the same pose infinitely\"\n              \" many times.\\n\";\n  }\n\n  return std::unique_ptr<TSRSampleGenerator>(\n      new TSRSampleGenerator(mRng->clone(), mStateSpace, mT0_w, mBw, mTw_e));\n}\n\n//==============================================================================\nbool TSR::isSatisfied(\n    const statespace::StateSpace::State* _s, TestableOutcome* outcome) const\n{\n  auto defaultOutcomeObject\n      = dynamic_cast_or_throw<DefaultTestableOutcome>(outcome);\n\n  Eigen::VectorXd dist;\n  getValue(_s, dist);\n\n  bool isSatisfiedResult = dist.norm() < mTestableTolerance;\n  if (defaultOutcomeObject)\n    defaultOutcomeObject->setSatisfiedFlag(isSatisfiedResult);\n  return isSatisfiedResult;\n}\n\n//==============================================================================\nstd::unique_ptr<TestableOutcome> TSR::createOutcome() const\n{\n  return std::unique_ptr<TestableOutcome>(new DefaultTestableOutcome);\n}\n\n//==============================================================================\nvoid TSR::validate() const\n{\n  // Assertion checks for min, max on bounds\n  for (int i = 0; i < 6; i++)\n  {\n    if (mBw(i, 0) > mBw(i, 1))\n    {\n      throw std::logic_error(\n          str(format(\"Lower bound exceeds upper bound on dimension %d: %f > %f\")\n              % i % mBw(i, 0) % mBw(i, 1)));\n    }\n  }\n}\n\n//==============================================================================\nvoid TSR::setRNG(std::unique_ptr<common::RNG> rng)\n{\n  mRng = std::move(rng);\n}\n\n//==============================================================================\nstd::size_t TSR::getConstraintDimension() const\n{\n  return 6;\n}\n\n//==============================================================================\nvoid TSR::getValue(\n    const statespace::StateSpace::State* _s, Eigen::VectorXd& _out) const\n{\n  using SE3 = statespace::SE3;\n  using SE3State = SE3::State;\n\n  auto se3state = static_cast<const SE3State*>(_s);\n  Eigen::Isometry3d se3 = se3state->getIsometry();\n\n  using TransformTraits = Eigen::TransformTraits;\n\n  Eigen::Isometry3d T0_w_inv = mT0_w.inverse(TransformTraits::Isometry);\n  Eigen::Isometry3d Tw_e_inv = mTw_e.inverse(TransformTraits::Isometry);\n  Eigen::Isometry3d Tw_s = T0_w_inv * se3 * Tw_e_inv;\n\n  Eigen::Vector3d translation = Tw_s.translation();\n  Eigen::Vector3d eulerOrig = ::dart::math::matrixToEulerZYX(Tw_s.linear());\n  Eigen::Vector3d eulerZYX = eulerOrig.reverse();\n\n  _out.resize(6);\n\n  for (int i = 0; i < 3; ++i)\n  {\n    if (translation(i) < mBw(i, 0))\n      _out(i) = std::abs(translation(i) - mBw(i, 0));\n\n    else if (translation(i) > mBw(i, 1))\n      _out(i) = std::abs(translation(i) - mBw(i, 1));\n\n    else\n      _out(i) = 0;\n  }\n\n  for (int i = 3; i < 6; ++i)\n  {\n    // Find n such that: 2*n*pi <= mBw(i, 0) < 2*(n+1)*pi\n    int n = mBw(i, 0) / (2 * M_PI);\n\n    // Map eulerZYX(i-3) to [2*n*pi, 2*(n+1)*pi)\n    double angle = M_PI * 2 * n + eulerZYX(i - 3);\n\n    // check if angle is within bound\n    if ((angle >= mBw(i, 0) && angle <= mBw(i, 1))\n        || (angle + M_PI * 2 >= mBw(i, 0) && angle + M_PI * 2 <= mBw(i, 1))\n        || (angle - M_PI * 2 >= mBw(i, 0) && angle - M_PI * 2 <= mBw(i, 1)))\n    {\n      _out(i) = 0;\n      continue;\n    }\n\n    // Take min-distance between angle and either side of bound\n    if (angle < mBw(i, 0))\n      _out(i) = std::min(mBw(i, 0) - angle, angle - (mBw(i, 1) - 2 * M_PI));\n\n    else if (mBw(i, 1) < angle)\n      _out(i) = std::min(angle - mBw(i, 1), mBw(i, 0) + 2 * M_PI - angle);\n  }\n}\n\n//==============================================================================\nvoid TSR::getJacobian(\n    const statespace::StateSpace::State* _s, Eigen::MatrixXd& _out) const\n{\n  using SE3 = statespace::SE3;\n  using SE3State = SE3::State;\n\n  _out.resize(6, 6);\n\n  auto se3state = static_cast<const SE3State*>(_s);\n  Eigen::Isometry3d se3 = se3state->getIsometry();\n\n  Eigen::Vector6d twist = ::dart::math::logMap(se3);\n\n  Eigen::Vector6d posit(twist), negat(twist);\n\n  static constexpr double eps = 1e-5;\n\n  auto se3posit = mStateSpace->createState();\n  auto se3negat = mStateSpace->createState();\n\n  // Finite Differencing.\n  for (int i = 0; i < 6; ++i)\n  {\n    posit(i) = twist(i) + eps;\n    negat(i) = twist(i) - eps;\n\n    se3posit.setIsometry(::dart::math::expMap(posit));\n    se3negat.setIsometry(::dart::math::expMap(negat));\n\n    Eigen::VectorXd positValue, negatValue;\n    getValue(se3posit, positValue);\n    getValue(se3negat, negatValue);\n\n    Eigen::Vector6d diff = positValue - negatValue;\n    _out.col(i) = diff / (2 * eps);\n\n    posit(i) = twist(i);\n    negat(i) = twist(i);\n  }\n}\n\n//==============================================================================\nstd::vector<ConstraintType> TSR::getConstraintTypes() const\n{\n  return std::vector<ConstraintType>(6, ConstraintType::INEQUALITY);\n}\n\n//==============================================================================\nbool TSR::project(\n    const statespace::StateSpace::State* /*_s*/,\n    statespace::StateSpace::State* /*_out*/) const\n{\n  // TODO\n  return false;\n}\n\n//==============================================================================\nTSRSampleGenerator::TSRSampleGenerator(\n    std::unique_ptr<common::RNG> _rng,\n    std::shared_ptr<SE3> _stateSpace,\n    const Eigen::Isometry3d& _T0_w,\n    const Eigen::Matrix<double, 6, 2>& _Bw,\n    const Eigen::Isometry3d& _Tw_e)\n  : mRng(std::move(_rng))\n  , mStateSpace(std::move(_stateSpace))\n  , mT0_w(_T0_w)\n  , mBw(_Bw)\n  , mTw_e(_Tw_e)\n{\n  if (!mRng)\n  {\n    throw std::invalid_argument(\"Random generator is empty.\");\n  }\n\n  if (mBw.col(0) == mBw.col(1))\n    mPointTSR = true;\n  else\n    mPointTSR = false;\n\n  mPointTSRSampled = false;\n}\n\n//==============================================================================\nstatespace::ConstStateSpacePtr TSRSampleGenerator::getStateSpace() const\n{\n  return mStateSpace;\n}\n\n//==============================================================================\nbool TSRSampleGenerator::sample(statespace::StateSpace::State* _state)\n{\n  if (mPointTSR && mPointTSRSampled)\n    return false;\n\n  using statespace::SE3;\n\n  Eigen::Vector3d translation;\n  Eigen::Vector3d angles;\n\n  if (mPointTSR)\n  {\n    translation = mBw.block(0, 0, 3, 1);\n    angles = mBw.block(3, 0, 3, 1);\n\n    mPointTSRSampled = true;\n  }\n  else\n  {\n    std::vector<std::uniform_real_distribution<double> > distributions;\n    for (int i = 0; i < 6; i++)\n      distributions.emplace_back(mBw(i, 0), mBw(i, 1));\n\n    for (int i = 0; i < 3; i++)\n      translation(i) = distributions.at(i)(*mRng);\n\n    for (int i = 0; i < 3; i++)\n      angles(i) = distributions.at(i + 3)(*mRng);\n  }\n\n  Eigen::Isometry3d Tw_s;\n  Tw_s.setIdentity();\n  Tw_s.translation() = translation;\n  Tw_s.linear() = ::dart::math::eulerZYXToMatrix(angles.reverse());\n\n  Eigen::Isometry3d T0_s(mT0_w * Tw_s * mTw_e);\n  mStateSpace->setIsometry(static_cast<SE3::State*>(_state), T0_s);\n\n  return true;\n}\n\n//==============================================================================\ndouble TSR::getTestableTolerance()\n{\n  return mTestableTolerance;\n}\n\n//==============================================================================\nvoid TSR::setTestableTolerance(double _testableTolerance)\n{\n  mTestableTolerance = _testableTolerance;\n}\n\n//==============================================================================\nbool TSRSampleGenerator::canSample() const\n{\n  if (mPointTSR && mPointTSRSampled)\n    return false;\n\n  return true;\n}\n\n//==============================================================================\nint TSRSampleGenerator::getNumSamples() const\n{\n  if (mPointTSR && !mPointTSRSampled)\n    return 1;\n\n  if (mPointTSR && mPointTSRSampled)\n    return 0;\n\n  return NO_LIMIT;\n}\n\n} // namespace dart\n} // namespace constraint\n} // namespace aikido\n", "meta": {"hexsha": "c6c31a6066d01ab654c1992f1f898a3b3d781445", "size": 13324, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/constraint/dart/TSR.cpp", "max_stars_repo_name": "personalrobotics/r3", "max_stars_repo_head_hexsha": "1303e3f3ef99a0c2249abc7415d19113f0026565", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 181.0, "max_stars_repo_stars_event_min_datetime": "2016-04-22T15:11:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T12:51:08.000Z", "max_issues_repo_path": "src/constraint/dart/TSR.cpp", "max_issues_repo_name": "personalrobotics/r3", "max_issues_repo_head_hexsha": "1303e3f3ef99a0c2249abc7415d19113f0026565", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 514.0, "max_issues_repo_issues_event_min_datetime": "2016-04-20T04:29:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T19:46:21.000Z", "max_forks_repo_path": "src/constraint/dart/TSR.cpp", "max_forks_repo_name": "personalrobotics/r3", "max_forks_repo_head_hexsha": "1303e3f3ef99a0c2249abc7415d19113f0026565", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2017-03-17T09:53:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T10:35:05.000Z", "avg_line_length": 27.2474437628, "max_line_length": 80, "alphanum_fraction": 0.5582407685, "num_tokens": 3727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2760252753174524}}
{"text": "#include \"slice.h\"\n\n#include <cstdio>\n#include <iostream>\n#include <map>\n#include <stdint.h>\n\n#include <Eigen/Sparse>\n\nusing namespace Eigen;\n\nusing std::cout;\nusing std::endl;\nusing std::map;\nusing std::ostream;\nusing std::pair;\nusing std::vector;\n\nvoid debug_print_sparse(const SparseMatrix<uint8_t> &mat) {\n    for (int i = 0; i < mat.cols(); i++) {\n        cout << \"\\t\" << i;\n    }\n    cout << endl;\n    for (int i = 0; i < mat.rows(); i++) {\n        cout << i << \":\\t\";\n        for (int j = 0; j < mat.cols(); j++) {\n            cout << (int) mat.coeff(i, j) << \"\\t\";\n        }\n        cout << endl;\n    }\n}\n\n#define OUT_OF_PLANE (0)\n#define POINT_IN_PLANE (1)\n#define FACE_IN_PLANE (2)\n\n// returns FACE_IN_PLANE if the face is fully in-plane (all verteces lie in the\n// plane). returns POINT_IN_PLANE if the plane and face intersect at a single\n// point. returns OUT_OF_PLANE if neither property holds.\n//\n// this function should only be called on faces that either intersect the plane\n// or lie in it.\nint inplane_status(const float z, const face* f) {\n    edge *e0 = f->e;\n    // check for in-plane conditions\n    int verts_inplane = 0;\n    int verts_above = 0;\n    int verts_below = 0;\n\n    do {\n        vertex *v = e0->vert;\n        if (v->loc[2] == z) {\n            verts_inplane++;\n        } else if (v->loc[2] > z) {\n            verts_above++;\n        } else {\n            verts_below++;\n        }\n        e0 = e0->next;\n    } while (e0 != f->e);\n\n    // check for whole-tri-in-plane\n    if (verts_above == 0 && verts_below == 0) {\n        return FACE_IN_PLANE;\n\n    }\n    // check for single-point-in-plane\n    if (verts_inplane == 1 && (verts_above == 0 || verts_below == 0)) {\n        return POINT_IN_PLANE;\n    }\n    return OUT_OF_PLANE;\n}\n\n// returns the line segment across the face representing the line of\n// intersection between the xy-plane at height z and the provided face.\n// returns a zero-length line segment if face does not intersect plane\nlineseg isect_tri_xy_plane(const float z, const face* f) {\n    lineseg l;\n\n    if (f->sides() != 3) {\n        // TODO: triangularize!\n        cout << \"got a nontriangular mesh and I'm a stupid slicer.\" << endl;\n        return l;\n    }\n\n    int points_found = 0;\n    edge *e0 = f->e;\n    do {\n        // do this at the start so we can use continue within the loop\n        e0 = e0->next;\n\n        vertex *v = e0->next->vert,\n               *v0 = e0->vert;\n        float v_z = v->loc[2],\n              v0_z = v0->loc[2];\n\n        if (v_z == v0_z) {\n            // check for edge-in-plane condition. since we know the whole\n            // tri /isn't/ in-plane from the check above, we know that this\n            // edge must be our levelset poly line segment\n            if (v_z == z) {\n                l.p1 = v0->loc;\n                l.p2 = v->loc;\n                points_found = 2;\n                break;\n            }\n            continue;\n        }\n\n        float n = (v_z - z) / (v_z - v0_z);\n        if (0 <= n && n <= 1) {\n            Vector3f p = v->loc - n * (v->loc - v0->loc);\n            if (points_found == 0) {\n                l.p1 = p;\n                points_found++;\n            } else if (points_found == 1 && p != l.p1) {\n                l.p2 = p;\n                points_found++;\n            }\n        }\n    } while (e0 != f->e);\n    return l;\n}\n\n// assign faces to layer buckets. this modifies the levelset vector in-place.\nvoid bucket_faces(\n        const mesh &m, const bounds &b,\n        const float layer_height, vector<levelset> &layers) {\n    for (auto iter = m.faces.begin(); iter != m.faces.end(); iter++) {\n        face* f = *iter;\n\n        // find face bounds\n        float z_min = INFINITY, z_max = -INFINITY;\n        edge *e = f->e;\n        vertex *v;\n        do {\n            v = e->vert;\n            if (v->loc[2] > z_max) {\n                z_max = v->loc[2];\n            }\n            if (v->loc[2] < z_min) {\n                z_min = v->loc[2];\n            }\n            e = e->next;\n        } while (e != f->e);\n\n        // add face to appropriate buckets\n        for (auto ls = layers.begin(); ls != layers.end(); ls++) {\n            if (z_min <= ls->z && ls->z <= z_max) {\n                ls->faces.push_back(f);\n            } else if (ls->z > z_max) {\n                // we're out of our good range, break\n                break;\n            }\n        }\n    }\n}\n\n// generates a list of line segments based on the intersection of the bucketed\n// faces and the xy-plane at height ls.z\nvoid find_line_segments(levelset &ls) {\n    for (auto iter = ls.faces.begin(); iter != ls.faces.end(); iter++) {\n        face* f = *iter;\n        int inplane = inplane_status(ls.z, f);\n\n        if (inplane == FACE_IN_PLANE) {\n            ls.inplane.push_back(f);\n            continue;\n        } else if (inplane == POINT_IN_PLANE) {\n            continue;\n        }\n\n        lineseg line = isect_tri_xy_plane(ls.z, f);\n        if ((line.p1 - line.p2).norm() == 0) {\n            cout << \"warning: face doesn't intersect z = \" << ls.z << endl;\n            edge *e = f->e;\n            do {\n                vertex *v = e->vert;\n                printf(\"  v[%lx]\\t%f\\t%f\\t%f\\n\", (unsigned long) v,\n                        v->loc[0], v->loc[1], v->loc[2]);\n                e = e->next;\n            } while (e != f->e);\n        } else {\n            ls.lines.push_back(line);\n        }\n    }\n}\n\n// creates a vertex in the vert_ids map and in the verts list. returns the ID to\n// use for the next vertex (either next_id or next_id + 1)\nint create_vertex(\n        map<Vector3f, uint32_t, vector_comparitor> &vert_ids,\n        Vector3f &loc, vector<Vector3f> &verts, int next_id) {\n    if (vert_ids.find(loc) != vert_ids.end()) {\n        return next_id;\n    }\n    vert_ids.insert(pair<Vector3f, uint32_t>(loc, next_id));\n    verts.push_back(loc);\n    return next_id + 1;\n}\n\n// converts an unsorted list of line segments to a list of ordered lists of\n// verteces representing paths around the levelset.\nvoid linesegs_to_vert_list(levelset &ls) {\n    map<Vector3f, uint32_t, vector_comparitor> vert_ids;\n    int next_id = 0;\n\n    // build vert list\n    for (auto iter = ls.lines.begin(); iter != ls.lines.end(); iter++) {\n        next_id = create_vertex(vert_ids, iter->p1, ls.verteces, next_id);\n        next_id = create_vertex(vert_ids, iter->p2, ls.verteces, next_id);\n    }\n    int n = ls.verteces.size();\n\n    // build adjacency\n    // TODO: handle double-edges\n    vector<Triplet<uint8_t>> adjacents;\n    for (auto iter = ls.lines.begin(); iter != ls.lines.end(); iter++) {\n        auto i1 = vert_ids.find(iter->p1);\n        if (i1 == vert_ids.end()) {\n            cout << \"warning: after building vert list, vert \" <<\n                iter->p1.transpose() << \" is missing\" << endl;\n        }\n        auto i2 = vert_ids.find(iter->p2);\n        if (i2 == vert_ids.end()) {\n            cout << \"warning: after building vert list, vert \" <<\n                iter->p2.transpose() << \" is missing\" << endl;\n        }\n        adjacents.push_back(Triplet<uint8_t>(i1->second, i2->second, 1));\n        adjacents.push_back(Triplet<uint8_t>(i2->second, i1->second, 1));\n    }\n\n    SparseMatrix<uint8_t> adj(n, n);\n    adj.setFromTriplets(adjacents.begin(), adjacents.end());\n\n    int vert = -1;\n    vector<uint32_t> perimeter;\n    vector<vector<uint32_t>*> perimeters;\n\n    while (true) {\n        if (vert == -1) {\n            for (vert = 0; vert < adj.cols(); vert++) {\n                for (int i = 0; i < adj.rows(); i++) {\n                    if (adj.coeff(i, vert) > 0) {\n                        goto next_vert;\n                    }\n                }\n            }\n            goto exit;\n        } else {\n            int next = -1;\n            for (int r = 0; r < adj.rows(); r++) {\n                if (adj.coeff(vert, r) > 0) {\n                    adj.coeffRef(vert, r)--;\n                    adj.coeffRef(r, vert)--;\n                    next = r;\n                    break;\n                }\n            }\n            vert = next;\n        }\nnext_vert:\n        if (vert != -1) {\n            perimeter.push_back(vert);\n        } else if (perimeter.size() > 0) {\n            ls.perimeters.push_back(perimeter);\n            perimeter.clear();\n        }\n    }\nexit:\n    return;\n}\n\nvoid slice(const tooldef td, const mesh &m, vector<levelset> &levelsets) {\n    levelsets.clear();\n\n    bounds b = m.get_bounds();\n    int level_count = ceil((b.max_z - b.min_z) / td.z_accuracy);\n    for (int i = 0; i < level_count; i++) {\n        levelset l;\n        l.z = b.min_z + i * td.z_accuracy;\n        levelsets.push_back(l);\n    }\n    levelset l;\n    l.z = b.max_z;\n    levelsets.push_back(l);\n\n    bucket_faces(m, b, td.z_accuracy, levelsets);\n\n    for (auto iter = levelsets.begin(); iter != levelsets.end(); iter++) {\n        find_line_segments(*iter);\n        linesegs_to_vert_list(*iter);\n    }\n}\n\nlineseg::lineseg() {}\n\nlineseg::lineseg(const lineseg &other) : p1(other.p1), p2(other.p2) {}\n\nlevelset::levelset() {}\n\nlevelset::levelset(const levelset &other) :\n        verteces(other.verteces), perimeters(other.perimeters),\n        inplane(other.inplane), z(other.z), faces(other.faces),\n        lines(other.lines) {}\n\nostream& operator<< (ostream &out, const lineseg &l) {\n    out << \"(\" << l.p1.transpose() << \",\\t\" << l.p2.transpose() << \")\";\n    return out;\n}\n\nostream& operator<< (ostream &out, const levelset &ls) {\n    out << \"[verteces = \" << ls.verteces.size()\n        << \" lines size \" << ls.lines.size()\n        << \"]\";\n    return out;\n}\n", "meta": {"hexsha": "b4112deaa988dcbc86a4c87f79eaf99c3fbc1aec", "size": 9513, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/slice.cpp", "max_stars_repo_name": "haldean/toolpath", "max_stars_repo_head_hexsha": "98da1b8636aa40ac43fa32e26e6e7b30ca857aa9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-08-12T16:46:41.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-12T16:46:41.000Z", "max_issues_repo_path": "src/slice.cpp", "max_issues_repo_name": "haldean/toolpath", "max_issues_repo_head_hexsha": "98da1b8636aa40ac43fa32e26e6e7b30ca857aa9", "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/slice.cpp", "max_forks_repo_name": "haldean/toolpath", "max_forks_repo_head_hexsha": "98da1b8636aa40ac43fa32e26e6e7b30ca857aa9", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9150943396, "max_line_length": 80, "alphanum_fraction": 0.5208661831, "num_tokens": 2583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.2760252753174524}}
{"text": "// This file is part of the dune-gdt project:\n//   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//   Felix Schindler (2015 - 2017)\n//   Rene Milk       (2016 - 2018)\n//   Tobias Leibner  (2018)\n\n#ifndef DUNE_GDT_LOCAL_OPERATORS_INTEGRALS_HH\n#define DUNE_GDT_LOCAL_OPERATORS_INTEGRALS_HH\n\n#include <type_traits>\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <dune/common/densematrix.hh>\n\n#include <dune/geometry/quadraturerules.hh>\n\n#include <dune/xt/common/matrix.hh>\n\n#include <dune/xt/functions/interfaces.hh>\n\n#include <dune/xt/la/container/common/matrix/dense.hh>\n\n#include <dune/gdt/local/integrands/interfaces.hh>\n#include <dune/gdt/type_traits.hh>\n\n#include \"interfaces.hh\"\n\nnamespace Dune {\nnamespace GDT {\n\n\ntemplate <class BinaryEvaluationType,\n          class TestBase,\n          class AnsatzBase = TestBase,\n          class Field = typename TestBase::RangeFieldType>\nclass LocalVolumeIntegralOperator : public LocalVolumeTwoFormInterface<TestBase, AnsatzBase, Field>\n{\n  static_assert(is_binary_volume_integrand<BinaryEvaluationType>::value, \"\");\n  static_assert(std::is_same<typename TestBase::EntityType, typename AnsatzBase::EntityType>::value, \"\");\n  static_assert(std::is_same<typename TestBase::DomainFieldType, typename AnsatzBase::DomainFieldType>::value, \"\");\n  static_assert(TestBase::dimDomain == AnsatzBase::dimDomain, \"\");\n\n  typedef LocalVolumeIntegralOperator<BinaryEvaluationType, TestBase, AnsatzBase, Field> ThisType;\n  typedef LocalVolumeTwoFormInterface<TestBase, AnsatzBase, Field> BaseType;\n\n  typedef typename TestBase::DomainFieldType D;\n  static const size_t d = TestBase::dimDomain;\n\npublic:\n  using typename BaseType::TestBaseType;\n  using typename BaseType::AnsatzBaseType;\n  using typename BaseType::FieldType;\n\n  template <class... Args>\n  explicit LocalVolumeIntegralOperator(Args&&... args)\n    : integrand_(std::forward<Args>(args)...)\n    , over_integrate_(0)\n  {\n  }\n\n  template <class... Args>\n  explicit LocalVolumeIntegralOperator(const int over_integrate, Args&&... args)\n    : integrand_(std::forward<Args>(args)...)\n    , over_integrate_(boost::numeric_cast<size_t>(over_integrate))\n  {\n  }\n\n  template <class... Args>\n  explicit LocalVolumeIntegralOperator(const size_t over_integrate, Args&&... args)\n    : integrand_(std::forward<Args>(args)...)\n    , over_integrate_(over_integrate)\n  {\n  }\n\n  LocalVolumeIntegralOperator(const ThisType& other) = default;\n  LocalVolumeIntegralOperator(ThisType&& source) = default;\n\n  using BaseType::apply2;\n\n  // copied from apply2 below\n  // TODO: fix properly (use CommonDenseMatrix instead of DynamicMatrix everywhere in dune-gdt?)\n  void apply2(const TestBaseType& test_base,\n              const AnsatzBaseType& ansatz_base,\n              XT::LA::CommonDenseMatrix<FieldType>& ret) const\n  {\n    const auto& entity = ansatz_base.entity();\n    const auto local_functions = integrand_.localFunctions(entity);\n    // create quadrature\n    const size_t integrand_order = integrand_.order(local_functions, test_base, ansatz_base) + over_integrate_;\n    const auto& quadrature = QuadratureRules<D, d>::rule(entity.type(), boost::numeric_cast<int>(integrand_order));\n    // prepare storage\n    const size_t rows = test_base.size();\n    const size_t cols = ansatz_base.size();\n    ret *= 0.0;\n    assert(ret.rows() >= rows);\n    assert(ret.cols() >= cols);\n    DynamicMatrix<FieldType> integrand_eval(rows, cols, 0.); // \\todo: make mutable member, after SMP refactor\n    // loop over all quadrature points\n    for (const auto& quadrature_point : quadrature) {\n      const auto xx = quadrature_point.position();\n      // integration factors\n      const auto integration_factor = entity.geometry().integrationElement(xx);\n      const auto quadrature_weight = quadrature_point.weight();\n      // evaluate the integrand\n      integrand_.evaluate(local_functions, test_base, ansatz_base, xx, integrand_eval);\n      // compute integral\n      ret.axpy(integration_factor * quadrature_weight, integrand_eval);\n    } // loop over all quadrature points\n  } // ... apply2(...)\n\n  void\n  apply2(const TestBaseType& test_base, const AnsatzBaseType& ansatz_base, DynamicMatrix<FieldType>& ret) const override\n  {\n    const auto& entity = ansatz_base.entity();\n    const auto local_functions = integrand_.localFunctions(entity);\n    // create quadrature\n    const size_t integrand_order = integrand_.order(local_functions, test_base, ansatz_base) + over_integrate_;\n    const auto& quadrature = QuadratureRules<D, d>::rule(entity.type(), boost::numeric_cast<int>(integrand_order));\n    // prepare storage\n    const size_t rows = test_base.size();\n    const size_t cols = ansatz_base.size();\n    ret *= 0.0;\n    assert(ret.rows() >= rows);\n    assert(ret.cols() >= cols);\n    DynamicMatrix<FieldType> integrand_eval(rows, cols, 0.); // \\todo: make mutable member, after SMP refactor\n    // loop over all quadrature points\n    for (const auto& quadrature_point : quadrature) {\n      const auto xx = quadrature_point.position();\n      // integration factors\n      const auto integration_factor = entity.geometry().integrationElement(xx);\n      const auto quadrature_weight = quadrature_point.weight();\n      // evaluate the integrand\n      integrand_.evaluate(local_functions, test_base, ansatz_base, xx, integrand_eval);\n      // compute integral\n      for (size_t ii = 0; ii < rows; ++ii) {\n        const auto& integrand_eval_row = integrand_eval[ii];\n        auto& ret_row = ret[ii];\n        for (size_t jj = 0; jj < cols; ++jj)\n          ret_row[jj] += integrand_eval_row[jj] * integration_factor * quadrature_weight;\n      } // compute integral\n    } // loop over all quadrature points\n  } // ... apply2(...)\n\nprivate:\n  const BinaryEvaluationType integrand_;\n  const size_t over_integrate_;\n}; // class LocalVolumeIntegralOperator\n\n\ntemplate <class QuaternaryFaceIntegrandType,\n          class TestBaseEntity,\n          class Intersection,\n          class AnsatzBaseEntity = TestBaseEntity,\n          class TestBaseNeighbor = TestBaseEntity,\n          class AnsatzBaseNeighbor = AnsatzBaseEntity,\n          class Field = typename TestBaseEntity::RangeFieldType>\nclass LocalCouplingIntegralOperator : public LocalCouplingTwoFormInterface<TestBaseEntity,\n                                                                           Intersection,\n                                                                           AnsatzBaseEntity,\n                                                                           TestBaseNeighbor,\n                                                                           AnsatzBaseNeighbor,\n                                                                           Field>\n{\n  static_assert(is_quaternary_face_integrand<QuaternaryFaceIntegrandType>::value, \"\");\n  static_assert(std::is_same<typename TestBaseEntity::EntityType, typename AnsatzBaseEntity::EntityType>::value, \"\");\n  static_assert(std::is_same<typename TestBaseEntity::EntityType, typename TestBaseNeighbor::EntityType>::value, \"\");\n  static_assert(std::is_same<typename TestBaseEntity::EntityType, typename AnsatzBaseNeighbor::EntityType>::value, \"\");\n  static_assert(\n      std::is_same<typename TestBaseEntity::DomainFieldType, typename AnsatzBaseEntity::DomainFieldType>::value, \"\");\n  static_assert(\n      std::is_same<typename TestBaseEntity::DomainFieldType, typename TestBaseNeighbor::DomainFieldType>::value, \"\");\n  static_assert(\n      std::is_same<typename TestBaseEntity::DomainFieldType, typename AnsatzBaseNeighbor::DomainFieldType>::value, \"\");\n  static_assert(TestBaseEntity::dimDomain == AnsatzBaseEntity::dimDomain, \"\");\n  static_assert(TestBaseEntity::dimDomain == TestBaseNeighbor::dimDomain, \"\");\n  static_assert(TestBaseEntity::dimDomain == AnsatzBaseNeighbor::dimDomain, \"\");\n\n  typedef LocalCouplingIntegralOperator<QuaternaryFaceIntegrandType,\n                                        TestBaseEntity,\n                                        Intersection,\n                                        AnsatzBaseEntity,\n                                        TestBaseNeighbor,\n                                        AnsatzBaseNeighbor,\n                                        Field>\n      ThisType;\n  typedef LocalCouplingTwoFormInterface<TestBaseEntity,\n                                        Intersection,\n                                        AnsatzBaseEntity,\n                                        TestBaseNeighbor,\n                                        AnsatzBaseNeighbor,\n                                        Field>\n      BaseType;\n  typedef typename TestBaseEntity::DomainFieldType D;\n  static const size_t d = TestBaseEntity::dimDomain;\n\npublic:\n  using typename BaseType::TestBaseEntityType;\n  using typename BaseType::AnsatzBaseEntityType;\n  using typename BaseType::TestBaseNeighborType;\n  using typename BaseType::AnsatzBaseNeighborType;\n  using typename BaseType::IntersectionType;\n  using typename BaseType::FieldType;\n\n  template <class... Args>\n  explicit LocalCouplingIntegralOperator(Args&&... args)\n    : integrand_(std::forward<Args>(args)...)\n    , over_integrate_(0)\n  {\n  }\n\n  template <class... Args>\n  explicit LocalCouplingIntegralOperator(const int over_integrate, Args&&... args)\n    : integrand_(std::forward<Args>(args)...)\n    , over_integrate_(boost::numeric_cast<size_t>(over_integrate))\n  {\n  }\n\n  template <class... Args>\n  explicit LocalCouplingIntegralOperator(const size_t over_integrate, Args&&... args)\n    : integrand_(std::forward<Args>(args)...)\n    , over_integrate_(over_integrate)\n  {\n  }\n\n  LocalCouplingIntegralOperator(const ThisType& other) = default;\n  LocalCouplingIntegralOperator(ThisType&& source) = default;\n\n  void apply2(const TestBaseEntityType& test_base_en,\n              const AnsatzBaseEntityType& ansatz_base_en,\n              const TestBaseNeighborType& test_base_ne,\n              const AnsatzBaseNeighborType& ansatz_base_ne,\n              const IntersectionType& intersection,\n              DynamicMatrix<FieldType>& ret_en_en,\n              DynamicMatrix<FieldType>& ret_ne_ne,\n              DynamicMatrix<FieldType>& ret_en_ne,\n              DynamicMatrix<FieldType>& ret_ne_en) const override\n  {\n    // local inducing function\n    const auto& entity = test_base_en.entity();\n    const auto& neighbor = test_base_ne.entity();\n    const auto local_functions_en = integrand_.localFunctions(entity);\n    const auto local_functions_ne = integrand_.localFunctions(neighbor);\n    // quadrature\n    const size_t integrand_order =\n        integrand_.order(\n            local_functions_en, local_functions_ne, test_base_en, ansatz_base_en, test_base_ne, ansatz_base_ne)\n        + over_integrate_;\n    const auto& quadrature =\n        QuadratureRules<D, d - 1>::rule(intersection.type(), boost::numeric_cast<int>(integrand_order));\n    // check matrices\n    ret_en_en *= 0.0;\n    ret_ne_ne *= 0.0;\n    ret_en_ne *= 0.0;\n    ret_ne_en *= 0.0;\n    const size_t rows_en = test_base_en.size();\n    const size_t cols_en = ansatz_base_en.size();\n    const size_t rows_ne = test_base_ne.size();\n    const size_t cols_ne = ansatz_base_ne.size();\n    assert(ret_en_en.rows() >= rows_en);\n    assert(ret_en_en.cols() >= cols_en);\n    assert(ret_ne_ne.rows() >= rows_ne);\n    assert(ret_ne_ne.cols() >= cols_ne);\n    assert(ret_en_ne.rows() >= rows_en);\n    assert(ret_en_ne.cols() >= cols_ne);\n    assert(ret_ne_en.rows() >= rows_en);\n    assert(ret_ne_en.cols() >= cols_en);\n    // \\todo: make mutable member, after SMP refactor\n    DynamicMatrix<FieldType> integrand_eval_en_en(rows_en, cols_en, 0.);\n    DynamicMatrix<FieldType> integrand_eval_ne_ne(rows_ne, cols_ne, 0.);\n    DynamicMatrix<FieldType> integrand_eval_en_ne(rows_en, cols_ne, 0.);\n    DynamicMatrix<FieldType> integrand_eval_ne_en(rows_ne, cols_en, 0.);\n    // loop over all quadrature points\n    for (const auto& quadrature_point : quadrature) {\n      const auto xx = quadrature_point.position();\n      const auto integration_factor = intersection.geometry().integrationElement(xx);\n      const auto quadrature_weight = quadrature_point.weight();\n      // evaluate local\n      integrand_.evaluate(local_functions_en,\n                          local_functions_ne,\n                          test_base_en,\n                          ansatz_base_en,\n                          test_base_ne,\n                          ansatz_base_ne,\n                          intersection,\n                          xx,\n                          integrand_eval_en_en,\n                          integrand_eval_ne_ne,\n                          integrand_eval_en_ne,\n                          integrand_eval_ne_en);\n      // compute integrals\n      // loop over all entity test basis functions\n      for (size_t ii = 0; ii < rows_en; ++ii) {\n        auto& ret_en_en_row = ret_en_en[ii];\n        auto& ret_en_ne_row = ret_en_ne[ii];\n        const auto& integrand_eval_en_en_row = integrand_eval_en_en[ii];\n        const auto& integrand_eval_en_ne_row = integrand_eval_en_ne[ii];\n        // loop over all entity ansatz basis functions\n        for (size_t jj = 0; jj < cols_en; ++jj) {\n          ret_en_en_row[jj] += integrand_eval_en_en_row[jj] * integration_factor * quadrature_weight;\n        }\n        // loop over all neighbor ansatz basis functions\n        for (size_t jj = 0; jj < cols_ne; ++jj) {\n          ret_en_ne_row[jj] += integrand_eval_en_ne_row[jj] * integration_factor * quadrature_weight;\n        }\n      }\n      // loop over all neighbor test basis functions\n      for (size_t ii = 0; ii < rows_ne; ++ii) {\n        auto& ret_ne_ne_row = ret_ne_ne[ii];\n        auto& ret_ne_en_row = ret_ne_en[ii];\n        const auto& integrand_eval_ne_ne_row = integrand_eval_ne_ne[ii];\n        const auto& integrand_eval_ne_en_row = integrand_eval_ne_en[ii];\n        // loop over all neighbor ansatz basis functions\n        for (size_t jj = 0; jj < cols_ne; ++jj) {\n          ret_ne_ne_row[jj] += integrand_eval_ne_ne_row[jj] * integration_factor * quadrature_weight;\n        }\n        // loop over all entity ansatz basis functions\n        for (size_t jj = 0; jj < cols_en; ++jj) {\n          ret_ne_en_row[jj] += integrand_eval_ne_en_row[jj] * integration_factor * quadrature_weight;\n        }\n      }\n    } // loop over all quadrature points\n  } // void apply(...) const\n\nprivate:\n  const QuaternaryFaceIntegrandType integrand_;\n  const size_t over_integrate_;\n}; // class LocalCouplingIntegralOperator\n\n\ntemplate <class BinaryFaceIntegrandType,\n          class TestBase,\n          class Intersection,\n          class AnsatzBase = TestBase,\n          class Field = typename TestBase::RangeFieldType>\nclass LocalBoundaryIntegralOperator : public LocalBoundaryTwoFormInterface<TestBase, Intersection, AnsatzBase, Field>\n{\n  static_assert(is_binary_face_integrand<BinaryFaceIntegrandType>::value, \"\");\n  static_assert(std::is_same<typename TestBase::EntityType, typename AnsatzBase::EntityType>::value, \"\");\n  static_assert(std::is_same<typename TestBase::DomainFieldType, typename AnsatzBase::DomainFieldType>::value, \"\");\n  static_assert(TestBase::dimDomain == AnsatzBase::dimDomain, \"\");\n\n  typedef LocalBoundaryIntegralOperator<BinaryFaceIntegrandType, TestBase, Intersection, AnsatzBase, Field> ThisType;\n  typedef LocalBoundaryTwoFormInterface<TestBase, Intersection, AnsatzBase, Field> BaseType;\n  typedef typename TestBase::DomainFieldType D;\n  static const size_t d = TestBase::dimDomain;\n\npublic:\n  using typename BaseType::TestBaseType;\n  using typename BaseType::AnsatzBaseType;\n  using typename BaseType::IntersectionType;\n  using typename BaseType::FieldType;\n\n  template <class... Args>\n  LocalBoundaryIntegralOperator(Args&&... args)\n    : integrand_(std::forward<Args>(args)...)\n    , over_integrate_(0)\n  {\n  }\n\n  template <class... Args>\n  LocalBoundaryIntegralOperator(const int over_integrate, Args&&... args)\n    : integrand_(std::forward<Args>(args)...)\n    , over_integrate_(boost::numeric_cast<size_t>(over_integrate))\n  {\n  }\n\n  template <class... Args>\n  LocalBoundaryIntegralOperator(const size_t over_integrate, Args&&... args)\n    : integrand_(std::forward<Args>(args)...)\n    , over_integrate_(over_integrate)\n  {\n  }\n\n  void apply2(const TestBaseType& test_base,\n              const AnsatzBaseType& ansatz_base,\n              const IntersectionType& intersection,\n              DynamicMatrix<FieldType>& ret) const override\n  {\n    // local inducing function\n    const auto& entity = test_base.entity();\n    const auto local_functions = integrand_.localFunctions(entity);\n    // create quadrature\n    const auto integrand_order = integrand_.order(local_functions, test_base, ansatz_base) + over_integrate_;\n    const auto& quadrature =\n        QuadratureRules<D, d - 1>::rule(intersection.type(), boost::numeric_cast<int>(integrand_order));\n    // prepare storage\n    ret *= 0.0;\n    const size_t rows = test_base.size();\n    const size_t cols = ansatz_base.size();\n    assert(ret.rows() >= rows);\n    assert(ret.cols() >= cols);\n    DynamicMatrix<FieldType> integrand_eval(rows, cols, 0.); // \\todo: make mutable member, after SMP refactor\n    // loop over all quadrature points\n    for (const auto& quadrature_point : quadrature) {\n      const auto xx = quadrature_point.position();\n      const auto integration_factor = intersection.geometry().integrationElement(xx);\n      const auto quadrature_weight = quadrature_point.weight();\n      // evaluate local\n      integrand_.evaluate(local_functions, test_base, ansatz_base, intersection, xx, integrand_eval);\n      // compute integral\n      assert(integrand_eval.rows() >= rows);\n      assert(integrand_eval.cols() >= cols);\n      // loop over all test basis functions\n      for (size_t ii = 0; ii < rows; ++ii) {\n        auto& ret_row = ret[ii];\n        const auto& integrand_eval_row = integrand_eval[ii];\n        // loop over all ansatz basis functions\n        for (size_t jj = 0; jj < cols; ++jj) {\n          ret_row[jj] += integrand_eval_row[jj] * integration_factor * quadrature_weight;\n        }\n      }\n    }\n  } // ... apply(...)\n\nprivate:\n  const BinaryFaceIntegrandType integrand_;\n  const size_t over_integrate_;\n}; // class LocalBoundaryIntegralOperator\n\n\n} // namespace GDT\n} // namespace Dune\n\n#endif // DUNE_GDT_LOCAL_OPERATORS_INTEGRALS_HH\n", "meta": {"hexsha": "de4f5512dc863040ce8d1d2fb90b639a395a4a71", "size": 18582, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/gdt/local/operators/integrals.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/local/operators/integrals.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/local/operators/integrals.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": 43.1136890951, "max_line_length": 120, "alphanum_fraction": 0.6754385965, "num_tokens": 4231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2760081986672223}}
{"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// Standard includes\n#include <fstream>\n#include <string>\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/staticsite.h>\n\nnamespace votca {\nnamespace xtp {\n\nEigen::Matrix3d StaticSite::CalculateCartesianMultipole() const {\n  // We are transforming here just quadrupoles\n  // const  Eigen::VectorXd& MP = _multipole;\n  const Vector9d& MP = _Q;\n  Eigen::Matrix3d theta = Eigen::Matrix3d::Zero();\n  if (_rank > 1) {\n    double sqr3 = std::sqrt(3);\n    theta(0, 0) = 0.5 * (-MP(4) + sqr3 * MP(7));     // theta_xx\n    theta(1, 1) = 0.5 * (-MP(4) - sqr3 * MP(7));     // theta_yy\n    theta(2, 2) = MP(4);                             // theta_zz\n    theta(0, 1) = theta(1, 0) = 0.5 * sqr3 * MP(8);  // theta_xy = theta_yx\n    theta(0, 2) = theta(2, 0) = 0.5 * sqr3 * MP(5);  // theta_xz = theta_zx\n    theta(1, 2) = theta(2, 1) = 0.5 * sqr3 * MP(6);  // theta_yz = theta_zy\n  }\n  return theta;\n}\n\nEigen::VectorXd StaticSite::CalculateSphericalMultipole(\n    const Eigen::Matrix3d& quad_cart) {\n  Eigen::VectorXd quadrupole_polar = Eigen::VectorXd::Zero(5);\n  const double sqr3 = std::sqrt(3);\n  quadrupole_polar(0) = quad_cart(2, 2);\n  quadrupole_polar(1) = (2. / sqr3) * quad_cart(0, 2);\n  quadrupole_polar(2) = (2. / sqr3) * quad_cart(1, 2);\n  quadrupole_polar(3) = (1. / sqr3) * (quad_cart(0, 0) - quad_cart(1, 1));\n  quadrupole_polar(4) = (2. / sqr3) * quad_cart(0, 1);\n  return quadrupole_polar;\n}\n\nvoid StaticSite::Rotate(const Eigen::Matrix3d& R,\n                        const Eigen::Vector3d& refPos) {\n  Eigen::Vector3d dir = _pos - refPos;\n  dir = R * dir;\n  _pos = refPos + dir;  // Rotated Position\n  if (_rank > 0) {\n    const Eigen::Vector3d temp = R * _Q.segment<3>(1);\n    _Q.segment<3>(1) = temp;\n  }\n  if (_rank > 1) {\n    Eigen::Matrix3d cartesianquad = CalculateCartesianMultipole();\n    Eigen::Matrix3d rotated = R * cartesianquad * R.transpose();\n    _Q.segment<5>(4) = CalculateSphericalMultipole(rotated);\n  }\n  return;\n}\n\nvoid StaticSite::Translate(const Eigen::VectorXd& shift) {\n  _pos += shift;\n  return;\n}\n\nstd::string StaticSite::writepolarization() const {\n  tools::Elements e;\n  double default_pol = 1;  // default is alway 1A^3\n  try {\n    default_pol =\n        e.getPolarizability(_element) * std::pow(tools::conv::nm2ang, 3);\n  } catch (const std::runtime_error&) {\n    ;\n  }\n  return (boost::format(\"     P %1$+1.7f\\n\") % default_pol).str();\n}\n\nstd::string StaticSite::WriteMpsLine(std::string unit) const {\n  double conv_pos = 1.;\n  if (unit == \"angstrom\") {\n    conv_pos = tools::conv::bohr2ang;\n  } else if (unit == \"bohr\") {\n    conv_pos = 1.;\n  } else {\n    throw std::runtime_error(\n        \" StaticSite::WriteMpsLine: Unit conversion not known\");\n  }\n  std::string output = \"\";\n  output += (boost::format(\" %1$2s %2$+1.7f %3$+1.7f %4$+1.7f Rank %5$d\\n\") %\n             _element % (_pos(0) * conv_pos) % (_pos(1) * conv_pos) %\n             (_pos(2) * conv_pos) % _rank)\n                .str();\n  output += (boost::format(\"    %1$+1.7f\\n\") % getCharge()).str();\n  if (_rank > 0) {\n    // Dipole z x y\n    output += (boost::format(\"    %1$+1.7f %2$+1.7f %3$+1.7f\\n\") % _Q(3) %\n               _Q(1) % _Q(2))\n                  .str();\n    if (_rank > 1) {\n      // Quadrupole 20 21c 21s 22c 22s\n      output +=\n          (boost::format(\"    %1$+1.7f %2$+1.7f %3$+1.7f %4$+1.7f %5$+1.7f\\n\") %\n           _Q(4) % _Q(5) % _Q(6) % _Q(7) % _Q(8))\n              .str();\n    }\n  }\n  // Polarizability\n  output += writepolarization();\n  return output;\n}\n\nvoid StaticSite::SetupCptTable(CptTable& table) const {\n  table.addCol(_id, \"index\", HOFFSET(data, id));\n  table.addCol(_element, \"type\", HOFFSET(data, element));\n\n  table.addCol(_pos[0], \"posX\", HOFFSET(data, posX));\n  table.addCol(_pos[1], \"posY\", HOFFSET(data, posY));\n  table.addCol(_pos[2], \"posZ\", HOFFSET(data, posZ));\n\n  table.addCol(_rank, \"rank\", HOFFSET(data, rank));\n\n  table.addCol(_Q[0], \"Q00\", HOFFSET(data, Q00));\n  table.addCol(_Q[1], \"Q11c\", HOFFSET(data, Q11c));\n  table.addCol(_Q[2], \"Q11s\", HOFFSET(data, Q11s));\n  table.addCol(_Q[3], \"Q10\", HOFFSET(data, Q10));\n  table.addCol(_Q[4], \"Q20\", HOFFSET(data, Q20));\n  table.addCol(_Q[5], \"Q21c\", HOFFSET(data, Q21c));\n  table.addCol(_Q[6], \"Q21s\", HOFFSET(data, Q21s));\n  table.addCol(_Q[7], \"Q22c\", HOFFSET(data, Q22c));\n  table.addCol(_Q[8], \"Q22s\", HOFFSET(data, Q22s));\n}\n\nvoid StaticSite::WriteData(data& d) const {\n  d.id = _id;\n  d.element = const_cast<char*>(_element.c_str());\n  d.posX = _pos[0];\n  d.posY = _pos[1];\n  d.posZ = _pos[2];\n\n  d.rank = _rank;\n\n  d.Q00 = _Q[0];\n  d.Q11c = _Q[1];\n  d.Q11s = _Q[2];\n  d.Q10 = _Q[3];\n  d.Q20 = _Q[4];\n  d.Q21c = _Q[5];\n  d.Q21s = _Q[6];\n  d.Q22c = _Q[7];\n  d.Q22s = _Q[8];\n}\n\nvoid StaticSite::ReadData(const data& d) {\n  _id = d.id;\n  _element = std::string(d.element);\n  free(d.element);\n  _pos[0] = d.posX;\n  _pos[1] = d.posY;\n  _pos[2] = d.posZ;\n\n  _rank = d.rank;\n\n  _Q[0] = d.Q00;\n  _Q[1] = d.Q11c;\n  _Q[2] = d.Q11s;\n  _Q[3] = d.Q10;\n  _Q[4] = d.Q20;\n  _Q[5] = d.Q21c;\n  _Q[6] = d.Q21s;\n  _Q[7] = d.Q22c;\n  _Q[8] = d.Q22s;\n}\n\n}  // namespace xtp\n}  // namespace votca\n", "meta": {"hexsha": "3a50ae69092a464cae9346fd76e54a839edfd5a5", "size": 5855, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/staticsite.cc", "max_stars_repo_name": "fossabot/xtp", "max_stars_repo_head_hexsha": "e82cc53f23e213d09da15da80ada6e32ac031a07", "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/staticsite.cc", "max_issues_repo_name": "fossabot/xtp", "max_issues_repo_head_hexsha": "e82cc53f23e213d09da15da80ada6e32ac031a07", "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/staticsite.cc", "max_forks_repo_name": "fossabot/xtp", "max_forks_repo_head_hexsha": "e82cc53f23e213d09da15da80ada6e32ac031a07", "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.7208121827, "max_line_length": 80, "alphanum_fraction": 0.5962425278, "num_tokens": 2110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2760081986672223}}
{"text": "#include <stdio.h>\n#include <cstdlib>\n#include <ctime>\n#include <fstream>\n#include <dirent.h>\n#include <iostream>\n#include <sstream>\n#include <string>\n\n#include \"stereo_sdf/SGMStereo.h\"\n#include \"stereo_sdf/utils.h\"\n\n#include <Eigen/Dense>\n\n// Headers from package stereo_utils.\n#include <stereo_utils/stereo_utils.hpp>\n#include <stereo_utils/Common.hpp>\n\nusing namespace std;\n\nusing JSON = nlohmann::json;\nnamespace su = stereo_utils;\n\n/* -------------------------- SET THESE PARAMETERS --------------------------- */\n/* stereo options */\n#define STEREO_FULL_PIPELINE -1\n#define STEREO_LEFT_ONLY      0\n\n/* cost volume update options */\n#define VOLUME_UPDATE_NAIVE   3\n#define VOLUME_UPDATE_DIFFB   2\n#define VOLUME_UPDATE_NEIGH   1\n#define VOLUME_UPDATE_NONE   -1\n\n/* image save flag */\n#define SAVE_IMAGES           1\n\n/* ground truth sampling option */\ndouble SAMPLING_FRACTION   = 0.50;\n\n/* disparity scaling factor (256 for KITTI) */\ndouble SCALING_FACTOR      = 256.0;\n\n/* --------------------------------------------------------------------------- */\n\n/* ------------ Type definition for interfacing the JSON file. --------------- */\n\nstruct CaseDescription {\n\tstd::string name    = \"\";   // Name of the test case.\n\tstd::string fn0     = \"\";   // Filename of image Ref.\n\tstd::string fn1     = \"\";   // Filename of image Tst.\n\tstd::string fnD     = \"\";   // Filename of the true disparity map.\n\tstd::string outDir  = \"\";   // Output directory.\n\tstd::string fnQ     = \"\";   // Filename of the Q matrix.\n\tfloat qFactor       = 1.0f; // Scale factor of Q.\n\tfloat dOffs         = 0.0f; // Disparity offset. Non-zero for Middlebury dataset. Zero for other datasets.\n    float distLimit     = 20.f; // The distance limit for point cloud generation.\n    double gtSampleFrac = 0.5;  // Ground truth sampling option.\n\n    SGMParams sgmParams = SGMParams();\n};\n\n/* --------------------------------------------------------------------------- */\n\nvoid SemiGlobalMatching(const cv::Mat &leftImage,\n                        const cv::Mat &rightImage,\n                        cv::Mat &dispImage,\n                        int STEREO_PIPELINE_MODE,\n                        const std::string cameraParamFile,\n                        cv::Mat depthImage,\n                        cv::Mat weightImg,\n                        int FUSE_FLAG,\n                        const SGMParams &sgmParams)\n{\n    png::image<png::rgb_pixel> leftImageSGM, rightImageSGM;\n    Utils utilities;\n    utilities.convertCVMatToPNG(leftImage, leftImageSGM);\n    utilities.convertCVMatToPNG(rightImage, rightImageSGM);\n    size_t width = leftImageSGM.get_width();\n    size_t height = leftImageSGM.get_height();\n    if (width != rightImageSGM.get_width() ||\n        height != rightImageSGM.get_height())\n    {\n        dispImage = cv::Mat1w();\n        return;\n    }\n    float* dispImageFloat = (float*)malloc(width*height*sizeof(float));\n    SGMStereo sgm;\n\n    // Configure the SGM method.\n    std::cout << \"P1 = \" << sgmParams.P1 << \", \"\n              << \"P2 = \" << sgmParams.P2 << \". \\n\";\n    sgm.setSmoothnessCostParameters( sgmParams.P1, sgmParams.P2 );\n    sgm.setDisparityTotal( sgmParams.total );\n\n    cv::Mat leftImageGray;\n    cv::cvtColor(leftImage, leftImageGray, CV_RGB2GRAY);\n    sgm.compute(leftImageSGM,\n                rightImageSGM,\n                dispImageFloat,\n                STEREO_PIPELINE_MODE,\n                cameraParamFile,\n                depthImage,\n                FUSE_FLAG,\n                leftImageGray,\n                weightImg);\n    dispImage = utilities.convertFloatToCVMat(width, height, dispImageFloat);\n    free(dispImageFloat);\n}\n\nvoid displayMinMax(cv::Mat array)\n{\n    double min, max;\n    cv::minMaxLoc(array, &min, &max);\n    std::cout << \"Minimum: \" << min << \" | Maximum: \" << max << std::endl;\n}\n\nstatic void save_ply( \n    const std::string &fn,\n    const Eigen::MatrixXf &Q,\n    const cv::Mat &dispFloat, \n    const cv::Mat &color,\n    float distLimit=20.f,\n    float dOffs=0.f ) {\n\n    cv::Mat dispFloat32;\n    dispFloat.convertTo(dispFloat32, CV_32FC1);\n\n    const bool flagFlip       = true; // Flip the point cloud so that the y-axis is upwards.\n    const bool flagBinary     = true; // Write binary PLY files.\n    const float distanceLimit = 20.f; // All points with depth greater than this value will be ignored.\n    cv::Mat predDispOffs      = dispFloat32 + dOffs; // This is required by Middlebury dataset. dOffs will be zero for other dataset.\n    su::write_ply_with_color(fn, \n        predDispOffs, color, \n        Q, flagFlip, distanceLimit, flagBinary);\n}\n\nstatic void process( const CaseDescription &cd ) {\n    /* input and output directories */\n    // std::string repo_dir = argv[1];\n    // std::string left_image_uri = repo_dir + \"imgs/stereo_left.png\";\n    // std::string right_image_uri = repo_dir + \"imgs/stereo_right.png\";\n    // std::string left_depth_uri = repo_dir + \"imgs/gt_disparity.png\";\n    // std::string save_dir = repo_dir + \"results/\";\n\n    std::string left_image_uri  = cd.fn0;\n    std::string right_image_uri = cd.fn1;\n    std::string left_depth_uri  = cd.fnD;\n    std::string save_dir        = cd.outDir + \"/\";\n\n    su::test_directory(save_dir);\n\n    Eigen::MatrixXf Q;\n    if ( cd.fnQ != \"\" ) {\n        su::read_matrix(cd.fnQ, 4, 4, \" \", Q);\n\n\t\t// Update the Q matrix according to the scale factor.\n\t\tQ(0, 3) *= cd.qFactor;\n\t\tQ(1, 3) *= cd.qFactor;\n\t\tQ(2, 3) *= cd.qFactor;\n    }\n\n    Utils utilities;\n\n    std::cout << \"DATA DETAILS: \" << std::endl;\n    std::cout << \"--- Left Image: \" << left_image_uri << std::endl;\n    std::cout << \"--- Right Image: \" << right_image_uri << std::endl;\n    std::cout << \"--- Disparity: (GT) \" << left_depth_uri << std::endl;\n\n    std::vector<int> compression_params;\n    compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);\n    compression_params.push_back(0);\n\n    cv::Mat left_image_clr = cv::imread(left_image_uri);\n    cv::Mat right_image_clr = cv::imread(right_image_uri);\n\n    cv::Mat_<double> disp_image = cv::imread(left_depth_uri,\n                                             cv::IMREAD_ANYDEPTH);\n    disp_image = disp_image / SCALING_FACTOR;\n    std::cout << \"{read status:} successfully read input images..\" << std::endl;\n\n    /* EVALUATION A: SEMI GLOBAL MATCHING */\n    std::cout << \"\\n{EVALUATION A:} -- SEMI GLOBAL MATCHING -- \" << std::endl;\n    cv::Mat disparity_image;\n    SemiGlobalMatching(left_image_clr,\n                       right_image_clr,\n                       disparity_image,\n                       STEREO_LEFT_ONLY,\n                       \"no_params_needed\",\n                       cv::Mat(),\n                       cv::Mat(),\n                       VOLUME_UPDATE_NONE,\n                       cd.sgmParams);\n    if (SAVE_IMAGES) {\n        std::string save_file_name = + \"sgm_default.png\";\n        std::string save_url = save_dir + save_file_name;\n        std::cout << \"{SGM} saving image to: \" << save_url << std::endl;\n        cv::imwrite(save_url, disparity_image, compression_params);\n    }\n\n    cv::Mat_<double> disp_SGM = disparity_image / SCALING_FACTOR;\n    /* evaluate SGM */\n    cv::Mat_<double> error_image_sgm;\n    double average_error_sgm;\n    cv::Mat sample_mask_sgm = cv::Mat::zeros(disp_SGM.rows,\n                                             disp_SGM.cols,\n                                             CV_32FC1);\n    utilities.calculateAccuracy(disp_SGM,\n                                disp_image,\n                                average_error_sgm,\n                                error_image_sgm,\n                                sample_mask_sgm);\n    std::cout << \"{SGM} avg error: \" << average_error_sgm << std::endl;\n\n    cv::Mat sample_mask;\n    // utilities.generateRandomSamplingMask(disp_image,\n    //                                      sample_mask,\n    //                                      SAMPLING_FRACTION);\n    utilities.generateRandomSamplingMask(disp_image,\n                                         sample_mask,\n                                         cd.gtSampleFrac);\n\n    if (SAVE_IMAGES) {\n        std::string save_file_name = \"sparse_mask.png\";\n        std::string save_url = save_dir + save_file_name;\n        std::cout << \"{MASK} saving image to: \" << save_url << std::endl;\n        cv::imwrite(save_url, sample_mask, compression_params);\n    }\n    cv::Mat masked_depth;\n    disp_image.copyTo(masked_depth, sample_mask);\n\n    // Save PLY file.\n    if ( cd.fnQ != \"\" ) {\n        std::string plyFn = save_dir + \"Cloud_SGM.ply\";\n        save_ply(plyFn, Q, \n            disp_SGM, left_image_clr, \n            cd.distLimit, cd.dOffs );\n        std::cout << \"Point cloud saved to \" << plyFn << \"\\n\";\n    }\n\n    /* EVALUATION B: USE SPARSE LIDAR POINTS FOR NAIVE FUSION */\n    std::cout << \"\\n{EVALUATION B:} -- NAIVE LIDAR FUSION -- \" << std::endl;\n    cv::Mat disparity_image_sl_naive;\n    SemiGlobalMatching(left_image_clr,\n                       right_image_clr,\n                       disparity_image_sl_naive,\n                       STEREO_LEFT_ONLY,\n                       \"no_params_needed\",\n                       masked_depth,\n                       cv::Mat(),\n                       VOLUME_UPDATE_NAIVE,\n                       cd.sgmParams);\n    if (SAVE_IMAGES) {\n        std::string save_file_name = \"fuse_naive.png\";\n        std::string save_url = save_dir + save_file_name;\n        std::cout << \"{Naive Fusion} saving image to: \" << save_url << std::endl;\n        cv::imwrite(save_url, disparity_image_sl_naive, compression_params);\n    }\n    cv::Mat_<double> disp_NF = disparity_image_sl_naive / SCALING_FACTOR;\n    /* evaluate naive fusion */\n    cv::Mat_<double> error_image_nf;\n    double average_error_nf;\n    utilities.calculateAccuracy(disp_NF,\n                                disp_image,\n                                average_error_nf,\n                                error_image_nf, sample_mask);\n    std::cout << \"{NAIVE FUSION} avg error: \" << average_error_nf << std::endl;\n\n    // Save PLY file.\n    if ( cd.fnQ != \"\" ) {\n        std::string plyFn = save_dir + \"Cloud_Naive.ply\";\n        save_ply(plyFn, Q, \n            disp_NF, left_image_clr, \n            cd.distLimit, cd.dOffs );\n        std::cout << \"Point cloud saved to \" << plyFn << \"\\n\";\n    }\n\n    /*EVALUATION C: USE DIFFUSION BASED METHOD */\n    std::cout << \"\\n{EVALUATION C:} -- DIFFUSION BASED -- \" << std::endl;\n    cv::Mat disparity_image_db;\n    SemiGlobalMatching(left_image_clr,\n                       right_image_clr,\n                       disparity_image_db,\n                       STEREO_LEFT_ONLY,\n                       \"no_params_needed\",\n                       masked_depth,\n                       cv::Mat(),\n                       VOLUME_UPDATE_DIFFB, \n                       cd.sgmParams);\n    if (SAVE_IMAGES) {\n        std::string save_file_name = \"fuse_diffusionbased.png\";\n        std::string save_url = save_dir + save_file_name;\n        std::cout << \"{DB} saving image to: \" << save_url << std::endl;\n        cv::imwrite(save_url, disparity_image_db, compression_params);\n    }\n    cv::Mat_<double> disp_DB = disparity_image_db / SCALING_FACTOR;\n    /* evaluate diffusion based confidence propagation method */\n    cv::Mat_<double> error_image_db;\n    double average_error_db;\n    utilities.calculateAccuracy(disp_DB,\n                                disp_image,\n                                average_error_db,\n                                error_image_db,\n                                sample_mask);\n    std::cout << \"{DB} avg error: \" << average_error_db << std::endl;\n\n    // Save PLY file.\n    if ( cd.fnQ != \"\" ) {\n        std::string plyFn = save_dir + \"Cloud_Diffusion.ply\";\n        save_ply(plyFn, Q, \n            disp_DB, left_image_clr, \n            cd.distLimit, cd.dOffs );\n        std::cout << \"Point cloud saved to \" << plyFn << \"\\n\";\n    }\n\n    /*EVALUATION D: USE BASIC BILATERAL COST UPDATE */\n    std::cout << \"\\n{EVALUATION D:} -- NEIGHBORHOOD SUPPORT -- \" << std::endl;\n    cv::Mat disparity_image_ns;\n    SemiGlobalMatching(left_image_clr,\n                       right_image_clr,\n                       disparity_image_ns,\n                       STEREO_LEFT_ONLY,\n                       \"no_params_needed\",\n                       masked_depth,\n                       cv::Mat(),\n                       VOLUME_UPDATE_NEIGH, \n                       cd.sgmParams);\n    if (SAVE_IMAGES) {\n        std::string save_file_name = \"fuse_neighborhoodsupport.png\";\n        std::string save_url = save_dir + save_file_name;\n        std::cout << \"{NS} saving image to: \" << save_url << std::endl;\n        cv::imwrite(save_url, disparity_image_ns, compression_params);\n    }\n    cv::Mat_<double> disp_NS = disparity_image_ns / SCALING_FACTOR;\n    /* evaluate neighborhood support method */\n    cv::Mat_<double> error_image_ns;\n    double average_error_ns;\n    utilities.calculateAccuracy(disp_NS,\n                                disp_image,\n                                average_error_ns,\n                                error_image_ns,\n                                sample_mask);\n    std::cout << \"{NS} avg error: \" << average_error_ns << std::endl;\n\n    // Save PLY file.\n    if ( cd.fnQ != \"\" ) {\n        std::string plyFn = save_dir + \"Cloud_Neighbor.ply\";\n        save_ply(plyFn, Q, \n            disp_NS, left_image_clr, \n            cd.distLimit, cd.dOffs );\n        std::cout << \"Point cloud saved to \" << plyFn << \"\\n\";\n    }\n}\n\nint main(int argc, char** argv)\n{\n    if ( argc < 2 ) {\n\t\tstd::cerr << \"Must specify the input JSON file. \\n\";\n\t\tthrow std::runtime_error(\"Must specify the input JSON file. \");\n\t}\n\n\t// Read the JSON file.\n\tstd::shared_ptr<JSON> pJSON = su::read_json(argv[1]);\n\tauto& cases = (*pJSON)[\"cases\"];\n\tconst int N = cases.size();\n\n\t// Process all the cases.\n\tfor ( int i = 0; i < N; ++i ) {\n        if ( true != cases[i][\"enable\"] )\n            continue;\n\n\t\tauto cd = CaseDescription();\n\t\tcd.fn0  = cases[i][\"fn0\"]; // Filename of image 0.\n\t\tcd.fn1  = cases[i][\"fn1\"]; // Filename of image 1.\n\n\t\t// True disparity if exists.\n\t\tcd.fnD = cases[i][\"fnD\"];\n\n\t\tcd.name         = cases[i][\"name\"];         // Case name.\n        cd.gtSampleFrac = cases[i][\"gtSampleFrac\"]; // The true data sample fraction.\n\n        std::stringstream ss;\n        std::string tempDir = cases[i][\"outDir\"]; // This strips the double quotes.\n        ss << tempDir << \"/\" << cd.name << \"_\" << cd.gtSampleFrac;\n        cd.outDir = ss.str(); // Output directory.\n\n\t\t// Q matrix if exists.\n\t\tif ( cases[i].find(\"fnQ\") != cases[i].end() ) {\n\t\t\tcd.fnQ       = cases[i][\"fnQ\"];\n\t\t\tcd.qFactor   = cases[i][\"QF\"];\n\t\t\tcd.dOffs     = cases[i][\"dOffs\"];\n            cd.distLimit = cases[i][\"distLimit\"];\n\t\t} else {\n\t\t\tcd.fnQ       = \"\";\n\t\t\tcd.qFactor   = 1.f;\n\t\t\tcd.dOffs     = 0.f;\n            cd.distLimit = 20.f;\n\t\t}\n\n        // SGM parameters.\n        cd.sgmParams.P1    = cases[i][\"sgm\"][\"P1\"];\n        cd.sgmParams.P2    = cases[i][\"sgm\"][\"P2\"];\n        cd.sgmParams.total = cases[i][\"sgm\"][\"total\"];\n\n\t\tstd::cout << \"\\n========== Procesing \" << cd.name << \"_\" << cd.gtSampleFrac << \". ==========\\n\\n\";\n\t\tprocess( cd );\n\t}\n\n\tstd::cout << \"SPS-Stereo done. \\n\";\n\n    return 0;\n}\n", "meta": {"hexsha": "d93463925c3dad03cb87d75028db9dd79268f832", "size": 15156, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "stereo_sparse_depth_fusion/src/stereo_depth_fusion.cpp", "max_stars_repo_name": "huyaoyu/Tutorial2020_Stereo_ROS", "max_stars_repo_head_hexsha": "32f7427b597ac01674a36a19b8439844d1ea291b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-10-27T03:12:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T07:04:34.000Z", "max_issues_repo_path": "stereo_sparse_depth_fusion/src/stereo_depth_fusion.cpp", "max_issues_repo_name": "huyaoyu/Tutorial2020_Stereo_ROS", "max_issues_repo_head_hexsha": "32f7427b597ac01674a36a19b8439844d1ea291b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stereo_sparse_depth_fusion/src/stereo_depth_fusion.cpp", "max_forks_repo_name": "huyaoyu/Tutorial2020_Stereo_ROS", "max_forks_repo_head_hexsha": "32f7427b597ac01674a36a19b8439844d1ea291b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-08-14T23:05:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T11:31:22.000Z", "avg_line_length": 36.6973365617, "max_line_length": 133, "alphanum_fraction": 0.5558194774, "num_tokens": 3736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.2759745958884768}}
{"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/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/two_dimensional_spectra_config.hpp\"\n#include \"heom/sites_to_states.hpp\"\n\nnamespace bmt = ::heom::bmt;\nnamespace num = ::heom::num;\nnamespace ocl = ::heom::ocl;\nusing heom::int_t;\nusing heom::real_t;\nusing heom::complex_t;\nusing heom::real_format;\nusing heom::default_delimiter;\nusing heom::complex_matrix_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::two_dimensional_spectra_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\tconst int_t steps_per_iteration = heom_config.program_observe_steps();\n\t\tconst int_t t_1_iterations = heom_config.spectra_steps_t_1() / heom_config.program_observe_steps(); // not including zero\n\t\tconst int_t t_3_iterations = heom_config.spectra_steps_t_3() / heom_config.program_observe_steps() + 1; // including 0 and max_steps 0 : steps_per_iteration : spectra_t_3_steps\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// output data structure for traces\n\t\tconst int_t num_t_1_observations = t_1_iterations + 1;\n\t\tconst int_t num_t_3_observations = t_3_iterations;\n\n\t\t// pre-allocate t_3 x t_1 sized 2d vector for accumulating the observations\n\t\t//std::vector<std::vector<heom::matrix_trace_observation_view>> observations(num_t_3_observations);\n\t\tstd::vector<std::vector<complex_t>> observations(num_t_3_observations);\n\t\tfor (auto& vec : observations) {\n\t\t\tvec.resize(num_t_1_observations, complex_t(0.0, 0.0));\n\t\t}\n\n//\t\tstd::cout << \"Coupling identity: \" << heom::state_baths_coupling(heom_config.baths_coupling(), heom::sites_to_states_mode_t::identity) << std::endl;\n//\t\tstd::cout << \"Coupling with ground state: \" << heom::state_baths_coupling(heom_config.baths_coupling(), heom::sites_to_states_mode_t::with_ground_state) << std::endl;\n//\t\tstd::cout << \"Coupling excited state absorption: \" << heom::state_baths_coupling(heom_config.baths_coupling(), heom::sites_to_states_mode_t::excited_state_absorption) << std::endl;\n//\n//\t\tstd::cout << \"Hamiltonian identity: \" << heom::state_hamiltonian(heom_config.system_hamiltonian(), heom::sites_to_states_mode_t::identity) << std::endl;\n//\t\tstd::cout << \"Hamiltonian with ground state: \" << heom::state_hamiltonian(heom_config.system_hamiltonian(), heom::sites_to_states_mode_t::with_ground_state) << std::endl;\n//\t\tstd::cout << \"Hamiltonian excited state absorption: \" << heom::state_hamiltonian(heom_config.system_hamiltonian(), heom::sites_to_states_mode_t::excited_state_absorption) << std::endl;\n\n\n\t\tconst auto& pathways = heom_config.spectra_pathways().get();\n\n\t\t// for progress estimate\n\t\tconst size_t solver_runs = pathways.size() * heom_config.dipole_tensor_prefactors().size() * t_3_iterations;\n\t\tsize_t solver_run = 0;\n\n\t\t// iterate over pathways\n\t\tfor (size_t p = 0; p < pathways.size(); ++p)\n\t\t{\n\t\t\tDEBUG_ONLY( std::cout << \"Pathway \" << p << \" is \" << pathways.at(p) << std::endl; )\n\t\t\tconst auto& pathway_spec = heom::spectra_pathway_to_specification.at(pathways[p]);\n\t\t\tconst auto sts_mode = pathway_spec.sites_to_states_mode();\n\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\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\n\t\t\tfor (size_t tensor_index = 0; tensor_index < heom_config.dipole_tensor_prefactors().size(); ++tensor_index) {\n\t\t\t\tfor (int_t t_3_index = 0; t_3_index < t_3_iterations; ++t_3_index) {\n\t\t\t\t\tconst int_t t_3 = t_3_index * steps_per_iteration;\n\n\t\t\t\t\t// re-init instance\n\t\t\t\t\theom_instance.null_hierarchy();\n\t\t\t\t\theom_instance.set_hierarchy_top();\n\t\t\t\t\t// re-init solver\n\t\t\t\t\tsolver.reset();\n\t\t\t\t\t++solver_run; // for progress estimate\n\n\t\t\t\t\t// TODO: optimise: multiply top only on host-side (synchronise host/device!) => think through where possible\n\t\t\t\t\tauto get_dipole_matrix = [&](size_t spec_index) {\n\t\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\t};\n\n\t\t\t\t\t// lambda for generic dipole multiplication with plus/minus, from left/right\n\t\t\t\t\tauto dipole_mult = [&](size_t spec_index) {\n\t\t\t\t\t\tconst auto dipole_matrix = get_dipole_matrix(spec_index);\n\n\t\t\t\t\t\t// multiple from left or right on hierarchy according to pathway specification\n\t\t\t\t\t\tif (pathway_spec.pathway()[spec_index].second ==\n\t\t\t\t\t\t    heom::pathway_dipole_side_t::left)\n\t\t\t\t\t\t\tsolver.hierarchy_mmult_left(dipole_matrix.data());\n\t\t\t\t\t\telse // must be right\n\t\t\t\t\t\t\tsolver.hierarchy_mmult_right(dipole_matrix.data());\n\t\t\t\t\t};\n\n\t\t\t\t\t// first dipole multiplication from specification\n\t\t\t\t\tdipole_mult(0);\n\n\t\t\t\t\t// propagate t_3 steps\n\t\t\t\t\tsolver.step_forward(t_3);\n\n\t\t\t\t\t// second dipole multiplication from specification\n\t\t\t\t\tdipole_mult(1);\n\n\t\t\t\t\t// propagate delay steps\n\t\t\t\t\tsolver.step_forward(heom_config.spectra_steps_t_delay());\n\n\t\t\t\t\t// third dipole multiplication from specification\n\t\t\t\t\tdipole_mult(2);\n\n\t\t\t\t\t// propagate additional t_1 steps and observe\n\n\t\t\t\t\t// setup observer with pre-scaled dipole matrix\n\t\t\t\t\tauto dipole_matrix = get_dipole_matrix(3);\n\t\t\t\t\tdipole_matrix.scale(heom::get_dipole_tensor_prefactor(pathway_spec, heom_config, tensor_index));\n\t\t\t\t\theom::matrix_trace_observer<solver_t> trace_observer(complete_graph, solver, dipole_matrix.data()); // use last (fourth) polarization for trace, i.e. index 3\n\n\t\t\t\t\t// generate first observation with initial value\n\t\t\t\t\tobservations[t_3_index][0] += trace_observer.observe_trace(0.0).trace();\n\n\t\t\t\t\tfor (int_t t_1_index = 0; t_1_index < t_1_iterations; ++t_1_index) {\n\t\t\t\t\t\t// propagate\n\t\t\t\t\t\tsolver.step_forward(steps_per_iteration);\n\n\t\t\t\t\t\t// after propagation, we are at:\n\t\t\t\t\t\tconst auto current_step = (t_1_index + 1) * steps_per_iteration;\n\t\t\t\t\t\tconst real_t current_time = current_step * heom_config.solver_step_size();\n\n\t\t\t\t\t\t// observe\n\t\t\t\t\t\tobservations[t_3_index][t_1_index + 1] += trace_observer.observe_trace(current_time).trace();\n\n\t\t\t\t\t\t// update status\n\t\t\t\t\t\tif(!command_line.no_progress())\n\t\t\t\t\t\t\theom::write_progress(current_step - 1, heom_config.spectra_steps_t_1(), solver_run, solver_runs, \"Calculating two dimensional spectra: \", std::cout);\n\t\t\t\t\t} // t_1\n\t\t\t\t} // t_3\n\t\t\t} // tensor_index\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\t\t} // pathways\n\n\n\t\t// TODO: re-enable\n\t\t// average traces\n//\t\tfor (auto& vec : observations)\n//\t\t\tfor (auto& elem : vec)\n//\t\t\t\telem = { elem.real() / num_dipole_matrices, elem.imag() / num_dipole_matrices };\n//\t\t\t\t//elem.avg(num_dipole_matrices);\n\n\t\t// write traces\n\t\tauto format = real_format;\n\t\tobservation_file << \"t_3\" << default_delimiter << \"t_1\" << default_delimiter << \"trace_real\" << default_delimiter << \"trace_imag\" << std::endl;\n\t\tfor (int_t t_3_index = 0; t_3_index < num_t_3_observations; ++t_3_index) {\n\t\t\tfor (int_t t_1_index = 0; t_1_index < num_t_1_observations; ++t_1_index) {\n\t\t\t\tconst auto& current_obs = observations[t_3_index][t_1_index];\n\t\t\t\tobservation_file << format % (t_3_index * steps_per_iteration * heom_config.solver_step_size());\n\t\t\t\tobservation_file << default_delimiter;\n\t\t\t\tobservation_file << format % (t_1_index * steps_per_iteration * heom_config.solver_step_size());\n\t\t\t\tobservation_file << default_delimiter;\n\t\t\t\tobservation_file << format % current_obs.real();\n\t\t\t\tobservation_file << default_delimiter;\n\t\t\t\tobservation_file << format % current_obs.imag();\n\t\t\t\tobservation_file << '\\n';\n\t\t\t}\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_thermal_state.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_thermal_state.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\") % (bicgstab.ocl_helper().allocated_byte_max() / 1024.0 / 1024.0)\n//\t\t          << \" (\"\n//\t\t          << boost::format(\"count: %6i\") % bicgstab.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": "29aab29b0c6728bc7e1f78591b04dabc2718555b", "size": 12110, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dm-heom/src/app_two_dimensional_spectra.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_two_dimensional_spectra.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_two_dimensional_spectra.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": 46.398467433, "max_line_length": 188, "alphanum_fraction": 0.6778695293, "num_tokens": 3242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.2759745958884768}}
{"text": "#include <iostream>\n#include <boost/numeric/conversion/cast.hpp>\n\n\nint main()\n{\n// this is fine\n    const auto s1 = boost::numeric_cast<unsigned short>(42);\n    std::cout << \"boost::numeric_cast<unsigned short>(42) = \" << s1 << \"\\n\";\n\n// this will throw\n    try{\n        const auto s2 = boost::numeric_cast<unsigned>(-1);\n        (void)s2;\n    }\n    catch(const boost::numeric::bad_numeric_cast& e){\n        std::cout << e.what() << \"\\n\";\n    }\n\n// so will this\n    try{\n        const auto s3 = boost::numeric_cast<unsigned short>(100000);\n        (void)s3;\n    }\n    catch(const boost::numeric::positive_overflow& e){\n        std::cout << e.what() << \"\\n\";\n    }\n\n// exception types:\n    // boost::numeric::positive_overflow;\n    // boost::numeric::negative_overflow;\n    // boost::numeric::bad_numeric_cast;\n}\n", "meta": {"hexsha": "4fe70f06f60babbaf4dd82ecdf6087e89f661c0b", "size": 812, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Ch2_ConvertingData/numeric_cast.cpp", "max_stars_repo_name": "jeremimucha/Boost-Cpp-App-Dev-Cookbook", "max_stars_repo_head_hexsha": "bc700281b38ab3ef4fa9d19801ee15b3ea4bc978", "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": "Ch2_ConvertingData/numeric_cast.cpp", "max_issues_repo_name": "jeremimucha/Boost-Cpp-App-Dev-Cookbook", "max_issues_repo_head_hexsha": "bc700281b38ab3ef4fa9d19801ee15b3ea4bc978", "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": "Ch2_ConvertingData/numeric_cast.cpp", "max_forks_repo_name": "jeremimucha/Boost-Cpp-App-Dev-Cookbook", "max_forks_repo_head_hexsha": "bc700281b38ab3ef4fa9d19801ee15b3ea4bc978", "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.8823529412, "max_line_length": 76, "alphanum_fraction": 0.5948275862, "num_tokens": 212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.27590740667197156}}
{"text": "//\r\n//  Copyright (c) 2000-2002\r\n//  Joerg Walter, Mathias Koch\r\n//\r\n//  Permission to use, copy, modify, distribute and sell this software\r\n//  and its documentation for any purpose is hereby granted without fee,\r\n//  provided that the above copyright notice appear in all copies and\r\n//  that both that copyright notice and this permission notice appear\r\n//  in supporting documentation.  The authors make no representations\r\n//  about the suitability of this software for any purpose.\r\n//  It is provided \"as is\" without express or implied warranty.\r\n//\r\n//  The authors gratefully acknowledge the support of\r\n//  GeNeSys mbH & Co. KG in producing this work.\r\n//\r\n\r\n#ifndef BOOST_UBLAS_TRAITS_H\r\n#define BOOST_UBLAS_TRAITS_H\r\n\r\n#include <algorithm>\r\n#include <cmath>\r\n#include <complex>\r\n\r\n#include <boost/numeric/ublas/config.hpp>\r\n\r\n// Promote traits borrowed from Todd Veldhuizen\r\n\r\nnamespace boost { namespace numeric { namespace ublas {\r\n\r\n    template<class T>\r\n    struct type_traits {\r\n        typedef type_traits<T> self_type;\r\n        typedef T value_type;\r\n        typedef const T &const_reference;\r\n        typedef T &reference;\r\n        typedef T real_type;\r\n        typedef T precision_type;\r\n\r\n        BOOST_STATIC_CONSTANT (std::size_t, plus_complexity = 0);\r\n        BOOST_STATIC_CONSTANT (std::size_t, multiplies_complexity = 0);\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type real (const_reference t);\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type imag (const_reference t);\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type conj (const_reference t);\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type abs (const_reference t);\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type sqrt (const_reference t);\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_1 (const_reference t) {\r\n            // Oops, should have known that!\r\n            return type_traits<real_type>::abs (self_type::real (t)) +\r\n                   type_traits<real_type>::abs (self_type::imag (t));\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_2 (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_inf (const_reference t) {\r\n            // Oops, should have known that!\r\n            return std::max (type_traits<real_type>::abs (self_type::real (t)),\r\n                             type_traits<real_type>::abs (self_type::imag (t)));\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        bool equals (const_reference t1, const_reference t2) {\r\n            // Check, that the values match at least half.\r\n            static real_type sqrt_epsilon (type_traits<real_type>::sqrt (std::numeric_limits<real_type>::epsilon ()));\r\n            return self_type::norm_inf (t1 - t2) < sqrt_epsilon *\r\n                   std::max (std::max (self_type::norm_inf (t1),\r\n                                       self_type::norm_inf (t2)),\r\n                             std::numeric_limits<real_type>::min ());\r\n        }\r\n    };\r\n\r\n    template<>\r\n    struct type_traits<float> {\r\n        typedef type_traits<float> self_type;\r\n        typedef float value_type;\r\n        typedef float const_reference;\r\n        typedef float &reference;\r\n        typedef float real_type;\r\n        typedef double precision_type;\r\n\r\n        BOOST_STATIC_CONSTANT (std::size_t, plus_complexity = 1);\r\n        BOOST_STATIC_CONSTANT (std::size_t, multiplies_complexity = 1);\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type real (const_reference t) {\r\n                return t;\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type imag (const_reference t) {\r\n                return 0;\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type conj (const_reference t) {\r\n                return t;\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type abs (const_reference t) {\r\n#if defined (BOOST_NO_STDC_NAMESPACE) || defined (BOOST_UBLAS_NO_CMATH)\r\n            return ::fabsf (t);\r\n#else\r\n            return std::abs (t);\r\n#endif\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type sqrt (const_reference t) {\r\n#if defined (BOOST_NO_STDC_NAMESPACE) || defined (BOOST_UBLAS_NO_CMATH)\r\n            return ::sqrtf (t);\r\n#else\r\n            return std::sqrt (t);\r\n#endif\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_1 (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_2 (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_inf (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        bool equals (const_reference t1, const_reference t2) {\r\n            // Check, that the values match at least half.\r\n            static real_type sqrt_epsilon (type_traits<real_type>::sqrt (std::numeric_limits<real_type>::epsilon ()));\r\n            return self_type::norm_inf (t1 - t2) < sqrt_epsilon *\r\n                   std::max (std::max (self_type::norm_inf (t1),\r\n                                       self_type::norm_inf (t2)),\r\n                             std::numeric_limits<real_type>::min ());\r\n        }\r\n    };\r\n    template<>\r\n    struct type_traits<double> {\r\n        typedef type_traits<double> self_type;\r\n        typedef double value_type;\r\n        typedef double const_reference;\r\n        typedef double &reference;\r\n        typedef double real_type;\r\n#ifndef BOOST_UBLAS_USE_LONG_DOUBLE\r\n        typedef double precision_type;\r\n#else\r\n        typedef long double precision_type;\r\n#endif\r\n\r\n        BOOST_STATIC_CONSTANT (std::size_t, plus_complexity = 1);\r\n        BOOST_STATIC_CONSTANT (std::size_t, multiplies_complexity = 1);\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type real (const_reference t) {\r\n                return t;\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type imag (const_reference t) {\r\n                return 0;\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type conj (const_reference t) {\r\n                return t;\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type abs (const_reference t) {\r\n#if defined (BOOST_NO_STDC_NAMESPACE) || defined (BOOST_UBLAS_NO_CMATH)\r\n            return ::fabs (t);\r\n#else\r\n            return std::abs (t);\r\n#endif\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type sqrt (const_reference t) {\r\n#if defined (BOOST_NO_STDC_NAMESPACE) || defined (BOOST_UBLAS_NO_CMATH)\r\n            return ::sqrt (t);\r\n#else\r\n            return std::sqrt (t);\r\n#endif\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_1 (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_2 (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_inf (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        bool equals (const_reference t1, const_reference t2) {\r\n            // Check, that the values match at least half.\r\n            static real_type sqrt_epsilon (type_traits<real_type>::sqrt (std::numeric_limits<real_type>::epsilon ()));\r\n            return self_type::norm_inf (t1 - t2) < sqrt_epsilon *\r\n                   std::max (std::max (self_type::norm_inf (t1),\r\n                                       self_type::norm_inf (t2)),\r\n                             std::numeric_limits<real_type>::min ());\r\n        }\r\n    };\r\n#ifdef BOOST_UBLAS_USE_LONG_DOUBLE\r\n    template<>\r\n    struct type_traits<long double> {\r\n        typedef type_traits<long double> self_type;\r\n        typedef long double value_type;\r\n        typedef long double const_reference;\r\n        typedef long double &reference;\r\n        typedef long double real_type;\r\n        typedef long double precision_type;\r\n\r\n        BOOST_STATIC_CONSTANT (std::size_t, plus_complexity = 1);\r\n        BOOST_STATIC_CONSTANT (std::size_t, multiplies_complexity = 1);\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type real (const_reference t) {\r\n                return t;\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type imag (const_reference t) {\r\n                return 0;\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type conj (const_reference t) {\r\n                return t;\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type abs (const_reference t) {\r\n#if defined (BOOST_NO_STDC_NAMESPACE) || defined (BOOST_UBLAS_NO_CMATH)\r\n            return ::fabsl (t);\r\n#else\r\n            return std::abs (t);\r\n#endif\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type sqrt (const_reference t) {\r\n#if defined (BOOST_NO_STDC_NAMESPACE) || defined (BOOST_UBLAS_NO_CMATH)\r\n            return ::sqrtl (t);\r\n#else\r\n            return std::sqrt (t);\r\n#endif\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_1 (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_2 (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_inf (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        bool equals (const_reference t1, const_reference t2) {\r\n            // Check, that the values match at least half.\r\n            static real_type sqrt_epsilon (type_traits<real_type>::sqrt (std::numeric_limits<real_type>::epsilon ()));\r\n            return self_type::norm_inf (t1 - t2) < sqrt_epsilon *\r\n                   std::max (std::max (self_type::norm_inf (t1),\r\n                                       self_type::norm_inf (t2)),\r\n                             std::numeric_limits<real_type>::min ());\r\n        }\r\n    };\r\n#endif\r\n\r\n    template<>\r\n    struct type_traits<std::complex<float> > {\r\n        typedef type_traits<std::complex<float> > self_type;\r\n        typedef std::complex<float> value_type;\r\n        typedef const std::complex<float> &const_reference;\r\n        typedef std::complex<float> &reference;\r\n        typedef float real_type;\r\n        typedef std::complex<double> precision_type;\r\n\r\n        BOOST_STATIC_CONSTANT (std::size_t, plus_complexity = 2);\r\n        BOOST_STATIC_CONSTANT (std::size_t, multiplies_complexity = 6);\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type real (const_reference t) {\r\n                // return t.real ();\r\n                return std::real (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type imag (const_reference t) {\r\n                // return t.imag ();\r\n                return std::imag (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type conj (const_reference t) {\r\n                // return t.conj ();\r\n                return std::conj (t);\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type abs (const_reference t) {\r\n                return std::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type sqrt (const_reference t) {\r\n                return std::sqrt (t);\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_1 (const_reference t) {\r\n            // Oops, should have known that!\r\n            return type_traits<real_type>::abs (self_type::real (t)) +\r\n                   type_traits<real_type>::abs (self_type::imag (t));\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_2 (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_inf (const_reference t) {\r\n            // Oops, should have known that!\r\n            return std::max (type_traits<real_type>::abs (self_type::real (t)),\r\n                             type_traits<real_type>::abs (self_type::imag (t)));\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        bool equals (const_reference t1, const_reference t2) {\r\n            // Check, that the values match at least half.\r\n            static real_type sqrt_epsilon (type_traits<real_type>::sqrt (std::numeric_limits<real_type>::epsilon ()));\r\n            return self_type::norm_inf (t1 - t2) < sqrt_epsilon *\r\n                   std::max (std::max (self_type::norm_inf (t1),\r\n                                       self_type::norm_inf (t2)),\r\n                             std::numeric_limits<real_type>::min ());\r\n        }\r\n    };\r\n    template<>\r\n    struct type_traits<std::complex<double> > {\r\n        typedef type_traits<std::complex<double> > self_type;\r\n        typedef std::complex<double> value_type;\r\n        typedef const std::complex<double> &const_reference;\r\n        typedef std::complex<double> &reference;\r\n        typedef double real_type;\r\n#ifndef BOOST_UBLAS_USE_LONG_DOUBLE\r\n        typedef std::complex<double> precision_type;\r\n#else\r\n        typedef std::complex<long double> precision_type;\r\n#endif\r\n\r\n        BOOST_STATIC_CONSTANT (std::size_t, plus_complexity = 2);\r\n        BOOST_STATIC_CONSTANT (std::size_t, multiplies_complexity = 6);\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type real (const_reference t) {\r\n                // return t.real ();\r\n                return std::real (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type imag (const_reference t) {\r\n                // return t.imag ();\r\n                return std::imag (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type conj (const_reference t) {\r\n                // return t.conj ();\r\n                return std::conj (t);\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type abs (const_reference t) {\r\n                return std::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type sqrt (const_reference t) {\r\n                return std::sqrt (t);\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_1 (const_reference t) {\r\n            // Oops, should have known that!\r\n            return type_traits<real_type>::abs (self_type::real (t)) +\r\n                   type_traits<real_type>::abs (self_type::imag (t));\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_2 (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_inf (const_reference t) {\r\n            // Oops, should have known that!\r\n            return std::max (type_traits<real_type>::abs (self_type::real (t)),\r\n                             type_traits<real_type>::abs (self_type::imag (t)));\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        bool equals (const_reference t1, const_reference t2) {\r\n            // Check, that the values match at least half.\r\n            static real_type sqrt_epsilon (type_traits<real_type>::sqrt (std::numeric_limits<real_type>::epsilon ()));\r\n            return self_type::norm_inf (t1 - t2) < sqrt_epsilon *\r\n                   std::max (std::max (self_type::norm_inf (t1),\r\n                                       self_type::norm_inf (t2)),\r\n                             std::numeric_limits<real_type>::min ());\r\n        }\r\n    };\r\n#ifdef BOOST_UBLAS_USE_LONG_DOUBLE\r\n    template<>\r\n    struct type_traits<std::complex<long double> > {\r\n        typedef type_traits<std::complex<long double> > self_type;\r\n        typedef std::complex<long double> value_type;\r\n        typedef const std::complex<long double> &const_reference;\r\n        typedef std::complex<long double> &reference;\r\n        typedef long double real_type;\r\n        typedef std::complex<long double> precision_type;\r\n\r\n        BOOST_STATIC_CONSTANT (std::size_t, plus_complexity = 2);\r\n        BOOST_STATIC_CONSTANT (std::size_t, multiplies_complexity = 6);\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type real (const_reference t) {\r\n                // return t.real ();\r\n                return std::real (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type imag (const_reference t) {\r\n                // return t.imag ();\r\n                return std::imag (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type conj (const_reference t) {\r\n                // return t.conj ();\r\n                return std::conj (t);\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type abs (const_reference t) {\r\n                return std::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type sqrt (const_reference t) {\r\n                return std::sqrt (t);\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_1 (const_reference t) {\r\n            // Oops, should have known that!\r\n            return type_traits<real_type>::abs (self_type::real (t)) +\r\n                   type_traits<real_type>::abs (self_type::imag (t));\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_2 (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_inf (const_reference t) {\r\n            // Oops, should have known that!\r\n            return std::max (type_traits<real_type>::abs (self_type::real (t)),\r\n                             type_traits<real_type>::abs (self_type::imag (t)));\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        bool equals (const_reference t1, const_reference t2) {\r\n            // Check, that the values match at least half.\r\n            static real_type sqrt_epsilon (type_traits<real_type>::sqrt (std::numeric_limits<real_type>::epsilon ()));\r\n            return self_type::norm_inf (t1 - t2) < sqrt_epsilon *\r\n                   std::max (std::max (self_type::norm_inf (t1),\r\n                                       self_type::norm_inf (t2)),\r\n                             std::numeric_limits<real_type>::min ());\r\n        }\r\n    };\r\n#endif\r\n\r\n    template<class T1, class T2>\r\n    struct promote_traits {\r\n        // Default promotion will badly fail, if the types are different.\r\n        // Thanks to Kresimir Fresl for spotting this.\r\n        BOOST_STATIC_ASSERT ((boost::is_same<T1, T2>::value));\r\n        typedef T1 promote_type;\r\n    };\r\n\r\n    template<>\r\n    struct promote_traits<float, double> {\r\n        typedef double promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<double, float> {\r\n        typedef double promote_type;\r\n    };\r\n#ifdef BOOST_UBLAS_USE_LONG_DOUBLE\r\n    template<>\r\n    struct promote_traits<float, long double> {\r\n        typedef long double promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<long double, float> {\r\n        typedef long double promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<double, long double> {\r\n        typedef long double promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<long double, double> {\r\n        typedef long double promote_type;\r\n    };\r\n#endif\r\n\r\n    template<>\r\n    struct promote_traits<float, std::complex<float> > {\r\n        typedef std::complex<float> promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<std::complex<float>, float> {\r\n        typedef std::complex<float> promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<float, std::complex<double> > {\r\n        typedef std::complex<double> promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<std::complex<double>, float> {\r\n        typedef std::complex<double> promote_type;\r\n    };\r\n#ifdef BOOST_UBLAS_USE_LONG_DOUBLE\r\n    template<>\r\n    struct promote_traits<float, std::complex<long double> > {\r\n        typedef std::complex<long double> promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<std::complex<long double>, float> {\r\n        typedef std::complex<long double> promote_type;\r\n    };\r\n#endif\r\n\r\n    template<>\r\n    struct promote_traits<double, std::complex<float> > {\r\n        // Here we'd better go the conservative way.\r\n        // typedef std::complex<float> promote_type;\r\n        typedef std::complex<double> promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<std::complex<float>, double> {\r\n        // Here we'd better go the conservative way.\r\n        // typedef std::complex<float> promote_type;\r\n        typedef std::complex<double> promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<double, std::complex<double> > {\r\n        typedef std::complex<double> promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<std::complex<double>, double> {\r\n        typedef std::complex<double> promote_type;\r\n    };\r\n#ifdef BOOST_UBLAS_USE_LONG_DOUBLE\r\n    template<>\r\n    struct promote_traits<double, std::complex<long double> > {\r\n        typedef std::complex<long double> promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<std::complex<long double>, double> {\r\n        typedef std::complex<long double> promote_type;\r\n    };\r\n#endif\r\n\r\n#ifdef BOOST_UBLAS_USE_LONG_DOUBLE\r\n    template<>\r\n    struct promote_traits<long double, std::complex<float> > {\r\n        // Here we'd better go the conservative way.\r\n        // typedef std::complex<float> promote_type;\r\n        typedef std::complex<long double> promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<std::complex<float>, long double> {\r\n        // Here we'd better go the conservative way.\r\n        // typedef std::complex<float> promote_type;\r\n        typedef std::complex<long double> promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<long double, std::complex<double> > {\r\n        // Here we'd better go the conservative way.\r\n        // typedef std::complex<double> promote_type;\r\n        typedef std::complex<long double> promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<std::complex<double>, long double> {\r\n        // Here we'd better go the conservative way.\r\n        // typedef std::complex<double> promote_type;\r\n        typedef std::complex<long double> promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<long double, std::complex<long double> > {\r\n        typedef std::complex<long double> promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<std::complex<long double>, long double> {\r\n        typedef std::complex<long double> promote_type;\r\n    };\r\n#endif\r\n\r\n    template<>\r\n    struct promote_traits<std::complex<float>, std::complex<double> > {\r\n        typedef std::complex<double> promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<std::complex<double>, std::complex<float> > {\r\n        typedef std::complex<double> promote_type;\r\n    };\r\n#ifdef BOOST_UBLAS_USE_LONG_DOUBLE\r\n    template<>\r\n    struct promote_traits<std::complex<float>, std::complex<long double> > {\r\n        typedef std::complex<long double> promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<std::complex<long double>, std::complex<float> > {\r\n        typedef std::complex<long double> promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<std::complex<double>, std::complex<long double> > {\r\n        typedef std::complex<long double> promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<std::complex<long double>, std::complex<double> > {\r\n        typedef std::complex<long double> promote_type;\r\n    };\r\n#endif\r\n\r\n#ifdef BOOST_UBLAS_USE_INTERVAL\r\n    template<>\r\n    struct type_traits<boost::numeric::interval<float> > {\r\n        typedef type_traits<boost::numeric::interval<float> > self_type;\r\n        typedef boost::numeric::interval<float> value_type;\r\n        typedef const boost::numeric::interval<float> &const_reference;\r\n        typedef boost::numeric::interval<float> &reference;\r\n        typedef boost::numeric::interval<float> real_type;\r\n        typedef boost::numeric::interval<double> precision_type;\r\n\r\n        BOOST_STATIC_CONSTANT (std::size_t, plus_complexity = 1);\r\n        BOOST_STATIC_CONSTANT (std::size_t, multiplies_complexity = 1);\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type real (const_reference t) {\r\n                return t;\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type imag (const_reference t) {\r\n                return 0;\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type conj (const_reference t) {\r\n                return t;\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type abs (const_reference t) {\r\n            return boost::numeric::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type sqrt (const_reference t) {\r\n            return boost::numeric::sqrt (t);\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_1 (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_2 (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_inf (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        bool equals (const_reference t1, const_reference t2) {\r\n            // Check, that the values match at least half.\r\n            static real_type sqrt_epsilon (type_traits<real_type>::sqrt (std::numeric_limits<real_type>::epsilon ()));\r\n            return self_type::norm_inf (t1 - t2) < sqrt_epsilon *\r\n                   std::max (std::max (self_type::norm_inf (t1),\r\n                                       self_type::norm_inf (t2)),\r\n                             std::numeric_limits<real_type>::min ());\r\n        }\r\n    };\r\n    template<>\r\n    struct type_traits<boost::numeric::interval<double> > {\r\n        typedef type_traits<boost::numeric::interval<double> > self_type;\r\n        typedef boost::numeric::interval<double> value_type;\r\n        typedef const boost::numeric::interval<double> &const_reference;\r\n        typedef boost::numeric::interval<double> &reference;\r\n        typedef boost::numeric::interval<double> real_type;\r\n#ifndef BOOST_UBLAS_USE_LONG_DOUBLE\r\n        typedef boost::numeric::interval<double> precision_type;\r\n#else\r\n        typedef boost::numeric::interval<boost::numeric::interval<long double> > precision_type;\r\n#endif\r\n\r\n        BOOST_STATIC_CONSTANT (std::size_t, plus_complexity = 1);\r\n        BOOST_STATIC_CONSTANT (std::size_t, multiplies_complexity = 1);\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type real (const_reference t) {\r\n                return t;\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type imag (const_reference t) {\r\n                return 0;\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type conj (const_reference t) {\r\n                return t;\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type abs (const_reference t) {\r\n            return boost::numeric::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type sqrt (const_reference t) {\r\n            return boost::numeric::sqrt (t);\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_1 (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_2 (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_inf (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        bool equals (const_reference t1, const_reference t2) {\r\n            // Check, that the values match at least half.\r\n            static real_type sqrt_epsilon (type_traits<real_type>::sqrt (std::numeric_limits<real_type>::epsilon ()));\r\n            return self_type::norm_inf (t1 - t2) < sqrt_epsilon *\r\n                   std::max (std::max (self_type::norm_inf (t1),\r\n                                       self_type::norm_inf (t2)),\r\n                             std::numeric_limits<real_type>::min ());\r\n        }\r\n    };\r\n#ifdef BOOST_UBLAS_USE_LONG_DOUBLE\r\n    template<>\r\n    struct type_traits<boost::numeric::interval<long double> > {\r\n        typedef type_traits<boost::numeric::interval<long double> > self_type;\r\n        typedef boost::numeric::interval<long double> value_type;\r\n        typedef const boost::numeric::interval<long double> &const_reference;\r\n        typedef boost::numeric::interval<long double> &reference;\r\n        typedef boost::numeric::interval<long double> real_type;\r\n        typedef boost::numeric::interval<long double> precision_type;\r\n\r\n        BOOST_STATIC_CONSTANT (std::size_t, plus_complexity = 1);\r\n        BOOST_STATIC_CONSTANT (std::size_t, multiplies_complexity = 1);\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type real (const_reference t) {\r\n                return t;\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type imag (const_reference t) {\r\n                return 0;\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type conj (const_reference t) {\r\n                return t;\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type abs (const_reference t) {\r\n            return boost::numeric::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type sqrt (const_reference t) {\r\n            return boost::numeric::sqrt (t);\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_1 (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_2 (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_inf (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        bool equals (const_reference t1, const_reference t2) {\r\n            // Check, that the values match at least half.\r\n            static real_type sqrt_epsilon (type_traits<real_type>::sqrt (std::numeric_limits<real_type>::epsilon ()));\r\n            return self_type::norm_inf (t1 - t2) < sqrt_epsilon *\r\n                   std::max (std::max (self_type::norm_inf (t1),\r\n                                       self_type::norm_inf (t2)),\r\n                             std::numeric_limits<real_type>::min ());\r\n        }\r\n    };\r\n#endif\r\n\r\n#ifdef BOOST_UBLAS_USE_BOOST_COMPLEX\r\n    template<>\r\n    struct type_traits<boost::complex<boost::numeric::interval<float> > > {\r\n        typedef type_traits<boost::complex<boost::numeric::interval<float> > > self_type;\r\n        typedef boost::complex<boost::numeric::interval<float> > value_type;\r\n        typedef const boost::complex<boost::numeric::interval<float> > &const_reference;\r\n        typedef boost::complex<boost::numeric::interval<float> > &reference;\r\n        typedef boost::numeric::interval<float> real_type;\r\n        typedef boost::complex<double> precision_type;\r\n\r\n        BOOST_STATIC_CONSTANT (std::size_t, plus_complexity = 2);\r\n        BOOST_STATIC_CONSTANT (std::size_t, multiplies_complexity = 6);\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type real (const_reference t) {\r\n                // return t.real ();\r\n                return std::real (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type imag (const_reference t) {\r\n                // return t.imag ();\r\n                return std::imag (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type conj (const_reference t) {\r\n                // return t.conj ();\r\n                return std::conj (t);\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type abs (const_reference t) {\r\n                return boost::numeric::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type sqrt (const_reference t) {\r\n                return boost::numeric::sqrt (t);\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_1 (const_reference t) {\r\n            // Oops, should have known that!\r\n            return type_traits<real_type>::abs (self_type::real (t)) +\r\n                   type_traits<real_type>::abs (self_type::imag (t));\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_2 (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_inf (const_reference t) {\r\n            // Oops, should have known that!\r\n            return std::max (type_traits<real_type>::abs (self_type::real (t)),\r\n                             type_traits<real_type>::abs (self_type::imag (t)));\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        bool equals (const_reference t1, const_reference t2) {\r\n            // Check, that the values match at least half.\r\n            static real_type sqrt_epsilon (type_traits<real_type>::sqrt (std::numeric_limits<real_type>::epsilon ()));\r\n            return self_type::norm_inf (t1 - t2) < sqrt_epsilon *\r\n                   std::max (std::max (self_type::norm_inf (t1),\r\n                                       self_type::norm_inf (t2)),\r\n                             std::numeric_limits<real_type>::min ());\r\n        }\r\n    };\r\n    template<>\r\n    struct type_traits<boost::complex<double> > {\r\n        typedef type_traits<boost::complex<double> > self_type;\r\n        typedef boost::complex<double> value_type;\r\n        typedef const boost::complex<double> &const_reference;\r\n        typedef boost::complex<double> &reference;\r\n        typedef double real_type;\r\n#ifndef BOOST_UBLAS_USE_LONG_DOUBLE\r\n        typedef boost::complex<double> precision_type;\r\n#else\r\n        typedef boost::complex<boost::numeric::interval<long double> > precision_type;\r\n#endif\r\n\r\n        BOOST_STATIC_CONSTANT (std::size_t, plus_complexity = 2);\r\n        BOOST_STATIC_CONSTANT (std::size_t, multiplies_complexity = 6);\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type real (const_reference t) {\r\n                // return t.real ();\r\n                return std::real (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type imag (const_reference t) {\r\n                // return t.imag ();\r\n                return std::imag (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type conj (const_reference t) {\r\n                // return t.conj ();\r\n                return std::conj (t);\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type abs (const_reference t) {\r\n                return boost::numeric::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type sqrt (const_reference t) {\r\n                return boost::numeric::sqrt (t);\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_1 (const_reference t) {\r\n            // Oops, should have known that!\r\n            return type_traits<real_type>::abs (self_type::real (t)) +\r\n                   type_traits<real_type>::abs (self_type::imag (t));\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_2 (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_inf (const_reference t) {\r\n            // Oops, should have known that!\r\n            return std::max (type_traits<real_type>::abs (self_type::real (t)),\r\n                             type_traits<real_type>::abs (self_type::imag (t)));\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        bool equals (const_reference t1, const_reference t2) {\r\n            // Check, that the values match at least half.\r\n            static real_type sqrt_epsilon (type_traits<real_type>::sqrt (std::numeric_limits<real_type>::epsilon ()));\r\n            return self_type::norm_inf (t1 - t2) < sqrt_epsilon *\r\n                   std::max (std::max (self_type::norm_inf (t1),\r\n                                       self_type::norm_inf (t2)),\r\n                             std::numeric_limits<real_type>::min ());\r\n        }\r\n    };\r\n#ifdef BOOST_UBLAS_USE_LONG_DOUBLE\r\n    template<>\r\n    struct type_traits<boost::complex<boost::numeric::interval<long double> > > {\r\n        typedef type_traits<boost::complex<boost::numeric::interval<long double> > > self_type;\r\n        typedef boost::complex<boost::numeric::interval<long double> > value_type;\r\n        typedef const boost::complex<boost::numeric::interval<long double> > &const_reference;\r\n        typedef boost::complex<boost::numeric::interval<long double> > &reference;\r\n        typedef boost::numeric::interval<long double> real_type;\r\n        typedef boost::complex<boost::numeric::interval<long double> > precision_type;\r\n\r\n        BOOST_STATIC_CONSTANT (std::size_t, plus_complexity = 2);\r\n        BOOST_STATIC_CONSTANT (std::size_t, multiplies_complexity = 6);\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type real (const_reference t) {\r\n                // return t.real ();\r\n                return std::real (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type imag (const_reference t) {\r\n                // return t.imag ();\r\n                return std::imag (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type conj (const_reference t) {\r\n                // return t.conj ();\r\n                return std::conj (t);\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type abs (const_reference t) {\r\n                return boost::numeric::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        value_type sqrt (const_reference t) {\r\n                return boost::numeric::sqrt (t);\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_1 (const_reference t) {\r\n            // Oops, should have known that!\r\n            return type_traits<real_type>::abs (self_type::real (t)) +\r\n                   type_traits<real_type>::abs (self_type::imag (t));\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_2 (const_reference t) {\r\n            return self_type::abs (t);\r\n        }\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        real_type norm_inf (const_reference t) {\r\n            // Oops, should have known that!\r\n            return std::max (type_traits<real_type>::abs (self_type::real (t)),\r\n                             type_traits<real_type>::abs (self_type::imag (t)));\r\n        }\r\n\r\n        static\r\n        BOOST_UBLAS_INLINE\r\n        bool equals (const_reference t1, const_reference t2) {\r\n            // Check, that the values match at least half.\r\n            static real_type sqrt_epsilon (type_traits<real_type>::sqrt (std::numeric_limits<real_type>::epsilon ()));\r\n            return self_type::norm_inf (t1 - t2) < sqrt_epsilon *\r\n                   std::max (std::max (self_type::norm_inf (t1),\r\n                                       self_type::norm_inf (t2)),\r\n                             std::numeric_limits<real_type>::min ());\r\n        }\r\n    };\r\n#endif\r\n#endif\r\n\r\n    template<>\r\n    struct promote_traits<boost::numeric::interval<float>, boost::numeric::interval<double> > {\r\n        typedef boost::numeric::interval<double> promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<boost::numeric::interval<double>, boost::numeric::interval<float> > {\r\n        typedef boost::numeric::interval<double> promote_type;\r\n    };\r\n#ifdef BOOST_UBLAS_USE_LONG_DOUBLE\r\n    template<>\r\n    struct promote_traits<boost::numeric::interval<float>, boost::numeric::interval<long double> > {\r\n        typedef boost::numeric::interval<long double> promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<boost::numeric::interval<long double>, boost::numeric::interval<float> > {\r\n        typedef boost::numeric::interval<long double> promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<boost::numeric::interval<double>, boost::numeric::interval<long double> > {\r\n        typedef boost::numeric::interval<long double> promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<boost::numeric::interval<long double>, boost::numeric::interval<double> > {\r\n        typedef boost::numeric::interval<long double> promote_type;\r\n    };\r\n#endif\r\n\r\n#ifdef BOOST_UBLAS_USE_BOOST_COMPLEX\r\n    template<>\r\n    struct promote_traits<boost::numeric::interval<float>, boost::complex<boost::numeric::interval<float> > > {\r\n        typedef boost::complex<boost::numeric::interval<float> > promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<boost::complex<boost::numeric::interval<float> >, boost::numeric::interval<float> > {\r\n        typedef boost::complex<boost::numeric::interval<float> > promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<boost::numeric::interval<float>, boost::complex<boost::numeric::interval<double> > > {\r\n        typedef boost::complex<boost::numeric::interval<double> > promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<boost::complex<boost::numeric::interval<double> >, boost::numeric::interval<float> > {\r\n        typedef boost::complex<boost::numeric::interval<double> > promote_type;\r\n    };\r\n#ifdef BOOST_UBLAS_USE_LONG_DOUBLE\r\n    template<>\r\n    struct promote_traits<boost::numeric::interval<float>, boost::complex<boost::numeric::interval<long double> > > {\r\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<boost::complex<boost::numeric::interval<long double> >, boost::numeric::interval<float> > {\r\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\r\n    };\r\n#endif\r\n\r\n    template<>\r\n    struct promote_traits<boost::numeric::interval<double>, boost::complex<boost::numeric::interval<float> > > {\r\n        // Here we'd better go the conservative way.\r\n        // typedef boost::complex<boost::numeric::interval<float> > promote_type;\r\n        typedef boost::complex<boost::numeric::interval<double> > promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<boost::complex<boost::numeric::interval<float> >, boost::numeric::interval<double> > {\r\n        // Here we'd better go the conservative way.\r\n        // typedef boost::complex<boost::numeric::interval<float> > promote_type;\r\n        typedef boost::complex<boost::numeric::interval<double> > promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<boost::numeric::interval<double>, boost::complex<boost::numeric::interval<double> > > {\r\n        typedef boost::complex<boost::numeric::interval<double> > promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<boost::complex<boost::numeric::interval<double> >, boost::numeric::interval<double> > {\r\n        typedef boost::complex<boost::numeric::interval<double> > promote_type;\r\n    };\r\n#ifdef BOOST_UBLAS_USE_LONG_DOUBLE\r\n    template<>\r\n    struct promote_traits<boost::numeric::interval<double>, boost::complex<boost::numeric::interval<long double> > > {\r\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<boost::complex<boost::numeric::interval<long double> >, boost::numeric::interval<double> > {\r\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\r\n    };\r\n#endif\r\n\r\n#ifdef BOOST_UBLAS_USE_LONG_DOUBLE\r\n    template<>\r\n    struct promote_traits<boost::numeric::interval<long double>, boost::complex<boost::numeric::interval<float> > > {\r\n        // Here we'd better go the conservative way.\r\n        // typedef boost::complex<boost::numeric::interval<float> > promote_type;\r\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<boost::complex<boost::numeric::interval<float> >, boost::numeric::interval<long double> > {\r\n        // Here we'd better go the conservative way.\r\n        // typedef boost::complex<boost::numeric::interval<float> > promote_type;\r\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<boost::numeric::interval<long double>, boost::complex<boost::numeric::interval<double> > > {\r\n        // Here we'd better go the conservative way.\r\n        // typedef boost::complex<boost::numeric::interval<double> > promote_type;\r\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<boost::complex<boost::numeric::interval<double> >, boost::numeric::interval<long double> > {\r\n        // Here we'd better go the conservative way.\r\n        // typedef boost::complex<boost::numeric::interval<double> > promote_type;\r\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<boost::numeric::interval<long double>, boost::complex<boost::numeric::interval<long double> > > {\r\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<boost::complex<boost::numeric::interval<long double> >, boost::numeric::interval<long double> > {\r\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\r\n    };\r\n#endif\r\n\r\n    template<>\r\n    struct promote_traits<boost::complex<boost::numeric::interval<float> >, boost::complex<boost::numeric::interval<double> > > {\r\n        typedef boost::complex<boost::numeric::interval<double> > promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<boost::complex<boost::numeric::interval<double> >, boost::complex<boost::numeric::interval<float> > > {\r\n        typedef boost::complex<boost::numeric::interval<double> > promote_type;\r\n    };\r\n#ifdef BOOST_UBLAS_USE_LONG_DOUBLE\r\n    template<>\r\n    struct promote_traits<boost::complex<boost::numeric::interval<float> >, boost::complex<boost::numeric::interval<long double> > > {\r\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<boost::complex<boost::numeric::interval<long double> >, boost::complex<boost::numeric::interval<float> > > {\r\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<boost::complex<boost::numeric::interval<double> >, boost::complex<boost::numeric::interval<long double> > > {\r\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\r\n    };\r\n    template<>\r\n    struct promote_traits<boost::complex<boost::numeric::interval<long double> >, boost::complex<boost::numeric::interval<double> > > {\r\n        typedef boost::complex<boost::numeric::interval<long double> > promote_type;\r\n    };\r\n#endif\r\n#endif\r\n#endif\r\n\r\n    struct unknown_storage_tag {};\r\n    struct sparse_proxy_tag: public unknown_storage_tag {};\r\n    struct sparse_tag: public sparse_proxy_tag {};\r\n    struct packed_proxy_tag: public sparse_proxy_tag {};\r\n    struct packed_tag: public packed_proxy_tag {};\r\n    struct dense_proxy_tag: public packed_proxy_tag {};\r\n    struct dense_tag: public dense_proxy_tag {};\r\n\r\n    template<class S1, class S2>\r\n    struct storage_restrict_traits {\r\n        typedef S1 storage_category;\r\n    };\r\n\r\n    template<>\r\n    struct storage_restrict_traits<sparse_tag, dense_proxy_tag> {\r\n        typedef sparse_proxy_tag storage_category;\r\n    };\r\n    template<>\r\n    struct storage_restrict_traits<sparse_tag, packed_proxy_tag> {\r\n        typedef sparse_proxy_tag storage_category;\r\n    };\r\n    template<>\r\n    struct storage_restrict_traits<sparse_tag, sparse_proxy_tag> {\r\n        typedef sparse_proxy_tag storage_category;\r\n    };\r\n\r\n    template<>\r\n    struct storage_restrict_traits<packed_tag, dense_proxy_tag> {\r\n        typedef packed_proxy_tag storage_category;\r\n    };\r\n    template<>\r\n    struct storage_restrict_traits<packed_tag, packed_proxy_tag> {\r\n        typedef packed_proxy_tag storage_category;\r\n    };\r\n    template<>\r\n    struct storage_restrict_traits<packed_tag, sparse_proxy_tag> {\r\n        typedef sparse_proxy_tag storage_category;\r\n    };\r\n\r\n    template<>\r\n    struct storage_restrict_traits<packed_proxy_tag, sparse_proxy_tag> {\r\n        typedef sparse_proxy_tag storage_category;\r\n    };\r\n\r\n    template<>\r\n    struct storage_restrict_traits<dense_tag, dense_proxy_tag> {\r\n        typedef dense_proxy_tag storage_category;\r\n    };\r\n    template<>\r\n    struct storage_restrict_traits<dense_tag, packed_proxy_tag> {\r\n        typedef packed_proxy_tag storage_category;\r\n    };\r\n    template<>\r\n    struct storage_restrict_traits<dense_tag, sparse_proxy_tag> {\r\n        typedef sparse_proxy_tag storage_category;\r\n    };\r\n\r\n    template<>\r\n    struct storage_restrict_traits<dense_proxy_tag, packed_proxy_tag> {\r\n        typedef packed_proxy_tag storage_category;\r\n    };\r\n    template<>\r\n    struct storage_restrict_traits<dense_proxy_tag, sparse_proxy_tag> {\r\n        typedef sparse_proxy_tag storage_category;\r\n    };\r\n\r\n    struct sparse_bidirectional_iterator_tag : public std::bidirectional_iterator_tag {};\r\n    struct packed_random_access_iterator_tag : public std::random_access_iterator_tag {};\r\n    struct dense_random_access_iterator_tag : public packed_random_access_iterator_tag {};\r\n\r\n    // Thanks to Kresimir Fresl for convincing Comeau with iterator_base_traits ;-)\r\n    template<class IC>\r\n    struct iterator_base_traits {};\r\n\r\n    template<>\r\n    struct iterator_base_traits<std::forward_iterator_tag> {\r\n        template<class I, class T>\r\n        struct iterator_base {\r\n            typedef forward_iterator_base<std::forward_iterator_tag, I, T> type;\r\n        };\r\n    };\r\n\r\n    template<>\r\n    struct iterator_base_traits<std::bidirectional_iterator_tag> {\r\n        template<class I, class T>\r\n        struct iterator_base {\r\n            typedef bidirectional_iterator_base<std::bidirectional_iterator_tag, I, T> type;\r\n        };\r\n    };\r\n    template<>\r\n    struct iterator_base_traits<sparse_bidirectional_iterator_tag> {\r\n        template<class I, class T>\r\n        struct iterator_base {\r\n            typedef bidirectional_iterator_base<sparse_bidirectional_iterator_tag, I, T> type;\r\n        };\r\n    };\r\n\r\n    template<>\r\n    struct iterator_base_traits<std::random_access_iterator_tag> {\r\n        template<class I, class T>\r\n        struct iterator_base {\r\n            typedef random_access_iterator_base<std::bidirectional_iterator_tag, I, T> type;\r\n        };\r\n    };\r\n    template<>\r\n    struct iterator_base_traits<packed_random_access_iterator_tag> {\r\n        template<class I, class T>\r\n        struct iterator_base {\r\n            typedef random_access_iterator_base<packed_random_access_iterator_tag, I, T> type;\r\n        };\r\n    };\r\n    template<>\r\n    struct iterator_base_traits<dense_random_access_iterator_tag> {\r\n        template<class I, class T>\r\n        struct iterator_base {\r\n            typedef random_access_iterator_base<dense_random_access_iterator_tag, I, T> type;\r\n        };\r\n    };\r\n\r\n    template<class I1, class I2>\r\n    struct iterator_restrict_traits {\r\n        typedef I1 iterator_category;\r\n    };\r\n\r\n    template<>\r\n    struct iterator_restrict_traits<packed_random_access_iterator_tag, sparse_bidirectional_iterator_tag> {\r\n        typedef sparse_bidirectional_iterator_tag iterator_category;\r\n    };\r\n    template<>\r\n    struct iterator_restrict_traits<sparse_bidirectional_iterator_tag, packed_random_access_iterator_tag> {\r\n        typedef sparse_bidirectional_iterator_tag iterator_category;\r\n    };\r\n\r\n    template<>\r\n    struct iterator_restrict_traits<dense_random_access_iterator_tag, sparse_bidirectional_iterator_tag> {\r\n        typedef sparse_bidirectional_iterator_tag iterator_category;\r\n    };\r\n    template<>\r\n    struct iterator_restrict_traits<sparse_bidirectional_iterator_tag, dense_random_access_iterator_tag> {\r\n        typedef sparse_bidirectional_iterator_tag iterator_category;\r\n    };\r\n\r\n    template<>\r\n    struct iterator_restrict_traits<dense_random_access_iterator_tag, packed_random_access_iterator_tag> {\r\n        typedef packed_random_access_iterator_tag iterator_category;\r\n    };\r\n    template<>\r\n    struct iterator_restrict_traits<packed_random_access_iterator_tag, dense_random_access_iterator_tag> {\r\n        typedef packed_random_access_iterator_tag iterator_category;\r\n    };\r\n\r\n}}}\r\n\r\n#endif\r\n\r\n\r\n", "meta": {"hexsha": "7d36faa22fa5900f0568101f57c97b76565e0ca2", "size": 53171, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/boost/numeric/ublas/traits.hpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-05-04T06:40:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T20:24:28.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/boost/numeric/ublas/traits.hpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/boost/numeric/ublas/traits.hpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-05-17T10:01:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-11T20:17:27.000Z", "avg_line_length": 36.8986814712, "max_line_length": 136, "alphanum_fraction": 0.5993116548, "num_tokens": 11274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.27590740667197156}}
{"text": "//=======================================================================\r\n// Copyright (c) Aaron Windsor 2007\r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n//=======================================================================\r\n\r\n#ifndef __PLANAR_CANONICAL_ORDERING_HPP__\r\n#define __PLANAR_CANONICAL_ORDERING_HPP__\r\n\r\n#include <vector>\r\n#include <list>\r\n#include <boost/config.hpp>\r\n#include <boost/next_prior.hpp>\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/property_map/property_map.hpp>\r\n\r\n\r\nnamespace boost\r\n{\r\n\r\n\r\n  namespace detail {\r\n    enum planar_canonical_ordering_state\r\n         {PCO_PROCESSED, \r\n          PCO_UNPROCESSED, \r\n          PCO_ONE_NEIGHBOR_PROCESSED, \r\n          PCO_READY_TO_BE_PROCESSED};\r\n  }\r\n    \r\n  template<typename Graph, \r\n           typename PlanarEmbedding, \r\n           typename OutputIterator, \r\n           typename VertexIndexMap>\r\n  void planar_canonical_ordering(const Graph& g, \r\n                                 PlanarEmbedding embedding, \r\n                                 OutputIterator ordering, \r\n                                 VertexIndexMap vm)\r\n  {\r\n    \r\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\r\n    typedef typename graph_traits<Graph>::edge_descriptor edge_t;\r\n    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator_t;\r\n    typedef typename graph_traits<Graph>::adjacency_iterator\r\n      adjacency_iterator_t;\r\n    typedef typename std::pair<vertex_t, vertex_t> vertex_pair_t;\r\n    typedef typename property_traits<PlanarEmbedding>::value_type \r\n      embedding_value_t;\r\n    typedef typename embedding_value_t::const_iterator embedding_iterator_t;\r\n    typedef iterator_property_map\r\n      <typename std::vector<vertex_t>::iterator, VertexIndexMap> \r\n      vertex_to_vertex_map_t;\r\n    typedef iterator_property_map\r\n      <typename std::vector<std::size_t>::iterator, VertexIndexMap> \r\n      vertex_to_size_t_map_t;\r\n    \r\n    std::vector<vertex_t> processed_neighbor_vector(num_vertices(g));\r\n    vertex_to_vertex_map_t processed_neighbor\r\n      (processed_neighbor_vector.begin(), vm);\r\n\r\n    std::vector<std::size_t> status_vector(num_vertices(g), detail::PCO_UNPROCESSED);\r\n    vertex_to_size_t_map_t status(status_vector.begin(), vm);\r\n\r\n    std::list<vertex_t> ready_to_be_processed;\r\n    \r\n    vertex_t first_vertex = *vertices(g).first;\r\n    vertex_t second_vertex;\r\n    adjacency_iterator_t ai, ai_end;\r\n    for(boost::tie(ai,ai_end) = adjacent_vertices(first_vertex,g); ai != ai_end; ++ai)\r\n      {\r\n        if (*ai == first_vertex)\r\n          continue;\r\n        second_vertex = *ai;\r\n        break;\r\n      }\r\n\r\n    ready_to_be_processed.push_back(first_vertex);\r\n    status[first_vertex] = detail::PCO_READY_TO_BE_PROCESSED;\r\n    ready_to_be_processed.push_back(second_vertex);\r\n    status[second_vertex] = detail::PCO_READY_TO_BE_PROCESSED;\r\n\r\n    while(!ready_to_be_processed.empty())\r\n      {\r\n        vertex_t u = ready_to_be_processed.front();\r\n        ready_to_be_processed.pop_front();\r\n\r\n        if (status[u] != detail::PCO_READY_TO_BE_PROCESSED && u != second_vertex)\r\n          continue;\r\n\r\n        embedding_iterator_t ei, ei_start, ei_end;\r\n        embedding_iterator_t next_edge_itr, prior_edge_itr;\r\n\r\n        ei_start = embedding[u].begin();\r\n        ei_end = embedding[u].end();\r\n        prior_edge_itr = prior(ei_end);\r\n        while(source(*prior_edge_itr, g) == target(*prior_edge_itr,g))\r\n          prior_edge_itr = prior(prior_edge_itr);\r\n\r\n        for(ei = ei_start; ei != ei_end; ++ei)\r\n          {\r\n            \r\n            edge_t e(*ei); // e = (u,v)\r\n            next_edge_itr = boost::next(ei) == ei_end ? ei_start : boost::next(ei);\r\n            vertex_t v = source(e,g) == u ? target(e,g) : source(e,g);\r\n\r\n            vertex_t prior_vertex = source(*prior_edge_itr, g) == u ? \r\n              target(*prior_edge_itr, g) : source(*prior_edge_itr, g);\r\n            vertex_t next_vertex = source(*next_edge_itr, g) == u ? \r\n              target(*next_edge_itr, g) : source(*next_edge_itr, g);\r\n\r\n            // Need prior_vertex, u, v, and next_vertex to all be\r\n            // distinct. This is possible, since the input graph is\r\n            // triangulated. It'll be true all the time in a simple\r\n            // graph, but loops and parallel edges cause some complications.\r\n            if (prior_vertex == v || prior_vertex == u)\r\n              {\r\n                prior_edge_itr = ei;\r\n                continue;\r\n              }\r\n\r\n            //Skip any self-loops\r\n            if (u == v)\r\n                continue;\r\n                                                                \r\n            // Move next_edge_itr (and next_vertex) forwards\r\n            // past any loops or parallel edges\r\n            while (next_vertex == v || next_vertex == u)\r\n              {\r\n                next_edge_itr = boost::next(next_edge_itr) == ei_end ?\r\n                  ei_start : boost::next(next_edge_itr);\r\n                next_vertex = source(*next_edge_itr, g) == u ? \r\n                  target(*next_edge_itr, g) : source(*next_edge_itr, g);\r\n              }\r\n\r\n\r\n            if (status[v] == detail::PCO_UNPROCESSED)\r\n              {\r\n                status[v] = detail::PCO_ONE_NEIGHBOR_PROCESSED;\r\n                processed_neighbor[v] = u;\r\n              }\r\n            else if (status[v] == detail::PCO_ONE_NEIGHBOR_PROCESSED)\r\n              {\r\n                vertex_t x = processed_neighbor[v];\r\n                //are edges (v,u) and (v,x) adjacent in the planar\r\n                //embedding? if so, set status[v] = 1. otherwise, set\r\n                //status[v] = 2.\r\n\r\n                if ((next_vertex == x &&\r\n                     !(first_vertex == u && second_vertex == x)\r\n                     )\r\n                    ||\r\n                    (prior_vertex == x &&\r\n                     !(first_vertex == x && second_vertex == u)\r\n                     )\r\n                    )\r\n                  {\r\n                    status[v] = detail::PCO_READY_TO_BE_PROCESSED;\r\n                  }\r\n                else\r\n                  {\r\n                    status[v] = detail::PCO_READY_TO_BE_PROCESSED + 1;\r\n                  }                                                        \r\n              }\r\n            else if (status[v] > detail::PCO_ONE_NEIGHBOR_PROCESSED)\r\n              {\r\n                //check the two edges before and after (v,u) in the planar\r\n                //embedding, and update status[v] accordingly\r\n\r\n                bool processed_before = false;\r\n                if (status[prior_vertex] == detail::PCO_PROCESSED)\r\n                  processed_before = true;\r\n\r\n                bool processed_after = false;\r\n                if (status[next_vertex] == detail::PCO_PROCESSED)\r\n                  processed_after = true;\r\n\r\n                if (!processed_before && !processed_after)\r\n                    ++status[v];\r\n\r\n                else if (processed_before && processed_after)\r\n                    --status[v];\r\n\r\n              }\r\n\r\n            if (status[v] == detail::PCO_READY_TO_BE_PROCESSED)\r\n              ready_to_be_processed.push_back(v);\r\n\r\n            prior_edge_itr = ei;\r\n\r\n          }\r\n\r\n        status[u] = detail::PCO_PROCESSED;\r\n        *ordering = u;\r\n        ++ordering;\r\n        \r\n      }\r\n    \r\n  }\r\n\r\n\r\n  template<typename Graph, typename PlanarEmbedding, typename OutputIterator>\r\n  void planar_canonical_ordering(const Graph& g, \r\n                                 PlanarEmbedding embedding, \r\n                                 OutputIterator ordering\r\n                                 )\r\n  {\r\n    planar_canonical_ordering(g, embedding, ordering, get(vertex_index,g));\r\n  }\r\n \r\n\r\n} //namespace boost\r\n\r\n#endif //__PLANAR_CANONICAL_ORDERING_HPP__\r\n", "meta": {"hexsha": "81a3a86b04d588b0f81cba9c97dac1450d613de6", "size": 7891, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "master/core/third/boost/graph/planar_canonical_ordering.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/graph/planar_canonical_ordering.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/graph/planar_canonical_ordering.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": 36.7023255814, "max_line_length": 87, "alphanum_fraction": 0.544797871, "num_tokens": 1642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2758066636828176}}
{"text": "/**\r\nCommon functions and typedefs.\r\n\r\n@file cnet_common.hpp\r\n@author Bastian \r\n*/\r\n\r\n\r\n#ifndef CNET_INTERNAL_HPP\r\n#define CNET_INTERNAL_HPP\r\n\r\n#include <map>\r\n#include <fstream> \r\n\r\n#include <Eigen/StdVector>\r\n#include <Eigen/Dense>\r\n#include <experimental/filesystem>\r\n#include <mutex>\r\n#include <condition_variable>\r\n#include \"cnet_cv2eigen.hpp\"\r\n\r\n\r\n#define INITIAL_QUEUE_SIZE 64\r\n#define THREAD_RETRY_DELAY 2\r\n\r\n\r\n\r\nnamespace Cnet\r\n{\r\n\r\n\ttypedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatrixRm;\r\n\ttypedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> MatrixCm;\r\n\ttypedef std::vector<MatrixRm, Eigen::aligned_allocator<MatrixRm > > AlignedStdVector;\r\n\ttypedef std::vector<MatrixRm, Eigen::aligned_allocator<MatrixRm > > AlignedStdVector;\r\n\t//typedef std::vector<std::pair<MatrixRm, MatrixRm>, std::pair< Eigen::aligned_allocator< MatrixRm >, Eigen::aligned_allocator< MatrixRm > >  > AlignedStdPairVector;\r\n\ttypedef std::map<int, Eigen::Vector4f, std::less<int>, Eigen::aligned_allocator<std::pair<const int, Eigen::Vector4f> > > AlignedMap;\r\n\ttypedef Eigen::Map< Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > MatrixRmMap;\r\n\ttypedef Eigen::Map< Eigen::VectorXf> VectorMap;\r\n\r\n\tinline void disable_multithreading()\r\n\t{\r\n\t\tEigen::setNbThreads(1);\r\n\t}\r\n\r\n\t/*\r\n\tChecks if file exists...\r\n\t*/\r\n\tinline bool file_exists(const std::string& file_name)\r\n\t{\r\n\t\tstd::ifstream infile(file_name);\r\n\t\treturn infile.good();\r\n\t}\r\n\r\n\t/*\r\n\tGet filename from string\r\n\t*/\r\n\tinline std::string strip_filename(const std::string& path)\r\n\t{\r\n\t\tstd::string stripped = path.substr(path.find_last_of(\"/\\\\\") + 1);\r\n\t\tsize_t dot_i = path.find_last_of('.');\r\n\t\treturn stripped.substr(0, dot_i);\r\n\t}\r\n\r\n\t/*\r\n\tStruct to hold convolution parameters\r\n\t*/\r\n\tclass ConvolutionParams\r\n\t{\r\n\tprivate:\r\n\t\tsize_t _kernel_size;\r\n\t\tsize_t _kernel_width;\r\n\t\tsize_t _stride;\r\n\t\tsize_t _padding;\r\n\tpublic:\r\n\r\n\t\tConvolutionParams(size_t kernel_width, size_t stride, size_t padding)\r\n\t\t{\r\n\t\t\t_kernel_width = kernel_width;\r\n\t\t\t_kernel_size = (size_t)pow(kernel_width, 2.0);\r\n\t\t\t_stride = stride;\r\n\t\t\t_padding = padding;\r\n\t\t\r\n\t\t}\r\n\r\n\t\tinline size_t kernel_size()\r\n\t\t{\r\n\t\t\treturn _kernel_size;\r\n\t\t}\r\n\r\n\t\tinline size_t padding()\r\n\t\t{\r\n\t\t\treturn _padding;\r\n\t\t}\r\n\r\n\t\tinline size_t kernel_width()\r\n\t\t{\r\n\t\t\treturn _kernel_width;\r\n\t\t}\r\n\r\n\t\tinline size_t stride()\r\n\t\t{\r\n\t\t\treturn _stride;\r\n\t\t}\r\n\r\n\t\tvoid stride(size_t stride)\r\n\t\t{\r\n\t\t\t_stride = stride;\r\n\t\t}\r\n\r\n\t\tvoid padding(size_t padding)\r\n\t\t{\r\n\t\t\t_padding = padding;\r\n\t\t}\r\n\r\n\t\tvoid kernel_width(size_t kernel_width)\r\n\t\t{\r\n\t\t\t_kernel_width = kernel_width;\r\n\t\t\t_kernel_size = (size_t)pow(kernel_width, 2.0);\r\n\t\t}\r\n\r\n\t};\r\n\r\n\t/*\r\n\tStruct to hold Datasample\r\n\t*/\r\n\tclass Entry\r\n\t{\r\n\tprivate:\r\n\t\tMatrixRm _data;\r\n\t\tbool _is_file;\r\n\t\tstd::string _file_name;\r\n\t\tstd::string _file_path;\r\n\tpublic:\r\n\r\n\t\tEntry(MatrixRm data, const std::string& fpath)\r\n\t\t{\r\n\t\t\t_data = data;\r\n\t\t\t_file_name = strip_filename(fpath);\r\n\t\t\t_file_path = fpath;\r\n\t\t\t_is_file = true;\r\n\t\t}\r\n\r\n        explicit Entry(MatrixRm data)\r\n\t\t{\r\n\t\t\t_data = data;\r\n\t\t\t_is_file = false;\r\n\t\t}\r\n\r\n\t\tEntry()\r\n\t\t{\r\n\t\t\t_is_file = false;\r\n\t\t}\r\n\r\n\t\tMatrixRm* data()\r\n\t\t{\r\n\t\t\treturn &_data;\r\n\t\t}\r\n\r\n\t\tstd::string file_name()\r\n\t\t{\r\n\t\t\treturn _file_name;\r\n\t\t}\r\n\r\n\t\tbool is_file()\r\n\t\t{\r\n\t\t\treturn _is_file;\r\n\t\t}\r\n\r\n\t\tstd::string file_path()\r\n\t\t{\r\n\t\t\treturn _file_path;\r\n\t\t}\r\n\r\n\t};\r\n\r\n\t/*\r\n\tTemplate for thread-safe queue class\r\n\t*/\r\n\ttemplate <class T> class DataQueue\r\n\t{\r\n\tpublic:\r\n\r\n        explicit DataQueue(size_t max_size)\r\n\t\t{\r\n\t\t\t_max_size = max_size;\r\n\t\t\t_current_size = 0;\r\n\t\t}\r\n\r\n\t\tDataQueue()\r\n\t\t{\r\n\t\t\t_max_size = INITIAL_QUEUE_SIZE;\r\n\t\t\t_current_size = 0;\r\n\t\t}\r\n\r\n\t\t~DataQueue() = default;\r\n\r\n\r\n\t\tvoid push(T t)\r\n\t\t{\r\n\t\t\tstd::unique_lock<std::mutex> lock(_m);\r\n\t\t\t_c.wait(lock, [this]() {return _queue.size() < _max_size; });\r\n\t\t\t_queue.push_back(t);\r\n\t\t\t_c.notify_all();\r\n\t\t}\r\n\r\n\t\tvoid push_streight(T t)\r\n\t\t{\r\n\t\t\t//std::unique_lock<std::mutex> lock(_m);\r\n\t\t\t//c.wait(lock, [this]() {return _queue.size() < _max_size; });\r\n\t\t\t_queue.push_back(t);\r\n\t\t\t//_c.notify_all();\r\n\t\t}\r\n\r\n\t\tT pop()\r\n\t\t{\r\n\t\t\tstd::unique_lock<std::mutex> lock(_m);\r\n\t\t\twhile (_queue.empty())\r\n\t\t\t{\r\n\t\t\t\t_c.wait(lock);\r\n\t\t\t}\r\n\t\t\t_c.notify_all();\r\n\t\t\tT val = _queue.front();\r\n\t\t\t_queue.pop_front();\r\n\t\t\treturn val;\r\n\t\t}\r\n\r\n\t\tbool try_pop(T& item, std::chrono::milliseconds timeout)\r\n\t\t{\r\n\t\t\tstd::unique_lock<std::mutex> lock(_m);\r\n\t\t\tif (!_c.wait_for(lock, timeout, [this] { return !_queue.empty(); }))\r\n\t\t\t{\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\t_c.notify_all();\r\n\t\t\titem = _queue.front();\r\n\t\t\t_queue.pop_front();\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\t\tT at(size_t idx)\r\n\t\t{\r\n\t\t\tstd::unique_lock<std::mutex> lock(_m);\r\n\t\t\twhile (_queue.empty())\r\n\t\t\t{\r\n\t\t\t\t_c.wait(lock);\r\n\t\t\t}\r\n\t\t\t_c.notify_all();\r\n\t\t\tT val = _queue[idx];\r\n\t\t\treturn val;\r\n\t\t}\r\n\r\n\t\tsize_t get_size()\r\n\t\t{\r\n\t\t\treturn _queue.size();\r\n\t\t}\r\n\r\n\t\tsize_t get_max_size()\r\n\t\t{\r\n\t\t\treturn _max_size;\r\n\t\t}\r\n\r\n\t\tvoid set_max_size(size_t queue_size)\r\n\t\t{\r\n\t\t\t_max_size = queue_size;\r\n\t\t}\r\n\r\n\tprivate:\r\n\t\tstd::deque<T> _queue;\r\n\t\tmutable std::mutex _m;\r\n\t\tstd::condition_variable _c;\r\n\t\tsize_t _max_size;\r\n\t\tsize_t _current_size;\r\n\t};\r\n\t\r\n\r\n\tinline int load_image(MatrixRm* image, const std::string& path)\r\n\t{\r\n\t\tif (file_exists(path))\r\n\t\t{\r\n\t\t\tMatrixRm input;\r\n\t\t\teigen2cv(input) = cv::imread(path, cv::IMREAD_GRAYSCALE);\r\n\t\t\t//scale down\r\n\t\t\t*image = MatrixRmMap(input.data(), 1, input.cols()*input.rows());\r\n\t\t\t//*image /= 255.f;\r\n\t\t\t//std::cout << \"image:\\n\" << *image << std::endl;\r\n\t\t\treturn 1;\r\n\t\t}\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tinline int load_image(MatrixRm& image, const std::string& path)\r\n\t{\r\n\t\treturn load_image(&image, path);\r\n\t}\r\n\r\n\tvoid save_image(MatrixRm* image, std::string path)\r\n\t{\r\n\t\tauto width = (size_t) sqrt(image->cols());\r\n\t\tMatrixRm out = MatrixRmMap(image->data(), width, width);\r\n\t\tout *= 255;\r\n\t\tcv::Mat mat_out = eigen2cv(out);\r\n\t\tcv::imwrite(path, mat_out);\r\n\t}\r\n\r\n\tvoid save_image(MatrixRm& image, const std::string& path)\r\n\t{\r\n\t\tsave_image(&image, path);\r\n\t}\r\n\r\n\t/*\r\n\tMethod to extract image tiles.\r\n\t*/\r\n\tinline void extract_image_tiles(MatrixRm* image, AlignedStdVector tile_vec, const size_t tile_size, const size_t stride)\r\n\t{\r\n\t\tMatrixRm tile = MatrixRm::Zero(tile_size, tile_size);\r\n\t\tconst auto input_width = (size_t)sqrt(image->cols());\r\n\t\tconst auto num_tiles = (size_t)((image->cols() - tile_size) / 2) + 1;\r\n\t\tfor (size_t row = 0; row < num_tiles; ++row)\r\n\t\t{\r\n\t\t\tconst size_t current_row = row * input_width;\r\n\t\t\tfor (size_t col = 0; col < num_tiles; ++col)\r\n\t\t\t{\r\n\t\t\t\tconst size_t current_pos = (current_row*stride) + (col*stride);\r\n\t\t\t\tfor (size_t kernel_row = 0; kernel_row < tile_size; ++kernel_row)\r\n\t\t\t\t{\r\n\t\t\t\t\ttile.block(kernel_row, 0, 1, tile_size) = (*image).block(0, current_pos + kernel_row*input_width, 1, tile_size);\r\n\t\t\t\t}\r\n\t\t\t\ttile_vec.push_back(tile);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/*\r\n\tMethod to pad border with zeros.\r\n\t*/\r\n\tinline void pad_border(MatrixRm* in, MatrixRm* out, size_t offset)\r\n\t{\r\n\t\tif (offset == 0)\r\n\t\t{\r\n\t\t\t*out = *in;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tconst auto input_width = (size_t)sqrt(in->cols());\r\n\t\t\t*out = MatrixRm::Zero(in->rows(), (unsigned int)pow(2 * offset + input_width, 2.));\r\n\t\t\tconst size_t steps = 2 * offset + input_width;\r\n\t\t\tsize_t start = 0;\r\n\t\t\tfor (size_t i = 0; i < input_width; ++i)\r\n\t\t\t{\r\n\t\t\t\tout->block(0, start, in->rows(), input_width) = in->block(0, i*input_width, in->rows(), input_width);\r\n\t\t\t\tstart += steps;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t/*\r\n\tAlternative method to add zeros to the border.\r\n\t*/\r\n\tinline void pad(MatrixRm* in, MatrixRm* out, size_t offset)\r\n\t{\r\n\t\tconst size_t padded_width = (size_t)sqrt(in->cols()) + offset;\r\n\t\t*out = MatrixRm::Zero(in->rows(), (unsigned int)pow(padded_width, 2.));\r\n\t\tconst auto org_width = (size_t)sqrt(in->cols());\r\n\t\tfor (unsigned int channel = 0; channel < out->rows(); ++channel)\r\n\t\t{\r\n\t\t\tMatrixRmMap(out->row(channel).data(), padded_width, padded_width).block(offset /2, offset/2, org_width, org_width) \r\n\t\t\t\t= MatrixRmMap(in->row(channel).data(), org_width, org_width);\r\n\t\t}\r\n\t}\r\n\r\n\t/*\r\n\tCrops center of the image by given offset.\r\n\t*/\r\n\tinline void crop(MatrixRm* in, MatrixRm* out, size_t offset)\r\n\t{\r\n\t\tconst size_t cropped_width = (size_t)sqrt(in->cols()) - offset;\r\n\t\t*out = MatrixRm(in->rows(), (unsigned int)pow(cropped_width, 2.));\r\n\t\tconst auto org_width = (size_t)sqrt(in->cols());\r\n\t\tfor (unsigned int channel = 0; channel < out->rows(); ++channel)\r\n\t\t{\r\n\t\t\tMatrixRmMap(out->row(channel).data(), cropped_width, cropped_width) = MatrixRmMap(in->row(channel).data(), org_width, org_width).block(offset / 2, offset / 2, cropped_width, cropped_width);\r\n\t\t}\r\n\t}\r\n\r\n\t/*\r\n\tInserts zeros between values of a matrix by stride - 1.\r\n\t*/\r\n\tinline void pad_inner(MatrixRm* input, MatrixRm* out, const size_t stride)\r\n\t{\r\n\t\tconst auto input_width = (size_t)sqrt(input->cols());\r\n\t\tconst size_t inner_pad = stride - 1;\r\n\t\tconst size_t out_width = input_width + (input_width*inner_pad - 1);\r\n\t\t*out = MatrixRm::Zero(input->rows(), (unsigned int)pow(out_width, 2.));\r\n\t\tsize_t current_pos = 0;\r\n\t\tfor (int i = 0; i < input->cols(); ++i)\r\n\t\t{\r\n\t\t\tout->block(0, current_pos, input->rows(), 1) = input->block(0, i, input->rows(), 1);\r\n\t\t\tif (++current_pos % out_width != 0)\r\n\t\t\t{\r\n\t\t\t\tcurrent_pos += inner_pad;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tcurrent_pos += out_width;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/*\r\n\tReverse's pad_inner method using stride - 1.\r\n\t*/\r\n\tinline void unpad_inner(MatrixRm* input, MatrixRm* out, const size_t org_width, const size_t stride)\r\n\t{\r\n\t\tconst auto input_width = (size_t)sqrt(input->cols());\r\n\t\tconst auto inner_pad = stride - 1;\r\n\t\t*out = MatrixRm::Zero(input->rows(), (unsigned int)pow(org_width, 2.));\r\n\t\tsize_t current_pos = 0;\r\n\t\tfor (int i = 0; i < out->cols(); ++i)\r\n\t\t{\r\n\t\t\tout->block(0, i, input->rows(), 1) = input->block(0, current_pos, input->rows(), 1);\r\n\t\t\tif (++current_pos % input_width != 0)\r\n\t\t\t{\r\n\t\t\t\tcurrent_pos += inner_pad;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tcurrent_pos += input_width;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/*\r\n\tPerforms im2col operation. As before, see Caffe's source code for further details. This can potentially implemented in a faster way....\r\n\t*/\r\n\tinline void im2col(MatrixRm* input, MatrixRm* out, const size_t kernel_width, const size_t kernel_size, const size_t stride)\r\n\t{\r\n\t\tconst auto input_width = (size_t)sqrt(input->cols());\r\n\t\tconst auto kernel_moves = (size_t)((input_width - kernel_width) / stride) + 1;\r\n\t\t*out = MatrixRm::Zero(input->rows()* kernel_size, (unsigned int)pow(kernel_moves, 2));\r\n\t\tsize_t column_idx = 0;\r\n\t\tMatrixRm tile = MatrixRm::Zero(input->rows(), kernel_size);\r\n\t\tfor (size_t row = 0; row < kernel_moves; ++row)\r\n\t\t{\r\n\t\t\tconst size_t current_row = row * input_width;\r\n\t\t\tfor (size_t col = 0; col < kernel_moves; ++col)\r\n\t\t\t{\r\n\t\t\t\tconst size_t current_pos = (current_row*stride) + (col*stride);\r\n\t\t\t\tfor (size_t kernel_row = 0; kernel_row < kernel_width; ++kernel_row)\r\n\t\t\t\t{\r\n\t\t\t\t\ttile.block(0, kernel_row*kernel_width, input->rows(), kernel_width) =\r\n\t\t\t\t\t\tinput->block(0, current_pos + kernel_row*input_width, input->rows(), kernel_width);\r\n\t\t\t\t}\r\n\t\t\t\tout->col(column_idx++) = Eigen::Map<Eigen::VectorXf>(tile.data(), out->rows());\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/*\r\n\tPerforms im2col operation. See Caffe's source code for further details.\r\n\t*/\r\n\tinline void im2col(MatrixRm* input, MatrixRm* out, ConvolutionParams& conv_params)\r\n\t{\r\n\t\tim2col(input, out, conv_params.kernel_width(), conv_params.kernel_size(), conv_params.stride());\r\n\t}\r\n\r\n\t/*\r\n\tReverse operation for im2col.\r\n\t*/\r\n\tinline void col2im(MatrixRm* input, const MatrixRm* im2col, MatrixRm* out, ConvolutionParams& conv_params)\r\n\t{\r\n\t\tconst auto input_width = (size_t)sqrt(input->cols());\r\n\t\tconst auto kernel_moves = (size_t)((input_width - conv_params.kernel_width()) / conv_params.stride()) + 1;\r\n\t\t*out = MatrixRm::Zero(input->rows(), input->cols());\r\n\t\tsize_t col_cnt = 0;\r\n\t\tfor (size_t row = 0; row < kernel_moves; ++row)\r\n\t\t{\r\n\t\t\tfor (size_t col = 0; col < kernel_moves; ++col)\r\n\t\t\t{\r\n\t\t\t\tfor (int ch = 0; ch < input->rows(); ++ch)\r\n\t\t\t\t{\r\n\t\t\t\t\tMatrixRm chunk = im2col->block(ch * conv_params.kernel_size(), col_cnt, conv_params.kernel_size(), 1);\r\n\t\t\t\t\tMatrixRmMap(out->row(ch).data(), input_width, input_width).block(row, col, conv_params.kernel_width(), conv_params.kernel_width()).array()\r\n\t\t\t\t\t\t+= MatrixRmMap(chunk.data(), conv_params.kernel_width(), conv_params.kernel_width()).array();\r\n\t\t\t\t}\r\n\t\t\t\t++col_cnt;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/*\r\n\tAlternative col2im method... still reversing the col2im.\r\n\t*/\r\n\tinline void col2im(MatrixRm* im2col, MatrixRm* out, const size_t output_width, ConvolutionParams& conv_params)\r\n\t{\r\n\t\tconst size_t output_depth = (size_t)im2col->rows() / conv_params.kernel_size();\r\n\t\t*out = MatrixRm::Zero(output_depth, output_width * output_width);\r\n\t\tsize_t row = 0;\r\n\t\tsize_t col = 0;\r\n\t\tfor (int i = 0; i < im2col->cols(); i++)\r\n\t\t{\r\n\t\t\tfor (size_t j = 0; j < output_depth; j++)\r\n\t\t\t{\r\n\t\t\t\tMatrixRm chunk = im2col->block(j*conv_params.kernel_size(), 0, conv_params.kernel_size(), 1);\r\n\t\t\t\tMatrixRmMap(out->row(j).data(), output_width, output_width).block(col, row, conv_params.kernel_width(), conv_params.kernel_width()).array() +=\r\n\t\t\t\t\tMatrixRmMap(chunk.data(), conv_params.kernel_width(), conv_params.kernel_width()).array();\r\n\r\n\t\t\t}\r\n\t\t\tcol += conv_params.stride();\r\n\t\t\tif ((col + conv_params.kernel_width()) > output_width)\r\n\t\t\t{\r\n\t\t\t\tcol = 0;\r\n\t\t\t\trow += conv_params.stride();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/*\r\n\tComputes weight gradient as matrix multiplication.\r\n\t*/\r\n\tinline void compute_wgrad_gemm_cpu(MatrixRm* dout, MatrixRm* im2col_input, MatrixRm* wgrad, MatrixRm* dout_rs, const size_t w_rows, const size_t w_cols, const size_t num_filters)\r\n\t{\r\n\t\tconst size_t row_len = (size_t)(dout->cols() * dout->rows()) / num_filters;\r\n\t\t*dout_rs = MatrixRmMap(dout->transpose().data(), w_rows, row_len);\r\n\t\tMatrixRm wgrad_tmp = *dout_rs * im2col_input->transpose();\r\n\t\t*wgrad = MatrixRmMap(wgrad_tmp.data(), w_rows, w_cols).array();\r\n\t}\r\n\r\n\t/*\r\n\tComputes input delta as matrix multiplication.\r\n\t*/\r\n\tinline void compute_dx_gemm_cpu(MatrixRm* dx, MatrixRm* dout_rs, MatrixRm* input, MatrixRm* w, ConvolutionParams& conv_params)\r\n\t{\r\n\t\tMatrixRm dx_col = w->transpose() * *dout_rs;\r\n\t\tcol2im(input, &dx_col, dx, conv_params);\r\n\t}\r\n\r\n\t/*\r\n\tComputes backwards pass of a convolution layer as matrix multiplication...probably the wrong place for this.\r\n\t*/\r\n\tinline void backward_gemm_cpu(MatrixRm* dout, MatrixRm* dx, MatrixRm* input, MatrixRm* im2col_input, MatrixRm* w, MatrixRm* wgrad, ConvolutionParams& conv_params)\r\n\t{\r\n\r\n\t\tconst size_t row_len = (size_t)(dout->cols() * dout->rows()) / wgrad->rows();\r\n\t\tMatrixRm dout_rs = MatrixRmMap(dout->transpose().data(), wgrad->rows(), row_len);\r\n\t\tMatrixRm raw_grads = dout_rs * im2col_input->transpose();\r\n\t\t*wgrad = MatrixRmMap(raw_grads.data(), wgrad->rows(), wgrad->cols());\r\n\t\tMatrixRm dx_col = w->transpose() * dout_rs;\r\n\t\tcol2im(input, &dx_col, dx, conv_params);\r\n\t}\r\n\r\n\tinline void crop_center(MatrixRm* in, MatrixRm* out, size_t offset)\r\n\t{\r\n\t\tconst auto input_width = (size_t)sqrt(in->cols());\r\n\t\tconst size_t delta = input_width - (2 * offset);\r\n\t\tconst size_t border = 2 * offset;\r\n\t\t*out = MatrixRm(in->rows(), (size_t)pow(delta, 2.));\r\n\t\tsize_t start = (offset * input_width) + offset;\r\n\t\tfor (size_t i = 0; i < delta; ++i)\r\n\t\t{\r\n\t\t\tout->block(0, i*delta, in->rows(), delta) = in->block(0, start, in->rows(), delta);\r\n\t\t\tstart += delta + border;\r\n\t\t}\r\n\t}\r\n\r\n\tinline void pad_border(MatrixRm& in, MatrixRm& out, size_t offset)\r\n\t{\r\n\t\tconst auto input_width = (size_t)sqrt(in.cols());\r\n\t\tconst size_t steps = 2 * offset + input_width;\r\n\t\tsize_t start = 0;\r\n\t\tfor (size_t i = 0; i < input_width; ++i)\r\n\t\t{\r\n\t\t\tout.block(0, start, in.rows(), input_width) = in.block(0, i*input_width, in.rows(), input_width);\r\n\t\t\tstart += steps;\r\n\t\t}\r\n\t}\r\n\r\n\tinline MatrixRm encode_one_hot_axis1(const size_t class_idx, const size_t num_classes)\r\n\t{\r\n\t\tMatrixRm one_hot_encoded_mat = MatrixRm::Zero(1, num_classes);\r\n\t\tfor (size_t i = 0; i < num_classes; ++i)\r\n\t\t{\r\n\t\t\tif (class_idx == i)\r\n\t\t\t{\r\n\t\t\t\tone_hot_encoded_mat(0, i) = 1.f;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn one_hot_encoded_mat;\r\n\t}\r\n\r\n\r\n\t/*\r\n\t* Function to encode labels to one-hot over x-axis, e.g. 2 -> [0, 1]\r\n\t* @param clas_idx\r\n\t* @param num_classes\r\n\t* @return the one-hot encoded vector\r\n\t*/\r\n\tinline MatrixRm encode_one_hot(const size_t class_idx, const size_t num_classes)\r\n\t{\r\n\t\tMatrixRm one_hot_encoded_mat = MatrixRm::Zero(1, num_classes);\r\n\t\tfor (size_t i = 0; i < num_classes; ++i)\r\n\t\t{\r\n\t\t\tif (class_idx == i)\r\n\t\t\t{\r\n\t\t\t\tone_hot_encoded_mat(0, i) = 1.f;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn one_hot_encoded_mat;\r\n\t}\r\n\r\n\tinline void encode_one_hot(MatrixRm& label, const size_t class_idx, const size_t num_classes)\r\n\t{\r\n\t\tlabel = MatrixRm::Zero(1, num_classes);\r\n\t\tfor (size_t i = 0; i < num_classes; ++i)\r\n\t\t{\r\n\t\t\tif (class_idx == i)\r\n\t\t\t{\r\n\t\t\t\tlabel(0, i) = 1.f;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/*\r\n\t* Function to encode labels to one-hot over y-axis, e.g. 2 -> [0, 1]\r\n\t* @param clas_idx\r\n\t* @param num_classes\r\n\t* @return the one-hot encoded matrix\r\n\t*/\r\n\t/*\r\n\tMatrixRm encode_one_hot(const MatrixRm& label, const size_t num_classes)\r\n\t{\r\n\t\tMatrixRm one_hot_encoded_mat = MatrixRm::Zero(num_classes, label.cols());\r\n\t\tfor (int i = 0; i < label.cols(); ++i)\r\n\t\t{\r\n\t\t\tfor (size_t j = 0; j < num_classes; ++j)\r\n\t\t\t{\r\n\t\t\t\tif ((size_t)label(0, i) == j)\r\n\t\t\t\t{\r\n\t\t\t\t\tone_hot_encoded_mat(j, i) = 1.f;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn one_hot_encoded_mat;\r\n\t}\r\n\t*/\r\n\r\n\tinline void encode_label(AlignedStdVector& data_container, const size_t num_classes, const float label)\r\n\t{\r\n\t\tif (num_classes > 1)\r\n\t\t{\r\n\t\t\tMatrixRm label_mat = encode_one_hot((size_t)label, num_classes);\r\n\t\t\tdata_container.push_back(label_mat);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tMatrixRm label_mat(1, 1);\r\n\t\t\tlabel_mat(0, 0) = label;\r\n\t\t\tdata_container.push_back(label_mat);\r\n\t\t}\r\n\t}\r\n\r\n\t/*\r\n\t* Argmax of a given input. Will determine the axis to perform action by the shape of outputs.\r\n\t* NOTE: Currently only 1d data is processed correctly.\r\n\t*/\r\n\tinline unsigned int argmax(MatrixRm* outputs)\r\n\t{\r\n\t\tunsigned int i = 0, j = 0;\r\n\t\toutputs->maxCoeff(&i, &j);\r\n\t\treturn j;\r\n\t}\r\n\r\n\tinline unsigned int argmax(MatrixRm& outputs)\r\n\t{\r\n\t\treturn argmax(&outputs);\r\n\t}\r\n\r\n\tinline void depthwise_argmax(MatrixRm& outputs, MatrixRm& argmaxed)\r\n\t{\r\n\t\targmaxed = MatrixRm::Zero(1, outputs.cols());\r\n\t\tfor (int col = 0; col < outputs.cols(); ++col)\r\n\t\t{\r\n\t\t\tunsigned int i = 0, j = 0;\r\n\t\t\toutputs.block(0, col, outputs.rows(), 1).maxCoeff(&i, &j);\r\n\t\t\targmaxed(0, col) = (float)i;\r\n\t\t}\r\n\t}\r\n\r\n\t/*\r\n\t* Argmax of a given input. Will determine the axis to perform action by the shape of outputs.\r\n\t* NOTE: Currently only 1d data is processed correctly.\r\n\t*/\r\n\tinline void argmax(MatrixRm& outputs, MatrixRm& result)\r\n\t{\r\n\t\tfor (unsigned int i = 0; i < outputs.cols(); ++i)\r\n\t\t{\r\n\t\t\tunsigned int x = 0, y = 0;\r\n\t\t\toutputs.block(0, i, outputs.rows(), 1).maxCoeff(&x, &y);\r\n\t\t\tresult(0, i) = (float)y;\r\n\t\t}\r\n\t}\r\n\r\n\tinline MatrixRm to_matrix(std::vector<std::vector<float> > data)\r\n\t{\r\n\t\tMatrixRm sample = MatrixRm::Zero(data.size(), data[0].size());\r\n\t\tfor (size_t i = 0; i < data.size(); i++)\r\n\t\t{\r\n\t\t\tfor (size_t j = 0; j < data[i].size(); j++)\r\n\t\t\t{\r\n\t\t\t\tsample(i, j) = data[i][j];\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn sample;\r\n\t}\r\n\r\n\t/*\r\n\tMatrixRm to_matrix(std::vector<std::vector<float> > data)\r\n\t{\r\n\t\tMatrixRm sample = MatrixRm::Zero(data.size(), data[0].size());\r\n\t\tfor (size_t i = 0; i < data.size(); i++)\r\n\t\t{\r\n\t\t\tfor (size_t j = 0; j < data[i].size(); j++)\r\n\t\t\t{\r\n\t\t\t\tsample(i, j) = data[i][j];\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn sample;\r\n\t}\r\n\t*/\r\n}\r\n#endif\r\n", "meta": {"hexsha": "58e887c9ee5d9a3d3a996e988ad8f081e1003788", "size": 19536, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cnet/src/cnet_common.hpp", "max_stars_repo_name": "ba5t1an/cnet", "max_stars_repo_head_hexsha": "7e78462d4146fa56f1396b22347b336d2d066936", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cnet/src/cnet_common.hpp", "max_issues_repo_name": "ba5t1an/cnet", "max_issues_repo_head_hexsha": "7e78462d4146fa56f1396b22347b336d2d066936", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cnet/src/cnet_common.hpp", "max_forks_repo_name": "ba5t1an/cnet", "max_forks_repo_head_hexsha": "7e78462d4146fa56f1396b22347b336d2d066936", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6885245902, "max_line_length": 193, "alphanum_fraction": 0.6344185094, "num_tokens": 5901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2758066636828176}}
{"text": "// r_c_shortest_paths.hpp header file\n\n// Copyright Michael Drexl 2005, 2006.\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GRAPH_R_C_SHORTEST_PATHS_HPP\n#define BOOST_GRAPH_R_C_SHORTEST_PATHS_HPP\n\n#include <map>\n#include <queue>\n#include <vector>\n#include <list>\n\n#include <boost/make_shared.hpp>\n#include <boost/enable_shared_from_this.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/property_map/property_map.hpp>\n\nnamespace boost {\n\n// r_c_shortest_paths_label struct\ntemplate<class Graph, class Resource_Container>\nstruct r_c_shortest_paths_label : public boost::enable_shared_from_this<r_c_shortest_paths_label<Graph, Resource_Container> >\n{\n  r_c_shortest_paths_label\n  ( const unsigned long n,\n    const Resource_Container& rc = Resource_Container(),\n    const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > pl = boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> >(),\n    const typename graph_traits<Graph>::edge_descriptor& ed = graph_traits<Graph>::edge_descriptor(),\n    const typename graph_traits<Graph>::vertex_descriptor& vd = graph_traits<Graph>::vertex_descriptor() )\n  : num( n ),\n    cumulated_resource_consumption( rc ),\n    p_pred_label( pl ),\n    pred_edge( ed ),\n    resident_vertex( vd ),\n    b_is_dominated( false ),\n    b_is_processed( false )\n  {}\n\n  r_c_shortest_paths_label& operator=( const r_c_shortest_paths_label& other )\n  {\n    if( this == &other )\n      return *this;\n    this->~r_c_shortest_paths_label();\n    new( this ) r_c_shortest_paths_label( other );\n    return *this;\n  }\n  const unsigned long num;\n  Resource_Container cumulated_resource_consumption;\n  const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > p_pred_label;\n  const typename graph_traits<Graph>::edge_descriptor pred_edge;\n  const typename graph_traits<Graph>::vertex_descriptor resident_vertex;\n  bool b_is_dominated;\n  bool b_is_processed;\n}; // r_c_shortest_paths_label\n\ntemplate<class Graph, class Resource_Container>\ninline bool operator==\n( const r_c_shortest_paths_label<Graph, Resource_Container>& l1,\n  const r_c_shortest_paths_label<Graph, Resource_Container>& l2 )\n{\n  return\n    l1.cumulated_resource_consumption == l2.cumulated_resource_consumption;\n}\n\ntemplate<class Graph, class Resource_Container>\ninline bool operator!=\n( const r_c_shortest_paths_label<Graph, Resource_Container>& l1,\n  const r_c_shortest_paths_label<Graph, Resource_Container>& l2 )\n{\n  return\n    !( l1 == l2 );\n}\n\ntemplate<class Graph, class Resource_Container>\ninline bool operator<\n( const r_c_shortest_paths_label<Graph, Resource_Container>& l1,\n  const r_c_shortest_paths_label<Graph, Resource_Container>& l2 )\n{\n  return\n    l1.cumulated_resource_consumption < l2.cumulated_resource_consumption;\n}\n\ntemplate<class Graph, class Resource_Container>\ninline bool operator>\n( const r_c_shortest_paths_label<Graph, Resource_Container>& l1,\n  const r_c_shortest_paths_label<Graph, Resource_Container>& l2 )\n{\n  return\n    l2.cumulated_resource_consumption < l1.cumulated_resource_consumption;\n}\n\ntemplate<class Graph, class Resource_Container>\ninline bool operator<=\n( const r_c_shortest_paths_label<Graph, Resource_Container>& l1,\n  const r_c_shortest_paths_label<Graph, Resource_Container>& l2 )\n{\n  return\n    l1 < l2 || l1 == l2;\n}\n\ntemplate<class Graph, class Resource_Container>\ninline bool operator>=\n( const r_c_shortest_paths_label<Graph, Resource_Container>& l1,\n  const r_c_shortest_paths_label<Graph, Resource_Container>& l2 )\n{\n  return l2 < l1 || l1 == l2;\n}\n\ntemplate<typename Graph, typename Resource_Container>\ninline bool operator<\n        ( const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > &t,\n          const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > &u) {\n    return *t < *u;\n}\n\ntemplate<typename Graph, typename Resource_Container>\ninline bool operator<=( const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > &t,\n                        const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > &u ) {\n    return *t <= *u;\n}\n\ntemplate<typename Graph, typename Resource_Container>\ninline bool operator>\n        (\n          const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > &t,\n          const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > &u ) {\n    return *t > *u;\n}\n\ntemplate<typename Graph, typename Resource_Container>\ninline bool operator>=\n        (\n          const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > &t,\n          const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > &u) {\n    return *t >= *u;\n}\n\nnamespace detail {\n\n// r_c_shortest_paths_dispatch function (body/implementation)\ntemplate<class Graph,\n         class VertexIndexMap,\n         class EdgeIndexMap,\n         class Resource_Container,\n         class Resource_Extension_Function,\n         class Dominance_Function,\n         class Label_Allocator,\n         class Visitor>\nvoid r_c_shortest_paths_dispatch\n( const Graph& g,\n  const VertexIndexMap& vertex_index_map,\n  const EdgeIndexMap& /*edge_index_map*/,\n  typename graph_traits<Graph>::vertex_descriptor s,\n  typename graph_traits<Graph>::vertex_descriptor t,\n  // each inner vector corresponds to a pareto-optimal path\n  std::vector\n    <std::vector\n      <typename graph_traits\n        <Graph>::edge_descriptor> >& pareto_optimal_solutions,\n  std::vector\n    <Resource_Container>& pareto_optimal_resource_containers,\n  bool b_all_pareto_optimal_solutions,\n  // to initialize the first label/resource container\n  // and to carry the type information\n  const Resource_Container& rc,\n  Resource_Extension_Function& ref,\n  Dominance_Function& dominance,\n  // to specify the memory management strategy for the labels\n  Label_Allocator /*la*/,\n  Visitor vis )\n{\n  pareto_optimal_resource_containers.clear();\n  pareto_optimal_solutions.clear();\n\n  size_t i_label_num = 0;\n#if defined(BOOST_NO_CXX11_ALLOCATOR)\n  typedef\n    typename\n      Label_Allocator::template rebind\n        <r_c_shortest_paths_label\n          <Graph, Resource_Container> >::other LAlloc;\n#else\n  typedef\n     typename\n     std::allocator_traits<Label_Allocator>::template rebind_alloc\n     <r_c_shortest_paths_label\n     <Graph, Resource_Container> > LAlloc;\n  typedef std::allocator_traits<LAlloc> LTraits;\n#endif\n  LAlloc l_alloc;\n  typedef\n    boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > Splabel;\n  std::priority_queue<Splabel, std::vector<Splabel>, std::greater<Splabel> >\n    unprocessed_labels;\n\n  bool b_feasible = true;\n  Splabel splabel_first_label = boost::allocate_shared<r_c_shortest_paths_label<Graph, Resource_Container> >(\n          l_alloc,\n          i_label_num++,\n          rc,\n          boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> >(),\n          typename graph_traits<Graph>::edge_descriptor(),\n          s );\n\n  unprocessed_labels.push( splabel_first_label );\n  std::vector<std::list<Splabel> > vec_vertex_labels_data( num_vertices( g ) );\n  iterator_property_map<typename std::vector<std::list<Splabel> >::iterator,\n                        VertexIndexMap>\n    vec_vertex_labels(vec_vertex_labels_data.begin(), vertex_index_map);\n  vec_vertex_labels[s].push_back( splabel_first_label );\n  typedef\n    std::vector<typename std::list<Splabel>::iterator>\n    vec_last_valid_positions_for_dominance_data_type;\n  vec_last_valid_positions_for_dominance_data_type\n    vec_last_valid_positions_for_dominance_data( num_vertices( g ) );\n  iterator_property_map<\n      typename vec_last_valid_positions_for_dominance_data_type::iterator,\n      VertexIndexMap>\n    vec_last_valid_positions_for_dominance\n      (vec_last_valid_positions_for_dominance_data.begin(),\n       vertex_index_map);\n  BGL_FORALL_VERTICES_T(v, g, Graph) {\n    put(vec_last_valid_positions_for_dominance, v, vec_vertex_labels[v].begin());\n  }\n  std::vector<size_t> vec_last_valid_index_for_dominance_data( num_vertices( g ), 0 );\n  iterator_property_map<std::vector<size_t>::iterator, VertexIndexMap>\n    vec_last_valid_index_for_dominance\n      (vec_last_valid_index_for_dominance_data.begin(), vertex_index_map);\n  std::vector<bool>\n    b_vec_vertex_already_checked_for_dominance_data( num_vertices( g ), false );\n  iterator_property_map<std::vector<bool>::iterator, VertexIndexMap>\n    b_vec_vertex_already_checked_for_dominance\n      (b_vec_vertex_already_checked_for_dominance_data.begin(),\n       vertex_index_map);\n\n  while( !unprocessed_labels.empty()  && vis.on_enter_loop(unprocessed_labels, g) )\n  {\n    Splabel cur_label = unprocessed_labels.top();\n    unprocessed_labels.pop();\n    vis.on_label_popped( *cur_label, g );\n    // an Splabel object in unprocessed_labels and the respective Splabel\n    // object in the respective list<Splabel> of vec_vertex_labels share their\n    // embedded r_c_shortest_paths_label object\n    // to avoid memory leaks, dominated\n    // r_c_shortest_paths_label objects are marked and deleted when popped\n    // from unprocessed_labels, as they can no longer be deleted at the end of\n    // the function; only the Splabel object in unprocessed_labels still\n    // references the r_c_shortest_paths_label object\n    // this is also for efficiency, because the else branch is executed only\n    // if there is a chance that extending the\n    // label leads to new undominated labels, which in turn is possible only\n    // if the label to be extended is undominated\n    if( !cur_label->b_is_dominated )\n    {\n      typename boost::graph_traits<Graph>::vertex_descriptor\n        i_cur_resident_vertex = cur_label->resident_vertex;\n      std::list<Splabel>& list_labels_cur_vertex =\n        get(vec_vertex_labels, i_cur_resident_vertex);\n      if( list_labels_cur_vertex.size() >= 2\n          && vec_last_valid_index_for_dominance[i_cur_resident_vertex]\n               < list_labels_cur_vertex.size() )\n      {\n        typename std::list<Splabel>::iterator outer_iter =\n          list_labels_cur_vertex.begin();\n        bool b_outer_iter_at_or_beyond_last_valid_pos_for_dominance = false;\n        while( outer_iter != list_labels_cur_vertex.end() )\n        {\n          Splabel cur_outer_splabel = *outer_iter;\n          typename std::list<Splabel>::iterator inner_iter = outer_iter;\n          if( !b_outer_iter_at_or_beyond_last_valid_pos_for_dominance\n              && outer_iter ==\n                   get(vec_last_valid_positions_for_dominance,\n                       i_cur_resident_vertex) )\n            b_outer_iter_at_or_beyond_last_valid_pos_for_dominance = true;\n          if( !get(b_vec_vertex_already_checked_for_dominance, i_cur_resident_vertex)\n              || b_outer_iter_at_or_beyond_last_valid_pos_for_dominance )\n          {\n            ++inner_iter;\n          }\n          else\n          {\n            inner_iter =\n              get(vec_last_valid_positions_for_dominance,\n                  i_cur_resident_vertex);\n            ++inner_iter;\n          }\n          bool b_outer_iter_erased = false;\n          while( inner_iter != list_labels_cur_vertex.end() )\n          {\n            Splabel cur_inner_splabel = *inner_iter;\n            if( dominance( cur_outer_splabel->\n                             cumulated_resource_consumption,\n                           cur_inner_splabel->\n                             cumulated_resource_consumption ) )\n            {\n              typename std::list<Splabel>::iterator buf = inner_iter;\n              ++inner_iter;\n              list_labels_cur_vertex.erase( buf );\n              if( cur_inner_splabel->b_is_processed )\n              {\n                cur_inner_splabel.reset();\n              }\n              else\n                cur_inner_splabel->b_is_dominated = true;\n              continue;\n            }\n            else\n              ++inner_iter;\n            if( dominance( cur_inner_splabel->\n                             cumulated_resource_consumption,\n                           cur_outer_splabel->\n                             cumulated_resource_consumption ) )\n            {\n              typename std::list<Splabel>::iterator buf = outer_iter;\n              ++outer_iter;\n              list_labels_cur_vertex.erase( buf );\n              b_outer_iter_erased = true;\n              if( cur_outer_splabel->b_is_processed )\n              {\n                cur_outer_splabel.reset();\n              }\n              else\n                cur_outer_splabel->b_is_dominated = true;\n              break;\n            }\n          }\n          if( !b_outer_iter_erased )\n            ++outer_iter;\n        }\n        if( list_labels_cur_vertex.size() > 1 )\n          put(vec_last_valid_positions_for_dominance, i_cur_resident_vertex,\n            (--(list_labels_cur_vertex.end())));\n        else\n          put(vec_last_valid_positions_for_dominance, i_cur_resident_vertex,\n            list_labels_cur_vertex.begin());\n        put(b_vec_vertex_already_checked_for_dominance,\n            i_cur_resident_vertex, true);\n        put(vec_last_valid_index_for_dominance, i_cur_resident_vertex,\n          list_labels_cur_vertex.size() - 1);\n      }\n    }\n    if( !b_all_pareto_optimal_solutions && cur_label->resident_vertex == t )\n    {\n      // the devil don't sleep\n      if( cur_label->b_is_dominated )\n      {\n        cur_label.reset();\n      }\n      while( unprocessed_labels.size() )\n      {\n        Splabel l = unprocessed_labels.top();\n        unprocessed_labels.pop();\n        // delete only dominated labels, because nondominated labels are\n        // deleted at the end of the function\n        if( l->b_is_dominated )\n        {\n          l.reset();\n        }\n      }\n      break;\n    }\n    if( !cur_label->b_is_dominated )\n    {\n      cur_label->b_is_processed = true;\n      vis.on_label_not_dominated( *cur_label, g );\n      typename graph_traits<Graph>::vertex_descriptor cur_vertex =\n        cur_label->resident_vertex;\n      typename graph_traits<Graph>::out_edge_iterator oei, oei_end;\n      for( boost::tie( oei, oei_end ) = out_edges( cur_vertex, g );\n           oei != oei_end;\n           ++oei )\n      {\n        b_feasible = true;\n        Splabel new_label = boost::allocate_shared<r_c_shortest_paths_label<Graph, Resource_Container> >(\n                l_alloc,\n                i_label_num++,\n                cur_label->cumulated_resource_consumption,\n                cur_label,\n                *oei,\n                target( *oei, g ) );\n        b_feasible =\n          ref( g,\n               new_label->cumulated_resource_consumption,\n               new_label->p_pred_label->cumulated_resource_consumption,\n               new_label->pred_edge );\n\n        if( !b_feasible )\n        {\n          vis.on_label_not_feasible( *new_label, g );\n          new_label.reset();\n        }\n        else\n        {\n          vis.on_label_feasible( *new_label, g );\n          vec_vertex_labels[new_label->resident_vertex].\n            push_back( new_label );\n          unprocessed_labels.push( new_label );\n        }\n      }\n    }\n    else\n    {\n      vis.on_label_dominated( *cur_label, g );\n      cur_label.reset();\n    }\n  }\n  std::list<Splabel> dsplabels = get(vec_vertex_labels, t);\n  typename std::list<Splabel>::const_iterator csi = dsplabels.begin();\n  typename std::list<Splabel>::const_iterator csi_end = dsplabels.end();\n  // if d could be reached from o\n  if( !dsplabels.empty() )\n  {\n    for( ; csi != csi_end; ++csi )\n    {\n      std::vector<typename graph_traits<Graph>::edge_descriptor>\n        cur_pareto_optimal_path;\n      boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > p_cur_label = *csi;\n      pareto_optimal_resource_containers.\n        push_back( p_cur_label->cumulated_resource_consumption );\n      while( p_cur_label->num != 0 )\n      {\n        cur_pareto_optimal_path.push_back( p_cur_label->pred_edge );\n        p_cur_label = p_cur_label->p_pred_label;\n\n        // assertion b_is_valid beyond this point is not correct if the domination function\n        // requires resource levels to be strictly greater than existing values\n        //\n        // Example\n        // Customers\n        // id   min_arrival   max_departure\n        //  2             0             974\n        //  3             0             972\n        //  4             0             964\n        //  5           678             801\n        //\n        // Path A: 2-3-4-5 (times: 0-16-49-84-678)\n        // Path B: 3-2-4-5 (times: 0-18-51-62-678)\n        // The partial path 3-2-4 dominates the other partial path 2-3-4,\n        // though the path 3-2-4-5 does not strictly dominate the path 2-3-4-5\n      }\n      pareto_optimal_solutions.push_back( cur_pareto_optimal_path );\n      if( !b_all_pareto_optimal_solutions )\n        break;\n    }\n  }\n\n  BGL_FORALL_VERTICES_T(i, g, Graph) {\n    std::list<Splabel>& list_labels_cur_vertex = vec_vertex_labels[i];\n    typename std::list<Splabel>::iterator si = list_labels_cur_vertex.begin();\n    const typename std::list<Splabel>::iterator si_end = list_labels_cur_vertex.end();\n    for(; si != si_end; ++si )\n    {\n      (*si).reset();\n    }\n  }\n} // r_c_shortest_paths_dispatch\n\n} // detail\n\n// default_r_c_shortest_paths_visitor struct\nstruct default_r_c_shortest_paths_visitor\n{\n  template<class Label, class Graph>\n  void on_label_popped( const Label&, const Graph& ) {}\n  template<class Label, class Graph>\n  void on_label_feasible( const Label&, const Graph& ) {}\n  template<class Label, class Graph>\n  void on_label_not_feasible( const Label&, const Graph& ) {}\n  template<class Label, class Graph>\n  void on_label_dominated( const Label&, const Graph& ) {}\n  template<class Label, class Graph>\n  void on_label_not_dominated( const Label&, const Graph& ) {}\n  template<class Queue, class Graph>\n  bool on_enter_loop(const Queue& queue, const Graph& graph) {return true;}\n}; // default_r_c_shortest_paths_visitor\n\n\n// default_r_c_shortest_paths_allocator\ntypedef\n  std::allocator<int> default_r_c_shortest_paths_allocator;\n// default_r_c_shortest_paths_allocator\n\n\n// r_c_shortest_paths functions (handle/interface)\n// first overload:\n// - return all pareto-optimal solutions\n// - specify Label_Allocator and Visitor arguments\ntemplate<class Graph,\n         class VertexIndexMap,\n         class EdgeIndexMap,\n         class Resource_Container,\n         class Resource_Extension_Function,\n         class Dominance_Function,\n         class Label_Allocator,\n         class Visitor>\nvoid r_c_shortest_paths\n( const Graph& g,\n  const VertexIndexMap& vertex_index_map,\n  const EdgeIndexMap& edge_index_map,\n  typename graph_traits<Graph>::vertex_descriptor s,\n  typename graph_traits<Graph>::vertex_descriptor t,\n  // each inner vector corresponds to a pareto-optimal path\n  std::vector<std::vector<typename graph_traits<Graph>::edge_descriptor> >&\n    pareto_optimal_solutions,\n  std::vector<Resource_Container>& pareto_optimal_resource_containers,\n  // to initialize the first label/resource container\n  // and to carry the type information\n  const Resource_Container& rc,\n  const Resource_Extension_Function& ref,\n  const Dominance_Function& dominance,\n  // to specify the memory management strategy for the labels\n  Label_Allocator la,\n  Visitor vis )\n{\n  r_c_shortest_paths_dispatch( g,\n                               vertex_index_map,\n                               edge_index_map,\n                               s,\n                               t,\n                               pareto_optimal_solutions,\n                               pareto_optimal_resource_containers,\n                               true,\n                               rc,\n                               ref,\n                               dominance,\n                               la,\n                               vis );\n}\n\n// second overload:\n// - return only one pareto-optimal solution\n// - specify Label_Allocator and Visitor arguments\ntemplate<class Graph,\n         class VertexIndexMap,\n         class EdgeIndexMap,\n         class Resource_Container,\n         class Resource_Extension_Function,\n         class Dominance_Function,\n         class Label_Allocator,\n         class Visitor>\nvoid r_c_shortest_paths\n( const Graph& g,\n  const VertexIndexMap& vertex_index_map,\n  const EdgeIndexMap& edge_index_map,\n  typename graph_traits<Graph>::vertex_descriptor s,\n  typename graph_traits<Graph>::vertex_descriptor t,\n  std::vector<typename graph_traits<Graph>::edge_descriptor>&\n    pareto_optimal_solution,\n  Resource_Container& pareto_optimal_resource_container,\n  // to initialize the first label/resource container\n  // and to carry the type information\n  const Resource_Container& rc,\n  const Resource_Extension_Function& ref,\n  const Dominance_Function& dominance,\n  // to specify the memory management strategy for the labels\n  Label_Allocator la,\n  Visitor vis )\n{\n  // each inner vector corresponds to a pareto-optimal path\n  std::vector<std::vector<typename graph_traits<Graph>::edge_descriptor> >\n    pareto_optimal_solutions;\n  std::vector<Resource_Container> pareto_optimal_resource_containers;\n  r_c_shortest_paths_dispatch( g,\n                               vertex_index_map,\n                               edge_index_map,\n                               s,\n                               t,\n                               pareto_optimal_solutions,\n                               pareto_optimal_resource_containers,\n                               false,\n                               rc,\n                               ref,\n                               dominance,\n                               la,\n                               vis );\n  if (!pareto_optimal_solutions.empty()) {\n    pareto_optimal_solution = pareto_optimal_solutions[0];\n    pareto_optimal_resource_container = pareto_optimal_resource_containers[0];\n  }\n}\n\n// third overload:\n// - return all pareto-optimal solutions\n// - use default Label_Allocator and Visitor\ntemplate<class Graph,\n         class VertexIndexMap,\n         class EdgeIndexMap,\n         class Resource_Container,\n         class Resource_Extension_Function,\n         class Dominance_Function>\nvoid r_c_shortest_paths\n( const Graph& g,\n  const VertexIndexMap& vertex_index_map,\n  const EdgeIndexMap& edge_index_map,\n  typename graph_traits<Graph>::vertex_descriptor s,\n  typename graph_traits<Graph>::vertex_descriptor t,\n  // each inner vector corresponds to a pareto-optimal path\n  std::vector<std::vector<typename graph_traits<Graph>::edge_descriptor> >&\n    pareto_optimal_solutions,\n  std::vector<Resource_Container>& pareto_optimal_resource_containers,\n  // to initialize the first label/resource container\n  // and to carry the type information\n  const Resource_Container& rc,\n  const Resource_Extension_Function& ref,\n  const Dominance_Function& dominance )\n{\n  r_c_shortest_paths_dispatch( g,\n                               vertex_index_map,\n                               edge_index_map,\n                               s,\n                               t,\n                               pareto_optimal_solutions,\n                               pareto_optimal_resource_containers,\n                               true,\n                               rc,\n                               ref,\n                               dominance,\n                               default_r_c_shortest_paths_allocator(),\n                               default_r_c_shortest_paths_visitor() );\n}\n\n// fourth overload:\n// - return only one pareto-optimal solution\n// - use default Label_Allocator and Visitor\ntemplate<class Graph,\n         class VertexIndexMap,\n         class EdgeIndexMap,\n         class Resource_Container,\n         class Resource_Extension_Function,\n         class Dominance_Function>\nvoid r_c_shortest_paths\n( const Graph& g,\n  const VertexIndexMap& vertex_index_map,\n  const EdgeIndexMap& edge_index_map,\n  typename graph_traits<Graph>::vertex_descriptor s,\n  typename graph_traits<Graph>::vertex_descriptor t,\n  std::vector<typename graph_traits<Graph>::edge_descriptor>&\n    pareto_optimal_solution,\n  Resource_Container& pareto_optimal_resource_container,\n  // to initialize the first label/resource container\n  // and to carry the type information\n  const Resource_Container& rc,\n  const Resource_Extension_Function& ref,\n  const Dominance_Function& dominance )\n{\n  // each inner vector corresponds to a pareto-optimal path\n  std::vector<std::vector<typename graph_traits<Graph>::edge_descriptor> >\n    pareto_optimal_solutions;\n  std::vector<Resource_Container> pareto_optimal_resource_containers;\n  r_c_shortest_paths_dispatch( g,\n                               vertex_index_map,\n                               edge_index_map,\n                               s,\n                               t,\n                               pareto_optimal_solutions,\n                               pareto_optimal_resource_containers,\n                               false,\n                               rc,\n                               ref,\n                               dominance,\n                               default_r_c_shortest_paths_allocator(),\n                               default_r_c_shortest_paths_visitor() );\n  if (!pareto_optimal_solutions.empty()) {\n    pareto_optimal_solution = pareto_optimal_solutions[0];\n    pareto_optimal_resource_container = pareto_optimal_resource_containers[0];\n  }\n}\n// r_c_shortest_paths\n\n\n// check_r_c_path function\ntemplate<class Graph,\n         class Resource_Container,\n         class Resource_Extension_Function>\nvoid check_r_c_path( const Graph& g,\n                     const std::vector\n                       <typename graph_traits\n                         <Graph>::edge_descriptor>& ed_vec_path,\n                     const Resource_Container& initial_resource_levels,\n                     // if true, computed accumulated final resource levels must\n                     // be equal to desired_final_resource_levels\n                     // if false, computed accumulated final resource levels must\n                     // be less than or equal to desired_final_resource_levels\n                     bool b_result_must_be_equal_to_desired_final_resource_levels,\n                     const Resource_Container& desired_final_resource_levels,\n                     Resource_Container& actual_final_resource_levels,\n                     const Resource_Extension_Function& ref,\n                     bool& b_is_a_path_at_all,\n                     bool& b_feasible,\n                     bool& b_correctly_extended,\n                     typename graph_traits<Graph>::edge_descriptor&\n                       ed_last_extended_arc )\n{\n  size_t i_size_ed_vec_path = ed_vec_path.size();\n  std::vector<typename graph_traits<Graph>::edge_descriptor> buf_path;\n  if( i_size_ed_vec_path == 0 )\n    b_feasible = true;\n  else\n  {\n    if( i_size_ed_vec_path == 1\n        || target( ed_vec_path[0], g ) == source( ed_vec_path[1], g ) )\n      buf_path = ed_vec_path;\n    else\n      for( size_t i = i_size_ed_vec_path ; i > 0; --i )\n        buf_path.push_back( ed_vec_path[i - 1] );\n    for( size_t i = 0; i < i_size_ed_vec_path - 1; ++i )\n    {\n      if( target( buf_path[i], g ) != source( buf_path[i + 1], g ) )\n      {\n        b_is_a_path_at_all = false;\n        b_feasible = false;\n        b_correctly_extended = false;\n        return;\n      }\n    }\n  }\n  b_is_a_path_at_all = true;\n  b_feasible = true;\n  b_correctly_extended = false;\n  Resource_Container current_resource_levels = initial_resource_levels;\n  actual_final_resource_levels = current_resource_levels;\n  for( size_t i = 0; i < i_size_ed_vec_path; ++i )\n  {\n    ed_last_extended_arc = buf_path[i];\n    b_feasible = ref( g,\n                      actual_final_resource_levels,\n                      current_resource_levels,\n                      buf_path[i] );\n    current_resource_levels = actual_final_resource_levels;\n    if( !b_feasible )\n      return;\n  }\n  if( b_result_must_be_equal_to_desired_final_resource_levels )\n    b_correctly_extended =\n     actual_final_resource_levels == desired_final_resource_levels ?\n       true : false;\n  else\n  {\n    if( actual_final_resource_levels < desired_final_resource_levels\n        || actual_final_resource_levels == desired_final_resource_levels )\n      b_correctly_extended = true;\n  }\n} // check_path\n\n} // namespace\n\n#endif // BOOST_GRAPH_R_C_SHORTEST_PATHS_HPP\n", "meta": {"hexsha": "ccd778c92e2ae07f2ba0502f88351f5c392bddca", "size": 28491, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/r_c_shortest_paths.hpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/graph/r_c_shortest_paths.hpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/graph/r_c_shortest_paths.hpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 37.8869680851, "max_line_length": 161, "alphanum_fraction": 0.6612263522, "num_tokens": 6374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.27580666368281753}}
{"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 \"mesh.h\"\n#include <Eigen/Dense>\n#include <iostream>\n\nnamespace explicit_fea {\n    Mesh::Mesh(const std::vector<Node> &nodes,\n               const std::vector<std::unique_ptr<BeamElement>>& elems,\n               BCList bcs) :\n        bcs(std::move(bcs))\n    {\n        assemble_matrices(nodes, elems);\n        apply_bcs();\n    }\n    \n    SparseMatrix const& Mesh::get_global_stiffness_matrix() const {\n        return global_stiffness_matrix;\n    }\n    \n    SparseMatrix const& Mesh::get_inv_mass_matrix() const {\n        return inverse_mass_matrix;\n    }\n\n    SparseMatrix const& Mesh::get_mass_matrix() const {\n        return mass_matrix;\n    }\n\n    BCList const& Mesh::get_bcs() const {\n        return bcs;\n    }\n\n    void Mesh::assemble_matrices(const std::vector<Node> &nodes, const std::vector<std::unique_ptr<BeamElement>>& elems) {\n        int n = DOF::NUM_DOFS * nodes.size();\n        global_stiffness_matrix.resize(n, n);\n        mass_matrix.resize(n, n);\n        inverse_mass_matrix.resize(n, n);\n\n        std::vector<Eigen::Triplet<double> > stiffness_triplets, mass_triplets, inv_mass_triplets;\n        stiffness_triplets.reserve(40 * elems.size());\n        mass_triplets.reserve(40 * elems.size());\n        inv_mass_triplets.reserve(40 * elems.size());\n        LocalMatrix inv_mass, mass;\n\n        for (size_t i = 0; i < elems.size(); ++i) {\n            inv_mass = elems[i]->calculate_inv_mass_matrix(nodes);\n            mass = inv_mass.inverse();\n            append_triplets(*elems[i], stiffness_triplets, elems[i]->calculate_stiffness_matrix(nodes));\n            append_triplets(*elems[i], mass_triplets, mass);\n            append_triplets(*elems[i], inv_mass_triplets, inv_mass);\n        }\n        global_stiffness_matrix.setFromTriplets(stiffness_triplets.begin(), stiffness_triplets.end());\n        inverse_mass_matrix.setFromTriplets(inv_mass_triplets.begin(), inv_mass_triplets.end());\n        mass_matrix.setFromTriplets(mass_triplets.begin(), mass_triplets.end());\n\n        global_stiffness_matrix.prune(1.e-14);\n        mass_matrix.prune(1.e-14);\n        inverse_mass_matrix.prune(1.e-14);\n\n        global_stiffness_matrix.makeCompressed();\n        mass_matrix.makeCompressed();\n        inverse_mass_matrix.makeCompressed();\n    }\n\n    void Mesh::append_triplets(const BeamElement& elem, std::vector<Eigen::Triplet<double> > &triplets, const LocalMatrix& mat) {\n        const int nn1 = elem.get_node_numbers()[0];\n        const int nn2 = elem.get_node_numbers()[1];\n        size_t row, col;\n        const unsigned int dofs_per_elem = DOF::NUM_DOFS;\n\n        SparseMatrix sparse_mat = mat.sparseView();\n\n        for (size_t j = 0; j < sparse_mat.outerSize(); ++j) {\n            for (SparseMatrix::InnerIterator it(sparse_mat, j); it; ++it) {\n                row = it.row();\n                col = it.col();\n\n                // check position in local matrix and update corresponding global position\n                if (row < dofs_per_elem) {\n                    // top left\n                    if (col < dofs_per_elem) {\n                        triplets.push_back(Eigen::Triplet<double>(dofs_per_elem * nn1 + row,\n                                                                  dofs_per_elem * nn1 + col,\n                                                                  it.value()));\n                    }\n                        // top right\n                    else {\n                        triplets.push_back(Eigen::Triplet<double>(dofs_per_elem * nn1 + row,\n                                                                  dofs_per_elem * (nn2 - 1) + col,\n                                                                  it.value()));\n                    }\n                }\n                else {\n                    // bottom left\n                    if (col < dofs_per_elem) {\n                        triplets.push_back(Eigen::Triplet<double>(dofs_per_elem * (nn2 - 1) + row,\n                                                                  dofs_per_elem * nn1 + col,\n                                                                  it.value()));\n                    }\n                        // bottom right\n                    else {\n                        triplets.push_back(Eigen::Triplet<double>(dofs_per_elem * (nn2 - 1) + row,\n                                                                  dofs_per_elem * (nn2 - 1) + col,\n                                                                  it.value()));\n                    }\n                }\n            }\n        }\n    }\n\n    void Mesh::apply_bcs() {\n        BcsPruneFunctor prune_functor(bcs);\n        inverse_mass_matrix.prune(prune_functor);\n        for (std::set<int>::const_iterator it = prune_functor.bcs_ind_set.begin();\n             it != prune_functor.bcs_ind_set.end(); ++it) {\n            inverse_mass_matrix.insert(*it, *it) = 1.0;\n        }\n    }\n\n    Mesh::BcsPruneFunctor::BcsPruneFunctor(const BCList &bcs){\n        for (BCList::const_iterator it = bcs.begin(); it != bcs.end(); ++it) {\n            bcs_ind_set.insert((*it)->global_index);\n        }\n    }\n\n    bool Mesh::BcsPruneFunctor::operator()(int row, int col, double value) const {\n        bool row_exists = bcs_ind_set.find(row) != bcs_ind_set.end();\n        if (row_exists)\n            return false;\n\n        bool col_exists = bcs_ind_set.find(col) != bcs_ind_set.end();\n        return !col_exists;\n    }\n\n} // namespace explicit_fea", "meta": {"hexsha": "2ca8c43ebe4d8268a589ffdf0384ef278d6e3929", "size": 6807, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mesh.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/mesh.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/mesh.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": 43.082278481, "max_line_length": 129, "alphanum_fraction": 0.5749963273, "num_tokens": 1455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.27573012226707305}}
{"text": "/* $Id: step-48.cc 27687 2012-11-26 14:37:31Z kronbichler $ */\n/* Author: Katharina Kormann, Martin Kronbichler, Uppsala University, 2011-2012 */\n\n/*    $Id: step-48.cc 27687 2012-11-26 14:37:31Z kronbichler $       */\n/*                                                                */\n/*    Copyright (C) 2011-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\n// The necessary files from the deal.II library.\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/utilities.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/conditional_ostream.h>\n#include <deal.II/base/timer.h>\n#include <deal.II/lac/vector.h>\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/tria_boundary_lib.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/lac/constraint_matrix.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/compressed_simple_sparsity_pattern.h>\n#include <deal.II/lac/trilinos_vector.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/data_out.h>\n#include <deal.II/distributed/tria.h>\n\n// This includes the data structures for the efficient implementation of\n// matrix-free methods.\n#include <deal.II/lac/parallel_vector.h>\n#include <deal.II/matrix_free/matrix_free.h>\n#include <deal.II/matrix_free/fe_evaluation.h>\n\n#include <fstream>\n#include <iostream>\n#include <iomanip>\n\n\nnamespace Step48\n{\n  using namespace dealii;\n\n  // We start by defining two global variables to collect all parameters\n  // subject to changes at one place: One for the dimension and one for the\n  // finite element degree. The dimension is used in the main function as a\n  // template argument for the actual classes (like in all other deal.II\n  // programs), whereas the degree of the finite element is more crucial, as\n  // it is passed as a template argument to the implementation of the\n  // Sine-Gordon operator. Therefore, it needs to be a compile-time constant.\n  const unsigned int dimension = 2;\n  const unsigned int fe_degree = 4;\n\n\n  // @sect3{SineGordonOperation}\n\n  // The <code>SineGordonOperation</code> class implements the cell-based\n  // operation that is needed in each time step. This nonlinear operation can\n  // be implemented straight-forwardly based on the <code>MatrixFree</code>\n  // class, in the same way as a linear operation would be treated by this\n  // implementation of the finite element operator application. We apply two\n  // template arguments to the class, one for the dimension and one for the\n  // degree of the finite element. This is a difference to other functions in\n  // deal.II where only the dimension is a template argument. This is\n  // necessary to provide the inner loops in @p FEEvaluation with information\n  // about loop lengths etc., which is essential for efficiency. On the other\n  // hand, it makes it more challenging to implement the degree as a run-time\n  // parameter.\n  template <int dim, int fe_degree>\n  class SineGordonOperation\n  {\n  public:\n    SineGordonOperation(const MatrixFree<dim,double> &data_in,\n                        const double                  time_step);\n\n    void apply (parallel::distributed::Vector<double>                     &dst,\n                const std::vector<parallel::distributed::Vector<double>*> &src) const;\n\n  private:\n    const MatrixFree<dim,double>         &data;\n    const VectorizedArray<double>         delta_t_sqr;\n    parallel::distributed::Vector<double> inv_mass_matrix;\n\n    void local_apply (const MatrixFree<dim,double>               &data,\n                      parallel::distributed::Vector<double>      &dst,\n                      const std::vector<parallel::distributed::Vector<double>*> &src,\n                      const std::pair<unsigned int,unsigned int> &cell_range) const;\n  };\n\n\n\n  // @sect4{SineGordonOperation::SineGordonOperation}\n\n  // This is the constructor of the SineGordonOperation class. It receives a\n  // reference to the MatrixFree holding the problem information and the time\n  // step size as input parameters. The initialization routine sets up the\n  // mass matrix. Since we use Gauss-Lobatto elements, the mass matrix is a\n  // diagonal matrix and can be stored as a vector. The computation of the\n  // mass matrix diagonal is simple to achieve with the data structures\n  // provided by FEEvaluation: Just loop over all (macro-) cells and integrate\n  // over the function that is constant one on all quadrature points by using\n  // the <code>integrate</code> function with @p true argument at the slot for\n  // values. Finally, we invert the diagonal entries since we have to multiply\n  // by the inverse mass matrix in each time step.\n  template <int dim, int fe_degree>\n  SineGordonOperation<dim,fe_degree>::\n  SineGordonOperation(const MatrixFree<dim,double> &data_in,\n                      const double                  time_step)\n    :\n    data(data_in),\n    delta_t_sqr(make_vectorized_array(time_step *time_step))\n  {\n    VectorizedArray<double> one = make_vectorized_array (1.);\n\n    data.initialize_dof_vector (inv_mass_matrix);\n\n    FEEvaluationGL<dim,fe_degree> fe_eval(data);\n    const unsigned int            n_q_points = fe_eval.n_q_points;\n\n    for (unsigned int cell=0; cell<data.n_macro_cells(); ++cell)\n      {\n        fe_eval.reinit(cell);\n        for (unsigned int q=0; q<n_q_points; ++q)\n          fe_eval.submit_value(one,q);\n        fe_eval.integrate (true,false);\n        fe_eval.distribute_local_to_global (inv_mass_matrix);\n      }\n\n    inv_mass_matrix.compress();\n    for (unsigned int k=0; k<inv_mass_matrix.local_size(); ++k)\n      if (inv_mass_matrix.local_element(k)>1e-15)\n        inv_mass_matrix.local_element(k) = 1./inv_mass_matrix.local_element(k);\n      else\n        inv_mass_matrix.local_element(k) = 0;\n  }\n\n\n\n  // @sect4{SineGordonOperation::local_apply}\n\n  // This operator implements the core operation of the program, the\n  // integration over a range of cells for the nonlinear operator of the\n  // Sine-Gordon problem. The implementation is based on the FEEvaluationGL\n  // class since we are using the cell-based implementation for Gauss-Lobatto\n  // elements.\n\n  // The nonlinear function that we have to evaluate for the time stepping\n  // routine includes the value of the function at the present time @p current\n  // as well as the value at the previous time step @p old. Both values are\n  // passed to the operator in the collection of source vectors @p src, which\n  // is simply an STL vector of pointers to the actual solution vectors. This\n  // construct of collecting several source vectors into one is necessary as\n  // the cell loop in @p MatrixFree takes exactly one source and one\n  // destination vector, even if we happen to use many vectors like the two in\n  // this case. Note that the cell loop accepts any valid class for input and\n  // output, which does not only include vectors but general data\n  // types. However, only in case it encounters a\n  // parallel::distributed::Vector<Number> or an STL vector collecting these\n  // vectors, it calls functions that exchange data at the beginning and the\n  // end of the loop. In the loop over the cells, we first have to read in the\n  // values in the vectors related to the local values. Then, we evaluate the\n  // value and the gradient of the current solution vector and the values of\n  // the old vector at the quadrature points. Then, we combine the terms in\n  // the scheme in the loop over the quadrature points. Finally, we integrate\n  // the result against the test function and accumulate the result to the\n  // global solution vector @p dst.\n  template <int dim, int fe_degree>\n  void SineGordonOperation<dim, fe_degree>::\n  local_apply (const MatrixFree<dim>                      &data,\n               parallel::distributed::Vector<double>      &dst,\n               const std::vector<parallel::distributed::Vector<double>*> &src,\n               const std::pair<unsigned int,unsigned int> &cell_range) const\n  {\n    AssertDimension (src.size(), 2);\n    FEEvaluationGL<dim,fe_degree> current (data), old (data);\n    for (unsigned int cell=cell_range.first; cell<cell_range.second; ++cell)\n      {\n        current.reinit (cell);\n        old.reinit (cell);\n\n        current.read_dof_values (*src[0]);\n        old.read_dof_values     (*src[1]);\n\n        current.evaluate (true, true, false);\n        old.evaluate (true, false, false);\n\n        for (unsigned int q=0; q<current.n_q_points; ++q)\n          {\n            const VectorizedArray<double> current_value = current.get_value(q);\n            const VectorizedArray<double> old_value     = old.get_value(q);\n\n            current.submit_value (2.*current_value - old_value -\n                                  delta_t_sqr * std::sin(current_value),q);\n            current.submit_gradient (- delta_t_sqr *\n                                     current.get_gradient(q), q);\n          }\n\n        current.integrate (true,true);\n        current.distribute_local_to_global (dst);\n      }\n  }\n\n\n\n  //@sect4{SineGordonOperation::apply}\n\n  // This function performs the time stepping routine based on the cell-local\n  // strategy. First the destination vector is set to zero, then the cell-loop\n  // is called, and finally the solution is multiplied by the inverse mass\n  // matrix. The structure of the cell loop is implemented in the cell finite\n  // element operator class. On each cell it applies the routine defined as\n  // the <code>local_apply()</code> method of the class\n  // <code>SineGordonOperation</code>, i.e., <code>this</code>. One could also\n  // provide a function with the same signature that is not part of a class.\n  template <int dim, int fe_degree>\n  void SineGordonOperation<dim, fe_degree>::\n  apply (parallel::distributed::Vector<double>                     &dst,\n         const std::vector<parallel::distributed::Vector<double>*> &src) const\n  {\n    dst = 0;\n    data.cell_loop (&SineGordonOperation<dim,fe_degree>::local_apply,\n                    this, dst, src);\n    dst.scale(inv_mass_matrix);\n  }\n\n\n  //@sect3{Equation data}\n\n  // We define a time-dependent function that is used as initial\n  // value. Different solutions can be obtained by varying the starting\n  // time. This function has already been explained in step-25.\n  template <int dim>\n  class ExactSolution : public Function<dim>\n  {\n  public:\n    ExactSolution (const unsigned int n_components = 1,\n                   const double time = 0.) : Function<dim>(n_components, time) {}\n    virtual double value (const Point<dim> &p,\n                          const unsigned int component = 0) const;\n  };\n\n  template <int dim>\n  double ExactSolution<dim>::value (const Point<dim> &p,\n                                    const unsigned int /* component */) const\n  {\n    double t = this->get_time ();\n\n    const double m = 0.5;\n    const double c1 = 0.;\n    const double c2 = 0.;\n    const double factor = (m / std::sqrt(1.-m*m) *\n                           std::sin(std::sqrt(1.-m*m)*t+c2));\n    double result = 1.;\n    for (unsigned int d=0; d<dim; ++d)\n      result *= -4. * std::atan (factor / std::cosh(m*p[d]+c1));\n    return result;\n  }\n\n\n\n  // @sect3{SineGordonProblem class}\n\n  // This is the main class that builds on the class in step-25.  However, we\n  // replaced the SparseMatrix<double> class by the MatrixFree class to store\n  // the geometry data. Also, we use a distributed triangulation in this\n  // example.\n  template <int dim>\n  class SineGordonProblem\n  {\n  public:\n    SineGordonProblem ();\n    void run ();\n\n  private:\n    ConditionalOStream pcout;\n\n    void make_grid_and_dofs ();\n    void oldstyle_operation ();\n    void assemble_system ();\n    void output_results (const unsigned int timestep_number) const;\n\n#ifdef DEAL_II_USE_P4EST\n    parallel::distributed::Triangulation<dim>   triangulation;\n#else\n    Triangulation<dim>   triangulation;\n#endif\n    FE_Q<dim>            fe;\n    DoFHandler<dim>      dof_handler;\n    ConstraintMatrix     constraints;\n    IndexSet             locally_relevant_dofs;\n\n    MatrixFree<dim,double> matrix_free_data;\n\n    parallel::distributed::Vector<double> solution, old_solution, old_old_solution;\n\n    const unsigned int n_global_refinements;\n    double time, time_step;\n    const double final_time;\n    const double cfl_number;\n    const unsigned int output_timestep_skip;\n  };\n\n\n  //@sect4{SineGordonProblem::SineGordonProblem}\n\n  // This is the constructor of the SineGordonProblem class. The time interval\n  // and time step size are defined here. Moreover, we use the degree of the\n  // finite element that we defined at the top of the program to initialize a\n  // FE_Q finite element based on Gauss-Lobatto support points. These points\n  // are convenient because in conjunction with a QGaussLobatto quadrature\n  // rule of the same order they give a diagonal mass matrix without\n  // compromising accuracy too much (note that the integration is inexact,\n  // though), see also the discussion in the introduction.\n  template <int dim>\n  SineGordonProblem<dim>::SineGordonProblem ()\n    :\n    pcout (std::cout,\n           Utilities::System::get_this_mpi_process(MPI_COMM_WORLD)==0),\n#ifdef DEAL_II_USE_P4EST\n    triangulation (MPI_COMM_WORLD),\n#endif\n    fe (QGaussLobatto<1>(fe_degree+1)),\n    dof_handler (triangulation),\n    n_global_refinements (10-2*dim),\n    time (-10),\n    final_time (10),\n    cfl_number (.1/fe_degree),\n    output_timestep_skip (200)\n  {}\n\n  //@sect4{SineGordonProblem::make_grid_and_dofs}\n\n  // As in step-25 this functions sets up a cube grid in <code>dim</code>\n  // dimensions of extent $[-15,15]$. We refine the mesh more in the center of\n  // the domain since the solution is concentrated there. We first refine all\n  // cells whose center is within a radius of 11, and then refine once more\n  // for a radius 6.  This is simple ad-hoc refinement could be done better by\n  // adapting the mesh to the solution using error estimators during the time\n  // stepping as done in other example programs, and using\n  // parallel::distributed::SolutionTransfer to transfer the solution to the\n  // new mesh.\n  template <int dim>\n  void SineGordonProblem<dim>::make_grid_and_dofs ()\n  {\n    GridGenerator::hyper_cube (triangulation, -15, 15);\n    triangulation.refine_global (n_global_refinements);\n    {\n      typename Triangulation<dim>::active_cell_iterator\n      cell = triangulation.begin_active(),\n      end_cell = triangulation.end();\n      for ( ; cell != end_cell; ++cell)\n        if (cell->is_locally_owned())\n          if (cell->center().norm() < 11)\n            cell->set_refine_flag();\n      triangulation.execute_coarsening_and_refinement();\n\n      cell = triangulation.begin_active();\n      end_cell = triangulation.end();\n      for ( ; cell != end_cell; ++cell)\n        if (cell->is_locally_owned())\n          if (cell->center().norm() < 6)\n            cell->set_refine_flag();\n      triangulation.execute_coarsening_and_refinement();\n    }\n\n    pcout << \"   Number of global active cells: \"\n#ifdef DEAL_II_USE_P4EST\n          << triangulation.n_global_active_cells()\n#else\n          << triangulation.n_active_cells()\n#endif\n          << std::endl;\n\n    dof_handler.distribute_dofs (fe);\n\n    pcout << \"   Number of degrees of freedom: \"\n          << dof_handler.n_dofs()\n          << std::endl;\n\n\n    // We generate hanging node constraints for ensuring continuity of the\n    // solution. As in step-40, we need to equip the constraint matrix with\n    // the IndexSet of locally relevant degrees of freedom to avoid it to\n    // consume too much memory for big problems. Next, the <code> MatrixFree\n    // </code> for the problem is set up. Note that we specify the MPI\n    // communicator which we are going to use, and that we also want to use\n    // shared-memory parallelization (hence one would use multithreading for\n    // intra-node parallelism and not MPI; note that we here choose the\n    // standard option &mdash; if we wanted to disable shared memory\n    // parallelization, we would choose @p none). Finally, three solution\n    // vectors are initialized. MatrixFree stores the layout that is to be\n    // used by distributed vectors, so we just ask it to initialize the\n    // vectors.\n    DoFTools::extract_locally_relevant_dofs (dof_handler,\n                                             locally_relevant_dofs);\n    constraints.clear();\n    constraints.reinit (locally_relevant_dofs);\n    DoFTools::make_hanging_node_constraints (dof_handler, constraints);\n    constraints.close();\n\n    QGaussLobatto<1> quadrature (fe_degree+1);\n    typename MatrixFree<dim>::AdditionalData additional_data;\n    additional_data.mpi_communicator = MPI_COMM_WORLD;\n    additional_data.tasks_parallel_scheme =\n      MatrixFree<dim>::AdditionalData::partition_partition;\n\n    matrix_free_data.reinit (dof_handler, constraints,\n                             quadrature, additional_data);\n\n    matrix_free_data.initialize_dof_vector (solution);\n    old_solution.reinit (solution);\n    old_old_solution.reinit (solution);\n  }\n\n\n\n  //@sect4{SineGordonProblem::output_results}\n\n  // This function prints the norm of the solution and writes the solution\n  // vector to a file. The norm is standard (except for the fact that we need\n  // to be sure to only count norms on locally owned cells), and the second is\n  // similar to what we did in step-40. However, we first need to generate an\n  // appropriate vector for output: The ones we used during time stepping\n  // contained information about ghosts dofs that one needs write access to\n  // during the loops over cell. However, that is not the same as needed when\n  // outputting. So we first initialize a vector with locally relevant degrees\n  // of freedom by copying the solution (note how we use the function @p\n  // copy_from to transfer data between vectors with the same local range, but\n  // different layouts of ghosts). Then, we import the values on the ghost\n  // DoFs and then distribute the constraints (as constraints are zero in the\n  // vectors during loop over all cells).\n  template <int dim>\n  void\n  SineGordonProblem<dim>::output_results (const unsigned int timestep_number) const\n  {\n    parallel::distributed::Vector<double> locally_relevant_solution;\n    locally_relevant_solution.reinit (dof_handler.locally_owned_dofs(),\n                                      locally_relevant_dofs,\n                                      MPI_COMM_WORLD);\n    locally_relevant_solution.copy_from (solution);\n    locally_relevant_solution.update_ghost_values ();\n    constraints.distribute (locally_relevant_solution);\n\n    Vector<float> norm_per_cell (triangulation.n_active_cells());\n    VectorTools::integrate_difference (dof_handler,\n                                       locally_relevant_solution,\n                                       ZeroFunction<dim>(),\n                                       norm_per_cell,\n                                       QGauss<dim>(fe_degree+1),\n                                       VectorTools::L2_norm);\n    const double solution_norm =\n      std::sqrt(Utilities::MPI::sum (norm_per_cell.norm_sqr(), MPI_COMM_WORLD));\n\n    pcout << \"   Time:\"\n          << std::setw(8) << std::setprecision(3) << time\n          << \", solution norm: \"\n          << std::setprecision(5) << std::setw(7) << solution_norm\n          << std::endl;\n\n    DataOut<dim> data_out;\n\n    data_out.attach_dof_handler (dof_handler);\n    data_out.add_data_vector (locally_relevant_solution, \"solution\");\n    data_out.build_patches ();\n\n    const std::string filename =\n      \"solution-\" + Utilities::int_to_string (timestep_number, 3) +\n      \".\" + Utilities::int_to_string (Utilities::MPI::\n                                      this_mpi_process(MPI_COMM_WORLD),4);\n\n    std::ofstream output ((filename + \".vtu\").c_str());\n    data_out.write_vtu (output);\n\n    if (Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0)\n      {\n        std::vector<std::string> filenames;\n        for (unsigned int i=0;\n             i<Utilities::MPI::n_mpi_processes (MPI_COMM_WORLD); ++i)\n          filenames.push_back (\"solution-\" +\n                               Utilities::int_to_string (timestep_number, 3) +\n                               \".\" +\n                               Utilities::int_to_string (i, 4) +\n                               \".vtu\");\n\n        std::ofstream master_output ((filename + \".pvtu\").c_str());\n        data_out.write_pvtu_record (master_output, filenames);\n      }\n  }\n\n\n  // @sect4{SineGordonProblem::run}\n\n  // This function is called by the main function and calls the subroutines of\n  // the class.\n  //\n  // The first step is to set up the grid and the cell operator. Then, the\n  // time step is computed from the CFL number given in the constructor and\n  // the finest mesh size. The finest mesh size is computed as the diameter of\n  // the last cell in the triangulation, which is the last cell on the finest\n  // level of the mesh. This is only possible for Cartesian meshes, otherwise,\n  // one needs to loop over all cells). Note that we need to query all the\n  // processors for their finest cell since the not all processors might hold\n  // a region where the mesh is at the finest level. Then, we readjust the\n  // time step a little to hit the final time exactly if necessary.\n  template <int dim>\n  void\n  SineGordonProblem<dim>::run ()\n  {\n    make_grid_and_dofs();\n\n    const double local_min_cell_diameter =\n      triangulation.last()->diameter()/std::sqrt(dim);\n    const double global_min_cell_diameter\n      = -Utilities::MPI::max(-local_min_cell_diameter, MPI_COMM_WORLD);\n    time_step = cfl_number * global_min_cell_diameter;\n    time_step = (final_time-time)/(int((final_time-time)/time_step));\n    pcout << \"   Time step size: \" << time_step << \", finest cell: \"\n          << global_min_cell_diameter << std::endl << std::endl;\n\n    // Next the initial value is set. Since we have a two-step time stepping\n    // method, we also need a value of the solution at time-time_step. For\n    // accurate results, one would need to compute this from the time\n    // derivative of the solution at initial time, but here we ignore this\n    // difficulty and just set it to the initial value function at that\n    // artificial time.\n\n    // We create an output of the initial value. Then we also need to collect\n    // the two starting solutions in an STL vector of pointers field and to\n    // set up an instance of the <code> SineGordonOperation class </code>\n    // based on the finite element degree specified at the top of this file.\n    VectorTools::interpolate (dof_handler,\n                              ExactSolution<dim> (1, time),\n                              solution);\n    VectorTools::interpolate (dof_handler,\n                              ExactSolution<dim> (1, time-time_step),\n                              old_solution);\n    output_results (0);\n\n    std::vector<parallel::distributed::Vector<double>*> previous_solutions;\n    previous_solutions.push_back(&old_solution);\n    previous_solutions.push_back(&old_old_solution);\n\n    SineGordonOperation<dim,fe_degree> sine_gordon_op (matrix_free_data,\n                                                       time_step);\n\n    // Now loop over the time steps. In each iteration, we shift the solution\n    // vectors by one and call the <code> apply </code> function of the <code>\n    // SineGordonOperator </code>. Then, we write the solution to a file. We\n    // clock the wall times for the computational time needed as wall as the\n    // time needed to create the output and report the numbers when the time\n    // stepping is finished.\n    //\n    // Note how this shift is implemented: We simply call the swap method on\n    // the two vectors which swaps only some pointers without the need to copy\n    // data around. Obviously, this is a more efficient way to move data\n    // around. Let us see what happens in more detail: First, we exchange\n    // <code>old_solution</code> with <code>old_old_solution</code>, which\n    // means that <code>old_old_solution</code> gets\n    // <code>old_solution</code>, which is what we expect. Similarly,\n    // <code>old_solution</code> gets the content from <code>solution</code>\n    // in the next step. Afterward, <code>solution</code> holds\n    // <code>old_old_solution</code>, but that will be overwritten during this\n    // step.\n    unsigned int timestep_number = 1;\n\n    Timer timer;\n    double wtime = 0;\n    double output_time = 0;\n    for (time+=time_step; time<=final_time; time+=time_step, ++timestep_number)\n      {\n        timer.restart();\n        old_old_solution.swap (old_solution);\n        old_solution.swap (solution);\n        sine_gordon_op.apply (solution, previous_solutions);\n        wtime += timer.wall_time();\n\n        timer.restart();\n        if (timestep_number % output_timestep_skip == 0)\n          output_results(timestep_number / output_timestep_skip);\n\n        output_time += timer.wall_time();\n      }\n    timer.restart();\n    output_results(timestep_number / output_timestep_skip + 1);\n    output_time += timer.wall_time();\n\n    pcout << std::endl\n          << \"   Performed \" << timestep_number << \" time steps.\"\n          << std::endl;\n\n    pcout << \"   Average wallclock time per time step: \"\n          << wtime / timestep_number << \"s\" << std::endl;\n\n    pcout << \"   Spent \" << output_time << \"s on output and \"\n          << wtime << \"s on computations.\" << std::endl;\n  }\n}\n\n\n\n// @sect3{The <code>main</code> function}\n\n// This is as in all other programs:\nint main (int argc, char **argv)\n{\n  using namespace Step48;\n  using namespace dealii;\n\n  Utilities::System::MPI_InitFinalize mpi_initialization(argc, argv);\n\n  try\n    {\n      deallog.depth_console (0);\n\n      SineGordonProblem<dimension> sg_problem;\n      sg_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": "e50cf7700adad90e9babafc746462e986d0dcfcd", "size": 27055, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-48/step-48.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-48/step-48.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-48/step-48.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": 41.495398773, "max_line_length": 86, "alphanum_fraction": 0.6575124746, "num_tokens": 6336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.275730122267073}}
{"text": "#include <string>\n#include <memory>\n#include <tuple>\n#include <stdexcept>\n#include <algorithm>\n#include <cmath>\n#include <map>\n\n#include <boost/thread/mutex.hpp>\n#include <boost/thread/locks.hpp>\n#include <boost/thread/lock_guard.hpp>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <string.h>\n\n#include \"cpl_serv.h\"\n#include \"tiff.h\"\n#include \"libxtiff/xtiffio.h\"\n#include \"geotiffio.h\"\n#include \"geovalues.h\"\n#include \"geo_normalize.h\"\n\n#include \"rastermap.h\"\n#include \"map_geotiff.h\"\n#include \"projection.h\"\n#include \"util.h\"\n\nconst char * const DEFAULT_ENCODING = \"UTF-8\";\n\n// Map between the unit square (x and y in [0, 1]) and a general\n// quadrilateral using bilinear interpolation.\n// Normalized coordinates are given as UnitSquareCoord.\n// Quadrilateral coordinatese are given as MapPixelDelta.\nclass BilinearInterpolator {\n    public:\n        // Initialize with the four corners of the general quadrilateral.\n        // The coordinates are given in clock-wise order.\n        BilinearInterpolator(const MapPixelDelta &P00,\n                             const MapPixelDelta &P10,\n                             const MapPixelDelta &P11,\n                             const MapPixelDelta &P01);\n\n        // Map from input (within the unit square) to the general quad.\n        // Example: forward(UnitSquareCoord(0.25, 0)) -> P00 * 0.75 + P10 * 0.25\n        MapPixelDelta forward(const UnitSquareCoord &input);\n\n        // Map from the general quad back to the unit square.\n        // This is the inverse transformation of forward().\n        UnitSquareCoord inverse(const MapPixelDelta &X);\n    private:\n        template <typename T>\n        T lerp(double f, const T &A, const T &B) {\n            return (1-f)*A + f*B;\n        }\n        const MapPixelDelta A, B, C, D;\n        const MapPixelDelta E, F, G;\n};\n\nBilinearInterpolator::BilinearInterpolator(const MapPixelDelta &P00,\n                                           const MapPixelDelta &P10,\n                                           const MapPixelDelta &P11,\n                                           const MapPixelDelta &P01)\n: A(P00), B(P10), C(P11), D(P01), E(B-A), F(D-A), G(A-B-D+C)\n{}\n\n\nMapPixelDelta BilinearInterpolator::forward(const UnitSquareCoord &input) {\n    // Straight-forward bilinear interpolation.\n    return lerp(input.y, lerp(input.x, A, B), lerp(input.x, D, C));\n}\n\nUnitSquareCoord BilinearInterpolator::inverse(const MapPixelDelta &X) {\n    // Inverse bilinear interpolation involves solving a quadratic equation.\n    // Cf. http://www.iquilezles.org/www/articles/ibilinear/ibilinear.htm\n    MapPixelDelta H = X-A;\n    double k2 = G.x*F.y - G.y*F.x;\n    double k1 = E.x*F.y - E.y*F.x + H.x*G.y - H.y*G.x;\n    double k0 = H.x*E.y - H.y*E.x;\n    double v = (-k1 + sqrt(k1*k1 - 4*k0*k2)) / (2 * k2);\n    if (v < 0 || v > 1) {\n        v = (-k1 - sqrt(k1*k1 - 4*k0*k2)) / (2 * k2);\n    }\n    double u = (H.x - F.x*v)/(E.x + G.x*v);\n    return UnitSquareCoord(u, v);\n}\n\n\nclass TiffHandle {\n    public:\n        explicit TiffHandle(const std::wstring &fname)\n        // Pass \"m\" flag to disable memory-mapped IO.\n        // Otherwise we fill up the whole virtual address space with mmapped\n        // TIF files and run out of space to load libraries or map other data.\n        // This gives hard-to-diagnose OOM errors (debug with VMMap on Win32).\n        : m_tiff(XTIFFOpenW(fname.c_str(), \"rm\"))\n        {\n            if (!m_tiff) {\n                throw std::runtime_error(\"File not found\");\n            }\n        };\n        ~TiffHandle() {\n            if (m_tiff) {\n                XTIFFClose(m_tiff);\n                m_tiff = NULL;\n            }\n        }\n        TIFF *GetTIFF() { return m_tiff; };\n    private:\n        DISALLOW_COPY_AND_ASSIGN(TiffHandle);\n        TIFF* m_tiff;\n};\n\nclass GeoTiffHandle {\n    public:\n        explicit GeoTiffHandle(TiffHandle &tiffhandle)\n            : m_gtif(GTIFNew(tiffhandle.GetTIFF()))\n        {\n            if (!m_gtif)\n                throw std::runtime_error(\"Opening GeoTiff failed.\");\n        };\n        ~GeoTiffHandle() {\n            if (m_gtif) {\n                GTIFFree(m_gtif);\n                m_gtif = NULL;\n            }\n        };\n        GTIF *GetGTIF() { return m_gtif; };\n    private:\n        DISALLOW_COPY_AND_ASSIGN(GeoTiffHandle);\n        GTIF *m_gtif;\n};\n\nclass Tiff {\n    public:\n        explicit Tiff(const std::wstring &fname);\n        virtual ~Tiff() { };\n        TIFF *GetTIFF() { return m_rawtiff; };\n        unsigned int GetWidth() const { return m_width; };\n        unsigned int GetHeight() const { return m_height; };\n        unsigned int GetBitsPerSample() const { return m_bitspersample; };\n        unsigned int GetSamplesPerPixel() const { return m_samplesperpixel; };\n        PixelBuf GetRegion(\n                const class MapPixelCoordInt &pos,\n                const class MapPixelDeltaInt &size) const;\n\n        template <typename T>\n        std::tuple<unsigned int, const T*>\n        GetField(ttag_t field) const;\n\n        const std::wstring &GetFilename() const { return m_fname; };\n        const std::wstring &GetTitle() const { return m_title; };\n        const std::wstring &GetDescription() const { return m_description; };\n    protected:\n        const std::wstring m_fname;\n        std::wstring m_title;\n        std::wstring m_description;\n        TiffHandle m_tiffhandle;\n        TIFF *m_rawtiff;\n\n        virtual void Hook_TIFFRGBAImageGet(TIFFRGBAImage &img) const {};\n    private:\n        unsigned int m_width, m_height;\n        unsigned short int m_bitspersample, m_samplesperpixel;\n\n        PixelBuf DoGetRegion(\n                const class MapPixelCoordInt &pos,\n                const class MapPixelDeltaInt &size) const;\n};\n\nclass GeoTiff : public Tiff {\n    public:\n        explicit GeoTiff(const std::wstring &fname);\n        virtual ~GeoTiff() { };\n\n        bool CheckVersion() const;\n        bool LoadCoordinates();\n\n        bool PixelToPCS(double *x, double *y) const;\n        bool PCSToPixel(double *x, double *y) const;\n        const std::string &GetProj4String() const { return m_proj; };\n        GeoDrawable::DrawableType GetType() const { return m_type; };\n\n        template <typename T>\n        std::tuple<unsigned int, std::shared_ptr<T>>\n        GetKey(geokey_t key) const;\n\n        template <typename T>\n        bool GetKeySingle(geokey_t key, T *result) const;\n\n        bool HasKey(geokey_t) const;\n\n        geocode_t GetModel() const { return m_model; }\n\n    protected:\n        GeoTiffHandle m_gtifhandle;\n        GTIF *m_rawgtif;\n\n        virtual void Hook_TIFFRGBAImageGet(TIFFRGBAImage &img) const;\n    private:\n        bool CheckDHMValid() const;\n\n        geocode_t m_model;\n        const double *m_tiepoints;\n        const double *m_pixscale;\n        const double *m_transform;\n        unsigned short int m_ntiepoints, m_npixscale, m_ntransform;\n\n        std::string m_proj;\n        GeoDrawable::DrawableType m_type;\n};\n\n\nstatic void put16bitbw_DHM(\n    TIFFRGBAImage* img,\n    uint32* cp,                     // ptr to write target in TO (dest buf)\n    uint32 x, uint32 y,             // x,y offset of write target within TO\n    uint32 w, uint32 h,             // pixel count of one row; number of rows\n    int32 fromskew, int32 toskew,   // offsets on row change in FROM/TO\n    unsigned char* pp)              // ptr to read location in FROM\n{\n    int samplesperpixel = img->samplesperpixel;\n    int16 *wp = reinterpret_cast<int16*>(pp);\n    while (h-- > 0) {\n        for (x = w; x-- > 0;) {\n            // Copy the 16 bit heightmap value over into the RGBA image\n            // Take care to sign-extend\n            *cp++ = (uint32)*wp;\n            wp += samplesperpixel;\n        }\n        cp += toskew;\n        wp += fromskew;\n    }\n}\n\n\nTiff::Tiff(const std::wstring &fname)\n    : m_fname(fname), m_title(), m_description(), m_tiffhandle(fname),\n      m_rawtiff(m_tiffhandle.GetTIFF())\n{\n    if (!TIFFGetField(m_rawtiff, TIFFTAG_IMAGEWIDTH, &m_width) ||\n        !TIFFGetField(m_rawtiff, TIFFTAG_IMAGELENGTH, &m_height)) {\n        throw std::runtime_error(\"Failed getting TIF dimensions.\");\n    }\n\n    if (!TIFFGetField(m_rawtiff, TIFFTAG_BITSPERSAMPLE, &m_bitspersample) ||\n        !TIFFGetField(m_rawtiff, TIFFTAG_SAMPLESPERPIXEL, &m_samplesperpixel))\n    {\n        throw std::runtime_error(\"Failed getting TIF pixel format.\");\n    }\n    char *title;\n    if (TIFFGetField(m_rawtiff, TIFFTAG_DOCUMENTNAME, &title)) {\n        m_title = WStringFromString(title, DEFAULT_ENCODING);\n    }\n    char *description;\n    if (TIFFGetField(m_rawtiff, TIFFTAG_IMAGEDESCRIPTION, &description)) {\n        m_description = WStringFromString(description, DEFAULT_ENCODING);\n    }\n};\n\nPixelBuf\nTiff::DoGetRegion(const MapPixelCoordInt &pos,\n                  const MapPixelDeltaInt &size) const\n{\n    MapPixelCoordInt endpos = pos + size;\n    if (endpos.x <= 0 || endpos.y <= 0 ||\n        pos.x >= static_cast<int>(m_width) ||\n        pos.y >= static_cast<int>(m_height))\n    {\n        return PixelBuf(size.x, size.y);\n    }\n\n    TIFFRGBAImage img;\n    char emsg[1024] = \"\";\n    if (!TIFFRGBAImageOK(m_rawtiff, emsg) ||\n        !TIFFRGBAImageBegin(&img, m_rawtiff, 0, emsg)) {\n        throw std::runtime_error(\"TIFF RGBA access not possible.\");\n    }\n\n    img.col_offset = pos.x;\n    img.row_offset = pos.y;\n\n    // Give derived classes a chance to influence TIFFRGBAGetImage\n    Hook_TIFFRGBAImageGet(img);\n\n    PixelBuf result(size.x, size.y);\n    int ok = TIFFRGBAImageGet(&img, result.GetRawData(), size.x, size.y);\n    TIFFRGBAImageEnd(&img);\n\n    if (!ok) {\n        throw std::runtime_error(\"Loading TIFF data failed.\");\n    }\n    return result;\n}\n\nPixelBuf\nTiff::GetRegion(const MapPixelCoordInt &pos,\n                const MapPixelDeltaInt &size) const\n{\n    if (TIFFIsTiled(m_rawtiff))\n        return DoGetRegion(pos, size);\n\n    // Handle stripped images:\n    // TIFFRGBAImageGet ignores img.col_offset for stripped images.\n    // It always returns data starting from the first column of the image.\n    //\n    // So, fetch a full-width strip and copy the relevant portion into the\n    // output PixelBuf.\n    auto result = PixelBuf(size.x, size.y);\n    MapPixelCoordInt end = pos + size;\n\n    int strip_size = -1;\n    if (!TIFFGetFieldDefaulted(m_rawtiff, TIFFTAG_ROWSPERSTRIP, &strip_size)) {\n        throw std::runtime_error(\"Failed getting TIF dimensions.\");\n    }\n    if (strip_size < 0) {\n        throw std::runtime_error(\"Stripped TIF image with strip height < 0?!\");\n    }\n    if (static_cast<unsigned int>(strip_size) > m_height) {\n        // TIFFRGBAImageGet crashes when reading from an image where\n        // rows_per_strip > total_rows_in_image if more than\n        // total_rows_in_image rows are requested.\n        //\n        // Cap the number of rows we try to read, in this case.\n        strip_size = m_height;\n    }\n\n    int first_ty = pos.y / strip_size;\n    int last_ty = (end.y - 1) / strip_size;\n    for (int ty = pos.y / strip_size; ty*strip_size < end.y; ty++) {\n        PixelBuf tile = DoGetRegion(\n                MapPixelCoordInt(0, ty*strip_size),\n                MapPixelDeltaInt(m_width, strip_size));\n        if (!tile.GetData()) {\n            continue;\n        }\n        auto insert_pos = PixelBufCoord(\n                -pos.x,\n                (last_ty - ty + first_ty) * strip_size - pos.y);\n        result.Insert(insert_pos, tile);\n    }\n    return result;\n}\n\ntemplate <typename T>\nstd::tuple<unsigned int, const T*>\nTiff::GetField(ttag_t field) const {\n    const T *data;\n    unsigned int length;\n    if (!TIFFGetField(m_rawtiff, field, &length, &data)) {\n        length = 0;\n        data = NULL;\n    }\n    return std::make_tuple(length, data);\n}\n\n/**\n * Internal callback to resolve csv data filenames to full paths.\n *\n * @locking Acquires an internal ``std::mutex``. No external calls are made\n * with that mutex held.\n */\nstatic const char *CSVFileOverride(const char * input_fname) {\n    static boost::mutex strmap_mutex;\n    static std::map<std::string, const char *> strmap;\n\n    {\n        boost::lock_guard<boost::mutex> lock(strmap_mutex);\n        auto result = strmap.find(input_fname);\n        if (result != strmap.end()) {\n            return result->second;\n        }\n    }\n\n    std::string csvdir = GetModuleDir_char() + \"csv\" + ODM_PathSep_char;\n    std::string fpath = csvdir + input_fname;\n    if (!FileExists(fpath)) {\n        throw std::runtime_error(\"CSV file does not exist: \" + fpath);\n    }\n\n    // Intentionally leak this memory.\n    // The buffer address must never change, which STL containers don't\n    // guarantee. Only ~40 input file names are possible, so cache per input\n    // filename and stop worrying.\n    const char * const fpath_cstr = _strdup(fpath.c_str());\n    {\n        boost::lock_guard<boost::mutex> lock(strmap_mutex);\n        strmap[input_fname] = fpath_cstr;\n    }\n    return fpath_cstr;\n}\n\n// http://rocky.ess.washington.edu/data/raster/geotiff/docs/manual.txt\n// ftp://kratmos.gsfc.nasa.gov/pub/jim/imager/latest_version/TIFF_reader2.c\n// http://svn.osgeo.org/fdocore/tags/3.2.x_G052/Thirdparty/GDAL1.3/src/frmts/gtiff/geotiff.cpp\n// http://ojs.klaki.net/geotiff2ncdf/gt2nc.c\n\nGeoTiff::GeoTiff(const std::wstring &fname)\n    : Tiff(fname), m_gtifhandle(m_tiffhandle),\n      m_rawgtif(m_gtifhandle.GetGTIF()),\n      m_tiepoints(NULL), m_pixscale(NULL), m_transform(NULL),\n      m_ntiepoints(0), m_npixscale(0), m_ntransform(0),\n      m_proj(), m_type()\n{\n    SetCSVFilenameHook(&CSVFileOverride);\n    if (!CheckVersion()) {\n        throw std::runtime_error(\"GeoTIFF version not supported.\");\n    }\n    if (!LoadCoordinates()) {\n        m_type = RasterMap::TYPE_IMAGE;\n    }\n};\n\nbool GeoTiff::CheckVersion() const {\n    enum GTIFVersion { VERSION = 0, REV_MAJOR, REV_MINOR };\n    int versions[3];\n    GTIFDirectoryInfo(m_rawgtif, versions, NULL);\n    return versions[VERSION] <= GvCurrentVersion &&\n           versions[REV_MAJOR] <= GvCurrentRevision;\n}\n\nbool GeoTiff::LoadCoordinates() {\n    if (!GetKeySingle<geocode_t>(GTModelTypeGeoKey, &m_model)) {\n        return false;\n    }\n\n    // The rest is not implemented\n    if (m_model != ModelTypeProjected && m_model != ModelTypeGeographic) {\n        throw std::runtime_error(\"Map type not supported yet\");\n    }\n\n    GTIFDefn    defn;\n    if(!GTIFGetDefn(m_rawgtif, &defn)) {\n        return false;\n    }\n\n    std::shared_ptr<char> proj_str(GTIFGetProj4Defn(&defn),\n                                   [](char* mem) { GTIFFreeMemory(mem); });\n    if (!proj_str)\n        return false;\n\n    m_proj = proj_str.get();\n    if (!m_proj.length() || !m_proj[0])\n        return false;\n\n    using std::tie;\n    tie(m_ntiepoints, m_tiepoints) = GetField<double>(TIFFTAG_GEOTIEPOINTS);\n    tie(m_npixscale, m_pixscale) = GetField<double>(TIFFTAG_GEOPIXELSCALE);\n    tie(m_ntransform, m_transform) = GetField<double>(TIFFTAG_GEOTRANSMATRIX);\n\n    unsigned int sample_fmt = 0;\n    TIFFGetFieldDefaulted(m_rawtiff, TIFFTAG_SAMPLEFORMAT, &sample_fmt);\n    if (HasKey(VerticalUnitsGeoKey)) {\n        m_type = RasterMap::TYPE_DHM;\n    } else if (GetSamplesPerPixel() == 1 && GetBitsPerSample() == 16 &&\n               sample_fmt == SAMPLEFORMAT_INT)\n    {\n        // Some DHM's don't set VerticalUnitsGeoKey, unfortunately.\n        // Use this heuristic to catch those, SAMPLEFORMAT_INT should be\n        // a pretty good indicator.\n        m_type = RasterMap::TYPE_DHM;\n    } else {\n        m_type = RasterMap::TYPE_MAP;\n    }\n\n    return true;\n}\n\ntemplate <typename T>\nstd::tuple<unsigned int, std::shared_ptr<T>>\nGeoTiff::GetKey(geokey_t key) const\n{\n    int size;\n    tagtype_t type;\n    unsigned int count = GTIFKeyInfo(m_rawgtif, key, &size, &type);\n    if (!count) {\n        return make_tuple(0, std::shared_ptr<T>());\n    }\n    if (sizeof(T) != size) {\n        throw std::runtime_error(\"GeoTIFF key malformed.\");\n    }\n\n    std::shared_ptr<T> buffer(new T[count](), ArrayDeleter<T>());\n    if (GTIFKeyGet(m_rawgtif, key, buffer.get(), 0, count) != count) {\n        throw std::runtime_error(\"GeoTIFF key read error.\");\n    }\n    return std::make_tuple(count, buffer);\n};\n\ntemplate <typename T>\nbool GeoTiff::GetKeySingle(geokey_t key, T *output) const {\n    auto result = GetKey<T>(key);\n    if (std::get<0>(result) != 1) {\n        return false;\n    }\n    *output = *std::get<1>(result).get();\n    return true;\n}\n\nbool GeoTiff::HasKey(geokey_t key) const {\n    return 0 != GTIFKeyInfo(m_rawgtif, key, NULL, NULL);\n}\n\nbool GeoTiff::PixelToPCS(double *x, double *y) const {\n    if (m_type == RasterMap::TYPE_IMAGE)\n        return false;\n\n    if (m_ntiepoints > 6 && m_npixscale == 0) {\n        // Interpolate between multiple tiepoints\n        if (m_ntiepoints != 4*6) {\n            // Currently, we only support 4 tiepoints.\n            return false;\n        };\n\n        unsigned int w = GetWidth();\n        unsigned int h = GetHeight();\n        std::unique_ptr<MapPixelDelta> p00, p10, p01, p11;\n\n        for (unsigned int i=0; i < m_ntiepoints; i += 6) {\n            if (m_tiepoints[i+0] == 0 && m_tiepoints[i+1] == 0)\n                p00.reset(new MapPixelDelta(m_tiepoints[i+3], m_tiepoints[i+4]));\n            else if (m_tiepoints[i+0] == w && m_tiepoints[i+1] == 0)\n                p10.reset(new MapPixelDelta(m_tiepoints[i+3], m_tiepoints[i+4]));\n            else if (m_tiepoints[i+0] == 0 && m_tiepoints[i+1] == h)\n                p01.reset(new MapPixelDelta(m_tiepoints[i+3], m_tiepoints[i+4]));\n            else if (m_tiepoints[i+0] == w && m_tiepoints[i+1] == h)\n                p11.reset(new MapPixelDelta(m_tiepoints[i+3], m_tiepoints[i+4]));\n            else {\n                // For now, we require tie points to be at the image corners.\n                return false;\n            }\n        }\n        if (!p00 || !p10 || !p01 || !p11) {\n            return false;\n        }\n        auto interpolator = BilinearInterpolator(*p00, *p10, *p11, *p01);\n        auto res = interpolator.forward(UnitSquareCoord(*x/w, *y/h));\n        *x = res.x;\n        *y = res.y;\n    }\n    else if (m_ntransform == 16) {\n        // Use matrix for transformation\n        double x_in = *x, y_in = *y;\n        *x = x_in * m_transform[0] + y_in * m_transform[1] + m_transform[3];\n        *y = x_in * m_transform[4] + y_in * m_transform[5] + m_transform[7];\n    }\n    else if (m_npixscale >= 3 && m_ntiepoints >= 6) {\n        // Use one tiepoint + pixscale\n        *x = (*x - m_tiepoints[0]) * m_pixscale[0] + m_tiepoints[3];\n        *y = (*y - m_tiepoints[1]) * (-1 * m_pixscale[1]) + m_tiepoints[4];\n    }\n    else {\n        throw std::runtime_error(\"Couldn't find GeoTIFF coordinates.\");\n    }\n    return true;\n}\n\nbool GeoTiff::PCSToPixel(double *x, double *y) const {\n    if (m_type == RasterMap::TYPE_IMAGE)\n        return false;\n\n    if (m_ntiepoints > 6 && m_npixscale == 0) {\n        // Interpolate between multiple tiepoints\n        if (m_ntiepoints != 4*6) {\n            // Currently, we only support 4 tiepoints.\n            return false;\n        }\n\n        unsigned int w = GetWidth();\n        unsigned int h = GetHeight();\n        std::unique_ptr<MapPixelDelta> p00, p10, p01, p11;\n\n        for (unsigned int i=0; i < m_ntiepoints; i += 6) {\n            if (m_tiepoints[i+0] == 0 && m_tiepoints[i+1] == 0)\n                p00.reset(new MapPixelDelta(m_tiepoints[i+3], m_tiepoints[i+4]));\n            else if (m_tiepoints[i+0] == w && m_tiepoints[i+1] == 0)\n                p10.reset(new MapPixelDelta(m_tiepoints[i+3], m_tiepoints[i+4]));\n            else if (m_tiepoints[i+0] == 0 && m_tiepoints[i+1] == h)\n                p01.reset(new MapPixelDelta(m_tiepoints[i+3], m_tiepoints[i+4]));\n            else if (m_tiepoints[i+0] == w && m_tiepoints[i+1] == h)\n                p11.reset(new MapPixelDelta(m_tiepoints[i+3], m_tiepoints[i+4]));\n            else {\n                // For now, we require tie points to be at the image corners.\n                return false;\n            }\n        }\n        if (!p00 || !p10 || !p01 || !p11) {\n            return false;\n        }\n        auto interpolator = BilinearInterpolator(*p00, *p10, *p11, *p01);\n        auto res = interpolator.inverse(MapPixelDelta(*x, *y));\n        *x = res.x * w;\n        *y = res.y * h;\n    }\n    else if (m_ntransform == 16) {\n        // Use inverse matrix for transformation.\n        const double *mat = m_transform;\n        double x_in = *x, y_in = *y;\n        double denom = (mat[0] * mat[5] - mat[1] * mat[4]);\n        *x = (+(x_in - mat[3]) * mat[5] - (y_in - mat[7]) * mat[1]) / denom;\n        *y = (-(x_in - mat[3]) * mat[4] + (y_in - mat[7]) * mat[0]) / denom;\n    }\n    else if (m_npixscale >= 3 && m_ntiepoints >= 6) {\n        // Use one tiepoint + pixscale\n        *x = (*x - m_tiepoints[3]) / m_pixscale[0] + m_tiepoints[0];\n        *y = (*y - m_tiepoints[4]) / (-1 * m_pixscale[1]) + m_tiepoints[1];\n    }\n    else {\n        throw std::runtime_error(\"Couldn't find GeoTIFF coordinates.\");\n    }\n    return true;\n}\n\nbool GeoTiff::CheckDHMValid() const {\n    short int vert_units;\n    if (!GetKeySingle<short int>(VerticalUnitsGeoKey, &vert_units))\n        return false;\n\n    // Other vertical formats not supported at the moment\n    return vert_units == Linear_Meter;\n}\n\n// If we have a DHM map, the pixel values typically represent height in m\n// The default TIFFRGBAImageGet turns this (typically 16 bit) value into\n// a grayscale rgb image (thus truncating the lower 8 bits).\n// Prevent this and simply store the 16 bit value within the 32 bit RGBA.\nvoid GeoTiff::Hook_TIFFRGBAImageGet(TIFFRGBAImage &img) const {\n    // Only hook DHM maps\n    if (GetType() != RasterMap::TYPE_DHM)\n        return;\n\n    if (GetBitsPerSample() != 16) {\n        assert(false);  // not implemented\n    }\n    if (!img.isContig) {\n        assert(false);  // not implemented\n    }\n    if (img.photometric != PHOTOMETRIC_MINISWHITE &&\n        img.photometric != PHOTOMETRIC_MINISBLACK)\n    {\n        assert(false);  // not implemented\n    }\n    img.put.contig = put16bitbw_DHM;\n}\n\nTiffMap::TiffMap(const wchar_t *fname)\n    : m_geotiff(new GeoTiff(fname)), m_proj(m_geotiff->GetProj4String())\n{}\n\nGeoDrawable::DrawableType TiffMap::GetType() const {\n    return m_geotiff->GetType();\n}\nunsigned int TiffMap::GetWidth() const { return m_geotiff->GetWidth(); };\nunsigned int TiffMap::GetHeight() const { return m_geotiff->GetHeight(); };\nMapPixelDeltaInt TiffMap::GetSize() const {\n    return MapPixelDeltaInt(m_geotiff->GetWidth(), m_geotiff->GetHeight());\n}\n\nPixelBuf TiffMap::GetRegion(\n                      const MapPixelCoordInt &pos,\n                      const MapPixelDeltaInt &size) const\n{\n    auto fixed_bounds_pb = GetRegion_BoundsHelper(*this, pos, size);\n    if (fixed_bounds_pb.GetData())\n        return fixed_bounds_pb;\n\n    boost::lock_guard<boost::mutex> lock(m_getregion_mutex);\n    return m_geotiff->GetRegion(pos, size);\n}\n\nbool TiffMap::PixelToPCS(double *x, double *y) const\n    { return m_geotiff->PixelToPCS(x, y); }\nbool TiffMap::PCSToPixel(double *x, double *y) const\n    { return m_geotiff->PCSToPixel(x, y); }\nconst std::wstring &TiffMap::GetFname() const\n    { return m_geotiff->GetFilename(); }\nconst std::wstring &TiffMap::GetTitle() const\n    { return m_geotiff->GetTitle(); }\nconst std::wstring &TiffMap::GetDescription() const\n    { return m_geotiff->GetDescription(); }\nProjection TiffMap::GetProj() const\n    { return m_proj; }\n\nbool TiffMap::PixelToLatLon(const MapPixelCoord &pos, LatLon *result) const {\n    double x = pos.x;\n    double y = pos.y;\n    if (!PixelToPCS(&x, &y))\n        return false;\n\n    if (m_geotiff->GetModel() == ModelTypeProjected) {\n        if (!GetProj().PCSToLatLong(x, y)) {\n            return false;\n        }\n    }\n    *result = LatLon(y, x);\n    return true;\n}\n\nbool TiffMap::LatLonToPixel(const LatLon &pos, MapPixelCoord *result) const {\n    double x = pos.lon;\n    double y = pos.lat;\n    if (m_geotiff->GetModel() == ModelTypeProjected) {\n        if (!GetProj().LatLongToPCS(x, y)) {\n            return false;\n        }\n    }\n    if (!PCSToPixel(&x, &y))\n        return false;\n\n    *result = MapPixelCoord(x, y);\n    return true;\n}\n", "meta": {"hexsha": "08dc637ba83625ae6422902b4c2f552fa5b14b55", "size": 24089, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pymaplib_cpp/src/map_geotiff.cpp", "max_stars_repo_name": "Grk0/MapsEvolved", "max_stars_repo_head_hexsha": "e058a324e7d3c9b4c9b7e00d65b6f9da029fc7de", "max_stars_repo_licenses": ["PSF-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-06-09T10:41:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T07:42:19.000Z", "max_issues_repo_path": "pymaplib_cpp/src/map_geotiff.cpp", "max_issues_repo_name": "Grk0/MapsEvolved", "max_issues_repo_head_hexsha": "e058a324e7d3c9b4c9b7e00d65b6f9da029fc7de", "max_issues_repo_licenses": ["PSF-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": "pymaplib_cpp/src/map_geotiff.cpp", "max_forks_repo_name": "Grk0/MapsEvolved", "max_forks_repo_head_hexsha": "e058a324e7d3c9b4c9b7e00d65b6f9da029fc7de", "max_forks_repo_licenses": ["PSF-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.7380952381, "max_line_length": 94, "alphanum_fraction": 0.6087840923, "num_tokens": 6631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301064, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2756402498416349}}
{"text": "// g2o - General Graph Optimization\n// Copyright (C) 2011 Kurt Konolige\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 \"sbacam.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"g2o/stuff/macros.h\"\n#include \"g2o/stuff/misc.h\"\n\nnamespace g2o {\n\n// initialize an object\nSBACam::SBACam() {\n  setKcam(1, 1, cst(0.5), cst(0.5), 0);  // unit image projection\n}\n\n// set the object pose\nSBACam::SBACam(const Quaternion& r_, const Vector3& t_) : SE3Quat(r_, t_) {\n  Kcam.setZero();\n  setTransform();\n  setProjection();\n  setDr();\n}\n\nSBACam::SBACam(const SE3Quat& p) : SE3Quat(p) {\n  Kcam.setZero();\n  setTransform();\n  setProjection();\n  setDr();\n}\n\n// update from the linear solution\n// defined in se3quat\nvoid SBACam::update(const Vector6& update) {\n  // position update\n  _t += update.head(3);\n  // small quaternion update\n  Quaternion qr;\n  qr.vec() = update.segment<3>(3);\n  qr.w() =\n      sqrt(cst(1.0) - qr.vec().squaredNorm());  // should always be positive\n  _r *= qr;                                     // post-multiply\n  _r.normalize();\n  setTransform();\n  setProjection();\n  setDr();\n}\n\n// transforms\nvoid SBACam::transformW2F(Eigen::Matrix<number_t, 3, 4>& m,\n                          const Vector3& trans, const Quaternion& qrot) {\n  m.block<3, 3>(0, 0) = qrot.toRotationMatrix().transpose();\n  m.col(3).setZero();  // make sure there's no translation\n  Vector4 tt;\n  tt.head(3) = trans;\n  tt[3] = 1.0;\n  m.col(3) = -m * tt;\n}\n\nvoid SBACam::transformF2W(Eigen::Matrix<number_t, 3, 4>& m,\n                          const Vector3& trans, const Quaternion& qrot) {\n  m.block<3, 3>(0, 0) = qrot.toRotationMatrix();\n  m.col(3) = trans;\n}\n\n// set up camera matrix\nvoid SBACam::setKcam(number_t fx, number_t fy, number_t cx, number_t cy,\n                     number_t tx) {\n  Kcam.setZero();\n  Kcam(0, 0) = fx;\n  Kcam(1, 1) = fy;\n  Kcam(0, 2) = cx;\n  Kcam(1, 2) = cy;\n  Kcam(2, 2) = cst(1.0);\n  baseline = tx;\n  setTransform();\n  setProjection();\n  setDr();\n}\n\n// sets angle derivatives\nvoid SBACam::setDr() {\n  // inefficient, just for testing\n  // use simple multiplications and additions for production code in calculating\n  // dRdx,y,z\n  Matrix3 dRidx, dRidy, dRidz;\n  dRidx << cst(0.0), cst(0.0), cst(0.0), cst(0.0), cst(0.0), cst(2.0), cst(0.0),\n      cst(-2.0), cst(0.0);\n  dRidy << cst(0.0), cst(0.0), cst(-2.0), cst(0.0), cst(0.0), cst(0.0),\n      cst(2.0), cst(0.0), cst(0.0);\n  dRidz << cst(0.0), cst(2.0), cst(0.0), cst(-2.0), cst(0.0), cst(0.0),\n      cst(0.0), cst(0.0), cst(0.0);\n\n  // for dS'*R', with dS the incremental change\n  dRdx = dRidx * w2n.block<3, 3>(0, 0);\n  dRdy = dRidy * w2n.block<3, 3>(0, 0);\n  dRdz = dRidz * w2n.block<3, 3>(0, 0);\n}\n\n// human-readable SBACam object\nstd::ostream& operator<<(std::ostream& out_str, const SBACam& cam) {\n  out_str << cam.translation().transpose() << std::endl;\n  out_str << cam.rotation().coeffs().transpose() << std::endl << std::endl;\n  out_str << cam.Kcam << std::endl << std::endl;\n  out_str << cam.w2n << std::endl << std::endl;\n  out_str << cam.w2i << std::endl << std::endl;\n  return out_str;\n}\n\n}  // namespace g2o\n", "meta": {"hexsha": "5c1db17f0acb4562a5102fe62b8ed6518a0742b2", "size": 4389, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/g2o/g2o/types/sba/sbacam.cpp", "max_stars_repo_name": "Refstop/VSLAM_Example", "max_stars_repo_head_hexsha": "060b9419f79f035d1c9ebfa75ad46e2e9a53e992", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3rdparty/g2o/g2o/types/sba/sbacam.cpp", "max_issues_repo_name": "Refstop/VSLAM_Example", "max_issues_repo_head_hexsha": "060b9419f79f035d1c9ebfa75ad46e2e9a53e992", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3rdparty/g2o/g2o/types/sba/sbacam.cpp", "max_forks_repo_name": "Refstop/VSLAM_Example", "max_forks_repo_head_hexsha": "060b9419f79f035d1c9ebfa75ad46e2e9a53e992", "max_forks_repo_licenses": ["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.2720588235, "max_line_length": 80, "alphanum_fraction": 0.6529961267, "num_tokens": 1361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.27564024283741045}}
{"text": "//\n//=======================================================================\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek\n//\n// This file is part of the Boost Graph Library\n//\n// You should have received a copy of the License Agreement for the\n// Boost Graph Library along with the software; see the file LICENSE.\n// If not, contact Office of Research, University of Notre Dame, Notre\n// Dame, IN 46556.\n//\n// Permission to modify the code and to distribute modified code is\n// granted, provided the text of this NOTICE is retained, a notice that\n// the code was modified is included with the above COPYRIGHT NOTICE and\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n// file is distributed with the modified code.\n//\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n// By way of example, but not limitation, Licensor MAKES NO\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\n// OR OTHER RIGHTS.\n//=======================================================================\n//\n\n#ifndef BOOST_GRAPH_RELAX_HPP\n#define BOOST_GRAPH_RELAX_HPP\n\n#include <functional>\n#include <boost/limits.hpp> // for numeric limits\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map.hpp>\n\nnamespace boost {\n\n    // The following version of the plus functor prevents\n    // problems due to overflow at positive infinity.\n\n    template <class T>\n    struct closed_plus\n    {\n      // std::abs just isn't portable :(\n      template <class X>\n      inline X my_abs(const X& x) const { return x < 0 ? -x : x; }\n\n      T operator()(const T& a, const T& b) const {\n        using namespace std;\n        T inf = numeric_limits<T>::max();\n        if (b > 0 && my_abs(inf - a) < b)\n          return inf;\n        return a + b;\n      }\n    };\n    \n    template <class Graph, class WeightMap, \n            class PredecessorMap, class DistanceMap, \n            class BinaryFunction, class BinaryPredicate>\n    bool relax(typename graph_traits<Graph>::edge_descriptor e, \n               const Graph& g, WeightMap w, \n               PredecessorMap p, DistanceMap d, \n               BinaryFunction combine, BinaryPredicate compare)\n    {\n      typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n      Vertex u = source(e, g), v = target(e, g);\n      typedef typename property_traits<DistanceMap>::value_type D;\n      typedef typename property_traits<WeightMap>::value_type W;\n      D d_u = get(d, u), d_v = get(d, v);\n      W w_e = get(w, e);\n\n      if ( compare(combine(d_u, w_e), d_v) ) {\n        put(d, v, combine(d_u, w_e));\n        put(p, v, u);\n        return true;\n      } else\n        return false;\n    }\n    \n    template <class Graph, class WeightMap, \n      class PredecessorMap, class DistanceMap>\n    bool relax(typename graph_traits<Graph>::edge_descriptor e,\n               const Graph& g, WeightMap w, PredecessorMap p, DistanceMap d)\n    {\n      typedef typename property_traits<DistanceMap>::value_type D;\n      typedef closed_plus<D> Combine;\n      typedef std::less<D> Compare;\n      return relax(e, g, w, p, d, Combine(), Compare());\n    }\n\n} // namespace boost\n\n#endif /* BOOST_GRAPH_RELAX_HPP */\n", "meta": {"hexsha": "b8a630bedad599f12ea0bc1dbbb6c1d400da4942", "size": 3399, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vegastrike/boost/1_28/boost/graph/relax.hpp", "max_stars_repo_name": "Ezeer/VegaStrike_win32FR", "max_stars_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vegastrike/boost/1_28/boost/graph/relax.hpp", "max_issues_repo_name": "Ezeer/VegaStrike_win32FR", "max_issues_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vegastrike/boost/1_28/boost/graph/relax.hpp", "max_forks_repo_name": "Ezeer/VegaStrike_win32FR", "max_forks_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1595744681, "max_line_length": 76, "alphanum_fraction": 0.6404824949, "num_tokens": 790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2756402428374104}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_TPEQD_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_TPEQD_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// 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 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 <boost/math/special_functions/hypot.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#include <boost/geometry/srs/projections/impl/aasincos.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace srs { namespace par4\n{\n    struct tpeqd {};\n\n}} //namespace srs::par4\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace tpeqd\n    {\n            template <typename T>\n            struct par_tpeqd\n            {\n                T cp1, sp1, cp2, sp2, ccs, cs, sc, r2z0, z02, dlam2;\n                T hz0, thz0, rhshz0, ca, sa, lp, lamc;\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename CalculationType, typename Parameters>\n            struct base_tpeqd_spheroid : public base_t_fi<base_tpeqd_spheroid<CalculationType, Parameters>,\n                     CalculationType, Parameters>\n            {\n\n                typedef CalculationType geographic_type;\n                typedef CalculationType cartesian_type;\n\n                par_tpeqd<CalculationType> m_proj_parm;\n\n                inline base_tpeqd_spheroid(const Parameters& par)\n                    : base_t_fi<base_tpeqd_spheroid<CalculationType, Parameters>,\n                     CalculationType, Parameters>(*this, par) {}\n\n                // FORWARD(s_forward)  sphere\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                    CalculationType t, z1, z2, dl1, dl2, sp, cp;\n\n                    sp = sin(lp_lat);\n                    cp = cos(lp_lat);\n                    z1 = aacos(this->m_proj_parm.sp1 * sp + this->m_proj_parm.cp1 * cp * cos(dl1 = lp_lon + this->m_proj_parm.dlam2));\n                    z2 = aacos(this->m_proj_parm.sp2 * sp + this->m_proj_parm.cp2 * cp * cos(dl2 = lp_lon - this->m_proj_parm.dlam2));\n                    z1 *= z1;\n                    z2 *= z2;\n                    xy_x = this->m_proj_parm.r2z0 * (t = z1 - z2);\n                    t = this->m_proj_parm.z02 - t;\n                    xy_y = this->m_proj_parm.r2z0 * asqrt(4. * this->m_proj_parm.z02 * z2 - t * t);\n                    if ((this->m_proj_parm.ccs * sp - cp * (this->m_proj_parm.cs * sin(dl1) - this->m_proj_parm.sc * sin(dl2))) < 0.)\n                        xy_y = -xy_y;\n                }\n\n                // INVERSE(s_inverse)  sphere\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                    CalculationType cz1, cz2, s, d, cp, sp;\n\n                    cz1 = cos(boost::math::hypot(xy_y, xy_x + this->m_proj_parm.hz0));\n                    cz2 = cos(boost::math::hypot(xy_y, xy_x - this->m_proj_parm.hz0));\n                    s = cz1 + cz2;\n                    d = cz1 - cz2;\n                    lp_lon = - atan2(d, (s * this->m_proj_parm.thz0));\n                    lp_lat = aacos(boost::math::hypot(this->m_proj_parm.thz0 * s, d) * this->m_proj_parm.rhshz0);\n                    if ( xy_y < 0. )\n                        lp_lat = - lp_lat;\n                    /* lam--phi now in system relative to P1--P2 base equator */\n                    sp = sin(lp_lat);\n                    cp = cos(lp_lat);\n                    lp_lat = aasin(this->m_proj_parm.sa * sp + this->m_proj_parm.ca * cp * (s = cos(lp_lon -= this->m_proj_parm.lp)));\n                    lp_lon = atan2(cp * sin(lp_lon), this->m_proj_parm.sa * cp * s - this->m_proj_parm.ca * sp) + this->m_proj_parm.lamc;\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"tpeqd_spheroid\";\n                }\n\n            };\n\n            // Two Point Equidistant\n            template <typename Parameters, typename T>\n            inline void setup_tpeqd(Parameters& par, par_tpeqd<T>& proj_parm)\n            {\n                T lam_1, lam_2, phi_1, phi_2, A12, pp;\n\n                /* get control point locations */\n                phi_1 = pj_param(par.params, \"rlat_1\").f;\n                lam_1 = pj_param(par.params, \"rlon_1\").f;\n                phi_2 = pj_param(par.params, \"rlat_2\").f;\n                lam_2 = pj_param(par.params, \"rlon_2\").f;\n                if (phi_1 == phi_2 && lam_1 == lam_2)\n                    BOOST_THROW_EXCEPTION( projection_exception(-25) );\n                par.lam0 = adjlon(0.5 * (lam_1 + lam_2));\n                proj_parm.dlam2 = adjlon(lam_2 - lam_1);\n                proj_parm.cp1 = cos(phi_1);\n                proj_parm.cp2 = cos(phi_2);\n                proj_parm.sp1 = sin(phi_1);\n                proj_parm.sp2 = sin(phi_2);\n                proj_parm.cs = proj_parm.cp1 * proj_parm.sp2;\n                proj_parm.sc = proj_parm.sp1 * proj_parm.cp2;\n                proj_parm.ccs = proj_parm.cp1 * proj_parm.cp2 * sin(proj_parm.dlam2);\n                proj_parm.z02 = aacos(proj_parm.sp1 * proj_parm.sp2 + proj_parm.cp1 * proj_parm.cp2 * cos(proj_parm.dlam2));\n                proj_parm.hz0 = .5 * proj_parm.z02;\n                A12 = atan2(proj_parm.cp2 * sin(proj_parm.dlam2),\n                    proj_parm.cp1 * proj_parm.sp2 - proj_parm.sp1 * proj_parm.cp2 * cos(proj_parm.dlam2));\n                proj_parm.ca = cos(pp = aasin(proj_parm.cp1 * sin(A12)));\n                proj_parm.sa = sin(pp);\n                proj_parm.lp = adjlon(atan2(proj_parm.cp1 * cos(A12), proj_parm.sp1) - proj_parm.hz0);\n                proj_parm.dlam2 *= .5;\n                proj_parm.lamc = geometry::math::half_pi<T>() - atan2(sin(A12) * proj_parm.sp1, cos(A12)) - proj_parm.dlam2;\n                proj_parm.thz0 = tan(proj_parm.hz0);\n                proj_parm.rhshz0 = .5 / sin(proj_parm.hz0);\n                proj_parm.r2z0 = 0.5 / proj_parm.z02;\n                proj_parm.z02 *= proj_parm.z02;\n                par.es = 0.;\n            }\n\n    }} // namespace detail::tpeqd\n    #endif // doxygen\n\n    /*!\n        \\brief Two Point Equidistant 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 Projection parameters\n         - lat_1: Latitude of first standard parallel (degrees)\n         - lon_1 (degrees)\n         - lat_2: Latitude of second standard parallel (degrees)\n         - lon_2 (degrees)\n        \\par Example\n        \\image html ex_tpeqd.gif\n    */\n    template <typename CalculationType, typename Parameters>\n    struct tpeqd_spheroid : public detail::tpeqd::base_tpeqd_spheroid<CalculationType, Parameters>\n    {\n        inline tpeqd_spheroid(const Parameters& par) : detail::tpeqd::base_tpeqd_spheroid<CalculationType, Parameters>(par)\n        {\n            detail::tpeqd::setup_tpeqd(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::par4::tpeqd, tpeqd_spheroid, tpeqd_spheroid)\n\n        // Factory entry(s)\n        template <typename CalculationType, typename Parameters>\n        class tpeqd_entry : public detail::factory_entry<CalculationType, Parameters>\n        {\n            public :\n                virtual base_v<CalculationType, Parameters>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<tpeqd_spheroid<CalculationType, Parameters>, CalculationType, Parameters>(par);\n                }\n        };\n\n        template <typename CalculationType, typename Parameters>\n        inline void tpeqd_init(detail::base_factory<CalculationType, Parameters>& factory)\n        {\n            factory.add_to_factory(\"tpeqd\", new tpeqd_entry<CalculationType, Parameters>);\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n} // namespace projections\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_TPEQD_HPP\n\n", "meta": {"hexsha": "2d08d49bde0f92f28f3a14efebf3ed723786ca04", "size": 10450, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost_1_67_0/boost/geometry/srs/projections/proj/tpeqd.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/proj/tpeqd.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/proj/tpeqd.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": 44.2796610169, "max_line_length": 137, "alphanum_fraction": 0.6075598086, "num_tokens": 2586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2755924096181456}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n/// \\file statistics.hpp\r\n/// Includes all of the Statistical Accumulators Library\r\n//\r\n//  Copyright 2005 Eric Niebler. 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_HPP_EAN_01_17_2006\r\n#define BOOST_ACCUMULATORS_STATISTICS_HPP_EAN_01_17_2006\r\n\r\n#include <boost/accumulators/statistics/count.hpp>\r\n#include <boost/accumulators/statistics/covariance.hpp>\r\n#include <boost/accumulators/statistics/density.hpp>\r\n#include <boost/accumulators/statistics/error_of.hpp>\r\n#include <boost/accumulators/statistics/error_of_mean.hpp>\r\n#include <boost/accumulators/statistics/extended_p_square.hpp>\r\n#include <boost/accumulators/statistics/extended_p_square_quantile.hpp>\r\n#include <boost/accumulators/statistics/kurtosis.hpp>\r\n#include <boost/accumulators/statistics/max.hpp>\r\n#include <boost/accumulators/statistics/mean.hpp>\r\n#include <boost/accumulators/statistics/median.hpp>\r\n#include <boost/accumulators/statistics/min.hpp>\r\n#include <boost/accumulators/statistics/moment.hpp>\r\n#include <boost/accumulators/statistics/peaks_over_threshold.hpp>\r\n#include <boost/accumulators/statistics/pot_tail_mean.hpp>\r\n#include <boost/accumulators/statistics/pot_quantile.hpp>\r\n#include <boost/accumulators/statistics/p_square_cumulative_distribution.hpp>\r\n#include <boost/accumulators/statistics/p_square_quantile.hpp>\r\n#include <boost/accumulators/statistics/skewness.hpp>\r\n#include <boost/accumulators/statistics/stats.hpp>\r\n#include <boost/accumulators/statistics/sum.hpp>\r\n#include <boost/accumulators/statistics/tail.hpp>\r\n#include <boost/accumulators/statistics/tail_quantile.hpp>\r\n#include <boost/accumulators/statistics/tail_mean.hpp>\r\n#include <boost/accumulators/statistics/tail_variate.hpp>\r\n#include <boost/accumulators/statistics/tail_variate_means.hpp>\r\n#include <boost/accumulators/statistics/variance.hpp>\r\n#include <boost/accumulators/statistics/weighted_covariance.hpp>\r\n#include <boost/accumulators/statistics/weighted_density.hpp>\r\n#include <boost/accumulators/statistics/weighted_kurtosis.hpp>\r\n#include <boost/accumulators/statistics/weighted_extended_p_square.hpp>\r\n#include <boost/accumulators/statistics/weighted_mean.hpp>\r\n#include <boost/accumulators/statistics/weighted_median.hpp>\r\n#include <boost/accumulators/statistics/weighted_moment.hpp>\r\n#include <boost/accumulators/statistics/weighted_peaks_over_threshold.hpp>\r\n#include <boost/accumulators/statistics/weighted_p_square_cumulative_distribution.hpp>\r\n#include <boost/accumulators/statistics/weighted_p_square_quantile.hpp>\r\n#include <boost/accumulators/statistics/weighted_skewness.hpp>\r\n#include <boost/accumulators/statistics/weighted_sum.hpp>\r\n#include <boost/accumulators/statistics/weighted_tail_quantile.hpp>\r\n#include <boost/accumulators/statistics/weighted_tail_mean.hpp>\r\n#include <boost/accumulators/statistics/weighted_tail_variate_means.hpp>\r\n#include <boost/accumulators/statistics/weighted_variance.hpp>\r\n#include <boost/accumulators/statistics/with_error.hpp>\r\n#include <boost/accumulators/statistics/parameters/quantile_probability.hpp>\r\n#include <boost/accumulators/statistics/variates/covariate.hpp>\r\n\r\n#endif\r\n", "meta": {"hexsha": "81bbe6076b6ec31b610e6b133ab13295a251bae7", "size": 3331, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Compiler/boost/boost/accumulators/statistics.hpp", "max_stars_repo_name": "davidov541/MiniC", "max_stars_repo_head_hexsha": "d3b16a1568b97a4d801880b110a8be04fe848adb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-12-29T07:21:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-29T10:47:38.000Z", "max_issues_repo_path": "LibsExternes/Includes/boost/accumulators/statistics.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/accumulators/statistics.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": 55.5166666667, "max_line_length": 87, "alphanum_fraction": 0.8096667667, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.27553164030879257}}
{"text": "/*\nCopyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.\nAll Rights Reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\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 Sony Pictures Imageworks 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.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(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 <limits>\n\n#include \"oslexec_pvt.h\"\n#include \"noiseimpl.h\"\n#include \"OSL/dual_vec.h\"\n#include \"OSL/Imathx.h\"\n\n#include <OpenImageIO/fmath.h>\n\nusing namespace OSL;\n\nOSL_NAMESPACE_ENTER\nnamespace pvt {\n\n\n\n#if 0 // only when testing the statistics of perlin noise to normalize the range\n\n#include <boost/random.hpp>\n\nvoid test_perlin(int d) {\n    HashScalar h;\n    float noise_min = +std::numeric_limits<float>::max();\n    float noise_max = -std::numeric_limits<float>::max();\n    float noise_avg = 0;\n    float noise_avg2 = 0;\n    float noise_stddev;\n    boost::mt19937 rndgen;\n    boost::uniform_01<boost::mt19937, float> rnd(rndgen);\n    printf(\"Running perlin-%d noise test ...\\n\", d);\n    const int n = 100000000;\n    const float r = 1024;\n    for (int i = 0; i < n; i++) {\n        float noise;\n        float nx = rnd(); nx = (2 * nx - 1) * r;\n        float ny = rnd(); ny = (2 * ny - 1) * r;\n        float nz = rnd(); nz = (2 * nz - 1) * r;\n        float nw = rnd(); nw = (2 * nw - 1) * r;\n        switch (d) {\n            case 1: perlin(noise, h, nx); break;\n            case 2: perlin(noise, h, nx, ny); break;\n            case 3: perlin(noise, h, nx, ny, nz); break;\n            case 4: perlin(noise, h, nx, ny, nz, nw); break;\n        }\n        if (noise_min > noise) noise_min = noise;\n        if (noise_max < noise) noise_max = noise;\n        noise_avg += noise;\n        noise_avg2 += noise * noise;\n    }\n    noise_avg /= n;\n    noise_stddev = std::sqrt((noise_avg2 - noise_avg * noise_avg * n) / n);\n    printf(\"Result: perlin-%d noise stats:\\n\\tmin: %.17g\\n\\tmax: %.17g\\n\\tavg: %.17g\\n\\tdev: %.17g\\n\",\n            d, noise_min, noise_max, noise_avg, noise_stddev);\n    printf(\"Normalization: %.17g\\n\", 1.0f / std::max(fabsf(noise_min), fabsf(noise_max)));\n}\n\n#endif\n\n\n\n/***********************************************************************\n * noise routines callable by the LLVM-generated code.\n */\n\n#if 1\n\n\n#define NOISE_IMPL(opname,implname)                                     \\\nOSL_SHADEOP float osl_ ##opname## _ff (float x) {                       \\\n    implname impl;                                                      \\\n    float r;                                                            \\\n    impl (r, x);                                                        \\\n    return r;                                                           \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP float osl_ ##opname## _fff (float x, float y) {             \\\n    implname impl;                                                      \\\n    float r;                                                            \\\n    impl (r, x, y);                                                     \\\n    return r;                                                           \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP float osl_ ##opname## _fv (char *x) {                       \\\n    implname impl;                                                      \\\n    float r;                                                            \\\n    impl (r, VEC(x));                                                   \\\n    return r;                                                           \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP float osl_ ##opname## _fvf (char *x, float y) {             \\\n    implname impl;                                                      \\\n    float r;                                                            \\\n    impl (r, VEC(x), y);                                                \\\n    return r;                                                           \\\n}                                                                       \\\n                                                                        \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _vf (char *r, float x) {               \\\n    implname impl;                                                      \\\n    impl (VEC(r), x);                                                   \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _vff (char *r, float x, float y) {     \\\n    implname impl;                                                      \\\n    impl (VEC(r), x, y);                                                \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _vv (char *r, char *x) {               \\\n    implname impl;                                                      \\\n    impl (VEC(r), VEC(x));                                              \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _vvf (char *r, char *x, float y) {     \\\n    implname impl;                                                      \\\n    impl (VEC(r), VEC(x), y);                                           \\\n}\n\n\n\n\n\n#define NOISE_IMPL_DERIV(opname,implname)                               \\\nOSL_SHADEOP void osl_ ##opname## _dfdf (char *r, char *x) {             \\\n    implname impl;                                                      \\\n    impl (DFLOAT(r), DFLOAT(x));                                        \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dfdfdf (char *r, char *x, char *y) {  \\\n    implname impl;                                                      \\\n    impl (DFLOAT(r), DFLOAT(x), DFLOAT(y));                             \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dfdff (char *r, char *x, float y) {   \\\n    implname impl;                                                      \\\n    impl (DFLOAT(r), DFLOAT(x), Dual2<float>(y));                       \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dffdf (char *r, float x, char *y) {   \\\n    implname impl;                                                      \\\n    impl (DFLOAT(r), Dual2<float>(x), DFLOAT(y));                       \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dfdv (char *r, char *x) {             \\\n    implname impl;                                                      \\\n    impl (DFLOAT(r), DVEC(x));                                          \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dfdvdf (char *r, char *x, char *y) {  \\\n    implname impl;                                                      \\\n    impl (DFLOAT(r), DVEC(x), DFLOAT(y));                               \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dfdvf (char *r, char *x, float y) {   \\\n    implname impl;                                                      \\\n    impl (DFLOAT(r), DVEC(x), Dual2<float>(y));                         \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dfvdf (char *r, char *x, char *y) {   \\\n    implname impl;                                                      \\\n    impl (DFLOAT(r), Dual2<Vec3>(VEC(x)), DFLOAT(y));                   \\\n}                                                                       \\\n                                                                        \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dvdf (char *r, char *x) {             \\\n    implname impl;                                                      \\\n    impl (DVEC(r), DFLOAT(x));                                          \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dvdfdf (char *r, char *x, char *y) {  \\\n    implname impl;                                                      \\\n    impl (DVEC(r), DFLOAT(x), DFLOAT(y));                               \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dvdff (char *r, char *x, float y) {   \\\n    implname impl;                                                      \\\n    impl (DVEC(r), DFLOAT(x), Dual2<float>(y));                         \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dvfdf (char *r, float x, char *y) {   \\\n    implname impl;                                                      \\\n    impl (DVEC(r), Dual2<float>(x), DFLOAT(y));                         \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dvdv (char *r, char *x) {             \\\n    implname impl;                                                      \\\n    impl (DVEC(r), DVEC(x));                                            \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dvdvdf (char *r, char *x, char *y) {  \\\n    implname impl;                                                      \\\n    impl (DVEC(r), DVEC(x), DFLOAT(y));                                 \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dvdvf (char *r, char *x, float y) {   \\\n    implname impl;                                                      \\\n    impl (DVEC(r), DVEC(x), Dual2<float>(y));                           \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dvvdf (char *r, char *x, char *y) {   \\\n    implname impl;                                                      \\\n    impl (DVEC(r), Dual2<Vec3>(VEC(x)), DFLOAT(y));                     \\\n}\n\n\n\n\n#define NOISE_IMPL_DERIV_OPT(opname,implname)                           \\\nOSL_SHADEOP void osl_ ##opname## _dfdf (char *name, char *r, char *x, char *sg, char *opt) { \\\n    implname impl;                                                      \\\n    impl (USTR(name), DFLOAT(r), DFLOAT(x), (ShaderGlobals *)sg, (NoiseParams *)opt);                                   \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dfdfdf (char *name, char *r, char *x, char *y, char *sg, char *opt) { \\\n    implname impl;                                                      \\\n    impl (USTR(name), DFLOAT(r), DFLOAT(x), DFLOAT(y), (ShaderGlobals *)sg, (NoiseParams *)opt);                        \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dfdv (char *name, char *r, char *x, char *sg, char *opt) {  \\\n    implname impl;                                                      \\\n    impl (USTR(name), DFLOAT(r), DVEC(x), (ShaderGlobals *)sg, (NoiseParams *)opt);                                     \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dfdvdf (char *name, char *r, char *x, char *y, char *sg, char *opt) { \\\n    implname impl;                                                      \\\n    impl (USTR(name), DFLOAT(r), DVEC(x), DFLOAT(y), (ShaderGlobals *)sg, (NoiseParams *)opt);                          \\\n}                                                                       \\\n                                                                        \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dvdf (char *name, char *r, char *x, char *sg, char *opt) {  \\\n    implname impl;                                                      \\\n    impl (USTR(name), DVEC(r), DFLOAT(x), (ShaderGlobals *)sg, (NoiseParams *)opt);                                     \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dvdfdf (char *name, char *r, char *x, char *y, char *sg, char *opt) { \\\n    implname impl;                                                      \\\n    impl (USTR(name), DVEC(r), DFLOAT(x), DFLOAT(y), (ShaderGlobals *)sg, (NoiseParams *)opt);                                     \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dvdv (char *name, char *r, char *x, char *sg, char *opt) {  \\\n    implname impl;                                                      \\\n    impl (USTR(name), DVEC(r), DVEC(x), (ShaderGlobals *)sg, (NoiseParams *)opt);                                       \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dvdvdf (char *name, char *r, char *x, char *y, char *sg, char *opt) { \\\n    implname impl;                                                      \\\n    impl (USTR(name), DVEC(r), DVEC(x), DFLOAT(y), (ShaderGlobals *)sg, (NoiseParams *)opt);                            \\\n}\n\n\n\n\nNOISE_IMPL (cellnoise, CellNoise)\nNOISE_IMPL (noise, Noise)\nNOISE_IMPL_DERIV (noise, Noise)\nNOISE_IMPL (snoise, SNoise)\nNOISE_IMPL_DERIV (snoise, SNoise)\nNOISE_IMPL (simplexnoise, SimplexNoise)\nNOISE_IMPL_DERIV (simplexnoise, SimplexNoise)\nNOISE_IMPL (usimplexnoise, USimplexNoise)\nNOISE_IMPL_DERIV (usimplexnoise, USimplexNoise)\n\n\n\n#define PNOISE_IMPL(opname,implname)                                    \\\n    OSL_SHADEOP float osl_ ##opname## _fff (float x, float px) {        \\\n    implname impl;                                                      \\\n    float r;                                                            \\\n    impl (r, x, px);                                                    \\\n    return r;                                                           \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP float osl_ ##opname## _fffff (float x, float y, float px, float py) { \\\n    implname impl;                                                      \\\n    float r;                                                            \\\n    impl (r, x, y, px, py);                                             \\\n    return r;                                                           \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP float osl_ ##opname## _fvv (char *x, char *px) {            \\\n    implname impl;                                                      \\\n    float r;                                                            \\\n    impl (r, VEC(x), VEC(px));                                          \\\n    return r;                                                           \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP float osl_ ##opname## _fvfvf (char *x, float y, char *px, float py) { \\\n    implname impl;                                                      \\\n    float r;                                                            \\\n    impl (r, VEC(x), y, VEC(px), py);                                   \\\n    return r;                                                           \\\n}                                                                       \\\n                                                                        \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _vff (char *r, float x, float px) {    \\\n    implname impl;                                                      \\\n    impl (VEC(r), x, px);                                               \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _vffff (char *r, float x, float y, float px, float py) { \\\n    implname impl;                                                      \\\n    impl (VEC(r), x, y, px, py);                                        \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _vvv (char *r, char *x, char *px) {    \\\n    implname impl;                                                      \\\n    impl (VEC(r), VEC(x), VEC(px));                                     \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _vvfvf (char *r, char *x, float y, char *px, float py) { \\\n    implname impl;                                                      \\\n    impl (VEC(r), VEC(x), y, VEC(px), py);                              \\\n}\n\n\n\n\n\n#define PNOISE_IMPL_DERIV(opname,implname)                              \\\nOSL_SHADEOP void osl_ ##opname## _dfdff (char *r, char *x, float px) {  \\\n    implname impl;                                                      \\\n    impl (DFLOAT(r), DFLOAT(x), px);                                    \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dfdfdfff (char *r, char *x, char *y, float px, float py) { \\\n    implname impl;                                                      \\\n    impl (DFLOAT(r), DFLOAT(x), DFLOAT(y), px, py);                     \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dfdffff (char *r, char *x, float y, float px, float py) { \\\n    implname impl;                                                      \\\n    impl (DFLOAT(r), DFLOAT(x), Dual2<float>(y), px, py);               \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dffdfff (char *r, float x, char *y, float px, float py) { \\\n    implname impl;                                                      \\\n    impl (DFLOAT(r), Dual2<float>(x), DFLOAT(y), px, py);               \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dfdvv (char *r, char *x, char *px) {  \\\n    implname impl;                                                      \\\n    impl (DFLOAT(r), DVEC(x), VEC(px));                                 \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dfdvdfvf (char *r, char *x, char *y, char *px, float py) { \\\n    implname impl;                                                      \\\n    impl (DFLOAT(r), DVEC(x), DFLOAT(y), VEC(px), py);                  \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dfdvfvf (char *r, char *x, float y, char *px, float py) { \\\n    implname impl;                                                      \\\n    impl (DFLOAT(r), DVEC(x), Dual2<float>(y), VEC(px), py);            \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dfvdfvf (char *r, char *x, char *y, char *px, float py) { \\\n    implname impl;                                                      \\\n    impl (DFLOAT(r), Dual2<Vec3>(VEC(x)), DFLOAT(y), VEC(px), py);      \\\n}                                                                       \\\n                                                                        \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dvdff (char *r, char *x, float px) {  \\\n    implname impl;                                                      \\\n    impl (DVEC(r), DFLOAT(x), px);                                      \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dvdfdfff (char *r, char *x, char *y, float px, float py) { \\\n    implname impl;                                                      \\\n    impl (DVEC(r), DFLOAT(x), DFLOAT(y), px, py);                       \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dvdffff (char *r, char *x, float y, float px, float py) { \\\n    implname impl;                                                      \\\n    impl (DVEC(r), DFLOAT(x), Dual2<float>(y), px, py);                 \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dvfdfff (char *r, float x, char *y, float px, float py) { \\\n    implname impl;                                                      \\\n    impl (DVEC(r), Dual2<float>(x), DFLOAT(y), px, py);                 \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dvdvv (char *r, char *x, char *px) {  \\\n    implname impl;                                                      \\\n    impl (DVEC(r), DVEC(x), VEC(px));                                   \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dvdvdfvf (char *r, char *x, char *y, char *px, float py) { \\\n    implname impl;                                                      \\\n    impl (DVEC(r), DVEC(x), DFLOAT(y), VEC(px), py);                    \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dvdvfvf (char *r, char *x, float y, float *px, float py) { \\\n    implname impl;                                                      \\\n    impl (DVEC(r), DVEC(x), Dual2<float>(y), VEC(px), py);              \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dvvdfvf (char *r, char *x, char *px, char *y, float py) { \\\n    implname impl;                                                      \\\n    impl (DVEC(r), Dual2<Vec3>(VEC(x)), DFLOAT(y), VEC(px), py);        \\\n}\n\n\n\n\n#define PNOISE_IMPL_DERIV_OPT(opname,implname)                          \\\nOSL_SHADEOP void osl_ ##opname## _dfdff (char *name, char *r, char *x, float px, char *sg, char *opt) { \\\n    implname impl;                                                      \\\n    impl (USTR(name), DFLOAT(r), DFLOAT(x), px, (ShaderGlobals *)sg, (NoiseParams *)opt); \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dfdfdfff (char *name, char *r, char *x, char *y, float px, float py, char *sg, char *opt) { \\\n    implname impl;                                                      \\\n    impl (USTR(name), DFLOAT(r), DFLOAT(x), DFLOAT(y), px, py, (ShaderGlobals *)sg, (NoiseParams *)opt); \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dfdvv (char *name, char *r, char *x, char *px, char *sg, char *opt) {  \\\n    implname impl;                                                      \\\n    impl (USTR(name), DFLOAT(r), DVEC(x), VEC(px), (ShaderGlobals *)sg, (NoiseParams *)opt); \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dfdvdfvf (char *name, char *r, char *x, char *y, char *px, float py, char *sg, char *opt) { \\\n    implname impl;                                                      \\\n    impl (USTR(name), DFLOAT(r), DVEC(x), DFLOAT(y), VEC(px), py, (ShaderGlobals *)sg, (NoiseParams *)opt); \\\n}                                                                       \\\n                                                                        \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dvdff (char *name, char *r, char *x, float px, char *sg, char *opt) {  \\\n    implname impl;                                                      \\\n    impl (USTR(name), DVEC(r), DFLOAT(x), px, (ShaderGlobals *)sg, (NoiseParams *)opt); \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dvdfdfff (char *name, char *r, char *x, char *y, float px, float py, char *sg, char *opt) { \\\n    implname impl;                                                      \\\n    impl (USTR(name), DVEC(r), DFLOAT(x), DFLOAT(y), px, py, (ShaderGlobals *)sg, (NoiseParams *)opt); \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dvdvv (char *name, char *r, char *x, char *px, char *sg, char *opt) {  \\\n    implname impl;                                                      \\\n    impl (USTR(name), DVEC(r), DVEC(x), VEC(px), (ShaderGlobals *)sg, (NoiseParams *)opt); \\\n}                                                                       \\\n                                                                        \\\nOSL_SHADEOP void osl_ ##opname## _dvdvdfvf (char *name, char *r, char *x, char *y, char *px, float py, char *sg, char *opt) { \\\n    implname impl;                                                      \\\n    impl (USTR(name), DVEC(r), DVEC(x), DFLOAT(y), VEC(px), py, (ShaderGlobals *)sg, (NoiseParams *)opt); \\\n}\n\n\n\n\nPNOISE_IMPL (pcellnoise, PeriodicCellNoise)\nPNOISE_IMPL (pnoise, PeriodicNoise)\nPNOISE_IMPL_DERIV (pnoise, PeriodicNoise)\nPNOISE_IMPL (psnoise, PeriodicSNoise)\nPNOISE_IMPL_DERIV (psnoise, PeriodicSNoise)\n\n\n\nstruct GaborNoise {\n    GaborNoise () { }\n\n    // Gabor always uses derivatives, so dual versions only\n\n    inline void operator() (ustring noisename, Dual2<float> &result,\n                            const Dual2<float> &x,\n                            ShaderGlobals *sg, const NoiseParams *opt) const {\n        result = gabor (x, opt);\n    }\n\n    inline void operator() (ustring noisename, Dual2<float> &result,\n                            const Dual2<float> &x, const Dual2<float> &y,\n                            ShaderGlobals *sg, const NoiseParams *opt) const {\n        result = gabor (x, y, opt);\n    }\n\n    inline void operator() (ustring noisename, Dual2<float> &result,\n                            const Dual2<Vec3> &p,\n                            ShaderGlobals *sg, const NoiseParams *opt) const {\n        result = gabor (p, opt);\n    }\n\n    inline void operator() (ustring noisename, Dual2<float> &result,\n                            const Dual2<Vec3> &p, const Dual2<float> &t,\n                            ShaderGlobals *sg, const NoiseParams *opt) const {\n        // FIXME -- This is very broken, we are ignoring 4D!\n        result = gabor (p, opt);\n    }\n\n    inline void operator() (ustring noisename, Dual2<Vec3> &result,\n                            const Dual2<float> &x,\n                            ShaderGlobals *sg, const NoiseParams *opt) const {\n        result = gabor3 (x, opt);\n    }\n\n    inline void operator() (ustring noisename, Dual2<Vec3> &result,\n                            const Dual2<float> &x, const Dual2<float> &y,\n                            ShaderGlobals *sg, const NoiseParams *opt) const {\n        result = gabor3 (x, y, opt);\n    }\n\n    inline void operator() (ustring noisename, Dual2<Vec3> &result,\n                            const Dual2<Vec3> &p,\n                            ShaderGlobals *sg, const NoiseParams *opt) const {\n        result = gabor3 (p, opt);\n    }\n\n    inline void operator() (ustring noisename, Dual2<Vec3> &result,\n                            const Dual2<Vec3> &p, const Dual2<float> &t,\n                            ShaderGlobals *sg, const NoiseParams *opt) const {\n        // FIXME -- This is very broken, we are ignoring 4D!\n        result = gabor3 (p, opt);\n    }\n};\n\n\n\nstruct GaborPNoise {\n    GaborPNoise () { }\n\n    // Gabor always uses derivatives, so dual versions only\n\n    inline void operator() (ustring noisename, Dual2<float> &result,\n                            const Dual2<float> &x, float px,\n                            ShaderGlobals *sg, const NoiseParams *opt) const {\n        result = pgabor (x, px, opt);\n    }\n\n    inline void operator() (ustring noisename, Dual2<float> &result,\n                            const Dual2<float> &x, const Dual2<float> &y,\n                            float px, float py,\n                            ShaderGlobals *sg, const NoiseParams *opt) const {\n        result = pgabor (x, y, px, py, opt);\n    }\n\n    inline void operator() (ustring noisename, Dual2<float> &result,\n                            const Dual2<Vec3> &p, const Vec3 &pp,\n                            ShaderGlobals *sg, const NoiseParams *opt) const {\n        result = pgabor (p, pp, opt);\n    }\n\n    inline void operator() (ustring noisename, Dual2<float> &result,\n                            const Dual2<Vec3> &p, const Dual2<float> &t,\n                            const Vec3 &pp, float tp,\n                            ShaderGlobals *sg, const NoiseParams *opt) const {\n        // FIXME -- This is very broken, we are ignoring 4D!\n        result = pgabor (p, pp, opt);\n    }\n\n    inline void operator() (ustring noisename, Dual2<Vec3> &result,\n                            const Dual2<float> &x, float px,\n                            ShaderGlobals *sg, const NoiseParams *opt) const {\n        result = pgabor3 (x, px, opt);\n    }\n\n    inline void operator() (ustring noisename, Dual2<Vec3> &result,\n                            const Dual2<float> &x, const Dual2<float> &y,\n                            float px, float py,\n                            ShaderGlobals *sg, const NoiseParams *opt) const {\n        result = pgabor3 (x, y, px, py, opt);\n    }\n\n    inline void operator() (ustring noisename, Dual2<Vec3> &result,\n                            const Dual2<Vec3> &p, const Vec3 &pp,\n                            ShaderGlobals *sg, const NoiseParams *opt) const {\n        result = pgabor3 (p, pp, opt);\n    }\n\n    inline void operator() (ustring noisename, Dual2<Vec3> &result,\n                            const Dual2<Vec3> &p, const Dual2<float> &t,\n                            const Vec3 &pp, float tp,\n                            ShaderGlobals *sg, const NoiseParams *opt) const {\n        // FIXME -- This is very broken, we are ignoring 4D!\n        result = pgabor3 (p, pp, opt);\n    }\n};\n\n\n\nNOISE_IMPL_DERIV_OPT (gabornoise, GaborNoise)\nPNOISE_IMPL_DERIV_OPT (gaborpnoise, GaborPNoise)\n\n\n\nstruct GenericNoise {\n    GenericNoise () { }\n\n    // Template on R, S, and T to be either float or Vec3\n\n    // dual versions -- this is always called with derivs\n\n    template<class R, class S>\n    inline void operator() (ustring name, Dual2<R> &result, const Dual2<S> &s,\n                            ShaderGlobals *sg, const NoiseParams *opt) const {\n        if (name == Strings::uperlin || name == Strings::noise) {\n            Noise noise;\n            noise(result, s);\n        } else if (name == Strings::perlin || name == Strings::snoise) {\n            SNoise snoise;\n            snoise(result, s);\n        } else if (name == Strings::simplexnoise || name == Strings::simplex) {\n            SimplexNoise simplexnoise;\n            simplexnoise(result, s);\n        } else if (name == Strings::usimplexnoise || name == Strings::usimplex) {\n            USimplexNoise usimplexnoise;\n            usimplexnoise(result, s);\n        } else if (name == Strings::cell) {\n            CellNoise cellnoise;\n            cellnoise(result.val(), s.val());\n            result.clear_d();\n        } else if (name == Strings::gabor) {\n            GaborNoise gnoise;\n            gnoise (name, result, s, sg, opt);\n        } else {\n            ((ShadingContext *)sg->context)->error (\"Unknown noise type \\\"%s\\\"\", name.c_str());\n        }\n    }\n\n    template<class R, class S, class T>\n    inline void operator() (ustring name, Dual2<R> &result,\n                            const Dual2<S> &s, const Dual2<T> &t,\n                            ShaderGlobals *sg, const NoiseParams *opt) const {\n        if (name == Strings::uperlin || name == Strings::noise) {\n            Noise noise;\n            noise(result, s, t);\n        } else if (name == Strings::perlin || name == Strings::snoise) {\n            SNoise snoise;\n            snoise(result, s, t);\n        } else if (name == Strings::simplexnoise || name == Strings::simplex) {\n            SimplexNoise simplexnoise;\n            simplexnoise(result, s, t);\n        } else if (name == Strings::usimplexnoise || name == Strings::usimplex) {\n            USimplexNoise usimplexnoise;\n            usimplexnoise(result, s, t);\n        } else if (name == Strings::cell) {\n            CellNoise cellnoise;\n            cellnoise(result.val(), s.val(), t.val());\n            result.clear_d();\n        } else if (name == Strings::gabor) {\n            GaborNoise gnoise;\n            gnoise (name, result, s, t, sg, opt);\n        } else {\n            ((ShadingContext *)sg->context)->error (\"Unknown noise type \\\"%s\\\"\", name.c_str());\n        }\n    }\n};\n\n\nNOISE_IMPL_DERIV_OPT (genericnoise, GenericNoise)\n\n\nstruct GenericPNoise {\n    GenericPNoise () { }\n\n    // Template on R, S, and T to be either float or Vec3\n\n    // dual versions -- this is always called with derivs\n\n    template<class R, class S>\n    inline void operator() (ustring name, Dual2<R> &result, const Dual2<S> &s,\n                            const S &sp,\n                            ShaderGlobals *sg, const NoiseParams *opt) const {\n        if (name == Strings::uperlin || name == Strings::noise) {\n            PeriodicNoise noise;\n            noise(result, s, sp);\n        } else if (name == Strings::perlin || name == Strings::snoise) {\n            PeriodicSNoise snoise;\n            snoise(result, s, sp);\n        } else if (name == Strings::cell) {\n            PeriodicCellNoise cellnoise;\n            cellnoise(result.val(), s.val(), sp);\n            result.clear_d();\n        } else if (name == Strings::gabor) {\n            GaborPNoise gnoise;\n            gnoise (name, result, s, sp, sg, opt);\n        } else {\n            ((ShadingContext *)sg->context)->error (\"Unknown noise type \\\"%s\\\"\", name.c_str());\n        }\n    }\n\n    template<class R, class S, class T>\n    inline void operator() (ustring name, Dual2<R> &result,\n                            const Dual2<S> &s, const Dual2<T> &t,\n                            const S &sp, const T &tp,\n                            ShaderGlobals *sg, const NoiseParams *opt) const {\n        if (name == Strings::uperlin || name == Strings::noise) {\n            PeriodicNoise noise;\n            noise(result, s, t, sp, tp);\n        } else if (name == Strings::perlin || name == Strings::snoise) {\n            PeriodicSNoise snoise;\n            snoise(result, s, t, sp, tp);\n        } else if (name == Strings::cell) {\n            PeriodicCellNoise cellnoise;\n            cellnoise(result.val(), s.val(), t.val(), sp, tp);\n            result.clear_d();\n        } else if (name == Strings::gabor) {\n            GaborPNoise gnoise;\n            gnoise (name, result, s, t, sp, tp, sg, opt);\n        } else {\n            ((ShadingContext *)sg->context)->error (\"Unknown noise type \\\"%s\\\"\", name.c_str());\n        }\n    }\n};\n\n\nPNOISE_IMPL_DERIV_OPT (genericpnoise, GenericPNoise)\n\n\n// Utility: retrieve a pointer to the ShadingContext's noise params\n// struct, also re-initialize its contents.\nOSL_SHADEOP void *\nosl_get_noise_options (void *sg_)\n{\n    ShaderGlobals *sg = (ShaderGlobals *)sg_;\n    RendererServices::NoiseOpt *opt = sg->context->noise_options_ptr ();\n    new (opt) RendererServices::NoiseOpt;\n    return opt;\n}\n\n\n\nOSL_SHADEOP void\nosl_noiseparams_set_anisotropic (void *opt, int a)\n{\n    ((RendererServices::NoiseOpt *)opt)->anisotropic = a;\n}\n\n\n\nOSL_SHADEOP void\nosl_noiseparams_set_do_filter (void *opt, int a)\n{\n    ((RendererServices::NoiseOpt *)opt)->do_filter = a;\n}\n\n\n\nOSL_SHADEOP void\nosl_noiseparams_set_direction (void *opt, void *dir)\n{\n    ((RendererServices::NoiseOpt *)opt)->direction = VEC(dir);\n}\n\n\n\nOSL_SHADEOP void\nosl_noiseparams_set_bandwidth (void *opt, float b)\n{\n    ((RendererServices::NoiseOpt *)opt)->bandwidth = b;\n}\n\n\n\nOSL_SHADEOP void\nosl_noiseparams_set_impulses (void *opt, float i)\n{\n    ((RendererServices::NoiseOpt *)opt)->impulses = i;\n}\n\n\n\n} // namespace pvt\nOSL_NAMESPACE_EXIT\n\n#endif\n", "meta": {"hexsha": "108a993a874da08e78966bdf0e2b4cfc791ee11c", "size": 41114, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/liboslexec/opnoise.cpp", "max_stars_repo_name": "LumaPictures/OpenShadingLanguage", "max_stars_repo_head_hexsha": "e5764ed8c3d7977632d74e373b6fbf28cd372621", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-07-13T16:01:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-22T21:13:46.000Z", "max_issues_repo_path": "src/liboslexec/opnoise.cpp", "max_issues_repo_name": "johnhaddon/OpenShadingLanguage", "max_issues_repo_head_hexsha": "efb4a9a622080f25ce3c83b763036bab47689949", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/liboslexec/opnoise.cpp", "max_forks_repo_name": "johnhaddon/OpenShadingLanguage", "max_forks_repo_head_hexsha": "efb4a9a622080f25ce3c83b763036bab47689949", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-04-12T06:34:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-10-20T10:24:39.000Z", "avg_line_length": 52.0430379747, "max_line_length": 132, "alphanum_fraction": 0.3693145887, "num_tokens": 8296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2755047284487132}}
{"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#ifndef MTL_DIM_SPLITTER_INCLUDE\n#define MTL_DIM_SPLITTER_INCLUDE\n\n#include <algorithm>\n#include <boost/numeric/mtl/recursion/utility.hpp>\n\nnamespace mtl { namespace recursion {\n\n// Splits dimensions of a matrix separately into halfs (first value rounded up)\ntemplate <typename Matrix> \nstruct half_splitter\n{\n    typedef typename Matrix::size_type                            size_type;\n\n    explicit half_splitter(Matrix const& matrix) \n    {\n\tsize_type nr= matrix.num_rows(), nc= matrix.num_cols();\n\tnr-= nr / 2; // keep the part (by removind the down-rounded half)\n\tnc-= nc / 2;\n\tmy_row_split= matrix.begin_row() + nr;\n\tmy_col_split= matrix.begin_col() + nc;\n    }\n\n    // End of northern half and beginning of southern\n    size_type row_split() const\n    {\n\treturn my_row_split;\n    }\n\n    // End of western half and beginning of eastern\n    size_type col_split() const\n    {\n\treturn my_col_split;\n    }\n\nprivate:\n    size_type             my_row_split, my_col_split;\n};\n\n// Splits dimensions of a matrix separately into a first part that\n//   is the largest power of 2 smaller than m or n, plus rest;\n//   doesn't yield empty submatrices if both dimension > 1\ntemplate <typename Matrix> \nstruct separate_dim_splitter\n{\n    typedef typename Matrix::size_type                            size_type;\n\n    explicit separate_dim_splitter(Matrix const& matrix) \n\t: my_row_split(matrix.begin_row() + first_part(matrix.num_rows())),\n\t  my_col_split(matrix.begin_col() + first_part(matrix.num_cols()))\n    {}\n\n    // End of northern half and beginning of southern\n    size_type row_split() const\n    {\n\treturn my_row_split;\n    }\n\n    // End of western half and beginning of eastern\n    size_type col_split() const\n    {\n\treturn my_col_split;\n    }\n\nprivate:\n    size_type             my_row_split, my_col_split;\n};\n\n// Splits dimensions of a matrix separately into a first part that\n//   is the largest power of 2 smaller than the maximum of m and n;\n//   can yield 1 or two empty submatrices if matrix is rather unproportional;\n//   helps creating square submatrices\ntemplate <typename Matrix> \nstruct max_dim_splitter\n{\n    typedef typename Matrix::size_type                            size_type;\n\n    explicit max_dim_splitter(Matrix const& matrix) \n\t: // matrix(matrix),\n\t  my_split(std::max(first_part(matrix.num_rows()), first_part(matrix.num_cols()))),\n\t  my_row_split(std::min(matrix.begin_row() + my_split, matrix.end_row())),\n\t  my_col_split(std::min(matrix.begin_col() + my_split, matrix.end_col()))\n   {}\n\n    // End of northern half and beginning of southern (limited to end_row)\n    size_type row_split() const\n    {\n\treturn my_row_split;\n    }\n\n    // End of western half and beginning of eastern (limited to end_col)\n    size_type col_split() const\n    {\n\treturn my_col_split;\n    }\n\nprivate:\n    //    Matrix const&   matrix;\n    size_type             my_split, // minimal 2^(k-1) such that 2^k >= max(num_rows, num_cols)\n                    my_row_split, my_col_split;\n};\n\n\n// Splitting within bounding box of power of 2, using recursators\n// For instance, the upper left part of a 530 x 17 matrix is\n//   530 x 17   if the bound is 2048 or larger\n//   512 x 17   if the bound is 1024\n//                 bound of 512 or smaller is a wrong bound\ntemplate <typename Recursator>\nstruct outer_bound_splitter\n{\n    typedef typename Recursator::size_type                            size_type;\n\n    explicit outer_bound_splitter(Recursator const& recursator) \n    {\n\ttypename Recursator::matrix_type const& matrix= recursator.get_value();\n\tmy_row_split= std::min(matrix.begin_row() + recursator.bound() / 2, matrix.end_row());\n\tmy_col_split= std::min(matrix.begin_col() + recursator.bound() / 2, matrix.end_col());\n    }\n\n\n    // End of northern half and beginning of southern (limited to end_row)\n    size_type row_split() const\n    {\n\treturn my_row_split;\n    }\n\n    // End of western half and beginning of eastern (limited to end_col)\n    size_type col_split() const\n    {\n\treturn my_col_split;\n    }\n\nprivate:\n    size_type             my_row_split, my_col_split;\n};\n\n\n\n}} // namespace mtl::recursion \n\n#endif // MTL_DIM_SPLITTER_INCLUDE\n", "meta": {"hexsha": "d1569a4ffebf675b722dfbc7cf4301996e15cd1c", "size": 4593, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/recursion/dim_splitter.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/mtl/recursion/dim_splitter.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/mtl/recursion/dim_splitter.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": 29.6322580645, "max_line_length": 95, "alphanum_fraction": 0.6838667538, "num_tokens": 1102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.27550472844871315}}
{"text": "#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <stdio.h>\n#include <math.h>\n#include <vector>\n#include <numeric>\n#include <strings.h>\n#include <assert.h>\n#include <sys/types.h>\n#include <stdexcept>\n\n#include <dirent.h>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/adapted/c_array.hpp>\n\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)\n\ntypedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > Polygon;\n\n\nusing namespace std;\n\n/*=======================================================================\nSTATIC EVALUATION PARAMETERS\n=======================================================================*/\n\n// easy and hard evaluation level\nenum DIFFICULTY{EASY=0, HARD=1};\n\nconst int32_t N_TESTIMAGES = 27661;\n\nconst int32_t MIN_3D_N_POINTS = 10;\nconst double MAX_3D_DIST[2] = {15, 25};\nconst double MIN_2D_AREA[2] = {1600, 500};\nconst double MAX_2D_OCC = 2;\n// evaluation metrics: image, ground or 3D\nenum METRIC{IMAGE=0, GROUND=1, BOX3D=2};\n\n// evaluated object classes\nenum CLASSES{CAR=0, PEDESTRIAN=1, CYCLIST=2};\nconst int NUM_CLASS = 3;\n\n// parameters varying per class\nvector<string> CLASS_NAMES;\nvector<string> CLASS_NAMES_CAP;\n// the minimum overlap required for 2D evaluation on the image/ground plane and 3D evaluation\nconst double MIN_OVERLAP[3][3] = {{0.7, 0.5, 0.5}, {0.7, 0.5, 0.5}, {0.5, 0.3, 0.3}};\n\n// no. of recall steps that should be evaluated (discretized)\nconst double N_SAMPLE_PTS = 41;\n\n// initialize class names\nvoid initGlobals () {\n  CLASS_NAMES.push_back(\"car\");\n  CLASS_NAMES.push_back(\"pedestrian\");\n  CLASS_NAMES.push_back(\"cyclist\");\n  CLASS_NAMES_CAP.push_back(\"Car\");\n  CLASS_NAMES_CAP.push_back(\"Pedestrian\");\n  CLASS_NAMES_CAP.push_back(\"Cyclist\");\n}\n\n/*=======================================================================\nDATA TYPES FOR EVALUATION\n=======================================================================*/\n\n// holding data needed for precision-recall and precision-aos\nstruct tPrData {\n  vector<double> v;           // detection score for computing score thresholds\n  double         similarity;  // orientation similarity\n  int32_t        tp;          // true positives\n  int32_t        fp;          // false positives\n  int32_t        fn;          // false negatives\n  tPrData () :\n    similarity(0), tp(0), fp(0), fn(0) {}\n};\n\n// holding bounding boxes for ground truth and detections\nstruct tBox {\n  string  type;     // object type as car, pedestrian or cyclist,...\n  double   x1;      // left corner\n  double   y1;      // top corner\n  double   x2;      // right corner\n  double   y2;      // bottom corner\n  double   alpha;   // image orientation\n  tBox (string type, double x1,double y1,double x2,double y2,double alpha) :\n    type(type),x1(x1),y1(y1),x2(x2),y2(y2),alpha(alpha) {}\n};\n\n// holding ground truth data\nstruct tGroundtruth {\n  tBox    box;        // object type, box, orientation\n  int32_t  truncation; // truncation 0..1\n  int32_t occlusion;  // occlusion 0,1,2,3 (non, partly, partly, fully)\n  int32_t num_points_3d;\n  double ry;\n  double  t1, t2, t3;\n  double h, w, l;\n  tGroundtruth () :\n    box(tBox(\"invalild\",-1,-1,-1,-1,-10)),truncation(-1),occlusion(-1) {}\n  tGroundtruth (tBox box,int32_t truncation,int32_t occlusion) :\n    box(box),truncation(truncation),occlusion(occlusion) {}\n  tGroundtruth (string type,double x1,double y1,double x2,double y2,double alpha,int32_t truncation,int32_t occlusion) :\n    box(tBox(type,x1,y1,x2,y2,alpha)),truncation(truncation),occlusion(occlusion) {}\n};\n\n// holding detection data\nstruct tDetection {\n  tBox    box;    // object type, box, orientation\n  double  thresh; // detection score\n  double  ry;\n  double  t1, t2, t3;\n  double  h, w, l;\n  tDetection ():\n    box(tBox(\"invalid\",-1,-1,-1,-1,-10)),thresh(-1000) {}\n  tDetection (tBox box,double thresh) :\n    box(box),thresh(thresh) {}\n  tDetection (string type,double x1,double y1,double x2,double y2,double alpha,double thresh) :\n    box(tBox(type,x1,y1,x2,y2,alpha)),thresh(thresh) {}\n};\n\n\n/*=======================================================================\nFUNCTIONS TO LOAD DETECTION AND GROUND TRUTH DATA ONCE, SAVE RESULTS\n=======================================================================*/\nvector<tDetection> loadDetection(string file_name) {\n\n  vector<tDetection> detections;\n  FILE *fp = fopen(file_name.c_str(),\"r\");\n  if (!fp)\n    throw invalid_argument(\"cannot read detection file \" + file_name);\n  while (!feof(fp)) {\n    tDetection d;\n    int trash;\n    char str[255];\n    if (fscanf(fp, \"%s %d %d %d %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf\",\n                   str, &trash, &trash, &trash, &d.box.alpha, &d.box.x1, &d.box.y1,\n                   &d.box.x2, &d.box.y2, &d.h, &d.w, &d.l, &d.t1, &d.t2, &d.t3,\n                   &d.ry, &d.thresh)==17) {\n      d.box.type = str;\n      detections.push_back(d);\n    }\n  }\n\n  fclose(fp);\n  return detections;\n}\n\nvector<tGroundtruth> loadGroundtruth(string file_name) {\n  vector<tGroundtruth> groundtruth;\n  FILE *fp = fopen(file_name.c_str(),\"r\");\n  if (!fp)\n    throw invalid_argument(\"cannot read ground truth file \" + file_name);\n  while (!feof(fp)) {\n    tGroundtruth g;\n    int trash;\n    char str[255];\n    if (fscanf(fp, \"%s %d %d %d %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %d %d\",\n                   str, &g.truncation, &g.occlusion, &g.num_points_3d,\n                   &g.box.alpha, &g.box.x1, &g.box.y1, &g.box.x2, &g.box.y2,\n                   &g.h, &g.w, &g.l, &g.t1, &g.t2, &g.t3, &g.ry, &trash)==17) {\n      g.box.type = str;\n      groundtruth.push_back(g);\n    }\n  }\n  fclose(fp);\n  return groundtruth;\n}\n\n\nvector<string> list_dir(const string path) {\n  struct dirent *entry;\n  DIR *dir = opendir(path.c_str());\n  vector<string> entries;\n\n  if (dir == NULL) {\n    return entries;\n  }\n  while ((entry = readdir(dir)) != NULL) {\n    if (strcmp(entry->d_name, \".\") != 0 && strcmp(entry->d_name, \"..\") != 0)\n      entries.push_back(entry->d_name);\n  }\n  closedir(dir);\n  return entries;\n}\n\n/*=======================================================================\nEVALUATION HELPER FUNCTIONS\n=======================================================================*/\n\n// criterion defines whether the overlap is computed with respect to both areas (ground truth and detection)\n// or with respect to box a or b (detection and \"dontcare\" areas)\ninline double imageBoxOverlap(tBox a, tBox b, int32_t criterion=-1){\n\n  // overlap is invalid in the beginning\n  double o = -1;\n\n  // get overlapping area\n  double x1 = max(a.x1, b.x1);\n  double y1 = max(a.y1, b.y1);\n  double x2 = min(a.x2, b.x2);\n  double y2 = min(a.y2, b.y2);\n\n  // compute width and height of overlapping area\n  double w = x2-x1;\n  double h = y2-y1;\n\n  // set invalid entries to 0 overlap\n  if(w<=0 || h<=0)\n    return 0;\n\n  // get overlapping areas\n  double inter = w*h;\n  double a_area = (a.x2-a.x1) * (a.y2-a.y1);\n  double b_area = (b.x2-b.x1) * (b.y2-b.y1);\n\n  // intersection over union overlap depending on users choice\n  if(criterion==-1)     // union\n    o = inter / (a_area+b_area-inter);\n  else if(criterion==0) // bbox_a\n    o = inter / a_area;\n  else if(criterion==1) // bbox_b\n    o = inter / b_area;\n\n  // overlap\n  return o;\n}\n\ninline double imageBoxOverlap(tDetection a, tGroundtruth b, int32_t criterion=-1){\n  return imageBoxOverlap(a.box, b.box, criterion);\n}\n\n// compute polygon of an oriented bounding box\ntemplate <typename T>\nPolygon toPolygon(const T& g) {\n    using namespace boost::numeric::ublas;\n    using namespace boost::geometry;\n    matrix<double> mref(2, 2);\n    mref(0, 0) = cos(g.ry); mref(0, 1) = sin(g.ry);\n    mref(1, 0) = -sin(g.ry); mref(1, 1) = cos(g.ry);\n\n    static int count = 0;\n    matrix<double> corners(2, 4);\n    double data[] = {g.l / 2, g.l / 2, -g.l / 2, -g.l / 2,\n                     g.w / 2, -g.w / 2, -g.w / 2, g.w / 2};\n    std::copy(data, data + 8, corners.data().begin());\n    matrix<double> gc = prod(mref, corners);\n    for (int i = 0; i < 4; ++i) {\n        gc(0, i) += g.t1;\n        gc(1, i) += g.t3;\n    }\n\n    double points[][2] = {{gc(0, 0), gc(1, 0)},{gc(0, 1), gc(1, 1)},{gc(0, 2), gc(1, 2)},{gc(0, 3), gc(1, 3)},{gc(0, 0), gc(1, 0)}};\n    Polygon poly;\n    append(poly, points);\n    return poly;\n}\n\n// measure overlap between bird's eye view bounding boxes, parametrized by (ry, l, w, tx, tz)\ninline double groundBoxOverlap(tDetection d, tGroundtruth g, int32_t criterion = -1) {\n    using namespace boost::geometry;\n    Polygon gp = toPolygon(g);\n    Polygon dp = toPolygon(d);\n\n    std::vector<Polygon> in, un;\n    intersection(gp, dp, in);\n    union_(gp, dp, un);\n\n    double inter_area = in.empty() ? 0 : area(in.front());\n    double union_area = area(un.front());\n    double o;\n    if(criterion==-1)     // union\n        o = inter_area / union_area;\n    else if(criterion==0) // bbox_a\n        o = inter_area / area(dp);\n    else if(criterion==1) // bbox_b\n        o = inter_area / area(gp);\n\n    return o;\n}\n\n// measure overlap between 3D bounding boxes, parametrized by (ry, h, w, l, tx, ty, tz)\ninline double box3DOverlap(tDetection d, tGroundtruth g, int32_t criterion = -1) {\n    using namespace boost::geometry;\n    Polygon gp = toPolygon(g);\n    Polygon dp = toPolygon(d);\n\n    std::vector<Polygon> in, un;\n    intersection(gp, dp, in);\n    union_(gp, dp, un);\n\n    double ymax = min(d.t2, g.t2);\n    double ymin = max(d.t2 - d.h, g.t2 - g.h);\n\n    double inter_area = in.empty() ? 0 : area(in.front());\n    double inter_vol = inter_area * max(0.0, ymax - ymin);\n\n    double det_vol = d.h * d.l * d.w;\n    double gt_vol = g.h * g.l * g.w;\n\n    double o;\n    if(criterion==-1)     // union\n        o = inter_vol / (det_vol + gt_vol - inter_vol);\n    else if(criterion==0) // bbox_a\n        o = inter_vol / det_vol;\n    else if(criterion==1) // bbox_b\n        o = inter_vol / gt_vol;\n\n    return o;\n}\n\nvector<double> getThresholds(vector<double> &v, double n_groundtruth){\n\n  // holds scores needed to compute N_SAMPLE_PTS recall values\n  vector<double> t;\n\n  // sort scores in descending order\n  // (highest score is assumed to give best/most confident detections)\n  sort(v.begin(), v.end(), greater<double>());\n\n  // get scores for linearly spaced recall\n  double current_recall = 0;\n  for(int32_t i=0; i<v.size(); i++){\n\n    // check if right-hand-side recall with respect to current recall is close than left-hand-side one\n    // in this case, skip the current detection score\n    double l_recall, r_recall, recall;\n    l_recall = (double)(i+1)/n_groundtruth;\n    if(i<(v.size()-1))\n      r_recall = (double)(i+2)/n_groundtruth;\n    else\n      r_recall = l_recall;\n\n    if( (r_recall-current_recall) < (current_recall-l_recall) && i<(v.size()-1))\n      continue;\n\n    // left recall is the best approximation, so use this and goto next recall step for approximation\n    recall = l_recall;\n\n    // the next recall step was reached\n    t.push_back(v[i]);\n    current_recall += 1.0/(N_SAMPLE_PTS-1.0);\n  }\n  return t;\n}\n\nvoid cleanData(CLASSES current_class, const vector<tGroundtruth> &gt, const vector<tDetection> &det, vector<int32_t> &ignored_gt, vector<tGroundtruth> &dc, vector<int32_t> &ignored_det, int32_t &n_gt, DIFFICULTY difficulty, bool depth) {\n\n  // extract ground truth bounding boxes for current evaluation class\n  for(int32_t i=0;i<gt.size(); i++){\n\n    // neighboring classes are ignored (\"van\" for \"car\" and \"person_sitting\" for \"pedestrian\")\n    // (lower/upper cases are ignored)\n    int32_t valid_class;\n\n    // all classes without a neighboring class\n    if(!strcasecmp(gt[i].box.type.c_str(), CLASS_NAMES[current_class].c_str()))\n      valid_class = 1;\n\n    // classes with a neighboring class\n    else if(!strcasecmp(CLASS_NAMES[current_class].c_str(), \"Pedestrian\") && !strcasecmp(\"Person_sitting\", gt[i].box.type.c_str()))\n      valid_class = 0;\n    else if(!strcasecmp(CLASS_NAMES[current_class].c_str(), \"Car\") && !strcasecmp(\"Van\", gt[i].box.type.c_str()))\n      valid_class = 0;\n\n    // classes not used for evaluation\n    else\n      valid_class = -1;\n\n    bool ignore = false;\n    bool invalid = false;\n    // 3D groundtruth filter criteria\n    if (depth) {\n      if (gt[i].num_points_3d < 0)\n        invalid = true;\n      if (gt[i].num_points_3d < MIN_3D_N_POINTS)\n        ignore = true;\n      if (gt[i].t1 * gt[i].t1 + gt[i].t3 * gt[i].t3 > MAX_3D_DIST[difficulty] * MAX_3D_DIST[difficulty])\n        ignore = true;\n    } else {\n      double height = gt[i].box.y2 - gt[i].box.y1;\n      double width = gt[i].box.x2 - gt[i].box.x1;\n      double area = width * height;\n      if (gt[i].box.x1 < 0)\n        invalid = true;\n      if (area < MIN_2D_AREA[difficulty])\n        ignore = true;\n      if (gt[i].occlusion > MAX_2D_OCC)\n        ignore = true;\n    }\n    // set ignored vector for ground truth\n    // current class and not ignored (total no. of ground truth is detected for recall denominator)\n    if(invalid)\n      ignored_gt.push_back(-1);\n    else if(valid_class==1 && !ignore){\n      ignored_gt.push_back(0);\n      n_gt++;\n    }\n    else\n      ignored_gt.push_back(1);\n  }\n\n  // extract dontcare areas\n  for(int32_t i=0;i<gt.size(); i++)\n    if(!strcasecmp(\"DontCare\", gt[i].box.type.c_str()))\n      dc.push_back(gt[i]);\n\n  // extract detections bounding boxes of the current class\n  for(int32_t i=0;i<det.size(); i++){\n\n    // neighboring classes are not evaluated\n    int32_t valid_class;\n    if(!strcasecmp(det[i].box.type.c_str(), CLASS_NAMES[current_class].c_str()))\n      valid_class = 1;\n    else\n      valid_class = -1;\n\n    bool ignore = false;\n    if (depth) {\n      if (det[i].t1 * det[i].t1 + det[i].t3 * det[i].t3 > MAX_3D_DIST[difficulty] * MAX_3D_DIST[difficulty])\n        ignore = true;\n    } else {\n      double height = det[i].box.y2 - det[i].box.y1;\n      double width = det[i].box.x2 - det[i].box.x1;\n      double area = width * height;\n      if (area < MIN_2D_AREA[difficulty])\n        ignore = true;\n    }\n    // set ignored vector for detections\n    if(ignore)\n      ignored_det.push_back(1);\n    else if(valid_class==1)\n      ignored_det.push_back(0);\n    else\n      ignored_det.push_back(-1);\n  }\n}\n\ntPrData computeStatistics(CLASSES current_class, const vector<tGroundtruth> &gt,\n        const vector<tDetection> &det, const vector<tGroundtruth> &dc,\n        const vector<int32_t> &ignored_gt, const vector<int32_t>  &ignored_det,\n        bool compute_fp, double (*boxoverlap)(tDetection, tGroundtruth, int32_t),\n        METRIC metric, bool compute_aos=false, double thresh=0, bool debug=false){\n\n  tPrData stat = tPrData();\n  const double NO_DETECTION = -10000000;\n  vector<double> delta;            // holds angular difference for TPs (needed for AOS evaluation)\n  vector<bool> assigned_detection; // holds wether a detection was assigned to a valid or ignored ground truth\n  assigned_detection.assign(det.size(), false);\n  vector<bool> ignored_threshold;\n  ignored_threshold.assign(det.size(), false); // holds detections with a threshold lower than thresh if FP are computed\n\n  // detections with a low score are ignored for computing precision (needs FP)\n  if(compute_fp)\n    for(int32_t i=0; i<det.size(); i++)\n      if(det[i].thresh<thresh)\n        ignored_threshold[i] = true;\n\n  // evaluate all ground truth boxes\n  for(int32_t i=0; i<gt.size(); i++){\n\n    // this ground truth is not of the current or a neighboring class and therefore ignored\n    if(ignored_gt[i]==-1)\n      continue;\n\n    /*=======================================================================\n    find candidates (overlap with ground truth > 0.5) (logical len(det))\n    =======================================================================*/\n    int32_t det_idx          = -1;\n    double valid_detection = NO_DETECTION;\n    double max_overlap     = 0;\n\n    // search for a possible detection\n    bool assigned_ignored_det = false;\n    for(int32_t j=0; j<det.size(); j++){\n\n      // detections not of the current class, already assigned or with a low threshold are ignored\n      if(ignored_det[j]==-1)\n        continue;\n      if(assigned_detection[j])\n        continue;\n      if(ignored_threshold[j])\n        continue;\n\n      // find the maximum score for the candidates and get idx of respective detection\n      double overlap = boxoverlap(det[j], gt[i], -1);\n\n      // for computing recall thresholds, the candidate with highest score is considered\n      if(!compute_fp && overlap>MIN_OVERLAP[metric][current_class] && det[j].thresh>valid_detection){\n        det_idx         = j;\n        valid_detection = det[j].thresh;\n      }\n\n      // for computing pr curve values, the candidate with the greatest overlap is considered\n      // if the greatest overlap is an ignored detection, the overlapping detection is used\n      else if(compute_fp && overlap>MIN_OVERLAP[metric][current_class] && (overlap>max_overlap || assigned_ignored_det) && ignored_det[j]==0){\n        max_overlap     = overlap;\n        det_idx         = j;\n        valid_detection = 1;\n        assigned_ignored_det = false;\n      }\n      else if(compute_fp && overlap>MIN_OVERLAP[metric][current_class] && valid_detection==NO_DETECTION && ignored_det[j]==1){\n        det_idx              = j;\n        valid_detection      = 1;\n        assigned_ignored_det = true;\n      }\n    }\n\n    /*=======================================================================\n    compute TP, FP and FN\n    =======================================================================*/\n\n    // nothing was assigned to this valid ground truth\n    if(valid_detection==NO_DETECTION && ignored_gt[i]==0) {\n      stat.fn++;\n    }\n\n    // only evaluate valid ground truth <=> detection assignments\n    else if(valid_detection!=NO_DETECTION && (ignored_gt[i]==1 || ignored_det[det_idx]==1))\n      assigned_detection[det_idx] = true;\n\n    // found a valid true positive\n    else if(valid_detection!=NO_DETECTION){\n\n      // write highest score to threshold vector\n      stat.tp++;\n      stat.v.push_back(det[det_idx].thresh);\n\n      // compute angular difference of detection and ground truth if valid detection orientation was provided\n      if(compute_aos)\n        delta.push_back(gt[i].box.alpha - det[det_idx].box.alpha);\n\n      // clean up\n      assigned_detection[det_idx] = true;\n    }\n  }\n\n  // if FP are requested, consider stuff area\n  if(compute_fp){\n\n    // count fp\n    for(int32_t i=0; i<det.size(); i++){\n\n      // count false positives if required (height smaller than required is ignored (ignored_det==1)\n      if(!(assigned_detection[i] || ignored_det[i]==-1 || ignored_det[i]==1 || ignored_threshold[i]))\n        stat.fp++;\n    }\n\n    // do not consider detections overlapping with stuff area\n    int32_t nstuff = 0;\n    for(int32_t i=0; i<dc.size(); i++){\n      for(int32_t j=0; j<det.size(); j++){\n\n        // detections not of the current class, already assigned, with a low threshold or a low minimum height are ignored\n        if(assigned_detection[j])\n          continue;\n        if(ignored_det[j]==-1 || ignored_det[j]==1)\n          continue;\n        if(ignored_threshold[j])\n          continue;\n\n        // compute overlap and assign to stuff area, if overlap exceeds class specific value\n        double overlap = boxoverlap(det[j], dc[i], 0);\n        if(overlap>MIN_OVERLAP[metric][current_class]){\n          assigned_detection[j] = true;\n          nstuff++;\n        }\n      }\n    }\n\n    // FP = no. of all not to ground truth assigned detections - detections assigned to stuff areas\n    stat.fp -= nstuff;\n\n    // if all orientation values are valid, the AOS is computed\n    if(compute_aos){\n      vector<double> tmp;\n\n      // FP have a similarity of 0, for all TP compute AOS\n      tmp.assign(stat.fp, 0);\n      for(int32_t i=0; i<delta.size(); i++)\n        tmp.push_back((1.0+cos(delta[i]))/2.0);\n\n      // be sure, that all orientation deltas are computed\n      assert(tmp.size()==stat.fp+stat.tp);\n      assert(delta.size()==stat.tp);\n\n      // get the mean orientation similarity for this image\n      if(stat.tp>0 || stat.fp>0)\n        stat.similarity = accumulate(tmp.begin(), tmp.end(), 0.0);\n\n      // there was neither a FP nor a TP, so the similarity is ignored in the evaluation\n      else\n        stat.similarity = -1;\n    }\n  }\n  return stat;\n}\n\n/*=======================================================================\nEVALUATE CLASS-WISE\n=======================================================================*/\n\nbool eval_class(CLASSES current_class,\n        const vector< vector<tGroundtruth> > &groundtruth,\n        const vector< vector<tDetection> > &detections, bool compute_aos,\n        double (*boxoverlap)(tDetection, tGroundtruth, int32_t),\n        vector<double> &precision,\n        METRIC metric, DIFFICULTY difficulty, bool depth) {\n  assert(groundtruth.size() == detections.size());\n\n  // init\n  int32_t n_gt=0;                                     // total no. of gt (denominator of recall)\n  vector<double> v, thresholds;                       // detection scores, evaluated for recall discretization\n  vector< vector<int32_t> > ignored_gt, ignored_det;  // index of ignored gt detection for current class\n  vector< vector<tGroundtruth> > dontcare;            // index of dontcare areas, included in ground truth\n\n  // for all test images do\n  for (int32_t i=0; i<groundtruth.size(); i++){\n\n    // holds ignored ground truth, ignored detections and dontcare areas for current frame\n    vector<int32_t> i_gt, i_det;\n    vector<tGroundtruth> dc;\n\n    // only evaluate objects of current class and ignore occluded, truncated objects\n    cleanData(current_class, groundtruth[i], detections[i], i_gt, dc, i_det, n_gt, difficulty, depth);\n    ignored_gt.push_back(i_gt);\n    ignored_det.push_back(i_det);\n    dontcare.push_back(dc);\n\n    // compute statistics to get recall values\n    tPrData pr_tmp = tPrData();\n    pr_tmp = computeStatistics(current_class, groundtruth[i], detections[i], dc, i_gt, i_det, false, boxoverlap, metric);\n\n    // add detection scores to vector over all images\n    for(int32_t j=0; j<pr_tmp.v.size(); j++)\n      v.push_back(pr_tmp.v[j]);\n  }\n\n  // get scores that must be evaluated for recall discretization\n  thresholds = getThresholds(v, n_gt);\n\n  // compute TP,FP,FN for relevant scores\n  vector<tPrData> pr;\n  pr.assign(thresholds.size(),tPrData());\n  for (int32_t i=0; i<groundtruth.size(); i++){\n\n    // for all scores/recall thresholds do:\n    for(int32_t t=0; t<thresholds.size(); t++){\n      tPrData tmp = tPrData();\n      tmp = computeStatistics(current_class, groundtruth[i], detections[i], dontcare[i],\n                              ignored_gt[i], ignored_det[i], true, boxoverlap, metric,\n                              compute_aos, thresholds[t], t==38);\n\n      // add no. of TP, FP, FN, AOS for current frame to total evaluation for current threshold\n      pr[t].tp += tmp.tp;\n      pr[t].fp += tmp.fp;\n      pr[t].fn += tmp.fn;\n      if(tmp.similarity!=-1)\n        pr[t].similarity += tmp.similarity;\n    }\n  }\n\n  // compute recall, precision and AOS\n  precision.assign(N_SAMPLE_PTS, 0);\n  double r=0;\n  for (int32_t i=0; i<thresholds.size(); i++){\n    r = pr[i].tp/(double)(pr[i].tp + pr[i].fn);\n    precision[i] = pr[i].tp/(double)(pr[i].tp + pr[i].fp);\n  }\n\n  // filter precision and AOS using max_{i..end}(precision)\n  for (int32_t i=0; i<thresholds.size(); i++){\n    precision[i] = *max_element(precision.begin()+i, precision.end());\n  }\n\n  return true;\n}\n\nvoid write_result(ofstream& outfile, string exp_name, vector<double> &precisions) {\n  double ap = accumulate(precisions.begin() + 1, precisions.end(), 0.0) / (N_SAMPLE_PTS - 1);\n  outfile << exp_name << \",\" << ap ;\n  for (const double& prec : precisions) {\n    outfile << ',' << prec;\n  }\n  outfile << endl;\n}\n\nvoid eval(string gt_dir, string result_dir, int c, bool depth, ofstream& outfile) {\n\n  vector<vector<tGroundtruth>> groundtruths;\n  vector<vector<tDetection>> detections;\n  map<string, vector<vector<tGroundtruth>>> groundtruths_perseq;\n  map<string, vector<vector<tDetection>>> detections_perseq;\n\n  cout << \"Loading data\" << endl;\n  string path;\n  vector<string> sequences = list_dir(gt_dir);\n  for (const auto& sequence : sequences) {\n    vector<string> frames = list_dir(gt_dir + '/' + sequence);\n    vector<vector<tGroundtruth>> groundtruths_seq;\n    vector<vector<tDetection>> detections_seq;\n    for (const auto& frame : frames) {\n      string gt_path = gt_dir + '/' + sequence + '/' + frame;\n      string result_path = \"\";\n      if (depth) {\n        result_path = result_dir + '/' + sequence + '/' + frame;\n      } else {\n        result_path = result_dir + '/' + sequence + \"/image_stitched/\" + frame;\n      }\n      vector<tGroundtruth> gt = loadGroundtruth(gt_path);\n      vector<tDetection> det = loadDetection(result_path);\n      groundtruths.push_back(gt);\n      detections.push_back(det);\n      groundtruths_seq.push_back(gt);\n      detections_seq.push_back(det);\n    }\n    groundtruths_perseq[sequence] = groundtruths_seq;\n    detections_perseq[sequence] = detections_seq;\n  }\n  // if (groundtruths.size() != N_TESTIMAGES)\n  //   throw invalid_argument(\"Mismatch in number of ground truth files.\");\n\n  cout << \"Loaded data\" << endl;\n\n  CLASSES cls = (CLASSES)c;\n\n  // eval image 2D bounding boxes\n  if (!depth) {\n    cout << \"Starting 2D evaluation (\" << CLASS_NAMES[c].c_str() << \") ...\" << endl;\n    vector<double> precision_2d_hard;\n    if (!eval_class(cls, groundtruths, detections, false, imageBoxOverlap, precision_2d_hard, IMAGE, HARD, depth)) {\n      cout << CLASS_NAMES[c].c_str() << \" evaluation failed.\" << endl;\n    } else {\n      write_result(outfile, \"overall\", precision_2d_hard);\n    }\n    for (auto const& groundtruths_seq : groundtruths_perseq) {\n      cout << \"Starting per-sequence 2D evaluation (\" << groundtruths_seq.first << \", \" << CLASS_NAMES[c].c_str() << \") ...\" << endl;\n      vector<double> precision_2d_seq;\n      if (!eval_class(cls, groundtruths_seq.second, detections_perseq[groundtruths_seq.first], false, imageBoxOverlap, precision_2d_seq, IMAGE, HARD, depth)) {\n        cout << CLASS_NAMES[c].c_str() << \" evaluation failed.\" << endl;\n      } else {\n        write_result(outfile, groundtruths_seq.first, precision_2d_seq);\n      }\n    }\n  } else {\n    cout << \"Starting 3D evaluation (\" << CLASS_NAMES[c].c_str() << \") ...\" << endl;\n    vector<double> precision_3d_hard;\n    if (!eval_class(cls, groundtruths, detections, false, box3DOverlap, precision_3d_hard, BOX3D, HARD, depth)) {\n      cout << CLASS_NAMES[c].c_str() << \" evaluation failed.\" << endl;\n    } else {\n      write_result(outfile, \"overall\", precision_3d_hard);\n    }\n    for (auto const& groundtruths_seq : groundtruths_perseq) {\n      cout << \"Starting per-sequence 3D evaluation (\" << groundtruths_seq.first << \", \" << CLASS_NAMES[c].c_str() << \") ...\" << endl;\n      vector<double> precision_3d_seq;\n      if (!eval_class(cls, groundtruths_seq.second, detections_perseq[groundtruths_seq.first], false, box3DOverlap, precision_3d_seq, BOX3D, HARD, depth)) {\n        cout << CLASS_NAMES[c].c_str() << \" evaluation failed.\" << endl;\n      } else {\n        write_result(outfile, groundtruths_seq.first, precision_3d_seq);\n      }\n    }\n  }\n}\n\nint32_t main (int32_t argc, char *argv[]) {\n  if (argc != 5) {\n    cout << \"Usage: ./eval_detection gt_dir result_dir eval_type save_path\" << endl;\n    return 1;\n  }\n  initGlobals();\n\n  vector<vector<tGroundtruth>> groundtruths;\n  vector<vector<tDetection>> detections;\n\n  bool depth = strcmp(argv[3], \"0\") != 0;\n\n  // run evaluation\n  ofstream outfile;\n  outfile.open(argv[4]);\n\n  eval(argv[1], argv[2], 1, depth, outfile);\n  cout << \"Finished evaluating\" << endl;\n\n  outfile.close();\n  cout << \"Saved metrics to \" << argv[4] << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "db5786c2ff44d168ca726aa9cdd3ab769ef94fce", "size": 27933, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/detection_eval/evaluate_object.cpp", "max_stars_repo_name": "huzjkevin/PointRCNN", "max_stars_repo_head_hexsha": "179e45a1e609eacd23b79d973243e3c9361849d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tools/detection_eval/evaluate_object.cpp", "max_issues_repo_name": "huzjkevin/PointRCNN", "max_issues_repo_head_hexsha": "179e45a1e609eacd23b79d973243e3c9361849d8", "max_issues_repo_licenses": ["MIT"], "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/detection_eval/evaluate_object.cpp", "max_forks_repo_name": "huzjkevin/PointRCNN", "max_forks_repo_head_hexsha": "179e45a1e609eacd23b79d973243e3c9361849d8", "max_forks_repo_licenses": ["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.1358490566, "max_line_length": 237, "alphanum_fraction": 0.6179429349, "num_tokens": 7502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.27546412922738334}}
{"text": "/*******************************************************************************\n*\n*  Filename    : RooFit_CompareBackground.cc\n*  Description : Control flow of background function comparison fitting and plotting\n*  Author      : Yi-Mu \"Enoch\" Chen [ ensc@hep1.phys.ntu.edu.tw ]\n*\n*******************************************************************************/\n#include \"TstarAnalysis/Common/interface/PlotStyle.hpp\"\n#include \"TstarAnalysis/LimitCalc/interface/Common.hpp\"\n#include \"TstarAnalysis/LimitCalc/interface/SampleRooFitMgr.hpp\"\n\n#include \"ManagerUtils/Maths/interface/RooFitExt.hpp\"\n#include \"ManagerUtils/PlotUtils/interface/Common.hpp\"\n#include \"ManagerUtils/PlotUtils/interface/RooFitUtils.hpp\"\n\n#include \"RooDataSet.h\"\n#include \"RooFitResult.h\"\n#include \"RooMinimizer.h\"\n#include \"RooNLLVar.h\"\n#include \"TMath.h\"\n\n#include <boost/format.hpp>\n#include <vector>\n\nusing namespace std;\n\nstatic Color_t sequence[] = {\n  KBLUE,\n  KGREEN,\n  KRED,\n  KPURPLE\n};\n\nstruct MyFitResult\n{\n  RooFitResult*      fitresult;\n  TGraph*            fitplot;\n  TGraphAsymmErrors* pullplot;\n  double             ksvalue;\n};\n\n/******************************************************************************/\n\nvoid\nCompareFitFunc( SampleRooFitMgr* mgr )\n{\n  TCanvas* c        = mgr::NewCanvas();\n  TPad* toppad      = mgr::NewTopPad();\n  TPad* botpad      = mgr::NewBottomPad();\n  RooPlot* frame    = SampleRooFitMgr::x().frame();\n  const double xmin = SampleRooFitMgr::x().getMin();\n  const double xmax = SampleRooFitMgr::x().getMax();\n\n  vector<MyFitResult> fitlist;\n  const vector<string> funclist = limnamer.GetInputList<string>( \"fitfunc\" );\n\n  /*******************************************************************************\n  *   Making the top plots\n  *******************************************************************************/\n  toppad->Draw();\n  toppad->cd();\n\n  TGraphAsymmErrors* setplot = (TGraphAsymmErrors*)mgr::PlotOn(\n    frame, mgr->DataSet( \"\" ),\n    RooFit::DrawOption( PGS_DATA )\n    );\n\n  vector<double> prevfitvaluelist = {280, 0.51};\n\n  for( const auto& fitfunc : funclist ){\n    RooAbsPdf* pdf  = mgr->NewPdf( fitfunc, fitfunc );\n    RooDataSet* set = (RooDataSet*)( mgr->DataSet( \"\" ) );\n\n    // Setting up fitting parameters with previous fit results for faster convertions\n    vector<RooRealVar*> fitparams = mgr->VarContains( fitfunc );\n\n    for( size_t i = 0; i < fitparams.size(); ++i ){\n      if( i < prevfitvaluelist.size() ){\n        *( fitparams.at( i ) ) = prevfitvaluelist.at( i );\n      } else {\n        *( fitparams.at( i ) ) = 0;\n      }\n    }\n\n    // Manually calling NNL minizer functions\n    static RooCmdArg min    = RooFit::Minimizer( \"Minuit\", \"Migrad\" );\n    static RooCmdArg sumerr = RooFit::SumW2Error( kTRUE );\n    static RooCmdArg minos  = 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( &minos  );\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    RooFitResult* ans = NULL;\n    const unsigned maxiter = 50;\n    unsigned iter = 0;\n    while( !ans ){\n      ans = pdf->fitTo( *set, fitopt );\n      if( ans->status() ){// Not properly converged\n        ++iter;\n        if( iter > maxiter ) { break; }\n        delete ans;\n        ans = NULL;\n      }\n    }\n\n    MyFitResult x;\n\n    // Saving fit results\n    x.fitresult = ans;\n    x.fitplot   = mgr::PlotOn( frame, pdf );\n    x.ksvalue   = KSTest( *set, *pdf, SampleRooFitMgr::x() );\n    x.pullplot  = mgr::DividedGraph( setplot, x.fitplot );\n\n    // Small information dump after fit\n    prevfitvaluelist.clear();\n    cout << \"Minimum NLL:\" << x.fitresult->minNll() << endl;\n    cout << \"Parameter fit values: \" << endl;\n\n    for( int i = 0; i < x.fitresult->floatParsFinal().getSize(); ++i ){\n      RooRealVar* var = (RooRealVar*)( x.fitresult->floatParsFinal().at( i ) );\n      cout << var->GetName() << \" \" << var->getVal() << \" \" << var->getError() << endl;\n      prevfitvaluelist.push_back( var->getVal() );\n    }\n\n    cout << \"===\" << endl;\n\n    fitlist.push_back( x );\n  }\n\n\n  frame->Draw();\n  frame->SetMinimum( 0.3 );\n  mgr::SetTopPlotAxis( frame );\n  frame->SetTitle( \"\" );\n  c->cd();\n\n  /*******************************************************************************\n  *   Drawing bottom pad.\n  *******************************************************************************/\n  botpad->Draw();\n  botpad->cd();\n\n  TMultiGraph* mg = new TMultiGraph;\n\n  for( const auto fitresult : fitlist ){\n    mg->Add( fitresult.pullplot, \"Z\" );\n  }\n\n  TLine line( xmin, 1, xmax, 1 );\n  TLine line_top( xmin, 1.5, xmax, 1.5 );\n  TLine line_bot( xmin, 0.5, xmax, 0.5 );\n\n  mg->Draw( \"AZ\" );\n  line.Draw( \"SAME\" );\n  line_top.Draw( \"SAME\" );\n  line_bot.Draw( \"SAME\" );\n  mg->GetXaxis()->SetTitle( frame->GetXaxis()->GetTitle() );\n  mg->GetYaxis()->SetTitle( \"Data/Fit\" );\n  mg->GetXaxis()->SetRangeUser( xmin, xmax );\n  mgr::SetBottomPlotAxis( mg );\n  mg->SetMaximum( 1.6 );\n  mg->SetMinimum( 0.4 );\n  c->cd();\n\n  /*******************************************************************************\n  *   Object styling\n  *******************************************************************************/\n  tstar::SetDataStyle( setplot );\n\n  line.SetLineColor( KRED );\n  line.SetLineStyle( 1 );\n  line_top.SetLineColor( kBlack );\n  line_bot.SetLineColor( kBlack );\n  line_top.SetLineStyle( 3 );\n  line_bot.SetLineStyle( 3 );\n\n  // Drawing common\n  mgr::DrawCMSLabel();\n  mgr::DrawLuminosity( mgr::SampleMgr::TotalLuminosity() );\n\n  // Drawing legends\n  TLegend* l = mgr::NewLegend( 0.45, 0.6 );\n  if( limnamer.GetInput<string>( \"sample\" ) == \"Data\" ){\n    l->AddEntry( setplot, \"Data\", \"lp\" );\n  } else {\n    l->AddEntry( setplot, \"MC background\", \"lp\" );\n  }\n\n  for( size_t i = 0; i < fitlist.size(); ++i ){\n    auto fitplot  = fitlist.at( i ).fitplot;\n    auto pullplot = fitlist.at( i ).pullplot;\n    fitplot->SetLineColor( sequence[i] );\n    pullplot->SetLineColor( sequence[i] );\n    fitplot->SetLineWidth( 2 );\n    pullplot->SetLineWidth( 2 );\n    auto funcname = funclist.at( i );\n\n    boost::format fitentryfmt( \"%s K=%.3lf\" );\n    const string fitentry = boost::str(\n      fitentryfmt\n      % limnamer.ExtQuery<string>( \"fitfunc\", funcname, \"Full Name\" )\n      % fitlist.at( i ).ksvalue\n      );\n    l->AddEntry( fitplot, fitentry.c_str(), \"l\" );\n  }\n\n  l->Draw();\n\n  mgr::LatexMgr latex;\n  latex.SetOrigin( PLOT_X_TEXT_MIN, PLOT_Y_TEXT_MAX, TOP_LEFT )\n  .WriteLine( limnamer.GetChannelEXT( \"Root Name\" ) );\n\n  boost::format chi2testfmt( \"LR Test_{%d/%d} = %.3lf\" );\n\n  // Writing LR test results\n  for( size_t i = 0; i+1 < fitlist.size(); ++i ){\n    const double thisnll  = fitlist[i].fitresult->minNll();\n    const double nextnll  = fitlist[i+1].fitresult->minNll();\n    const int thisorder   = fitlist[i].fitresult->floatParsFinal().getSize();\n    const int nextorder   = fitlist[i+1].fitresult->floatParsFinal().getSize();\n    const double chi2test = TMath::Prob( 2*( std::max( fabs( thisnll-nextnll ), 0. ) ), nextorder-thisorder );\n\n    latex.WriteLine( boost::str( chi2testfmt % thisorder % nextorder % chi2test ) );\n  }\n\n  /*******************************************************************************\n  *   Updating everything and saving\n  *******************************************************************************/\n  toppad->Update();\n  botpad->Update();\n  c->Update();\n\n  frame->SetMaximum( mgr::GetYmax( setplot )*1.5 );\n  mgr::SaveToPDF( c, limnamer.PlotFileName( \"bkgcomp\" ) );\n  mgr::SaveToROOT( c, limnamer.PlotRootFile(), limnamer.PlotFileName( \"bkgcomp\" ) );\n  toppad->SetLogy( kTRUE );\n  frame->SetMaximum( mgr::GetYmax( setplot )*300 );\n  mgr::SaveToPDF( c, limnamer.PlotFileName( \"bkgcomp\", \"log\" ) );\n\n\n  /*******************************************************************************\n  *   Printing results and leaving\n  *******************************************************************************/\n  for( auto fit : fitlist ){\n    cout << boost::str( boost::format( \"%.6lf\" ) % fit.fitresult->minNll() ) << endl;\n\n    for( int i = 0; i < fit.fitresult->floatParsFinal().getSize(); ++i ){\n      RooRealVar* var = (RooRealVar*)( fit.fitresult->floatParsFinal().at( i ) );\n      cout << var->GetName() << \" \" << var->getVal() << \" \" << var->getError() << endl;\n    }\n\n    cout << \"===\" << endl;\n  }\n\n  delete toppad;\n  delete botpad;\n  delete c;\n  delete frame;\n}\n", "meta": {"hexsha": "b145703b7d4abe17063cd1b9d5a3e4d6a6384aca", "size": 8808, "ext": "cc", "lang": "C++", "max_stars_repo_path": "LimitCalc/src/RooFit_CompareBackground.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_CompareBackground.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_CompareBackground.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": 32.1459854015, "max_line_length": 110, "alphanum_fraction": 0.5475703906, "num_tokens": 2438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.27543053132934386}}
{"text": "//=======================================================================\n// Copyright (c) 2013 Piotr Wygocki\n//               2014 Piotr Godlewski\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 iterative_rounding.hpp\n * @brief\n * @author Piotr Wygocki, Piotr Godlewski\n * @version 1.0\n * @date 2013-05-06\n */\n#ifndef PAAL_ITERATIVE_ROUNDING_HPP\n#define PAAL_ITERATIVE_ROUNDING_HPP\n\n\n#include \"paal/iterative_rounding/ir_components.hpp\"\n#include \"paal/lp/glp.hpp\"\n#include \"paal/utils/floating.hpp\"\n#include \"paal/utils/type_functions.hpp\"\n#include \"paal/utils/irange.hpp\"\n\n#include <boost/optional.hpp>\n\n#include <cstdlib>\n#include <unordered_map>\n\nnamespace paal {\nnamespace ir {\n\n/**\n * @brief Default Iterative Rounding visitor.\n */\nstruct trivial_visitor {\n    /**\n     * @brief Method called after (re)solving the LP.\n     */\n    template <typename Problem, typename LP>\n    void solve_lp(Problem &problem, LP &lp) {}\n\n    /**\n     * @brief Method called after rounding a column of the LP.\n     */\n    template <typename Problem, typename LP>\n    void round_col(Problem &problem, LP &lp, lp::col_id col, double val) {}\n\n    /**\n     * @brief Method called after relaxing a row of the LP.\n     */\n    template <typename Problem, typename LP>\n    void relax_row(Problem &problem, LP &lp, lp::row_id row) {}\n};\n\n///default solve lp for row_generation,\n///at first call PRIMAL, and DUAL on the next calls\ntemplate <typename Problem, typename LP>\nclass default_solve_lp_in_row_generation {\n    bool m_first;\n    LP & m_lp;\npublic:\n    ///constructor\n    default_solve_lp_in_row_generation(Problem &, LP & lp) : m_first(true), m_lp(lp) {}\n\n    ///operator()\n    lp::problem_type operator()()\n    {\n        if (m_first) {\n            m_first = false;\n            return m_lp.solve_simplex(lp::PRIMAL);\n        }\n        return m_lp.resolve_simplex(lp::DUAL);\n    }\n};\n\n/// default row_generation for lp,\n/// one can customize LP solving, by setting SolveLP\ntemplate <template <class, class> class SolveLP = default_solve_lp_in_row_generation>\nstruct row_generation_solve_lp {\n///operator()\ntemplate <class Problem, class LP>\n    auto operator()(Problem & problem, LP & lp) {\n        return row_generation(problem.get_find_violation(lp), SolveLP<Problem, LP>(problem, lp));\n    }\n};\n\n\n\nnamespace detail {\n\n    /**\n     * @brief This class solves an iterative rounding problem.\n *\n * @tparam Problem\n * @tparam IRcomponents\n * @tparam Visitor\n * @tparam LP\n */\ntemplate <typename Problem, typename IRcomponents, typename Visitor = trivial_visitor, typename LP = lp::glp>\nclass iterative_rounding  {\n    using RoundedCols = std::unordered_map<lp::col_id, std::pair<double, double>>;\n\n    /**\n     * @brief Returns the current value of the LP column.\n     */\n    double get_val(lp::col_id col) const {\n        auto i = m_rounded.find(col);\n        if (i == m_rounded.end()) {\n            return m_lp.get_col_value(col);\n        } else {\n            return i->second.first;\n        }\n    }\n\n  public:\n    /**\n     * @brief Constructor.\n     */\n    iterative_rounding(Problem &problem, IRcomponents e,\n                       Visitor vis = Visitor())\n        : m_ir_components(std::move(e)), m_visitor(std::move(vis)),\n          m_problem(problem) {\n        call<Init>(m_problem, m_lp);\n    }\n\n    /**\n     * @brief Finds solution to the LP.\n     *\n     * @return LP solution status\n     */\n    lp::problem_type solve_lp() {\n        auto prob_type = call<SolveLP>(m_problem, m_lp);\n        assert(prob_type != lp::UNDEFINED);\n        m_visitor.solve_lp(m_problem, m_lp);\n        return prob_type;\n    }\n\n    /**\n     * @brief Finds solution to the LP.\n     *\n     * @return LP solution status\n     */\n    lp::problem_type resolve_lp() {\n        auto prob_type = call<ResolveLP>(m_problem, m_lp);\n        assert(prob_type != lp::UNDEFINED);\n        m_visitor.solve_lp(m_problem, m_lp);\n        return prob_type;\n    }\n\n    /**\n     * @brief Returns the solution cost based on the LP values.\n     */\n    double get_solution_cost() {\n        double sol_cost(0);\n        for (auto col : m_lp.get_columns()) {\n            sol_cost += m_lp.get_col_value(col) * m_lp.get_col_coef(col);\n        }\n        for (auto rounded_col : m_rounded) {\n            sol_cost += rounded_col.second.first * rounded_col.second.second;\n        }\n        return sol_cost;\n    }\n\n    /**\n     * @brief Rounds the LP columns (independently) using the RoundCondition\n     * component.\n     *\n     * @return true iff at least one column was rounded\n     */\n    bool round() {\n        int deleted(0);\n        auto &&cols = m_lp.get_columns();\n        auto cbegin = std::begin(cols);\n        auto cend = std::end(cols);\n\n        while (cbegin != cend) {\n            lp::col_id col = *cbegin;\n            auto do_round = call<RoundCondition>(m_problem, m_lp, col);\n            if (do_round) {\n                ++deleted;\n                m_rounded.insert(std::make_pair(col,\n                    std::make_pair(*do_round, m_lp.get_col_coef(col))));\n                m_visitor.round_col(m_problem, m_lp, col, *do_round);\n                cbegin = delete_column(cbegin, *do_round);\n            }\n            else {\n                ++cbegin;\n            }\n        }\n\n        return deleted > 0;\n    }\n\n    /**\n     * @brief Relaxes the LP rows using the RelaxCondition component.\n     *\n     * @return true iff at least one row was relaxed\n     */\n    bool relax() {\n        int deleted(0);\n        auto &&rows = m_lp.get_rows();\n        auto rbegin = std::begin(rows);\n        auto rend = std::end(rows);\n\n        while (rbegin != rend) {\n            lp::row_id row = *rbegin;\n            if (call<RelaxCondition>(m_problem, m_lp, row)) {\n                ++deleted;\n                m_visitor.relax_row(m_problem, m_lp, row);\n                rbegin = m_lp.delete_row(rbegin);\n                if (call<RelaxationsLimit>(deleted)) {\n                    break;\n                }\n            } else {\n                ++rbegin;\n            }\n        }\n\n        return deleted > 0;\n    }\n\n    /**\n     * @brief Returns the LP object used to solve the IR.\n     */\n    LP &get_lp() { return m_lp; }\n\n    /**\n     * @brief Returns the IR components.\n     */\n    IRcomponents &get_ir_components() { return m_ir_components; }\n\n    /**\n     * @brief Sets the solution to the problem using SetSolution component.\n     */\n    void set_solution() {\n        call<SetSolution>(m_problem, boost::bind(&iterative_rounding::get_val,\n                                               this, _1));\n    }\n\n    /**\n     * @brief Rounds the LP using the RoundCondition component.\n     */\n    void dependent_round() { call<RoundCondition>(m_problem, m_lp); }\n\n    /**\n     * @brief Checks if the IR problem has been solved, using the StopCondition\n    * component.\n     *\n     * @return true iff the problem has been solved\n     */\n    bool stop_condition() { return call<StopCondition>(m_problem, m_lp); }\n\n  private:\n    template <typename Action, typename... Args>\n    auto call(Args &&... args)\n        ->decltype(std::declval<IRcomponents>().template call<Action>(\n              std::forward<Args>(args)...)) {\n        return m_ir_components.template call<Action>(\n            std::forward<Args>(args)...);\n    }\n\n    /// Deletes a column from the LP and adjusts the row bounds.\n    typename LP::ColIter\n    delete_column(typename LP::ColIter col_iter, double value) {\n        auto column = m_lp.get_rows_in_column(*col_iter);\n        lp::row_id row;\n        double coef;\n        for (auto const &c : column) {\n            boost::tie(row, coef) = c;\n            double ub = m_lp.get_row_upper_bound(row);\n            double lb = m_lp.get_row_lower_bound(row);\n            double diff = coef * value;\n            m_lp.set_row_upper_bound(row, ub - diff);\n            m_lp.set_row_lower_bound(row, lb - diff);\n        }\n        return m_lp.delete_col(col_iter);\n    };\n\n    LP m_lp;\n    IRcomponents m_ir_components;\n    Visitor m_visitor;\n    utils::compare<double> m_compare;\n    RoundedCols m_rounded;\n    Problem &m_problem;\n};\n\n} //detail\n\n/// Iterative Rounding solution cost type. Solution cost only makes sense if the LP has been solved to optimal value.\nusing IRSolutionCost = boost::optional<double>;\n/// Iterative Rounding result type: Pair consisting of LP problem type and IR\n/// solution cost.\nusing IRResult = std::pair<lp::problem_type, IRSolutionCost>;\n\n/**\n * @brief Solves an Iterative Rounding problem.\n *\n * @tparam Problem\n * @tparam IRcomponents\n * @tparam Visitor\n * @tparam LP\n * @param problem IR problem\n * @param components IR problem components\n * @param visitor visitor object used for logging progress of the algoithm\n */\ntemplate <typename Problem, typename IRcomponents, typename Visitor = trivial_visitor, typename LP = lp::glp>\nIRResult solve_iterative_rounding(Problem & problem, IRcomponents components, Visitor visitor = Visitor()) {\n    detail::iterative_rounding<Problem, IRcomponents, Visitor, LP> ir(problem, std::move(components), std::move(visitor));\n\n    auto prob_type = ir.solve_lp();\n    if (prob_type != lp::OPTIMAL) {\n        return IRResult(prob_type, IRSolutionCost{});\n    }\n\n    while (!ir.stop_condition()) {\n        bool rounded{ ir.round() };\n        bool relaxed{ ir.relax() };\n        assert(rounded || relaxed);\n\n        prob_type = ir.resolve_lp();\n        if (prob_type != lp::OPTIMAL) {\n            return IRResult(prob_type, IRSolutionCost{});\n        }\n    }\n    ir.set_solution();\n    return IRResult(lp::OPTIMAL, IRSolutionCost(ir.get_solution_cost()));\n}\n\n/**\n * @brief Solves an Iterative Rounding problem with dependent rounding.\n *\n * @tparam Problem\n * @tparam IRcomponents\n * @tparam Visitor\n * @tparam LP\n * @param problem IR problem\n * @param components IR problem components\n * @param visitor visitor object used for logging progress of the algoithm\n */\ntemplate <typename Problem, typename IRcomponents, typename Visitor = trivial_visitor, typename LP = lp::glp>\nIRResult solve_dependent_iterative_rounding(Problem & problem, IRcomponents components, Visitor visitor = Visitor()) {\n    detail::iterative_rounding<Problem, IRcomponents, Visitor, LP> ir(problem, std::move(components), std::move(visitor));\n\n    auto prob_type = ir.solve_lp();\n    if (prob_type != lp::OPTIMAL) {\n        return IRResult(prob_type, IRSolutionCost{});\n    }\n\n    while (!ir.stop_condition()) {\n        ir.dependent_round();\n        ir.relax();\n\n        prob_type = ir.resolve_lp();\n        if (prob_type != lp::OPTIMAL) {\n            return IRResult(prob_type, IRSolutionCost{});\n        }\n    }\n    ir.set_solution();\n    return IRResult(lp::OPTIMAL, IRSolutionCost(ir.get_solution_cost()));\n}\n\n} // ir\n} // paal\n\n#endif // PAAL_ITERATIVE_ROUNDING_HPP\n", "meta": {"hexsha": "48b5d96702b3d8990bc80abbac4688b78d0b8293", "size": 10931, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/iterative_rounding/iterative_rounding.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/iterative_rounding/iterative_rounding.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/iterative_rounding/iterative_rounding.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": 29.7847411444, "max_line_length": 122, "alphanum_fraction": 0.6100997164, "num_tokens": 2578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2752004492301763}}
{"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_MUL_IEXP_OUTER_HPP\n#define AMA_TENSOR_MUL_IEXP_OUTER_HPP 1\n\n#include <ama/tensor/iexp/index_reorder.hpp>\n#include <ama/tensor/iexp/iexp_base.hpp>\n#include <ama/tensor/mul/mul_calculator.hpp>\n#include <boost/mpl/bool.hpp>\n#include <boost/mpl/plus.hpp>\n\nnamespace ama\n{\n  namespace tensor_\n  {\n\n    /* forward declaration*/\n    template <typename LEFT, typename RIGHT> class mul_outer;\n\n\n    /* traits definition */\n    template <typename LEFT, typename RIGHT>\n    struct iexp_traits< mul_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 mul_index<LEFT, RIGHT>::controvariant_list controvariant_list;\n      typedef typename mul_index<LEFT, RIGHT>::covariant_list covariant_list;\n\n      typedef ::boost::mpl::false_ is_assignable;\n    };\n\n\n    /* class declaration */\n    template <typename LEFT, typename RIGHT>\n    class mul_outer:\n        public iexp_base< mul_outer<LEFT, RIGHT> >\n    {\n    protected:\n      typedef iexp_base< mul_outer<LEFT, RIGHT> > base_type;\n      typedef mul_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      mul_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 IMAP>\n      value_type at() const\n      {\n        return (m_left.template at<IMAP>()) * (m_right.template at<IMAP>());\n      }\n\n    protected:\n      /* members */\n      left_operand_type const m_left;\n      right_operand_type const m_right;\n    };\n\n  }\n}\n\n#endif /* AMA_TENSOR_MUL_IEXP_OUTER_HPP */\n", "meta": {"hexsha": "ef9a766edddc536f3db90db0d42e0e557b0af8e9", "size": 3505, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ama/tensor/mul/mul_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/mul/mul_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/mul/mul_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": 34.0291262136, "max_line_length": 85, "alphanum_fraction": 0.7124108417, "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2750693762907397}}
{"text": "/** @file INPUTS/parallelInputs.cpp\n *  @brief Translates the input file into a structure that can be used by parallelFDTDField\n *\n *  Takes in a boost property tree and converts that information into a structure used by parallelFDTDField\n *\n *  @author Thomas A. Purcell (tpurcell90)\n *  @author Joshua E. Szekely (jeszekely)\n *  @bug No known bugs.\n */\n\n#ifndef PRALLEL_FDTD_INPUTS\n#define PRALLEL_FDTD_INPUTS\n\n#include <src/OBJECTS/Obj.hpp>\n#include <src/UTIL/ml_consts.hpp>\n#include <src/UTIL/dielectric_params.hpp>\n#include <src/UTIL/utilityFxns.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n#include <UTIL/ML_Dist_Fxn.hpp>\n#include <iterator>\n\nstruct EnergyLevelDiscriptor\n{\n    DISTRIBUTION EDist_; //!< Distribution type for the energy level\n    int nstates_; //!< number of states in the level\n    int levDescribed_; //!< how many levels are described by this distribution\n    std::vector<double> energyStates_; //!< energy of all the states in the level\n    std::vector<double> weights_; //!< weights for the levels\n};\n\n/**\n * @brief input parameters class for the parallel FDTD class\n * @details sores all the values necessary to convert the input files into a fdtd grid\n */\nclass parallelProgramInputs\n{\npublic:\n    bool periodic_; //!< if true use PBC\n    POLARIZATION pol_; //!< polarization of the grid (EX, EY, HZ = TE; HX, HY, EZ = TM)\n\n    std::string filename_; //!< filename of the input file\n    int res_; //!< number of grid points per unit length\n\n    double courant_; //!< Courant factor of the cell\n    double a_; //!< the unit length of the calculations\n    double tMax_; //!< the max time of the calculation\n    double I0_; //!< the unit current of the cell\n\n    bool cplxFields_; //!< if true use complex fields\n    bool saveFreqField_; //!< if true save the flux fields\n\n    std::array<int,3> pmlThickness_; //!< thickness of the PMLs in all directions\n    std::array<double,3> k_point_; //!< k_point vector of the light\n    std::array<double,3> size_; //!< size of the cell in units of the unit length\n    std::array<double,3> d_; //!< size of the cell in units of the unit length\n\n    double dt_; //!< time step of the algorithm\n    double pmlSigOptRat_; //!< Ratio of SigMax to SigOpt\n    double pmlKappaMax_; //!< max a value for CPML\n    double pmlAMax_; //!< max a value for CPML\n    double pmlMa_; //!< scaling factor of a for the CPML\n    double pmlM_; //!< scaling factor for the CPML\n\n    std::vector<double> inputMapSlicesX_; //!< list of slices in the YZ plane\n    std::vector<double> inputMapSlicesY_; //!< list of slices in the XZ plane\n    std::vector<double> inputMapSlicesZ_; //!< list of slices in the XY plane\n\n    std::vector<POLARIZATION> srcPol_; //!<polarization of all sources\n    std::vector<std::vector<std::vector<cplx>>> srcFxn_; //!< pulse function parameters for the sources\n    std::vector<std::array<int,3>> srcLoc_; //!<location of all sources\n    std::vector<std::array<int,3>> srcSz_; //!<sizes of all all sources\n    std::vector<double> srcPhi_; //!< angle of incidence for the source detector\n    std::vector<double> srcTheta_; //!< angle of incidence for the source detector\n    std::vector<std::vector<PLSSHAPE>> srcPulShape_; //!< pulse shape of all sources\n    std::vector<std::vector<double>> srcEmax_; //!< max E incd field of all sources\n    std::vector<double> srcEllipticalKratio_; //!< ratio between the long and short axis for current source surfaces\n    std::vector<double> srcPsi_; //!< angle of polarization for circular and elliptical light\n\n    std::vector<std::array<int,3>> tfsfLoc_;//!< location of the tfsf lower left point\n    std::vector<std::array<int,3>> tfsfSize_; //!< size of the TFSF region\n    std::vector<std::array<int,3>> tfsfM_; //!< vector describing the m value for tfsf surfaces\n    std::vector<double> tfsfTheta_; //!< Phi angle of the TFSF surface\n    std::vector<double> tfsfPhi_; //!< Phi angle of the TFSF surface\n    std::vector<double> tfsfPsi_; //!< Phi angle of the TFSF surface\n    std::vector<std::vector<std::vector<cplx>>> tfsfPulFxn_; //!< pulse function parameters for the sources\n    std::vector<std::vector<PLSSHAPE>> tfsfPulShape_; //!< pulse shape of all sources\n    std::vector<std::vector<double>> tfsfEmax_; //!< max E incd field of all sources\n    std::vector<POLARIZATION> tfsfCircPol_; //!< sets the TFSF surface to be L or R polarized\n    std::vector<double> tfsfEllipticalKratio_; //!< ratio between the long and short axis for TFSF surfaces\n    std::vector<int> tfsfPMLThick_; //!< thickness of the incd PML's in number of grid points\n    std::vector<double> tfsfPMLAMax_; //!< max a value for CPML\n    std::vector<double> tfsfPMLM_; //!< scaling factor for the CPML\n    std::vector<double> tfsfPMLMa_; //!< scaling factor of a for the CPML\n\n    std::vector<std::shared_ptr<Obj>> objArr_; //!< array of all objects in the grid\n\n    std::vector<std::vector<std::array<int,2>>> qeBasis_; //!< vector describing the basis functions for each state\n    std::vector<EnergyLevelDiscriptor> qeELevs_; //!< vector storing the level descriptor for each level\n    std::vector<std::vector<double>> qeCouplings_; //!< dipole coupling matrix for all systems\n    std::vector<std::vector<std::array<int,3>>> qeLoc_; //!< location of all QE points\n    std::vector<std::vector<std::vector<double>>> qeGam_; //!< relaxation matrix for all QEs\n    std::vector<double> qeDen_; //!< molecular density of all QEs\n    std::vector<std::vector<std::array<int,2>>> qeRelaxTransitonStates_; //!< Transitions for Lindblad Operator\n    std::vector<std::vector<double>> qeRelaxRates_; //!< Rate of relaxation for Linblad operators\n    std::vector<std::vector<double>> qeRelaxDephasingRate_; //!< Rate of dephasing between both states\n    std::vector<bool> qeAccumP_; //!< bool to determine if output Polarization vector at every time\n    std::vector<std::string> qeOutPolFname_; //!< filename for output\n    std::vector<int> qeDtcPopTimeInt_; //!< Time interval for level dtc\n    std::vector<std::vector<int>> qePopDtcLevs_; //!< vector storing the levels outputted at each step\n    std::vector<std::vector<std::string>> qeDtcPopOutFile_; //!< filename for the pop output\n\n    std::vector<int> qeContinuumStates_; //!< vector containing all of the Continuum states\n    std::vector<double> qeContinuumNa_; //!< vector containing all of the Continuum band gap energy\n    std::vector<double> qeContinuumOmgGap_; //!< vector containing all of the Continuum band gap energy\n    std::vector<double> qeContinuum_dOmg_; //!< vector containing all of the Continuum inter-continuum state energy separation\n    std::vector<double> qeContinuumMu_; //!< vector containing all of the Continuum transition dipole moments\n    std::vector<double> qeContinuumGam1_; //!< vector containing all of the Continuum relaxation to the ground state (rationalness)\n    std::vector<double> qeContinuumGamk_; //!< vector containing all of the Continuum relaxation to the conduction band edge (raditionless)\n    std::vector<double> qeContinuumGamP_; //!< vector containing all of the Continuum relaxation to the conduction band edge (raditionless)\n    std::vector<std::vector<std::array<int,2>>> qeContinuumLocs_; //!< vector containing all of the Continuum locations\n\n    std::vector<DTCCLASS> dtcClass_; //!< describer of output file type for all detectors\n    std::vector<bool> dtcSI_; //!< if true use SI units\n    std::vector<std::array<int,3>> dtcLoc_; //!< location of all detectors\n    std::vector<std::array<int,3>> dtcSz_; //!< sizes of all detectors\n    std::vector<std::string> dtcName_; //!< file name for all detectors\n    std::vector<DTCTYPE> dtcType_; //!< whether the dtc stores the Ex, Ey, Ez, Hx, Hy, Hz fields or the H or E power\n    std::vector<double> dtcTimeInt_; //!< time interval for all detectors\n    std::vector<GRIDOUTFXN> dtcOutBMPFxnType_; //!< what function should bmp converter use\n    std::vector<GRIDOUTTYPE> dtcOutBMPOutType_; //!< how to output the values for the detector ina text file\n    std::vector<std::vector<double>> dtcFreqList_; //!< center frequency\n    std::vector<double> dtcTStart_; //!< time to start collecting fields\n    std::vector<double> dtcTEnd_; //!< time to end collecting fields\n    std::vector<bool> dtcOutputAvg_; //!< True if only outputting time_integrated fields\n    std::vector<bool> dtcOutputMaps_; //!< True if only outputting time_integrated fields\n\n    std::vector<int> fluxXOff_; //!< the x location offset of the fields\n    std::vector<int> fluxYOff_; //!< the y location offset of the fields\n    std::vector<int> fluxTimeInt_; //!< time interval used to intake the fields\n    std::vector<std::array<int,3>> fluxLoc_; //!< Location of the lower left corner of the flux surface\n    std::vector<std::array<int,3>> fluxSz_; //!< size of the flux surface\n    std::vector<double> fluxWeight_; //!< weight of the flux surface\n    std::vector<std::string> fluxName_; //!< file name for the output file\n    std::vector<std::vector<double>> fluxFreqList_; //!<  center frequency\n    std::vector<bool> fluxSI_; //!<  use SI units\n    std::vector<bool> fluxCrossSec_; //!< calculate the cross-section?\n    std::vector<bool> fluxSave_; //!< save the fields?\n    std::vector<bool> fluxLoad_; //!< load the fields?\n    std::vector<std::string> fluxIncdFieldsFilename_; //!< incident file names\n\n    /**\n     * @brief      Constructs the input parameter object\n     *\n     * @param[in]  IP    boost property tree generated from the input json file\n     * @param[in]  fn    The filename of the input file\n     */\n    parallelProgramInputs(boost::property_tree::ptree IP,std::string fn);\n\n    /**\n     * @brief      Gets the dielectric parameters for a material.\n     *\n     * @param[in]  mat   String identifier of the material\n     *\n     * @return     The dielectric parameters.\n     */\n    std::vector<double> getDielectricParams(std::string mat);\n\n    /**\n     * @brief      converts a string to GRIDOUTFXN\n     *\n     * @param[in]  f     String identifier to a GRIDOUTFXN\n     *\n     * @return     GRIDOUTFXN from that input string\n     */\n    GRIDOUTFXN string2GRIDOUTFXN (std::string f);\n\n    /**\n     * @brief      converts a string to GRIDOUTTYPE\n     *\n     * @param[in]  t     String identifier to a GRIDOUTTYPE\n     *\n     * @return     GRIDOUTTYPE from that input string\n     */\n    GRIDOUTTYPE string2GRIDOUTTYPE (std::string t);\n\n    /**\n     * @brief      converts a string to POLARIZATION\n     *\n     * @param[in]  p     String identifier to a POLARIZATION\n     *\n     * @return     POLARIZATION from that input string\n     */\n    POLARIZATION string2pol(std::string p);\n\n    /**\n     * @brief      converts a string to SHAPE\n     *\n     * @param[in]  s     String identifier to a SHAPE\n     *\n     * @return     SHAPE from that input string\n     */\n    SHAPE string2shape(std::string s);\n\n    /**\n     * @brief      converts a string to DTCTYPE\n     *\n     * @param[in]  t     String identifier to a DTCTYPE\n     *\n     * @return     DTCTYPE from that input string\n     */\n    DTCTYPE string2out(std::string t);\n\n    /**\n     * @brief      converts a string to DTCCLASS\n     *\n     * @param[in]  c     String identifier to a DTCCLASS\n     *\n     * @return     DTCCLASS from that input string\n     */\n    DTCCLASS string2dtcclass(std::string c);\n\n    /**\n     * @brief      converts a string to PLSSHAPE\n     *\n     * @param[in]  p     String identifier to a PLSSHAPE\n     *\n     * @return     PLSSHAPE from that input string\n     */\n    PLSSHAPE string2prof(std::string p);\n\n    /**\n     * @brief      converts a string to DIRECTION\n     *\n     * @param[in]  dir   String identifier to a DIRECTION\n     *\n     * @return     DIRECTION from that input string\n     */\n    DIRECTION string2dir(std::string dir);\n\n    /**\n     * @brief      converts a string to DISTRIBUTION\n     *\n     * @param[in]  f     String identifier to a DISTRIBUTION\n     *\n     * @return     DISTRIBUTION from that input string\n     */\n    DISTRIBUTION string2dist(std::string dist);\n\n    /**\n     * @brief      Converts a string to MAT_DIP_ORIENTAITON\n     *\n     * @param[in]  dipOr  String identifier for the MAT_DIP_ORIENTAITON\n     *\n     * @return     The MAT_DIP_ORIENTAITON from the input string\n     */\n    MAT_DIP_ORIENTAITON string2dipor(std::string dipOr);\n\n    /**\n     * @brief      Gets the material parameters for a given material\n     *\n     * @param[in]  mat   String identifying the material\n     *\n     * @return     The material parameters\n     */\n    std::tuple<double,double,double, std::vector<LorenzDipoleOscillator> > getMater(std::string mat);\n\n    /**\n     * @brief      Converts the metal parameters from eV based units to FDTD based units\n     *\n     * @param[in]  params  The parameters for the metallic material in eV\n     *\n     * @return     The parameters for the metallic material in FDTD units\n     */\n    std::vector<LorenzDipoleOscillator> getMetal(std::vector<double> params);\n\n    std::vector<LorenzDipoleOscillator> getMetalJM(std::vector<double> params);\n\n    /**\n     * @brief      Converts eV units to FDTD units\n     *\n     * @param[in]  eV    The value in eV\n     *\n     * @return     The value in FDTD frequency units\n     */\n    double ev2FDTD(double eV);\n\n    /**\n     * @brief      Converts the point from real space to grid points\n     *\n     * @param[in]  pt    Real space value\n     *\n     * @return     Corresponding grid point value\n     */\n    inline int find_pt(double pt, double d) {return int( floor(pt/d + 0.5) );}\n\n    /**\n     * @brief      Accessor function to tMax_\n     *\n     * @return     Maximum time of the simulation\n     */\n    inline double tMax() {return tMax_;}\n\n    /**\n     * @brief      Constructs an object from the object list child tree\n     *\n     * @param      iter  boost::ptree child corresponding to the object\n     *\n     * @return     shared_ptr to the object\n     */\n    std::shared_ptr<Obj> ptreeToObject(boost::property_tree::ptree::value_type &iter);\n};\n/**\n * @brief      strips comments from the input file\n *\n * @param      filename  The filename of the file to strip\n */\nvoid stripComments(std::string& filename);\n\n\n/**\n * @brief      boost json to std::vector<T>\n *\n * @param[in]  pt          property tree\n * @param[in]  key         property tree key\n *\n * @tparam     T           double, int\n *\n * @return     json input as a std::vector<T>\n */\ntemplate <typename T>\nstd::vector<T> as_vector(boost::property_tree::ptree const &pt, boost::property_tree::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/**\n * @brief      boost json to std::vector<T>\n *\n * @param[in]  pt          property tree\n * @param[in]  key         property tree key\n * @param[in]  defaultVal  The default value\n * @param[in]  szVec       The size of the vector\n *\n * @tparam     T           double, int\n *\n * @return     json input as a std::vector<T>\n */\ntemplate <typename T>\nstd::vector<T> as_vector(boost::property_tree::ptree const &pt, boost::property_tree::ptree::key_type const &key, T defaultVal, int szVec)\n{\n    std::vector<T> r;\n    try\n    {\n        for (auto& item : pt.get_child(key))\n            r.push_back(item.second.get_value<T>());\n    }\n    catch(std::exception& e)\n    {\n        r = std::vector<T>(szVec, defaultVal);\n    }\n    return r;\n}\n\n\n/**\n * @brief      boost json to std::array<T,3>\n *\n * @param[in]  pt          property tree\n * @param[in]  key         property tree key\n * @param[in]  defaultVal  The default value\n *\n * @tparam     T           double, int\n *\n * @return     json input as a std::array<T,3>\n */\ntemplate <typename T>\nstd::array<T,3> as_ptArr(boost::property_tree::ptree const &pt, boost::property_tree::ptree::key_type const &key, T defaultVal=0)\n{\n    std::array<T, 3> r = {0,0,0};\n    try\n    {\n        int ii = 0;\n        for (auto& item : pt.get_child(key))\n        {\n            r[ii] = item.second.get_value<T>();\n            ++ii;\n        }\n    }\n    catch(std::exception& e)\n    {\n        r = {{ defaultVal, defaultVal, defaultVal}};\n    }\n    return r;\n}\n\n/**\n * @brief      boost json to std::array<T,3>\n *\n * @param[in]  pt          property tree\n * @param[in]  key         property tree key\n * @param[in]  defaultVal  The default value\n *\n * @tparam     T           double, int\n *\n * @return     json input as a std::array<T,3>\n */\ntemplate <typename T>\nstd::array<T,2> as_ptArr2(boost::property_tree::ptree const &pt, boost::property_tree::ptree::key_type const &key, T defaultVal=0)\n{\n    std::array<T, 2> r = {0,0};\n    try\n    {\n        int ii = 0;\n        for (auto& item : pt.get_child(key))\n        {\n            r[ii] = item.second.get_value<T>();\n            ++ii;\n        }\n    }\n    catch(std::exception& e)\n    {\n        r = {{ defaultVal, defaultVal}};\n    }\n    return r;\n}\n#endif", "meta": {"hexsha": "09fab8b293d552bebb5be779d5685014b4624724", "size": 16931, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/INPUTS/parallelInputs.hpp", "max_stars_repo_name": "Seideman-Group/chiML", "max_stars_repo_head_hexsha": "9ace5dccdbc6c173e8383f6a31ff421b4fefffdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-27T05:25:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-27T05:25:27.000Z", "max_issues_repo_path": "src/INPUTS/parallelInputs.hpp", "max_issues_repo_name": "Seideman-Group/chiML", "max_issues_repo_head_hexsha": "9ace5dccdbc6c173e8383f6a31ff421b4fefffdf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/INPUTS/parallelInputs.hpp", "max_forks_repo_name": "Seideman-Group/chiML", "max_forks_repo_head_hexsha": "9ace5dccdbc6c173e8383f6a31ff421b4fefffdf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-03T10:08:21.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-30T22:40:28.000Z", "avg_line_length": 39.283062645, "max_line_length": 139, "alphanum_fraction": 0.6527671136, "num_tokens": 4511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2750693762907397}}
{"text": "#include <iostream>\n\n#include <El.hpp>\n#include <boost/mpi.hpp>\n#include <boost/format.hpp>\n\n// Some tricks to make compilation faster\n#define SKYLARK_NO_ANY\n#define SKYLARK_WITH_JLT_ANY\n#define SKYLARK_WITH_UST_ANY\n#define SKYLARK_WITH_GAUSSIAN_RFT_ANY\n#define SKYLARK_WITH_LAPLACIAN_RFT_ANY\n#define SKYLARK_WITH_PPT_ANY\n#define SKYLARK_WITH_FAST_GAUSSIAN_RFT_ANY\n\n#include <skylark.hpp>\n\n\n// Algorithms constants\n#define CLASSIC_KRR                      0\n#define FASTER_KRR                       1\n#define APPROXIMATE_KRR                  2\n#define SKETCHED_APPROXIMATE_KRR         3\n#define FAST_SKETCHED_APPROXIMATE_KRR    4\n#define LARGE_SCALE_KRR                  5\n#define EXPERIMENTAL_1                 100\n#define EXPERIMENTAL_2                 101\n\n// Kernels constants\n#define GAUSSIAN_KERNEL   0\n#define LAPLACIAN_KERNEL  1\n#define POLYNOMIAL_KERNEL 2\n#define LINEAR_KERNEL   100\n\nstd::string cmdline;\nint seed = 38734, algorithm = FASTER_KRR, kernel_type = GAUSSIAN_KERNEL;\nskylark::utility::io::fileformat_t fileformat =\n    skylark::utility::io::FORMAT_LIBSVM;\nint s = 2000, partial = -1, sketch_size = -1, sample = -1, maxit = 0, maxsplit = 0;\nstd::string fname, testname, modelname = \"model.dat\", logfile = \"\",\n    outputfile = \"\";\ndouble kp1 = 10.0, kp2 = 0.0, kp3 = 1.0, lambda = 0.01, tolerance=0;\nbool use_single = false, use_fast = false, regression = false;\nbool predict = false, decisionvals = false;\nboost::property_tree::ptree pt;\n\n#ifndef SKYLARK_AVOID_BOOST_PO\n\n#include <boost/program_options.hpp>\nnamespace bpo = boost::program_options;\n\nint parse_program_options(int argc, char* argv[]) {\n\n    bpo::options_description desc(\"Options\");\n    desc.add_options()\n        (\"help,h\", \"produce a help message\")\n        (\"trainfile\",\n            bpo::value<std::string>(&fname)->default_value(\"\"),\n            \"Data to train on. For predict - data to predict on. \")\n        (\"testfile\",\n            bpo::value<std::string>(&testname)->default_value(\"\"),\n            \"Test data (libsvm format).\")\n        (\"outputfile\",\n            bpo::value<std::string>(&outputfile)->default_value(\"\"),\n            \"Output file (for predicition). Will not output if empty.\")\n        (\"predict\", \"Predict mode -- load model file and use it.\")\n        (\"model\",\n            bpo::value<std::string>(&modelname)->default_value(\"model.dat\"),\n            \"Name of model file.\")\n        (\"logfile\",\n            bpo::value<std::string>(&logfile)->default_value(\"\"),\n            \"File to write log (standard output if empty).\")\n        (\"kernel,k\",\n             bpo::value<int>(&kernel_type)->default_value(GAUSSIAN_KERNEL),\n            \"Kernel to use (0: Gaussian, 1: Laplacian, 2: Polynomial).\")\n        (\"algorithm,a\",\n             bpo::value<int>(&algorithm)->default_value(FASTER_KRR),\n            \"Algorithm to use (0: Classic, 1: Faster (Precond), \"\n            \"2: Approximate (Random Features)), \"\n            \"3: Sketched Approximate (Piecemeal Random Features + Sketch)), \"\n            \"4: Sketched Approximate w/ Faster Sketching, \"\n            \"5: Large Scale. OPTIONAL.\")\n        (\"seed,s\",\n            bpo::value<int>(&seed)->default_value(38734),\n            \"Seed for random number generation. OPTIONAL.\")\n        (\"kernelparam,g\",\n            bpo::value<double>(&kp1),\n            \"Kernel parameter. REQUIRED.\")\n        (\"kernelparam2,x\",\n            bpo::value<double>(&kp2)->default_value(0.0),\n            \"If Applicable - Second Kernel Parameter (Polynomial Kernel: c).\")\n        (\"kernelparam3,y\",\n            bpo::value<double>(&kp3)->default_value(1.0),\n            \"If Applicable - Third Kernel Parameter (Polynomial Kernel: gamma).\")\n        (\"lambda,l\",\n            bpo::value<double>(&lambda)->default_value(0.01),\n            \"Lambda regularization parameter.\")\n        (\"tolerance,t\",\n            bpo::value<double>(&tolerance)->default_value(0),\n            \"Tolerance for the iterative method (when used). \"\n            \"0 will default based on algorithm (1e-3 for -a 1, 1e-1 for -a 5)\")\n        (\"maxsplit,c\",\n            bpo::value<int>(&maxsplit)->default_value(0),\n            \"Maximum number of random features in a split for large scale \"\n            \"algorithms (-a 3 to 5). 0 will default to 2 * input dimension. \")\n        (\"maxit,i\",\n            bpo::value<int>(&maxit)->default_value(0),\n            \"Maximum number of iterations for the iterative method (when used). \"\n            \"0 will default based on algorithm (1000 for -a 1, 20 for -a 5)\")\n        (\"partial,p\",\n            bpo::value<int>(&partial)->default_value(-1),\n            \"Load only specified quantity examples from training. \"\n            \"Will read all if -1.\")\n        (\"sample,z\",\n            bpo::value<int>(&sample)->default_value(-1),\n            \"Sample the input data. Will use all if -1. \")\n        (\"decisionvals\",\n            \"In predict mode, for classification, output the \"\n            \"decision values instead of class.\")\n        (\"single\", \"Whether to use single precision instead of double.\")\n        (\"fast\", \"Try using a fast feature transform.\")\n        (\"regression\", \"Build a regression model\"\n            \"(default is classification).\")\n        (\"numfeatures,f\",\n            bpo::value<int>(&s),\n            \"Number of random features (if relevant).\")\n        (\"sketchsize,r\",\n            bpo::value<int>(&sketch_size)->default_value(-1),\n            \"Sketch size (for regression problem; if relevant (i.e., -a 3). \"\n            \"-1 - will be determined by software. \")\n        (\"fileformat\",\n            po::value<char>((char *)&fileformat)->\n            default_value(skylark::utility::io::FORMAT_LIBSVM),\n            \"Fileformat (default: 0 (libsvm), 1 (hdf5)\");\n\n    bpo::positional_options_description positional;\n    positional.add(\"trainfile\", 1);\n    positional.add(\"testfile\", 2);\n\n    bpo::variables_map vm;\n    try {\n        bpo::store(bpo::command_line_parser(argc, argv)\n            .options(desc).positional(positional).run(), vm);\n\n        if (vm.count(\"help\")) {\n            std::cout << \"Usage: \" << argv[0]\n                      << \" [options] input-file-name [test-file-name]\"\n                      << std::endl;\n            std::cout << desc;\n            return 0;\n        }\n\n        bpo::notify(vm);\n\n        use_single = vm.count(\"single\");\n        use_fast = vm.count(\"fast\");\n        regression = vm.count(\"regression\");\n        predict = vm.count(\"predict\");\n        decisionvals = vm.count(\"decisionvals\");\n\n        if (!vm.count(\"trainfile\")) {\n            std::cout << \"Input trainfile file is required! \"\n                      << \"(In predict mode, it is the test data.)\"\n                      << std::endl;\n            return -1;\n        }\n\n    } catch(bpo::error& e) {\n        std::cerr << e.what() << std::endl;\n        std::cerr << desc << std::endl;\n        return -1;\n    }\n\n    return 1000;\n}\n\n\n#else\n\nint parse_program_options(int argc, char* argv[]) {\n\n    int poscount = 0;\n    for (int i = 1; i < argc; i += 2) {\n        std::string flag = argv[i];\n        std::string value = i + 1 < argc ? argv[i+1] : \"\";\n\n        if (flag == \"--seed\" || flag == \"-s\")\n            seed = boost::lexical_cast<int>(value);\n\n        if (flag == \"--lambda\" || flag == \"-l\")\n            lambda = boost::lexical_cast<double>(value);\n\n        if (flag == \"--tolerance\" || flag == \"-t\")\n            tolerance = boost::lexical_cast<double>(value);\n\n        if (flag == \"--maxit\" || flag == \"-i\")\n            maxit = boost::lexical_cast<int>(value);\n\n        if (flag == \"--maxsplit\" || flag == \"-c\")\n            maxsplit = boost::lexical_cast<int>(value);\n\n        if (flag == \"--partial\" || flag == \"-p\")\n            partial = boost::lexical_cast<int>(value);\n\n        if (flag == \"--sample\" || flag == \"-z\")\n            sample = boost::lexical_cast<int>(value);\n\n        if (flag == \"--kernelparam\" || flag == \"-g\")\n            kp1 = boost::lexical_cast<double>(value);\n\n        if (flag == \"--kernelparam2\" || flag == \"-x\")\n            kp2 = boost::lexical_cast<double>(value);\n\n        if (flag == \"--kernelparam3\" || flag == \"-y\")\n            kp3 = boost::lexical_cast<double>(value);\n\n        if (flag == \"--kernel\" || flag == \"-k\")\n            kernel_type = boost::lexical_cast<int>(value);\n\n        if (flag == \"--algorithm\" || flag == \"-a\")\n            algorithm = boost::lexical_cast<int>(value);\n\n        if (flag == \"--fileformat\")\n            fileformat = boost::lexical_cast<int>(value);\n\n        if (flag == \"--nunmfeatures\" || flag == \"-f\")\n            s = boost::lexical_cast<int>(value);\n\n        if (flag == \"--sketchsize\" || flag == \"-r\")\n            sketch_size = boost::lexical_cast<int>(value);\n\n        if (flag == \"--single\") {\n            use_single = true;\n            i--;\n        }\n\n        if (flag == \"--decisionvals\") {\n            decisionvals = true;\n            i--;\n        }\n\n        if (flag == \"--regression\") {\n            regression = true;\n            i--;\n        }\n\n        if (flag == \"--predict\") {\n            predict = true;\n            i--;\n        }\n\n        if (flag == \"--fast\") {\n            use_fast = true;\n            i--;\n        }\n\n        if (flag == \"--trainfile\")\n            fname = value;\n\n        if (flag == \"--logfile\")\n            logfile = value;\n\n        if (flag == \"--model\")\n            modelname = value;\n\n        if (flag == \"--testfile\")\n            testname = value;\n\n        if (flag == \"--outputfile\")\n            outputfile = value;\n\n        if (flag[0] != '-' && poscount != 0)\n            testname = flag;\n\n        if (flag[0] != '-' && poscount == 0) {\n            fname = flag;\n            poscount++;\n        }\n\n        if (flag[0] != '-')\n            i--;\n    }\n\n    return 1000;\n}\n\n#endif\n\ntemplate<typename T>\nint execute_classification(skylark::base::context_t &context) {\n\n    boost::mpi::communicator world;\n    int rank = world.rank();\n\n    std::ostream *log_stream = &std::cout;\n    if (rank == 0 && logfile != \"\") {\n        log_stream = new std::ofstream();\n        ((std::ofstream *)log_stream)->open(logfile);\n    }\n\n    El::DistMatrix<T> X0, X;\n    El::DistMatrix<El::Int> L0, L;\n\n    boost::mpi::timer timer;\n\n    if (rank == 0) {\n        *log_stream << \"# Generated using kernel_regression \";\n        *log_stream << \"using the following command-line: \" << std::endl;\n        *log_stream << \"#\\t\" << cmdline << std::endl;\n        *log_stream << \"# Number of ranks is \" << world.size() << std::endl;\n    }\n\n    // Load X and L\n    if (rank == 0) {\n        *log_stream << \"Reading the matrix... \";\n        log_stream->flush();\n        timer.restart();\n    }\n\n    switch (fileformat) {\n    case skylark::utility::io::FORMAT_LIBSVM:\n        skylark::utility::io::ReadLIBSVM(fname, X0, L0, skylark::base::COLUMNS,\n            0, partial);\n        break;\n\n#ifdef SKYLARK_HAVE_HDF5\n    case skylark::utility::io::FORMAT_HDF5: {\n        H5::H5File in(fname, H5F_ACC_RDONLY);\n        skylark::utility::io::ReadHDF5(in, \"X\", X0, -1, partial);\n        skylark::utility::io::ReadHDF5(in, \"Y\", L0, -1, partial);\n        in.close();\n    }\n        break;\n#endif\n\n    default:\n        *log_stream << \"Invalid file format specified.\" << std::endl;\n        return -1;\n    }\n\n    if (rank == 0)\n        *log_stream <<\"took \" << boost::format(\"%.2e\") % timer.elapsed()\n                  << \" sec\\n\";\n\n    skylark::sketch::generic_sketch_container_t SampT;\n    if (sample == -1) {\n\n        El::View(X, X0);\n        El::View(L, L0);\n\n    } else {\n        // Sample X and L\n        if (rank == 0) {\n            *log_stream << \"Sampling the data... \";\n            log_stream->flush();\n            timer.restart();\n        }\n\n        SampT =\n            skylark::sketch::create_sketch<skylark::sketch::UST_t>(X0.Width(),\n                sample, skylark::sketch::UST_data_t::params_t(false), context);\n\n        X.Resize(X0.Height(), sample);\n        SampT.apply(&X0, &X, skylark::sketch::rowwise_tag());\n\n        L.Resize(1, sample);\n        SampT.apply(&L0, &L, skylark::sketch::rowwise_tag());\n\n        if (rank == 0)\n            *log_stream <<\"took \" << boost::format(\"%.2e\") % timer.elapsed()\n                        << \" sec\\n\";\n    }\n\n    // Training\n    if (rank == 0) {\n        *log_stream << \"Training... \" << std::endl;\n        timer.restart();\n    }\n\n    std::shared_ptr<skylark::ml::kernel_t> k_ptr;\n\n    switch (kernel_type) {\n    case GAUSSIAN_KERNEL:\n        k_ptr.reset(new skylark::ml::gaussian_t(X.Height(), kp1));\n        break;\n\n    case LAPLACIAN_KERNEL:\n        k_ptr.reset(new skylark::ml::laplacian_t(X.Height(), kp1));\n        break;\n\n    case POLYNOMIAL_KERNEL:\n        k_ptr.reset(new skylark::ml::polynomial_t(X.Height(), kp1, kp2, kp3));\n        break;\n\n    case LINEAR_KERNEL:\n        k_ptr.reset(new skylark::ml::linear_t(X.Height()));\n        break;\n\n    default:\n        *log_stream << \"Invalid kernel specified.\" << std::endl;\n        return -1;\n    }\n\n    skylark::ml::kernel_container_t k(k_ptr);\n\n    El::DistMatrix<T> A, W;\n    std::vector<El::Int> rcoding;\n\n    skylark::sketch::sketch_transform_container_t<El::DistMatrix<T>,\n                                                  El::DistMatrix<T> >  S;\n    bool scale_maps = true;\n    std::vector<\n        skylark::sketch::sketch_transform_container_t<El::DistMatrix<T>,\n                                                      El::DistMatrix<T> > > transforms;\n\n    skylark::ml::rlsc_params_t rlsc_params(rank == 0, 4, *log_stream, \"\\t\");\n    rlsc_params.use_fast = use_fast;\n\n    skylark::ml::model_t<El::Int, T> *model;\n\n    switch(algorithm) {\n    case CLASSIC_KRR:\n        skylark::ml::KernelRLSC(skylark::base::COLUMNS, k, X, L,\n            T(lambda), A, rcoding, rlsc_params);\n        model =\n            new skylark::ml::kernel_model_t<skylark::ml::kernel_container_t,\n              El::Int, T>(k, skylark::base::COLUMNS, X, fname, partial, fileformat,\n                  SampT, A, rcoding);\n        break;\n\n    case FASTER_KRR:\n        rlsc_params.iter_lim = (maxit == 0) ? 1000 : maxit;\n        rlsc_params.tolerance = (tolerance == 0) ? 1e-3 : tolerance;\n        skylark::ml::FasterKernelRLSC(skylark::base::COLUMNS, k, X, L,\n            T(lambda), A, rcoding, s, context, rlsc_params);\n        model =\n            new skylark::ml::kernel_model_t<skylark::ml::kernel_container_t,\n              El::Int, T>(k, skylark::base::COLUMNS, X, fname, partial,  \n                  fileformat, SampT, A, rcoding);\n        break;\n\n    case APPROXIMATE_KRR:\n        skylark::ml::ApproximateKernelRLSC(skylark::base::COLUMNS, k, X, L,\n            T(lambda), S, W, rcoding, s, context, rlsc_params);\n        model =\n            new skylark::ml::feature_expansion_model_t<\n                skylark::sketch::sketch_transform_container_t, El::Int, T>\n            (S, W, rcoding);\n        break;\n\n    case SKETCHED_APPROXIMATE_KRR:\n    case FAST_SKETCHED_APPROXIMATE_KRR:\n        rlsc_params.sketched_rls = true;\n        rlsc_params.sketch_size = sketch_size;\n        rlsc_params.fast_sketch = algorithm == FAST_SKETCHED_APPROXIMATE_KRR;\n        rlsc_params.max_split = maxsplit;\n        skylark::ml::SketchedApproximateKernelRLSC(skylark::base::COLUMNS, k, X, L,\n            T(lambda), scale_maps, transforms, W, rcoding, s, sketch_size,\n            context, rlsc_params);\n        model =\n            new skylark::ml::feature_expansion_model_t<\n                skylark::sketch::sketch_transform_container_t, El::Int, T>\n            (scale_maps, transforms, W, rcoding);\n        break;\n\n    case LARGE_SCALE_KRR:\n        rlsc_params.iter_lim = (maxit == 0) ? 20 : maxit;\n        rlsc_params.tolerance = (tolerance == 0) ? 1e-1 : tolerance;\n        rlsc_params.max_split = maxsplit;\n        skylark::ml::LargeScaleKernelRLSC(skylark::base::COLUMNS, k, X, L,\n            T(lambda), scale_maps, transforms, W, rcoding, s,\n            context, rlsc_params);\n        model =\n            new skylark::ml::feature_expansion_model_t<\n                skylark::sketch::sketch_transform_container_t, El::Int, T>\n            (scale_maps, transforms, W, rcoding);\n        break;\n\n    case EXPERIMENTAL_1:\n    case EXPERIMENTAL_2:\n        rlsc_params.sketched_rls = true;\n        rlsc_params.fast_sketch = algorithm == EXPERIMENTAL_2;\n        skylark::ml::ApproximateKernelRLSC(skylark::base::COLUMNS, k, X, L,\n            T(lambda), S, W, rcoding, s, context, rlsc_params);\n        model =\n            new skylark::ml::feature_expansion_model_t<\n                skylark::sketch::sketch_transform_container_t, El::Int, T>\n            (S, W, rcoding);\n        break;\n\n    default:\n        *log_stream << \"Invalid algorithm value specified.\" << std::endl;\n        return -1;\n    }\n\n    if (rank == 0)\n        *log_stream << \"Training took \" << boost::format(\"%.2e\") % timer.elapsed()\n                  << \" sec\\n\";\n\n    if (modelname != \"NOSAVE\") {\n        // Save model\n        if (rank == 0) {\n            *log_stream << \"Saving model... \";\n            log_stream->flush();\n            timer.restart();\n        }\n\n        pt = model->to_ptree();\n\n        if (rank == 0) {\n            std::ofstream of(modelname);\n            of << \"# Generated using kernel_regression \";\n            of << \"using the following command-line: \" << std::endl;\n            of << \"#\\t\" << cmdline << std::endl;\n            of << \"# Number of ranks is \" << world.size() << std::endl;\n            boost::property_tree::write_json(of, pt);\n            of.close();\n        }\n\n        if (rank == 0)\n            *log_stream <<\"took \" << boost::format(\"%.2e\") % timer.elapsed()\n                        << \" sec\\n\";\n    }\n\n    // Test\n    if (!testname.empty()) {\n        if (rank == 0) {\n            *log_stream << \"Predicting... \";\n            log_stream->flush();\n            timer.restart();\n        }\n\n        El::DistMatrix<T> XT;\n        El::DistMatrix<El::Int> LT;\n\n        switch (fileformat) {\n        case skylark::utility::io::FORMAT_LIBSVM:\n            skylark::utility::io::ReadLIBSVM(testname, XT, LT,\n                skylark::base::COLUMNS, X.Height());\n            break;\n\n#ifdef SKYLARK_HAVE_HDF5\n        case skylark::utility::io::FORMAT_HDF5: {\n            H5::H5File in(testname, H5F_ACC_RDONLY);\n            skylark::utility::io::ReadHDF5(in, \"X\", XT);\n            skylark::utility::io::ReadHDF5(in, \"Y\", LT);\n            in.close();\n        }\n            break;\n#endif\n\n        default:\n            *log_stream << \"Invalid file format specified.\" << std::endl;\n            return -1;\n        }\n\n        El::DistMatrix<T> DV;\n        El::DistMatrix<El::Int> LP;\n        model->predict(skylark::base::COLUMNS, XT, LP, DV);\n\n        if (rank == 0)\n            *log_stream << \"took \" << boost::format(\"%.2e\") % timer.elapsed()\n                      << \" sec\\n\";\n\n        int errs = 0;\n        if (LT.LocalHeight() > 0)\n            for(int i = 0; i < LT.LocalWidth(); i++)\n                if (LT.GetLocal(0, i) != LP.GetLocal(0, i))\n                    errs++;\n\n        errs = El::mpi::AllReduce(errs, MPI_SUM, LT.DistComm());\n\n        if (rank == 0)\n            *log_stream << \"Error rate: \"\n                      << boost::format(\"%.2f\") % ((errs * 100.0) / LT.Width())\n                      << \"%\" << std::endl;\n    }\n\n    if (rank == 0 && logfile != \"\") {\n        ((std::ofstream *)log_stream)->close();\n        delete log_stream;\n    }\n\n    delete model;\n\n    return 0;\n}\n\ntemplate<typename T>\nint execute_regression(skylark::base::context_t &context) {\n\n    boost::mpi::communicator world;\n    int rank = world.rank();\n\n    std::ostream *log_stream = &std::cout;\n    if (rank == 0 && logfile != \"\") {\n        log_stream = new std::ofstream();\n        ((std::ofstream *)log_stream)->open(logfile);\n    }\n\n    El::DistMatrix<T> X0, X, Y0, Y;\n\n    boost::mpi::timer timer;\n\n    if (rank == 0) {\n        *log_stream << \"# Generated using kernel_regression \";\n        *log_stream << \"using the following command-line: \" << std::endl;\n        *log_stream << \"#\\t\" << cmdline << std::endl;\n        *log_stream << \"# Number of ranks is \" << world.size() << std::endl;\n    }\n\n    // Load X and Y\n    if (rank == 0) {\n        *log_stream << \"Reading the matrix... \";\n        log_stream->flush();\n        timer.restart();\n    }\n\n    switch (fileformat) {\n    case skylark::utility::io::FORMAT_LIBSVM:\n        skylark::utility::io::ReadLIBSVM(fname, X0, Y0, skylark::base::COLUMNS,\n            0, partial);\n        break;\n\n#ifdef SKYLARK_HAVE_HDF5\n    case skylark::utility::io::FORMAT_HDF5: {\n        H5::H5File in(fname, H5F_ACC_RDONLY);\n        skylark::utility::io::ReadHDF5(in, \"X\", X0, -1, partial);\n        skylark::utility::io::ReadHDF5(in, \"Y\", Y0, -1, partial);\n        in.close();\n    }\n        break;\n#endif\n\n    default:\n        *log_stream << \"Invalid file format specified.\" << std::endl;\n        return -1;\n    }\n\n    if (rank == 0)\n        *log_stream <<\"took \" << boost::format(\"%.2e\") % timer.elapsed()\n                  << \" sec\\n\";\n\n    skylark::sketch::generic_sketch_container_t SampT;\n    if (sample == -1) {\n\n        El::View(X, X0);\n        El::View(Y, Y0);\n\n    } else {\n        // Sample X and Y\n        if (rank == 0) {\n            *log_stream << \"Sampling the data... \";\n            log_stream->flush();\n            timer.restart();\n        }\n\n        SampT =\n            skylark::sketch::create_sketch<skylark::sketch::UST_t>(X0.Width(),\n                sample, skylark::sketch::UST_data_t::params_t(false), context);\n\n        X.Resize(X0.Height(), sample);\n        SampT.apply(&X0, &X, skylark::sketch::rowwise_tag());\n\n        Y.Resize(1, sample);\n        SampT.apply(&Y0, &Y, skylark::sketch::rowwise_tag());\n\n        if (rank == 0)\n            *log_stream <<\"took \" << boost::format(\"%.2e\") % timer.elapsed()\n                        << \" sec\\n\";\n    }\n\n    // Training\n    if (rank == 0) {\n        *log_stream << \"Training... \" << std::endl;\n        timer.restart();\n    }\n\n    std::shared_ptr<skylark::ml::kernel_t> k_ptr;\n\n    switch (kernel_type) {\n    case GAUSSIAN_KERNEL:\n        k_ptr.reset(new skylark::ml::gaussian_t(X.Height(), kp1));\n        break;\n\n    case LAPLACIAN_KERNEL:\n        k_ptr.reset(new skylark::ml::laplacian_t(X.Height(), kp1));\n        break;\n\n    case POLYNOMIAL_KERNEL:\n        k_ptr.reset(new skylark::ml::polynomial_t(X.Height(), kp1, kp2, kp3));\n        break;\n\n    default:\n        *log_stream << \"Invalid kernel specified.\" << std::endl;\n        return -1;\n    }\n\n    skylark::ml::kernel_container_t k(k_ptr);\n\n    El::DistMatrix<T> A, W;\n\n    skylark::sketch::sketch_transform_container_t<El::DistMatrix<T>,\n                                                  El::DistMatrix<T> >  S;\n    bool scale_maps = true;\n    std::vector<\n        skylark::sketch::sketch_transform_container_t<El::DistMatrix<T>,\n                                                      El::DistMatrix<T> > > transforms;\n\n    skylark::ml::krr_params_t krr_params(rank == 0, 4, *log_stream, \"\\t\");\n    krr_params.use_fast = use_fast;\n\n    // Transpose Y since KernelRidge expects it to be a column vector (TODO ?)\n    El::DistMatrix<T> Ytransp;\n    El::Transpose(Y, Ytransp, true);\n\n    skylark::ml::model_t<T, T> *model;\n\n    switch(algorithm) {\n    case CLASSIC_KRR:\n        skylark::ml::KernelRidge(skylark::base::COLUMNS, k, X, Ytransp,\n            T(lambda), A, krr_params);\n        model =\n            new skylark::ml::kernel_model_t<skylark::ml::kernel_container_t,\n                T, T>(k, skylark::base::COLUMNS, X, fname, partial, fileformat,\n                    SampT, A);\n        break;\n\n    case FASTER_KRR:\n        krr_params.iter_lim = (maxit == 0) ? 1000 : maxit;\n        krr_params.tolerance = (tolerance == 0) ? 1e-3 : tolerance;\n        skylark::ml::FasterKernelRidge(skylark::base::COLUMNS, k, X, Ytransp,\n            T(lambda), A, s, context, krr_params);\n        model =\n            new skylark::ml::kernel_model_t<skylark::ml::kernel_container_t,\n             T, T>(k, skylark::base::COLUMNS, X, fname, partial, fileformat, \n                 SampT, A);\n        break;\n\n    case APPROXIMATE_KRR:\n        skylark::ml::ApproximateKernelRidge(skylark::base::COLUMNS, k, X, Ytransp,\n            T(lambda), S, W, s, context, krr_params);\n        model =\n            new skylark::ml::feature_expansion_model_t<\n                skylark::sketch::sketch_transform_container_t, T, T>\n            (S, W);\n        break;\n\n    case SKETCHED_APPROXIMATE_KRR:\n    case FAST_SKETCHED_APPROXIMATE_KRR:\n        krr_params.sketched_rr = true;\n        krr_params.sketch_size = sketch_size;\n        krr_params.fast_sketch = algorithm == FAST_SKETCHED_APPROXIMATE_KRR;\n        krr_params.max_split = maxsplit;\n        skylark::ml::SketchedApproximateKernelRidge(skylark::base::COLUMNS, k,\n            X, Ytransp,\n            T(lambda), scale_maps, transforms, W, s, sketch_size,\n            context, krr_params);\n        model =\n            new skylark::ml::feature_expansion_model_t<\n                skylark::sketch::sketch_transform_container_t, T, T>\n            (scale_maps, transforms, W);\n        break;\n\n    case LARGE_SCALE_KRR:\n        krr_params.iter_lim = (maxit == 0) ? 20 : maxit;\n        krr_params.tolerance = (tolerance == 0) ? 1e-1 : tolerance;\n        krr_params.max_split = maxsplit;\n        skylark::ml::LargeScaleKernelRidge(skylark::base::COLUMNS, k, X, Ytransp,\n            T(lambda), scale_maps, transforms, W, s,\n            context, krr_params);\n        model =\n            new skylark::ml::feature_expansion_model_t<\n                skylark::sketch::sketch_transform_container_t, T, T>\n            (scale_maps, transforms, W);\n        break;\n\n    case EXPERIMENTAL_1:\n    case EXPERIMENTAL_2:\n        krr_params.sketched_rr = true;\n        krr_params.fast_sketch = algorithm == EXPERIMENTAL_2;\n        skylark::ml::ApproximateKernelRidge(skylark::base::COLUMNS, k, X, Ytransp,\n            T(lambda), S, W, s, context, krr_params);\n        model =\n            new skylark::ml::feature_expansion_model_t<\n                skylark::sketch::sketch_transform_container_t, T, T>\n            (S, W);\n        break;\n\n    default:\n        *log_stream << \"Invalid algorithm value specified.\" << std::endl;\n        return -1;\n    }\n\n    if (rank == 0)\n        *log_stream << \"Training took \" << boost::format(\"%.2e\") % timer.elapsed()\n                  << \" sec\\n\";\n\n    if (modelname != \"NOSAVE\") {\n        // Save model\n        if (rank == 0) {\n            *log_stream << \"Saving model... \";\n            log_stream->flush();\n            timer.restart();\n        }\n\n        pt = model->to_ptree();\n\n        if (rank == 0) {\n            std::ofstream of(modelname);\n            of << \"# Generated using kernel_regression \";\n            of << \"using the following command-line: \" << std::endl;\n            of << \"#\\t\" << cmdline << std::endl;\n            of << \"# Number of ranks is \" << world.size() << std::endl;\n            boost::property_tree::write_json(of, pt);\n            of.close();\n        }\n\n        if (rank == 0)\n            *log_stream <<\"took \" << boost::format(\"%.2e\") % timer.elapsed()\n                        << \" sec\\n\";\n    }\n\n\n    // Test\n    if (!testname.empty()) {\n        if (rank == 0) {\n            *log_stream << \"Predicting... \";\n            log_stream->flush();\n            timer.restart();\n        }\n\n        El::DistMatrix<T> XT;\n        El::DistMatrix<T> YT;\n\n        switch (fileformat) {\n        case skylark::utility::io::FORMAT_LIBSVM:\n            skylark::utility::io::ReadLIBSVM(testname, XT, YT,\n                skylark::base::COLUMNS, X.Height());\n            break;\n\n#ifdef SKYLARK_HAVE_HDF5\n        case skylark::utility::io::FORMAT_HDF5: {\n            H5::H5File in(testname, H5F_ACC_RDONLY);\n            skylark::utility::io::ReadHDF5(in, \"X\", XT);\n            skylark::utility::io::ReadHDF5(in, \"Y\", YT);\n            in.close();\n        }\n            break;\n#endif\n\n        default:\n            *log_stream << \"Invalid file format specified.\" << std::endl;\n            return -1;\n        }\n\n        El::DistMatrix<T> YP;\n        model->predict(skylark::base::COLUMNS, XT, YP);\n\n        if (rank == 0)\n            *log_stream << \"took \" << boost::format(\"%.2e\") % timer.elapsed()\n                      << \" sec\\n\";\n\n        T nrm_Yt = El::Nrm2(YT);\n        El::Axpy(T(-1.0), YP, YT);\n        T nrm_E = El::Nrm2(YT);\n\n        if (rank == 0)\n            *log_stream << \"Error rate: \"\n                        << boost::format(\"%.4e\") % (nrm_E / nrm_Yt)\n                        << std::endl;\n        world.barrier();\n    }\n\n    if (rank == 0 && logfile != \"\") {\n        ((std::ofstream *)log_stream)->close();\n        delete log_stream;\n    }\n\n    delete model;\n\n    return 0;\n}\n\n\ntemplate<typename T>\nint predict_regression(skylark::base::context_t &context) {\n    boost::mpi::timer timer;\n\n    boost::mpi::communicator world;\n    int rank = world.rank();\n\n    std::ostream *log_stream = &std::cout;\n    if (rank == 0 && logfile != \"\") {\n        log_stream = new std::ofstream();\n        ((std::ofstream *)log_stream)->open(logfile);\n    }\n\n    if (rank == 0) {\n        *log_stream << \"Reading model... \";\n        log_stream->flush();\n        timer.restart();\n    }\n\n    skylark::ml::model_container_t<T, T> model(pt);\n\n    if (rank == 0)\n        *log_stream <<\"took \" << boost::format(\"%.2e\") % timer.elapsed()\n                    << \" sec\\n\";\n\n    if (rank == 0) {\n        *log_stream << \"Predicting... \";\n        log_stream->flush();\n        timer.restart();\n    }\n\n    El::DistMatrix<T> XT, YT;\n\n    switch (fileformat) {\n    case skylark::utility::io::FORMAT_LIBSVM:\n        skylark::utility::io::ReadLIBSVM(fname, XT, YT,\n            skylark::base::COLUMNS, model.get_input_size());\n        break;\n\n#ifdef SKYLARK_HAVE_HDF5\n    case skylark::utility::io::FORMAT_HDF5: {\n        H5::H5File in(fname, H5F_ACC_RDONLY);\n        skylark::utility::io::ReadHDF5(in, \"X\", XT);\n        skylark::utility::io::ReadHDF5(in, \"Y\", YT);\n        in.close();\n    }\n        break;\n#endif\n\n    default:\n        *log_stream << \"Invalid file format specified.\" << std::endl;\n        return -1;\n    }\n\n    El::DistMatrix<T> YP;\n    model.predict(skylark::base::COLUMNS, XT, YP);\n\n    if (rank == 0)\n        *log_stream << \"took \" << boost::format(\"%.2e\") % timer.elapsed()\n                    << \" sec\\n\";\n\n    T nrm_Yt = El::Nrm2(YT);\n    El::Axpy(T(-1.0), YP, YT);\n    T nrm_E = El::Nrm2(YT);\n\n    if (rank == 0)\n        *log_stream << \"Error rate: \"\n                    << boost::format(\"%.4e\") % (nrm_E / nrm_Yt)\n                    << std::endl;\n    world.barrier();\n\n    if (!outputfile.empty()) {\n        if (rank == 0) {\n            *log_stream << \"Writing output... \";\n            log_stream->flush();\n            timer.restart();\n        }\n\n        El::DistMatrix<T> YPT;\n        El::Transpose(YP, YPT);\n\n        El::Write(YPT, outputfile, El::ASCII);\n\n        if (rank == 0)\n            *log_stream << \"took \" << boost::format(\"%.2e\") % timer.elapsed()\n                    << \" sec\\n\";\n    }\n\n    if (rank == 0 && logfile != \"\") {\n        ((std::ofstream *)log_stream)->close();\n        delete log_stream;\n    }\n\n    return 0;\n}\n\ntemplate<typename T>\nint predict_classification(skylark::base::context_t &context) {\n\n    boost::mpi::timer timer;\n\n    boost::mpi::communicator world;\n    int rank = world.rank();\n\n    std::ostream *log_stream = &std::cout;\n    if (rank == 0 && logfile != \"\") {\n        log_stream = new std::ofstream();\n        ((std::ofstream *)log_stream)->open(logfile);\n    }\n\n    if (rank == 0) {\n        *log_stream << \"Reading model... \";\n        log_stream->flush();\n        timer.restart();\n    }\n\n    skylark::ml::model_container_t<El::Int, T> model(pt);\n\n    if (rank == 0)\n        *log_stream <<\"took \" << boost::format(\"%.2e\") % timer.elapsed()\n                    << \" sec\\n\";\n\n    if (rank == 0) {\n        *log_stream << \"Predicting... \";\n        log_stream->flush();\n        timer.restart();\n    }\n\n    El::DistMatrix<T> XT;\n    El::DistMatrix<El::Int> LT;\n\n    switch (fileformat) {\n    case skylark::utility::io::FORMAT_LIBSVM:\n        skylark::utility::io::ReadLIBSVM(fname, XT, LT,\n            skylark::base::COLUMNS, model.get_input_size());\n        break;\n\n#ifdef SKYLARK_HAVE_HDF5\n    case skylark::utility::io::FORMAT_HDF5: {\n        H5::H5File in(fname, H5F_ACC_RDONLY);\n        skylark::utility::io::ReadHDF5(in, \"X\", XT);\n        skylark::utility::io::ReadHDF5(in, \"Y\", LT);\n        in.close();\n    }\n        break;\n#endif\n\n    default:\n        *log_stream << \"Invalid file format specified.\" << std::endl;\n        return -1;\n    }\n\n    El::DistMatrix<T> DV;\n    El::DistMatrix<El::Int> LP;\n    model.predict(skylark::base::COLUMNS, XT, LP, DV);\n\n    if (rank == 0)\n        *log_stream << \"took \" << boost::format(\"%.2e\") % timer.elapsed()\n                    << \" sec\\n\";\n\n    int errs = 0;\n    if (LT.LocalHeight() > 0)\n        for(int i = 0; i < LT.LocalWidth(); i++)\n            if (LT.GetLocal(0, i) != LP.GetLocal(0, i))\n                errs++;\n\n    errs = El::mpi::AllReduce(errs, MPI_SUM, LT.DistComm());\n\n    if (rank == 0)\n        *log_stream << \"Error rate: \"\n                    << boost::format(\"%.2f\") % ((errs * 100.0) / LT.Width())\n                    << \"%\" << std::endl;\n\n    if (!outputfile.empty()) {\n        if (rank == 0) {\n            *log_stream << \"Writing output... \";\n            log_stream->flush();\n            timer.restart();\n        }\n\n        if (!decisionvals) {\n            El::DistMatrix<El::Int> LPT;\n            El::Transpose(LP, LPT);\n            El::Write(LPT, outputfile, El::ASCII);\n        } else {\n            El::DistMatrix<T> DVT;\n            El::Transpose(DV, DVT);\n            std::stringstream stream;\n            stream << \"# Column order for decision values:\" << std::endl\n                   << \"# \";\n            std::vector<El::Int> colcoding;\n            model.get_column_coding(colcoding);\n            for(int i = 0; i < colcoding.size(); i++)\n                stream << colcoding[i] << \" \";\n            El::Write(DVT, outputfile, El::ASCII, stream.str());\n        }\n        if (rank == 0)\n            *log_stream << \"took \" << boost::format(\"%.2e\") % timer.elapsed()\n                    << \" sec\\n\";\n    }\n\n    if (rank == 0 && logfile != \"\") {\n        ((std::ofstream *)log_stream)->close();\n        delete log_stream;\n    }\n\n    return 0;\n}\n\nint main(int argc, char* argv[]) {\n\n    for(int i = 0; i < argc; i++) {\n        cmdline.append(argv[i]);\n        if (i < argc - 1)\n            cmdline.append(\" \");\n    }\n\n    El::Initialize(argc, argv);\n\n    boost::mpi::communicator world;\n    int rank = world.rank();\n\n    int flag = parse_program_options(argc, argv);\n\n    if (flag != 1000)\n        return flag;\n\n    skylark::base::context_t context(seed);\n\n    int ret = -1;\n\n    SKYLARK_BEGIN_TRY()\n\n        // If in predict mode, we need to read the model to see if regression\n        // or classification mode.\n        if (predict) {\n            std::ifstream is(modelname);\n\n            // Skip all lines begining with \"#\"\n            while(is.peek() == '#')\n                is.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n\n            boost::property_tree::read_json(is, pt);\n            is.close();\n\n            regression = pt.get<bool>(\"regression\");\n\n            if (regression) {\n                if (use_single)\n                    ret = predict_regression<float>(context);\n                else\n                    ret = predict_regression<double>(context);\n            } else {\n                if (use_single)\n                    ret = predict_classification<float>(context);\n                else\n                    ret = predict_classification<double>(context);\n            }\n        } else {\n\n            if (regression) {\n                if (use_single)\n                    ret = execute_regression<float>(context);\n                else\n                    ret = execute_regression<double>(context);\n            } else {\n                if (use_single)\n                    ret = execute_classification<float>(context);\n                else\n                    ret = execute_classification<double>(context);\n            }\n        }\n    SKYLARK_END_TRY() SKYLARK_CATCH_AND_PRINT((rank == 0))\n\n        catch (const std::exception& ex) {\n            if (rank == 0) SKYLARK_PRINT_EXCEPTION_DETAILS(ex);\n        }\n\n    El::Finalize();\n\n    return ret;\n}\n", "meta": {"hexsha": "b67b0b8cbbb6ad98ae90ce6354bc9dbbdc1c76f3", "size": 36327, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ml/skylark_krr.cpp", "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": "ml/skylark_krr.cpp", "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": "ml/skylark_krr.cpp", "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": 31.1018835616, "max_line_length": 87, "alphanum_fraction": 0.5278443031, "num_tokens": 9635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.27506937629073963}}
{"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 <boost/noncopyable.hpp>\n#include <boost/function.hpp>\n#include <Eigen/Core>\n#include \"genfile/VariantIdentifyingData.hpp\"\n#include \"genfile/VariantEntry.hpp\"\n#include \"genfile/VariantDataReader.hpp\"\n#include \"appcontext/OptionProcessor.hpp\"\n#include \"components/SNPSummaryComponent/InfoComputation.hpp\"\n\nnamespace stats {\n\tvoid InfoComputation::operator()(\n\t\tVariantIdentifyingData const& snp,\n\t\tGenotypes const& genotypes,\n\t\tPloidy const& ploidy,\n\t\tgenfile::VariantDataReader&,\n\t\tResultCallback callback\n\t) {\n\t\tm_computation.compute( snp, genotypes, ploidy ) ;\n\t\tcallback( \"info\", m_computation.info() ) ;\n\t\tcallback( \"impute_info\", m_computation.impute_info() ) ;\n\t}\n\t\n\tstd::string InfoComputation::get_summary( std::string const& prefix, std::size_t column_width ) const {\n\t\treturn prefix + \"InfoComputation\" ;\n\t}\n\t\n\tnamespace impl {\n\t\tnamespace {\n\t\t\tdouble compute_variance( Eigen::VectorXd const& levels, Eigen::VectorXd const& levels_squared, Eigen::VectorXd const& probs ) {\n\t\t\t\tdouble const mean = ( probs.transpose() * levels )(0) ;\n\t\t\t\tdouble const variance = ( probs.transpose() * levels_squared )(0) - ( mean * mean ) ;\n\t\t\t\treturn variance ;\n\t\t\t}\n\n\t\t\t// treat the rows of the probabilities matrix as probabilities.\n\t\t\t// distribution for individual i is taken as a mixture of the distribution given by row i of probabilities,\n\t\t\t// and the fallback distribution if the sum of row i < 1, appropriately weighted.\n\t\t\t// Only individuals with inclusion = 1 are used.\n\t\t\ttemplate< typename Probabilities, typename InclusionIndicator >\n\t\t\tdouble compute_sum_of_variances( Eigen::VectorXd const& levels, Probabilities const& probabilities, Eigen::VectorXd const& fallback, InclusionIndicator const& inclusion ) {\n\t\t\t\tassert( levels.size() == fallback.size() ) ;\n\t\t\t\tassert( levels.size() == probabilities.cols() ) ;\n\t\t\t\tassert( inclusion.size() == probabilities.rows() ) ;\n\t\t\t\tEigen::VectorXd levels_squared = ( levels.array() * levels.array() ) ;\n\n\t\t\t\tdouble result = 0.0 ;\n\t\t\t\tfor( int i = 0; i < probabilities.rows(); ++i ) {\n\t\t\t\t\tif( inclusion( i ) == 1 ) {\n\t\t\t\t\t\tdouble const c = probabilities.row( i ).sum() ;\n\t\t\t\t\t\tresult += compute_variance( levels, levels_squared, probabilities.row( i ).transpose() + ( 1 - c ) * fallback ) ;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn result ;\n\t\t\t}\n\t\n\t\t}\n\t\t\n\t\tInfoComputation::InfoComputation():\n\t\t\tm_diploid_fallback_distribution( Eigen::VectorXd::Zero( 3 )),\n\t\t\tm_haploid_fallback_distribution( Eigen::VectorXd::Zero( 2 )),\n\t\t\tm_diploid_levels( Eigen::VectorXd::LinSpaced( 3, 0, 2 )),\n\t\t\tm_haploid_levels( Eigen::VectorXd::LinSpaced( 2, 0, 1 ))\n\t\t{}\n\t\t\n\t\tvoid InfoComputation::compute(\n\t\t\tVariantIdentifyingData const& snp,\n\t\t\tGenotypes const& genotypes,\n\t\t\tPloidy const& ploidy\n\t\t) {\n\t\t\tcompute(\n\t\t\t\tsnp, genotypes, ploidy,\n\t\t\t\tstd::vector< metro::SampleRange >( 1, metro::SampleRange( 0, genotypes.rows()) )\n\t\t\t) ;\n\t\t}\n\t\t\t\n\t\tvoid InfoComputation::compute(\n\t\t\tVariantIdentifyingData const& snp,\n\t\t\tGenotypes const& genotypes,\n\t\t\tPloidy const& ploidy,\n\t\t\tstd::vector< metro::SampleRange > const& included_samples\n\t\t) {\n\t\t\tm_info = std::numeric_limits< double >::quiet_NaN() ;\n\t\t\tm_impute_info = std::numeric_limits< double >::quiet_NaN() ;\n\n\t\t\t// we don't compute for multiallelics currently\n\t\t\tif( snp.number_of_alleles() == 2 ) {\n\t\t\t\tcompute_impl( snp, genotypes, ploidy, included_samples ) ;\n\t\t\t}\n\t\t}\n\t\n\t\tvoid InfoComputation::compute_impl(\n\t\t\tVariantIdentifyingData const& snp,\n\t\t\tGenotypes const& genotypes,\n\t\t\tPloidy const& ploidy,\n\t\t\tstd::vector< metro::SampleRange > const& included_samples\n\t\t) {\n\t\t\ttypedef Eigen::Block< Genotypes const > GenotypeBlock ;\n\t\t\ttypedef Eigen::VectorBlock< Eigen::VectorXd const > PloidyBlock ;\n\n\t\t\t// This function assumes every sample is haploid or diploid.\n\t\t\tEigen::VectorXd const haploids = ( ploidy.array() == 1 ).cast< double >() ;\n\t\t\tEigen::VectorXd const diploids = ( ploidy.array() == 2 ).cast< double >() ;\n\t\t\t\n\t\t\tdouble b_allele_count = 0 ;\n\t\t\tdouble total_allele_count = 0 ;\n\t\t\tdouble autosomal_b_allele_count = 0 ;\t\t// for computations that pretend ploidy == 2 everywhere.\n\t\t\tdouble autosomal_total_allele_count = 0 ;\t// for computations that pretend ploidy == 2 everywhere.\n\n\t\t\tdouble number_of_haploid_info_samples = 0 ;\n\t\t\tdouble number_of_diploid_info_samples = 0 ;\n\t\t\tdouble total_probability = 0 ;\n\t\t\tfor( std::size_t i = 0; i < included_samples.size(); ++i ) {\n\t\t\t\tGenotypeBlock const block = genotypes.block( included_samples[i].begin(), 0, included_samples[i].end() - included_samples[i].begin(), genotypes.cols() ) ;\n\t\t\t\tPloidyBlock const haploid_block = haploids.segment( included_samples[i].begin(), included_samples[i].size() ) ;\n\t\t\t\tPloidyBlock const diploid_block = diploids.segment( included_samples[i].begin(), included_samples[i].size() ) ;\n\t\t\n\t\t\t\tb_allele_count += (( block.col( 1 ) + 2.0 * block.col( 2 ) ).array() * diploid_block.array() ).sum() ;\n\t\t\t\tb_allele_count += (( block.col( 1 ) ).array() * haploid_block.array() ).sum() ;\n\n\t\t\t\ttotal_allele_count += 2 * ( block.rowwise().sum().array() * diploid_block.array() ).sum() ;\n\t\t\t\ttotal_allele_count += ( block.rowwise().sum().array() * haploid_block.array() ).sum() ;\n\n\t\t\t\tautosomal_b_allele_count += ( block.col( 1 ) + 2.0 * block.col( 2 ) ).array().sum() ;\n\t\t\t\tautosomal_total_allele_count += 2 * block.sum() ;\n\t\t\t\n\t\t\t\tnumber_of_haploid_info_samples += haploid_block.sum() ;\n\t\t\t\tnumber_of_diploid_info_samples += diploid_block.sum() ;\n\t\t\t\ttotal_probability += block.sum() ;\n\t\t\t}\n\t\t\t\n\t\t\t// MLE estimate of allele frequency\n\t\t\tdouble const theta_mle = b_allele_count / total_allele_count ;\n\t\t\tdouble const autosomal_theta_mle = autosomal_b_allele_count / autosomal_total_allele_count ;\n\t\t\tdouble const theta_est = theta_mle ;\n\n\t\t\tm_diploid_fallback_distribution( 0 ) = ( 1 - theta_mle ) * ( 1 - theta_mle ) ;\n\t\t\tm_diploid_fallback_distribution( 1 ) = 2.0 * theta_mle * ( 1 - theta_mle ) ;\n\t\t\tm_diploid_fallback_distribution( 2 ) = theta_mle * theta_mle ;\n\t\t\n\t\t\tm_haploid_fallback_distribution( 0 ) = 1 - theta_mle ;\n\t\t\tm_haploid_fallback_distribution( 1 ) = theta_mle ;\n\t\t\n\t\t\t//std::cerr << \"theta = \" << theta_mle << \", fallback_distribution = \" << fallback_distribution.transpose() << \".\\n\" ;\n\t\t\n\t\t\tdouble diploid_info_term = 0.0 ;\n\t\t\tdouble haploid_info_term = 0.0 ;\n\t\t\tdouble impute_info_term = 0.0 ;\n\t\t\tfor( std::size_t i = 0; i < included_samples.size(); ++i ) {\n\t\t\t\tGenotypeBlock const diploid_genotype_block = genotypes.block( included_samples[i].begin(), 0, included_samples[i].size(), genotypes.cols() ) ;\n\t\t\t\tGenotypeBlock const haploid_genotype_block = genotypes.block( included_samples[i].begin(), 0, included_samples[i].size(), 2 ) ;\n\t\t\t\tPloidyBlock const haploid_block = haploids.segment( included_samples[i].begin(), included_samples[i].size() ) ;\n\t\t\t\tPloidyBlock const diploid_block = diploids.segment( included_samples[i].begin(), included_samples[i].size() ) ;\n\n\t\t\t\thaploid_info_term -= compute_sum_of_variances(\n\t\t\t\t\tm_haploid_levels, haploid_genotype_block,\n\t\t\t\t\tm_haploid_fallback_distribution, haploid_block\n\t\t\t\t)\n\t\t\t\t/ ( theta_mle * ( 1 - theta_mle ) ) ;\n\n\t\t\t\tdiploid_info_term -= compute_sum_of_variances(\n\t\t\t\t\tm_diploid_levels, diploid_genotype_block,\n\t\t\t\t\tm_diploid_fallback_distribution, diploid_block\n\t\t\t\t)\n\t\t\t\t/ ( 2.0 * theta_mle * ( 1 - theta_mle ) ) ;\n\t\t\t\n\t\t\t\timpute_info_term -= compute_sum_of_variances(\n\t\t\t\t\tm_diploid_levels, diploid_genotype_block,\n\t\t\t\t\tEigen::VectorXd::Zero( 3 ), Eigen::VectorXd::Constant( diploid_genotype_block.rows(), 1 )\n\t\t\t\t)\n\t\t\t\t/ ( 2.0 * autosomal_theta_mle * ( 1 - autosomal_theta_mle ) ) ;\n\t\t\t}\n\t\t\n\t\t\tdouble info = std::numeric_limits< double >::quiet_NaN() ;\n\t\t\tdouble impute_info = std::numeric_limits< double >::quiet_NaN() ;\n\n\t\t\tif(( number_of_haploid_info_samples + number_of_diploid_info_samples ) > 0 ) {\n\t\t\t\tinfo = 1.0 + (haploid_info_term + diploid_info_term) / ( number_of_haploid_info_samples + number_of_diploid_info_samples ) ;\n\t\t\t}\n\t\t\t\n\t\t\tif( total_probability > 0 ) {\n\t\t\t\timpute_info = 1.0 + impute_info_term / total_probability ;\n\t\t\t}\n\n\t\t\tm_info = info ;\n\t\t\tm_impute_info = impute_info ;\n\t\t}\n\n\t}\n}\n", "meta": {"hexsha": "d35f22d6ccd75b806ae46f43b58ef16546be1ccf", "size": 8297, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "components/SNPSummaryComponent/src/InfoComputation.cpp", "max_stars_repo_name": "gavinband/qctool", "max_stars_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-21T05:42:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T14:59:43.000Z", "max_issues_repo_path": "components/SNPSummaryComponent/src/InfoComputation.cpp", "max_issues_repo_name": "gavinband/qctool", "max_issues_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-09T16:11:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T11:18:56.000Z", "max_forks_repo_path": "components/SNPSummaryComponent/src/InfoComputation.cpp", "max_forks_repo_name": "gavinband/qctool", "max_forks_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.904040404, "max_line_length": 175, "alphanum_fraction": 0.6950705074, "num_tokens": 2331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.27498393982620556}}
{"text": "\n/*=========================================================================\n\n  Program:   Small Body Geophysical Analysis\n  Module:    SBGATObsRadar.hpp\n\n  Class derived from VTK's vtkPolyDataAlgorithm by Benjamin Bercovici  \n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*/\n/**\n@file SBGATObsRadar.hpp\n@class  SBGATObsRadar\n@author Benjamin Bercovici\n@author Jay McMahon\n@date October 2018\n@brief  Computes range/range-rate Doppler images over the surface of\nprovided small body\n@details Computes range/range-rate Doppler images over the surface of\nprovided small body\n@copyright MIT License, Benjamin Bercovici and Jay McMahon\n\n  \n*/\n\n#ifndef SBGATObsRadar_H\n#define SBGATObsRadar_H\n\n#include <vtkFiltersCoreModule.h> // For export macro\n#include <vtkPolyDataAlgorithm.h>\n\n#include <vtkModifiedBSPTree.h>\n#include <vtkImageData.h>\n\n#include <armadillo>\n#include <array>\n\n#include <SBGATObs.hpp>\n\n\n/**\nVector of vector of radar observations. Each observation is comprised of (range,range-rate,incidence)\nThis incidence is not strictly speaking a measured quantity but is used to penalize the binned \nobservations, blurring out returns collected at a high incidence\n*/\ntypedef typename std::vector<std::vector<std::array<double, 3> > > SBGATRadarObsSequence;\n\n\nclass VTKFILTERSCORE_EXPORT SBGATObsRadar : public SBGATObs{\npublic:\n  /**\n   * Constructs with initial values of zero.\n   */\n  static SBGATObsRadar *New();\n\n  vtkTypeMacro(SBGATObsRadar,vtkPolyDataAlgorithm);\n  void PrintSelf(std::ostream& os, vtkIndent indent) override;\n  void PrintHeader(std::ostream& os, vtkIndent indent) override;\n  void PrintTrailer(std::ostream& os, vtkIndent indent) override;\n\n  /**\n  Collects range/range-rate samples over the surface of the specified system of small bodies at a given time after the epoch. The radar source is positionned at 1e6 * l meters from the target's center of mass, where \n  l is a measure of the first object's diagonal. \n  @param measurements_sequence reference to MeasurementsSequence, holding collected range/range-rate measurements at each observation time\n  @param time observation timestamp\n  @param N minimum number of measurements to produce over the smallest facet in the shape. The number of samples for any other facet will be equal to N * facet_surface_area / smallest_facet_surface_area\n  @param radar_dir unit direction towards radar from target in inertial frame\n  @param positions_vec vector of positions of each target's center-of-mass expressed in the primary's body frame\n  @param velocities_vec vector of inertial velocities of each target's center-of-mass expressed in the primary's body frame\n  @param mrps_vec vector of MRPs defining the inertial-to-body DCM [BN]\n  @param omegas_vec vector of angular velocities of each body expressed in the inertial frame\n  @param penalize_incidence if true, each measurement will be weighed by the cos(incidence) angle between\n  the sampled point and the radar squared. If false, all measurements (in view of the radar and not blocked) are weighed equally\n  have the same weight\n  */\n  void CollectMeasurements(SBGATRadarObsSequence & measurements_sequence,  \n  const double & time,\n  const int & N,\n  const arma::vec & radar_dir,\n  const std::vector<arma::vec> & positions_vec,\n  const std::vector<arma::vec> & velocities_vec,\n  const std::vector<arma::vec> & mrps_vec,\n  const std::vector<arma::vec> & omegas_vec,\n  const bool & penalize_indicence);\n\n\n\n\n  /**\n  Bins the provided measurements sequence into a series of 2d-histogram\n  Will throw an std::runtime_error exception if \n  - either of the provided bin sizes are invalid (i.e <= 0)\n  - the provided bin sizes yield empty histogram dimensions\n  @param measurements_sequence reference to MeasurementsSequence, holding collected range/range-rate measurements at each observation time\n  @param r_bin range bin size (m)\n  @param rr_bin range-rate bin size (m/s)\n  */\n  void BinObservations(\n    const SBGATRadarObsSequence & measurements_sequence,\n    const double & r_bin,\n    const double & rr_bin);\n\n  /**\n  Save the binned radar images to PNGs in the prescribed folder.\n  The images will be normalized by the largest value in the observation sequence\n  @param savepath path to folder where images will be saved (ex: \"output/\")\n  */\n  void SaveImages(std::string savepath);\n\n  \n  /**\n  Return vector holding the computed images\n  @return vector of radar images\n  */\n  std::vector<vtkSmartPointer<vtkImageData>> GetImages() const;\n\n  /**\n  Clears images, if any\n  */\n\n  void ClearImages() { this -> images.clear();}\n\n\nprotected:\n  SBGATObsRadar();\n  ~SBGATObsRadar() override;\n\n\n\n  /**\n  Ray traces the facets in view to the radar and measurements sequence with range/range-rate data\n  if sampled point was in view of the radar\n  @param measurements_sequence Sequence of measurements to add new image data to\n  @param facets_in_view reference to a vector of vector holding indices of (maybe) illuminated facets for all considered bodies\n  @param radar_dir radar direction expressed in inertial frame\n  @param BN_dcms_vec vector holding the DCMs orienting the body frame of each body w/r to inertial\n  @param positions_vec vector holding the position vector of the CM of each body w/r to the primary\n  @param velocities_vec vector holding the velocities vector of the CM of each body\n  @param omega_vec vector holding the angular velocities vector of each body\n  */\n  void reverse_ray_trace(SBGATRadarObsSequence & measurements_sequence,\n    const std::vector<std::vector<int> > & facets_in_view,\n    const arma::vec & radar_dir,\n    const int N,\n    const bool penalize_indicence,\n    const std::vector<arma::mat> & BN_dcms_vec,\n    const std::vector<arma::vec> & positions_vec,\n    const std::vector<arma::vec> & velocities_vec,\n    const std::vector<arma::vec> & omega_vec);\n\n\n  std::vector<vtkSmartPointer<vtkImageData>> images;\n  \n  double max_value;\n\n  \n\nprivate:\n  SBGATObsRadar(const SBGATObsRadar&) = delete;\n  void operator=(const SBGATObsRadar&) = delete;\n};\n\n#endif\n\n\n", "meta": {"hexsha": "180b79548f03168c887f0efd61e7f2e8c16f80da", "size": 6409, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SbgatCore/include/SbgatCore/SBGATObsRadar.hpp", "max_stars_repo_name": "bbercovici/SBGAT", "max_stars_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-11-29T02:47:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T05:25:44.000Z", "max_issues_repo_path": "SbgatCore/include/SbgatCore/SBGATObsRadar.hpp", "max_issues_repo_name": "bbercovici/SBGAT", "max_issues_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34.0, "max_issues_repo_issues_event_min_datetime": "2017-02-09T15:38:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-25T20:53:37.000Z", "max_forks_repo_path": "SbgatCore/include/SbgatCore/SBGATObsRadar.hpp", "max_forks_repo_name": "bbercovici/SBGAT", "max_forks_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-12T12:20:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-12T12:20:25.000Z", "avg_line_length": 37.0462427746, "max_line_length": 216, "alphanum_fraction": 0.7459822125, "num_tokens": 1511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2749656881660291}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <unsupported/Eigen/MatrixFunctions>\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/range/adaptor/transformed.hpp>\n\n#include \"graphviz_interface.hpp\"\n\n#include \"DiGraph.hpp\"\n#include \"tran_mat_cell.hpp\"\n#include <fmt/format.h>\n\nconst size_t DEFAULT_N_SAMPLES = 200;\n\nenum InitialBeta { ZERO, ONE, HALF, MEAN, RANDOM };\n\ntypedef std::unordered_map<std::string, std::vector<double>>\n    AdjectiveResponseMap;\n\ntypedef std::vector<std::vector<std::vector<std::vector<double>>>>\n    ObservedStateSequence;\n\ntypedef std::vector<std::vector<std::vector<double>>>\n    PredictedObservedStateSequence;\n\ntypedef std::pair<std::tuple<std::string, int, std::string>,\n                  std::tuple<std::string, int, std::string>>\n    CausalFragment;\n\ntypedef std::vector<std::vector<\n    std::unordered_map<std::string, std::unordered_map<std::string, double>>>>\n    FormattedPredictionResult;\n\ntypedef std::tuple<std::pair<std::pair<int, int>, std::pair<int, int>>,\n                   std::vector<std::string>,\n                   FormattedPredictionResult>\n    Prediction;\n\nAdjectiveResponseMap construct_adjective_response_map(size_t n_kernels);\n\n/**\n * The AnalysisGraph class is the main model/interface for Delphi.\n */\nclass AnalysisGraph {\n\n  DiGraph graph;\n\n  public:\n  AnalysisGraph() {}\n  Node& operator[](std::string);\n  Node& operator[](int);\n  Edge& edge(int, int);\n  size_t num_vertices();\n  size_t num_edges();\n  // Manujinda: I had to move this up since I am usign this within the private:\n  // block This is ugly. We need to re-factor the code to make it pretty again\n  auto node_indices() {\n    return boost::make_iterator_range(boost::vertices(this->graph));\n  };\n\n  auto nodes(){\n    using boost::adaptors::transformed;\n    return this->node_indices() |\n          transformed([&](int v) -> Node& { return (*this)[v]; });\n  };\n\n  boost::range_detail::integer_iterator<unsigned long> begin() {return boost::vertices(this->graph).first;};\n  boost::range_detail::integer_iterator<unsigned long> end() {return boost::vertices(this->graph).second;};\n\n\n  auto successors(int i);\n\n  // Allocate a num_verts x num_verts 2D array (std::vector of std::vectors)\n  void allocate_A_beta_factors();\n\n  void print_A_beta_factors();\n\n  private:\n  void clear_state();\n\n  // Maps each concept name to the vertex id of the\n  // vertex that concept is represented in the CAG\n  // concept name --> CAG vertex id\n  std::unordered_map<std::string, int> name_to_vertex = {};\n\n  // Keeps track of indicators in CAG to ensure there are no duplicates.\n  // std::vector<std::string> indicators_in_CAG;\n  std::unordered_set<std::string> indicators_in_CAG;\n\n  // A_beta_factors is a 2D array (std::vector of std::vectors) that keeps track\n  // of the β factors involved with each cell of the transition matrix A.\n  //\n  // Accordign to our current model, which uses variables and their partial\n  // derivatives with respect to each other ( x --> y, βxy = ∂y/∂x ),\n  // atmost half of the transition matrix cells can be affected by βs.\n  // According to the way we organize the transition matrix, the cells\n  // A[row][col] where row is an even index and col is an odd index\n  // are such cells.\n  //\n  // Each cell of matrix A_beta_factors represent all the directed paths\n  // starting at the vertex equal to the column index of the matrix and\n  // ending at the vertex equal to the row index of the matrix.\n  //\n  // Each cell of matrix A_beta_factors is an object of Tran_Mat_Cell class.\n  std::vector<std::vector<std::shared_ptr<Tran_Mat_Cell>>> A_beta_factors;\n\n  // A set of (row, column) numbers of the 2D matrix A_beta_factors\n  // where the cell (row, column) depends on β factors.\n  std::set<std::pair<int, int>> beta_dependent_cells;\n\n  // Maps each β to all the transition matrix cells that are dependent on it.\n  std::multimap<std::pair<int, int>, std::pair<int, int>> beta2cell;\n\n  double t = 0.0;\n  double delta_t = 1.0;\n\n  // Latent state that is evolved by sampling.\n  // Since s0 is used to represent a sequence of latent states,\n  // I named this s0_original. Once things are refactored, we might be able to\n  // convert this to s0\n  Eigen::VectorXd s0;\n\n  // Transition matrix that is evolved by sampling.\n  // Since variable A has been already used locally in other methods,\n  // I chose to name this A_orginal. After refactoring the code, we could\n  // rename this to A.\n  Eigen::MatrixXd A_original;\n\n  int n_timesteps;\n  int pred_timesteps;\n  std::pair<std::pair<int, int>, std::pair<int, int>> training_range;\n\n  // This is a column of the\n  // this->training_latent_state_sequences\n  // prediction_initial_latent_states.size() = this->res\n  // TODO: If we make the code using this variable to directly fetch the values\n  // from this->training_latent_state_sequences, we can get rid of this\n  std::vector<Eigen::VectorXd> prediction_initial_latent_states;\n  std::vector<std::string> pred_range;\n\n  // Access this as\n  // prediction_latent_state_sequences[ sample ][ time step ]\n  std::vector<std::vector<Eigen::VectorXd>> predicted_latent_state_sequences;\n\n  // Access this as\n  // prediction_observed_state_sequences\n  //                            [ sample ][ time step ][ vertex ][ indicator ]\n  std::vector<PredictedObservedStateSequence>\n      predicted_observed_state_sequences;\n\n  PredictedObservedStateSequence test_observed_state_sequence;\n\n  // Sampling resolution. Default is 200\n  int res = DEFAULT_N_SAMPLES;\n\n  // Keep track whether the model is trained.\n  // Used to check whether there is a trained model before calling\n  // generate_prediction()\n  bool trained = false;\n\n  // Access this as\n  // current_latent_state\n  Eigen::VectorXd current_latent_state;\n\n  // Access this as\n  // observed_state_sequence[ time step ][ vertex ][ indicator ]\n  ObservedStateSequence observed_state_sequence;\n\n  std::vector<Eigen::MatrixXd> transition_matrix_collection;\n\n  // Remember the old β and the edge where we perturbed the β.\n  // We need this to revert the system to the previous state if the proposal\n  // gets rejected.\n  std::pair<boost::graph_traits<DiGraph>::edge_descriptor, double>\n      previous_beta;\n\n  double log_likelihood = 0.0;\n  double previous_log_likelihood = 0.0;\n  bool data_heuristic = false;\n\n  void get_subgraph(int vert,\n                    std::unordered_set<int>& vertices_to_keep,\n                    int cutoff,\n                    bool inward);\n\n  void get_subgraph_between(int start,\n                            int end,\n                            std::vector<int>& path,\n                            std::unordered_set<int>& vertices_to_keep,\n                            int cutoff);\n\n  /**\n   * Finds all the simple paths starting at the start vertex and\n   * ending at the end vertex.\n   * Uses find_all_paths_between_util() as a helper to recursively find the\n   * paths\n   */\n  void find_all_paths_between(int start, int end, int cutoff);\n\n  /**\n   * Recursively finds all the simple paths starting at the start vertex and\n   * ending at the end vertex. Used by find_all_paths_between()\n   * Paths found are added to the Tran_Mat_Cell object that is tracking the\n   * transition matrix cell (2*end, 2*start)\n   *\n   * @param start: Start vertex of the path\n   * @param end  : End vertex of the path\n   * @param path : A path starting at vettex start that is being explored\n   *\n   * @return void\n   */\n  void find_all_paths_between_util(int start,\n                                   int end,\n                                   std::vector<int>& path,\n                                   int cutoff);\n\n  /*\n   ==========================================================================\n   Utilities\n   ==========================================================================\n  */\n  void set_default_initial_state();\n\n  std::mt19937 rand_num_generator;\n\n  // Uniform distribution used by the MCMC sampler\n  std::uniform_real_distribution<double> uni_dist;\n\n  // Normal distrubution used to perturb β\n  std::normal_distribution<double> norm_dist;\n\n  int get_vertex_id_for_concept(std::string concept, std::string caller);\n\n  int get_degree(int vertex_id);\n\n  void remove_node(int node_id);\n\n  public:\n  ~AnalysisGraph() {}\n\n  /**\n   * A method to construct an AnalysisGraph object given a JSON-serialized list\n   * of INDRA statements.\n   *\n   * @param filename: The path to the file containing the JSON-serialized INDRA\n   * statements.\n   */\n  static AnalysisGraph from_json_file(std::string filename,\n                                      double belief_score_cutoff = 0.9,\n                                      double grounding_score_cutoff = 0.0,\n                                      std::string ontology = \"WM\");\n\n  /**\n   * A method to construct an AnalysisGraph object given from a std::vector of\n   * ( subject, object ) pairs (Statements)\n   *\n   * @param statements: A std::vector of CausalFragment objects\n   */\n  static AnalysisGraph\n  from_causal_fragments(std::vector<CausalFragment> causal_fragments);\n\n  // TODO Change the name of this function to something better, like\n  // restrict_to_subgraph_for_concept, update docstring\n\n  /**\n   * Returns a new AnaysisGraph related to the concept provided,\n   * which is a subgraph of this graph.\n   *\n   * @param concept: The concept where the subgraph is about.\n   * @param depth  : The maximum number of hops from the concept provided\n   *                 to be included in the subgraph.\n   * #param inward : Sets the direction of the causal influence flow to\n   *                 examine.\n   *                 False - (default) A subgraph rooted at the concept\n   * provided.\n   *                 True  - A subgraph with all the paths ending at the concept\n   * provided.\n   */\n  AnalysisGraph get_subgraph_for_concept(std::string concept,\n                                         bool inward = false,\n                                         int depth = -1);\n\n  /**\n   * Returns a new AnaysisGraph related to the source concept and the target\n   * concetp provided, which is a subgraph of this graph.\n   * This subgraph contains all the simple directed paths of length less than\n   * or equal to the provided cutoff.\n   *\n   * @param source_concept: The concept where the influence starts.\n   * @param target_concept: The concept where the influence ends.\n   * @param cutoff        : Maximum length of a directed simple path from\n   *                        the source to target to be included in the\n   *                        subgraph.\n   */\n  AnalysisGraph get_subgraph_for_concept_pair(std::string source_concept,\n                                              std::string target_concept,\n                                              int cutoff = -1);\n\n  void prune(int cutoff = 2);\n\n  void add_node(std::string concept);\n\n  void add_edge(CausalFragment causal_fragment);\n  void change_polarity_of_edge(std::string source_concept,\n                               int source_polarity,\n                               std::string target_concept,\n                               int target_polarity);\n  void remove_node(std::string concept);\n\n  // Note:\n  //      Although just calling this->remove_node(concept) within the loop\n  //          for( std::string concept : concept_s )\n  //      is suffifient to implement this method, it is not very efficient.\n  //      It re-calculates directed simple paths for each vertex removed\n  //\n  //      Therefore, the code in this->remove_node() has been duplicated with\n  //      slightly different flow to achive a more efficient execution.\n  void remove_nodes(std::unordered_set<std::string> concepts);\n\n  void remove_edge(std::string src, std::string tgt);\n\n  void remove_edges(std::vector<std::pair<std::string, std::string>> edges);\n\n  auto edges() { return boost::make_iterator_range(boost::edges(graph)); }\n\n  /** Number of nodes in the graph */\n  int num_nodes() { return boost::num_vertices(graph); }\n\n  auto predecessors(int i) {\n    return boost::make_iterator_range(boost::inv_adjacent_vertices(i, graph));\n  }\n\n  // Merge node n1 into node n2, with the option to specify relative polarity.\n  // void\n  // merge_nodes_old(std::string n1, std::string n2, bool same_polarity = true);\n\n  /**\n   * Merges the CAG nodes for the two concepts concept_1 and concept_2\n   * with the option to specify relative polarity.\n   */\n  void merge_nodes(std::string concept_1,\n                   std::string concept_2,\n                   bool same_polarity = true);\n\n  auto out_edges(int i) {\n    return boost::make_iterator_range(boost::out_edges(i, graph));\n  }\n\n  double get_beta(std::string source_vertex_name,\n                  std::string target_vertex_name) {\n    // This is ∂target / ∂source\n    // return this->A_original(2 * this->name_to_vertex[target_vertex_name],\n    //                        2 * this->name_to_vertex[source_vertex_name] + 1);\n    return this->A_original(\n        2 * get_vertex_id_for_concept(target_vertex_name, \"get_beta()\"),\n        2 * get_vertex_id_for_concept(source_vertex_name, \"get_beta()\") + 1);\n  }\n\n  void construct_beta_pdfs();\n\n  AnalysisGraph\n  find_all_paths_for_concept(std::string concept, int depth, bool reverse);\n\n  /*\n   * Find all the simple paths between all the paris of nodes of the graph\n   */\n  void find_all_paths();\n\n  /*\n   * Prints the simple paths found between all pairs of nodes of the graph\n   * Groupd according to the starting and ending vertex.\n   * find_all_paths() should be called before this to populate the paths\n   */\n  void print_all_paths();\n\n  // Given an edge (source, target vertex ids - i.e. a β ≡ ∂target/∂source),\n  // print all the transition matrix cells that are dependent on it.\n  void print_cells_affected_by_beta(int source, int target);\n\n  /*\n   ==========================================================================\n   Sampling and inference\n   ----------------------\n\n   This section contains code for sampling and Bayesian inference.\n   ==========================================================================\n  */\n\n  // Sample elements of the stochastic transition matrix from the\n  // prior distribution, based on gradable adjectives.\n  void sample_initial_transition_matrix_from_prior();\n\n  /**\n   * Utility function that converts a time range given a start date and end date\n   * into an integer value.\n   * At the moment returns the number of months withing the time range.\n   * This should be the number of traing data time points we have\n   *\n   * @param start_year  : Start year of the training data sequence\n   * @param start_month : Start month of the training data sequence\n   * @param end_year    : End year of the training data sequence\n   * @param end_month   : End month of the training data sequence\n   *\n   * @return            : Number of months in the training data sequence\n   *                      Including both start and end months\n   */\n  int calculate_num_timesteps(int start_year,\n                              int start_month,\n                              int end_year,\n                              int end_month);\n\n  /**\n   * Get the observed state (values for all the indicators)\n   * for a given time point from data.\n   * See data.hpp::get_data_value() for missing data rules.\n   * Note: units are automatically set according\n   * to the parameterization of the given CAG.\n   *\n   * @param year    : Year of the time point data is extracted\n   * @param month   : Month of the time point data is extracted\n   * @param country : Country where the data is about\n   * @param state   : State where the data is about\n   * @param county  : County where the data is about\n   *\n   * @return        : Observed state std::vector for the specified location\n   *                  on the specified time point.\n   *                  Access it as: [ vertex id ][ indicator id ]\n   */\n  std::vector<std::vector<std::vector<double>>>\n  get_observed_state_from_data(int year,\n                               int month,\n                               std::string country = \"South Sudan\",\n                               std::string state = \"\",\n                               std::string county = \"\");\n\n  /**\n   * Set the observed state sequence for a given time range from data.\n   * The sequence includes both ends of the range.\n   * See data.hpp::get_data_value() for missing data rules.\n   * Note: units are automatically set according\n   * to the parameterization of the given CAG.\n   *\n   * @param start_year  : Start year of the sequence of data\n   * @param start_month : Start month of the sequence of data\n   * @param end_year    : End year of the sequence of data\n   * @param end_month   : End month of the sequenec of data\n   * @param country     : Country where the data is about\n   * @param state       : State where the data is about\n   * @param county      : County where the data is about\n   *\n   */\n  void\n  set_observed_state_sequence_from_data(int start_year,\n                                        int start_month,\n                                        int end_year,\n                                        int end_month,\n                                        std::string country = \"South Sudan\",\n                                        std::string state = \"\",\n                                        std::string county = \"\");\n\n  /**\n   * Utility function that sets an initial latent state from observed data.\n   * This is used for the inference of the transition matrix as well as the\n   * training latent state sequences.\n   *\n   * @param timestep: Optional setting for setting the initial state to be other\n   *                  than the first time step. Not currently used.\n   *                  0 <= timestep < this->n_timesteps\n   */\n  void set_initial_latent_state_from_observed_state_sequence();\n\n  void initialize_random_number_generator();\n\n  void set_random_initial_latent_state();\n\n  /**\n   * To help experiment with initializing βs to differet values\n   *\n   * @param ib: Criteria to initialize β\n   */\n  void init_betas_to(InitialBeta ib = InitialBeta::MEAN);\n\n  /**\n   * Train a prediction model given a CAG with indicators\n   *\n   * @param start_year  : Start year of the sequence of data\n   * @param start_month : Start month of the sequence of data\n   * @param end_year    : End year of the sequence of data\n   * @param end_month   : End month of the sequenec of data\n   * @param res         : Sampling resolution. The number of samples to retain.\n   * @param burn        : Number of samples to throw away. Start retaining\n   *                      samples after throwing away this many samples.\n   * @param country     : Country where the data is about\n   * @param state       : State where the data is about\n   * @param county      : county where the data is about\n   * @param units       : Units for each indicator. Maps\n   *                      indicator name --> unit\n   * @param initial_beta: Criteria to initialize β\n   *\n   */\n  void train_model(int start_year = 2012,\n                   int start_month = 1,\n                   int end_year = 2017,\n                   int end_month = 12,\n                   int res = 200,\n                   int burn = 10000,\n                   std::string country = \"South Sudan\",\n                   std::string state = \"\",\n                   std::string county = \"\",\n                   std::map<std::string, std::string> units = {},\n                   InitialBeta initial_beta = InitialBeta::ZERO,\n                   bool use_heuristic = false);\n\n  /**\n   * Sample a collection of observed state sequences from the likelihood\n   * model given a collection of transition matrices.\n   *\n   * @param prediction_timesteps: The number of timesteps for the prediction\n   * sequences.\n   * @param initial_prediction_step: The initial prediction timestep relative\n   *                                 to training timesteps.\n   * @param total_timesteps: Total number of timesteps from the initial\n   *                         training date to the end prediction date.\n   */\n  void sample_predicted_latent_state_sequences(int prediction_timesteps,\n                                               int initial_prediction_step,\n                                               int total_timesteps);\n\n  /** Generate predicted observed state sequenes given predicted latent state\n   * sequences using the emission model\n   */\n  void\n  generate_predicted_observed_state_sequences_from_predicted_latent_state_sequences();\n\n  /**\n   * Given a trained model, generate this->res number of\n   * predicted observed state sequences.\n   *\n   * @param start_year  : Start year of the prediction\n   *                      Should be >= the start year of training\n   * @param start_month : Start month of the prediction\n   *                      If training and prediction start years are equal\n   *                      should be >= the start month of training\n   * @param end_year    : End year of the prediction\n   * @param end_month   : End month of the prediction\n   *\n   * @return Predicted observed state (indicator value) sequence for the\n   *         prediction period including start and end time points.\n   *         This is a tuple.\n   *         The first element is a std::vector of std::strings with lables for\n   * each time point predicted (year-month). The second element contains\n   * predicted values. Access it as: [ sample number ][ time point ][ vertex\n   * name ][ indicator name ]\n   */\n  Prediction generate_prediction(int start_year,\n                                 int start_month,\n                                 int end_year,\n                                 int end_month);\n\n  /**\n   * Format the prediction result into a format python callers favor.\n   *\n   * @param pred_timestes: Number of timesteps in the predicted sequence.\n   *\n   * @return Re-formatted prediction result.\n   *         Access it as:\n   *         [ sample number ][ time point ][ vertex name ][ indicator name ]\n   */\n\n  FormattedPredictionResult format_prediction_result();\n\n  /**\n   * this->generate_prediction() must be called before callign this method.\n   * Outputs raw predictions for a given indicator that were generated by\n   * generate_prediction(). Each column is a time step and the rows are the\n   * samples for that time step.\n   *\n   * @param indicator: A std::string representing the indicator variable for\n   which we\n   *                   want predictions for.\n\n   * @return A this->res x this->pred_timesteps dimension 2D array\n   *         (std::vector of std::vectors)\n   *\n  */\n  std::vector<std::vector<double>> prediction_to_array(std::string indicator);\n\n  std::vector<Eigen::VectorXd> synthetic_latent_state_sequence;\n  // ObservedStateSequence synthetic_observed_state_sequence;\n  bool synthetic_data_experiment = false;\n\n  void generate_synthetic_latent_state_sequence();\n\n  void\n  generate_synthetic_observed_state_sequence_from_synthetic_latent_state_sequence();\n\n  std::pair<PredictedObservedStateSequence, Prediction>\n  test_inference_with_synthetic_data(\n      int start_year = 2015,\n      int start_month = 1,\n      int end_year = 2015,\n      int end_month = 12,\n      int res = 100,\n      int burn = 900,\n      std::string country = \"South Sudan\",\n      std::string state = \"\",\n      std::string county = \"\",\n      std::map<std::string, std::string> units = {},\n      InitialBeta initial_beta = InitialBeta::HALF);\n\n  // TODO: Need testing\n  /**\n   * Sample observed state std::vector.\n   * This is the implementation of the emission function.\n   *\n   * @param latent_state: Latent state std::vector.\n   *                      This has 2 * number of vertices in the CAG.\n   *                      Even indices track the state of each vertex.\n   *                      Odd indices track the state of the derivative.\n   *\n   * @return Observed state std::vector. Observed state for each indicator for\n   * each vertex. Indexed by: [ vertex id ][ indicator id ]\n   */\n  std::vector<std::vector<double>>\n  sample_observed_state(Eigen::VectorXd latent_state);\n\n  /**\n   * Find all the transition matrix (A) cells that are dependent on the β\n   * attached to the provided edge and update them.\n   * Acts upon this->A_original\n   *\n   * @param e: The directed edge ≡ β that has been perturbed\n   */\n  void update_transition_matrix_cells(\n      boost::graph_traits<DiGraph>::edge_descriptor e);\n\n  /**\n   * Sample a new transition matrix from the proposal distribution,\n   * given a current candidate transition matrix.\n   * In practice, this amounts to:\n   *    Selecting a random β.\n   *    Perturbing it a bit.\n   *    Updating all the transition matrix cells that are dependent on it.\n   */\n  // TODO: Need testng\n  // TODO: Before calling sample_from_proposal() we must call\n  // AnalysisGraph::find_all_paths()\n  // TODO: Before calling sample_from_proposal(), we mush assign initial βs and\n  // run Tran_Mat_Cell::compute_cell() to initialize the first transistion\n  // matrix.\n  // TODO: Update Tran_Mat_Cell::compute_cell() to calculate the proper value.\n  // At the moment it just computes sum of length of all the paths realted to\n  // this cell\n  void sample_from_proposal();\n\n  void set_current_latent_state(int ts);\n\n  double log_normpdf(double x, double mean, double sd);\n\n  void set_log_likelihood();\n\n  double calculate_delta_log_prior();\n\n  void revert_back_to_previous_state();\n\n  /**\n   * Run Bayesian inference - sample from the posterior distribution.\n   */\n  void sample_from_posterior();\n\n  // ==========================================================================\n  // Manipulation\n  // ==========================================================================\n\n  void\n  set_indicator(std::string concept, std::string indicator, std::string source);\n\n  void delete_indicator(std::string concept, std::string indicator);\n\n  void delete_all_indicators(std::string concept);\n\n  /*\n  // TODO: Demosntrate how to use the Node::get_indicator() method\n  // with the custom exception.\n  // Not sure whether we need this method in AnalaysisGraph\n  // so that python side can directly access the Indicator class\n  // objects and maipulate them (we need to fiture out how to map a\n  // custom class from C++ into python for this) - harder\n  // or\n  // mirror getter and setter methods of the Indicator class\n  // in AnalysisGraph and make the python side call them - easier.\n  Indicator get_indicator(std::string concept, std::string indicator) {\n    try {\n      return graph[name_to_vertex.at(concept)].get_indicator(indicator);\n    } catch (const std::out_of_range &oor) {\n      fmt::print(\"Error: AnalysisGraph::get_indicator()\\n\");\n      fmt::print(\"\\tConcept: {} is not in the CAG\\n\", concept);\n    } catch (IndicatorNotFoundException &infe) {\n      std::cerr << \"Error: AnalysisGraph::get_indicator()\\n\"\n                << \"\\tindicator: \" << infe.what()\n                << \" is not attached to CAG node \" << concept << std::endl;\n    }\n  }\n  */\n\n  void replace_indicator(std::string concept,\n                         std::string indicator_old,\n                         std::string indicator_new,\n                         std::string source);\n\n  /*\n    ==========================================================================\n    Model parameterization\n    *Loren: I am going to try to port this, I'll try not to touch anything up\n    top\n    and only push changes that compile. If I do push a change that breaks things\n    you could probably just comment out this section.*\n    ==========================================================================\n  */\n\n  /**\n   * Map each concept node in the AnalysisGraph instance to one or more\n   * tangible quantities, known as 'indicators'.\n   *\n   * @param n: Int representing number of indicators to attach per node.\n   * Default is 1 since our model so far is configured for only 1 indicator per\n   * node.\n   */\n  void map_concepts_to_indicators(int n = 1);\n\n  /**\n   * Parameterize the indicators of the AnalysisGraph..\n   *\n   */\n  void parameterize(std::string country = \"South Sudan\",\n                    std::string state = \"\",\n                    std::string county = \"\",\n                    int year = 2012,\n                    int month = 1,\n                    std::map<std::string, std::string> units = {});\n\n  void print_nodes();\n\n  void print_edges();\n\n  void print_name_to_vertex();\n\n  std::pair<Agraph_t*, GVC_t*>\n  to_agraph(bool simplified_labels =\n                false, /** Whether to create simplified labels or not. */\n            int label_depth =\n                1 /** Depth in the ontology to which simplified labels extend */\n  );\n\n  std::string to_dot();\n\n  void\n  to_png(std::string filename = \"CAG.png\",\n         bool simplified_labels =\n             false, /** Whether to create simplified labels or not. */\n         int label_depth =\n             1 /** Depth in the ontology to which simplified labels extend */\n  );\n\n  void print_indicators();\n};\n", "meta": {"hexsha": "55c0fcd45643a3b33c226395240b07147b7a327a", "size": 28893, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/AnalysisGraph.hpp", "max_stars_repo_name": "mwdchang/delphi", "max_stars_repo_head_hexsha": "c6177f2d614118883eaaa7f5300f3e46f10ddc7e", "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/AnalysisGraph.hpp", "max_issues_repo_name": "mwdchang/delphi", "max_issues_repo_head_hexsha": "c6177f2d614118883eaaa7f5300f3e46f10ddc7e", "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/AnalysisGraph.hpp", "max_forks_repo_name": "mwdchang/delphi", "max_forks_repo_head_hexsha": "c6177f2d614118883eaaa7f5300f3e46f10ddc7e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-18T19:13:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-18T19:13:13.000Z", "avg_line_length": 37.5233766234, "max_line_length": 108, "alphanum_fraction": 0.6357249161, "num_tokens": 6378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.27496568816602907}}
{"text": "/*\n* Copyright (c) 2017, Chennakesava Kadapa (c.kadapa@swansea.ac.uk).\n* All rights reserved.\n* Date: 17-July-2017\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.\n* The author is not responsible for any damage.\n*\n*\n* =========================================================================\n\n* Create triangulation for the base grid and perform \n* subtriangulation for the cut-cells\n\n* distVTK\n*       type    - vtkFloatArray\n*       details - stores distance function value at a node of the background mesh\n\n* nodeInOutVTK\n*       type    - vtkIntArray\n*       details - stores true/false depending upon whether a node is inside/outside\n                these values are computed based on 'distVTK' data\n* cutCellTypeVTK\n*       type    - vtkIntArray\n*       details - stores 0/1/2 depending upon whether an element is cut or not. \n                If it is not then which domain (#1 or #2) the element belongs to.\n\n* =========================================================================\n*/\n\n#include \"headersVTK.h\"\n#include \"headersBasic.h\"\n#include \"utilfuns.h\"\n\n#include <algorithm>\n#include <iostream>\n#include <list>\n#include <vector>\n#include <fstream>\n#include <limits>\n#include <boost/foreach.hpp>\n\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/AABB_tree.h>\n#include <CGAL/AABB_traits.h>\n#include <CGAL/AABB_triangle_primitive.h>\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/boost/graph/graph_traits_Polyhedron_3.h>\n#include <CGAL/AABB_face_graph_triangle_primitive.h>\n#include <CGAL/Side_of_triangle_mesh.h>\n \n\n\ntypedef CGAL::Simple_cartesian<double> K;\n//typedef CGAL::Exact_predicates_exact_constructions_kernel K;\n\ntypedef K::FT FT;\ntypedef K::Ray_3 Ray;\ntypedef K::Line_3 Line;\ntypedef K::Point_3 Point;\ntypedef K::Segment_3 Segment;\ntypedef K::Triangle_3 Triangle;\n//typedef std::list<Triangle>::iterator Iterator;\n//typedef CGAL::AABB_triangle_primitive<K, Iterator> Primitive;\n//typedef CGAL::AABB_traits<K, Primitive> AABB_triangle_traits;\n//typedef CGAL::AABB_tree<AABB_triangle_traits> Tree;\n\ntypedef CGAL::Polyhedron_3<K> Polyhedron;\ntypedef CGAL::AABB_face_graph_triangle_primitive<Polyhedron> Primitive;\ntypedef CGAL::AABB_traits<K, Primitive> Traits;\ntypedef CGAL::AABB_tree<Traits> Tree;\n\ntypedef CGAL::Side_of_triangle_mesh<Polyhedron, K> Point_inside;\n\ntypedef Polyhedron::HalfedgeDS  HalfedgeDS;\n\n\n// A modifier creating a triangle with the incremental builder.\ntemplate<class HDS>\nclass polyhedron_builder : public CGAL::Modifier_base<HDS>\n{\n  public:\n    std::vector<Point> &vertices;\n    std::vector<int>    &faces;\n    int  elType;\n\n    polyhedron_builder( std::vector<Point> &_coords, std::vector<int> &_tris, int eT=3 ) : vertices(_coords), faces(_tris), elType(eT) {}\n    \n    void operator()( HDS& hds)\n    {\n        typedef typename HDS::Vertex   Vertex;\n        typedef typename Vertex::Point Point;\n \n        // create a cgal incremental builder\n        CGAL::Polyhedron_incremental_builder_3<HDS> B( hds, true);\n        \n        if(elType == 3)\n          B.begin_surface( vertices.size(), faces.size()/3 );\n        else\n          B.begin_surface( vertices.size(), faces.size()/4 );\n\n       // add the polyhedron vertices\n       for( int i=0; i<(int)vertices.size(); i++ )\n       {\n         B.add_vertex(vertices[i]);\n         //B.add_vertex( Point( coords[i+0], coords[i+1], coords[i+2] ) );\n       }\n   \n       // add the polyhedron triangles\n\n       if(elType == 3)\n       {\n         for( int i=0; i<(int)faces.size(); i+=3 )\n         {\n           B.begin_facet();\n           B.add_vertex_to_facet( faces[i+0] );\n           B.add_vertex_to_facet( faces[i+1] );\n           B.add_vertex_to_facet( faces[i+2] );\n           B.end_facet();\n         }\n       }\n       else\n       {\n         for( int i=0; i<(int)faces.size(); i+=4 )\n         {\n           B.begin_facet();\n           B.add_vertex_to_facet( faces[i+0] );\n           B.add_vertex_to_facet( faces[i+1] );\n           B.add_vertex_to_facet( faces[i+3] );\n           B.end_facet();\n\n           B.begin_facet();\n           B.add_vertex_to_facet( faces[i+0] );\n           B.add_vertex_to_facet( faces[i+3] );\n           B.add_vertex_to_facet( faces[i+2] );\n           B.end_facet();\n         }\n       }\n\n       // finish up the surface\n       B.end_surface();\n    }\n};\n\n\n\nPoint_inside*  createPointer1(std::vector<Point> &vertices, std::vector<int> &faces, int eT=3)\n{\n    // build a polyhedron from the loaded arrays\n    Polyhedron  polyhedronTemp;\n    polyhedron_builder<HalfedgeDS>  poly_builder( vertices, faces, eT );\n    polyhedronTemp.delegate( poly_builder );\n\n    Tree tree;\n    tree.insert(polyhedronTemp.facets_begin(), polyhedronTemp.facets_end(), polyhedronTemp);\n\n    Point_inside*  inside_tester = new Point_inside(tree);\n    \n    return inside_tester;\n}\n\n\nPoint_inside*  createPointer2(Polyhedron& polyhedronTemp)\n{\n    Tree tree;\n    tree.insert(polyhedronTemp.facets_begin(), polyhedronTemp.facets_end(), polyhedronTemp);\n\n    Point_inside*  inside_tester = new Point_inside(tree);\n    \n    return inside_tester;\n}\n\n\ninline Point_inside*  createPointer3(Tree& tree)\n{\n    Point_inside*  inside_tester = new Point_inside(tree);\n    \n    return inside_tester;\n}\n\n\n\nusing namespace std;\n\n\nint main(int argc, char* argv[])\n{\n    //////////////////////////////////////////////\n    //\n    // declare vtk variables\n    //\n    //////////////////////////////////////////////\n\n    vtkSmartPointer<vtkDataSetMapper>        mapperVTK    =  vtkSmartPointer<vtkDataSetMapper>::New();\n    vtkSmartPointer<vtkUnstructuredGrid>     uGridVTK     =  vtkSmartPointer<vtkUnstructuredGrid>::New();\n    vtkSmartPointer<vtkPoints>               pointsGrid   =  vtkSmartPointer<vtkPoints>::New();\n    vtkSmartPointer<vtkPoints>               pointsVTK2   =  vtkSmartPointer<vtkPoints>::New();\n    vtkSmartPointer<vtkVertex>               vertexVTK    =  vtkSmartPointer<vtkVertex>::New();\n    vtkSmartPointer<vtkLine>                 lineVTK      =  vtkSmartPointer<vtkLine>::New();\n    vtkSmartPointer<vtkQuad>                 quadVTK      =  vtkSmartPointer<vtkQuad>::New();\n    vtkSmartPointer<vtkHexahedron>           hexVTK       =  vtkSmartPointer<vtkHexahedron>::New();\n    vtkSmartPointer<vtkTriangle>             triaVTK      =  vtkSmartPointer<vtkTriangle>::New();\n    vtkSmartPointer<vtkPolygon>              polygonVTK   =  vtkSmartPointer<vtkPolygon>::New();\n    vtkSmartPointer<vtkTetra>                tetraVTK     =  vtkSmartPointer<vtkTetra>::New();\n    vtkSmartPointer<vtkPyramid>              pyramidVTK   =  vtkSmartPointer<vtkPyramid>::New();\n    vtkSmartPointer<vtkWedge>                wedgeVTK     =  vtkSmartPointer<vtkWedge>::New();\n\n    vtkSmartPointer<vtkIntArray>          nodeInOutVTK       =  vtkSmartPointer<vtkIntArray>::New();\n    vtkSmartPointer<vtkIntArray>          cutCellTypeVTK       =  vtkSmartPointer<vtkIntArray>::New();\n    vtkSmartPointer<vtkIntArray>          cellOrientationVTK    =  vtkSmartPointer<vtkIntArray>::New();\n    vtkSmartPointer<vtkIntArray>          cellOrientationVTK2    =  vtkSmartPointer<vtkIntArray>::New();\n    vtkSmartPointer<vtkFloatArray>          vecVTK       =  vtkSmartPointer<vtkFloatArray>::New();\n    vtkSmartPointer<vtkFloatArray>          vecVTK2       =  vtkSmartPointer<vtkFloatArray>::New();\n    vtkSmartPointer<vtkFloatArray>          distVTK       =  vtkSmartPointer<vtkFloatArray>::New();\n    vtkSmartPointer<vtkFloatArray>          scaVTK2       =  vtkSmartPointer<vtkFloatArray>::New();\n    vtkSmartPointer<vtkFloatArray>          cellDataVTK       =  vtkSmartPointer<vtkFloatArray>::New();\n    vtkSmartPointer<vtkFloatArray>          cellDataVTK2       =  vtkSmartPointer<vtkFloatArray>::New();\n    vtkSmartPointer<vtkExtractEdges>     extractEdgesVTK  =    vtkSmartPointer<vtkExtractEdges>::New();\n\n    vtkSmartPointer<vtkUnstructuredGrid> uGrid   =  vtkSmartPointer<vtkUnstructuredGrid>::New();\n    vtkSmartPointer<vtkUnstructuredGrid> uGrid2  =  vtkSmartPointer<vtkUnstructuredGrid>::New();\n\n    vtkSmartPointer<vtkPoints>              pointsPoly  =  vtkSmartPointer<vtkPoints>::New();\n\n    // Add the polygon to a list of polygons\n    vtkSmartPointer<vtkCellArray> polyList  =   vtkSmartPointer<vtkCellArray>::New();\n\n    // Create a PolyData\n    vtkSmartPointer<vtkPolyData> polyData =   vtkSmartPointer<vtkPolyData>::New();\n    vtkSmartPointer<vtkPolyData> polyData2 =   vtkSmartPointer<vtkPolyData>::New();\n\n    vtkSmartPointer<vtkXMLUnstructuredGridWriter>  writerUGridVTK =  vtkSmartPointer<vtkXMLUnstructuredGridWriter>::New();\n    vtkSmartPointer<vtkXMLPolyDataWriter>  writerPolyData =     vtkSmartPointer<vtkXMLPolyDataWriter>::New();\n    vtkSmartPointer<vtkXMLUnstructuredGridWriter>  writeruGrid   =  vtkSmartPointer<vtkXMLUnstructuredGridWriter>::New();\n    vtkSmartPointer<vtkXMLUnstructuredGridWriter>  writeruGrid2  =  vtkSmartPointer<vtkXMLUnstructuredGridWriter>::New();\n\n    vtkSmartPointer<vtkMergePoints> mergePoints =     vtkSmartPointer<vtkMergePoints>::New();\n\n\n    //////////////////////////////////////////////\n    //\n    // generate base triangulation\n    //\n    //////////////////////////////////////////////\n\n    double  x0, x1, y0, y1, z0, z1;\n\n    int nEx, nEy, nEz, nNx, nNy, nNz, nNode, nElem;\n\n    x0 = -1.6;    x1 =  1.6;    nEx = 50;\n    y0 = -1.6;    y1 =  1.6;    nEy = 50;\n    z0 = -1.6;    z1 =  1.6;    nEz = 50;\n\n/*\n    if(argc == 0)\n      cerr << \" Input data \" << endl;\n    else\n    {\n       x0  = atof(argv[1]);\n       x1  = atof(argv[2]);\n       nEx = atoi(argv[3]);\n\n       y0  = atof(argv[4]);\n       y1  = atof(argv[5]);\n       nEy = atoi(argv[6]);\n\n       z0  = atof(argv[7]);\n       z1  = atof(argv[8]);\n       nEz = atoi(argv[9]);\n    }\n*/\n    nElem = nEx*nEy*nEz;\n\n    nNx = nEx+1;\n    nNy = nEy+1;\n    nNz = nEz+1;\n\n    nNode = nNx*nNy*nNz;\n\n\n    uGridVTK->Reset();\n    pointsGrid->Reset();\n    cellDataVTK->Reset();\n    cellDataVTK->Reset();\n    cutCellTypeVTK->Reset();\n    nodeInOutVTK->Reset();\n\n    int  ii, jj, kk, ll, n1, n2, n3, n4, nn;\n    int  ind, ind1, ind2, ind3, ind4, ind5, ind6;\n\n    double dx = (x1-x0)/nEx;\n    double dy = (y1-y0)/nEy;\n    double dz = (z1-z0)/nEz;\n    double xx, yy, zz, fact;\n\n    cout << x0 << '\\t' << x1 << '\\t' << dx << endl;\n    cout << y0 << '\\t' << y1 << '\\t' << dy << endl;\n    cout << z0 << '\\t' << z1 << '\\t' << dz << endl;\n\n\n    vtkIdType pts[10];\n\n    distVTK->SetName(\"dist\");\n    distVTK->SetNumberOfTuples(nNode);\n    nodeInOutVTK->SetName(\"InOut\");\n    nodeInOutVTK->SetNumberOfTuples(nNode);\n    cutCellTypeVTK->SetName(\"cellType\");\n    cutCellTypeVTK->SetNumberOfTuples(nElem);\n    cellOrientationVTK->SetName(\"elType\");\n    cellOrientationVTK->SetNumberOfTuples(nElem);\n    cellOrientationVTK2->SetName(\"elType\");\n    cellOrientationVTK2->SetNumberOfTuples(nElem);\n\n    //////////////////////////////////////////////\n    //\n    // create nodes/points\n    //\n    //////////////////////////////////////////////\n\n    ind = 0;\n    zz = z0;\n    for(kk=0; kk<nNz; kk++)\n    {\n      yy = y0;\n      for(jj=0;jj<nNy;jj++)\n      {\n        xx = x0;\n        for(ii=0;ii<nNx;ii++)\n        {\n          pts[0] = pointsGrid->InsertNextPoint(xx, yy, zz);\n\n          //distVTK->SetTuple1(ind, fact);\n          //nodeInOutVTK->SetTuple1(ind, (fact >= 0.0));\n\n          xx += dx;\n          ind++;\n        }\n        yy += dy;\n      }\n      zz += dz;\n    }\n\n\n    ////////////////////////////////////////////////\n    ////////////////////////////////////////////////\n    //\n    // read the surface and generate polydata\n    //\n    ////////////////////////////////////////////////\n    ////////////////////////////////////////////////\n\n    //char infile_nodes[]=\"sphere-nodes.dat\";\n    //char infile_trias[]=\"sphere-trias.dat\";\n\n    //char infile_nodes[]=\"reliefvalve3Dblock-nodes.dat\";\n    //char infile_trias[]=\"reliefvalve3Dblock-trias.dat\";\n\n    //char infile_nodes[]=\"turekbeam3d-nodes.dat\";\n    //char infile_trias[]=\"turekbeam3d-quads.dat\";\n\n    char infile_nodes[]=\"thickplate-nodes.dat\";\n    char infile_trias[]=\"thickplate-elems.dat\";\n\n\n    ifstream  infile(infile_nodes);\n\n    if(infile.fail())\n    {\n      cout << \" Could not open the input file\" << endl;\n      exit(1);\n    }\n\n\n    double  val[10];\n\n    vtkIdType pt[12];\n\n    while(infile >> val[0] >> val[1] >> val[2] >> val[3])\n    {\n       //printf(\"%12.6f \\t %12.6f \\t %12.6f \\n\", val[0], val[1], val[2]);\n\n       pt[0] = pointsPoly->InsertNextPoint(val[1], val[2], val[3]);\n    }\n\n    ifstream  infile2(infile_trias);\n\n    if(infile2.fail())\n    {\n       cout << \" Could not open the input file\" << endl;\n      exit(1);\n    }\n\n    int  valInt[10], ETYPE=4;\n\n    if(ETYPE==3)\n    {\n      while(infile2 >> valInt[0] >> valInt[1] >> valInt[2] >> valInt[3] >> valInt[4])\n      {\n        //printf(\"%12.6f \\t %12.6f \\t %12.6f \\n\", valInt[0], valInt[1], valInt[2]);\n       \n        polygonVTK->GetPointIds()->SetNumberOfIds(3); //make a triangle\n\n        polygonVTK->GetPointIds()->SetId(0, valInt[2]-1);\n        polygonVTK->GetPointIds()->SetId(1, valInt[3]-1);\n        polygonVTK->GetPointIds()->SetId(2, valInt[4]-1);\n\n        polyList->InsertNextCell(polygonVTK);\n      }\n    }\n    else\n    {\n      while(infile2 >> valInt[0] >> valInt[1] >> valInt[2] >> valInt[3] >> valInt[4] >> valInt[5])\n      {\n        //printf(\"%12.6f \\t %12.6f \\t %12.6f \\n\", valInt[0], valInt[1], valInt[2]);\n       \n        //polygonVTK->GetPointIds()->SetNumberOfIds(4); //make a quad\n\n        //polygonVTK->GetPointIds()->SetId(0, valInt[2]-1);\n        //polygonVTK->GetPointIds()->SetId(1, valInt[3]-1);\n        //polygonVTK->GetPointIds()->SetId(2, valInt[5]-1);\n        //polygonVTK->GetPointIds()->SetId(3, valInt[4]-1);\n\n        polygonVTK->GetPointIds()->SetNumberOfIds(3); //make a triangle\n\n        polygonVTK->GetPointIds()->SetId(0, valInt[2]-1);\n        polygonVTK->GetPointIds()->SetId(1, valInt[3]-1);\n        polygonVTK->GetPointIds()->SetId(2, valInt[5]-1);\n\n        polyList->InsertNextCell(polygonVTK);\n\n        polygonVTK->GetPointIds()->SetNumberOfIds(3); //make a triangle\n\n        polygonVTK->GetPointIds()->SetId(0, valInt[2]-1);\n        polygonVTK->GetPointIds()->SetId(1, valInt[5]-1);\n        polygonVTK->GetPointIds()->SetId(2, valInt[4]-1);\n\n        polyList->InsertNextCell(polygonVTK);\n      }\n    }\n\n    polyData->SetPoints(pointsPoly);\n    polyData->SetPolys(polyList);\n\n    writerPolyData->SetFileName(\"immersedpoly.vtp\");\n    writerPolyData->SetInputData(polyData);\n    writerPolyData->Write();\n\n    /////////////////////////////////////////////////////\n    /////////////////////////////////////////////////////\n    //\n    // compute using VTK\n    //\n    /////////////////////////////////////////////////////\n    /////////////////////////////////////////////////////\n\n    time_t tstart, tend;\n\n    tstart = time(0);\n\n\n    vtkSmartPointer<vtkPolyData> pointsPolydataVTK   =   vtkSmartPointer<vtkPolyData>::New();\n    pointsPolydataVTK->SetPoints(pointsGrid);\n\n    vtkSmartPointer<vtkSelectEnclosedPoints> selectEnclosedPoints = vtkSmartPointer<vtkSelectEnclosedPoints>::New();\n\n    selectEnclosedPoints->SetInputData(pointsPolydataVTK);\n    selectEnclosedPoints->SetTolerance(0.00001);\n    selectEnclosedPoints->Initialize(polyData);\n\n\n    //////////////////////////////////////////////\n    //\n    // create cells/elements\n    //\n    //////////////////////////////////////////////\n\n    double  bnds[6];\n    bool flag;\n    double ptTemp[3];\n\n    vector<int>  ff(8);\n\n    vtkIdType npts=3, cellId, cellId2, type, id;\n    vtkCell  *cellVTK, *cellVTK2;\n\n    cout << \" AAAAAAAAAAAAA \" << endl;\n\n    nn = nNx*nNy;\n\n    cellId = 0;\n    ind=0;\n    for(kk=0; kk<nEz; kk++)\n    {\n      ind5 = nn*kk;\n      ind6 = nn*(kk+1);\n\n      for(jj=0; jj<nEy; jj++)\n      {\n        ind1 = ind5 + nNx*jj;\n        ind2 = ind5 + nNx*(jj+1);\n\n        ind3 = ind6 + nNx*jj;\n        ind4 = ind6 + nNx*(jj+1);\n\n        for(ii=0;ii<nEx;ii++)\n        {\n          pts[0] = ind1+ii;          pts[4] = ind3+ii;\n          pts[1] = pts[0]+1;         pts[5] = pts[4]+1;\n          pts[3] = ind2+ii;          pts[7] = ind4+ii;\n          pts[2] = pts[3]+1;         pts[6] = pts[7]+1;\n\n          ff.assign(8,0);\n\n          for(ll=0;ll<8;ll++)\n          {\n            hexVTK->GetPointIds()->SetId(ll, pts[ll]);\n            //cout << ll << '\\t' << pts[ll] << endl;\n            pointsGrid->GetPoint(pts[ll], ptTemp);\n            //ff[ll] = selectEnclosedPoints->IsInside(pts[ll]);\n            ff[ll] = selectEnclosedPoints->IsInsideSurface(ptTemp[0], ptTemp[1], ptTemp[2]);\n            //cout << ptTemp[0] << '\\t' << ptTemp[1] << '\\t' << ptTemp[2] << '\\t' << ff[ll] << endl;\n          }\n\n          uGrid->InsertNextCell(hexVTK->GetCellType(), hexVTK->GetPointIds());\n\n          flag = std::equal( ff.begin()+1, ff.end(), ff.begin() );\n\n          if( flag )\n          {\n            cellOrientationVTK->SetTuple1(cellId, ff[0]);\n          }\n          else\n          {\n            cellOrientationVTK->SetTuple1(cellId, -1);\n          }\n\n          cellId++;\n        }\n      }\n    }\n\n    //////////////////////////////////////////////\n    //\n    // setup and write grid data\n    //\n    //////////////////////////////////////////////\n\n    char fname1[50];\n    sprintf(fname1,\"%s%d%s\", \"cutFEMhex-vtk-\",nEx,\".vtu\");\n\n    uGrid->SetPoints(pointsGrid);\n//    uGrid->GetPointData()->SetScalars(distVTK);\n//    uGrid->GetPointData()->AddArray(nodeInOutVTK);\n\n    cout << \" uGrid->GetNumberOfPoints() = \" <<  uGrid->GetNumberOfPoints() << endl;\n    cout << \" uGrid->GetNumberOfCells()  = \" <<  uGrid->GetNumberOfCells() << endl;\n\n    uGrid->GetCellData()->SetScalars(cellOrientationVTK);\n\n    writeruGrid->SetFileName(fname1);\n    writeruGrid->SetInputData(uGrid);\n    writeruGrid->Write();\n\n    tend = time(0); \n    cout << \"Time taken = \"<< difftime(tend, tstart) <<\" second(s).\"<< endl;\n\n    //////////////////////////////////////////////////////\n    //////////////////////////////////////////////////////\n    //\n    // compute using CGAL\n    //\n    //////////////////////////////////////////////////////\n    //////////////////////////////////////////////////////\n\n    tstart = time(0); \n\n    /*\n    ifstream  infile3(infile_nodes);\n    \n    if(infile3.fail())\n    {\n      cout << \" Could not open the input file\" << endl;\n      exit(1);\n    }\n\n    std::vector<Point> pointsCGAL;\n\n    while(infile3 >> val[0] >> val[1] >> val[2] >> val[3])\n    {\n      Point a(val[1], val[2], val[3]);\n      pointsCGAL.push_back(a);\n    }\n\n    ifstream  infile4(infile_trias);\n\n    if(infile4.fail())\n    {\n      cout << \" Could not open the input file\" << endl;\n      exit(1);\n    }\n\n    std::list<Triangle> triangles;\n\n    if(ETYPE==3)\n    {\n      while(infile4 >> valInt[0] >> valInt[1] >> valInt[2] >> valInt[3] >> valInt[4])\n      {\n        triangles.push_back(Triangle(pointsCGAL[valInt[2]-1], pointsCGAL[valInt[3]-1], pointsCGAL[valInt[4]-1]));\n      }\n    }\n    else\n    {\n      while(infile4 >> valInt[0] >> valInt[1] >> valInt[2] >> valInt[3] >> valInt[4] >> valInt[5])\n      {\n        triangles.push_back(Triangle(pointsCGAL[valInt[2]-1], pointsCGAL[valInt[3]-1], pointsCGAL[valInt[5]-1]));\n        triangles.push_back(Triangle(pointsCGAL[valInt[2]-1], pointsCGAL[valInt[5]-1], pointsCGAL[valInt[4]-1]));\n      }\n    }\n    */\n\n    ifstream  infile3(infile_nodes);\n    \n    if(infile3.fail())\n    {\n      cout << \" Could not open the input file\" << endl;\n      exit(1);\n    }\n\n    // create a cgal incremental builder\n\n    //vector<double>  vertices;\n    vector<Point> vertices;\n   \n    // add the polyhedron vertices\n    while(infile3 >> val[0] >> val[1] >> val[2] >> val[3])\n    {\n      //vertices.push_back(val[1]);\n      //vertices.push_back(val[2]);\n      //vertices.push_back(val[3]);\n\n      vertices.push_back(Point(val[1], val[2], val[3]));\n    }\n   \n    ifstream  infile4(infile_trias);\n\n    if(infile4.fail())\n    {\n      cout << \" Could not open the input file\" << endl;\n      exit(1);\n    }\n    \n    vector<int>  faces;\n\n    // add the polyhedron triangles\n    if(ETYPE==3)\n    {\n      while(infile4 >> valInt[0] >> valInt[1] >> valInt[2] >> valInt[3] >> valInt[4])\n      {\n        faces.push_back(valInt[2]-1);\n        faces.push_back(valInt[3]-1);\n        faces.push_back(valInt[4]-1);\n      }\n    }\n    else\n    {\n      while(infile4 >> valInt[0] >> valInt[1] >> valInt[2] >> valInt[3] >> valInt[4] >> valInt[5])\n      {\n        faces.push_back(valInt[2]-1);\n        faces.push_back(valInt[3]-1);\n        faces.push_back(valInt[4]-1);\n        faces.push_back(valInt[5]-1);\n      }\n    }\n    \n    /*\n    // build a polyhedron from the loaded arrays\n    Polyhedron  polyhedronTemp;\n    polyhedron_builder<HalfedgeDS>  poly_builder( vertices, faces, ETYPE );\n    polyhedronTemp.delegate( poly_builder );\n\n\n    // constructs AABB tree\n    //Tree tree(polyhedronTemp.facets_begin(), polyhedronTemp.facets_end(), polyhedronTemp);\n\n    Tree tree;\n    tree.insert(polyhedronTemp.facets_begin(), polyhedronTemp.facets_end(), polyhedronTemp);\n\n    //Point_inside inside_tester(tree);\n\n    Point_inside  *inside_tester;\n    inside_tester = new Point_inside(tree);\n    */\n\n    Point_inside  *inside_tester;\n\n    \n    // function #1 ... does not work\n    //inside_tester = createPointer1(vertices, faces, ETYPE);\n\n\n    // function #2 ... does not work\n    Polyhedron  polyhedronTemp;\n    polyhedron_builder<HalfedgeDS>  poly_builder( vertices, faces, ETYPE );\n    polyhedronTemp.delegate( poly_builder );\n\n    //inside_tester = createPointer2(polyhedronTemp);\n\n    // function #3\n\n    Tree tree;\n    tree.insert(polyhedronTemp.facets_begin(), polyhedronTemp.facets_end(), polyhedronTemp);\n\n    inside_tester = createPointer3(tree);\n\n\n\n    int nints;\n    nn = nNx*nNy;\n\n    cellId = 0;\n    ind=0;\n    for(kk=0; kk<nEz; kk++)\n    {\n      ind5 = nn*kk;\n      ind6 = nn*(kk+1);\n\n      for(jj=0; jj<nEy; jj++)\n      {\n        ind1 = ind5 + nNx*jj;\n        ind2 = ind5 + nNx*(jj+1);\n\n        ind3 = ind6 + nNx*jj;\n        ind4 = ind6 + nNx*(jj+1);\n\n        for(ii=0;ii<nEx;ii++)\n        {\n          pts[0] = ind1+ii;          pts[4] = ind3+ii;\n          pts[1] = pts[0]+1;         pts[5] = pts[4]+1;\n          pts[3] = ind2+ii;          pts[7] = ind4+ii;\n          pts[2] = pts[3]+1;         pts[6] = pts[7]+1;\n\n          ff.assign(8,0);\n\n          for(ll=0;ll<8;ll++)\n          {\n            hexVTK->GetPointIds()->SetId(ll, pts[ll]);\n\n            //cout << ll << '\\t' << pts[ll] << endl;\n\n            pointsGrid->GetPoint(pts[ll], ptTemp);\n\n            //Point  ray_begin(ptTemp[0], ptTemp[1], ptTemp[2]);\n            //Point  ray_end(10.0, ptTemp[1], ptTemp[2]);\n\n            //FT sqd = tree.squared_distance(ray_begin);\n            //cout << \" sqd = \" << sqd << endl;\n            //ff[ll] = (sqd >= 0.0);\n\n            //count number of intersections\n            //Ray ray_query(ray_begin, ray_end);\n            //Segment segment_query(ray_begin, ray_end);\n\n            //ff[ll] = tree.number_of_intersected_primitives(Ray(ray_begin, ray_end)) % 2;\n            //ff[ll] = tree.number_of_intersected_primitives(segment_query) % 2;\n\n            //ff[ll] = tree.number_of_intersected_primitives(Ray(\n            //              Point(ptTemp[0], ptTemp[1], ptTemp[2]), \n            //              Point(100.0, ptTemp[1], ptTemp[2]))) % 2;\n\n\n            CGAL::Bounded_side res = (*inside_tester)(Point(ptTemp[0], ptTemp[1], ptTemp[2]));\n\n            if( (res == CGAL::ON_BOUNDED_SIDE) || (res == CGAL::ON_BOUNDARY) )\n            {\n              ff[ll] = 1;\n            }\n            else\n            {\n              ff[ll] = 0;\n            }\n\n          }\n\n          flag = std::equal( ff.begin()+1, ff.end(), ff.begin() );\n\n          if( flag )\n          {\n            if(ff[0] == 0)\n            {\n              uGrid2->InsertNextCell(hexVTK->GetCellType(), hexVTK->GetPointIds());\n              cellOrientationVTK2->SetTuple1(cellId, ff[0]);\n              cellId++;\n            }\n          }\n          else\n          {\n            uGrid2->InsertNextCell(hexVTK->GetCellType(), hexVTK->GetPointIds());\n            cellOrientationVTK2->SetTuple1(cellId, -1);\n            cellId++;\n          }\n        }\n      }\n    }\n\n    //////////////////////////////////////////////\n    //\n    // setup and write polyData\n    //\n    //////////////////////////////////////////////\n\n    char fname2[50];\n    sprintf(fname2,\"%s%d%s\", \"cutFEMhex-cgal-\",nEx,\".vtu\");\n\n    uGrid2->SetPoints(pointsGrid);\n//    uGrid->GetPointData()->SetScalars(distVTK);\n//    uGrid->GetPointData()->AddArray(nodeInOutVTK);\n\n    cout << \" uGrid2->GetNumberOfPoints() = \" <<  uGrid2->GetNumberOfPoints() << endl;\n    cout << \" uGrid2->GetNumberOfCells()  = \" <<  uGrid2->GetNumberOfCells() << endl;\n\n    uGrid2->GetCellData()->SetScalars(cellOrientationVTK2);\n\n    writeruGrid->SetFileName(fname2);\n    writeruGrid->SetInputData(uGrid2);\n    writeruGrid->Write();\n\n    tend = time(0); \n    cout << \"Time taken = \"<< difftime(tend, tstart) <<\" second(s).\"<< endl;\n\n  return 0;\n}\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "0fb191a6ba194163096ea7e2a98fb387417759fe", "size": 25129, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cutfem3dv1.cpp", "max_stars_repo_name": "chennachaos/CutCellCGAL", "max_stars_repo_head_hexsha": "98d68d4e9fef2c81680667352cd7398cd645ff06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-09T12:24:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T12:24:04.000Z", "max_issues_repo_path": "src/cutfem3dv1.cpp", "max_issues_repo_name": "chennachaos/CutCellCGAL", "max_issues_repo_head_hexsha": "98d68d4e9fef2c81680667352cd7398cd645ff06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cutfem3dv1.cpp", "max_forks_repo_name": "chennachaos/CutCellCGAL", "max_forks_repo_head_hexsha": "98d68d4e9fef2c81680667352cd7398cd645ff06", "max_forks_repo_licenses": ["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.7033096927, "max_line_length": 137, "alphanum_fraction": 0.5566874925, "num_tokens": 7048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2748883140527327}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl\n Copyright (C) 2003, 2004, 2005, 2006, 2007 StatPro Italia srl\n Copyright (C) 2006, 2008 Ferdinando Ametrano\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 vanillaswap.hpp\n    \\brief Simple fixed-rate vs Libor swap\n*/\n\n#ifndef quantlib_vanilla_swap_hpp\n#define quantlib_vanilla_swap_hpp\n\n#include <ql/instruments/swap.hpp>\n#include <ql/time/daycounter.hpp>\n#include <ql/time/schedule.hpp>\n#include <boost/optional.hpp>\n\nnamespace QuantLib {\n\n    class IborIndex;\n\n    //! Plain-vanilla swap: fix vs floating leg\n    /*! \\ingroup instruments\n\n        If no payment convention is passed, the convention of the\n        floating-rate schedule is used.\n\n        \\warning if <tt>Settings::includeReferenceDateCashFlows()</tt>\n                 is set to <tt>true</tt>, payments occurring at the\n                 settlement date of the swap might be included in the\n                 NPV and therefore affect the fair-rate and\n                 fair-spread calculation. This might not be what you\n                 want.\n\n        \\test\n        - the correctness of the returned value is tested by checking\n          that the price of a swap paying the fair fixed rate is null.\n        - the correctness of the returned value is tested by checking\n          that the price of a swap receiving the fair floating-rate\n          spread is null.\n        - the correctness of the returned value is tested by checking\n          that the price of a swap decreases with the paid fixed rate.\n        - the correctness of the returned value is tested by checking\n          that the price of a swap increases with the received\n          floating-rate spread.\n        - the correctness of the returned value is tested by checking\n          it against a known good value.\n    */\n    class VanillaSwap : public Swap {\n      public:\n        class arguments;\n        class results;\n        class engine;\n        VanillaSwap(Type type,\n                    Real nominal,\n                    Schedule fixedSchedule,\n                    Rate fixedRate,\n                    DayCounter fixedDayCount,\n                    Schedule floatSchedule,\n                    ext::shared_ptr<IborIndex> iborIndex,\n                    Spread spread,\n                    DayCounter floatingDayCount,\n                    boost::optional<BusinessDayConvention> paymentConvention = boost::none,\n                    boost::optional<bool> useIndexedCoupons = boost::none);\n        //! \\name Inspectors\n        //@{\n        Type type() const;\n        Real nominal() const;\n\n        const Schedule& fixedSchedule() const;\n        Rate fixedRate() const;\n        const DayCounter& fixedDayCount() const;\n\n        const Schedule& floatingSchedule() const;\n        const ext::shared_ptr<IborIndex>& iborIndex() const;\n        Spread spread() const;\n        const DayCounter& floatingDayCount() const;\n\n        BusinessDayConvention paymentConvention() const;\n\n        const Leg& fixedLeg() const;\n        const Leg& floatingLeg() const;\n        //@}\n\n        //! \\name Results\n        //@{\n        Real fixedLegBPS() const;\n        Real fixedLegNPV() const;\n        Rate fairRate() const;\n\n        Real floatingLegBPS() const;\n        Real floatingLegNPV() const;\n        Spread fairSpread() const;\n        //@}\n        // other\n        void setupArguments(PricingEngine::arguments* args) const override;\n        void fetchResults(const PricingEngine::results*) const override;\n\n      private:\n        void setupExpired() const override;\n        Type type_;\n        Real nominal_;\n        Schedule fixedSchedule_;\n        Rate fixedRate_;\n        DayCounter fixedDayCount_;\n        Schedule floatingSchedule_;\n        ext::shared_ptr<IborIndex> iborIndex_;\n        Spread spread_;\n        DayCounter floatingDayCount_;\n        BusinessDayConvention paymentConvention_;\n        // results\n        mutable Rate fairRate_;\n        mutable Spread fairSpread_;\n    };\n\n\n    //! %Arguments for simple swap calculation\n    class VanillaSwap::arguments : public Swap::arguments {\n      public:\n        arguments() : nominal(Null<Real>()) {}\n        Type type = Receiver;\n        Real nominal;\n\n        std::vector<Date> fixedResetDates;\n        std::vector<Date> fixedPayDates;\n        std::vector<Time> floatingAccrualTimes;\n        std::vector<Date> floatingResetDates;\n        std::vector<Date> floatingFixingDates;\n        std::vector<Date> floatingPayDates;\n\n        std::vector<Real> fixedCoupons;\n        std::vector<Spread> floatingSpreads;\n        std::vector<Real> floatingCoupons;\n        void validate() const override;\n    };\n\n    //! %Results from simple swap calculation\n    class VanillaSwap::results : public Swap::results {\n      public:\n        Rate fairRate;\n        Spread fairSpread;\n        void reset() override;\n    };\n\n    class VanillaSwap::engine : public GenericEngine<VanillaSwap::arguments,\n                                                     VanillaSwap::results> {};\n\n\n    // inline definitions\n\n    inline Swap::Type VanillaSwap::type() const {\n        return type_;\n    }\n\n    inline Real VanillaSwap::nominal() const {\n        return nominal_;\n    }\n\n    inline const Schedule& VanillaSwap::fixedSchedule() const {\n        return fixedSchedule_;\n    }\n\n    inline Rate VanillaSwap::fixedRate() const {\n        return fixedRate_;\n    }\n\n    inline const DayCounter& VanillaSwap::fixedDayCount() const {\n        return fixedDayCount_;\n    }\n\n    inline const Schedule& VanillaSwap::floatingSchedule() const {\n        return floatingSchedule_;\n    }\n\n    inline const ext::shared_ptr<IborIndex>& VanillaSwap::iborIndex() const {\n        return iborIndex_;\n    }\n\n    inline Spread VanillaSwap::spread() const {\n        return spread_;\n    }\n\n    inline const DayCounter& VanillaSwap::floatingDayCount() const {\n        return floatingDayCount_;\n    }\n\n    inline BusinessDayConvention VanillaSwap::paymentConvention() const {\n        return paymentConvention_;\n    }\n\n    inline const Leg& VanillaSwap::fixedLeg() const {\n        return legs_[0];\n    }\n\n    inline const Leg& VanillaSwap::floatingLeg() const {\n        return legs_[1];\n    }\n\n}\n\n#endif\n", "meta": {"hexsha": "60fdf947aeb531efdcb3a3c0e523566365ecba04", "size": 6901, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/instruments/vanillaswap.hpp", "max_stars_repo_name": "jiangjiali/QuantLib", "max_stars_repo_head_hexsha": "37c98eccfa18a95acb1e98b276831641be92b38e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3358.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T02:56:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T02:42:47.000Z", "max_issues_repo_path": "ql/instruments/vanillaswap.hpp", "max_issues_repo_name": "jiangjiali/QuantLib", "max_issues_repo_head_hexsha": "37c98eccfa18a95acb1e98b276831641be92b38e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 965.0, "max_issues_repo_issues_event_min_datetime": "2015-12-21T10:35:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T02:47:00.000Z", "max_forks_repo_path": "ql/instruments/vanillaswap.hpp", "max_forks_repo_name": "jiangjiali/QuantLib", "max_forks_repo_head_hexsha": "37c98eccfa18a95acb1e98b276831641be92b38e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1663.0, "max_forks_repo_forks_event_min_datetime": "2015-12-17T17:45:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:58:29.000Z", "avg_line_length": 31.6559633028, "max_line_length": 91, "alphanum_fraction": 0.636429503, "num_tokens": 1460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2747723658559566}}
{"text": "#include \"ViscositySolver.h\"\n\n#include <iostream>\n\n#include <Eigen/Sparse>\n\n#include \"tbb/blocked_range.h\"\n#include \"tbb/parallel_for.h\"\n\n#include \"ComputeWeights.h\"\n#include \"LevelSet.h\"\n\nnamespace FluidSim3D\n{\n\nvoid ViscositySolver(double dt,\n                    const LevelSet& surface,\n                    VectorGrid<double>& velocity,\n                    const LevelSet& solidSurface,\n                    const VectorGrid<double>& solidVelocity,\n                    const ScalarGrid<double>& viscosity)\n{\n    // For efficiency sake, this should only take in velocity on a staggered grid\n    // that matches the center sampled surface and collision\n    assert(surface.isGridMatched(solidSurface));\n    assert(surface.isGridMatched(viscosity));\n    assert(velocity.isGridMatched(solidVelocity));\n\n    for (int axis : {0, 1, 2})\n    {\n        Vec3i faceSize = velocity.size(axis);\n        --faceSize[axis];\n\n        assert(faceSize == surface.size());\n    }\n\n    int volumeSamples = 3;\n\n    ScalarGrid<double> centerVolumes(surface.xform(), surface.size(), 0, ScalarGridSettings::SampleType::CENTER);\n    computeSupersampleVolumes(centerVolumes, surface, 3);\n\n    VectorGrid<double> edgeVolumes(surface.xform(), surface.size(), Vec3d::Zero(), VectorGridSettings::SampleType::EDGE);\n    for (int axis : {0, 1, 2}) computeSupersampleVolumes(edgeVolumes.grid(axis), surface, 3);\n\n    VectorGrid<double> faceVolumes = computeSupersampledFaceVolumes(surface, 3);\n\n    enum class MaterialLabels\n    {\n        SOLID_FACE,\n        LIQUID_FACE,\n        AIR_FACE\n    };\n\n    VectorGrid<MaterialLabels> materialFaceLabels(surface.xform(), surface.size(), Vec3t<MaterialLabels>::Constant(MaterialLabels::AIR_FACE),\n                                                  VectorGridSettings::SampleType::STAGGERED);\n\n    // Set material labels for each grid face. We assume faces along the simulation boundary\n    // are solid.\n\n    for (int faceAxis : {0, 1, 2})\n    {\n        tbb::parallel_for(tbb::blocked_range<int>(0, materialFaceLabels.grid(faceAxis).voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)\n        {\n            for (int faceIndex = range.begin(); faceIndex != range.end(); ++faceIndex)\n            {\n                Vec3i face = materialFaceLabels.grid(faceAxis).unflatten(faceIndex);\n\n                if (face[faceAxis] == 0 || face[faceAxis] == materialFaceLabels.size(faceAxis)[faceAxis] - 1)\n                    continue;\n\n                bool isFaceInSolve = false;\n\n                for (int direction : {0, 1})\n                {\n                    Vec3i cell = faceToCell(face, faceAxis, direction);\n                    if (centerVolumes(cell) > 0) isFaceInSolve = true;\n                }\n\n                if (!isFaceInSolve)\n                {\n                    for (int edgeAxis : {0, 1, 2})\n                    {\n                        if (edgeAxis == faceAxis) continue;\n\n                        for (int direction : {0, 1})\n                        {\n                            Vec3i edge = faceToEdge(face, faceAxis, edgeAxis, direction);\n\n                            if (edgeVolumes(edge, edgeAxis) > 0) isFaceInSolve = true;\n                        }\n                    }\n                }\n\n                if (isFaceInSolve)\n                {\n                    if (solidSurface.triLerp(materialFaceLabels.indexToWorld(face.cast<double>(), faceAxis)) <= 0.)\n                        materialFaceLabels(face, faceAxis) = MaterialLabels::SOLID_FACE;\n                    else\n                        materialFaceLabels(face, faceAxis) = MaterialLabels::LIQUID_FACE;\n                }\n            }\n        });\n    }\n\n    int liquidDOFCount = 0;\n\n    constexpr int UNLABELLED_CELL = -1;\n\n    VectorGrid<int> liquidFaceIndices(surface.xform(), surface.size(), Vec3t<int>::Constant(UNLABELLED_CELL),\n                                      VectorGridSettings::SampleType::STAGGERED);\n\n    for (int axis : {0, 1, 2})\n    {\n        forEachVoxelRange(Vec3i::Zero(), materialFaceLabels.size(axis), [&](const Vec3i& face)\n        {\n            if (materialFaceLabels(face, axis) == MaterialLabels::LIQUID_FACE)\n                liquidFaceIndices(face, axis) = liquidDOFCount++;\n        });\n    }\n\n    double discreteScalar = dt / std::pow(surface.dx(), 2);\n\n    // Pre-scale all the control volumes with coefficients to reduce\n    // redundant operations when building the linear system.\n\n    tbb::parallel_for(tbb::blocked_range<int>(0, centerVolumes.voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)\n    {\n        for (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)\n        {\n            Vec3i cell = centerVolumes.unflatten(cellIndex);\n\n            if (centerVolumes(cell) > 0) centerVolumes(cell) *= 2. * discreteScalar * viscosity(cell);\n        }\n    });\n\n    for (int edgeAxis : {0, 1, 2})\n    {\n        tbb::parallel_for(tbb::blocked_range<int>(0, edgeVolumes.grid(edgeAxis).voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)\n        {\n            for (int edgeIndex = range.begin(); edgeIndex != range.end(); ++edgeIndex)\n            {\n                Vec3i edge = edgeVolumes.grid(edgeAxis).unflatten(edgeIndex);\n\n                if (edgeVolumes(edge, edgeAxis) > 0)\n                    edgeVolumes(edge, edgeAxis) *= discreteScalar * viscosity.triLerp(edgeVolumes.indexToWorld(edge.cast<double>(), edgeAxis));\n            }\n        });\n    }\n\n    std::vector<Eigen::Triplet<double>> sparseElements;\n    VectorXd initialGuessVector = VectorXd::Zero(liquidDOFCount);\n    VectorXd rhsVector = VectorXd::Zero(liquidDOFCount);\n\n    {\n        tbb::enumerable_thread_specific<std::vector<Eigen::Triplet<double>>> parallelSparseElements;\n\n        for (int faceAxis : {0, 1, 2})\n        {\n            tbb::parallel_for(tbb::blocked_range<int>(0, materialFaceLabels.grid(faceAxis).voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)\n            {\n                auto& localSparseElements = parallelSparseElements.local();\n\n                for (int faceIndex = range.begin(); faceIndex != range.end(); ++faceIndex)\n                {\n                    Vec3i face = materialFaceLabels.grid(faceAxis).unflatten(faceIndex);\n\n                    int liquidFaceIndex = liquidFaceIndices(face, faceAxis);\n\n                    if (liquidFaceIndex >= 0)\n                    {\n                        assert(materialFaceLabels(face, faceAxis) == MaterialLabels::LIQUID_FACE);\n\n                        // Use old velocity as an initial guess since we're solving for a new\n                        // velocity field with viscous forces applied to the old velocity field.\n                        initialGuessVector(liquidFaceIndex) = velocity(face, faceAxis);\n\n                        // Build RHS with volume weights\n                        double localFaceVolume = faceVolumes(face, faceAxis);\n\n                        rhsVector(liquidFaceIndex) = localFaceVolume * velocity(face, faceAxis);\n\n                        // Add volume weight to diagonal\n                        double diagonal = localFaceVolume;\n\n                        // Build cell centered stress terms\n                        for (int divergenceDirection : {0, 1})\n                        {\n                            Vec3i cell = faceToCell(face, faceAxis, divergenceDirection);\n\n                            assert(cell[faceAxis] >= 0 && cell[faceAxis] < centerVolumes.size()[faceAxis]);\n\n                            double divergenceSign = (divergenceDirection == 0) ? -1 : 1;\n\n                            if (centerVolumes(cell) > 0)\n                            {\n                                for (int gradientDirection : {0, 1})\n                                {\n                                    Vec3i adjacentFace = cellToFace(cell, faceAxis, gradientDirection);\n\n                                    double gradientSign = (gradientDirection == 0) ? -1. : 1.;\n\n                                    double coefficient = divergenceSign * gradientSign * centerVolumes(cell);\n\n                                    int adjacentFaceIndex = liquidFaceIndices(adjacentFace, faceAxis);\n                                    if (adjacentFaceIndex >= 0)\n                                    {\n                                        if (adjacentFaceIndex == liquidFaceIndex)\n                                            diagonal -= coefficient;\n                                        else\n                                            localSparseElements.emplace_back(liquidFaceIndex, adjacentFaceIndex, -coefficient);\n                                    }\n                                    else if (materialFaceLabels(adjacentFace, faceAxis) == MaterialLabels::SOLID_FACE)\n                                        rhsVector(liquidFaceIndex) += coefficient * solidVelocity(adjacentFace, faceAxis);\n                                    else\n                                        assert(materialFaceLabels(adjacentFace, faceAxis) == MaterialLabels::AIR_FACE);\n                                }\n                            }\n                        }\n\n                        for (int edgeAxis : {0, 1, 2})\n                        {\n                            if (edgeAxis == faceAxis) continue;\n\n                            for (int divergenceDirection : {0, 1})\n                            {\n                                Vec3i edge = faceToEdge(face, faceAxis, edgeAxis, divergenceDirection);\n\n                                if (edgeVolumes(edge, edgeAxis) > 0)\n                                {\n                                    double divergenceSign = (divergenceDirection == 0) ? -1 : 1;\n\n                                    for (int gradientAxis : {0, 1, 2})\n                                    {\n                                        if (gradientAxis == edgeAxis) continue;\n\n                                        int gradientFaceAxis = 3 - gradientAxis - edgeAxis;\n\n                                        for (int gradientDirection : {0, 1})\n                                        {\n                                            double gradientSign = (gradientDirection == 0) ? -1 : 1;\n\n                                            Vec3i localGradientFace = edgeToFace(edge, edgeAxis, gradientFaceAxis, gradientDirection);\n\n                                            int gradientFaceIndex = liquidFaceIndices(localGradientFace, gradientFaceAxis);\n\n                                            double coefficient = divergenceSign * gradientSign * edgeVolumes(edge, edgeAxis);\n                                            if (gradientFaceIndex >= 0)\n                                            {\n                                                if (gradientFaceIndex == liquidFaceIndex)\n                                                    diagonal -= coefficient;\n                                                else\n                                                    localSparseElements.emplace_back(liquidFaceIndex, gradientFaceIndex, -coefficient);\n                                            }\n                                            else if (materialFaceLabels(localGradientFace, gradientFaceAxis) == MaterialLabels::SOLID_FACE)\n                                                rhsVector(liquidFaceIndex) += coefficient * solidVelocity(localGradientFace, gradientFaceAxis);\n                                            else\n                                                assert(materialFaceLabels(localGradientFace, gradientFaceAxis) == MaterialLabels::AIR_FACE);\n                                        }\n                                    }\n                                }\n                            }\n                        }\n\n                        localSparseElements.emplace_back(liquidFaceIndex, liquidFaceIndex, diagonal);\n                    }\n                    else\n                        assert(materialFaceLabels(face, faceAxis) != MaterialLabels::LIQUID_FACE);\n                }\n            });\n        }\n\n        mergeLocalThreadVectors(sparseElements, parallelSparseElements);\n    }\n\n    SparseMatrix sparseMatrix(liquidDOFCount, liquidDOFCount);\n    sparseMatrix.setFromTriplets(sparseElements.begin(), sparseElements.end());\n\n    Eigen::ConjugateGradient<SparseMatrix, Eigen::Upper | Eigen::Lower> solver;\n    solver.compute(sparseMatrix);\n    solver.setTolerance(1E-3);\n\n    if (solver.info() != Eigen::Success)\n    {\n        std::cout << \"   Solver failed to build\" << std::endl;\n        return;\n    }\n\n    VectorXd solutionVector = solver.solveWithGuess(rhsVector, initialGuessVector);\n\n    if (solver.info() != Eigen::Success)\n    {\n        std::cout << \"   Solver failed to converge\" << std::endl;\n        return;\n    }\n    else\n    {\n        std::cout << \"    Solver iterations:     \" << solver.iterations() << std::endl;\n        std::cout << \"    Solver error: \" << solver.error() << std::endl;\n    }\n\n    for (int faceAxis : {0, 1, 2})\n    {\n        tbb::parallel_for(tbb::blocked_range<int>(0, materialFaceLabels.grid(faceAxis).voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)\n        {\n            for (int faceIndex = range.begin(); faceIndex != range.end(); ++faceIndex)\n            {\n                Vec3i face = materialFaceLabels.grid(faceAxis).unflatten(faceIndex);\n\n                int liquidFaceIndex = liquidFaceIndices(face, faceAxis);\n                if (liquidFaceIndex >= 0)\n                {\n                    assert(materialFaceLabels(face, faceAxis) == MaterialLabels::LIQUID_FACE);\n                    velocity(face, faceAxis) = solutionVector(liquidFaceIndex);\n                }\n            }\n        });\n    }\n}\n\n}", "meta": {"hexsha": "dbf86716dd309234157b329eecf98b9247ad2a34", "size": 13701, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Library/SimTools/ViscositySolver.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/SimTools/ViscositySolver.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/SimTools/ViscositySolver.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": 42.815625, "max_line_length": 166, "alphanum_fraction": 0.513977082, "num_tokens": 2696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.2747505620070897}}
{"text": "#ifndef DESCARTES_LIGHT_SOLVERS_BGL_IMPL_BGL_DIJKSTRA_SOLVER_HPP\n#define DESCARTES_LIGHT_SOLVERS_BGL_IMPL_BGL_DIJKSTRA_SOLVER_HPP\n\n#include <descartes_light/solvers/bgl/bgl_dijkstra_solver.h>\n#include <descartes_light/solvers/bgl/impl/event_visitors.hpp>\n\n#include <descartes_light/descartes_macros.h>\nDESCARTES_IGNORE_WARNINGS_PUSH\n#include <boost/graph/dijkstra_shortest_paths.hpp>\nDESCARTES_IGNORE_WARNINGS_POP\n\nnamespace descartes_light\n{\ntemplate <typename FloatType>\nSearchResult<FloatType> BGLDijkstraSVSESolver<FloatType>::search()\n{\n  // Convenience aliases\n  auto& graph_ = BGLSolverBase<FloatType>::graph_;\n  const auto& source_ = BGLSolverBase<FloatType>::source_;\n  auto& predecessors_ = BGLSolverBase<FloatType>::predecessors_;\n  const auto& ladder_rungs_ = BGLSolverBase<FloatType>::ladder_rungs_;\n\n  // Internal properties\n  auto index_prop_map = boost::get(boost::vertex_index, graph_);\n  auto weight_prop_map = boost::get(boost::edge_weight, graph_);\n  auto color_prop_map = boost::get(&Vertex<FloatType>::color, graph_);\n  auto distance_prop_map = boost::get(&Vertex<FloatType>::distance, graph_);\n\n  typedef typename boost::property_map<BGLGraph<FloatType>, boost::vertex_index_t>::type IndexMap;\n  typedef boost::iterator_property_map<typename std::vector<VertexDesc<FloatType>>::iterator, IndexMap> PredecessorMap;\n  predecessors_.resize(boost::num_vertices(graph_), std::numeric_limits<std::size_t>::max());\n  PredecessorMap predecessor_it_map = boost::make_iterator_property_map(predecessors_.begin(), index_prop_map);\n\n  // Perform the search\n  boost::dijkstra_shortest_paths(graph_,\n                                 source_,\n                                 predecessor_it_map,\n                                 distance_prop_map,\n                                 weight_prop_map,\n                                 index_prop_map,\n                                 std::less<>(),\n                                 std::plus<>(),\n                                 std::numeric_limits<FloatType>::max(),\n                                 static_cast<FloatType>(0.0),\n                                 boost::default_dijkstra_visitor(),\n                                 color_prop_map);\n\n  // Find lowest cost node in last rung\n  auto target = std::min_element(ladder_rungs_.back().begin(),\n                                 ladder_rungs_.back().end(),\n                                 [&](const VertexDesc<FloatType>& a, const VertexDesc<FloatType>& b) {\n                                   return graph_[a].distance < graph_[b].distance;\n                                 });\n\n  SearchResult<FloatType> result;\n\n  // Reconstruct the path from the predecesor map; remove the artificial start state\n  const auto vd_path = BGLSolverBase<FloatType>::reconstructPath(source_, *target);\n  result.trajectory = BGLSolverBase<FloatType>::toStates(vd_path);\n  result.trajectory.erase(result.trajectory.begin());\n\n  result.cost = graph_[*target].distance;\n\n  return result;\n}\n\ntemplate <typename FloatType>\nSearchResult<FloatType> BGLEfficientDijkstraSVSESolver<FloatType>::search()\n{\n  // Convenience aliases\n  auto& graph_ = BGLSolverBase<FloatType>::graph_;\n  const auto& source_ = BGLSolverBase<FloatType>::source_;\n  auto& predecessors_ = BGLSolverBase<FloatType>::predecessors_;\n  const auto& ladder_rungs_ = BGLSolverBase<FloatType>::ladder_rungs_;\n\n  // Internal properties\n  auto index_prop_map = boost::get(boost::vertex_index, graph_);\n  auto weight_prop_map = boost::get(boost::edge_weight, graph_);\n  auto color_prop_map = boost::get(&Vertex<FloatType>::color, graph_);\n  auto distance_prop_map = boost::get(&Vertex<FloatType>::distance, graph_);\n\n  typedef typename boost::property_map<BGLGraph<FloatType>, boost::vertex_index_t>::type IndexMap;\n  typedef boost::iterator_property_map<typename std::vector<VertexDesc<FloatType>>::iterator, IndexMap> PredecessorMap;\n  predecessors_.resize(boost::num_vertices(graph_), std::numeric_limits<std::size_t>::max());\n  PredecessorMap predecessor_it_map = boost::make_iterator_property_map(predecessors_.begin(), index_prop_map);\n\n  const long last_rung_idx = static_cast<long>(ladder_rungs_.size() - 1);\n  auto visitor = boost::make_dijkstra_visitor(early_terminator<FloatType>(last_rung_idx));\n\n  // Perform the search\n  try\n  {\n    boost::dijkstra_shortest_paths(graph_,\n                                   source_,\n                                   predecessor_it_map,\n                                   distance_prop_map,\n                                   weight_prop_map,\n                                   index_prop_map,\n                                   std::less<>(),\n                                   std::plus<>(),\n                                   std::numeric_limits<FloatType>::max(),\n                                   static_cast<FloatType>(0.0),\n                                   visitor,\n                                   color_prop_map);\n  }\n  catch (const VertexDesc<FloatType>& target)\n  {\n    SearchResult<FloatType> result;\n\n    // Reconstruct the path from the predecesor map; remove the artificial start state\n    const auto vd_path = BGLSolverBase<FloatType>::reconstructPath(source_, target);\n    result.trajectory = BGLSolverBase<FloatType>::toStates(vd_path);\n    result.trajectory.erase(result.trajectory.begin());\n\n    result.cost = graph_[target].distance;\n\n    return result;\n  }\n\n  // If the visitor never threw the vertex descriptor, there was an issue with the search\n  throw std::runtime_error(\"Search failed to encounter vertex associated with the last waypoint in the trajectory\");\n}\n\n}  // namespace descartes_light\n\n#endif  // DESCARTES_LIGHT_SOLVERS_BGL_IMPL_BGL_DIJKSTRA_SOLVER_HPP\n", "meta": {"hexsha": "3a9e4b2d78f66e5fa046771d8b5009aba4786bc1", "size": 5692, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "descartes_light/solvers/include/descartes_light/solvers/bgl/impl/bgl_dijkstra_solver.hpp", "max_stars_repo_name": "John-Bonnin/descartes_light", "max_stars_repo_head_hexsha": "44e0de3877851031ecc5237627d42354f833a6b5", "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": "descartes_light/solvers/include/descartes_light/solvers/bgl/impl/bgl_dijkstra_solver.hpp", "max_issues_repo_name": "John-Bonnin/descartes_light", "max_issues_repo_head_hexsha": "44e0de3877851031ecc5237627d42354f833a6b5", "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": "descartes_light/solvers/include/descartes_light/solvers/bgl/impl/bgl_dijkstra_solver.hpp", "max_forks_repo_name": "John-Bonnin/descartes_light", "max_forks_repo_head_hexsha": "44e0de3877851031ecc5237627d42354f833a6b5", "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": 44.8188976378, "max_line_length": 119, "alphanum_fraction": 0.6596978215, "num_tokens": 1209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.27436813603029103}}
{"text": "/*\n * This file is a part of\n *\n * ============================================\n * ###   Pteros molecular modeling library  ###\n * ============================================\n *\n * https://github.com/yesint/pteros\n *\n * (C) 2009-2020, 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\n#include \"pteros/extras/gnm.h\"\n#include \"pteros/core/pteros_error.h\"\n#include \"pteros/core/distance_search.h\"\n#include <fstream>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <ctime>\n\nusing namespace std;\nusing namespace pteros;\nusing namespace Eigen;\n\nvoid GNM::compute(Selection& sel, float cutoff){\n    int i,j,k;\n\n    cout << \"Running GNM...\"<<endl;\n\n    N = sel.size();\n    eigenvalues.resize(N-1);\n    eigenvectors.resize(N,N-1);\n\n    cout << \"Constructing GNM Kirkgoff matrix. Cut-off: \" << cutoff << \" Size: \" << N << endl;\n    MatrixXf kirk(N,N); //Kirgoff matrix\n    float d, time1, time2;\n\n    kirk.fill(0.0);\n    // Compute off-diagonal elements\n    /*\n    for(i=0;i<N-1;++i)        \n        for(j=i+1;j<N;++j){            \n            d = (sel.xyz(i)-sel.xyz(j)).norm();\n            if(d<=cutoff){\n                kirk(i,j)= -1.0;\n                kirk(j,i)= -1.0;\n            }\n        }\n    */\n\n    vector<Eigen::Vector2i> bon;\n    search_contacts(cutoff,sel,bon);\n    for(int i=0; i<bon.size(); ++i){\n        kirk(bon[i](0),bon[i](1)) = kirk(bon[i](1),bon[i](0)) = -1.0;\n    }\n\n    // Compute diagonal elements\n    for(i=0;i<N;++i) kirk(i,i) = -kirk.col(i).sum();\n\n    cout << \"Computing eigenvectors...\";\n    time1 = clock();\n\n    Eigen::SelfAdjointEigenSolver<MatrixXf> solver(kirk);\n    eigenvalues = solver.eigenvalues();\n    eigenvectors = solver.eigenvectors();\n    // Vectors are already sorted, cool :)\n\n    time2 = clock();\n    cout << \" Done in \" << (time2-time1)/CLOCKS_PER_SEC << \" s.\" << endl;\n}\n\nGNM::GNM(Selection& sel, float cutoff){\n    compute(sel,cutoff);\n}\n\nvoid GNM::write_eigenvectors(string fname, int v1, int v2){\n    if(v1<0 || v2>N-2 || v2<v1) throw Pteros_error(\"Can't write these eigenvectors!\");\n    ofstream f(fname.c_str());\n    if(!f) throw Pteros_error(\"Can't open file \"+fname+\" for writing!\");\n    int i,j;\n    for(i=0;i<N;++i){\n        f << i << \" \";\n        for(j=v1;j<=v2;++j) f << eigenvectors(i,j) << \" \";\n        f << endl;\n    }\n    f.close();\n}\n\nvoid GNM::compute_c_matrix(bool normalize){\n    int i,j,k;\n    cout << \"Calculating correlations...\" << endl;\n    c.resize(N,N);\n    c.fill(0.0);\n    for(k=1;k<N;++k) // For all eigenvectors except first, which is zero\n        for(i=0;i<N;++i)\n            for(j=i;j<N;++j)\n                c(i,j) = c(i,j) + eigenvectors(i,k)*eigenvectors(j,k)/eigenvalues(k);\n\n    // Set lower triangle of the matrix\n    for(i=0;i<N-1;++i)\n        for(j=i+1;j<N;++j)\n            c(j,i) = c(i,j);\n\n    if(normalize)\n        for(i=0;i<N;++i)\n            for(j=0;j<N;++j)\n                c(i,j) = c(i,j)/sqrt(c(i,i)*c(j,j));\n}\n\nvoid GNM::compute_p_matrix(){\n    if(!c.size()) compute_c_matrix();\n    cout << \"Calculating correlations of correlation patterns...\";\n    int i,j;\n    float time1,time2;\n\n    time1 = clock();\n\n    p.resize(N,N);\n    p.fill(0.0);\n\n    // See if c-matrix is ready\n    if(!c.cols()) compute_c_matrix();\n\n    // Pre-compute m and s\n    VectorXf m(N), s(N);\n\n    for(i=0;i<N;++i){\n        m(i) = c.col(i).sum()/float(N);\n        s(i) = c.col(i).array().pow(2).sum()/float(N) - pow(m(i),2);\n    }\n\n    for(i=0;i<N;++i)\n        for(j=i;j<N;++j){\n            p(i,j) = (c.col(i).array() * c.col(j).array()).sum() /float(N) - m(i)*m(j);\n            p(i,j) = p(i,j) / sqrt(s(i)*s(j));\n            p(j,i) = p(i,j);\n        }\n\n    time2 = clock();\n    cout << \" Done in \" << (time2-time1)/CLOCKS_PER_SEC << \" s.\" << endl;\n}\n\nvoid GNM::write_c_matrix(string fname){\n    // See if c-matrix is ready\n    if(!c.cols()) compute_c_matrix();\n\n    int i,j;\n    ofstream f(fname.c_str());\n    if(!f) throw Pteros_error(\"Can't open file \"+fname+\" for writing!\");\n    for(i=0;i<N;++i){\n        for(j=0;j<N;++j)\n            f << c(i,j) << \" \";\n        f << endl;\n    }\n    f.close();\n}\n\nvoid GNM::write_p_matrix(string fname){\n    // See if p-matrix is ready\n    if(!p.cols()) compute_p_matrix();\n\n    int i,j;\n    ofstream f(fname.c_str());\n    if(!f) throw Pteros_error(\"Can't open file \"+fname+\" for writing!\");\n\n    for(i=0;i<N;++i){\n        for(j=0;j<N;++j)\n            f << p(i,j) << \" \";\n        f << endl;\n    }\n    f.close();\n}\n\n\n", "meta": {"hexsha": "eba4211a6ad37acc30aca3bb092047aa28566c8f", "size": 5051, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/extras/gnm/gnm.cpp", "max_stars_repo_name": "mdimura/pteros", "max_stars_repo_head_hexsha": "1692394075482987638c40236312ebaac49d5780", "max_stars_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-01T10:28:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-01T10:28:52.000Z", "max_issues_repo_path": "src/extras/gnm/gnm.cpp", "max_issues_repo_name": "mdimura/pteros", "max_issues_repo_head_hexsha": "1692394075482987638c40236312ebaac49d5780", "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/gnm/gnm.cpp", "max_forks_repo_name": "mdimura/pteros", "max_forks_repo_head_hexsha": "1692394075482987638c40236312ebaac49d5780", "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": 26.170984456, "max_line_length": 94, "alphanum_fraction": 0.5339536725, "num_tokens": 1559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.27409401599164396}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_PROB_MULTI_NORMAL_CHOLESKY_LPDF_HPP\n#define STAN_MATH_PRIM_MAT_PROB_MULTI_NORMAL_CHOLESKY_LPDF_HPP\n\n#include <stan/math/prim/scal/meta/is_constant_struct.hpp>\n#include <stan/math/prim/scal/meta/partials_return_type.hpp>\n#include <stan/math/prim/mat/meta/operands_and_partials.hpp>\n#include <stan/math/prim/mat/fun/dot_self.hpp>\n#include <stan/math/prim/mat/fun/log.hpp>\n#include <stan/math/prim/mat/fun/mdivide_left_tri.hpp>\n#include <stan/math/prim/mat/fun/transpose.hpp>\n#include <stan/math/prim/mat/meta/vector_seq_view.hpp>\n#include <stan/math/prim/scal/err/check_size_match.hpp>\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/meta/max_size_mvt.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n#include <stan/math/prim/scal/meta/return_type.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\nnamespace stan {\nnamespace math {\n/**\n * The log of the multivariate normal density for the given y, mu, and\n * a Cholesky factor L of the variance matrix.\n * Sigma = LL', a square, semi-positive definite matrix.\n *\n * Analytic expressions taken from\n * http://qwone.com/~jason/writing/multivariateNormal.pdf\n * written by Jason D. M. Rennie.\n *\n * All expressions are adapted to avoid (most) inversions and maximal\n * reuse of intermediates.\n *\n * @param y A scalar vector\n * @param mu The mean vector of the multivariate normal distribution.\n * @param L The Cholesky decomposition of a variance matrix\n * of the multivariate normal distribution\n * @return The log of the multivariate normal density.\n * @throw std::domain_error if LL' is not square, not symmetric,\n * or not semi-positive definite.\n * @tparam T_y Type of scalar.\n * @tparam T_loc Type of location.\n * @tparam T_covar Type of scale.\n */\ntemplate <bool propto, typename T_y, typename T_loc, typename T_covar>\ntypename return_type<T_y, T_loc, T_covar>::type multi_normal_cholesky_lpdf(\n    const T_y& y, const T_loc& mu, const T_covar& L) {\n  static const char* function = \"multi_normal_cholesky_lpdf\";\n  typedef typename scalar_type<T_covar>::type T_covar_elem;\n  typedef typename return_type<T_y, T_loc, T_covar>::type T_return;\n  typedef typename stan::partials_return_type<T_y, T_loc, T_covar>::type\n      T_partials_return;\n  typedef Eigen::Matrix<T_partials_return, Eigen::Dynamic, Eigen::Dynamic>\n      matrix_partials_t;\n  typedef Eigen::Matrix<T_partials_return, Eigen::Dynamic, 1> vector_partials_t;\n  typedef Eigen::Matrix<T_partials_return, 1, Eigen::Dynamic>\n      row_vector_partials_t;\n\n  vector_seq_view<T_y> y_vec(y);\n  vector_seq_view<T_loc> mu_vec(mu);\n  const size_t size_vec = max_size_mvt(y, mu);\n\n  const int size_y = y_vec[0].size();\n  const int size_mu = mu_vec[0].size();\n  if (likely(size_vec > 1)) {\n    // check size consistency of all random variables y\n    int size_y_old = size_y;\n    for (size_t i = 1, size_ = length_mvt(y); i < size_; i++) {\n      int size_y_new = y_vec[i].size();\n      check_size_match(function,\n                       \"Size of one of the vectors of \"\n                       \"the random variable\",\n                       size_y_new,\n                       \"Size of another vector of the \"\n                       \"random variable\",\n                       size_y_old);\n      size_y_old = size_y_new;\n    }\n    // check size consistency of all means mu\n    int size_mu_old = size_mu;\n    for (size_t i = 1, size_ = length_mvt(mu); i < size_; i++) {\n      int size_mu_new = mu_vec[i].size();\n      check_size_match(function,\n                       \"Size of one of the vectors of \"\n                       \"the location variable\",\n                       size_mu_new,\n                       \"Size of another vector of the \"\n                       \"location variable\",\n                       size_mu_old);\n      size_mu_old = size_mu_new;\n    }\n  }\n\n  check_size_match(function, \"Size of random variable\", size_y,\n                   \"size of location parameter\", size_mu);\n  check_size_match(function, \"Size of random variable\", size_y,\n                   \"rows of covariance parameter\", L.rows());\n  check_size_match(function, \"Size of random variable\", size_y,\n                   \"columns of covariance parameter\", L.cols());\n\n  for (size_t i = 0; i < size_vec; i++) {\n    check_finite(function, \"Location parameter\", mu_vec[i]);\n    check_not_nan(function, \"Random variable\", y_vec[i]);\n  }\n\n  if (unlikely(size_y == 0))\n    return T_return(0.0);\n\n  T_partials_return logp(0.0);\n  operands_and_partials<T_y, T_loc, T_covar> ops_partials(y, mu, L);\n\n  if (include_summand<propto>::value)\n    logp += NEG_LOG_SQRT_TWO_PI * size_y * size_vec;\n\n  const matrix_partials_t inv_L_dbl\n      = mdivide_left_tri<Eigen::Lower>(value_of(L));\n\n  if (include_summand<propto, T_y, T_loc, T_covar_elem>::value) {\n    for (size_t i = 0; i < size_vec; i++) {\n      vector_partials_t y_minus_mu_dbl(size_y);\n      for (int j = 0; j < size_y; j++)\n        y_minus_mu_dbl(j) = value_of(y_vec[i](j)) - value_of(mu_vec[i](j));\n\n      const row_vector_partials_t half\n          = (inv_L_dbl.template triangularView<Eigen::Lower>() * y_minus_mu_dbl)\n                .transpose();\n      const vector_partials_t scaled_diff\n          = (half * inv_L_dbl.template triangularView<Eigen::Lower>())\n                .transpose();\n\n      logp -= 0.5 * dot_self(half);\n\n      if (!is_constant_struct<T_y>::value) {\n        for (int j = 0; j < size_y; j++)\n          ops_partials.edge1_.partials_vec_[i](j) -= scaled_diff(j);\n      }\n      if (!is_constant_struct<T_loc>::value) {\n        for (int j = 0; j < size_y; j++)\n          ops_partials.edge2_.partials_vec_[i](j) += scaled_diff(j);\n      }\n      if (!is_constant_struct<T_covar>::value) {\n        ops_partials.edge3_.partials_ += scaled_diff * half;\n      }\n    }\n  }\n\n  if (include_summand<propto, T_covar_elem>::value) {\n    logp += inv_L_dbl.diagonal().array().log().sum() * size_vec;\n    if (!is_constant_struct<T_covar>::value) {\n      ops_partials.edge3_.partials_ -= size_vec * inv_L_dbl.transpose();\n    }\n  }\n\n  return ops_partials.build(logp);\n}\n\ntemplate <typename T_y, typename T_loc, typename T_covar>\ninline typename return_type<T_y, T_loc, T_covar>::type\nmulti_normal_cholesky_lpdf(const T_y& y, const T_loc& mu, const T_covar& L) {\n  return multi_normal_cholesky_lpdf<false>(y, mu, L);\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "641c5e0bb65abbafccb0a67b87f152bb8dd07b61", "size": 6514, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/mat/prob/multi_normal_cholesky_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/mat/prob/multi_normal_cholesky_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/mat/prob/multi_normal_cholesky_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": 38.7738095238, "max_line_length": 80, "alphanum_fraction": 0.6733190052, "num_tokens": 1717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791786991753929, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2740940107502977}}
{"text": "#include \"source/newtonian/two_dimensional/hdsim2d.hpp\"\n#include \"source/newtonian/common/hllc.hpp\"\n#include \"source/newtonian/common/ideal_gas.hpp\"\n#include \"source/newtonian/two_dimensional/amr.hpp\"\n#include \"source/newtonian/two_dimensional/modular_flux_calculator.hpp\"\n#include \"source/newtonian/two_dimensional/simple_cell_updater.hpp\"\n#include \"source/newtonian/two_dimensional/simple_cfl.hpp\"\n#include \"source/newtonian/two_dimensional/simple_extensive_updater.hpp\"\n#include \"source/newtonian/two_dimensional/point_motions/lagrangian.hpp\"\n#include \"source/newtonian/two_dimensional/point_motions/round_cells.hpp\"\n#include \"source/newtonian/two_dimensional/interpolations/LinearGaussImproved.hpp\"\n#include \"source/tessellation/VoronoiMesh.hpp\"\n#include \"source/misc/mesh_generator.hpp\"\n#include \"source/newtonian/two_dimensional/periodic_edge_velocities.hpp\"\n#include \"source/newtonian/two_dimensional/geometric_outer_boundaries/PeriodicBox.hpp\"\n#include \"source/newtonian/two_dimensional/ghost_point_generators/PeriodicGhostGenerator.hpp\"\n#include \"source/newtonian/two_dimensional/source_terms/zero_force.hpp\"\n#include \"source/newtonian/two_dimensional/hdf5_diagnostics.hpp\"\n#include <boost/random/uniform_int_distribution.hpp>\n#include \"source/misc/simple_io.hpp\"\n\nnamespace {\nclass ConserveRefine : public CellsToRefine\n{\npublic:\n\tvector<size_t> ToRefine(Tessellation const& tess, vector<ComputationalCell> const& /*cells*/, double time,\n\tTracerStickerNames const& /*ts*/)const\n\t{\n\t\tboost::random::mt19937_64 gen(static_cast<uint64_t>(time*10000));\n\t\tboost::random::uniform_int_distribution<> dist(0, tess.GetPointNo()-1);\n\t\tvector<size_t> res(10);\n\t\tfor (size_t i = 0; i < res.size(); ++i)\n\t\t  res[i] = static_cast<size_t>(dist(gen));\n\t\treturn res;\n\t}\n};\n\nclass ConserveRemove : public CellsToRemove\n{\npublic:\n\tstd::pair<vector<size_t>, vector<double> > ToRemove(Tessellation const& tess, vector<ComputationalCell> const& /*cells*/, double time,\n\tTracerStickerNames const& /*ts*/)const\n\t{\n\t\tboost::random::mt19937_64 gen(static_cast<uint64_t>(time * 11000));\n\t\tboost::random::uniform_int_distribution<> dist(0,tess.GetPointNo()-1);\n\t\tstd::pair<vector<size_t>, vector<double> > res(vector<size_t>(10), vector<double>(10));\n\t\tfor (size_t i = 0; i < res.first.size(); ++i)\n\t\t{\n\t\t  res.first[i] = static_cast<size_t>(dist(gen));\n\t\t\tres.second[i] = static_cast<double>(dist(gen));\n\t\t}\n\t\treturn res;\n\t}\n};\n\ndouble TotalMass(hdsim const& sim)\n{\n\tdouble res = 0;\n\tfor (int i = 0; i < sim.getTessellation().GetPointNo(); ++i)\n\t\tres += sim.getTessellation().GetVolume(i)*sim.getAllCells()[static_cast<size_t>(i)].density;\n\treturn res;\n}\n\nvector<ComputationalCell> calc_cells(size_t n)\n{\n\tvector<ComputationalCell> res(n);\n\tfor (size_t i = 0; i < n; ++i)\n\t{\n\t\tres[i].density = 1;\n\t\tres[i].pressure = 1;\n\t\tres[i].velocity = Vector2D(1, 0);\n\t}\n\treturn res;\n}\n}\n\nint main(void)\n{\n\tint np = 30;\n\tvector<Vector2D> points = cartesian_mesh(np, np, Vector2D(-1, -1), Vector2D(1, 1));\n\tPeriodicBox outer(Vector2D(-1, -1), Vector2D(1, 1));\n\tVoronoiMesh tess(points, outer);\n\tvector<ComputationalCell> cells = calc_cells(static_cast<size_t>(tess.GetPointNo()));\n\tHllc rs;\n\tIdealGas eos(5. / 3.);\n\tPeriodicGhostGenerator ghost;\n\tPeriodicEdgeVelocities vedge;\n\tLinearGaussImproved interp(eos, ghost);\n\tSimpleCellUpdater cu;\n\tSimpleExtensiveUpdater eu;\n\tSimpleCFL tsf(0.3);\n\tModularFluxCalculator fc(interp, rs);\n\tLagrangian pm;\n\tSlabSymmetry pg;\n\tZeroForce force;\n\n\thdsim sim(tess, outer, pg, cells, eos, pm, vedge, force, tsf, fc, eu, cu);\n\n\tConserveRefine refine;\n\tConserveRemove remove;\n\tConservativeAMR amr(refine, remove,true, &interp);\n\n\tfor (size_t i = 0; i < 50; ++i)\n\t{\n\t\tsim.TimeAdvance2Heun();\n\t\tamr(sim);\n\t}\n\t\n\twrite_number(TotalMass(sim), \"mass.txt\",9);\n\twrite_snapshot_to_hdf5(sim, \"final.h5\");\n\n\treturn 0;\n}\n", "meta": {"hexsha": "21fe2804f3f2f0a99ac1804b9c62b2d7e88a9841", "size": 3810, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/tests/newtonian/two_dimensional/amrconserve2/test.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/tests/newtonian/two_dimensional/amrconserve2/test.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/tests/newtonian/two_dimensional/amrconserve2/test.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": 33.4210526316, "max_line_length": 135, "alphanum_fraction": 0.7501312336, "num_tokens": 1114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2740171072132699}}
{"text": "//------------------------------------------//\r\n//  This file is a modified version of      //\r\n//  basics.cpp, which was distributed as    //\r\n//  part of MuJoCo,  Written by Emo Todorov //\r\n//  Copyright (C) 2017 Roboti LLC           //\r\n//  Modifications by Atabak Dehban          //\r\n//------------------------------------------//\r\n\r\n\r\n#include <iostream>\r\n\r\n#include \"mujoco.h\"\r\n#include \"cstdio\"\r\n#include \"cstdlib\"\r\n#include \"cstring\"\r\n#include \"glfw3.h\"\r\n\r\n// for sleep timers\r\n#include <chrono>\r\n#include <thread>\r\n\r\n// Eigen, used by drake\r\n#include <Eigen/Core>\r\n#include <unsupported/Eigen/MatrixFunctions>\r\n#include \"drake/systems/controllers/linear_quadratic_regulator.h\"\r\n\r\n\r\n// MuJoCo data structures\r\nmjModel* m = NULL;                  // MuJoCo model\r\nmjData* d = NULL;                   // MuJoCo data\r\nmjvCamera cam;                      // abstract camera\r\nmjvOption opt;                      // visualization options\r\nmjvScene scn;                       // abstract scene\r\nmjrContext con;                     // custom GPU context\r\n\r\n// mouse interaction\r\nbool button_left = false;\r\nbool button_middle = false;\r\nbool button_right =  false;\r\ndouble lastx = 0;\r\ndouble lasty = 0;\r\n\r\n// holders of one step history of time and position to calculate dertivatives\r\nmjtNum position_history = 0;\r\nmjtNum previous_time = 0;\r\n\r\n// controller related variables\r\nfloat_t ctrl_update_freq = 1000;\r\nmjtNum last_update = 0.0;\r\nmjtNum ctrl;\r\n\r\n\r\n\r\n// keyboard callback\r\nvoid keyboard(GLFWwindow* window, int key, int scancode, int act, int mods)\r\n{\r\n    // backspace: reset simulation\r\n    if( act==GLFW_PRESS && key==GLFW_KEY_BACKSPACE )\r\n    {\r\n        mj_resetData(m, d);\r\n        mj_forward(m, d);\r\n    }\r\n}\r\n\r\n\r\n// mouse button callback\r\nvoid mouse_button(GLFWwindow* window, int button, int act, int mods)\r\n{\r\n    // update button state\r\n    button_left =   (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT)==GLFW_PRESS);\r\n    button_middle = (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_MIDDLE)==GLFW_PRESS);\r\n    button_right =  (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT)==GLFW_PRESS);\r\n\r\n    // update mouse position\r\n    glfwGetCursorPos(window, &lastx, &lasty);\r\n}\r\n\r\n\r\n// mouse move callback\r\nvoid mouse_move(GLFWwindow* window, double xpos, double ypos)\r\n{\r\n    // no buttons down: nothing to do\r\n    if( !button_left && !button_middle && !button_right )\r\n        return;\r\n\r\n    // compute mouse displacement, save\r\n    double dx = xpos - lastx;\r\n    double dy = ypos - lasty;\r\n    lastx = xpos;\r\n    lasty = ypos;\r\n\r\n    // get current window size\r\n    int width, height;\r\n    glfwGetWindowSize(window, &width, &height);\r\n\r\n    // get shift key state\r\n    bool mod_shift = (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT)==GLFW_PRESS ||\r\n                      glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT)==GLFW_PRESS);\r\n\r\n    // determine action based on mouse button\r\n    mjtMouse action;\r\n    if( button_right )\r\n        action = mod_shift ? mjMOUSE_MOVE_H : mjMOUSE_MOVE_V;\r\n    else if( button_left )\r\n        action = mod_shift ? mjMOUSE_ROTATE_H : mjMOUSE_ROTATE_V;\r\n    else\r\n        action = mjMOUSE_ZOOM;\r\n\r\n    // move camera\r\n    mjv_moveCamera(m, action, dx/height, dy/height, &scn, &cam);\r\n}\r\n\r\n\r\n// scroll callback\r\nvoid scroll(GLFWwindow* window, double xoffset, double yoffset)\r\n{\r\n    // emulate vertical mouse motion = 5% of window height\r\n    mjv_moveCamera(m, mjMOUSE_ZOOM, 0, -0.05*yoffset, &scn, &cam);\r\n}\r\n\r\n// control loop callback\r\nvoid mycontroller(const mjModel* m, mjData* d)\r\n{\r\n    // printouts for debugging purposes\r\n    mjtObj geom = mjOBJ_GEOM;\r\n    mjtObj body = mjOBJ_BODY;\r\n    mjtObj dof = mjOBJ_JOINT;\r\n    int ball_id = mj_name2id(m, body, \"ballbody\");\r\n    int rod_id = mj_name2id(m, geom, \"rod\");\r\n    int pivot_id = mj_name2id(m, dof, \"pivot\");\r\n    std::cout << \"ball body id: \" << ball_id << std::endl;\r\n    std::cout << \"rod geom id: \" << rod_id << std::endl;\r\n    std::cout << \"pivot joint id: \" << pivot_id << std::endl;\r\n    std::cout << \"ball mass: \" << m->body_mass[ball_id] << std::endl;\r\n    std::cout << \"length of the rod: \" << m->geom_size[rod_id*3+1] << std::endl;\r\n    std::cout << \"friction coefficient: \" << m->dof_damping[pivot_id] << std::endl;\r\n    std::cout << \"gravity: \" << m->opt.gravity[2] << std::endl;\r\n    std::cout << \"Sensor output: \" << d->sensordata[0] << std::endl;\r\n\r\n\r\n    // System dynamics matrices: https://github.com/RobotLocomotion/drake/blob/master/systems/controllers/zmp_planner.h#L306\r\n    Eigen::Matrix<mjtNum , 2, 2> A_;\r\n    Eigen::Matrix<mjtNum , 2, 1> B_;\r\n    Eigen::Matrix<mjtNum , 2, 2> Q_ = Eigen::Matrix<mjtNum , 2, 2>::Identity();\r\n    Eigen::Matrix<mjtNum , 1, 1> R_ = Eigen::Matrix<mjtNum , 1, 1>::Identity();\r\n    Eigen::Matrix<mjtNum , 2, 1> N = Eigen::Matrix<mjtNum , 2, 1>::Zero();\r\n\r\n\r\n    // Eqs comming from https://youtu.be/XA6B1IxALhk?t=30m3s\r\n    A_(0,0) = 0.0;\r\n    A_(0,1) = 1.0;\r\n    A_(1,0) = - m->opt.gravity[2]*mju_cos(d->sensordata[0])/(m->geom_size[rod_id*3+1]*2);\r\n    A_(1,1) = - m->dof_damping[pivot_id]/(m->body_mass[ball_id]*mju_pow(m->geom_size[rod_id*3+1]*2,2.0));\r\n    B_(0,0) = 0.0;\r\n    B_(1,0) = 1.0;\r\n    Q_ *= 10.0;\r\n\r\n    drake::systems::controllers::LinearQuadraticRegulatorResult lqr_result =\r\n            drake::systems::controllers::LinearQuadraticRegulator(A_, B_, Q_, R_, N);\r\n    Eigen::Matrix<mjtNum, 2, 2> S1_ = lqr_result.S;\r\n    Eigen::Matrix<mjtNum, 1, 2> K_= -lqr_result.K;\r\n\r\n\r\n    // controller with true values, but it is cheating.\r\n//    ctrl = 3.5*(-d->qvel[0]-10.0*d->qpos[0]);\r\n\r\n    // controller with sensor readings\r\n    if (previous_time == 0)\r\n    {\r\n        previous_time = d->time;\r\n        return;\r\n    }\r\n    if (d->time - last_update > 1.0/ctrl_update_freq)\r\n    {\r\n        mjtNum vel = (d->sensordata[0] - position_history)/(d->time-previous_time);\r\n        ctrl = K_(0,0)*d->sensordata[0] + K_(0,1)*vel;\r\n        last_update = d->time;\r\n        position_history = d->sensordata[0];\r\n        previous_time = d->time;\r\n    }\r\n    d->ctrl[0] = ctrl;\r\n\r\n    std::cout << \"torque effort: \" << ctrl << std::endl;\r\n}\r\n\r\n\r\n// main function\r\nint main(int argc, const char** argv)\r\n{\r\n\r\n    // activate software\r\n    mj_activate(\"../../../mjkey.txt\");\r\n\r\n\r\n    // load and compile model\r\n    char error[1000] = \"Could not load binary model\";\r\n\r\n    // check command-line arguments\r\n    if( argc<2 )\r\n        m = mj_loadXML(\"../../../models/invertedPendulum.xml\", 0, error, 1000);\r\n\r\n    else\r\n        if( strlen(argv[1])>4 && !strcmp(argv[1]+strlen(argv[1])-4, \".mjb\") )\r\n            m = mj_loadModel(argv[1], 0);\r\n        else\r\n            m = mj_loadXML(argv[1], 0, error, 1000);\r\n    if( !m )\r\n        mju_error_s(\"Load model error: %s\", error);\r\n\r\n    // make data\r\n    d = mj_makeData(m);\r\n\r\n\r\n    // init GLFW\r\n    if( !glfwInit() )\r\n        mju_error(\"Could not initialize GLFW\");\r\n\r\n    // create window, make OpenGL context current, request v-sync\r\n    GLFWwindow* window = glfwCreateWindow(1200, 900, \"Demo\", NULL, NULL);\r\n    glfwMakeContextCurrent(window);\r\n    glfwSwapInterval(1);\r\n\r\n    // initialize visualization data structures\r\n    mjv_defaultCamera(&cam);\r\n    mjv_defaultOption(&opt);\r\n    mjv_defaultScene(&scn);\r\n    mjr_defaultContext(&con);\r\n    mjv_makeScene(m, &scn, 2000);                // space for 2000 objects\r\n    mjr_makeContext(m, &con, mjFONTSCALE_150);   // model-specific context\r\n\r\n    // install GLFW mouse and keyboard callbacks\r\n    glfwSetKeyCallback(window, keyboard);\r\n    glfwSetCursorPosCallback(window, mouse_move);\r\n    glfwSetMouseButtonCallback(window, mouse_button);\r\n    glfwSetScrollCallback(window, scroll);\r\n\r\n    // install control callback\r\n    mjcb_control = mycontroller;\r\n\r\n    // initial position\r\n    d->qpos[0] = 1.57;\r\n\r\n    // run main loop, target real-time simulation and 60 fps rendering\r\n    mjtNum timezero = d->time;\r\n    double_t update_rate = 0.01;\r\n\r\n    // making sure the first time step updates the ctrl previous_time\r\n    last_update = timezero-1.0/ctrl_update_freq;\r\n\r\n    // use the first while condition if you want to simulate for a period.\r\n//    while( !glfwWindowShouldClose(window) and d->time-timezero < 1.5)\r\n    while( !glfwWindowShouldClose(window))\r\n    {\r\n        // advance interactive simulation for 1/60 sec\r\n        //  Assuming MuJoCo can simulate faster than real-time, which it usually can,\r\n        //  this loop will finish on time for the next frame to be rendered at 60 fps.\r\n        //  Otherwise add a cpu timer and exit this loop when it is time to render.\r\n        mjtNum simstart = d->time;\r\n        while( d->time - simstart < 1.0/60.0 )\r\n            mj_step(m, d);\r\n\r\n        // 15 ms is a little smaller than 60 Hz.\r\n        std::this_thread::sleep_for(std::chrono::milliseconds(15));\r\n       // get framebuffer viewport\r\n        mjrRect viewport = {0, 0, 0, 0};\r\n        glfwGetFramebufferSize(window, &viewport.width, &viewport.height);\r\n\r\n          // update scene and render\r\n        mjv_updateScene(m, d, &opt, NULL, &cam, mjCAT_ALL, &scn);\r\n        mjr_render(viewport, &scn, &con);\r\n\r\n        // swap OpenGL buffers (blocking call due to v-sync)\r\n        glfwSwapBuffers(window);\r\n\r\n        // process pending GUI events, call GLFW callbacks\r\n        glfwPollEvents();\r\n\r\n    }\r\n\r\n\r\n    // free visualization storage\r\n    mjv_freeScene(&scn);\r\n    mjr_freeContext(&con);\r\n\r\n    // free MuJoCo model and data, deactivate\r\n    mj_deleteData(d);\r\n    mj_deleteModel(m);\r\n    mj_deactivate();\r\n\r\n    // terminate GLFW (crashes with Linux NVidia drivers)\r\n#if defined(__APPLE__) || defined(_WIN32)\r\n    glfwTerminate();\r\n#endif\r\n    return 1;\r\n}\r\n", "meta": {"hexsha": "da1d12e7e35d35837d483a75a64e49a3631e1043", "size": 9638, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/2.1_LQR/LQR-pendulum.cpp", "max_stars_repo_name": "atabakd/MuJoCo-Tutorials", "max_stars_repo_head_hexsha": "d6b86726ca9f01e682a45c4de7c11761ec326d38", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2018-09-27T14:04:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T21:58:54.000Z", "max_issues_repo_path": "src/2.1_LQR/LQR-pendulum.cpp", "max_issues_repo_name": "atabakd/MuJoCo-Tutorials", "max_issues_repo_head_hexsha": "d6b86726ca9f01e682a45c4de7c11761ec326d38", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-02-18T03:26:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-22T20:23:16.000Z", "max_forks_repo_path": "src/2.1_LQR/LQR-pendulum.cpp", "max_forks_repo_name": "atabakd/MuJoCo-Tutorials", "max_forks_repo_head_hexsha": "d6b86726ca9f01e682a45c4de7c11761ec326d38", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-10-03T14:20:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T08:32:30.000Z", "avg_line_length": 32.5608108108, "max_line_length": 125, "alphanum_fraction": 0.6118489313, "num_tokens": 2656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.2739021323302521}}
{"text": "#define NDEBUG\n#define _ITERATOR_DEBUG_LEVEL 0\n\n#include <array>\n#include <boost/lexical_cast.hpp>\n#ifdef DOMAGICK\n#include <Magick++.h>\n#endif\n#include <boost/fusion/adapted/array.hpp>\n#include <boost/fusion/adapted/std_array.hpp>\n#include <boost/fusion/adapted/std_tuple.hpp>\n#include <boost/fusion/adapted/std_pair.hpp>\n#include <boost/spirit/home/x3.hpp>\n#include <boost/format.hpp>\n#include <boost/spirit/include/support_istream_iterator.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <map>\n#include <string>\n\nusing namespace boost::spirit;\nusing namespace std;\n\nusing box = std::array<int, 4>;\n\nbox intersect(const box& a, const box& b)\n{\n\tbox res = { max(a[0], b[0]), max(a[1], b[1]), min(a[2], b[2]), min(a[3], b[3]) };\n\tres[0] = min(res[0], res[2]);\n\tres[1] = min(res[1], res[3]);\n\n\treturn res;\n}\n\nbox boxunion(const box& a, const box& b)\n{\n\tbox res = { min(a[0], b[0]), min(a[1], b[1]), max(a[2], b[2]), max(a[3], b[3]) };\t\n\n\treturn res;\n}\n\nint area(const box& a)\n{\n\treturn (a[2] - a[0]) * (a[3] - a[1]);\n}\n\n// According to https://wandbox.org/permlink/poeusnilIOwmiEBo\nnamespace boost {\n\tnamespace spirit {\n\t\tnamespace x3 {\n\t\t\tnamespace traits {\n\t\t\t\t// It can't be specialized because X3 implements is_container as a template aliases,\n\t\t\t\t// thus we need QUITE TERRIBLE DIRTY hack for fixed length container.\n\t\t\t\t//template <> struct is_container<Vertex const> : mpl::false_ { };\n\t\t\t\t//template <> struct is_container<Vertex> : mpl::false_ { };\n\t\t\t\tnamespace detail {\n\t\t\t\t\ttemplate <> struct has_type_value_type<box> : mpl::false_ { };\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\ntemplate<class T> auto constexpr bracketize(T what)\n{\n\treturn '[' > what > ']';\n}\n\n// Vector of four ints\nauto boxrule = bracketize(x3::int_ > ',' > x3::int_ > ',' > x3::int_ > ',' > x3::int_);\n// Comma-separated list of such vectors\nauto innerboxlist = (boxrule % ',');\nauto fullboxlist = x3::lit(\"array\") > '(' > bracketize(innerboxlist ) > ',' > \"dtype\" > '=' > (x3::lit(\"int32\") | x3::lit(\"int64\")) > ')';\n// The whole first section of the data file\nauto boxes = bracketize(*(fullboxlist));\n\n// Array of lists of doubles\nauto scorelist = x3::lit(\"array\") > '(' > bracketize(x3::double_ % ',') > ')';\nauto scores = bracketize(*(scorelist));\n\ntemplate<class RuleType, class AttrType> void parseToEndWithError(istream& file, const RuleType& rule, AttrType& target)\n{\n\tauto parseriter = boost::spirit::istream_iterator(file);\n\tboost::spirit::istream_iterator end;\n\n\tbool res = phrase_parse(parseriter, end, rule, x3::space - x3::eol, target);\n\n\tif (!res)\n\t{\n\t\tstd::string val;\n\t\tfile >> val;\n\t\tthrow logic_error(\"Parsing failed. \" + (std::string) __func__ + \" \" + val);\n\t}\n}\n\nstruct wordmapper\n{\nprivate:\n\tmap<string, int> mapping;\n\tmap<int, string> inversemapping;\npublic:\n\tint getMapping(const string& word)\n\t{\n\t\tauto i = mapping.find(word);\n\t\tif (i != mapping.end())\n\t\t{\n\t\t\treturn i->second;\n\t\t}\n\n\t\tint index = mapping.size();\n\t\tmapping[word] = index;\n\t\tinversemapping[index] = word;\n\n\t\treturn index;\n\t}\n\n\tstring getWord(int mapping)\n\t{\n\t\treturn inversemapping[mapping];\n\t}\n\n\tint size()\n\t{\n\t\treturn mapping.size();\n\t}\n} wordmap;\n\n// Coming in C++ 17\ntemplate <class T>\nconstexpr std::add_const_t<T>& as_const_cheat(const T& t) noexcept\n{\n\treturn t;\n}\n\nauto word_ = x3::lexeme[+(x3::char_ - x3::space)];\nauto linefile = *word_ % x3::eol;\nconstexpr int statelimit = 4000;\n\nusing stateVec = array<double, statelimit>;\n\nstruct hmmtype\n{\n\tvector<vector<box>> ourBoxes;\n\tvector<vector<double>> scoreVals;\n\tvector<bool> lineEnd;\n\n\tstateVec fwbw[2][statelimit] = { 0 };\n\n\tvoid prepareLineEnd(const vector<vector<int>>& introws)\n\t{\n\t\tlineEnd.reserve(scoreVals.size());\n\t\tfor (const auto& r : introws)\n\t\t{\n\t\t\tfor (int i : r)\n\t\t\t{\n\t\t\t\tlineEnd.push_back(false);\n\t\t\t}\n\t\t\t*(lineEnd.end() - 1) = true;\n\t\t}\n\t}\n\n\tvoid emit(stateVec& state, int pos)\n\t{\n\t\tfor (int i = 0; i < scoreVals[pos].size(); i++)\n\t\t{\n\t\t\tstate[i] *= max(1e-50, scoreVals[pos][i]);\n\t\t}\n\t}\n\n\tstatic double transProb(const box& a, const box& b, bool linebreak)\n\t{\n\t\tbool ok = false;\n\t\tint height = max(a[3] - a[1], b[3] - b[1]);\n\t\tif (linebreak)\n\t\t{\n\t\t\tif (b[3] > a[1]) ok = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (b[0] > a[0] && b[1] > a[1] - height && b[1] < a[1] + height) ok = true;\n\t\t}\n\n\t\treturn (ok ? 1 : 1e-2) * (1 - 0.99 * area(intersect(a, b)) / max(min(area(a), area(b)) * 1., 1e-9)) * (linebreak ? 1. : 0.01 + 0.99 * (area(a) + area(b) - area(intersect(a,b))) / max(area(boxunion(a, b)), 1));\n\t}\n\n\ttemplate<int dir> void transition(const stateVec& fState, stateVec& tState, int fromPos, int toPos)\n\t{\n\t\tstatic_assert(dir == -1 || dir == 1);\n\n\t\tfor (int i = 0; i < scoreVals[toPos].size(); i++)\n\t\t{\n\t\t\ttState[i] = 0;\n\t\t}\n\n\t\tfor (int i = 0; i < scoreVals[fromPos].size(); i++)\n\t\t{\n\t\t\tfor (int j = 0; j < scoreVals[toPos].size(); j++)\n\t\t\t{\n\t\t\t\tbox* fromBox = &ourBoxes[fromPos][i];\n\t\t\t\tbox* toBox = &ourBoxes[toPos][j];\n\t\t\t\tint fIndex = fromPos;\n\n\t\t\t\tif (dir == -1)\n\t\t\t\t{\n\t\t\t\t\tfIndex = toPos;\n\t\t\t\t\tswap(fromBox, toBox);\n\t\t\t\t}\n\n\t\t\t\ttState[j] += fState[i] * transProb(*fromBox, *toBox, lineEnd[fIndex]);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid normalize(stateVec& state, int pos)\n\t{\n\t\tdouble sum = 0;\n\t\tfor (int i = 0; i < scoreVals[pos].size(); i++)\n\t\t{\n\t\t\tsum += state[i];\n\t\t}\n\t\tif (isnan(sum)) cerr << \"Normalization error at \" << pos << \"\\n\";\n\t\tif (sum == 0) cerr << \"Zero at \" << pos << \"\\n\";\n\t\t//cout << \"Sum at \" << pos << \":\" << sum << \"\\n\";\n\n\t\tif (sum < 1e-10)\n\t\t{\n\t\t\tfor (int i = 0; i < scoreVals[pos].size(); i++)\n\t\t\t{\n\t\t\t\tstate[i] *= 1e150;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid computeFB()\n\t{\n\t\t// FW\n\t\tfor (int i = 0; i < scoreVals[0].size(); i++)\n\t\t{\n\t\t\tfwbw[0][0][i] = 1;\n\t\t}\n\n\t\tfor (int i = 0; i < scoreVals.size(); i++)\n\t\t{\n\t\t\temit(fwbw[0][i], i);\n\t\t\tif (i != scoreVals.size() - 1)\n\t\t\t{\n\t\t\t\ttransition<1>(fwbw[0][i], fwbw[0][i + 1], i, i + 1);\n\t\t\t}\n\n\t\t\tnormalize(fwbw[0][i + 1], i);\n\t\t}\n\n\t\t// BW\n\t\tfor (int i = 0; i < scoreVals[scoreVals.size() - 1].size(); i++)\n\t\t{\n\t\t\tfwbw[1][scoreVals.size() - 1][i] = 1;\n\t\t}\n\n\t\tfor (int i = scoreVals.size() - 1; i != 0; i--)\n\t\t{\n\t\t\tstateVec copy = fwbw[1][i];\n\t\t\temit(copy, i);\n\t\t\ttransition<-1>(copy, fwbw[1][i - 1], i, i - 1);\t\t\t\n\n\t\t\tnormalize(fwbw[1][i - 1], i - 1);\n\t\t}\n\t}\n\n\tvoid fakeFB()\n\t{\n\t\t// FW\n\t\tfor (int j = 0; j < scoreVals.size(); j++)\n\t\t{\n\t\t\tfor (int i = 0; i < scoreVals[j].size(); i++)\n\t\t\t{\n\t\t\t\tfwbw[0][j][i] = 1;\n\t\t\t}\n\n\t\t\temit(fwbw[0][j], j);\n\t\t}\t\n\n\t\t// BW\n\t\tfor (int j = 0; j < scoreVals.size(); j++)\n\t\t{\n\t\t\tfor (int i = 0; i < scoreVals[j].size(); i++)\n\t\t\t{\n\t\t\t\tfwbw[1][j][i] = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\tstateVec getProbs(int pos) const\n\t{\n\t\tstateVec toret;\n\t\tdouble sum = 0;\n\t\tfor (int i = 0; i < scoreVals[pos].size(); i++)\n\t\t{\n\t\t\ttoret[i] = fwbw[0][pos][i] * fwbw[1][pos][i];\n\t\t\tsum += toret[i];\n\t\t}\n\n\t\tsum = 1 / sum;\n\t\tfor (int i = 0; i < scoreVals[pos].size(); i++)\n\t\t{\n\t\t\ttoret[i] *= sum;\n\t\t}\n\n\t\treturn toret;\n\t}\n\n\tvoid softmax(double factor)\n\t{\n\t\tfor (auto& scoreList : scoreVals)\n\t\t{\n\t\t\tdouble maxVal = 0;\n\t\t\tfor (double& score : scoreList)\n\t\t\t{\n\t\t\t\tscore *= factor;\n\t\t\t\tmaxVal = max(score, maxVal);\n\t\t\t}\n\n\t\t\tdouble sum = 0;\n\t\t\tfor (double score : scoreList)\n\t\t\t{\n\t\t\t\tsum += exp(score * score);\n\t\t\t\t//sum += exp(score - maxVal);\n\t\t\t}\n\n\t\t\tfor (double& score : scoreList)\n\t\t\t{\n\t\t\t\tscore = exp(score * score) / sum;\n\t\t\t\t//score = exp(score - maxVal) / sum;\n\t\t\t}\n\t\t}\n\t}\n} hmm;\n\ntemplate<bool doimg> void writeWithSeparator(const string& separator\n#ifdef DOMAGICK\n\t, Magick::Image img, string path\n#endif\n)\n{\n#ifdef DOMAGICK\n\tstd::list<Magick::Drawable> drawList;\n\tdrawList.push_back(Magick::DrawableFillOpacity(0));\n\tdrawList.push_back(Magick::DrawableStrokeWidth(5));\n\tdrawList.push_back(Magick::DrawableStrokeColor(\"white\"));\n\tarray<string, 3> colors = { \"red\", \"green\", \"blue\" };\n\n\tif constexpr (doimg)\n\t{\t\t\n\t\timg.strokeWidth(0.5);\n\t\t//drawList.push_back(Magick::DrawableStrokeOpacity(0.25));\n\t}\n#endif\n\n\tfor (int i = 0; i < hmm.scoreVals.size(); i++)\n\t{\n\t\tstateVec states = hmm.getProbs(i);\n\t\tint maxindex = 0;\n\t\tfor (int j = 0; j < hmm.scoreVals[i].size(); j++)\n\t\t{\n\t\t\tif (states[j] > states[maxindex]) maxindex = j;\n\t\t}\n\t\tcout << maxindex << \":\" << states[maxindex];\n\t\t/*for (int j = 0; j < 4; j++)\n\t\t{\n\t\tcout << \":\" << hmm.ourBoxes[i][maxindex][j];\n\t\t}*/\n\t\t//img.fillColor(Magick::Color::Color(0, 0, 0, 65535 - states[maxindex] * 65535));\n\t\tconst box& b = hmm.ourBoxes[i][maxindex];\n\n#ifdef DOMAGICK\n\t\tif constexpr (doimg)\n\t\t{\n\t\t\tdrawList.push_back(Magick::DrawableRectangle(b[0], b[1], b[2], b[3]));\n\t\t\timg.draw(drawList);\n\t\t\tdrawList.pop_back();\n\n\t\t\timg.strokeColor(colors[i % 3]);\n\t\t\timg.draw(Magick::DrawableText(b[0] + 20, b[1] + 20, boost::lexical_cast<string>(i) + \":\" + boost::str(boost::format(\"%.2f\") % states[maxindex])));\n\t\t}\n#endif\n\t\tcout << \" \";\n\t\tif (hmm.lineEnd[i]) cout << separator << \"\\n\";\n\t}\n#ifdef DOMAGICK\n\tif constexpr (doimg)\n\t{\n\t\timg.write(path);\n\t}\n#endif\n}\n\nvoid writeDiffs(const vector<int>& words)\n{\n\tvector<stateVec> wordScoresNew;\n\tvector<stateVec> wordScoresOld;\n\twordScoresNew.resize(wordmap.size());\n\twordScoresOld.resize(wordmap.size());\n\tvector<int> lens;\n\tlens.resize(wordmap.size());\n\tfill(lens.begin(), lens.end(), 0);\n\n\t\n\tfor (int i = 0; i < hmm.scoreVals.size(); i++)\n\t{\n\t\tif (!lens[words[i]])\n\t\t{\n\t\t\tlens[words[i]] = hmm.scoreVals[i].size();\n\t\t\tfor (int j = 0; j < hmm.scoreVals[i].size(); j++)\n\t\t\t{\n\t\t\t\twordScoresNew[words[i]][j] = 0;\n\t\t\t\twordScoresOld[words[i]][j] = 0;\n\t\t\t}\n\t\t}\n\t\t\n\t\tstateVec states = hmm.getProbs(i);\t\t\n\t\tfor (int j = 0; j < hmm.scoreVals[i].size(); j++)\n\t\t{\n\t\t\twordScoresNew[words[i]][j] += states[j];\n\t\t\twordScoresOld[words[i]][j] += hmm.scoreVals[i][j];\n\t\t}\n\t}\n\n\tcout << \"{\";\n\tbool first = true;\n\tfor (int i = 0; i < wordScoresNew.size(); i++)\n\t{\n\t\tif (!lens[i]) continue;\n\t\tif (!first)\n\t\t{\n\t\t\tcout << \",\\n\";\n\t\t}\n\t\t\n\t\tfirst = false;\n\t\tcout << \"\\\"\" << wordmap.getWord(i) << \"\\\" : \";\n\t\tcout << \"[\";\n\t\tfor (int j = 0; j < lens[i]; j++)\n\t\t{\n\t\t\t// Richer debug:\n\t\t\t//cout << wordScoresNew[i][j] << \":\" << wordScoresOld[i][j] << \":\" << log(sqrt(wordScoresNew[i][j] / wordScoresOld[i][j])) << (j != lens[i] - 1 ? \", \" : \"]\");\n\t\t\tcout << log(sqrt(wordScoresNew[i][j] / wordScoresOld[i][j])) << (j != lens[i] - 1 ? \", \" : \"]\");\n\t\t}\n\t}\n\tcout << \"}\";\n}\n\nint main(int argc, char** argv)\n{\n#ifdef DOMAGICK\n\tMagick::InitializeMagick(0);\n#endif\n\tif (argc < 3)\n\t{\n\t\treturn -1;\n\t}\n\tifstream file(argv[1]);\n\t\n\tparseToEndWithError(file, boxes > scores, as_const_cheat(std::forward_as_tuple(hmm.ourBoxes, hmm.scoreVals)));\n\tcerr << \"Read \" << hmm.ourBoxes.size() << \" box lists and \" << hmm.scoreVals.size() << \" score lists.\" << \"\\n\";\n\n\tfor (int i = 0; i < hmm.ourBoxes.size(); i++)\n\t{\n\t\tif (hmm.ourBoxes[i].size() > statelimit)\n\t\t{\n\t\t\thmm.ourBoxes[i].resize(statelimit);\n\t\t\thmm.scoreVals[i].resize(statelimit);\n\t\t\tfprintf(stderr, \"Capping state count at word %d to limit %d.\\n\", i, statelimit);\n\t\t}\n\t}\n\n\t// Do soft-max with amplification 1\n\thmm.softmax(0.5 * sqrt(108));\t\n\n\tfile = ifstream(argv[2]);\n\tvector<vector<int>> introws;\n\tvector<int> words;\n\tvector<vector<string>> rows;\n\tfile >> noskipws;\n\tparseToEndWithError(file, linefile, rows);\n\n\ttransform(rows.begin(), rows.end(), back_inserter(introws),\n\t\t[](vector<string>& row)\n\t{\n\t\tvector<int> introw;\n\t\ttransform(row.begin(), row.end(), back_inserter(introw),\n\t\t\t[](const string& word)\n\t\t{\n\t\t\treturn wordmap.getMapping(word);\n\t\t});\n\n\t\treturn introw;\n\t});\n\tfor (auto row : introws)\n\t{\n\t\tfor (int w : row)\n\t\t{\n\t\t\twords.push_back(w);\n\t\t}\n\t}\n\n\tif (words.size() != hmm.ourBoxes.size())\n\t{\n\t\tcerr << \"Number of words in transcription is \" << words.size() << \", but number of box lists is \" << hmm.ourBoxes.size() << \". This does not make sense. Terminating.\";\n\n\t\treturn -1;\n\t}\n\n\thmm.prepareLineEnd(introws);\n\n#ifdef DOMAGICK\n\tMagick::Image origImg(argv[3]);\n#endif\n\n\thmm.computeFB();\t\n\twriteWithSeparator<false>(\"//\");// , origImg, string(argv[3]) + \".N.png\");\n\t\n\t// Sanity check, basically compute probs WITHOUT the HMM\n\t//hmm.fakeFB();\n\t//writeWithSeparator(\"//\", origImg, string(argv[3]) + \".naive.png\");\n\n\twriteDiffs(words);\n}\n", "meta": {"hexsha": "9abbf2339a305c88e9addf60c36c3e79b92ae4c2", "size": 11906, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "canaline.cpp", "max_stars_repo_name": "cnettel/canaline", "max_stars_repo_head_hexsha": "952d1d14bc6ef478b6fcaecf68f559b836f35119", "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": "canaline.cpp", "max_issues_repo_name": "cnettel/canaline", "max_issues_repo_head_hexsha": "952d1d14bc6ef478b6fcaecf68f559b836f35119", "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": "canaline.cpp", "max_forks_repo_name": "cnettel/canaline", "max_forks_repo_head_hexsha": "952d1d14bc6ef478b6fcaecf68f559b836f35119", "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": 22.5066162571, "max_line_length": 211, "alphanum_fraction": 0.5918024525, "num_tokens": 4030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2738631569853561}}
{"text": "\n\n//\n//=======================================================================\n// Copyright (c) 2004 Kristopher Beevers\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\n#ifndef BOOST_GRAPH_ASTAR_SEARCH_HPP\n#define BOOST_GRAPH_ASTAR_SEARCH_HPP\n\n\n#include <functional>\n#include <vector>\n#include <boost/limits.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <boost/graph/relax.hpp>\n#include <boost/graph/exception.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/detail/d_ary_heap.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/property_map/vector_property_map.hpp>\n\n\nnamespace boost {\n\n\n  template <class Heuristic, class Graph>\n  struct AStarHeuristicConcept {\n    void constraints()\n    {\n      function_requires< CopyConstructibleConcept<Heuristic> >();\n      h(u);\n    }\n    Heuristic h;\n    typename graph_traits<Graph>::vertex_descriptor u;\n  };\n\n\n  template <class Graph, class CostType>\n  class astar_heuristic : public std::unary_function<\n    typename graph_traits<Graph>::vertex_descriptor, CostType>\n  {\n  public:\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n    astar_heuristic() {}\n    CostType operator()(Vertex u) { return static_cast<CostType>(0); }\n  };\n\n\n\n  template <class Visitor, class Graph>\n  struct AStarVisitorConcept {\n    void constraints()\n    {\n      function_requires< CopyConstructibleConcept<Visitor> >();\n      vis.initialize_vertex(u, g);\n      vis.discover_vertex(u, g);\n      vis.examine_vertex(u, g);\n      vis.examine_edge(e, g);\n      vis.edge_relaxed(e, g);\n      vis.edge_not_relaxed(e, g);\n      vis.black_target(e, g);\n      vis.finish_vertex(u, g);\n    }\n    Visitor vis;\n    Graph g;\n    typename graph_traits<Graph>::vertex_descriptor u;\n    typename graph_traits<Graph>::edge_descriptor e;\n  };\n\n\n  template <class Visitors = null_visitor>\n  class astar_visitor : public bfs_visitor<Visitors> {\n  public:\n    astar_visitor() {}\n    astar_visitor(Visitors vis)\n      : bfs_visitor<Visitors>(vis) {}\n\n    template <class Edge, class Graph>\n    void edge_relaxed(Edge e, Graph& g) {\n      invoke_visitors(this->m_vis, e, g, on_edge_relaxed());\n    }\n    template <class Edge, class Graph>\n    void edge_not_relaxed(Edge e, Graph& g) {\n      invoke_visitors(this->m_vis, e, g, on_edge_not_relaxed());\n    }\n  private:\n    template <class Edge, class Graph>\n    void tree_edge(Edge e, Graph& g) {}\n    template <class Edge, class Graph>\n    void non_tree_edge(Edge e, Graph& g) {}\n  };\n  template <class Visitors>\n  astar_visitor<Visitors>\n  make_astar_visitor(Visitors vis) {\n    return astar_visitor<Visitors>(vis);\n  }\n  typedef astar_visitor<> default_astar_visitor;\n\n\n  namespace detail {\n\n    template <class AStarHeuristic, class UniformCostVisitor,\n              class UpdatableQueue, class PredecessorMap,\n              class CostMap, class DistanceMap, class WeightMap,\n              class ColorMap, class BinaryFunction,\n              class BinaryPredicate>\n    struct astar_bfs_visitor\n    {\n\n      typedef typename property_traits<CostMap>::value_type C;\n      typedef typename property_traits<ColorMap>::value_type ColorValue;\n      typedef color_traits<ColorValue> Color;\n      typedef typename property_traits<DistanceMap>::value_type distance_type;\n\n      astar_bfs_visitor(AStarHeuristic h, UniformCostVisitor vis,\n                        UpdatableQueue& Q, PredecessorMap p,\n                        CostMap c, DistanceMap d, WeightMap w,\n                        ColorMap col, BinaryFunction combine,\n                        BinaryPredicate compare, C zero)\n        : m_h(h), m_vis(vis), m_Q(Q), m_predecessor(p), m_cost(c),\n          m_distance(d), m_weight(w), m_color(col),\n          m_combine(combine), m_compare(compare), m_zero(zero) {}\n\n\n      template <class Vertex, class Graph>\n      void initialize_vertex(Vertex u, Graph& g) {\n        m_vis.initialize_vertex(u, g);\n      }\n      template <class Vertex, class Graph>\n      void discover_vertex(Vertex u, Graph& g) {\n        m_vis.discover_vertex(u, g);\n      }\n      template <class Vertex, class Graph>\n      void examine_vertex(Vertex u, Graph& g) {\n        m_vis.examine_vertex(u, g);\n      }\n      template <class Vertex, class Graph>\n      void finish_vertex(Vertex u, Graph& g) {\n        m_vis.finish_vertex(u, g);\n      }\n      template <class Edge, class Graph>\n      void examine_edge(Edge e, Graph& g) {\n        if (m_compare(get(m_weight, e), m_zero))\n          throw negative_edge();\n        m_vis.examine_edge(e, g);\n      }\n      template <class Edge, class Graph>\n      void non_tree_edge(Edge, Graph&) {}\n\n\n\n      template <class Edge, class Graph>\n      void tree_edge(Edge e, Graph& g) {\n        m_decreased = relax(e, g, m_weight, m_predecessor, m_distance,\n                            m_combine, m_compare);\n\n        if(m_decreased) {\n          m_vis.edge_relaxed(e, g);\n          put(m_cost, target(e, g),\n              m_combine(get(m_distance, target(e, g)),\n                        m_h(target(e, g))));\n        } else\n          m_vis.edge_not_relaxed(e, g);\n      }\n\n\n      template <class Edge, class Graph>\n      void gray_target(Edge e, Graph& g) {\n        m_decreased = relax(e, g, m_weight, m_predecessor, m_distance,\n                            m_combine, m_compare);\n\n        if(m_decreased) {\n          put(m_cost, target(e, g),\n              m_combine(get(m_distance, target(e, g)),\n                        m_h(target(e, g))));\n          m_Q.update(target(e, g));\n          m_vis.edge_relaxed(e, g);\n        } else\n          m_vis.edge_not_relaxed(e, g);\n      }\n\n\n      template <class Edge, class Graph>\n      void black_target(Edge e, Graph& g) {\n        m_decreased = relax(e, g, m_weight, m_predecessor, m_distance,\n                            m_combine, m_compare);\n\n        if(m_decreased) {\n          m_vis.edge_relaxed(e, g);\n          put(m_cost, target(e, g),\n              m_combine(get(m_distance, target(e, g)),\n                        m_h(target(e, g))));\n          m_Q.push(target(e, g));\n          put(m_color, target(e, g), Color::gray());\n          m_vis.black_target(e, g);\n        } else\n          m_vis.edge_not_relaxed(e, g);\n      }\n\n\n\n      AStarHeuristic m_h;\n      UniformCostVisitor m_vis;\n      UpdatableQueue& m_Q;\n      PredecessorMap m_predecessor;\n      CostMap m_cost;\n      DistanceMap m_distance;\n      WeightMap m_weight;\n      ColorMap m_color;\n      BinaryFunction m_combine;\n      BinaryPredicate m_compare;\n      bool m_decreased;\n      C m_zero;\n\n    };\n\n  } // namespace detail\n\n\n\n  template <typename VertexListGraph, typename AStarHeuristic,\n            typename AStarVisitor, typename PredecessorMap,\n            typename CostMap, typename DistanceMap,\n            typename WeightMap, typename ColorMap,\n            typename VertexIndexMap,\n            typename CompareFunction, typename CombineFunction,\n            typename CostInf, typename CostZero>\n  inline void\n  astar_search_no_init\n    (VertexListGraph &g,\n     typename graph_traits<VertexListGraph>::vertex_descriptor s,\n     AStarHeuristic h, AStarVisitor vis,\n     PredecessorMap predecessor, CostMap cost,\n     DistanceMap distance, WeightMap weight,\n     ColorMap color, VertexIndexMap /*index_map*/,\n     CompareFunction compare, CombineFunction combine,\n     CostInf /*inf*/, CostZero zero)\n  {\n    typedef typename graph_traits<VertexListGraph>::vertex_descriptor\n      Vertex;\n    typedef boost::vector_property_map<std::size_t> IndexInHeapMap;\n    IndexInHeapMap index_in_heap;\n    typedef d_ary_heap_indirect<Vertex, 4, IndexInHeapMap, CostMap, CompareFunction>\n      MutableQueue;\n    MutableQueue Q(cost, index_in_heap, compare);\n\n    detail::astar_bfs_visitor<AStarHeuristic, AStarVisitor,\n        MutableQueue, PredecessorMap, CostMap, DistanceMap,\n        WeightMap, ColorMap, CombineFunction, CompareFunction>\n      bfs_vis(h, vis, Q, predecessor, cost, distance, weight,\n              color, combine, compare, zero);\n\n    breadth_first_visit(g, s, Q, bfs_vis, color);\n  }\n\n\n  // Non-named parameter interface\n  template <typename VertexListGraph, typename AStarHeuristic,\n            typename AStarVisitor, typename PredecessorMap,\n            typename CostMap, typename DistanceMap,\n            typename WeightMap, typename VertexIndexMap,\n            typename ColorMap,\n            typename CompareFunction, typename CombineFunction,\n            typename CostInf, typename CostZero>\n  inline void\n  astar_search\n    (VertexListGraph &g,\n     typename graph_traits<VertexListGraph>::vertex_descriptor s,\n     AStarHeuristic h, AStarVisitor vis,\n     PredecessorMap predecessor, CostMap cost,\n     DistanceMap distance, WeightMap weight,\n     VertexIndexMap index_map, ColorMap color,\n     CompareFunction compare, CombineFunction combine,\n     CostInf inf, CostZero zero)\n  {\n\n    typedef typename property_traits<ColorMap>::value_type ColorValue;\n    typedef color_traits<ColorValue> Color;\n    typename graph_traits<VertexListGraph>::vertex_iterator ui, ui_end;\n    for (tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui) {\n      put(color, *ui, Color::white());\n      put(distance, *ui, inf);\n      put(cost, *ui, inf);\n      put(predecessor, *ui, *ui);\n      vis.initialize_vertex(*ui, g);\n    }\n    put(distance, s, zero);\n    put(cost, s, h(s));\n\n    astar_search_no_init\n      (g, s, h, vis, predecessor, cost, distance, weight,\n       color, index_map, compare, combine, inf, zero);\n\n  }\n\n\n\n  namespace detail {\n    template <class VertexListGraph, class AStarHeuristic,\n              class CostMap, class DistanceMap, class WeightMap,\n              class IndexMap, class ColorMap, class Params>\n    inline void\n    astar_dispatch2\n      (VertexListGraph& g,\n       typename graph_traits<VertexListGraph>::vertex_descriptor s,\n       AStarHeuristic h, CostMap cost, DistanceMap distance,\n       WeightMap weight, IndexMap index_map, ColorMap color,\n       const Params& params)\n    {\n      dummy_property_map p_map;\n      typedef typename property_traits<CostMap>::value_type C;\n      astar_search\n        (g, s, h,\n         choose_param(get_param(params, graph_visitor),\n                      make_astar_visitor(null_visitor())),\n         choose_param(get_param(params, vertex_predecessor), p_map),\n         cost, distance, weight, index_map, color,\n         choose_param(get_param(params, distance_compare_t()),\n                      std::less<C>()),\n         choose_param(get_param(params, distance_combine_t()),\n                      closed_plus<C>()),\n         choose_param(get_param(params, distance_inf_t()),\n                      std::numeric_limits<C>::max BOOST_PREVENT_MACRO_SUBSTITUTION ()),\n         choose_param(get_param(params, distance_zero_t()),\n                      C()));\n    }\n\n    template <class VertexListGraph, class AStarHeuristic,\n              class CostMap, class DistanceMap, class WeightMap,\n              class IndexMap, class ColorMap, class Params>\n    inline void\n    astar_dispatch1\n      (VertexListGraph& g,\n       typename graph_traits<VertexListGraph>::vertex_descriptor s,\n       AStarHeuristic h, CostMap cost, DistanceMap distance,\n       WeightMap weight, IndexMap index_map, ColorMap color,\n       const Params& params)\n    {\n      typedef typename property_traits<WeightMap>::value_type D;\n      std::vector<D> distance_map;\n      std::vector<D> cost_map;\n      std::vector<default_color_type> color_map;\n\n      detail::astar_dispatch2\n        (g, s, h,\n         choose_param(cost, vector_property_map<D, IndexMap>(index_map)),\n         choose_param(distance, vector_property_map<D, IndexMap>(index_map)),\n         weight, index_map,\n         choose_param(color, vector_property_map<default_color_type, IndexMap>(index_map)),\n         params);\n    }\n  } // namespace detail\n\n\n  // Named parameter interface\n  template <typename VertexListGraph,\n            typename AStarHeuristic,\n            typename P, typename T, typename R>\n  void\n  astar_search\n    (VertexListGraph &g,\n     typename graph_traits<VertexListGraph>::vertex_descriptor s,\n     AStarHeuristic h, const bgl_named_params<P, T, R>& params)\n  {\n\n    detail::astar_dispatch1\n      (g, s, h,\n       get_param(params, vertex_rank),\n       get_param(params, vertex_distance),\n       choose_const_pmap(get_param(params, edge_weight), g, edge_weight),\n       choose_const_pmap(get_param(params, vertex_index), g, vertex_index),\n       get_param(params, vertex_color),\n       params);\n\n  }\n\n} // namespace boost\n\n#endif // BOOST_GRAPH_ASTAR_SEARCH_HPP\n", "meta": {"hexsha": "4f9563292ebab173500f51fcd69fff7c15a00511", "size": 12719, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/astar_search.hpp", "max_stars_repo_name": "oudream/boost_1_42_0", "max_stars_repo_head_hexsha": "e92227bf374e478030e89876ec353de6eecaeac0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-27T15:35:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-27T15:35:46.000Z", "max_issues_repo_path": "boost/graph/astar_search.hpp", "max_issues_repo_name": "ystk/debian-boost1.42", "max_issues_repo_head_hexsha": "bd93c2f24bcb675701139609a80f689ea5408e73", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/graph/astar_search.hpp", "max_forks_repo_name": "ystk/debian-boost1.42", "max_forks_repo_head_hexsha": "bd93c2f24bcb675701139609a80f689ea5408e73", "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.9507772021, "max_line_length": 91, "alphanum_fraction": 0.6460413555, "num_tokens": 2945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.27381875107934384}}
{"text": "#include <utility/Configuration_Chain.hpp>\n#include <utility/Configurations.hpp>\n#include <data/Spin_System.hpp>\n#include <engine/Vectormath.hpp>\n#include <engine/Manifoldmath.hpp>\n\n#include <Eigen/Dense>\n\n#include <random>\n#include <iostream>\n#include <string>\n#include <vector>\n\n\nnamespace Utility\n{\n\tnamespace Configuration_Chain\n\t{\n\t\tvoid Add_Noise_Temperature(std::shared_ptr<Data::Spin_System_Chain> c, int idx_1, int idx_2, scalar temperature)\n\t\t{\n\t\t\tfor (int img = idx_1 + 1; img <= idx_2 - 1; ++img)\n\t\t\t{\n\t\t\t\tConfigurations::Add_Noise_Temperature(*c->images[img], temperature, img);\n\t\t\t}\n\t\t}\n\n\t\tvoid Homogeneous_Rotation(std::shared_ptr<Data::Spin_System_Chain> c, int idx_1, int idx_2)\n\t\t{\n\t\t\tint nos = c->images[0]->nos;\n\t\t\tint noi = idx_2 - idx_1 + 1;\n\n\t\t\tscalar angle, rot_angle;\n\t\t\tVector3 axis, rot_axis, a, b, temp;\n\n\t\t\tfor (int i = 0; i < nos; ++i)\n\t\t\t{\n\t\t\t\ta = (*c->images[idx_1]->spins)[i];\n\t\t\t\tb = (*c->images[idx_2]->spins)[i];\n\n\t\t\t\trot_angle = Engine::Manifoldmath::dist_greatcircle(a, b);\n\t\t\t\trot_axis = a.cross(b);\n\n\t\t\t\t// If they are not strictly parallel we can rotate\n\t\t\t\tif (rot_axis.norm() > 1e-8)\n\t\t\t\t{\n\t\t\t\t\trot_axis.normalize();\n\n\t\t\t\t\tfor (int img = idx_1+1; img < idx_2; ++img)\n\t\t\t\t\t{\n\t\t\t\t\t\tangle = (img-idx_1)*rot_angle/noi;\n\t\t\t\t\t\tEngine::Vectormath::rotate(a, rot_axis, angle, temp);\n\n\t\t\t\t\t\t(*c->images[img]->spins)[i] = temp;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Otherwise we simply leave the spin untouched\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tfor (int img = idx_1+1; img < idx_2; ++img)\n\t\t\t\t\t{\n\t\t\t\t\t\t(*c->images[img]->spins)[i] = a;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tvoid Homogeneous_Rotation(std::shared_ptr<Data::Spin_System_Chain> c, vectorfield A, vectorfield B)\n\t\t{\n\t\t\t(*c->images[0]->spins) = A;\n\t\t\t(*c->images[c->noi - 1]->spins) = B;\n\n\t\t\tint nos = c->images[0]->nos;\n\n\t\t\tscalar angle, rot_angle;\n\t\t\tVector3 axis, rot_axis, a, b, temp;\n\n\t\t\tfor (int i = 0; i < c->images[0]->nos; ++i)\n\t\t\t{\n\t\t\t\ta = A[i];\n\t\t\t\tb = B[i];\n\t\t\t\t\n\t\t\t\trot_angle = Engine::Manifoldmath::dist_greatcircle(a, b);\n\t\t\t\trot_axis = a.cross(b);\n\n\t\t\t\t// If they are not strictly parallel we can rotate\n\t\t\t\tif (rot_axis.norm() > 1e-8)\n\t\t\t\t{\n\t\t\t\t\trot_axis.normalize();\n\n\t\t\t\t\tfor (int img = 1; img < c->noi - 1; ++img)\n\t\t\t\t\t{\n\t\t\t\t\t\tangle = (img)*rot_angle / (c->noi - 1);\n\t\t\t\t\t\tEngine::Vectormath::rotate(a, rot_axis, angle, temp);\n\n\t\t\t\t\t\t(*c->images[img]->spins)[i] = temp;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Otherwise we simply leave the spin untouched\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tfor (int img = 1; img < c->noi - 1; ++img)\n\t\t\t\t\t{\n\t\t\t\t\t\t(*c->images[img]->spins)[i] = a;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/*\n\t\t\t\tdo i=1,NOS\n\t\t\t\t  Start(i,:)  = Start(i,:)/length(Start(i,:))\n\t\t\t\t  Finish(i,:) = Finish(i,:)/length(Finish(i,:))\n      \n\t\t\t\t  IMAGES(idx_start,i,:)  = Start(i,:)\n\t\t\t\t  IMAGES(idx_finish,i,:) = Finish(i,:)\n      \n\t\t\t\t  r = max(-1.0,min(1.0, dot_product(Start(i,:), Finish(i,:)) )) !! this prevents NaNs from ocurring\n\t\t\t\t  rot_angle(i)  = acos(r)\n\t\t\t\t  rot_axis(i,:) = cross_product(Start(i,:), Finish(i,:))\n\t\t\t\t  if (abs(length(rot_axis(i,:))) > 1e-18) rot_axis(i,:) = rot_axis(i,:)/length(rot_axis(i,:))\n\t\t\t\tenddo\n\t\t\t*/\n\n\t\t\t/*\n\t\t\t\tdo i=idx_start+1,idx_finish-1\n\t\t\t\t  !! loop over spins in image\n\t\t\t\t  do j=1,NOS\n\t\t\t\t\t angle = (i-1)*rot_angle(j)/(idx_finish-idx_start)\n\t\t\t\t\t IMAGES(i,j,:) = rotate_spin(Start(j,:),rot_axis(j,:),angle)\n         \n\t\t\t\t  enddo\n\t\t\t\tenddo\n\t\t\t*/\n\t\t}\n\t}//end namespace Configuration_Chain\n}//end namespace Utility", "meta": {"hexsha": "255a781202258109b54260c8cfa7d3422b9c9946", "size": 3381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/src/utility/Configuration_Chain.cpp", "max_stars_repo_name": "Zeleznyj/spirit", "max_stars_repo_head_hexsha": "5e23bf3be5aa4bacf5aae24514b0b22cbd395619", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T13:54:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T09:10:27.000Z", "max_issues_repo_path": "core/src/utility/Configuration_Chain.cpp", "max_issues_repo_name": "SpiritSuperUser/spirit", "max_issues_repo_head_hexsha": "fbe69c2a9b7a73e8f47d302c619303aea2a22ace", "max_issues_repo_licenses": ["MIT"], "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/utility/Configuration_Chain.cpp", "max_forks_repo_name": "SpiritSuperUser/spirit", "max_forks_repo_head_hexsha": "fbe69c2a9b7a73e8f47d302c619303aea2a22ace", "max_forks_repo_licenses": ["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.8602941176, "max_line_length": 114, "alphanum_fraction": 0.5794143744, "num_tokens": 1127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984137988773, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.273818743491746}}
{"text": "/* Copyright 2015,2016 Tao Xu\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the 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,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\n#include \"Gbm.h\"\n\n#include <boost/scoped_array.hpp>\n#include <boost/shared_ptr.hpp>\n#include <vector>\n\n#include \"Concurrency.h\"\n#include \"Config.h\"\n#include \"DataSet.h\"\n#include \"GbmFun.h\"\n#include \"Tree.h\"\n#include \"TreeRegressor.h\"\n#include <gflags/gflags.h>\n\nnamespace boosting {\n\nusing namespace std;\n\nGbm::Gbm(const GbmFun& fun, const DataSet& ds, const Config& cfg)\n  : fun_(fun), ds_(ds), cfg_(cfg) {\n}\n\nclass ParallelEval : public apache::thrift::concurrency::Runnable {\n public:\n  ParallelEval(\n    CounterMonitor& monitor,\n    const int numExamples,\n    const int numFeatures,\n    const GbmFun& fun,\n    const std::unique_ptr<TreeNode<uint16_t>>& weakModel,\n    const DataSet& ds,\n    const vector<double>& targets,\n    boost::scoped_array<double>& F,\n    boost::scoped_array<double>& subLoss,\n    const int workIdx,\n    const int totalWorkers)\n    : monitor_(monitor), numExamples_(numExamples),\n      numFeatures_(numFeatures), fun_(fun), weakModel_(weakModel),\n      ds_(ds), targets_(targets), F_(F),\n      subLoss_(subLoss), workIdx_(workIdx),\n      totalWorkers_(totalWorkers) {\n  }\n\n  void run() {\n    //boost::scoped_array<uint16_t> fvec(new uint16_t[numFeatures_]);\n    for (int i = 0; i < numExamples_; i++) {\n      if (i % totalWorkers_ == workIdx_) {\n        //ds_.getFeatureVec(i, fvec);\n        //double score = weakModel_->eval(fvec);\n        double score = ds_.getPrediction(weakModel_.get(), i);\n        F_[i] += score;\n        subLoss_[workIdx_] += fun_.getExampleLoss(targets_[i], F_[i]);\n      }\n    }\n    monitor_.decrement();\n  }\n\n private:\n  CounterMonitor& monitor_;\n  const int numExamples_;\n  const int numFeatures_;\n  const GbmFun& fun_;\n  const std::unique_ptr<TreeNode<uint16_t>>& weakModel_;\n  const DataSet& ds_;\n  const vector<double> targets_;\n  boost::scoped_array<double>& F_;\n  boost::scoped_array<double>& subLoss_;\n  const int workIdx_;\n  const int totalWorkers_;\n};\n\nvoid Gbm::getModel(\n  vector<TreeNode<double>*>* model,\n  double fimps[]) {\n\n  const int numExamples = ds_.getNumExamples();\n\n  boost::scoped_array<double> F(new double[numExamples]);\n  boost::scoped_array<double> y(new double[numExamples]);\n\n  double f0 = fun_.getF0(ds_.targets_);\n  for (int i = 0; i < numExamples; i++) {\n    F[i] = f0;\n  }\n\n  model->push_back(new LeafNode<double>(f0));\n\n  double initLoss = fun_.getInitLoss(ds_.targets_);\n\n  LOG(INFO) << \"init avg loss \" << initLoss / numExamples;\n\n  for (int it = 0; it < cfg_.getNumTrees(); it++) {\n\n    LOG(INFO) << \"------- iteration \" << it << \" -------\";\n\n    fun_.getGradient(ds_.targets_, F, y);\n    TreeRegressor regressor(ds_, y, fun_);\n\n    std::unique_ptr<TreeNode<uint16_t>> weakModel(\n      regressor.getTree(cfg_.getNumLeaves(), cfg_.getExampleSamplingRate(),\n                        cfg_.getFeatureSamplingRate(), fimps));\n\n    weakModel->scale(cfg_.getLearningRate());\n\n    model->push_back(mapTree(weakModel.get()));\n\n    VLOG(1) << toPrettyJson(weakModel->toJson(cfg_));\n    double newLoss = 0.0;\n\n    if (FLAGS_num_threads > 1) {\n      CounterMonitor monitor(FLAGS_num_threads);\n      boost::scoped_array<double> subLoss(new double[FLAGS_num_threads]);\n      for (int wid = 0; wid < FLAGS_num_threads; wid++) {\n        subLoss[wid] = 0.0;\n        Concurrency::threadManager->add(\n          boost::shared_ptr<apache::thrift::concurrency::Runnable>(\n            new ParallelEval(monitor, numExamples, ds_.numFeatures_,\n                             fun_, weakModel,\n                             ds_, ds_.targets_, F, subLoss,\n                             wid, FLAGS_num_threads)));\n      }\n      monitor.wait();\n\n      for (int wid = 0; wid < FLAGS_num_threads; wid++) {\n        newLoss += subLoss[wid];\n      }\n    } else {\n      //boost::scoped_array<uint16_t> fvec(new uint16_t[ds_.numFeatures_]);\n      for (int i = 0; i < numExamples; i++) {\n        // ds_.getFeatureVec(i, fvec);\n        // double score = weakModel->eval(fvec);\n        double score = ds_.getPrediction(weakModel.get(), i);\n        F[i] += score;\n        newLoss += fun_.getExampleLoss(ds_.targets_[i], F[i]);\n      }\n    }\n\n    LOG(INFO) << \"total avg loss \" << newLoss/numExamples\n              << \" reduction: \" << 1.0 - newLoss/initLoss;\n  }\n}\n\nTreeNode<double>* Gbm::mapTree(const TreeNode<uint16_t>* rt) {\n  const PartitionNode<uint16_t>* pnode =\n    dynamic_cast<const PartitionNode<uint16_t>*>(rt);\n  if (pnode != NULL) {\n    int fid = pnode->getFid();\n    PartitionNode<double>* newNode = new PartitionNode<double>(\n      fid, ds_.features_[fid].transitions[pnode->getFv()]);\n    newNode->setVote(pnode->getVote());\n    newNode->setLeft(mapTree(pnode->getLeft()));\n    newNode->setRight(mapTree(pnode->getRight()));\n    return newNode;\n  } else {\n    const LeafNode<uint16_t>* lfnode =\n      dynamic_cast<const LeafNode<uint16_t>*>(rt);\n    return new LeafNode<double>(lfnode->getVote());\n  }\n}\n\n}\n", "meta": {"hexsha": "81f52355bf460c263e88585167985ed1b892762a", "size": 5701, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Gbm.cpp", "max_stars_repo_name": "bayesian/boosting", "max_stars_repo_head_hexsha": "fdba746fa5e9e47ee57fb6f32ed6ceb3ea1e50cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-03-10T21:27:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-28T20:53:29.000Z", "max_issues_repo_path": "Gbm.cpp", "max_issues_repo_name": "bayesian/boosting", "max_issues_repo_head_hexsha": "fdba746fa5e9e47ee57fb6f32ed6ceb3ea1e50cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2015-10-07T22:49:47.000Z", "max_issues_repo_issues_event_max_datetime": "2016-02-18T21:20:12.000Z", "max_forks_repo_path": "Gbm.cpp", "max_forks_repo_name": "bayesian/boosting", "max_forks_repo_head_hexsha": "fdba746fa5e9e47ee57fb6f32ed6ceb3ea1e50cf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T19:12:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-26T16:37:19.000Z", "avg_line_length": 31.4972375691, "max_line_length": 75, "alphanum_fraction": 0.6544465883, "num_tokens": 1469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.27380204863356894}}
{"text": "//----------------------------------------------------------------------\r\n//\tFile:\t\t\tsegmentation.cpp\r\n//\tAuthor:\t\t\tElena Garces and Adolfo Munoz\r\n//\tLast modified:\t18/07/2012\r\n//\tDescription:\tfuncions that control the clustering\r\n//----------------------------------------------------------------------\r\n// This file is part of Intrinsic Images by Clustering.\r\n//\r\n//    Intrinsic Images by Clustering is free software: you can redistribute it\r\n//    and/or modify it under the terms of the GNU General Public License as\r\n//    published by the Free Software Foundation, either version 3 of the License,\r\n//     or (at your option) any later version.\r\n//\r\n//    Intrinsic Images by Clustering is distributed in the hope that it will\r\n//    be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n//    GNU General Public License for more details.\r\n//\r\n//    You should have received a copy of the GNU General Public License\r\n//    along with Intrinsic Images by Clustering.  If not,\r\n//\t  see <http://www.gnu.org/licenses/>.\r\n////----------------------------------------------------------------------\r\n\r\n#include \"segmentacion.h\"\r\n#include \"auxiliar.h\"\r\n\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include <boost/numeric/ublas/symmetric.hpp>\r\n\r\n#include <algorithm>\r\n#include <list>\r\n#include <iostream>\r\n#include <fstream>\r\n#include \"CImg.h\"\r\nusing namespace std;\r\nusing namespace cimg_library;\r\n\r\n\r\n\r\n/*-------------------------------------------------------------------------------------------------*/\r\nvoid Segmentacion::updateLabels()\r\n/*-------------------------------------------------------------------------------------------------*/\r\n{\r\n\r\n\tint width = this->imageMapLabels.width();\r\n\tint height = this->imageMapLabels.height();\r\n\r\n\tvector<Cluster> newClusters;\r\n\tvector<int> founds;\r\n\r\n\tcimg_forXY(imageMapLabels,x,y)\r\n\t{\r\n\r\n\t\tint comp = *imageMapLabels.data(x,y,0,0);\r\n\t\tif ( comp != BACKG_CLUSTER )\r\n\t\t{\r\n\t\t\tvector<int>::iterator i = find(founds.begin(), founds.end(), comp);\r\n\r\n\t\t\tif (i == founds.end())\r\n\t\t\t{\r\n\t\t\t\t/* add */\r\n\t\t\t\tfounds.push_back(comp);\r\n\t\t\t\t*imageMapLabels.data(x,y,0,0) = int(founds.size())-1;\r\n\t\t\t\tCluster nuevo(comp, y*width+x);\r\n\t\t\t\tnewClusters.push_back(nuevo);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t/* already exists, update*/\r\n\t\t\t\tint index = std::distance (founds.begin(), i );\r\n\t\t\t\t*imageMapLabels.data(x,y,0,0) = index;\r\n\t\t\t\tnewClusters[index].addPixel(y*width+x);\r\n\r\n\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tsetListOfClusters(newClusters);\r\n}\r\n\r\n\r\n\r\n\r\nint Segmentacion::mergeSegment(const CImg<double>& image, int pos, int min_size_clus)\r\n{\r\n\r\n\tint width = image.width();\r\n\tint n_changes=0;\r\n\r\n\tvector<int> pixels = getListOfClusters()[pos].getPixels();\r\n\r\n\tint idSetCentral = getListOfClusters()[pos].idCluster;\r\n\r\n\tfor (int p = 0; p < (int) pixels.size(); p++)\r\n\t{\r\n\t\tint x = pixels[p] % width;\tint y = pixels[p] / width;\r\n\t\tint idMostSimilar=-1;\r\n\t\tdouble diffMostSimilar=10000000.;\r\n\r\n\t\tint dist = 1;\r\n\t\tfor (int j = y-dist; j <= y+dist; j++) {\r\n\t\t\tfor (int i = x-dist; i <= x+dist; i++) {\r\n\r\n\t\t\t\tint set = getCluster(i,j);\r\n\t\t\t\tif (set >= 0 && set != idSetCentral && getListOfClusters().at(*imageMapLabels.data(i,j,0,0)).size() >= min_size_clus)\r\n\t\t\t\t{\r\n\t\t\t\t\tdouble squaredDiff = 0.0;\r\n\t\t\t\t\tcimg_forC(image,c) squaredDiff += pow(image(i, j,0,c) -  image(x, y,0,c), 2);\r\n\t\t\t\t\tsquaredDiff=sqrt(squaredDiff);\r\n\r\n\r\n\t\t\t\t\tif (squaredDiff < diffMostSimilar)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdiffMostSimilar = squaredDiff;\r\n\t\t\t\t\t\tidMostSimilar = set;\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\tif (idMostSimilar >=0)\r\n\t\t{\r\n\t\t\tn_changes++;\r\n\t\t\tsetCluster(x, y, idMostSimilar);\r\n\t\t}\r\n\t}\r\n\t\treturn n_changes;\r\n}\r\n\r\n\r\n/*-------------------------------------------------------------------------------------------------*/\r\n/*  */\r\n\r\nint Segmentacion::detectSpurious(const CImg<double>& image, int max_size_clus, float percent_external)\r\n/*-------------------------------------------------------------------------------------------------*/\r\n{\r\n\tint total_changes=0;\r\n\r\n\tint width = image.width();\r\n\tfor (int k = 0; k < (int) listOfClusters.size(); k++)\r\n\t{\r\n\t\tif (listOfClusters[k].getPixels().size() < max_size_clus)\r\n\t\t{\r\n\t\t\tvector<int> pixels = listOfClusters[k].getPixels();\r\n\t\t\tint votesBoundary = 0;\r\n\t\t\tfor (int p = 0; p < (int) pixels.size(); p++)\r\n\t\t\t{\r\n\t\t\t\tint x = pixels[p] % width;\r\n\t\t\t\tint y = pixels[p] / width;\r\n\t\t\t\tint idSetCentral = getCluster(x,y); /* id del conjunto del pixel central */\r\n\r\n\t\t\t\tif ( (getCluster(x-1, y) >= 0 && getCluster(x-1, y) != idSetCentral) ||\r\n\t\t\t\t\t(getCluster(x+1, y) >= 0 && getCluster(x+1, y) != idSetCentral) ||\r\n\t\t\t\t\t(getCluster(x, y+1) >= 0 && getCluster(x, y+1) != idSetCentral) ||\r\n\t\t\t\t\t(getCluster(x, y-1) >= 0 && getCluster(x, y-1) != idSetCentral))\r\n\t\t\t\t\tvotesBoundary++;\r\n\t\t\t}\r\n\r\n\t\t\tif (votesBoundary >= percent_external * pixels.size())\r\n\t\t\t{\r\n\t\t\t\tint changes = mergeSegment(image, k, max_size_clus);\r\n\t\t\t\ttotal_changes+=changes;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn total_changes;\r\n}\r\n\r\n\r\n\r\nvoid Segmentacion::mergeSmallClusters(const CImg<double>& image, int max_it,\r\n\t\t\t\t\t\t\t\t   int max_size_clus, float percent_external)\r\n{\r\n\tint n_changes = 1; \tint it = 1;\r\n\twhile (it < max_it && n_changes > 0)\r\n\t{\r\n\t\tn_changes = detectSpurious(image, max_size_clus, percent_external);\r\n\t\t#ifdef VERBOSE\r\n\t\tcout << \"Clustering: --> \\t\\tIteration  \" << it << \" changes \" << n_changes << endl;\r\n\t\t#endif\r\n\t\tupdateLabels();\r\n\t\tit++;\r\n\t}\r\n}\r\n\r\n\r\n\r\ntemplate <typename matrizBoost>\r\nvoid analysis_gradient_clusters(matrizBoost& matrixRatios, const Segmentacion& seg,\r\n\t\t\tconst CImg<double>& input, const MatteImage& matte)\r\n\t{\r\n\t\tint num_sets = int(seg.getListOfClusters().size());\r\n\t\tlist<edge> edges;\r\n\t\tublas::symmetric_matrix<int> edges_counter(num_sets,num_sets);\r\n\r\n\t\tfor (int i=0; i < num_sets; i++)\r\n\t\t\tfor (int j=i; j < num_sets; j++)\r\n\t\t\t{\r\n\t\t\t\tedges_counter(i,j) = 0;\r\n\t\t\t\tmatrixRatios(i,j) = 0.0;\r\n\t\t\t}\r\n\r\n\t\tfor (int i=0; i < num_sets; i++)\r\n\t\t\tmatrixRatios(i,i) = 0.0;\r\n\r\n\r\n\t\tbuildGraph(edges, input, 2, matte);\r\n\t\tfor (list<edge>::const_iterator i=edges.begin(); i != edges.end(); i++)\r\n\t\t{\r\n\t\t\tint aSeg = seg.getCluster((*i).a);\r\n\t\t\tint bSeg = seg.getCluster((*i).b);\r\n\r\n\t\t\tif (aSeg != bSeg && aSeg >= 0 && bSeg >= 0)\r\n\t\t\t{\r\n\t\t\t\tint xa = (*i).a % input.width();\r\n\t\t\t\tint ya = (*i).a / input.width();\r\n\t\t\t\tint xb = (*i).b % input.width();\r\n\t\t\t\tint yb = (*i).b / input.width();\r\n\r\n\t\t\t\tdouble diffgrad =0.0;\r\n\t\t\t\tcimg_forC(input,c)\r\n\t\t\t\t{\r\n\t\t\t\t\tdiffgrad+= fabs(input(xa, ya,0,c) - input(xb, yb,0,c));\r\n\t\t\t\t}\r\n\t\t\t\tdiffgrad/=input.spectrum();\r\n\r\n\r\n\t\t\t\tif (aSeg <= bSeg)\r\n\t\t\t\t{\r\n\t\t\t\t\tedges_counter(aSeg,bSeg)++;\r\n\t\t\t\t\tmatrixRatios(aSeg,bSeg)+=diffgrad;\r\n\t\t\t\t} else\r\n\t\t\t\t{\r\n\t\t\t\t\tedges_counter(bSeg,aSeg)++;\r\n\t\t\t\t\tmatrixRatios(bSeg,aSeg)+=diffgrad;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfor (int i=0; i < num_sets; i++)\r\n\t\t\tfor (int j=(i+1); j < num_sets; j++)\r\n\t\t\t{\r\n\t\t\t\tif (matrixRatios(i,j)!=0)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (edges_counter(i,j) > 15)\r\n\t\t\t\t\t\tmatrixRatios(i,j)/=edges_counter(i,j);\r\n\t\t\t\t\telse matrixRatios(i,j)=0.0;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t}\r\n\r\n\r\nbool func_ord_e(const edge &a, const edge &b)\r\n\t{ return (a.w < b.w);}\r\n\r\n\r\nint Segmentacion::mergeSmoothBoundaries(CImg<double> *im_input, const MatteImage &matte, vector<tpPair> &paresR)\r\n{\r\n\r\n\tint width = im_input->width();\r\n\tint height = im_input->height();\r\n\r\n\r\n\tfor (unsigned int p=0; p < paresR.size(); p++)\r\n\t{\r\n\t\tparesR[p].i= imageMapLabels( paresR[p].i % im_input->width(), paresR[p].i / im_input->width(),0,0);\r\n\t\tparesR[p].j= imageMapLabels( paresR[p].j % im_input->width(), paresR[p].j / im_input->width(),0,0);\r\n\t}\r\n\r\n\r\n\tfloat max_grad = percent_grad_max*im_input->max();\r\n\r\n\r\n\t/* MERGE, ANALYZING GRADIENTS */\r\n\tint num_sets = int(getListOfClusters().size());\r\n\tublas::symmetric_matrix<float> matrixRatios(num_sets,num_sets);\r\n\tanalysis_gradient_clusters(matrixRatios, *(this),*im_input,matte);\r\n\r\n\tvector<edge> edges;\r\n\r\n\tint n=0;\r\n\tfor (int i=0; i < num_sets; i++)\r\n\t\tfor (int j=(i+1); j < num_sets; j++)\r\n\t\t{\r\n\t\t\tif (matrixRatios(i,j) != 0)\r\n\t\t\t{\r\n\t\t\t\tdouble diff=matrixRatios(i,j);\r\n\t\t\t\tif (diff  < max_grad)\r\n\t\t\t\t\tedges.push_back(edge(i,j,diff));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\tstd::sort(edges.begin(), edges.end(), func_ord_e);\r\n\r\n\tvector<bool> tratados(getListOfClusters().size(),false);\r\n\tvector<bool> referenciado(getListOfClusters().size(),false);\r\n\r\n\tint n_changes=0;\r\n\tfor (vector<edge>::const_iterator i=edges.begin(); i != edges.end(); i++)\r\n\t{\r\n\t\tint peq, grand;\r\n\t\tif (getListOfClusters()[(*i).a].size() < getListOfClusters()[(*i).b].size())\r\n\t\t{\r\n\t\t\tpeq = (*i).a;\r\n\t\t\tgrand = (*i).b;\r\n\t\t} else  {\r\n\t\t\tpeq = (*i).b;\r\n\t\t\tgrand = (*i).a;\r\n\t\t}\r\n\r\n\t\tif (tratados[grand] == false)\r\n\t\t{\r\n\r\n\t\t\tn_changes++;\r\n\t\t\t// remove the smaller cluster\r\n\t\t\tfor (unsigned int p=0; p < getListOfClusters()[peq].size(); p++)\r\n\t\t\t{\r\n\t\t\t\tsetCluster(getListOfClusters()[peq].getPixels()[p], grand);\r\n\t\t\t}\r\n\t\t\ttratados[peq]=true;\r\n\t\t\tlistOfClusters[grand].addPixel(listOfClusters[peq].getPixels());\r\n\r\n\t\t\tfor (unsigned int i=0; i < paresR.size(); i++)\r\n\t\t\t{\r\n\t\t\t\tif (paresR[i].valid && (paresR[i].i==peq || paresR[i].j == peq))\r\n\t\t\t\t{\r\n\t\t\t\t\tparesR[i].valid=false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tvector<tpPair> paresRnew;\r\n\tfor (unsigned int i=0; i < paresR.size(); i++)\r\n\t{\r\n\t\t\tif (paresR[i].valid)\r\n\t\t\t{\r\n\t\t\t\ttpPair aux;\r\n\t\t\t\taux.i = getListOfClusters()[paresR[i].i].getPixels()[0];\r\n\t\t\t\taux.j = getListOfClusters()[paresR[i].j].getPixels()[0];\r\n\t\t\t\taux.valid = true;\r\n\t\t\t\tparesRnew.push_back(aux);\r\n\t\t\t}\r\n\r\n\t}\r\n\tparesR = paresRnew;\r\n\tupdateLabels();\r\n\r\n\t//* --------------------------------------------------*/\r\n\r\n\r\n\treturn n_changes;\r\n\r\n\r\n\r\n}\r\n\r\n\r\nvoid Segmentacion::updateReflectancePairs(vector<tpPair>& eqReflectance,  CImg<double> *luminance, int MIN_SIZE_CLUS)\r\n{\r\n\tvector<tpPair> eqReflectancenew;\r\n\tfloat MIN_VARIATION_L = (float) 0.07*luminance->max();\r\n\r\n\r\n\tif (eqReflectance.size() > 0)\r\n\t{\r\n\t\tvector<float> averageLuminance(getListOfClusters().size(), -1);\r\n\t\tint index=0;\r\n\t\tfor (unsigned int i=0; i < eqReflectance.size(); i++)\r\n\t\t{\r\n\t\t\ttpPair aux;\r\n\t\t\taux.valid=true;\r\n\t\t\taux.i = imageMapLabels(eqReflectance[i].i % width(),eqReflectance[i].i / width(),0,0);\r\n\t\t\taux.j = imageMapLabels(eqReflectance[i].j % width(),eqReflectance[i].j / width(),0,0);\r\n\r\n\t\t\tif (aux.i > aux.j) std::swap(aux.i, aux.j);\r\n\r\n\t\t\tif (aux.i != aux.j && getListOfClusters().at(aux.i).size() > MIN_SIZE_CLUS && getListOfClusters().at(aux.j).size() > MIN_SIZE_CLUS)\r\n\t\t\t{\r\n\t\t\t\taverageLuminance[aux.i] = (averageLuminance[aux.i] < 0) ? computeMean(luminance, getListOfClusters().at(aux.i).getPixels()) : averageLuminance[aux.i];\r\n\t\t\t\taverageLuminance[aux.j] = (averageLuminance[aux.j] < 0) ? computeMean(luminance, getListOfClusters().at(aux.j).getPixels()) : averageLuminance[aux.j];\r\n\r\n\t\t\t\tif (averageLuminance[aux.i]  > 0 && averageLuminance[aux.j] > 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tdouble diff = fabs(averageLuminance[aux.i]-averageLuminance[aux.j]);\r\n\t\t\t\t\tif (diff < MIN_VARIATION_L)\teqReflectancenew.push_back(aux);\r\n\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}\r\n\r\n\teqReflectance=eqReflectancenew;\r\n\r\n}\r\n\r\n\r\nvector<tpPair> Segmentacion::searchPairsRcte(Segmentacion& seg_old)\r\n{\r\n\r\n\tvector<tpPair> pairsReflectance;\r\n\tvector< vector<int> > vec(seg_old.getListOfClusters().size(), vector<int>(0));\r\n\tfor (unsigned int s = 0; s < getListOfClusters().size(); s++)\r\n\t{\r\n\t\tint p = getListOfClusters()[s].getPixels()[0];\r\n\t\tint clus_old=seg_old.getCluster(p);\r\n\t\tif (getListOfClusters()[s].getPixels().size() > 100)\r\n\t\t\tvec[clus_old].push_back(s);\r\n\t}\r\n\r\n\tfor (unsigned int s = 0; s < vec.size(); s++)\r\n\t{\r\n\t\tfor (unsigned int subS = 0; subS < vec[s].size(); subS++)\r\n\t\t{\r\n\r\n\t\t\tfor (unsigned int sS = subS+1; sS < vec[s].size(); sS++)\r\n\t\t\t{\r\n\t\t\t\tint clusa=vec[s][subS];\r\n\t\t\t\tint clusb=vec[s][sS];\r\n\r\n\t\t\t\ttpPair aux;\r\n\t\t\t\taux.i = getListOfClusters()[clusa].getPixels()[0];\r\n\t\t\t\taux.j = getListOfClusters()[clusb].getPixels()[0];\r\n\r\n\t\t\t\tpairsReflectance.push_back(aux);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn pairsReflectance;\r\n}\r\n\r\n\r\n\r\nvoid Segmentacion::scanline(unsigned int coriginal, unsigned int cnew, int x, int y, Segmentacion& sol)\r\n{\r\n\tint x2;\r\n\r\n\tif (getCluster(x,y) != BACKG_CLUSTER)\r\n\t{\r\n\t\tfor (x2 = x; (getCluster(x2,y)==coriginal);x2++)\tsol.setCluster(x2,y,cnew);\r\n\r\n\t\tfor (x2 = (x - 1); (getCluster(x2,y)==coriginal);x2--) sol.setCluster(x2,y,cnew);\r\n\r\n\t\tfor (x2 = (x - 1); (sol.getCluster(x2,y)==cnew) && (getCluster(x2,y)==coriginal);x2--)\r\n\t\t{\r\n\t\t\tif ( (sol.getCluster(x2,y-1)==NON_ASIGN) && (getCluster(x2,y-1)==coriginal) ) scanline(coriginal,cnew,x2,y-1,sol);\r\n\t\t\tif ( (sol.getCluster(x2,y+1)==NON_ASIGN) && (getCluster(x2,y+1)==coriginal) ) scanline(coriginal,cnew,x2,y+1,sol);\r\n\t\t}\r\n\t\tfor (x2 = x; (sol.getCluster(x2,y)==cnew) && (getCluster(x2,y)==coriginal);x2++)\r\n\t\t{\r\n\t\t\tif ( (sol.getCluster(x2,y-1)==NON_ASIGN) && (getCluster(x2,y-1)==coriginal) ) scanline(coriginal,cnew,x2,y-1,sol);\r\n\t\t\tif ( (sol.getCluster(x2,y+1)==NON_ASIGN) && (getCluster(x2,y+1)==coriginal) ) scanline(coriginal,cnew,x2,y+1,sol);\r\n\t\t}\r\n\r\n\t\tfor (x2 = (x - 1); (sol.getCluster(x2,y)==cnew) && (getCluster(x2,y)==coriginal);x2--)\r\n\t\t{\r\n\t\t\tif ( (sol.getCluster(x2+1,y-1)==NON_ASIGN) && (getCluster(x2+1,y-1)==coriginal) ) scanline(coriginal,cnew,x2+1,y-1,sol);\r\n\t\t\tif ( (sol.getCluster(x2-1,y-1)==NON_ASIGN) && (getCluster(x2-1,y-1)==coriginal) ) scanline(coriginal,cnew,x2-1,y-1,sol);\r\n\r\n\t\t\tif ( (sol.getCluster(x2+1,y+1)==NON_ASIGN) && (getCluster(x2+1,y+1)==coriginal) ) scanline(coriginal,cnew,x2+1,y+1,sol);\r\n\t\t\tif ( (sol.getCluster(x2-1,y+1)==NON_ASIGN) && (getCluster(x2-1,y+1)==coriginal) ) scanline(coriginal,cnew,x2-1,y+1,sol);\r\n\r\n\t\t}\r\n\r\n\t\tfor (x2 = x; (sol.getCluster(x2,y)==cnew) && (getCluster(x2,y)==coriginal);x2++)\r\n\t\t{\r\n\t\t\tif ( (sol.getCluster(x2+1,y-1)==NON_ASIGN) && (getCluster(x2+1,y-1)==coriginal) ) scanline(coriginal,cnew,x2+1,y-1,sol);\r\n\t\t\tif ( (sol.getCluster(x2-1,y-1)==NON_ASIGN) && (getCluster(x2-1,y-1)==coriginal) ) scanline(coriginal,cnew,x2-1,y-1,sol);\r\n\r\n\t\t\tif ( (sol.getCluster(x2+1,y+1)==NON_ASIGN) && (getCluster(x2+1,y+1)==coriginal) ) scanline(coriginal,cnew,x2+1,y+1,sol);\r\n\t\t\tif ( (sol.getCluster(x2-1,y+1)==NON_ASIGN) && (getCluster(x2-1,y+1)==coriginal) ) scanline(coriginal,cnew,x2-1,y+1,sol);\r\n\r\n\t\t}\r\n\t} else sol.setCluster(x,y,BACKG_CLUSTER);\r\n}\r\n\r\nSegmentacion Segmentacion::get_separate_noncontiguous_clusters()\r\n{\r\n\tSegmentacion sol(width(),height());\r\n\tsol.imageMapLabels.fill(NON_ASIGN);\r\n\tunsigned int cnew = 0;\r\n\tint x=0, y=0;\r\n\r\n\twhile (y<height())\r\n\t{\r\n\t\twhile ( (sol.getCluster(x,y)!=NON_ASIGN) && (y<height()) )\r\n\t\t{\r\n\t\t\tx++;\r\n\t\t\tif (x>=width()) { x = 0; y++;}\r\n\t\t}\r\n\r\n\t\tif (y<height())\tscanline(getCluster(x,y),cnew,x,y,sol);\r\n\t\tcnew++;\r\n\t}\r\n\treturn sol;\r\n}\r\n\r\n", "meta": {"hexsha": "20ffedc62d05fbd40a4db36436107f096e87a200", "size": 14559, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "server/intrinsic/algorithm/garces2012/intrinsic_code/src/segmentacion.cpp", "max_stars_repo_name": "paulu/opensurfaces", "max_stars_repo_head_hexsha": "7f3e987560faa62cd37f821760683ccd1e053c7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-02-19T00:00:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T03:56:01.000Z", "max_issues_repo_path": "server/intrinsic/algorithm/garces2012/intrinsic_code/src/segmentacion.cpp", "max_issues_repo_name": "paulu/opensurfaces", "max_issues_repo_head_hexsha": "7f3e987560faa62cd37f821760683ccd1e053c7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T23:39:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-19T11:40:55.000Z", "max_forks_repo_path": "server/intrinsic/algorithm/garces2012/intrinsic_code/src/segmentacion.cpp", "max_forks_repo_name": "paulu/opensurfaces", "max_forks_repo_head_hexsha": "7f3e987560faa62cd37f821760683ccd1e053c7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 49.0, "max_forks_repo_forks_event_min_datetime": "2015-02-09T15:21:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T14:22:33.000Z", "avg_line_length": 29.0598802395, "max_line_length": 155, "alphanum_fraction": 0.5842434233, "num_tokens": 4437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.27380204863356894}}
{"text": "// Copyright (C) 2002-2006 Klaas Gadeyne <first dot last at gmail dot com>\n//\n// This program 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 2.1 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 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 this program; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.\n//\n#include \"rng.h\"\n\n#include <../config.h>\n#ifdef __RNGWRAPPER_BOOST__  // BOOST RANDOM LIBRARY\n// THE BOOST RANDOM NUMBER GENERATION LIBRARY\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/uniform_real.hpp>\n\nstatic boost::mt19937 Boost_Rng; // Source of randomness\n\nstatic boost::uniform_real<double> Uniform_Distribution; // Uniform distribution\nstatic boost::variate_generator<boost::mt19937&,boost::uniform_real<double> > roll(Boost_Rng,Uniform_Distribution);\n\ndouble BFL::rnorm(const double& mu,const double& sigma)\n{\n  boost::normal_distribution<double> TestDist(mu,sigma);\n  boost::variate_generator <boost::mt19937 &,boost::normal_distribution<double> > TestGen(Boost_Rng,TestDist);\n  return TestGen();\n}\n\ndouble BFL::runif()\n{\n  return roll();\n}\n\ndouble BFL::runif(const double &min, const double& max)\n{\n  boost::uniform_real<double> Uniform_DistributionMinMax(min,max); // Uniform distribution\n  boost::variate_generator<boost::mt19937&,boost::uniform_real<double> > roll(Boost_Rng,Uniform_DistributionMinMax);\n  return roll();\n}\n\n#endif // __RNGWRAPPER_BOOST__\n\n\n\n\n\n\n", "meta": {"hexsha": "5327cee6c23debeb639ca241e9403aa0393791b1", "size": 2054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/turtlebot2_src/src/orocos-bayesian-filtering/orocos_bfl/src/wrappers/rng/rng.cpp", "max_stars_repo_name": "alexoterno/turtlebot2_with_head", "max_stars_repo_head_hexsha": "ac714f77379dd0f47ddb76d83896fdabee269a03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/turtlebot2_src/src/orocos-bayesian-filtering/orocos_bfl/src/wrappers/rng/rng.cpp", "max_issues_repo_name": "alexoterno/turtlebot2_with_head", "max_issues_repo_head_hexsha": "ac714f77379dd0f47ddb76d83896fdabee269a03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/turtlebot2_src/src/orocos-bayesian-filtering/orocos_bfl/src/wrappers/rng/rng.cpp", "max_forks_repo_name": "alexoterno/turtlebot2_with_head", "max_forks_repo_head_hexsha": "ac714f77379dd0f47ddb76d83896fdabee269a03", "max_forks_repo_licenses": ["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.2333333333, "max_line_length": 116, "alphanum_fraction": 0.7643622201, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.27380204863356894}}
{"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/*\n * qchem_interface.cpp\n */\n\n#include \"qchem_interface.h\"\n\n#include <algorithm>\n#include <chrono>\n#include <Eigen/Dense>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <string>\n\n#include \"gto_ordering.h\"\n#include \"opencap_exception.h\"\n#include \"utils.h\"\n\n\nvoid qchem_parse_fchk_dms(std::string dmat_filename,std::vector<std::vector<Eigen::MatrixXd>> &alpha_opdms,\n\t\tstd::vector<std::vector<Eigen::MatrixXd>> &beta_opdms, size_t nstates, size_t ntdm, BasisSet &bs,\n\t\tbool symmetric_rdm, bool do_spin)\n{\n\talpha_opdms = std::vector< std::vector<Eigen::MatrixXd>>(nstates, std::vector<Eigen::MatrixXd> (nstates));\n\tbeta_opdms = std::vector< std::vector<Eigen::MatrixXd>>(nstates, std::vector<Eigen::MatrixXd> (nstates));\n\tint lt_number = bs.Nbasis*(bs.Nbasis+1)/2;\n\tint lt_tdm = nstates*(nstates+1)/2 - nstates;\n\tstd::ifstream is(dmat_filename);\n\tstd::vector<Eigen::MatrixXd> alpha_tdms;\n\tstd::vector<Eigen::MatrixXd> beta_tdms;\n    if (is.good())\n    {\n    \tstd::string line, rest;\n    \tstd::getline(is, line);\n    \tauto start = std::chrono::high_resolution_clock::now();\n    \tfor (size_t i=0;i<nstates;i++)\n    \t{\n    \t\t\t//alpha first, then beta\n    \t\t\tfor(size_t spin=0;spin<=do_spin;spin++)\n    \t\t\t{\n\t\t\t\t\twhile(line.find(\"State Density\")== std::string::npos)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::getline(is,line);\n\t    \t    \t\tif (is.peek()==EOF)\n\t    \t    \t\t\topencap_throw(\"Error: Reached end of file before densities for \"+\n\t    \t    \t\t\t\t\tstd::to_string(nstates) + \" states were found.\");\n\t\t\t\t\t}\n\t\t\t\t\t//last part of line should be number of elements to read\n\t\t\t\t\tint num_elements = stoi(split(line,' ').back());\n\t\t\t\t\tif(sqrt(num_elements)!=bs.Nbasis && num_elements!=lt_number)\n\t\t\t\t\t\topencap_throw(\"Error: dimensions of TDMs do not match specified basis set.\");\n\t\t\t\t\tsize_t lines_to_read = num_elements%5==0 ? (num_elements/5) : num_elements/5+1;\n\t\t\t\t\tstd::vector<double> matrix_elements;\n\t\t\t\t\tfor (size_t k=1;k<=lines_to_read;k++)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::getline(is,line);\n\t\t\t\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\t\t\t\tfor (auto token:tokens)\n\t\t\t\t\t\t\tmatrix_elements.push_back(std::stod(token));\n\t\t\t\t\t}\n\t\t\t\t\tEigen::MatrixXd st_opdm(bs.Nbasis,bs.Nbasis);\n\t\t\t\t\tif(symmetric_rdm)\n\t\t\t\t\t\tfill_LT<double>(matrix_elements,st_opdm);\n\t\t\t\t\telse\n\t\t\t\t\t\tfill_mat<double>(matrix_elements,st_opdm);\n\t\t\t\t\tto_opencap_ordering(st_opdm,bs,get_qchem_ids(bs));\n\t\t\t\t\tif(spin==0)\n\t\t\t\t\t{\n\t\t\t\t\t\talpha_opdms[i][i]=st_opdm;\n\t\t\t\t\t\tif(!do_spin)\n\t\t\t\t\t\t\tbeta_opdms[i][i]=st_opdm;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tbeta_opdms[i][i]=st_opdm;\n    \t\t\t}\n\t\t}\n        is.seekg (0, ios::beg);\n    \tfor(size_t i=0;i<ntdm;i++)\n    \t{\n\t\t\t//alpha first, then beta\n\t\t\tfor (size_t spin=0;spin<=do_spin;spin++)\n\t\t\t{\n\t\t\t\twhile(line.find(\"Transition DM\")== std::string::npos)\n\t\t\t\t{\n\t\t\t\t\tstd::getline(is,line);\n\t\t\t\t\tif (is.peek()==EOF)\n\t\t\t\t\t\topencap_throw(\"Error: Reached end of file before densities for \"+\n\t\t\t\t\t\t\t\tstd::to_string(nstates) + \" states were found.\");\n\t\t\t\t}\n\t\t\t\t//last part of line should be number of elements to read\n\t\t\t\tsize_t num_elements = stoi(split(line,' ').back());\n\t\t\t\tif(sqrt(num_elements)!=bs.Nbasis && num_elements!=lt_number)\n\t\t\t\t\topencap_throw(\"Error: dimensions of TDMs do not match specified basis set.\");\n\t\t\t\tsize_t lines_to_read = num_elements%5==0 ? (num_elements/5) : num_elements/5+1;\n\t\t\t\tstd::vector<double> matrix_elements;\n\t\t\t\tfor (size_t k=1;k<=lines_to_read;k++)\n\t\t\t\t{\n\t\t\t\t\tstd::getline(is,line);\n\t\t\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\t\t\tfor (auto token:tokens)\n\t\t\t\t\t\tmatrix_elements.push_back(std::stod(token));\n\t\t\t\t}\n\t\t\t\tEigen::MatrixXd st_opdm(bs.Nbasis,bs.Nbasis);\n\t\t\t\tfill_mat<double>(matrix_elements,st_opdm);\n\t\t\t\tto_opencap_ordering(st_opdm,bs,get_qchem_ids(bs));\n\t\t\t\tif(spin==0)\n\t\t\t\t{\n\t\t\t\t\talpha_tdms.push_back(st_opdm);\n\t\t\t\t\tif(!do_spin)\n\t\t\t\t\t\tbeta_tdms.push_back(st_opdm);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tbeta_tdms.push_back(st_opdm);\n\t\t\t}\n    \t}\n    }\n    is.close();\n    if(ntdm == lt_tdm)\n    {\n        std::cout << \"Warning: TDM M-->N is assumed to be conjugate transpose of \"\n        << \"TDM N-->M where M>N\" << std::endl;\n    \tsize_t dm_idx = 0;\n    \tfor(size_t i=0;i<nstates;i++)\n    \t{\n    \t\tfor(size_t j=i+1;j<nstates;j++)\n    \t\t{\n    \t\t\talpha_opdms[i][j] = alpha_tdms[dm_idx];\n    \t\t\talpha_opdms[j][i] = alpha_tdms[dm_idx].adjoint();\n    \t\t\tbeta_opdms[i][j] = beta_tdms[dm_idx].adjoint();\n    \t\t\tbeta_opdms[j][i] = beta_tdms[dm_idx];\n\t\t\t\tdm_idx++;\n    \t\t}\n    \t}\n    }\n    else\n    {\n    \tsize_t dm_idx = 0;\n    \tfor(size_t i=0;i<nstates;i++)\n    \t{\n    \t\tfor(size_t j=0;j<nstates;j++)\n    \t\t{\n    \t\t\tif(i!=j)\n    \t\t\t{\n    \t\t\t\talpha_opdms[i][j] = alpha_tdms[dm_idx];\n    \t\t\t\tbeta_opdms[i][j] = beta_tdms[dm_idx];\n    \t\t\t\tdm_idx++;\n    \t\t\t}\n    \t\t}\n    \t}\n    }\n}\n\nvoid qchem_read_dms(std::vector<std::vector<Eigen::MatrixXd>> &alpha_dms,\n\t\tstd::vector<std::vector<Eigen::MatrixXd>> &beta_dms,\n\t\tstd::string fchk_filename, BasisSet &bs,size_t num_states)\n{\n\tstd::ifstream is(fchk_filename);\n\tsize_t nstates = 0;\n\tsize_t num_tdm = 0;\n\tbool sep_alpha_beta;\n\tbool symmetric_rdm = false;\n\tbool symmetric_tdm = false;\n\tstd::string line, rest;\n\tif (is.good())\n\t{\n\t\twhile(is.peek() != EOF )\n\t\t{\n\t\t\tstd::getline(is, line);\n\t\t\tif(line.find(\"State Density\")!= std::string::npos)\n\t\t\t{\n\t\t\t\tif(line.find(\"Alpha\")!=std::string::npos)\n\t\t\t\t{\n\t\t\t\t\tsep_alpha_beta=true;\n\t\t\t\t\tint num_elements = stoi(split(line,' ').back());\n\t\t\t\t\tif(sqrt(num_elements)!=bs.Nbasis)\n\t\t\t\t\t{\n\t\t\t\t\t\tint lt_number = bs.Nbasis*(bs.Nbasis+1)/2;\n\t\t\t\t\t\tif(lt_number == num_elements)\n\t\t\t\t\t\t\tsymmetric_rdm = true;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\topencap_throw(\"Error: dimensions of DMs do not match specified basis set.\");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tsep_alpha_beta=false;\n\t\t\t\t\tint num_elements = stoi(split(line,' ').back());\n\t\t\t\t\tif(sqrt(num_elements)!=bs.Nbasis)\n\t\t\t\t\t{\n\t\t\t\t\t\tint lt_number = bs.Nbasis*(bs.Nbasis+1)/2;\n\t\t\t\t\t\tif (lt_number == num_elements)\n\t\t\t\t\t\t\tsymmetric_rdm = true;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\topencap_throw(\"Error: dimensions of DMs do not match specified basis set.\");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tis.seekg (0, ios::beg);\n\t\twhile(is.peek()!=EOF)\n\t\t{\n\t\t\tstd::getline(is, line);\n\t\t\tif((line.find(\"Alpha\")!= std::string::npos && line.find(\"State Density\")!= std::string::npos) && sep_alpha_beta)\n\t\t\t\tnstates++;\n\t\t\telse if(line.find(\"State Density\")!= std::string::npos && !sep_alpha_beta)\n\t\t\t\tnstates++;\n\t\t\tif((line.find(\"Alpha\")!= std::string::npos && line.find(\"Transition DM\")!= std::string::npos) && sep_alpha_beta)\n\t\t\t\tnum_tdm++;\n\t\t\telse if(line.find(\"Transition DM\")!= std::string::npos && !sep_alpha_beta)\n\t\t\t\tnum_tdm++;\n\t\t}\n\t\tis.close();\n\t\tif(nstates==0)\n\t\t{\n\t\t\topencap_throw(\"Error: Unable to find any densities in:\" +fchk_filename);\n\t\t}\n\t\telse if(nstates!=num_states)\n\t\t{\n\t\t\topencap_throw(\"Error: number of states found: \" + std::to_string(nstates) + \", does not match \"\n\t\t\t\t\t\"number of states specified in the input: \" + std::to_string(num_states)+ \". Exiting...\");\n\t\t}\n\t\tqchem_parse_fchk_dms(fchk_filename,alpha_dms,beta_dms,nstates,num_tdm,bs,symmetric_rdm,sep_alpha_beta);\n\t}\n\telse\n\t    opencap_throw(\"Error: I couldn't read:\" + fchk_filename);\n}\n\nEigen::MatrixXd qchem_read_overlap(std::string dmat_filename, BasisSet bs)\n{\n\tsize_t num_bf = bs.Nbasis;\n    std::ifstream is(dmat_filename);\n\tEigen::MatrixXd smat(num_bf,num_bf);\n\tsmat=Eigen::MatrixXd::Zero(num_bf,num_bf);\n    if (is.good())\n    {\n    \tstd::string line, rest;\n    \twhile (line.find(\"Overlap Matrix\")== std::string::npos)\n    \t{\n        \tstd::getline(is, line);\n    \t\tif (is.peek()==EOF)\n    \t\t\topencap_throw(\"Error: Reached end of file before Overlap Matrix was found.\");\n    \t}\n    \tsize_t num_elements = stoi(split(line,' ').back());\n    \tint lt_number = bs.Nbasis*(bs.Nbasis+1)/2;\n    \tif(num_elements!=lt_number)\n    \t\topencap_throw(\"Error: Dimensions of overlap matrix do not match basis.\");\n\t\tsize_t lines_to_read = num_elements%5==0 ? (num_elements/5) : num_elements/5+1;\n\t\tstd::vector<double> matrix_elements;\n\t\tfor (size_t k=1;k<=lines_to_read;k++)\n\t\t{\n\t\t\tstd::getline(is,line);\n\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\tfor (auto token:tokens)\n\t\t\t\tmatrix_elements.push_back(std::stod(token));\n\t\t}\n\t\tfill_LT<double>(matrix_elements,smat);\n\t\tto_opencap_ordering(smat,bs,get_qchem_ids(bs));\n    }\n    else\n    \topencap_throw(\"Error: I couldn't read:\" + dmat_filename);\n    return smat;\n}\n\n\nEigen::MatrixXd read_qchem_tddft_energies(size_t nstates,std::string output_file)\n{\n\tEigen::MatrixXd ZERO_ORDER_H(nstates,nstates);\n\tZERO_ORDER_H=Eigen::MatrixXd::Zero(nstates,nstates);\n\tstd::ifstream is(output_file);\n    if (is.good())\n    {\n    \tstd::string line, rest;\n    \tstd::getline(is, line);\n    \tsize_t state_idx = 1;\n    \twhile (state_idx<nstates)\n    \t{\n    \t\tif (is.peek()==EOF)\n    \t\t\topencap_throw(\"Error: Reached end of file before \"+ std::to_string(nstates) + \" energies were found. \"\n    \t\t\t\t\t\"Only \" + std::to_string(state_idx) + \" states were found. Exiting...\");\n    \t\tif (line.find(\"Total energy in the final basis set\")!= std::string::npos)\n    \t\t\tZERO_ORDER_H(0,0) = std::stod(split(line,' ')[8]);\n\t\t\tif (line.find(\"Total energy for state\")!= std::string::npos)\n\t\t\t{\n\t\t\t\t\tZERO_ORDER_H(state_idx,state_idx) = std::stod(split(line,' ')[5]);\n\t\t\t\t\tstate_idx++;\n\t\t\t\t\tstd::getline(is,line);\n\t\t\t}\n    \t\telse\n    \t\t\tstd::getline(is,line);\n    \t}\n    }\n    else\n    \topencap_throw(\"Error: I couldn't read:\" + output_file);\n    return ZERO_ORDER_H;\n}\n\nEigen::MatrixXd read_qchem_eom_energies(size_t nstates,std::string output_file)\n{\n\tEigen::MatrixXd ZERO_ORDER_H(nstates,nstates);\n\tZERO_ORDER_H=Eigen::MatrixXd::Zero(nstates,nstates);\n\tstd::ifstream is(output_file);\n    if (is.good())\n    {\n    \tstd::string line, rest;\n    \tstd::getline(is, line);\n    \tsize_t state_idx = 1;\n    \twhile (state_idx<=nstates)\n    \t{\n    \t\tif (is.peek()==EOF)\n    \t\t\topencap_throw(\"Error: Reached end of file before \"+ std::to_string(nstates) + \" energies were found. \"\n    \t\t\t\t\t\"Only \" + std::to_string(state_idx) + \" states were found. Exiting...\");\n\t\t\tif (line.find(\"Total energy\")!= std::string::npos && line.find(\"Excitation energy\")!= std::string::npos)\n\t\t\t{\n\t\t\t\t\tZERO_ORDER_H(state_idx-1,state_idx-1) = std::stod(split(line,' ')[3]);\n\t\t\t\t\tstate_idx++;\n\t\t\t\t\tstd::getline(is,line);\n\t\t\t}\n    \t\telse\n    \t\t\tstd::getline(is,line);\n    \t}\n    }\n    else\n    \topencap_throw(\"Error: I couldn't read:\" + output_file);\n    return ZERO_ORDER_H;\n}\n\nstd::vector<Atom> read_geometry_from_fchk(std::string fchk_filename)\n{\n\tstd::vector<Atom> atoms;\n\tstd::vector<size_t> atom_nums;\n\tstd::vector<double> coords;\n\tstd::ifstream is(fchk_filename);\n    if (is.good())\n    {\n    \tstd::string line, rest;\n    \tstd::getline(is, line);\n\t\twhile(line.find(\"Atomic numbers\")== std::string::npos)\n\t\t{\n\t\t\tstd::getline(is,line);\n    \t\tif (is.peek()==EOF)\n    \t\t\topencap_throw(\"Error: Reached end of file before atomic numbers were found.\");\n\t\t}\n\t\tsize_t num_elements = stoi(split(line,' ').back());\n\t\tsize_t lines_to_read = num_elements%6==0 ? (num_elements/6) : num_elements/6+1;\n\t\tfor (size_t k=1;k<=lines_to_read;k++)\n\t\t{\n\t\t\tstd::getline(is,line);\n\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\tfor (auto token:tokens)\n\t\t\t\tatom_nums.push_back(std::stoi(token));\n\t\t}\n\t\twhile(line.find(\"Current cartesian coordinates\")== std::string::npos)\n\t\t{\n\t\t\tstd::getline(is,line);\n    \t\tif (is.peek()==EOF)\n    \t\t\topencap_throw(\"Error: Reached end of file before Current Cartesian Coordinates were found.\");\n\t\t}\n\t\tnum_elements = stoi(split(line,' ').back());\n\t\tlines_to_read = num_elements%5==0 ? (num_elements/5) : num_elements/5+1;\n\t\tfor (size_t k=1;k<=lines_to_read;k++)\n\t\t{\n\t\t\tstd::getline(is,line);\n\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\tfor (auto token:tokens)\n\t\t\t\tcoords.push_back(std::stod(token));\n\t\t}\n\t\t//ok now lets populate our atoms\n\t\tfor(size_t i=0;i<atom_nums.size();i++)\n\t\t\tatoms.push_back(Atom(atom_nums[i],coords[i*3],coords[i*3+1],coords[i*3+2]));\n    }\n    else\n    \topencap_throw(\"Error: I couldn't read:\" + fchk_filename);\n    return atoms;\n}\n\nBasisSet read_basis_from_fchk(std::string fchk_filename, std::vector<Atom> atoms)\n{\n\tauto start = std::chrono::high_resolution_clock::now();\n\tstd::vector<int> shell_types;\n\tstd::vector<int> prims_per_shell;\n\tstd::vector<int> atom_ids;\n\tstd::vector<double> exps;\n\tstd::vector<double> coeffs;\n\t// needed for SP specification\n\tstd::vector<double> p_coeffs;\n\tbool SP_basis_function = true;\n\tBasisSet bs;\n\tfor(auto atm:atoms)\n\t\tbs.centers.push_back(atm.coords);\n\tstd::vector<shell_id> ids;\n\tstd::ifstream is(fchk_filename);\n    if (is.good())\n    {\n    \tstd::string line, rest;\n    \tstd::getline(is, line);\n    \t//First lets figure out if there are SP functions\n    \t//shell types\n\t\twhile(line.find(\"Shell types\")== std::string::npos)\n\t\t{\n\t\t\tstd::getline(is,line);\n    \t\tif (is.peek()==EOF)\n    \t\t\topencap_throw(\"Error: Reached end of file before shell types were found.\");\n\t\t}\n\t\tsize_t num_elements = stoi(split(line,' ').back());\n\t\tsize_t lines_to_read = num_elements%6==0 ? (num_elements/6) : num_elements/6+1;\n\t\tfor (size_t k=1;k<=lines_to_read;k++)\n\t\t{\n\t\t\tstd::getline(is,line);\n\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\tfor (auto token:tokens)\n\t\t\t{\n\t\t\t\tshell_types.push_back(std::stoi(token));\n\t\t\t}\n\t\t}\n\t\t//prims per shell\n\t\twhile(line.find(\"Number of primitives per shell\")== std::string::npos)\n\t\t{\n\t\t\tstd::getline(is,line);\n    \t\tif (is.peek()==EOF)\n    \t\t\topencap_throw(\"Error: Reached end of file before Number of primitives per shell were found.\");\n\t\t}\n\t\tnum_elements = stoi(split(line,' ').back());\n\t\tlines_to_read = num_elements%6==0 ? (num_elements/6) : num_elements/6+1;\n\t\tfor (size_t k=1;k<=lines_to_read;k++)\n\t\t{\n\t\t\tstd::getline(is,line);\n\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\tfor (auto token:tokens)\n\t\t\t\tprims_per_shell.push_back(std::stoi(token));\n\t\t}\n\t\t//atom ids\n\t\twhile(line.find(\"Shell to atom map\")== std::string::npos)\n\t\t{\n\t\t\tstd::getline(is,line);\n    \t\tif (is.peek()==EOF)\n    \t\t\topencap_throw(\"Error: Reached end of file before Shell to atom map was found.\");\n\t\t}\n\t\tnum_elements = stoi(split(line,' ').back());\n\t\tlines_to_read = num_elements%6==0 ? (num_elements/6) : num_elements/6+1;\n\t\tfor (size_t k=1;k<=lines_to_read;k++)\n\t\t{\n\t\t\tstd::getline(is,line);\n\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\tfor (auto token:tokens)\n\t\t\t\tatom_ids.push_back(std::stoi(token));\n\t\t}\n\t\t//prims\n\t\twhile(line.find(\"Primitive exponents\")== std::string::npos)\n\t\t{\n\t\t\tstd::getline(is,line);\n    \t\tif (is.peek()==EOF)\n    \t\t\topencap_throw(\"Error: Reached end of file before Primitive exponents were found.\");\n\t\t}\n\t\tnum_elements = stoi(split(line,' ').back());\n\t\tlines_to_read = num_elements%5==0 ? (num_elements/5) : num_elements/5+1;\n\t\tfor (size_t k=1;k<=lines_to_read;k++)\n\t\t{\n\t\t\tstd::getline(is,line);\n\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\tfor (auto token:tokens)\n\t\t\t\texps.push_back(std::stod(token));\n\t\t}\n\t\t//coeffs\n\t\twhile(line.find(\"Contraction coefficients\")== std::string::npos)\n\t\t{\n\t\t\tstd::getline(is,line);\n    \t\tif (is.peek()==EOF)\n    \t\t\topencap_throw(\"Error: Reached end of file before Contraction coefficients were found.\");\n\t\t}\n\t\tnum_elements = stoi(split(line,' ').back());\n\t\tlines_to_read = num_elements%5==0 ? (num_elements/5) : num_elements/5+1;\n\t\tfor (size_t k=1;k<=lines_to_read;k++)\n\t\t{\n\t\t\tstd::getline(is,line);\n\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\tfor (auto token:tokens)\n\t\t\t\tcoeffs.push_back(std::stod(token));\n\t\t}\n\t\twhile(line.find(\"P(S=P) Contraction coefficients\")== std::string::npos)\n\t\t{\n\t\t\tstd::getline(is,line);\n    \t\tif (is.peek()==EOF)\n    \t\t{\n    \t\t\tSP_basis_function = false;\n    \t\t\tbreak;\n    \t\t}\n\t\t}\n\t\tif (SP_basis_function)\n\t\t{\n\t\t\tnum_elements = stoi(split(line,' ').back());\n\t\t\tlines_to_read = num_elements%5==0 ? (num_elements/5) : num_elements/5+1;\n\t\t\tfor (size_t k=1;k<=lines_to_read;k++)\n\t\t\t{\n\t\t\t\tstd::getline(is,line);\n\t\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\t\tfor (auto token:tokens)\n\t\t\t\t\tp_coeffs.push_back(std::stod(token));\n\t\t\t}\n\t\t}\n    }\n    else\n    \topencap_throw(\"Error: I couldn't read:\" + fchk_filename);\n    size_t prim_idx=0;\n    for(size_t i=0;i<shell_types.size();i++)\n    {\n    \t//SP\n    \tif(shell_types[i]==-1)\n    \t{\n    \t\tif(p_coeffs.size()==0)\n    \t\t\topencap_throw(\"Error: missing section P(S=P) Contraction coefficients.\");\n    \t\tShell s_shell(0,atoms[atom_ids[i]-1].coords);\n    \t\tShell p_shell(1,atoms[atom_ids[i]-1].coords);\n\t\t\tint num_prims = prims_per_shell[i];\n\t\t\tfor(int j=1;j<=num_prims;j++)\n\t\t\t{\n\t\t\t\ts_shell.add_primitive(exps[prim_idx],coeffs[prim_idx]);\n\t\t\t\tp_shell.add_primitive(exps[prim_idx],p_coeffs[prim_idx]);\n\t\t\t\tprim_idx++;\n\t\t\t}\n\t\t\tbs.add_shell(s_shell);\n\t\t\tbs.add_shell(p_shell);\n    \t}\n    \telse\n    \t{\n\t\t\tShell new_shell(abs(shell_types[i]),atoms[atom_ids[i]-1].coords);\n\t\t\tif(shell_types[i]>0 && new_shell.l>1)\n\t\t\t\tnew_shell.pure=false;\n\t\t\tint num_prims = prims_per_shell[i];\n\t\t\tfor(int j=1;j<=num_prims;j++)\n\t\t\t{\n\t\t\t\tnew_shell.add_primitive(exps[prim_idx],coeffs[prim_idx]);\n\t\t\t\tprim_idx++;\n\t\t\t}\n\t\t\tbs.add_shell(new_shell);\n    \t}\n    }\n    bs.normalize();\n\tauto stop = std::chrono::high_resolution_clock::now();\n\tauto total_time = std::chrono::duration<double>(stop-start).count();\n    return bs;\n}\n", "meta": {"hexsha": "cb31b421ad231364122c0c582824c15e9c2c345b", "size": 18204, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "opencap/src/qchem_interface.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/qchem_interface.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/qchem_interface.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": 32.2194690265, "max_line_length": 115, "alphanum_fraction": 0.6454076027, "num_tokens": 5198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.27377548225867393}}
{"text": "/*\n\nCopyright (c) 2005-2016, 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 AVERAGEDSOURCEPDE_HPP_\n#define AVERAGEDSOURCEPDE_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n#include <boost/serialization/vector.hpp>\n\n#include \"AbstractCellPopulation.hpp\"\n#include \"TetrahedralMesh.hpp\"\n#include \"AbstractLinearEllipticPde.hpp\"\n\n/**\n *  An Elliptic PDE which calculates the source term by adding the number of cells\n *  in the element containing that point and scaling by the element area.\n */\ntemplate<unsigned DIM>\nclass AveragedSourcePde : public AbstractLinearEllipticPde<DIM,DIM>\n{\n    friend class TestCellBasedPdes;\n\nprivate:\n\n    /** Needed for serialization.*/\n    friend class boost::serialization::access;\n    /**\n     * Serialize the PDE and its member variables.\n     *\n     * @param archive the 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<AbstractLinearEllipticPde<DIM, DIM> >(*this);\n       archive & mCoefficient;\n       archive & mCellDensityOnCoarseElements;\n    }\n\nprotected:\n\n    /** The cell population member. */\n    AbstractCellPopulation<DIM>& mrCellPopulation;\n\n    /** Coefficient of consumption of nutrient by cells. */\n    double mCoefficient;\n\n    /** Vector of averaged cell densities on elements of the coarse mesh. */\n    std::vector<double> mCellDensityOnCoarseElements;\n\npublic:\n\n    /**\n     * Constructor.\n     *\n     * @param rCellPopulation reference to the cell population\n     * @param coefficient the coefficient of consumption of nutrient by cells (defaults to 0.0)\n     */\n    AveragedSourcePde(AbstractCellPopulation<DIM>& rCellPopulation, double coefficient=0.0);\n\n    /**\n     * @return const reference to the cell population (used in archiving).\n     */\n    const AbstractCellPopulation<DIM>& rGetCellPopulation() const;\n\n    /**\n     * @return mCoefficient\n     */\n    double GetCoefficient() const;\n\n    /**\n     * Set up the source terms.\n     *\n     * @param rCoarseMesh reference to the coarse mesh\n     * @param pCellPdeElementMap optional pointer to the map from cells to coarse elements\n     */\n    void virtual SetupSourceTerms(TetrahedralMesh<DIM,DIM>& rCoarseMesh, std::map<CellPtr, unsigned>* pCellPdeElementMap=NULL);\n\n    /**\n     * Overridden ComputeConstantInUSourceTerm() method.\n     *\n     * @param rX The point in space\n     * @param pElement the element\n     *\n     * @return the constant in u part of the source term, i.e g(x) in\n     *  Div(D Grad u)  +  f(x)u + g(x) = 0.\n     */\n    double ComputeConstantInUSourceTerm(const ChastePoint<DIM>& rX, Element<DIM,DIM>* pElement);\n\n    /**\n     * Overridden ComputeLinearInUCoeffInSourceTerm() method.\n     *\n     * @param rX The point in space\n     * @param pElement the element\n     *\n     * @return the coefficient of u in the linear part of the source term, i.e f(x) in\n     *  Div(D Grad u)  +  f(x)u + g(x) = 0.\n     */\n    double ComputeLinearInUCoeffInSourceTerm(const ChastePoint<DIM>& rX, Element<DIM,DIM>* pElement);\n\n    /**\n     * Overridden ComputeDiffusionTerm() method.\n     *\n     * @param rX The point in space at which the diffusion term is computed\n     *\n     * @return a matrix.\n     */\n    c_matrix<double,DIM,DIM> ComputeDiffusionTerm(const ChastePoint<DIM>& rX);\n\n    /**\n     * @return the uptake rate.\n     *\n     * @param elementIndex the element we wish to return the uptake rate for\n     */\n    double GetUptakeRateForElement(unsigned elementIndex);\n};\n\n#include \"SerializationExportWrapper.hpp\"\nEXPORT_TEMPLATE_CLASS_SAME_DIMS(AveragedSourcePde)\n\nnamespace boost\n{\nnamespace serialization\n{\n/**\n * Serialize information required to construct an AveragedSourcePde.\n */\ntemplate<class Archive, unsigned DIM>\ninline void save_construct_data(\n    Archive & ar, const AveragedSourcePde<DIM>* t, const unsigned int file_version)\n{\n    // Save data required to construct instance\n    const AbstractCellPopulation<DIM>* p_cell_population = &(t->rGetCellPopulation());\n    ar & p_cell_population;\n}\n\n/**\n * De-serialize constructor parameters and initialise an AveragedSourcePde.\n */\ntemplate<class Archive, unsigned DIM>\ninline void load_construct_data(\n    Archive & ar, AveragedSourcePde<DIM>* t, const unsigned int file_version)\n{\n    // Retrieve data from archive required to construct new instance\n    AbstractCellPopulation<DIM>* p_cell_population;\n    ar >> p_cell_population;\n\n    // Invoke inplace constructor to initialise instance\n    ::new(t)AveragedSourcePde<DIM>(*p_cell_population);\n}\n}\n} // namespace ...\n\n#endif /*AVERAGEDSOURCEPDE_HPP_*/\n", "meta": {"hexsha": "4fee52fc8ce4855b80a25900683072f9a71ab0bf", "size": 6365, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cell_based/src/population/pdes/AveragedSourcePde.hpp", "max_stars_repo_name": "uofs-simlab/ChasteOS", "max_stars_repo_head_hexsha": "04d98998e2ebad3f29086b8eaa1d89c08c6fccf6", "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": "cell_based/src/population/pdes/AveragedSourcePde.hpp", "max_issues_repo_name": "uofs-simlab/ChasteOS", "max_issues_repo_head_hexsha": "04d98998e2ebad3f29086b8eaa1d89c08c6fccf6", "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": "cell_based/src/population/pdes/AveragedSourcePde.hpp", "max_forks_repo_name": "uofs-simlab/ChasteOS", "max_forks_repo_head_hexsha": "04d98998e2ebad3f29086b8eaa1d89c08c6fccf6", "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.6772486772, "max_line_length": 127, "alphanum_fraction": 0.7294579733, "num_tokens": 1465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.27370207411262276}}
{"text": "/*\n * ext.cc\n *\n *  Copyright (C) 2018 Diamond Light Source\n *\n *  Author: James Parkhurst\n *\n *  This code is distributed under the BSD license, a copy of which is\n *  included in the root directory of this package.\n */\n#include <boost/python.hpp>\n#include <boost/python/def.hpp>\n#include <boost/math/distributions/chi_squared.hpp>\n#include <scitbx/constants.h>\n#include <scitbx/vec2.h>\n#include <scitbx/vec3.h>\n#include <scitbx/mat2.h>\n#include <scitbx/mat3.h>\n#include <scitbx/sym_mat2.h>\n#include <scitbx/math/r3_rotation.h>\n#include <scitbx/matrix/multiply.h>\n#include <scitbx/matrix/eigensystem.h>\n#include <dxtbx/model/experiment.h>\n#include <dials/model/data/shoebox.h>\n#include <dials/algorithms/profile_model/gaussian_rs/coordinate_system.h>\n#include <dials/algorithms/shoebox/mask_code.h>\n#include <dials/array_family/reflection_table.h>\n#include <dials/error.h>\n\nusing namespace boost::python;\n\nnamespace dials { namespace algorithms { namespace boost_python {\n\n  using dials::algorithms::profile_model::gaussian_rs::CoordinateSystem2d;\n  using dials::model::Background;\n  using dials::model::Foreground;\n  using dials::model::Overlapped;\n  using dials::model::Shoebox;\n  using dials::model::Valid;\n  using dxtbx::model::BeamBase;\n  using dxtbx::model::Detector;\n  using dxtbx::model::Experiment;\n  using dxtbx::model::Panel;\n  using scitbx::mat2;\n  using scitbx::mat3;\n  using scitbx::sym_mat2;\n  using scitbx::vec2;\n  using scitbx::vec3;\n  using scitbx::af::int6;\n  using scitbx::matrix::multiply_transpose;\n  using scitbx::matrix::transpose_multiply;\n\n  namespace detail {\n\n    /**\n     * Helper function to do matrix multiplication\n     */\n    double AT_B_A(vec2<double> A, mat2<double> B) {\n      vec2<double> ATB = A * B;\n      return ATB * A;\n    }\n\n    /**\n     * Helper function to do matrix multiplication\n     */\n    double AT_B_A(vec3<double> A, mat3<double> B) {\n      vec3<double> ATB = A * B;\n      return ATB * A;\n    }\n\n  }  // namespace detail\n\n  /**\n   * Function to given chisq quantile value\n   * @param k The degrees of freedom\n   * @param p The probability\n   */\n  double chisq_pdf(int k, double x) {\n    DIALS_ASSERT(k > 0);\n    DIALS_ASSERT(x >= 0);\n    boost::math::chi_squared_distribution<> dist(k);\n    return boost::math::pdf(dist, x);\n  }\n\n  /**\n   * Function to given chisq quantile value\n   * @param k The degrees of freedom\n   * @param p The probability\n   */\n  double chisq_quantile(int k, double p) {\n    DIALS_ASSERT(k > 0);\n    DIALS_ASSERT(p >= 0 && p <= 1);\n    boost::math::chi_squared_distribution<> dist(k);\n    return boost::math::quantile(dist, p);\n  }\n\n  /**\n   * Perform the change of basis from lab coordinates to the kabsch coordinate\n   * system\n   * @param s0 The incident beam vector\n   * @param s2 The diffracted beam vector\n   * @return The change of basis matrix\n   */\n  mat3<double> compute_change_of_basis_operation(vec3<double> s0, vec3<double> s2) {\n    const double TINY = 1e-7;\n    DIALS_ASSERT((s2 - s0).length() > TINY);\n    vec3<double> e1 = s2.cross(s0).normalize();\n    vec3<double> e2 = s2.cross(e1).normalize();\n    vec3<double> e3 = s2.normalize();\n    mat3<double> R(e1[0], e1[1], e1[2], e2[0], e2[1], e2[2], e3[0], e3[1], e3[2]);\n    return R;\n  }\n\n  /**\n   * Perform the change of basis from reciprocal space to a coordinate system of\n   * orientated with the reciprocal lattice vector to the reflection\n   * @param s0 The incident beam vector\n   * @param r The reciprocal lattice vector\n   * @return The change of basis matrix\n   */\n  mat3<double> compute_change_of_basis_operation2(vec3<double> s0, vec3<double> r) {\n    vec3<double> e1 = r.cross(s0).normalize();\n    vec3<double> e2 = r.cross(e1).normalize();\n    vec3<double> e3 = r.normalize();\n    mat3<double> R(e1[0], e1[1], e1[2], e2[0], e2[1], e2[2], e3[0], e3[1], e3[2]);\n    return R;\n  }\n\n  /**\n   * A class to predict the reflections\n   */\n  class PredictorBase {\n  public:\n    /**\n     * Initialise the predictor\n     * @param experiment The experiment\n     * @param probability The probability\n     */\n    PredictorBase(Experiment experiment, double probability)\n        : experiment_(experiment), probability_(probability) {\n      DIALS_ASSERT(probability > 0 && probability < 1);\n    }\n\n    /**\n     * Predict the reflections\n     * @param h The list of miller indices\n     * @returns The reflection table\n     */\n    af::reflection_table predict(af::const_ref<cctbx::miller::index<> > h) const {\n      // Get the beam and detector\n      const double TINY = 1e-7;\n      DIALS_ASSERT(experiment_.get_beam() != NULL);\n      DIALS_ASSERT(experiment_.get_crystal() != NULL);\n      DIALS_ASSERT(experiment_.get_detector() != NULL);\n      Detector detector = *experiment_.get_detector();\n\n      // Compute quantile\n      double quantile = chisq_quantile(3, probability_);\n\n      // Get stuff from experiment\n      mat3<double> A = experiment_.get_crystal()->get_A();\n      vec3<double> s0 = experiment_.get_beam()->get_s0();\n      Panel panel = detector[0];\n\n      // Initialise some arrays\n      af::shared<cctbx::miller::index<> > miller_indices;\n      af::shared<bool> entering;\n      af::shared<vec3<double> > s1_list;\n      af::shared<vec3<double> > s2_list;\n      af::shared<vec3<double> > xyzcalpx;\n      af::shared<vec3<double> > xyzcalmm;\n      af::shared<std::size_t> panel_list;\n      af::shared<int> experiment_id;\n\n      // Loop through the input miller indices\n      for (std::size_t i = 0; i < h.size(); ++i) {\n        // Compute the point and the distance from the Ewald sphere\n        vec3<double> r = A * h[i];\n        vec3<double> s2 = s0 + r;\n        vec3<double> s3 = s2.normalize() * s0.length();\n\n        // Invert the matrix\n        mat3<double> sigma = get_sigma(s0, r);\n        mat3<double> sigma_inv = sigma.inverse();\n\n        // Compute distance\n        double d = detail::AT_B_A(s3 - s2, sigma_inv);\n\n        // If it is close enough then predict stuff\n        if (d < quantile) {\n          // Compute the rotation of the reflection\n          mat3<double> R = compute_change_of_basis_operation(s0, s2);\n\n          // Rotate the covariance matrix and s2 vector\n          mat3<double> S = R * sigma * R.transpose();\n          vec3<double> mu = R * s2;\n          vec3<double> zaxis(0, 0, 1);\n          DIALS_ASSERT(std::abs((mu.normalize() * zaxis) - 1) < TINY);\n\n          // Partition the covariance matrix\n          mat2<double> S11(S[0], S[1], S[3], S[4]);\n          vec2<double> S12(S[2], S[5]);\n          vec2<double> S21(S[6], S[7]);\n          double S22 = S[8];\n\n          // Partition the mean vector\n          vec2<double> mu1(mu[0], mu[1]);\n          double mu2 = mu[2];\n\n          // Compute epsilon the distance to the Ewald sphere\n          double epsilon = s0.length() - mu2;\n\n          // Compute the mean of the conditional distribution\n          DIALS_ASSERT(S22 > 0);\n          double S22_inv = 1.0 / S22;\n          vec2<double> mubar = mu1 + S12 * S22_inv * epsilon;\n\n          // Compute the diffracted beam vector\n          vec3<double> v(mubar[0], mubar[1], s0.length());\n          vec3<double> s1 = R.transpose() * (v.normalize() * s0.length());\n\n          try {\n            // Do the panel ray intersection\n            vec2<double> xymm = panel.get_ray_intersection(s1);\n            vec2<double> xypx = panel.millimeter_to_pixel(xymm);\n\n            // Append the stuff to arrays\n            experiment_id.push_back(0);\n            miller_indices.push_back(h[i]);\n            entering.push_back(false);\n            panel_list.push_back(0);\n            s1_list.push_back(s1);\n            s2_list.push_back(s2);\n            xyzcalpx.push_back(vec3<double>(xypx[0], xypx[1], 0));\n            xyzcalmm.push_back(vec3<double>(xymm[0], xymm[1], 0));\n          } catch (dxtbx::error) {\n            continue;\n          }\n        }\n      }\n\n      // Construct the reflection table\n      af::reflection_table reflections(miller_indices.size());\n      reflections[\"miller_index\"] = miller_indices;\n      reflections[\"entering\"] = entering;\n      reflections[\"s1\"] = s1_list;\n      reflections[\"s2\"] = s2_list;\n      reflections[\"xyzcal.px\"] = xyzcalpx;\n      reflections[\"xyzcal.mm\"] = xyzcalmm;\n      reflections[\"panel\"] = panel_list;\n      reflections[\"id\"] = experiment_id;\n      return reflections;\n    }\n\n  protected:\n    /**\n     * Get the sigma for a reflection\n     */\n    virtual mat3<double> get_sigma(vec3<double> s0, vec3<double> r) const {\n      throw DIALS_ERROR(\"Overload!\");\n    }\n\n    Experiment experiment_;\n    double probability_;\n  };\n\n  /**\n   * The predictor for simple profile models\n   */\n  class PredictorSimple : public PredictorBase {\n  public:\n    /**\n     * Initialise the class\n     * @param experiment The experiment\n     * @param sigma The covariance matrix\n     */\n    PredictorSimple(Experiment experiment, mat3<double> sigma, double probability)\n        : PredictorBase(experiment, probability), sigma_(sigma) {}\n\n  protected:\n    /**\n     * Get the sigma for a reflection\n     */\n    virtual mat3<double> get_sigma(vec3<double> s0, vec3<double> r) const {\n      return sigma_;\n    }\n\n    mat3<double> sigma_;\n  };\n\n  /**\n   * The predictor for angular profile models\n   */\n  class PredictorAngular : public PredictorBase {\n  public:\n    /**\n     * Initialise the class\n     * @param experiment The experiment\n     * @param sigma The covariance matrix\n     */\n    PredictorAngular(Experiment experiment, mat3<double> sigma, double probability)\n        : PredictorBase(experiment, probability), sigma_(sigma) {}\n\n  protected:\n    /**\n     * Get the sigma for a reflection\n     */\n    virtual mat3<double> get_sigma(vec3<double> s0, vec3<double> r) const {\n      const double TINY = 1e-7;\n      mat3<double> Q = compute_change_of_basis_operation2(s0, r);\n      vec3<double> zaxis(0, 0, 1);\n      DIALS_ASSERT(std::abs(((Q * r.normalize()) * zaxis) - 1) < TINY);\n      return (Q.transpose() * sigma_ * Q);\n    }\n\n    mat3<double> sigma_;\n  };\n\n  /**\n   * A class to compute the bounding box\n   */\n  class BBoxCalculatorBase {\n  public:\n    /**\n     * Initialise the class\n     * @param experiment The experiment\n     * @param sigma The covariance matrix\n     */\n    BBoxCalculatorBase(Experiment experiment, double probability, int border)\n        : experiment_(experiment), probability_(probability), border_(border) {\n      DIALS_ASSERT(border > 0);\n      DIALS_ASSERT(probability < 1.0);\n      DIALS_ASSERT(probability > 0);\n    }\n\n    /**\n     * Compute the bounding box\n     * @param reflections The reflection table\n     */\n    void compute(af::reflection_table reflections) const {\n      // Get some array from the reflection table\n      af::const_ref<vec3<double> > s1 = reflections[\"s1\"];\n      af::const_ref<vec3<double> > s2 = reflections[\"s2\"];\n      af::const_ref<std::size_t> panel = reflections[\"panel\"];\n      af::ref<int6> bbox = reflections[\"bbox\"];\n\n      // Compute quantile\n      double D = chisq_quantile(2, probability_);\n\n      // Compute mask for all reflections\n      for (std::size_t i = 0; i < reflections.size(); ++i) {\n        bbox[i] = compute_single(s1[i], s2[i], panel[i], D);\n      }\n    }\n\n  protected:\n    /**\n     * Get the sigma for a reflection\n     */\n    virtual mat3<double> get_sigma(vec3<double> s0, vec3<double> r) const {\n      throw DIALS_ERROR(\"Overload!\");\n    }\n\n    /**\n     * Compute the bounding box for a single reflection\n     * @param s1 The diffracted beam vector touching the Ewald sphere\n     * @param s2 The diffracted beam vector to the centre of the rlp\n     * @param panel_id The panel id\n     * @param D the distance\n     */\n    int6 compute_single(vec3<double> s1,\n                        vec3<double> s2,\n                        std::size_t panel_id,\n                        double D) const {\n      const double TINY = 1e-7;\n      DIALS_ASSERT(s1.length() > 0);\n      DIALS_ASSERT(s2.length() > 0);\n      DIALS_ASSERT(D > 0);\n\n      // Get the beam and detector\n      DIALS_ASSERT(experiment_.get_beam() != NULL);\n      DIALS_ASSERT(experiment_.get_detector() != NULL);\n      Detector detector = *experiment_.get_detector();\n\n      // The the indicident beam vector\n      vec3<double> s0 = experiment_.get_beam()->get_s0();\n      double s0_length = s0.length();\n      DIALS_ASSERT(std::abs(s0_length - s1.length()) < TINY);\n\n      vec3<double> r = s2 - s0;\n\n      // Compute the change of basis for the reflection\n      mat3<double> R = compute_change_of_basis_operation(s0, s2);\n\n      // Rotate the covariance matrix and s2 vector\n      mat3<double> S = R * get_sigma(s0, r) * R.transpose();\n      vec3<double> mu = R * s2;\n      vec3<double> zaxis(0, 0, 1);\n      DIALS_ASSERT(std::abs((mu.normalize() * zaxis) - 1) < TINY);\n\n      // Partition the covariance matrix\n      mat2<double> S11(S[0], S[1], S[3], S[4]);\n      vec2<double> S12(S[2], S[5]);\n      vec2<double> S21(S[6], S[7]);\n      double S22 = S[8];\n\n      // Partition the mean vector\n      vec2<double> mu1(mu[0], mu[1]);\n      double mu2 = mu[2];\n\n      // Compute epsilon the distance to the Ewald sphere\n      double epsilon = s0.length() - mu2;\n\n      // Compute the mean of the conditional distribution\n      DIALS_ASSERT(S22 > 0);\n      double S22_inv = 1.0 / S22;\n      vec2<double> mubar = mu1 + S12 * S22_inv * epsilon;\n\n      // Compute the covariance of the conditional distribution\n      mat2<double> S12_S21;\n      multiply_transpose(&S12[0], &S21[0], 2, 1, 2, &S12_S21[0]);\n      mat2<double> Sbar = S11 - S12_S21 * S22_inv;\n\n      // Get the panel model\n      Panel panel = detector[panel_id];\n\n      // Compute the the min/max bounding box on the ellipse\n      double A1 = Sbar[0];\n      double A2 = Sbar[3];\n      DIALS_ASSERT(A1 >= 0 && A2 >= 0);\n      double delta1 = std::sqrt(D * A1);\n      double delta2 = std::sqrt(D * A2);\n\n      // The corner points in conditional space\n      vec2<double> p1 = mubar + vec2<double>(-delta1, -delta2);\n      vec2<double> p2 = mubar + vec2<double>(-delta1, +delta2);\n      vec2<double> p3 = mubar + vec2<double>(+delta1, -delta2);\n      vec2<double> p4 = mubar + vec2<double>(+delta1, +delta2);\n\n      // The corner points in lab space\n      vec3<double> sp1 = R.transpose() * vec3<double>(p1[0], p1[1], s0.length());\n      vec3<double> sp2 = R.transpose() * vec3<double>(p2[0], p2[1], s0.length());\n      vec3<double> sp3 = R.transpose() * vec3<double>(p3[0], p3[1], s0.length());\n      vec3<double> sp4 = R.transpose() * vec3<double>(p4[0], p4[1], s0.length());\n\n      // The xy coordinates on the detector\n      vec2<double> xy1 = panel.get_ray_intersection_px(sp1);\n      vec2<double> xy2 = panel.get_ray_intersection_px(sp2);\n      vec2<double> xy3 = panel.get_ray_intersection_px(sp3);\n      vec2<double> xy4 = panel.get_ray_intersection_px(sp4);\n\n      // Get the min and max x and y coords\n      double xmin = std::min(std::min(xy1[0], xy2[0]), std::min(xy3[0], xy4[0]));\n      double ymin = std::min(std::min(xy1[1], xy2[1]), std::min(xy3[1], xy4[1]));\n      double xmax = std::max(std::max(xy1[0], xy2[0]), std::max(xy3[0], xy4[0]));\n      double ymax = std::max(std::max(xy1[1], xy2[1]), std::max(xy3[1], xy4[1]));\n\n      // Create bounding box\n      int x0 = ((int)std::floor(xmin)) - border_;\n      int y0 = ((int)std::floor(ymin)) - border_;\n      int x1 = ((int)std::ceil(xmax)) + border_;\n      int y1 = ((int)std::ceil(ymax)) + border_;\n      DIALS_ASSERT(x1 > x0);\n      DIALS_ASSERT(y1 > y0);\n      return int6(x0, x1, y0, y1, 0, 1);\n    }\n\n    Experiment experiment_;\n    double probability_;\n    int border_;\n  };\n\n  /**\n   * The bbox calculator for simple profile models\n   */\n  class BBoxCalculatorSimple : public BBoxCalculatorBase {\n  public:\n    /**\n     * Initialise the class\n     * @param experiment The experiment\n     * @param sigma The covariance matrix\n     */\n    BBoxCalculatorSimple(Experiment experiment,\n                         mat3<double> sigma,\n                         double probability,\n                         int border)\n        : BBoxCalculatorBase(experiment, probability, border), sigma_(sigma) {}\n\n  protected:\n    /**\n     * Get the sigma for a reflection\n     */\n    virtual mat3<double> get_sigma(vec3<double> s0, vec3<double> r) const {\n      return sigma_;\n    }\n\n    mat3<double> sigma_;\n  };\n\n  /**\n   * The bbox calculator for angular profile models\n   */\n  class BBoxCalculatorAngular : public BBoxCalculatorBase {\n  public:\n    /**\n     * Initialise the class\n     * @param experiment The experiment\n     * @param sigma The covariance matrix\n     */\n    BBoxCalculatorAngular(Experiment experiment,\n                          mat3<double> sigma,\n                          double probability,\n                          int border)\n        : BBoxCalculatorBase(experiment, probability, border), sigma_(sigma) {}\n\n  protected:\n    /**\n     * Get the sigma for a reflection\n     */\n    virtual mat3<double> get_sigma(vec3<double> s0, vec3<double> r) const {\n      const double TINY = 1e-7;\n      mat3<double> Q = compute_change_of_basis_operation2(s0, r);\n      vec3<double> zaxis(0, 0, 1);\n      DIALS_ASSERT(std::abs(((Q * r.normalize()) * zaxis) - 1) < TINY);\n      return (Q.transpose() * sigma_ * Q);\n    }\n\n    mat3<double> sigma_;\n  };\n\n  /**\n   * A class to compute the reflection mask\n   */\n  class MaskCalculatorBase {\n  public:\n    /**\n     * Initialise the class\n     * @param experiment The experiment\n     * @param sigma The covariance matrix\n     */\n    MaskCalculatorBase(Experiment experiment, double probability)\n        : experiment_(experiment), probability_(probability) {\n      DIALS_ASSERT(probability < 1.0);\n      DIALS_ASSERT(probability > 0);\n    }\n\n    /**\n     * Compute the reflection mask\n     * @param reflections The reflection table\n     */\n    void compute(af::reflection_table reflections) const {\n      // Get some array from the reflection table\n      af::const_ref<vec3<double> > s1 = reflections[\"s1\"];\n      af::const_ref<vec3<double> > s2 = reflections[\"s2\"];\n      af::ref<Shoebox<> > sbox = reflections[\"shoebox\"];\n\n      // Compute quantile\n      double D = chisq_quantile(2, probability_);\n\n      // Compute mask for all reflections\n      for (std::size_t i = 0; i < reflections.size(); ++i) {\n        compute_single(s1[i], s2[i], sbox[i], D);\n      }\n    }\n\n  protected:\n    /**\n     * Get the sigma for a reflection\n     */\n    virtual mat3<double> get_sigma(vec3<double> s0, vec3<double> r) const {\n      throw DIALS_ERROR(\"Overload!\");\n    }\n\n    /**\n     * Compute the bounding box for a single reflection\n     * @param s1 The diffracted beam vector touching the Ewald sphere\n     * @param s2 The diffracted beam vector to the centre of the rlp\n     * @param sbox The shoebox\n     * @param D the distance\n     */\n    void compute_single(vec3<double> s1,\n                        vec3<double> s2,\n                        Shoebox<> sbox,\n                        double D) const {\n      const double TINY = 1e-7;\n      DIALS_ASSERT(s1.length() > 0);\n      DIALS_ASSERT(s2.length() > 0);\n      DIALS_ASSERT(sbox.is_consistent());\n      DIALS_ASSERT(D > 0);\n\n      // Get the beam and detector\n      DIALS_ASSERT(experiment_.get_beam() != NULL);\n      DIALS_ASSERT(experiment_.get_detector() != NULL);\n      Detector detector = *experiment_.get_detector();\n\n      // The the indicident beam vector\n      vec3<double> s0 = experiment_.get_beam()->get_s0();\n      double s0_length = s0.length();\n      DIALS_ASSERT(std::abs(s0_length - s1.length()) < TINY);\n\n      vec3<double> r = s2 - s0;\n\n      // Compute the change of basis for the reflection\n      mat3<double> R = compute_change_of_basis_operation(s0, s2);\n\n      // Rotate the covariance matrix and s2 vector\n      mat3<double> S = R * get_sigma(s0, r) * R.transpose();\n      vec3<double> mu = R * s2;\n      vec3<double> zaxis(0, 0, 1);\n      DIALS_ASSERT(std::abs((mu.normalize() * zaxis) - 1) < TINY);\n\n      // Partition the covariance matrix\n      mat2<double> S11(S[0], S[1], S[3], S[4]);\n      vec2<double> S12(S[2], S[5]);\n      vec2<double> S21(S[6], S[7]);\n      double S22 = S[8];\n\n      // Partition the mean vector\n      vec2<double> mu1(mu[0], mu[1]);\n      double mu2 = mu[2];\n\n      // Compute epsilon the distance to the Ewald sphere\n      double epsilon = s0.length() - mu2;\n\n      // Compute the mean of the conditional distribution\n      DIALS_ASSERT(S22 > 0);\n      double S22_inv = 1.0 / S22;\n      vec2<double> mubar = mu1 + S12 * S22_inv * epsilon;\n\n      // Compute the covariance of the conditional distribution\n      mat2<double> S12_S21;\n      multiply_transpose(&S12[0], &S21[0], 2, 1, 2, &S12_S21[0]);\n      mat2<double> Sbar = S11 - S12_S21 * S22_inv;\n      mat2<double> Sbar_inv = Sbar.inverse();\n\n      // Get the mask array\n      af::ref<int, af::c_grid<3> > mask = sbox.mask.ref();\n\n      // Get the bounding box\n      int x0 = sbox.bbox[0];\n      int x1 = sbox.bbox[1];\n      int y0 = sbox.bbox[2];\n      int y1 = sbox.bbox[3];\n      int z0 = sbox.bbox[4];\n      int z1 = sbox.bbox[5];\n      DIALS_ASSERT(x0 < x1);\n      DIALS_ASSERT(y0 < y1);\n      DIALS_ASSERT(z0 < z1);\n      DIALS_ASSERT(z1 - z0 == 1);\n\n      // Create the coordinate system\n      CoordinateSystem2d cs(s0, s2);\n\n      // Get the panel model\n      Panel panel = detector[sbox.panel];\n\n      // Set the mask value for each pixel\n      DIALS_ASSERT(mask.accessor()[0] == 1);\n      for (std::size_t j = 0; j < mask.accessor()[1]; ++j) {\n        for (std::size_t i = 0; i < mask.accessor()[2]; ++i) {\n          int ii = x0 + ((int)i);\n          int jj = y0 + ((int)j);\n\n          // The pixel coordinates of the corners\n          vec2<double> p1(ii, jj);\n          vec2<double> p2(ii + 1, jj);\n          vec2<double> p3(ii, jj + 1);\n          vec2<double> p4(ii + 1, jj + 1);\n\n          // The lab coordinates of the pixel corners\n          vec3<double> sp1 = panel.get_pixel_lab_coord(p1).normalize() * s0_length;\n          vec3<double> sp2 = panel.get_pixel_lab_coord(p2).normalize() * s0_length;\n          vec3<double> sp3 = panel.get_pixel_lab_coord(p3).normalize() * s0_length;\n          vec3<double> sp4 = panel.get_pixel_lab_coord(p4).normalize() * s0_length;\n\n          // The coordinates in kabsch space\n          vec2<double> x1 = cs.from_beam_vector(sp1);\n          vec2<double> x2 = cs.from_beam_vector(sp2);\n          vec2<double> x3 = cs.from_beam_vector(sp3);\n          vec2<double> x4 = cs.from_beam_vector(sp4);\n\n          // The distance from the mean\n          double d1 = detail::AT_B_A(x1 - mubar, Sbar_inv);\n          double d2 = detail::AT_B_A(x2 - mubar, Sbar_inv);\n          double d3 = detail::AT_B_A(x3 - mubar, Sbar_inv);\n          double d4 = detail::AT_B_A(x4 - mubar, Sbar_inv);\n\n          // The minimum distance\n          if (std::min(std::min(d1, d2), std::min(d3, d4)) < D) {\n            mask(0, j, i) |= Foreground;\n          } else {\n            mask(0, j, i) |= Background;\n          }\n        }\n      }\n    }\n\n    Experiment experiment_;\n    double probability_;\n  };\n\n  /**\n   * The mask calculator for simple profile models\n   */\n  class MaskCalculatorSimple : public MaskCalculatorBase {\n  public:\n    /**\n     * Initialise the class\n     * @param experiment The experiment\n     * @param sigma The covariance matrix\n     */\n    MaskCalculatorSimple(Experiment experiment, mat3<double> sigma, double probability)\n        : MaskCalculatorBase(experiment, probability), sigma_(sigma) {}\n\n  protected:\n    /**\n     * Get the sigma for a reflection\n     */\n    virtual mat3<double> get_sigma(vec3<double> s0, vec3<double> r) const {\n      return sigma_;\n    }\n\n    mat3<double> sigma_;\n  };\n\n  /**\n   * The mask calculator for angular profile models\n   */\n  class MaskCalculatorAngular : public MaskCalculatorBase {\n  public:\n    /**\n     * Initialise the class\n     * @param experiment The experiment\n     * @param sigma The covariance matrix\n     */\n    MaskCalculatorAngular(Experiment experiment, mat3<double> sigma, double probability)\n        : MaskCalculatorBase(experiment, probability), sigma_(sigma) {}\n\n  protected:\n    /**\n     * Get the sigma for a reflection\n     */\n    virtual mat3<double> get_sigma(vec3<double> s0, vec3<double> r) const {\n      const double TINY = 1e-7;\n      mat3<double> Q = compute_change_of_basis_operation2(s0, r);\n      vec3<double> zaxis(0, 0, 1);\n      DIALS_ASSERT(std::abs(((Q * r.normalize()) * zaxis) - 1) < TINY);\n      return (Q.transpose() * sigma_ * Q);\n    }\n\n    mat3<double> sigma_;\n  };\n\n  BOOST_PYTHON_MODULE(dials_algorithms_profile_model_ellipsoid_ext) {\n    def(\"chisq_quantile\", &chisq_quantile);\n    def(\"chisq_pdf\", &chisq_pdf);\n\n    class_<PredictorBase>(\"PredictorBase\", no_init)\n      .def(\"predict\", &PredictorBase::predict);\n\n    class_<PredictorSimple, bases<PredictorBase> >(\"PredictorSimple\", no_init)\n      .def(init<Experiment, mat3<double>, double>());\n\n    class_<PredictorAngular, bases<PredictorBase> >(\"PredictorAngular\", no_init)\n      .def(init<Experiment, mat3<double>, double>());\n\n    class_<BBoxCalculatorBase>(\"BBoxCalculatorBase\", no_init)\n      .def(\"compute\", &BBoxCalculatorBase::compute);\n\n    class_<BBoxCalculatorSimple, bases<BBoxCalculatorBase> >(\"BBoxCalculatorSimple\",\n                                                             no_init)\n      .def(init<Experiment, mat3<double>, double, int>());\n\n    class_<BBoxCalculatorAngular, bases<BBoxCalculatorBase> >(\"BBoxCalculatorAngular\",\n                                                              no_init)\n      .def(init<Experiment, mat3<double>, double, int>());\n\n    class_<MaskCalculatorBase>(\"MaskCalculatorBase\", no_init)\n      .def(\"compute\", &MaskCalculatorBase::compute);\n\n    class_<MaskCalculatorSimple, bases<MaskCalculatorBase> >(\"MaskCalculatorSimple\",\n                                                             no_init)\n      .def(init<Experiment, mat3<double>, double>());\n\n    class_<MaskCalculatorAngular, bases<MaskCalculatorBase> >(\"MaskCalculatorAngular\",\n                                                              no_init)\n      .def(init<Experiment, mat3<double>, double>());\n  }\n\n}}}  // namespace dials::algorithms::boost_python\n", "meta": {"hexsha": "69de620fcd198613a500c01dafec52b867b5107f", "size": 26112, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/dials/algorithms/profile_model/ellipsoid/boost_python/ext.cc", "max_stars_repo_name": "dials-src/dials", "max_stars_repo_head_hexsha": "25055c1f6164dc33e672e7c5c6a9c5a35e870660", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-10T17:28:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T17:28:16.000Z", "max_issues_repo_path": "src/dials/algorithms/profile_model/ellipsoid/boost_python/ext.cc", "max_issues_repo_name": "dials-src/dials", "max_issues_repo_head_hexsha": "25055c1f6164dc33e672e7c5c6a9c5a35e870660", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dials/algorithms/profile_model/ellipsoid/boost_python/ext.cc", "max_forks_repo_name": "dials-src/dials", "max_forks_repo_head_hexsha": "25055c1f6164dc33e672e7c5c6a9c5a35e870660", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-07T12:39:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-07T12:39:04.000Z", "avg_line_length": 33.0113780025, "max_line_length": 88, "alphanum_fraction": 0.6088771446, "num_tokens": 7172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2735575186582459}}
{"text": "//\n// Created by Сергей Кривонос on 01.09.17.\n//\n#include \"Integer.h\"\n\n#include \"i.h\"\n#include \"Infinity.h\"\n#include \"Exponentiation.h\"\n#include \"Fraction.h\"\n#include \"Modulo.h\"\n#include \"PrincipalSurd.h\"\n#include \"Product.h\"\n#include \"Sum.h\"\n\n#include <rt/Prime.h>\n#include <rt/tasq.h>\n\n#include <algorithm>\n#include <codecvt>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n\n#include <boost/archive/binary_oarchive.hpp>\n#if __cplusplus >= 201700\n#include <random>\n#ifndef __GNUC__\nnamespace std {\n    template< class It >\n    void random_shuffle( It f, It l )\n    {\n        std::random_device rd;\n        std::mt19937 g(rd());\n        std::shuffle(f, l, g);\n    }\n}\n#endif\n#endif\n#ifdef OPENMIND_USE_OPENCL\n#include <boost/compute.hpp>\n#endif\n#include <boost/functional/hash.hpp>\n#include <boost/numeric/conversion/converter.hpp>\n#include <boost/math/special_functions/prime.hpp>\n#include <boost/multiprecision/integer.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/detail/default_ops.hpp>\n#include <boost/multiprecision/detail/integer_ops.hpp>\n#include <boost/multiprecision/integer.hpp>\n#include <boost/multiprecision/miller_rabin.hpp>\n\n\nusing boost::multiprecision::cpp_int;\n\nnamespace omnn{\nnamespace math {\n\n    const Integer::ranges_t Integer::empty_zero_zone;\n\n    Integer::Integer(const Fraction& f)\n    : arbitrary(f.getNumerator().ca() / f.getDenominator().ca())\n    {\n        \n    }\n    \n    Integer::operator a_int() const {\n        return arbitrary;\n    }\n    \n    a_int& Integer::a() {\n        return arbitrary;\n    }\n    \n    const a_int& Integer::ca() const {\n        return arbitrary;\n    }\n    \n    Integer::operator int64_t() const {\n        return boost::numeric_cast<int64_t>(arbitrary);\n    }\n    \n    Integer::operator uint64_t() const {\n        return boost::numeric_cast<uint64_t>(arbitrary);\n    }\n    \n    Valuable::YesNoMaybe Integer::IsEven() const {\n        return (arbitrary >= 0 ? arbitrary : -arbitrary) & 1 ? YesNoMaybe::No : YesNoMaybe::Yes;\n    }\n\n    \n    Valuable Integer::operator -() const\n    {\n        return Integer(-arbitrary);\n    }\n    \n    Valuable& Integer::operator +=(const Valuable& v)\n    {\n        if (v.IsInt())\n        {\n            arbitrary += v.ca();\n            hash = std::hash<base_int>()(arbitrary);\n        }\n        else\n        {\n            Become(v + *this);\n        }\n        return *this;\n    }\n\n    Valuable& Integer::operator +=(int v)\n    {\n        arbitrary += v;\n        hash = std::hash<base_int>()(arbitrary);\n        return *this;\n    }\n\n    Valuable& Integer::operator *=(const Valuable& v)\n    {\n        if (v.IsInt())\n        {\n            arbitrary *= v.ca();\n            hash = std::hash<base_int>()(arbitrary);\n        }\n        else\n        {\n            // all other types should handle multiplication by Integer\n            Become(v**this);\n        }\n        return *this;\n    }\n    \n    bool Integer::MultiplyIfSimplifiable(const Valuable& v)\n    {\n        auto is = v.IsInt();\n        if(is) {\n            arbitrary *= v.ca();\n            hash = std::hash<base_int>()(arbitrary);\n        } else if (v.IsVa()) {\n        } else {\n            auto s = v.IsMultiplicationSimplifiable(*this);\n            is = s.first;\n            if(is)\n                Become(std::move(s.second));\n        }\n        return is;\n    }\n\n    std::pair<bool,Valuable> Integer::IsMultiplicationSimplifiable(const Valuable& v) const\n    {\n        std::pair<bool,Valuable> is;\n        is.first = v.IsInt() || v.IsFraction();\n        if (is.first) {\n            is.second = v * *this;\n            if (is.second.Complexity() > v.Complexity())\n                IMPLEMENT; // TODO: not a simple fraction\n        } else if (v.IsVa() || v.IsExponentiation()) {\n        } else {\n            is = v.IsMultiplicationSimplifiable(*this);\n        }\n        return is;\n    }\n\n    bool Integer::SumIfSimplifiable(const Valuable& v)\n    {\n        auto is = v.IsInt();\n        if(is) {\n            arbitrary += v.ca();\n            hash = std::hash<base_int>()(arbitrary);\n        } else {\n            auto s = v.IsSummationSimplifiable(*this);\n            is = s.first;\n            if(is)\n                Become(std::move(s.second));\n        }\n        return is;\n    }\n\n    std::pair<bool,Valuable> Integer::IsSummationSimplifiable(const Valuable& v) const\n    {\n        std::pair<bool,Valuable> is;\n        is.first = v.IsInt();\n        if (is.first) {\n            is.second = v + *this;\n        } else if (v.IsVa() || v.IsExponentiation()) {\n        } else if (v.IsProduct()) {\n        } else {\n            is = v.IsSummationSimplifiable(*this);\n            if (is.first && is.second.Complexity() > v.Complexity())\n                LOG_AND_IMPLEMENT(\"Simplification complexidy exceeds source complexity: \" << v << \"   +   \" << str() << \"   =   \" << is.second);\n        }\n        return is;\n    }\n\n    Valuable& Integer::operator /=(const Valuable& v)\n    {\n        if (v.IsInt())\n        {\n            auto& a = v.ca();\n            if (a == 0) {\n                if (arbitrary < 0) {\n                    Become(MInfinity());\n                } else if (arbitrary > 0) {\n                    Become(Infinity());\n                } else {\n                    Become(NaN());\n                }\n            } else if (arbitrary % a == 0) {\n                arbitrary /= a;\n                hash = std::hash<base_int>()(arbitrary);\n            } else {\n                Become(Fraction(*this, v));\n            }\n        }\n        else if(v.FindVa())\n            *this *= v^-1;\n        else\n            Become(Fraction(*this,v));\n        return *this;\n    }\n\n    Valuable& Integer::operator %=(const Valuable& v)\n    {\n        if (v.IsInt())\n        {\n            arbitrary %= v.ca();\n            hash = std::hash<base_int>()(arbitrary);\n        }\n        else\n        {\n            Become(Modulo(*this, v));\n        }\n        return *this;\n    }\n\n    Valuable& Integer::operator --()\n    {\n        arbitrary--;\n        hash = std::hash<base_int>()(arbitrary);\n        return *this;\n    }\n\n    Valuable& Integer::operator ++()\n    {\n        arbitrary++;\n        hash = std::hash<base_int>()(arbitrary);\n        return *this;\n    }\n\n    Integer::operator int() const\n    {\n        return boost::numeric_cast<int>(arbitrary);\n    }\n\n    Integer::operator uint32_t() const\n    {\n        return boost::numeric_cast<uint32_t>(arbitrary);\n    }\n    \n    Integer::operator double() const\n    {\n        return boost::numeric_cast<double>(arbitrary);\n    }\n\n    Integer::operator long double() const\n    {\n        return boost::numeric_cast<long double>(arbitrary);\n    }\n    \n    Integer::operator unsigned char() const\n    {\n        return boost::numeric_cast<unsigned char>(arbitrary);\n    }\n\n    Valuable Integer::bit(const Valuable& n) const\n    {\n        if (n.IsInt()) {\n            if (arbitrary < 0) {\n                if (arbitrary == -1) {\n                    return 1;\n                }\n                IMPLEMENT\n            }\n            unsigned N = static_cast<unsigned>(n);\n            return static_cast<int>(bit_test(arbitrary, N));\n        }\n        else\n            IMPLEMENT;\n    }\n    \n    Valuable& Integer::shl(const Valuable& n)\n    {\n        if (n.IsInt())\n            arbitrary = arbitrary << static_cast<int>(n);\n        else\n            base::shl(n);\n        return *this;\n    }\n\n    Valuable& Integer::shr(const Valuable& n)\n    {\n        if (n.IsInt())\n            arbitrary = arbitrary >> static_cast<int>(n);\n        else\n            base::shl(n);\n        return *this;\n    }\n\n    Valuable Integer::Shr() const\n    {\n        return Integer(decltype(arbitrary)(arbitrary>>1));\n    }\n    \n    Valuable Integer::Shr(const Valuable& n) const\n    {\n        if (!n.IsInt()) {\n            IMPLEMENT\n        }\n        return Integer(decltype(arbitrary)(arbitrary>>static_cast<unsigned>(n)));\n    }\n    \n    Valuable Integer::Or(const Valuable& n, const Valuable& v) const\n    {\n        IMPLEMENT\n    }\n    Valuable Integer::And(const Valuable& n, const Valuable& v) const\n    {\n        if (v.IsInt()) {\n            auto mask = std::move(--((vo<2>() ^ n).a()));\n            if (arbitrary < v.ca()) {\n                mask &= arbitrary;\n                mask &= v.ca();\n            } else {\n                mask &= v.ca();\n                mask &= arbitrary;\n            }\n            return Valuable(std::move(mask));\n        }\n        else\n            return base::And(n, v);\n    }\n    Valuable Integer::Xor(const Valuable& n, const Valuable& v) const\n    {\n        IMPLEMENT\n    }\n    Valuable Integer::Not(const Valuable& n) const\n    {\n        return Integer(~arbitrary);\n    }\n    \n    std::pair<Valuable,Valuable> Integer::GreatestCommonExp(const Valuable &e) const {\n        // test : 50_v.GCE(2) == 5_v\n        //        32_v.GCE(2) == 4_v\n        //  which is needed to be powered into 2 to get gretest devisor that may be powered into 2 to get devisor of the initial value\n        if (e == constants::one)\n            return {*this,*this};\n\n        auto xFactors = Facts();\n        std::sort(xFactors.begin(), xFactors.end());\n        while(xFactors.size() > 1) {\n            auto&& xFactor = std::move(xFactors.back());\n            if(xFactor > constants::one) {\n                if(e == constants::two){\n                    Valuable v = boost::multiprecision::sqrt(xFactor.ca());\n                    if((v^e) == xFactor)\n                        return {std::move(v),std::move(xFactor)};\n                } else if (e < constants::zero) {\n                    auto me = -e;\n                    IMPLEMENT\n                } else {\n                    IMPLEMENT\n//                    auto v = boost::multiprecision::pow(xFactor, 1/e);\n                }\n            }\n            xFactors.pop_back();\n        }\n        return {constants::one, constants::one};\n    }\n\n    Valuable& Integer::operator^=(const Valuable& v)\n    {\n        if(v == constants::one)\n            return *this;\n        if(arbitrary == 0 || (arbitrary == 1 && v.IsInt()))\n        {\n            if (v == 0) {\n                IMPLEMENT; //NaN\n            }\n            return *this;\n        } else if ((arbitrary == 1 || arbitrary == -1) && v.IsSimpleFraction()) {\n            if(!v.as<Fraction>().getDenominator().IsEven())\n                return *this;\n            else\n                return Become(Exponentiation{*this,v});\n        }\n        if(v.IsInt())\n        {\n// FIXME:     arbitrary = boost::multiprecision::pow(a(), v.ca());\n//            hash = std::hash<base_int>()(arbitrary);\n//            return *this;\n            if (v != 0_v) {\n                if (v > 1) {\n                    Valuable x = *this;\n                    Valuable n = v;\n                    if (n < 0_v)\n                    {\n                        x = 1_v / x;\n                        n = -n;\n                    }\n                    if (n == 0_v)\n                    {\n                        arbitrary = 1;\n                        hash = std::hash<base_int>()(arbitrary);\n                        return *this;\n                    }\n                    auto y = 1_v;\n                    while(n > 1)\n                    {\n                        auto nIsInt = n.IsInt();\n                        if (!nIsInt) IMPLEMENT;\n                        if (n.ca() & 1)\n                        {\n                            y *= x;\n                            --n;\n                        }\n                        x.sq();\n                        n /= 2;\n                    }\n                    x *= y;\n                    if (x.IsInt()) {\n                        arbitrary = std::move(x.a());\n                        hash = std::hash<base_int>()(arbitrary);\n                    }\n                    else\n                        return Become(std::move(x));\n                } else if (v != 1) {\n                    return Become(Exponentiation{*this, v});\n                }\n            }\n            else { // zero\n                if (arbitrary == 0)\n                    throw \"NaN\"; // feel free to handle this properly\n                else\n                {\n                    arbitrary = 1;\n                    hash = std::hash<base_int>()(arbitrary);\n                }\n            }\n        }\n        else if(v.IsSimpleFraction())\n        {\n            auto& f = v.as<Fraction>();\n            auto& nu = f.getNumerator();\n            Valuable mn;\n            auto nlz = nu < 0;\n            if(nlz)\n                mn = -nu;\n            auto n = std::cref(nlz ? mn : nu);\n            auto dn = nlz ? -f.getDenominator() : f.getDenominator();\n\n            auto numeratorIsOne = n == 1_v;\n            if (!numeratorIsOne){\n                *this ^= n;\n                n = std::cref(constants::one);\n            }\n\n            auto isNeg = operator<(0_v);\n            auto signs = 0; //dimmensions\n            while(dn.IsEven() == YesNoMaybe::Yes) {\n                auto minus = arbitrary < 0;\n                auto _ = boost::multiprecision::sqrt(minus ? -arbitrary : arbitrary);\n                auto _sq = _ * _;\n                if (_sq == boost::multiprecision::abs(arbitrary)){\n                    arbitrary = _;\n    //                Become(isNeg ? -operator-().Sqrt() : Sqrt());\n                    dn /= 2;\n                    ++signs;\n                } else {\n//                    IMPLEMENT\n                    if(n!=1_v)\n                        IMPLEMENT;\n                    auto gce = GreatestCommonExp(dn);\n                    return Become(gce.first*Exponentiation{operator/=(gce.second),n/dn});\n                }\n            }\n            if(signs)\n                hash = std::hash<base_int>()(arbitrary);\n            \n            auto dnSubZ = dn < 0;\n            if(dnSubZ)\n                dn = -dn;\n            if(dn != 1_v) {\n                auto even = dn.IsEven();\n                if(even == YesNoMaybe::Yes){\n                    Valuable x = *this;\n                    if(x<0_v){\n                        Valuable exp;\n                        if (!numeratorIsOne) {\n                            *this ^= n;\n                            exp = 1_v / dn;\n                        }\n                        auto& exponentiating = numeratorIsOne ? v : exp;\n                        auto xFactors = FactSet();\n                        auto rb = xFactors.rbegin(), re = xFactors.rend();\n                        for (auto it = rb; it != re; ++it) {\n                            auto& xFactor = *it;\n                            if(xFactor > 1_v /* && !operator==(xFactor) */){\n                                auto e = xFactor ^ dn;\n                                if(operator==(e))\n                                    return Become(e*(1_v^exponentiating));\n                                auto f = xFactor ^ exponentiating;\n                                if(!f.IsInt())\n                                    f /= 1_v ^ exponentiating;\n                                if(f.IsInt())\n                                    return Become(f*((x/xFactor)^exponentiating));\n                            }\n                        }\n                        IMPLEMENT\n                    }\n                }\n//                else if(dn==2_v) {\n//                    return Become(Sqrt()*(1^(1_v/2)));\n//                }\n\n                Valuable nroot;\n                bool rootFound = false;\n                Valuable left =0, right = *this;\n                \n                while (!rootFound)\n                {\n                    auto d = right - left;\n                    d -= d % 2;\n                    if (d!=0) {\n                        nroot = left + d / 2;\n                        auto result = nroot ^ dn;\n                        rootFound = result == *this;\n                        if (rootFound)\n                            break;\n                        else\n                            if (result > *this)\n                                right = nroot;\n                            else\n                                left = nroot;\n                    }\n                    else {\n                        nroot = Exponentiation(*this, 1_v/dn);\n                        break;\n                    }\n                    // *this ^ 1/dn  == (nroot^dn + t)^ 1/dn\n                    // this == nroot^dn +\n                    // TODO : IMPLEMENT//return Become(Sum {nroot, (*this-(nroot^dn))^(1/dn)});\n                }\n                return Become(std::move(nroot));\n            }\n            if(dnSubZ)\n                Become(1_v / *this);\n            if(signs) {\n                return operator*=((isNeg?-1_v:1_v)^(1_v/(2_v^signs)));\n            }\n        }\n        else\n            return Become(Exponentiation(*this, v));\n\n        optimize();\n        return *this;\n    }\n    \n    Valuable& Integer::d(const Variable& x)\n    {\n        arbitrary = 0;\n        return *this;\n    }\n    \n    bool Integer::IsComesBefore(const Valuable& v) const\n    {\n        return v.IsInt() && *this > v;\n    }\n    \n    Valuable Integer::InCommonWith(const Valuable& v) const\n    {\n        return (v.IsInt() && v!=0_v && *this!=0_v) ? boost::gcd(v.ca(),ca()) : 1_v;\n    }\n\n    // sqrt using boost\n    Valuable Integer::Sqrt() const\n    {\n        auto minus = arbitrary < 0;\n        auto _ = boost::multiprecision::sqrt(minus ? -arbitrary : arbitrary); // integer square root\n        auto _sq = _ * _;\n        if (_sq != boost::multiprecision::abs(arbitrary)){ // no integer square root\n            auto d = GreatestCommonExp(2);\n            if (d.second != 1)\n                return (*this / d.second).Sqrt() * d.first;\n            else\n            {\n                return Valuable(std::make_shared<PrincipalSurd>(*this));\n                LOG_AND_IMPLEMENT(str() << \" integer square root is \" << _ << \" and \" << _ << \"^2=\" << _sq); // implement radicals support\n            }\n        }\n        return minus ? constant::i * _ : _;\n    }\n\n    // Sqrt using rational root test\n//    Valuable Integer::Sqrt() const\n//    {\n//        auto minus = arbitrary < 0;\n//\n//        // build an equation, find using RRT:\n//        Variable x;\n//        Valuable eq = *this;\n//        auto _ = x.Sq();\n//        eq += minus ? _ : -_;\n//        eq.SetView(View::Solving);\n//\n//        auto esurrto = enforce_solve_using_rational_root_test_only;\n//        enforce_solve_using_rational_root_test_only = true;\n//        auto sols = eq.Solutions(x);\n//        enforce_solve_using_rational_root_test_only = esurrto;\n//\n//        if(!sols.size()){\n//            IMPLEMENT\n//        }\n//        auto it = sols.begin();\n//        if(*it < 0)\n//            ++it;\n//        _ = *it;\n//\n//        return minus ? constant::i * _ : _;\n//    }\n\n    std::wstring Integer::save(const std::wstring& f) const\n    {\n        using namespace std;\n        using convert_typeX = codecvt_utf8<wchar_t>;\n        std::wstring_convert<convert_typeX, wchar_t> c;\n        std::ofstream s(c.to_bytes(f));\n        boost::archive::binary_oarchive a(s);\n        a & arbitrary;\n        return f;\n    }\n\n    Valuable Integer::Sign() const {\n        return arbitrary.sign();\n    }\n    \n    bool Integer::operator <(const Valuable& v) const\n    {\n        if (v.IsInt())\n            return arbitrary < v.ca();\n        else if (v.IsFraction())\n            return !(v < *this) && *this!=v;\n        else if(v.IsMInfinity())\n            return {};\n        else if(v.IsInfinity())\n            return true;\n        else if (!v.FindVa()) {\n            double _1 = boost::numeric_cast<double>(arbitrary);\n            double _2 = static_cast<double>(v);\n            if(_1 == _2) {\n                IMPLEMENT\n            }\n            return _1 < _2;\n       } else\n            return base::operator <(v);\n    }\n\n    bool Integer::operator ==(const Valuable& v) const\n    {\n        if (v.IsInt())\n            return Hash() == v.Hash() && arbitrary == v.ca();\n        else if(v.FindVa())\n            return false;\n        else\n            return v.operator==(*this);\n    }\n\n    std::ostream& Integer::print(std::ostream& out) const\n    {\n        return out << arbitrary;\n    }\n    \n    std::wostream& Integer::print(std::wostream& out) const\n    {\n        return out << arbitrary.str().c_str();\n    }\n\n    Valuable Integer::calcFreeMember() const\n    {\n        return *this;\n    }\n\n    std::deque<Valuable> Integer::Facts() const\n    {\n        std::deque<Valuable> f;\n        Factorization([&](auto& v){\n            f.push_back(v);\n            return false;\n        }, abs());\n        return f;\n    }\n\n\tvoid Integer::factorial() {\n        if (arbitrary == 0)\n            arbitrary = 1;\n        else for (auto i = arbitrary; i-- > 1;)\n            arbitrary *= i;\n        hash = std::hash<base_int>()(arbitrary);\n\t}\n\n    bool Integer::IsPrime() const\n    {\n        auto is = //boost::multiprecision::miller_rabin_test(boost::numeric_cast<uint64_t>(ca()), 3) &&\n            !Factorization(\n            [&](auto& v) {\n                auto isPrimeFactor = v == 0_v || v == 1_v || v == *this;\n                auto stop = !isPrimeFactor;\n                return stop;\n            },\n            abs());\n        return is;\n    }\n\n    std::set<Valuable> Integer::SimpleFactsSet() const {\n        std::set<Valuable> f;\n        SimpleFactorization(\n            [&](auto& v) {\n                f.emplace(std::move(v));\n                return false;\n            },\n            abs());\n        f.erase(0);\n        return f;\n    }\n\n    std::set<Valuable> Integer::FactSet() const {\n        std::set<Valuable> f;\n        Factorization(\n            [&](auto& v) {\n                f.emplace(std::move(v));\n                return false;\n            },\n            abs());\n        f.erase(0);\n        return f;\n    }\n\n    bool Integer::SimpleFactorization(const std::function<bool(const Valuable&)>& f, const Valuable& max,\n                                const ranges_t& zz) const {\n        auto h = arbitrary;\n        if(h < 0)\n            h = -h;\n        if (f(0)) {\n            return true;\n        }\n        bool scanz = zz.second.size();\n        auto scanIt = zz.second.end();\n        Valuable up = Integer(h);\n        if (up > max) up = max;\n        auto from = 1_v;\n        if (scanz) {\n            if (zz.first.second < up) {\n                if(zz.first.second.IsInt())\n                    up = zz.first.second;\n                else\n                    up = static_cast<int>(static_cast<double>(zz.first.second));\n            }\n            if (zz.first.first > from) {\n                if(zz.first.first.IsInt())\n                    from = zz.first.first;\n                else\n                    from = static_cast<int>(static_cast<double>(zz.first.first));\n            }\n            scanIt = zz.second.begin();\n            while (scanIt != zz.second.end() && scanIt->second < from) {\n                ++scanIt;\n            }\n        }\n        auto absolute = abs();\n        if(from==up)\n            return f(up);\n        else\n            for (auto i = from; i < up; ++i) {\n                auto a = absolute / i;\n                if (a.IsInt()) {\n                    if(f(i) || f(a))\n                        return true;\n                    if (a < up) {\n                        up = a;\n                    }\n                }\n\n                if (scanz && i > scanIt->second) {\n                    ++scanIt;\n                    if (scanIt == zz.second.end()) {\n                        break;\n                    }\n                    i = scanIt->first;\n                    if (!i.IsInt()) {\n                        IMPLEMENT;\n                    }\n                }\n            }\n        return false;\n    }\n\n    namespace {\n        StoringTasksQueue factorizationTasks;\n    }\n    bool Integer::Factorization(const std::function<bool(const Valuable&)>& f, const Valuable& max, const ranges_t& zz) const\n    //{\n    //    std::set<Integer> factors;\n    //    return Factorization(f, max, factors, zz);\n    //}\n\n    //bool Integer::Factorization(const std::function<bool(const Valuable&)>& f, \n    //    const Valuable& max,\n    //    std::set<Integer>& factors,\n    //    const ranges_t& zz) const\n    {   // check division by primes\n        // iterate by primes to find factor and store it in factors set \n        // togather with lowest factor found highest factor as result of division\n        // the highest factor reduces the search range to its value exclusively (1)\n        // after scan all the primes, need to scan permutations\n        // \n        // starting from smallest prime factor, \n        //   new set of non-prime factors is enreached with muiltiple multiplications to current prime to self and to each member of the new set\n        //   new set iterating starting from smallest too and until range out of upper bound (1)\n        //  ...\n\n        // Multi-threaded way:\n        // for devisible of thouse: isDevisible = (ResultOfDivision = This / iPrime).IsInt():\n        // add products of the Divisibles with factorization set numbers of result of division:\n        // (add all [ResultOfDivision factors starting from iPrime inclusively] time iPrime)  recursively\n        auto absolute = arbitrary;\n        if (absolute < 0)\n            absolute = -absolute;\n        decltype(arbitrary) from = 2;\n        if (zz.first.first > from) {\n            if(zz.first.first.IsInt())\n                from = zz.first.first.ca();\n            else\n                from = static_cast<int>(static_cast<double>(zz.first.first)); // FIXME: precision issues\n        }\n        else if (f(0_v) || f(1_v)) {\n            return true;\n        }\n        bool scanz = zz.second.size();\n        auto scanIt = zz.second.end();\n        Valuable up(absolute);\n        if (up > max) up = max;\n        auto primeIdx = 0;\n        if (zz.first.first < zz.first.second) {\n            if (zz.first.second < up) {\n                if (zz.first.second.IsInt())\n                    up = zz.first.second;\n                else\n                    up = static_cast<int>(static_cast<double>(zz.first.second)); // FIXME: precision issues\n            }\n        } else {\n            // assuming its current prime index stored\n            primeIdx = boost::numeric_cast<decltype(primeIdx)>(zz.first.second.ca());\n        }\n        if (absolute <= up && f(absolute)) {\n            return true;\n        }\n        if (scanz) {\n            scanIt = zz.second.begin();\n            while (scanIt != zz.second.end() && scanIt->second < from) {\n                ++scanIt;\n            }\n        }\n        if(from==up)\n            return f(up);\n        else {\n            std::set<decltype(arbitrary)> primeFactors, nonPrimeFactors;\n            auto maxPrimeIdx = omnn::rt::primes();\n            auto& primeUpmost = omnn::rt::prime(maxPrimeIdx);\n            auto prime = omnn::rt::prime(primeIdx);\n            while (prime < from)\n                prime = omnn::rt::prime(++primeIdx);\n            if (prime != from) { // from is not a prime number\n                for (auto i = from; i < prime; ++i) { // slow scan till first prime\n                    if (absolute % i == 0) {\n                        auto a = absolute;\n                        a /= i;\n                        if (f(i) || f(a))\n                            return true;\n                        if (a < up) {\n                            up = a;\n                        }\n                        nonPrimeFactors.emplace(a);\n                    }\n                    if (scanz && i > scanIt->second) {\n                        ++scanIt;\n                        if (scanIt == zz.second.end()) {\n                            break;\n                        }\n                        if (!scanIt->first.IsInt()) {\n                            IMPLEMENT;\n                        }\n                        i = scanIt->first.ca();\n                    }\n                }\n            }\n\n            // iterating by primes\n            auto primeScanUp = up;\n            while (from <= primeUpmost\n                && primeScanUp >= prime\n\t\t\t\t&& primeIdx < maxPrimeIdx)\n            {\n                if (absolute % prime == 0) {\n                    auto a = absolute;\n                    a /= prime;\n                    if(prime > a)\n                        break;\n                    if (f(prime) || f(a))\n                        return true;\n                    primeFactors.emplace(prime);\n                    nonPrimeFactors.emplace(a);\n                    if (a < primeScanUp)\n                        primeScanUp = a;\n                }\n                prime = omnn::rt::prime(++primeIdx);\n            }\n\n            if (primeIdx == maxPrimeIdx)\n            {\n#ifdef OPENMIND_PRIME_MINING\n                static bool OutOfPrimesTableWarning = {};\n                if (!OutOfPrimesTableWarning) {\n                    std::cerr\n                        << primeUpmost\n                        << \" is the biggest prime number in the hardcoaded primes table used for fast factorization to \"\n                           \"solve equations using RRT. Consider extending primes table to make this perform much \"\n                           \"quicker.\"\n                        << std::endl;\n                    OutOfPrimesTableWarning = true;\n                    //rt::GrowPrime(absolute,\n                    //    [](const decltype(absolute)& v) {\n                    //        return Integer(v).IsPrime();\n                    //    });\n                }\n#endif\n                // Fallback algorithm\n                for (auto i = from; i < up; ++i) {\n                    if (absolute % i == 0) {\n                        auto a = absolute;\n                        a /= i;\n                        if (f(i) || f(a))\n                            return true;\n                        if (a < up) {\n                            up = a;\n                        }\n                    }\n\n                    if (scanz && i > scanIt->second) {\n                        ++scanIt;\n                        if (scanIt == zz.second.end()) {\n                            break;\n                        }\n                        if (!scanIt->first.IsInt()) {\n                            IMPLEMENT;\n                        }\n                        i = scanIt->first.ca();\n                    }\n                }\n                return false;\n            }\n\n            for (auto& prime : primeFactors) {\n                auto mul = prime;\n                mul *= prime;\n                decltype(primeFactors) addNonPrime;\n                while (mul <= up)\n                {\n                    if (absolute % mul == 0) {\n                        auto a = absolute;\n                        a /= mul;\n                        if (nonPrimeFactors.find(mul) == nonPrimeFactors.end()\n                            && addNonPrime.emplace(mul).second)\n                        {\n                            if (f(mul))\n                                return true;\n                            if (nonPrimeFactors.find(a) == nonPrimeFactors.end()\n                                && addNonPrime.emplace(a).second) {\n                                if (f(a))\n                                    return true;\n                            }\n                        }\n                    } else {\n                        break;\n                    }\n                    mul *= prime;\n                }\n\n                for (auto& nonPrime : nonPrimeFactors) {\n                    mul = nonPrime;\n                    for (;;) {\n                        mul *= prime;\n                        if (mul > up)\n                            break;\n                        if (absolute % mul == 0) {\n                            auto a = absolute;\n                            a /= mul;\n                            if (nonPrimeFactors.find(mul) == nonPrimeFactors.end() && addNonPrime.emplace(mul).second) {\n                                if (f(mul))\n                                    return true;\n                                if (nonPrimeFactors.find(a) == nonPrimeFactors.end() && addNonPrime.emplace(a).second) {\n                                    if (f(a))\n                                        return true;\n                                }\n                            } else {\n                                break;\n                            }\n                        } else {\n                            break;\n                        }\n                    }\n                }\n\n                nonPrimeFactors.merge(std::move(addNonPrime));\n            }\n\n        }\n        //        }\n//        else\n//        {\n//            // build OpenCL kernel\n//            using namespace boost::compute;\n//            auto copy = *this;\n//            copy.optimize();\n//            std::stringstream source;\n//            source << \"__kernel void f(__global long16 a, __global long16 *c) {\"\n//                << \"    const uint i = get_global_id(0);\"\n//                << \"    c[i] = a/i;\"\n//                << \";}\";\n//\n//            device cuwinner = system::default_device();\n//            for(auto& p: system::platforms())\n//                for(auto& d: p.devices())\n//                    if (d.compute_units() > cuwinner.compute_units())\n//                        cuwinner = d;\n//            auto wgsz = cuwinner.max_work_group_size();\n//            context context(cuwinner);\n//\n//            kernel k(program::build_with_source(source.str(), context), \"f\");\n//            auto sz = wgsz * sizeof(cl_long16);\n//            buffer c(context, sz);\n//            k.set_arg(0, c);\n//\n//            command_queue queue(context, cuwinner);\n//            // run the add kernel\n//            queue.enqueue_1d_range_kernel(k, 0, wgsz, 0);\n//\n//            // transfer results to the host array 'c'\n//            std::vector<cl_long> z(wgsz);\n//            queue.enqueue_read_buffer(c, 0, sz, &z[0]);\n//            queue.finish();\n        \n//        }\n\n        \n//#pragma omp for\n        return false;\n    }\n}}\n\n", "meta": {"hexsha": "f38a1385de238845e490387e55bd59aef1c864bf", "size": 33850, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "omnn/math/Integer.cpp", "max_stars_repo_name": "iHateInventNames/openmind", "max_stars_repo_head_hexsha": "2587b811e594daf9d9c235cb63eeae2950e93ff0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "omnn/math/Integer.cpp", "max_issues_repo_name": "iHateInventNames/openmind", "max_issues_repo_head_hexsha": "2587b811e594daf9d9c235cb63eeae2950e93ff0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2016-05-21T08:48:41.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-22T19:37:03.000Z", "max_forks_repo_path": "omnn/math/Integer.cpp", "max_forks_repo_name": "iHateInventNames/openmind", "max_forks_repo_head_hexsha": "2587b811e594daf9d9c235cb63eeae2950e93ff0", "max_forks_repo_licenses": ["BSD-3-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.6651075772, "max_line_length": 144, "alphanum_fraction": 0.4278286558, "num_tokens": 7464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2735575132026653}}
{"text": "/*\r\n * Copyright (c) 2011 Adrian Michel\r\n * http://www.amichel.com\r\n *\r\n * Permission to use, copy, modify, distribute and sell this \r\n * software and its documentation for any purpose is hereby \r\n * granted without fee, provided that both the above copyright \r\n * notice and this permission notice appear in all copies and in \r\n * the supporting documentation. \r\n *  \r\n * This library is distributed in the hope that it will be \r\n * useful. However, Adrian Michel makes no representations about\r\n * the suitability of this software for any purpose.  It is \r\n * provided \"as is\" without any express or implied warranty. \r\n * \r\n * Should you find this library useful, please email \r\n * info@amichel.com with a link or other reference \r\n * to your work. \r\n */\r\n\r\n#ifndef DE_DIFFERENTIAL_EVOLUTION_HPP_INCLUDED\r\n#define DE_DIFFERENTIAL_EVOLUTION_HPP_INCLUDED\r\n\r\n// MS compatible compilers support #pragma once\r\n\r\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\r\n#pragma once\r\n#endif\r\n\r\n#include <boost/shared_ptr.hpp>\r\n#include <boost/make_shared.hpp>\r\n#include <boost/enable_shared_from_this.hpp>\r\n#include <boost/shared_array.hpp>\r\n#include <boost/scope_exit.hpp>\r\n\r\n#include \"random_generator.hpp\"\r\n#include \"multithread.hpp\"\r\n#include \"individual.hpp\"\r\n#include \"processors.hpp\"\r\n#include \"mutation_strategy.hpp\"\r\n#include \"population.hpp\"\r\n#include \"selection_strategy.hpp\"\r\n#include \"termination_strategy.hpp\"\r\n#include \"listener.hpp\"\r\n\r\nnamespace de\r\n{\r\n\r\n/**\r\n * Exception thrown in case of an error during an optimization \r\n * session \r\n * \r\n * @author adrian (12/1/2011)\r\n */\r\nclass differential_evolution_exception\r\n{\r\n};\r\n\r\n/**\r\n * Differential evolution main class \r\n *  \r\n * Runs an optimization session based on various input \r\n * parameters or strategies \r\n * \r\n * @author adrian (12/1/2011)\r\n */\r\ntemplate< typename T > class differential_evolution\r\n{\r\nprivate:\r\n    const size_t m_varCount;\r\n    const size_t m_popSize;\r\n\r\n    population_ptr m_pop1;\r\n    population_ptr m_pop2;\r\n    individual_ptr m_bestInd;\r\n\r\n    constraints_ptr m_constraints;\r\n    typename processors< T >::processors_ptr m_processors;\r\n    termination_strategy_ptr m_terminationStrategy;\r\n    selection_strategy_ptr m_selectionStrategy;\r\n    mutation_strategy_ptr m_mutationStrategy;\r\n    listener_ptr m_listener;\r\n\r\n    const bool m_minimize;\r\npublic:\r\n    /**\r\n     * constructs a differential_evolution object\r\n     * \r\n     * @author adrian (12/4/2011)\r\n     * \r\n     * @param varCount total number of variables. It includes the \r\n     *  \t\t\t   variables required by the objective function\r\n     *  \t\t\t   but has many more elements as required by the\r\n     *  \t\t\t   algorithm\r\n     * @param popSize total number of individuals in a population\r\n     * @param processors number of parallel processors used \r\n     *  \t\t\t\t during an optimization session\r\n     * @param constraints a vector of constraints that contains the \r\n     *  \t\t\t\t  constraints for the variables used by the\r\n     *  \t\t\t\t  objective function as well as constraints\r\n     *  \t\t\t\t  for all other variables used internally by\r\n     *  \t\t\t\t  the algorithm\r\n     * @param minimize will attempt to minimize the cost if true, or \r\n     *  \t\t\t   maximize the cost if false\r\n     * @param terminationStrategy a termination strategy\r\n     * @param selectionStrategy a selection strategy\r\n     * @param mutationStrategy a mutation strategy\r\n     * @param listener a listener\r\n     */\r\n    differential_evolution( size_t varCount, size_t popSize, typename processors< T >::processors_ptr processors, constraints_ptr constraints, bool minimize, \r\n                            termination_strategy_ptr terminationStrategy, selection_strategy_ptr selectionStrategy, \r\n                            mutation_strategy_ptr mutationStrategy, de::listener_ptr listener )\r\n    try\r\n\r\n        : m_varCount( varCount ), m_popSize( popSize ), m_pop1( boost::make_shared< population >( popSize, varCount, constraints ) ), \r\n              m_pop2( boost::make_shared< population >( popSize, varCount ) ), m_bestInd( m_pop1->best( minimize ) ),\r\n              m_constraints( constraints ), m_processors( processors ), m_minimize( minimize ), m_terminationStrategy( terminationStrategy ),\r\n              m_listener( listener ), m_selectionStrategy( selectionStrategy ), m_mutationStrategy( mutationStrategy )\r\n\t{\r\n            assert( processors );\r\n            assert( constraints );\r\n            assert( terminationStrategy );\r\n            assert( selectionStrategy );\r\n            assert( listener );\r\n            assert( mutationStrategy );\r\n\r\n            assert( popSize > 0 );\r\n            assert( varCount > 0 );\r\n\r\n            // initializing population 1 by running all objective functions with\r\n            // the initial random arguments\r\n            processors->push( m_pop1 );\r\n            processors->start();\r\n            processors->wait();\r\n\r\n\t}\r\n    catch( const processors_exception&)\r\n    {\r\n        throw differential_evolution_exception();\r\n    }\r\n\r\n    virtual ~differential_evolution(void)\r\n    {\r\n    }\r\n\r\n    /**\r\n     * starts a differential evolution optimization process \r\n     *  \r\n     * although the processing is done in parallel, this function is \r\n     * synchronous and won't return until the optimization is \r\n     * complete, or an error triggered an exception \r\n     * \r\n     * @author adrian (12/4/2011)\r\n     */\r\n    void run()\r\n    {\r\n        try\r\n        {\r\n            m_listener->start();\r\n            individual_ptr bestIndIteration( m_bestInd );\r\n\r\n            for( size_t genCount = 0 ; m_terminationStrategy->event( m_bestInd, genCount ); ++genCount ) \r\n            {\r\n                m_listener->startGeneration( genCount );\r\n                for( size_t i = 0; i < m_popSize; ++i) \r\n                {\r\n                    mutation_strategy::mutation_info mutationInfo( ( *m_mutationStrategy)( *m_pop1, bestIndIteration, i ) );\r\n\r\n                    individual_ptr tmpInd( boost::tuples::get< 0 >( mutationInfo ) );\r\n\r\n                    tmpInd->ensureConstraints( m_constraints, boost::tuples::get< 1 >( mutationInfo ) );\r\n\r\n                    // populate the queue\r\n                    m_processors->push( tmpInd );\r\n\r\n                    // put temps in a temp vector for now (they are empty until processed), will be moved to the right place\r\n                    // after processed\r\n                    (*m_pop2)[ i ] = tmpInd;\r\n                }\r\n\r\n                m_listener->startProcessors( genCount );\r\n                m_processors->start();\r\n                m_processors->wait();\r\n                m_listener->endProcessors( genCount );\r\n\r\n                //BestParentChildSelectionStrategy()( m_pop1, m_pop2, m_bestInd, m_minimize );\r\n                m_listener->startSelection( genCount );\r\n                (*m_selectionStrategy)( m_pop1, m_pop2, m_bestInd, m_minimize );\r\n                bestIndIteration = m_bestInd;\r\n\r\n                m_listener->endSelection( genCount );\r\n\r\n                m_listener->endGeneration( genCount, bestIndIteration, m_bestInd );\r\n\r\n            }\r\n\r\n            BOOST_SCOPE_EXIT_TPL( (m_listener) )\r\n            {\r\n                m_listener->end();\r\n            } \r\n            BOOST_SCOPE_EXIT_END\r\n\t\t}\r\n        catch( const processors_exception& )\r\n        {\r\n            m_listener->error();\r\n            throw differential_evolution_exception();\r\n        }\r\n\r\n    }\r\n\r\n    /**\r\n     * returns the best individual resulted from the optimization \r\n     * process \r\n     * \r\n     * @author adrian (12/4/2011)\r\n     * \r\n     * @return individual_ptr \r\n     */\r\n    individual_ptr best() const { return m_bestInd; }\r\n};\r\n\r\n}\r\n\r\n#endif //DE_DIFFERENTIAL_EVOLUTION_HPP_INCLUDED\r\n", "meta": {"hexsha": "8dd99b88cec69df4ccb36ab9279014b4c72051f9", "size": 7696, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/de/differential_evolution.hpp", "max_stars_repo_name": "gchoinka/gpcxx", "max_stars_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2015-05-15T08:01:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T07:28:54.000Z", "max_issues_repo_path": "third_party/de/differential_evolution.hpp", "max_issues_repo_name": "gchoinka/gpcxx", "max_issues_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-03-26T23:48:04.000Z", "max_issues_repo_issues_event_max_datetime": "2016-02-29T14:16:37.000Z", "max_forks_repo_path": "third_party/de/differential_evolution.hpp", "max_forks_repo_name": "gchoinka/gpcxx", "max_forks_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-02-12T21:39:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-01T05:14:08.000Z", "avg_line_length": 34.2044444444, "max_line_length": 159, "alphanum_fraction": 0.6248700624, "num_tokens": 1584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2735521581443009}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_PROB_PARETO_TYPE_2_RNG_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_PARETO_TYPE_2_RNG_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <stan/math/prim/scal/err/check_positive_finite.hpp>\n#include <stan/math/prim/scal/prob/exponential_rng.hpp>\n#include <stan/math/prim/scal/prob/normal_rng.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Return a Pareto type 2 random variate for the given location,\n * scale, and shape using the specified random number generator.\n *\n * mu, lambda, and alpha can each be a scalar or a one-dimensional container.\n * Any non-scalar inputs must be the same size.\n *\n * @tparam T_loc Type of location parameter\n * @tparam T_scale Type of scale parameter\n * @tparam T_shape Type of shape parameter\n * @tparam RNG type of random number generator\n * @param mu (Sequence of) location parameter(s)\n * @param lambda (Sequence of) scale parameter(s)\n * @param alpha (Sequence of) shape parameter(s)\n * @param rng random number generator\n * @return (Sequence of) Pareto type 2 random variate(s)\n * @throw std::domain_error if mu is infinite or lambda or alpha are\n * nonpositive,\n * @throw std::invalid_argument if non-scalar arguments are of different\n * sizes\n */\ntemplate <typename T_loc, typename T_scale, typename T_shape, class RNG>\ninline typename VectorBuilder<true, double, T_loc, T_scale, T_shape>::type\npareto_type_2_rng(const T_loc& mu, const T_scale& lambda, const T_shape& alpha,\n                  RNG& rng) {\n  using boost::random::uniform_real_distribution;\n  using boost::variate_generator;\n  static const char* function = \"pareto_type_2_rng\";\n\n  check_finite(function, \"Location parameter\", mu);\n  check_positive_finite(function, \"Scale parameter\", lambda);\n  check_positive_finite(function, \"Shape parameter\", alpha);\n  check_consistent_sizes(function, \"Location parameter\", mu, \"Scale Parameter\",\n                         lambda, \"Shape Parameter\", alpha);\n\n  scalar_seq_view<T_loc> mu_vec(mu);\n  scalar_seq_view<T_scale> lambda_vec(lambda);\n  scalar_seq_view<T_shape> alpha_vec(alpha);\n  size_t N = max_size(mu, lambda, alpha);\n  VectorBuilder<true, double, T_loc, T_scale, T_shape> output(N);\n\n  variate_generator<RNG&, uniform_real_distribution<> > uniform_rng(\n      rng, uniform_real_distribution<>(0.0, 1.0));\n  for (size_t n = 0; n < N; ++n) {\n    output[n] = (std::pow(1.0 - uniform_rng(), -1.0 / alpha_vec[n]) - 1.0)\n                    * lambda_vec[n]\n                + mu_vec[n];\n  }\n\n  return output.data();\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "40f546674f39a407cca0e27ccdd3de15853fbbec", "size": 2747, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/scal/prob/pareto_type_2_rng.hpp", "max_stars_repo_name": "PhilClemson/math", "max_stars_repo_head_hexsha": "fffe604a7ead4525be2551eb81578c5f351e5c87", "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/pareto_type_2_rng.hpp", "max_issues_repo_name": "PhilClemson/math", "max_issues_repo_head_hexsha": "fffe604a7ead4525be2551eb81578c5f351e5c87", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/pareto_type_2_rng.hpp", "max_forks_repo_name": "PhilClemson/math", "max_forks_repo_head_hexsha": "fffe604a7ead4525be2551eb81578c5f351e5c87", "max_forks_repo_licenses": ["BSD-3-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.6901408451, "max_line_length": 79, "alphanum_fraction": 0.7302511831, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2735521581443009}}
{"text": "// Copyright  (C)  2021 Djordje Vukcevic <djordje dot vukcevic at h-brs dot de>\n\n// Version: 1.0\n// Author: Djordje Vukcevic <djordje dot vukcevic at h-brs dot de>\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#ifndef KDL_CHAIN_EXTERNAL_WRENCH_ESTIMATOR_HPP\n#define KDL_CHAIN_EXTERNAL_WRENCH_ESTIMATOR_HPP\n\n#include <Eigen/Core>\n#include \"utilities/svd_eigen_HH.hpp\"\n#include \"chaindynparam.hpp\"\n#include \"chainjnttojacsolver.hpp\"\n#include \"chainfksolverpos_recursive.hpp\"\n#include <iostream>\n\nnamespace KDL {\n\n    /**\n     * \\brief First-order momentum observer for the estimation of external wrenches applied on the robot's end-effector. \n     *\n     * Implementation based on:\n     * S. Haddadin, A. De Luca and A. Albu-Schäffer,\n     * \"Robot Collisions: A Survey on Detection, Isolation, and Identification,\"\n     * in IEEE Transactions on Robotics, vol. 33(6), pp. 1292-1312, 2017.\n     * \n     * Note: This component assumes that the external wrench is applied on the end-effector (last) link of the robot's chain.\n     */\n    class ChainExternalWrenchEstimator : public SolverI\n    {\n        typedef Eigen::Matrix<double, 6, 1 > Vector6d;\n\n    public:\n\n        static const int E_FKSOLVERPOS_FAILED = -100; //! Internally-used Forward Position Kinematics (Recursive) solver failed\n        static const int E_JACSOLVER_FAILED = -101; //! Internally-used Jacobian solver failed\n        static const int E_DYNPARAMSOLVERMASS_FAILED = -102; //! Internally-used Dynamics Parameters (Mass) solver failed\n        static const int E_DYNPARAMSOLVERCORIOLIS_FAILED = -103; //! Internally-used Dynamics Parameters (Coriolis) solver failed\n        static const int E_DYNPARAMSOLVERGRAVITY_FAILED = -104; //! Internally-used Dynamics Parameters (Gravity) solver failed\n\n        /**\n         * Constructor for the estimator, it will allocate all the necessary memory\n         * \\param chain The kinematic chain of the robot, an internal copy will be made.\n         * \\param gravity The gravity-acceleration vector to use during the calculation.\n         * \\param sample_frequency Frequency at which users updates it estimation loop (in Hz).\n         * \\param estimation_gain Parameter used to control the estimator's convergence\n         * \\param filter_constant Parameter defining how much the estimated signal should be filtered by the low-pass filter.\n         *                        This input value should be between 0 and 1. Higher the number means more noise needs to be filtered-out.\n         *                        The filter can be turned off by setting this value to 0.\n         * \\param eps If a SVD-singular value is below this value, its inverse is set to zero. Default: 0.00001\n         * \\param maxiter Maximum iterations for the SVD computations. Default: 150.\n         */\n        ChainExternalWrenchEstimator(const Chain &chain, const Vector &gravity, const double sample_frequency, const double estimation_gain, const double filter_constant, const double eps = 0.00001, const int maxiter = 150);\n        ~ChainExternalWrenchEstimator(){};\n\n        /**\n         * Calculates robot's initial momentum in the joint space. \n         * Bassically, sets the offset for future estimation (momentum calculation).\n         * If this method is not called by the user, zero values will be taken for the initial momentum.\n         */\n        int setInitialMomentum(const JntArray &joint_position, const JntArray &joint_velocity);\n\n        // Sets singular-value eps parameter for the SVD calculation\n        void setSVDEps(const double eps_in);\n\n        // Sets maximum iteration parameter for the SVD calculation\n        void setSVDMaxIter(const int maxiter_in);\n\n        /**\n         * This method calculates the external wrench that is applied on the robot's end-effector.\n         * Input parameters:\n         * \\param joint_position The current (measured) joint positions.\n         * \\param joint_velocity The current (measured) joint velocities.\n         * \\param joint_torque The joint space torques. \n         *                     Depending on the user's choice, this array can represent commanded or measured joint torques.\n         *                     A particular choice depends on the available sensors in robot's joint. \n         *                     For more details see the above-referenced article.\n         *\n         * Output parameters:\n         * \\param external_wrench The estimated external wrench applied on the robot's end-effector.\n         *                        The wrench will be expressed w.r.t. end-effector's frame.\n         *\n         * @return error/success code\n         */\n        int JntToExtWrench(const JntArray &joint_position, const JntArray &joint_velocity, const JntArray &joint_torque, Wrench &external_wrench);\n\n        // Returns the torques felt in the robot's joints as a result of the external wrench being applied on the robot.\n        void getEstimatedJntTorque(JntArray &external_joint_torque);\n\n        /// @copydoc KDL::SolverI::updateInternalDataStructures()\n        virtual void updateInternalDataStructures();\n\n        /// @copydoc KDL::SolverI::strError()\n        virtual const char* strError(const int error) const;\n\n    private:\n        const Chain &CHAIN;\n        const double DT_SEC, FILTER_CONST;\n        double svd_eps;\n        int svd_maxiter;\n        unsigned int nj, ns;\n        JntSpaceInertiaMatrix jnt_mass_matrix, previous_jnt_mass_matrix, jnt_mass_matrix_dot;\n        JntArray initial_jnt_momentum, estimated_momentum_integral, filtered_estimated_ext_torque, \n                 gravity_torque, coriolis_torque, total_torque, estimated_ext_torque;\n        Jacobian jacobian_end_eff;\n        Eigen::MatrixXd jacobian_end_eff_transpose, jacobian_end_eff_transpose_inv, U, V;\n        Eigen::VectorXd S, S_inv, tmp, ESTIMATION_GAIN;\n        ChainDynParam dynparam_solver;\n        ChainJntToJacSolver jacobian_solver;\n        ChainFkSolverPos_recursive fk_pos_solver;\n    };\n}\n\n#endif\n", "meta": {"hexsha": "c60b882d41ae1eb765c18c6293b593ff5e918f4c", "size": 6683, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdparty/kdl/src/chainexternalwrenchestimator.hpp", "max_stars_repo_name": "rocos-sia/rocos-app", "max_stars_repo_head_hexsha": "83aa8aa31dd303d77693cfc5ad48055d051fa4bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-12-06T15:30:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:21:40.000Z", "max_issues_repo_path": "3rdparty/kdl/src/chainexternalwrenchestimator.hpp", "max_issues_repo_name": "thinkexist1989/rocos-app", "max_issues_repo_head_hexsha": "7d6ab256c8212504b0a8bbe1ec1dea0c41ea3ff2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3rdparty/kdl/src/chainexternalwrenchestimator.hpp", "max_forks_repo_name": "thinkexist1989/rocos-app", "max_forks_repo_head_hexsha": "7d6ab256c8212504b0a8bbe1ec1dea0c41ea3ff2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.8062015504, "max_line_length": 224, "alphanum_fraction": 0.6990872363, "num_tokens": 1533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2735521581443009}}
{"text": "/*\n * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n *     https://www.orfeo-toolbox.org/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include \"itkNumericTraits.h\"\n\n#include \"otbSailModel.h\"\n#include \"otb_boost_expint_header.h\"\n#include <boost/shared_ptr.hpp>\n#include \"otbMath.h\"\n\n// TODO check EPSILON matlab\n#define EPSILON 0.0000000000000000000000001\n\nnamespace otb\n{\n\n/** Constructor */\nSailModel::SailModel()\n  : m_LAI(2), m_Angl(50), m_PSoil(1), m_Skyl(70), m_HSpot(0.2), m_TTS(30), m_TTO(0), m_PSI(0), m_FCoverView(0.0), m_UseSoilFile(false), m_SoilIndex(0)\n{\n  this->ProcessObject::SetNumberOfRequiredInputs(2);\n  this->ProcessObject::SetNumberOfRequiredOutputs(4);\n\n  SpectralResponseType::Pointer vRefl = static_cast<SpectralResponseType*>(this->MakeOutput(0).GetPointer());\n  this->itk::ProcessObject::SetNthOutput(0, vRefl.GetPointer());\n\n  SpectralResponseType::Pointer hRefl = static_cast<SpectralResponseType*>(this->MakeOutput(1).GetPointer());\n  this->itk::ProcessObject::SetNthOutput(1, hRefl.GetPointer());\n\n  SpectralResponseType::Pointer vAbs = static_cast<SpectralResponseType*>(this->MakeOutput(2).GetPointer());\n  this->itk::ProcessObject::SetNthOutput(2, vAbs.GetPointer());\n\n  SpectralResponseType::Pointer hAbs = static_cast<SpectralResponseType*>(this->MakeOutput(3).GetPointer());\n  this->itk::ProcessObject::SetNthOutput(3, hAbs.GetPointer());\n}\n\n/** Destructor */\nSailModel::~SailModel()\n{\n}\n\n/** Set/Get input reflectance */\nvoid SailModel::SetReflectance(const SpectralResponseType* object)\n{\n  this->itk::ProcessObject::SetNthInput(0, const_cast<SpectralResponseType*>(object));\n}\n\nSailModel::SpectralResponseType* SailModel::GetReflectance()\n{\n  if (this->GetNumberOfInputs() != 2)\n  {\n    // exit\n    return nullptr;\n  }\n  return static_cast<SpectralResponseType*>(this->itk::ProcessObject::GetInput(0));\n}\n\n/** Set/Get input transmittance */\nvoid SailModel::SetTransmittance(const SpectralResponseType* object)\n{\n  this->itk::ProcessObject::SetNthInput(1, const_cast<SpectralResponseType*>(object));\n}\n\nSailModel::SpectralResponseType* SailModel::GetTransmittance()\n{\n  if (this->GetNumberOfInputs() != 2)\n  {\n    // exit\n    return nullptr;\n  }\n  return static_cast<SpectralResponseType*>(this->itk::ProcessObject::GetInput(1));\n}\n\n/** Make output */\nSailModel::DataObjectPointer SailModel::MakeOutput(DataObjectPointerArraySizeType)\n{\n  return static_cast<itk::DataObject*>(SpectralResponseType::New().GetPointer());\n}\n\n/** Get output viewing reflectance */\nSailModel::SpectralResponseType* SailModel::GetViewingReflectance()\n{\n  if (this->GetNumberOfOutputs() < 4)\n  {\n    // exit\n    return nullptr;\n  }\n  return static_cast<SpectralResponseType*>(this->itk::ProcessObject::GetOutput(0));\n}\n\n/** Get output hemispherical reflectance */\nSailModel::SpectralResponseType* SailModel::GetHemisphericalReflectance()\n{\n  if (this->GetNumberOfOutputs() < 4)\n  {\n    // exit\n    return nullptr;\n  }\n  return static_cast<SpectralResponseType*>(this->itk::ProcessObject::GetOutput(1));\n}\n\n/** Get output viewing absorptance */\nSailModel::SpectralResponseType* SailModel::GetViewingAbsorptance()\n{\n  if (this->GetNumberOfOutputs() < 4)\n  {\n    // exit\n    return nullptr;\n  }\n  return static_cast<SpectralResponseType*>(this->itk::ProcessObject::GetOutput(2));\n}\n\n/** Get output hemispherical absorptance */\nSailModel::SpectralResponseType* SailModel::GetHemisphericalAbsorptance()\n{\n  if (this->GetNumberOfOutputs() < 4)\n  {\n    // exit\n    return nullptr;\n  }\n  return static_cast<SpectralResponseType*>(this->itk::ProcessObject::GetOutput(3));\n}\n\n\n/** Set Parameters */\nvoid SailModel::SetInput(const ParametersType& params)\n{\n\n  if (params.Size() != 8)\n    itkExceptionMacro(<< \"Must have 8 parameters in that order : LAI, Angl, PSoil, Skyl, HSpot, TTS, TTO, PSI\");\n  this->SetParameters(params);\n  m_LAI   = params[0];\n  m_Angl  = params[1];\n  m_PSoil = params[2];\n  m_Skyl  = params[3];\n  m_HSpot = params[4];\n  m_TTS   = params[5];\n  m_TTO   = params[6];\n  m_PSI   = params[7];\n}\n\n/** Get Parameters */\nconst SailModel::ParametersType SailModel::GetInput()\n{\n  ParametersType parameters = this->GetParameters();\n  if (parameters.Size() != 8)\n  {\n    parameters[0] = m_LAI;\n    parameters[1] = m_Angl;\n    parameters[2] = m_PSoil;\n    parameters[3] = m_Skyl;\n    parameters[4] = m_HSpot;\n    parameters[5] = m_TTS;\n    parameters[6] = m_TTO;\n    parameters[7] = m_PSI;\n    this->SetParameters(parameters);\n  }\n  return this->GetParameters();\n}\n\n\n/** Generate data */\nvoid SailModel::GenerateData()\n{\n\n  SpectralResponseType::Pointer inRefl   = this->GetReflectance();\n  SpectralResponseType::Pointer inTrans  = this->GetTransmittance();\n  SpectralResponseType::Pointer outVRefl = this->GetViewingReflectance();\n  SpectralResponseType::Pointer outHRefl = this->GetHemisphericalReflectance();\n  SpectralResponseType::Pointer outVAbs  = this->GetViewingAbsorptance();\n  SpectralResponseType::Pointer outHAbs  = this->GetHemisphericalAbsorptance();\n\n  // LEAF ANGLE DISTRIBUTION\n  double     rd = CONST_PI / 180;\n  VectorType lidf;\n  this->Calc_LIDF(m_Angl, lidf);\n\n  double cts, cto, ctscto, tants, tanto, cospsi, dso;\n  cts    = std::cos(rd * m_TTS);\n  cto    = std::cos(rd * m_TTO);\n  ctscto = cts * cto;\n  tants  = std::tan(rd * m_TTS);\n  tanto  = std::tan(rd * m_TTO);\n  cospsi = std::cos(rd * m_PSI);\n  dso    = std::sqrt(tants * tants + tanto * tanto - 2. * tants * tanto * cospsi);\n\n  // angular distance, compensation of shadow length\n  // Calculate geometric factors associated with extinction and scattering\n  // Initialise sums\n  double     ks  = 0;\n  double     ko  = 0;\n  double     bf  = 0;\n  double     sob = 0;\n  double     sof = 0;\n  double     ttl, ctl, ksli, koli, sobli, sofli, bfli;\n  double     chi_s, chi_o, frho, ftau;\n  VectorType result(4);\n\n  // Weighted sums over LIDF\n  for (unsigned int i = 0; i < lidf.size(); ++i)\n  {\n    ttl = 2.5 + 5 * i; // leaf inclination discrete values\n    ctl = std::cos(rd * ttl);\n    // SAIL volume scattering phase function gives interception and portions to be\n    // multiplied by rho and tau\n\n    this->Volscatt(m_TTS, m_TTO, m_PSI, ttl, result);\n    chi_s = result[0];\n    chi_o = result[1];\n    frho  = result[2];\n    ftau  = result[3];\n\n    //********************************************************************************\n    //*                   SUITS SYSTEM COEFFICIENTS\n    //*\n    //*       ks  : Extinction coefficient for direct solar flux\n    //*       ko  : Extinction coefficient for direct observed flux\n    //*       att : Attenuation coefficient for diffuse flux\n    //*       sigb : Backscattering coefficient of the diffuse downward flux\n    //*       sigf : Forwardscattering coefficient of the diffuse upward flux\n    //*       sf  : Scattering coefficient of the direct solar flux for downward diffuse flux\n    //*       sb  : Scattering coefficient of the direct solar flux for upward diffuse flux\n    //*       vf   : Scattering coefficient of upward diffuse flux in the observed direction\n    //*       vb   : Scattering coefficient of downward diffuse flux in the observed direction\n    //*       w   : Bidirectional scattering coefficient\n    //********************************************************************************\n\n    // Extinction coefficients\n    ksli = chi_s / cts;\n    koli = chi_o / cto;\n\n    // Area scattering coefficient fractions\n    sobli = frho * CONST_PI / ctscto;\n    sofli = ftau * CONST_PI / ctscto;\n    bfli  = ctl * ctl;\n    ks    = ks + ksli * lidf[i];\n    ko    = ko + koli * lidf[i];\n    bf    = bf + bfli * lidf[i];\n    sob   = sob + sobli * lidf[i];\n    sof   = sof + sofli * lidf[i];\n  }\n\n  // Geometric factors to be used later with rho and tau\n  double sdb, sdf, dob, dof, ddb, ddf;\n  sdb = 0.5 * (ks + bf);\n  sdf = 0.5 * (ks - bf);\n  dob = 0.5 * (ko + bf);\n  dof = 0.5 * (ko - bf);\n  ddb = 0.5 * (1. + bf);\n  ddf = 0.5 * (1. - bf);\n\n  double lambda, Es, Ed, Rsoil1, Rsoil2, rsoil0, rho, tau, PARdiro, PARdifo;\n  double sigb, sigf, att, m2, m, sb, sf, vb, vf, w;\n  double tss, too, tsstoo, rdd, tdd, rsd, tsd, rdo, tdo, rsos, rsod;\n  double rddt, rsdt, rdot, rsodt, rsost, rsot, dn;\n  double e1, e2, rinf, rinf2, re, denom, J1ks, J2ks, J1ko, J2ko;\n  double Ps, Qs, Pv, Qv, z, g1, g2, Tv1, Tv2, T1, T2, T3;\n  double alf, sumint, fhot, x1, y1, f1, fint, x2, y2, f2;\n  double resh, resv, absh, absv;\n\n  int nbdata = sizeof(DataSpecP5B) / sizeof(DataSpec);\n  for (int i = 0; i < nbdata; ++i)\n  {\n    lambda = DataSpecP5B[i].lambda;\n    Es     = DataSpecP5B[i].directLight;       // 8\n    Ed     = DataSpecP5B[i].diffuseLight;      // 9\n    Rsoil1 = DataSpecP5B[i].drySoil;           // 10\n    Rsoil2 = DataSpecP5B[i].wetSoil;           // 11\n    rho    = inRefl->GetResponse()[i].second;  // rho = LRT[1][i];\n    tau    = inTrans->GetResponse()[i].second; // tau = LRT[2][i];\n\n    // direct/diffuse light\n    // Es = direct\n    // Ed = diffuse\n    PARdiro = (1 - m_Skyl / 100.) * Es;\n    PARdifo = (m_Skyl / 100.) * Ed;\n\n    // Soil Reflectance Properties\n    // rsoil1 = dry soil\n    // rsoil2 = wet soil\n    if (!m_UseSoilFile)\n    {\n      rsoil0 = m_PSoil * Rsoil1 + (1 - m_PSoil) * Rsoil2;\n    }\n    else\n    {\n      rsoil0 = m_SoilDataBase->GetReflectance(m_SoilIndex, lambda) * m_PSoil;\n    }\n\n    // Here rho and tau come in\n    sigb = ddb * rho + ddf * tau;\n    sigf = ddf * rho + ddb * tau;\n    att  = 1. - sigf;\n    m2   = (att + sigb) * (att - sigb);\n    if (m2 <= 0)\n      m2 = 0;\n    m    = std::sqrt(m2);\n\n\n    sb = sdb * rho + sdf * tau;\n    sf = sdf * rho + sdb * tau;\n    vb = dob * rho + dof * tau;\n    vf = dof * rho + dob * tau;\n    w  = sob * rho + sof * tau;\n\n    // Here the LAI comes in\n    // Outputs for the case LAI = 0\n    if (m_LAI < 0)\n    {\n      // tss = 1;\n      too    = 1;\n      tsstoo = 1;\n      rdd    = 0;\n      tdd    = 1;\n      rsd    = 0;\n      tsd    = 0;\n      rdo    = 0;\n      tdo    = 0;\n      // rso = 0;\n      rsos = 0;\n      rsod = 0;\n\n      rddt  = rsoil0;\n      rsdt  = rsoil0;\n      rdot  = rsoil0;\n      rsodt = 0;\n      rsost = rsoil0;\n      // rsot = rsoil0;\n    }\n\n    // Other cases (LAI > 0)\n    e1    = exp(-m * m_LAI);\n    e2    = e1 * e1;\n    rinf  = (att - m) / sigb;\n    rinf2 = rinf * rinf;\n    re    = rinf * e1;\n    denom = 1. - rinf2 * e2;\n\n    J1ks = Jfunc1(ks, m, m_LAI);\n    J2ks = Jfunc2(ks, m, m_LAI);\n    J1ko = Jfunc1(ko, m, m_LAI);\n    J2ko = Jfunc2(ko, m, m_LAI);\n\n    Ps = (sf + sb * rinf) * J1ks;\n    Qs = (sf * rinf + sb) * J2ks;\n    Pv = (vf + vb * rinf) * J1ko;\n    Qv = (vf * rinf + vb) * J2ko;\n\n    rdd = rinf * (1. - e2) / denom;\n    tdd = (1. - rinf2) * e1 / denom;\n    tsd = (Ps - re * Qs) / denom;\n    rsd = (Qs - re * Ps) / denom;\n    tdo = (Pv - re * Qv) / denom;\n    rdo = (Qv - re * Pv) / denom;\n\n    tss = exp(-ks * m_LAI);\n    too = exp(-ko * m_LAI);\n    z   = Jfunc3(ks, ko, m_LAI);\n    g1  = (z - J1ks * too) / (ko + m);\n    g2  = (z - J1ko * tss) / (ks + m);\n\n    Tv1 = (vf * rinf + vb) * g1;\n    Tv2 = (vf + vb * rinf) * g2;\n    T1  = Tv1 * (sf + sb * rinf);\n    T2  = Tv2 * (sf * rinf + sb);\n    T3  = (rdo * Qs + tdo * Ps) * rinf;\n\n    // Multiple scattering contribution to bidirectional canopy reflectance\n    rsod = (T1 + T2 - T3) / (1. - rinf2);\n\n    // Treatment of the hotspot-effect\n    alf = 1e6;\n    // Apply correction 2/(K+k) suggested by F.-M. Bron\n    if (m_HSpot > 0)\n      alf = (dso / m_HSpot) * 2. / (ks + ko);\n    if (alf > 200)\n      alf = 200;\n    if (alf == 0)\n    {\n      // The pure hotspot - no shadow\n      tsstoo = tss;\n      sumint = (1 - tss) / (ks * m_LAI);\n    }\n    else\n    {\n      // Outside the hotspot\n      fhot = m_LAI * std::sqrt(ko * ks);\n      // Integrate by exponential Simpson method in 20 steps\n      // the steps are arranged according to equal partitioning\n      // of the slope of the joint probability function\n      x1     = 0;\n      y1     = 0;\n      f1     = 1;\n      fint   = (1. - exp(-alf)) * 0.05;\n      sumint = 0;\n\n      for (unsigned int j = 1; j <= 20; ++j)\n      {\n        if (j < 20)\n          x2 = -std::log(1. - j * fint) / alf;\n        else\n          x2   = 1;\n        y2     = -(ko + ks) * m_LAI * x2 + fhot * (1. - exp(-alf * x2)) / alf;\n        f2     = exp(y2);\n        sumint = sumint + (f2 - f1) * (x2 - x1) / (y2 - y1);\n        x1     = x2;\n        y1     = y2;\n        f1     = f2;\n      }\n      tsstoo = f1;\n    }\n\n    // Bidirectional reflectance\n    // Single scattering contribution\n    rsos = w * m_LAI * sumint;\n    // Total canopy contribution\n    // rso=rsos+rsod;\n    // Interaction with the soil\n    dn = 1. - rsoil0 * rdd;\n\n    rddt = rdd + tdd * rsoil0 * tdd / dn;\n    rsdt = rsd + (tsd + tss) * rsoil0 * tdd / dn;\n    rdot = rdo + tdd * rsoil0 * (tdo + too) / dn;\n\n    rsodt = rsod + ((tss + tsd) * tdo + (tsd + tss * rsoil0 * rdd) * too) * rsoil0 / dn;\n    rsost = rsos + tsstoo * rsoil0;\n    rsot  = rsost + rsodt;\n\n    resh = (rddt * PARdifo + rsdt * PARdiro) / (PARdiro + PARdifo);\n    resv = (rdot * PARdifo + rsot * PARdiro) / (PARdiro + PARdifo);\n\n    absh = (1 - rddt - (1 - rsoil0) * (tdd + (tdd * rdd * rsoil0) / dn));\n    absv = (1 - rsdt - (1 - rsoil0) * (tss + (tss * rsoil0 * rdd + tsd) / dn));\n\n    SpectralResponseType::PairType response;\n    response.first  = lambda / 1000.0;\n    response.second = resh;\n    outHRefl->GetResponse().push_back(response);\n    response.second = resv;\n    outVRefl->GetResponse().push_back(response);\n    response.second = absh;\n    outHAbs->GetResponse().push_back(response);\n    response.second = absv;\n    outVAbs->GetResponse().push_back(response);\n  }\n  m_FCoverView = 1 - too;\n}\n\n\nvoid SailModel::Calc_LIDF(const double a, VectorType& lidf) const\n{\n  int        ala = a;\n  VectorType freq;\n  Campbell(ala, freq);\n  lidf = freq;\n}\n\n\nvoid SailModel::Campbell(const double ala, VectorType& freq) const\n{\n  unsigned int n      = 18;\n  double       excent = exp(-1.6184e-5 * std::pow(ala, 3) + 2.1145e-3 * ala * ala - 1.2390e-1 * ala + 3.2491);\n  double       sum    = 0;\n  unsigned int tx2, tx1;\n  double       tl1, tl2, x1, x2, v, alpha, alpha2, x12, x22, alpx1, alpx2, dum, almx1, almx2;\n  VectorType   temp;\n\n  for (unsigned int i = 0; i < n; ++i)\n  {\n    tx2 = 5 * i;\n    tx1 = 5 * (i + 1);\n    tl1 = tx1 * CONST_PI / 180;\n    tl2 = tx2 * CONST_PI / 180;\n\n\n    x1 = excent / sqrt(1. + excent * excent * std::tan(tl1) * std::tan(tl1));\n    x2 = excent / sqrt(1. + excent * excent * std::tan(tl2) * std::tan(tl2));\n    if (excent == 1)\n    {\n      v = std::abs(cos(tl1) - cos(tl2));\n      temp.push_back(v);\n      sum = sum + v;\n    }\n    else\n    {\n      alpha  = excent / std::sqrt(std::abs(1. - excent * excent));\n      alpha2 = alpha * alpha;\n      x12    = x1 * x1;\n      x22    = x2 * x2;\n      if (excent > 1)\n      {\n        alpx1 = std::sqrt(alpha2 + x12);\n        alpx2 = std::sqrt(alpha2 + x22);\n        dum   = x1 * alpx1 + alpha2 * log(x1 + alpx1);\n        v     = std::abs(dum - (x2 * alpx2 + alpha2 * log(x2 + alpx2)));\n        temp.push_back(v);\n        sum = sum + v;\n      }\n      else\n      {\n        almx1 = sqrt(alpha2 - x12);\n        almx2 = sqrt(alpha2 - x22);\n        dum   = x1 * almx1 + alpha2 * asin(x1 / alpha);\n        v     = std::abs(dum - (x2 * almx2 + alpha2 * asin(x2 / alpha)));\n        temp.push_back(v);\n        sum = sum + v;\n      }\n    }\n  }\n\n  for (unsigned int i = 0; i < n; ++i)\n  {\n    freq.push_back(temp[i] / sum);\n  }\n}\n\n\nvoid SailModel::Volscatt(const double tts, const double tto, const double psi, const double ttl, VectorType& result) const\n{\n\n  double rd     = CONST_PI / 180;\n  double costs  = std::cos(rd * tts);\n  double costo  = std::cos(rd * tto);\n  double sints  = std::sin(rd * tts);\n  double sinto  = std::sin(rd * tto);\n  double cospsi = std::cos(rd * psi);\n  double psir   = rd * psi;\n  double costl  = std::cos(rd * ttl);\n  double sintl  = std::sin(rd * ttl);\n  double cs     = costl * costs;\n  double co     = costl * costo;\n  double ss     = sintl * sints;\n  double so     = sintl * sinto;\n\n  // ..............................................................................\n  //     betas -bts- and betao -bto- computation\n  //     Transition angles (beta) for solar (betas) and view (betao) directions\n  //     if thetav+thetal>pi/2, bottom side of the leaves is observed for leaf azimut\n  //     interval betao+phi<leaf azimut<2pi-betao+phi.\n  //     if thetav+thetal<pi/2, top side of the leaves is always observed, betao=pi\n  //     same consideration for solar direction to compute betas\n  // ..............................................................................\n  double cosbts, cosbto, bts, ds, chi_s, bto, doo, chi_o;\n  double btran1, btran2, bt1, bt2, bt3, t1, t2, denom, frho, ftau;\n\n  cosbts = 5;\n  if (std::abs(ss) > 1e-6)\n    cosbts = -cs / ss;\n\n  cosbto = 5;\n  if (std::abs(so) > 1e-6)\n    cosbto = -co / so;\n\n\n  if (std::abs(cosbts) < 1)\n  {\n    bts = std::acos(cosbts);\n    ds  = ss;\n  }\n  else\n  {\n    bts = CONST_PI;\n    ds  = cs;\n  }\n\n  chi_s = 2. / CONST_PI * ((bts - CONST_PI * 0.5) * cs + std::sin(bts) * ss);\n\n  if (std::abs(cosbto) < 1)\n  {\n    bto = std::acos(cosbto);\n    doo = so;\n  }\n  else if (tto < 90)\n  {\n    bto = CONST_PI;\n    doo = co;\n  }\n  else\n  {\n    bto = 0;\n    doo = -co;\n  }\n  chi_o = 2. / CONST_PI * ((bto - CONST_PI * 0.5) * co + std::sin(bto) * so);\n\n  // ..............................................................................\n  //   Computation of auxiliary azimut angles bt1, bt2, bt3 used\n  //   for the computation of the bidirectional scattering coefficient w\n  // .............................................................................\n\n  btran1 = std::abs(bts - bto);\n  btran2 = CONST_PI - std::abs(bts + bto - CONST_PI);\n\n  if (psir <= btran1)\n  {\n    bt1 = psir;\n    bt2 = btran1;\n    bt3 = btran2;\n  }\n  else\n  {\n    bt1 = btran1;\n    if (psir <= btran2)\n    {\n      bt2 = psir;\n      bt3 = btran2;\n    }\n    else\n    {\n      bt2 = btran2;\n      bt3 = psir;\n    }\n  }\n\n  t1 = 2. * cs * co + ss * so * cospsi;\n  t2 = 0;\n  if (bt2 > 0)\n    t2  = sin(bt2) * (2. * ds * doo + ss * so * cos(bt1) * cos(bt3));\n  denom = 2. * CONST_PI * CONST_PI;\n  frho  = ((CONST_PI - bt2) * t1 + t2) / denom;\n  ftau  = (-bt2 * t1 + t2) / denom;\n\n  if (frho < 0)\n    frho = 0;\n  if (ftau < 0)\n    ftau = 0;\n\n  result[0] = chi_s;\n  result[1] = chi_o;\n  result[2] = frho;\n  result[3] = ftau;\n}\n\n\ndouble SailModel::Jfunc1(const double k, const double l, const double t) const\n{\n  // J1 function with avoidance of singularity problem\n  double v;\n  double del = (k - l) * t;\n  if (std::abs(del) > 1e-3)\n  {\n    v = (exp(-l * t) - exp(-k * t)) / (k - l);\n    return v;\n  }\n  else\n  {\n    v = 0.5 * t * (exp(-k * t) + exp(-l * t)) * (1. - del * del / 12.);\n    return v;\n  }\n}\n\n\ndouble SailModel::Jfunc2(const double k, const double l, const double t) const\n{\n  double v;\n  v = (1. - exp(-(k + l) * t)) / (k + l);\n  return v;\n}\n\n\ndouble SailModel::Jfunc3(const double k, const double l, const double t) const\n{\n  double v;\n  v = (1. - exp(-(k + l) * t)) / (k + l);\n  return v;\n}\n\n\nvoid SailModel::PrintSelf(std::ostream& os, itk::Indent indent) const\n{\n  Superclass::PrintSelf(os, indent);\n}\n\nvoid SailModel::UseExternalSoilDB(std::shared_ptr<SoilDataBase> SoilDB, size_t SoilIndex)\n{\n  m_UseSoilFile  = true;\n  m_SoilIndex    = SoilIndex;\n  m_SoilDataBase = SoilDB;\n}\n} // end namespace otb\n", "meta": {"hexsha": "141128f80e8c0af5bc483ab47a40bab62ca0f419", "size": 19884, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Modules/Radiometry/Simulation/src/otbSailModel.cxx", "max_stars_repo_name": "qingswu/otb", "max_stars_repo_head_hexsha": "ed903b6a5e51a27a3d04786e4ad1637cf6b2772e", "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/Radiometry/Simulation/src/otbSailModel.cxx", "max_issues_repo_name": "qingswu/otb", "max_issues_repo_head_hexsha": "ed903b6a5e51a27a3d04786e4ad1637cf6b2772e", "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/Radiometry/Simulation/src/otbSailModel.cxx", "max_forks_repo_name": "qingswu/otb", "max_forks_repo_head_hexsha": "ed903b6a5e51a27a3d04786e4ad1637cf6b2772e", "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.5279770445, "max_line_length": 150, "alphanum_fraction": 0.5738784953, "num_tokens": 6758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2734034621938684}}
{"text": "/*! @file stats.cc\n *  @brief Statistical measures calculation.\n *  @author Markovtsev Vadim <v.markovtsev@samsung.com>\n *  @version 1.0\n *\n *  @section Notes\n *  This code partially conforms to <a href=\"http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml\">Google C++ Style Guide</a>.\n *\n *  @section Copyright\n *  Copyright © 2013 Samsung R&D Institute Russia\n *\n *  @section License\n *  Licensed to the Apache Software Foundation (ASF) under one\n *  or more contributor license agreements.  See the NOTICE file\n *  distributed with this work for additional information\n *  regarding copyright ownership.  The ASF licenses this file\n *  to you under the Apache License, Version 2.0 (the\n *  \"License\"); you may not use this file except in compliance\n *  with the 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,\n *  software distributed under the License is distributed on an\n *  \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n *  KIND, either express or implied.  See the License for the\n *  specific language governing permissions and limitations\n *  under the License.\n */\n\n#include \"src/transforms/stats.h\"\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wold-style-cast\"\n#include <boost/regex.hpp>\n#pragma GCC diagnostic pop\n#include <cmath>\n#include <simd/instruction_set.h>\n\nnamespace sound_feature_extraction {\nnamespace transforms {\n\nstd::set<StatsType> Parse(const std::string& value,\n                          identity<std::set<StatsType>>) {\n  static const std::unordered_map<std::string, StatsType> map {\n    { internal::kStatsTypeAverageStr, kStatsTypeAverage },\n    { internal::kStatsTypeStdDeviationStr, kStatsTypeStdDeviation },\n    { internal::kStatsTypeSkewnessStr, kStatsTypeSkewness },\n    { internal::kStatsTypeKurtosisStr, kStatsTypeKurtosis }\n  };\n\n  static const boost::regex all_regex(\"^\\\\s*(\\\\w+\\\\s*(\\\\s|$))+\");\n  boost::smatch match;\n  if (!boost::regex_match(value, match, all_regex)) {\n    throw InvalidParameterValueException();\n  }\n\n  if (value == internal::kStatsTypeAllStr) {\n    return { kStatsTypeAverage, kStatsTypeStdDeviation, kStatsTypeSkewness,\n             kStatsTypeKurtosis };\n  }\n  std::set<StatsType> ret;\n  std::transform(boost::sregex_token_iterator(value.begin(), value.end(),\n                                            boost::regex(\"\\\\s*(\\\\w+)\\\\s*\"),\n                                            1),\n                 boost::sregex_token_iterator(),\n                 std::inserter(ret, ret.begin()),\n                 [](const std::string& subval) {\n    auto stit = map.find(subval);\n    if (stit == map.end()) {\n      throw InvalidParameterValueException();\n    }\n    return stit->second;\n  });\n\n  return ret;\n}\n\nconst std::unordered_map<int, Stats::CalculateFunc> Stats::kStatsFuncs {\n  { kStatsTypeAverage, Stats::CalculateAverage },\n  { kStatsTypeStdDeviation, Stats::CalculateStdDeviation },\n  { kStatsTypeSkewness, Stats::CalculateSkewness },\n  { kStatsTypeKurtosis, Stats::CalculateKurtosis }\n};\n\nStats::Stats()\n    : types_(kDefaultStatsTypes()),\n      interval_(kDefaultInterval),\n      overlap_(kDefaultOverlap) {\n}\n\nALWAYS_VALID_TP(Stats, types)\n\nbool Stats::validate_interval(const int& value) noexcept {\n  return value >= 2;\n}\n\nbool Stats::validate_overlap(const int& value) noexcept {\n  return value >= 0;\n}\n\nvoid Stats::Initialize() const {\n  if (interval_ > 0 && overlap_ >= interval_) {\n    throw InvalidParameterValueException(\"overlap\", std::to_string(overlap_),\n                                         HostName());\n  }\n  if (input_format_->Size() < static_cast<size_t>(interval_)) {\n    throw UnableToCalculateStatsException(input_format_->Size(), interval_);\n  }\n}\n\nsize_t Stats::OnInputFormatChanged(size_t buffersCount) {\n  if (interval_ != 0) {\n    int step = interval_ - overlap_;\n    auto ratio = (input_format_->Size() - interval_) / step + 1;\n    if (((input_format_->Size() - interval_) % step) == 0) {\n      output_format_->SetSize(ratio * types_.size());\n    } else {\n      output_format_->SetSize((ratio + 1) * types_.size());\n    }\n  } else {\n    output_format_->SetSize(types_.size());\n  }\n  return buffersCount;\n}\n\nvoid Stats::Do(const float* in, float* out) const noexcept {\n  float rawMoments[kStatsTypeCount];\n  if (interval_ == 0) {\n    CalculateRawMoments(true, in, 0, input_format_->Size(), rawMoments);\n    Calculate(rawMoments, out);\n  } else {\n    size_t i;\n    size_t step = interval_ - overlap_;\n    for (i = 0; i < input_format_->Size() - interval_ + 1; i += step) {\n      CalculateRawMoments(true, in, i, interval_, rawMoments);\n      Calculate(rawMoments, out + i / step * types_.size());\n    }\n    if ((input_format_->Size() - interval_) % step != 0) {\n      int index = input_format_->Size() - interval_;\n      CalculateRawMoments(true, in, index, interval_, rawMoments);\n      Calculate(rawMoments, out + i / step * types_.size());\n    }\n  }\n}\n\nvoid Stats::Calculate(const float* rawMoments, float* out) const noexcept {\n  for (auto stat : types_) {\n    int sind = 0;\n    int istat = stat;\n    while (istat >>= 1) {\n      sind++;\n    }\n    out[sind] = kStatsFuncs.find(stat)->second(rawMoments);\n  }\n}\n\nvoid Stats::CalculateRawMoments(bool simd, const float* in, int startIndex,\n                                int length, float* rawMoments) noexcept {\n  float avg1 = 0, avg2 = 0, avg3 = 0, avg4 = 0;\n  auto end_index = startIndex + length;\n  if (simd) {\n#ifdef __AVX__\n    __m256 avg1vec = _mm256_setzero_ps();\n    __m256 avg2vec = _mm256_setzero_ps();\n    __m256 avg3vec = _mm256_setzero_ps();\n    __m256 avg4vec = _mm256_setzero_ps();\n    for (int i = startIndex; i < end_index - 7; i+=8) {\n      __m256 val = _mm256_loadu_ps(in + i);\n      avg1vec = _mm256_add_ps(avg1vec, val);\n      __m256 val2 = _mm256_mul_ps(val, val);\n      avg2vec = _mm256_add_ps(avg2vec, val2);\n      val = _mm256_mul_ps(val2, val);\n      avg3vec = _mm256_add_ps(avg3vec, val);\n      val2 = _mm256_mul_ps(val2, val2);\n      avg4vec = _mm256_add_ps(avg4vec, val2);\n    }\n    avg1vec = _mm256_hadd_ps(avg1vec, avg1vec);\n    avg1vec = _mm256_hadd_ps(avg1vec, avg1vec);\n    avg1 += _mm256_get_ps(avg1vec, 0);\n    avg1 += _mm256_get_ps(avg1vec, 4);\n    avg2vec = _mm256_hadd_ps(avg2vec, avg2vec);\n    avg2vec = _mm256_hadd_ps(avg2vec, avg2vec);\n    avg2 += _mm256_get_ps(avg2vec, 0);\n    avg2 += _mm256_get_ps(avg2vec, 4);\n    avg3vec = _mm256_hadd_ps(avg3vec, avg3vec);\n    avg3vec = _mm256_hadd_ps(avg3vec, avg3vec);\n    avg3 += _mm256_get_ps(avg3vec, 0);\n    avg3 += _mm256_get_ps(avg3vec, 4);\n    avg4vec = _mm256_hadd_ps(avg4vec, avg4vec);\n    avg4vec = _mm256_hadd_ps(avg4vec, avg4vec);\n    avg4 += _mm256_get_ps(avg4vec, 0);\n    avg4 += _mm256_get_ps(avg4vec, 4);\n    for (int i = ((end_index) & ~0x7); i < end_index; i++) {\n      float v = in[i];\n      avg1 += v;\n      float v2 = v * v;\n      avg2 += v2;\n      v *= v2;\n      avg3 += v;\n      v2 *= v2;\n      avg4 += v2;\n    }\n  } else {\n#elif defined(__ARM_NEON__)\n    float32x4_t avg1vec = vdupq_n_f32(0);\n    float32x4_t avg2vec = vdupq_n_f32(0);\n    float32x4_t avg3vec = vdupq_n_f32(0);\n    float32x4_t avg4vec = vdupq_n_f32(0);\n    for (int i = startIndex; i < end_index - 3; i+=4) {\n      float32x4_t val = vld1q_f32(in + i);\n      avg1vec = vaddq_f32(avg1vec, val);\n      float32x4_t val2 = vmulq_f32(val, val);\n      avg2vec = vaddq_f32(avg2vec, val2);\n      val = vmulq_f32(val2, val);\n      avg3vec = vaddq_f32(avg3vec, val);\n      val2 = vmulq_f32(val2, val2);\n      avg4vec = vaddq_f32(avg4vec, val2);\n    }\n    avg1 += vgetq_lane_f32(avg1vec, 0);\n    avg1 += vgetq_lane_f32(avg1vec, 1);\n    avg1 += vgetq_lane_f32(avg1vec, 2);\n    avg1 += vgetq_lane_f32(avg1vec, 3);\n    avg2 += vgetq_lane_f32(avg2vec, 0);\n    avg2 += vgetq_lane_f32(avg2vec, 1);\n    avg2 += vgetq_lane_f32(avg2vec, 2);\n    avg2 += vgetq_lane_f32(avg2vec, 3);\n    avg3 += vgetq_lane_f32(avg3vec, 0);\n    avg3 += vgetq_lane_f32(avg3vec, 1);\n    avg3 += vgetq_lane_f32(avg3vec, 2);\n    avg3 += vgetq_lane_f32(avg3vec, 3);\n    avg4 += vgetq_lane_f32(avg4vec, 0);\n    avg4 += vgetq_lane_f32(avg4vec, 1);\n    avg4 += vgetq_lane_f32(avg4vec, 2);\n    avg4 += vgetq_lane_f32(avg4vec, 3);\n    for (int i = ((end_index) & ~0x3); i < end_index; i++) {\n      float v = in[i];\n      avg1 += v;\n      float v2 = v * v;\n      avg2 += v2;\n      v *= v2;\n      avg3 += v;\n      v2 *= v2;\n      avg4 += v2;\n    }\n  } else {\n#else\n  } {\n#endif\n    for (int i = startIndex; i < end_index; i++) {\n      float v = in[i];\n      avg1 += v;\n      float v2 = v * v;\n      avg2 += v2;\n      v *= v2;\n      avg3 += v;\n      v2 *= v2;\n      avg4 += v2;\n    }\n  }\n  avg1 /= length;\n  avg2 /= length;\n  avg3 /= length;\n  avg4 /= length;\n  rawMoments[0] = avg1;\n  rawMoments[1] = avg2;\n  rawMoments[2] = avg3;\n  rawMoments[3] = avg4;\n}\n\nfloat Stats::CalculateAverage(const float* rawMoments) noexcept {\n  return rawMoments[0];\n}\n\nfloat Stats::CalculateStdDeviation(const float* rawMoments) noexcept {\n  auto value = rawMoments[1] - rawMoments[0] * rawMoments[0];\n  if (value < 0) {\n    return 0;\n  }\n  value = sqrtf(value);\n  return value;\n}\n\nfloat Stats::CalculateSkewness(const float* rawMoments) noexcept {\n  float avg1 = rawMoments[0];\n  float avg2 = rawMoments[1];\n  float avg3 = rawMoments[2];\n  double u2 = avg2 - avg1 * avg1;\n  if (u2 <= 0) {\n    return 0;\n  }\n  double u3 = avg3 - 3 * avg2 * avg1 + 2 * avg1 * avg1 * avg1;\n  auto value = u3 / (sqrt(u2) * u2);\n  return value;\n}\n\nfloat Stats::CalculateKurtosis(const float* rawMoments) noexcept {\n  float avg1 = rawMoments[0];\n  float avg2 = rawMoments[1];\n  float avg3 = rawMoments[2];\n  float avg4 = rawMoments[3];\n  double u2 = avg2 - avg1 * avg1;\n  if (u2 == 0) {\n    return -2.f;\n  }\n  double u4 = avg4 - 4 * avg3 * avg1 + 6 * avg2 * avg1 * avg1\n      - 3 * avg1 * avg1 * avg1 * avg1;\n  auto value = u4 / (u2 * u2) - 3;\n  return value;\n}\n\nRTP(Stats, types)\nRTP(Stats, interval)\nRTP(Stats, overlap)\nREGISTER_TRANSFORM(Stats);\n\n}  // namespace transforms\n}  // namespace sound_feature_extraction\n", "meta": {"hexsha": "730f2f6141fa799095feba58cece1c042473d554", "size": 10090, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/transforms/stats.cc", "max_stars_repo_name": "Samsung/veles.sound_feature_extraction-", "max_stars_repo_head_hexsha": "56b7c5d3816d092c72a874ca236e889fe843e6cd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2015-11-10T06:06:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-28T04:54:17.000Z", "max_issues_repo_path": "src/transforms/stats.cc", "max_issues_repo_name": "Samsung/veles.sound_feature_extraction-", "max_issues_repo_head_hexsha": "56b7c5d3816d092c72a874ca236e889fe843e6cd", "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/transforms/stats.cc", "max_forks_repo_name": "Samsung/veles.sound_feature_extraction-", "max_forks_repo_head_hexsha": "56b7c5d3816d092c72a874ca236e889fe843e6cd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2015-08-08T20:28:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T01:03:47.000Z", "avg_line_length": 31.7295597484, "max_line_length": 136, "alphanum_fraction": 0.6373637265, "num_tokens": 3157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.4765796510636759, "lm_q1q2_score": 0.2734034552464824}}
{"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:37:45\n\n#include \"MSSMatMSUSYEFTHiggs_mAmu_two_scale_initial_guesser.hpp\"\n#include \"MSSMatMSUSYEFTHiggs_mAmu_two_scale_model.hpp\"\n#include \"MSSMatMSUSYEFTHiggs_mAmu_standard_model_two_scale_matching.hpp\"\n#include \"standard_model_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\nnamespace flexiblesusy {\n\n#define INPUTPARAMETER(p) model->get_input().p\n#define MODELPARAMETER(p) model->get_##p()\n#define SMPARAMETER(p) eft->get_##p()\n#define PHASE(p) model->get_##p()\n#define LowEnergyConstant(p) Electroweak_constants::p\n#define MODEL model\n\nMSSMatMSUSYEFTHiggs_mAmu_standard_model_initial_guesser<Two_scale>::MSSMatMSUSYEFTHiggs_mAmu_standard_model_initial_guesser(\n   MSSMatMSUSYEFTHiggs_mAmu<Two_scale>* model_,\n   standard_model::StandardModel<Two_scale>* eft_,\n   const softsusy::QedQcd& qedqcd_,\n   const standard_model::Standard_model_low_scale_constraint<Two_scale>& low_constraint_,\n   const MSSMatMSUSYEFTHiggs_mAmu_susy_scale_constraint<Two_scale>& susy_constraint_\n)\n   : Initial_guesser()\n   , model(model_)\n   , eft(eft_)\n   , qedqcd(qedqcd_)\n   , low_constraint(low_constraint_)\n   , susy_constraint(susy_constraint_)\n{\n   if (!model)\n      throw SetupError(\"MSSMatMSUSYEFTHiggs_mAmu_initial_guesser: Error: pointer to model\"\n                       \" MSSMatMSUSYEFTHiggs_mAmu<Two_scale> must not be zero\");\n}\n\nMSSMatMSUSYEFTHiggs_mAmu_standard_model_initial_guesser<Two_scale>::~MSSMatMSUSYEFTHiggs_mAmu_standard_model_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 MSSMatMSUSYEFTHiggs_mAmu_standard_model_initial_guesser<Two_scale>::guess()\n{\n   guess_eft_parameters();\n   guess_model_parameters();\n}\n\n/**\n * Guesses the effective 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) are ignored\n */\nvoid MSSMatMSUSYEFTHiggs_mAmu_standard_model_initial_guesser<Two_scale>::guess_eft_parameters()\n{\n   softsusy::QedQcd leAtMt(qedqcd);\n   const double mtpole = leAtMt.displayPoleMt();\n\n   mu_guess = leAtMt.displayMass(softsusy::mUp);\n   mc_guess = leAtMt.displayMass(softsusy::mCharm);\n   mt_guess = model->get_thresholds() > 0 && model->get_threshold_corrections().mt > 0 ?\n      leAtMt.displayMass(softsusy::mTop) - 30.0 :\n      leAtMt.displayPoleMt();\n   md_guess = leAtMt.displayMass(softsusy::mDown);\n   ms_guess = leAtMt.displayMass(softsusy::mStrange);\n   mb_guess = leAtMt.displayMass(softsusy::mBottom);\n   me_guess = model->get_thresholds() > 0 ?\n      leAtMt.displayMass(softsusy::mElectron) :\n      leAtMt.displayPoleMel();\n   mm_guess = model->get_thresholds() > 0 ?\n      leAtMt.displayMass(softsusy::mMuon) :\n      leAtMt.displayPoleMmuon();\n   mtau_guess = leAtMt.displayMass(softsusy::mTau);\n\n   // guess gauge couplings at mt\n   const auto alpha_sm(leAtMt.guess_alpha_SM5(mtpole));\n\n   eft->set_g1(sqrt(4.0 * Pi * alpha_sm(0)));\n   eft->set_g2(sqrt(4.0 * Pi * alpha_sm(1)));\n   eft->set_g3(sqrt(4.0 * Pi * alpha_sm(2)));\n   eft->set_scale(mtpole);\n\n   eft->set_v(Electroweak_constants::vev);\n   eft->set_Yu(ZEROMATRIX(3,3));\n   eft->set_Yd(ZEROMATRIX(3,3));\n   eft->set_Ye(ZEROMATRIX(3,3));\n\n   eft->set_Yu(0, 0, -Sqrt(2.)* mu_guess/ eft->get_v());\n   eft->set_Yu(1, 1, -Sqrt(2.)* mc_guess/ eft->get_v());\n   eft->set_Yu(2, 2, -Sqrt(2.)* mt_guess/ eft->get_v());\n\n   eft->set_Yd(0, 0, Sqrt(2.)* md_guess/ eft->get_v());\n   eft->set_Yd(1, 1, Sqrt(2.)* ms_guess/ eft->get_v());\n   eft->set_Yd(2, 2, Sqrt(2.)* mb_guess/ eft->get_v());\n\n   eft->set_Ye(0, 0, Sqrt(2.)* me_guess/ eft->get_v());\n   eft->set_Ye(1, 1, Sqrt(2.)* mm_guess/ eft->get_v());\n   eft->set_Ye(2, 2, Sqrt(2.)* mtau_guess/ eft->get_v());\n\n   eft->set_Lambdax(0.12604);\n   eft->solve_ewsb_tree_level();\n\n}\n\nvoid MSSMatMSUSYEFTHiggs_mAmu_standard_model_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 MSSMatMSUSYEFTHiggs_mAmu_standard_model_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\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 MSSMatMSUSYEFTHiggs_mAmu_standard_model_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\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 MSSMatMSUSYEFTHiggs_mAmu_standard_model_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\n}\n\n/**\n * Guesses the full model parameters.  At first it runs to the\n * guess of the SUSY-scale (SUSYScaleFirstGuess) and imposes the\n * SUSY scale initial guess and the\n * SUSY-scale constraint (SUSYScaleInput).  Afterwards, it solves the\n * EWSB conditions at the tree-level.\n * Finally the DR-bar mass spectrum is calculated.\n */\nvoid MSSMatMSUSYEFTHiggs_mAmu_standard_model_initial_guesser<Two_scale>::guess_model_parameters()\n{\n   const double susy_scale_guess = susy_constraint.get_initial_scale_guess();\n   const auto scale_getter = [this] () { return susy_constraint.get_scale(); };\n\n   model->set_scale(susy_scale_guess);\n\n   // apply susy-scale first guess\n   const auto TanBeta = INPUTPARAMETER(TanBeta);\n   const auto M1Input = INPUTPARAMETER(M1Input);\n   const auto M2Input = INPUTPARAMETER(M2Input);\n   const auto M3Input = INPUTPARAMETER(M3Input);\n   const auto mq2Input = INPUTPARAMETER(mq2Input);\n   const auto mu2Input = INPUTPARAMETER(mu2Input);\n   const auto md2Input = INPUTPARAMETER(md2Input);\n   const auto ml2Input = INPUTPARAMETER(ml2Input);\n   const auto me2Input = INPUTPARAMETER(me2Input);\n   const auto MuInput = INPUTPARAMETER(MuInput);\n   const auto mAInput = INPUTPARAMETER(mAInput);\n   const auto AuInput = INPUTPARAMETER(AuInput);\n   const auto AdInput = INPUTPARAMETER(AdInput);\n   const auto AeInput = INPUTPARAMETER(AeInput);\n   const auto Yu = MODELPARAMETER(Yu);\n   const auto Yd = MODELPARAMETER(Yd);\n   const auto Ye = MODELPARAMETER(Ye);\n\n   MODEL->set_vu(Re((TanBeta*LowEnergyConstant(vev))/Sqrt(1 + Sqr(TanBeta))));\n   MODEL->set_vd(Re(LowEnergyConstant(vev)/Sqrt(1 + Sqr(TanBeta))));\n   MODEL->set_MassB(Re(M1Input));\n   MODEL->set_MassWB(Re(M2Input));\n   MODEL->set_MassG(Re(M3Input));\n   MODEL->set_mq2((mq2Input).real());\n   MODEL->set_mu2((mu2Input).real());\n   MODEL->set_md2((md2Input).real());\n   MODEL->set_ml2((ml2Input).real());\n   MODEL->set_me2((me2Input).real());\n   MODEL->set_Mu(Re(MuInput));\n   MODEL->set_BMu(Re(Sqr(mAInput)/(1/TanBeta + TanBeta)));\n   MODEL->set_TYu(((AuInput).cwiseProduct(Yu)).real());\n   MODEL->set_TYd(((AdInput).cwiseProduct(Yd)).real());\n   MODEL->set_TYe(((AeInput).cwiseProduct(Ye)).real());\n\n\n   eft->run_to(susy_scale_guess, running_precision);\n   eft->calculate_DRbar_masses();\n\n   //get gauge and Yukawa couplings from effective theory\n   MSSMatMSUSYEFTHiggs_mAmu_standard_model_matching_up<Two_scale> matching_up;\n   matching_up.set_models(eft, model);\n   matching_up.set_scale(scale_getter);\n   matching_up.match_tree_level();\n\n   model->run_to(susy_scale_guess, running_precision);\n\n   // apply susy-scale constraint\n   susy_constraint.set_model(model);\n   susy_constraint.apply();\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": "33d2cb5e9e224b126a28dcecf2c367458b8c9a0a", "size": 9222, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMatMSUSYEFTHiggs_mAmu/MSSMatMSUSYEFTHiggs_mAmu_two_scale_initial_guesser.cpp", "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/MSSMatMSUSYEFTHiggs_mAmu/MSSMatMSUSYEFTHiggs_mAmu_two_scale_initial_guesser.cpp", "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/MSSMatMSUSYEFTHiggs_mAmu/MSSMatMSUSYEFTHiggs_mAmu_two_scale_initial_guesser.cpp", "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": 35.7441860465, "max_line_length": 126, "alphanum_fraction": 0.7259813489, "num_tokens": 2786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2731168920282664}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"PointwiseFunctions/AnalyticSolutions/GeneralRelativity/Tov.hpp\"\n\n#include <algorithm>\n#include <array>\n#include <boost/numeric/odeint.hpp>  // IWYU pragma: keep\n#include <cmath>\n#include <cstddef>\n#include <functional>\n#include <pup.h>\n#include <vector>\n\n#include \"DataStructures/DataVector.hpp\"\n#include \"Utilities/Gsl.hpp\"\n\n// IWYU pragma: no_forward_declare boost::numeric::odeint::controlled_runge_kutta\n// IWYU pragma: no_forward_declare EquationsOfState::EquationOfState\n// IWYU pragma: no_forward_declare Tensor\n// IWYU pragma: no_include <boost/numeric/odeint/integrate/integrate_adaptive.hpp>\n// IWYU pragma: no_include <boost/numeric/odeint/stepper/controlled_runge_kutta.hpp>\n// IWYU pragma: no_include <boost/numeric/odeint/stepper/dense_output_runge_kutta.hpp>\n// IWYU pragma: no_include <boost/numeric/odeint/stepper/generation/make_dense_output.hpp>\n// IWYU pragma: no_include <boost/numeric/odeint/stepper/runge_kutta_dopri5.hpp>\n\n/// \\cond\nnamespace {\n\nvoid lindblom_rhs(\n    gsl::not_null<std::array<double, 2>*> dvars,\n    const std::array<double, 2>& vars, const double log_enthalpy,\n    const std::unique_ptr<EquationsOfState::EquationOfState<true, 1>>&\n        equation_of_state) noexcept {\n  const double& radius_squared = vars[0];\n  const double& mass_over_radius = vars[1];\n  double& d_radius_squared = (*dvars)[0];\n  double& d_mass_over_radius = (*dvars)[1];\n  const double specific_enthalpy = std::exp(log_enthalpy);\n  const double rest_mass_density =\n      get(equation_of_state->rest_mass_density_from_enthalpy(\n          Scalar<double>{specific_enthalpy}));\n  const double pressure = get(equation_of_state->pressure_from_density(\n      Scalar<double>{rest_mass_density}));\n  const double energy_density =\n      specific_enthalpy * rest_mass_density - pressure;\n\n  // At the center of the star: (u,v) = (0,0)\n  if (UNLIKELY((radius_squared == 0.0) and (mass_over_radius == 0.0))) {\n    d_radius_squared = -3.0 / (2.0 * M_PI * (energy_density + 3.0 * pressure));\n    d_mass_over_radius =\n        -2.0 * energy_density / (energy_density + 3.0 * pressure);\n  } else {\n    const double common_factor =\n        (1.0 - 2.0 * mass_over_radius) /\n        (4.0 * M_PI * radius_squared * pressure + mass_over_radius);\n    d_radius_squared = -2.0 * radius_squared * common_factor;\n    d_mass_over_radius =\n        -(4.0 * M_PI * radius_squared * energy_density - mass_over_radius) *\n        common_factor;\n  }\n}\n\nclass Observer {\n public:\n  void operator()(const std::array<double, 2>& vars,\n                  const double current_log_enthalpy) noexcept {\n    radius.push_back(std::sqrt(vars[0]));\n    mass.push_back(std::sqrt(vars[0]) * vars[1]);\n    log_enthalpy.push_back(current_log_enthalpy);\n  }\n  std::vector<double> radius;\n  std::vector<double> mass;\n  std::vector<double> log_enthalpy;\n};\n\n}  // namespace\n\nnamespace gr {\nnamespace Solutions {\n\nTovSolution::TovSolution(\n    const std::unique_ptr<EquationsOfState::EquationOfState<true, 1>>&\n        equation_of_state,\n    const double central_mass_density, const double final_log_enthalpy,\n    const double absolute_tolerance, const double relative_tolerance) {\n  std::array<double, 2> u_and_v = {{0.0, 0.0}};\n  std::array<double, 2> dudh_and_dvdh{};\n  const double central_log_enthalpy =\n      std::log(get(equation_of_state->specific_enthalpy_from_density(\n          Scalar<double>{central_mass_density})));\n  lindblom_rhs(&dudh_and_dvdh, u_and_v, central_log_enthalpy,\n               equation_of_state);\n  const double initial_step = -std::min(std::abs(1.0 / dudh_and_dvdh[0]),\n                                        std::abs(1.0 / dudh_and_dvdh[1]));\n  using StateDopri5 =\n      boost::numeric::odeint::runge_kutta_dopri5<std::array<double, 2>>;\n  boost::numeric::odeint::dense_output_runge_kutta<\n      boost::numeric::odeint::controlled_runge_kutta<StateDopri5>>\n      dopri5 = make_dense_output(absolute_tolerance, relative_tolerance,\n                                 StateDopri5{});\n  Observer observer{};\n  boost::numeric::odeint::integrate_adaptive(\n      dopri5,\n      [&equation_of_state](const std::array<double, 2>& lindblom_u_and_v,\n                           std::array<double, 2>& lindblom_dudh_and_dvdh,\n                           const double lindblom_enthalpy) noexcept {\n        return lindblom_rhs(&lindblom_dudh_and_dvdh, lindblom_u_and_v,\n                            lindblom_enthalpy, equation_of_state);\n      },\n      u_and_v, central_log_enthalpy, final_log_enthalpy, initial_step,\n      std::ref(observer));\n  outer_radius_ = observer.radius.back();\n  mass_interpolant_ =\n      intrp::BarycentricRational(observer.radius, observer.mass, 5);\n  // log_enthalpy(radius) is almost linear so an interpolant of order 3\n  // maximizes precision\n  log_enthalpy_interpolant_ =\n      intrp::BarycentricRational(observer.radius, observer.log_enthalpy, 3);\n}\n\ndouble TovSolution::outer_radius() const noexcept { return outer_radius_; }\n\ndouble TovSolution::mass(const double r) const noexcept {\n  return mass_interpolant_(r);\n}\n\nScalar<DataVector> TovSolution::mass(const Scalar<DataVector>& radius) const\n    noexcept {\n  DataVector mass(radius.size(), 0.0);\n  for (size_t i = 0; i < radius.size(); i++) {\n    mass[i] = mass_interpolant_(get(radius)[i]);\n  }\n  return Scalar<DataVector>{std::move(mass)};\n}\n\ndouble TovSolution::log_specific_enthalpy(const double r) const noexcept {\n  return log_enthalpy_interpolant_(r);\n}\n\nScalar<DataVector> TovSolution::log_specific_enthalpy(\n    const Scalar<DataVector>& radius) const noexcept {\n  DataVector log_specific_enthalpy(radius.size(), 0.0);\n  for (size_t i = 0; i < radius.size(); i++) {\n    log_specific_enthalpy[i] = log_enthalpy_interpolant_(get(radius)[i]);\n  }\n  return Scalar<DataVector>{std::move(log_specific_enthalpy)};\n}\n\ndouble TovSolution::specific_enthalpy(const double r) const noexcept {\n  return std::exp(log_enthalpy_interpolant_(r));\n}\n\nScalar<DataVector> TovSolution::specific_enthalpy(\n    const Scalar<DataVector>& radius) const noexcept {\n  return Scalar<DataVector>{\n      exp(get(TovSolution::log_specific_enthalpy(radius)))};\n}\n\nvoid TovSolution::pup(PUP::er& p) noexcept {  // NOLINT\n  p | outer_radius_;\n  p | mass_interpolant_;\n  p | log_enthalpy_interpolant_;\n}\n}  // namespace Solutions\n}  // namespace gr\n/// \\endcond\n", "meta": {"hexsha": "c7da0782752274a077e430641ae7dde29160aee0", "size": 6378, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PointwiseFunctions/AnalyticSolutions/GeneralRelativity/Tov.cpp", "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/PointwiseFunctions/AnalyticSolutions/GeneralRelativity/Tov.cpp", "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/PointwiseFunctions/AnalyticSolutions/GeneralRelativity/Tov.cpp", "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": 37.9642857143, "max_line_length": 90, "alphanum_fraction": 0.7115083098, "num_tokens": 1747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2730158446064715}}
{"text": "/* boost random/subtract_with_carry.hpp header file\n *\n * Copyright Jens Maurer 2002\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * See http://www.boost.org for most recent version including documentation.\n *\n * $Id: subtract_with_carry.hpp 72951 2011-07-07 04:57:37Z steven_watanabe $\n *\n * Revision history\n *  2002-03-02  created\n */\n\n#ifndef BOOST_RANDOM_SUBTRACT_WITH_CARRY_HPP\n#define BOOST_RANDOM_SUBTRACT_WITH_CARRY_HPP\n\n#include <boost/config/no_tr1/cmath.hpp>         // std::pow\n#include <iostream>\n#include <algorithm>     // std::equal\n#include <stdexcept>\n#include <boost/config.hpp>\n#include <boost/limits.hpp>\n#include <boost/cstdint.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/integer/static_log2.hpp>\n#include <boost/integer/integer_mask.hpp>\n#include <boost/detail/workaround.hpp>\n#include <boost/random/detail/config.hpp>\n#include <boost/random/detail/seed.hpp>\n#include <boost/random/detail/operators.hpp>\n#include <boost/random/detail/seed_impl.hpp>\n#include <boost/random/detail/generator_seed_seq.hpp>\n#include <boost/random/linear_congruential.hpp>\n\n\nnamespace boost {\nnamespace random {\n\nnamespace detail {\n   \nstruct subtract_with_carry_discard\n{\n    template<class Engine>\n    static void apply(Engine& eng, boost::uintmax_t z)\n    {\n        typedef typename Engine::result_type IntType;\n        const std::size_t short_lag = Engine::short_lag;\n        const std::size_t long_lag = Engine::long_lag;\n        std::size_t k = eng.k;\n        IntType carry = eng.carry;\n        if(k != 0) {\n            // increment k until it becomes 0.\n            if(k < short_lag) {\n                std::size_t limit = (short_lag - k) < z?\n                    short_lag : (k + static_cast<std::size_t>(z));\n                for(std::size_t j = k; j < limit; ++j) {\n                    carry = eng.do_update(j, j + long_lag - short_lag, carry);\n                }\n            }\n            std::size_t limit = (long_lag - k) < z?\n                long_lag : (k + static_cast<std::size_t>(z));\n            std::size_t start = (k < short_lag ? short_lag : k);\n            for(std::size_t j = start; j < limit; ++j) {\n                carry = eng.do_update(j, j - short_lag, carry);\n            }\n        }\n\n        k = ((z % long_lag) + k) % long_lag;\n\n        if(k < z) {\n            // main loop: update full blocks from k = 0 to long_lag\n            for(std::size_t i = 0; i < (z - k) / long_lag; ++i) {\n                for(std::size_t j = 0; j < short_lag; ++j) {\n                    carry = eng.do_update(j, j + long_lag - short_lag, carry);\n                }\n                for(std::size_t j = short_lag; j < long_lag; ++j) {\n                    carry = eng.do_update(j, j - short_lag, carry);\n                }\n            }\n\n            // Update the last partial block\n            std::size_t limit = short_lag < k? short_lag : k; \n            for(std::size_t j = 0; j < limit; ++j) {\n                carry = eng.do_update(j, j + long_lag - short_lag, carry);\n            }\n            for(std::size_t j = short_lag; j < k; ++j) {\n                carry = eng.do_update(j, j - short_lag, carry);\n            }\n        }\n        eng.carry = carry;\n        eng.k = k;\n    }\n};\n\n}\n\n/**\n * Instantiations of @c subtract_with_carry_engine model a\n * \\pseudo_random_number_generator.  The algorithm is\n * described in\n *\n *  @blockquote\n *  \"A New Class of Random Number Generators\", George\n *  Marsaglia and Arif Zaman, Annals of Applied Probability,\n *  Volume 1, Number 3 (1991), 462-480.\n *  @endblockquote\n */\ntemplate<class IntType, std::size_t w, std::size_t s, std::size_t r>\nclass subtract_with_carry_engine\n{\npublic:\n    typedef IntType result_type;\n    BOOST_STATIC_CONSTANT(std::size_t, word_size = w);\n    BOOST_STATIC_CONSTANT(std::size_t, long_lag = r);\n    BOOST_STATIC_CONSTANT(std::size_t, short_lag = s);\n    BOOST_STATIC_CONSTANT(uint32_t, default_seed = 19780503u);\n\n    // Required by the old Boost.Random concepts\n    BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);\n    // Backwards compatibility\n    BOOST_STATIC_CONSTANT(result_type, modulus = (result_type(1) << w));\n    \n    BOOST_STATIC_ASSERT(std::numeric_limits<result_type>::is_integer);\n\n    /**\n     * Constructs a new @c subtract_with_carry_engine and seeds\n     * it with the default seed.\n     */\n    subtract_with_carry_engine() { seed(); }\n    /**\n     * Constructs a new @c subtract_with_carry_engine and seeds\n     * it with @c value.\n     */\n    BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(subtract_with_carry_engine,\n                                               IntType, value)\n    { seed(value); }\n    /**\n     * Constructs a new @c subtract_with_carry_engine and seeds\n     * it with values produced by @c seq.generate().\n     */\n    BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(subtract_with_carry_engine,\n                                             SeedSeq, seq)\n    { seed(seq); }\n    /**\n     * Constructs a new @c subtract_with_carry_engine and seeds\n     * it with values from a range.  first is updated to point\n     * one past the last value consumed.  If there are not\n     * enough elements in the range to fill the entire state of\n     * the generator, throws @c std::invalid_argument.\n     */\n    template<class It> subtract_with_carry_engine(It& first, It last)\n    { seed(first,last); }\n\n    // compiler-generated copy ctor and assignment operator are fine\n\n    /** Seeds the generator with the default seed. */\n    void seed() { seed(default_seed); }\n    BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(subtract_with_carry_engine,\n                                        IntType, value)\n    {\n        typedef linear_congruential_engine<uint32_t,40014,0,2147483563> gen_t;\n        gen_t intgen(static_cast<boost::uint32_t>(value));\n        detail::generator_seed_seq<gen_t> gen(intgen);\n        seed(gen);\n    }\n\n    /** Seeds the generator with values produced by @c seq.generate(). */\n    BOOST_RANDOM_DETAIL_SEED_SEQ_SEED(subtract_with_carry, SeedSeq, seq)\n    {\n        detail::seed_array_int<w>(seq, x);\n        carry = (x[long_lag-1] == 0);\n        k = 0;\n    }\n\n    /**\n     * Seeds the generator with values from a range.  Updates @c first to\n     * point one past the last consumed value.  If the range does not\n     * contain enough elements to fill the entire state of the generator,\n     * throws @c std::invalid_argument.\n     */\n    template<class It>\n    void seed(It& first, It last)\n    {\n        detail::fill_array_int<w>(first, last, x);\n        carry = (x[long_lag-1] == 0);\n        k = 0;\n    }\n\n    /** Returns the smallest value that the generator can produce. */\n    static result_type min BOOST_PREVENT_MACRO_SUBSTITUTION ()\n    { return 0; }\n    /** Returns the largest value that the generator can produce. */\n    static result_type max BOOST_PREVENT_MACRO_SUBSTITUTION ()\n    { return boost::low_bits_mask_t<w>::sig_bits; }\n\n    /** Returns the next value of the generator. */\n    result_type operator()()\n    {\n        std::size_t short_index =\n            (k < short_lag)?\n                (k + long_lag - short_lag) :\n                (k - short_lag);\n        carry = do_update(k, short_index, carry);\n        IntType result = x[k];\n        ++k;\n        if(k >= long_lag)\n            k = 0;\n        return result;\n    }\n\n    /** Advances the state of the generator by @c z. */\n    void discard(boost::uintmax_t z)\n    {\n        detail::subtract_with_carry_discard::apply(*this, z);\n    }\n\n    /** Fills a range with random values. */\n    template<class It>\n    void generate(It first, It last)\n    { detail::generate_from_int(*this, first, last); }\n \n    /** Writes a @c subtract_with_carry_engine to a @c std::ostream. */\n    BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, subtract_with_carry_engine, f)\n    {\n        for(unsigned int j = 0; j < f.long_lag; ++j)\n            os << f.compute(j) << ' ';\n        os << f.carry;\n        return os;\n    }\n\n    /** Reads a @c subtract_with_carry_engine from a @c std::istream. */\n    BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, subtract_with_carry_engine, f)\n    {\n        for(unsigned int j = 0; j < f.long_lag; ++j)\n            is >> f.x[j] >> std::ws;\n        is >> f.carry;\n        f.k = 0;\n        return is;\n    }\n\n    /**\n     * Returns true if the two generators will produce identical\n     * sequences of values.\n     */\n    BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(subtract_with_carry_engine, x, y)\n    {\n        for(unsigned int j = 0; j < r; ++j)\n            if(x.compute(j) != y.compute(j))\n                return false;\n        return true;\n    }\n\n    /**\n     * Returns true if the two generators will produce different\n     * sequences of values.\n     */\n    BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(subtract_with_carry_engine)\n\nprivate:\n    /// \\cond show_private\n    // returns x(i-r+index), where index is in 0..r-1\n    IntType compute(unsigned int index) const\n    {\n        return x[(k+index) % long_lag];\n    }\n\n    friend struct detail::subtract_with_carry_discard;\n\n    IntType do_update(std::size_t current, std::size_t short_index, IntType carry)\n    {\n        IntType delta;\n        IntType temp = x[current] + carry;\n        if (x[short_index] >= temp) {\n            // x(n) >= 0\n            delta =  x[short_index] - temp;\n            carry = 0;\n        } else {\n            // x(n) < 0\n            delta = modulus - temp + x[short_index];\n            carry = 1;\n        }\n        x[current] = delta;\n        return carry;\n    }\n    /// \\endcond\n\n    // state representation; next output (state) is x(i)\n    //   x[0]  ... x[k] x[k+1] ... x[long_lag-1]     represents\n    //  x(i-k) ... x(i) x(i+1) ... x(i-k+long_lag-1)\n    // speed: base: 20-25 nsec\n    // ranlux_4: 230 nsec, ranlux_7: 430 nsec, ranlux_14: 810 nsec\n    // This state representation makes operator== and save/restore more\n    // difficult, because we've already computed \"too much\" and thus\n    // have to undo some steps to get at x(i-r) etc.\n\n    // state representation: next output (state) is x(i)\n    //   x[0]  ... x[k] x[k+1]          ... x[long_lag-1]     represents\n    //  x(i-k) ... x(i) x(i-long_lag+1) ... x(i-k-1)\n    // speed: base 28 nsec\n    // ranlux_4: 370 nsec, ranlux_7: 688 nsec, ranlux_14: 1343 nsec\n    IntType x[long_lag];\n    std::size_t k;\n    IntType carry;\n};\n\n#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION\n//  A definition is required even for integral static constants\ntemplate<class IntType, std::size_t w, std::size_t s, std::size_t r>\nconst bool subtract_with_carry_engine<IntType, w, s, r>::has_fixed_range;\ntemplate<class IntType, std::size_t w, std::size_t s, std::size_t r>\nconst IntType subtract_with_carry_engine<IntType, w, s, r>::modulus;\ntemplate<class IntType, std::size_t w, std::size_t s, std::size_t r>\nconst std::size_t subtract_with_carry_engine<IntType, w, s, r>::word_size;\ntemplate<class IntType, std::size_t w, std::size_t s, std::size_t r>\nconst std::size_t subtract_with_carry_engine<IntType, w, s, r>::long_lag;\ntemplate<class IntType, std::size_t w, std::size_t s, std::size_t r>\nconst std::size_t subtract_with_carry_engine<IntType, w, s, r>::short_lag;\ntemplate<class IntType, std::size_t w, std::size_t s, std::size_t r>\nconst uint32_t subtract_with_carry_engine<IntType, w, s, r>::default_seed;\n#endif\n\n\n// use a floating-point representation to produce values in [0..1)\n/**\n * Instantiations of \\subtract_with_carry_01_engine model a\n * \\pseudo_random_number_generator.  The algorithm is\n * described in\n *\n *  @blockquote\n *  \"A New Class of Random Number Generators\", George\n *  Marsaglia and Arif Zaman, Annals of Applied Probability,\n *  Volume 1, Number 3 (1991), 462-480.\n *  @endblockquote\n */\ntemplate<class RealType, std::size_t w, std::size_t s, std::size_t r>\nclass subtract_with_carry_01_engine\n{\npublic:\n    typedef RealType result_type;\n    BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);\n    BOOST_STATIC_CONSTANT(std::size_t, word_size = w);\n    BOOST_STATIC_CONSTANT(std::size_t, long_lag = r);\n    BOOST_STATIC_CONSTANT(std::size_t, short_lag = s);\n    BOOST_STATIC_CONSTANT(boost::uint32_t, default_seed = 19780503u);\n\n    BOOST_STATIC_ASSERT(!std::numeric_limits<result_type>::is_integer);\n\n    /** Creates a new \\subtract_with_carry_01_engine using the default seed. */\n    subtract_with_carry_01_engine() { init_modulus(); seed(); }\n    /** Creates a new subtract_with_carry_01_engine and seeds it with value. */\n    BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(subtract_with_carry_01_engine,\n                                               boost::uint32_t, value)\n    { init_modulus(); seed(value); }\n    /**\n     * Creates a new \\subtract_with_carry_01_engine and seeds with with values\n     * produced by seq.generate().\n     */\n    BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(subtract_with_carry_01_engine,\n                                             SeedSeq, seq)\n    { init_modulus(); seed(seq); }\n    /**\n     * Creates a new \\subtract_with_carry_01_engine and seeds it with values\n     * from a range.  Advances first to point one past the last consumed\n     * value.  If the range does not contain enough elements to fill the\n     * entire state, throws @c std::invalid_argument.\n     */\n    template<class It> subtract_with_carry_01_engine(It& first, It last)\n    { init_modulus(); seed(first,last); }\n\nprivate:\n    /// \\cond show_private\n    void init_modulus()\n    {\n#ifndef BOOST_NO_STDC_NAMESPACE\n        // allow for Koenig lookup\n        using std::pow;\n#endif\n        _modulus = pow(RealType(2), RealType(word_size));\n    }\n    /// \\endcond\n\npublic:\n    // compiler-generated copy ctor and assignment operator are fine\n\n    /** Seeds the generator with the default seed. */\n    void seed() { seed(default_seed); }\n\n    /** Seeds the generator with @c value. */\n    BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(subtract_with_carry_01_engine,\n                                        boost::uint32_t, value)\n    {\n        typedef linear_congruential_engine<uint32_t, 40014, 0, 2147483563> gen_t;\n        gen_t intgen(value);\n        detail::generator_seed_seq<gen_t> gen(intgen);\n        seed(gen);\n    }\n\n    /** Seeds the generator with values produced by @c seq.generate(). */\n    BOOST_RANDOM_DETAIL_SEED_SEQ_SEED(subtract_with_carry_01_engine,\n                                      SeedSeq, seq)\n    {\n        detail::seed_array_real<w>(seq, x);\n        carry = (x[long_lag-1] ? 0 : 1 / _modulus);\n        k = 0;\n    }\n\n    /**\n     * Seeds the generator with values from a range.  Updates first to\n     * point one past the last consumed element.  If there are not\n     * enough elements in the range to fill the entire state, throws\n     * @c std::invalid_argument.\n     */\n    template<class It>\n    void seed(It& first, It last)\n    {\n        detail::fill_array_real<w>(first, last, x);\n        carry = (x[long_lag-1] ? 0 : 1 / _modulus);\n        k = 0;\n    }\n\n    /** Returns the smallest value that the generator can produce. */\n    static result_type min BOOST_PREVENT_MACRO_SUBSTITUTION ()\n    { return result_type(0); }\n    /** Returns the largest value that the generator can produce. */\n    static result_type max BOOST_PREVENT_MACRO_SUBSTITUTION ()\n    { return result_type(1); }\n\n    /** Returns the next value of the generator. */\n    result_type operator()()\n    {\n        std::size_t short_index =\n            (k < short_lag) ?\n                (k + long_lag - short_lag) :\n                (k - short_lag);\n        carry = do_update(k, short_index, carry);\n        RealType result = x[k];\n        ++k;\n        if(k >= long_lag)\n            k = 0;\n        return result;\n    }\n\n    /** Advances the state of the generator by @c z. */\n    void discard(boost::uintmax_t z)\n    { detail::subtract_with_carry_discard::apply(*this, z); }\n\n    /** Fills a range with random values. */\n    template<class Iter>\n    void generate(Iter first, Iter last)\n    { detail::generate_from_real(*this, first, last); }\n\n    /** Writes a \\subtract_with_carry_01_engine to a @c std::ostream. */\n    BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, subtract_with_carry_01_engine, f)\n    {\n        std::ios_base::fmtflags oldflags =\n            os.flags(os.dec | os.fixed | os.left); \n        for(unsigned int j = 0; j < f.long_lag; ++j)\n            os << (f.compute(j) * f._modulus) << ' ';\n        os << (f.carry * f._modulus);\n        os.flags(oldflags);\n        return os;\n    }\n    \n    /** Reads a \\subtract_with_carry_01_engine from a @c std::istream. */\n    BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, subtract_with_carry_01_engine, f)\n    {\n        RealType value;\n        for(unsigned int j = 0; j < long_lag; ++j) {\n            is >> value >> std::ws;\n            f.x[j] = value / f._modulus;\n        }\n        is >> value;\n        f.carry = value / f._modulus;\n        f.k = 0;\n        return is;\n    }\n\n    /** Returns true if the two generators will produce identical sequences. */\n    BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(subtract_with_carry_01_engine, x, y)\n    {\n        for(unsigned int j = 0; j < r; ++j)\n            if(x.compute(j) != y.compute(j))\n                return false;\n        return true;\n    }\n\n    /** Returns true if the two generators will produce different sequences. */\n    BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(subtract_with_carry_01_engine)\n\nprivate:\n    /// \\cond show_private\n    RealType compute(unsigned int index) const\n    {\n        return x[(k+index) % long_lag];\n    }\n\n    friend struct detail::subtract_with_carry_discard;\n\n    RealType do_update(std::size_t current, std::size_t short_index, RealType carry)\n    {\n        RealType delta = x[short_index] - x[current] - carry;\n        if(delta < 0) {\n            delta += RealType(1);\n            carry = RealType(1)/_modulus;\n        } else {\n            carry = 0;\n        }\n        x[current] = delta;\n        return carry;\n    }\n    /// \\endcond\n    std::size_t k;\n    RealType carry;\n    RealType x[long_lag];\n    RealType _modulus;\n};\n\n#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION\n//  A definition is required even for integral static constants\ntemplate<class RealType, std::size_t w, std::size_t s, std::size_t r>\nconst bool subtract_with_carry_01_engine<RealType, w, s, r>::has_fixed_range;\ntemplate<class RealType, std::size_t w, std::size_t s, std::size_t r>\nconst std::size_t subtract_with_carry_01_engine<RealType, w, s, r>::word_size;\ntemplate<class RealType, std::size_t w, std::size_t s, std::size_t r>\nconst std::size_t subtract_with_carry_01_engine<RealType, w, s, r>::long_lag;\ntemplate<class RealType, std::size_t w, std::size_t s, std::size_t r>\nconst std::size_t subtract_with_carry_01_engine<RealType, w, s, r>::short_lag;\ntemplate<class RealType, std::size_t w, std::size_t s, std::size_t r>\nconst uint32_t subtract_with_carry_01_engine<RealType, w, s, r>::default_seed;\n#endif\n\n\n/// \\cond show_deprecated\n\ntemplate<class IntType, IntType m, unsigned s, unsigned r, IntType v>\nclass subtract_with_carry :\n    public subtract_with_carry_engine<IntType,\n        boost::static_log2<m>::value, s, r>\n{\n    typedef subtract_with_carry_engine<IntType,\n        boost::static_log2<m>::value, s, r> base_type;\npublic:\n    subtract_with_carry() {}\n    BOOST_RANDOM_DETAIL_GENERATOR_CONSTRUCTOR(subtract_with_carry, Gen, gen)\n    { seed(gen); }\n    BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(subtract_with_carry,\n                                               IntType, val)\n    { seed(val); }\n    template<class It>\n    subtract_with_carry(It& first, It last) : base_type(first, last) {}\n    void seed() { base_type::seed(); }\n    BOOST_RANDOM_DETAIL_GENERATOR_SEED(subtract_with_carry, Gen, gen)\n    {\n        detail::generator_seed_seq<Gen> seq(gen);\n        base_type::seed(seq);\n    }\n    BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(subtract_with_carry, IntType, val)\n    { base_type::seed(val); }\n    template<class It>\n    void seed(It& first, It last) { base_type::seed(first, last); }\n};\n\ntemplate<class RealType, int w, unsigned s, unsigned r, int v = 0>\nclass subtract_with_carry_01 :\n    public subtract_with_carry_01_engine<RealType, w, s, r>\n{\n    typedef subtract_with_carry_01_engine<RealType, w, s, r> base_type;\npublic:\n    subtract_with_carry_01() {}\n    BOOST_RANDOM_DETAIL_GENERATOR_CONSTRUCTOR(subtract_with_carry_01, Gen, gen)\n    { seed(gen); }\n    BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(subtract_with_carry_01,\n                                               uint32_t, val)\n    { seed(val); }\n    template<class It>\n    subtract_with_carry_01(It& first, It last) : base_type(first, last) {}\n    void seed() { base_type::seed(); }\n    BOOST_RANDOM_DETAIL_GENERATOR_SEED(subtract_with_carry_01, Gen, gen)\n    {\n        detail::generator_seed_seq<Gen> seq(gen);\n        base_type::seed(seq);\n    }\n    BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(subtract_with_carry_01, uint32_t, val)\n    { base_type::seed(val); }\n    template<class It>\n    void seed(It& first, It last) { base_type::seed(first, last); }\n};\n\n/// \\endcond\n\nnamespace detail {\n\ntemplate<class Engine>\nstruct generator_bits;\n\ntemplate<class RealType, std::size_t w, std::size_t s, std::size_t r>\nstruct generator_bits<subtract_with_carry_01_engine<RealType, w, s, r> > {\n    static std::size_t value() { return w; }\n};\n\ntemplate<class RealType, int w, unsigned s, unsigned r, int v>\nstruct generator_bits<subtract_with_carry_01<RealType, w, s, r, v> > {\n    static std::size_t value() { return w; }\n};\n\n}\n\n} // namespace random\n} // namespace boost\n\n#endif // BOOST_RANDOM_SUBTRACT_WITH_CARRY_HPP\n", "meta": {"hexsha": "298eb334751f67d9996133d329e58a224f243a33", "size": 21556, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Pods/boost/boost/random/subtract_with_carry.hpp", "max_stars_repo_name": "dzq1991/DJ_YingKe", "max_stars_repo_head_hexsha": "53f093ecf5fcd6093756b6935bf66e79c4d5fa5e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 130.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T23:34:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T19:22:35.000Z", "max_issues_repo_path": "Boost_1_49/boost/random/subtract_with_carry.hpp", "max_issues_repo_name": "jjzhang166/WinUtil4", "max_issues_repo_head_hexsha": "7c7b1e9bbe2fb6177bb066d74764d10711748ec5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2015-01-12T19:30:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-27T10:53:56.000Z", "max_forks_repo_path": "Boost_1_49/boost/random/subtract_with_carry.hpp", "max_forks_repo_name": "jjzhang166/WinUtil4", "max_forks_repo_head_hexsha": "7c7b1e9bbe2fb6177bb066d74764d10711748ec5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 44.0, "max_forks_repo_forks_event_min_datetime": "2015-03-18T09:20:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T08:09:17.000Z", "avg_line_length": 35.1074918567, "max_line_length": 84, "alphanum_fraction": 0.6335591019, "num_tokens": 5677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.27290379170824725}}
{"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_VECTOR_ASSIGN_\n#define _BOOST_UBLAS_VECTOR_ASSIGN_\n\n#include <boost/numeric/ublas/functional.hpp> // scalar_assign\n// Required for make_conformant storage\n#include <vector>\n\n// Iterators based on ideas of Jeremy Siek\n\nnamespace boost { namespace numeric { namespace ublas {\nnamespace detail {\n\n    // Weak equality check - useful to compare equality two arbitary vector expression results.\n    // Since the actual expressions are unknown, we check for and arbitary error bound\n    // on the relative error.\n    // For a linear expression the infinity norm makes sense as we do not know how the elements will be\n    // combined in the expression. False positive results are inevitable for arbirary expressions!\n    template<class E1, class E2, class S>\n    BOOST_UBLAS_INLINE\n    bool equals (const vector_expression<E1> &e1, const vector_expression<E2> &e2, S epsilon, S min_norm) {\n        return norm_inf (e1 - e2) < epsilon *\n               std::max<S> (std::max<S> (norm_inf (e1), norm_inf (e2)), min_norm);\n    }\n\n    template<class E1, class E2>\n    BOOST_UBLAS_INLINE\n    bool expression_type_check (const vector_expression<E1> &e1, const vector_expression<E2> &e2) {\n        typedef typename type_traits<typename promote_traits<typename E1::value_type,\n                                     typename E2::value_type>::promote_type>::real_type real_type;\n        return equals (e1, e2, BOOST_UBLAS_TYPE_CHECK_EPSILON, BOOST_UBLAS_TYPE_CHECK_MIN);\n    }\n\n\n    // Make sparse proxies conformant\n    template<class V, class E>\n    // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.\n    void make_conformant (V &v, const vector_expression<E> &e) {\n        BOOST_UBLAS_CHECK (v.size () == e ().size (), bad_size ());\n        typedef typename V::size_type size_type;\n        typedef typename V::difference_type difference_type;\n        typedef typename V::value_type value_type;\n        // FIXME unbounded_array with push_back maybe better\n        std::vector<size_type> index;\n        typename V::iterator it (v.begin ());\n        typename V::iterator it_end (v.end ());\n        typename E::const_iterator ite (e ().begin ());\n        typename E::const_iterator ite_end (e ().end ());\n        if (it != it_end && ite != ite_end) {\n            size_type it_index = it.index (), ite_index = ite.index ();\n            while (true) {\n                difference_type compare = it_index - ite_index;\n                if (compare == 0) {\n                    ++ it, ++ ite;\n                    if (it != it_end && ite != ite_end) {\n                        it_index = it.index ();\n                        ite_index = ite.index ();\n                    } else\n                        break;\n                } else if (compare < 0) {\n                    increment (it, it_end, - compare);\n                    if (it != it_end)\n                        it_index = it.index ();\n                    else\n                        break;\n                } else if (compare > 0) {\n                    if (*ite != value_type/*zero*/())\n                        index.push_back (ite.index ());\n                    ++ ite;\n                    if (ite != ite_end)\n                        ite_index = ite.index ();\n                    else\n                        break;\n                }\n            }\n        }\n\n        while (ite != ite_end) {\n            if (*ite != value_type/*zero*/())\n                index.push_back (ite.index ());\n            ++ ite;\n        }\n        for (size_type k = 0; k < index.size (); ++ k)\n            v (index [k]) = value_type/*zero*/();\n    }\n\n}//namespace detail\n\n\n    // Explicitly iterating\n    template<template <class T1, class T2> class F, class V, class T>\n    // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.\n    void iterating_vector_assign_scalar (V &v, const T &t) {\n        typedef F<typename V::iterator::reference, T> functor_type;\n        typedef typename V::difference_type difference_type;\n        difference_type size (v.size ());\n        typename V::iterator it (v.begin ());\n        BOOST_UBLAS_CHECK (v.end () - it == size, bad_size ());\n#ifndef BOOST_UBLAS_USE_DUFF_DEVICE\n        while (-- size >= 0)\n            functor_type::apply (*it, t), ++ it;\n#else\n        DD (size, 4, r, (functor_type::apply (*it, t), ++ it));\n#endif\n    }\n    // Explicitly case\n    template<template <class T1, class T2> class F, class V, class T>\n    // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.\n    void indexing_vector_assign_scalar (V &v, const T &t) {\n        typedef F<typename V::reference, T> functor_type;\n        typedef typename V::size_type size_type;\n        size_type size (v.size ());\n#ifndef BOOST_UBLAS_USE_DUFF_DEVICE\n        for (size_type i = 0; i < size; ++ i)\n            functor_type::apply (v (i), t);\n#else\n        size_type i (0);\n        DD (size, 4, r, (functor_type::apply (v (i), t), ++ i));\n#endif\n    }\n\n    // Dense (proxy) case\n    template<template <class T1, class T2> class F, class V, class T>\n    // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.\n    void vector_assign_scalar (V &v, const T &t, dense_proxy_tag) {\n#ifdef BOOST_UBLAS_USE_INDEXING\n        indexing_vector_assign_scalar<F> (v, t);\n#elif BOOST_UBLAS_USE_ITERATING\n        iterating_vector_assign_scalar<F> (v, t);\n#else\n        typedef typename V::size_type size_type;\n        size_type size (v.size ());\n        if (size >= BOOST_UBLAS_ITERATOR_THRESHOLD)\n            iterating_vector_assign_scalar<F> (v, t);\n        else\n            indexing_vector_assign_scalar<F> (v, t);\n#endif\n    }\n    // Packed (proxy) case\n    template<template <class T1, class T2> class F, class V, class T>\n    // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.\n    void vector_assign_scalar (V &v, const T &t, packed_proxy_tag) {\n        typedef F<typename V::iterator::reference, T> functor_type;\n        typedef typename V::difference_type difference_type;\n        typename V::iterator it (v.begin ());\n        difference_type size (v.end () - it);\n        while (-- size >= 0)\n            functor_type::apply (*it, t), ++ it;\n    }\n    // Sparse (proxy) case\n    template<template <class T1, class T2> class F, class V, class T>\n    // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.\n    void vector_assign_scalar (V &v, const T &t, sparse_proxy_tag) {\n        typedef F<typename V::iterator::reference, T> functor_type;\n        typename V::iterator it (v.begin ());\n        typename V::iterator it_end (v.end ());\n        while (it != it_end)\n            functor_type::apply (*it, t), ++ it;\n    }\n\n    // Dispatcher\n    template<template <class T1, class T2> class F, class V, class T>\n    BOOST_UBLAS_INLINE\n    void vector_assign_scalar (V &v, const T &t) {\n        typedef typename V::storage_category storage_category;\n        vector_assign_scalar<F> (v, t, storage_category ());\n    }\n\n    template<class SC, bool COMPUTED, class RI>\n    struct vector_assign_traits {\n        typedef SC storage_category;\n    };\n\n    template<bool COMPUTED>\n    struct vector_assign_traits<dense_tag, COMPUTED, packed_random_access_iterator_tag> {\n        typedef packed_tag storage_category;\n    };\n    template<>\n    struct vector_assign_traits<dense_tag, false, sparse_bidirectional_iterator_tag> {\n        typedef sparse_tag storage_category;\n    };\n    template<>\n    struct vector_assign_traits<dense_tag, true, sparse_bidirectional_iterator_tag> {\n        typedef sparse_proxy_tag storage_category;\n    };\n\n    template<bool COMPUTED>\n    struct vector_assign_traits<dense_proxy_tag, COMPUTED, packed_random_access_iterator_tag> {\n        typedef packed_proxy_tag storage_category;\n    };\n    template<>\n    struct vector_assign_traits<dense_proxy_tag, false, sparse_bidirectional_iterator_tag> {\n        typedef sparse_proxy_tag storage_category;\n    };\n    template<>\n    struct vector_assign_traits<dense_proxy_tag, true, sparse_bidirectional_iterator_tag> {\n        typedef sparse_proxy_tag storage_category;\n    };\n\n    template<>\n    struct vector_assign_traits<packed_tag, false, sparse_bidirectional_iterator_tag> {\n        typedef sparse_tag storage_category;\n    };\n    template<>\n    struct vector_assign_traits<packed_tag, true, sparse_bidirectional_iterator_tag> {\n        typedef sparse_proxy_tag storage_category;\n    };\n\n    template<bool COMPUTED>\n    struct vector_assign_traits<packed_proxy_tag, COMPUTED, sparse_bidirectional_iterator_tag> {\n        typedef sparse_proxy_tag storage_category;\n    };\n\n    template<>\n    struct vector_assign_traits<sparse_tag, true, dense_random_access_iterator_tag> {\n        typedef sparse_proxy_tag storage_category;\n    };\n    template<>\n    struct vector_assign_traits<sparse_tag, true, packed_random_access_iterator_tag> {\n        typedef sparse_proxy_tag storage_category;\n    };\n    template<>\n    struct vector_assign_traits<sparse_tag, true, sparse_bidirectional_iterator_tag> {\n        typedef sparse_proxy_tag storage_category;\n    };\n\n    // Explicitly iterating\n    template<template <class T1, class T2> class F, class V, class E>\n    // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.\n    void iterating_vector_assign (V &v, const vector_expression<E> &e) {\n        typedef F<typename V::iterator::reference, typename E::value_type> functor_type;\n        typedef typename V::difference_type difference_type;\n        difference_type size (BOOST_UBLAS_SAME (v.size (), e ().size ()));\n        typename V::iterator it (v.begin ());\n        BOOST_UBLAS_CHECK (v.end () - it == size, bad_size ());\n        typename E::const_iterator ite (e ().begin ());\n        BOOST_UBLAS_CHECK (e ().end () - ite == size, bad_size ());\n#ifndef BOOST_UBLAS_USE_DUFF_DEVICE\n        while (-- size >= 0)\n            functor_type::apply (*it, *ite), ++ it, ++ ite;\n#else\n        DD (size, 2, r, (functor_type::apply (*it, *ite), ++ it, ++ ite));\n#endif\n    }\n    // Explicitly indexing\n    template<template <class T1, class T2> class F, class V, class E>\n    // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.\n    void indexing_vector_assign (V &v, const vector_expression<E> &e) {\n        typedef F<typename V::reference, typename E::value_type> functor_type;\n        typedef typename V::size_type size_type;\n        size_type size (BOOST_UBLAS_SAME (v.size (), e ().size ()));\n#ifndef BOOST_UBLAS_USE_DUFF_DEVICE\n        for (size_type i = 0; i < size; ++ i)\n            functor_type::apply (v (i), e () (i));\n#else\n        size_type i (0);\n        DD (size, 2, r, (functor_type::apply (v (i), e () (i)), ++ i));\n#endif\n    }\n\n    // Dense (proxy) case\n    template<template <class T1, class T2> class F, class V, class E>\n    // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.\n    void vector_assign (V &v, const vector_expression<E> &e, dense_proxy_tag) {\n#ifdef BOOST_UBLAS_USE_INDEXING\n        indexing_vector_assign<F> (v, e);\n#elif BOOST_UBLAS_USE_ITERATING\n        iterating_vector_assign<F> (v, e);\n#else\n        typedef typename V::size_type size_type;\n        size_type size (BOOST_UBLAS_SAME (v.size (), e ().size ()));\n        if (size >= BOOST_UBLAS_ITERATOR_THRESHOLD)\n            iterating_vector_assign<F> (v, e);\n        else\n            indexing_vector_assign<F> (v, e);\n#endif\n    }\n    // Packed (proxy) case\n    template<template <class T1, class T2> class F, class V, class E>\n    // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.\n    void vector_assign (V &v, const vector_expression<E> &e, packed_proxy_tag) {\n        BOOST_UBLAS_CHECK (v.size () == e ().size (), bad_size ());\n        typedef F<typename V::iterator::reference, typename E::value_type> functor_type;\n        typedef typename V::difference_type difference_type;\n        typedef typename V::value_type value_type;\n#if BOOST_UBLAS_TYPE_CHECK\n        vector<value_type> cv (v.size ());\n        indexing_vector_assign<scalar_assign> (cv, v);\n        indexing_vector_assign<F> (cv, e);\n#endif\n        typename V::iterator it (v.begin ());\n        typename V::iterator it_end (v.end ());\n        typename E::const_iterator ite (e ().begin ());\n        typename E::const_iterator ite_end (e ().end ());\n        difference_type it_size (it_end - it);\n        difference_type ite_size (ite_end - ite);\n        if (it_size > 0 && ite_size > 0) {\n            difference_type size ((std::min) (difference_type (it.index () - ite.index ()), ite_size));\n            if (size > 0) {\n                ite += size;\n                ite_size -= size;\n            }\n        }\n        if (it_size > 0 && ite_size > 0) {\n            difference_type size ((std::min) (difference_type (ite.index () - it.index ()), it_size));\n            if (size > 0) {\n                it_size -= size;\n                if (!functor_type::computed) {\n                    while (-- size >= 0)    // zeroing\n                        functor_type::apply (*it, value_type/*zero*/()), ++ it;\n                } else {\n                    it += size;\n                }\n            }\n        }\n        difference_type size ((std::min) (it_size, ite_size));\n        it_size -= size;\n        ite_size -= size;\n        while (-- size >= 0)\n            functor_type::apply (*it, *ite), ++ it, ++ ite;\n        size = it_size;\n        if (!functor_type::computed) {\n            while (-- size >= 0)    // zeroing\n                functor_type::apply (*it, value_type/*zero*/()), ++ it;\n        } else {\n            it += size;\n        }\n#if BOOST_UBLAS_TYPE_CHECK\n        if (! disable_type_check<bool>::value) \n            BOOST_UBLAS_CHECK (detail::expression_type_check (v, cv), \n                               external_logic (\"external logic or bad condition of inputs\"));\n#endif\n    }\n    // Sparse case\n    template<template <class T1, class T2> class F, class V, class E>\n    // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.\n    void vector_assign (V &v, const vector_expression<E> &e, sparse_tag) {\n        BOOST_UBLAS_CHECK (v.size () == e ().size (), bad_size ());\n        typedef F<typename V::iterator::reference, typename E::value_type> functor_type;\n        BOOST_STATIC_ASSERT ((!functor_type::computed));\n        typedef typename V::value_type value_type;\n#if BOOST_UBLAS_TYPE_CHECK\n        vector<value_type> cv (v.size ());\n        indexing_vector_assign<scalar_assign> (cv, v);\n        indexing_vector_assign<F> (cv, e);\n#endif\n        v.clear ();\n        typename E::const_iterator ite (e ().begin ());\n        typename E::const_iterator ite_end (e ().end ());\n        while (ite != ite_end) {\n            value_type t (*ite);\n            if (t != value_type/*zero*/())\n                v.insert_element (ite.index (), t);\n            ++ ite;\n        }\n#if BOOST_UBLAS_TYPE_CHECK\n        if (! disable_type_check<bool>::value) \n            BOOST_UBLAS_CHECK (detail::expression_type_check (v, cv), \n                               external_logic (\"external logic or bad condition of inputs\"));\n#endif\n    }\n    // Sparse proxy or functional case\n    template<template <class T1, class T2> class F, class V, class E>\n    // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.\n    void vector_assign (V &v, const vector_expression<E> &e, sparse_proxy_tag) {\n        BOOST_UBLAS_CHECK (v.size () == e ().size (), bad_size ());\n        typedef F<typename V::iterator::reference, typename E::value_type> functor_type;\n        typedef typename V::size_type size_type;\n        typedef typename V::difference_type difference_type;\n        typedef typename V::value_type value_type;\n#if BOOST_UBLAS_TYPE_CHECK\n        vector<value_type> cv (v.size ());\n        indexing_vector_assign<scalar_assign> (cv, v);\n        indexing_vector_assign<F> (cv, e);\n#endif\n        detail::make_conformant (v, e);\n\n        typename V::iterator it (v.begin ());\n        typename V::iterator it_end (v.end ());\n        typename E::const_iterator ite (e ().begin ());\n        typename E::const_iterator ite_end (e ().end ());\n        if (it != it_end && ite != ite_end) {\n            size_type it_index = it.index (), ite_index = ite.index ();\n            while (true) {\n                difference_type compare = it_index - ite_index;\n                if (compare == 0) {\n                    functor_type::apply (*it, *ite);\n                    ++ it, ++ ite;\n                    if (it != it_end && ite != ite_end) {\n                        it_index = it.index ();\n                        ite_index = ite.index ();\n                    } else\n                        break;\n                } else if (compare < 0) {\n                    if (!functor_type::computed) {\n                        functor_type::apply (*it, value_type/*zero*/());\n                        ++ it;\n                    } else\n                        increment (it, it_end, - compare);\n                    if (it != it_end)\n                        it_index = it.index ();\n                    else\n                        break;\n                } else if (compare > 0) {\n                    increment (ite, ite_end, compare);\n                    if (ite != ite_end)\n                        ite_index = ite.index ();\n                    else\n                        break;\n                }\n            }\n        }\n\n        if (!functor_type::computed) {\n            while (it != it_end) {  // zeroing\n                functor_type::apply (*it, value_type/*zero*/());\n                ++ it;\n            }\n        } else {\n            it = it_end;\n        }\n#if BOOST_UBLAS_TYPE_CHECK\n        if (! disable_type_check<bool>::value)\n            BOOST_UBLAS_CHECK (detail::expression_type_check (v, cv), \n                               external_logic (\"external logic or bad condition of inputs\"));\n#endif\n    }\n\n    // Dispatcher\n    template<template <class T1, class T2> class F, class V, class E>\n    BOOST_UBLAS_INLINE\n    void vector_assign (V &v, const vector_expression<E> &e) {\n        typedef typename vector_assign_traits<typename V::storage_category,\n                                              F<typename V::reference, typename E::value_type>::computed,\n                                              typename E::const_iterator::iterator_category>::storage_category storage_category;\n        vector_assign<F> (v, e, storage_category ());\n    }\n\n    template<class SC, class RI>\n    struct vector_swap_traits {\n        typedef SC storage_category;\n    };\n\n    template<>\n    struct vector_swap_traits<dense_proxy_tag, sparse_bidirectional_iterator_tag> {\n        typedef sparse_proxy_tag storage_category;\n    };\n\n    template<>\n    struct vector_swap_traits<packed_proxy_tag, sparse_bidirectional_iterator_tag> {\n        typedef sparse_proxy_tag storage_category;\n    };\n\n    // Dense (proxy) case\n    template<template <class T1, class T2> class F, class V, class E>\n    // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.\n    void vector_swap (V &v, vector_expression<E> &e, dense_proxy_tag) {\n        typedef F<typename V::iterator::reference, typename E::iterator::reference> functor_type;\n        typedef typename V::difference_type difference_type;\n        difference_type size (BOOST_UBLAS_SAME (v.size (), e ().size ()));\n        typename V::iterator it (v.begin ());\n        typename E::iterator ite (e ().begin ());\n        while (-- size >= 0)\n            functor_type::apply (*it, *ite), ++ it, ++ ite;\n    }\n    // Packed (proxy) case\n    template<template <class T1, class T2> class F, class V, class E>\n    // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.\n    void vector_swap (V &v, vector_expression<E> &e, packed_proxy_tag) {\n        typedef F<typename V::iterator::reference, typename E::iterator::reference> functor_type;\n        typedef typename V::difference_type difference_type;\n        typename V::iterator it (v.begin ());\n        typename V::iterator it_end (v.end ());\n        typename E::iterator ite (e ().begin ());\n        typename E::iterator ite_end (e ().end ());\n        difference_type it_size (it_end - it);\n        difference_type ite_size (ite_end - ite);\n        if (it_size > 0 && ite_size > 0) {\n            difference_type size ((std::min) (difference_type (it.index () - ite.index ()), ite_size));\n            if (size > 0) {\n                ite += size;\n                ite_size -= size;\n            }\n        }\n        if (it_size > 0 && ite_size > 0) {\n            difference_type size ((std::min) (difference_type (ite.index () - it.index ()), it_size));\n            if (size > 0)\n                it_size -= size;\n        }\n        difference_type size ((std::min) (it_size, ite_size));\n        it_size -= size;\n        ite_size -= size;\n        while (-- size >= 0)\n            functor_type::apply (*it, *ite), ++ it, ++ ite;\n    }\n    // Sparse proxy case\n    template<template <class T1, class T2> class F, class V, class E>\n    // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.\n    void vector_swap (V &v, vector_expression<E> &e, sparse_proxy_tag) {\n        BOOST_UBLAS_CHECK (v.size () == e ().size (), bad_size ());\n        typedef F<typename V::iterator::reference, typename E::iterator::reference> functor_type;\n        typedef typename V::size_type size_type;\n        typedef typename V::difference_type difference_type;\n\n        detail::make_conformant (v, e);\n        // FIXME should be a seperate restriction for E\n        detail::make_conformant (e (), v);\n\n        typename V::iterator it (v.begin ());\n        typename V::iterator it_end (v.end ());\n        typename E::iterator ite (e ().begin ());\n        typename E::iterator ite_end (e ().end ());\n        if (it != it_end && ite != ite_end) {\n            size_type it_index = it.index (), ite_index = ite.index ();\n            while (true) {\n                difference_type compare = it_index - ite_index;\n                if (compare == 0) {\n                    functor_type::apply (*it, *ite);\n                    ++ it, ++ ite;\n                    if (it != it_end && ite != ite_end) {\n                        it_index = it.index ();\n                        ite_index = ite.index ();\n                    } else\n                        break;\n                } else if (compare < 0) {\n                    increment (it, it_end, - compare);\n                    if (it != it_end)\n                        it_index = it.index ();\n                    else\n                        break;\n                } else if (compare > 0) {\n                    increment (ite, ite_end, compare);\n                    if (ite != ite_end)\n                        ite_index = ite.index ();\n                    else\n                        break;\n                }\n            }\n        }\n\n#if BOOST_UBLAS_TYPE_CHECK\n        increment (ite, ite_end);\n        increment (it, it_end);\n#endif\n    }\n\n    // Dispatcher\n    template<template <class T1, class T2> class F, class V, class E>\n    BOOST_UBLAS_INLINE\n    void vector_swap (V &v, vector_expression<E> &e) {\n        typedef typename vector_swap_traits<typename V::storage_category,\n                                            typename E::const_iterator::iterator_category>::storage_category storage_category;\n        vector_swap<F> (v, e, storage_category ());\n    }\n\n}}}\n\n#endif\n", "meta": {"hexsha": "0f8f9384f48401e18c10dbc20fe65ce1ae14839a", "size": 23990, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "install/boost/numeric/ublas/detail/vector_assign.hpp", "max_stars_repo_name": "Jeremy0076/Search_engine", "max_stars_repo_head_hexsha": "8432a33200a0acfc54e94f1e22d3be6a92060349", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "install/boost/numeric/ublas/detail/vector_assign.hpp", "max_issues_repo_name": "Jeremy0076/Search_engine", "max_issues_repo_head_hexsha": "8432a33200a0acfc54e94f1e22d3be6a92060349", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "install/boost/numeric/ublas/detail/vector_assign.hpp", "max_forks_repo_name": "Jeremy0076/Search_engine", "max_forks_repo_head_hexsha": "8432a33200a0acfc54e94f1e22d3be6a92060349", "max_forks_repo_licenses": ["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.0877192982, "max_line_length": 128, "alphanum_fraction": 0.5882451021, "num_tokens": 5653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2729037844611154}}
{"text": "#include <unordered_map>\n\n#include <boost/filesystem.hpp>\n#include <g2o/types/slam3d/edge_se3.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/solvers/csparse/linear_solver_csparse.h>\n#include <g2o/solvers/pcg/linear_solver_pcg.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n\n#include \"GraphOptimizer/OptApp.h\"\n#include \"GraphOptimizer/vertigo/vertex_switchLinear.h\"\n#include \"GraphOptimizer/vertigo/edge_switchPrior.h\"\n#include \"GraphOptimizer/vertigo/edge_se3Switchable.h\"\n\ntypedef g2o::BlockSolver<g2o::BlockSolverTraits<6, 3>> SlamBlockSolver;\ntypedef g2o::LinearSolverCSparse<SlamBlockSolver::PoseMatrixType>\n    SlamLinearCSparseSolver;\ntypedef g2o::LinearSolverPCG<SlamBlockSolver::PoseMatrixType>\n    SlamLinearPCGSolver;\ntypedef std::unordered_map<int, g2o::HyperGraph::Vertex *> VertexIDMap;\ntypedef std::pair<int, g2o::HyperGraph::Vertex *> VertexIDPair;\ntypedef std::set<g2o::HyperGraph::Edge *> EdgeSet;\n\nCOptApp::COptApp(void) {}\n\nCOptApp::~COptApp(void) {}\n\nbool COptApp::Init() {\n    namespace fs = boost::filesystem;\n    if (fs::exists(fs::path(odometry_log_file_))) {\n        odometry_traj_.LoadFromFile(odometry_log_file_);\n        if (fs::exists(fs::path(odometry_info_file_))) {\n            odometry_info_.LoadFromFile(odometry_info_file_);\n        }\n    }\n    if (fs::exists(fs::path(loop_log_file_))) {\n        loop_traj_.LoadFromFile(loop_log_file_);\n        if (fs::exists(fs::path(loop_info_file_))) {\n            loop_info_.LoadFromFile(loop_info_file_);\n        }\n    }\n    pose_traj_.data_.clear();\n    pose_traj_.data_.push_back(\n        FramedTransformation(0, 0, 1, Eigen::Matrix4d::Identity()));\n    for (int i = 0; i < (int)odometry_traj_.data_.size(); i++) {\n        pose_traj_.data_.push_back(\n            FramedTransformation(i + 1, i + 1, i + 2,\n                                 pose_traj_.data_[i].transformation_ *\n                                     odometry_traj_.data_[i].transformation_));\n    }\n    return (odometry_traj_.data_.size() > 0);\n}\n\nvoid COptApp::OptimizeSwitchable() {\n    struct SwitchableEdge {\n      public:\n        VertexSwitchLinear *v_;\n        EdgeSwitchPrior *ep_;\n        EdgeSE3Switchable *e_;\n        FramedTransformation *t_;\n    };\n\n    g2o::SparseOptimizer *optimizer;\n    optimizer = new g2o::SparseOptimizer();\n    optimizer->setVerbose(true);\n    SlamBlockSolver *solver = NULL;\n    SlamLinearCSparseSolver *linearSolver = new SlamLinearCSparseSolver();\n    linearSolver->setBlockOrdering(false);\n    solver = new SlamBlockSolver(linearSolver);\n    g2o::OptimizationAlgorithmLevenberg *algo =\n        new g2o::OptimizationAlgorithmLevenberg(solver);\n    optimizer->setAlgorithm(algo);\n\n    std::vector<SwitchableEdge> switch_edge;\n\n    Eigen::Matrix<double, 6, 6> default_information;\n    default_information = Eigen::Matrix<double, 6, 6>::Identity();\n\n    for (int i = 0; i < (int)pose_traj_.data_.size(); i++) {\n        g2o::VertexSE3 *v = new g2o::VertexSE3();\n        v->setId(i);\n        v->setEstimate(Eigen2G2O(pose_traj_.data_[i].transformation_));\n        if (i == 0) {\n            v->setFixed(true);\n        }\n        optimizer->addVertex(v);\n\n        if (i > 0) {\n            g2o::EdgeSE3 *g2o_edge = new g2o::EdgeSE3();\n            g2o_edge->vertices()[0] =\n                dynamic_cast<g2o::VertexSE3 *>(optimizer->vertex(i - 1));\n            g2o_edge->vertices()[1] =\n                dynamic_cast<g2o::VertexSE3 *>(optimizer->vertex(i));\n            g2o_edge->setMeasurement(g2o::internal::fromSE3Quat(\n                Eigen2G2O(odometry_traj_.data_[i - 1].transformation_)));\n            if (odometry_info_.data_.size() > 0) {\n                g2o_edge->setInformation(\n                    odometry_info_.data_[i - 1].information_);\n            } else {\n                g2o_edge->setInformation(default_information);\n            }\n            optimizer->addEdge(g2o_edge);\n        }\n    }\n\n    for (int i = 0; i < (int)loop_traj_.data_.size(); i++) {\n        FramedTransformation &t = loop_traj_.data_[i];\n\n        SwitchableEdge edge;\n        edge.t_ = &t;\n\n        edge.v_ = new VertexSwitchLinear();\n        edge.v_->setId(optimizer->vertices().size());\n        edge.v_->setEstimate(1.0);\n        optimizer->addVertex(edge.v_);\n\n        edge.ep_ = new EdgeSwitchPrior();\n        edge.ep_->vertices()[0] = edge.v_;\n        edge.ep_->setMeasurement(1.0);\n        edge.ep_->setInformation(Eigen::Matrix<double, 1, 1>::Identity() *\n                                 weight_);\n        optimizer->addEdge(edge.ep_);\n\n        edge.e_ = new EdgeSE3Switchable();\n        edge.e_->vertices()[0] =\n            dynamic_cast<g2o::VertexSE3 *>(optimizer->vertex(t.id1_));\n        edge.e_->vertices()[1] =\n            dynamic_cast<g2o::VertexSE3 *>(optimizer->vertex(t.id2_));\n        edge.e_->vertices()[2] = edge.v_;\n        edge.e_->setMeasurement(\n            g2o::internal::fromSE3Quat(Eigen2G2O(t.transformation_)));\n        if (loop_info_.data_.size() > 0) {\n            edge.e_->setInformation(loop_info_.data_[i].information_);\n        } else {\n            edge.e_->setInformation(default_information);\n        }\n        optimizer->addEdge(edge.e_);\n        switch_edge.push_back(edge);\n    }\n\n    optimizer->initializeOptimization();\n    optimizer->optimize(max_iteration_);\n\n    for (int i = 0; i < (int)pose_traj_.data_.size(); i++) {\n        g2o::VertexSE3 *v =\n            dynamic_cast<g2o::VertexSE3 *>(optimizer->vertex(i));\n        pose_traj_.data_[i].transformation_ =\n            G2O2Matrix4d(v->estimateAsSE3Quat());\n    }\n    pose_traj_.SaveToFile(pose_log_file_);\n\n    loop_remain_traj_.data_.clear();\n    for (int i = 0; i < (int)switch_edge.size(); i++) {\n        SwitchableEdge &edge = switch_edge[i];\n        if (edge.v_->estimate() > 0.5) {\n            loop_remain_traj_.data_.push_back(loop_traj_.data_[i]);\n        }\n    }\n    loop_remain_traj_.SaveToFile(loop_remain_log_file_);\n\n    refine_traj_.data_.clear();\n    for (int i = 0; i < (int)odometry_traj_.data_.size(); i++) {\n        refine_traj_.data_.push_back(odometry_traj_.data_[i]);\n    }\n    for (int i = 0; i < (int)switch_edge.size(); i++) {\n        SwitchableEdge &edge = switch_edge[i];\n        if (edge.v_->estimate() > 0.5 &&\n            loop_traj_.data_[i].id1_ + 1 < loop_traj_.data_[i].id2_) {\n            refine_traj_.data_.push_back(loop_traj_.data_[i]);\n        }\n    }\n    refine_traj_.SaveToFile(refine_log_file_);\n}\n\nvoid COptApp::OptimizeEM() {\n    struct SwitchableEdge {\n      public:\n        double weight_;\n        g2o::EdgeSE3 *e_;\n        FramedTransformation *t_;\n    };\n\n    g2o::SparseOptimizer *optimizer;\n    optimizer = new g2o::SparseOptimizer();\n    optimizer->setVerbose(true);\n    SlamBlockSolver *solver = NULL;\n    SlamLinearCSparseSolver *linearSolver = new SlamLinearCSparseSolver();\n    linearSolver->setBlockOrdering(false);\n    solver = new SlamBlockSolver(linearSolver);\n    g2o::OptimizationAlgorithmLevenberg *algo =\n        new g2o::OptimizationAlgorithmLevenberg(solver);\n    optimizer->setAlgorithm(algo);\n\n    std::vector<SwitchableEdge> switch_edge;\n\n    Eigen::Matrix<double, 6, 6> default_information;\n    default_information = Eigen::Matrix<double, 6, 6>::Identity();\n\n    for (int i = 0; i < (int)pose_traj_.data_.size(); i++) {\n        g2o::VertexSE3 *v = new g2o::VertexSE3();\n        v->setId(i);\n        v->setEstimate(Eigen2G2O(pose_traj_.data_[i].transformation_));\n        if (i == 0) {\n            v->setFixed(true);\n        }\n        optimizer->addVertex(v);\n\n        if (i > 0) {\n            g2o::EdgeSE3 *g2o_edge = new g2o::EdgeSE3();\n            g2o_edge->vertices()[0] =\n                dynamic_cast<g2o::VertexSE3 *>(optimizer->vertex(i - 1));\n            g2o_edge->vertices()[1] =\n                dynamic_cast<g2o::VertexSE3 *>(optimizer->vertex(i));\n            g2o_edge->setMeasurement(g2o::internal::fromSE3Quat(\n                Eigen2G2O(odometry_traj_.data_[i - 1].transformation_)));\n            if (odometry_info_.data_.size() > 0) {\n                g2o_edge->setInformation(\n                    odometry_info_.data_[i - 1].information_);\n            } else {\n                g2o_edge->setInformation(default_information);\n            }\n            optimizer->addEdge(g2o_edge);\n        }\n    }\n\n    for (int i = 0; i < (int)loop_traj_.data_.size(); i++) {\n        FramedTransformation &t = loop_traj_.data_[i];\n        SwitchableEdge edge;\n        edge.t_ = &t;\n        edge.weight_ = 0.0;\n\n        edge.e_ = new g2o::EdgeSE3();\n        edge.e_->vertices()[0] =\n            dynamic_cast<g2o::VertexSE3 *>(optimizer->vertex(t.id1_));\n        edge.e_->vertices()[1] =\n            dynamic_cast<g2o::VertexSE3 *>(optimizer->vertex(t.id2_));\n        edge.e_->setMeasurement(\n            g2o::internal::fromSE3Quat(Eigen2G2O(t.transformation_)));\n        if (loop_info_.data_.size() > 0) {\n            edge.e_->setInformation(loop_info_.data_[i].information_);\n        } else {\n            edge.e_->setInformation(default_information);\n        }\n        optimizer->addEdge(edge.e_);\n        switch_edge.push_back(edge);\n    }\n\n    for (int itr = 0; itr < max_iteration_; itr++) {\n        // E step\n        for (int i = 0; i < (int)switch_edge.size(); i++) {\n            SwitchableEdge &edge = switch_edge[i];\n            if (loop_info_.data_.size() > 0) {\n                edge.e_->setInformation(loop_info_.data_[i].information_);\n            } else {\n                edge.e_->setInformation(default_information);\n            }\n            edge.e_->computeError();\n            edge.weight_ = (weight_ * weight_) /\n                           (weight_ * weight_ + switch_edge[i].e_->chi2());\n\n            if (loop_info_.data_.size() > 0) {\n                edge.e_->setInformation(loop_info_.data_[i].information_ *\n                                        sqrt(edge.weight_));\n            } else {\n                edge.e_->setInformation(default_information *\n                                        sqrt(edge.weight_));\n            }\n        }\n\n        // M step\n        optimizer->initializeOptimization();\n        optimizer->optimize(1);\n    }\n\n    for (int i = 0; i < (int)pose_traj_.data_.size(); i++) {\n        g2o::VertexSE3 *v =\n            dynamic_cast<g2o::VertexSE3 *>(optimizer->vertex(i));\n        pose_traj_.data_[i].transformation_ =\n            G2O2Matrix4d(v->estimateAsSE3Quat());\n    }\n    pose_traj_.SaveToFile(pose_log_file_);\n\n    loop_remain_traj_.data_.clear();\n    for (int i = 0; i < (int)switch_edge.size(); i++) {\n        SwitchableEdge &edge = switch_edge[i];\n        if (edge.weight_ > 0.25) {\n            loop_remain_traj_.data_.push_back(loop_traj_.data_[i]);\n        }\n    }\n    loop_remain_traj_.SaveToFile(loop_remain_log_file_);\n}\n", "meta": {"hexsha": "43f64a5e3bbdc8c12d83777643755af69ef70ee4", "size": 10711, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GraphOptimizer/OptApp.cpp", "max_stars_repo_name": "yxlao/ElasticReconstruction", "max_stars_repo_head_hexsha": "3afce2f84f117378708f6121f319af18ca01518f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GraphOptimizer/OptApp.cpp", "max_issues_repo_name": "yxlao/ElasticReconstruction", "max_issues_repo_head_hexsha": "3afce2f84f117378708f6121f319af18ca01518f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GraphOptimizer/OptApp.cpp", "max_forks_repo_name": "yxlao/ElasticReconstruction", "max_forks_repo_head_hexsha": "3afce2f84f117378708f6121f319af18ca01518f", "max_forks_repo_licenses": ["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.6815068493, "max_line_length": 79, "alphanum_fraction": 0.5996638969, "num_tokens": 2846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2727202743968327}}
{"text": "#include \"gauss_newton_solver.h\"\n#include \"prior_sparse_features.h\"\n#include \"util.h\"\n#include \"device_util.h\"\n#include \"device_array.h\"\n\n#include <Eigen/Dense>\n#include <chrono>\n\nGaussNewtonSolver::GaussNewtonSolver()\n\t: m_face_bb(1)\n\t, m_sh_coefficients_gpu(9)\n{\n\tcublasCreate(&m_cublas);\n}\n\nGaussNewtonSolver::~GaussNewtonSolver()\n{\n\tcublasDestroy(m_cublas);\n\tdestroyTextures();\n}\n\nvoid GaussNewtonSolver::solve(const std::vector<glm::vec2>& sparse_features, Face& face, cv::Mat& frame, glm::mat4& projection, const Pyramid& pyramid)\n{\n\tif (sparse_features.empty()) //no tracking -> cublas doesnt like a getting matrix/vector of size 0\n\t{\n\t\treturn;\n\t}\n\n\tauto number_of_levels = pyramid.getNumberOfLevels();\n\tif (sizeof(m_params.num_gn_iterations) / sizeof(int) != number_of_levels)\n\t{\n\t\tthrow std::runtime_error(\"Please specify number of GN iteration per pyramid level!\");\n\t}\n\n\tconst int nFeatures = sparse_features.size();\n\tconst int nShapeCoeffs = m_params.num_shape_coefficients;\n\tconst int nExpressionCoeffs = m_params.num_expression_coefficients;\n\tconst int nAlbedoCoeffs = m_params.num_albedo_coefficients;\n\tconst int nFaceCoeffs = nShapeCoeffs + nExpressionCoeffs + nAlbedoCoeffs;\n\tconst int nUnknowns = 7 + nFaceCoeffs + 9; //3+3+1 = 7 DoF for rotation, translation and intrinsics. Plus nFaceCoeffs for face parameters and 9 for lighting.\n\n\tconst float wSparse = std::powf(10, m_params.sparse_weight_exponent);\n\tconst float wDense = std::powf(10, m_params.dense_weight_exponent);\n\tconst float wReg = std::powf(10, m_params.regularisation_weight_exponent);\n\n\tfor (int pyramid_level = number_of_levels - 1; pyramid_level >= 0; pyramid_level--)\n\t{\n\t\tpyramid.setGraphicsSettings(pyramid_level, face.getGraphicsSettings());\n\n\t\tconst int frameWidth = face.m_graphics_settings.texture_width;\n\t\tconst int frameHeight = face.m_graphics_settings.texture_height;\n\t\tconst int nPixels = frameWidth * frameHeight;\n\t\tconst int nResiduals = 2 * nFeatures + 3 * nPixels + nFaceCoeffs; //nFaceCoeffs -> regularizer\n\n\t\tconst auto& prior_local_ids = PriorSparseFeatures::get().getPriorIds();\n\n\t\t//TODO: Allocate all of the objects below once. So, move them out of here.\n\t\tauto jacobian_gpu = util::DeviceArray<float>(nResiduals * nUnknowns);\n\t\tauto residuals_gpu = util::DeviceArray<float>(nResiduals);\n\t\tauto result_gpu = util::DeviceArray<float>(nUnknowns);\n\t\tstd::vector<float> result(nUnknowns);\n\t\tauto ids_gpu = util::DeviceArray<int>(prior_local_ids);\n\t\tauto key_pts_gpu = util::DeviceArray<glm::vec2>(sparse_features);\n\n\t\tcv::Mat processed_frame;\n\t\tcv::resize(frame, processed_frame, cv::Size(frameWidth, frameHeight));\n\t\tcv::cvtColor(processed_frame, processed_frame, cv::COLOR_BGR2RGB);\n\t\tutil::DeviceArray<uchar> frame_gpu = util::DeviceArray<uchar>(3 * nPixels);\n\t\tutil::copy(frame_gpu, processed_frame.data, 3 * nPixels);\n\n\t\tfor (int iteration = 0; iteration < m_params.num_gn_iterations[pyramid_level]; ++iteration)\n\t\t{\n\t\t\tjacobian_gpu.memset(0);\n\t\t\tresiduals_gpu.memset(0);\n\t\t\tface.computeFace();\n\t\t\tface.updateVertexBuffer();\n\t\t\tface.draw();\n\n\t\t\tauto face_pose = face.computeModelMatrix();\n\t\t\tEigen::Matrix<float, 3, 3> jacobian_local;\n\t\t\tjacobian_local <<\n\t\t\t\tface_pose[0][0], face_pose[1][0], face_pose[2][0],\n\t\t\t\tface_pose[0][1], face_pose[1][1], face_pose[2][1],\n\t\t\t\tface_pose[0][2], face_pose[1][2], face_pose[2][2];\n\n\t\t\tglm::mat3 drx, dry, drz;\n\t\t\tface.computeRotationDerivatives(drx, dry, drz);\n\n\t\t\tmapRenderTargets(face);\n\t\t\tFaceBoundingBox face_bb = computeFaceBoundingBox(face.m_graphics_settings.texture_width, face.m_graphics_settings.texture_height);\n\n\t\t\tint n_current_residuals = 2 * nFeatures + nFaceCoeffs + 3 * face_bb.width * face_bb.height;\n\n\t\t\tutil::copy(m_sh_coefficients_gpu, face.m_sh_coefficients, 9);\n\n\t\t\t//CUDA\n\t\t\tcomputeJacobian(\n\t\t\t\t//shared memory\n\t\t\t\tface_bb,\n\t\t\t\tnFeatures, frameWidth, frameHeight,\n\t\t\t\tnShapeCoeffs, nExpressionCoeffs, nAlbedoCoeffs, nUnknowns, n_current_residuals,\n\t\t\t\tface.m_number_of_vertices * 3,\n\t\t\t\tface.m_shape_coefficients.size(),\n\t\t\t\tface.m_expression_coefficients.size(),\n\t\t\t\tface.m_albedo_coefficients.size(),\n\t\t\t\tface.m_sh_coefficients.size(),\n\t\t\t\twSparse, wDense, wReg,\n\n\t\t\t\tframe_gpu.getPtr(),\n\n\t\t\t\tface_pose, drx, dry, drz, projection, jacobian_local,\n\n\t\t\t\t//device memory input\n\t\t\t\tids_gpu.getPtr(), face.m_current_face_gpu.getPtr(), key_pts_gpu.getPtr(),\n\n\t\t\t\tface.m_shape_basis_gpu.getPtr(),\n\t\t\t\tface.m_expression_basis_gpu.getPtr(),\n\t\t\t\tface.m_albedo_basis_gpu.getPtr(),\n\n\t\t\t\tface.m_shape_coefficients_gpu.getPtr(),\n\t\t\t\tface.m_expression_coefficients_gpu.getPtr(),\n\t\t\t\tface.m_albedo_coefficients_gpu.getPtr(),\n\t\t\t\tm_sh_coefficients_gpu.getPtr(),\n\n\t\t\t\t//device memory output\n\t\t\t\tjacobian_gpu.getPtr(), residuals_gpu.getPtr()\n\t\t\t);\n\n\t\t\tunmapRenderTargets(face);\n\n\t\t\t//Apply step and update poses GPU\n\t\t\tsolveUpdatePCG(m_cublas, nUnknowns, n_current_residuals, nResiduals, jacobian_gpu, residuals_gpu, result_gpu, 1.0f, -1.0f);\n\t\t\tutil::copy(result, result_gpu, nUnknowns);\n\n\t\t\tupdateParameters(result, projection, frame.cols / static_cast<float>(frame.rows), face, nShapeCoeffs, nExpressionCoeffs, nAlbedoCoeffs);\n\n\t\t\tstd::vector<float> residuals_loss_test(n_current_residuals);\n\t\t\tutil::copy(residuals_loss_test, residuals_gpu, n_current_residuals);\n\t\t\tEigen::Map<Eigen::VectorXf> residuals_loss_test_eigen(residuals_loss_test.data(), n_current_residuals);\n\t\t\tstd::cout << \"Unknowns: \" << nUnknowns << \", Residuals: \" << nResiduals << std::endl;\n\t\t\tstd::cout << \"Iteration: \" << iteration << \" , Loss: \" << glm::sqrt(residuals_loss_test_eigen.dot(residuals_loss_test_eigen)) << std::endl;\n\t\t}\n\t}\n}\n\nvoid GaussNewtonSolver::solveUpdatePCG(const cublasHandle_t& cublas, const int nUnknowns, const int nCurrentResiduals, const int nResiduals, util::DeviceArray<float>& jacobian,\n\tutil::DeviceArray<float>& residuals, util::DeviceArray<float>& x, const float alphaLHS, const float alphaRHS)\n{\n\tconst float alpha = 1, beta = 0;\n\tx.memset(0);\n\n\tauto r = util::DeviceArray<float>(nUnknowns);\t//current residual\n\tauto p = util::DeviceArray<float>(nUnknowns);\t//gradient \n\tauto M = util::DeviceArray<float>(nUnknowns);\t//preconditioner\n\tM.memset(0);\n\tauto z = util::DeviceArray<float>(nUnknowns);\t//preconditioned residual\n\tauto Jp = util::DeviceArray<float>(nCurrentResiduals);\n\tauto JTJp = util::DeviceArray<float>(nUnknowns);\n\n\t//M=inv(diag(JTJ))\n\tcomputeJacobiPreconditioner(nUnknowns, nCurrentResiduals, nResiduals, jacobian.getPtr(), M.getPtr());\n\n\t//r = -JTf;\n\tcublasSgemv(cublas, CUBLAS_OP_T, nCurrentResiduals, nUnknowns, &alphaRHS, jacobian.getPtr(), nCurrentResiduals, residuals.getPtr(), 1, &beta, r.getPtr(), 1);\n\n\t//z = Mr\n\telementwiseMultiplication(nUnknowns, M.getPtr(), r.getPtr(), z.getPtr());\n\n\t//p=z;\n\tcublasScopy(cublas, nUnknowns, z.getPtr(), 1, p.getPtr(), 1);\n\n\tfloat zTr_old = 0, zTr = 0;\n\tfloat pTJTJp;\n\t//zTr\n\tcublasSdot(cublas, nUnknowns, z.getPtr(), 1, r.getPtr(), 1, &zTr_old);\n\tint i = 0;\n\tfor (; i < std::min(nUnknowns, m_params.num_pcg_iterations); ++i)\n\t{\n\t\t//apply JTJ\n\t\tcublasSgemv(cublas, CUBLAS_OP_N, nCurrentResiduals, nUnknowns, &alphaLHS, jacobian.getPtr(), nCurrentResiduals, p.getPtr(), 1, &beta, Jp.getPtr(), 1);\n\t\tcublasSgemv(cublas, CUBLAS_OP_T, nCurrentResiduals, nUnknowns, &alpha, jacobian.getPtr(), nCurrentResiduals, Jp.getPtr(), 1, &beta, JTJp.getPtr(), 1);\n\n\t\tcublasSdot(cublas, nUnknowns, p.getPtr(), 1, JTJp.getPtr(), 1, &pTJTJp);\n\n\t\tfloat ak = zTr_old / std::max(pTJTJp, m_params.kNearZero);\n\t\t//x = ak*p + x\n\t\tcublasSaxpy(cublas, nUnknowns, &ak, p.getPtr(), 1, x.getPtr(), 1);\n\n\t\t//r = r - ak* JTJp\n\t\tak *= -1;\n\t\tcublasSaxpy(cublas, nUnknowns, &ak, JTJp.getPtr(), 1, r.getPtr(), 1);\n\n\t\t//z=Mr\n\t\telementwiseMultiplication(nUnknowns, M.getPtr(), r.getPtr(), z.getPtr());\n\n\t\t//zTr\n\t\tcublasSdot(cublas, nUnknowns, z.getPtr(), 1, r.getPtr(), 1, &zTr);\n\n\t\tif (zTr < m_params.kTolerance)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\n\t\tfloat bk = zTr / std::max(zTr_old, m_params.kNearZero);\n\n\t\t//p = z + bk*p        \n\t\tcublasSscal(cublas, nUnknowns, &bk, p.getPtr(), 1);\n\t\tcublasSaxpy(cublas, nUnknowns, &alpha, z.getPtr(), 1, p.getPtr(), 1);\n\n\t\tzTr_old = zTr;\n\t}\n\t//\tstd::cout << \"PCG iters: \" << i << std::endl; \n}\n\nvoid GaussNewtonSolver::solveUpdateCG(const cublasHandle_t& cublas, const int nUnknowns, const int nResiduals, util::DeviceArray<float>& jacobian,\n\tutil::DeviceArray<float>& residuals, util::DeviceArray<float>& x, const float alphaLHS, const float alphaRHS)\n{\n\tconst float alpha = 1, beta = 0;\n\tx.memset(0);\n\n\tauto r = util::DeviceArray<float>(nUnknowns);\t//current residual\n\tauto p = util::DeviceArray<float>(nUnknowns);\t//gradient \n\tauto Jp = util::DeviceArray<float>(nResiduals);\n\tauto JTJp = util::DeviceArray<float>(nUnknowns);\n\n\t//r = -JTf;\n\tcublasSgemv(cublas, CUBLAS_OP_T, nResiduals, nUnknowns, &alphaRHS, jacobian.getPtr(), nResiduals, residuals.getPtr(), 1, &beta, r.getPtr(), 1);\n\n\t//p=r;\n\tcublasScopy(cublas, nUnknowns, r.getPtr(), 1, p.getPtr(), 1);\n\n\tfloat rTr_old = 0, rTr;\n\tfloat pTJTJp;\n\t//rTr\n\tcublasSdot(cublas, nUnknowns, r.getPtr(), 1, r.getPtr(), 1, &rTr);\n\tint i = 0;\n\tauto num_of_iterations = std::min(nUnknowns, m_params.num_pcg_iterations);\n\tfor (; i < num_of_iterations; ++i)\n\t{\n\t\t//apply JTJ\n\t\tcublasSgemv(cublas, CUBLAS_OP_N, nResiduals, nUnknowns, &alphaLHS, jacobian.getPtr(), nResiduals, p.getPtr(), 1, &beta, Jp.getPtr(), 1);\n\t\tcublasSgemv(cublas, CUBLAS_OP_T, nResiduals, nUnknowns, &alpha, jacobian.getPtr(), nResiduals, Jp.getPtr(), 1, &beta, JTJp.getPtr(), 1);\n\n\t\trTr_old = rTr;\n\n\t\tcublasSdot(cublas, nUnknowns, p.getPtr(), 1, JTJp.getPtr(), 1, &pTJTJp);\n\n\t\tfloat ak = rTr / std::max(pTJTJp, m_params.kNearZero);\n\t\t//x = ak*p + x\n\t\tcublasSaxpy(cublas, nUnknowns, &ak, p.getPtr(), 1, x.getPtr(), 1);\n\n\t\t//r = r - ak* JTJp\n\t\tak *= -1;\n\t\tcublasSaxpy(cublas, nUnknowns, &ak, JTJp.getPtr(), 1, r.getPtr(), 1);\n\n\t\t//rTr\n\t\tcublasSdot(cublas, nUnknowns, r.getPtr(), 1, r.getPtr(), 1, &rTr);\n\n\t\tif (rTr < m_params.kTolerance)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\n\t\tfloat bk = rTr / std::max(rTr_old, m_params.kNearZero);\n\n\t\t//p = r + bk*p        \n\t\tcublasSscal(cublas, nUnknowns, &bk, p.getPtr(), 1);\n\t\tcublasSaxpy(cublas, nUnknowns, &alpha, r.getPtr(), 1, p.getPtr(), 1);\n\t}\n}\n\nvoid GaussNewtonSolver::updateParameters(const std::vector<float>& result, glm::mat4& projection, float aspect_ratio, Face& face,\n\tconst int nShapeCoeffs, const int nExpressionCoeffs, const int nAlbedoCoeffs)\n{\n\tprojection[0][0] += result[0];\n\tprojection[1][1] = projection[0][0] * aspect_ratio;\n\n\tface.m_rotation_coefficients.x += result[1];\n\tface.m_rotation_coefficients.y += result[2];\n\tface.m_rotation_coefficients.z += result[3];\n\n\tface.m_translation_coefficients.x += result[4];\n\tface.m_translation_coefficients.y += result[5];\n\tface.m_translation_coefficients.z += result[6];\n\n#pragma omp parallel num_threads(4)\n\t{\n#pragma omp single\n\t\t{\n\t\t\tfor (int i = 0; i < nShapeCoeffs; ++i)\n\t\t\t{\n\t\t\t\tface.m_shape_coefficients[i] += result[7 + i];\n\t\t\t}\n\t\t}\n\n#pragma omp single\n\t\t{\n\t\t\tfor (int i = 0; i < nExpressionCoeffs; ++i)\n\t\t\t{\n\t\t\t\tauto c = face.m_expression_coefficients[i] + result[7 + nShapeCoeffs + i];\n\t\t\t\tface.m_expression_coefficients[i] = glm::clamp(c, -0.5f, 0.5f);\n\t\t\t}\n\t\t}\n\n#pragma omp single\n\t\t{\n\t\t\tfor (int i = 0; i < nAlbedoCoeffs; ++i)\n\t\t\t{\n\t\t\t\tface.m_albedo_coefficients[i] += result[7 + nShapeCoeffs + nExpressionCoeffs + i];\n\t\t\t}\n\t\t}\n\n#pragma omp single\n\t\t{\n\t\t\tfor (int i = 0; i < 9; ++i)\n\t\t\t{\n\t\t\t\tface.m_sh_coefficients[i] += result[7 + nShapeCoeffs + nExpressionCoeffs + nAlbedoCoeffs + i];\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid GaussNewtonSolver::mapRenderTargets(Face& face)\n{\n\tif (face.m_graphics_settings.mapped_to_cuda)\n\t{\n\t\tstd::cout << \"Warning: mapRenderTargets is called while rts is already mapped!\" << std::endl;\n\t\treturn;\n\t}\n\n\tcudaGraphicsResource* resources[] = { face.m_graphics_settings.rt_rgb_cuda_resource,\n\t\tface.m_graphics_settings.rt_barycentrics_cuda_resource,\n\t\tface.m_graphics_settings.rt_vertex_ids_cuda_resource };\n\tCHECK_CUDA_ERROR(cudaGraphicsMapResources(3, resources, 0));\n\n\tcudaArray* array_rgb{ nullptr };\n\tcudaArray* array_barycentrics{ nullptr };\n\tcudaArray* array_vertex_ids{ nullptr };\n\n\tCHECK_CUDA_ERROR(cudaGraphicsSubResourceGetMappedArray(&array_rgb, resources[0], 0, 0));\n\tCHECK_CUDA_ERROR(cudaGraphicsSubResourceGetMappedArray(&array_barycentrics, resources[1], 0, 0));\n\tCHECK_CUDA_ERROR(cudaGraphicsSubResourceGetMappedArray(&array_vertex_ids, resources[2], 0, 0));\n\n\t//RGB texture\n\tcudaResourceDesc res_desc;\n\tmemset(&res_desc, 0, sizeof(res_desc));\n\tres_desc.resType = cudaResourceTypeArray;\n\tres_desc.res.array.array = array_rgb;\n\n\tcudaTextureDesc tex_desc;\n\tmemset(&tex_desc, 0, sizeof(tex_desc));\n\ttex_desc.addressMode[0] = cudaTextureAddressMode(cudaAddressModeWrap);\n\ttex_desc.addressMode[1] = cudaTextureAddressMode(cudaAddressModeWrap);\n\ttex_desc.filterMode = cudaTextureFilterMode(cudaFilterModeLinear);\n\ttex_desc.readMode = cudaReadModeNormalizedFloat;\n\ttex_desc.normalizedCoords = 0;\n\tCHECK_CUDA_ERROR(cudaCreateTextureObject(&m_texture_rgb, &res_desc, &tex_desc, nullptr));\n\n\t//Barycentrics texture\n\tres_desc.res.array.array = array_barycentrics;\n\ttex_desc.filterMode = cudaTextureFilterMode(cudaFilterModePoint);\n\ttex_desc.readMode = cudaReadModeElementType;\n\tCHECK_CUDA_ERROR(cudaCreateTextureObject(&m_texture_barycentrics, &res_desc, &tex_desc, nullptr));\n\n\t//Vertex ids texture\n\tres_desc.res.array.array = array_vertex_ids;\n\tCHECK_CUDA_ERROR(cudaCreateTextureObject(&m_texture_vertex_ids, &res_desc, &tex_desc, nullptr));\n\n\tface.m_graphics_settings.mapped_to_cuda = true;\n}\n\nvoid GaussNewtonSolver::unmapRenderTargets(Face& face)\n{\n\tif (!face.m_graphics_settings.mapped_to_cuda)\n\t{\n\t\tstd::cout << \"Warning: unmapRenderTargets is called while rts is already unmapped!\" << std::endl;\n\t\treturn;\n\t}\n\n\tdestroyTextures();\n\n\tcudaGraphicsResource* resources[] = { face.m_graphics_settings.rt_rgb_cuda_resource,\n\t\tface.m_graphics_settings.rt_barycentrics_cuda_resource,\n\t\tface.m_graphics_settings.rt_vertex_ids_cuda_resource };\n\tCHECK_CUDA_ERROR(cudaGraphicsUnmapResources(3, resources, 0));\n\n\tface.m_graphics_settings.mapped_to_cuda = false;\n}\n\nvoid GaussNewtonSolver::destroyTextures()\n{\n\tif (m_texture_rgb)\n\t{\n\t\tCHECK_CUDA_ERROR(cudaDestroyTextureObject(m_texture_rgb));\n\t\tm_texture_rgb = 0;\n\t}\n\tif (m_texture_barycentrics)\n\t{\n\t\tm_texture_barycentrics = 0;\n\t\tCHECK_CUDA_ERROR(cudaDestroyTextureObject(m_texture_barycentrics));\n\t}\n\tif (m_texture_vertex_ids)\n\t{\n\t\tCHECK_CUDA_ERROR(cudaDestroyTextureObject(m_texture_vertex_ids));\n\t\tm_texture_vertex_ids = 0;\n\t}\n}\n", "meta": {"hexsha": "259d7f824d471981ef326a5b94e755fa526c5aae", "size": 14413, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gauss_newton_solver.cpp", "max_stars_repo_name": "isikmustafa/face-tracking", "max_stars_repo_head_hexsha": "443c0e691e301ab3fb56568f932939fe2fb7baa4", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-04-23T23:48:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T02:02:37.000Z", "max_issues_repo_path": "src/gauss_newton_solver.cpp", "max_issues_repo_name": "Zielon/face-tracking", "max_issues_repo_head_hexsha": "443c0e691e301ab3fb56568f932939fe2fb7baa4", "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/gauss_newton_solver.cpp", "max_forks_repo_name": "Zielon/face-tracking", "max_forks_repo_head_hexsha": "443c0e691e301ab3fb56568f932939fe2fb7baa4", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-05-13T14:58:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-23T07:25:34.000Z", "avg_line_length": 35.239608802, "max_line_length": 176, "alphanum_fraction": 0.7292721848, "num_tokens": 4440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2727202687294685}}
{"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_EULER_FUNCTIONS_SIMD_COMMON_GAMMALN_HPP_INCLUDED\n#define NT2_EULER_FUNCTIONS_SIMD_COMMON_GAMMALN_HPP_INCLUDED\n\n#include <nt2/euler/functions/gammaln.hpp>\n#include <nt2/euler/functions/details/gammaln_kernel.hpp>\n#include <nt2/include/functions/simd/abs.hpp>\n#include <nt2/include/functions/simd/any.hpp>\n#include <nt2/include/functions/simd/dec.hpp>\n#include <nt2/include/functions/simd/divides.hpp>\n#include <nt2/include/functions/simd/floor.hpp>\n#include <nt2/include/functions/simd/fma.hpp>\n#include <nt2/include/functions/simd/if_allbits_else.hpp>\n#include <nt2/include/functions/simd/if_else.hpp>\n#include <nt2/include/functions/simd/inbtrue.hpp>\n#include <nt2/include/functions/simd/is_equal.hpp>\n#include <nt2/include/functions/simd/is_flint.hpp>\n#include <nt2/include/functions/simd/is_greater.hpp>\n#include <nt2/include/functions/simd/is_greater_equal.hpp>\n#include <nt2/include/functions/simd/is_less.hpp>\n#include <nt2/include/functions/simd/is_lez.hpp>\n#include <nt2/include/functions/simd/is_ltz.hpp>\n#include <nt2/include/functions/simd/log.hpp>\n#include <nt2/include/functions/simd/logical_and.hpp>\n#include <nt2/include/functions/simd/logical_andnot.hpp>\n#include <nt2/include/functions/simd/minus.hpp>\n#include <nt2/include/functions/simd/multiplies.hpp>\n#include <nt2/include/functions/simd/plus.hpp>\n#include <nt2/include/functions/simd/rec.hpp>\n#include <nt2/include/functions/simd/seladd.hpp>\n#include <nt2/include/functions/simd/seldec.hpp>\n#include <nt2/include/functions/simd/selinc.hpp>\n#include <nt2/include/functions/simd/selsub.hpp>\n#include <nt2/include/functions/simd/sinpi.hpp>\n#include <nt2/include/functions/simd/splat.hpp>\n#include <nt2/include/functions/simd/sqr.hpp>\n#include <nt2/include/functions/simd/unary_minus.hpp>\n#include <nt2/include/constants/false.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/invpi.hpp>\n#include <nt2/include/constants/logpi.hpp>\n#include <nt2/include/constants/logsqrt2pi.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/constants/mone.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/three.hpp>\n#include <nt2/include/constants/two.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/sdk/meta/as_logical.hpp>\n#include <nt2/sdk/meta/cardinal_of.hpp>\n#include <nt2/sdk/meta/scalar_of.hpp>\n\n#include <boost/simd/sdk/config.hpp>\n\n#ifndef BOOST_SIMD_NO_INFINITES\n#include <nt2/include/functions/simd/logical_or.hpp>\n#endif\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( gammaln_, tag::cpu_\n                            , (A0)(X)\n                            , ((simd_<double_<A0>,X>))\n                            )\n  {\n    typedef A0 result_type;\n    typedef typename meta::as_logical<A0>::type bA0;\n    NT2_FUNCTOR_CALL(1)\n    {\n      bA0 inf_result = logical_and(is_lez(a0), is_flint(a0));\n      A0 x = if_nan_else(inf_result, a0);\n      A0 q = nt2::abs(x);\n      #ifndef BOOST_SIMD_NO_INFINITES\n      inf_result = eq(q, Inf<A0>());\n      #endif\n      bA0 test = lt(a0, nt2::splat<A0>(-34.0));\n      size_t nb = nt2::inbtrue(test);\n      A0 r =  Nan<A0>();\n      if(nb > 0)\n      {\n        //treat negative large with reflection\n        r = large_negative(q);\n        if (nb >= meta::cardinal_of<A0>::value)\n          return nt2::if_else(inf_result, Nan<A0>(), r);\n      }\n      A0 r1 = other(a0);\n      A0 r2 = if_else(test, r, r1);\n      return nt2::if_else(eq(a0, Minf<A0>()),\n                          Nan<A0>(),\n                          nt2::if_else(inf_result, Inf<A0>(), r2)\n                         );\n    }\n  private :\n    static inline A0 large_negative(const A0& q)\n    {\n      A0 w = gammaln(q);\n      A0 p = nt2::floor(q);\n      A0 z = q - p;\n      bA0 test2 = lt(z, nt2::Half<A0>() );\n      z = nt2::selsub(test2, z, nt2::One<A0>());\n      z = q*nt2::sinpi(z);\n      z =  nt2::abs(z);\n      return Logpi<A0>()-log(z)-w;\n    }\n    static inline A0 other(const A0& xx)\n    {\n      A0 x =  xx;\n      bA0 test = lt(x, nt2::splat<A0>(13.0) );\n      size_t nb = inbtrue(test);\n      A0 r1 = Zero<A0>();\n      if (nb > 0)\n      {\n        A0 z = One<A0>();\n        A0 p = Zero<A0>();\n        A0 u = x;\n        bA0 test1 = ge(u,Three<A0>());\n        while(nt2::any(test1))\n        {\n          p = seldec(test1, p);\n          u = if_else(test1, x+p, u);\n          z = if_else(test1, z*u, z);\n          test1 = ge(u,Three<A0>());\n        }\n        //all u are less than 3\n        bA0 test2 = lt(u,Two<A0>());\n\n        while(nt2::any(test2))\n        {\n          z = if_else(test2, z/u, z);\n          p = selinc(test2, p);\n          u = if_else(test2, x+p, u);\n          test2 = lt(u,Two<A0>());\n        }\n        z = nt2::abs(z);\n        x +=  p-Two<A0>();\n        r1 = x * details::gammaln_kernel<A0>::gammaln1(x)+nt2::log(z);\n        if (nb >= meta::cardinal_of<A0>::value) return r1;\n      }\n      A0 r2 = fma(xx-Half<A0>(),nt2::log(xx), Logsqrt2pi<A0>()-xx);\n      A0 p = rec(sqr(xx));\n      r2 += details::gammaln_kernel<A0>::gammalnA(p)/xx;\n      return if_else(test, r1, r2);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( gammaln_, tag::cpu_\n                            , (A0)(X)\n                            , ((simd_<single_<A0>,X>))\n                            )\n  {\n\n    typedef A0 result_type;\n    typedef typename meta::as_logical<A0>::type bA0;\n    typedef typename meta::scalar_of<A0>::type sA0;\n    NT2_FUNCTOR_CALL(1)\n    {\n      bA0 inf_result = logical_and(is_lez(a0), is_flint(a0));\n      A0 x = if_nan_else(inf_result, a0);\n      A0 q = nt2::abs(x);\n      #ifndef BOOST_SIMD_NO_INFINITES\n      inf_result = logical_or(eq(x, Inf<A0>()), inf_result);\n      #endif\n      bA0 ltza0 = is_ltz(a0);\n      size_t nb = nt2::inbtrue(ltza0);\n      A0 r, r1 =  other(q);\n      if(nb > 0)\n      {\n        //treat negative\n        r = nt2::if_else(inf_result, Inf<A0>(), negative(q, r1));\n        if (nb >= meta::cardinal_of<A0>::value) return r;\n      }\n      A0 r2 = if_else(ltza0, r, r1);\n      return nt2::if_else(eq(a0, Minf<A0>()),\n                          Nan<A0>(),\n                          nt2::if_else(inf_result, Inf<A0>(), r2)\n                         );\n    }\n  private :\n    static inline A0 negative(const A0& q,  const A0& w)\n    {\n      A0 p = nt2::floor(q);\n      A0 z = q - p;\n      bA0 test2 = lt(z, nt2::Half<A0>() );\n      z = nt2::selsub(test2, z, nt2::One<A0>());\n      z = q*nt2::sinpi(z);\n      z =  nt2::abs(z);\n      return -log(Invpi<A0>()*nt2::abs(z))-w;\n    }\n    static inline A0 other(const A0& x)\n    {\n      bA0 xlt650 = lt(x, nt2::splat<A0>(6.50) );\n      size_t nb = inbtrue(xlt650);\n      A0 r0x = x;\n      A0 r0z = x;\n      A0 r0s = One<A0>();\n      A0 r1 = Zero<A0>();\n      A0 p =  Nan<A0>();\n      if (nb > 0)\n      {\n        bA0 kernelC = False<bA0>();\n        A0 z = One<A0>();\n        A0 tx = x;\n        A0 nx = Zero<A0>();\n\n        const A0 _075 = nt2::splat<A0>(0.75);\n        const A0 _150 = Two<A0>()*_075;\n        const A0 _125 = nt2::splat<A0>(1.25);\n        const A0 _250 = Two<A0>()*_125;\n        bA0 xge150 = ge(x, _150);\n        bA0 txgt250= gt(tx,_250);\n\n        // x >= 1.5\n        while (nt2::any(logical_and(xge150, txgt250)))\n        {\n          nx = seldec(txgt250, nx);\n          tx = if_else(txgt250, x + nx, tx);\n          z = if_else(txgt250, z*tx, z);\n          txgt250= gt(tx,_250);\n        }\n        r0x = seladd(xge150, x, nx - Two<A0>());\n        r0z = if_else(xge150, z, r0z);\n        r0s = if_else(xge150,One<A0>(), r0s);\n\n        // x >= 1.25 && x < 1.5\n        bA0 xge125 = ge(x, _125);\n        bA0 xge125t = l_andnot(xge125, xge150);\n        if (nt2::any(xge125))\n        {\n          r0x =  if_else(xge125t, dec(x)    , r0x);\n          r0z =  if_else(xge125t, z*x       , r0z);\n          r0s =  if_else(xge125t, Mone<A0>(), r0s);\n        }\n        // x >= 0.75&& x < 1.5\n        bA0 xge075  = ge(x, _075);\n        bA0 xge075t = l_andnot(xge075, xge125);\n        if (nt2::any(xge075t))\n        {\n          kernelC =  xge075t;\n          r0x =  if_else(xge075t, dec(x)    , r0x);\n          r0z =  if_else(xge075t, One<A0>() , r0z);\n          r0s =  if_else(xge075t, Mone<A0>(), r0s);\n          p = details::gammaln_kernel<A0>::gammalnC(r0x);\n        }\n        // tx < 1.5 && x < 0.75\n        bA0 txlt150 = l_andnot(lt(tx,_150), xge075);\n        if (nt2::any(txlt150))\n        {\n          bA0 orig = txlt150;\n          while( nt2::any(txlt150) )\n          {\n            z  = if_else(txlt150, z*tx, z);\n            nx = selinc(txlt150, nx);\n            tx = if_else(txlt150, x + nx, tx);\n            txlt150= l_andnot(lt(tx,_150), xge075);\n          }\n          r0x =  seladd(orig, r0x, nx - Two<A0>());\n          r0z =  if_else(orig,z         , r0z);\n          r0s =  if_else(orig,Mone<A0>(), r0s);\n        }\n        p =  if_else(kernelC, p, details::gammaln_kernel<A0>::gammalnB(r0x));\n        if (nb >= meta::cardinal_of<A0>::value)\n          return fma(r0x, p, r0s*nt2::log(nt2::abs(r0z)));\n      }\n      r0z = if_else(xlt650, nt2::abs(r0z), x);\n      A0 m = nt2::log(r0z);\n      r1 = fma(r0x, p, r0s*m);\n      A0 r2 = fma(x-Half<A0>(),m,Logsqrt2pi<A0>()-x);\n      r2 += details::gammaln_kernel<A0>::gammaln2(rec(sqr(x)))/x;\n      return if_else(xlt650, r1, r2);\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "1e88311fce7bd40f6b6cde8257a6f8bdb42a3c79", "size": 9833, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/euler/include/nt2/euler/functions/simd/common/gammaln.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/euler/include/nt2/euler/functions/simd/common/gammaln.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/euler/include/nt2/euler/functions/simd/common/gammaln.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": 34.6232394366, "max_line_length": 80, "alphanum_fraction": 0.5523238076, "num_tokens": 3110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2727202630621042}}
{"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#ifndef BOOST_MATH_QUADRATURE_WAVELET_TRANSFORMS_HPP\r\n#define BOOST_MATH_QUADRATURE_WAVELET_TRANSFORMS_HPP\r\n#include <boost/math/special_functions/daubechies_wavelet.hpp>\r\n#include <boost/math/quadrature/trapezoidal.hpp>\r\n\r\nnamespace boost::math::quadrature {\r\n\r\ntemplate<class F, typename Real, int p>\r\nclass daubechies_wavelet_transform\r\n{\r\npublic:\r\n    daubechies_wavelet_transform(F f, int grid_refinements = -1, Real tol = 100*std::numeric_limits<Real>::epsilon(),\r\n    int max_refinements = 12) : f_{f}, psi_(grid_refinements), tol_{tol}, max_refinements_{max_refinements}\r\n    {}\r\n\r\n    daubechies_wavelet_transform(F f, boost::math::daubechies_wavelet<Real, p> wavelet, Real tol = 100*std::numeric_limits<Real>::epsilon(),\r\n    int max_refinements = 12) : f_{f}, psi_{wavelet}, tol_{tol}, max_refinements_{max_refinements}\r\n    {}\r\n\r\n    auto operator()(Real s, Real t)->decltype(std::declval<F>()(std::declval<Real>())) const\r\n    {\r\n        using std::sqrt;\r\n        using std::abs;\r\n        using boost::math::quadrature::trapezoidal;\r\n        auto g = [&] (Real u) {\r\n            return f_(s*u+t)*psi_(u);\r\n        };\r\n        auto [a,b] = psi_.support();\r\n        return sqrt(abs(s))*trapezoidal(g, a, b, tol_, max_refinements_);\r\n    }\r\n\r\nprivate:\r\n    F f_;\r\n    boost::math::daubechies_wavelet<Real, p> psi_;\r\n    Real tol_;\r\n    int max_refinements_;\r\n};\r\n\r\n\r\n}\r\n#endif", "meta": {"hexsha": "44e25129b866ce628211fbe6e52624dfc9e67a22", "size": 1620, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/math/quadrature/wavelet_transforms.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/quadrature/wavelet_transforms.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/quadrature/wavelet_transforms.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": 34.4680851064, "max_line_length": 141, "alphanum_fraction": 0.6759259259, "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.4035668537353745, "lm_q1q2_score": 0.27271619916949325}}
{"text": "#ifndef VIENNACL_LINALG_DETAIL_AMG_AMG_INTERPOL_HPP\n#define VIENNACL_LINALG_DETAIL_AMG_AMG_INTERPOL_HPP\n\n/* =========================================================================\n   Copyright (c) 2010-2012, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n   Portions of this software are copyright by UChicago Argonne, LLC.\n\n                            -----------------\n                  ViennaCL - The Vienna Computing Library\n                            -----------------\n\n   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at\n               \n   (A list of authors and contributors can be found in the PDF manual)\n\n   License:         MIT (X11), see file LICENSE in the base directory\n============================================================================= */\n\n/** @file amg_interpol.hpp\n    @brief Implementations of several variants of the AMG interpolation operators (setup phase). Experimental.\n*/\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <cmath>\n#include \"viennacl/linalg/amg.hpp\"\n\n#include <map>\n#ifdef VIENNACL_WITH_OPENMP\n#include <omp.h>\n#endif\n\n#include \"amg_debug.hpp\"\n\nnamespace viennacl\n{\n  namespace linalg\n  {\n    namespace detail\n    {\n      namespace amg\n      {\n    \n    /** @brief Calls the right function to build interpolation matrix\n     * @param level    Coarse level identifier\n     * @param A      Operator matrix on all levels\n     * @param P      Prolongation matrices. P[level] is constructed\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_interpol(unsigned int level, InternalType1 & A, InternalType1 & P, InternalType2 & Pointvector, amg_tag & tag)\n    {\n      switch (tag.get_interpol())\n      {\n        case VIENNACL_AMG_INTERPOL_DIRECT: amg_interpol_direct (level, A, P, Pointvector, tag); break;\n        case VIENNACL_AMG_INTERPOL_CLASSIC: amg_interpol_classic (level, A, P, Pointvector, tag); break;\n        case VIENNACL_AMG_INTERPOL_AG: amg_interpol_ag (level, A, P, Pointvector, tag); break;\n        case VIENNACL_AMG_INTERPOL_SA: amg_interpol_sa (level, A, P, Pointvector, tag); break;\n      }\n    } \n    /** @brief Direct interpolation. Multi-threaded! (VIENNACL_AMG_INTERPOL_DIRECT)\n     * @param level    Coarse level identifier\n     * @param A      Operator matrix on all levels\n     * @param P      Prolongation matrices. P[level] is constructed\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_interpol_direct(unsigned int level, InternalType1 & A, InternalType1 & P, InternalType2 & Pointvector, amg_tag & tag)\n    {\n      typedef typename InternalType1::value_type SparseMatrixType;\n      typedef typename InternalType2::value_type PointVectorType;\n      typedef typename SparseMatrixType::value_type ScalarType;\n      typedef typename SparseMatrixType::iterator1 InternalRowIterator;\n      typedef typename SparseMatrixType::iterator2 InternalColIterator;\n      \n      ScalarType temp_res;\n      ScalarType row_sum, c_sum, diag;\n      //int diag_sign;\n      unsigned int x, y;\n      amg_point *pointx, *pointy;\n      unsigned int c_points = Pointvector[level].get_cpoints();\n\n      // Setup Prolongation/Interpolation matrix\n      P[level] = SparseMatrixType(A[level].size1(),c_points);\n      P[level].clear();\n      \n      // Assign indices to C points\n      Pointvector[level].build_index();\n      \n      // Direct Interpolation (Yang, p.14)\n#ifdef VIENNACL_WITH_OPENMP\n      #pragma omp parallel for private (pointx,pointy,row_sum,c_sum,temp_res,y,x,diag) shared (P,A,Pointvector,tag)\n#endif      \n      for (x=0; x < Pointvector[level].size(); ++x)\n      {\n        pointx = Pointvector[level][x];\n        /*if (A[level](x,x) > 0) \n          diag_sign = 1;\n        else\n          diag_sign = -1;*/\n        \n        // When the current line corresponds to a C point then the diagonal coefficient is 1 and the rest 0\n        if (pointx->is_cpoint())\n          P[level](x,pointx->get_coarse_index()) = 1;\n        \n        // When the current line corresponds to a F point then the diagonal is 0 and the rest has to be computed (Yang, p.14)\n        if (pointx->is_fpoint())\n        {\n          // Jump to row x\n          InternalRowIterator row_iter = A[level].begin1();\n          row_iter += x;\n          \n          // Row sum of coefficients (without diagonal) and sum of influencing C point coefficients has to be computed\n          row_sum = c_sum = diag = 0;\n          for (InternalColIterator col_iter = row_iter.begin(); col_iter != row_iter.end(); ++col_iter)\n          {\n            y = col_iter.index2();\n            if (x == y)// || *col_iter * diag_sign > 0)\n            {\n              diag += *col_iter;\n              continue;\n            }\n            \n            // Sum all other coefficients in line x\n            row_sum += *col_iter;\n\n            pointy = Pointvector[level][y];\n            // Sum all coefficients that correspond to a strongly influencing C point\n            if (pointy->is_cpoint())\n              if (pointx->is_influencing(pointy))\n                c_sum += *col_iter;        \n          }\n          temp_res = -row_sum/(c_sum*diag);\n\n          // Iterate over all strongly influencing points of point x\n          for (amg_point::iterator iter = pointx->begin_influencing(); iter != pointx->end_influencing(); ++iter)\n          {    \n            pointy = *iter;\n            // The value is only non-zero for columns that correspond to a C point\n            if (pointy->is_cpoint())\n            {\n              if (temp_res != 0)\n                P[level](x, pointy->get_coarse_index()) = temp_res * A[level](x,pointy->get_index());\n            }\n          }\n          \n          //Truncate interpolation if chosen\n          if (tag.get_interpolweight() != 0)\n            amg_truncate_row(P[level], x, tag);\n        }\n      }\n      \n      // P test\n      //test_interpolation(A[level], P[level], Pointvector[level]);\n      \n      #ifdef VIENNACL_AMG_DEBUG\n      std::cout << \"Prolongation Matrix:\" << std::endl;\n      printmatrix (P[level]);\n      #endif  \n    }\n    \n    /** @brief Classical interpolation. Don't use with onepass classical coarsening or RS0 (Yang, p.14)! Multi-threaded! (VIENNACL_AMG_INTERPOL_CLASSIC)\n     * @param level    Coarse level identifier\n     * @param A      Operator matrix on all levels\n     * @param P      Prolongation matrices. P[level] is constructed\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_interpol_classic(unsigned int level, InternalType1 & A, InternalType1 & P, InternalType2 & Pointvector, amg_tag & tag)\n    {\n      typedef typename InternalType1::value_type SparseMatrixType;\n      typedef typename InternalType2::value_type PointVectorType;\n      typedef typename SparseMatrixType::value_type ScalarType;\n      typedef typename SparseMatrixType::iterator1 InternalRowIterator;\n      typedef typename SparseMatrixType::iterator2 InternalColIterator;\n      \n      ScalarType temp_res;\n      ScalarType weak_sum, strong_sum;\n      int diag_sign;\n      amg_sparsevector<ScalarType> c_sum_row;\n      amg_point *pointx, *pointy, *pointk, *pointm;\n      unsigned int x, y, k, m;\n      \n      unsigned int c_points = Pointvector[level].get_cpoints();\n      \n      // Setup Prolongation/Interpolation matrix\n      P[level] = SparseMatrixType(A[level].size1(), c_points);\n      P[level].clear();\n      \n      // Assign indices to C points\n      Pointvector[level].build_index();\n      \n      // Classical Interpolation (Yang, p.13-14)\n#ifdef VIENNACL_WITH_OPENMP\n      #pragma omp parallel for private (pointx,pointy,pointk,pointm,weak_sum,strong_sum,c_sum_row,temp_res,x,y,k,m,diag_sign) shared (A,P,Pointvector)\n#endif      \n      for (x=0; x < Pointvector[level].size(); ++x)\n      {\n        pointx = Pointvector[level][x];\n        if (A[level](x,x) > 0) \n          diag_sign = 1;\n        else\n          diag_sign = -1;\n        \n        // When the current line corresponds to a C point then the diagonal coefficient is 1 and the rest 0\n        if (pointx->is_cpoint())\n          P[level](x,pointx->get_coarse_index()) = 1;\n\n        // When the current line corresponds to a F point then the diagonal is 0 and the rest has to be computed (Yang, p.14)\n        if (pointx->is_fpoint())\n        {  \n          // Jump to row x\n          InternalRowIterator row_iter = A[level].begin1();\n          row_iter += x;\n          \n          weak_sum = 0;\n          c_sum_row = amg_sparsevector<ScalarType>(A[level].size1());\n          c_sum_row.clear();\n          for (InternalColIterator col_iter = row_iter.begin(); col_iter != row_iter.end(); ++col_iter)\n          {\n            k = col_iter.index2();\n            pointk = Pointvector[level][k];\n            \n            // Sum of weakly influencing neighbors + diagonal coefficient\n            if (x == k || !pointx->is_influencing(pointk))// || *col_iter * diag_sign > 0)\n            {\n              weak_sum += *col_iter;\n              continue;\n            }\n              \n            // Sums of coefficients in row k (strongly influening F neighbors) of C point neighbors of x are calculated\n            if (pointk->is_fpoint() && pointx->is_influencing(pointk))\n            {\n              for (amg_point::iterator iter = pointx->begin_influencing(); iter != pointx->end_influencing(); ++iter)\n              {\n                pointm = *iter;\n                m = pointm->get_index();\n                \n                if (pointm->is_cpoint())\n                  // Only use coefficients that have opposite sign of diagonal.\n                  if (A[level](k,m) * diag_sign < 0)\n                    c_sum_row[k] += A[level](k,m);\n              }\n              continue;\n            }\n          }\n          \n          // Iterate over all strongly influencing points of point x\n          for (amg_point::iterator iter = pointx->begin_influencing(); iter != pointx->end_influencing(); ++iter)\n          {    \n            pointy = *iter;\n            y = pointy->get_index();\n            \n            // The value is only non-zero for columns that correspond to a C point\n            if (pointy->is_cpoint())\n            {\n              strong_sum = 0;\n              // Calculate term for strongly influencing F neighbors\n              for (typename amg_sparsevector<ScalarType>::iterator iter2 = c_sum_row.begin(); iter2 != c_sum_row.end(); ++iter2)\n              {\n                k = iter2.index();\n                // Only use coefficients that have opposite sign of diagonal.\n                if (A[level](k,y) * diag_sign < 0)\n                  strong_sum += (A[level](x,k) * A[level](k,y)) / (*iter2);\n              }\n              \n              // Calculate coefficient\n              temp_res = - (A[level](x,y) + strong_sum) / (weak_sum);\n              if (temp_res != 0)\n                P[level](x,pointy->get_coarse_index()) = temp_res;   \n            }\n          }\n          \n          //Truncate iteration if chosen\n          if (tag.get_interpolweight() != 0)\n            amg_truncate_row(P[level], x, tag);\n        }\n      }\n      \n      #ifdef VIENNACL_AMG_DEBUG\n      std::cout << \"Prolongation Matrix:\" << std::endl;\n      printmatrix (P[level]);\n      #endif  \n    }\n    \n    /** @brief Interpolation truncation (for VIENNACL_AMG_INTERPOL_DIRECT and VIENNACL_AMG_INTERPOL_CLASSIC)\n    *\n    * @param P    Interpolation matrix\n    * @param row  Row which has to be truncated\n    * @param tag  AMG preconditioner tag\n    */\n    template <typename SparseMatrixType>\n    void amg_truncate_row(SparseMatrixType & P, unsigned int row, amg_tag & tag)\n    {\n      typedef typename SparseMatrixType::value_type ScalarType;\n      typedef typename SparseMatrixType::iterator1 InternalRowIterator;\n      typedef typename SparseMatrixType::iterator2 InternalColIterator;\n      \n      ScalarType row_max, row_min, row_sum_pos, row_sum_neg, row_sum_pos_scale, row_sum_neg_scale;\n      \n      InternalRowIterator row_iter = P.begin1();\n      row_iter += row;\n      \n      row_max = 0;\n      row_min = 0;\n      row_sum_pos = 0;\n      row_sum_neg = 0;\n      \n      // Truncate interpolation by making values to zero that are a lot smaller than the biggest value in a row\n      // Determine max entry and sum of row (seperately for negative and positive entries)\n      for (InternalColIterator col_iter = row_iter.begin(); col_iter != row_iter.end(); ++col_iter)\n      {\n        if (*col_iter > row_max)\n          row_max = *col_iter;\n        if (*col_iter < row_min)\n          row_min = *col_iter;\n        if (*col_iter > 0)\n          row_sum_pos += *col_iter;\n        if (*col_iter < 0)\n          row_sum_neg += *col_iter;\n      }\n      \n      row_sum_pos_scale = row_sum_pos;\n      row_sum_neg_scale = row_sum_neg;\n      \n      // Make certain values to zero (seperately for negative and positive entries)\n      for (InternalColIterator col_iter = row_iter.begin(); col_iter != row_iter.end(); ++col_iter)\n      {\n        if (*col_iter > 0 && *col_iter < tag.get_interpolweight() * row_max)\n        {\n          row_sum_pos_scale -= *col_iter;\n          *col_iter = 0;\n        }\n        if (*col_iter < 0 && *col_iter > tag.get_interpolweight() * row_min)\n        {\n          row_sum_pos_scale -= *col_iter;\n          *col_iter = 0;\n        }\n      }\n      \n      // Scale remaining values such that row sum is unchanged\n      for (InternalColIterator col_iter = row_iter.begin(); col_iter != row_iter.end(); ++col_iter)\n      {\n        if (*col_iter > 0)\n          *col_iter = *col_iter *(row_sum_pos/row_sum_pos_scale);\n        if (*col_iter < 0)\n          *col_iter = *col_iter *(row_sum_neg/row_sum_neg_scale);\n      }\n    }\n    \n    /** @brief AG (aggregation based) interpolation. Multi-Threaded! (VIENNACL_INTERPOL_SA)\n     * @param level    Coarse level identifier\n     * @param A      Operator matrix on all levels\n     * @param P      Prolongation matrices. P[level] is constructed\n     * @param Pointvector  Vector of points on all levels\n    */\n    template <typename InternalType1, typename InternalType2>\n    void amg_interpol_ag(unsigned int level, InternalType1 & A, InternalType1 & P, InternalType2 & Pointvector, amg_tag)\n    {\n      typedef typename InternalType1::value_type SparseMatrixType;\n      typedef typename InternalType2::value_type PointVectorType;\n      typedef typename SparseMatrixType::value_type ScalarType;\n      typedef typename SparseMatrixType::iterator1 InternalRowIterator;\n      typedef typename SparseMatrixType::iterator2 InternalColIterator;\n      \n      unsigned int x;\n      amg_point *pointx, *pointy;\n      unsigned int c_points = Pointvector[level].get_cpoints();\n      \n      P[level] = SparseMatrixType(A[level].size1(), c_points);\n      P[level].clear();\n      \n      // Assign indices to C points\n      Pointvector[level].build_index();\n      \n      // Set prolongation such that F point is interpolated (weight=1) by the aggregate it belongs to (Vanek et al p.6)\n#ifdef VIENNACL_WITH_OPENMP\n      #pragma omp parallel for private (x,pointx) shared (P)\n#endif      \n      for (x=0; x<Pointvector[level].size(); ++x)\n      {\n        pointx = Pointvector[level][x];\n        pointy = Pointvector[level][pointx->get_aggregate()];\n        // Point x belongs to aggregate y.\n        P[level](x,pointy->get_coarse_index()) = 1;\n      }\n      \n      #ifdef VIENNACL_AMG_DEBUG\n      std::cout << \"Aggregation based Prolongation:\" << std::endl;\n      printmatrix(P[level]);\n      #endif\n    }\n      \n    /** @brief SA (smoothed aggregate) interpolation. Multi-Threaded! (VIENNACL_INTERPOL_SA)\n     * @param level    Coarse level identifier\n     * @param A      Operator matrix on all levels\n     * @param P      Prolongation matrices. P[level] is constructed\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_interpol_sa(unsigned int level, InternalType1 & A, InternalType1 & P, InternalType2 & Pointvector, amg_tag & tag)\n    {\n      typedef typename InternalType1::value_type SparseMatrixType;\n      typedef typename InternalType2::value_type PointVectorType;\n      typedef typename SparseMatrixType::value_type ScalarType;\n      typedef typename SparseMatrixType::iterator1 InternalRowIterator;\n      typedef typename SparseMatrixType::iterator2 InternalColIterator;\n      \n      unsigned int x,y;\n      ScalarType diag = 0;\n      unsigned int c_points = Pointvector[level].get_cpoints();\n           \n      InternalType1 P_tentative = InternalType1(P.size());\n      SparseMatrixType Jacobi = SparseMatrixType(A[level].size1(), A[level].size2());\n      Jacobi.clear();\n      P[level] = SparseMatrixType(A[level].size1(), c_points);\n      P[level].clear();      \n           \n      // Build Jacobi Matrix via filtered A matrix (Vanek et al. p.6)\n#ifdef VIENNACL_WITH_OPENMP\n      #pragma omp parallel for private (x,y,diag) shared (A,Pointvector)\n#endif      \n      for (x=0; x<A[level].size1(); ++x)\n      {\n        diag = 0;\n        InternalRowIterator row_iter = A[level].begin1();\n        row_iter += x;\n        for (InternalColIterator col_iter = row_iter.begin(); col_iter != row_iter.end(); ++col_iter)\n        {\n          y = col_iter.index2();\n          // Determine the structure of the Jacobi matrix by using a filtered matrix of A:\n          // The diagonal consists of the diagonal coefficient minus all coefficients of points not in the neighborhood of x.\n          // All other coefficients are the same as in A.\n          // Already use Jacobi matrix to save filtered A matrix to speed up computation.\n          if (x == y)\n            diag += *col_iter;\n          else if (!Pointvector[level][x]->is_influencing(Pointvector[level][y]))\n            diag += -*col_iter;\n          else\n            Jacobi (x,y) = *col_iter;      \n        }\n        InternalRowIterator row_iter2 = Jacobi.begin1();\n        row_iter2 += x;\n        // Traverse through filtered A matrix and compute the Jacobi filtering\n        for (InternalColIterator col_iter2 = row_iter2.begin(); col_iter2 != row_iter2.end(); ++col_iter2)\n        {\n            *col_iter2 = - static_cast<ScalarType>(tag.get_interpolweight())/diag * *col_iter2;\n        }\n        // Diagonal can be computed seperately.\n        Jacobi (x,x) = 1 - static_cast<ScalarType>(tag.get_interpolweight());\n      }\n          \n      #ifdef VIENNACL_AMG_DEBUG\n      std::cout << \"Jacobi Matrix:\" << std::endl;\n      printmatrix(Jacobi);\n      #endif\n      \n      // Use AG interpolation as tentative prolongation\n      amg_interpol_ag(level, A, P_tentative, Pointvector, tag);\n      \n      #ifdef VIENNACL_AMG_DEBUG\n      std::cout << \"Tentative Prolongation:\" << std::endl;\n      printmatrix(P_tentative[level]);\n      #endif\n      \n      // Multiply Jacobi matrix with tentative prolongation to get actual prolongation\n      amg_mat_prod(Jacobi,P_tentative[level],P[level]);\n      \n      #ifdef VIENNACL_AMG_DEBUG\n      std::cout << \"Prolongation Matrix:\" << std::endl;\n      printmatrix (P[level]);\n      #endif    \n    }\n      } //namespace amg\n    }\n  }\n}\n\n#endif\n", "meta": {"hexsha": "baa59f8ea933450ac09038606d9ff6d3f14588de", "size": 19514, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "viennacl/linalg/detail/amg/amg_interpol.hpp", "max_stars_repo_name": "bollig/viennacl", "max_stars_repo_head_hexsha": "6dac70e558ed42abe63d8c5bfd08465aafeda859", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-21T08:33:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T08:33:10.000Z", "max_issues_repo_path": "viennacl/linalg/detail/amg/amg_interpol.hpp", "max_issues_repo_name": "bollig/viennacl", "max_issues_repo_head_hexsha": "6dac70e558ed42abe63d8c5bfd08465aafeda859", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "viennacl/linalg/detail/amg/amg_interpol.hpp", "max_forks_repo_name": "bollig/viennacl", "max_forks_repo_head_hexsha": "6dac70e558ed42abe63d8c5bfd08465aafeda859", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2350515464, "max_line_length": 152, "alphanum_fraction": 0.6052577637, "num_tokens": 4695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2725273285758125}}
{"text": "// Copyright 2019 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include <ros/ros.h>\n#include <trajectory_following_controller/trajectory_following_controller.h>\n#include <trajectory_math/float_comparison.h>\n#include <trajectory_math/trajectory_algorithms.h>\n\n#include <Eigen/Geometry>\n#include <limits>\n\nnamespace bookbot {\n\nconstexpr double kPurePursuitLookaheadTime = 1;\nconstexpr double kPurePursuitMinLookaheadDistance = 0.5;\nconstexpr double kLongitudinalFeedbackGain = 0.1;\nconstexpr double kMaxCurvatureForNonzeroVelocity = 1.5;\nconstexpr double kMaxLateralAcceleration = 1.0;\nconstexpr double kMaxPositionError = 1.0;\nconstexpr double kMaxAngularVelocity = 1.0;\n\ndouble ComputePurePursuitCurvature(Eigen::Vector2d robot_position,\n                                   double robot_yaw, Eigen::Vector2d goal_pt) {\n  if (robot_position == goal_pt) {\n    return 0;\n  }\n\n  Eigen::Rotation2Dd R(-robot_yaw);\n\n  Eigen::Vector2d relative_goal_pt =\n      R * Eigen::Vector2d(goal_pt - robot_position);\n\n  double desired_curvature =\n      2 * relative_goal_pt[1] / relative_goal_pt.dot(relative_goal_pt);\n  return desired_curvature;\n}\n\nControlCommand ComputeControlCommand(const Eigen::Vector2d robot_position,\n                                     double robot_yaw,\n                                     const Trajectory& trajectory,\n                                     double current_time,\n                                     ControlIntrospection* introspection) {\n  // Match to trajectory spatially to compute longitudinal error\n  if (ApproxEqual(trajectory.front().distance_along_path,\n                  trajectory.back().distance_along_path, 0.01)) {\n    introspection->matched_point = trajectory.back();\n    introspection->spatially_matched_point = trajectory.back();\n    introspection->lookahead_point = trajectory.back().Position();\n    introspection->desired_curvature = 0.;\n    return {0., 0.};\n  }\n\n  const TrajectoryPoint spatially_matched_point = MatchToTrajectory(\n      robot_position, std::begin(trajectory), std::end(trajectory));\n\n  // Interpolate trajectory based on current time\n  const double current_point_time =\n      std::min(current_time, trajectory.back().time);\n\n  // Exit early if temporally or spatially past end of trajectory\n  if (ApproxEqual(spatially_matched_point.distance_along_path,\n                  trajectory.back().distance_along_path) ||\n      ApproxEqual(current_point_time, trajectory.back().time)) {\n    introspection->matched_point = trajectory.back();\n    introspection->spatially_matched_point = trajectory.back();\n    introspection->lookahead_point = trajectory.back().Position();\n    introspection->desired_curvature = 0.;\n    return {0., 0.};\n  }\n\n  // Exit early if too far away from trajectory\n  if (Eigen::Vector2d(robot_position - spatially_matched_point.Position())\n          .squaredNorm() > kMaxPositionError * kMaxPositionError) {\n    introspection->matched_point = spatially_matched_point;\n    introspection->spatially_matched_point = spatially_matched_point;\n    introspection->lookahead_point = spatially_matched_point.Position();\n    introspection->desired_curvature = 0.;\n    return {0., 0.};\n  }\n\n  TrajectoryPoint matched_point = InterpolateTrajectoryByTime(\n      current_point_time, std::begin(trajectory), std::end(trajectory));\n\n  const double longitudinal_error = matched_point.distance_along_path -\n                                    spatially_matched_point.distance_along_path;\n\n  const double commanded_forward_velocity =\n      matched_point.velocity + kLongitudinalFeedbackGain * longitudinal_error;\n\n  const double lookahead_relative_distance =\n      std::max(matched_point.velocity * kPurePursuitLookaheadTime,\n               kPurePursuitMinLookaheadDistance);\n  double lookahead_distance =\n      spatially_matched_point.distance_along_path + lookahead_relative_distance;\n\n  if (ApproxEqual(lookahead_distance, trajectory.back().distance_along_path) ||\n      lookahead_distance > trajectory.back().distance_along_path) {\n    const double distance_past_end =\n        lookahead_distance - trajectory.back().distance_along_path;\n    // Trajectory is too short for pure pursuit, just go in a straight line\n    introspection->matched_point = matched_point;\n    introspection->spatially_matched_point = spatially_matched_point;\n    introspection->lookahead_point = trajectory.back().Position();\n    introspection->desired_curvature = 0.;\n    return {commanded_forward_velocity, 0.};\n  }\n\n  TrajectoryPoint lookahead_trajectory_point =\n      InterpolateTrajectoryByDistanceAlongPath(\n          lookahead_distance, std::begin(trajectory), std::end(trajectory));\n  Eigen::Vector2d lookahead_point = lookahead_trajectory_point.Position();\n\n  const double desired_curvature =\n      ComputePurePursuitCurvature(robot_position, robot_yaw, lookahead_point);\n\n  // Limit commanded_forward_velocity based on curvature\n  double max_velocity_based_on_curvature =\n      std::numeric_limits<double>::infinity();\n  if (!ApproxZero(desired_curvature)) {\n    // Limit by maximum lateral acceleration\n    max_velocity_based_on_curvature =\n        std::sqrt(kMaxLateralAcceleration / std::abs(desired_curvature));\n  }\n  if (std::abs(desired_curvature) > kMaxCurvatureForNonzeroVelocity) {\n    max_velocity_based_on_curvature = 0;\n  }\n  const double limited_commanded_forward_velocity =\n      std::min(max_velocity_based_on_curvature, commanded_forward_velocity);\n\n  const double commanded_angular_velocity =\n      std::max(limited_commanded_forward_velocity, 1.0) * desired_curvature;\n\n  // Limit commanded_angular_velocity\n  const double limited_commanded_angular_velocity = std::copysign(\n      std::min(std::abs(commanded_angular_velocity), kMaxAngularVelocity),\n      commanded_angular_velocity);\n\n  introspection->matched_point = matched_point;\n  introspection->spatially_matched_point = spatially_matched_point;\n  introspection->lookahead_point = lookahead_point;\n  introspection->desired_curvature = desired_curvature;\n\n  return {limited_commanded_forward_velocity,\n          limited_commanded_angular_velocity};\n}\n\n}  // namespace bookbot\n", "meta": {"hexsha": "f856e202fdf18a3439f783e6402ec0fa62d7417f", "size": 6621, "ext": "cc", "lang": "C++", "max_stars_repo_path": "trajectory_following_controller/src/trajectory_following_controller.cc", "max_stars_repo_name": "google/bookbot-navigation", "max_stars_repo_head_hexsha": "5e5a17a022fe2d7137e7047e913020a3b7a0ff02", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-05-17T15:42:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-11T02:12:38.000Z", "max_issues_repo_path": "trajectory_following_controller/src/trajectory_following_controller.cc", "max_issues_repo_name": "google/bookbot-navigation", "max_issues_repo_head_hexsha": "5e5a17a022fe2d7137e7047e913020a3b7a0ff02", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trajectory_following_controller/src/trajectory_following_controller.cc", "max_forks_repo_name": "google/bookbot-navigation", "max_forks_repo_head_hexsha": "5e5a17a022fe2d7137e7047e913020a3b7a0ff02", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-05-03T16:24:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-10T13:07:43.000Z", "avg_line_length": 41.641509434, "max_line_length": 80, "alphanum_fraction": 0.7446005135, "num_tokens": 1433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.27245974548808255}}
{"text": "#include <data/Geometry.hpp>\n#include <engine/Neighbours.hpp>\n#include <engine/Vectormath.hpp>\n#include <utility/Exception.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"Qhull.h\"\n#include \"QhullFacetList.h\"\n#include \"QhullVertexSet.h\"\n\n#include <array>\n\nnamespace Data\n{\n    Geometry::Geometry(std::vector<Vector3> bravais_vectors, intfield n_cells, std::vector<Vector3> cell_atoms,\n        intfield cell_atom_types, scalar lattice_constant) :\n        bravais_vectors(bravais_vectors), n_cells(n_cells),\n        n_cell_atoms(cell_atoms.size()), cell_atoms(cell_atoms), lattice_constant(lattice_constant),\n        nos(cell_atoms.size() * n_cells[0] * n_cells[1] * n_cells[2]), cell_atom_types(cell_atom_types),\n        n_cells_total(n_cells[0] * n_cells[1] * n_cells[2])\n    {\n        for (int iatom = 0; iatom < n_cell_atoms; ++iatom)\n        {\n            // Get x,y,z of component of atom positions in unit of length (instead of in units of a,b,c)\n            Vector3 build_array = bravais_vectors[0] * cell_atoms[iatom][0] + bravais_vectors[1] * cell_atoms[iatom][1] + bravais_vectors[2] * cell_atoms[iatom][2];\n            cell_atoms[iatom] = lattice_constant * build_array;\n        }\n\n        // Generate positions and atom types\n        this->positions = vectorfield(nos);\n        this->atom_types = intfield(nos, 0);\n        Engine::Vectormath::Build_Spins(positions, atom_types, cell_atoms, cell_atom_types, bravais_vectors, n_cells);\n\n        // Calculate some info\n        this->calculateBounds();\n        this->calculateUnitCellBounds();\n        this->calculateDimensionality();\n\n        // Calculate center of the System\n        this->center = 0.5 *  (this->bounds_min + this->bounds_max);\n\n        // Calculate the type of geometry\n        this->calculateGeometryType();\n\n        // For updates of triangulation and tetrahedra\n        this->last_update_n_cell_step = -1;\n        this->last_update_n_cells = intfield(3, -1);\n    }\n\n\n\n    std::vector<tetrahedron_t> compute_delaunay_triangulation_3D(const std::vector<vector3_t> & points)\n    {\n        const int ndim = 3;\n        std::vector<tetrahedron_t> tetrahedra;\n        tetrahedron_t tmp_tetrahedron;\n        int *current_index;\n\n        orgQhull::Qhull qhull;\n        qhull.runQhull(\"\", ndim, points.size(), (coordT *) points.data(),  \"d Qt Qbb Qz\");\n        orgQhull::QhullFacetList facet_list = qhull.facetList();\n        for(const auto & facet : facet_list)\n        {\n            if(!facet.isUpperDelaunay())\n            {\n                current_index = &tmp_tetrahedron[0];\n                for(const auto & vertex : facet.vertices())\n                {\n                    *current_index++ = vertex.point().id();\n                }\n                tetrahedra.push_back(tmp_tetrahedron);\n            }\n        }\n        return tetrahedra;\n    }\n\n    std::vector<triangle_t> compute_delaunay_triangulation_2D(const std::vector<vector2_t> & points)\n    {\n        const int ndim = 2;\n        std::vector<triangle_t> triangles;\n        triangle_t tmp_triangle;\n        int *current_index;\n\n        orgQhull::Qhull qhull;\n        qhull.runQhull(\"\", ndim, points.size(), (coordT *) points.data(),  \"d Qt Qbb Qz\");\n        for(const auto & facet : qhull.facetList())\n        {\n            if(!facet.isUpperDelaunay())\n            {\n                current_index = &tmp_triangle[0];\n                for(const auto & vertex : facet.vertices())\n                {\n                    *current_index++ = vertex.point().id();\n                }\n                triangles.push_back(tmp_triangle);\n            }\n        }\n        return triangles;\n    }\n\n    const std::vector<triangle_t>& Geometry::triangulation(int n_cell_step)\n    {\n        // Only every n_cell_step'th cell is used. So we check if there is still enough cells in all\n        //      directions. Note: when visualising, 'n_cell_step' can be used to e.g. olny visualise\n        //      every 2nd spin.\n        if ( (n_cells[0]/n_cell_step < 2 && n_cells[0] > 1) ||\n             (n_cells[1]/n_cell_step < 2 && n_cells[1] > 1) ||\n             (n_cells[2]/n_cell_step < 2 && n_cells[2] > 1) )\n        {\n            _triangulation.clear();\n            return _triangulation;\n        }\n\n        // 2D: triangulation\n        if (dimensionality == 2)\n        {\n            // Check if the tetrahedra for this combination of n_cells and n_cell_step has already been calculated\n            if (this->last_update_n_cell_step != n_cell_step ||\n                this->last_update_n_cells[0]  != n_cells[0]  ||\n                this->last_update_n_cells[1]  != n_cells[1]  ||\n                this->last_update_n_cells[2]  != n_cells[2]  )\n            {\n                this->last_update_n_cell_step = n_cell_step;\n                this->last_update_n_cells[0]  = n_cells[0];\n                this->last_update_n_cells[1]  = n_cells[1];\n                this->last_update_n_cells[2]  = n_cells[2];\n                \n                _triangulation.clear();\n\n                std::vector<vector2_t> points;\n                points.resize(positions.size());\n\n                int icell = 0, idx;\n                for (int cell_c=0; cell_c<n_cells[2]; cell_c+=n_cell_step)\n                {\n                    for (int cell_b=0; cell_b<n_cells[1]; cell_b+=n_cell_step)\n                    {\n                        for (int cell_a=0; cell_a<n_cells[0]; cell_a+=n_cell_step)\n                        {\n                            for (int ibasis=0; ibasis < n_cell_atoms; ++ibasis)\n                            {\n                                idx = ibasis + n_cell_atoms*cell_a + n_cell_atoms*n_cells[0]*cell_b + n_cell_atoms*n_cells[0]*n_cells[1]*cell_c;\n                                points[icell].x = positions[idx][0];\n                                points[icell].y = positions[idx][1];\n                                ++icell;\n                            }\n                        }\n                    }\n                }\n                _triangulation = compute_delaunay_triangulation_2D(points);\n            }\n        }// endif 2D\n        // 0D, 1D and 3D give no triangulation\n        else\n        {\n            _triangulation.clear();\n        }\n        return _triangulation;\n    }\n\n    const std::vector<tetrahedron_t>& Geometry::tetrahedra(int n_cell_step)\n    {\n        // Only every n_cell_step'th cell is used. So we check if there is still enough cells in all\n        //      directions. Note: when visualising, 'n_cell_step' can be used to e.g. olny visualise\n        //      every 2nd spin.\n        if (n_cells[0]/n_cell_step < 2 || n_cells[1]/n_cell_step < 2 || n_cells[2]/n_cell_step < 2)\n        {\n            _tetrahedra.clear();\n            return _tetrahedra;\n        }\n\n        // 3D: Tetrahedra\n        if (dimensionality == 3)\n        {\n            // Check if the tetrahedra for this combination of n_cells and n_cell_step has already been calculated\n            if (this->last_update_n_cell_step != n_cell_step ||\n                this->last_update_n_cells[0]  != n_cells[0]  ||\n                this->last_update_n_cells[1]  != n_cells[1]  ||\n                this->last_update_n_cells[2]  != n_cells[2]  )\n            {\n                this->last_update_n_cell_step = n_cell_step;\n                this->last_update_n_cells[0]  = n_cells[0];\n                this->last_update_n_cells[1]  = n_cells[1];\n                this->last_update_n_cells[2]  = n_cells[2];\n\n                // If we have only one spin in the basis our lattice is a simple regular geometry\n                bool is_simple_regular_geometry = n_cell_atoms == 1;\n\n                // If we have a simple regular geometry everything can be calculated by hand\n                if (is_simple_regular_geometry)\n                {\n                    _tetrahedra.clear();\n                    int cell_indices[] = {\n                        0, 1, 5, 3,\n                        1, 3, 2, 5,\n                        3, 2, 5, 6,\n                        7, 6, 5, 3,\n                        4, 7, 5, 3,\n                        0, 4, 3, 5\n                        };\n                    int x_offset = 1;\n                    int y_offset = n_cells[0]/n_cell_step;\n                    int z_offset = n_cells[0]/n_cell_step*n_cells[1]/n_cell_step;\n                    int offsets[] = {\n                        0, x_offset, x_offset+y_offset, y_offset,\n                        z_offset, x_offset+z_offset, x_offset+y_offset+z_offset, y_offset+z_offset\n                        };\n                \n                    for (int ix = 0; ix < (n_cells[0]-1)/n_cell_step; ix++)\n                    {\n                        for (int iy = 0; iy < (n_cells[1]-1)/n_cell_step; iy++)\n                        {\n                            for (int iz = 0; iz < (n_cells[2]-1)/n_cell_step; iz++)\n                            {\n                                int base_index = ix*x_offset+iy*y_offset+iz*z_offset;\n                                for (int j = 0; j < 6; j++)\n                                {\n                                    tetrahedron_t tetrahedron;\n                                    for (int k = 0; k < 4; k++)\n                                    {\n                                        int index = base_index + offsets[cell_indices[j*4+k]];\n                                        tetrahedron[k] = index;\n                                    }\n                                    _tetrahedra.push_back(tetrahedron);\n                                }\n                            }\n                        }\n                    }\n                }\n                // For general basis cells we calculate the Delaunay tetrahedra\n                else \n                {\n                    std::vector<vector3_t> points;\n                    points.resize(positions.size());\n\n                    int icell = 0, idx;\n                    for (int cell_c=0; cell_c<n_cells[2]; cell_c+=n_cell_step)\n                    {\n                        for (int cell_b=0; cell_b<n_cells[1]; cell_b+=n_cell_step)\n                        {\n                            for (int cell_a=0; cell_a<n_cells[0]; cell_a+=n_cell_step)\n                            {\n                                for (int ibasis=0; ibasis < n_cell_atoms; ++ibasis)\n                                {\n                                    idx = ibasis + n_cell_atoms*cell_a + n_cell_atoms*n_cells[0]*cell_b + n_cell_atoms*n_cells[0]*n_cells[1]*cell_c;\n                                    points[icell].x = positions[idx][0];\n                                    points[icell].y = positions[idx][1];\n                                    points[icell].z = positions[idx][2];\n                                    ++icell;\n                                }\n                            }\n                        }\n                    }\n                    _tetrahedra = compute_delaunay_triangulation_3D(points);\n                }\n            }\n        } // endif 3D\n        // 0-2 D gives no tetrahedra\n        else\n        {\n            _tetrahedra.clear();\n        }\n        return _tetrahedra;\n    }\n\n\n    std::vector<Vector3> Geometry::BravaisVectorsSC()\n    {\n        return { { 1,0,0 },\n                 { 0,1,0 },\n                 { 0,0,1 } };\n    }\n\n    std::vector<Vector3> Geometry::BravaisVectorsFCC()\n    {\n        return { { 0.5,0.0,0.5 },\n                 { 0.5,0.5,0.0 },\n                 { 0.0,0.5,0.5 } };\n    }\n\n    std::vector<Vector3> Geometry::BravaisVectorsBCC()\n    {\n        return { { 0.5, 0.5,-0.5 },\n                 { -0.5, 0.5,-0.5 },\n                 { 0.5,-0.5, 0.5 } };\n    }\n\n    std::vector<Vector3> Geometry::BravaisVectorsHex2D60()\n    {\n        return { { 1,   0,                0 },\n                 { 0.5, 0.5*std::sqrt(3), 0 },\n                 { 0,   0,                1 } };\n    }\n\n    std::vector<Vector3> Geometry::BravaisVectorsHex2D120()\n    {\n        return { {  1,   0,                0 },\n                 { -0.5, 0.5*std::sqrt(3), 0 },\n                 {  0,   0,                1 } };\n    }\n\n\n    void Geometry::calculateDimensionality()\n    {\n        int dims_basis = 0, dims_translations = 0;\n        Vector3 test_vec_basis, test_vec_translations;\n\n        // ----- Find dimensionality of the basis -----\n        if      (n_cell_atoms == 1) dims_basis = 0;\n        else if (n_cell_atoms == 2) dims_basis = 1;\n        else if (n_cell_atoms == 3) dims_basis = 2;\n        else\n        {\n            // Get basis atoms relative to the first atom\n            Vector3 v0 = cell_atoms[0];\n            std::vector<Vector3> b_vectors(n_cell_atoms-1);\n            for (int i = 1; i < n_cell_atoms; ++i)\n            {\n                b_vectors[i-1] = cell_atoms[i] - v0;\n            }\n            // Calculate basis dimensionality\n            // test vec is along line\n            test_vec_basis = b_vectors[0];\n            //\t\tis it 1D?\n            int n_parallel = 0;\n            for (unsigned int i = 1; i < b_vectors.size(); ++i)\n            {\n                if (std::abs(b_vectors[i].dot(test_vec_basis) - 1.0) < 1e-9) ++n_parallel;\n                // else n_parallel will give us the last parallel vector\n                // also the if-statement for dims_basis=1 wont be met\n                else break;\n            }\n            if (n_parallel == b_vectors.size() - 1)\n            {\n                dims_basis = 1;\n            }\n            else\n            {\n                // test vec is normal to plane\n                test_vec_basis = b_vectors[0].cross(b_vectors[n_parallel+1]);\n                //\t\tis it 2D?\n                int n_in_plane = 0;\n                for (unsigned int i = 2; i < b_vectors.size(); ++i)\n                {\n                    if (std::abs(b_vectors[i].dot(test_vec_basis)) < 1e-9) ++n_in_plane;\n                }\n                if (n_in_plane == b_vectors.size() - 2)\n                {\n                    dims_basis = 2;\n                }\n                else\n                {\n                    this->dimensionality = 3;\n                    return;\n                }\n            }\n        }\n\n\n        // ----- Find dimensionality of the translations -----\n        //\t\tThe following are zero if the corresponding pair is parallel\n        double t01, t02, t12;\n        t01 = std::abs(bravais_vectors[0].dot(bravais_vectors[1]) - 1.0);\n        t02 = std::abs(bravais_vectors[0].dot(bravais_vectors[2]) - 1.0);\n        t12 = std::abs(bravais_vectors[1].dot(bravais_vectors[2]) - 1.0);\n        //\t\tCheck if pairs are linearly independent\n        int n_independent_pairs = 0;\n        if (t01>1e-9 && n_cells[0] > 1 && n_cells[1] > 1) ++n_independent_pairs;\n        if (t02>1e-9 && n_cells[0] > 1 && n_cells[2] > 1) ++n_independent_pairs;\n        if (t12>1e-9 && n_cells[1] > 1 && n_cells[2] > 1) ++n_independent_pairs;\n        //\t\tCalculate translations dimensionality\n        if (n_cells[0] == 1 && n_cells[1] == 1 && n_cells[2] == 1) dims_translations = 0;\n        else if (n_independent_pairs == 0)\n        {\n            dims_translations = 1;\n            // test vec is along the line\n            for (int i=0; i<3; ++i) if (n_cells[i] > 1) test_vec_translations = bravais_vectors[i];\n        }\n        else if (n_independent_pairs < 3)\n        {\n            dims_translations = 2;\n            // test vec is normal to plane\n            int n = 0;\n            std::vector<Vector3> plane(2);\n            for (int i = 0; i < 3; ++i)\n            {\n                if (n_cells[i] > 1) plane[n] = bravais_vectors[i];\n                ++n;\n            }\n            test_vec_translations = plane[0].cross(plane[1]);\n        }\n        else\n        {\n            this->dimensionality = 3;\n            return;\n        }\n\n\n        // ----- Calculate dimensionality of system -----\n        test_vec_basis.normalize();\n        test_vec_translations.normalize();\n        //\t\tIf one dimensionality is zero, only the other counts\n        if (dims_basis == 0)\n        {\n            this->dimensionality = dims_translations;\n            return;\n        }\n        else if (dims_translations == 0)\n        {\n            this->dimensionality = dims_basis;\n            return;\n        }\n        //\t\tIf both are linear or both are planar, the test vectors should be parallel if the geometry is 1D or 2D\n        else if (dims_basis == dims_translations)\n        {\n            if (std::abs(test_vec_basis.dot(test_vec_translations) - 1.0) < 1e-9)\n            {\n                this->dimensionality = dims_basis;\n                return;\n            }\n            else if (dims_basis == 1)\n            {\n                this->dimensionality = 2;\n                return;\n            }\n            else if (dims_basis == 2)\n            {\n                this->dimensionality = 3;\n                return;\n            }\n        }\n        //\t\tIf one is linear (1D), and the other planar (2D) then the test vectors should be orthogonal if the geometry is 2D\n        else if ( (dims_basis == 1 && dims_translations == 2) || (dims_basis == 2 && dims_translations == 1) )\n        {\n            if (std::abs(test_vec_basis.dot(test_vec_translations)) < 1e-9)\n            {\n                this->dimensionality = 2;\n                return;\n            }\n            else\n            {\n                this->dimensionality = 3;\n                return;\n            }\n        }\n    }\n\n    void Geometry::calculateBounds()\n    {\n        this->bounds_max.setZero();\n        this->bounds_min.setZero();\n        for (int iatom = 0; iatom < nos; ++iatom)\n        {\n            for (int dim = 0; dim < 3; ++dim)\n            {\n                if (this->positions[iatom][dim] < this->bounds_min[dim]) this->bounds_min[dim] = positions[iatom][dim];\n                if (this->positions[iatom][dim] > this->bounds_max[dim]) this->bounds_max[dim] = positions[iatom][dim];\n            }\n        }\n    }\n\n    void Geometry::calculateUnitCellBounds()\n    {\n        this->cell_bounds_max.setZero();\n        this->cell_bounds_min.setZero();\n        for (unsigned int ivec = 0; ivec < bravais_vectors.size(); ++ivec)\n        {\n            for (int iatom = 0; iatom < n_cell_atoms; ++iatom)\n            {\n                auto neighbour1 = cell_atoms[iatom] + bravais_vectors[ivec];\n                auto neighbour2 = cell_atoms[iatom] - bravais_vectors[ivec];\n                for (int dim = 0; dim < 3; ++dim)\n                {\n                    if (neighbour1[dim] < this->cell_bounds_min[dim]) this->cell_bounds_min[dim] = neighbour1[dim];\n                    if (neighbour1[dim] > this->cell_bounds_max[dim]) this->cell_bounds_max[dim] = neighbour1[dim];\n                    if (neighbour2[dim] < this->cell_bounds_min[dim]) this->cell_bounds_min[dim] = neighbour2[dim];\n                    if (neighbour2[dim] > this->cell_bounds_max[dim]) this->cell_bounds_max[dim] = neighbour2[dim];\n                }\n            }\n        }\n        this->cell_bounds_min *= 0.5;\n        this->cell_bounds_max *= 0.5;\n    }\n\n    void Geometry::calculateGeometryType()\n    {\n        // Automatically try to determine GeometryType\n        // Single-atom unit cell\n        if (cell_atoms.size() == 1)\n        {\n            // If the basis vectors are orthogonal, it is a rectilinear lattice\n            if (std::abs(bravais_vectors[0].dot(bravais_vectors[1])) < 1e-6 &&\n                std::abs(bravais_vectors[0].dot(bravais_vectors[2])) < 1e-6)\n            {\n                // If equidistant it is simple cubic\n                if (bravais_vectors[0].norm() == bravais_vectors[1].norm() == bravais_vectors[2].norm())\n                    this->classifier = BravaisLatticeType::SC;\n                // Otherwise only rectilinear\n                else\n                    this->classifier = BravaisLatticeType::Rectilinear;\n            }\n        }\n        // Regular unit cell with multiple atoms (e.g. bcc, fcc, hex)\n        //else if (n_cell_atoms == 2)\n        // Irregular unit cells arranged on a lattice (e.g. B20 or custom)\n        /*else if (n_cells[0] > 1 || n_cells[1] > 1 || n_cells[2] > 1)\n        {\n            this->classifier = BravaisLatticeType::Lattice;\n        }*/\n        // A single irregular unit cell\n        else\n        {\n            this->classifier = BravaisLatticeType::Irregular;\n        }\n    }\n}\n\n", "meta": {"hexsha": "c42fab159d8e0a661618a586400baec6fa8d340b", "size": 20185, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/src/data/Geometry.cpp", "max_stars_repo_name": "SpiritSuperUser/spirit", "max_stars_repo_head_hexsha": "fbe69c2a9b7a73e8f47d302c619303aea2a22ace", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T13:54:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T09:10:27.000Z", "max_issues_repo_path": "core/src/data/Geometry.cpp", "max_issues_repo_name": "SpiritSuperUser/spirit", "max_issues_repo_head_hexsha": "fbe69c2a9b7a73e8f47d302c619303aea2a22ace", "max_issues_repo_licenses": ["MIT"], "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/data/Geometry.cpp", "max_forks_repo_name": "SpiritSuperUser/spirit", "max_forks_repo_head_hexsha": "fbe69c2a9b7a73e8f47d302c619303aea2a22ace", "max_forks_repo_licenses": ["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.8173076923, "max_line_length": 164, "alphanum_fraction": 0.4876888779, "num_tokens": 5041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.27238873260277924}}
{"text": "#include <boost/python/module.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/def.hpp>\n#include <boost/python/list.hpp>\n#include <scitbx/vec2.h>\n#include <scitbx/vec3.h>\n#include <scitbx/array_family/flex_types.h>\n#include <scitbx/array_family/shared.h>\n#include <dxtbx/model/detector.h>\n#include <dxtbx/model/panel.h>\n#include <math.h>\n#include <vector>\n\nnamespace kapton {\n\nusing dxtbx::model::Detector;\nusing scitbx::vec2;\nusing scitbx::vec3;\n\n/**\n * Implementing a c++ version of the get_kapton_path function. Significant speedups\n * observed\n */\n\nscitbx::af::shared<double> get_kapton_path_cpp(\n  boost::python::list kapton_faces,\n  scitbx::af::const_ref<vec3<double> > s1_flex) {\n  scitbx::af::shared<double> kapton_path_mm;\n  int nfaces = boost::python::len(kapton_faces);\n  std::vector<Detector> all_kapton_faces;\n  // Store all the detectors ahead of time to avoid making expensive extract calls every\n  // time\n  for (std::size_t i = 0; i < nfaces; ++i) {\n    all_kapton_faces.push_back(boost::python::extract<Detector>(kapton_faces[i]));\n  }\n  for (scitbx::af::const_ref<vec3<double> >::const_iterator it = s1_flex.begin();\n       it != s1_flex.end();\n       ++it) {\n    double max_d2 = -999.9;\n    scitbx::af::shared<vec3<double> > intersection_xy_list;\n    // Find out intersection points of s1 vector with all faces of kapton volume\n    for (std::size_t j = 0; j < nfaces; ++j) {\n      Detector detector = all_kapton_faces.at(j);\n      try {\n        vec2<double> px = detector[0].get_ray_intersection_px(*it);\n        if (px[0] > 0.0 && px[1] > 0.0 && px[0] < detector[0].get_image_size()[0]\n            && px[1] < detector[0].get_image_size()[1]) {\n          intersection_xy_list.push_back(\n            detector[0].get_lab_coord(detector[0].get_ray_intersection(*it)));\n        }\n      } catch (dxtbx::error) {\n        // Do nothing\n      }\n    }  // kapton faces\n    /*\n     * Now find out the maximum path length through the kapton. That is the path\n     * traversed by s1 vector if no intersection or intersects with only one face then\n     * path length is set to 0.0\n     */\n    if (intersection_xy_list.size() == 0) {\n      kapton_path_mm.push_back(0.0);\n    } else if (intersection_xy_list.size() == 1) {\n      kapton_path_mm.push_back(0.0);\n    } else {\n      double d2 = 0.0;\n      for (std::size_t k1 = 0; k1 < intersection_xy_list.size() - 1; ++k1) {\n        for (std::size_t k2 = k1 + 1; k2 < intersection_xy_list.size(); ++k2) {\n          vec3<double> pt1 = intersection_xy_list[k1];\n          vec3<double> pt2 = intersection_xy_list[k2];\n          d2 = (pt1[0] - pt2[0]) * (pt1[0] - pt2[0])\n               + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1])\n               + (pt1[2] - pt2[2]) * (pt1[2] - pt2[2]);\n          if (d2 > max_d2) {\n            max_d2 = d2;\n          }\n        }\n      }\n      double d = sqrt(max_d2);\n      kapton_path_mm.push_back(d);\n    }\n  }  // s1\n  return kapton_path_mm;\n}\n}  // namespace kapton\n\nusing namespace boost::python;\nnamespace kapton { namespace boost_python { namespace {\n\n  void kapton_init_module() {\n    using namespace boost::python;\n\n    def(\"get_kapton_path_cpp\", &kapton::get_kapton_path_cpp);\n  }\n\n}}}  // namespace kapton::boost_python::\n\nBOOST_PYTHON_MODULE(dials_algorithms_integration_kapton_ext) {\n  kapton::boost_python::kapton_init_module();\n}\n", "meta": {"hexsha": "f53bdfda46bd2475addeeef6e25eff6def0976a3", "size": 3337, "ext": "cc", "lang": "C++", "max_stars_repo_path": "algorithms/integration/boost_python/kapton_ext.cc", "max_stars_repo_name": "TiankunZhou/dials", "max_stars_repo_head_hexsha": "bd5c95b73c442cceb1c61b1690fd4562acf4e337", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-17T11:25:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T04:20:54.000Z", "max_issues_repo_path": "algorithms/integration/boost_python/kapton_ext.cc", "max_issues_repo_name": "TiankunZhou/dials", "max_issues_repo_head_hexsha": "bd5c95b73c442cceb1c61b1690fd4562acf4e337", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-07-31T22:37:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-31T23:08:55.000Z", "max_forks_repo_path": "algorithms/integration/boost_python/kapton_ext.cc", "max_forks_repo_name": "TiankunZhou/dials", "max_forks_repo_head_hexsha": "bd5c95b73c442cceb1c61b1690fd4562acf4e337", "max_forks_repo_licenses": ["BSD-3-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.37, "max_line_length": 88, "alphanum_fraction": 0.6364998502, "num_tokens": 1011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.4225046348141883, "lm_q1q2_score": 0.27218809335415517}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <vector>\n#include <numeric>\n#include <cmath>\n#include <stdexcept>\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\n#include \"domain_partition.hpp\"\n\n#include \"mba.hpp\"\n\n#include <boost/scope_exit.hpp>\n#include <memory>\n#include <boost/program_options.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n\n#include <boost/multi_array.hpp>\n\n#if defined(SOLVER_BACKEND_VEXCL)\n#  include <amgcl/backend/vexcl.hpp>\n   typedef amgcl::backend::vexcl<double> Backend;\n#elif defined(SOLVER_BACKEND_CUDA)\n#  include <amgcl/backend/cuda.hpp>\n#  include <amgcl/relaxation/cusparse_ilu0.hpp>\n   typedef amgcl::backend::cuda<double> Backend;\n#else\n#  ifndef SOLVER_BACKEND_BUILTIN\n#    define SOLVER_BACKEND_BUILTIN\n#  endif\n#  include <amgcl/backend/builtin.hpp>\n   typedef amgcl::backend::builtin<double> Backend;\n#endif\n\n#include <amgcl/make_solver.hpp>\n#include <amgcl/amg.hpp>\n#include <amgcl/solver/runtime.hpp>\n#include <amgcl/coarsening/runtime.hpp>\n#include <amgcl/relaxation/runtime.hpp>\n#include <amgcl/preconditioner/runtime.hpp>\n#include <amgcl/mpi/direct_solver/runtime.hpp>\n#include <amgcl/mpi/subdomain_deflation.hpp>\n#include <amgcl/adapter/crs_tuple.hpp>\n#include <amgcl/adapter/zero_copy.hpp>\n#include <amgcl/profiler.hpp>\n\nnamespace amgcl {\n    profiler<> prof;\n}\n\nstruct partitioned_deflation {\n    unsigned nparts;\n    std::vector<unsigned> domain;\n\n    partitioned_deflation(\n            boost::array<ptrdiff_t, 2> LO,\n            boost::array<ptrdiff_t, 2> HI,\n            unsigned nparts\n            ) : nparts(nparts)\n    {\n        domain_partition<2> part(LO, HI, nparts);\n\n        ptrdiff_t nx = HI[0] - LO[0] + 1;\n        ptrdiff_t ny = HI[1] - LO[1] + 1;\n\n        domain.resize(nx * ny);\n        for(unsigned p = 0; p < nparts; ++p) {\n            boost::array<ptrdiff_t, 2> lo = part.domain(p).min_corner();\n            boost::array<ptrdiff_t, 2> hi = part.domain(p).max_corner();\n\n            for(int j = lo[1]; j <= hi[1]; ++j) {\n                for(int i = lo[0]; i <= hi[0]; ++i) {\n                    domain[(j - LO[1]) * nx + (i - LO[0])] = p;\n                }\n            }\n        }\n    }\n\n    size_t dim() const { return nparts; }\n\n    double operator()(ptrdiff_t i, unsigned j) const {\n        return domain[i] == j;\n    }\n};\n\nstruct linear_deflation {\n    std::vector<double> x;\n    std::vector<double> y;\n\n    linear_deflation(\n            ptrdiff_t chunk,\n            boost::array<ptrdiff_t, 2> lo,\n            boost::array<ptrdiff_t, 2> hi\n            )\n    {\n        double hx = 1.0 / (hi[0] - lo[0]);\n        double hy = 1.0 / (hi[1] - lo[1]);\n\n        ptrdiff_t nx = hi[0] - lo[0] + 1;\n        ptrdiff_t ny = hi[1] - lo[1] + 1;\n\n        x.reserve(chunk);\n        y.reserve(chunk);\n\n        for (ptrdiff_t j = 0; j < ny; ++j) {\n            for (ptrdiff_t i = 0; i < nx; ++i) {\n                x.push_back(i * hx - 0.5);\n                y.push_back(j * hy - 0.5);\n            }\n        }\n    }\n\n    size_t dim() const { return 3; }\n\n    double operator()(ptrdiff_t i, unsigned j) const {\n        switch(j) {\n            default:\n            case 0:\n                return 1;\n            case 1:\n                return x[i];\n            case 2:\n                return y[i];\n        }\n    }\n};\n\nstruct bilinear_deflation {\n    size_t nv, chunk;\n    std::vector<double> v;\n\n    bilinear_deflation(\n            ptrdiff_t n,\n            ptrdiff_t chunk,\n            boost::array<ptrdiff_t, 2> lo,\n            boost::array<ptrdiff_t, 2> hi\n            ) : nv(0), chunk(chunk)\n    {\n        // See which neighbors we have.\n        int neib[2][2] = {\n            {lo[0] > 0 || lo[1] > 0,     hi[0] + 1 < n || lo[1] > 0    },\n            {lo[0] > 0 || hi[1] + 1 < n, hi[0] + 1 < n || hi[1] + 1 < n}\n        };\n\n        for(int j = 0; j < 2; ++j)\n            for(int i = 0; i < 2; ++i)\n                if (neib[j][i]) ++nv;\n\n        if (nv == 0) {\n            // Single MPI process?\n            nv = 1;\n            v.resize(chunk, 1);\n            return;\n        }\n\n        v.resize(chunk * nv, 0);\n\n        double *dv = v.data();\n\n        ptrdiff_t nx = hi[0] - lo[0] + 1;\n        ptrdiff_t ny = hi[1] - lo[1] + 1;\n\n        double hx = 1.0 / (nx - 1);\n        double hy = 1.0 / (ny - 1);\n\n        for(int j = 0; j < 2; ++j) {\n            for(int i = 0; i < 2; ++i) {\n                if (!neib[j][i]) continue;\n\n                boost::multi_array_ref<double, 2> V(dv, boost::extents[ny][nx]);\n\n                for(ptrdiff_t jj = 0; jj < ny; ++jj) {\n                    double y = jj * hy;\n                    double b = std::abs((1 - j) - y);\n                    for(ptrdiff_t ii = 0; ii < nx; ++ii) {\n                        double x = ii * hx;\n\n                        double a = std::abs((1 - i) - x);\n                        V[jj][ii] = a * b;\n                    }\n                }\n\n                dv += chunk;\n            }\n        }\n    }\n\n    size_t dim() const { return nv; }\n\n    double operator()(ptrdiff_t i, unsigned j) const {\n        return v[j * chunk + i];\n    }\n};\n\n#ifndef SOLVER_BACKEND_CUDA\nstruct mba_deflation {\n    size_t chunk, nv;\n    std::vector<double> v;\n\n    mba_deflation(\n            ptrdiff_t n,\n            ptrdiff_t chunk,\n            boost::array<ptrdiff_t,2> lo,\n            boost::array<ptrdiff_t,2> hi\n            ) : chunk(chunk), nv(1)\n    {\n        // See which neighbors we have.\n        int neib[2][2] = {\n            {lo[0] > 0 || lo[1] > 0,     hi[0] + 1 < n || lo[1] > 0    },\n            {lo[0] > 0 || hi[1] + 1 < n, hi[0] + 1 < n || hi[1] + 1 < n}\n        };\n\n        for(int j = 0; j < 2; ++j)\n            for(int i = 0; i < 2; ++i)\n                if (neib[j][i]) ++nv;\n\n        v.resize(chunk * nv, 0);\n\n        double *dv = v.data();\n        std::fill(dv, dv + chunk, 1.0);\n        dv += chunk;\n\n        ptrdiff_t nx = hi[0] - lo[0] + 1;\n        ptrdiff_t ny = hi[1] - lo[1] + 1;\n\n        double hx = 1.0 / (nx - 1);\n        double hy = 1.0 / (ny - 1);\n\n        std::array<double, 2> cmin = {-0.01, -0.01};\n        std::array<double, 2> cmax = { 1.01,  1.01};\n        std::array<size_t, 2> grid = {3, 3};\n\n        std::array< std::array<double, 2>, 4 > coo;\n        std::array< double, 4 > val;\n\n        for(int j = 0, idx = 0; j < 2; ++j) {\n            for(int i = 0; i < 2; ++i, ++idx) {\n                coo[idx][0] = i;\n                coo[idx][1] = j;\n            }\n        }\n\n        for(int j = 0, idx = 0; j < 2; ++j) {\n            for(int i = 0; i < 2; ++i, ++idx) {\n                if (!neib[j][i]) continue;\n\n                std::fill(val.begin(), val.end(), 0.0);\n                val[idx] = 1.0;\n\n                mba::MBA<2> interp(cmin, cmax, grid, coo, val, 8, 1e-8, 0.5, zero);\n\n                boost::multi_array_ref<double, 2> V(dv, boost::extents[ny][nx]);\n\n                for(int jj = 0; jj < ny; ++jj)\n                    for(int ii = 0; ii < nx; ++ii) {\n                        std::array<double, 2> p = {ii * hx, jj * hy};\n                        V[jj][ii] = interp(p);\n                    }\n\n                dv += chunk;\n            }\n        }\n    }\n\n    size_t dim() const { return nv; }\n\n    double operator()(ptrdiff_t i, unsigned j) const {\n        return v[j * chunk + i];\n    }\n\n    static double zero(const std::array<double, 2>&) {\n        return 0;\n    }\n};\n#endif\n\nstruct harmonic_deflation {\n    size_t nv, chunk;\n    std::vector<double> v;\n\n    harmonic_deflation(\n            ptrdiff_t n,\n            ptrdiff_t chunk,\n            boost::array<ptrdiff_t, 2> lo,\n            boost::array<ptrdiff_t, 2> hi\n            ) : nv(0), chunk(chunk)\n    {\n        // See which neighbors we have.\n        int neib[2][2] = {\n            {lo[0] > 0 || lo[1] > 0,     hi[0] + 1 < n || lo[1] > 0    },\n            {lo[0] > 0 || hi[1] + 1 < n, hi[0] + 1 < n || hi[1] + 1 < n}\n        };\n\n        for(int j = 0; j < 2; ++j)\n            for(int i = 0; i < 2; ++i)\n                if (neib[j][i]) ++nv;\n\n        if (nv == 0) {\n            // Single MPI process?\n            nv = 1;\n            v.resize(chunk, 1);\n            return;\n        }\n\n        v.resize(chunk * nv, 0);\n        double *dv = v.data();\n\n\n        ptrdiff_t nx = hi[0] - lo[0] + 1;\n        ptrdiff_t ny = hi[1] - lo[1] + 1;\n\n        std::vector<ptrdiff_t> ptr;\n        std::vector<ptrdiff_t> col;\n        std::vector<double>    val;\n        std::vector<double>    rhs(chunk, 0.0);\n\n        ptr.reserve(chunk + 1);\n        col.reserve(chunk * 5);\n        val.reserve(chunk * 5);\n\n        ptr.push_back(0);\n\n        for(int j = 0, k = 0; j < ny; ++j) {\n            for(int i = 0; i < nx; ++i, ++k) {\n                if (\n                        (i == 0    && j == 0   ) ||\n                        (i == 0    && j == ny-1) ||\n                        (i == nx-1 && j == 0   ) ||\n                        (i == nx-1 && j == ny-1)\n                   )\n                {\n                    col.push_back(k);\n                    val.push_back(1);\n                } else {\n                    col.push_back(k);\n                    val.push_back(1.0);\n\n                    if (j == 0) {\n                        col.push_back(k + nx);\n                        val.push_back(-0.5);\n                    } else if (j == ny-1) {\n                        col.push_back(k - nx);\n                        val.push_back(-0.5);\n                    } else {\n                        col.push_back(k - nx);\n                        val.push_back(-0.25);\n\n                        col.push_back(k + nx);\n                        val.push_back(-0.25);\n                    }\n\n                    if (i == 0) {\n                        col.push_back(k + 1);\n                        val.push_back(-0.5);\n                    } else if (i == nx-1) {\n                        col.push_back(k - 1);\n                        val.push_back(-0.5);\n                    } else {\n                        col.push_back(k - 1);\n                        val.push_back(-0.25);\n\n                        col.push_back(k + 1);\n                        val.push_back(-0.25);\n                    }\n                }\n\n                ptr.push_back(col.size());\n            }\n        }\n\n        amgcl::make_solver<\n            amgcl::amg<\n                amgcl::backend::builtin<double>,\n                amgcl::coarsening::smoothed_aggregation,\n                amgcl::relaxation::gauss_seidel\n                >,\n            amgcl::solver::gmres<\n                amgcl::backend::builtin<double>\n                >\n            > solve( amgcl::adapter::zero_copy(chunk, ptr.data(), col.data(), val.data()) );\n\n        for(int j = 0; j < 2; ++j) {\n            for(int i = 0; i < 2; ++i) {\n                if (!neib[j][i]) continue;\n\n                ptrdiff_t idx = i * (nx - 1) + j * (ny - 1) * nx;\n                rhs[idx] = 1.0;\n\n                boost::iterator_range<double*> x(dv, dv + chunk);\n                solve(rhs, x);\n\n                rhs[idx] = 0.0;\n\n                dv += chunk;\n            }\n        }\n    }\n\n    size_t dim() const { return nv; }\n\n    double operator()(ptrdiff_t i, unsigned j) const {\n        return v[j * chunk + i];\n    }\n};\n\nstruct renumbering {\n    const domain_partition<2> &part;\n    const std::vector<ptrdiff_t> &dom;\n\n    renumbering(\n            const domain_partition<2> &p,\n            const std::vector<ptrdiff_t> &d\n            ) : part(p), dom(d)\n    {}\n\n    ptrdiff_t operator()(ptrdiff_t i, ptrdiff_t j) const {\n        boost::array<ptrdiff_t, 2> p = {{i, j}};\n        std::pair<int,ptrdiff_t> v = part.index(p);\n        return dom[v.first] + v.second;\n    }\n};\n\nint main(int argc, char *argv[]) {\n    int provided;\n    MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided);\n    BOOST_SCOPE_EXIT(void) {\n        MPI_Finalize();\n    } BOOST_SCOPE_EXIT_END\n\n    amgcl::mpi::communicator world(MPI_COMM_WORLD);\n\n    if (world.rank == 0)\n        std::cout << \"World size: \" << world.size << std::endl;\n\n    // Read configuration from command line\n    ptrdiff_t n = 1024;\n    std::string deflation_type = \"bilinear\";\n\n    amgcl::runtime::coarsening::type  coarsening       = amgcl::runtime::coarsening::smoothed_aggregation;\n    amgcl::runtime::relaxation::type  relaxation       = amgcl::runtime::relaxation::spai0;\n    amgcl::runtime::solver::type      iterative_solver = amgcl::runtime::solver::bicgstabl;\n    amgcl::runtime::mpi::direct::type direct_solver    = amgcl::runtime::mpi::direct::skyline_lu;\n\n    bool just_relax = false;\n    bool symm_dirichlet = true;\n    std::string problem = \"laplace2d\";\n    std::string parameter_file;\n    std::string out_file;\n\n    namespace po = boost::program_options;\n    po::options_description desc(\"Options\");\n\n    desc.add_options()\n        (\"help,h\", \"show help\")\n        (\n         \"problem\",\n         po::value<std::string>(&problem)->default_value(problem),\n         \"laplace2d, recirc2d\"\n        )\n        (\n         \"symbc\",\n         po::value<bool>(&symm_dirichlet)->default_value(symm_dirichlet),\n         \"Use symmetric Dirichlet conditions in laplace2d\"\n        )\n        (\n         \"size,n\",\n         po::value<ptrdiff_t>(&n)->default_value(n),\n         \"domain size\"\n        )\n        (\n         \"coarsening,c\",\n         po::value<amgcl::runtime::coarsening::type>(&coarsening)->default_value(coarsening),\n         \"ruge_stuben, aggregation, smoothed_aggregation, smoothed_aggr_emin\"\n        )\n        (\n         \"relaxation,r\",\n         po::value<amgcl::runtime::relaxation::type>(&relaxation)->default_value(relaxation),\n         \"gauss_seidel, ilu0, iluk, ilut, damped_jacobi, spai0, spai1, chebyshev\"\n        )\n        (\n         \"iter_solver,i\",\n         po::value<amgcl::runtime::solver::type>(&iterative_solver)->default_value(iterative_solver),\n         \"cg, bicgstab, bicgstabl, gmres\"\n        )\n        (\n         \"dir_solver,d\",\n         po::value<amgcl::runtime::mpi::direct::type>(&direct_solver)->default_value(direct_solver),\n         \"skyline_lu\"\n#ifdef AMGCL_HAVE_PASTIX\n         \", pastix\"\n#endif\n        )\n        (\n         \"deflation,v\",\n         po::value<std::string>(&deflation_type)->default_value(deflation_type),\n         \"constant, partitioned, linear, bilinear, mba, harmonic\"\n        )\n        (\n         \"subparts\",\n         po::value<int>()->default_value(16),\n         \"number of partitions for partitioned deflation\"\n        )\n        (\n         \"params,P\",\n         po::value<std::string>(&parameter_file),\n         \"parameter file in json format\"\n        )\n        (\n         \"prm,p\",\n         po::value< std::vector<std::string> >()->multitoken(),\n         \"Parameters specified as name=value pairs. \"\n         \"May be provided multiple times. Examples:\\n\"\n         \"  -p solver.tol=1e-3\\n\"\n         \"  -p precond.coarse_enough=300\"\n        )\n        (\n         \"just-relax,0\",\n         po::bool_switch(&just_relax),\n         \"Do not create AMG hierarchy, use relaxation as preconditioner\"\n        )\n        (\n         \"out,o\",\n         po::value<std::string>(&out_file),\n         \"out file\"\n        )\n        ;\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\")) {\n        std::cout << desc << std::endl;\n        return 0;\n    }\n\n    boost::property_tree::ptree prm;\n    if (vm.count(\"params\")) read_json(parameter_file, prm);\n\n    if (vm.count(\"prm\")) {\n        for(const std::string &v : vm[\"prm\"].as< std::vector<std::string> >()) {\n            amgcl::put(prm, v);\n        }\n    }\n\n    prm.put(\"isolver.type\", iterative_solver);\n    prm.put(\"dsolver.type\", direct_solver);\n\n    const ptrdiff_t n2 = n * n;\n    const double hinv  = (n - 1);\n    const double h2i   = (n - 1) * (n - 1);\n    const double h     = 1 / hinv;\n\n\n    boost::array<ptrdiff_t, 2> lo = { {0, 0} };\n    boost::array<ptrdiff_t, 2> hi = { {n - 1, n - 1} };\n\n    using amgcl::prof;\n\n    prof.tic(\"partition\");\n    domain_partition<2> part(lo, hi, world.size);\n    ptrdiff_t chunk = part.size( world.rank );\n\n    std::vector<ptrdiff_t> domain(world.size + 1);\n    MPI_Allgather(\n            &chunk, 1, amgcl::mpi::datatype<ptrdiff_t>(),\n            &domain[1], 1, amgcl::mpi::datatype<ptrdiff_t>(), world);\n    std::partial_sum(domain.begin(), domain.end(), domain.begin());\n\n    lo = part.domain(world.rank).min_corner();\n    hi = part.domain(world.rank).max_corner();\n    prof.toc(\"partition\");\n\n    renumbering renum(part, domain);\n\n    prof.tic(\"deflation\");\n    std::function<double(ptrdiff_t,unsigned)> dv;\n    unsigned ndv = 1;\n\n    if (deflation_type == \"constant\") {\n        dv = amgcl::mpi::constant_deflation(1);\n    } else if (deflation_type == \"partitioned\") {\n        ndv = vm[\"subparts\"].as<int>();\n        dv  = partitioned_deflation(lo, hi, ndv);\n    } else if (deflation_type == \"linear\") {\n        ndv = 3;\n        dv  = linear_deflation(chunk, lo, hi);\n    } else if (deflation_type == \"bilinear\") {\n        bilinear_deflation bld(n, chunk, lo, hi);\n        ndv = bld.dim();\n        dv  = bld;\n#ifndef SOLVER_BACKEND_CUDA\n    } else if (deflation_type == \"mba\") {\n        mba_deflation mba(n, chunk, lo, hi);\n        ndv = mba.dim();\n        dv  = mba;\n#endif\n    } else if (deflation_type == \"harmonic\") {\n        harmonic_deflation hd(n, chunk, lo, hi);\n        ndv = hd.dim();\n        dv  = hd;\n    } else {\n        throw std::runtime_error(\"Unsupported deflation type\");\n    }\n\n    prm.put(\"num_def_vec\", ndv);\n    prm.put(\"def_vec\", &dv);\n    prof.toc(\"deflation\");\n\n    prof.tic(\"assemble\");\n    std::vector<ptrdiff_t> ptr;\n    std::vector<ptrdiff_t> col;\n    std::vector<double>    val;\n    std::vector<double>    rhs;\n\n    ptr.reserve(chunk + 1);\n    col.reserve(chunk * 5);\n    val.reserve(chunk * 5);\n    rhs.reserve(chunk);\n\n    ptr.push_back(0);\n\n    if (problem == \"recirc2d\") {\n        const double eps  = 1e-5;\n\n        for(ptrdiff_t j = lo[1]; j <= hi[1]; ++j) {\n            double y = h * j;\n            for(ptrdiff_t i = lo[0]; i <= hi[0]; ++i) {\n                double x = h * i;\n\n                if (i == 0 || j == 0 || i + 1 == n || j + 1 == n) {\n                    col.push_back(renum(i,j));\n                    val.push_back(1);\n                    rhs.push_back(\n                            sin(M_PI * x) + sin(M_PI * y) +\n                            sin(13 * M_PI * x) + sin(13 * M_PI * y)\n                            );\n                } else {\n                    double a = -sin(M_PI * x) * cos(M_PI * y) * hinv;\n                    double b =  sin(M_PI * y) * cos(M_PI * x) * hinv;\n\n                    if (j > 0) {\n                        col.push_back(renum(i,j-1));\n                        val.push_back(-eps * h2i - std::max(b, 0.0));\n                    }\n\n                    if (i > 0) {\n                        col.push_back(renum(i-1,j));\n                        val.push_back(-eps * h2i - std::max(a, 0.0));\n                    }\n\n                    col.push_back(renum(i,j));\n                    val.push_back(4 * eps * h2i + fabs(a) + fabs(b));\n\n                    if (i + 1 < n) {\n                        col.push_back(renum(i+1,j));\n                        val.push_back(-eps * h2i + std::min(a, 0.0));\n                    }\n\n                    if (j + 1 < n) {\n                        col.push_back(renum(i,j+1));\n                        val.push_back(-eps * h2i + std::min(b, 0.0));\n                    }\n\n                    rhs.push_back(1.0);\n                }\n                ptr.push_back( col.size() );\n            }\n        }\n    } else {\n        for(ptrdiff_t j = lo[1]; j <= hi[1]; ++j) {\n            for(ptrdiff_t i = lo[0]; i <= hi[0]; ++i) {\n                if (!symm_dirichlet && (i == 0 || j == 0 || i + 1 == n || j + 1 == n)) {\n                    col.push_back(renum(i,j));\n                    val.push_back(1);\n                    rhs.push_back(0);\n                } else {\n                    if (j > 0)  {\n                        col.push_back(renum(i,j-1));\n                        val.push_back(-h2i);\n                    }\n\n                    if (i > 0) {\n                        col.push_back(renum(i-1,j));\n                        val.push_back(-h2i);\n                    }\n\n                    col.push_back(renum(i,j));\n                    val.push_back(4 * h2i);\n\n                    if (i + 1 < n) {\n                        col.push_back(renum(i+1,j));\n                        val.push_back(-h2i);\n                    }\n\n                    if (j + 1 < n) {\n                        col.push_back(renum(i,j+1));\n                        val.push_back(-h2i);\n                    }\n\n                    rhs.push_back(1);\n                }\n                ptr.push_back( col.size() );\n            }\n        }\n    }\n    prof.toc(\"assemble\");\n\n    Backend::params bprm;\n\n#if defined(SOLVER_BACKEND_VEXCL)\n    vex::Context ctx(vex::Filter::Env);\n    std::cout << ctx << std::endl;\n    bprm.q = ctx;\n#elif defined(SOLVER_BACKEND_CUDA)\n    cusparseCreate(&bprm.cusparse_handle);\n#endif\n\n    auto f = Backend::copy_vector(rhs, bprm);\n    auto x = Backend::create_vector(chunk, bprm);\n\n    amgcl::backend::clear(*x);\n\n    size_t iters;\n    double resid, tm_setup, tm_solve;\n\n    if (just_relax) {\n        prm.put(\"local.class\", \"relaxation\");\n        prm.put(\"local.type\", relaxation);\n    } else {\n        prm.put(\"local.coarsening.type\", coarsening);\n        prm.put(\"local.relax.type\", relaxation);\n    }\n\n    prof.tic(\"setup\");\n    typedef\n        amgcl::mpi::subdomain_deflation<\n            amgcl::runtime::preconditioner< Backend >,\n            amgcl::runtime::solver::wrapper,\n            amgcl::runtime::mpi::direct::solver<double>\n        > SDD;\n\n    SDD solve(world, std::tie(chunk, ptr, col, val), prm, bprm);\n    tm_setup = prof.toc(\"setup\");\n\n    prof.tic(\"solve\");\n    std::tie(iters, resid) = solve(*f, *x);\n    tm_solve = prof.toc(\"solve\");\n\n    if (world.rank == 0) {\n        std::cout\n            << \"Iterations: \" << iters << std::endl\n            << \"Error:      \" << resid << std::endl\n            << prof << std::endl;\n\n#ifdef _OPENMP\n        int nt = omp_get_max_threads();\n#else\n        int nt = 1;\n#endif\n        std::ostringstream log_name;\n        log_name << \"log_\" << n2 << \"_\" << nt << \"_\" << world.size << \".txt\";\n        std::ofstream log(log_name.str().c_str(), std::ios::app);\n        log << n2 << \"\\t\" << nt << \"\\t\" << world.size\n            << \"\\t\" << tm_setup << \"\\t\" << tm_solve\n            << \"\\t\" << iters << \"\\t\" << std::endl;\n    }\n\n\n    if (!out_file.empty()) {\n        std::vector<double> X(world.rank == 0 ? n2 : chunk);\n\n#if defined(SOLVER_BACKEND_VEXCL)\n        vex::copy(x->begin(), x->end(), X.begin());\n#elif defined(SOLVER_BACKEND_CUDA)\n        thrust::copy(x->begin(), x->end(), X.begin());\n#else\n        std::copy(x->data(), x->data() + chunk, X.begin());\n#endif\n\n        if (world.rank == 0) {\n            for(int i = 1; i < world.size; ++i)\n                MPI_Recv(&X[domain[i]], domain[i+1] - domain[i], MPI_DOUBLE, i, 42, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n\n            std::ofstream f(out_file.c_str(), std::ios::binary);\n            int m = n;\n            f.write((char*)&m, sizeof(int));\n            for(int j = 0; j < n; ++j) {\n                for(int i = 0; i < n; ++i) {\n                    double buf = X[renum(i,j)];\n                    f.write((char*)&buf, sizeof(double));\n                }\n            }\n        } else {\n            MPI_Send(X.data(), chunk, MPI_DOUBLE, 0, 42, MPI_COMM_WORLD);\n        }\n    }\n}\n", "meta": {"hexsha": "c1d9c42daebf3b4944af16b93a190fa957003ce2", "size": 23466, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/mpi/runtime_sdd.cpp", "max_stars_repo_name": "moyner/amgcl", "max_stars_repo_head_hexsha": "a551614040f0a7b793b41a4a63386675ca61d8da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-20T06:16:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-20T06:16:20.000Z", "max_issues_repo_path": "examples/mpi/runtime_sdd.cpp", "max_issues_repo_name": "moyner/amgcl", "max_issues_repo_head_hexsha": "a551614040f0a7b793b41a4a63386675ca61d8da", "max_issues_repo_licenses": ["MIT"], "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/mpi/runtime_sdd.cpp", "max_forks_repo_name": "moyner/amgcl", "max_forks_repo_head_hexsha": "a551614040f0a7b793b41a4a63386675ca61d8da", "max_forks_repo_licenses": ["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.2229140722, "max_line_length": 119, "alphanum_fraction": 0.4633086167, "num_tokens": 6613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.4225046348141883, "lm_q1q2_score": 0.27218809335415517}}
{"text": "//=================================================================================================\n// Copyright (c) 2013, Johannes Meyer, TU Darmstadt\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 Flight Systems and Automatic Control group,\n//       TU Darmstadt, nor the names of its contributors may be used to\n//       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 COPYRIGHT HOLDER 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 <hector_pose_estimation/filter/ekf.h>\n#include <hector_pose_estimation/system.h>\n\n#include <boost/pointer_cast.hpp>\n\n#ifdef USE_HECTOR_TIMING\n  #include <hector_diagnostics/timing.h>\n#endif\n\nnamespace hector_pose_estimation {\nnamespace filter {\n\nEKF::EKF(State &state)\n  : Filter(state)\n{}\n\nEKF::~EKF()\n{}\n\nbool EKF::init(PoseEstimation &estimator)\n{\n  x_diff = State::Vector(state_.getVectorDimension());\n  A = State::SystemMatrix(state_.getCovarianceDimension(), state_.getCovarianceDimension());\n  Q = State::Covariance(state_.getCovarianceDimension(), state_.getCovarianceDimension());\n  return true;\n}\n\nbool EKF::preparePredict(double dt)\n{\n  x_diff.setZero();\n  A.setIdentity();\n  Q.setZero();\n  return Filter::preparePredict(dt);\n}\n\nbool EKF::predict(const SystemPtr& system, double dt)\n{\n  if (!Filter::predict(system, dt)) return false;\n  EKF::Predictor *predictor = boost::dynamic_pointer_cast<EKF::Predictor>(system->predictor());\n  x_diff += predictor->x_diff;\n  A += predictor->A;\n  Q += predictor->Q;\n  return true;\n}\n\nbool EKF::doPredict(double dt) {\n  ROS_DEBUG_NAMED(\"ekf.prediction\", \"EKF prediction (dt = %f):\", dt);\n\n  ROS_DEBUG_STREAM_NAMED(\"ekf.prediction\", \"A      = [\" << std::endl << A << \"]\");\n  ROS_DEBUG_STREAM_NAMED(\"ekf.prediction\", \"Q      = [\" << std::endl << Q << \"]\");\n\n#ifdef USE_HECTOR_TIMING\n  { hector_diagnostics::TimingSection section(\"predict.ekf.covariance\");\n#endif\n  state().P() = A * state().P() * A.transpose() + Q;\n  state().P().assertSymmetric();\n\n#ifdef USE_HECTOR_TIMING\n  }\n  { hector_diagnostics::TimingSection section(\"predict.ekf.state\");\n#endif\n  state().update(x_diff);\n\n#ifdef USE_HECTOR_TIMING\n  }\n#endif\n\n  ROS_DEBUG_STREAM_NAMED(\"ekf.prediction\", \"x_pred = [\" << state().getVector().transpose() << \"]\");\n  ROS_DEBUG_STREAM_NAMED(\"ekf.prediction\", \"P_pred = [\" << std::endl << state().getCovariance() << \"]\");\n\n  Filter::doPredict(dt);\n  return true;\n}\n\n} // namespace filter\n} // namespace hector_pose_estimation\n", "meta": {"hexsha": "46d73111a2b067cfbcac1ca6f75c1b5ada98144a", "size": 3818, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hector_quadrotor/hector_pose_estimation_core/src/filter/ekf.cpp", "max_stars_repo_name": "Eashwar-S/Swarm_Drones", "max_stars_repo_head_hexsha": "1611c9a66ff0feb6d2ceed4518402e32064bf0f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-06-04T07:27:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T09:45:06.000Z", "max_issues_repo_path": "hector_quadrotor/hector_pose_estimation_core/src/filter/ekf.cpp", "max_issues_repo_name": "Eashwar-S/Swarm_Drones", "max_issues_repo_head_hexsha": "1611c9a66ff0feb6d2ceed4518402e32064bf0f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-11-24T13:19:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-29T12:48:35.000Z", "max_forks_repo_path": "hector_quadrotor/hector_pose_estimation_core/src/filter/ekf.cpp", "max_forks_repo_name": "Eashwar-S/Swarm_Drones", "max_forks_repo_head_hexsha": "1611c9a66ff0feb6d2ceed4518402e32064bf0f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-25T23:36:44.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-28T20:07:25.000Z", "avg_line_length": 36.3619047619, "max_line_length": 104, "alphanum_fraction": 0.6859612362, "num_tokens": 878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883592602049, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.27204248487560295}}
{"text": "#pragma once\n\n#include <vector>\n#include <algorithm>\n\n#include <boost/tuple/tuple.hpp>\n#include <boost/tuple/tuple_comparison.hpp>\n\n#include \"cartesian_tree.hpp\"\n\nnamespace succinct {\n\n    // XXX(ot): implement arbitrary comparator\n    template <typename Vector>\n    class topk_vector : boost::noncopyable {\n    public:\n        typedef Vector vector_type;\n        typedef typename vector_type::value_type value_type;\n        typedef boost::tuple<value_type, uint64_t> entry_type;\n        typedef std::vector<entry_type> entry_vector_type;\n\n        topk_vector()\n        {}\n\n        template <typename Range>\n        topk_vector(Range const& v)\n        {\n            cartesian_tree(v, std::greater<typename boost::range_value<Range>::type>())\n                .swap(m_cartesian_tree);\n            vector_type(v).swap(m_v);\n        }\n\n        value_type const\n        operator[](uint64_t idx) const\n        {\n            return m_v[idx];\n        }\n\n        uint64_t size() const\n        {\n            return m_v.size();\n        }\n\n        class enumerator\n        {\n        public:\n            enumerator()\n                : m_topkv(0)\n            {}\n\n            bool next()\n            {\n                using boost::tie;\n                if (m_q.empty()) return false;\n\n                value_type cur_mid_val;\n                uint64_t cur_mid, cur_a, cur_b;\n\n                std::pop_heap(m_q.begin(), m_q.end(), value_index_comparator());\n                tie(cur_mid_val, cur_mid, cur_a, cur_b) = m_q.back();\n                m_q.pop_back();\n\n                m_cur = entry_type(cur_mid_val, cur_mid);\n\n                if (cur_mid != cur_a) {\n                    uint64_t m = m_topkv->m_cartesian_tree.rmq(cur_a, cur_mid - 1);\n                    m_q.push_back(queue_element_type(m_topkv->m_v[m], m, cur_a, cur_mid - 1));\n                    std::push_heap(m_q.begin(), m_q.end(), value_index_comparator());\n                }\n\n                if (cur_mid != cur_b) {\n                    uint64_t m = m_topkv->m_cartesian_tree.rmq(cur_mid + 1, cur_b);\n                    m_q.push_back(queue_element_type(m_topkv->m_v[m], m, cur_mid + 1, cur_b));\n                    std::push_heap(m_q.begin(), m_q.end(), value_index_comparator());\n                }\n\n                return true;\n            }\n\n            entry_type const& value() const\n            {\n                return m_cur;\n            }\n\n            friend class topk_vector;\n\n            void swap(enumerator& other)\n            {\n                using std::swap;\n                swap(m_topkv, other.m_topkv);\n                swap(m_q, other.m_q);\n                swap(m_cur, other.m_cur);\n            }\n\n        private:\n\n            void set(topk_vector const* topkv, uint64_t a, uint64_t b)\n            {\n                assert(a <= b);\n                clear();\n                m_topkv = topkv;\n\n                uint64_t m = m_topkv->m_cartesian_tree.rmq(a, b);\n                m_q.push_back(queue_element_type(m_topkv->m_v[m], m, a, b));\n            }\n\n            typedef boost::tuple<value_type, uint64_t, uint64_t, uint64_t> queue_element_type;\n\n            struct value_index_comparator {\n                template <typename Tuple>\n                bool operator()(Tuple const& a, Tuple const& b) const\n                {\n                    using boost::get;\n                    // lexicographic, increasing on value and decreasing\n                    // on index\n                    return (get<0>(a) < get<0>(b) ||\n                            (get<0>(a) == get<0>(b) &&\n                             get<1>(a) > get<1>(b)));\n                }\n            };\n\n        public:\n            void clear()\n            {\n                m_topkv = 0;\n                m_q.clear();\n            }\n\n        private:\n            topk_vector const* m_topkv;\n            std::vector<queue_element_type> m_q;\n            entry_type m_cur;\n        };\n\n        // NOTE this is b inclusive\n        // XXX switch to [a, b) ?\n        void get_topk_enumerator(uint64_t a, uint64_t b, enumerator& ret) const\n        {\n            ret.set(this, a, b);\n        }\n\n        enumerator get_topk_enumerator(uint64_t a, uint64_t b) const\n        {\n            enumerator ret;\n            get_topk_enumerator(a, b, ret);\n            return ret;\n        }\n\n        entry_vector_type\n        topk(uint64_t a, uint64_t b, size_t k) const\n        {\n            entry_vector_type ret(std::min(size_t(b - a + 1), k));\n            enumerator it = get_topk_enumerator(a, b);\n\n            bool hasnext;\n            for (size_t i = 0; i < ret.size(); ++i) {\n                hasnext = it.next();\n                assert(hasnext); (void)hasnext;\n                ret[i] = it.value();\n            }\n\n            assert(ret.size() == k || !it.next());\n\n            return ret;\n        }\n\n\n        template <typename Visitor>\n        void map(Visitor& visit)\n        {\n            visit\n                (m_v, \"m_v\")\n                (m_cartesian_tree, \"m_cartesian_tree\");\n        }\n\n        void swap(topk_vector& other)\n        {\n            other.m_v.swap(m_v);\n            other.m_cartesian_tree.swap(m_cartesian_tree);\n        }\n\n    protected:\n\n        vector_type m_v;\n        cartesian_tree m_cartesian_tree;\n    };\n\n}\n", "meta": {"hexsha": "c64895f4146a637e0c737b2415b34875393533a0", "size": 5244, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/succinct/topk_vector.hpp", "max_stars_repo_name": "bowlofstew/omim", "max_stars_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4879.0, "max_stars_repo_stars_event_min_datetime": "2015-09-30T10:56:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T18:43:03.000Z", "max_issues_repo_path": "3party/succinct/topk_vector.hpp", "max_issues_repo_name": "bowlofstew/omim", "max_issues_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7549.0, "max_issues_repo_issues_event_min_datetime": "2015-09-30T10:52:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:04:22.000Z", "max_forks_repo_path": "3party/succinct/topk_vector.hpp", "max_forks_repo_name": "bowlofstew/omim", "max_forks_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1493.0, "max_forks_repo_forks_event_min_datetime": "2015-09-30T10:43:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T09:16:49.000Z", "avg_line_length": 27.746031746, "max_line_length": 94, "alphanum_fraction": 0.4841723875, "num_tokens": 1181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.27201444600146546}}
{"text": "/*ckwg +29\n * Copyright 2015 by Kitware, 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 *  * 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 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 name of Kitware, Inc. nor the names of any contributors may be used\n *    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''\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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR\n * 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/**\n * \\file\n * \\brief core fundamental matrix template implementations\n */\n\n#include \"fundamental_matrix.h\"\n\n#include <cmath>\n\n#include <vital/exceptions/math.h>\n\n#include <Eigen/SVD>\n\n\nnamespace kwiver {\nnamespace vital {\n\n\n/// Construct from a provided matrix\ntemplate <typename T>\nfundamental_matrix_<T>\n::fundamental_matrix_( Eigen::Matrix<T,3,3> const &mat )\n{\n  Eigen::JacobiSVD<matrix_t> svd(mat, Eigen::ComputeFullU |\n                                      Eigen::ComputeFullV);\n  auto S = svd.singularValues();\n  const matrix_t& U = svd.matrixU();\n  const matrix_t& V = svd.matrixV();\n\n  // clear the last singular value\n  S[2] = T(0);\n  S /= S.norm();\n  mat_ = U*S.asDiagonal()*V.transpose();\n}\n\n/// Conversion Copy constructor -- float specialization\ntemplate <>\ntemplate <>\nfundamental_matrix_<float>\n::fundamental_matrix_( fundamental_matrix_<float> const &other )\n  : mat_( other.mat_ )\n{\n}\n\n/// Conversion Copy constructor -- double specialization\ntemplate <>\ntemplate <>\nfundamental_matrix_<double>\n::fundamental_matrix_( fundamental_matrix_<double> const &other )\n  : mat_( other.mat_ )\n{\n}\n\n/// Construct from a generic fundamental_matrix\ntemplate <typename T>\nfundamental_matrix_<T>\n::fundamental_matrix_( fundamental_matrix const &base )\n  : mat_( base.matrix().template cast<T>() )\n{\n}\n\n/// Construct from a generic fundamental_matrix -- double specialization\ntemplate <>\nfundamental_matrix_<double>\n::fundamental_matrix_( fundamental_matrix const &base )\n  : mat_( base.matrix() )\n{\n}\n\n/// Create a clone of outself as a shared pointer\ntemplate <typename T>\nfundamental_matrix_sptr\nfundamental_matrix_<T>\n::clone() const\n{\n  return fundamental_matrix_sptr( new fundamental_matrix_<T>( *this ) );\n}\n\n/// Get a double-typed copy of the underlying matrix\ntemplate <typename T>\nEigen::Matrix<double,3,3>\nfundamental_matrix_<T>\n::matrix() const\n{\n  return this->mat_.template cast<double>();\n}\n\n/// Specialization for matrices with native double type\ntemplate <>\nEigen::Matrix<double,3,3>\nfundamental_matrix_<double>\n::matrix() const\n{\n  return this->mat_;\n}\n\n\n// ===========================================================================\n// Other Functions\n// ---------------------------------------------------------------------------\n\n/// Output stream operator for \\p fundamental_matrix instances\nstd::ostream&\noperator<<( std::ostream &s, fundamental_matrix const &f )\n{\n  s << f.matrix();\n  return s;\n}\n\n// ===========================================================================\n// Template class instantiation\n// ---------------------------------------------------------------------------\n/// \\cond DoxygenSuppress\n#define INSTANTIATE_FUNDAMENTAL_MATRIX(T) \\\n  template class fundamental_matrix_<T>;\n\nINSTANTIATE_FUNDAMENTAL_MATRIX(float);\nINSTANTIATE_FUNDAMENTAL_MATRIX(double);\n#undef INSTANTIATE_FUNDAMENTAL_MATRIX\n/// \\endcond\n\n\n} } // end vital namespace\n", "meta": {"hexsha": "20865502a8f3f65fa7d61ad2ed1b136ea64dc8a0", "size": 4460, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "vital/types/fundamental_matrix.cxx", "max_stars_repo_name": "neal-siekierski/kwiver", "max_stars_repo_head_hexsha": "1c97ad72c8b6237cb4b9618665d042be16825005", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-31T07:07:32.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-31T07:07:32.000Z", "max_issues_repo_path": "vital/types/fundamental_matrix.cxx", "max_issues_repo_name": "neal-siekierski/kwiver", "max_issues_repo_head_hexsha": "1c97ad72c8b6237cb4b9618665d042be16825005", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-03-19T00:52:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T23:48:06.000Z", "max_forks_repo_path": "vital/types/fundamental_matrix.cxx", "max_forks_repo_name": "neal-siekierski/kwiver", "max_forks_repo_head_hexsha": "1c97ad72c8b6237cb4b9618665d042be16825005", "max_forks_repo_licenses": ["BSD-3-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.961038961, "max_line_length": 81, "alphanum_fraction": 0.6867713004, "num_tokens": 943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2719598375416356}}
{"text": "/*\n * graph.cpp\n *\n * Purpose: Graph\n * Created by: Keisuke Okumura <okumura.k@coord.c.titech.ac.jp>\n */\n\n\n#include \"graph.h\"\n#include <random>\n#include <unordered_set>\n#include \"util.h\"\n#include <boost/heap/fibonacci_heap.hpp>\n\nGraph::Graph() {\n  std::random_device seed_gen;\n  MT = new std::mt19937(seed_gen());\n  init();\n}\n\nGraph::Graph(std::mt19937* _MT) : MT(_MT) {\n  init();\n}\n\nvoid Graph::init() {\n  directed = false;\n  regFlg = true;\n}\n\nGraph::~Graph() {\n  for (auto v : nodes) delete v;\n  nodes.clear();\n  for (auto p : knownPaths) delete p.second;\n  knownPaths.clear();\n}\n\nNode* Graph::getNode(int id) {\n  auto itr = std::find_if(nodes.begin(), nodes.end(),\n                          [id](Node* v){ return v->getId() == id; });\n  // error check\n  if (itr == nodes.end()) {\n    std::cout << \"error@Graph::getNode, \"\n              << \"node index is over, \" << id << \"\\n\";\n    std::exit(1);\n  }\n\n  return *itr;\n}\n\nNode* Graph::getNode(int x, int y) {\n  auto itr = std::find_if(nodes.begin(), nodes.end(),\n                          [x, y](Node* v)\n                          { return v->getPos().x == x\n                              && v->getPos().y == y; });\n  if (itr == nodes.end()) return nullptr;\n  return *itr;\n}\n\nbool Graph::existNode(int id) {\n  auto itr = std::find_if(nodes.begin(), nodes.end(),\n                          [id](Node* v){ return v->getId() == id; });\n  return itr != nodes.end();\n}\n\nint Graph::getNodeIndex(Node* v) {\n  return v->getIndex();\n}\n\nNodes Graph::neighbor(Node* v) {\n  return v->getNeighbor();\n}\n\nNodes Graph::neighbor(int i) {\n  return getNode(i)->getNeighbor();\n}\n\nNodes Graph::getPath(Node* s, Node* g, Nodes &prohibitedNodes) {\n  return {};\n}\n\n// regFlg : whether register\nNodes Graph::getPath(Node* _s, Node* _g,\n                     Nodes &prohibitedNodes, int (*dist) (Node*, Node*))\n{\n  bool prohibited = !prohibitedNodes.empty();\n  Nodes path, C;\n  std::string key;\n\n  // ==== fast implementation ====\n  if (regFlg && !prohibited) {\n    key = getKey(_s, _g);\n    auto itrK = knownPaths.find(key);\n    if (itrK != knownPaths.end()) {  // known\n      path = itrK->second->path;\n      return path;\n    }\n  }\n  // =============================\n\n  int f;\n  bool invalid = true;\n\n  // prepare node open hashtable\n  boost::heap::fibonacci_heap<Fib_AN> OPEN;\n  std::unordered_map<int, boost::heap::fibonacci_heap<Fib_AN>::handle_type> SEARCHED;\n  std::unordered_set<int> CLOSE;\n  AN* n = new AN { _s, 0, dist(_s, _g), nullptr };\n  auto handle = OPEN.push(Fib_AN(n));\n  SEARCHED.emplace(n->v->getId(), handle);\n\n  while (!OPEN.empty()) {\n    // argmin\n    n = OPEN.top().node;\n\n    // check goal condition\n    if (n->v == _g) {\n      invalid = false;\n      break;\n    }\n\n    // ==== fast implementation ====\n    key = getKey(n->v, _g);\n    auto itrK = knownPaths.find(key);\n    if (itrK != knownPaths.end()) {  // known\n      Nodes kPath = itrK->second->path;\n      bool valid = true;\n      if (prohibited) {\n        for (auto v : kPath) {\n          if (inArray(v, prohibitedNodes)) {\n            valid = false;\n            break;\n          }\n        }\n      }\n      if (valid) {\n        for (int i = 1; i < kPath.size(); ++i) {\n          n = new AN { kPath[i], 0, 0, n };\n        }\n        invalid = false;\n        break;\n      }\n    }\n    // =============================\n\n    // update list\n    OPEN.pop();\n    CLOSE.emplace(n->v->getId());\n\n    // search neighbor\n    C = neighbor(n->v);\n\n    for (auto m : C) {\n      if (prohibited && inArray(m, prohibitedNodes)) continue;\n      if (CLOSE.find(m->getId()) != CLOSE.end()) continue;\n      f = n->g + 1 + dist(m, _g);\n\n      // ==== fast implementation ====\n      if (regFlg) {\n        key = getKey(m, _g);\n        auto itrK = knownPaths.find(key);\n        if (itrK != knownPaths.end()) {\n          f = n->g + 1 + itrK->second->path.size() - 1;\n        }\n      }\n      // =============================\n\n      auto itrS = SEARCHED.find(m->getId());\n      if (itrS == SEARCHED.end()) {  // new node\n        AN* l = new AN { m, n->g + 1, f, n };\n        auto handle = OPEN.push(Fib_AN(l));\n        SEARCHED.emplace(l->v->getId(), handle);\n      } else {\n        auto handle = itrS->second;\n        AN* l = (*handle).node;\n        if (l->f > f) {\n          l->g = n->g + 1;\n          l->f = f;\n          l->p = n;\n          OPEN.increase(handle);\n        }\n      }\n    }\n  }\n\n  if (invalid) return path;\n\n  // back tracking\n  while (n != nullptr) {\n    path.push_back(n->v);\n    n = n->p;\n  }\n  std::reverse(path.begin(), path.end());\n\n  // register path\n  if (regFlg && !prohibited) registerPath(path);\n\n  return path;\n}\n\nstd::string Graph::getKey(Node* s, Node* g) {\n  int sIndex = getNodeIndex(s);\n  int gIndex = getNodeIndex(g);\n  std::string key = \"\";\n  key += std::to_string(sIndex);\n  key += \"-\";\n  key += std::to_string(gIndex);\n  return key;\n}\n\nvoid Graph::registerPath(const Nodes &path) {\n  if (path.empty()) return;\n\n  Nodes tmp = path;\n  std::string key;\n\n  Node *v1, *v2;\n  do {\n    v1 = tmp[0];\n    v2 = tmp[tmp.size() - 1];\n    key = getKey(v1, v2);\n    KnownPath* knownPath = new KnownPath { v1, v2, tmp };\n    knownPaths.emplace(key, knownPath);\n    tmp.erase(tmp.begin());\n  } while (tmp.size() > 2);\n}\n\nPaths Graph::getRandomStartGoal(int num) {\n  if (num > starts.size() || num > goals.size()) {\n    std::cout << \"error@Graph::getStartGoal, over node size\" << \"\\n\";\n    std::exit(1);\n  }\n\n  Paths points;\n  Nodes ss(starts.size());\n  Nodes gs(goals.size());\n  bool flg;\n\n  std::copy(starts.begin(), starts.end(), ss.begin());\n  std::copy(goals.begin(),  goals.end(), gs.begin());\n\n  while (true) {\n    points.clear();\n    std::shuffle(ss.begin(), ss.end(), *MT);\n    std::shuffle(gs.begin(), gs.end(), *MT);\n\n    flg = true;\n    for (int i = 0; i < num; ++i) {\n      if (ss[i] != gs[i]) {\n        points.push_back({ ss[i], gs[i] });\n      } else {\n        flg = false;\n        break;\n      }\n    }\n\n    if (flg) break;\n  }\n\n  return points;\n}\n", "meta": {"hexsha": "4fed0f40562bc4531d023665dc0a8c960e980a4f", "size": 5955, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PIBT/graph.cpp", "max_stars_repo_name": "YimingXieUSC/JY_LNS", "max_stars_repo_head_hexsha": "396f0198b3e6f644c7601747ac53d6406442c8d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2021-05-21T10:40:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T07:34:27.000Z", "max_issues_repo_path": "src/PIBT/graph.cpp", "max_issues_repo_name": "YimingXieUSC/JY_LNS", "max_issues_repo_head_hexsha": "396f0198b3e6f644c7601747ac53d6406442c8d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PIBT/graph.cpp", "max_forks_repo_name": "YimingXieUSC/JY_LNS", "max_forks_repo_head_hexsha": "396f0198b3e6f644c7601747ac53d6406442c8d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2021-05-23T23:51:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T13:25:08.000Z", "avg_line_length": 22.816091954, "max_line_length": 85, "alphanum_fraction": 0.5190596138, "num_tokens": 1723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.27192803161602486}}
{"text": "/*\nCopyright (c) 2013, Regents of the University of Alaska\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n    * Neither the name of the Geographic Information Network of Alaska nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nThis code was developed by Dan Stahlke for the Geographic Information Network of Alaska.\n*/\n\n\n\n#include <cassert>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/numeric/conversion/cast.hpp>\n\n#include \"common.h\"\n#include \"ndv.h\"\n\nusing namespace dangdal;\n\nstruct Binning {\n\tBinning() :\n\t\tnbins(0),\n\t\toffset(0),\n\t\tscale(0)\n\t{ }\n\n\tint to_bin(double v) const {\n\t\tif(std::isinf(v) == -1) return 0;\n\t\tif(std::isinf(v) ==  1) return nbins-1;\n\t\tdouble bin_dbl = round((v-offset)/scale);\n\t\tif(std::isnan(bin_dbl)) fatal_error(\"nan in to_bin\");\n\t\tif(bin_dbl < 0) return 0;\n\t\tif(bin_dbl > nbins-1) return nbins-1;\n\t\tint bin_int = int(bin_dbl);\n\t\tassert(bin_int >= 0 && bin_int < nbins);\n\t\treturn bin_int;\n\t}\n\n\tdouble from_bin(int i) const {\n\t\treturn double(i) * scale + offset;\n\t}\n\n\tint nbins;\n\tdouble offset;\n\tdouble scale;\n};\n\nstruct Histogram {\n\tHistogram() :\n\t\tmin(0), max(0), mean(0), stddev(0),\n\t\tdata_count(0), ndv_count(0)\n\t{ }\n\n\tBinning binning;\n\tdouble min, max, mean, stddev;\n\tsize_t data_count;\n\tsize_t ndv_count;\n\tstd::vector<size_t> counts;\n};\n\nstd::vector<std::pair<double, double> > compute_minmax(\n\tconst std::vector<GDALRasterBandH> &src_bands, const NdvDef &ndv_def, \n\tsize_t w, size_t h\n);\nstd::vector<Histogram> compute_histogram(\n\tconst std::vector<GDALRasterBandH> &src_bands, const NdvDef &ndv_def, \n\tsize_t w, size_t h, const std::vector<Binning> &binnings\n);\nvoid get_scale_from_percentile(\n\tconst Histogram &histogram, int output_range,\n\tdouble from_percentile, double to_percentile,\n\tdouble *scale_out, double *offset_out\n);\nstd::vector<uint8_t> invert_histogram_to_gaussian(const Histogram &histogram_in, double variance, \n\tint output_range);\nvoid copyGeoCode(GDALDatasetH dst_ds, GDALDatasetH src_ds);\n\nvoid usage(const std::string &cmdname) {\n\tprintf(\"Usage: %s <options> src.tif dst.tif\\n\\n\", cmdname.c_str());\n\tNdvDef::printUsage();\n\tprintf(\n\"  -outndv <output_nodata_val>        Output no-data value\\n\"\n\"\\n\"\n\"Operation:\\n\"\n\"  -linear-stretch <target_avg> <target_stddev>      Linear stretch to a target range\\n\"\n\"  -percentile-range <from: 0.0-1.0> <to: 0.0-1.0>   Linear stretch using a percentile range of input\\n\"\n\"  -histeq <target_stddev>                           Histogram normalize to a target bell curve\\n\"\n\"  -dump-histogram                                   Just print the histogram to console\\n\"\n\"\\n\"\n\"Input can be any integer or floating type (but not complex).  Output is 8-bit.\\n\"\n);\n\texit(1);\n}\n\nint main(int argc, char *argv[]) {\n\tconst std::string cmdname = argv[0];\n\tif(argc == 1) usage(cmdname);\n\tstd::vector<std::string> arg_list = argv_to_list(argc, argv);\n\n\tstd::string src_fn;\n\tstd::string dst_fn;\n\tstd::string output_format;\n\n\tint mode_histeq = 0;\n\tint mode_stddev = 0;\n\tdouble dst_avg = -1;\n\tdouble dst_stddev = -1;\n\tint mode_percentile = 0;\n\tint mode_dump_histogram = 0;\n\tdouble from_percentile = -1;\n\tdouble to_percentile = -1;\n\tint out_ndv = 0, set_out_ndv = 0;\n\n\tNdvDef ndv_def = NdvDef(arg_list);\n\n\tsize_t argp = 1;\n\twhile(argp < arg_list.size()) {\n\t\tconst std::string &arg = arg_list[argp++];\n\t\t// FIXME - check for duplicate values\n\t\tif(arg[0] == '-') {\n\t\t\ttry {\n\t\t\t\tif(arg == \"-of\") {\n\t\t\t\t\tif(argp == arg_list.size()) usage(cmdname);\n\t\t\t\t\toutput_format = arg_list[argp++];\n\t\t\t\t} else if(arg == \"-linear-stretch\") {\n\t\t\t\t\tif(argp == arg_list.size()) usage(cmdname);\n\t\t\t\t\tdst_avg = boost::lexical_cast<double>(arg_list[argp++]);\n\n\t\t\t\t\tif(argp == arg_list.size()) usage(cmdname);\n\t\t\t\t\tdst_stddev = boost::lexical_cast<double>(arg_list[argp++]);\n\n\t\t\t\t\tmode_stddev = 1;\n\t\t\t\t} else if(arg == \"-percentile-range\") {\n\t\t\t\t\tif(argp == arg_list.size()) usage(cmdname);\n\t\t\t\t\tfrom_percentile = boost::lexical_cast<double>(arg_list[argp++]);\n\n\t\t\t\t\tif(argp == arg_list.size()) usage(cmdname);\n\t\t\t\t\tto_percentile = boost::lexical_cast<double>(arg_list[argp++]);\n\n\t\t\t\t\tmode_percentile = 1;\n\t\t\t\t} else if(arg == \"-histeq\") {\n\t\t\t\t\tif(argp == arg_list.size()) usage(cmdname);\n\t\t\t\t\tdst_stddev = boost::lexical_cast<double>(arg_list[argp++]);\n\n\t\t\t\t\tmode_histeq = 1;\n\t\t\t\t} else if(arg == \"-dump-histogram\") {\n\t\t\t\t\tmode_dump_histogram = 1;\n\t\t\t\t} else if(arg == \"-outndv\") {\n\t\t\t\t\tif(argp == arg_list.size()) usage(cmdname);\n\t\t\t\t\tint64_t ndv_long = boost::lexical_cast<int64_t>(arg_list[argp++]);\n\t\t\t\t\tif(ndv_long < 0 || ndv_long > 255) fatal_error(\"ndv must be in the range 0..255\");\n\t\t\t\t\tout_ndv = boost::numeric_cast<uint8_t>(ndv_long);\n\t\t\t\t\tset_out_ndv++;\n\t\t\t\t} else {\n\t\t\t\t\tusage(cmdname);\n\t\t\t\t}\n\t\t\t} catch(boost::bad_lexical_cast &e) {\n\t\t\t\tfatal_error(\"cannot parse number given on command line\");\n\t\t\t} catch(boost::bad_numeric_cast &e) {\n\t\t\t\tfatal_error(\"number given on command line out of range: %s\", e.what());\n\t\t\t}\n\t\t} else {\n\t\t\tif(src_fn.empty()) {\n\t\t\t\tsrc_fn = arg;\n\t\t\t} else if(dst_fn.empty()) {\n\t\t\t\tdst_fn = arg;\n\t\t\t} else {\n\t\t\t\tusage(cmdname);\n\t\t\t}\n\t\t}\n\t}\n\n\tif(src_fn.empty()) usage(cmdname);\n\tif(dst_fn.empty() != (mode_dump_histogram > 0)) usage(cmdname);\n\tif(mode_percentile + mode_stddev + mode_histeq + mode_dump_histogram > 1) usage(cmdname);\n\tif(mode_stddev && (dst_avg < 0 || dst_stddev < 0)) usage(cmdname);\n\tif(mode_percentile && !(\n\t\t0 <= from_percentile && \n\t\tfrom_percentile < to_percentile &&\n\t\tto_percentile <= 1)) usage(cmdname);\n\n\tif(output_format.empty()) output_format = \"GTiff\";\n\n\tGDALAllRegister();\n\n\t//////// open source ////////\n\n\tGDALDatasetH src_ds = GDALOpen(src_fn.c_str(), GA_ReadOnly);\n\tif(!src_ds) fatal_error(\"open failed\");\n\n\tsize_t w = GDALGetRasterXSize(src_ds);\n\tsize_t h = GDALGetRasterYSize(src_ds);\n\tif(!w || !h) fatal_error(\"missing width/height\");\n\tsize_t src_band_count = GDALGetRasterCount(src_ds);\n\tprintf(\"Input size is %zd, %zd, %zd\\n\", w, h, src_band_count);\n\n\tstd::vector<size_t> bandlist;\n\tfor(size_t i=0; i<src_band_count; i++) {\n\t\tbandlist.push_back(i+1);\n\t}\n\tsize_t dst_band_count = bandlist.size();\n\n\tif(ndv_def.empty()) {\n\t\tndv_def = NdvDef(src_ds, bandlist);\n\t}\n\n\tbool use_ndv = !ndv_def.empty();\n\tif(use_ndv && !set_out_ndv) {\n\t\tif(ndv_def.slabs.size() == 1) {\n\t\t\tconst NdvSlab &slab = ndv_def.slabs[0];\n\t\t\tassert(slab.range_by_band.size());\n\t\t\tconst NdvInterval &range = slab.range_by_band[0];\n\t\t\tif(range.first == range.second) {\n\t\t\t\tdouble v = range.first;\n\t\t\t\tout_ndv = (uint8_t)v;\n\t\t\t\tif((double)out_ndv == v) {\n\t\t\t\t\tset_out_ndv++;\n\t\t\t\t} else {\n\t\t\t\t\tprintf(\"Cannot use %g as an NDV value because it cannot be cast to an 8-bit number.\\n\", v);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(!set_out_ndv) {\n\t\t\tout_ndv = 0;\n\t\t\tset_out_ndv++;\n\t\t}\n\t\tprintf(\"Output NDV is defaulting to %d.\\n\", out_ndv);\n\t}\n\n\t//////// open output ////////\n\n\tprintf(\"Output size is %zd x %zd x %zd\\n\", w, h, dst_band_count);\n\n\tGDALDriverH dst_driver = GDALGetDriverByName(output_format.c_str());\n\tif(!dst_driver) fatal_error(\"unrecognized output format (%s)\", output_format.c_str());\n\n\t//////// open bands ////////\n\n\tstd::vector<GDALRasterBandH> src_bands;\n\tstd::vector<GDALRasterBandH> dst_bands;\n\n\tfor(size_t band_idx=0; band_idx<dst_band_count; band_idx++) {\n\t\tsrc_bands.push_back(GDALGetRasterBand(src_ds, bandlist[band_idx]));\n\t}\n\n\t//////// find optimal binning ////////\n\n\tstd::vector<Binning> binnings(dst_band_count);\n\t{\n\t\t// computed on demand\n\t\tstd::vector<std::pair<double, double> > minmax;\n\n\t\tfor(size_t band_idx=0; band_idx<dst_band_count; band_idx++) {\n\t\t\tBinning &binning = binnings[band_idx];\n\t\t\tGDALDataType dt = GDALGetRasterDataType(src_bands[band_idx]);\n\t\t\tswitch(dt) {\n\t\t\t\tcase GDT_Byte:\n\t\t\t\t\tbinning.nbins = 256;\n\t\t\t\t\tbinning.offset = 0;\n\t\t\t\t\tbinning.scale = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase GDT_UInt16:\n\t\t\t\t\tbinning.nbins = 65536;\n\t\t\t\t\tbinning.offset = 0;\n\t\t\t\t\tbinning.scale = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase GDT_Int16:\n\t\t\t\t\tbinning.nbins = 65536;\n\t\t\t\t\tbinning.offset = -32768;\n\t\t\t\t\tbinning.scale = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tif(minmax.empty()) {\n\t\t\t\t\t\tprintf(\"Computing min/max values...\\n\");\n\t\t\t\t\t\tminmax = compute_minmax(src_bands, ndv_def, w, h);\n\t\t\t\t\t}\n\t\t\t\t\tdouble min = minmax[band_idx].first;\n\t\t\t\t\tdouble max = minmax[band_idx].second;\n\t\t\t\t\t// a compromise between memory usage and datavalue resolution\n\t\t\t\t\tbinning.nbins = 10000000;\n\t\t\t\t\tbinning.offset = min;\n\t\t\t\t\tbinning.scale = (max - min) / double(binning.nbins-1);\n\t\t\t}\n\t\t}\n\t}\n\n\t//////// compute lookup table ////////\n\n\tprintf(\"\\nComputing histogram...\\n\");\n\tstd::vector<Histogram> histograms =\n\t\tcompute_histogram(src_bands, ndv_def, w, h, binnings);\n\n\tfor(size_t band_idx=0; band_idx<dst_band_count; band_idx++) {\n\t\tHistogram &hg = histograms[band_idx];\n\t\tprintf(\"band %zd: min=%g, max=%g, mean=%g, stddev=%g, valid_count=%zd, ndv_count=%zd\\n\",\n\t\t\tband_idx+1, hg.min, hg.max, hg.mean, hg.stddev, hg.data_count, hg.ndv_count);\n\t\tif(mode_dump_histogram) {\n\t\t\tfor(int i=0; i<hg.binning.nbins; i++) {\n\t\t\t\tprintf(\"bin %d: val=%g cnt=%zd\\n\",\n\t\t\t\t\ti, hg.binning.from_bin(i), hg.counts[i]);\n\t\t\t}\n\t\t}\n\t}\n\tif(mode_dump_histogram) {\n\t\treturn 0;\n\t}\n\n\t//////// open output ////////\n\n\tGDALDatasetH dst_ds = GDALCreate(dst_driver, dst_fn.c_str(), w, h, dst_band_count, GDT_Byte, NULL);\n\tif(!dst_ds) fatal_error(\"couldn't create output\");\n\tcopyGeoCode(dst_ds, src_ds);\n\n\tfor(size_t band_idx=0; band_idx<dst_band_count; band_idx++) {\n\t\tdst_bands.push_back(GDALGetRasterBand(dst_ds, band_idx+1));\n\t}\n\n\t//////// compute tranformation parameters ////////\n\n\tconst int output_range = 256;\n\tbool use_table; // otherwise, use linear\n\tstd::vector<std::vector<uint8_t> > xform_table(dst_band_count);\n\tstd::vector<double> lin_scales(dst_band_count);\n\tstd::vector<double> lin_offsets(dst_band_count);\n\n\tif(mode_histeq) {\n\t\tuse_table = true;\n\t\tfor(size_t band_idx=0; band_idx<dst_band_count; band_idx++) {\n\t\t\txform_table[band_idx] = invert_histogram_to_gaussian(\n\t\t\t\thistograms[band_idx], dst_stddev, output_range);\n\t\t}\n\t} else{\n\t\tuse_table = false;\n\t\tbool was_nop = false;\n\t\tif(mode_percentile) {\n\t\t\tfor(size_t band_idx=0; band_idx<dst_band_count; band_idx++) {\n\t\t\t\tget_scale_from_percentile(\n\t\t\t\t\thistograms[band_idx], output_range, from_percentile, to_percentile,\n\t\t\t\t\t&lin_scales[band_idx], &lin_offsets[band_idx]);\n\t\t\t}\n\t\t} else if(mode_stddev) {\n\t\t\tfor(size_t band_idx=0; band_idx<dst_band_count; band_idx++) {\n\t\t\t\tHistogram &hg = histograms[band_idx];\n\t\t\t\tlin_scales[band_idx] = hg.stddev ? dst_stddev / hg.stddev : 0;\n\t\t\t\tlin_offsets[band_idx] = hg.mean - dst_avg / lin_scales[band_idx];\n\t\t\t}\n\t\t} else { // no transformation\n\t\t\tprintf(\"\\nWarning: no transformation was specified!  I'll just cast the input to 8-bit.\\n\");\n\t\t\twas_nop = true;\n\t\t\tfor(size_t band_idx=0; band_idx<dst_band_count; band_idx++) {\n\t\t\t\tlin_scales[band_idx] = 1;\n\t\t\t\tlin_offsets[band_idx] = 0;\n\t\t\t}\n\t\t}\n\t\tif(!was_nop) {\n\t\t\tprintf(\"\\nLinear stretch:\\n\");\n\t\t\tfor(size_t band_idx=0; band_idx<dst_band_count; band_idx++) {\n\t\t\t\tdouble scale = lin_scales[band_idx];\n\t\t\t\tdouble offset = lin_offsets[band_idx];\n\t\t\t\tprintf(\"band %zd: scale=%f, offset=%f, src_range=[%f, %f]\\n\",\n\t\t\t\t\tband_idx+1, scale, offset, offset, ((double)(output_range-1)/scale)+offset);\n\t\t\t}\n\t\t}\n\t}\n\n\thistograms.clear(); // free up memory\n\n\tif(use_table) {\n\t\t// avoid ndv in output for good pixels\n\t\tif(use_ndv) {\n\t\t\tfor(size_t band_idx=0; band_idx<dst_band_count; band_idx++) {\n\t\t\t\tfor(size_t i=0; i<xform_table[band_idx].size(); i++) {\n\t\t\t\t\tuint8_t v = xform_table[band_idx][i];\n\t\t\t\t\tif(v == out_ndv) {\n\t\t\t\t\t\tif(out_ndv < output_range/2) v++;\n\t\t\t\t\t\telse v--;\n\t\t\t\t\t}\n\t\t\t\t\txform_table[band_idx][i] = v;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t//////// do transformation ////////\n\n\tprintf(\"\\nComputing output...\\n\");\n\n\tint blocksize_x_int, blocksize_y_int;\n\tGDALGetBlockSize(src_bands[0], &blocksize_x_int, &blocksize_y_int);\n\tsize_t blocksize_x = blocksize_x_int;\n\tsize_t blocksize_y = blocksize_y_int;\n\tsize_t block_len = blocksize_x*blocksize_y;\n\n\tstd::vector<std::vector<double> > buf_in(dst_band_count);\n\tstd::vector<std::vector<uint8_t> > buf_out(dst_band_count);\n\tfor(size_t band_idx=0; band_idx<dst_band_count; band_idx++) {\n\t\tbuf_in[band_idx].resize(block_len);\n\t\tbuf_out[band_idx].resize(block_len);\n\t}\n\tstd::vector<uint8_t> ndv_mask(block_len);\n\n\tfor(size_t boff_y=0; boff_y<h; boff_y+=blocksize_y) {\n\t\tsize_t bsize_y = blocksize_y;\n\t\tif(bsize_y + boff_y > h) bsize_y = h - boff_y;\n\t\tfor(size_t boff_x=0; boff_x<w; boff_x+=blocksize_x) {\n\t\t\tsize_t bsize_x = blocksize_x;\n\t\t\tif(bsize_x + boff_x > w) bsize_x = w - boff_x;\n\n\t\t\tblock_len = bsize_x*bsize_y;\n\n\t\t\tdouble progress = \n\t\t\t\t((double)boff_y * (double)w +\n\t\t\t\t(double)boff_x * (double)bsize_y) /\n\t\t\t\t((double)w * (double)h);\n\t\t\tGDALTermProgress(progress, NULL, NULL);\n\n\t\t\tfor(size_t band_idx=0; band_idx<dst_band_count; band_idx++) {\n\t\t\t\tGDALRasterIO(src_bands[band_idx], GF_Read, boff_x, boff_y, bsize_x, bsize_y, \n\t\t\t\t\t&buf_in[band_idx][0], bsize_x, bsize_y, GDT_Float64, 0, 0);\n\t\t\t}\n\n\t\t\tndv_def.getNdvMask(buf_in, &ndv_mask[0], block_len);\n\n\t\t\tfor(size_t band_idx=0; band_idx<dst_band_count; band_idx++) {\n\t\t\t\tdouble *p_in = &buf_in[band_idx][0];\n\t\t\t\tuint8_t *p_out = &buf_out[band_idx][0];\n\t\t\t\tuint8_t *p_ndv = &ndv_mask[0];\n\t\t\t\tif(use_table) {\n\t\t\t\t\tuint8_t *xform = &xform_table[band_idx][0];\n\t\t\t\t\tBinning binning = binnings[band_idx];\n\n\t\t\t\t\tfor(size_t i=0; i<block_len; i++) {\n\t\t\t\t\t\tif(*p_ndv) {\n\t\t\t\t\t\t\t*p_out = out_ndv;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t*p_out = xform[binning.to_bin(*p_in)];\n\t\t\t\t\t\t\t//printf(\"%g %d %d\\n\", *p_in, binning.to_bin(*p_in), *p_out);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tp_in++; p_out++; p_ndv++;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tdouble scale = lin_scales[band_idx];\n\t\t\t\t\tdouble offset = lin_offsets[band_idx];\n\t\t\t\t\tfor(size_t i=0; i<block_len; i++) {\n\t\t\t\t\t\tif(*p_ndv) {\n\t\t\t\t\t\t\t*p_out = out_ndv;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdouble out_dbl = (*p_in - offset) * scale;\n\t\t\t\t\t\t\tuint8_t v =\n\t\t\t\t\t\t\t\t(out_dbl < 0) ? 0 :\n\t\t\t\t\t\t\t\t(out_dbl > output_range-1) ? output_range-1 :\n\t\t\t\t\t\t\t\tuint8_t(out_dbl);\n\t\t\t\t\t\t\tif(v == out_ndv) {\n\t\t\t\t\t\t\t\tif(out_ndv < output_range/2) v++;\n\t\t\t\t\t\t\t\telse v--;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t*p_out = v;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tp_in++; p_out++; p_ndv++;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tGDALRasterIO(dst_bands[band_idx], GF_Write, boff_x, boff_y, bsize_x, bsize_y, \n\t\t\t\t\t&buf_out[band_idx][0], bsize_x, bsize_y, GDT_Byte, 0, 0);\n\t\t\t} // band\n\t\t} // block x\n\t} // block y\n\n\tGDALClose(src_ds);\n\tGDALClose(dst_ds);\n\n\tGDALTermProgress(1, NULL, NULL);\n\n\treturn 0;\n}\n\nstd::vector<std::pair<double, double> > compute_minmax(\n\tconst std::vector<GDALRasterBandH> &src_bands, const NdvDef &ndv_def, \n\tsize_t w, size_t h\n) {\n\tsize_t band_count = src_bands.size();\n\tstd::vector<std::pair<double, double> > minmax(band_count);\n\n\tint blocksize_x_int, blocksize_y_int;\n\tGDALGetBlockSize(src_bands[0], &blocksize_x_int, &blocksize_y_int);\n\tsize_t blocksize_x = blocksize_x_int;\n\tsize_t blocksize_y = blocksize_y_int;\n\tsize_t block_len = blocksize_x*blocksize_y;\n\n\tstd::vector<std::vector<double> > buf_in(band_count);\n\tfor(size_t band_idx=0; band_idx<band_count; band_idx++) {\n\t\tbuf_in[band_idx].resize(block_len);\n\t}\n\tstd::vector<uint8_t> ndv_mask(block_len);\n\n\tstd::vector<bool> got_data(band_count);\n\n\tfor(size_t boff_y=0; boff_y<h; boff_y+=blocksize_y) {\n\t\tsize_t bsize_y = blocksize_y;\n\t\tif(bsize_y + boff_y > h) bsize_y = h - boff_y;\n\t\tfor(size_t boff_x=0; boff_x<w; boff_x+=blocksize_x) {\n\t\t\tsize_t bsize_x = blocksize_x;\n\t\t\tif(bsize_x + boff_x > w) bsize_x = w - boff_x;\n\n\t\t\tblock_len = bsize_x*bsize_y;\n\n\t\t\tdouble progress = \n\t\t\t\t((double)boff_y * (double)w +\n\t\t\t\t(double)boff_x * (double)bsize_y) /\n\t\t\t\t((double)w * (double)h);\n\t\t\tGDALTermProgress(progress, NULL, NULL);\n\n\t\t\tfor(size_t band_idx=0; band_idx<band_count; band_idx++) {\n\t\t\t\tGDALRasterIO(src_bands[band_idx], GF_Read, boff_x, boff_y, bsize_x, bsize_y, \n\t\t\t\t\t&buf_in[band_idx][0], bsize_x, bsize_y, GDT_Float64, 0, 0);\n\t\t\t}\n\n\t\t\tndv_def.getNdvMask(buf_in, &ndv_mask[0], block_len);\n\n\t\t\tfor(size_t band_idx=0; band_idx<band_count; band_idx++) {\n\t\t\t\tfor(size_t i=0; i<block_len; i++) {\n\t\t\t\t\tif(ndv_mask[i]) continue;\n\t\t\t\t\tdouble v = buf_in[band_idx][i];\n\t\t\t\t\tif(std::isnan(v) || std::isinf(v)) continue;\n\n\t\t\t\t\tassert(!minmax.empty());\n\t\t\t\t\tdouble &min = minmax[band_idx].first;\n\t\t\t\t\tdouble &max = minmax[band_idx].second;\n\t\t\t\t\tif(!got_data[band_idx]) {\n\t\t\t\t\t\tmin = v;\n\t\t\t\t\t\tmax = v;\n\t\t\t\t\t\tgot_data[band_idx] = true;\n\t\t\t\t\t}\n\t\t\t\t\tif(v < min) min = v;\n\t\t\t\t\tif(v > max) max = v;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tGDALTermProgress(1, NULL, NULL);\n\n\treturn minmax;\n}\n\nstd::vector<Histogram> compute_histogram(\n\tconst std::vector<GDALRasterBandH> &src_bands, const NdvDef &ndv_def, \n\tsize_t w, size_t h, const std::vector<Binning> &binnings\n) {\n\tsize_t band_count = src_bands.size();\n\tstd::vector<Histogram> histograms(band_count);\n\n\tfor(size_t band_idx=0; band_idx<band_count; band_idx++) {\n\t\thistograms[band_idx].binning = binnings[band_idx];\n\t\thistograms[band_idx].counts.assign(binnings[band_idx].nbins, 0);\n\t}\n\n\tint blocksize_x_int, blocksize_y_int;\n\tGDALGetBlockSize(src_bands[0], &blocksize_x_int, &blocksize_y_int);\n\tsize_t blocksize_x = blocksize_x_int;\n\tsize_t blocksize_y = blocksize_y_int;\n\tsize_t block_len = blocksize_x*blocksize_y;\n\n\tstd::vector<std::vector<double> > buf_in(band_count);\n\tfor(size_t band_idx=0; band_idx<band_count; band_idx++) {\n\t\tbuf_in[band_idx].resize(block_len);\n\t}\n\tstd::vector<uint8_t> ndv_mask(block_len);\n\n\tstd::vector<bool> first_valid_pixel(band_count, true);\n\n\tfor(size_t boff_y=0; boff_y<h; boff_y+=blocksize_y) {\n\t\tsize_t bsize_y = blocksize_y;\n\t\tif(bsize_y + boff_y > h) bsize_y = h - boff_y;\n\t\tfor(size_t boff_x=0; boff_x<w; boff_x+=blocksize_x) {\n\t\t\tsize_t bsize_x = blocksize_x;\n\t\t\tif(bsize_x + boff_x > w) bsize_x = w - boff_x;\n\n\t\t\tblock_len = bsize_x*bsize_y;\n\n\t\t\tdouble progress = \n\t\t\t\t((double)boff_y * (double)w +\n\t\t\t\t(double)boff_x * (double)bsize_y) /\n\t\t\t\t((double)w * (double)h);\n\t\t\tGDALTermProgress(progress, NULL, NULL);\n\n\t\t\tfor(size_t band_idx=0; band_idx<band_count; band_idx++) {\n\t\t\t\tGDALRasterIO(src_bands[band_idx], GF_Read, boff_x, boff_y, bsize_x, bsize_y, \n\t\t\t\t\t&buf_in[band_idx][0], bsize_x, bsize_y, GDT_Float64, 0, 0);\n\t\t\t}\n\n\t\t\tndv_def.getNdvMask(buf_in, &ndv_mask[0], block_len);\n\n\t\t\tfor(size_t band_idx=0; band_idx<band_count; band_idx++) {\n\t\t\t\tHistogram &hg = histograms[band_idx];\n\t\t\t\tdouble *p = &buf_in[band_idx][0];\n\t\t\t\t\n\t\t\t\tfor(size_t i=0; i<block_len; i++) {\n\t\t\t\t\tif(ndv_mask[i]) {\n\t\t\t\t\t\thg.ndv_count++;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdouble v = p[i];\n\t\t\t\t\t\thg.counts[hg.binning.to_bin(v)]++;\n\t\t\t\t\t\tif(first_valid_pixel[band_idx]) {\n\t\t\t\t\t\t\thg.min = hg.max = v;\n\t\t\t\t\t\t\tfirst_valid_pixel[band_idx] = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(v < hg.min) hg.min = v;\n\t\t\t\t\t\tif(v > hg.max) hg.max = v;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tGDALTermProgress(1, NULL, NULL);\n\n\tfor(size_t band_idx=0; band_idx<band_count; band_idx++) {\n\t\tHistogram &hg = histograms[band_idx];\n\t\tdouble accum = 0;\n\t\tfor(int i=0; i<hg.binning.nbins; i++) {\n\t\t\tsize_t cnt = hg.counts[i];\n\t\t\tdouble v = hg.binning.from_bin(i);\n\t\t\thg.data_count += cnt;\n\t\t\taccum += v * cnt;\n\t\t}\n\t\thg.mean = accum / hg.data_count;\n\n\t\tdouble var_accum = 0;\n\t\tfor(int i=0; i<hg.binning.nbins; i++) {\n\t\t\tsize_t cnt = hg.counts[i];\n\t\t\tdouble v = hg.binning.from_bin(i);\n\t\t\tvar_accum += (v-hg.mean) * (v-hg.mean) * cnt;\n\t\t}\n\t\thg.stddev = sqrt(var_accum / hg.data_count);\n\t}\n\n\treturn histograms;\n}\n\nvoid get_scale_from_percentile(\n\tconst Histogram &histogram, int output_range,\n\tdouble from_percentile, double to_percentile,\n\tdouble *scale_out, double *offset_out\n) {\n\tsize_t start_count = (size_t)(histogram.data_count * from_percentile);\n\tsize_t end_count = (size_t)(histogram.data_count * to_percentile);\n\n\tsize_t cnt = 0;\n\tint from_idx = -1;\n\tint to_idx = -1;\n\tfor(int i=0; i<histogram.binning.nbins; i++) {\n\t\tif(cnt <= start_count) from_idx = i;\n\t\tcnt += histogram.counts[i];\n\t\tif(cnt <= end_count) to_idx = i; \n\t\telse break;\n\t}\n\tif(from_idx<0 || to_idx<0) fatal_error(\"impossible: could not find window\");\n\tif(from_idx == to_idx) { from_idx=0; to_idx=histogram.binning.nbins-1; }\n\n\tdouble from_val = histogram.binning.from_bin(from_idx);\n\tdouble to_val = histogram.binning.from_bin(to_idx);\n\n\t*scale_out = (double)(output_range-1) / (double)(to_val-from_val);\n\t*offset_out = from_val;\n}\n\nstd::vector<double> gen_gaussian(double variance, int bin_count) {\n\tstd::vector<double> arr(bin_count);\n\tdouble total = 0;\n\tfor(int i=0; i<bin_count; i++) {\n\t\tif(variance == 0.0) {\n\t\t\t// if variance==0.0, just use a uniform distribution\n\t\t\tarr[i] = 1;\n\t\t} else {\n\t\t\t// Gaussian distribution.  Large variance gives\n\t\t\t// a more level curve, small variance gives\n\t\t\t// a curved peaked at center.\n\t\t\tdouble x = (double)(i-bin_count/2) / variance;\n\t\t\tarr[i] = exp(-x*x);\n\t\t}\n\t\ttotal += arr[i];\n\t}\n\n\tfor(int i=0; i<bin_count; i++) arr[i] /= total;\n\n\treturn arr;\n}\n\nstd::vector<uint8_t> invert_histogram(\n\tconst Histogram &src_h_in,\n\tconst std::vector<double> &dst_h,\n\tsize_t output_range\n) {\n\tstd::vector<size_t> src_h(src_h_in.counts);\n\tsize_t pixel_count = 0;\n\tfor(size_t i=0; i<src_h.size(); i++) pixel_count += src_h[i];\n\n\tstd::vector<uint8_t> out_h(src_h.size());\n\tdouble src_total = 0;\n\tdouble dst_total = 0;\n\tuint8_t j = 0;\n\tfor(size_t i=0; i<src_h.size(); i++) {\n\t\tout_h[i] = j;\n\t\tsrc_total += src_h[i];\n\t\twhile(j<output_range-1 && dst_total < src_total) {\n\t\t\tdst_total += dst_h[j++] * (double)pixel_count;\n\t\t}\n\t}\n\n\treturn out_h;\n}\n\nstd::vector<uint8_t> invert_histogram_to_gaussian(\n\tconst Histogram &histogram_in, double variance, \n\tint output_range\n) {\n\tstd::vector<double> gaussian = gen_gaussian(variance, output_range);\n\treturn invert_histogram(histogram_in, gaussian, output_range);\n}\n\nvoid copyGeoCode(GDALDatasetH dst_ds, GDALDatasetH src_ds) {\n\tdouble affine[6];\n\tif(GDALGetGeoTransform(src_ds, affine) == CE_None) {\n\t\tGDALSetGeoTransform(dst_ds, affine);\n\t}\n\tGDALSetProjection(dst_ds, GDALGetProjectionRef(src_ds));\n}\n", "meta": {"hexsha": "90080eee4eef7e6a938db96205d851e1c75e3de6", "size": 22943, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/gdal_contrast_stretch.cc", "max_stars_repo_name": "asirobots/dans-gdal-scripts", "max_stars_repo_head_hexsha": "67758cec35b68d227443195951a4d05056ab96dc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2015-02-03T10:21:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T23:45:49.000Z", "max_issues_repo_path": "src/gdal_contrast_stretch.cc", "max_issues_repo_name": "asirobots/dans-gdal-scripts", "max_issues_repo_head_hexsha": "67758cec35b68d227443195951a4d05056ab96dc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2015-02-03T10:44:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-13T16:37:27.000Z", "max_forks_repo_path": "src/gdal_contrast_stretch.cc", "max_forks_repo_name": "asirobots/dans-gdal-scripts", "max_forks_repo_head_hexsha": "67758cec35b68d227443195951a4d05056ab96dc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2015-02-01T20:25:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T02:08:28.000Z", "avg_line_length": 30.754691689, "max_line_length": 217, "alphanum_fraction": 0.6730593209, "num_tokens": 7031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2718286493343826}}
{"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 ABB_IRB1600_145_FK_FAST_HPP\n#define ABB_IRB1600_145_FK_FAST_HPP\n\nnamespace ABB_IRB1600_145_FK_FAST\n{\n    const size_t ABB_IRB1600_145_NUM_ACTIVE_JOINTS = 6;\n    const size_t ABB_IRB1600_145_NUM_LINKS = 8;\n\n    const std::string ABB_IRB1600_145_ACTIVE_JOINT_1_NAME = \"joint_1\";\n    const std::string ABB_IRB1600_145_ACTIVE_JOINT_2_NAME = \"joint_2\";\n    const std::string ABB_IRB1600_145_ACTIVE_JOINT_3_NAME = \"joint_3\";\n    const std::string ABB_IRB1600_145_ACTIVE_JOINT_4_NAME = \"joint_4\";\n    const std::string ABB_IRB1600_145_ACTIVE_JOINT_5_NAME = \"joint_5\";\n    const std::string ABB_IRB1600_145_ACTIVE_JOINT_6_NAME = \"joint_6\";\n\n    const std::string ABB_IRB1600_145_LINK_1_NAME = \"link_0\";\n    const std::string ABB_IRB1600_145_LINK_2_NAME = \"link_1\";\n    const std::string ABB_IRB1600_145_LINK_3_NAME = \"link_2\";\n    const std::string ABB_IRB1600_145_LINK_4_NAME = \"link_3\";\n    const std::string ABB_IRB1600_145_LINK_5_NAME = \"link_4\";\n    const std::string ABB_IRB1600_145_LINK_6_NAME = \"link_5\";\n    const std::string ABB_IRB1600_145_LINK_7_NAME = \"link_6\";\n    const std::string ABB_IRB1600_145_LINK_8_NAME = \"link_7\";\n\n    typedef std::vector<Eigen::Isometry3d, Eigen::aligned_allocator<Eigen::Isometry3d>> VectorIsometry3d;\n\n    inline Eigen::Isometry3d Get_base_joint1_LinkJointTransform(const double joint_val)\n    {\n        Eigen::Translation3d pre_joint_translation(0.0, 0.0, 0.1245);\n        Eigen::Quaterniond pre_joint_rotation(1.0, 0.0, 0.0, 0.0);\n        Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n        Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n        Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitZ()));\n        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        Eigen::Translation3d pre_joint_translation(0.15, -0.1395, 0.362);\n        Eigen::Quaterniond pre_joint_rotation(1.0, 0.0, 0.0, 0.0);\n        Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n        Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n        Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitY()));\n        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        Eigen::Translation3d pre_joint_translation(0.0, 0.028, 0.7);\n        Eigen::Quaterniond pre_joint_rotation(1.0, 0.0, 0.0, 0.0);\n        Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n        Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n        Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitY()));\n        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        Eigen::Translation3d pre_joint_translation(0.314, 0.107, 0.0);\n        Eigen::Quaterniond pre_joint_rotation(1.0, 0.0, 0.0, 0.0);\n        Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n        Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n        Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitX()));\n        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        Eigen::Translation3d pre_joint_translation(0.286, 0.0, 0.0);\n        Eigen::Quaterniond pre_joint_rotation(1.0, 0.0, 0.0, 0.0);\n        Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n        Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n        Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitY()));\n        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        Eigen::Translation3d pre_joint_translation(0.0, 0.0, 0.0);\n        Eigen::Quaterniond pre_joint_rotation(1.0, 0.0, 0.0, 0.0);\n        Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n        Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n        Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitX()));\n        Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;\n        return (pre_joint_transform * joint_transform);\n    }\n\n    inline Eigen::Isometry3d Get_Fixed_link_6_joint_tool_LinkJointTransform(void)\n    {\n        Eigen::Translation3d pre_joint_translation(0.065, 0.0, 0.0);\n        Eigen::Quaterniond pre_joint_rotation(0.7071067811865476, 0.0, 0.7071067811865476, 0.0);\n        Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n        return pre_joint_transform;\n    }\n\n    inline VectorIsometry3d GetLinkTransforms(const std::vector<double>& configuration, const Eigen::Isometry3d& base_transform=Eigen::Isometry3d::Identity())\n    {\n        assert(configuration.size() == ABB_IRB1600_145_NUM_ACTIVE_JOINTS);\n        VectorIsometry3d link_transforms(ABB_IRB1600_145_NUM_LINKS);\n        link_transforms[0] = base_transform;\n        link_transforms[1] = link_transforms[0] * Get_base_joint1_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_Fixed_link_6_joint_tool_LinkJointTransform();\n        return link_transforms;\n    }\n\n    inline VectorIsometry3d GetLinkTransforms(std::map<std::string, double> configuration, const Eigen::Isometry3d& base_transform=Eigen::Isometry3d::Identity())\n    {\n        std::vector<double> configuration_vector(ABB_IRB1600_145_NUM_ACTIVE_JOINTS);\n        configuration_vector[0] = configuration[ABB_IRB1600_145_ACTIVE_JOINT_1_NAME];\n        configuration_vector[1] = configuration[ABB_IRB1600_145_ACTIVE_JOINT_2_NAME];\n        configuration_vector[2] = configuration[ABB_IRB1600_145_ACTIVE_JOINT_3_NAME];\n        configuration_vector[3] = configuration[ABB_IRB1600_145_ACTIVE_JOINT_4_NAME];\n        configuration_vector[4] = configuration[ABB_IRB1600_145_ACTIVE_JOINT_5_NAME];\n        configuration_vector[5] = configuration[ABB_IRB1600_145_ACTIVE_JOINT_6_NAME];\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[ABB_IRB1600_145_LINK_1_NAME] = link_transforms[0];\n        link_transforms_map[ABB_IRB1600_145_LINK_2_NAME] = link_transforms[1];\n        link_transforms_map[ABB_IRB1600_145_LINK_3_NAME] = link_transforms[2];\n        link_transforms_map[ABB_IRB1600_145_LINK_4_NAME] = link_transforms[3];\n        link_transforms_map[ABB_IRB1600_145_LINK_5_NAME] = link_transforms[4];\n        link_transforms_map[ABB_IRB1600_145_LINK_6_NAME] = link_transforms[5];\n        link_transforms_map[ABB_IRB1600_145_LINK_7_NAME] = link_transforms[6];\n        link_transforms_map[ABB_IRB1600_145_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[ABB_IRB1600_145_LINK_1_NAME] = link_transforms[0];\n        link_transforms_map[ABB_IRB1600_145_LINK_2_NAME] = link_transforms[1];\n        link_transforms_map[ABB_IRB1600_145_LINK_3_NAME] = link_transforms[2];\n        link_transforms_map[ABB_IRB1600_145_LINK_4_NAME] = link_transforms[3];\n        link_transforms_map[ABB_IRB1600_145_LINK_5_NAME] = link_transforms[4];\n        link_transforms_map[ABB_IRB1600_145_LINK_6_NAME] = link_transforms[5];\n        link_transforms_map[ABB_IRB1600_145_LINK_7_NAME] = link_transforms[6];\n        link_transforms_map[ABB_IRB1600_145_LINK_8_NAME] = link_transforms[7];\n        return link_transforms_map;\n    }\n}\n\n#endif // ABB_IRB1600_145_FK_FAST_HPP\n", "meta": {"hexsha": "a6d95dd0efe3d8f8c62f8c512caa38e0f2dbdb63", "size": 9720, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Modules/planning/FastPlanner/plan_env/ThirdParty/arc_utilities/include/arc_utilities/abb_irb1600_145_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/abb_irb1600_145_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/abb_irb1600_145_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": 57.5147928994, "max_line_length": 188, "alphanum_fraction": 0.754526749, "num_tokens": 2766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.2717428732771955}}
{"text": "// OS / System\n#include <iostream>\n#include <vector>\n\n// Boost\n#include <boost/any.hpp>\n\n// Lapack\n// #include <Accelerate/Accelerate.h>\n\nextern \"C\" void dgetrf_(int* dim1, int* dim2, double* a, int* lda, int* ipiv, int* info);\nextern \"C\" void dgetrs_(char *TRANS, int *N, int *NRHS, double *A, int *LDA, int *IPIV, double *B, int *LDB, int *INFO );\n\n\n// RapidJSON\n#include \"rapidjson/document.h\"\n#include \"rapidjson/writer.h\"\n#include \"rapidjson/stringbuffer.h\"\n\nusing namespace std;\nusing namespace rapidjson;\n\nint main(int argc, char *argv[]){\n    cout << \"Hello there, World!\" << endl;\n    std::cout << \"Hello Main2!\" << std::endl;\n\n    // Boost\n    boost::any foo = 42;\n    foo.clear();\n\n    // Lapack\n    char trans = 'N';\n    int dim = 2;    \n    int nrhs = 1;\n    int LDA = dim;\n    int LDB = dim;\n    int info;\n\n    vector<double> a, b;\n\n    a.push_back(1);\n    a.push_back(1);\n    a.push_back(1);\n    a.push_back(-1);\n\n    b.push_back(2);\n    b.push_back(0);\n\n    int ipiv[3];\n\n    dgetrf_(&dim, &dim, &*a.begin(), &LDA, ipiv, &info);\n    dgetrs_(&trans, &dim, &nrhs, & *a.begin(), &LDA, ipiv, & *b.begin(), &LDB, &info);\n\n\n    std::cout << \"solution is:\";    \n    std::cout << \"[\" << b[0] << \", \" << b[1] << \", \" << \"]\" << std::endl;\n    std::cout << \"Info = \" << info << std::endl; \n\n    // RapidJson\n     // 1. Parse a JSON string into DOM.\n    const char* json = \"{\\\"project\\\":\\\"rapidjson\\\",\\\"stars\\\":10}\";\n    Document d;\n    d.Parse(json);\n\n    // 2. Modify it by DOM.\n    Value& s = d[\"stars\"];\n    s.SetInt(s.GetInt() + 1);\n\n    // 3. Stringify the DOM\n    StringBuffer buffer;\n    Writer<StringBuffer> writer(buffer);\n    d.Accept(writer);\n    // Output {\"project\":\"rapidjson\",\"stars\":11}\n    std::cout << buffer.GetString() << std::endl;\n\n\n    // Static Analysis\n    // this should throw a compile time warning as well\n    // as get caught by the cppcheck static analysis ( with make analysis )\n    char tmp[10];\n    tmp[11] = 's';\n    return 0;\n}\n", "meta": {"hexsha": "1b41adcfe87e264b3b38418f486fd75ab39fb511", "size": 1968, "ext": "cc", "lang": "C++", "max_stars_repo_path": "hello/hello.cc", "max_stars_repo_name": "kettlewell/BuildSys", "max_stars_repo_head_hexsha": "2d8867e6c5b836c52dd5663529817297e128228f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hello/hello.cc", "max_issues_repo_name": "kettlewell/BuildSys", "max_issues_repo_head_hexsha": "2d8867e6c5b836c52dd5663529817297e128228f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hello/hello.cc", "max_forks_repo_name": "kettlewell/BuildSys", "max_forks_repo_head_hexsha": "2d8867e6c5b836c52dd5663529817297e128228f", "max_forks_repo_licenses": ["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.4285714286, "max_line_length": 121, "alphanum_fraction": 0.5696138211, "num_tokens": 617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.27172933061375243}}
{"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 <ThermalOperator.hh>\n#include <instantiation.hh>\n\n#include <deal.II/base/index_set.h>\n#include <deal.II/base/types.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/fe/mapping_q1.h>\n#include <deal.II/grid/filtered_iterator.h>\n#include <deal.II/hp/fe_values.h>\n#include <deal.II/matrix_free/fe_evaluation.h>\n\nnamespace adamantine\n{\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nThermalOperator<dim, fe_degree, MemorySpaceType>::ThermalOperator(\n    MPI_Comm const &communicator, BoundaryType boundary_type,\n    std::shared_ptr<MaterialProperty<dim>> material_properties,\n    std::vector<std::shared_ptr<HeatSource<dim>>> heat_sources)\n    : _communicator(communicator), _boundary_type(boundary_type),\n      _material_properties(material_properties), _heat_sources(heat_sources),\n      _inverse_mass_matrix(\n          new dealii::LA::distributed::Vector<double, MemorySpaceType>())\n{\n  _matrix_free_data.tasks_parallel_scheme =\n      dealii::MatrixFree<dim, double>::AdditionalData::partition_color;\n  _matrix_free_data.mapping_update_flags =\n      dealii::update_values | dealii::update_gradients |\n      dealii::update_JxW_values | dealii::update_quadrature_points;\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nvoid ThermalOperator<dim, fe_degree, MemorySpaceType>::reinit(\n    dealii::DoFHandler<dim> const &dof_handler,\n    dealii::AffineConstraints<double> const &affine_constraints,\n    dealii::hp::QCollection<1> const &q_collection)\n{\n  _matrix_free.reinit(dealii::StaticMappingQ1<dim>::mapping, dof_handler,\n                      affine_constraints, q_collection, _matrix_free_data);\n  _affine_constraints = &affine_constraints;\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nvoid ThermalOperator<dim, fe_degree, MemorySpaceType>::\n    compute_inverse_mass_matrix(\n        dealii::DoFHandler<dim> const &dof_handler,\n        dealii::AffineConstraints<double> const &affine_constraints,\n        dealii::hp::FECollection<dim> const &fe_collection)\n{\n  // Compute the inverse of the mass matrix\n  dealii::hp::QCollection<dim> mass_matrix_q_collection;\n  mass_matrix_q_collection.push_back(dealii::QGaussLobatto<dim>(fe_degree + 1));\n  mass_matrix_q_collection.push_back(dealii::QGaussLobatto<dim>(2));\n  auto locally_owned_dofs = dof_handler.locally_owned_dofs();\n  dealii::IndexSet locally_relevant_dofs;\n  dealii::DoFTools::extract_locally_relevant_dofs(dof_handler,\n                                                  locally_relevant_dofs);\n  _inverse_mass_matrix->reinit(locally_owned_dofs, locally_relevant_dofs,\n                               _communicator);\n  dealii::hp::FEValues<dim> hp_fe_values(\n      fe_collection, mass_matrix_q_collection,\n      dealii::update_quadrature_points | dealii::update_values |\n          dealii::update_JxW_values);\n  unsigned int const dofs_per_cell = fe_collection.max_dofs_per_cell();\n  unsigned int const n_q_points =\n      mass_matrix_q_collection.max_n_quadrature_points();\n  std::vector<dealii::types::global_dof_index> local_dof_indices(dofs_per_cell);\n  dealii::Vector<double> cell_mass(dofs_per_cell);\n  for (auto const &cell : dealii::filter_iterators(\n           dof_handler.active_cell_iterators(),\n           dealii::IteratorFilters::LocallyOwnedCell(),\n           dealii::IteratorFilters::ActiveFEIndexEqualTo(0)))\n  {\n    cell_mass = 0.;\n    hp_fe_values.reinit(cell);\n    dealii::FEValues<dim> const &fe_values =\n        hp_fe_values.get_present_fe_values();\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        for (unsigned int j = 0; j < dofs_per_cell; ++j)\n        {\n\n          cell_mass[i] += fe_values.shape_value(j, q) *\n                          fe_values.shape_value(i, q) * fe_values.JxW(q);\n        }\n      }\n    }\n    cell->get_dof_indices(local_dof_indices);\n    affine_constraints.distribute_local_to_global(cell_mass, local_dof_indices,\n                                                  *_inverse_mass_matrix);\n  }\n  _inverse_mass_matrix->compress(dealii::VectorOperation::add);\n\n  unsigned int const local_size = _inverse_mass_matrix->locally_owned_size();\n  for (unsigned int k = 0; k < local_size; ++k)\n  {\n    if (_inverse_mass_matrix->local_element(k) > 1e-15)\n      _inverse_mass_matrix->local_element(k) =\n          1. / _inverse_mass_matrix->local_element(k);\n    else\n      _inverse_mass_matrix->local_element(k) = 0.;\n  }\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nvoid ThermalOperator<dim, fe_degree, MemorySpaceType>::clear()\n{\n  _matrix_free.clear();\n  _inverse_mass_matrix->reinit(0);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nvoid ThermalOperator<dim, fe_degree, MemorySpaceType>::vmult(\n    dealii::LA::distributed::Vector<double, MemorySpaceType> &dst,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> const &src) const\n{\n  dst = 0.;\n  vmult_add(dst, src);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nvoid ThermalOperator<dim, fe_degree, MemorySpaceType>::Tvmult(\n    dealii::LA::distributed::Vector<double, MemorySpaceType> &dst,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> const &src) const\n{\n  dst = 0.;\n  Tvmult_add(dst, src);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nvoid ThermalOperator<dim, fe_degree, MemorySpaceType>::vmult_add(\n    dealii::LA::distributed::Vector<double, MemorySpaceType> &dst,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> const &src) const\n{\n  // Execute the matrix-free matrix-vector multiplication\n  _matrix_free.cell_loop(&ThermalOperator::cell_local_apply, this, dst, src);\n  // We compute the boundary conditions by hand. We would like to use\n  // dealii::MatrixFree::loop() but there are two problems: 1. the function does\n  // not work with FE_Nothing 2. even if it did we could only use it for the\n  // domain boundary, we would still need to deal with the interface with\n  // FE_Nothing ourselves.\n  if (!(_boundary_type & BoundaryType::adiabatic))\n  {\n    unsigned int const dofs_per_cell = _matrix_free.get_dofs_per_cell();\n    dealii::Vector<double> cell_src(dofs_per_cell);\n    dealii::Vector<double> cell_dst(dofs_per_cell);\n    auto &dof_handler = _matrix_free.get_dof_handler();\n    std::vector<dealii::types::global_dof_index> local_dof_indices(\n        dofs_per_cell);\n    dealii::QGauss<dim - 1> face_quadrature(fe_degree + 1);\n    dealii::FEFaceValues<dim> fe_face_values(\n        dof_handler.get_fe(), face_quadrature,\n        dealii::update_values | dealii::update_quadrature_points |\n            dealii::update_JxW_values);\n    unsigned int const n_face_q_points = face_quadrature.size();\n    // Loop over the locally owned cells with an active FE index of zero\n    for (auto const &cell : dealii::filter_iterators(\n             dof_handler.active_cell_iterators(),\n             dealii::IteratorFilters::LocallyOwnedCell(),\n             dealii::IteratorFilters::ActiveFEIndexEqualTo(0)))\n    {\n      cell_dst = 0.;\n      cell->get_dof_indices(local_dof_indices);\n      for (unsigned int i = 0; i < dofs_per_cell; ++i)\n        cell_src[i] = src[local_dof_indices[i]];\n      bool is_on_domain_boundary = false;\n      for (unsigned int f = 0; f < dealii::GeometryInfo<dim>::faces_per_cell;\n           ++f)\n      {\n        // We need to add the boundary conditions on the faces on the boundary\n        // but also on the faces at the interface with FE_Nothing\n        auto const &face = cell->face(f);\n        if ((face->at_boundary()) ||\n            ((!face->at_boundary()) &&\n             (cell->neighbor(f)->active_fe_index() != 0)))\n        {\n          double conv_temperature_infty = 0.;\n          double conv_heat_transfer_coef = 0.;\n          double rad_temperature_infty = 0.;\n          double rad_heat_transfer_coef = 0.;\n          if (_boundary_type & BoundaryType::convective)\n          {\n            conv_temperature_infty = _material_properties->get_cell_value(\n                cell, Property::convection_temperature_infty);\n            conv_heat_transfer_coef = _material_properties->get_cell_value(\n                cell, StateProperty::convection_heat_transfer_coef);\n          }\n          if (_boundary_type & BoundaryType::radiative)\n          {\n            rad_temperature_infty = _material_properties->get_cell_value(\n                cell, Property::radiation_temperature_infty);\n            rad_heat_transfer_coef = _material_properties->get_cell_value(\n                cell, StateProperty::radiation_heat_transfer_coef);\n          }\n\n          fe_face_values.reinit(cell, face);\n          for (unsigned int j = 0; j < dofs_per_cell; ++j)\n          {\n            for (unsigned int i = 0; i < dofs_per_cell; ++i)\n            {\n              for (unsigned int q = 0; q < n_face_q_points; ++q)\n              {\n                // FIXME Need to be aware that we are using face quadrature\n                // points not volumetric quadrature point. Right now we accept\n                // this slight error.\n                double const inv_rho_cp = get_inv_rho_cp(cell, q);\n\n                cell_dst[i] -= inv_rho_cp *\n                               (conv_heat_transfer_coef *\n                                    (cell_src[j] - conv_temperature_infty) +\n                                rad_heat_transfer_coef *\n                                    (cell_src[j] - rad_temperature_infty)) *\n                               fe_face_values.shape_value(i, q) *\n                               fe_face_values.shape_value(j, q) *\n                               fe_face_values.JxW(q);\n              }\n            }\n          }\n          is_on_domain_boundary = true;\n        }\n      }\n\n      if (is_on_domain_boundary)\n      {\n        _affine_constraints->distribute_local_to_global(cell_dst,\n                                                        local_dof_indices, dst);\n      }\n    }\n  }\n\n  // Because cell_loop resolves the constraints, the constrained dofs are not\n  // called they stay at zero. Thus, we need to force the value on the\n  // constrained dofs by hand. The variable scaling is used so that we get the\n  // right order of magnitude.\n  // TODO: for now the value of scaling is set to 1\n  double const scaling = 1.;\n  std::vector<unsigned int> const &constrained_dofs =\n      _matrix_free.get_constrained_dofs();\n  for (auto &dof : constrained_dofs)\n    dst.local_element(dof) += scaling * src.local_element(dof);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nvoid ThermalOperator<dim, fe_degree, MemorySpaceType>::Tvmult_add(\n    dealii::LA::distributed::Vector<double, MemorySpaceType> &dst,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> const &src) const\n{\n  // The system of equation is symmetric so we can use vmult_add\n  vmult_add(dst, src);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nvoid ThermalOperator<dim, fe_degree, MemorySpaceType>::update_state_ratios(\n    unsigned int cell, unsigned int q,\n    dealii::VectorizedArray<double> temperature,\n    std::array<dealii::VectorizedArray<double>,\n               static_cast<unsigned int>(MaterialState::SIZE)> &state_ratios)\n    const\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\n  // Loop over the vectorized arrays\n  for (unsigned int n = 0; n < temperature.size(); ++n)\n  {\n    // Get the material id at this point\n    dealii::types::material_id material_id = _material_id(cell, q)[n];\n\n    // Get the material thermodynamic properties\n    double const solidus =\n        _material_properties->get(material_id, Property::solidus);\n    double const liquidus =\n        _material_properties->get(material_id, Property::liquidus);\n\n    // Update the state ratios\n    state_ratios[powder] = _powder_ratio(cell, q);\n\n    if (temperature[n] < solidus)\n      state_ratios[liquid][n] = 0.;\n    else if (temperature[n] > liquidus)\n      state_ratios[liquid][n] = 1.;\n    else\n    {\n      state_ratios[liquid][n] =\n          (temperature[n] - solidus) / (liquidus - solidus);\n    }\n    // Because the powder can only become liquid, the solid can only\n    // become liquid, and the liquid can only become solid, the ratio of\n    // powder can only decrease.\n    state_ratios[powder][n] =\n        std::min(1. - state_ratios[liquid][n], state_ratios[powder][n]);\n    // Use max to make sure that we don't create matter because of\n    // round-off.\n    state_ratios[solid][n] =\n        std::max(1. - state_ratios[liquid][n] - state_ratios[powder][n], 0.);\n  }\n\n  _liquid_ratio(cell, q) = state_ratios[liquid];\n  _powder_ratio(cell, q) = state_ratios[powder];\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\ndealii::VectorizedArray<double>\nThermalOperator<dim, fe_degree, MemorySpaceType>::get_inv_rho_cp(\n    unsigned int cell, unsigned int q,\n    std::array<dealii::VectorizedArray<double>,\n               static_cast<unsigned int>(MaterialState::SIZE)>\n        state_ratios,\n    dealii::VectorizedArray<double> temperature) const\n{\n  // Here we need the specific heat (including the latent heat contribution)\n  // and the density\n\n  auto material_id = _material_id(cell, q);\n  // First, get the state-independent material properties\n  dealii::VectorizedArray<double> solidus, liquidus, latent_heat;\n  for (unsigned int n = 0; n < solidus.size(); ++n)\n  {\n    solidus[n] = _material_properties->get(material_id[n], Property::solidus);\n    liquidus[n] = _material_properties->get(material_id[n], Property::liquidus);\n    latent_heat[n] =\n        _material_properties->get(material_id[n], Property::latent_heat);\n  }\n\n  // Now compute the state-dependent properties\n  dealii::VectorizedArray<double> density =\n      _material_properties->compute_material_property(\n          StateProperty::density, material_id.data(), state_ratios.data(),\n          temperature);\n\n  dealii::VectorizedArray<double> specific_heat =\n      _material_properties->compute_material_property(\n          StateProperty::specific_heat, material_id.data(), state_ratios.data(),\n          temperature);\n\n  // Add in the latent heat contribution\n  unsigned int constexpr liquid =\n      static_cast<unsigned int>(MaterialState::liquid);\n\n  for (unsigned int n = 0; n < specific_heat.size(); ++n)\n  {\n    if (state_ratios[liquid][n] > 0.0 && (state_ratios[liquid][n] < 1.0))\n    {\n      specific_heat[n] += latent_heat[n] / (liquidus[n] - solidus[n]);\n    }\n  }\n\n  _inv_rho_cp(cell, q) = 1.0 / (density * specific_heat);\n\n  return _inv_rho_cp(cell, q);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nvoid ThermalOperator<dim, fe_degree, MemorySpaceType>::cell_local_apply(\n    dealii::MatrixFree<dim, double> const &data,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> &dst,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> const &src,\n    std::pair<unsigned int, unsigned int> const &cell_range) const\n{\n  // Get the subrange of cells associated with the fe index 0\n  std::pair<unsigned int, unsigned int> cell_subrange =\n      data.create_cell_subrange_hp_by_index(cell_range, 0);\n\n  dealii::FEEvaluation<dim, fe_degree, fe_degree + 1, 1, double> fe_eval(data);\n  dealii::Tensor<1, dim> unit_tensor;\n  for (unsigned int i = 0; i < dim; ++i)\n    unit_tensor[i] = 1.;\n\n  std::array<dealii::VectorizedArray<double>,\n             static_cast<unsigned int>(MaterialState::SIZE)>\n      state_ratios = {{dealii::make_vectorized_array(-1.0),\n                       dealii::make_vectorized_array(-1.0),\n                       dealii::make_vectorized_array(-1.0)}};\n\n  // Loop over the \"cells\". Note that we don't really work on a cell but on a\n  // set of quadrature point.\n  for (unsigned int cell = cell_subrange.first; cell < cell_subrange.second;\n       ++cell)\n  {\n    // Reinit fe_eval on the current cell\n    fe_eval.reinit(cell);\n    // Store in a local vector the local values of src\n    fe_eval.read_dof_values(src);\n    // Evaluate the function and its gradient on the reference cell\n    fe_eval.evaluate(dealii::EvaluationFlags::values |\n                     dealii::EvaluationFlags::gradients);\n    // Apply the Jacobian of the transformation, multiply by the variable\n    // coefficients and the quadrature points\n    for (unsigned int q = 0; q < fe_eval.n_q_points; ++q)\n    {\n      auto temperature = fe_eval.get_value(q);\n\n      // Calculate the local material properties\n      update_state_ratios(cell, q, temperature, state_ratios);\n      auto inv_rho_cp = get_inv_rho_cp(cell, q, state_ratios, temperature);\n      auto mat_id = _material_id(cell, q);\n      auto thermal_conductivity =\n          _material_properties->compute_material_property(\n              StateProperty::thermal_conductivity, mat_id.data(),\n              state_ratios.data(), temperature);\n\n      fe_eval.submit_gradient(\n          -inv_rho_cp * thermal_conductivity * fe_eval.get_gradient(q), q);\n\n      // Compute source term\n      dealii::Point<dim, dealii::VectorizedArray<double>> const &q_point =\n          fe_eval.quadrature_point(q);\n\n      dealii::VectorizedArray<double> quad_pt_source = 0.0;\n      for (unsigned int i = 0;\n           i < _matrix_free.n_active_entries_per_cell_batch(cell); ++i)\n      {\n        dealii::Point<dim> q_point_loc;\n        for (unsigned int d = 0; d < dim; ++d)\n          q_point_loc(d) = q_point(d)[i];\n\n        for (auto &beam : _heat_sources)\n          quad_pt_source[i] +=\n              beam->value(q_point_loc, _time, _current_source_height);\n      }\n      quad_pt_source *= inv_rho_cp;\n\n      fe_eval.submit_value(quad_pt_source, q);\n    }\n    // Sum over the quadrature points.\n    fe_eval.integrate(dealii::EvaluationFlags::values |\n                      dealii::EvaluationFlags::gradients);\n    fe_eval.distribute_local_to_global(dst);\n  }\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nvoid ThermalOperator<dim, fe_degree,\n                     MemorySpaceType>::get_state_from_material_properties()\n{\n  unsigned int const n_cells = _matrix_free.n_cell_batches();\n  dealii::FEEvaluation<dim, fe_degree, fe_degree + 1, 1, double> fe_eval(\n      _matrix_free);\n\n  _liquid_ratio.reinit(n_cells, fe_eval.n_q_points);\n  _powder_ratio.reinit(n_cells, fe_eval.n_q_points);\n  _material_id.reinit(n_cells, fe_eval.n_q_points);\n  _inv_rho_cp.reinit(n_cells, fe_eval.n_q_points);\n\n  for (unsigned int cell = 0; cell < n_cells; ++cell)\n    for (unsigned int q = 0; q < fe_eval.n_q_points; ++q)\n      for (unsigned int i = 0;\n           i < _matrix_free.n_active_entries_per_cell_batch(cell); ++i)\n      {\n        typename dealii::DoFHandler<dim>::cell_iterator cell_it =\n            _matrix_free.get_cell_iterator(cell, i);\n        // Cast to Triangulation<dim>::cell_iterator to access the material_id\n        typename dealii::Triangulation<dim>::active_cell_iterator cell_tria(\n            cell_it);\n\n        _liquid_ratio(cell, q)[i] = _material_properties->get_state_ratio(\n            cell_tria, MaterialState::liquid);\n        _powder_ratio(cell, q)[i] = _material_properties->get_state_ratio(\n            cell_tria, MaterialState::powder);\n        _material_id(cell, q)[i] = cell_tria->material_id();\n      }\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nvoid ThermalOperator<dim, fe_degree,\n                     MemorySpaceType>::set_state_to_material_properties()\n{\n  _material_properties->set_state(_liquid_ratio, _powder_ratio,\n                                  _cell_it_to_mf_cell_map,\n                                  _matrix_free.get_dof_handler());\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nvoid ThermalOperator<dim, fe_degree, MemorySpaceType>::\n    evaluate_material_properties(\n        dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host> const\n            &temperature)\n{\n  if (!(_boundary_type & BoundaryType::adiabatic))\n    _material_properties->update_boundary_material_properties(\n        _matrix_free.get_dof_handler(), temperature);\n\n  // Store the volumetric material properties\n  unsigned int const n_cells = _matrix_free.n_cell_batches();\n  for (unsigned int cell = 0; cell < n_cells; ++cell)\n    for (unsigned int i = 0;\n         i < _matrix_free.n_active_entries_per_cell_batch(cell); ++i)\n    {\n      typename dealii::DoFHandler<dim>::cell_iterator cell_it =\n          _matrix_free.get_cell_iterator(cell, i);\n      _cell_it_to_mf_cell_map[cell_it] = std::make_pair(cell, i);\n    }\n}\n} // namespace adamantine\n\nINSTANTIATE_DIM_FEDEGREE_HOST(TUPLE(ThermalOperator))\n", "meta": {"hexsha": "99e0517cdb7d5f33ebd7a17007a47a26b152d297", "size": 20932, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/ThermalOperator.cc", "max_stars_repo_name": "Rombur/adamantine", "max_stars_repo_head_hexsha": "45dd37397680fad1eaa64dbb311724c4f727a675", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-09-03T02:08:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-03T01:26:41.000Z", "max_issues_repo_path": "source/ThermalOperator.cc", "max_issues_repo_name": "Rombur/adamantine", "max_issues_repo_head_hexsha": "45dd37397680fad1eaa64dbb311724c4f727a675", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 74.0, "max_issues_repo_issues_event_min_datetime": "2016-08-31T18:10:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T01:51:44.000Z", "max_forks_repo_path": "source/ThermalOperator.cc", "max_forks_repo_name": "Rombur/adamantine", "max_forks_repo_head_hexsha": "45dd37397680fad1eaa64dbb311724c4f727a675", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-11-12T15:43:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-19T02:58:56.000Z", "avg_line_length": 41.0431372549, "max_line_length": 80, "alphanum_fraction": 0.6789126696, "num_tokens": 5116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2717150727871119}}
{"text": "#include \"astar.h\"\n#include <queue>\n#include <deque>\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <math.h>\n#include <stdio.h>\n#include \"forward_kinematics.h\"\n#define BASIC 0\n#define NOALPHA 1\n#define WRENCH 2\n#define WRENCH_NOALPHA 3\n#define WRENCH_RATIO 4\n#define ENERGY_LINEAR 5\n#define ENERGY_ANGULAR 6\n#define ENERGY_KINETIC 7\n#define TORQUE_RATE 8\n#define TORQUE_KINETIC 9\nAstar::Astar(){\n\tdist_threshold = 9;\n\tint n_ticks = 100;\n\tnumticks = n_ticks;\n\tn_ticks = numticks;\n    time_step = .01;\n    angle_threshold = .1;\n\tspace = new State**[n_ticks];\n\tobj_mass = 1;\n\tfor(int i = 0; i < n_ticks; i++){\n\t\tspace[i] = new State*[n_ticks];\n\t\tfor(int j = 0; j < n_ticks; j++){\n\t\t\tspace[i][j] = new State[n_ticks];\n\t\t\tfor(int k = 0; k < n_ticks; k++){\n\t\t\t\tspace[i][j][k].visited = false;\n\t\t\t\tspace[i][j][k].heuristic = -1;\n\t\t\t\tspace[i][j][k].value = -1;\n\t\t\t\tspace[i][j][k].id[0] = i;\n\t\t\t\tspace[i][j][k].id[1] = j;\n\t\t\t\tspace[i][j][k].id[2] = k;\n\t\t\t}\n\t\t}\n\t}\n\n\n}\n\nstd::vector<PState*> Astar::run(int* start, double* target,double targett0){\n\t// std::cout << \"Running A*\\n\";\n\t// std::cout << \"Initializing target\\n\";\n    this->target = target;\n    this -> t0 = radian_to_ticks(targett0,numticks);\n    // std::cout << \"Initialize Start\\n\";\n\tcompute_fk(start[0], start[1], start[2]);\n\tState* starts = &space[start[0]][start[1]][start[2]];\n\tstarts->heuristic\n\t\t= heuristic(&space[start[0]][start[1]][start[2]]);\n\tstarts->prev[0] = -1;\n\tstarts->prev[1] = -1;\n\tstarts->prev[2] = -1;\n\n\tstarts->value = starts->heuristic;\n\t// std::cout << \"Initialzing Priority Queue\\n\";\n\tPState* pstart = new PState;\n\tpstart->value = starts->value;\n\tpstart->state[0] = start[0];\n\tpstart->state[1] = start[1];\n\tpstart->state[2] = start[2];\n\n\tfrontier.push(pstart);\n\n\tState* current = starts;\n\tPState* tracker = new PState;\n\t// std::cout << \"Searching For Target\\n\";\n\n\twhile(!frontier.empty() && will_continue(current)){\n\t\t/* Get the next priority */\n\t\tPState* pcur = frontier.top();\n\t\tfrontier.pop();\n\n\t\ttracker->value = pcur->value;\n\t\ttracker->state[0] = pcur->state[0];\n\t\ttracker->state[1] = pcur->state[1];\n\t\ttracker->state[2] = pcur->state[2];\n\t\tcurrent =\n\t\t\t&space[pcur->state[0]][pcur->state[1]][pcur->state[2]];\n\n\t\tif(current->visited == false){\n\t\t\tcurrent->visited = true;\n\t\t\texpand_frontier(pcur->state[0],pcur->state[1],pcur->state[2]);\n\t\t}\n\t\tdelete(pcur);\n\t}\n\n\t// std::cout << \"Search Completed\\n\";\n\tstd::vector<PState*> path;\n\tState* back_tracker = current;;\n\tpath.push_back(tracker);\n\t// std::cout <<\"Compiling Path\\n\";\n\twhile(back_tracker != starts){\n\t\tint i0 = back_tracker->prev[0];\n\t\tint i1 = back_tracker->prev[1];\n\t\tint i2 = back_tracker->prev[2];\n\t\tPState* next = new PState;\n\t\tnext->value = back_tracker->value;\n\t\tnext->state[0] = i0;\n\t\tnext->state[1] = i1;\n\t\tnext->state[2] = i2;\n\t\tback_tracker = &space[i0][i1][i2];\n\t\tpath.push_back(next);\n\t}\n\n\treturn path;\n\n\n}\n\nvoid Astar::expand_frontier(int is, int js, int ks){\n\tfor(int i = -1; i <= 1; i++){\n\t\tfor(int j = -1; j <= 1; j++){\n\t\t\tfor(int k = -1; k <= 1; k++){\n\t\t\t\tif(i == 0 && j == 0 && k == 0){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif(inbounds(is+i, js+j, ks+k)){\n\t\t\t\t\t/* Check if visited */\n\n\t\t\t\t\tif(space[is+i][js+j][ks+k].visited){\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t/* Has the heuristic been calculated */\n\n\t\t\t\t\tif(space[is+i][js+j][ks+k].heuristic < 0){\n\t\t\t\t\t\tcompute_fk(is+i, js+j, ks+k);\n\t\t\t\t\t\tspace[is+i][js+j][ks+k].heuristic\n\t\t\t\t\t\t\t= heuristic(&space[is+i][js+j][ks+k]);\n\t\t\t\t\t}\n\t\t\t\t\tdouble curcost =  (space[is][js][ks].value -\n\t\t\t\t\t\tspace[is][js][ks].heuristic) +\n\t\t\t\t\t\tcost(&space[is][js][ks],\n\t\t\t\t\t\t&space[is+i][js+j][ks+k]);\n\n\n\t\t\t\t    /* Check if new value is less than min value */\n\t\t\t\t\tif(space[is+i][js+j][ks+k].value < 0){\n\t\t\t\t\t\tspace[is+i][js+j][ks+k].value =\n\t\t\t\t\t\t\tspace[is+i][js+j][ks+k].heuristic+curcost;\n\t\t\t\t\t\tspace[is+i][js+j][ks+k].prev[0] = is;\n\t\t                space[is+i][js+j][ks+k].prev[1] = js;\n\t\t                space[is+i][js+j][ks+k].prev[2] = ks;\n\n\t\t\t\t\t\tPState* p = new PState;\n\t\t\t\t\t\tp->state[0] = is+i;\n\t\t\t\t\t\tp->state[1] = js+j;\n\t\t\t\t\t\tp->state[2] = ks+k;\n\t\t\t\t\t\tp->value = space[is+i][js+j][ks+k].value;\n\t\t\t\t\t\tfrontier.push(p);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif(curcost + space[is+i][js+j][ks+k].heuristic\n\t\t\t\t\t\t\t< space[is+i][js+j][ks+k].value){\n\t\t\t\t\t\t\tspace[is+i][js+j][ks+k].value =\n\t\t\t\t\t\t\t\tcurcost+space[is+i][js+j][ks+k].heuristic;\n\t\t\t\t\t\t\tspace[is+i][js+j][ks+k].prev[0] = is;\n\t\t                \tspace[is+i][js+j][ks+k].prev[1] = js;\n\t\t                \tspace[is+i][js+j][ks+k].prev[2] = ks;\n\t\t\t\t\t\t\tPState* p = new PState;\n\t\t\t\t\t\t\tp->state[0] = is+i;\n\t\t\t\t\t\t\tp->state[1] = js+j;\n\t\t\t\t\t\t\tp->state[2] = ks+k;\n\t\t\t\t\t\t\tp->value = space[is+i][js+j][ks+k].value;\n\t\t\t\t\t\t\tfrontier.push(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}\n}\n\ndouble Astar::cost(State* s1, State* s2){\n#if COSTFUNCTION == NOALPHA\n\treturn pow(s1->x - s2->x,2)+pow(s1->z - s2->z,2);\n#elif COSTFUNCTION == WRENCH\n\tdouble dist = pow(s1->x - s2->x,2)+pow(s1->z - s2->z,2)\n\t\t+pow(s1->alpha - s2->alpha,2);\n\tdouble t1 = tick_to_radians(s2->id[0],numticks);\n\tdouble t2 = tick_to_radians(s2->id[1],numticks);\n\tdouble t3 = tick_to_radians(s2->id[2],numticks);\n\tdouble c1 = 150*cos(t1)*obj_mass;\n\tdouble c12 = 150*cos(t1+t2)*obj_mass;\n\tdouble s123 = 116.525*sin(t1+t2+t3)*obj_mass;\n\n\tdouble mag_torque = pow(c1+c12+s123,2)\n\t\t+pow(c12+s123, 2)+pow(s123, 2);\n\treturn dist+mag_torque;\n#elif COSTFUNCTION == WRENCH_NOALPHA\n\tdouble dist = pow(s1->x - s2->x,2)+pow(s1->z - s2->z,2);\n\tdouble t1 = tick_to_radians(s2->id[0],numticks);\n\tdouble t2 = tick_to_radians(s2->id[1],numticks);\n\tdouble t3 = tick_to_radians(s2->id[2],numticks);\n\tdouble c1 = 150*cos(t1)*obj_mass;\n\tdouble c12 = 150*cos(t1+t2)*obj_mass;\n\tdouble s123 = 116.525*sin(t1+t2+t3)*obj_mass;\n\n\tdouble mag_torque = pow(c1+c12+s123,2)\n\t\t+pow(c12+s123, 2)+pow(s123, 2);\n\treturn dist+mag_torque;\n#elif COSTFUNCTION == WRENCH_RATIO\n\tdouble dist = pow(s1->x - s2->x,2)+pow(s1->z - s2->z,2)\n\t\t+pow(s1->alpha - s2->alpha,2);\n\tdouble s2t1 = tick_to_radians(s2->id[0],numticks);\n\tdouble s2t2 = tick_to_radians(s2->id[1],numticks);\n\tdouble s2t3 = tick_to_radians(s2->id[2],numticks);\n\tdouble s2c1 = 150*cos(s2t1)*obj_mass;\n\tdouble s2c12 = 150*cos(s2t1+s2t2)*obj_mass;\n\tdouble s2s123 = 116.525*sin(s2t1+s2t2+s2t3)*obj_mass;\n\n\tdouble s1t1 = tick_to_radians(s1->id[0],numticks);\n\tdouble s1t2 = tick_to_radians(s1->id[1],numticks);\n\tdouble s1t3 = tick_to_radians(s1->id[2],numticks);\n\tdouble s1c1 = 150*cos(s1t1)*obj_mass;\n\tdouble s1c12 = 150*cos(s1t1+s1t2)*obj_mass;\n\tdouble s1s123 = 116.525*sin(s1t1+s1t2+s1t3)*obj_mass;\n\n\tdouble mag_torque2 = pow(s2c1+s2c12+s2s123,2)\n\t\t+pow(s2c12+s2s123, 2)+pow(s2s123, 2)+.0001;\n\n\tdouble mag_torque1 = pow(s1c1+s1c12+s1s123,2)\n\t\t+pow(s1c12+s1s123, 2)+pow(s1s123, 2)+.0001;\n\treturn dist + (mag_torque2/mag_torque1);\n#elif COSTFUNCTION == ENERGY_LINEAR\n\tdouble dist = pow(s1->x - s2->x,2)+pow(s1->z - s2->z,2)\n\t\t+pow(s1->alpha - s2->alpha,2);\n\tdouble s2t1 = tick_to_radians(s2->id[0],numticks);\n\tdouble s2t2 = tick_to_radians(s2->id[1],numticks);\n\tdouble s2t3 = tick_to_radians(s2->id[2],numticks);\n\tdouble s1t1 = tick_to_radians(s1->id[0],numticks);\n\tdouble s1t2 = tick_to_radians(s1->id[1],numticks);\n\tdouble s1t3 = tick_to_radians(s1->id[2],numticks);\n\n\tEigen::Matrix<double,3,5> J = jacobian(0,s1->id[0],s1->id[1],s1->id[2],0,numticks);\n\tEigen::Matrix<double,5,1> thetadot;\n\tthetadot << 0, ((s2t1-s1t1)/time_step), ((s2t2-s1t2)/time_step), ((s2t3-s1t3)/time_step),  0;\n\tEigen::Vector3d vel = J*thetadot;\n        return dist+ obj_mass*vel.squaredNorm();\n#elif COSTFUNCTION == ENERGY_ANGULAR\n    double dist = pow(s1->x - s2->x,2)+pow(s1->z - s2->z,2);\n\n\tdouble alphadist = dist + pow(s1->alpha - s2->alpha,2);\n\tdouble s2t1 = tick_to_radians(s2->id[0],numticks);\n\tdouble s2t2 = tick_to_radians(s2->id[1],numticks);\n\tdouble s2t3 = tick_to_radians(s2->id[2],numticks);\n\tdouble s1t1 = tick_to_radians(s1->id[0],numticks);\n\tdouble s1t2 = tick_to_radians(s1->id[1],numticks);\n\tdouble s1t3 = tick_to_radians(s1->id[2],numticks);\n\n\tdouble angular_vel = ((s2t1-s1t1)+(s2t2-s1t2)+(s2t3-s1t3))/time_step;\n\treturn alphadist + obj_mass*dist*pow(angular_vel,2);\n\n#elif COSTFUNCTION == ENERGY_KINETIC\n\tdouble dist = pow(s1->x - s2->x,2)+pow(s1->z - s2->z,2);\n\n\tdouble alphadist = dist + pow(s1->alpha - s2->alpha,2);\n\tdouble s2t1 = tick_to_radians(s2->id[0],numticks);\n\tdouble s2t2 = tick_to_radians(s2->id[1],numticks);\n\tdouble s2t3 = tick_to_radians(s2->id[2],numticks);\n\tdouble s1t1 = tick_to_radians(s1->id[0],numticks);\n\tdouble s1t2 = tick_to_radians(s1->id[1],numticks);\n\tdouble s1t3 = tick_to_radians(s1->id[2],numticks);\n\n\tdouble angular_vel = ((s2t1-s1t1)+(s2t2-s1t2)+(s2t3-s1t3))/time_step;\n\tEigen::Matrix<double,3,5> J = jacobian(0,s1->id[0],s1->id[1],s1->id[2],0,numticks);\n\tEigen::Matrix<double,5,1> thetadot;\n\tthetadot << 0, ((s2t1-s1t1)/time_step), ((s2t2-s1t2)/time_step), ((s2t3-s1t3)/time_step),  0;\n\tEigen::Vector3d vel = J*thetadot;\n    return alphadist+ obj_mass*vel.squaredNorm()+ obj_mass*dist*pow(angular_vel,2);\n#elif COSTFUNCTION == TORQUE_RATE\n\n\tdouble s2t1 = tick_to_radians(s2->id[0],numticks);\n\tdouble s2t2 = tick_to_radians(s2->id[1],numticks);\n\tdouble s2t3 = tick_to_radians(s2->id[2],numticks);\n\tdouble s2c1 = 150*cos(s2t1)*obj_mass;\n\tdouble s2c12 = 150*cos(s2t1+s2t2)*obj_mass;\n\tdouble s2s123 = 116.525*sin(s2t1+s2t2+s2t3)*obj_mass;\n\n\tdouble s1t1 = tick_to_radians(s1->id[0],numticks);\n\tdouble s1t2 = tick_to_radians(s1->id[1],numticks);\n\tdouble s1t3 = tick_to_radians(s1->id[2],numticks);\n\tdouble s1c1 = 150*cos(s1t1)*obj_mass;\n\tdouble s1c12 = 150*cos(s1t1+s1t2)*obj_mass;\n\tdouble s1s123 = 116.525*sin(s1t1+s1t2+s1t3)*obj_mass;\n\n\tdouble mag_torque2 = pow(s2c1+s2c12+s2s123,2)\n\t\t+pow(s2c12+s2s123, 2)+pow(s2s123, 2)+.0001;\n\n\tdouble mag_torque1 = pow(s1c1+s1c12+s1s123,2)\n\t\t+pow(s1c12+s1s123, 2)+pow(s1s123, 2)+.0001;\n\treturn abs(mag_torque2-mag_torque1)/time_step;\n#elif COSTFUNCTION == TORQUE_KINETIC\n\t//Torque Rate\n\tdouble s2t1 = tick_to_radians(s2->id[0],numticks);\n\tdouble s2t2 = tick_to_radians(s2->id[1],numticks);\n\tdouble s2t3 = tick_to_radians(s2->id[2],numticks);\n\tdouble s2c1 = 150*cos(s2t1)*obj_mass;\n\tdouble s2c12 = 150*cos(s2t1+s2t2)*obj_mass;\n\tdouble s2s123 = 116.525*sin(s2t1+s2t2+s2t3)*obj_mass;\n\n\tdouble s1t1 = tick_to_radians(s1->id[0],numticks);\n\tdouble s1t2 = tick_to_radians(s1->id[1],numticks);\n\tdouble s1t3 = tick_to_radians(s1->id[2],numticks);\n\tdouble s1c1 = 150*cos(s1t1)*obj_mass;\n\tdouble s1c12 = 150*cos(s1t1+s1t2)*obj_mass;\n\tdouble s1s123 = 116.525*sin(s1t1+s1t2+s1t3)*obj_mass;\n\n\tdouble mag_torque2 = pow(s2c1+s2c12+s2s123,2)\n\t\t+pow(s2c12+s2s123, 2)+pow(s2s123, 2)+.0001;\n\n\tdouble mag_torque1 = pow(s1c1+s1c12+s1s123,2)\n\t\t+pow(s1c12+s1s123, 2)+pow(s1s123, 2)+.0001;\n\n\t//Kinetic\n\n\tEigen::Matrix<double,3,5> J = jacobian(0,s1->id[0],s1->id[1],s1->id[2],0,numticks);\n\tEigen::Matrix<double,5,1> thetadot;\n\tthetadot << 0, ((s2t1-s1t1)/time_step), ((s2t2-s1t2)/time_step), ((s2t3-s1t3)/time_step),  0;\n\tEigen::Vector3d vel = J*thetadot;\n\treturn abs(mag_torque2-mag_torque1)/time_step+obj_mass*vel.squaredNorm();\n\n#else\n\treturn pow(s1->x - s2->x,2)+pow(s1->z - s2->z,2)\n\t\t+pow(s1->alpha - s2->alpha,2);\n\n#endif\n}\n\ndouble Astar::heuristic(State* s){\n#if COSTFUNCTION == NOALPHA || COSTFUNCTION == WRENCH_NOALPHA\n\treturn pow(s->x - target[0],2)+pow(s->z - target[1],2);\n#elif COSTFUNCTION == TORQUE_RATE || COSTFUNCTION == TORQUE_KINETIC\n\treturn 0;\n#else\n\treturn pow(s->x - target[0],2)+pow(s->z - target[1],2)\n\t\t+pow(s->alpha - target[2],2);\n#endif\n}\n\nvoid Astar::compute_fk(int i, int j, int k){\n\tdouble x;\n\tdouble z;\n\tdouble alpha;\n\tfk(&x, &z, &alpha,t0, i, j, k,numticks);\n\tspace[i][j][k].x  = x;\n\tspace[i][j][k].z = z;\n\tspace[i][j][k].alpha = alpha;\n}\n\nbool Astar::inbounds(int i, int j, int k){\n\tif(i<numticks && j < numticks && k < numticks){\n\t\tif(i >= 0 && j >= 0 && k >= 0)\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool Astar::will_continue(State* current){\n#if COSTFUNCTION == NOALPHA || COSTFUNCTION == WRENCH_NOALPHA\n\tdouble dist = pow(current->x-target[0], 2) + pow(current->z-target[1], 2);\n\treturn dist > dist_threshold;\n#elif COSTFUNCTION == TORQUE_RATE || COSTFUNCTION == TORQUE_KINETIC\n\tdouble dist = pow(current->x-target[0], 2) + pow(current->z-target[1], 2);\n\treturn dist > dist_threshold;\n#else\n\tdouble dist = pow(current->x-target[0], 2) + pow(current->z-target[1], 2);\n\tdouble angle = current->alpha;\n\treturn !(dist < dist_threshold && (fabs(angle-target[2]) < angle_threshold\n\t\t|| (fabs(angle+2*M_PI-target[2]) < angle_threshold)\n\t\t|| (fabs(angle-2*M_PI-target[2]) < angle_threshold )));\n#endif\n\n}\n", "meta": {"hexsha": "94b257422c1c992362b96261f1e6c4a5283abfa0", "size": 12469, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "armplanning_test/astar_optimized/astar.cpp", "max_stars_repo_name": "Boberito25/ButlerBot", "max_stars_repo_head_hexsha": "959f961bbc8c43be0ccb533dd2e2af5c55b0cc2a", "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": "armplanning_test/astar_optimized/astar.cpp", "max_issues_repo_name": "Boberito25/ButlerBot", "max_issues_repo_head_hexsha": "959f961bbc8c43be0ccb533dd2e2af5c55b0cc2a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-06-08T19:55:40.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-08T19:55:40.000Z", "max_forks_repo_path": "armplanning_test/astar_optimized/astar.cpp", "max_forks_repo_name": "Boberito25/ButlerBot", "max_forks_repo_head_hexsha": "959f961bbc8c43be0ccb533dd2e2af5c55b0cc2a", "max_forks_repo_licenses": ["BSD-3-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.7270341207, "max_line_length": 94, "alphanum_fraction": 0.6435961184, "num_tokens": 4781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2716677081263402}}
{"text": "// Copyright 2013-2020 Lawrence Livermore National Security, LLC and other\n// HavoqGT Project Developers. See the top-level LICENSE file for details.\n//\n// SPDX-License-Identifier: MIT\n\n#ifndef HAVOQGT_MPI_GEN_PREFERENTIAL_ATTACHMENT_EDGE_LIST_HPP_INCLUDED\n#define HAVOQGT_MPI_GEN_PREFERENTIAL_ATTACHMENT_EDGE_LIST_HPP_INCLUDED\n\n#include <havoqgt/mpi.hpp>\n#include <havoqgt/detail/hash.hpp>\n#include <havoqgt/detail/preferential_attachment.hpp>\n#include <boost/random.hpp>\n#include <algorithm>\n\nnamespace havoqgt {\n\n\ntemplate <typename EdgeType>\nvoid gen_preferential_attachment_edge_list(std::vector<EdgeType>& local_edges,\n                                           uint64_t in_base_seed,\n                                           uint64_t in_node_scale,\n                                           uint64_t in_edge_scale,\n                                           double in_beta,\n                                           double in_prob_rewire,\n                                           MPI_Comm in_comm)\n{\n  namespace ad = havoqgt::detail;\n  int mpi_rank, mpi_size;\n  CHK_MPI( MPI_Comm_rank(in_comm, &mpi_rank) );\n  CHK_MPI( MPI_Comm_size(in_comm, &mpi_size) );\n\n  //\n  // Calc global number of nodes and edges\n  uint64_t global_num_nodes = uint64_t(1) << in_node_scale;\n  uint64_t global_num_edges = uint64_t(1) << in_edge_scale;\n  uint64_t k = global_num_edges / global_num_nodes;\n  uint64_t edges_per_rank = global_num_edges / mpi_size;\n\n  ad::preferential_attachment_helper<uint64_t> pa(k, global_num_edges, in_beta,\n                                             in_base_seed*mpi_rank + mpi_rank);\n\n  //\n  // Generate inital pa edges.  Includes unresolved links\n  double init_time_start = MPI_Wtime();\n  local_edges.resize(edges_per_rank);\n  for(uint64_t i=0; i<edges_per_rank; ++i) {\n    uint64_t edge_index = uint64_t(mpi_rank) + i*uint64_t(mpi_size);\n    local_edges[i] = pa.gen_edge(edge_index);\n  }\n  double init_time_end = MPI_Wtime();\n  if(mpi_rank == 0) {\n    std::cout << \"Initial rng for edges took \" << init_time_end - init_time_start\n              << \" seconds. \" << std::endl;\n  }\n\n  //\n  // We loop until all edges are resolved\n  uint64_t iteration_count(1), count_missing(0), count_total_mising(0);\n  do {\n    //\n    // Count number still missing\n    for(uint64_t i=0; i<edges_per_rank; ++i) {\n      if(pa.is_pointer(local_edges[i].second)) {\n        ++count_total_mising;\n      }\n    }\n\n    count_missing = 0;\n    double time_start = MPI_Wtime();\n    //\n    // Generate vectors to exchange\n    std::vector<std::vector<uint64_t> > tmp_send_to_rank(mpi_size);\n    std::vector<std::vector<uint64_t> > tmp_mark_send_to_rank(mpi_size);\n    uint64_t count_to_send(0);\n    for(uint64_t i=0; i<local_edges.size(); ++i) {\n      if(pa.is_pointer(local_edges[i].second)) {\n        int owner = pa.value_of_pointer(local_edges[i].second) % mpi_size;\n        tmp_mark_send_to_rank[owner].push_back(i);\n        tmp_send_to_rank[owner].push_back(pa.value_of_pointer(local_edges[i].second));\n        ++count_to_send;\n      }\n    }\n    //\n    // Combine send/recv vectors\n    std::vector<uint64_t> to_send(count_to_send); to_send.reserve(1);\n    std::vector<uint64_t> mark_to_send(count_to_send);\n    std::vector<int>      sendcnts(mpi_size,0); sendcnts.reserve(1);\n    to_send.clear(); mark_to_send.clear();\n    for(int i = 0; i < mpi_size; ++i) {\n      for(size_t j = 0; j < tmp_send_to_rank[i].size(); ++j) {\n        to_send.push_back(tmp_send_to_rank[i][j]);\n        mark_to_send.push_back(tmp_mark_send_to_rank[i][j]);\n      }\n      sendcnts[i] = tmp_send_to_rank[i].size();\n    }\n    //\n    // Release memory from temp vectors\n    {\n      std::vector<std::vector<uint64_t> > empty;\n      tmp_send_to_rank.swap(empty);\n    }\n    {\n      std::vector<std::vector<uint64_t> > empty;\n      tmp_mark_send_to_rank.swap(empty);\n    }\n    //\n    // Exchange vectors\n    std::vector<uint64_t> to_recv; // not sized\n    std::vector<int>      recvcnts; // not sized\n    mpi_all_to_all(to_send, sendcnts, to_recv, recvcnts, MPI_COMM_WORLD);\n    //\n    // Look up pointers, pointer jump!\n    for(size_t i=0; i<to_recv.size(); ++i) {\n      uint64_t local_index = to_recv[i]/mpi_size;\n      to_recv[i] = local_edges[local_index].second;\n    }\n    //\n    // Return exchange vectors\n    mpi_all_to_all(to_recv, recvcnts, to_send, sendcnts, MPI_COMM_WORLD);\n    //\n    // Return new pointers to marked location\n    for(size_t i=0; i<to_send.size(); ++i) {\n        local_edges[ mark_to_send[i] ].second = to_send[i];;\n    }\n    //\n    // Count number still missing\n    for(uint64_t i=0; i<edges_per_rank; ++i) {\n      if(pa.is_pointer(local_edges[i].second)) {\n        ++count_missing;\n      }\n    }\n    count_missing = mpi_all_reduce(count_missing, std::plus<uint64_t>(), MPI_COMM_WORLD);\n\n    //\n    // Iteration ouput\n    double time_end = MPI_Wtime();\n    if(mpi_rank == 0) {\n      std::cout << \"Iteration \" << iteration_count << \" took \"\n                << time_end - time_start << \" seconds.   \"\n                << count_missing << \" still missing. \" << std::endl;\n    }\n    ++iteration_count;\n  } while(count_missing > 0);\n  //\n  // Output total nuumber of global exchanges\n  count_total_mising = mpi_all_reduce(count_total_mising, std::plus<uint64_t>(), MPI_COMM_WORLD);\n  if(mpi_rank == 0) {\n    std::cout << \"Total missing (how much data globally exchanged) = \" << count_total_mising << std::endl;\n  }\n\n\n  //\n  // Randomly rewire\n  if(in_prob_rewire > double(0)) {\n    boost::mt19937 rng(in_base_seed + uint64_t(mpi_rank) * 3ULL);\n    boost::random::uniform_int_distribution<> rand_node(0,global_num_nodes-1);\n    boost::random::uniform_01<> rand_real;\n    for(size_t i=0; i<local_edges.size(); ++i) {\n      if(rand_real(rng) < in_prob_rewire) {\n        EdgeType rand_edge(rand_node(rng), rand_node(rng));\n        local_edges[i] = rand_edge;\n      }\n    }\n  }\n\n  //\n  // Scramble edges\n  for(size_t i=0; i<local_edges.size(); ++i) {\n    //TODO:  This needs a mod because we never exactly make the correct\n    //number of vertices.   We need a better solution!\n    local_edges[i].first  %= global_num_nodes;\n    local_edges[i].second %= global_num_nodes;\n    local_edges[i].first  = ad::hash_nbits(local_edges[i].first,  in_node_scale);\n    local_edges[i].second = ad::hash_nbits(local_edges[i].second, in_node_scale);\n  }\n\n  // //\n  // // Symmetrizing b/c PA is always undirected.\n  // uint64_t old_size = local_edges.size();\n  // local_edges.reserve(old_size * 2);\n  // for(uint64_t i=0; i<old_size; ++i) {\n  //   EdgeType edge;\n  //   edge.first = local_edges[i].second;\n  //   edge.second = local_edges[i].first;\n  //   local_edges.push_back( edge );\n  // }\n\n  // //\n  // // Shuffle edges because we need to mix the hubs in for future partitioning\n  // std::random_shuffle(local_edges.begin(), local_edges.end());\n}\n\n} //end namespace havoqgt\n\n\n#endif //end HAVOQGT_MPI_GEN_PREFERENTIAL_ATTACHMENT_EDGE_LIST_HPP_INCLUDED\n\n", "meta": {"hexsha": "422a0374bf6bcc61ef2679565ca36ba3b1dc9806", "size": 6929, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/havoqgt/gen_preferential_attachment_edge_list.hpp", "max_stars_repo_name": "niklas-uhl/havoqgt", "max_stars_repo_head_hexsha": "24df89686c8ca52b9f18ac86ba4e94689da2242e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2017-05-15T08:33:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T17:28:03.000Z", "max_issues_repo_path": "include/havoqgt/gen_preferential_attachment_edge_list.hpp", "max_issues_repo_name": "niklas-uhl/havoqgt", "max_issues_repo_head_hexsha": "24df89686c8ca52b9f18ac86ba4e94689da2242e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-09-25T15:32:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-16T15:39:35.000Z", "max_forks_repo_path": "include/havoqgt/gen_preferential_attachment_edge_list.hpp", "max_forks_repo_name": "niklas-uhl/havoqgt", "max_forks_repo_head_hexsha": "24df89686c8ca52b9f18ac86ba4e94689da2242e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2017-02-09T15:30:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T10:19:26.000Z", "avg_line_length": 34.9949494949, "max_line_length": 106, "alphanum_fraction": 0.6429499206, "num_tokens": 1841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.27166770189359}}
{"text": "#include \"file_io.hpp\"\n#include <boost/filesystem.hpp>\n#include <cmath>\n\nsize_t get_cnt_lines(const std::string &name_file)\n{\n    throw (std::runtime_error(\"not yet implemented\"));\n    return 0;\n}\n\nsize_t read_int(const std::string &name_file)\n{\n    std::ifstream is(name_file, std::ifstream::in);\n    size_t res; \n    is >> res;\n    return res;\n}\n\nsize_t get_filesize(const std::string & name_file)\n{\n    std::ifstream in(name_file, std::ifstream::ate | std::ifstream::binary);\n    if (!in.is_open())\n    {\n        std::string message=\"get_filesize() can not open file \";\n        throw std::runtime_error (message+name_file);\n    }\n    return in.tellg(); \n}\n\ndouble get_PMI(Index cnt,Index id1,Index id2,Vocabulary const & vocab)\n{\n    return log2((static_cast<double>(cnt)*vocab.cnt_words_processed)/(vocab.freq_per_id[id1]*vocab.freq_per_id[id2]));    \n}\n\nvoid dump_crs(std::string path_out,std::vector<Accumulator> const & counters,Vocabulary const & vocab, bool binary)\n{\n    std::ofstream file;\n    auto mode=binary? std::ios::out | std::ios::binary : std::ios::out;\n    std::string str_path = (boost::filesystem::path(path_out) / boost::filesystem::path(binary?\"bigrams.data.bin\":\"bigrams.data\")).string();\n    file.open (str_path,mode);\n    if(!file) throw  std::runtime_error(\"can not open output file \" + str_path + \" , check the path\");\n    for (size_t first=0;first<counters.size();first++)\n        for (const auto& second : counters[first]) \n        {\n            float v=get_PMI(second.second,first,second.first,vocab);\n            if (binary)\n                file.write( reinterpret_cast<const char*>(&v),sizeof(v));\n            else\n                file<<v<<\"\\n\";\n        }\n    file.close();\n\n    str_path = (boost::filesystem::path(path_out) / boost::filesystem::path(binary?\"bigrams.col_ind.bin\":\"bigrams.col_ind\")).string();\n    file.open (str_path,mode);\n    for (size_t first=0;first<counters.size();first++)\n        for (const auto& second : counters[first]) \n        {\n            size_t v=second.first;\n            if (binary)\n               file.write( reinterpret_cast<const char*>(&v),sizeof(v));\n            else\n                file<<v<<\"\\n\";\n        }\n    file.close();\n\n    str_path = (boost::filesystem::path(path_out) / boost::filesystem::path(binary?\"bigrams.row_ptr.bin\":\"bigrams.row_ptr\")).string();\n    file.open (str_path,mode);\n    Index row_ptr=0;\n    Index id_last=0;\n    for (size_t first=0;first<counters.size();first++)\n    {\n        if (first==0) \n            {\n                if (binary)\n                    file.write( reinterpret_cast<const char*>(&row_ptr),sizeof(row_ptr));\n                else\n                    file<<row_ptr<<\"\\n\";\n            }\n        else\n            for (size_t k=id_last;k<first;k++)\n                if (binary)\n                    file.write( reinterpret_cast<const char*>(&row_ptr),sizeof(row_ptr));\n                else\n                    file<<row_ptr<<\"\\n\";\n            id_last=first;\n            row_ptr+=counters[first].size();\n        }\n        for (size_t k=id_last;k<vocab.cnt_words;k++)\n            if (binary)\n                file.write( reinterpret_cast<const char*>(&row_ptr),sizeof(row_ptr));\n            else\n                file<<row_ptr<<\"\\n\";\n       file.close();\n   }\n\nvoid write_cooccurrence_text(std::string name_file,std::vector<Accumulator> const & counters,Vocabulary const & vocab)\n{\nstd::ofstream file;\nfile.open (name_file);\nif(!file) throw  std::runtime_error(\"can not open output file \"+name_file+\" , check the path\");\nfor (size_t first=0;first<counters.size();first++)\n{\n    for (const auto& second : counters[first]) \n    {\n      //if (t.second>0)\n       // file<<first.first<<\"\\t\"<<second.first<<\"\\t\"<<second.second<<\"\\n\";\n        double v=log2((static_cast<double>(second.second)*vocab.cnt_words_processed)/(vocab.freq_per_id[first]*vocab.freq_per_id[second.first]));\n        //file<<first<<\"\\t\"<<second.first<<\"\\t\"<<v<<\"\\n\";\n        file<<vocab.lst_id2word[first]<<\"\\t\"<<vocab.lst_id2word[second.first]<<\"\\t\"<<second.second<<\"\\t\"<<v<<\"\\n\"; \n    }\n}\n\nfile.close();\n}", "meta": {"hexsha": "63b5c04d44d8c571fc7d0ea06408309713e50ff5", "size": 4078, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/basic_utils/file_io.cpp", "max_stars_repo_name": "undertherain/nlp_cooc", "max_stars_repo_head_hexsha": "e316740c469e4ade6ba064e6756057fee10466ed", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-20T03:04:47.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-20T03:04:47.000Z", "max_issues_repo_path": "src/basic_utils/file_io.cpp", "max_issues_repo_name": "undertherain/nlp_cooc", "max_issues_repo_head_hexsha": "e316740c469e4ade6ba064e6756057fee10466ed", "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/basic_utils/file_io.cpp", "max_forks_repo_name": "undertherain/nlp_cooc", "max_forks_repo_head_hexsha": "e316740c469e4ade6ba064e6756057fee10466ed", "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.7719298246, "max_line_length": 145, "alphanum_fraction": 0.5966159882, "num_tokens": 1009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2715969707161612}}
{"text": "///////////////////////////////////////////////////////////////////////////\n//\n// Copyright (c) 1998-2011, Industrial Light & Magic, a division of Lucas\n// Digital Ltd. LLC\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 are\n// 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 disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// *       Neither the name of Industrial Light & Magic nor the names of\n// its 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 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//\n///////////////////////////////////////////////////////////////////////////\n\n#include \"PyIlmBaseConfigInternal.h\"\n\n#include \"PyImathRandom.h\"\n#include \"PyImathDecorators.h\"\n#include <Python.h>\n#include <boost/python.hpp>\n#include <boost/format.hpp>\n#include <boost/python/make_constructor.hpp>\n#include \"PyImath.h\"\n#include \"PyImathMathExc.h\"\n#include \"PyImathFixedArray.h\"\n\n\nnamespace PyImath{\nusing namespace boost::python;\n\ntemplate <class Rand, class T>\nstatic T\nnextf2 (Rand &rand, T min, T max)\n{\n    MATH_EXC_ON;\n    return rand.nextf(min, max);\n}\n\ntemplate <class Rand>\nstatic float\nnextGauss (Rand &rand)\n{\n    MATH_EXC_ON;\n    return gaussRand(rand);\n}\n\ntemplate <class T, class Rand>\nstatic IMATH_NAMESPACE::Vec3<T> nextGaussSphere(Rand &rand, const IMATH_NAMESPACE::Vec3<T> &v)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::gaussSphereRand<IMATH_NAMESPACE::Vec3<T>,Rand>(rand);\n}\ntemplate <class T, class Rand>\nstatic IMATH_NAMESPACE::Vec2<T> nextGaussSphere(Rand &rand, const IMATH_NAMESPACE::Vec2<T> &v)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::gaussSphereRand<IMATH_NAMESPACE::Vec2<T>,Rand>(rand);\n}\n\ntemplate <class T, class Rand>\nstatic IMATH_NAMESPACE::Vec3<T> nextHollowSphere(Rand &rand, const IMATH_NAMESPACE::Vec3<T> &v)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::hollowSphereRand<IMATH_NAMESPACE::Vec3<T>,Rand>(rand);\n}\n\ntemplate <class T, class Rand>\nstatic IMATH_NAMESPACE::Vec2<T> nextHollowSphere(Rand &rand, const IMATH_NAMESPACE::Vec2<T> &v)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::hollowSphereRand<IMATH_NAMESPACE::Vec2<T>,Rand>(rand);\n}\n\ntemplate <class T, class Rand>\nstatic IMATH_NAMESPACE::Vec3<T> nextSolidSphere(Rand &rand, const IMATH_NAMESPACE::Vec3<T> &v)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::solidSphereRand<IMATH_NAMESPACE::Vec3<T>,Rand>(rand);\n}\n\ntemplate <class T, class Rand>\nstatic IMATH_NAMESPACE::Vec2<T> nextSolidSphere(Rand &rand, const IMATH_NAMESPACE::Vec2<T> &v)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::solidSphereRand<IMATH_NAMESPACE::Vec2<T>,Rand>(rand);\n}\n\ntemplate <class Rand>\nstatic Rand *Rand_constructor1(unsigned long int seed)\n{\n    return new Rand(seed);\n}\n\ntemplate <class Rand>\nstatic Rand *Rand_constructor2(Rand rand)\n{\n    Rand *r = new Rand();\n    *r = rand;\n    \n    return r;\n}\n\ntemplate <class T, class Rand>\nstatic PyImath::FixedArray<IMATH_NAMESPACE::Vec3<T> >\nhollowSphereRand(Rand &rand, int num)\n{\n    MATH_EXC_ON;\n    PyImath::FixedArray<IMATH_NAMESPACE::Vec3<T> >  retval(num);\n    for (int i=0; i<num; ++i) {\n        retval[i] = IMATH_NAMESPACE::hollowSphereRand<IMATH_NAMESPACE::Vec3<T>,Rand>(rand);\n    }\n    return retval;\n}\n\ntemplate <class T, class Rand>\nstatic PyImath::FixedArray<IMATH_NAMESPACE::Vec3<T> >\nsolidSphereRand(Rand &rand, int num)\n{\n    MATH_EXC_ON;\n    PyImath::FixedArray<IMATH_NAMESPACE::Vec3<T> >  retval(num);\n    for (int i=0; i<num; ++i) {\n        retval[i] = IMATH_NAMESPACE::solidSphereRand<IMATH_NAMESPACE::Vec3<T>,Rand>(rand);\n    }\n    return retval;\n}\n\nPYIMATH_EXPORT\nclass_<IMATH_NAMESPACE::Rand32>\nregister_Rand32()\n{\n    float (IMATH_NAMESPACE::Rand32::*nextf1)(void) = &IMATH_NAMESPACE::Rand32::nextf;\n    \n    IMATH_NAMESPACE::Vec3<float> (*nextGaussSphere1)(IMATH_NAMESPACE::Rand32 &, const IMATH_NAMESPACE::Vec3<float> &v) = &nextGaussSphere<float,IMATH_NAMESPACE::Rand32>;\n    IMATH_NAMESPACE::Vec3<double> (*nextGaussSphere2)(IMATH_NAMESPACE::Rand32 &, const IMATH_NAMESPACE::Vec3<double> &v) = &nextGaussSphere<double,IMATH_NAMESPACE::Rand32>;\n    IMATH_NAMESPACE::Vec2<float> (*nextGaussSphere3)(IMATH_NAMESPACE::Rand32 &, const IMATH_NAMESPACE::Vec2<float> &v) = &nextGaussSphere<float,IMATH_NAMESPACE::Rand32>;\n    IMATH_NAMESPACE::Vec2<double> (*nextGaussSphere4)(IMATH_NAMESPACE::Rand32 &, const IMATH_NAMESPACE::Vec2<double> &v) = &nextGaussSphere<double,IMATH_NAMESPACE::Rand32>;\n    \n    IMATH_NAMESPACE::Vec3<float> (*nextHollowSphere1)(IMATH_NAMESPACE::Rand32 &, const IMATH_NAMESPACE::Vec3<float> &v) = &nextHollowSphere<float,IMATH_NAMESPACE::Rand32>;\n    IMATH_NAMESPACE::Vec3<double> (*nextHollowSphere2)(IMATH_NAMESPACE::Rand32 &, const IMATH_NAMESPACE::Vec3<double> &v) = &nextHollowSphere<double,IMATH_NAMESPACE::Rand32>;\n    IMATH_NAMESPACE::Vec2<float> (*nextHollowSphere3)(IMATH_NAMESPACE::Rand32 &, const IMATH_NAMESPACE::Vec2<float> &v) = &nextHollowSphere<float,IMATH_NAMESPACE::Rand32>;\n    IMATH_NAMESPACE::Vec2<double> (*nextHollowSphere4)(IMATH_NAMESPACE::Rand32 &, const IMATH_NAMESPACE::Vec2<double> &v) = &nextHollowSphere<double,IMATH_NAMESPACE::Rand32>;\n\n    IMATH_NAMESPACE::Vec3<float> (*nextSolidSphere1)(IMATH_NAMESPACE::Rand32 &, const IMATH_NAMESPACE::Vec3<float> &v) = &nextSolidSphere<float,IMATH_NAMESPACE::Rand32>;\n    IMATH_NAMESPACE::Vec3<double> (*nextSolidSphere2)(IMATH_NAMESPACE::Rand32 &, const IMATH_NAMESPACE::Vec3<double> &v) = &nextSolidSphere<double,IMATH_NAMESPACE::Rand32>;\n    IMATH_NAMESPACE::Vec2<float> (*nextSolidSphere3)(IMATH_NAMESPACE::Rand32 &, const IMATH_NAMESPACE::Vec2<float> &v) = &nextSolidSphere<float,IMATH_NAMESPACE::Rand32>;\n    IMATH_NAMESPACE::Vec2<double> (*nextSolidSphere4)(IMATH_NAMESPACE::Rand32 &, const IMATH_NAMESPACE::Vec2<double> &v) = &nextSolidSphere<double,IMATH_NAMESPACE::Rand32>;\n    \n    class_< IMATH_NAMESPACE::Rand32 > rand32_class(\"Rand32\");\n    rand32_class\n        .def(init<>(\"default construction\"))\n        .def(\"__init__\", make_constructor(Rand_constructor1<IMATH_NAMESPACE::Rand32>))\n        .def(\"__init__\", make_constructor(Rand_constructor2<IMATH_NAMESPACE::Rand32>))\n        .def(\"init\", &IMATH_NAMESPACE::Rand32::init,\n             \"r.init(i) -- initialize with integer \"\n\t\t\t \"seed i\")\n             \n        .def(\"nexti\", &IMATH_NAMESPACE::Rand32::nexti,\n        \t \"r.nexti() -- return the next integer \"\n\t\t\t \"value in the uniformly-distributed \"\n\t\t\t \"sequence\")\n        .def(\"nextf\", nextf1,\n        \t \"r.nextf() -- return the next floating-point \"\n\t\t\t \"value in the uniformly-distributed \"\n\t\t\t \"sequence\\n\"\n             \n        \t \"r.nextf(float, float) -- return the next floating-point \"\n\t\t\t \"value in the uniformly-distributed \"\n\t\t\t \"sequence\")             \n        .def(\"nextf\", &nextf2 <IMATH_NAMESPACE::Rand32, float>)\n             \n        .def(\"nextb\", &IMATH_NAMESPACE::Rand32::nextb,\n\t \t     \"r.nextb() -- return the next boolean \"\n\t\t\t \"value in the uniformly-distributed \"\n\t\t\t \"sequence\")\n\n        .def(\"nextGauss\", &nextGauss<IMATH_NAMESPACE::Rand32>,\n        \t \"r.nextGauss() -- returns the next \"\n\t\t\t \"floating-point value in the normally \"\n\t\t\t \"(Gaussian) distributed sequence\")\n             \n        .def(\"nextGaussSphere\", nextGaussSphere1, \n\t \t\t \"r.nextGaussSphere(v) -- returns the next \"\n\t\t\t \"point whose distance from the origin \"\n\t\t\t \"has a normal (Gaussian) distribution with \"\n\t\t\t \"mean 0 and variance 1.  The vector \"\n\t\t\t \"argument, v, specifies the dimension \"\n\t\t\t \"and number type.\")             \n        .def(\"nextGaussSphere\", nextGaussSphere2)             \n        .def(\"nextGaussSphere\", nextGaussSphere3)             \n        .def(\"nextGaussSphere\", nextGaussSphere4)\n        \n        .def(\"nextHollowSphere\", nextHollowSphere1,\n        \t \"r.nextHollowSphere(v) -- return the next \"\n\t \t\t \"point uniformly distributed on the surface \"\n\t \t\t \"of a sphere of radius 1 centered at the \"\n\t \t\t \"origin.  The vector argument, v, specifies \"\n\t\t\t \"the dimension and number type.\")             \n        .def(\"nextHollowSphere\", nextHollowSphere2)             \n        .def(\"nextHollowSphere\", nextHollowSphere3)             \n        .def(\"nextHollowSphere\", nextHollowSphere4)\n\n        .def(\"nextSolidSphere\", nextSolidSphere1,\n        \t \"r.nextSolidSphere(v) -- return the next \"\n\t\t\t \"point uniformly distributed in a sphere \"\n\t\t\t \"of radius 1 centered at the origin.  The \"\n\t\t\t \"vector argument, v, specifies the \"\n\t\t\t \"dimension and number type.\")             \n        .def(\"nextSolidSphere\", nextSolidSphere2)             \n        .def(\"nextSolidSphere\", nextSolidSphere3)             \n        .def(\"nextSolidSphere\", nextSolidSphere4)    \n        ;\n\n    def(\"hollowSphereRand\",&hollowSphereRand<float,IMATH_NAMESPACE::Rand32>,\"hollowSphereRand(randObj,num) return XYZ vectors uniformly \"\n        \"distributed across the surface of a sphere generated from the given Rand32 object\",\n        args(\"randObj\",\"num\"));\n        \n    def(\"solidSphereRand\",&solidSphereRand<float,IMATH_NAMESPACE::Rand32>,\"solidSphereRand(randObj,num) return XYZ vectors uniformly \"\n        \"distributed through the volume of a sphere generated from the given Rand32 object\",\n        args(\"randObj\",\"num\"));\n\n    decoratecopy(rand32_class);\n\n    return rand32_class;\n}\n\nPYIMATH_EXPORT\nclass_<IMATH_NAMESPACE::Rand48>\nregister_Rand48()\n{\n    double (IMATH_NAMESPACE::Rand48::*nextf1)(void) = &IMATH_NAMESPACE::Rand48::nextf;\n    \n    IMATH_NAMESPACE::Vec3<float> (*nextGaussSphere1)(IMATH_NAMESPACE::Rand48 &, const IMATH_NAMESPACE::Vec3<float> &v) = &nextGaussSphere<float,IMATH_NAMESPACE::Rand48>;\n    IMATH_NAMESPACE::Vec3<double> (*nextGaussSphere2)(IMATH_NAMESPACE::Rand48 &, const IMATH_NAMESPACE::Vec3<double> &v) = &nextGaussSphere<double,IMATH_NAMESPACE::Rand48>;\n    IMATH_NAMESPACE::Vec2<float> (*nextGaussSphere3)(IMATH_NAMESPACE::Rand48&, const IMATH_NAMESPACE::Vec2<float> &v) = &nextGaussSphere<float,IMATH_NAMESPACE::Rand48>;\n    IMATH_NAMESPACE::Vec2<double> (*nextGaussSphere4)(IMATH_NAMESPACE::Rand48 &, const IMATH_NAMESPACE::Vec2<double> &v) = &nextGaussSphere<double,IMATH_NAMESPACE::Rand48>;\n    \n    IMATH_NAMESPACE::Vec3<float> (*nextHollowSphere1)(IMATH_NAMESPACE::Rand48 &, const IMATH_NAMESPACE::Vec3<float> &v) = &nextHollowSphere<float,IMATH_NAMESPACE::Rand48>;\n    IMATH_NAMESPACE::Vec3<double> (*nextHollowSphere2)(IMATH_NAMESPACE::Rand48 &, const IMATH_NAMESPACE::Vec3<double> &v) = &nextHollowSphere<double,IMATH_NAMESPACE::Rand48>;\n    IMATH_NAMESPACE::Vec2<float> (*nextHollowSphere3)(IMATH_NAMESPACE::Rand48 &, const IMATH_NAMESPACE::Vec2<float> &v) = &nextHollowSphere<float,IMATH_NAMESPACE::Rand48>;\n    IMATH_NAMESPACE::Vec2<double> (*nextHollowSphere4)(IMATH_NAMESPACE::Rand48 &, const IMATH_NAMESPACE::Vec2<double> &v) = &nextHollowSphere<double,IMATH_NAMESPACE::Rand48>;\n\n    IMATH_NAMESPACE::Vec3<float> (*nextSolidSphere1)(IMATH_NAMESPACE::Rand48 &, const IMATH_NAMESPACE::Vec3<float> &v) = &nextSolidSphere<float,IMATH_NAMESPACE::Rand48>;\n    IMATH_NAMESPACE::Vec3<double> (*nextSolidSphere2)(IMATH_NAMESPACE::Rand48 &, const IMATH_NAMESPACE::Vec3<double> &v) = &nextSolidSphere<double,IMATH_NAMESPACE::Rand48>;\n    IMATH_NAMESPACE::Vec2<float> (*nextSolidSphere3)(IMATH_NAMESPACE::Rand48&, const IMATH_NAMESPACE::Vec2<float> &v) = &nextSolidSphere<float,IMATH_NAMESPACE::Rand48>;\n    IMATH_NAMESPACE::Vec2<double> (*nextSolidSphere4)(IMATH_NAMESPACE::Rand48 &, const IMATH_NAMESPACE::Vec2<double> &v) = &nextSolidSphere<double,IMATH_NAMESPACE::Rand48>;\n   \n    class_< IMATH_NAMESPACE::Rand48 > rand48_class(\"Rand48\");\n    rand48_class\n        .def(init<>(\"default construction\"))\n        .def(\"__init__\", make_constructor(Rand_constructor1<IMATH_NAMESPACE::Rand48>))\n        .def(\"__init__\", make_constructor(Rand_constructor2<IMATH_NAMESPACE::Rand48>))\n        .def(\"init\", &IMATH_NAMESPACE::Rand48::init,\n             \"r.init(i) -- initialize with integer \"\n\t\t\t \"seed i\")\n             \n        .def(\"nexti\", &IMATH_NAMESPACE::Rand48::nexti,\n        \t \"r.nexti() -- return the next integer \"\n\t\t\t \"value in the uniformly-distributed \"\n\t\t\t \"sequence\")\n             \n        .def(\"nextf\", nextf1,\n        \t \"r.nextf() -- return the next double \"\n\t\t\t \"value in the uniformly-distributed \"\n\t\t\t \"sequence\\n\"\n             \n        \t \"r.nextf(double,double) -- return the next double \"\n\t\t\t \"value in the uniformly-distributed \"\n\t\t\t \"sequence\")             \n        .def(\"nextf\", &nextf2 <IMATH_NAMESPACE::Rand48, double>)\n             \n        .def(\"nextb\", &IMATH_NAMESPACE::Rand48::nextb,\n\t \t     \"r.nextb() -- return the next boolean \"\n\t\t\t \"value in the uniformly-distributed \"\n\t\t\t \"sequence\")\n \n        .def(\"nextGauss\", &nextGauss<IMATH_NAMESPACE::Rand48>,\n        \t \"r.nextGauss() -- returns the next \"\n\t\t\t \"floating-point value in the normally \"\n\t\t\t \"(Gaussian) distributed sequence\")\n             \n        .def(\"nextGaussSphere\", nextGaussSphere1, \n\t \t\t \"r.nextGaussSphere(v) -- returns the next \"\n\t\t\t \"point whose distance from the origin \"\n\t\t\t \"has a normal (Gaussian) distribution with \"\n\t\t\t \"mean 0 and variance 1.  The vector \"\n\t\t\t \"argument, v, specifies the dimension \"\n\t\t\t \"and number type.\")             \n        .def(\"nextGaussSphere\", nextGaussSphere2)             \n        .def(\"nextGaussSphere\", nextGaussSphere3)             \n        .def(\"nextGaussSphere\", nextGaussSphere4)\n        \n        .def(\"nextHollowSphere\", nextHollowSphere1,\n        \t \"r.nextHollowSphere(v) -- return the next \"\n\t \t\t \"point uniformly distributed on the surface \"\n\t \t\t \"of a sphere of radius 1 centered at the \"\n\t \t\t \"origin.  The vector argument, v, specifies \"\n\t\t\t \"the dimension and number type.\")             \n        .def(\"nextHollowSphere\", nextHollowSphere2)             \n        .def(\"nextHollowSphere\", nextHollowSphere3)             \n        .def(\"nextHollowSphere\", nextHollowSphere4)\n\n        .def(\"nextSolidSphere\", nextSolidSphere1,\n        \t \"r.nextSolidSphere(v) -- return the next \"\n\t\t\t \"point uniformly distributed in a sphere \"\n\t\t\t \"of radius 1 centered at the origin.  The \"\n\t\t\t \"vector argument, v, specifies the \"\n\t\t\t \"dimension and number type.\")             \n        .def(\"nextSolidSphere\", nextSolidSphere2)             \n        .def(\"nextSolidSphere\", nextSolidSphere3)             \n        .def(\"nextSolidSphere\", nextSolidSphere4) \n        ;\n\n    decoratecopy(rand48_class);\n\n    return rand48_class;\n}\n\n//\n\nPyObject *\nRand32::wrap (const IMATH_NAMESPACE::Rand32 &r)\n{\n    boost::python::return_by_value::apply <IMATH_NAMESPACE::Rand32>::type converter;\n    PyObject *p = converter (r);\n    return p;\n}\n\nPyObject *\nRand48::wrap (const IMATH_NAMESPACE::Rand48 &r)\n{\n    boost::python::return_by_value::apply <IMATH_NAMESPACE::Rand48>::type converter;\n    PyObject *p = converter (r);\n    return p;\n}\n\n} //namespace PyIMath\n", "meta": {"hexsha": "44427e1e35516ade02b427061b0af8b23413a575", "size": 15884, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PyIlmBase/PyImath/PyImathRandom.cpp", "max_stars_repo_name": "FnGyula/openexr", "max_stars_repo_head_hexsha": "82d3d53e46e009a9719f71126a186ef894f7c305", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2016-11-20T19:54:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-25T22:45:51.000Z", "max_issues_repo_path": "PyIlmBase/PyImath/PyImathRandom.cpp", "max_issues_repo_name": "FnGyula/openexr", "max_issues_repo_head_hexsha": "82d3d53e46e009a9719f71126a186ef894f7c305", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-04-10T14:00:47.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-10T14:00:47.000Z", "max_forks_repo_path": "PyIlmBase/PyImath/PyImathRandom.cpp", "max_forks_repo_name": "FnGyula/openexr", "max_forks_repo_head_hexsha": "82d3d53e46e009a9719f71126a186ef894f7c305", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-03-11T10:11:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-05T05:56:01.000Z", "avg_line_length": 44.4929971989, "max_line_length": 174, "alphanum_fraction": 0.688806346, "num_tokens": 4124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.27158018473165396}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <boost/preprocessor/arithmetic/dec.hpp>\n#include <boost/preprocessor/arithmetic/inc.hpp>\n#include <boost/preprocessor/control/expr_iif.hpp>\n#include <boost/preprocessor/list/adt.hpp>\n#include <boost/preprocessor/repetition/for.hpp>\n#include <boost/preprocessor/repetition/repeat.hpp>\n#include <boost/preprocessor/tuple/to_list.hpp>\n#include <limits>\n#include <pup.h>\n\n#include \"DataStructures/Tensor/TypeAliases.hpp\"\n#include \"Options/Options.hpp\"\n#include \"Parallel/CharmPupable.hpp\"\n#include \"PointwiseFunctions/Hydro/EquationsOfState/EquationOfState.hpp\"  // IWYU pragma: keep\n#include \"Utilities/TMPL.hpp\"\n\n/// \\cond\nclass DataVector;\n/// \\endcond\n\nnamespace EquationsOfState {\n/*!\n * \\ingroup EquationsOfStateGroup\n * \\brief Equation of state for a dark energy fluid\n *\n * A dark energy fluid equation of state:\n * \\f[\n * p = w(z) \\rho ( 1.0 + \\epsilon)\n * \\f]\n * where \\f$\\rho\\f$ is the rest mass density, \\f$\\epsilon\\f$ is the specific\n * internal energy, and \\f$w(z) > 0\\f$ is a parameter depending on the redshift\n * \\f$z\\f$.\n */\ntemplate <bool IsRelativistic>\nclass DarkEnergyFluid : public EquationOfState<IsRelativistic, 2> {\n public:\n  static_assert(IsRelativistic,\n                \"Dark energy fluid equation of state only makes sense in a \"\n                \"relativistic setting.\");\n\n  struct ParameterW {\n    using type = double;\n    static constexpr OptionString help = {\"Parameter w(z)\"};\n  };\n\n  static constexpr OptionString help = {\n      \"A dark energy fluid equation of state.\\n\"\n      \"The pressure is related to the rest mass density by \"\n      \"p = w(z) * rho * (1 + epsilon), where p is the pressure, rho is the \"\n      \"rest mass density, epsilon is the specific internal energy, and w(z) is \"\n      \"a parameter.\"};\n\n  using options = tmpl::list<ParameterW>;\n\n  DarkEnergyFluid() = default;\n  DarkEnergyFluid(const DarkEnergyFluid&) = default;\n  DarkEnergyFluid& operator=(const DarkEnergyFluid&) = default;\n  DarkEnergyFluid(DarkEnergyFluid&&) = default;\n  DarkEnergyFluid& operator=(DarkEnergyFluid&&) = default;\n  ~DarkEnergyFluid() override = default;\n\n  explicit DarkEnergyFluid(double parameter_w) noexcept;\n\n  EQUATION_OF_STATE_FORWARD_DECLARE_MEMBERS(DarkEnergyFluid, 2)\n\n  WRAPPED_PUPable_decl_base_template(  // NOLINT\n      SINGLE_ARG(EquationOfState<IsRelativistic, 2>), DarkEnergyFluid);\n\n private:\n  EQUATION_OF_STATE_FORWARD_DECLARE_MEMBER_IMPLS(2)\n\n  double parameter_w_ = std::numeric_limits<double>::signaling_NaN();\n};\n\n/// \\cond\ntemplate <bool IsRelativistic>\nPUP::able::PUP_ID EquationsOfState::DarkEnergyFluid<IsRelativistic>::my_PUP_ID =\n    0;\n/// \\endcond\n}  // namespace EquationsOfState\n", "meta": {"hexsha": "84981883342065052b964a3c470fe793a39ee855", "size": 2737, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/PointwiseFunctions/Hydro/EquationsOfState/DarkEnergyFluid.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/PointwiseFunctions/Hydro/EquationsOfState/DarkEnergyFluid.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/PointwiseFunctions/Hydro/EquationsOfState/DarkEnergyFluid.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": 31.8255813953, "max_line_length": 94, "alphanum_fraction": 0.7296309828, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.2715801777686696}}
{"text": "#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include \"BodyModel.hpp\"\n#include \"Generator.hpp\"\n#include \"utils/body.hpp\"\n#include \"utils/matrix_helpers.hpp\"\n\nconst float BodyModel::COM_HEIGHT = 200;\nconst float BodyModel::MOTION_DT = 1 / 100.0f;\nconst float BodyModel::FOOT_LENGTH = 160;\nconst float BodyModel::L_RATE = 0.5;\n\nBodyModel::BodyModel() : filAccX(0.0),\n                         filAccY(0.0),\n                         filteredTotalPressure(0.0),\n                         filHighZMPF(0.0),\n                         filLowZMPF(0.0),\n                         filZMPL(0.0)\n{\n   stepCounter = 0;\n   sagittalAcceleration = 0.0;\n   forwardR = forwardL = 0.0;\n\n   isLeftPhase = false;\n   isOnFront = false;\n   lastIsLeftPhase = false;\n\n   // real body model\n   isStopped = false;\n\n   //Used to AutoCalibrate Footsensors\n\tfsLfr = fsLfl = fsLrr = fsLrl = 0.1;                   // keeps maximum foot sensor readings\n\tfsRfr = fsRfl = fsRrr = fsRrl = 0.1;                   // small value deemed close to zero initially\n}\n\nvoid BodyModel::update(Odometry *odometry,\n                       const SensorValues &sensors) {\n   // Various Center of Pressure calcs to help stabilise walk (ZMP)\n   stepCounter++;\n   // Update maximum sensed foot-sensor readings\n\tfloat temp = sensors.sensors[Sensors::LFoot_FSR_FrontLeft]; if(fsLfl<temp and fsLfl<5.0) fsLfl = temp;\n\ttemp = sensors.sensors[Sensors::LFoot_FSR_FrontLeft];       if(fsLfl<temp and fsLfl<5.0) fsLfl = temp;\n\ttemp = sensors.sensors[Sensors::LFoot_FSR_FrontRight];      if(fsLfr<temp and fsLfr<5.0) fsLfr = temp;\n\ttemp = sensors.sensors[Sensors::LFoot_FSR_RearLeft];        if(fsLrl<temp and fsLrl<5.0) fsLrl = temp;\n\ttemp = sensors.sensors[Sensors::LFoot_FSR_RearRight];       if(fsLrr<temp and fsLrr<5.0) fsLrr = temp;\n\ttemp = sensors.sensors[Sensors::RFoot_FSR_FrontLeft];       if(fsRfl<temp and fsRfl<5.0) fsRfl = temp;\n\ttemp = sensors.sensors[Sensors::RFoot_FSR_FrontRight];      if(fsRfr<temp and fsRfr<5.0) fsRfr = temp;\n\ttemp = sensors.sensors[Sensors::RFoot_FSR_RearLeft];        if(fsRrl<temp and fsRrl<5.0) fsRrl = temp;\n\ttemp = sensors.sensors[Sensors::RFoot_FSR_RearRight];       if(fsRrr<temp and fsRrr<5.0) fsRrr = temp;\n\tlastZMPL = ZMPL;\n\tZMPL = 0;\n\t// Calculate ZMPL (left-right) used to eg switch support foot in Walk2014\n\tfloat pressureL =\n\t  +sensors.sensors[Sensors::LFoot_FSR_FrontLeft]/fsLfl\n\t  + sensors.sensors[Sensors::LFoot_FSR_FrontRight]/fsLfr\n\t  + sensors.sensors[Sensors::LFoot_FSR_RearLeft]/fsLrl\n\t  + sensors.sensors[Sensors::LFoot_FSR_RearRight]/fsLrr;\n\tfloat pressureR =\n\t  +sensors.sensors[Sensors::RFoot_FSR_FrontLeft]/fsRfl\n\t  + sensors.sensors[Sensors::RFoot_FSR_FrontRight]/fsRfr\n\t  + sensors.sensors[Sensors::RFoot_FSR_RearLeft]/fsRrl\n\t  + sensors.sensors[Sensors::RFoot_FSR_RearRight]/fsRrr;\n\tfloat totalPressure = pressureL + pressureR;\n\tif (ABS(totalPressure) > 0.000001f) {\n\t\t\tZMPL =\n\t\t\t(  .080 * sensors.sensors[Sensors::LFoot_FSR_FrontLeft]/fsLfl\n\t\t\t+ .030 * sensors.sensors[Sensors::LFoot_FSR_FrontRight]/fsLfr\n\t\t\t+ .080 * sensors.sensors[Sensors::LFoot_FSR_RearLeft]/fsLrl\n\t\t\t+ .030 * sensors.sensors[Sensors::LFoot_FSR_RearRight]/fsLrr\n\t\t\t- .030 * sensors.sensors[Sensors::RFoot_FSR_FrontLeft]/fsRfl\n\t\t\t- .080 * sensors.sensors[Sensors::RFoot_FSR_FrontRight]/fsRfr\n\t\t\t- .030 * sensors.sensors[Sensors::RFoot_FSR_RearLeft]/fsRrl\n\t\t\t- .080 * sensors.sensors[Sensors::RFoot_FSR_RearRight]/fsRrr) / totalPressure;\n\t\t}\n\n   isOnFront = isOnFrontOfFoot(sensors);\n   processUpdate(odometry, sensors);\n   observationUpdate(odometry, sensors);\n}\n\n\nbool BodyModel::isFootOnGround(const SensorValues &sensors) {\n   float leftFrontL = sensors.sensors[Sensors::LFoot_FSR_FrontLeft];\n   float leftFrontR = sensors.sensors[Sensors::LFoot_FSR_FrontRight];\n   float rightFrontL = sensors.sensors[Sensors::RFoot_FSR_FrontLeft];\n   float rightFrontR = sensors.sensors[Sensors::RFoot_FSR_FrontRight];\n   float leftRearL  = sensors.sensors[Sensors::LFoot_FSR_RearLeft];\n   float leftRearR  = sensors.sensors[Sensors::LFoot_FSR_RearRight];\n   float rightRearL = sensors.sensors[Sensors::RFoot_FSR_RearLeft];\n   float rightRearR = sensors.sensors[Sensors::RFoot_FSR_RearRight];\n   if (isLeftPhase) {\n      return rightFrontL > 0.01 && rightFrontR > 0.01 &&\n             rightRearL > 0.01 && rightRearR > 0.01;\n   }\n   return leftFrontL > 0.01 &&  leftFrontR > 0.01 &&\n          leftRearL > 0.01 && leftRearR > 0.01;\n}\n\nbool BodyModel::isOnFrontOfFoot(const SensorValues &sensors) {\n   float leftFront = sensors.sensors[Sensors::LFoot_FSR_FrontLeft] +\n                     sensors.sensors[Sensors::LFoot_FSR_FrontRight];\n   float rightFront = sensors.sensors[Sensors::RFoot_FSR_FrontLeft] +\n                      sensors.sensors[Sensors::RFoot_FSR_FrontRight];\n   float leftRear  = sensors.sensors[Sensors::LFoot_FSR_RearLeft] +\n                     sensors.sensors[Sensors::LFoot_FSR_RearRight];\n   float rightRear = sensors.sensors[Sensors::RFoot_FSR_RearLeft] +\n                     sensors.sensors[Sensors::RFoot_FSR_RearRight];\n   if (isLeftPhase) {\n      return rightFront > rightRear;\n   }\n   return leftFront > leftRear;\n}\n\nfloat BodyModel::getFootZMP(bool isLeft, const SensorValues &sensors) {\n   if (walkCycle.isDoubleSupportPhase()) return 0;\n   float ZMPF = 0;\n   float totalPressure = 0;\n   if (isLeft) {\n      totalPressure += sensors.sensors[Sensors::LFoot_FSR_FrontLeft]\n                         + sensors.sensors[Sensors::LFoot_FSR_FrontRight]\n                         + sensors.sensors[Sensors::LFoot_FSR_RearLeft]\n                         + sensors.sensors[Sensors::LFoot_FSR_RearRight];\n   } else {\n      totalPressure += sensors.sensors[Sensors::RFoot_FSR_FrontLeft]\n                         + sensors.sensors[Sensors::RFoot_FSR_FrontRight]\n                         + sensors.sensors[Sensors::RFoot_FSR_RearLeft]\n                         + sensors.sensors[Sensors::RFoot_FSR_RearRight];\n   }\n   if (isLeft) {\n      ZMPF =  \n            (75.0f) * sensors.sensors[Sensors::LFoot_FSR_FrontLeft]\n          + (-45.0f) * sensors.sensors[Sensors::LFoot_FSR_RearLeft]\n          + (75.0f) * sensors.sensors[Sensors::LFoot_FSR_FrontRight]\n          + (-45.0f) * sensors.sensors[Sensors::LFoot_FSR_RearRight];\n   } else {   \n      ZMPF = \n           (75.0f) * sensors.sensors[Sensors::RFoot_FSR_FrontRight]\n         + (-45.0f) * sensors.sensors[Sensors::RFoot_FSR_RearRight]\n         + (75.0f) * sensors.sensors[Sensors::RFoot_FSR_FrontLeft]\n         + (-45.0f) * sensors.sensors[Sensors::RFoot_FSR_RearLeft];\n   }\n   if (totalPressure == 0) return  0;\n   ZMPF /= totalPressure;\n   return ZMPF;\n}\n\nfloat BodyModel::getHorizontalFootZMP(bool isLeft, const SensorValues &sensors) {\n   float ZMPF = 0;\n   float totalPressure = 0;\n   if (isLeft) {\n      totalPressure += sensors.sensors[Sensors::LFoot_FSR_FrontLeft]\n                         + sensors.sensors[Sensors::LFoot_FSR_FrontRight]\n                         + sensors.sensors[Sensors::LFoot_FSR_RearLeft]\n                         + sensors.sensors[Sensors::LFoot_FSR_RearRight];\n   } else {\n      totalPressure += sensors.sensors[Sensors::RFoot_FSR_FrontLeft]\n                         + sensors.sensors[Sensors::RFoot_FSR_FrontRight]\n                         + sensors.sensors[Sensors::RFoot_FSR_RearLeft]\n                         + sensors.sensors[Sensors::RFoot_FSR_RearRight];\n   }\n   if (isLeft) {\n      ZMPF =  \n            (20.0f) * sensors.sensors[Sensors::LFoot_FSR_FrontLeft]\n          + (20.0f) * sensors.sensors[Sensors::LFoot_FSR_RearLeft]\n          + (-20.0f) * sensors.sensors[Sensors::LFoot_FSR_FrontRight]\n          + (-20.0f) * sensors.sensors[Sensors::LFoot_FSR_RearRight];\n   } else {   \n      ZMPF = \n           (-20.0f) * sensors.sensors[Sensors::RFoot_FSR_FrontRight]\n         + (-20.0f) * sensors.sensors[Sensors::RFoot_FSR_RearRight]\n         + (20.0f) * sensors.sensors[Sensors::RFoot_FSR_FrontLeft]\n         + (20.0f) * sensors.sensors[Sensors::RFoot_FSR_RearLeft];\n   }\n   if (totalPressure == 0) return  0;\n   ZMPF /= totalPressure;\n   return ZMPF;\n}\n\nvoid BodyModel::simulationUpdate() {}\n\nvoid BodyModel::processUpdate(Odometry *odometry, const SensorValues &sensors) {\n   float forwardL, forwardR, leftL, leftR, turnLR, liftL, liftR;\n   walkCycle.generateWalk(forwardL, forwardR, leftL, leftR, turnLR, liftL, liftR);\n   \n   boost::numeric::ublas::matrix<float> b2f =\n      kinematics->evaluateDHChain(\n         Kinematics::FOOT,\n         Kinematics::BODY,\n         isLeftPhase ? Kinematics::RIGHT_CHAIN : Kinematics::LEFT_CHAIN);\n   \n   boost::numeric::ublas::matrix<float> b2fOther =\n      kinematics->evaluateDHChain(\n         Kinematics::FOOT,\n         Kinematics::BODY,\n         isLeftPhase ? Kinematics::LEFT_CHAIN : Kinematics::RIGHT_CHAIN);\n\n   boost::numeric::ublas::matrix<float> n2f =\n      kinematics->evaluateDHChain(\n         Kinematics::FOOT,\n         Kinematics::NECK,\n         isLeftPhase ? Kinematics::RIGHT_CHAIN : Kinematics::LEFT_CHAIN);\n\n\n   boost::numeric::ublas::matrix<float> f2w =\n                  kinematics->createFootToWorldTransform(\n         isLeftPhase ? Kinematics::RIGHT_CHAIN : Kinematics::LEFT_CHAIN);\n\n   boost::numeric::ublas::matrix<float> b2w = boost::numeric::ublas::prod(f2w, b2f);\n   boost::numeric::ublas::matrix<float> n2w = boost::numeric::ublas::prod(f2w, n2f);\n   boost::numeric::ublas::matrix<float> origin = vec4<float>(0, 0, 0, 1);\n   boost::numeric::ublas::matrix<float> result = boost::numeric::ublas::prod(b2f, origin);\n   boost::numeric::ublas::matrix<float> rPend = boost::numeric::ublas::prod(b2w, origin);\n   boost::numeric::ublas::matrix<float> neckPend = boost::numeric::ublas::prod(n2w, origin);\n   // float deg = atan2(neckPend(0, 0) - rPend(0, 0), neckPend(2, 0) - rPend(2, 0));\n//   std::cout << neckPend(0, 0) << \" : \" << rPend(0, 0) << \" \" << neckPend(1, 0) << \" \" << neckPend(2, 0) << \" \" << RAD2DEG(deg) << std::endl;\n\n   // float alpha = sensors.sensors[Sensors::InertialSensor_AngleY];\n   // float beta = deg; // sensors.joints.angles[Joints::LHipPitch];\n   // float psi = alpha - beta;\n   // float psiKinematic = atan2(rPend(0, 0), COM_HEIGHT);\n   // float thau = psi - psiKinematic;\n\n   // Calculate the centre of mass, convert to frame of reference of foot\n   // (ie to foot then rotated by body lean)\n   boost::numeric::ublas::matrix<float> com = kinematics->evaluateMassChain();\n   boost::numeric::ublas::matrix<float> comOther = prod(b2fOther, com); // inserted CoM for other foot - BH\n   centreOfMassOther.x = comOther(0, 0);                                // \"\n   centreOfMassOther.y = comOther(1, 0);                                // \"\n   centreOfMassOther.z = comOther(2, 0);                                // \"\n   com = prod(b2f, com);\n   centreOfMass.x = com(0, 0);\n   centreOfMass.y = com(1, 0);\n   centreOfMass.z = com(2, 0);\n\n   //std::cout << \"COM x: \" << centreOfMass.x << \" y: \" << centreOfMass.y << \" z: \" << centreOfMass.z << std::endl;\n\n\n   //the following is left from 2011 and is not used atm\n\n   // Get the ZMP from the supporting foot\n   float zmpFootOffset = 0;\n   if (!getWalkCycle().isDoubleSupportPhase()) {\n      zmpFootOffset = getFootZMP(!isLeftPhase, sensors);\n   }\n\n   //prediction update\n   pendulumModel.predictNext(1/100.0, zmpFootOffset);\n\n   //std::cout << \"##############\" << std::endl;\n   //std::cout << \"prediction:   \" << std::endl;\n   //std::cout << \"x: \" << pendulumModel.x << std::endl;\n   //std::cout << \"dx: \" << pendulumModel.dx << std::endl;\n   //std::cout << \"accX: \" << pendulumModel.accX << std::endl;\n   //std::cout << \"theta: \" << pendulumModel.theta << std::endl;\n   //std::cout << \"t: \" << pendulumModel.walkCycle.t << std::endl;\n   \n   //observation update\n   float supportFootPosition = result(0, 0); \n   //float h = result(2, 0);\n   //float deg = atan2(supportFootPosition - zmpFootOffset, h);\n   WalkCycle currentWalkCycle = walkCycle;\n   \n   /*\n   std::cout << \"ZMP :\" << zmpFootOffset << std::endl;\n   std::cout << \"observed x:\" << supportFootPosition <<  std::endl;\n   std::cout << \"observed accX:\" << sensors.sensors[Sensors::InertialSensor_AccX] \n             << std::endl;\n   */\n\n   float alpha = 0.2;\n   float beta = 0.5;\n      \n   pendulumModel.x = (1 - beta) * pendulumModel.x + (beta) * supportFootPosition;\n   if (pendulumModel.walkCycle.leftPhase == currentWalkCycle.leftPhase) {\n      pendulumModel.dx = (1 - alpha) * pendulumModel.dx + (alpha) * (pendulumModel.x - lastPendulumModel.x) * 100;\n   } else { //switching foot\n      pendulumModel.x = -pendulumModel.x/1.2;\n   }\n   pendulumModel.walkCycle = currentWalkCycle;\n   \n   lastPendulumModel.x = pendulumModel.x;\n   lastPendulumModel.dx = pendulumModel.dx;\n  \n   /*\n   std::cout << \"updated:\" << std::endl;\n   std::cout << \"x: \" << pendulumModel.x << std::endl;\n   std::cout << \"dx: \" << pendulumModel.dx << std::endl;\n   std::cout << \"t: \" << pendulumModel.walkCycle.t << std::endl;\n   */\n\n   /*foot switched\n   if (pendulumModel.walkCycle.leftPhase != currentWalkCycle.leftPhase) {\n      if (!currentWalkCycle.leftPhase) {\n         // switching to left support phase\n         pendulumModel.x = pendulumModel.x + forwardR - forwardL;\n      } else {\n         pendulumModel.x = pendulumModel.x + forwardL - forwardR;\n      }\n\n   }*/\n}\n\nvoid BodyModel::observationUpdate(Odometry *odometry, const SensorValues &sensors) {\n   /*\n   float supportFootPosition = isLeftPhase ? forwardR : forwardL;\n   // supportFootPosition += isOnFront ? FOOT_LENGTH/2 : -FOOT_LENGTH/2;\n   float r = sqrt(supportFootPosition * supportFootPosition + COM_HEIGHT * COM_HEIGHT);\n\n   float obsDTheta = lastHatDTheta +\n                     sensors.sensors[Sensors::InertialSensor_AccX] * cos(theta) * MOTION_DT / r;\n   dTheta += (obsDTheta - dTheta) * 0.5;\n   */\n}\n\n", "meta": {"hexsha": "d137f2e14d805d09c79bf90404c1b41919b4a559", "size": 13785, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Core/External/unsw/unsw/motion/generator/BodyModel.cpp", "max_stars_repo_name": "pedrohsreis/boulos", "max_stars_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-09-18T18:05:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-23T17:47:07.000Z", "max_issues_repo_path": "src/Core/External/unsw/unsw/motion/generator/BodyModel.cpp", "max_issues_repo_name": "pedrohsreis/boulos", "max_issues_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-08T18:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-19T21:41:16.000Z", "max_forks_repo_path": "src/Core/External/unsw/unsw/motion/generator/BodyModel.cpp", "max_forks_repo_name": "pedrohsreis/boulos", "max_forks_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-09-11T17:19:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-30T16:43:56.000Z", "avg_line_length": 43.6234177215, "max_line_length": 143, "alphanum_fraction": 0.6504896627, "num_tokens": 4203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.27157998280467}}
{"text": "/**\n * @brief       Battery_model\n * @file        Battery_model.cpp\n * @author      Richard Kirby <rkirby@kspresearch.com>\n * @copyright   Copyright (c) 2018, Swift Engineering Inc.\n * @license     Licensed under the MIT license. See LICENSE for details.\n */\n\n#include \"Battery_model.hpp\"\n\n#include <boost/math/tools/rational.hpp>\n\n#include <cmath>\n#include <cstdint>\n#include <cstdio>\n#include <limits>\n\nnamespace avionics_sim {\n\nbool Battery_model::initialize(const double initial_soc, const double capacity, const uint8_t num_cells, const double C,\n                               const double R) {\n    // R must be > 0 or divide by zero error, set C = 0 to turn off transient response.\n    if (!(R <= 0.0 || C < 0.0)) {\n        m_c = C;\n        m_r = R;\n    }\n\n    m_num_discharge_curves = 0;\n    m_initial_soc = initial_soc;\n    m_soc = m_initial_soc;  // in Ah\n    m_capacity = capacity;  // in Ah\n    m_num_cells = num_cells;\n    m_low_current_curve_current = std::numeric_limits<double>::infinity();\n    m_high_current_curve_current = -1;\n    return true;\n}\n\nvoid Battery_model::update_soc(const double current, const double timestep, double *const voltage, double *const soc) {\n    // simple coluomb counter\n    if (timestep > 0.0) {\n        m_soc += current * timestep / 3600;  // Time step is in seconds, need hours for mAhrs\n        *voltage = get_voltage(m_soc * 1000, current, timestep);  // curves are in mA hours\n        *soc = m_soc;\n    } else {\n        *voltage = m_last_voltage;\n        *soc = m_soc;\n    }\n}\n\nvoid Battery_model::update_soc_ocv(const double current, const double timestep, double *const voltage,\n                                   double *const soc) {\n    // simple coluomb counter\n    if (timestep > 0.0 && current > 0.0) {\n        m_soc += current * timestep / 3600;  // Time step is in seconds, need hours for mAhrs\n        *voltage = get_voltage_ocv(m_soc, current, timestep);\n        *soc = m_soc;\n    } else {\n        *voltage = m_last_voltage_ocv;\n        *soc = m_soc;\n    }\n}\n\n// discharge curves are in mAhrs\ndouble Battery_model::get_voltage(const double soc, const double current_in, const double timestep) {\n    double current = current_in;\n\n    // Ensure that there are at least two discharge curves\n    if (m_num_discharge_curves < 2) {\n        return m_num_cells * m_last_voltage;\n    }\n\n    // Ensure current is between the two discharge curves\n    if (current > m_high_current_curve_current) {\n        current = m_high_current_curve_current;\n    }\n\n    if (current < m_low_current_curve_current) {\n        current = m_low_current_curve_current;\n    }\n\n    // Find the curves that bracket the load\n    int8_t low_current_discharge_curve = -1, high_current_discharge_curve = -1;\n    double delta1 = std::numeric_limits<double>::infinity(), delta2 = std::numeric_limits<double>::infinity();\n\n    for (uint8_t i = 0 ; i < m_num_discharge_curves ; i++) {\n        if (m_discharge_curves[i].load <= current) {\n            if (delta1 > (current - m_discharge_curves[i].load)) {\n                delta1 = current - m_discharge_curves[i].load;\n                low_current_discharge_curve = i;\n            }\n        }\n\n        if (m_discharge_curves[i].load >= current) {\n            if (delta2 > (m_discharge_curves[i].load - current)) {\n                delta2 = m_discharge_curves[i].load - current;\n                high_current_discharge_curve = i;\n            }\n        }\n    }\n\n    // The low voltage comes from the high discharge current and vice versa\n    double voltage_low = compute_voltage(soc, high_current_discharge_curve);\n    double voltage_high = compute_voltage(soc, low_current_discharge_curve);\n\n    // If the load is bracketed by the same curve, then the load is equal to that curve otherwise interpolate\n    double voltage;\n\n    if (low_current_discharge_curve == high_current_discharge_curve) {\n        voltage = voltage_low;\n    } else {\n        voltage = (\n                      (current - m_discharge_curves[low_current_discharge_curve].load) /\n                      (\n                          m_discharge_curves[high_current_discharge_curve].load\n                          - m_discharge_curves[low_current_discharge_curve].load\n                      )\n                  )\n                  * (voltage_high - voltage_low) + voltage_low;\n    }\n\n    // add transient response\n    if (timestep > 0) {\n        voltage = voltage - (m_c / m_r) * (voltage - m_last_voltage) / (timestep);\n        m_last_voltage = voltage;\n    }\n\n    return m_num_cells * voltage;\n}\n\n// discharge curves are in mAhrs\ndouble Battery_model::get_voltage_ocv(const double soc, const double current_in, const double timestep) {\n    double current = current_in;\n\n    // get open circuit voltage, OCV uses curve 0\n    double voltage = compute_voltage(soc, 0);   // returns voltage per cell\n\n    // compensate for internal resistance drop\n    float soc_percent = (m_capacity - soc) / m_capacity;\n    double ir = compute_internal_resistance(soc_percent, 1.0);\n    voltage = voltage - (ir * current) / m_num_cells;\n\n    // add transient response\n    if (timestep > 0) {\n        voltage = voltage - (m_c / m_r) * (voltage - m_last_voltage_ocv) / (timestep);\n        m_last_voltage_ocv = voltage;\n    }\n\n    return  m_num_cells * voltage;\n}\n\nbool Battery_model::add_discharge_curves(const discharge_curve &dc) {\n    if (m_num_discharge_curves > max_num_discharge_curves) {\n        return false;\n    }\n\n    m_discharge_curves.push_back(dc);\n\n    if (m_discharge_curves[m_num_discharge_curves].load < m_low_current_curve_current) {\n        m_low_current_curve_current = m_discharge_curves[m_num_discharge_curves].load;\n        m_index_of_low_current_curve = m_num_discharge_curves;\n    }\n\n    if (m_discharge_curves[m_num_discharge_curves].load > m_high_current_curve_current) {\n        m_high_current_curve_current = m_discharge_curves[m_num_discharge_curves].load;\n        m_index_of_high_current_curve = m_num_discharge_curves;\n    }\n\n    m_num_discharge_curves++;\n    return true;\n}\n\nbool Battery_model::set_internal_resistance_coefficients(const internal_resistance_curve &ir_coeff) {\n    if (m_internal_resistance_curve.size() > 0) {\n        return false;    // currently only one internal resistance curve is supported, but\n    }\n\n    // using a vector allows support for multiple internal resistance curves, which will change with state of health\n    m_internal_resistance_curve.push_back(ir_coeff);\n    return true;\n}\n\ndouble  Battery_model::compute_voltage(double soc, const uint8_t curve) {\n    return boost::math::tools::evaluate_polynomial(m_discharge_curves[curve].c, soc);\n}\n\ndouble Battery_model::compute_internal_resistance(double soc, double soh) {\n    // allows adding additional internal resistance curves for different states of health\n    // currently only one curve is supported\n    const uint8_t curve =  0;\n\n    return (boost::math::tools::evaluate_polynomial(m_internal_resistance_curve[curve].c, soc,\n            m_internal_resistance_num_coef) + m_internal_resistance_curve[curve].harness_resistance);\n}\n\ndouble Battery_model::compute_max_power_available(const double v_volts, const double ir_ohms) {\n    return v_volts * v_volts / (4 * ir_ohms);\n}\n\ndouble Battery_model::get_soc_percent() {\n    return (m_capacity - m_soc) / m_capacity;\n}\n\n}  // namespace avionics_sim\n", "meta": {"hexsha": "d089517a8981abb202aeb2fe68bad3948eb1f2cc", "size": 7326, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Battery_model.cpp", "max_stars_repo_name": "SwiftEngineering/avionics_sim", "max_stars_repo_head_hexsha": "8fa3ef497137dd54966ff9de43cbcf2bfbf82d96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Battery_model.cpp", "max_issues_repo_name": "SwiftEngineering/avionics_sim", "max_issues_repo_head_hexsha": "8fa3ef497137dd54966ff9de43cbcf2bfbf82d96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Battery_model.cpp", "max_forks_repo_name": "SwiftEngineering/avionics_sim", "max_forks_repo_head_hexsha": "8fa3ef497137dd54966ff9de43cbcf2bfbf82d96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9117647059, "max_line_length": 120, "alphanum_fraction": 0.6722631723, "num_tokens": 1777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.27157998280467}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_MOD_STER_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_MOD_STER_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 <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#include <boost/geometry/extensions/gis/projections/impl/aasincos.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/pj_zpoly1.hpp>\n\nnamespace boost { namespace geometry { namespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace mod_ster\n    {\n\n            static const double EPSLN = 1e-10;\n\n            struct par_mod_ster\n            {\n                COMPLEX    *zcoeff;\n                double    cchio, schio;\n                int        n;\n            };\n\n            /* based upon Snyder and Linck, USGS-NMD */\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename Geographic, typename Cartesian, typename Parameters>\n            struct base_mod_ster_ellipsoid : public base_t_fi<base_mod_ster_ellipsoid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>\n            {\n\n                 typedef double geographic_type;\n                 typedef double cartesian_type;\n\n                par_mod_ster m_proj_parm;\n\n                inline base_mod_ster_ellipsoid(const Parameters& par)\n                    : base_t_fi<base_mod_ster_ellipsoid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>(*this, par) {}\n\n                // FORWARD(e_forward)  ellipsoid\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 sinlon, coslon, esphi, chi, schi, cchi, s;\n                    COMPLEX p;\n\n                    sinlon = sin(lp_lon);\n                    coslon = cos(lp_lon);\n                    esphi = this->m_par.e * sin(lp_lat);\n                    chi = 2. * atan(tan((geometry::math::half_pi<double>() + lp_lat) * .5) *\n                        pow((1. - esphi) / (1. + esphi), this->m_par.e * .5)) - geometry::math::half_pi<double>();\n                    schi = sin(chi);\n                    cchi = cos(chi);\n                    s = 2. / (1. + this->m_proj_parm.schio * schi + this->m_proj_parm.cchio * cchi * coslon);\n                    p.r = s * cchi * sinlon;\n                    p.i = s * (this->m_proj_parm.cchio * schi - this->m_proj_parm.schio * cchi * coslon);\n                    p = pj_zpoly1(p, this->m_proj_parm.zcoeff, this->m_proj_parm.n);\n                    xy_x = p.r;\n                    xy_y = p.i;\n                }\n\n                // INVERSE(e_inverse)  ellipsoid\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                    int nn;\n                    COMPLEX p, fxy, fpxy, dp;\n                    double den, rh = 0, z, sinz = 0, cosz = 0, chi, phi = 0, dphi, esphi;\n\n                    p.r = xy_x;\n                    p.i = xy_y;\n                    for (nn = 20; nn ;--nn) {\n                        fxy = pj_zpolyd1(p, this->m_proj_parm.zcoeff, this->m_proj_parm.n, &fpxy);\n                        fxy.r -= xy_x;\n                        fxy.i -= xy_y;\n                        den = fpxy.r * fpxy.r + fpxy.i * fpxy.i;\n                        dp.r = -(fxy.r * fpxy.r + fxy.i * fpxy.i) / den;\n                        dp.i = -(fxy.i * fpxy.r - fxy.r * fpxy.i) / den;\n                        p.r += dp.r;\n                        p.i += dp.i;\n                        if ((fabs(dp.r) + fabs(dp.i)) <= EPSLN)\n                            break;\n                    }\n                    if (nn) {\n                        rh = boost::math::hypot(p.r, p.i);\n                        z = 2. * atan(.5 * rh);\n                        sinz = sin(z);\n                        cosz = cos(z);\n                        lp_lon = this->m_par.lam0;\n                        if (fabs(rh) <= EPSLN) {\n                            lp_lat = this->m_par.phi0;\n                            return;\n                        }\n                        chi = aasin(cosz * this->m_proj_parm.schio + p.i * sinz * this->m_proj_parm.cchio / rh);\n                        phi = chi;\n                        for (nn = 20; nn ;--nn) {\n                            esphi = this->m_par.e * sin(phi);\n                            dphi = 2. * atan(tan((geometry::math::half_pi<double>() + chi) * .5) *\n                                pow((1. + esphi) / (1. - esphi), this->m_par.e * .5)) - geometry::math::half_pi<double>() - phi;\n                            phi += dphi;\n                            if (fabs(dphi) <= EPSLN)\n                                break;\n                        }\n                    }\n                    if (nn) {\n                        lp_lat = phi;\n                        lp_lon = atan2(p.r * sinz, rh * this->m_proj_parm.cchio * cosz - p.i *\n                            this->m_proj_parm.schio * sinz);\n                    } else\n                        lp_lon = lp_lat = HUGE_VAL;\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"mod_ster_ellipsoid\";\n                }\n\n            };\n\n            template <typename Parameters>\n            void setup(Parameters& par, par_mod_ster& proj_parm)  /* general initialization */\n            {\n                double esphi, chio;\n\n                if (par.es) {\n                    esphi = par.e * sin(par.phi0);\n                    chio = 2. * atan(tan((geometry::math::half_pi<double>() + par.phi0) * .5) *\n                        pow((1. - esphi) / (1. + esphi), par.e * .5)) - geometry::math::half_pi<double>();\n                } else\n                    chio = par.phi0;\n                proj_parm.schio = sin(chio);\n                proj_parm.cchio = cos(chio);\n            }\n\n\n            // Miller Oblated Stereographic\n            template <typename Parameters>\n            void setup_mil_os(Parameters& par, par_mod_ster& proj_parm)\n            {\n                static COMPLEX /* Miller Oblated Stereographic */\n            AB[] = {\n                {0.924500,    0.},\n                {0.,            0.},\n                {0.019430,    0.}\n            };\n\n                proj_parm.n = 2;\n                par.lam0 = geometry::math::d2r<double>() * 20.;\n                par.phi0 = geometry::math::d2r<double>() * 18.;\n                proj_parm.zcoeff = AB;\n                par.es = 0.;\n                setup(par, proj_parm);\n            }\n\n            // Lee Oblated Stereographic\n            template <typename Parameters>\n            void setup_lee_os(Parameters& par, par_mod_ster& proj_parm)\n            {\n                static COMPLEX /* Lee Oblated Stereographic */\n            AB[] = {\n                {0.721316,    0.},\n                {0.,            0.},\n                    {-0.0088162,     -0.00617325}\n            };\n\n                proj_parm.n = 2;\n                par.lam0 = geometry::math::d2r<double>() * -165.;\n                par.phi0 = geometry::math::d2r<double>() * -10.;\n                proj_parm.zcoeff = AB;\n                par.es = 0.;\n                setup(par, proj_parm);\n            }\n\n            // Mod. Stererographics of 48 U.S.\n            template <typename Parameters>\n            void setup_gs48(Parameters& par, par_mod_ster& proj_parm)\n            {\n                static COMPLEX /* 48 United States */\n            AB[] = {\n                {0.98879,    0.},\n                {0.,        0.},\n                {-0.050909,    0.},\n                {0.,        0.},\n                    {0.075528,    0.}\n            };\n\n                proj_parm.n = 4;\n                par.lam0 = geometry::math::d2r<double>() * -96.;\n                par.phi0 = geometry::math::d2r<double>() * -39.;\n                proj_parm.zcoeff = AB;\n                par.es = 0.;\n                par.a = 6370997.;\n                setup(par, proj_parm);\n            }\n\n            // Mod. Stererographics of Alaska\n            template <typename Parameters>\n            void setup_alsk(Parameters& par, par_mod_ster& proj_parm)\n            {\n                static COMPLEX\n            ABe[] = { /* Alaska ellipsoid */\n                {.9945303,    0.},\n                {.0052083,    -.0027404},\n                {.0072721,    .0048181},\n                {-.0151089,    -.1932526},\n                {.0642675,    -.1381226},\n                {.3582802,    -.2884586}},\n            ABs[] = { /* Alaska sphere */\n                {.9972523,    0.},\n                {.0052513,    -.0041175},\n                {.0074606,    .0048125},\n                {-.0153783,    -.1968253},\n                {.0636871,    -.1408027},\n                    {.3660976,    -.2937382}\n            };\n\n                proj_parm.n = 5;\n                par.lam0 = geometry::math::d2r<double>() * -152.;\n                par.phi0 = geometry::math::d2r<double>() * 64.;\n                if (par.es) { /* fixed ellipsoid/sphere */\n                    proj_parm.zcoeff = ABe;\n                    par.a = 6378206.4;\n                    par.e = sqrt(par.es = 0.00676866);\n                } else {\n                    proj_parm.zcoeff = ABs;\n                    par.a = 6370997.;\n                }\n                setup(par, proj_parm);\n            }\n\n            // Mod. Stererographics of 50 U.S.\n            template <typename Parameters>\n            void setup_gs50(Parameters& par, par_mod_ster& proj_parm)\n            {\n                static COMPLEX\n            ABe[] = { /* GS50 ellipsoid */\n                {.9827497,    0.},\n                {.0210669,    .0053804},\n                {-.1031415,    -.0571664},\n                {-.0323337,    -.0322847},\n                {.0502303,    .1211983},\n                {.0251805,    .0895678},\n                {-.0012315,    -.1416121},\n                {.0072202,    -.1317091},\n                {-.0194029,    .0759677},\n                    {-.0210072,    .0834037}\n            },\n            ABs[] = { /* GS50 sphere */\n                {.9842990,    0.},\n                {.0211642,    .0037608},\n                {-.1036018,    -.0575102},\n                {-.0329095,    -.0320119},\n                {.0499471,    .1223335},\n                {.0260460,    .0899805},\n                {.0007388,    -.1435792},\n                {.0075848,    -.1334108},\n                {-.0216473,    .0776645},\n                    {-.0225161,    .0853673}\n            };\n\n                proj_parm.n = 9;\n                par.lam0 = geometry::math::d2r<double>() * -120.;\n                par.phi0 = geometry::math::d2r<double>() * 45.;\n                if (par.es) { /* fixed ellipsoid/sphere */\n                    proj_parm.zcoeff = ABe;\n                    par.a = 6378206.4;\n                    par.e = sqrt(par.es = 0.00676866);\n                } else {\n                    proj_parm.zcoeff = ABs;\n                    par.a = 6370997.;\n                }\n                setup(par, proj_parm);\n            }\n\n        }} // namespace detail::mod_ster\n    #endif // doxygen\n\n    /*!\n        \\brief Miller Oblated Stereographic 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         - Azimuthal (mod)\n        \\par Example\n        \\image html ex_mil_os.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct mil_os_ellipsoid : public detail::mod_ster::base_mod_ster_ellipsoid<Geographic, Cartesian, Parameters>\n    {\n        inline mil_os_ellipsoid(const Parameters& par) : detail::mod_ster::base_mod_ster_ellipsoid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::mod_ster::setup_mil_os(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Lee Oblated Stereographic 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         - Azimuthal (mod)\n        \\par Example\n        \\image html ex_lee_os.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct lee_os_ellipsoid : public detail::mod_ster::base_mod_ster_ellipsoid<Geographic, Cartesian, Parameters>\n    {\n        inline lee_os_ellipsoid(const Parameters& par) : detail::mod_ster::base_mod_ster_ellipsoid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::mod_ster::setup_lee_os(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Mod. Stererographics of 48 U.S. 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         - Azimuthal (mod)\n        \\par Example\n        \\image html ex_gs48.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct gs48_ellipsoid : public detail::mod_ster::base_mod_ster_ellipsoid<Geographic, Cartesian, Parameters>\n    {\n        inline gs48_ellipsoid(const Parameters& par) : detail::mod_ster::base_mod_ster_ellipsoid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::mod_ster::setup_gs48(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Mod. Stererographics of Alaska 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         - Azimuthal (mod)\n        \\par Example\n        \\image html ex_alsk.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct alsk_ellipsoid : public detail::mod_ster::base_mod_ster_ellipsoid<Geographic, Cartesian, Parameters>\n    {\n        inline alsk_ellipsoid(const Parameters& par) : detail::mod_ster::base_mod_ster_ellipsoid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::mod_ster::setup_alsk(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Mod. Stererographics of 50 U.S. 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         - Azimuthal (mod)\n        \\par Example\n        \\image html ex_gs50.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct gs50_ellipsoid : public detail::mod_ster::base_mod_ster_ellipsoid<Geographic, Cartesian, Parameters>\n    {\n        inline gs50_ellipsoid(const Parameters& par) : detail::mod_ster::base_mod_ster_ellipsoid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::mod_ster::setup_gs50(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 mil_os_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<mil_os_ellipsoid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        class lee_os_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<lee_os_ellipsoid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        class gs48_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<gs48_ellipsoid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        class alsk_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<alsk_ellipsoid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        class gs50_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<gs50_ellipsoid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        inline void mod_ster_init(detail::base_factory<Geographic, Cartesian, Parameters>& factory)\n        {\n            factory.add_to_factory(\"mil_os\", new mil_os_entry<Geographic, Cartesian, Parameters>);\n            factory.add_to_factory(\"lee_os\", new lee_os_entry<Geographic, Cartesian, Parameters>);\n            factory.add_to_factory(\"gs48\", new gs48_entry<Geographic, Cartesian, Parameters>);\n            factory.add_to_factory(\"alsk\", new alsk_entry<Geographic, Cartesian, Parameters>);\n            factory.add_to_factory(\"gs50\", new gs50_entry<Geographic, Cartesian, Parameters>);\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n}}} // namespace boost::geometry::projections\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_MOD_STER_HPP\n\n", "meta": {"hexsha": "02daa00395d13ce83b846afa7582335c84604c66", "size": 20633, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/mod_ster.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/mod_ster.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/mod_ster.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": 41.9369918699, "max_line_length": 138, "alphanum_fraction": 0.5372461591, "num_tokens": 4742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.27157998280467}}
{"text": "#include \"kd_tree.h\"\n#include <Eigen/Eigenvalues>\n\n#ifdef __SRRG_PARALLEL_KDTREE__\n#include <omp.h>\n#endif\n\nnamespace srrg2_core {\n\n\n  template <class T, size_t D>\n  KDTree_<T, D>::TreeNode::TreeNode(KDTree_<T, D>* tree_, int node_num) :\n    _tree(tree_),\n    _node_num(node_num),\n    _node_type(KDTreeNodeType::Leaf) {\n    _mean.setZero();\n    _normal.setZero();\n    _left_child  = 0;\n    _right_child = 0;\n    _min_index   = -1;\n    _max_index   = -1;\n    _num_points  = 0;\n  }\n\n  template <class T, size_t D>\n  KDTree_<T, D>::TreeNode::TreeNode(KDTree_<T, D>* tree_,\n                       int node_num,\n                       const VectorTD& mean_,\n                       const VectorTD& normal_,\n                       TreeNode* left_child,\n                       TreeNode* right_child) :\n    _tree(tree_),\n    _node_num(node_num),\n    _node_type(KDTreeNodeType::Middle) {\n    _min_index = _max_index = -1;\n    assert(normal_.rows() == D);\n    assert(mean_.rows() == D);\n    _normal      = normal_;\n    _mean        = mean_;\n    _num_points  = 0;\n    _left_child  = left_child;\n    _right_child = right_child;\n    if (_left_child) {\n      _num_points += _left_child->_num_points;\n    }\n    if (_right_child) {\n      _num_points += _right_child->_num_points;\n    }\n  }\n\n  //! dtor\n  template <class T, size_t D>\n  KDTree_<T, D>::TreeNode::~TreeNode() {\n    if (_left_child) {\n      delete _left_child;\n      _left_child = 0;\n    }\n    if (_right_child) {\n      delete _right_child;\n      _right_child = 0;\n    }\n  }\n  \n  template <class T, size_t D>\n  void\n  KDTree_<T, D>::TreeNode::\n  findNeighbors(VectorTDVector& answers,\n                std::vector<int>& indices,\n                const VectorTD& query,\n                const T maximum_distance,\n                KDTreeSearchType search_type) const {\n    assert(maximum_distance >= 0);\n    const T maximum_squared_distance=pow(maximum_distance,2);\n    switch (_node_type) {\n    case KDTreeNodeType::Leaf: {\n      // ds return all points in this leaf that satisfy the distance\n      assert(_max_index >= _min_index);\n      const size_t number_of_points = _max_index - _min_index;\n      size_t s=answers.size();\n      answers.reserve(s+number_of_points);\n      indices.reserve(s+number_of_points);\n      int k=0;\n      for (size_t i = _min_index; i < _max_index; ++i) {\n        assert(i < _tree->_points.size());\n        const T squared_distance = (_tree->_points[i] - query).squaredNorm();\n        if (squared_distance < maximum_squared_distance) {\n          answers.emplace_back(_tree->_points[i]);\n          indices.emplace_back(_tree->_indices[i]);\n          ++k;\n        }\n      }\n      //std::cerr << k << \"/\" << number_of_points << \"/\" << indices.size() << \" \" ;\n      return;\n    }\n      \n\n    case KDTreeNodeType::Middle: {\n      T plane_distance = planeDistance(query);\n      //std:: cerr << \" - {\" << plane_distance << \"} \";\n      if (search_type==Complete) {\n        //std::cerr <<\"2(\";\n        //std::cerr << \"answers_size (before): \" << answers.size() ;\n        //std::cerr << \"l(\";\n        _left_child->findNeighbors(answers, indices, query, maximum_distance, search_type);\n        //std::cerr << \"answers_size (left): \" << answers.size() << std::endl;\n        //std::cerr << \")r(\";\n        _right_child->findNeighbors(answers, indices, query, maximum_distance, search_type);\n        //std::cerr << \"answers_size (right): \" << answers.size() << std::endl;\n        //std::cerr <<\"))\";\n      } else if (plane_distance < 0) {\n        //std::cerr << \"l(\";\n        _left_child->findNeighbors(answers, indices, query, maximum_distance, search_type);\n        //std::cerr << \")\";\n      } else {\n        //std::cerr << \"r(\";\n        _right_child->findNeighbors(answers, indices, query, maximum_distance, search_type);\n        //std::cerr << \")\";\n      }\n      return;\n    }\n    default:\n      std::cerr << \"KDTree::findNeighbors|ERROR, sanity check (\" << _tree\n                << \") : \" << _tree->sanityCheck() << std::endl;\n      throw std::runtime_error(\"KDTree::findNeighbors|ERROR, unknown node type\");\n    }\n  }\n\n  template <class T, size_t D>\n  KDTree_<T, D>::KDTree_(const VectorTDVector& points_, T max_leaf_range, size_t min_leaf_points) {\n      good_queries = 0;\n      _num_nodes   = 0;\n      _points      = points_;\n      _aux_points  = points_;\n      _indices.resize(points_.size());\n      _aux_indices.resize(points_.size());\n      _min_leaf_points = min_leaf_points;\n      for (size_t i = 0; i < _indices.size(); ++i) {\n        _indices[i] = i;\n      }\n      _root = _buildTree(0, points_.size(), max_leaf_range, 0);\n    }\n\n    //! dtor\n  template <class T, size_t D>\n  KDTree_<T, D>::~KDTree_() {\n      if (_root) {\n        delete _root;\n      }\n      _root = 0;\n    }\n\n  template <class T, size_t D>\n  bool KDTree_<T, D>::sanityCheck() const {\n    std::vector<int> checked_indices(_points.size());\n    std::fill(checked_indices.begin(), checked_indices.end(), -1);\n    const size_t k = sanityCheck(checked_indices, 0, _root);\n    if (k != _points.size()) {\n      throw std::runtime_error(\"KDTree::sanityCheck(void)|ERROR, illegal size reported\");\n    }\n    std::sort(checked_indices.begin(), checked_indices.end(), std::less<int>());\n    for (size_t i = 0; i < checked_indices.size(); i++) {\n      if (i != static_cast<size_t>(checked_indices[i])) {\n        throw std::runtime_error(\"KDTree::sanityCheck(void)|ERROR, missing indices\");\n        }\n    }\n    return true;\n  }\n\n  template <class T, size_t D>\n  int KDTree_<T, D>::sanityCheck(std::vector<int>& checked_indices, int k, const TreeNode* node) const {\n    if (!node) {\n      return k;\n    }\n    switch (node->_node_type) {\n    case KDTreeNodeType::Leaf:\n      for (size_t i = node->_min_index; i < node->_max_index; i++) {\n        int idx = _indices[i];\n        if (checked_indices[k] != -1) {\n          throw std::runtime_error(\"KDTree::sanityCheck|ERROR, writing on an occupied index\");\n        }\n        checked_indices[k] = idx;\n        k++;\n      }\n      return k;\n    case KDTreeNodeType::Middle:\n      k = sanityCheck(checked_indices, k, node->_left_child);\n      k = sanityCheck(checked_indices, k, node->_right_child);\n      return k;\n    default:\n      throw std::runtime_error(\"KDTree::sanityCheck|ERROR, illegal type index\");\n    }\n  }\n\n\n  template <class T, size_t D>\n  void KDTree_<T, D>::findNeighbors(VectorTDVector& answers,\n                     std::vector<int>& indices,\n                     const KDTree_<T, D>::VectorTD& query,\n                     const T max_distance,\n                     KDTreeSearchType search_type) const {\n    if (!_root) {\n      throw std::runtime_error(\"KDTree::findNeighbors|ERROR, no root node\");\n    }\n    answers.clear();\n    indices.clear();\n    good_queries++;\n    _root->findNeighbors(answers, indices, query, max_distance, search_type);\n    //std::cerr << \"indices.size: \" << indices.size() << std::endl;\n  }\n\n\n  template <class T, size_t D>\n  T KDTree_<T, D>::findNeighbor(VectorTD& answer,\n                                int& index,\n                                const VectorTD& query,\n                                const T max_distance,\n                                const KDTreeSearchType search_type) const {\n    if (!_root) {\n      throw std::runtime_error(\"KDTree::findNeighbors|ERROR, no root node\");\n    }\n    index=-1;\n    \n    // approx search, we take the quick path unrolling tail recursion\n    T max_distance2 = pow(max_distance, 2);\n    if (search_type==Approximate) {\n      TreeNode* current=_root;\n      while(! current->_node_type==Leaf) {\n        assert(current->_node_type==Middle && \"node is not middle\");\n        T plane_distance = current->planeDistance(query);\n        if(plane_distance<0) {\n          current=current->_left_child;\n        } else {\n          current=current->_right_child;\n        }\n      }\n      assert(current->_node_type==Leaf && \"node is leaf\");\n      assert(current->_max_index >= current->_min_index);\n      T best_distance=std::numeric_limits<T>::max();\n      for (size_t i = current->_min_index; i < current->_max_index; ++i) {\n        const T squared_distance = (_points[i] - query).squaredNorm();\n        if (squared_distance < best_distance && squared_distance < max_distance2) {\n          best_distance=squared_distance;\n          answer=_points[i];\n          index=_indices[i];\n        }\n      }\n      return best_distance;\n    }\n\n    //exact search, we need a buffer\n    VectorTDVector answers;\n    std::vector<int> indices;\n    _root->findNeighbors(answers, indices, query, max_distance, search_type);\n    T best_distance=std::numeric_limits<T>::max();\n    for (size_t i=0; i<answers.size(); ++i) {\n      T current_distance = (query-answers[i]).squaredNorm();\n      if (current_distance<max_distance) {\n        answer=answers[i];\n        index=indices[i];\n      }\n    }\n    return best_distance;\n  }\n      \n  template <class T, size_t D>\n  T KDTree_<T, D>::_splitPoints(KDTree_<T, D>::VectorTD& mean,\n                               KDTree_<T, D>::VectorTD& normal,\n                               size_t& num_left_points,\n                               const size_t min_index,\n                               const size_t max_index) {\n    // if points empty, nothing to do\n    if (min_index == max_index) {\n      return 0;\n    }\n\n    const size_t num_points            = max_index - min_index;\n    const T inverse_num_points         = 1.0 / num_points;\n    VectorTD sum                       = VectorTD::Zero();\n    Eigen::Matrix<T, D, D> squared_sum = Eigen::Matrix<T, D, D>::Zero();\n    Eigen::Matrix<T, D, D> covariance  = Eigen::Matrix<T, D, D>::Zero();\n    for (size_t i = min_index; i < max_index; ++i) {\n      sum += _points[i];\n      squared_sum += _points[i] * _points[i].transpose();\n    }\n    mean       = sum * inverse_num_points;\n    covariance = squared_sum * inverse_num_points - mean * mean.transpose();\n\n    // eigenvalue decomposition\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix<T, D, D>> solver;\n    solver.compute(covariance, Eigen::ComputeEigenvectors);\n    normal = solver.eigenvectors().col(D - 1).normalized();\n\n    // the following var will contain the range of points along the normal\n    // vector\n    T max_distance_from_plane = 0;\n\n    // run through the points and split them in the left or the right set\n    size_t left_index  = min_index;\n    size_t right_index = max_index;\n\n    size_t num_left  = 0;\n    size_t num_right = 0;\n    for (size_t i = min_index; i < max_index; ++i) {\n      T distance_from_plane = normal.dot(_points[i] - mean);\n      if (fabs(distance_from_plane) > max_distance_from_plane) {\n        max_distance_from_plane = fabs(distance_from_plane);\n      }\n\n      bool side = distance_from_plane < 0;\n      if (side) {\n        _aux_points[left_index]  = _points[i];\n        _aux_indices[left_index] = _indices[i];\n        left_index++;\n        num_left++;\n      } else {\n        right_index--;\n        _aux_points[right_index]  = _points[i];\n        _aux_indices[right_index] = _indices[i];\n        num_right++;\n      }\n    }\n    assert(max_index - min_index == num_right + num_left);\n    for (size_t i = min_index; i < max_index; ++i) {\n      _points[i]  = _aux_points[i];\n      _indices[i] = _aux_indices[i];\n    }\n\n    num_left_points = num_left;\n    return max_distance_from_plane;\n  }\n\n  template <class T, size_t D>\n    typename KDTree_<T, D>::TreeNode*\n    KDTree_<T, D>::_buildTree(const size_t min_index, const size_t max_index, const T max_leaf_range, int level) {\n      const size_t num_points = max_index - min_index;\n      if (!num_points) {\n        return 0;\n      }\n\n\n      VectorTD mean;\n      VectorTD normal;\n      size_t num_left_points = 0;\n\n      const T range = _splitPoints(mean, normal, num_left_points, min_index, max_index);\n      assert(range >= 0);\n      TreeNode* node = 0;\n      if (range < max_leaf_range || num_points < _min_leaf_points) {\n        node = new TreeNode(this, _num_nodes);\n        node->_min_index=min_index;\n        node->_max_index=max_index;\n        node->_num_points = num_points;\n        //std::cerr << \"leaf: \" << num_points << std::endl;\n      } else {\n        TreeNode *left_tree, *right_tree;\n\n#ifdef __SRRG_PARALLEL_KDTREE__\n        int num_threads = omp_get_max_threads();\n        int split_level = -1;\n        if (level > 0)\n          split_level = floor(log(num_threads) / log(2));\n\n        if (split_level == level) {\n#pragma omp parallel sections\n          {\n#pragma omp section\n            {\n              left_tree =\n                _buildTree(min_index, min_index + num_left_points, max_leaf_range, level + 1);\n            }\n#pragma omp section\n            {\n              right_tree =\n                _buildTree(min_index + num_left_points, max_index, max_leaf_range, level + 1);\n            }\n          }\n        } else {\n#endif //__SRRG_PARALLEL_KDTREE__\n\n          left_tree = _buildTree(min_index, min_index + num_left_points, max_leaf_range, level + 1);\n          right_tree =\n            _buildTree(min_index + num_left_points, max_index, max_leaf_range, level + 1);\n#ifdef __SRRG_PARALLEL_KDTREE__\n        }\n#endif\n        node = new TreeNode(this, _num_nodes, mean, normal, left_tree, right_tree);\n      }\n      _num_nodes++;\n      return node;\n    }\n\n  template <class T, size_t D>\n  void KDTree_<T, D>::_printKDTree(TreeNode* node) {\n    std::cerr << \"(\";\n    switch (node->_node_type) {\n    case Leaf:\n      std::cerr << node->_max_index - node->_min_index;\n      // for (size_t i = node->_min_index; i < node->_max_index; ++i) {\n      //   std::cerr << _points[i].transpose() << std::endl;\n      // }\n      break;\n    case Middle:\n      _printKDTree(node->_left_child);\n      _printKDTree(node->_right_child);\n      break;\n    }\n    std::cerr << \")\";\n\n  }\n\n} // namespace srrg2_core\n", "meta": {"hexsha": "77de0276502b6fdd71b589f948bc0bf232d11988", "size": 13766, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/srrg2_core/srrg2_core/src/srrg_data_structures/kd_tree_impl.cpp", "max_stars_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_stars_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-03-11T14:36:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T09:01:15.000Z", "max_issues_repo_path": "catkin_ws/src/srrg2_core/srrg2_core/src/srrg_data_structures/kd_tree_impl.cpp", "max_issues_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_issues_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-07T17:25:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-15T07:36:10.000Z", "max_forks_repo_path": "catkin_ws/src/srrg2_core/srrg2_core/src/srrg_data_structures/kd_tree_impl.cpp", "max_forks_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_forks_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-30T08:17:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-19T05:07:07.000Z", "avg_line_length": 33.4126213592, "max_line_length": 114, "alphanum_fraction": 0.5892779311, "num_tokens": 3542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2715799769291319}}
{"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/////////////////// Below are private member functions /////////////////\n\nvoid Approximation::prior_allocate_memory()\n{\n    //Allocate memory for RChol\n    RChol = new mat [partition->nRegionsInTotal];\n\n    //Allocate memory for wTilde (first dimension: partition.nKnots, second dimesnion: partition.nLvs-1)\n    wTilde = new mat [partition->nRegionsInTotal];\n\n    //Allocate memory for ATilde (first dimension: partition.nKnots, second dimesnion: partition.nKnots, third dimension or the number of slices: (partition.nLvs-1)*partition.nLvs/2)\n    ATilde = new cube [partition->nRegionsInTotal];\n    \n    //Assign paramter values if predicting\n    if(CALCULATION_MODE == \"prediction\")\n    {\n        posteriorPredictionMean = new vec [partition->nRegionsAtEachLevel[NUM_LEVELS_M-1]];\n        posteriorPredictionVariance = new vec [partition->nRegionsAtEachLevel[NUM_LEVELS_M-1]];\n        BTilde = new double** [partition->nRegionsAtEachLevel[NUM_LEVELS_M-1]];\n    }\n}\n\nvoid Approximation::get_all_ancestors(unsigned long* ancestorArray, unsigned long currentRegion, const unsigned long &nAncestors)\n{\n    for(unsigned long iAncestor = 0; iAncestor < nAncestors; iAncestor++)\n    {\n        currentRegion = (currentRegion-1)/NUM_PARTITIONS_J;\n        ancestorArray[nAncestors-iAncestor-1] = currentRegion;\n    }\n}\n\n//Update: Changed the column-row for KcW and covariance matrix. Need to modify prediction routines accordingly\nvoid Approximation::get_conditional_covariance_matrix(const int &ancestorLevel, double **ancestorNow, double **ancestorBefore, double* nowBefore, const int &numKnotsNow, const int &numKnotsBefore, const int &numKnotsAncestor)\n{\n    for(int iLevel = 0; iLevel < ancestorLevel; iLevel++)\n        cblas_dgemm(CblasColMajor,CblasTrans,CblasNoTrans,numKnotsBefore,numKnotsNow,numKnotsAncestor,-1.0,ancestorBefore[iLevel],numKnotsAncestor,ancestorNow[iLevel],numKnotsAncestor,1.0,nowBefore,numKnotsBefore);\n}\n\nvoid Approximation::get_wTilde_and_ATilde_in_prior(const int &nKnots, const int &currentLevel, const unsigned long &iRegion, vec *Sicy, mat **SicB)\n{\n    cube* ATildeCurrent;\n\n    if(SAVE_TO_DISK_FLAG)\n    {\n        ATildeCurrent = new cube;\n        (*ATildeCurrent).set_size(nKnots,nKnots,(NUM_LEVELS_M-1)*NUM_LEVELS_M/2);\n    }\n\n    unsigned long count = 0;\n    for(int jLevel = 0; jLevel < currentLevel; jLevel++)\n    {\n        mat tmp = (*SicB[jLevel]).t();\n        wTilde[iRegion].unsafe_col(jLevel) = tmp*(*Sicy);\n        for(int kLevelAfterjLevel = jLevel; kLevelAfterjLevel < currentLevel; kLevelAfterjLevel++)\n        {\n            if(SAVE_TO_DISK_FLAG)\n                (*ATildeCurrent).slice(count++) = tmp*(*SicB[kLevelAfterjLevel]);\n            else\n                ATilde[iRegion].slice(count++) = tmp*(*SicB[kLevelAfterjLevel]);\n        }\n    }\n\n    if(SAVE_TO_DISK_FLAG)\n    {\n        std::string fileName=TMP_DIRECTORY+\"/\"+std::to_string(iRegion)+\".bin\";\n        ATildeCurrent->save(fileName,arma_binary);\n        delete ATildeCurrent;\n    }\n}\n\nvoid Approximation::loop_regions_before_finest_level_in_prior(double ***KCholTimesw)\n{\n    int maxOpenMPThreads=omp_get_max_threads();\n\n    unsigned long **ancestorArray = new unsigned long* [maxOpenMPThreads];\n    for(int i = 0; i < maxOpenMPThreads; i++) ancestorArray[i] = new unsigned long [NUM_LEVELS_M-2];\n    \n    //Allocate memory for the current region of KCholTimesw\n    for(int currentLevel = 0; currentLevel < NUM_LEVELS_M-1; currentLevel++)\n    {\n        for(unsigned long iRegion = REGION_START[currentLevel]; iRegion < REGION_END[currentLevel] + 1; iRegion++)\n        {\n            KCholTimesw[iRegion] = new double* [currentLevel];\n            for(int jLevel = 0; jLevel < currentLevel; jLevel++)\n                KCholTimesw[iRegion][jLevel]= new double [partition->nKnots*partition->nKnots];\n\n            RChol[iRegion].set_size(partition->nKnots,partition->nKnots);\n        }\n    }\n\n    //Auxilliary variables for matrix computations\n    char L='L', N='N';\n    int nKnots = partition->nKnots;\n\n    for(int currentLevel = 0; currentLevel < NUM_LEVELS_M-1; currentLevel++)\n    {\n        #pragma omp parallel for num_threads(maxOpenMPThreads) schedule(dynamic,1)\n        for(unsigned long iRegion = REGION_START[currentLevel]; iRegion < REGION_END[currentLevel] + 1; iRegion++)\n        {\n            int rankOpenMP = omp_get_thread_num();\n            int status;\n            //Find the indices of all the ancestors\n\n            get_all_ancestors(ancestorArray[rankOpenMP], iRegion, currentLevel);\n\n            //Loop for all ancestors to get the conditional cross-covariance matrix\n            for(int jLevel = 0; jLevel < currentLevel; jLevel++)\n            {\n                evaluate_cross_covariance(KCholTimesw[iRegion][jLevel], partition->knotsX[iRegion], partition->knotsY[iRegion], partition->knotsX[ancestorArray[rankOpenMP][jLevel]], partition->knotsY[ancestorArray[rankOpenMP][jLevel]], partition->nKnots, partition->nKnots, sill, range, nugget);\n\n                get_conditional_covariance_matrix(jLevel, KCholTimesw[iRegion], KCholTimesw[ancestorArray[rankOpenMP][jLevel]],KCholTimesw[iRegion][jLevel],nKnots,nKnots,nKnots);\n                \n                dtrtrs_(&L,&N,&N,&nKnots,&nKnots,(RChol[ancestorArray[rankOpenMP][jLevel]]).memptr(),&nKnots,KCholTimesw[iRegion][jLevel],&nKnots,&status);\n            }\n\n            //Get the conditional variance-covariance matrix of this region\n            evaluate_variance_covariance(RChol[iRegion].memptr(), partition->knotsX[iRegion], partition->knotsY[iRegion], partition->nKnots, sill, range, nugget);\n\n            get_conditional_covariance_matrix(currentLevel, KCholTimesw[iRegion], KCholTimesw[iRegion], RChol[iRegion].memptr(),nKnots,nKnots,nKnots);\n\n            //dpotrf_(&L,&nKnots,(RChol[iRegion]).memptr(),&nKnots,&status);  \n            RChol[iRegion] = chol(RChol[iRegion],\"lower\");\n\n        }\n\n        timeval timeNow;\n        gettimeofday(&timeNow, NULL);\n\n        if(WORKER == 0) cout<<\"Prior: Level \"<<currentLevel+1<<\" 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    for(int i = 0; i < maxOpenMPThreads; i++) delete[] ancestorArray[i];\n    delete[] ancestorArray; ancestorArray = NULL;\n}\n\ntemplate<typename T> void Approximation::receive(T &object, double *tempMemory, int tag, unsigned long iRegion)\n{\n    std::set<unsigned long>::iterator workerToReceive = WORKERS_FOR_EACH_REGION[iRegion].begin();\n    for(workerToReceive++; workerToReceive != WORKERS_FOR_EACH_REGION[iRegion].end(); workerToReceive++)\n    {   \n        MPI_Recv(tempMemory,object.size(),MPI_DOUBLE,*workerToReceive,tag,WORLD,MPI_STATUS_IGNORE);\n        for(unsigned long i = 0; i < object.size(); i++) object[i] += tempMemory[i];\n    }\n}\n\ntemplate<typename T> void Approximation::send(const T &object, int tag, unsigned long iRegion)\n{\n    MPI_Send(object.memptr(),object.size(),MPI_DOUBLE,*WORKERS_FOR_EACH_REGION[iRegion].begin(),tag,WORLD);\n}\n\nvoid Approximation::aggregate_A(mat &A, double *tempMemory, const unsigned long &indexA, const unsigned long &indexStart, const unsigned long &indexEnd, unsigned long iRegion, bool &supervisor, bool &synchronizeFlag)\n{\n    bool firstChild = true;\n\n    for(unsigned long jChild = indexStart; jChild < indexEnd + 1; jChild++)\n    {\n        if( !WORKING_REGION_FLAG[jChild] ) \n        {\n            synchronizeFlag = true;\n            continue;\n        }\n        if(firstChild)\n        {\n            A = ATilde[jChild].slice(indexA);\n            firstChild = false;\n        }\n        else\n            A += ATilde[jChild].slice(indexA);\n    }\n\n    if(synchronizeFlag)\n    {\n        supervisor = WORKER == *WORKERS_FOR_EACH_REGION[iRegion].begin();\n        //Check whether this worker is the master worker\n        if(supervisor)\n        {\n            //Supervisor, to receive\n            receive<mat>(A, tempMemory, MPI_TAG_MAT, iRegion);\n        }\n        else\n        {\n            //Not supervisor, to send\n            send<mat>(A, MPI_TAG_MAT, iRegion);\n        }\n    }\n}\n\nvoid Approximation::aggregate_w_and_A(vec &w, mat &A, double *tempMemory, const int &jLevel, const unsigned long &indexA, const unsigned long &indexStart, const unsigned long &indexEnd, unsigned long iRegion, bool &supervisor, bool &synchronizeFlag)\n{\n    bool firstChild = true;\n    for(unsigned long jChild = indexStart; jChild < indexEnd+1; jChild++)\n    {\n        if( !WORKING_REGION_FLAG[jChild] ) \n        {\n            synchronizeFlag = true;\n            continue;\n        }\n        if(firstChild)\n        {\n            w = wTilde[jChild].unsafe_col(jLevel);\n            A = ATilde[jChild].slice(indexA);\n            firstChild = false;\n        }\n        else\n        {\n            w += wTilde[jChild].unsafe_col(jLevel);\n            A += ATilde[jChild].slice(indexA);\n        }\n    }\n\n    if(synchronizeFlag)\n    {\n        //Check whether this worker is the supervisor\n        supervisor = WORKER == *WORKERS_FOR_EACH_REGION[iRegion].begin();\n        \n        if(supervisor)\n        {\n            //Supervisor, to receive\n            receive<vec>(w, tempMemory, MPI_TAG_VEC, iRegion);\n            receive<mat>(A, tempMemory,  MPI_TAG_MAT, iRegion);\n        }\n        else\n        {\n            //Not supervisor, to send\n            send<vec>(w, MPI_TAG_VEC, iRegion);\n            send<mat>(A, MPI_TAG_MAT, iRegion);\n        }\n    }\n}\n\nvoid Approximation::get_wTilde_and_ATilde_in_posterior(vec &w, mat &A, double *tempMemory, const unsigned long &nKnots, cube &KCholTimesCurrentA, const vec &KCholTimesCurrentw, const unsigned long &iRegion, const int &currentLevel, bool &supervisor, bool &synchronizeFlag)\n{\n    if(currentLevel == 0) return;\n\n    wTilde[iRegion].set_size(nKnots,currentLevel);\n    ATilde[iRegion].set_size(nKnots,nKnots,(currentLevel+1)*currentLevel/2);\n\n    unsigned long indexAChild = (currentLevel+1)*(currentLevel+2)/2-1;\n    unsigned long indexACurrent = currentLevel*(currentLevel+1)/2;\n    for(long jLevel = currentLevel-1; jLevel > -1; jLevel--)\n    {\n        aggregate_w_and_A(w, A, tempMemory, jLevel, --indexAChild, iRegion*NUM_PARTITIONS_J+1, iRegion*NUM_PARTITIONS_J+NUM_PARTITIONS_J, iRegion, supervisor, synchronizeFlag);\n\n        if(supervisor)\n        {\n            KCholTimesCurrentA.slice(jLevel) = solve(trimatl(RChol[iRegion]),A.t());\n            \n            wTilde[iRegion].unsafe_col(jLevel) = w-KCholTimesCurrentA.slice(jLevel).t()*KCholTimesCurrentw;\n        }\n\n        for(long kLevelAfterjLevel = currentLevel-1; kLevelAfterjLevel > jLevel-1; kLevelAfterjLevel--)\n        {\n            aggregate_A(A, tempMemory, --indexAChild, iRegion*NUM_PARTITIONS_J+1, iRegion*NUM_PARTITIONS_J+NUM_PARTITIONS_J, iRegion, supervisor, synchronizeFlag);\n\n            if(supervisor)\n                ATilde[iRegion].slice(--indexACurrent) = A-KCholTimesCurrentA.slice(jLevel).t()*KCholTimesCurrentA.slice(kLevelAfterjLevel);\n        }\n    }\n}\n\nvoid Approximation::synchronizeIndicesRegionsForEachWorker()\n{\n    //Get the working region indices of this worker at the current level\n    INDICES_REGIONS_AT_ONE_LEVEL_BELOW = INDICES_REGIONS_AT_CURRENT_LEVEL;\n    INDICES_REGIONS_AT_CURRENT_LEVEL.clear();\n    for(std::set<unsigned long>::iterator child = INDICES_REGIONS_AT_ONE_LEVEL_BELOW.begin(); child != INDICES_REGIONS_AT_ONE_LEVEL_BELOW.end(); child++)\n    {   \n        unsigned long ancestor = (*child-1)/NUM_PARTITIONS_J;\n        INDICES_REGIONS_AT_CURRENT_LEVEL.insert(ancestor);\n        WORKING_REGION_FLAG[ancestor] = true;\n    }\n    \n    if(INDICES_REGIONS_AT_CURRENT_LEVEL.size() > (unsigned long)INT_MAX)\n    {\n        cout<<\"Program exits with an error: too many levels. It is required that the number of regions at the third finest level is smaller than the maximum value of type \\\"int\\\" \"<<INT_MAX<<endl;\n        exit(EXIT_FAILURE);\n    }\n\n    int *numWorkingRegionsEachWorker = new int [MPI_SIZE];\n    int numWorkingRegionsThisWorker = INDICES_REGIONS_AT_CURRENT_LEVEL.size();\n\n    unsigned long *indicesWorkingRegionsThisWorker = new unsigned long [numWorkingRegionsThisWorker];\n    std::set<unsigned long>::iterator iter = INDICES_REGIONS_AT_CURRENT_LEVEL.begin();\n    for(int i = 0; i < numWorkingRegionsThisWorker; i++)\n    {\n        indicesWorkingRegionsThisWorker[i] = *iter;\n        iter++;\n    }\n\n    //Synchronize the number of working regions of each worker\n    MPI_Allgather(&numWorkingRegionsThisWorker,1,MPI_INT,numWorkingRegionsEachWorker,1,MPI_INT,WORLD);\n\n    //Get the max number of working regions among all workers\n    int maxNumWorkingRegionsEachWorker = 0;\n    for(int i = 0; i < MPI_SIZE; i++) \n        if (maxNumWorkingRegionsEachWorker < numWorkingRegionsEachWorker[i]) maxNumWorkingRegionsEachWorker = numWorkingRegionsEachWorker[i];\n\n    //Synchronize the working region indices of each worker\n    unsigned long *indicesWorkingRegionsEachWorker = new unsigned long [(unsigned long)MPI_SIZE*maxNumWorkingRegionsEachWorker];\n    int *offset = new int [MPI_SIZE];\n    offset[0] = 0;\n    for(int i = 1; i < MPI_SIZE; i++) \n        offset[i] = offset [i-1] + maxNumWorkingRegionsEachWorker;\n\n    MPI_Allgatherv(indicesWorkingRegionsThisWorker,numWorkingRegionsThisWorker,MPI_UNSIGNED_LONG,indicesWorkingRegionsEachWorker,numWorkingRegionsEachWorker,offset,MPI_UNSIGNED_LONG,WORLD);\n\n    //Update WORKERS_FOR_EACH_REGION\n    for(int iWorker = 0; iWorker < MPI_SIZE; iWorker++)\n        for(int jIndex = offset[iWorker]; jIndex < offset[iWorker]+numWorkingRegionsEachWorker[iWorker]; jIndex++)\n            WORKERS_FOR_EACH_REGION[indicesWorkingRegionsEachWorker[jIndex]].insert(iWorker);\n\n    delete[] offset; offset = NULL;\n    delete[] indicesWorkingRegionsEachWorker; indicesWorkingRegionsEachWorker = NULL;\n    delete[] indicesWorkingRegionsThisWorker; indicesWorkingRegionsThisWorker = NULL;\n    delete[] numWorkingRegionsEachWorker; numWorkingRegionsEachWorker = NULL;\n}\n\nvoid Approximation::free_wTilde_and_ATilde(const unsigned long &indexStartFreeingATilde, const unsigned long &indexEndFreeingATilde)\n{\n    //#pragma omp parallel for\n    for(unsigned long i = indexStartFreeingATilde; i < indexEndFreeingATilde + 1; i++)\n    {\n        if( !WORKING_REGION_FLAG[i] ) continue;\n        ATilde[i].reset();\n        wTilde[i].reset();\n    }\n}\n\nvoid Approximation::load_ATilde_from_disk(const unsigned long &indexChildrenStart, const unsigned long &indexChildrenEnd, bool secondLastLevel, unsigned long* nKnotsAtFinestLevel, unsigned long offset, unsigned long size1, unsigned long size2)\n{\n    for(unsigned long i = indexChildrenStart; i < indexChildrenEnd + 1; i++)\n    {\n        if( !WORKING_REGION_FLAG[i] ) continue;\n        if( secondLastLevel && nKnotsAtFinestLevel[i-offset]==0) \n        {\n            ATilde[i].set_size(size1,size1,size2);\n            ATilde[i].zeros();\n            continue;\n        }\n        std::string fileName=TMP_DIRECTORY+\"/\"+std::to_string(i)+\".bin\";\n        ATilde[i].load(fileName,arma_binary);\n    }\n}\n\n/////////////////// Above are private member functions /////////////////\n\n/////////////////// Below are public member functions /////////////////\n\nApproximation::Approximation(const double &sill, const double &range, const double &nugget)\n{\n    (*this).sill=sill;\n    (*this).range=range;\n    (*this).nugget=nugget;\n    loglikelihood = 0;\n}\n\nvoid Approximation::create_prior()\n{\n    if(WORKER == 0)\n    {\n        gettimeofday(&timeNow, NULL);\n        cout<<\"===========================> Processor 1: calculating prior quantities 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\n    prior_allocate_memory();\n\n    //Allocate memory for temporary variables storing K^{1/2}*W\n    double ***KCholTimesw = new double** [partition->nRegionsInTotal];\n\n    //Loop each region before the finest level\n    loop_regions_before_finest_level_in_prior(KCholTimesw);\n    \n    //Loop each region in the finest level\n    loop_regions_at_finest_level_in_prior(KCholTimesw);\n    \n    timeval timeNow;\n    gettimeofday(&timeNow, NULL);\n\n    if(WORKER == 0) cout<<\"Prior: Level \"<<NUM_LEVELS_M<<\" 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    for(int currentLevel = 0; currentLevel < NUM_LEVELS_M-1; currentLevel++)\n    {\n        for(unsigned long iRegion = REGION_START[currentLevel]; iRegion < REGION_END[currentLevel] + 1; iRegion++)\n        {\n            for(int jLevel = 0; jLevel < currentLevel; jLevel++)\n                delete[] KCholTimesw[iRegion][jLevel];\n            delete[] KCholTimesw[iRegion];\n        }\n    }\n\n    if(CALCULATION_MODE==\"prediction\")\n    {\n        for(unsigned long iRegion = REGION_START[NUM_LEVELS_M-1]; iRegion < REGION_END[NUM_LEVELS_M-1] + 1; iRegion++)\n        {\n            if(partition->nKnotsAtFinestLevel[iRegion-partition->nRegionsInTotal+partition->nRegionsAtEachLevel[NUM_LEVELS_M-1]] == 0) continue;\n\n            for(int jLevel = 0; jLevel < NUM_LEVELS_M - 1; jLevel++)\n                delete[] KCholTimesw[iRegion][jLevel];\n            delete[] KCholTimesw[iRegion];\n        }\n    }\n\n    delete [] KCholTimesw; KCholTimesw=NULL;\n\n    if(WORKER == 0)\n    {\n        gettimeofday(&timeNow, NULL);\n        cout<<\"===========================> Processor 1: calculating prior quantities 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\n\nvoid Approximation::likelihood()\n{\n\tcreate_prior();\n\tposterior_inference();\n}\n\n\nvoid Approximation::dump_prediction_result()\n{\n    if(WORKER == 0)\n    {\n        gettimeofday(&timeNow, NULL);\n        cout<<\"===========================> Processor 1: dumping prediction results 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\t\n    std::ofstream file;\n    char fileNameThisWorker[255];\n    if(MPI_SIZE>1)\n        sprintf(fileNameThisWorker,\"%s%d\",PREDICTION_RESULTS_FILE_NAME.c_str(),WORKER);\n    else\n        sprintf(fileNameThisWorker,\"%s\",PREDICTION_RESULTS_FILE_NAME.c_str());\n\n    file.open(fileNameThisWorker, ios::binary);\n\n    unsigned long offset = partition->nRegionsAtEachLevel[NUM_LEVELS_M-1]-partition->nRegionsInTotal;\n    if(file.is_open())\n    {\n        //Write the number of prediction locations\n        unsigned long n = 0;\n        for(unsigned long indexRegionAtThisLevel = REGION_START[NUM_LEVELS_M-1]+offset; indexRegionAtThisLevel < REGION_END[NUM_LEVELS_M-1]+1+offset; indexRegionAtThisLevel++)\n            n += partition->nPredictionsAtFinestLevel[indexRegionAtThisLevel];\n        file.write((char*)&n,sizeof(unsigned long));\n        \n        //Write the prediction longtitude\n        for(unsigned long indexRegionAtThisLevel = REGION_START[NUM_LEVELS_M-1]+offset; indexRegionAtThisLevel < REGION_END[NUM_LEVELS_M-1]+1+offset; indexRegionAtThisLevel++)\n        {\n            if(partition->nPredictionsAtFinestLevel[indexRegionAtThisLevel]==0) continue;\n            file.write((char*)partition->predictionX[indexRegionAtThisLevel],sizeof(double)*partition->nPredictionsAtFinestLevel[indexRegionAtThisLevel]);\n        }\n\n        //Write the prediction lattitude\n        for(unsigned long indexRegionAtThisLevel = REGION_START[NUM_LEVELS_M-1]+offset; indexRegionAtThisLevel < REGION_END[NUM_LEVELS_M-1]+1+offset; indexRegionAtThisLevel++)\n        {\n            if(partition->nPredictionsAtFinestLevel[indexRegionAtThisLevel]==0) continue;\n            file.write((char*)partition->predictionY[indexRegionAtThisLevel],sizeof(double)*partition->nPredictionsAtFinestLevel[indexRegionAtThisLevel]);\n        }\n\n        //Write the prediction mean\n        for(unsigned long indexRegionAtThisLevel = REGION_START[NUM_LEVELS_M-1]+offset; indexRegionAtThisLevel < REGION_END[NUM_LEVELS_M-1]+1+offset; indexRegionAtThisLevel++)\n            for(unsigned long jPrediction = 0; jPrediction < partition->nPredictionsAtFinestLevel[indexRegionAtThisLevel]; jPrediction++)\n            {\n                vec designVec(3);\n                designVec[1] = partition->predictionX[indexRegionAtThisLevel][jPrediction];\n                designVec[2] = partition->predictionY[indexRegionAtThisLevel][jPrediction];\n                designVec[0] = 1.0;\n                double mean = posteriorPredictionMean[indexRegionAtThisLevel][jPrediction]+dot(designVec,data->coefficients);\n                file.write((char*)&mean,sizeof(double));\n            }\n        \n        //Write the prediction variance\n        for(unsigned long indexRegionAtThisLevel = REGION_START[NUM_LEVELS_M-1]+offset; indexRegionAtThisLevel < REGION_END[NUM_LEVELS_M-1]+1+offset; indexRegionAtThisLevel++)\n            for(unsigned long jPrediction = 0; jPrediction < partition->nPredictionsAtFinestLevel[indexRegionAtThisLevel]; jPrediction++)\n                file.write((char*)&posteriorPredictionVariance[indexRegionAtThisLevel][jPrediction],sizeof(double));\n        \n        //Close the data file\n        file.close();\n    }else \n    {\n        cout<<\"Program exits with an error: fail to open the output file \"<<PREDICTION_RESULTS_FILE_NAME<<endl;\n        exit(EXIT_FAILURE);\n    }\n\n    if(WORKER == 0)\n    {\n        gettimeofday(&timeNow, NULL);\n        cout<<\"===========================> Processor 1: dumping prediction results 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\nApproximation::~Approximation()\n{\n    delete[] RChol;\n        \n    delete[] wTilde;\n    delete[] ATilde;\n\n    delete[] KCholTimesCurrentw;\n    delete[] KCholTimesCurrentA;\n\n    if(CALCULATION_MODE == \"prediction\")\n    {\n        delete[] BTilde;\n\n        delete[] posteriorPredictionMean;\n        delete[] posteriorPredictionVariance;\n    }\n    //cout<<\"Approximation is deleted\\n\";\n}\n\n\n\n", "meta": {"hexsha": "e064c98560e61364114746a4ccbb529aec9ab515", "size": 22319, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "parallel_MRA/src/class_approximation.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.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.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": 42.3510436433, "max_line_length": 295, "alphanum_fraction": 0.6779425602, "num_tokens": 5734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.27148777709118327}}
{"text": "//=======================================================================\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\n// Copyright 2004, 2005 Trustees of Indiana University\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek,\n//          Doug Gregor, D. Kevin McGrath\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================//\n#ifndef BOOST_GRAPH_KING_HPP\n#define BOOST_GRAPH_KING_HPP\n\n#include <boost/config.hpp>\n#include <boost/graph/detail/sparse_ordering.hpp>\n#include <boost/graph/graph_utility.hpp>\n\n/*\n  King Algorithm for matrix reordering\n*/\n\nnamespace boost {\n  namespace detail {\n    template<typename OutputIterator, typename Buffer, typename Compare, \n             typename PseudoDegreeMap, typename VecMap, typename VertexIndexMap>\n    class bfs_king_visitor:public default_bfs_visitor\n    {\n    public:\n      bfs_king_visitor(OutputIterator *iter, Buffer *b, Compare compare, \n                       PseudoDegreeMap deg, std::vector<int> loc, VecMap color, \n                       VertexIndexMap vertices): \n        permutation(iter), Qptr(b), degree(deg), comp(compare), \n        Qlocation(loc), colors(color), vertex_map(vertices) { }\n      \n      template <typename Vertex, typename Graph>\n      void finish_vertex(Vertex, Graph& g) {\n        typename graph_traits<Graph>::out_edge_iterator ei, ei_end;\n        Vertex v, w;\n\n        typedef typename std::deque<Vertex>::reverse_iterator reverse_iterator;\n\n        reverse_iterator rend = Qptr->rend()-index_begin;\n        reverse_iterator rbegin = Qptr->rbegin();\n\n\n        //heap the vertices already there\n        std::make_heap(rbegin, rend, boost::bind<bool>(comp, _2, _1));\n\n        unsigned i = 0;\n        \n        for(i = index_begin; i != Qptr->size(); ++i){\n          colors[get(vertex_map, (*Qptr)[i])] = 1;\n          Qlocation[get(vertex_map, (*Qptr)[i])] = i;\n        }\n\n        i = 0;\n\n        for( ; rbegin != rend; rend--){\n          percolate_down<Vertex>(i);\n          w = (*Qptr)[index_begin+i];\n          for (boost::tie(ei, ei_end) = out_edges(w, g); ei != ei_end; ++ei) {\n            v = target(*ei, g);\n            put(degree, v, get(degree, v) - 1);\n    \n            if (colors[get(vertex_map, v)] == 1) {\n              percolate_up<Vertex>(get(vertex_map, v), i);            \n            }\n          }\n          \n          colors[get(vertex_map, w)] = 0;\n          i++;\n        }\n      }\n    \n      template <typename Vertex, typename Graph>\n      void examine_vertex(Vertex u, const Graph&) {\n        \n        *(*permutation)++ = u;\n        index_begin = Qptr->size();\n        \n      }\n    protected:\n\n\n      //this function replaces pop_heap, and tracks state information\n      template <typename Vertex>\n      void percolate_down(int offset){\n        int heap_last = index_begin + offset;\n        int heap_first = Qptr->size() - 1;\n        \n        //pop_heap functionality:\n        //swap first, last\n        std::swap((*Qptr)[heap_last], (*Qptr)[heap_first]);\n        \n        //swap in the location queue\n        std::swap(Qlocation[heap_first], Qlocation[heap_last]);\n\n        //set drifter, children\n        int drifter = heap_first;\n        int drifter_heap = Qptr->size() - drifter;\n\n        int right_child_heap = drifter_heap * 2 + 1;\n        int right_child = Qptr->size() - right_child_heap;\n\n        int left_child_heap = drifter_heap * 2;\n        int left_child = Qptr->size() - left_child_heap;\n\n        //check that we are staying in the heap\n        bool valid = (right_child < heap_last) ? false : true;\n        \n        //pick smallest child of drifter, and keep in mind there might only be left child\n        int smallest_child = (valid && get(degree, (*Qptr)[left_child]) > get(degree,(*Qptr)[right_child])) ? \n          right_child : left_child;\n        \n        while(valid && smallest_child < heap_last && comp((*Qptr)[drifter], (*Qptr)[smallest_child])){\n          \n          //if smallest child smaller than drifter, swap them\n          std::swap((*Qptr)[smallest_child], (*Qptr)[drifter]);\n          std::swap(Qlocation[drifter], Qlocation[smallest_child]);\n\n          //update the values, run again, as necessary\n          drifter = smallest_child;\n          drifter_heap = Qptr->size() - drifter;\n\n          right_child_heap = drifter_heap * 2 + 1;\n          right_child = Qptr->size() - right_child_heap;\n\n          left_child_heap = drifter_heap * 2;\n          left_child = Qptr->size() - left_child_heap;\n\n          valid = (right_child < heap_last) ? false : true;\n\n          smallest_child = (valid && get(degree, (*Qptr)[left_child]) > get(degree,(*Qptr)[right_child])) ? \n            right_child : left_child;\n        }\n\n      }\n\n\n      \n      // this is like percolate down, but we always compare against the\n      // parent, as there is only a single choice\n      template <typename Vertex>\n      void percolate_up(int vertex, int offset){\n        \n        int child_location = Qlocation[vertex];\n        int heap_child_location = Qptr->size() - child_location;\n        int heap_parent_location = (int)(heap_child_location/2);\n        unsigned parent_location = Qptr->size() - heap_parent_location; \n\n        bool valid = (heap_parent_location != 0 && child_location > index_begin + offset && \n                      parent_location < Qptr->size());\n\n        while(valid && comp((*Qptr)[child_location], (*Qptr)[parent_location])){\n          \n          //swap in the heap\n          std::swap((*Qptr)[child_location], (*Qptr)[parent_location]);\n          \n          //swap in the location queue\n          std::swap(Qlocation[child_location], Qlocation[parent_location]);\n\n          child_location = parent_location;\n          heap_child_location = heap_parent_location;\n          heap_parent_location = (int)(heap_child_location/2);\n          parent_location = Qptr->size() - heap_parent_location; \n          valid = (heap_parent_location != 0 && child_location > index_begin + offset);\n        }\n      }\n      \n      OutputIterator *permutation;\n      int index_begin;\n      Buffer *Qptr;\n      PseudoDegreeMap degree;\n      Compare comp;\n      std::vector<int> Qlocation;\n      VecMap colors;\n      VertexIndexMap vertex_map;\n    };\n  \n\n  } // namespace detail  \n  \n\n  template<class Graph, class OutputIterator, class ColorMap, class DegreeMap,\n           typename VertexIndexMap> \n  OutputIterator\n  king_ordering(const Graph& g,\n                std::deque< typename graph_traits<Graph>::vertex_descriptor >\n                  vertex_queue,\n                OutputIterator permutation, \n                ColorMap color, DegreeMap degree,\n                VertexIndexMap index_map)\n  {\n    typedef typename property_traits<DegreeMap>::value_type ds_type;\n    typedef typename property_traits<ColorMap>::value_type ColorValue;\n    typedef color_traits<ColorValue> Color;\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n    typedef iterator_property_map<typename std::vector<ds_type>::iterator, VertexIndexMap, ds_type, ds_type&> PseudoDegreeMap;\n    typedef indirect_cmp<PseudoDegreeMap, std::less<ds_type> > Compare;\n    typedef typename boost::sparse::sparse_ordering_queue<Vertex> queue;\n    typedef typename detail::bfs_king_visitor<OutputIterator, queue, Compare,             \n      PseudoDegreeMap, std::vector<int>, VertexIndexMap > Visitor;\n    typedef typename graph_traits<Graph>::vertices_size_type\n      vertices_size_type;\n    std::vector<ds_type> pseudo_degree_vec(num_vertices(g));\n    PseudoDegreeMap pseudo_degree(pseudo_degree_vec.begin(), index_map);\n    \n    typename graph_traits<Graph>::vertex_iterator ui, ui_end;    \n    queue Q;\n    // Copy degree to pseudo_degree\n    // initialize the color map\n    for (boost::tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui){\n      put(pseudo_degree, *ui, get(degree, *ui));\n      put(color, *ui, Color::white());\n    }\n    \n    Compare comp(pseudo_degree);\n    std::vector<int> colors(num_vertices(g));\n\n    for(vertices_size_type i = 0; i < num_vertices(g); i++) \n      colors[i] = 0;\n\n    std::vector<int> loc(num_vertices(g));\n\n    //create the visitor\n    Visitor vis(&permutation, &Q, comp, pseudo_degree, loc, colors, index_map);\n    \n    while( !vertex_queue.empty() ) {\n      Vertex s = vertex_queue.front();\n      vertex_queue.pop_front();\n      \n      //call BFS with visitor\n      breadth_first_visit(g, s, Q, vis, color);\n    }\n\n    return permutation;\n  }\n\n  \n  // This is the case where only a single starting vertex is supplied.\n  template <class Graph, class OutputIterator,\n            class ColorMap, class DegreeMap, typename VertexIndexMap>\n  OutputIterator\n  king_ordering(const Graph& g,\n                typename graph_traits<Graph>::vertex_descriptor s,\n                OutputIterator permutation, \n                ColorMap color, DegreeMap degree, VertexIndexMap index_map)\n  {\n\n    std::deque< typename graph_traits<Graph>::vertex_descriptor > vertex_queue;\n    vertex_queue.push_front( s );\n    return king_ordering(g, vertex_queue, permutation, color, degree,\n                         index_map);\n  }\n\n  \n  template < class Graph, class OutputIterator, \n             class ColorMap, class DegreeMap, class VertexIndexMap>\n  OutputIterator \n  king_ordering(const Graph& G, OutputIterator permutation, \n                ColorMap color, DegreeMap degree, VertexIndexMap index_map)\n  {\n    if (has_no_vertices(G))\n      return permutation;\n\n    typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\n    typedef typename property_traits<ColorMap>::value_type ColorValue;\n    typedef color_traits<ColorValue> Color;\n\n    std::deque<Vertex>      vertex_queue;\n\n    // Mark everything white\n    BGL_FORALL_VERTICES_T(v, G, Graph) put(color, v, Color::white());\n\n    // Find one vertex from each connected component \n    BGL_FORALL_VERTICES_T(v, G, Graph) {\n      if (get(color, v) == Color::white()) {\n        depth_first_visit(G, v, dfs_visitor<>(), color);\n        vertex_queue.push_back(v);\n      }\n    }\n\n    // Find starting nodes for all vertices\n    // TBD: How to do this with a directed graph?\n    for (typename std::deque<Vertex>::iterator i = vertex_queue.begin();\n         i != vertex_queue.end(); ++i)\n      *i = find_starting_node(G, *i, color, degree);\n    \n    return king_ordering(G, vertex_queue, permutation, color, degree,\n                         index_map);\n  }\n\n  template<typename Graph, typename OutputIterator, typename VertexIndexMap>\n  OutputIterator \n  king_ordering(const Graph& G, OutputIterator permutation, \n                VertexIndexMap index_map)\n  {\n    if (has_no_vertices(G))\n      return permutation;\n\n    std::vector<default_color_type> colors(num_vertices(G));\n    return king_ordering(G, permutation, \n                         make_iterator_property_map(&colors[0], index_map,\n                                                    colors[0]),\n                         make_out_degree_map(G), index_map);\n  }\n\n  template<typename Graph, typename OutputIterator>\n  inline OutputIterator \n  king_ordering(const Graph& G, OutputIterator permutation)\n  { return king_ordering(G, permutation, get(vertex_index, G)); }\n\n} // namespace boost\n\n\n#endif // BOOST_GRAPH_KING_HPP\n", "meta": {"hexsha": "29e7ac970f15523005bb8e88a3c746ec8a51477e", "size": 11357, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/king_ordering.hpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/graph/king_ordering.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/king_ordering.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": 35.8264984227, "max_line_length": 126, "alphanum_fraction": 0.6229638109, "num_tokens": 2606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.27148777043861516}}
{"text": "// These headers are deprecated.\n//\n// #include <boost/math/common_factor_ct.hpp>\n// #include <boost/math/common_factor.hpp>\n// #include <boost/math/common_factor_rt.hpp>\n\n#include <boost/cstdfloat.hpp>\n#include <boost/math/complex.hpp>\n#include <boost/math/distributions.hpp>\n#include <boost/math_fwd.hpp>\n#include <boost/math/octonion.hpp>\n#include <boost/math/quaternion.hpp>\n#include <boost/math/special_functions.hpp>\n\n// This header is used by the other drivers.\n//\n// #include <boost/math/tr1.hpp>\n\nint\nmain ()\n{\n  return boost::math::prime (0) == 2 && boost::math::prime (9) == 29 ? 0 : 1;\n}\n", "meta": {"hexsha": "42bd8be55432fcecaab2472f9a60c7794786e9a2", "size": 600, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "downstream/libs/math/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-math/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-math/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": 25.0, "max_line_length": 77, "alphanum_fraction": 0.7116666667, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.27140252420237715}}
{"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 NoiseModel.cpp\n * @date Jan 13, 2010\n * @author Richard Roberts\n * @author Frank Dellaert\n */\n\n#include <gtsam/linear/NoiseModel.h>\n#include <gtsam/base/timing.h>\n\n#include <boost/format.hpp>\n#include <boost/make_shared.hpp>\n\n#include <cmath>\n#include <iostream>\n#include <limits>\n#include <stdexcept>\n#include <typeinfo>\n\nusing namespace std;\n\nnamespace gtsam {\nnamespace noiseModel {\n\n/* ************************************************************************* */\n// update A, b\n// A' \\define A_{S}-ar and b'\\define b-ad\n// Linear algebra: takes away projection on latest orthogonal\n// Graph: make a new factor on the separator S\n// __attribute__ ((noinline))  // uncomment to prevent inlining when profiling\ntemplate<class MATRIX>\nvoid updateAb(MATRIX& Ab, int j, const Vector& a, const Vector& rd) {\n  size_t n = Ab.cols()-1;\n  Ab.middleCols(j+1,n-j) -= a * rd.segment(j+1, n-j).transpose();\n}\n\n/* ************************************************************************* */\n// check *above the diagonal* for non-zero entries\nboost::optional<Vector> checkIfDiagonal(const Matrix M) {\n  size_t m = M.rows(), n = M.cols();\n  // check all non-diagonal entries\n  bool full = false;\n  size_t i, j;\n  for (i = 0; i < m; i++)\n    if (!full)\n      for (j = i + 1; j < n; j++)\n        if (std::abs(M(i, j)) > 1e-9) {\n          full = true;\n          break;\n        }\n  if (full) {\n    return boost::none;\n  } else {\n    Vector diagonal(n);\n    for (j = 0; j < n; j++)\n      diagonal(j) = M(j, j);\n    return diagonal;\n  }\n}\n\n/* ************************************************************************* */\nVector Base::sigmas() const {\n  throw(\"Base::sigmas: sigmas() not implemented for this noise model\");\n}\n\n/* ************************************************************************* */\ndouble Base::squaredMahalanobisDistance(const Vector& v) const {\n  // Note: for Diagonal, which does ediv_, will be correct for constraints\n  Vector w = whiten(v);\n  return w.dot(w);\n}\n\n/* ************************************************************************* */\nGaussian::shared_ptr Gaussian::SqrtInformation(const Matrix& R, bool smart) {\n  size_t m = R.rows(), n = R.cols();\n  if (m != n)\n    throw invalid_argument(\"Gaussian::SqrtInformation: R not square\");\n  if (smart) {\n    boost::optional<Vector> diagonal = checkIfDiagonal(R);\n    if (diagonal)\n      return Diagonal::Sigmas(diagonal->array().inverse(), true);\n  }\n  // NOTE(frank): only reaches here if !(smart && diagonal)\n  return shared_ptr(new Gaussian(R.rows(), R));\n}\n\n/* ************************************************************************* */\nGaussian::shared_ptr Gaussian::Information(const Matrix& information, bool smart) {\n  size_t m = information.rows(), n = information.cols();\n  if (m != n)\n    throw invalid_argument(\"Gaussian::Information: R not square\");\n  boost::optional<Vector> diagonal = boost::none;\n  if (smart)\n    diagonal = checkIfDiagonal(information);\n  if (diagonal)\n    return Diagonal::Precisions(*diagonal, true);\n  else {\n    Eigen::LLT<Matrix> llt(information);\n    Matrix R = llt.matrixU();\n    return shared_ptr(new Gaussian(n, R));\n  }\n}\n\n/* ************************************************************************* */\nGaussian::shared_ptr Gaussian::Covariance(const Matrix& covariance,\n    bool smart) {\n  size_t m = covariance.rows(), n = covariance.cols();\n  if (m != n)\n    throw invalid_argument(\"Gaussian::Covariance: covariance not square\");\n  boost::optional<Vector> variances = boost::none;\n  if (smart)\n    variances = checkIfDiagonal(covariance);\n  if (variances)\n    return Diagonal::Variances(*variances, true);\n  else {\n    // NOTE: if cov = L'*L, then the square root information R can be found by\n    // QR, as L.inverse() = Q*R, with Q some rotation matrix. However, R has\n    // annoying sign flips with respect the simpler Information(inv(cov)),\n    // hence we choose the simpler path here:\n    return Information(covariance.inverse(), false);\n  }\n}\n\n/* ************************************************************************* */\nvoid Gaussian::print(const string& name) const {\n  gtsam::print(thisR(), name + \"Gaussian\");\n}\n\n/* ************************************************************************* */\nbool Gaussian::equals(const Base& expected, double tol) const {\n  const Gaussian* p = dynamic_cast<const Gaussian*> (&expected);\n  if (p == nullptr) return false;\n  if (typeid(*this) != typeid(*p)) return false;\n  return equal_with_abs_tol(R(), p->R(), sqrt(tol));\n}\n\n/* ************************************************************************* */\nMatrix Gaussian::covariance() const {\n  // Uses a fast version of `covariance = information().inverse();`\n  const Matrix& R = this->R();\n  Matrix I = Matrix::Identity(R.rows(), R.cols());\n  // Fast inverse of upper-triangular matrix R using forward-substitution\n  Matrix Rinv = R.triangularView<Eigen::Upper>().solve(I);\n  // (R' * R)^{-1} = R^{-1} * R^{-1}'\n  return Rinv * Rinv.transpose();\n}\n\n/* ************************************************************************* */\nVector Gaussian::sigmas() const {\n  return Vector(covariance().diagonal()).cwiseSqrt();\n}\n\n/* ************************************************************************* */\nVector Gaussian::whiten(const Vector& v) const {\n  return thisR() * v;\n}\n\n/* ************************************************************************* */\nVector Gaussian::unwhiten(const Vector& v) const {\n  return backSubstituteUpper(thisR(), v);\n}\n\n/* ************************************************************************* */\nMatrix Gaussian::Whiten(const Matrix& H) const {\n  return thisR() * H;\n}\n\n/* ************************************************************************* */\nvoid Gaussian::WhitenInPlace(Matrix& H) const {\n  H = thisR() * H;\n}\n\n/* ************************************************************************* */\nvoid Gaussian::WhitenInPlace(Eigen::Block<Matrix> H) const {\n  H = thisR() * H;\n}\n\n/* ************************************************************************* */\n// General QR, see also special version in Constrained\nSharedDiagonal Gaussian::QR(Matrix& Ab) const {\n\n  gttic(Gaussian_noise_model_QR);\n\n  static const bool debug = false;\n\n  // get size(A) and maxRank\n  // TODO: really no rank problems ?\n   size_t m = Ab.rows(), n = Ab.cols()-1;\n   size_t maxRank = min(m,n);\n\n  // pre-whiten everything (cheaply if possible)\n  WhitenInPlace(Ab);\n\n  if(debug) gtsam::print(Ab, \"Whitened Ab: \");\n\n  // Eigen QR - much faster than older householder approach\n  inplace_QR(Ab);\n  Ab.triangularView<Eigen::StrictlyLower>().setZero();\n\n  // hand-coded householder implementation\n  // TODO: necessary to isolate last column?\n  // householder(Ab, maxRank);\n\n  return noiseModel::Unit::Create(maxRank);\n}\n\nvoid Gaussian::WhitenSystem(vector<Matrix>& A, Vector& b) const {\n  for(Matrix& Aj: A) { WhitenInPlace(Aj); }\n  whitenInPlace(b);\n}\n\nvoid Gaussian::WhitenSystem(Matrix& A, Vector& b) const {\n  WhitenInPlace(A);\n  whitenInPlace(b);\n}\n\nvoid Gaussian::WhitenSystem(Matrix& A1, Matrix& A2, Vector& b) const {\n  WhitenInPlace(A1);\n  WhitenInPlace(A2);\n  whitenInPlace(b);\n}\n\nvoid Gaussian::WhitenSystem(Matrix& A1, Matrix& A2, Matrix& A3, Vector& b) const{\n  WhitenInPlace(A1);\n  WhitenInPlace(A2);\n  WhitenInPlace(A3);\n  whitenInPlace(b);\n}\n\n/* ************************************************************************* */\n// Diagonal\n/* ************************************************************************* */\nDiagonal::Diagonal() :\n    Gaussian(1) // TODO: Frank asks: really sure about this?\n{\n}\n\n/* ************************************************************************* */\nDiagonal::Diagonal(const Vector& sigmas)\n    : Gaussian(sigmas.size()),\n      sigmas_(sigmas),\n      invsigmas_(sigmas.array().inverse()),\n      precisions_(invsigmas_.array().square()) {\n}\n\n/* ************************************************************************* */\nDiagonal::shared_ptr Diagonal::Variances(const Vector& variances, bool smart) {\n  if (smart) {\n    // check whether all the same entry\n    size_t n = variances.size();\n    for (size_t j = 1; j < n; j++)\n      if (variances(j) != variances(0)) goto full;\n    return Isotropic::Variance(n, variances(0), true);\n  }\n  full: return shared_ptr(new Diagonal(variances.cwiseSqrt()));\n}\n\n/* ************************************************************************* */\nDiagonal::shared_ptr Diagonal::Sigmas(const Vector& sigmas, bool smart) {\n  if (smart) {\n    size_t n = sigmas.size();\n    if (n==0) goto full;\n    // look for zeros to make a constraint\n    for (size_t j=0; j< n; ++j)\n      if (sigmas(j)<1e-8)\n        return Constrained::MixedSigmas(sigmas);\n    // check whether all the same entry\n    for (size_t j = 1; j < n; j++)\n      if (sigmas(j) != sigmas(0)) goto full;\n    return Isotropic::Sigma(n, sigmas(0), true);\n  }\n  full: return Diagonal::shared_ptr(new Diagonal(sigmas));\n}\n\n/* ************************************************************************* */\nvoid Diagonal::print(const string& name) const {\n  gtsam::print(sigmas_, name + \"diagonal sigmas\");\n}\n\n/* ************************************************************************* */\nVector Diagonal::whiten(const Vector& v) const {\n  return v.cwiseProduct(invsigmas_);\n}\n\n/* ************************************************************************* */\nVector Diagonal::unwhiten(const Vector& v) const {\n  return v.cwiseProduct(sigmas_);\n}\n\n/* ************************************************************************* */\nMatrix Diagonal::Whiten(const Matrix& H) const {\n  return vector_scale(invsigmas(), H);\n}\n\n/* ************************************************************************* */\nvoid Diagonal::WhitenInPlace(Matrix& H) const {\n  vector_scale_inplace(invsigmas(), H);\n}\n\n/* ************************************************************************* */\nvoid Diagonal::WhitenInPlace(Eigen::Block<Matrix> H) const {\n  H = invsigmas().asDiagonal() * H;\n}\n\n/* ************************************************************************* */\n// Constrained\n/* ************************************************************************* */\n\nnamespace internal {\n// switch precisions and invsigmas to finite value\n// TODO: why?? And, why not just ask s==0.0 below ?\nstatic void fix(const Vector& sigmas, Vector& precisions, Vector& invsigmas) {\n  for (Vector::Index i = 0; i < sigmas.size(); ++i)\n    if (!std::isfinite(1. / sigmas[i])) {\n      precisions[i] = 0.0;\n      invsigmas[i] = 0.0;\n    }\n}\n}\n\n/* ************************************************************************* */\nConstrained::Constrained(const Vector& sigmas)\n  : Diagonal(sigmas), mu_(Vector::Constant(sigmas.size(), 1000.0)) {\n  internal::fix(sigmas, precisions_, invsigmas_);\n}\n\n/* ************************************************************************* */\nConstrained::Constrained(const Vector& mu, const Vector& sigmas)\n  : Diagonal(sigmas), mu_(mu) {\n  internal::fix(sigmas, precisions_, invsigmas_);\n}\n\n/* ************************************************************************* */\nConstrained::shared_ptr Constrained::MixedSigmas(const Vector& mu,\n    const Vector& sigmas) {\n  return shared_ptr(new Constrained(mu, sigmas));\n}\n\n/* ************************************************************************* */\nbool Constrained::constrained(size_t i) const {\n  // TODO why not just check sigmas_[i]==0.0 ?\n  return !std::isfinite(1./sigmas_[i]);\n}\n\n/* ************************************************************************* */\nvoid Constrained::print(const std::string& name) const {\n  gtsam::print(sigmas_, name + \"constrained sigmas\");\n  gtsam::print(mu_, name + \"constrained mu\");\n}\n\n/* ************************************************************************* */\nVector Constrained::whiten(const Vector& v) const {\n  // If sigmas[i] is not 0 then divide v[i] by sigmas[i], as usually done in\n  // other normal Gaussian noise model. Otherwise, sigmas[i] = 0 indicating\n  // a hard constraint, we don't do anything.\n  const Vector& a = v;\n  const Vector& b = sigmas_;\n  size_t n = a.size();\n  assert (b.size()==a.size());\n  Vector c(n);\n  for( size_t i = 0; i < n; i++ ) {\n    const double& ai = a(i), bi = b(i);\n    c(i) = (bi==0.0) ? ai : ai/bi; // NOTE: not ediv_()\n  }\n  return c;\n}\n\n#ifdef GTSAM_ALLOW_DEPRECATED_SINCE_V4\n/* ************************************************************************* */\ndouble Constrained::error(const Vector& v) const {\n  Vector w = Diagonal::whiten(v); // get noisemodel for constrained elements\n  for (size_t i=0; i<dim_; ++i)  // add mu weights on constrained variables\n    if (constrained(i)) // whiten makes constrained variables zero\n      w[i] = v[i] * sqrt(mu_[i]); // TODO: may want to store sqrt rather than rebuild\n  return 0.5 * w.dot(w);\n}\n#endif\n\n/* ************************************************************************* */\ndouble Constrained::squaredMahalanobisDistance(const Vector& v) const {\n  Vector w = Diagonal::whiten(v); // get noisemodel for constrained elements\n  for (size_t i=0; i<dim_; ++i)  // add mu weights on constrained variables\n    if (constrained(i)) // whiten makes constrained variables zero\n      w[i] = v[i] * sqrt(mu_[i]); // TODO: may want to store sqrt rather than rebuild\n  return w.dot(w);\n}\n\n/* ************************************************************************* */\nMatrix Constrained::Whiten(const Matrix& H) const {\n  Matrix A = H;\n  for (DenseIndex i=0; i<(DenseIndex)dim_; ++i)\n    if (!constrained(i)) // if constrained, leave row of A as is\n      A.row(i) *= invsigmas_(i);\n  return A;\n}\n\n/* ************************************************************************* */\nvoid Constrained::WhitenInPlace(Matrix& H) const {\n  for (DenseIndex i=0; i<(DenseIndex)dim_; ++i)\n    if (!constrained(i)) // if constrained, leave row of H as is\n      H.row(i) *= invsigmas_(i);\n}\n\n/* ************************************************************************* */\nvoid Constrained::WhitenInPlace(Eigen::Block<Matrix> H) const {\n  for (DenseIndex i=0; i<(DenseIndex)dim_; ++i)\n    if (!constrained(i)) // if constrained, leave row of H as is\n      H.row(i) *= invsigmas_(i);\n}\n\n/* ************************************************************************* */\nConstrained::shared_ptr Constrained::unit() const {\n  Vector sigmas = Vector::Ones(dim());\n  for (size_t i=0; i<dim(); ++i)\n    if (constrained(i))\n      sigmas(i) = 0.0;\n  return MixedSigmas(mu_, sigmas);\n}\n\n/* ************************************************************************* */\n// Special version of QR for Constrained calls slower but smarter code\n// that deals with possibly zero sigmas\n// It is Gram-Schmidt orthogonalization rather than Householder\n\n// Check whether column a triggers a constraint and corresponding variable is deterministic\n// Return constraint_row with maximum element in case variable plays in multiple constraints\ntemplate <typename VECTOR>\nboost::optional<size_t> check_if_constraint(VECTOR a, const Vector& invsigmas, size_t m) {\n  boost::optional<size_t> constraint_row;\n  // not zero, so roundoff errors will not be counted\n  // TODO(frank): that's a fairly crude way of dealing with roundoff errors :-(\n  double max_element = 1e-9;\n  for (size_t i = 0; i < m; i++) {\n    if (!std::isinf(invsigmas[i]))\n      continue;\n    double abs_ai = std::abs(a(i,0));\n    if (abs_ai > max_element) {\n      max_element = abs_ai;\n      constraint_row.reset(i);\n    }\n  }\n  return constraint_row;\n}\n\nSharedDiagonal Constrained::QR(Matrix& Ab) const {\n  static const double kInfinity = std::numeric_limits<double>::infinity();\n\n  // get size(A) and maxRank\n  size_t m = Ab.rows();\n  const size_t n = Ab.cols() - 1;\n  const size_t maxRank = min(m, n);\n\n  // create storage for [R d]\n  typedef boost::tuple<size_t, Matrix, double> Triple;\n  list<Triple> Rd;\n\n  Matrix rd(1, n + 1);  // and for row of R\n  Vector invsigmas = sigmas_.array().inverse();\n  Vector weights = invsigmas.array().square();  // calculate weights once\n\n  // We loop over all columns, because the columns that can be eliminated\n  // are not necessarily contiguous. For each one, estimate the corresponding\n  // scalar variable x as d-rS, with S the separator (remaining columns).\n  // Then update A and b by substituting x with d-rS, zero-ing out x's column.\n  for (size_t j = 0; j < n; ++j) {\n    // extract the first column of A\n    Eigen::Block<Matrix> a = Ab.block(0, j, m, 1);\n\n    // Check whether we need to handle as a constraint\n    boost::optional<size_t> constraint_row = check_if_constraint(a, invsigmas, m);\n\n    if (constraint_row) {\n      // Handle this as a constraint, as the i^th row has zero sigma with non-zero entry A(i,j)\n\n      // In this case, the row in [R|d] is simply the row in [A|b]\n      // NOTE(frank): we used to divide by a[i] but there is no need with a constraint\n      rd = Ab.row(*constraint_row);\n\n      // Construct solution (r, d, sigma)\n      Rd.push_back(boost::make_tuple(j, rd, kInfinity));\n\n      // exit after rank exhausted\n      if (Rd.size() >= maxRank)\n        break;\n\n      // The constraint row will be zeroed out, so we can save work by swapping in the\n      // last valid row and decreasing m. This will save work on subsequent down-dates, too.\n      m -= 1;\n      if (*constraint_row != m) {\n        Ab.row(*constraint_row) = Ab.row(m);\n        weights(*constraint_row) = weights(m);\n        invsigmas(*constraint_row) = invsigmas(m);\n      }\n\n      // get a reduced a-column which is now shorter\n      Eigen::Block<Matrix> a_reduced = Ab.block(0, j, m, 1);\n      a_reduced *= (1.0/rd(0, j)); // NOTE(frank): this is the 1/a[i] = 1/rd(0,j) factor we need!\n\n      // Rank-1 down-date of Ab, expensive, using outer product\n      Ab.block(0, j + 1, m, n - j).noalias() -= a_reduced * rd.middleCols(j + 1, n - j);\n    } else {\n      // Treat in normal Gram-Schmidt way\n      // Calculate weighted pseudo-inverse and corresponding precision\n\n      // Form psuedo-inverse inv(a'inv(Sigma)a)a'inv(Sigma)\n      // For diagonal Sigma, inv(Sigma) = diag(precisions)\n      double precision = 0;\n      Vector pseudo(m);     // allocate storage for pseudo-inverse\n      for (size_t i = 0; i < m; i++) {\n        double ai = a(i, 0);\n        if (std::abs(ai) > 1e-9) {  // also catches remaining sigma==0 rows\n          pseudo[i] = weights[i] * ai;\n          precision += pseudo[i] * ai;\n        } else\n          pseudo[i] = 0;\n      }\n\n      if (precision > 1e-8) {\n        pseudo /= precision;\n\n        // create solution [r d], rhs is automatically r(n)\n        rd(0, j) = 1.0;  // put 1 on diagonal\n        rd.block(0, j + 1, 1, n - j) = pseudo.transpose() * Ab.block(0, j + 1, m, n - j);\n\n        // construct solution (r, d, sigma)\n        Rd.push_back(boost::make_tuple(j, rd, precision));\n      } else {\n        // If precision is zero, no information on this column\n        // This is actually not limited to constraints, could happen in Gaussian::QR\n        // In that case, we're probably hosed. TODO: make sure Householder is rank-revealing\n        continue;  // but even if not, no need to update if a==zeros\n      }\n\n      // exit after rank exhausted\n      if (Rd.size() >= maxRank)\n        break;\n\n      // Rank-1 down-date of Ab, expensive, using outer product\n      Ab.block(0, j + 1, m, n - j).noalias() -= a * rd.middleCols(j + 1, n - j);\n    }\n  }\n\n  // Create storage for precisions\n  Vector precisions(Rd.size());\n\n  // Write back result in Ab, imperative as we are\n  size_t i = 0;  // start with first row\n  bool mixed = false;\n  Ab.setZero();  // make sure we don't look below\n  for (const Triple& t: Rd) {\n    const size_t& j = t.get<0>();\n    const Matrix& rd = t.get<1>();\n    precisions(i) = t.get<2>();\n    if (std::isinf(precisions(i)))\n      mixed = true;\n    Ab.block(i, j, 1, n + 1 - j) = rd.block(0, j, 1, n + 1 - j);\n    i += 1;\n  }\n\n  // Must include mu, as the defaults might be higher, resulting in non-convergence\n  return mixed ? Constrained::MixedPrecisions(mu_, precisions) : Diagonal::Precisions(precisions);\n}\n\n/* ************************************************************************* */\n// Isotropic\n/* ************************************************************************* */\nIsotropic::shared_ptr Isotropic::Sigma(size_t dim, double sigma, bool smart)  {\n  if (smart && std::abs(sigma-1.0)<1e-9) return Unit::Create(dim);\n  return shared_ptr(new Isotropic(dim, sigma));\n}\n\n/* ************************************************************************* */\nIsotropic::shared_ptr Isotropic::Variance(size_t dim, double variance, bool smart)  {\n  if (smart && std::abs(variance-1.0)<1e-9) return Unit::Create(dim);\n  return shared_ptr(new Isotropic(dim, sqrt(variance)));\n}\n\n/* ************************************************************************* */\nvoid Isotropic::print(const string& name) const {\n  cout << boost::format(\"isotropic dim=%1% sigma=%2%\") % dim() % sigma_ << endl;\n}\n\n/* ************************************************************************* */\ndouble Isotropic::squaredMahalanobisDistance(const Vector& v) const {\n  return v.dot(v) * invsigma_ * invsigma_;\n}\n\n/* ************************************************************************* */\nVector Isotropic::whiten(const Vector& v) const {\n  return v * invsigma_;\n}\n\n/* ************************************************************************* */\nVector Isotropic::unwhiten(const Vector& v) const {\n  return v * sigma_;\n}\n\n/* ************************************************************************* */\nMatrix Isotropic::Whiten(const Matrix& H) const {\n  return invsigma_ * H;\n}\n\n/* ************************************************************************* */\nvoid Isotropic::WhitenInPlace(Matrix& H) const {\n  H *= invsigma_;\n}\n\n/* ************************************************************************* */\nvoid Isotropic::whitenInPlace(Vector& v) const {\n  v *= invsigma_;\n}\n\n/* ************************************************************************* */\nvoid Isotropic::WhitenInPlace(Eigen::Block<Matrix> H) const {\n  H *= invsigma_;\n}\n\n/* ************************************************************************* */\n// Unit\n/* ************************************************************************* */\nvoid Unit::print(const std::string& name) const {\n  cout << name << \"unit (\" << dim_ << \") \" << endl;\n}\n\n/* ************************************************************************* */\n// Robust\n/* ************************************************************************* */\n\nvoid Robust::print(const std::string& name) const {\n  robust_->print(name);\n  noise_->print(name);\n}\n\nbool Robust::equals(const Base& expected, double tol) const {\n  const Robust* p = dynamic_cast<const Robust*> (&expected);\n  if (p == nullptr) return false;\n  return noise_->equals(*p->noise_,tol) && robust_->equals(*p->robust_,tol);\n}\n\nvoid Robust::WhitenSystem(Vector& b) const {\n  noise_->whitenInPlace(b);\n  robust_->reweight(b);\n}\n\nvoid Robust::WhitenSystem(vector<Matrix>& A, Vector& b) const {\n  noise_->WhitenSystem(A,b);\n  robust_->reweight(A,b);\n}\n\nvoid Robust::WhitenSystem(Matrix& A, Vector& b) const {\n  noise_->WhitenSystem(A,b);\n  robust_->reweight(A,b);\n}\n\nvoid Robust::WhitenSystem(Matrix& A1, Matrix& A2, Vector& b) const {\n  noise_->WhitenSystem(A1,A2,b);\n  robust_->reweight(A1,A2,b);\n}\n\nvoid Robust::WhitenSystem(Matrix& A1, Matrix& A2, Matrix& A3, Vector& b) const{\n  noise_->WhitenSystem(A1,A2,A3,b);\n  robust_->reweight(A1,A2,A3,b);\n}\n\nRobust::shared_ptr Robust::Create(\nconst RobustModel::shared_ptr &robust, const NoiseModel::shared_ptr noise){\n  return shared_ptr(new Robust(robust,noise));\n}\n\n/* ************************************************************************* */\n\n}\n} // gtsam\n", "meta": {"hexsha": "f5ec956968e60f19565d59fd489cc1b9a4485041", "size": 24054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/linear/NoiseModel.cpp", "max_stars_repo_name": "baoyufuyou/gtsam", "max_stars_repo_head_hexsha": "905be415fa89111577671064d3a1681b083d075e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-08-13T20:25:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-05T22:24:43.000Z", "max_issues_repo_path": "gtsam/linear/NoiseModel.cpp", "max_issues_repo_name": "baoyufuyou/gtsam", "max_issues_repo_head_hexsha": "905be415fa89111577671064d3a1681b083d075e", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/NoiseModel.cpp", "max_forks_repo_name": "baoyufuyou/gtsam", "max_forks_repo_head_hexsha": "905be415fa89111577671064d3a1681b083d075e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-12T20:46:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-12T20:46:15.000Z", "avg_line_length": 35.1153284672, "max_line_length": 98, "alphanum_fraction": 0.5252348882, "num_tokens": 5783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2714025177952416}}
{"text": "#pragma once\n\n// system includes ------------------------------------------------------------\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <vector>\n#include \"aux/exceptions.h\"\n\nnamespace boltzmann {\nclass CollisionTensor\n{\n private:\n  typedef Eigen::SparseMatrix<double> sparse_matrix_t;\n  typedef std::shared_ptr<sparse_matrix_t> ptr_t;\n  typedef Eigen::SparseLU<sparse_matrix_t> lu_t;\n\n public:\n  CollisionTensor(int N);\n  CollisionTensor()\n      : N_(0)\n  {\n  }\n\n  void apply(double* out, const double* in) const;\n  void apply(double* out, const double* in, double* buffer) const;\n\n  /**\n   *\n   *\n   * @param out\n   * @param in\n   * @param L        #local phys. DoFs\n   * @param buffer   external buffer of length N*L\n   * @param local_bd_indicator true: is at boundary, do not apply scattering,\n   *                           false: inner vertex, apply scattering\n   */\n  void apply(double* out,\n             const double* in,\n             const unsigned int L,\n             double* buffer,\n             const std::vector<bool>& local_bd_indicator = std::vector<bool>()) const;\n\n  void apply_adaptive(double* out, const double* in, int nmax) const;\n  void add(ptr_t& slice, unsigned int j);\n  const sparse_matrix_t& get(int j);\n\n  void set_mass_matrix(sparse_matrix_t& m);\n  const lu_t& get_invm() const { return lu_; }\n  const sparse_matrix_t& mass_matrix() const { return mass_matrix_; }\n\n  const std::vector<ptr_t>& slices() const { return slices_; }\n\n  /**\n   * @brief read tensor from file\n   *\n   * @param fname Filename\n   * @param N     #DoFs\n   */\n  void read_hdf5(const char* fname, const int N);\n\n private:\n  /// basis size\n  unsigned int N_;\n  /// buffer\n  mutable Eigen::VectorXd vtmp;\n  /// tensor entries\n  std::vector<ptr_t> slices_;\n  /// mass matrix\n  sparse_matrix_t mass_matrix_;\n  /// inverse of mass matrix\n  lu_t lu_;\n};\n\n// ------------------------------------------------------------\ninline void\nCollisionTensor::apply(double* out, const double* in) const\n{\n  assert(mass_matrix_.rows() > 0);\n  typedef Eigen::Map<Eigen::VectorXd> vec_t;\n  typedef Eigen::Map<const Eigen::VectorXd> const_vec_t;\n  const_vec_t v_in(in, N_);\n  vec_t v_out(out, N_);\n\n#pragma omp parallel for\n  for (unsigned int j = 0; j < N_; ++j) {\n    vtmp[j] = v_in.dot((*slices_[j]) * v_in);\n  }\n\n  // this is not parallel\n  v_out = lu_.solve(vtmp);\n}\n\n// ------------------------------------------------------------\ninline void\nCollisionTensor::apply_adaptive(double* out, const double* in, int nmax) const\n{\n  assert(mass_matrix_.rows() > 0);\n  typedef Eigen::Map<Eigen::VectorXd> vec_t;\n  typedef Eigen::Map<const Eigen::VectorXd> const_vec_t;\n  const_vec_t v_in(in, nmax);\n  vec_t v_out(out, N_);\n\n// is this load-balanced? probably not\n#pragma omp parallel for\n  for (unsigned int j = 0; j < N_; ++j) {\n    vtmp[j] = v_in.dot((*slices_[j]).topLeftCorner(nmax, nmax) * v_in);\n  }\n\n  // this is not parallel\n  v_out = lu_.solve(vtmp);\n}\n\n// ------------------------------------------------------------\ninline void\nCollisionTensor::apply(double* out, const double* in, double* buffer) const\n{\n  assert(mass_matrix_.rows() > 0);\n  typedef Eigen::Map<Eigen::VectorXd> vec_t;\n  typedef Eigen::Map<const Eigen::VectorXd> const_vec_t;\n  const_vec_t v_in(in, N_);\n  vec_t vbuf(buffer, N_);\n  vec_t v_out(out, N_);\n#pragma omp parallel for schedule(guided)\n  for (unsigned int j = 0; j < N_; ++j) {\n    vbuf[j] = v_in.dot((*slices_[j]) * v_in);\n  }\n  v_out = lu_.solve(vbuf);\n}\n\n// ------------------------------------------------------------\ninline void\nCollisionTensor::apply(double* out,\n                       const double* in,\n                       const unsigned int L,\n                       double* buffer,\n                       const std::vector<bool>& local_bd_indicator) const\n{\n  assert(mass_matrix_.rows() > 0);\n  typedef Eigen::Map<Eigen::VectorXd> vec_t;\n  typedef Eigen::Map<const Eigen::VectorXd> const_vec_t;\n\n  vec_t vbuf(buffer, N_ * L);\n\n  if (local_bd_indicator.size() == 0) {\n#pragma omp parallel\n    {\n#pragma omp for schedule(guided)\n      for (unsigned int j = 0; j < N_; ++j) {\n        for (unsigned int l = 0; l < L; ++l) {\n          const_vec_t v_in(in + N_ * l, N_);\n          vbuf[N_ * l + j] = v_in.dot((*slices_[j]) * v_in);\n        }\n      }\n\n#pragma omp for schedule(static)\n      for (unsigned int l = 0; l < L; ++l) {\n        vec_t vout(out + N_ * l, N_);\n        const_vec_t vbuf(buffer + N_ * l, N_);\n        vout = lu_.solve(vbuf);\n      }\n    }\n  } else if (local_bd_indicator.size() == L) {\n#pragma omp parallel\n    {\n#pragma omp for schedule(guided)\n      for (unsigned int j = 0; j < N_; ++j) {\n        for (unsigned int l = 0; l < L; ++l) {\n          if (local_bd_indicator[l]) continue;\n          const_vec_t v_in(in + N_ * l, N_);\n          vbuf[N_ * l + j] = v_in.dot((*slices_[j]) * v_in);\n        }\n      }\n\n#pragma omp for schedule(static)\n      for (unsigned int l = 0; l < L; ++l) {\n        if (local_bd_indicator[l]) continue;\n        vec_t vout(out + N_ * l, N_);\n        const_vec_t vbuf(buffer + N_ * l, N_);\n        vout = lu_.solve(vbuf);\n      }\n    }\n\n  }\n#ifdef DEBUG\n  else {\n    BAssertThrow(false, \"something went wrong with bd_indicator\");\n  }\n#endif\n}\n\n}  // end boltzmann\n", "meta": {"hexsha": "152f1c8e60e6eea854556eb9e696b3b4d6fd2884", "size": 5246, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/collision_tensor/collision_tensor.hpp", "max_stars_repo_name": "simonpintarelli/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/collision_tensor/collision_tensor.hpp", "max_issues_repo_name": "simonpintarelli/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/collision_tensor/collision_tensor.hpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3229166667, "max_line_length": 86, "alphanum_fraction": 0.5794891346, "num_tokens": 1423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.271402511388106}}
{"text": "#include <string>\r\n#include <string.h>\r\n#include <stdlib.h>\r\n#include <iostream>\r\n#include <cstdio>\r\n\r\n#include <Eigen/Core>\r\n#include <pcl/common/transforms.h>\r\n#include <pcl/common/time.h>\r\n#include <pcl/visualization/pcl_visualizer.h>\r\n#include <pcl/visualization/image_viewer.h>\r\n#include <pcl/point_types.h>\r\n#include <pcl/io/pcd_io.h>\r\n#include <pcl/io/dinast_grabber.h>\r\n\r\n#define FPS_CALC(_WHAT_) \\\r\ndo \\\r\n{ \\\r\n    static unsigned count = 0;\\\r\n    static double last = pcl::getTime ();\\\r\n    double now = pcl::getTime (); \\\r\n    ++count; \\\r\n    if (now - last >= 1.0) \\\r\n    { \\\r\n      std::cout << \"Average framerate(\"<< _WHAT_ << \"): \" << double(count)/double(now - last) << \" Hz\" <<  std::endl; \\\r\n      count = 0; \\\r\n      last = now; \\\r\n    } \\\r\n}while(false)\r\n\r\nvoid\r\nsavePGM (const unsigned char *image, const std::string& filename)\r\n{\r\n  FILE *file = fopen (filename.c_str (), \"w\");\r\n  if (!file)\r\n  {\r\n    std::cerr << \"Unable to open file '\" << filename << \"' for writing.\" << std::endl;\r\n    return;\r\n  }\r\n\r\n  // PGM header\r\n  fprintf (file, \"P2\\n%d %d\\n255\\n\", IMAGE_WIDTH, IMAGE_HEIGHT);\r\n\r\n  // Write data as ASCII\r\n  for (int i = 0; i < IMAGE_HEIGHT; ++i)\r\n  {\r\n    for (int j = 0; j < IMAGE_WIDTH; ++j)\r\n    {\r\n      fprintf (file, \"%3d \", (int)*image++);\r\n    }\r\n    fprintf (file, \"\\n\");\r\n  }\r\n\r\n  fclose (file);\r\n}\r\n\r\nvoid\r\nkeyboardEventOccurred (const pcl::visualization::KeyboardEvent &event, void* data)\r\n{\r\n  static int NUM_IMAGES = 0;\r\n  if (event.getKeySym () == \"s\" && event.keyDown ())\r\n  {\r\n    char filename[16];\r\n    snprintf (filename, sizeof(filename), \"image%.2d.pgm\", NUM_IMAGES++);\r\n    unsigned char *image = reinterpret_cast<unsigned char*> (data);\r\n    savePGM (image, filename);\r\n    printf (\"Wrote %s\\n\", filename);\r\n  }\r\n}\r\n\r\nvoid\r\nconvertImageToCloud (const unsigned char *image, pcl::PointCloud<pcl::PointXYZI> &cloud)\r\n{\r\n  cloud.points.resize (IMAGE_WIDTH * IMAGE_HEIGHT);\r\n  cloud.width = IMAGE_WIDTH;\r\n  cloud.height = IMAGE_HEIGHT;\r\n  cloud.is_dense = false;\r\n\r\n  int depth_idx = 0;\r\n  int pxl[9];\r\n\r\n  for (int x = 0; x < cloud.width; ++x)\r\n  {\r\n    for (int y = 0; y < cloud.height; ++y, ++depth_idx)\r\n    {\r\n      float xc = (float)(x - 160);\r\n      float yc = (float)(y - 120);\r\n      double r1 = sqrt (xc * xc + yc * yc);\r\n      double r2 = r1 * r1;\r\n      double r3 = r1 * r2;\r\n      double A = -2e-5 * r3 + 0.004 * r2 + 0.1719 * r1 + 350.03;\r\n      double B = -2e-9 * r3 + 3e-7 * r2 - 1e-5 * r1 - 0.01;\r\n\r\n      // Low pass filtering\r\n      /// @todo Try a bilateral filter to avoid blurring over depth boundaries\r\n      int measure = 0;\r\n      if ((y > 0) && (y < (IMAGE_HEIGHT - 1)) && (x > 0) && (x < (IMAGE_WIDTH - 1)))\r\n      {\r\n        int ipx = x + IMAGE_WIDTH * y;\r\n#if 1\r\n        pxl[0] = image[ipx];\r\n        pxl[1] = image[ipx-1];\r\n        pxl[2] = image[ipx+1];\r\n        pxl[3] = image[ipx - IMAGE_WIDTH];\r\n        pxl[4] = image[ipx - IMAGE_WIDTH - 1];\r\n        pxl[5] = image[ipx - IMAGE_WIDTH + 1];\r\n        pxl[6] = image[ipx + IMAGE_WIDTH];\r\n        pxl[7] = image[ipx + IMAGE_WIDTH - 1];\r\n        pxl[8] = image[ipx + IMAGE_WIDTH + 1];\r\n\r\n        for (int ii = 0; ii < 9; ii++) \r\n          measure += pxl[ii];\r\n        measure /= 9;\r\n#else\r\n        // No blurring\r\n        measure = image[ipx];\r\n#endif\r\n      }\r\n      if (measure > 255)\r\n        measure = 255;  // saturation for display\r\n\r\n      unsigned char pixel = measure;//image[depth_idx];\r\n      if (pixel < 1)\r\n      {\r\n        cloud.points[depth_idx].x = std::numeric_limits<float>::quiet_NaN ();\r\n        cloud.points[depth_idx].y = std::numeric_limits<float>::quiet_NaN ();\r\n        cloud.points[depth_idx].z = std::numeric_limits<float>::quiet_NaN ();\r\n        cloud.points[depth_idx].intensity = pixel;\r\n        continue;\r\n      }\r\n\r\n      if (pixel > A)\r\n        pixel = A;\r\n\r\n      float dy = y*0.1;\r\n      double dist = (log((double)pixel/A)/B-dy)*(7E-07*r3 - 0.0001*r2 + 0.004*r1 + 0.9985)*1.5;\r\n      double dist_2d = r1;\r\n\r\n      static const double dist_max_2d = 1 / 160.0; /// @todo Why not 200?\r\n      //static const double dist_max_2d = 1 / 200.0;\r\n      static const double FOV = 64.0 * M_PI / 180.0; // diagonal FOV?\r\n  \r\n      double theta_colati = FOV * r1 * dist_max_2d;\r\n      double c_theta = cos (theta_colati);\r\n      double s_theta = sin (theta_colati);\r\n      double c_ksai = ((double)(x - 160.)) / r1;\r\n      double s_ksai = ((double)(y - 120.)) / r1;\r\n\r\n      cloud.points[depth_idx].x = (dist * s_theta * c_ksai) / 500.0 + 0.5; //cartesian x\r\n      cloud.points[depth_idx].y = (dist * s_theta * s_ksai) / 500.0 + 0.5; //cartesian y\r\n      cloud.points[depth_idx].z = (dist * c_theta);                        //cartesian z\r\n      /// @todo This looks weird, can it cause artifacts?\r\n      if (cloud.points[depth_idx].z < 0.01)\r\n#if 1\r\n        cloud.points[depth_idx].z = 0.01;\r\n#else\r\n        cloud.points[depth_idx].x = std::numeric_limits<float>::quiet_NaN ();\r\n        cloud.points[depth_idx].y = std::numeric_limits<float>::quiet_NaN ();\r\n        cloud.points[depth_idx].z = std::numeric_limits<float>::quiet_NaN ();\r\n        cloud.points[depth_idx].intensity = pixel;\r\n        continue;\r\n#endif\r\n\r\n      cloud.points[depth_idx].z /= 500.0;\r\n      cloud.points[depth_idx].intensity = pixel;\r\n    }\r\n  }\r\n}\r\n\r\n/* --[ */ \r\n\r\nint\r\nmain (int argc, char** argv) \r\n{\r\n\r\n  pcl::DinastGrabber grabber;\r\n  \r\n  grabber.findDevice (1);\r\n  \r\n  grabber.openDevice();\r\n\r\n  std::cerr << \"Device version/revision number: \" << grabber.getDeviceVersion () << std::endl;\r\n  \r\n  grabber.start ();\r\n\r\n  pcl::visualization::ImageViewer vis_img (\"Dinast Image Viewer\");\r\n  pcl::visualization::PCLVisualizer vis_cld (argc, argv, \"Dinast Cloud Viewer\");\r\n\r\n  unsigned char *img1 = (unsigned char*)malloc (IMAGE_SIZE);\r\n  unsigned char *img2 = (unsigned char*)malloc (IMAGE_SIZE);\r\n\r\n  pcl::PointCloud<pcl::PointXYZI>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZI>);\r\n  \r\n  while (true)\r\n  {\r\n    if (grabber.readImage ( img1, img2) == 0)\r\n      continue;\r\n\r\n     convertImageToCloud (img1, *cloud);\r\n    \r\n    \r\n    FPS_CALC (\"grabber + visualization\");\r\n    vis_img.showMonoImage (img1, IMAGE_WIDTH, IMAGE_HEIGHT);\r\n    \r\n    pcl::visualization::PointCloudColorHandlerGenericField<pcl::PointXYZI> handler (cloud, \"intensity\");\r\n    if (!vis_cld.updatePointCloud (cloud, handler, \"DinastCloud\"))\r\n    {\r\n      vis_cld.addPointCloud (cloud, handler, \"DinastCloud\");\r\n      vis_cld.resetCameraViewpoint (\"DinastCloud\");\r\n    }\r\n\r\n    vis_img.spinOnce ();\r\n    vis_cld.spinOnce ();\r\n    \r\n  }\r\n  \r\n  grabber.stop ();\r\n  grabber.closeDevice ();\r\n\r\n}\r\n", "meta": {"hexsha": "3e2eee0d9ff57531fcd0fd996e4d404b165264bc", "size": 6596, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/src/dinast_grabber_example.cpp", "max_stars_repo_name": "zhangxaochen/CuFusion", "max_stars_repo_head_hexsha": "e8bab7a366b1f2c85a80b95093d195d9f0774c11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 52.0, "max_stars_repo_stars_event_min_datetime": "2017-09-05T13:31:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T08:48:29.000Z", "max_issues_repo_path": "apps/src/dinast_grabber_example.cpp", "max_issues_repo_name": "GucciPrada/CuFusion", "max_issues_repo_head_hexsha": "522920bcf316d1ddf9732fc71fa457174168d2fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-05-17T22:45:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-01T21:46:42.000Z", "max_forks_repo_path": "apps/src/dinast_grabber_example.cpp", "max_forks_repo_name": "GucciPrada/CuFusion", "max_forks_repo_head_hexsha": "522920bcf316d1ddf9732fc71fa457174168d2fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2015-07-27T13:00:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T08:18:41.000Z", "avg_line_length": 29.8461538462, "max_line_length": 120, "alphanum_fraction": 0.5729229836, "num_tokens": 1947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.27140251138810595}}
{"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__COMPAT__OSQP_HPP_\n#define SMOOTH__FEEDBACK__COMPAT__OSQP_HPP_\n\n/**\n * @file\n * @brief Solve quadratiac programs with OSQP.\n */\n\n#include <Eigen/Sparse>\n#include <osqp/osqp.h>\n\n#include \"smooth/feedback/qp_solver.hpp\"\n\nnamespace smooth::feedback {\n\n/**\n * @brief Solve a QuadraticProgram with the OSQP solver\n *\n * @param pbm QuadraticProgram to solve\n * @param prm solver paramters\n * @param warmstart initial point to start iterating from\n *\n * @return solution\n *\n * @note This is a convenience interface that performs copies and memory allocation in each\n * call. For more fine-grained control use the low-level OSQP interface (https://osqp.org/).\n */\ntemplate<typename Problem>\nQPSolution<-1, -1, double> solve_qp_osqp(\n  const Problem & pbm,\n  const QPSolverParams & prm,\n  std::optional<std::reference_wrapper<const QPSolution<-1, -1, double>>> warmstart = {})\n{\n  // Covert to sparse matrices with OSQP indexing\n  Eigen::SparseMatrix<double, Eigen::ColMajor, c_int> P;\n  Eigen::SparseMatrix<double, Eigen::ColMajor, c_int> A;\n  if constexpr (std::is_base_of_v<Eigen::SparseMatrixBase<decltype(pbm.A)>, decltype(pbm.A)>) {\n    A = pbm.A;\n    P = pbm.P.template triangularView<Eigen::Upper>();\n  } else {\n    A                   = pbm.A.sparseView();\n    Eigen::MatrixXd Pup = pbm.P.template triangularView<Eigen::Upper>();\n    P                   = Pup.sparseView();\n    A.prune(1e-6);\n    P.prune(1e-6);\n  }\n  A.makeCompressed();\n  P.makeCompressed();\n\n  OSQPSettings * settings = (OSQPSettings *)c_malloc(sizeof(OSQPSettings));\n  osqp_set_default_settings(settings);\n\n  settings->verbose            = prm.verbose;\n  settings->sigma              = prm.sigma;\n  settings->alpha              = prm.alpha;\n  settings->rho                = prm.rho;\n  settings->eps_abs            = prm.eps_abs;\n  settings->eps_rel            = prm.eps_rel;\n  settings->eps_prim_inf       = prm.eps_primal_inf;\n  settings->eps_dual_inf       = prm.eps_dual_inf;\n  settings->scaling            = prm.scaling;\n  settings->check_termination  = prm.stop_check_iter;\n  settings->polish             = prm.polish;\n  settings->polish_refine_iter = prm.polish_iter;\n  settings->delta              = prm.delta;\n\n  settings->adaptive_rho       = false;\n  settings->linsys_solver      = QDLDL_SOLVER;\n  settings->scaled_termination = false;\n\n  if (prm.max_iter) {\n    settings->max_iter = prm.max_iter.value();\n  } else {\n    settings->max_iter = std::numeric_limits<c_int>::max();\n  }\n  if (prm.max_time) {\n    settings->time_limit =\n      duration_cast<std::chrono::duration<double>>(prm.max_time.value()).count();\n  } else {\n    settings->time_limit = 0;\n  }\n\n  OSQPData * data = (OSQPData *)c_malloc(sizeof(OSQPData));\n  data->n         = A.cols();\n  data->m         = A.rows();\n  data->A         = csc_matrix(\n    A.rows(), A.cols(), A.nonZeros(), A.valuePtr(), A.innerIndexPtr(), A.outerIndexPtr());\n  data->q = const_cast<double *>(pbm.q.data());\n  data->P = csc_matrix(\n    P.rows(), P.cols(), P.nonZeros(), P.valuePtr(), P.innerIndexPtr(), P.outerIndexPtr());\n  data->l = const_cast<double *>(pbm.l.data());\n  data->u = const_cast<double *>(pbm.u.data());\n\n  OSQPWorkspace * work;\n\n  QPSolution<-1, -1, double> ret;\n  ret.code = QPSolutionStatus::Unknown;\n\n  c_int error = osqp_setup(&work, data, settings);\n\n  if (warmstart) {\n    osqp_warm_start(\n      work, warmstart.value().get().primal.data(), warmstart.value().get().dual.data());\n    settings->warm_start = 1;\n  } else {\n    settings->warm_start = 0;\n  }\n\n  if (!error) { error &= osqp_solve(work); }\n\n  if (!error) {\n    switch (work->info->status_val) {\n    case OSQP_SOLVED: {\n      ret.code = QPSolutionStatus::Optimal;\n      break;\n    }\n    case OSQP_PRIMAL_INFEASIBLE: {\n      ret.code = QPSolutionStatus::PrimalInfeasible;\n      break;\n    }\n    case OSQP_DUAL_INFEASIBLE: {\n      ret.code = QPSolutionStatus::DualInfeasible;\n      break;\n    }\n    case OSQP_MAX_ITER_REACHED: {\n      ret.code = QPSolutionStatus::MaxIterations;\n      break;\n    }\n    case OSQP_TIME_LIMIT_REACHED: {\n      ret.code = QPSolutionStatus::MaxTime;\n      break;\n    }\n    default: {\n      break;\n    }\n    }\n\n    ret.iter      = work->info->iter;\n    ret.primal    = Eigen::Map<const Eigen::Matrix<double, -1, 1>>(work->solution->x, data->n);\n    ret.dual      = Eigen::Map<const Eigen::Matrix<double, -1, 1>>(work->solution->y, data->m);\n    ret.objective = work->info->obj_val;\n  }\n\n  osqp_cleanup(work);\n\n  c_free(data->A);\n  c_free(data->P);\n  c_free(data);\n  c_free(settings);\n\n  return ret;\n}\n\n}  // namespace smooth::feedback\n\n#endif  // SMOOTH__FEEDBACK__COMPAT__OSQP_HPP_\n", "meta": {"hexsha": "c01f1da51bab8a655d55297693d319ed7f3ff785", "size": 5935, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/feedback/compat/osqp.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/compat/osqp.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/compat/osqp.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": 32.6098901099, "max_line_length": 95, "alphanum_fraction": 0.6675652906, "num_tokens": 1562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2712334235359007}}
{"text": "#include \"igl/readOBJ.h\"\n#include \"igl/writeOBJ.h\"\n// #include \"igl/decimate.h\"\n\n#include <Eigen/Core>\n\n#include \"pythonlike.h\"\n\n#include <cstdlib> // exit()\n#include <iostream>\n#include <cassert>\n#include <cstdio> // printf()\n\n#include <igl/seam_edges.h>\n#include \"decimate.h\"\n#include \"quadric_error_metric.h\"\n#include <igl/writeDMAT.h>\n\n// An anonymous namespace. This hides these symbols from other modules.\nnamespace {\n\nvoid usage( const char* argv0 )\n{\n    std::cerr << \"Usage: \" << argv0 << \" <path/to/input.obj> num-vertices     <target_number_of_vertices>  [--strict] [<strictness>]\" << std::endl;\n    std::cerr << \"Usage: \" << argv0 << \" <path/to/input.obj> percent-vertices <target_percent_of_vertices> [--strict] [<strictness>]\" << std::endl;\n    exit(-1);\n}\n\nint count_seam_edge_num(const EdgeMap& seam_vertex_edges)\n{\n\tint count = 0;\n\tfor(auto & v : seam_vertex_edges) {\n\t\tcount += v.second.size();\n\t}\n\treturn count / 2;\n}\n\nenum SeamAwareDegree\n{\n\tNoUVShapePreserving,\n\tUVShapePreserving,\n\tSeamless\n};\n\n/*\nDecimates a triangle mesh down to a target number of vertices,\npreserving the UV parameterization.\nTODO Q: Should we do a version that does not preserve the UV parameterization exactly,\n        but instead returns a sequence of TC/FTC that can be used to transform a UV\n        point between the parameterizations of the decimated and undecimated mesh?\nInput parameters:\n    V: The 3D positions of the input mesh (3 columns)\n    TC: The 2D texture coordinates of the input mesh (2 columns)\n    F: Indices into `V` for the three vertices of each triangle.\n    FTC: Indices into `TC` for the three vertices of each triangle.\nOutput parameters:\n    Vout: The 3D positions of the decimated mesh (3 columns),\n          where #vertices is as close as possible to `target_num_vertices`)\n    TCout: The texture coordinates of the decimated mesh (2 columns)\n    Fout: Indices into `Vout` for the three vertices of each triangle.\n    FTCout: Indices into `TCout` for the three vertices of each triangle.\nReturns:\n    True if the routine succeeded, false if an error occurred.\nNotes:\n    The output mesh will a vertex count as close as possible to `target_num_vertices`.\n    The decimated mesh should never have fewer vertices than `target_num_vertices`.\n*/\ntemplate <typename DerivedV, typename DerivedF, typename DerivedT>\nbool decimate_down_to(\n    const Eigen::PlainObjectBase<DerivedV>& V,\n    const Eigen::PlainObjectBase<DerivedF>& F,\n    const Eigen::PlainObjectBase<DerivedT>& TC,\n    const Eigen::PlainObjectBase<DerivedF>& FT,\n    int target_num_vertices,\n    Eigen::MatrixXd& V_out,\n    Eigen::MatrixXi& F_out,\n    Eigen::MatrixXd& TC_out,\n    Eigen::MatrixXi& FT_out,\n    int seam_aware_degree\n    )\n{\n#define DEBUG_DECIMATE_DOWN_TO\n    assert( target_num_vertices > 0 );\n    assert( target_num_vertices < V.rows() );\n    \n    /// 3D triangle mesh with UVs.\n    // 3D\n    assert( V.cols() == 3 );\n    // triangle mesh\n    assert( F.cols() == 3 );\n    // UVs\n    assert( TC.cols() == 2 );\n    assert( FT.cols() == 3 );\n    assert( FT.cols() == F.cols() );\n    \n    // Print information about seams.\n    Eigen::MatrixXi seams, boundaries, foldovers;\n    igl::seam_edges( V, TC, F, FT, seams, boundaries, foldovers );\n#ifdef DEBUG_DECIMATE_DOWN_TO\n    std::cout << \"seams: \" << seams.rows() << \"\\n\";\n    std::cout << seams << std::endl;\n    std::cout << \"boundaries: \" << boundaries.rows() << \"\\n\";\n    std::cout << boundaries << std::endl;\n    std::cout << \"foldovers: \" << foldovers.rows() << \"\\n\";\n    std::cout << foldovers << std::endl;\n#endif\n    \n    // Collect all vertex indices involved in seams.\n    std::unordered_set< int > seam_vertex_indices;\n    // Also collect the edges in terms of position vertex indices themselves.\n    EdgeMap seam_vertex_edges;\n    {\n\t\tfor( int i = 0; i < seams.rows(); ++i ) {\n\t\t    const int v1 = F( seams( i, 0 ),   seams( i, 1 ) );\n\t\t    const int v2 = F( seams( i, 0 ), ( seams( i, 1 ) + 1 ) % 3 );\n\t\t\tseam_vertex_indices.insert( v1 );\n\t\t\tseam_vertex_indices.insert( v2 );\n\t\t\tinsert_edge( seam_vertex_edges, v1, v2 );\n\t\t\t// The vertices on both sides should match:\n\t\t\tassert( seam_vertex_indices.count( F( seams( i, 2 ),   seams( i, 3 ) ) ) );\n\t\t\tassert( seam_vertex_indices.count( F( seams( i, 2 ), ( seams( i, 3 ) + 1 ) % 3 ) ) );\n\t\t}\n\t\tfor( int i = 0; i < boundaries.rows(); ++i ) {\n\t\t    const int v1 = F( boundaries( i, 0 ),   boundaries( i, 1 ) );\n\t\t    const int v2 = F( boundaries( i, 0 ), ( boundaries( i, 1 ) + 1 ) % 3 );\n\t\t\tseam_vertex_indices.insert( v1 );\n\t\t\tseam_vertex_indices.insert( v2 );\n\t\t\tinsert_edge( seam_vertex_edges, v1, v2 );\n\t\t}\n\t\tfor( int i = 0; i < foldovers.rows(); ++i ) {\n\t\t    const int v1 = F( foldovers( i, 0 ),   foldovers( i, 1 ) );\n\t\t    const int v2 = F( foldovers( i, 0 ), ( foldovers( i, 1 ) + 1 ) % 3 );\n\t\t\tseam_vertex_indices.insert( v1 );\n\t\t\tseam_vertex_indices.insert( v2 );\n\t\t\tinsert_edge( seam_vertex_edges, v1, v2 );\n\t\t\t// The vertices on both sides should match:\n\t\t\tassert( seam_vertex_indices.count( F( foldovers( i, 2 ),   foldovers( i, 3 ) ) ) );\n\t\t\tassert( seam_vertex_indices.count( F( foldovers( i, 2 ), ( foldovers( i, 3 ) + 1 ) % 3 ) ) );\n\t\t}\n\t\n\t    std::cout << \"# seam vertices: \" << seam_vertex_indices.size() << std::endl;\t\t\n\t\tstd::cout << \"# seam edges: \" << count_seam_edge_num(seam_vertex_edges) << std::endl;\n    }\n  \n    // Compute the per-vertex quadric error metric.\n    std::vector< Eigen::MatrixXd > Q;\n    bool success = false;\n    Eigen::VectorXi J;\n    \n\tMapV5d hash_Q;\n\thalf_edge_qslim_5d(V,F,TC,FT,hash_Q);\n\tstd::cout << \"computing initial metrics finished\\n\" << std::endl;\n\tsuccess = decimate_halfedge_5d(\n\t\tV, F,\n\t\tTC, FT,\n\t\tseam_vertex_edges,\n\t\thash_Q,\n\t\ttarget_num_vertices,\n\t\tseam_aware_degree,\n\t\tV_out, F_out,\n\t\tTC_out, FT_out\n\t\t);\n\tstd::cout << \"#seams after decimation: \" << count_seam_edge_num(seam_vertex_edges) << std::endl;\n    std::cout << \"#interior foldeover: \" << interior_foldovers.size() << std::endl;\n    std::cout << \"#exterior foldeover: \" << exterior_foldovers.size() << std::endl;\n    return success;\n}\n}\n\nint main( int argc, char* argv[] ) {\n    std::vector<std::string> args( argv + 1, argv + argc );\n    std::string strictness;\n    int seam_aware_degree = int( SeamAwareDegree::Seamless );\n    const bool found_strictness = pythonlike::get_optional_parameter( args, \"--strict\", strictness );\t\n\tif ( found_strictness ) {\n\t\tseam_aware_degree = atoi(strictness.c_str());\n\t}\n    \n    if( args.size() != 3 && args.size() != 4 )\tusage( argv[0] );\n    std::string input_path, command, command_parameter;\n    pythonlike::unpack( args.begin(), input_path, command, command_parameter );\n    args.erase( args.begin(), args.begin() + 3 );\n    \n    // Does the input path exist?\n    Eigen::MatrixXd V, TC, CN;\n    Eigen::MatrixXi F, FT, FN;\n    if( !igl::readOBJ( input_path, V, TC, CN, F, FT, FN ) ) {\n        std::cerr << \"ERROR: Could not read OBJ: \" << input_path << std::endl;\n        usage( argv[0] );\n    }\n\n    std::cout << \"Loaded a mesh with \" << V.rows() << \" vertices and \" << F.rows() << \" faces: \" << input_path << std::endl;\n    \n    // Get the target number of vertices.\n    int target_num_vertices = 0;\n    if( command == \"num-vertices\" ) {\n        // strto<> returns 0 upon failure, which is fine, since that is invalid input for us.\n        target_num_vertices = pythonlike::strto< int >( command_parameter );\n    }\n    else if( command == \"percent-vertices\" ) {\n        const double percent = pythonlike::strto< double >( command_parameter );\n        target_num_vertices = lround( ( percent * V.rows() )/100. );\n        std::cout << command_parameter << \"% of \" << std::to_string( V.rows() ) << \" input vertices is \" << std::to_string( target_num_vertices ) << \" output vertices.\" << std::endl;\n        // Ugh, printf() requires me to specify the types of integers versus longs.\n        // printf( \"%.2f%% of %d input vertices is %d output vertices.\", percent, V.rows(), target_num_vertices );\n    }\n    else {\n        std::cerr << \"ERROR: Unknown command: \" << command << std::endl;\n        usage( argv[0] );\n    }\n    \n    // Check that the target number of vertices is positive and fewer than the input number of vertices.\n    if( target_num_vertices <= 0 ) {\n        std::cerr << \"ERROR: Target number of vertices must be a positive integer: \" << argv[4] << std::endl;\n        usage( argv[0] );\n    }\n    if( target_num_vertices >= V.rows() ) {\n    \tstd::string output_path = pythonlike::os_path_splitext( input_path ).first + \"-decimated_to_\" + std::to_string( V.rows() ) + \"_vertices.obj\";\n        if( !igl::writeOBJ( output_path, V, F, CN, FN, TC, FT ) ) {\n\t\t\tstd::cerr << \"ERROR: Could not write OBJ: \" << output_path << std::endl;\n\t\t\tusage( argv[0] );\n\t\t}\n   \t\tstd::cout << \"Wrote: \" << output_path << std::endl;\n        std::cerr << \"ERROR: Target number of vertices must be smaller than the input number of vertices: \" << argv[4] << std::endl;\n        return 0;\n    }\n    \n    // Make the default output path.\n    std::string output_path = pythonlike::os_path_splitext( input_path ).first + \"-decimated_to_\" + std::to_string( target_num_vertices ) + \"_vertices.obj\";\n    if( !args.empty() ) {\n        output_path = args.front();\n        args.erase( args.begin() );\n    }\n    \n    // We should have consumed all arguments.\n    if( !args.empty() ) usage( argv[0] );\n    \n    // Decimate!\n    Eigen::MatrixXd V_out, TC_out, CN_out;\n    Eigen::MatrixXi F_out, FT_out, FN_out;\n    const bool success = decimate_down_to( V, F, TC, FT, target_num_vertices, V_out, F_out, TC_out, FT_out, seam_aware_degree );\n    if( !success ) {\n        std::cerr << \"WARNING: decimate_down_to() returned false (target number of vertices may have been unachievable).\" << std::endl;\n    }\n    \n    if( !igl::writeOBJ( output_path, V_out, F_out, CN_out, FN_out, TC_out, FT_out ) ) {\n        std::cerr << \"ERROR: Could not write OBJ: \" << output_path << std::endl;\n        usage( argv[0] );\n    }\n    std::cout << \"Wrote: \" << output_path << std::endl;\n    \n    return 0;\n}\n", "meta": {"hexsha": "50bb24000c82a66348b296d751f006ba0db4497c", "size": 10028, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "decimater.cpp", "max_stars_repo_name": "unclearness/SeamAwareDecimater", "max_stars_repo_head_hexsha": "c69934356ecdb0dd91070a6fc0520cdb0cc4d983", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 380.0, "max_stars_repo_stars_event_min_datetime": "2017-09-18T02:07:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:04:03.000Z", "max_issues_repo_path": "decimater.cpp", "max_issues_repo_name": "unclearness/SeamAwareDecimater", "max_issues_repo_head_hexsha": "c69934356ecdb0dd91070a6fc0520cdb0cc4d983", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2017-09-17T03:53:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-16T17:13:06.000Z", "max_forks_repo_path": "decimater.cpp", "max_forks_repo_name": "unclearness/SeamAwareDecimater", "max_forks_repo_head_hexsha": "c69934356ecdb0dd91070a6fc0520cdb0cc4d983", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 51.0, "max_forks_repo_forks_event_min_datetime": "2017-09-18T02:07:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-14T02:34:33.000Z", "avg_line_length": 39.4803149606, "max_line_length": 182, "alphanum_fraction": 0.6361188672, "num_tokens": 2830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2711683040967255}}
{"text": "﻿/*! \\file orbitaldensityrand.cpp\n    \\brief OrbitalDensityRandクラスの実装\n\n    Copyright © 2019-2021 @dc1394 All Rights Reserved.\n    (but this is originally adapted by サンマヤ for TDXHydrogenScene.cpp from http://sammaya.garyoutensei.com/math_phys/phys_sym/monte_hydrogen.html )\n    https://tsujimotter.hatenablog.com/entry/metropolis-hastings-algorithm も参考にさせて頂きました。ありがとうございます。\n    This software is released under the BSD 2-Clause License.\n*/\n\n#include \"orbitaldensityrand.h\"\n#include \"utility/utility.h\"\n#include <boost/assert.hpp>                                     // for boost::assert\n#include <boost/math/constants/constants.hpp>                   // for boost::math::constants::pi\n#include <boost/math/special_functions/spherical_harmonic.hpp>  // for boost::math::spherical_harmonic\n#include <boost/range/algorithm.hpp>                            // for boost::fill\n\nnamespace orbitaldensityrand {\n    // #region コンストラクタ\n\n\tOrbitalDensityRand::OrbitalDensityRand(std::shared_ptr<getdata::GetData> const & pgd)\n        :   Complete([this] { return complete_.load(); }, nullptr),\n            Dt([this] { return dt_; }, [this](auto dt) { return dt_ = dt; }),\n            Elapsed_time([this] { return count_ * dt_; }, nullptr),\n            Pth([this] { return std::cref(pth_); }, nullptr),\n\t\t    Redraw(nullptr, [this](auto redraw) { return redraw_ = redraw; }),\n            Rmax([this] { return rmax_; }, nullptr),\n            Thread_end(nullptr, [this](auto thread_end) { \n\t\t\t    thread_end_.store(thread_end);\n\t\t\t    return thread_end; }),\n            Vertex([this] { return std::cref(vertex_); }, nullptr),\n\t\t    Vertexsize([this]{ return vertexsize_.load(); }, [this](std::vector<SimpleVertex>::size_type size) { \n\t\t\t\tvertexsize_.store(size);\n\t\t\t\treturn size; }),\n            pgd_(pgd),\n            q0_({ 1.0, 1.0, 0.0 }),\n            q_(q0_),\n\t\t    rmax_(GetRmax(pgd)),\n\t\t    vertex_(pgd_->Rho_wf_type == getdata::GetData::Rho_Wf_type::RHO ? RHO_VERTEXSIZE_INIT_VALUE : WF_VERTEXSIZE_INIT_VALUE),\n            vertexsize_(pgd_->Rho_wf_type == getdata::GetData::Rho_Wf_type::RHO ? RHO_VERTEXSIZE_INIT_VALUE : WF_VERTEXSIZE_INIT_VALUE)\n    {\n    }\n\n    // #endregion コンストラクタ\n\n    // #region privateメンバ関数\n\n    void OrbitalDensityRand::operator()(std::int32_t m, Normal_Nelson_type nornel)\n    {\n        if (redraw_) {\n            if (vertex_.size() != vertexsize_) {\n                vertex_.resize(vertexsize_);\n            }\n\n            pth_.reset(new std::thread([this, m, nornel] { ClearFillSimpleVertex(m, nornel); }), [this](std::thread * pth)\n            {\n                if (pth->joinable()) {\n                    thread_end_.store(true);\n                    pth->join();\n                }\n\n                utility::Safe_Delete<std::thread> sd;\n                sd(pth);\n            });\n            redraw_ = false;\n        }\n    }\n\n\tvoid OrbitalDensityRand::ClearFillSimpleVertex(std::int32_t m, Normal_Nelson_type nornel)\n\t{\n\t\tcomplete_.store(false);\n\n\t\tSimpleVertex sv{};\n\t\tsv.Color = { 0.0f, 0.0f, 0.0f, 0.0f };\n\t\tsv.Pos = { 0.0f, 0.0f, 0.0f };\n\t\tboost::fill(vertex_, sv);\n\n        switch (nornel)\n        {\n        case Normal_Nelson_type::NORMAL:\n            {\n                auto const threads = static_cast<std::int32_t>(std::thread::hardware_concurrency());\n                auto const num = static_cast<std::int32_t>(vertexsize_.load() / threads);\n\n                auto thvec = std::vector<std::thread>(threads);\n                for (auto i = 0; i < threads - 1; i++) {\n                    thvec[i] = std::thread([i, m, num, this]() { FillSimpleVertex(m, num * i, num * (i + 1)); });\n                }\n                thvec[threads - 1] = std::thread([m, num, threads, this]() { FillSimpleVertex(m, num * (threads - 1), static_cast<std::int32_t>(vertexsize_.load())); });\n\n                for (auto && th : thvec) {\n                    th.join();\n                }\n            }\n            break;\n\n        case Normal_Nelson_type::NELSON:\n            FillSimpleVertex(m);\n            break;\n\n        default:\n            BOOST_ASSERT(!\"nornelが異常!\");\n            break;\n        }\n        \n\t\tcomplete_.store(true);\n\t}\n\n    void OrbitalDensityRand::FillSimpleVertex(std::int32_t m)\n    {\n        using namespace boost::math;\n        using namespace constants;\n\n        auto const actual_dt = dt_ * ATTOSECTOAU;\n\n        count_ = 0U;\n        do {\n            if (thread_end_) {\n                return;\n            }\n\n            auto const r = std::hypot(q_[0], q_[1], q_[2]);\n\n            if (r < pgd_->R_meshmin() || r > pgd_->R_meshmax()) {\n                Resetq();\n                continue;\n            }\n\n            double phi = 0.0;\n            if (std::fabs(q_[1]) < THRESHOLD) {\n                if (q_[0] < 0.0) {\n                    phi = boost::math::constants::pi<double>();\n                }\n            }\n            else if (q_[0] * q_[0] + q_[1] * q_[1] > 0.0) {\n                auto const sign = q_[1] > 0 ? 1 : -1;\n                phi = sign * std::acos(q_[0] / std::sqrt(q_[0] * q_[0] + q_[1] * q_[1]));\n            }\n            auto const theta = std::acos(q_[2] / r);\n\n            auto const ylm = Spherical_harmonic(pgd_->L, m, theta, phi);\n            auto const dylmdtheta = Numerical_diff(\n                theta,\n                myfunctional::make_functional([this, m, phi](double th) { return Spherical_harmonic(pgd_->L, m, th, phi); }));\n\n            if (std::fabs(ylm) < THRESHOLD && std::fabs(dylmdtheta) < THRESHOLD) {\n                Resetq();\n                continue;\n            }\n\n            auto const dylmdphi = Numerical_diff(\n                phi,\n                myfunctional::make_functional([this, m, theta](double ph) { return Spherical_harmonic(pgd_->L, m, theta, ph); }));\n\n            if (std::fabs(ylm) < THRESHOLD && std::fabs(dylmdphi) < THRESHOLD) {\n                Resetq();\n                continue;\n            }\n\n            auto f_x = std::sin(theta) * std::cos(phi) * pgd_->dphidr(r) / (*pgd_)(r);\n            f_x += std::cos(theta) * std::cos(phi) / r * dylmdtheta / ylm;\n            f_x -= std::sin(phi) / (r * std::sin(theta)) * dylmdphi / ylm;\n\n            auto f_y = std::sin(theta) * std::sin(phi) * pgd_->dphidr(r) / (*pgd_)(r);\n            f_y += std::cos(theta) * std::sin(phi) / r * dylmdtheta / ylm;\n            f_y += std::cos(phi) / (r * std::sin(theta)) * dylmdphi / ylm;\n\n            auto f_z = std::cos(theta) * pgd_->dphidr(r) / (*pgd_)(r);\n            f_z -= std::sin(theta) / r * dylmdtheta / ylm;\n\n            q_[0] += f_x * actual_dt + mr_.normal_distribution_rand() * std::sqrt(actual_dt);\n            q_[1] += f_y * actual_dt + mr_.normal_distribution_rand() * std::sqrt(actual_dt);\n            q_[2] += f_z * actual_dt + mr_.normal_distribution_rand() * std::sqrt(actual_dt);\n\n            vertex_[count_].Pos.x = static_cast<float>(q_[0]);\n            vertex_[count_].Pos.y = static_cast<float>(q_[1]);\n            vertex_[count_].Pos.z = static_cast<float>(q_[2]);\n\n            vertex_[count_].Color.x = 0.8f;\n            vertex_[count_].Color.y = 0.0f;\n            vertex_[count_].Color.z = 0.8f;\n            vertex_[count_].Color.w = 1.0f;\n\n            count_++;\n        } while (count_ < vertexsize_.load());\n    }\n\n\tvoid OrbitalDensityRand::FillSimpleVertex(std::int32_t m, std::int32_t starti, std::int32_t endi)\n\t{\n\t\tif (thread_end_) {\n\t\t\treturn;\n\t\t}\n\n\t\tauto sign = 1;\n\t\tauto x = 0.0;\n        auto y = 0.0;\n        auto z = 0.0;\n\n        myrandom::MyRandSfmt mr;\n                \n        auto nextflag = false;\n        auto count_ = 0;\n\n        do {\n            if (thread_end_) {\n                return;\n            }\n\n            switch (pgd_->Rho_wf_type) {\n            case getdata::GetData::Rho_Wf_type::RHO:\n            {\n                auto rho = [this, m, nextflag](auto x, auto y, auto z) mutable\n                {\n                    auto const r = std::sqrt(x * x + y * y + z * z);\n                    if (r < pgd_->R_meshmin()) {\n                        nextflag = true;\n                        return 0.0;\n                    }\n\n                    double phi = 0.0;\n                    if (std::fabs(y) < EPS) {\n                        if (x < 0.0) {\n                            phi = boost::math::constants::pi<double>();\n                        }\n                    }\n                    else if (x * x + y * y > 0.0) {\n                        auto const sign = y > 0 ? 1 : -1;\n                        phi = sign * std::acos(x / std::sqrt(x * x + y * y));\n                    }\n\n                    auto const ylm = Spherical_harmonic(pgd_->L, m, std::acos(z / r), phi);\n\n                    return (*pgd_)(r) * ylm * ylm;\n                };\n\n                auto const maxr = pgd_->R2rhomaxr();\n\n                auto const x_star = mr.normal_distribution_rand(x, maxr);\n                auto const y_star = mr.normal_distribution_rand(y, maxr);\n                auto const z_star = mr.normal_distribution_rand(z, maxr);\n\n                auto const rho_t = rho(x, y, z);    // xの電子密度\n                if (nextflag) {\n                    x = x_star;\n                    y = y_star;\n                    z = z_star;\n                    nextflag = false;\n                    continue;\n                }\n\n                auto const rho_star = rho(x_star, y_star, z_star);  // x* の電子密度\n\n                // 採択率を計算  α = p(x*) / p(x_t)\n                auto const alpha = (rho_star * rho_star) / (rho_t * rho_t);\n\n                // 採択率により決定\n                auto const ar = mr.myrand();    // 0 <= ar <= 1 の一様乱数 ar を生成\n                if (ar <= alpha) {              // 採択\n                    x = x_star;\n                    y = y_star;\n                    z = z_star;\n                    if (rho_star >= 0.0) {\n                        sign = 1;\n                    }\n                    else {\n                        sign = -1;\n                    }\n                }\n            }\n            break;\n\n            case getdata::GetData::Rho_Wf_type::WF:\n            {\n                auto phi = [this, m, nextflag](auto x, auto y, auto z) mutable\n                {\n                    auto const r = std::sqrt(x * x + y * y + z * z);\n                    if (r < pgd_->R_meshmin()) {\n                        nextflag = true;\n                        return 0.0;\n                    }\n\n                    double phi = 0.0;\n                    if (std::fabs(y) < EPS) {\n                        if (x < 0.0) {\n                            phi = boost::math::constants::pi<double>();\n                        }\n                    }\n                    else if (x * x + y * y > 0.0) {\n                        auto const sign = y > 0 ? 1 : -1;\n                        phi = sign * std::acos(x / std::sqrt(x * x + y * y));\n                    }\n\n                    return (*pgd_)(r) * Spherical_harmonic(pgd_->L, m, std::acos(z / r), phi);\n                };\n\n                auto const maxr = pgd_->R2rhomaxr();\n\n                auto const x_star = mr.normal_distribution_rand(x, maxr);\n                auto const y_star = mr.normal_distribution_rand(y, maxr);\n                auto const z_star = mr.normal_distribution_rand(z, maxr);\n\n                auto const phi_t = phi(x, y, z);    // xの波動関数\n                if (nextflag) {\n                    x = x_star;\n                    y = y_star;\n                    z = z_star;\n                    nextflag = false;\n                    continue;\n                }\n\n                auto const phi_star = phi(x_star, y_star, z_star);  // x* の波動関数\n\n                // 採択率を計算  α = p(x*) / p(x_t)\n                auto const alpha = (phi_star * phi_star) / (phi_t * phi_t);\n\n                //採択率により決定\n                auto const ar = mr.myrand();    // 0 <= ar <= 1 の一様乱数 ar を生成\n                if (ar <= alpha) {              // 採択\n                    x = x_star;\n                    y = y_star;\n                    z = z_star;\n                    if (phi_star >= 0.0) {\n                        sign = 1;\n                    }\n                    else {\n                        sign = -1;\n                    }\n                }\n                else {                          // 採択しない\n                    continue;\n                }\n            }\n            break;\n\n            default:\n                BOOST_ASSERT(!\"何かがおかしい!\");\n                break;\n            }\n\n            vertex_[starti + count_].Pos.x = static_cast<float>(x);\n            vertex_[starti + count_].Pos.y = static_cast<float>(y);\n            vertex_[starti + count_].Pos.z = static_cast<float>(z);\n\n            vertex_[starti + count_].Color.x = sign > 0 ? 0.8f : 0.0f;\n            vertex_[starti + count_].Color.y = sign < 0 ? 0.8f : 0.0f;\n            vertex_[starti + count_].Color.z = 0.8f;\n            vertex_[starti + count_].Color.w = 1.0f;\n            count_++;\n\t\t} while (count_ < (endi - starti));\n\t}\n\n    // #endregion privateメンバ関数\n\n    // #region フリー関数\n\n\tdouble GetRmax(std::shared_ptr<getdata::GetData> const & pgd)\n\t{\n\t\tauto const n = static_cast<double>(pgd->N);\n\t\treturn (2.3622 * n + 3.3340) * n + 1.3228;\n\t}\n\n    double Spherical_harmonic(std::int32_t l, std::int32_t m, double theta, double phi)\n    {\n        if (!m) {\n            return boost::math::spherical_harmonic_r(l, m, theta, phi);\n        }\n        else if (m > 0) {\n            auto const sign = (m & 1 ? -1 : 1);\n            return (sign * boost::math::spherical_harmonic_r(l, m, theta, phi) + boost::math::spherical_harmonic_r(l, -m, theta, phi)) / std::sqrt(2.0);\n        }\n        else {\n            m = -m;\n            auto const sign = (m & 1 ? -1 : 1);\n            return (sign * boost::math::spherical_harmonic_i(l, m, theta, phi) - boost::math::spherical_harmonic_i(l, -m, theta, phi)) / std::sqrt(2.0);\n        }\n    }\n\n    // #endregion フリー関数\n}\n", "meta": {"hexsha": "a628ce9b1a9c969c8d9c668b7125d5ed7c300274", "size": 13759, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SchracVisualize2/orbitaldensityrand/orbitaldensityrand.cpp", "max_stars_repo_name": "dc1394/SchracVisualize_Direct3D_11", "max_stars_repo_head_hexsha": "b1b8418efeab2ada1d38c86dd3205fcd2ef7cba2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-07-04T10:53:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T12:20:33.000Z", "max_issues_repo_path": "SchracVisualize2/orbitaldensityrand/orbitaldensityrand.cpp", "max_issues_repo_name": "dc1394/SchracVisualize2", "max_issues_repo_head_hexsha": "b1b8418efeab2ada1d38c86dd3205fcd2ef7cba2", "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": "SchracVisualize2/orbitaldensityrand/orbitaldensityrand.cpp", "max_forks_repo_name": "dc1394/SchracVisualize2", "max_forks_repo_head_hexsha": "b1b8418efeab2ada1d38c86dd3205fcd2ef7cba2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-04T11:44:57.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-04T11:44:57.000Z", "avg_line_length": 36.3034300792, "max_line_length": 169, "alphanum_fraction": 0.463841849, "num_tokens": 3757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2711683040967255}}
{"text": "#ifndef EDMONDS_OPTIMUM_BRANCHING_IMPL_HPP\n#define EDMONDS_OPTIMUM_BRANCHING_IMPL_HPP\n\n#include <vector>\n#include <algorithm>\n#include <list>\n#include <boost/property_map/property_map.hpp>\n#include <boost/foreach.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/concept_check.hpp>\n#include <boost/pending/disjoint_sets.hpp>\n\n\n\n// namespace detail\n//\n// The namespace encapsulates classes and/or functions that are\n// required for the implementation of edmonds's optimum branching\n// algorithm which should not be visible to the user. This way the\n// global namespace remains unpolluted.\nnamespace detail {\n    using namespace boost;\n\n\n\n    // class OptimumBranching\n    //\n    // I encapsulate all the details of edmonds's algorithm inside a\n    // class. This makes the code easier to read (and easier to write)\n    // since the number of template declarations is reduced\n    // considerably. Besides, all the utility functions used to\n    // implement one algorithm conceptually do belong together.\n    //\n    // Note that any concept checks are performed in the function that\n    // uses this class, so there is no need to repeat them here.\n    template <bool TOptimumIsMaximum,\n              bool TAttemptToSpan,\n              bool TGraphIsDense,\n              class TEdgeListGraph,\n              class TVertexIndexMap,\n              class TWeightMap,\n              class TInputIterator,\n              class TOutputIterator>\n    class OptimumBranching {\n    public:\n        typedef TEdgeListGraph                                        Graph;\n        typedef typename graph_traits<Graph>::edge_descriptor         Edge;\n        typedef typename graph_traits<Graph>::vertex_descriptor       Vertex;\n        typedef typename graph_traits<Graph>::edge_iterator           EdgeIter;\n        typedef typename property_traits<TWeightMap>::value_type      weight_t;\n        typedef typename property_traits<TVertexIndexMap>::value_type vertex_idx_t;\n\n\n\n        // struct EdgeNode\n        //\n        // One unique EdgeNode object is created for each edge of the\n        // input graph. Any containers then store pointers to these\n        // objects. The edges of the graph F (which is described in\n        // the document describing the implementation) are stored in\n        // each EdgeNode object via the parent and children members.\n        // For efficiency reasons a boolean member 'removed_from_F' is\n        // also present in each EdgeNode object. If this member is\n        // set, then the edge (which is also a vertex in F) was\n        // removed during the expansion phase of the algorithm.\n        struct EdgeNode {\n            Edge                        edge;\n            vertex_idx_t                source;\n            vertex_idx_t                target;\n            weight_t                    weight;\n            EdgeNode                   *parent;\n            std::vector<EdgeNode *>     children;\n            bool                        removed_from_F;\n\n            EdgeNode(const Edge &e,\n                     const vertex_idx_t &s,\n                     const vertex_idx_t &t,\n                     const weight_t w)\n                : edge(e), source(s), target(t), weight(w), parent(0),\n                  removed_from_F(false)\n            {\n                ;\n            }\n\n            // operator<\n            //\n            // This is only used temporarily when sorting the\n            // EdgeNodes by their sources. Once a radix-sort algorithm\n            // has been implemented, this is no longer needed.\n            bool        operator<(const EdgeNode &en) const\n            {\n                return source < en.source;\n            }\n        };\n\n\n\n        // The data members of the OptimumBranching class. These\n        // include both the input and the variables needed internally for the implemenationa.\n        const TEdgeListGraph   &g;\n        const TVertexIndexMap  &index;\n        const TWeightMap       &weight;\n        TInputIterator          roots_begin;\n        TInputIterator          roots_end;\n        TOutputIterator         out;\n\n        // The constructor\n        OptimumBranching(const TEdgeListGraph &g,\n                         const TVertexIndexMap &index,\n                         const TWeightMap &weight,\n                         TInputIterator roots_begin,\n                         TInputIterator roots_end,\n                         TOutputIterator out)\n            : g(g), index(index), weight(weight),\n              roots_begin(roots_begin), roots_end(roots_end), out(out)\n        {\n            ;\n        }\n\n\n\n        // remove_from_F()\n        //\n        // It removes the EdgeNode en and all its ancestors from the\n        // graph F (by resetting the parent and children members and\n        // setting the flag removed_from_F). Any newly created roots\n        // of F are inserted into F_roots. Note that the root of F\n        // that is removed as a consequence is not actually removed\n        // from F_roots. It is simply marked as removed via the\n        // 'removed_from_F' flag.\n        void remove_from_F(EdgeNode *en, std::vector<EdgeNode *> &F_roots)\n        {\n            // Note that en is inserted into F_roots as well. But\n            // since it is marked as removed_from_F it will not cause\n            // any trouble. This is more efficient than making sure\n            // that only the siblings of en are inserted into F_roots.\n            for ( ; en != 0; en = en->parent)\n            {\n                en->removed_from_F = true;\n                BOOST_FOREACH (EdgeNode *child, en->children)\n                {\n                    F_roots.push_back(child);\n                    child->parent = 0;\n                }\n\n                // free the memory used in en->children.\n                std::vector<EdgeNode *>().swap(en->children);\n            }\n        }\n\n\n        // sort_edges()\n        //\n        // sorts a vector of EdgeNode pointers with EdgeNode.source as\n        // key using the radix-sort algorithm. Also, if there are\n        // several EdgeNode pointers with the same source, the\n        // function only keeps the one with optimum weight.\n        void sort_edges(std::vector<EdgeNode *> &edge_vec)\n        {\n            const int byte_len = 8;\n            const int num_buckets = 1u << byte_len;\n            const unsigned digits = (sizeof (vertex_idx_t)) * std::numeric_limits<unsigned char>::digits;\n            const unsigned mask = (1u << byte_len) - 1;\n\n            std::vector< std::list<EdgeNode *> > buckets(num_buckets);\n\n            for (unsigned i = 0; byte_len * i <= digits; ++i)\n            {\n                BOOST_FOREACH (EdgeNode *en, edge_vec)\n                {\n                    buckets[(en->source >> byte_len * i) & mask].push_back(en);\n                }\n\n                edge_vec.clear();\n                BOOST_FOREACH (std::list<EdgeNode *> &bucket, buckets)\n                {\n                    BOOST_FOREACH (EdgeNode *en, bucket)\n                    {\n                        if (!edge_vec.empty() && edge_vec.back()->source == en->source)\n                        {\n                            bool en_is_better = TOptimumIsMaximum ?\n                                en->weight > edge_vec.back()->weight :\n                                en->weight < edge_vec.back()->weight;\n                            if (en_is_better)\n                            {\n                                edge_vec.back() = en;\n                            }\n                        }\n                        else\n                        {\n                            edge_vec.push_back(en);\n                        }\n                    }\n                }\n\n                buckets.clear();\n                buckets.resize(num_buckets);\n            }\n        }\n\n\n        // operator()\n        //\n        // This is the main function implementing Tarjan's\n        // implementation of Edmonds's algorithm.\n        void operator()()\n        {\n            std::vector<EdgeNode> all_edges;\n            vertex_idx_t max_vertex_idx;\n\n            // Create EdgeNodes for all the edges and find the maximum vertex\n            // index. Note that we skip self-loops.\n            max_vertex_idx = 0;\n            BOOST_FOREACH (const Edge &e, edges(g))\n            {\n                if (source(e, g) == target(e, g))\n                    continue;\n\n                all_edges.push_back(EdgeNode (e, source(e, g), target(e, g), get(weight, e)));\n                max_vertex_idx = std::max(max_vertex_idx, index[target(e, g)]);\n            }\n\n            // insert into in_edges[v] all edges entering v.\n\n            //!! TODO !! If sparse graphs, I have to change the\n            //representation of in_edges to a special kind of priority\n            //queue that are able to be merged in log n time.\n\n            std::vector< std::vector<EdgeNode *> > in_edges(max_vertex_idx + 1);\n            std::vector<weight_t> edge_weight_change(max_vertex_idx + 1);\n            BOOST_FOREACH (EdgeNode &en, all_edges)\n            {\n                in_edges[en.target].push_back(&en);\n            }\n            BOOST_FOREACH (std::vector<EdgeNode *> &edges, in_edges)\n            {\n                sort_edges(edges);\n            }\n\n            // Save the specified roots in a random access fashion.\n            std::vector<bool> is_specified_root(max_vertex_idx + 1);\n            std::vector<vertex_idx_t> final_roots;\n            for ( ; roots_begin != roots_end; ++roots_begin)\n            {\n                is_specified_root[index[*roots_begin]] = true;\n                final_roots.push_back(index[*roots_begin]);\n            }\n\n            // Initialize S, W, roots, cycles, lambda, enter, F, and min\n            std::vector< std::vector<EdgeNode *> > cycle(max_vertex_idx + 1);\n            std::vector<EdgeNode *> lambda(max_vertex_idx + 1);\n            std::vector<vertex_idx_t> roots;\n            disjoint_sets_with_storage<> S(2*(max_vertex_idx +1));\n            disjoint_sets_with_storage<> W(2*(max_vertex_idx +1));\n            std::vector<vertex_idx_t> min(max_vertex_idx + 1);\n            std::vector<EdgeNode *> enter(max_vertex_idx + 1);\n            std::vector<EdgeNode *> F;\n            for (vertex_idx_t v = 0; v <= max_vertex_idx; ++v)\n            {\n                S.make_set(v);\n                W.make_set(v);\n                min[v] = v;\n                if (!is_specified_root[v])\n                    roots.push_back(v);\n            }\n\n            // Keep adding critical edges and contracting cycles while\n            // doing a whole bunch of book-keeping.\n            while (!roots.empty())\n            {\n                // Find an S-component with an entering edge\n                vertex_idx_t cur_root = roots.back(); roots.pop_back();\n                if (in_edges[cur_root].empty())\n                {\n                    final_roots.push_back(min[cur_root]);\n                    continue;\n                }\n\n                // Find an optimum-weight edge entering cur_root\n\n                //!! TODO !! We have to do this differently for sparse graphs.\n                EdgeNode *critical_edge = in_edges[cur_root].front();\n                BOOST_FOREACH (EdgeNode *en, in_edges[cur_root])\n                {\n                    bool en_is_better = TOptimumIsMaximum ?\n                        en->weight > critical_edge->weight :\n                        en->weight < critical_edge->weight;\n                    if (en_is_better)\n                    {\n                        critical_edge = en;\n                    }\n                }\n\n                // Do not add critical_edge if it worsens the total\n                // weight and we are not attempting to span.\n                if (!TAttemptToSpan)\n                {\n                    bool improves = TOptimumIsMaximum ?\n                        critical_edge->weight > weight_t(0) :\n                        critical_edge->weight < weight_t(0);\n                    if (!improves)\n                    {\n                        final_roots.push_back(min[cur_root]);\n                        continue;\n                    }\n                }\n\n                // Insert critical_edge into \"F\" and let any edges in\n                // cycle[cur_root] be its children.\n                F.push_back(critical_edge);\n                BOOST_FOREACH (EdgeNode *en, cycle[cur_root])\n                {\n                    en->parent = critical_edge;\n                    critical_edge->children.push_back(en);\n                }\n\n                // If critical_edge is a leaf in \"F\", then add a\n                // pointer to it.\n                if (cycle[cur_root].empty())\n                {\n                    lambda[cur_root] = critical_edge;\n                }\n\n                // If adding critical_edge didn't create a cycle\n                if (W.find_set(critical_edge->source) !=\n                    W.find_set(critical_edge->target))\n                {\n                    enter[cur_root] = critical_edge;\n                    W.union_set(critical_edge->source, critical_edge->target);\n                }\n                else // If adding critical_edge did create a cycle\n                {\n                    // Find the edges of the cycle, the\n                    // representatives of the strong components in the\n                    // cycle, and the least costly edge of the cycle.\n                    std::vector<EdgeNode *> cycle_edges;\n                    std::vector<vertex_idx_t> cycle_repr;\n                    EdgeNode *least_costly_edge = critical_edge;\n                    enter[cur_root] = 0;\n\n                    cycle_edges.push_back(critical_edge);\n                    cycle_repr.push_back(S.find_set(critical_edge->target));\n                    for (vertex_idx_t v = S.find_set(critical_edge->source);\n                         enter[v] != 0; v = S.find_set(enter[v]->source))\n                    {\n                        cycle_edges.push_back(enter[v]);\n                        cycle_repr.push_back(v);\n                        bool is_less_costly = TOptimumIsMaximum ?\n                            enter[v]->weight < least_costly_edge->weight :\n                            enter[v]->weight > least_costly_edge->weight;\n                        if (is_less_costly)\n                        {\n                            least_costly_edge = enter[v];\n                        }\n                    }\n                    // change the weight of the edges entering\n                    // vertices of the cycle.\n                    //!! TODO !! Change this for sparse graphs\n                    BOOST_FOREACH (EdgeNode *en, cycle_edges)\n                    {\n                        edge_weight_change[S.find_set(en->target)] =\n                            least_costly_edge->weight - en->weight;\n                    }\n\n                    // Save the vertex that would be root if the newly\n                    // created strong component would be a root.\n                    vertex_idx_t cycle_root =\n                        min[S.find_set(least_costly_edge->target)];\n\n                    // Union all components of the cycle into one component.\n                    vertex_idx_t new_repr = cycle_repr.front();\n                    BOOST_FOREACH (vertex_idx_t v, cycle_repr)\n                    {\n                        S.link(v, new_repr);\n                        new_repr = S.find_set(new_repr);\n                    }\n                    min[new_repr] = cycle_root;\n                    roots.push_back(new_repr);\n                    cycle[new_repr].swap(cycle_edges);\n\n                    //!! TODO !! Needs to be changed for sparse graphs.\n                    BOOST_FOREACH (vertex_idx_t v, cycle_repr)\n                    {\n                        BOOST_FOREACH (EdgeNode *en, in_edges[v])\n                        {\n                            en->weight += edge_weight_change[v];\n                        }\n                    }\n\n                    // Merge all in_edges of the cycle into one list.\n                    //!! TODO !! needs to be changed for sparse graphs.\n                    std::vector<EdgeNode *> new_in_edges;\n                    for (unsigned i = 1; i < cycle_repr.size(); ++i)\n                    {\n                        typedef typename std::vector<EdgeNode *>::iterator Iter;\n                        Iter i1 = in_edges[cycle_repr[i]].begin();\n                        Iter e1 = in_edges[cycle_repr[i]].end();\n                        Iter i2 = in_edges[cycle_repr[i-1]].begin();\n                        Iter e2 = in_edges[cycle_repr[i-1]].end();\n\n                        ///*\n                        while (i1 != e1 || i2 != e2)\n                        {\n                            while (i1 != e1 && S.find_set((*i1)->source) == new_repr)\n                            {\n                                ++i1;\n                            }\n                            while (i2 != e2 && S.find_set((*i2)->source) == new_repr)\n                            {\n                                ++i2;\n                            }\n\n                            if (i1 == e1 && i2 == e2)\n                                break;\n\n                            if (i1 == e1)\n                            {\n                                new_in_edges.push_back(*i2);\n                                ++i2;\n                            }\n                            else if (i2 == e2)\n                            {\n                                new_in_edges.push_back(*i1);\n                                ++i1;\n                            }\n                            else if (((*i1)->source) < ((*i2)->source))\n                            {\n                                new_in_edges.push_back(*i1);\n                                ++i1;\n                            }\n                            else if ((*i1)->source > (*i2)->source)\n                            {\n                                new_in_edges.push_back(*i2);\n                                ++i2;\n                            }\n                            else // if the sources are equal\n                            {\n                                bool i1_is_better = TOptimumIsMaximum ?\n                                    (*i1)->weight > (*i2)->weight :\n                                    (*i1)->weight < (*i2)->weight;\n                                if (i1_is_better)\n                                {\n                                    new_in_edges.push_back(*i1);\n                                }\n                                else\n                                {\n                                    new_in_edges.push_back(*i2);\n                                }\n                                ++i1;\n                                ++i2;\n                            }\n                        }\n                        in_edges[cycle_repr[i]].swap(new_in_edges);\n                        new_in_edges.clear();\n                    }\n                    in_edges[new_repr].swap(in_edges[cycle_repr.back()]);\n                    edge_weight_change[new_repr] = weight_t(0);\n                    //*/\n                }\n            } // while (!roots.empty())\n\n            // Extract the optimum branching\n\n            // Find all roots of F.\n            std::vector<EdgeNode *> F_roots;\n            BOOST_FOREACH (EdgeNode *en, F)\n            {\n                if (en->parent == 0)\n                {\n                    F_roots.push_back(en);\n                }\n            }\n\n            // Remove edges entering the root nodes.\n            BOOST_FOREACH (vertex_idx_t v, final_roots)\n            {\n                if (lambda[v] != 0)\n                {\n                    remove_from_F(lambda[v], F_roots);\n                }\n            }\n\n            while (!F_roots.empty())\n            {\n                EdgeNode *en = F_roots.back(); F_roots.pop_back();\n                if (en->removed_from_F)\n                    continue;\n\n                *out = en->edge;\n                ++out;\n                remove_from_F(lambda[en->target], F_roots);\n            }\n        }\n\n    };\n}\n\ntemplate <bool TOptimumIsMaximum,\n          bool TAttemptToSpan,\n          bool TGraphIsDense,\n          class TEdgeListGraph,\n          class TVertexIndexMap,\n          class TWeightMap,\n          class TInputIterator,\n          class TOutputIterator>\nvoid\nedmonds_optimum_branching(TEdgeListGraph &g,\n                          TVertexIndexMap index,\n                          TWeightMap weight,\n                          TInputIterator roots_begin,\n                          TInputIterator roots_end,\n                          TOutputIterator out)\n{\n    using namespace boost;\n\n    typedef typename graph_traits<TEdgeListGraph>::edge_descriptor    Edge;\n    typedef typename graph_traits<TEdgeListGraph>::vertex_descriptor  Vertex;\n    typedef typename graph_traits<TEdgeListGraph>::edge_iterator      EdgeIter;\n    typedef typename property_traits<TWeightMap>::value_type          weight_t;\n\n    function_requires< EdgeListGraphConcept<TEdgeListGraph> >();\n    function_requires< ReadablePropertyMapConcept<TWeightMap, Edge> >();\n    function_requires< ReadablePropertyMapConcept<TVertexIndexMap, Vertex> >();\n    function_requires< InputIteratorConcept<TInputIterator> >();\n    function_requires< OutputIteratorConcept<TOutputIterator, Edge> >();\n    //!! Add the following requirements:\n    //\n    // property_traits<TVertexIndexMap>::value_type is a built-in\n    // integral type, or perhaps require that it can be used to index\n    // into arrays.\n    //\n    // property_traits<TWeightMap>::value_type is a numeric type that\n    // handles the operations +, -, and <.\n    //\n    // TInputIterator's value type is Vertex\n    // TOutputIterator's value type is Edge\n\n\n    ::detail::OptimumBranching<TOptimumIsMaximum, TAttemptToSpan,\n        TGraphIsDense, TEdgeListGraph, TVertexIndexMap, TWeightMap,\n        TInputIterator, TOutputIterator>\n          optimum_branching(g, index, weight, roots_begin, roots_end, out);\n    optimum_branching();\n}\n\n\n\n\n#endif // not EDMONDS_OPTIMUM_BRANCHING_IMPL_HPP\n", "meta": {"hexsha": "8108ac2acb865cf732886fb5dd85cb655cc00cfb", "size": 22070, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "task1/edmonds_optimum_branching_impl.hpp", "max_stars_repo_name": "garncarz/prague-transport-2017", "max_stars_repo_head_hexsha": "f758a0f5a2e920bc5df8da74d4c55914c07d9fe3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "task1/edmonds_optimum_branching_impl.hpp", "max_issues_repo_name": "garncarz/prague-transport-2017", "max_issues_repo_head_hexsha": "f758a0f5a2e920bc5df8da74d4c55914c07d9fe3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "task1/edmonds_optimum_branching_impl.hpp", "max_forks_repo_name": "garncarz/prague-transport-2017", "max_forks_repo_head_hexsha": "f758a0f5a2e920bc5df8da74d4c55914c07d9fe3", "max_forks_repo_licenses": ["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.054446461, "max_line_length": 105, "alphanum_fraction": 0.4828726778, "num_tokens": 4214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2711683040967255}}
{"text": "/*\n *            Copyright 2009-2017 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// Overload of uBLAS prod function with MKL/GSL implementations\n#include <votca/tools/linalg.h>\n#include <votca/xtp/aomatrix.h>\n#include <votca/xtp/bsecoupling.h>\n#include <votca/tools/constants.h>\n#include <boost/format.hpp>\n\n\n\nnamespace votca { namespace xtp {\n\nnamespace ub = boost::numeric::ublas;\nusing boost::format;\n\nvoid BSECoupling::Initialize(Property* options){\n    \n    #if (GWBSE_DOUBLE)\n        CTP_LOG(ctp::logDEBUG, *_pLog) <<  \" Compiled with full double support\" << flush;   \n    #else\n        CTP_LOG(ctp::logDEBUG, *_pLog) <<  \" Compiled with float/double mixture (standard)\" << flush;   \n    #endif\n    \n    std::string key = Identify(); \n    _doSinglets=false;\n    _doTriplets=false;\n   _output_perturbation=false;\n    \n    \n    _openmp_threads = 0;\n    \n    if ( options->exists( key + \".openmp\") ) {\n                 _openmp_threads = options->get(key + \".openmp\").as<int> ();\n            }\n    \n    string spintype   = options->get(key + \".spin\").as<string> ();\n        if(spintype==\"all\"){\n            _doSinglets=true;\n            _doTriplets=true;\n        }\n        else if(spintype==\"triplet\"){\n            _doTriplets=true;\n        }\n        else if(spintype==\"singlet\"){\n            _doSinglets=true;\n        }\n        else{\n            throw std::runtime_error((boost::format(\"Choice % for type not known. Available singlet,triplet,all\") % spintype).str());\n        }\n    _degeneracy = options->get(key + \".degeneracy\").as<double> ();\n     \n     \n   if ( options->exists( key + \".algorithm\") ) {\n                string algorithm = options->get(key + \".algorithm\").as<string> ();\n                 if(algorithm==\"perturbation\"){\n                    _output_perturbation=true;\n                 }\n   }\n    \n   \n    \n        _levA  = options->get(key + \".moleculeA.states\").as<int> ();\n        _levB  = options->get(key + \".moleculeB.states\").as<int> ();\n        _occA  = options->get(key + \".moleculeA.occLevels\").as<int> ();\n        _occB  = options->get(key + \".moleculeB.occLevels\").as<int> ();\n        _unoccA  = options->get(key + \".moleculeA.unoccLevels\").as<int> ();\n        _unoccB  = options->get(key + \".moleculeB.unoccLevels\").as<int> ();\n        \n   \n        \n        \n}\n\nvoid BSECoupling::addoutput(Property *_type_summary,Orbitals* _orbitalsA, \n                               Orbitals* _orbitalsB){\n   \n    string algorithm=\"full_diag\";\n    int methodindex=1;\n    if (_output_perturbation){\n        algorithm=\"perturbation\";\n        methodindex=0;\n    }\n    _type_summary->setAttribute(\"algorithm\",algorithm);\n    if (_doSinglets){\n        Property *_singlet_summary = &_type_summary->add(\"singlets\",\"\");\n        for (int stateA = 0; stateA < _levA ; ++stateA ) {\n           for (int stateB = 0; stateB <_levB ; ++stateB ) {\n               double JAB = getSingletCouplingElement( stateA , stateB, methodindex);\n              \n               Property *_coupling_summary = &_singlet_summary->add(\"coupling\", (format(\"%1$1.6e\") % JAB).str()); \n               double energyA = _orbitalsA->BSESingletEnergies()(stateA)*conv::hrt2ev;\n               double energyB = _orbitalsB->BSESingletEnergies()(stateB)*conv::hrt2ev;\n               _coupling_summary->setAttribute(\"excitonA\", stateA);\n               _coupling_summary->setAttribute(\"excitonB\", stateB);\n               _coupling_summary->setAttribute(\"energyA\", (format(\"%1$1.6e\") % energyA).str());\n               _coupling_summary->setAttribute(\"energyB\", (format(\"%1$1.6e\") % energyB).str());\n               _coupling_summary->setAttribute(\"pert\", (format(\"%1$1.6e\") % getSingletCouplingElement( stateA , stateB, 0)).str());\n               _coupling_summary->setAttribute(\"diag\", (format(\"%1$1.6e\") % getSingletCouplingElement( stateA , stateB, 1)).str());\n               \n           } \n        }\n    }\n    \n    \n    if ( _doTriplets){\n        Property *_triplet_summary = &_type_summary->add(\"triplets\",\"\");\n        for (int stateA = 0; stateA < _levA ; ++stateA ) {\n           for (int stateB = 0; stateB < _levA ; ++stateB ) {\n               double JAB = getTripletCouplingElement( stateA , stateB,methodindex );\n               //real_gwbse energyAD = getTripletDimerEnergy( stateA  );\n               //real_gwbse energyBD = getTripletDimerEnergy( stateB  );\n               Property *_coupling_summary = &_triplet_summary->add(\"coupling\", (format(\"%1$1.6e\") % JAB).str()); \n               double energyA = _orbitalsA->BSETripletEnergies()(stateA)*conv::hrt2ev;\n               double energyB = _orbitalsB->BSETripletEnergies()(stateB)*conv::hrt2ev;\n               _coupling_summary->setAttribute(\"excitonA\", stateA);\n               _coupling_summary->setAttribute(\"excitonB\", stateB);\n               _coupling_summary->setAttribute(\"energyA\", (format(\"%1$1.6e\") % energyA).str());\n               _coupling_summary->setAttribute(\"energyB\", (format(\"%1$1.6e\") % energyB).str());\n               _coupling_summary->setAttribute(\"pert\", (format(\"%1$1.6e\") % getTripletCouplingElement( stateA , stateB, 0)).str());\n               _coupling_summary->setAttribute(\"diag\", (format(\"%1$1.6e\") % getTripletCouplingElement( stateA , stateB, 1)).str());\n              \n           } \n        }\n    }       \n}\n\n\ndouble BSECoupling::getSingletCouplingElement( int levelA, int levelB, int methodindex) {\n    return JAB_singlet[methodindex]( levelA  , levelB +  _levA ) * votca::tools::conv::hrt2ev;\n}\n\n\n\ndouble BSECoupling::getTripletCouplingElement( int levelA, int levelB, int methodindex) {\n\n    return JAB_triplet[methodindex]( levelA  , levelB + _levA ) * votca::tools::conv::hrt2ev;\n}\n\n\n/**\n * \\brief evaluates electronic couplings  \n *   \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 * @param _JAB matrix with electronic couplings\n * @return false if failed\n */\nbool BSECoupling::CalculateCouplings(Orbitals* _orbitalsA, Orbitals* _orbitalsB, Orbitals* _orbitalsAB) {\n       CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \"  Calculating exciton couplings\" << flush;\n     // set the parallelization \n    #ifdef _OPENMP\n    \n    if ( _openmp_threads > 0 ) omp_set_num_threads(_openmp_threads);      \n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \" Using \"<< omp_get_max_threads()<<\" threads\" << flush;\n    #endif\n    \n    \n    \n    _orbitalsAB->setCoupledExcitonsA(_levA);\n    _orbitalsAB->setCoupledExcitonsB(_levB);\n    //check to see if ordering of atoms agrees\n    const std::vector<ctp::QMAtom*> atomsA=_orbitalsA->QMAtoms();\n    const std::vector<ctp::QMAtom*> atomsB=_orbitalsB->QMAtoms();\n    const std::vector<ctp::QMAtom*> atomsAB=_orbitalsAB->QMAtoms();\n    \n    for (unsigned i=0;i<atomsAB.size();i++){\n        ctp::QMAtom* dimer=atomsAB[i];\n        ctp::QMAtom* monomer=NULL;\n        if (i<atomsA.size()){\n            monomer=atomsA[i];\n        }\n        else if (i<atomsB.size()+atomsA.size() ){\n            monomer=atomsB[i-atomsA.size()];\n        }\n        else{\n            throw runtime_error((boost::format(\"Number of Atoms in dimer %3i and the two monomers A:%3i B:%3i does not agree\") %atomsAB.size() %atomsA.size() %atomsB.size()).str());\n        }\n        \n        if(monomer->type != dimer->type){\n            throw runtime_error(\"\\nERROR: Atom types do not agree in dimer and monomers\\n\");\n        }\n        if(std::abs(monomer->x-dimer->x)>0.001 || std::abs(monomer->y-dimer->y)>0.001 || std::abs(monomer->z-dimer->z)>0.001){\n            CTP_LOG(ctp::logERROR,*_pLog) << \"======WARNING=======\\n Coordinates of monomers and dimer atoms do not agree, do you know what you are doing?\\n \" << flush;\n            break;\n        }\n        \n    }\n    \n    \n    // constructing the direct product orbA x orbB\n    int _basisA = _orbitalsA->getBasisSetSize();\n    int _basisB = _orbitalsB->getBasisSetSize();\n    \n    if ( ( _basisA == 0 ) || ( _basisB == 0 ) ) {\n        CTP_LOG(ctp::logERROR,*_pLog) << \"Basis set size is not stored in monomers\" << flush;\n        return false;\n    }\n\n    // number of levels stored in monomers\n    int _levelsA = _orbitalsA->getNumberOfLevels();\n    int _levelsB = _orbitalsB->getNumberOfLevels();\n    \n        \n    // get exciton information of molecule A\n    int _bseA_cmax        = _orbitalsA->getBSEcmax();\n    int _bseA_cmin        = _orbitalsA->getBSEcmin();\n    int _bseA_vmax        = _orbitalsA->getBSEvmax();\n    int _bseA_vmin        = _orbitalsA->getBSEvmin();\n    int _bseA_vtotal      = _bseA_vmax - _bseA_vmin +1 ;\n    int _bseA_ctotal      = _bseA_cmax - _bseA_cmin +1 ;\n    int _bseA_size        = _bseA_vtotal * _bseA_ctotal;\n    int _bseA_singlet_exc = _orbitalsA->BSESingletCoefficients().size2();\n    int _bseA_triplet_exc = _orbitalsA->BSETripletCoefficients().size2();\n\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()   << \"   molecule A has \" << _bseA_singlet_exc << \" singlet excitons with dimension \" << _bseA_size << flush;\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()   << \"   molecule A has \" << _bseA_triplet_exc << \" triplet excitons with dimension \" << _bseA_size << flush;\n    \n    // now, two storage assignment matrices for two-particle functions\n    ub::matrix<int> _combA;\n    _combA.resize(_bseA_size,2);\n    int _cnt = 0;\n    for ( int _v = 0; _v < _bseA_vtotal; _v++){\n        for ( int _c = 0; _c < _bseA_ctotal; _c++){\n            _combA(_cnt,0) = _v;\n            _combA(_cnt,1) = _bseA_vtotal + _c;\n            _cnt++;\n        }\n    }\n    \n    // get exciton information of molecule B\n    int _bseB_cmax        = _orbitalsB->getBSEcmax();\n    int _bseB_cmin        = _orbitalsB->getBSEcmin();\n    int _bseB_vmax        = _orbitalsB->getBSEvmax();\n    int _bseB_vmin        = _orbitalsB->getBSEvmin();\n    int _bseB_vtotal      = _bseB_vmax - _bseB_vmin +1 ;\n    int _bseB_ctotal      = _bseB_cmax - _bseB_cmin +1 ;\n    int _bseB_size        = _bseB_vtotal * _bseB_ctotal;\n    int _bseB_singlet_exc = _orbitalsB->BSESingletCoefficients().size2();\n    int _bseB_triplet_exc = _orbitalsB->BSETripletCoefficients().size2();\n    \n\n    \n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()   << \"   molecule B has \" << _bseB_singlet_exc << \" singlet excitons with dimension \" << _bseB_size << flush;\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()   << \"   molecule B has \" << _bseB_triplet_exc << \" triplet excitons with dimension \" << _bseB_size << flush;\n    \n    // now, two storage assignment matrices for two-particle functions\n    ub::matrix<int> _combB;\n    _combB.resize(_bseB_size,2);\n    _cnt = 0;\n    for ( int _v = 0; _v < _bseB_vtotal; _v++){\n        for ( int _c = 0; _c < _bseB_ctotal; _c++){\n            _combB(_cnt,0) = _bseA_vtotal + _bseA_ctotal + _v;\n            _combB(_cnt,1) = _bseA_vtotal + _bseA_ctotal + _bseB_vtotal + _c;\n            _cnt++;\n        }\n    }\n    \n    if(_levA>_bseA_singlet_exc){\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \"  Number of excitons you want is greater than stored for molecule A. Setting to max number available\" << flush; \n        _levA=_bseA_singlet_exc;\n    }\n    if(_levB>_bseB_singlet_exc){\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \"  Number of excitons you want is greater than stored for molecule B. Setting to max number available\" << flush; \n        _levB=_bseB_singlet_exc;\n    }\n    \n    \n    if(_levA>_bseA_singlet_exc){\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \"  Number of Frenkel states you want is greater than stored for molecule A. Setting to max number available\" << flush; \n        _levA=_bseA_singlet_exc;\n    }\n    if(_levB>_bseB_singlet_exc){\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \"  Number of Frenkel states you want is greater than stored for molecule B. Setting to max number available\" << flush; \n        _levB=_bseB_singlet_exc;\n    }\n    \n    if(_unoccA>_bseA_ctotal){\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \"  Number of occupied orbitals in molecule A for CT creation exceeds number of KS-orbitals in BSE\" << flush; \n        _unoccA=_bseA_ctotal;\n    }\n    else if (_unoccA<0){\n        _unoccA=_bseA_ctotal;\n    }\n    if(_unoccB>_bseB_ctotal){\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \"  Number of occupied orbitals in molecule B for CT creation exceeds number of KS-orbitals in BSE\" << flush; \n        _unoccB=_bseB_ctotal;\n    }\n    else if (_unoccB<0){\n        _unoccB=_bseB_ctotal;\n    }\n    \n    if(_occA>_bseA_vtotal){\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \"  Number of unoccupied orbitals in molecule A for CT creation exceeds number of KS-orbitals in BSE\" << flush; \n        _occA=_bseA_vtotal;\n    }\n    else if (_occA<0){\n        _occA=_bseA_vtotal;\n    }\n    if(_occB>_bseB_vtotal){\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \"  Number of unoccupied orbitals in molecule B for CT creation exceeds number of KS-orbitals in BSE\" << flush; \n        _occB=_bseB_vtotal;\n    }else if (_occB<0){\n        _occB=_bseB_vtotal;\n    }\n    \n    \n   \n    \n    // get exciton information of pair AB\n    int _bseAB_cmax = _orbitalsAB->getBSEcmax();\n    int _bseAB_cmin = _orbitalsAB->getBSEcmin();\n    int _bseAB_vmax = _orbitalsAB->getBSEvmax();\n    int _bseAB_vmin = _orbitalsAB->getBSEvmin();\n    int _bseAB_vtotal = _bseAB_vmax - _bseAB_vmin +1 ;\n    int _bseAB_ctotal = _bseAB_cmax - _bseAB_cmin +1 ;\n    int _bseAB_size   = _bseAB_vtotal * _bseAB_ctotal;\n    // check if electron-hole interaction matrices are stored\n    if ( ! _orbitalsAB->hasEHinteraction() ){\n        CTP_LOG(ctp::logERROR,*_pLog) << \"BSE EH int not stored in dimer \" << flush;\n        return false;\n    }\n    const ub::matrix<real_gwbse>&    _eh_d = _orbitalsAB->eh_d(); \n    const ub::matrix<real_gwbse>&    _eh_x = _orbitalsAB->eh_x(); \n    \n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()   << \"   dimer AB has BSE EH interaction (direct)   with dimension \" << _eh_d.size1() << \" x \" <<  _eh_d.size2() << flush;\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()   << \"   dimer AB has BSE EH interaction (exchange) with dimension \" << _eh_x.size1() << \" x \" <<  _eh_x.size2() << flush;\n    // now, two storage assignment matrices for two-particle functions\n    ub::matrix<int> _combAB;\n    _combAB.resize(_bseAB_size,2);\n    _cnt = 0;\n    for ( int _v = 0; _v < _bseAB_vtotal; _v++){\n        for ( int _c = 0; _c < _bseAB_ctotal; _c++){\n            //_combAB(_cnt,0) = _v;\n            //_combAB(_cnt,1) = _bseAB_vtotal + _c;\n            \n            _combAB(_cnt,0) = _bseAB_vmin + _v;\n            _combAB(_cnt,1) = _bseAB_vmin + _bseAB_vtotal + _c;\n            \n            _cnt++;\n        }\n    }\n    \n    \n\n    \n    // DFT levels of monomers can be reduced to those used in BSE\n    _levelsA = _bseA_vtotal + _bseA_ctotal;\n    _levelsB = _bseB_vtotal + _bseB_ctotal;\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \"   levels used in BSE of molA: \" << _bseA_vmin << \" to \" << _bseA_cmax << \" total: \" << _bseA_vtotal + _bseA_ctotal <<  flush;\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \"   levels used in BSE of molB: \" << _bseB_vmin << \" to \" << _bseB_cmax << \" total: \" << _bseB_vtotal + _bseB_ctotal <<  flush;\n    \n    \n    if ( ( _levelsA == 0 ) || (_levelsB == 0) ) {\n        CTP_LOG(ctp::logERROR,*_pLog) << \"No information about number of occupied/unoccupied levels is stored\" << flush;\n        return false;\n    } \n    \n    //       | Orbitals_A          0 |      | Overlap_A |     \n    //       | 0          Orbitals_B |  X   | Overlap_B |  X  Transpose( Orbitals_AB )\n    ub::zero_matrix<double> zeroB( _levelsA, _basisB ) ;\n    ub::zero_matrix<double> zeroA( _levelsB, _basisA ) ;\n    ub::matrix<double> _psi_AxB ( _levelsA + _levelsB, _basisA + _basisB  );\n    \n    // constructing merged orbitals\n    ub::project( _psi_AxB, ub::range (0, _levelsA ), ub::range ( _basisA, _basisA +_basisB ) ) = zeroB;\n    ub::project( _psi_AxB, ub::range (_levelsA, _levelsA + _levelsB ), ub::range ( 0, _basisA ) ) = zeroA;    \n    ub::project( _psi_AxB, ub::range (0, _levelsA ), ub::range ( 0, _basisA ) ) = ub::project( _orbitalsA->MOCoefficients() , ub::range(_bseA_vmin, _bseA_cmax+1) , ub::range ( 0, _basisA ));\n    ub::project( _psi_AxB, ub::range (_levelsA, _levelsA + _levelsB ), ub::range ( _basisA, _basisA + _basisB ) ) = ub::project( _orbitalsB->MOCoefficients(), ub::range(_bseB_vmin, _bseB_cmax+1) , ub::range ( 0, _basisB )); \n    \n    // psi_AxB * S_AB * psi_AB\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \"   projecting monomer onto dimer orbitals\" << flush; \n    \n     ub::matrix<double> _overlapAB;\n    if ( !_orbitalsAB->hasAOOverlap() ) {\n            CTP_LOG(ctp::logDEBUG,*_pLog) << \"Reading overlap matrix from orbitals\" << flush; \n           _overlapAB= _orbitalsAB->AOOverlap();\n    }else{\n        CTP_LOG(ctp::logDEBUG,*_pLog) << \"Calculating overlap matrix for basisset: \"<< _orbitalsAB->getDFTbasis()<< flush; \n        BasisSet _dftbasisset;\n        AOBasis _dftbasis;\n        _dftbasisset.LoadBasisSet(_orbitalsAB->getDFTbasis());\n\n        _dftbasis.AOBasisFill(&_dftbasisset, _orbitalsAB->QMAtoms());\n        AOOverlap _dftAOoverlap;\n        _dftAOoverlap.Fill(_dftbasis);\n        _overlapAB=_dftAOoverlap.Matrix();\n    }\n    \n    ub::matrix<double> _psi_AB = ub::prod( _overlapAB,ub::trans(_orbitalsAB->MOCoefficients()) );  \n    ub::matrix<double> _psi_AxB_dimer_basis = ub::prod( _psi_AxB, _psi_AB );  \n    _psi_AB.resize(0,0);\n    _overlapAB.resize(0,0);\n    //cout<< \"_psi_AxB_dimer\"<<endl;\n    unsigned int LevelsA = _levelsA;\n    for (unsigned i=0;i<_psi_AxB_dimer_basis.size1();i++){\n        double mag=0.0;\n        for (unsigned j=0;j<_psi_AxB_dimer_basis.size2();j++){\n            mag+=_psi_AxB_dimer_basis(i,j)*_psi_AxB_dimer_basis(i,j);\n            \n    }\n         if (mag<0.95){\n            int monomer = 0;\n            int level = 0;\n            if ( i < LevelsA ) {\n                monomer = 1;\n                level   = _bseA_vmin + i;\n            } else {\n                monomer = 2;\n                level   = _bseB_vmin + i -_levelsA;\n                \n            }\n            CTP_LOG(ctp::logERROR,*_pLog) << \"\\nERROR: \" << i << \" Projection of orbital \" << level << \" of monomer \" << monomer << \" on dimer is insufficient,mag=\"<<mag<<\" maybe the orbital order is screwed up, otherwise increase dimer basis.\\n\"<<flush;\n        }\n    }\n   \n    \n    //notation AB is CT states with A+B-, BA is the counterpart\n    //Setting up CT-states:\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \"   Setting up CT-states\" << flush; \n    //Number of A+B- states\n    int noAB=_occA*_unoccB;\n    //Number of A-B+ states\n    int noBA=_unoccA*_occB;\n    \n    \n    ub::matrix<int> comb_CTAB;\n    comb_CTAB.resize(noAB,2);\n    _cnt = 0;\n    \n\n    \n    \n    // iterate A over occupied, B over unoccupied\n    int v_start=_bseA_vtotal-_occA;\n    for ( int _v = v_start; _v < _bseA_vtotal; _v++){\n        for ( int _c = 0; _c <_unoccB; _c++){            \n            comb_CTAB(_cnt,0) =_v;\n            comb_CTAB(_cnt,1) = _bseA_vtotal+_bseA_ctotal+_bseB_vtotal + _c;\n           \n            _cnt++;\n        }\n    }\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  <<\"  \"<<noAB <<\" CT states A+B- created\" << flush;\n \n    ub::matrix<int> comb_CTBA;\n    comb_CTBA.resize(noBA,2);\n    _cnt = 0;\n    // iterate A over unoccupied, B over occupied\n    v_start=_bseB_vtotal-_occB;\n    for ( int _v = v_start; _v < _bseB_vtotal; _v++){\n        for ( int _c = 0; _c <_unoccA; _c++){            \n            comb_CTBA(_cnt,0) =_bseA_vtotal+_bseA_ctotal+_v;\n            comb_CTBA(_cnt,1) = _bseA_vtotal+ _c;\n            \n            _cnt++;\n        }\n    }\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  <<\"  \"<<noBA <<\" CT states B+A- created\" << flush;\n    \n    \n    \n    // these 4 matrixes, matrix(i,j) contains the j-th dimer MO component of the i-th excitation\n   \n    ctAB.resize(noAB,_bseAB_size);\n    #pragma omp parallel for\n    for ( int _i_CT = 0 ; _i_CT < noAB ; _i_CT++){\n    for ( int _i_bseAB = 0 ; _i_bseAB < _bseAB_size ; _i_bseAB++){\n        ctAB(_i_CT,_i_bseAB)=_psi_AxB_dimer_basis( comb_CTAB(_i_CT,0), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( comb_CTAB(_i_CT,1), _combAB( _i_bseAB,1) );\n        }\n    }\n    \n    \n    ctBA.resize(noBA,_bseAB_size);\n    #pragma omp parallel for\n    for ( int _i_CT = 0 ; _i_CT < noBA ; _i_CT++){\n    for ( int _i_bseAB = 0 ; _i_bseAB < _bseAB_size ; _i_bseAB++){\n        ctBA(_i_CT,_i_bseAB)=_psi_AxB_dimer_basis( comb_CTBA(_i_CT,0), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( comb_CTBA(_i_CT,1), _combAB( _i_bseAB,1) );\n        }\n    }\n    \n      \n    // some more convenient storage\n    \n    \n    _kap.resize(_bseA_size,_bseAB_size);\n    #pragma omp parallel for\n    for ( int _i_bseA = 0 ; _i_bseA < _bseA_size ; _i_bseA++){\n        for ( int _i_bseAB = 0 ; _i_bseAB < _bseAB_size ; _i_bseAB++){\n            _kap(_i_bseA,_i_bseAB) = _psi_AxB_dimer_basis( _combA(_i_bseA,0), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( _combA(_i_bseA,1), _combAB( _i_bseAB,1) );\n            \n        }\n    }\n\n    \n    \n\n    _kbp.resize(_bseB_size,_bseAB_size);\n    #pragma omp parallel for\n    for ( int _i_bseB = 0 ; _i_bseB < _bseB_size ; _i_bseB++){\n        for ( int _i_bseAB = 0 ; _i_bseAB < _bseAB_size ; _i_bseAB++){\n            _kbp(_i_bseB,_i_bseAB) = _psi_AxB_dimer_basis( _combB(_i_bseB,0), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( _combB(_i_bseB,1), _combAB( _i_bseAB,1) );\n        }\n    }\n    \n    // Same routines but also take <v|c'> <c|v'> projections into account \n    /*\n \n    _kap.resize(_bseA_size,_bseAB_size);\n    for ( int _i_bseA = 0 ; _i_bseA < _bseA_size ; _i_bseA++){\n        for ( int _i_bseAB = 0 ; _i_bseAB < _bseAB_size ; _i_bseAB++){\n            _kap(_i_bseA,_i_bseAB) = _psi_AxB_dimer_basis( _combA(_i_bseA,0), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( _combA(_i_bseA,1), _combAB( _i_bseAB,1) )+\n              _psi_AxB_dimer_basis( _combA(_i_bseA,1), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( _combA(_i_bseA,0), _combAB( _i_bseAB,1) )     ;\n            \n        }\n    }\n\n    \n\n    \n   \n    _kbp.resize(_bseB_size,_bseAB_size);\n    for ( int _i_bseB = 0 ; _i_bseB < _bseB_size ; _i_bseB++){\n        for ( int _i_bseAB = 0 ; _i_bseAB < _bseAB_size ; _i_bseAB++){\n            _kbp(_i_bseB,_i_bseAB) = _psi_AxB_dimer_basis( _combB(_i_bseB,0), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( _combB(_i_bseB,1), _combAB( _i_bseAB,1) )+\n                    _psi_AxB_dimer_basis( _combB(_i_bseB,1), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( _combB(_i_bseB,0), _combAB( _i_bseAB,1) );\n        }\n    }\n    */ \n  \n\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()   << \"   construct projection of product functions \" << flush; \n\n   \n    \n        \n    //     cout << \"Size of _kap \" << _kap.size1() << \" : \" <<  _kap.size2() << \"\\n\" << flush; \n    //     cout << \"Size of _kbp \" << _kbp.size1() << \" : \" <<  _kbp.size2() << \"\\n\" << flush; \n    _psi_AxB_dimer_basis.resize(0,0);\n    _combAB.resize(0,0);\n    _combA.resize(0,0);\n    _combB.resize(0,0);\n    // now the different spin types\n            if (_doSinglets) {\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \"   Evaluating singlets\" << flush;\n                // get singlet BSE Hamiltonian from _orbitalsAB\n                ub::matrix<double> _Hamiltonian_AB = _eh_d + 2.0 * _eh_x;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \"   Setup Hamiltonian\" << flush;\n                ub::matrix<real_gwbse> temp = ub::project(_orbitalsA->BSESingletCoefficients(),\n                        ub::range(0, _orbitalsA->BSESingletCoefficients().size1()), ub::range(0, _levA));\n\n                const ub::matrix<double> _bseA_T = ub::trans(temp);\n                temp = ub::project(_orbitalsB->BSESingletCoefficients(),\n                        ub::range(0, _orbitalsB->BSESingletCoefficients().size1()), ub::range(0, _levB));\n                const ub::matrix<double> _bseB_T = ub::trans(temp);\n                temp.resize(0, 0);\n                \n                JAB_singlet = ProjectExcitons(_bseA_T, _bseB_T, _Hamiltonian_AB);\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \"   calculated singlet couplings \" << flush;\n            }\n\n\n\n            if (_doTriplets) {\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \"   Evaluating triplets\" << flush;\n                // get triplet BSE Hamiltonian from _orbitalsAB\n                ub::matrix<double> _Hamiltonian_AB = _eh_d;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \"  Converted Hamiltonian to double\" << flush;\n                ub::matrix<real_gwbse> temp = ub::project(_orbitalsA->BSETripletCoefficients(),\n                        ub::range(0, _orbitalsA->BSETripletCoefficients().size1()), ub::range(0, _levA));\n                const ub::matrix<double> _bseA_T = ub::trans(temp);\n                temp = ub::project(_orbitalsB->BSETripletCoefficients(), ub::range(0, _orbitalsB->BSETripletCoefficients().size1()), ub::range(0, _levB));\n                const ub::matrix<double> _bseB_T = ub::trans(temp);\n                temp.resize(0, 0);\n\n                JAB_triplet = ProjectExcitons(_bseA_T, _bseB_T, _Hamiltonian_AB);\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \"   calculated triplet couplings \" << flush;\n            }\n    \n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \"  Done with exciton couplings\" << flush;\n    return true;   \n};\n\n\nstd::vector< ub::matrix<double> > BSECoupling::ProjectExcitons(const ub::matrix<double>& _bseA_T, const ub::matrix<double>& _bseB_T, \n                                  ub::matrix<double>& _H){\n    \n    \n    \n    \n     // get projection of monomer excitons on dimer product functions\n     ub::matrix<double> _proj_excA = ub::prod( _bseA_T, _kap);\n     ub::matrix<double> _proj_excB = ub::prod( _bseB_T, _kbp);\n     \n     _bseA_exc = _proj_excA.size1();\n     _bseB_exc = _proj_excB.size1();\n     _bse_exc=_bseA_exc+_bseB_exc;\n     \n     \n     \n     unsigned _ctAB=ctAB.size1();\n     \n     unsigned _ctBA=ctBA.size1();\n     _ct=_ctAB+_ctBA;\n     unsigned nobasisfunc=_H.size1();\n     \n     \n     \n     ub::matrix<double> fe_states=ub::matrix<double>(_bse_exc,nobasisfunc);\n     ub::project(fe_states, ub::range ( 0, _bseA_exc ),ub::range (0, nobasisfunc )  )=_proj_excA;\n     ub::project(fe_states, ub::range ( _bseA_exc, _bse_exc ),ub::range (0, nobasisfunc )  )=_proj_excB;\n      \n     ub::matrix<double> ct_states=ub::matrix<double>(_ct,nobasisfunc);\n     \n     //cout<< _ct<< \"ct states\"<<endl;\n    if(_ct>0){ \n     //orthogonalize ct-states with respect to the FE states. \n       CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \" Orthogonalizing CT-states with respect to FE-states\" << flush;\n   \n     if(_ctAB>0){\n     ub::project(ct_states, ub::range ( 0 , _ctAB ) ,ub::range (0,nobasisfunc ) )=ctAB;\n    }\n    if(_ctBA>0){\n     ub::project(ct_states, ub::range ( _ctAB, _ct ),ub::range (0, nobasisfunc )  )=ctBA;\n     }\n       \n       \n        //orthogonalize ct-states with respect to FE states\n     ub::matrix<double> overlaps=ub::prod(fe_states,ub::trans(ct_states));\n     \n     //cout << \"overlap\"<< overlaps.size1()<< \"x\"<<overlaps.size2()<<endl;\n     //cout << overlaps<<endl;\n     ub::matrix<double> correction=ub::prod(ub::trans(overlaps),fe_states);\n     //cout << \"correction\"<< correction.size1()<< \"x\"<<correction.size2()<<endl;\n    // cout << \"ct_states\"<< ct_states.size1()<< \"x\"<<ct_states.size2()<<endl;\n  \n   \n\n    ct_states=ct_states-correction;    \n\n     overlaps.resize(0,0);\n     correction.resize(0,0);\n     //normalize\n    \n     for (unsigned i=0;i<_ct;i++){\n         double norm=0.0;\n         for (unsigned j=0;j<nobasisfunc;j++){\n         norm+=ct_states(i,j)*ct_states(i,j);    \n         }\n         //cout << \"norm [\"<<i<<\"]:\" <<norm<<endl;\n         norm=1/std::sqrt(norm);\n         if(norm<0.95){\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \" WARNING: CT-state \"<< i<< \" norm is only\"<< norm << flush; \n         }\n         for (unsigned j=0;j<nobasisfunc;j++){\n            ct_states(i,j)=norm*ct_states(i,j);    \n         }\n         \n     }\n    //cout <<ub::prod(fe_states,ub::trans(ct_states))<<endl; \n      \n    } \n\n     \n    \n    \n     ub::matrix<double> projection =ub::zero_matrix<double>(_bse_exc+_ct,nobasisfunc);\n     \n     \n     CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \" merging projections into one vector  \" << flush;\n    \n  ub::project(projection, ub::range (0 , _bse_exc) ,ub::range (0,nobasisfunc ) )=fe_states;\n   \n     if(_ct>0){\n    ub::project(projection, ub::range ( _bse_exc , _bse_exc+_ct ) ,ub::range (0,nobasisfunc ) )=ct_states;\n     }\n      CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \"   Setting up coupling matrix size \"<< _bse_exc +_ct<<\"x\"<<_bse_exc +_ct << flush;\n     // matrix _J\n     \n    //  E_A         J_AB        J_A_ABCT        J_A_BACT\n    //  J_BA        E_B         J_B_ABCT        J_B_BACT\n    //  J_ABCT_A    J_ABCT_B    E_ABCT          J_ABCT_BACT\n    //  J_BACT_A   J_BACT_B    J_BACT_ABCT     E_BACT\n     \n     // I think this only works for hermitian/symmetric H so only in TDA\n     // setup J\n     \n    \n     \n     ub::matrix<double> _temp=ub::prod(_H,ub::trans(projection));\n     _H.resize(0,0);\n     ub::matrix<double> _J_dimer=ub::prod(projection,_temp);\n     _temp.resize(0,0);\n     \n\n    \n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \"   Setting up overlap matrix size \"<< _bse_exc +_ct<<\"x\"<<_bse_exc +_ct << flush;\n     // setup S\n    \n    ub::matrix<double> _S_dimer=ub::prod(projection,ub::trans(projection));\n    \n    projection.resize(0,0);\n    if(tools::globals::verbose &&  _bse_exc+_ct<100){\n         CTP_LOG(ctp::logDEBUG, *_pLog) << \"---------------------------------------\"<<flush;\n     CTP_LOG(ctp::logDEBUG, *_pLog) << \"_J_dimer[Ryd]\"<<flush;\n     \n     CTP_LOG(ctp::logDEBUG, *_pLog) << _J_dimer<<flush;\n     CTP_LOG(ctp::logDEBUG, *_pLog) << \"_S_dimer\"<<flush;\n     \n     CTP_LOG(ctp::logDEBUG, *_pLog) << _S_dimer<<flush;\n      CTP_LOG(ctp::logDEBUG, *_pLog) << \"---------------------------------------\"<<flush;\n    }\n   \n    \n    double small=linalg_loewdin(_J_dimer,_S_dimer);\n    \n    if(tools::globals::verbose && _bse_exc+_ct<100){\n         CTP_LOG(ctp::logDEBUG, *_pLog) << \"---------------------------------------\"<<flush;\n    CTP_LOG(ctp::logDEBUG, *_pLog) << \"_J_ortho[Ryd]\"<<flush;\n    CTP_LOG(ctp::logDEBUG, *_pLog) << _J_dimer<<flush;\n    CTP_LOG(ctp::logDEBUG, *_pLog) << \"_S-1/2\"<<flush;\n    CTP_LOG(ctp::logDEBUG, *_pLog) << _S_dimer<<flush;\n     CTP_LOG(ctp::logDEBUG, *_pLog) << \"---------------------------------------\"<<flush;\n    }\n     CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \"   Smallest value of dimer overlapmatrix is \"<< small<< flush;\n     \n    std::vector< ub::matrix<double> >_J;\n     \n     CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \"   Running Perturbation algorithm\"<< flush;\n    _J.push_back( Perturbation(_J_dimer));\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \"    Running Projection algorithm\"<< flush;\n    _J.push_back( Fulldiag(_J_dimer));\n    \n    \n       if(tools::globals::verbose){\n     CTP_LOG(ctp::logDEBUG, *_pLog) << \"---------------------------------------\"<<flush;\n     CTP_LOG(ctp::logDEBUG, *_pLog) << \"Jeff_pert[Hrt]\"<<flush;\n     CTP_LOG(ctp::logDEBUG, *_pLog) << _J[0]<<flush;\n     CTP_LOG(ctp::logDEBUG, *_pLog) << \"Jeff_diag[Hrt]\"<<flush;\n     CTP_LOG(ctp::logDEBUG, *_pLog) << _J[1]<<flush;\n     CTP_LOG(ctp::logDEBUG, *_pLog) << \"---------------------------------------\"<<flush;\n     }\n      \n     return _J;\n}\n\nub::matrix<double> BSECoupling::Perturbation(const ub::matrix<double>& _J_dimer){\n    \n    ub::matrix<double> _J = ub::zero_matrix<double>(_bse_exc, _bse_exc);\n    bool _diag_ct = true;\n    ub::matrix<double> _J_result=_J_dimer;\n    if (_ct > 0 && _diag_ct) {\n\n        ub::matrix<double> transformation = ub::identity_matrix<double>(_bse_exc + _ct, _bse_exc + _ct);\n        ub::vector<double> eigenvalues_ct;\n\n\n\n        ub::matrix<double> Ct = ub::project(_J_dimer, ub::range(_bse_exc, _bse_exc + _ct), ub::range(_bse_exc, _bse_exc + _ct));\n        linalg_eigenvalues(eigenvalues_ct, Ct);\n        ub::project(transformation, ub::range(_bse_exc, _bse_exc + _ct), ub::range(_bse_exc, _bse_exc + _ct)) = Ct;\n\n        Ct.resize(0, 0);\n\n        if (tools::globals::verbose) {\n\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"FE state hamiltonian\" << flush;\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ub::project(_J_dimer, ub::range(0, _bse_exc), ub::range(0, _bse_exc)) << flush;\n            if (_ct > 0) {\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \"eigenvalues of CT states\" << flush;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << eigenvalues_ct << flush;\n            }\n\n        }\n\n        ub::matrix<double> _temp = ub::prod(_J_dimer, transformation);\n        _J_result = ub::prod(ub::trans(transformation), _temp);\n        if (tools::globals::verbose && _bse_exc + _ct < 100) {\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"---------------------------------------\" << flush;\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"_J_ortho[Hrt] CT-state diag\" << flush;\n            CTP_LOG(ctp::logDEBUG, *_pLog) << _J_result << flush;\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"---------------------------------------\" << flush;\n        }\n    }\n    for (int stateA = 0; stateA < _levA; stateA++) {\n        double Ea = _J_result(stateA, stateA);\n        for (int stateB = 0; stateB < _levB; stateB++) {\n            int stateBd = stateB + _bseA_exc;\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \"   Calculating coupling between exciton A\" << stateA + 1 << \" and exciton B\" << stateB + 1 << flush;\n            double J = _J_result(stateA, stateBd);\n\n            double Eb = _J_result(stateBd, stateBd);\n            for (unsigned k = _bse_exc; k < (_bse_exc + _ct); k++) {\n                double Eab = _J_result(k, k);\n                if (std::abs(Eab - Ea) < 0.001) {\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \"Energydifference between state A \" << stateA + 1 << \"and CT state \" << k + 1 << \" is \" << Eab - Ea << \"[Hrt]\" << flush;\n                }\n                if (std::abs(Eab - Eb) < 0.001) {\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \"Energydifference between state B \" << stateB + 1 << \"and CT state \" << k + 1 << \" is \" << Eab - Eb << \"[Hrt]\" << flush;\n\n                }\n                J += 0.5 * _J_result(k, stateA) * _J_result(k, stateBd)*(1 / (Ea - Eab) + 1 / (Eb - Eab)); // Have no clue why 0.5\n            }\n            _J(stateA, stateBd) = J;\n            _J(stateBd, stateA) = J;\n\n\n        }\n    }\n\n            \n    return _J;\n}\n\n\nub::matrix<double> BSECoupling::Fulldiag(const ub::matrix<double>& _J_dimer){\n    ub::matrix<double> _J = ub::zero_matrix<double>(_bse_exc, _bse_exc);\n   \n\n    ub::vector<double> _J_eigenvalues;\n    ub::matrix<double> J_eigenvectors;\n\n    linalg_eigenvalues(_J_dimer,_J_eigenvalues, J_eigenvectors);\n    if (tools::globals::verbose && _bse_exc + _ct < 10) {\n        CTP_LOG(ctp::logDEBUG, *_pLog) << \"---------------------------------------\" << flush;\n        CTP_LOG(ctp::logDEBUG, *_pLog) << \"Eigenvectors of J\" << flush;\n\n        CTP_LOG(ctp::logDEBUG, *_pLog) << J_eigenvectors << flush;\n        CTP_LOG(ctp::logDEBUG, *_pLog) << \"J_eigenvalues[Hrt]\" << flush;\n        CTP_LOG(ctp::logDEBUG, *_pLog) << _J_eigenvalues << flush;\n        CTP_LOG(ctp::logDEBUG, *_pLog) << \"---------------------------------------\" << flush;\n    }\n    //Calculate projection on subspace for every pair of excitons separately\n    for (int stateA = 0; stateA < _levA; stateA++) {\n        for (int stateB = 0; stateB < _levB; stateB++) {\n            int stateBd = stateB + _bseA_exc;\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \"   Calculating coupling between exciton A\" << stateA + 1 << \" and exciton B\" << stateB + 1 << flush;\n            std::vector<unsigned> index;\n            std::vector<int> signvec;\n            for (unsigned i = 0; i < _bse_exc + _ct; i++) {\n                if (i == unsigned(stateA) || i == unsigned(stateBd)) {\n\n                    double close = 0.0;\n                    unsigned ind = 0;\n                    int sign = 0;\n                    //row\n                    for (unsigned j = 0; j < _bse_exc + _ct; j++) {\n                        bool check = true;\n                        // if index i is already in index\n                        // should not happen but if one vector was similar to two others.\n                        for (unsigned l = 0; l < index.size(); l++) {\n                            if (j == index[l]) {\n                                check = false;\n                                break;\n                            }\n                        }\n\n                        if (check && std::abs(J_eigenvectors(i, j)) > close) {\n                            ind = j;\n                            close = std::abs(J_eigenvectors(i, j));\n                            if (J_eigenvectors(i, j) >= 0) {\n                                sign = 1;\n                            } else {\n                                sign = -1;\n                            }\n                        }\n                    }\n                    index.push_back(ind);\n                    signvec.push_back(sign);\n                }\n            }\n\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \"   Order is: [Initial state n->nth eigenvalue]\" << flush;\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"    A\" << stateA + 1 << \":\" << stateA + 1 << \"->\" << index[0] + 1 << \" \";\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"    B\" << stateB + 1 << \":\" << stateBd + 1 << \"->\" << index[1] + 1 << \" \" << flush;\n\n            //setting up transformation matrix _T and diagonal matrix _E for the eigenvalues;\n\n            ub::matrix<double> _E = ub::zero_matrix<double>(2, 2);\n            ub::matrix<double> _T = ub::zero_matrix<double>(2, 2);\n            //find the eigenvectors which are most similar to the initial states\n\n            //row \n            for (unsigned i = 0; i < 2; i++) {\n                unsigned k = index[i];\n                double sign = signvec[i];\n                double normr = 1 / std::sqrt(J_eigenvectors(stateA, k) * J_eigenvectors(stateA, k) + J_eigenvectors(stateBd, k) * J_eigenvectors(stateBd, k));\n                _T(0, i) = sign * J_eigenvectors(stateA, k) * normr;\n                _T(1, i) = sign * J_eigenvectors(stateBd, k) * normr;\n                _E(i, i) = _J_eigenvalues(k);\n            }\n\n\n            if ((_T(1, 1) * _T(0, 0) - _T(1, 0) * _T(0, 1)) < 0) {\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \" Reduced state matrix is not in a right handed basis, multiplying second eigenvector by -1 \" << flush;\n                _T(0, 1) = -_T(0, 1);\n                _T(1, 1) = -_T(1, 1);\n            }\n\n            if (tools::globals::verbose) {\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \"---------------------------------------\" << flush;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \"_T\" << flush;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << _T << flush;\n\n            }\n\n            ub::matrix<double> S_small = ub::prod(_T, ub::trans(_T));\n            if (tools::globals::verbose) {\n\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \"S_small\" << flush;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << S_small << flush;\n\n            }\n            //orthogonalize that matrix\n            double small = linalg_loewdin(_E, S_small);\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \"   Smallest value of dimer overlapmatrix is \" << small << flush;\n            if (tools::globals::verbose) {\n\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \"S-1/2\" << flush;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << S_small << flush;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \"E_ortho\" << flush;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << _E << flush;\n            }\n            _T = ub::prod(_T, S_small);\n            //cout <<  ub::prod(_T,ub::trans(_T))<<endl;\n            if (tools::globals::verbose) {\n\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \"T_ortho\" << flush;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << _T << flush;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \"---------------------------------------\" << flush;\n            }\n\n            ub::matrix<double> temp = ub::prod(_T, _E);\n\n            ub::matrix<double> _J_small = ub::prod(temp, ub::trans(_T));\n            if (tools::globals::verbose) {\n\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \"T_ortho*E_ortho\" << flush;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << temp << flush;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \"T_ortho*E_ortho*T_ortho^T\" << flush;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << _J_small << flush;\n            }\n\n            _J(stateA, stateBd) = _J_small(0, 1);\n            _J(stateBd, stateA) = _J_small(1, 0);\n\n        }\n    }\n       \n    return _J;\n}\n\n\n    \n}}\n", "meta": {"hexsha": "77260ccfc30e814e7ab57879c3169a47a483b0e8", "size": 41911, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/bsecoupling.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/bsecoupling.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/bsecoupling.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": 43.0297741273, "max_line_length": 254, "alphanum_fraction": 0.5671542077, "num_tokens": 13092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2709296636763177}}
{"text": "#include \"CS_Retro_NavigatorGadget.h\"\r\n\r\n#include <armadillo>\r\n#include <algorithm>\r\n#include <cmath>\r\n\r\n#include \"hoNDArray_math_util.cpp\"\r\n\r\nusing namespace Gadgetron;\r\n\r\n// class constructor\r\nCS_Retro_NavigatorGadget::CS_Retro_NavigatorGadget()\r\n{\r\n}\r\n\r\n// class destructor - delete temporal buffer/memory\r\nCS_Retro_NavigatorGadget::~CS_Retro_NavigatorGadget()\r\n{\r\n}\r\n\r\n// read flexible data header\r\nint CS_Retro_NavigatorGadget::process_config(ACE_Message_Block *mb)\r\n{\r\n\t// get gadget property\r\n#ifdef __GADGETRON_VERSION_HIGHER_3_6__\r\n\tmin_card_freq_\t= MinCardFreq.value();\r\n\tmax_card_freq_\t= MaxCardFreq.value();\r\n\tmin_resp_freq_\t= MinRespFreq.value();\r\n\tmax_resp_freq_\t= MaxRespFreq.value();\r\n\tiNavMethod_\t\t= NavigationMethod.value();\r\n#else\r\n\tmin_card_freq_\t= *(get_int_value(\"MinCardFreq\").get());\r\n\tmax_card_freq_\t= *(get_int_value(\"MaxCardFreq\").get());\r\n\tmin_resp_freq_\t= *(get_int_value(\"MinRespFreq\").get());\r\n\tmax_resp_freq_\t= *(get_int_value(\"MaxRespFreq\").get());\r\n\tiNavMethod_\t\t= *(get_int_value(\"NavigationMethod\").get());\r\n#endif\r\n\r\n\t// some basic error checking for parameters\r\n\tif (min_card_freq_ < 0 || max_card_freq_ < 0 || min_resp_freq_ < 0 || max_resp_freq_ < 0) {\r\n\t\tGERROR(\"Given parameters min_card_freq_, max_card_freq_, min_resp_freq_, max_resp_freq_ must not be negative!\\n\");\r\n\t\treturn GADGET_FAIL;\r\n\t}\r\n\r\n\tif (min_card_freq_ >= max_card_freq_) {\r\n\t\tGERROR(\"max_card_freq_ must be greater than min_card_freq_!\\n\");\r\n\t\treturn GADGET_FAIL;\r\n\t}\r\n\r\n\tif (min_resp_freq_ >= max_resp_freq_) {\r\n\t\tGERROR(\"max_resp_freq_ must be greater than min_resp_freq_!\\n\");\r\n\t\treturn GADGET_FAIL;\r\n\t}\r\n\r\n\treturn GADGET_OK;\r\n}\r\n\r\nint CS_Retro_NavigatorGadget::process(GadgetContainerMessage<ISMRMRD::ImageHeader> *m1,GadgetContainerMessage<hoNDArray<std::complex<float> > > *m2, GadgetContainerMessage<hoNDArray<std::complex<float> > > *m3)\r\n{\r\n\t// fetch attribute values from header\r\n\tiNoChannels_ = m1->getObjectPtr()->channels;\r\n\tiNoNav_\t\t = m1->getObjectPtr()->user_int[5];\r\n\tlNoScans_\t = m3->getObjectPtr()->get_size(1);\r\n\r\n\tfield_of_view_[0] = m1->getObjectPtr()->field_of_view[0];\r\n\tfield_of_view_[1] = m1->getObjectPtr()->field_of_view[1];\r\n\tfield_of_view_[2] = m1->getObjectPtr()->field_of_view[2];\r\n\r\n\t// get navigator signal according to selected method\r\n\t// 0: classical\r\n\t// 1: PCA\r\n\tswitch (iNavMethod_) {\r\n\tcase 0:\r\n\t\ttry {\r\n\t\t\tgetNav2D(*m2->getObjectPtr());\r\n\t\t} catch ( ... ) {\r\n\t\t\tGERROR(\"An exception occurred\\n\");\r\n\t\t\treturn GADGET_FAIL;\r\n\t\t}\r\n\r\n\t\tbreak;\r\n\r\n\tcase 1:\r\n\t\ttry {\r\n\t\t\tgetNav2DPCA(*m2->getObjectPtr());\r\n\t\t} catch ( ... ) {\r\n\t\t\tGERROR(\"An exception occurred\\n\");\r\n\t\t\treturn GADGET_FAIL;\r\n\t\t}\r\n\r\n\t\tbreak;\r\n\r\n\tdefault:\r\n\t\tGERROR(\"Navigation method %d unknown! Please specify one via gadget property.\\n\", iNavMethod_);\r\n\t\treturn GADGET_FAIL;\r\n\t}\r\n\r\n\t// update cardiac gates to 1 if no signal is present\r\n\tif (navigator_card_interpolated_.size() == 0) {\r\n\t\tset_number_of_gates(m1->getObjectPtr()->user_int[0], 1, 1);\r\n\t}\r\n\r\n\t// equalize vector lengths (zero-padding)\r\n\twhile (navigator_card_interpolated_.size() < navigator_resp_interpolated_.size()) {\r\n\t\tnavigator_card_interpolated_.push_back(0);\r\n\t}\r\n\twhile (navigator_resp_interpolated_.size() < navigator_card_interpolated_.size()) {\r\n\t\tnavigator_resp_interpolated_.push_back(0);\r\n\t}\r\n\r\n\t// achieve message format [respiratory navigator, cardiac navigator]\r\n\tGadgetContainerMessage<hoNDArray<float> > *tmp_m2 = new GadgetContainerMessage<hoNDArray<float> >();\r\n\ttmp_m2->getObjectPtr()->create(navigator_resp_interpolated_.size(), 2);\r\n\r\n\t// copy data to array (resp, card, resp, card,... - therefore Indices 2*iI [+1]\r\n\tfloat *fPtr = tmp_m2->getObjectPtr()->get_data_ptr();\r\n\tfor (size_t iI = 0; iI < navigator_resp_interpolated_.size(); iI++) {\r\n\t\tfPtr[2*iI] = navigator_resp_interpolated_.at(iI);\r\n\t\tfPtr[2*iI+1] = navigator_card_interpolated_.at(iI);\r\n\t}\r\n\r\n\tm1->cont(tmp_m2);\r\n\ttmp_m2->cont(m3);\r\n\r\n\tif (this->next()->putq(m1) < 0) {\r\n\t\treturn GADGET_FAIL;\r\n\t}\r\n\r\n\t// free memory\r\n\tm2->cont(NULL);\r\n\tm2->release();\r\n\r\n\treturn GADGET_OK;\r\n}\r\n\r\n// get interpolated navigator signal\r\nvoid CS_Retro_NavigatorGadget::getNav2D(hoNDArray<std::complex<float> > &aNav)\r\n{\r\n\tGDEBUG(\"\\n\\n**************************************\\n********** get navigator 2D **********\\n**************************************\\n\\n\");\r\n\r\n\t// reconstruct the 1-D projections for all measurements and all channels\r\n\tGINFO(\"domain transformation - k-space to image\\n\");\r\n\r\n\t/* MATLAB\r\n\t% Reconstruct the 1-D projections for all measurements and all channels\r\n\tdImg = fftshift(ifft(ifftshift(dKSpace)));\r\n\tdImg = fftshift(ifft(ifftshift(dImg, 3), [], 3), 3);\r\n\tdImg = flipdim(dImg, 1); % Invert the RO direction: 1-N -> H-F\r\n\tdImg = dImg(iNSamples/4:iNSamples.*3/4 - 1, :, :, :); % RO x t x PE x CH\r\n\t*/\r\n\thoNDArray<std::complex<float> > aImg = aNav;\r\n\thoNDFFT_CS<float>::instance()->ifftshift3D(aImg);\r\n\thoNDFFT_CS<float>::instance()->ifft1(aImg);\r\n\thoNDFFT_CS<float>::instance()->fftshift3D(aImg);\r\n\thoNDFFT_CS<float>::instance()->ifft(&aImg, 2, true);\r\n\tflip_array(aImg, 0);\r\n\r\n\t// crop center part due to twofold oversampling\r\n\tGINFO(\"crop center part of two-fold oversampled data..\\n\");\r\n\r\n\tstd::vector<size_t> vStart, vSize;\r\n\r\n\tvStart.push_back(static_cast<size_t>(std::floor(0.25*aNav.get_size(0)))-1);\r\n\tvStart.push_back(0);\r\n\tvStart.push_back(0);\r\n\tvStart.push_back(0);\r\n\r\n\tvSize.push_back(std::floor(0.5*aNav.get_size(0)));\r\n\tvSize.push_back(aNav.get_size(1));\r\n\tvSize.push_back(aNav.get_size(2));\r\n\tvSize.push_back(aNav.get_size(3));\r\n\r\n\tget_subarray(aImg, vStart, vSize, aImg);\r\n\r\n\t// get channel power and normalize channel images\r\n\tGINFO(\"calculate channel power and normalize channel images..\\n\");\r\n\r\n\tstd::vector<float> fPower(iNoChannels_);\r\n\thoNDArray<std::complex<float> > aPower = aImg;\r\n\taPower.fill(std::complex<float>(0,0));\r\n\r\n\tfor (int c = 0; c < iNoChannels_; c++) {\r\n\t\tsize_t offset = aImg.get_size(0)*aImg.get_size(1)*aImg.get_size(2)*c;\r\n\t\thoNDArray<std::complex<float> > SubArray(aImg.get_size(0), aImg.get_size(1), aImg.get_size(2), aImg.get_data_ptr()+offset, false);\r\n\t\tfPower.at(c) = asum(SubArray);\r\n\r\n\t\t// fill part of the 3D array\r\n\t\t#pragma omp parallel for\r\n\t\tfor (size_t i = 0; i < aImg.get_size(0)*aImg.get_size(1)*aImg.get_size(2); i++) {\r\n\t\t\taPower.at(i+offset) = std::complex<float>(fPower.at(c), fPower.at(c));\r\n\t\t}\r\n\t}\r\n\r\n\tdivide(aImg, aPower, aImg);\r\n\r\n\tGINFO(\"channel images normalized..\\n\");\r\n\r\n\taPower.clear();\r\n\r\n\t// get x range of respiratory motion & FFT without scrambling\r\n\thoNDArray<std::complex<float> > aFreq = aImg;\r\n\thoNDFFT_CS<float>::instance()->fft(&aFreq, 1, false);\r\n\tmultiplyConj(aFreq,aFreq,aPower);\r\n\r\n\t// conversion from complex float to float\r\n\thoNDArray<float> afPower(aPower.get_dimensions());\r\n\tfor (size_t i = 0; i < afPower.get_number_of_elements(); i++) {\r\n\t\tafPower[i] = aPower[i].real();\r\n\t}\r\n\r\n\t/*\r\n\tdIMGres = 1./(double(dNavPeriod)./1000.*double(iNMeasurements)); % The frequency resolution of dIMG in Hz\r\n\tdPower = squeeze(sum(dPower(:, round(1./(5.*dIMGres)):round(1./(3.*dIMGres)), :, :), 2)); % RO x PE x CH\r\n\t*/\r\n\tfloat fIMGRes = 1.0/((static_cast<float>(GlobalVar::instance()->iNavPeriod_)/1000.0)*static_cast<float>(iNoNav_)); // frequency resolution of aImg in Hz\r\n\thoNDArray<float> aPowerInChan, aPowerAcrossChan;\r\n\r\n\tvStart.clear();\r\n\tvStart.push_back(0);\r\n\tvStart.push_back(std::floor(1.0/(5*fIMGRes)-.5));\r\n\tvStart.push_back(0);\r\n\tvStart.push_back(0);\r\n\r\n\tvSize.clear();\r\n\tvSize.push_back(afPower.get_size(0));\r\n\tvSize.push_back(std::ceil(1.0/(3*fIMGRes)-.5)-std::ceil(1.0/(5*fIMGRes)-.5)+1);\r\n\tvSize.push_back(afPower.get_size(2));\r\n\tvSize.push_back(afPower.get_size(3));\r\n\r\n\tget_subarray(afPower, vStart, vSize, afPower);\r\n\r\n\tsum_dim(afPower, 1, afPower); // RO x PE x CH\r\n\tsum_dim(afPower, 1, aPowerInChan); // RO x CH\r\n\tsum_dim(aPowerInChan, 1, aPowerAcrossChan); // RO x 1\r\n\r\n\t// Prevent detection of regions in the abdomen\r\n\tfor (long i = aPowerAcrossChan.get_number_of_elements(); i > std::floor(aPowerAcrossChan.get_number_of_elements()*.75); i--) {\r\n\t\taPowerAcrossChan.at(i) = 0;\r\n\t}\r\n\r\n\t// get Gaussian filter kernel\r\n\tstd::vector<float> vGaussian;\r\n\tfilter1DGaussian(vGaussian, 20);\r\n\tarrayConv(aPowerAcrossChan, vGaussian, 0);\r\n\r\n\t// find index of maximum\r\n\tint iMaxIndex = amax(aPowerAcrossChan);\r\n\r\n\tGINFO(\"data filtered and maximum determined.. iMaxIndex: %i\\n\", iMaxIndex);\r\n\r\n\tif (iMaxIndex < 20) {\r\n\t\tGWARN(\"iMaxIndex=%d < 20! It is set to 20 to be able to perform further computing. Errors may occur.\\n\", iMaxIndex);\r\n\t\tiMaxIndex = 20;\r\n\t}\r\n\r\n\tif ((iMaxIndex < 20) || (iMaxIndex > static_cast<int>(aPowerInChan.get_size(0))-20)) {\r\n\t\tGERROR(\"Error: iMaxIndex out of bounds..\\n\");\r\n\r\n\t\tthrow std::range_error(\"iMaxIndex out of bounds\\n\");\r\n\t}\r\n\r\n\t//-------------------------------------------------------------------------\r\n\t// sort out channels with no relevant information in target area\r\n\tGINFO(\"get channels which contain most information..\\n\");\r\n\r\n\tvStart.clear();\r\n\tvStart.push_back(iMaxIndex-20);\r\n\tvStart.push_back(0);\r\n\r\n\tvSize.clear();\r\n\tvSize.push_back(41);\r\n\tvSize.push_back(iNoChannels_);\r\n\r\n\tget_subarray(aPowerInChan, vStart, vSize,aPowerInChan);\r\n\r\n\tGINFO(\"41 elements around maximum cropped..\\n\");\r\n\r\n\tstd::vector<float> vGoodChannels;\r\n\r\n\t// loop over channels\r\n\tfor (int c = 0; c < iNoChannels_; c++) {\r\n\t\thoNDArray<float> aTmp;\r\n\t\tsize_t offset = aPowerInChan.get_size(0)*c;\r\n\t\taTmp.create(aPowerInChan.get_size(0), aPowerInChan.get_data_ptr()+offset, false);\r\n\t\tint iTmpInd = amax(aTmp);\r\n\t\tvGoodChannels.push_back(aTmp.at(iTmpInd));\r\n\t}\r\n\r\n\tint iIndex = std::max_element(vGoodChannels.begin(), vGoodChannels.end())- vGoodChannels.begin();\r\n\tfloat fMax = vGoodChannels.at(iIndex);\r\n\tint iNumGood = 0;\r\n\r\n\tfor (size_t i = 0; i < vGoodChannels.size(); i++) {\r\n\t\tif (vGoodChannels.at(i) > .2*fMax) {\r\n\t\t\tvGoodChannels.at(i) = 1;\r\n\t\t\tiNumGood++;\r\n\t\t} else {\r\n\t\t\tvGoodChannels.at(i) = 0;\r\n\t\t}\r\n\t}\r\n\r\n\tfor (size_t i = 0; i < vGoodChannels.size(); i++) {\r\n\t\tGDEBUG(\"vGoodChannels[%i]: %f\\n\", i,vGoodChannels.at(i));\r\n\t}\r\n\r\n\t//-------------------------------------------------------------------------\r\n\t// get the best PE line\r\n\t// get sub array of good channels\r\n\tGDEBUG(\"get best PE line..\\n\");\r\n\r\n\thoNDArray<float> aPowerInPE(41,afPower.get_size(1), iNumGood);\r\n\r\n\tvStart.clear();\r\n\tvStart.push_back(iMaxIndex-20);\r\n\tvStart.push_back(0);\r\n\tvStart.push_back(0);\r\n\r\n\tvSize.clear();\r\n\tvSize.push_back(41);\r\n\tvSize.push_back(afPower.get_size(1));\r\n\tvSize.push_back(1);\r\n\r\n\tGDEBUG(\"vStart: %i, %i, %i, vSize: %i, %i, %i, afPower size: %i, %i, %i\\n\", vStart.at(0), vStart.at(1), vStart.at(2), vSize.at(0), vSize.at(1), vSize.at(2), afPower.get_size(0), afPower.get_size(1), afPower.get_size(2));\r\n\r\n\tsize_t o = 0; //helper - only non-zero entries of vGoodChannels are of interest\r\n\tfor (int c = 0; c < iNoChannels_; c++) {\r\n\t\tif (vGoodChannels.at(c) == 1) {\r\n\t\t\thoNDArray<float> aTmp;\r\n\t\t\taTmp.create(&vSize);\r\n\t\t\tvStart.at(2) = c;\r\n\t\t\tget_subarray(afPower, vStart, vSize, aTmp);\r\n\r\n\t\t\t// fill array\r\n\t\t\tsize_t offset = aPowerInPE.get_size(0)*aPowerInPE.get_size(1)*o;\r\n\t\t\tfor (size_t i = 0; i < aTmp.get_number_of_elements(); i++) {\r\n\t\t\t\taPowerInPE.at(i + offset) = aTmp.at(i);\r\n\t\t\t}\r\n\r\n\t\t\to++;\r\n\t\t}\r\n\t}\r\n\r\n\tsum_dim(aPowerInPE, 2, aPowerInPE);\r\n\tsum_dim(aPowerInPE, 0, aPowerInPE);\r\n\r\n\tGINFO(\"\\n aPowerInPE\\n\");\r\n\taPowerInPE.print(std::cout);\r\n\r\n\tiMaxIndex = amax(aPowerInPE);\r\n\tint iMaxChan = iMaxIndex;\r\n\r\n\tGINFO(\"found at %i\\n\", iMaxIndex);\r\n\r\n\t//-------------------------------------------------------------------------\r\n\t// find best corresponding channels according to best phase encoding position\r\n\tGINFO(\"searching for channels according to best PE line..\\n\");\r\n\r\n\t// get sub array\r\n\tvStart.clear();\r\n\tvStart.push_back(0);\r\n\tvStart.push_back(0);\r\n\tvStart.push_back(iMaxIndex);\r\n\tvStart.push_back(0);\r\n\r\n\tvSize.clear();\r\n\tvSize.push_back(aImg.get_size(0));\r\n\tvSize.push_back(aImg.get_size(1));\r\n\tvSize.push_back(1);\r\n\tvSize.push_back(aImg.get_size(3));\r\n\r\n\taFreq.clear();\r\n\r\n\tget_subarray(aImg, vStart, vSize, aFreq);\r\n\r\n\thoNDFFT_CS<float>::instance()->fft(&aFreq, 1, false);\r\n\tmultiplyConj(aFreq,aFreq,aPower);\r\n\r\n\t// conversion from complex float to float\r\n\tafPower.clear();\r\n\tafPower.create(*aPower.get_dimensions());\r\n\tfor (size_t i = 0; i < afPower.get_number_of_elements(); i++) {\r\n\t\tafPower[i] = aPower[i].real();\r\n\t}\r\n\r\n\tfIMGRes = 1.0/((static_cast<float>(GlobalVar::instance()->iNavPeriod_)/1000.0)*static_cast<float>(iNoNav_)); // frequency resolution of aImg in Hz\r\n\r\n\taPowerInChan.clear();\r\n\taPowerAcrossChan.clear();\r\n\r\n\tvStart.clear();\r\n\tvStart.push_back(0);\r\n\tvStart.push_back(std::ceil(1.0/(5*fIMGRes)-.5));\r\n\tvStart.push_back(0);\r\n\tvStart.push_back(0);\r\n\r\n\tvSize.clear();\r\n\tvSize.push_back(afPower.get_size(0));\r\n\tvSize.push_back(std::ceil(1.0/(3*fIMGRes)-.5)-std::ceil(1.0/(5*fIMGRes)-.5)+1);\r\n\tvSize.push_back(afPower.get_size(2));\r\n\tvSize.push_back(afPower.get_size(3));\r\n\r\n\tGDEBUG(\"vSize: %i, %i, %i, %i - fIMGRes: %f\\n\", vSize.at(0), vSize.at(1), vSize.at(2), vSize.at(3), fIMGRes);\r\n\r\n\tget_subarray(afPower, vStart, vSize, afPower);\r\n\tsum_dim(afPower, 1, afPower); // RO x PE x CH\r\n\tsum_dim(afPower, 1, aPowerInChan); // RO x CH\r\n\tsum_dim(aPowerInChan, 1, aPowerAcrossChan); // RO x 1\r\n\r\n\t// Prevent detection of regions in the abdomen\r\n\tfor (long i = aPowerAcrossChan.get_number_of_elements(); i > std::floor(aPowerAcrossChan.get_number_of_elements()*.75); i--) {\r\n\t\taPowerAcrossChan.at(i) = 0;\r\n\t}\r\n\r\n\tGINFO(\"filter data with Gaussian kernel..\\n\");\r\n\r\n\t// get Gaussian filter kernel\r\n\tvGaussian.clear();\r\n\tfilter1DGaussian(vGaussian, 20);\r\n\tarrayConv(aPowerAcrossChan, vGaussian);\r\n\r\n\t// find index of maximum\r\n\tiMaxIndex = amax(aPowerAcrossChan);\r\n\tint dX = iMaxIndex;\r\n\r\n\tGINFO(\"found at %i\\n\", iMaxIndex);\r\n\r\n\t// get good channels\r\n\tvStart.clear();\r\n\tvStart.push_back(iMaxIndex-20);\r\n\tvStart.push_back(0);\r\n\r\n\tvSize.clear();\r\n\tvSize.push_back(41);\r\n\tvSize.push_back(aPowerInChan.get_size(1));\r\n\r\n\tget_subarray(aPowerInChan, vStart, vSize,aPowerInChan);\r\n\r\n\tvGoodChannels.clear();\r\n\r\n\t// loop over channels\r\n\tfor (int c = 0; c < iNoChannels_; c++) {\r\n\t\tsize_t offset = aPowerInChan.get_size(0)*c;\r\n\r\n\t\thoNDArray<float> aTmp;\r\n\t\taTmp.create(aPowerInChan.get_size(0), aPowerInChan.get_data_ptr()+offset, false);\r\n\r\n\t\tint iTmpInd = amax(aTmp);\r\n\t\tvGoodChannels.push_back(aTmp.at(iTmpInd));\r\n\t}\r\n\r\n\tiIndex = std::max_element(vGoodChannels.begin(), vGoodChannels.end())-vGoodChannels.begin();\r\n\tfMax =vGoodChannels.at(iIndex);\r\n\tiNumGood = 0;\r\n\r\n\tfor (size_t i = 0; i < vGoodChannels.size(); i++) {\r\n\t\tif (vGoodChannels.at(i) > .2*fMax) {\r\n\t\t\tvGoodChannels.at(i) = 1;\r\n\t\t\tiNumGood++;\r\n\t\t} else {\r\n\t\t\tvGoodChannels.at(i) = 0;\r\n\t\t}\r\n\t}\r\n\r\n\tfor (size_t i = 0; i < vGoodChannels.size(); i++) {\r\n\t\tGDEBUG(\"vGoodChannels[%i]: %f\\n\", i,vGoodChannels.at(i));\r\n\t}\r\n\r\n\t// get relevant image - dRelevantImg = squeeze(dImg(:, :, dPos, lGoodChannels));\r\n\tvStart.clear();\r\n\tvStart.push_back(0);\r\n\tvStart.push_back(0);\r\n\tvStart.push_back(iMaxChan);\r\n\tvStart.push_back(0);\r\n\r\n\tvSize.clear();\r\n\tvSize.push_back(aImg.get_size(0));\r\n\tvSize.push_back(aImg.get_size(1));\r\n\tvSize.push_back(1);\r\n\tvSize.push_back(1);\r\n\r\n\thoNDArray<std::complex<float> > acRelevantImg(aImg.get_size(0), aImg.get_size(1), iNumGood);\r\n\r\n\to = 0; //helper - only non-zero entries of vGoodChannels are of interest\r\n\thoNDArray<std::complex<float> > afTmp;\r\n\tfor (int c = 0; c < iNoChannels_; c++) {\r\n\t\tif (vGoodChannels.at(c) == 1) {\r\n\t\t\tvStart.at(3) = c;\r\n\t\t\tget_subarray(aImg, vStart, vSize, afTmp);\r\n\r\n\t\t\t// fill array\r\n\t\t\tsize_t offset = acRelevantImg.get_size(0)*acRelevantImg.get_size(1)*o;\r\n\t\t\tfor (size_t i = 0; i < afTmp.get_number_of_elements(); i++) {\r\n\t\t\t\tacRelevantImg.at(i + offset) = afTmp.at(i);\r\n\t\t\t}\r\n\r\n\t\t\to++;\r\n\t\t}\r\n\t}\r\n\r\n\t//-------------------------------------------------------------------------\r\n\tGINFO(\"get SOSImg\\n\");\r\n\r\n\thoNDArray<float> aRelevantImg(*acRelevantImg.get_dimensions());\r\n\tmultiplyConj(acRelevantImg,acRelevantImg,acRelevantImg);\r\n\t// complex float to float datatype\r\n\tfor (size_t i = 0; i < aRelevantImg.get_number_of_elements(); i++) {\r\n\t\taRelevantImg[i] = acRelevantImg[i].real();\r\n\t}\r\n\r\n\t// loop over channels\r\n\tsize_t tOffset = aRelevantImg.get_size(0)*aRelevantImg.get_size(1);\r\n\thoNDArray<float> hafMax(aRelevantImg.get_dimensions());\r\n\tfloat *fPtr = hafMax.get_data_ptr();\r\n\tfor (size_t iI = 0; iI < aRelevantImg.get_size(2); iI++) {\r\n\t\thoNDArray<float> tmp(aRelevantImg.get_size(0), aRelevantImg.get_size(1), aRelevantImg.get_data_ptr()+tOffset*iI);\r\n\t\tiMaxIndex = amax(tmp);\r\n\t\tfMax = tmp.at(iMaxIndex);\r\n\r\n\t\tfor (size_t iL = 0; iL < tOffset; iL++) {\r\n\t\t\tfPtr[iL+tOffset*iI] = fMax;\r\n\t\t}\r\n\t}\r\n\r\n\tdivide(aRelevantImg, hafMax, aRelevantImg);\r\n\r\n\thoNDArray<float> aSOSImg;\r\n\tsum_dim(aRelevantImg, 2, aSOSImg);\r\n\tsqrt(aSOSImg, aSOSImg);\r\n\r\n\t// convert array\r\n\thoNDArray<std::complex<float> > cfaSOSImgTest(aSOSImg.get_dimensions());\r\n\tcfaSOSImgTest.fill(std::complex<float>(0.0, 0.0));\r\n\tstd::complex<float> *cfPointer = cfaSOSImgTest.get_data_ptr();\r\n\tfor (size_t iI = 0; iI < cfaSOSImgTest.get_number_of_elements(); iI++) {\r\n\t\tcfPointer[iI] = std::complex<float>(aSOSImg.at(iI), 0.0);\r\n\t}\r\n\r\n\t//-------------------------------------------------------------------------\r\n\t// get navigator\r\n\tint iDisplacementMax = 80; // [mm] diaphragm displacement (max. +/- 80mm)\r\n\tint iDisplacement = static_cast<int>(std::ceil(static_cast<float>(iDisplacementMax)/(static_cast<float>(field_of_view_[0])/static_cast<float>(aImg.get_size(0))) - 0.5));\r\n\r\n\t// fill last line in ref image\r\n\thoNDArray<float> aRefImg = aSOSImg;\r\n\taRefImg.fill(0.0);\r\n\tfor (size_t iI = 0; iI < aSOSImg.get_size(0); iI++) {\r\n\t\taRefImg.at(iI + aSOSImg.get_size(0)*(aSOSImg.get_size(1)-1)) = aSOSImg.at(iI + aSOSImg.get_size(0)*(aSOSImg.get_size(1)-1));\r\n\t}\r\n\r\n\t// create index vector and navigator vector (filled with zeros)\r\n\tstd::vector<int> vIdx;\r\n\tfor (size_t i = 0; i < aRefImg.get_size(1); i++) {\r\n\t\tvIdx.push_back(i);\r\n\t}\r\n\r\n\tstd::vector<float> navigator_resp;\r\n\tfor (size_t i = 0; i < aRefImg.get_size(1); i++) {\r\n\t\tnavigator_resp.push_back(0);\r\n\t}\r\n\r\n\thoNDArray<float> aRMSImg;\r\n\tfor (int i = aRefImg.get_size(1)-2; i > 1; i--) {// -1 ; i--){\r\n\t\taRMSImg.create(aRefImg.get_size(0), 2*iDisplacement+1);\r\n\t\taRMSImg.fill(0.0);\r\n\r\n\t\t//MATLAB: tmp = dRefImg(:,idx(i+1:end))\r\n\t\thoNDArray<float> tmp;\r\n\r\n\t\tvStart.clear();\r\n\t\tvStart.push_back(0);\r\n\t\tvStart.push_back(i+1);\r\n\r\n\t\tvSize.clear();\r\n\t\tvSize.push_back(aRefImg.get_size(0));\r\n\t\tvSize.push_back(aRefImg.get_size(1)-i-1);\r\n\r\n\t\tget_subarray(aRefImg, vStart, vSize, tmp);\r\n\r\n\t\thoNDArray<float> repTmp(tmp.get_dimensions());\r\n\r\n\t\t//MATLAB: dSOSImg(:,idx(i)\r\n\t\thoNDArray<float> aTmp;\r\n\r\n\t\tvStart.clear();\r\n\t\tvStart.push_back(0);\r\n\t\tvStart.push_back(vIdx.at(i));\r\n\r\n\t\tvSize.clear();\r\n\t\tvSize.push_back(aSOSImg.get_size(0));\r\n\t\tvSize.push_back(1);\r\n\r\n\t\tget_subarray(aSOSImg, vStart, vSize, aTmp);\r\n\r\n\t\thoNDArray<float> aTmp2 = aTmp;\r\n\t\tcircshift(aTmp2, -iDisplacement-1, 0);\r\n\r\n\t\tfor (int l = -iDisplacement; l <= iDisplacement; l++) {\r\n\t\t\t//MATLAB: circshift(dSOSImg(:,idx(i)), iD)\r\n\t\t\tcircshift(aTmp2, 1, 0);\r\n\r\n\t\t\t//MATLAB: (tmp - repmat(circshift(dSOSImg(:,idx(i)), iD),[1 size(tmp,2)]))\r\n\t\t\thoNDArray<float> tmp2(tmp.get_dimensions());\r\n\t\t\ttmp2.fill(0.0); // result of subtraction\r\n\r\n\t\t\tint N = tmp.get_size(0), LE = tmp.get_size(1);\r\n\t\t\tfloat *pA = tmp.begin(), *pB = aTmp2.begin(), *pR = tmp2.begin();\r\n\r\n\t\t\t#pragma omp parallel for default(none) schedule(static) shared(N, pA, pB, pR, LE)\r\n\t\t\tfor (int iL = 0; iL < LE; iL++) {\r\n\t\t\t\tfor (int iE = 0; iE < N; iE++) {\r\n\t\t\t\t\tpR[iE + N*iL] = pA[iE + N*iL] - pB[iE];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t//MATLAB: (tmp - repmat(circshift(dSOSImg(:,idx(i)), iD),[1 size(tmp,2)])).^2\r\n\t\t\tmultiply(tmp2, tmp2, tmp2);\r\n\r\n\t\t\t//MATLAB: sum((tmp - repmat(circshift(dSOSImg(:,idx(i)), iD),[1 size(tmp,2)])).^2,2)\r\n\t\t\thoNDArray<float> hTmp2;\r\n\t\t\tif (tmp2.get_number_of_dimensions() > 1) {\r\n\t\t\t\tstd::vector<size_t> vD = *tmp2.get_dimensions();\r\n\t\t\t\tvD.pop_back();\r\n\t\t\t\thTmp2.create(&vD);\r\n\t\t\t\thTmp2.fill(0.0);\r\n\r\n\t\t\t\tfloat *pNewArray = hTmp2.get_data_ptr();\r\n\t\t\t\tfloat *pOldArray = tmp2.get_data_ptr();\r\n\t\t\t\tint N = tmp2.get_size(1);\r\n\t\t\t\tint L = hTmp2.get_number_of_elements();\r\n\r\n\t\t\t\t#pragma omp parallel for default(none) schedule(static) shared(N, L, pNewArray, pOldArray)\r\n\t\t\t\tfor (int sum_dim = 0; sum_dim < N; sum_dim++) {\r\n\t\t\t\t\tfor (int i = 0; i < L; i++) {\r\n\t\t\t\t\t\tpNewArray[i] += pOldArray[i + L*sum_dim];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t//MATLAB: dRMSImg(:,dDisplacement-iD+1) = sum((tmp - repmat(circshift(dSOSImg(:,idx(i)), iD),[1 size(tmp,2)])).^2,2)\r\n\t\t\tint iOffset = (iDisplacement-l)*hTmp2.get_size(0);\r\n\t\t\tmemcpy(aRMSImg.begin() + iOffset, hTmp2.begin(), sizeof(float)*hTmp2.get_size(0));\r\n\t\t}\r\n\r\n\t\t//MATLAB: sum(dRMSImg(dX-round(dDisplacement/2):dX+round(dDisplacement/2),:))\r\n\t\tvStart.clear();\r\n\t\tvStart.push_back(dX-static_cast<int>((static_cast<float>(iDisplacement)/2)+.5));\r\n\t\tvStart.push_back(0);\r\n\r\n\t\tvSize.clear();\r\n\t\tvSize.push_back(iDisplacement+1);\r\n\t\tvSize.push_back(aRMSImg.get_size(1));\r\n\r\n\t\tget_subarray(aRMSImg, vStart, vSize, aRMSImg);\r\n\r\n\t\thoNDArray<std::complex<float>> cfaRMSImgTest(aRMSImg.get_dimensions());\r\n\t\tcfaRMSImgTest.fill(std::complex<float>(0.0, 0.0));\r\n\t\tstd::complex<float> *cfPointer = cfaRMSImgTest.get_data_ptr();\r\n\t\tfor (size_t iI = 0; iI < cfaRMSImgTest.get_number_of_elements(); iI++) {\r\n\t\t\tcfPointer[iI] = std::complex<float>(aRMSImg.at(iI), 0.0);\r\n\t\t}\r\n\r\n\t\tsum_dim(aRMSImg, 0, aRMSImg);\r\n\r\n\t\tcfaRMSImgTest.clear();\r\n\t\tcfaRMSImgTest.create(aRMSImg.get_dimensions());\r\n\t\tcfaRMSImgTest.fill(std::complex<float>(0.0, 0.0));\r\n\t\tcfPointer = cfaRMSImgTest.get_data_ptr();\r\n\t\tfor (size_t iI = 0; iI < cfaRMSImgTest.get_number_of_elements(); iI++) {\r\n\t\t\tcfPointer[iI] = std::complex<float>(aRMSImg.at(iI), 0.0);\r\n\t\t}\r\n\r\n\t\t//MATLAB: min(sum(dRMSImg(dX-round(dDisplacement/2):dX+round(dDisplacement/2),:)))\r\n\t\t// TODO: change back to amin (Gadgetron project seems to introduce the error)\r\n// \t\tint iMinVal = amin(&aRMSImg);\r\n\t\tint iMinVal = aRMSImg.at(0);\r\n\t\tfor (size_t i = 0; i < aRMSImg.get_number_of_elements(); i++) {\r\n\t\t\tif (aRMSImg.at(i) < iMinVal) {\r\n\t\t\t\tiMinVal = aRMSImg.at(i);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//MATLAB: dDisplacement + 1 - dNav(i)\r\n\t\tnavigator_resp.at(i) = iDisplacement - iMinVal;\r\n\r\n\t\t//MATLAB: circshift(dSOSImg(:,idx(i)), dNav(i))\r\n\t\thoNDArray<float> aTmp3 = aTmp;\r\n\t\tcircshift(aTmp3, navigator_resp.at(i), 0);\r\n\r\n\t\tif (i%20 == 0) {\r\n\t\t\tGINFO(\"Getting Navigator - %.1f %%\\n\", static_cast<float>(aRefImg.get_size(1)-2-i)/static_cast<float>(aRefImg.get_size(1)-2)*100);\r\n\t\t}\r\n\r\n\t\t//MATLAB: dRefImg(:,idx(i)) = circshift(dSOSImg(:,idx(i)), dNav(i))\r\n\t\tmemcpy(aRefImg.get_data_ptr()+vIdx.at(i)*aRefImg.get_size(0), aTmp3.get_data_ptr(), sizeof(float)*aTmp3.get_size(0));\r\n\t}\r\n\r\n\tfor (size_t i = 0; i < navigator_resp.size(); i++) {\r\n\t\tnavigator_resp.at(i) *= -1;\r\n\t}\r\n\r\n\t// get Gaussian filter kernel and calculate convolution with navigator data\r\n\tvGaussian.clear();\r\n\tfilter1DGaussian(vGaussian, 5);\r\n\tvectorConv(navigator_resp, vGaussian, 0);\r\n\r\n\t//-------------------------------------------------------------------------\r\n\t// interpolate navigator data signal to TR intervals\r\n\tGINFO(\"interpolation of navigator data to TR intervals..\\n\");\r\n\r\n\tfor (size_t i = 0; i < navigator_resp.size(); i++) {\r\n\t\tnavigator_resp.at(i) = -navigator_resp.at(i);\r\n\t}\r\n\r\n\tint iMin = std::min_element(navigator_resp.begin(), navigator_resp.end())-navigator_resp.begin();\r\n\tfloat fMin = navigator_resp.at(iMin);\r\n\tfor (size_t i = 0; i < navigator_resp.size(); i++) {\r\n\t\tnavigator_resp.at(i) -= fMin;\r\n\t}\r\n\r\n\t// build vector with elements 0..lNoScans_ to interpolate navigator_resp_interpolated_ below\r\n\tstd::vector<float> vNavIndNew;\r\n\tfor (long i = 0; i < lNoScans_; i++) {\r\n\t\tvNavIndNew.push_back(i);\r\n\t}\r\n\r\n\tGDEBUG(\"vNavInd size: %i, navigator_resp size: %i, vNavIndNew size: %i\\n\", GlobalVar::instance()->vNavInd_.size(), navigator_resp.size(), vNavIndNew.size());\r\n\r\n\tstd::vector<float> vNavInd = GlobalVar::instance()->vNavInd_;\r\n\tnavigator_resp_interpolated_ = interp1<float>(vNavInd, navigator_resp, vNavIndNew);\r\n\r\n\treturn;\r\n}\r\n\r\n// get interpolated navigator signal by Principal Component Analysis\r\nvoid CS_Retro_NavigatorGadget::getNav2DPCA(hoNDArray<std::complex<float> > &aNav)\r\n{\r\n\tGDEBUG(\"\\n\\n**************************************\\n********** get navigator 2D **********\\n**************************************\\n\\n\");\r\n\r\n\t// reconstruct the 1-D projections for all measurements and all channels\r\n\tGINFO(\"domain transformation - k-space to image\\n\");\r\n\r\n\tsize_t iNSamples\t\t= aNav.get_size(0);\r\n\tsize_t iNMeasurement\t= aNav.get_size(1);\r\n\tsize_t iNavRes\t \t\t= aNav.get_size(2);\r\n\tsize_t iNChannels\t\t= aNav.get_size(3);\r\n\r\n\t/* MATLAB\r\n\t% Reconstruct the 1-D projections for all measurements and all channels\r\n\tdImg = fftshift(ifft(ifftshift(dKSpace)));\r\n\t*/\r\n\thoNDArray<std::complex<float> > aImg = aNav;\r\n\thoNDFFT_CS<float>::instance()->ifftshift3D(aImg);\r\n\thoNDFFT_CS<float>::instance()->ifft1(aImg);\r\n\thoNDFFT_CS<float>::instance()->fftshift3D(aImg);\r\n\r\n\t// ATTENTION: Work with [s] values\r\n\t// dNavPeriod = dNavPeriod/1000; dTR = dTR/1000;\r\n\tmin_card_freq_ /= 60;\r\n\tmax_card_freq_ /= 60;\r\n\tmin_resp_freq_ /= 60;\r\n\tmax_resp_freq_ /= 60;\r\n\r\n\t// 1. Step: Restack\r\n\t// is already done in C++ code\r\n\r\n\t// 2. Step: Compute PCA based on KLT principal components are saved in coeff in descending order\r\n\tstd::vector<size_t> coeff_dims;\r\n\tcoeff_dims.push_back(iNMeasurement);\r\n\tcoeff_dims.push_back(iNMeasurement);\r\n\r\n\thoNDArray<std::complex<float> > coeff;\r\n\tcoeff.create(&coeff_dims);\r\n\tcoeff.delete_data_on_destruct(true);\r\n\r\n\t// prepare aImg for KLT\r\n\t// first: permute\r\n\tstd::vector<size_t> aImg_new_order;\r\n\taImg_new_order.push_back(0);\r\n\taImg_new_order.push_back(2);\r\n\taImg_new_order.push_back(3);\r\n\taImg_new_order.push_back(1);\r\n\taImg = permute(aImg, aImg_new_order);\r\n\r\n\t// then reshape\r\n\tstd::vector<size_t> new_aImg_dims;\r\n\tnew_aImg_dims.push_back(iNSamples*iNavRes*iNChannels);\r\n\tnew_aImg_dims.push_back(iNMeasurement);\r\n\taImg.reshape(&new_aImg_dims);\r\n\r\n\tGINFO(\"Performing KLT (may take a while)\\n\");\r\n\r\n\thoNDKLT<std::complex<float> > VT;\r\n\tVT.prepare(aImg, static_cast<size_t>(1), static_cast<size_t>(0), true);\r\n\tVT.eigen_vector(coeff);\r\n\r\n\tGINFO(\"Continuing with search for motion\\n\");\r\n\r\n\t// 3. Step: search for respiratory motion\r\n\t// calculate frequency\r\n\t//%dFs = 1/((length(iLC)*dTR/1000)/(length(coeff)));\r\n\tdouble f_s = iNMeasurement/(lNoScans_*(GlobalVar::instance()->fTR_/1000.0)); // Get the sampling frequency (/1000 because fTR_ is in ms, not in s)\r\n\r\n\t// get next base of 2\r\n\t//%dFactorfft = 2.^nextpow2(size(dCoeff,1));\r\n\tunsigned int factor_fft = std::pow(2, std::ceil(log(coeff.get_size(0))/log(2)));\r\n\r\n\t// first zero padd coeff\r\n\thoNDArray<std::complex<float> > coeff_padded;\r\n\tstd::vector<size_t> coeff_padded_dims;\r\n\tcoeff_padded_dims.push_back(factor_fft);\r\n\tcoeff_padded_dims.push_back(coeff.get_size(1));\r\n\tcoeff_padded.create(&coeff_padded_dims);\r\n\tfor (size_t col = 0; col < coeff.get_size(1); col++) {\r\n\t\tsize_t offset_old = col * coeff.get_size(0);\r\n\t\tsize_t offset_new = col * coeff_padded.get_size(0);\r\n\t\tmemcpy(coeff_padded.get_data_ptr()+offset_new, coeff.get_data_ptr()+offset_old, coeff.get_size(0)*sizeof(coeff.at(0)));\r\n\t}\r\n\r\n\t// and continue with fft\r\n\t// note: ifftshift2D is done before zero padding, thus none here\r\n\thoNDFFT_CS<float>::instance()->fft1(coeff_padded);\r\n\r\n\t//%dCoeffF = abs(dCoeffF);\r\n\thoNDArray<float> coeff_abs;\r\n\tcoeff_abs.create(&coeff_padded_dims);\r\n\tfor (size_t i = 0; i < coeff_padded.get_number_of_elements(); i++) {\r\n\t\tcoeff_abs.at(i) = abs(coeff_padded.at(i));\r\n\t}\r\n\r\n\t// filtering\r\n\t// calculate lower and upper boundary frequency\r\n\t// Note: we only need the floor() value, so we build it directly instead of later on.\r\n\t//%Fl = dFactorfft/dFs * dCutOffResp(1);\r\n\tconst unsigned int resp_f_l = std::floor(factor_fft/f_s * min_resp_freq_);\r\n\t//%Fu = dFactorfft/dFs * dCutOffResp(2);\r\n\tconst unsigned int resp_f_u = std::floor(factor_fft/f_s * max_resp_freq_);\r\n\r\n\tif (resp_f_u <= resp_f_l) {\r\n\t\tGERROR(\"resp_f_u (=%d) must be greater than resp_f_l (=%d). Please set parameters correct!\\n\", resp_f_u, resp_f_l);\r\n\t\tthrow runtime_error(\"Illegal parameters min_resp_freq_ or max_resp_freq_!\");\r\n\t}\r\n\r\n\t// now get iPeak (dVal can be omitted). iPeak is the column number where the maximum value occures.\r\n\t// we could either implement it the Matlab way (crop hoNDArray, search max value per line and max col position)\r\n\t// or we do some intelligent data handling to get the position directly:\r\n\tfloat max_val = std::numeric_limits<float>::min();\t\t// initialize as minimum (it could also be 0 because coeff_abs only contains abs values)\r\n\tsize_t peak_position = 0;\t\t// note: -1 is insufficient because size_t is unsigned, so pos is max. But we will rewrite max_val either.\r\n\tfor (size_t f = static_cast<size_t>(resp_f_l); f <= static_cast<size_t>(resp_f_u); f++) {\r\n\t\tfor (size_t component_number = search_range_min_-1; component_number < search_range_max_; component_number++) {\t\t// be aware: search_range counts MATLAB like (from 1 to length)\r\n\t\t\tsize_t pos = component_number * coeff_abs.get_size(0) + f;\r\n\r\n\t\t\tif (max_val < coeff_abs.at(pos)) {\r\n\t\t\t\tmax_val = coeff_abs.at(pos);\r\n\t\t\t\tpeak_position = component_number;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t// now extract navi signal\r\n\t//%dRespNavi = real(dCoeff(:,iPeak)) - imag(dCoeff(:,iPeak));\r\n\tstd::vector<float> resp_navi;\r\n\r\n\tfor (size_t f = 0; f < coeff.get_size(0); f++) {\r\n\t\tsize_t pos = peak_position * coeff.get_size(0) + f;\r\n\t\tresp_navi.push_back(coeff.at(pos).real() - coeff.at(pos).imag());\r\n\t}\r\n\r\n\t// and convolute\r\n\t//%dRespNavi = conv(dRespNavi, fGaussianLP(5), 'same');\r\n\t// first build gaussian low pass\r\n\tstd::vector<float> gaussian_lowpass = {\r\n\t\t0.0269,\r\n\t\t0.2334,\r\n\t\t0.4794,\r\n\t\t0.2334,\r\n\t\t0.0269,\r\n\t};\r\n\t// convolute\r\n\tresp_navi = arma::conv_to<std::vector<float> >::from(arma::conv(arma::Col<float>(resp_navi), arma::Col<float>(gaussian_lowpass), \"same\"));\r\n\r\n\t// Note: Matlab implementation: %dRespNavi = -dRespNavi;\r\n\t// is implicitly done during KLT and can be omitted here\r\n\r\n\t// build vector with elements 0..lNoScans_ to interpolate navigator_resp_interpolated_ below\r\n\tstd::vector<float> nav_ind_new;\r\n\tfor (long i = 0; i < lNoScans_; i++) {\r\n\t\tnav_ind_new.push_back(i);\r\n\t}\r\n\r\n\t// get navigator indices\r\n\tstd::vector<float> nav_ind = GlobalVar::instance()->vNavInd_;\r\n\r\n\tGDEBUG(\"nav_ind size: %i, resp_navi size: %i, nav_ind_new size: %i\\n\", nav_ind.size(), resp_navi.size(), nav_ind_new.size());\r\n\r\n\t// interpolate to output vector\r\n\tnavigator_resp_interpolated_ = interp1<float>(nav_ind, resp_navi, nav_ind_new);\r\n\r\n\t// 4. Step: search for cardiac motion\r\n\t//%Fl = dFactorfft/dFs * dCutOffCard(1);\r\n\tconst unsigned int card_f_l = std::floor(factor_fft/f_s * min_card_freq_);\r\n\t//%Fu = dFactorfft/dFs * dCutOffCard(2);\r\n\tconst unsigned int card_f_u = std::floor(factor_fft/f_s * max_card_freq_);\r\n\r\n\tif (card_f_u <= card_f_l) {\r\n\t\tGERROR(\"card_f_u (=%d) must be greater than card_f_l (=%d). Please set parameters correct!\\n\", card_f_u, card_f_l);\r\n\t\tthrow runtime_error(\"Illegal parameters min_resp_freq_ or max_resp_freq_!\");\r\n\t}\r\n\r\n\t// now get iPeak (dVal can be omitted). iPeak is the column number where the maximum value occures.\r\n\t// we could either implement it the Matlab way (crop hoNDArray, search max value per line and max col position)\r\n\t// or we do some intelligent data handling to get the position directly:\r\n\tmax_val = std::numeric_limits<float>::min();\t\t// initialize as minimum (it could also be 0 because coeff_abs only contains abs values)\r\n\tpeak_position = 0;\t\t// note: -1 is insufficient because size_t is unsigned, so pos is max. But we will rewrite max_val either.\r\n\tfor (size_t f = static_cast<size_t>(card_f_l); f <= static_cast<size_t>(card_f_u); f++) {\r\n\t\tfor (size_t component_number = search_range_min_-1; component_number < search_range_max_; component_number++) {\t\t// be aware: search_range counts MATLAB like (from 1 to length)\r\n\t\t\tsize_t pos = component_number * coeff_abs.get_size(0) + f;\r\n\r\n\t\t\tif (max_val < coeff_abs.at(pos)) {\r\n\t\t\t\tmax_val = coeff_abs.at(pos);\r\n\t\t\t\tpeak_position = component_number;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t// now extract navi signal\r\n\t//%dCardNavi = real(dCoeff(:,iPeak)) - imag(dCoeff(:,iPeak));\r\n\tfor (size_t f = 0; f < coeff.get_size(0); f++) {\r\n\t\tsize_t pos = peak_position * coeff.get_size(0) + f;\r\n\t\tnavigator_card_interpolated_.push_back(coeff.at(pos).real() - coeff.at(pos).imag());\r\n\t}\r\n\r\n\t// interpolate signal\r\n\t//%dCardNavi = interp1(0:dNavPeriod:dNavPeriod*(size(dCoeff,1)-1), dCardNavi, 0:dTR:dTR*(length(iLC)-1), 'pchip');\r\n\t// first build new interpolation indices\r\n\tnav_ind.clear();\r\n\tnav_ind_new.clear();\r\n\tfor (unsigned int i = 0; i < GlobalVar::instance()->iNavPeriod_*(coeff.get_size(0)-1); i += GlobalVar::instance()->iNavPeriod_) {\r\n\t\tnav_ind.push_back(i);\r\n\t}\r\n\tfor (int counter = 0; counter < lNoScans_; counter++) {\r\n\t\tnav_ind_new.push_back(counter*GlobalVar::instance()->fTR_);\r\n\t}\r\n\tnavigator_card_interpolated_ = interp1<float>(nav_ind, navigator_card_interpolated_, nav_ind_new);\r\n\r\n\t// change f_s\r\n\t//%dFs = 1./(dTR/1000); % now interpolated to TR level\r\n\tf_s = 1.0f/(GlobalVar::instance()->fTR_/1000);\r\n\r\n\t// butterworth filtering\r\n\t// % smoothing and R-peak detection\r\n\t//%[b,a] = fButterself(dCutOffCard(1)/(dFs/2), dCutOffCard(2)/(dFs/2));\r\n\t//%dCardNavi = FiltFiltSelf(b,a,double(dCardNavi));\r\n\tbutterworth_filtering(min_card_freq_/(f_s/2.0f), max_card_freq_/(f_s/2.0f), navigator_card_interpolated_);\r\n\r\n\t//%dCardNavi = diff(dCardNavi); % search R-peak and differential signal\r\n\tnavigator_card_interpolated_ = arma::conv_to<std::vector<float> >::from(arma::diff(arma::Col<float>(navigator_card_interpolated_)));\r\n\r\n\t//%dECGInt_ms = (dCardNavi-min(dCardNavi(floor(length(dCardNavi)/10):floor(length(dCardNavi)*8/10))))/(max(dCardNavi(floor(length(dCardNavi)/10):floor(length(dCardNavi)*8/10)))-min(dCardNavi(floor(length(dCardNavi)/10):floor(length(dCardNavi)*8/10))));\r\n\t// first get correction factors\r\n\tfloat factor_subtract\t= *std::min_element(std::begin(navigator_card_interpolated_)+(navigator_card_interpolated_.size()/10), std::begin(navigator_card_interpolated_)+(navigator_card_interpolated_.size()*8/10));\t// note: integer divisions ensure std::floor()\r\n\tfloat factor_divide\t\t= *std::max_element(std::begin(navigator_card_interpolated_)+(navigator_card_interpolated_.size()/10), std::begin(navigator_card_interpolated_)+(navigator_card_interpolated_.size()*8/10)) - factor_subtract;\r\n\r\n\t// apply factors\r\n\tfor (size_t i = 0; i < navigator_card_interpolated_.size(); i++) {\r\n\t\tnavigator_card_interpolated_.at(i) = (navigator_card_interpolated_.at(i)-factor_subtract) / factor_divide;\r\n\t}\r\n}\r\n\r\nvoid CS_Retro_NavigatorGadget::butterworth_filtering(const double fl, const double fh, std::vector<float> &signal)\r\n{\r\n\t// Filter the Signal with a first order butterworth filter\r\n\r\n\t//===============================================================\r\n\t//calculate the numerator and denominator of a first order butterworth filter. (End of calulation is indicated by =======)\r\n\t//===============================================================\r\n\r\n\t//ul = 4*tan(pi*fl/2);\r\n\t//uh = 4*tan(pi*fh/2);\r\n\tfloat ul = 4*tan(M_PI*fl/2);\r\n\tfloat uh = 4*tan(M_PI*fh/2);\r\n\r\n\t//Bandwidth and center frequency\r\n\tfloat Bw = uh - ul;\r\n\tfloat Wn = std::sqrt(ul*uh);\r\n\r\n\t// Matlab:\r\n\t//t1 = [1+(Wn*(-Bw/Wn)/4) Wn/4; -Wn/4 1];\r\n\t//t2 = [1-(Wn*(-Bw/Wn)/4) -Wn/4; Wn/4 1];\r\n\t//ad = inv(t2)*t1;\r\n\t// Note: indexing follows mathematical convention: t1[row number][column number]\r\n\tfloat t1[2][2], t2[2][2];\r\n\tstd::complex<float> ad[2][2];\t// note: only real values in ad, but calculation of e later on must be complex\r\n\r\n\tt1[0][0] = 1+(Wn*(-Bw/Wn)/4);\r\n\tt1[0][1] = Wn/4;\r\n\tt1[1][0] = -Wn/4;\r\n\tt1[1][1] = 1;\r\n\r\n\t// also transpose\r\n\tt2[0][0]= 1-(Wn*(-Bw/Wn)/4);\r\n\tt2[0][1]= -Wn/4;\r\n\tt2[1][0]= Wn/4;\r\n\tt2[1][1]= 1;\r\n\r\n\t// matlab: ad = inv(t2)*t1;\r\n\tfloat det_t2 = t2[0][0]*t2[1][1]-t2[0][1]*t2[1][0];\r\n\tad[0][0] = (+t2[1][1]*t1[0][0]-t2[0][1]*t1[1][0])/det_t2;\r\n\tad[0][1] = (+t2[1][1]*t1[0][1]-t2[0][1]*t1[1][1])/det_t2;\r\n\tad[1][0] = (-t2[1][0]*t1[0][0]+t2[0][0]*t1[1][0])/det_t2;\r\n\tad[1][1] = (-t2[1][0]*t1[0][1]+t2[0][0]*t1[1][1])/det_t2;\r\n\r\n\t//%den = poly(ad);\r\n\t//e = eig(ad);\r\n\tstd::complex<float> e[2];\r\n\r\n\t// computate eigenvalues\r\n\te[0] = (ad[0][0]+ad[1][1]+std::sqrt(std::pow(ad[0][0]+ad[1][1], 2) - std::complex<float>(4)*(ad[0][0]*ad[1][1]-ad[0][1]*ad[1][0])))/std::complex<float>(2);\r\n\te[1] = (ad[0][0]+ad[1][1]-std::sqrt(std::pow(ad[0][0]+ad[1][1], 2) - std::complex<float>(4)*(ad[0][0]*ad[1][1]-ad[0][1]*ad[1][0])))/std::complex<float>(2);\r\n\r\n\tstd::complex<float> kern[3];\r\n\r\n\t//den = [1 0 0];\r\n\tfloat den[] = {1, 0, 0};\r\n\r\n\t// In Matlab:\r\n\t//% Expand recursion formula\r\n\t//den(2) = den(2) - e(1)*den(1);\r\n\t//den(3) = den(3) - e(2)*den(2);\r\n\t//den(2) = den(2) - e(2)*den(1);\r\n\t//\r\n\t// Some thoughts:\r\n\t//\t- e is either real or conjugate complex (see above)\r\n\t//\t- in complex case: calculation of den becomes real (because e conjugate complex)\r\n\t//\t- then: imaginary part can always be ignored and the matlab calculation reduces to:\r\n\tden[1] = -e[0].real() - e[1].real();\r\n\tden[2] = e[0].real() * e[1].real() + std::pow(e[0].imag(), 2);\r\n\r\n\tWn = 2*atan(Wn/4);\r\n\r\n\t//%  normalize so |H(w)| == 1:\r\n\t//%kern = exp(-1i*Wn*(0:2));\r\n\tfor (size_t k = 0; k < ARRAYSIZE(kern); k++) {\r\n\t\tkern[k] = std::exp(std::complex<float>(0.0, -1.0)*std::complex<float>(Wn)*std::complex<float>(k));\r\n\t}\r\n\r\n\t//f = (kern(1)*den(1)+kern(2)*den(2)+kern(3)*den(3))/(kern(1)-kern(3));\r\n\tstd::complex<float> f = (kern[0]*den[0]+kern[1]*den[1]+kern[2]*den[2])/(kern[0]-kern[2]);\r\n\r\n\tfloat num[3] = {f.real(), 0, -f.real()};\r\n\r\n\t//===========================================================\r\n\t//end of calculating the numerator and denominator of the first order butterworth filter\r\n\t//===========================================================\r\n\r\n\t//filtfilt() equivalent function. b = num and a = den\r\n\r\n\t//============================================================\r\n\t//start of zero phase digital filter function\r\n\t//============================================================\r\n\r\n\t//n    = length(den); always 3 in first order case\r\n\t//z(n) = 0;\r\n\t//num = num / den(1);\r\n\t//den = den / den(1);\r\n\tfloat z[3] = {0};\r\n\r\n\t//Y    = zeros(size(X));\r\n\t//for m = 1:length(Y)\r\n\t//  Y(m) = num(1) * X(m) + z(1);\r\n\t//   for i = 2:n\r\n\t//      z(i - 1) = num(i) * X(m) + z(i) - den(i) * Y(m);\r\n\t//   end\r\n\t//end\r\n\tstd::vector<float> Y;\r\n\tfor (size_t m = 0; m < signal.size(); m++) {\r\n\t\tY.push_back(num[0] * signal.at(m) + z[0]);\r\n\r\n\t\tfor (size_t i = 1; i < ARRAYSIZE(den); i++) {\r\n\t\t\tz[i-1] = num[i] * signal.at(m) + z[i] - den[i] * Y.at(m);\r\n\t\t}\r\n\t}\r\n\r\n\t//clear z\r\n\t//z(n) = 0;\r\n\tz[0] = 0;\r\n\tz[1] = 0;\r\n\tz[2] = 0;\r\n\r\n\t//flip vector\r\n\tstd::reverse(Y.begin(),Y.end());\r\n\tsignal.clear();\r\n\tsignal = Y;\r\n\r\n\t//Y    = zeros(size(X));\r\n\t// second round filtering (backward)\r\n\t//for m = 1:length(Y)\r\n\t//   Y(m) = b(1) * X(m) + z(1);\r\n\t//   for i = 2:n\r\n\t//      z(i - 1) = b(i) * X(m) + z(i) - a(i) * Y(m);\r\n\t//   end\r\n\t//end\r\n\tY.clear();\r\n\tfor (size_t m = 0; m < signal.size(); m++) {\r\n\t\tY.push_back(num[0] * signal.at(m) + z[0]);\r\n\r\n\t\tfor (size_t i = 1; i < ARRAYSIZE(den); i++) {\r\n\t\t\tz[i-1] = num[i] * signal.at(m) + z[i] - den[i] * Y.at(m);\r\n\t\t}\r\n\t}\r\n\r\n\t//flip again\r\n\tstd::reverse(Y.begin(),Y.end());\r\n\tsignal = Y;\r\n\tY.clear();\r\n\r\n\t//============================================================\r\n\t//end of zero phase digital filter function\r\n\t//============================================================\r\n}\r\n\r\nGADGET_FACTORY_DECLARE(CS_Retro_NavigatorGadget)\r\n", "meta": {"hexsha": "4b2d3f1f3ea304f7faaec7e0ae86bd5db7522299", "size": 39541, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "reconstruction/gadgetron/CS_LAB_Gadget/src/RETRO/CS_Retro_NavigatorGadget.cpp", "max_stars_repo_name": "alwaysbefun123/CS_MoCo_LAB", "max_stars_repo_head_hexsha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 83.0, "max_stars_repo_stars_event_min_datetime": "2017-08-11T09:18:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T03:08:00.000Z", "max_issues_repo_path": "reconstruction/gadgetron/CS_LAB_Gadget/src/RETRO/CS_Retro_NavigatorGadget.cpp", "max_issues_repo_name": "MrYuwan/CS_MoCo_LAB", "max_issues_repo_head_hexsha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-09-19T23:02:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-23T11:25:18.000Z", "max_forks_repo_path": "reconstruction/gadgetron/CS_LAB_Gadget/src/RETRO/CS_Retro_NavigatorGadget.cpp", "max_forks_repo_name": "MrYuwan/CS_MoCo_LAB", "max_forks_repo_head_hexsha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 49.0, "max_forks_repo_forks_event_min_datetime": "2017-03-19T18:41:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-25T08:25:44.000Z", "avg_line_length": 35.2415329768, "max_line_length": 259, "alphanum_fraction": 0.6455830657, "num_tokens": 12425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.27073188951632104}}
{"text": "//| This file is a part of the sferes2 framework.\n//| Copyright 2009, ISIR / Universite Pierre et Marie Curie (UPMC)\n//| Main contributor(s): Jean-Baptiste Mouret, mouret@isir.fr\n//|\n//| This software is a computer program whose purpose is to facilitate\n//| experiments in evolutionary computation and evolutionary robotics.\n//|\n//| This software is governed by the CeCILL license under French law\n//| and abiding by the rules of distribution of free software.  You\n//| can use, modify and/ or redistribute the software under the terms\n//| of the CeCILL license as circulated by CEA, CNRS and INRIA at the\n//| following URL \"http://www.cecill.info\".\n//|\n//| As a counterpart to the access to the source code and rights to\n//| copy, modify and redistribute granted by the license, users are\n//| provided only with a limited warranty and the software's author,\n//| the holder of the economic rights, and the successive licensors\n//| have only limited liability.\n//|\n//| In this respect, the user's attention is drawn to the risks\n//| associated with loading, using, modifying and/or developing or\n//| reproducing the software by the user in light of its specific\n//| status of free software, that may mean that it is complicated to\n//| manipulate, and that also therefore means that it is reserved for\n//| developers and experienced professionals having in-depth computer\n//| knowledge. Users are therefore encouraged to load and test the\n//| software's suitability as regards their requirements in conditions\n//| enabling the security of their systems and/or data to be ensured\n//| and, more generally, to use and operate it in the same conditions\n//| as regards security.\n//|\n//| The fact that you are presently reading this means that you have\n//| had knowledge of the CeCILL license and that you accept its terms.\n\n\n\n\n#ifndef PNSGA_HPP_\n#define PNSGA_HPP_\n\n#include <algorithm>\n#include <limits>\n\n#include <boost/foreach.hpp>\n\n#include <sferes/stc.hpp>\n#include <sferes/parallel.hpp>\n#include <sferes/ea/ea.hpp>\n#include <sferes/fit/fitness.hpp>\n#include <sferes/ea/dom_sort_basic.hpp>\n#include <sferes/ea/common.hpp>\n#include <sferes/ea/crowd.hpp>\n\n#ifdef ENABLE_TIMING\n#include \"clock.hpp\"\n#endif\n\nnamespace sferes\n{\nnamespace ea\n{\nnamespace pnsga\n{\nSFERES_CLASS(prob_dom_f){\npublic:\n    template<typename Indiv>\n    inline bool operator() (const Indiv &ind, const std::vector<Indiv>&pop) const{\n        dbg::trace trace(\"dom_sort_trace\" , DBG_HERE);\n        BOOST_FOREACH(Indiv i, pop){\n            if (dominate_flag(i, ind) == 1)\n                return false;\n        }\n        return true;\n    }\n\n    template<typename I1, typename I2>\n    inline int dominate_flag(const I1& i1, const I2& i2) const\n    {\n        dbg::trace trace(\"dom_sort_trace\" , DBG_HERE);\n        assert(i1->fit().objs().size());\n        assert(i2->fit().objs().size());\n        assert(i1->fit().objs().size() == i2->fit().objs().size());\n\n        size_t nb_objs = i1->fit().objs().size();\n        assert(nb_objs);\n\n        bool flag1 = false, flag2 = false;\n        for (unsigned i = 0; i < nb_objs; ++i)\n        {\n            assert(i < Params::ea::obj_pressure_size());\n            float pressure = Params::ea::obj_pressure(i);;\n#ifdef GRADUAL\n            if(i == 1) pressure = Params::ea::pressure;\n#endif\n            if (misc::rand<float>() > pressure)\n                continue;\n            float fi1 = i1->fit().obj(i);\n            float fi2 = i2->fit().obj(i);\n            if (fi1 > fi2)\n                flag1 = true;\n            else\n                if (fi2 > fi1)\n                    flag2 = true;\n        }\n        if (flag1 && !flag2)\n            return 1;\n        else\n            if (!flag1 && flag2)\n                return -1;\n            else\n                return 0;\n    }\n};\n}\n// Main class\nSFERES_EA(Pnsga, Ea)\n{\npublic:\n    typedef boost::shared_ptr<crowd::Indiv<Phen> > indiv_t;\n    typedef typename std::vector<indiv_t> pop_t;\n    typedef typename pop_t::iterator it_t;\n    typedef typename std::vector<std::vector<indiv_t> > front_t;\n\n\n    void random_pop()\n    {\n        parallel::init();\n\n        _parent_pop.resize(Params::pop::size);\n        assert(Params::pop::size % 4 == 0);\n\n        pop_t init_pop((size_t)(Params::pop::size * Params::pop::initial_aleat));\n        parallel::p_for(parallel::range_t(0, init_pop.size()), random<crowd::Indiv<Phen> >(init_pop));\n        _init_pop(init_pop);\n    }\n\n\n    void epoch()\n    {\n        //Clearing populations\n\n        _mixed_pop.clear();\n        _child_pop.clear();\n        this->_pop.clear();\n        _pareto_front.clear();\n\n        //Parent selection\n#ifdef ENABLE_TIMING\n        _epoch_clock.resetAndStart();\n        _parent_selection_clock.resetAndStart();\n#endif\n        _selection (_parent_pop, _child_pop);\n\n#ifdef ENABLE_TIMING\n        _parent_selection_clock.stop();\n        _mutate_clock.resetAndStart();\n#endif\n\n        //Mutation (and crossover, if applicable)\n\n        parallel::p_for(parallel::range_t(0, _child_pop.size()),\n                mutate<crowd::Indiv<Phen> >(_child_pop));\n\n#ifdef ENABLE_TIMING\n        _mutate_clock.stop();\n        _eval_clock.resetAndStart();\n#endif\n\n        //Evaluation\n#ifndef EA_EVAL_ALL\n        _eval_pop(_child_pop);\n        _merge(_parent_pop, _child_pop, _mixed_pop);\n#else\n        _merge(_parent_pop, _child_pop, _mixed_pop);\n        _eval_pop(_mixed_pop);\n#endif\n\n#ifdef ENABLE_TIMING\n        _eval_clock.stop();\n        _mod_clock.resetAndStart();\n#endif\n\n        //Apply modifiers (such as behavioral diversity)\n        _apply_modifier(_mixed_pop);\n\n#ifdef ENABLE_TIMING\n        _mod_clock.stop();\n        _survivor_selection_clock.resetAndStart();\n#endif\n\n#ifndef NDEBUG\n        BOOST_FOREACH(indiv_t & ind, _mixed_pop)\n        for (size_t i = 0; i < ind->fit().objs().size(); ++i)\n        {\n            assert(!std::isnan(ind->fit().objs()[i]));\n        }\n#endif\n        _fill_nondominated_sort(_mixed_pop, _parent_pop);\n        _convert_pop(_parent_pop, this->_pop);\n\n#ifdef ENABLE_TIMING\n        _survivor_selection_clock.stop();\n        _epoch_clock.stop();\n#endif\n        assert(_parent_pop.size() == Params::pop::size);\n        assert(_pareto_front.size() <= Params::pop::size * 2);\n        assert(this->_pop.size() == Params::pop::size);\n    }\n\n    const std::vector<boost::shared_ptr<Phen> >& pareto_front() const {\n        return _pareto_front;\n    }\n\n    const pop_t& mixed_pop() const{\n        return _mixed_pop;\n    }\n\n    const pop_t& parent_pop() const{\n        return _parent_pop;\n    }\n\n    const pop_t& child_pop() const{\n        return _child_pop;\n    }\n\n    void init_pop(std::vector<boost::shared_ptr<Phen> > population){\n        //        \tstd::cout << \"Reading population: pnsga\" << std::endl;\n        _mixed_pop.clear();\n        for (size_t i = 0; i < population.size(); ++i){\n            indiv_t indiv (new crowd::Indiv<Phen>(*population[i]));\n            _mixed_pop.push_back(indiv);\n        }\n        _init_pop(_mixed_pop);\n        _convert_pop(_parent_pop, this->_pop);\n    }\n\n    void init_parent_pop(std::vector<boost::shared_ptr<Phen> > population){\n        dbg::assertion(DBG_ASSERTION(population.size() <= Params::pop::size));\n        _parent_pop.clear();\n        for (size_t i = 0; i < Params::pop::size; ++i){\n            indiv_t indiv (new crowd::Indiv<Phen>(*population[i]));\n            _parent_pop.push_back(indiv);\n        }\n    }\n\n    void set_gen(size_t gen){\n        this->_gen = gen;\n    }\n\n    void best_pop(std::vector<boost::shared_ptr<Phen> >& population){\n        //        \tstd::cout << \"Reading population: pnsga\" << std::endl;\n        _mixed_pop.clear();\n        for (size_t i = 0; i < Params::pop::size*2; ++i){\n            indiv_t indiv (new crowd::Indiv<Phen>());\n            indiv->gen() = population[0]->gen();\n            _mixed_pop.push_back(indiv);\n        }\n        _init_pop(_mixed_pop);\n        _convert_pop(_parent_pop, this->_pop);\n    }\n\n#ifdef ENABLE_TIMING\npublic:\n    //Timing related functions\n    double getEpochTime() const{\n        return _epoch_clock.time();\n    }\n\n    double getParentSelectionTime() const{\n        return _parent_selection_clock.time();\n    }\n\n    double getMutateTime() const{\n        return _mutate_clock.time();\n    }\n\n    double getEvalTime() const{\n        return _eval_clock.time();\n    }\n\n    double getModTime() const{\n        return _mod_clock.time();\n    }\n\n    double getSurvivorSelectionTime() const{\n        return _survivor_selection_clock.time();\n    }\n\nprotected:\n    //Timing related variables\n    Clock _epoch_clock;\n    Clock _parent_selection_clock;\n    Clock _mutate_clock;\n    Clock _eval_clock;\n    Clock _mod_clock;\n    Clock _survivor_selection_clock;\n#endif\n\nprotected:\n\n    std::vector<boost::shared_ptr<Phen> > _pareto_front;\n\n    pop_t _parent_pop;\n    pop_t _child_pop;\n    pop_t _mixed_pop;\n\n    void _init_pop(pop_t& init_pop)\n    {\n        _eval_pop(init_pop);\n        _apply_modifier(init_pop);\n        front_t fronts;\n        _rank_crowd(init_pop, fronts);\n        _fill_nondominated_sort(init_pop, _parent_pop);\n\n    }\n\n    void _update_pareto_front(const front_t& fronts)\n    {\n        _convert_pop(fronts.front(), _pareto_front);\n    }\n\n    void _convert_pop(const pop_t& pop1, std::vector<boost::shared_ptr<Phen> >& pop2)\n    {\n        pop2.resize(pop1.size());\n        for (size_t i = 0; i < pop1.size(); ++i)\n            pop2[i] = pop1[i];\n    }\n\n    void _eval_pop(pop_t& pop)\n    {\n        this->_eval.eval(pop, 0, pop.size(), this->_fit_proto);\n    }\n\n    void _apply_modifier(pop_t& pop)\n    {\n        _convert_pop(pop, this->_pop);\n        this->apply_modifier();\n    }\n\n    void _fill_nondominated_sort(pop_t& mixed_pop, pop_t& new_pop)\n    {\n        assert(mixed_pop.size());\n        front_t fronts;\n#ifndef NDEBUG\n        BOOST_FOREACH(indiv_t & ind, mixed_pop)\n        for (size_t i = 0; i < ind->fit().objs().size(); ++i)\n        {\n            assert(!std::isnan(ind->fit().objs()[i]));\n        }\n#endif\n        _rank_crowd(mixed_pop, fronts);\n        new_pop.clear();\n\n        // fill the i first layers\n        size_t i;\n        for (i = 0; i < fronts.size(); ++i)\n            if (fronts[i].size() + new_pop.size() < Params::pop::size)\n                new_pop.insert(new_pop.end(), fronts[i].begin(), fronts[i].end());\n            else\n                break;\n\n        size_t size = Params::pop::size - new_pop.size();\n        // sort the last layer\n        if (new_pop.size() < Params::pop::size)\n        {\n            std::sort(fronts[i].begin(), fronts[i].end(), crowd::compare_crowd());\n            for (size_t k = 0; k < size; ++k)\n            {\n                assert(i < fronts.size());\n                new_pop.push_back(fronts[i][k]);\n            }\n        }\n        assert(new_pop.size() == Params::pop::size);\n    }\n\n    //\n    void _merge(const pop_t& pop1, const pop_t& pop2, pop_t& pop3)\n    {\n        assert(pop1.size());\n        assert(pop2.size());\n        pop3.clear();\n        pop3.insert(pop3.end(), pop1.begin(), pop1.end());\n        pop3.insert(pop3.end(), pop2.begin(), pop2.end());\n        assert(pop3.size() == pop1.size() + pop2.size());\n    }\n\n    // --- tournament selection ---\n    void _selection(pop_t& old_pop, pop_t& new_pop)\n    {\n        new_pop.resize(old_pop.size());\n        std::vector<size_t> a1, a2;\n        misc::rand_ind(a1, old_pop.size());\n        misc::rand_ind(a2, old_pop.size());\n        // todo : this loop could be parallelized\n        for (size_t i = 0; i < old_pop.size(); i += 4)\n        {\n            const indiv_t& p1 = _tournament(old_pop[a1[i]], old_pop[a1[i + 1]]);\n            const indiv_t& p2 = _tournament(old_pop[a1[i + 2]], old_pop[a1[i + 3]]);\n            const indiv_t& p3 = _tournament(old_pop[a2[i]], old_pop[a2[i + 1]]);\n            const indiv_t& p4 = _tournament(old_pop[a2[i + 2]], old_pop[a2[i + 3]]);\n            assert(i + 3 < new_pop.size());\n            p1->cross(p2, new_pop[i], new_pop[i + 1]);\n            p3->cross(p4, new_pop[i + 2], new_pop[i + 3]);\n        }\n    }\n\n    const indiv_t& _tournament(const indiv_t& i1, const indiv_t& i2)\n    {\n        pnsga::prob_dom_f<Params> p;\n        int flag = p.dominate_flag(i1, i2);\n        if (flag == 1)\n            return i1;\n        if (flag == -1)\n            return i2;\n        if (i1->crowd() > i2->crowd())\n            return i1;\n        if (i1->crowd() < i2->crowd())\n            return i2;\n        if (misc::flip_coin())\n            return i1;\n        else\n            return i2;\n    }\n\n    // --- rank & crowd ---\n    void _rank_crowd(pop_t& pop, front_t& fronts){\n        std::vector<size_t> ranks;\n#ifndef NDEBUG\n        BOOST_FOREACH(indiv_t& ind, pop)\n        for (size_t i = 0; i < ind->fit().objs().size(); ++i)\n        { assert(!std::isnan(ind->fit().objs()[i])); }\n#endif\n        typename Params::ea::dom_sort_f()(pop, fronts, pnsga::prob_dom_f<Params>(), ranks);\n        _update_pareto_front(fronts);\n        parallel::p_for(parallel::range_t(0, fronts.size()),\n                crowd::assign_crowd<indiv_t >(fronts));\n\n        for (size_t i = 0; i < ranks.size(); ++i)\n            pop[i]->set_rank(ranks[i]);\n        parallel::sort(pop.begin(), pop.end(), crowd::compare_ranks());;\n    }\n\n};\n}\n}\n#endif\n\n\n", "meta": {"hexsha": "33d8c093afa296468479df49c3b98724a31d8cfd", "size": 13199, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pnsga.hpp", "max_stars_repo_name": "JoostHuizinga/nsgaext", "max_stars_repo_head_hexsha": "3199c2e1aaff946bbc5f68745ac1e402951ba4db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pnsga.hpp", "max_issues_repo_name": "JoostHuizinga/nsgaext", "max_issues_repo_head_hexsha": "3199c2e1aaff946bbc5f68745ac1e402951ba4db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pnsga.hpp", "max_forks_repo_name": "JoostHuizinga/nsgaext", "max_forks_repo_head_hexsha": "3199c2e1aaff946bbc5f68745ac1e402951ba4db", "max_forks_repo_licenses": ["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.3964365256, "max_line_length": 102, "alphanum_fraction": 0.5938328661, "num_tokens": 3453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2707244073014906}}
{"text": "// Software License Agreement (BSD-3-Clause)\n//\n// Copyright 2018 The University of North Carolina at Chapel Hill\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\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\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\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//! @author Jeff Ichnowski\n\n#pragma once\n#ifndef NIGH_IMPL_REGION_LP_HPP\n#define NIGH_IMPL_REGION_LP_HPP\n\n#include \"region.hpp\"\n#include \"box_distance.hpp\"\n#include \"lp_sum.hpp\"\n#include <Eigen/Dense>\n#include <array>\n#include <type_traits>\n\nnamespace unc::robotics::nigh::impl {\n\n    template <typename Key, int dim, int p, typename Concurrency>\n    class LPRegion {\n        static constexpr int kDim = (dim == -1 ? Eigen::Dynamic : dim);\n        using Space = metric::Space<Key, metric::LP<p>>;\n        using Distance = typename Space::Distance;\n\n        Eigen::Matrix<Distance, kDim, 1> min_;\n        Eigen::Matrix<Distance, kDim, 1> max_;\n\n    public:\n        LPRegion() = default;\n        \n        LPRegion(const LPRegion& region)\n            : min_(region.min_)\n            , max_(region.max_)\n        {\n        }\n\n        template <typename Traversal>\n        LPRegion(const Space&, const Traversal&, const Key& q)\n            : min_(q), max_(q)\n        {\n        }\n        // LPRegion(const LPMetric<p>&, const T& q) : min_(q), max_(q) {}\n\n        template <typename D>\n        void init(const Space&, const Eigen::MatrixBase<D>& q) {\n            min_ = q;\n            max_ = q;\n        }\n        \n        template <typename D>\n        void grow(const Space&, const Eigen::MatrixBase<D>& q) {\n            min_ = min_.cwiseMin(q);\n            max_ = max_.cwiseMax(q);\n        }\n\n        template <typename D>\n        void init(const Space& space, const Eigen::ArrayBase<D>& q) {\n            init(space, q.matrix());\n        }\n\n        template <typename D>\n        void grow(const Space& space, const Eigen::ArrayBase<D>& q) {\n            grow(space, q.matrix());\n        }\n\n        template <std::size_t N>\n        std::enable_if_t<N == dim>\n        init(const Space& space, const std::array<Distance, N>& q) {\n            init(space, Eigen::Map<const Eigen::Matrix<Distance, dim, 1>>(q.data()));\n        }\n\n        template <std::size_t N>\n        std::enable_if_t<N == dim>\n        grow(const Space& space, const std::array<Distance, N>& q) {\n            grow(space, Eigen::Map<const Eigen::Matrix<Distance, dim, 1>>(q.data()));\n        }\n\n        template <typename Alloc>\n        void init(const Space& space, const std::vector<Distance, Alloc>& q) {\n            init(space, Eigen::Map<const Eigen::Matrix<Distance, dim, 1>>(q.data(), q.size()));\n        }\n\n        template <typename Alloc>\n        void grow(const Space& space, const std::vector<Distance, Alloc>& q) {\n            grow(space, Eigen::Map<const Eigen::Matrix<Distance, dim, 1>>(q.data(), q.size()));\n        }\n\n        constexpr unsigned dimensions() const {\n            return min_.size();\n        }\n\n        Distance selectAxis(unsigned *axis) const {\n            return (max_ - min_).maxCoeff(axis);\n        }\n\n        Distance distTo(const Key& key) const {\n            return boxDistance<p>(min_, max_, key);\n        }\n\n        Distance min(int index) const { return min_[index]; }\n        Distance max(int index) const { return max_[index]; }\n    };\n\n    template <typename Key, int dim, int p>\n    class LPRegion<Key, dim, p, Concurrent> {\n        static constexpr int kDim = dim;\n        using Space = metric::Space<Key, metric::LP<p>>;\n        using Distance = typename Space::Distance;\n\n        std::array<Atom<Distance, true>, kDim> min_;\n        std::array<Atom<Distance, true>, kDim> max_;\n\n    public:\n        LPRegion() = default;\n        \n        LPRegion(const LPRegion& other) {\n            for (int i=0 ; i<kDim ; ++i) {\n                min_[i].store(other.min_[i].load(std::memory_order_relaxed), std::memory_order_relaxed);\n                max_[i].store(other.max_[i].load(std::memory_order_relaxed), std::memory_order_relaxed);\n            }\n        }\n\n        template <typename Traversal>\n        LPRegion(const Space&, const Traversal&, const Key& q) {\n            // LPRegion(const metric::LP<p>&, const Q& q) {\n            for (int i=0 ; i<kDim ; ++i) {\n                min_[i].store(Space::coeff(q, i), std::memory_order_relaxed);\n                max_[i].store(Space::coeff(q, i), std::memory_order_relaxed);\n            }\n        }\n\n        constexpr unsigned dimensions() const {\n            return kDim;\n        }\n\n        Distance min(int index) const { return min_[index].load(std::memory_order_relaxed); }\n        Distance max(int index) const { return max_[index].load(std::memory_order_relaxed); }\n\n        template <typename State>\n        void grow(const Space&, const State& q) {\n            for (int i=0 ; i<kDim ; ++i) {\n                Distance v = Space::coeff(q, i);\n                for (Distance e = min(i) ; v < e && !min_[i].compare_exchange_weak(e, v, std::memory_order_relaxed); );\n                for (Distance e = max(i) ; v > e && !max_[i].compare_exchange_weak(e, v, std::memory_order_relaxed); );\n                // std::cout << \"region \" << i << \": \" << min_[i].load() << \" to \" << max_[i].load() << std::endl;\n            }\n        }\n\n        Distance selectAxis(unsigned *axis) const {\n            Distance dBest = max(0) - min(0);\n            *axis = 0;\n\n            for (int i=1 ; i<kDim ; ++i) {\n                Distance dx = max(i) - min(i);\n                if (dx > dBest) {\n                    dBest = dx;\n                    *axis = i;\n                }\n            }\n\n            return dBest;\n        }\n\n        Distance distTo(const Key& key) const {\n            Eigen::Matrix<Distance, kDim, 1> d;\n            for (int i=0 ; i<kDim ; ++i)\n                d[i] = std::max({\n                        min_[i].load(std::memory_order_relaxed) - Space::coeff(key, i),\n                        Space::coeff(key, i) - max_[i].load(std::memory_order_relaxed),\n                        static_cast<Distance>(0)\n                    });;\n            return d.template lpNorm<p>();\n        }\n    };\n\n    template <typename Key, int p>\n    class LPRegion<Key, -1, p, Concurrent> {\n        using Space = metric::Space<Key, metric::LP<p>>;\n        using Distance = typename Space::Distance;\n\n        // In order to put std::atomic into a vector, we need to\n        // provide a move constructor.  Since we only expect the move\n        // constructor to be used during initialization of the region,\n        // we can implement it with relaxed memory order.\n        struct Coeff : Atom<Distance, true> {\n            using Base = Atom<Distance, true>;\n            using Base::Base;\n            Coeff(const Coeff& other) : Base(other.load(std::memory_order_relaxed)) {}\n            Coeff(Coeff&& other) : Base(other.load(std::memory_order_relaxed)) {}\n        };\n\n        std::vector<Coeff> min_;\n        std::vector<Coeff> max_;\n\n    public:\n        LPRegion() = default;\n        \n        LPRegion(const LPRegion& other)\n            : min_(other.min_)\n            , max_(other.max_)\n        {\n        }\n\n        LPRegion(const Space&, LPRegion&& other)\n            : min_(std::move(other.min_))\n            , max_(std::move(other.max_))\n        {\n        }\n\n        template <typename Traversal>\n        LPRegion(const Space& space, const Traversal&, const Key& q) {\n            unsigned dim = space.dimensions();\n            min_.reserve(dim);\n            max_.reserve(dim);\n            for (unsigned i=0 ; i<dim ; ++i) {\n                min_.emplace_back(Space::coeff(q, i));\n                max_.emplace_back(Space::coeff(q, i));\n            }\n        }\n\n        unsigned dimensions() const {\n            return min_.size();\n        }\n\n        Distance min(int index) const { return min_[index].load(std::memory_order_relaxed); }\n        Distance max(int index) const { return max_[index].load(std::memory_order_relaxed); }\n\n        template <typename State>\n        void grow(const Space& space, const State& q) {\n            unsigned dim = space.dimensions();\n            assert(dim == min_.size());\n            for (unsigned i=0 ; i<dim ; ++i) {\n                Distance v = Space::coeff(q, i);\n                for (Distance e = min(i) ; v < e && !min_[i].compare_exchange_weak(e, v, std::memory_order_relaxed); );\n                for (Distance e = max(i) ; v > e && !max_[i].compare_exchange_weak(e, v, std::memory_order_relaxed); );\n                // std::cout << \"region \" << i << \": \" << min(i) << \" to \" << max(i) << std::endl;\n            }\n        }\n\n        Distance selectAxis(unsigned *axis) const {\n            int dimensions = min_.size();\n            Distance dBest = max(0) - min(0);\n            *axis = 0;\n\n            for (int i=1 ; i<dimensions ; ++i) {\n                Distance dx = max(i) - min(i);\n                if (dx > dBest) {\n                    dBest = dx;\n                    *axis = i;\n                }\n            }\n\n            return dBest;\n        }\n\n        Distance distTo(const Key& key) const {\n            std::size_t dimensions = min_.size();\n            impl::LPSum<p, Distance> sum(std::max({Distance(0), min(0) - key[0], key[0] - max(0)}));\n            for (std::size_t i=1 ; i<dimensions ; ++i)\n                sum += std::max({Distance(0), min(i) - key[i], key[i] - max(i)});\n            return sum;\n        }\n    };\n\n    template <typename Key, int p, typename Concurrency>\n    class Region<Key, metric::LP<p>, Concurrency>\n        : public LPRegion<Key, metric::Space<Key, metric::LP<p>>::kDimensions, p, Concurrency>\n    {\n    public:\n        using LPRegion<Key, metric::Space<Key, metric::LP<p>>::kDimensions, p, Concurrency>::LPRegion;\n    };\n\n}\n\n#endif\n", "meta": {"hexsha": "65f141e5d33d03ee2d0367a6a84f0750d763e4fa", "size": 11080, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/nigh/impl/region_lp.hpp", "max_stars_repo_name": "mengyu-fu/nigh", "max_stars_repo_head_hexsha": "da16672bf5b083c019d72b7f3df476c672bb78b4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2018-12-09T16:38:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T13:31:51.000Z", "max_issues_repo_path": "src/nigh/impl/region_lp.hpp", "max_issues_repo_name": "mengyu-fu/nigh", "max_issues_repo_head_hexsha": "da16672bf5b083c019d72b7f3df476c672bb78b4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-03-27T01:02:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-05T15:47:59.000Z", "max_forks_repo_path": "src/nigh/impl/region_lp.hpp", "max_forks_repo_name": "mengyu-fu/nigh", "max_forks_repo_head_hexsha": "da16672bf5b083c019d72b7f3df476c672bb78b4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-03-27T23:09:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-20T15:57:46.000Z", "avg_line_length": 36.2091503268, "max_line_length": 119, "alphanum_fraction": 0.5607400722, "num_tokens": 2643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.270682590973585}}
{"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 <fstream>\n\n#include <boost/filesystem.hpp>\n#include \"Problems/applicationOutput.h\"\n#include \"Problems/getAlgorithm.h\"\n#include \"Problems/saveOptimizationResults.h\"\n#include \"tudat/simulation/simulation.h\"\n#include \"tudat/astro/LowThrustTrajectories/lowThrustOptimisationSetup.h\"\n#include \"tudat/astro/LowThrustTrajectories/ShapeBasedMethods/hodographicShaping.h\"\n#include \"tudat/astro/LowThrustTrajectories/ShapeBasedMethods/sphericalShaping.h\"\n#include \"tudat/astro/LowThrustTrajectories/ShapeBasedMethods/createBaseFunctionHodographicShaping.h\"\n#include \"tudat/astro/LowThrustTrajectories/lowThrustLegSettings.h\"\n#include \"tudat/astro/LowThrustTrajectories/lowThrustLeg.h\"\n#include \"tudat/astro/ephemerides/approximatePlanetPositions.h\"\n#include \"tudat/astro/LowThrustTrajectories/ShapeBasedMethods/hodographicShapingOptimisationSetup.h\"\n#include \"tudat/astro/LowThrustTrajectories/ShapeBasedMethods/getRecommendedBaseFunctionsHodographicShaping.h\"\n\nusing namespace tudat;\n\n//! Execute  main\nint main( )\n{\n    //Set seed for reproducible results\n    pagmo::random_device::set_seed( 123 );\n\n    tudat::spice_interface::loadStandardSpiceKernels( );\n\n    // Ephemeris departure body.\n    ephemerides::EphemerisPointer pointerToDepartureBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions>(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::earthMoonBarycenter );\n\n    // Ephemeris arrival body.\n    ephemerides::EphemerisPointer pointerToArrivalBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::mars );\n\n    std::function< Eigen::Vector6d( const double ) > departureStateFunction = [ = ]( const double currentTime )\n    { return pointerToDepartureBodyEphemeris->getCartesianState( currentTime ); };\n\n    std::function< Eigen::Vector6d( const double ) > arrivalStateFunction = [ = ]( const double currentTime )\n    { return pointerToArrivalBodyEphemeris->getCartesianState( currentTime ); };\n\n\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    //////////////////////        GRID SEARCH FOR HODOGRAPHIC SHAPING LOWEST-ORDER SOLUTION            /////////////////////////\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    // Define bounds for departure date and time-of-flight.\n    std::pair< double, double > departureTimeBounds =\n            std::make_pair( 7304.5 * physical_constants::JULIAN_DAY, 10225.5 * physical_constants::JULIAN_DAY  );\n    std::pair< double, double > timeOfFlightBounds =\n            std::make_pair( 500.0 * physical_constants::JULIAN_DAY, 2000.0 * physical_constants::JULIAN_DAY );\n\n    // Initialize free coefficients vectors\n    Eigen::VectorXd freeCoefficientsRadialVelocityFunction = Eigen::VectorXd::Zero( 0 );\n    Eigen::VectorXd freeCoefficientsNormalVelocityFunction = Eigen::VectorXd::Zero( 0 );\n    Eigen::VectorXd freeCoefficientsAxialVelocityFunction = Eigen::VectorXd::Zero( 0 );\n\n    std::map< int, Eigen::Vector4d > hodographicShapingResultsLowOrder;\n\n    int numberCases = 0;\n\n    // for-loop parsing the time-of-flight values, ranging from 500 to 2000 days, with a time-step of 5 days.\n    for ( int i = 0 ; i <= ( timeOfFlightBounds.second - timeOfFlightBounds.first ) / ( 5.0 * physical_constants::JULIAN_DAY ) ; i++  )\n    {\n        double currentTOF = timeOfFlightBounds.first + i * 5.0 * physical_constants::JULIAN_DAY;\n\n        // Get recommended base functions for the radial velocity composite function.\n        std::vector< std::shared_ptr< shape_based_methods::BaseFunctionHodographicShaping > > radialVelocityFunctionComponents;\n        shape_based_methods::getRecommendedRadialVelocityBaseFunctions(\n                    radialVelocityFunctionComponents, freeCoefficientsRadialVelocityFunction, currentTOF );\n\n        // Get recommended base functions for the normal velocity composite function.\n        std::vector< std::shared_ptr< shape_based_methods::BaseFunctionHodographicShaping > > normalVelocityFunctionComponents;\n        shape_based_methods::getRecommendedNormalAxialBaseFunctions(\n                    normalVelocityFunctionComponents, freeCoefficientsNormalVelocityFunction, currentTOF );\n\n        // for-loop parsing the departure date values, ranging from 7304 MJD to 10225 MJD (with 401 steps)\n        for ( int j = 0 ; j <= 400; j++ )\n        {\n            double currentDepartureDate = departureTimeBounds.first + j * ( departureTimeBounds.second - departureTimeBounds.first ) / 400.0;\n\n            // Compute states at departure and arrival.\n            Eigen::Vector6d cartesianStateAtDeparture = pointerToDepartureBodyEphemeris->getCartesianState( currentDepartureDate );\n            Eigen::Vector6d cartesianStateAtArrival = pointerToArrivalBodyEphemeris->getCartesianState( currentDepartureDate + currentTOF );\n\n            int bestNumberOfRevolutions;\n            double currentBestDeltaV;\n\n            // Parse shaped trajectories with numbers of revolutions between 0 and 5.\n            for ( int currentNumberOfRevolutions = 0 ; currentNumberOfRevolutions <= 5 ; currentNumberOfRevolutions++ )\n            {\n                // Get recommended base functions for the axial velocity composite function.\n                std::vector< std::shared_ptr< shape_based_methods::BaseFunctionHodographicShaping > > axialVelocityFunctionComponents;\n                shape_based_methods::getRecommendedAxialVelocityBaseFunctions(\n                            axialVelocityFunctionComponents, freeCoefficientsAxialVelocityFunction, currentTOF,\n                            currentNumberOfRevolutions );\n\n                // Create hodographically shaped trajectory.\n                tudat::shape_based_methods::HodographicShaping hodographicShaping = shape_based_methods::HodographicShaping(\n                            cartesianStateAtDeparture, cartesianStateAtArrival, currentTOF,\n                            spice_interface::getBodyGravitationalParameter( \"Sun\" ), currentNumberOfRevolutions,\n                            radialVelocityFunctionComponents, normalVelocityFunctionComponents, axialVelocityFunctionComponents,\n                            freeCoefficientsRadialVelocityFunction, freeCoefficientsNormalVelocityFunction,\n                            freeCoefficientsAxialVelocityFunction );\n\n                // Save trajectory with the lowest deltaV.\n                if ( currentNumberOfRevolutions == 0 )\n                {\n                    bestNumberOfRevolutions = 0;\n                    currentBestDeltaV = hodographicShaping.computeDeltaV( );\n                }\n                else\n                {\n                    if ( hodographicShaping.computeDeltaV( ) < currentBestDeltaV )\n                    {\n                        currentBestDeltaV = hodographicShaping.computeDeltaV( );\n                        bestNumberOfRevolutions = currentNumberOfRevolutions;\n                    }\n                }\n            }\n\n            // Save results.\n            Eigen::Vector4d outputVector =\n                    ( Eigen::Vector4d( ) << currentTOF / physical_constants::JULIAN_DAY,\n                      currentDepartureDate / physical_constants::JULIAN_DAY, currentBestDeltaV, bestNumberOfRevolutions ).finished( );\n            numberCases++;\n            hodographicShapingResultsLowOrder[ numberCases ] = outputVector;\n\n        }\n    }\n\n    input_output::writeDataMapToTextFile( hodographicShapingResultsLowOrder,\n                                          \"hodographicShapingLowOrder.dat\",\n                                          tudat_pagmo_applications::getOutputPath( ),\n                                          \"\",\n                                          std::numeric_limits< double >::digits10,\n                                          std::numeric_limits< double >::digits10,\n                                          \",\" );\n\n\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    //////////////////////        RESTRICTED GRID SEARCH FOR HODOGRAPHIC SHAPING HIGH-ORDER SOLUTION             ///////////////\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    numberCases = 0;\n\n    // Define lower and upper bounds for the radial velocity free coefficients.\n    std::vector< std::vector< double > > bounds( 2, std::vector< double >( 2, 0.0 ) );\n    bounds[ 0 ][ 0 ] = - 600.0;\n    bounds[ 1 ][ 0 ] = 800.0;\n    bounds[ 0 ][ 1 ] = 0.0;\n    bounds[ 1 ][ 1 ] = 1500.0;\n\n    // Set fixed number of revolutions.\n    int numberOfRevolutions = 1;\n\n    std::map< int, Eigen::Vector4d > hodographicShapingResultsHigherOrder;\n    std::map< int, Eigen::Vector4d > hodographicShapingResultsLowOrderOneRevolution;\n\n    // for-loop parsing the time-of-flight values, ranging from 500 to 900 days, with a time-step of 20 days.\n    for ( int i = 0 ; i <= ( 900.0 * physical_constants::JULIAN_DAY - timeOfFlightBounds.first ) / ( 20 * physical_constants::JULIAN_DAY ) ; i++  )\n    {\n        double currentTOF = timeOfFlightBounds.first + i * 20.0 * physical_constants::JULIAN_DAY;\n\n        double frequency = 2.0 * mathematical_constants::PI / currentTOF;\n        double scaleFactor = 1.0 / currentTOF;\n\n        // Define settings for the two additional base functions for the radial velocity composite function.\n        std::shared_ptr< shape_based_methods::BaseFunctionHodographicShapingSettings > fourthRadialVelocityBaseFunctionSettings =\n                std::make_shared< shape_based_methods::PowerTimesTrigonometricFunctionHodographicShapingSettings >(\n                    1.0, 0.5 * frequency, scaleFactor );\n        std::shared_ptr< shape_based_methods::BaseFunctionHodographicShapingSettings > fifthRadialVelocityBaseFunctionSettings =\n                std::make_shared< shape_based_methods::PowerTimesTrigonometricFunctionHodographicShapingSettings >(\n                    1.0, 0.5 * frequency, scaleFactor );\n\n        // Get recommended base functions for the radial velocity composite function, and add two additional base functions\n        // (introducing two degrees of freedom in the trajectory design problem).\n        std::vector< std::shared_ptr< shape_based_methods::BaseFunctionHodographicShaping > > radialVelocityFunctionComponents;\n        shape_based_methods::getRecommendedRadialVelocityBaseFunctions( radialVelocityFunctionComponents, freeCoefficientsRadialVelocityFunction, currentTOF );\n        radialVelocityFunctionComponents.push_back(\n                    createBaseFunctionHodographicShaping( shape_based_methods::scaledPowerSine, fourthRadialVelocityBaseFunctionSettings ) );\n        radialVelocityFunctionComponents.push_back(\n                    createBaseFunctionHodographicShaping( shape_based_methods::scaledPowerCosine, fifthRadialVelocityBaseFunctionSettings ) );\n\n        // Get recommended base functions for the normal velocity composite function.\n        std::vector< std::shared_ptr< shape_based_methods::BaseFunctionHodographicShaping > > normalVelocityFunctionComponents;\n        shape_based_methods::getRecommendedNormalAxialBaseFunctions( normalVelocityFunctionComponents, freeCoefficientsNormalVelocityFunction, currentTOF );\n\n\n        // for-loop parsing departure dates ranging from 7304 MJD to 7379 MJD (with a time-step of 15 days).\n        for ( int j = 0 ; j <= ( 7379.5 * physical_constants::JULIAN_DAY - departureTimeBounds.first ) / ( 15 * physical_constants::JULIAN_DAY ); j++ )\n        {\n            double currentDepartureDate = departureTimeBounds.first +\n                    j * 15.0 * physical_constants::JULIAN_DAY;\n\n            // Compute states at departure and arrival.\n            Eigen::Vector6d cartesianStateAtDeparture = pointerToDepartureBodyEphemeris->getCartesianState( currentDepartureDate );\n            Eigen::Vector6d cartesianStateAtArrival = pointerToArrivalBodyEphemeris->getCartesianState( currentDepartureDate + currentTOF );\n\n\n            // Get recommended base functions for the axial velocity composite function.\n            std::vector< std::shared_ptr< shape_based_methods::BaseFunctionHodographicShaping > > axialVelocityFunctionComponents;\n            shape_based_methods::getRecommendedAxialVelocityBaseFunctions( axialVelocityFunctionComponents, freeCoefficientsAxialVelocityFunction,\n                                                                           currentTOF, numberOfRevolutions );\n\n\n            // Create hodographic shaping optimisation problem.\n            problem prob{ shape_based_methods::FixedTimeHodographicShapingOptimisationProblem(\n                            cartesianStateAtDeparture, cartesianStateAtArrival, currentTOF,\n                            spice_interface::getBodyGravitationalParameter( \"Sun\" ), numberOfRevolutions,\n                            radialVelocityFunctionComponents,\n                            normalVelocityFunctionComponents, axialVelocityFunctionComponents, bounds ) };\n\n            // Perform optimisation.\n            algorithm algo{ pagmo::sga( ) };\n\n            // Create an island with 1024 individuals\n            island isl{ algo, prob, 25 };\n\n            // Evolve for 100 generations\n            for( int i = 0 ; i < 10; i++ )\n            {\n                isl.evolve( );\n                while( isl.status( ) != pagmo::evolve_status::idle &&\n                       isl.status( ) != pagmo::evolve_status::idle_error )\n                {\n                    isl.wait( );\n                }\n                isl.wait_check( ); // Raises errors\n\n            }\n\n            // Save high-order shaping solution.\n            double currentBestDeltaV = isl.get_population( ).champion_f( )[ 0 ];\n\n            Eigen::Vector4d outputVector = ( Eigen::Vector4d( ) << currentTOF / physical_constants::JULIAN_DAY,\n                                             currentDepartureDate / physical_constants::JULIAN_DAY, currentBestDeltaV, 1 ).finished( );\n\n            hodographicShapingResultsHigherOrder[ numberCases ] = outputVector;\n\n\n            // Compute corresponding low-order hodographic shaping solution.\n            Eigen::VectorXd freeCoefficientsRadialVelocityFunction = Eigen::VectorXd::Zero( 2 );\n            Eigen::VectorXd freeCoefficientsNormalVelocityFunction = Eigen::VectorXd::Zero( 0 );\n            Eigen::VectorXd freeCoefficientsAxialVelocityFunction = Eigen::VectorXd::Zero( 0 );\n\n            // Compute low-order hodographically shaped trajectory (number of revolutions set to 1).\n            tudat::shape_based_methods::HodographicShaping hodographicShapingLowOrderOneRevolution = shape_based_methods::HodographicShaping(\n                        cartesianStateAtDeparture, cartesianStateAtArrival, currentTOF,\n                        spice_interface::getBodyGravitationalParameter( \"Sun\" ), numberOfRevolutions,\n                        radialVelocityFunctionComponents, normalVelocityFunctionComponents, axialVelocityFunctionComponents,\n                        freeCoefficientsRadialVelocityFunction, freeCoefficientsNormalVelocityFunction, freeCoefficientsAxialVelocityFunction );\n\n            // Save low-order shaping solution.\n            outputVector = ( Eigen::Vector4d( ) << currentTOF / physical_constants::JULIAN_DAY,\n                             currentDepartureDate / physical_constants::JULIAN_DAY, hodographicShapingLowOrderOneRevolution.computeDeltaV( ), 1 ).finished( );\n            hodographicShapingResultsLowOrderOneRevolution[ numberCases ] = outputVector;\n\n            numberCases++;\n\n        }\n    }\n\n    input_output::writeDataMapToTextFile( hodographicShapingResultsLowOrderOneRevolution,\n                                          \"hodographicShapingLowOrderOneRevolution.dat\",\n                                          tudat_pagmo_applications::getOutputPath( ),\n                                          \"\",\n                                          std::numeric_limits< double >::digits10,\n                                          std::numeric_limits< double >::digits10,\n                                          \",\" );\n\n    input_output::writeDataMapToTextFile( hodographicShapingResultsHigherOrder,\n                                          \"hodographicShapingHigherOrder.dat\",\n                                          tudat_pagmo_applications::getOutputPath( ),\n                                          \"\",\n                                          std::numeric_limits< double >::digits10,\n                                          std::numeric_limits< double >::digits10,\n                                          \",\" );\n\n    return 0;\n\n}\n", "meta": {"hexsha": "1cedba4dd11dd553bc6ceb74f8e8b67e047dd7a2", "size": 17254, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/pagmo/hodographicShapingTrajectoryExample.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/pagmo/hodographicShapingTrajectoryExample.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/pagmo/hodographicShapingTrajectoryExample.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": 58.6870748299, "max_line_length": 159, "alphanum_fraction": 0.6425176771, "num_tokens": 3579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.27068258546251345}}
{"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#include \"rbm_multival.hpp\"\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <map>\n#include <vector>\n#include \"Utils/all_utils.hpp\"\n#include \"Utils/log_cosh.hpp\"\n#include \"abstract_machine.hpp\"\n#include \"rbm_spin.hpp\"\n\nnamespace netket {\n\nRbmMultival::RbmMultival(std::shared_ptr<const AbstractHilbert> hilbert,\n                         int nhidden, int alpha, bool usea, bool useb)\n    : AbstractMachine(hilbert),\n      nv_(hilbert->Size()),\n      ls_(hilbert->LocalSize()),\n      usea_(usea),\n      useb_(useb) {\n  nh_ = std::max(nhidden, alpha * nv_);\n  Init();\n}\n\nvoid RbmMultival::Init() {\n  W_.resize(nv_ * ls_, nh_);\n  a_.resize(nv_ * ls_);\n  b_.resize(nh_);\n\n  thetas_.resize(nh_);\n  lnthetas_.resize(nh_);\n  thetasnew_.resize(nh_);\n  lnthetasnew_.resize(nh_);\n\n  npar_ = nv_ * nh_ * ls_;\n\n  if (usea_) {\n    npar_ += nv_ * ls_;\n  } else {\n    a_.setZero();\n  }\n\n  if (useb_) {\n    npar_ += nh_;\n  } else {\n    b_.setZero();\n  }\n\n  auto localstates = GetHilbert().LocalStates();\n\n  localconfs_.resize(nv_ * ls_);\n  for (int i = 0; i < nv_ * ls_; i += ls_) {\n    for (int j = 0; j < ls_; j++) {\n      localconfs_(i + j) = localstates[j];\n    }\n  }\n\n  mask_.resize(nv_ * ls_, nv_);\n  mask_.setZero();\n\n  for (int i = 0; i < nv_ * ls_; i++) {\n    mask_(i, i / ls_) = 1;\n  }\n\n  for (int i = 0; i < ls_; i++) {\n    confindex_[localstates[i]] = i;\n  }\n\n  vtilde_.resize(nv_ * ls_);\n\n  InfoMessage() << \"RBM Multival Initizialized with nvisible = \" << nv_\n                << \" and nhidden = \" << nh_ << std::endl;\n  InfoMessage() << \"Using visible bias = \" << usea_ << std::endl;\n  InfoMessage() << \"Using hidden bias  = \" << useb_ << std::endl;\n  InfoMessage() << \"Local size is      = \" << ls_ << std::endl;\n}\n\nint RbmMultival::Nvisible() const { return nv_; }\n\nint RbmMultival::Npar() const { return npar_; }\n\nany RbmMultival::InitLookup(VisibleConstType v) {\n  LookupType lt;\n  lt.resize(b_.size());\n  ComputeTheta(v, lt);\n  return any{std::move(lt)};\n}\n\nvoid RbmMultival::UpdateLookup(VisibleConstType v,\n                               const std::vector<int> &tochange,\n                               const std::vector<double> &newconf,\n                               any &lookup) {\n  if (tochange.size() != 0) {\n    auto &lt = any_cast_ref<LookupType>(lookup);\n    for (std::size_t s = 0; s < tochange.size(); s++) {\n      const int sf = tochange[s];\n      const int oldtilde = confindex_[v[sf]];\n      const int newtilde = confindex_[newconf[s]];\n\n      lt -= W_.row(ls_ * sf + oldtilde);\n      lt += W_.row(ls_ * sf + newtilde);\n    }\n  }\n}\n\nRbmMultival::VectorType RbmMultival::DerLogSingle(VisibleConstType v,\n                                                  const any &lookup) {\n  return DerLogSingleImpl(v, lookup.empty() ? InitLookup(v) : lookup);\n}\n\nRbmMultival::VectorType RbmMultival::DerLogSingleImpl(VisibleConstType v,\n                                                      const any &lookup) {\n  VectorType der(npar_);\n  der.setZero();\n\n  ComputeVtilde(v, vtilde_);\n\n  int k = 0;\n\n  if (usea_) {\n    for (; k < nv_ * ls_; k++) {\n      der(k) = vtilde_(k);\n    }\n  }\n\n  lnthetas_ = (any_cast_ref<LookupType>(lookup)).array().tanh();\n\n  if (useb_) {\n    for (int p = 0; p < nh_; p++) {\n      der(k) = lnthetas_(p);\n      k++;\n    }\n  }\n\n  for (int i = 0; i < nv_ * ls_; i++) {\n    for (int j = 0; j < nh_; j++) {\n      der(k) = lnthetas_(j) * vtilde_(i);\n      k++;\n    }\n  }\n  return der;\n}\n\nRbmMultival::VectorType RbmMultival::GetParameters() {\n  VectorType pars(npar_);\n\n  int k = 0;\n\n  if (usea_) {\n    for (; k < nv_ * ls_; k++) {\n      pars(k) = a_(k);\n    }\n  }\n\n  if (useb_) {\n    for (int p = 0; p < nh_; p++) {\n      pars(k) = b_(p);\n      k++;\n    }\n  }\n\n  for (int i = 0; i < nv_ * ls_; i++) {\n    for (int j = 0; j < nh_; j++) {\n      pars(k) = W_(i, j);\n      k++;\n    }\n  }\n\n  return pars;\n}\n\nvoid RbmMultival::SetParameters(VectorConstRefType pars) {\n  int k = 0;\n\n  if (usea_) {\n    for (; k < nv_ * ls_; k++) {\n      a_(k) = pars(k);\n    }\n  }\n\n  if (useb_) {\n    for (int p = 0; p < nh_; p++) {\n      b_(p) = pars(k);\n      k++;\n    }\n  }\n\n  for (int i = 0; i < nv_ * ls_; i++) {\n    for (int j = 0; j < nh_; j++) {\n      W_(i, j) = pars(k);\n      k++;\n    }\n  }\n}\n\n// Value of the logarithm of the wave-function\n// using pre-computed look-up tables for efficiency\nComplex RbmMultival::LogValSingle(VisibleConstType v, const any &lt) {\n  if (lt.empty()) {\n    ComputeTheta(v, thetas_);\n\n    return (vtilde_.dot(a_) + SumLogCosh(thetas_));\n  }\n\n  ComputeVtilde(v, vtilde_);\n  return (vtilde_.dot(a_) + SumLogCosh(any_cast_ref<LookupType>(lt)));\n}\n\n// Difference between logarithms of values, when one or more visible variables\n// are being changed\nvoid RbmMultival::LogValDiff(VisibleConstType v,\n                             const std::vector<std::vector<int>> &tochange,\n                             const std::vector<std::vector<double>> &newconf,\n                             Eigen::Ref<Eigen::VectorXcd> logvaldiffs) {\n  const std::size_t nconn = tochange.size();\n  logvaldiffs = VectorType::Zero(nconn);\n\n  ComputeTheta(v, thetas_);\n\n  Complex logtsum = SumLogCosh(thetas_);\n\n  for (std::size_t k = 0; k < nconn; k++) {\n    if (tochange[k].size() != 0) {\n      thetasnew_ = thetas_;\n\n      for (std::size_t s = 0; s < tochange[k].size(); s++) {\n        const int sf = tochange[k][s];\n        const int oldtilde = confindex_[v[sf]];\n        const int newtilde = confindex_[newconf[k][s]];\n\n        logvaldiffs(k) -= a_(ls_ * sf + oldtilde);\n        logvaldiffs(k) += a_(ls_ * sf + newtilde);\n\n        thetasnew_ -= W_.row(ls_ * sf + oldtilde);\n        thetasnew_ += W_.row(ls_ * sf + newtilde);\n      }\n\n      logvaldiffs(k) += SumLogCosh(thetasnew_) - logtsum;\n    }\n  }\n}\n\n#if 0\n// Computhes the values of the theta pseudo-angles\ninline void RbmMultival::ComputeTheta(VisibleConstType v, VectorType &theta) {\n  ComputeVtilde(v, vtilde_);\n  theta = (W_.transpose() * vtilde_ + b_);\n}\n\ninline void RbmMultival::ComputeVtilde(VisibleConstType v,\n                                       Eigen::VectorXd &vtilde) {\n  auto t = (localconfs_.array() == (mask_ * v).array());\n  vtilde = t.template cast<double>();\n}\n#endif\n\nvoid RbmMultival::Save(const std::string &filename) const {\n  json state;\n  state[\"Name\"] = \"RbmMultival\";\n  state[\"Nvisible\"] = nv_;\n  state[\"Nhidden\"] = nh_;\n  state[\"LocalSize\"] = ls_;\n  state[\"UseVisibleBias\"] = usea_;\n  state[\"UseHiddenBias\"] = useb_;\n  state[\"a\"] = a_;\n  state[\"b\"] = b_;\n  state[\"W\"] = W_;\n  WriteJsonToFile(state, filename);\n}\n\nvoid RbmMultival::Load(const std::string &filename) {\n  auto const pars = ReadJsonFromFile(filename);\n  if (pars.at(\"Name\") != \"RbmMultival\") {\n    throw InvalidInputError(\n        \"Error while constructing RbmMultival from Json input\");\n  }\n\n  if (FieldExists(pars, \"Nvisible\")) {\n    nv_ = pars[\"Nvisible\"];\n  }\n\n  if (nv_ != GetHilbert().Size()) {\n    throw InvalidInputError(\n        \"Loaded wave-function has incompatible Hilbert space\");\n  }\n\n  if (FieldExists(pars, \"LocalSize\")) {\n    ls_ = pars[\"LocalSize\"];\n  }\n  if (ls_ != GetHilbert().LocalSize()) {\n    throw InvalidInputError(\n        \"Loaded wave-function has incompatible Hilbert space\");\n  }\n\n  if (FieldExists(pars, \"Nhidden\")) {\n    nh_ = FieldVal(pars, \"Nhidden\");\n  } else {\n    nh_ = nv_ * double(FieldVal(pars, \"Alpha\"));\n  }\n\n  usea_ = FieldOrDefaultVal(pars, \"UseVisibleBias\", true);\n  useb_ = FieldOrDefaultVal(pars, \"UseHiddenBias\", true);\n\n  Init();\n\n  // Loading parameters, if defined in the input\n  if (FieldExists(pars, \"a\")) {\n    a_ = pars[\"a\"];\n  } else {\n    a_.setZero();\n  }\n\n  if (FieldExists(pars, \"b\")) {\n    b_ = pars[\"b\"];\n  } else {\n    b_.setZero();\n  }\n  if (FieldExists(pars, \"W\")) {\n    W_ = pars[\"W\"];\n  }\n}\n\nbool RbmMultival::IsHolomorphic() const noexcept { return true; }\n\n}  // namespace netket\n", "meta": {"hexsha": "ce2f13c79a7889102a0dded811e9f62e4b6f0962", "size": 8442, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Sources/Machine/rbm_multival.cc", "max_stars_repo_name": "vigsterkr/netket", "max_stars_repo_head_hexsha": "1e187ae2b9d2aa3f2e53b09fe743e50763d04c9a", "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": "Sources/Machine/rbm_multival.cc", "max_issues_repo_name": "vigsterkr/netket", "max_issues_repo_head_hexsha": "1e187ae2b9d2aa3f2e53b09fe743e50763d04c9a", "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": "Sources/Machine/rbm_multival.cc", "max_forks_repo_name": "vigsterkr/netket", "max_forks_repo_head_hexsha": "1e187ae2b9d2aa3f2e53b09fe743e50763d04c9a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8294117647, "max_line_length": 78, "alphanum_fraction": 0.5832741057, "num_tokens": 2594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2706716178980064}}
{"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// @file This module implements two binding commitment schemes used in the Groth16\n// aggregation.\n// The first one is a commitment scheme that commits to a single vector $a$ of\n// length n in the second base group $G_1$ (for example):\n// * it requires a structured SRS $v_1$ of the form $(h,h^u,h^{u^2}, ...\n// ,g^{h^{n-1}})$ with $h \\in G_2$ being a random generator of $G_2$ and $u$ a\n// random scalar (coming from a power of tau ceremony for example)\n// * it requires a second structured SRS $v_2$ of the form $(h,h^v,h^{v^2},\n// ...$ with $v$ being a random scalar different than u (coming from another\n// power of tau ceremony for example)\n// The Commitment is a tuple $(\\prod_{i=0}^{n-1} e(a_i,v_{1,i}),\n// \\prod_{i=0}^{n-1} e(a_i,v_{2,i}))$\n//\n// The second one takes two vectors $a \\in G_1^n$ and $b \\in G_2^n$ and commits\n// to them using a similar approach as above. It requires an additional SRS\n// though:\n// * $v_1$ and $v_2$ stay the same\n// * An additional tuple $w_1 = (g^{u^n},g^{u^{n+1}},...g^{u^{2n-1}})$ and $w_2 =\n// (g^{v^n},g^{v^{n+1},...,g^{v^{2n-1}})$ where $g$ is a random generator of\n// $G_1$\n// The commitment scheme returns a tuple:\n// * $\\prod_{i=0}^{n-1} e(a_i,v_{1,i})e(w_{1,i},b_i)$\n// * $\\prod_{i=0}^{n-1} e(a_i,v_{2,i})e(w_{2,i},b_i)$\n//\n// The second commitment scheme enables to save some KZG verification in the\n// verifier of the Groth16 verification protocol since we pack two vectors in\n// one commitment.\n\n#ifndef CRYPTO3_R1CS_GG_PPZKSNARK_IPP2_COMMITMENT_HPP\n#define CRYPTO3_R1CS_GG_PPZKSNARK_IPP2_COMMITMENT_HPP\n\n#include <tuple>\n#include <vector>\n\n#include <boost/assert.hpp>\n#include <boost/iterator/zip_iterator.hpp>\n\n#include <nil/crypto3/algebra/type_traits.hpp>\n\n#include <nil/crypto3/algebra/algorithms/pair.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace zk {\n            namespace snark {\n                /// Both commitment outputs a pair of $F_q^k$ element.\n                template<typename CurveType>\n                using r1cs_gg_ppzksnark_ipp2_commitment_output =\n                    std::pair<typename CurveType::scalar_field_type::value_type,\n                              typename CurveType::scalar_field_type::value_type>;\n\n                /// Key is a generic commitment key that is instanciated with g and h as basis,\n                /// and a and b as powers.\n                template<typename FieldType>\n                struct r1cs_gg_ppzksnark_ipp2_commitment_key {\n                    typedef FieldType field_type;\n                    typedef typename field_type::value_type value_type;\n\n                    typedef typename std::vector<value_type>::const_iterator const_iterator;\n                    typedef typename std::vector<value_type>::iterator iterator;\n\n                    /// Exponent is a\n                    std::vector<value_type> a;\n                    /// Exponent is b\n                    std::vector<value_type> b;\n\n                    /// Returns true if commitment keys have the exact required length.\n                    /// It is necessary for the IPP scheme to work that commitment\n                    /// key have the exact same number of arguments as the number of proofs to\n                    /// aggregate.\n                    inline bool valid(std::size_t n) {\n                        return a.size() == n && n == b.size();\n                    }\n\n                    /// Returns both vectors scaled by the given vector entrywise.\n                    /// In other words, it returns $\\{v_i^{s_i}\\}$\n                    template<typename InputIterator>\n                    r1cs_gg_ppzksnark_ipp2_commitment_key<FieldType> scale(InputIterator sfirst, InputIterator slast) {\n                        BOOST_ASSERT(std::distance(sfirst, slast) == a.size() &&\n                                     std::distance(sfirst, slast) == b.size());\n                        r1cs_gg_ppzksnark_ipp2_commitment_key<FieldType> result;\n                        const_iterator afirst = a.begin(), bfirst = b.begin();\n\n                        while (sfirst != slast && afirst != a.end() && bfirst != b.end()) {\n                            result.a.emplace_back(afirst->to_projective() * sfirst->to_affine());\n                            result.b.emplace_back(bfirst->to_projective() * sfirst->to_affine());\n                        }\n\n                        return result;\n                    }\n\n                    /// Takes a left and right commitment key and returns a commitment\n                    /// key $left \\circ right^{scale} = (left_i*right_i^{scale} ...)$. This is\n                    /// required step during GIPA recursion.\n                    r1cs_gg_ppzksnark_ipp2_commitment_key<FieldType>\n                        compress(const r1cs_gg_ppzksnark_ipp2_commitment_key<FieldType> &other,\n                                 const typename FieldType::number_type &scale) {\n                        BOOST_ASSERT(a.size() == other.a.size() && other.valid());\n\n                        r1cs_gg_ppzksnark_ipp2_commitment_key<FieldType> result;\n                        const_iterator afirst = a.begin(), bfirst = b.begin();\n                        const_iterator oafirst = other.a.begin(), obfirst = other.b.begin();\n\n                        while (afirst != a.end() && bfirst != b.end() && oafirst != other.a.begin() &&\n                               obfirst != other.b.begin()) {\n                            auto ra = oafirst->to_projective() * scale;\n                            auto rb = obfirst->to_projective() * scale;\n\n                            ra.add_assign_mixed(*afirst);\n                            rb.add_assign_mixed(*bfirst);\n\n                            result.a.emplace_back(ra.to_affine());\n                            result.b.emplace_back(rb.to_affine());\n\n                            ++afirst;\n                            ++bfirst;\n                            ++oafirst;\n                            ++obfirst;\n                        }\n\n                        return result;\n                    }\n                };\n\n                /*!\n                 * Returns both vectors scaled by the given vector entrywise.\n                 * In other words, it returns $\\{v_i^{s_i}\\}$\n                 */\n                template<typename FieldType, typename InputIterator>\n                r1cs_gg_ppzksnark_ipp2_commitment_key<FieldType>\n                    scale(const r1cs_gg_ppzksnark_ipp2_commitment_key<FieldType> &key,\n                          InputIterator first,\n                          InputIterator last) {\n                    BOOST_ASSERT(std::distance(first, last) == key.a.size() &&\n                                 std::distance(first, last) == key.b.size());\n                    r1cs_gg_ppzksnark_ipp2_commitment_key<FieldType> result;\n\n                    std::for_each(\n                        boost::make_zip_iterator(std::make_tuple(first, key.a.begin(), key.b.begin())),\n                        boost::make_zip_iterator(std::make_tuple(last, key.a.end(), key.b.end())),\n                        [&](const std::tuple<const typename FieldType::value_type &,\n                                             const typename FieldType::value_type &,\n                                             const typename FieldType::value_type &> &t) {\n                            result.a.emplace_back(std::get<1>(t).to_projective() * std::get<0>(t).to_affine());\n                            result.b.emplace_back(std::get<2>(t).to_projective() * std::get<0>(t).to_affine());\n                        });\n\n                    return result;\n                }\n\n                /// Takes a left and right commitment key and returns a commitment\n                /// key $left \\circ right^{scale} = (left_i*right_i^{scale} ...)$. This is\n                /// required step during GIPA recursion.\n                template<typename FieldType>\n                r1cs_gg_ppzksnark_ipp2_commitment_key<FieldType>\n                    compress(const r1cs_gg_ppzksnark_ipp2_commitment_key<FieldType> &left,\n                             const r1cs_gg_ppzksnark_ipp2_commitment_key<FieldType> &right,\n                             const typename FieldType::number_type &scale) {\n                    BOOST_ASSERT(left.a.size() == right.a.size());\n\n                    r1cs_gg_ppzksnark_ipp2_commitment_key<FieldType> result;\n                    typename r1cs_gg_ppzksnark_ipp2_commitment_key<FieldType>::const_iterator lafirst = left.a.begin(),\n                                                                                              lbfirst = left.b.begin();\n                    typename r1cs_gg_ppzksnark_ipp2_commitment_key<FieldType>::const_iterator rafirst = right.a.begin(),\n                                                                                              rbfirst = right.b.begin();\n\n                    std::for_each(\n                        boost::make_zip_iterator(\n                            std::make_tuple(left.a.begin(), left.b.begin(), right.a.begin(), right.b.begin())),\n                        boost::make_zip_iterator(\n                            std::make_tuple(left.a.end(), left.b.end(), right.a.end(), right.b.end())),\n                        [&](const std::tuple<\n                            const typename FieldType::value_type &, const typename FieldType::value_type &,\n                            const typename FieldType::value_type &, const typename FieldType::value_type &> &t) {\n                            auto ra = std::get<2>(t).to_projective() * scale;\n                            auto rb = std::get<3>(t).to_projective() * scale;\n\n                            ra += std::get<0>(t);\n                            rb += std::get<1>(t);\n\n                            result.a.emplace_back(ra.to_affine());\n                            result.b.emplace_back(rb.to_affine());\n                        });\n\n                    return result;\n                }\n\n                /// Commitment key used by the \"single\" commitment on G1 values as\n                /// well as in the \"pair\" commtitment.\n                /// It contains $\\{h^a^i\\}_{i=1}^n$ and $\\{h^b^i\\}_{i=1}^n$\n                template<typename CurveType>\n                using r1cs_gg_ppzksnark_ipp2_vkey = r1cs_gg_ppzksnark_ipp2_commitment_key<typename CurveType::g2_type>;\n\n                /// Commitment key used by the \"pair\" commitment. Note the sequence of\n                /// powers starts at $n$ already.\n                /// It contains $\\{g^{a^{n+i}}\\}_{i=1}^n$ and $\\{g^{b^{n+i}}\\}_{i=1}^n$\n                template<typename CurveType>\n                using r1cs_gg_ppzksnark_ipp2_wkey = r1cs_gg_ppzksnark_ipp2_commitment_key<typename CurveType::g1_type>;\n\n                template<typename CurveType>\n                struct r1cs_gg_ppzksnark_ipp2_commitment {\n                    typedef CurveType curve_type;\n\n                    typedef r1cs_gg_ppzksnark_ipp2_wkey<CurveType> wkey_type;\n                    typedef r1cs_gg_ppzksnark_ipp2_vkey<CurveType> vkey_type;\n\n                    typedef r1cs_gg_ppzksnark_ipp2_commitment_output<CurveType> output_type;\n\n                    /// Commits to a tuple of G1 vector and G2 vector in the following way:\n                    /// $T = \\prod_{i=0}^n e(A_i, v_{1,i})e(B_i,w_{1,i})$\n                    /// $U = \\prod_{i=0}^n e(A_i, v_{2,i})e(B_i,w_{2,i})$\n                    /// Output is $(T,U)$\n                    template<typename InputG1Iterator, typename InputG2Iterator>\n                    static output_type pair(const vkey_type &vkey, const wkey_type &wkey, InputG1Iterator afirst,\n                                            InputG1Iterator alast, InputG2Iterator bfirst, InputG2Iterator blast) {\n                        // (A * v)\n                        auto t1 = algebra::pair(afirst, alast, vkey.a);\n                        auto t2 = algebra::pair(wkey.a, bfirst, blast);\n\n                        // (B * v)\n                        auto u1 = algebra::pair(afirst, alast, vkey.b);\n                        auto u2 = algebra::pair(wkey.b, bfirst, blast);\n\n                        // (A * v)(w * B)\n                        return {t1 *= t2, u1 *= u2};\n                    }\n\n                    /// Commits to a single vector of G1 elements in the following way:\n                    /// $T = \\prod_{i=0}^n e(A_i, v_{1,i})$\n                    /// $U = \\prod_{i=0}^n e(A_i, v_{2,i})$\n                    /// Output is $(T,U)$\n                    template<typename InputG1Iterator>\n                    output_type pair(const vkey_type &vkey, InputG1Iterator afirst, InputG1Iterator alast) {\n                        return {algebra::pair(afirst, alast, vkey.a), algebra::pair(afirst, alast, vkey.b)};\n                    }\n                };\n\n                /// Commits to a tuple of G1 vector and G2 vector in the following way:\n                /// $T = \\prod_{i=0}^n e(A_i, v_{1,i})e(B_i,w_{1,i})$\n                /// $U = \\prod_{i=0}^n e(A_i, v_{2,i})e(B_i,w_{2,i})$\n                /// Output is $(T,U)$\n                template<typename ProofSchemeCommitmentType, typename InputG1Iterator, typename InputG2Iterator>\n                typename ProofSchemeCommitmentType::output_type\n                    pair(const typename ProofSchemeCommitmentType::vkey_type &vkey,\n                         const typename ProofSchemeCommitmentType::wkey_type &wkey, InputG1Iterator afirst,\n                         InputG1Iterator alast, InputG2Iterator bfirst, InputG2Iterator blast) {\n                    // (A * v)\n                    auto t1 = algebra::pair(afirst, alast, vkey.a);\n                    auto t2 = algebra::pair(wkey.a, bfirst, blast);\n\n                    // (B * v)\n                    auto u1 = algebra::pair(afirst, alast, vkey.b);\n                    auto u2 = algebra::pair(wkey.b, bfirst, blast);\n\n                    // (A * v)(w * B)\n                    return {t1 *= t2, u1 *= u2};\n                }\n\n                /// Commits to a single vector of G1 elements in the following way:\n                /// $T = \\prod_{i=0}^n e(A_i, v_{1,i})$\n                /// $U = \\prod_{i=0}^n e(A_i, v_{2,i})$\n                /// Output is $(T,U)$\n                template<typename ProofSchemeCommitmentType, typename InputG1Iterator>\n                typename ProofSchemeCommitmentType::output_type\n                    pair(const typename ProofSchemeCommitmentType::vkey_type &vkey, InputG1Iterator afirst,\n                         InputG1Iterator alast) {\n                    return {algebra::pair(afirst, alast, vkey.a), algebra::pair(afirst, alast, vkey.b)};\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": "d19edf11930c7f549f13cbf1ab1227e5bc98f666", "size": 16113, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/ipp2/commitment.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/commitment.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/commitment.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": 53.889632107, "max_line_length": 120, "alphanum_fraction": 0.5288276547, "num_tokens": 3684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334527, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2704619509440082}}
{"text": "// For std::iota\n#include <numeric>\n#include <learning/algorithms/constraint.hpp>\n#include <learning/algorithms/mmpc.hpp>\n#include <Eigen/Dense>\n#include <util/combinations.hpp>\n#include <util/progress.hpp>\n#include <util/vector.hpp>\n#include <util/validate_whitelists.hpp>\n\nusing Eigen::VectorXd, Eigen::VectorXi, Eigen::MatrixXd;\nusing util::Combinations, util::AllSubsets;\n\nnamespace learning::algorithms {\n\nenum MMPC_Progress { MMPC_FORWARD_PHASE_STOP = -1, MMPC_FORWARD_PHASE_RECOMPUTE_ASSOC = -2 };\n\nstruct CPCAssoc {\n    MatrixXd min_assoc;\n    VectorXd maxmin_assoc;\n    VectorXi maxmin_index;\n};\n\ntemplate <typename BN>\nclass BNCPCAssoc;\n\ntemplate <typename BN>\nclass BNCPCAssocCol {\npublic:\n    BNCPCAssocCol(BNCPCAssoc<BN>& self, int col) : m_self(self), m_col(col) {}\n\n    void fill(double v) { m_self.fill_col(m_col, v); }\n\n    void reset_maxmin() {\n        maxmin_assoc() = m_self.alpha();\n        maxmin_index() = MMPC_FORWARD_PHASE_STOP;\n    }\n\n    double& min_assoc(int index) { return m_self.min_assoc(index, m_col); }\n\n    double min_assoc(int index) const { return m_self.min_assoc(index, m_col); }\n\n    double& maxmin_assoc() { return m_self.maxmin_assoc(m_col); }\n\n    double maxmin_assoc() const { return m_self.maxmin_assoc(m_col); }\n\n    int& maxmin_index() { return m_self.maxmin_index(m_col); }\n\n    int maxmin_index() const { return m_self.maxmin_index(m_col); }\n\n    void initialize_assoc(int index, double pvalue) {\n        min_assoc(index) = pvalue;\n\n        if (pvalue < maxmin_assoc()) {\n            maxmin_assoc() = pvalue;\n            maxmin_index() = index;\n        }\n    }\n\n    void update_assoc(int index, double pvalue) {\n        double new_max = min_assoc(index) = std::max(min_assoc(index), pvalue);\n\n        if (new_max < maxmin_assoc()) {\n            maxmin_assoc() = new_max;\n            maxmin_index() = index;\n        }\n    }\n\nprivate:\n    BNCPCAssoc<BN>& m_self;\n    int m_col;\n};\n\ntemplate <typename BN>\nBNCPCAssocCol(BNCPCAssoc<BN>&, int) -> BNCPCAssocCol<BN>;\n\ntemplate <>\nclass BNCPCAssocCol<VectorXd> {\npublic:\n    BNCPCAssocCol(VectorXd& col, double alpha)\n        : m_col(col), m_maxmin_assoc(alpha), m_maxmin_index(MMPC_FORWARD_PHASE_STOP), m_alpha(alpha) {}\n\n    void fill(double v) { m_col.fill(v); }\n\n    void reset_maxmin() {\n        m_maxmin_assoc = m_alpha;\n        m_maxmin_index = MMPC_FORWARD_PHASE_STOP;\n    }\n\n    double& min_assoc(int index) { return m_col(index); }\n\n    double min_assoc(int index) const { return m_col(index); }\n\n    double& maxmin_assoc() { return m_maxmin_assoc; }\n\n    double maxmin_assoc() const { return m_maxmin_assoc; }\n\n    int& maxmin_index() { return m_maxmin_index; }\n\n    int maxmin_index() const { return m_maxmin_index; }\n\n    void initialize_assoc(int index, double pvalue) {\n        m_col(index) = pvalue;\n\n        if (pvalue < m_maxmin_assoc) {\n            m_maxmin_assoc = pvalue;\n            m_maxmin_index = index;\n        }\n    }\n\n    void update_assoc(int index, double pvalue) {\n        double new_max = min_assoc(index) = std::max(min_assoc(index), pvalue);\n\n        if (new_max < m_maxmin_assoc) {\n            m_maxmin_assoc = new_max;\n            m_maxmin_index = index;\n        }\n    }\n\nprivate:\n    VectorXd& m_col;\n    double m_maxmin_assoc;\n    int m_maxmin_index;\n    double m_alpha;\n};\n\ntemplate <>\nclass BNCPCAssoc<PartiallyDirectedGraph> {\npublic:\n    BNCPCAssoc(const PartiallyDirectedGraph& g, double alpha) : m_graph(g), m_assoc(), m_alpha(alpha) {\n        m_assoc = CPCAssoc{/*.min_assoc = */ MatrixXd::Zero(g.num_nodes(), g.num_nodes()),\n                           /*.maxmin_assoc = */ VectorXd::Constant(g.num_nodes(), m_alpha),\n                           /*.maxmin_index = */ VectorXi::Constant(g.num_nodes(), MMPC_FORWARD_PHASE_STOP)};\n    }\n\n    const PartiallyDirectedGraph& graph() { return m_graph; }\n\n    CPCAssoc& raw_assoc() { return m_assoc; }\n\n    double alpha() { return m_alpha; }\n\n    void reset_maxmin(int index) {\n        maxmin_assoc(index) = m_alpha;\n        maxmin_index(index) = MMPC_FORWARD_PHASE_STOP;\n    }\n\n    void fill_col(int col_index, double v) { m_assoc.min_assoc.col(col_index).fill(v); }\n\n    double& min_assoc(int row_index, int col_index) { return m_assoc.min_assoc(row_index, col_index); }\n\n    double min_assoc(int row_index, int col_index) const { return m_assoc.min_assoc(row_index, col_index); }\n\n    BNCPCAssocCol<PartiallyDirectedGraph> min_assoc_col(int col_index) { return BNCPCAssocCol(*this, col_index); }\n\n    double& maxmin_assoc(int index) { return m_assoc.maxmin_assoc(index); }\n\n    double maxmin_assoc(int index) const { return m_assoc.maxmin_assoc(index); }\n\n    int& maxmin_index(int index) { return m_assoc.maxmin_index(index); }\n\n    int maxmin_index(int index) const { return m_assoc.maxmin_index(index); }\n\n    void initialize_assoc(int row_index, int col_index, double pvalue) {\n        min_assoc(row_index, col_index) = pvalue;\n        if (pvalue < m_assoc.maxmin_assoc(col_index)) {\n            maxmin_assoc(col_index) = pvalue;\n            maxmin_index(col_index) = row_index;\n        }\n    }\n\n    void update_assoc(int row_index, int col_index, double pvalue) {\n        double new_max = min_assoc(row_index, col_index) = std::max(min_assoc(row_index, col_index), pvalue);\n        if (new_max < m_assoc.maxmin_assoc(col_index)) {\n            maxmin_assoc(col_index) = new_max;\n            maxmin_index(col_index) = row_index;\n        }\n    }\n\nprivate:\n    const PartiallyDirectedGraph& m_graph;\n    CPCAssoc m_assoc;\n    double m_alpha;\n};\n\ntemplate <>\nclass BNCPCAssoc<ConditionalPartiallyDirectedGraph> {\npublic:\n    BNCPCAssoc(const ConditionalPartiallyDirectedGraph& g, double alpha)\n        : m_graph(g), m_assoc(), m_interface_assoc(), m_alpha(alpha) {\n        m_assoc = CPCAssoc{/*.min_assoc = */ MatrixXd::Zero(g.num_joint_nodes(), g.num_nodes()),\n                           /*.maxmin_assoc = */ VectorXd::Constant(g.num_nodes(), m_alpha),\n                           /*.maxmin_index = */ VectorXi::Constant(g.num_nodes(), MMPC_FORWARD_PHASE_STOP)};\n\n        m_interface_assoc =\n            CPCAssoc{/*.min_assoc = */ MatrixXd::Zero(g.num_nodes(), g.num_interface_nodes()),\n                     /*.maxmin_assoc = */ VectorXd::Constant(g.num_interface_nodes(), m_alpha),\n                     /*.maxmin_index = */ VectorXi::Constant(g.num_interface_nodes(), MMPC_FORWARD_PHASE_STOP)};\n    }\n\n    const ConditionalPartiallyDirectedGraph& graph() { return m_graph; }\n\n    CPCAssoc& raw_assoc() { return m_assoc; }\n\n    CPCAssoc& raw_interface_assoc() { return m_interface_assoc; }\n\n    void reset_maxmin(int index) {\n        maxmin_assoc(index) = m_alpha;\n        maxmin_index(index) = MMPC_FORWARD_PHASE_STOP;\n    }\n\n    double alpha() { return m_alpha; }\n\n    void fill_col(int col_index, double v) {\n        if (m_graph.is_interface(col_index)) {\n            m_interface_assoc.min_assoc.col(m_graph.interface_collapsed_from_index(col_index)).fill(v);\n        } else {\n            m_assoc.min_assoc.col(m_graph.collapsed_from_index(col_index)).fill(v);\n        }\n    }\n\n    double& min_assoc_node(int row_index, int col_index) {\n        return m_assoc.min_assoc(m_graph.joint_collapsed_from_index(row_index),\n                                 m_graph.collapsed_from_index(col_index));\n    }\n\n    double min_assoc_node(int row_index, int col_index) const {\n        return m_assoc.min_assoc(m_graph.joint_collapsed_from_index(row_index),\n                                 m_graph.collapsed_from_index(col_index));\n    }\n\n    double& min_assoc_interface(int row_index, int col_index) {\n        return m_interface_assoc.min_assoc(m_graph.collapsed_from_index(row_index),\n                                           m_graph.interface_collapsed_from_index(col_index));\n    }\n\n    double min_assoc_interface(int row_index, int col_index) const {\n        return m_interface_assoc.min_assoc(m_graph.collapsed_from_index(row_index),\n                                           m_graph.interface_collapsed_from_index(col_index));\n    }\n\n    double& min_assoc(int row_index, int col_index) {\n        if (m_graph.is_interface(col_index))\n            return min_assoc_interface(row_index, col_index);\n        else\n            return min_assoc_node(row_index, col_index);\n    }\n\n    double min_assoc(int row_index, int col_index) const {\n        if (m_graph.is_interface(col_index))\n            return min_assoc_interface(row_index, col_index);\n        else\n            return min_assoc_node(row_index, col_index);\n    }\n\n    BNCPCAssocCol<ConditionalPartiallyDirectedGraph> min_assoc_col(int col_index) {\n        return BNCPCAssocCol(*this, col_index);\n    }\n\n    double& maxmin_assoc_node(int index) { return m_assoc.maxmin_assoc(m_graph.collapsed_from_index(index)); }\n\n    double maxmin_assoc_node(int index) const { return m_assoc.maxmin_assoc(m_graph.collapsed_from_index(index)); }\n\n    double& maxmin_assoc_interface(int index) {\n        return m_interface_assoc.maxmin_assoc(m_graph.interface_collapsed_from_index(index));\n    }\n\n    double maxmin_assoc_interface(int index) const {\n        return m_interface_assoc.maxmin_assoc(m_graph.interface_collapsed_from_index(index));\n    }\n\n    double& maxmin_assoc(int index) {\n        if (m_graph.is_interface(index))\n            return maxmin_assoc_interface(index);\n        else\n            return maxmin_assoc_node(index);\n    }\n\n    double maxmin_assoc(int index) const {\n        if (m_graph.is_interface(index))\n            return maxmin_assoc_interface(index);\n        else\n            return maxmin_assoc_node(index);\n    }\n\n    int& maxmin_index_node(int index) { return m_assoc.maxmin_index(m_graph.collapsed_from_index(index)); }\n\n    int maxmin_index_node(int index) const { return m_assoc.maxmin_index(m_graph.collapsed_from_index(index)); }\n\n    int& maxmin_index_interface(int index) {\n        return m_interface_assoc.maxmin_index(m_graph.interface_collapsed_from_index(index));\n    }\n\n    int maxmin_index_interface(int index) const {\n        return m_interface_assoc.maxmin_index(m_graph.interface_collapsed_from_index(index));\n    }\n\n    int& maxmin_index(int index) {\n        if (m_graph.is_interface(index))\n            return maxmin_index_interface(index);\n        else\n            return maxmin_index_node(index);\n    }\n\n    int maxmin_index(int index) const {\n        if (m_graph.is_interface(index))\n            return maxmin_index_interface(index);\n        else\n            return maxmin_index_node(index);\n    }\n\n    void initialize_assoc(int row_index, int col_index, double pvalue) {\n        if (m_graph.is_interface(col_index)) {\n            min_assoc_interface(row_index, col_index) = pvalue;\n            if (pvalue < maxmin_assoc_interface(col_index)) {\n                maxmin_assoc_interface(col_index) = pvalue;\n                maxmin_index_interface(col_index) = row_index;\n            }\n\n        } else {\n            min_assoc_node(row_index, col_index) = pvalue;\n            if (pvalue < maxmin_assoc_node(col_index)) {\n                maxmin_assoc_node(col_index) = pvalue;\n                maxmin_index_node(col_index) = row_index;\n            }\n        }\n    }\n\n    void update_assoc(int row_index, int col_index, double pvalue) {\n        if (m_graph.is_interface(col_index)) {\n            double new_max = min_assoc_interface(row_index, col_index) =\n                std::max(min_assoc_interface(row_index, col_index), pvalue);\n            if (new_max < maxmin_assoc_interface(col_index)) {\n                maxmin_assoc_interface(col_index) = new_max;\n                maxmin_index_interface(col_index) = row_index;\n            }\n        } else {\n            double new_max = min_assoc_node(row_index, col_index) =\n                std::max(min_assoc_node(row_index, col_index), pvalue);\n            if (new_max < maxmin_assoc_node(col_index)) {\n                maxmin_assoc_node(col_index) = new_max;\n                maxmin_index_node(col_index) = row_index;\n            }\n        }\n    }\n\nprivate:\n    const ConditionalPartiallyDirectedGraph& m_graph;\n    CPCAssoc m_assoc;\n    CPCAssoc m_interface_assoc;\n    double m_alpha;\n};\n\ntemplate <typename G>\nBNCPCAssoc(const G&, double) -> BNCPCAssoc<G>;\n\ntemplate <typename G, typename ColAssoc>\nvoid recompute_assoc(const IndependenceTest& test,\n                     const G& g,\n                     int variable,\n                     const std::unordered_set<int>& cpc,\n                     std::unordered_set<int>& to_be_checked,\n                     ColAssoc& assoc,\n                     util::BaseProgressBar& progress) {\n    const auto& variable_name = g.name(variable);\n    progress.set_text(\"MMPC Forward: sepset order \" + std::to_string(cpc.size()) + \" for \" + variable_name);\n    progress.set_max_progress(to_be_checked.size());\n    progress.set_progress(0);\n\n    std::vector<std::string> cpc_vec;\n    cpc_vec.reserve(cpc.size());\n    for (auto c : cpc) {\n        cpc_vec.push_back(g.name(c));\n    }\n\n    assoc.reset_maxmin();\n\n    for (auto it = to_be_checked.begin(); it != to_be_checked.end();) {\n        double pvalue = test.pvalue(variable_name, g.name(*it), cpc_vec);\n        assoc.initialize_assoc(*it, pvalue);\n        progress.tick();\n    }\n}\n\ntemplate <typename G, typename ColAssoc>\nvoid update_min_assoc(const IndependenceTest& test,\n                      const G& g,\n                      int variable,\n                      const std::unordered_set<int>& to_be_checked,\n                      const std::unordered_set<int>& cpc,\n                      ColAssoc& assoc,\n                      int last_added_cpc,\n                      util::BaseProgressBar& progress) {\n    const auto& variable_name = g.name(variable);\n\n    assoc.reset_maxmin();\n\n    if (cpc.empty()) {\n        progress.set_text(\"MMPC Forward: no sepset for \" + variable_name);\n        progress.set_max_progress(to_be_checked.size());\n        progress.set_progress(0);\n\n        for (auto v : to_be_checked) {\n            double pvalue = test.pvalue(variable_name, g.name(v));\n            assoc.initialize_assoc(v, pvalue);\n            progress.tick();\n        }\n    } else if (cpc.size() == 1) {\n        progress.set_text(\"MMPC Forward: sepset order 1 for \" + variable_name);\n        progress.set_max_progress(to_be_checked.size());\n        progress.set_progress(0);\n\n        const auto& last_added_name = g.name(last_added_cpc);\n        for (auto v : to_be_checked) {\n            double pvalue = test.pvalue(variable_name, g.name(v), last_added_name);\n            assoc.update_assoc(v, pvalue);\n            progress.tick();\n        }\n    } else if (cpc.size() == 2) {\n        const auto& last_added_name = g.name(last_added_cpc);\n\n        std::vector<std::string> cond;\n        cond.reserve(2);\n        for (auto pc : cpc) {\n            cond.push_back(g.name(pc));\n        }\n\n        progress.set_text(\"MMPC Forward: sepset order 2 for \" + variable_name);\n        progress.set_max_progress(to_be_checked.size());\n        progress.set_progress(0);\n\n        for (auto v : to_be_checked) {\n            const auto& v_name = g.name(v);\n\n            double pvalue = test.pvalue(variable_name, v_name, last_added_name);\n            assoc.update_assoc(v, pvalue);\n\n            pvalue = test.pvalue(variable_name, v_name, cond);\n            assoc.update_assoc(v, pvalue);\n\n            progress.tick();\n        }\n    } else {\n        progress.set_text(\"MMPC Forward: sepset up to order \" + std::to_string(cpc.size()) + \" for \" + variable_name);\n        progress.set_max_progress(to_be_checked.size());\n        progress.set_progress(0);\n\n        const auto& last_added_name = g.name(last_added_cpc);\n\n        std::vector<std::string> fixed = {last_added_name};\n\n        std::vector<std::string> old_cpc;\n        old_cpc.reserve(cpc.size());\n        for (auto pc : cpc) {\n            if (pc != last_added_cpc) {\n                old_cpc.push_back(g.name(pc));\n            }\n        }\n\n        std::vector<std::string> cond(2);\n        cond[1] = last_added_name;\n\n        // Conditioning in all the subsets of 2 to CPC.size()-1 size, including last variable added.\n        AllSubsets<std::string> comb;\n        if (cpc.size() > 3) {\n            comb = AllSubsets(old_cpc, std::move(fixed), 3, cpc.size() - 1);\n        }\n\n        for (auto v : to_be_checked) {\n            const auto& v_name = g.name(v);\n            // Conditioning in just the last variable added.\n            double pvalue = test.pvalue(variable_name, v_name, last_added_name);\n            assoc.update_assoc(v, pvalue);\n\n            // Conditioning in the last variable and another variable added.\n            for (const auto& pc : old_cpc) {\n                cond[0] = pc;\n                pvalue = test.pvalue(variable_name, v_name, cond);\n                assoc.update_assoc(v, pvalue);\n            }\n\n            if (cpc.size() > 3) {\n                for (const auto& subset : comb) {\n                    pvalue = test.pvalue(variable_name, v_name, subset);\n                    assoc.update_assoc(v, pvalue);\n                }\n            }\n\n            // Conditioning in all the variables.\n            old_cpc.push_back(last_added_name);\n            pvalue = test.pvalue(variable_name, v_name, old_cpc);\n            assoc.update_assoc(v, pvalue);\n            old_cpc.pop_back();\n        }\n\n        progress.tick();\n    }\n}\n\ntemplate <typename ColAssoc>\nvoid update_to_be_checked(const ColAssoc& assoc, std::unordered_set<int>& to_be_checked, double alpha) {\n    for (auto it = to_be_checked.begin(), end = to_be_checked.end(); it != end;) {\n        if (assoc.min_assoc(*it) > alpha) {\n            it = to_be_checked.erase(it);\n        } else {\n            ++it;\n        }\n    }\n}\n\ntemplate <typename G, typename ColAssoc>\nvoid mmpc_forward_phase(const IndependenceTest& test,\n                        const G& g,\n                        int variable,\n                        double alpha,\n                        std::unordered_set<int>& cpc,\n                        std::unordered_set<int>& to_be_checked,\n                        ColAssoc& assoc,\n                        int last_added,\n                        util::BaseProgressBar& progress) {\n    bool changed_cpc = true;\n\n    if (cpc.empty()) {\n        assoc.fill(0);\n    } else if (last_added == MMPC_FORWARD_PHASE_RECOMPUTE_ASSOC) {\n        // The CPC is not empty because of whitelists, so we compute the association of the selected CPC.\n        recompute_assoc(test, g, variable, cpc, to_be_checked, assoc, progress);\n\n        int to_add = assoc.maxmin_index();\n\n        if (to_add != MMPC_FORWARD_PHASE_STOP) {\n            cpc.insert(to_add);\n            to_be_checked.erase(to_add);\n            last_added = to_add;\n            update_to_be_checked(assoc, to_be_checked, alpha);\n        } else {\n            changed_cpc = false;\n        }\n    }\n\n    while (changed_cpc && !to_be_checked.empty()) {\n        update_min_assoc(test, g, variable, to_be_checked, cpc, assoc, last_added, progress);\n        // int to_add = find_maxmin_assoc(assoc, to_be_checked, alpha);\n        int to_add = assoc.maxmin_index();\n\n        if (to_add != MMPC_FORWARD_PHASE_STOP) {\n            cpc.insert(to_add);\n            to_be_checked.erase(to_add);\n            last_added = to_add;\n            update_to_be_checked(assoc, to_be_checked, alpha);\n        } else {\n            changed_cpc = false;\n        }\n    }\n}\n\nbool is_whitelisted_pc(int variable, int candidate_pc, const ArcSet& arc_whitelist, const EdgeSet& edge_whitelist) {\n    return edge_whitelist.count({variable, candidate_pc}) > 0 || arc_whitelist.count({variable, candidate_pc}) > 0 ||\n           arc_whitelist.count({candidate_pc, variable}) > 0;\n}\n\ntemplate <typename G>\nvoid mmpc_backward_phase(const IndependenceTest& test,\n                         const G& g,\n                         int variable,\n                         double alpha,\n                         std::unordered_set<int>& cpc,\n                         const ArcSet& arc_whitelist,\n                         const EdgeSet& edge_whitelist,\n                         util::BaseProgressBar& progress) {\n    const auto& variable_name = g.name(variable);\n\n    if (cpc.size() > 1) {\n        std::vector<std::string> subset_variables;\n        subset_variables.reserve(cpc.size());\n        for (auto pc : cpc) {\n            subset_variables.push_back(g.name(pc));\n        }\n\n        progress.set_text(\"MMPC Backwards for \" + variable_name);\n        progress.set_max_progress(cpc.size());\n        progress.set_progress(0);\n\n        for (auto it = cpc.begin(), end = cpc.end(); it != end;) {\n            if (is_whitelisted_pc(variable, *it, arc_whitelist, edge_whitelist)) {\n                ++it;\n                progress.tick();\n                continue;\n            }\n\n            const auto& it_name = g.name(*it);\n            util::swap_remove_v(subset_variables, it_name);\n\n            // Marginal independence\n            if (test.pvalue(variable_name, it_name) > alpha) {\n                it = cpc.erase(it);\n                progress.set_max_progress(cpc.size());\n                progress.tick();\n                continue;\n            }\n\n            // Independence sepset length 1.\n            bool found_sepset = false;\n            for (auto it_other = subset_variables.begin(), end_other = subset_variables.end(); it_other != end_other;\n                 ++it_other) {\n                if (test.pvalue(variable_name, it_name, *it_other) > alpha) {\n                    it = cpc.erase(it);\n                    progress.set_max_progress(cpc.size());\n                    found_sepset = true;\n                    break;\n                }\n            }\n\n            if (!found_sepset && subset_variables.size() > 2) {\n                // Independence sepset length 2 to subset size - 1.\n                AllSubsets comb(subset_variables, 2, subset_variables.size() - 1);\n\n                for (const auto& s : comb) {\n                    if (test.pvalue(variable_name, it_name, s) > alpha) {\n                        it = cpc.erase(it);\n                        progress.set_max_progress(cpc.size());\n                        found_sepset = true;\n                        break;\n                    }\n                }\n            }\n\n            // Independence sepset length of subset size.\n            if (!found_sepset && subset_variables.size() > 1 &&\n                test.pvalue(variable_name, it_name, subset_variables) > alpha) {\n                it = cpc.erase(it);\n                progress.set_max_progress(cpc.size());\n                found_sepset = true;\n            }\n\n            if (!found_sepset) {\n                // No sepset found, so include again the variable.\n                subset_variables.push_back(it_name);\n                ++it;\n            }\n\n            progress.tick();\n        }\n    }\n}\n\nstd::unordered_set<int> mmpc_variable(const IndependenceTest& test,\n                                      const PartiallyDirectedGraph& g,\n                                      int variable,\n                                      double alpha,\n                                      const ArcSet& arc_whitelist,\n                                      const EdgeSet& edge_blacklist,\n                                      const EdgeSet& edge_whitelist,\n                                      util::BaseProgressBar& progress) {\n    std::unordered_set<int> cpc;\n    std::unordered_set<int> to_be_checked;\n\n    for (int i = 0; i < g.num_nodes(); ++i) {\n        if (i != variable && edge_blacklist.count({variable, i}) == 0) {\n            to_be_checked.insert(i);\n        }\n    }\n\n    for (const auto& edge : edge_whitelist) {\n        if (edge.first == variable) {\n            cpc.insert(edge.second);\n            to_be_checked.erase(edge.second);\n        }\n\n        if (edge.second == variable) {\n            cpc.insert(edge.first);\n            to_be_checked.erase(edge.first);\n        }\n    }\n\n    for (const auto& arc : arc_whitelist) {\n        if (arc.first == variable) {\n            cpc.insert(arc.second);\n            to_be_checked.erase(arc.second);\n        }\n\n        if (arc.second == variable) {\n            cpc.insert(arc.first);\n            to_be_checked.erase(arc.first);\n        }\n    }\n\n    VectorXd min_assoc(g.num_nodes());\n    BNCPCAssocCol<VectorXd> assoc_col(min_assoc, alpha);\n\n    int last_added = 0;\n    if (!cpc.empty()) last_added = MMPC_FORWARD_PHASE_RECOMPUTE_ASSOC;\n\n    mmpc_forward_phase(test, g, variable, alpha, cpc, to_be_checked, assoc_col, last_added, progress);\n    mmpc_backward_phase(test, g, variable, alpha, cpc, arc_whitelist, edge_whitelist, progress);\n    return cpc;\n}\n\ntemplate <typename G>\nvoid marginal_cpcs_all_variables(const IndependenceTest& test,\n                                 const G& g,\n                                 double alpha,\n                                 std::vector<std::unordered_set<int>>& cpcs,\n                                 std::vector<std::unordered_set<int>>& to_be_checked,\n                                 const EdgeSet& edge_blacklist,\n                                 BNCPCAssoc<G>& assoc,\n                                 util::BaseProgressBar& progress) {\n    auto nnodes = g.num_nodes();\n\n    progress.set_text(\"MMPC Forward: No sepset\");\n    progress.set_max_progress((nnodes * (nnodes - 1) / 2));\n    progress.set_progress(0);\n\n    for (int i = 0, i_end = nnodes - 1; i < i_end; ++i) {\n        const auto& i_name = g.collapsed_name(i);\n        auto i_index = g.index(i_name);\n        for (int j = i + 1; j < nnodes; ++j) {\n            const auto& j_name = g.collapsed_name(j);\n            auto j_index = g.index(j_name);\n            if ((cpcs[i_index].empty() || cpcs[j_index].empty()) && edge_blacklist.count({i_index, j_index}) == 0) {\n                double pvalue = test.pvalue(i_name, j_name);\n                if (pvalue < alpha) {\n                    if (cpcs[i_index].empty()) {\n                        assoc.initialize_assoc(j_index, i_index, pvalue);\n                    }\n\n                    if (cpcs[j_index].empty()) {\n                        assoc.initialize_assoc(i_index, j_index, pvalue);\n                    }\n                } else {\n                    to_be_checked[i_index].erase(j_index);\n                    to_be_checked[j_index].erase(i_index);\n                }\n            }\n\n            progress.tick();\n        }\n    }\n}\n\nvoid marginal_cpcs_all_variables(const IndependenceTest& test,\n                                 const ConditionalPartiallyDirectedGraph& g,\n                                 double alpha,\n                                 std::vector<std::unordered_set<int>>& cpcs,\n                                 std::vector<std::unordered_set<int>>& to_be_checked,\n                                 const EdgeSet& edge_blacklist,\n                                 BNCPCAssoc<ConditionalPartiallyDirectedGraph>& assoc,\n                                 util::BaseProgressBar& progress) {\n    auto nnodes = g.num_nodes();\n    auto inodes = g.num_interface_nodes();\n\n    progress.set_text(\"MMPC Forward: No sepset\");\n    progress.set_max_progress(inodes * nnodes + (nnodes * (nnodes - 1) / 2));\n    progress.set_progress(0);\n\n    // Cache marginal between nodes\n    marginal_cpcs_all_variables<ConditionalPartiallyDirectedGraph>(\n        test, g, alpha, cpcs, to_be_checked, edge_blacklist, assoc, progress);\n\n    // Cache between nodes and interface_nodes\n    for (const auto& node : g.nodes()) {\n        auto nindex = g.index(node);\n        for (const auto& inode : g.interface_nodes()) {\n            auto iindex = g.index(inode);\n\n            if ((cpcs[nindex].empty() || cpcs[iindex].empty()) && edge_blacklist.count({nindex, iindex}) == 0) {\n                double pvalue = test.pvalue(node, inode);\n                if (pvalue < alpha) {\n                    if (cpcs[nindex].empty()) {\n                        assoc.initialize_assoc(iindex, nindex, pvalue);\n                    }\n\n                    if (cpcs[iindex].empty()) {\n                        assoc.initialize_assoc(nindex, iindex, pvalue);\n                    }\n                } else {\n                    to_be_checked[nindex].erase(iindex);\n                    to_be_checked[iindex].erase(nindex);\n                }\n            }\n\n            progress.tick();\n        }\n    }\n}\n\ntemplate <typename G>\nvoid univariate_cpcs_all_variables(const IndependenceTest& test,\n                                   const G& g,\n                                   int num_total_nodes,\n                                   double alpha,\n                                   std::vector<std::unordered_set<int>>& cpcs,\n                                   std::vector<std::unordered_set<int>>& to_be_checked,\n                                   BNCPCAssoc<G>& assoc,\n                                   util::BaseProgressBar& progress) {\n    progress.set_text(\"MMPC Forward: sepset order 1\");\n    progress.set_max_progress(num_total_nodes);\n    progress.set_progress(0);\n\n    for (int i = 0; i < num_total_nodes; ++i) {\n        if (cpcs[i].size() == 1) {\n            int cpc_variable = *cpcs[i].begin();\n            const auto& i_name = g.name(i);\n            const auto& cpc_name = g.name(cpc_variable);\n            for (auto it = to_be_checked[i].begin(), end = to_be_checked[i].end(); it != end;) {\n                auto p = *it;\n                bool repeated_test =\n                    cpcs[p].size() == 1 && cpc_variable == *cpcs[p].begin() && to_be_checked[p].count(i) > 0;\n\n                if (!repeated_test || i < p) {\n                    const auto& p_name = g.name(p);\n                    double pvalue = test.pvalue(i_name, p_name, cpc_name);\n\n                    assoc.update_assoc(p, i, pvalue);\n                    if (assoc.min_assoc(p, i) > alpha)\n                        it = to_be_checked[i].erase(it);\n                    else\n                        ++it;\n\n                    if (repeated_test) {\n                        assoc.update_assoc(i, p, pvalue);\n                        if (assoc.min_assoc(i, p) > alpha) to_be_checked[p].erase(i);\n                    }\n                } else {\n                    ++it;\n                }\n            }\n        }\n\n        progress.tick();\n    }\n}\n\nstd::pair<std::vector<std::unordered_set<int>>, std::vector<std::unordered_set<int>>> generate_cpcs(\n    const PartiallyDirectedGraph& g,\n    const ArcSet& arc_whitelist,\n    const EdgeSet& edge_blacklist,\n    const EdgeSet& edge_whitelist) {\n    std::vector<std::unordered_set<int>> cpcs(g.num_nodes());\n    std::vector<std::unordered_set<int>> to_be_checked(g.num_nodes());\n\n    // Add whitelisted CPCs\n    for (const auto& edge : edge_whitelist) {\n        cpcs[edge.first].insert(edge.second);\n        cpcs[edge.second].insert(edge.first);\n    }\n\n    for (const auto& arc : arc_whitelist) {\n        cpcs[arc.first].insert(arc.second);\n        cpcs[arc.second].insert(arc.first);\n    }\n\n    // Generate to_be_checked indices\n    for (int i = 0, i_end = g.num_nodes() - 1; i < i_end; ++i) {\n        const auto& x_name = g.collapsed_name(i);\n        auto x_index = g.index(x_name);\n        for (int j = i + 1; j < g.num_nodes(); ++j) {\n            const auto& y_name = g.collapsed_name(j);\n            auto y_index = g.index(y_name);\n\n            if (edge_blacklist.count({x_index, y_index}) == 0) {\n                if (cpcs[x_index].count(y_index) == 0) {\n                    to_be_checked[x_index].insert(y_index);\n                }\n\n                if (cpcs[y_index].count(x_index) == 0) {\n                    to_be_checked[y_index].insert(x_index);\n                }\n            }\n        }\n    }\n\n    return std::make_pair(cpcs, to_be_checked);\n}\n\nstd::pair<std::vector<std::unordered_set<int>>, std::vector<std::unordered_set<int>>> generate_cpcs(\n    const ConditionalPartiallyDirectedGraph& g,\n    const ArcSet& arc_whitelist,\n    const EdgeSet& edge_blacklist,\n    const EdgeSet& edge_whitelist) {\n    std::vector<std::unordered_set<int>> cpcs(g.num_joint_nodes());\n    std::vector<std::unordered_set<int>> to_be_checked(g.num_joint_nodes());\n\n    // Add whitelisted CPCs\n    for (const auto& edge : edge_whitelist) {\n        cpcs[edge.first].insert(edge.second);\n        cpcs[edge.second].insert(edge.first);\n    }\n\n    for (const auto& arc : arc_whitelist) {\n        cpcs[arc.first].insert(arc.second);\n        cpcs[arc.second].insert(arc.first);\n    }\n\n    // Generate to_be_checked indices\n    for (const auto& node : g.nodes()) {\n        auto index = g.index(node);\n        for (const auto& other : g.joint_nodes()) {\n            auto other_index = g.index(other);\n\n            if (index != other_index && edge_blacklist.count({index, other_index}) == 0) {\n                if (cpcs[index].count(other_index) == 0) to_be_checked[index].insert(other_index);\n                if (cpcs[other_index].count(index) == 0) to_be_checked[other_index].insert(index);\n            }\n        }\n    }\n\n    return std::make_pair(cpcs, to_be_checked);\n}\n\ntemplate <typename G>\nstd::vector<std::unordered_set<int>> mmpc_all_variables(const IndependenceTest& test,\n                                                        const G& g,\n                                                        int num_total_nodes,\n                                                        double alpha,\n                                                        const ArcSet& arc_whitelist,\n                                                        const EdgeSet& edge_blacklist,\n                                                        const EdgeSet& edge_whitelist,\n                                                        util::BaseProgressBar& progress) {\n    auto [cpcs, to_be_checked] = generate_cpcs(g, arc_whitelist, edge_blacklist, edge_whitelist);\n\n    BNCPCAssoc assoc(g, alpha);\n\n    marginal_cpcs_all_variables(test, g, alpha, cpcs, to_be_checked, edge_blacklist, assoc, progress);\n\n    bool all_finished = true;\n    for (int i = 0; i < num_total_nodes; ++i) {\n        if (assoc.maxmin_index(i) != MMPC_FORWARD_PHASE_STOP) {\n            all_finished = false;\n            cpcs[i].insert(assoc.maxmin_index(i));\n            to_be_checked[i].erase(assoc.maxmin_index(i));\n        }\n\n        if (cpcs[i].size() == 1) {\n            assoc.reset_maxmin(i);\n        }\n    }\n\n    if (!all_finished) {\n        univariate_cpcs_all_variables(test, g, num_total_nodes, alpha, cpcs, to_be_checked, assoc, progress);\n\n        for (int i = 0; i < num_total_nodes; ++i) {\n            auto col_min_assoc = assoc.min_assoc_col(i);\n            // The cpc is whitelisted.\n            if (cpcs[i].size() > 1) {\n                mmpc_forward_phase(test,\n                                   g,\n                                   i,\n                                   alpha,\n                                   cpcs[i],\n                                   to_be_checked[i],\n                                   col_min_assoc,\n                                   MMPC_FORWARD_PHASE_RECOMPUTE_ASSOC,\n                                   progress);\n            } else if (assoc.maxmin_index(i) != MMPC_FORWARD_PHASE_STOP) {\n                cpcs[i].insert(assoc.maxmin_index(i));\n                to_be_checked[i].erase(assoc.maxmin_index(i));\n                mmpc_forward_phase(\n                    test, g, i, alpha, cpcs[i], to_be_checked[i], col_min_assoc, assoc.maxmin_index(i), progress);\n            }\n\n            mmpc_backward_phase(test, g, i, alpha, cpcs[i], arc_whitelist, edge_whitelist, progress);\n        }\n    }\n\n    return cpcs;\n}\n\n//\n// WARNING!: This method should be called with a Graph without removed nodes.\n//\nstd::vector<std::unordered_set<int>> mmpc_all_variables(const IndependenceTest& test,\n                                                        const PartiallyDirectedGraph& g,\n                                                        double alpha,\n                                                        const ArcSet& arc_whitelist,\n                                                        const EdgeSet& edge_blacklist,\n                                                        const EdgeSet& edge_whitelist,\n                                                        util::BaseProgressBar& progress) {\n    return mmpc_all_variables(test, g, g.num_nodes(), alpha, arc_whitelist, edge_blacklist, edge_whitelist, progress);\n}\n\n//\n// WARNING!: This method should be called with a Graph without removed nodes.\n//\nstd::vector<std::unordered_set<int>> mmpc_all_variables(const IndependenceTest& test,\n                                                        const ConditionalPartiallyDirectedGraph& g,\n                                                        double alpha,\n                                                        const ArcSet& arc_whitelist,\n                                                        const EdgeSet& edge_blacklist,\n                                                        const EdgeSet& edge_whitelist,\n                                                        util::BaseProgressBar& progress) {\n    return mmpc_all_variables(\n        test, g, g.num_joint_nodes(), alpha, arc_whitelist, edge_blacklist, edge_whitelist, progress);\n}\n\ntemplate <typename G>\nvoid estimate(G& skeleton,\n              const IndependenceTest& test,\n              const ArcStringVector& varc_blacklist,\n              const ArcStringVector& varc_whitelist,\n              const EdgeStringVector& vedge_blacklist,\n              const EdgeStringVector& vedge_whitelist,\n              double alpha,\n              double ambiguous_threshold,\n              bool allow_bidirected,\n              int verbose) {\n    auto restrictions =\n        util::validate_restrictions(skeleton, varc_blacklist, varc_whitelist, vedge_blacklist, vedge_whitelist);\n\n    for (const auto& a : restrictions.arc_whitelist) {\n        skeleton.add_arc(a.first, a.second);\n    }\n\n    auto progress = util::progress_bar(verbose);\n\n    auto cpcs = mmpc_all_variables(test,\n                                   skeleton,\n                                   alpha,\n                                   restrictions.arc_whitelist,\n                                   restrictions.edge_blacklist,\n                                   restrictions.edge_whitelist,\n                                   *progress);\n\n    for (auto i = 0; i < skeleton.num_nodes(); ++i) {\n        for (auto p : cpcs[i]) {\n            if (i < p && cpcs[p].count(i) > 0 && !skeleton.has_arc(i, p) && !skeleton.has_arc(p, i)) {\n                if constexpr (graph::is_unconditional_graph_v<G>) {\n                    skeleton.add_edge(i, p);\n                } else if constexpr (graph::is_conditional_graph_v<G>) {\n                    if (skeleton.is_interface(i))\n                        skeleton.add_arc(i, p);\n                    else if (skeleton.is_interface(p))\n                        skeleton.add_arc(p, i);\n                    else\n                        skeleton.add_edge(i, p);\n                } else {\n                    static_assert(util::always_false<G>, \"Wrong graph type\");\n                }\n            }\n        }\n    }\n\n    direct_arc_blacklist(skeleton, restrictions.arc_blacklist);\n    direct_unshielded_triples(skeleton,\n                              test,\n                              restrictions.arc_blacklist,\n                              restrictions.arc_whitelist,\n                              alpha,\n                              std::nullopt,\n                              true,\n                              ambiguous_threshold,\n                              allow_bidirected,\n                              *progress);\n\n    progress->set_max_progress(3);\n    progress->set_text(\"Applying Meek rules\");\n\n    bool changed = true;\n    while (changed) {\n        changed = false;\n        progress->set_progress(0);\n\n        changed |= MeekRules::rule1(skeleton);\n        progress->tick();\n        changed |= MeekRules::rule2(skeleton);\n        progress->tick();\n        changed |= MeekRules::rule3(skeleton);\n        progress->tick();\n    }\n\n    progress->mark_as_completed(\"Finished MMPC!\");\n}\n\nPartiallyDirectedGraph MMPC::estimate(const IndependenceTest& test,\n                                      const std::vector<std::string>& nodes,\n                                      const ArcStringVector& varc_blacklist,\n                                      const ArcStringVector& varc_whitelist,\n                                      const EdgeStringVector& vedge_blacklist,\n                                      const EdgeStringVector& vedge_whitelist,\n                                      double alpha,\n                                      double ambiguous_threshold,\n                                      bool allow_bidirected,\n                                      int verbose) const {\n    if (alpha <= 0 || alpha >= 1) throw std::invalid_argument(\"alpha must be a number between 0 and 1.\");\n    if (ambiguous_threshold < 0 || ambiguous_threshold > 1)\n        throw std::invalid_argument(\"ambiguous_threshold must be a number between 0 and 1.\");\n\n    PartiallyDirectedGraph skeleton;\n    if (nodes.empty())\n        skeleton = PartiallyDirectedGraph(test.variable_names());\n    else {\n        if (!test.has_variables(nodes))\n            throw std::invalid_argument(\"IndependenceTest do not contain all the variables in nodes list.\");\n        skeleton = PartiallyDirectedGraph(nodes);\n    }\n\n    learning::algorithms::estimate(skeleton,\n                                   test,\n                                   varc_blacklist,\n                                   varc_whitelist,\n                                   vedge_blacklist,\n                                   vedge_whitelist,\n                                   alpha,\n                                   ambiguous_threshold,\n                                   allow_bidirected,\n                                   verbose);\n\n    return skeleton;\n}\n\nConditionalPartiallyDirectedGraph MMPC::estimate_conditional(const IndependenceTest& test,\n                                                             const std::vector<std::string>& nodes,\n                                                             const std::vector<std::string>& interface_nodes,\n                                                             const ArcStringVector& varc_blacklist,\n                                                             const ArcStringVector& varc_whitelist,\n                                                             const EdgeStringVector& vedge_blacklist,\n                                                             const EdgeStringVector& vedge_whitelist,\n                                                             double alpha,\n                                                             double ambiguous_threshold,\n                                                             bool allow_bidirected,\n                                                             int verbose) const {\n    if (alpha <= 0 || alpha >= 1) throw std::invalid_argument(\"alpha must be a number between 0 and 1.\");\n    if (ambiguous_threshold < 0 || ambiguous_threshold > 1)\n        throw std::invalid_argument(\"ambiguous_threshold must be a number between 0 and 1.\");\n\n    if (nodes.empty()) throw std::invalid_argument(\"Node list cannot be empty to train a Conditional graph.\");\n    if (interface_nodes.empty())\n        return MMPC::estimate(test,\n                              nodes,\n                              varc_blacklist,\n                              varc_whitelist,\n                              vedge_blacklist,\n                              vedge_whitelist,\n                              alpha,\n                              ambiguous_threshold,\n                              allow_bidirected,\n                              verbose)\n            .conditional_graph();\n\n    if (!test.has_variables(nodes) || !test.has_variables(interface_nodes))\n        throw std::invalid_argument(\n            \"IndependenceTest do not contain all the variables in nodes/interface_nodes lists.\");\n\n    ConditionalPartiallyDirectedGraph skeleton(nodes, interface_nodes);\n\n    learning::algorithms::estimate(skeleton,\n                                   test,\n                                   varc_blacklist,\n                                   varc_whitelist,\n                                   vedge_blacklist,\n                                   vedge_whitelist,\n                                   alpha,\n                                   ambiguous_threshold,\n                                   allow_bidirected,\n                                   verbose);\n    return skeleton;\n}\n\n}  // namespace learning::algorithms\n", "meta": {"hexsha": "fbf07fc9b90060fda24977afdb7c0cb5b8c36f47", "size": 44462, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pybnesian/learning/algorithms/mmpc.cpp", "max_stars_repo_name": "vishalbelsare/PyBNesian", "max_stars_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T19:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:08:05.000Z", "max_issues_repo_path": "pybnesian/learning/algorithms/mmpc.cpp", "max_issues_repo_name": "vishalbelsare/PyBNesian", "max_issues_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pybnesian/learning/algorithms/mmpc.cpp", "max_forks_repo_name": "vishalbelsare/PyBNesian", "max_forks_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T13:44:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T02:57:02.000Z", "avg_line_length": 38.3623813632, "max_line_length": 118, "alphanum_fraction": 0.5502451532, "num_tokens": 9336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2704424765702841}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\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_AGNOSTIC_CONVEX_GRAHAM_ANDREW_HPP\n#define BOOST_GEOMETRY_STRATEGIES_AGNOSTIC_CONVEX_GRAHAM_ANDREW_HPP\n\n\n#include <cstddef>\n#include <algorithm>\n#include <vector>\n\n#include <boost/range.hpp>\n\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/core/point_type.hpp>\n#include <boost/geometry/strategies/convex_hull.hpp>\n\n#include <boost/geometry/views/detail/range_type.hpp>\n\n#include <boost/geometry/policies/compare.hpp>\n\n#include <boost/geometry/algorithms/detail/for_each_range.hpp>\n#include <boost/geometry/views/reversible_view.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace convex_hull\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\n\ntemplate\n<\n    typename InputRange,\n    typename RangeIterator,\n    typename StrategyLess,\n    typename StrategyGreater\n>\nstruct get_extremes\n{\n    typedef typename point_type<InputRange>::type point_type;\n\n    point_type left, right;\n\n    bool first;\n\n    StrategyLess less;\n    StrategyGreater greater;\n\n    inline get_extremes()\n        : first(true)\n    {}\n\n    inline void apply(InputRange const& range)\n    {\n        if (boost::size(range) == 0)\n        {\n            return;\n        }\n\n        // First iterate through this range\n        // (this two-stage approach avoids many point copies,\n        //  because iterators are kept in memory. Because iterators are\n        //  not persistent (in MSVC) this approach is not applicable\n        //  for more ranges together)\n\n        RangeIterator left_it = boost::begin(range);\n        RangeIterator right_it = boost::begin(range);\n\n        for (RangeIterator it = boost::begin(range) + 1;\n            it != boost::end(range);\n            ++it)\n        {\n            if (less(*it, *left_it))\n            {\n                left_it = it;\n            }\n\n            if (greater(*it, *right_it))\n            {\n                right_it = it;\n            }\n        }\n\n        // Then compare with earlier\n        if (first)\n        {\n            // First time, assign left/right\n            left = *left_it;\n            right = *right_it;\n            first = false;\n        }\n        else\n        {\n            // Next time, check if this range was left/right from\n            // the extremes already collected\n            if (less(*left_it, left))\n            {\n                left = *left_it;\n            }\n\n            if (greater(*right_it, right))\n            {\n                right = *right_it;\n            }\n        }\n    }\n};\n\n\ntemplate\n<\n    typename InputRange,\n    typename RangeIterator,\n    typename Container,\n    typename SideStrategy\n>\nstruct assign_range\n{\n    Container lower_points, upper_points;\n\n    typedef typename point_type<InputRange>::type point_type;\n\n    point_type const& most_left;\n    point_type const& most_right;\n\n    inline assign_range(point_type const& left, point_type const& right)\n        : most_left(left)\n        , most_right(right)\n    {}\n\n    inline void apply(InputRange const& range)\n    {\n        typedef SideStrategy side;\n\n        // Put points in one of the two output sequences\n        for (RangeIterator it = boost::begin(range);\n            it != boost::end(range);\n            ++it)\n        {\n            // check if it is lying most_left or most_right from the line\n\n            int dir = side::apply(most_left, most_right, *it);\n            switch(dir)\n            {\n                case 1 : // left side\n                    upper_points.push_back(*it);\n                    break;\n                case -1 : // right side\n                    lower_points.push_back(*it);\n                    break;\n\n                // 0: on line most_left-most_right,\n                //    or most_left, or most_right,\n                //    -> all never part of hull\n            }\n        }\n    }\n};\n\ntemplate <typename Range>\nstatic inline void sort(Range& range)\n{\n    typedef typename boost::range_value<Range>::type point_type;\n    typedef geometry::less<point_type> comparator;\n\n    std::sort(boost::begin(range), boost::end(range), comparator());\n}\n\n} // namespace detail\n#endif // DOXYGEN_NO_DETAIL\n\n\n/*!\n\\brief Graham scan strategy to calculate convex hull\n\\ingroup strategies\n\\note Completely reworked version inspired on the sources listed below\n\\see http://www.ddj.com/architect/201806315\n\\see http://marknelson.us/2007/08/22/convex\n */\ntemplate <typename InputGeometry, typename OutputPoint>\nclass graham_andrew\n{\npublic :\n    typedef OutputPoint point_type;\n    typedef InputGeometry geometry_type;\n\nprivate:\n\n    typedef typename cs_tag<point_type>::type cs_tag;\n\n    typedef typename std::vector<point_type> container_type;\n    typedef typename std::vector<point_type>::const_iterator iterator;\n    typedef typename std::vector<point_type>::const_reverse_iterator rev_iterator;\n\n\n    class partitions\n    {\n        friend class graham_andrew;\n\n        container_type m_lower_hull;\n        container_type m_upper_hull;\n        container_type m_copied_input;\n    };\n\n\npublic:\n    typedef partitions state_type;\n\n\n    inline void apply(InputGeometry const& geometry, partitions& state) const\n    {\n        // First pass.\n        // Get min/max (in most cases left / right) points\n        // This makes use of the geometry::less/greater predicates\n\n        // For the left boundary it is important that multiple points\n        // are sorted from bottom to top. Therefore the less predicate\n        // does not take the x-only template parameter (this fixes ticket #6019.\n        // For the right boundary it is not necessary (though also not harmful),\n        // because points are sorted from bottom to top in a later stage.\n        // For symmetry and to get often more balanced lower/upper halves\n        // we keep it.\n\n        typedef typename geometry::detail::range_type<InputGeometry>::type range_type;\n\n        typedef typename boost::range_iterator\n            <\n                range_type const\n            >::type range_iterator;\n\n        detail::get_extremes\n            <\n                range_type,\n                range_iterator,\n                geometry::less<point_type>,\n                geometry::greater<point_type>\n            > extremes;\n        geometry::detail::for_each_range(geometry, extremes);\n\n        // Bounding left/right points\n        // Second pass, now that extremes are found, assign all points\n        // in either lower, either upper\n        detail::assign_range\n            <\n                range_type,\n                range_iterator,\n                container_type,\n                typename strategy::side::services::default_strategy<cs_tag>::type\n            > assigner(extremes.left, extremes.right);\n\n        geometry::detail::for_each_range(geometry, assigner);\n\n\n        // Sort both collections, first on x(, then on y)\n        detail::sort(assigner.lower_points);\n        detail::sort(assigner.upper_points);\n\n        //std::cout << boost::size(assigner.lower_points) << std::endl;\n        //std::cout << boost::size(assigner.upper_points) << std::endl;\n\n        // And decide which point should be in the final hull\n        build_half_hull<-1>(assigner.lower_points, state.m_lower_hull,\n                extremes.left, extremes.right);\n        build_half_hull<1>(assigner.upper_points, state.m_upper_hull,\n                extremes.left, extremes.right);\n    }\n\n\n    template <typename OutputIterator>\n    inline void result(partitions const& state,\n                    OutputIterator out, bool clockwise)  const\n    {\n        if (clockwise)\n        {\n            output_range<iterate_forward>(state.m_upper_hull, out, false);\n            output_range<iterate_reverse>(state.m_lower_hull, out, true);\n        }\n        else\n        {\n            output_range<iterate_forward>(state.m_lower_hull, out, false);\n            output_range<iterate_reverse>(state.m_upper_hull, out, true);\n        }\n    }\n\n\nprivate:\n\n    template <int Factor>\n    static inline void build_half_hull(container_type const& input,\n            container_type& output,\n            point_type const& left, point_type const& right)\n    {\n        output.push_back(left);\n        for(iterator it = input.begin(); it != input.end(); ++it)\n        {\n            add_to_hull<Factor>(*it, output);\n        }\n        add_to_hull<Factor>(right, output);\n    }\n\n\n    template <int Factor>\n    static inline void add_to_hull(point_type const& p, container_type& output)\n    {\n        typedef typename strategy::side::services::default_strategy<cs_tag>::type side;\n\n        output.push_back(p);\n        std::size_t output_size = output.size();\n        while (output_size >= 3)\n        {\n            rev_iterator rit = output.rbegin();\n            point_type const last = *rit++;\n            point_type const& last2 = *rit++;\n\n            if (Factor * side::apply(*rit, last, last2) <= 0)\n            {\n                // Remove last two points from stack, and add last again\n                // This is much faster then erasing the one but last.\n                output.pop_back();\n                output.pop_back();\n                output.push_back(last);\n                output_size--;\n            }\n            else\n            {\n                return;\n            }\n        }\n    }\n\n\n    template <iterate_direction Direction, typename OutputIterator>\n    static inline void output_range(container_type const& range,\n        OutputIterator out, bool skip_first)\n    {\n        typedef typename reversible_view<container_type const, Direction>::type view_type;\n        view_type view(range);\n        bool first = true;\n        for (typename boost::range_iterator<view_type const>::type it = boost::begin(view);\n            it != boost::end(view); ++it)\n        {\n            if (first && skip_first)\n            {\n                first = false;\n            }\n            else\n            {\n                *out = *it;\n                ++out;\n            }\n        }\n    }\n\n};\n\n}} // namespace strategy::convex_hull\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\ntemplate <typename InputGeometry, typename OutputPoint>\nstruct strategy_convex_hull<InputGeometry, OutputPoint, cartesian_tag>\n{\n    typedef strategy::convex_hull::graham_andrew<InputGeometry, OutputPoint> type;\n};\n#endif\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGIES_AGNOSTIC_CONVEX_GRAHAM_ANDREW_HPP\n", "meta": {"hexsha": "ce3142d892cf90429b7df851ee920d2bf5568cd3", "size": 10778, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost_1_56_0/boost/geometry/strategies/agnostic/hull_graham_andrew.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/strategies/agnostic/hull_graham_andrew.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/strategies/agnostic/hull_graham_andrew.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": 27.9948051948, "max_line_length": 91, "alphanum_fraction": 0.6105956578, "num_tokens": 2313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.27044247657028403}}
{"text": "/*\n * KameleonInterpolator_compute_gradient.cpp\n *\n *  Created on: Sep 28, 2009\n *      Author: David Berrios\n */\n\n#include \"KameleonInterpolator.h\"\n#include <vector>\n#include <boost/algorithm/string.hpp>\n\n\nnamespace ccmc\n{\n\n\n\t/**\n\t * @param variable\n\t * @param positionComponent1 The first component of the position\n\t * @param positionComponent2 The second component of the position\n\t * @param positionComponent3 The third component of the position\n\t * @return\n\t */\n\tfloat KameleonInterpolator::compute_gradient(const std::string& variable, const float& positionComponent1,\n\t\t\tconst float& positionComponent2, const float& positionComponent3)\n\t{\n\t\tfloat dComponent1, dComponent2, dComponent3;\n\t\treturn compute_gradient(variable, positionComponent1, positionComponent2, positionComponent3, dComponent1,\n\t\t\t\tdComponent2, dComponent3);\n\t}\n\n\t/**\n\t * @param variable\n\t * @param c0 The first component of the position\n\t * @param c1 The second component of the position\n\t * @param c2 The third component of the position\n\t * @param dComponent1 The delta of the block size for component1 at the position specified.\n\t * @param dComponent2 The delta of the block size for component2 at the position specified.\n\t * @param dComponent3 The delta of the block size for component3 at the position specified.\n\t * @return\n\t */\n\tfloat KameleonInterpolator::compute_gradient(const std::string& variable, const float& c0,\n\t\t\tconst float& c1, const float& c2, float& dc0, float& dc1,\n\t\t\tfloat& dc2)\n\t{\n\t\t//parse the string, and attempt to calculate the gradient of the parsed variable\n\n\t\tstd::vector<std::string> tokens;\n\t\tboost::split(tokens, variable, boost::is_any_of(\".\"), boost::token_compress_on);\n\n\t\t/*t = interpolate(\"t\", positionComponent1, positionComponent2, positionComponent3, dComponent1, dComponent2,\n\t\t\t\tdComponent3);\n\t\tif (t == missingValue)\n\t\t\treturn missingValue;\n\t\tn = interpolate(\"n\", positionComponent1, positionComponent2, positionComponent3, dComponent1, dComponent2,\n\t\t\t\tdComponent3);\n\t\tif (n == missingValue)\n\t\t\treturn missingValue;\n\t\tfloat s = t / pow(n, 2.0f / 3.0f);*/\n\t\t//cout << \"gradient variable: '\" << tokens[1] << \"'\" << endl;\n\n\t\t//super expensive to calculation this. Try to store the components of the gradient, and speed up the calculations\n\t\t//if the components are requested in sequential order\n\t\tfloat pointValue = interpolate(tokens[1],c0,c1,c2,dc0,dc1,dc2);\n\t\tfloat direction;\n\t\tfloat dc0_scaled = dc0*.5f;\n\t\tfloat dc1_scaled = dc1*.5f;\n\t\tfloat dc2_scaled = dc2*.5f;\n\t\tfloat positions_c0[8];\n\t\tfloat positions_c1[8];\n\t\tfloat positions_c2[8];\n\n\t\tpositions_c0[0] = c0 + dc0_scaled;\n\t\tpositions_c0[1] = c0 + dc0_scaled;\n\t\tpositions_c0[2] = c0 - dc0_scaled;\n\t\tpositions_c0[3] = c0 - dc0_scaled;\n\t\tpositions_c0[4] = c0 + dc0_scaled;\n\t\tpositions_c0[5] = c0 + dc0_scaled;\n\t\tpositions_c0[6] = c0 - dc0_scaled;\n\t\tpositions_c0[7] = c0 - dc0_scaled;\n\n\n\t\tpositions_c1[0] = c1 - dc1_scaled;\n\t\tpositions_c1[1] = c1 - dc1_scaled;\n\t\tpositions_c1[2] = c1 - dc1_scaled;\n\t\tpositions_c1[3] = c1 - dc1_scaled;\n\t\tpositions_c1[4] = c1 + dc1_scaled;\n\t\tpositions_c1[5] = c1 + dc1_scaled;\n\t\tpositions_c1[6] = c1 + dc1_scaled;\n\t\tpositions_c1[7] = c1 + dc1_scaled;\n\n\t\tpositions_c2[0] = c2 - dc2_scaled;\n\t\tpositions_c2[1] = c2 + dc2_scaled;\n\t\tpositions_c2[2] = c2 + dc2_scaled;\n\t\tpositions_c2[3] = c2 - dc2_scaled;\n\t\tpositions_c2[4] = c2 - dc2_scaled;\n\t\tpositions_c2[5] = c2 + dc2_scaled;\n\t\tpositions_c2[6] = c2 + dc2_scaled;\n\t\tpositions_c2[7] = c2 - dc2_scaled;\n\n\t\t//direction and magnitude of greatest change\n\t\tfloat p0 = c0;\n\t\tfloat p1 = c1;\n\t\tfloat p2 = c2;\n\t\tfloat current_max = -999999999999.f;\n\t\tfor (int i = 0; i < 8; i++)\n\t\t{\n\n\t\t\tdirection = interpolate(tokens[1],positions_c0[i],positions_c1[i],positions_c2[i]);\n\t\t\t//cout << \"*i: \" << i << endl;\n\t\t\tfloat current_diff = direction - pointValue;\n\t\t\tif (current_diff > current_max )\n\t\t\t{\n\t\t\t\tcurrent_max = current_diff;\n\t\t\t\tp0 = positions_c0[i];\n\t\t\t\tp1 = positions_c1[i];\n\t\t\t\tp2 = positions_c2[i];\n\t\t\t}\n\t\t}\n\n\t\treturn current_max;\n\n\t}\n}\n", "meta": {"hexsha": "0f0ea60543c1ba2d39067909a4e6b532029a3c9a", "size": 3987, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/kameleon/src/ccmc/KameleonInterpolator_compute_gradient.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/KameleonInterpolator_compute_gradient.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/KameleonInterpolator_compute_gradient.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": 31.896, "max_line_length": 115, "alphanum_fraction": 0.7060446451, "num_tokens": 1230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.27024872028474856}}
{"text": "//=============================================================================================================\n/**\n * @file     spectrogram.cpp\n * @author   Lorenz Esch <lesch@mgh.harvard.edu>\n * @version  dev\n * @date     September, 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    Definition of spectrogram class.\n */\n\n//*************************************************************************************************************\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include \"spectrogram.h\"\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// Eigen INCLUDES\n//=============================================================================================================\n\n#include <Eigen/SparseCore>\n#include <unsupported/Eigen/FFT>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// Qt INCLUDES\n//=============================================================================================================\n\n#include <QDebug>\n#include <QElapsedTimer>\n#include <QThread>\n#include <QtConcurrent>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace UTILSLIB;\nusing namespace Eigen;\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// DEFINE MEMBER METHODS\n//=============================================================================================================\n\nMatrixXd Spectrogram::makeSpectrogram(VectorXd signal, qint32 windowSize = 0)\n{\n    //QElapsedTimer timer;\n    //timer.start();\n\n    signal.array() -= signal.mean();\n    QList<SpectogramInputData> lData;\n    int iThreadSize = QThread::idealThreadCount()*2;\n    int iStepsSize = signal.rows()/iThreadSize;\n    int iResidual = signal.rows()%iThreadSize;\n\n    SpectogramInputData dataTemp;\n    dataTemp.vecInputData = signal;\n    dataTemp.window_size = windowSize;\n    if(dataTemp.window_size == 0) {\n        dataTemp.window_size = signal.rows()/15;\n    }\n\n    for (int i = 0; i < iThreadSize; ++i) {\n        dataTemp.iRangeLow = i*iStepsSize;\n        dataTemp.iRangeHigh = i*iStepsSize+iStepsSize;\n        lData.append(dataTemp);\n    }\n\n    dataTemp.iRangeLow = iThreadSize*iStepsSize;\n    dataTemp.iRangeHigh = iThreadSize*iStepsSize+iResidual;\n    lData.append(dataTemp);\n\n    QFuture<MatrixXd> resultMat = QtConcurrent::mappedReduced(lData,\n                                                              compute,\n                                                              reduce);\n    resultMat.waitForFinished();\n\n    //qDebug() << \"Spectrogram::make_spectrogram - timer.elapsed()\" << timer.elapsed();\n    return resultMat.result();\n}\n\n\n//*************************************************************************************************************\n\nVectorXd Spectrogram::gaussWindow(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//*************************************************************************************************************\n\nMatrixXd Spectrogram::compute(const SpectogramInputData& inputData)\n{\n    #ifdef EIGEN_FFTW_DEFAULT\n        fftw_make_planner_thread_safe();\n    #endif\n\n    Eigen::FFT<double> fft;\n    MatrixXd tf_matrix = MatrixXd::Zero(inputData.vecInputData.rows()/2, inputData.vecInputData.rows());\n    VectorXd envelope, windowed_sig, real_coeffs;\n    VectorXcd fft_win_sig;\n    qint32 window_size = inputData.window_size;\n\n    for(quint32 translate = inputData.iRangeLow; translate < inputData.iRangeHigh; translate++) {\n        envelope = gaussWindow(inputData.vecInputData.rows(), window_size, translate);\n\n        windowed_sig = VectorXd::Zero(inputData.vecInputData.rows());\n        fft_win_sig = VectorXcd::Zero(inputData.vecInputData.rows());\n\n        windowed_sig = inputData.vecInputData.array() * envelope.array();\\\n\n        fft.fwd(fft_win_sig, windowed_sig);\n\n        real_coeffs = fft_win_sig.segment(0,inputData.vecInputData.rows()/2).array().abs2();\n\n        tf_matrix.col(translate) = real_coeffs;\n    }\n\n    return tf_matrix;\n}\n\n\n//*************************************************************************************************************\n\nvoid Spectrogram::reduce(MatrixXd &resultData,\n                         const MatrixXd &data)\n{\n    if(resultData.size() == 0) {\n        resultData = data;\n    } else {\n        resultData += data;\n    }\n}\n", "meta": {"hexsha": "f6c58c4e39d11dedda1bd9fd8033189fdeafccee", "size": 7064, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/utils/spectrogram.cpp", "max_stars_repo_name": "Andrey1994/mne-cpp", "max_stars_repo_head_hexsha": "6264b1107b9447b7db64309f73f09e848fd198c4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-11-16T19:38:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T20:52:08.000Z", "max_issues_repo_path": "libraries/utils/spectrogram.cpp", "max_issues_repo_name": "Andrey1994/mne-cpp", "max_issues_repo_head_hexsha": "6264b1107b9447b7db64309f73f09e848fd198c4", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/spectrogram.cpp", "max_forks_repo_name": "Andrey1994/mne-cpp", "max_forks_repo_head_hexsha": "6264b1107b9447b7db64309f73f09e848fd198c4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-16T19:39:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-16T19:39:01.000Z", "avg_line_length": 40.5977011494, "max_line_length": 117, "alphanum_fraction": 0.4800396376, "num_tokens": 1205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.27024872028474856}}
{"text": "//=======================================================================\n// Copyright (c) 2013 Attila Bernath, Piotr Wygocki\n//               2014 Piotr Godlewski, Piotr Smulewicz\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 tree_augmentation.hpp\n * @brief\n * @author Attila Bernath, Piotr Smulewicz, Piotr Wygocki, Piotr Godlewski\n * @version 1.0\n * @date 2013-06-20\n */\n#ifndef PAAL_TREE_AUGMENTATION_HPP\n#define PAAL_TREE_AUGMENTATION_HPP\n\n\n#include \"paal/iterative_rounding/ir_components.hpp\"\n#include \"paal/iterative_rounding/iterative_rounding.hpp\"\n#include \"paal/utils/hash.hpp\"\n\n#include <boost/bimap.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/filtered_graph.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <boost/graph/stoer_wagner_min_cut.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/range/as_array.hpp>\n#include <boost/range/distance.hpp>\n\n#include <algorithm>\n#include <utility>\n\nnamespace paal {\nnamespace ir {\n\nnamespace detail {\n\n/// This function returns the number of edges in a graph. The\n/// reason this function was written is that BGL's num_edges()\n/// function does not work properly for filtered_graph.  See\n/// http://www.boost.org/doc/libs/1_55_0/libs/graph/doc/filtered_graph.html#2\ntemplate <class EdgeListGraph>\nint filtered_num_edges(const EdgeListGraph & g) {\n    return boost::distance(edges(g));\n}\n\n/// A class that translates bool map on the edges to a filter, which can be used\n/// with\n/// boost::filtered_graph. That is, we translate operator[] to\n/// operator().  We do a little more: we will also need the negated\n/// version of the map (for the graph of the non-tree edges).\ntemplate <typename EdgeBoolMap> struct bool_map_to_tree_filter {\n    bool_map_to_tree_filter() {}\n\n    bool_map_to_tree_filter(EdgeBoolMap m) : ebmap(m) {}\n\n    template <typename Edge> bool operator()(const Edge &e) const {\n        return get(ebmap, e);\n    }\n\n    EdgeBoolMap ebmap;\n};\n\ntemplate <typename EdgeBoolMap> struct bool_map_to_non_tree_filter {\n    bool_map_to_non_tree_filter() {}\n\n    bool_map_to_non_tree_filter(EdgeBoolMap m) : ebmap(m) {}\n\n    template <typename Edge> bool operator()(const Edge &e) const {\n        return !get(ebmap, e);\n    }\n\n    EdgeBoolMap ebmap;\n};\n\n/// A boost graph map that returns a constant integer value.\ntemplate <typename KeyType, int num>\nclass const_int_map\n    : public boost::put_get_helper<int, const_int_map<KeyType, num>> {\n  public:\n    using category = boost::readable_property_map_tag;\n    using value_type = int;\n    using reference = int;\n    using key_type = KeyType;\n    reference operator[](KeyType e) const { return num; }\n};\n\n} // namespace detail\n\nnamespace {\nstruct ta_compare_traits {\n    static const double EPSILON;\n};\n\nconst double ta_compare_traits::EPSILON = 1e-10;\n}\n\n/**\n * Round Condition of the IR Tree Augmentation algorithm.\n */\nstruct ta_round_condition {\n    /**\n     * Constructor. Takes epsilon used in double comparison.\n     */\n    ta_round_condition(double epsilon = ta_compare_traits::EPSILON)\n        : m_round_half(epsilon) {}\n\n    /**\n     * Rounds a column up if it is at least half in the\n     * current solution. If the column is rounded, the\n     * corresponding edge is added to the result.\n     */\n    template <typename Problem, typename LP>\n    boost::optional<double> operator()(Problem &problem, LP &lp,\n                                       lp::col_id col) {\n        auto res = m_round_half(problem, lp, col);\n        if (res) {\n            problem.add_to_solution(col);\n        }\n        return res;\n    }\n\n  private:\n    round_condition_greater_than_half m_round_half;\n};\n\n/**\n * Set Solution component of the IR Tree Augmentation algorithm.\n */\nstruct ta_set_solution {\n    /**\n     * Constructor. Takes epsilon used in double comparison.\n     */\n    ta_set_solution(double epsilon = ta_compare_traits::EPSILON)\n        : m_compare(epsilon) {}\n\n    /**\n     * Creates the result form the LP (all edges corresponding to columns with\n     * value 1).\n     */\n    template <typename Problem, typename GetSolution>\n    void operator()(Problem &problem, const GetSolution &solution) {\n        for (auto e :\n             boost::as_array(edges(problem.get_links_graph()))) {\n            if (!problem.is_in_solution(e)) {\n                auto col = problem.edge_to_col(e);\n                if (m_compare.e(solution(col), 1)) {\n                    problem.add_to_solution(col);\n                }\n            }\n        }\n    }\n\nprivate:\n    const utils::compare<double> m_compare;\n};\n\n/**\n * Initialization of the IR Tree Augmentation algorithm.\n */\nclass ta_init {\n  public:\n    /**\n     * Initialize the cut LP.\n     */\n    template <typename Problem, typename LP>\n    void operator()(Problem &problem, LP &lp) {\n        problem.init();\n        lp.set_lp_name(\"Tree augmentation\");\n        lp.set_optimization_type(lp::MINIMIZE);\n\n        add_variables(problem, lp);\n        add_cut_constraints(problem, lp);\n    }\n\n  private:\n    /**\n     * Adds a variable to the LP for each link in the input graph.\n     * Binds the LP columns to graph edges.\n     */\n    template <typename Problem, typename LP>\n    void add_variables(Problem & problem, LP & lp) {\n        for (auto e : boost::as_array(edges(problem.get_links_graph()))) {\n            lp::col_id col_idx = lp.add_column(problem.get_cost(e), 0);\n            problem.bind_edge_to_col(e, col_idx);\n        }\n    }\n\n    /**\n     * Adds a cut constraint to the LP for each edge in the input graph\n     * and binds edges to LP rows.\n     */\n    template <typename Problem, typename LP>\n    void add_cut_constraints(Problem &problem, LP &lp) {\n        for (auto e :\n             boost::as_array(edges(problem.get_tree_graph()))) {\n            lp::linear_expression expr;\n            for (auto pe : problem.get_covered_by(e)) {\n                expr += problem.edge_to_col(pe);\n            }\n\n            lp::row_id row_idx = lp.add_row(std::move(expr) >= 1);\n            problem.bind_edge_to_row(e, row_idx);\n        }\n    }\n};\n\ntemplate <\n    typename Init = ta_init,\n    typename RoundCondition = ta_round_condition,\n    typename RelaxContition = utils::always_false,\n    typename SetSolution = ta_set_solution>\n        using tree_augmentation_ir_components = IRcomponents<Init, RoundCondition,\n                        RelaxContition, SetSolution>;\n\n/**\n * @brief This is Jain's iterative rounding\n * 2-approximation algorithm for the Generalised Steiner Network\n * Problem, specialized for the Tree Augmentation Problem.\n *\n * The Tree Augmentation Problem is the following. Given a\n * 2-edge connected graph, in which a spanning tree is\n * designated. The non-tree edges are also called links. The\n * links have non-negative costs. The problem is to find a\n * minimum cost subset of links which, together with the\n * tree-edges give a 2-edge-connected graph.\n *\n * @tparam Graph the graph type used\n * @tparam TreeMap it is assumed to be a bool map on the edges of a graph of type Graph.\n *  It is used for designating a spanning tree in the graph.\n * @tparam CostMap type for the costs of the links.\n * @tparam VertexIndex type for the vertex index map.\n * @tparam EdgeSetOutputIterator type for the result edge set.\n */\ntemplate <typename Graph, typename TreeMap, typename CostMap,\n          typename VertexIndex, typename EdgeSetOutputIterator>\nclass tree_aug {\n  public:\n    using Edge = typename boost::graph_traits<Graph>::edge_descriptor;\n    using Vertex = typename boost::graph_traits<Graph>::vertex_descriptor;\n    using CostValue = double;\n\n    using TreeGraph =\n        boost::filtered_graph<Graph, detail::bool_map_to_tree_filter<TreeMap>>;\n    using NonTreeGraph = boost::filtered_graph<\n        Graph, detail::bool_map_to_non_tree_filter<TreeMap>>;\n\n    using EdgeList = std::vector<Edge>;\n    using CoverMap = std::unordered_map<Edge, EdgeList, edge_hash<Graph>>;\n\n    // cross reference between links and columns\n    using EdgeToColId = boost::bimap<Edge, lp::col_id>;\n    using RowIdToEdge = std::unordered_map<lp::row_id, Edge>;\n\n    using ErrorMessage = boost::optional<std::string>;\n\n    /**\n     * Constructor.\n     *\n     * @param g  the graph to work with\n     * @param tree_map designate a spanning tree in \\c g\n     * @param cost_map costs of the links (=non-tree edges). The costs assigned to tree edges are not used.\n     * @param vertex_index vertex index map\n     * @param solution result set of edges output iterator\n     */\n    tree_aug(const Graph & g, TreeMap tree_map, CostMap cost_map,\n            VertexIndex vertex_index, EdgeSetOutputIterator solution) :\n        m_g(g), m_tree_map(tree_map), m_cost_map(cost_map), m_index(vertex_index),\n        m_solution(solution),\n        m_tree(m_g, detail::bool_map_to_tree_filter<TreeMap>(m_tree_map)),\n        m_ntree(m_g, detail::bool_map_to_non_tree_filter<TreeMap>(m_tree_map)),\n        m_sol_cost(0)\n    {}\n\n    /// Checks validity of the input\n    ErrorMessage check_input_validity() {\n        // Num of edges == num of nodes-1 in the tree?\n        int n_v = num_vertices(m_g);\n        int n_e = filtered_num_edges(m_tree);\n\n        if (n_e != n_v - 1) {\n            return \"Incorrect number of edges in the spanning tree. \"\n                        + std::string(\"Should be \") + std::to_string(n_v - 1)\n                        + \", but it is \" + std::to_string(n_e) + \".\";\n        }\n\n        // Is the tree connected?\n        std::vector<int> component(num_vertices(m_g));\n        int num = boost::connected_components(m_tree, &component[0]);\n        if (num > 1) {\n            return ErrorMessage{ \"The spanning tree is not connected.\" };\n        }\n\n        // Is the graph 2-edge-connected?\n        detail::const_int_map<Edge, 1> const_1_edge_map;\n        // TODO This stoer-wagner algorithm is unnecessarily slow for some reason\n        int min_cut = boost::stoer_wagner_min_cut(m_g, const_1_edge_map);\n        if (min_cut < 2) {\n            return ErrorMessage{\"The graph is not 2-edge-connected.\"};\n        }\n\n        return ErrorMessage{};\n    }\n\n    /**\n     * Returns the non-tree graph (set of links).\n     */\n    const NonTreeGraph &get_links_graph() const { return m_ntree; }\n\n    /**\n     * Returns the spanning tree.\n     */\n    const TreeGraph &get_tree_graph() const { return m_tree; }\n\n    /**\n     * Returns the cost of an edge.\n     */\n    auto get_cost(Edge e)->decltype(get(std::declval<CostMap>(), e)) {\n        return get(m_cost_map, e);\n    }\n\n    /**\n     * Adds an edge corresponding to the given LP column to the result set.\n     */\n    void add_to_solution(lp::col_id col) {\n        *m_solution = m_edge_to_col_id.right.at(col);\n        ++m_solution;\n        m_sol_cost += m_cost_map[m_edge_to_col_id.right.at(col)];\n        m_edge_to_col_id.right.erase(col);\n    }\n\n    /**\n     * Binds a graph edge to a LP column.\n     */\n    void bind_edge_to_col(Edge e, lp::col_id col) {\n        auto tmp =\n            m_edge_to_col_id.insert(typename EdgeToColId::value_type(e, col));\n        assert(tmp.second);\n    }\n\n    /**\n     * Binds a graph edge to a LP row.\n     */\n    void bind_edge_to_row(Edge e, lp::row_id row) {\n        auto tmp =\n            m_row_id_to_edge.insert(typename RowIdToEdge::value_type(row, e));\n        assert(tmp.second);\n    }\n\n    /**\n     * Initializes the necessary data structures.\n     */\n    void init() {\n        // We need to fill very useful auxiliary data structures:\n        //\\c m_covered_by - containing lists of\n        // edges. For a tree edge \\c t the list \\c m_covered_by[t]\n        // contains the list of links covering \\c t.\n\n        std::vector<Edge> pred(num_vertices(m_g));\n        auto pred_map =\n            boost::make_iterator_property_map(pred.begin(), m_index);\n        std::set<Vertex> seen;\n        for (auto u : boost::as_array(vertices(m_g))) {\n            auto tmp = seen.insert(u);\n            assert(tmp.second);\n            boost::breadth_first_search(\n                m_tree, u, boost::visitor(boost::make_bfs_visitor(\n                               boost::record_edge_predecessors(\n                                   pred_map, boost::on_tree_edge()))));\n\n            for (auto e : boost::as_array(out_edges(u, m_ntree))) {\n                auto node = target(e, m_ntree);\n                if (!seen.count(node)) {\n                    while (node != u) {\n                        m_covered_by[get(pred_map, node)].push_back(e);\n                        node = source(get(pred_map, node), m_tree);\n                    }\n                }\n            }\n        }\n    }\n\n    /**\n     * Returns the edge corresponding to an LP row.\n     */\n    Edge row_to_edge(lp::row_id row) const { return m_row_id_to_edge.at(row); }\n\n    /**\n     * Returns the LP columnn corresponding to a graph edge.\n     */\n    lp::col_id edge_to_col(Edge e) const { return m_edge_to_col_id.left.at(e); }\n\n    /**\n     * Returns the list of links covering a given edge.\n     */\n    EdgeList &get_covered_by(Edge e) { return m_covered_by[e]; }\n\n    /**\n     * Checks if an edge belongs to the solution.\n     */\n    bool is_in_solution(Edge e) const {\n        return m_edge_to_col_id.left.find(e) == m_edge_to_col_id.left.end();\n    }\n\n    /**\n     * Returns cost of the found solution.\n     */\n    CostValue get_solution_cost() const { return m_sol_cost; }\n\n  private:\n\n    /// Input graph\n    const Graph &m_g;\n    /// Input tree edges map\n    TreeMap m_tree_map;\n    /// Input edge cost map\n    CostMap m_cost_map;\n    /// Vertex index map\n    VertexIndex m_index;\n\n    /// Which links are chosen in the solution\n    EdgeSetOutputIterator m_solution;\n\n    /// Auxiliary data structures\n    EdgeToColId m_edge_to_col_id;\n\n    /// The spanning tree\n    TreeGraph m_tree;\n    /// The non-tree (=set of links)\n    NonTreeGraph m_ntree;\n    /// Cost of the solution found\n    CostValue m_sol_cost;\n    /// Structures for the \"m_covered_by\" relations\n    CoverMap m_covered_by;\n    /// Reference between tree edges and row ids\n    RowIdToEdge m_row_id_to_edge;\n};\n\nnamespace detail {\n/**\n * @brief Creates a tree_aug object. Non-named parameters.\n *\n * @tparam Graph\n * @tparam TreeMap\n * @tparam CostMap\n * @tparam VertexIndex\n * @tparam EdgeSetOutputIterator\n * @param g\n * @param tree_map\n * @param cost_map\n * @param vertex_index\n * @param solution\n *\n * @return tree_aug object\n */\ntemplate <typename Graph, typename TreeMap, typename CostMap,\n          typename VertexIndex, typename EdgeSetOutputIterator>\ntree_aug<Graph, TreeMap, CostMap, VertexIndex, EdgeSetOutputIterator>\nmake_tree_aug(const Graph & g, TreeMap tree_map, CostMap cost_map,\n                VertexIndex vertex_index, EdgeSetOutputIterator solution) {\n    return paal::ir::tree_aug<Graph, TreeMap, CostMap,\n            VertexIndex, EdgeSetOutputIterator>(g, tree_map, cost_map, vertex_index, solution);\n}\n\n/**\n * @brief Solves the Tree Augmentation problem using Iterative Rounding.\n* Non-named parameters.\n *\n * @tparam Graph\n * @tparam TreeMap\n * @tparam CostMap\n * @tparam VertexIndex\n * @tparam EdgeSetOutputIterator\n * @tparam IRcomponents\n * @tparam Visitor\n * @param g\n * @param tree_map\n * @param cost_map\n * @param vertex_index\n * @param solution\n * @param components\n * @param visitor\n *\n * @return solution status\n */\ntemplate <typename Graph, typename TreeMap, typename CostMap,\n          typename VertexIndex, typename EdgeSetOutputIterator,\n          typename IRcomponents = tree_augmentation_ir_components<>,\n          typename Visitor = trivial_visitor>\nIRResult tree_augmentation_iterative_rounding(\n        const Graph & g,\n        TreeMap tree_map,\n        CostMap cost_map,\n        VertexIndex vertex_index,\n        EdgeSetOutputIterator solution,\n        IRcomponents components = IRcomponents(),\n        Visitor visitor = Visitor()) {\n    auto treeaug = make_tree_aug(g, tree_map, cost_map, vertex_index, solution);\n    return solve_iterative_rounding(treeaug, std::move(components), std::move(visitor));\n}\n} // detail\n\n/**\n * Creates a tree_aug object. Named parameters.\n * The returned object can be used to check input validity or to get a lower\n* bound on the\n * optimal solution cost.\n *\n * @tparam Graph\n * @tparam EdgeSetOutputIterator\n * @tparam P\n * @tparam T\n * @tparam R\n * @param g\n * @param params\n * @param solution\n *\n * @return tree_aug object\n */\ntemplate <typename Graph, typename EdgeSetOutputIterator, typename P,\n          typename T, typename R>\nauto make_tree_aug(const Graph &g,\n                   const boost::bgl_named_params<P, T, R> &params,\n                   EdgeSetOutputIterator solution)\n    ->tree_aug<\n          Graph,\n          decltype(choose_const_pmap(get_param(params, boost::edge_color), g,\n                                     boost::edge_color)),\n          decltype(choose_const_pmap(get_param(params, boost::edge_weight), g,\n                                     boost::edge_weight)),\n          decltype(choose_const_pmap(get_param(params, boost::vertex_index), g,\n                                     boost::vertex_index)),\n          EdgeSetOutputIterator> {\n    return detail::make_tree_aug(\n        g, choose_const_pmap(get_param(params, boost::edge_color), g,\n                             boost::edge_color),\n        choose_const_pmap(get_param(params, boost::edge_weight), g,\n                          boost::edge_weight),\n        choose_const_pmap(get_param(params, boost::vertex_index), g,\n                          boost::vertex_index),\n        solution);\n}\n\n/**\n * Creates a tree_aug object. All default parameters.\n * The returned object can be used to check input validity or to get a lower\n* bound on the\n * optimal solution cost.\n *\n * @tparam Graph\n * @tparam EdgeSetOutputIterator\n * @param g\n * @param solution\n *\n * @return tree_aug object\n */\ntemplate <typename Graph, typename EdgeSetOutputIterator>\nauto make_tree_aug(const Graph &g, EdgeSetOutputIterator solution)\n    ->decltype(make_tree_aug(g, boost::no_named_parameters(), solution)) {\n    return make_tree_aug(g, boost::no_named_parameters(), solution);\n}\n\n/**\n * @brief Solves the Tree Augmentation problem using Iterative Rounding. Named\n* parameters.\n *\n * @tparam Graph\n * @tparam EdgeSetOutputIterator\n * @tparam IRcomponents\n * @tparam Visitor\n * @tparam P\n * @tparam T\n * @tparam R\n * @param g\n * @param params\n * @param solution\n * @param components\n * @param visitor\n *\n * @return solution status\n */\ntemplate <typename Graph, typename EdgeSetOutputIterator,\n          typename IRcomponents = tree_augmentation_ir_components<>,\n          typename Visitor = trivial_visitor, typename P, typename T,\n          typename R>\nIRResult tree_augmentation_iterative_rounding(\n    const Graph &g, const boost::bgl_named_params<P, T, R> &params,\n    EdgeSetOutputIterator solution, IRcomponents components = IRcomponents(),\n    Visitor visitor = Visitor()) {\n    return detail::tree_augmentation_iterative_rounding(\n        g, choose_const_pmap(get_param(params, boost::edge_color), g,\n                             boost::edge_color),\n        choose_const_pmap(get_param(params, boost::edge_weight), g,\n                          boost::edge_weight),\n        choose_const_pmap(get_param(params, boost::vertex_index), g,\n                          boost::vertex_index),\n        std::move(solution), std::move(components), std::move(visitor));\n}\n\n/**\n * @brief Solves the Tree Augmentation problem using Iterative Rounding. All\n* default parameters.\n *\n * @tparam Graph\n * @tparam EdgeSetOutputIterator\n * @tparam IRcomponents\n * @tparam Visitor\n * @param g\n * @param solution\n * @param components\n * @param visitor\n *\n * @return solution status\n */\ntemplate <typename Graph, typename EdgeSetOutputIterator,\n          typename IRcomponents = tree_augmentation_ir_components<>,\n          typename Visitor = trivial_visitor>\nIRResult tree_augmentation_iterative_rounding(const Graph &g,\n                                              EdgeSetOutputIterator solution,\n                                              IRcomponents components =\n                                                  IRcomponents(),\n                                              Visitor visitor = Visitor()) {\n    return tree_augmentation_iterative_rounding(\n        g, boost::no_named_parameters(), std::move(solution),\n        std::move(components), std::move(visitor));\n}\n\n} // ir\n} // paal\n\n#endif // PAAL_TREE_AUGMENTATION_HPP\n", "meta": {"hexsha": "c6033b158df289f598ec072ff28b72c4d9809bd3", "size": 20702, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/iterative_rounding/treeaug/tree_augmentation.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/iterative_rounding/treeaug/tree_augmentation.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/iterative_rounding/treeaug/tree_augmentation.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": 32.4992150706, "max_line_length": 107, "alphanum_fraction": 0.6445754033, "num_tokens": 4759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.27003091375399757}}
{"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 SplitMSSM_FullMSSM_THRESHOLDS_H\n#define SplitMSSM_FullMSSM_THRESHOLDS_H\n\n#include <Eigen/Core>\n\n/**\n * @file splitmssm_thresholds.hpp\n *\n * Contains function declarations for threshold corrections of the\n * MSSM to the Standard Model or the Split-MSSM from arXiv:1407.4081.\n *\n * Example for matching of the MSSM to the Standard Model:\n@code\n   Parameters pars;\n   // fill parameters ...\n\n   double lambda = lambda_tree_level(pars);\n\n   if (loopLevel > 0) {\n      lambda +=\n         + delta_lambda_1loop_reg(pars)\n         + delta_lambda_1loop_phi(pars)\n         + delta_lambda_1loop_chi_1(pars)\n         + delta_lambda_1loop_chi_2(pars);\n   }\n\n   if (loopLevel > 1)\n      lambda += delta_lambda_2loop_phi_HSS(pars);\n@endcode\n *\n * Example for matching of the MSSM to the Split-MSSM:\n@code\n   Parameters pars;\n   // fill parameters ...\n   // Note: g1 and g2 are defined in the Split-MSSM\n\n   double lambda_split = lambda_tree_level(pars);\n   double gYu = gYu_tree_level(pars);\n   double gYd = gYd_tree_level(pars);\n   double g2u = g2u_tree_level(pars);\n   double g2d = g2d_tree_level(pars);\n\n   if (loopLevel > 0) {\n      lambda_split +=\n         + delta_lambda_1loop_reg(pars)\n         + delta_lambda_1loop_phi(pars);\n      gYu += delta_gYu_1loop(pars);\n      gYd += delta_gYd_1loop(pars);\n      g2u += delta_g2u_1loop(pars);\n      g2d += delta_g2d_1loop(pars);\n   }\n\n   if (loopLevel > 1)\n      lambda_split += delta_lambda_2loop_phi(pars);\n@endcode\n *\n * Example for matching of the Split-MSSM to the Standard Model:\n@code\n   Parameters pars;\n   // fill parameters ...\n   // Note: parameters are defined in the Split-MSSM\n\n   double lambda_SM = lambda_split;\n\n   if (loopLevel > 0) {\n      lambda_SM += delta_lambda_1loop_chi_1(\n         scale, mu, lambda_split, gYu, gYd, g2u, g2d, m1, m2);\n   }\n@endcode\n */\n\nnamespace flexiblesusy {\nnamespace splitmssm_thresholds {\n\n/**\n * @class Parameters\n * @brief Parameters for MSSM threshold corrections to the SM or Split-MSSM\n *\n * Contains the running MS-bar parameters of the EFT (either the SM or\n * the Split-MSSM) and the runnign DR-bar parameters of the MSSM.  See\n * arXiv:1407.4081 for the parameter definition.\n */\nstruct Parameters {\n   double g1{0.}, g2{0.}, g3{0.}; ///< MS-bar gauge couplings in the EFT (GUT normalized)\n   double gt{0.};          ///< MS-bar top Yukawa coupling of the SM or Split-MSSM\n   double At{0.};          ///< DR-bar trilinear coupling for the stops in the MSSM\n   double mu{0.};          ///< bilinear Higgsino coupling\n   double mA{0.};          ///< mass of the heavy Higgs doublett\n   double m1{0.};          ///< bino mass parameter\n   double m2{0.};          ///< wino mass parameter\n   double tan_beta{0.};    ///< mixing angle of the heavy Higgs doublett in the MSSM\n   double scale{0.};       ///< renormalization scale\n   Eigen::Matrix<double,3,3> mq2{Eigen::Matrix<double,3,3>::Zero()}; ///< DR-bar squared soft-breaking left-handed squark mass parameters in the MSSM\n   Eigen::Matrix<double,3,3> mu2{Eigen::Matrix<double,3,3>::Zero()}; ///< DR-bar squared soft-breaking right-handed up-squark mass parameters in the MSSM\n   Eigen::Matrix<double,3,3> md2{Eigen::Matrix<double,3,3>::Zero()}; ///< DR-bar squared soft-breaking right-handed down-squark mass parameters in the MSSM\n   Eigen::Matrix<double,3,3> ml2{Eigen::Matrix<double,3,3>::Zero()}; ///< DR-bar squared soft-breaking left-handed selectron mass parameters in the MSSM\n   Eigen::Matrix<double,3,3> me2{Eigen::Matrix<double,3,3>::Zero()}; ///< DR-bar squared soft-breaking right-handed selectron mass parameters in the MSSM\n};\n\nstd::ostream& operator<<(std::ostream&, const Parameters&);\n\ndouble lambda_tree_level(const Parameters&);\ndouble gYu_tree_level(const Parameters&);\ndouble gYd_tree_level(const Parameters&);\ndouble g2u_tree_level(const Parameters&);\ndouble g2d_tree_level(const Parameters&);\n\ndouble delta_lambda_1loop_reg(const Parameters&);\ndouble delta_lambda_1loop_phi(const Parameters&);\ndouble delta_lambda_1loop_chi_1(const Parameters&);\ndouble delta_lambda_1loop_chi_1(\n   double scale, double mu, double lambda, double gYu, double gYd,\n   double g2u, double g2d, double m1, double m2);\ndouble delta_lambda_1loop_chi_2(const Parameters&);\ndouble delta_lambda_1loop_chi_2(\n   double scale, double mu, double m2, double g1, double g2, double tan_beta);\ndouble delta_lambda_2loop_phi(const Parameters&);\ndouble delta_lambda_2loop_phi_HSS(const Parameters&);\ndouble delta_gYu_1loop(const Parameters&);\ndouble delta_gYd_1loop(const Parameters&);\ndouble delta_g2u_1loop(const Parameters&);\ndouble delta_g2d_1loop(const Parameters&);\ndouble delta_gt_1loop_chi(\n   double scale, double mu, double gYu, double gYd,\n   double g2u, double g2d, double m1, double m2);\ndouble delta_m2_1loop_chi(const Parameters&);\n\n} // namespace splitmssm_thresholds\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "ff46d999c0519b8adba056e67101bc0b2bf13aac", "size": 5695, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/src/splitmssm_thresholds.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/splitmssm_thresholds.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/splitmssm_thresholds.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": 37.9666666667, "max_line_length": 155, "alphanum_fraction": 0.6971027217, "num_tokens": 1529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2700309137539975}}
{"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// Test real concept.\n\n// real_concept is an archetype for User defined Real types.\n\n// This file defines the features, constructors, operators, functions...\n// that are essential to use mathematical and statistical functions.\n// The template typename \"RealType\" is used where this type\n// (as well as the normal built-in types, float, double & long double)\n// can be used.\n// That this is the minimum set is confirmed by use as a type\n// in tests of all functions & distributions, for example:\n//   test_spots(0.F); & test_spots(0.);  for float and double, but also\n//   test_spots(boost::math::concepts::real_concept(0.));\n// NTL quad_float type is an example of a type meeting the requirements,\n// but note minor additions are needed - see ntl.diff and documentation\n// \"Using With NTL - a High-Precision Floating-Point Library\".\n\n#ifndef BOOST_MATH_REAL_CONCEPT_HPP\n#define BOOST_MATH_REAL_CONCEPT_HPP\n\n#include <boost/config.hpp>\n#include <boost/limits.hpp>\n#include <boost/math/special_functions/round.hpp>\n#include <boost/math/special_functions/trunc.hpp>\n#include <boost/math/special_functions/modf.hpp>\n#include <boost/math/tools/big_constant.hpp>\n#include <boost/math/tools/precision.hpp>\n#include <boost/math/policies/policy.hpp>\n#include <boost/math/special_functions/asinh.hpp>\n#include <boost/math/special_functions/atanh.hpp>\n#if defined(__SGI_STL_PORT)\n#  include <boost/math/tools/real_cast.hpp>\n#endif\n#include <ostream>\n#include <istream>\n#include <boost/config/no_tr1/cmath.hpp>\n#include <math.h> // fmodl\n\n#if defined(__SGI_STL_PORT) || defined(_RWSTD_VER) || defined(__LIBCOMO__)\n#  include <cstdio>\n#endif\n\nnamespace boost{ namespace math{\n\nnamespace concepts\n{\n\n#ifdef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   typedef double real_concept_base_type;\n#else\n   typedef long double real_concept_base_type;\n#endif\n\nclass real_concept\n{\npublic:\n   // Constructors:\n   real_concept() : m_value(0){}\n   real_concept(char c) : m_value(c){}\n#ifndef BOOST_NO_INTRINSIC_WCHAR_T\n   real_concept(wchar_t c) : m_value(c){}\n#endif\n   real_concept(unsigned char c) : m_value(c){}\n   real_concept(signed char c) : m_value(c){}\n   real_concept(unsigned short c) : m_value(c){}\n   real_concept(short c) : m_value(c){}\n   real_concept(unsigned int c) : m_value(c){}\n   real_concept(int c) : m_value(c){}\n   real_concept(unsigned long c) : m_value(c){}\n   real_concept(long c) : m_value(c){}\n#if defined(__DECCXX) || defined(__SUNPRO_CC)\n   real_concept(unsigned long long c) : m_value(static_cast<real_concept_base_type>(c)){}\n   real_concept(long long c) : m_value(static_cast<real_concept_base_type>(c)){}\n#elif defined(BOOST_HAS_LONG_LONG)\n   real_concept(boost::ulong_long_type c) : m_value(static_cast<real_concept_base_type>(c)){}\n   real_concept(boost::long_long_type c) : m_value(static_cast<real_concept_base_type>(c)){}\n#elif defined(BOOST_HAS_MS_INT64)\n   real_concept(unsigned __int64 c) : m_value(static_cast<real_concept_base_type>(c)){}\n   real_concept(__int64 c) : m_value(static_cast<real_concept_base_type>(c)){}\n#endif\n   real_concept(float c) : m_value(c){}\n   real_concept(double c) : m_value(c){}\n   real_concept(long double c) : m_value(c){}\n#ifdef BOOST_MATH_USE_FLOAT128\n   real_concept(BOOST_MATH_FLOAT128_TYPE c) : m_value(c){}\n#endif\n\n   // Assignment:\n   real_concept& operator=(char c) { m_value = c; return *this; }\n   real_concept& operator=(unsigned char c) { m_value = c; return *this; }\n   real_concept& operator=(signed char c) { m_value = c; return *this; }\n#ifndef BOOST_NO_INTRINSIC_WCHAR_T\n   real_concept& operator=(wchar_t c) { m_value = c; return *this; }\n#endif\n   real_concept& operator=(short c) { m_value = c; return *this; }\n   real_concept& operator=(unsigned short c) { m_value = c; return *this; }\n   real_concept& operator=(int c) { m_value = c; return *this; }\n   real_concept& operator=(unsigned int c) { m_value = c; return *this; }\n   real_concept& operator=(long c) { m_value = c; return *this; }\n   real_concept& operator=(unsigned long c) { m_value = c; return *this; }\n#ifdef BOOST_HAS_LONG_LONG\n   real_concept& operator=(boost::long_long_type c) { m_value = static_cast<real_concept_base_type>(c); return *this; }\n   real_concept& operator=(boost::ulong_long_type c) { m_value = static_cast<real_concept_base_type>(c); return *this; }\n#endif\n   real_concept& operator=(float c) { m_value = c; return *this; }\n   real_concept& operator=(double c) { m_value = c; return *this; }\n   real_concept& operator=(long double c) { m_value = c; return *this; }\n\n   // Access:\n   real_concept_base_type value()const{ return m_value; }\n\n   // Member arithmetic:\n   real_concept& operator+=(const real_concept& other)\n   { m_value += other.value(); return *this; }\n   real_concept& operator-=(const real_concept& other)\n   { m_value -= other.value(); return *this; }\n   real_concept& operator*=(const real_concept& other)\n   { m_value *= other.value(); return *this; }\n   real_concept& operator/=(const real_concept& other)\n   { m_value /= other.value(); return *this; }\n   real_concept operator-()const\n   { return -m_value; }\n   real_concept const& operator+()const\n   { return *this; }\n   real_concept& operator++()\n   { ++m_value;  return *this; }\n   real_concept& operator--()\n   { --m_value;  return *this; }\n\nprivate:\n   real_concept_base_type m_value;\n};\n\n// Non-member arithmetic:\ninline real_concept operator+(const real_concept& a, const real_concept& b)\n{\n   real_concept result(a);\n   result += b;\n   return result;\n}\ninline real_concept operator-(const real_concept& a, const real_concept& b)\n{\n   real_concept result(a);\n   result -= b;\n   return result;\n}\ninline real_concept operator*(const real_concept& a, const real_concept& b)\n{\n   real_concept result(a);\n   result *= b;\n   return result;\n}\ninline real_concept operator/(const real_concept& a, const real_concept& b)\n{\n   real_concept result(a);\n   result /= b;\n   return result;\n}\n\n// Comparison:\ninline bool operator == (const real_concept& a, const real_concept& b)\n{ return a.value() == b.value(); }\ninline bool operator != (const real_concept& a, const real_concept& b)\n{ return a.value() != b.value();}\ninline bool operator < (const real_concept& a, const real_concept& b)\n{ return a.value() < b.value(); }\ninline bool operator <= (const real_concept& a, const real_concept& b)\n{ return a.value() <= b.value(); }\ninline bool operator > (const real_concept& a, const real_concept& b)\n{ return a.value() > b.value(); }\ninline bool operator >= (const real_concept& a, const real_concept& b)\n{ return a.value() >= b.value(); }\n\n// Non-member functions:\ninline real_concept acos(real_concept a)\n{ return std::acos(a.value()); }\ninline real_concept cos(real_concept a)\n{ return std::cos(a.value()); }\ninline real_concept asin(real_concept a)\n{ return std::asin(a.value()); }\ninline real_concept atan(real_concept a)\n{ return std::atan(a.value()); }\ninline real_concept atan2(real_concept a, real_concept b)\n{ return std::atan2(a.value(), b.value()); }\ninline real_concept ceil(real_concept a)\n{ return std::ceil(a.value()); }\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n// I've seen std::fmod(long double) crash on some platforms\n// so use fmodl instead:\n#ifdef _WIN32_WCE\n//\n// Ugly workaround for macro fmodl:\n//\ninline long double call_fmodl(long double a, long double b)\n{  return fmodl(a, b); }\ninline real_concept fmod(real_concept a, real_concept b)\n{ return call_fmodl(a.value(), b.value()); }\n#else\ninline real_concept fmod(real_concept a, real_concept b)\n{ return fmodl(a.value(), b.value()); }\n#endif\n#endif\ninline real_concept cosh(real_concept a)\n{ return std::cosh(a.value()); }\ninline real_concept exp(real_concept a)\n{ return std::exp(a.value()); }\ninline real_concept fabs(real_concept a)\n{ return std::fabs(a.value()); }\ninline real_concept abs(real_concept a)\n{ return std::abs(a.value()); }\ninline real_concept floor(real_concept a)\n{ return std::floor(a.value()); }\ninline real_concept modf(real_concept a, real_concept* ipart)\n{\n#ifdef __MINGW32__\n   real_concept_base_type ip;\n   real_concept_base_type result = boost::math::modf(a.value(), &ip);\n   *ipart = ip;\n   return result;\n#else\n   real_concept_base_type ip;\n   real_concept_base_type result = std::modf(a.value(), &ip);\n   *ipart = ip;\n   return result;\n#endif\n}\ninline real_concept frexp(real_concept a, int* expon)\n{ return std::frexp(a.value(), expon); }\ninline real_concept ldexp(real_concept a, int expon)\n{ return std::ldexp(a.value(), expon); }\ninline real_concept log(real_concept a)\n{ return std::log(a.value()); }\ninline real_concept log10(real_concept a)\n{ return std::log10(a.value()); }\ninline real_concept tan(real_concept a)\n{ return std::tan(a.value()); }\ninline real_concept pow(real_concept a, real_concept b)\n{ return std::pow(a.value(), b.value()); }\n#if !defined(__SUNPRO_CC)\ninline real_concept pow(real_concept a, int b)\n{ return std::pow(a.value(), b); }\n#else\ninline real_concept pow(real_concept a, int b)\n{ return std::pow(a.value(), static_cast<real_concept_base_type>(b)); }\n#endif\ninline real_concept sin(real_concept a)\n{ return std::sin(a.value()); }\ninline real_concept sinh(real_concept a)\n{ return std::sinh(a.value()); }\ninline real_concept sqrt(real_concept a)\n{ return std::sqrt(a.value()); }\ninline real_concept tanh(real_concept a)\n{ return std::tanh(a.value()); }\n\n//\n// C++11 ism's\n// Note that these must not actually call the std:: versions as that precludes using this\n// header to test in C++03 mode, call the Boost versions instead:\n//\ninline boost::math::concepts::real_concept asinh(boost::math::concepts::real_concept a)\n{\n   return boost::math::asinh(a.value(), boost::math::policies::make_policy(boost::math::policies::overflow_error<boost::math::policies::ignore_error>()));\n}\ninline boost::math::concepts::real_concept acosh(boost::math::concepts::real_concept a)\n{\n   return boost::math::acosh(a.value(), boost::math::policies::make_policy(boost::math::policies::overflow_error<boost::math::policies::ignore_error>()));\n}\ninline boost::math::concepts::real_concept atanh(boost::math::concepts::real_concept a)\n{\n   return boost::math::atanh(a.value(), boost::math::policies::make_policy(boost::math::policies::overflow_error<boost::math::policies::ignore_error>()));\n}\n\n//\n// Conversion and truncation routines:\n//\ntemplate <class Policy>\ninline int iround(const concepts::real_concept& v, const Policy& pol)\n{ return boost::math::iround(v.value(), pol); }\ninline int iround(const concepts::real_concept& v)\n{ return boost::math::iround(v.value(), policies::policy<>()); }\ntemplate <class Policy>\ninline long lround(const concepts::real_concept& v, const Policy& pol)\n{ return boost::math::lround(v.value(), pol); }\ninline long lround(const concepts::real_concept& v)\n{ return boost::math::lround(v.value(), policies::policy<>()); }\n\n#ifdef BOOST_HAS_LONG_LONG\ntemplate <class Policy>\ninline boost::long_long_type llround(const concepts::real_concept& v, const Policy& pol)\n{ return boost::math::llround(v.value(), pol); }\ninline boost::long_long_type llround(const concepts::real_concept& v)\n{ return boost::math::llround(v.value(), policies::policy<>()); }\n#endif\n\ntemplate <class Policy>\ninline int itrunc(const concepts::real_concept& v, const Policy& pol)\n{ return boost::math::itrunc(v.value(), pol); }\ninline int itrunc(const concepts::real_concept& v)\n{ return boost::math::itrunc(v.value(), policies::policy<>()); }\ntemplate <class Policy>\ninline long ltrunc(const concepts::real_concept& v, const Policy& pol)\n{ return boost::math::ltrunc(v.value(), pol); }\ninline long ltrunc(const concepts::real_concept& v)\n{ return boost::math::ltrunc(v.value(), policies::policy<>()); }\n\n#ifdef BOOST_HAS_LONG_LONG\ntemplate <class Policy>\ninline boost::long_long_type lltrunc(const concepts::real_concept& v, const Policy& pol)\n{ return boost::math::lltrunc(v.value(), pol); }\ninline boost::long_long_type lltrunc(const concepts::real_concept& v)\n{ return boost::math::lltrunc(v.value(), policies::policy<>()); }\n#endif\n\n// Streaming:\ntemplate <class charT, class traits>\ninline std::basic_ostream<charT, traits>& operator<<(std::basic_ostream<charT, traits>& os, const real_concept& a)\n{\n   return os << a.value();\n}\ntemplate <class charT, class traits>\ninline std::basic_istream<charT, traits>& operator>>(std::basic_istream<charT, traits>& is, real_concept& a)\n{\n   real_concept_base_type v;\n   is >> v;\n   a = v;\n   return is;\n}\n\n} // namespace concepts\n\nnamespace tools\n{\n\ntemplate <>\ninline concepts::real_concept make_big_value<concepts::real_concept>(boost::math::tools::largest_float val, const char* , std::false_type const&, std::false_type const&)\n{\n   return val;  // Can't use lexical_cast here, sometimes it fails....\n}\n\ntemplate <>\ninline concepts::real_concept max_value<concepts::real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::real_concept))\n{\n   return max_value<concepts::real_concept_base_type>();\n}\n\ntemplate <>\ninline concepts::real_concept min_value<concepts::real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::real_concept))\n{\n   return min_value<concepts::real_concept_base_type>();\n}\n\ntemplate <>\ninline concepts::real_concept log_max_value<concepts::real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::real_concept))\n{\n   return log_max_value<concepts::real_concept_base_type>();\n}\n\ntemplate <>\ninline concepts::real_concept log_min_value<concepts::real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::real_concept))\n{\n   return log_min_value<concepts::real_concept_base_type>();\n}\n\ntemplate <>\ninline concepts::real_concept epsilon<concepts::real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::real_concept))\n{\n#ifdef __SUNPRO_CC\n   return std::numeric_limits<concepts::real_concept_base_type>::epsilon();\n#else\n   return tools::epsilon<concepts::real_concept_base_type>();\n#endif\n}\n\ntemplate <>\ninline BOOST_MATH_CONSTEXPR int digits<concepts::real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::real_concept)) BOOST_NOEXCEPT\n{\n   // Assume number of significand bits is same as real_concept_base_type,\n   // unless std::numeric_limits<T>::is_specialized to provide digits.\n   return tools::digits<concepts::real_concept_base_type>();\n   // Note that if numeric_limits real concept is NOT specialized to provide digits10\n   // (or max_digits10) then the default precision of 6 decimal digits will be used\n   // by Boost test (giving misleading error messages like\n   // \"difference between {9.79796} and {9.79796} exceeds 5.42101e-19%\"\n   // and by Boost lexical cast and serialization causing loss of accuracy.\n}\n\n} // namespace tools\n} // namespace math\n} // namespace boost\n\n#endif // BOOST_MATH_REAL_CONCEPT_HPP\n\n\n", "meta": {"hexsha": "f6dcce4f86d961891301006918b09db27010e382", "size": 14910, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/concepts/real_concept.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": 310.0, "max_stars_repo_stars_event_min_datetime": "2017-02-02T09:14:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T06:50:11.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/concepts/real_concept.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": 61.0, "max_issues_repo_issues_event_min_datetime": "2017-01-22T20:35:25.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-13T14:48:46.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/concepts/real_concept.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": 54.0, "max_forks_repo_forks_event_min_datetime": "2017-03-02T06:55:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T01:12:20.000Z", "avg_line_length": 37.3684210526, "max_line_length": 169, "alphanum_fraction": 0.7350100604, "num_tokens": 3961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2698859562062589}}
{"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#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"kindr/common/common.hpp\"\n#include \"kindr/common/assert_macros_eigen.hpp\"\n#include \"kindr/vectors/VectorBase.hpp\"\n#include \"kindr/phys_quant/PhysicalType.hpp\"\n\nnamespace kindr {\n\n/*! \\class Vector\n * \\brief Vector in n-dimensional-space.\n *\n * This class implements a vector in n-dimensional-space.\n * More precisely an interface to store and access the coordinates of a vector of a point in n-dimensional-space is provided.\n * \\tparam PhysicalType_    Physical type of the vector.\n * \\tparam PrimType_        Primitive type of the coordinates.\n * \\tparam Dimension_       Dimension of the vector.\n * \\ingroup vectors\n */\ntemplate<enum PhysicalType PhysicalType_, typename PrimType_, int Dimension_>\nclass Vector : public VectorBase<Vector<PhysicalType_, PrimType_, Dimension_> >, private Eigen::Matrix<PrimType_, Dimension_, 1> {\n private:\n  /*! \\brief The base type.\n   */\n  typedef VectorBase<Vector<PhysicalType_, PrimType_, Dimension_> > Base;\n\n  /*! \\brief The size if the vector has dynamic dimension (must be equal to Eigen::Dynamic).\n   */\n  static constexpr int DynamicDimension = -1;\n\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  /*! \\brief The implementation type.\n   *\n   *  The implementation type is always an Eigen object.\n   */\n  typedef Eigen::Matrix<PrimType_, Dimension_, 1> Implementation;\n\n  /*! \\brief The primitive type of the coordinates.\n   */\n  typedef PrimType_ Scalar;\n\n  /*! \\brief The dimension of the vector.\n   */\n  static constexpr int Dimension = Dimension_;\n\n  /*! \\brief Default constructor for static sized vectors which initializes all components with zero.\n   */\n  template<int DimensionCopy_ = Dimension_>\n  Vector(typename std::enable_if<DimensionCopy_ != DynamicDimension>::type* = nullptr)\n    : Implementation(Implementation::Zero()) {\n  }\n\n  /*! \\brief Default constructor for dynamic sized vectors.\n   */\n  template<int DimensionCopy_ = Dimension_>\n  Vector(typename std::enable_if<DimensionCopy_ == DynamicDimension>::type* = nullptr)\n    : Implementation() {\n  }\n\n  /*! \\brief Constructor using other vector with generic type.\n   *  \\param other   Vector<OtherPhysicalType_, OtherPrimType_, Dimension_>\n   */\n  template<enum PhysicalType OtherPhysicalType_, typename OtherPrimType_>\n  explicit Vector(const Vector<OtherPhysicalType_, OtherPrimType_, Dimension_>& other)\n    : Implementation(other.toImplementation().template cast<PrimType_>()) {\n  }\n\n  /*! \\brief Constructor of a dynamic vector using a static vector.\n   *  \\param other   Vector<OtherPhysicalType_, OtherPrimType_, Dimension_>\n   */\n  template<int DimensionOther_, int DimensionCopy_ = Dimension_>\n  Vector(const Vector<PhysicalType_, PrimType_, DimensionOther_>& other, typename std::enable_if<DimensionCopy_ == DynamicDimension>::type* = nullptr)\n    : Implementation(other.toImplementation()) {\n  }\n\n  /*! \\brief Constructor using Eigen::Matrix.\n   *  \\param other   Eigen::Matrix<PrimType_,Dimension_,1>\n   */\n  explicit Vector(const Implementation& other)\n    : Implementation(other) {\n  }\n\n  /*! \\brief Constructor using three scalars.\n   *  \\param x x-Component\n   *  \\param y y-Component\n   *  \\param z z-Component\n   */\n  template<int DimensionCopy_ = Dimension_>\n  Vector(Scalar x, Scalar y, Scalar z, typename std::enable_if<DimensionCopy_ == 3>::type* = nullptr)\n    : Implementation(x,y,z) {\n  }\n\n  /*! \\brief Get zero element.\n   * \\returns zero element\n   */\n  static Vector<PhysicalType_, PrimType_, Dimension_> Zero() {\n    return Vector<PhysicalType_, PrimType_, Dimension_>(Implementation::Zero());\n  }\n\n  /*! \\brief Sets all components of the vector to zero.\n   * \\returns reference\n   */\n  Vector<PhysicalType_, PrimType_, Dimension_>& setZero() {\n    Implementation::setZero();\n    return *this;\n  }\n\n  /*! \\brief Get random element.\n   * \\returns random element\n   */\n  static Vector<PhysicalType_, PrimType_, Dimension_> Random() {\n    return Vector<PhysicalType_, PrimType_, Dimension_>(Implementation::Random());\n  }\n\n  /*! \\brief Sets all components of the vector to random.\n   * \\returns reference\n   */\n  Vector<PhysicalType_, PrimType_, Dimension_>& setRandom() {\n    Implementation::setRandom();\n    return *this;\n  }\n\n  /*! \\brief Get the unity vector in x.\n   * \\returns the unity vector in x\n   */\n  static Vector<PhysicalType_, PrimType_, Dimension_> UnitX() {\n    return Vector<PhysicalType_, PrimType_, Dimension_>(Implementation::UnitX());\n  }\n\n  /*! \\brief Get the unity vector in y.\n   * \\returns the unity vector in y\n   */\n  static Vector<PhysicalType_, PrimType_, Dimension_> UnitY() {\n    return Vector<PhysicalType_, PrimType_, Dimension_>(Implementation::UnitY());\n  }\n\n  /*! \\brief Get the unity vector in z.\n   * \\returns the unity vector in z\n   */\n  static Vector<PhysicalType_, PrimType_, Dimension_> UnitZ() {\n    return Vector<PhysicalType_, PrimType_, Dimension_>(Implementation::UnitZ());\n  }\n\n  /*! \\brief Set values.\n   */\n  using Implementation::operator<<;\n\n  /*! \\brief Get/set values.\n   */\n  using Implementation::operator();\n\n  /*!\\brief Get the head of the vector (copy)\n   * \\returns the head of the vector (copy)\n   */\n  template<int DimensionOutput_>\n  Vector<PhysicalType_, PrimType_, DimensionOutput_> getHead() const {\n    return Vector<PhysicalType_, PrimType_, DimensionOutput_>(this->toImplementation().template head<DimensionOutput_>());\n  }\n\n  /*!\\brief Get the head of the vector (copy)\n   * \\returns the head of the vector (copy)\n   */\n  Vector<PhysicalType_, PrimType_, DynamicDimension> getHead(int length) const {\n    return Vector<PhysicalType_, PrimType_, DynamicDimension>(this->toImplementation().head(length));\n  }\n\n  /*!\\brief Get the tail of the vector (copy)\n   * \\returns the tail of the vector (copy)\n   */\n  template<int DimensionOutput_>\n  Vector<PhysicalType_, PrimType_, DimensionOutput_> getTail() const {\n    return Vector<PhysicalType_, PrimType_, DimensionOutput_>(this->toImplementation().template tail<DimensionOutput_>());\n  }\n\n  /*!\\brief Get the tail of the vector (copy)\n   * \\returns the tail of the vector (copy)\n   */\n  Vector<PhysicalType_, PrimType_, DynamicDimension> getTail(int length) const {\n    return Vector<PhysicalType_, PrimType_, DynamicDimension>(this->toImplementation().tail(length));\n  }\n\n  /*!\\brief Get a segment of the vector (copy)\n   * \\returns a segment of the vector (copy)\n   */\n  template<int DimensionOutput_>\n  Vector<PhysicalType_, PrimType_, DimensionOutput_> getSegment(int start) const {\n    return Vector<PhysicalType_, PrimType_, DimensionOutput_>(this->toImplementation().template segment<DimensionOutput_>(start));\n  }\n\n  /*!\\brief Get a segment of the vector (copy)\n   * \\returns a segment of the vector (copy)\n   */\n  Vector<PhysicalType_, PrimType_, DynamicDimension> getSegment(int start, int length) const {\n    return Vector<PhysicalType_, PrimType_, DynamicDimension>(this->toImplementation().segment(start, length));\n  }\n\n  /*!\\brief Set the head of the vector\n   */\n  template<int DimensionInput_>\n  void setHead(const Vector<PhysicalType_, PrimType_, DimensionInput_> & input) {\n    this->toImplementation().template head<DimensionInput_>() = input.toImplementation();\n  }\n\n  /*!\\brief Set the tail of the vector\n   */\n  template<int DimensionInput_>\n  void setTail(const Vector<PhysicalType_, PrimType_, DimensionInput_> & input) {\n    this->toImplementation().template tail<DimensionInput_>() = input.toImplementation();\n  }\n\n  /*!\\brief Set a segment of the vector\n   */\n  template<int DimensionInput_>\n  void setSegment(int start, const Vector<PhysicalType_, PrimType_, DimensionInput_> & input) {\n    this->toImplementation().template segment<DimensionInput_>(start) = input.toImplementation();\n  }\n\n  /*!\\brief Get x-coordinate of the vector (copy)\n   * \\returns the x-coordinate of the vector (copy)\n   */\n  template<int DimensionCopy_ = Dimension_>\n  Scalar x(typename std::enable_if<DimensionCopy_ == 3>::type* = nullptr) const {\n    return this->toImplementation().x();\n  }\n\n  /*!\\brief Get x-coordinate of the vector (reference)\n   * \\returns the x-coordinate of the vector (reference)\n   */\n  template<int DimensionCopy_ = Dimension_>\n  Scalar& x(typename std::enable_if<DimensionCopy_ == 3>::type* = nullptr) {\n    return this->toImplementation().x();\n  }\n\n  /*!\\brief Get y-coordinate of the vector (copy)\n   * \\returns the y-coordinate of the vector (copy)\n   */\n  template<int DimensionCopy_ = Dimension_>\n  Scalar y(typename std::enable_if<DimensionCopy_ == 3>::type* = nullptr) const {\n    return this->toImplementation().y();\n  }\n\n  /*!\\brief Get y-coordinate of the vector (reference)\n   * \\returns the y-coordinate of the vector (reference)\n   */\n  template<int DimensionCopy_ = Dimension_>\n  Scalar& y(typename std::enable_if<DimensionCopy_ == 3>::type* = nullptr) {\n    return this->toImplementation().y();\n  }\n\n  /*!\\brief Get z-coordinate of the vector (copy)\n   * \\returns the z-coordinate of the vector (copy)\n   */\n  template<int DimensionCopy_ = Dimension_>\n  Scalar z(typename std::enable_if<DimensionCopy_ == 3>::type* = nullptr) const {\n    return this->toImplementation().z();\n  }\n\n  /*!\\brief Get z-coordinate of the vector (reference)\n   * \\returns the z-coordinate of the vector (reference)\n   */\n  template<int DimensionCopy_ = Dimension_>\n  Scalar& z(typename std::enable_if<DimensionCopy_ == 3>::type* = nullptr) {\n    return this->toImplementation().z();\n  }\n\n  /*! \\brief Cast to the implementation type.\n   *  \\returns the implementation (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 (recommended only for advanced users)\n   */\n  inline const Implementation& toImplementation() const {\n    return static_cast<const Implementation&>(*this);\n  }\n\n  /*! \\brief Cast to Eigen::Matrix<PrimType_, Dimension_, 1>.\n   *  \\returns Eigen::Matrix<PrimType_, Dimension_, 1>\n   */\n  inline Implementation& vector() {\n    return static_cast<Implementation&>(*this);\n  }\n\n  /*! \\brief Cast to Eigen::Matrix<PrimType_, Dimension_, 1>.\n   *  \\returns Eigen::Matrix<PrimType_, Dimension_, 1>\n   */\n  inline const Implementation& vector() const {\n    return static_cast<const Implementation&>(*this);\n  }\n\n  /*! \\brief Assignment operator.\n   * \\param other   other vector\n   * \\returns reference\n   */\n  Vector<PhysicalType_, PrimType_, Dimension_> & operator=(const Vector<PhysicalType_, PrimType_, Dimension_>& other) { // (The assignment of a static to a dynamic vector does not work because the amount of parameters must be one and SFINAE leads to two parameters. Workaround: cast the static vector into a dynamic one, then assign.)\n    this->toImplementation() = other.toImplementation();\n    return *this;\n  }\n\n  /*! \\brief Addition of two vectors.\n   * \\param other   other vector\n   * \\returns sum\n   */\n  Vector<PhysicalType_, PrimType_, Dimension_> operator+(const Vector<PhysicalType_, PrimType_, Dimension_>& other) const {\n    return Vector<PhysicalType_, PrimType_, Dimension_>(this->toImplementation() + other.toImplementation());\n  }\n\n  /*! \\brief Subtraction of two vectors.\n   * \\param other   other vector\n   * \\returns difference\n   */\n  Vector<PhysicalType_, PrimType_, Dimension_> operator-(const Vector<PhysicalType_, PrimType_, Dimension_>& other) const {\n    return Vector<PhysicalType_, PrimType_, Dimension_>(this->toImplementation() - other.toImplementation());\n  }\n\n  /*! \\brief Multiplies vector with a scalar.\n   * \\param factor   factor\n   * \\returns product\n   */\n  template<typename PrimTypeFactor_>\n  Vector<PhysicalType_, PrimType_, Dimension_> operator*(PrimTypeFactor_ factor) const {\n    return Vector<PhysicalType_, PrimType_, Dimension_>(this->toImplementation()*(PrimType_)factor);\n  }\n\n  /*! \\brief Divides vector by a scalar.\n   * \\param divisor   divisor\n   * \\returns quotient\n   */\n  template<typename PrimTypeDivisor_>\n  Vector<PhysicalType_, PrimType_, Dimension_> operator/(PrimTypeDivisor_ divisor) const {\n    return Vector<PhysicalType_, PrimType_, Dimension_>(this->toImplementation()/(PrimType_)divisor);\n  }\n\n  /*! \\brief Addition and assignment of two vectors.\n   * \\param other   other vector\n   * \\returns reference\n   */\n  Vector<PhysicalType_, PrimType_, Dimension_>& operator+=(const Vector<PhysicalType_, PrimType_, Dimension_>& other) {\n    this->toImplementation() += other.toImplementation();\n    return *this;\n  }\n\n  /*! \\brief Subtraction and assignment of two vectors.\n   * \\param other   other vector\n   * \\returns reference\n   */\n  Vector<PhysicalType_, PrimType_, Dimension_>& operator-=(const Vector<PhysicalType_, PrimType_, Dimension_>& other) {\n    this->toImplementation() -= other.toImplementation();\n    return *this;\n  }\n\n  /*! \\brief Multiplication with a scalar and assignment.\n   * \\param factor   factor\n   * \\returns reference\n   */\n  template<typename PrimTypeFactor_>\n  Vector<PhysicalType_, PrimType_, Dimension_>& operator*=(PrimTypeFactor_ factor) {\n    this->toImplementation() *= (PrimType_)factor;\n    return *this;\n  }\n\n  /*! \\brief Division by a scalar and assignment.\n   * \\param divisor   divisor\n   * \\returns reference\n   */\n  template<typename PrimTypeDivisor_>\n  Vector<PhysicalType_, PrimType_, Dimension_>& operator/=(PrimTypeDivisor_ divisor) {\n    this->toImplementation() /= (PrimType_)divisor;\n    return *this;\n  }\n\n  /*! \\brief Negation of a vector.\n   * \\returns negative vector\n   */\n  Vector<PhysicalType_, PrimType_, Dimension_> operator-() const {\n    return Vector<PhysicalType_, PrimType_, Dimension_>(-this->toImplementation());\n  }\n\n  /*! \\brief Comparison operator.\n   * \\param other   other vector\n   * \\returns true if equal\n   */\n  bool operator==(const Vector<PhysicalType_, PrimType_, Dimension_>& other) const {\n    return this->toImplementation() == other.toImplementation();\n  }\n\n  /*! \\brief Comparison operator.\n   * \\param other   other vector\n   * \\returns true if unequal\n   */\n  bool operator!=(const Vector<PhysicalType_, PrimType_, Dimension_>& other) const {\n    return this->toImplementation() != other.toImplementation();\n  }\n\n  /*! \\brief Comparison function.\n   * \\param other   other vector\n   * \\param tol   tolerance\n   * \\returns true if similar within tolerance\n   */\n  bool isSimilarTo(const Vector<PhysicalType_, PrimType_, Dimension_>& other, Scalar tol) const {\n    if((*this - other).abs().max() < tol) {\n      return true;\n    } else {\n      return false;\n    }\n  }\n\n  /*! \\brief Norm of the vector.\n   *  \\returns norm.\n   */\n  Scalar norm() const {\n    return this->toImplementation().norm();\n  }\n\n  /*! \\brief Squared norm of the vector.\n   *  \\returns norm.\n   */\n  Scalar squaredNorm() const {\n    return this->toImplementation().squaredNorm();\n  }\n\n  /*! \\brief Normalizes the vector.\n   *  \\returns reference.\n   */\n  Vector<PhysicalType_, PrimType_, Dimension_>& normalize() {\n    this->toImplementation().normalize();\n    return *this;\n  }\n\n  /*! \\brief Get a normalized version of the vector.\n   *  \\returns normalized vector.\n   */\n  Vector<PhysicalType_, PrimType_, Dimension_> normalized() const {\n    return Vector<PhysicalType_, PrimType_, Dimension_>(this->toImplementation().normalized());\n  }\n\n  /*! \\brief Dot product with other vector.\n   *  \\param other   other vector\n   *  \\returns dot product.\n   */\n  template<enum PhysicalType PhysicalTypeOther_>\n  Scalar dot(const Vector<PhysicalTypeOther_, PrimType_, Dimension_>& other) const {\n    return this->toImplementation().dot(other.toImplementation());\n  }\n\n  /*! \\brief Cross product with other vector.\n   *  \\param other   other vector\n   *  \\returns cross product.\n   */\n  template<enum PhysicalType PhysicalTypeOther_, int DimensionCopy_ = Dimension_>\n  typename internal::MultiplicationReturnTypeTrait<Vector<PhysicalType_, PrimType_, Dimension_>, Vector<PhysicalTypeOther_, PrimType_, Dimension_>>::ReturnType\n  cross(const Vector<PhysicalTypeOther_, PrimType_, Dimension_>& other, typename std::enable_if<DimensionCopy_ == 3>::type* = nullptr) const {\n    return typename internal::MultiplicationReturnTypeTrait<Vector<PhysicalType_, PrimType_, Dimension_>, Vector<PhysicalTypeOther_, PrimType_, Dimension_>>::ReturnType(this->toImplementation().cross(other.toImplementation()));\n  }\n\n  /*! \\brief Projects this vector (a) on the other vector (b).\n   *  The result  is\n   *    proj = b/|b| * |a| * cos(angle) = b/|b| * |a| * a.b / |a| / |b|,\n   *  which is computed by\n   *           a.b\n   *  proj = ------- * a\n   *          |a|*|a|\n   *  \\param other   other vector\n   *  \\returns projected vector.\n   */\n  template<enum PhysicalType PhysicalTypeOther_>\n  Vector<PhysicalType_, PrimType_, Dimension_> projectOn(const Vector<PhysicalTypeOther_, PrimType_, Dimension_>& other) const {\n    return other * (this->dot(other)/other.squaredNorm());\n  }\n\n\n  /*! \\brief Elementwise product with other vector.\n   *  \\param other   other vector\n   *  \\returns elementwise product.\n   */\n  template<enum PhysicalType PhysicalTypeOther_>\n  typename internal::MultiplicationReturnTypeTrait<Vector<PhysicalType_, PrimType_, Dimension_>, Vector<PhysicalTypeOther_, PrimType_, Dimension_>>::ReturnType\n  elementwiseMultiplication(const Vector<PhysicalTypeOther_, PrimType_, Dimension_>& other) const {\n    return typename internal::MultiplicationReturnTypeTrait<Vector<PhysicalType_, PrimType_, Dimension_>, Vector<PhysicalTypeOther_, PrimType_, Dimension_>>::ReturnType(this->toImplementation().cwiseProduct(other.toImplementation()));\n  }\n\n  /*! \\brief Elementwise division by other vector.\n   *  \\param other   other vector\n   *  \\returns elementwise quotient.\n   */\n  template<enum PhysicalType PhysicalTypeOther_>\n  typename internal::DivisionReturnTypeTrait<Vector<PhysicalType_, PrimType_, Dimension_>, Vector<PhysicalTypeOther_, PrimType_, Dimension_>>::ReturnType\n  elementwiseDivision(const Vector<PhysicalTypeOther_, PrimType_, Dimension_>& other) const {\n    return typename internal::DivisionReturnTypeTrait<Vector<PhysicalType_, PrimType_, Dimension_>, Vector<PhysicalTypeOther_, PrimType_, Dimension_>>::ReturnType(this->toImplementation().cwiseQuotient(other.toImplementation()));\n  }\n\n  /*! \\brief Absolute components.\n   *  \\returns absolute components.\n   */\n  Vector<PhysicalType_, PrimType_, Dimension_> abs() const {\n    return Vector<PhysicalType_, PrimType_, Dimension_>(this->toImplementation().cwiseAbs());\n  }\n\n  /*! \\brief Maximum of the components.\n   *  \\returns maximum.\n   */\n  Scalar max() const {\n    return this->toImplementation().maxCoeff();\n  }\n\n  /*! \\brief Minimum of the components.\n   *  \\returns minimum.\n   */\n  Scalar min() const {\n    return this->toImplementation().minCoeff();\n  }\n\n  /*! \\brief Sum of the components.\n   *  \\returns sum.\n   */\n  Scalar sum() const {\n    return this->toImplementation().sum();\n  }\n\n  /*! \\brief Mean of the components.\n   *  \\returns mean.\n   */\n  Scalar mean() const {\n    return this->toImplementation().mean();\n  }\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 Vector<PhysicalType_, PrimType_, Dimension_>& vector) {\n    out << vector.transpose();\n    return out;\n  }\n};\n\n\n/*! \\brief Multiplies a vector with a scalar.\n * \\param factor   factor\n * \\returns product\n */\ntemplate<enum PhysicalType PhysicalType_, typename PrimTypeFactor_, typename PrimType_, int Dimension_>\nVector<PhysicalType_, PrimType_, Dimension_> operator*(PrimTypeFactor_ factor, const Vector<PhysicalType_, PrimType_, Dimension_>& vector) {\n  return vector*(PrimType_)factor;\n}\n\n\nnamespace internal {\n\n/*! \\brief Gets the primitive type of the vector\n */\ntemplate<enum PhysicalType PhysicalType_, typename PrimType_, int Dimension_>\nclass get_scalar<Vector<PhysicalType_, PrimType_, Dimension_>> {\n public:\n  typedef PrimType_ Scalar;\n};\n\n/*! \\brief Gets the dimension of the vector\n */\ntemplate<enum PhysicalType PhysicalType_, typename PrimType_, int Dimension_>\nclass get_dimension<Vector<PhysicalType_, PrimType_, Dimension_>> {\n public:\n  static constexpr int Dimension = Dimension_;\n};\n\n/*! \\brief Gets the return type of a multiplication\n */\ntemplate<enum PhysicalType PhysicalType1_, enum PhysicalType PhysicalType2_, typename PrimType_, int Dimension_>\nclass MultiplicationReturnTypeTrait<Vector<PhysicalType1_, PrimType_, Dimension_>, Vector<PhysicalType2_, PrimType_, Dimension_>>\n{\n public:\n  typedef Vector<PhysicalType::Typeless, PrimType_, Dimension_> ReturnType;\n};\n\n/*! \\brief Gets the return type of a multiplication\n */\ntemplate<enum PhysicalType PhysicalType1_, enum PhysicalType PhysicalType2_, typename PrimType_, int Dimension_>\nclass DivisionReturnTypeTrait<Vector<PhysicalType1_, PrimType_, Dimension_>, Vector<PhysicalType2_, PrimType_, Dimension_>>\n{\n public:\n  typedef Vector<PhysicalType::Typeless, PrimType_, Dimension_> ReturnType;\n};\n\n/*! \\brief Specializes multiplication and division traits for the triple (factor1 != factor2)\n */\n#define KINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(FACTOR1, FACTOR2, PRODUCT) \\\n    template<typename PrimType_, int Dimension_> \\\n    class MultiplicationReturnTypeTrait<Vector<PhysicalType::FACTOR1, PrimType_, Dimension_>, Vector<PhysicalType::FACTOR2, PrimType_, Dimension_>> \\\n    { \\\n     public: \\\n      typedef Vector<PhysicalType::PRODUCT, PrimType_, Dimension_> ReturnType; \\\n    }; \\\n    template<typename PrimType_, int Dimension_> \\\n    class MultiplicationReturnTypeTrait<Vector<PhysicalType::FACTOR2, PrimType_, Dimension_>, Vector<PhysicalType::FACTOR1, PrimType_, Dimension_>> \\\n    { \\\n     public: \\\n      typedef Vector<PhysicalType::PRODUCT, PrimType_, Dimension_> ReturnType; \\\n    }; \\\n    template<typename PrimType_, int Dimension_> \\\n    class DivisionReturnTypeTrait<Vector<PhysicalType::PRODUCT, PrimType_, Dimension_>, Vector<PhysicalType::FACTOR1, PrimType_, Dimension_>> \\\n    { \\\n     public: \\\n      typedef Vector<PhysicalType::FACTOR2, PrimType_, Dimension_> ReturnType; \\\n    }; \\\n    template<typename PrimType_, int Dimension_> \\\n    class DivisionReturnTypeTrait<Vector<PhysicalType::PRODUCT, PrimType_, Dimension_>, Vector<PhysicalType::FACTOR2, PrimType_, Dimension_>> \\\n    { \\\n     public: \\\n      typedef Vector<PhysicalType::FACTOR1, PrimType_, Dimension_> ReturnType; \\\n    };\n\n/*! \\brief Specializes multiplication and division traits for the triple (factor1 == factor2)\n */\n#define KINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_B(FACTOR1AND2, PRODUCT) \\\n    template<typename PrimType_, int Dimension_> \\\n    class MultiplicationReturnTypeTrait<Vector<PhysicalType::FACTOR1AND2, PrimType_, Dimension_>, Vector<PhysicalType::FACTOR1AND2, PrimType_, Dimension_>> \\\n    { \\\n     public: \\\n      typedef Vector<PhysicalType::PRODUCT, PrimType_, Dimension_> ReturnType; \\\n    }; \\\n    template<typename PrimType_, int Dimension_> \\\n    class DivisionReturnTypeTrait<Vector<PhysicalType::PRODUCT, PrimType_, Dimension_>, Vector<PhysicalType::FACTOR1AND2, PrimType_, Dimension_>> \\\n    { \\\n     public: \\\n      typedef Vector<PhysicalType::FACTOR1AND2, PrimType_, Dimension_> ReturnType; \\\n    };\n\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_B(Typeless, Typeless)\n\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Typeless, Time, Time)\n\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Typeless, Jerk, Jerk)\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Typeless, Acceleration, Acceleration)\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Typeless, Velocity, Velocity)\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Typeless, Position, Position) // Position/Position = Typeless\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Typeless, Force, Force)\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Typeless, Momentum, Momentum)\n\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Typeless, AngularJerk, AngularJerk)\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Typeless, AngularAcceleration, AngularAcceleration)\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Typeless, AngularVelocity, AngularVelocity)\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Typeless, Angle, Angle)\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Typeless, Torque, Torque)\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Typeless, AngularMomentum, AngularMomentum)\n\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Position, AngularJerk, Jerk)\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Position, AngularAcceleration, Acceleration)\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Position, AngularVelocity, Velocity)\n//KINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Position, Angle, Position) // Position/Position = Angle -> ambiguous, explicit cast to Angle if needed\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Position, Force, Torque)\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Position, Momentum, AngularMomentum)\n\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Time, Jerk, Acceleration)\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Time, Acceleration, Velocity)\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Time, Velocity, Position)\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Time, Force, Momentum)\n\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Time, AngularJerk, AngularAcceleration)\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Time, AngularAcceleration, AngularVelocity)\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Time, AngularVelocity, Angle)\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Time, Torque, AngularMomentum)\n\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Mass, Acceleration, Force)\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Mass, Velocity, Momentum)\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Inertia, AngularAcceleration, Torque)\nKINDR_SPECIALIZE_PHYS_QUANT_RETURN_TYPE_A(Inertia, AngularVelocity, AngularMomentum)\n\n\n\n} // namespace internal\n} // namespace kindr\n\n\n\n\n", "meta": {"hexsha": "c8999982575a6a29d3193ea7490f00d790bc0a12", "size": 27457, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kindr/vectors/Vector.hpp", "max_stars_repo_name": "meyerj/kindr", "max_stars_repo_head_hexsha": "a5ef954dcc2cbba8de36e36e03f6922c9c486463", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 126.0, "max_stars_repo_stars_event_min_datetime": "2015-06-17T12:49:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T13:39:04.000Z", "max_issues_repo_path": "include/kindr/vectors/Vector.hpp", "max_issues_repo_name": "meyerj/kindr", "max_issues_repo_head_hexsha": "a5ef954dcc2cbba8de36e36e03f6922c9c486463", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2015-01-12T10:39:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-31T13:24:52.000Z", "max_forks_repo_path": "include/kindr/vectors/Vector.hpp", "max_forks_repo_name": "meyerj/kindr", "max_forks_repo_head_hexsha": "a5ef954dcc2cbba8de36e36e03f6922c9c486463", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 80.0, "max_forks_repo_forks_event_min_datetime": "2015-11-06T02:47:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-25T10:26:18.000Z", "avg_line_length": 38.617440225, "max_line_length": 334, "alphanum_fraction": 0.7344210948, "num_tokens": 6540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2698859562062588}}
{"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 <cmath>\n#include <boost/random.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <wx/wxprec.h>\n#include <wx/wx.h>\n#include <wx/xrc/xmlres.h>\n#include <wx/msgdlg.h>\n#include \"../Project.h\"\n#include \"../DataViewer/TableInterface.h\"\n#include \"../DataViewer/TimeState.h\"\n#include \"../DataViewer/DataViewerAddColDlg.h\"\n#include \"../GenUtils.h\"\n#include \"../logger.h\"\n#include \"FieldNewCalcSpecialDlg.h\"\n#include \"FieldNewCalcUniDlg.h\"\n#include \"FieldNewCalcBinDlg.h\"\n#include \"FieldNewCalcLagDlg.h\"\n#include \"FieldNewCalcRateDlg.h\"\n\nBEGIN_EVENT_TABLE( FieldNewCalcUniDlg, wxPanel )\n\tEVT_BUTTON( XRCID(\"ID_ADD_COLUMN\"), FieldNewCalcUniDlg::OnAddColumnClick )\n    EVT_CHOICE( XRCID(\"IDC_UNARY_RESULT\"),\n\t\t\t   FieldNewCalcUniDlg::OnUnaryResultUpdated )\n\tEVT_CHOICE( XRCID(\"IDC_UNARY_RESULT_TM\"),\n\t\t   FieldNewCalcUniDlg::OnUnaryResultTmUpdated )\n\tEVT_CHOICE( XRCID(\"IDC_UNARY_OPERATOR\"),\n\t\t\t   FieldNewCalcUniDlg::OnUnaryOperatorUpdated )\n\tEVT_TEXT( XRCID(\"IDC_UNARY_OPERAND\"),\n\t\t\t FieldNewCalcUniDlg::OnUnaryOperandUpdated )\n    EVT_COMBOBOX( XRCID(\"IDC_UNARY_OPERAND\"),\n\t\t\t\t FieldNewCalcUniDlg::OnUnaryOperandUpdated )\n\tEVT_CHOICE( XRCID(\"IDC_UNARY_OPERAND_TM\"),\n\t\t\t\t FieldNewCalcUniDlg::OnUnaryOperandTmUpdated )\nEND_EVENT_TABLE()\n\nFieldNewCalcUniDlg::FieldNewCalcUniDlg(Project* project_s,\n\t\t\t\t\t\t\t\t\t   wxWindow* parent,\n\t\t\t\t\t\t\t\t\t   wxWindowID id, const wxString& caption,\n\t\t\t\t\t\t\t\t\t   const wxPoint& pos, const wxSize& size,\n\t\t\t\t\t\t\t\t\t   long style )\n: all_init(false), op_string(9), project(project_s),\ntable_int(project_s->GetTableInt()),\nm_valid_const(false), m_const(1), m_var_sel(wxNOT_FOUND),\nis_space_time(project_s->GetTableInt()->IsTimeVariant())\n{\n\tSetParent(parent);\n    CreateControls();\n    Centre();\n    \n\top_string[assign_op] = \"ASSIGN\";\n\top_string[negate_op] = \"NEGATIVE\";\n\top_string[invert_op] = \"INVERT\";\n\top_string[sqrt_op] = \"SQUARE ROOT\";\n\top_string[log_10_op] = \"LOG (base 10)\";\n\top_string[log_e_op] = \"LOG (base e)\";\n\top_string[dev_from_mean_op] = \"DEVIATION FROM MEAN\";\n\top_string[standardize_op] = \"STANDARDIZED\";\n\top_string[shuffle_op] = \"SHUFFLE\";\n\t\n\tfor (int i=0, iend=op_string.size(); i<iend; i++) {\n\t\tm_op->Append(op_string[i]);\n\t}\n\tm_op->SetSelection(0);\n\t\n\tInitFieldChoices();\n\tall_init = true;\n}\n\nvoid FieldNewCalcUniDlg::CreateControls()\n{    \n    wxXmlResource::Get()->LoadPanel(this, GetParent(), \"IDD_FIELDCALC_UN\");\n    m_result = XRCCTRL(*this, \"IDC_UNARY_RESULT\", wxChoice);\n\tm_result_tm = XRCCTRL(*this, \"IDC_UNARY_RESULT_TM\", wxChoice);\n\tInitTime(m_result_tm);\n    m_op = XRCCTRL(*this, \"IDC_UNARY_OPERATOR\", wxChoice);\n    m_var = XRCCTRL(*this, \"IDC_UNARY_OPERAND\", wxComboBox);\n\tm_var_tm = XRCCTRL(*this, \"IDC_UNARY_OPERAND_TM\", wxChoice);\n    InitTime(m_var_tm);\n\tm_text = XRCCTRL(*this, \"IDC_EDIT1\", wxTextCtrl);\n\tm_text->SetMaxLength(0);\n}\n\nvoid FieldNewCalcUniDlg::Apply()\n{\n\tif (m_result->GetSelection() == wxNOT_FOUND) {\n\t\twxString msg(\"Please choose a Result field.\");\n\t\twxMessageDialog dlg (this, msg, \"Error\", wxOK | wxICON_ERROR);\n\t\tdlg.ShowModal();\n\t\treturn;\n\t}\n\tint result_col = col_id_map[m_result->GetSelection()];\n\n\tint var_col = wxNOT_FOUND;\n\tif (m_var_sel != wxNOT_FOUND) {\n\t\tvar_col = col_id_map[m_var_sel];\n\t}\t\n\tif (var_col == wxNOT_FOUND && !m_valid_const) {\n\t\twxString msg(\"Operation requires a valid field name or constant.\");\n\t\twxMessageDialog dlg (this, msg, \"Error\", wxOK | wxICON_ERROR);\n\t\tdlg.ShowModal();\n\t\treturn;\n\t}\n\t\n\tif (is_space_time && var_col != wxNOT_FOUND &&\n\t\t!IsAllTime(result_col, m_result_tm->GetSelection()) &&\n\t\tIsAllTime(var_col, m_var_tm->GetSelection())) {\n\t\twxString msg(\"When \\\"all times\\\" selected for variable, result \"\n\t\t\t\t\t \"field must also be \\\"all times.\\\"\");\n\t\twxMessageDialog dlg (this, msg, \"Error\", wxOK | wxICON_ERROR);\n\t\tdlg.ShowModal();\n\t\treturn;\n\t}\n\t\n\tTableState* ts = project->GetTableState();\n\twxString grp_nm = table_int->GetColName(result_col);\n\tif (!Project::CanModifyGrpAndShowMsgIfNot(ts, grp_nm)) return;\n\n\t\n\t// Mersenne Twister random number generator, randomly seeded\n\t// with current time in seconds since Jan 1 1970.\n\tstatic boost::mt19937 rng(std::time(0));\n\t\n\tstd::vector<int> time_list;\n\tif (IsAllTime(result_col, m_result_tm->GetSelection())) {\n\t\tint ts = project->GetTableInt()->GetTimeSteps();\n\t\ttime_list.resize(ts);\n\t\tfor (int i=0; i<ts; i++) time_list[i] = i;\n\t} else {\n\t\tint tm = IsTimeVariant(result_col) ? m_result_tm->GetSelection() : 0;\n\t\ttime_list.resize(1);\n\t\ttime_list[0] = tm;\n\t}\n\t\n\tint rows = table_int->GetNumberRows();\n\tstd::vector<double> data(rows, 0);\n\tstd::vector<bool> undefined(rows, false);\n\tif (var_col != wxNOT_FOUND &&\n\t\t!IsAllTime(var_col, m_var_tm->GetSelection())) {\n\t\tint tm = IsTimeVariant(var_col) ? m_var_tm->GetSelection() : 0;\n\t\ttable_int->GetColData(var_col,tm, data);\n\t\ttable_int->GetColUndefined(var_col, tm, undefined);\n\t} else {\n\t\tfor (int i=0; i<rows; i++) data[i] = m_const;\n\t}\n\tstd::vector<double> r_data(table_int->GetNumberRows(), 0);\n\tstd::vector<bool> r_undefined(table_int->GetNumberRows(), false);\n\t\n\tfor (int t=0; t<time_list.size(); t++) {\n\t\tif (var_col != wxNOT_FOUND &&\n\t\t\tIsAllTime(var_col, m_var_tm->GetSelection()))\n\t\t{\n\t\t\ttable_int->GetColData(var_col, time_list[t], data);\n\t\t\ttable_int->GetColUndefined(var_col, time_list[t], undefined);\n\t\t}\n\t\tfor (int i=0; i<rows; i++) {\n\t\t\tr_data[i] = data[i];\n\t\t\tr_undefined[i] = undefined[i];\n\t\t}\n\t\tswitch (m_op->GetSelection()) {\n\t\t\tcase assign_op:\n\t\t\t{\n\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase negate_op:\n\t\t\t{\n\t\t\t\tfor (int i=0; i<rows; i++) {\n\t\t\t\t\tif (!undefined[i]) r_data[i] = -data[i];\n\t\t\t\t}\n\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase invert_op:\n\t\t\t{\n\t\t\t\tfor (int i=0; i<rows; i++) {\n\t\t\t\t\tif (!undefined[i] && data[i] != 0) {\n\t\t\t\t\t\tr_data[i] = 1.0 / data[i];\n\t\t\t\t\t} else {\n\t\t\t\t\t\tr_data[i] = 0;\n\t\t\t\t\t\tr_undefined[i] = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase sqrt_op:\n\t\t\t{\n\t\t\t\tfor (int i=0; i<rows; i++) {\n\t\t\t\t\tif (!undefined[i] && data[i] >= 0) {\n\t\t\t\t\t\tr_data[i] = sqrt(data[i]);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tr_data[i] = 0;\n\t\t\t\t\t\tr_undefined[i] = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase log_10_op:\n\t\t\t{\n\t\t\t\tfor (int i=0; i<rows; i++) {\n\t\t\t\t\tif (!undefined[i] && data[i] > 0) {\n\t\t\t\t\t\tr_data[i] = log10(data[i]);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tr_data[i] = 0;\n\t\t\t\t\t\tr_undefined[i] = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\tbreak;\t\t\t\n\t\t\tcase log_e_op:\n\t\t\t{\n\t\t\t\tfor (int i=0; i<rows; i++) {\n\t\t\t\t\tif (!undefined[i] && data[i] > 0) {\n\t\t\t\t\t\tr_data[i] = log(data[i]);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tr_data[i] = 0;\n\t\t\t\t\t\tr_undefined[i] = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase dev_from_mean_op:\n\t\t\t{\n\t\t\t\tfor (int i=0; i<rows; i++) {\n\t\t\t\t\tif (undefined[i]) {\n\t\t\t\t\t\twxString msg;\n\t\t\t\t\t\tmsg << \"Observation \" << i;\n\t\t\t\t\t\tmsg << \" is undefined. \";\n\t\t\t\t\t\tmsg << \"Operation aborted.\";\n\t\t\t\t\t\twxMessageDialog dlg (this, msg, \"Error\",\n\t\t\t\t\t\t\t\t\t\t\t wxOK | wxICON_ERROR);\n\t\t\t\t\t\tdlg.ShowModal();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tr_data[i] = data[i];\n\t\t\t\t}\n\t\t\t\tGenUtils::DeviationFromMean(r_data);\n\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase standardize_op:\n\t\t\t{\n\t\t\t\tfor (int i=0; i<rows; i++) {\n\t\t\t\t\tif (undefined[i]) {\n\t\t\t\t\t\twxString msg;\n\t\t\t\t\t\tmsg << \"Observation \";\n\t\t\t\t\t\tmsg << i << \" is undefined. \";\n\t\t\t\t\t\tmsg << \"Operation aborted.\";\n\t\t\t\t\t\twxMessageDialog dlg (this, msg, \"Error\",\n\t\t\t\t\t\t\t\t\t\t\t wxOK | wxICON_ERROR);\n\t\t\t\t\t\tdlg.ShowModal();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tr_data[i] = data[i];\n\t\t\t\t}\n\t\t\t\tdouble ssum = 0.0;\n\t\t\t\tfor (int i=0; i<rows; i++) ssum += r_data[i] * r_data[i];\n\t\t\t\tif (ssum == 0) {\n\t\t\t\t\twxString msg(\"Standard deviation is 0, operation aborted.\");\n\t\t\t\t\twxMessageDialog dlg (this, msg, \"Error\", wxOK|wxICON_ERROR);\n\t\t\t\t\tdlg.ShowModal();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tGenUtils::StandardizeData(r_data);\n\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase shuffle_op:\n\t\t\t{\n\t\t\t\tfor (int i=0; i<rows; i++) {\n\t\t\t\t\tr_data[i] = data[i];\n\t\t\t\t\tr_undefined[i] = undefined[i];\n\t\t\t\t}\n\t\t\t\tstatic boost::random::uniform_int_distribution<> X(0, rows-1);\n\t\t\t\t// X(rng) -> returns a uniform random number from 0 to rows-1;\n\t\t\t\tfor (int i=0; i<rows; i++) {\n\t\t\t\t\t// swap each item in data with a random position in data.\n\t\t\t\t\t// This will produce a random permutation\n\t\t\t\t\tint r = X(rng);\n\t\t\t\t\tdouble d_t = r_data[r];\n\t\t\t\t\tbool u_t = r_undefined[r];\n\t\t\t\t\tr_data[r] = r_data[i];\n\t\t\t\t\tr_undefined[r] = r_undefined[i];\n\t\t\t\t\tr_data[i] = d_t;\n\t\t\t\t\tr_undefined[i] = u_t;\n\t\t\t\t\tif (undefined[i]) r_data[i] = 0;\n\t\t\t\t\tif (undefined[r]) r_data[r] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn;\n\t\t\t\tbreak;\n\t\t}\n\t\ttable_int->SetColData(result_col, time_list[t], r_data);\n\t\ttable_int->SetColUndefined(result_col, time_list[t], r_undefined);\n\n\t}\n}\n\nvoid FieldNewCalcUniDlg::InitFieldChoices()\n{\n\twxString r_str_sel = m_result->GetStringSelection();\n\tint r_sel = m_result->GetSelection();\n\tint prev_cnt = m_result->GetCount();\n\t\n\twxString var_val_orig = m_var->GetValue();\n\tm_result->Clear();\n\t{\n\t\tint sel_temp = m_var_sel;\n\t\tm_var->Clear();\n\t\tm_var_sel = sel_temp;\n\t}\n\t\n\ttable_int->FillNumericColIdMap(col_id_map);\n\tm_var_str.resize(col_id_map.size());\n\n\twxString r_tm, v_tm;\n\tif (is_space_time) {\n\t\tr_tm << \" (\" << m_result_tm->GetStringSelection() << \")\";\n\t\tv_tm << \" (\" << m_var_tm->GetStringSelection() << \")\";\n\t}\n\tfor (int i=0, iend=col_id_map.size(); i<iend; i++) {\n\t\tif (is_space_time &&\n\t\t\ttable_int->GetColTimeSteps(col_id_map[i]) > 1) {\t\t\t\n\t\t\tm_result->Append(table_int->GetColName(col_id_map[i]) + r_tm);\n\t\t\tm_var->Append(table_int->GetColName(col_id_map[i]) + v_tm);\n\t\t\tm_var_str[i] = table_int->GetColName(col_id_map[i]) + v_tm;\n\t\t} else {\n\t\t\tm_result->Append(table_int->GetColName(col_id_map[i]));\n\t\t\tm_var->Append(table_int->GetColName(col_id_map[i]));\n\t\t\tm_var_str[i] = table_int->GetColName(col_id_map[i]);\n\t\t}\n\t}\n\t\n\tif (m_result->GetCount() == prev_cnt) {\n\t\t// only the time field changed\n\t\tm_result->SetSelection(r_sel);\n\t} else {\n\t\t// a new variable might have been added, so find old string\n\t\tm_result->SetSelection(m_result->FindString(r_str_sel));\n\t}\n\t\n\tif (m_var->GetCount() == prev_cnt) {\n\t\t// only the time field changed\n\t\tif (m_var_sel != wxNOT_FOUND) {\n\t\t\tm_var->SetSelection(m_var_sel);\n\t\t} else {\n\t\t\tm_var->SetValue(var_val_orig);\n\t\t}\n\t} else {\n\t\t// a new variable might have been added, so find old string\n\t\tif (m_var_sel != wxNOT_FOUND) {\n\t\t\tm_var->SetSelection(m_var->FindString(var_val_orig));\n\t\t\tm_var_sel = m_var->GetSelection();\n\t\t} else {\n\t\t\tm_var->SetValue(var_val_orig);\n\t\t}\n\t}\n\t\n\tDisplay();\n}\n\nvoid FieldNewCalcUniDlg::UpdateOtherPanels()\n{\n\ts_panel->InitFieldChoices();\n\tb_panel->InitFieldChoices();\n\tl_panel->InitFieldChoices();\n\tr_panel->InitFieldChoices();\n}\n\nvoid FieldNewCalcUniDlg::Display()\n{\n\tif (!all_init) return;\n\twxString s(\"\");\n\twxString lhs(m_result->GetStringSelection());\n\twxString rhs(\"\");\n\twxString var(\"\");\n\tif (m_var_sel != wxNOT_FOUND) var = m_var_str[m_var_sel];\n\tif (m_var_sel == wxNOT_FOUND && m_valid_const) {\n\t\tvar = m_var->GetValue();\n\t\tvar.Trim(false);\n\t\tvar.Trim(true);\n\t}\n\t\n\tint op_sel = m_op->GetSelection();\n\tif (op_sel == assign_op) {\n\t\trhs = var;\n\t} else if (op_sel == negate_op) {\n\t\tif (!var.IsEmpty()) rhs << \"-\" << var;\n\t} else if (op_sel == invert_op) {\n\t\tif (!var.IsEmpty()) rhs << \"1/\" << var;\n\t} else if (op_sel == sqrt_op) {\n\t\tif (!var.IsEmpty()) rhs << \"sqrt( \" << var << \" )\";\n\t} else if (op_sel == log_10_op) {\n\t\tif (!var.IsEmpty()) rhs << \"log( \" << var << \" )\";\n\t} else if (op_sel == log_e_op) {\n\t\tif (!var.IsEmpty()) rhs << \"ln( \" << var << \" )\";\n\t} else if (op_sel == dev_from_mean_op) {\n\t\tif (!var.IsEmpty()) rhs << \"dev from mean of \" << var;\n\t} else if (op_sel == standardize_op) {\n\t\tif (!var.IsEmpty()) rhs << \"standardized dev from mean of \" << var;\n\t} else { // op_sel == shuffle_op\n\t\tif (!var.IsEmpty()) rhs << \"randomly permute values in \" << var;\n\t}\n\n\tif (lhs.IsEmpty() && rhs.IsEmpty()) {\n\t\ts = \"\";\n\t} else if (!lhs.IsEmpty() && rhs.IsEmpty()) {\n\t\ts << lhs << \" =\";\n\t} else if (lhs.IsEmpty() && !rhs.IsEmpty()) {\n\t\ts << rhs;\n\t} else {\n\t\t// a good time to enable the apply button.\n\t\ts << lhs << \" = \" << rhs;\n\t}\n\t\n\tm_text->SetValue(s);\n}\n\nbool FieldNewCalcUniDlg::IsTimeVariant(int col_id)\n{\n\tif (!is_space_time) return false;\n\treturn (table_int->IsColTimeVariant(col_id));\n}\n\nbool FieldNewCalcUniDlg::IsAllTime(int col_id, int tm_sel)\n{\n\tif (!is_space_time) return false;\n\tif (!table_int->IsColTimeVariant(col_id)) return false;\n\treturn tm_sel == project->GetTableInt()->GetTimeSteps();\n}\n\nvoid FieldNewCalcUniDlg::OnUnaryResultUpdated( wxCommandEvent& event )\n{\n\tint sel = m_result->GetSelection();\n\tm_result_tm->Enable(sel != wxNOT_FOUND &&\n\t\t\t\t\t\tIsTimeVariant(col_id_map[sel]));\n    Display();\n}\n\nvoid FieldNewCalcUniDlg::OnUnaryResultTmUpdated( wxCommandEvent& event )\n{\n\tInitFieldChoices();\n    Display();\n}\n\nvoid FieldNewCalcUniDlg::OnUnaryOperatorUpdated( wxCommandEvent& event )\n{\n    Display();\n}\n\nvoid FieldNewCalcUniDlg::OnUnaryOperandUpdated( wxCommandEvent& event )\n{\n\tif (!all_init) return;\n\t\n\twxString var_val = m_var->GetValue();\n\tvar_val.Trim(false);\n\tvar_val.Trim(true);\n\tif (m_var->GetValue() != m_var->GetStringSelection()) {\n\t\t// User has typed something in manually.\n\t\t// if value matches some item on list, then set list to that\n\t\t// otherwise, set selection back to wxNOT_FOUND\n\t\tm_var_sel = wxNOT_FOUND;\n\t\tfor (int i=0, i_end=m_var_str.size(); m_var_sel==-1 && i<i_end; i++) {\n\t\t\tif (var_val.IsSameAs(m_var_str[i], false)) m_var_sel = i;\n\t\t}\n\t\tif (m_var_sel != wxNOT_FOUND) {\n\t\t\t// don't use SetSelection because otherwise it will\n\t\t\t// be difficult to type in string names that have prefixes that\n\t\t\t// match someing in m_var_str\n\t\t\t//m_var->SetSelection(m_var_sel);\n\t\t} else {\n\t\t\tm_valid_const = var_val.ToDouble(&m_const);\n\t\t}\n\t} else {\n\t\tm_var_sel = m_var->GetSelection();\n\t}\n\tm_var_tm->Enable(m_var_sel != wxNOT_FOUND &&\n\t\t\t\t\t table_int->GetColTimeSteps(col_id_map[m_var_sel]) > 1);\n\tDisplay();\n}\n\nvoid FieldNewCalcUniDlg::OnUnaryOperandTmUpdated( wxCommandEvent& event )\n{\n\tInitFieldChoices();\n    Display();\n}\n\nvoid FieldNewCalcUniDlg::OnAddColumnClick( wxCommandEvent& event )\n{\n\tDataViewerAddColDlg dlg(project, this);\n\tif (dlg.ShowModal() != wxID_OK) return;\n\tInitFieldChoices();\n\twxString sel_str = dlg.GetColName();\n\tif (table_int->GetColTimeSteps(dlg.GetColId()) > 1) {\n\t\tsel_str << \" (\" << m_result_tm->GetStringSelection() << \")\";\n\t}\n\tm_result->SetSelection(m_result->FindString(sel_str));\n\tOnUnaryResultUpdated(event);\n\tUpdateOtherPanels();\n}\n\nvoid FieldNewCalcUniDlg::InitTime(wxChoice* time_list)\n{\n\ttime_list->Clear();\n\tfor (int i=0; i<project->GetTableInt()->GetTimeSteps(); i++) {\n\t\twxString t;\n\t\tt << project->GetTableInt()->GetTimeString(i);\n\t\ttime_list->Append(t);\n\t}\n\ttime_list->Append(\"all times\");\n\ttime_list->SetSelection(project->GetTableInt()->GetTimeSteps());\n\ttime_list->Disable();\n\ttime_list->Show(is_space_time);\n}\n", "meta": {"hexsha": "efe1c7d7fe2793f3e84b708b5d513182885d31b0", "size": 15451, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DialogTools/FieldNewCalcUniDlg.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": "DialogTools/FieldNewCalcUniDlg.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": "DialogTools/FieldNewCalcUniDlg.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": 28.9344569288, "max_line_length": 75, "alphanum_fraction": 0.6565918064, "num_tokens": 4600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.2698366209481967}}
{"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/**\n * @file rcbdd.hpp\n *\n * @brief Data structure for BDD of a characteristic function to a reversible function\n *\n * @author Mathias Soeken\n * @since  2.0\n */\n\n#ifndef RCBDD_HPP\n#define RCBDD_HPP\n\n#include <boost/assign/std/vector.hpp>\n#include <boost/optional.hpp>\n\n#include <cuddObj.hh>\n\n#include <reversible/circuit.hpp>\n\nnamespace cirkit\n{\n\n  using namespace boost::assign;\n\n  class rcbdd\n  {\n  public:\n    void initialize_manager();\n    void create_variables( unsigned n, bool create_zs = true );\n    BDD x( unsigned i ) const;\n    BDD y( unsigned i ) const;\n    BDD z( unsigned i ) const;\n\n    const std::vector<BDD> xs() const;\n    const std::vector<BDD> ys() const;\n    const std::vector<BDD> zs() const;\n\n    unsigned num_vars() const;\n    const Cudd& manager() const;\n    BDD chi() const;\n    void set_chi( BDD f );\n    void set_constant_value( bool v );\n    bool constant_value() const;\n    void set_num_inputs( unsigned n );\n    void set_num_outputs( unsigned n );\n    unsigned num_inputs() const;\n    unsigned num_outputs() const;\n    void set_input_labels( const std::vector<std::string>& labels );\n    void set_output_labels( const std::vector<std::string>& labels );\n    const std::vector<std::string> input_labels() const;\n    const std::vector<std::string> output_labels() const;\n\n    BDD compose(const BDD& left, const BDD& right) const;\n    BDD cofactor( BDD f, unsigned var, bool input_polarity, bool output_polarity ) const;\n    BDD move_xs_to_tmp( const BDD& f ) const;\n    BDD move_ys_to_tmp( const BDD& f ) const;\n    BDD move_tmp_to_ys( const BDD& f ) const;\n    BDD move_ys_to_xs( const BDD& f) const;\n    BDD remove_xs( const BDD& f ) const;\n    BDD remove_ys( const BDD& f ) const;\n    BDD remove_tmp( const BDD& f ) const;\n    BDD invert( const BDD&f ) const;\n    bool is_self_inverse( const BDD& f ) const;\n\n    BDD create_from_gate( unsigned target, const BDD& controlf ) const;\n    BDD create_from_gate( const gate& g ) const;\n    BDD create_from_circuit( const circuit& circ ) const;\n\n    void print_truth_table() const;\n    void write_pla( const std::string& filename, bool full = false ) const;\n\n  private:\n    boost::optional<Cudd> _manager;\n    BDD _chi;\n\n    bool _constant_value = false;\n    unsigned _num_inputs = 0u;\n    unsigned _num_outputs = 0u;\n    std::vector<std::string> _input_labels;\n    std::vector<std::string> _output_labels;\n    unsigned _n = 0u;\n    std::vector<BDD> _xs;\n    std::vector<BDD> _ys;\n    std::vector<BDD> _zs;\n  };\n\n  void copy_meta_data( circuit& circ, const rcbdd& cf );\n}\n\n#endif\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": "6900e005a359277ee79314d38689afc7304e1b50", "size": 3889, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "addons/cirkit-addon-reversible/src/reversible/rcbdd.hpp", "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/rcbdd.hpp", "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/rcbdd.hpp", "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": 31.6178861789, "max_line_length": 89, "alphanum_fraction": 0.7004371304, "num_tokens": 1034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.26975442221551515}}
{"text": "// Copyright (C) 2013 The Regents of the University of California (Regents).\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//\n//     * Redistributions in binary form must reproduce the above\n//       copyright notice, this list of conditions and the following\n//       disclaimer in the documentation and/or other materials provided\n//       with the distribution.\n//\n//     * Neither the name of The Regents or University of California nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Please contact the author of this library if you have any questions.\n// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include \"theia/vision/sfm/pose/util.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <glog/logging.h>\n#include \"theia/util/random.h\"\n\nnamespace theia {\n\nusing Eigen::Map;\nusing Eigen::Matrix;\nusing Eigen::Matrix3d;\nusing Eigen::Vector2d;\nusing Eigen::Vector3d;\n\nvoid ComposeProjectionMatrix(const double focal_length[2],\n                             const double principle_point[2],\n                             const double rotation[9],\n                             const double translation[3],\n                             double projection_matrix[12]) {\n  Matrix3d camera_matrix;\n  camera_matrix << focal_length[0], 0.0, principle_point[0],\n      0.0, focal_length[1], principle_point[1],\n      0.0, 0.0, 1.0;\n\n  Map<Matrix<double, 3, 4> > proj_mat(projection_matrix);\n  proj_mat.block<3, 3>(0, 0) = Map<const Matrix3d>(rotation);\n  proj_mat.block<3, 1>(0, 3) = Map<const Vector3d>(translation);\n}\n\n// Adds noise to the 3D point passed in.\nvoid AddNoiseToPoint(const double noise_factor, Vector3d* point) {\n  *point += Vector3d((-0.5 + RandDouble(0.0, 1.0)) * 2.0 * noise_factor,\n                     (-0.5 + RandDouble(0.0, 1.0)) * 2.0 * noise_factor,\n                     (-0.5 + RandDouble(0.0, 1.0)) * 2.0 * noise_factor);\n}\n\n// Adds noise to the ray i.e. the projection of the point.\nvoid AddNoiseToProjection(const double noise_factor, Vector2d* ray) {\n  const double noise_x = (-0.5 + RandDouble(0.0, 1.0)) * 2.0 * noise_factor;\n  const double noise_y = (-0.5 + RandDouble(0.0, 1.0)) * 2.0 * noise_factor;\n\n  *ray = Vector2d(ray->x() + noise_x, ray->y() + noise_y);\n}\n\nvoid AddGaussianNoise(const double noise_factor, Vector2d* ray) {\n  const double noise_x = RandGaussian(0.0, noise_factor);\n  const double noise_y = RandGaussian(0.0, noise_factor);\n  *ray = Vector2d(ray->x() + noise_x, ray->y() + noise_y);\n}\n\nvoid CreateRandomPointsInFrustum(const double near_plane_width,\n                                 const double near_plane_height,\n                                 const double near_plane_depth,\n                                 const double far_plane_depth,\n                                 const int num_points,\n                                 std::vector<Eigen::Vector3d>* random_points) {\n  random_points->reserve(num_points);\n  for (int i = 0; i < num_points; i++) {\n    const double rand_depth = RandDouble(near_plane_depth, far_plane_depth);\n    const double x_radius = near_plane_width * rand_depth / near_plane_depth;\n    const double y_radius = near_plane_height * rand_depth / near_plane_depth;\n    Vector3d rand_point(RandDouble(-x_radius, x_radius),\n                        RandDouble(-y_radius, y_radius), rand_depth);\n    random_points->push_back(rand_point);\n  }\n}\n\n// For an E or F that is defined such that y^t * E * x = 0\ndouble SampsonDistance(const Matrix3d& F, const Vector2d& x,\n                       const Vector2d& y) {\n  const Vector3d epiline_x = F * x.homogeneous();\n  const Vector3d epiline_y = F.transpose() * y.homogeneous();\n\n  const double numerator_sqrt = y.homogeneous().dot(epiline_x);\n  const double denominator = epiline_x.hnormalized().squaredNorm() +\n                             epiline_y.hnormalized().squaredNorm();\n\n  // Finally, return the complete Sampson distance.\n  return numerator_sqrt * numerator_sqrt / denominator;\n}\n\nEigen::Matrix3d CrossProductMatrix(const Vector3d& cross_vec) {\n  Matrix3d cross;\n  cross << 0.0, -cross_vec.z(), cross_vec.y(),\n      cross_vec.z(), 0.0, -cross_vec.x(),\n      -cross_vec.y(), cross_vec.x(), 0.0;\n  return cross;\n}\n\n// Computes the normalization matrix transformation that centers image points\n// around the origin with an average distance of sqrt(2) to the centroid.\n// Returns the transformation matrix and the transformed points. This assumes\n// that no points are at infinity.\nbool NormalizeImagePoints(\n    const std::vector<Vector2d>& image_points,\n    std::vector<Vector2d>* normalized_image_points,\n    Matrix3d* normalization_matrix) {\n  Eigen::Map<const Matrix<double, 2, Eigen::Dynamic> > image_points_mat(\n      image_points[0].data(), 2, image_points.size());\n\n  // Allocate the output vector and map an Eigen object to the underlying data\n  // for efficient calculations.\n  normalized_image_points->clear();\n  normalized_image_points->resize(image_points.size());\n  Eigen::Map<Matrix<double, 2, Eigen::Dynamic> >\n      normalized_image_points_mat((*normalized_image_points)[0].data(), 2,\n                                  image_points.size());\n\n  // Compute centroid.\n  const Vector2d centroid(image_points_mat.rowwise().mean());\n\n  // Calculate average distance to centroid.\n  const double mean_dist = (image_points_mat.colwise() - centroid).norm();\n\n  // Create normalization matrix.\n  const double norm_factor = sqrt(2.0) / mean_dist;\n  *normalization_matrix << norm_factor, 0, -1.0 * norm_factor* centroid.x(),\n      0, norm_factor, -1.0 * norm_factor * centroid.y(),\n      0, 0, 1;\n\n  // Normalize image points.\n  const Matrix<double, 3, Eigen::Dynamic> normalized_homog_points =\n      (*normalization_matrix) * image_points_mat.colwise().homogeneous();\n  normalized_image_points_mat = normalized_homog_points.colwise().hnormalized();\n\n  return true;\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "3b5f7f797dfebcc4fea5f132834759dc26eb58c0", "size": 7013, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/vision/sfm/pose/util.cc", "max_stars_repo_name": "nuernber/Theia", "max_stars_repo_head_hexsha": "4bac771b09458a46c44619afa89498a13cd39999", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-02T13:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T13:30:52.000Z", "max_issues_repo_path": "src/theia/vision/sfm/pose/util.cc", "max_issues_repo_name": "nuernber/Theia", "max_issues_repo_head_hexsha": "4bac771b09458a46c44619afa89498a13cd39999", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/vision/sfm/pose/util.cc", "max_forks_repo_name": "nuernber/Theia", "max_forks_repo_head_hexsha": "4bac771b09458a46c44619afa89498a13cd39999", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-28T08:43:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-28T08:43:13.000Z", "avg_line_length": 42.503030303, "max_line_length": 80, "alphanum_fraction": 0.6861542849, "num_tokens": 1690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118493816806, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.2697544143018108}}
{"text": "/* ============================================================================\n * Copyright (c) 2009-2016 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\n#pragma once\n\n#include <algorithm>\n#include <cassert> /* assert */\n#include <complex>\n#include <iostream>\n#include <string>\n\n#if __APPLE__\n#include <Accelerate/Accelerate.h>\n#endif\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Eigen>\n\n#include \"EbsdLib/Core/Quaternion.hpp\"\n#include \"EbsdLib/EbsdLib.h\"\n#include \"EbsdLib/Math/EbsdMatrixMath.h\"\n#include \"EbsdLib/Utilities/ModifiedLambertProjection3D.hpp\"\n\n/* This comment block is commented as Markdown. if you paste this into a text\n * editor then render it with a Markdown aware system a nice table should show\n * up for you.\n\n ## Function Mapping Check List ##\n\n#### Master Table of Conversions ####\n\n| From/To |  e   |  o   |  a   |  r   |  q   |  h   |  c   |\n|  -      |  -   |  -   |  -   |  -   |  -   |  -   |  -   |\n|  e      |  -   |  X   |  X   |  X   |  X   |  a   | ah   |\n|  o      |  X   |  --  |  X   |  e   |  X   |  a   | ah   |\n|  a      |  o   |  X   | --   |  X   |  X   |  X   |  h   |\n|  r      |  o   |  a   |  X   | --   |  a   |  X   |  h   |\n|  q      |  X   |  X   |  X   |  X   | --   |  X   |  h   |\n|  h      |  ao  |  a   |  X   |  a   |  a   | --   |  X   |\n|  c      | hao  |  ha  |  h   |  ha  | ha   |  X   | --   |\n\n\n#### DREAM3D Implemented ####\n\n\n| From/To |  e   |  o   |  a   |  r   |  q   |  h   |  c   |\n|  -      |  -   |  -   |  -   |  -   |  -   |  -   |  -   |\n|  e      |  #   |  X   |  X   |  X   |  X   |  a   |  X   |\n|  o      |  X   |  #   |  @   |  X   |  X   |  a   |  -   |\n|  a      |  X   |  X   |  #   |  X   |  X   |  X   |  -   |\n|  r      |  X   |  X   |  X   |  #   |  X   |  X   |  -   |\n|  q      |  X   |  X   |  X   |  X   |  #   |  X   |  -   |\n|  h      |  X   |  X   |  X   |  X   |  X   |  #   |  X   |\n|  c      |  -   |  -   |  -   |  -   |  -   |  X   |  #   |\n*/\n\n/**\n * The Orientation codes are written in such a way that the value of -1 indicates\n * an Active Rotation and +1 indicates a passive rotation.\n *\n * DO NOT UNDER ANY CIRCUMSTANCE CHANGE THESE VARIABLES. THERE WILL BE BAD\n * CONSEQUENCES IF THESE ARE CHANGED. EVERY PIECE OF CODE THAT RELIES ON THESE\n * FUNCTIONS WILL BREAK. IN ADDITION, THE QUATERNION ARITHMETIC WILL NO LONGER\n * BE CONSISTENT WITH ROTATION ARITHMETIC.\n *\n * YOU HAVE BEEN WARNED.\n *\n * Adam  Morawiec's book uses Passive rotations.\n **/\n#ifndef DREAM3D_PASSIVE_ROTATION\n// #define DREAM3D_ACTIVE_ROTATION               -1.0\n#define DREAM3D_PASSIVE_ROTATION 1\n#endif\n\n#ifndef ROTATIONS_CONSTANTS\n#define ROTATIONS_CONSTANTS\nnamespace Rotations::Constants\n{\n#if DREAM3D_PASSIVE_ROTATION\nstatic const float epsijk = 1.0f;\nstatic const double epsijkd = 1.0;\n#elif DREAM3D_ACTIVE_ROTATION\nstatic const float epsijk = -1.0f;\nstatic const double epsijkd = -1.0;\n#endif\n} // namespace Rotations::Constants\n\n#endif\n\n// Add some shortened namespace alias\n// Condense some of the namespaces to same some typing later on.\nnamespace LPs = EbsdLib::LambertParametersType;\nnamespace RConst = Rotations::Constants;\nnamespace DConst = EbsdLib::Constants;\n\n/**\n * @brief The OrientationTransformation namespace\n * template parameter InputType can be one of std::vector<T>, std::vector<T> or OrientationArray<T>\n * and template parameter typename OutputType::value_type is the type specified in T. For example if InputType is std::vector<float>\n * then typename OutputType::value_type is float.\n */\nnamespace OrientationTransformation\n{\n\n// using RotationMatrixType = Eigen::Matrix<K, 3, 3, Eigen::RowMajor>;\n// using RotationMatrixMapType = Eigen::Map<RotationMatrixType>;\n// using OMHelperType = ArrayHelpers<T, K>;\n\nstruct ResultType\n{\n  int result;\n  std::string msg;\n};\n\n// static void FatalError(const std::string& func, const std::string& msg)\n//{\n//  std::cout << func << \"::\" << msg << std::endl;\n//}\n/* ###################################################################\n Original Fotran codes written by Dr. Marc De Graef.\n\n* MODULE: rotations\n*\n* @brief everything that has to do with rotations and conversions between rotations\n*\n* @details This file relies a lot on the relations listed in the book \"Orientations\n* and Rotations\" by Adam Morawiec [Springer 2004].  I've tried to implement every\n* available representation for rotations in a way that makes it easy to convert\n* between any pair.  Needless to say, this needs extensive testing and debugging...\n*\n* Instead of converting all the time between representations, I've opted to\n* \"waste\" a little more memory and time and provide the option to precompute all the representations.\n* This way all representations are available via a single data structure.\n*\n* Obviously, the individual conversion routines also exist and can be called either in\n* single or in double precision (using a function interface for each call, so that only\n* one function name is used).  The conversion routines use the following format for their\n* call name:  ab2cd, where (ab and cd are two-characters strings selected from the following\n* possibilities: [the number in parenthesis lists the number of entries that need to be provided]\n*\n* eu : euler angle representation (3)\n* om : orientation matrix representation (3x3)\n* ax : axis angle representation (4)\n* ro : Rodrigues vector representation (3)\n* qu : unit quaternion representation (4)\n* ho : homochoric representation (3)\n* cu : cubochoric representation (3).\n*\n* hence, conversion from homochoric to euler angle is called as ho2eu(); the argument of\n* each routine must have the correct number of dimensions and entries.\n* All 42 conversion routines exist in both single and double precision.\n*\n* Some routines were modified in July 2014, to simplify the paths in case the direct conversion\n* routine does not exist.  Given the complexity of the cubochoric transformations, all routines\n* going to and from this representation will require at least one and sometimes two or three\n* intermediate representations.  cu2eu and qu2cu currently represent the longest computation\n* paths with three intermediate steps each.\n*\n* In August 2014, all routines were modified to account for active vs. passive rotations,\n* after some inconsistencies were discovered that could be traced back to that distinction.\n* The default is for a rotation to be passive, and only those transformation rules have been\n* implemented.  For active rotations, the user needs to explicitly take action in the calling\n* program by setting the correct option in the ApplyRotation function.\n*\n* Testing: the program rotationtest.f90 was generated by an IDL script and contains all possible\n* pairwise and triplet transformations, using a series of input angle combinations; for now, these\n* are potentially problematic Euler combinations.\n*\n* The conventions of this module are:\n*\n* - all reference frames are right-handed and orthonormal (except for the Bravais frames)\n* - a rotation angle is positive for a counterclockwise rotation when viewing along the positive rotation axis towards the origin\n* - all rotations are interpreted in the passive way\n* - Euler angles follow the Bunge convention, with phi1 in [0,2pi], Phi in [0,pi], and phi2 in [0,2pi]\n* - rotation angles (in axis-angle derived representations) are limited to the range [0,pi]\n*\n* To make things easier for the user, this module provides a routine to create a rotation\n* representation starting from an axis, described by a unit axis vector, and a rotation angle.\n* This routine properly takes the sign of epsijk into account, and always produces a passive rotation.\n* The user must explicitly take action to interpret a rotation a being active.\n*\n* @date 08/04/13 MDG 1.0 original\n* @date 07/08/14 MDG 2.0 modifications to several routines (mostly simplifications)\n* @date 08/08/14 MDG 3.0 added active/passive handling (all routines passive)\n* @date 08/11/14 MDG 3.1 modified Rodrigues vector to 4 components (n and length) to accomodate Infinity\n* @date 08/18/14 MDG 3.2 added RotateVector, RotateTensor2 routines with active/passive switch\n* @date 08/20/14 MDG 3.3 completed extensive testing of epsijk<0 mode; all tests passed for the first time !\n* @date 08/21/14 MDG 3.4 minor correction in om2ax to get things to work for epsijk>0 mode; all tests passed!\n* @date 09/30/14 MDG 3.5 added routines to make rotation definitions easier\n* @date 09/30/14 MDG 3.6 added strict range checking routines for all representations (tested on 10/1/14)\n//--------------------------------------------------------------------------\n//--------------------------------\n* routines to check the validity range of rotation representations\n//--------------------------------\n* general rotation creation routine, to make sure that a rotation representation is\n* correctly initialized, takes an axis and an angle as input, returns an orientationtype structure\n* general interface routine to populate the orientation type\n//--------------------------------\n* convert Euler angles to 3x3 orientation matrix\n* convert Euler angles to axis angle\n* convert Euler angles to Rodrigues vector\n* convert Euler angles to quaternion\n* convert Euler angles to homochoric\n* convert Euler angles to cubochoric\n//--------------------------------\n* convert 3x3 orientation matrix to Euler angles\n* convert 3x3 orientation matrix to axis angle\n* convert 3x3 orientation matrix to Rodrigues\n* convert 3x3 rotation matrix to quaternion\n* convert 3x3 rotation matrix to homochoric\n* convert 3x3 rotation matrix to cubochoric\n//--------------------------------\n* convert axis angle pair to euler\n* convert axis angle pair to orientation matrix\n* convert axis angle pair to Rodrigues\n* convert axis angle pair to quaternion\n* convert axis angle pair to homochoric representation\n* convert axis angle pair to cubochoric\n//--------------------------------\n* convert Rodrigues vector to Euler angles\n* convert Rodrigues vector to orientation matrix\n* convert Rodrigues vector to axis angle pair\n* convert Rodrigues vector to quaternion\n* convert Rodrigues vector to homochoric\n* convert Rodrigues vector to cubochoric\n//--------------------------------\n* convert quaternion to Euler angles\n* convert quaternion to orientation matrix\n* convert quaternion to axis angle\n* convert quaternion to Rodrigues\n* convert quaternion to homochoric\n* convert quaternion to cubochoric\n//--------------------------------\n* convert homochoric to euler\n* convert homochoric to orientation matrix\n* convert homochoric to axis angle pair\n* convert homochoric to Rodrigues\n* convert homochoric to quaternion\n* convert homochoric to cubochoric\n//--------------------------------\n* convert cubochoric to euler\n* convert cubochoric to orientation matrix\n* convert cubochoric to axis angle\n* convert cubochoric to Rodrigues\n* convert cubochoric to quaternion\n* convert cubochoric to homochoric\n* apply a rotation to a vector\n* apply a rotation to a second rank tensor\n//--------------------------------\n* print quaternion and equivalent 3x3 rotation matrix\n*/\n\n/**: eu_check\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief verify that the Euler angles are in the correct respective ranges\n *\n * @param eu 3-component vector\n *\n *\n * @date 9/30/14   MDG 1.0 original\n */\ntemplate <typename T>\nResultType eu_check(const T& eu)\n{\n  ResultType res;\n  res.result = 1;\n\n  if((eu[0] < 0.0) || (eu[0] > (EbsdLib::Constants::k_2PiD)))\n  {\n    res.msg = \"rotations:eu_check:: phi1 Euler angle outside of valid range [0,2pi]\";\n    res.result = -1;\n  }\n  if((eu[1] < 0.0) || (eu[1] > EbsdLib::Constants::k_PiD))\n  {\n    res.msg = \"rotations:eu_check:: Phi Euler angle outside of valid range [0,pi]\";\n    res.result = -2;\n  }\n  if((eu[2] < 0.0) || (eu[2] > (EbsdLib::Constants::k_2PiD)))\n  {\n    res.msg = \"rotations:eu_check:: phi2 Euler angle outside of valid range [0,2pi]\";\n    res.result = -3;\n  }\n  return res;\n}\n\n/**: ro_check\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief verify that the Rodrigues vector has positive length and unit axis vector\n *\n * @param ro 4-component vector ( <v0, v1, v2>, L )\n *\n *\n * @date 9/30/14   MDG 1.0 original\n */\ntemplate <typename InputType>\nResultType ro_check(const InputType& ro)\n{\n  typename InputType::value_type eps = static_cast<typename InputType::value_type>(1.0E-6L);\n  ResultType res;\n  res.result = 1;\n  if(ro[3] < 0.0L)\n  {\n    res.msg = \"rotations:ro_check:: Rodrigues-Frank vector has negative length: \";\n    res.result = -1;\n    return res;\n  }\n  typename InputType::value_type ttl = std::sqrt(ro[0] * ro[0] + ro[1] * ro[1] + ro[2] * ro[2]);\n\n  if(std::fabs(ttl - 1.0) > eps)\n  {\n    res.msg = \"rotations:ro_check:: Rodrigues-Frank axis vector not normalized\";\n    res.result = -2;\n  }\n  return res;\n}\n\n/**: ho_check\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief verify that the homochoric vector is inside or on the homochoric ball\n *\n * @param ho 3-component vector\n *\n *\n * @date 9/30/14   MDG 1.0 original\n */\ntemplate <typename InputType>\nResultType ho_check(const InputType& ho)\n{\n  using value_type = typename InputType::value_type;\n  ResultType res;\n  res.result = 1;\n\n  value_type r = std::sqrt(ho[0] * ho[0] + ho[1] * ho[1] + ho[2] * ho[2]);\n\n  if(r > static_cast<float>(LPs::R1))\n  {\n    res.msg = \"rotations:ho_check: homochoric vector outside homochoric ball\";\n    res.result = -1;\n  }\n  return res;\n}\n\n/**: cu_check\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief verify that the cubochoric vector is inside or on the cube\n *\n * @param cu 3-component vector\n *\n *\n * @date 9/30/14   MDG 1.0 original\n */\ntemplate <typename InputType>\nResultType cu_check(const InputType& cu)\n{\n  using ValueType = typename InputType::value_type;\n  ResultType res;\n  res.result = 1;\n\n  ValueType maxValue = static_cast<ValueType>(LPs::ap / 2.0);\n  bool maxValueHit = false;\n\n  std::for_each(cu.begin(), cu.end(), [&](const ValueType& v) {\n    ValueType value = std::fabs(v);\n    if(value > maxValue)\n    {\n      maxValueHit = true;\n    }\n  });\n\n  if(maxValueHit)\n  {\n    res.msg = \"rotations:cu_check: cubochoric vector outside cube\";\n    res.result = -1;\n  }\n  return res;\n}\n\n/**: qu_check\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief verify that the quaternion has unit length and positive scalar part\n *\n * @param qu 4-component vector (w, <v0, v1, v2> )\n *\n *\n * @date 9/30/14   MDG 1.0 original\n */\ntemplate <typename InputType>\nResultType qu_check(const InputType& qu, typename Quaternion<typename InputType::value_type>::Order layout = Quaternion<typename InputType::value_type>::Order::VectorScalar)\n{\n  using SizeType = typename InputType::size_type;\n  SizeType w = 0;\n  SizeType x = 1;\n  SizeType y = 2;\n  SizeType z = 3;\n  if(layout == Quaternion<typename InputType::value_type>::Order::VectorScalar)\n  {\n    w = 3;\n    x = 0;\n    y = 1;\n    z = 2;\n  }\n  ResultType res;\n  res.result = 1;\n\n  if(qu[w] < 0.0)\n  {\n    res.msg = \"rotations:qu_check: quaternion must have positive scalar part\";\n    res.result = -1;\n    return res;\n  }\n\n  typename InputType::value_type eps = std::numeric_limits<typename InputType::value_type>::epsilon();\n  typename InputType::value_type r = std::sqrt(qu[x] * qu[x] + qu[y] * qu[y] + qu[z] * qu[z] + qu[w] * qu[w]);\n  if(fabs(r - 1.0) > eps)\n  {\n    res.msg = \"rotations:qu_check: quaternion must have unit norm\";\n    res.result = -2;\n  }\n  return res;\n}\n\n/**: ax_check\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief verify that the axis angle pair has a unit vector and angle in the correct range\n *\n * @param ax 4-component vector (<ax0, ax1, ax2>, angle )\n *\n *\n * @date 9/30/14   MDG 1.0 original\n */\ntemplate <typename InputType>\nResultType ax_check(const InputType& ax)\n{\n  using value_type = typename InputType::value_type;\n  ResultType res;\n  res.result = 1;\n  if((ax[3] < 0.0) || (ax[3] > EbsdLib::Constants::k_PiD))\n  {\n    res.msg = \"rotations:ax_check: angle must be in range [0,pi]\";\n    res.result = -1;\n    return res;\n  }\n  typename InputType::value_type eps = std::numeric_limits<value_type>::epsilon();\n\n  typename InputType::value_type r = std::sqrt(ax[0] * ax[0] + ax[1] * ax[1] + ax[2] * ax[2]);\n  typename InputType::value_type absv = static_cast<typename InputType::value_type>(fabs(r - 1.0));\n\n  if(absv > eps)\n  {\n    res.msg = \"rotations:ax_check: axis-angle axis vector must have unit norm\";\n    res.result = -2;\n  }\n  return res;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\ntemplate <typename T>\nvoid Print_OM(const T& om)\n{\n  printf(\"OM: /    % 3.16f    % 3.16f    % 3.16f    \\\\\\n\", om[0], om[1], om[2]);\n  printf(\"OM: |    % 3.16f    % 3.16f    % 3.16f    |\\n\", om[3], om[4], om[5]);\n  printf(\"OM: \\\\    % 3.16f    % 3.16f    % 3.16f    /\\n\", om[6], om[7], om[8]);\n}\n\n/**: om_check\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief verify that the rotation matrix is actually a proper rotation matrix\n *\n * @param om 3x3-component matrix\n *\n *\n * @date 9/30/14   MDG 1.0 original\n */\ntemplate <typename InputType>\nResultType om_check(const InputType& om)\n{\n  ResultType res;\n  res.result = 1;\n  using ValueType = typename InputType::value_type;\n  ValueType threshold = static_cast<ValueType>(1.0E-5L);\n  using RotationMatrixType = Eigen::Matrix<ValueType, 3, 3, Eigen::RowMajor>;\n  using RotationMatrixMapType = Eigen::Map<RotationMatrixType>;\n  RotationMatrixMapType omE(const_cast<ValueType*>(om.data()));\n\n  ValueType det = omE.determinant();\n\n  std::stringstream ss;\n  if(det < 0.0)\n  {\n    ss << \"rotations:om_check: Determinant of rotation matrix must be positive: \" << det;\n    res.msg = ss.str();\n    res.result = -1;\n    return res;\n  }\n\n  ValueType r = fabs(det - static_cast<ValueType>(1.0L));\n  if(!EbsdLibMath::closeEnough(r, static_cast<ValueType>(0.0L), threshold))\n  {\n    ss << \"rotations:om_check: Determinant (\" << det << \") of rotation matrix must be unity (1.0)\";\n    res.msg = ss.str();\n    res.result = -2;\n    return res;\n  }\n\n  RotationMatrixType abv = (omE * omE.transpose()).cwiseAbs();\n\n  RotationMatrixType identity;\n  identity.setIdentity();\n\n  identity = identity - abv;\n  identity = identity.cwiseAbs();\n\n  for(int c = 0; c < 3; c++)\n  {\n    for(int r = 0; r < 3; r++)\n    {\n      if(identity(r, c) > threshold)\n      {\n        std::stringstream ss;\n        ss << \"rotations:om_check: rotation matrix times transpose must be identity matrix: (\";\n        ss << r << \", \" << c << \") = \" << abv(r, c);\n        res.msg = ss.str();\n        res.result = -3;\n      }\n    }\n  }\n\n  return res;\n}\n\n#if 0\n    /**: genrot\n    *\n    * @author Marc De Graef, Carnegie Mellon University\n    *\n    * @brief generate a passive rotation representation, given the unit axis vector and the rotation angle\n    *\n    * @param av 3-component vector\n    * @param omega rotation angle (radians)\n    *\n    *\n    * @date 9/30/14   MDG 1.0 original\n    */\n    template <typename InputType, typename OutputType> void genrot(const T& av, typename OutputType::value_type omega, OutputType& res)\n    {\n      //*** use local\n      //*** use constants\n      //*** use error\n      //*** IMPLICIT NONE\n      //real(kind=sgl),INTENT(IN)       :: av[2]\n      //real(kind=sgl),INTENT(IN)       :: omega\n      type(orientationtype)           :: res;\n      typename OutputType::value_type axang[4];\n      typename OutputType::value_type s;\n\n      if ((omega < 0.0) || (omega > M_PI))\n      {\n        assert(false);\n      }\n\n      axang[0] = -RConst::epsijk * av[0];\n      axang[1] = -RConst::epsijk * av[1];\n      axang[2] = -RConst::epsijk * av[2];\n      axang[3] = omega;\n      s = sqrt(sumofSquares(av));\n\n      if (s != 0.0)\n      {\n        axang[0] = axang[0] / s;\n        axang[1] = axang[1] / s;\n        axang[2] = axang[2] / s;\n      }\n      else\n      {\n        assert(false);\n      }\n      init_orientation(axang, 'ax', res);\n    }\n\n\n\n    /**: init_orientation\n    *\n    * @author Marc De Graef, Carnegie Mellon University\n    *\n    * @brief take an orientation representation with 3 components and init all others\n    *\n    * @param orient 3-component vector\n    * @param intype input type ['eu', 'ro', 'ho', 'cu']\n    * @param rotcheck  optional parameter to enforce strict range checking\n    *\n    * @date 8/04/13   MDG 1.0 original\n    * @date 9/30/14   MDG 1.1 added testing of valid ranges\n    */\n\n    template <typename InputType, typename OutputType>\nvoid init_orientation(const T& orient, char intype[2], bool rotcheck, OutputType& res)\n    {\n\n    }\n\n    /**: init_orientation_om\n    *\n    * @author Marc De Graef, Carnegie Mellon University\n    *\n    * @brief take an orientation representation with 3x3 components and init all others\n    *\n    * @param orient r-component vector\n    * @param intype input type ['om']\n    * @param rotcheck  optional parameter to enforce strict range checking\n    *\n    *\n    * @date 8/04/13   MDG 1.0 original\n    */\n\n    void init_orientation_om(float* orient, char intype[2], bool rotcheck, float* res);\n#endif\n\n/**: eu2om\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief Euler angles to orientation matrix  [Morawiec, page 28]\n * also from Appendix 1, equation 1 in\n *\n * Consistent representations of and conversions between 3D rotations\n * D Rowenhorst, A D Rollett, G S Rohrer, M Groeber, M Jackson, P J Konijnenberg, and M De Graef\n * Published 5 October 2015 IOP Publishing Ltd\n * Modelling and Simulation in Materials Science and Engineering, Volume 23, Number 8\n *\n * The output orientation matrix is laid out in memory such that the following is true:\n *       |  c1c2-s1cs2      s1c2+c1cs2    ss2 |\n * OM =  | -c1s2-s1cc2     -s1s2+c1cc2    sc2 |\n *       |      s1s           -c1s         c  |\n *\n *       | res[0]   res[1]  res[2] |\n * OM =  | res[3]   res[4]  res[5] |\n *       | res[6]   res[7]  res[8] |\n *\n * @param e 3 Euler angles in radians\n *\n *\n * @date 8/04/13   MDG 1.0 original\n * @date 7/23/14   MDG 1.1 verified\n */\ntemplate <typename InputType, typename OutputType>\nOutputType eu2om(const InputType& e)\n{\n  OutputType om(9);\n  // typename OutputType::value_type eps = std::numeric_limits<typename OutputType::value_type>::epsilon();\n  using ValueType = typename OutputType::value_type;\n\n  ValueType eps = 1.0E-7f;\n\n  ValueType c1 = cos(e[0]);\n  ValueType c = cos(e[1]);\n  ValueType c2 = cos(e[2]);\n  ValueType s1 = sin(e[0]);\n  ValueType s = sin(e[1]);\n  ValueType s2 = sin(e[2]);\n  om[0] = c1 * c2 - s1 * s2 * c;\n  om[1] = s1 * c2 + c1 * s2 * c;\n  om[2] = s2 * s;\n  om[3] = -c1 * s2 - s1 * c2 * c;\n  om[4] = -s1 * s2 + c1 * c2 * c;\n  om[5] = c2 * s;\n  om[6] = s1 * s;\n  om[7] = -c1 * s;\n  om[8] = c;\n  for(size_t i = 0; i < 9; i++)\n  {\n    if(fabs(om[i]) < eps)\n    {\n      om[i] = 0.0;\n    }\n  }\n  return om;\n}\n\n/**: eu2ax\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert euler to axis angle\n *\n * @param e 3 euler angles\n *\n *\n * @date 8/12/13   MDG 1.0 original\n * @date 7/23/14   MDG 2.0 explicit implementation\n * @date 7/23/14   MDG 2.1 exception for zero rotation angle\n */\ntemplate <typename InputType, typename OutputType>\nOutputType eu2ax(const InputType& e)\n{\n  OutputType res(4);\n  using value_type = typename OutputType::value_type;\n  value_type thr = static_cast<value_type>(1.0E-6);\n  value_type alpha = static_cast<value_type>(0.0);\n  value_type t = static_cast<value_type>(tan(e[1] * 0.5));\n  value_type sig = static_cast<value_type>(0.5 * (e[0] + e[2]));\n  value_type del = static_cast<value_type>(0.5 * (e[0] - e[2]));\n  value_type tau = static_cast<value_type>(std::sqrt(t * t + sin(sig) * sin(sig)));\n  if(EbsdLibMath::closeEnough(sig, static_cast<typename OutputType::value_type>(EbsdLib::Constants::k_PiOver2D), static_cast<typename OutputType::value_type>(1.0E-6L)))\n  {\n    alpha = static_cast<value_type>(EbsdLib::Constants::k_PiD);\n  }\n  else\n  {\n    alpha = static_cast<value_type>(2.0 * atan(tau / cos(sig))); //! return a default identity axis-angle pair\n  }\n\n  if(fabs(alpha) < thr)\n  {\n    res[0] = 0.0;\n    res[1] = 0.0;\n    res[2] = 1.0;\n    res[3] = 0.0;\n  }\n  else\n  {\n    //! passive axis-angle pair so a minus sign in front\n    res[0] = static_cast<value_type>(-RConst::epsijkd * t * cos(del) / tau);\n    res[1] = static_cast<value_type>(-RConst::epsijkd * t * sin(del) / tau);\n    res[2] = static_cast<value_type>(-RConst::epsijkd * sin(sig) / tau);\n    res[3] = alpha;\n\n    if(alpha < 0.0)\n    {\n      res[0] = -res[0];\n      res[1] = -res[1];\n      res[2] = -res[2];\n      res[3] = -res[3];\n    }\n  }\n\n  return res;\n}\n\n/**: eu2ro\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief Euler angles to Rodrigues vector  [Morawiec, page 40]\n *\n * @param e 3 Euler angles in radians\n *\n *\n * @date 8/04/13   MDG 1.0 original\n */\ntemplate <typename InputType, typename OutputType>\nOutputType eu2ro(const InputType& e)\n{\n  typename OutputType::value_type thr = 1.0E-6f;\n\n  OutputType res = eu2ax<InputType, OutputType>(e);\n  typename OutputType::value_type t = res[3];\n  if(std::fabs(t - EbsdLib::Constants::k_PiD) < thr)\n  {\n    res[3] = std::numeric_limits<typename OutputType::value_type>::infinity();\n    return res;\n  }\n\n  if(t == 0.0)\n  {\n    res[0] = 0.0;\n    res[1] = 0.0;\n    res[2] = 0.0;\n    res[3] = 0.0;\n  }\n  else\n  {\n    res[3] = static_cast<typename OutputType::value_type>(tan(t * 0.5));\n  }\n  return res;\n}\n\n/**: eu2qu\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief Euler angles to quaternion  [Morawiec, page 40]\n *\n * @note verified 8/5/13\n *\n * @param e 3 Euler angles in radians\n * @param Quaternion can be of form Scalar<Vector> or <Vector>Scalar in memory. The\n * default is (Scalar, <Vector>)\n *\n * @date 8/04/13   MDG 1.0 original\n * @date 8/07/14   MDG 1.1 verified\n */\n\ntemplate <typename InputType, typename OutputType>\nOutputType eu2qu(const InputType& e, typename Quaternion<typename OutputType::value_type>::Order layout = Quaternion<typename OutputType::value_type>::Order::VectorScalar)\n{\n  OutputType res(4);\n  using SizeType = typename OutputType::size_type;\n  SizeType w = 0;\n  SizeType x = 1;\n  SizeType y = 2;\n  SizeType z = 3;\n  if(layout == Quaternion<typename OutputType::value_type>::Order::VectorScalar)\n  {\n    w = 3;\n    x = 0;\n    y = 1;\n    z = 2;\n  }\n  using OutputValueType = typename OutputType::value_type;\n  std::array<OutputValueType, 3> ee = {0.0f, 0.0f, 0.0f};\n  OutputValueType cPhi = 0.0f;\n  OutputValueType cp = 0.0f;\n  OutputValueType cm = 0.0f;\n  OutputValueType sPhi = 0.0f;\n  OutputValueType sp = 0.0f;\n  OutputValueType sm = 0.0f;\n\n  ee[0] = static_cast<OutputValueType>(0.5 * e[0]);\n  ee[1] = static_cast<OutputValueType>(0.5 * e[1]);\n  ee[2] = static_cast<OutputValueType>(0.5 * e[2]);\n\n  cPhi = cos(ee[1]);\n  sPhi = sin(ee[1]);\n  cm = cos(ee[0] - ee[2]);\n  sm = sin(ee[0] - ee[2]);\n  cp = cos(ee[0] + ee[2]);\n  sp = sin(ee[0] + ee[2]);\n  res[w] = cPhi * cp;\n  res[x] = -RConst::epsijk * sPhi * cm;\n  res[y] = -RConst::epsijk * sPhi * sm;\n  res[z] = -RConst::epsijk * cPhi * sp;\n\n  if(res[w] < 0.0)\n  {\n    res[w] = -res[w];\n    res[x] = -res[x];\n    res[y] = -res[y];\n    res[z] = -res[z];\n  }\n  return res;\n}\n\n/**: om2eu\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief orientation matrix to euler angles\n *\n * @note verified 8/19/14 using Mathematica\n *\n * @param o orientation matrix\n * @param res Euler Angles\n *\n * @date 8/04/13   MDG 1.0 original\n * @date 8/19/14   MDG 1.1 verification using Mathematica\n */\ntemplate <typename InputType, typename OutputType>\nOutputType om2eu(const InputType& o)\n{\n  using OutputValueType = typename OutputType::value_type;\n  OutputType res(3);\n  typename OutputType::value_type zeta = 0.0;\n  bool close = EbsdLibMath::closeEnough(std::fabs(o[8]), static_cast<typename OutputType::value_type>(1.0), static_cast<typename OutputType::value_type>(1.0E-6));\n  if(!close)\n  {\n    res[1] = acos(o[8]);\n    zeta = static_cast<typename OutputType::value_type>(1.0 / sqrt(1.0 - o[8] * o[8]));\n    res[0] = atan2(o[6] * zeta, -o[7] * zeta);\n    res[2] = atan2(o[2] * zeta, o[5] * zeta);\n  }\n  else\n  {\n    close = EbsdLibMath::closeEnough(o[8], static_cast<typename OutputType::value_type>(1.0), static_cast<typename OutputType::value_type>(1.0E-6));\n    if(close)\n    {\n      res[0] = atan2(o[1], o[0]);\n      res[1] = 0.0;\n      res[2] = 0.0;\n    }\n    else\n    {\n      res[0] = static_cast<OutputValueType>(-atan2(-o[1], o[0]));\n      res[1] = static_cast<OutputValueType>(EbsdLib::Constants::k_PiD);\n      res[2] = 0.0;\n    }\n  }\n\n  if(res[0] < 0.0)\n  {\n    res[0] = static_cast<typename OutputType::value_type>(fmod(res[0] + 100.0 * DConst::k_PiD, DConst::k_2PiD));\n  }\n  if(res[1] < 0.0)\n  {\n    res[1] = static_cast<typename OutputType::value_type>(fmod(res[1] + 100.0 * DConst::k_PiD, DConst::k_PiD));\n  }\n  if(res[2] < 0.0)\n  {\n    res[2] = static_cast<typename OutputType::value_type>(fmod(res[2] + 100.0 * DConst::k_PiD, DConst::k_2PiD));\n  }\n  return res;\n}\n\n/**: ax2om\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief Axis angle pair to orientation matrix\n *\n * @note verified 8/5/13.\n *\n * @param a axis angle pair\n *\n *\n * @date 8/04/13   MDG 1.0 original\n */\ntemplate <typename InputType, typename OutputType>\nOutputType ax2om(const InputType& a)\n{\n  OutputType res(9);\n  using value_type = typename OutputType::value_type;\n  value_type q = 0.0L;\n  value_type c = 0.0L;\n  value_type s = 0.0L;\n  value_type omc = 0.0L;\n\n  c = cos(a[3]);\n  s = sin(a[3]);\n\n  omc = static_cast<value_type>(1.0 - c);\n\n  res[0] = a[0] * a[0] * omc + c;\n  res[4] = a[1] * a[1] * omc + c;\n  res[8] = a[2] * a[2] * omc + c;\n  int _01 = 1;\n  int _10 = 3;\n  int _12 = 5;\n  int _21 = 7;\n  int _02 = 2;\n  int _20 = 6;\n  // Check to see if we need to transpose\n  if(Rotations::Constants::epsijk == 1.0L)\n  {\n    _01 = 3;\n    _10 = 1;\n    _12 = 7;\n    _21 = 5;\n    _02 = 6;\n    _20 = 2;\n  }\n\n  q = omc * a[0] * a[1];\n  res[_01] = q + s * a[2];\n  res[_10] = q - s * a[2];\n  q = omc * a[1] * a[2];\n  res[_12] = q + s * a[0];\n  res[_21] = q - s * a[0];\n  q = omc * a[2] * a[0];\n  res[_02] = q - s * a[1];\n  res[_20] = q + s * a[1];\n\n  return res;\n}\n\n/**: qu2eu\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief Quaternion to Euler angles  [Morawiec page 40, with errata !!!! ]\n *\n * @param q quaternion\n *\n *\n * @date 8/04/13   MDG 1.0 original\n */\ntemplate <typename InputType, typename OutputType>\nOutputType qu2eu(const InputType& q, typename Quaternion<typename OutputType::value_type>::Order layout = Quaternion<typename OutputType::value_type>::Order::VectorScalar)\n{\n  OutputType res(3);\n  size_t w = 0;\n  size_t x = 1;\n  size_t y = 2;\n  size_t z = 3;\n  if(layout == Quaternion<typename OutputType::value_type>::Order::VectorScalar)\n  {\n    w = 3;\n    x = 0;\n    y = 1;\n    z = 2;\n  }\n\n  InputType qq(4);\n  using OutputValueType = typename OutputType::value_type;\n  OutputValueType q12 = 0.0f;\n  OutputValueType q03 = 0.0f;\n  OutputValueType chi = 0.0f;\n  OutputValueType Phi = 0.0f;\n  OutputValueType phi1 = 0.0f;\n  OutputValueType phi2 = 0.0f;\n\n  qq = q;\n\n  q03 = qq.w() * qq.w() + qq.z() * qq.z();\n  q12 = qq.x() * qq.x() + qq.y() * qq.y();\n  chi = sqrt(q03 * q12);\n  if(chi == 0.0)\n  {\n    if(q12 == 0.0)\n    {\n      if(RConst::epsijk == 1.0)\n      {\n        Phi = 0.0;\n        phi2 = 0.0; // arbitrarily due to degeneracy\n        phi1 = static_cast<OutputValueType>(atan2(-2.0 * qq.w() * qq.z(), qq.w() * qq.w() - qq.z() * qq.z()));\n      }\n      else\n      {\n        Phi = 0.0;\n        phi2 = 0.0; // arbitrarily due to degeneracy\n        phi1 = static_cast<OutputValueType>(atan2(2.0 * qq.w() * qq.z(), qq.w() * qq.w() - qq.z() * qq.z()));\n      }\n    }\n    else\n    {\n      Phi = static_cast<OutputValueType>(EbsdLib::Constants::k_PiD);\n      phi2 = 0.0; // arbitrarily due to degeneracy\n      phi1 = static_cast<OutputValueType>(atan2(2.0 * qq.x() * qq.y(), qq.x() * qq.x() - qq.y() * qq.y()));\n    }\n  }\n  else\n  {\n    if(RConst::epsijk == 1.0)\n    {\n      Phi = static_cast<OutputValueType>(atan2(2.0 * chi, q03 - q12));\n      chi = static_cast<OutputValueType>(1.0 / chi);\n      phi1 = atan2((-qq.w() * qq.y() + qq.x() * qq.z()) * chi, (-qq.w() * qq.x() - qq.y() * qq.z()) * chi);\n      phi2 = atan2((qq.w() * qq.y() + qq.x() * qq.z()) * chi, (-qq.w() * qq.x() + qq.y() * qq.z()) * chi);\n    }\n    else\n    {\n      Phi = static_cast<OutputValueType>(atan2(2.0 * chi, q03 - q12));\n      chi = static_cast<OutputValueType>(1.0 / chi);\n      typename OutputType::value_type y1 = (qq.w() * qq.y() + qq.x() * qq.z()) * chi;\n      typename OutputType::value_type x1 = (qq.w() * qq.x() - qq.y() * qq.z()) * chi;\n      phi1 = atan2(y1, x1);\n      y1 = (-qq.w() * qq.y() + qq.x() * qq.z()) * chi;\n      x1 = (qq.w() * qq.x() + qq.y() * qq.z()) * chi;\n      phi2 = atan2(y1, x1);\n    }\n  }\n\n  res[0] = phi1;\n  res[1] = Phi;\n  res[2] = phi2;\n\n  if(res[0] < 0.0)\n  {\n    res[0] = static_cast<OutputValueType>(fmod(res[0] + 100.0 * DConst::k_PiD, DConst::k_2PiD));\n  }\n  if(res[1] < 0.0)\n  {\n    res[1] = static_cast<OutputValueType>(fmod(res[1] + 100.0 * DConst::k_PiD, DConst::k_PiD));\n  }\n  if(res[2] < 0.0)\n  {\n    res[2] = static_cast<OutputValueType>(fmod(res[2] + 100.0 * DConst::k_PiD, DConst::k_2PiD));\n  }\n\n  return res;\n}\n\n/**: ax2ho\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief Axis angle pair to homochoric\n *\n * @param a axis-angle pair\n *\n * !\n * @date 8/04/13   MDG 1.0 originaleu2ho\n */\ntemplate <typename InputType, typename OutputType>\nOutputType ax2ho(const InputType& a)\n{\n  OutputType res(3);\n  typename OutputType::value_type f = static_cast<typename OutputType::value_type>(0.75 * (a[3] - sin(a[3])));\n  f = static_cast<typename OutputType::value_type>(pow(f, (1.0 / 3.0)));\n  res[0] = a[0] * f;\n  res[1] = a[1] * f;\n  res[2] = a[2] * f;\n  return res;\n}\n\n/**: ho2ax\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief Homochoric to axis angle pair\n *\n * @param h homochoric coordinates\n *\n *\n *\n * @date 8/04/13  MDG 1.0 original\n * @date 07/21/14 MDG 1.1 double precision fit coefficients\n */\ntemplate <typename InputType, typename OutputType>\nOutputType ho2ax(const InputType& h)\n{\n  OutputType res(4);\n  using value_type = typename OutputType::value_type;\n  using OMHelperType = ArrayHelpers<OutputType, value_type>;\n\n  value_type thr = 1.0E-8f;\n\n  typename OutputType::value_type hmag = ArrayHelpers<InputType, value_type>::sumofSquares(h);\n  if(hmag == 0.0)\n  {\n    res[0] = 0.0;\n    res[1] = 0.0;\n    res[2] = 1.0;\n    res[3] = 0.0;\n  }\n  else\n  {\n    using OutputValueType = typename OutputType::value_type;\n    OutputValueType hm = hmag;\n    InputType hn = h;\n    OutputValueType sqrRtHMag = static_cast<OutputValueType>(1.0 / sqrt(hmag));\n    OMHelperType::scalarMultiply(hn, sqrRtHMag); // In place scalar multiply\n    OutputValueType s = static_cast<OutputValueType>(LPs::tfit[0] + LPs::tfit[1] * hmag);\n    for(int i = 2; i < 16; i++)\n    {\n      hm = hm * hmag;\n      s = static_cast<OutputValueType>(s + LPs::tfit[i] * hm);\n    }\n    s = static_cast<OutputValueType>(2.0 * acos(s));\n    res[0] = hn[0];\n    res[1] = hn[1];\n    res[2] = hn[2];\n    OutputValueType delta = static_cast<OutputValueType>(std::fabs(s - EbsdLib::Constants::k_PiD));\n    if(delta < thr)\n    {\n      res[3] = static_cast<value_type>(EbsdLib::Constants::k_PiD);\n    }\n    else\n    {\n      res[3] = s;\n    }\n  }\n  return res;\n}\n\n/**: om2qu\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert a 3x3 rotation matrix to a unit quaternion (see Morawiec, page 37)\n *\n * @param x 3x3 matrix to be converted\n *\n *\n * @date 8/12/13   MDG 1.0 original\n * @date 8/18/14   MDG 2.0 new version\n */\ntemplate <typename InputType, typename OutputType>\nOutputType om2qu(const InputType& om, typename Quaternion<typename OutputType::value_type>::Order layout = Quaternion<typename OutputType::value_type>::Order::VectorScalar)\n{\n  OutputType res(4);\n  using SizeType = typename OutputType::size_type;\n  SizeType w = 0;\n  SizeType x = 1;\n  SizeType y = 2;\n  SizeType z = 3;\n  if(layout == Quaternion<typename OutputType::value_type>::Order::VectorScalar)\n  {\n    w = 3;\n    x = 0;\n    y = 1;\n    z = 2;\n  }\n  using OutputValueType = typename OutputType::value_type;\n  OutputValueType thr = static_cast<typename OutputType::value_type>(1.0E-10L);\n  if(sizeof(typename InputType::value_type) == 4)\n  {\n    thr = static_cast<typename OutputType::value_type>(1.0E-6L);\n  }\n  OutputValueType s = 0.0;\n  OutputValueType s1 = 0.0;\n  OutputValueType s2 = 0.0;\n  OutputValueType s3 = 0.0;\n\n  s = static_cast<OutputValueType>(om[0] + om[4] + om[8] + 1.0);\n  if(EbsdLibMath::closeEnough(std::fabs(s), static_cast<typename OutputType::value_type>(0.0), thr)) // Are we close to Zero\n  {\n    s = 0.0;\n  }\n  s = sqrt(s);\n  s1 = static_cast<OutputValueType>(om[0] - om[4] - om[8] + 1.0);\n  if(EbsdLibMath::closeEnough(std::fabs(s1), static_cast<typename OutputType::value_type>(0.0), thr)) // Are we close to Zero\n  {\n    s1 = 0.0;\n  }\n  s1 = sqrt(s1);\n  s2 = static_cast<OutputValueType>(-om[0] + om[4] - om[8] + 1.0);\n  if(EbsdLibMath::closeEnough(std::fabs(s2), static_cast<typename OutputType::value_type>(0.0), thr)) // Are we close to Zero\n  {\n    s2 = 0.0;\n  }\n  s2 = sqrt(s2);\n  s3 = static_cast<OutputValueType>(-om[0] - om[4] + om[8] + 1.0);\n  if(EbsdLibMath::closeEnough(std::fabs(s3), static_cast<typename OutputType::value_type>(0.0), thr)) // Are we close to Zero\n  {\n    s3 = 0.0;\n  }\n  s3 = sqrt(s3);\n  res[w] = static_cast<OutputValueType>(s * 0.5);\n  res[x] = static_cast<OutputValueType>(s1 * 0.5);\n  res[y] = static_cast<OutputValueType>(s2 * 0.5);\n  res[z] = static_cast<OutputValueType>(s3 * 0.5);\n  // printf(\"res[z]: % 3.16f \\n\", res[z]);\n\n  // verify the signs (q0 always positive)\n  if(om[7] < om[5])\n  {\n    res[x] = -Rotations::Constants::epsijk * res[x];\n  }\n  if(om[2] < om[6])\n  {\n    res[y] = -Rotations::Constants::epsijk * res[y];\n  }\n  if(om[3] < om[1])\n  {\n    res[z] = -Rotations::Constants::epsijk * res[z];\n  }\n  // printf(\"res[z]: % 3.16f \\n\", res[z]);\n\n  s = EbsdMatrixMath::Magnitude4x1(&(res[0]));\n\n  if(s != 0.0)\n  {\n    EbsdMatrixMath::Divide4x1withConstant<typename OutputType::value_type>(&(res[0]), s);\n  }\n\n  /* we need to do a quick test here to make sure that the\n  ! sign of the vector part is the same as that of the\n  ! corresponding vector in the axis-angle representation;\n  ! these two can end up being different, presumably due to rounding\n  ! issues, but this needs to be further analyzed...\n  ! This adds a little bit of computation overhead but for now it\n  ! is the easiest way to make sure the signs are correct.\n  */\n  // om2ax(om, oax);\n\n  InputType eu = om2eu<InputType, InputType>(om);\n  InputType oax = eu2ax<InputType, InputType>(eu);\n\n  if(oax[0] * res[x] < 0.0)\n  {\n    res[x] = -res[x];\n  }\n  if(oax[1] * res[y] < 0.0)\n  {\n    res[y] = -res[y];\n  }\n  if(oax[2] * res[z] < 0.0)\n  {\n    res[z] = -res[z];\n  }\n  return res;\n}\n\n/**: qu2ax\n *\n * @author Dr. David Rowenhorst, NRL\n *\n * @brief convert quaternion to axis angle\n *\n * @param q quaternion\n * @param res Result Axis-Angle\n * @param layout The ordering of the data: Vector-Scalar or Scalar-Vector\n */\ntemplate <typename InputType, typename OutputType>\nOutputType qu2ax(const InputType& q, typename Quaternion<typename OutputType::value_type>::Order layout = Quaternion<typename OutputType::value_type>::Order::VectorScalar)\n{\n  using OutputValueType = typename OutputType::value_type;\n  OutputType res(4);\n  using SizeType = typename OutputType::size_type;\n  SizeType w = 0;\n  SizeType x = 1;\n  SizeType y = 2;\n  SizeType z = 3;\n  if(layout == Quaternion<typename OutputType::value_type>::Order::VectorScalar)\n  {\n    w = 3;\n    x = 0;\n    y = 1;\n    z = 2;\n  }\n\n  OutputValueType epsijk = RConst::epsijkd;\n  InputType qo(q);\n  // make sure q[0] is >= 0.0\n  typename OutputType::value_type sign = 1.0;\n  if(q[w] < 0.0)\n  {\n    sign = -1.0;\n  }\n  for(int i = 0; i < 4; i++)\n  {\n    qo[i] = sign * q[i];\n  }\n  OutputValueType eps = static_cast<OutputValueType>(1.0e-12L);\n  OutputValueType omega = static_cast<OutputValueType>(2.0 * acos(qo[w]));\n  if(omega < eps)\n  {\n    res[0] = 0.0;\n    res[1] = 0.0;\n    res[2] = static_cast<OutputValueType>(1.0 * epsijk);\n    res[3] = 0.0;\n  }\n  else\n  {\n    typename OutputType::value_type mag = 0.0;\n    mag = static_cast<OutputValueType>(1.0 / sqrt(q[x] * q[x] + q[y] * q[y] + q[z] * q[z]));\n    res[0] = q[x] * mag;\n    res[1] = q[y] * mag;\n    res[2] = q[z] * mag;\n    res[3] = omega;\n  }\n  return res;\n}\n\n/**: om2ax\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert orientation matrix to axis angle\n *\n * @details this assumes that the matrix represents a passive rotation.\n *\n * @param om 3x3 orientation matrix\n *\n *\n * @date 8/12/13  MDG 1.0 original\n * @date 07/08/14 MDG 2.0 replaced by direct solution\n */\ntemplate <typename InputType, typename OutputType>\nOutputType om2ax(const InputType& om)\n{\n  OutputType qu = om2qu<InputType, OutputType>(om);\n  return qu2ax<OutputType, OutputType>(qu);\n}\n\n/**: ro2ax\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief Rodrigues vector to axis angle pair\n *\n * @param r Rodrigues vector\n *\n *\n * @date 8/04/13   MDG 1.0 original\n * @date 8/11/14   MDG 1.1 added infty handling\n */\ntemplate <typename InputType, typename OutputType>\nOutputType ro2ax(const InputType& r)\n{\n  using OutputValueType = typename OutputType::value_type;\n  OutputType res(4);\n  OutputValueType ta = 0.0L;\n  OutputValueType angle = 0.0L;\n\n  ta = r[3];\n  if(ta == 0.0L)\n  {\n    res[0] = 0.0L;\n    res[1] = 0.0L;\n    res[2] = 1.0L;\n    res[3] = 0.0L;\n    return res;\n  }\n  if(ta == std::numeric_limits<typename OutputType::value_type>::infinity())\n  {\n    res[0] = r[0];\n    res[1] = r[1];\n    res[2] = r[2];\n    res[3] = static_cast<OutputValueType>(DConst::k_PiD);\n  }\n  else\n  {\n    angle = static_cast<OutputValueType>(2.0L * atan(ta));\n    ta = r[0] * r[0] + r[1] * r[1] + r[2] * r[2];\n    ta = sqrt(ta);\n    ta = static_cast<OutputValueType>(1.0L / ta);\n    res[0] = r[0] * ta;\n    res[1] = r[1] * ta;\n    res[2] = r[2] * ta;\n    res[3] = angle;\n  }\n  return res;\n}\n\n/**: ax2ro\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert axis angle to Rodrigues\n *\n * @param a axis angle pair\n *\n *\n * @date 8/12/13 MDG 1.0 original\n * @date 7/6/14  MDG 2.0 simplified\n * @date 8/11/14 MDG 2.1 added infty handling\n */\ntemplate <typename InputType, typename OutputType>\nOutputType ax2ro(const InputType& ax)\n{\n  OutputType res(4);\n  using OutputValueType = typename OutputType::value_type;\n\n  OutputValueType thr = 1.0E-7f;\n\n  if(ax[3] == 0.0)\n  {\n    res[0] = 0.0;\n    res[1] = 0.0;\n    res[2] = 0.0;\n    res[3] = 0.0;\n    return res;\n  }\n  res[0] = ax[0];\n  res[1] = ax[1];\n  res[2] = ax[2];\n  if(fabs(ax[3] - EbsdLib::Constants::k_PiD) < thr)\n  {\n    res[3] = std::numeric_limits<typename OutputType::value_type>::infinity();\n  }\n  else\n  {\n    res[3] = static_cast<OutputValueType>(tan(ax[3] * 0.5));\n  }\n  return res;\n}\n\n/**: ax2qu\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert axis angle to quaternion\n *\n * @param a axis angle pair\n *\n *\n * @date 8/12/13   MDG 1.0 original\n * @date 7/23/14   MDG 1.1 explicit transformation\n */\ntemplate <typename InputType, typename OutputType>\nOutputType ax2qu(const InputType& r, typename Quaternion<typename OutputType::value_type>::Order layout = Quaternion<typename OutputType::value_type>::Order::VectorScalar)\n{\n  using OutputValueType = typename OutputType::value_type;\n  OutputType res(4);\n  using SizeType = typename OutputType::size_type;\n  SizeType w = 0;\n  SizeType x = 1;\n  SizeType y = 2;\n  SizeType z = 3;\n  if(layout == Quaternion<typename OutputType::value_type>::Order::VectorScalar)\n  {\n    w = 3;\n    x = 0;\n    y = 1;\n    z = 2;\n  }\n  if(r[3] == 0.0)\n  {\n    res[w] = 1.0;\n    res[x] = 0.0;\n    res[y] = 0.0;\n    res[z] = 0.0;\n  }\n  else\n  {\n    typename OutputType::value_type c = static_cast<OutputValueType>(cos(r[3] * 0.5));\n    typename OutputType::value_type s = static_cast<OutputValueType>(sin(r[3] * 0.5));\n    res[w] = c;\n    res[x] = r[0] * s;\n    res[y] = r[1] * s;\n    res[z] = r[2] * s;\n  }\n  return res;\n}\n\n/**: ro2ho\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert rodrigues to homochoric\n *\n * @param r Rodrigues vector\n *\n *\n * @date 8/12/13   MDG 1.0 original\n * @date 7/24/14   MDG 2.0 explicit transformation\n * @date 8/11/14   MDG 3.0 added infty handling\n */\ntemplate <typename InputType, typename OutputType>\nOutputType ro2ho(const InputType& r)\n{\n  OutputType res(3);\n  using value_type = typename OutputType::value_type;\n  using OMHelperType = ArrayHelpers<OutputType, value_type>;\n\n  value_type f = 0.0;\n  value_type rv = OMHelperType::sumofSquares(r);\n  if(rv == 0.0)\n  {\n    OMHelperType::splat(res, 0.0);\n    return res;\n  }\n  if(r[3] == std::numeric_limits<typename OutputType::value_type>::infinity())\n  {\n    f = static_cast<value_type>(0.75 * EbsdLib::Constants::k_PiD);\n  }\n  else\n  {\n    value_type t = static_cast<value_type>(2.0 * std::atan(r[3]));\n    f = static_cast<value_type>(0.75 * (t - std::sin(t)));\n  }\n  f = static_cast<value_type>(pow(f, 1.0 / 3.0));\n  res[0] = r[0] * f;\n  res[1] = r[1] * f;\n  res[2] = r[2] * f;\n  return res;\n}\n\n/**: qu2om\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert a quaternion to a 3x3 matrix\n *\n * @param q quaternion\n *\n *\n * @note verified 8/5/13\n *\n * @date 6/03/13   MDG 1.0 original\n */\ntemplate <typename InputType, typename OutputType>\nOutputType qu2om(const InputType& r, typename Quaternion<typename OutputType::value_type>::Order layout = Quaternion<typename OutputType::value_type>::Order::VectorScalar)\n{\n  using OutputValueType = typename OutputType::value_type;\n  OutputType res(9);\n  using SizeType = typename OutputType::size_type;\n  SizeType w = 0;\n  SizeType x = 1;\n  SizeType y = 2;\n  SizeType z = 3;\n  if(layout == Quaternion<typename OutputType::value_type>::Order::VectorScalar)\n  {\n    w = 3;\n    x = 0;\n    y = 1;\n    z = 2;\n  }\n  OutputValueType qq = r[w] * r[w] - (r[x] * r[x] + r[y] * r[y] + r[z] * r[z]);\n  res[0] = static_cast<OutputValueType>(qq + 2.0 * r[x] * r[x]);\n  res[4] = static_cast<OutputValueType>(qq + 2.0 * r[y] * r[y]);\n  res[8] = static_cast<OutputValueType>(qq + 2.0 * r[z] * r[z]);\n  res[1] = static_cast<OutputValueType>(2.0 * (r[x] * r[y] - r[w] * r[z]));\n  res[5] = static_cast<OutputValueType>(2.0 * (r[y] * r[z] - r[w] * r[x]));\n  res[6] = static_cast<OutputValueType>(2.0 * (r[z] * r[x] - r[w] * r[y]));\n  res[3] = static_cast<OutputValueType>(2.0 * (r[y] * r[x] + r[w] * r[z]));\n  res[7] = static_cast<OutputValueType>(2.0 * (r[z] * r[y] + r[w] * r[x]));\n  res[2] = static_cast<OutputValueType>(2.0 * (r[x] * r[z] + r[w] * r[y]));\n  if(Rotations::Constants::epsijk != 1.0)\n  {\n    using value_type = typename OutputType::value_type;\n    using RotationMatrixType = Eigen::Matrix<value_type, 3, 3, Eigen::RowMajor>;\n    using RotationMatrixMapType = Eigen::Map<RotationMatrixType>;\n\n    RotationMatrixMapType resWrap(const_cast<value_type*>(res.data()));\n    resWrap.transpose();\n  }\n  return res;\n}\n\n/**: qu2ro\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert quaternion to Rodrigues\n *\n * @param q quaternion\n *\n * @date 8/12/13   MDG 1.0 original\n * @date 7/23/14   MDG 2.0 direct transformation\n * @date 8/11/14   MDG 2.1 added infty handling\n */\ntemplate <typename InputType, typename OutputType>\nOutputType qu2ro(const InputType& q, typename Quaternion<typename OutputType::value_type>::Order layout = Quaternion<typename OutputType::value_type>::Order::VectorScalar)\n{\n  OutputType res(4);\n  using SizeType = typename OutputType::size_type;\n  SizeType w = 0;\n  SizeType x = 1;\n  SizeType y = 2;\n  SizeType z = 3;\n  if(layout == Quaternion<typename OutputType::value_type>::Order::VectorScalar)\n  {\n    w = 3;\n    x = 0;\n    y = 1;\n    z = 2;\n  }\n  typename OutputType::value_type thr = static_cast<typename OutputType::value_type>(1.0E-8L);\n  res[0] = q[x];\n  res[1] = q[y];\n  res[2] = q[z];\n  res[3] = 0.0;\n\n  if(q[w] < thr)\n  {\n    res[3] = std::numeric_limits<typename OutputType::value_type>::infinity();\n    return res;\n  }\n  typename OutputType::value_type s = EbsdMatrixMath::Magnitude3x1(&(res[0]));\n  if(s < thr)\n  {\n    res[0] = 0.0;\n    res[1] = 0.0;\n    res[2] = 0.0;\n    res[3] = 0.0;\n    return res;\n  }\n\n  res[0] = res[0] / s;\n  res[1] = res[1] / s;\n  res[2] = res[2] / s;\n  res[3] = tan(acos(q[w]));\n  return res;\n}\n\n/**: qu2ho\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert quaternion to homochoric\n *\n * @param q quaternion\n *\n *\n * @date 8/12/13   MDG 1.0 original\n * @date 7/23/14   MDG 2.0 explicit transformation\n */\ntemplate <typename InputType, typename OutputType>\nOutputType qu2ho(const InputType& q, typename Quaternion<typename OutputType::value_type>::Order layout = Quaternion<typename OutputType::value_type>::Order::VectorScalar)\n{\n  OutputType res(3);\n  using value_type = typename OutputType::value_type;\n  using OMHelperType = ArrayHelpers<OutputType, value_type>;\n\n  using SizeType = typename OutputType::size_type;\n  SizeType w = 0;\n  SizeType x = 1;\n  SizeType y = 2;\n  SizeType z = 3;\n  if(layout == Quaternion<typename OutputType::value_type>::Order::VectorScalar)\n  {\n    w = 3;\n    x = 0;\n    y = 1;\n    z = 2;\n  }\n  value_type s;\n  value_type f;\n\n  value_type omega = static_cast<value_type>(2.0 * std::acos(q[w]));\n  if(omega == 0.0)\n  {\n    OMHelperType::splat(res, 0.0);\n    // res.assign(0.0);\n  }\n  else\n  {\n    res[0] = q[x];\n    res[1] = q[y];\n    res[2] = q[z];\n    s = static_cast<value_type>(1.0 / std::sqrt(OMHelperType::sumofSquares(res)));\n    OMHelperType::scalarMultiply(res, s);\n    f = static_cast<value_type>(0.75 * (omega - std::sin(omega)));\n    f = static_cast<value_type>(std::pow(f, 1.0 / 3.0));\n    OMHelperType::scalarMultiply(res, f);\n  }\n  return res;\n}\n\n/**: ho2cu\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert homochoric to cubochoric\n *\n * @param h homochoric coordinates\n *\n *\n * @date 8/12/13   MDG 1.0 original\n */\ntemplate <typename InputType, typename OutputType>\nOutputType ho2cu(const InputType& q)\n{\n  int ierr = -1;\n  OutputType res(3);\n  res = ModifiedLambertProjection3D<InputType, typename InputType::value_type>::LambertBallToCube(q, ierr);\n  return res;\n}\n\n/**: cu2ho\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert cubochoric to homochoric\n *\n * @param c cubochoric coordinates\n *\n *\n *\n * @date 8/12/13   MDG 1.0 original\n */\ntemplate <typename InputType, typename OutputType>\nOutputType cu2ho(const InputType& cu)\n{\n  int ierr = 0;\n  OutputType res(3);\n  res = ModifiedLambertProjection3D<InputType, typename InputType::value_type>::LambertCubeToBall(cu, ierr);\n  return res;\n}\n\n/**: ro2om\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert rodrigues to orientation matrix\n *\n * @param r Rodrigues vector\n *\n *\n * @date 8/12/13   MDG 1.0 original\n */\ntemplate <typename InputType, typename OutputType>\nOutputType ro2om(const InputType& ro)\n{\n  OutputType ax = ro2ax<InputType, OutputType>(ro);\n  return ax2om<OutputType, OutputType>(ax);\n}\n\n/**: ro2eu\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief Rodrigues vector to Euler angles\n *\n * @param r Rodrigues vector\n *\n *\n * @date 8/04/13   MDG 1.0 original\n * @date 8/11/14   MDG 1.1 added infty handling\n */\ntemplate <typename InputType, typename OutputType>\nOutputType ro2eu(const InputType& ro)\n{\n  OutputType om = ro2om<InputType, OutputType>(ro);\n  return om2eu<OutputType, OutputType>(om);\n}\n\n/**: eu2ho\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert euler to homochoric\n *\n * @param e 3 euler angles\n *\n *\n * @date 8/12/13   MDG 1.0 original\n */\ntemplate <typename InputType, typename OutputType>\nOutputType eu2ho(const InputType& eu)\n{\n  OutputType ax = eu2ax<InputType, OutputType>(eu);\n  return ax2ho<OutputType, OutputType>(ax);\n}\n\n/**: om2ro\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert orientation matrix to Rodrigues\n *\n * @param om 3x3 orientation matrix\n *\n *\n * @date 8/12/13   MDG 1.0 original\n */\ntemplate <typename InputType, typename OutputType>\nOutputType om2ro(const InputType& om)\n{\n  OutputType eu = om2eu<InputType, OutputType>(om); // Convert the OM to Euler\n  return eu2ro<OutputType, OutputType>(eu);         // Convert Euler to Rodrigues\n}\n\n/**: om2ho\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert orientation matrix to homochoric\n *\n * @param om 3x3 orientation matrix\n *\n *\n * @date 8/12/13   MDG 1.0 original\n * @date 07/08/14 MDG 2.0 simplification via ax (shorter path)\n */\ntemplate <typename InputType, typename OutputType>\nOutputType om2ho(const InputType& om)\n{\n  OutputType ax = om2ax<InputType, OutputType>(om); // Convert the OM to Axis-Angles\n  return ax2ho<OutputType, OutputType>(ax);         // Convert Axis-Angles to Homochoric\n}\n\n/**: ax2eu\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert axis angle to euler\n *\n * @param a axis angle pair\n *\n *\n * @date 8/12/13   MDG 1.0 original\n * @date 07/08/14 MDG 2.0 simplification via ro (shorter path)\n */\ntemplate <typename InputType, typename OutputType>\nOutputType ax2eu(const InputType& ax)\n{\n  OutputType om = ax2om<InputType, OutputType>(ax);\n  return om2eu<OutputType, OutputType>(om);\n}\n\n/**: ro2qu\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert rodrigues to quaternion\n *\n * @param r Rodrigues vector\n *\n *\n * @date 8/12/13   MDG 1.0 original\n */\ntemplate <typename InputType, typename OutputType>\nOutputType ro2qu(const InputType& ro, typename Quaternion<typename OutputType::value_type>::Order layout = Quaternion<typename OutputType::value_type>::Order::VectorScalar)\n{\n  OutputType ax = ro2ax<InputType, OutputType>(ro);\n  return ax2qu<OutputType, OutputType>(ax, layout);\n}\n\n/**: ho2eu\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert homochoric to euler\n *\n * @param h homochoric coordinates\n *\n *\n * @date 8/12/13   MDG 1.0 original\n */\ntemplate <typename InputType, typename OutputType>\nOutputType ho2eu(const InputType& ho)\n{\n  OutputType ax = ho2ax<InputType, OutputType>(ho);\n  return ax2eu<OutputType, OutputType>(ax);\n}\n\n/**: ho2om\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert homochoric to orientation matrix\n *\n * @param h homochoric coordinates\n *\n *\n * @date 8/12/13   MDG 1.0 original\n */\ntemplate <typename InputType, typename OutputType>\nOutputType ho2om(const InputType& ho)\n{\n  OutputType ax = ho2ax<InputType, OutputType>(ho);\n  return ax2om<OutputType, OutputType>(ax);\n}\n\n/**: ho2ro\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert homochoric to Rodrigues\n *\n * @param h homochoric coordinates\n *\n *\n * @date 8/12/13   MDG 1.0 original\n */\ntemplate <typename InputType, typename OutputType>\nOutputType ho2ro(const InputType& ho)\n{\n  OutputType ax = ho2ax<InputType, OutputType>(ho);\n  return ax2ro<OutputType, OutputType>(ax);\n}\n\n/**: ho2qu\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert homochoric to quaternion\n *\n * @param r homochoric coordinates\n *\n *\n * @date 8/12/13   MDG 1.0 original\n */\ntemplate <typename InputType, typename OutputType>\nOutputType ho2qu(const InputType& ho, typename Quaternion<typename OutputType::value_type>::Order layout = Quaternion<typename OutputType::value_type>::Order::VectorScalar)\n{\n  InputType ax = ho2ax<InputType, InputType>(ho);\n  return ax2qu<InputType, OutputType>(ax, layout);\n}\n\n/**: eu2cu\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert euler angles to cubochoric\n *\n * @param e euler angles\n *\n *\n *\n * @date 8/12/13   MDG 1.0 original\n */\ntemplate <typename InputType, typename OutputType>\nOutputType eu2cu(const InputType& eu)\n{\n  OutputType ho = eu2ho<InputType, OutputType>(eu);\n  return ho2cu<OutputType, OutputType>(ho);\n}\n\n/**: om2cu\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert orientation matrix to cubochoric\n *\n * @param o orientation matrix\n *\n *\n *\n * @date 8/12/13   MDG 1.0 original\n */\ntemplate <typename InputType, typename OutputType>\nOutputType om2cu(const InputType& om)\n{\n  OutputType ho = om2ho<InputType, OutputType>(om);\n  return ho2cu<OutputType, OutputType>(ho);\n}\n\n/**: ax2cu\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert axis angle to cubochoric\n *\n * @param a axis angle\n *\n *\n *\n * @date 8/12/13   MDG 1.0 original\n */\n\ntemplate <typename InputType, typename OutputType>\nOutputType ax2cu(const InputType& ax)\n{\n  OutputType ho = ax2ho<InputType, OutputType>(ax);\n  return ho2cu<OutputType, OutputType>(ho);\n}\n\n/**: ro2cu\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert Rodrigues to cubochoric\n *\n * @param r Rodrigues\n *\n *\n *\n * @date 8/12/13   MDG 1.0 original\n */\ntemplate <typename InputType, typename OutputType>\nOutputType ro2cu(const InputType& ro)\n{\n  OutputType ho = ro2ho<InputType, OutputType>(ro);\n  return ho2cu<OutputType, OutputType>(ho);\n}\n\n/**: qu2cu\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert quaternion to cubochoric\n *\n * @param q quaternion\n *\n *\n *\n * @date 8/12/13   MDG 1.0 original\n */\ntemplate <typename InputType, typename OutputType>\nOutputType qu2cu(const InputType& qu, typename Quaternion<typename OutputType::value_type>::Order layout = Quaternion<typename OutputType::value_type>::Order::VectorScalar)\n{\n  OutputType ho = qu2ho<InputType, OutputType>(qu, layout);\n  return ho2cu<OutputType, OutputType>(ho);\n}\n\n/**: cu2eu\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert cubochoric to euler angles\n *\n * @param c cubochoric coordinates\n *\n *\n *\n * @date 8/12/13   MDG 1.0 original\n */\n\ntemplate <typename InputType, typename OutputType>\nOutputType cu2eu(const InputType& cu)\n{\n  OutputType ho = cu2ho<InputType, OutputType>(cu);\n  return ho2eu<OutputType, OutputType>(ho);\n}\n\n/**: cu2om\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert cubochoric to orientation matrix\n *\n * @param c cubochoric coordinates\n *\n *\n *\n * @date 8/12/13   MDG 1.0 original\n */\n\ntemplate <typename InputType, typename OutputType>\nOutputType cu2om(const InputType& cu)\n{\n  OutputType ho = cu2ho<InputType, OutputType>(cu);\n  return ho2om<OutputType, OutputType>(ho);\n}\n\n/**: cu2ax\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert cubochoric to axis angle\n *\n * @param c cubochoric coordinates\n *\n *\n *\n * @date 8/12/13   MDG 1.0 original\n */\n\ntemplate <typename InputType, typename OutputType>\nOutputType cu2ax(const InputType& cu)\n{\n  OutputType ho = cu2ho<InputType, OutputType>(cu);\n  return ho2ax<OutputType, OutputType>(ho);\n}\n\n/**: cu2ro\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert cubochoric to Rodrigues\n *\n * @param c cubochoric coordinates\n *\n *\n *\n * @date 8/12/13   MDG 1.0 original\n */\n\ntemplate <typename InputType, typename OutputType>\nOutputType cu2ro(const InputType& cu)\n{\n  OutputType ho = cu2ho<InputType, OutputType>(cu);\n  return ho2ro<OutputType, OutputType>(ho);\n}\n\n/**: cu2qu\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief convert cubochoric to quaternion\n *\n * @param c cubochoric coordinates\n *\n *\n *\n * @date 8/12/13   MDG 1.0 original\n */\n\ntemplate <typename InputType, typename OutputType>\nOutputType cu2qu(const InputType& cu, typename Quaternion<typename OutputType::value_type>::Order layout = Quaternion<typename OutputType::value_type>::Order::VectorScalar)\n{\n  InputType ho = cu2ho<InputType, InputType>(cu); // Convert the Cuborchoric to Homochoric\n  return ho2qu<InputType, OutputType>(ho);        // Convert Homochoric to Quaternion\n}\n\n/**: RotVec_om\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief rotate a vector using a rotation matrix, active or passive\n *\n * @details This routine provides a way for the user to transform a vector\n * and it returns the new vector components.  The user can use either a\n * rotation matrix or a quaternion to define the transformation, and must\n * also specifiy whether an active or passive result is needed.\n *\n *\n * @param vec input vector components\n * @param om orientation matrix\n * @param ap active/passive switch\n *\n *\n * @date 8/18/14   MDG 1.0 original\n */\n\nvoid RotVec_om(float* vec, float* om, char ap, float* res);\n\n/**: RotVec_qu\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief rotate a vector using a quaternion, active or passive\n *\n * @details This routine provides a way for the user to transform a vector\n * and it returns the new vector components.  The user can use either a\n * rotation matrix or a quaternion to define the transformation, and must\n * also specifiy whether an active or passive result is needed.\n *\n *\n * @param vec input vector components\n * @param qu quaternion\n * @param ap active/passive switch\n *\n *\n * @date 8/18/14   MDG 1.0 original\n */\n\nvoid RotVec_qu(float* vec, float* qu, char ap, float* res);\n\n/**: RotTensor2_om\n *\n * @author Marc De Graef, Carnegie Mellon University\n *\n * @brief rotate a second rank tensor using a rotation matrix, active or passive\n *\n * @param tensor input tensor components\n * @param om orientation matrix\n * @param ap active/passive switch\n *\n *\n * @date 8/18/14   MDG 1.0 original\n */\n\nvoid RotTensor2_om(float* tensor, float* om, char ap, float* res);\n\n/**\n* SUBROUTINE: print_orientation\n              *\n              * @author Marc De Graef, Carnegie Mellon University\n              *\n              * @brief  prints a complete orientationtype record or a single entry\n              *\n              * @param o orientationtype record\n              * @param outtype (optional) indicates which representation to print\n* @param pretext (optional) up to 10 characters that will precede each line\n*\n* @date  8/4/13   MDG 1.0 original\nprint the entire record with all representations\n\n* SUBROUTINE: print_orientation_d\n*\n* @author Marc De Graef, Carnegie Mellon University\n                         *\n                         * @brief  prints a complete orientationtype record or a single entry (double precision)\n*\n* @param o orientationtype record\n* @param outtype (optional) indicates which representation to print\n* @param pretext (optional) up to 10 characters that will precede each line\n*\n* @date  8/4/13   MDG 1.0 original\nprint the entire record with all representations\n*/\n\n} // namespace OrientationTransformation\n", "meta": {"hexsha": "789f9920c99e2be38d93308f95e1ff0e867c4517", "size": 64643, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Source/EbsdLib/Core/OrientationTransformation.hpp", "max_stars_repo_name": "mgroeber/EbsdLib", "max_stars_repo_head_hexsha": "3b2c842c31dedf3b1a3bfc7e5cd701b55ae7381d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-13T09:33:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-08T00:48:26.000Z", "max_issues_repo_path": "Source/EbsdLib/Core/OrientationTransformation.hpp", "max_issues_repo_name": "mgroeber/EbsdLib", "max_issues_repo_head_hexsha": "3b2c842c31dedf3b1a3bfc7e5cd701b55ae7381d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-10T20:13:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-13T13:18:10.000Z", "max_forks_repo_path": "Source/EbsdLib/Core/OrientationTransformation.hpp", "max_forks_repo_name": "mgroeber/EbsdLib", "max_forks_repo_head_hexsha": "3b2c842c31dedf3b1a3bfc7e5cd701b55ae7381d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-02-10T21:20:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-19T01:45:50.000Z", "avg_line_length": 28.3770851624, "max_line_length": 173, "alphanum_fraction": 0.6452670823, "num_tokens": 19988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2697350667351386}}
{"text": "#include <complex>\n#include <iostream>\n#include <fstream>\n#include <string>\n\n#include <boost/regex.hpp>\n#include <boost/filesystem.hpp>\n\n#include <Eigen/Core>\n\n#include <vtkDataArraySelection.h>\n#include <vtkXMLImageDataReader.h>\n\n#include \"FullSampleSimulation.h\"\n#include \"DropletSampleSimulation.h\"\n\nusing json = nlohmann::json;\n\nvoid print_usage() {\n\tstd::cout <<\n\t\tstd::endl <<\n\t\t\"Usage: ./rt-solver [ -h | -c FILE | -x FILE ]\" <<\n\t\tstd::endl << std::endl <<\n\t\t\"\\t-h\" << std::endl <<\n\t\t\"\\t\\tPrint this message and exit.\" << \n\t\tstd::endl << std::endl <<\n\t\t\"\\t-c FILE\" << std::endl <<\n\t\t\"\\t\\tCreate a default settings file with the specified name and exit.\" << \n\t\tstd::endl << std::endl <<\n\t\t\"\\t-x FILE\" << std::endl <<\n\t\t\"\\t\\tRun the code with the specified settings file.\" << \n\t\tstd::endl << std::endl;\n}\n\nstd::string minify_json(std::string filename) {\n\n\tstd::ifstream f(filename);\n\tif(!f.is_open())\n\t\tthrow std::string(\n\t\t\t\"Could not open the specified setting file\");\n\n\tboost::regex empty_re(\"\\\\s*\");\n\tboost::regex comment_re(\"\\\\s*#.*\");\n\tboost::smatch match_result;\n\n\tstd::string line, minified_json;\n\twhile(std::getline(f, line)) {\n\t\tif(!boost::regex_match(line, match_result, empty_re) &&\n\t\t\t\t!boost::regex_match(line, match_result, comment_re))\n\t\t\tminified_json.append(line+\"\\n\");\n\t}\n\treturn minified_json;\n}\n\nvoid create_default_settings_file(std::string filename) {\n\n\tconst char *file_content = R\"V0G0N(\n{\n\t\"Light source\": {\n\t\t# Widths (µm) of the light source (array of size [spatial_dim-1]). Should be smaller\n\t\t# than the director field mesh in the transverse direction if the sample type is \n\t\t# \"Full\".\n\t\t\"Source widths\": [10, 10],\n\n\t\t# Number of rays per dimension for the light source\n\t\t\"Source N rays per dim\": [200, 200],\n\n\t\t# Mean wavelength (µm) for the spectrum of the source\n\t\t\"Mean wavelength\": 0.6,\n\n\t\t# Full width (µm) of the light spectrum\n\t\t\"Spectral FWHM\": 0.2,\n\n\t\t# Number of wavelengths in the spectrum\n\t\t\"N wavelengths\": 1\n\t},\n\t\"Geometry\": {\n\t\t# Type of sample: \"Droplet\" or \"Full\". If \"Droplet\" is choosed, the given vti file for\n\t\t# the director field should have a cubic mesh (only values inside a sphere of same\n\t\t# diameter than the mesh will be considered).\n\t\t\"Sample type\": \"Full\",\n\n\t\t# Relative path to a VTI file containing a VTK array \"n\" for the director values.\n\t\t# IMPORTANT: the specified director field should have C_1 regularity (which exclude\n\t\t# the presence of defects and n->-n jumps).\n\t\t\"Director field VTI file\": \"\",\n\n\t\t\"Droplet sample parameters\": {\n\t\t\t# Since the ray mapping is singular near the vertical part of the droplet boundary,\n\t\t\t# the light source for droplet rays is shrinked by the following factor\n\t\t\t\"Source shrink factor\": 0.92,\n\n\t\t\t# Distance (µm) between the boundary of the droplet and the sample plates (the\n\t\t\t# droplet is centered inside the sample).\n\t\t\t\"Distance from upper sample plate\": 10\n\t\t}\n\t},\n\t\"Material properties\": {\n\t\t# Ordinary refractive index of the liquid crystal\n\t\t\"Ordinary refractive index\": 1.5,\n\n\t\t# Extraordinary refractive index of the liquid crystal\n\t\t\"Extraordinary refractive index\": 1.6,\n\n\t\t# Refractive index of the host fluid in case of a droplet sample\n\t\t\"Host fluid refractive index\": 1.55,\n\n\t\t# Refractive index of the external medium outside the sample\n\t\t\"External medium refractive index\": 1,\n\n\t\t# Refractive indices of the isotropic layers defining the lower part of the sample\n\t\t# (light propagates from bottom to top in the z direction, layers should be specified\n\t\t# with increasing z)\n\t\t\"Refractive indices of the lower isotropic layers\": [1.5],\n\n\t\t# Refractive indices of the isotropic layers defining the upper part of the sample\n\t\t# (light propagates from bottom to top in the z direction, layers should be specified\n\t\t# with increasing z)\n\t\t\"Refractive indices of the upper isotropic layers\": [1.5],\n\n\t\t# Thicknesses of the isotropic layers defining the lower part of the sample\n\t\t# (light propagates from bottom to top in the z direction, layers should be specified\n\t\t# with increasing z)\n\t\t\"Thicknesses of the lower isotropic layers\": [1000],\n\n\t\t# Thicknesses of the isotropic layers defining the upper part of the sample\n\t\t# (light propagates from bottom to top in the z direction, layers should be specified\n\t\t# with increasing z)\n\t\t\"Thicknesses of the upper isotropic layers\": [1000]\n\t},\n\t\"Visualisation\": {\n\t\t# Results will be stored in this folder (automatically created if it does not exists)\n\t\t\"Results folder name\": \"results/\",\n\n\t\t# Widths (µm) of the target plane on which fields are reconstructed. Will be used to \n\t\t# set the transverse size of output data. Should be smaller than the source widths.\n\t\t\"Target output widths\": [8, 8],\n\n\t\t# Number of pixels per dimension for the target plane on which fields are \n\t\t# reconstructed. Will be used to set the transverse dims of output data\n\t\t\"Target N pixels per dim\": [100, 100],\n\n\t\t\"Bulk output\": {\n\t\t\t# Base name for bulk data files\n\t\t\t\"Base name\": \"bulk\",\n\n\t\t\t# Should we run the homotopy continuation algorithm to reconstruct and save optical\n\t\t\t# fields in the bulk of the liquid crystal?\n\t\t\t\"Export reconstructed fields\": true,\n\n\t\t\t# Should we save bulk data associated with the rays?\n\t\t\t\"Export ray data\": true\n\t\t},\n\t\t\"Screen output\": {\n\t\t\t# Base name for screen data files\n\t\t\t\"Base name\": \"screen\",\n\n\t\t\t# Should we run the homotopy continuation algorithm to reconstruct and save optical\n\t\t\t# fields on the focal plane?\n\t\t\t\"Export reconstructed fields\": true,\n\n\t\t\t# Should we save data associated with the rays on the focal plane?\n\t\t\t\"Export ray data\": true,\n\n\t\t\t# Numerical aperture of the focal lens\n\t\t\t\"Numerical aperture\": 0.4\n\t\t}\n\t},\n\t\"InverseScreenMap parameters\": {\n\t\t# Number of adaptative refinements when inverting the ray mapping. Should be tweaked to\n\t\t# get a good compromise between accuracy and speed.\n\t\t\"N refinement cycles\": 4,\n\n\t\t# Homotopy settings used in the coarse phase of the inversion process\n\t\t\"Coarse step HC parameters\": {\n\t\t\t# Tolerance of the newton algorithm when computing corrector steps\n\t\t\t\"Newton tolerance\": 1e-8,\n\t\t\t\n\t\t\t# The homotopy step size will be adjusted so that the newton algorithm for the\n\t\t\t# corrector step runs in at most N iteration, where N is set in this parameter.\n\t\t\t\"Optimum newton step number\": 4,\n\n\t\t\t# Maximum size for the homotopy step size (µm)\n\t\t\t\"Max arclength step\": 0.1,\n\n\t\t\t# Maximum distance (µm) run by a homotopy path before stopping the search for\n\t\t\t# inverses.\n\t\t\t\"Max arclength\": 6\n\t\t},\n\n\t\t# Homotopy settings used in the refinement phase of the inversion process\n\t\t\"Refinement step HC parameters\": {\n\t\t\t# Tolerance of the newton algorithm when computing corrector steps\n\t\t\t\"Newton tolerance\": 1e-8,\n\t\t\t\n\t\t\t# The homotopy step size will be adjusted so that the newton algorithm for the\n\t\t\t# corrector step runs in at most N iteration, where N is set in this parameter.\n\t\t\t\"Optimum newton step number\": 4,\n\n\t\t\t# Maximum size for the homotopy step size (µm)\n\t\t\t\"Max arclength step\": 0.1,\n\n\t\t\t# Maximum distance (µm) run by a homotopy path before stopping the search for\n\t\t\t# inverses.\n\t\t\t\"Max arclength\": 6\n\t\t}\n\t}\n})V0G0N\";\n\n\tstd::ofstream f(filename);\n\tif(!f.is_open())\n\t\tthrow std::string(\n\t\t\t\"Could not open the specified setting file, maybe you\"\n\t\t\t\"prepended a nonexistent directory?\");\n\n\tf << file_content;\n}\n\nint main(int argc, char *argv[]) {\n\n\tstd::string param_file_name;\n\n\tbool failed_parsing = (argc>1) ? false : true;\n\tint i=1;\n\twhile(i<argc) {\n\t\tif(strcmp(argv[i],\"-x\")==0) {\n\t\t\tif(argv[++i][0]!='-') {\n\t\t\t\tparam_file_name = argv[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfailed_parsing = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse if(strcmp(argv[i],\"-h\")==0) {\n\t\t\tprint_usage();\n\t\t\treturn 0;\n\t\t}\n\t\telse if(strcmp(argv[i],\"-c\")==0) {\n\t\t\tif(argv[++i][0]!='-') {\n\t\t\t\tcreate_default_settings_file(argv[i]);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tfailed_parsing = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(failed_parsing) {\n\t\tstd::cout <<\n\t\t\tstd::endl << \"Syntax error!\" << std::endl;\n\t\tprint_usage();\n\t\treturn -1;\n\t}\n\n\tEigen::initParallel();\n\tjson j;\n\n\ttry {\n\t\tj = json::parse(minify_json(param_file_name));\n\n\t\tstd::string filename = j.at(\"Geometry\").at(\"Director field VTI file\");\n\t\tboost::filesystem::path path(filename);\n\t\tif(!boost::filesystem::exists(path))\n\t\t\tthrow std::string(\n\t\t\t\t\"The given vti file for the director file does not exists\");\n\n\t\tvtkObject::GlobalWarningDisplayOff();\n\n\t\tstd::cout <<\n\t\t\t\"Loading director field values\" << std::endl;\n\t\tauto reader = vtkSmartPointer<vtkXMLImageDataReader>::New();\n\t\treader->SetFileName(filename.c_str());\n\t\treader->UpdateInformation();\n\n\t\tbool found_n_data = false;\n\t\tfor(unsigned int i=0; i<reader->GetNumberOfPointArrays(); i++) {\n\t\t\tauto array_name = reader->GetPointArrayName(i);\n\t\t\tif(!std::strcmp(array_name, \"n\")) {\n\t\t\t\tfound_n_data = true;\n\t\t\t\treader->SetPointArrayStatus(array_name, 1);\n\t\t\t}\n\t\t\telse\n\t\t\t\treader->SetPointArrayStatus(array_name, 0);\n\t\t}\n\t\tif(!found_n_data)\n\t\t\tthrow std::string(\n\t\t\t\t\"Could not find a vector field named \\\"n\\\" in the given vti file\");\n\n\t\treader->Update();\n\t\tauto nfield_vti_data = reader->GetOutput();\n\t\tauto nfield_vti_vals = vtkDoubleArray::FastDownCast(\n\t\t\tnfield_vti_data->GetPointData()->GetAbstractArray(\"n\"));\n\n\t\tint dims[3];\t\t\tnfield_vti_data->GetDimensions(dims);\n\t\tdouble spacings[3];\t\tnfield_vti_data->GetSpacing(spacings);\n\n\t\tunsigned int spatial_dim;\n\t\tif(dims[2]<=1)\n\t\t\tthrow std::string(\n\t\t\t\t\"Not enough points in the z-direction\");\n\t\telse if(dims[0]==1 && dims[1]==1)\n\t\t\tthrow std::string(\n\t\t\t\t\"1D samples not supported\");\n\t\telse if(dims[1]==1)\n\t\t\tthrow std::string(\n\t\t\t\t\"2D samples should be specified in the YZ plane\");\n\t\telse if(dims[0]==1)\n\t\t\tspatial_dim = 2;\n\t\telse\n\t\t\tspatial_dim = 3;\n\n\t\tdouble lc_thickness = (dims[2]-1)*spacings[2];\n\t\tunsigned int N_lc_steps = dims[2];\n\n\t\tswitch(spatial_dim) {\n\t\t\tcase 2: {\n\t\t\t\tauto n_values = std::make_shared<std::vector<Vector<3,double> > >();\n\t\t\t\tVector<3,double> n_val;\n\t\t\t\tfor(int iy=-2; iy<dims[1]+2; iy++) {\n\t\t\t\t\tfor(int iz=-2; iz<dims[2]+2; iz++) {\n\t\t\t\t\t\tif(iy>=0 && iy<dims[1] && iz>=0 && iz<dims[2]) \n\t\t\t\t\t\t\tfor(int c=0; c<3; c++)\n\t\t\t\t\t\t\t\tn_val(c) = nfield_vti_vals->GetComponent(iy+dims[1]*iz, c);\n\t\t\t\t\t\tn_values->push_back(n_val);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tVector<2,unsigned long> full_dims({dims[1]+4,dims[2]+4});\n\t\t\t\tVector<2,double> full_origin(\n\t\t\t\t\t{-(dims[1]+3)*spacings[1]/2.,-(dims[2]+3)*spacings[2]/2.});\n\t\t\t\tVector<2,double> full_lengths(\n\t\t\t\t\t{(dims[1]+3)*spacings[1],(dims[2]+3)*spacings[2]});\n\t\t\t\tauto full_mesh = std::make_shared<CartesianMesh<2> >(\n\t\t\t\t\tfull_origin, full_lengths, full_dims);\n\n\t\t\t\tstd::shared_ptr<Simulation<2> > sim;\n\t\t\t\tif(j.at(\"Geometry\").at(\"Sample type\") == \"Full\") {\n\t\t\t\t\tVector<2,unsigned long> lc_dims({dims[1],dims[2]});\n\t\t\t\t\tVector<2,double> lc_origin(\n\t\t\t\t\t\t{-(dims[1]-1)*spacings[1]/2.,-(dims[2]-1)*spacings[2]/2.});\n\t\t\t\t\tVector<2,double> lc_lengths(\n\t\t\t\t\t\t{(dims[1]-1)*spacings[1],(dims[2]-1)*spacings[2]});\n\t\t\t\t\tauto lc_mesh = std::make_shared<CartesianMesh<2> >(\n\t\t\t\t\t\tlc_origin, lc_lengths, lc_dims);\n\t\t\t\t\tauto lc_domain = std::make_shared<ParallelotopeDomain<2> >(*lc_mesh);\n\t\t\t\t\tauto n_field = std::make_shared<CubicInterpolatedMapping<2,3,double> >(\n\t\t\t\t\t\tn_values, full_mesh, lc_domain);\n\t\t\t\t\tn_field->normalize();\n\n\t\t\t\t\tsim = std::make_shared<FullSampleSimulation<2> >(\n\t\t\t\t\t\tj, lc_thickness, N_lc_steps, n_field);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tthrow(std::string(\n\t\t\t\t\t\t\"Error: \\\"Sample type\\\" value should be \\\"Full\\\"\\n\"\n\t\t\t\t\t\t\"in dimension 2.\"));\n\t\t\t\tsim->run();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 3: {\n\t\t\t\tauto n_values = std::make_shared<std::vector<Vector<3,double> > >();\n\t\t\t\tVector<3,double> n_val;\n\t\t\t\tfor(int ix=-2; ix<dims[0]+2; ix++) {\n\t\t\t\t\tfor(int iy=-2; iy<dims[1]+2; iy++) {\n\t\t\t\t\t\tfor(int iz=-2; iz<dims[2]+2; iz++) {\n\t\t\t\t\t\t\tif(ix>=0 && ix<dims[0] && iy>=0 && iy<dims[1]\n\t\t\t\t\t\t\t\t\t&& iz>=0 && iz<dims[2]) \n\t\t\t\t\t\t\t\tfor(int c=0; c<3; c++)\n\t\t\t\t\t\t\t\t\tn_val(c) = nfield_vti_vals->GetComponent(\n\t\t\t\t\t\t\t\t\t\tix+dims[0]*(iy+dims[1]*iz), c);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tn_val = 0;\n\t\t\t\t\t\t\tn_values->push_back(n_val);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tVector<3,unsigned long> full_dims({dims[0]+4,dims[1]+4,dims[2]+4});\n\t\t\t\tVector<3,double> full_origin({-(dims[0]+3)*spacings[0]/2.,\n\t\t\t\t\t-(dims[1]+3)*spacings[1]/2.,-(dims[2]+3)*spacings[2]/2.});\n\t\t\t\tVector<3,double> full_lengths({(dims[0]+3)*spacings[0],\n\t\t\t\t\t(dims[1]+3)*spacings[1],(dims[2]+3)*spacings[2]});\n\t\t\t\tauto full_mesh = std::make_shared<CartesianMesh<3> >(\n\t\t\t\t\tfull_origin, full_lengths, full_dims);\n\n\t\t\t\tstd::shared_ptr<Simulation<3> > sim;\n\t\t\t\tif(j.at(\"Geometry\").at(\"Sample type\") == \"Full\") {\n\t\t\t\t\tVector<3,unsigned long> lc_dims({dims[0],dims[1],dims[2]});\n\t\t\t\t\tVector<3,double> lc_origin({-(dims[0]-1)*spacings[0]/2.,\n\t\t\t\t\t\t-(dims[1]-1)*spacings[1]/2.,-(dims[2]-1)*spacings[2]/2.});\n\t\t\t\t\tVector<3,double> lc_lengths({(dims[0]-1)*spacings[0],\n\t\t\t\t\t\t(dims[1]-1)*spacings[1],(dims[2]-1)*spacings[2]});\n\t\t\t\t\tauto lc_mesh = std::make_shared<CartesianMesh<3> >(\n\t\t\t\t\t\tlc_origin, lc_lengths, lc_dims);\n\t\t\t\t\tauto lc_domain = std::make_shared<ParallelotopeDomain<3> >(*lc_mesh);\n\t\t\t\t\tauto n_field = std::make_shared<CubicInterpolatedMapping<3,3,double> >(\n\t\t\t\t\t\tn_values, full_mesh, lc_domain);\n\t\t\t\t\tn_field->normalize();\n\n\n\t\t\t\t\tsim = std::make_shared<FullSampleSimulation<3> >(\n\t\t\t\t\t\tj, lc_thickness, N_lc_steps, n_field);\n\t\t\t\t}\n\t\t\t\telse if(j.at(\"Geometry\").at(\"Sample type\") == \"Droplet\") {\n\t\t\t\t\tauto lc_domain = std::make_shared<SphericalDomain<3> >(\n\t\t\t\t\t\tVector<3,double>({0,0,0}), (dims[2]-1)*spacings[2]/2.);\n\t\t\t\t\tauto n_field = std::make_shared<CubicInterpolatedMapping<3,3,double> >(\n\t\t\t\t\t\tn_values, full_mesh, lc_domain);\n\t\t\t\t\tn_field->extrapolate_data();\n\t\t\t\t\tn_field->normalize();\n\t\t\t\t\tlc_thickness += 2*j.at(\"Geometry\").at(\"Droplet sample parameters\").at(\n\t\t\t\t\t\t\"Distance from upper sample plate\").get<double>();\n\n\t\t\t\t\tsim = std::make_shared<DropletSampleSimulation>(\n\t\t\t\t\t\tj, lc_thickness, N_lc_steps, n_field);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tthrow(std::string(\n\t\t\t\t\t\t\"Error: \\\"Sample type\\\" value should be \\\"Full\\\"\\n\"\n\t\t\t\t\t\t\"or \\\"Droplet\\\" in dimension 3.\"));\n\t\t\t\tsim->run();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tcatch(std::string &s) {\n\t\tstd::cerr <<\n\t\t\tstd::endl << std::endl <<\n\t\t\t\"----------------------------------------------------------------\" <<\n\t\t\tstd::endl <<\n\t\t\t\"Exception on processing: \" << std::endl <<\n\t\t\ts << std::endl <<\n\t\t\t\"Aborting!\" << std::endl <<\n\t\t\t\"----------------------------------------------------------------\" <<\n\t\t\tstd::endl << std::endl;\n\t\treturn -1;\n\t}\n\tcatch(std::exception &exc) {\n\t\tstd::cerr <<\n\t\t\tstd::endl << std::endl <<\n\t\t\t\"----------------------------------------------------------------\" <<\n\t\t\tstd::endl <<\n\t\t\t\"Exception on processing: \" << std::endl <<\n\t\t\texc.what() << std::endl <<\n\t\t\t\"Aborting!\" << std::endl <<\n\t\t\t\"----------------------------------------------------------------\" <<\n\t\t\tstd::endl << std::endl;\n\t\treturn -1;\n\t}\n\tcatch(...) {\n\t\tstd::cerr <<\n\t\t\tstd::endl << std::endl <<\n\t\t\t\"----------------------------------------------------------------\" <<\n\t\t\tstd::endl <<\n\t\t\t\"Unknown exception!\" << std::endl <<\n\t\t\t\"Aborting!\" << std::endl <<\n\t\t\t\"----------------------------------------------------------------\" <<\n\t\t\tstd::endl << std::endl;\n\t\treturn -1;\n\t}\n\t\n\treturn 0;\n}\n", "meta": {"hexsha": "adf70b21af5975554919792d680ec21efa50b915", "size": 15091, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RayTracingSolver/src/main.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/main.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/main.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": 32.3147751606, "max_line_length": 89, "alphanum_fraction": 0.6344841296, "num_tokens": 4465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2697202215154219}}
{"text": "#ifndef HDGRAPH_HPP\n#define HDGRAPH_HPP\n\n#include <boost/graph/graph_utility.hpp>\n#include \"globals.hpp\"\n#include \"rbgraph.hpp\"\n\n//=============================================================================\n// Data structures\n\n/**\n  Scoped enumeration type whose underlying size is 1 byte, used for character\n  state.\n\n  State is paired with a character in the struct SignedCharacter.\n*/\nenum class State : bool {\n  lose,  ///< The paired character is lost\n  gain   ///< The paired character is gained\n};\n\n/**\n  @brief Struct used to represent a signed character\n\n  Each character c+ and c− is called a signed character.\n*/\nstruct SignedCharacter {\n  std::string character{};    ///< Character name\n  State state = State::gain;  ///< Character state\n};\n\n//=============================================================================\n// Bundled properties\n\n/**\n  @brief Struct used to represent the properties of an edge (Hasse diagram)\n\n  The character c is gained in the edge (x, y) such that y is a child of x and\n  c has state 0 in x and state 1 in y.\n  In this case the edge (x, y) is labeled by c+.\n  Conversely, c is lost in the edge (x, y) if y is a child of x and character c\n  has state 1 in x and state 0 in y.\n  In the latter case the edge (x, y) is labeled by c−.\n  For each character c, we allow at most one edge labeled by c−.\n*/\nstruct HDEdgeProperties {\n  std::list<SignedCharacter> signedcharacters{};  ///< List of SignedCharacters\n                                                  ///< that label the edge\n};\n\n/**\n  @brief Struct used to represent the properties of a vertex (Hasse diagram)\n\n  Given s a species, by C(s) we denote the set of characters of s.\n  Let GM be a maximal reducible graph.\n  Then the diagram P for GM is the Hasse diagram for the poset (Ps , ≤) of all\n  species of GM ordered by the relation ≤, where s1 ≤ s2 if C(s1) ⊆ C(s2).\n*/\nstruct HDVertexProperties {\n  std::list<std::string> species{};  ///< List of species that label the vertex\n  std::list<std::string> characters{};  ///< List of characters of the species\n};\n\n/**\n  @brief Struct used to represent the properties of a Hasse diagram\n*/\nstruct HDGraphProperties {\n  const RBGraph* g{};   ///< Original red-black graph\n  const RBGraph* gm{};  ///< Original maximal reducible graph\n  size_t num_v; ///< Number of vertices\n};\n\n//=============================================================================\n// Typedefs used for readabily\n\n// Graph\n\n/**\n  Hasse diagram\n*/\ntypedef boost::adjacency_list<boost::setS,            // OutEdgeList\n                              boost::listS,            // VertexList\n                              boost::bidirectionalS,  // Directed\n                              HDVertexProperties,     // VertexProperties\n                              HDEdgeProperties,       // EdgeProperties\n                              HDGraphProperties       // GraphProperties\n                              >\n    HDGraph;\n\n// Descriptors\n\n/**\n  Edge of a Hasse diagram\n*/\ntypedef boost::graph_traits<HDGraph>::edge_descriptor HDEdge;\n\n/**\n  Vertex of a Hasse diagram\n*/\ntypedef boost::graph_traits<HDGraph>::vertex_descriptor HDVertex;\n\n// Iterators\n\n/**\n  Iterator of vertices (Hasse diagram)\n*/\ntypedef boost::graph_traits<HDGraph>::vertex_iterator HDVertexIter;\n\n/**\n  Iterator of incoming edges (Hasse diagram)\n*/\ntypedef boost::graph_traits<HDGraph>::in_edge_iterator HDInEdgeIter;\n\n/**\n  Iterator of outgoing edges (Hasse diagram)\n*/\ntypedef boost::graph_traits<HDGraph>::out_edge_iterator HDOutEdgeIter;\n\n/**\n  Iterator (const) of a list of signed characters\n*/\ntypedef std::list<SignedCharacter>::const_iterator SignedCharacterIter;\n\n// Size types\n\n/**\n  Size type of vertices (Hasse diagram)\n*/\ntypedef boost::graph_traits<HDGraph>::vertices_size_type HDVertexSize;\n\n// Maps\n\n/**\n  Map of vertex indexes (Hasse diagram)\n*/\ntypedef std::map<HDVertex, HDVertexSize> HDVertexIMap;\n\n/**\n  Associative property map of vertex indexes (Hasse diagram)\n*/\ntypedef boost::associative_property_map<HDVertexIMap> HDVertexIAssocMap;\n\ntypedef std::map<HDVertex, size_t> HDVertexIndexMap;\ntypedef boost::associative_property_map<HDVertexIndexMap> HDVertexIndexAssocMap;\n\n//=============================================================================\n// Enum / Struct operator overloads\n\n/**\n  @brief Overloading of operator<< for State\n\n  @param[in] os Output stream\n  @param[in] s  State\n\n  @return Updated output stream\n*/\ninline std::ostream& operator<<(std::ostream& os, const State s) {\n  const bool sign = (s == State::lose);\n\n  return os << (sign ? \"-\" : \"+\");\n}\n\n/**\n  @brief Overloading of operator<< for SignedCharacter\n\n  @param[in] os Output stream\n  @param[in] sc SignedCharacter\n\n  @return Updated output stream\n*/\ninline std::ostream& operator<<(std::ostream& os, const SignedCharacter sc) {\n  return os << sc.character << sc.state;\n}\n\n/**\n  @brief Overloading of operator== for a pair of signed characters\n\n  @param[in] a SignedCharacter\n  @param[in] b SignedCharacter\n\n  @return True if a is equal to b\n*/\ninline bool operator==(const SignedCharacter& a, const SignedCharacter b) {\n  return (a.character == b.character && a.state == b.state);\n}\n\n//=============================================================================\n// Boost functions (overloading)\n\n/**\n  @brief Add vertex with \\e species and \\e characters to \\e hasse\n\n  @param[in]     species    List of species names\n  @param[in]     characters List of character names\n  @param[in,out] hasse      Hasse diagram graph\n\n  @return Vertex descriptor for the new vertex\n*/\nHDVertex add_vertex(const std::list<std::string>& species,\n                    const std::list<std::string>& characters, HDGraph& hasse);\n\n/**\n  @brief Add vertex with \\e species and \\e characters to \\e hasse\n\n  @param[in]     species    Species name\n  @param[in]     characters List of character names\n  @param[in,out] hasse      Hasse diagram graph\n\n  @return Vertex descriptor for the new vertex\n*/\ninline HDVertex add_vertex(const std::string& species,\n                           const std::list<std::string>& characters,\n                           HDGraph& hasse) {\n  return add_vertex(std::list<std::string>{species}, characters, hasse);\n}\n\n/**\n  @brief Add edge between \\e u and \\e v with a list of signed characters to\n         \\e hasse\n\n  @param[in]     u                Source Vertex\n  @param[in]     v                Target Vertex\n  @param[in]     signedcharacters List of signed characters\n  @param[in,out] hasse            Hasse diagram graph\n\n  @return Edge descriptor for the new edge.\n          If the edge is already in the graph then a duplicate will not be\n          added and the bool flag will be false.\n          When the flag is false, the returned edge descriptor points to the\n          already existing edge\n*/\nstd::pair<HDEdge, bool> add_edge(\n    const HDVertex u, const HDVertex v,\n    const std::list<SignedCharacter>& signedcharacters, HDGraph& hasse);\n\n//=============================================================================\n// General functions\n\n/**\n  @brief Return a pointer to the original red-black graph of \\e hasse\n\n  @param[in] hasse Hasse diagram graph\n\n  @return Pointer to the the original red-black graph of \\e hasse\n*/\ninline const RBGraph* const orig_g(const HDGraph& hasse) {\n  return hasse[boost::graph_bundle].g;\n}\n\n/**\n  @brief Return a pointer to the original maximal reducible graph of \\e hasse\n\n  @param[in] hasse Hasse diagram graph\n\n  @return Pointer to the the original maximal reducible graph of \\e hasse\n*/\ninline const RBGraph* const orig_gm(const HDGraph& hasse) {\n  return hasse[boost::graph_bundle].gm;\n}\n\n/**\n  @brief Overloading of operator<< for HDGraph\n\n  @param[in] os    Output stream\n  @param[in] hasse Hasse diagram graph\n\n  @return Updated output stream\n*/\nstd::ostream& operator<<(std::ostream& os, const HDGraph& hasse);\n\n//=============================================================================\n// Algorithm functions\n\n/**\n  @brief Returns True if \\e a is included in \\e b\n\n  @param[in] a List of character names (strings)\n  @param[in] b List of character names (strings)\n\n  @return True if \\e a is included in \\e b, False otherwise\n*/\nbool is_included(const std::list<std::string>& a,\n                 const std::list<std::string>& b);\n\n/**\n  @brief Build the Hasse diagram of \\e gm\n\n  Let GM be a maximal reducible graph.\n  Then the diagram P for GM is the Hasse diagram for the poset (Ps, ≤) of all\n  species of GM ordered by the relation ≤, where s1 ≤ s2 if C(s1) ⊆ C(s2).\n  Given (Ps, ≤) the poset of all species of a red-black graph, we\n  consider the representation of the poset (Ps, ≤) by its Hasse diagram,\n  represented by a directed acyclic graph P.\n  More precisely, two species s1 and s2 are connected by the arc (s1, s2) if\n  s1 < s2 and there does not exist a species s3 such that s1 < s3 < s2.\n\n  @param[out] hasse Hasse diagram graph\n  @param[in]  g     Red-black graph\n  @param[in]  gm    Maximal reducible red-black graph\n  @param[in]  components Vector of red-black connected subgraphs\n  @param[in]  c_assocmap Connected Components map\n*/\nvoid hasse_diagram(HDGraph& hasse, const RBGraph& g, const RBGraph& gm, const RBGraphVector& components, const RBVertexIMap& c_map);\n\n/**\n  @brief Removes active species from an hasse diagram\n\n  A reduced HDGraph is the one with active species eliminated.\n  A specie is active if it has red edges incident to it.\n\n  @param [in] hasse Hasse diagram graph\n  @param [in] g     Red-black graph\n  @param[in]  components Vector of red-black connected subgraphs\n  @param[in]  c_assocmap Connected Components map\n\n  @return Reduced Hasse diagram graph\n*/\nvoid reduce_diagram(HDGraph& hasse, const RBGraph& gm);\n\n\nvoid transitive_reduction(HDGraph& hasse); \nvoid remove_vertex(HDVertex& v, HDGraph& p);\ninline size_t num_vertices(const HDGraph& hasse) {\n  return hasse[boost::graph_bundle].num_v;\n}\n\n#endif  // HDGRAPH_HPP\n", "meta": {"hexsha": "904d97df4d0100ed6421c2887f4044448b873893", "size": 9925, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/hdgraph.hpp", "max_stars_repo_name": "AlgoLab/persistent-phylogeny", "max_stars_repo_head_hexsha": "d3e7f25a94c8895e4ca72dc05490492b5c225779", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/hdgraph.hpp", "max_issues_repo_name": "AlgoLab/persistent-phylogeny", "max_issues_repo_head_hexsha": "d3e7f25a94c8895e4ca72dc05490492b5c225779", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hdgraph.hpp", "max_forks_repo_name": "AlgoLab/persistent-phylogeny", "max_forks_repo_head_hexsha": "d3e7f25a94c8895e4ca72dc05490492b5c225779", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-21T16:05:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-30T11:50:38.000Z", "avg_line_length": 30.2591463415, "max_line_length": 132, "alphanum_fraction": 0.6456423174, "num_tokens": 2386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.2696394000253643}}
{"text": "//  (C) Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_TOOLS_NEWTON_SOLVER_HPP\n#define BOOST_MATH_TOOLS_NEWTON_SOLVER_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n#include <boost/math/tools/complex.hpp> // test for multiprecision types.\n\n#include <iostream>\n#include <utility>\n#include <boost/config/no_tr1/cmath.hpp>\n#include <stdexcept>\n\n#include <boost/math/tools/config.hpp>\n#include <boost/cstdint.hpp>\n#include <boost/assert.hpp>\n#include <boost/throw_exception.hpp>\n\n#ifdef BOOST_MSVC\n#pragma warning(push)\n#pragma warning(disable: 4512)\n#endif\n#include <boost/math/tools/tuple.hpp>\n#ifdef BOOST_MSVC\n#pragma warning(pop)\n#endif\n\n#include <boost/math/special_functions/sign.hpp>\n#include <boost/math/special_functions/next.hpp>\n#include <boost/math/tools/toms748_solve.hpp>\n#include <boost/math/policies/error_handling.hpp>\n\nnamespace boost {\nnamespace math {\nnamespace tools {\n\nnamespace detail {\n\nnamespace dummy {\n\n   template<int n, class T>\n   typename T::value_type get(const T&) BOOST_MATH_NOEXCEPT(T);\n}\n\ntemplate <class Tuple, class T>\nvoid unpack_tuple(const Tuple& t, T& a, T& b) BOOST_MATH_NOEXCEPT(T)\n{\n   using dummy::get;\n   // Use ADL to find the right overload for get:\n   a = get<0>(t);\n   b = get<1>(t);\n}\ntemplate <class Tuple, class T>\nvoid unpack_tuple(const Tuple& t, T& a, T& b, T& c) BOOST_MATH_NOEXCEPT(T)\n{\n   using dummy::get;\n   // Use ADL to find the right overload for get:\n   a = get<0>(t);\n   b = get<1>(t);\n   c = get<2>(t);\n}\n\ntemplate <class Tuple, class T>\ninline void unpack_0(const Tuple& t, T& val) BOOST_MATH_NOEXCEPT(T)\n{\n   using dummy::get;\n   // Rely on ADL to find the correct overload of get:\n   val = get<0>(t);\n}\n\ntemplate <class T, class U, class V>\ninline void unpack_tuple(const std::pair<T, U>& p, V& a, V& b) BOOST_MATH_NOEXCEPT(T)\n{\n   a = p.first;\n   b = p.second;\n}\ntemplate <class T, class U, class V>\ninline void unpack_0(const std::pair<T, U>& p, V& a) BOOST_MATH_NOEXCEPT(T)\n{\n   a = p.first;\n}\n\ntemplate <class F, class T>\nvoid handle_zero_derivative(F f,\n   T& last_f0,\n   const T& f0,\n   T& delta,\n   T& result,\n   T& guess,\n   const T& min,\n   const T& max) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n{\n   if (last_f0 == 0)\n   {\n      // this must be the first iteration, pretend that we had a\n      // previous one at either min or max:\n      if (result == min)\n      {\n         guess = max;\n      }\n      else\n      {\n         guess = min;\n      }\n      unpack_0(f(guess), last_f0);\n      delta = guess - result;\n   }\n   if (sign(last_f0) * sign(f0) < 0)\n   {\n      // we've crossed over so move in opposite direction to last step:\n      if (delta < 0)\n      {\n         delta = (result - min) / 2;\n      }\n      else\n      {\n         delta = (result - max) / 2;\n      }\n   }\n   else\n   {\n      // move in same direction as last step:\n      if (delta < 0)\n      {\n         delta = (result - max) / 2;\n      }\n      else\n      {\n         delta = (result - min) / 2;\n      }\n   }\n}\n\n} // namespace\n\ntemplate <class F, class T, class Tol, class Policy>\nstd::pair<T, T> bisect(F f, T min, T max, Tol tol, boost::uintmax_t& max_iter, const Policy& pol) BOOST_NOEXCEPT_IF(policies::is_noexcept_error_policy<Policy>::value&& BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n{\n   T fmin = f(min);\n   T fmax = f(max);\n   if (fmin == 0)\n   {\n      max_iter = 2;\n      return std::make_pair(min, min);\n   }\n   if (fmax == 0)\n   {\n      max_iter = 2;\n      return std::make_pair(max, max);\n   }\n\n   //\n   // Error checking:\n   //\n   static const char* function = \"boost::math::tools::bisect<%1%>\";\n   if (min >= max)\n   {\n      return boost::math::detail::pair_from_single(policies::raise_evaluation_error(function,\n         \"Arguments in wrong order in boost::math::tools::bisect (first arg=%1%)\", min, pol));\n   }\n   if (fmin * fmax >= 0)\n   {\n      return boost::math::detail::pair_from_single(policies::raise_evaluation_error(function,\n         \"No change of sign in boost::math::tools::bisect, either there is no root to find, or there are multiple roots in the interval (f(min) = %1%).\", fmin, pol));\n   }\n\n   //\n   // Three function invocations so far:\n   //\n   boost::uintmax_t count = max_iter;\n   if (count < 3)\n      count = 0;\n   else\n      count -= 3;\n\n   while (count && (0 == tol(min, max)))\n   {\n      T mid = (min + max) / 2;\n      T fmid = f(mid);\n      if ((mid == max) || (mid == min))\n         break;\n      if (fmid == 0)\n      {\n         min = max = mid;\n         break;\n      }\n      else if (sign(fmid) * sign(fmin) < 0)\n      {\n         max = mid;\n      }\n      else\n      {\n         min = mid;\n         fmin = fmid;\n      }\n      --count;\n   }\n\n   max_iter -= count;\n\n#ifdef BOOST_MATH_INSTRUMENT\n   std::cout << \"Bisection iteration, final count = \" << max_iter << std::endl;\n\n   static boost::uintmax_t max_count = 0;\n   if (max_iter > max_count)\n   {\n      max_count = max_iter;\n      std::cout << \"Maximum iterations: \" << max_iter << std::endl;\n   }\n#endif\n\n   return std::make_pair(min, max);\n}\n\ntemplate <class F, class T, class Tol>\ninline std::pair<T, T> bisect(F f, T min, T max, Tol tol, boost::uintmax_t& max_iter)  BOOST_NOEXCEPT_IF(policies::is_noexcept_error_policy<policies::policy<> >::value&& BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n{\n   return bisect(f, min, max, tol, max_iter, policies::policy<>());\n}\n\ntemplate <class F, class T, class Tol>\ninline std::pair<T, T> bisect(F f, T min, T max, Tol tol) BOOST_NOEXCEPT_IF(policies::is_noexcept_error_policy<policies::policy<> >::value&& BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n{\n   boost::uintmax_t m = (std::numeric_limits<boost::uintmax_t>::max)();\n   return bisect(f, min, max, tol, m, policies::policy<>());\n}\n\n\ntemplate <class F, class T>\nT newton_raphson_iterate(F f, T guess, T min, T max, int digits, boost::uintmax_t& max_iter) BOOST_NOEXCEPT_IF(policies::is_noexcept_error_policy<policies::policy<> >::value&& BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n{\n   BOOST_MATH_STD_USING\n\n   static const char* function = \"boost::math::tools::newton_raphson_iterate<%1%>\";\n   if (min >= max)\n   {\n      return policies::raise_evaluation_error(function, \"Range arguments in wrong order in boost::math::tools::newton_raphson_iterate(first arg=%1%)\", min, boost::math::policies::policy<>());\n   }\n\n   T f0(0), f1, last_f0(0);\n   T result = guess;\n\n   T factor = static_cast<T>(ldexp(1.0, 1 - digits));\n   T delta = tools::max_value<T>();\n   T delta1 = tools::max_value<T>();\n   T delta2 = tools::max_value<T>();\n\n   //\n   // We use these to sanity check that we do actually bracket a root,\n   // we update these to the function value when we update the endpoints\n   // of the range.  Then, provided at some point we update both endpoints\n   // checking that max_range_f * min_range_f <= 0 verifies there is a root\n   // to be found somewhere.  Note that if there is no root, and we approach \n   // a local minima, then the derivative will go to zero, and hence the next\n   // step will jump out of bounds (or at least past the minima), so this\n   // check *should* happen in pathological cases.\n   //\n   T max_range_f = 0;\n   T min_range_f = 0;\n\n   boost::uintmax_t count(max_iter);\n\n#ifdef BOOST_MATH_INSTRUMENT\n   std::cout << \"Newton_raphson_iterate, guess = \" << guess << \", min = \" << min << \", max = \" << max\n      << \", digits = \" << digits << \", max_iter = \" << max_iter << std::endl;\n#endif\n\n   do {\n      last_f0 = f0;\n      delta2 = delta1;\n      delta1 = delta;\n      detail::unpack_tuple(f(result), f0, f1);\n      --count;\n      if (0 == f0)\n         break;\n      if (f1 == 0)\n      {\n         // Oops zero derivative!!!\n#ifdef BOOST_MATH_INSTRUMENT\n         std::cout << \"Newton iteration, zero derivative found!\" << std::endl;\n#endif\n         detail::handle_zero_derivative(f, last_f0, f0, delta, result, guess, min, max);\n      }\n      else\n      {\n         delta = f0 / f1;\n      }\n#ifdef BOOST_MATH_INSTRUMENT\n      std::cout << \"Newton iteration \" << max_iter - count << \", delta = \" << delta << std::endl;\n#endif\n      if (fabs(delta * 2) > fabs(delta2))\n      {\n         // Last two steps haven't converged.\n         T shift = (delta > 0) ? (result - min) / 2 : (result - max) / 2;\n         if ((result != 0) && (fabs(shift) > fabs(result)))\n         {\n            delta = sign(delta) * fabs(result) * 1.1f; // Protect against huge jumps!\n            //delta = sign(delta) * result; // Protect against huge jumps! Failed for negative result. https://github.com/boostorg/math/issues/216\n         }\n         else\n            delta = shift;\n         // reset delta1/2 so we don't take this branch next time round:\n         delta1 = 3 * delta;\n         delta2 = 3 * delta;\n      }\n      guess = result;\n      result -= delta;\n      if (result <= min)\n      {\n         delta = 0.5F * (guess - min);\n         result = guess - delta;\n         if ((result == min) || (result == max))\n            break;\n      }\n      else if (result >= max)\n      {\n         delta = 0.5F * (guess - max);\n         result = guess - delta;\n         if ((result == min) || (result == max))\n            break;\n      }\n      // Update brackets:\n      if (delta > 0)\n      {\n         max = guess;\n         max_range_f = f0;\n      }\n      else\n      {\n         min = guess;\n         min_range_f = f0;\n      }\n      //\n      // Sanity check that we bracket the root:\n      //\n      if (max_range_f * min_range_f > 0)\n      {\n         return policies::raise_evaluation_error(function, \"There appears to be no root to be found in boost::math::tools::newton_raphson_iterate, perhaps we have a local minima near current best guess of %1%\", guess, boost::math::policies::policy<>());\n      }\n   }while(count && (fabs(result * factor) < fabs(delta)));\n\n   max_iter -= count;\n\n#ifdef BOOST_MATH_INSTRUMENT\n   std::cout << \"Newton Raphson final iteration count = \" << max_iter << std::endl;\n\n   static boost::uintmax_t max_count = 0;\n   if (max_iter > max_count)\n   {\n      max_count = max_iter;\n      // std::cout << \"Maximum iterations: \" << max_iter << std::endl;\n      // Puzzled what this tells us, so commented out for now?\n   }\n#endif\n\n   return result;\n}\n\ntemplate <class F, class T>\ninline T newton_raphson_iterate(F f, T guess, T min, T max, int digits) BOOST_NOEXCEPT_IF(policies::is_noexcept_error_policy<policies::policy<> >::value&& BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n{\n   boost::uintmax_t m = (std::numeric_limits<boost::uintmax_t>::max)();\n   return newton_raphson_iterate(f, guess, min, max, digits, m);\n}\n\nnamespace detail {\n\n   struct halley_step\n   {\n      template <class T>\n      static T step(const T& /*x*/, const T& f0, const T& f1, const T& f2) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(T))\n      {\n         using std::fabs;\n         T denom = 2 * f0;\n         T num = 2 * f1 - f0 * (f2 / f1);\n         T delta;\n\n         BOOST_MATH_INSTRUMENT_VARIABLE(denom);\n         BOOST_MATH_INSTRUMENT_VARIABLE(num);\n\n         if ((fabs(num) < 1) && (fabs(denom) >= fabs(num) * tools::max_value<T>()))\n         {\n            // possible overflow, use Newton step:\n            delta = f0 / f1;\n         }\n         else\n            delta = denom / num;\n         return delta;\n      }\n   };\n\n   template <class F, class T>\n   T bracket_root_towards_min(F f, T guess, const T& f0, T& min, T& max, boost::uintmax_t& count) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())));\n\n   template <class F, class T>\n   T bracket_root_towards_max(F f, T guess, const T& f0, T& min, T& max, boost::uintmax_t& count) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n   {\n      using std::fabs;\n      //\n      // Move guess towards max until we bracket the root, updating min and max as we go:\n      //\n      T guess0 = guess;\n      T multiplier = 2;\n      T f_current = f0;\n      if (fabs(min) < fabs(max))\n      {\n         while (--count && ((f_current < 0) == (f0 < 0)))\n         {\n            min = guess;\n            guess *= multiplier;\n            if (guess > max)\n            {\n               guess = max;\n               f_current = -f_current;  // There must be a change of sign!\n               break;\n            }\n            multiplier *= 2;\n            unpack_0(f(guess), f_current);\n         }\n      }\n      else\n      {\n         //\n         // If min and max are negative we have to divide to head towards max:\n         //\n         while (--count && ((f_current < 0) == (f0 < 0)))\n         {\n            min = guess;\n            guess /= multiplier;\n            if (guess > max)\n            {\n               guess = max;\n               f_current = -f_current;  // There must be a change of sign!\n               break;\n            }\n            multiplier *= 2;\n            unpack_0(f(guess), f_current);\n         }\n      }\n\n      if (count)\n      {\n         max = guess;\n         if (multiplier > 16)\n            return (guess0 - guess) + bracket_root_towards_min(f, guess, f_current, min, max, count);\n      }\n      return guess0 - (max + min) / 2;\n   }\n\n   template <class F, class T>\n   T bracket_root_towards_min(F f, T guess, const T& f0, T& min, T& max, boost::uintmax_t& count) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n   {\n      using std::fabs;\n      //\n      // Move guess towards min until we bracket the root, updating min and max as we go:\n      //\n      T guess0 = guess;\n      T multiplier = 2;\n      T f_current = f0;\n\n      if (fabs(min) < fabs(max))\n      {\n         while (--count && ((f_current < 0) == (f0 < 0)))\n         {\n            max = guess;\n            guess /= multiplier;\n            if (guess < min)\n            {\n               guess = min;\n               f_current = -f_current;  // There must be a change of sign!\n               break;\n            }\n            multiplier *= 2;\n            unpack_0(f(guess), f_current);\n         }\n      }\n      else\n      {\n         //\n         // If min and max are negative we have to multiply to head towards min:\n         //\n         while (--count && ((f_current < 0) == (f0 < 0)))\n         {\n            max = guess;\n            guess *= multiplier;\n            if (guess < min)\n            {\n               guess = min;\n               f_current = -f_current;  // There must be a change of sign!\n               break;\n            }\n            multiplier *= 2;\n            unpack_0(f(guess), f_current);\n         }\n      }\n\n      if (count)\n      {\n         min = guess;\n         if (multiplier > 16)\n            return (guess0 - guess) + bracket_root_towards_max(f, guess, f_current, min, max, count);\n      }\n      return guess0 - (max + min) / 2;\n   }\n\n   template <class Stepper, class F, class T>\n   T second_order_root_finder(F f, T guess, T min, T max, int digits, boost::uintmax_t& max_iter) BOOST_NOEXCEPT_IF(policies::is_noexcept_error_policy<policies::policy<> >::value&& BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n   {\n      BOOST_MATH_STD_USING\n\n#ifdef BOOST_MATH_INSTRUMENT\n        std::cout << \"Second order root iteration, guess = \" << guess << \", min = \" << min << \", max = \" << max\n        << \", digits = \" << digits << \", max_iter = \" << max_iter << std::endl;\n#endif\n      static const char* function = \"boost::math::tools::halley_iterate<%1%>\";\n      if (min >= max)\n      {\n         return policies::raise_evaluation_error(function, \"Range arguments in wrong order in boost::math::tools::halley_iterate(first arg=%1%)\", min, boost::math::policies::policy<>());\n      }\n\n      T f0(0), f1, f2;\n      T result = guess;\n\n      T factor = ldexp(static_cast<T>(1.0), 1 - digits);\n      T delta = (std::max)(T(10000000 * guess), T(10000000));  // arbitrarily large delta\n      T last_f0 = 0;\n      T delta1 = delta;\n      T delta2 = delta;\n      bool out_of_bounds_sentry = false;\n\n   #ifdef BOOST_MATH_INSTRUMENT\n      std::cout << \"Second order root iteration, limit = \" << factor << std::endl;\n   #endif\n\n      //\n      // We use these to sanity check that we do actually bracket a root,\n      // we update these to the function value when we update the endpoints\n      // of the range.  Then, provided at some point we update both endpoints\n      // checking that max_range_f * min_range_f <= 0 verifies there is a root\n      // to be found somewhere.  Note that if there is no root, and we approach \n      // a local minima, then the derivative will go to zero, and hence the next\n      // step will jump out of bounds (or at least past the minima), so this\n      // check *should* happen in pathological cases.\n      //\n      T max_range_f = 0;\n      T min_range_f = 0;\n\n      boost::uintmax_t count(max_iter);\n\n      do {\n         last_f0 = f0;\n         delta2 = delta1;\n         delta1 = delta;\n         detail::unpack_tuple(f(result), f0, f1, f2);\n         --count;\n\n         BOOST_MATH_INSTRUMENT_VARIABLE(f0);\n         BOOST_MATH_INSTRUMENT_VARIABLE(f1);\n         BOOST_MATH_INSTRUMENT_VARIABLE(f2);\n\n         if (0 == f0)\n            break;\n         if (f1 == 0)\n         {\n            // Oops zero derivative!!!\n   #ifdef BOOST_MATH_INSTRUMENT\n            std::cout << \"Second order root iteration, zero derivative found!\" << std::endl;\n   #endif\n            detail::handle_zero_derivative(f, last_f0, f0, delta, result, guess, min, max);\n         }\n         else\n         {\n            if (f2 != 0)\n            {\n               delta = Stepper::step(result, f0, f1, f2);\n               if (delta * f1 / f0 < 0)\n               {\n                  // Oh dear, we have a problem as Newton and Halley steps\n                  // disagree about which way we should move.  Probably\n                  // there is cancelation error in the calculation of the\n                  // Halley step, or else the derivatives are so small\n                  // that their values are basically trash.  We will move\n                  // in the direction indicated by a Newton step, but\n                  // by no more than twice the current guess value, otherwise\n                  // we can jump way out of bounds if we're not careful.\n                  // See https://svn.boost.org/trac/boost/ticket/8314.\n                  delta = f0 / f1;\n                  if (fabs(delta) > 2 * fabs(guess))\n                     delta = (delta < 0 ? -1 : 1) * 2 * fabs(guess);\n               }\n            }\n            else\n               delta = f0 / f1;\n         }\n   #ifdef BOOST_MATH_INSTRUMENT\n         std::cout << \"Second order root iteration, delta = \" << delta << std::endl;\n   #endif\n         T convergence = fabs(delta / delta2);\n         if ((convergence > 0.8) && (convergence < 2))\n         {\n            // last two steps haven't converged.\n            delta = (delta > 0) ? (result - min) / 2 : (result - max) / 2;\n            if ((result != 0) && (fabs(delta) > result))\n               delta = sign(delta) * fabs(result) * 0.9f; // protect against huge jumps!\n            // reset delta2 so that this branch will *not* be taken on the\n            // next iteration:\n            delta2 = delta * 3;\n            delta1 = delta * 3;\n            BOOST_MATH_INSTRUMENT_VARIABLE(delta);\n         }\n         guess = result;\n         result -= delta;\n         BOOST_MATH_INSTRUMENT_VARIABLE(result);\n\n         // check for out of bounds step:\n         if (result < min)\n         {\n            T diff = ((fabs(min) < 1) && (fabs(result) > 1) && (tools::max_value<T>() / fabs(result) < fabs(min)))\n               ? T(1000)\n               : (fabs(min) < 1) && (fabs(tools::max_value<T>() * min) < fabs(result))\n               ? ((min < 0) != (result < 0)) ? -tools::max_value<T>() : tools::max_value<T>() : T(result / min);\n            if (fabs(diff) < 1)\n               diff = 1 / diff;\n            if (!out_of_bounds_sentry && (diff > 0) && (diff < 3))\n            {\n               // Only a small out of bounds step, lets assume that the result\n               // is probably approximately at min:\n               delta = 0.99f * (guess - min);\n               result = guess - delta;\n               out_of_bounds_sentry = true; // only take this branch once!\n            }\n            else\n            {\n               if (fabs(float_distance(min, max)) < 2)\n               {\n                  result = guess = (min + max) / 2;\n                  break;\n               }\n               delta = bracket_root_towards_min(f, guess, f0, min, max, count);\n               result = guess - delta;\n               guess = min;\n               continue;\n            }\n         }\n         else if (result > max)\n         {\n            T diff = ((fabs(max) < 1) && (fabs(result) > 1) && (tools::max_value<T>() / fabs(result) < fabs(max))) ? T(1000) : T(result / max);\n            if (fabs(diff) < 1)\n               diff = 1 / diff;\n            if (!out_of_bounds_sentry && (diff > 0) && (diff < 3))\n            {\n               // Only a small out of bounds step, lets assume that the result\n               // is probably approximately at min:\n               delta = 0.99f * (guess - max);\n               result = guess - delta;\n               out_of_bounds_sentry = true; // only take this branch once!\n            }\n            else\n            {\n               if (fabs(float_distance(min, max)) < 2)\n               {\n                  result = guess = (min + max) / 2;\n                  break;\n               }\n               delta = bracket_root_towards_max(f, guess, f0, min, max, count);\n               result = guess - delta;\n               guess = min;\n               continue;\n            }\n         }\n         // update brackets:\n         if (delta > 0)\n         {\n            max = guess;\n            max_range_f = f0;\n         }\n         else\n         {\n            min = guess;\n            min_range_f = f0;\n         }\n         //\n         // Sanity check that we bracket the root:\n         //\n         if (max_range_f * min_range_f > 0)\n         {\n            return policies::raise_evaluation_error(function, \"There appears to be no root to be found in boost::math::tools::newton_raphson_iterate, perhaps we have a local minima near current best guess of %1%\", guess, boost::math::policies::policy<>());\n         }\n      } while(count && (fabs(result * factor) < fabs(delta)));\n\n      max_iter -= count;\n\n   #ifdef BOOST_MATH_INSTRUMENT\n      std::cout << \"Second order root finder, final iteration count = \" << max_iter << std::endl;\n   #endif\n\n      return result;\n   }\n} // T second_order_root_finder\n\ntemplate <class F, class T>\nT halley_iterate(F f, T guess, T min, T max, int digits, boost::uintmax_t& max_iter) BOOST_NOEXCEPT_IF(policies::is_noexcept_error_policy<policies::policy<> >::value&& BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n{\n   return detail::second_order_root_finder<detail::halley_step>(f, guess, min, max, digits, max_iter);\n}\n\ntemplate <class F, class T>\ninline T halley_iterate(F f, T guess, T min, T max, int digits) BOOST_NOEXCEPT_IF(policies::is_noexcept_error_policy<policies::policy<> >::value&& BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n{\n   boost::uintmax_t m = (std::numeric_limits<boost::uintmax_t>::max)();\n   return halley_iterate(f, guess, min, max, digits, m);\n}\n\nnamespace detail {\n\n   struct schroder_stepper\n   {\n      template <class T>\n      static T step(const T& x, const T& f0, const T& f1, const T& f2) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(T))\n      {\n         using std::fabs;\n         T ratio = f0 / f1;\n         T delta;\n         if ((x != 0) && (fabs(ratio / x) < 0.1))\n         {\n            delta = ratio + (f2 / (2 * f1)) * ratio * ratio;\n            // check second derivative doesn't over compensate:\n            if (delta * ratio < 0)\n               delta = ratio;\n         }\n         else\n            delta = ratio;  // fall back to Newton iteration.\n         return delta;\n      }\n   };\n\n}\n\ntemplate <class F, class T>\nT schroder_iterate(F f, T guess, T min, T max, int digits, boost::uintmax_t& max_iter) BOOST_NOEXCEPT_IF(policies::is_noexcept_error_policy<policies::policy<> >::value&& BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n{\n   return detail::second_order_root_finder<detail::schroder_stepper>(f, guess, min, max, digits, max_iter);\n}\n\ntemplate <class F, class T>\ninline T schroder_iterate(F f, T guess, T min, T max, int digits) BOOST_NOEXCEPT_IF(policies::is_noexcept_error_policy<policies::policy<> >::value&& BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n{\n   boost::uintmax_t m = (std::numeric_limits<boost::uintmax_t>::max)();\n   return schroder_iterate(f, guess, min, max, digits, m);\n}\n//\n// These two are the old spelling of this function, retained for backwards compatibility just in case:\n//\ntemplate <class F, class T>\nT schroeder_iterate(F f, T guess, T min, T max, int digits, boost::uintmax_t& max_iter) BOOST_NOEXCEPT_IF(policies::is_noexcept_error_policy<policies::policy<> >::value&& BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n{\n   return detail::second_order_root_finder<detail::schroder_stepper>(f, guess, min, max, digits, max_iter);\n}\n\ntemplate <class F, class T>\ninline T schroeder_iterate(F f, T guess, T min, T max, int digits) BOOST_NOEXCEPT_IF(policies::is_noexcept_error_policy<policies::policy<> >::value&& BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))\n{\n   boost::uintmax_t m = (std::numeric_limits<boost::uintmax_t>::max)();\n   return schroder_iterate(f, guess, min, max, digits, m);\n}\n\n#ifndef BOOST_NO_CXX11_AUTO_DECLARATIONS\n/*\n   * Why do we set the default maximum number of iterations to the number of digits in the type?\n   * Because for double roots, the number of digits increases linearly with the number of iterations,\n   * so this default should recover full precision even in this somewhat pathological case.\n   * For isolated roots, the problem is so rapidly convergent that this doesn't matter at all.\n   */\ntemplate<class Complex, class F>\nComplex complex_newton(F g, Complex guess, int max_iterations = std::numeric_limits<typename Complex::value_type>::digits)\n{\n   typedef typename Complex::value_type Real;\n   using std::norm;\n   using std::abs;\n   using std::max;\n   // z0, z1, and z2 cannot be the same, in case we immediately need to resort to Muller's Method:\n   Complex z0 = guess + Complex(1, 0);\n   Complex z1 = guess + Complex(0, 1);\n   Complex z2 = guess;\n\n   do {\n      auto pair = g(z2);\n      if (norm(pair.second) == 0)\n      {\n         // Muller's method. Notation follows Numerical Recipes, 9.5.2:\n         Complex q = (z2 - z1) / (z1 - z0);\n         auto P0 = g(z0);\n         auto P1 = g(z1);\n         Complex qp1 = static_cast<Complex>(1) + q;\n         Complex A = q * (pair.first - qp1 * P1.first + q * P0.first);\n\n         Complex B = (static_cast<Complex>(2) * q + static_cast<Complex>(1)) * pair.first - qp1 * qp1 * P1.first + q * q * P0.first;\n         Complex C = qp1 * pair.first;\n         Complex rad = sqrt(B * B - static_cast<Complex>(4) * A * C);\n         Complex denom1 = B + rad;\n         Complex denom2 = B - rad;\n         Complex correction = (z1 - z2) * static_cast<Complex>(2) * C;\n         if (norm(denom1) > norm(denom2))\n         {\n            correction /= denom1;\n         }\n         else\n         {\n            correction /= denom2;\n         }\n\n         z0 = z1;\n         z1 = z2;\n         z2 = z2 + correction;\n      }\n      else\n      {\n         z0 = z1;\n         z1 = z2;\n         z2 = z2 - (pair.first / pair.second);\n      }\n\n      // See: https://math.stackexchange.com/questions/3017766/constructing-newton-iteration-converging-to-non-root\n      // If f' is continuous, then convergence of x_n -> x* implies f(x*) = 0.\n      // This condition approximates this convergence condition by requiring three consecutive iterates to be clustered.\n      Real tol = (max)(abs(z2) * std::numeric_limits<Real>::epsilon(), std::numeric_limits<Real>::epsilon());\n      bool real_close = abs(z0.real() - z1.real()) < tol && abs(z0.real() - z2.real()) < tol && abs(z1.real() - z2.real()) < tol;\n      bool imag_close = abs(z0.imag() - z1.imag()) < tol && abs(z0.imag() - z2.imag()) < tol && abs(z1.imag() - z2.imag()) < tol;\n      if (real_close && imag_close)\n      {\n         return z2;\n      }\n\n   } while (max_iterations--);\n\n   // The idea is that if we can get abs(f) < eps, we should, but if we go through all these iterations\n   // and abs(f) < sqrt(eps), then roundoff error simply does not allow that we can evaluate f to < eps\n   // This is somewhat awkward as it isn't scale invariant, but using the Daubechies coefficient example code,\n   // I found this condition generates correct roots, whereas the scale invariant condition discussed here:\n   // https://scicomp.stackexchange.com/questions/30597/defining-a-condition-number-and-termination-criteria-for-newtons-method\n   // allows nonroots to be passed off as roots.\n   auto pair = g(z2);\n   if (abs(pair.first) < sqrt(std::numeric_limits<Real>::epsilon()))\n   {\n      return z2;\n   }\n\n   return { std::numeric_limits<Real>::quiet_NaN(),\n            std::numeric_limits<Real>::quiet_NaN() };\n}\n#endif\n\n\n#if !defined(BOOST_NO_CXX17_IF_CONSTEXPR)\n// https://stackoverflow.com/questions/48979861/numerically-stable-method-for-solving-quadratic-equations/50065711\nnamespace detail\n{\n#if defined(BOOST_GNU_STDLIB) && !defined(_GLIBCXX_USE_C99_MATH_TR1)\ninline float fma_workaround(float x, float y, float z) { return ::fmaf(x, y, z); }\ninline double fma_workaround(double x, double y, double z) { return ::fma(x, y, z); }\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\ninline long double fma_workaround(long double x, long double y, long double z) { return ::fmal(x, y, z); }\n#endif\n#endif            \ntemplate<class T>\ninline T discriminant(T const& a, T const& b, T const& c)\n{\n   T w = 4 * a * c;\n#if defined(BOOST_GNU_STDLIB) && !defined(_GLIBCXX_USE_C99_MATH_TR1)\n   T e = fma_workaround(-c, 4 * a, w);\n   T f = fma_workaround(b, b, -w);\n#else\n   T e = std::fma(-c, 4 * a, w);\n   T f = std::fma(b, b, -w);\n#endif\n   return f + e;\n}\n\ntemplate<class T>\nstd::pair<T, T> quadratic_roots_imp(T const& a, T const& b, T const& c)\n{\n#if defined(BOOST_GNU_STDLIB) && !defined(_GLIBCXX_USE_C99_MATH_TR1)\n   using boost::math::copysign;\n#else\n   using std::copysign;\n#endif\n   using std::sqrt;\n   if constexpr (std::is_floating_point<T>::value)\n   {\n      T nan = std::numeric_limits<T>::quiet_NaN();\n      if (a == 0)\n      {\n         if (b == 0 && c != 0)\n         {\n            return std::pair<T, T>(nan, nan);\n         }\n         else if (b == 0 && c == 0)\n         {\n            return std::pair<T, T>(0, 0);\n         }\n         return std::pair<T, T>(-c / b, -c / b);\n      }\n      if (b == 0)\n      {\n         T x0_sq = -c / a;\n         if (x0_sq < 0) {\n            return std::pair<T, T>(nan, nan);\n         }\n         T x0 = sqrt(x0_sq);\n         return std::pair<T, T>(-x0, x0);\n      }\n      T discriminant = detail::discriminant(a, b, c);\n      // Is there a sane way to flush very small negative values to zero?\n      // If there is I don't know of it.\n      if (discriminant < 0)\n      {\n         return std::pair<T, T>(nan, nan);\n      }\n      T q = -(b + copysign(sqrt(discriminant), b)) / T(2);\n      T x0 = q / a;\n      T x1 = c / q;\n      if (x0 < x1)\n      {\n         return std::pair<T, T>(x0, x1);\n      }\n      return std::pair<T, T>(x1, x0);\n   }\n   else if constexpr (boost::math::tools::is_complex_type<T>::value)\n   {\n      typename T::value_type nan = std::numeric_limits<typename T::value_type>::quiet_NaN();\n      if (a.real() == 0 && a.imag() == 0)\n      {\n         using std::norm;\n         if (b.real() == 0 && b.imag() && norm(c) != 0)\n         {\n            return std::pair<T, T>({ nan, nan }, { nan, nan });\n         }\n         else if (b.real() == 0 && b.imag() && c.real() == 0 && c.imag() == 0)\n         {\n            return std::pair<T, T>({ 0,0 }, { 0,0 });\n         }\n         return std::pair<T, T>(-c / b, -c / b);\n      }\n      if (b.real() == 0 && b.imag() == 0)\n      {\n         T x0_sq = -c / a;\n         T x0 = sqrt(x0_sq);\n         return std::pair<T, T>(-x0, x0);\n      }\n      // There's no fma for complex types:\n      T discriminant = b * b - T(4) * a * c;\n      T q = -(b + sqrt(discriminant)) / T(2);\n      return std::pair<T, T>(q / a, c / q);\n   }\n   else // Most likely the type is a boost.multiprecision.\n   {    //There is no fma for multiprecision, and in addition it doesn't seem to be useful, so revert to the naive computation.\n      T nan = std::numeric_limits<T>::quiet_NaN();\n      if (a == 0)\n      {\n         if (b == 0 && c != 0)\n         {\n            return std::pair<T, T>(nan, nan);\n         }\n         else if (b == 0 && c == 0)\n         {\n            return std::pair<T, T>(0, 0);\n         }\n         return std::pair<T, T>(-c / b, -c / b);\n      }\n      if (b == 0)\n      {\n         T x0_sq = -c / a;\n         if (x0_sq < 0) {\n            return std::pair<T, T>(nan, nan);\n         }\n         T x0 = sqrt(x0_sq);\n         return std::pair<T, T>(-x0, x0);\n      }\n      T discriminant = b * b - 4 * a * c;\n      if (discriminant < 0)\n      {\n         return std::pair<T, T>(nan, nan);\n      }\n      T q = -(b + copysign(sqrt(discriminant), b)) / T(2);\n      T x0 = q / a;\n      T x1 = c / q;\n      if (x0 < x1)\n      {\n         return std::pair<T, T>(x0, x1);\n      }\n      return std::pair<T, T>(x1, x0);\n   }\n}\n}  // namespace detail\n\ntemplate<class T1, class T2 = T1, class T3 = T1>\ninline std::pair<typename tools::promote_args<T1, T2, T3>::type, typename tools::promote_args<T1, T2, T3>::type> quadratic_roots(T1 const& a, T2 const& b, T3 const& c)\n{\n   typedef typename tools::promote_args<T1, T2, T3>::type value_type;\n   return detail::quadratic_roots_imp(static_cast<value_type>(a), static_cast<value_type>(b), static_cast<value_type>(c));\n}\n\n#endif\n\n} // namespace tools\n} // namespace math\n} // namespace boost\n\n#endif // BOOST_MATH_TOOLS_NEWTON_SOLVER_HPP\n", "meta": {"hexsha": "145f4947f1679baed42469d3de0b2c1d6fab00b7", "size": 34330, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "eosio.evm/external/boost/math/tools/roots.hpp", "max_stars_repo_name": "conr2d/eosio.evm", "max_stars_repo_head_hexsha": "93e6b9bd46bef24e356f924ed1bf0c33196e7432", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 84.0, "max_stars_repo_stars_event_min_datetime": "2020-02-26T22:26:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T20:21:47.000Z", "max_issues_repo_path": "eosio.evm/external/boost/math/tools/roots.hpp", "max_issues_repo_name": "cnamway/eosio.evm", "max_issues_repo_head_hexsha": "93e6b9bd46bef24e356f924ed1bf0c33196e7432", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-02-22T04:15:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T20:06:16.000Z", "max_forks_repo_path": "eosio.evm/external/boost/math/tools/roots.hpp", "max_forks_repo_name": "cnamway/eosio.evm", "max_forks_repo_head_hexsha": "93e6b9bd46bef24e356f924ed1bf0c33196e7432", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2020-02-27T14:07:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T07:53:36.000Z", "avg_line_length": 33.8226600985, "max_line_length": 256, "alphanum_fraction": 0.5651325371, "num_tokens": 9497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5, "lm_q1q2_score": 0.26949161034384206}}
{"text": "/// @file\n///\n/// A linear solver for parameters from the normal equations\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#include <fitting/LinearSolver.h>\n\n#include <askap/AskapError.h>\n#include <profile/AskapProfiler.h>\n#include <boost/config.hpp>\n\n#include <casacore/casa/aips.h>\n#include <casacore/casa/Arrays/Array.h>\n#include <casacore/casa/Arrays/Matrix.h>\n#include <casacore/casa/Arrays/Vector.h>\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_linalg.h>\n\n#include <askap/AskapLogging.h>\nASKAP_LOGGER(logger, \".linearsolver\");\n\n#include <iostream>\n\n#include <string>\n#include <map>\n\n#include <cmath>\nusing std::abs;\nusing std::map;\nusing std::string;\n\nnamespace askap\n{\n  namespace scimath\n  {\n    BOOST_CONSTEXPR_OR_CONST double LinearSolver::KeepAllSingularValues;\n    \n    /// @brief Constructor\n    /// @details Optionally, it is possible to limit the condition number of\n    /// normal equation matrix to a given number.\n    /// @param maxCondNumber maximum allowed condition number of the range\n    /// of the normal equation matrix for the SVD algorithm. Effectively this\n    /// puts the limit on the singular values, which are considered to be\n    /// non-zero (all greater than the largest singular value divided by this\n    /// condition number threshold). Default is 1e3. Put a negative number\n    /// if you don't want to drop any singular values (may be a not very wise\n    /// thing to do!). A very large threshold has the same effect. Zero\n    /// threshold is not allowed and will cause an exception.\n    LinearSolver::LinearSolver(double maxCondNumber) : \n           itsMaxCondNumber(maxCondNumber) \n    {\n      ASKAPASSERT(itsMaxCondNumber!=0);\n    };\n\n    \n    void LinearSolver::init()\n    {\n      resetNormalEquations();\n    }\n    \n/// @brief test that all matrix elements are below tolerance by absolute value\n/// @details This is a helper method to test all matrix elements\n/// @param[in] matr matrix to test\n/// @param[in] tolerance tolerance on the element absolute values\n/// @return true if all elements are zero within the tolerance\nbool LinearSolver::allMatrixElementsAreZeros(const casa::Matrix<double> &matr, const double tolerance)\n{\n  for (casa::uInt row = 0; row < matr.nrow(); ++row) {\n       for (casa::uInt col = 0; col < matr.ncolumn(); ++col) {\n            if (abs(matr(row,col)) > tolerance) {\n                return false;\n            }\n       }\n  }\n  return true;\n} \n    \n    \n/// @brief extract an independent subset of parameters\n/// @details This method analyses the normal equations and forms a subset of \n/// parameters which can be solved for independently. Although the SVD is more than\n/// capable of dealing with degeneracies, it is often too slow if the number of parameters is large.\n/// This method essentially gives the solver a hint based on the structure of the equations\n/// @param[in] names names for parameters to choose from\n/// @param[in] tolerance tolerance on the matrix elements to decide whether they can be considered independent\n/// @return names of parameters in this subset\nstd::vector<std::string> LinearSolver::getIndependentSubset(std::vector<std::string> &names, const double tolerance) const\n{\n   ASKAPTRACE(\"LinearSolver::getIndependentSubset\");\n   ASKAPDEBUGASSERT(names.size() > 0);\n   std::vector<std::string> resultNames;\n   resultNames.reserve(names.size());\n   resultNames.push_back(names[0]);\n   for (std::vector<std::string>::const_iterator ci = ++names.begin(); ci != names.end(); ++ci) {\n        for (std::vector<std::string>::const_iterator ciRes = resultNames.begin(); ciRes != resultNames.end(); ++ciRes) {\n             const casa::Matrix<double>& nm1 = normalEquations().normalMatrix(*ci, *ciRes);\n             const casa::Matrix<double>& nm2 = normalEquations().normalMatrix(*ciRes, *ci);\n             if (!allMatrixElementsAreZeros(nm1,tolerance) || !allMatrixElementsAreZeros(nm2,tolerance)) {\n                 // this parameter (iterated in the outer loop) belongs to the same subset\n                 resultNames.push_back(*ci);\n                 break;\n             } \n        }\n   } \n   return resultNames;\n}\n    \n    \n/// @brief solve for a subset of parameters\n/// @details This method is used in solveNormalEquations\n/// @param[in] params parameters to be updated           \n/// @param[in] quality Quality of the solution\n/// @param[in] names names of the parameters to solve for \nstd::pair<double,double>  LinearSolver::solveSubsetOfNormalEquations(Params &params, Quality& quality, \n                   const std::vector<std::string> &names) const\n{\n    ASKAPTRACE(\"LinearSolver::solveSubsetOfNormalEquations\");\n    std::pair<double,double> result(0.,0.);\n    \n// Solving A^T Q^-1 V = (A^T Q^-1 A) P\n\n    int nParameters = 0;\n\n    std::vector<std::pair<string, int> > indices(names.size());\n    {\n      std::vector<std::pair<string, int> >::iterator it = indices.begin();\n      for (vector<string>::const_iterator cit=names.begin(); cit!=names.end(); ++cit,++it)\n      {\n        ASKAPDEBUGASSERT(it != indices.end());\n        it->second = nParameters;\n        it->first = *cit;\n        ASKAPLOG_DEBUG_STR(logger, \"Processing \"<<*cit<<\" \"<<nParameters);\n        const casa::uInt newParameters = normalEquations().dataVector(*cit).nelements();\n        nParameters += newParameters;\n        ASKAPDEBUGASSERT((params.isFree(*cit) ? params.value(*cit).nelements() : newParameters) == newParameters);        \n      }\n    }\n    ASKAPLOG_DEBUG_STR(logger, \"Done\");\n    ASKAPCHECK(nParameters>0, \"No free parameters in a subset of normal equations\");\n    \n    ASKAPDEBUGASSERT(indices.size() > 0);\n        \n    // Convert the normal equations to gsl format\n    gsl_matrix * A = gsl_matrix_alloc (nParameters, nParameters);\n    gsl_vector * B = gsl_vector_alloc (nParameters);\n    gsl_vector * X = gsl_vector_alloc (nParameters);\n\n    for (std::vector<std::pair<string, int> >::const_iterator indit2=indices.begin();indit2!=indices.end(); ++indit2)  {\n        for (std::vector<std::pair<string, int> >::const_iterator indit1=indices.begin();indit1!=indices.end(); ++indit1)  {\n             // Axes are dof, dof for each parameter\n             // Take a deep breath for const-safe indexing into the double layered map\n             const casa::Matrix<double>& nm = normalEquations().normalMatrix(indit1->first, indit2->first);\n          \n             for (size_t row=0; row<nm.nrow(); ++row)  {\n                  for (size_t col=0; col<nm.ncolumn(); ++col) {\n                       const double elem = nm(row,col);\n                       ASKAPCHECK(!std::isnan(elem), \"Normal matrix seems to have NaN for row = \"<<row<<\" and col = \"<<col<<\", this shouldn't happem!\");\n                       gsl_matrix_set(A, row+(indit1->second), col+(indit2->second), elem);\n                       //   std::cout << \"A \" << row << \" \" << col << \" \" << nm(row,col) << std::endl; \n                  }\n             }\n         }\n    }\n    \n    for (std::vector<std::pair<string, int> >::const_iterator indit1=indices.begin();indit1!=indices.end(); ++indit1) {\n        const casa::Vector<double> &dv = normalEquations().dataVector(indit1->first);\n        for (size_t row=0; row<dv.nelements(); ++row) {\n             const double elem = dv(row);\n             ASKAPCHECK(!std::isnan(elem), \"Data vector seems to have NaN for row = \"<<row<<\", this shouldn't happem!\");\n             gsl_vector_set(B, row+(indit1->second), elem);\n//          std::cout << \"B \" << row << \" \" << dv(row) << std::endl; \n        }\n    }\n      \n      /*\n      // temporary code to export matrices, which cause problems with the GSL\n      // to write up a clear case\n      {\n        std::ofstream os(\"dbg.dat\");\n        os<<nParameters<<std::endl;\n        for (int row=0;row<nParameters;++row) {\n             for (int col=0;col<nParameters;++col) {\n                  if (col) {\n                      os<<\" \";\n                  } \n                  os<<gsl_matrix_get(A,row,col);\n             }\n             os<<std::endl;\n        }\n      }\n      // end of the temporary code\n      */\n      \n    if(algorithm()==\"SVD\")  {  \n         gsl_matrix * V = gsl_matrix_alloc (nParameters, nParameters);\n         ASKAPDEBUGASSERT(V!=NULL);\n         gsl_vector * S = gsl_vector_alloc (nParameters);\n         ASKAPDEBUGASSERT(S!=NULL);\n         gsl_vector * work = gsl_vector_alloc (nParameters);\n         ASKAPDEBUGASSERT(work!=NULL);\n        \n         const int status = gsl_linalg_SV_decomp (A, V, S, work);\n         ASKAPCHECK(status == 0, \"gsl_linalg_SV_decomp failed, status = \"<<status);\n        \n         // a hack for now. For some reason, for some matrices gsl_linalg_SV_decomp may return NaN as singular value, perhaps some\n         // numerical precision issue inside SVD. Although it needs to be investigated further  (see ASKAPSDP-2270), for now trying\n         // to replace those singular values with zeros to exclude them from processing. Note, singular vectors may also contain NaNs\n         for (int i=0; i<nParameters; ++i) {\n              if (std::isnan(gsl_vector_get(S,i))) {\n                  gsl_vector_set(S,i,0.);\n              }\n              for (int k=0; k < nParameters; ++k) {\n                   ASKAPCHECK(!std::isnan(gsl_matrix_get(V,i,k)), \"NaN in V: i=\"<<i<<\" k=\"<<k); \n              }\n         }\n\n         // end of the hack\n\n         //SVDecomp (A, V, S);\n        \n         // code to put a limit on the condition number of the system\n         const double singularValueLimit = nParameters>1 ? \n                     gsl_vector_get(S,0)/itsMaxCondNumber : -1.; \n         for (int i=1; i<nParameters; ++i) {\n              if (gsl_vector_get(S,i)<singularValueLimit) {\n                  gsl_vector_set(S,i,0.);\n              }\n         }\n        \n        /*\n        // temporary code for debugging\n        {\n          std::ofstream os(\"dbg2.dat\");\n          for (int i=0; i<nParameters; ++i) {\n               os<<i<<\" \"<<gsl_vector_get(S,i)<<std::endl;\n          } \n          \n          //std::cout<<\"new singular value spectrum is ready\"<<std::endl;\n          //char tst;\n          //std::cin>>tst;\n          \n        }\n        // end of temporary code\n        */\n        \n         gsl_vector * X = gsl_vector_alloc(nParameters);\n         ASKAPDEBUGASSERT(X!=NULL);\n        \n         const int solveStatus = gsl_linalg_SV_solve (A, V, S, B, X);\n         ASKAPCHECK(solveStatus == 0, \"gsl_linalg_SV_solve failed\");\n        \n// Now find the statistics for the decomposition\n         int rank=0;\n         double smin = 1e50;\n         double smax = 0.0;\n         for (int i=0;i<nParameters; ++i) {\n              const double sValue = std::abs(gsl_vector_get(S, i));\n              ASKAPCHECK(!std::isnan(sValue), \"Got NaN as a singular value for normal matrix, this shouldn't happen S[i]=\"<<gsl_vector_get(S,i)<<\" parameter \"<<i<<\" singularValueLimit=\"<<singularValueLimit);\n              if(sValue>0.0) {\n                 ++rank;\n                 if ((sValue>smax) || (i == 0)) {\n                     smax=sValue;\n                 }\n                 if ((sValue<smin) || (i == 0)) {\n                     smin=sValue;\n                 }\n               }\n         }\n         result.first = smin;\n         result.second = smax;\n         \n         quality.setDOF(nParameters);\n         quality.setRank(rank);\n         quality.setCond(smax/smin);\n         if(rank==nParameters) {\n            quality.setInfo(\"SVD decomposition rank complete\");\n         } else {\n            quality.setInfo(\"SVD decomposition rank deficient\");\n         }\n      \n// Update the parameters for the calculated changes. Exploit reference\n// semantics of casa::Array.\n         std::vector<std::pair<string, int> >::const_iterator indit;\n         for (indit=indices.begin();indit!=indices.end();++indit) {\n              casa::IPosition vecShape(1, params.value(indit->first).nelements());\n              casa::Vector<double> value(params.value(indit->first).reform(vecShape));\n              for (size_t i=0; i<value.nelements(); ++i)  {\n//          \t   std::cout << value(i) << \" \" << gsl_vector_get(X, indit->second+i) << std::endl;\n                   const double adjustment = gsl_vector_get(X, indit->second+i);\n                   ASKAPCHECK(!std::isnan(adjustment), \"Solution resulted in NaN as an update for parameter \"<<(indit->second + i));\n                   value(i) += adjustment;\n              }\n          }\n          gsl_vector_free(S);\n          gsl_vector_free(work);\n          gsl_matrix_free(V);\n    } else {\n        quality.setInfo(\"Cholesky decomposition\");\n        gsl_linalg_cholesky_decomp(A);\n        gsl_linalg_cholesky_solve(A, B, X);\n// Update the parameters for the calculated changes\n        std::vector<std::pair<string, int> >::const_iterator indit;\n        for (indit=indices.begin();indit!=indices.end();++indit)\n        {\n          casa::IPosition vecShape(1, params.value(indit->first).nelements());\n          casa::Vector<double> value(params.value(indit->first).reform(vecShape));\n          for (size_t i=0; i<value.nelements(); ++i)  {\n               value(i)+=gsl_vector_get(X, indit->second+i);\n          }\n        }\n    }\n\n// Free up gsl storage\n    gsl_vector_free(B);\n    gsl_matrix_free(A);\n    gsl_vector_free(X);\n    return result;\n}    \n\n    /// @brief solve for parameters\n    /// The solution is constructed from the normal equations and given\n    /// parameters are updated. If there are no free parameters in the\n    /// given Params class, all unknowns in the normal\n    /// equatons will be solved for.\n    /// @param[in] params parameters to be updated \n    /// @param[in] quality Quality of solution\n    /// @note This is fully general solver for the normal equations for any shape\n    /// parameters.        \n    bool LinearSolver::solveNormalEquations(Params &params, Quality& quality)\n    {\n      ASKAPTRACE(\"LinearSolver::solveNormalEquations\");\n      \n// Solving A^T Q^-1 V = (A^T Q^-1 A) P\n     \n// Find all the free parameters\n      vector<string> names(params.freeNames());\n      if (names.size() == 0) {\n          // list of parameters is empty, will solve for all \n          // unknowns in the equation \n          names = normalEquations().unknowns();\n      }\n      ASKAPCHECK(names.size()>0, \"No free parameters in Linear Solver\");\n\n      if (names.size() < 100) {\n          // no need to extract independent blocks if number of unknowns is small\n          solveSubsetOfNormalEquations(params,quality,names);\n      } else {\n          while (names.size() > 0) {\n              const std::vector<std::string> subsetNames = getIndependentSubset(names,1e-6);\n              if (subsetNames.size() == names.size()) {\n                  names.resize(0);\n              } else {\n                  // remove the elements corresponding to the current subset from the list of names prepared for the\n                  // following integration\n                  std::vector<size_t> indicesToRemove(subsetNames.size(),subsetNames.size());                                   \n                  for (size_t index = 0,indexToRemove = 0; index < names.size(); ++index) {\n                       if (find(subsetNames.begin(),subsetNames.end(),names[index]) != subsetNames.end()) {\n                           ASKAPDEBUGASSERT(indexToRemove < indicesToRemove.size());\n                           indicesToRemove[indexToRemove++] = index;\n                       }\n                  }\n                  \n                  // the following could be done more elegantly/faster, but leave the optimisation to later time                  \n                  for (std::vector<size_t>::const_reverse_iterator ci = indicesToRemove.rbegin(); ci!=indicesToRemove.rend(); ++ci) {\n                       ASKAPDEBUGASSERT(*ci < names.size());\n                       names.erase(names.begin() + *ci);\n                  }\n              }\n              solveSubsetOfNormalEquations(params,quality, subsetNames);\n          } \n      }\n        \n      return true;\n    };\n\n    Solver::ShPtr LinearSolver::clone() const\n    {\n      return Solver::ShPtr(new LinearSolver(*this));\n    }\n\n  }\n}\n", "meta": {"hexsha": "b6949769861f6196e9e9e70d6b42d7e63d339f11", "size": 17118, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Code/Base/scimath/current/fitting/LinearSolver.cc", "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": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/Base/scimath/current/fitting/LinearSolver.cc", "max_issues_repo_name": "rtobar/askapsoft", "max_issues_repo_head_hexsha": "6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e", "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/Base/scimath/current/fitting/LinearSolver.cc", "max_forks_repo_name": "rtobar/askapsoft", "max_forks_repo_head_hexsha": "6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e", "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": 41.9558823529, "max_line_length": 207, "alphanum_fraction": 0.5985512326, "num_tokens": 4099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5, "lm_q1q2_score": 0.26949161034384206}}
{"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_EXTENSIONS_GIS_LATLONG_DETAIL_GRATICULE_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_GIS_LATLONG_DETAIL_GRATICULE_HPP\n\n#include <cmath>\n#include <sstream>\n#include <string>\n\n#include <boost/numeric/conversion/cast.hpp>\n#include <boost/geometry/util/math.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n/*!\n    \\brief Cardinal directions.\n    \\ingroup cs\n    \\details They are used in the dms-class. When specified by the library user,\n    north/east/south/west is, in general, enough. When parsed or received by an algorithm,\n    the user knows it it is lat/long but not more\n*/\nenum cd_selector\n{\n    /*cd_none, */\n    north,\n    east,\n    south,\n    west,\n    cd_lat,\n    cd_lon\n};\n\n/*!\n    \\brief Utility class to assign poinst with degree,minute,second\n    \\ingroup cs\n    \\note Normally combined with latitude and longitude classes\n    \\tparam CardinalDir selects if it is north/south/west/east\n    \\tparam coordinate value, double/float\n    \\par Example:\n    Example showing how to use the dms class\n    \\dontinclude doxygen_1.cpp\n    \\skip example_dms\n    \\line {\n    \\until }\n*/\ntemplate <cd_selector CardinalDir, typename T = double>\nclass dms\n{\npublic:\n\n    /// Constructs with a value\n    inline explicit dms(T v)\n        : m_value(v)\n    {}\n\n    /// Constructs with a degree, minute, optional second\n    inline explicit dms(int d, int m, T s = 0.0)\n    {\n        double v = ((CardinalDir == west || CardinalDir == south) ? -1.0 : 1.0)\n                    * (double(d) + (m / 60.0) + (s / 3600.0));\n\n        m_value = boost::numeric_cast<T>(v);\n    }\n\n    // Prohibit automatic conversion to T\n    // because this would enable lon(dms<south>)\n    // inline operator T() const { return m_value; }\n\n    /// Explicit conversion to T (double/float)\n    inline const T& as_value() const\n    {\n        return m_value;\n    }\n\n    /// Get degrees as integer, minutes as integer, seconds as double.\n    inline void get_dms(int& d, int& m, double& s,\n                        bool& positive, char& cardinal) const\n    {\n        double value = m_value;\n\n        // Set to normal earth latlong coordinates\n        while (value < -180)\n        {\n            value += 360;\n        }\n        while (value > 180)\n        {\n            value -= 360;\n        }\n        // Make positive and indicate this\n        positive = value > 0;\n\n        // Todo: we might implement template/specializations here\n        // Todo: if it is \"west\" and \"positive\", make east? or keep minus sign then?\n\n        cardinal = ((CardinalDir == cd_lat && positive) ? 'N'\n            :  (CardinalDir == cd_lat && !positive) ? 'S'\n            :  (CardinalDir == cd_lon && positive) ? 'E'\n            :  (CardinalDir == cd_lon && !positive) ? 'W'\n            :  (CardinalDir == east) ? 'E'\n            :  (CardinalDir == west) ? 'W'\n            :  (CardinalDir == north) ? 'N'\n            :  (CardinalDir == south) ? 'S'\n            : ' ');\n\n        value = geometry::math::abs(value);\n\n        // Calculate the values\n        double fraction = 0;\n        double integer = 0;\n        fraction = std::modf(value, &integer);\n        d = int(integer);\n        s = 60.0 * std::modf(fraction * 60.0, &integer);\n        m = int(integer);\n    }\n\n    /// Get degrees, minutes, seconds as a string, separators can be specified optionally\n    inline std::string get_dms(std::string const& ds = \" \",\n        const std::string& ms = \"'\",\n        const std::string& ss = \"\\\"\") const\n    {\n        double s = 0;\n        int d = 0;\n        int m = 0;\n        bool positive = false;\n        char cardinal = 0;\n        get_dms(d, m, s, positive, cardinal);\n        std::ostringstream out;\n        out << d << ds << m << ms << s << ss << \" \" << cardinal;\n\n        return out.str();\n    }\n\nprivate:\n\n    T m_value;\n};\n\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n/*!\n    \\brief internal base class for latitude and longitude classes\n    \\details The latitude longitude classes define different types for lat and lon. This is convenient\n    to construct latlong class without ambiguity.\n    \\note It is called graticule, after <em>\"This latitude/longitude \"webbing\" is known as the common\n    graticule\" (http://en.wikipedia.org/wiki/Geographic_coordinate_system)</em>\n    \\tparam S latitude/longitude\n    \\tparam T coordinate type, double float or int\n*/\ntemplate <typename T>\nclass graticule\n{\npublic:\n\n    // TODO: Pass 'v' by const-ref\n    inline explicit graticule(T v) : m_v(v) {}\n    inline operator T() const { return m_v; }\n\nprivate:\n\n    T m_v;\n};\n\n} // namespace detail\n#endif // DOXYGEN_NO_DETAIL\n\n/*!\n    \\brief Utility class to assign points with latitude value (north/south)\n    \\ingroup cs\n    \\tparam T coordinate type, double / float\n    \\note Often combined with dms class\n*/\ntemplate <typename T = double>\nclass latitude : public detail::graticule<T>\n{\npublic:\n\n    /// Can be constructed with a value\n    inline explicit latitude(T v)\n        : detail::graticule<T>(v)\n    {}\n\n    /// Can be constructed with a NORTH dms-class\n    inline explicit latitude(dms<north,T> const& v)\n        : detail::graticule<T>(v.as_value())\n    {}\n\n    /// Can be constructed with a SOUTH dms-class\n    inline explicit latitude(dms<south,T> const& v)\n       : detail::graticule<T>(v.as_value())\n   {}\n};\n\n/*!\n\\brief Utility class to assign points with longitude value (west/east)\n\\ingroup cs\n\\tparam T coordinate type, double / float\n\\note Often combined with dms class\n*/\ntemplate <typename T = double>\nclass longitude : public detail::graticule<T>\n{\npublic:\n\n    /// Can be constructed with a value\n    inline explicit longitude(T v)\n        : detail::graticule<T>(v)\n    {}\n\n    /// Can be constructed with a WEST dms-class\n    inline explicit longitude(dms<west, T> const& v)\n        : detail::graticule<T>(v.as_value())\n    {}\n\n    /// Can be constructed with an EAST dms-class\n    inline explicit longitude(dms<east, T> const& v)\n        : detail::graticule<T>(v.as_value())\n    {}\n};\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_GIS_LATLONG_DETAIL_GRATICULE_HPP\n", "meta": {"hexsha": "84f519e72bd0cafc2bf68ddd2b81934741f57ae3", "size": 6642, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Siv3D/src/ThirdParty/boost/geometry/extensions/gis/latlong/detail/graticule.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/gis/latlong/detail/graticule.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/gis/latlong/detail/graticule.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": 27.7907949791, "max_line_length": 102, "alphanum_fraction": 0.6278229449, "num_tokens": 1717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2694916029385518}}
{"text": "/*\n * Copyright (c) 2020 Johannes Pankert <pankertj@ethz.ch>\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 * 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 this work 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 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#include <Eigen/Dense>\n#include <perceptive_mpc/kinematics/KinematicsInterface.hpp>\n\nusing namespace perceptive_mpc;\n\ntemplate <typename SCALAR_T>\nKinematicsInterface<SCALAR_T>::KinematicsInterface(const KinematicInterfaceConfig& config) : config_(config) {}\n\ntemplate <typename SCALAR_T>\nvoid KinematicsInterface<SCALAR_T>::computeState2EndeffectorTransform(Eigen::Matrix<SCALAR_T, 4, 4>& transform,\n                                                                      const Eigen::Matrix<SCALAR_T, -1, 1>& state) const {\n  if (state.size() != 13) {\n    std::stringstream ss;\n    ss << \"Error: state.size()=\" << state.size() << \"!=13\";\n    std::string errorMessage = ss.str();\n    std::cerr << std::endl << errorMessage << std::endl << std::endl;\n    throw std::runtime_error(ss.str());\n  }\n\n  Eigen::Quaternion<SCALAR_T> baseOrientation;\n  baseOrientation.coeffs() = state.template head<7>().template head<4>();\n  const Eigen::Matrix<SCALAR_T, 3, 1>& basePosition = state.template head<7>().template tail<3>();\n  const Eigen::Matrix<SCALAR_T, 6, 1>& armState = state.template tail<6>();\n\n  // homogeneous transform world -> base\n  Eigen::Matrix<SCALAR_T, 4, 4> homWorld2Base = Eigen::Matrix<SCALAR_T, 4, 4>::Identity();\n  homWorld2Base.template topLeftCorner<3, 3>() = baseOrientation.toRotationMatrix();\n  homWorld2Base.template topRightCorner<3, 1>() = basePosition;\n\n  // world -> endeffector\n  transform = homWorld2Base * computeBase2EndeffectorTransform(armState);\n}\n\ntemplate <typename SCALAR_T>\nEigen::Matrix<SCALAR_T, 4, 4> KinematicsInterface<SCALAR_T>::computeBase2EndeffectorTransform(\n    const Eigen::Matrix<SCALAR_T, 6, 1>& armState) const {\n  const Eigen::Matrix<SCALAR_T, 4, 4> armBaseToWrist2Transform = computeArmMountToToolMountTransform(armState);\n  return config_.transformBase_X_ArmMount.template cast<SCALAR_T>() * armBaseToWrist2Transform *\n         config_.transformToolMount_X_Endeffector.template cast<SCALAR_T>();\n}\n\ntemplate <typename SCALAR_T>\nEigen::Matrix<SCALAR_T, 3, -1> KinematicsInterface<SCALAR_T>::computeState2MultiplePointsOnRobot(\n    const Eigen::Matrix<SCALAR_T, -1, 1>& state, const std::vector<std::vector<double>>& points) const {\n  if (state.size() != 13) {\n    std::stringstream ss;\n    ss << \"Error: state.size()=\" << state.size() << \"!=13\";\n    std::string errorMessage = ss.str();\n    std::cerr << std::endl << errorMessage << std::endl << std::endl;\n    throw std::runtime_error(ss.str());\n  }\n\n  int dim = 0;\n  for (int i = 0; i < points.size(); i++) {\n    for (int j = 0; j < points[i].size(); j++) {\n      dim++;\n    }\n  }\n  if (dim == 0) {\n    return Eigen::Matrix<SCALAR_T, 3, -1>(3, 0);\n  }\n  Eigen::Matrix<SCALAR_T, 3, -1> result(3, dim);\n  int resultIndex = 0;\n  int linkIndex;\n\n  Eigen::Quaternion<SCALAR_T> baseOrientation;\n  baseOrientation.coeffs() = state.template head<7>().template head<4>();\n  const Eigen::Matrix<SCALAR_T, 3, 1>& basePosition = state.template head<7>().template tail<3>();\n  const Eigen::Matrix<SCALAR_T, 6, 1>& armState = state.template tail<6>();\n\n  Eigen::Matrix<SCALAR_T, 4, 4> worldXFrBase = Eigen::Matrix<SCALAR_T, 4, 4>::Identity();\n  worldXFrBase.template topLeftCorner<3, 3>() = baseOrientation.toRotationMatrix();\n  worldXFrBase.template topRightCorner<3, 1>() = basePosition;\n\n  return computeArmState2MultiplePointsOnRobot(armState, points, config_.transformBase_X_ArmMount, config_.transformToolMount_X_Endeffector,\n                                               worldXFrBase);\n}\n\ntemplate <typename SCALAR_T>\nEigen::Quaternion<SCALAR_T> KinematicsInterface<SCALAR_T>::matrixToQuaternion(const Eigen::Matrix<SCALAR_T, 3, 3>& R) const {\n  SCALAR_T t1, t2, t;\n  SCALAR_T x1, x2, x;\n  SCALAR_T y1, y2, y;\n  SCALAR_T z1, z2, z;\n  SCALAR_T w1, w2, w;\n\n  t1 = CppAD::CondExpGt(R(0, 0), R(1, 1), 1 + R(0, 0) - R(1, 1) - R(2, 2), 1 - R(0, 0) + R(1, 1) - R(2, 2));\n  t2 = CppAD::CondExpLt(R(0, 0), -R(1, 1), 1 - R(0, 0) - R(1, 1) + R(2, 2), 1 + R(0, 0) + R(1, 1) + R(2, 2));\n  t = CppAD::CondExpLt(R(2, 2), SCALAR_T(0.0), t1, t2);\n\n  x1 = CppAD::CondExpGt(R(0, 0), R(1, 1), t, R(1, 0) + R(0, 1));\n  x2 = CppAD::CondExpLt(R(0, 0), -R(1, 1), R(0, 2) + R(2, 0), R(2, 1) - R(1, 2));\n  x = CppAD::CondExpLt(R(2, 2), SCALAR_T(0.0), x1, x2);\n\n  y1 = CppAD::CondExpGt(R(0, 0), R(1, 1), R(1, 0) + R(0, 1), t);\n  y2 = CppAD::CondExpLt(R(0, 0), -R(1, 1), R(2, 1) + R(1, 2), R(0, 2) - R(2, 0));\n  y = CppAD::CondExpLt(R(2, 2), SCALAR_T(0.0), y1, y2);\n\n  z1 = CppAD::CondExpGt(R(0, 0), R(1, 1), R(0, 2) + R(2, 0), R(2, 1) + R(1, 2));\n  z2 = CppAD::CondExpLt(R(0, 0), -R(1, 1), t, R(1, 0) - R(0, 1));\n  z = CppAD::CondExpLt(R(2, 2), SCALAR_T(0.0), z1, z2);\n\n  w1 = CppAD::CondExpGt(R(0, 0), R(1, 1), R(2, 1) - R(1, 2), R(0, 2) - R(2, 0));\n  w2 = CppAD::CondExpLt(R(0, 0), -R(1, 1), R(1, 0) - R(0, 1), t);\n  w = CppAD::CondExpLt(R(2, 2), SCALAR_T(0.0), w1, w2);\n\n  Eigen::Matrix<SCALAR_T, 4, 1> q({x, y, z, w});\n  q *= 0.5 / sqrt(t);\n\n  Eigen::Quaternion<SCALAR_T> quaternion;\n  quaternion.x() = q(0);\n  quaternion.y() = q(1);\n  quaternion.z() = q(2);\n  quaternion.w() = q(3);\n\n  return quaternion;\n}\ntemplate <typename SCALAR_T>\nEigen::Matrix<SCALAR_T, 3, 1> KinematicsInterface<SCALAR_T>::getCOMBaseFrame(const Eigen::Matrix<SCALAR_T, -1, 1>& state) const {\n  const Eigen::Matrix<SCALAR_T, 6, 1>& armState = state.template tail<6>();\n  Eigen::Matrix<SCALAR_T, 4, 1> armCOM = Eigen::Matrix<SCALAR_T, 4, 1>::Ones();\n  armCOM.template head<3>() = getArmCOM(armState);\n  Eigen::Matrix<SCALAR_T, 3, 1> armCOMBaseFrame = (config_.transformBase_X_ArmMount.template cast<SCALAR_T>() * armCOM).template head<3>();\n  double armMass = getArmMass();\n  return ((SCALAR_T)armMass * armCOMBaseFrame + (config_.baseMass * config_.baseCOM).template cast<SCALAR_T>()) /\n         (SCALAR_T)(armMass + config_.baseMass);\n}\ntemplate <typename SCALAR_T>\nEigen::Matrix<SCALAR_T, 3, 1> KinematicsInterface<SCALAR_T>::getZMPBaseFrame(\n    const Eigen::Matrix<SCALAR_T, -1, 1>& state, const Eigen::Matrix<SCALAR_T, 7, 1>& eePoseReference,\n    const Eigen::Matrix<SCALAR_T, 6, 1>& wrenchReferenceEEFrame) const {\n  using vector3_t = Eigen::Matrix<SCALAR_T, 3, 1>;\n  using hom_transform_t = Eigen::Matrix<SCALAR_T, 4, 4>;\n  vector3_t rcog = getCOMBaseFrame(state);\n  double robotMass = config_.baseMass + getArmMass();\n\n  // convert reference force from fixed ee frame to base frame\n  hom_transform_t worldToEndeffectorReference = hom_transform_t::Zero();\n  worldToEndeffectorReference.template block<3, 3>(0, 0) =\n      Eigen::Quaternion<SCALAR_T>(eePoseReference.template head<4>()).toRotationMatrix();\n  worldToEndeffectorReference.template block<3, 1>(0, 3) = eePoseReference.template tail<3>();\n  worldToEndeffectorReference(3, 3) = 1;\n\n  hom_transform_t worldToBase = getWorldToBaseTransform(state);\n  hom_transform_t baseToWorld = worldToBase;\n  baseToWorld.template block<3, 3>(0, 0) = worldToBase.template block<3, 3>(0, 0).transpose();\n  baseToWorld.template block<3, 1>(0, 3) = -baseToWorld.template block<3, 3>(0, 0) * worldToBase.template block<3, 1>(0, 3);\n\n  hom_transform_t baseToEndeffectorReference = baseToWorld * worldToEndeffectorReference;\n  vector3_t forceBaseFrame = baseToEndeffectorReference.template block<3, 3>(0, 0) * wrenchReferenceEEFrame.template head<3>();\n  vector3_t torqueBaseFrame = baseToEndeffectorReference.template block<3, 3>(0, 0) * wrenchReferenceEEFrame.template tail<3>();\n\n  // compute a virtual mass for the acting end-effector force\n  const double g = 9.81;\n  vector3_t fg;\n  fg << (SCALAR_T)0, (SCALAR_T)0, (SCALAR_T)-robotMass * g;\n\n  // compute translation to the virtual mass in base frame\n  hom_transform_t base_X_Endeffector = computeBase2EndeffectorTransform(state.template tail<6>());\n  vector3_t ree = base_X_Endeffector.template block<3, 1>(0, 3);\n\n  vector3_t n;\n  n << (SCALAR_T)0, (SCALAR_T)0, (SCALAR_T)1;\n\n  return n.template cross(rcog.cross(fg) + ree.cross(forceBaseFrame) + torqueBaseFrame) / n.dot(fg + forceBaseFrame);\n}\n\ntemplate <typename SCALAR_T>\nEigen::Matrix<SCALAR_T, 4, 4> KinematicsInterface<SCALAR_T>::getWorldToBaseTransform(const Eigen::Matrix<SCALAR_T, -1, 1>& state) const {\n  Eigen::Quaternion<SCALAR_T> baseOrientation;\n  baseOrientation.coeffs() = state.template head<7>().template head<4>();\n  const Eigen::Matrix<SCALAR_T, 3, 1>& basePosition = state.template head<7>().template tail<3>();\n\n  // homogeneous transform world -> base\n  Eigen::Matrix<SCALAR_T, 4, 4> homWorld2Base = Eigen::Matrix<SCALAR_T, 4, 4>::Identity();\n  homWorld2Base.template topLeftCorner<3, 3>() = baseOrientation.toRotationMatrix();\n  homWorld2Base.template topRightCorner<3, 1>() = basePosition;\n  return homWorld2Base;\n}\n\ntemplate class perceptive_mpc::KinematicsInterface<double>;\ntemplate class perceptive_mpc::KinematicsInterface<CppAD::AD<CppAD::cg::CG<double>>>;", "meta": {"hexsha": "ebb148fd01fcb63aadfba9af0ac322cc5c7d58a5", "size": 10372, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/kinematics/KinematicsInterface.cpp", "max_stars_repo_name": "julius-forks/_fork-pmpc", "max_stars_repo_head_hexsha": "d18e81ea1bce5a45c0880ee9fed0f520da4029d1", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2020-07-21T10:57:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:08:01.000Z", "max_issues_repo_path": "src/kinematics/KinematicsInterface.cpp", "max_issues_repo_name": "julius-forks/_fork-pmpc", "max_issues_repo_head_hexsha": "d18e81ea1bce5a45c0880ee9fed0f520da4029d1", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2021-07-20T15:47:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-24T10:48:58.000Z", "max_forks_repo_path": "src/kinematics/KinematicsInterface.cpp", "max_forks_repo_name": "julius-forks/_fork-pmpc", "max_forks_repo_head_hexsha": "d18e81ea1bce5a45c0880ee9fed0f520da4029d1", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2020-07-25T13:55:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-27T08:58:21.000Z", "avg_line_length": 49.3904761905, "max_line_length": 140, "alphanum_fraction": 0.6930196683, "num_tokens": 3352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2693599324318154}}
{"text": "#include <vector>\n#include <iostream>\n#include <boost/python.hpp>\n#include \"util.hpp\"\n\nusing namespace std;\n\ndouble treegkr(Tree T, vector<double> creation, vector<double> destruction, vector<double> x, vector<double> y);\n\ndouble treegkr_python_wrapper(boost::python::list vs,\n                          boost::python::list us,\n                          boost::python::list cost,\n                          boost::python::list creation,\n                          boost::python::list destruction,\n                          boost::python::list x,\n                          boost::python::list y){\n  int n = boost::python::len(x);\n  assert(boost::python::len(vs) == n - 1);\n  assert(boost::python::len(us) == n - 1);\n  assert(boost::python::len(cost) == n - 1);\n  assert(boost::python::len(y) == n);\n  assert(boost::python::len(creation) == n);\n  assert(boost::python::len(destruction) == n);\n  Tree T(n);\n  Unionfind uf(n);\n  for(int i = 0; i < n - 1; i++){\n    int v = boost::python::extract<int>(vs[i]);\n    int u = boost::python::extract<int>(us[i]);\n    double c = boost::python::extract<double>(cost[i]);\n    T.add_edge(v, u, c);\n    if(uf.same(u, v)){\n      cerr << \"Input is not a tree\" << endl;\n      exit(1);\n    }\n    uf.unite(u, v);\n  }\n  if(uf.size[uf.find(0)] != n){\n    cerr << \"Input is not a tree\" << endl;\n    exit(1);\n  }\n  vector<double> xv(n), yv(n), creationv(n), destructionv(n);\n  for(int i = 0; i < n; i++){\n    xv[i] = boost::python::extract<double>(x[i]);\n    yv[i] = boost::python::extract<double>(y[i]);\n    creationv[i] = boost::python::extract<double>(creation[i]);\n    destructionv[i] = boost::python::extract<double>(destruction[i]);\n  }\n  return treegkr(T, creationv, destructionv, xv, yv);\n}\n\nBOOST_PYTHON_MODULE(treegkr){\n  boost::python::def(\"treegkr\",\n                     treegkr_python_wrapper,\n                     boost::python::args(\"vs\",\n                                         \"us\",\n                                         \"cost\",\n                                         \"creation\",\n                                         \"destruction\",\n                                         \"x\",\n                                         \"y\"),\n                     \"Fast computation of the generalized Kantorovich Rubinstein (GKR) distance on tree metrics\\n\"\n                     \"\\n\"\n                     \"Parameters\\n\"\n                     \"----------\\n\"\n                     \"vs : list of ints\\n\"\n                     \"    A list of endpoints of edges\\n\"\n                     \"    The node indices should start from zero\\n\"\n                     \"    The length of the list should be n-1\\n\"\n                     \"us : list of ints\\n\"\n                     \"    A list of endpoints of edges\\n\"\n                     \"    The node indices should start from zero\\n\"\n                     \"    The length of the list should be n-1\\n\"\n                     \"cost : list of floats\\n\"\n                     \"    A list of costs of edges\\n\"\n                     \"    The i-th edge connects node vs[i] and us[i] with cost[i].\\n\"\n                     \"    The length of the list should be n-1\\n\"\n                     \"creation : list of floats\\n\"\n                     \"    A list of creation costs\\n\"\n                     \"    A mass on node i can be created by cost creation[i].\\n\"\n                     \"    The length of the list should be n\\n\"\n                     \"destruction : list of floats\\n\"\n                     \"    A list of destruction costs\\n\"\n                     \"    A mass on node i can be destructed by cost destruction[i].\\n\"\n                     \"    The length of the list should be n\\n\"\n                     \"x : list of floats\\n\"\n                     \"    A list of source mass\\n\"\n                     \"    There exist x[i] target mass on node i.\\n\"\n                     \"    The length of the list should be n\\n\"\n                     \"y : list of floats\\n\"\n                     \"    A list of target mass\\n\"\n                     \"    There exist y[i] target mass on node i.\\n\"\n                     \"    The length of the list should be n\\n\"\n                     \"\\n\"\n                     \"Returns\\n\"\n                     \"-------\\n\"\n                     \"gkr: float\\n\"\n                     \"    The GKR distance\\n\");\n}\n\n", "meta": {"hexsha": "f3f40ee21741b4c6c38afcd9034a454fa193614c", "size": 4263, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "treegkr_python.cpp", "max_stars_repo_name": "joisino/treegkr", "max_stars_repo_head_hexsha": "373775f6f49b66bc61d640f7b10ce8a3bebd63ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-10-30T07:01:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T06:01:20.000Z", "max_issues_repo_path": "treegkr_python.cpp", "max_issues_repo_name": "joisino/treegkr", "max_issues_repo_head_hexsha": "373775f6f49b66bc61d640f7b10ce8a3bebd63ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "treegkr_python.cpp", "max_forks_repo_name": "joisino/treegkr", "max_forks_repo_head_hexsha": "373775f6f49b66bc61d640f7b10ce8a3bebd63ba", "max_forks_repo_licenses": ["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.63, "max_line_length": 114, "alphanum_fraction": 0.4520290875, "num_tokens": 958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2693256547202471}}
{"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_STRATEGIES_CARTESIAN_POINT_IN_POLY_CROSSINGS_MULTIPLY_HPP\n#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_POINT_IN_POLY_CROSSINGS_MULTIPLY_HPP\n\n\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace within\n{\n\n/*!\n\\brief Within detection using cross counting,\n\\ingroup strategies\n\\tparam Point \\tparam_point\n\\tparam PointOfSegment \\tparam_segment_point\n\\tparam CalculationType \\tparam_calculation\n\\see http://tog.acm.org/resources/GraphicsGems/gemsiv/ptpoly_haines/ptinpoly.c\n\\note Does NOT work correctly for point ON border\n\\qbk{\n[heading See also]\n[link geometry.reference.algorithms.within.within_3_with_strategy within (with strategy)]\n}\n */\n\ntemplate\n<\n    typename Point,\n    typename PointOfSegment = Point,\n    typename CalculationType = void\n>\nclass crossings_multiply\n{\n    typedef typename select_calculation_type\n        <\n            Point,\n            PointOfSegment,\n            CalculationType\n        >::type calculation_type;\n\n    class flags\n    {\n        bool inside_flag;\n        bool first;\n        bool yflag0;\n\n    public :\n\n        friend class crossings_multiply;\n\n        inline flags()\n            : inside_flag(false)\n            , first(true)\n            , yflag0(false)\n        {}\n    };\n\npublic :\n\n    typedef Point point_type;\n    typedef PointOfSegment segment_point_type;\n    typedef flags state_type;\n\n    static inline bool apply(Point const& point,\n            PointOfSegment const& seg1, PointOfSegment const& seg2,\n            flags& state)\n    {\n        calculation_type const tx = get<0>(point);\n        calculation_type const ty = get<1>(point);\n        calculation_type const x0 = get<0>(seg1);\n        calculation_type const y0 = get<1>(seg1);\n        calculation_type const x1 = get<0>(seg2);\n        calculation_type const y1 = get<1>(seg2);\n\n        if (state.first)\n        {\n            state.first = false;\n            state.yflag0 = y0 >= ty;\n        }\n\n\n        bool yflag1 = y1 >= ty;\n        if (state.yflag0 != yflag1)\n        {\n            if ( ((y1-ty) * (x0-x1) >= (x1-tx) * (y0-y1)) == yflag1 )\n            {\n                state.inside_flag = ! state.inside_flag;\n            }\n        }\n        state.yflag0 = yflag1;\n        return true;\n    }\n\n    static inline int result(flags const& state)\n    {\n        return state.inside_flag ? 1 : -1;\n    }\n};\n\n\n\n}} // namespace strategy::within\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_POINT_IN_POLY_CROSSINGS_MULTIPLY_HPP\n", "meta": {"hexsha": "a930daa9a82fae38c62bc4b168f8fec5a7bc7e99", "size": 3199, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/boost_1_47_0/boost/geometry/strategies/cartesian/point_in_poly_crossings_multiply.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/strategies/cartesian/point_in_poly_crossings_multiply.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/strategies/cartesian/point_in_poly_crossings_multiply.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": 25.592, "max_line_length": 89, "alphanum_fraction": 0.6648952798, "num_tokens": 781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2693256547202471}}
{"text": "/*******************************************************************************\n * Copyright (c) 2014, 2016  IBM Corporation and others\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *******************************************************************************/\n\n#ifndef GaussianProcessLight_hpp\n#define GaussianProcessLight_hpp\n\n#include <iostream>\n#include <limits>\n#include <Eigen/Dense>\n\n#include \"KernelFunction.hpp\"\n#include \"GaussianProcess.hpp\"\n#include \"SerializeUtils.hpp\"\n\nnamespace loc{\n    \n    class GaussianProcessLight : public GaussianProcess{\n        \n    private:\n        // variables to be serialized\n        std::vector<GaussianProcess> LGPs_;     //Local Gaussian Processes\n        std::vector<Eigen::VectorXd> centers_;  //center for each LGP\n        \n        double sigmaN_ = 1.0;\n        GaussianKernel gaussianKernel_;\n        \n    public:\n        static const int N_FEATURES = 4;\n        constexpr static const double MIN_DENOMINATOR = std::numeric_limits<double>::min() * 1e+16;\n\n        GaussianProcessLight() = default;\n        \n        enum ClusteringType{\n            GREEDY,\n            KMEANS\n        };\n        ClusteringType clType = KMEANS;\n        bool usesOverlap = true;\n        int mLocalsMixed_ = 3;\n        \n        // A function for serealization\n        template<class Archive>\n        void serialize(Archive& ar){\n            ar(CEREAL_NVP(LGPs_));\n            ar(CEREAL_NVP(centers_));\n            ar(CEREAL_NVP(sigmaN_));\n            ar(CEREAL_NVP(gaussianKernel_));\n            \n            std::vector<std::string> names;\n            try{\n                ar(CEREAL_NVP(mLocalsMixed_));\n            }catch(cereal::Exception& e){\n                names.push_back(\"mLocalsMixed_\");\n            }\n            \n            if(0<names.size()){\n                std::stringstream ss;\n                ss << \"[notice] parameters not found: \";\n                for(const auto& name: names){\n                    ss << name << \",\";\n                }\n                std::cerr << ss.str() << std::endl;\n            }\n        }\n        \n        GaussianProcessLight& sigmaN(double sigmaN){\n            sigmaN_ = sigmaN;\n            return *this;\n        }\n        \n        double sigmaN() const{\n            return sigmaN_;\n        }\n        \n        //Calculate maximum cluster size based on max complexity of the function predict()\n        static const size_t MAX_CLUSTER_SIZE(const size_t MAX_COMPLEXITY,\n                                             const size_t MAX_N_OVERLAP,\n                                             const size_t N_LOCALS_MIXED) {\n            const size_t k = MAX_N_OVERLAP;     //max # cluster overlaps for a sample\n            const size_t M = N_LOCALS_MIXED;    //# local models mixed in prediction\n            const size_t MAX_AMP = (std::min(k, M) + 1) * std::max(k, M);\n            const size_t MAX_CLUSTER_SIZE = MAX_COMPLEXITY / MAX_AMP;\n            \n            const size_t MIN_FEASIBLE_CLUSTER_SIZE = 50;\n            if (MAX_CLUSTER_SIZE < MIN_FEASIBLE_CLUSTER_SIZE) {\n                std::cout << \"WARNING: MAX_CLUSTER_SIZE=\" << MAX_CLUSTER_SIZE << \" is less than MIN_FEASIBLE_CLUSTER_SIZE=\" << MIN_FEASIBLE_CLUSTER_SIZE << std::endl;\n            }\n            return MAX_CLUSTER_SIZE;\n        }\n\n        GaussianProcessLight& fit(const Eigen::MatrixXd& X, const Eigen::MatrixXd& Y)\n        {\n            //Clustering samples\n            const size_t TARGET_N_CLUSTER = 1 + (X.rows() / MAX_CLUSTER_SIZE(800, 3, 3));\n            CentroidBasedClusteringResult cr;\n            if(clType==GREEDY){\n                cr = clusteringGreedyWithMagicThreshold(X, Y, 1e-8);\n            }else if(clType==KMEANS){\n                cr = kMeansClustering(X, Y, TARGET_N_CLUSTER);\n            }\n            \n            cr.printSummary();\n\n            if(usesOverlap){\n            //Improve the clusters\n            const double OVERLAP_SCALE = 0.001;\n            improveWithOverlap(cr, OVERLAP_SCALE, X, Y);\n            cr.printSummary();\n            }\n                \n            std::cout << \"clustered into \" << cr.nCluster() << \" local models\" << std::endl;\n            \n            centers_ = cr.centers;\n            \n            //Get local models by cluster\n            for (auto k=0; k < cr.nCluster(); k++) {\n                GaussianProcess gp;\n                gp.sigmaN(sigmaN_);\n                gp.gaussianKernel(gaussianKernel_);\n                \n                gp.fit(cr.XC[k], cr.YC[k]);\n                \n                LGPs_.push_back(gp);\n            }\n            \n            return *this;\n        }\n        \n        double predict(double x[], int index) const \n        {\n            std::vector<int> indices(1, index);\n            std::vector<double> ypreds = predict(x, indices);\n            return ypreds.at(0);\n        }\n        \n        //TODO change return type: Eigen::VectorXd would be better\n        std::vector<double> predict(double x[], const std::vector<int>& indices) const\n        {\n            const size_t M = mLocalsMixed_;\n            const size_t n = centers_.size();\n            \n            std::vector<double> weights(n);\n            for (size_t i=0; i < n; ++i) {\n                const double* c = centers_.at(i).data();\n                weights[i] = gaussianKernel_.computeKernel(x, c);\n            }\n            \n            //indices of k-nearest (=top-k weight) neigbors\n            std::vector<size_t> neighbors = top_k(weights, std::min(M, n));\n            \n            Eigen::VectorXd sum_wy = Eigen::VectorXd::Zero(indices.size());\n            double sum_w = 0.0;\n            for (auto m : neighbors) {\n                double w = weights.at(m);\n                std::vector<double> tmp = LGPs_.at(m).predict(x, indices);\n                Eigen::VectorXd y = Eigen::Map<Eigen::VectorXd>(tmp.data(), indices.size());\n                sum_wy += w * y;\n                sum_w  += w;\n            }\n            \n            Eigen::VectorXd y_hat = sum_wy;\n            if (sum_w > MIN_DENOMINATOR) {\n                y_hat /= sum_w;\n            } else {\n                std::vector<double> top1ypred = LGPs_.at(neighbors.at(0)).predict(x, indices);\n                y_hat = Eigen::Map<Eigen::VectorXd>(top1ypred.data(), indices.size());\n//                std::cout << \"WARN: sum_w~=0 in predict() with \" << n << \" LGPs\"\n//                          << \" >> predicted only with the nearest local model.\"<< std::endl;\n            }\n            std::vector<double> ypreds(y_hat.data(), y_hat.data() + indices.size());\n            return ypreds;\n        }\n\n        /**\n         * Estimate parameters as preparation\n         */\n        void fitCV(const Eigen::MatrixXd& X, const Eigen::MatrixXd& Y, const Eigen::MatrixXd& Actives)\n        {\n            GaussianProcess gp;\n            gp.sigmaN(sigmaN_);\n            gp.gaussianKernel(gaussianKernel_);\n            \n            // estimate parameters using GaussianProcess::fitCV\n            gp.fitCV(X, Y, Actives);\n            \n            // set estimated parameters to this\n            sigmaN_ = gp.sigmaN();\n            gaussianKernel_ = gp.gaussianKernel();\n        \n            this->fit(X, Y);\n        }\n        \n//        Eigen::VectorXd predictVarianceF(double x[]) const;\n//        Eigen::VectorXd predictVarianceF(const Eigen::VectorXd& kstar) const{;\n//        double computeLogLikelihood(double x[], const Eigen::VectorXd& y) const;\n\n    private:\n        class CentroidBasedClusteringResult{\n        public:\n            std::vector<Eigen::MatrixXd> XC;\n            std::vector<Eigen::MatrixXd> YC;\n            std::vector<Eigen::VectorXd> centers = {};\n            size_t nCluster() const { return centers.size(); }\n            void printSummary() const;\n            void printAll() const;\n        };\n        \n        /**\n         * k-means++ clustering\n         */\n        CentroidBasedClusteringResult kMeansClustering(const Eigen::MatrixXd& X,\n                                                       const Eigen::MatrixXd& Y,\n                                                       const size_t TARGET_N_CLUSTER) const;\n        \n        /**\n         * Greedy clustering \n         */\n        CentroidBasedClusteringResult clusteringGreedyWithMagicThreshold(const Eigen::MatrixXd& X,\n                                                                         const Eigen::MatrixXd& Y,\n                                                                         const double MAGIC_W_THRESHOLD) const;\n        \n        void improveWithOverlap(CentroidBasedClusteringResult& cr,\n                                const double OVERLAP_SCALE,\n                                const Eigen::MatrixXd& X,\n                                const Eigen::MatrixXd& Y) const;\n        \n    public:\n        // TODO move to an appropriate util class\n        static std::vector<size_t> top_k(const std::vector<double>& values, const size_t k)\n        {\n            assert(k <= values.size());\n            size_t n = values.size();\n            std::vector<size_t> labels(n);\n            for (auto i=0; i < n; ++i) { labels[i] = i; }\n            \n            auto comp = [&values](size_t i, size_t j) { return values[i] > values[j]; };\n            \n            if (n == k) {\n                std::sort(labels.begin(), labels.end(), comp);\n                return labels;\n            }\n            \n            assert(n > k);  //need +1 elements to make heap\n            auto first = labels.begin(), last = labels.begin() + k, end = labels.end();\n            std::make_heap(first, last + 1, comp);\n            std::pop_heap(first, last + 1, comp);\n            for (auto it = last + 1; it != end; it++) {\n                if (values[*it] <= values[*first]) {\n                    continue;\n                } else {\n                    *last = *it;\n                    std::pop_heap(first, last + 1, comp);\n                }\n            }\n            std::sort_heap(first, last, comp);\n            return std::vector<size_t>{first, last};\n        }\n        \n//    private:\n//        CentroidBasedClusteringResult aggregativeClustering(const Eigen::MatrixXd& X,\n//                                                            const Eigen::MatrixXd& Y,\n//                                                            const size_t TARGET_N_CLUSTER) const\n//        class CentroidBasedCluster{\n//        public:\n//            CentroidBasedCluster(size_t i, const Eigen::MatrixXd& X) {\n//                labels.push_back(i);\n//                center = X.row(i);\n//            };\n//            std::vector<size_t> labels;\n//            Eigen::VectorXd center;\n//            void merge(const CentroidBasedCluster& that) {\n//                std::copy(that.labels.begin(),that.labels.end(),std::back_inserter(this->labels));\n//                std::sort(this->labels.begin(), this->labels.end());\n//                double nis = this->labels.size();\n//                double nat = that.labels.size();\n//                this->center = (nis * this->center + nat * that.center) / (nis + nat);\n//            }\n//        };\n\n    };\n}\n\n#endif /* GaussianProcessLight_hpp */\n", "meta": {"hexsha": "ae064ae1bdbcf4358f86c4d3916e17ac8ab2af88", "size": 12101, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ble-cpp/src/model/GaussianProcessLight.hpp", "max_stars_repo_name": "harsh-agarwal/blelocpp", "max_stars_repo_head_hexsha": "eaba46c6239981c7b8e69bef2ab33bb08ecb15b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ble-cpp/src/model/GaussianProcessLight.hpp", "max_issues_repo_name": "harsh-agarwal/blelocpp", "max_issues_repo_head_hexsha": "eaba46c6239981c7b8e69bef2ab33bb08ecb15b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ble-cpp/src/model/GaussianProcessLight.hpp", "max_forks_repo_name": "harsh-agarwal/blelocpp", "max_forks_repo_head_hexsha": "eaba46c6239981c7b8e69bef2ab33bb08ecb15b4", "max_forks_repo_licenses": ["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.9372937294, "max_line_length": 166, "alphanum_fraction": 0.5126849021, "num_tokens": 2553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2693111250282043}}
{"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 <boost/bind.hpp>\n#include <boost/function.hpp>\n#include <ql/instruments/makecapfloor.hpp>\n#include <ql/pricingengines/capfloor/bacheliercapfloorengine.hpp>\n#include <ql/pricingengines/capfloor/blackcapfloorengine.hpp>\n#include <ql/quotes/derivedquote.hpp>\n#include <qle/termstructures/capfloorhelper.hpp>\n\nusing namespace QuantLib;\nusing std::ostream;\n\nnamespace {\nvoid no_deletion(OptionletVolatilityStructure*) {}\n} // namespace\n\nnamespace QuantExt {\n\n// The argument to RelativeDateBootstrapHelper below is not simply the `quote`. Instead we create a DerivedQuote that,\n// each time it is asked for its value, it returns a premium by calling CapFloorHelper::npv with the `quote` value. In\n// this way, the `BootstrapHelper<T>::quoteError()` is always based on the cap floor premium and we do not have imply\n// the volatility. This leads to all kinds of issues when deciding on max and min values in the iterative bootstrap\n// where the quote volatility type input is of one type and the optionlet structure that we are trying to build is of\n// another different type.\nCapFloorHelper::CapFloorHelper(Type type, const Period& tenor, Rate strike, const Handle<Quote>& quote,\n                               const boost::shared_ptr<IborIndex>& iborIndex,\n                               const Handle<YieldTermStructure>& discountingCurve, bool moving,\n                               const QuantLib::Date& effectiveDate, QuoteType quoteType,\n                               QuantLib::VolatilityType quoteVolatilityType, QuantLib::Real quoteDisplacement,\n                               bool endOfMonth, bool firstCapletExcluded)\n    : RelativeDateBootstrapHelper<OptionletVolatilityStructure>(\n          Handle<Quote>(boost::make_shared<DerivedQuote<boost::function<Real(Real)> > >(\n              quote, boost::bind(&CapFloorHelper::npv, this, _1)))),\n      type_(type), tenor_(tenor), strike_(strike), iborIndex_(iborIndex), discountHandle_(discountingCurve),\n      moving_(moving), effectiveDate_(effectiveDate), quoteType_(quoteType), quoteVolatilityType_(quoteVolatilityType),\n      quoteDisplacement_(quoteDisplacement), endOfMonth_(endOfMonth), firstCapletExcluded_(firstCapletExcluded),\n      rawQuote_(quote), initialised_(false) {\n\n    if (quoteType_ == Premium) {\n        QL_REQUIRE(type_ != Automatic, \"Cannot have CapFloorHelper type 'Automatic' with quote type of Premium\");\n    }\n\n    QL_REQUIRE(!(moving_ && effectiveDate_ != Date()),\n               \"A fixed effective date does not make sense for a moving helper\");\n\n    registerWith(iborIndex_);\n    registerWith(discountHandle_);\n\n    initializeDates();\n    initialised_ = true;\n}\n\nvoid CapFloorHelper::initializeDates() {\n\n    if (!initialised_ || moving_) {\n        CapFloor::Type capFloorType = CapFloor::Cap;\n        if (type_ == CapFloorHelper::Floor) {\n            capFloorType = CapFloor::Floor;\n        }\n\n        // Initialise the instrument and a copy\n        // The strike can be Null<Real>() to indicate an ATM cap floor helper\n        Rate dummyStrike = strike_ == Null<Real>() ? 0.01 : strike_;\n        capFloor_ = MakeCapFloor(capFloorType, tenor_, iborIndex_, dummyStrike, 0 * Days)\n                        .withEndOfMonth(endOfMonth_)\n                        .withEffectiveDate(effectiveDate_, firstCapletExcluded_);\n        capFloorCopy_ = MakeCapFloor(capFloorType, tenor_, iborIndex_, dummyStrike, 0 * Days)\n                            .withEndOfMonth(endOfMonth_)\n                            .withEffectiveDate(effectiveDate_, firstCapletExcluded_);\n\n        // Maturity date is just the maturity date of the cap floor\n        maturityDate_ = capFloor_->maturityDate();\n\n        // We need the leg underlying the cap floor to determine the remaining date members\n        const Leg& leg = capFloor_->floatingLeg();\n\n        // Earliest date is the first optionlet fixing date\n        boost::shared_ptr<CashFlow> cf = leg.front();\n        boost::shared_ptr<FloatingRateCoupon> frc = boost::dynamic_pointer_cast<FloatingRateCoupon>(cf);\n        QL_REQUIRE(frc, \"Expected the first cashflow on the cap floor instrument to be a FloatingRateCoupon\");\n        earliestDate_ = frc->fixingDate();\n\n        // Remaining dates are each equal to the fixing date on the final optionlet\n        cf = leg.back();\n        frc = boost::dynamic_pointer_cast<FloatingRateCoupon>(cf);\n        QL_REQUIRE(frc, \"Expected the final cashflow on the cap floor instrument to be a FloatingRateCoupon\");\n        pillarDate_ = latestDate_ = latestRelevantDate_ = frc->fixingDate();\n    }\n}\n\nvoid CapFloorHelper::setTermStructure(OptionletVolatilityStructure* ovts) {\n\n    if (strike_ == Null<Real>()) {\n        // If the strike is Null<Real>(), we want an ATM helper\n        Rate atm = capFloor_->atmRate(**discountHandle_);\n        capFloor_ = MakeCapFloor(capFloor_->type(), tenor_, iborIndex_, atm, 0 * Days)\n                        .withEndOfMonth(endOfMonth_)\n                        .withEffectiveDate(effectiveDate_, firstCapletExcluded_);\n        capFloorCopy_ = MakeCapFloor(capFloor_->type(), tenor_, iborIndex_, atm, 0 * Days)\n                            .withEndOfMonth(endOfMonth_)\n                            .withEffectiveDate(effectiveDate_, firstCapletExcluded_);\n\n    } else if (type_ == CapFloorHelper::Automatic && quoteType_ != Premium) {\n        // If the helper is set to automatically choose the underlying instrument type, do it now based on the ATM rate\n        Rate atm = capFloor_->atmRate(**discountHandle_);\n        CapFloor::Type capFloorType = atm > strike_ ? CapFloor::Floor : CapFloor::Cap;\n        if (capFloor_->type() != capFloorType) {\n            capFloor_ = MakeCapFloor(capFloorType, tenor_, iborIndex_, strike_, 0 * Days)\n                            .withEndOfMonth(endOfMonth_)\n                            .withEffectiveDate(effectiveDate_, firstCapletExcluded_);\n            capFloorCopy_ = MakeCapFloor(capFloorType, tenor_, iborIndex_, strike_, 0 * Days)\n                                .withEndOfMonth(endOfMonth_)\n                                .withEffectiveDate(effectiveDate_, firstCapletExcluded_);\n        }\n    }\n\n    // Set this helper's optionlet volatility structure\n    boost::shared_ptr<OptionletVolatilityStructure> temp(ovts, no_deletion);\n    ovtsHandle_.linkTo(temp, false);\n\n    // Set the term structure pointer member variable in the base class\n    RelativeDateBootstrapHelper<OptionletVolatilityStructure>::setTermStructure(ovts);\n\n    // Set this helper's pricing engine depending on the type of the optionlet volatilities\n    if (ovts->volatilityType() == ShiftedLognormal) {\n        capFloor_->setPricingEngine(boost::make_shared<BlackCapFloorEngine>(discountHandle_, ovtsHandle_));\n    } else {\n        capFloor_->setPricingEngine(boost::make_shared<BachelierCapFloorEngine>(discountHandle_, ovtsHandle_));\n    }\n\n    // If the quote type is not a premium, we will need to use capFloorCopy_ to return the premium from the volatility\n    // quote\n    if (quoteType_ != Premium) {\n        if (quoteVolatilityType_ == ShiftedLognormal) {\n            capFloorCopy_->setPricingEngine(boost::make_shared<BlackCapFloorEngine>(\n                discountHandle_, rawQuote_, ovtsHandle_->dayCounter(), quoteDisplacement_));\n        } else {\n            capFloorCopy_->setPricingEngine(\n                boost::make_shared<BachelierCapFloorEngine>(discountHandle_, rawQuote_, ovtsHandle_->dayCounter()));\n        }\n    }\n}\n\nReal CapFloorHelper::impliedQuote() const {\n    QL_REQUIRE(termStructure_ != 0, \"CapFloorHelper's optionlet volatility term structure has not been set\");\n    capFloor_->recalculate();\n    return capFloor_->NPV();\n}\n\nvoid CapFloorHelper::accept(AcyclicVisitor& v) {\n    if (Visitor<CapFloorHelper>* v1 = dynamic_cast<Visitor<CapFloorHelper>*>(&v))\n        v1->visit(*this);\n    else\n        RelativeDateBootstrapHelper<OptionletVolatilityStructure>::accept(v);\n}\n\nReal CapFloorHelper::npv(Real quoteValue) {\n    if (quoteType_ == Premium) {\n        return quoteValue;\n    } else {\n        // If the quote value is a volatility, return the premium\n        return capFloorCopy_->NPV();\n    }\n}\n\nostream& operator<<(ostream& out, CapFloorHelper::Type type) {\n    switch (type) {\n    case CapFloorHelper::Cap:\n        return out << \"Cap\";\n    case CapFloorHelper::Floor:\n        return out << \"Floor\";\n    case CapFloorHelper::Automatic:\n        return out << \"Automatic\";\n    default:\n        QL_FAIL(\"Unknown CapFloorHelper::Type (\" << Integer(type) << \")\");\n    }\n}\n\nostream& operator<<(ostream& out, CapFloorHelper::QuoteType type) {\n    switch (type) {\n    case CapFloorHelper::Volatility:\n        return out << \"Volatility\";\n    case CapFloorHelper::Premium:\n        return out << \"Premium\";\n    default:\n        QL_FAIL(\"Unknown CapFloorHelper::QuoteType (\" << Integer(type) << \")\");\n    }\n}\n\n} // namespace QuantExt\n", "meta": {"hexsha": "aea2ce60b9222ec1d4a72794b2bfc186978dcf94", "size": 9615, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/termstructures/capfloorhelper.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/capfloorhelper.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/capfloorhelper.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.2259615385, "max_line_length": 119, "alphanum_fraction": 0.6838273531, "num_tokens": 2204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2693111250282043}}
{"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#ifndef LIMBO_OPT_RPROP_HPP\n#define LIMBO_OPT_RPROP_HPP\n\n#include <algorithm>\n\n#include <Eigen/Core>\n\n#include <limbo/opt/optimizer.hpp>\n#include <limbo/tools/macros.hpp>\n#include <limbo/tools/math.hpp>\n\nnamespace limbo {\n    namespace defaults {\n        struct opt_rprop {\n            /// @ingroup opt_defaults\n            /// number of max iterations\n            BO_PARAM(int, iterations, 300);\n\n            /// gradient norm epsilon for stopping\n            BO_PARAM(double, eps_stop, 0.0);\n        };\n    }\n    namespace opt {\n        /// @ingroup opt\n        /// Gradient-based optimization (rprop)\n        /// - partly inspired by libgp: https://github.com/mblum/libgp\n        /// - reference :\n        /// Blum, M., & Riedmiller, M. (2013). Optimization of Gaussian\n        /// Process Hyperparameters using Rprop. In European Symposium\n        /// on Artificial Neural Networks, Computational Intelligence\n        /// and Machine Learning.\n        ///\n        /// Parameters:\n        /// - int iterations\n        /// - double eps_stop\n        template <typename Params>\n        struct Rprop {\n            template <typename F>\n            Eigen::VectorXd operator()(const F& f, const Eigen::VectorXd& init, bool bounded) const\n            {\n                assert(Params::opt_rprop::eps_stop() >= 0.);\n\n                size_t param_dim = init.size();\n                double delta0 = 0.1;\n                double deltamin = 1e-6;\n                double deltamax = 50;\n                double etaminus = 0.5;\n                double etaplus = 1.2;\n                double eps_stop = Params::opt_rprop::eps_stop();\n\n                Eigen::VectorXd delta = Eigen::VectorXd::Ones(param_dim) * delta0;\n                Eigen::VectorXd grad_old = Eigen::VectorXd::Zero(param_dim);\n                Eigen::VectorXd params = init;\n\n                if (bounded) {\n                    for (int j = 0; j < params.size(); j++) {\n                        if (params(j) < 0)\n                            params(j) = 0;\n                        if (params(j) > 1)\n                            params(j) = 1;\n                    }\n                }\n\n                Eigen::VectorXd best_params = params;\n                double best = log(0);\n\n                for (int i = 0; i < Params::opt_rprop::iterations(); ++i) {\n                    auto perf = opt::eval_grad(f, params);\n                    double lik = opt::fun(perf);\n                    if (lik > best) {\n                        best = lik;\n                        best_params = params;\n                    }\n                    Eigen::VectorXd grad = -opt::grad(perf);\n                    grad_old = grad_old.cwiseProduct(grad);\n\n                    for (int j = 0; j < grad_old.size(); ++j) {\n                        if (grad_old(j) > 0) {\n                            delta(j) = std::min(delta(j) * etaplus, deltamax);\n                        }\n                        else if (grad_old(j) < 0) {\n                            delta(j) = std::max(delta(j) * etaminus, deltamin);\n                            grad(j) = 0;\n                        }\n                        params(j) += -tools::signum(grad(j)) * delta(j);\n\n                        if (bounded && params(j) < 0)\n                            params(j) = 0;\n                        if (bounded && params(j) > 1)\n                            params(j) = 1;\n                    }\n\n                    grad_old = grad;\n                    if (grad_old.norm() < eps_stop)\n                        break;\n                }\n\n                return best_params;\n            }\n        };\n    }\n}\n\n#endif\n", "meta": {"hexsha": "cb67730e2bc1ae8970e527b94356d82c42a1a0bf", "size": 5993, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "limbo/src/limbo/opt/rprop.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/opt/rprop.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/opt/rprop.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": 39.9533333333, "max_line_length": 99, "alphanum_fraction": 0.5598197898, "num_tokens": 1376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2693111250282043}}
{"text": "//\n//  MosekProgram.cpp\n//  Gravity\n//\n//  Created by Guanglei Wang on 14/7/17.\n//\n//\n#include <Eigen/Dense>\n#include \"MosekProgram.h\"\nusing namespace mosek;\nusing namespace monty;\n\nMosekProgram::MosekProgram() {    \n    _mosek_model = new fusion::Model(\"noname\");\n    _mosek_model->setLogHandler([=](const std::string & msg){std::cout << msg << std::flush;});\n\n}\n\nMosekProgram::MosekProgram(Model* m) {    \n    _mosek_model = new fusion::Model(\"noname\");\n    _mosek_model->setLogHandler([=](const std::string & msg){std::cout << msg << std::flush;});\n    _model = m;\n}\n\nMosekProgram::~MosekProgram() {\n    _mosek_model->dispose();\n}\n\nvoid MosekProgram::update_model() {};\n    \n\n// remain to do\nbool MosekProgram::solve(bool relax) {\n//    _mosek_model->setSolverParam(\"log\", 10);\n    // Set max solution time\n//    _mosek_model->setSolverParam(\"mioMaxTime\", 360.0);\n    // Set max relative gap (to its default value)\n    _mosek_model->setSolverParam(\"intpntCoTolRelGap\", 1e-6);\n//    _mosek_model->setSolverParam(\"presolveUse\", \"on\");\n//    _mosek_model->setSolverParam(\"intpntCoTolPfeas\", 1);\n//    _mosek_model->setSolverParam(\"intpntQoTolPfeas\", 1);\n//    _mosek_model->setSolverParam(\"intpntCoTolMuRed\", 1);\n    // Set max absolute gap (to its default value)\n//    _mosek_model->setSolverParam(\"mioTolRelGap\", 1e-4);\n//    _mosek_model->setSolverParam(\"mioTolAbsGap\", 0.0);\n//    _mosek_model->setSolverParam(\"numThreads\",1);\n    //if(!_output) _mosek_model->setSolverParam(\"log\", 0);\n    if(relax) {\n        for (auto &vv: _mosek_vars)\n            vv->makeContinuous();\n    }\n    _mosek_model->solve();\n\n    if (!relax) {\n        cout <<_mosek_model->getProblemStatus(fusion::SolutionType::Integer) << endl;\n        cout << _mosek_model->getPrimalSolutionStatus() << endl;\n    }\n    else {\n        cout <<_mosek_model->getProblemStatus(fusion::SolutionType::Interior) << endl;\n        cout << _mosek_model->getPrimalSolutionStatus() << endl;\n    }\n\n\n    switch (_mosek_model->getPrimalSolutionStatus()) {\n        case mosek::fusion::SolutionStatus::Undefined:\n            _status = \"Undefined\";\n            break;\n        case mosek::fusion::SolutionStatus::Unknown:\n            _status = \"Unknown\";\n            break;\n        case mosek::fusion::SolutionStatus::Optimal:\n            _status = \"Optimal\";\n            break;\n        case mosek::fusion::SolutionStatus::NearOptimal:\n            _status = \"NearOptimal\";\n            break;\n        case mosek::fusion::SolutionStatus::Feasible:\n            _status = \"Feasible\";\n            break;\n        case mosek::fusion::SolutionStatus::NearFeasible:\n            _status = \"NearFeasible\";\n            break;\n        case mosek::fusion::SolutionStatus::Certificate:\n            _status = \"Certificate\";\n            break;\n        case mosek::fusion::SolutionStatus::NearCertificate:\n            _status = \"NearCertificate\";\n            break;\n        case mosek::fusion::SolutionStatus::IllposedCert:\n            _status = \"IllposedCert\";\n            break;\n        default:\n            break;\n    }\n    DebugOn(\"Cost = \" << _mosek_model->primalObjValue() << std::endl);\n    \n    // set the optimal value.\n    \n    _mosek_model->acceptedSolutionStatus(mosek::fusion::AccSolutionStatus::Feasible);\n    _model->_obj_val = _mosek_model->primalObjValue();\n\n\n    // Note that there is only one way to retrieve solutions, i.e.,\n    // variable.level(). It only returns double. Thus, we need to cast the\n    // solution to required types.\n    //std::cout << \"Solution = \" << std::endl;\n    // cout << \"dim: \" << _mosek_vars.size() << endl;\n    //auto sol = _mosek_vars[0]->level();\n    //mosek::fusion::Variable::t s= _mosek_vars[0];\n    //cout << \"size of s: \" << s->size() << endl;\n\n    for (auto i = 0; i < _mosek_vars.size(); i++) {\n        auto sol = _mosek_vars[i]->level();\n        if(i >= _model->_vars.size()) continue;\n        if (_model->_vars[i]->get_intype()== binary_ ||_model->_vars[i]->get_intype()== integer_) {\n            for (auto j = 0; j < _model->_vars[i]->get_nb_instances(); j++) {\n                auto val = (*sol)[j];\n                val = round(val);\n                poly_set_val(j, val , _model->_vars[i]);\n            }\n        }\n        else if(!_model->_vars[i]->_is_matrix){\n            for (auto j = 0; j < _model->_vars[i]->get_nb_instances(); j++) {\n                poly_set_val(j, (*sol)[j], _model->_vars[i]);\n            }\n        }\n        else {\n            int n = _model->_vars[i]->_dim[0];\n            for(auto j1 = 0; j1 < n; j1++) {\n                for(auto j2 = j1; j2 < n; j2++) {\n                    string key = to_string(j1)+\",\"+to_string(j2);\n                    ((param<double>*)_model->_vars[i])->set_val(key, (*sol)[j1*n+j2]);\n                }\n            }\n\n\n        }\n    }\n    return 0;\n}\n\nvoid MosekProgram::fill_in_mosek_vars() {\n    param_* v;\n    for(auto& v_p: _model->_vars)\n    {\n        v = v_p.second;\n        if(v->get_id()==-1) {\n            throw invalid_argument(\"Variable needs to be added to model first: use add_var(v) function:\" + v->get_name());\n        }\n        switch (v->get_intype()) {\n        case float_: {\n            if (v->get_type() == var_c) {\n                auto real_var = (var<float>*)v;\n                //for (int i = 0; i < real_var->get_nb_instances(); i++) {\n                //    _mosek_vars.push_back(_mosek_model->variable(real_var->get_name()+\"_\"+to_string(i),fusion::Domain::inRange(real_var->get_lb(i), real_var->get_ub(i))));\n                //}\n                auto lb  = new_array_ptr<double,1>(real_var->get_nb_instances());\n                auto ub  = new_array_ptr<double,1>(real_var->get_nb_instances());\n                for (int i = 0; i < real_var->get_nb_instances(); i++) {\n                    (*lb)[i] = real_var->get_lb(i);\n                    (*ub)[i] = real_var->get_ub(i);\n                }\n                if(!real_var->_in_q_cone && !real_var->_psd) _mosek_vars.push_back(_mosek_model->variable(real_var->get_name(), real_var->get_nb_instances(), fusion::Domain::inRange(lb,ub)));\n                else if(real_var->_in_q_cone) _mosek_vars.push_back(_mosek_model->variable(real_var->get_name(), fusion::Domain::inQCone(real_var->get_nb_instances())));\n                else {\n//                    _mosek_vars.push_back(_mosek_model->variable(real_var->get_name(), fusion::Domain::inPSDCone((1 + sqrt(1+8*real_var->get_nb_instances()))/2)));\n                    _mosek_vars.push_back(_mosek_model->variable(real_var->get_name(), fusion::Domain::inPSDCone(real_var->_dim[0])));\n                }\n            }\n            else {\n                auto sdp_var = (sdpvar<float>*)v;\n                _mosek_vars.push_back(_mosek_model->variable(sdp_var->get_name(), fusion::Domain::inPSDCone(sdp_var->_symdim)));\n            }\n            break;\n        }\n        case long_: {\n            if (v->get_type() == var_c) {\n                auto real_var = (var<long double>*)v;\n                //for (int i = 0; i < real_var->get_nb_instances(); i++) {\n                //    _mosek_vars.push_back(_mosek_model->variable(real_var->get_name()+\"_\"+to_string(i),fusion::Domain::inRange(real_var->get_lb(i), real_var->get_ub(i))));\n                //}\n                auto lb  = new_array_ptr<double,1>(real_var->get_nb_instances());\n                auto ub  = new_array_ptr<double,1>(real_var->get_nb_instances());\n                for (int i = 0; i < real_var->get_nb_instances(); i++) {\n                    (*lb)[i] = real_var->get_lb(i);\n                    (*ub)[i] = real_var->get_ub(i);\n                }\n                if(!real_var->_in_q_cone)_mosek_vars.push_back(_mosek_model->variable(real_var->get_name(), real_var->get_nb_instances(), fusion::Domain::inRange(lb,ub)));\n                else _mosek_vars.push_back(_mosek_model->variable(real_var->get_name(), fusion::Domain::inQCone(real_var->get_nb_instances())));\n            }\n            else {\n                auto sdp_var = (sdpvar<long double>*)v;\n                _mosek_vars.push_back(_mosek_model->variable(sdp_var->get_name(), fusion::Domain::inPSDCone(sdp_var->get_nb_instances())));\n            }\n            break;\n        }\n        case double_: {\n            if (v->get_type() == var_c) {\n                auto real_var = (var<double>*)v;\n                //for (int i = 0; i < real_var->get_nb_instances(); i++) {\n                //    _mosek_vars.push_back(_mosek_model->variable(real_var->get_name()+\"_\"+to_string(i),fusion::Domain::inRange(real_var->get_lb(i), real_var->get_ub(i))));\n                //}\n                auto lb  = new_array_ptr<double,1>(real_var->get_nb_instances());\n                auto ub  = new_array_ptr<double,1>(real_var->get_nb_instances());\n                for (int i = 0; i < real_var->get_nb_instances(); i++) {\n                    (*lb)[i] = real_var->get_lb(i);\n                    (*ub)[i] = real_var->get_ub(i);\n                }\n                if(!real_var->_in_q_cone && !real_var->_psd) _mosek_vars.push_back(_mosek_model->variable(real_var->get_name(), real_var->get_nb_instances(), fusion::Domain::inRange(lb,ub)));\n                else if(real_var->_in_q_cone) _mosek_vars.push_back(_mosek_model->variable(real_var->get_name(), fusion::Domain::inQCone(real_var->get_nb_instances())));\n                else {\n//                    _mosek_vars.push_back(_mosek_model->variable(real_var->get_name(), fusion::Domain::inPSDCone((1 + sqrt(1+8*real_var->get_nb_instances()))/2.)));\n                    _mosek_vars.push_back(_mosek_model->variable(real_var->get_name(), fusion::Domain::inPSDCone(real_var->_dim[0])));\n                }\n            }\n            else {\n                auto sdp_var = (sdpvar<double>*)v;\n                size_t num = sdp_var->_symdim;\n                auto c  = _mosek_model->variable(sdp_var->get_name(), fusion::Domain::inPSDCone(num));\n                _mosek_vars.push_back(c);\n                std::cout << c->toString() << endl;\n\n            }\n            break;\n        }\n        case integer_: {\n            if (v->get_type() == var_c) {\n                auto real_var = (var<int>*)v;\n                auto lb  = new_array_ptr<double,1>(real_var->get_nb_instances());\n                auto ub  = new_array_ptr<double,1>(real_var->get_nb_instances());\n                for (int i = 0; i < real_var->get_nb_instances(); i++) {\n                    (*lb)[i] = real_var->get_lb(i);\n                    (*ub)[i] = real_var->get_ub(i);\n                }\n                _mosek_vars.push_back(_mosek_model->variable(real_var->get_name(), real_var->get_nb_instances(), fusion::Domain::integral(fusion::Domain::inRange(lb,ub))));\n            }\n            else {\n                auto sdp_var = (sdpvar<int>*)v;\n                _mosek_vars.push_back(_mosek_model->variable(sdp_var->get_name(), fusion::Domain::inPSDCone(sdp_var->get_nb_instances())));\n            }\n            break;\n        }\n        case short_: {\n            if (v->get_type() == var_c) {\n                auto real_var = (var<short>*)v;\n                auto lb  = new_array_ptr<double,1>(real_var->get_nb_instances());\n                auto ub  = new_array_ptr<double,1>(real_var->get_nb_instances());\n                for (int i = 0; i < real_var->get_nb_instances(); i++) {\n                    (*lb)[i] = real_var->get_lb(i);\n                    (*ub)[i] = real_var->get_ub(i);\n                }\n                _mosek_vars.push_back(_mosek_model->variable(real_var->get_name(), real_var->get_nb_instances(), fusion::Domain::integral(fusion::Domain::inRange(lb,ub))));\n            }\n            else {\n                auto sdp_var = (sdpvar<short>*)v;\n                _mosek_vars.push_back(_mosek_model->variable(sdp_var->get_name(), fusion::Domain::inPSDCone(sdp_var->get_nb_instances())));\n            }\n            break;\n        }\n        case binary_: {\n            if (v->get_type() == var_c) {\n                auto real_var = (var<bool>*)v;\n                //for (unsigned int i = 0; i < real_var->get_nb_instances(); i++) {\n                //    _mosek_vars.push_back(_mosek_model->variable(real_var->get_name()+\"_\"+to_string(i),fusion::Domain::binary()));\n                //}\n                _mosek_vars.push_back(_mosek_model->variable(real_var->get_name(), real_var->get_nb_instances(), fusion::Domain::binary()));\n            }\n            else {\n                auto sdp_var = (sdpvar<bool>*)v;\n                _mosek_vars.push_back(_mosek_model->variable(sdp_var->get_name(), fusion::Domain::inPSDCone(sdp_var->get_nb_instances())));\n            }\n            break;\n        }\n        default:\n            break;\n        }\n    }\n}\n\n/*void MosekProgram::create_mosek_constraints() {\n    //size_t idx = 0;\n    //size_t nb_inst = 0;\n    size_t idx = 0, idx_inst = 0,idx1 = 0, idx2 = 0, idx_inst1 = 0, idx_inst2 = 0, nb_inst = 0, inst = 0;\n    size_t c_idx_inst = 0;\n    shared_ptr<Constraint> c;\n    for(auto& p: _model->_cons) {\n        c = p.second;\n//        c->print();\n        if (c->is_nonlinear()) {\n            cout <<  \"We haven't implemented quadratic expressions interface for mosek\" << endl;\n            throw invalid_argument(\"Mosek cannot handle nonlinear constraints that are not convex quadratic.\\n\");\n        }\n        nb_inst = c->get_nb_instances();\n        auto fusion_sums = new ndarray<fusion::Expression::t,1>(shape(nb_inst));\n        for (int i = 0; i< nb_inst; i++) {\n            // get constant part first.\n            monty::rc_ptr<mosek::fusion::Expression > expr= fusion::Expr::constTerm(poly_eval(c->get_cst())); // expr is a pointer to the Expression.\n            for (auto& it1: c->get_lterms()) {\n                //idx = it1.second._p->get_id();\n                idx = it1.second._p->get_vec_id();\n                //cout << \"get_id: \" << it1.second._p->get_id() << endl;\n                //cout << \"get_vec_id: \" << it1.second._p->get_vec_id() << endl;\n\n                CType vartype = it1.second._p->get_type();\n                if (vartype == var_c) {\n                    if(!it1.second._p->_is_matrix) {\n\n                        if (it1.second._coef->_is_transposed) {\n                            auto coefs = new_array_ptr<double, 1>(it1.second._p->get_nb_instances());\n                            for (int j = 0; j < it1.second._p->get_nb_instances(); j++) {\n                                (*coefs)(j) = poly_eval(it1.second._coef, j);\n                            }\n                            expr = fusion::Expr::add(expr, fusion::Expr::dot(coefs, _mosek_vars[idx]));\n                            //    cout << \"expr\" << expr->toString() << endl;\n                        } else {\n                            if (is_indexed(it1.second._p)) {\n                                idx_inst = it1.second._p->get_id_inst(i);\n                            } else {\n                                idx_inst = inst;\n                            }\n                            if (is_indexed(it1.second._coef)) {\n                                c_idx_inst = get_poly_id_inst(it1.second._coef);\n                            } else {\n                                c_idx_inst = inst;\n                            }\n                            auto lterm = fusion::Expr::mul(poly_eval(it1.second._coef, c_idx_inst),\n                                                           _mosek_vars[idx]->index(idx_inst));\n\n                            if (!it1.second._sign) {\n                                lterm = fusion::Expr::mul(-1, lterm);\n                            }\n                            expr = fusion::Expr::add(expr, lterm);\n                        }\n                    }else{\n                        if (it1.second._coef->_is_transposed) {\n                            auto coefs = new_array_ptr<double, 1>(it1.second._p->get_nb_instances());\n                            for (int j = 0; j < it1.second._p->get_nb_instances(); j++) {\n                                (*coefs)(j) = poly_eval(it1.second._coef, j);\n                            }\n                            expr = fusion::Expr::add(expr, fusion::Expr::dot(coefs, _mosek_vars[idx]));\n                            //    cout << \"expr\" << expr->toString() << endl;\n                        } else {\n                            pair<size_t, size_t>  pair;\n                            if (is_indexed(it1.second._p)) {\n//                                idx_inst = it1.second._p->get_id_inst(i);\n                                pair = it1.second._p->get_sdp_inst(i);\n                            } else {\n                                idx_inst = inst;\n                            }\n                            if (is_indexed(it1.second._coef)) {\n                                c_idx_inst = get_poly_id_inst(it1.second._coef);\n                            } else {\n                                c_idx_inst = inst;\n                            }\n                            DebugOff(\"\\nindex: \" << pair.first << \", \" << pair.second);\n                            auto lterm = fusion::Expr::mul(poly_eval(it1.second._coef, c_idx_inst),\n                                                           _mosek_vars[idx]->index(pair.first,pair.second));\n\n                            if (!it1.second._sign) {\n                                lterm = fusion::Expr::mul(-1, lterm);\n                            }\n                            expr = fusion::Expr::add(expr, lterm);\n                        }\n                    }\n\n\n                }\n                else if(vartype == sdpvar_c) {\n                    if (it1.second._coef->_is_transposed) {\n                        auto coefs = new_array_ptr<double,1>(it1.second._p->get_nb_instances());\n                        for (int j = 0; j<it1.second._p->get_nb_instances(); j++) {\n                            (*coefs)(j) = poly_eval(it1.second._coef,j);\n                        }\n                        expr = fusion::Expr::add(expr,fusion::Expr::dot(coefs,_mosek_vars[idx]));\n                    }\n                    else {\n                        pair<size_t, size_t>  pair = make_pair(0, 0);\n\n                        if (is_indexed(it1.second._p)) {\n                            pair = it1.second._p->get_sdpid();\n                        }\n\n                        if (is_indexed(it1.second._coef)) {\n                            c_idx_inst = get_poly_id_inst(it1.second._coef);\n                        }\n                        else {\n                            c_idx_inst = inst;\n                        }\n                        auto lterm = fusion::Expr::mul(poly_eval(it1.second._coef, c_idx_inst), _mosek_vars[idx]->index(pair.first, pair.second));\n                        if (!it1.second._sign) {\n                            lterm = fusion::Expr::mul(-1, lterm);\n                        }\n                        expr = fusion::Expr::add(expr,lterm);\n                    }\n\n                }else{ //param\n                    if (it1.second._coef->_is_transposed) {\n                        auto coefs = new_array_ptr<double,1>(it1.second._p->get_nb_instances());\n                        for (int j = 0; j<it1.second._p->get_nb_instances(); j++) {\n                            (*coefs)(j) = poly_eval(it1.second._coef,j);\n                        }\n                        expr = fusion::Expr::add(expr,fusion::Expr::dot(coefs,_mosek_vars[idx]));\n                        //    cout << \"expr\" << expr->toString() << endl;\n                    }\n                    else { //this results in always taking the first instance? it doesn't use i at all?\n                        if (is_indexed(it1.second._p)) {\n                            idx_inst = it1.second._p->get_id_inst(i); //fixed here, look for similar errors\n                        }\n                        else {\n                            idx_inst = inst;\n                        }\n                        if (is_indexed(it1.second._coef)) {\n                            c_idx_inst = get_poly_id_inst(it1.second._coef);\n                        }\n                        else {\n                            c_idx_inst = inst;\n                        }\n                        auto lterm = fusion::Expr::constTerm(poly_eval(it1.second._coef, c_idx_inst) * poly_eval(it1.second._p, i)); // was idx_inst\n                        if (!it1.second._sign) {\n                            lterm = fusion::Expr::mul(-1, lterm);\n                        }\n                        expr = fusion::Expr::add(expr,lterm);\n                    }\n                }\n            }\n\n            DebugOff(\"\\nconstr in Mosek: \" << expr->toString());\n            if(c->get_type()==geq) {\n                DebugOff(\"\\n >= \" << c->get_rhs());\n                _mosek_model->constraint(c->get_name()+to_string(i), expr, fusion::Domain::greaterThan(c->get_rhs()));\n            }\n            else if(c->get_type()==leq) {\n                DebugOff(\"\\n <= \" << c->get_rhs());\n                _mosek_model->constraint(c->get_name()+to_string(i), expr, fusion::Domain::lessThan(c->get_rhs()));\n            }\n            else if(c->get_type()==eq) {\n                DebugOff(\"\\n\" << expr->toString());\n                DebugOff(\" = \" << c->get_rhs());\n                _mosek_model->constraint(c->get_name()+to_string(i), expr, fusion::Domain::equalsTo(c->get_rhs()));\n            }\n            inst++;\n        }\n    }\n}*/\n\nsize_t get_num_qterms(map<string, qterm>& qterms) {\n    size_t qn = 0;\n    for (auto& it1: qterms) {\n        if ((it1.second._coef->_is_transposed || it1.second._coef->_is_matrix) && !it1.second._p->first->_is_matrix) {\n            size_t dim = it1.second._p->first->get_nb_instances();\n            qn += dim;\n        }\n        else if(it1.second._p->first->_is_transposed){\n            size_t dim = it1.second._p->first->get_nb_instances();\n            qn += dim;\n        }\n        else qn++;\n    }\n    return qn;\n}\n\nfusion::Expression::t MosekProgram::create_lin_expr(map<string, lterm>& lt, constant_* cst, size_t inst){\n    size_t idx = 0, idx_inst = 0, c_idx_inst = 0;\n    auto fusion_lterms = new_array_ptr<fusion::Expression::t,1>(lt.size()+1);\n    (*fusion_lterms)[0] = fusion::Expr::constTerm(poly_eval(cst,inst));\n    int lterm_idx = 1;\n\n    for (auto& it1: lt) {\n        idx = it1.second._p->get_vec_id();\n\n        CType vartype = it1.second._p->get_type();\n        if (vartype == var_c) {\n//                    cout << \"\\nvar = \" << it1.second._p->get_name();\n//                    cout << \"\\nfull Mosek var: \" << _mosek_vars[idx]->toString();\n            if(!it1.second._p->_is_matrix) {\n                if (it1.second._coef->_is_transposed) {\n                    auto coefs = new_array_ptr<double, 1>(it1.second._p->get_nb_instances(inst));\n                    auto vars = new_array_ptr<fusion::Variable::t,1>(it1.second._p->get_nb_instances(inst));\n                    for (int j = 0; j < it1.second._p->get_nb_instances(inst); j++) {\n                        (*coefs)(j) = poly_eval(it1.second._coef,inst,j);\n                        idx_inst = it1.second._p->get_id_inst(inst,j);\n//                                if(idx_inst >= _mosek_vars[idx]->size()){\n//                                    cout << \"\\nidx_inst >= var size: idx_inst = \" << idx_inst << \", var size = \" << _mosek_vars[idx]->size();\n//                                }\n                        (*vars)(j) = _mosek_vars[idx]->index(idx_inst);\n//                                cout << \"\\nj, idx, idx_inst = \" << j << \", \" << idx << \", \" << idx_inst << \", var = \" <<  _mosek_vars[idx]->index(idx_inst)->toString();\n                    }\n                    rc_ptr<fusion::Variable> P;\n                    if(it1.second._p->get_nb_instances(inst)!=1) P = fusion::Var::vstack(vars);\n                    else P = _mosek_vars[idx]->index(idx_inst);\n//                            cout << \"\\nCoef = \";\n//                            for(auto& coef: *coefs)\n//                                cout << coef << \"; \";\n//                            cout << \"\\nP = \" << P->toString();\n                    auto lterm = fusion::Expr::dot(coefs, P);\n                    if (!it1.second._sign) lterm = fusion::Expr::mul(-1, lterm);\n                    (*fusion_lterms)[lterm_idx] = lterm;\n                    //expr = fusion::Expr::add(expr, fusion::Expr::dot(coefs, _mosek_vars[idx]));\n                } else {\n                    if (is_indexed(it1.second._p)) idx_inst = it1.second._p->get_id_inst(inst);\n                    else idx_inst = inst;\n\n                    if (is_indexed(it1.second._coef)) c_idx_inst = get_poly_id_inst(it1.second._coef);\n                    else c_idx_inst = inst;\n\n                    auto lterm = fusion::Expr::mul(poly_eval(it1.second._coef, inst), //was c_idx_inst instead of i\n                                                   _mosek_vars[idx]->index(idx_inst));\n\n                    if (!it1.second._sign) lterm = fusion::Expr::mul(-1, lterm);\n                    (*fusion_lterms)[lterm_idx] = lterm;\n                    //expr = fusion::Expr::add(expr, lterm);\n                }\n            }else{\n                if (it1.second._coef->_is_transposed) {\n                    auto coefs = new_array_ptr<double, 1>(it1.second._p->get_nb_instances());\n                    for (int j = 0; j < it1.second._p->get_nb_instances(); j++) {\n                        (*coefs)(j) = poly_eval(it1.second._coef, j);\n                    }\n                    (*fusion_lterms)[lterm_idx] = fusion::Expr::dot(coefs, _mosek_vars[idx]);\n                    //expr = fusion::Expr::add(expr, fusion::Expr::dot(coefs, _mosek_vars[idx]));\n                } else {\n                    pair<size_t, size_t>  pair;\n                    if (is_indexed(it1.second._p)) {\n//                                idx_inst = it1.second._p->get_id_inst(i);\n                        pair = it1.second._p->get_sdp_inst(inst);\n                    } else idx_inst = inst;\n\n                    if (is_indexed(it1.second._coef)) c_idx_inst = get_poly_id_inst(it1.second._coef);\n                    else c_idx_inst = inst;\n\n                    DebugOff(\"\\nindex: \" << pair.first << \", \" << pair.second);\n                    DebugOff(\"\\nMosek var:\" << _mosek_vars[idx]->toString());\n\n                    auto lterm = fusion::Expr::mul(poly_eval(it1.second._coef, c_idx_inst),\n                                                   _mosek_vars[idx]->index(pair.first,pair.second));\n\n                    if (!it1.second._sign) lterm = fusion::Expr::mul(-1, lterm);\n                    (*fusion_lterms)[lterm_idx] = lterm;\n                    //expr = fusion::Expr::add(expr, lterm);\n                }\n            }\n\n        }\n        else{ //param\n            if (it1.second._coef->_is_transposed) {\n                auto coefs = new_array_ptr<double,1>(it1.second._p->get_nb_instances());\n                for (int j = 0; j<it1.second._p->get_nb_instances(); j++) {\n                    (*coefs)(j) = poly_eval(it1.second._coef,j);\n                }\n                (*fusion_lterms)[lterm_idx] = fusion::Expr::dot(coefs,_mosek_vars[idx]);\n                //expr = fusion::Expr::add(expr,fusion::Expr::dot(coefs,_mosek_vars[idx]));\n            }\n            else { //this results in always taking the first instance? it doesn't use i at all?\n                if (is_indexed(it1.second._p)) idx_inst = it1.second._p->get_id_inst(inst); //fixed here, look for similar errors\n                else idx_inst = inst;\n\n                if (is_indexed(it1.second._coef)) c_idx_inst = get_poly_id_inst(it1.second._coef);\n                else c_idx_inst = inst;\n\n                auto lterm = fusion::Expr::constTerm(poly_eval(it1.second._coef, c_idx_inst) * poly_eval(it1.second._p, inst)); // was idx_inst\n                if (!it1.second._sign) lterm = fusion::Expr::mul(-1, lterm);\n\n                (*fusion_lterms)[lterm_idx] = lterm;\n//                        expr = fusion::Expr::add(expr,lterm);\n            }\n        }\n        lterm_idx++;\n    }\n    fusion::Expression::t res;\n    res = fusion::Expr::add(std::shared_ptr<ndarray<fusion::Expression::t,1>>(fusion_lterms));\n    return res;\n}\n\n//TODO: check use inst\nfusion::Expression::t MosekProgram::form_Fx(map<string, qterm>& qterms, size_t qn, size_t inst){\n    size_t aidx = 0, idx1 = 0, idx2 = 0, idx_inst = 0;\n\n    //create a var map\n    map<pair<size_t,size_t>,int> qvars;\n    int idx_in_A = 0;\n    for(auto& it1: qterms) {\n        idx1 = it1.second._p->first->get_vec_id();\n        idx2 = it1.second._p->second->get_vec_id();\n        if ((it1.second._coef->_is_transposed || it1.second._coef->_is_matrix) && !it1.second._p->first->_is_matrix) {\n            auto dim = it1.second._p->first->get_nb_instances(inst);\n            for (int j = 0; j < dim; j++) {\n                idx_inst = it1.second._p->first->get_id_inst(inst, j);\n                pair<size_t, size_t> p = make_pair(idx1, idx_inst);\n                if (qvars.find(p) == qvars.end()) {\n                    qvars.insert(make_pair(p, idx_in_A));\n                    idx_in_A++;\n                }\n                idx_inst = it1.second._p->second->get_id_inst(inst, j);\n                p = make_pair(idx2, idx_inst);\n                if (qvars.find(p) == qvars.end()) {\n                    qvars.insert(make_pair(p, idx_in_A));\n                    idx_in_A++;\n                }\n            }\n        } else if (it1.second._p->first->_is_transposed) {\n//                auto dim = _p->first->get_nb_instances(i);\n//                for (int j = 0; j<dim; j++)\n//                    res += poly_eval(_coef,i,j) * poly_eval(_p->first, i,j)* poly_eval(_p->second, i,j);\n        } else {\n            idx_inst = it1.second._p->first->get_id_inst(inst);\n            pair<size_t, size_t> p = make_pair(idx1, idx_inst);\n            if (qvars.find(p) == qvars.end()) {\n                qvars.insert(make_pair(p, idx_in_A));\n                idx_in_A++;\n            }\n            idx_inst = it1.second._p->second->get_id_inst(inst);\n            p = make_pair(idx2, idx_inst);\n            if (qvars.find(p) == qvars.end()) {\n                qvars.insert(make_pair(p, idx_in_A));\n                idx_in_A++;\n            }\n        }\n    }\n    auto qvars_arr = new_array_ptr<fusion::Variable::t,1>(qvars.size());\n    for(auto& it1: qvars) {\n        (*qvars_arr)[it1.second] = _mosek_vars[it1.first.first]->index(it1.first.second);\n        DebugOff(\"\\nqvar with index \" << it1.second << \" is (\" << it1.first.first << \", \" << it1.first.second << \")\");\n        DebugOff(\"\\ncorresp mosek vars are \" << _mosek_vars[it1.first.first]->index(it1.first.second)->toString());\n    }\n\n    Eigen::MatrixXf A = Eigen::MatrixXf::Zero(qvars.size(),qvars.size());\n    fusion::Variable::t xi = fusion::Var::vstack(qvars_arr);\n//    auto qvarsi = new_array_ptr<fusion::Variable::t,1>(qn);\n\n    size_t j2 = 0;\n    for (auto& it1: qterms) {\n        double sign;\n        if(!it1.second._sign) sign = -2;\n        else sign = 2;\n        idx1 = it1.second._p->first->get_vec_id();\n        idx2 = it1.second._p->second->get_vec_id();\n        if ((it1.second._coef->_is_transposed || it1.second._coef->_is_matrix) && !it1.second._p->first->_is_matrix) {\n            throw invalid_argument(\"This type of expression in the constraint is not implemented.\");\n//            auto dim = it1.second._p->first->get_nb_instances(inst);\n//            auto qvarsi = new_array_ptr<fusion::Variable::t,1>(dim);\n//            for (int j = 0; j<dim; j++) {\n////                    res += poly_eval(_coef,i,j) * poly_eval(_p->first, i,j)* poly_eval(_p->second, i,j);\n//                if(it1.second._p->first->get_id_inst(inst,j) != it1.second._p->second->get_id_inst(inst,j))\n//                    throw invalid_argument(\"Bilinear expressions in Mosek objective are not implemented.\");\n//                A(aidx,aidx) = sign*poly_eval(it1.second._coef,inst,j);\n//                aidx++;\n//                idx_inst = it1.second._p->first->get_id_inst(inst,j);\n////                (*qvarsi)(j) = _mosek_vars[idx1]->index(idx_inst);\n//            }\n//            xi = fusion::Var::vstack(qvarsi);\n        }\n        else if(it1.second._p->first->_is_transposed){\n//                auto dim = _p->first->get_nb_instances(i);\n//                for (int j = 0; j<dim; j++)\n//                    res += poly_eval(_coef,i,j) * poly_eval(_p->first, i,j)* poly_eval(_p->second, i,j);\n            throw invalid_argument(\"This type of expression in the constraint is not implemented.\");\n        }\n        else {\n//                res = poly_eval(_coef,i) * poly_eval(_p->first, i) * poly_eval(_p->second, i);\n            idx_inst = it1.second._p->first->get_id_inst(inst);\n            int aidx1 = qvars.find(make_pair(idx1,idx_inst))->second;\n            DebugOff(\"\\nvars: \" << _mosek_vars[idx1]->index(idx_inst)->toString());\n            idx_inst = it1.second._p->second->get_id_inst(inst);\n            int aidx2 = qvars.find(make_pair(idx2,idx_inst))->second;\n            DebugOff(\", \" << _mosek_vars[idx2]->index(idx_inst)->toString());\n            if(aidx1==aidx2) A(aidx1,aidx2) = sign*poly_eval(it1.second._coef,inst);\n            else {\n                A(aidx1,aidx2) = 0.5*sign*poly_eval(it1.second._coef,inst);\n                A(aidx2,aidx1) = 0.5*sign*poly_eval(it1.second._coef,inst);\n            }\n//            aidx++;\n\n//            (*qvarsi)(j2) = _mosek_vars[idx1]->index(idx_inst);\n//            j2++;\n        }\n//            if (!it1.second._sign) res *= -1;\n    }\n    DebugOff(\"\\nA = \\n\" << A);\n    DebugOff(\"\\nx = \" << xi->toString());\n\n    Eigen::LLT<Eigen::MatrixXf> lltOfA(A); // compute the Cholesky decomposition of A\n    Eigen::MatrixXf L = lltOfA.matrixL();\n//    Eigen::MatrixXf L = A.sqrt();\n    DebugOff(\"\\nL: \" << L);\n\n    std::shared_ptr<ndarray<double, 1>> Farr = new_array_ptr<double,1>(qn*qn);\n    for(size_t Fi = 0; Fi < L.rows(); Fi++) {\n        for(size_t Fj = 0; Fj < L.cols(); Fj++) {\n            (*Farr)[Fi*(L.cols())+Fj] = L(Fi,Fj);\n        }\n    }\n    fusion::Matrix::t F = fusion::Matrix::dense(qvars.size(),qvars.size(),Farr);\n    DebugOff(\"\\nF = \" << F->toString());\n    fusion::Expression::t Fx = fusion::Expr::mul(F, xi);\n    DebugOff(\"\\nFx = \" << Fx->toString());\n\n    return Fx;\n}\n\nvoid MosekProgram::create_mosek_constraints() {\n    size_t idx = 0, idx_inst = 0, idx1 = 0, idx2 = 0, idx_inst1 = 0, idx_inst2 = 0, nb_inst = 0, inst = 0;\n    size_t c_idx_inst = 0;\n    shared_ptr<Constraint> c;\n    for(auto& p: _model->_cons) {\n        c = p.second;\n        DebugOff(\"\\nconstr \" << c->get_name());\n        if(c->is_nonlinear() && !c->is_quadratic())\n            throw invalid_argument(\"Mosek cannot handle nonlinear constraints that are not convex quadratic.\\n\");\n\n        nb_inst = c->get_nb_instances();\n\n        if (c->is_quadratic()) {\n            size_t qn = get_num_qterms(c->get_qterms());\n            auto fusion_cols = new_array_ptr<fusion::Expression::t,1>(nb_inst);\n            for (int i = 0; i< nb_inst; i++) {\n                //create matrix F;\n                fusion::Expression::t Fx = form_Fx(c->get_qterms(),qn,i);\n\n                //build the linear expression\n                fusion::Expression::t lin_expr_i = create_lin_expr(c->get_lterms(), c->get_cst(), i);\n\n                //arrange it all into a row, add the row to an array\n                auto Earr = new_array_ptr<fusion::Expression::t,1>(2 + qn);\n                (*Earr)[0] = fusion::Expr::constTerm(1);\n                (*Earr)[1] = fusion::Expr::mul(lin_expr_i,-1);\n                for(size_t Fxi = 0; Fxi < qn; Fxi++) {\n                    (*Earr)[Fxi+2] = Fx->index(Fxi);\n                }\n                fusion::Expression::t qexpr = fusion::Expr::hstack(Earr);\n                DebugOff(\"\\nqexpr = \" << qexpr->toString());\n\n                (*fusion_cols)[i] = qexpr;\n            }\n\n            // use the array of rows to create a matrix\n            auto M = fusion::Expr::vstack(fusion_cols);\n            DebugOff(\"\\nM = \" << M->toString());\n\n            // add a conic constraint\n            auto mosek_constr = _mosek_model->constraint(c->get_name(), M, fusion::Domain::inRotatedQCone(nb_inst,2+qn));\n            DebugOff(\"\\nConstraint generated: \" << mosek_constr->toString());\n        } // quadratic expression\n        else{\n            auto fusion_sums = new_array_ptr<fusion::Expression::t, 1>(nb_inst);\n            for (int i = 0; i < nb_inst; i++) {\n                fusion::Expression::t lin_expr = create_lin_expr(c->get_lterms(), c->get_cst(), i);\n                (*fusion_sums)[i] = lin_expr;\n                inst++;\n            }\n            auto E = fusion::Expr::vstack(fusion_sums);\n\n            DebugOff(\"\\nconstr \" << c->get_name() << \" in Mosek: \" << E->toString());\n            if (c->get_type() == geq) {\n                DebugOff(\"\\n >= \" << c->get_rhs());\n                _mosek_model->constraint(c->get_name(), E, fusion::Domain::greaterThan(c->get_rhs()));\n            } else if (c->get_type() == leq) {\n                DebugOff(\"\\n <= \" << c->get_rhs());\n                _mosek_model->constraint(c->get_name(), E, fusion::Domain::lessThan(c->get_rhs()));\n            } else if (c->get_type() == eq) {\n                DebugOff(\" = \" << c->get_rhs());\n                _mosek_model->constraint(c->get_name(), E, fusion::Domain::equalsTo(c->get_rhs()));\n            }\n        } // linear expression\n    } //for(p: _model->_cons)\n}\n\nfusion::Expression::t MosekProgram::form_Fx(map<string, qterm>& qterms, size_t qn){\n    size_t aidx = 0, idx, idx_inst;\n    Eigen::MatrixXf A = Eigen::MatrixXf::Zero(qn,qn);\n    fusion::Variable::t xi;\n    for (auto& it1: qterms) {\n        double sign;\n        if(!it1.second._sign) sign = -2;\n        else sign = 2;\n        idx = it1.second._p->first->get_vec_id();\n        if ((it1.second._coef->_is_transposed || it1.second._coef->_is_matrix) && !it1.second._p->first->_is_matrix) {\n            auto dim = it1.second._p->first->get_nb_instances();\n            auto qvarsi = new_array_ptr<fusion::Variable::t,1>(dim);\n            for (int j = 0; j<dim; j++) { //now only supports quadratic (not bilinear) terms\n//                    res += poly_eval(_coef,i,j) * poly_eval(_p->first, i,j)* poly_eval(_p->second, i,j);\n                if(it1.second._p->first->get_id_inst(j) != it1.second._p->second->get_id_inst(j))\n                    throw invalid_argument(\"Bilinear expressions in Mosek objective are not implemented.\");\n                A(aidx,aidx) = sign*poly_eval(it1.second._coef,0,j);\n                aidx++;\n                idx_inst = it1.second._p->first->get_id_inst(j);\n                (*qvarsi)(j) = _mosek_vars[idx]->index(idx_inst);\n            }\n            xi = fusion::Var::vstack(qvarsi);\n//                (*qvars)(qtermi) = xi; qtermi++;\n        }\n        else if(it1.second._p->first->_is_transposed){\n//                auto dim = _p->first->get_nb_instances(i);\n//                for (int j = 0; j<dim; j++)\n//                    res += poly_eval(_coef,i,j) * poly_eval(_p->first, i,j)* poly_eval(_p->second, i,j);\n            throw invalid_argument(\"This type of expression in the objective is not implemented.\");\n        }\n        else {\n//                res = poly_eval(_coef,i) * poly_eval(_p->first, i) * poly_eval(_p->second, i);\n            throw invalid_argument(\"This type of expression in the objective is not implemented.\");\n        }\n//            if (!it1.second._sign) res *= -1;\n    }\n    DebugOff(\"\\nA = \" << A);\n    DebugOff(\"\\nx = \" << xi->toString());\n\n    Eigen::LLT<Eigen::MatrixXf> lltOfA(A); // compute the Cholesky decomposition of A\n    Eigen::MatrixXf L = lltOfA.matrixL();\n    DebugOff(\"\\nL: \" << L);\n\n    std::shared_ptr<ndarray<double, 1>> Farr = new_array_ptr<double,1>(qn*qn);\n    for(size_t Fi = 0; Fi < L.rows(); Fi++) {\n        for(size_t Fj = 0; Fj < L.cols(); Fj++) {\n            (*Farr)[Fi*(L.cols())+Fj] = L(Fi,Fj);\n        }\n    }\n    fusion::Matrix::t F = fusion::Matrix::dense(qn,qn,Farr);\n    DebugOff(\"\\nF = \" << F->toString());\n    fusion::Expression::t Fx = fusion::Expr::mul(F, xi);\n    DebugOff(\"\\nFx = \" << Fx->toString());\n\n    return Fx;\n}\n\nvoid MosekProgram::set_mosek_objective() {\n    size_t idx = 0, idx_inst = 0, idx1 = 0, idx2 = 0, idx_inst1 = 0, idx_inst2 = 0, qn;\n    size_t c_idx_inst = 0;\n    // initialize with the constant part.\n    monty::rc_ptr< ::mosek::fusion::Expression >  expr= fusion::Expr::constTerm(poly_eval(_model->_obj.get_cst())); // expr is a pointer to the Expression.\n    if(_model->_obj.get_qterms().empty() == false){\n        //cerr << \"\\nMosek doesn't support quadratic objectives!\\n\";\n        qn = get_num_qterms(_model->_obj.get_qterms());\n\n        _mosek_vars.push_back(_mosek_model->variable(\"r_obj\", 1, fusion::Domain::unbounded()));\n        //obj = r + (linear part) (see Mosek modelling cookbook)\n        expr = fusion::Expr::add(expr,_mosek_vars[_mosek_vars.size()-1]);\n        //auto qvars = new_array_ptr<fusion::Variable::t,1>(_model->_obj.get_qterms().size());\n        fusion::Expression::t Fx = form_Fx(_model->_obj.get_qterms(),qn);\n\n        auto Earr = new_array_ptr<fusion::Expression::t,1>(2 + qn);\n        (*Earr)[0] = fusion::Expr::constTerm(1);\n        (*Earr)[1] = _mosek_vars[_mosek_vars.size()-1]->asExpr();\n        for(size_t Fxi = 0; Fxi < qn; Fxi++) {\n            (*Earr)[Fxi+2] = Fx->index(Fxi);\n        }\n        fusion::Expression::t qexpr = fusion::Expr::vstack(Earr);\n        DebugOn(\"\\nqexpr = \" << qexpr->toString());\n\n        //(1,r,Fx) in Qr\n        _mosek_model->constraint(qexpr, fusion::Domain::inRotatedQCone());\n    }\n    for (auto& it1: _model->_obj.get_lterms()) {\n        //idx = it1.second._p->get_id();\n        idx = it1.second._p->get_vec_id();\n        CType vartype = it1.second._p->get_type();\n        if (vartype == var_c) {\n            if (it1.second._coef->_is_transposed) {\n                auto coefs = new_array_ptr<double,1>((it1.second._p->get_nb_instances()));\n                for (int j = 0; j<it1.second._p->get_nb_instances(); j++) {\n                    (*coefs)(j)=poly_eval(it1.second._coef, j);\n                }\n                expr = fusion::Expr::add(expr,fusion::Expr::dot(coefs,_mosek_vars[idx]));\n            }\n            else {\n                // get pos.\n                idx_inst = it1.second._p->get_id_inst();\n                c_idx_inst = get_poly_id_inst(it1.second._coef);\n                //auto t = _mosek_vars[idx]->index\n                auto lterm = fusion::Expr::mul(poly_eval(it1.second._coef, c_idx_inst), _mosek_vars[idx]->index(idx_inst));\n                if (!it1.second._sign) {\n                    lterm = fusion::Expr::mul(-1, lterm);\n                }\n                expr = fusion::Expr::add(expr,lterm);\n            }\n        }\n        else {\n            // sdpvar_c\n            if (it1.second._coef->_is_transposed) {\n                auto coefs = new_array_ptr<double,1>((it1.second._p->get_nb_instances()));\n                for (int j = 0; j<it1.second._p->get_nb_instances(); j++) {\n                    (*coefs)(j)=poly_eval(it1.second._coef, j);\n                }\n                expr = fusion::Expr::add(expr,fusion::Expr::dot(coefs,_mosek_vars[idx]));\n            }\n            else {\n                // retrive the index of the parameter.\n                // This is quite different from the general variable definition.\n                pair<size_t, size_t>  pair = it1.second._p->get_sdpid();\n                c_idx_inst = get_poly_id_inst(it1.second._coef);\n                auto lterm = fusion::Expr::mul(poly_eval(it1.second._coef, c_idx_inst), _mosek_vars[idx]->index(pair.first,pair.second));\n\n                if (!it1.second._sign) {\n                    lterm = fusion::Expr::mul(-1, lterm);\n                }\n                expr = fusion::Expr::add(expr,lterm);\n            }\n        }\n    }\n    if (_model->_objt == maximize) {\n        _mosek_model->objective(\"obj\", mosek::fusion::ObjectiveSense::Maximize, expr);\n    }\n    else {\n        _mosek_model->objective(\"obj\", mosek::fusion::ObjectiveSense::Minimize, expr);\n    }\n//    cout << \"\\nObj = \" << expr->toString() << endl;\n}\n\nvoid MosekProgram::prepare_model() {\n    double time_before = get_wall_time();\n    fill_in_mosek_vars();\n    create_mosek_constraints();\n    set_mosek_objective();\n    cout << \"\\nTime spent on building model = \" << get_wall_time() - time_before;\n    //    print_constraints();\n}\n", "meta": {"hexsha": "779688235b5e04a1df8f51cda59b2c2d8abeb8aa", "size": 44169, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MosekProgram.cpp", "max_stars_repo_name": "lanl-ansi/ODO", "max_stars_repo_head_hexsha": "d454eb226cd1861b622a381198ce4756709dfa95", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-02-28T14:49:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:32:09.000Z", "max_issues_repo_path": "src/MosekProgram.cpp", "max_issues_repo_name": "hhijazi/Gravity", "max_issues_repo_head_hexsha": "08c4470547a94d878cd7f306cc18b0d05d452e02", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-22T00:14:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T00:14:48.000Z", "max_forks_repo_path": "src/MosekProgram.cpp", "max_forks_repo_name": "hhijazi/Gravity", "max_forks_repo_head_hexsha": "08c4470547a94d878cd7f306cc18b0d05d452e02", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-12-31T14:04:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T11:44:49.000Z", "avg_line_length": 48.2721311475, "max_line_length": 191, "alphanum_fraction": 0.5124182119, "num_tokens": 11490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2692999171646949}}
{"text": "#include <ctype.h>\n#include <regex>\n#include <algorithm>\n\n#include <boost/log/trivial.hpp>\n\n#include \"lib/stats/relative_strength_index.h\"\n#include \"lib/stats/exponential_moving_average.h\"\n#include \"lib/stats/simple_moving_average.h\"\n#include \"lib/stats/bollinger.h\"\n#include \"lib/rsiscript.h\"\n\n/**\n * Parse a math-related script. There are several phases.\n *\n * 1. Replace variables.\n * 2. Identify sections in parenthesis. Process these first.\n * 3. Process the math equations/comparisons.\n *\n * @param const char *script [ex: (1+3)/(2 * (4 + 6))]\n * @return const char *result\n */\nint script_max_paren_depth = 50;\nstd::string rsiscript::parse(const char* const script, const stockinfo &data) {\n\tstd::string err = \"0\", repl, expr = script;\n\tstd::size_t pos, lparen_pos, rparen_pos = 0;\n\tunsigned int lparens, rparens;\n\tbool found = false;\n\n\tlast_variables_used.clear();\n\tlast_variables.clear();\n\tif (script == nullptr)\n\t\treturn err;\n\n\tBOOST_LOG_TRIVIAL(trace) << \"Script: \" << script;\n\texpr = replace_variables(expr, data);\n\n\tdo {\n\t\t// Search for a ')'.\n\t\tpos = rparen_pos = expr.find(\")\", rparen_pos);\n\t\tfound = (rparen_pos != std::string::npos);\n\n\t\t// Find the matching '('.\n\t\tif (found) {\n\t\t\trparens = 1;\n\t\t\tlparens = 0;\n\n\t\t\twhile (pos > 0) {\n\t\t\t\tpos--;\n\n\t\t\t\tif (expr[pos] == ')') // TODO: Should not be possible.\n\t\t\t\t\trparens++;\n\t\t\t\telse if (expr[pos] == '(') {\n\t\t\t\t\tlparens++;\n\n\t\t\t\t\t// Will only happen with a '(' find.\n\t\t\t\t\tif (lparens == rparens) {\n\t\t\t\t\t\tlparen_pos = pos;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ERROR: Mismatched parenthesis.\n\t\t\tif (rparens != lparens) {\n\t\t\t\tBOOST_LOG_TRIVIAL(error) << \"Mismatched parenthesis: \" << script;\n\t\t\t\tprintf(\"ERROR: Mismatched parenthesis: %s\\n\", script);\n\t\t\t\treturn err;\n\t\t\t}\n\n\t\t\t// Parse the substring. Do not include the current parenthesis set.\n\t\t\trepl = parse(expr.substr(lparen_pos + 1, rparen_pos - lparen_pos - 1).c_str(), data);\n\t\t\trepl = exec_script_calculate(repl);\n\t\t\texpr.replace(lparen_pos, rparen_pos - lparen_pos + 1, repl);\n\n\t\t\trparen_pos -= (rparen_pos - lparen_pos - repl.length());\n\t\t}\n\t} while (found);\n\n\texpr = exec_script_calculate(expr);\n\tBOOST_LOG_TRIVIAL(info) << \"End of run: \" << expr;\n\treturn expr;\n}\n\n/**\n * Find/replace the variables in our script.\n *\n * @return string\n */\nstd::string rsiscript::replace_variables(const std::string &script, const stockinfo &data) {\n\tstd::string expr = script;\n\tstd::string err = \"0\", repl;\n\tstd::size_t pos, lparen_pos, rparen_pos = 0;\n\tunsigned int lparens, rparens;\n\tbool found = false;\n\n\tdo {\n\t\t// Search for a ')'.\n\t\tpos = rparen_pos = expr.find(\"}\", rparen_pos);\n\t\tfound = (rparen_pos != std::string::npos);\n\n\t\t// Find the matching '('.\n\t\tif (found) {\n\t\t\trparens = 1;\n\t\t\tlparens = 0;\n\n\t\t\twhile (pos > 0) {\n\t\t\t\tpos--;\n\n\t\t\t\tif (expr[pos] == '}') // TODO: Should not be possible.\n\t\t\t\t\trparens++;\n\t\t\t\telse if (expr[pos] == '{') {\n\t\t\t\t\tlparens++;\n\n\t\t\t\t\t// Will only happen with a '(' find.\n\t\t\t\t\tif (lparens == rparens) {\n\t\t\t\t\t\tlparen_pos = pos;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/*if (lparens > script_max_paren_depth) {\n\t\t\t\t\tBOOST_LOG_TRIVIAL(error) << \"Found too many opening parens: \" << lparens;\n\t\t\t\t\tprintf(\"Found too many opening parens: %iu\\n\", lparens);\n\t\t\t\t\treturn nullptr;\n\t\t\t\t}*/\n\t\t\t}\n\n\t\t\t// ERROR: Mismatched parenthesis.\n\t\t\tif (rparens != lparens) {\n\t\t\t\tBOOST_LOG_TRIVIAL(error) << \"Mismatched brackets: \" << script;\n\t\t\t\tprintf(\"ERROR: Mismatched brackets: %s\\n\", script.c_str());\n\t\t\t\treturn err;\n\t\t\t}\n\n\t\t\t// Parse the substring. Do not include the current parenthesis set.\n\t\t\trepl = replace_variables(expr.substr(lparen_pos + 1, rparen_pos - lparen_pos - 1), data);\n\t\t\tBOOST_LOG_TRIVIAL(trace) << \"Replacing: \" << repl;\n\t\t\trepl = variables(repl, data);\n\t\t\t// TODO: Replace all instances of this same variable?\n\t\t\texpr.replace(lparen_pos, rparen_pos - lparen_pos + 1, repl);\n\n\t\t\trparen_pos -= (rparen_pos - lparen_pos - repl.length());\n\t\t}\n\t} while (found);\n\n\tBOOST_LOG_TRIVIAL(trace) << \"Replaced variables: \" << expr;\n\n\treturn expr;\n}\n\n/**\n * Parse script variables into values.\n *\n * Format: high\n * Format: rsi\n * Format: high:52wk\n * Format: rsi:52wk(28)\n *\n * @param string req The variable to process.\n * @param stockinfo data The stock data to use in processing req.\n * @return string The script without any more variables.\n */\nstd::string rsiscript::variables(const std::string &req, const stockinfo &data) {\n\tstd::string ret = \"0\";\n\tstd::vector<std::string> tokens;\n\tstockinfo *working_data = (stockinfo *)&data;\n\tstockinfo week_data;\n\n\ttokenize(req, tokens, \":\", true);\n\tBOOST_LOG_TRIVIAL(trace) << \"Variable tokens: \" << tokens.size();\n\n\t// TODO: Parse options for stat variables. Weekly, monthly, RSI/SMA/EMA/BB/&c.\n\tstd::string period;\n\tif (tokens.size() >= 2) {\n\t\tperiod = tokens[1];\n\t}\n\tif (period.length()) {\n\t\tint number;\n\t\ttimeperiods tp;\n\t\tparse_period(period, number, tp);\n\n\t\tweek_data = working_data->rollup(number, tp);\n\t\tworking_data = &week_data;\n\t}\n\n\tif (!(*working_data).length()) {\n\t\treturn ret;\n\t}\n\n\t// Process the requested variable.\n\tstd::string var = tokens[0];\n\tif (var.compare(\"open\") == 0) {\n\t\tret = last_variable(req, (*working_data)[0]->open);\n\t}\n\telse if (var.compare(\"high\") == 0) {\n\t\tret = last_variable(req, (*working_data)[0]->high);\n\t}\n\telse if (var.compare(\"low\") == 0) {\n\t\tret = last_variable(req, (*working_data)[0]->low);\n\t}\n\telse if (var.compare(\"close\") == 0) {\n\t\tret = last_variable(req, (*working_data)[0]->close);\n\t}\n\telse if (var.compare(\"volume\") == 0) {\n\t\tret = last_variable(req, (*working_data)[0]->volume);\n\t}\n\telse if (var.compare(\"rsi\") == 0) {\n\t\trelative_strength_index rsi;\n\t\tdouble *rsi_data = rsi.generate(*working_data, 14, (*working_data).length() - 26);\n\t\tret = last_variable(req, *rsi_data);\n\t\tfree(rsi_data);\n\t}\n\telse if (var.compare(\"sma\") == 0) {\n\t\tsimple_moving_average sma;\n\t\tdouble *sma_data = sma.generate(*working_data, 20, (*working_data).length() - 26);\n\t\tret = last_variable(req, *sma_data);\n\t\tfree(sma_data);\n\t}\n\telse if (var.compare(\"ema\") == 0) {\n\t\tsimple_moving_average ema;\n\t\tdouble *ema_data = ema.generate(*working_data, 20, (*working_data).length() - 26);\n\t\tret = last_variable(req, *ema_data);\n\t\tfree(ema_data);\n\t}\n\telse if (var.compare(\"bb_top\") == 0) {\n\t\tsimple_moving_average sma;\n\t\tbollinger bb;\n\t\tdouble *sma_data = sma.generate(*working_data, 20, (*working_data).length() - 26);\n\t\tdouble *bb_data = bb.bands(*working_data, 14, (*working_data).length() - 26);\n\t\tret = last_variable(req, *sma_data + *bb_data);\n\t\tfree(sma_data);\n\t\tfree(bb_data);\n\t}\n\telse if (var.compare(\"bb_bottom\") == 0) {\n\t\tsimple_moving_average sma;\n\t\tbollinger bb;\n\t\tdouble *sma_data = sma.generate(*working_data, 20, (*working_data).length() - 26);\n\t\tdouble *bb_data = bb.bands(*working_data, 14, (*working_data).length() - 26);\n\t\tret = last_variable(req, *sma_data - *bb_data);\n\t\tfree(sma_data);\n\t\tfree(bb_data);\n\t}\n\n\treturn ret;\n}\n\n/**\n * Parse a string like \"52weeks\" roughly into \"52\" and \"week.\" It would have been nice to use regex for this, but the\n * regex parser does not appear to work in this dev's compiler.\n *\n * @todo We could refactor this to place number & period into a struct.\n *\n * @param req String\n * @param number Return value.\n * @param period Return value.\n */\nvoid rsiscript::parse_period(std::string req, int &number, timeperiods &period) {\n\tstd::istringstream i(req);\n\ti >> number;\n\n\tif (!number) {\n\t\tnumber = 1;\n\t}\n\n\tif (req.compare(\"week\"))\n\t\tperiod = week;\n\telse if (req.compare(\"month\"))\n\t\tperiod = month;\n\telse if (req.compare(\"year\"))\n\t\tperiod = year;\n\telse //if (req.compare(\"day\"))\n\t\tperiod = day;\n\n\treturn;\n}\n\n/**\n * Store name + value in last_variables.\n *\n * @param name\n * @param value\n * @return string value\n */\ntemplate<typename T>\nstd::string rsiscript::last_variable(const std::string &name, T value) {\n\tstd::string ret = std::to_string(value);\n\tbool add = !last_variables_used.size();\n\n\tif (!add) {\n\t\tadd = std::find(last_variables_used.begin(), last_variables_used.end(), name) == last_variables_used.end();\n\t}\n\n\tif (add) {\n\t\tif (last_variables.length()) {\n\t\t\tlast_variables += \", \";\n\t\t}\n\t\tlast_variables += name + \" = \" + ret;\n\t\tlast_variables_used.push_back(name);\n\t}\n\n\treturn ret;\n}\n\n/**\n * Direct the order of operator usage.\n *\n * Phase 1: ^\n * Phase 2: * / %\n * Phase 3: + -\n * Phase 4: > < =\n * Phase 5: | &\n *\n * @todo >= <=\n *\n * @return string The value calculated.\n */\nconst std::string rsiscript::exec_script_calculate(const std::string &script) {\n\tstd::string ret;\n\n\tBOOST_LOG_TRIVIAL(trace) << \"Script chunk: \" << script;\n\n\t// Operational passes. The terminating 0's allow us to use string functions.\n\tconst char first_pass[] = {'^', 0};\n\tconst char second_pass[] = {'*', 'x', '/', '%', 0};\n\tconst char third_pass[] = {'+', '-', 0};\n\tconst char fourth_pass[] = {'>', '<', '=', 0};\n\tconst char fifth_pass[] = {'|', '&', 0};\n\n\t// Pass over the string three times to give us proper order of operation.\n\tret = exec_script_operations(script, first_pass);\n\tret = exec_script_operations(ret, second_pass);\n\tret = exec_script_operations(ret, third_pass);\n\tret = exec_script_operations(ret, fourth_pass);\n\tret = exec_script_operations(ret, fifth_pass);\n\n\tBOOST_LOG_TRIVIAL(trace) << \"Script chunk reduced: \" << ret;\n\n\treturn ret;\n}\n\n/**\n * Find numbers and their operators for direct calculation.\n *\n * @return string The calculated value(s).\n */\nstd::string rsiscript::exec_script_operations(const std::string &script, const char *operators) {\n\tstd::size_t sc_len = script.length();\n\tconst char digits[] = \"0123456789.\";\n\tstd::size_t x, start, operation, end;\n\tbool isdigit, calc_end, calc_start = false;\n\tlong num1l, num2l;\n\tdouble num1d, num2d;\n\tstd::string ret = script, result, num1str, num2str;\n\n\tfor (x = 0; x < sc_len; x++) {\n\t\t/**\n\t\t * This logic assumes well-formed expressions: 4+(*1+2) => 4+*3 => 4+3 => 7.\n\t\t */\n\n\t\t// Ignore space characters.\n\t\tif (isspace(ret[x]))\n\t\t\tcontinue;\n\n\t\t// Mark the beginning of numbers as we work through the string.\n\t\tisdigit = (strchr(digits, ret[x]) != NULL);\n\t\tif (!calc_start && isdigit) {\n\t\t\tcalc_start = true;\n\t\t\tstart = x;\n\t\t}\n\t\t// After we find a number, find an operation.\n\t\telse if (calc_start && (strchr(operators, ret[x]) != NULL)) {\n\t\t\toperation = x;\n\t\t\tcalc_end = false;\n\n\t\t\t// Is there another number after the operator?\n\t\t\t// TODO: Allow negative numbers.\n\t\t\tfor (x++; x < sc_len; x++) {\n\t\t\t\tif (strchr(digits, ret[x]) != NULL) {\n\t\t\t\t\tcalc_end = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If we found another number...\n\t\t\tif (calc_end) {\n\t\t\t\t// Find the end of the number;\n\t\t\t\tend = sc_len;\n\t\t\t\tfor (x++; x < sc_len; x++) {\n\t\t\t\t\tif (strchr(digits, ret[x]) == NULL) {\n\t\t\t\t\t\tend = x - 1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Pull this expression apart.\n\t\t\t\tnum1str = ret.substr(start, operation - start);\n\t\t\t\tnum2str = ret.substr(operation + 1, end - operation);\n\n\t\t\t\tBOOST_LOG_TRIVIAL(trace) << \"Script operation: \" << num1str << \", \" << ret[operation] << \", \" << num2str;\n\n\t\t\t\t// If this is a long/integer operation\n\t\t\t\tif ((num1str.find(\".\") == std::string::npos) && (num2str.find(\".\") == std::string::npos)) {\n\t\t\t\t\tnum1l = atol(num1str.c_str());\n\t\t\t\t\tnum2l = atol(num2str.c_str());\n\n\t\t\t\t\tresult = exec_script_calculate_operation(num1l, num2l, ret[operation]);\n\t\t\t\t} else {\n\t\t\t\t\tnum1d = atof(num1str.c_str());\n\t\t\t\t\tnum2d = atof(num2str.c_str());\n\n\t\t\t\t\tresult = exec_script_calculate_operation(num1d, num2d, ret[operation]);\n\t\t\t\t}\n\n\t\t\t\tret.replace(start, end - start + 1, result);\n\t\t\t\tsc_len = ret.length();\n\t\t\t\tx = start; // Re-process this result since it might start the next calculation.\n\n\t\t\t\tBOOST_LOG_TRIVIAL(trace) << \"Script operation result: \" << ret;\n\t\t\t} // End calculation.\n\n\t\t\t//calc_start = false;\n\t\t} // End operator section.\n\t\telse if (!isdigit) {\n\t\t\t// If this is not a valid digit, a space, or in the current operations list, start over.\n\t\t\tcalc_start = false;\n\t\t}\n\t} // Next character.\n\n\treturn ret;\n}\n\n/**\n * Takes two numeric (int/double) values and a comparison operator. Performs the required operation.\n *\n * @return int/double\n */\ntemplate<typename T>\nstd::string rsiscript::exec_script_calculate_operation(const T val1, const T val2, char operation) {\n\tdouble res;\n\tT result;\n\n\tswitch(operation) {\n\t\tcase '*':\n\t\tcase 'x':\n\t\t\tresult = val1 * val2;\n\t\t\tbreak;\n\t\tcase '/':\n\t\t\tres = (double)val1 / (double)val2;\n\t\t\tbreak;\n\t\tcase '+':\n\t\t\tresult = val1 + val2;\n\t\t\tbreak;\n\t\tcase '-':\n\t\t\tresult = val1 - val2;\n\t\t\tbreak;\n\t\tcase '^':\n\t\t\tresult = pow(val1, val2);\n\t\t\tbreak;\n\t\tcase '%':\n\t\t\tresult = remainder(val1, val2);\n\t\t\tbreak;\n\t\tcase '>':\n\t\t\tresult = (val1 > val2) ? 1 : 0;\n\t\t\tbreak;\n\t\tcase '<':\n\t\t\tresult = (val1 < val2) ? 1 : 0;\n\t\t\tbreak;\n\t\tcase '=':\n\t\t\tresult = (val1 == val2) ? 1 : 0;\n\t\t\tbreak;\n\t\tcase '|':\n\t\t\tresult = (val1 || val2) ? 1 : 0;\n\t\t\tbreak;\n\t\tcase '&':\n\t\t\tresult = (val1 && val2) ? 1 : 0;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tresult = 0;\n\t\t\tBOOST_LOG_TRIVIAL(error) << \"Unknown script operation: \" << operation;\n\t}\n\n\t// Force (double) for division.\n\treturn (operation == '/') ? std::to_string(res) : std::to_string(result);\n}\n\n/**\n * Split a string.\n *\n * @link https://stackoverflow.com/a/1493195/850782\n *\n * @param string str\n * @param tokens The return structure.\n * @param string delimiters The characters to split for (default: \" \").\n * @param bool trimEmpty Should empty values be skipped (default: true)?\n * @return None. Use tokens.\n */\ntemplate<class ContainerT>\nvoid rsiscript::tokenize(const std::string& str, ContainerT& tokens,\n\t\t\t\tconst std::string& delimiters, bool trimEmpty)\n{\n\tstd::string::size_type pos, lastPos = 0, length = str.length();\n\n\tusing value_type\t= typename ContainerT::value_type;\n\tusing size_type\t\t= typename ContainerT::size_type;\n\n\twhile(lastPos < length + 1)\n\t{\n\t\tpos = str.find_first_of(delimiters, lastPos);\n\t\tif(pos == std::string::npos)\n\t\t{\n\t\t\tpos = length;\n\t\t}\n\n\t\tif(pos != lastPos || !trimEmpty)\n\t\t\ttokens.push_back(value_type(str.data()+lastPos,\n\t\t\t\t\t(size_type)pos-lastPos ));\n\n\t\tlastPos = pos + 1;\n\t}\n}\n", "meta": {"hexsha": "0bd8ecc1af3581a373e814ad357a51b809919c51", "size": 13864, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/rsiscript.cpp", "max_stars_repo_name": "EpicVoyage/rsiscan", "max_stars_repo_head_hexsha": "0ab639f70b71115e478a26e33fb7c7f9e231608f", "max_stars_repo_licenses": ["MIT"], "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/rsiscript.cpp", "max_issues_repo_name": "EpicVoyage/rsiscan", "max_issues_repo_head_hexsha": "0ab639f70b71115e478a26e33fb7c7f9e231608f", "max_issues_repo_licenses": ["MIT"], "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/rsiscript.cpp", "max_forks_repo_name": "EpicVoyage/rsiscan", "max_forks_repo_head_hexsha": "0ab639f70b71115e478a26e33fb7c7f9e231608f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-06-21T04:13:44.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-21T04:13:44.000Z", "avg_line_length": 26.5593869732, "max_line_length": 117, "alphanum_fraction": 0.6395701096, "num_tokens": 4031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.26929991716469487}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// This file is manually converted from PROJ4\r\n\r\n// Copyright (c) 2008-2012 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 Geometry Library by Barend Gehrels (Geodan, Amsterdam)\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_IMPL_PJ_AUTH_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_IMPL_PJ_AUTH_HPP\r\n\r\n#include <cassert>\r\n#include <cmath>\r\n\r\n#include <boost/geometry/core/assert.hpp>\r\n\r\nnamespace boost { namespace geometry { namespace projections {\r\n\r\nnamespace detail {\r\n\r\nstatic const int APA_SIZE = 3;\r\n\r\n/* determine latitude from authalic latitude */\r\ntemplate <typename T>\r\ninline bool pj_authset(T const& es, T* APA)\r\n{\r\n    BOOST_GEOMETRY_ASSERT(0 != APA);\r\n\r\n    static const T P00 = .33333333333333333333;\r\n    static const T P01 = .17222222222222222222;\r\n    static const T P02 = .10257936507936507936;\r\n    static const T P10 = .06388888888888888888;\r\n    static const T P11 = .06640211640211640211;\r\n    static const T P20 = .01641501294219154443;\r\n\r\n    T t = 0;\r\n\r\n    // if (APA = (double *)pj_malloc(APA_SIZE * sizeof(double)))\r\n    {\r\n        APA[0] = es * P00;\r\n        t = es * es;\r\n        APA[0] += t * P01;\r\n        APA[1] = t * P10;\r\n        t *= es;\r\n        APA[0] += t * P02;\r\n        APA[1] += t * P11;\r\n        APA[2] = t * P20;\r\n    }\r\n    return true;\r\n}\r\n\r\ntemplate <typename T>\r\ninline T pj_authlat(T const& beta, const T* APA)\r\n{\r\n    BOOST_GEOMETRY_ASSERT(0 != APA);\r\n\r\n    T const t = beta + beta;\r\n\r\n    return(beta + APA[0] * sin(t) + APA[1] * sin(t + t) + APA[2] * sin(t + t + t));\r\n}\r\n\r\n} // namespace detail\r\n}}} // namespace boost::geometry::projections\r\n\r\n#endif // BOOST_GEOMETRY_PROJECTIONS_IMPL_PJ_AUTH_HPP\r\n", "meta": {"hexsha": "7086c8162012733a2fca0465e61ba020e14909f1", "size": 3400, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/boost/geometry/srs/projections/impl/pj_auth.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/impl/pj_auth.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/impl/pj_auth.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": 35.4166666667, "max_line_length": 84, "alphanum_fraction": 0.6947058824, "num_tokens": 846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160664, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2692999171646948}}
{"text": "#include \"IterativeClosestPoint.h\"\n\n#include <Eigen/Geometry>\n\n#include \"SIMPLib/Common/Constants.h\"\n#include \"SIMPLib/DataContainers/DataContainer.h\"\n#include \"SIMPLib/DataContainers/DataContainerArray.h\"\n#include \"SIMPLib/FilterParameters/BooleanFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/DataContainerSelectionFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/IntFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/StringFilterParameter.h\"\n#include \"SIMPLib/Geometry/VertexGeom.h\"\n\n#include \"DREAM3DReview/DREAM3DReviewConstants.h\"\n#include \"DREAM3DReview/DREAM3DReviewVersion.h\"\n\n#include \"DREAM3DReview/DREAM3DReviewFilters/util/nanoflann.hpp\"\n\nnamespace\n{\ntemplate <typename Derived>\nstruct VertexGeomAdaptor\n{\n  const Derived& obj;\n\n  VertexGeomAdaptor(const Derived& obj_)\n  : obj(obj_)\n  {\n  }\n\n  inline const Derived& derived() const\n  {\n    return obj;\n  }\n\n  inline size_t kdtree_get_point_count() const\n  {\n    return derived()->getNumberOfVertices();\n  }\n\n  inline float kdtree_get_pt(const size_t idx, const size_t dim) const\n  {\n    if(dim == 0)\n    {\n      return derived()->getVertexPointer(idx)[0];\n    }\n    if(dim == 1)\n    {\n      return derived()->getVertexPointer(idx)[1];\n    }\n\n    return derived()->getVertexPointer(idx)[2];\n  }\n\n  template <class BBOX>\n  bool kdtree_get_bbox(BBOX& /*bb*/) const\n  {\n    return false;\n  }\n};\n} // namespace\n\nenum createdPathID : RenameDataPath::DataID_t\n{\n  AttributeMatrixID20 = 20,\n  ArrayID21 = 21,\n};\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nIterativeClosestPoint::IterativeClosestPoint()\n{\n  initialize();\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nIterativeClosestPoint::~IterativeClosestPoint() = default;\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid IterativeClosestPoint::initialize()\n{\n  clearErrorCode();\n  clearWarningCode();\n  setCancel(false);\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid IterativeClosestPoint::setupFilterParameters()\n{\n  FilterParameterVectorType parameters;\n  DataContainerSelectionFilterParameter::RequirementType dcsReq;\n  dcsReq.dcGeometryTypes = {IGeometry::Type::Vertex};\n  parameters.push_back(SIMPL_NEW_DC_SELECTION_FP(\"Moving Vertex Geometry\", MovingVertexGeometry, FilterParameter::Category::RequiredArray, IterativeClosestPoint, dcsReq));\n  parameters.push_back(SIMPL_NEW_DC_SELECTION_FP(\"Target Vertex Geometry\", TargetVertexGeometry, FilterParameter::Category::RequiredArray, IterativeClosestPoint, dcsReq));\n  parameters.push_back(SIMPL_NEW_INTEGER_FP(\"Number of Iterations\", Iterations, FilterParameter::Category::Parameter, IterativeClosestPoint));\n  parameters.push_back(SIMPL_NEW_BOOL_FP(\"Apply Transform to Moving Geometry\", ApplyTransform, FilterParameter::Category::Parameter, IterativeClosestPoint));\n  parameters.push_back(SIMPL_NEW_STRING_FP(\"Transform Attribute Matrix Name\", TransformAttributeMatrixName, FilterParameter::Category::CreatedArray, IterativeClosestPoint));\n  parameters.push_back(SIMPL_NEW_STRING_FP(\"Transform Array Name\", TransformArrayName, FilterParameter::Category::CreatedArray, IterativeClosestPoint));\n  setFilterParameters(parameters);\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid IterativeClosestPoint::dataCheck()\n{\n  clearErrorCode();\n  clearWarningCode();\n\n  getDataContainerArray()->getPrereqGeometryFromDataContainer<VertexGeom>(this, m_MovingVertexGeometry);\n  getDataContainerArray()->getPrereqGeometryFromDataContainer<VertexGeom>(this, m_TargetVertexGeometry);\n\n  if(getIterations() < 1)\n  {\n    setErrorCondition(-1, \"Number if iterations must be at least 1\");\n  }\n\n  DataContainer::Pointer dc = getDataContainerArray()->getPrereqDataContainer(this, m_MovingVertexGeometry);\n\n  if(getErrorCode() < 0)\n  {\n    return;\n  }\n\n  AttributeMatrix::Pointer am = dc->createNonPrereqAttributeMatrix(this, DataArrayPath(m_MovingVertexGeometry.getDataContainerName(), getTransformAttributeMatrixName(), \"\"), {1},\n                                                                   AttributeMatrix::Type::Generic, AttributeMatrixID20);\n\n  if(getErrorCode() < 0)\n  {\n    return;\n  }\n\n  am->createNonPrereqArray<DataArray<float>>(this, getTransformArrayName(), 0, {4, 4}, ArrayID21);\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid IterativeClosestPoint::execute()\n{\n  initialize();\n  dataCheck();\n  if(getErrorCode() < 0)\n  {\n    return;\n  }\n\n  VertexGeom::Pointer moving = getDataContainerArray()->getDataContainer(m_MovingVertexGeometry.getDataContainerName())->getGeometryAs<VertexGeom>();\n  VertexGeom::Pointer movingCopy = std::dynamic_pointer_cast<VertexGeom>(moving->deepCopy());\n  VertexGeom::Pointer target = getDataContainerArray()->getDataContainer(m_TargetVertexGeometry.getDataContainerName())->getGeometryAs<VertexGeom>();\n\n  float* movingPtr = moving->getVertexPointer(0);\n  float* movingCopyPtr = movingCopy->getVertexPointer(0);\n  float* targetPtr = target->getVertexPointer(0);\n\n  size_t numMovingVerts = moving->getNumberOfVertices();\n  std::vector<size_t> cDims(1, 3);\n  FloatArrayType::Pointer dynTarget = FloatArrayType::CreateArray(numMovingVerts, cDims, \"tmp\", true);\n  dynTarget->initializeWithZeros();\n  float* dynTargetPtr = dynTarget->getPointer(0);\n\n  using Adaptor = VertexGeomAdaptor<VertexGeom::Pointer>;\n  const Adaptor adaptor(target);\n\n  notifyStatusMessage(\"Building kd-tree index...\");\n\n  using KDtree = nanoflann::KDTreeSingleIndexAdaptor<nanoflann::L2_Adaptor<float, Adaptor>, Adaptor, 3>;\n  KDtree index(3, adaptor, nanoflann::KDTreeSingleIndexAdaptorParams(30));\n  index.buildIndex();\n\n  size_t iters = m_Iterations;\n  const size_t nn = 1;\n\n  typedef Eigen::Matrix<float, 3, Eigen::Dynamic, Eigen::ColMajor> PointCloud;\n  typedef Eigen::Matrix<float, 4, 4, Eigen::ColMajor> UmeyamaTransform;\n\n  UmeyamaTransform globalTransform;\n  globalTransform << 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1;\n\n  int64_t progIncrement = iters / 100;\n  int64_t prog = 1;\n  int64_t progressInt = 0;\n  int64_t counter = 0;\n\n  for(size_t i = 0; i < iters; i++)\n  {\n    if(getCancel())\n    {\n      return;\n    }\n\n    for(size_t j = 0; j < numMovingVerts; j++)\n    {\n      size_t id;\n      float dist;\n      nanoflann::KNNResultSet<float> results(nn);\n      results.init(&id, &dist);\n      index.findNeighbors(results, movingCopyPtr + (3 * j), nanoflann::SearchParams());\n      dynTargetPtr[3 * j + 0] = targetPtr[3 * id + 0];\n      dynTargetPtr[3 * j + 1] = targetPtr[3 * id + 1];\n      dynTargetPtr[3 * j + 2] = targetPtr[3 * id + 2];\n    }\n\n    Eigen::Map<PointCloud> moving_(movingCopyPtr, 3, numMovingVerts);\n    Eigen::Map<PointCloud> target_(dynTargetPtr, 3, numMovingVerts);\n\n    UmeyamaTransform transform = Eigen::umeyama(moving_, target_, false);\n\n    for(size_t j = 0; j < numMovingVerts; j++)\n    {\n      Eigen::Vector4f position(movingCopyPtr[3 * j + 0], movingCopyPtr[3 * j + 1], movingCopyPtr[3 * j + 2], 1);\n      Eigen::Vector4f transformedPosition = transform * position;\n      std::memcpy(movingCopyPtr + (3 * j), transformedPosition.data(), sizeof(float) * 3);\n    }\n\n    globalTransform = transform * globalTransform;\n\n    if(counter > prog)\n    {\n      progressInt = static_cast<int64_t>((static_cast<float>(counter) / iters) * 100.0f);\n      QString ss = QObject::tr(\"Performing Registration Iterations || %1% Completed\").arg(progressInt);\n      notifyStatusMessage(ss);\n      prog = prog + progIncrement;\n    }\n    counter++;\n  }\n\n  float* transformPtr = getDataContainerArray()\n                            ->getDataContainer(m_MovingVertexGeometry.getDataContainerName())\n                            ->getAttributeMatrix(m_TransformAttributeMatrixName)\n                            ->getAttributeArrayAs<DataArray<float>>(m_TransformArrayName)\n                            ->getPointer(0);\n\n  if(m_ApplyTransform)\n  {\n    for(size_t j = 0; j < numMovingVerts; j++)\n    {\n      Eigen::Vector4f position(movingPtr[3 * j + 0], movingPtr[3 * j + 1], movingPtr[3 * j + 2], 1);\n      Eigen::Vector4f transformedPosition = globalTransform * position;\n      std::memcpy(movingPtr + (3 * j), transformedPosition.data(), sizeof(float) * 3);\n    }\n  }\n\n  globalTransform.transposeInPlace();\n  std::memcpy(transformPtr, globalTransform.data(), sizeof(float) * 16);\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nAbstractFilter::Pointer IterativeClosestPoint::newFilterInstance(bool copyFilterParameters) const\n{\n  IterativeClosestPoint::Pointer filter = IterativeClosestPoint::New();\n  if(copyFilterParameters)\n  {\n    copyFilterParameterInstanceVariables(filter.get());\n  }\n  return filter;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString IterativeClosestPoint::getCompiledLibraryName() const\n{\n  return DREAM3DReviewConstants::DREAM3DReviewBaseName;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString IterativeClosestPoint::getBrandingString() const\n{\n  return \"DREAM3DReview\";\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString IterativeClosestPoint::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 IterativeClosestPoint::getGroupName() const\n{\n  return SIMPL::FilterGroups::ReconstructionFilters;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString IterativeClosestPoint::getSubGroupName() const\n{\n  return SIMPL::FilterSubGroups::AlignmentFilters;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString IterativeClosestPoint::getHumanLabel() const\n{\n  return \"Iterative Closest Point\";\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQUuid IterativeClosestPoint::getUuid() const\n{\n  return QUuid(\"{6c8fb24b-5b12-551c-ba6d-ae2fa7724764}\");\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nIterativeClosestPoint::Pointer IterativeClosestPoint::NullPointer()\n{\n  return Pointer(static_cast<Self*>(nullptr));\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nstd::shared_ptr<IterativeClosestPoint> IterativeClosestPoint::New()\n{\n  struct make_shared_enabler : public IterativeClosestPoint\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// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString IterativeClosestPoint::getNameOfClass() const\n{\n  return QString(\"IterativeClosestPoint\");\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString IterativeClosestPoint::ClassName()\n{\n  return QString(\"IterativeClosestPoint\");\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid IterativeClosestPoint::setMovingVertexGeometry(const DataArrayPath& value)\n{\n  m_MovingVertexGeometry = value;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nDataArrayPath IterativeClosestPoint::getMovingVertexGeometry() const\n{\n  return m_MovingVertexGeometry;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid IterativeClosestPoint::setTargetVertexGeometry(const DataArrayPath& value)\n{\n  m_TargetVertexGeometry = value;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nDataArrayPath IterativeClosestPoint::getTargetVertexGeometry() const\n{\n  return m_TargetVertexGeometry;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid IterativeClosestPoint::setIterations(const int& value)\n{\n  m_Iterations = value;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nint IterativeClosestPoint::getIterations() const\n{\n  return m_Iterations;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid IterativeClosestPoint::setApplyTransform(const bool& value)\n{\n  m_ApplyTransform = value;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nbool IterativeClosestPoint::getApplyTransform() const\n{\n  return m_ApplyTransform;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid IterativeClosestPoint::setTransformAttributeMatrixName(const QString& value)\n{\n  m_TransformAttributeMatrixName = value;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString IterativeClosestPoint::getTransformAttributeMatrixName() const\n{\n  return m_TransformAttributeMatrixName;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid IterativeClosestPoint::setTransformArrayName(const QString& value)\n{\n  m_TransformArrayName = value;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString IterativeClosestPoint::getTransformArrayName() const\n{\n  return m_TransformArrayName;\n}\n", "meta": {"hexsha": "1d71593f89dff0c9a0ff97767e22d20ca809d896", "size": 15893, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DREAM3DReviewFilters/IterativeClosestPoint.cpp", "max_stars_repo_name": "cartercocke/DREAM3DReview", "max_stars_repo_head_hexsha": "1255efdf682ca4fe79b663cfd5a62398da27ea3f", "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/IterativeClosestPoint.cpp", "max_issues_repo_name": "cartercocke/DREAM3DReview", "max_issues_repo_head_hexsha": "1255efdf682ca4fe79b663cfd5a62398da27ea3f", "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/IterativeClosestPoint.cpp", "max_forks_repo_name": "cartercocke/DREAM3DReview", "max_forks_repo_head_hexsha": "1255efdf682ca4fe79b663cfd5a62398da27ea3f", "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": 34.7008733624, "max_line_length": 178, "alphanum_fraction": 0.5082111621, "num_tokens": 2983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.26923434131207413}}
{"text": "#include \"drake/solvers/moby_lcp_solver.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <functional>\n#include <iostream>\n#include <limits>\n#include <memory>\n#include <sstream>\n#include <stdexcept>\n#include <vector>\n\n#include <Eigen/LU>\n#include <Eigen/SparseCore>\n#include <Eigen/SparseLU>\n\n#include \"drake/common/autodiff.h\"\n#include \"drake/common/drake_assert.h\"\n#include \"drake/common/never_destroyed.h\"\n#include \"drake/common/text_logging.h\"\n\nnamespace drake {\nnamespace solvers {\n\nnamespace {\n\ntemplate <typename Scalar>\nbool CheckLemkeTrivial(int n, const Scalar& zero_tol, const VectorX<Scalar>& q,\n                       VectorX<Scalar>* z) {\n  // see whether trivial solution exists\n  if (q.minCoeff() > -zero_tol) {\n    z->resize(n);\n    z->fill(0);\n    return true;\n  }\n\n  return false;\n}\n\n// AutoDiff-supported linear system solver for performing principle pivoting\n// transformations. The matrix is supposed to be a linear basis, but it's\n// possible that the basis becomes degenerate (meaning that the matrix becomes\n// singular) due to accumulated roundoff error from pivoting. Recovering from\n// a degenerate basis is currently an open problem;\n// see http://www.optimization-online.org/DB_FILE/2011/03/2948.pdf, for\n// example. The caller would ideally terminate at this point, but\n// compilation of householderQr().rank() with AutoDiff currently generates\n// template errors. Continuing on blindly means that the calling pivoting\n// algorithm might continue on for some time.\ntemplate <class T>\nVectorX<T> LinearSolve(const MatrixX<T>& M, const VectorX<T>& b) {\n  // Special case necessary because Eigen doesn't always handle empty matrices\n  // properly.\n  if (M.rows() == 0) {\n    DRAKE_ASSERT(b.size() == 0);\n    return VectorX<T>(0);\n  }\n  return M.householderQr().solve(b);\n}\n\n// Linear system solver, specialized for double types. This method is faster\n// than the QR factorization necessary for AutoDiff support. It is assumed that\n// the matrix is full rank (see notes for generic LinearSolve() above).\ntemplate <>\nVectorX<double> LinearSolve(\n    const MatrixX<double>& M, const VectorX<double>& b) {\n  // Special case necessary because Eigen doesn't always handle empty matrices\n  // properly.\n  if (M.rows() == 0) {\n    DRAKE_ASSERT(b.size() == 0);\n    return VectorX<double>(0);\n  }\n  return M.partialPivLu().solve(b);\n}\n\n// Utility function for copying part of a matrix (designated by the indices\n// in rows and cols) from in to a target matrix, out. This template approach\n// allows selecting parts of both sparse and dense matrices for input; only\n// a dense matrix is returned.\ntemplate <typename Derived, typename T>\nvoid selectSubMat(const Eigen::MatrixBase<Derived>& in,\n                  const std::vector<unsigned>& rows,\n                  const std::vector<unsigned>& cols, MatrixX<T>* out) {\n  const int num_rows = rows.size();\n  const int num_cols = cols.size();\n  out->resize(num_rows, num_cols);\n\n  for (int i = 0; i < num_rows; i++) {\n    const auto row_in = in.row(rows[i]);\n    auto row_out = out->row(i);\n    for (int j = 0; j < num_cols; j++) {\n      row_out(j) = row_in(cols[j]);\n    }\n  }\n}\n\n// TODO(sammy-tri) this could also use a more efficient implementation.\ntemplate <typename T>\nvoid selectSubVec(const VectorX<T>& in,\n                  const std::vector<unsigned>& rows, VectorX<T>* out) {\n  const int num_rows = rows.size();\n  out->resize(num_rows);\n  for (int i = 0; i < num_rows; i++) {\n    (*out)(i) = in(rows[i]);\n  }\n}\n\ntemplate <typename Derived>\nEigen::SparseVector<double> makeSparseVector(\n    const Eigen::MatrixBase<Derived>& in) {\n  DRAKE_ASSERT(in.cols() == 1);\n  Eigen::SparseVector<double> out(in.rows());\n  for (int i = 0; i < in.rows(); i++) {\n    if (in(i) != 0.0) {\n      out.coeffRef(i) = in(i);\n    }\n  }\n  return out;\n}\n\ntemplate <typename Derived>\nEigen::Index minCoeffIdx(const Eigen::MatrixBase<Derived>& in) {\n  Eigen::Index idx;\n  in.minCoeff(&idx);\n  return idx;\n}\n\nconst double kSqrtEps = std::sqrt(std::numeric_limits<double>::epsilon());\n}  // anonymous namespace\n\ntemplate <typename T>\nvoid MobyLCPSolver<T>::SetLoggingEnabled(bool enabled) {\n  log_enabled_ = enabled; }\n\ntemplate <typename T>\nstd::ostream& MobyLCPSolver<T>::Log() const {\n  if (log_enabled_) {\n    return std::cerr;\n  }\n  return null_stream_;\n}\n\ntemplate <typename T>\nvoid MobyLCPSolver<T>::ClearIndexVectors() const {\n  // clear all vectors\n  all_.clear();\n  tlist_.clear();\n  bas_.clear();\n  nonbas_.clear();\n  j_.clear();\n}\n\ntemplate <>\nvoid MobyLCPSolver<Eigen::AutoDiffScalar<Vector1d>>::DoSolve(\n    const MathematicalProgram&, const Eigen::VectorXd&,\n    const SolverOptions&, MathematicalProgramResult*) const {\n  throw std::logic_error(\n      \"MobyLCPSolver cannot yet be used in a MathematicalProgram \"\n      \"while templatized as an AutoDiff\");\n}\n\n// TODO(edrumwri): Break the following code out into a special\n// MobyLcpMathematicalProgram class.\ntemplate <typename T>\nvoid MobyLCPSolver<T>::DoSolve(\n    const MathematicalProgram& prog,\n    const Eigen::VectorXd& initial_guess,\n    const SolverOptions& merged_options,\n    MathematicalProgramResult* result) const {\n  if (!prog.GetVariableScaling().empty()) {\n    static const logging::Warn log_once(\n      \"MobyLCPSolver doesn't support the feature of variable scaling.\");\n  }\n\n  // Moby doesn't use initial guess or the solver options.\n  unused(initial_guess);\n  unused(merged_options);\n\n  // Solve each individual LCP, writing the result back to the decision\n  // variables through the binding and returning true iff all LCPs are\n  // feasible.\n  //\n  // If any is infeasible, returns false and does not alter the decision\n  // variables.\n  //\n  // TODO(ggould-tri) This could also be solved by constructing a single large\n  // square matrix and vector, and then copying the elements of the individual\n  // Ms and qs into the appropriate places.  That would be equivalent to this\n  // implementation but might perform better if the solver were to parallelize\n  // internally.\n\n  const auto& bindings = prog.linear_complementarity_constraints();\n  Eigen::VectorXd x_sol(prog.num_vars());\n  for (const auto& binding : bindings) {\n    Eigen::VectorXd constraint_solution(binding.GetNumElements());\n    const std::shared_ptr<LinearComplementarityConstraint> constraint =\n        binding.evaluator();\n    bool solved = SolveLcpLemkeRegularized(\n        constraint->M(), constraint->q(), &constraint_solution);\n    if (!solved) {\n      result->set_solution_result(SolutionResult::kUnknownError);\n      return;\n    }\n    for (int i = 0; i < binding.evaluator()->num_vars(); ++i) {\n      const int variable_index =\n          prog.FindDecisionVariableIndex(binding.variables()(i));\n      x_sol(variable_index) = constraint_solution(i);\n    }\n  }\n  result->set_optimal_cost(0.0);\n  result->set_x_val(x_sol);\n  result->set_solution_result(SolutionResult::kSolutionFound);\n}\n\ntemplate <typename T>\nbool MobyLCPSolver<T>::SolveLcpFast(const MatrixX<T>& M,\n                                    const VectorX<T>& q, VectorX<T>* z,\n                                    const T& zero_tol) const {\n  using std::abs;\n\n  // Variables that will be reused multiple times, thus hopefully allowing\n  // Eigen to keep from freeing/reallocating memory repeatedly.\n  VectorX<T> zz, w, qbas;\n  MatrixX<T> Mmix, Msub;\n\n  const unsigned N = q.rows();\n  const unsigned UINF = std::numeric_limits<unsigned>::max();\n\n  if (M.rows() != N || M.cols() != N)\n    throw std::logic_error(\"M's dimensions do not match that of q.\");\n\n  Log() << \"MobyLCPSolver::SolveLcpFast() entered\" << std::endl;\n\n  // look for trivial solution\n  if (N == 0) {\n    Log() << \"MobyLCPSolver::SolveLcpFast() - empty problem\" << std::endl;\n    z->resize(0);\n    return true;\n  }\n\n  // set zero tolerance if necessary\n  T mod_zero_tol = zero_tol;\n  if (mod_zero_tol < 0)\n    mod_zero_tol = ComputeZeroTolerance(M);\n\n  // prepare to setup basic and nonbasic variable indices for z\n  nonbas_.clear();\n  bas_.clear();\n\n  // see whether to warm-start\n  if (z->size() == q.size()) {\n    Log() << \"MobyLCPSolver::SolveLcpFast() - warm starting activated\"\n          << std::endl;\n\n    for (unsigned i = 0; i < z->size(); i++) {\n      if (abs((*z)[i]) < mod_zero_tol) {\n        bas_.push_back(i);\n      } else {\n        nonbas_.push_back(i);\n      }\n    }\n\n    if (log_enabled_) {\n      std::ostringstream str;\n      str << \" -- non-basic indices:\";\n      for (unsigned i = 0; i < nonbas_.size(); i++) str << \" \" << nonbas_[i];\n      Log() << str.str() << std::endl;\n    }\n  } else {\n    // get minimum element of q (really w)\n    Eigen::Index minw;\n    const T minw_val = q.minCoeff(&minw);\n    if (minw_val > -mod_zero_tol) {\n      Log() << \"MobyLCPSolver::SolveLcpFast() - trivial solution found\"\n            << std::endl;\n      z->resize(N);\n      z->fill(0);\n      return true;\n    }\n\n    // setup basic and nonbasic variable indices\n    nonbas_.push_back(minw);\n    bas_.resize(N - 1);\n    for (unsigned i = 0, j = 0; i < N; i++) {\n      if (i != minw) {\n        bas_[j++] = i;\n      }\n    }\n  }\n\n  // Loop for the maximum number of pivots.\n  const unsigned MAX_PIV = 2 * N;\n  for (pivots_ = 1; pivots_ <= MAX_PIV; pivots_++) {\n    // select nonbasic indices\n    selectSubMat(M, nonbas_, nonbas_, &Msub);\n    selectSubMat(M, bas_, nonbas_, &Mmix);\n    selectSubVec(q, nonbas_, &zz);\n    selectSubVec(q, bas_, &qbas);\n    zz *= -1;\n\n    // Solve for nonbasic z.\n    zz = LinearSolve(Msub, zz.eval());\n\n    // Eigen doesn't handle empty matrices properly, which causes the code\n    // below to abort in the absence of the conditional.\n    unsigned minw;\n    if (Mmix.rows() == 0) {\n      w = VectorX<T>();\n      minw = UINF;\n    } else {\n      w = Mmix * zz;\n      w += qbas;\n      minw = minCoeffIdx(w);\n    }\n\n    // TODO(sammy-tri) this log can't print when minw is UINF.\n    // LOG() << \"MobyLCPSolver::SolveLcpFast() - minimum w after pivot: \"\n    // << _w[minw] << std::endl;\n\n    // if w >= 0, check whether any component of z < 0\n    if (minw == UINF || w[minw] > -mod_zero_tol) {\n      // find the (a) minimum of z\n      unsigned minz = (zz.rows() > 0) ? minCoeffIdx(zz) : UINF;\n      if (log_enabled_ && zz.rows() > 0) {\n        Log() << \"MobyLCPSolver::SolveLcpFast() - minimum z after pivot: \"\n              << zz[minz] << std::endl;\n      }\n      if (minz < UINF && zz[minz] < -mod_zero_tol) {\n        // get the original index and remove it from the nonbasic set\n        unsigned idx = nonbas_[minz];\n        nonbas_.erase(nonbas_.begin() + minz);\n\n        // move index to basic set and continue looping\n        bas_.push_back(idx);\n        std::sort(bas_.begin(), bas_.end());\n      } else {\n        // found the solution\n        z->resize(N);\n        z->fill(0);\n\n        // set values of z corresponding to _z\n        for (unsigned i = 0, j = 0; j < nonbas_.size(); i++, j++) {\n          (*z)[nonbas_[j]] = zz[i];\n        }\n\n        Log() << \"MobyLCPSolver::SolveLcpFast() - solution found!\" << std::endl;\n        return true;\n      }\n    } else {\n      Log() << \"(minimum w too negative)\" << std::endl;\n\n      // one or more components of w violating w >= 0\n      // move component of w from basic set to nonbasic set\n      unsigned idx = bas_[minw];\n      bas_.erase(bas_.begin() + minw);\n      nonbas_.push_back(idx);\n      std::sort(nonbas_.begin(), nonbas_.end());\n\n      // look whether any component of z needs to move to basic set\n      unsigned minz = (zz.rows() > 0) ? minCoeffIdx(zz) : UINF;\n      if (log_enabled_ && zz.rows() > 0) {\n        Log() << \"MobyLCPSolver::SolveLcpFast() - minimum z after pivot: \"\n              << zz[minz] << std::endl;\n      }\n      if (minz < UINF && zz[minz] < -mod_zero_tol) {\n        // move index to basic set and continue looping\n        unsigned k = nonbas_[minz];\n        Log() << \"MobyLCPSolver::SolveLcpFast() - moving index \" << k\n              << \" to basic set\" << std::endl;\n\n        nonbas_.erase(nonbas_.begin() + minz);\n        bas_.push_back(k);\n        std::sort(bas_.begin(), bas_.end());\n      }\n    }\n  }\n\n  Log() << \"MobyLCPSolver::SolveLcpFast() - maximum allowable pivots exceeded\"\n        << std::endl;\n\n  // if we're here, then the maximum number of pivots has been exceeded\n  z->setZero(N);\n  return false;\n}\n\ntemplate <typename T>\nbool MobyLCPSolver<T>::SolveLcpFastRegularized(const MatrixX<T>& M,\n                                               const VectorX<T>& q,\n                                               VectorX<T>* z, int min_exp,\n                                               unsigned step_exp, int max_exp,\n                                               const T& zero_tol) const {\n  Log() << \"MobyLCPSolver::SolveLcpFastRegularized() entered\" << std::endl;\n\n  // Variables that will be reused multiple times, thus hopefully allowing\n  // Eigen to keep from freeing/reallocating memory repeatedly.\n  VectorX<T> wx;\n  MatrixX<T> MM;\n\n  // look for fast exit\n  if (q.size() == 0) {\n    z->resize(0);\n    return true;\n  }\n\n  // copy MM\n  MM = M;\n\n  // A discourse on the zero tolerance in the context of regularization:\n  // The zero tolerance is used to determine when an element of w or z is\n  // effectively zero though its floating point value is negative. The question\n  // is whether the regularization process will change the zero tolerance\n  // necessary to solve the problem numerically. In such a case, the infinity\n  // norm of M would be small while the infinity norm of MM (regularized M)\n  // would be large. Consider the case of a symmetric, indefinite matrix with\n  // maximum and minimum eigenvalues of a and -a, respectively. The matrix could\n  // be made positive definite (and thereby guaranteed to possess a solution to\n  // the linear complementarity problem) by adding an identity matrix times\n  // (a+ε) to the LCP matrix, where ε > 0 (its magnitude will depend upon the\n  // magnitude of a). The infinity norm (and hence the zero tolerance) could\n  // then be expected to grow by a factor of approximately two during the\n  // regularization process. In other words, recomputing the zero tolerance\n  // for each regularization update to the LCP matrix appears wasteful. For\n  // this reason, we compute it only once below, but a practical effect is\n  // not discernible at this time.\n\n  // Assign value for zero tolerance, if necessary.\n  const T mod_zero_tol = (zero_tol > 0) ? zero_tol : ComputeZeroTolerance(M);\n\n  Log() << \" zero tolerance: \" << mod_zero_tol << std::endl;\n\n  // store the total pivots\n  unsigned total_piv = 0;\n\n  // try non-regularized version first\n  bool result = SolveLcpFast(MM, q, z, mod_zero_tol);\n  if (result) {\n    // verify that solution truly is a solution -- check z\n    if (z->minCoeff() >= -mod_zero_tol) {\n      // check w\n      wx = (M * (*z)) + q;\n      if (wx.minCoeff() >= -mod_zero_tol) {\n        // Check element-wise operation of z*wx.\n        wx = z->array() * wx.eval().array();\n        const T wx_min = wx.minCoeff();\n        const T wx_max = wx.maxCoeff();\n\n        if (wx_min >= -mod_zero_tol && wx_max < mod_zero_tol) {\n          Log() << \"  solved with no regularization necessary!\" << std::endl;\n          Log() << \"  pivots / total pivots: \" << pivots_ << \" \" << pivots_\n                << std::endl;\n          Log() << \"MobyLCPSolver::SolveLcpFastRegularized() exited\"\n                << std::endl;\n\n          return true;\n        } else {\n          Log() << \"MobyLCPSolver::SolveLcpFastRegularized() - \"\n                << \"'<w, z> not within tolerance(min value: \" << wx_min\n                << \" max value: \" << wx_max << \")\" << std::endl;\n        }\n      } else {\n        Log() << \"  MobyLCPSolver::SolveLcpFastRegularized() - \"\n              << \"'w' not solved to desired tolerance\" << std::endl;\n        Log() << \"  minimum w: \" << wx.minCoeff() << std::endl;\n      }\n    } else {\n      Log() << \"  MobyLCPSolver::SolveLcpFastRegularized() - \"\n            << \"'z' not solved to desired tolerance\" << std::endl;\n      Log() << \"  minimum z: \" << z->minCoeff() << std::endl;\n    }\n  } else {\n    Log() << \"  MobyLCPSolver::SolveLcpFastRegularized() \"\n          << \"- solver failed with zero regularization\" << std::endl;\n  }\n\n  // update the pivots\n  total_piv += pivots_;\n\n  // start the regularization process\n  int rf = min_exp;\n  while (rf < max_exp) {\n    // setup regularization factor\n    double lambda =\n        std::pow(static_cast<double>(10.0), static_cast<double>(rf));\n\n    Log() << \"  trying to solve LCP with regularization factor: \" << lambda\n          << std::endl;\n\n    // regularize M\n    MM = M;\n    for (unsigned i = 0; i < M.rows(); i++) {\n      MM(i, i) += lambda;\n    }\n\n    // try to solve the LCP\n    result = SolveLcpFast(MM, q, z, mod_zero_tol);\n\n    // update total pivots\n    total_piv += pivots_;\n\n    if (result) {\n      // verify that solution truly is a solution -- check z\n      if (z->minCoeff() > -mod_zero_tol) {\n        // check w\n        wx = (MM * (*z)) + q;\n        if (wx.minCoeff() > -mod_zero_tol) {\n          // Check element-wise operation of z*wx.\n          wx = z->array() * wx.eval().array();\n          const T wx_min = wx.minCoeff();\n          const T wx_max = wx.maxCoeff();\n\n          if (wx_min > -mod_zero_tol && wx_max < mod_zero_tol) {\n            Log() << \"  solved with regularization factor: \" << lambda\n                  << std::endl;\n            Log() << \"  pivots / total pivots: \" << pivots_ << \" \" << total_piv\n                  << std::endl;\n            Log() << \"MobyLCPSolver::SolveLcpFastRegularized() exited\"\n                  << std::endl;\n            pivots_ = total_piv;\n            return true;\n          } else {\n            Log() << \"MobyLCPSolver::SolveLcpFastRegularized() - \"\n                  << \"'<w, z> not within tolerance(min value: \" << wx_min\n                  << \" max value: \" << wx_max << \")\" << std::endl;\n          }\n        } else {\n          Log() << \"  MobyLCPSolver::SolveLcpFastRegularized() - \"\n                << \"'w' not solved to desired tolerance\" << std::endl;\n          Log() << \"  minimum w: \" << wx.minCoeff() << std::endl;\n        }\n      } else {\n        Log() << \"  MobyLCPSolver::SolveLcpFastRegularized() - \"\n              << \"'z' not solved to desired tolerance\" << std::endl;\n        Log() << \"  minimum z: \" << z->minCoeff() << std::endl;\n      }\n    }\n\n    // increase rf\n    rf += step_exp;\n  }\n\n  Log() << \"  unable to solve given any regularization!\" << std::endl;\n  Log() << \"MobyLCPSolver::SolveLcpFastRegularized() exited\" << std::endl;\n\n  // store total pivots\n  pivots_ = total_piv;\n\n  // still here?  failure...\n  return false;\n}\n\n// Retrieves the solution computed by Lemke's Algorithm.\n// T is irrelevant for this method (necessary only for the member function).\n// MatrixType allows both dense and sparse matrices to be used.\n// Scalar allows this method to be used for when the T is AutoDiffXd but\n// the caller wants to use sparse methods.\n// TODO(edrumwri): Address this kludge when calling sparse LCP solves from\n//                 MobyLCPSolver<AutoDiffXd> has been prevented.\ntemplate <typename T>\ntemplate <typename MatrixType, typename Scalar>\nvoid MobyLCPSolver<T>::FinishLemkeSolution(const MatrixType& M,\n                                           const VectorX<Scalar>& q,\n                                           const VectorX<Scalar>& x,\n                                           VectorX<Scalar>* z) const {\n  using std::abs;\n  using std::max;\n  std::vector<unsigned>::iterator iiter;\n  int idx;\n  for (idx = 0, iiter = bas_.begin(); iiter != bas_.end(); iiter++, idx++) {\n    (*z)(*iiter) = x(idx);\n  }\n\n  // TODO(sammy-tri) Is there a more efficient way to resize and\n  // preserve the data?\n  z->conservativeResize(q.size());\n\n  // check to see whether tolerances are satisfied\n  if (log_enabled_) {\n    VectorX<T> wl = (M * (*z)) + q;\n    const T minw = wl.minCoeff();\n    const T w_dot_z = abs(wl.dot(*z));\n    Log() << \"  z: \" << z << std::endl;\n    Log() << \"  w: \" << wl << std::endl;\n    Log() << \"  minimum w: \" << minw << std::endl;\n    Log() << \"  w'z: \" << w_dot_z << std::endl;\n  }\n}\n\ntemplate <typename T>\nbool MobyLCPSolver<T>::SolveLcpLemke(const MatrixX<T>& M,\n                                     const VectorX<T>& q, VectorX<T>* z,\n                                     const T& piv_tol,\n                                     const T& zero_tol) const {\n  using std::max;\n\n  // Variables that will be reused multiple times, thus hopefully allowing\n  // Eigen to keep from freeing/reallocating memory repeatedly.\n  VectorX<T> result, dj, dl, x, xj, Be, u, z0;\n  MatrixX<T> Bl, t1, t2;\n\n  if (log_enabled_) {\n    Log() << \"MobyLCPSolver::SolveLcpLemke() entered\" << std::endl;\n    Log() << \"  M: \" << std::endl << M;\n    Log() << \"  q: \" << q << std::endl;\n  }\n\n  const unsigned n = q.size();\n  const unsigned max_iter = std::min(unsigned{1000}, 50 * n);\n\n  if (M.rows() != n || M.cols() != n)\n    throw std::logic_error(\"M's dimensions do not match that of q.\");\n\n  // update the pivots\n  pivots_ = 0;\n\n  // look for immediate exit\n  if (n == 0) {\n    z->resize(0);\n    return true;\n  }\n\n  // come up with a sensible value for zero tolerance if none is given\n  T mod_zero_tol = zero_tol;\n  if (mod_zero_tol <= 0)\n    mod_zero_tol = ComputeZeroTolerance(M);\n\n  if (CheckLemkeTrivial(n, mod_zero_tol, q, z)) {\n    Log() << \" -- trivial solution found\" << std::endl;\n    Log() << \"MobyLCPSolver::SolveLcpLemke() exited\" << std::endl;\n    return true;\n  }\n\n  // Lemke's algorithm doesn't seem to like warmstarting\n  //\n  // TODO(sammy-tri) this is not present in the sparse solver, and it\n  // causes subtle dead code below.\n  z->fill(0);\n\n  // copy z to z0\n  z0 = *z;\n\n  ClearIndexVectors();\n\n  // initialize variables\n  z->resize(n * 2);\n  z->fill(0);\n  unsigned t = 2 * n;\n  unsigned entering = t;\n  unsigned leaving = 0;\n  for (unsigned i = 0; i < n; i++) {\n    all_.push_back(i);\n  }\n  unsigned lvindex;\n  unsigned idx;\n  std::vector<unsigned>::iterator iiter;\n\n  // determine initial basis\n  if (z0.size() != n) {\n    // setup the nonbasic indices\n    for (unsigned i = 0; i < n; i++) nonbas_.push_back(i);\n  } else {\n    for (unsigned i = 0; i < n; i++) {\n      if (z0[i] > 0) {\n        bas_.push_back(i);\n      } else {\n        nonbas_.push_back(i);\n      }\n    }\n  }\n\n  // determine initial values\n  if (!bas_.empty()) {\n    Log() << \"-- initial basis not empty (warmstarting)\" << std::endl;\n\n    // start from good initial basis\n    Bl.resize(n, n);\n    Bl.setIdentity();\n    Bl *= -1;\n\n    // select columns of M corresponding to z vars in the basis\n    selectSubMat(M, all_, bas_, &t1);\n\n    // select columns of I corresponding to z vars not in the basis\n    selectSubMat(Bl, all_, nonbas_, &t2);\n\n    // setup the basis matrix\n    Bl.resize(n, t1.cols() + t2.cols());\n    Bl.block(0, 0, t1.rows(), t1.cols()) = t1;\n    Bl.block(0, t1.cols(), t2.rows(), t2.cols()) = t2;\n\n    // Solve B*x = -q.\n    x = LinearSolve(Bl, q);\n  } else {\n    Log() << \"-- using basis of -1 (no warmstarting)\" << std::endl;\n\n    // use standard initial basis\n    Bl.resize(n, n);\n    Bl.setIdentity();\n    Bl *= -1;\n    x = q;\n  }\n\n  // check whether initial basis provides a solution\n  if (x.minCoeff() >= 0.0) {\n    Log() << \" -- initial basis provides a solution!\" << std::endl;\n    FinishLemkeSolution(M, q, x, z);\n    Log() << \"MobyLCPSolver::SolveLcpLemke() exited\" << std::endl;\n    return true;\n  }\n\n  // use a new pivot tolerance if necessary\n  const T naive_piv_tol = n * max(T(1), M.template lpNorm<Eigen::Infinity>()) *\n      std::numeric_limits<double>::epsilon();\n  const T mod_piv_tol = (piv_tol > 0) ? piv_tol : naive_piv_tol;\n\n  // determine initial leaving variable\n  Eigen::Index min_x;\n  const T min_x_val = x.topRows(n).minCoeff(&min_x);\n  const T tval = -min_x_val;\n  for (size_t i = 0; i < nonbas_.size(); i++) {\n    bas_.push_back(nonbas_[i] + n);\n  }\n  lvindex = min_x;\n  iiter = bas_.begin();\n  std::advance(iiter, lvindex);\n  leaving = *iiter;\n  Log() << \" -- x: \" << x << std::endl;\n  Log() << \" -- first pivot: leaving index=\" << lvindex\n        << \"  entering index=\" << entering << \" minimum value: \" << tval\n        << std::endl;\n\n  // pivot in the artificial variable\n  *iiter = t;  // replace w var with _z0 in basic indices\n  u.resize(n);\n  for (unsigned i = 0; i < n; i++) {\n    u[i] = (x[i] < 0) ? 1 : 0;\n  }\n  Be = (Bl * u) * -1;\n  u *= tval;\n  x += u;\n  x[lvindex] = tval;\n  Bl.col(lvindex) = Be;\n  Log() << \"  new q: \" << x << std::endl;\n\n  // main iterations begin here\n  for (pivots_ = 0; pivots_ < max_iter; pivots_++) {\n    if (log_enabled_) {\n      std::ostringstream basic;\n      for (unsigned i = 0; i < bas_.size(); i++) {\n        basic << \" \" << bas_[i];\n      }\n      Log() << \"basic variables:\" << basic.str() << std::endl;\n      Log() << \"leaving: \" << leaving << \" t:\" << t << std::endl;\n    }\n\n    // check whether done; if not, get new entering variable\n    if (leaving == t) {\n      Log() << \"-- solved LCP successfully!\" << std::endl;\n      FinishLemkeSolution(M, q, x, z);\n      Log() << \"MobyLCPSolver::SolveLcpLemke() exited\" << std::endl;\n      return true;\n    } else if (leaving < n) {\n      entering = n + leaving;\n      Be.resize(n);\n      Be.fill(0);\n      Be[leaving] = -1;\n    } else {\n      entering = leaving - n;\n      Be = M.col(entering);\n    }\n    dl = Be;\n\n    // See comments above on the possibility of this solve failing.\n    dl = LinearSolve(Bl, dl.eval());\n\n    // ** find new leaving variable\n    j_.clear();\n    for (unsigned i = 0; i < dl.size(); i++) {\n      if (dl[i] > mod_piv_tol) {\n        j_.push_back(i);\n      }\n    }\n\n    // check for no new pivots; ray termination\n    if (j_.empty()) {\n      Log()\n          << \"MobyLCPSolver::SolveLcpLemke() - no new pivots (ray termination)\"\n          << std::endl;\n      Log() << \"MobyLCPSolver::SolveLcpLemke() exiting\" << std::endl;\n      z->setZero(n);\n      return false;\n    }\n\n    if (log_enabled_) {\n      std::ostringstream j;\n      for (unsigned i = 0; i < j_.size(); i++) j << \" \" << j_[i];\n      Log() << \"d: \" << dl << std::endl;\n      Log() << \"j (before min ratio):\" << j.str() << std::endl;\n    }\n\n    // select elements j from x and d\n    selectSubVec(x, j_, &xj);\n    selectSubVec(dl, j_, &dj);\n\n    // compute minimal ratios x(j) + EPS_DOUBLE ./ d(j), d > 0\n    result.resize(xj.size());\n    result.fill(mod_zero_tol);\n    result = xj.eval().array() + result.array();\n    result = result.eval().array() / dj.array();\n    const T theta = result.minCoeff();\n\n    // NOTE: lexicographic ordering is not used here to prevent\n    // cycling (see [Cottle 1992], pp. 340-342). Cycling is indirectly prevented\n    // by (a) limiting the maximum number of pivots and (b) using\n    // regularized solvers, as necessary. In other words, cycling may cause\n    // solver to fail when the LCP is theoretically solvable, but wrapping the\n    // solver with regularization practically addresses the problem (albeit,\n    // at the cost of additional computation).\n\n    // find indices of minimal ratios, d> 0\n    //   divide _x(j) ./ d(j) -- remove elements above the minimum ratio\n    for (int i = 0; i < result.size(); i++) {\n      result(i) = xj(i) / dj(i);\n    }\n\n    for (iiter = j_.begin(), idx = 0; iiter != j_.end();) {\n      if (result[idx++] <= theta) {\n        iiter++;\n      } else {\n        iiter = j_.erase(iiter);\n      }\n    }\n    if (log_enabled_) {\n      std::ostringstream j;\n      for (unsigned i = 0; i < j_.size(); i++) {\n        j << \" \" << j_[i];\n      }\n      Log() << \"j (after min ratio):\" << j.str() << std::endl;\n    }\n\n    // if j is empty, then likely the zero tolerance is too low\n    if (j_.empty()) {\n      Log() << \"zero tolerance too low?\" << std::endl;\n      Log() << \"MobyLCPSolver::SolveLcpLemke() exited\" << std::endl;\n      z->setZero(n);\n      return false;\n    }\n\n    // check whether artificial index among these\n    tlist_.clear();\n    for (size_t i = 0; i < j_.size(); i++) {\n      tlist_.push_back(bas_[j_[i]]);\n    }\n    if (std::find(tlist_.begin(), tlist_.end(), t) != tlist_.end()) {\n      iiter = std::find(bas_.begin(), bas_.end(), t);\n      lvindex = iiter - bas_.begin();\n    } else {\n      // several indices pass the minimum ratio test, pick one randomly\n      //      lvindex = _j[rand() % _j.size()];\n      // NOTE: solver seems *much* more capable of solving when we pick the\n      // first\n      // element rather than picking a random one\n      lvindex = j_[0];\n    }\n\n    // set leaving = bas(lvindex)\n    iiter = bas_.begin();\n    std::advance(iiter, lvindex);\n    leaving = *iiter;\n\n    // ** perform pivot\n    const T ratio = x[lvindex] / dl[lvindex];\n    dl *= ratio;\n    x -= dl;\n    x[lvindex] = ratio;\n    Bl.col(lvindex) = Be;\n    *iiter = entering;\n    Log() << \" -- pivoting: leaving index=\" << lvindex\n          << \"  entering index=\" << entering << std::endl;\n  }\n\n  Log() << \" -- maximum number of iterations exceeded (n=\" << n\n        << \", max=\" << max_iter << \")\" << std::endl;\n  Log() << \"MobyLCPSolver::SolveLcpLemke() exited\" << std::endl;\n  z->setZero(n);\n  return false;\n}\n\ntemplate <class T>\nbool MobyLCPSolver<T>::SolveLcpLemkeRegularized(const MatrixX<T>& M,\n                                                const VectorX<T>& q,\n                                                VectorX<T>* z, int min_exp,\n                                                unsigned step_exp, int max_exp,\n                                                const T& piv_tol,\n                                                const T& zero_tol) const {\n  // Variables that will be reused multiple times, thus hopefully allowing\n  // Eigen to keep from freeing/reallocating memory repeatedly.\n  VectorX<T> wx;\n\n  Log() << \"MobyLCPSolver::SolveLcpLemkeRegularized() entered\" << std::endl;\n\n  // look for fast exit\n  if (q.size() == 0) {\n    z->resize(0);\n    return true;\n  }\n\n  // copy MM\n  MatrixX<T> MM = M;\n\n  // Assign value for zero tolerance, if necessary. See discussion in\n  // SolveLcpFastRegularized() to see why this tolerance is computed here once,\n  // rather than for each regularized version of M.\n  const T mod_zero_tol = (zero_tol > 0) ? zero_tol : ComputeZeroTolerance(M);\n\n  Log() << \" zero tolerance: \" << mod_zero_tol << std::endl;\n\n  // store the total pivots\n  unsigned total_piv = 0;\n\n  // try non-regularized version first\n  bool result = SolveLcpLemke(MM, q, z, piv_tol, mod_zero_tol);\n  if (result) {\n    // verify that solution truly is a solution -- check z\n    if (z->minCoeff() >= -mod_zero_tol) {\n      // check w\n      wx = (M * (*z)) + q;\n      if (wx.minCoeff() >= -mod_zero_tol) {\n        // Check element-wise operation of z*wx.\n        wx = z->array() * wx.eval().array();\n\n        const T wx_min = wx.minCoeff();\n        const T wx_max = wx.maxCoeff();\n        if (wx_min >= -mod_zero_tol && wx_max < mod_zero_tol) {\n          Log() << \"  solved with no regularization necessary!\" << std::endl;\n          Log() << \"MobyLCPSolver::SolveLcpLemkeRegularized() exited\"\n                << std::endl;\n\n          return true;\n        } else {\n          Log() << \"MobyLCPSolver::SolveLcpLemke() - \"\n                << \"'<w, z> not within tolerance(min value: \" << wx_min\n                << \" max value: \" << wx_max << \")\" << std::endl;\n        }\n      } else {\n        Log() << \"  MobyLCPSolver::SolveLcpLemke() - 'w' not solved to desired \"\n            \"tolerance\"\n              << std::endl;\n        Log() << \"  minimum w: \" << wx.minCoeff() << std::endl;\n      }\n    } else {\n      Log() << \"  MobyLCPSolver::SolveLcpLemke() - 'z' not solved to desired \"\n          \"tolerance\"\n            << std::endl;\n      Log() << \"  minimum z: \" << z->minCoeff() << std::endl;\n    }\n  }\n\n  // update the pivots\n  total_piv += pivots_;\n\n  // start the regularization process\n  int rf = min_exp;\n  while (rf < max_exp) {\n    // setup regularization factor\n    double lambda =\n        std::pow(static_cast<double>(10.0), static_cast<double>(rf));\n\n    Log() << \"  trying to solve LCP with regularization factor: \" << lambda\n          << std::endl;\n\n    // regularize M\n    MM = M;\n    for (unsigned i = 0; i < M.rows(); i++) {\n      MM(i, i) += lambda;\n    }\n\n    // try to solve the LCP\n    result = SolveLcpLemke(MM, q, z, piv_tol, mod_zero_tol);\n\n    // update total pivots\n    total_piv += pivots_;\n\n    if (result) {\n      // verify that solution truly is a solution -- check z\n      if (z->minCoeff() > -mod_zero_tol) {\n        // check w\n        wx = (MM * (*z)) + q;\n        if (wx.minCoeff() > -mod_zero_tol) {\n          // Check element-wise operation of z*wx.\n          wx = z->array() * wx.eval().array();\n\n          const T wx_min = wx.minCoeff();\n          const T wx_max = wx.maxCoeff();\n          if (wx_min > -mod_zero_tol && wx_max < mod_zero_tol) {\n            Log() << \"  solved with regularization factor: \" << lambda\n                  << std::endl;\n            Log() << \"MobyLCPSolver::SolveLcpLemkeRegularized() exited\"\n                  << std::endl;\n            pivots_ = total_piv;\n            return true;\n          } else {\n            Log() << \"MobyLCPSolver::SolveLcpLemke() - \"\n                  << \"'<w, z> not within tolerance(min value: \" << wx_min\n                  << \" max value: \" << wx_max << \")\" << std::endl;\n          }\n        } else {\n          Log() << \"  MobyLCPSolver::SolveLcpLemke() - 'w' not solved to \"\n              \"desired tolerance\"\n                << std::endl;\n          Log() << \"  minimum w: \" << wx.minCoeff() << std::endl;\n        }\n      } else {\n        Log() << \"  MobyLCPSolver::SolveLcpLemke() - 'z' not solved to desired \"\n            \"tolerance\"\n              << std::endl;\n        Log() << \"  minimum z: \" << z->minCoeff() << std::endl;\n      }\n    }\n\n    // increase rf\n    rf += step_exp;\n  }\n\n  Log() << \"  unable to solve given any regularization!\" << std::endl;\n  Log() << \"MobyLCPSolver::SolveLcpLemkeRegularized() exited\" << std::endl;\n\n  // store total pivots\n  pivots_ = total_piv;\n\n  // still here?  failure...\n  return false;\n}\n\ntemplate <typename T>\nMobyLCPSolver<T>::MobyLCPSolver()\n    : SolverBase(&id, &is_available, &is_enabled,\n                 &ProgramAttributesSatisfied) {}\n\ntemplate <typename T>\nMobyLCPSolver<T>::~MobyLCPSolver() = default;\n\nSolverId MobyLcpSolverId::id() {\n  static const never_destroyed<SolverId> singleton{\"Moby LCP\"};\n  return singleton.access();\n}\n\ntemplate <typename T>\nSolverId MobyLCPSolver<T>::id() {\n  return MobyLcpSolverId::id();\n}\n\ntemplate <typename T>\nbool MobyLCPSolver<T>::is_available() {\n  return true;\n}\n\ntemplate <typename T>\nbool MobyLCPSolver<T>::is_enabled() {\n  return true;\n}\n\ntemplate <typename T>\nbool MobyLCPSolver<T>::ProgramAttributesSatisfied(\n    const MathematicalProgram& prog) {\n  // This solver currently imposes restrictions that its problem:\n  //\n  // (1) Contains only linear complementarity constraints,\n  // (2) Has no element of any decision variable appear in more than one\n  //     constraint, and\n  // (3) Has every element of every decision variable in a constraint.\n  //\n  // Restriction 1 could reasonably be relaxed by reformulating other\n  // constraint types that can be expressed as LCPs (eg, convex QLPs),\n  // although this would also entail adding an output stage to convert\n  // the LCP results back to the desired form.  See eg. @RussTedrake on\n  // how to convert a linear equality constraint of n elements to an\n  // LCP of 2n elements.\n  //\n  // There is no obvious way to relax restriction 2.\n  //\n  // Restriction 3 could reasonably be relaxed to simply let unbound\n  // variables sit at 0.\n  if (prog.required_capabilities() != ProgramAttributes({\n        ProgramAttribute::kLinearComplementarityConstraint})) {\n    return false;\n  }\n\n  // Check that the available LCPs cover the program and no two LCPs cover the\n  // same variable.\n  const auto& bindings = prog.linear_complementarity_constraints();\n  for (int i = 0; i < static_cast<int>(prog.num_vars()); ++i) {\n    int coverings = 0;\n    for (const auto& binding : bindings) {\n      if (binding.ContainsVariable(prog.decision_variable(i))) {\n        coverings++;\n      }\n    }\n    if (coverings != 1) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\n// Instantiate templates.\ntemplate class MobyLCPSolver<double>;\ntemplate class MobyLCPSolver<Eigen::AutoDiffScalar<Vector1d>>;\n\n}  // namespace solvers\n}  // namespace drake\n", "meta": {"hexsha": "319c0278faf083f8757693a5114f50866a915891", "size": 36353, "ext": "cc", "lang": "C++", "max_stars_repo_path": "solvers/moby_lcp_solver.cc", "max_stars_repo_name": "RobotLocomotion/drake-python3.7", "max_stars_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:01:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T04:52:04.000Z", "max_issues_repo_path": "solvers/moby_lcp_solver.cc", "max_issues_repo_name": "RobotLocomotion/drake-python3.7", "max_issues_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solvers/moby_lcp_solver.cc", "max_forks_repo_name": "RobotLocomotion/drake-python3.7", "max_forks_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T12:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T12:05:39.000Z", "avg_line_length": 32.6915467626, "max_line_length": 80, "alphanum_fraction": 0.5914229912, "num_tokens": 10084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.26920285041118197}}
{"text": "/**\n  STD\n **/\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <cmath>\n\n\n/**\n  ROS RELATED\n **/\n#include <ros/ros.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/PointStamped.h>\n//#include <iiwa_msgs/JointPosition.h>\n#include <iiwa_msgs/JointPosition.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <visualization_msgs/MarkerArray.h>\n\n\n/**\n  PCL RELATED\n **/\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl/common/transforms.h>\n#include <pcl/common/pca.h>\n#include <pcl/common/common.h>\n#include <pcl/visualization/pcl_visualizer.h>\n#include <pcl/kdtree/kdtree_flann.h>\n#include <pcl/features/normal_3d.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include \"preprocessing.hpp\"\n#include <pcl/filters/extract_indices.h>\n\n/**\n  EIGEN RELATED\n **/\n\n#include <Eigen/Core>\n\nconst std::string BASE_LINK = \"iiwa_link_0\";\nconst std::string EE_LINK = \"iiwa_link_ee\";\n\n\nusing PointT = pcl::PointXYZ;\nusing PointCloudT = pcl::PointCloud<PointT>;\n\nvoid optimize_normals(PointCloudT::Ptr &trajectory, pcl::PointCloud<pcl::Normal>::Ptr &trajectory_normals) {\n  Eigen::Vector3f gt_normal(0, 0, -1);\n  for(unsigned int i = 0; i < trajectory->size(); i++) {\n    // go thru the elements in the trajectory and optimize the normals by looking at the previous and current normal\n    auto normal = trajectory_normals->points[i].getNormalVector3fMap();\n    if(normal[2] > 0) {\n      normal[0] *= -1;\n      normal[1] *= -1;\n      normal[2] *= -1;\n    }\n\n\n    // look at the normals around it\n    unsigned int first_point;\n    unsigned int second_point;\n    if(i == trajectory->size() - 1) {\n      first_point = i - 2;\n      second_point = i - 1;\n    }\n    else if (i == 0) {\n      first_point = i + 1;\n      second_point = i + 2;\n    }\n    else {\n      first_point = i - 1;\n      second_point = i + 1;\n    }\n\n    auto first_normal = trajectory_normals->points[first_point].getNormalVector3fMap();\n    auto second_normal = trajectory_normals->points[second_point].getNormalVector3fMap();\n    auto curr_normal = trajectory_normals->points[i].getNormalVector3fMap();\n    auto cos_theta = first_normal.dot(curr_normal) /\n        (first_normal.norm() * curr_normal.norm());\n    auto theta_between_first_curr =  acos(cos_theta) * 180.0 / M_PI;\n\n    cos_theta = first_normal.dot(second_normal) /\n        (first_normal.norm() * second_normal.norm());\n    auto theta_between_first_second =  acos(cos_theta) * 180.0 / M_PI;\n\n    if(theta_between_first_curr > 10.0) {\n      // then first and curr has a large difference\n      if(theta_between_first_second < 10.0) {\n        // then the curr point has an issue, lets change its normal\n        trajectory_normals->points[i]._Normal::normal_x = (first_normal.x() + second_normal.x()) / 2;\n        trajectory_normals->points[i]._Normal::normal_y = (first_normal.x() + second_normal.y()) / 2;\n        trajectory_normals->points[i]._Normal::normal_z = (first_normal.x() + second_normal.z()) / 2;\n      }\n\n    }\n\n  }\n}\n\nEigen::Quaternionf get_rotation(Eigen::Vector3f x, Eigen::Vector3f z){\n  if(z[2] > 0) {\n    z[2] = - z[2];\n    z[1] = - z[1];\n    z[0] = - z[0];\n  }\n\n  x = x.normalized();\n  z = z.normalized();\n\n  Eigen::Vector3f y = (z.cross(x)).normalized();\n\n\n  Eigen::Matrix3f pose_rotm;\n  pose_rotm << x, y, z;\n  Eigen::Quaternionf q(pose_rotm);\n  return q.normalized();\n}\n\nPointCloudT project_trajectory_onto_surface_method2(const PointCloudT::Ptr &trajectory, const PointCloudT::Ptr & arm_cloud, const pcl::PointCloud<pcl::Normal>::Ptr &trajectory_normals, pcl::PointCloud<pcl::Normal>::Ptr &new_normals){\n  // if two points in the trajectory are on almost the same direction, then we don't need to add all the points\n\n  PointCloudT new_trajectory;\n\n  Eigen::Vector3f prev_direction;\n  Eigen::Vector3f curr_direction;\n  bool defined_prev_dir = false;\n  for(size_t i = 0; i < trajectory->points.size() - 1; i ++) {\n    auto curr_point = trajectory->points[i];\n    auto curr_normal = trajectory_normals->points[i];\n    auto next_point = trajectory->points[i + 1];\n    curr_direction = next_point.getArray3fMap() - curr_point.getArray3fMap();\n    if(!defined_prev_dir) {\n      // add the first point of the trajectory\n      prev_direction = curr_direction;\n      new_trajectory.points.push_back(curr_point);\n      new_normals->points.push_back(curr_normal);\n      defined_prev_dir = true;\n    }\n    else{\n      auto cos_theta = curr_direction.dot(prev_direction) /\n          (curr_direction.norm() * prev_direction.norm());\n      auto theta =  acos(cos_theta) * 180.0 / M_PI;\n      if(theta > 30 && theta <= 40) {\n        // add the curr point to the trajectory\n        new_trajectory.points.push_back(curr_point);\n        new_normals->points.push_back(curr_normal);\n      }\n    }\n  }\n\n  // add the last point of the trajectory\n  new_trajectory.points.push_back(trajectory->points[trajectory->points.size()-1]);\n  new_normals->points.push_back(trajectory_normals->points[trajectory_normals->points.size() - 1]);\n  new_normals->height = 1;\n  new_normals->width = new_normals->points.size();\n  return new_trajectory;\n}\n\n\n/**\n * @brief find_trajectory_from_p_cloud in this function, the trajectory is created from the point cloud of the artery.\n * @param artery_cloud artery to create the trajectory from\n * @param transformed_cloud generated trajectory will be written here\n * @return\n */\nPointCloudT find_trajectory_from_p_cloud(const PointCloudT::Ptr &artery_cloud, PointCloudT::Ptr &transformed_cloud){\n\n  /**\n  find the PCA of the artery cloud and then project it to the\n  eigen vector space.\n  **/\n\n  // find the centroid of the original cloud\n  Eigen::Vector4f pcaCentroid;\n  pcl::compute3DCentroid(*artery_cloud, pcaCentroid);\n\n\n  pcl::PCA<PointT> cpca = new pcl::PCA<PointT>;\n  cpca.setInputCloud(artery_cloud);\n  cpca.project(*artery_cloud, *transformed_cloud); // original cloud is projected to the eigen vector space\n  Eigen::Matrix3f eigenVectorsPCA = cpca.getEigenVectors();\n  Eigen::Vector3f eigenValuesPCA = cpca.getEigenValues();\n\n  /**\n    Project the eigen vectors to the eigen space as well\n  **/\n\n  // rotation matrx to go to eigen vector space\n//  Eigen::Matrix4f tm = Eigen::Matrix4f::Identity();\n//  tm.block<3, 3>(0, 0) = eigenVectorsPCA.transpose();   //R.\n//  tm.block<3, 1>(0, 3) = -1.0f * (eigenVectorsPCA.transpose()) *(pcaCentroid.head<3>());//  -R*t\n\n  /**\n   X DIRECTION SHOWS THE LARGEST EIGEN VALUE DIRECTION\n   START FROM SMALLEST X VALUE AND GO USING SOME INTERVAL\n   next_point = curr_point + interval\n   **/\n\n   PointT min_p, max_p;\n   pcl::getMinMax3D(*transformed_cloud, min_p, max_p);\n\n   pcl::KdTreeFLANN<pcl::PointXYZ> kdtree;\n   kdtree.setInputCloud(transformed_cloud);\n   auto result_cloud = std::make_shared<pcl::PointCloud<pcl::PointXYZ>>();\n\n   // every 2 cm we look for the knn to find the point\n   for(float start = min_p.x; start < max_p.x; start += 0.02f) {\n\n     pcl::PointXYZ searchPoint;\n\n     searchPoint.x = start;\n     searchPoint.y = 0;\n     searchPoint.z = 0;\n\n     // K nearest neighbor search\n\n     int K = 5;\n\n     std::vector<int> pointIdxKNNSearch(K);\n     std::vector<float> pointKNNSquaredDistance(K);\n\n     /*std::cout << \"K nearest neighbor search at (\" << searchPoint.x\n               << \" \" << searchPoint.y\n               << \" \" << searchPoint.z\n               << \") with K=\" << K << std::endl;*/\n\n     if ( kdtree.nearestKSearch (searchPoint, K, pointIdxKNNSearch, pointKNNSquaredDistance) > 0 )\n     {\n       pcl::PointXYZ result_point;\n       result_point.x = 0;\n       result_point.y = 0;\n       result_point.z = 0;\n       for (std::size_t i = 0; i < pointIdxKNNSearch.size (); ++i) {\n         result_point.x += (*transformed_cloud)[ pointIdxKNNSearch[i] ].x;\n         result_point.y += (*transformed_cloud)[ pointIdxKNNSearch[i] ].y;\n         result_point.z += (*transformed_cloud)[ pointIdxKNNSearch[i] ].z;\n\n       }\n       result_point.x  = result_point.x / pointIdxKNNSearch.size ();\n       result_point.y  = result_point.y / pointIdxKNNSearch.size ();\n       result_point.z  = result_point.z / pointIdxKNNSearch.size ();\n       result_cloud->points.push_back(result_point);\n     }\n   }\n   // project the resulting trajectory to its old place\n   cpca.reconstruct(*result_cloud, *result_cloud);\n\n   // After the projection some points in the trajectory have exactly the same coordinates.\n   // Below code is to get rid of them\n   PointCloudT trajectory;\n   size_t ind = 0;\n   PointT prev_point;\n   for(const auto &point : result_cloud->points) {\n     if(ind == 0 ) {\n       trajectory.points.push_back(point);\n     }\n     else {\n       if(std::abs(prev_point.x - point.x) > 1e-4f || std::abs(prev_point.y - point.y) > 1e-4f || std::abs(prev_point.z - point.z) > 1e-4f) {\n         // this check is necessary to make sure not to add the same point two times.\n          trajectory.points.push_back(point);\n       }\n     }\n     prev_point = point;\n     ind  += 1;\n   }\n   return trajectory;\n}\n\nint main(int argc, char **argv)\n{\n\n  ros::init(argc, argv, \"find_trajectory\");\n  ros::NodeHandle nh;\n  std::string catkin_directory_path;\n  nh.getParam(\"trajectory_extraction/catkin_directory_path\", catkin_directory_path);\n  /**\n    READ THE ARM AND ARTERY POINT CLOUDS\n   **/\n\n  auto artery_cloud = std::make_shared<PointCloudT>();\n  auto artery_cloud_cam_base = std::make_shared<PointCloudT>();\n  auto arm_cloud = std::make_shared<PointCloudT>();\n  auto transformed_cloud = std::make_shared<PointCloudT>();\n\n  if (pcl::io::loadPCDFile<PointT> (catkin_directory_path + \"src/artery_downsampled_robot_base.pcd\", *artery_cloud) == -1) //* load the artery\n  {\n    PCL_ERROR (\"Couldn't read file\\n\");\n  }\n\n  if (pcl::io::loadPCDFile<PointT> (catkin_directory_path + \"src/arm_downsampled_robot_base.pcd\", *arm_cloud) == -1) //* load the arm\n  {\n    PCL_ERROR (\"Couldn't read file\\n\");\n  }\n\n  /**\n    FIND THE TRAJECTORY FROM THE ARTERY POINT CLOUD\n   **/\n\n   auto trajectory = std::make_shared<PointCloudT>(find_trajectory_from_p_cloud(artery_cloud, transformed_cloud));\n\n   /**\n     PROJECT THE TRAJECTORY TO THE ARM SURFACE AND RECOVER THE NORMAL DIRECTIONS TO DECIDE THE ORIENTATION OF THE PROBE\n    **/\n\n   // For now lets project it directly up\n\n   pcl::PointXYZ minPt, maxPt;\n   pcl::getMinMax3D (*arm_cloud, minPt, maxPt);\n   float max_z  = maxPt.z;\n\n   pcl::KdTreeFLANN<pcl::PointXYZ> kdtree_n;\n   kdtree_n.setInputCloud(arm_cloud);\n   auto trajectory_projected = std::make_shared<pcl::PointCloud<pcl::PointXYZ>>();\n\n   auto indices_to_extract = pcl::make_shared<std::vector<int>>();\n\n   std::vector<geometry_msgs::PoseStamped> poses;\n   PointT prev_point;\n   PointT first_point;\n   first_point.x = trajectory->points[0].x;\n   first_point.y = trajectory->points[0].y;\n   first_point.z = max_z;\n\n\n   int K_1 = 2;\n   std::vector<int> pointIdxKNNSearch_1(K_1);\n   std::vector<float> pointKNNSquaredDistance_1(K_1);\n\n   size_t num_neighbors_1 = kdtree_n.nearestKSearch (first_point, K_1, pointIdxKNNSearch_1, pointKNNSquaredDistance_1);\n   max_z = (*arm_cloud)[ std::size_t(pointIdxKNNSearch_1[0])].z;\n\n   for(const auto &point : *trajectory) {\n     PointT searchPoint;\n     int K = 5;\n     searchPoint.x = point.x;\n     searchPoint.y = point.y;\n     searchPoint.z = max_z;\n     std::vector<int> pointIdxKNNSearch(K);\n     std::vector<float> pointKNNSquaredDistance(K);\n\n     size_t num_neighbors = kdtree_n.nearestKSearch (searchPoint, K, pointIdxKNNSearch, pointKNNSquaredDistance);\n     //std::cout << num_neighbors << std::endl;\n\n     if ( num_neighbors > 0 )\n     {\n       auto avg_depth = 0.0f;\n       for(int ind : pointIdxKNNSearch) {\n         avg_depth += (*arm_cloud)[ std::size_t(ind)].z;\n       }\n       avg_depth /= num_neighbors;\n       auto inner_circle_avg_depth = 0.0f;\n       auto variance = 0.002f;\n       unsigned int inner_circle_count = 0;\n       for(int ind : pointIdxKNNSearch) {\n         if(std::abs((*arm_cloud)[ std::size_t(ind)].z - avg_depth) < variance) {\n           inner_circle_avg_depth += (*arm_cloud)[ std::size_t(ind)].z;\n           inner_circle_count += 1;\n         }\n       }\n       if(inner_circle_count == 0) {\n         inner_circle_avg_depth = avg_depth;\n       }\n       else{\n         inner_circle_avg_depth /= inner_circle_count;\n       }\n       PointT new_point;\n       (*arm_cloud)[ std::size_t(0) ].x = searchPoint.x;\n       (*arm_cloud)[ std::size_t(0) ].y = searchPoint.y;\n       (*arm_cloud)[ std::size_t(0) ].z = inner_circle_avg_depth;\n       trajectory_projected->points.push_back((*arm_cloud)[ std::size_t(0)]);\n     }\n   }\n\n\n   /**\n     FIND THE NORMAL DIRECTION OF THE TRAJECTORY POINTS AND WRITE THEM INTO A TEXT FILE TO USE TO MOVE THE ROBOT\n   **/\n\n\n   // Create the normal estimation class, and pass the input dataset to it\n   pcl::NormalEstimation<PointT, pcl::Normal> ne;\n   ne.setInputCloud (trajectory_projected);\n\n   // Pass the original data (before downsampling) as the search surface\n   ne.setSearchSurface (arm_cloud);\n\n   // Create an empty kdtree representation, and pass it to the normal estimation object.\n   // Its content will be filled inside the object, based on the given input dataset (as no other search surface is given).\n   pcl::search::KdTree<PointT>::Ptr tree (new pcl::search::KdTree<PointT> ());\n   ne.setSearchMethod (tree);\n\n   // Output datasets\n   pcl::PointCloud<pcl::Normal>::Ptr trajectory_normals (new pcl::PointCloud<pcl::Normal>);\n\n   // Use all neighbors in a sphere of radius 2cm\n   // TODO can be also 3 cm\n   ne.setRadiusSearch (0.03);\n\n   // Compute the features\n   ne.compute (*trajectory_normals);\n\n   // std::cout << trajectory_projected->points.size() << std::endl;\n   // std::cout << trajectory_normals->points.size() << std::endl;\n\n   optimize_normals(trajectory_projected, trajectory_normals);\n\n//   pcl::PointCloud<pcl::Normal>::Ptr new_normals (new pcl::PointCloud<pcl::Normal>);\n\n//   trajectory_projected = std::make_shared<PointCloudT>(project_trajectory_onto_surface_method2(trajectory_projected, arm_cloud, trajectory_normals, new_normals));\n//   trajectory_normals = new_normals;\n\n   // std::cout << trajectory_projected->points.size() << std::endl;\n   // std::cout << trajectory_normals->points.size() << std::endl;\n\n//   for(auto &point : trajectory_normals->points) {\n//     point._Normal::normal_x *= -1;\n//     point._Normal::normal_y *= -1;\n//     point._Normal::normal_z *= -1;\n//   }\n\n   // visualize normals\n   pcl::visualization::PCLVisualizer viewer(\"PCL Viewer\");\n   viewer.setBackgroundColor (1, 1, 1);\n   pcl::visualization::PointCloudColorHandlerCustom<PointT> arm_handler(arm_cloud, 0, 0, 255);\n   viewer.addPointCloud(arm_cloud, arm_handler, \"trajectory_cloud\");\n   viewer.addPointCloudNormals<pcl::PointXYZ,pcl::Normal>(trajectory_projected, trajectory_normals, 1, 0.03f, \"normals\");\n   viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_COLOR, 1.0, 0, 0, \"normals\");\n   viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_LINE_WIDTH, 3, \"normals\");\n   viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 5, \"trajectory_cloud\");\n\n\n\n   while (!viewer.wasStopped ())\n   {\n     viewer.spinOnce ();\n   }\n\n\n   /**\n     FIND THE POSES\n   **/\n\n   ofstream myfile (catkin_directory_path + \"src/artery_in_robot_base.txt\");\n   if (!myfile.is_open()) {\n    std::cout << \"ERROR\" << std::endl;\n   }\n\n   for(size_t i = 1; i < trajectory_projected->size(); i++) {\n     const auto &prev_point = trajectory_projected->points[i-1];\n     const auto &curr_point = trajectory_projected->points[i];\n\n     Eigen::Vector3f direction = curr_point.getArray3fMap() - prev_point.getArray3fMap();\n     Eigen::Quaternionf q = get_rotation(direction, trajectory_normals->points[i].getNormalVector3fMap());\n     myfile << prev_point.x << \" \" << prev_point.y << \" \" << prev_point.z << \" \" << q.x() << \" \" << q.y() << \" \" << q.z() << \" \" << q.w() << \"\\n\";\n   }\n\n   myfile.close();\n\n   // Extract inliers\n   pcl::ExtractIndices<PointT> extract;\n   extract.setInputCloud(arm_cloud);\n   extract.setIndices(indices_to_extract);\n   extract.setNegative(true);     // Extract the inliers\n   extract.filter(*arm_cloud); // cloud_inliers contains the plane\n\n  return 0;\n}\n", "meta": {"hexsha": "71de5b9313090cc53cbfad75a98e46cf2eb77ed8", "size": 16218, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "shape_registration/src/utils/find_pca_of_artery.cpp", "max_stars_repo_name": "NehilDanis/markerless_motion_capture_for_RUSS", "max_stars_repo_head_hexsha": "30f66cea723181f122f15ff861f49d29c8559c95", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "shape_registration/src/utils/find_pca_of_artery.cpp", "max_issues_repo_name": "NehilDanis/markerless_motion_capture_for_RUSS", "max_issues_repo_head_hexsha": "30f66cea723181f122f15ff861f49d29c8559c95", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "shape_registration/src/utils/find_pca_of_artery.cpp", "max_forks_repo_name": "NehilDanis/markerless_motion_capture_for_RUSS", "max_forks_repo_head_hexsha": "30f66cea723181f122f15ff861f49d29c8559c95", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-10-04T13:33:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T13:54:18.000Z", "avg_line_length": 34.2875264271, "max_line_length": 233, "alphanum_fraction": 0.6764705882, "num_tokens": 4315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.26920284381460396}}
{"text": "// Copyright András Vukics 2006–2020. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt)\n#include \"BinarySystem.h\"\n\n#include \"DensityOperator.h\"\n#include \"Interaction.h\"\n#include \"StateVector.h\"\n\n#include \"Algorithm.h\"\n#include \"SliceIterator.tcc\"\n\n#include \"BlitzTiny.h\"\n\n#include <boost/range/algorithm/copy.hpp>\n#include <boost/range/algorithm/for_each.hpp>\n#include <boost/range/algorithm_ext/for_each.hpp>\n\n\nusing composite::SubSystemFree;\n\n\nusing namespace structure;\n\nusing cppqedutils::sliceiterator::fullRange;\n\n\nnamespace {\n\n#include \"details_BinaryHelper.h\"\n\n}\n\n\n//////////\n//      //\n// Base //\n//      //\n//////////\n\n\nbinary::Base::Base(InteractionPtr ia)\n  : QuantumSystem<2>(Dimensions(ia->getFrees()[0]->getDimension(),ia->getFrees()[1]->getDimension())),\n    free0_(ia->getFrees()[0]), free1_(ia->getFrees()[1]), ia_(ia)\n{\n} \n\n\ndouble binary::Base::highestFrequency_v() const\n{\n  using std::max;\n  return max(ia_.get()->highestFrequency(),max(free0_.get()->highestFrequency(),free1_.get()->highestFrequency()));\n}\n\n\nstd::ostream& binary::Base::streamParameters_v(std::ostream& os) const\n{\n  using namespace std;\n  os<<\"Binary System\\nDimensions: \"<<getDimensions()<<\". Total: \"<<getTotalDimension()\n    <<\"\\n\\nSubsystem Nr. 0\\n\";     free0_.get()->streamParameters(os);\n  os<<    \"Subsystem Nr. 1\\n\";     free1_.get()->streamParameters(os);\n  os<<\"0 - 1 - Interaction\\n\";\n  return ia_.get()->streamParameters(os);\n}\n\n\n\n#define SUCCESSIVE_Ranges(f0,f1,ia) ptrdiff_t l=-1, u;  \\\n  if ((u=l+free0_.nAvr<LA_Av>())>l) {                          \\\n    PROCESS_Range( averages(blitz::Range(l+1,u)) , f0)  \\\n  }                                                     \\\n  if ((l=u+free1_.nAvr<LA_Av>())>u) {                          \\\n    PROCESS_Range( averages(blitz::Range(u+1,l)) , f1)  \\\n  }                                                     \\\n  if ((u=l+ia_.nAvr<LA_Av>())>l) {                             \\\n    PROCESS_Range( averages(blitz::Range(l+1,u)) , ia)  \\\n  }                                                     \\\n\n\nvoid binary::Base::process_v(Averages& averages) const\n{\n#define PROCESS_Range(av,ss) Averages temp(av); ss.process(temp);\n  \n  SUCCESSIVE_Ranges(free0_,free1_,ia_) ;\n  \n#undef  PROCESS_Range\n  \n}\n\n\nstd::ostream& binary::Base::stream_v(const Averages& averages, std::ostream& os, int precision) const\n{\n  const auto \n    av0 =free0_.getAv(),\n    av1 =free1_.getAv();\n  const auto\n    av01=   ia_.getAv();\n\n#define PROCESS_Range(av,ss) ss->stream(av,os,precision);\n  \n  SUCCESSIVE_Ranges(av0,av1,av01) ;\n  \n#undef  PROCESS_Range\n\n  return os;\n\n}\n\n#undef  SUCCESSIVE_Ranges\n\n////////////////////////////\n//                        //\n// Averaged - Liouvillean //\n//                        //\n////////////////////////////\n\n\nnamespace binary {\n\n// These possibilities get instantiated through compilation, so that explicit instantiation is not necessary here.\n  \ntemplate<LiouvilleanAveragedTag LA>\nstd::ostream& streamKey(std::ostream& os, size_t& i, const SSF& free0, const SSF& free1, const SSI& ia)\n{\n  os<<\"Binary system\\n\";\n  free0.streamKey<LA>(os,i);\n  free1.streamKey<LA>(os,i);\n  return ia.streamKey<LA>(os,i);\n}\ntemplate std::ostream& streamKey<LA_Li>(std::ostream& os, size_t& i, const SSF& free0, const SSF& free1, const SSI& ia);\ntemplate std::ostream& streamKey<LA_Av>(std::ostream& os, size_t& i, const SSF& free0, const SSF& free1, const SSI& ia);\n\n\ntemplate<LiouvilleanAveragedTag LA>\nsize_t nAvr(const SSF& free0, const SSF& free1, const SSI& ia)\n{\n  return free0.nAvr<LA>() + free1.nAvr<LA>() + ia.nAvr<LA>();\n}\ntemplate size_t nAvr< LA_Li >(const SSF& free0, const SSF& free1, const SSI& ia); // explicit instantiation\ntemplate size_t nAvr< LA_Av >(const SSF& free0, const SSF& free1, const SSI& ia); // explicit instantiation\n\n\ntemplate<LiouvilleanAveragedTag LA>\nconst Averages average(double t, const LazyDensityOperator& ldo, const SSF& free0, const SSF& free1, const SSI& ia, size_t numberAvr)\n{\n  using boost::copy;\n\n  const Averages\n    a0 {quantumdata::partialTrace<V0>(ldo,[&](const auto& m){return free0.average<LA>(t,m);})},\n    a1 {quantumdata::partialTrace<V1>(ldo,[&](const auto& m){return free1.average<LA>(t,m);})},\n    a01{ia.average<LA>(t,ldo)};\n\n  Averages a(numberAvr);\n\n  copy(a01,copy(a1,copy(a0,a.begin())));\n\n  return a;\n}\n\n\n} // binary\n\n\n///////////\n//       //\n// Exact //\n//       //\n///////////\n\n\n\nbool binary::Exact::applicableInMaster_v() const\n{\n  return free0_.applicableInMaster() && free1_.applicableInMaster() && ia_.applicableInMaster();\n}\n\n\n\nvoid binary::Exact::actWithU_v(double t, StateVectorLow& psi, double t0) const\n{\n  if (const auto ex=free0_.getEx()) for(auto& psiS : fullRange<V0>(psi)) ex->actWithU(t,psiS,t0);\n  if (const auto ex=free1_.getEx()) for(auto& psiS : fullRange<V1>(psi)) ex->actWithU(t,psiS,t0);\n\n  ia_.actWithU(t,psi,t0);\n\n}\n\n\n/////////////////\n//             //\n// Hamiltonian //\n//             //\n/////////////////\n\n\nvoid binary::Hamiltonian::addContribution_v(double t, const StateVectorLow& psi, StateVectorLow& dpsidt, double t0) const\n{\n  const auto lambda=[=](auto ha) {\n    return [=](const auto& psiS, auto& dpsidtS) {\n      ha->addContribution(t,psiS,dpsidtS,t0);\n    };\n  };\n  \n  if (const auto ha=free0_.getHa()) boost::range::for_each(fullRange<V0>(psi),fullRange<V0>(dpsidt),lambda(ha));\n  if (const auto ha=free1_.getHa()) boost::range::for_each(fullRange<V1>(psi),fullRange<V1>(dpsidt),lambda(ha));\n\n  ia_.addContribution(t,psi,dpsidt,t0);\n\n}\n\n\n/////////////////\n//             //\n// Liouvillean //\n//             //\n/////////////////\n\n\nvoid binary::Liouvillean::actWithJ_v(double t, StateVectorLow& psi, size_t i) const\n{\n  const auto\n    li0 =free0_.getLi(),\n    li1 =free1_.getLi();\n\n  size_t n=free0_.nAvr<LA_Li>();\n  if (li0 && i<n) {\n    for(auto& psiS : fullRange<V0>(psi)) li0->actWithJ(t,psiS,i);\n    return;\n  }\n\n  i-=n;  \n  if (li1 && i<(n=free1_.nAvr<LA_Li>())) {\n    for(auto& psiS : fullRange<V1>(psi)) li1->actWithJ(t,psiS,i);\n    return;\n  }\n\n  i-=n;\n  if (i<ia_.nAvr<LA_Li>())\n    ia_.actWithJ(t,psi,i);\n\n}\n\n\nvoid binary::Liouvillean::actWithSuperoperator_v(double t, const DensityOperatorLow& rho, DensityOperatorLow& drhodt, size_t i) const\n{\n  const auto lambda=[=,&i](auto li) {\n    return [=,&i](const auto& rhoS, auto& drhodtS) {\n      li->actWithSuperoperator(t,rhoS,drhodtS,i);\n    };\n  };\n\n  typedef tmptools::Vector<0,2> V0;\n  typedef tmptools::Vector<1,3> V1;\n\n  const auto\n    li0 =free0_.getLi(),\n    li1 =free1_.getLi();\n\n  size_t n=free0_.nAvr<LA_Li>();\n  if (li0 && i<n) {\n    boost::range::for_each(fullRange<V0>(rho),fullRange<V0>(drhodt),lambda(li0));\n    return;\n  }\n\n  i-=n;  \n  if (li1 && i<(n=free1_.nAvr<LA_Li>())) {\n    boost::range::for_each(fullRange<V1>(rho),fullRange<V1>(drhodt),lambda(li1));\n    return;\n  }\n\n  i-=n;\n  if (i<ia_.nAvr<LA_Li>())\n    ia_.actWithSuperoperator(t,rho,drhodt,i);\n\n}\n\n\n//////////////////\n//              //\n// Constructors //\n//              //\n//////////////////\n\n\n#define BASE_ctor(Class) Class##Base(getFree0(),getFree1(),getIA())\n\n\ntemplate<bool IS_EX, bool IS_HA, bool IS_LI>\nBinarySystem<IS_EX,IS_HA,IS_LI>::BinarySystem(binary::InteractionPtr ia) \n: binary::Base(ia),\n  BASE_ctor(Exact),\n  BASE_ctor(Hamiltonian),\n  BASE_ctor(Liouvillean)\n{\n} \n\n\n#undef BASE_ctor\n\n\nnamespace {\n\nusing structure::SystemCharacteristics;\n\nconst SystemCharacteristics querySystemCharacteristics(binary::InteractionPtr ia)\n{\n  using namespace structure;\n  \n  const QuantumSystemPtr<1>\n    free0=ia->getFrees()[0],\n    free1=ia->getFrees()[1];\n\n  return SystemCharacteristics{\n    std::dynamic_pointer_cast<const Exact<1>>(free0) || std::dynamic_pointer_cast<const Exact<1>>(free1) || std::dynamic_pointer_cast<const Exact<2>>(ia),\n    std::dynamic_pointer_cast<const Hamiltonian<1>>(free0) || std::dynamic_pointer_cast<const Hamiltonian<1>>(free1) || std::dynamic_pointer_cast<const Hamiltonian<2>>(ia),\n    std::dynamic_pointer_cast<const Liouvillean<1>>(free0) || std::dynamic_pointer_cast<const Liouvillean<1>>(free1) || std::dynamic_pointer_cast<const Liouvillean<2>>(ia)};\n}\n\n}\n\n\n#define DISPATCHER(EX,HA,LI) (all(querySystemCharacteristics(ia)==SystemCharacteristics{EX,HA,LI})) return std::make_shared<BinarySystem<EX,HA,LI> >(ia)\n\n\nconst binary::Ptr binary::make(InteractionPtr ia)\n{\n  if      DISPATCHER(true ,true ,true ) ;\n  else if DISPATCHER(true ,true ,false) ;\n  else if DISPATCHER(true ,false,true ) ;\n  else if DISPATCHER(true ,false,false) ;\n  else if DISPATCHER(false,true ,true ) ;\n  else if DISPATCHER(false,true ,false) ;\n  else if DISPATCHER(false,false,true ) ;\n  else return std::make_shared<BinarySystem<false,false,false> >(ia);\n}\n\n\n#undef DISPATCHER\n\ntemplate class BinarySystem<true ,true ,true >;\ntemplate class BinarySystem<true ,true ,false>;\ntemplate class BinarySystem<true ,false,true >;\ntemplate class BinarySystem<true ,false,false>;\ntemplate class BinarySystem<false,true ,true >;\ntemplate class BinarySystem<false,true ,false>;\ntemplate class BinarySystem<false,false,true >;\ntemplate class BinarySystem<false,false,false>;\n\n", "meta": {"hexsha": "be0319acac6f04b5ad5f466371e7d012ee7ac1f1", "size": 9099, "ext": "cc", "lang": "C++", "max_stars_repo_path": "CPPQEDcore/composites/BinarySystem.cc", "max_stars_repo_name": "vukics/cppqed", "max_stars_repo_head_hexsha": "a933375f53b982b14cebf7cb63de300996ddd00b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-02-21T14:00:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T15:12:11.000Z", "max_issues_repo_path": "CPPQEDcore/composites/BinarySystem.cc", "max_issues_repo_name": "vukics/cppqed", "max_issues_repo_head_hexsha": "a933375f53b982b14cebf7cb63de300996ddd00b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-04-14T11:18:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-04T20:11:23.000Z", "max_forks_repo_path": "CPPQEDcore/composites/BinarySystem.cc", "max_forks_repo_name": "vukics/cppqed", "max_forks_repo_head_hexsha": "a933375f53b982b14cebf7cb63de300996ddd00b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-25T10:16:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T18:29:01.000Z", "avg_line_length": 26.2219020173, "max_line_length": 173, "alphanum_fraction": 0.6431475986, "num_tokens": 2714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.26909803175274005}}
{"text": "//=============================================================================================================\r\n/**\r\n* @file     mnemath.cpp\r\n* @author   Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;\r\n*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>\r\n* @version  1.0\r\n* @date     July, 2012\r\n*\r\n* @section  LICENSE\r\n*\r\n* Copyright (C) 2012, Christoph Dinh and Matti Hamalainen. All rights reserved.\r\n*\r\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\r\n* the following conditions are met:\r\n*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the\r\n*       following disclaimer.\r\n*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\r\n*       the following disclaimer in the documentation and/or other materials provided with the distribution.\r\n*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used\r\n*       to endorse or promote products derived from this software without specific prior written permission.\r\n*\r\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\r\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\r\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\r\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\r\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r\n* POSSIBILITY OF SUCH DAMAGE.\r\n*\r\n*\r\n* @brief    Definition of the MNEMath Class.\r\n*\r\n*/\r\n\r\n//*************************************************************************************************************\r\n//=============================================================================================================\r\n// INCLUDES\r\n//=============================================================================================================\r\n\r\n#include \"mnemath.h\"\r\n\r\n\r\n//*************************************************************************************************************\r\n//=============================================================================================================\r\n// Eigen INCLUDES\r\n//=============================================================================================================\r\n\r\n#include <Eigen/Eigen>\r\n\r\n\r\n//*************************************************************************************************************\r\n//=============================================================================================================\r\n// Qt INCLUDES\r\n//=============================================================================================================\r\n\r\n#include <QDebug>\r\n\r\n\r\n//*************************************************************************************************************\r\n//=============================================================================================================\r\n// USED NAMESPACES\r\n//=============================================================================================================\r\n\r\nusing namespace UTILSLIB;\r\nusing namespace Eigen;\r\n\r\n\r\n//*************************************************************************************************************\r\n//=============================================================================================================\r\n// DEFINE MEMBER METHODS\r\n//=============================================================================================================\r\n\r\nVectorXd* MNEMath::combine_xyz(const VectorXd& vec)\r\n{\r\n    if (vec.size() % 3 != 0)\r\n    {\r\n        printf(\"Input must be a row or a column vector with 3N components\\n\");\r\n        return NULL;\r\n    }\r\n\r\n    MatrixXd tmp = MatrixXd(vec.transpose());\r\n    SparseMatrix<double>* s = make_block_diag(tmp,3);\r\n\r\n    SparseMatrix<double> sC = *s*s->transpose();\r\n    VectorXd* comb = new VectorXd(sC.rows());\r\n\r\n    for(qint32 i = 0; i < sC.rows(); ++i)\r\n        (*comb)[i] = sC.coeff(i,i);\r\n\r\n    delete s;\r\n    return comb;\r\n}\r\n\r\n\r\n//*************************************************************************************************************\r\n\r\ndouble MNEMath::getConditionNumber(const MatrixXd& A, VectorXd &s)\r\n{\r\n    JacobiSVD<MatrixXd> svd(A);\r\n    s = svd.singularValues();\r\n\r\n    double c = s.maxCoeff()/s.minCoeff();\r\n\r\n    return c;\r\n}\r\n\r\n\r\n//*************************************************************************************************************\r\n\r\ndouble MNEMath::getConditionSlope(const MatrixXd& A, VectorXd &s)\r\n{\r\n    JacobiSVD<MatrixXd> svd(A);\r\n    s = svd.singularValues();\r\n\r\n    double c = s.maxCoeff()/s.mean();\r\n\r\n    return c;\r\n}\r\n\r\n\r\n//*************************************************************************************************************\r\n\r\nvoid MNEMath::get_whitener(MatrixXd &A, bool pca, QString ch_type, VectorXd &eig, MatrixXd &eigvec)\r\n{\r\n    // whitening operator\r\n    SelfAdjointEigenSolver<MatrixXd> t_eigenSolver(A);//Can be used because, covariance matrices are self-adjoint matrices.\r\n\r\n    eig = t_eigenSolver.eigenvalues();\r\n    eigvec = t_eigenSolver.eigenvectors().transpose();\r\n\r\n    MNEMath::sort<double>(eig, eigvec, false);\r\n    qint32 rnk = MNEMath::rank(A);\r\n\r\n    for(qint32 i = 0; i < eig.size()-rnk; ++i)\r\n        eig(i) = 0;\r\n\r\n    printf(\"Setting small %s eigenvalues to zero.\\n\", ch_type.toUtf8().constData());\r\n    if (!pca)  // No PCA case.\r\n        printf(\"Not doing PCA for %s\\n\", ch_type.toUtf8().constData());\r\n    else\r\n    {\r\n        printf(\"Doing PCA for %s.\",ch_type.toUtf8().constData());\r\n        // This line will reduce the actual number of variables in data\r\n        // and leadfield to the true rank.\r\n        eigvec = eigvec.block(eigvec.rows()-rnk, 0, rnk, eigvec.cols());\r\n    }\r\n}\r\n\r\n\r\n//*************************************************************************************************************\r\n\r\nVectorXi MNEMath::intersect(const VectorXi &v1, const VectorXi &v2, VectorXi &idx_sel)\r\n{\r\n    std::vector<int> tmp;\r\n\r\n    std::vector< std::pair<int,int> > t_vecIntIdxValue;\r\n\r\n    //ToDo:Slow; map VectorXi to stl container\r\n    for(qint32 i = 0; i < v1.size(); ++i)\r\n        tmp.push_back(v1[i]);\r\n\r\n    std::vector<int>::iterator it;\r\n    for(qint32 i = 0; i < v2.size(); ++i)\r\n    {\r\n        it = std::search(tmp.begin(), tmp.end(), &v2[i], &v2[i]+1);\r\n        if(it != tmp.end())\r\n            t_vecIntIdxValue.push_back(std::pair<int,int>(v2[i], it-tmp.begin()));//Index and int value are swapped // to sort using the idx\r\n    }\r\n\r\n    std::sort(t_vecIntIdxValue.begin(), t_vecIntIdxValue.end(), MNEMath::compareIdxValuePairSmallerThan<int>);\r\n\r\n    VectorXi p_res(t_vecIntIdxValue.size());\r\n    idx_sel = VectorXi(t_vecIntIdxValue.size());\r\n\r\n    for(quint32 i = 0; i < t_vecIntIdxValue.size(); ++i)\r\n    {\r\n        p_res[i] = t_vecIntIdxValue[i].first;\r\n        idx_sel[i] = t_vecIntIdxValue[i].second;\r\n    }\r\n\r\n    return p_res;\r\n}\r\n\r\n\r\n//*************************************************************************************************************\r\n\r\n//    static inline MatrixXd extract_block_diag(MatrixXd& A, qint32 n)\r\n//    {\r\n\r\n\r\n//        //\r\n//        // Principal Investigators and Developers:\r\n//        // ** Richard M. Leahy, PhD, Signal & Image Processing Institute,\r\n//        //    University of Southern California, Los Angeles, CA\r\n//        // ** John C. Mosher, PhD, Biophysics Group,\r\n//        //    Los Alamos National Laboratory, Los Alamos, NM\r\n//        // ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,\r\n//        //    CNRS, Hopital de la Salpetriere, Paris, France\r\n//        //\r\n//        // Copyright (c) 2005 BrainStorm by the University of Southern California\r\n//        // This software distributed  under the terms of the GNU General Public License\r\n//        // as published by the Free Software Foundation. Further details on the GPL\r\n//        // license can be found at http://www.gnu.org/copyleft/gpl.html .\r\n//        //\r\n//        //FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\r\n//        // UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\r\n//        // WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\r\n//        // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\r\n//        // LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\r\n//        //\r\n//        // Author: John C. Mosher 1993 - 2004\r\n//        //\r\n//        //\r\n//        // Modifications for mne Matlab toolbox\r\n//        //\r\n//        //   Matti Hamalainen\r\n//        //   2006\r\n\r\n\r\n//          [mA,na] = size(A);\t\t% matrix always has na columns\r\n//          % how many entries in the first column?\r\n//          bdn = na/n;\t\t\t% number of blocks\r\n//          ma = mA/bdn;\t\t\t% rows in first block\r\n\r\n//          % blocks may themselves contain zero entries.  Build indexing as above\r\n//          tmp = reshape([1:(ma*bdn)]',ma,bdn);\r\n//          i = zeros(ma*n,bdn);\r\n//          for iblock = 1:n,\r\n//            i((iblock-1)*ma+[1:ma],:) = tmp;\r\n//          end\r\n\r\n//          i = i(:); \t\t\t% row indices foreach sparse bd\r\n\r\n\r\n//          j = [0:mA:(mA*(na-1))];\r\n//          j = j(ones(ma,1),:);\r\n//          j = j(:);\r\n\r\n//          i = i + j;\r\n\r\n//          bd = full(A(i)); \t% column vector\r\n//          bd = reshape(bd,ma,na);\t% full matrix\r\n\r\n//    }\r\n\r\n\r\n//*************************************************************************************************************\r\n\r\nbool MNEMath::issparse(VectorXd &v)\r\n{\r\n    //ToDo: Figure out how to accelerate MNEMath::issparse(VectorXd &v)\r\n\r\n    qint32 c = 0;\r\n    qint32 n = v.rows();\r\n    qint32 t = n/2;\r\n\r\n    for(qint32 i = 0; i < n; ++i)\r\n    {\r\n        if(v(i) == 0)\r\n            ++c;\r\n        if(c > t)\r\n            return true;\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\n\r\n//*************************************************************************************************************\r\n\r\nMatrixXd MNEMath::legendre(qint32 n, const VectorXd &X, QString normalize)\r\n{\r\n    MatrixXd y;\r\n\r\n    Q_UNUSED(y);\r\n\r\n    Q_UNUSED(n);\r\n    Q_UNUSED(X);\r\n    Q_UNUSED(normalize);\r\n\r\n    //ToDo\r\n\r\n    return y;\r\n}\r\n\r\n\r\n//*************************************************************************************************************\r\n\r\nSparseMatrix<double>* MNEMath::make_block_diag(const MatrixXd &A, qint32 n)\r\n{\r\n\r\n    qint32 ma = A.rows();\r\n    qint32 na = A.cols();\r\n    float bdn = ((float)na)/n;      // number of submatrices\r\n\r\n//    std::cout << std::endl << \"ma \" << ma << \" na \" << na << \" bdn \" << bdn << std::endl;\r\n\r\n    if(bdn - floor(bdn))\r\n    {\r\n        printf(\"Width of matrix must be even multiple of n\\n\");\r\n        return NULL;\r\n    }\r\n\r\n    typedef Eigen::Triplet<double> T;\r\n    std::vector<T> tripletList;\r\n    tripletList.reserve(bdn*ma*n);\r\n\r\n    qint32 current_col, current_row, i, r, c;\r\n    for(i = 0; i < bdn; ++i)\r\n    {\r\n        current_col = i * n;\r\n        current_row = i * ma;\r\n\r\n        for(r = 0; r < ma; ++r)\r\n            for(c = 0; c < n; ++c)\r\n                tripletList.push_back(T(r+current_row, c+current_col, A(r, c+current_col)));\r\n    }\r\n\r\n    SparseMatrix<double>* bd = new SparseMatrix<double>((int)floor((float)ma*bdn+0.5),na);\r\n//    SparseMatrix<double> p_Matrix(nrow, ncol);\r\n    bd->setFromTriplets(tripletList.begin(), tripletList.end());\r\n\r\n    return bd;\r\n}\r\n\r\n\r\n//*************************************************************************************************************\r\n\r\nint MNEMath::nchoose2(int n)\r\n{\r\n\r\n    //nchoosek(n, k) with k = 2, equals n*(n-1)*0.5\r\n\r\n    int t_iNumOfCombination = (int)(n*(n-1)*0.5);\r\n\r\n    return t_iNumOfCombination;\r\n}\r\n\r\n\r\n//*************************************************************************************************************\r\n\r\nqint32 MNEMath::rank(const MatrixXd& A, double tol)\r\n{\r\n    JacobiSVD<MatrixXd> t_svdA(A);//U and V are not computed\r\n    VectorXd s = t_svdA.singularValues();\r\n    double t_dMax = s.maxCoeff();\r\n    t_dMax *= tol;\r\n    qint32 sum = 0;\r\n    for(qint32 i = 0; i < s.size(); ++i)\r\n        sum += s[i] > t_dMax ? 1 : 0;\r\n    return sum;\r\n}\r\n\r\n\r\n//*************************************************************************************************************\r\n\r\nMatrixXd MNEMath::rescale(const MatrixXd &data, const RowVectorXf &times, QPair<QVariant,QVariant> baseline, QString mode)\r\n{\r\n    MatrixXd data_out = data;\r\n    QStringList valid_modes;\r\n    valid_modes << \"logratio\" << \"ratio\" << \"zscore\" << \"mean\" << \"percent\";\r\n    if(!valid_modes.contains(mode))\r\n    {\r\n        qWarning() << \"\\tWarning: mode should be any of : \" << valid_modes;\r\n        return data_out;\r\n    }\r\n    printf(\"\\tApplying baseline correction ... (mode: %s)\\n\", mode.toUtf8().constData());\r\n\r\n    qint32 imin = 0;\r\n    qint32 imax = times.size();\r\n\r\n    if(!baseline.first.isValid())\r\n        imin = 0;\r\n    else\r\n    {\r\n        float bmin = baseline.first.toFloat();\r\n        for(qint32 i = 0; i < times.size(); ++i)\r\n        {\r\n            if(times[i] >= bmin)\r\n            {\r\n                imin = i;\r\n                break;\r\n            }\r\n        }\r\n    }\r\n    if (!baseline.second.isValid())\r\n        imax = times.size();\r\n    else\r\n    {\r\n        float bmax = baseline.second.toFloat();\r\n        for(qint32 i = times.size()-1; i >= 0; --i)\r\n        {\r\n            if(times[i] <= bmax)\r\n            {\r\n                imax = i+1;\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    VectorXd mean = data_out.block(0, imin,data_out.rows(),imax-imin).rowwise().mean();\r\n    if(mode.compare(\"mean\") == 0)\r\n    {\r\n        data_out -= mean.rowwise().replicate(data.cols());\r\n    }\r\n    else if(mode.compare(\"logratio\") == 0)\r\n    {\r\n        for(qint32 i = 0; i < data_out.rows(); ++i)\r\n            for(qint32 j = 0; j < data_out.cols(); ++j)\r\n                data_out(i,j) = log10(data_out(i,j)/mean[i]); // a value of 1 means 10 times bigger\r\n    }\r\n    else if(mode.compare(\"ratio\") == 0)\r\n    {\r\n        data_out = data_out.cwiseQuotient(mean.rowwise().replicate(data_out.cols()));\r\n    }\r\n    else if(mode.compare(\"zscore\") == 0)\r\n    {\r\n        MatrixXd std_mat = data.block(0, imin, data.rows(), imax-imin) - mean.rowwise().replicate(imax-imin);\r\n        std_mat = std_mat.cwiseProduct(std_mat);\r\n        VectorXd std_v = std_mat.rowwise().mean();\r\n        for(qint32 i = 0; i < std_v.size(); ++i)\r\n            std_v[i] = sqrt(std_v[i] / (float)(imax-imin));\r\n\r\n        data_out -= mean.rowwise().replicate(data_out.cols());\r\n        data_out = data_out.cwiseQuotient(std_v.rowwise().replicate(data_out.cols()));\r\n    }\r\n    else if(mode.compare(\"percent\") == 0)\r\n    {\r\n        data_out -= mean.rowwise().replicate(data_out.cols());\r\n        data_out = data_out.cwiseQuotient(mean.rowwise().replicate(data_out.cols()));\r\n    }\r\n\r\n    return data_out;\r\n}\r\n\r\n//*************************************************************************************************************\r\n", "meta": {"hexsha": "2414de781a390bb5224a0ff2af7a3949358e8660", "size": 15370, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/utils/mnemath.cpp", "max_stars_repo_name": "MagCPP/mne-cpp", "max_stars_repo_head_hexsha": "05f634a8401b20226bd719254a5da227e67a379b", "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/mnemath.cpp", "max_issues_repo_name": "MagCPP/mne-cpp", "max_issues_repo_head_hexsha": "05f634a8401b20226bd719254a5da227e67a379b", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/mnemath.cpp", "max_forks_repo_name": "MagCPP/mne-cpp", "max_forks_repo_head_hexsha": "05f634a8401b20226bd719254a5da227e67a379b", "max_forks_repo_licenses": ["BSD-3-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.0913242009, "max_line_length": 141, "alphanum_fraction": 0.4614834092, "num_tokens": 3371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.26909803175274005}}
{"text": "/*********************************************************************\n* Software License Agreement (BSD License)\n*\n*  Copyright (c) 2014, 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 the 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: Caleb Voss */\n\n#include \"ompl/base/spaces/constraint/AtlasChart.h\"\n#include <boost/math/constants/constants.hpp>\n#include <eigen3/Eigen/Dense>\n\n/// AtlasChart::Halfspace\n\n/// Public\n\nompl::base::AtlasChart::Halfspace::Halfspace(const AtlasChart *owner, const AtlasChart *neighbor) : owner_(owner)\n{\n    // Project neighbor's chart center onto our chart.\n    Eigen::VectorXd u(owner_->k_);\n    owner_->psiInverse(*neighbor->getOrigin(), u);\n\n    // Compute the halfspace equation, which is the perpendicular bisector\n    // between 0 and u (plus 5% to reduce cracks, see Jaillet et al.).\n    setU(1.05 * u);\n}\n\nbool ompl::base::AtlasChart::Halfspace::contains(const Eigen::Ref<const Eigen::VectorXd> &v) const\n{\n    return v.dot(u_) <= rhs_;\n}\n\nvoid ompl::base::AtlasChart::Halfspace::checkNear(const Eigen::Ref<const Eigen::VectorXd> &v) const\n{\n    // Threshold is 10% of the distance from the boundary to the origin.\n    if (distanceToPoint(v) < 1.0 / 20)\n    {\n        Eigen::VectorXd x(owner_->n_);\n        owner_->psi(v, x);\n        complement_->expandToInclude(x);\n    }\n}\n\nbool ompl::base::AtlasChart::Halfspace::circleIntersect(const double r, Eigen::Ref<Eigen::VectorXd> v1,\n                                                        Eigen::Ref<Eigen::VectorXd> v2) const\n{\n    if (owner_->getManifoldDimension() != 2)\n        throw ompl::Exception(\"ompl::base::AtlasChart::Halfspace::circleIntersect() \"\n                              \"Only works on 2D manifolds.\");\n\n    // Check if there will be no solutions.\n    double discr = 4 * r * r - usqnorm_;\n    if (discr < 0)\n        return false;\n    discr = std::sqrt(discr);\n\n    // Compute the 2 solutions (possibly 1 repeated solution).\n    double unorm = std::sqrt(usqnorm_);\n    v1[0] = -u_[1] * discr;\n    v1[1] = u_[0] * discr;\n    v2 = -v1;\n    v1 += u_ * unorm;\n    v2 += u_ * unorm;\n    v1 /= 2 * unorm;\n    v2 /= 2 * unorm;\n\n    return true;\n}\n\n/// Public static\n\nvoid ompl::base::AtlasChart::Halfspace::intersect(const Halfspace &l1, const Halfspace &l2,\n                                                  Eigen::Ref<Eigen::VectorXd> out)\n{\n    if (l1.owner_ != l2.owner_)\n        throw ompl::Exception(\"Cannot intersect linear inequalities on different charts.\");\n    if (l1.owner_->getManifoldDimension() != 2)\n        throw ompl::Exception(\"AtlasChart::Halfspace::intersect() only works on 2D manifolds.\");\n\n    // Computer the intersection point of these lines.\n    Eigen::MatrixXd A(2, 2);\n    A.row(0) = l1.u_.transpose();\n    A.row(1) = l2.u_.transpose();\n    out[0] = l1.u_.squaredNorm();\n    out[1] = l2.u_.squaredNorm();\n    out = 0.5 * A.inverse() * out;\n}\n\n/// Private\n\nvoid ompl::base::AtlasChart::Halfspace::setU(const Eigen::Ref<const Eigen::VectorXd> &u)\n{\n    u_ = u;\n\n    // Precompute the squared norm of u.\n    usqnorm_ = u_.squaredNorm();\n\n    // Precompute the right-hand side of the linear inequality.\n    rhs_ = usqnorm_ / 2;\n}\n\ndouble ompl::base::AtlasChart::Halfspace::distanceToPoint(const Eigen::Ref<const Eigen::VectorXd> &v) const\n{\n    // Result is a scalar factor of u_.\n    return (0.5 - v.dot(u_)) / usqnorm_;\n}\n\nvoid ompl::base::AtlasChart::Halfspace::expandToInclude(const Eigen::Ref<const Eigen::VectorXd> &x)\n{\n    // Compute how far v = psiInverse(x) lies past the boundary, if at all.\n    Eigen::VectorXd v(owner_->k_);\n    owner_->psiInverse(x, v);\n    const double t = -distanceToPoint(v);\n\n    // Move u_ further out by twice that much.\n    if (t > 0)\n        setU((1 + 2 * t) * u_);\n}\n\n/// AtlasChart\n\n/// Public\n\nompl::base::AtlasChart::AtlasChart(const AtlasStateSpace *atlas, const AtlasStateSpace::StateType *state)\n  : constraint_(atlas->getConstraint().get())\n  , n_(atlas->getAmbientDimension())\n  , k_(atlas->getManifoldDimension())\n  , state_(state)\n  , bigPhi_([&]() -> const Eigen::MatrixXd {\n      Eigen::MatrixXd j(n_ - k_, n_);\n      constraint_->jacobian(*state_, j);\n\n      Eigen::FullPivLU<Eigen::MatrixXd> decomp = j.fullPivLu();\n      if (!decomp.isSurjective())\n          throw ompl::Exception(\"Cannot compute full-rank tangent space.\");\n\n      // Compute the null space and orthonormalize, which is a basis for the tangent space.\n      return decomp.kernel().householderQr().householderQ() * Eigen::MatrixXd::Identity(n_, k_);\n  }())\n  , radius_(atlas->getRho_s())\n{\n}\n\nompl::base::AtlasChart::~AtlasChart()\n{\n    clear();\n}\n\nvoid ompl::base::AtlasChart::clear()\n{\n    for (auto h : polytope_)\n        delete h;\n\n    polytope_.clear();\n}\n\nvoid ompl::base::AtlasChart::phi(const Eigen::Ref<const Eigen::VectorXd> &u, Eigen::Ref<Eigen::VectorXd> out) const\n{\n    out = *state_ + bigPhi_ * u;\n}\n\nbool ompl::base::AtlasChart::psi(const Eigen::Ref<const Eigen::VectorXd> &u, Eigen::Ref<Eigen::VectorXd> out) const\n{\n    // Initial guess for Newton's method\n    Eigen::VectorXd x0(n_);\n    phi(u, x0);\n\n    // Newton-Raphson to solve Ax = b\n    unsigned int iter = 0;\n    double norm = 0;\n    Eigen::MatrixXd A(n_, n_);\n    Eigen::VectorXd b(n_);\n\n    const double tolerance = constraint_->getTolerance();\n    const double squaredTolerance = tolerance * tolerance;\n\n    // Initialize output to initial guess\n    out = x0;\n\n    // Initialize A with orthonormal basis (constant)\n    A.block(n_ - k_, 0, k_, n_) = bigPhi_.transpose();\n\n    // Initialize b with initial f(out) = b\n    constraint_->function(out, b.head(n_ - k_));\n    b.tail(k_).setZero();\n\n    while ((norm = b.squaredNorm()) > squaredTolerance && iter++ < constraint_->getMaxIterations())\n    {\n        // Recompute the Jacobian at the new guess.\n        constraint_->jacobian(out, A.block(0, 0, n_ - k_, n_));\n\n        // Move in the direction that decreases F(out) and is perpendicular to\n        // the chart.\n        out -= A.partialPivLu().solve(b);\n\n        // Recompute b with new guess.\n        constraint_->function(out, b.head(n_ - k_));\n        b.tail(k_) = bigPhi_.transpose() * (out - x0);\n    }\n\n    return norm < squaredTolerance;\n}\n\nvoid ompl::base::AtlasChart::psiInverse(const Eigen::Ref<const Eigen::VectorXd> &x,\n                                        Eigen::Ref<Eigen::VectorXd> out) const\n{\n    out = bigPhi_.transpose() * (x - *state_);\n}\n\nbool ompl::base::AtlasChart::inPolytope(const Eigen::Ref<const Eigen::VectorXd> &u, const Halfspace *const ignore1,\n                                        const Halfspace *const ignore2) const\n{\n    if (u.norm() > radius_)\n        return false;\n\n    for (Halfspace *h : polytope_)\n    {\n        if (h == ignore1 || h == ignore2)\n            continue;\n\n        if (!h->contains(u))\n            return false;\n    }\n\n    return true;\n}\n\nvoid ompl::base::AtlasChart::borderCheck(const Eigen::Ref<const Eigen::VectorXd> &v) const\n{\n    for (Halfspace *h : polytope_)\n        h->checkNear(v);\n}\n\nconst ompl::base::AtlasChart *ompl::base::AtlasChart::owningNeighbor(const Eigen::Ref<const Eigen::VectorXd> &x) const\n{\n    Eigen::VectorXd projx(n_), proju(k_);\n    for (Halfspace *h : polytope_)\n    {\n        // Project onto the neighboring chart.\n        const AtlasChart *c = h->getComplement()->getOwner();\n        c->psiInverse(x, proju);\n        c->phi(proju, projx);\n\n        // Check if it's within the validity region and polytope boundary.\n        const bool withinTolerance = (projx - x).norm();\n        const bool inPolytope = c->inPolytope(proju);\n\n        if (withinTolerance && inPolytope)\n            return c;\n    }\n\n    return nullptr;\n}\n\nbool ompl::base::AtlasChart::toPolygon(std::vector<Eigen::VectorXd> &vertices) const\n{\n    if (k_ != 2)\n        throw ompl::Exception(\"AtlasChart::toPolygon() only works on 2D manifold/charts.\");\n\n    // Compile a list of all the vertices in P and all the times the border\n    // intersects the circle.\n    Eigen::VectorXd v(2);\n    Eigen::VectorXd intersection(n_);\n    vertices.clear();\n    for (std::size_t i = 0; i < polytope_.size(); i++)\n    {\n        for (std::size_t j = i + 1; j < polytope_.size(); j++)\n        {\n            // Check if intersection of the lines is a part of the boundary and\n            // within the circle.\n            Halfspace::intersect(*polytope_[i], *polytope_[j], v);\n            phi(v, intersection);\n            if (inPolytope(v, polytope_[i], polytope_[j]))\n                vertices.push_back(intersection);\n        }\n\n        // Check if intersection with circle is part of the boundary.\n        Eigen::VectorXd v1(2), v2(2);\n        if ((polytope_[i])->circleIntersect(radius_, v1, v2))\n        {\n            if (inPolytope(v1, polytope_[i]))\n            {\n                phi(v1, intersection);\n                vertices.push_back(intersection);\n            }\n            if (inPolytope(v2, polytope_[i]))\n            {\n                phi(v2, intersection);\n                vertices.push_back(intersection);\n            }\n        }\n    }\n\n    // Include points approximating the circle, if they're inside the polytope.\n    bool is_frontier = false;\n    Eigen::VectorXd v0(2);\n    v0 << radius_, 0;\n    const double step = boost::math::constants::pi<double>() / 32.;\n    for (double a = 0.; a < 2. * boost::math::constants::pi<double>(); a += step)\n    {\n        const Eigen::VectorXd vn = Eigen::Rotation2Dd(a) * v0;\n\n        if (inPolytope(vn))\n        {\n            is_frontier = true;\n            phi(vn, intersection);\n            vertices.push_back(intersection);\n        }\n    }\n\n    // Put all the points in order.\n    std::sort(vertices.begin(), vertices.end(),\n              [&](const Eigen::Ref<const Eigen::VectorXd> &x1, const Eigen::Ref<const Eigen::VectorXd> &x2) -> bool {\n                  // Check the angles to see who should come first.\n                  Eigen::VectorXd v1(2), v2(2);\n                  psiInverse(x1, v1);\n                  psiInverse(x2, v2);\n                  return std::atan2(v1[1], v1[0]) < std::atan2(v2[1], v2[0]);\n              });\n\n    return is_frontier;\n}\n\nbool ompl::base::AtlasChart::estimateIsFrontier() const\n{\n    RNG rng;\n    Eigen::VectorXd ru(k_);\n    for (int k = 0; k < 1000; k++)\n    {\n        for (int i = 0; i < ru.size(); i++)\n            ru[i] = rng.gaussian01();\n        ru *= radius_ / ru.norm();\n        if (inPolytope(ru))\n            return true;\n    }\n    return false;\n}\n\n/// Public Static\n\nvoid ompl::base::AtlasChart::generateHalfspace(AtlasChart *c1, AtlasChart *c2)\n{\n    if (c1 == c2)\n        throw ompl::Exception(\"ompl::base::AtlasChart::generateHalfspace(): \"\n                              \"Must use two different charts.\");\n\n    // c1, c2 will delete l1, l2, respectively, upon destruction.\n    Halfspace *l1, *l2;\n    l1 = new Halfspace(c1, c2);\n    l2 = new Halfspace(c2, c1);\n    l1->setComplement(l2);\n    l2->setComplement(l1);\n    c1->addBoundary(l1);\n    c2->addBoundary(l2);\n}\n\n/// Protected\n\nvoid ompl::base::AtlasChart::addBoundary(Halfspace *halfspace)\n{\n    polytope_.push_back(halfspace);\n}\n", "meta": {"hexsha": "e0e8738842bb72b5ec7ec5d87d6305597a0f1079", "size": 12606, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ompl/base/spaces/constraint/src/AtlasChart.cpp", "max_stars_repo_name": "blinnassime/ompl_old", "max_stars_repo_head_hexsha": "db6e507bc57e37e4676eadbd817463b6a8527111", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-20T03:53:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-20T03:53:52.000Z", "max_issues_repo_path": "src/ompl/base/spaces/constraint/src/AtlasChart.cpp", "max_issues_repo_name": "blinnassime/ompl_old", "max_issues_repo_head_hexsha": "db6e507bc57e37e4676eadbd817463b6a8527111", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ompl/base/spaces/constraint/src/AtlasChart.cpp", "max_forks_repo_name": "blinnassime/ompl_old", "max_forks_repo_head_hexsha": "db6e507bc57e37e4676eadbd817463b6a8527111", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-05T12:23:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-05T12:23:32.000Z", "avg_line_length": 32.2404092072, "max_line_length": 118, "alphanum_fraction": 0.6128827542, "num_tokens": 3336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.26906947542758086}}
{"text": "#include <iostream>\n#include <iterator>\n#include <iomanip>\n#include <fstream>\n#include <vector>\n#include <numeric>\n#include <cmath>\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\n#include <boost/program_options.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/scope_exit.hpp>\n\n#if defined(SOLVER_BACKEND_VEXCL)\n#  include <amgcl/backend/vexcl.hpp>\n   typedef amgcl::backend::vexcl<double> Backend;\n#elif defined(SOLVER_BACKEND_CUDA)\n#  include <amgcl/backend/cuda.hpp>\n#  include <amgcl/relaxation/cusparse_ilu0.hpp>\n   typedef amgcl::backend::cuda<double> Backend;\n#else\n#  ifndef SOLVER_BACKEND_BUILTIN\n#    define SOLVER_BACKEND_BUILTIN\n#  endif\n#  include <amgcl/backend/builtin.hpp>\n   typedef amgcl::backend::builtin<double> Backend;\n#endif\n\n#include <amgcl/io/binary.hpp>\n#include <amgcl/io/mm.hpp>\n#include <amgcl/adapter/crs_tuple.hpp>\n#include <amgcl/amg.hpp>\n#include <amgcl/solver/runtime.hpp>\n#include <amgcl/coarsening/runtime.hpp>\n#include <amgcl/relaxation/runtime.hpp>\n#include <amgcl/relaxation/as_preconditioner.hpp>\n#include <amgcl/mpi/make_solver.hpp>\n#include <amgcl/mpi/schur_pressure_correction.hpp>\n#include <amgcl/mpi/block_preconditioner.hpp>\n#include <amgcl/mpi/subdomain_deflation.hpp>\n#include <amgcl/mpi/direct_solver/runtime.hpp>\n#include <amgcl/profiler.hpp>\n\nnamespace amgcl {\n    profiler<> prof;\n}\n\nusing amgcl::prof;\nusing amgcl::precondition;\n\n//---------------------------------------------------------------------------\nstd::vector<ptrdiff_t> read_problem(\n        const amgcl::mpi::communicator &world,\n        const std::string &A_file,\n        const std::string &rhs_file,\n        const std::string &part_file,\n        std::vector<ptrdiff_t> &ptr,\n        std::vector<ptrdiff_t> &col,\n        std::vector<double>    &val,\n        std::vector<double>    &rhs\n        )\n{\n    // Read partition\n    ptrdiff_t n, m;\n    std::vector<ptrdiff_t> domain(world.size + 1, 0);\n    std::vector<int> part;\n\n    std::tie(n, m) = amgcl::io::mm_reader(part_file)(part);\n    for(int p : part) {\n        ++domain[p+1];\n        precondition(p < world.size, \"MPI world does not correspond to partition\");\n    }\n    std::partial_sum(domain.begin(), domain.end(), domain.begin());\n\n    ptrdiff_t chunk_beg = domain[world.rank];\n    ptrdiff_t chunk_end = domain[world.rank + 1];\n    ptrdiff_t chunk     = chunk_end - chunk_beg;\n\n    // Reorder unknowns\n    std::vector<ptrdiff_t> order(n);\n    for(ptrdiff_t i = 0; i < n; ++i)\n        order[i] = domain[part[i]]++;\n\n    std::rotate(domain.begin(), domain.end()-1, domain.end());\n    domain[0] = 0;\n\n    // Read matrix chunk\n    {\n        using namespace amgcl::io;\n\n        std::ifstream A(A_file.c_str(), std::ios::binary);\n        precondition(A, \"Failed to open matrix file (\" + A_file + \")\");\n\n        std::ifstream b(rhs_file.c_str(), std::ios::binary);\n        precondition(b, \"Failed to open rhs file (\" + rhs_file + \")\");\n\n        ptrdiff_t rows;\n        precondition(read(A, rows), \"File I/O error\");\n        precondition(rows == n, \"Matrix and partition have incompatible sizes\");\n\n        ptr.clear(); ptr.reserve(chunk + 1); ptr.push_back(0);\n\n        std::vector<ptrdiff_t> gptr(n + 1);\n        precondition(read(A, gptr), \"File I/O error\");\n\n        size_t col_beg = sizeof(rows) + sizeof(gptr[0]) * (n + 1);\n        size_t val_beg = col_beg + sizeof(col[0]) * gptr.back();\n        size_t rhs_beg = 2 * sizeof(ptrdiff_t);\n\n        // Count local nonzeros\n        for(ptrdiff_t i = 0; i < n; ++i)\n            if (part[i] == world.rank)\n                ptr.push_back(gptr[i+1] - gptr[i]);\n\n        std::partial_sum(ptr.begin(), ptr.end(), ptr.begin());\n\n        col.clear(); col.reserve(ptr.back());\n        val.clear(); val.reserve(ptr.back());\n        rhs.clear(); rhs.reserve(chunk);\n\n        // Read local matrix and rhs stripes\n        for(ptrdiff_t i = 0; i < n; ++i) {\n            if (part[i] != world.rank) continue;\n\n            ptrdiff_t c;\n            A.seekg(col_beg + gptr[i] * sizeof(c));\n            for(ptrdiff_t j = gptr[i], e = gptr[i+1]; j < e; ++j) {\n                precondition(read(A, c), \"File I/O error (1)\");\n                col.push_back(order[c]);\n            }\n        }\n\n        for(ptrdiff_t i = 0; i < n; ++i) {\n            if (part[i] != world.rank) continue;\n\n            double v;\n            A.seekg(val_beg + gptr[i] * sizeof(v));\n            for(ptrdiff_t j = gptr[i], e = gptr[i+1]; j < e; ++j) {\n                precondition(read(A, v), \"File I/O error (2)\");\n                val.push_back(v);\n            }\n        }\n\n        for(ptrdiff_t i = 0; i < n; ++i) {\n            if (part[i] != world.rank) continue;\n\n            double f;\n            b.seekg(rhs_beg + i * sizeof(f));\n            precondition(read(b, f), \"File I/O error (3)\");\n            rhs.push_back(f);\n        }\n    }\n\n    return domain;\n}\n\n//---------------------------------------------------------------------------\nint main(int argc, char *argv[]) {\n    int provided;\n    MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided);\n    BOOST_SCOPE_EXIT(void) {\n        MPI_Finalize();\n    } BOOST_SCOPE_EXIT_END\n\n    amgcl::mpi::communicator world(MPI_COMM_WORLD);\n\n    if (world.rank == 0)\n        std::cout << \"World size: \" << world.size << std::endl;\n\n    // Read configuration from command line\n    namespace po = boost::program_options;\n    using std::string;\n    po::options_description desc(\"Options\");\n\n    desc.add_options()\n        (\"help,h\", \"show help\")\n        (\n         \"matrix,A\",\n         po::value<string>()->required(),\n         \"The system matrix in binary format\"\n        )\n        (\n         \"rhs,f\",\n         po::value<string>(),\n         \"The right-hand side in binary format\"\n        )\n        (\n         \"part,s\",\n         po::value<string>()->required(),\n         \"Partitioning of the problem in MatrixMarket format\"\n        )\n        (\n         \"pmask,m\",\n         po::value<string>(),\n         \"The pressure mask in binary format. Or, if the parameter has \"\n         \"the form '%n:m', then each (n+i*m)-th variable is treated as pressure.\"\n        )\n        (\n         \"params,P\",\n         po::value<string>(),\n         \"parameter file in json format\"\n        )\n        (\n         \"prm,p\",\n         po::value< std::vector<string> >()->multitoken(),\n         \"Parameters specified as name=value pairs. \"\n         \"May be provided multiple times. Examples:\\n\"\n         \"  -p solver.tol=1e-3\\n\"\n         \"  -p precond.coarse_enough=300\"\n        )\n        ;\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n\n    if (vm.count(\"help\")) {\n        if (world.rank == 0)\n            std::cout << desc << std::endl;\n        return 0;\n    }\n\n    po::notify(vm);\n\n    boost::property_tree::ptree prm;\n    if (vm.count(\"params\")) read_json(vm[\"params\"].as<string>(), prm);\n\n    if (vm.count(\"prm\")) {\n        for(const string &v : vm[\"prm\"].as<std::vector<string> >()) {\n            amgcl::put(prm, v);\n        }\n    }\n\n    prof.tic(\"read problem\");\n    std::vector<ptrdiff_t> ptr;\n    std::vector<ptrdiff_t> col;\n    std::vector<double>    val;\n    std::vector<double>    rhs;\n\n    std::vector<ptrdiff_t> domain = read_problem(\n            world,\n            vm[\"matrix\"].as<string>(), vm[\"rhs\"].as<string>(), vm[\"part\"].as<string>(),\n            ptr, col, val, rhs\n            );\n\n    ptrdiff_t chunk = domain[world.rank + 1] - domain[world.rank];\n    prof.toc(\"read problem\");\n\n    std::vector<char> pm;\n    if(vm.count(\"pmask\")) {\n        std::string pmask = vm[\"pmask\"].as<string>();\n        prm.put(\"precond.pmask_size\", chunk);\n\n        switch (pmask[0]) {\n            case '%':\n            case '<':\n            case '>':\n                prm.put(\"precond.pmask_pattern\", pmask);\n                break;\n            default:\n                precondition(false, \"Pressure mask may only be set with a pattern\");\n        }\n    }\n\n    std::function<double(ptrdiff_t,unsigned)> dv = amgcl::mpi::constant_deflation(1);\n    prm.put(\"precond.psolver.num_def_vec\", 1);\n    prm.put(\"precond.psolver.def_vec\", &dv);\n\n    Backend::params bprm;\n\n#if defined(SOLVER_BACKEND_VEXCL)\n    vex::Context ctx(vex::Filter::Env);\n    std::cout << ctx << std::endl;\n    bprm.q = ctx;\n#elif defined(SOLVER_BACKEND_CUDA)\n    cusparseCreate(&bprm.cusparse_handle);\n#endif\n\n    auto f = Backend::copy_vector(rhs, bprm);\n    auto x = Backend::create_vector(chunk, bprm);\n\n    amgcl::backend::clear(*x);\n\n    MPI_Barrier(world);\n\n    prof.tic(\"setup\");\n    typedef\n        amgcl::mpi::make_solver<\n            amgcl::mpi::schur_pressure_correction<\n                amgcl::mpi::make_solver<\n                    amgcl::mpi::block_preconditioner<\n                        amgcl::relaxation::as_preconditioner<Backend, amgcl::runtime::relaxation::wrapper>\n                        >,\n                    amgcl::runtime::solver::wrapper\n                    >,\n                amgcl::mpi::subdomain_deflation<\n                    amgcl::amg<Backend, amgcl::runtime::coarsening::wrapper, amgcl::runtime::relaxation::wrapper>,\n                    amgcl::runtime::solver::wrapper,\n                    amgcl::runtime::mpi::direct::solver<double>\n                    >\n                >,\n            amgcl::runtime::solver::wrapper\n            > Solver;\n\n    Solver solve(world, std::tie(chunk, ptr, col, val), prm, bprm);\n    double tm_setup = prof.toc(\"setup\");\n\n    prof.tic(\"solve\");\n    size_t iters;\n    double resid;\n    std::tie(iters, resid) = solve(*f, *x);\n    double tm_solve = prof.toc(\"solve\");\n\n    if (world.rank == 0) {\n        std::cout\n            << \"Iterations: \" << iters << std::endl\n            << \"Error:      \" << resid << std::endl\n            << std::endl\n            << prof << std::endl;\n\n#ifdef _OPENMP\n        int nt = omp_get_max_threads();\n#else\n        int nt = 1;\n#endif\n        std::ostringstream log_name;\n        log_name << \"schur_\" << domain.back() << \"_\" << nt << \"_\" << world.size << \".txt\";\n        std::ofstream log(log_name.str().c_str(), std::ios::app);\n        log << domain.back() << \"\\t\" << nt << \"\\t\" << world.size\n            << \"\\t\" << tm_setup << \"\\t\" << tm_solve\n            << \"\\t\" << iters << \"\\t\" << std::endl;\n    }\n}\n", "meta": {"hexsha": "789a12e20a4e5a72d7cc469ed05af1661febd093", "size": 10287, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/mpi/schur_pc_mpi.cpp", "max_stars_repo_name": "moyner/amgcl", "max_stars_repo_head_hexsha": "a551614040f0a7b793b41a4a63386675ca61d8da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-20T06:16:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-20T06:16:20.000Z", "max_issues_repo_path": "examples/mpi/schur_pc_mpi.cpp", "max_issues_repo_name": "moyner/amgcl", "max_issues_repo_head_hexsha": "a551614040f0a7b793b41a4a63386675ca61d8da", "max_issues_repo_licenses": ["MIT"], "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/mpi/schur_pc_mpi.cpp", "max_forks_repo_name": "moyner/amgcl", "max_forks_repo_head_hexsha": "a551614040f0a7b793b41a4a63386675ca61d8da", "max_forks_repo_licenses": ["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.5252225519, "max_line_length": 114, "alphanum_fraction": 0.5525420434, "num_tokens": 2686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.26906946272346455}}
{"text": "#include <armadillo>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <algorithm>\n//~ #include <thread>\n\n#include <boost/filesystem.hpp>\n#include <boost/filesystem/fstream.hpp>\n\n#include <iomanip>\n#include <sstream>\n\nusing namespace std;\nusing namespace arma;\nusing namespace boost::filesystem;\n\n\nclass Pdb_data {\n    \n    int anchor_len;\n    int loop_len_1;\n    int loop_len_2;\n    int n_atoms;\n    \n    mat anchor_points_1;\n    mat aligned_anchor_points_1;\n    mat anchor_points_2;\n    \n    mat loop_points_1;\n    mat aligned_loop_points_1;\n    mat loop_points_2;\n    \n    rowvec anchor_atom_found_1;\n    rowvec anchor_atom_found_2;\n    \n    rowvec residue_atom_found_1;\n    rowvec residue_atom_found_2;\n    \n    void get_atom(char[], char[]);\n    bool correct_atom(char[]);\n    double get_double(string, int, int);\n    int atom_index(char[]);\n    int get_index(char*, char[][5], int);\n    void read_number(char[], int, int, double*);\n    void read_file(string, mat&, mat&, rowvec&, rowvec&, char[][5], int, int);\n    void Kabsch(mat, mat, mat&, mat&, mat&);\n    void Align_anchors();\n    template <typename T> int sgn(T);\n    void ResidueRM_TSD(mat, mat, rowvec, rowvec, double&, double&, int&);\n    string format_number(double);\n    \n    \n    public:\n    \n    Pdb_data(string, string, char[][5], int, int);\n    void Retrieve_Residue(int, int, mat&, rowvec&);\n    void calculate_DTW(double*);\n    void write_modified_file(const char*, const char*, int);\n    \n};\n\nvoid Pdb_data::get_atom(char line[], char atom[]){\n    int atom_index = 0;\n    for(int i=12; i<16; i++){\n        if(isalnum(line[i])){\n            atom[atom_index++] = line[i];\n        }\n    }\n    atom[atom_index] = '\\0';\n}\n\nbool Pdb_data::correct_atom(char atom[]){\n    return strcmp(atom,\"C\")==0 || strcmp(atom,\"CA\")==0 || strcmp(atom,\"N\")==0 || strcmp(atom,\"O\")==0;\n}\n\ndouble Pdb_data::get_double(string line, int start, int length){\n    double x = atof(line.substr(start, length).c_str());\n    return x;\n}\n\nint Pdb_data::atom_index(char atom[]){\n    if(strcmp(atom,\"N\")==0){\n        return 0;\n    } else if(strcmp(atom,\"CA\")==0){     \n        return 1;\n    } else if(strcmp(atom,\"C\")==0){\n        return 2;\n    } else if(strcmp(atom,\"O\")==0){\n        return 3;\n    }\n\n    cout << \"Unrecognized atom \" << atom << endl;\n}\n\nint Pdb_data::get_index(char* atom, char atoms[][5], int n_atoms){\n    for(int i=0; i<n_atoms; i++){\n        if(strcmp(atom, atoms[i]) == 0){\n            return i;\n        }\n    }\n    return -1;\n}\n\nvoid Pdb_data::read_number(char line[], int from, int length, double *result){\n    char num[length+1];\n    memcpy(num, &line[from], length);\n    num[length] = '\\0';\n    *result = atof(num);\n}\n\nvoid Pdb_data::read_file(string file, mat &anchor_points, mat &loop_points, rowvec &anchor_atom_found, rowvec &residue_atom_found, char atoms[][5], int n_atoms, int anchor_len){\n    boost::filesystem::ifstream input(file);\n    char buf[81];\n    char c_aa[6], l_aa[6], atom[5];  \n    char beginning[7];  \n    const char *ATOM = \"ATOM  \";\n    const char *HETATM = \"HETATM\";\n    int aa_index = -1;\n    rowvec g_atom_found;\n    mat points;\n    \n    c_aa[5] = '\\0';\n    l_aa[5] = '\\0';\n    atom[4] = '\\0';\n    beginning[4] = '\\0';\n    \n    mat aa_atoms = zeros<mat>(3, n_atoms);\n    //mat empty = zeros<mat>(n_atoms,3);\n    rowvec l_atom_found = zeros<rowvec>(n_atoms);\n    //rowvec empty_vec = zeros<rowvec>(n_atoms);\n    \n    // cout << \"Reading file \" << file << endl;\n    \n    while(input.good()){\n\n        input.getline(buf, 81);\n                \n        memcpy(beginning, &buf[0], 6);\n\n        beginning[6] = '\\0';\n        \n        if (strcmp(beginning, ATOM) == 0 || strcmp(beginning, HETATM) == 0)\n        {\n        \n            // Change Amino Acid\n            memcpy(l_aa, &buf[22], 5);\n            \n            //cout << c_aa << endl;\n            \n            if(strcmp(c_aa, l_aa) != 0){\n                //cout << \"Change from\" << c_aa << \"to\" << l_aa << \" \" << strcmp(c_aa, l_aa) << endl;\n                memcpy(c_aa, &l_aa[0], 5);            \n                aa_index++;\n                //cout << aa_index << '\\n';\n                if(aa_index != 0){\n                    points = join_horiz(points, aa_atoms);\n                    \n                    //cout << points << '\\n';\n                    \n                    g_atom_found = join_horiz(g_atom_found, l_atom_found);\n                }\n                \n                l_atom_found = zeros<rowvec>(n_atoms);\n                aa_atoms = zeros<mat>(3, n_atoms);\n                \n            }\n            \n            get_atom(buf, atom);\n            int atom_index = get_index(atom, atoms, n_atoms);\n            \n            if(atom_index != -1){\n                double x, y, z;\n                read_number(buf,30, 8,&x);\n                read_number(buf,38, 8,&y);\n                read_number(buf,46, 8,&z);\n            \n                colvec point = zeros<colvec>(3);\n                point(0) = x;\n                point(1) = y;\n                point(2) = z;\n            \n            \n                aa_atoms.col(atom_index) = point;\n                \n                l_atom_found(atom_index) = 1.0;\n            }\n            \n        }\n    }\n\n    points = join_horiz(points, aa_atoms);\n    \n    g_atom_found = join_horiz(g_atom_found, l_atom_found);\n    \n    int points_len = points.n_cols;\n    \n    anchor_points = join_horiz(points.cols(0, anchor_len*n_atoms - 1), points.cols(points_len - anchor_len*n_atoms, points_len - 1));\n    \n    loop_points = points.cols(anchor_len*n_atoms, points_len - anchor_len*n_atoms - 1);\n    \n    anchor_atom_found = join_horiz(g_atom_found.subvec(0, anchor_len*n_atoms - 1), g_atom_found.subvec(points_len - anchor_len*n_atoms, points_len - 1));\n    \n    residue_atom_found = g_atom_found.subvec(anchor_len*n_atoms, points_len - anchor_len*n_atoms - 1);\n    \n    //~ cout << loop_points << endl;\n    \n}\n\nvoid Pdb_data::Kabsch(mat P, mat Q, mat &anchor_mass_centre_1, mat &anchor_mass_centre_2, mat &Rotation_mat)\n{\n    mat Middle_mat;\n    \n    mat P_translated;\n    mat Q_translated;\n    mat P_rotated_translated;\n    mat P_finish;\n    \n    mat U;\n    vec s;\n    mat V;\n    \n    mat R;\n    \n    colvec P_centroid;\n    colvec Q_centroid;\n    rowvec v_ones;\n    \n    mat Covariance_matrix;\n    \n    int d;\n    int n_points;\n    \n    // Calculate the number of datapoints\n    n_points = P.n_cols;\n    \n    //Calculate the coordinates of the centres of mass\n    P_centroid=sum(P,1)/n_points;\n    \n    Q_centroid=sum(Q,1)/n_points;\n    \n    v_ones = ones<rowvec>(n_points);\n    \n    //Translate the points so that the cetre of mass coincides with the origin\n    P_translated = P - P_centroid*v_ones;\n    \n    Q_translated = Q - Q_centroid*v_ones;\n    \n    //Calculate the covariance matrix   \n    Covariance_matrix=P_translated*Q_translated.t()/n_points;\n    \n    //Calculate svd\n    svd(U,s,V,Covariance_matrix);\n    \n    //Ensure a right-handed coordinate system\n    d = sgn(det( V*U.t() ));\n    \n    Middle_mat = eye<mat>(3,3);\n    \n    Middle_mat(2,2) =  d;\n    \n    //Calculate the rotation matrix\n    R=V*Middle_mat*U.t();\n    \n    //~ cout << Q << endl;\n    //~ cout << R*(P - P_centroid*v_ones) + Q_centroid*v_ones << endl;\n    \n    aligned_anchor_points_1 = R*(P - P_centroid*v_ones) + Q_centroid*v_ones;\n    \n    anchor_mass_centre_1 = P_centroid;\n    anchor_mass_centre_2 = Q_centroid;\n    Rotation_mat = R;\n    \n}\n\nvoid Pdb_data::Align_anchors(){\n    \n    mat anchor_mass_centre_1;\n    mat anchor_mass_centre_2;\n    mat Rotation_mat;\n    int len_1;\n    uvec logic_vec_1;\n    \n    Kabsch(anchor_points_1, anchor_points_2, anchor_mass_centre_1, anchor_mass_centre_2, Rotation_mat);\n    \n    rowvec v_ones = ones<rowvec>(sum(residue_atom_found_1));\n    \n    logic_vec_1 = find(residue_atom_found_1 == 1);\n    \n    aligned_loop_points_1 = loop_points_1;\n    \n    aligned_loop_points_1.cols(logic_vec_1) = aligned_loop_points_1.cols(logic_vec_1) - anchor_mass_centre_1*v_ones;\n    \n    aligned_loop_points_1.cols(logic_vec_1) = Rotation_mat*aligned_loop_points_1.cols(logic_vec_1);\n    \n    aligned_loop_points_1.cols(logic_vec_1) = aligned_loop_points_1.cols(logic_vec_1) + anchor_mass_centre_2*v_ones;\n    \n}\n\ntemplate <typename T> int Pdb_data::sgn(T val) {\n    return (T(0) < val) - (val < T(0));\n}\n\nvoid Pdb_data::Retrieve_Residue(int data_index, int res_index, mat &Residue_points, rowvec &individual_atoms_found){\n    \n    if(data_index == 1)\n    {\n        Residue_points = aligned_loop_points_1.cols(res_index*n_atoms, (res_index + 1)*n_atoms - 1);\n        \n        individual_atoms_found = residue_atom_found_1.subvec(res_index*n_atoms, (res_index + 1)*n_atoms - 1);\n        \n    }\n    else if(data_index == 2)\n    {\n        Residue_points = loop_points_2.cols(res_index*n_atoms, (res_index + 1)*n_atoms - 1);\n        \n        individual_atoms_found = residue_atom_found_2.subvec(res_index*n_atoms, (res_index + 1)*n_atoms - 1);\n        \n    }\n    else\n    {\n        cout << \"There are only two datasets\" << endl;\n        \n    }\n    \n}\n\nvoid Pdb_data::ResidueRM_TSD(mat Res1, mat Res2, rowvec individual_atoms_found_1, rowvec individual_atoms_found_2, double &RMSD, double &TSD, int &N){\n    \n    uvec logic_vec_both;\n    \n    mat Diff;\n    \n    rowvec total_individual_atoms_found;\n    \n    mat Res_inboth_1;\n    \n    mat Res_inboth_2;\n    \n    total_individual_atoms_found = individual_atoms_found_1 % individual_atoms_found_2;\n    \n    N = sum(total_individual_atoms_found);\n    \n    logic_vec_both = find(total_individual_atoms_found == 1);\n    \n    Res_inboth_1 = Res1.cols(logic_vec_both);\n    \n    Res_inboth_2 = Res2.cols(logic_vec_both);\n    \n    Diff = Res_inboth_1 - Res_inboth_2;\n    \n    RMSD = sqrt(1.0/N * sum(sum(Diff % Diff)));\n    \n    TSD = sum(sum(Diff % Diff));\n    \n}\n\nvoid Pdb_data::calculate_DTW(double *result)\n{\n    \n    double RMSD_val;\n    \n    double SD_val;\n    \n    int N;\n    \n    mat Residue_points_1;\n    rowvec individual_atoms_found_1;\n    \n    mat Residue_points_2;\n    rowvec individual_atoms_found_2;\n    \n    mat cost_mat = zeros<mat>(loop_len_1, loop_len_2);\n    \n    mat SD_mat = zeros<mat>(loop_len_1, loop_len_2);\n    \n    mat N_mat = zeros<mat>(loop_len_1, loop_len_2);\n    \n    uword index;\n    \n    double min_out_of_three;\n    \n    rowvec three_values = zeros<rowvec>(3);\n    rowvec SD_three_values = zeros<rowvec>(3);\n    rowvec N_three_values = zeros<rowvec>(3);\n    \n    Retrieve_Residue(1, 0 ,Residue_points_1, individual_atoms_found_1);\n    Retrieve_Residue(2, 0 ,Residue_points_2, individual_atoms_found_2);\n    \n    ResidueRM_TSD(Residue_points_1, Residue_points_2, individual_atoms_found_1, individual_atoms_found_2, RMSD_val, SD_val, N);\n    \n    cost_mat(0,0) = RMSD_val;\n    SD_mat(0,0) = SD_val;\n    N_mat(0,0) = N;\n    \n    for(int i = 1; i < loop_len_1; i++)\n    {\n        Retrieve_Residue(1, i ,Residue_points_1, individual_atoms_found_1);\n        \n        ResidueRM_TSD(Residue_points_1, Residue_points_2, individual_atoms_found_1, individual_atoms_found_2, RMSD_val, SD_val, N);\n        \n        cost_mat(i,0) = cost_mat(i-1,0) + RMSD_val;\n        \n        SD_mat(i,0) = SD_mat(i-1,0) + SD_val;\n        \n        N_mat(i,0) = N_mat(i-1,0) + N;\n        \n    }\n    \n    Retrieve_Residue(1, 0 ,Residue_points_1, individual_atoms_found_1);\n    \n    for(int j = 1; j < loop_len_2; j++)\n    {\n        Retrieve_Residue(2, j ,Residue_points_2, individual_atoms_found_2);\n        \n        ResidueRM_TSD(Residue_points_1, Residue_points_2, individual_atoms_found_1, individual_atoms_found_2, RMSD_val, SD_val, N);\n        \n        cost_mat(0,j) = cost_mat(0, j-1) + RMSD_val;\n        \n        SD_mat(0,j) = SD_mat(0, j-1) + SD_val;\n        \n        N_mat(0,j) = N_mat(0, j-1) + N;\n        \n    }\n    \n    for(int i = 1; i < loop_len_1; i++)\n    {\n        // cout << \"Here\" << endl;\n        for(int j = 1; j< loop_len_2; j++)\n        {\n            Retrieve_Residue(1, i ,Residue_points_1, individual_atoms_found_1);\n            Retrieve_Residue(2, j ,Residue_points_2, individual_atoms_found_2);\n            \n            ResidueRM_TSD(Residue_points_1, Residue_points_2, individual_atoms_found_1, individual_atoms_found_2, RMSD_val, SD_val, N);\n            \n            three_values(0) = cost_mat(i-1, j);\n            three_values(1) = cost_mat(i, j-1);\n            three_values(2) = cost_mat(i-1, j-1);\n            \n            SD_three_values(0) = SD_mat(i-1, j);\n            SD_three_values(1) = SD_mat(i, j-1);\n            SD_three_values(2) = SD_mat(i-1, j-1);\n            \n            N_three_values(0) = N_mat(i-1, j);\n            N_three_values(1) = N_mat(i, j-1);\n            N_three_values(2) = N_mat(i-1, j-1);\n            \n            min_out_of_three = three_values.min(index);\n            \n            //cout << i << ' ' << j <<' '  << SD_val << three_values << endl;\n            \n            cost_mat(i,j) = min_out_of_three + RMSD_val;\n            \n            SD_mat(i, j) = SD_three_values(index) + SD_val;\n            \n            N_mat(i, j) = N_three_values(index) + N;\n            \n        }\n    }\n    \n    //~ cout << cost_mat << endl;\n    //~ \n    //~ cout << SD_mat << endl;\n    //~ \n    //~ cout << N_mat << endl;\n    \n    N = N_mat(loop_len_1 - 1, loop_len_2 - 1);\n    \n    //~ cout << N << endl;\n    //~ \n    //~ cout << sqrt(1.0/N * SD_mat(loop_len_1 - 1, loop_len_2 - 1)) << endl;\n    \n    *result = sqrt(1.0/N * SD_mat(loop_len_1 - 1, loop_len_2 - 1));\n    \n}\n\nstring Pdb_data::format_number(double Number_to_format)\n{\n    int wspc_missing;\n    \n    string Result;\n    \n    string complete_string;\n    \n    ostringstream Convert;\n    \n    Convert << fixed << setprecision(3) << Number_to_format;\n    \n    Result = Convert.str();\n    \n    wspc_missing = 7 - Result.length();\n    \n    complete_string = string(wspc_missing, ' ') + Result;\n    \n    return complete_string;\n\n}\n\nvoid Pdb_data::write_modified_file(const char *original_file, const char *result_file, int data_index)\n{\n    mat P_mat;\n    \n    if(data_index == 1)\n    {\n        P_mat = join_horiz(aligned_anchor_points_1.cols(0, anchor_len*n_atoms - 1), aligned_loop_points_1);\n        P_mat = join_horiz(P_mat, aligned_anchor_points_1.cols(anchor_len*n_atoms, 2 * anchor_len*n_atoms - 1));\n        \n    }\n    else if(data_index == 2)\n    {\n        P_mat = join_horiz(anchor_points_2.cols(0, anchor_len*n_atoms - 1), loop_points_2);\n        P_mat = join_horiz(P_mat, anchor_points_2.cols(anchor_len*n_atoms, 2 * anchor_len*n_atoms - 1));\n        \n    }\n    else\n    {\n        cout << \"There are only two datasets\" << endl;\n        \n    }\n    \n    \n    boost::filesystem::ifstream infile(original_file);\n    boost::filesystem::ofstream pdb_modified;\n    \n    double x,y,z;\n    \n    int i;\n    \n    pdb_modified.open(result_file);\n    \n    string line;\n    \n    string x_string;\n    \n    string y_string;\n    \n    string z_string;\n    \n    i=0;\n    \n    while(getline(infile, line))\n    {\n        \n        if (line.compare(13, 3, \"CA \")==0 or line.compare(13, 3, \"N  \")==0 or line.compare(13, 3, \"C  \")==0 or line.compare(13, 3, \"O  \")==0)\n        \n        {\n            x = P_mat(0,i);\n            \n            y = P_mat(1,i);\n            \n            z = P_mat(2,i);\n            \n            x_string = format_number(x);\n            \n            y_string = format_number(y);\n            \n            z_string = format_number(z);\n            \n            line.replace(31,7,x_string);\n            \n            line.replace(39,7,y_string);\n            \n            line.replace(47,7,z_string);\n            \n            //~ cout << line << line.length() << '\\n';\n            \n            pdb_modified << line << '\\n';\n            \n            i++;\n        }\n    }\n    \n    pdb_modified.close();\n}\n    \nPdb_data::Pdb_data(string file1, string file2, char atoms[][5], int n_atoms, int anchor_len){\n    \n    this->anchor_len = anchor_len;\n    this->n_atoms = n_atoms;\n    \n    uvec logic_vec;\n    rowvec total_anchor_atoms_found;\n    \n    \n    //~ thread thread1(read_file, file1, ref(pos1), ref(atom_found1), atoms, n_atoms);\n    //~ thread thread2(read_file, file2, ref(pos2), ref(atom_found2), atoms, n_atoms);\n    //~ \n    //~ thread1.join();\n    //~ thread2.join();\n\n    // cout << file1 << endl;\n\n    // cout << file2 << endl;\n    \n    read_file( file1, anchor_points_1, loop_points_1, anchor_atom_found_1, residue_atom_found_1, atoms, n_atoms, anchor_len);\n    read_file( file2, anchor_points_2, loop_points_2, anchor_atom_found_2, residue_atom_found_2, atoms, n_atoms, anchor_len); \n    \n    total_anchor_atoms_found = anchor_atom_found_1 % anchor_atom_found_2;\n    \n    // cout << anchor_points_1 << endl;\n    \n    // cout << anchor_points_2 << endl; \n    \n    logic_vec = find(total_anchor_atoms_found == 1);\n    \n    anchor_points_1 = anchor_points_1.cols(logic_vec);\n    \n    anchor_points_2 = anchor_points_2.cols(logic_vec);\n    \n    //~ cout << anchor_points_1 << endl;\n    \n    if(anchor_points_1.n_elem != anchor_points_2.n_elem)\n    {\n        cout << \"Anchor Lengths are not the same \" << file1 << \" \" << file2 << endl;\n    }\n    \n    //~ cout << anchor_points_2 << endl; \n    //~ \n    //~ cout << loop_points_1 << endl;\n    //~ \n    //~ cout << loop_points_2 << endl;\n    \n    if(loop_points_1.n_cols % 4 != 0 || loop_points_2.n_cols % 4 != 0)\n    {\n        cout << \"Something's wrong with the number of residues \" << file1 << \" \" << file2 << endl;\n    }\n    \n    loop_len_1 = loop_points_1.n_cols / 4.0;\n    \n    loop_len_2 = loop_points_2.n_cols / 4.0;\n    \n    //~ cout << loop_len_1 << \" \" << loop_len_2 << endl;\n    \n    Align_anchors();\n    \n    //~ cout << aligned_loop_points_1 << endl;\n    //~ \n    //~ cout << loop_points_2 << endl;\n    \n    \n    \n    \n}\n\nint main(int argc, char* argv[])\n{\n\n    boost::filesystem::ofstream distmat_file;\n    boost::filesystem::ofstream file_list;\n\n    mat P1_kabsch;\n\n    int anchor_len = 5;\n\n    double result;\n    \n    char atoms[4][5];\n\n    strcpy(atoms[0],\"N\");\n    strcpy(atoms[1],\"CA\");\n    strcpy(atoms[2],\"C\");\n    strcpy(atoms[3],\"O\");\n\n    string filename;\n\n    string extension = \"pdb\";\n\n    string current_extension;\n\n    int filelen;\n\n    int start;\n\n    vector<string> filenames;\n\n    mat distmat;\n\n    int n_files;\n\n    int row, col;\n\n    int res_anchor_len = 5;\n    int start_atom_anchor_len, end_atom_anchor_len;\n\n    const char* directory = argv[1];\n\n    const char* output_file_list_name = argv[2];\n\n    const char* output_distmat_name = argv[3];\n\n    path p(directory);\n\n    // Read old file list\n    vector<string> filenames_old;\n    int n_oldfiles = 0;\n    bool found_old = false;\n    if (boost::filesystem::exists(output_file_list_name))\n    {\n        found_old = true;\n\tcout << \"Found output file list\\n\";\n        boost::filesystem::ifstream file_list_old(output_file_list_name);\n        while(getline(file_list_old,filename))\n        {\n            filenames.push_back(filename);\n        }\n        n_oldfiles = filenames.size();\n        cout << \"Number of files: \"<<n_oldfiles<<endl;\n    }\n    // Read old distmat\n    mat distmat_old;\n    if (found_old & boost::filesystem::exists(output_distmat_name))\n    {\n        boost::filesystem::ifstream distmat_file_old(output_distmat_name);\n        distmat_old.load(distmat_file_old);\n    }\n\n    for (auto i = directory_iterator(p); i != directory_iterator(); i++)\n    {\n        if (!is_directory(i->path())) //we eliminate directories\n        {\n\n            filename = i->path().string();\n\n            filelen = filename.length();\n\n            start = filelen - 3;\n\n            current_extension = filename.substr(start,filelen);\n\n            if(!current_extension.compare(extension) & std::find(filenames.begin(),filenames.end(),filename) == filenames.end() ){\n                filenames.push_back(filename);\n            }\n\n            \n        }\n        else\n            continue;\n    }\n\n    cout << \"Reading files and calculating distmat...\" << endl;\n\n    file_list.open(output_file_list_name);\n\n    n_files = filenames.size();\n\n    distmat = zeros<mat>(n_files, n_files);\n\n    row = 0;\n\n    for(auto i = filenames.begin(); i != filenames.end(); ++i)\n    {\n\n        //cout << row << \" \" << *i << endl;\n\n        col = row + 1;\n        file_list << *i << endl;\n\n        for(auto j = i + 1; j != filenames.end(); ++j)\n        {            \n            //cout << *i << \" \" << *j << \" \" << row << \" \" << col << \" \";\n            if (found_old & col<n_oldfiles)\n            {\n\t\t//cout << \"skipped with \"<<distmat_old(row,col)<<endl;\n                distmat(row,col) = distmat_old(row,col);\n                distmat(col,row) = distmat_old(col,row);\n                col++;\n                continue;\n            }\n            //cout << \"calculating\"<<endl;\n            Pdb_data x(*i, *j, atoms, 4, anchor_len);\n\n            x.calculate_DTW(&result);\n\n            distmat(row,col) = result;\n\n            distmat(col,row) = result;\n\n            col++;\n\n        }\n\n        row++;\n    }\n\n    distmat_file.open(output_distmat_name);\n\n    distmat_file << distmat;\n\n    distmat_file.close();\n\n    // cout << distmat << endl;\n\n\n\n    // cout << \"Done !\" << endl;\n\n    // Kabsch(all_Ps[0], all_Ps[2], &rmsd);\n\n    // cout << filenames[0] << \" \" << filenames[1] << endl;\n\n    // cout << rmsd << endl;\n}\n", "meta": {"hexsha": "b5dc167a98d8f913b8bc7ef11c00552970ba4e59", "size": 21277, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "builddb_code/ReadDir_DTW.cpp", "max_stars_repo_name": "gvrocha/SCALOP", "max_stars_repo_head_hexsha": "3e9514a2636f59efab7b53341e0376497c7a75b1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-05-19T20:27:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T20:23:48.000Z", "max_issues_repo_path": "builddb_code/ReadDir_DTW.cpp", "max_issues_repo_name": "gvrocha/SCALOP", "max_issues_repo_head_hexsha": "3e9514a2636f59efab7b53341e0376497c7a75b1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-03-17T14:57:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-23T17:28:17.000Z", "max_forks_repo_path": "builddb_code/ReadDir_DTW.cpp", "max_forks_repo_name": "gvrocha/SCALOP", "max_forks_repo_head_hexsha": "3e9514a2636f59efab7b53341e0376497c7a75b1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T09:44:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T08:55:50.000Z", "avg_line_length": 26.4639303483, "max_line_length": 177, "alphanum_fraction": 0.570945152, "num_tokens": 5807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.2690590621821101}}
{"text": "#include <fstream>\n#include <iostream>\n#include <filesystem>\n#include <string>\n#include <random>\n#include <unordered_map>\n#include <algorithm>\n#include <chrono>\n#include <future>\n#include <utility>\n#include <cmath>\n#include <boost/iostreams/filtering_streambuf.hpp>\n#include <boost/iostreams/filter/gzip.hpp>\n#include <xtensor/xarray.hpp>\n#include <xtensor/xmath.hpp>\n#include \"csv.hpp\"\n#include \"../assembly/assembly.cpp\"\n#include \"../distance/distance.cpp\"\n#include \"../distribution/distribution.cpp\"\n#include \"../probability/probability.cpp\"\n#include \"../probability/probability_util.cpp\"\n#include \"../domain/domain.cpp\"\n#include \"../fasta/fasta.cpp\"\n#include \"../count/tri_count.cpp\"\n#include \"../codons/swap_codons.cpp\"\n\nusing namespace std;\nusing namespace std::chrono;\nusing namespace csv;\n\nunordered_map<string, vector<double>> MakeInterventions(\n\tFastaParser parser, \n\tconst xt::xarray<double>& genome_wide_dist,\n\tconst string& intervention, \n\tconst int n_samples,\n\tmt19937 rng\n) {\n\tunordered_map<string, vector<double>> protein_id_to_distances;\n\tFastaRecord cds_record{};\n\twhile (parser.Get(cds_record)) {\n\t\tauto& sequence = cds_record.content;\n\t\tstring protein_id = cds_record.id;\n\n\t\t// Perform a number of random interventions on the CDS\n\t\tvector<double> distances;\n\t\tfor (int s = 0; s < n_samples; ++s) {\n\t\t\tstring seq = \"\";\n\t\t\tif (intervention == \"swap\") {\n\t\t\t\tseq = SwapSynonymousCodons(sequence, rng);\n\t\t\t} else if (intervention == \"shuffle\") {\n\t\t\t\tseq = ShuffleCodons(sequence, rng);\n\t\t\t} else {\n\t\t\t\tthrow runtime_error(\"Unknown intervention type: \" + intervention);\n\t\t\t}\n\n\t\t\t// Count tri-nucleotides\n\t\t\tbool overlap = true;\n\t\t\tbool use_async = false;\n\t\t\tvector<int> counts = CountTriNucleotides(seq, overlap, use_async);\n\n\t\t\t// Compute distribution\n\t\t\txt::xarray<double> cds_distribution = xt::zeros<double>({counts.size()});\n\t\t\tint sum = accumulate(counts.begin(), counts.end(), 0);\n\t\t\tfor (int cix = 0; cix < counts.size(); ++cix) {\n\t\t\t\tcds_distribution[cix] = (double) counts[cix] / (double) sum;\n\t\t\t}\n\n\t\t\t// Compute distance\n\t\t\tdouble distance = jensen_shannon_distance(genome_wide_dist, cds_distribution);\n\t\t\tif (isinf(distance) || isnan(distance)) {\n\t\t\t\tcerr << \"MakeInterventions: Nan or Inf encountered for protein id: \" << protein_id << endl;\n\t\t\t\tcontinue;\n\t\t\t} else {\n\t\t\t\tdistances.push_back(distance);\n\t\t\t}\n\t\t}\n\t\tif (distances.size() > 0) {\n\t\t\tprotein_id_to_distances[protein_id] = distances;\n\t\t}\n\t}\n\treturn protein_id_to_distances;\n}\n\nbool task_intervention_per_assembly(\n\tconst int task_nb,\n\tconst string& query, \n\tconst string& tail,\n\tconst string intervention,\n\tconst int n_samples,\n\tconst vector<string>& assembly_ids\n) {\n\tauto start_clock = system_clock::now();\n\n\tcerr << \"Thread \" << task_nb << \" started.\" << endl;\n\n\tstring dataFolder = \"../data/\";\n\tstring sequencesFolder = dataFolder + \"sequences/\";\n\tauto n_assemblies = assembly_ids.size();\n\n\t// Load genome-wide distributions\n\tstring assembly_dist_path = (\n\t\tdataFolder + \"tri_nucleotide_dist_genome_wide_with_overlap.csv\"\n\t);\n\tifstream assembly_dist_f(assembly_dist_path);\n\tDistributions assembly_distributions(assembly_dist_f);\n\n\t// Load Protein domains metadata\n\tstring metadata_path = dataFolder + query + \"_master.csv\";\n\tauto metadata = LoadDomainMetadata(metadata_path);\n\n\t// Random number generator\n\trandom_device rd;\n\tmt19937 rng(rd());\n\n\t// Compute interventions on every assemblies\n\tint i = 0;\n\tfor (auto& accession : assembly_ids) {\n\t\tauto elapsed = duration_cast<seconds>(system_clock::now() - start_clock).count();\n\t\tcerr << \"Thread \" << task_nb << \": \";\n\t\tcerr << \"Processing assembly \" << i + 1 << \" / \" << n_assemblies;\n\t\tcerr << \" (elapsed: \" << elapsed << \" seconds)\" << endl;\n\t\t++i;\n\n\t\t// Get genome-wide distribution\n\t\txt::xarray<double> genome_wide_dist = assembly_distributions[accession];\n\n\t\t// Load protein domains to protein ids map\n\t\tstring protein_domains_path = (\n\t\t\tsequencesFolder + accession + \"/\" + \n\t\t\taccession + \"_\" + query + \".csv.gz\"\n\t\t);\n\t\tifstream protein_domains_file(protein_domains_path);\n\t\tboost::iostreams::filtering_streambuf<boost::iostreams::input> inbuf;\n\t\tinbuf.push(boost::iostreams::gzip_decompressor());\n\t\tinbuf.push(protein_domains_file);\n\t\tistream instream(&inbuf);\n\t\tProteinDomains domains(instream);\n\n\t\t// Instanciate CDS parser\n\t\tstring cds_path = (\n\t\t\tsequencesFolder + \n\t\t\taccession + \"/\" + \n\t\t\taccession + \"_cds_from_genomic.fna.gz\"\n\t\t);\n\t\tifstream input_file(cds_path, ios_base::in | ios_base::binary);\n\t\tboost::iostreams::filtering_streambuf<boost::iostreams::input> inbuf_cds;\n\t\tinbuf_cds.push(boost::iostreams::gzip_decompressor());\n\t\tinbuf_cds.push(input_file);\n\t\tistream instream_cds(&inbuf_cds);\n\t\tFastaParser parser(instream_cds);\n\n\t\t// Make interventions: randomly modify sequences a bunch of times and return results as a\n\t\t// map of protein ids to the list of distances from the modified sequence distributions \n\t\t// the genome-wide distribution. \n\t\tunordered_map<string, vector<double>> protein_id_to_distances = MakeInterventions(\n\t\t\tparser,\n\t\t\tgenome_wide_dist,\n\t\t\tintervention,\n\t\t\tn_samples,\n\t\t\trng\n\t\t);\n\n\t\t// Compute mean probability per sample\n\t\tvector<double> means(n_samples);\n\t\tfor (int s = 0; s < n_samples; ++s) {\n\t\t\txt::xarray<double> probs = xt::zeros<double>({protein_id_to_distances.size()});\n\t\t\tint ix = 0;\n\t\t\tfor (auto& it : protein_id_to_distances) {\n\t\t\t\tdouble distance = it.second[s];\n\t\t\t\tprobs[ix] = compute_probability_from_distance(distance, tail == \"left\");\n\t\t\t\t++ix;\n\t\t\t}\n\t\t\tdouble mean = xt::mean(probs)();\n\t\t\tmeans[s] = mean;\n\t\t}\n\n\t\t// Compute domain probability\n\t\tvector<DomainProbability> records;\n\t\tfor (ProteinDomain& domain : domains.Keys()) {\n\t\t\t// Set description from metadata rather than from annotations\n\t\t\tif (metadata.find(domain.id) != metadata.end()) {\n\t\t\t\tauto& [domain_query, domain_description] = metadata[domain.id];\n\t\t\t\tdomain.query = domain_query;\n\t\t\t\tdomain.description = domain_description;\n\t\t\t}\n\n\t\t\t// Get protein ids containing this domain\n\t\t\tauto protein_ids = domains.ProteinIds(domain);\n\n\t\t\t// Compute gene probabilities for each sample\n\t\t\tint n_records = -1;\n\t\t\txt::xarray<double> log_probs = xt::zeros<double>({n_samples});\n\t\t\txt::xarray<double> log_probs_baseline = xt::zeros<double>({n_samples});\n\t\t\tfor (int s = 0; s < n_samples; ++s) {\n\t\t\t\tdouble mean = means[s];\n\n\t\t\t\txt::xarray<double> probabilities = xt::zeros<double>({protein_ids.size()});\n\t\t\t\txt::xarray<double> probabilities_baseline = xt::zeros<double>({protein_ids.size()});\n\t\t\t\tfor (int k = 0; k < protein_ids.size(); ++k) {\n\t\t\t\t\tauto& protein_id = protein_ids[k];\n\t\t\t\t\tdouble distance = mean; // Default in case there is no data for protein id\n\t\t\t\t\tif (protein_id_to_distances.find(protein_id) != protein_id_to_distances.end()) {\n\t\t\t\t\t\tdistance = protein_id_to_distances[protein_id][s];\n\t\t\t\t\t}\n\t\t\t\t\tprobabilities[k] = compute_probability_from_distance(distance, tail == \"left\");\n\t\t\t\t\tprobabilities_baseline[k] = mean;\n\t\t\t\t}\n\n\t\t\t\txt::xarray<double> log_probabilities = xt::eval(xt::log(probabilities));\n\t\t\t\txt::xarray<double> log_probabilities_baseline = xt::eval(xt::log(probabilities_baseline));\n\n\t\t\t\tdouble log_prob = product_rule_log(log_probabilities);\n\t\t\t\tdouble log_prob_baseline = product_rule_log(log_probabilities_baseline);\n\n\t\t\t\tif (n_records == -1) {\n\t\t\t\t\tn_records = log_probabilities.size();\n\t\t\t\t}\n\t\t\t\tlog_probs[s] = log_prob;\n\t\t\t\tlog_probs_baseline[s] = log_prob_baseline;\n\t\t\t}\n\n\t\t\t// Take the average of all samples\n\t\t\tDomainProbability record(\n\t\t\t\tdomain, \n\t\t\t\txt::mean(log_probs)(), \n\t\t\t\txt::mean(log_probs_baseline)(), \n\t\t\t\tn_records\n\t\t\t);\n\t\t\trecords.push_back(record);\n\t\t}\n\n\t\t// Sort records from best to worse evidence\n\t\tsort(records.begin(), records.end(), greater<DomainProbability>()); \n\n\t\t// Create assembly directory if it does not exist\n\t\tstring assembly_domain_prob_out_folder = (\n\t\t\tdataFolder + \"intervention/\" +  intervention + \"/sequences/\" + accession + \"/\"\n\t\t);\n\t\tfilesystem::create_directory(assembly_domain_prob_out_folder);\n\n\t\t// Prepare output writer\n\t\tstring assembly_domain_prob_out_path = (\n\t\t\tassembly_domain_prob_out_folder +\n\t\t\taccession + \"_\" + query + \"_probability_\" + tail + \".csv\"\n\t\t);\n\t\tofstream of(assembly_domain_prob_out_path);\n\t\tauto writer = make_csv_writer(of);\n\t\twriter << DomainProbability::RecordHeader();\n\n\t\t// Write assembly outputs\n\t\tfor (auto& record : records) {\n\t\t\twriter << record.Record();\n\t\t}\n\t}\n\treturn true;\n}\n\nbool task_compute_domain_probabilities_per_phylum(\n\tconst int task_nb,\n\tconst string& query, \n\tconst string& tail,\n\tconst string intervention,\n\tconst vector<string>& phyla,\n\tconst unordered_map<string, vector<string>>& assemblies_per_phylum\n) {\n\tcerr << \"Thread \" << task_nb << \" started.\" << endl;\n\n\tstring dataFolder = \"../data/intervention/\" + intervention + \"/\";\n\tstring sequencesFolder = dataFolder + \"sequences/\";\n\tstring phylumFolder = dataFolder + \"phylum/\";\n\tauto n_phyla = phyla.size();\n\n\t// Create phylum directory if it does not exist.\n\tfilesystem::create_directory(phylumFolder);\n\n\tint i = 0;\n\tfor (auto& phylum : phyla) {\n\t\tauto& assembly_ids = assemblies_per_phylum.at(phylum);\n\t\tauto n_assemblies = assembly_ids.size();\n\n\t\tcerr << \"Thread \" << task_nb << \": \";\n\t\tcerr << \"Processing phylum \" << i + 1 << \" / \" << n_phyla;\n\t\tcerr << \": \" << phylum << \" (\" << n_assemblies << \" assemblies)\";\n\t\tcerr << endl;\n\t\t++i;\n\n\t\tset<ProteinDomain> protein_domains;\n\t\tunordered_map<ProteinDomain, vector<DomainProbability>> protein_domain_probs;\n\t\tfor (auto& accession : assembly_ids) {\n\t\t\tstring path = (\n\t\t\t\tsequencesFolder + accession + \"/\" + \n\t\t\t\taccession + \"_\" + query + \"_probability_\" + tail + \".csv\"\n\t\t\t);\n\t\t\tvector<DomainProbability> domains = LoadDomainProbabilities(path);\n\t\t\tfor (auto& domain_prob : domains) {\n\t\t\t\tauto& domain = domain_prob.domain;\n\t\t\t\tprotein_domains.insert(domain);\n\n\t\t\t\tif (protein_domain_probs.find(domain) == protein_domain_probs.end()) {\n\t\t\t\t\tprotein_domain_probs[domain] = vector<DomainProbability>{domain_prob};\n\t\t\t\t} else {\n\t\t\t\t\tprotein_domain_probs[domain].push_back(domain_prob);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tstring phylum_lower = phylum;\n\t\ttransform(phylum_lower.begin(), phylum_lower.end(), phylum_lower.begin(), ::tolower);\n\t\ttransform(phylum_lower.begin(), phylum_lower.end(), phylum_lower.begin(), [](char ch) {\n\t\t    return ch == ' ' ? '_' : ch;\n\t\t});\n\n\t\tstring phylumDir = phylumFolder + phylum_lower + \"/\";\n\n\t\tfilesystem::create_directory(phylumDir);\n\n\t\tstring phylum_domain_prob_out_path = (\n\t\t\tphylumDir + \n\t\t\tphylum_lower + \"_\" + query + \"_probability_\" + tail + \".csv\"\n\t\t);\n\t\tofstream of(phylum_domain_prob_out_path);\n\t\tauto writer = make_csv_writer(of);\n\t\twriter << DomainProbability::RecordHeader();\n\n\t\tvector<DomainProbability> records;\n\t\tfor (auto& domain : protein_domains) {\n\t\t\tauto& domain_probs = protein_domain_probs[domain];\n\t\t\tauto n_probs = domain_probs.size();\n\t\t\txt::xarray<double> log_probs = xt::zeros<double>({n_probs});\n\t\t\txt::xarray<double> log_probs_random = xt::zeros<double>({n_probs});\n\t\t\tfor (int ix = 0; ix < n_probs; ++ix) {\n\t\t\t\tlog_probs[ix] = domain_probs[ix].log_probability;\n\t\t\t\tlog_probs_random[ix] = domain_probs[ix].log_probability_random;\n\t\t\t}\n\n\t\t\tdouble log_prob = product_rule_log(log_probs);\n\t\t\tdouble log_prob_random = product_rule_log(log_probs_random);\n\n\t\t\ttry {\n\t\t\t\tDomainProbability record(\n\t\t\t\t\tdomain, \n\t\t\t\t\tlog_prob, \n\t\t\t\t\tlog_prob_random,\n\t\t\t\t\tn_probs\n\t\t\t\t);\n\t\t\t\trecords.push_back(record);\n\t\t\t}\n\t\t\tcatch (exception& e) {\n\t\t\t\tcerr << \"Thread \" << task_nb << \" | Phylum: \" << phylum << \" | \";\n\t\t\t\tcerr << \"Exception: \" << e.what() << endl;\n\t\t\t\tthrow;\n\t\t\t}\n\t\t}\n\n\t\tsort(records.begin(), records.end(), greater<DomainProbability>()); \n\n\t\tfor (auto& record : records) {\n\t\t\twriter << record.Record();\n\t\t}\n\t}\n\tcerr << \"Thread \" << task_nb << \": DONE\" << endl;\n\treturn true;\n}\n\nvoid compute_intervention(\n\tconst string query, \n\tconst string tail, \n\tconst string intervention,\n\tconst int n_samples,\n\tconst int n_threads\n) {\n\tauto start_clock = system_clock::now();\n\n\tstring dataFolder = \"../data/\";\n\n\tbool complete_genome_only = true;\n\tAssemblies assemblies(dataFolder + \"intervention/\" + \"sample_assemblies.csv\");\n\tauto assembly_ids = assemblies.GetIds();\n\tauto n_per_thread = ceil((double) assembly_ids.size() / (double) n_threads);\n\n\tcerr << \"Processing \" << assemblies.Size() << \" assemblies\" << endl;\n\n\t// \n\t// 1) Proceed with intervention and compute domain probability per assembly.\n\t//\n\tvector<future<bool>> futures;\n\tfor (int i = 0; i < n_threads; ++i) {\n\t\tauto start = assembly_ids.begin() + i * n_per_thread;\n\t\tauto end = assembly_ids.end();\n\t\tint endInt = i * n_per_thread + n_per_thread;\n\t\tif (endInt < assembly_ids.size()) {\n\t\t\tend = assembly_ids.begin() + endInt;\n\t\t}\n\t\tauto ids = vector<string>(start, end);\n\t\tfutures.push_back(async(\n\t\t\ttask_intervention_per_assembly, \n\t\t\ti+1, \n\t\t\tquery, \n\t\t\ttail, \n\t\t\tintervention,\n\t\t\tn_samples,\n\t\t\tids\n\t\t));\n\t}\n\tfor (auto& f : futures) {\n\t\tif(!f.get()) {\n\t\t\tthrow runtime_error(\"Unexpected error while processing assembly output\");\n\t\t}\n\t}\n\n\t// \n\t// 2) Compute probability of domains for each phylum.\n\t//\n\tcerr << \"Processing of domain probabilities per phylum\" << endl;\n\n\tunordered_map<string, vector<string>> assemblies_per_phylum;\n\tfor (auto& assembly_id : assembly_ids) {\n\t\tAssembly& assembly = assemblies.Get(assembly_id);\n\t\tstring phylum = assembly.phylum;\n\t\tif (phylum.empty()) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (assemblies_per_phylum.find(phylum) == assemblies_per_phylum.end()) {\n\t\t\tassemblies_per_phylum[phylum] = vector<string>{assembly_id};\n\t\t} else {\n\t\t\tassemblies_per_phylum[phylum].push_back(assembly_id);\n\t\t}\n\t}\n\n\tset<string> phyla_set;\n\tfor (auto& assembly_id : assembly_ids) {\n\t\tAssembly& assembly = assemblies.Get(assembly_id);\n\t\tstring phylum = assembly.phylum;\n\t\tif (!phylum.empty()) {\n\t\t\tphyla_set.insert(phylum);\n\t\t}\n\t}\n\n\tvector<string> phyla;\n\tphyla.assign(phyla_set.begin(), phyla_set.end());\n\tauto n_phyla = phyla.size();\n\n\tcerr << \"Processing \" << n_phyla << \" phyla\" << endl;\n\tcerr << \"Starting \" << n_threads << \" threads\" << endl;\n\n\tn_per_thread = ceil((double) n_phyla / (double) n_threads);\n\n\tvector<future<bool>> futuresP;\n\tfor (int i = 0; i < n_threads; ++i) {\n\t\tauto start = phyla.begin() + i * n_per_thread;\n\t\tauto end = phyla.end();\n\t\tint endInt = i * n_per_thread + n_per_thread;\n\t\tif (endInt < n_phyla) {\n\t\t\tend = phyla.begin() + endInt;\n\t\t}\n\t\tfuturesP.push_back(async(\n\t\t\ttask_compute_domain_probabilities_per_phylum, \n\t\t\ti+1, \n\t\t\tquery, \n\t\t\ttail, \n\t\t\tintervention,\n\t\t\tvector<string>(start, end),\n\t\t\tassemblies_per_phylum\n\t\t));\n\t}\n\tfor (auto& f : futuresP) {\n\t\tif(!f.get()) {\n\t\t\tthrow runtime_error(\"Unexpected error while processing phylum output\");\n\t\t}\n\t}\n\tauto elapsed = duration_cast<seconds>(system_clock::now() - start_clock).count();\n\tcerr << \"Processing of domain probabilities per phylum is complete\" << endl;\n\tcerr << \"Elapsed: \" << elapsed << \" seconds\" << endl;\n\n\t//\n\t// 3) Compute global probability of domains.\n\t//\n\tcerr << \"Processing of domain probabilities globally\" << endl;\n\tset<ProteinDomain> protein_domains;\n\tunordered_map<ProteinDomain, vector<DomainProbability>> protein_domain_probs;\n\tfor (auto& phylum : phyla) {\n\t\tstring phylum_lower = phylum;\n\t\ttransform(phylum_lower.begin(), phylum_lower.end(), phylum_lower.begin(), ::tolower);\n\t\ttransform(phylum_lower.begin(), phylum_lower.end(), phylum_lower.begin(), [](char ch) {\n\t\t    return ch == ' ' ? '_' : ch;\n\t\t});\n\t\tstring phylumDir = (\n\t\t\tdataFolder + \"intervention/\" + intervention + \"/phylum/\" + phylum_lower + \"/\"\n\t\t);\n\t\tstring phylum_domain_prob_path = (\n\t\t\tphylumDir + \n\t\t\tphylum_lower + \"_\" + query + \"_probability_\" + tail + \".csv\"\n\t\t);\n\n\t\tvector<DomainProbability> domains = LoadDomainProbabilities(phylum_domain_prob_path);\n\t\tfor (auto& domain_prob : domains) {\n\t\t\tauto& domain = domain_prob.domain;\n\t\t\tprotein_domains.insert(domain);\n\n\t\t\tif (protein_domain_probs.find(domain) == protein_domain_probs.end()) {\n\t\t\t\tprotein_domain_probs[domain] = vector<DomainProbability>{domain_prob};\n\t\t\t} else {\n\t\t\t\tprotein_domain_probs[domain].push_back(domain_prob);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst string protein_out_path = (\n\t\tdataFolder + \"intervention/\" + intervention + \"/\" + \n\t\tquery + \"_probability_\" + tail + \".csv\"\n\t);\n\tofstream output_file(protein_out_path);\n\tauto writer = make_csv_writer(output_file);\n\twriter << DomainProbability::RecordHeader();\n\n\txt::xarray<double> uniform_log_prior = xt::eval(\n\t\txt::log(make_uniform_prior(n_phyla))\n\t);\n\n\tvector<DomainProbability> records;\n\tfor (auto& domain : protein_domains) {\n\t\tauto& domain_probs = protein_domain_probs[domain];\n\t\tauto n_probs = domain_probs.size();\n\t\txt::xarray<double> log_probs = xt::zeros<double>({n_phyla});\n\t\txt::xarray<double> log_probs_random = xt::zeros<double>({n_phyla});\n\t\tfor (int ix = 0; ix < n_probs; ++ix) {\n\t\t\tlog_probs[ix] = domain_probs[ix].log_probability;\n\t\t\tlog_probs_random[ix] = domain_probs[ix].log_probability_random;\n\t\t}\n\n\t\tdouble log_prob = marginalization_log(\n\t\t\tuniform_log_prior, \n\t\t\tlog_probs\n\t\t);\n\t\tdouble log_prob_random = marginalization_log(\n\t\t\tuniform_log_prior, \n\t\t\tlog_probs_random\n\t\t);\n\n\t\ttry {\n\t\t\tDomainProbability record(\n\t\t\t\tdomain, \n\t\t\t\tlog_prob, \n\t\t\t\tlog_prob_random,\n\t\t\t\tn_probs\n\t\t\t);\n\t\t\trecords.push_back(record);\n\t\t}\n\t\tcatch (exception& e) {\n\t\t\tcerr << \"Global computation | \";\n\t\t\tcerr << \"Exception: \" << e.what() << endl;\n\t\t\tthrow;\n\t\t}\n\t}\n\n\tsort(records.begin(), records.end(), greater<DomainProbability>()); \n\n\tfor (auto& record : records) {\n\t\twriter << record.Record();\n\t}\n\n\tauto elapsed_final = duration_cast<seconds>(system_clock::now() - start_clock).count();\n\tcerr << \"Elapsed: \" << elapsed_final << \" seconds\" << endl;\n\tcerr << \"DONE\" << endl;\n}\n", "meta": {"hexsha": "279d07e2a4556577e27094838ab611f44540254f", "size": 17563, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/task/intervention_task.cpp", "max_stars_repo_name": "srom/nbias", "max_stars_repo_head_hexsha": "be8cf8dd623038dcf08d38ed3d19f635ee2dbeae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/task/intervention_task.cpp", "max_issues_repo_name": "srom/nbias", "max_issues_repo_head_hexsha": "be8cf8dd623038dcf08d38ed3d19f635ee2dbeae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/task/intervention_task.cpp", "max_forks_repo_name": "srom/nbias", "max_forks_repo_head_hexsha": "be8cf8dd623038dcf08d38ed3d19f635ee2dbeae", "max_forks_repo_licenses": ["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.0300353357, "max_line_length": 95, "alphanum_fraction": 0.690998121, "num_tokens": 4560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850154599562, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2690590574637346}}
{"text": "#include \"dnn.hpp\"\n#include \"fixedwavefunction.hpp\"\n#include \"hardspherewavefunction.hpp\"\n#include \"inputsorter.hpp\"\n#include \"jastrowmcmillian.hpp\"\n#include \"jastroworion.hpp\"\n#include \"jastrowpade.hpp\"\n#include \"rbmsymmetricwavefunction.hpp\"\n#include \"rbmwavefunction.hpp\"\n#include \"simplegaussian.hpp\"\n#include \"wavefunction.hpp\"\n#include \"wavefunctionpooling.hpp\"\n#include \"wavefunctionproduct.hpp\"\n\n#include <Eigen/Dense>\n#include <pybind11/eigen.h>\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n\nnamespace py = pybind11;\n\nvoid init_nn(py::module&);\n\nvoid init_wavefunction(py::module& main)\n{\n    auto m  = main.def_submodule(\"wavefunctions\");\n    m.doc() = R\"doc(\nWavefunctions\n-------------\n\nThe wavefunction module defines a set of pre-built components that can be used to\nset up a variety of different trial wavefunctions.\n\n)doc\";\n\n    init_nn(m);\n\n    py::class_<Wavefunction>(m, \"Wavefunction\", R\"doc(\nThe :class:`Wavefunction` class provides a unified abstraction for all wavefunctions.\n\nAll other code expecting a wavefunction instance will take a :class:`Wavefunction` reference.\n\nIn this context, a trial wavefunction is defied to be a class that can:\n\n- Have zero or more parameters, :math:`\\vec\\alpha`\n- Evaluate given some system configuraiton :math:`\\mathbf{X}`:\n\n.. math::\n    \\text{Evaluation}_\\Psi(\\mathbf{X} = \\Psi(\\mathbf{X})\n\n- Compute the gradient w.r.t. each variational parameter, :math:`\\vec{\\alpha}`:\n\n.. math::\n\n    \\text{Gradient}_\\Psi(\\mathbf{X}) = \\frac{1}{\\Psi(\\mathbf{X})}\n        \\frac{\\partial \\Psi(\\mathbf{X})}{\\partial\\vec\\alpha}\n\n- Compute the drift force w.r.t. particle :math:`k`'s dimensions ional coordinate :math:`l`:\n\n.. math::\n\n    \\text{Drift}_{\\Psi(\\mathbf{X}), k,l} = \\frac{2}{\\Psi(\\mathbf{X})}\n        \\frac{\\partial \\Psi(\\mathbf{X})}{\\partial X_{kl}}\n\n- Compute the laplacian of a system of :math:`N` particles in :math:`D` dimensions:\n\n.. math::\n\n    \\text{Laplacian}_\\Psi(\\mathbf{X}) = \\sum_{k=1}^N\\sum_{l=1}^D\n        \\frac{1}{\\Psi(\\mathbf{X})}\\frac{\\partial^2 \\Psi(\\mathbf{X})}{\\partial X_{kl}^2}\n\n.. note::\n    Wavefunctions are limited to real-valued functions only - there is no\n    support for complex valued wavefunctions at this time.\n\n)doc\")\n\n        .def(\"__call__\", &Wavefunction::operator(), py::arg(\"system\"), R\"doc(\nReturn the evaluation of the wavefunction for the given system\n\n.. math::\n\n    \\text{Evaluation}_\\Psi(\\mathbf{X} = \\Psi(\\mathbf{X})\n)doc\")\n\n        .def(\"gradient\", &Wavefunction::gradient, py::arg(\"system\"), R\"doc(\nReturn the gradient w.r.t. each variational parameter, divided by the evaluation:\n\n.. math::\n    \\text{Gradient}_\\Psi(\\mathbf{X}) = \\frac{1}{\\Psi(\\mathbf{X})}\n        \\frac{\\partial \\Psi(\\mathbf{X})}{\\partial\\vec\\alpha}\n)doc\")\n\n        .def(\"laplacian\", &Wavefunction::laplacian, py::arg(\"system\"), R\"doc(\n\n.. math::\n\n    \\text{Laplacian}_\\Psi(\\mathbf{X}) = \\sum_{k=1}^N\\sum_{l=1}^D\n        \\frac{1}{\\Psi(\\mathbf{X})}\\frac{\\partial^2 \\Psi(\\mathbf{X})}{\\partial X_{kl}^2}\n)doc\")\n        .def(\"drift_force\",\n             py::overload_cast<const System&, int, int>(&Wavefunction::drift_force),\n             py::arg(\"system\"),\n             py::arg(\"k\"),\n             py::arg(\"l\"),\n             R\"doc(\n\nReturn the drift force w.r.t. particle :math:`k`'s dimensions ional coordinate :math:`l`:\n\n.. math::\n\n    \\text{Drift}_{\\Psi(\\mathbf{X}), k, l} = \\frac{2}{\\Psi(\\mathbf{X})}\n        \\frac{\\partial \\Psi(\\mathbf{X})}{\\partial X_{kl}}\n )doc\")\n\n        .def(\"drift_force\",\n             py::overload_cast<const System&>(&Wavefunction::drift_force),\n             py::arg(\"system\"),\n             R\"doc(\nReturn a list of drift forces for all particles and all dimensions.\n\nThe list will be one-dimensional, such that\n:math:`\\text{Drift}_{\\Psi(\\mathbf{X}), k,l}` is at index ``k * D + l``.\n )doc\")\n        .def(\"symmetry_metric\",\n             &Wavefunction::symmetry_metric,\n             py::arg(\"sampler\"),\n             py::arg(\"samples\"),\n             py::arg(\"max_permutations\") = 100,\n             R\"doc(\nReturn an estimate of the symmetry of the wavefunction.\n\nThis is defined as follows:\n\n.. math::\n    S(\\Psi) =  \\frac{\\int_{-\\infty}^\\infty \\text{d}\\mathbf X\\left|\\frac{1}{n!}\n    \\sum_{\\mathbf\\alpha\\in \\mathcal{P}_n} P_{\\mathbf\\alpha}\\Psi\\right|^2}{\\int_{-\\infty}^\\infty\\text{d}\\mathbf X\n    \\max_{\\mathbf\\alpha\\in \\mathcal{P}} \\left|P_{\\mathbf\\alpha}\\Psi\\right|^2}\n\nHere :math:`P_\\mathbf{\\alpha}\\Psi` denotes applying the permutation\n:math:`\\mathbf{\\alpha}` to the input system before evaluating the wavefunction,\nand :math:`\\mathcal{P}_n` is the set of all permutations of :math:`n` particles.\n\nProperties of this metric:\n\n    - It takes values in :math:`[0, 1]`\n    - For symmetric wavefunctions, it equals exactly 1\n    - For anti-symmetric wavefunctions, it equals exactly 0\n    - Any other function evaluates in :math:`(0, 1)`\n\nThis integral will be approximated with Monte Carlo integration using samples from the provided\nsampling strategy, and using the specified number of samples. While the integral is defied over all\npermutations, a maximum of ``max_permutations`` will be used to make it tractable for large ``N``.\n )doc\")\n        .def_property(\n            \"parameters\",\n            py::overload_cast<>(&Wavefunction::get_parameters, py::const_),\n            py::overload_cast<const RowVector&>(&Wavefunction::set_parameters),\n            R\"doc(\nList of all variational parameters. Supports both read and write.\n)doc\");\n\n    py::class_<FixedWavefunction, Wavefunction>(m, \"FixedWavefunction\", R\"doc(\nWrapper for any wavefunction that fixes the variational parameters.\n\nThis means that if this wavefunction is used in a optimization call, its\nparameters will not change. This is useful if parts of a wavefunction should be\nheld constant, while another is allowed to be optimized.\n)doc\")\n        .def(py::init<Wavefunction&>(), py::arg(\"wavefunction\"));\n\n    py::class_<WavefunctionProduct, Wavefunction>(m, \"WavefunctionProduct\", R\"doc(\nDefines a wavefunction that acts like the product of two others.\n\nAll derivatives will be suitably derived, so this is a simple way to produce\ncompound expressions.\n)doc\")\n        .def(py::init<Wavefunction&, Wavefunction&>(),\n             py::arg(\"Psi_1\"),\n             py::arg(\"Psi_2\"));\n\n    py::class_<SumPooling, Wavefunction>(m, \"SumPooling\", R\"doc(\nThis wavefunction expects a wavefunction of two particles,\n:math:`f(\\mathbf{x}_1, \\mathbf{x}_2)`, and represents the following compound\nexpression:\n\n.. math::\n    \\Psi(\\mathbf{X}) = \\sum_{i \\neq j}^N f(\\mathbf{X}_i, \\mathbf{X}_j)\n\nThis is guaranteed to produce a permutation symmetric wavefunction, given any suitable\ninner wavefunction :math:`f`.\n)doc\")\n        .def(py::init<Wavefunction&>());\n\n    py::class_<InputSorter, Wavefunction>(m, \"InputSorter\")\n        .def(py::init<Wavefunction&>());\n\n    py::class_<SimpleGaussian, Wavefunction>(m, \"SimpleGaussian\", R\"doc(\nA product of gaussians:\n\n.. math::\n\n    \\Psi(\\mathbf{X}) = \\prod_{i=1}^N e^{-\\alpha ||\\mathbf{X}_i||^2}\n\nThe only variational parameter is :math:`\\alpha`.\n\nFor 3D systems, an optional *fixed* parameter :math:`\\beta` can be specified, which changes the above definition to:\n\n.. math::\n\n    \\Psi(\\mathbf{X}) = \\prod_{i=1}^N e^{-\\alpha\\left(X_{i,1}^2 + X_{i,2}^2 + \\beta X_{i,3}^2\\right)}\n)doc\")\n        .def(py::init<Real, Real>(), py::arg(\"alpha\") = 0.5, py::arg(\"beta\") = 1);\n\n    py::class_<HardSphereWavefunction, SimpleGaussian>(\n        m, \"HardSphereWavefunction\", R\"doc(\nA product of gaussians and pairwise correlation factors:\n\n.. math::\n\n    \\Psi(\\mathbf{X}) = \\prod_{i=1}^N e^{-\\alpha\\left(X_{i,1}^2 + X_{i,2}^2 + \\beta X_{i,3}^2\\right)}\n        \\prod_{j = i + 1}^{N} \\begin{cases} 0 &\\text{if}\\ \\  ||\\mathbf{X}_i - \\mathbf{X}_j|| \\leq a\\\\\n                                            1 - \\frac{a}{||\\mathbf{X}_i - \\mathbf{X}_j||} &\\text{otherwise}\n                              \\end{cases}\n\nSimilarly to :class:`SimpleGaussian`, the only variational parameter is\n:math:`\\alpha`, while the other two parameters :math:`\\beta` and :math:`a` are\nassumed constant.\n)doc\")\n        .def(py::init<Real, Real, Real>(),\n             py::arg(\"alpha\") = 0.5,\n             py::arg(\"beta\")  = 1,\n             py::arg(\"a\")     = 0);\n\n    py::class_<JastrowPade, Wavefunction>(m, \"JastrowPade\", R\"doc(\nA correlation term meant to be suitable for particles in a harmonic oscillator potential with\na repulsive Coulomb force causing interactions:\n\n.. math::\n\n    \\Psi(\\mathbf{X}) = \\prod_{i < j}^N e^{\\frac{\\alpha r_ij}{1 + \\beta r_ij}}\n\n)doc\")\n        .def(py::init<Real, Real, bool>(),\n             py::arg(\"alpha\")             = 0.5,\n             py::arg(\"beta\")              = 1,\n             py::arg(\"alpha_is_constant\") = true);\n\n    py::class_<JastrowOrion, Wavefunction>(m, \"JastrowOrion\", R\"doc(\nA correlation term meant to be suitable for particles in a harmonic oscillator potential with\na repulsive Coulomb force causing interactions:\n\n.. math::\n\n    \\Psi(\\mathbf{X}) = \\prod_{i < j}^N\n        e^{-\\frac{\\beta^2}{2}||\\mathbf{X_i}-\\mathbf{X_j}||^2 +\n            |\\beta\\gamma|||\\mathbf{X_i}-\\mathbf{X_j}||}\n\n\n)doc\")\n        .def(py::init<Real, Real>(), py::arg(\"beta\") = 1.0, py::arg(\"gamma\") = 0);\n\n    py::class_<JastrowMcMillian, Wavefunction>(m, \"JastrowMcMillian\")\n        .def(py::init<int, Real, Real>(), py::arg(\"n\"), py::arg(\"beta\"), py::arg(\"L\"));\n\n    py::class_<RBMWavefunction, Wavefunction>(m, \"RBMWavefunction\")\n        .def(py::init<int, int, Real, Real>(),\n             py::arg(\"M\"),\n             py::arg(\"N\"),\n             py::arg(\"sigma2\")      = 1,\n             py::arg(\"root_factor\") = 1);\n\n    py::class_<RBMSymmetricWavefunction, Wavefunction>(m, \"RBMSymmetricWavefunction\")\n        .def(py::init<int, int, int, Real, Real>(),\n             py::arg(\"M\"),\n             py::arg(\"N\"),\n             py::arg(\"f\"),\n             py::arg(\"sigma2\")      = 1,\n             py::arg(\"root_factor\") = 1);\n\n    py::class_<Dnn, Wavefunction>(m, \"Dnn\")\n        .def(py::init<>())\n        .def(\"add_layer\", &Dnn::addLayer)\n        .def_property_readonly(\"layers\", &Dnn::getLayers);\n}\n", "meta": {"hexsha": "9eb3fd407460f5e8884e50993bda3a44101c4f9c", "size": 10078, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "qflow/wavefunctions/pywavefunction.cpp", "max_stars_repo_name": "johanere/qflow", "max_stars_repo_head_hexsha": "5453cd5c3230ad7f082adf9ec1aea63ab0a4312a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-07-24T21:46:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-11T18:18:24.000Z", "max_issues_repo_path": "qflow/wavefunctions/pywavefunction.cpp", "max_issues_repo_name": "johanere/qflow", "max_issues_repo_head_hexsha": "5453cd5c3230ad7f082adf9ec1aea63ab0a4312a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2019-02-19T10:49:26.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-18T09:42:13.000Z", "max_forks_repo_path": "qflow/wavefunctions/pywavefunction.cpp", "max_forks_repo_name": "bsamseth/FYS4411", "max_forks_repo_head_hexsha": "72b879e7978364498c48fc855b5df676c205f211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-04T15:17:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T16:37:38.000Z", "avg_line_length": 35.2377622378, "max_line_length": 116, "alphanum_fraction": 0.6305814646, "num_tokens": 3016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.26863315835217727}}
{"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 <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/recursive_matrix_mult.hpp>\n\n\n#ifdef __INTEL_COMPILER\n#  define MTL_DECL16  __declspec(align(16))\n#else\n#  define MTL_DECL16\n#endif\n\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\n    // Bitmasks: \n    const unsigned long morton_mask= generate_mask<true, 0, row_major, 0>::value,\n\tmorton_z_mask= generate_mask<false, 0, row_major, 0>::value,\n\tdoppled_16_row_mask= generate_mask<true, 4, row_major, 0>::value,\n\tdoppled_16_col_mask= generate_mask<true, 4, col_major, 0>::value,\n\tdoppled_32_row_mask= generate_mask<true, 5, row_major, 0>::value,\n\tdoppled_32_col_mask= generate_mask<true, 5, col_major, 0>::value,\n\tdoppled_z_32_row_mask= generate_mask<false, 5, row_major, 0>::value,\n\tdoppled_z_32_col_mask= generate_mask<false, 5, col_major, 0>::value,\n\tdoppled_64_row_mask= generate_mask<true, 6, row_major, 0>::value,\n\tdoppled_64_col_mask= generate_mask<true, 6, col_major, 0>::value,\n\tdoppled_z_64_row_mask= generate_mask<false, 6, row_major, 0>::value,\n\tdoppled_z_64_col_mask= generate_mask<false, 6, col_major, 0>::value,\n\tdoppled_128_row_mask= generate_mask<true, 7, row_major, 0>::value,\n\tdoppled_128_col_mask= generate_mask<true, 7, col_major, 0>::value,\n\tshark_32_row_mask= generate_mask<true, 5, row_major, 1>::value,\n\tshark_32_col_mask= generate_mask<true, 5, col_major, 1>::value,\n\tshark_z_32_row_mask= generate_mask<false, 5, row_major, 1>::value,\n\tshark_z_32_col_mask= generate_mask<false, 5, col_major, 1>::value,\n\tshark_64_row_mask= generate_mask<true, 6, row_major, 1>::value,\n\tshark_64_col_mask= generate_mask<true, 6, col_major, 1>::value,\n\tshark_z_64_row_mask= generate_mask<false, 6, row_major, 1>::value,\n\tshark_z_64_col_mask= generate_mask<false, 6, col_major, 1>::value;\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;\ntypedef gen_tiling_dense_mat_mat_mult_t<2, 4, assign::plus_sum>  tiling_24_base_mult_t;\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\tfor (; start.elapsed() < 1; reps++)\n\t    mult(a, b, c);\n\tdouble time= start.elapsed() / double(reps);\n\tprint_time_and_mflops(time, a.num_rows());\n\tif (time > max_time)\n\t    enabled[i]= 0;\n    } else\n\tstd::cout << \", , \";\n}\n\n\n\ntemplate <typename Functor, typename Result, typename Arg1, typename Arg2, typename Arg3>\nstruct no_inline3\n{\n    Result operator()(Arg1& arg1, Arg2& arg2, Arg3& arg3)\n    {\n\tstatic Functor* f= new(Functor);  \n\treturn apply(f, arg1, arg2, arg3);\n    }\n\n    Result apply(Functor* f, Arg1& arg1, Arg2& arg2, Arg3& arg3)\n    {\n\treturn (*f)(arg1, arg2, arg3);\n    }\n};\n\n#if 0\n// Specialization not needed, at least not with g++\ntemplate <typename Functor, typename Arg1, typename Arg2, typename Arg3>\nstruct no_inline3<Functor, void, Arg1, Arg2, Arg3>\n{\n   \n    void operator()(Arg1& arg1, Arg2& arg2, Arg3& arg3)\n    {\n\tFunctor* f= new(Functor);\n\tapply(f, arg1, arg2, arg3);\n\tfree(f);\n    }\n\n    void apply(Functor* f, Arg1& arg1, Arg2& arg2, Arg3& arg3)\n    {\n\t(*f)(arg1, arg2, arg3);\n    }\n};\n#endif\n\n#if 0\nvoid hybrid_ext_mult_44(const morton_dense<double,  doppled_64_row_mask>& a, \n\t\t\tconst morton_dense<double,  doppled_64_col_mask>& b,\n\t\t\tmorton_dense<double,  doppled_64_row_mask>& c);\n#endif\n\nvoid dense_ext_mult_44(const dense2D<double>& a,\n\t\t       const dense2D<double, mat::parameters<col_major> >& b,\n\t\t       dense2D<double>& c);\n \nstruct ext_mult_44\n{\n#if 0\n    void operator()(const morton_dense<double,  doppled_64_row_mask>& a, \n\t\t    const morton_dense<double,  doppled_64_col_mask>& b,\n\t\t    morton_dense<double,  doppled_64_row_mask>& c)\n    {\n\thybrid_ext_mult_44(a, b, c);\n    }\n#endif\n\n    void operator()(const dense2D<double>& a,\n\t\t    const dense2D<double, mat::parameters<col_major> >& b,\n\t\t    dense2D<double>& c)\n    {\n\tdense_ext_mult_44(a, b, c);\n    }\n};\n\ntypedef dense2D<double> rmt;\ntypedef dense2D<double, mat::parameters<col_major> > cmt;\n\n// C must have even dimensions\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC>\nvoid mult_simple_ptu22t(const MatrixA& a, const MatrixB& b, MatrixC& c)\n{\n    typedef typename MatrixC::value_type  value_type;\n    const value_type z= math::zero(c[0][0]);    // if this are matrices we need their size\n    \n    set_to_zero(c);\n\n    // Temporary solution; dense matrices need to return const referencens\n    MatrixA& aref= const_cast<MatrixA&>(a);\n    MatrixB& bref= const_cast<MatrixB&>(b);\n\n    size_t ari= &aref(1, 0) - &aref(0, 0), // how much is the offset of A's entry increased by incrementing row\n\taci= &aref(0, 1) - &aref(0, 0), bri= &bref(1, 0) - &bref(0, 0), bci= &bref(0, 1) - &bref(0, 0);\n\n    for (unsigned i= 0; i < c.num_rows(); i+=2)\n\tfor (unsigned k= 0; k < c.num_cols(); k+=2) {\n\t    int ld= b.num_rows();\n\t    value_type tmp00= z, tmp01= z, tmp10= z, tmp11= z;\n\n\t    MTL_DECL16 const value_type *begin_a= &aref[i][0], *end_a= &aref[i][a.num_cols()];\n\t    MTL_DECL16 const value_type *begin_b= &bref[0][k];\n\t    for (; begin_a != end_a; begin_a+= aci, begin_b+= bri) {\n\t\ttmp00+= *begin_a * *begin_b;\n\t\ttmp01+= *begin_a * *(begin_b+bci);\n\t\ttmp10+= *(begin_a+ari) * *begin_b;\n\t\ttmp11+= *(begin_a+ari) * *(begin_b+bci);\n\t    }\n\t    assign::assign_sum::update(c[i][k], tmp00);\n\t    assign::assign_sum::update(c[i][k+1], tmp01);\n\t    assign::assign_sum::update(c[i+1][k], tmp10);\n\t    assign::assign_sum::update(c[i+1][k+1], tmp11);\n\n#if 0\n\t    c[i][k]= tmp00; c[i][k+1]= tmp01;\n\t    c[i+1][k]= tmp10; c[i+1][k+1]= tmp11;\n#endif\n\t}\n}\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    dense2D<double> dense(4, 4);\n    dense2D<double, mat::parameters<col_major> >    denseb(4, 4);\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    gen_recursive_dense_mat_mat_mult_t<tiling_24_base_mult_t> mult_24;\n\n    typedef gen_tiling_22_dense_mat_mat_mult_ft<Matrix, MatrixB, Matrix, assign::plus_sum> \n      tiling_22_t;\n    typedef no_inline3<tiling_22_t, void, const Matrix, const MatrixB, Matrix> tiling_22_no_inline_t;\n\n    typedef gen_tiling_44_dense_mat_mat_mult_ft<Matrix, MatrixB, Matrix, assign::plus_sum> \n      tiling_44_t;\n    typedef no_inline3<tiling_44_t, void, const Matrix, const MatrixB, Matrix> tiling_44_no_inline_t;\n\n    gen_recursive_dense_mat_mat_mult_t<ext_mult_44>           rec_ext_mult_44;\n\n    typedef typename base_case_matrix<Matrix, test64_t>::type    BaseMatrix;\n    typedef typename base_case_matrix<MatrixB, test64_t>::type   BaseMatrixB;\n    typedef no_inline3<tiling_44_t, void, const BaseMatrix, const BaseMatrixB, BaseMatrix> tiling_44_base_t;\n    gen_recursive_dense_mat_mat_mult_t<tiling_44_base_mult_t>    rec_no_inline_mult_44;\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    single_measure(matrix, matrixb, matrix, tiling_22_no_inline_t(), size, enabled, 3);\n    single_measure(matrix, matrixb, matrix, tiling_44_no_inline_t(), size, enabled, 4);\n    single_measure(matrix, matrixb, matrix, rec_ext_mult_44, size, enabled, 5);\n    single_measure(matrix, matrixb, matrix, rec_no_inline_mult_44, size, enabled, 6);\n    single_measure(dense, denseb, dense, tiling_22_base_mult_t(), size, enabled, 7);\n    single_measure(dense, denseb, dense, tiling_44_base_mult_t(), size, enabled, 8);\n    single_measure(dense, denseb, dense, mult_simple_ptu22t<rmt, cmt, rmt>, size, enabled, 9);\n    //single_measure(matrix, matrixb, matrix, mult_24, size, enabled, 10);\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\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\\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\n    std::vector<std::string> scenarii;\n    scenarii.push_back(string(\"Comparing different unrolling for hybrid row-major matrices\"));\n\n    using std::cout;\n    if (argc < 3) {\n\tcerr << \"usage: recursive_mult_timing  <steps> <max_size>\\n\"; \n\texit(1);\n    }\n    unsigned int steps= atoi(argv[1]), max_size= atoi(argv[2]), size= 32; \n    series(steps, max_size, measure_unrolling_hybrid, scenarii[0]);\n\n\n    return 0; \n\n}\n \n\n", "meta": {"hexsha": "455554023530ee4dbee691be73aac00a4989b1bc", "size": 11098, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/timing/no_inline_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/no_inline_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/no_inline_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": 35.1202531646, "max_line_length": 111, "alphanum_fraction": 0.7041809335, "num_tokens": 3427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2685744434144668}}
{"text": "#include <trajopt_utils/macros.h>\nTRAJOPT_IGNORE_WARNINGS_PUSH\n#include <Eigen/Core>\nTRAJOPT_IGNORE_WARNINGS_POP\n\n#include <trajopt_sco/expr_ops.hpp>\n#include <trajopt_sco/modeling_utils.hpp>\n#include <trajopt_utils/eigen_conversions.hpp>\n\n#include \"trajopt/trajectory_costs.hpp\"\n\nnamespace\n{\n/** @brief Returns the difference between each row of a matrixXd and the row before */\nstatic Eigen::MatrixXd diffAxis0(const Eigen::MatrixXd& in)\n{\n  return in.middleRows(1, in.rows() - 1) - in.middleRows(0, in.rows() - 1);\n}\n}  // namespace\n\nnamespace trajopt\n{\n//////////// Joint cost functions /////////////////\n\n//////////////////// Position /////////////////////\nJointPosEqCost::JointPosEqCost(const VarArray& vars, const Eigen::VectorXd& coeffs, const Eigen::VectorXd& targets,\n                               int& first_step, int& last_step)\n  : Cost(\"JointPosEq\"), vars_(vars), coeffs_(coeffs), targets_(targets), first_step_(first_step), last_step_(last_step)\n{\n  for (int i = first_step_; i <= last_step_; ++i)\n  {\n    for (int j = 0; j < vars.cols(); ++j)\n    {\n      // pos = x1 - targ\n      sco::AffExpr pos;\n      sco::exprInc(pos, sco::exprMult(vars(i, j), 1));\n      sco::exprDec(pos, targets_[j]);\n      // expr_ = coeff * vel^2\n      sco::exprInc(expr_, sco::exprMult(sco::exprSquare(pos), coeffs_[j]));\n    }\n  }\n}\ndouble JointPosEqCost::value(const DblVec& xvec)\n{\n  // Convert vector from optimization to trajectory\n  Eigen::MatrixXd traj = (getTraj(xvec, vars_));\n  // Takes diff b/n the subsequent rows and subtract each row by the targets_ vector\n  Eigen::MatrixXd diff =\n      (traj.block(first_step_, 0, last_step_ - first_step_ + 1, traj.cols())).rowwise() - targets_.transpose();\n  // Element-wise square it, multiply it by a diagonal matrix of coefficients, and sums output\n  return (diff.array().square().matrix() * coeffs_.asDiagonal()).sum();\n}\nsco::ConvexObjectivePtr JointPosEqCost::convex(const DblVec& /*x*/, sco::Model* model)\n{\n  sco::ConvexObjectivePtr out(new sco::ConvexObjective(model));\n  out->addQuadExpr(expr_);\n  return out;\n}\n\nJointPosIneqCost::JointPosIneqCost(const VarArray& vars, const Eigen::VectorXd& coeffs, const Eigen::VectorXd& targets,\n                                   const Eigen::VectorXd& upper_tols, const Eigen::VectorXd& lower_tols,\n                                   int& first_step, int& last_step)\n  : Cost(\"JointPosIneq\")\n  , vars_(vars)\n  , coeffs_(coeffs)\n  , upper_tols_(upper_tols)\n  , lower_tols_(lower_tols)\n  , targets_(targets)\n  , first_step_(first_step)\n  , last_step_(last_step)\n{\n  for (int i = first_step_; i <= last_step_; ++i)\n  {\n    for (int j = 0; j < vars.cols(); ++j)\n    {\n      sco::AffExpr expr;\n      sco::AffExpr expr_neg;\n      // pos = x1 - targ\n      sco::AffExpr pos;\n      sco::exprInc(pos, sco::exprMult(vars(i, j), 1));\n      sco::exprDec(pos, targets_[j]);\n      sco::exprInc(expr, upper_tols_[j]);  // expr_ = upper_tol\n\n      // Form upper limit expr = - (upper_tol-(vel-targ))\n      sco::exprDec(expr, pos);           // expr = upper_tol_- (vel - targets_)\n      sco::exprScale(expr, -coeffs[j]);  // expr = - (upper_tol_- (vel - targets_)) * coeffs_\n      expr_vec_.push_back(expr);\n\n      // Form upper limit expr = - (upper_tol-(vel-targ))\n      sco::exprDec(expr_neg, pos);          // expr = lower_tol_- (vel - targets_)\n      sco::exprScale(expr_neg, coeffs[j]);  // expr = (lower_tol_- (vel - targets_)) * coeffs_\n      expr_vec_.push_back(expr_neg);\n    }\n  }\n}\n\ndouble JointPosIneqCost::value(const DblVec& xvec)\n{\n  // Convert vector from optimization to trajectory\n  Eigen::MatrixXd traj = getTraj(xvec, vars_);\n  // Takes diff b/n the subsequent rows to get velocity\n  Eigen::MatrixXd pos = traj.block(first_step_, 0, last_step_ - first_step_ + 1, traj.cols());\n  // Subtract targets to center about 0 and then subtract from tolerance\n  Eigen::MatrixXd diff0 = (pos.rowwise() - targets_.transpose());\n  Eigen::MatrixXd diff1 = (diff0.rowwise() - upper_tols_.transpose()) * coeffs_.asDiagonal();\n  Eigen::MatrixXd diff2 = ((diff0 * -1).rowwise() + lower_tols_.transpose()) * coeffs_.asDiagonal();\n  // Applies hinge, multiplies it by a diagonal matrix of coefficients, sums each corresponding value, and converts to\n  // vector\n  return diff1.cwiseMax(0).sum() + diff2.cwiseMax(0).sum();\n}\n\nsco::ConvexObjectivePtr JointPosIneqCost::convex(const DblVec& /*x*/, sco::Model* model)\n{\n  sco::ConvexObjectivePtr out(new sco::ConvexObjective(model));\n  // Add hinge cost. Set the coefficient to 1 here since we include it in the AffExpr already\n  // This is necessary since we want a seperate coefficient per joint\n  for (sco::AffExpr& expr : expr_vec_)\n  {\n    out->addHinge(expr, 1);\n  }\n  return out;\n}\n\nJointPosEqConstraint::JointPosEqConstraint(const VarArray& vars, const Eigen::VectorXd& coeffs,\n                                           const Eigen::VectorXd& targets, int& first_step, int& last_step)\n  : EqConstraint(\"JointPosEq\")\n  , vars_(vars)\n  , coeffs_(coeffs)\n  , targets_(targets)\n  , first_step_(first_step)\n  , last_step_(last_step)\n{\n  for (int i = first_step_; i <= last_step_; ++i)\n  {\n    for (int j = 0; j < vars.cols(); ++j)\n    {\n      // pos = x1 - targ\n      sco::AffExpr pos;\n      sco::exprInc(pos, sco::exprMult(vars(i, j), 1));\n      sco::exprDec(pos, targets_[j]);\n      // expr_ = coeff * vel - Not squared b/c QuadExpr cnt not yet supported (TODO)\n      expr_vec_.push_back(sco::exprMult(pos, coeffs_[j]));\n    }\n  }\n}\n\nDblVec JointPosEqConstraint::value(const DblVec& xvec)\n{\n  // Convert vector from optimization to trajectory\n  Eigen::MatrixXd traj = getTraj(xvec, vars_);\n  // Takes diff b/n the subsequent rows and subtract each row by the targets_ vector\n  Eigen::MatrixXd diff =\n      (traj.block(first_step_, 0, last_step_ - first_step_ + 1, traj.cols())).rowwise() - targets_.transpose();\n  // Squares it, multiplies it by a diagonal matrix of coefficients, and converts to vector\n  return util::toDblVec((diff.array().square()).matrix() * coeffs_.asDiagonal());\n}\nsco::ConvexConstraintsPtr JointPosEqConstraint::convex(const DblVec& /*x*/, sco::Model* model)\n{\n  sco::ConvexConstraintsPtr out(new sco::ConvexConstraints(model));\n  for (sco::AffExpr& expr : expr_vec_)\n  {\n    out->addEqCnt(expr);\n  }\n  return out;\n}\n\nJointPosIneqConstraint::JointPosIneqConstraint(const VarArray& vars, const Eigen::VectorXd& coeffs,\n                                               const Eigen::VectorXd& targets, const Eigen::VectorXd& upper_tols,\n                                               const Eigen::VectorXd& lower_tols, int& first_step, int& last_step)\n  : IneqConstraint(\"JointPosIneq\")\n  , vars_(vars)\n  , coeffs_(coeffs)\n  , upper_tols_(upper_tols)\n  , lower_tols_(lower_tols)\n  , targets_(targets)\n  , first_step_(first_step)\n  , last_step_(last_step)\n{\n  for (int i = first_step_; i <= last_step_; ++i)\n  {\n    for (int j = 0; j < vars.cols(); ++j)\n    {\n      sco::AffExpr expr;\n      sco::AffExpr expr_neg;\n      // pos = x1 - targ\n      sco::AffExpr pos;\n      sco::exprInc(pos, sco::exprMult(vars(i, j), 1));\n      sco::exprDec(pos, targets_[j]);\n      sco::exprInc(expr, upper_tols_[j]);  // expr_ = upper_tol\n\n      // Form upper limit expr = - (upper_tol-(vel-targ))\n      sco::exprDec(expr, pos);           // expr = upper_tol_- (vel - targets_)\n      sco::exprScale(expr, -coeffs[j]);  // expr = - (upper_tol_- (vel - targets_)) * coeffs_\n      expr_vec_.push_back(expr);\n\n      // Form lower limit expr = (upper_tol-(vel-targ))\n      sco::exprDec(expr_neg, pos);          // expr = lower_tol_- (vel - targets_)\n      sco::exprScale(expr_neg, coeffs[j]);  // expr = (lower_tol_- (vel - targets_)) * coeffs_\n      expr_vec_.push_back(expr_neg);\n    }\n  }\n}\n\nDblVec JointPosIneqConstraint::value(const DblVec& xvec)\n{\n  // Convert vector from optimization to trajectory\n  Eigen::MatrixXd traj = getTraj(xvec, vars_);\n  // Takes diff b/n the subsequent rows to get velocity\n  Eigen::MatrixXd pos = diffAxis0(traj.block(first_step_, 0, last_step_ - first_step_ + 1, traj.cols()));\n  // Subtract targets to center about 0 and then subtract from tolerance\n  Eigen::MatrixXd diff0 = (pos.rowwise() - targets_.transpose());\n  Eigen::MatrixXd diff1 = (diff0.rowwise() - upper_tols_.transpose()) * coeffs_.asDiagonal();\n  Eigen::MatrixXd diff2 = ((diff0 * -1).rowwise() + lower_tols_.transpose()) * coeffs_.asDiagonal();\n  // Applies hinge, multiplies it by a diagonal matrix of coefficients, sums each corresponding value, and converts to\n  // vector\n  Eigen::MatrixXd out(diff1.rows(), diff1.cols() + diff2.cols());\n  out << diff1, diff2;\n  return util::toDblVec(out);\n}\n\nsco::ConvexConstraintsPtr JointPosIneqConstraint::convex(const DblVec& /*x*/, sco::Model* model)\n{\n  sco::ConvexConstraintsPtr out(new sco::ConvexConstraints(model));\n  // Add hinge cost. Set the coefficient to 1 here since we include it in the AffExpr already\n  // This is necessary since we want a seperate coefficient per joint\n  for (sco::AffExpr& expr : expr_vec_)\n  {\n    out->addIneqCnt(expr);\n  }\n  return out;\n}\n\n//////////////////// Velocity /////////////////////\nJointVelEqCost::JointVelEqCost(const VarArray& vars, const Eigen::VectorXd& coeffs, const Eigen::VectorXd& targets,\n                               int& first_step, int& last_step)\n  : Cost(\"JointVelEq\"), vars_(vars), coeffs_(coeffs), targets_(targets), first_step_(first_step), last_step_(last_step)\n{\n  for (int i = first_step_; i <= last_step_ - 1; ++i)\n  {\n    for (int j = 0; j < vars.cols(); ++j)\n    {\n      // vel = (x2 - x1) - targ\n      sco::AffExpr vel;\n      sco::exprInc(vel, sco::exprMult(vars(i, j), -1));\n      sco::exprInc(vel, sco::exprMult(vars(i + 1, j), 1));\n      exprDec(vel, targets_[j]);\n      // expr_ = coeff * vel^2\n      exprInc(expr_, exprMult(exprSquare(vel), coeffs_[j]));\n    }\n  }\n}\ndouble JointVelEqCost::value(const DblVec& xvec)\n{\n  // Convert vector from optimization to trajectory\n  Eigen::MatrixXd traj = (getTraj(xvec, vars_));\n  // Takes diff b/n the subsequent rows and subtract each row by the targets_ vector\n  Eigen::MatrixXd diff = (diffAxis0(traj.block(first_step_, 0, last_step_ - first_step_ + 1, traj.cols()))).rowwise() -\n                         targets_.transpose();\n  // Element-wise square it, multiply it by a diagonal matrix of coefficients, and sums output\n  return (diff.array().square().matrix() * coeffs_.asDiagonal()).sum();\n}\nsco::ConvexObjectivePtr JointVelEqCost::convex(const DblVec& /*x*/, sco::Model* model)\n{\n  sco::ConvexObjectivePtr out(new sco::ConvexObjective(model));\n  out->addQuadExpr(expr_);\n  return out;\n}\n\nJointVelIneqCost::JointVelIneqCost(const VarArray& vars, const Eigen::VectorXd& coeffs, const Eigen::VectorXd& targets,\n                                   const Eigen::VectorXd& upper_tols, const Eigen::VectorXd& lower_tols,\n                                   int& first_step, int& last_step)\n  : Cost(\"JointVelIneq\")\n  , vars_(vars)\n  , coeffs_(coeffs)\n  , upper_tols_(upper_tols)\n  , lower_tols_(lower_tols)\n  , targets_(targets)\n  , first_step_(first_step)\n  , last_step_(last_step)\n{\n  for (int i = first_step_; i <= last_step_ - 1; ++i)\n  {\n    for (int j = 0; j < vars.cols(); ++j)\n    {\n      // vel = (x2 - x1) - targ\n      sco::AffExpr vel;\n      sco::AffExpr expr;\n      sco::AffExpr expr_neg;\n      sco::exprInc(vel, sco::exprMult(vars(i, j), -1));\n      sco::exprInc(vel, sco::exprMult(vars(i + 1, j), 1));\n      sco::exprDec(vel, targets_[j]);  // offset to center about 0\n\n      // Form upper limit expr = - (upper_tol-(vel-targ))\n      sco::exprInc(expr, upper_tols_[j]);  // expr_ = upper_tol\n      sco::exprDec(expr, vel);             // expr = upper_tol_- (vel - targets_)\n      sco::exprScale(expr, -coeffs[j]);    // expr = - (upper_tol_- (vel - targets_)) * coeffs_\n      expr_vec_.push_back(expr);\n\n      // Form lower limit expr =  (upper_tol-(vel-targ))\n      sco::exprInc(expr_neg, lower_tols_[j]);  // expr_ = lower_tol_\n      sco::exprDec(expr_neg, vel);             // expr = lower_tol_- (vel - targets_)\n      sco::exprScale(expr_neg, coeffs[j]);     // expr = (lower_tol_- (vel - targets_)) * coeffs_\n      expr_vec_.push_back(expr_neg);\n    }\n  }\n}\n\ndouble JointVelIneqCost::value(const DblVec& xvec)\n{\n  // Convert vector from optimization to trajectory\n  Eigen::MatrixXd traj = getTraj(xvec, vars_);\n  // Takes diff b/n the subsequent rows to get velocity\n  Eigen::MatrixXd vel = diffAxis0(traj.block(first_step_, 0, last_step_ - first_step_ + 1, traj.cols()));\n  // Subtract targets_ to center about 0 and then subtract from tolerance\n  Eigen::MatrixXd diff0 = (vel.rowwise() - targets_.transpose());\n  Eigen::MatrixXd diff1 = (diff0.rowwise() - upper_tols_.transpose()) * coeffs_.asDiagonal();\n  Eigen::MatrixXd diff2 = ((diff0 * -1).rowwise() + lower_tols_.transpose()) * coeffs_.asDiagonal();\n  // Applies hinge, multiplies it by a diagonal matrix of coefficients, sums each corresponding value, and converts to\n  // vector\n  return diff1.cwiseMax(0).sum() + diff2.cwiseMax(0).sum();\n}\n\nsco::ConvexObjectivePtr JointVelIneqCost::convex(const DblVec& /*x*/, sco::Model* model)\n{\n  sco::ConvexObjectivePtr out(new sco::ConvexObjective(model));\n  // Add hinge cost. Set the coefficient to 1 here since we include it in the AffExpr already\n  // This is necessary since we want a seperate coefficient per joint\n  for (sco::AffExpr& expr : expr_vec_)\n  {\n    out->addHinge(expr, 1);\n  }\n  return out;\n}\n\nJointVelEqConstraint::JointVelEqConstraint(const VarArray& vars, const Eigen::VectorXd& coeffs,\n                                           const Eigen::VectorXd& targets, int& first_step, int& last_step)\n  : EqConstraint(\"JointVelEq\")\n  , vars_(vars)\n  , coeffs_(coeffs)\n  , targets_(targets)\n  , first_step_(first_step)\n  , last_step_(last_step)\n{\n  for (int i = first_step_; i <= last_step_ - 1; ++i)\n  {\n    for (int j = 0; j < vars.cols(); ++j)\n    {\n      // vel = (x2 - x1) - targ\n      sco::AffExpr vel;\n      sco::exprInc(vel, sco::exprMult(vars(i, j), -1));\n      sco::exprInc(vel, sco::exprMult(vars(i + 1, j), 1));\n      sco::exprDec(vel, targets_[j]);\n      // expr_ = coeff * vel - Not squared b/c QuadExpr cnt not yet supported (TODO)\n      expr_vec_.push_back(sco::exprMult(vel, coeffs_[j]));\n    }\n  }\n}\n\nDblVec JointVelEqConstraint::value(const DblVec& xvec)\n{\n  // Convert vector from optimization to trajectory\n  Eigen::MatrixXd traj = getTraj(xvec, vars_);\n  // Takes diff b/n the subsequent rows and subtract each row by the targets_ vector\n  Eigen::MatrixXd diff = (diffAxis0(traj.block(first_step_, 0, last_step_ - first_step_ + 1, traj.cols()))).rowwise() -\n                         targets_.transpose();\n  // Squares it, multiplies it by a diagonal matrix of coefficients, and converts to vector\n  return util::toDblVec((diff.array().square()).matrix() * coeffs_.asDiagonal());\n}\nsco::ConvexConstraintsPtr JointVelEqConstraint::convex(const DblVec& /*x*/, sco::Model* model)\n{\n  sco::ConvexConstraintsPtr out(new sco::ConvexConstraints(model));\n  for (sco::AffExpr& expr : expr_vec_)\n  {\n    out->addEqCnt(expr);\n  }\n  return out;\n}\n\nJointVelIneqConstraint::JointVelIneqConstraint(const VarArray& vars, const Eigen::VectorXd& coeffs,\n                                               const Eigen::VectorXd& targets, const Eigen::VectorXd& upper_tols,\n                                               const Eigen::VectorXd& lower_tols, int& first_step, int& last_step)\n  : IneqConstraint(\"JointVelIneq\")\n  , vars_(vars)\n  , coeffs_(coeffs)\n  , upper_tols_(upper_tols)\n  , lower_tols_(lower_tols)\n  , targets_(targets)\n  , first_step_(first_step)\n  , last_step_(last_step)\n{\n  for (int i = first_step_; i <= last_step_ - 1; ++i)\n  {\n    for (int j = 0; j < vars.cols(); ++j)\n    {\n      // vel = (x2 - x1) - targ\n      sco::AffExpr vel;\n      sco::AffExpr expr;\n      sco::AffExpr expr_neg;\n      sco::exprInc(vel, sco::exprMult(vars(i, j), -1));\n      sco::exprInc(vel, sco::exprMult(vars(i + 1, j), 1));\n      sco::exprDec(vel, targets_[j]);  // offset to center about 0\n\n      // Form upper limit expr = - (upper_tol-(vel-targ))\n      sco::exprInc(expr, upper_tols_[j]);  // expr_ = upper_tol\n      sco::exprDec(expr, vel);             // expr = upper_tol_- (vel - targets_)\n      sco::exprScale(expr, -coeffs[j]);    // expr = - (upper_tol_- (vel - targets_)) * coeffs_\n      expr_vec_.push_back(expr);\n\n      // Form lower limit expr = (lower_tol-(vel-targ))\n      sco::exprInc(expr_neg, lower_tols_[j]);  // expr_ = lower_tol_\n      sco::exprDec(expr_neg, vel);             // expr = lower_tol_- (vel - targets_)\n      sco::exprScale(expr_neg, coeffs[j]);     // expr = (lower_tol_- (vel - targets_)) * coeffs_\n      expr_vec_.push_back(expr_neg);\n    }\n  }\n}\n\nDblVec JointVelIneqConstraint::value(const DblVec& xvec)\n{\n  // Convert vector from optimization to trajectory\n  Eigen::MatrixXd traj = getTraj(xvec, vars_);\n  // Takes diff b/n the subsequent rows to get velocity\n  Eigen::MatrixXd vel = diffAxis0(traj.block(first_step_, 0, last_step_ - first_step_ + 1, traj.cols()));\n  // Subtract targets_ to center about 0 and then subtract from tolerance\n  Eigen::MatrixXd diff0 = (vel.rowwise() - targets_.transpose());\n  Eigen::MatrixXd diff1 = (diff0.rowwise() - upper_tols_.transpose()) * coeffs_.asDiagonal();\n  Eigen::MatrixXd diff2 = ((diff0 * -1).rowwise() + lower_tols_.transpose()) * coeffs_.asDiagonal();\n  // Applies hinge, multiplies it by a diagonal matrix of coefficients, sums each corresponding value, and converts to\n  // vector\n  Eigen::MatrixXd out(diff1.rows(), diff1.cols() + diff2.cols());\n  out << diff1, diff2;\n  return util::toDblVec(out.cwiseMax(0));\n}\n\nsco::ConvexConstraintsPtr JointVelIneqConstraint::convex(const DblVec& /*x*/, sco::Model* model)\n{\n  sco::ConvexConstraintsPtr out(new sco::ConvexConstraints(model));\n  // Add hinge cost. Set the coefficient to 1 here since we include it in the AffExpr already\n  // This is necessary since we want a seperate coefficient per joint\n  for (sco::AffExpr& expr : expr_vec_)\n  {\n    out->addIneqCnt(expr);\n  }\n  return out;\n}\n\n//////////////////// Acceleration /////////////////////\nJointAccEqCost::JointAccEqCost(const VarArray& vars, const Eigen::VectorXd& coeffs, const Eigen::VectorXd& targets,\n                               int& first_step, int& last_step)\n  : Cost(\"JointAccEq\"), vars_(vars), coeffs_(coeffs), targets_(targets), first_step_(first_step), last_step_(last_step)\n{\n  for (int i = first_step_; i <= last_step_ - 2; ++i)\n  {\n    for (int j = 0; j < vars.cols(); ++j)\n    {\n      // acc = (x3 - 2*x2 + x1) - targ\n      sco::AffExpr acc;\n      sco::exprInc(acc, sco::exprMult(vars(i, j), 1.0));\n      sco::exprInc(acc, sco::exprMult(vars(i + 1, j), -2.0));\n      sco::exprInc(acc, sco::exprMult(vars(i + 2, j), 1.0));\n\n      sco::exprDec(acc, targets_[j]);\n      // expr_ = coeff * acc^2\n      sco::exprInc(expr_, sco::exprMult(sco::exprSquare(acc), coeffs_[j]));\n    }\n  }\n}\ndouble JointAccEqCost::value(const DblVec& xvec)\n{\n  // Convert vector from optimization to trajectory\n  Eigen::MatrixXd traj = (getTraj(xvec, vars_));\n  // Takes diff b/n the subsequent rows and subtract each row by the targets_ vector\n  Eigen::MatrixXd diff =\n      (diffAxis0(diffAxis0(traj.block(first_step_, 0, last_step_ - first_step_ + 1, traj.cols())))).rowwise() -\n      targets_.transpose();\n  // Element-wise square it, multiply it by a diagonal matrix of coefficients, and sums output\n  return (diff.array().square().matrix() * coeffs_.asDiagonal()).sum();\n}\nsco::ConvexObjectivePtr JointAccEqCost::convex(const DblVec& /*x*/, sco::Model* model)\n{\n  sco::ConvexObjectivePtr out(new sco::ConvexObjective(model));\n  out->addQuadExpr(expr_);\n  return out;\n}\n\nJointAccIneqCost::JointAccIneqCost(const VarArray& vars, const Eigen::VectorXd& coeffs, const Eigen::VectorXd& targets,\n                                   const Eigen::VectorXd& upper_tols, const Eigen::VectorXd& lower_tols,\n                                   int& first_step, int& last_step)\n  : Cost(\"JointAccIneq\")\n  , vars_(vars)\n  , coeffs_(coeffs)\n  , upper_tols_(upper_tols)\n  , lower_tols_(lower_tols)\n  , targets_(targets)\n  , first_step_(first_step)\n  , last_step_(last_step)\n{\n  for (int i = first_step_; i <= last_step_ - 2; ++i)\n  {\n    for (int j = 0; j < vars.cols(); ++j)\n    {\n      // acc = (x3 - 2*x2 + x1) - targ\n      sco::AffExpr acc;\n      sco::AffExpr expr;\n      sco::AffExpr expr_neg;\n      sco::exprInc(acc, sco::exprMult(vars(i, j), 1.0));\n      sco::exprInc(acc, sco::exprMult(vars(i + 1, j), -2.0));\n      sco::exprInc(acc, sco::exprMult(vars(i + 2, j), 1.0));\n      sco::exprDec(acc, targets_[j]);  // offset to center about 0\n\n      // Form upper limit expr = - (upper_tol-(acc-targ))\n      sco::exprInc(expr, upper_tols_[j]);  // expr_ = upper_tol\n      sco::exprDec(expr, acc);             // expr = upper_tol_- (vel - targets_)\n      sco::exprScale(expr, -coeffs[j]);    // expr = - (upper_tol_- (vel - targets_)) * coeffs_\n      expr_vec_.push_back(expr);\n\n      // Form lower limit expr = (lower_tol-(acc-targ))\n      sco::exprInc(expr_neg, lower_tols_[j]);  // expr_ = lower_tol_\n      sco::exprDec(expr_neg, acc);             // expr = lower_tol_- (vel - targets_)\n      sco::exprScale(expr_neg, coeffs[j]);     // expr = (lower_tol_- (vel - targets_)) * coeffs_\n      expr_vec_.push_back(expr_neg);\n    }\n  }\n}\n\ndouble JointAccIneqCost::value(const DblVec& xvec)\n{\n  // Convert vector from optimization to trajectory\n  Eigen::MatrixXd traj = getTraj(xvec, vars_);\n  // Takes diff b/n the subsequent rows to get velocity\n  Eigen::MatrixXd acc = diffAxis0(diffAxis0(traj.block(first_step_, 0, last_step_ - first_step_ + 1, traj.cols())));\n  // Subtract targets_ to center about 0 and then subtract from tolerance\n  Eigen::MatrixXd diff0 = (acc.rowwise() - targets_.transpose());\n  Eigen::MatrixXd diff1 = (diff0.rowwise() - upper_tols_.transpose()) * coeffs_.asDiagonal();\n  Eigen::MatrixXd diff2 = ((diff0 * -1).rowwise() + lower_tols_.transpose()) * coeffs_.asDiagonal();\n  // Applies hinge, multiplies it by a diagonal matrix of coefficients, sums each corresponding value, and converts to\n  // vector\n  return diff1.cwiseMax(0).sum() + diff2.cwiseMax(0).sum();\n}\n\nsco::ConvexObjectivePtr JointAccIneqCost::convex(const DblVec& /*x*/, sco::Model* model)\n{\n  sco::ConvexObjectivePtr out(new sco::ConvexObjective(model));\n  // Add hinge cost. Set the coefficient to 1 here since we include it in the AffExpr already\n  // This is necessary since we want a seperate coefficient per joint\n  for (sco::AffExpr& expr : expr_vec_)\n  {\n    out->addHinge(expr, 1);\n  }\n  return out;\n}\n\nJointAccEqConstraint::JointAccEqConstraint(const VarArray& vars, const Eigen::VectorXd& coeffs,\n                                           const Eigen::VectorXd& targets, int& first_step, int& last_step)\n  : EqConstraint(\"JointAccEq\")\n  , vars_(vars)\n  , coeffs_(coeffs)\n  , targets_(targets)\n  , first_step_(first_step)\n  , last_step_(last_step)\n{\n  for (int i = first_step_; i <= last_step_ - 2; ++i)\n  {\n    for (int j = 0; j < vars.cols(); ++j)\n    {\n      // acc = (x3 - 2*x2 + x1) - targ\n      sco::AffExpr acc;\n      sco::exprInc(acc, sco::exprMult(vars(i, j), 1.0));\n      sco::exprInc(acc, sco::exprMult(vars(i + 1, j), -2.0));\n      sco::exprInc(acc, sco::exprMult(vars(i + 2, j), 1.0));\n\n      sco::exprDec(acc, targets_[j]);  // offset to center about 0\n      // expr_ = coeff * vel - Not squared b/c QuadExpr cnt not yet supported (TODO)\n      expr_vec_.push_back(sco::exprMult(acc, coeffs_[j]));\n    }\n  }\n}\n\nDblVec JointAccEqConstraint::value(const DblVec& xvec)\n{\n  // Convert vector from optimization to trajectory\n  Eigen::MatrixXd traj = getTraj(xvec, vars_);\n  // Takes diff b/n the subsequent rows and subtract each row by the targets_ vector\n  Eigen::MatrixXd diff =\n      (diffAxis0(diffAxis0(traj.block(first_step_, 0, last_step_ - first_step_ + 1, traj.cols())))).rowwise() -\n      targets_.transpose();\n  // Squares it, multiplies it by a diagonal matrix of coefficients, and converts to vector\n  return util::toDblVec((diff.array().square()).matrix() * coeffs_.asDiagonal());\n}\nsco::ConvexConstraintsPtr JointAccEqConstraint::convex(const DblVec& /*x*/, sco::Model* model)\n{\n  sco::ConvexConstraintsPtr out(new sco::ConvexConstraints(model));\n  for (sco::AffExpr& expr : expr_vec_)\n  {\n    out->addEqCnt(expr);\n  }\n  return out;\n}\n\nJointAccIneqConstraint::JointAccIneqConstraint(const VarArray& vars, const Eigen::VectorXd& coeffs,\n                                               const Eigen::VectorXd& targets, const Eigen::VectorXd& upper_tols,\n                                               const Eigen::VectorXd& lower_tols, int& first_step, int& last_step)\n  : IneqConstraint(\"JointAccIneq\")\n  , vars_(vars)\n  , coeffs_(coeffs)\n  , upper_tols_(upper_tols)\n  , lower_tols_(lower_tols)\n  , targets_(targets)\n  , first_step_(first_step)\n  , last_step_(last_step)\n{\n  // Form upper limit expr = - (upper_tol-(vel-targ))\n  for (int i = first_step_; i <= last_step_ - 2; ++i)\n  {\n    for (int j = 0; j < vars.cols(); ++j)\n    {\n      // acc = (x3 - 2*x2 + x1) - targ\n      sco::AffExpr acc;\n      sco::AffExpr expr;\n      sco::AffExpr expr_neg;\n      sco::exprInc(acc, sco::exprMult(vars(i, j), 1.0));\n      sco::exprInc(acc, sco::exprMult(vars(i + 1, j), -2.0));\n      sco::exprInc(acc, sco::exprMult(vars(i + 2, j), 1.0));\n      sco::exprDec(acc, targets_[j]);  // offset to center about 0\n\n      // Form upper limit expr = - (upper_tol-(vel-targ))\n      sco::exprInc(expr, upper_tols_[j]);  // expr_ = upper_tol\n      sco::exprDec(expr, acc);             // expr = upper_tol_- (vel - targets_)\n      sco::exprScale(expr, -coeffs[j]);    // expr = - (upper_tol_- (vel - targets_)) * coeffs_\n      expr_vec_.push_back(expr);\n\n      // Form upper limit expr = - (upper_tol-(vel-targ))\n      sco::exprInc(expr_neg, lower_tols_[j]);  // expr_ = lower_tol_\n      sco::exprDec(expr_neg, acc);             // expr = lower_tol_- (vel - targets_)\n      sco::exprScale(expr_neg, coeffs[j]);     // expr = (lower_tol_- (vel - targets_)) * coeffs_\n      expr_vec_.push_back(expr_neg);\n    }\n  }\n}\n\nDblVec JointAccIneqConstraint::value(const DblVec& xvec)\n{\n  // Convert vector from optimization to trajectory\n  Eigen::MatrixXd traj = getTraj(xvec, vars_);\n  // Takes diff b/n the subsequent rows to get velocity\n  Eigen::MatrixXd acc = diffAxis0(diffAxis0(traj.block(first_step_, 0, last_step_ - first_step_ + 1, traj.cols())));\n  // Subtract targets_ to center about 0 and then subtract from tolerance\n  Eigen::MatrixXd diff0 = (acc.rowwise() - targets_.transpose());\n  Eigen::MatrixXd diff1 = (diff0.rowwise() - upper_tols_.transpose()) * coeffs_.asDiagonal();\n  Eigen::MatrixXd diff2 = ((diff0 * -1).rowwise() + lower_tols_.transpose()) * coeffs_.asDiagonal();\n  // Applies hinge, multiplies it by a diagonal matrix of coefficients, sums each corresponding value, and converts to\n  // vector\n  Eigen::MatrixXd out(diff1.rows(), diff1.cols() + diff2.cols());\n  out << diff1, diff2;\n  return util::toDblVec(out.cwiseMax(0));\n}\n\nsco::ConvexConstraintsPtr JointAccIneqConstraint::convex(const DblVec& /*x*/, sco::Model* model)\n{\n  sco::ConvexConstraintsPtr out(new sco::ConvexConstraints(model));\n  // Add hinge cost. Set the coefficient to 1 here since we include it in the AffExpr already\n  // This is necessary since we want a seperate coefficient per joint\n  for (sco::AffExpr& expr : expr_vec_)\n  {\n    out->addIneqCnt(expr);\n  }\n  return out;\n}\n\n//////////////////// Jerk /////////////////////\nJointJerkEqCost::JointJerkEqCost(const VarArray& vars, const Eigen::VectorXd& coeffs, const Eigen::VectorXd& targets,\n                                 int& first_step, int& last_step)\n  : Cost(\"JointJerkEq\"), vars_(vars), coeffs_(coeffs), targets_(targets), first_step_(first_step), last_step_(last_step)\n{\n  for (int i = first_step_; i <= last_step_ - 4; ++i)\n  {\n    for (int j = 0; j < vars.cols(); ++j)\n    {\n      sco::AffExpr jerk;\n      sco::exprInc(jerk, sco::exprMult(vars(i, j), -1.0 / 2.0));\n      sco::exprInc(jerk, sco::exprMult(vars(i + 1, j), 1.0));\n      sco::exprInc(jerk, sco::exprMult(vars(i + 2, j), 0.0));\n      sco::exprInc(jerk, sco::exprMult(vars(i + 3, j), -1.0));\n      sco::exprInc(jerk, sco::exprMult(vars(i + 4, j), 1.0 / 2.0));\n\n      sco::exprDec(jerk, targets_[j]);\n      // expr_ = coeff * jerk^2\n      sco::exprInc(expr_, sco::exprMult(sco::exprSquare(jerk), coeffs_[j]));\n    }\n  }\n}\ndouble JointJerkEqCost::value(const DblVec& xvec)\n{\n  // Convert vector from optimization to trajectory\n  Eigen::MatrixXd traj = (getTraj(xvec, vars_));\n  // Takes diff b/n the subsequent rows and subtract each row by the targets_ vector\n  Eigen::MatrixXd diff =\n      (diffAxis0(diffAxis0(diffAxis0(traj.block(first_step_, 0, last_step_ - first_step_ + 1, traj.cols())))))\n          .rowwise() -\n      targets_.transpose();\n  // Element-wise square it, multiply it by a diagonal matrix of coefficients, and sums output\n  return (diff.array().square().matrix() * coeffs_.asDiagonal()).sum();\n}\nsco::ConvexObjectivePtr JointJerkEqCost::convex(const DblVec& /*x*/, sco::Model* model)\n{\n  sco::ConvexObjectivePtr out(new sco::ConvexObjective(model));\n  out->addQuadExpr(expr_);\n  return out;\n}\n\nJointJerkIneqCost::JointJerkIneqCost(const VarArray& vars, const Eigen::VectorXd& coeffs,\n                                     const Eigen::VectorXd& targets, const Eigen::VectorXd& upper_tols,\n                                     const Eigen::VectorXd& lower_tols, int& first_step, int& last_step)\n  : Cost(\"JointJerkIneq\")\n  , vars_(vars)\n  , coeffs_(coeffs)\n  , upper_tols_(upper_tols)\n  , lower_tols_(lower_tols)\n  , targets_(targets)\n  , first_step_(first_step)\n  , last_step_(last_step)\n{\n  for (int i = first_step_; i <= last_step_ - 4; ++i)\n  {\n    for (int j = 0; j < vars.cols(); ++j)\n    {\n      sco::AffExpr jerk;\n      sco::AffExpr expr;\n      sco::AffExpr expr_neg;\n      sco::exprInc(jerk, sco::exprMult(vars(i, j), -1.0 / 2.0));\n      sco::exprInc(jerk, sco::exprMult(vars(i + 1, j), 1.0));\n      sco::exprInc(jerk, sco::exprMult(vars(i + 2, j), 0.0));\n      sco::exprInc(jerk, sco::exprMult(vars(i + 3, j), -1.0));\n      sco::exprInc(jerk, sco::exprMult(vars(i + 4, j), 1.0 / 2.0));\n      sco::exprDec(jerk, targets_[j]);\n\n      // Form upper limit expr = - (upper_tol-(jerk-targ))\n      sco::exprInc(expr, upper_tols_[j]);  // expr_ = upper_tol\n      sco::exprDec(expr, jerk);            // expr = upper_tol_- (vel - targets_)\n      sco::exprScale(expr, -coeffs[j]);    // expr = - (upper_tol_- (vel - targets_)) * coeffs_\n      expr_vec_.push_back(expr);\n\n      // Form lower limit expr = (lower_tol-(acc-targ))\n      sco::exprInc(expr_neg, lower_tols_[j]);  // expr_ = lower_tol_\n      sco::exprDec(expr_neg, jerk);            // expr = lower_tol_- (vel - targets_)\n      sco::exprScale(expr_neg, coeffs[j]);     // expr = (lower_tol_- (vel - targets_)) * coeffs_\n      expr_vec_.push_back(expr_neg);\n    }\n  }\n}\n\ndouble JointJerkIneqCost::value(const DblVec& xvec)\n{\n  // Convert vector from optimization to trajectory\n  Eigen::MatrixXd traj = getTraj(xvec, vars_);\n  // Takes diff b/n the subsequent rows to get velocity\n  Eigen::MatrixXd jerk =\n      diffAxis0(diffAxis0(diffAxis0(traj.block(first_step_, 0, last_step_ - first_step_ + 1, traj.cols()))));\n  // Subtract targets_ to center about 0 and then subtract from tolerance\n  Eigen::MatrixXd diff0 = (jerk.rowwise() - targets_.transpose());\n  Eigen::MatrixXd diff1 = (diff0.rowwise() - upper_tols_.transpose()) * coeffs_.asDiagonal();\n  Eigen::MatrixXd diff2 = ((diff0 * -1).rowwise() + lower_tols_.transpose()) * coeffs_.asDiagonal();\n  // Applies hinge, multiplies it by a diagonal matrix of coefficients, sums each corresponding value, and converts to\n  // vector\n  return diff1.cwiseMax(0).sum() + diff2.cwiseMax(0).sum();\n}\n\nsco::ConvexObjectivePtr JointJerkIneqCost::convex(const DblVec& /*x*/, sco::Model* model)\n{\n  sco::ConvexObjectivePtr out(new sco::ConvexObjective(model));\n  // Add hinge cost. Set the coefficient to 1 here since we include it in the AffExpr already\n  // This is necessary since we want a seperate coefficient per joint\n  for (sco::AffExpr& expr : expr_vec_)\n  {\n    out->addHinge(expr, 1);\n  }\n  return out;\n}\n\nJointJerkEqConstraint::JointJerkEqConstraint(const VarArray& vars, const Eigen::VectorXd& coeffs,\n                                             const Eigen::VectorXd& targets, int& first_step, int& last_step)\n  : EqConstraint(\"JointJerkEq\")\n  , vars_(vars)\n  , coeffs_(coeffs)\n  , targets_(targets)\n  , first_step_(first_step)\n  , last_step_(last_step)\n{\n  for (int i = first_step_; i <= last_step_ - 4; ++i)\n  {\n    for (int j = 0; j < vars.cols(); ++j)\n    {\n      sco::AffExpr jerk;\n      sco::exprInc(jerk, sco::exprMult(vars(i, j), -1.0 / 2.0));\n      sco::exprInc(jerk, sco::exprMult(vars(i + 1, j), 1.0));\n      sco::exprInc(jerk, sco::exprMult(vars(i + 2, j), 0.0));\n      sco::exprInc(jerk, sco::exprMult(vars(i + 3, j), -1.0));\n      sco::exprInc(jerk, sco::exprMult(vars(i + 4, j), 1.0 / 2.0));\n\n      sco::exprDec(jerk, targets_[j]);  // offset to center about 0\n      // expr_ = coeff * jerk - Not squared b/c QuadExpr cnt not yet supported (TODO)\n      expr_vec_.push_back(sco::exprMult(jerk, coeffs_[j]));\n    }\n  }\n}\n\nDblVec JointJerkEqConstraint::value(const DblVec& xvec)\n{\n  // Convert vector from optimization to trajectory\n  Eigen::MatrixXd traj = getTraj(xvec, vars_);\n  // Takes diff b/n the subsequent rows and subtract each row by the targets_ vector\n  Eigen::MatrixXd diff =\n      (diffAxis0(diffAxis0(diffAxis0(traj.block(first_step_, 0, last_step_ - first_step_ + 1, traj.cols())))))\n          .rowwise() -\n      targets_.transpose();\n  // Squares it, multiplies it by a diagonal matrix of coefficients, and converts to vector\n  return util::toDblVec((diff.array().square()).matrix() * coeffs_.asDiagonal());\n}\nsco::ConvexConstraintsPtr JointJerkEqConstraint::convex(const DblVec& /*x*/, sco::Model* model)\n{\n  sco::ConvexConstraintsPtr out(new sco::ConvexConstraints(model));\n  for (sco::AffExpr& expr : expr_vec_)\n  {\n    out->addEqCnt(expr);\n  }\n  return out;\n}\n\nJointJerkIneqConstraint::JointJerkIneqConstraint(const VarArray& vars, const Eigen::VectorXd& coeffs,\n                                                 const Eigen::VectorXd& targets, const Eigen::VectorXd& upper_tols,\n                                                 const Eigen::VectorXd& lower_tols, int& first_step, int& last_step)\n  : IneqConstraint(\"JointJerkIneq\")\n  , vars_(vars)\n  , coeffs_(coeffs)\n  , upper_tols_(upper_tols)\n  , lower_tols_(lower_tols)\n  , targets_(targets)\n  , first_step_(first_step)\n  , last_step_(last_step)\n{\n  for (int i = first_step_; i <= last_step_ - 4; ++i)\n  {\n    for (int j = 0; j < vars.cols(); ++j)\n    {\n      sco::AffExpr jerk;\n      sco::AffExpr expr;\n      sco::AffExpr expr_neg;\n      sco::exprInc(jerk, sco::exprMult(vars(i, j), -1.0 / 2.0));\n      sco::exprInc(jerk, sco::exprMult(vars(i + 1, j), 1.0));\n      sco::exprInc(jerk, sco::exprMult(vars(i + 2, j), 0.0));\n      sco::exprInc(jerk, sco::exprMult(vars(i + 3, j), -1.0));\n      sco::exprInc(jerk, sco::exprMult(vars(i + 4, j), 1.0 / 2.0));\n      sco::exprDec(jerk, targets_[j]);  // offset to center about 0\n\n      // Form upper limit expr = - (upper_tol-(vel-targ))\n      sco::exprInc(expr, upper_tols_[j]);  // expr_ = upper_tol\n      sco::exprDec(expr, jerk);            // expr = upper_tol_- (vel - targets_)\n      sco::exprScale(expr, -coeffs[j]);    // expr = - (upper_tol_- (vel - targets_)) * coeffs_\n      expr_vec_.push_back(expr);\n\n      // Form upper limit expr = - (upper_tol-(vel-targ))\n      sco::exprInc(expr_neg, lower_tols_[j]);  // expr_ = lower_tol_\n      sco::exprDec(expr_neg, jerk);            // expr = lower_tol_- (vel - targets_)\n      sco::exprScale(expr_neg, coeffs[j]);     // expr = (lower_tol_- (vel - targets_)) * coeffs_\n      expr_vec_.push_back(expr_neg);\n    }\n  }\n}\n\nDblVec JointJerkIneqConstraint::value(const DblVec& xvec)\n{\n  // Convert vector from optimization to trajectory\n  Eigen::MatrixXd traj = getTraj(xvec, vars_);\n  // Takes diff b/n the subsequent rows to get velocity\n  Eigen::MatrixXd acc = diffAxis0(diffAxis0(traj.block(first_step_, 0, last_step_ - first_step_ + 1, traj.cols())));\n  // Subtract targets_ to center about 0 and then subtract from tolerance\n  Eigen::MatrixXd diff0 = (acc.rowwise() - targets_.transpose());\n  Eigen::MatrixXd diff1 = (diff0.rowwise() - upper_tols_.transpose()) * coeffs_.asDiagonal();\n  Eigen::MatrixXd diff2 = ((diff0 * -1).rowwise() + lower_tols_.transpose()) * coeffs_.asDiagonal();\n  // Applies hinge, multiplies it by a diagonal matrix of coefficients, sums each corresponding value, and converts to\n  // vector\n  Eigen::MatrixXd out(diff1.rows(), diff1.cols() + diff2.cols());\n  out << diff1, diff2;\n  return util::toDblVec(out.cwiseMax(0));\n}\n\nsco::ConvexConstraintsPtr JointJerkIneqConstraint::convex(const DblVec& /*x*/, sco::Model* model)\n{\n  sco::ConvexConstraintsPtr out(new sco::ConvexConstraints(model));\n  // Add hinge cost. Set the coefficient to 1 here since we include it in the AffExpr already\n  // This is necessary since we want a seperate coefficient per joint\n  for (sco::AffExpr& expr : expr_vec_)\n  {\n    out->addIneqCnt(expr);\n  }\n  return out;\n}\n\n}  // namespace trajopt\n", "meta": {"hexsha": "b12fcf925b7bec69a4744ea3d9c942d070a56c29", "size": 37323, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "moveit_planners/trajopt/trajopt/src/trajectory_costs.cpp", "max_stars_repo_name": "adam-vonderviszt/moveit", "max_stars_repo_head_hexsha": "b18b8c66963907aa6d03cbee4450fc3d6e740162", "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_planners/trajopt/trajopt/src/trajectory_costs.cpp", "max_issues_repo_name": "adam-vonderviszt/moveit", "max_issues_repo_head_hexsha": "b18b8c66963907aa6d03cbee4450fc3d6e740162", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "moveit_planners/trajopt/trajopt/src/trajectory_costs.cpp", "max_forks_repo_name": "adam-vonderviszt/moveit", "max_forks_repo_head_hexsha": "b18b8c66963907aa6d03cbee4450fc3d6e740162", "max_forks_repo_licenses": ["BSD-3-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.47, "max_line_length": 120, "alphanum_fraction": 0.6461967152, "num_tokens": 10647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040617, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.268539245130019}}
{"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_GENERAL_FUNM_HPP_INCLUDED\n#define NT2_LINALG_FUNCTIONS_GENERAL_FUNM_HPP_INCLUDED\n\n#include <nt2/linalg/functions/funm.hpp>\n#include <nt2/core/container/table/table.hpp>\n#include <nt2/core/container/dsl/size.hpp>\n#include <nt2/sdk/complex/meta/is_complex.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/functions/abs.hpp>\n#include <nt2/include/functions/conj.hpp>\n#include <nt2/include/functions/colon.hpp>\n#include <nt2/include/functions/diag_of.hpp>\n#include <nt2/include/functions/divides.hpp>\n#include <nt2/include/functions/eye.hpp>\n#include <nt2/include/functions/eyeminus.hpp>\n#include <nt2/include/functions/factorial.hpp>\n#include <nt2/include/functions/from_diag.hpp>\n#include <nt2/include/functions/isdiagonal.hpp>\n#include <nt2/include/functions/is_finite.hpp>\n#include <nt2/include/functions/length.hpp>\n#include <nt2/include/functions/linsolve.hpp>\n#include <nt2/include/functions/max.hpp>\n#include <nt2/include/functions/globalmean.hpp>\n#include <nt2/include/functions/mtimes.hpp>\n#include <nt2/include/functions/multiplies.hpp>\n#include <nt2/include/functions/mnorminf.hpp>\n#include <nt2/include/functions/oneplus.hpp>\n#include <nt2/include/functions/ones.hpp>\n#include <nt2/include/functions/schur.hpp>\n#include <nt2/include/functions/size.hpp>\n#include <nt2/include/functions/tie.hpp>\n#include <nt2/include/functions/transpose.hpp>\n#include <nt2/include/functions/triu.hpp>\n#include <nt2/include/functions/zeros.hpp>\n#include <nt2/include/functions/extent.hpp>\n#include <nt2/include/functions/issquare.hpp>\n#include <boost/assert.hpp>\n\n// there are many optimisations/ameliorations to be done\n// -- passing parameters to functor\n// -- fine tuning of types\n// -- some code can be shared with logm\n\nnamespace nt2\n{\n  namespace ext\n  {\n    BOOST_DISPATCH_IMPLEMENT  ( funm_, tag::cpu_\n                              , (A0)(A1)\n                              , (unspecified_<A0>)\n                                (scalar_<unspecified_<A1> >)\n                              )\n    {\n      typedef A1 result_type;\n      NT2_FUNCTOR_CALL(2)\n      {\n        return a0(a1, 0);\n      }\n    };\n\n    // funm tag only used for functor/matrix\n    template<class Domain, int N, class Expr>\n    struct size_of<tag::funm_,Domain,N,Expr>\n    {\n      typedef _2D                                                      result_type;\n      BOOST_FORCEINLINE result_type operator()(Expr& e) const\n      {\n        BOOST_ASSERT_MSG( issquare(boost::proto::child_c<1>(e)),\n                          \"funm needs a functor and scalar or a \");\n        return nt2::extent(boost::proto::child_c<1>(e));\n      }\n    };\n\n  BOOST_DISPATCH_IMPLEMENT  ( run_assign_, tag::cpu_\n                            , (A0)(A1)\n                            , ((ast_<A0, nt2::container::domain>))\n                              ((node_<A1, nt2::tag::funm_, boost::mpl::long_<2>, nt2::container::domain>))\n                            )\n  {\n      typedef void                                                    result_type;\n      typedef typename A0::value_type                                  value_type;\n      typedef typename meta::as_real<value_type>::type                     r_type;\n      typedef typename meta::as_complex<r_type>::type                   cplx_type;\n      typedef typename meta::as_integer<r_type>::type                      i_type;\n      typedef nt2::table<value_type >                                       tab_t;\n      typedef nt2::table<r_type>                                           btab_t;\n      typedef table<cplx_type>                                             ctab_t;\n      typedef table<i_type>                                                itab_t;\n\n      BOOST_FORCEINLINE result_type operator()(const A0& a0, const A1& a1) const\n      {\n        compute_funm(boost::proto::value(boost::proto::child_c<0>(a1)), boost::proto::child_c<1>(a1), a0);\n      }\n    private:\n      template <class F, class T >\n      BOOST_FORCEINLINE static void compute_funm(const F& f, const T& a0, A0& res)\n      {\n         r_type tol = nt2::Eps<r_type>();\n         uint32_t maxterms = 250;\n         //u, t and r are complex arrays\n         res.resize(extent(a0));\n         ctab_t u, t;\n         nt2::tie(u, t) = schur(a0, nt2::cmplx_);\n         if (isdiagonal(t))\n         {\n           t = nt2::from_diag(f(nt2::diag_of(t), 0));\n           BOOST_AUTO_TPL(r, nt2::mtimes(u, nt2::mtimes(t, nt2::trans(nt2::conj(u)))));\n           transtype(res, r, typename nt2::meta::is_complex<value_type>::type());\n           return;\n         }\n         else\n         {\n           ctab_t r = zeros(extent(a0), meta::as_<cplx_type>()); //is it necessary ?\n           r_type delta = 0.1;\n           itab_t  ord(nt2::of_size(2u, nt2::size(a0,1)));\n           blocking(diag_of(t),delta, ord);\n           uint32_t lord = nt2::size(ord, 2);\n           ctab_t ca0 = a0;\n\n           for(uint32_t col=1; col <= lord ; ++col)\n           {\n             BOOST_AUTO_TPL(j, nt2::_(ord(1, col), ord(2, col)));\n\n             itab_t terms(nt2::of_size(1, lord));\n             uint32_t nj =  length(j);\n             ctab_t rj(nt2::of_size(nj, nj));\n             terms(col) = funm_atom(f, a0(j, j), tol, maxterms, rj);\n             r(j, j) = rj;\n             for(uint32_t row=col-1; row >= 1; --row)\n             {\n               BOOST_AUTO_TPL(i, nt2::_(ord(1, row), ord(2, row)));\n               if (length(i) == 1 && length(j) == 1)\n               {\n                 size_t ii = i(1), jj = j(1);\n                 BOOST_AUTO_TPL(k, nt2::_(ii+1, jj-1));\n                 cplx_type temp = ca0(ii,jj)*(r(ii,ii) - r(jj,jj));\n                 if (!isempty(k)) temp += mtimes(r(ii,k), ca0(k,jj)) - mtimes(ca0(ii,k), r(k,jj));\n                 r(ii,jj) = temp/(ca0(ii,ii)-ca0(jj,jj));\n               }\n               else\n               {\n                 itab_t k(nt2::of_size(1, 0));\n                 for(uint32_t l = row+1; l < col; ++l)\n                 {\n                   itab_t k1 = horzcat(k, nt2::_(ord(1, l), ord(2, l)));\n                   k = k1;\n                 }\n                 ctab_t rhs =  mtimes(r(i,i), ca0(i,j)) - mtimes(ca0(i,j), r(j,j));\n                 if(!isempty(k)) rhs += mtimes(r(i,k), ca0(k,j)) -  mtimes(ca0(i,k), r(k,j));\n                 r(i,j) = sylv_tri(ca0(i,i),-ca0(j,j),rhs);\n               }\n             }\n             ctab_t z =  mtimes(mtimes(u, r), trans(conj(u)));\n             transtype(res, z, typename nt2::meta::is_complex<value_type>::type());\n           }\n         }\n       }\n\n      template <class F, class X, class N> static inline\n        cplx_type feval(const F & f, const X& x,  const N& k)\n      {\n        ctab_t xx = x;\n        return f(xx, k);\n      }\n\n      template < class F, class D1, class D2> static inline\n      int32_t funm_atom(const F& f, const D1& t,\n                        const r_type& tol,\n                        const uint32_t& maxterms,\n                        D2& rj)\n      {\n        // Function of triangular matrix with nearly constant diagonal.\n        //   n_terms = funm_atom(f, a0, tol, maxterms, fa0)\n        //   evaluates function f at the upper triangular matrix t,\n        //   where t has nearly constant diagonal.\n        //   a taylor series is used, taking at most maxterms terms.\n        //   the function represented by f must have a taylor series with an\n        //   infinite radius of convergence.\n        //   f(x,k) must return the k'th derivative of\n        //   the function represented by fun evaluated at the vector x.\n        //   tol is a convergence tolerance for the taylor series, defaulting to eps.\n        //   if prnt ~= 0 information is printed on the convergence of the\n        //   taylor series evaluation.\n        //   n_terms is the number of terms taken in the taylor series.\n        //   n_terms  = -1 signals lack of convergence.\n\n        uint32_t n = length(t);\n        if (n == 1)\n        {\n          rj = f(t, 0);\n          return 1;\n        }\n        cplx_type lambda{nt2::globalmean(diag_of(t)),0};\n        rj = feval(f, lambda,0)*eye(n, meta::as_<cplx_type>());\n        btab_t f_deriv_max = zeros(maxterms+n-1,1, meta::as_<r_type>());\n        ctab_t nn = t - lambda*eye(n, meta::as_<cplx_type>());\n        r_type mu = mnorminf(linsolve(eyeminus(nt2::abs(triu(t,1))), nt2::ones(n,1, meta::as_<r_type>())));\n        ctab_t p = nn;\n        uint32_t max_d = 1;\n        for(uint32_t k = 1; k <= maxterms; ++k)\n        {\n          cplx_type fval = feval(f, lambda,k);\n          BOOST_ASSERT_MSG(is_finite(fval), \"funm infinite derivative\");\n          ctab_t rj_old = rj;\n          rj+= p*fval;\n          r_type  rel_diff = nt2::mnorminf(rj - rj_old)/(tol+mnorminf(rj_old));\n          p = mtimes(p, nn)/r_type(oneplus(k));\n          if (rel_diff <= tol)\n          {\n            // Approximate the maximum of derivatives in convex set containing\n            // eigenvalues by maximum of derivatives at eigenvalues.\n            for(uint32_t j = max_d; j <=  k+n-1; ++j)\n            {\n              f_deriv_max(j) = nt2::mnorminf(f(nt2::diag_of(t),j));\n            }\n            max_d = k+n;\n            r_type omega = nt2::Zero<r_type>();\n            for(uint32_t j = 0; j <= n-1; ++j)\n            {\n              omega = nt2::max(omega,f_deriv_max(k+j)/nt2::factorial(j));\n            }\n            r_type trunc = nt2::mnorminf(p)*mu*omega;\n            if (trunc <= tol*mnorminf(rj))\n            {\n              return k+1;\n            }\n          }\n        }\n        return -1;\n      }\n\n      template < class T1, class T2 >\n      BOOST_FORCEINLINE static void transtype(T1& r, T2& z, boost::mpl::false_ const &)\n      {\n        r =  real(z);\n      }\n\n      template < class T1, class T2 >\n        BOOST_FORCEINLINE static void transtype(T1& r, T2& z, boost::mpl::true_ const &)\n      {\n        r =  z;\n      }\n      template < class D> static inline void blocking(const D& a0, const r_type& delta, itab_t & ord)\n      {\n        uint32_t n = nt2::size(a0, 1);\n        uint32_t j = 1;\n        ord(1, 1) = 1;\n        for(uint32_t i=2; i <= n; ++i)\n        {\n          if (nt2::abs(a0(i-1)-a0(i)) >= delta)\n          {\n            ord(2, j) = i-1;\n            ord(1, ++j) = i;\n          }\n        }\n        ord(2, j) = n;\n        ord.resize(nt2::of_size(2u, j));\n      }\n      template < class T, class U, class B>\n        static inline ctab_t sylv_tri(const T& t,const U& u, const B& b)\n      {\n\n        // sylv_tri    solve triangular sylvester equation.\n        //    x = sylv_tri(t,u,b) solves the sylvester equation\n        //  t*x + x*u = b, where t and u are square upper triangular matrices.\n\n        uint32_t m = length(t);\n        uint32_t n = length(u);\n        ctab_t x = zeros(m,n, nt2::meta::as_<cplx_type>());\n        for(uint32_t i = 1;  i <= n; ++i)\n        {\n          ctab_t bb = b(nt2::_,i);\n          BOOST_AUTO_TPL(ii, nt2::_(1u, i-1));\n          if(!isempty(ii)) bb -= mtimes(x(nt2::_,ii),u(ii,i));\n          x(nt2::_,i) = linsolve(t + u(i,i)*eye(m, meta::as_<cplx_type>()),\n                                 bb);\n        }\n        return x;\n     }\n    };\n\n  }\n}\n\n#endif\n", "meta": {"hexsha": "f2511d20e742e839fe44019e126290c3f3376ca5", "size": 11605, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/functions/general/funm.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/core/linalg/include/nt2/linalg/functions/general/funm.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/funm.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4727891156, "max_line_length": 107, "alphanum_fraction": 0.5207238259, "num_tokens": 3098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040617, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.268539245130019}}
{"text": "/*\n * cuCTProjectionOperator.cpp\n *\n *  Created on: Feb 18, 2015\n *      Author: u051747\n */\n\n#include \"CTProjectionOperator.h\"\n#include <boost/math/constants/constants.hpp>\n#include \"ct_projection.h\"\n#include \"hoNDArray_math.h\"\n\nusing namespace boost::math::float_constants;\nnamespace Gadgetron {\n\n\n    template<template<class> class ARRAY>\n    CTProjectionOperator<ARRAY>::CTProjectionOperator() {\n        // TODO Auto-generated constructor stub\n\n        samples_per_pixel_ = 1.5f;\n\n    }\n\n    template<template<class> class ARRAY>\n    CTProjectionOperator<ARRAY>::~CTProjectionOperator() {\n        // TODO Auto-generated destructor stub\n    }\n\n    template<template<class> class ARRAY>\n    void CTProjectionOperator<ARRAY>::mult_M(ARRAY<float> *input,\n                                             ARRAY<float> *output, bool accumulate) {\n\n        auto dims = *input->get_dimensions();\n        std::vector<size_t> dims3d(dims);\n\n        if (dims3d.size() == 4) dims3d.pop_back();\n        auto outdims = *output->get_dimensions();\n        std::vector<size_t> outbindims(outdims);\n        float *input_ptr = input->get_data_ptr();\n        ARRAY<float> *tmp_out = output;\n        if (accumulate)\n            tmp_out = new ARRAY<float>(output->get_dimensions());\n\n        float *output_ptr = tmp_out->get_data_ptr();\n        for (int bin = 0; bin < binning->get_number_of_bins(); bin++) {\n            //Check for empty bins\n            if (binning->get_bin(bin).size() == 0)\n                continue;\n            ARRAY<float> input_view(dims3d, input_ptr);\n            outbindims.back() = detector_focal_cyls[bin].size();\n            auto output_view = ARRAY<float>(outbindims, output_ptr);\n\n\n            ct_forwards_projection(&output_view, &input_view, detector_focal_cyls[bin], focal_offset_cyls[bin],\n                                   central_elements[bin], is_dims_in_mm, ps_spacing, ADD, samples_per_pixel_, false);\n            //conebeam_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            input_ptr += input_view.get_number_of_elements();\n            output_ptr += output_view.get_number_of_elements();\n\n\n        }\n        if (weights)\n            *tmp_out *= *weights;\n\n        if (accumulate) {\n            *output += *tmp_out;\n            delete tmp_out;\n        }\n\n\n    }\n\n\n\n    template<template<class> class ARRAY>\n    void CTProjectionOperator<ARRAY>::mult_MH(ARRAY<float> *input,\n                                              ARRAY<float> *output, bool accumulate) {\n\n        ARRAY<float> *tmp_in = input;\n        if (weights) {\n            tmp_in = new ARRAY<float>(input);\n            *tmp_in *= *weights;\n        }\n        auto dims = *output->get_dimensions();\n        std::vector<size_t> dims3d = dims;\n        if (dims3d.size() == 4) dims3d.pop_back();\n\n        auto indims = *input->get_dimensions();\n        std::vector<size_t> inbindims(indims);\n        float *input_ptr = tmp_in->get_data_ptr();\n        float *output_ptr = output->get_data_ptr();\n        if (!accumulate)\n            clear(output);\n        for (int bin = 0; bin < binning->get_number_of_bins(); bin++) {\n            //Check for empty bins\n            if (binning->get_bin(bin).size() == 0)\n                continue;\n\n            ARRAY<float> output_view(dims3d, output_ptr);\n            inbindims.back() = detector_focal_cyls[bin].size();\n            auto input_view = ARRAY<float>(inbindims, input_ptr);\n\n            vector_td<int, 3> is_dims_in_pixels{dims3d[0], dims3d[1], dims3d[2]};\n\n            ct_backwards_projection(&input_view, &output_view, detector_focal_cyls[bin], focal_offset_cyls[bin],\n                                    central_elements[bin], proj_indices[bin], is_dims_in_mm, ps_spacing, ADD,\n                                    accumulate);\n            input_ptr += input_view.get_number_of_elements();\n            output_ptr += output_view.get_number_of_elements();\n        }\n\n        if (weights) {\n            delete tmp_in;\n        }\n\n\n    }\n\n    template<template<class> class ARRAY>\n    void Gadgetron::CTProjectionOperator<ARRAY>::setup(boost::shared_ptr<CT_acquisition> acquisition,\n                                                       floatd3 is_dims_in_mm) {\n        std::vector<unsigned int> bins(acquisition->geometry.detectorFocalCenterAngularPosition.size());\n        std::iota(bins.begin(), bins.end(), 0);\n        auto tmp_binning = boost::make_shared<CBCT_binning>(std::vector<std::vector<unsigned int>>(1, bins));\n        this->setup(acquisition, tmp_binning, is_dims_in_mm);\n    }\n\n    template<template<class> class ARRAY>\n    std::vector<intd2> Gadgetron::CTProjectionOperator<ARRAY>::calculate_slice_indices(CT_acquisition &acquisition) {\n\n        floatd2 detectorSize = acquisition.geometry.detectorSize;\n        auto &centralElements = acquisition.geometry.detectorCentralElement;\n        auto &axialPosition = acquisition.geometry.detectorFocalCenterAxialPosition;\n\n        auto image_dims = *this->get_domain_dimensions();\n        auto proj_dims = *this->get_codomain_dimensions();\n\n\n        std::vector<intd2> slice_indices(image_dims[2]);\n        std::fill(slice_indices.begin(), slice_indices.end(), intd2(0, 0));\n        std::vector<float> start_point(centralElements.size() + 1);\n\n        for (int i = 0; i < centralElements.size(); i++) {\n            start_point[i] = axialPosition[i] + (centralElements[i][1] - float(proj_dims[1]) / 2) * detectorSize[1] -\n                             detectorSize[1] * proj_dims[1] / 2;\n            //std::cout << \"Start point \" << start_point[i] << std::endl;\n        }\n        start_point.back() = 2 * start_point[centralElements.size() - 1] - start_point[centralElements.size() - 2];\n\n        int projection_start = 0;\n        int projection_stop = 0;\n        for (int i = 0; i < slice_indices.size(); i++) {\n            float slice_start = is_dims_in_mm[2] / image_dims[2] * (i - 0.5f) - is_dims_in_mm[2] / 2;\n            float slice_stop = is_dims_in_mm[2] / image_dims[2] * (i + 0.5f) - is_dims_in_mm[2] / 2;\n            //std::cout << \"Slice start \" << slice_start << \" slice end \" << slice_stop << std::endl;\n            while (slice_start > (start_point[projection_start] + detectorSize[1] * proj_dims[1])) {\n                projection_start++;\n                if (projection_start >= centralElements.size()) {\n                    projection_start = centralElements.size();\n                    break;\n                }\n            }\n            while (slice_stop > start_point[projection_stop]) {\n\n                projection_stop++;\n                if (projection_stop >= centralElements.size()) {\n                    projection_stop = centralElements.size();\n                    break;\n                }\n            }\n\n\n            slice_indices[i][0] = projection_start;\n            slice_indices[i][1] = projection_stop;\n            //std::cout << \"Projection start stop \" << projection_start << \" \" << projection_stop << \" start point \" << start_point[projection_start] << \" \" << start_point[projection_stop] << \" \" << detectorSize[1] << std::endl;\n        }\n\n        std::cout << \"Indices size \" << slice_indices.size() << std::endl;\n        return slice_indices;\n\n    }\n\n    template<template<class> class ARRAY>\n    void Gadgetron::CTProjectionOperator<ARRAY>::setup(boost::shared_ptr<CT_acquisition> acquisition,\n                                                       boost::shared_ptr<ARRAY<float>> weights, floatd3 is_dims_in_mm) {\n        this->weights = weights;\n        setup(acquisition, is_dims_in_mm);\n    }\n\n    template<template<class> class ARRAY>\n    void Gadgetron::CTProjectionOperator<ARRAY>::setup(boost::shared_ptr<CT_acquisition> acquisition,\n                                                       boost::shared_ptr<CBCT_binning> binning, floatd3 is_dims_in_mm) {\n        this->binning = binning;\n        auto bins = binning->get_bins();\n        this->is_dims_in_mm = is_dims_in_mm;\n\n        //Variables needed for differewnt\n        detector_focal_cyls = std::vector<std::vector<floatd3>>(bins.size());\n        focal_offset_cyls = std::vector<std::vector<floatd3>>(bins.size());\n        central_elements = std::vector<std::vector<floatd2>>(bins.size());\n        proj_indices = std::vector<std::vector<intd2>>(bins.size());\n\n        proj_indices[0] = calculate_slice_indices(*acquisition);\n        CT_geometry &geometry = acquisition->geometry;\n        ps_spacing = acquisition->geometry.detectorSize;\n        ADD = acquisition->geometry.constantRadialDistance[0];\n\n        if (bins.size() != 1) throw std::runtime_error(\"CT reconstruction does not fully support 4D data yet\");\n        for (size_t b = 0; b < bins.size(); b++) {\n            for (auto i : bins[b]) {\n                detector_focal_cyls[b].emplace_back(geometry.detectorFocalCenterAngularPosition[i],\n                                                    geometry.detectorFocalRadialDistance[i],\n                                                    geometry.detectorFocalCenterAxialPosition[i]);\n\n                focal_offset_cyls[b].emplace_back(geometry.sourceAngularPositionShift[i],\n                                                  geometry.sourceRadialDistanceShift[i],\n                                                  geometry.sourceAxialPositionShift[i]);\n\n                central_elements[b].push_back(geometry.detectorCentralElement[i]);\n                //proj_indices[b].push_back(all_proj_indices[i]);\n            }\n\n        }\n    }\n\n\n    template\n    class CTProjectionOperator<cuNDArray>;\n\n    template\n    class CTProjectionOperator<hoCuNDArray>;\n\n\n} /* namespace Gadgetron */\n", "meta": {"hexsha": "fdc9674ddf99c57170ae1a1088b93b68203de803", "size": 9776, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xray/CTProjectionOperator.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/CTProjectionOperator.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/CTProjectionOperator.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": 41.2489451477, "max_line_length": 265, "alphanum_fraction": 0.5966653028, "num_tokens": 2221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.26853764563574933}}
{"text": " /*\n  Copyright (c) 2016, Bart Vermeulen\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 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\n#include \"Point.hpp\"\n#include <CGAL/basic.h>\n#include <CGAL/Search_traits.h>\n#include <CGAL/Orthogonal_incremental_neighbor_search.h>\n#include <CGAL/iterator.h>\n#include \"mex.h\"\n#include <math.h>\n#include <algorithm>\n#include <iterator>\n#include <Eigen/Dense>\n#include <thread>\n#include <functional>\n#include <future>\n#include <chrono>\n\nusing namespace std;\n\nextern void main_();\n\ntypedef CGAL::Search_traits<double, Point, Point::Cit, Construct_coord_iterator> Traits; // search traits\ntypedef CGAL::Orthogonal_incremental_neighbor_search<Traits> K_inc_neighbor_search; // incremental searcher\ntypedef K_inc_neighbor_search::Tree Tree; // The tree\ntypedef K_inc_neighbor_search::iterator Piterator; //The search iterator\ntypedef K_inc_neighbor_search::Point_with_transformed_distance P_with_dist; //Return type of searcher\nstruct Point_rw_not_zero{\n\tbool operator() (const Piterator& it){\n\t\treturn it->first.rw()==0; //functor to exclude points with rw == 0\n\t}\n};\ntypedef CGAL::Filter_iterator< Piterator, Point_rw_not_zero > P_pos_rw_it; // construct filtered iterator\n\n\nvoid loess(vector< Point > &,const vector< Point >&, vector< double > &, mwSize, mwSize, mwSize, mwSize);\n\ntypedef std::vector< P_with_dist >::const_iterator regpoints_iit;\ntypedef std::back_insert_iterator< std::vector< double > > weights_oit;\nvoid triCube(regpoints_iit, regpoints_iit, weights_oit);\n\nvoid biCube(Tree const & tree, const vector< double > &);\n\nvoid localFit( Tree const &, vector< Point > const & qp,mwSize q, vector< double > &, mwSize, mwSize, double &);\ndouble median(vector< double >);\n\n\nvoid mexFunction(int nlhs,mxArray *plhs[],int nrhs, const mxArray * prhs[]){\n   \tmwSize nin,nd,nout,q,niter=0, order=1, nthreads=thread::hardware_concurrency() ;\n\tdouble * span=0, *x,*v,*xi,*vi;\n\tif (nrhs < 4)\n\t\tmexErrMsgIdAndTxt(\"loess:nargin\",\"At least 4 arguments are required\");\n\t// Input checking: x, v, xi\n\tnin=mxGetM( prhs[0] );\n\tnd=mxGetN( prhs[0] );\n\tnout=mxGetM( prhs[2] );\n\tif ( !( mxGetNumberOfDimensions( prhs[0] )==2 && mxGetNumberOfDimensions( prhs[1] )==2 && mxGetNumberOfDimensions( prhs[2] ) ==2 ) )\n\t\tmexErrMsgIdAndTxt(\"loess:notArray\",\"Inputs should not have more than two dimensions\");\n\tif ( nin != static_cast<mwSize>( mxGetM( prhs[1] ) ) )\n\t\tmexErrMsgIdAndTxt(\"loess:nin\",\"Second input (values) should have same number of rows as first input (locations)\");\n\tif ( nd != static_cast<mwSize>( mxGetN(prhs[2] ) ) )\n\t\tmexErrMsgIdAndTxt(\"loess:nd\",\"Third input (query points) should have same number of columns as first input (locations)\");\n\tif ( mxGetN( prhs[1] ) != 1)\n\t\tmexErrMsgIdAndTxt(\"loess:notColumnV\",\"Second input should be a column vector\");\n\tif ( !( mxIsDouble( prhs[0] ) && mxIsDouble( prhs[1] ) && mxIsDouble( prhs[2] ) && mxIsDouble( prhs[3] )  ) )\n\t\tmexErrMsgIdAndTxt(\"loess:isdouble\",\"All input arguments should be of type Double\");\n\tif ( mxGetNumberOfElements( prhs[3] ) != 1 )\n\t\tmexErrMsgIdAndTxt(\"loess:spanNotScalar\",\"Fourth argument should be a scalar\");\n\t// if ( nin < min_dat )\n\t// \tmexErrMsgIdAndTxt(\"loess:smallInput\",\"At least 3 rows required in first input\");\n\t//Read required inputs\n\tspan = mxGetPr( prhs[3] );\n\tx = mxGetPr( prhs[0] );\n\tv = mxGetPr( prhs[1] );\n\txi = mxGetPr( prhs [2] );\n\n\tif (nrhs > 4){\n\t\tif ( mxGetNumberOfElements( prhs[4] ) != 1)\n\t\t\tmexErrMsgIdAndTxt(\"loess:niterNotScalar\",\"Fifth argument should be a scalar\");\n\t\tif ( floor( * mxGetPr( prhs[4] )) != * mxGetPr( prhs[4] ) )\n\t\t\tmexErrMsgIdAndTxt(\"loess:niterNotInteger\",\"Fifth argument should be an integer\");\n\t\tif ( * mxGetPr( prhs[4] ) < 0 )\n\t\t\tmexErrMsgIdAndTxt(\"loess:niterNegative\",\"Fifth argument should be positive\");\n\t\tniter=static_cast< mwSize >(* mxGetPr( prhs[4] ) );\n\t}\n\n\tif (nrhs > 5){\n\t\tif ( floor( * mxGetPr( prhs[5] )) != * mxGetPr( prhs[5] ) )\n\t\t\tmexErrMsgIdAndTxt(\"loess:orderNotInteger\",\"Sixth argument should be an integer\");\n\t\tif ( mxGetNumberOfElements( prhs[5] ) != 1 )\n\t\t\tmexErrMsgIdAndTxt(\"loess:orderNotScalar\",\"Sixth argument should be a scalar\");\n\t\tif ( * mxGetPr( prhs[5] ) !=1 &&  * mxGetPr( prhs[5] ) !=2)\n\t\t\tmexErrMsgIdAndTxt(\"loess:orderNotOneOrTwo\",\"Sixth argument should be equal to one or two\");\n\t\torder = static_cast< mwSize >(* mxGetPr( prhs[5] ) );\n\t}\n\n\tif (nrhs > 6){\n\t\tif ( floor( * mxGetPr( prhs[6] )) != * mxGetPr( prhs[6] ) )\n\t\t\tmexErrMsgIdAndTxt(\"loess:orderNotInteger\",\"Seventh argument (nthreads) should be an integer\");\n\t\tif ( mxGetNumberOfElements( prhs[6] ) != 1 )\n\t\t\tmexErrMsgIdAndTxt(\"loess:orderNotScalar\",\"Seventh argument (nthreads) should be a scalar\");\n\t\tif ( * mxGetPr( prhs[6] ) < 1 ){\n\t\t\tmexWarnMsgIdAndTxt(\"loess:orderNotOneOrTwo\",\"Using one thread instead!\");\n\t\t\tnthreads=1;\n\t\t}\n\t\telse if ( * mxGetPr( prhs[6] ) > thread::hardware_concurrency() ){\n\t\t\tmexWarnMsgIdAndTxt(\"loess:orderNotOneOrTwo\",\"Using number of available threads instead!\");\n\t\t\tnthreads = thread::hardware_concurrency();\n\t\t}\n\t\telse\n\t\t\tnthreads = static_cast< unsigned int >(* mxGetPr( prhs[6] ) );\n\t}\n\n\t//Make output variable\n\tplhs[0]=mxCreateDoubleMatrix(nout,1, mxREAL);\n\tvi=mxGetPr( plhs[0] );\n\n\t//Transfor vars into vectors\n\tvector< Point > inpoints, outpoints;\n\tvector< double > valsout;\n\t//inpoints.resize(nin,Point(nd,0));\n\toutpoints.resize(nout,Point(nd,0));\n\tvalsout.resize(nout,std::numeric_limits<double>::quiet_NaN() );\n\tfor (mwSize cin=0; cin < nin; cin++){\n\t\tif (!std::isfinite(v[cin]))\n\t\t\tcontinue;\n\t\tPoint tmpPoint(nd,0);\n\t\ttmpPoint.val(v[cin]);\n\t\tbool point_is_finite=true;\n\t\tfor (mwSize cd=0; (cd < nd) & point_is_finite; cd++){\n\t\t\tif (!std::isfinite(x[cd*nin+cin])){\n\t\t\t\tpoint_is_finite=false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttmpPoint[cd]=(x[cd*nin+cin]);\n\t\t}\n\t\tif (point_is_finite)\n\t\t\tinpoints.push_back(tmpPoint);\n\t}\n\tfor (mwSize co=0; co<nout; co++){\n\t\tfor (mwSize cd=0; cd < nd; cd++) {\n\t\t\toutpoints[co][cd]=xi[cd*nout+co];\n\t\t}\n\t}\n\n\t//Make span\n\tif (*span > 1)\n\t\tq=static_cast<mwSize>(round(*span));\n\telse\n\t\tq=static_cast<mwSize>(round(*span * static_cast<double> (nin)));\n\t\n\tq=max(static_cast<mwSize>(3),min(nin,q));\n\n\t//Perform computation\n\tloess(inpoints, outpoints, valsout, q, niter, order, nthreads);\n\n\t// Copy output\n\tfor (mwSize co=0; co<nout; co++){\n\t\tvi[co]=valsout[co];\n\t}\n}\n\nvoid loess(vector< Point > & inpoints,const vector < Point > & outpoints, vector <double> & valsout, mwSize q, mwSize niter, mwSize order, mwSize nthreads){\n\t// Build search tree\n\tTree tree(inpoints.begin(), inpoints.end());\n\n\t// Perform regression on input data\n\tdouble prog_lf(0);\n\tvector<double> vals_reg=vector<double>(inpoints.size(),0); // holds regression results at input locations\n\tdouble frac_riter = double(inpoints.size())/double(inpoints.size()*niter+outpoints.size());\n\tdouble frac_interp = double(outpoints.size())/double(inpoints.size()*niter+outpoints.size());\n\tdouble prog(0);\n\tstd::cout << std::fixed << std::setw(10) << std::setprecision(2);\n\tfor (mwSize citer=0; citer < niter; citer++) {// robust iterations\n\t    prog_lf=0;\n\t    std::future< void > f = std::async(std::launch::async, localFit, std::ref(tree), std::ref(inpoints),q,std::ref(vals_reg), order, nthreads, std::ref(prog_lf));\n\t\tstd::future_status status;\n\t    do {\n\t    \tstatus = f.wait_for(std::chrono::seconds(1));\n\t    \tprog = (double(citer) + prog_lf) * frac_riter;\n                //mexPrintf(\"\\r%10.2f%%\", prog*100);\n\t    \t//std::cout << \"\\r\" << prog*100 << \"%\" << std::flush;\n\t    } while (status != std::future_status::ready);\n\t    biCube(tree,vals_reg); // Compute robust weights (This is not included in computation of progress)\n\t}\n\n\t// Perform regression on output points\n\tprog_lf = 0;\n\tstd::future< void > f = std::async(std::launch::async, localFit, std::ref(tree), std::ref(outpoints),q,std::ref(valsout),order, nthreads, std::ref(prog_lf));\n\tstd::future_status status;\n    do {\n    \tstatus = f.wait_for(std::chrono::seconds(1));\n    \tprog = prog_lf * frac_interp + double(niter) * frac_riter;\n        //mexPrintf(\"\\r%10.2f%%\", prog*100);\n    \t//std::cout << \"\\r\" << prog*100 << \"%\" << std::flush;\n    } while (status != std::future_status::ready);\n    //std::cout << \"\\rDone.      \" << std::endl;\n}\n\n\nvoid triCube(regpoints_iit pd_begin, regpoints_iit pd_end,  weights_oit w_it) {\n\t// Computes regression weights\n\tdouble arg=0;\n\tfor (auto pd_it=pd_begin; pd_it != pd_end; pd_it++){\n\t\targ=pd_it->second / (pd_end-1)->second;\n\t\t*w_it = pd_it->first.rw() * ( (arg < 1) ? pow(1 - pow(arg,1.5),1.5) : 0); // This is tricube, but distances are given squared, and we want to use the square of the weights in weighted regression hence twice the 1.5 exponent\n\t\t++w_it;\n\t}\n}\n\nvoid biCube(Tree const & tree, const vector<double> & vals_reg ){\n\t// biCube function for the computation of robust weights from residuals of the fit\n\tdouble arg=0;\n\t// calculate residuals\n\tvector<double> res=vector<double>(tree.size(),0);\n\tfor (std::size_t cp=0; cp<static_cast<std::size_t>(tree.size()); cp++)\n\t\tres[cp]=abs((tree.begin()+cp)->val()-vals_reg[cp]);\n\tdouble sixmres=6*median(res);\n\tauto tit=tree.begin();\n\tfor (std::size_t cp=0; cp<static_cast<std::size_t>(tree.size()); cp++){\n\t\targ=res[cp]/sixmres;\n\t\tconst_cast<Point *> (&(*tit))->rw( (arg < 1) ? 1-pow(arg,2) : 0 ); //const_cast shouldn't do any harm here. Second square is removed since we use square root of weights in regression\n\t\ttit++;\n\t}\n}\n\nvoid parFit(const Tree & tree, vector< Point >::const_iterator qp_begin, vector< Point >::const_iterator qp_end, vector< double >::iterator val_beg, mwSize q, mwSize n, mwSize order, double & prog){\n// Performs the actual local regression\n// Input:\n// \t\tTree:      the spatial search tree (not modified)\n// \t\tqp_begin:  begin iterator of query points (not modified)\n// \t\tqp_end:\t   end iterator of query points (not modified)\n// \t\tval_begin: begin iterator of values (modified to hold output of regression)\n// \t\tq:         number of points for regression (not modified)\n// \t\tn:\t\t   number of terms in regression (not modified)\n// \t\torder:\t   order of regression (not modified)\n// \t\tprog:\t   to keep track of progress, between 0 and 1 (modified)\n\t// Initialize variable\n\tmwSize ndims=qp_begin->dims();      // number of dimensions\n\n\t\n\t// Search for N-nearest neighbors and perform regression\n\tfor (auto qp_it = qp_begin; qp_it != qp_end; qp_it++){ // loop over all query points\n\t\tbool point_is_finite=true;\n\t\tfor (auto c_it = qp_it->begin(); c_it != qp_it->end(); c_it++)\n\t\t\tif (!std::isfinite(*c_it))\n\t\t\t\tpoint_is_finite=false;\n\t\tif (!point_is_finite){\n\t\t\t++val_beg;\n\t\t\tcontinue;\n\t\t}\n\t\tK_inc_neighbor_search ins (tree,*qp_it); //Create incremental searcher\n\t\tP_pos_rw_it it(ins.end(), Point_rw_not_zero(), ins.begin()), end(ins.end(), Point_rw_not_zero()); //filtered iterator to exclude non-finite values and nan-values\n\t\tvector< P_with_dist > regpoints; // holds nearest neighbor search results\n\n\t\t// Copy N-nearest points to current query point\n\t\tfor (mwSize cc=0; cc < q && it!=end; cc++){\n\t\t\tregpoints.push_back(*it);// store filtered nearest neighbors\n\t\t\tit++;\n\t\t}\n\t\t\n\t\tif (regpoints.size() < n){\n\t\t\t++val_beg;\n\t\t\tcontinue;\n\t\t}\t\t\n\t\t// Compute weights for regression\n\t\tvector< double > w; \t\t\t\t// hold regression weights\n\t\ttriCube(regpoints.cbegin(), regpoints.cend(), std::back_inserter(w));\n\t\t\n\t\t// Eigen matrices for regression\n\t\tEigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> A(regpoints.size(),n); // Regression matrix\n\t\tEigen::Matrix<double, Eigen::Dynamic, 1> x(n,1);\t\t      // Regression result vector\n\t\tEigen::Matrix<double, Eigen::Dynamic, 1> b(regpoints.size(),1);              // Known values for regression\n\t\t// Fill EIGEN matrices and perform regression\n\t\tfor (mwSize cc=0; cc < regpoints.size(); cc++) { // loop over points to regress\n\t\t\tA(cc,0)=w[cc]; // Term 1: Intercept, i.e. 1\n\t\t\tb(cc,0)=regpoints[cc].first.val()*w[cc]; // Known value\n\t\t\tfor (mwSize cd=0; cd < ndims ; cd++)  // Regression terms (1st order)\n\t\t\t\tA(cc,cd+1)=w[cc]*(regpoints[cc].first[cd]-(*qp_it)[cd]); // Terms are centered coordinates\n\t\t\tif (order==2){ // Quadratic terms (2nd order), i.e. all cross products\n\t\t\t\tmwSize cpos=ndims+1; // Term number in matrix (column number)\n\t\t\t\tfor (mwSize cd1=0; cd1<ndims; cd1++) // Loop over dimension\n\t\t\t\t\tfor (mwSize cd2=cd1; cd2 < ndims; cd2++ ) // Loop from outer loop dimension to number of dimensions\n\t\t\t\t\t\tA(cc, cpos++)=w[cc]*((regpoints[cc].first[cd1]-(*qp_it)[cd1]) * (regpoints[cc].first[cd2]-(*qp_it)[cd2])); // Assign cross-products (centered and weighed)\n\t\t\t}\n\t\t}\n\t\tx=A.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b); // Perform weighted least squares regression. Note the weights get squared in here\n\t\t* val_beg = x(0,0); // store result\n\t\t++val_beg;\t// Increase pointer to output values\n\t\tprog = double(std::distance(qp_begin,qp_it))/double(std::distance(qp_begin,qp_end)); // keep track of progress\n\t}\n\tprog = 1;\n}\n\nvoid localFit(const Tree & tree, const vector< Point > & qp, mwSize q, vector<double> & val, mwSize order, mwSize nthreads, double & prog) {\n\t// This function controls the local fitting by calling the function parFit in separate computational threads.\n\t// Inputs are:\n\t// \ttree:     The Spatial search tree (not modified)\n\t// \tqp:       Query points (not modified)\n\t// \tq:\t      Number of points in regression (not modified)\n\t// \tval:      Estimated function value at query points (modified)\n\t// \torder:    Order of the regression (not modified)\n\t// \tnthreads: Number of computational threads (not modified)\n\t// \tprog:\t  Keeps track of progress (modified)\n\n\t// Compute number of input points and dimensions\n\tmwSize nin=qp.size();\n\tmwSize ndims=qp.begin()->dims();\n\n\t// Compute number of terms in regression\n\t// \tLinear terms\n\tmwSize n=ndims+1; // number of dimensions plus one\n\t//  Quadratic terms\n\tif (order == 2)\n\t\tfor (mwSize cd=1; cd < ndims + 1; cd++)\n\t\t\tn += cd; // cross-products (1 + 2 + ... + ndims)\n\n\tmwSize usedthreads = nthreads>nin ? nin : nthreads; // Reduce the number of threads when there are less query points than threads\n\t// Compute number of points in each each computational thread\n\tvector< mwSize > n_in_thread(usedthreads,nin/usedthreads); // Number of threads is equal to the integral division of number of points and threads\n\tfor (mwSize cr=0; cr < nin % usedthreads; cr++)         // Remaining point (modulo) are spread over the threads\n\t\tn_in_thread[cr]++;\n\n\t// Start computation in threads asynchronously\n\tvector<double> prog_th(usedthreads,0); \t\t\t // Vector holding progress (between 0 and 1) of each computation thread\n\tstd::vector< std::future < void > > all_futures; // Vector with one feature per thread\n\tmwSize total=0; \t\t\t\t\t\t\t\t // Keeps track of points passed to previous threads\n\tfor (mwSize cth = 0; cth<usedthreads; cth++){       // Loop to launch computations asynchronously\n\t\tall_futures.push_back( std::async( std::launch::async, parFit, std::ref(tree), qp.begin()+total, qp.begin()+total+n_in_thread[cth], val.begin()+total, q, n ,order, std::ref(prog_th[cth]) ) ); // Start thread\n\t\ttotal += n_in_thread[cth];\t// Keep track of points already passed to the function\n\t}\n\n\t// Check status of threads every second\n\tstd::future_status status;\n\tfor (mwSize cth = 0; cth < usedthreads; cth++){ // Check status of each thread\n\t\tdo {\n\t\t\tstatus = all_futures[cth].wait_for(std::chrono::seconds(1)); // Wait for 1 second, or for thread ending (whichever comes first)\n\t\t\tprog = std::accumulate(prog_th.begin(),prog_th.end(),0.0)/double(usedthreads); // Compute current progress of threads\n\t\t} while (status != std::future_status::ready); // Repeat loop until thread ended successfully\n\t}\n\n} // end of localFit\n\n\ndouble median(vector<double> v) // vector copied to avoid modifications on it\n{\n  if(v.empty()) {\n    return 0.0;\n  }\n  auto n = v.size() / 2;\n  nth_element(v.begin(), v.begin()+n, v.end());\n  auto med = v[n];\n  if(!(v.size() & 1)) { //If the set size is even\n    auto max_it = max_element(v.begin(), v.begin()+n);\n    med = (*max_it + med) / 2.0;\n  }\n  return med;    \n}\n\n\n", "meta": {"hexsha": "be24b75d8cca549248d7766e7c287614b0bd46dc", "size": 17173, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "loess.cpp", "max_stars_repo_name": "bartverm/loess", "max_stars_repo_head_hexsha": "f48f55b543ef4690415c0b1be6cb9e45944e111d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-03-19T08:30:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-12T17:44:14.000Z", "max_issues_repo_path": "loess.cpp", "max_issues_repo_name": "bartverm/loess", "max_issues_repo_head_hexsha": "f48f55b543ef4690415c0b1be6cb9e45944e111d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "loess.cpp", "max_forks_repo_name": "bartverm/loess", "max_forks_repo_head_hexsha": "f48f55b543ef4690415c0b1be6cb9e45944e111d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-12T13:03:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-03T00:14:30.000Z", "avg_line_length": 44.6051948052, "max_line_length": 225, "alphanum_fraction": 0.6886973738, "num_tokens": 4991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2684785094968909}}
{"text": "#include <ros/ros.h>\n#include \"ros_utils.hpp\"\n#include \"kinematics.hpp\"\n#include \"estimators.hpp\"\n#include <boost/array.hpp>\n#include <boost/numeric/odeint.hpp>\n#include <casadi/casadi.hpp>\n\n#include <mhe_estimator/ArticulatedAngles.h>\n#include <mhe_estimator/CanData.h>\n#include \"std_msgs/String.h\"\n#include \"geometry_msgs/PoseWithCovarianceStamped.h\"\n#include \"geometry_msgs/Twist.h\"\n#include \"ackermann_msgs/AckermannDrive.h\"\n#include \"std_srvs/Trigger.h\"\n#include \"std_srvs/Empty.h\"\n\n//--------------------------| Moving Horizen Window Length |---------------------------// \nconst long unsigned int N_mhe = 60;\n//-------------------------------------------------------------------------------------// \n\nint main(int argc, char **argv)\n{\n    using namespace mhe_estimator;\n    using namespace ast;\n    using namespace ast::ros;\n    ::ros::init(argc, argv, \"mhe_estimator_node\");\n    NodeHandle nh;\n    \n    /*----------------| Get Params |----------------*/\n    CarParams carParams;\n    MheParams mheParams;\n    ParamsIn(carParams, mheParams, nh);\n    /*---------------------------------------------*/\n\n    /*------------| Global Var and Obj |-----------*/\n    ::ros::Time lastPerceptionTime;\n    const long unsigned int N_mhePlus1 = N_mhe + 1;\n    boost::array<Vec4, N_mhePlus1> q4wLoc;        //x y theta beta window\n    boost::array<Vec2, N_mhe> control2w;           //control2 window\n\n    boost::array<Vec4, N_mhePlus1> q4wCov;        //state cov window\n    boost::array<Vec2, N_mhe> control2wCov;        //control cov window\n\n    boost::array<Vec5, N_mhePlus1> q5wLocTrailer; //x y theta beta window triler =1 \n    boost::array<Vec2, N_mhe> control2wTrailer;    //control2 window triler =1 \n\n    boost::array<Vec5, N_mhePlus1> q5wCovTrailer; //state cov window trailer1\n    boost::array<Vec2, N_mhe> control2wCovTrailer; //control cov window trailer1 \n\n    Vec4 qLoc;                 //triler == 0 \n    Vec2 controls;              //triler == 0 \n    Vec4 qEstFirstSample;       //triler == 0 \n\n    Vec4 qCov;               //cov triler == 0 \n    Vec4 qCovMhe;\n    Vec2 controlsCov;           //cov triler == 0 \n\n    Vec5 qLocTrailer;         //triler == 1 \n    Vec2 controlsTrailer;        //triler == 1 \n    Vec5 qEstFirstSampleTrailer; //triler == 1 \n\n    Vec5 qCovTrailer;\n    Vec5 qCovMheTrailer;         //Cov triler == 1 \n    Vec2 controlsCovTrailer;     //cov triler == 1 \n\n    Vec3 q;\n    Vec4 qTrailerLoc;\n    Vec3 qCarEst;\n    Vec4 qCarEstMhe;\n    Vec2 ctrlEstMhe;\n    Vec5 qMheTrailer;\n    Vec2 ctrMheTrailer;\n    Vec4 qOneTrailerEst;\n    int sampleNo;\n    /*---------------------------------------------*/\n\n    /*----------------| Get Casadi Solver  |----------------*/\n    casadi::Function solverCar;\n    casadi::Function solverTrailer;\n    ROS_INFO_STREAM(\"Creating CasADi Solvers\");\n    mheSetupCar(solverCar, carParams, mheParams,N_mhe);\n    mheSetupTrailer(solverTrailer, carParams, mheParams,N_mhe);\n    ROS_INFO_STREAM(\"Car like solver: \"<< solverCar <<\"\");\n    ROS_INFO_STREAM(\"single wagon like solver: \"<< solverTrailer <<\"\");\n    \n    casadi::DM argx0 = casadi::SX::zeros((4*(N_mhe + 1))+(2*N_mhe));  // 4 =  n_state    2 = n_control   //triler = 0\n    casadi::DM argx0Trailer = casadi::SX::zeros((5*(N_mhe + 1))+(2*N_mhe));  // 4 =  n_state    2 = n_control  //triler =1 \n    /*------------------------------------------------------*/\n\n    /*----------------| ROS Subscribers and Publishers  |-----------------------------------------*/\n\n    auto canDataIn = nh.Input<CanData>(\"/processed_can_data\");\n    boost::shared_ptr<CanData> canData(new CanData());\n\n    auto perceptionPoseCamIn = nh.Input<geometry_msgs::PoseStamped>(\"/pose_estimator/charger_pose/location_cam\");\n    auto perceptionPoseGpsIn = nh.Input<geometry_msgs::PoseStamped>(\"/pose_estimator/charger_pose/location_gps\");\n    boost::shared_ptr<geometry_msgs::PoseStamped> perceptionPose(new geometry_msgs::PoseStamped());\n\n\n    auto perceptionTwistOut = nh.Output<geometry_msgs::Twist>(\"mhe_node/perception/twist\");\n    boost::shared_ptr<geometry_msgs::Twist> perceptionTwistData(new geometry_msgs::Twist());\n\n\n    auto perceptionTwistMheOut = nh.Output<geometry_msgs::Twist>(\"mhe_node/mhe_estimated/twist\");\n    geometry_msgs::Twist perceptionTwistMheData;\n\n    auto perceptionTwistWeightedOut = nh.Output<geometry_msgs::Twist>(\"mhe_node/weighted_estimated/twist\");\n    geometry_msgs::Twist perceptionTwistWeightedData;\n\n    auto articulatedAnglesOut = nh.Output<ArticulatedAngles>(\"mhe_node/can_data/articulated_angles\");\n    ArticulatedAngles articulatedAnglesData;\n\n    auto articulatedAnglesMheOut = nh.Output<ArticulatedAngles>(\"mhe_node/mhe_estimated/articulated_angles\");\n    ArticulatedAngles articulatedAnglesMheData;\n\n    auto articulatedAnglesWeightedOut = nh.Output<ArticulatedAngles>(\"mhe_node/weighted_estimated/articulated_angles\");\n    ArticulatedAngles articulatedAnglesWeightedData;\n\n    auto poseWithCovarianceIn = nh.Input<geometry_msgs::PoseWithCovarianceStamped>(\"mhe_node/perception_data/pose_with_covariance\");\n    //geometry_msgs::PoseWithCovarianceStamped poseWithCovarianceData;\n    \n    auto poseWithCovarianceMheOut = nh.Output<geometry_msgs::PoseWithCovarianceStamped>(\"mhe_node/mhe_estimated/pose_with_covariance\");\n    geometry_msgs::PoseWithCovarianceStamped poseWithCovarianceMheData;\n\n    auto poseWithCovarianceWeightedOut = nh.Output<geometry_msgs::PoseWithCovarianceStamped>(\"mhe_node/weighted_estimated/pose_with_covariance\");\n    geometry_msgs::PoseWithCovarianceStamped poseWithCovarianceWeightedData;\n\n    auto ackermannDriveOut = nh.Output<ackermann_msgs::AckermannDrive>(\"mhe_node/can_data/ackermann_drive\");\n    ackermann_msgs::AckermannDrive ackermannDriveData;\n\n    auto ackermannDriveMheOut = nh.Output<ackermann_msgs::AckermannDrive>(\"mhe_node/mhe_estimated/ackermann_drive\");\n    ackermann_msgs::AckermannDrive ackermannDriveMheData;\n    \n    //auto ackermannDriveWeightedOut = nh.Output<ackermann_msgs::AckermannDrive>(\"mhe_node/weighted_estimated/ackermann_drive\");\n    //ackermann_msgs::AckermannDrive ackermannDriveWeightedData;\n    /*------------------------------------------------------------------------------------------*/\n\n    ROS_INFO_STREAM(\"Estimator loop rate: \"<< mheParams.loopRate <<\"\");\n    Real t = 0;\n    bool firstPoseMeasured = false;\n    ::ros::Rate loop_rate(mheParams.loopRate);\n    while(::ros::ok())\n    {\n        \n        auto now = ::ros::Time::now();\n     \n        *canData = canDataIn(); \n\n        ackermannDriveData.speed = canData->tachoVelocity;\n        ackermannDriveData.steering_angle = canData->steeringAngle;\n        auto& poseWithCovarianceData = poseWithCovarianceIn();\n\n        if (!mheParams.covarianceFromTopicStamp)\n        {\n            if(mheParams.perceptionGPS)\n            {\n                *perceptionPose = perceptionPoseGpsIn(); \n            }else\n            {\n                *perceptionPose = perceptionPoseCamIn();  \n            }\n        } else\n        {\n            perceptionPose->pose = poseWithCovarianceData.pose.pose;\n            perceptionPose->header.stamp = poseWithCovarianceData.header.stamp;      \n        }\n       \n        \n         \n        auto perceptionTh = tf::getYaw(perceptionPose->pose.orientation);\n        ::ros::Duration timeDiff = perceptionPose->header.stamp - lastPerceptionTime;\n        lastPerceptionTime = perceptionPose->header.stamp;                           \n        bool isPerceptionPoseFresh = timeDiff.toSec() >= 0.01;\n\n        perceptionTwistData->linear.x = perceptionPose->pose.position.x;\n        perceptionTwistData->linear.y = perceptionPose->pose.position.y;\n        perceptionTwistData->angular.z = perceptionTh;\n        articulatedAnglesData.trailer1 = canData->beta1;\n        if(perceptionPose->pose.position.x != 0 && perceptionPose->pose.position.y != 0)\n        {\n            if (carParams.TrailerNumber == 0)\n            { \n                \n                //Th base on estimator \n                qLoc[1] = perceptionPose->pose.position.x - carParams.L*cos(perceptionTh);\n                qLoc[2] = perceptionPose->pose.position.y - carParams.L*sin(perceptionTh);\n                qLoc[3] = canData->steeringAngle;\n                \n                if(mheParams.mheActive)\n                {\n                    controlsCov[0] = 0;\n                    controlsCov[1] = 1/mheParams.noiseVarianceLinearVel;\n                    if (!mheParams.covarianceFromTopicStamp)\n                    {       \n                        qCov[0] = 1/mheParams.noiseVarianceTh;         \n                        qCov[1] = 1/mheParams.noiseVariancePos;\n                        qCov[2] = 1/mheParams.noiseVariancePos;\n                    }else\n                    {\n                        qCov[0] = poseWithCovarianceData.pose.covariance.elems[35];        \n                        qCov[1] = poseWithCovarianceData.pose.covariance.elems[0];\n                        qCov[2] = poseWithCovarianceData.pose.covariance.elems[7];\n                    }\n                    \n                    qCov[3] = 1/mheParams.noiseVariancesteering;\n                    \n                    qLoc[0] = continuousAngle(perceptionTh, qCarEstMhe[0]);\n                    controls[0] = 0;  //no measured value for dbeta\n                    controls[1] = canData->tachoVelocity; //uCar.longitudinalVelocity + noiseArray[4];\n\n                    std::rotate(q4wLoc.begin(), q4wLoc.begin()+1, q4wLoc.end());\n                    std::rotate(control2w.begin(), control2w.begin()+1, control2w.end());\n                    std::rotate(q4wCov.begin(), q4wCov.begin()+1, q4wCov.end());\n                    std::rotate(control2wCov.begin(), control2wCov.begin()+1, control2wCov.end());\n            \n                    \n                    ::ros::Duration sampleDiff = ::ros::Time::now() - perceptionPose->header.stamp;\n                    int sampleNumber = floor(sampleDiff.toSec()/(1.0/mheParams.loopRate));\n                    if (sampleNumber > N_mhe)\n                    {\n                        ROS_WARN_STREAM(\"WARNING: localization delay = \"<< sampleNumber<<\" sample\" );\n                    }\n                    if(sampleNumber >=0  && sampleNumber < N_mhe)\n                    {\n                        if(!firstPoseMeasured)\n                        {\n                          ROS_INFO_STREAM(\"First config \"<<qLoc[0] <<\" \"<< qLoc[1]<<\" \"<< qLoc[2]<<\" \"<<qLoc[3]<<\" \");\n                          for(size_t i = 0; i < q4wCov.size(); ++i)\n                          {\n                            q4wCov[i] = qCov;\n                            q4wLoc[i] = qLoc;\n                          }\n                          qEstFirstSample = qLoc;\n\n                          for(size_t i = 0; i < control2w.size(); ++i)\n                          {\n                              controls[0] = 0.0;\n                              controls[1] = 0.0;\n                              control2w[i] = controls;\n                              control2wCov[i] = controlsCov;\n                          }\n                          sampleNo = sampleNumber;\n                          ROS_INFO_STREAM(\"feeding at: N_mhe - \"<< sampleNo << \" index\");\n                          ROS_INFO(\"First pose received. Starting.\");\n                          firstPoseMeasured = true;\n                        }\n\n                        q4wCov[N_mhe] = {0.0, 0.0, 0.0, 0.0};\n                        //-----   canData to window -------//\n                        q4wCov[N_mhe][3] = qCov[3];    \n                        q4wLoc[N_mhe][3] = qLoc[3];\n\n                        control2w[N_mhe-1] = controls;\n                        control2wCov[N_mhe-1] = controlsCov;\n                        //---------------------------------//\n                        \n                        // ---------perception to window -------//\n                        q4wCov[N_mhe - sampleNo][0] = qCov[0];\n                        q4wCov[N_mhe - sampleNo][1] = qCov[1];\n                        q4wCov[N_mhe - sampleNo][2] = qCov[2];\n\n                        q4wLoc[N_mhe - sampleNo][0] = qLoc[0];\n                        q4wLoc[N_mhe - sampleNo][1] = qLoc[1];\n                        q4wLoc[N_mhe - sampleNo][2] = qLoc[2];\n                        //---------------------------------//\n                      \n                    }\n                   \n                    q4wLoc[0] = qEstFirstSample; \n                    auto qCovF = qCov;\n                    qCovF[0] = qCov[0]*5;\n                    qCovF[1] = qCov[1]*5;\n                    qCovF[2] = qCov[2]*5;\n                    qCovF[3] = qCov[3]*5;\n                    q4wCov[0] = qCovF;\n\n                    estimateMhe(argx0, q4wLoc, control2w, q4wCov, control2wCov, carParams, mheParams, solverCar);\n                    std::vector<double> resx = std::vector<double>(argx0);\n                    qCarEstMhe[0] = resx[(4*(N_mhe+1))-4]; //theta    return estimated 4 = n_states\n                    qCarEstMhe[1] = resx[(4*(N_mhe+1))-3]; //x \n                    qCarEstMhe[2] = resx[(4*(N_mhe+1))-2]; //y\n                    qCarEstMhe[3] = resx[(4*(N_mhe+1))-1]; //beta0\n                    \n                    qEstFirstSample[0] = resx[0]; //theta return estimated 4 = n_states\n                    qEstFirstSample[1] = resx[1]; //x\n                    qEstFirstSample[2] = resx[2]; //y\n                    qEstFirstSample[3] = resx[3]; //beta0\n\n                    ctrlEstMhe[0] = resx[(4*(N_mhe+1))+(4*N_mhe)-4]; //dbeta\n                    ctrlEstMhe[1] = resx[(4*(N_mhe+1))+(4*N_mhe)-3]; //u2\n\n                    qCovMhe[0] = resx[(4*(N_mhe+1))+(4*N_mhe)+(4*(N_mhe+1))-4];//theta\n                    qCovMhe[1] = resx[(4*(N_mhe+1))+(4*N_mhe)+(4*(N_mhe+1))-3];//x \n                    qCovMhe[2] = resx[(4*(N_mhe+1))+(4*N_mhe)+(4*(N_mhe+1))-2];//y\n                    qCovMhe[3] = resx[(4*(N_mhe+1))+(4*N_mhe)+(4*(N_mhe+1))-1];//beta0\n                    \n                    poseWithCovarianceMheData.pose.pose.orientation = tf::createQuaternionMsgFromYaw(qCarEstMhe[0]);\n                    poseWithCovarianceMheData.pose.pose.position.x = qCarEstMhe[1] + carParams.L*cos(qCarEstMhe[0]);\n                    poseWithCovarianceMheData.pose.pose.position.y = qCarEstMhe[2] + carParams.L*sin(qCarEstMhe[0]);\n\n                    poseWithCovarianceMheData.pose.covariance.elems[0] = qCovMhe[1];\n                    poseWithCovarianceMheData.pose.covariance.elems[7] = qCovMhe[2];\n                    poseWithCovarianceMheData.pose.covariance.elems[35] = qCovMhe[0];\n                    poseWithCovarianceMheOut(poseWithCovarianceMheData);\n\n                    ackermannDriveMheData.steering_angle = qCarEstMhe[3];\n                    ackermannDriveMheData.speed = ctrlEstMhe[1];\n                    ackermannDriveMheData.steering_angle_velocity = ctrlEstMhe[0];\n                    ackermannDriveMheOut(ackermannDriveMheData);\n\n                    perceptionTwistMheData.angular.z = qCarEstMhe[0];\n                    perceptionTwistMheData.linear.x = qCarEstMhe[1] + carParams.L*cos(qCarEstMhe[0]);\n                    perceptionTwistMheData.linear.y = qCarEstMhe[2] + carParams.L*sin(qCarEstMhe[0]);\n                    perceptionTwistMheOut(perceptionTwistMheData);\n\n                    perceptionTwistOut(perceptionTwistData);\n                    articulatedAnglesOut(articulatedAnglesData);\n                    ackermannDriveOut(ackermannDriveData);\n\n                }\n                if(mheParams.WeightedActive)\n                {\n                    qLoc[0] = continuousAngle(perceptionTh, qCarEst[0]);\n                    q = {qLoc[0],qLoc[1],qLoc[2]};\n                    auto simFunc = [&](const Vec3& q, Vec3& dq, const double t)\n                    {\n                        //if(!carParams.moveGuidancePoint)\n                            dq = RDCarKinematicsGPRear(carParams, q, ackermannDriveData);\n                        //else\n                        //  dq = RDCarKinematicsGPFront(carParams, q, ackermannDriveData);\n                    };\n                    Vec3 qCarPred = qCarEst;\n                    boost::numeric::odeint::integrate(simFunc, qCarPred, 0.0, 1.0/(Real)mheParams.loopRate, 1.0/(Real)mheParams.loopRate);\n\n                    if(!isPerceptionPoseFresh)\n                    {\n                        qCarEst = qCarPred;\n                    }\n                    else\n                    {\n                        //ROS_INFO(\"fresh gps pose\");\n                        estimateEst(qCarEst, q, qCarPred ,mheParams);  \n                    }\n                    poseWithCovarianceWeightedData.pose.pose.orientation = tf::createQuaternionMsgFromYaw(qCarEst[0]);\n                    poseWithCovarianceWeightedData.pose.pose.position.x = qCarEst[1] + carParams.L*cos(qCarEst[0]);\n                    poseWithCovarianceWeightedData.pose.pose.position.y = qCarEst[2] + carParams.L*sin(qCarEst[0]);\n                    poseWithCovarianceWeightedData.header.stamp = ::ros::Time::now();\n                    poseWithCovarianceWeightedOut(poseWithCovarianceWeightedData);\n\n                    perceptionTwistWeightedData.angular.z = qCarEst[0];\n                    perceptionTwistWeightedData.linear.x = qCarEst[1] + carParams.L*cos(qCarEst[0]);\n                    perceptionTwistWeightedData.linear.y = qCarEst[2] + carParams.L*sin(qCarEst[0]);\n                    perceptionTwistWeightedOut(perceptionTwistWeightedData);\n                }\n\n                \n\n            }else if (carParams.TrailerNumber == 1)\n            {\n                \n                qLocTrailer[0] = canData->beta1;\n                //Th base on estimator is different\n                qLocTrailer[2] = perceptionPose->pose.position.x - carParams.L*cos(perceptionTh);\n                qLocTrailer[3] = perceptionPose->pose.position.y - carParams.L*sin(perceptionTh);\n                qLocTrailer[4] = canData->steeringAngle;\n                \n\n                if(mheParams.mheActive)\n                {\n                    controlsCovTrailer[0] = 0;\n                    controlsCovTrailer[1] = 1/mheParams.noiseVarianceLinearVel;\n\n                    qCovTrailer[0] = 1/mheParams.noiseVarianceTrailer1;\n                    if (!mheParams.covarianceFromTopicStamp)\n                    {  \n                        qCovTrailer[1] = 1/mheParams.noiseVarianceTh;\n                        qCovTrailer[2] = 1/mheParams.noiseVariancePos;\n                        qCovTrailer[3] = 1/mheParams.noiseVariancePos;\n                    }else\n                    {\n                        qCovTrailer[1] = poseWithCovarianceData.pose.covariance.elems[35];\n                        qCovTrailer[2] = poseWithCovarianceData.pose.covariance.elems[0];\n                        qCovTrailer[3] = poseWithCovarianceData.pose.covariance.elems[7];\n                    }\n\n                    qCovTrailer[4] = 1/mheParams.noiseVariancesteering;\n\n                    qLocTrailer[1] = continuousAngle(perceptionTh, qMheTrailer[1]); \n                    controlsTrailer[0] = 0; //no measured value for dbeta\n                    controlsTrailer[1] = canData->tachoVelocity; //uCar.longitudinalVelocity + noiseArray[4];\n                \n                    std::rotate(q5wLocTrailer.begin(), q5wLocTrailer.begin()+1, q5wLocTrailer.end());\n                    std::rotate(control2wTrailer.begin(), control2wTrailer.begin()+1, control2wTrailer.end());\n                    std::rotate(q5wCovTrailer.begin(), q5wCovTrailer.begin()+1, q5wCovTrailer.end());\n                    std::rotate(control2wCovTrailer.begin(), control2wCovTrailer.begin()+1, control2wCovTrailer.end());\n                    \n\n                    ::ros::Duration sampleDiff = ::ros::Time::now() - perceptionPose->header.stamp;\n                    int sampleNumber = floor(sampleDiff.toSec()/(1.0/mheParams.loopRate));\n                    if (sampleNumber > N_mhe)\n                    {\n                        ROS_WARN_STREAM(\"WARNING: localization delay = \"<< sampleNumber<<\" sample\" );\n                    }\n                    if(sampleNumber >=0  && sampleNumber < N_mhe)\n                    {\n                        if(!firstPoseMeasured)\n                        {\n                          ROS_INFO_STREAM(\"First config \"<<qLocTrailer[0] <<\" \"<< qLocTrailer[1]<<\" \"<< qLocTrailer[2]<<\" \"<<qLocTrailer[3]<<\" \"<<qLocTrailer[4]);\n                          \n                          for(size_t i = 0; i < q5wCovTrailer.size(); ++i)\n                          {                            \n                            q5wCovTrailer[i] = qCovTrailer;\n                            q5wLocTrailer[i] = qLocTrailer;\n                          }\n\n                          qEstFirstSampleTrailer = qLocTrailer;\n\n                          for(size_t i = 0; i < control2wTrailer.size(); ++i)\n                          {\n                            controlsTrailer[0] = 0.0;\n                            controlsTrailer[1] = 0.0;\n                            control2wTrailer[i] = controlsTrailer;\n                            control2wCovTrailer[i] = controlsCovTrailer;\n                          }\n                          sampleNo = sampleNumber;\n                          ROS_INFO_STREAM(\"feeding at: N_mhe - \"<< sampleNo << \" index\");\n                          ROS_INFO(\"First pose received. Starting.\");\n                          firstPoseMeasured = true;\n                        }\n\n                        q5wCovTrailer[N_mhe] = {0.0, 0.0, 0.0, 0.0, 0.0};\n\n                        //-----   canData to window -------//\n                        q5wCovTrailer[N_mhe][0] = 1/mheParams.noiseVarianceTrailer1;\n                        q5wCovTrailer[N_mhe][4] = 1/mheParams.noiseVariancesteering;\n\n                        q5wLocTrailer[N_mhe][0] = qLocTrailer[0];\n                        q5wLocTrailer[N_mhe][4] = qLocTrailer[4];\n\n                        control2wTrailer[N_mhe-1] = controlsTrailer;\n                        control2wCovTrailer[N_mhe-1] = controlsCovTrailer;\n                        //---------------------------------//\n\n                        // ---------perception to window -------//\n                        q5wCovTrailer[N_mhe -sampleNo][1] = qCovTrailer[1];\n                        q5wCovTrailer[N_mhe -sampleNo][2] = qCovTrailer[2];\n                        q5wCovTrailer[N_mhe -sampleNo][3] = qCovTrailer[3];\n\n                        q5wLocTrailer[N_mhe -sampleNo][1] = qLocTrailer[1];\n                        q5wLocTrailer[N_mhe -sampleNo][2] = qLocTrailer[2];\n                        q5wLocTrailer[N_mhe -sampleNo][3] = qLocTrailer[3];\n                        //--------------------------------------------//\n                        \n\n                    }\n                    \n                    \n                    q5wLocTrailer[0] = qEstFirstSampleTrailer;\n                    auto qCovTrailerF = qCovTrailer;\n                    qCovTrailerF[0] = 5/mheParams.noiseVarianceTrailer1;\n\n                    qCovTrailerF[1] = qCovTrailer[1]*5;\n                    qCovTrailerF[2] = qCovTrailer[2]*5;\n                    qCovTrailerF[3] = qCovTrailer[3]*5;\n\n                    qCovTrailerF[4] = 5/mheParams.noiseVariancesteering;\n                    q5wCovTrailer[0] = qCovTrailerF;\n\n                    control2wTrailer[N_mhe-1] = controlsTrailer;\n                    control2wCovTrailer[N_mhe-1] = controlsCovTrailer;\n                \n                    estimateMheTrailer(argx0Trailer, q5wLocTrailer, control2wTrailer, q5wCovTrailer, control2wCovTrailer, carParams, mheParams,solverTrailer);\n                        \n                    std::vector<double> resxTrailer = std::vector<double>(argx0Trailer);\n                    qMheTrailer[0] = resxTrailer[(5*(N_mhe+1))-5]; //beta1                return estimated 4 = n_states\n                    qMheTrailer[1] = resxTrailer[(5*(N_mhe+1))-4]; //theta\n                    qMheTrailer[2] = resxTrailer[(5*(N_mhe+1))-3]; //x\n                    qMheTrailer[3] = resxTrailer[(5*(N_mhe+1))-2]; //y\n                    qMheTrailer[4] = resxTrailer[(5*(N_mhe+1))-1]; //beta0\n\n                    qEstFirstSampleTrailer[0] = resxTrailer[0]; //beta1                return estimated 4 = n_states\n                    qEstFirstSampleTrailer[1] = resxTrailer[1]; //theta\n                    qEstFirstSampleTrailer[2] = resxTrailer[2]; //x\n                    qEstFirstSampleTrailer[3] = resxTrailer[3]; //y\n                    qEstFirstSampleTrailer[4] = resxTrailer[4]; //beta0\n\n                    ctrMheTrailer[0] = resxTrailer[(5*(N_mhe+1))+(5*N_mhe)-5]; //dbeta\n                    ctrMheTrailer[1] = resxTrailer[(5*(N_mhe+1))+(5*N_mhe)-4]; //u2\n                    \n                    qCovMheTrailer[0] = resxTrailer[(5*(N_mhe+1))+(5*N_mhe)+(5*(N_mhe+1))-5]; //beta1\n                    qCovMheTrailer[1] = resxTrailer[(5*(N_mhe+1))+(5*N_mhe)+(5*(N_mhe+1))-4]; //theta\n                    qCovMheTrailer[2] = resxTrailer[(5*(N_mhe+1))+(5*N_mhe)+(5*(N_mhe+1))-3]; //x\n                    qCovMheTrailer[3] = resxTrailer[(5*(N_mhe+1))+(5*N_mhe)+(5*(N_mhe+1))-2]; //y\n                    qCovMheTrailer[4] = resxTrailer[(5*(N_mhe+1))+(5*N_mhe)+(5*(N_mhe+1))-1]; //beta0\n\n                    poseWithCovarianceMheData.pose.pose.orientation = tf::createQuaternionMsgFromYaw(qMheTrailer[1]);\n                    poseWithCovarianceMheData.pose.pose.position.x = qMheTrailer[2] + carParams.L*cos(qMheTrailer[1]);\n                    poseWithCovarianceMheData.pose.pose.position.y = qMheTrailer[3] + carParams.L*sin(qMheTrailer[1]);\n\n                    poseWithCovarianceMheData.pose.covariance.elems[0] = qCovMheTrailer[2];\n                    poseWithCovarianceMheData.pose.covariance.elems[7] = qCovMheTrailer[3];\n                    poseWithCovarianceMheData.pose.covariance.elems[35] = qCovMheTrailer[1];\n                    poseWithCovarianceMheOut(poseWithCovarianceMheData);\n\n                    ackermannDriveMheData.steering_angle = qMheTrailer[4];\n                    ackermannDriveMheData.speed = ctrMheTrailer[1];\n                    ackermannDriveMheData.steering_angle_velocity = ctrMheTrailer[0];\n                    ackermannDriveMheOut(ackermannDriveMheData);\n\n                    perceptionTwistMheData.angular.z = qMheTrailer[1];\n                    perceptionTwistMheData.linear.x = qMheTrailer[2] + carParams.L*cos(qMheTrailer[1]);\n                    perceptionTwistMheData.linear.y = qMheTrailer[3] + carParams.L*sin(qMheTrailer[1]);\n                    perceptionTwistMheOut(perceptionTwistMheData);\n\n                    articulatedAnglesMheData.trailer1 = qMheTrailer[0];\n                    articulatedAnglesMheOut(articulatedAnglesMheData);\n\n                    perceptionTwistOut(perceptionTwistData);\n                    articulatedAnglesOut(articulatedAnglesData);\n                    ackermannDriveOut(ackermannDriveData);\n                \n                \n                }   \n                if(mheParams.WeightedActive)\n                {\n                    \n                    qLocTrailer[1] = continuousAngle(perceptionTh, qOneTrailerEst[1]);\n                    qTrailerLoc = {qLocTrailer[0],qLocTrailer[1],qLocTrailer[2],qLocTrailer[3] };\n                    auto simFunc = [&](const Vec4& qTrailer, Vec4& dq, const double t)\n                    {\n                        if(!carParams.moveGuidancePoint)\n                            dq = OneTrailerKinematicsGPRear(carParams, qTrailer, ackermannDriveData);\n                        else\n                            dq = OneTrailerKinematicsGPFront(carParams, qTrailer, ackermannDriveData);\n                    };\n                        \n                    Vec4 qOneTrailerPred = qOneTrailerEst;\n                    boost::numeric::odeint::integrate(simFunc, qOneTrailerPred, 0.0, 1.0/(Real)mheParams.loopRate, 1.0/(Real)mheParams.loopRate);\n                    \n                    if(!isPerceptionPoseFresh)\n                    {\n                        qOneTrailerEst = qOneTrailerPred;\n                    }\n                    else\n                    {\n                        ROS_INFO(\"fresh gps pose\");\n                        estimateEstTrailer(qOneTrailerEst, qTrailerLoc, qOneTrailerPred, mheParams);\n                        //betaEst = estParams.weightBeta*betaPred + (1-estParams.weightBeta)*(beta);\n                    }\n                    poseWithCovarianceWeightedData.pose.pose.orientation = tf::createQuaternionMsgFromYaw(qOneTrailerEst[1]);\n                    poseWithCovarianceWeightedData.pose.pose.position.x = qOneTrailerEst[2]  + carParams.L*cos(qOneTrailerEst[1]);\n                    poseWithCovarianceWeightedData.pose.pose.position.y = qOneTrailerEst[3]  + carParams.L*sin(qOneTrailerEst[1]);\n                    poseWithCovarianceWeightedData.header.stamp = ::ros::Time::now();\n                    poseWithCovarianceWeightedOut(poseWithCovarianceWeightedData);\n                    \n\n                    articulatedAnglesWeightedData.trailer1 = qOneTrailerEst[0];\n                    articulatedAnglesWeightedOut(articulatedAnglesWeightedData);\n\n                    perceptionTwistWeightedData.angular.z = qOneTrailerEst[1];\n                    perceptionTwistWeightedData.linear.x = qOneTrailerEst[2] + carParams.L*cos(qOneTrailerEst[1]);\n                    perceptionTwistWeightedData.linear.y = qOneTrailerEst[3] + carParams.L*sin(qOneTrailerEst[1]);\n                    perceptionTwistWeightedOut(perceptionTwistWeightedData);\n\n\n\n                    \n\n                }\n                \n            }else\n            {\n                ROS_ERROR(\" Trailer Number out of range, accepted values: 0, 1\");\n            }\n            \n        }\n        \n        auto loopTime =  ::ros::Time::now() - now;\n        ROS_INFO_STREAM(\"loop time\" << loopTime.toSec());\n\n        t += 1/((Real) mheParams.loopRate);\n        ::ros::spinOnce();\n        loop_rate.sleep();\n\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "0e15b600f6a889b02ddf1e9edb085f5369a8fb20", "size": 29777, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mhe_estimator_node.cpp", "max_stars_repo_name": "crt-adas/mhe_estimator", "max_stars_repo_head_hexsha": "e96669c84c1eae76d13f03b2f5123e099419f2c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mhe_estimator_node.cpp", "max_issues_repo_name": "crt-adas/mhe_estimator", "max_issues_repo_head_hexsha": "e96669c84c1eae76d13f03b2f5123e099419f2c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mhe_estimator_node.cpp", "max_forks_repo_name": "crt-adas/mhe_estimator", "max_forks_repo_head_hexsha": "e96669c84c1eae76d13f03b2f5123e099419f2c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.4694915254, "max_line_length": 162, "alphanum_fraction": 0.5300063808, "num_tokens": 7688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.26847850273573265}}
{"text": "/*\n *  tutte.cpp\n *\n *\n *  Created by Andrea Bedini on 24/Nov/2011.\n *  Copyright (c) 2011-2014, Andrea Bedini <andrea.bedini@gmail.com>.\n *\n *  Distributed under the terms of the Modified BSD License.\n *  The full license is in the file COPYING, distributed as part of\n *  this software.\n *\n */\n\n#include \"chinese_remainder.hpp\"\n#include \"graph_type.hpp\"\n#include \"parse_graph.hpp\"\n#include \"transfer.hpp\"\n#include \"tree_decomposition/heuristics.hpp\"\n#include \"tree_decomposition/tree_decomposition.hpp\"\n#include \"tutte.hpp\"\n#include \"utility/gmp.hpp\"\n#include \"utility/polynomial_two.hpp\"\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/property_map/vector_property_map.hpp>\n#include <boost/range/irange.hpp>\n#include <boost/range/algorithm/equal.hpp>\n#include <boost/range/algorithm/sort.hpp>\n#include <boost/program_options.hpp>\n#include <boost/tokenizer.hpp>\n\n#include <exception>\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <vector>\n\nconst char manifesto[] =\n  \"tutte - computes the Tutte Polynomial\\n\"\n  \"Copyright (c) 2011-2014, Andrea Bedini <andrea.bedini@gmail.com>.\\n\\n\"\n  \"Distributed under the terms of the Modified BSD License.\\n\"\n  \"The full license is in the file COPYING, distributed as part of\\n\"\n  \"this software.\\n\";\n\n/*\n * code to parse user-supplied elimination order\n */\n\ntemplate<class OutputIterator>\nvoid parse_elimination_order(std::string const& s, OutputIterator out)\n{\n  boost::tokenizer<> tok(s);\n  for (auto& c : tok)\n    *out++ = boost::lexical_cast<unsigned>(c);\n}\n\n/*\n *  validate the ordering by checking if it's a permutation of [0..num_vertices)\n */\ntemplate<class Range, class Graph>\nbool validate_elimination_order(Range range, Graph const& g)\n{\n  using namespace boost;\n  return range::equal(sort(range), irange((size_t) 0, num_vertices(g)));\n}\n\n/*\n *  The algorithm to run, dependent on the weight type\n */\n\ntemplate<typename T>\nusing algo = tutte<polynomial_two<T>>;\n\nint main (int argc, char *argv[])\n{\n  namespace po = boost::program_options;\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()\n    (\"help,h\", \"Produce help message\")\n    (\"input-file\", po::value<std::string>(), \"Read the graph from a file.\")\n    // tree decomposition options\n    (\"degree\", \"Use greedy degree algorithm [default].\")\n    (\"fill-in\", \"Use greedy fill-in algorithm.\")\n    (\"local-degree\", \"Use 'local' greedy degree algorithm.\")\n    (\"local-fill-in\", \"Use 'local' greedy fill-in algorithm.\")\n    (\"elimination-order\", po::value<std::string>(), \"Specify a vertex elimination order.\")\n    (\"print-tree\", \"Print tree decomposition.\")\n    (\"tree-only\", \"Print tree decomposition and exit.\")\n    // tutte options\n    (\"flow,f\", \"Compute the flow polynomial\")\n    (\"chromatic,c\", \"Compute the chromatic polynomial\")\n    (\"Q,Q\", po::value<int32_t>(), \"Fix Q value, to be used with v\")\n    (\"v,v\", po::value<int32_t>(), \"Fix v value, to be used with Q\")\n    (\"chinese-remainder\", \"Use the chinese remainder trick.\")\n    ;\n\n  po::variables_map vm;\n\n  try {\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n  } catch (po::error& e) {\n    std::cerr << \"error: \" << e.what() << \"\\n\";\n    return 1;\n  }\n\n  if (vm.count(\"help\")) {\n    std::cerr << manifesto << \"\\n\" << desc << \"\\n\";\n    return 0;\n  }\n\n  int check = 0;\n  check += vm.count(\"degree\");\n  check += vm.count(\"fill-in\");\n  check += vm.count(\"local-degree\");\n  check += vm.count(\"local-fill-in\");\n  check += vm.count(\"elimination-order\");\n\n  if (check > 1) {\n    std::cerr <<\n      \"error: please specify at most one between degree, fill-in,\"\n      \"local-degree, local-fill-in and elimination-order\\n\";\n    return 1;\n  }\n\n  graph_type g;\n  try {\n    std::string s;\n    if (vm.count(\"input-file\")) {\n      std::string filename = vm[\"input-file\"].as<std::string>();\n      std::ifstream input(filename.c_str(), std::ios_base::in);\n      if (not input.is_open()) {\n        std::cerr << \"error: file \" << filename << \" not found\\n\";\n        return 1;\n      }\n      input >> s;\n    } else {\n      std::cin >> s;\n    }\n    g = parse_graph(s);\n  } catch (std::exception& e) {\n    std::cerr << \"error: \" << e.what() << \"\\n\";\n    return 1;\n  }\n\n  std::cerr << \"Graph with \" << num_vertices(g) << \" vertices and \"\n            << num_edges(g) << \" edges.\\n\";\n\n  // check for connectedness\n  auto component = boost::make_vector_property_map<int>(\n    get(boost::vertex_index, g));\n  auto num = connected_components(g, component);\n  if (num > 1) {\n    std::cerr << \"The input graph is not connected. A connected input is required\\n\";\n    return 1;\n  }\n\n  std::vector<unsigned int> order(num_vertices(g));\n\n  if (vm.count(\"fill-in\")) {\n    heuristics::greedy_fillin_order(g, order.begin());\n  } else if (vm.count(\"local-degree\")) {\n    heuristics::greedy_local_degree_order(g, order.begin());\n  } else if (vm.count(\"local-fill-in\")) {\n    heuristics::greedy_local_fillin_order(g, order.begin());\n  } else if (vm.count(\"elimination-order\")) {\n    // parse the std::string\n    std::string s = vm[\"elimination-order\"].as<std::string>();\n    parse_elimination_order(s, order.begin());\n    bool valid = validate_elimination_order(order, g);\n    if (not valid) {\n      std::cerr << \"error: elimination order not valid\\n\";\n      return 1;\n    }\n    std::cerr << \"Vertex ordering: \" << s << \"\\n\";\n  } else {\n    heuristics::greedy_degree_order(g, order.begin());\n  }\n\n  auto td = tree_decomposition::build_tree_decomposition(order, g);\n\n  if (vm.count(\"print-tree\") or vm.count(\"tree-only\")) {\n    std::cerr << \"Elimination order: \";\n    for (auto x : order)\n      std::cerr << x << \" \";\n    std::cerr << \"\\n\";\n\n    std::cerr << \"Tree decomposition: \" << td << \"\\n\"\n              << \"Tree decomposition width: \"\n              << max_bag_size(td) - 1 << \"\\n\";\n  }\n\n  if (vm.count(\"tree-only\"))\n    return 0;\n\n  if (vm.count(\"Q\") && vm.count(\"v\")) {\n    std::cerr << \"Running with fixed values of Q and v\\n\";\n    auto Q = vm[\"Q\"].as<int32_t>();\n    auto v = vm[\"v\"].as<int32_t>();\n    chinese_remainder::chinese_remainder<tutte>(td, Q, v);\n  } else {\n    auto Q = polynomial_two<int>::Q();\n    auto v = polynomial_two<int>::v();\n\n    if (vm.count(\"flow\")) {\n      v = -Q;\n    } else if (vm.count(\"chromatic\")) {\n      v = -1;\n    }\n\n    if (vm.count(\"chinese-remainder\")) {\n      chinese_remainder::chinese_remainder<algo>(td, Q, v);\n    } else {\n      using gmp::mpz_int;\n      auto result = transfer::transfer(algo<mpz_int>(Q, v), td);\n      std::cout << result << \"\\n\";\n    }\n  }\n}\n", "meta": {"hexsha": "c1fea038b384a414ea168d9da0065e8d003e6ba9", "size": 6568, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "andreabedini/tutte", "max_stars_repo_head_hexsha": "6bd620e06f6ac27fafc75898a3b12e9995a5e964", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-01-29T23:04:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T13:33:46.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "andreabedini/tutte", "max_issues_repo_head_hexsha": "6bd620e06f6ac27fafc75898a3b12e9995a5e964", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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": "andreabedini/tutte", "max_forks_repo_head_hexsha": "6bd620e06f6ac27fafc75898a3b12e9995a5e964", "max_forks_repo_licenses": ["BSD-3-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.7194570136, "max_line_length": 90, "alphanum_fraction": 0.6298721072, "num_tokens": 1765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.26838842492807635}}
{"text": "// Boost.Units\n\n#include <iostream>\n\n#include <boost/units/quantity.hpp>\n#include <boost/units/systems/si.hpp>\n#include <boost/units/io.hpp>\n\nint main()\n{\n    boost::units::quantity<boost::units::si::mass> w = 20.6 * boost::units::si::kilograms + 10.2 * boost::units::si::kilograms;\n    std::cout << w << std::endl;\n}", "meta": {"hexsha": "ea86f90ca351071c4506958f4cb35b75fd01f403", "size": 317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp_playground/ex045/boost_units1.cpp", "max_stars_repo_name": "chgogos/oop", "max_stars_repo_head_hexsha": "3b0e6bbd29a76f863611e18d082913f080b1b571", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-04-23T13:45:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T18:26:47.000Z", "max_issues_repo_path": "cpp_playground/ex045/boost_units1.cpp", "max_issues_repo_name": "chgogos/oop", "max_issues_repo_head_hexsha": "3b0e6bbd29a76f863611e18d082913f080b1b571", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp_playground/ex045/boost_units1.cpp", "max_forks_repo_name": "chgogos/oop", "max_forks_repo_head_hexsha": "3b0e6bbd29a76f863611e18d082913f080b1b571", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-09-01T15:17:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T20:31:36.000Z", "avg_line_length": 24.3846153846, "max_line_length": 127, "alphanum_fraction": 0.6593059937, "num_tokens": 97, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.26838841865178714}}
{"text": "/*\n   For more information, please see: http://software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2020 Scientific Computing and Imaging Institute,\n   University of Utah.\n\n   Permission is hereby granted, free of charge, to any person obtaining a\n   copy of this software and associated documentation files (the \"Software\"),\n   to deal in the Software without restriction, including without limitation\n   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n   and/or sell copies of the Software, and to permit persons to whom the\n   Software is furnished to do so, subject to the following conditions:\n\n   The above copyright notice and this permission notice shall be included\n   in all copies or substantial portions of the Software.\n\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n   DEALINGS IN THE SOFTWARE.\n*/\n\n\n#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 <iomanip>\n#include <locale>\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\nclass KernelBase\n{\n\npublic:\n\tKernelBase(const AlgorithmBase* algo, int t) :\n\t  algo_(algo),\n\t  numprocessors_(Parallel::NumCores()),\n\t  barrier_(\"BSV KernelBase Barrier\", numprocessors_),\n\t  typeOut_(t)\n\t{\n\t}\n\n\tvirtual ~KernelBase()\n\t{\n\t}\n\n\t//! Local entry function, must be implemented by each specific kernel\n\tvirtual bool integrate(FieldHandle& mesh, FieldHandle& coil, DenseMatrixHandle& outdata) = 0;\n\nprotected:\n\n\t//! ref to the executing algorithm context\n\tconst AlgorithmBase* algo_;\n\tunsigned int numprocessors_;\n\n\t//! model miscs.\n\tVMesh* vmesh_ {nullptr};\n\tVField* vfield_ {nullptr};\n\tsize_type modelSize_ {0};\n\n\t//! coil miscs.\n\tVMesh* vcoil_ {nullptr};\n\tVField* vcoilField_ {nullptr};\n\tsize_type coilSize_ {0};\n\n\t//! parallel essential primitives\n\tBarrier barrier_;\n\tstd::vector<bool> success_;\n\n\t//! output Field\n\tint typeOut_;\n\tDenseMatrixHandle matOut_;\n\n\tbool preIntegration( FieldHandle& mesh, FieldHandle& coil )\n\t{\n\t\tvmesh_ = mesh->vmesh();\n\t\tvcoil_ = coil->vmesh();\n\t\tvfield_ = mesh->vfield();\n\t\tvcoilField_ = coil->vfield();\n\n\t\tnumprocessors_ = Parallel::NumCores();\n\n\t\t#ifdef _DEBUG\n\t\t\t//! DEBUG when we want to test with one CPU only\n\t\t\tnumprocessors_ = 1;\n\t\t#endif\n\n\t\tsuccess_.resize(numprocessors_, true);\n\n\t\t//! get number of nodes for the model\n\t\tmodelSize_ = vmesh_->num_nodes();\n\t\tassert(modelSize_ > 0);\n\n\t\tmatOut_.reset(new DenseMatrix(static_cast<int>(modelSize_), 3));\n\n    algo_->remark(\"Output matrix size: \" + std::to_string(modelSize_) + \"x3\");\n    algo_->remark(\"Number of processors:  \" + boost::lexical_cast<std::string>(numprocessors_));\n    algo_->remark(\"[Important] CPU usage will be very high while running this module. \\r\\nTo limit the number of cores used, adjust the maximum core setting in Preferences->Advanced\");\n\n\t\treturn true;\n\t}\n\n\tbool postIntegration(DenseMatrixHandle& outdata)\n\t{\n\t\t//! check for error\n\t\tfor (size_t j=0; j < success_.size(); j++)\n\t\t{\n\t\t\tif (!success_[j]) return (false);\n\t\t}\n\t\toutdata = matOut_;\n\t\treturn true;\n\t}\n};\n\nnamespace\n{\n  template<class T>\n  std::string formatWithCommas(const T& value)\n  {\n    std::stringstream ss;\n    ss.imbue(std::locale(\"\"));\n    ss << std::fixed << value;\n    return ss.str();\n  }\n}\n\nclass PieceWiseKernel : public KernelBase\n{\npublic:\n\tPieceWiseKernel(const AlgorithmBase* algo, int t ) : KernelBase(algo,t)\n\t{\n\t\t//we keep last calculated step\n\t\t//however if segments lenght varies,\n\t\t//it makes more sense to keep a look-up table of previous steps for given lenght\n\t\tautostep_ = 0.1;\n\t\textstep_ = -1.0;\n\t}\n\n\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\tbool integrate(FieldHandle& mesh, FieldHandle& coil, DenseMatrixHandle& outdata) override\n\t{\n\t\tif (!preIntegration(mesh,coil))\n\t\t{\n\t\t\treturn (false);\n\t\t}\n\n    algo_->remark(\"Launching PieceWiseKernel. Size of computation remark coming soon..\");\n\n\t\tvmesh_->synchronize(Mesh::NODES_E | Mesh::EDGES_E);\n\n\t\tVMesh::Node::array_type enodes;\n\t\tPoint enode1, enode2;\n\n\t\t//! get numbder of nodes for the coil\n\t\tcoilSize_ = vcoil_->num_nodes();\n\n\t\t//! basic assumption\n\t\tassert(modelSize_ > 0 && coilSize_ > 1);\n\n\t\tcoilNodes_.clear();\n\t\tcoilNodes_.reserve(coilSize_);\n\n\t\tfor (VMesh::Edge::index_type i = 0; i < vcoil_->num_edges(); i++)\n\t\t{\n\t\t\tvcoil_->get_nodes(enodes,i);\n\t\t\tvcoil_->get_point(enode1,enodes[0]);\n\t\t\tvcoil_->get_point(enode2,enodes[1]);\n\t\t\tcoilNodes_.push_back(Vector(enode1));\n\t\t\tcoilNodes_.push_back(Vector(enode2));\n\t\t}\n\n\t\t//! Start the multi threaded\n\t\tParallel::RunTasks([this](int i) { ParallelKernel(i); }, numprocessors_);\n\n\t\treturn postIntegration(outdata);\n\t}\n\n\tvoid setIntegrationStep(double step)\n\t{\n\t\tassert(step >= 0.0);\n\t\textstep_ = step;\n\t}\n\n\tdouble getIntegrationStep() const\n\t{\n\t\treturn extstep_;\n\t}\n\nprivate:\n\t//! integration step, will auto adapt\n\tdouble autostep_;\n\t//! integration step, externally provided\n\tdouble extstep_;\n\t//! keep nodes on the coil cached\n\tstd::vector<Vector> coilNodes_;\n\n\t//! execute in parallel\n\tvoid ParallelKernel(int proc_num)\n\t{\n\t\tassert(proc_num >= 0);\n\n\t\tint cnt = 0;\n\n\t\tconst index_type begins = (modelSize_ * proc_num) / numprocessors_;\n\t\tconst index_type ends  = (modelSize_ * (proc_num+1)) / numprocessors_;\n\n\t\tassert( begins <= ends );\n\n\t\t//! buffer of points used for integration\n\t\tstd::vector<Vector> integrPoints;\n\t\tintegrPoints.reserve(256);\n\n\t\t//! keep previous step length\n\t\t//! used for optimization purpose\n\t\tdouble prevSegLen = 123456789.12345678;\n\n\t\t//! number of integration points\n\t\tint nips = 0;\n\n    bool remarkedOnProblemSize = false;\n\n\t\ttry\n\t\t{\n\t\t\tfor (index_type iM = begins; iM < ends; iM++)\n\t\t\t{\n        Point modelNodeP;\n\t\t\t\tvmesh_->get_node(modelNodeP, iM);\n        const Vector modelNodeV(modelNodeP);\n\n\t\t\t\t// result\n\t\t\t\tVector F;\n\n\t\t\t\tfor (size_t iC0 = 0, iC1 =1, iCV = 0; iC0 < coilNodes_.size(); iC0+=2, iC1+=2, iCV++)\n\t\t\t\t{\n          double currentFromField;\n\t\t\t\t\tvcoilField_->get_value(currentFromField,iCV);\n\n\t\t\t\t\tconst double current = currentFromField == 0.0 ? 1.0 : currentFromField;\n          auto absCurrent = std::fabs(current);\n\n\t\t\t\t\tVector coilNodeThis;\n\t\t\t\t\tVector coilNodeNext;\n\n\t\t\t\t\tif (current >= 0.0)\n\t\t\t\t\t{\n\t\t\t\t\t\tcoilNodeThis = coilNodes_[iC0];\n\t\t\t\t\t\tcoilNodeNext = coilNodes_[iC1];\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tcoilNodeThis = coilNodes_[iC1];\n\t\t\t\t\t\tcoilNodeNext = coilNodes_[iC0];\n\t\t\t\t\t}\n\n\t\t\t\t\t//! Length of the curve element\n\t\t\t\t\tVector diffNodes = coilNodeNext - coilNodeThis;\n\t\t\t\t\tdouble newSegLen = diffNodes.length();\n\n\t\t\t\t\t//first check if externally suplied integration step is available and use it\n\t\t\t\t\tif (extstep_ > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tnips = newSegLen / extstep_;\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//! optimization\n\t\t\t\t\t\t//! only recompute integration step only if segment length changes\n\t\t\t\t\t\tif (Abs(prevSegLen - newSegLen ) > 0.00000001)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tprevSegLen = newSegLen;\n\n\t\t\t\t\t\t\t//auto adaptive integration step calculation\n\t\t\t\t\t\t\tnips = adjustNumberOfIntegrationPoints(newSegLen);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (nips < 3)\n\t\t\t\t\t{\n\t\t\t\t\t\talgo_->warning(\"integration step too big\");\n\t\t\t\t\t}\n\n\t\t\t\t\tintegrPoints.clear();\n\n          if (!remarkedOnProblemSize && proc_num == 0)\n          {\n            auto problemSize = (ends - begins) * coilNodes_.size() * nips;\n            algo_->remark(\"Per core load: \" + formatWithCommas(problemSize) + \" field computations.\");\n            algo_->remark(\"To speed up this module, reduce the number of nodes in either the input mesh or the coil, or pick a simpler algorithm.\");\n            remarkedOnProblemSize = true;\n          }\n\n\t\t\t\t\t//! curve segment discretization\n\t\t\t\t\tfor (int iip = 0; iip < nips; iip++)\n\t\t\t\t\t{\n\n\t\t\t\t\t\tdouble interpolant = static_cast<double>(iip) / static_cast<double>(nips);\n\t\t\t\t\t\tVector v = Interpolate( coilNodeThis, coilNodeNext, interpolant );\n\t\t\t\t\t\tintegrPoints.push_back( v );\n\t\t\t\t\t}\n\n\t\t\t\t\t//! integration step over line segment\n\t\t\t\t\tfor (int iip = 0; iip < nips -1; iip++)\n\t\t\t\t\t{\n            const auto piip = integrPoints[iip];\n            const auto piip1 = integrPoints[iip+1];\n\t\t\t\t\t\t//! Vector connecting the infinitesimal curve-element\n\t\t\t\t\t\tVector Rxyz = (piip + piip1) / 2  - modelNodeV;\n\n\t\t\t\t\t\t//! Infinitesimal curve-element components\n\t\t\t\t\t\tVector dLxyz = piip1 - piip;\n\n\t\t\t\t\t\tdouble Rn = Rxyz.length();\n\n\t\t\t\t\t\tif (typeOut_ == 1)\n\t\t\t\t\t\t{\n              //! check for distance between coil and model close to zero\n              //! it might cause numerical stability issues with respect to the cross-product\n              if (Rn < 0.00001)\n              {\n                algo_->warning(\"coil<->model distance approaching zero!\");\n              }\n\t\t\t\t\t\t\t//! Biot-Savart Magnetic Field\n\t\t\t\t\t\t\tF += 1.0e-7 * Cross( Rxyz, dLxyz ) * (absCurrent / (Rn*Rn*Rn) );\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (typeOut_ == 2)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//! Biot-Savart Magnetic Vector Potential Field\n\t\t\t\t\t\t\tF += 1.0e-7 * dLxyz * (absCurrent / (Rn) );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tmatOut_->put(iM,0, F[0]);\n\t\t\t\tmatOut_->put(iM,1, F[1]);\n\t\t\t\tmatOut_->put(iM,2, F[2]);\n\n\t\t\t\t//! progress reporter\n\t\t\t\tif (proc_num == 0)\n\t\t\t\t{\n\t\t\t\t\tcnt++;\n\t\t\t\t\tif (cnt == 200)\n\t\t\t\t\t{\n\t\t\t\t\t\tcnt = 0;\n\t\t\t\t\t\talgo_->update_progress_max(iM, ends-begins);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tsuccess_[proc_num] = true;\n\t\t}\n\t\tcatch (...)\n\t\t{\n\t\t\talgo_->error(\"PieceWiseKernel crashed while integrating\");\n\t\t\tsuccess_[proc_num] = false;\n\t\t}\n\n\t\t//! check point\n\t\tbarrier_.wait();\n\n\t\t// Bail out if one of the processes failed\n\t\tfor (size_t q = 0; q < numprocessors_; q++)\n\t\t\tif (!success_[q]) return;\n\t}\n\n\t//! Auto adjust accuracy of integration\n\tint adjustNumberOfIntegrationPoints(double len)\n\t{\n\t\tint minNP = 100;//more than 1 for sure\n\t\tint maxNP = 200;//no more than 1000\n\t\tint NP = 0;\n\t\tbool over = false;\n\t\tbool under = false;\n\n\t\tdo\n\t\t{\n\t\t\tNP = ceil( len / autostep_ );\n\n\t\t\tunder = NP < minNP;\n\t\t\tover = NP > maxNP;\n\n\t\t\tif (under) autostep_ *= 0.5;\n\t\t\tif (over) autostep_ *= 1.5;\n\n\t\t} while ( under || over );\n\n\t\treturn NP;\n\t}\n};\n\n//! TODO\nclass VolumetricKernel : public KernelBase\n{\npublic:\n\tusing KernelBase::KernelBase;\n\n\tbool integrate(FieldHandle& mesh, FieldHandle& coil, DenseMatrixHandle& outdata) override\n\t{\n\t\tif (!preIntegration(mesh,coil))\n\t\t{\n\t\t\treturn (false);\n\t\t}\n\n    algo_->remark(\"Launching VolumetricKernel\");\n\n\t\t//! get numbder of nodes for the coil\n\t\tcoilSize_ = vcoil_->num_elems();\n\n\t\t//! basic assumption\n\t\tassert(modelSize_ > 0 && coilSize_ > 1);\n\n\t\tvmesh_->synchronize(Mesh::NODES_E | Mesh::EDGES_E);\n\n\t\t//! Start the multi threaded\n\t\tParallel::RunTasks([this](int i) { ParallelKernel(i); }, numprocessors_);\n\n\t\treturn postIntegration(outdata);\n\t}\nprivate:\n\tvoid ParallelKernel(int proc_num)\n\t{\n\t\tassert(proc_num >= 0);\n\n\t\tint cnt = 0;\n\t\tPoint modelNode;\n\t\tPoint coilCenter;\n\t\tVector current;\n\n\t\tconst VMesh::Node::index_type begins = (modelSize_ * proc_num) / numprocessors_;\n\t\tconst VMesh::Node::index_type ends  = (modelSize_ * (proc_num+1)) / numprocessors_;\n\n\t\tassert( begins <= ends );\n\n\t\ttry\n\t\t{\n\t\t\tfor (VMesh::Node::index_type iM = begins; iM < ends; iM++)\n\t\t\t{\n\t\t\t\tvmesh_->get_node(modelNode,iM);\n\n\t\t\t\t//! accumulatedresult\n\t\t\t\tVector F, R;\n\t\t\t\tdouble evol = 0.0;\n\t\t\t\tdouble Rl;\n\n\t\t\t\tfor (VMesh::Elem::index_type iC = 0; iC < coilSize_; iC++)\n\t\t\t\t{\n\t\t\t\t\tvcoilField_->get_value(current,iC);\n\n\t\t\t\t\tvcoilField_->get_center(coilCenter, iC);//auto resolve based on basis_order\n\n\t\t\t\t\tevol = vcoil_->get_volume(iC);\n\n\t\t\t\t\tR = coilCenter - modelNode;\n\n\t\t\t\t\tRl = R.length();\n\n\t\t\t\t\tif (typeOut_ == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\t//! Biot-Savart Magnetic Field\n\t\t\t\t\t\tF += Cross ( current , R ) * ( evol / (4.0 * M_PI * Rl) );\n\t\t\t\t\t}\n\t\t\t\t\telse if (typeOut_ == 2)\n\t\t\t\t\t{\n\t\t\t\t\t\t//! Biot-Savart Magnetic Vector Potential Field\n\t\t\t\t\t\tF += current * ( evol / (4.0 * M_PI * Rl) );\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tmatOut_->put(iM, 0, F[0]);\n\t\t\t\tmatOut_->put(iM, 1, F[1]);\n\t\t\t\tmatOut_->put(iM, 2, F[2]);\n\n\t\t\t\t//! progress reporter\n\t\t\t\tif (proc_num == 0)\n\t\t\t\t{\n\t\t\t\t\tcnt++;\n\t\t\t\t\tif (cnt == 200)\n\t\t\t\t\t{\n\t\t\t\t\t\tcnt = 0;\n\t\t\t\t\t\talgo_->update_progress_max(iM, ends - begins);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsuccess_[proc_num] = true;\n\t\t}\n\t\tcatch (...)\n\t\t{\n\t\t\talgo_->error(\"VolumetricKernel crashed while integrating\");\n\t\t\tsuccess_[proc_num] = false;\n\t\t}\n\n\t\t//! check point\n\t\tbarrier_.wait();\n\n\t\t// Bail out if one of the processes failed\n\t\tfor (size_t q = 0; q < numprocessors_; q++)\n\t\t\tif (!success_[q])\n\t\t\t\treturn;\n\t}\n};\n\n\n//! Magnetic Dipoles solver\nclass DipolesKernel : public KernelBase\n{\npublic:\n\tusing KernelBase::KernelBase;\n\n\tbool integrate(FieldHandle& mesh, FieldHandle& coil, DenseMatrixHandle& outdata) override\n\t{\n\t\tif (!preIntegration(mesh,coil))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n    algo_->remark(\"Launching DipolesKernel\");\n\n\t\t//! get number of nodes for the coil\n\t\tcoilSize_ = vcoil_->num_elems();\n\n\t\t//! basic assumption\n\t\tassert(modelSize_ > 0 && coilSize_ > 1);\n\n\t\t//needed?\n\t\tvmesh_->synchronize(Mesh::NODES_E | Mesh::EDGES_E);\n\n\t\t//! Start the multi threaded\n\t\tParallel::RunTasks([this](int i) { ParallelKernel(i); }, numprocessors_);\n\n\t\treturn postIntegration(outdata);\n\t}\n\nprivate:\n\tvoid ParallelKernel(int proc_num)\n\t{\n\t\tassert(proc_num >= 0);\n\n\t\tint cnt = 0;\n\t\tPoint modelNode;\n\t\tPoint dipoleLocation;\n\t\tVector dipoleMoment;\n\n\t\tconst VMesh::Node::index_type begins = (modelSize_ * proc_num) / numprocessors_;\n\t\tconst VMesh::Node::index_type ends  = (modelSize_ * (proc_num+1)) / numprocessors_;\n\n\t\tassert( begins <= ends );\n\n\t\ttry\n\t\t{\n\t\t\tfor (VMesh::Node::index_type iM = begins; iM < ends; iM++)\n\t\t\t{\n\t\t\t\tvmesh_->get_node(modelNode,iM);\n\n\t\t\t\t//! accumulated result\n\t\t\t\tVector F, R;\n\t\t\t\tdouble Rl;\n\n\t\t\t\tfor (VMesh::Elem::index_type iC = 0; iC < coilSize_; iC++)\n\t\t\t\t{\n\t\t\t\t\tvcoilField_->get_value(dipoleMoment, iC);\n\t\t\t\t\tvcoilField_->get_center(dipoleLocation, iC);//auto resolve based on basis_order\n\n\t\t\t\t\tR = dipoleLocation - modelNode;\n\t\t\t\t\tRl = R.length();\n\n\t\t\t\t\tif (typeOut_ == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\t//! Biot-Savart Magnetic Field\n\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}\n\t\t\t\t\tif (typeOut_ == 2)\n\t\t\t\t\t{\n\t\t\t\t\t\t//! Biot-Savart Magnetic Vector Potential Field\n\t\t\t\t\t\tF += 1.0e-7 * Cross ( dipoleMoment , R ) / (Rl*Rl*Rl) ;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tmatOut_->put(iM, 0, F[0]);\n\t\t\t\tmatOut_->put(iM, 1, F[1]);\n\t\t\t\tmatOut_->put(iM, 2, F[2]);\n\n\t\t\t\t//! progress reporter\n\t\t\t\tif (proc_num == 0)\n\t\t\t\t{\n\t\t\t\t\tcnt++;\n\t\t\t\t\tif (cnt == 200)\n\t\t\t\t\t{\n\t\t\t\t\t\tcnt = 0;\n\t\t\t\t\t\talgo_->update_progress_max(iM, ends - begins);;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsuccess_[proc_num] = true;\n\t\t}\n\t\tcatch (...)\n\t\t{\n\t\t\talgo_->error(std::string(\"DipoleKernel crashed while integrating\"));\n\t\t\tsuccess_[proc_num] = false;\n\t\t}\n\n\t\t//! check point\n\t\tbarrier_.wait();\n\n\t\t// Bail out if one of the processes failed\n\t\tfor (size_t q = 0; q < numprocessors_; q++)\n\t\t\tif (!success_[q])\n\t\t\t\treturn;\n\t}\n};\n\nbool BiotSavartSolverAlgorithm::run(FieldHandle mesh, FieldHandle coil, DenseMatrixHandle& 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\t\terror(\"Need data on coil mesh.\");\n\t\treturn (false);\n  }\n\n  if (coil->vmesh()->is_curvemesh())\n  {\n    if (coil->vfield()->is_constantdata() && coil->vfield()->is_scalar())\n    {\n      PieceWiseKernel pwk(this, outtype);\n      if (!pwk.integrate(mesh,coil,outdata))\n      {\n\t\t\t\terror(\"Aborted during integration\");\n\t\t\t\treturn (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\t\tif ((coil->vfield()->is_lineardata() || coil->vfield()->is_constantdata() ) && coil->vfield()->is_vector())\n\t\t{\n\t\t\tDipolesKernel dp(this, outtype);\n\t\t\tif (!dp.integrate(mesh,coil,outdata))\n\t\t\t{\n\t\t\t\terror(\"Aborted during integration\");\n\t\t\t\treturn (false);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\terror(\"Pointcloud expected with linear vector data.\");\n\t\t\treturn (false);\n\t\t}\n\t}\n  else if (coil->vmesh()->is_volume())\n  {\n\t\tif (coil->vfield()->is_constantdata() && coil->vfield()->is_vector())\n\t\t{\n\t\t\tVolumetricKernel vp(this, outtype);\n\t\t\tif (!vp.integrate(mesh,coil,outdata))\n\t\t\t{\n\t\t\t\terror(\"Aborted during integration\");\n\t\t\t\treturn (false);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\terror(\"Volumetric mesh expected with constant vector data.\");\n\t\t\treturn (false);\n\t\t}\n\t}\n\telse\n\t{\n\t\terror(\"Unsupported mesh type! Only curve or volumetric.\");\n\t\treturn (false);\n\t}\n\n  return (true);\n}\n\nAlgorithmOutput BiotSavartSolverAlgorithm::run(const AlgorithmInput& input) const\n{\n\tAlgorithmOutput output;\n\n\tauto mesh = input.get<Field>(Parameters::Mesh);\n\tauto coil = input.get<Field>(Parameters::Coil);\n\n\tauto oports = get(Parameters::OutType).toInt();\n\tstd::map<int, DenseMatrixHandle> cases;\n\tif (oports == 3)\n\t\tcases = {{1, nullptr}, {2, nullptr}};\n\telse\n\t\tcases[oports] = nullptr;\n\n  for (auto& c : cases)\n  {\n    if (!run(mesh, coil, c.second, c.first))\n    {\n      error(\"Error: Algorithm of BiotSavartSolver failed.\");\n    }\n  }\n\toutput[Parameters::VectorBField] = cases[1];\n\toutput[Parameters::VectorAField] = cases[2];\n\n\treturn output;\n}\n", "meta": {"hexsha": "a4a42b5549c95b33a005c7fe9c7f66226d3c0dd3", "size": 18391, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Algorithms/BrainStimulator/BiotSavartSolverAlgorithm.cc", "max_stars_repo_name": "mckees/SCIRun", "max_stars_repo_head_hexsha": "40c2c5b17925181bd2581ab8e11b325d58618165", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Core/Algorithms/BrainStimulator/BiotSavartSolverAlgorithm.cc", "max_issues_repo_name": "mckees/SCIRun", "max_issues_repo_head_hexsha": "40c2c5b17925181bd2581ab8e11b325d58618165", "max_issues_repo_licenses": ["MIT"], "max_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": "mckees/SCIRun", "max_forks_repo_head_hexsha": "40c2c5b17925181bd2581ab8e11b325d58618165", "max_forks_repo_licenses": ["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.6198125837, "max_line_length": 184, "alphanum_fraction": 0.6486324833, "num_tokens": 5305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2680326628819653}}
{"text": "/******************************************************************************\n *\n * AMDiS - Adaptive multidimensional simulations\n *\n * Copyright (C) 2013 Dresden University of Technology. All Rights Reserved.\n * Web: https://fusionforge.zih.tu-dresden.de/projects/amdis\n *\n * Authors:\n * Simon Vey, Thomas Witkowski, Andreas Naumann, Simon Praetorius, et al.\n *\n * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE\n * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\n *\n * This file is part of AMDiS\n *\n * See also license.opensource.txt in the distribution.\n *\n ******************************************************************************/\n\n\n#include <vector>\n#include <boost/numeric/mtl/mtl.hpp>\n#include \"SubElementAssembler.h\"\n#include \"ScalableQuadrature.h\"\n#include \"SubPolytope.h\"\n\nnamespace compositeFEM\n{\n\n  SubElementAssembler::SubElementAssembler(Operator* op,\n      const FiniteElemSpace* rowFeSpace_,\n      const FiniteElemSpace* colFeSpace_)\n    : StandardAssembler(op, NULL, NULL, NULL, NULL, rowFeSpace_, colFeSpace_)\n  {\n    /**\n     * Create a scalable quadrature for subassembler and replace the original\n     * quadrature of the subassembler with the scalable quadrature.\n     */\n\n    if (zeroOrderAssembler)\n    {\n      checkQuadratures();\n      zeroOrderScalableQuadrature =\n        new ScalableQuadrature(zeroOrderAssembler->getQuadrature());\n      zeroOrderAssembler->setQuadrature(zeroOrderScalableQuadrature);\n    }\n    else\n    {\n      zeroOrderScalableQuadrature = NULL;\n    }\n\n    if (firstOrderAssemblerGrdPsi)\n    {\n      checkQuadratures();\n      firstOrderGrdPsiScalableQuadrature =\n        new ScalableQuadrature(firstOrderAssemblerGrdPsi->getQuadrature());\n      firstOrderAssemblerGrdPsi->setQuadrature(firstOrderGrdPsiScalableQuadrature);\n    }\n    else\n    {\n      firstOrderGrdPsiScalableQuadrature = NULL;\n    }\n\n    if (firstOrderAssemblerGrdPhi)\n    {\n      checkQuadratures();\n      firstOrderGrdPhiScalableQuadrature =\n        new ScalableQuadrature(firstOrderAssemblerGrdPhi->getQuadrature());\n      firstOrderAssemblerGrdPhi->setQuadrature(firstOrderGrdPhiScalableQuadrature);\n    }\n    else\n    {\n      firstOrderGrdPhiScalableQuadrature = NULL;\n    }\n\n    if (secondOrderAssembler)\n    {\n      checkQuadratures();\n      secondOrderScalableQuadrature =\n        new ScalableQuadrature(secondOrderAssembler->getQuadrature());\n      secondOrderAssembler->setQuadrature(secondOrderScalableQuadrature);\n    }\n    else\n    {\n      secondOrderScalableQuadrature = NULL;\n    }\n  }\n\n  void SubElementAssembler::scaleQuadratures(const SubElInfo& subElInfo)\n  {\n    if (zeroOrderAssembler)\n    {\n      zeroOrderScalableQuadrature->scaleQuadrature(subElInfo);\n    }\n    if (firstOrderAssemblerGrdPsi)\n    {\n      firstOrderGrdPsiScalableQuadrature->scaleQuadrature(subElInfo);\n    }\n    if (firstOrderAssemblerGrdPhi)\n    {\n      firstOrderGrdPhiScalableQuadrature->scaleQuadrature(subElInfo);\n    }\n    if (secondOrderAssembler)\n    {\n      secondOrderScalableQuadrature->scaleQuadrature(subElInfo);\n    }\n  }\n\n  void SubElementAssembler::getSubElementVector(SubElInfo* subElInfo,\n      const ElInfo* elInfo,\n      DenseVector<double>& userVec)\n  {\n    /**\n     * Manipulate the quadratures of the SubAssemblers for subelement.\n     */\n    scaleQuadratures(*subElInfo);\n\n    calculateElementVector(elInfo, userVec);\n\n    /**\n     * The integration has been performed with a quadrature living on element. The\n     * determinant of element has been used instead of the determinant of subelement. Thus\n     * the result must be corrected with respect to subelement.\n     */\n    double corrFactor = subElInfo->getDet() / fabs(elInfo->getDet());\n    for (int i = 0; i < nRow; i++)\n      userVec[i] *= corrFactor;\n  }\n\n  void SubElementAssembler::getSubElementMatrix(SubElInfo* subElInfo,\n      const ElInfo* elInfo,\n      ElementMatrix& userMat)\n  {\n    /**\n     * Manipulate the quadratures of the SubAssemblers for subelement.\n     */\n    scaleQuadratures(*subElInfo);\n\n    /**\n     * Integrate using the manipulated quadrature.\n     */\n    calculateElementMatrix(elInfo, userMat);\n\n    /**\n     * The integration has been performed with a quadrature living on element. The\n     * determinant of element has been used instead of the determinant of subelement.\n     * Thus the result must be corrected with respect to subelement.\n     */\n    double corrFactor = subElInfo->getDet() / fabs(elInfo->getDet());\n    for (int i = 0; i < nRow; i++)\n    {\n      for (int j = 0; j < nCol; j++)\n      {\n        userMat[i][j] *= corrFactor;\n      }\n    }\n  }\n\n  void SubElementAssembler::getSubPolytopeVector(SubPolytope* subPolytope,\n      SubElementAssembler* subElementAssembler,\n      const ElInfo* elInfo,\n      DenseVector<double>& subPolVec)\n  {\n    /// Note: There is no reset of subPolVec.\n    std::vector<SubElInfo*>::iterator it;\n    DenseVector<double> subElVec(nRow);\n\n    /// Assemble for each subelement of subpolytope.\n    for (it = subPolytope->getSubElementsBegin();\n         it != subPolytope->getSubElementsEnd();\n         it++)\n    {\n      set_to_zero(subElVec);\n      subElementAssembler->getSubElementVector(*it, elInfo, subElVec);\n\n      /// Add results for subelement to total result for subpolytope.\n      subPolVec += subElVec;\n    }\n  }\n\n  void SubElementAssembler::getSubPolytopeMatrix(SubPolytope* subPolytope,\n      SubElementAssembler* subElementAssembler,\n      const ElInfo* elInfo,\n      ElementMatrix& subPolMat)\n  {\n    /**\n     * Note: There is no reset of subPolMat.\n     */\n    std::vector<SubElInfo*>::iterator it;\n    ElementMatrix subElMat(nRow, nCol);\n\n    /**\n     * Assemble for each subelement of subpolytope.\n     */\n    for (it = subPolytope->getSubElementsBegin();\n         it != subPolytope->getSubElementsEnd();\n         it++)\n    {\n      set_to_zero(subElMat);\n      subElementAssembler->getSubElementMatrix(*it, elInfo, subElMat);\n\n      /**\n       * Add results for subelement to total result for subpolytope.\n       */\n      for (int i = 0; i < nRow; i++)\n        for (int j = 0; j < nCol; j++)\n          subPolMat[i][j] += subElMat[i][j];\n    }\n  }\n\n}\n", "meta": {"hexsha": "b3bc3399bd5afd8f50a6dd61c71834959b600ecc", "size": 6186, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/compositeFEM/SubElementAssembler.cpp", "max_stars_repo_name": "spraetor/amdis2", "max_stars_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T16:44:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T07:26:27.000Z", "max_issues_repo_path": "src/compositeFEM/SubElementAssembler.cpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/compositeFEM/SubElementAssembler.cpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0422535211, "max_line_length": 90, "alphanum_fraction": 0.6618170061, "num_tokens": 1603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2679904786531365}}
{"text": "/*\n    Lightmetrica - A modern, research-oriented renderer\n\n    Copyright (c) 2015 Hisanari Otsu\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 <lightmetrica/lightmetrica.h>\n#include \"radiosityutils.h\"\n#include <sstream>\n#include <boost/format.hpp>\n#if LM_COMPILER_MSVC\n#pragma warning(disable:4714)\n#pragma warning(disable:4701)\n#pragma warning(disable:4456)\n#include <Eigen/Sparse>\n#else\n#include <eigen3/Eigen/Sparse>\n#endif\n\n#define LM_RADIOSITY_DEBUG 0\n\nnamespace Eigen\n{\n    template <>\n    struct NumTraits<lightmetrica_v2::Vec3>\n    {\n        using T          = lightmetrica_v2::Vec3;\n        using VT         = lightmetrica_v2::Float;\n        using Real       = T;\n        using NonInteger = T;\n        using Nested     = T;\n        using Literal    = T;\n        enum\n        {\n            IsComplex = 0,\n            IsInteger = 0,\n            IsSigned = 1,\n            RequireInitialization = 1,\n            ReadCost = 3,\n            AddCost = 3,\n            MulCost = 3\n        };\n        static inline T epsilon()         { return T(NumTraits<VT>::epsilon()); }\n        static inline T dummy_precision() { return T(NumTraits<VT>::dummy_precision()); }\n        static inline T highest()         { return T(std::numeric_limits<VT>::max()); }\n        static inline T lowest()          { return T(std::numeric_limits<VT>::min()); }\n    };\n\n    namespace internal\n    {\n        template<>\n        struct significant_decimals_impl<lightmetrica_v2::Vec3>\n        {\n            static inline int run()\n            {\n                return significant_decimals_impl<lightmetrica_v2::Float>::run();\n            }\n        };\n    }\n}\n\nLM_NAMESPACE_BEGIN\n\n// For Eigen\n// https://eigen.tuxfamily.org/dox/TopicCustomizingEigen.html\nauto abs(const Vec3& v) -> Vec3 { return Vec3(std::abs(v.x), std::abs(v.y), std::abs(v.z)); }\nauto sqrt(const Vec3& v) -> Vec3 { return Vec3(std::sqrt(v.x), std::sqrt(v.y), std::sqrt(v.z)); }\nauto log(const Vec3& v) -> Vec3 { return Vec3(std::log(v.x), std::log(v.y), std::log(v.z)); }\nauto ceil(const Vec3& v) -> Vec3 { return Vec3(std::ceil(v.x), std::ceil(v.y), std::ceil(v.z)); }\nauto operator<<(std::ostream& os, const Vec3& v) -> std::ostream&\n{\n    os << \"(\" << v.x << \",\" << v.y << \",\" << v.z << \")\";\n    return os;\n}\n\n/*!\n    \\brief Radiosity renderer.\n    \n    Implements the radiosity algorithm by directly solving linear system.\n    This implementation currently only supports the diffues BSDF (`bsdf::diffuse`)\n    and the area light (`light::area`).\n\n    References:\n      - [Cohen & Wallace 1995] Radiosity and realistic image synthesis\n      - [Willmott & Heckbert 1997] An empirical comparison of radiosity algorithms\n      - [Schroder & Hanrahan 1993] On the form factor between two polygons\n*/\nclass Renderer_Radiosity final : public Renderer\n{\npublic:\n\n    LM_IMPL_CLASS(Renderer_Radiosity, Renderer);\n\npublic:\n\n    LM_IMPL_F(Initialize) = [this](const PropertyNode* prop) -> bool\n    {\n        subdivLimitArea_ = prop->ChildAs<Float>(\"subdivlimitarea\", 0.1_f);\n        wireframe_ = prop->ChildAs<int>(\"wireframe\", 0);\n        return true;\n    };\n\n    LM_IMPL_F(Render) = [this](const Scene* scene_, Random* initRng, const std::string& outputPath) -> void\n    {\n        const auto* scene = static_cast<const Scene3*>(scene_);\n        auto* film = static_cast<const Sensor*>(scene->GetSensor()->emitter)->GetFilm();\n\n        // --------------------------------------------------------------------------------\n\n        // Create patches\n        Patches patches;\n        patches.Create(scene, subdivLimitArea_);\n\n        // --------------------------------------------------------------------------------\n\n        #pragma region Setup matrices\n\n        LM_LOG_INFO(\"Setup matrix\");\n\n        const int N = patches.Size();\n        //using Matrix = Eigen::SparseMatrix<Vec3>;\n        using Matrix = Eigen::Matrix<Vec3, Eigen::Dynamic, Eigen::Dynamic>;\n        using Vector = Eigen::Matrix<Vec3, Eigen::Dynamic, 1>;\n\n        // Setup emission term\n        Vector E(N);\n        for (int i = 0; i < N; i++)\n        {\n            const auto& patch = patches.At(i);\n            const auto* light = patch.primitive->light;\n            if (!light)\n            {\n                continue;\n            }\n            E(i) = light->Emittance().ToRGB();\n        }\n\n        // Setup matrix of interactions\n        Matrix K(N, N);\n        K.setIdentity();\n        for (int i = 0; i < N; i++)\n        {\n            for (int j = 0; j < N; j++)\n            {\n                const auto Fij = RadiosityUtils::EstimateFormFactor(scene, patches.At(i), patches.At(j));\n                if (Fij > 0_f)\n                {\n                    K.coeffRef(i, j) -= patches.At(i).primitive->bsdf->Reflectance().ToRGB() * Fij;\n                }\n            }\n\n            const double progress = 100.0 * i / N;\n            LM_LOG_INPLACE(boost::str(boost::format(\"Progress: %.1f%%\") % progress));\n        }\n\n        LM_LOG_INFO(\"Progress: 100.0%\");\n\n        #pragma endregion\n\n        // --------------------------------------------------------------------------------\n\n        #pragma region Solve radiosity equation\n\n        LM_LOG_INFO(\"Solving linear system\");\n\n        Eigen::BiCGSTAB<Matrix> solver;\n        solver.compute(K);\n        Vector B = solver.solve(E);\n\n        #if LM_RADIOSITY_DEBUG\n        std::stringstream ss;\n        ss << B << std::endl;\n        LM_LOG_INFO(ss.str());\n        #endif\n\n        #pragma endregion\n\n        // --------------------------------------------------------------------------------\n\n        #pragma region Rendering (ray casting)\n\n        LM_LOG_INFO(\"Visualizing result\");\n\n        const int width  = film->Width();\n        const int height = film->Height();\n        for (int y = 0; y < height; y++)\n        {\n            for (int x = 0; x < width; x++)\n            {\n                // Raster position\n                Vec2 rasterPos((Float(x) + 0.5_f) / Float(width), (Float(y) + 0.5_f) / Float(height));\n\n                // Position and direction of a ray\n                SurfaceGeometry geomE;\n                Vec3 wo;\n                scene->GetSensor()->emitter->SamplePositionAndDirection(rasterPos, Vec2(), geomE, wo);\n\n                // Setup a ray\n                Ray ray = { geomE.p, wo };\n\n                // Intersection query\n                Intersection isect;\n                if (!scene->Intersect(ray, isect))\n                {\n                    // No intersection -> black\n                    film->SetPixel(x, y, SPD());\n                    continue;\n                }\n                \n                // Compute patch index & visualize the radiosity\n                patches.IteratePatches(isect, subdivLimitArea_, [&](size_t patchindex, const Vec2& uv) -> void\n                {\n                    if (wireframe_)\n                    {\n                        // Visualize wire frame\n                        // Compute minimum distance from each edges\n                        const auto mind = Math::Min(uv.x, Math::Min(uv.y, 1_f - uv.x - uv.y));\n                        if (mind < 0.05f)\n                        {\n                            film->SetPixel(x, y, SPD(Math::Abs(Math::Dot(isect.geom.sn, -ray.d))));\n                        }\n                    }\n                    else\n                    {\n                        film->SetPixel(x, y, SPD(B(patchindex)));\n                    }\n                });\n            }\n\n            if (y % 10 == 0)\n            {\n                const double progress = 100.0 * y / film->Height();\n                LM_LOG_INPLACE(boost::str(boost::format(\"Progress: %.1f%%\") % progress));\n            }\n        }\n\n        LM_LOG_INFO(\"Progress: 100.0%\");\n\n        #pragma endregion\n\n        // --------------------------------------------------------------------------------\n\n        #pragma region Save image\n        {\n            LM_LOG_INFO(\"Saving image\");\n            LM_LOG_INDENTER();\n            film->Save(outputPath);\n        }\n        #pragma endregion\n    };\n\nprivate:\n\n    Float subdivLimitArea_;\n    int wireframe_;\n\n};\n\nLM_COMPONENT_REGISTER_IMPL(Renderer_Radiosity, \"renderer::radiosity\");\n\nLM_NAMESPACE_END\n", "meta": {"hexsha": "c9859c289c8555b99df45d731d03b8c4c52df13f", "size": 9202, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "plugin/renderer_radiosity/renderer_radiosity.cpp", "max_stars_repo_name": "jammm/lightmetrica-v2", "max_stars_repo_head_hexsha": "6864942ec48d37f2c35dc30a38a26d7cc4bb527e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 150.0, "max_stars_repo_stars_event_min_datetime": "2015-12-28T10:26:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T14:36:16.000Z", "max_issues_repo_path": "plugin/renderer_radiosity/renderer_radiosity.cpp", "max_issues_repo_name": "jammm/lightmetrica-v2", "max_issues_repo_head_hexsha": "6864942ec48d37f2c35dc30a38a26d7cc4bb527e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plugin/renderer_radiosity/renderer_radiosity.cpp", "max_forks_repo_name": "jammm/lightmetrica-v2", "max_forks_repo_head_hexsha": "6864942ec48d37f2c35dc30a38a26d7cc4bb527e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2016-02-08T10:57:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-04T03:57:33.000Z", "avg_line_length": 32.8642857143, "max_line_length": 110, "alphanum_fraction": 0.5268419909, "num_tokens": 2068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150636, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.26792187363657843}}
{"text": "// Copyright 2020 Poofee (https://github.com/Poofee)\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// 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 *****************************************************************************\n *                                                                           *\n *  Authors: Poofee                                                          *\n *  Email:   poofee@qq.com                                                   *\n *  Address:                                                                 *\n *  Original Date: 2020-07-15                                                *\n *                                                                           *\n *****************************************************************************/\n#include \"relay1250.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <cmath>\n#if !defined(ARMA_32BIT_WORD)\n#define ARMA_32BIT_WORD\n#endif\n#include <armadillo>\n#include <vector>\n#include <ctime>\n#include <omp.h>\n\n#include \"SuperLU_MT.h\"\n#include \"qcustomplot.h\"\n#include \"slu_mt_ddefs.h\"\n\n\nusing namespace std;\nusing namespace arma;\n\n#define PI 3.14159265358979323846\n#define r 2\n\nconst double miu0 = PI*4e-7;\n\nRelay1250::Relay1250()\n{\n\n}\n\nRelay1250::~Relay1250()\n{\n\n}\n\n/*!\n \\brief 参数初始化\n\n*/\nvoid Relay1250::init()\n{\n    /** 文件名，需不带扩展名 **/\n    sprintf(fileName,\"%s\",\"JRS1250/JRS1250bgm\");\n    /** 初始化时间步长 **/\n    current_step = 0;\n    min_time = 0;\n    max_time = 4e-3;\n    for(double t = 1e-5; t < 3e-3; t+=1e-5){\n        timesteps.emplace_back(1e-5);\n    }\n    for(double t = 3e-3; t <= 3e-3; t+=5e-5){\n        timesteps.emplace_back(5e-5);\n    }\n\n    /** 初始化变量 **/\n    current_step = 0;\n    Ddisplacements.resize(timesteps.size()+1);\n    Ddisplacements.at(current_step) = 0;\n    displacements.resize(timesteps.size()+1);\n    displacements.at(current_step) = 0;\n    velocities.resize(timesteps.size()+1);\n    velocities.at(current_step) = 0;\n    accelerations.resize(timesteps.size()+1);\n    accelerations.at(current_step) = 0;\n    PhiCoil.resize(timesteps.size()+1);\n    PhiCoil.at(current_step) = 0;\n    ICoil.resize(timesteps.size()+1);\n    ICoil.at(current_step) = 0;\n    magforces.resize(timesteps.size()+1);\n    magforces.at(current_step) = 0;\n    UCoil.resize(timesteps.size()+1);\n    UCoil.at(current_step) = 420;\n\n    MAX_NONLINEARSTEPS = 20;\n    /** 设置材料参数 **/\n    CMaterial* air_material = new CMaterial;\n    materialList.emplace_back(air_material);\n\n    CMaterial* pm_material = new CMaterial;\n    materialList.emplace_back(pm_material);\n    pm_material->H_c = 1e6;\n    pm_material->miu = 1.12;\n\n    CMaterial* dt4e_material = new CMaterial;\n    materialList.emplace_back(dt4e_material);\n    dt4e_material->sigma = 1/(2e-7);\n    dt4e_material->BHpoints = 20;\n    double* Hdata = (double*)malloc(20*sizeof(double));\n    double* Bdata = (double*)malloc(20*sizeof(double));\n    /** 1250的BH曲线 **/\n\n\n    CMaterial* coil_material = new CMaterial;\n    materialList.emplace_back(coil_material);\n    coil_material->tau = 60/(3e-3 * 17e-3);\n\n    /** 设置映射关系 **/\n    materialMap[1] = dt4e_material;/** 衔铁 **/\n    materialMap[2] = coil_material;/** 线圈 **/\n    materialMap[3] = dt4e_material;/** 铁芯 **/\n    materialMap[4] = dt4e_material;/** 铁芯 **/\n    materialMap[5] = dt4e_material;/** 铁芯 **/\n    materialMap[6] = pm_material;/** 永磁 **/\n    materialMap[7] = dt4e_material;/** 铁芯（导磁环） **/\n    materialMap[8] = dt4e_material;/** 铁芯 **/\n    materialMap[9] = air_material;/** 外部空气 **/\n    materialMap[10] = air_material;/** 可压缩空气 **/\n    /** 设置形变区域 **/\n    tag_xiantie = 1;\n    tag_air = 10;\n\n    Precision = 1e-6;\n}\n\n\n\n/*!\n \\brief 计算区域index的电磁力，如果没有指定的话，就按衔铁算。\n\n \\param index\n*/\nvoid Relay1250::calcMagForce(int index)\n{\n\n}\n\n/*!\n \\brief 计算三角形单元的基本项\n\n \\param index\n*/\nvoid Relay1250::makeTriangle(int index)\n{\n    int k,m,n;\n    double p0,p1,p2,q0,q1,q2,area;\n    k = pmeshele[index].n[0];\n    m = pmeshele[index].n[1];\n    n = pmeshele[index].n[2];\n\n    p0 = pmeshnode[m].y - pmeshnode[n].y;\n    pmeshele[index].P[0] = p0;\n    p1 = pmeshnode[n].y - pmeshnode[k].y;\n    pmeshele[index].P[1] = p1;\n    p2 = pmeshnode[k].y - pmeshnode[m].y;\n    pmeshele[index].P[2] = p2;\n\n    q0 = pmeshnode[n].x - pmeshnode[m].x;\n    pmeshele[index].Q[0] = q0;\n    q1 = pmeshnode[k].x - pmeshnode[n].x;\n    pmeshele[index].Q[1] = q1;\n    q2 = pmeshnode[m].x - pmeshnode[k].x;\n    pmeshele[index].Q[2] = q2;\n\n    area = 0.5*abs(p1 * q2 - q1 * p2);\n    pmeshele[index].AREA = area;\n    pmeshele[index].rc = (pmeshnode[k].x +\n                          pmeshnode[m].x +\n                          pmeshnode[n].x) / 3;\n    pmeshele[index].zc = (pmeshnode[k].y +\n                          pmeshnode[m].y +\n                          pmeshnode[n].y) / 3;\n\n    int flag = 0;\n    for (int f = 0; f < 3; f++) {\n        if (pmeshnode[pmeshele[index].n[f]].x < 1e-7) {\n            flag++;\n        }\n    }\n    /** 计算三角形重心半径 **/\n    if (flag == 2) {\n        pmeshele[index].ydot = pmeshele[index].rc;\n    } else {\n        pmeshele[index].ydot  = 1 / (pmeshnode[k].x + pmeshnode[m].x);\n        pmeshele[index].ydot += 1 / (pmeshnode[k].x + pmeshnode[n].x);\n        pmeshele[index].ydot += 1 / (pmeshnode[m].x + pmeshnode[n].x);\n        pmeshele[index].ydot = 1.5 / pmeshele[index].ydot;\n    }\n\n//    double Y11,Y12,Y13,Y22,Y23,Y33;\n    pmeshele[index].Y11 = q0 * q0 + p0 * p0;\n    pmeshele[index].Y12 = q0 * q1 + p0 * p1;\n    pmeshele[index].Y13 = q0 * q2 + p0 * p2;\n    pmeshele[index].Y22 = q1 * q1 + p1 * p1;\n    pmeshele[index].Y23 = q1 * q2 + p1 * p2;\n    pmeshele[index].Y33 = q2 * q2 + p2 * p2;\n\n    pmeshele[index].Y11 /= 4. * area;\n    pmeshele[index].Y12 /= 4. * area;\n    pmeshele[index].Y13 /= 4. * area;\n    pmeshele[index].Y22 /= 4. * area;\n    pmeshele[index].Y23 /= 4. * area;\n    pmeshele[index].Y33 /= 4. * area;\n}\n\n/*!\n \\brief 使用传统的牛顿法进行求解\n\n*/\nvoid Relay1250::AxisNRsolve()\n{\n    /** 计时 **/\n    clock_t time[10];\n    int tt = 0;\n    time[tt++] = SuperLU_timer_();\n    /** 电路参数 **/\n    double C1 = 200e-6;\n    double C2 = 200e-6;\n    double R1 = 1e3;\n    double Rc = 28;\n    double Y1= 1/R1;\n    double Yc= 1/Rc;\n    /** 变量 **/\n    double beta = 1;\n    /** 时间步循环 **/\n    current_step = 0;\n    double totalTime = 0;\n    for(int i = 0; i < timesteps.size();i++){\n        totalTime += timesteps.at(i);\n        printf(\"Time step %d, current time is %lf s.\\n\",i,totalTime);\n        /** remesh，要使用增量位移，向下为负，向上为正 **/\n        remesh(0,Ddisplacements.at(i));\n        /** 读取第i步的分网 **/\n        loadMesh();\n        /** 查找边界，默认一次边界 **/\n        findBoundaryEdges(-1);\n        findBoundaryPoints(-1);\n\n        double* unknown_b = (double*)calloc(num_pts - boundaryPoints.size()+1, sizeof(double));\n        /** 将边界点排序到末尾 **/\n        int node_bdr = boundaryPoints.size();\n        int node_all = allPoints.size();\n        int num_dof = node_all - node_bdr + 1;/** 自由度：未知节点+电压 **/\n        /** 初始化，提出读取的gmsh多余的节点以及边界点 **/\n        for(int i2=0;i2<num_pts;i2++){\n            pmeshnode[i2].bdr = 3;\n        }\n        for(int i2=0;i2<node_all;i2++){\n            pmeshnode[allPoints.at(i2)].bdr = 0;\n        }\n        for(int i2=0;i2<node_bdr;i2++){\n            pmeshnode[boundaryPoints.at(i2)].bdr = 3;\n        }\n        /** 计算固定区域的单元节点数目，起始编号为0 **/\n        for(int i_tri = 0; i_tri < num_triangle; i_tri++){\n            int i1 = num_ele-num_triangle+i_tri;\n            if(pmeshele[i1].geometry_tag == tag_air){\n                air_position = i_tri;\n                break;\n            }\n        }\n\n        umat locs(2, 9 * num_triangle);\n        locs.zeros();\n        mat vals(1, 9 * num_triangle);\n        vec bbJz = zeros<vec>(num_pts);\n        uvec node_reorder = zeros<uvec>(num_pts);\n        uvec node_pos = zeros<uvec>(num_pts);\n        vec bn = zeros<vec>(num_pts);\n        vec A = zeros<vec>(num_pts);\n        vec A_old = A;/** 上一步的大小肯定和这一步不一样 **/\n        double Y11,Y12,Y13,Y22,Y23,Y33;\n\n        for (int ibdr = 0; ibdr < num_pts; ibdr++) {\n            if (pmeshnode[ibdr].bdr == 3) {\n                node_bdr++;\n                node_reorder(num_pts - node_bdr) = ibdr;\n                node_pos(ibdr) = num_pts - node_bdr;\n                pmeshnode[ibdr].A = 0;\n                A(ibdr) = 0;\n            } else {\n                node_reorder(ibdr - node_bdr) = ibdr;\n                node_pos(ibdr) = ibdr - node_bdr;\n            }\n        }\n        /** 单元初始化，如果是非线性区域，可以考虑优化先初始值设置 **/\n        for(int i_tri = 0; i_tri < num_triangle; i_tri++){\n            int i1 = num_ele-num_triangle+i_tri;\n            pmeshele[i1].B = 0;\n            /** 对于涡流区域，没有形变，直接将miu带过来 **/\n            if(i_tri < air_position){\n                pmeshele[i1].miu = pmeshelelast[i1].miut;\n                pmeshele[i1].miut = pmeshelelast[i1].miut;\n            }else{\n                pmeshele[i1].miu = miu0;\n                pmeshele[i1].miut = miu0;\n            }\n        }\n        double miuold = miu0;\n        /** 非线性迭代求解 **/\n        for(int non_iter = 0;non_iter < MAX_NONLINEARSTEPS;non_iter++){\n\n            /** 有限元装配 **/\n            double ce[3][3] = { {0} };/** 雅可比矩阵 **/\n            double Je[3][3] = { {0} };/** 用于牛顿迭代 **/\n            double Te[3][3] = { {0} };/** 涡流矩阵 **/\n            double De[3] = { 0 };/** 电流密度矩阵 **/\n            double dt = timesteps.at(non_iter);\n\n            int pos = 0;\n            for(int i_tri = 0; i_tri < num_triangle; i_tri++){\n                int k,m,n,i1;\n                i1 = num_ele-num_triangle+i_tri;\n                k = pmeshele[i1].n[0];m = pmeshele[i1].n[1];n = pmeshele[i1].n[2];\n\n                /** 计算除了磁导率部分的系数 **/\n                makeTriangle(i1);\n\n                /** 计算雅可比矩阵 **/\n                double ydot = pmeshele[i1].ydot;\n                double miut = pmeshele[i1].miut;\n                miuold = pmeshele[i1].miu;\n                /** 相当于C矩阵 **/\n                Y11 = pmeshele[i1].Y11;Y22 = pmeshele[i1].Y22;Y33 = pmeshele[i1].Y33;\n                Y12 = pmeshele[i1].Y12;Y13 = pmeshele[i1].Y13;Y23 = pmeshele[i1].Y23;\n\n                /** 应当是当前迭代的mu **/\n                ce[0][0] = Y11 / ydot;ce[1][1] = Y22 / ydot;ce[2][2] = Y33 / ydot;\n                ce[0][1] = Y12 / ydot;ce[0][2] = Y13 / ydot;ce[1][2] = Y23 / ydot;\n                ce[1][0] = ce[0][1];ce[2][0] = ce[0][2];ce[2][1] = ce[1][2];\n\n                double v[3];\n                v[0] = Y11*A(k) + Y12*A(m) + Y13*A(n);\n                v[1] = Y12*A(k) + Y22*A(m) + Y23*A(n);\n                v[2] = Y13*A(k) + Y23*A(m) + Y33*A(n);\n\n                CMaterial* mat = materialMap[pmeshele[i1].geometry_tag];\n                if (non_iter != 0) {\n                    double tmp;\n                    if (mat->BHpoints == 0) {\n                        tmp = 0;\n                    } else {\n                        tmp = mat->getdvdB(pmeshele[i1].B);\n                        if (pmeshele[i].B > 1e-9){\n                            tmp /= pmeshele[i].B * pmeshele[i].AREA;//B==0?\n                            tmp /= ydot * ydot * ydot;\n                        }\n\n                    }\n                    Je[0][0] = v[0] * v[0] * tmp;Je[1][1] = v[1] * v[1] * tmp;Je[2][2] = v[2] * v[2] * tmp;\n                    Je[0][1] = v[0] * v[1] * tmp;Je[0][2] = v[0] * v[2] * tmp;Je[1][2] = v[1] * v[2] * tmp;\n                    Je[1][0] = Je[0][1];Je[2][0] = Je[0][2];Je[2][1] = Je[1][2];\n                }\n\n\n                /** 计算右侧向量 **/\n                double dtmp = mat->tau * pmeshele[i1].AREA/3;\n                De[0] = dtmp;De[1] = dtmp;De[2] = dtmp;\n                double dtmp1 = 2*PI*Yc*dtmp*dtmp;\n                /** 计算涡流矩阵 **/\n                double etmp = mat->sigma/ydot*pmeshele[i1].AREA/12;\n                Te[0][0] = etmp * 2+dtmp1;Te[1][1] = etmp* 2+dtmp1;Te[2][2] = etmp* 2+dtmp1;\n                Te[0][1] = etmp+dtmp1;Te[0][2] = etmp+dtmp1;Te[1][2] = etmp+dtmp1;\n                Te[1][0] = Te[0][1];Te[2][0] = Te[0][2];Te[2][1] = Te[1][2];\n\n\n                for(int kk=0;kk<3;kk++){\n                    for(int mm=0;mm<3;mm++){\n                        Te[kk][mm] /= dt;\n                        Je[kk][mm] += ce[kk][mm]/miut;\n                        Je[kk][mm] += Te[kk][mm];\n                    }\n                }\n\n                double jr = pmeshele[i].AREA*mat->Jr / 3;\n                for (int j = 0; j < 3; j++) {\n                    bbJz(pmeshele[i].n[j]) += jr;\n                    /** 计算永磁部分 **/\n                    bbJz(pmeshele[i].n[j]) -= mat->H_c / 2.*pmeshele[i].Q[j];\n                }\n\n                for (int row = 0; row < 3; row++) {\n                    for (int col = 0; col < 3; col++) {\n                        /** 判断节点是否在未知节点内 **/\n                        /** 得到排序之后的编号 **/\n                        int n_row = node_pos(pmeshele[i].n[row]);\n                        int n_col = node_pos(pmeshele[i].n[col]);\n                        if (n_row < num_pts - node_bdr && n_col < num_pts - node_bdr) {\n                            locs(0, pos) = n_row;\n                            locs(1, pos) = n_col;\n                            vals(0, pos) = Je[row][col];\n                            pos++;\n                        }\n                        /** 与雅可比矩阵相关的项 **/\n//                        bn(pmeshele[i].n[row]) += Je[row][col] * A(pmeshele[i].n[col]);\n                    }\n                }\n            }/** 单元循环结束 **/\n            /** 右下角的点 **/\n            locs(0, pos) = num_dof-1;\n            locs(1, pos) = num_dof-1;\n            vals(0, pos) = ((Y1+Yc)/dt-(C1+C2))/(2*PI);\n            pos++;\n            if (non_iter == 0) {\n                locs.reshape(2, pos);\n                vals.reshape(1, pos);\n            }\n            bn += bbJz;\n            /** 调用线性求解器求解 **/\n            /** 使用构造函数来生成稀疏矩阵 **/\n            sp_mat X(true, locs, vals, num_pts - node_bdr, num_pts - node_bdr, true, true);\n\n            for (int i = 0; i < num_pts - node_bdr; i++) {\n                unknown_b[i] = bn(node_reorder(i));\n            }\n            //---------------------superLU_MT---------------------------------------\n            CSuperLU_MT superlumt(num_pts - node_bdr, X, unknown_b);\n            if (superlumt.solve() == 1) {\n                printf(\"Error: superlumt.slove. Info:%d\\n\",superlumt.info);\n                break;\n            } else {\n                double *sol = nullptr;\n                A_old = A;\n                sol = superlumt.getResult();\n\n                for (int i = 0; i < num_pts - node_bdr; i++) {\n                    pmeshnode[node_reorder(i)].A = sol[i];// / pmeshnode[i].x;//the A is r*A_real\n                    A(node_reorder(i)) = sol[i];\n                }\n            }\n            /** 更新磁场结果 **/\n//            FILE *fp1 = fopen(\"B_T3_NR.txt\", \"w\");\n            for (int i = 0; i < num_triangle; i++) {\n                double bx = 0;\n                double by = 0;\n                int i1 = num_ele-num_triangle+i;\n                for (int j = 0; j < 3; j++) {\n                    bx += pmeshele[i1].Q[j] * A(pmeshele[i1].n[j]);\n                    by += pmeshele[i1].P[j] * A(pmeshele[i1].n[j]);\n                }\n                CMaterial* mat = materialMap[pmeshele[i1].geometry_tag];\n                pmeshele[i].B = sqrt(bx*bx + by*by) / 2. / pmeshele[i].AREA / pmeshele[i1].ydot;\n                pmeshele[i].Bx = bx / 2. / pmeshele[i1].AREA / pmeshele[i1].ydot;\n                pmeshele[i].By = by / 2. / pmeshele[i1].AREA / pmeshele[i1].ydot;\n                pmeshele[i].miut = mat->getMiu(pmeshele[i].B);\n//                fprintf(fp1, \"%lf \\t %lf \\t %lf \\t %lf \\t %lf\\n\", pmeshele[i].rc, pmeshele[i].zc, pmeshele[i].Bx, pmeshele[i].By, pmeshele[i].B);\n//                y[i] = pmeshele[i].miut;\n            }\n//            fclose(fp1);\n            double error = norm((A_old - A), 2) / norm(A, 2);\n//            iter++;\n            if (error < Precision) {\n                break;\n            }\n            bn.zeros();\n            pos = 0;\n\n        }/** 牛顿迭代结束 **/\n\n        /** 计算电磁力 **/\n        calcMagForce(-1);\n\n        /** 更新结果 **/\n        current_step += 1;\n        Ddisplacements.at(current_step) = 0;\n        displacements.at(current_step) = 0;\n        velocities.at(current_step) = 0;\n        accelerations.at(current_step) = 0;\n        PhiCoil.at(current_step) = 0;\n        ICoil.at(current_step) = 0;\n        magforces.at(current_step) = 0;\n        UCoil.at(current_step) = 0;\n\n        /** 回收空间 **/\n        if(unknown_b) delete unknown_b;\n    }\n\n}\n\n/*!\n \\brief 使用传输线法进行求解\n\n*/\nvoid Relay1250::AxisTLMsolve()\n{\n\n}\n\n/*!\n \\brief 运行测试案例\n\n*/\nvoid Relay1250::run()\n{\n    init();\n    openGeo();\n\n    AxisNRsolve();\n\n    /** 输出信息 **/\n    outputResults();\n}\n\n/*!\n \\brief 将一些结果进行输出。\n\n*/\nvoid Relay1250::outputResults()\n{\n\n}\n", "meta": {"hexsha": "774bcf230450d7c18ff0e5941fbe6e2290f28c53", "size": 17365, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fastFEM/relay1250.cpp", "max_stars_repo_name": "Poofee/fastFEM", "max_stars_repo_head_hexsha": "14eb626df973e2123604041451912c867ab7188c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-06T09:35:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T16:26:45.000Z", "max_issues_repo_path": "fastFEM/relay1250.cpp", "max_issues_repo_name": "Poofee/fastFEM", "max_issues_repo_head_hexsha": "14eb626df973e2123604041451912c867ab7188c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fastFEM/relay1250.cpp", "max_forks_repo_name": "Poofee/fastFEM", "max_forks_repo_head_hexsha": "14eb626df973e2123604041451912c867ab7188c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-28T09:23:43.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-28T09:23:43.000Z", "avg_line_length": 32.9506641366, "max_line_length": 147, "alphanum_fraction": 0.4580477973, "num_tokens": 5639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.26788281136007264}}
{"text": "/******************************************************************************\n**\n** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>\n** All rights reserved.\n**\n** This file is a part of the chemkit project. For more information\n** see <http://www.chemkit.org>.\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 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 chemkit project 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 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**\n******************************************************************************/\n\n#include \"graphicstransform.h\"\n\n#include <Eigen/LU>\n\n#include <chemkit/constants.h>\n\nnamespace chemkit {\n\n// === GraphicsTransform =================================================== //\n/// \\class GraphicsTransform graphicstransform.h chemkit/graphicstransform.h\n/// \\ingroup chemkit-graphics\n/// \\brief The GraphicsTransform class represents a transformation\n///        matrix.\n\n// --- Construction and Destruction ---------------------------------------- //\n/// Creates a new, empty graphics transform.\n///\n/// The tranformation returned is:\n/** \\f[\n///   \\left[\n///   {\n///     \\begin{array}{cccc}\n///       0 & 0 & 0 & 0 \\\\\n///       0 & 0 & 0 & 0 \\\\\n///       0 & 0 & 0 & 0 \\\\\n///       0 & 0 & 0 & 0 \\\\\n///     \\end{array}\n///   }\n///   \\right]\n/// \\f]\n**/\nGraphicsTransform::GraphicsTransform()\n{\n    m_matrix = new Eigen::Matrix<float, 4, 4>();\n\n    // set transformation matrix to all zeros\n    m_matrix->setZero();\n}\n\n/// Creates a new transform as a copy of \\p transform.\nGraphicsTransform::GraphicsTransform(const GraphicsTransform &transform)\n{\n    m_matrix = new Eigen::Matrix<float, 4, 4>(*transform.m_matrix);\n}\n\n/// Creates a new transform that contains \\p matrix.\nGraphicsTransform::GraphicsTransform(const Eigen::Matrix<float, 4, 4> &matrix)\n{\n    m_matrix = new Eigen::Matrix<float, 4, 4>(matrix);\n}\n\n/// Destroys the graphics transform.\nGraphicsTransform::~GraphicsTransform()\n{\n    delete m_matrix;\n}\n\n// --- Properties ---------------------------------------------------------- //\n/// Returns the data for the transform.\n///\n/// Use the following code to load a GraphicsTransform into\n/// OpenGL:\n/// \\code\n/// glLoadMatrixf(transform.data());\n/// \\endcode\nconst float* GraphicsTransform::data() const\n{\n    return m_matrix->data();\n}\n\n// --- Math ---------------------------------------------------------------- //\n/// Inverts the transform.\nvoid GraphicsTransform::invert()\n{\n    *m_matrix = m_matrix->inverse();\n}\n\n/// Returns the inverted version of the transform.\nGraphicsTransform GraphicsTransform::inverted() const\n{\n    GraphicsTransform transform = *this;\n    transform.invert();\n    return transform;\n}\n\n/// Multiplies \\p ray by the transform.\nGraphicsRay GraphicsTransform::multiply(const GraphicsRay &ray) const\n{\n    Point3f origin = multiplyPoint(ray.origin());\n    Point3f direction = multiplyVector(ray.direction());\n\n    return GraphicsRay(origin, direction);\n}\n\n/// Multiplies \\p point by the transform.\nPoint3f GraphicsTransform::multiplyPoint(const Point3f &point) const\n{\n    Eigen::Matrix<float, 4, 1> vector4;\n    vector4[0] = point.x();\n    vector4[1] = point.y();\n    vector4[2] = point.z();\n    vector4[3] = 1;\n\n    vector4 = *m_matrix * vector4;\n\n    return Point3f(vector4[0], vector4[1], vector4[2]);\n}\n\n/// Multiplies \\p vector by the transform.\nVector3f GraphicsTransform::multiplyVector(const Vector3f &vector) const\n{\n    Eigen::Matrix<float, 4, 1> vector4;\n    vector4[0] = vector.x();\n    vector4[1] = vector.y();\n    vector4[2] = vector.z();\n    vector4[3] = 0;\n\n    vector4 = *m_matrix * vector4;\n\n    return Vector3f(vector4[0], vector4[1], vector4[2]);\n}\n\n/// Multiplies \\p transform by the transform.\nGraphicsTransform GraphicsTransform::multiply(const GraphicsTransform &transform) const\n{\n    return GraphicsTransform(*m_matrix * *transform.m_matrix);\n}\n\nEigen::Matrix<float, 4, 1> GraphicsTransform::multiply(const Eigen::Matrix<float, 4, 1> &vector) const\n{\n    return *m_matrix * vector;\n}\n\n/// Multiplies \\p point by the inverse of the transform.\nPoint3f GraphicsTransform::inverseMultiplyPoint(const Point3f &point) const\n{\n    Eigen::Matrix<float, 4, 1> vector4;\n    vector4[0] = point.x();\n    vector4[1] = point.y();\n    vector4[2] = point.z();\n    vector4[3] = 1;\n\n    vector4 = m_matrix->inverse() * vector4;\n\n    return Point3f(vector4[0], vector4[1], vector4[2]);\n}\n\n/// Multiplies \\p vector by the inverse of the transform.\nVector3f GraphicsTransform::inverseMultiplyVector(const Vector3f &vector) const\n{\n    Eigen::Matrix<float, 4, 1> vector4;\n    vector4[0] = vector.x();\n    vector4[1] = vector.y();\n    vector4[2] = vector.z();\n    vector4[3] = 0;\n\n    vector4 = m_matrix->inverse() * vector4;\n\n    return Vector3f(vector4[0], vector4[1], vector4[2]);\n}\n\nEigen::Matrix<float, 4, 1> GraphicsTransform::inverseMultiply(const Eigen::Matrix<float, 4, 1> &vector) const\n{\n    return m_matrix->inverse() * vector;\n}\n\n// --- Operators ----------------------------------------------------------- //\nfloat GraphicsTransform::operator()(int row, int column) const\n{\n    return m_matrix->operator()(row, column);\n}\n\nfloat& GraphicsTransform::operator()(int row, int column)\n{\n    return m_matrix->operator()(row, column);\n}\n\nGraphicsRay GraphicsTransform::operator*(const GraphicsRay &ray) const\n{\n    return multiply(ray);\n}\n\nPoint3f GraphicsTransform::operator*(const Point3f &point) const\n{\n    return multiplyPoint(point);\n}\n\nGraphicsTransform GraphicsTransform::operator*(const GraphicsTransform &transform) const\n{\n    return multiply(transform);\n}\n\nGraphicsTransform& GraphicsTransform::operator*=(const GraphicsTransform &transform)\n{\n    *m_matrix *= *transform.m_matrix;\n    return *this;\n}\n\nGraphicsTransform& GraphicsTransform::operator=(const GraphicsTransform &transform)\n{\n    *m_matrix = *transform.m_matrix;\n    return *this;\n}\n\n// --- Static Methods ------------------------------------------------------ //\n/// Returns the identity transform.\n///\n/// The transformation returned is the following:\n/** \\f[\n///   \\left[\n///   {\n///     \\begin{array}{cccc}\n///       1 & 0 & 0 & 0 \\\\\n///       0 & 1 & 0 & 0 \\\\\n///       0 & 0 & 1 & 0 \\\\\n///       0 & 0 & 0 & 1 \\\\\n///     \\end{array}\n///   }\n///   \\right]\n/// \\f]\n**/\nGraphicsTransform GraphicsTransform::identity()\n{\n    GraphicsTransform transform;\n    transform.m_matrix->setIdentity();\n    return transform;\n}\n\n/// Returns a transformation matrix that represents the translation by\n/// \\p vector.\n///\n/// The transformation returned is the following:\n/** \\f[\n///   \\left[\n///   {\n///     \\begin{array}{cccc}\n///       1 & 0 & 0 & vector_{x} \\\\\n///       0 & 1 & 0 & vector_{y} \\\\\n///       0 & 0 & 1 & vector_{z} \\\\\n///       0 & 0 & 0 & 1 \\\\\n///     \\end{array}\n///   }\n///   \\right]\n/// \\f]\n**/\nGraphicsTransform GraphicsTransform::translation(const Vector3f &vector)\n{\n    GraphicsTransform transform = identity();\n\n    transform(0, 3) = vector.x();\n    transform(1, 3) = vector.y();\n    transform(2, 3) = vector.z();\n\n    return transform;\n}\n\n/// Returns a transform that represents a rotation by \\p angle\n/// degrees around \\p axis.\nGraphicsTransform GraphicsTransform::rotation(const Vector3f &axis, float angle)\n{\n    GraphicsTransform transform = identity();\n\n    Vector3f v = axis.normalized();\n    float c = cos(angle * chemkit::constants::DegreesToRadians);\n    float s = sin(angle * chemkit::constants::DegreesToRadians);\n\n    transform(0, 0) = v.x() * v.x() + (1 - v.x() * v.x()) * c;\n    transform(0, 1) = v.x() * v.y() * (1 - c) - v.z() * s;\n    transform(0, 2) = v.x() * v.z() * (1 - c) + v.y() * s;\n    transform(1, 0) = v.x() * v.y() * (1 - c) + v.z() * s;\n    transform(1, 1) = v.y() * v.y() + (1 - v.y() * v.y()) * c;\n    transform(1, 2) = v.y() * v.z() * (1 - c) - v.x() * s;\n    transform(2, 0) = v.x() * v.z() * (1 - c) - v.y() * s;\n    transform(2, 1) = v.y() * v.z() * (1 - c) + v.x() * s;\n    transform(2, 2) = v.z() * v.z() + (1 - v.z() * v.z()) * c;\n\n    return transform;\n}\n\n/// Returns a perspective transform.\n///\n/// The transformation returned is the following:\n/// \\f[ f = cot(\\frac{angle}{2}) \\f]\n/** \\f[\n///   \\left[\n///   {\n///     \\begin{array}{cccc}\n///       \\frac{f}{aspectRatio} & 0 & 0 & 0 \\\\\n///       0 & f & 0 & 0 \\\\\n///       0 & 0 & \\frac{nearDistance+farDistance}{nearDistance-farDistance} & \\frac{2 \\cdot nearDistance \\cdot farDistance}{nearDistance-farDistance} \\\\\n///       0 & 0 & -1 & 0 \\\\\n///     \\end{array}\n///   }\n///   \\right]\n/// \\f]\n**/\nGraphicsTransform GraphicsTransform::perspective(float angle, float aspectRatio, float nearDistance, float farDistance)\n{\n    GraphicsTransform transform;\n\n    float f = 1.0 / tan(angle / 2.0);\n\n    transform(0, 0) = f / aspectRatio;\n    transform(1, 1) = f;\n    transform(2, 2) = (nearDistance + farDistance) / (nearDistance - farDistance);\n    transform(2, 3) = (2 * nearDistance * farDistance) / (nearDistance - farDistance);\n    transform(3, 2) = -1;\n\n    return transform;\n}\n\n/// Returns a frustum transform.\n///\n/// The transformation returned is the following:\n/** \\f[\n///   \\left[\n///   {\n///     \\begin{array}{cccc}\n///       \\frac{2 \\cdot nearDistance}{right-left} & 0 & \\frac{right+left}{right-left} & 0 \\\\\n///       0 & \\frac{2 \\cdot nearDistance}{top-bottom} & \\frac{top+bottom}{top-bottom} & 0 \\\\\n///       0 & 0 & -\\frac{farDistance+nearDistance}{farDistance-nearDistance} & -\\frac{2 \\cdot farDistance \\cdot nearDistance}{farDistance-nearDistance} \\\\\n///       0 & 0 & -1 & 0 \\\\\n///     \\end{array}\n///   }\n///   \\right]\n/// \\f]\n**/\nGraphicsTransform GraphicsTransform::frustum(float left, float right, float top, float bottom, float nearDistance, float farDistance)\n{\n    GraphicsTransform transform;\n\n    transform(0, 0) = (2 * nearDistance) / (right - left);\n    transform(1, 1) = (2 * nearDistance) / (top - bottom);\n    transform(2, 0) = (right + left) / (right - left);\n    transform(2, 1) = (top + bottom) / (top - bottom);\n    transform(2, 2) = -(farDistance + nearDistance) / (farDistance - nearDistance);\n    transform(2, 3) = -(2 * farDistance * nearDistance) / (farDistance - nearDistance);\n    transform(3, 2) = -1;\n\n    return transform;\n}\n\n/// Returns a orthographic transform.\n///\n/// The transformation returned is the following:\n/** \\f[\n///   \\left[\n///   {\n///     \\begin{array}{cccc}\n///       \\frac{2}{right-left} & 0 & 0 & -\\frac{right+left}{right-left} \\\\\n///       0 & \\frac{2}{top-bottom} & 0 & -\\frac{top+bottom}{top-bottom} \\\\\n///       0 & 0 & -\\frac{2}{farDistance-nearDistance} & -\\frac{farDistance+nearDistance}{farDistance-nearDistance} \\\\\n///       0 & 0 & 0 & 1 \\\\\n///     \\end{array}\n///   }\n///   \\right]\n/// \\f]\n**/\nGraphicsTransform GraphicsTransform::orthographic(float left, float right, float top, float bottom, float nearDistance, float farDistance)\n{\n    GraphicsTransform transform;\n\n    transform(0, 0) = 2.0 / (right - left);\n    transform(0, 3) = -(right + left) / (right - left);\n    transform(1, 1) = 2.0 / (top - bottom);\n    transform(1, 3) = -(top + bottom) / (top - bottom);\n    transform(2, 2) = -2.0 / (farDistance - nearDistance);\n    transform(2, 3) = -(farDistance + nearDistance) / (farDistance - nearDistance);\n    transform(3, 3) = 1;\n\n    return transform;\n}\n\n} // end chemkit namespace\n", "meta": {"hexsha": "8ca4e522d8ecb741e570320460fc865e88463044", "size": 12582, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/graphics/graphicstransform.cpp", "max_stars_repo_name": "quizzmaster/chemkit", "max_stars_repo_head_hexsha": "803e4688b514008c605cb5c7790f7b36e67b68fc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2015-01-24T23:59:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T13:48:01.000Z", "max_issues_repo_path": "src/graphics/graphicstransform.cpp", "max_issues_repo_name": "soplwang/chemkit", "max_issues_repo_head_hexsha": "d62b7912f2d724a05fa8be757f383776fdd5bbcb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-12-28T20:29:16.000Z", "max_issues_repo_issues_event_max_datetime": "2016-01-26T06:48:19.000Z", "max_forks_repo_path": "src/graphics/graphicstransform.cpp", "max_forks_repo_name": "soplwang/chemkit", "max_forks_repo_head_hexsha": "d62b7912f2d724a05fa8be757f383776fdd5bbcb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2015-01-23T14:50:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-10T15:43:50.000Z", "avg_line_length": 30.687804878, "max_line_length": 154, "alphanum_fraction": 0.6142902559, "num_tokens": 3391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.26787659355317867}}
{"text": "/*\r\n *  The core class (implementation) for roadmap building\r\n *\r\n *  Created on: Jan 30, 2015\r\n *  Author: Jingjin Yu\r\n */\r\n\r\n#include \"roadmap.h\"\r\n#include \"helper_functions.h\"\r\n\r\n#include <utility>   \r\n#include <algorithm> \r\n#include <vector>\r\n\r\n#include <CGAL/Qt/Converter.h>\r\n#include <CGAL/Boolean_set_operations_2.h>\r\n\r\n#include <QGraphicsSimpleTextItem>\r\n\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/graph/lookup_edge.hpp>\r\n\r\n/*------------------------------------------------------------------------------------------\r\n\t\t\tsee resources/lattice-indexing.pptx for the processing logic\r\n--------------------------------------------------------------------------------------------*/\r\n\r\nstatic const QColor BASIC_QCOLORS8[] = {Qt::red, Qt::blue, Qt::green, Qt::magenta, Qt::cyan, Qt::gray, Qt::black, Qt::yellow};\r\nstatic int colorCounter = 0;\r\n\r\nvoid Roadmap::buildRoadmap(Polygon2_list* pObsList, Polygon_2 *pBoundingRect, double radius){\r\n\t// Populate some internal variables for use across calls\r\n\tm_radius = radius;\r\n\tm_edgeLength = radius/0.43;\r\n\tm_obstaclePolyList = *pObsList;\r\n\tm_pBoundingRect = pBoundingRect;\r\n\tif(m_pVisibilityGraph != 0){\r\n\t\tdelete m_pVisibilityGraph;\r\n\t\tm_pVisibilityGraph = 0;\r\n\t}\r\n\tif(m_pEnvironment != 0){\r\n\t\tdelete m_pEnvironment;\r\n\t\tm_pEnvironment = 0;\r\n\t}\r\n\r\n\t// Some basic setup\r\n\tICPoint_2 bottomLeft = K_ICK_converter((*m_pBoundingRect)[0]);\r\n\tICPoint_2 topRight = K_ICK_converter((*m_pBoundingRect)[2]);\r\n\r\n\tbottomLeftX = bottomLeft.x();\r\n\tbottomLeftY = bottomLeft.y();\r\n\twidth = topRight.x() - bottomLeft.x();\r\n\theight = topRight.y() - bottomLeft.y();;\r\n\tsqrt3 = sqrt(3.0);\r\n\r\n\t// Compute number of columns and rows\r\n\tn_w = (int)(ceil(width/(m_edgeLength*3/2))) + 3;\r\n\tn_h = (int)(ceil(height/(m_edgeLength*sqrt3))) + 3;\r\n\r\n\t// The lattice start x, y\r\n\txs = bottomLeftX - (3/2)*m_edgeLength*1.35;\r\n\tys = bottomLeftY - sqrt3*m_edgeLength*1.4;\r\n\r\n\t// Clean up from previous build\r\n\tm_pointList.clear();\r\n\tm_vidPointMap.clear();\r\n\tm_pointVidMap.clear();\r\n\tm_graph.clear();\r\n\tm_finalGraph.clear();\r\n\tm_vidFGMap.clear();\r\n\tm_vidGFMap.clear();\r\n\tm_edgeToBeRemovedSet.clear();\r\n\tm_vertexToBeRemovedSet.clear();\r\n\tm_boundaryBoundingCycle.clear();\r\n\tm_connectingPathMap.clear();\r\n\tfor(std::vector<Graph*>::iterator git = m_obsBoundingCycleVec.begin(); git != m_obsBoundingCycleVec.end(); git++){\r\n\t\tdelete (*git);\r\n\t}\r\n\tm_obsBoundingCycleVec.clear();\r\n\r\n\t/*\r\n\t// Build the roadmap, first obtain a lattice that cover the outer boundary\r\n\tbuildHexgaonLattice();\r\n\r\n\t// Remove extra edges, at the same time, find smallest cycles enclosing the obstacles\r\n\tremoveExcessEdges();\r\n\r\n\t// Preserve connectivity\r\n\tcheckAndFixConnectivity();\r\n*/\r\n}\r\n\r\nvoid Roadmap::removeExcessEdges(){\r\n\t// We do this in several steps. First, we go through each polygon obstacle boundary \r\n\t// and delete all edges of the lattice that intersect with these boundaries. Then, \r\n\t// we find the connected components of the remaining lattice graph. For each component\r\n\t// we only need to test one vertex to know whether it belongs to the configuration space\r\n\t// or not. We keep all components that belong to the configuration space\r\n\r\n\t// =====================================================================================\r\n\t// Compute the set of edges that falls on obstacle boundaries, at the same time also\r\n\t// compute the smallest cycle in the full lattice that encloses the obstacle. First do\r\n\t// it for the bounding polygon\r\n\tgetIntersectingEdges(*m_pBoundingRect, m_boundaryBoundingCycle, true);\r\n\r\n\t// Then for all obstacles \r\n\tfor(Polygon2_list::iterator obsit = m_obstaclePolyList.begin(); obsit != m_obstaclePolyList.end(); obsit++){\r\n\t\tGraph* pg = new Graph();\r\n\t\tm_obsBoundingCycleVec.push_back(pg);\r\n\t\tgetIntersectingEdges(*obsit, *pg);\r\n\t}\r\n\r\n\t// =====================================================================================\r\n\t// Remove edges that do not belong to the graph\r\n\tGraph g;\r\n\tstd::set<std::pair<int, int> > edgeSet = m_graph.getEdgeSet();\r\n\tfor(std::set<std::pair<int, int> >::iterator eit = edgeSet.begin(); eit != edgeSet.end(); eit++){\r\n\t\tint fv = (*eit).first;\r\n\t\tint sv = (*eit).second;\r\n\t\tif(!edgeInSet(fv, sv, m_edgeToBeRemovedSet)){\r\n\t\t\tg.addEdge(fv, sv);\r\n\t\t}\r\n\t}\r\n\tm_graph = g;\r\n\r\n\t// =====================================================================================\r\n\t// Go through all vertices and find all vertices and edges inside the configuration\r\n\t// space. To do so, iterate over all lattices points (the full lattice minus the edges that\r\n\t// crosses obstacle boundaries) and for each point, if it has not been checked, see whether\r\n\t// the point is inside the configuration space. Then we do a BFS from the point and visit\r\n\t// all points/edges connected to the point. We add the edges to our final graph if and only\r\n\t// if the starting vertex is in the c-space. This way, we need to do c-space membership\r\n\t// check geometrically only very limited number of times, usually around the number of\r\n\t// obstacles in the c-space.\r\n\r\n\tg.clear();\r\n\tstd::set<int> visitedVertices;\r\n\tfor(std::map<int, Point_2>::iterator vit = m_vidPointMap.begin(); vit != m_vidPointMap.end(); vit++){\r\n\t\tint vid = vit->first;\r\n\t\tif(visitedVertices.find(vid) == visitedVertices.end()){\r\n\t\t\tvisitedVertices.insert(vid);\r\n\t\t\t// Test whether the vertex is inside the configuration space\r\n\t\t\tbool inCSpace = isPointInCSpace(vit->second);\r\n\r\n\t\t\t// Do BFS\r\n\t\t\tstd::list<int> tempQueue;\r\n\t\t\ttempQueue.push_back(vid);\r\n\t\t\twhile(tempQueue.size() > 0){\r\n\t\t\t\tint current = tempQueue.front();\r\n\t\t\t\ttempQueue.pop_front();\r\n\r\n\t\t\t\tstd::set<int> neighborSet = m_graph.getNeighborSet(current);\r\n\r\n\t\t\t\tfor(std::set<int>::iterator vit = neighborSet.begin(); vit != neighborSet.end(); vit++){\r\n\t\t\t\t\t// Retrieve first and second vertices\r\n\t\t\t\t\tint et = *vit;\r\n\t\t\t\t\tif(visitedVertices.find(et) == visitedVertices.end()){\r\n\t\t\t\t\t\tvisitedVertices.insert(et);\r\n\t\t\t\t\t\ttempQueue.push_back(et);\r\n\t\t\t\t\t}\r\n\t\t\t\t\t// Add edge as needed\r\n\t\t\t\t\tif(inCSpace) g.addEdge(current, et);\r\n\t\t\t\t}\r\n\t\t\t}\t\r\n\t\t}\r\n\t}\r\n\tm_graph.clear();\r\n\tm_graph = g;\r\n\r\n\t// Remove isolated vertices\r\n\tfor(std::set<int>::iterator vit = m_vertexToBeRemovedSet.begin(); vit != m_vertexToBeRemovedSet.end(); vit++){\r\n\t\t// std::cout << \"Removing vertex with id: \" << *vit << std::endl;\r\n\t\tm_graph.removeVertex(*vit);\r\n\t}\r\n\r\n\t// Remove single degree edges\r\n\tstd::set<int> vSetCopy = m_graph.getVertexSet();\r\n\tfor(std::set<int>::iterator vit = vSetCopy.begin(); vit != vSetCopy.end(); vit++){\r\n\t\tif(m_graph.hasVertex(*vit)){\r\n\t\t\tif(m_graph.getNeighborSet(*vit).size() == 0){\r\n\t\t\t\tm_graph.removeVertex(*vit);\r\n\t\t\t\t// std::cout << \"Removing vertex with id: \" << *vit << std::endl;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tbuildFinalGraph();\r\n}\r\n\r\nvoid Roadmap::buildFinalGraph(){\r\n\t// Construct m_finalGraph\r\n\tstd::set<std::pair<int, int>>& eSet = m_graph.getEdgeSet();\r\n\tint vIDCount = 0;\r\n\tfor(std::set<std::pair<int, int> >::iterator eit = eSet.begin(); eit != eSet.end(); eit++){\r\n\t\tint fv = eit->first;\r\n\t\tint sv = eit->second;\r\n\r\n\t\t// Check whether fv was added\r\n\t\tif(m_vidGFMap.find(fv) == m_vidGFMap.end()){\r\n\t\t\tm_vidGFMap[fv] = vIDCount;\r\n\t\t\tm_vidFGMap[vIDCount] = fv;\r\n\t\t\tfv = vIDCount++;\r\n\t\t}\r\n\t\telse{\r\n\t\t\tfv = m_vidGFMap[fv];\r\n\t\t}\r\n\r\n\t\t// Check whether sv was added\r\n\t\tif(m_vidGFMap.find(sv) == m_vidGFMap.end()){\r\n\t\t\tm_vidGFMap[sv] = vIDCount;\r\n\t\t\tm_vidFGMap[vIDCount] =sv;\r\n\t\t\tsv = vIDCount++;\r\n\t\t}\r\n\t\telse{\r\n\t\t\tsv = m_vidGFMap[sv];\r\n\t\t}\r\n\t\tm_finalGraph.addEdge(fv, sv);\r\n\t}\r\n}\r\n\r\nvoid Roadmap::drawBoundingCycle(QGraphicsScene& scene){\r\n\t// Draw the cycles\r\n\tQPen regularPen = QPen(QColor(0, 255, 0, 127), 0.5, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\r\n\tQPen illegalPen = QPen(QColor(255, 0, 0, 127), 0.5, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\r\n\tfor(std::vector<Graph*>::iterator git = m_obsBoundingCycleVec.begin(); git != m_obsBoundingCycleVec.end(); git++){\r\n\t\tGraph& g = *(*git);\r\n\t\tstd::set<std::pair<int, int> > edgeSet = g.getEdgeSet();\r\n\t\tfor(std::set<std::pair<int, int> >::iterator eit = edgeSet.begin(); eit != edgeSet.end(); eit++){\r\n\t\t\tint v1 = (*eit).first;\r\n\t\t\tint v2 = (*eit).second;\r\n\t\t\tICPoint_2 p1 = K_ICK_converter(m_vidPointMap[v1]);\r\n\t\t\tICPoint_2 p2 = K_ICK_converter(m_vidPointMap[v2]);\r\n\t\t\tif(m_graph.hasEdge(v1, v2)){\r\n\t\t\t\tscene.addLine(p1.x(), p1.y(), p2.x(), p2.y(), regularPen);\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\tscene.addLine(p1.x(), p1.y(), p2.x(), p2.y(), illegalPen);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nbool Roadmap::isPointInCSpace(Point_2 &p){\r\n\t// Check whether the point is inside the bounding rect\r\n\tif(m_pBoundingRect->bounded_side(p) == CGAL::ON_UNBOUNDED_SIDE){\r\n\t\treturn false;\r\n\t}\r\n\r\n    for(Polygon2_list::iterator pli = m_obstaclePolyList.begin(); pli != m_obstaclePolyList.end(); pli++){\r\n\t\tPolygon_2 &tp = *(pli);\r\n\t\tif(tp.bounded_side(p) == CGAL::ON_BOUNDED_SIDE){\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\treturn true;\r\n}\r\n\r\n\r\nvoid Roadmap::drawVertexIds(QGraphicsScene& scene){\r\n\t// Draw the id text of the vretex\r\n\tQFont font;\r\n\tQPainterPath path;\r\n\tfont.setPointSizeF(m_radius/1.5);\r\n\tfont.setBold(false);\r\n\tfor(std::set<int>::iterator vit = m_graph.getVertexSet().begin(); vit != m_graph.getVertexSet().end(); vit ++){\r\n\t\tICPoint_2 p = K_ICK_converter(m_vidPointMap[*vit]);\r\n\t\tQGraphicsSimpleTextItem *ti = scene.addSimpleText(QString::number(m_vidGFMap[*vit]), font);\r\n\t\tti->setPos(p.x() + m_radius/2, p.y() - m_radius/2);\r\n\t\tti->setPen(QPen(QColor(Qt::green), 0.03*m_radius, Qt::SolidLine, Qt::RoundCap,Qt::RoundJoin));\r\n\t\tti->setZValue(2);\r\n\t}\r\n}\r\n\r\nvoid Roadmap::buildVisibilityGraph(){\r\n\t// To build the visibility graph, we use the package VisiLibity, which is not precise arithematic, \r\n\t// but good for our purpose since we do not use visibility graph as part of our main logic. \r\n\r\n\t// Only build once per roadmap\r\n\tif(m_pVisibilityGraph != 0) return;\r\n\r\n\t// Vector to hold all polygon for contructing VisiLibity object\r\n\tvector<Polygon> polyVec;\r\n\r\n\t// We assume that the infated obstacles do not intersect each other but may intersect the boundary.\r\n\t// Therefore, we test such intersection and obtain an updated boundary (the inside)\r\n\tECPolygon_2 boundary = convertToExactPolygon(*m_pBoundingRect);\r\n\tif(boundary.is_clockwise_oriented()) boundary.reverse_orientation();\r\n\tfor(Polygon2_list::iterator pli = m_obstaclePolyList.begin(); pli != m_obstaclePolyList.end(); pli++){\r\n\t\tECPolygon_2 ecPoly = convertToExactPolygon(*pli);\r\n\t\tif(boundaryInterset(boundary, ecPoly)){\r\n\t\t\tvector<ECPolygon_with_holes_2> outVec;\r\n\r\n\t\t\t// Remove the obstacle \"from\" the boundary polygon\r\n\t\t\tCGAL::difference(boundary, ecPoly, back_inserter(outVec)); \r\n\r\n\t\t\t// Update boundary\r\n\t\t\tboundary = outVec[0].outer_boundary();\r\n\t\t}\r\n\t\telse{\r\n\t\t\t// Add all non intersecting obstacles \r\n\t\t\tPolygon tempPoly;\r\n\t\t\tconverFromCGALtoVisilibity(ecPoly, tempPoly, false);\r\n\t\t\tpolyVec.push_back(tempPoly);\r\n\t\t}\r\n\t}\r\n\r\n\t// Insert the boundary \r\n\tPolygon boundaryPoly;\r\n\tconverFromCGALtoVisilibity(boundary, boundaryPoly, true);\r\n\tpolyVec.insert(polyVec.begin(), boundaryPoly);\r\n\r\n\t// Build environment and visibility graph\t\r\n\tm_pEnvironment = new Environment(polyVec);\r\n\tm_pVisibilityGraph = new Visibility_Graph(*m_pEnvironment, m_epsilon);\r\n}\r\n\r\ndouble Roadmap::computeShortestPath(Point_2& p1, Point_2& p2, std::list<Point_2> & path){\r\n\tICPoint_2 p1x = K_ICK_converter(p1);\r\n\tICPoint_2 p2x = K_ICK_converter(p2);\r\n\treturn computeShortestPath(p1x.x(), p1x.y(), p2x.x(), p2x.y(), path);\r\n}\r\n\r\ndouble Roadmap::computeShortestPath(double x1, double y1, double x2, double y2, std::list<Point_2> & path){\r\n\tPolyline pl = m_pEnvironment->shortest_path(Point(x1, y1), Point(x2, y2), *m_pVisibilityGraph, m_epsilon);\r\n\tfor(int i = 0; i < pl.size(); i++){\r\n\t\tpath.push_back(Point_2(pl[i].x(), pl[i].y()));\r\n\t}\r\n\treturn getPathLength(path);\r\n}\r\n\r\ndouble Roadmap::computeShortestPath(double x1, double y1, double x2, double y2, vector<pair<double, double> >& path){\r\n\t// Compute shortest path\r\n\tstd::list<Point_2> shortestPath;\r\n\tdouble length = computeShortestPath(x1, y1, x2, y2, shortestPath);\r\n\r\n\t// Convert the path\r\n\tfor(std::list<Point_2>::iterator vi = shortestPath.begin(); vi != shortestPath.end(); vi++){\r\n\t\tICPoint_2 p = K_ICK_converter(*vi);\r\n\t\tpath.push_back(pair<double, double>(p.x(), p.y()));\r\n\t}\r\n\treturn length;\r\n}\r\n\r\nvoid Roadmap::addToScene(QGraphicsScene& scene, bool drawEdge, QPen edgePen, bool drawVertex, QPen vertexPen){\r\n\t// Paint the edges\r\n\tif(drawEdge){\r\n\t\tstd::set<std::pair<int, int> > edgeSet = m_graph.getEdgeSet();\r\n\t\tfor(std::set<std::pair<int, int> >::iterator eit = edgeSet.begin(); eit != edgeSet.end(); eit++){\r\n\t\t\tint v1 = (*eit).first;\r\n\t\t\tint v2 = (*eit).second;\r\n\t\t\tICPoint_2 p1 = K_ICK_converter(m_vidPointMap[v1]);\r\n\t\t\tICPoint_2 p2 = K_ICK_converter(m_vidPointMap[v2]);\r\n\t\t\tscene.addLine(p1.x(), p1.y(), p2.x(), p2.y(), edgePen);\r\n\t\t\t/*}*/\r\n\r\n\t\t\tif(m_boundaryBoundingCycle.hasEdge(v1, v2)){\r\n\t\t\t\tscene.addLine(p1.x(), p1.y(), p2.x(), p2.y(), QPen(Qt::blue, 0.05, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\tfor(std::vector<Graph*>::iterator git = m_obsBoundingCycleVec.begin(); git != m_obsBoundingCycleVec.end(); git++){\r\n\t\t\t\t\tif((*git)->hasEdge(v1, v2)){\r\n\t\t\t\t\t\tscene.addLine(p1.x(), p1.y(), p2.x(), p2.y(), QPen(Qt::yellow, 0.05, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\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\t// Paint vertices if needed and obtain the fill area\r\n\tif(!drawVertex){\r\n\t\tfor(std::list<Point_2>::iterator it = m_pointList.begin(); it != m_pointList.end(); it ++){\r\n\t\t\tICPoint_2 p = K_ICK_converter(*it);\r\n\t\t\tscene.addEllipse(p.x() - 0.025, p.y() - 0.025, 0.05, 0.05, vertexPen);\r\n\t\t}\r\n\t}\r\n\r\n\tfor(Path_Map::iterator pathIt = m_connectingPathMap.begin(); pathIt != m_connectingPathMap.end(); pathIt ++){\r\n\t\tstd::list<Point_2>& shortestPath = pathIt->second;\r\n\t\tstd::list<Point_2>::iterator vit = shortestPath.begin();\r\n\t\tif(vit != shortestPath.end()){\r\n\t\t\tICPoint_2 p = K_ICK_converter(*vit);\r\n\t\t\tvit++;\r\n\t\t\tfor(; vit != shortestPath.end(); vit++){\r\n\t\t\t\tICPoint_2 p2 = K_ICK_converter(*vit);\r\n\t\t\t\tscene.addLine(p.x(), p.y(), p2.x(), p2.y(), QPen(Qt::magenta, 0.025, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\r\n\t\t\t\tp = p2;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t// std::cout << shortestPath.size() << std::endl;\r\n\r\n}\r\n\r\nvoid Roadmap::getIntersectingEdges(Polygon_2 & poly, Graph& boundingCycle, bool outerBoundary){\r\n\t// Detecting all edges of the lattice graph that intersects the boundary of poly\r\n\r\n\t// =====================================================================================\r\n\t// Get a vertex of the poly and find the hexgaon of the lattice that contains the vetex.\r\n\t// For each col and row combo, there are three possible hexgaons the point may fall into\r\n\r\n\t// Locate the hexgon (relative to some arbitrary base choice)\r\n\tICPoint_2 p0 = K_ICK_converter(poly.vertex(0));\r\n\tstd::pair<int, int> crp = locateHexagonForPoint(p0);\r\n\tint col = crp.first;\r\n\tint row = crp.second;\r\n\r\n\t// Compute the current hexagon\r\n\tPoint_2 p[6];\r\n\tSegment_2 e[6];\r\n\tPolygon_2 hex; \r\n\tint pIndex[6];\r\n\tpopulateHexagon(col, row, p, e, hex, pIndex);\r\n\r\n\t// =====================================================================================\r\n\t// With a point of the obstacle and a hexgon containing the point, we iteratively check \r\n\t// intersections between the segments of the obstacle and the hexagon. We assume that \r\n\t// the obstacle would have at least three vertices. Note that a obstacle may be smaller than\r\n\t// a single hexagon. \r\n\r\n\tstd::set<std::pair<int, int> > tempEdgeToRemoveSet;\r\n\tint numVertices = poly.size();\t\t// \r\n\tint currentVertexIndex = 0;\r\n\twhile(currentVertexIndex < numVertices){\r\n\t\t// Get the current segment of polygon to be checked\r\n\t\tPoint_2 nextVertex = poly[currentVertexIndex==numVertices-1?0:currentVertexIndex+1];\r\n\r\n\t\t// Check whether nextVertex is outside of the current hexagon. If we are still in the \r\n\t\t// same hexagon, then move to the next obstacle vertex\r\n\t\tif(hex.bounded_side(nextVertex) == CGAL::ON_BOUNDED_SIDE) {\r\n\t\t\tcurrentVertexIndex ++;\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\t// If we are here, then we jumped outside of a lattice hexagon. Figure out which edge is \r\n\t\t// being intersected. We keep doing this until we cover the entire obstacle edge\r\n\t\tPoint_2 currentVertex = poly[currentVertexIndex];\r\n\t\tSegment_2 obsEdge(currentVertex, nextVertex);\r\n\r\n\t\tstd::pair<int, int> lastPair(-10, -10);\r\n\t\twhile(true){\r\n\t\t\tint edgeIndex = 0;\r\n\t\t\twhile(edgeIndex < 6){\r\n\t\t\t\tif(intersection(e[edgeIndex], obsEdge)){\r\n\t\t\t\t\tstd::pair<int, int> edgePair(pIndex[edgeIndex], pIndex[edgeIndex==5?0:edgeIndex+1]);\r\n\t\t\t\t\tstd::pair<int, int> edgePairReverse(pIndex[edgeIndex==5?0:edgeIndex+1], pIndex[edgeIndex]);\r\n\t\t\t\t\tif(lastPair != edgePair && lastPair != edgePairReverse){\r\n\t\t\t\t\t\tlastPair = edgePair;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tedgeIndex ++;\r\n\t\t\t};\r\n\r\n\t\t\tif(edgeIndex < 6){\r\n\t\t\t\t// We hit an intersection, mark the edge as to be removed\r\n\t\t\t\ttempEdgeToRemoveSet.insert(lastPair);\r\n\t\t\t\tm_edgeToBeRemovedSet.insert(lastPair);\r\n\r\n\t\t\t\t// Figure out the next hexgon to be checked \r\n\t\t\t\tif(col%2 == 0){\r\n\t\t\t\t\tswitch(edgeIndex){\r\n\t\t\t\t\t\tcase 0: col--; break;\r\n\t\t\t\t\t\tcase 1: row++; break;\r\n\t\t\t\t\t\tcase 2: col++; break;\r\n\t\t\t\t\t\tcase 3: col++; row--; break;\r\n\t\t\t\t\t\tcase 4: row--; break;\r\n\t\t\t\t\t\tcase 5: col--; row--; break;\r\n\t\t\t\t\t\tdefault: break;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse{\r\n\t\t\t\t\tswitch(edgeIndex){\r\n\t\t\t\t\t\tcase 0: col--; row++; break;\r\n\t\t\t\t\t\tcase 1: row++; break;\r\n\t\t\t\t\t\tcase 2: col++; row++; break;\r\n\t\t\t\t\t\tcase 3: col++; break;\r\n\t\t\t\t\t\tcase 4: row--; break;\r\n\t\t\t\t\t\tcase 5: col--; break;\r\n\t\t\t\t\t\tdefault: break;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tpopulateHexagon(col, row, p, e, hex, pIndex);\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\t// No more intersections, we are dong with the current obstacle edge\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tcurrentVertexIndex++;\r\n\t}\r\n\r\n\t// =====================================================================================\r\n\t// We now have all the edges of the lattice that lie on the polygonal obstacle boundary. \r\n\t// Next, we locate the bounding cycle in the full lattice graph surrounding the obstacle\r\n\tif(tempEdgeToRemoveSet.size() > 0){\r\n\t\t// Iterate through edges to be removed and find one with an end vertex that \r\n\t\t// has an associated edge in the configuraiton space\r\n\t\tint sIndex, t1Index, t2Index; \r\n\t\tfor(std::set<std::pair<int,int> >::iterator eit = tempEdgeToRemoveSet.begin();\r\n\t\teit != tempEdgeToRemoveSet.end(); eit++){\r\n\t\t\tstd::pair<int, int> edge = *eit;\r\n\t\t\t// Try one vertex\r\n\t\t\tsIndex = edge.first;\r\n\t\t\tif((t2Index = pointBelongToEdgeOutideObstacle(poly, sIndex, tempEdgeToRemoveSet, outerBoundary))!= -1)\r\n\t\t\t{\r\n\t\t\t\tt1Index = edge.second;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t\t// Try the other vertex\r\n\t\t\tsIndex = edge.second;\r\n\t\t\tif((t2Index = pointBelongToEdgeOutideObstacle(poly, sIndex, tempEdgeToRemoveSet, outerBoundary))!= -1)\r\n\t\t\t{\r\n\t\t\t\tt1Index = edge.first;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\t\t// Now edge (sIndex, t1Index) crosses the boundary, and (sIndex, t2Index) it outside the boundary \r\n\t\t// We simply locate a hexagon containing these two edges to extend the cycle \r\n\t\tPoint_2 p1 = m_vidPointMap[sIndex]; \r\n\t\tPoint_2 p2 = m_vidPointMap[t1Index]; \r\n\t\tPoint_2 p3 = m_vidPointMap[t2Index];\r\n\t\tICPoint_2 midPoint = K_ICK_converter(Point_2((p2.x() + p3.x())/2, (p2.y() + p3.y())/2));\r\n\t\tcrp = locateHexagonForPoint(midPoint);\r\n\t\tpopulateHexagon(crp.first, crp.second, p, e, hex, pIndex);\r\n\r\n\t\tint endIndex = sIndex;\t\t// When we see this index again, we are done\r\n\r\n\t\t// Add valid edge to cycle\r\n\t\taddEdgeIfNotThere(sIndex, t2Index, boundingCycle);\r\n\r\n\t\t// With the first hexagon, we can keep going along the boundary \r\n\t\twhile(true){\r\n\t\t\t// Get next candidate index\r\n\t\t\tint nextIndex = getNextNodeInSequence(sIndex, t2Index, pIndex);\r\n\t\t\t\r\n\t\t\tp1 = m_vidPointMap[sIndex]; \r\n\t\t\tp2 = m_vidPointMap[nextIndex]; \r\n\t\t\tp3 = m_vidPointMap[t2Index];\r\n\r\n\t\t\t// Check whether the edge (t2Index, nextIndex) crosses boundary\r\n\t\t\tif(edgeInSet(t2Index, nextIndex, tempEdgeToRemoveSet)){\r\n\t\t\t\t// In this case, we move to the next hexagon\r\n\t\t\t\tcrp = getBorderHexagon(crp.first, crp.second, nextIndex, t2Index, pIndex);\r\n\t\t\t\tpopulateHexagon(crp.first, crp.second, p, e, hex, pIndex);\r\n\t\t\t\tsIndex = nextIndex;\r\n\t\t\t\t// t2Index = sIndex;\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\t// Edge is valid, update indices\r\n\t\t\t\tsIndex = t2Index;\r\n\t\t\t\tt2Index = nextIndex;\r\n\r\n\t\t\t\t// Add valid edge to cycle\r\n\t\t\t\taddEdgeIfNotThere(sIndex, t2Index, boundingCycle);\r\n\t\t\t}\r\n\r\n\t\t\tif(endIndex == t2Index) break;\r\n\t\t}\r\n\t}\r\n\r\n\t// =====================================================================================\r\n\t// Process bounding cycle to remove single degree vertices\r\n\tstd::set<int> vSet = boundingCycle.getVertexSet();\r\n\tstd::set<int> vSingleSet;\r\n\t// Collect single degree vertices\r\n\tfor(std::set<int>::iterator vit = vSet.begin(); vit != vSet.end(); vit++){\r\n\t\tif(boundingCycle.getNeighborSet(*vit).size() == 1){\r\n\t\t\tvSingleSet.insert(*vit);\r\n\t\t\t// Need to check the neighbor as well\r\n\t\t\tint prevNbr = *vit;\r\n\t\t\tint nbr = *(boundingCycle.getNeighborSet(*vit).begin());\r\n\t\t\twhile(boundingCycle.getNeighborSet(nbr).size()==2){\r\n\t\t\t\tvSingleSet.insert(nbr);\r\n\t\t\t\tstd::set<int> nbrSet = boundingCycle.getNeighborSet(nbr);\r\n\t\t\t\tnbrSet.erase(prevNbr);\r\n\r\n\t\t\t\tprevNbr = nbr;\r\n\t\t\t\tnbr = *(nbrSet.begin());\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t// Delete them\r\n\tfor(std::set<int>::iterator vit = vSingleSet.begin(); vit != vSingleSet.end(); vit++){\r\n\t\tboundingCycle.removeVertex(*vit);\r\n\r\n\t\t// It seems good to remove these single degree vertices \r\n\t\tif(!outerBoundary)m_vertexToBeRemovedSet.insert(*vit);\r\n\t}\r\n}\r\n\r\nstd::pair<int, int> Roadmap::getBorderHexagon(int col, int row, int i1, int i2, int pIndex[]){\r\n\t// First locate the index of i1\r\n\tint i1Index = 0;\r\n\tfor(int i = 0; i < 6; i ++){\r\n\t\tif(pIndex[i] == i1){\r\n\t\t\ti1Index = i;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\t// Figure out the edge index\r\n\tint edgeIndex = 0;\r\n\tint nextIndex = (i1Index == 5? 0 : i1Index + 1);\r\n\tif(pIndex[nextIndex] == i2){\r\n\t\t// Going clockwise\r\n\t\tedgeIndex = i1Index;\r\n\t}\r\n\telse{\r\n\t\t// Going counterclockwise\r\n\t\tedgeIndex = (i1Index + 6 - 1)%6;\r\n\t}\r\n\r\n\t// Locate the next hexagon\r\n\tif(col%2 == 0){\r\n\t\tswitch(edgeIndex){\r\n\t\t\tcase 0: col--; break;\r\n\t\t\tcase 1: row++; break;\r\n\t\t\tcase 2: col++; break;\r\n\t\t\tcase 3: col++; row--; break;\r\n\t\t\tcase 4: row--; break;\r\n\t\t\tcase 5: col--; row--; break;\r\n\t\t\tdefault: break;\r\n\t\t}\r\n\t}\r\n\telse{\r\n\t\tswitch(edgeIndex){\r\n\t\t\tcase 0: col--; row++; break;\r\n\t\t\tcase 1: row++; break;\r\n\t\t\tcase 2: col++; row++; break;\r\n\t\t\tcase 3: col++; break;\r\n\t\t\tcase 4: row--; break;\r\n\t\t\tcase 5: col--; break;\r\n\t\t\tdefault: break;\r\n\t\t}\r\n\t}\r\n\treturn std::pair<int, int>(col, row);\r\n}\r\n\r\nbool Roadmap::edgeInSet(int v1, int v2, std::set<std::pair<int, int> >& edgeSet){\r\n\tstd::pair<int, int> edge(v1, v2);\r\n\tstd::pair<int, int> rEdge(v2, v1);\r\n\treturn (edgeSet.find(edge) != edgeSet.end() || edgeSet.find(rEdge) != edgeSet.end());\r\n}\r\n\r\nvoid Roadmap::addEdgeIfNotThere(int v1, int v2, Graph & graph){\r\n\tif(!graph.hasEdge(v1, v2)){\r\n\t\tgraph.addEdge(v1, v2);\r\n\t}\r\n}\r\n\r\nint Roadmap::getNextNodeInSequence(int i1, int i2, int pIndex[]){\r\n\t// First locate the index of i1\r\n\tint i1Index = 0;\r\n\tfor(int i = 0; i < 6; i ++){\r\n\t\tif(pIndex[i] == i1){\r\n\t\t\ti1Index = i;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tint nextIndex = (i1Index == 5? 0 : i1Index + 1);\r\n\tif(pIndex[nextIndex] == i2){\r\n\t\t// Going clockwise\r\n\t\treturn pIndex[(i1Index + 2)%6];\r\n\t}\r\n\telse{\r\n\t\t// Going counterclockwise\r\n\t\treturn pIndex[(6 + i1Index - 2)%6];\r\n\t}\r\n}\r\n\r\nstd::pair<int, int> Roadmap::locateHexagonForPoint(ICPoint_2 &p0){\r\n\t// Compute the rectangular (col, row) \r\n\tint col = (int)(floor((p0.x() - xs)/(m_edgeLength*1.5)));\r\n\tint row = (int)(floor((p0.y() - ys)/(m_edgeLength*sqrt3)));\r\n\r\n\t// Shift everything to the \"origin\"\r\n\tdouble dx = p0.x() - (xs + m_edgeLength*1.5*col);\r\n\tdouble dy = p0.y() - (ys + m_edgeLength*sqrt3*row);\r\n\r\n\t// For each col/row combo, which correspond to a rectangular region, there can be\r\n\t// three hexagons corrsponding to a point in that rectangle\r\n\tif(col%2 == 0){\r\n\t\tif(dx <= 0.5*m_edgeLength && dy <= sqrt3*m_edgeLength  - sqrt3*dx && dy >= sqrt3*dx){\r\n\t\t\t// We need to move left\r\n\t\t\tcol --;\r\n\t\t\t// row ++;\r\n\t\t}\r\n\t\telse if(dy >= m_edgeLength*0.5*sqrt3){\r\n\t\t\t// Off by one row\r\n\t\t\trow ++;\r\n\t\t}\r\n\t\telse{\r\n\t\t\t// Already in the right place, do nothing\r\n\t\t}\r\n\t}\r\n\telse{\r\n\t\tif(dy >= sqrt3*0.5*m_edgeLength + sqrt3*dx){\r\n\t\t\tcol--;\r\n\t\t\trow++;\r\n\t\t}\r\n\t\telse if(dy <= sqrt3*0.5*m_edgeLength - sqrt3*dx){\r\n\t\t\tcol--;\r\n\t\t}\r\n\t\telse{\r\n\t\t\t// Already in the right place, do nothing\r\n\t\t}\r\n\t}\r\n\treturn std::pair<int, int>(col, row);\r\n}\r\n\r\nint Roadmap::pointBelongToEdgeOutideObstacle(Polygon_2 & poly, int pIndex, \r\n\tstd::set<std::pair<int,int> > &tempEdgeToRemoveSet, bool outerBoundary){\r\n\t// Grab the point and check whether it is in the c-space \r\n\tif(pointOutsideObstacle(poly, pIndex, outerBoundary)){\r\n\t\t// The point is not \"in\" the obstacle, get edges and check that they are not \r\n\t\t// intersecting with the boundary. Because pIndex is outside obstacle, as long\r\n\t\t// as one edge from pIndex is not intersecting boundary, the edge must be outside \r\n\t\t// the boundary\r\n\t\tstd::set<int>& nbrSet = m_graph.getNeighborSet(pIndex);\r\n\t\tfor(std::set<int>::iterator nit = nbrSet.begin(); nit != nbrSet.end(); nit++){\r\n\t\t\tint et = *nit;\r\n\t\t\tif(!edgeInSet(pIndex, et, tempEdgeToRemoveSet)){\r\n\t\t\t\treturn et;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn -1;\r\n}\r\n\r\nbool Roadmap::pointOutsideObstacle(Polygon_2 & poly, int pIndex, bool outerBoundary){\r\n\tPoint_2 p = m_vidPointMap[pIndex];\r\n\tint boundedStatus = poly.bounded_side(p);\r\n\tif((boundedStatus == CGAL::ON_BOUNDED_SIDE && outerBoundary) ||\r\n\t\t(boundedStatus == CGAL::ON_UNBOUNDED_SIDE && !outerBoundary)){\r\n\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nvoid Roadmap::populateHexagon(int col, int row, Point_2* p, Segment_2* e, Polygon_2 &hex, int* pIndex){\r\n\thex.clear();\r\n\tif(col%2 == 0){\r\n\t\tpIndex[0] = (col + row*n_w)*2;\r\n\t\tpIndex[1] = (col + row*n_w)*2 + 1;\r\n\t\tpIndex[2] = (col + 1 + row*n_w)*2 + 1;\r\n\t\tpIndex[3] = (col + 1 + row*n_w)*2;\r\n\t\tpIndex[4] = (col + 1 + (row-1)*n_w)*2 + 1;\r\n\t\tpIndex[5] = (col + (row-1)*n_w)*2 + 1;\r\n\t}\r\n\telse{\r\n\t\tpIndex[0] = (col + row*n_w)*2 + 1;\r\n\t\tpIndex[1] = (col + (row+1)*n_w)*2;\r\n\t\tpIndex[2] = (col + 1 + (row+1)*n_w)*2;\r\n\t\tpIndex[3] = (col + 1 + row*n_w)*2 + 1;\r\n\t\tpIndex[4] = (col + 1 + row*n_w)*2;\r\n\t\tpIndex[5] = (col + row*n_w)*2;\r\n\t}\r\n\t// Then we get all vertices\r\n\tfor(int i = 0; i < 6; i ++){\r\n\t\tp[i] = m_vidPointMap[pIndex[i]];\r\n\t}\r\n\r\n\t// Then the edges and the hexgaon\r\n\tfor(int i = 0; i < 6; i ++){\r\n\t\te[i] = Segment_2(p[i], p[i == 5? 0 : i+1]);\r\n\t\thex.push_back(p[i]);\r\n\t}\r\n}\r\n\r\nvoid Roadmap::buildHexgaonLattice(){\r\n\r\n\t// Start the lattice at bottomLeftX, bottomLeftY. \r\n\t// Assume that there are n_w and n_h hexgons inside the rectangle, then we should have\r\n\t// (1/2)*sideLength + n_w*sideLength*3/2 <= width and width < (1/2)*sideLength + (n_w + 1)*sideLength*3/2 \r\n\t// (sqrt(3)/2)*sideLength + n_h*(sqrt(3)/2)*sideLength <= height and height < (sqrt(3)/2)*sideLength + (n_h + 1)*(sqrt(3)/2)*sideLength\r\n\t// From these we can compute n_w and n_h. We add a few to make sure that we cover everything. \r\n\r\n\t// Compute lattice nodes\r\n\tfor(int i = 0; i < n_w; i ++){\r\n\t\tfor(int j = 0; j < n_h; j ++){\r\n\t\t\t// Build one vertical \"wave\" of vertices\r\n\t\t\tPoint_2 v0(xs + i*m_edgeLength*1.5 + (i%2 == 0? 0 : m_edgeLength*0.5), \r\n\t\t\t\tys + j*m_edgeLength*sqrt3);\r\n\t\t\tPoint_2 v1(xs + m_edgeLength/2 + i*m_edgeLength*1.5 + (i%2 == 0? 0 : - m_edgeLength*0.5), \r\n\t\t\t\tys + sqrt3*m_edgeLength/2 + j*m_edgeLength*sqrt3);\r\n\r\n\t\t\tm_vidPointMap[(i + j*n_w)*2] = v0;\r\n\t\t\tm_pointVidMap[v0] = (i + j*n_w)*2;\r\n\t\t\tm_vidPointMap[(i + j*n_w)*2 + 1] = v1;\r\n\t\t\tm_pointVidMap[v1] = (i + j*n_w)*2 + 1;\r\n\r\n\t\t\tm_pointList.push_back(v0);\r\n\t\t\tm_pointList.push_back(v1);\r\n\t\t}\r\n\t}\r\n\r\n\t// Build adjacency, for each vertex, check whether its three neighbors are present\r\n\tfor(int id = 0; id < n_w*n_h*2; id ++){\r\n\t\t// Compute w, h\r\n\t\tint w = (id/2)%n_w;\r\n\t\tint h = (id/2)/n_w;\r\n\t\tbool odd = (id%2==1);\r\n\r\n\t\t// If odd is true, check the vertex above, which has index (w, h + 1, 0)\r\n\t\tif(odd){\r\n\t\t\tif(h + 1 < n_h){\r\n\t\t\t\tm_graph.addEdge(id, (w + (h + 1)*n_w)*2);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse{\r\n\t\t\tm_graph.addEdge(id, (w + (h)*n_w)*2 + 1);\r\n\t\t}\r\n\t\t// If odd is true and w is even, check (w + 1, h, 1)\r\n\t\tif(odd && w%2 == 0){\r\n\t\t\tif(w + 1 < n_w){\r\n\t\t\t\tm_graph.addEdge(id, (w + 1 + h*n_w)*2 + 1);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// If odd is false and w is odd, check (w + 1, h, 0)\r\n\t\tif(odd == false && w%2 == 1){\r\n\t\t\tif(w + 1 < n_w){\r\n\t\t\t\tm_graph.addEdge(id, (w + 1 + h*n_w)*2);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid Roadmap::drawHexagonLattice(QGraphicsScene& scene, bool drawVetex){\r\n\tQPen edgePen = QPen(Qt::gray, 0.25, Qt::DashLine, Qt::RoundCap, Qt::RoundJoin);\r\n\tQPen vertexPen = QPen(Qt::blue, 0.4, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\r\n\tstd::set<std::pair<int, int> > edgeSet = m_graph.getEdgeSet();\r\n\tstd::set<int> vSet;\r\n\tfor(std::set<std::pair<int, int> >::iterator eit = edgeSet.begin(); eit != edgeSet.end(); eit++){\r\n\t\tint v1 = (*eit).first;\r\n\t\tint v2 = (*eit).second;\r\n\t\tvSet.insert(v1); vSet.insert(v2);\r\n\t\tICPoint_2 p1 = K_ICK_converter(m_vidPointMap[v1]);\r\n\t\tICPoint_2 p2 = K_ICK_converter(m_vidPointMap[v2]);\r\n\t\tscene.addLine(p1.x(), p1.y(), p2.x(), p2.y(), edgePen);\r\n\t}\r\n\r\n\t// Paint vertices if needed and obtain the fill area\r\n\tif(drawVetex){\r\n\t\tfor(std::set<int>::iterator vit = vSet.begin(); vit != vSet.end(); vit ++){\r\n\t\t\tICPoint_2 p = K_ICK_converter(m_vidPointMap[*vit]);\r\n\t\t\tscene.addEllipse(p.x() - 0.25, p.y() - 0.25, 0.5, 0.5, vertexPen);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid Roadmap::snapToGraph(vector<pair<double, double> >&coords, vector<int>&snapped){\r\n\tset<int> usedVertices;\r\n\t// For each member in coords, locate the hexagon it belongs and then locate the closest \r\n\t// graph vertex to the said coordinate. \r\n\tfor(int r = 0; r < coords.size(); r ++){\r\n\t\tdouble x = coords[r].first;\r\n\t\tdouble y = coords[r].second;\r\n\t\tPoint_2 p0 = Point_2(x, y);\r\n\r\n\t\tICPoint_2 p0x = K_ICK_converter(p0);\r\n\t\tstd::pair<int, int> crp = locateHexagonForPoint(p0x);\r\n\t\tint col = crp.first;\r\n\t\tint row = crp.second;\r\n\r\n\t\t// Compute the current hexagon\r\n\t\tPoint_2 p[6];\r\n\t\tSegment_2 e[6];\r\n\t\tPolygon_2 hex; \r\n\t\tint pIndex[6];\r\n\t\tpopulateHexagon(col, row, p, e, hex, pIndex);\r\n\r\n\t\t// Find the closest vertex that is not occupied and inside the configuration space\r\n\t\tint bestV = -1;\r\n\t\tdouble minDist = -1;\r\n\t\tfor(int vi = 0; vi < 6; vi ++){\r\n\t\t\t// Only work with vertices inside the configuration space and not used\r\n\t\t\tif(m_graph.hasVertex(pIndex[vi]) \r\n\t\t\t   && usedVertices.find(pIndex[vi]) == usedVertices.end()){\r\n\t\t\t\tif(minDist < 0){\r\n\t\t\t\t\tminDist = getDistance(p0, p[vi]);\r\n\t\t\t\t\tbestV = pIndex[vi];\r\n\t\t\t\t}\r\n\t\t\t\telse{\r\n\t\t\t\t\tdouble dist = getDistance(p0, p[vi]);\r\n\t\t\t\t\tif(minDist > dist){\r\n\t\t\t\t\t\tminDist = dist;\r\n\t\t\t\t\t\tbestV = pIndex[vi];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// Snap!\r\n\t\tif(bestV != -1){\r\n#ifdef _DEBUG\r\n\t\t\tcout << \"Snapping point (\" << x << \", \" << y << \") to vertex \" << m_vidGFMap[bestV] << endl;\r\n#endif\r\n\t\t\tsnapped.push_back(m_vidGFMap[bestV]);\r\n\t\t\tusedVertices.insert(bestV);\r\n\t\t}\r\n\t\telse{\r\n\t\t\tthrow \"ERROR: Cannot find suitable vertex for snapping\";\r\n\t\t}\r\n\t}\r\n\r\n}\r\n\r\nvoid Roadmap::createRandomStartGoalPairs(int numRobots, double spacing,  vector<pair<double, double> >& starts, \r\n\tvector<pair<double, double> >& goals){\r\n\r\n\tcreateRandomCoords(numRobots, spacing, starts);\r\n\tcreateRandomCoords(numRobots, spacing, goals);\r\n}\r\n\r\nvoid Roadmap::createRandomCoords(int numRobots, double spacing, vector<pair<double, double> >& coords){\r\n\t// Uniform sample from the free space and pick 5 start/goal pairs\r\n\tCGAL::Bbox_2 bbox = m_pBoundingRect->bbox();\r\n\twhile(true){\r\n\t\tlong trialCount = 0;\r\n\t\tfor(int i = 0; i < numRobots; i ++){\r\n\t\t\twhile(trialCount < numRobots*30000){\r\n\t\t\t\ttrialCount ++;\r\n#ifdef _DEBUG\r\n\t\t\t\tif(trialCount %1000 == 0) {cout << trialCount << endl;}\r\n#endif\r\n\t\t\t\tdouble x = (rand()%10000)/10000.*(bbox.xmax() - bbox.xmin())  + bbox.xmin();\r\n\t\t\t\tdouble y = (rand()%10000)/10000.*(bbox.ymax() - bbox.ymin())  + bbox.ymin();\r\n#ifdef _DEBUG\r\n\t\t\t\tcout << \"Randomly created point with x=\" << x <<\", y=\" << y;\r\n#endif\r\n\t\t\t\tPoint_2 p(x, y);\r\n\t\t\t\t// Check that the point is in free configuration space\r\n\t\t\t\tif(isPointInCSpace(p)){\r\n\t\t\t\t\tbool good = true;\r\n\t\t\t\t\t// Check that the point has good distance from existing points\r\n\t\t\t\t\tfor(int vi = 0; vi < coords.size(); vi ++){\r\n\t\t\t\t\t\tif(getDistance(p, coords[vi].first, coords[vi].second) < (spacing > 2 ? spacing : 2)*m_radius){\r\n\t\t\t\t\t\t\tgood = false;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif(good){\r\n\t\t\t\t\t\t// No problem! We have a good set\r\n\t\t\t\t\t\tcoords.push_back(pair<double, double>(x, y));\r\n#ifdef _DEBUG\r\n\t\t\t\t\t\tcout << \" - added to set for robot \" << i << endl;\r\n#endif\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse{\r\n#ifdef _DEBUG\r\n\t\t\t\t\t\tcout << endl; \r\n#endif\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t}\r\n\t\t\t\telse{\r\n#ifdef _DEBUG\r\n\t\t\t\t\tcout << endl; \r\n#endif\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif(trialCount >= numRobots*30000){\r\n\t\t\t\t// cout << coords.size() << endl;\r\n\t\t\t\tcoords.clear();\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(coords.size() == numRobots)return;\r\n\t}\r\n}\r\n\r\n\r\nbool Roadmap::solveProblem(vector<pair<int, int> >& sgVec, map<int, vector<int> >& paths,\r\n\tstring& fileFolder, string& fileNameExtra){\r\n\t// Solve the problem by calling external java solver\r\n\t\r\n\t// =====================================================================================\r\n\t// First write the problem \r\n\tstring pfString = fileFolder + \"\\\\p\" + fileNameExtra + \".txt\";\r\n\tstring sfString = fileFolder + \"\\\\s\" + fileNameExtra + \".txt\";\r\n\tofstream ps(pfString.c_str(), ios::out);\r\n\r\n\t// Write the the number of robots\r\n\tps << m_finalGraph.getVertexSet().size() << endl;\r\n\r\n\t// Write out all the edges\r\n\tset<pair<int, int> >& edgeSet = m_finalGraph.getEdgeSet();\r\n\tfor(set<pair<int, int> >::iterator ei = edgeSet.begin(); ei != edgeSet.end(); ei ++){\r\n\t\tps << ei->first << \":\" << ei->second << \" \";\r\n\t}\r\n\tps << endl;\r\n\r\n\t// Write out the starts and then the goals\r\n\tfor(int r = 0; r < sgVec.size(); r ++){\r\n\t\tps << sgVec[r].first << \" \";\r\n\t}\r\n\tps << endl;\r\n\tfor(int r = 0; r < sgVec.size(); r ++){\r\n\t\tps << sgVec[r].second << \" \";\r\n\t}\r\n\tps << endl;\r\n\tps.close();\r\n\r\n\t// =====================================================================================\r\n\t// Make system call \r\n\tstring callStr = \"java -cp gurobi.jar;mp.jar projects.multipath.general.algorithms.Main\";\r\n\tif(fileNameExtra.length() > 0) {\r\n\t\tcallStr.append(\" \").append(pfString).append(\" \").append(sfString);\r\n\t}\r\n\tint i = system(callStr.c_str());\r\n\r\n\t// =====================================================================================\r\n\t// Read in the solution, there should be sgVec.size() robots\r\n\tifstream ss(sfString.c_str(), ios::in);\r\n\tif(ss.good()){\r\n\t\tfor(int r = 0; r < sgVec.size(); r++){\r\n\t\t\tstring line; \r\n\t\t\tgetline(ss, line);\r\n\t\t\tQString s(line.c_str());\r\n\t\t\tQStringList qsl = s.split(\" \");\r\n\t\t\tpaths[r] = vector<int>();\r\n\t\t\tfor(int t = 0; t < qsl.size(); t ++){\r\n\t\t\t\tpaths[r].push_back(qsl[t].toInt());\r\n\t\t\t}\r\n\t\t\tpaths[r].pop_back();\r\n\t\t}\r\n\t\tss.close();\r\n\t}\r\n\telse{\r\n\t\tss.close();\r\n\t\treturn false;\r\n\t}\r\n\r\n\t// Solve the problem locally\r\n\t// ILPSolver solver(&m_finalGraph);\r\n\t// solver.solve(sgVec, paths, -1);\r\n\r\n\r\n\timprovePaths(paths);\r\n\treturn true;\r\n}\r\n\r\nvoid Roadmap::improvePaths(map<int, vector<int> >& paths){\r\n\t// Remove obvious ossilation from the paths\r\n\tfor(int t = 1; t < paths[0].size() - 1; t ++){\r\n\t\tfor(int r = 0; r < paths.size(); r ++){\r\n\t\t\t// Do we have single step ossilation?\r\n\t\t\tif(paths[r][t - 1] == paths[r][t + 1] && paths[r][t - 1] != paths[r][t]){\r\n\t\t\t\t// Check whether any other robots goes to paths[r][t - 1] at t\r\n\t\t\t\tbool conflict = false;\r\n\t\t\t\tfor(int ori = 0; ori < paths.size(); ori ++){\r\n\t\t\t\t\tif(ori == r) continue;\r\n\t\t\t\t\tif(paths[ori][t] == paths[r][t - 1]){\r\n\t\t\t\t\t\tconflict = true;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// If not, let the robot stay\r\n\t\t\t\tif(!conflict){\r\n\t\t\t\t\tpaths[r][t] = paths[r][t - 1];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t// Do a two step look ahead as well\r\n\t\t\telse if((t < paths[0].size() - 2) && paths[r][t - 1] == paths[r][t + 2] && \r\n\t\t\t\tpaths[r][t] == paths[r][t + 1] && paths[r][t - 1] != paths[r][t]){\r\n\t\t\t\t// Check whether any other robots goes to paths[r][t - 1] at t\r\n\t\t\t\tbool conflict = false;\r\n\t\t\t\tfor(int ori = 0; ori < paths.size(); ori ++){\r\n\t\t\t\t\tif(ori == r) continue;\r\n\t\t\t\t\tif(paths[ori][t] == paths[r][t - 1] || paths[ori][t + 1] == paths[r][t - 1]){\r\n\t\t\t\t\t\tconflict = true;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// If not, let the robot stay\r\n\t\t\t\tif(!conflict){\r\n\t\t\t\t\tpaths[r][t+1] = paths[r][t] = paths[r][t - 1];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\npair<double, double> Roadmap::getVertexLocationFromID(int vid){\r\n\t// Get vid in the original graph\r\n\tvid = m_vidFGMap[vid];\r\n\r\n\t// Locate the vid\r\n\tPoint_2& p = m_vidPointMap[vid];\r\n\tICPoint_2 pp = K_ICK_converter(p);\r\n\r\n\treturn pair<double, double>(pp.x(), pp.y());\r\n}", "meta": {"hexsha": "9ef59be620a8fc35135665b93e795ad54fa00899", "size": 36532, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "roadmap.cpp", "max_stars_repo_name": "rutgers-arc-lab/optimal-mrpp-continuous", "max_stars_repo_head_hexsha": "d9a85869f79b640984c7469fb8c3aaa4da14a0b2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2017-06-05T09:40:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-24T01:24:07.000Z", "max_issues_repo_path": "roadmap.cpp", "max_issues_repo_name": "wuyou33/optimal-mrpp-continuous", "max_issues_repo_head_hexsha": "d9a85869f79b640984c7469fb8c3aaa4da14a0b2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-07-12T17:22:06.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-15T13:37:44.000Z", "max_forks_repo_path": "roadmap.cpp", "max_forks_repo_name": "wuyou33/optimal-mrpp-continuous", "max_forks_repo_head_hexsha": "d9a85869f79b640984c7469fb8c3aaa4da14a0b2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-07-26T17:08:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T05:41:51.000Z", "avg_line_length": 33.2714025501, "max_line_length": 137, "alphanum_fraction": 0.6147213402, "num_tokens": 10840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.2678755402412479}}
{"text": "/**********************************************************************\n*  Copyright (c) 2008-2016, Alliance for Sustainable Energy.  \n*  All rights reserved.\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 Street, Fifth Floor, Boston, MA  02110-1301  USA\n**********************************************************************/\n\n#ifndef UTILITIES_GEOMETRY_INTERSECTION_HPP\n#define UTILITIES_GEOMETRY_INTERSECTION_HPP\n\n#include \"../UtilitiesAPI.hpp\"\n\n#include \"Point3d.hpp\"\n\n#include <vector>\n#include <boost/optional.hpp>\n\nnamespace openstudio{\n\n  /** IntersectionResult contains detailed information about an intersection. */\n  class UTILITIES_API IntersectionResult {\n  public:\n    IntersectionResult(const std::vector<Point3d>& polygon1, \n                       const std::vector<Point3d>& polygon2, \n                       const std::vector< std::vector<Point3d> >& newPolygons1, \n                       const std::vector< std::vector<Point3d> >& newPolygons2); \n\n    // vertices of first polygon after intersection\n    std::vector<Point3d> polygon1() const;\n\n    // vertices of second polygon after intersection\n    std::vector<Point3d> polygon2() const;\n\n    // new polygons generated from the first surface\n    std::vector< std::vector<Point3d> > newPolygons1() const;\n\n    // new polygons generated from the second surface\n    std::vector< std::vector<Point3d> > newPolygons2() const;\n\n  private:\n    std::vector<Point3d> m_polygon1;\n    std::vector<Point3d> m_polygon2;\n    std::vector< std::vector<Point3d> > m_newPolygons1;\n    std::vector< std::vector<Point3d> > m_newPolygons2;\n  };\n\n  /// removes spikes from a polygon, requires that all vertices are in clockwise order on the z = 0 plane (i.e. in face coordinates but reversed) \n  UTILITIES_API std::vector<Point3d> removeSpikes(const std::vector<Point3d>& polygon, double tol);\n  \n  /// returns true if point is inside polygon, requires that all vertices are in clockwise order on the z = 0 plane (i.e. in face coordinates but reversed) \n  UTILITIES_API bool pointInPolygon(const Point3d& point, const std::vector<Point3d>& polygon, double tol);\n\n  /// compute the union of two overlapping polygons, requires that all vertices are in clockwise order on the z = 0 plane (i.e. in face coordinates but reversed) \n  UTILITIES_API boost::optional<std::vector<Point3d> > join(const std::vector<Point3d>& polygon1, const std::vector<Point3d>& polygon2, double tol);\n  \n  /// compute the union of many polygons, requires that all vertices are in clockwise order on the z = 0 plane (i.e. in face coordinates but reversed) \n  UTILITIES_API std::vector<std::vector<Point3d> > joinAll(const std::vector<std::vector<Point3d> >& polygons, double tol);\n\n  /// intersect two polygons, requires that all vertices are in clockwise order on the z = 0 plane (i.e. in face coordinates but reversed) \n  UTILITIES_API boost::optional<IntersectionResult> intersect(const std::vector<Point3d>& polygon1, const std::vector<Point3d>& polygon2, double tol);\n  \n  /// subtract all holes from polygon, requires that all vertices are in clockwise order on the z = 0 plane (i.e. in face coordinates but reversed) \n  UTILITIES_API std::vector<std::vector<Point3d> > subtract(const std::vector<Point3d>& polygon, const std::vector<std::vector<Point3d> >& holes, double tol);\n\n  /// returns true polygon intersects iteself, requires that all vertices are in clockwise order on the z = 0 plane (i.e. in face coordinates but reversed) \n  /// returns false if polygon has less than three vertices\n  UTILITIES_API bool selfIntersects(const std::vector<Point3d>& polygon, double tol);\n\n  /// returns true if polygon1 intersects polygon2, requires that all vertices are in clockwise order on the z = 0 plane (i.e. in face coordinates but reversed) \n  /// returns false if either polygon has less than three vertices\n  UTILITIES_API bool intersects(const std::vector<Point3d>& polygon1, const std::vector<Point3d>& polygon2, double tol);\n\n  /// returns true if geometry1 is completely within polygon2, requires that all vertices are in clockwise order on the z = 0 plane (i.e. in face coordinates but reversed) \n  /// geometry1 can be a point or a polygon \n  /// currently only tests that all points of geometry1 are within polygon2, better support when upgrade to boost 1.57\n  UTILITIES_API bool within(const Point3d& point1, const std::vector<Point3d>& polygon2, double tol);\n  UTILITIES_API bool within(const std::vector<Point3d>& geometry1, const std::vector<Point3d>& polygon2, double tol);\n\n} // openstudio\n\n#endif //UTILITIES_GEOMETRY_INTERSECTION_HPP\n", "meta": {"hexsha": "dc0c18fdad99ce75168093e5775417b4f609a188", "size": 5233, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "openstudiocore/src/utilities/geometry/Intersection.hpp", "max_stars_repo_name": "jasondegraw/OpenStudio", "max_stars_repo_head_hexsha": "2ab13f6e5e48940929041444e40ad9d36f80f552", "max_stars_repo_licenses": ["blessing"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-12-29T08:45:03.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-29T08:45:03.000Z", "max_issues_repo_path": "openstudiocore/src/utilities/geometry/Intersection.hpp", "max_issues_repo_name": "jasondegraw/OpenStudio", "max_issues_repo_head_hexsha": "2ab13f6e5e48940929041444e40ad9d36f80f552", "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/utilities/geometry/Intersection.hpp", "max_forks_repo_name": "jasondegraw/OpenStudio", "max_forks_repo_head_hexsha": "2ab13f6e5e48940929041444e40ad9d36f80f552", "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": 55.670212766, "max_line_length": 172, "alphanum_fraction": 0.7188992929, "num_tokens": 1241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2678428837907652}}
{"text": "#include <idmlib/translation/ibm_model1.h>\n#include <boost/unordered_map.hpp>\n#include <iostream>\nusing namespace idmlib::tl;\n\nIbmModel1::IbmModel1(uint32_t iteration)\n:iteration_(iteration)\n{\n}\n\nboost::unordered_map<std::pair<uint32_t, uint32_t>, double>* IbmModel1::Train(uint32_t source_num, const std::vector<SentencePair>& corpus)\n{\n    std::cout<<\"IBM MODEL 1 starting..\"<<std::endl;\n    ///result gives P(source | target)\n    boost::unordered_map<TermPair, double>* result = new boost::unordered_map<TermPair, double>();\n    uint32_t iteration = 0;\n    while(true)\n    {\n        ++iteration;\n        if(iteration>iteration_) break;\n        std::cout<<\"IBM MODEL 1 iteration \"<<iteration<<std::endl;\n        boost::unordered_map<TermPair, double> count;\n        boost::unordered_map<Term, double> total;\n        for(std::size_t i=0;i<corpus.size();i++)\n        {\n            boost::unordered_map<Term, double> total_s;\n            const Sentence& source = corpus[i].first;\n            const Sentence& target = corpus[i].second;\n            for(std::size_t i=0;i<source.size();i++)\n            {\n                Term source_term = source[i];\n                boost::unordered_map<Term, double>::iterator total_s_it = total_s.insert(std::make_pair(source_term, 0.0) ).first;\n                for(std::size_t j=0;j<target.size();j++)\n                {\n                    TermPair term_pair(source_term, target[j]);\n                    \n                    boost::unordered_map<TermPair, double>::iterator it = result->find(term_pair);\n                    if( it == result->end())\n                    {\n                        it = result->insert(std::make_pair(term_pair, 1.0/source_num)).first;\n                    }\n                    total_s_it->second += it->second;\n                }\n            }\n            \n            for(std::size_t i=0;i<source.size();i++)\n            {\n                Term source_term = source[i];\n                for(std::size_t j=0;j<target.size();j++)\n                {\n                    Term target_term = target[j];\n                    TermPair term_pair(source_term, target_term);\n                    \n                    boost::unordered_map<TermPair, double>::iterator count_it = count.find(term_pair);\n                    if(count_it == count.end())\n                    {\n                        count_it = count.insert(std::make_pair( term_pair, 0.0) ).first;\n                    }\n                    \n                    boost::unordered_map<Term, double>::iterator total_it = total.find(target_term);\n                    if(total_it == total.end())\n                    {\n                        total_it = total.insert(std::make_pair( target_term, 0.0) ).first;\n                    }\n                    \n                    boost::unordered_map<TermPair, double>::iterator it = result->find(term_pair);\n                    double t = it->second;\n\n                    boost::unordered_map<Term, double>::iterator total_s_it = total_s.find(source_term);\n                    double add = t/ (total_s_it->second);\n                    count_it->second += add;\n                    total_it->second += add;\n                }\n            }\n        }\n        \n        boost::unordered_map<TermPair, double>::iterator it = result->begin();\n        while(it!=result->end())\n        {\n            TermPair term_pair = it->first;\n            boost::unordered_map<TermPair, double>::iterator count_it = count.find(term_pair);\n            boost::unordered_map<Term, double>::iterator total_it = total.find(term_pair.second);\n            it->second = count_it->second / total_it->second;\n            ++it;\n        }\n    }\n    std::cout<<\"IBM MODEL 1 finished.\"<<std::endl;\n    return result;\n}\n", "meta": {"hexsha": "3d95cf50cfcf5ce9252cdde1282795c95ae4c47c", "size": 3728, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/translation/ibm_model1.cc", "max_stars_repo_name": "izenecloud/idmlib", "max_stars_repo_head_hexsha": "ec6afd44490170a70ef980afa6d21fba8c77ed9d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-11-14T06:37:25.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-14T06:37:25.000Z", "max_issues_repo_path": "source/translation/ibm_model1.cc", "max_issues_repo_name": "izenecloud/idmlib", "max_issues_repo_head_hexsha": "ec6afd44490170a70ef980afa6d21fba8c77ed9d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/translation/ibm_model1.cc", "max_forks_repo_name": "izenecloud/idmlib", "max_forks_repo_head_hexsha": "ec6afd44490170a70ef980afa6d21fba8c77ed9d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-09-06T05:59:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-17T06:11:24.000Z", "avg_line_length": 41.4222222222, "max_line_length": 139, "alphanum_fraction": 0.5222639485, "num_tokens": 806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2678428837907652}}
{"text": "#ifndef STAN_MATH_TORSTEN_DSOLVE_ODEINT_INTEGRATOR_HPP\n#define STAN_MATH_TORSTEN_DSOLVE_ODEINT_INTEGRATOR_HPP\n\n#include <stan/math/torsten/dsolve/pmx_odeint_system.hpp>\n#include <stan/math/torsten/mpi/precomputed_gradients.hpp>\n#include <boost/numeric/odeint.hpp>\n#include <type_traits>\n\nnamespace torsten {\nnamespace dsolve {\n\n/**\n * @c boost::odeint ODE integrator.\n */\n  template<typename scheme_t>\n  struct PMXOdeintIntegrator {\n    const double rtol_;\n    const double atol_;\n    const int64_t max_num_steps_;\n\n    template<typename Ode, bool GenVar>\n    struct SolObserver {\n      const Ode& ode_;\n      const size_t n;\n      const size_t m;\n      std::vector<std::vector<typename Ode::scalar_t>> y;\n      int step_counter_;\n\n      SolObserver(const Ode& ode) :\n        ode_(ode), n(ode.N_), m(ode.M_),\n        y(ode.ts_.size(), std::vector<typename Ode::scalar_t>(ode.N_, 0.0)),\n        step_counter_(0)\n      {}\n\n      /*\n       * use observer to convert y value and gradient to var\n       * results, if necessary.\n       */\n      inline void operator()(const std::vector<double>& curr_result, double t) {\n        if(t > ode_.t0_) {\n          observer_impl(y[step_counter_], curr_result, ode_.ts_, ode_.y0_, ode_.theta_, step_counter_);\n          step_counter_++;\n        }\n      }\n\n    private:\n      /*\n       * All data, return data\n       */\n      inline void observer_impl(std::vector<double>& y_res,\n                                const std::vector<double>& y,\n                                const std::vector<double>& ts,\n                                const std::vector<double>& y0,\n                                const std::vector<double>& theta,\n                                int i) const {\n        std::copy(y.begin(), y.end(), y_res.begin());\n      }\n\n      /*\n       * When only @c ts is @c var, we don't solve\n       * sensitivity ODE since the sensitivity is simply the RHS.\n       */\n      inline void observer_impl(std::vector<stan::math::var>& y_res,\n                                const std::vector<double>& y,\n                                const std::vector<stan::math::var>& ts,\n                                const std::vector<double>& y0,\n                                const std::vector<double>& theta,\n                                int i) const {\n        int n = y0.size();\n        std::vector<double> g(n * (1 + ts.size()), 0.0);\n        std::copy(y.begin(), y.end(), g.begin());        \n        std::vector<double> dy_dt(n);\n        ode_.dbl_rhs_impl(y, dy_dt, ts[i].val());\n        std::copy(dy_dt.begin(), dy_dt.end(), g.begin() + n + i * n);\n        y_res = torsten::precomputed_gradients(g, ts);\n      }\n\n      /*\n       * Only @c theta is @c var\n       */\n      inline void observer_impl(std::vector<stan::math::var>& y_res,\n                                const std::vector<double>& y,\n                                const std::vector<double>& ts,\n                                const std::vector<double>& y0,\n                                const std::vector<stan::math::var>& theta,\n                                int i) const {\n        y_res = torsten::precomputed_gradients(y, theta);\n      }\n\n      /*\n       * only @c y0 is @c var\n       */\n      inline void observer_impl(std::vector<stan::math::var>& y_res,\n                                const std::vector<double>& y,\n                                const std::vector<double>& ts,\n                                const std::vector<stan::math::var>& y0,\n                                const std::vector<double>& theta,\n                                int i) const {\n        y_res = torsten::precomputed_gradients(y, y0);\n      }\n\n      /*\n       * @c y0 and @c theta are @c var\n       */\n      inline void observer_impl(std::vector<stan::math::var>& y_res,\n                                const std::vector<double>& y,\n                                const std::vector<double>& ts,\n                                const std::vector<stan::math::var>& y0,\n                                const std::vector<stan::math::var>& theta,\n                                int i) const {\n        y_res = torsten::precomputed_gradients(y, ode_.vars());\n      }\n\n      /*\n       * @c theta and/or &c y0 are @c var, together with @c ts.\n       */\n      template<typename T1, typename T2>\n      inline void observer_impl(std::vector<stan::math::var>& y_res,\n                                const std::vector<double>& y,\n                                const std::vector<stan::math::var>& ts,\n                                const std::vector<T1>& y0,\n                                const std::vector<T2>& theta,\n                                int i) const {\n        int ns = ode_.ns;\n        int n = y0.size();\n        std::vector<double> g(n * (1 + ns + ts.size()), 0.0);\n        std::copy(y.begin(), y.end(), g.begin());        \n        std::vector<double> dy_dt(n), y_dbl(y.begin(), y.begin() + n);\n        ode_.dbl_rhs_impl(y_dbl, dy_dt, ts[i].val());\n        std::copy(dy_dt.begin(), dy_dt.end(), g.begin() + n + ns * n + i * n);\n        y_res = torsten::precomputed_gradients(g, ode_.vars());\n      }\n    };\n\n    template<typename Ode>\n    struct SolObserver<Ode, false> {\n      const Ode& ode_;\n      Eigen::MatrixXd y;\n      int step_counter_;\n\n      SolObserver(const Ode& ode) :\n        ode_(ode),\n        y(Eigen::MatrixXd::Zero(ode_.size_ + ode_.N_*(Ode::is_var_ts ? ode_.ts_.size() : 0), ode_.ts_.size())),\n        step_counter_(0)\n      {}\n\n      inline void operator()(const std::vector<double>& curr_result, double t) {\n        if(t > ode_.t0_) {\n          observer_impl(y, curr_result, ode_.ts_, step_counter_);\n          step_counter_++;\n        }\n      }\n\n    private:\n      /*\n       * @@c ts is data\n       */\n      inline void observer_impl(Eigen::MatrixXd& y_res,\n                                const std::vector<double>& y,\n                                const std::vector<double>& ts,\n                                int i) const {\n        using Eigen::VectorXd;\n        y_res.col(i) = VectorXd::Map(y.data(), ode_.size_);\n      }\n\n      /*\n       * @@c ts is @c var\n       */\n      inline void observer_impl(Eigen::MatrixXd& y_res,\n                                const std::vector<double>& y,\n                                const std::vector<stan::math::var>& ts,\n                                int i) const {\n        using Eigen::VectorXd;\n        for (size_t j = 0; j < ode_.size_; ++j) y_res(j, i) = y[j];\n        int n = ode_.N_;\n        std::vector<double> dy_dt(n);\n        std::vector<double> y_tmp(y.begin(), y.begin() + n);\n        ode_.dbl_rhs_impl(y_tmp, dy_dt, ts[i].val());\n        for (size_t j = 0; j < n; ++j) y_res(ode_.size_ + i * n + j, i) = dy_dt[j];\n      }\n    };\n\n  public:\n    /**\n     * constructor\n     * @param[in] rtol relative tolerance\n     * @param[in] atol absolute tolerance\n     * @param[in] max_num_steps max nb. of times steps\n     */\n    PMXOdeintIntegrator(const double rtol, const double atol,\n                        const int64_t max_num_steps)\n      : rtol_(rtol), atol_(atol), max_num_steps_(max_num_steps) {\n      using stan::math::invalid_argument;\n      if (rtol_ <= 0)\n        invalid_argument(\"cvodes_integrator\", \"relative tolerance,\", rtol_, \"\",\n                         \", must be greater than 0\");\n      if (rtol_ > 1.0E-3)\n        invalid_argument(\"cvodes_integrator\", \"relative tolerance,\", rtol_, \"\",\n                         \", must be less than 1.0E-3\");\n      if (atol_ <= 0)\n        invalid_argument(\"cvodes_integrator\", \"absolute tolerance,\", atol_, \"\",\n                         \", must be greater than 0\");\n      if (max_num_steps_ <= 0)\n        invalid_argument(\"cvodes_integrator\", \"max_num_steps,\",\n                         max_num_steps_, \"\",\n                         \", must be greater than 0\");\n    }\n\n    template <typename Ode, bool GenVar = true>\n    auto integrate(Ode& ode) {\n      std::vector<double> ts_vec(ode.ts_.size() + 1);\n      ts_vec[0] = ode.t0_;\n      for (size_t i = 0; i < ode.ts_.size(); ++i) {\n        ts_vec[i + 1] = stan::math::value_of(ode.ts_[i]);\n      }\n\n      SolObserver<Ode, GenVar> observer(ode);\n\n      const double init_dt = 0.1;\n      integrate_times(make_dense_output(atol_, rtol_, scheme_t()),\n                      boost::ref(ode), ode.y0_fwd_system,\n                      ts_vec.begin(), ts_vec.end(),\n                      init_dt, boost::ref(observer),\n                      boost::numeric::odeint::max_step_checker(max_num_steps_));\n      return observer.y;\n    }\n  };\n\n}\n}\n#endif\n", "meta": {"hexsha": "970356d2aa14976171c757c1efbee577e6c60692", "size": 8522, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/torsten/dsolve/pmx_odeint_integrator.hpp", "max_stars_repo_name": "csetraynor/Torsten", "max_stars_repo_head_hexsha": "55b59b8068e2a539346f566ec698c755a9e3536c", "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/dsolve/pmx_odeint_integrator.hpp", "max_issues_repo_name": "csetraynor/Torsten", "max_issues_repo_head_hexsha": "55b59b8068e2a539346f566ec698c755a9e3536c", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/dsolve/pmx_odeint_integrator.hpp", "max_forks_repo_name": "csetraynor/Torsten", "max_forks_repo_head_hexsha": "55b59b8068e2a539346f566ec698c755a9e3536c", "max_forks_repo_licenses": ["BSD-3-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.7327586207, "max_line_length": 111, "alphanum_fraction": 0.5017601502, "num_tokens": 2055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.267798815314657}}
{"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 \"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\nusing namespace tensorflow;\nusing namespace std;\n\ntypedef Eigen::ThreadPoolDevice CPUDevice;\n/*\n * 要求数据已经按重要呈度从0到data_nr排好了序(从大到小）\n * k:结果最多只包含k个\n * bottom_box:[X,4](ymin,xmin,ymax,xmax)\n * classes:[X]\n * output_box:[Y,4]\n * output_classes:[Y]\n * output_index:[Y]\n * 输出时的相对位置不能改变\n */\nREGISTER_OP(\"BoxesNms\")\n    .Attr(\"T: {float, double,int32}\")\n\t.Attr(\"threshold:float\")\n\t.Attr(\"classes_wise:bool\")\n\t.Attr(\"k:int\")\n    .Input(\"bottom_box: T\")\n    .Input(\"classes: int32\")\n\t.Output(\"output_box:T\")\n\t.Output(\"output_classes:int32\")\n\t.Output(\"output_index:int32\")\n\t.SetShapeFn([](shape_inference::InferenceContext* c) {\n\t\t\tc->set_output(0, c->Matrix(-1, 4));\n\t\t\tc->set_output(1, c->Vector(-1));\n\t\t\tc->set_output(2, c->Vector(-1));\n\t\t\treturn Status::OK();\n\t\t\t});\n\ntemplate <typename Device, typename T>\nclass BoxesNmsOp: public OpKernel {\n\tpublic:\n\t\texplicit BoxesNmsOp(OpKernelConstruction* context) : OpKernel(context) {\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"threshold\", &threshold));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"k\", &k_));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"classes_wise\", &classes_wise));\n\t\t}\n\n\t\tvoid Compute(OpKernelContext* context) override\n\t\t{\n            TIME_THIS();\n\t\t\tconst Tensor &bottom_box          = context->input(0);\n\t\t\tconst Tensor &bottom_classes      = context->input(1);\n\t\t\tauto          bottom_box_flat     = bottom_box.flat<T>().data();\n\t\t\tauto          bottom_classes_flat = bottom_classes.flat<int32>().data();\n\n\t\t\tOP_REQUIRES(context, bottom_box.dims() == 2, errors::InvalidArgument(\"box data must be 2-dimensional\"));\n\t\t\tOP_REQUIRES(context, bottom_classes.dims() == 1, errors::InvalidArgument(\"classes data must be 1-dimensional\"));\n\n\t\t\tconst int    data_nr           = bottom_box.dim_size(0);\n\t\t\tvector<bool> keep_mask(data_nr,true);\n\t\t\tconst int    loop_end          = data_nr-1;\n\n\t\t\tfor(auto i=0; i<loop_end; ++i) {\n\t\t\t\tif(keep_mask[i]) {\n\t\t\t\t\tconst auto iclass = bottom_classes_flat[i];\n                    const auto src_box = bottom_box_flat+i*4;\n\t\t\t\t\tfor(auto j=i+1; j<data_nr; ++j) {\n\t\t\t\t\t\tif(classes_wise && (bottom_classes_flat[j] != iclass)) continue;\n\t\t\t\t\t\tif(bboxes_jaccard(src_box,bottom_box_flat+j*4) < threshold) continue;\n\t\t\t\t\t\tkeep_mask[j] = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst auto _out_size = count(keep_mask.begin(),keep_mask.end(),true);\n\t\t\tconst auto out_size = k_>0?std::min<int>(k_,_out_size):_out_size;\n\t\t\tint dims_2d[2] = {int(out_size),4};\n\t\t\tint dims_1d[1] = {int(out_size)};\n\t\t\tTensorShape  outshape0;\n\t\t\tTensorShape  outshape1;\n\t\t\tTensor      *output_box         = NULL;\n\t\t\tTensor      *output_classes     = NULL;\n\t\t\tTensor      *output_index = NULL;\n\n\t\t\tTensorShapeUtils::MakeShape(dims_2d, 2, &outshape0);\n\t\t\tTensorShapeUtils::MakeShape(dims_1d, 1, &outshape1);\n\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(0, outshape0, &output_box));\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(1, outshape1, &output_classes));\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(2, outshape1, &output_index));\n\n\t\t\tauto obox     = output_box->template flat<T>();\n\t\t\tauto oclasses = output_classes->template flat<int32>();\n\t\t\tauto oindex   = output_index->template flat<int32>();\n\n\t\t\tfor(int i=0,j=0; i<data_nr; ++i) {\n\t\t\t\tif(!keep_mask[i]) continue;\n\t\t\t\tauto box = bottom_box_flat+i*4;\n\t\t\t\tstd::copy(box,box+4,obox.data()+4*j);\n\t\t\t\toclasses(j) = bottom_classes_flat[i];\n\t\t\t\toindex(j) = i;\n\t\t\t\t++j;\n\t\t\t\tif(j>=out_size)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\tprivate:\n\t\tfloat threshold    = 0.2;\n\t\tbool  classes_wise = true;\n\t\tint   k_           = -1;\n};\nREGISTER_KERNEL_BUILDER(Name(\"BoxesNms\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), BoxesNmsOp<CPUDevice, float>);\n/*\n * 要求数据已经按重要呈度从0到data_nr排好了序(从大到小）\n * bottom_box:[X,4](ymin,xmin,ymax,xmax)\n * classes:[X]\n * group:[Z,2]分组信息，分别为一个组里标签的开始与结束编号，不在分组信息的的默认为一个组\n * output_box:[Y,4]\n * output_classes:[Y]\n * output_index:[Y]\n * 输出时的相对位置不能改变\n */\nREGISTER_OP(\"GroupBoxesNms\")\n    .Attr(\"T: {float, double,int32}\")\n\t.Attr(\"threshold:float\")\n    .Input(\"bottom_box: T\")\n    .Input(\"classes: int32\")\n    .Input(\"group: int32\")\n\t.Output(\"output_box:T\")\n\t.Output(\"output_classes:int32\")\n\t.Output(\"output_index:int32\")\n\t.SetShapeFn([](shape_inference::InferenceContext* c) {\n\t\t\tc->set_output(0, c->Matrix(-1, 4));\n\t\t\tc->set_output(1, c->Vector(-1));\n\t\t\tc->set_output(2, c->Vector(-1));\n\t\t\treturn Status::OK();\n\t\t\t});\n\ntemplate <typename Device, typename T>\nclass GroupBoxesNmsOp: public OpKernel {\n\tpublic:\n\t\texplicit GroupBoxesNmsOp(OpKernelConstruction* context) : OpKernel(context) {\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"threshold\", &threshold));\n\t\t}\n\n\t\tvoid Compute(OpKernelContext* context) override\n\t\t{\n\t\t\tconst Tensor &bottom_box          = context->input(0);\n\t\t\tconst Tensor &bottom_classes      = context->input(1);\n\t\t\tconst Tensor &_group              = context->input(2);\n\t\t\tauto          bottom_box_flat     = bottom_box.flat<T>().data();\n\t\t\tauto          bottom_classes_flat = bottom_classes.flat<int32>().data();\n\t\t\tauto          group               = _group.template tensor<int,2>();\n\n\t\t\tOP_REQUIRES(context, bottom_box.dims() == 2, errors::InvalidArgument(\"box data must be 2-dimensional\"));\n\t\t\tOP_REQUIRES(context, bottom_classes.dims() == 1, errors::InvalidArgument(\"classes data must be 1-dimensional\"));\n\t\t\tOP_REQUIRES(context, _group.dims() == 2, errors::InvalidArgument(\"group data must be 2-dimensional\"));\n\n\t\t\tconst auto   data_nr           = bottom_box.dim_size(0);\n\t\t\tvector<bool> keep_mask(data_nr,true);\n\t\t\tconst auto   loop_end          = data_nr-1;\n\n\t\t\tfor(auto i=0; i<loop_end; ++i) {\n\t\t\t\tif(keep_mask[i]) {\n\t\t\t\t\tconst auto iclass = bottom_classes_flat[i];\n                    const auto igroup = get_group(group,iclass);\n                    const auto src_box = bottom_box_flat+i*4;\n\t\t\t\t\tfor(auto j=i+1; j<data_nr; ++j) {\n\t\t\t\t\t\tif(igroup != get_group(group,bottom_classes_flat[j])) continue;\n\t\t\t\t\t\tif(bboxes_jaccard(src_box,bottom_box_flat+j*4) < threshold) continue;\n\t\t\t\t\t\tkeep_mask[j] = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst auto out_size = count(keep_mask.begin(),keep_mask.end(),true);\n\t\t\tint dims_2d[2] = {int(out_size),4};\n\t\t\tint dims_1d[1] = {int(out_size)};\n\t\t\tTensorShape  outshape0;\n\t\t\tTensorShape  outshape1;\n\t\t\tTensor      *output_box         = NULL;\n\t\t\tTensor      *output_classes     = NULL;\n\t\t\tTensor      *output_index = NULL;\n\n\t\t\tTensorShapeUtils::MakeShape(dims_2d, 2, &outshape0);\n\t\t\tTensorShapeUtils::MakeShape(dims_1d, 1, &outshape1);\n\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(0, outshape0, &output_box));\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(1, outshape1, &output_classes));\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(2, outshape1, &output_index));\n\n\t\t\tauto obox     = output_box->template flat<T>();\n\t\t\tauto oclasses = output_classes->template flat<int32>();\n\t\t\tauto oindex   = output_index->template flat<int32>();\n\n\t\t\tfor(int i=0,j=0; i<data_nr; ++i) {\n\t\t\t\tif(!keep_mask[i]) continue;\n\t\t\t\tauto box = bottom_box_flat+i*4;\n\t\t\t\tstd::copy(box,box+4,obox.data()+4*j);\n\t\t\t\toclasses(j) = bottom_classes_flat[i];\n\t\t\t\toindex(j) = i;\n\t\t\t\t++j;\n\t\t\t}\n\t\t}\n        template<typename TM>\n        int get_group(const TM& group_data,int label)\n        {\n            for(auto i=0; i<group_data.dimension(0); ++i) {\n                if((label>=group_data(i,0)) && (label<=group_data(i,1)))\n                    return i;\n            }\n            return -1;\n        }\n\tprivate:\n\t\tfloat threshold    = 0.2;\n};\nREGISTER_KERNEL_BUILDER(Name(\"GroupBoxesNms\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), GroupBoxesNmsOp<CPUDevice, float>);\n/*\n * 数据不需要排序\n * bottom_box:[X,4](ymin,xmin,ymax,xmax)\n * classes:[X]\n * confidence:[X]\n * output_box:[Y,4]\n * output_classes:[Y]\n * output_index:[Y]\n * 输出时的相对位置不能改变\n */\nREGISTER_OP(\"BoxesSoftNms\")\n    .Attr(\"T: {float, double,int32}\")\n\t.Attr(\"threshold:float\")\n\t.Attr(\"classes_wise:bool\")\n\t.Attr(\"delta:float\")\n    .Input(\"bottom_box: T\")\n    .Input(\"classes: int32\")\n    .Input(\"confidence:float\")\n\t.Output(\"output_box:T\")\n\t.Output(\"output_classes:int32\")\n\t.Output(\"output_index:int32\")\n\t.SetShapeFn([](shape_inference::InferenceContext* c) {\n\t\t\tc->set_output(0, c->Matrix(-1, 4));\n\t\t\tc->set_output(1, c->Vector(-1));\n\t\t\tc->set_output(2, c->Vector(-1));\n\t\t\treturn Status::OK();\n\t\t\t});\n\ntemplate <typename Device, typename T>\nclass BoxesSoftNmsOp: public OpKernel {\n    public:\n        struct InterData\n        {\n            int index;\n            float score;\n            bool operator<(const InterData& v)const {\n                return score<v.score;\n            }\n        };\n        explicit BoxesSoftNmsOp(OpKernelConstruction* context) : OpKernel(context) {\n            OP_REQUIRES_OK(context, context->GetAttr(\"threshold\", &threshold));\n            OP_REQUIRES_OK(context, context->GetAttr(\"classes_wise\", &classes_wise));\n            OP_REQUIRES_OK(context, context->GetAttr(\"delta\", &delta));\n        }\n\n        void Compute(OpKernelContext* context) override\n        {\n            TIME_THIS();\n            const Tensor &bottom_box          = context->input(0);\n            const Tensor &bottom_classes      = context->input(1);\n            const Tensor &confidence          = context->input(2);\n            auto          bottom_box_flat     = bottom_box.flat<T>();\n            auto          bottom_classes_flat = bottom_classes.flat<int32>();\n            auto          confidence_flat     = confidence.flat<float>();\n\n            OP_REQUIRES(context, bottom_box.dims() == 2, errors::InvalidArgument(\"box data must be 2-dimensional\"));\n            OP_REQUIRES(context, bottom_classes.dims() == 1, errors::InvalidArgument(\"classes data must be 1-dimensional\"));\n            OP_REQUIRES(context, confidence.dims() == 1, errors::InvalidArgument(\"confidence data must be 1-dimensional\"));\n\n            const auto   data_nr           = bottom_box.dim_size(0);\n            vector<InterData> set_D(data_nr,InterData({0,0.0f}));\n            vector<InterData> set_B;\n            const auto   loop_end          = data_nr-1;\n\n            for(auto i=0; i<data_nr; ++i) {\n                set_D[i].index = i;\n                set_D[i].score = confidence_flat.data()[i];\n            }\n            set_B.reserve(data_nr);\n\n            for(auto i=0; i<data_nr; ++i) {\n                auto it = max_element(set_D.begin(),set_D.end());\n                if(it->score<threshold)\n                    break;\n                auto M = *it;\n                set_D.erase(it);\n                set_B.push_back(M);\n                const auto index = M.index;\n                const auto iclass = bottom_classes_flat(index);\n                for(auto& data:set_D) {\n                    const auto j = data.index;\n                    if(classes_wise && (bottom_classes_flat(j) != iclass)) continue;\n                    const auto iou = bboxes_jaccard(bottom_box_flat.data()+index*4,bottom_box_flat.data()+j*4);\n                    if(iou>1e-2)\n                        data.score *= exp(-iou*iou/delta);\n                }\n            }\n            sort(set_B.begin(),set_B.end(),[](const InterData& lhv, const InterData& rhv){ return lhv.index<rhv.index;});\n            const auto out_size = set_B.size();\n            int dims_2d[2] = {int(out_size),4};\n            int dims_1d[1] = {int(out_size)};\n            TensorShape  outshape0;\n            TensorShape  outshape1;\n            Tensor      *output_box         = NULL;\n            Tensor      *output_classes     = NULL;\n            Tensor      *output_index = NULL;\n\n            TensorShapeUtils::MakeShape(dims_2d, 2, &outshape0);\n            TensorShapeUtils::MakeShape(dims_1d, 1, &outshape1);\n\n            OP_REQUIRES_OK(context, context->allocate_output(0, outshape0, &output_box));\n            OP_REQUIRES_OK(context, context->allocate_output(1, outshape1, &output_classes));\n            OP_REQUIRES_OK(context, context->allocate_output(2, outshape1, &output_index));\n\n            auto obox     = output_box->template flat<T>();\n            auto oclasses = output_classes->template flat<int32>();\n            auto oindex   = output_index->template flat<int32>();\n\n            for(auto j=0; j<out_size; ++j) {\n                const auto i = set_B[j].index;\n                auto box = bottom_box_flat.data()+i*4;\n                std::copy(box,box+4,obox.data()+4*j);\n                oclasses(j) = bottom_classes_flat(i);\n                oindex(j) = i;\n            }\n        }\n    private:\n        float threshold    = 0.2;\n        float delta        = 2.0;\n        bool  classes_wise = true;\n};\nREGISTER_KERNEL_BUILDER(Name(\"BoxesSoftNms\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), BoxesSoftNmsOp<CPUDevice, float>);\n/*\n * 与BoxesNms的主要区别为BoxesNmsNr使用输出人数来进行处理\n * 要求数据已经按重要呈度从0到data_nr排好了序(从大到小）\n * bottom_box:[X,4](ymin,xmin,ymax,xmax)\n * classes:[X]\n * output_box:[Y,4]\n * output_classes:[Y]\n * output_indices:[X]\n * 输出时的相对位置不能改变\n * 程序会自动改变threshold的方式来使输出box的数量为k个\n */\nREGISTER_OP(\"BoxesNmsNr\")\n    .Attr(\"T: {float, double,int32}\")\n\t.Attr(\"classes_wise:bool\")\n\t.Attr(\"k:int\")\n\t.Attr(\"max_loop:int\")\n    .Input(\"bottom_box: T\")\n    .Input(\"classes:int32\")\n\t.Output(\"output_box:T\")\n\t.Output(\"output_classes:int32\")\n\t.Output(\"output_index:int32\")\n\t.SetShapeFn([](shape_inference::InferenceContext* c) {\n\t\t\tint k = 0;\n\t\t\tc->GetAttr(\"k\",&k);\n\t\t\tc->set_output(0, c->Matrix(k, 4));\n\t\t\tc->set_output(1, c->Vector(k));\n\t\t\tc->set_output(2, c->Vector(k));\n\t\t\treturn Status::OK();\n\t\t\t});\n\ntemplate <typename Device, typename T>\nclass BoxesNmsNrOp: public OpKernel {\n\tpublic:\n\t\texplicit BoxesNmsNrOp(OpKernelConstruction* context) : OpKernel(context) {\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"classes_wise\", &classes_wise_));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"k\", &k_));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"max_loop\", &max_loop_));\n            if(k_ <= 0) k_ = 8;\n            if(max_loop_ <= 0) max_loop_ = 4;\n\t\t}\n\n\t\tvoid Compute(OpKernelContext* context) override\n\t\t{\n            TIME_THIS();\n\t\t\tconst Tensor &bottom_box          = context->input(0);\n\t\t\tconst Tensor &bottom_classes      = context->input(1);\n\t\t\tauto          bottom_box_flat     = bottom_box.flat<T>();\n\t\t\tauto          bottom_classes_flat = bottom_classes.flat<int32>();\n\n\t\t\tOP_REQUIRES(context, bottom_box.dims() == 2, errors::InvalidArgument(\"box data must be 2-dimensional\"));\n\t\t\tOP_REQUIRES(context, bottom_classes.dims() == 1, errors::InvalidArgument(\"classes data must be 1-dimensional\"));\n\n\t\t\tconst auto   data_nr               = bottom_box.dim_size(0);\n\t\t\tvector<bool> keep_mask(data_nr,true);\n\t\t\tvector<bool> old_keep_mask(data_nr,true);\n\t\t\tconst auto   loop_end              = data_nr-1;\n\t\t\tint          old_nr                = 0;\n\n            auto loop_fn = [&](float threshold) {\n                if(old_nr>k_)\n\t\t\t\t    std::swap(old_keep_mask,keep_mask);\n\t\t\t\tfill(keep_mask.begin(),keep_mask.end(),true);\n                auto keep_nr = keep_mask.size();\n\t\t\t\tfor(auto i=0; i<loop_end; ++i) {\n\t\t\t\t\tif(!keep_mask.at(i)) continue;\n\t\t\t\t\tconst auto iclass = bottom_classes_flat(i);\n\t\t\t\t\tfor(auto j=i+1; j<data_nr; ++j) {\n\t\t\t\t\t\tif(classes_wise_ && (bottom_classes_flat(j) != iclass)) continue;\n\t\t\t\t\t\tif(!keep_mask.at(j)) continue;\n\t\t\t\t\t\tif(bboxes_jaccard(bottom_box_flat.data()+i*4,bottom_box_flat.data()+j*4) < threshold) continue;\n\t\t\t\t\t\tkeep_mask[j] = false;\n\t\t\t\t\t\t--keep_nr;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//cout<<\"keep nr:\"<<keep_nr<<\", threshold \"<<threshold<<endl;\n\t\t\t   //keep_nr = count(keep_mask.begin(),keep_mask.end(),true);\n               return keep_nr;\n            };\n\n            auto threshold_low   = 0.0;\n            auto threshold_hight = 1.0;\n\n            for(auto i=0; i<max_loop_; ++i) {\n                auto threshold = (threshold_low+threshold_hight)/2.0;\n                auto nr = loop_fn(threshold);\n                old_nr = nr;\n                if(nr == k_) break;\n                if(nr>k_)\n                    threshold_hight = threshold;\n                else\n                    threshold_low = threshold;\n            }\n\n\t\t\tauto out_size = count(keep_mask.begin(),keep_mask.end(),true);\n\n            if(k_>data_nr) k_ = data_nr;\n\n            if(out_size<k_) {\n                auto delta = k_-out_size;\n                for(auto it=keep_mask.begin(); it!=keep_mask.end(); ++it) \n                    if((*it) == false) {\n                        (*it) = true;\n                        --delta;\n                        if(0 == delta) break;\n                    }\n                out_size = count(keep_mask.begin(),keep_mask.end(),true);\n            } else if(out_size>k_) {\n                auto nr = out_size-k_;\n                for(auto it = keep_mask.rbegin(); it!=keep_mask.rend(); ++it) {\n                    if((*it) == true) {\n                        *it = false;\n                        --nr;\n                        if(0 == nr) break;\n                    }\n                }\n            }\n            out_size = k_;\n\n\t\t\tint dims_2d[2] = {int(out_size),4};\n\t\t\tint dims_1d[1] = {int(out_size)};\n\t\t\tTensorShape  outshape0;\n\t\t\tTensorShape  outshape1;\n\t\t\tTensor      *output_box         = NULL;\n\t\t\tTensor      *output_classes     = NULL;\n\t\t\tTensor      *output_index = NULL;\n\n\t\t\tTensorShapeUtils::MakeShape(dims_2d, 2, &outshape0);\n\t\t\tTensorShapeUtils::MakeShape(dims_1d, 1, &outshape1);\n\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(0, outshape0, &output_box));\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(1, outshape1, &output_classes));\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(2, outshape1, &output_index));\n\n\t\t\tauto obox     = output_box->template flat<T>();\n\t\t\tauto oclasses = output_classes->template flat<int32>();\n\t\t\tauto oindex   = output_index->template flat<int32>();\n\t\t\tint  j        = 0;\n\t\t\tint  i        = 0;\n\n\t\t\tfor(i=0,j=0; i<data_nr; ++i) {\n\t\t\t\tif(!keep_mask[i]) continue;\n\t\t\t\tauto box = bottom_box_flat.data()+i*4;\n\t\t\t\tstd::copy(box,box+4,obox.data()+4*j);\n\t\t\t\toclasses(j) = bottom_classes_flat(i);\n\t\t\t\toindex(j) = i;\n\t\t\t\t++j;\n\t\t\t\tif(j>=out_size) break;\n\t\t\t}\n            if(j<out_size) {\n\t\t\t\tcout<<\"out size = \"<<out_size<<\", in size = \"<<data_nr<<\", j= \"<<j<<std::endl;\n                auto i = data_nr-1;\n                for(;j<out_size; ++j) {\n                    auto box = bottom_box_flat.data()+i*4;\n                    std::copy(box,box+4,obox.data()+4*j);\n                    oclasses(j) = bottom_classes_flat(i);\n                    oindex(j) = i;\n                }\n            }\n\t\t}\n\tprivate:\n\t\tbool  classes_wise_ = true;\n\t\tint   k_            = 0;\n\t\tint   max_loop_     = 4;\n};\nREGISTER_KERNEL_BUILDER(Name(\"BoxesNmsNr\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), BoxesNmsNrOp<CPUDevice, float>);\n/*\n * 与BoxesNmsNr的主要区别, 使用输入的theshold进行处理，选靠前的nr个boxes, 如果NMS后没有足够的boxes部分被删除的boxes会重新加入进来\n * 要求数据已经按重要呈度从0到data_nr排好了序(从大到小）\n * bottom_box:[X,4](ymin,xmin,ymax,xmax)\n * classes:[X]\n * threshold: 第一次处理时使用的阀值，与普通NMS中阀值的用法一致\n * fast_mode: True, 表示结果中box较少时，会简单的从前到后添加已经标记为删除的box, 否则会使用一种启发式的方式添加（规则类似于soft-nms)\n * output_box:[Y,4]\n * output_classes:[Y]\n * output_indices:[X]\n * 输出时的相对位置不能改变\n * 程序会自动改变threshold的方式来使输出box的数量为k个\n */\nREGISTER_OP(\"BoxesNmsNr2\")\n    .Attr(\"T: {float, double,int32}\")\n\t.Attr(\"classes_wise:bool\")\n\t.Attr(\"k:int\")\n\t.Attr(\"threshold:float\")\n\t.Attr(\"fast_mode:bool\")\n\t.Attr(\"allow_less_output:bool=False\")\n    .Input(\"bottom_box: T\")\n    .Input(\"classes:int32\")\n    .Input(\"confidence:T\")\n\t.Output(\"output_box:T\")\n\t.Output(\"output_classes:int32\")\n\t.Output(\"output_index:int32\")\n\t.SetShapeFn([](shape_inference::InferenceContext* c) {\n\t\t\tint k = 0;\n            bool allow_less_output = false;\n\t\t\tc->GetAttr(\"k\",&k);\n\t\t\tc->GetAttr(\"allow_less_output\",&allow_less_output);\n            if(allow_less_output) {\n\t\t\tc->set_output(0, c->Matrix(-1, 4));\n\t\t\tc->set_output(1, c->Vector(-1));\n\t\t\tc->set_output(2, c->Vector(-1));\n            } else {\n\t\t\tc->set_output(0, c->Matrix(k, 4));\n\t\t\tc->set_output(1, c->Vector(k));\n\t\t\tc->set_output(2, c->Vector(k));\n            }\n\t\t\treturn Status::OK();\n\t\t\t});\n\ntemplate <typename Device, typename T>\nclass BoxesNmsNr2Op: public OpKernel {\n    private:\n        struct InterData\n        {\n            InterData(int i,float s):index(i),score(s){}\n            int index;\n            float score;\n            bool operator<(const InterData& v)const {\n                return score<v.score;\n            }\n        };\n\tpublic:\n\t\texplicit BoxesNmsNr2Op(OpKernelConstruction* context) : OpKernel(context) {\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"classes_wise\", &classes_wise_));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"threshold\", &threshold_));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"fast_mode\", &fast_mode_));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"k\", &k_));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"allow_less_output\", &allow_less_output_));\n            if(k_ <= 0) k_ = 1;\n\t\t}\n\n\t\tvoid Compute(OpKernelContext* context) override\n\t\t{\n            TIME_THISV1(\"NmsNr2\");\n\t\t\tconst Tensor &bottom_box          = context->input(0);\n\t\t\tconst Tensor &bottom_classes      = context->input(1);\n\t\t\tconst Tensor &confidence          = context->input(2);\n\t\t\tauto          bottom_box_flat     = bottom_box.flat<T>().data();\n\t\t\tauto          bottom_classes_flat = bottom_classes.flat<int32>().data();\n\t\t\tauto          confidence_flat     = confidence.flat<T>();\n\n\n\t\t\tOP_REQUIRES(context, bottom_box.dims() == 2, errors::InvalidArgument(\"box data must be 2-dimensional\"));\n\t\t\tOP_REQUIRES(context, bottom_classes.dims() == 1, errors::InvalidArgument(\"classes data must be 1-dimensional\"));\n\n\t\t\tconst auto   data_nr               = bottom_box.dim_size(0);\n\t\t\tvector<bool> keep_mask(data_nr,true);\n\t\t\tconst auto   loop_end              = data_nr-1;\n\n\n            if((k_>data_nr) && (!allow_less_output_)) {\n                cout<<\"ERROR NMSNR2 input size is less than require (\"<<data_nr<<\" vs \"<<k_<<\").\"<<endl;\n            }\n\n            if(k_<data_nr){\n\t\t\t\tfor(auto i=0; i<loop_end; ++i) {\n\t\t\t\t\tif(!keep_mask.at(i)) continue;\n\t\t\t\t\tconst auto iclass = bottom_classes_flat[i];\n                    const auto src_box = bottom_box_flat+i*4;\n\t\t\t\t\tfor(auto j=i+1; j<data_nr; ++j) {\n\t\t\t\t\t\tif(classes_wise_ && (bottom_classes_flat[j] != iclass)) continue;\n\t\t\t\t\t\tif(!keep_mask[j]) continue;\n\t\t\t\t\t\tif(bboxes_jaccard(src_box,bottom_box_flat+j*4) < threshold_) continue;\n\t\t\t\t\t\tkeep_mask[j] = false;\n\t\t\t\t\t}\n\t\t\t\t}\n            };\n\t\t\tauto out_size = count(keep_mask.begin(),keep_mask.end(),true);\n\n            if(out_size<k_) {\n                if(k_<data_nr) {\n                    /*\n                     * 处理返回的box过少的情况\n                     */\n                    if(fast_mode_) {\n                        /*\n                         * 快速模式，从前往后加入已经删除的box\n                         */\n                        auto nr = k_-out_size;\n                        for(auto it = keep_mask.begin(); it!=keep_mask.end(); ++it) {\n                            if((*it) == false) {\n                                *it = true;\n                                --nr;\n                                if(0 == nr) break;\n                            }\n                        }\n                    } else {\n                        /*\n                         * 使用启发的方式添加box\n                         */\n                        auto delta = k_-out_size;\n                        vector<InterData> datas;\n                        datas.reserve((data_nr-out_size)/2);\n\n                        for(auto it=keep_mask.begin(); it!=keep_mask.end(); ++it) \n                            if((*it) == false) {\n                                auto index = std::distance(keep_mask.begin(),it);\n                                auto score = confidence_flat.data()[index];\n                                for(auto kt=keep_mask.begin(); kt != it; ++kt) {\n                                    if((*kt) == false) \n                                        continue;\n                                    auto index0 = std::distance(keep_mask.begin(),kt);\n                                    auto iou = bboxes_jaccard(bottom_box_flat+index*4,bottom_box_flat+index0*4);\n                                    score *= (1.0-iou);\n                                }\n                                datas.emplace_back(int(index),score);\n                            }\n                        for(auto x=0; x<delta; ++x) {\n                            auto jt = max_element(datas.begin(),datas.end());\n                            const auto index = jt->index;\n                            keep_mask[jt->index] = true;\n                            datas.erase(jt);\n                            for(auto jt=datas.begin(); jt!=datas.end(); ++jt) {\n                                auto index0 = jt->index;\n                                auto iou = bboxes_jaccard(bottom_box_flat+index*4,bottom_box_flat+index0*4);\n                                jt->score *= (1.0-iou);\n                            }\n                        }\n                    }\n                    out_size = k_;\n                } else if(allow_less_output_)  {\n                    out_size = data_nr;\n                }\n            } else if(out_size>k_) {\n              /*\n               * 如果返回的box过多，简单的从后往前删除多余的box\n               */\n                auto nr = out_size-k_;\n                for(auto it = keep_mask.rbegin(); it!=keep_mask.rend(); ++it) {\n                    if((*it) == true) {\n                        *it = false;\n                        --nr;\n                        if(0 == nr) break;\n                    }\n                }\n                out_size = k_;\n            }\n\n\t\t\tint dims_2d[2] = {int(out_size),4};\n\t\t\tint dims_1d[1] = {int(out_size)};\n\t\t\tTensorShape  outshape0;\n\t\t\tTensorShape  outshape1;\n\t\t\tTensor      *output_box         = NULL;\n\t\t\tTensor      *output_classes     = NULL;\n\t\t\tTensor      *output_index = NULL;\n\n\t\t\tTensorShapeUtils::MakeShape(dims_2d, 2, &outshape0);\n\t\t\tTensorShapeUtils::MakeShape(dims_1d, 1, &outshape1);\n\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(0, outshape0, &output_box));\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(1, outshape1, &output_classes));\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(2, outshape1, &output_index));\n\n\t\t\tauto obox     = output_box->template flat<T>();\n\t\t\tauto oclasses = output_classes->template flat<int32>();\n\t\t\tauto oindex   = output_index->template flat<int32>();\n\t\t\tint  j        = 0;\n\t\t\tint  i        = 0;\n\n            obox.setZero();\n            oindex.setZero();\n            oclasses.setZero();\n\n\t\t\tfor(i=0,j=0; i<data_nr; ++i) {\n\t\t\t\tif(!keep_mask[i]) continue;\n\t\t\t\tauto box = bottom_box_flat+i*4;\n\t\t\t\tstd::copy(box,box+4,obox.data()+4*j);\n\t\t\t\toclasses(j) = bottom_classes_flat[i];\n\t\t\t\toindex(j) = i;\n\t\t\t\t++j;\n\t\t\t\tif(j>=out_size) break;\n\t\t\t}\n            /*\n            if(j<out_size) {\n\t\t\t\tcout<<\"out size = \"<<out_size<<\", in size = \"<<data_nr<<\", j= \"<<j<<std::endl;\n                auto i = data_nr-1;\n                for(;j<out_size; ++j) {\n                    auto box = bottom_box_flat+i*4;\n                    std::copy(box,box+4,obox.data()+4*j);\n                    oclasses(j) = bottom_classes_flat[i];\n                    oindex(j) = i;\n                }\n            }\n            */\n\t\t}\n\tprivate:\n\t\tbool  classes_wise_      = true;\n\t\tfloat threshold_         = 0.0;\n\t\tint   k_                 = 0;\n\t\tbool  fast_mode_         = false;\n\t\tbool  allow_less_output_ = false;\n};\nREGISTER_KERNEL_BUILDER(Name(\"BoxesNmsNr2\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), BoxesNmsNr2Op<CPUDevice, float>);\n/*\n * 要求数据已经按重要呈度从0到data_nr排好了序(从大到小）\n * 用于处理目标不会重叠的情况\n * bottom_box:[X,4](ymin,xmin,ymax,xmax)\n * classes:[X]\n * output_box:[Y,4]\n * output_classes:[Y]\n * output_index:[Y]\n * 输出时的相对位置不能改变\n */\nREGISTER_OP(\"NoOverlapBoxesNms\")\n    .Attr(\"T: {float, double,int32}\")\n\t.Attr(\"threshold0:float\")\n\t.Attr(\"threshold1:float\")\n\t.Attr(\"classes_wise:bool\")\n    .Input(\"bottom_box: T\")\n    .Input(\"classes: int32\")\n\t.Output(\"output_box:T\")\n\t.Output(\"output_classes:int32\")\n\t.Output(\"output_index:int32\")\n\t.SetShapeFn([](shape_inference::InferenceContext* c) {\n\t\t\tc->set_output(0, c->Matrix(-1, 4));\n\t\t\tc->set_output(1, c->Vector(-1));\n\t\t\tc->set_output(2, c->Vector(-1));\n\t\t\treturn Status::OK();\n\t\t\t});\n\ntemplate <typename Device, typename T>\nclass NoOverlapBoxesNmsOp: public OpKernel {\n\tpublic:\n\t\texplicit NoOverlapBoxesNmsOp(OpKernelConstruction* context) : OpKernel(context) {\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"threshold0\", &threshold0));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"threshold1\", &threshold1));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"classes_wise\", &classes_wise));\n\t\t}\n\n\t\tvoid Compute(OpKernelContext* context) override\n\t\t{\n            TIME_THIS();\n\t\t\tconst Tensor &bottom_box          = context->input(0);\n\t\t\tconst Tensor &bottom_classes      = context->input(1);\n\t\t\tauto          bottom_box_flat     = bottom_box.flat<T>();\n\t\t\tauto          bottom_classes_flat = bottom_classes.flat<int32>();\n\n\t\t\tOP_REQUIRES(context, bottom_box.dims() == 2, errors::InvalidArgument(\"box data must be 2-dimensional\"));\n\t\t\tOP_REQUIRES(context, bottom_classes.dims() == 1, errors::InvalidArgument(\"classes data must be 1-dimensional\"));\n\n\t\t\tconst auto   data_nr           = bottom_box.dim_size(0);\n\t\t\tvector<bool> keep_mask(data_nr,true);\n\t\t\tconst auto   loop_end          = data_nr-1;\n\n\t\t\tfor(auto i=0; i<loop_end; ++i) {\n\t\t\t\tif(keep_mask[i]) {\n\t\t\t\t\tconst auto iclass = bottom_classes_flat(i);\n                    for(auto j=i+1; j<data_nr; ++j) {\n                        if(classes_wise && (bottom_classes_flat(j) != iclass)) continue;\n                        if((bboxes_jaccard(bottom_box_flat.data()+i*4,bottom_box_flat.data()+j*4) < threshold0)\n                                && (bboxes_jaccard_of_box0(bottom_box_flat.data()+i*4,bottom_box_flat.data()+j*4)<threshold1)\n                                && (bboxes_jaccard_of_box0(bottom_box_flat.data()+j*4,bottom_box_flat.data()+i*4)<threshold1)\n                          ) continue;\n                        keep_mask[j] = false;\n                    }\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst auto out_size = count(keep_mask.begin(),keep_mask.end(),true);\n\t\t\tint dims_2d[2] = {int(out_size),4};\n\t\t\tint dims_1d[1] = {int(out_size)};\n\t\t\tTensorShape  outshape0;\n\t\t\tTensorShape  outshape1;\n\t\t\tTensor      *output_box         = NULL;\n\t\t\tTensor      *output_classes     = NULL;\n\t\t\tTensor      *output_index = NULL;\n\n\t\t\tTensorShapeUtils::MakeShape(dims_2d, 2, &outshape0);\n\t\t\tTensorShapeUtils::MakeShape(dims_1d, 1, &outshape1);\n\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(0, outshape0, &output_box));\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(1, outshape1, &output_classes));\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(2, outshape1, &output_index));\n\n\t\t\tauto obox     = output_box->template flat<T>();\n\t\t\tauto oclasses = output_classes->template flat<int32>();\n\t\t\tauto oindex   = output_index->template flat<int32>();\n\n\t\t\tfor(int i=0,j=0; i<data_nr; ++i) {\n\t\t\t\tif(!keep_mask[i]) continue;\n\t\t\t\tauto box = bottom_box_flat.data()+i*4;\n\t\t\t\tstd::copy(box,box+4,obox.data()+4*j);\n\t\t\t\toclasses(j) = bottom_classes_flat(i);\n\t\t\t\toindex(j) = i;\n\t\t\t\t++j;\n\t\t\t}\n\t\t}\n\tprivate:\n\t\tfloat threshold0    = 0.2;\n\t\tfloat threshold1    = 0.8;\n\t\tbool  classes_wise = true;\n};\nREGISTER_KERNEL_BUILDER(Name(\"NoOverlapBoxesNms\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), NoOverlapBoxesNmsOp<CPUDevice, float>);\n", "meta": {"hexsha": "5224f827af190a12d94ee616c15eb444396ad8bd", "size": 31706, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tfop/nms.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/nms.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/nms.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": 37.5663507109, "max_line_length": 136, "alphanum_fraction": 0.5797956223, "num_tokens": 8685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.2677790645914627}}
{"text": "// Copyright 2004 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#ifndef BOOST_GRAPH_ERDOS_RENYI_GENERATOR_HPP\n#define BOOST_GRAPH_ERDOS_RENYI_GENERATOR_HPP\n\n#include <iterator>\n#include <utility>\n#include <boost/random/uniform_int.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/type_traits/is_base_and_derived.hpp>\n#include <boost/type_traits/is_same.hpp>\n\nnamespace boost {\n\n  template<typename RandomGenerator, typename Graph>\n  class erdos_renyi_iterator\n  {\n    typedef typename graph_traits<Graph>::directed_category directed_category;\n    typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;\n    typedef typename graph_traits<Graph>::edges_size_type edges_size_type;\n\n    BOOST_STATIC_CONSTANT\n      (bool,\n       is_undirected = (is_base_and_derived<undirected_tag,\n                                            directed_category>::value\n                        || is_same<undirected_tag, directed_category>::value));\n\n  public:\n    typedef std::input_iterator_tag iterator_category;\n    typedef std::pair<vertices_size_type, vertices_size_type> value_type;\n    typedef const value_type& reference;\n    typedef const value_type* pointer;\n    typedef void difference_type;\n\n    erdos_renyi_iterator() : gen(0), n(0), edges(0), allow_self_loops(false) {}\n    erdos_renyi_iterator(RandomGenerator& gen, vertices_size_type n, \n                         double prob = 0.0, bool allow_self_loops = false)\n      : gen(&gen), n(n), edges(edges_size_type(prob * n * n)),\n        allow_self_loops(allow_self_loops)\n    { \n      if (is_undirected) edges = edges / 2;\n      next(); \n    }\n\n    reference operator*() const { return current; }\n    pointer operator->() const { return &current; }\n    \n    erdos_renyi_iterator& operator++()\n    { \n      --edges;\n      next();\n      return *this;\n    }\n\n    erdos_renyi_iterator operator++(int)\n    {\n      erdos_renyi_iterator temp(*this);\n      ++(*this);\n      return temp;\n    }\n\n    bool operator==(const erdos_renyi_iterator& other) const\n    { return edges == other.edges; }\n\n    bool operator!=(const erdos_renyi_iterator& other) const\n    { return !(*this == other); }\n\n  private:\n    void next()\n    {\n      uniform_int<vertices_size_type> rand_vertex(0, n-1);\n      current.first = rand_vertex(*gen);\n      do {\n        current.second = rand_vertex(*gen);\n      } while (current.first == current.second && !allow_self_loops);\n    }\n\n    RandomGenerator* gen;\n    vertices_size_type n;\n    edges_size_type edges;\n    bool allow_self_loops;\n    value_type current;\n  };\n\n} // end namespace boost\n\n#endif // BOOST_GRAPH_ERDOS_RENYI_GENERATOR_HPP\n", "meta": {"hexsha": "7d2250705f7992aed5e0a512f0dad6661b8aab44", "size": 2868, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "applications/physbam/physbam-lib/External_Libraries/Archives/boost/boost/graph/erdos_renyi_generator.hpp", "max_stars_repo_name": "schinmayee/nimbus", "max_stars_repo_head_hexsha": "170cd15e24a7a88243a6ea80aabadc0fc0e6e177", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2017-07-03T19:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T02:53:56.000Z", "max_issues_repo_path": "applications/physbam/physbam-lib/External_Libraries/Archives/boost/boost/graph/erdos_renyi_generator.hpp", "max_issues_repo_name": "schinmayee/nimbus", "max_issues_repo_head_hexsha": "170cd15e24a7a88243a6ea80aabadc0fc0e6e177", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/physbam/physbam-lib/External_Libraries/Archives/boost/boost/graph/erdos_renyi_generator.hpp", "max_forks_repo_name": "schinmayee/nimbus", "max_forks_repo_head_hexsha": "170cd15e24a7a88243a6ea80aabadc0fc0e6e177", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-09-17T02:05:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-31T00:12:01.000Z", "avg_line_length": 30.5106382979, "max_line_length": 80, "alphanum_fraction": 0.6844490934, "num_tokens": 686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2677775868026067}}
{"text": "#include \"stdafx.h\"\n#include <sstream>\n#include <fstream>\n#include <ostream>\n#include <filesystem>\n#include \"PersistenceBarcodes.h\"\n#include \"../TopoUtils_D64/StringUtils.h\"\n\n#include <boost/iostreams/device/file.hpp>\n#include <boost/iostreams/stream.hpp>\n#include <boost/foreach.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/algorithm/string/regex.hpp>\n\nnamespace NPersistenceUtils {\n    namespace fs = std::experimental::filesystem;\n\n    template <typename Dtype>\n    CPersistenceBarcodes<Dtype>::~CPersistenceBarcodes() {\n    };\n\n    template <typename Dtype>\n    CPersistenceBarcodes<Dtype>::CPersistenceBarcodes(const std::wstring filename,\n        const SHoleParam<Dtype> rprms, const SKerParam<Dtype> kprms) {\n        auto dim = rprms.dim;\n        auto valInfty = rprms.valInf;\n        auto skipInfty = rprms.skipInf;\n        auto threshold = rprms.threshold;\n\n        auto single_tau = kprms.single_tau;\n        auto max_tau    = kprms.max_tau;\n\t\tauto interval = kprms.interval;\n\n        //std::cout << \"Filename = \" << NStringUtil::_w2s(filename) << std::endl;\n        std::wifstream read_op;\n        read_op.open(NStringUtil::_w2s(filename));\n        if (!read_op.good()) {\n            return;\n        }\n        else {\n            while (read_op.good()) {\n                std::wstring line;\n                std::getline(read_op, line);\n\n                if (line.size()) {\n                    std::wstringstream s;\n                    std::wstring wbirth, wdeath, wtau;\n                    s << line;\n                    s >> wbirth;\n                    s >> wdeath;\n                    s >> wtau;\n\n                    Dtype birth, death, tau;\n                    if (typeid(Dtype) == typeid(double)) {\n                        birth = _wtof(wbirth.c_str());\n                        death = _wtof(wdeath.c_str());\n                        tau   = _wtof(wtau.c_str());\n                    }\n                    else {\n                        birth = (float) _wtof(wbirth.c_str());\n                        death = (float) _wtof(wdeath.c_str());\n                        tau   = (float) _wtof(wtau.c_str());\n                    }\n                    \n                    // read with specified tau\n                    if (max_tau > 0 && tau > max_tau)\n                        break;\n                    if (single_tau >= 0 && single_tau != tau)\n                        continue;\n\t\t\t\t\tif (interval >= 2.0 && tau > 1.0 && ((int)(tau) % (int)(interval) != 0))\n\t\t\t\t\t\tcontinue;\n                    if (skipInfty && death == std::numeric_limits<Dtype>::infinity()) {\n                        continue;\n                    }\n                    if (death == std::numeric_limits<Dtype>::infinity()) {\n                        death = std::max(birth, valInfty);\n                    }\n                    if (abs(death - birth) <= threshold) continue;\n                    PushBar(birth, death, tau);\n                }\n                else {\n                    break;\n                }\n            }\n        }\n        read_op.close();\n        //std::cout << \"Number of holes \" << m_barcodes.size() << std::endl;\n        m_dim = static_cast<size_t>(dim);\n        m_filesrc = filename;\n    }\n\n    template <typename Dtype>\n    CPersistenceBarcodes<Dtype>::CPersistenceBarcodes(const std::wstring filename,\n        const SHoleParam<Dtype> rprms) {\n        const SKerParam<Dtype> kprms(-1.0, 0.0, 1.0);\n        CPersistenceBarcodes<Dtype>(filename, rprms, kprms);\n    }\n\n    template <typename Dtype>\n    std::vector<Dtype> CPersistenceBarcodes<Dtype>::births() {\n        std::vector<Dtype> birth_vecs;\n        for (auto bar : m_barcodes) birth_vecs.push_back(bar->birth);\n        return birth_vecs;\n    }\n\n    template <typename Dtype>\n    std::vector<Dtype> CPersistenceBarcodes<Dtype>::deaths() {\n        std::vector<Dtype> death_vecs;\n        for (auto bar : m_barcodes) death_vecs.push_back(bar->death);\n        return death_vecs;\n    }\n\n    template<typename Dtype>\n    std::wstring CPersistenceBarcodes<Dtype>::ToFile(const std::wstring outpath, const std::wstring fileInitial)\n    {\n        namespace io = boost::iostreams;\n\n        std::wstring outfile = outpath + L\"/barcode_\" + fileInitial + L\"_dim_\" + std::to_wstring(dim()) + L\".txt\";\n        io::stream_buffer<io::file_sink> buf(NStringUtil::_w2s(outfile));\n        std::ostream out(&buf);\n        for (auto bar : m_barcodes) {\n            out << bar->birth << \" \" << bar->death << std::endl;\n        }\n        return outfile;\n    }\n\n    // Get the median of an unordered set of numbers of arbitrary \n    // type without modifying the underlying dataset.\n    template <typename It>\n    auto GetMedian(It begin, It end)\n    {\n        using T = typename std::iterator_traits<It>::value_type;\n        std::vector<T> data(begin, end);\n        std::nth_element(data.begin(), data.begin() + data.size() / 2, data.end());\n        return data[data.size() / 2];\n    }\n\n    template<typename Dtype>\n    Dtype CPersistenceBarcodes<Dtype>::GetOptimalTimeHole()\n    {\n        std::vector<Dtype> dis_diffs;\n        Dtype tHole = Dtype(0.0);\n        auto n = m_barcodes.size();\n        for (size_t i = 0; i < n; ++i) {\n            auto bar1 = m_barcodes[i];\n            for (size_t j = i + 1; j < n; ++j) {\n                auto bar2 = m_barcodes[j];\n                auto xdiff = bar1->birth - bar2->birth;\n                auto ydiff = bar1->death - bar2->death;\n                dis_diffs.push_back(xdiff * xdiff + ydiff * ydiff);\n            }\n        }\n        if (dis_diffs.empty() == false) {\n            tHole = GetMedian(dis_diffs.begin(), dis_diffs.end());\n        }\n        return tHole;\n    }\n\n    template PersistenceUtils_D64_API struct SHoleParam<float>;\n    template PersistenceUtils_D64_API struct SHoleParam<double>;\n\n    template PersistenceUtils_D64_API struct SKerParam<float>;\n    template PersistenceUtils_D64_API struct SKerParam<double>;\n\n    template PersistenceUtils_D64_API class CPersistenceBarcodes<float>;\n    template PersistenceUtils_D64_API class CPersistenceBarcodes<double>;\n}\n\nnamespace NPersistenceUtils {\n    PersistenceUtils_D64_API bool dummy_func()\n    {\n        return true;\n    }\n\n    template <typename Dtype>\n    bool MakeDiagramVecFromBarcodesFile(TypeBarcodesPtrVec<Dtype> &diagram_vec,\n        const std::wstring barlist_filename, const SHoleParam<Dtype> rprms, const SKerParam<Dtype> kprms) {\n        // Read parameters from file\n        std::wifstream read_op;\n        read_op.open(barlist_filename);\n        if (!read_op.good()) {\n            return false;\n        }\n        else {\n            while (read_op.good()) {\n                std::wstring line;\n                std::getline(read_op, line);\n\n                if (!line.empty()) {\n                    std::wstring bar_path = L\"\";\n                    fs::path bpath(line);\n                    if (fs::is_regular_file(bpath) == false) {\n                        fs::path barlist_path(barlist_filename);\n                        bpath = barlist_path.remove_filename() / bpath;\n                        if (fs::is_regular_file(bpath)) bar_path = bpath.c_str();\n                        else continue;\n                    }\n                    else {\n                        bar_path = line;\n                    }\n                    //std::cout << \"Line = \" << NStringUtil::_w2s(line) << std::endl;\n                    //std::cout << \"barlist = \" << NStringUtil::_w2s(barlist_filename) << std::endl;\n                    //std::cout << \"Barpath = \" << NStringUtil::_w2s(bar_path) << std::endl;\n                    CPersistenceBarcodesPtr<Dtype> bar_ptr(new CPersistenceBarcodes<Dtype>(bar_path, rprms, kprms));\n                    diagram_vec.push_back(bar_ptr);\n                }\n            }\n        }\n        read_op.close();\n        return true;\n    }\n\n    template <typename Dtype>\n    PersistenceUtils_D64_API bool MakeDiagramVec(TypeBarcodesPtrVec<Dtype>& diagram_vec,\n        const std::wstring barcodes_path,\n        const SHoleParam<Dtype> rprms, const SKerParam<Dtype> kprms) {\n        fs::path input_path(barcodes_path);\n\n        if (fs::is_directory(input_path)) {\n            // find barcode files in folder\n            fs::directory_iterator it(input_path), eod;\n            BOOST_FOREACH(fs::path const &p, std::make_pair(it, eod)) {\n                if (fs::is_regular_file(p)) {\n                    CPersistenceBarcodesPtr<Dtype> bar_ptr(new CPersistenceBarcodes<Dtype>(p.c_str(), rprms));\n                    if (bar_ptr->IsEmpty() == false) {\n                        diagram_vec.push_back(bar_ptr);\n                    }\n                }\n            }\n        }\n        else if (fs::is_regular_file(input_path)) {\n            MakeDiagramVecFromBarcodesFile(diagram_vec, barcodes_path, rprms, kprms);\n        }\n        else {\n            return false;\n        }\n        return true;\n    }\n}", "meta": {"hexsha": "03be49537fef07f3144adc32a167391f22195d01", "size": 8854, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ph-compute/ScaleVariantTopo/PersistenceUtils_D64/PersistenceBarcodes.cpp", "max_stars_repo_name": "OminiaVincit/scale-variant-topo", "max_stars_repo_head_hexsha": "6945bc42aacd0d71a6fb472c87e09da223821e1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-11-09T21:59:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-22T19:02:10.000Z", "max_issues_repo_path": "ph-compute/ScaleVariantTopo/PersistenceUtils_D64/PersistenceBarcodes.cpp", "max_issues_repo_name": "OminiaVincit/scale-variant-topo", "max_issues_repo_head_hexsha": "6945bc42aacd0d71a6fb472c87e09da223821e1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ph-compute/ScaleVariantTopo/PersistenceUtils_D64/PersistenceBarcodes.cpp", "max_forks_repo_name": "OminiaVincit/scale-variant-topo", "max_forks_repo_head_hexsha": "6945bc42aacd0d71a6fb472c87e09da223821e1e", "max_forks_repo_licenses": ["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.0460251046, "max_line_length": 116, "alphanum_fraction": 0.540320759, "num_tokens": 2065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.26777758680260666}}
{"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/Norm/PAlphaSL10.h\"\n#include \"latbuilder/WeightsDispatcher.h\"\n#include \"latbuilder/Util.h\"\n\n#include \"latticetester/CoordinateSets.h\"\n\n#include <boost/math/special_functions/zeta.hpp>\n#include <vector>\n#include <cmath>\n\nnamespace LatBuilder { namespace Norm {\n\nnamespace SumHelperPAlphaSL10{\n\n   template <typename WEIGHTS>\n   struct SumHelper {\n      Real operator()(\n            const WEIGHTS& weights,\n            Real normType,\n            Real z,\n            Real lambda,\n            Dimension dimension\n            ) const\n      {\n         std::cerr << \"warning: using default implementation of SumHelper\" << std::endl;\n         Real val = 0.0;\n         LatticeTester::CoordinateSets::FromRanges csets(1, dimension, 0, dimension - 1);\n         for (const auto& proj : csets) {\n            Real weight = weights.getWeight(proj);\n            if (weight)\n               // weights are assumed to already be to the power normType; map\n               // them to power 2\n               val += intPow(z, proj.size()) * std::pow(weight, lambda * 2 / normType);\n         }\n         return val;\n      }\n   };\n\n\n#define DECLARE_PALPHA_SL10_SUM(weight_type) \\\n      template <> \\\n      class SumHelper<weight_type> { \\\n      public: \\\n         Real operator()( \\\n               const weight_type& weights, \\\n               Real normType, \\\n               Real z, \\\n               Real lambda, \\\n               Dimension dimension \\\n               ) const; \\\n      }\n\n   DECLARE_PALPHA_SL10_SUM(LatticeTester::ProjectionDependentWeights);\n   DECLARE_PALPHA_SL10_SUM(LatticeTester::OrderDependentWeights);\n   DECLARE_PALPHA_SL10_SUM(LatticeTester::ProductWeights);\n   DECLARE_PALPHA_SL10_SUM(LatticeTester::PODWeights);\n   DECLARE_PALPHA_SL10_SUM(LatBuilder::CombinedWeights);\n\n#undef DECLARE_PALPHA_SL10_SUM\n\n   //===========================================================================\n   // combined weights\n   //===========================================================================\n\n   // Separating sumCombined() from\n   // SumHelper<LatBuilder::CombinedWeights>::operator() is a workaround for\n   // LLVM/clang++.\n   Real sumCombined(\n         const CombinedWeights& weights,\n         Real normType,\n         Real z,\n         Real lambda,\n         Dimension dimension\n         )\n   {\n      Real val = 0.0;\n      for (const auto& w : weights.list())\n         val += WeightsDispatcher::dispatch<SumHelper>(*w, normType, z, lambda * 2 / normType, dimension);\n      return val;\n   }\n\n   Real SumHelper<LatBuilder::CombinedWeights>::operator()(\n         const CombinedWeights& weights,\n         Real normType,\n         Real z,\n         Real lambda,\n         Dimension dimension\n         ) const\n   {\n      return sumCombined(weights, normType, z, lambda, dimension);\n   }\n\n\n   //===========================================================================\n   // projection-dependent weights\n   //===========================================================================\n\n   Real SumHelper<LatticeTester::ProjectionDependentWeights>::operator()(\n         const LatticeTester::ProjectionDependentWeights& weights,\n         Real normType,\n         Real z,\n         Real lambda,\n         Dimension dimension\n         ) const\n   {\n      Real val = 0.0;\n      for (Dimension largestIndex = 0; largestIndex < dimension; largestIndex++) {\n         // iterate only through projections that have a weight\n         for (const auto& pw : weights.getWeightsForLargestIndex(largestIndex)) {\n            const auto& proj = pw.first;\n            const auto& weight = pw.second;\n            if (weight)\n               // weights are assumed to already be to the power normType; map\n               // them to power 2\n               val += intPow(z, proj.size()) * pow(weight, lambda * 2 / normType);\n         }\n      }\n      return val;\n   }\n\n\n   //===========================================================================\n   // order-dependent weights\n   //===========================================================================\n\n   Real SumHelper<LatticeTester::OrderDependentWeights>::operator()(\n         const LatticeTester::OrderDependentWeights& weights,\n         Real normType,\n         Real z,\n         Real lambda,\n         Dimension dimension\n         ) const\n   {\n      Real val = 0.0;\n      Real cumul = 1.0;\n      for (Dimension order = 1; order <= dimension; order++) {\n         Real weight = weights.getWeightForOrder(order);\n         cumul *= (dimension - order + 1) * z / order;\n         if (weight)\n               // weights are assumed to already be to the power normType; map\n               // them to power 2\n            val += cumul * std::pow(weight, lambda * 2 / normType);\n      }\n      return val;\n   }\n\n\n   //===========================================================================\n   // product weights\n   //===========================================================================\n\n   Real SumHelper<LatticeTester::ProductWeights>::operator()(\n         const LatticeTester::ProductWeights& weights,\n         Real normType,\n         Real z,\n         Real lambda,\n         Dimension dimension\n         ) const\n   {\n      Real val = 1.0;\n      for (Dimension coord = 0; coord < dimension; coord++) {\n         Real weight = weights.getWeightForCoordinate(coord);\n         if (weight)\n               // weights are assumed to already be to the power normType; map\n               // them to power 2\n            val *= 1.0 + z * std::pow(weight, lambda * 2 / normType);\n      }\n      val -= 1.0;\n      return val;\n   }\n\n\n   //===========================================================================\n   // POD weights\n   //===========================================================================\n\n   Real SumHelper<LatticeTester::PODWeights>::operator()(\n         const LatticeTester::PODWeights& weights,\n         Real normType,\n         Real z,\n         Real lambda,\n         Dimension dimension\n         ) const\n   {\n      // compute states\n      std::vector<Real> states;\n      states.push_back(1.0);\n      for (Dimension s = 1; s <= dimension; s++) {\n         // weights are assumed to already be to the power normType; map\n         // them to power 2\n         Real pweight = std::pow(weights.getProductWeights().getWeightForCoordinate(s), lambda * 2 / normType);\n         states.push_back(0.0);\n         for (Dimension order = states.size() - 1; order > 0; order--)\n            states[order] += z * pweight * states[order - 1];\n      }\n      Real val = 0.0;\n      for (Dimension order = 1; order <= dimension; order++)\n         // weights are assumed to already be to the power normType; map\n         // them to power 2\n         val += std::pow(weights.getOrderDependentWeights().getWeightForOrder(order), lambda * 2 / normType) * states[order];\n      return val;\n   }\n\n}\n\nPAlphaSL10::PAlphaSL10(unsigned int alpha, const LatticeTester::Weights& weights, Real normType):\n   NormAlphaBase<PAlphaSL10>(alpha, normType),\n   m_weights(weights)\n{}\n\ntemplate <LatticeType LR, EmbeddingType L>\nReal PAlphaSL10::value(\n      Real lambda,\n      const SizeParam<LR, L>& sizeParam,\n      Dimension dimension,\n      Real norm\n      ) const\n{\n   norm = 1.0 / (norm * sizeParam.totient());\n   Real z = static_cast<Real>(2 * boost::math::zeta<Real>(this->alpha() * lambda));\n   Real val = WeightsDispatcher::dispatch<SumHelperPAlphaSL10::SumHelper>(\n         m_weights,\n         this->normType(),\n         z,\n         lambda,\n         dimension\n         );\n\n   return std::pow(norm * val, 1.0 / lambda);\n}\n\ntemplate Real PAlphaSL10::value<LatticeType::ORDINARY, EmbeddingType::UNILEVEL>(Real, const SizeParam<LatticeType::ORDINARY, EmbeddingType::UNILEVEL>&, Dimension, Real) const;\ntemplate Real PAlphaSL10::value<LatticeType::ORDINARY, EmbeddingType::MULTILEVEL>(Real, const SizeParam<LatticeType::ORDINARY, EmbeddingType::MULTILEVEL>&, Dimension, Real) const;\n\ntemplate Real PAlphaSL10::value<LatticeType::POLYNOMIAL, EmbeddingType::UNILEVEL>(Real, const SizeParam<LatticeType::POLYNOMIAL, EmbeddingType::UNILEVEL>&, Dimension, Real) const;\ntemplate Real PAlphaSL10::value<LatticeType::POLYNOMIAL, EmbeddingType::MULTILEVEL>(Real, const SizeParam<LatticeType::POLYNOMIAL, EmbeddingType::MULTILEVEL>&, Dimension, Real) const;\n\n}}\n", "meta": {"hexsha": "ca597c3da83c7c0c615865a272207465ecfd78cb", "size": 8981, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/LatBuilder/Norm/PAlphaSL10.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/Norm/PAlphaSL10.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/Norm/PAlphaSL10.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": 35.2196078431, "max_line_length": 183, "alphanum_fraction": 0.568644917, "num_tokens": 2018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2677492309189948}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\r\n *    All rigths reserved\r\n *\r\n *    This file is part of the Tudat. Redistribution and use in source and\r\n *    binary forms, with or without modification, are permitted exclusively\r\n *    under the terms of the Modified BSD license. You should have received\r\n *    a copy of the license with this file. If not, please or visit:\r\n *    http://tudat.tudelft.nl/LICENSE.\r\n *\r\n */\r\n\r\n#include <boost/bind.hpp>\r\n\r\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/physicalConstants.h\"\r\n#include \"Tudat/Mathematics/Interpolators/cubicSplineInterpolator.h\"\r\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/timeConversions.h\"\r\n#include \"Tudat/Astrodynamics/EarthOrientation/precessionNutationCalculator.h\"\r\n#include \"Tudat/External/SofaInterface/sofaTimeConversions.h\"\r\n\r\nnamespace tudat\r\n{\r\n\r\nnamespace earth_orientation\r\n{\r\n\r\n//! Constructor for (CIO-based) precession-nutation calculation object.\r\nPrecessionNutationCalculator::PrecessionNutationCalculator(\r\n        basic_astrodynamics::IAUConventions precessionNutationTheory,\r\n        std::shared_ptr< interpolators::OneDimensionalInterpolator< double, Eigen::Vector2d > >\r\n        dailyCorrectionInterpolator ):\r\n    precessionNutationTheory_( precessionNutationTheory ),\r\n    dailyCorrectionInterpolator_( dailyCorrectionInterpolator )\r\n{\r\n    // Link selected SOFA function wrapper for direct calculation of precession-nutation.\r\n    nominalCipPositionFunction_ =\r\n            std::bind( sofa_interface::getPositionOfCipInGcrs,\r\n                         std::placeholders::_1, basic_astrodynamics::JULIAN_DAY_ON_J2000, precessionNutationTheory );\r\n}\r\n\r\n//! Function to calculate the position of CIP in GCRS (CIO-based precession-nutation) and CIO-locator.\r\nstd::pair< Eigen::Vector2d, double > PrecessionNutationCalculator::getPositionOfCipInGcrs(\r\n        const double terrestrialTime )\r\n{\r\n    // Calculate current UTC from SOFA.\r\n    double utc = sofa_interface::convertTTtoUTC( terrestrialTime );\r\n\r\n    // Call function to compte precession-nutation from UTC and TT.\r\n    return getPositionOfCipInGcrs( terrestrialTime, utc );\r\n}\r\n\r\n//! Function to calculate the position of CIP in GCRS (CIO-based precession-nutation) and CIO-locator.\r\nstd::pair< Eigen::Vector2d, double > PrecessionNutationCalculator::getPositionOfCipInGcrs(\r\n        const double terrestrialTime,\r\n        const double utc )\r\n{\r\n    // Calculate nominal precession-nutation values.\r\n    std::pair< Eigen::Vector2d, double > nominalCipPosition = nominalCipPositionFunction_( terrestrialTime );\r\n\r\n    // Retrieve measured corrections to model.\r\n    Eigen::Vector2d iersCorrections = dailyCorrectionInterpolator_->interpolate( utc );\r\n\r\n    // Add nominal values and corrections and return.\r\n    return std::pair< Eigen::Vector2d, double >(\r\n                nominalCipPosition.first + iersCorrections, nominalCipPosition.second );\r\n}\r\n\r\n}\r\n\r\n}\r\n", "meta": {"hexsha": "ee6ae961752aac3090efcfe8d6600afdec6479cc", "size": 2934, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/EarthOrientation/precessionNutationCalculator.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/EarthOrientation/precessionNutationCalculator.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/EarthOrientation/precessionNutationCalculator.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": 41.9142857143, "max_line_length": 118, "alphanum_fraction": 0.7413087935, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2677492309189947}}
{"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 <wx/wx.h>\n\n#include <boost/foreach.hpp>\n#include <boost/random.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <wx/filename.h>\n#include <wx/string.h>\n#include <wx/stopwatch.h>\n#include \"ShpFile.h\"\n#include \"PointSetAlgs.h\"\n#include \"GenGeomAlgs.h\"\n#include \"SpatialIndAlgs.h\"\n#include \"VarCalc/NumericTests.h\"\n#include \"GdaException.h\"\n#include \"logger.h\"\n\nusing namespace std;\n\nvoid SpatialIndAlgs::get_centroids(std::vector<pt_2d>& centroids,\n                                   const Shapefile::Main& main_data)\n{\n\tsize_t num_obs = main_data.records.size();\n\tif (centroids.size() != num_obs) centroids.resize(num_obs);\n\tif (main_data.header.shape_type == Shapefile::POINT_TYP) {\n\t\tShapefile::PointContents* pc;\n\t\tfor (size_t i=0; i<num_obs; ++i) {\n\t\t\tpc = (Shapefile::PointContents*) main_data.records[i].contents_p;\n\t\t\tif (pc->shape_type == 0) {\n\t\t\t\tcentroids[i] = pt_2d(0, 0);\n\t\t\t} else {\n\t\t\t\tcentroids[i] = pt_2d(pc->x, pc->y);\n\t\t\t}\n\t\t}\n\t} else if (main_data.header.shape_type == Shapefile::POLYGON) {\n\t\tShapefile::PolygonContents* pc;\n\t\tfor (size_t i=0; i<num_obs; ++i) {\n\t\t\tpc = (Shapefile::PolygonContents*) main_data.records[i].contents_p;\n\t\t\tGdaPolygon poly(pc);\n\t\t\tif (poly.isNull()) {\n\t\t\t\tcentroids[i] = pt_2d(0, 0);\n\t\t\t} else {\n\t\t\t\twxRealPoint rp(GdaShapeAlgs::calculateCentroid(&poly));\n\t\t\t\tcentroids[i] = pt_2d(rp.x, rp.y);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid SpatialIndAlgs::get_centroids(std::vector<pt_lonlat>& centroids,\n                                   const Shapefile::Main& main_data)\n{\n\t// Note: Boost Geometry Spherical Equatorial system uses\n\t// points in order longitude, latitude as does Shapefiles. This\n\t// is so that arc points can be plotted as-is on an x/y plane,\n\t// although doing this results in some distortion.\n\tsize_t num_obs = main_data.records.size();\n\tif (centroids.size() != num_obs)\n        centroids.resize(num_obs);\n    \n\tif (main_data.header.shape_type == Shapefile::POINT_TYP) {\n\t\tShapefile::PointContents* pc;\n\t\tfor (size_t i=0; i<num_obs; ++i) {\n\t\t\tpc = (Shapefile::PointContents*) main_data.records[i].contents_p;\n\t\t\tif (pc->shape_type == 0) {\n\t\t\t\tcentroids[i] = pt_lonlat(0, 0);\n\t\t\t} else {\n\t\t\t\tcentroids[i] = pt_lonlat(pc->x, pc->y);\n\t\t\t}\n\t\t}\n\t} else if (main_data.header.shape_type == Shapefile::POLYGON) {\n\t\tShapefile::PolygonContents* pc;\n\t\tfor (size_t i=0; i<num_obs; ++i) {\n\t\t\tpc = (Shapefile::PolygonContents*) main_data.records[i].contents_p;\n\t\t\tGdaPolygon poly(pc);\n\t\t\tif (poly.isNull()) {\n\t\t\t\tcentroids[i] = pt_lonlat(0, 0);\n\t\t\t} else {\n\t\t\t\twxRealPoint rp(GdaShapeAlgs::calculateCentroid(&poly));\n\t\t\t\tcentroids[i] = pt_lonlat(rp.x, rp.y);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid SpatialIndAlgs::to_3d_centroids(const vector<pt_2d>& pt2d,\n                                     vector<pt_3d>& pt3d)\n{\n\tsize_t obs = pt2d.size();\n\tpt3d.resize(obs);\n\tfor (size_t i=0; i<obs; ++i) {\n\t\tpt3d[i] = pt_3d(bg::get<0>(pt2d[i]), bg::get<1>(pt2d[i]), 0);\n\t}\n}\n\nvoid SpatialIndAlgs::to_3d_centroids(const vector<pt_lonlat>& ptll,\n                                     vector<pt_3d>& pt3d)\n{\n\tsize_t obs = ptll.size();\n\tpt3d.resize(obs);\n\tfor (size_t i=0; i<obs; ++i) {\n\t\tdouble x, y, z;\n\t\tGenGeomAlgs::LongLatDegToUnit(bg::get<0>(ptll[i]),\n                                      bg::get<1>(ptll[i]),\n\t\t\t\t\t\t\t\t\t  x, y, z);\n\t\tpt3d[i] = pt_3d(x, y, z);\n\t}\n}\n\nvoid SpatialIndAlgs::get_shp_bb(Shapefile::PolygonContents* p,\n                                double& xmin, double& ymin,\n                                double& xmax, double& ymax)\n{\n\tif (!p || p->num_points <= 0) {\n\t\txmin = 0; ymin = 0; xmax = 0; ymax = 0;\n\t\treturn;\n\t}\n    \n\txmin = p->points[0].x;\n\tymin = p->points[0].y;\n\txmax = p->points[0].x;\n\tymax = p->points[0].y;\n    \n\tfor (int i=0; i<p->num_points; ++i) {\n\t\tif (p->points[i].x < xmin) {\n\t\t\txmin = p->points[i].x;\n\t\t} else if (p->points[i].x > xmax) {\n\t\t\txmax = p->points[i].x;\n\t\t}\n\t\tif (p->points[i].y < ymin) {\n\t\t\tymin = p->points[i].y;\n\t\t} else if (p->points[i].y > ymax) {\n\t\t\tymax = p->points[i].y;\n\t\t}\n\t}\n}\n\nbool comp_polys(Shapefile::PolygonContents* p1,\n                Shapefile::PolygonContents* p2,\n\t\t\t\tbool rook, double prec)\n{\n\tif (!p1 || !p2)\n        return false;\n    \n\tfor (int i=0; i<p1->num_points; ++i) {\n\t\tfor (int j=0; j<p1->num_points; ++j) {\n\t\t\tif (p1->points[i] == p2->points[j])\n                return true;\n\t\t}\n\t}\n\treturn false;\n}\n\nvoid SpatialIndAlgs::default_test()\n{\n    // create the rtree using default constructor\n    rtree_box_2d_t rtree;\n\n    // create some values\n    for ( unsigned i = 0 ; i < 10 ; ++i ) {\n        // create a box\n        box_2d b(pt_2d(i + 0.0f, i + 0.0f), pt_2d(i + 0.5f, i + 0.5f));\n        // insert new value\n        rtree.insert(std::make_pair(b, i));\n    }\n\n    // find values intersecting some area defined by a box\n    box_2d query_box(pt_2d(0, 0), pt_2d(5, 5));\n    std::vector<box_2d_val> result_s;\n    rtree.query(bgi::intersects(query_box), std::back_inserter(result_s));\n\n\tconst int k=3;\n    // find k nearest values to a point\n    std::vector<box_2d_val> result_n;\n    rtree.query(bgi::nearest(pt_2d(0, 0), k), std::back_inserter(result_n));\n\n    // note: in Boost.Geometry WKT representation of a box is polygon\n\n    // display results\n\tstringstream ss;\n    ss << \"spatial query box:\" << std::endl;\n    ss << bg::wkt<box_2d>(query_box) << std::endl;\n    ss << \"spatial query result:\" << std::endl;\n    BOOST_FOREACH(box_2d_val const& v, result_s) {\n        ss << bg::wkt<box_2d>(v.first) << \" - \" << v.second << std::endl;\n\t}\n\n    ss << k << \"-nn query point:\" << std::endl;\n    ss << bg::wkt<pt_2d>(pt_2d(0, 0)) << std::endl;\n    ss << k << \"-nn query result:\" << std::endl;\n    BOOST_FOREACH(box_2d_val const& v, result_n) {\n        ss << bg::wkt<box_2d>(v.first) << \" - \" << v.second << std::endl;\n\t}\n\n\tpt_lonlat sp(0, 45);\n\tss << \"Spherical pt get<0>: \" << bg::get<0>(sp) << std::endl;\n\tss << \"Spherical pt get<1>: \" << bg::get<1>(sp) << std::endl;\n\tss << \"Spherical pt: \" << bg::wkt<pt_lonlat>(sp) << std::endl;\n\t\n\tss << \"default_test() END\";\n}\n\nvoid SpatialIndAlgs::print_rtree_stats(rtree_box_2d_t& rtree)\n{\n\tstringstream ss;\n\tss << \"Rtree stats:\" << endl;\n\tss << \"  size: \" << rtree.size() << endl;\n\tss << \"  empty?: \" << rtree.empty() << endl;\n\tbox_2d bnds = rtree.bounds();\n\tss << \"  bounds: \" << bg::wkt<box_2d>(bnds);\n}\n\nvoid SpatialIndAlgs::query_all_boxes(rtree_box_2d_t& rtree)\n{\n\tint dzero = 0;\n\tint dpos = 0;\n\tint cnt=0;\n\tbox_2d bnds = rtree.bounds();\n\t\n\tfor (rtree_box_2d_t::const_query_iterator it =\n\t\t\t rtree.qbegin(bgi::intersects(rtree.bounds()));\n\t\t it != rtree.qend() ; ++it) { ++cnt; }\n\n\tcnt = 0;\n\t\n    rtree_box_2d_t::const_query_iterator it;\n\tfor (it=rtree.qbegin(bgi::intersects(rtree.bounds())); it != rtree.qend(); ++it)\n\t{\n\t\tconst box_2d_val& v = *it;\n\t\tpt_2d c;\n\t\tboost::geometry::centroid(v.first, c);\n\t\tvector<box_2d_val> q;\n\t\trtree.query(bgi::intersects(v.first), std::back_inserter(q));\n\t\tint qcnt=0;\n\t\tBOOST_FOREACH(box_2d_val const& w, q) {\n\t\t\tif (w.second == v.second)\n                continue;\n\t\t\t++cnt;\n\t\t\t++qcnt;\n\t\t}\n\t}\n}\n\nvoid SpatialIndAlgs::knn_query(const rtree_pt_2d_t& rtree, int nn)\n{\n\tint cnt=0;\n\tbox_2d bnds = rtree.bounds();\n\n    rtree_pt_2d_t::const_query_iterator it;\n\tfor (it= rtree.qbegin(bgi::intersects(rtree.bounds())); it != rtree.qend(); ++it)\n    {\n        ++cnt;\n    }\n\n\tcnt = 0;\n\n\tconst int k=nn+1;\n\tfor (it= rtree.qbegin(bgi::intersects(rtree.bounds())); it != rtree.qend(); ++it)\n\t{\n\t\tconst pt_2d_val& v = *it;\n\t\tvector<pt_2d_val> q;\n\t\trtree.query(bgi::nearest(v.first, k), std::back_inserter(q));\n\t\tBOOST_FOREACH(pt_2d_val const& w, q) {\n            if (w.second == v.second) {\n                continue;\n            }\n\t\t\t++cnt;\n\t\t}\n\t}\n}\n\nGwtWeight* SpatialIndAlgs::knn_build(const vector<double>& x,\n                                     const vector<double>& y,\n                                     int nn, bool is_arc, bool is_mi)\n{\n\tsize_t nobs = x.size();\n\tGwtWeight* gwt = 0;\n\tif (is_arc) {\n\t\trtree_pt_3d_t rtree;\n\t\t{\n\t\t\tvector<pt_3d> pts;\n\t\t\t{\n\t\t\t\tvector<pt_lonlat> ptll(nobs);\n\t\t\t\tfor (int i=0; i<nobs; ++i) ptll[i] = pt_lonlat(x[i], y[i]);\n\t\t\t\tto_3d_centroids(ptll, pts);\n\t\t\t}\n\t\t\tfill_pt_rtree(rtree, pts);\n\t\t}\n\t\tgwt = knn_build(rtree, nn, true, is_mi);\n        \n\t} else {\n\t\trtree_pt_2d_t rtree;\n\t\t{\n\t\t\tvector<pt_2d> pts(nobs);\n\t\t\tfor (int i=0; i<nobs; ++i) pts[i] = pt_2d(x[i], y[i]);\n\t\t\tfill_pt_rtree(rtree, pts);\n\t\t}\n\t\tgwt = knn_build(rtree, nn);\n        \n\t}\n\treturn gwt;\n}\n\nGwtWeight* SpatialIndAlgs::knn_build(const rtree_pt_2d_t& rtree, int nn)\n{\n\tGwtWeight* Wp = new GwtWeight;\n\tWp->num_obs = rtree.size();\n\tWp->is_symmetric = false;\n\tWp->symmetry_checked = true;\n\tWp->gwt = new GwtElement[Wp->num_obs];\n\t\n\tint cnt=0;\n\tconst int k=nn+1;\n\tfor (rtree_pt_2d_t::const_query_iterator it =\n\t\t\t rtree.qbegin(bgi::intersects(rtree.bounds()));\n\t\t it != rtree.qend() ; ++it)\n\t{\n\t\tconst pt_2d_val& v = *it;\n\t\tsize_t obs = v.second;\t\t\n\t\tvector<pt_2d_val> q;\n\t\trtree.query(bgi::nearest(v.first, k), std::back_inserter(q));\n\t\tGwtElement& e = Wp->gwt[obs];\n\t\te.alloc(q.size());\n\t\tBOOST_FOREACH(pt_2d_val const& w, q) {\n\t\t\tif (w.second == v.second) continue;\n\t\t\tGwtNeighbor neigh;\n\t\t\tneigh.nbx = w.second;\n\t\t\tneigh.weight = bg::distance(v.first, w.first);\n\t\t\te.Push(neigh);\n\t\t\t++cnt;\n\t\t}\n\t}\n\n\treturn Wp;\n}\n\nGwtWeight* SpatialIndAlgs::knn_build(const rtree_pt_3d_t& rtree, int nn,\n\t\t\t\t\t bool is_arc, bool is_mi)\n{\n\twxStopWatch sw;\n\tusing namespace GenGeomAlgs;\n\n\tGwtWeight* Wp = new GwtWeight;\n\tWp->num_obs = rtree.size();\n\tWp->is_symmetric = false;\n\tWp->symmetry_checked = true;\n\tWp->gwt = new GwtElement[Wp->num_obs];\n\t\n\tint cnt=0;\n\tconst int k=nn+1;\n\tfor (rtree_pt_3d_t::const_query_iterator it =\n\t\t\t rtree.qbegin(bgi::intersects(rtree.bounds()));\n\t\t it != rtree.qend() ; ++it)\n\t{\n\t\tconst pt_3d_val& v = *it;\n\t\tsize_t obs = v.second;\t\t\n\t\tvector<pt_3d_val> q;\n\t\trtree.query(bgi::nearest(v.first, k), std::back_inserter(q));\n\t\tGwtElement& e = Wp->gwt[obs];\n\t\te.alloc(q.size());\n\t\tdouble lon_v, lat_v;\n\t\tdouble x_v, y_v;\n\t\tif (is_arc) {\n\t\t\tUnitToLongLatDeg(bg::get<0>(v.first), bg::get<1>(v.first),\n\t\t\t\t\t\t\t bg::get<2>(v.first), lon_v, lat_v);\n\t\t} else {\n\t\t\tx_v = bg::get<0>(v.first);\n\t\t\ty_v = bg::get<1>(v.first);\n\t\t}\n\t\tBOOST_FOREACH(pt_3d_val const& w, q) {\n\t\t\tif (w.second == v.second) continue;\n\t\t\tGwtNeighbor neigh;\n\t\t\tneigh.nbx = w.second;\n\t\t\tif (is_arc) {\n\t\t\t\tdouble lon_w, lat_w;\n\t\t\t\tUnitToLongLatDeg(bg::get<0>(w.first), bg::get<1>(w.first),\n\t\t\t\t\t\t\t\t bg::get<2>(w.first), lon_w, lat_w);\n\t\t\t\tif (is_mi) {\n\t\t\t\t\tneigh.weight = ComputeArcDistMi(lon_v, lat_v, lon_w, lat_w);\n\t\t\t\t} else {\n\t\t\t\t\tneigh.weight = ComputeArcDistKm(lon_v, lat_v, lon_w, lat_w);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t//neigh.weight = bg::distance(v.first, w.first);\n\t\t\t\tneigh.weight = ComputeEucDist(x_v, y_v,\n\t\t\t\t\t\t\t\t\t\t\t  bg::get<0>(w.first),\n                                              bg::get<1>(w.first));\n\t\t\t}\n\t\t\te.Push(neigh);\n\t\t\t++cnt;\n\t\t}\n\t}\n\n\tstringstream ss;\n\tss << \"Time to create 3D \" << (is_arc ? \" arc \" : \"\")\n\t   << nn << \"-NN GwtWeight \"\n\t   << \"with \" << cnt << \" total neighbors in ms : \" << sw.Time();\n\treturn Wp;\n}\n\n\ndouble SpatialIndAlgs::est_thresh_for_num_pairs(const rtree_pt_2d_t& rtree,\n\t\t\t\t\t\t\t\t\t\t\t\tdouble num_pairs)\n{\n\tdouble nobs_d = (double) rtree.size();\n\tif (num_pairs >= (nobs_d*(nobs_d-1.0))/2.0) {\n\t\treturn bg::distance(rtree.bounds().min_corner(), rtree.bounds().max_corner());\n\t}\n\t// Need roughly double since pairs are visited twice.\n\tdouble avg_n = (num_pairs / nobs_d)*2.0;\n\t// To avoid the use of a hash table, we just allow pairs\n\t// to be counted twice each bin is just an average. Although\n\t// distances will be calculated twice, the cost should be offset\n\t// by the faster performance of no hash table inserts / lookups.\n\tdouble thresh = est_thresh_for_avg_num_neigh(rtree, avg_n);\n\treturn thresh;\n}\n\ndouble SpatialIndAlgs::est_thresh_for_avg_num_neigh(const rtree_pt_2d_t& rtree,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdouble avg_n)\n{\n\t// Use a binary search to estimate threshold to acheive average num neighbors\n\twxStopWatch sw;\n\tusing namespace GenGeomAlgs;\n\tint max_iters = 20;\n\tint iters = 0;\n\tdouble lower = 0;\n\tdouble lower_avg = 0;\n\tbox_2d bnds(rtree.bounds());\n\tdouble upper = bg::distance(bnds.min_corner(), bnds.max_corner());\n\tdouble upper_avg = (double) rtree.size();\n\tdouble guess = upper;\n\tdouble guess_avg = upper_avg;\n\tdouble th = guess;\n\t\n\tbool was_improvement = true;\n\tfor (iters=0; iters<max_iters && was_improvement; ++iters) {\n\t\tguess = lower + (upper-lower)/2.0;\n\t\tguess_avg = est_avg_num_neigh_thresh(rtree, guess);\n\t\t{\n\t\t\tstringstream ss;\n\t\t\tss << \"\\niter: \" << iters << \"   target avg: \" << avg_n << endl;\n\t\t\tss << \"  lower: \" << lower << \", lower_avg: \" << lower_avg << endl;\n\t\t\tss << \"  guess: \" << guess << \", guess_avg: \" << guess_avg << endl;\n\t\t\tss << \"  upper: \" << upper << \", upper_avg: \" << upper_avg;\n\t\t}\n\t\tif (guess_avg == avg_n) {\n\t\t\t//LOG_MSG(\"new guess was exact!\");\n\t\t\t// this will never happen, but put case here for completeness\n\t\t\tth = guess;\n\t\t\twas_improvement = false;\n\t\t} else if (guess_avg <= lower_avg) {\n\t\t\t//LOG_MSG(\"new guess below lower bound\");\n\t\t\twas_improvement = false;\n\t\t} else if (guess_avg >= upper_avg) {\n\t\t\t//LOG_MSG(\"new guess above lower bound\");\n\t\t\twas_improvement = false;\n\t\t} else if (guess_avg < avg_n) {\n\t\t\t//LOG_MSG(\"increase lower bound\");\n\t\t\tlower = guess;\n\t\t\tlower_avg = guess_avg;\n\t\t} else { // guess_avg > avg_n\n\t\t\t//LOG_MSG(\"decrease upper bound\");\n\t\t\tupper = guess;\n\t\t\tupper_avg = guess_avg;\n\t\t}\n\t\tif (was_improvement) {\n\t\t\tth = guess;\n\t\t}\n\t}\n\n\tstringstream ss;\n\tss << \"Estimated \" << th << \" threshold for average \"\n\t   << \"number neighbors \" << avg_n << \".\" << endl;\n\tss << \"Calculation time to peform \" << iters << \" iterations: \"\n\t   << sw.Time() << \" ms.\";\n\tLOG_MSG(\"Exiting est_thresh_for_avg_num_neigh\");\n\treturn th;\n}\n\ndouble SpatialIndAlgs::est_avg_num_neigh_thresh(const rtree_pt_2d_t& rtree,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdouble th, size_t trials)\n{\n\twxStopWatch sw;\n\tusing namespace GenGeomAlgs;\n\n\tvector<pt_2d_val> query_pts;\n\trtree.query(bgi::intersects(rtree.bounds()), back_inserter(query_pts));\n\t// Mersenne Twister random number generator, randomly seeded\n\t// with current time in seconds since Jan 1 1970.\n\tstatic boost::mt19937 rng(std::time(0));\n\tstatic boost::random::uniform_int_distribution<> X(0, query_pts.size()-1);\n\tsize_t tot_neigh = 0;\n\tfor (size_t i=0; i<trials; ++i) {\n\t\tconst pt_2d_val& v = query_pts[X(rng)];\n\t\tdouble x = v.first.get<0>();\n\t\tdouble y = v.first.get<1>();\n\t\tbox_2d b(pt_2d(x-th, y-th), pt_2d(x+th, y+th));\n\t\tvector<pt_2d_val> q;\n\t\trtree.query(bgi::intersects(b), std::back_inserter(q));\n\t\tBOOST_FOREACH(const pt_2d_val& w, q) {\n\t\t\tif (w.second != v.second && bg::distance(v.first, w.first) <= th)\n\t\t\t{\n\t\t\t\t++tot_neigh;\n\t\t\t}\n\t\t}\n\t}\n\n\tdouble avg = ((double) tot_neigh) / ((double) trials);\n\n\tstringstream ss;\n\tss << \"Estimated \" << avg << \" neighbors on average for \"\n\t   << \"threshold \" << th << \".\" << endl;\n\tss << \"Time to perform \" << trials << \" random trials: \"\n\t   << sw.Time() << \" ms.\";\n\t//LOG_MSG(ss.str());\n\treturn avg;\n}\n\ndouble SpatialIndAlgs::est_mean_distance(const std::vector<double>& x,\n\t\t\t\t\t\t\t\t\t\t const std::vector<double>& y,\n\t\t\t\t\t\t\t\t\t\t bool is_arc, size_t max_iters)\n{\n\twxStopWatch sw;\n\tusing namespace GenGeomAlgs;\n\tconst size_t pts_sz = x.size();\n\tconst size_t all_pairs_sz = (pts_sz*(pts_sz-1))/2;\n\tif (x.size() != y.size() || x.size() == 0 || y.size() == 0) { return -1; }\n\tdouble sum = 0;\n\tdouble smp_cnt = 0;\n\t\n\tif (all_pairs_sz <= max_iters) {\n\t\tfor (size_t i=0; i<pts_sz; ++i) {\n\t\t\tfor (size_t j=i+1; j<pts_sz; ++j) {\n\t\t\t\tsum += (is_arc ? ComputeArcDistRad(x[i], y[i], x[j], y[j]) :\n\t\t\t\t\t\tComputeEucDist(x[i], y[i], x[j], y[j]));\n\t\t\t}\n\t\t}\n\t\tsmp_cnt = (double) all_pairs_sz;\n\t} else {\n\t\t// Mersenne Twister random number generator, randomly seeded\n\t\t// with current time in seconds since Jan 1 1970.\n\t\tstatic boost::mt19937 rng(std::time(0));\n\t\tstatic boost::random::uniform_int_distribution<> X(0, pts_sz-1);\n\t\tfor (size_t t=0; t<max_iters; ++t) {\n\t\t\tsize_t i=X(rng);\n\t\t\tsize_t j=X(rng);\n\t\t\tsum += (is_arc ? ComputeArcDistRad(x[i], y[i], x[j], y[j]) :\n\t\t\t\t\tComputeEucDist(x[i], y[i], x[j], y[j]));\n\t\t}\n\t\tsmp_cnt = max_iters;\n\t}\n\tstringstream ss;\n\tss << \"est_mean_distance finished in \" << sw.Time() << \" ms.\";\n\treturn sum/smp_cnt;\n}\n\ndouble SpatialIndAlgs::est_median_distance(const std::vector<double>& x,\n\t\t\t\t\t\t\t\t\t\t   const std::vector<double>& y,\n\t\t\t\t\t\t\t\t\t\t   bool is_arc, size_t max_iters)\n{\n\twxStopWatch sw;\n\tusing namespace GenGeomAlgs;\n\tif (x.size() != y.size() || x.size() == 0 || y.size() == 0) { return -1; }\n\tconst size_t pts_sz = x.size();\n\tconst size_t all_pairs_sz = (pts_sz*(pts_sz-1))/2;\n\tvector<double> v;\n\n\tif (all_pairs_sz <= max_iters) {\n\t\tv.resize((pts_sz*(pts_sz-1))/2);\n\t\tsize_t t=0;\n\t\tfor (size_t i=0; i<pts_sz; ++i) {\n\t\t\tfor (size_t j=i+1; j<pts_sz; ++j) {\n\t\t\t\tv[t] = (is_arc ? ComputeArcDistRad(x[i], y[i], x[j], y[j]) :\n\t\t\t\t\t\tComputeEucDist(x[i], y[i], x[j], y[j]));\n\t\t\t\t++t;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tv.resize(max_iters);\n\t\t// Mersenne Twister random number generator, randomly seeded\n\t\t// with current time in seconds since Jan 1 1970.\n\t\tstatic boost::mt19937 rng(std::time(0));\n\t\tstatic boost::random::uniform_int_distribution<> X(0, pts_sz-1);\n\t\tsize_t cnt=0;\n\t\tfor (size_t t=0; t<max_iters; ++t) {\n\t\t\tsize_t i=X(rng);\n\t\t\tsize_t j=X(rng);\n\t\t\t//if (i==j) continue;\n\t\t\tv[t] = (is_arc ? ComputeArcDistRad(x[i], y[i], x[j], y[j]) :\n\t\t\t\t\tComputeEucDist(x[i], y[i], x[j], y[j]));\n\t\t\tif (!Gda::is_finite(v[t]) || Gda::is_nan(v[t])) {\n\t\t\t\tstringstream ss;\n\t\t\t\tss << \"d(i=\"<<i<<\",j=\"<<j<<\"): \"<<v[t];\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\tsort(v.begin(), v.end());\n\tstringstream ss;\n\tss << \"est_median_distance finished in \" << sw.Time() << \" ms.\";\n\treturn v[v.size()/2];\n}\n\nGwtWeight* SpatialIndAlgs::thresh_build(const std::vector<double>& x,\n                                        const std::vector<double>& y,\n                                        double th, bool is_arc, bool is_mi)\n{\n\tusing namespace GenGeomAlgs;\n\tsize_t nobs = x.size();\n\tGwtWeight* gwt = 0;\n\tif (is_arc) {\n\t\tdouble r_th = is_mi ? EarthMiToRad(th) : EarthKmToRad(th);\n\t\tdouble u_th = RadToUnitDist(r_th);\n\t\trtree_pt_3d_t rtree;\n\t\t{\n\t\t\tvector<pt_3d> pts;\n\t\t\t{\n\t\t\t\tvector<pt_lonlat> ptll(nobs);\n\t\t\t\tfor (int i=0; i<nobs; ++i) ptll[i] = pt_lonlat(x[i], y[i]);\n\t\t\t\tto_3d_centroids(ptll, pts);\n\t\t\t}\n\t\t\tfill_pt_rtree(rtree, pts);\n\t\t}\n\t\tgwt = thresh_build(rtree, u_th, is_mi);\n\t} else {\n\t\trtree_pt_2d_t rtree;\n\t\t{\n\t\t\tvector<pt_2d> pts(nobs);\n            for (int i=0; i<nobs; ++i) {\n                pts[i] = pt_2d(x[i], y[i]);\n            }\n\t\t\tfill_pt_rtree(rtree, pts);\n\t\t}\n\t\tgwt = thresh_build(rtree, th);\n\t}\n\treturn gwt;\n}\n\nGwtWeight* SpatialIndAlgs::thresh_build(const rtree_pt_2d_t& rtree, double th)\n{\n\twxStopWatch sw;\n    \n\tGwtWeight* Wp = new GwtWeight;\n\tWp->num_obs = rtree.size();\n\tWp->is_symmetric = false;\n\tWp->symmetry_checked = true;\n    \n    int num_obs = Wp->num_obs;\n\tWp->gwt = new GwtElement[num_obs];\n\t\n\tint cnt=0;\n\tbool ignore_too_large_compute = false;\n    rtree_pt_2d_t::const_query_iterator it;\n\tfor (it = rtree.qbegin(bgi::intersects(rtree.bounds()));\n\t\t it != rtree.qend() ; ++it)\n\t{\n\t\tconst pt_2d_val& v = *it;\n\t\tdouble x = v.first.get<0>();\n\t\tdouble y = v.first.get<1>();\n\t\tbox_2d b(pt_2d(x-th, y-th), pt_2d(x+th, y+th));\n\t\tsize_t obs = v.second;\t\t\n\t\tvector<pt_2d_val> q;\n\t\trtree.query(bgi::intersects(b), std::back_inserter(q));\n\t\tsize_t lcnt = 0;\n\t\tlist<pt_2d_val> l;\n\t\tBOOST_FOREACH(pt_2d_val const& w, q) {\n\t\t\tif (w.second != v.second &&\n\t\t\t\tbg::distance(v.first, w.first) <= th)\n\t\t\t{\n\t\t\t\tl.push_front(w);\n\t\t\t\t++lcnt;\n\t\t\t}\n\t\t}\n        if (lcnt > 200 && ignore_too_large_compute == false) {\n            \n            wxString msg = _(\"The current threshold distance value is too large to compute. Please input a smaller distance band (which might leave some observations neighborless) or use other weights (e.g. KNN).\");\n\t\t\twxMessageDialog dlg(NULL, msg, \"Do you want to continue?\", wxYES_NO | wxYES_DEFAULT);\n\t\t\tif (dlg.ShowModal() != wxID_YES) {\n\t\t\t\t// clean up memory\n\t\t\t\tdelete Wp;\n\t\t\t\tthrow GdaException(msg.mb_str());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tignore_too_large_compute = true;\n\t\t\t}\n            \n        }\n\t\tGwtElement& e = Wp->gwt[obs];\n\t\te.alloc(lcnt);\n\t\tBOOST_FOREACH(pt_2d_val const& w, l) {\n\t\t\tGwtNeighbor neigh;\n\t\t\tneigh.nbx = w.second;\n\t\t\tneigh.weight = bg::distance(v.first, w.first);\n\t\t\te.Push(neigh);\n\t\t\t++cnt;\n\t\t}\n\t}\n\n\tstringstream ss;\n\tss << \"Time to create \" << th << \" threshold GwtWeight,\"\n\t   << endl << \"  with \" << cnt << \" total neighbors in ms : \"\n\t   << sw.Time();\n\treturn Wp;\n}\n\ndouble SpatialIndAlgs::est_avg_num_neigh_thresh(const rtree_pt_3d_t& rtree,\n\t\t\t\t\t double th,\tsize_t trials)\n{\n\twxStopWatch sw;\n\tusing namespace GenGeomAlgs;\n\n\tvector<pt_3d_val> query_pts;\n\trtree.query(bgi::intersects(rtree.bounds()), back_inserter(query_pts));\n\t// Mersenne Twister random number generator, randomly seeded\n\t// with current time in seconds since Jan 1 1970.\n\tstatic boost::mt19937 rng(std::time(0));\n\tstatic boost::random::uniform_int_distribution<> X(0, query_pts.size()-1);\n\tsize_t tot_neigh = 0;\n\tfor (size_t i=0; i<trials; ++i) {\n\t\tconst pt_3d_val& v = query_pts[X(rng)];\n\t\tdouble x = v.first.get<0>();\n\t\tdouble y = v.first.get<1>();\n\t\tdouble z = v.first.get<2>();\n\t\tbox_3d b(pt_3d(x-th, y-th, z-th), pt_3d(x+th, y+th, z+th));\n\t\tvector<pt_3d_val> q;\n\t\trtree.query(bgi::intersects(b), std::back_inserter(q));\n\t\tBOOST_FOREACH(const pt_3d_val& w, q) {\n\t\t\tif (w.second != v.second && bg::distance(v.first, w.first) <= th)\n\t\t\t{\n\t\t\t\t++tot_neigh;\n\t\t\t}\n\t\t}\n\t}\n\tdouble avg = ((double) tot_neigh) / ((double) trials);\n\tstringstream ss;\n\tss << \"Estimated \" << avg << \" neighbors on average for \"\n\t   << \"threshold \" << th << \".\" << endl;\n\tss << \"Time to perform \" << trials << \" random trials: \"\n\t   << sw.Time() << \" ms.\";\n\treturn avg;\n}\n\n/** threshold th is the radius of intersection sphere with\n  respect to the unit shpere of the 3d point rtree */\nGwtWeight* SpatialIndAlgs::thresh_build(const rtree_pt_3d_t& rtree, double th, bool is_mi)\n{\n\twxStopWatch sw;\n\tusing namespace GenGeomAlgs;\n\t\n\tGwtWeight* Wp = new GwtWeight;\n\tWp->num_obs = rtree.size();\n\tWp->is_symmetric = false;\n\tWp->symmetry_checked = true;\n\tWp->gwt = new GwtElement[Wp->num_obs];\n\t\n\t{\n\t\tstringstream ss;\n\t\tss << \"In thresh_build for unit sphere\" << endl;\n\t\tss << \"th : \" << th << endl;\n\t\tss << \"Input th (unit sphere secant distance): \" << th << endl;\n\t\tdouble r = UnitDistToRad(th);\n\t\tss << \"Input th (unit sphere rad): \" << r << endl;\n\t\tss << \"Input th (earth km): \" << EarthRadToKm(r) << endl;\n\t\tss << \"Input th (earth mi): \" << EarthRadToMi(r);\t\n\t}\n\tint cnt=0;\n\tfor (rtree_pt_3d_t::const_query_iterator it =\n\t\t\t rtree.qbegin(bgi::intersects(rtree.bounds()));\n\t\t it != rtree.qend() ; ++it)\n\t{\n\t\tconst pt_3d_val& v = *it;\n\t\tdouble vx = v.first.get<0>();\n\t\tdouble vy = v.first.get<1>();\n\t\tdouble vz = v.first.get<2>();\n\t\tdouble lon_v, lat_v;\n\t\tUnitToLongLatDeg(vx, vy, vz, lon_v, lat_v);\n\t\tbox_3d b(pt_3d(vx-th, vy-th, vz-th), pt_3d(vx+th, vy+th, vz+th));\n\t\tsize_t obs = v.second;\n\t\tvector<pt_3d_val> q;\n\t\trtree.query(bgi::intersects(b), std::back_inserter(q));\n\t\tsize_t lcnt = 0;\n\t\tlist<pt_3d_val> l;\n\t\tBOOST_FOREACH(pt_3d_val const& w, q) {\n\t\t\tif (w.second != v.second &&\n\t\t\t\tbg::distance(v.first, w.first) <= th)\n\t\t\t{\n\t\t\t\tl.push_front(w);\n\t\t\t\t++lcnt;\n\t\t\t}\n\t\t}\n\t\tGwtElement& e = Wp->gwt[obs];\n\t\te.alloc(lcnt);\n\t\tBOOST_FOREACH(pt_3d_val const& w, l) {\n\t\t\tGwtNeighbor neigh;\n\t\t\tneigh.nbx = w.second;\n\t\t\tdouble wx = w.first.get<0>();\n\t\t\tdouble wy = w.first.get<1>();\n\t\t\tdouble wz = w.first.get<2>();\n\t\t\tdouble lon_w, lat_w;\n\t\t\tdouble d;\n\t\t\tUnitToLongLatDeg(wx, wy, wz, lon_w, lat_w);\n\t\t\tif (is_mi) {\n\t\t\t\td = ComputeArcDistMi(lon_v, lat_v, lon_w, lat_w);\n\t\t\t} else {\n\t\t\t\td = ComputeArcDistKm(lon_v, lat_v, lon_w, lat_w);\n\t\t\t}\n\t\t\tneigh.weight = d;\n\t\t\te.Push(neigh);\n\t\t\t++cnt;\n\t\t}\n\t}\n\n\tstringstream ss;\n\tss << \"Time to create arc \" << th << \" threshold GwtWeight,\"\n\t   << endl << \"  with \" << cnt << \" total neighbors in ms : \"\n\t   << sw.Time();\n\treturn Wp;\n}\n\ndouble SpatialIndAlgs::find_max_1nn_dist(const std::vector<double>& x,\n                                         const std::vector<double>& y,\n                                         bool is_arc, bool is_mi)\n{\n\tusing namespace GenGeomAlgs;\n\tsize_t nobs = x.size();\n\tdouble min_d_1nn, max_d_1nn, mean_d_1nn, median_d_1nn, d;\n\tif (is_arc) {\n\t\trtree_pt_3d_t rtree;\n\t\t{\n\t\t\tvector<pt_3d> pts;\n\t\t\t{\n\t\t\t\tvector<pt_lonlat> ptll(nobs);\n\t\t\t\tfor (int i=0; i<nobs; ++i) ptll[i] = pt_lonlat(x[i], y[i]);\n\t\t\t\tto_3d_centroids(ptll, pts);\n\t\t\t}\n\t\t\tfill_pt_rtree(rtree, pts);\n\t\t}\n\t\tget_pt_rtree_stats(rtree, min_d_1nn, max_d_1nn, mean_d_1nn, median_d_1nn);\n\t\td = is_mi ? EarthRadToMi(max_d_1nn) : EarthRadToKm(max_d_1nn);\n\t} else {\n\t\trtree_pt_2d_t rtree;\n\t\t{\n\t\t\tvector<pt_2d> pts(nobs);\n\t\t\tfor (int i=0; i<nobs; ++i) pts[i] = pt_2d(x[i], y[i]);\n\t\t\tfill_pt_rtree(rtree, pts);\n\t\t}\n\t\tget_pt_rtree_stats(rtree, min_d_1nn, max_d_1nn, mean_d_1nn, median_d_1nn);\n\t\td = max_d_1nn;\n\t}\n\treturn d;\n}\n\nvoid SpatialIndAlgs::get_pt_rtree_stats(const rtree_pt_2d_t& rtree,\n                                        double& min_d_1nn, double& max_d_1nn,\n                                        double& mean_d_1nn, double& median_d_1nn)\n{\n\twxStopWatch sw;\n\tconst int k=2;\n\tsize_t obs = rtree.size();\n\tvector<double> d(obs);\n\tfor (rtree_pt_2d_t::const_query_iterator it =\n\t\t\t rtree.qbegin(bgi::intersects(rtree.bounds()));\n\t\t it != rtree.qend() ; ++it)\n\t{\n\t\tconst pt_2d_val& v = *it;\n\t\tvector<pt_2d_val> q;\n\t\trtree.query(bgi::nearest(v.first, k), std::back_inserter(q));\n\t\tBOOST_FOREACH(pt_2d_val const& w, q) {\n\t\t\tif (w.second == v.second) continue;\n\t\t\td[v.second] = bg::distance(v.first, w.first);\n\t\t}\n\t}\n\tsort(d.begin(), d.end());\n\tmin_d_1nn = d[0];\n\tmax_d_1nn = d[d.size()-1];\n\tmedian_d_1nn = d[(d.size()-1)/2];\n\tdouble s=0;\n\tfor (size_t i=0; i<obs; ++i) s += d[i];\n\tmean_d_1nn = s / (double) obs;\n\n\tstringstream ss;\n\tss << \"Euclidean points stats:\" << endl;\n\tss << \"  min_d_1nn: \" << min_d_1nn << endl;\n\tss << \"  max_d_1nn: \" << max_d_1nn << endl;\n\tss << \"  median_d_1nn: \" << median_d_1nn << endl;\n\tss << \"  mean_d_1nn: \" << mean_d_1nn << endl;\n\tss << \"  running time in ms: \" << sw.Time();\n}\n\n/** results returned in radians */\nvoid SpatialIndAlgs::get_pt_rtree_stats(const rtree_pt_3d_t& rtree,\n\t\t\t\t\t double& min_d_1nn, double& max_d_1nn,\n\t\t\t\t\t double& mean_d_1nn, double& median_d_1nn)\n{\n\twxStopWatch sw;\n\tusing namespace GenGeomAlgs;\n\tsize_t obs = rtree.size();\n\tvector<double> d(obs);\n\tfor (rtree_pt_3d_t::const_query_iterator it =\n\t\t\t rtree.qbegin(bgi::intersects(rtree.bounds()));\n\t\t it != rtree.qend() ; ++it)\n\t{\n\t\tconst pt_3d_val& v = *it;\n\t\tvector<pt_3d_val> q;\n\t\trtree.query(bgi::nearest(v.first, 2), std::back_inserter(q));\n\t\tBOOST_FOREACH(pt_3d_val const& w, q) {\n\t\t\tif (w.second == v.second) continue;\n\t\t\tdouble lonv, latv, lonw, latw;\n\t\t\tUnitToLongLatRad(v.first.get<0>(), v.first.get<1>(),\n\t\t\t\t\t\t\t v.first.get<2>(), lonv, latv);\n\t\t\tUnitToLongLatRad(w.first.get<0>(), w.first.get<1>(),\n\t\t\t\t\t\t\t w.first.get<2>(), lonw, latw);\n\t\t\td[v.second] = LonLatRadDistRad(lonv, latv, lonw, latw);\n\t\t}\n\t}\n\tsort(d.begin(), d.end());\n\tmin_d_1nn = d[0];\n\tmax_d_1nn = d[d.size()-1];\n\tmedian_d_1nn = d[(d.size()-1)/2];\n\tdouble s=0;\n\tfor (size_t i=0; i<obs; ++i) s += d[i];\n\tmean_d_1nn = s / (double) obs;\n\n\tstringstream ss;\n\tss << \"Long / Lat points stats:\" << endl;\n\tss << \"  min_d_1nn: \" << min_d_1nn << \" rad, \"\n\t   << RadToDeg(min_d_1nn) << \" deg, \"\n\t   << EarthRadToKm(min_d_1nn) << \" km, \"\n\t   << EarthRadToMi(min_d_1nn) << \" mi\" << endl;\n\tss << \"  max_d_1nn: \" << max_d_1nn << \" rad, \"\n\t   << RadToDeg(max_d_1nn) << \" deg, \"\n\t   << EarthRadToKm(max_d_1nn) << \" km, \"\n\t   << EarthRadToMi(max_d_1nn) << \" mi\" << endl;\n\tss << \"  median_d_1nn: \" << median_d_1nn << \" rad, \"\n\t   << RadToDeg(median_d_1nn) << \" deg, \"\n\t   << EarthRadToKm(median_d_1nn) << \" km, \"\n\t   << EarthRadToMi(median_d_1nn) << \" mi\" << endl;\n\tss << \"  mean_d_1nn: \" << mean_d_1nn << \" rad, \"\n\t   << RadToDeg(mean_d_1nn) << \" deg, \"\n\t   << EarthRadToKm(mean_d_1nn) << \" km, \"\n\t   << EarthRadToMi(mean_d_1nn) << \" mi\" << endl;\n\tss << \"  running time in ms: \" << sw.Time();\n}\n\nGwtWeight* SpatialIndAlgs::knn_build(const rtree_pt_lonlat_t& rtree, int nn)\n{\n\tGwtWeight* Wp = new GwtWeight;\n\tWp->num_obs = rtree.size();\n\tWp->is_symmetric = false;\n\tWp->symmetry_checked = true;\n\tWp->gwt = new GwtElement[Wp->num_obs];\n\t\n\tint cnt=0;\n\tconst int k=nn+1;\n\tfor (rtree_pt_lonlat_t::const_query_iterator it =\n\t\t\t rtree.qbegin(bgi::intersects(rtree.bounds()));\n\t\t it != rtree.qend() ; ++it)\n\t{\n\t\tconst pt_lonlat_val& v = *it;\n\t\tsize_t obs = v.second;\t\t\n\t\tvector<pt_lonlat_val> q;\n\t\trtree.query(bgi::nearest(v.first, k), std::back_inserter(q));\n\t\tGwtElement& e = Wp->gwt[obs];\n\t\te.alloc(q.size());\n\t\tBOOST_FOREACH(const pt_lonlat_val& w, q) {\n\t\t\tif (w.second == v.second) continue;\n\t\t\tGwtNeighbor neigh;\n\t\t\tneigh.nbx = w.second;\n\t\t\tneigh.weight = bg::distance(v.first, w.first);\n\t\t\te.Push(neigh);\n\t\t\t++cnt;\n\t\t}\n\t}\n\n\treturn Wp;\n}\n\nbool SpatialIndAlgs::write_gwt(const GwtWeight* W,\n\t\t\t\t\t\t\t   const wxString& _layer_name,\n\t\t\t\t\t\t\t   const wxString& ofname,\n\t\t\t\t\t\t\t   const wxString& vname,\n\t\t\t\t\t\t\t   const std::vector<wxInt64>& id_vec)  \n{\n    if (!W) {\n        return false;\n    }\n\tconst GwtElement* g = W->gwt;\n\tsize_t num_obs = W->num_obs;\n    \n    if (!g ||\n        _layer_name.IsEmpty() ||\n        ofname.IsEmpty() ||\n        id_vec.size() == 0 ||\n        num_obs != id_vec.size())\n    {\n        return false;\n    }\n\n    wxFileName gwtfn(ofname);\n    gwtfn.SetExt(\"gwt\");\n    wxString gwt_ofn(gwtfn.GetFullPath());\n    std::ofstream out;\n\tout.open(GET_ENCODED_FILENAME(gwt_ofn));\n    \n    if (!(out.is_open() && out.good())) {\n        return false;\n    }\n\n    wxString layer_name(_layer_name);\n    // if layer_name contains an empty space, the layer name should be\n    // braced with quotes \"layer name\"\n    if (layer_name.Contains(\" \")) {\n        layer_name = \"\\\"\" + layer_name + \"\\\"\";\n    }\n    \n    out << \"0\" << \" \" << num_obs << \" \" << layer_name;\n    out << \" \" << vname.mb_str() << endl;\n    \n    for (size_t i=0; i<num_obs; ++i) {\n        for (long nbr=0, sz=g[i].Size(); nbr<sz; ++nbr) {\n            GwtNeighbor current=g[i].elt(nbr);\n            double w = current.weight;\n            out << id_vec[i] << ' ' << id_vec[current.nbx];\n\t\t\tout << ' ' << setprecision(9) << w << endl;\n        }\n    }\n    return true;\n}\n\nvoid SpatialIndAlgs::fill_box_rtree(rtree_box_2d_t& rtree,\n\t\t\t\t\t\t\t\t\tconst Shapefile::Main& main_data)\n{\n\twxStopWatch sw;\n\tnamespace sf = Shapefile;\n\tsize_t obs = main_data.records.size();\n\tsf::PolygonContents* p;\n\tfor (size_t i=0; i<obs; ++i) {\n\t\tp = (sf::PolygonContents*) main_data.records[i].contents_p;\n\t\tdouble xmin, ymin, xmax, ymax;\n\t\tget_shp_bb(p, xmin, ymin, xmax, ymax);\n\t\tbox_2d b(pt_2d(xmin, ymin), pt_2d(xmax, ymax));\n\t\trtree.insert(std::make_pair(b, i));\n\t}\n}\n\nvoid SpatialIndAlgs::fill_pt_rtree(rtree_pt_2d_t& rtree,\n\t\t\t\t\t\t\t\t   const std::vector<pt_2d>& pts)\n{\n\tsize_t obs = pts.size();\n\tfor (size_t i=0; i<obs; ++i) {\n\t\trtree.insert(make_pair(pts[i], i));\n\t}\n}\n\nvoid SpatialIndAlgs::fill_pt_rtree(rtree_pt_lonlat_t& rtree,\n\t\t\t\t\t\t\t\t   const std::vector<pt_lonlat>& pts)\n{\n\tsize_t obs = pts.size();\n\tfor (size_t i=0; i<obs; ++i) {\n\t\trtree.insert(make_pair(pts[i], i));\n\t}\n}\n\nvoid SpatialIndAlgs::fill_pt_rtree(rtree_pt_3d_t& rtree,\n\t\t\t\t\t\t\t\t   const std::vector<pt_3d>& pts)\n{\n\tsize_t obs = pts.size();\n\tfor (size_t i=0; i<obs; ++i) {\n\t\trtree.insert(make_pair(pts[i], i));\n\t}\n}\n\nstd::ostream& SpatialIndAlgs::operator<< (std::ostream &out,\n\t\t\t\t\t\t  const LonLatPt& pt) {\n\tout << \"(\" << pt.lon << \",\" << pt.lat << \")\";\n    return out;\n}\n\nstd::ostream& SpatialIndAlgs::operator<< (std::ostream &out,\n\t\t\t\t\t\t\t\t\t\t  const wxRealPoint& pt) {\n\tout << \"(\" << pt.x << \",\" << pt.y << \")\";\n    return out;\n}\n\nstd::ostream& SpatialIndAlgs::operator<< (std::ostream &out, const XyzPt& pt) {\n\tout << \"(\" << pt.x << \",\" << pt.y << \",\" << pt.z << \")\";\n    return out;\n}\n\n\n", "meta": {"hexsha": "29de3f950ccc6ca739d0fa6c8ec4420f569a2ec4", "size": 32606, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SpatialIndAlgs.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": "SpatialIndAlgs.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": "SpatialIndAlgs.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.321942446, "max_line_length": 215, "alphanum_fraction": 0.6110531804, "num_tokens": 10780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.26767968108592205}}
{"text": "#include <fstream>\r\n#include <iostream>\r\n#include <sstream>\r\n#include <cmath>\r\n\r\n#include \"str_util.h\"\r\n#include \"infer.h\"\r\n#include <boost/algorithm/string.hpp>\r\n#include \"str_util.h\"\r\n\r\nusing namespace str_util;\r\n\r\nInfer::Infer(const string & type, const Pvec<double> & pz, const Pmat<double> & pw_z, int K) :\r\n    type(type), pz(pz), pw_z(pw_z), K(K)\r\n  {\r\n\t  \r\n  }\r\n\r\nPmat<double> Infer::predict(const std::vector<std::string> & docs, const std::unordered_map<std::string, int> & w2id) {\r\n\tstd::vector<Pvec<double>> predictions;\r\n\tfor (const std::string& line : docs) {\t\t\r\n    \tstd::vector<int> word_idx;\r\n    \tstd::vector<std::string> words = split(line);\r\n\t\tfor (std::string w : words) {\r\n      \t\tw = trim(w);\r\n\t\t    if (w2id.find(w) == w2id.end()) {\r\n        \t\tword_idx.push_back(0);\r\n      \t\t} else {\r\n      \t\t\tword_idx.push_back(w2id.at(w));\r\n\t\t\t}\r\n\t\t}\r\n\t\tDoc doc(word_idx);\r\n\t\tPvec<double> pz_d(K);\r\n\t\tdoc_infer(doc, pz_d);\r\n\t\tpredictions.push_back(pz_d);\r\n\t}\r\n\treturn Pmat<double>(predictions);\r\n}\r\n\r\n\r\nvoid Infer::doc_infer(const Doc& doc, Pvec<double>& pz_d) {\r\n  if (type == \"sum_b\")\r\n\tdoc_infer_sum_b(doc, pz_d);\r\n  else if (type == \"sub_w\")\r\n\tdoc_infer_sum_w(doc, pz_d);\r\n  else if (type == \"mix\")\r\n\tdoc_infer_mix(doc, pz_d);\r\n  else {\r\n\tcout << \"[Err] unkown infer type:\" << type << endl;\r\n\texit(1);\r\n  }\r\n}\r\n\r\n\r\n// p(z|d) = \\sum_b{ p(z|b)p(b|d) }\r\nvoid Infer::doc_infer_sum_b(const Doc& doc, Pvec<double>& pz_d) {\r\n  pz_d.assign(K, 0);\r\n\r\n  if (doc.size() == 1) {\r\n\t// doc is a single word, p(z|d) = p(z|w) \\propo p(z)p(w|z)\r\n\tfor (int k = 0; k < K; ++k)\r\n\t  pz_d[k] = pz[k] * pw_z[k][doc.get_w(0)];\r\n  }\r\n  else {\r\n\t// more than one words\r\n\tvector<Biterm> bs;\r\n\tdoc.gen_biterms(bs);\r\n\r\n\tint W = pw_z.cols();\r\n\tfor (int b = 0; b < bs.size(); ++b) {\r\n\t  int w1 = bs[b].get_wi();\r\n\t  int w2 = bs[b].get_wj();\r\n\r\n\t  // filter out-of-vocabulary words\r\n\t  if (w2 >= W) continue;\r\n\r\n\t  // compute p(z|b) \\propo p(w1|z)p(w2|z)p(z)\r\n\t  Pvec<double> pz_b(K);\r\n\t  for (int k = 0; k < K; ++k) {\r\n\t\tassert(pw_z[k][w1]>0 && pw_z[k][w2]>0);\r\n\t\tpz_b[k] = pz[k] * pw_z[k][w1] * pw_z[k][w2];\r\n\t  }\r\n\t  pz_b.normalize();\r\n\r\n\t  // sum for b, p(b|d) is unifrom\r\n\t  for (int k = 0; k < K; ++k)\r\n\t\tpz_d[k] += pz_b[k];\r\n\t}\r\n  }\r\n\r\n  pz_d.normalize();\r\n}\r\n\r\n// p(z|d) = \\sum_w{ p(z|w)p(w|d) }\r\nvoid Infer::doc_infer_sum_w(const Doc& doc, Pvec<double>& pz_d) {\r\n  pz_d.assign(K, 0);\r\n\r\n  int W = pw_z.cols();\r\n  const vector<int>& ws = doc.get_ws();\r\n\r\n  for (int i = 0; i < ws.size(); ++i) {\r\n\tint w = ws[i];\r\n\tif (w >= W) continue;\r\n\r\n\t// compute p(z|w) \\propo p(w|z)p(z)\r\n\tPvec<double> pz_w(K);\r\n\tfor (int k = 0; k < K; ++k)\r\n\t  pz_w[k] = pz[k] * pw_z[k][w];\r\n\r\n\tpz_w.normalize();\r\n\r\n\t// sum for b, p(b|d) is unifrom\r\n\tfor (int k = 0; k < K; ++k)\r\n\t  pz_d[k] += pz_w[k];\r\n  }\r\n  pz_d.normalize();\r\n}\r\n\r\nvoid Infer::doc_infer_mix(const Doc& doc, Pvec<double>& pz_d) {\r\n  pz_d.resize(K);\r\n  for (int k = 0; k < K; ++k)\r\n\tpz_d[k] = pz[k];\r\n\r\n  const vector<int>& ws = doc.get_ws();\r\n  int W = pw_z.cols();\r\n  for (int i = 0; i < ws.size(); ++i) {\r\n\tint w = ws[i];\r\n\tif (w >= W) continue;\r\n\r\n\tfor (int k = 0; k < K; ++k)\r\n\t  pz_d[k] *= (pw_z[k][w] * W);\r\n  }\r\n\r\n\t// sum for b, p(b|d) is unifrom\r\n  pz_d.normalize();\r\n}\r\n\r\n// compute p(z|d, w) \\proto p(w|z)p(z|d)\r\nvoid Infer::compute_pz_dw(int w, const Pvec<double>& pz_d, Pvec<double>& p) {\r\n  p.resize(K);\r\n\r\n  for (int k = 0; k < K; ++k)\r\n\tp[k] = pw_z[k][w] * pz_d[k];\r\n\r\n  p.normalize();\r\n}\r\n", "meta": {"hexsha": "0b61f600f55934fd5d54269d235e27cebc4ecb83", "size": 3438, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "btm/infer.cpp", "max_stars_repo_name": "lucianolorenti/BTM", "max_stars_repo_head_hexsha": "32bddfc972d3fda8e5f77cd9a736787c430a7027", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-12-10T08:29:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T15:50:24.000Z", "max_issues_repo_path": "btm/infer.cpp", "max_issues_repo_name": "lucianolorenti/BTM", "max_issues_repo_head_hexsha": "32bddfc972d3fda8e5f77cd9a736787c430a7027", "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": "btm/infer.cpp", "max_forks_repo_name": "lucianolorenti/BTM", "max_forks_repo_head_hexsha": "32bddfc972d3fda8e5f77cd9a736787c430a7027", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-15T12:10:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-15T12:10:51.000Z", "avg_line_length": 23.387755102, "max_line_length": 120, "alphanum_fraction": 0.5392670157, "num_tokens": 1220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.267679681085922}}
{"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_SPHERICAL_HPP\n#define BOOST_GEOMETRY_STRATEGIES_DISTANCE_SPHERICAL_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/normalize.hpp>\n#include <boost/geometry/strategies/relate/spherical.hpp>\n\n#include <boost/geometry/strategies/spherical/azimuth.hpp>\n\n#include <boost/geometry/strategies/spherical/distance_cross_track.hpp>\n#include <boost/geometry/strategies/spherical/distance_cross_track_box_box.hpp>\n#include <boost/geometry/strategies/spherical/distance_cross_track_point_box.hpp>\n#include <boost/geometry/strategies/spherical/distance_haversine.hpp>\n#include <boost/geometry/strategies/spherical/distance_segment_box.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategies { namespace distance\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\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 <typename RadiusTypeOrSphere, typename CalculationType>\nclass spherical\n    : public strategies::relate::detail::spherical<RadiusTypeOrSphere, CalculationType>\n{\n    using base_t = strategies::relate::detail::spherical<RadiusTypeOrSphere, CalculationType>;\n\npublic:\n    spherical() = default;\n\n    template <typename RadiusOrSphere>\n    explicit spherical(RadiusOrSphere const& radius_or_sphere)\n        : base_t(radius_or_sphere)\n    {}\n\n    // azimuth\n\n    static auto azimuth()\n    {\n        return strategy::azimuth::spherical<CalculationType>();\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::haversine\n                <\n                    typename base_t::radius_type, CalculationType\n                >(base_t::radius());\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::cross_track\n            <\n                CalculationType,\n                strategy::distance::haversine<typename base_t::radius_type, CalculationType>\n            >(base_t::radius());\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::cross_track_point_box\n            <\n                CalculationType,\n                strategy::distance::haversine<typename base_t::radius_type, CalculationType>\n            >(base_t::radius());\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::spherical_segment_box\n            <\n                CalculationType,\n                strategy::distance::haversine<typename base_t::radius_type, CalculationType>\n            >(base_t::radius());\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::cross_track_box_box\n            <\n                CalculationType,\n                strategy::distance::haversine<typename base_t::radius_type, CalculationType>\n            >(base_t::radius());\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\n} // namespace detail\n#endif // DOXYGEN_NO_DETAIL\n\n\ntemplate\n<\n    typename RadiusTypeOrSphere = double,\n    typename CalculationType = void\n>\nclass spherical\n    : public strategies::distance::detail::spherical<RadiusTypeOrSphere, CalculationType>\n{\n    using base_t = strategies::distance::detail::spherical<RadiusTypeOrSphere, CalculationType>;\n\npublic:\n    spherical() = default;\n\n    template <typename RadiusOrSphere>\n    explicit spherical(RadiusOrSphere const& radius_or_sphere)\n        : base_t(radius_or_sphere)\n    {}\n};\n\n\nnamespace services\n{\n\ntemplate <typename Geometry1, typename Geometry2>\nstruct default_strategy\n    <\n        Geometry1, Geometry2,\n        spherical_equatorial_tag, spherical_equatorial_tag\n    >\n{\n    using type = strategies::distance::spherical<>;\n};\n\n\ntemplate <typename R, typename CT>\nstruct strategy_converter<strategy::distance::haversine<R, CT> >\n{\n    template <typename S>\n    static auto get(S const& s)\n    {\n        return strategies::distance::spherical<R, CT>(s.radius());\n    }\n};\n\ntemplate <typename CT, typename PPS>\nstruct strategy_converter<strategy::distance::cross_track<CT, PPS> >\n    : strategy_converter<PPS>\n{};\n\ntemplate <typename CT, typename PPS>\nstruct strategy_converter<strategy::distance::cross_track_point_box<CT, PPS> >\n    : strategy_converter<PPS>\n{};\n\ntemplate <typename CT, typename PPS>\nstruct strategy_converter<strategy::distance::spherical_segment_box<CT, PPS> >\n    : strategy_converter<PPS>\n{};\n\ntemplate <typename CT, typename PPS>\nstruct strategy_converter<strategy::distance::cross_track_box_box<CT, PPS> >\n    : strategy_converter<PPS>\n{};\n\n\ntemplate <typename R, typename CT>\nstruct strategy_converter<strategy::distance::comparable::haversine<R, CT> >\n{\n    template <typename S>\n    static auto get(S const& s)\n    {\n        return strategies::distance::detail::make_comparable(\n                strategies::distance::spherical<R, CT>(s.radius()));\n    }\n};\n\ntemplate <typename CT, typename PPS>\nstruct strategy_converter<strategy::distance::comparable::cross_track<CT, PPS> >\n    : strategy_converter<PPS>\n{};\n\n\n} // namespace services\n\n}} // namespace strategies::distance\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_DISTANCE_SPHERICAL_HPP\n", "meta": {"hexsha": "f96a1e0ef7e453ba668e919e6dd9667c3a3f9022", "size": 6709, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/strategies/distance/spherical.hpp", "max_stars_repo_name": "pranavgo/RRT", "max_stars_repo_head_hexsha": "87148c3ddb91600f4e74f00ffa8af14b54689aa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "boost/geometry/strategies/distance/spherical.hpp", "max_issues_repo_name": "pranavgo/RRT", "max_issues_repo_head_hexsha": "87148c3ddb91600f4e74f00ffa8af14b54689aa4", "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": "boost/geometry/strategies/distance/spherical.hpp", "max_forks_repo_name": "pranavgo/RRT", "max_forks_repo_head_hexsha": "87148c3ddb91600f4e74f00ffa8af14b54689aa4", "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": 29.4254385965, "max_line_length": 110, "alphanum_fraction": 0.6928007155, "num_tokens": 1478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.26767739484299075}}
{"text": "//*****************************************************************************\n// Copyright 2018-2019 Intel Corporation\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//*****************************************************************************\n\n#include <algorithm>\n#include <boost/asio.hpp>\n#include <functional>\n#include <iostream>\n#include <memory>\n#include <numeric>\n#include <string>\n#include <vector>\n\n#include \"ngraph/log.hpp\"\n#include \"seal/he_seal_client.hpp\"\n#include \"seal/seal.h\"\n#include \"seal/seal_util.hpp\"\n#include \"tcp/tcp_client.hpp\"\n#include \"tcp/tcp_message.hpp\"\n\nngraph::he::HESealClient::HESealClient(const std::string& hostname,\n                                       const size_t port,\n                                       const size_t batch_size,\n                                       const std::vector<float>& inputs)\n    : m_batch_size{batch_size}, m_is_done(false), m_inputs{inputs} {\n  boost::asio::io_context io_context;\n  tcp::resolver resolver(io_context);\n  auto endpoints = resolver.resolve(hostname, std::to_string(port));\n\n  auto client_callback = [this](const ngraph::he::TCPMessage& message) {\n    return handle_message(message);\n  };\n\n  m_tcp_client = std::make_shared<ngraph::he::TCPClient>(io_context, endpoints,\n                                                         client_callback);\n\n  io_context.run();\n}\n\nvoid ngraph::he::HESealClient::set_seal_context() {\n  m_context = seal::SEALContext::Create(m_encryption_params, true,\n                                        seal::sec_level_type::none);\n\n  print_seal_context(*m_context);\n\n  m_keygen = std::make_shared<seal::KeyGenerator>(m_context);\n  m_relin_keys = std::make_shared<seal::RelinKeys>(m_keygen->relin_keys());\n  m_public_key = std::make_shared<seal::PublicKey>(m_keygen->public_key());\n  m_secret_key = std::make_shared<seal::SecretKey>(m_keygen->secret_key());\n  m_encryptor = std::make_shared<seal::Encryptor>(m_context, *m_public_key);\n  m_decryptor = std::make_shared<seal::Decryptor>(m_context, *m_secret_key);\n\n  // Evaluator\n  m_evaluator = std::make_shared<seal::Evaluator>(m_context);\n\n  // Encoder\n  m_ckks_encoder = std::make_shared<seal::CKKSEncoder>(m_context);\n\n  // TODO: pick better scale?\n  m_scale = ngraph::he::choose_scale(m_encryption_params.coeff_modulus());\n  NGRAPH_INFO << \"Client scale \" << m_scale;\n}\n\nvoid ngraph::he::HESealClient::handle_message(\n    const ngraph::he::TCPMessage& message) {\n  ngraph::he::MessageType msg_type = message.message_type();\n\n  // NGRAPH_INFO << \"Client received message type: \"\n  //          << message_type_to_string(msg_type).c_str() ;\n\n  switch (msg_type) {\n    case ngraph::he::MessageType::parameter_size: {\n      // Number of (packed) ciphertexts to perform inference on\n      size_t parameter_size;\n      std::memcpy(&parameter_size, message.data_ptr(), message.data_size());\n\n      const size_t complex_pack_factor = complex_packing() ? 2 : 1;\n\n      NGRAPH_INFO << \"Parameter size \" << parameter_size;\n      NGRAPH_INFO << \"Client batch size \" << m_batch_size;\n      if (complex_packing()) {\n        NGRAPH_INFO << \"Client complex packing\";\n        // TODO: support odd batch sizes\n        assert(m_batch_size % 2 == 0);\n      }\n\n      // TODO: allow smaller sizes!\n      if (m_inputs.size() !=\n          parameter_size * m_batch_size * complex_pack_factor) {\n        NGRAPH_INFO << \"m_inputs.size() \" << m_inputs.size()\n                    << \" != paramter_size ( \" << parameter_size\n                    << \") * m_batch_size (\" << m_batch_size\n                    << \") * complex_pack_factor (\" << complex_pack_factor\n                    << \")\";\n      }\n      NGRAPH_CHECK(m_inputs.size() ==\n                       parameter_size * m_batch_size * complex_pack_factor,\n                   \"m_inputs.size()\", m_inputs.size(), \"parameter_size\",\n                   parameter_size, \"m_batch_size\", m_batch_size,\n                   \"complex_pack_factor\", complex_pack_factor);\n\n      std::vector<seal::Ciphertext> ciphers(parameter_size);\n#pragma omp parallel for\n      for (size_t data_idx = 0; data_idx < parameter_size; ++data_idx) {\n        seal::Plaintext plain;\n\n        size_t batch_start_idx = data_idx * m_batch_size * complex_pack_factor;\n        size_t batch_end_idx =\n            batch_start_idx + m_batch_size * complex_pack_factor;\n\n        std::vector<double> real_vals{m_inputs.begin() + batch_start_idx,\n                                      m_inputs.begin() + batch_end_idx};\n        if (complex_packing()) {\n          std::vector<std::complex<double>> complex_vals;\n          real_vec_to_complex_vec(complex_vals, real_vals);\n          m_ckks_encoder->encode(complex_vals, m_scale, plain);\n        } else {\n          m_ckks_encoder->encode(real_vals, m_scale, plain);\n        }\n        m_encryptor->encrypt(plain, ciphers[data_idx]);\n      }\n      NGRAPH_INFO << \"Creating execute message\";\n      auto execute_message =\n          TCPMessage(ngraph::he::MessageType::execute, ciphers);\n      NGRAPH_INFO << \"Sending execute message with \" << parameter_size\n                  << \" ciphertexts\";\n      write_message(std::move(execute_message));\n      break;\n    }\n    case ngraph::he::MessageType::result: {\n      size_t result_count = message.count();\n      size_t element_size = message.element_size();\n\n      NGRAPH_INFO << \"Client got \" << result_count << \" results \";\n\n      std::vector<seal::Ciphertext> result;\n      m_results.reserve(result_count * m_batch_size);\n      for (size_t result_idx = 0; result_idx < result_count; ++result_idx) {\n        seal::Ciphertext cipher;\n        std::stringstream cipher_stream;\n        cipher_stream.write(message.data_ptr() + result_idx * element_size,\n                            element_size);\n        cipher.load(m_context, cipher_stream);\n\n        result.push_back(cipher);\n        seal::Plaintext plain;\n        m_decryptor->decrypt(cipher, plain);\n\n        std::vector<double> outputs;\n        decode_to_real_vec(plain, outputs, complex_packing());\n        m_results.insert(m_results.end(), outputs.begin(), outputs.end());\n      }\n      NGRAPH_INFO << \"Results size \" << m_results.size();\n\n      close_connection();\n      break;\n    }\n\n    case ngraph::he::MessageType::none: {\n      close_connection();\n      break;\n    }\n\n    case ngraph::he::MessageType::encryption_parameters: {\n      std::stringstream param_stream;\n      param_stream.write(message.data_ptr(), message.element_size());\n      m_encryption_params = seal::EncryptionParameters::Load(param_stream);\n      NGRAPH_INFO << \"Loaded encryption parmeters\";\n\n      set_seal_context();\n\n      // Send public key\n      std::stringstream pk_stream;\n      m_public_key->save(pk_stream);\n      auto pk_message = TCPMessage(ngraph::he::MessageType::public_key, 1,\n                                   std::move(pk_stream));\n      NGRAPH_INFO << \"Sending public key\";\n      write_message(std::move(pk_message));\n\n      // Send evaluation key\n      std::stringstream evk_stream;\n      m_relin_keys->save(evk_stream);\n      auto evk_message = TCPMessage(ngraph::he::MessageType::eval_key, 1,\n                                    std::move(evk_stream));\n      NGRAPH_INFO << \"Sending evaluation key\";\n      write_message(std::move(evk_message));\n\n      break;\n    }\n    case ngraph::he::MessageType::relu6_request: {\n      handle_relu_request(message);\n      break;\n    }\n    case ngraph::he::MessageType::relu_request: {\n      handle_relu_request(message);\n      break;\n    }\n\n    case ngraph::he::MessageType::max_request: {\n      size_t complex_pack_factor = complex_packing() ? 2 : 1;\n      size_t cipher_count = message.count();\n      size_t element_size = message.element_size();\n\n      std::vector<std::vector<double>> input_cipher_values(\n          m_batch_size * complex_pack_factor,\n          std::vector<double>(cipher_count, 0));\n\n      std::vector<double> max_values(m_batch_size * complex_pack_factor,\n                                     std::numeric_limits<double>::lowest());\n\n#pragma omp parallel for\n      for (size_t cipher_idx = 0; cipher_idx < cipher_count; ++cipher_idx) {\n        seal::Ciphertext pre_sort_cipher;\n        seal::Plaintext pre_sort_plain;\n\n        // Load cipher from stream\n        std::stringstream pre_sort_cipher_stream;\n        pre_sort_cipher_stream.write(\n            message.data_ptr() + cipher_idx * element_size, element_size);\n        pre_sort_cipher.load(m_context, pre_sort_cipher_stream);\n\n        // Decrypt cipher\n        m_decryptor->decrypt(pre_sort_cipher, pre_sort_plain);\n        std::vector<double> pre_max_value;\n        decode_to_real_vec(pre_sort_plain, pre_max_value, complex_packing());\n\n        for (size_t batch_idx = 0;\n             batch_idx < m_batch_size * complex_pack_factor; ++batch_idx) {\n          input_cipher_values[batch_idx][cipher_idx] = pre_max_value[batch_idx];\n        }\n      }\n\n      // Get max of each vector of values\n      for (size_t batch_idx = 0; batch_idx < m_batch_size * complex_pack_factor;\n           ++batch_idx) {\n        max_values[batch_idx] =\n            *std::max_element(input_cipher_values[batch_idx].begin(),\n                              input_cipher_values[batch_idx].end());\n      }\n\n      // Encrypt maximum values\n      seal::Ciphertext cipher_max;\n      seal::Plaintext plain_max;\n      std::stringstream max_stream;\n\n      if (complex_packing()) {\n        assert(max_values.size() % 2 == 0);\n        std::vector<std::complex<double>> max_complex_vals;\n        real_vec_to_complex_vec(max_complex_vals, max_values);\n        m_ckks_encoder->encode(max_complex_vals, m_scale, plain_max);\n      } else {\n        m_ckks_encoder->encode(max_values, m_scale, plain_max);\n      }\n      m_encryptor->encrypt(plain_max, cipher_max);\n      cipher_max.save(max_stream);\n\n      auto max_result_msg = TCPMessage(ngraph::he::MessageType::max_result, 1,\n                                       std::move(max_stream));\n      write_message(std::move(max_result_msg));\n\n      break;\n    }\n    case ngraph::he::MessageType::execute:\n    case ngraph::he::MessageType::max_result:\n    case ngraph::he::MessageType::minimum_request:\n    case ngraph::he::MessageType::minimum_result:\n    case ngraph::he::MessageType::parameter_shape_request:\n    case ngraph::he::MessageType::public_key:\n    case ngraph::he::MessageType::relu_result:\n    case ngraph::he::MessageType::result_request:\n    default:\n      NGRAPH_INFO << \"Unsupported message type: \"\n                  << message_type_to_string(msg_type).c_str();\n  }\n}\n\nvoid ngraph::he::HESealClient::close_connection() {\n  NGRAPH_INFO << \"Closing connection\";\n  m_tcp_client->close();\n  m_is_done = true;\n}\n\nvoid ngraph::he::HESealClient::handle_relu_request(\n    const ngraph::he::TCPMessage& message) {\n  auto relu = [=](double d) { return d > 0 ? d : 0; };\n  auto relu6 = [=](double d) { return d > 6.0 ? 6.0 : (d > 0) ? d : 0.; };\n\n  std::function<double(double)> activation;\n\n  if (message.message_type() == ngraph::he::MessageType::relu6_request) {\n    activation = relu6;\n  } else if (message.message_type() == ngraph::he::MessageType::relu_request) {\n    activation = relu;\n  } else {\n    throw ngraph_error(\"Non-relu message type in handle_relu_request\");\n  }\n\n  size_t result_count = message.count();\n  size_t element_size = message.element_size();\n  // NGRAPH_INFO << \"Received Relu request with \" << result_count << \" elements\"\n  //            << \" of size \" << element_size;\n\n  std::vector<seal::Ciphertext> post_relu_ciphers(result_count);\n#pragma omp parallel for\n  for (size_t result_idx = 0; result_idx < result_count; ++result_idx) {\n    seal::Ciphertext pre_relu_cipher;\n    seal::Plaintext relu_plain;\n\n    // Load cipher from stream\n    std::stringstream pre_relu_cipher_stream;\n    pre_relu_cipher_stream.write(message.data_ptr() + result_idx * element_size,\n                                 element_size);\n    pre_relu_cipher.load(m_context, pre_relu_cipher_stream);\n\n    // Decrypt cipher\n    m_decryptor->decrypt(pre_relu_cipher, relu_plain);\n\n    std::vector<double> relu_vals;\n    decode_to_real_vec(relu_plain, relu_vals, complex_packing());\n\n    std::vector<double> post_relu_vals(relu_vals.size());\n    std::transform(relu_vals.begin(), relu_vals.end(), post_relu_vals.begin(),\n                   activation);\n\n    if (complex_packing()) {\n      std::vector<std::complex<double>> complex_relu_vals;\n      real_vec_to_complex_vec(complex_relu_vals, post_relu_vals);\n      m_ckks_encoder->encode(complex_relu_vals, m_scale, relu_plain);\n    } else {\n      m_ckks_encoder->encode(post_relu_vals, m_scale, relu_plain);\n    }\n    m_encryptor->encrypt(relu_plain, post_relu_ciphers[result_idx]);\n  }\n  auto relu_result_msg =\n      TCPMessage(ngraph::he::MessageType::relu_result, post_relu_ciphers);\n  // NGRAPH_INFO << \"Writing relu_result message with \" << result_count\n  //            << \" ciphertexts\";\n\n  write_message(std::move(relu_result_msg));\n  return;\n}\n\nvoid ngraph::he::HESealClient::decode_to_real_vec(const seal::Plaintext& plain,\n                                                  std::vector<double>& output,\n                                                  bool complex) {\n  assert(output.size() == 0);\n  if (complex) {\n    std::vector<std::complex<double>> complex_outputs;\n    m_ckks_encoder->decode(plain, complex_outputs);\n    assert(complex_outputs.size() >= m_batch_size);\n    complex_outputs.resize(m_batch_size);\n    complex_vec_to_real_vec(output, complex_outputs);\n  } else {\n    m_ckks_encoder->decode(plain, output);\n    assert(m_batch_size <= output.size());\n    output.resize(m_batch_size);\n  }\n}\n", "meta": {"hexsha": "83d351f2927e494cb378518abfc1b829ffa9cdc5", "size": 14093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/seal/he_seal_client.cpp", "max_stars_repo_name": "lorepieri8/he-transformer", "max_stars_repo_head_hexsha": "894b2204c9f9b62519207493d13756e12268e12b", "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/seal/he_seal_client.cpp", "max_issues_repo_name": "lorepieri8/he-transformer", "max_issues_repo_head_hexsha": "894b2204c9f9b62519207493d13756e12268e12b", "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/seal/he_seal_client.cpp", "max_forks_repo_name": "lorepieri8/he-transformer", "max_forks_repo_head_hexsha": "894b2204c9f9b62519207493d13756e12268e12b", "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.9865229111, "max_line_length": 80, "alphanum_fraction": 0.6410984177, "num_tokens": 3220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2676187721427645}}
{"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#include \"SiconosConfig.h\"\n\n#include \"SiconosAlgebraTypeDef.hpp\"\n\n#include <boost/numeric/ublas/io.hpp>            // for >> \n//#include <boost/numeric/ublas/vector_proxy.hpp>  // for project\n#include <boost/numeric/ublas/vector_sparse.hpp>\n\n\n#include <boost/numeric/bindings/ublas/vector_proxy.hpp>\n#include <boost/numeric/bindings/blas.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/std/vector.hpp>\nnamespace siconosBindings = boost::numeric::bindings::blas;\n\n#include \"SimpleMatrix.hpp\"\n#include \"BlockVector.hpp\"\n#include \"ioVector.hpp\"\n#include \"SiconosVector.hpp\"\n#include \"SiconosAlgebra.hpp\"\n\n\n// Do not document\n/// @cond\n#include \"Question.hpp\"\n\nstruct IsDense : public Question<bool>\n{\n  using SiconosVisitor::visit;\n\n  void visit(const SiconosVector& v)\n  {\n    answer = v._dense;\n  }\n\n  void visit(const BlockVector& v)\n  {\n    answer = false;\n  }\n};\n\nstruct IsSparse : public Question<bool>\n{\n\n  using SiconosVisitor::visit;\n\n  void visit(const SiconosVector& v)\n  {\n    answer = !v._dense;\n  }\n\n  void visit(const BlockVector& v)\n  {\n    answer = false;\n  }\n};\n\nstruct IsBlock : public Question<bool>\n{\n  using SiconosVisitor::visit;\n\n  void visit(const SiconosVector& v)\n  {\n    answer = false;\n  }\n\n  void visit(const BlockVector& v)\n  {\n    answer = true;\n  }\n};\n\n/// @endcond\n\n\n// =================================================\n//                CONSTRUCTORS\n// =================================================\n\n// Default\nSiconosVector::SiconosVector()\n{\n  _dense = true;\n  vect.Dense = new DenseVect(ublas::zero_vector<double>());\n}\n\n// parameters: dimension and type.\nSiconosVector::SiconosVector(unsigned row, Siconos::UBLAS_TYPE type)\n{\n  if (type == Siconos::SPARSE)\n  {\n    _dense = false;\n    vect.Sparse = new SparseVect(ublas::zero_vector<double>(row));\n  }\n  else if (type == Siconos::DENSE)\n  {\n    _dense = true;\n    vect.Dense = new DenseVect(ublas::zero_vector<double>(row));\n  }\n  else\n  {\n    SiconosVectorException::selfThrow(\"SiconosVector::constructor(Siconos::UBLAS_TYPE, unsigned int) failed, invalid type given\");\n  }\n}\n\n// parameters: dimension, default value for all components and type.\nSiconosVector::SiconosVector(unsigned row, double val, Siconos::UBLAS_TYPE type)\n{\n  if (type == Siconos::SPARSE)\n  {\n    _dense = false;\n    vect.Sparse = new SparseVect(row);\n    fill(val);\n  }\n  else if (type == Siconos::DENSE)\n  {\n    _dense = true;\n    vect.Dense = new DenseVect(ublas::scalar_vector<double>(row, val));\n  }\n  else\n  {\n    SiconosVectorException::selfThrow(\"SiconosVector::constructor(Siconos::UBLAS_TYPE, unsigned int) : invalid type given\");\n  }\n}\n\n// parameters: a vector (stl) of double and the type.\nSiconosVector::SiconosVector(const std::vector<double>& v, Siconos::UBLAS_TYPE typ)\n{\n  if (typ != Siconos::DENSE)\n    SiconosVectorException::selfThrow(\"SiconosVector::constructor(Siconos::UBLAS_TYPE, std::vector<double>, unsigned int) : invalid type given\");\n\n  _dense = true;\n  vect.Dense = new DenseVect(v.size());\n  std::copy(v.begin(), v.end(), (vect.Dense)->begin());\n}\n\n// Copy\nSiconosVector::SiconosVector(const SiconosVector &svect) : std11::enable_shared_from_this<SiconosVector>()\n{\n  if (ask<IsDense>(svect)) // dense\n  {\n    _dense = true;\n    vect.Dense = new DenseVect(svect.size());\n    noalias(*vect.Dense) = (*svect.dense());\n    // std::copy((vect.Dense)->begin(), (vect.Dense)->end(), (svect.dense())->begin());\n  }\n  else //sparse\n  {\n    _dense = false;\n    vect.Sparse = new SparseVect(svect.size());\n    noalias(*vect.Sparse) = (*svect.sparse());\n    //std::copy((vect.Sparse)->begin(), (vect.Sparse)->end(), (svect.sparse())->begin());\n  }\n\n  // Note FP: using constructor + noalias = (or std::copy) is more\n  // efficient than a call to ublas::vector copy constructor, this for\n  // large or small vectors.\n}\n\n// Copy from BlockVector\nSiconosVector::SiconosVector(const BlockVector & vIn) : std11::enable_shared_from_this<SiconosVector>()\n{\n  if (ask<IsDense>(**(vIn.begin()))) // dense\n  {\n    _dense = true;\n    vect.Dense = new DenseVect(vIn.size());\n  }\n  else\n  {\n    _dense = false;\n    vect.Sparse = new SparseVect(vIn.size());\n  }\n\n  VectorOfVectors::const_iterator it;\n  unsigned int pos = 0;\n  for (it = vIn.begin(); it != vIn.end(); ++it)\n  {\n    setBlock(pos, **it);\n    pos += (*it)->size();\n  }\n\n}\n\nSiconosVector::SiconosVector(const DenseVect& m)\n{\n  _dense = true;\n  vect.Dense = new DenseVect(m.size());\n  noalias(*vect.Dense) = m;\n\n}\n\nSiconosVector::SiconosVector(const SparseVect& m)\n{\n  _dense = false;\n  vect.Sparse = new SparseVect(m.size());\n  noalias(*vect.Sparse) = m;\n}\n\nSiconosVector::SiconosVector(const std::string &file, bool ascii)\n{\n  _dense = true;\n  vect.Dense = new DenseVect();\n  if (ascii)\n  {\n    ioVector::read(file, *this, ioVector::ASCII_IN);\n   }\n  else\n  {\n    ioVector::read(file, *this, ioVector::BINARY_IN);\n  }\n}\n\nSiconosVector::SiconosVector(const SiconosVector& v1, const SiconosVector& v2)\n{\n  unsigned int size1 = v1.size();\n  if (ask<IsDense>(v1) && ask<IsDense>(v2))\n  {\n    _dense = true;\n    vect.Dense = new DenseVect(size1 + v2.size());\n  }\n  else if (ask<IsSparse>(v1) && ask<IsSparse>(v2))\n  {\n    _dense = false;\n    vect.Sparse = new SparseVect(size1 + v2.size());\n  }\n  else\n  {\n    SiconosVectorException::selfThrow(\"SiconosVector::SiconosVector :: mixed dense and sparse vector detected\");\n  }\n  setBlock(0, v1);\n  setBlock(size1, v2);\n}\n\nSiconosVector::~SiconosVector()\n{\n  if (_dense)\n    delete(vect.Dense);\n  else delete(vect.Sparse);\n}\n\n\n// =================================================\n//        get Ublas component (dense or sparse)\n// =================================================\n\nconst DenseVect SiconosVector::getDense(unsigned int) const\n{\n  if (!_dense)\n    SiconosVectorException::selfThrow(\"SiconosVector::getDense(unsigned int row, unsigned int col) : the current vector is not a Dense vector\");\n\n  return *vect.Dense;\n}\n\nconst SparseVect SiconosVector::getSparse(unsigned int)const\n{\n\n  if (_dense)\n    SiconosVectorException::selfThrow(\"SiconosVector::getSparse(unsigned int row, unsigned int col) : the current vector is not a Sparse vector\");\n\n  return *vect.Sparse;\n}\n\nSparseVect* SiconosVector::sparse(unsigned int)const\n{\n\n  if (_dense)\n    SiconosVectorException::selfThrow(\"SiconosVector::sparse(unsigned int row, unsigned int col) : the current vector is not a Sparse vector\");\n\n  return vect.Sparse;\n}\n\ndouble* SiconosVector::getArray() const\n{\n  assert(vect.Dense && \"SiconosVector::getArray() : not yet implemented for sparse vector.\");\n\n  return &(((*vect.Dense).data())[0]);\n}\n\n// ===========================\n//       fill vector\n// ===========================\n\nvoid SiconosVector::zero()\n{\n  if (_dense)\n    siconosBindings::scal(0.0, *vect.Dense);\n\n  else\n  {\n    assert(vect.Sparse);\n    *vect.Sparse *= 0.0;\n  }\n\n}\n\nvoid SiconosVector::setVector(unsigned int , const SiconosVector& newV)\n{\n  if (newV.size() != size())\n    SiconosVectorException::selfThrow(\"SiconosVector::setVector(num,v), unconsistent sizes.\");\n\n  *this = newV ;\n}\n\nvoid SiconosVector::fill(double value)\n{\n  if (!_dense)\n  {\n    for (unsigned int i = 0; i < (vect.Sparse)->size(); ++i)\n      (vect.Sparse)->push_back(i, value);\n  }\n  else\n    siconosBindings::set(value, *vect.Dense);\n\n\n}\n\n//=======================\n// set vector dimension\n//=======================\n\nvoid SiconosVector::resize(unsigned int n, bool preserve)\n{\n  if (_dense)\n    (vect.Dense)->resize(n, preserve);\n  else\n    (vect.Sparse)->resize(n, preserve);\n}\n\n//=======================\n//       get norm\n//=======================\n\ndouble SiconosVector::normInf() const\n{\n  if (_dense)\n    return norm_inf(*vect.Dense);\n  else //if(num==4)\n    return norm_inf(*vect.Sparse);\n}\n\ndouble SiconosVector::norm2() const\n{\n  if (_dense)\n    return ublas::norm_2(*vect.Dense);\n  else //if(num==4)\n    return ublas::norm_2(*vect.Sparse);\n}\n//======================================\n// get sum of all elements of the vector\n//=====================================\ndouble SiconosVector::vector_sum() const\n{\n  if (_dense)\n    return ublas::sum(*vect.Dense);\n  else\n    return ublas::sum(*vect.Sparse);\n}\n\n//=====================\n// screen display\n//=====================\n\nvoid SiconosVector::display()const\n{\n  std::cout.setf(std::ios::scientific);\n  std::cout.precision(6);\n  if (_dense)\n    std::cout << *vect.Dense << std::endl;\n  else if (vect.Sparse)\n    std::cout << *vect.Sparse << std::endl;\n}\n\n//============================\n// Convert vector to a std::string\n//============================\n\nconst std::string SiconosVector::toString() const\n{\n  std::stringstream sstr;\n  std::string s;\n  if (_dense)\n    sstr << *vect.Dense;\n  else\n    sstr << *vect.Sparse;\n  sstr >> s;\n  s = s.substr(4, s.size() - 5); // Remove \"[size](\" at the beginning of the std::string\n  std::string::size_type pos;\n  while ((pos = s.find(\",\")) != std::string::npos) // Replace \",\" by \" \" in the std::string\n    s[pos] = ' ';\n  return s;\n}\n\n//=============================\n// Elements access (get or set)\n//=============================\n\ndouble SiconosVector::getValue(unsigned int row) const\n{\n  assert(row < size() && \"SiconosVector::getValue(index) : Index out of range\");\n\n  if (_dense)\n    return (*vect.Dense)(row);\n  else\n    return (*vect.Sparse)(row);\n}\n\nvoid SiconosVector::setValue(unsigned int row, double value)\n{\n  assert(row < size() && \"SiconosVector::setValue(index, value) : Index out of range\");\n  if (_dense)\n    (*vect.Dense)(row) = value ;\n  else\n    (*vect.Sparse)(row) = value;\n}\n\ndouble& SiconosVector::operator()(unsigned int row)\n{\n  assert(row < size() && \"SiconosVector::operator ( index ): Index out of range\");\n\n  if (_dense)\n    return (*vect.Dense)(row);\n  else\n    return (*vect.Sparse)(row).ref();\n}\n\ndouble SiconosVector::operator()(unsigned int row) const\n{\n  assert(row < size() && \"SiconosVector::operator ( index ): Index out of range\");\n\n  if (_dense)\n    return (*vect.Dense)(row);\n  else\n    return ((*vect.Sparse)(row)).ref();\n}\n\n//============================================\n// Access (get or set) to blocks of elements\n//============================================\n\nvoid SiconosVector::setBlock(unsigned int index, const SiconosVector& vIn)\n{\n  // Set current vector elements, starting from position \"index\", to the values of vector vIn\n\n  // Exceptions ...\n  assert(&vIn != this && \"SiconosVector::this->setBlock(pos,vIn): vIn = this.\");\n\n  assert(index < size() && \"SiconosVector::setBlock : invalid ranges\");\n\n  unsigned int end = vIn.size() + index;\n  assert(end <= size() && \"SiconosVector::setBlock : invalid ranges\");\n\n  assert (vIn.num() == num() && \"SiconosVector::setBlock: inconsistent types.\");\n\n  if (_dense)\n    noalias(ublas::subrange(*vect.Dense, index, end)) = *vIn.dense();\n  else\n    noalias(ublas::subrange(*vect.Sparse, index, end)) = *vIn.sparse();\n}\n\nvoid SiconosVector::toBlock(SiconosVector& vOut, unsigned int sizeB, unsigned int startIn, unsigned int startOut) const\n{\n  // To copy a subBlock of the vector (from position startIn to startIn+sizeB) into vOut (from pos. startOut to startOut+sizeB).\n  // Check dim ...\n  assert(startIn < size() && \"vector toBlock(v1,v2,...): start position in input vector is out of range.\");\n\n  assert(startOut < vOut.size() && \"vector toBlock(v1,v2,...): start position in output vector is out of range.\");\n\n  assert(startIn + sizeB <= size() && \"vector toBlock(v1,v2,...): end position in input vector is out of range.\");\n  assert(startOut + sizeB <= vOut.size() && \"vector toBlock(v1,v2,...): end position in output vector is out of range.\");\n\n  unsigned int endOut = startOut + sizeB;\n  unsigned int numIn = num();\n  unsigned int numOut = vOut.num();\n\n  if (numIn == numOut)\n  {\n    if (numIn == 1) // vIn / vOut are Dense\n      noalias(ublas::subrange(*vOut.dense(), startOut, endOut)) = ublas::subrange(*vect.Dense, startIn, startIn + sizeB);\n    else // if(numIn == 4)// vIn / vOut are Sparse\n      noalias(ublas::subrange(*vOut.sparse(), startOut, endOut)) = ublas::subrange(*vect.Sparse, startIn, startIn + sizeB);\n  }\n  else // vIn and vout of different types ...\n  {\n    if (numIn == 1) // vIn Dense\n      noalias(ublas::subrange(*vOut.sparse(), startOut, endOut)) = ublas::subrange(*vect.Dense, startIn, startIn + sizeB);\n    else // if(numIn == 4)// vIn Sparse\n      noalias(ublas::subrange(*vOut.dense(), startOut, endOut)) = ublas::subrange(*vect.Sparse, startIn, startIn + sizeB);\n  }\n}\n\nvoid SiconosVector::addBlock(unsigned int index, const SiconosVector& vIn)\n{\n  // Add vIn to the current vector, starting from position \"index\".\n  // vIn may be a BlockVector.\n\n  //if ( num != 1 ) SiconosVectorException::selfThrow(\"SiconosVector::addBlock : vector should be dense\");\n\n  if (&vIn == this)\n    SiconosVectorException::selfThrow(\"SiconosVector::this->addBlock(pos,vIn): vIn = this.\");\n\n  unsigned int end = vIn.size();\n  if ((index + end) > size()) SiconosVectorException::selfThrow(\"SiconosVector::addBlock : invalid ranges\");\n\n  unsigned int numVin = vIn.num();\n\n  if (numVin != num()) SiconosVectorException::selfThrow(\"SiconosVector::addBlock : inconsistent types.\");\n\n  if (_dense)\n    noalias(ublas::subrange(*vect.Dense, index, index + end)) += *vIn.dense();\n  else\n    noalias(ublas::subrange(*vect.Sparse, index, index + end)) += *vIn.sparse();\n}\n\nvoid SiconosVector::subBlock(unsigned int index, const SiconosVector& vIn)\n{\n  // Add vIn from the current vector, starting from position \"index\".\n  // vIn may be a BlockVector.\n\n  //  if ( num != 1 ) SiconosVectorException::selfThrow(\"SiconosVector::subBlock : vector should be dense\");\n\n  unsigned int end = vIn.size();\n  if ((index + end) > size()) SiconosVectorException::selfThrow(\"SiconosVector::subBlock : invalid ranges\");\n\n  unsigned int numVin = vIn.num();\n  if (numVin != num()) SiconosVectorException::selfThrow(\"SiconosVector::subBlock : inconsistent types.\");\n\n  if (_dense)\n    noalias(ublas::subrange(*vect.Dense, index, index + end)) -= *vIn.dense();\n  else\n    noalias(ublas::subrange(*vect.Sparse, index, index + end)) -= *vIn.sparse();\n}\n\n//===============\n//  Assignment\n//===============\n\nSiconosVector& SiconosVector::operator = (const SiconosVector& vIn)\n{\n  if (&vIn == this) return *this; // auto-assignment.\n\n  assert(size() == vIn.size() && \"SiconosVector::operator = failed: inconsistent sizes.\");\n\n  unsigned int vInNum = vIn.num();\n  {\n    switch (num())\n    {\n    case 1:\n      switch (vInNum)\n      {\n      case 1:\n        //siconosBindings::copy(*vIn.dense(),*vect.Dense);\n        noalias(*vect.Dense) = *vIn.dense();\n        break;\n      case 4:\n        noalias(*vect.Dense) = *vIn.sparse();\n        break;\n      default:\n        SiconosVectorException::selfThrow(\"SiconosVector::operator = : invalid type given\");\n        break;\n      }\n      break;\n    case 4:\n      if (vInNum == 4)\n        noalias(*vect.Sparse) = *vIn.sparse();\n      else\n        SiconosVectorException::selfThrow(\"SiconosVector::operator = : can not set sparse = dense.\");\n      break;\n    default:\n      SiconosVectorException::selfThrow(\"SiconosVector::operator = : invalid type given\");\n      break;\n    }\n  }\n  return *this;\n}\n\nSiconosVector& SiconosVector::operator = (const BlockVector& vIn)\n{\n  VectorOfVectors::const_iterator it;\n  unsigned int pos = 0;\n  for (it = vIn.begin(); it != vIn.end(); ++it)\n  {\n    setBlock(pos, **it);\n    pos += (*it)->size();\n  }\n  return *this;\n}\n\n\nSiconosVector& SiconosVector::operator = (const DenseVect& d)\n{\n  if (!_dense)\n    SiconosVectorException::selfThrow(\"SiconosVector::operator = DenseVect : forbidden: the current vector is not dense.\");\n  if (d.size() != size())\n    SiconosVectorException::selfThrow(\"SiconosVector::operator = DenseVect : inconsistent size.\");\n\n  siconosBindings::copy(d, *vect.Dense);\n  return *this;\n}\n\nSiconosVector& SiconosVector::operator = (const SparseVect& sp)\n{\n  if (_dense)\n    SiconosVectorException::selfThrow(\"SiconosVector::operator = SparseVect : current vector is not sparse.\");\n  if (sp.size() != size())\n    SiconosVectorException::selfThrow(\"SiconosVector::operator = SparseVect : inconsistent size.\");\n\n  noalias(*vect.Sparse) = sp;\n\n  return *this;\n}\n\nSiconosVector& SiconosVector::operator = (const double* d)\n{\n  assert(_dense && \"SiconosVector::operator = double* : forbidden: the current vector is not dense.\");\n\n  siconosBindings::detail::copy(vect.Dense->size(), d, 1, getArray(), 1);\n  return *this;\n}\n\nunsigned SiconosVector::copyData(double* data) const\n{\n  assert(_dense && \"SiconosVector::copyData : forbidden: the current vector is not dense.\");\n\n  unsigned size = vect.Dense->size();\n  siconosBindings::detail::copy(vect.Dense->size(), getArray(), 1, data, 1);\n  return size;\n}\n\n\n//=================================\n// Op. and assignment (+=, -= ... )\n//=================================\n\nSiconosVector& SiconosVector::operator += (const SiconosVector& vIn)\n{\n  if (&vIn == this) // alias\n  {\n    // Note: using this *= 2.0 is much more time-consuming.\n    switch (num())\n    {\n    case 1:\n      *vect.Dense += *vect.Dense;\n      break;\n    case 4:\n      *vect.Sparse += *vect.Sparse;\n      break;\n    default:\n      SiconosVectorException::selfThrow(\"SiconosVector::operator += : invalid type given\");\n      break;\n    }\n    return *this;\n  }\n\n  unsigned int vInNum = vIn.num();\n  {\n    switch (num())\n    {\n    case 1:\n      switch (vInNum)\n      {\n      case 1:\n        noalias(*vect.Dense) += *vIn.dense();\n        break;\n      case 4:\n        noalias(*vect.Dense) += *vIn.sparse();\n        break;\n      default:\n        SiconosVectorException::selfThrow(\"SiconosVector::operator += : invalid type given\");\n        break;\n      }\n      break;\n    case 4:\n      if (vInNum == 4)\n        noalias(*vect.Sparse) += *vIn.sparse();\n      else SiconosVectorException::selfThrow(\"SiconosVector::operator += : can not add a dense to a sparse.\");\n      break;\n    default:\n      SiconosVectorException::selfThrow(\"SiconosVector::operator += : invalid type given\");\n      break;\n    }\n  }\n  return *this;\n}\nSiconosVector& SiconosVector::operator += (const BlockVector& vIn)\n{\n  VectorOfVectors::const_iterator it;\n  unsigned int pos = 0;\n  for (it = vIn.begin(); it != vIn.end(); ++it)\n  {\n    addBlock(pos, **it);\n    pos += (*it)->size();\n  }\n  return *this;\n}\n\nSiconosVector& SiconosVector::operator -= (const SiconosVector& vIn)\n{\n  if (&vIn == this)\n  {\n    this->zero();\n    return *this;\n  }\n\n  unsigned int vInNum = vIn.num();\n  {\n    switch (num())\n    {\n    case 1:\n      switch (vInNum)\n      {\n      case 1:\n        noalias(*vect.Dense) -= *vIn.dense();\n        break;\n      case 4:\n        noalias(*vect.Dense) -= *vIn.sparse();\n        break;\n      default:\n        SiconosVectorException::selfThrow(\"SiconosVector::operator -= : invalid type given\");\n        break;\n      }\n      break;\n    case 4:\n      if (vInNum == 4)\n        noalias(*vect.Sparse) -= *vIn.sparse();\n      else SiconosVectorException::selfThrow(\"SiconosVector::operator -= : can not sub a dense to a sparse.\");\n      break;\n    default:\n      SiconosVectorException::selfThrow(\"SiconosVector::operator -= : invalid type given\");\n      break;\n    }\n  }\n  return *this;\n}\n\nSiconosVector& SiconosVector::operator -= (const BlockVector& vIn)\n{\n  VectorOfVectors::const_iterator it;\n  unsigned int pos = 0;\n  for (it = vIn.begin(); it != vIn.end(); ++it)\n  {\n    subBlock(pos, **it);\n    pos += (*it)->size();\n  }\n  return *this;\n}\n\n\n//===============\n// Comparison\n//===============\n\nbool operator == (const SiconosVector &m, const SiconosVector &x)\n{\n  return ((m - x).norm2() < std::numeric_limits<double>::epsilon());\n}\n\n//==================\n// y = scalar * x\n//==================\n\nSiconosVector operator * (const  SiconosVector&m, double d)\n{\n  unsigned int numM = m.num();\n\n  if (numM == 1)\n  {\n    // Copy m into p and call siconosBindings::scal(d,p), p = d*p.\n    DenseVect p = *m.dense();\n    siconosBindings::scal(d, p);\n    return p;\n  }\n  else// if(numM==4)\n  {\n    return (SparseVect)(*m.sparse() * d);\n  }\n}\n\nSiconosVector operator * (double d, const  SiconosVector&m)\n{\n  unsigned int numM = m.num();\n\n  if (numM == 1)\n  {\n    // Copy m into p and call siconosBindings::scal(d,p), p = d*p.\n    DenseVect p = *m.dense();\n    siconosBindings::scal(d, p);\n    return p;\n  }\n  else// if(numM==4)\n  {\n    return (SparseVect)(*m.sparse() * d);\n  }\n}\n\nSiconosVector operator / (const SiconosVector &m, double d)\n{\n  unsigned int numM = m.num();\n\n  if (numM == 1)\n  {\n    DenseVect p = *m.dense();\n    siconosBindings::scal((1.0 / d), p);\n    return p;\n  }\n\n  else// if(numM==4){\n    return (SparseVect)(*m.sparse() / d);\n}\n\n//====================\n//  Vectors addition\n//====================\n\nSiconosVector operator + (const  SiconosVector& x, const  SiconosVector& y)\n{\n  if (x.size() != y.size())\n    SiconosVectorException::selfThrow(\"SiconosVector, x + y: inconsistent sizes\");\n\n  unsigned int numX = x.num();\n  unsigned int numY = y.num();\n\n  if (numX == numY) // x, y SiconosVector of the same type\n  {\n    if (numX == 1)\n    {\n      //    siconosBindings::xpy(*x.dense(),p);\n      //    return p;\n      return (DenseVect)(*x.dense() + *y.dense());\n    }\n    else\n      return (SparseVect)(*x.sparse() + *y.sparse());\n  }\n\n  else // x, y SiconosVector with y and x of different types\n  {\n    if (numX == 1)\n      return (DenseVect)(*x.dense() + *y.sparse());\n    else\n      return (DenseVect)(*x.sparse() + *y.dense());\n  }\n\n}\n\nvoid add(const SiconosVector& x, const SiconosVector& y, SiconosVector& z)\n{\n  // Computes z = x + y in an \"optimized\" way (in comparison with operator +)\n\n  if (x.size() != y.size() || x.size() != z.size())\n    SiconosVectorException::selfThrow(\"add(x,y,z): inconsistent sizes\");\n\n  unsigned int numX = x.num();\n  unsigned int numY = y.num();\n  unsigned int numZ = z.num();\n\n  if (&z == &x) // x, and z are the same object.\n  {\n    z += y;\n  }\n  else if (&z == &y) // y and z are the same object, different from x\n  {\n    z += x;\n  }\n  else // No common memory between x,y and z\n  {\n\n    if (numZ != 0) // z is a SiconosVector\n    {\n      if (numX == numY && numX != 0) // x, y SiconosVector of the same type\n      {\n        if (numX == 1)\n        {\n          if (numZ != 1)\n            SiconosVectorException::selfThrow(\"SiconosVector addition, add(x,y,z) failed - Addition of two dense vectors into a sparse.\");\n          noalias(*z.dense()) = *x.dense() + *y.dense() ;\n        }\n        else\n        {\n          if (numZ == 1)\n            noalias(*z.dense()) = *x.sparse() + *y.sparse() ;\n          else\n            noalias(*z.sparse()) = *x.sparse() + *y.sparse() ;\n        }\n      }\n      else if (numX != 0 && numY != 0) // x and y of different types => z must be dense.\n      {\n        if (numZ != 1)\n          SiconosVectorException::selfThrow(\"SiconosVector addition, add(x,y,z) failed - z can not be sparse.\");\n        if (numX == 1)\n          noalias(*z.dense()) = *x.dense() + *y.sparse();\n        else\n          noalias(*z.dense()) = *x.sparse() + *y.dense() ;\n      }\n    }\n  }\n}\n\n//======================\n//  Vectors subtraction\n//======================\n\nSiconosVector operator - (const  SiconosVector& x, const  SiconosVector& y)\n{\n  if (x.size() != y.size())\n    SiconosVectorException::selfThrow(\"SiconosVector, x - y: inconsistent sizes\");\n\n  unsigned int numX = x.num();\n  unsigned int numY = y.num();\n\n  if (numX == numY) // x, y SiconosVector of the same type\n  {\n    if (numX == 1)\n    {\n      //    siconosBindings::xpy(*x.dense(),p);\n      //    return p;\n      return (DenseVect)(*x.dense() - *y.dense());\n    }\n    else\n      return (SparseVect)(*x.sparse() - *y.sparse());\n  }\n  else // x, y SiconosVector with y and x of different types\n  {\n    if (numX == 1)\n      return (DenseVect)(*x.dense() - *y.sparse());\n    else\n      return (DenseVect)(*x.sparse() - *y.dense());\n  }\n}\n\nvoid sub(const SiconosVector& x, const SiconosVector& y, SiconosVector& z)\n{\n  // Computes z = x - y in an \"optimized\" way (in comparison with operator +)\n\n  if (x.size() != y.size() || x.size() != z.size())\n    SiconosVectorException::selfThrow(\"sub(x,y,z): inconsistent sizes\");\n\n  unsigned int numX = x.num();\n  unsigned int numY = y.num();\n  unsigned int numZ = z.num();\n\n  if (&z == &x) // x and z are the same object.\n  {\n    z -= y;\n  }\n  else if (&z == &y) // y and z are the same object\n  {\n    {\n      if (numX == 1)\n      {\n        if (numZ != 1)\n          SiconosVectorException::selfThrow(\"SiconosVector subtraction, sub(x,y,z) failed - Subtraction of two dense vectors into a sparse.\");\n        *z.dense() = *x.dense() - *y.dense() ;\n      }\n      else\n      {\n        if (numZ == 1)\n          *z.dense() = *x.sparse() - *y.dense() ;\n        else\n          *z.sparse() = *x.sparse() - *y.sparse() ;\n      }\n    }\n  }\n  else // No common memory between x or y and z\n  {\n\n    if (numZ != 0) // z is a SiconosVector\n    {\n      if (numX == numY && numX != 0) // x, y SiconosVector of the same type\n      {\n        if (numX == 1)\n        {\n          if (numZ != 1)\n            SiconosVectorException::selfThrow(\"SiconosVector addition, sub(x,y,z) failed - Addition of two dense vectors into a sparse.\");\n          noalias(*z.dense()) = *x.dense() - *y.dense() ;\n        }\n        else\n        {\n          if (numZ == 1)\n            noalias(*z.dense()) = *x.sparse() - *y.sparse() ;\n          else\n            noalias(*z.sparse()) = *x.sparse() - *y.sparse() ;\n        }\n      }\n      else if (numX != 0 && numY != 0) // x and y of different types => z must be dense.\n      {\n        if (numZ != 1)\n          SiconosVectorException::selfThrow(\"SiconosVector addition, sub(x,y,z) failed - z can not be sparse.\");\n        if (numX == 1)\n          noalias(*z.dense()) = *x.dense() - *y.sparse();\n        else\n          noalias(*z.dense()) = *x.sparse() - *y.dense() ;\n      }\n    }\n  }\n}\n\nvoid axpby(double a, const SiconosVector& x, double b, SiconosVector& y)\n{\n  // Computes y = ax + by\n\n  if (x.size() != y.size())\n    SiconosVectorException::selfThrow(\"axpby(x,y,z): inconsistent sizes\");\n\n  unsigned int numX = x.num();\n  unsigned int numY = y.num();\n\n  if (numX == numY) // x and y of the same type\n  {\n    if (numX == 1) // all dense\n    {\n      siconosBindings::scal(b, *y.dense());\n      siconosBindings::axpy(a, *x.dense(), *y.dense());\n    }\n    else // all sparse\n    {\n      *y.sparse() *= b;\n      if (&y != &x)\n        noalias(*y.sparse()) += a**x.sparse();\n      else\n        *y.sparse() += a**x.sparse();\n    }\n  }\n\n  else // x and y of different types\n  {\n    y *= b;\n    {\n      if (numX == 1)\n        *y.sparse() += a**x.dense();\n      else\n        *y.dense() +=  a**x.sparse();\n    }\n  }\n}\n\nvoid axpy(double a, const SiconosVector& x, SiconosVector& y)\n{\n  // Computes y = ax + y\n\n  if (x.size() != y.size())\n    SiconosVectorException::selfThrow(\"axpy(x,y,z): inconsistent sizes\");\n\n  unsigned int numX = x.num();\n  unsigned int numY = y.num();\n\n  if (numX == numY) // x and y of the same type\n  {\n    if (numX == 1) // all dense\n      siconosBindings::axpy(a, *x.dense(), *y.dense());\n\n    else // all sparse\n    {\n      if (&y != &x)\n        noalias(*y.sparse()) += a**x.sparse();\n      else\n        *y.sparse() += a**x.sparse();\n    }\n  }\n\n  else // x and y of different types\n  {\n    {\n      if (numX == 1)\n        *y.sparse() += a**x.dense();\n      else\n        *y.dense() +=  a**x.sparse();\n    }\n  }\n}\n\ndouble inner_prod(const SiconosVector &x, const SiconosVector &m)\n{\n  if (x.size() != m.size())\n    SiconosVectorException::selfThrow(\"inner_prod: inconsistent sizes\");\n\n  unsigned int numM = m.num();\n  unsigned int numX = x.num();\n\n  if (numX == numM)\n  {\n    if (numM == 1)\n      return siconosBindings::dot(*x.dense(), *m.dense());\n    else\n      return inner_prod(*x.sparse(), *m.sparse());\n  }\n  else if (numM == 1)\n    return inner_prod(*x.sparse(), *m.dense());\n  else\n    return inner_prod(*x.dense(), *m.sparse());\n}\n\n// outer_prod(v,w) = trans(v)*w\nSimpleMatrix outer_prod(const SiconosVector &x, const SiconosVector& m)\n{\n  unsigned int numM = m.num();\n  unsigned int numX = x.num();\n\n  if (numM == 1)\n  {\n    if (numX == 1)\n      return (DenseMat)(outer_prod(*x.dense(), *m.dense()));\n\n    else// if(numX == 4)\n      return (DenseMat)(outer_prod(*x.sparse(), *m.dense()));\n  }\n  else // if(numM == 4)\n  {\n    if (numX == 1)\n      return (DenseMat)(outer_prod(*x.dense(), *m.sparse()));\n\n    else //if(numX == 4)\n      return (DenseMat)(outer_prod(*x.sparse(), *m.sparse()));\n  }\n}\n\nvoid scal(double a, const SiconosVector & x, SiconosVector & y, bool init)\n{\n  // To compute y = a *x (init = true) or y += a*x (init = false)\n\n  if (&x == &y)\n  {\n    if (init)\n      y *= a;\n    else\n    {\n      y *= (1.0 + a);\n    }\n  }\n  else\n  {\n    unsigned int sizeX = x.size();\n    unsigned int sizeY = y.size();\n\n    if (sizeX != sizeY)\n      SiconosVectorException::selfThrow(\"scal(a,SiconosVector,SiconosVector) failed, sizes are not consistent.\");\n\n    unsigned int numY = y.num();\n    unsigned int numX = x.num();\n    if (numX == numY)\n    {\n\n      if (numX == 1) // ie if both are Dense\n      {\n        if (init)\n          //siconosBindings::axpby(a,*x.dense(),0.0,*y.dense());\n          noalias(*y.dense()) = a * *x.dense();\n        else\n          noalias(*y.dense()) += a * *x.dense();\n      }\n      else  // if both are sparse\n      {\n        if (init)\n          noalias(*y.sparse()) = a**x.sparse();\n        else\n          noalias(*y.sparse()) += a**x.sparse();\n      }\n    }\n    else\n    {\n      if (numY == 0 || numX == 0) // if y or x is block\n      {\n        if (init)\n        {\n          y = x;\n          y *= a;\n        }\n        else\n        {\n          SiconosVector tmp(x);\n          tmp *= a;\n          y += tmp;\n        }\n      }\n      else\n      {\n        if (numY == 1) // if y is dense\n        {\n          if (init)\n            noalias(*y.dense()) = a**x.sparse();\n          else\n            noalias(*y.dense()) += a**x.sparse();\n\n        }\n        else\n          SiconosVectorException::selfThrow(\"SiconosVector::scal(a,dense,sparse) not allowed.\");\n      }\n    }\n  }\n}\n\nvoid subscal(double a, const SiconosVector & x, SiconosVector & y, const Index& coord, bool init)\n{\n  // To compute sub_y = a *sub_x (init = true) or sub_y += a*sub_x (init = false)\n  // Coord  = [r0x r1x r0y r1y];\n  // subX is the sub-vector of x, for row numbers between r0x and r1x-1.\n  // The same for y with riy.\n\n\n  // Check dimensions\n  unsigned int dimX = coord[1] - coord[0];\n  unsigned int dimY = coord[3] - coord[2];\n  if (dimY != dimX)\n    SiconosVectorException::selfThrow(\"subscal(a,x,y,...) error: inconsistent sizes between (sub)x and (sub)y.\");\n  if (dimY > y.size() || dimX > x.size())\n    SiconosVectorException::selfThrow(\"subscal(a,x,y,...) error: input index too large.\");\n\n  unsigned int numY = y.num();\n  unsigned int numX = x.num();\n\n  if (&x == &y) // if x and y are the same object\n  {\n    if (numX == 1) // Dense\n    {\n      ublas::vector_range<DenseVect> subY(*y.dense(), ublas::range(coord[2], coord[3]));\n      if (coord[0] == coord[2])\n      {\n        if (init)\n          subY *= a;\n        else\n          subY *= (1.0 + a);\n      }\n      else\n      {\n        ublas::vector_range<DenseVect> subX(*x.dense(), ublas::range(coord[0], coord[1]));\n        if (init)\n          subY = a * subX;\n        else\n          subY += a * subX;\n      }\n    }\n    else //if (numX == 4) // Sparse\n    {\n      ublas::vector_range<SparseVect> subY(*y.sparse(), ublas::range(coord[2], coord[3]));\n      if (coord[0] == coord[2])\n      {\n        if (init)\n          subY *= a;\n        else\n          subY *= (1.0 + a);\n      }\n      else\n      {\n        ublas::vector_range<SparseVect> subX(*x.sparse(), ublas::range(coord[0], coord[1]));\n        if (init)\n          subY = a * subX;\n        else\n          subY += a * subX;\n      }\n    }\n  }\n  else\n  {\n    if (numX == numY)\n    {\n      if (numX == 1) // ie if both are Dense\n      {\n        ublas::vector_range<DenseVect> subX(*x.dense(), ublas::range(coord[0], coord[1]));\n        ublas::vector_range<DenseVect> subY(*y.dense(), ublas::range(coord[2], coord[3]));\n\n        if (init)\n          noalias(subY) = a * subX;\n        else\n          noalias(subY) += a * subX;\n      }\n      else  // if both are sparse\n      {\n        ublas::vector_range<SparseVect> subX(*x.sparse(), ublas::range(coord[0], coord[1]));\n        ublas::vector_range<SparseVect> subY(*y.sparse(), ublas::range(coord[2], coord[3]));\n\n        if (init)\n          noalias(subY) = a * subX;\n        else\n          noalias(subY) += a * subX;\n      }\n    }\n    else // x and y of different types ...\n    {\n      if (numY == 1) // y dense, x sparse\n      {\n        ublas::vector_range<DenseVect> subY(*y.dense(), ublas::range(coord[2], coord[3]));\n        ublas::vector_range<SparseVect> subX(*x.sparse(), ublas::range(coord[0], coord[1]));\n\n        if (init)\n          noalias(subY) = a * subX;\n        else\n          noalias(subY) += a * subX;\n      }\n      else // y sparse, x dense => fails\n        SiconosVectorException::selfThrow(\"SiconosVector::subscal(a,dense,sparse) not allowed.\");\n    }\n  }\n}\nvoid cross_product(const SiconosVector& V1, const SiconosVector& V2, SiconosVector& VOUT)\n{\n  if (V1.size() != 3 || V2.size() != 3 || VOUT.size() != 3)\n    SiconosVectorException::selfThrow(\"SiconosVector::cross_product allowed only with dim 3.\");\n\n  double aux = V1.getValue(1) * V2.getValue(2) - V1.getValue(2) * V2.getValue(1);\n  VOUT.setValue(0, aux);\n\n  aux = V1.getValue(2) * V2.getValue(0) - V1.getValue(0) * V2.getValue(2);\n  VOUT.setValue(1, aux);\n\n  aux = V1.getValue(0) * V2.getValue(1) - V1.getValue(1) * V2.getValue(0);\n  VOUT.setValue(2, aux);\n\n}\n\n//\n\nvoid abs_wise(const SiconosVector& V, SiconosVector& Vabs)\n{\n  for (unsigned int it = 0; it < V.size(); ++it)\n  {\n    Vabs.setValue(it, std::abs(V.getValue(it)));\n  };\n}\n\n//\n\nvoid getMax(const SiconosVector& V, double& maxvalue, unsigned int& idmax)\n{\n  maxvalue = V.getValue(0);\n  idmax = 0;\n  for (unsigned int it = 1; it < V.size(); ++it)\n  {\n    if (V.getValue(it) > maxvalue)\n    {\n      maxvalue = V.getValue(it);\n      idmax = it;\n    };\n  };\n}\n\n//\n\nvoid getMin(const SiconosVector& V, double& minvalue, unsigned int& idmin)\n{\n  minvalue = V.getValue(0);\n  idmin = 0;\n  for (unsigned int it = 1; it < V.size(); ++it)\n  {\n    if (V.getValue(it) < minvalue)\n    {\n      minvalue = V.getValue(it);\n      idmin = it;\n    };\n  };\n}\n\n//\n/*\nSiconosVector abs_wise(const SiconosVector& V){\n  SiconosVector Vabs(V.size());\n  for (int it = 0; it < V.size(); ++it){\n    Vabs.setValue(it,std::abs(V.getValue(it)));\n  };\n  return Vabs;\n}\n//\nvoid getMin(const SiconosVector& V, double& minvalue, unsigned int& idmin){\n  minvalue = V.getValue(0);\n  idmin = 0;\n  for (unsigned int it = 1; it < V.size(); ++it){\n    if (V.getValue(it) < minvalue){\n      minvalue = V.getValue(it);\n      idmin = it;\n    };\n  };\n}\n*/\nvoid setBlock(const SiconosVector& vIn, SP::SiconosVector vOut, unsigned int sizeB,\n              unsigned int startIn, unsigned int startOut)\n{\n  unsigned int endOut = startOut + sizeB;\n  unsigned int numIn = vIn.num();\n  unsigned int numOut = vOut->num();\n  assert(vOut->size() >= endOut && \"The output vector is too small\");\n  if (numIn == numOut)\n  {\n    if (numIn == 1) // vIn / vOut are Dense\n      noalias(ublas::subrange(*vOut->dense(), startOut, endOut)) = ublas::subrange(*vIn.dense(), startIn, startIn + sizeB);\n    else // if(numIn == 4)// vIn / vOut are Sparse\n      noalias(ublas::subrange(*vOut->sparse(), startOut, endOut)) = ublas::subrange(*vIn.sparse(), startIn, startIn + sizeB);\n  }\n  else // vIn and vout of different types ...\n  {\n    if (numIn == 1) // vIn Dense\n      noalias(ublas::subrange(*vOut->sparse(), startOut, endOut)) = ublas::subrange(*vIn.dense(), startIn, startIn + sizeB);\n    else // if(numIn == 4)// vIn Sparse\n      noalias(ublas::subrange(*vOut->dense(), startOut, endOut)) = ublas::subrange(*vIn.sparse(), startIn, startIn + sizeB);\n  }\n}\n\nunsigned int SiconosVector::size(void) const\n{\n  if (!_dense)\n  {\n    return (vect.Sparse->size());\n  }\n  else\n  {\n    return (vect.Dense->size());\n  }\n}\n\nSiconosVector& operator *= (SiconosVector& v, const double& s)\n{\n  if (v._dense)\n    *v.dense() *= s;\n  else\n    *v.sparse() *= s;\n  return v;\n}\n\n\nSiconosVector& operator /= (SiconosVector& v, const double& s)\n{\n  if (v._dense)\n    *v.dense() /= s;\n  else\n    *v.sparse() /= s;\n  return v;\n}\n\n", "meta": {"hexsha": "eb107f2666a77ddf3d69cc891ee6f17248eb40f8", "size": 37139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosAlgebra/SiconosVector.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/utils/SiconosAlgebra/SiconosVector.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/utils/SiconosAlgebra/SiconosVector.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": 25.7373527374, "max_line_length": 146, "alphanum_fraction": 0.5836990764, "num_tokens": 10927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5, "lm_q1q2_score": 0.26754921431330575}}
{"text": "/* Copyright (C) 2018-2019 Thomas Jespersen, TKJ Electronics. All rights reserved.\n *\n * This program is free software: you can redistribute it and/or modify it\n * under the terms of the MIT License\n *\n * This program 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 * See the MIT License for further details.\n *\n * Contact information\n * ------------------------------------------\n * Thomas Jespersen, TKJ Electronics\n * Web      :  http://www.tkjelectronics.dk\n * e-mail   :  thomasj@tkjelectronics.dk\n * ------------------------------------------\n */\n\n#include \"Path.h\"\n\n#include <string>\n#include <iostream>\n#include <stdlib.h>\n#include <stdio.h>\n\n#include <cmath>\n#include <algorithm>\n\n#include <Eigen/SVD>\n\n/* For visualization/plotting only */\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n\n#define PATH_DEBUG  0\n\n\nnamespace MPC\n{\n\n    Polynomial::Polynomial()\n    {\n\n    }\n\n    // Copy constructor\n    Polynomial::Polynomial(const Polynomial& poly) : coeffs_(poly.coeffs_)\n    {\n\n    }\n\n    Polynomial::~Polynomial()\n    {\n\n    }\n\n    Polynomial::Polynomial(unsigned int order) : coeffs_(order+1, 0.0)\n    {\n\n    }\n\n    /* Coefficients are stored such that c[0] is the coefficient for the lowest order element, such that:\n     * y = c[n]*x^n + c[n-1]*x^(n-1) + ... c[2]*x^2 + c[1]*x + c[0]\n     */\n    Polynomial::Polynomial(std::vector<double> coeffs)\n    {\n        coeffs_ = coeffs;\n    }\n\n    Polynomial::Polynomial(const double * coeffs, int num_coeffs)\n    {\n        coeffs_.insert(coeffs_.end(), coeffs, coeffs + num_coeffs);\n    }\n\n    // Assignment operator\n    Polynomial& Polynomial::operator=(const Polynomial& other)\n    {\n        coeffs_ = other.coeffs_;\n        return *this;\n    }\n\n    Polynomial Polynomial::operator+(const Polynomial& other) const\n    {\n        Polynomial out;\n\n        if (order() >= other.order()) {\n            out.coeffs_ = coeffs_;\n            for (size_t i = 0; i < other.coeffs_.size(); i++)\n                out.coeffs_.at(i) += other.coeffs_.at(i);\n        }\n        else {\n            out.coeffs_ = other.coeffs_;\n            for (size_t i = 0; i < coeffs_.size(); i++)\n                out.coeffs_.at(i) += coeffs_.at(i);\n        }\n\n        return out;\n    }\n\n    Polynomial Polynomial::operator-(const Polynomial& other) const\n    {\n        Polynomial out;\n\n        if (order() >= other.order()) {\n            out.coeffs_ = coeffs_;\n            for (size_t i = 0; i < other.coeffs_.size(); i++)\n                out.coeffs_.at(i) -= other.coeffs_.at(i);\n        }\n        else {\n            out.coeffs_ = other.coeffs_;\n            for (size_t i = 0; i < coeffs_.size(); i++)\n                out.coeffs_.at(i) -= coeffs_.at(i);\n        }\n\n        return out;\n    }\n\n    Polynomial Polynomial::operator+(const double& offset) const\n    {\n        Polynomial out;\n        if (coeffs_.size() == 0) return out;\n\n        out.coeffs_ = coeffs_;\n        out.coeffs_[0] += offset;\n        return out;\n    }\n\n    Polynomial Polynomial::operator-(const double& offset) const\n    {\n        Polynomial out;\n        if (coeffs_.size() == 0) return out;\n\n        out.coeffs_ = coeffs_;\n        out.coeffs_[0] -= offset;\n        return out;\n    }\n\n    void Polynomial::print()\n    {\n        std::cout << \"Polynomial:\" << std::endl;\n        std::cout << \"   y = \";\n        if (order() < 0) {\n            std::cout << \"0\" << std::endl << std::endl;\n            return;\n        }\n\n        for (int i = order(); i >= 1; i--) {\n            if (i > 1)\n                std::cout << coeffs_.at(i) << \"*t^\" << i << \" + \";\n            else\n                std::cout << coeffs_.at(i) << \"*t + \";\n        }\n        std::cout << coeffs_.at(0) << std::endl;\n        std::cout << std::endl;\n    }\n\n    /* Coefficients are stored such that c[0] is the coefficient for the lowest order element, such that:\n     * out = c[n]*t^n + c[n-1]*t^(n-1) + ... c[2]*t^2 + c[1]*t + c[0]\n     */\n    double Polynomial::evaluate(double t)\n    {\n        // Polynomial evaluation\n        double pow_t = 1;\n        double out = 0;\n        for (unsigned int i = 0; i < coeffs_.size(); i++) {\n            out += coeffs_[i] * pow_t;\n            pow_t *= t;\n        }\n\n        return out;\n    }\n\n    double Polynomial::operator()(double t)\n    {\n        return evaluate(t);\n    }\n\n    std::vector<double> Polynomial::evaluate(std::vector<double> tVec)\n    {\n        std::vector<double> evaluatedPoints;\n\n        // Polynomial evaluation\n        for (auto& t : tVec) {\n            double pow_t = 1;\n            double out = 0;\n            for (unsigned int i = 0; i < coeffs_.size(); i++) {\n                pow_t *= t;\n                out += coeffs_[i] * pow_t;\n            }\n\n            evaluatedPoints.push_back(out);\n        }\n\n        return evaluatedPoints;\n    }\n\n    std::vector<double> Polynomial::operator()(std::vector<double> tVec)\n    {\n        return evaluate(tVec);\n    }\n\n    int Polynomial::order() const\n    {\n        return (int)coeffs_.size() - 1;\n    }\n\n    Polynomial Polynomial::squared() const\n    {\n        // Given polynomial coefficients for:\n        // f(x) = c_n*x^n + c_n-1*x^(n-1) + ... c_1*x + c_0\n        // This function computes the coefficients of the polynomial f^2(x)\n        // Coefficients are ordered such that coeffs[0] = c_0  (lowest order)\n\n        // f^2(x) = sum(sum(c_i * c_j * x^(i+j))\n        // The resulting coefficients, coeff_k = c_i*c_j | i+j=k\n        int n = order(); // input polynomial order\n        int m = 2*n; // squared (output) polynomial order\n\n        if (m < 0) {\n            Polynomial empty;\n            return empty;\n        }\n\n        Polynomial squared(m);\n        for (int k = 0; k <= m; k++) {\n            for (int i = 0; i <= n; i++) {\n                for (int j = 0; j <= n; j++) {\n                    if (i + j == k) {\n                        squared.coeffs_.at(k) = squared.coeffs_.at(k) + coeffs_.at(i) * coeffs_.at(j);\n                    }\n                }\n            }\n        }\n        return squared;\n    }\n\n    Polynomial Polynomial::derivative() const\n    {\n        // Given polynomial coefficients for:\n        // f(x) = c_n*x^n + c_n-1*x^(n-1) + ... c_1*x + c_0\n        // This function computes the coefficients of the polynomial f'(x)\n        // f'(x) = df/dx = n*c_n*x^(n-1) + (n-1)*c_n-1*x^(n-2) + ... +\n        // f'(x) = df/dx = n*c_n*x^(n-1) + (n-1)*c_n-1*x^(n-2) + ... + 2*c_2*x + 1*c_1\n        // Coefficients are ordered such that coeff[0] = c_0  (lowest order)\n        int n = order();\n\n        if (n < 0) {\n            Polynomial empty;\n            return empty;\n        }\n\n        Polynomial derivative(n-1);\n        for (int i = 0; i <= (n-1); i++) {\n            derivative.coeffs_.at(i) = (i+1) * coeffs_.at(i+1);\n        }\n        return derivative;\n    }\n\n    double Polynomial::getCoefficient(unsigned int index)\n    {\n        if (int(index) > order())\n            return 0;\n        else\n            return coeffs_.at(index);\n    }\n\n    double Polynomial::findMinimum(double s_init, double s_lower, double s_upper, double stoppingCriteria, unsigned int maxIterations)\n    {\n        // Find the minimum by Newton minimization\n        if (order() < 0) return 0;\n\n        Polynomial dPoly = derivative();\n        Polynomial ddPoly = dPoly.derivative();\n\n        // Newton's method - https://en.wikipedia.org/wiki/Newton%27s_method_in_optimization\n        bool converged = false;\n        unsigned int iterations = 0;\n        double s = s_init;\n        double delta_s;\n\n        while (!converged && iterations < maxIterations) {\n            double FirstDerivative = dPoly.evaluate(s); // first derivative, for higher dimensions it would be the Gradient\n            double SecondDerivative = ddPoly.evaluate(s); // second derivative, for higher dimensions it would be the Hessian\n\n            delta_s = -FirstDerivative / SecondDerivative;\n            s = s + delta_s;\n\n            if (s < s_lower)\n                s = s_lower;\n\n            if (s > s_upper)\n                s = s_upper;\n\n            if (std::abs(delta_s) < stoppingCriteria)\n                converged = true;\n\n            iterations = iterations + 1;\n        }\n\n        return s;\n    }\n\n    void Polynomial::FitPoints(unsigned int order, std::vector<double>& tVec, std::vector<double>& values, bool EnforceBeginEndConstraint, bool EnforceBeginEndAngleConstraint)\n    {\n        if (order < 1) {\n            std::cout << \"Polynomial order needs to be at least 1\" << std::endl; throw;\n        }\n        else if (order < 3 && EnforceBeginEndConstraint && EnforceBeginEndAngleConstraint) {\n            std::cout << \"Polynomial order too low to enforce both type of constraints\" << std::endl; throw;\n        }\n        if (tVec.size() != values.size()) {\n            std::cout << \"Number of evaluation points (tVec) and corresponding values needs to be consistent\" << std::endl; throw;\n        }\n\n        unsigned int n = tVec.size(); // should be the same length as values\n\n        Eigen::VectorXd t = Eigen::VectorXd::Map(tVec.data(), tVec.size());\n        Eigen::VectorXd tPow = Eigen::VectorXd::Ones(n, 1);\n\n        Eigen::MatrixXd A(n, order+1);\n        // Fill the matrix using the evaluation points, t\n        for (unsigned int i = 0; i <= order; i++) {\n            A.block(0, i, n, 1) = tPow;\n            tPow = tPow.cwiseProduct(t); // tPow = tPow .* tVec\n        }\n\n        Eigen::VectorXd b = Eigen::VectorXd::Map(values.data(), values.size());\n\n        // Create matrix and vector of equality constraints\n        Eigen::MatrixXd Aeq;\n        Eigen::VectorXd beq;\n        if (EnforceBeginEndConstraint || EnforceBeginEndAngleConstraint) { // compute the constraint matrices\n            Aeq.resize(4, order+1); // OBS. Note that resizing does not initialize values!\n            beq.resize(4, 1);\n\n            // First two rows enforces begin and end constraints\n            Aeq(0,0) = 1;\n            Aeq(1,0) = 1;\n            // Last two rows enforces begin and end angle (derivative) constraints\n            Aeq(2,0) = 0;\n            Aeq(3,0) = 0;\n\n            for (unsigned int j = 1; j <= order; j++) {\n                Aeq(0, j) = Aeq(0, j-1) * t(0);\n                Aeq(1, j) = Aeq(1, j-1) * t(n-1);\n                Aeq(2, j) = Aeq(0, j-1) * j;\n                Aeq(3, j) = Aeq(1, j-1) * j;\n            }\n\n            beq(0) = b(0); // first value\n            beq(1) = b(n-1); // last value\n            beq(2) = (b(1)-b(0)) / (t(1)-t(0)); // begin angle\n            beq(3) = (b(n-1)-b(n-2)) / (t(n-1)-t(n-2)); // end angle\n        }\n\n#if PATH_DEBUG\n        std::cout << \"Aeq = \" << std::endl << Aeq << std::endl;\n        std::cout << \"beq = \" << std::endl << beq << std::endl;\n#endif\n\n        if (order < 3) { // can only enforce one type of the constraints\n            // limit constraints due to reduced order such that we only require start and end point to be fulfilled\n            if (EnforceBeginEndConstraint) {\n                // Extract the first two rows\n                Aeq = Aeq.block(0, 0, 2, order+1);\n                beq = beq.block(0, 0, 2, 2);\n            } else if (EnforceBeginEndAngleConstraint) {\n                // Extract the last two rows\n                Aeq = Aeq.block(2, 0, 2, order+1);\n                beq = beq.block(2, 0, 2, 2);\n            }\n        }\n\n        Eigen::VectorXd polyCoeffs;\n        if (EnforceBeginEndConstraint || EnforceBeginEndAngleConstraint)\n            polyCoeffs = ConstrainedLeastSquares(A, b, Aeq, beq, n*10000);\n        else\n            polyCoeffs = ConstrainedLeastSquares(A, b, Eigen::MatrixXd(), Eigen::VectorXd(), 1);\n\n#if PATH_DEBUG\n        std::cout << \"polyCoeffs = \" << std::endl << polyCoeffs << std::endl;\n#endif\n\n        coeffs_.clear();\n        coeffs_.insert(coeffs_.begin(), polyCoeffs.data(), polyCoeffs.data() + polyCoeffs.rows());\n    }\n\n    Eigen::VectorXd Polynomial::ConstrainedLeastSquares(const Eigen::MatrixXd& A, const Eigen::VectorXd& b, const Eigen::MatrixXd& Aeq, const Eigen::VectorXd& beq, double lambda)\n    {\n        Eigen::MatrixXd A_;\n        Eigen::VectorXd b_;\n\n        if (Aeq.rows() == beq.rows() && Aeq.cols() == A.cols()) {\n            A_.resize(A.rows() + Aeq.rows(), A.cols()); // OBS. Note that resizing does not initialize values!\n            b_.resize(b.rows() + beq.rows());\n            A_ << A,\n                  Aeq*lambda;\n            b_ << b,\n                  beq*lambda;\n        } else {\n            A_ = A;\n            b_ = b;\n        }\n\n#if PATH_DEBUG\n        std::cout << \"A_ = \" << std::endl << A_ << std::endl;\n#endif\n\n        // Pseudo-inverse through numerically unstable way\n        //   A_invpseudo = inv(A_'*A_) * A_'\n        // Pseudo-inverse through MATLAB\n        //   A_invpseudo2 = pinv(A_)  % Moore-Penrose Pseudoinverse of matrix of A\n        // Pseudo-inverse through SVD\n        //   [U,S,V] = svd(A_);\n        //   Sinv = [diag(1./diag(S)), zeros(size(S,2), size(S,1)-size(S,2))];\n        //   A_invpseudo3 = V * Sinv * U';\n        //   x = A_invpseudo3 * b_;\n\n        Eigen::JacobiSVD<Eigen::MatrixXd> svd( A_, Eigen::ComputeFullV | Eigen::ComputeFullU );\n\n        // create a matrix of just zeros and fill top part with inverse singular values in a diagonal matrix\n        Eigen::MatrixXd Sinv = Eigen::MatrixXd::Zero(svd.singularValues().rows(), A_.rows());\n        Sinv.block(0, 0, svd.singularValues().rows(), svd.singularValues().rows()) = svd.singularValues().asDiagonal().inverse().toDenseMatrix();\n#if PATH_DEBUG\n        std::cout << \"Sinv = \" << std::endl << Sinv << std::endl;\n#endif\n\n        Eigen::MatrixXd A_PseudoInverse = svd.matrixV() * Sinv * svd.matrixU().transpose();\n#if PATH_DEBUG\n        std::cout << \"A_PseudoInverse = \" << std::endl << A_PseudoInverse << std::endl;\n#endif\n\n        // Now get the solution (least squares minimization) by using the pseudo-inverse\n        Eigen::VectorXd x = A_PseudoInverse * b_;\n#if PATH_DEBUG\n        std::cout << \"x = \" << std::endl << x << std::endl;\n#endif\n\n        return x;\n    }\n\n    Path::Path() : computed_dsquared_(false), s_end_(0)\n    {\n\n    }\n\n    Path::Path(Polynomial& poly_x, Polynomial& poly_y, double s_end) : poly_x_(poly_x), poly_y_(poly_y), s_end_(s_end), computed_dsquared_(false)\n    {\n\n    }\n\n    Path::Path(Trajectory& trajectory, unsigned int approximationOrder, bool StopAtEnd, bool EnforceBeginEndConstraint, bool EnforceBeginEndAngleConstraint) : computed_dsquared_(false)\n    {\n        FitTrajectory(trajectory, approximationOrder, StopAtEnd, EnforceBeginEndConstraint, EnforceBeginEndAngleConstraint);\n    }\n\n    Path::~Path()\n    {\n\n    }\n\n    // Assignment operator\n    Path& Path::operator=(const Path& other)\n    {\n        poly_x_ = other.poly_x_;\n        poly_y_ = other.poly_y_;\n        s_end_ = other.s_end_;\n        computed_dsquared_ = other.computed_dsquared_;\n        dsquared_ = other.dsquared_;\n        return *this;\n    }\n\n    Eigen::Vector2d Path::get(double s)\n    {\n        return Eigen::Vector2d(poly_x_.evaluate(s), poly_y_.evaluate(s));\n    }\n\n    Eigen::Vector2d Path::operator()(double s)\n    {\n        return get(s);\n    }\n\n    std::vector<Eigen::Vector2d> Path::get(std::vector<double> sVec)\n    {\n        std::vector<Eigen::Vector2d> evaluatedPoints;\n\n        // Polynomial evaluation\n        for (auto& s : sVec) {\n            evaluatedPoints.push_back(Eigen::Vector2d(poly_x_.evaluate(s), poly_y_.evaluate(s)));\n        }\n\n        return evaluatedPoints;\n    }\n\n    std::vector<Eigen::Vector2d> Path::operator()(std::vector<double> sVec)\n    {\n        return get(sVec);\n    }\n\n    int Path::order()\n    {\n        if (poly_x_.order() >= poly_y_.order())\n            return poly_x_.order();\n        else\n            return poly_y_.order();\n    }\n\n    double Path::getXcoefficient(unsigned int index)\n    {\n        return poly_x_.getCoefficient(index);\n    }\n\n    double Path::getYcoefficient(unsigned int index)\n    {\n        return poly_y_.getCoefficient(index);\n    }\n\n    double Path::ArcCurveLength(double t)\n    {\n        // Arc curve length of a polynomial path whose position is defined as:\n        //   p(t) = [x(t), y(t)]\n        // Is given by the integral:\n        // integral( sqrt( dxdt^2 + dydt^2 ) ) dt\n        // This can however be approximated by using the velocity polynomial\n        //   Q = sqrt( (df_x/dx)^2 + (df_dy)^2 );\n\n        // First we compute the coefficients of the inner polynomial, f\n        //   f = (df_x/dx)^2 + (df_dy)^2\n        if (!computed_dsquared_) {\n            Polynomial dx = poly_x_.derivative(); // taking the difference of a polynomial, moves the coefficients\n            Polynomial dy = poly_y_.derivative();\n            Polynomial dx_squared = dx.squared();\n            Polynomial dy_squared = dy.squared();\n            dsquared_ = dx_squared + dy_squared;\n            computed_dsquared_ = true;\n        }\n        // Such that\n        // Q = sqrt(EvaluatePolynomial(f_coeff, t))\n\n        // Return the approximated arc curve length at point t - hence curve length from f(0) to f(t)\n        // Based on http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.5.2912&rep=rep1&type=pdf\n        // The approximation (see paper above) is given by\n        // s(t) = t/2 * (5/9 * Q(1.774597*t/2) + 8/9 * Q(t/2) + 5/9 * Q(0.225403*t/2))\n        double s = t/2.0 * (\n                            5.0/9.0 * sqrt(dsquared_.evaluate(1.774597*t/2.0)) +\n                            8.0/9.0 * sqrt(dsquared_.evaluate(t/2.0)) +\n                            5.0/9.0 * sqrt(dsquared_.evaluate(0.225403*t/2.0))\n                           );\n        return s;\n    }\n\n    double Path::ApproximateArcCurveLength(double t, double discretizationStepSize)\n    {\n        double distance = 0;\n        double t_current = 0;\n\n        double x_prev = poly_x_.evaluate(t_current);\n        double y_prev = poly_y_.evaluate(t_current);\n        double x, y;\n        double x_diff, y_diff;\n\n        while (t_current < t) {\n            t_current += discretizationStepSize;\n            x = poly_x_.evaluate(t_current);\n            y = poly_y_.evaluate(t_current);\n\n            x_diff = x - x_prev;\n            y_diff = y - y_prev;\n\n            distance += sqrtf(x_diff*x_diff + y_diff*y_diff); // Euclidean distance\n\n            x_prev = x;\n            y_prev = y;\n        }\n\n        return distance;\n    }\n\n    void Path::plot(bool drawXup, double x_min, double y_min, double x_max, double y_max)\n    {\n        double aspect_ratio = (x_max - x_min) / (y_max - y_min);\n        double xres, yres;\n        if (aspect_ratio >= 1) {\n            yres = 500;\n            xres = yres * aspect_ratio;\n        } else {\n            xres = 500;\n            yres = xres / aspect_ratio;\n        }\n\n        // Create black empty images\n        cv::Mat image;\n        if (drawXup)\n            image = cv::Mat( xres, yres, CV_8UC3, cv::Scalar( 255, 255, 255 ) );\n        else\n            image = cv::Mat( yres, xres, CV_8UC3, cv::Scalar( 255, 255, 255 ) );\n\n        // Scale range (x_min:x_max) and (y_min:y_max) to (0:499)\n        double scale_x = xres / (x_max - x_min);\n        double scale_y = yres / (y_max - y_min);\n        double center_x = (x_min + x_max) / 2.0;\n        double center_y = (y_min + y_max) / 2.0;\n\n        if (s_end_ <= 0) return; // can not plot if length is unknown\n        double s_spacing = s_end_ / 99.0;\n\n        Eigen::Vector2d p_prev = get(0);\n        Eigen::Vector2d p;\n\n        for (unsigned int s_idx = 0; s_idx < 100; s_idx++) {\n            double s = s_spacing * s_idx;\n            p = get(s);\n\n            float x = (p[0]-x_min) * scale_x;\n            float y = (p[1]-y_min) * scale_y;\n\n            if (x >= 0 && x < xres && y >= 0 && y < yres) {\n                cv::Point point;\n                if (drawXup) // draw with robot x-axis pointing up in plot\n                    point = cv::Point(yres-y,xres-x);\n                else\n                    point = cv::Point(x,yres-y);\n\n                // Draw a line\n                //cv::line(image, cv::Point(p_prev[0], p_prev[1]), point, cv::Scalar( 0, 0, 0 ), 1, 8 );\n                cv::drawMarker(image, point, cv::Scalar( 255, 0, 0 ), cv::MARKER_CROSS, 3, 1, 8 );\n\n                p_prev = p;\n            }\n        }\n\n        cv::imshow(\"Path\", image);\n\n        cv::waitKey( 5 );\n    }\n\n    void Path::plot(cv::Mat& image, cv::Scalar color, bool drawXup, double x_min, double y_min, double x_max, double y_max)\n    {\n        double xres = image.cols;\n        double yres = image.rows;\n\n        cv::line(image, cv::Point(0, yres/2), cv::Point(xres-1, yres/2), cv::Scalar(128,128,128), 1, 8, 0);\n        cv::line(image, cv::Point(xres/2, 0), cv::Point(xres/2, yres-1), cv::Scalar(128,128,128), 1, 8, 0);\n\n        // Scale range (x_min:x_max) and (y_min:y_max) to (0:499)\n        double scale_x = xres / (x_max - x_min);\n        double scale_y = yres / (y_max - y_min);\n        double center_x = (x_min + x_max) / 2.0;\n        double center_y = (y_min + y_max) / 2.0;\n\n        if (s_end_ <= 0) return; // can not plot if length is unknown\n        double s_spacing = s_end_ / 99.0;\n\n        Eigen::Vector2d p_prev = get(0);\n        Eigen::Vector2d p;\n\n        for (unsigned int s_idx = 0; s_idx < 100; s_idx++) {\n            double s = s_spacing * s_idx;\n            p = get(s);\n\n            float x = (p[0]-x_min) * scale_x;\n            float y = (p[1]-y_min) * scale_y;\n\n            if (x >= 0 && x < xres && y >= 0 && y < yres) {\n                cv::Point point;\n                if (drawXup) // draw with robot x-axis pointing up in plot\n                    point = cv::Point(yres-y,xres-x);\n                else\n                    point = cv::Point(x,yres-y);\n\n                // Draw a line\n                //cv::line(image, cv::Point(p_prev[0], p_prev[1]), point, cv::Scalar( 0, 0, 0 ), 1, 8 );\n                cv::drawMarker(image, point, color, cv::MARKER_CROSS, 3, 1, 8 );\n\n                p_prev = p;\n            }\n        }\n    }\n\n    void Path::PlotPoint(double sValue, cv::Mat& image, cv::Scalar color, bool drawXup, double x_min, double y_min, double x_max, double y_max)\n    {\n        double xres = image.cols;\n        double yres = image.rows;\n        Eigen::Vector2d p = get(sValue);\n\n        // Scale range (x_min:x_max) and (y_min:y_max) to (0:499)\n        double scale_x = xres / (x_max - x_min);\n        double scale_y = yres / (y_max - y_min);\n        double center_x = (x_min + x_max) / 2.0;\n        double center_y = (y_min + y_max) / 2.0;\n\n        float x = (p[0]-x_min) * scale_x;\n        float y = (p[1]-y_min) * scale_y;\n\n        if (x >= 0 && x < xres && y >= 0 && y < yres) {\n            cv::Point point;\n            if (drawXup) // draw with robot x-axis pointing up in plot\n                point = cv::Point(yres-y,xres-x);\n            else\n                point = cv::Point(x,yres-y);\n\n            cv::drawMarker(image, point, color, cv::MARKER_STAR, 6, 2, 8);\n        }\n    }\n\n    void Path::FitTrajectory(Trajectory& trajectory, unsigned int approximationOrder, bool StopAtEnd, bool EnforceBeginEndConstraint, bool EnforceBeginEndAngleConstraint)\n    {\n        // approximationOrder is for x(t) and y(t) fitting\n        unsigned order_t2s = approximationOrder + 1; // order_t2s is for t(s) fitting\n        unsigned order_f2s = approximationOrder + 1; // order_f2s is the order for the final fitted path: x(s) and y(s)\n\n        std::vector<double> tVec = trajectory.GetDistanceList(); // get approximated distance vector for the individual points in the trajectory\n        std::vector<double> xValues = trajectory.GetX();\n        std::vector<double> yValues = trajectory.GetY();\n\n        if (tVec.size() <= order_t2s) { // we do not have sufficient points for fitting - therefore just do a path that corresponds to holding a static position (end point)\n            s_end_ = 99;\n            poly_x_ = Polynomial({trajectory.back().point[0], 0.001});\n            poly_y_ = Polynomial({trajectory.back().point[1], 0.001});\n            return;\n        }\n\n        /* Fit window points to two polynomials, x(t) and y(t), using parameters t starting with t0=0 and spaced with the distance between each point (chordal parameterization) */\n        Polynomial xt, yt;\n        xt.FitPoints(approximationOrder, tVec, xValues, EnforceBeginEndConstraint, EnforceBeginEndAngleConstraint);\n        yt.FitPoints(approximationOrder, tVec, yValues, EnforceBeginEndConstraint, EnforceBeginEndAngleConstraint);\n\n        // Create temporary path holding the x(t) and y(t) approximation\n        Path tmpPath(xt, yt);\n\n        /* Compute numerical approximation of arc length at the points, t, using the fitted polynomial */\n        // Given the now approximated x(t), y(t) path, we approximate the arc curve length for the different points\n        // Hence to be able to create a mapping between s to t : t(s)\n        std::vector<double> sVec;\n        for (double& t : tVec) {\n            sVec.push_back(tmpPath.ArcCurveLength(t));\n        }\n\n        double sTotal = sVec.back();\n\n        /* Fit t(s) polynomial */\n        Polynomial ts;\n        ts.FitPoints(order_t2s, sVec, tVec, true, false);\n\n        /* Create vector of evenly spaced distances, s, and get corresponding t values */\n        // Make 100 linearly (evenly) seperated distance points\n        double spacing = sTotal / 99;\n        std::vector<double> sEven;\n        std::vector<double> tEven;\n        for (int i = 0; i < 100; i++) {\n            double s = i * spacing;\n            sEven.push_back(s);\n            tEven.push_back(ts.evaluate(s));\n        }\n\n        /* Use vector of the corresponding t values (matching the evenly spaced s distances) to get corresponding x-y value pairs from the initial approximation */\n        std::vector<double> xEven;\n        std::vector<double> yEven;\n        for (double& t : tEven) {\n            xEven.push_back(xt.evaluate(t));\n            yEven.push_back(yt.evaluate(t));\n        }\n\n        /* Hack to make the fitted trajectory keep the same position after reaching the distance value */\n        /*if (StopAtEnd) {\n            for (int i = 1; i < 100; i++) {\n                double s = sTotal + i * spacing;\n                sEven.push_back(s);\n                xEven.push_back(xEven.back() + spacing/1000);\n                yEven.push_back(yEven.back());\n            }\n        }*/\n\n        /* Use the s to x-y pairs to create final approximation: x(s) and y(s) */\n        // Fit two new polynomials on the new generated points, x_0,...,x_n  and y_0,...,y_n  using the evenly spaced distance parameters, s_0,...,s_n, as the parameter\n        poly_x_.FitPoints(order_f2s, sEven, xEven, EnforceBeginEndConstraint, EnforceBeginEndAngleConstraint);\n        poly_y_.FitPoints(order_f2s, sEven, yEven, EnforceBeginEndConstraint, EnforceBeginEndAngleConstraint);\n        s_end_ = sEven.back(); // sTotal\n    }\n\n    void Path::print()\n    {\n        std::cout << \"x(s) \";\n        poly_x_.print();\n        std::cout << \"y(s) \";\n        poly_y_.print();\n    }\n\n    double Path::length()\n    {\n        return s_end_;\n    }\n\n    double Path::FindClosestPoint(const Eigen::Vector2d& position)\n    {\n        // Find point on path being closest to the input position and return the corresponding path parameter (s-value) at this point\n        // First we create a centered path around the input position, by taking the two polynomial and subtracting the position value\n        Polynomial xs_centered = poly_x_ - position[0];\n        Polynomial ys_centered = poly_y_ - position[1];\n        // Given this centered polynomial, the distance to any point along the original path is defined by the function:\n        //   dist(s) = sqrt( f_x(s)^2 + f_y(s)^2 )\n        // Since this is the function we want to minimize we create this function as a distance polynomial such that we can take the derivative and find the minimum point\n        Polynomial xs_squared = xs_centered.squared();\n        Polynomial ys_squared = ys_centered.squared();\n        // And since we want to find the closest distance, we can also just\n        // minimize the squared distance: dist(s)^2\n        //   dist(s)^2 = f_x(s)^2 + f_y(s)^2\n        Polynomial dist_squared = xs_squared + ys_squared;\n\n        // Finally we find the minimum distance, s, through a Newton-based minimization\n        return dist_squared.findMinimum(0, 0, s_end_, 0.001, 100);\n    }\n\n}\n", "meta": {"hexsha": "a6c8d07d09a3ea1c60a00e3cbd24664da72061a8", "size": 28409, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kugle_mpc/libs/mpc/Path.cpp", "max_stars_repo_name": "VBorjaDD/Kugle-ROS", "max_stars_repo_head_hexsha": "e7b9a7e070012a3049df5df576440c02608ec675", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2019-02-28T18:08:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T20:42:03.000Z", "max_issues_repo_path": "kugle_mpc/libs/mpc/Path.cpp", "max_issues_repo_name": "VBorjaDD/Kugle-ROS", "max_issues_repo_head_hexsha": "e7b9a7e070012a3049df5df576440c02608ec675", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T08:38:48.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-22T09:12:04.000Z", "max_forks_repo_path": "kugle_mpc/libs/mpc/Path.cpp", "max_forks_repo_name": "VBorjaDD/Kugle-ROS", "max_forks_repo_head_hexsha": "e7b9a7e070012a3049df5df576440c02608ec675", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-03-06T10:06:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T13:41:25.000Z", "avg_line_length": 34.8149509804, "max_line_length": 184, "alphanum_fraction": 0.5558449787, "num_tokens": 7628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2675476090480981}}
{"text": "/*\n\nRPBA - Robust Parallel Bundle Adjustment\n\nFile rpbacore.cpp\n\nDescription: Parallel bundle adjustment core\n\n\n\nCopyright 2019 Helmut Mayer, Bundeswehr University Munich, Germany, Helmut.Mayer@unibw.de\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\n\n#include \"rpba.h\"\n#include \"system.h\"\n#include <boost/math/special_functions/round.hpp>\n\n\n\nvoid CalcPLSA(Eigen::MatrixXf &XX,\n\t\tstd::vector<Eigen::MatrixXf> &xg,\n\t\tconst std::vector<std::vector<float> > &wx, const std::vector<std::vector<float> > &wy,\n\t\tconst std::vector<std::vector<float> > &wxy,\n\t\tstd::vector<std::vector<IMAPNR> > &pointXXvio,\n\t\tstd::vector<PMat> &PMatrices,\n\t\tstd::vector<Camera> &cameras,\n\t\tconst std::vector<int> &iwidth, const std::vector<int> &iheight,\n\t\tconst bool robustflag,\n\t\tconst std::vector<bool> &addflagsin,\n\t\tstd::ostream& os, const int mt,\n\t\tconst bool extevalflag) {\n\n\tstd::vector<bool> addflags,addflagsold;\n\taddflags = addflagsin;\n\n\tint nraddp = 0;\n\tfor (int i = 0; i < (int) addflags.size(); ++i)\n\t\tif (addflags[i])\n\t\t\t++nraddp;\n\n\taddflagsold = addflags;\n\n\tEigen::Matrix3f Ksi;\n\n\tstd::vector<std::vector<IMAPNR> > pointXXv,pointXXvold;\n\tpointXXv = pointXXvio;\n\n\tconst int pxs = (int) pointXXv.size();\n\tint nrimages = (int) xg.size();\n\n\tbool gcpflag = false;\n\n\tEigen::MatrixXd XXd(4,pxs), XXdold(4,pxs), XXdt(4,pxs), XXt(4,pxs);\n\tstd::vector<Eigen::MatrixXd> Zs; // XXs;\n\n\tstd::vector<int> imgind, imgindbv(nrimages);\n\tstd::vector<Camera> cameraps(nrimages);\n\tstd::vector<int> gcpinfo;\n\tstd::vector<std::vector<float> > W3iji(6);\n\tstd::vector<PMatd> PMatricesd(nrimages),PMatricesdold(nrimages),PMatricesdt(nrimages);\n\tstd::vector<std::vector<double> > gcpdata,gcpdatait;\n\n\tfor (int i = 0; i < nrimages; ++i) {\n\t\tcameraps[i] = cameras[i];\n\t\tPMatricesd[i] = PMatrices[i].cast <double> ();\n\t\tPMatricesdold[i] = PMatrices[i].cast <double> ();\n\t}\n\n\tXXd = XX.cast <double> ();\n\n\tint minnrimages = 70;\n\tconst int minnrthreads = boost::math::iround((float) nrimages / (float) minnrimages);\n\n\tint nrthreads = mt;\n\n\tif (minnrthreads < nrthreads)\n\t\tnrthreads = minnrthreads;\n\n\tfloat ihw2 = 0.f;\n\tfor(int i = 0; i < nrimages; ++i)\n\t\tihw2 += (float) ((iheight[i] + iwidth[i]) * (iheight[i] + iwidth[i])) * 0.25f;\n\tihw2 /= (float) nrimages;\n\n\tbool parflag = nrthreads > 1 && nrimages > 5;\n\n\tif (extevalflag) {\n\t\tEvalLSA(nraddp, cameraps, XXd, xg, wx, wy, wxy, pointXXv, PMatricesd, ihw2);\n\t\treturn;\n\t}\n\n\n\tif (parflag) {\n\n\t\tstd::vector<float> xiout;\n\t\tEigen::MatrixXf wap;\n\t\tstd::vector<float> sig0vio;\n\t\tdouble sig0g = 0.;\n\t\tlong redundancy = 0;\n\n\t\tgcpflag = true;\n\n\t\tstd::cout << \"#threads: \" << nrthreads << \" \" << minnrthreads << '\\n';\n\n\t\tstd::vector<std::vector<bool> > pitflagsv(pxs);\n\t\tstd::vector<LSA*> LSAv(nrthreads);\n\t\tstd::vector<Eigen::MatrixXd> XXdd(nrthreads);\n\t\tstd::vector<std::vector<PMatd> > PMatricesdd(nrthreads);\n\t\tstd::vector<std::vector<Camera> > camerasoit(nrthreads);\n\t\tstd::vector<std::vector<std::vector<IMAPNR> > > pointXXvv(nrthreads);\n\t\tstd::vector<IMAPNR> pxvv;\n\t\tstd::vector<std::vector<IMAPNR> > pxvvv(nrthreads);\n\t\tstd::vector<int> nriv(nrthreads+1);\n\t\tstd::vector<std::vector<int> > imgindv(nrthreads),gcpinfov(nrthreads),pindv(nrthreads);\n\t\tstd::vector<std::vector<std::vector<std::vector<float> > > > w3dvivv(nrthreads);\n\t\tstd::vector<std::vector<std::vector<float> > > sig0vvv(nrthreads);\n\t\tstd::vector<std::vector<std::vector<float> > > W3ijiv(nrthreads);\n\t\tstd::vector<std::vector<float> > sig0vvs(nrimages);\n\t\tstd::vector<long> redundancyv(nrthreads);\n\t\tstd::vector<float> sig0wv(nrimages);\n\t\tstd::vector<double> sig0gv(nrthreads);\n\t\tstd::vector<std::vector<std::vector<double> > > gcpdatav;\n\t\tstd::vector<int> beginv(nrthreads),endv(nrthreads);\n\t\tstd::vector<Camera> camerasnew(nrimages),camerasold(nrimages);\n\n\n\t\tstd::vector<std::vector<int> > imagesperpart;\n\t\tstd::vector<idx_t> part(nrimages);\n\n\t\tconst System::Time startp = System::getTickCount();\n\t\timagesperpart.resize(nrthreads);\n\t\tPartitionpointXXv(pointXXv, nrimages, nrthreads, part, imagesperpart);\n\t\tstd::cout << \"\\n\\nPartitioning runtime: \" << (float) (System::getTickCount()-startp) / 1000.f << \"s\\n\\n\";\n\n\t\tnriv[0] = 0;\n\t\tfor (int it = 0; it < nrthreads; ++it) {\n\t\t\tnriv[it+1] = nriv[it] + (int) imagesperpart[it].size();\n\t\t\tw3dvivv[it].resize(6);\n\t\t}\n\t\tnriv[nrthreads] = nrimages;\n\n\t\tstd::vector<int> imageind(nrimages);\n\n\t\tint itj = -1;\n\t\tfor (int it = 0; it < nrthreads; ++it)\n\t\t\tfor (int j = 0; j < (int) imagesperpart[it].size(); ++j)\n\t\t\t\timageind[++itj] = imagesperpart[it][j];\n\n\t\tfor (int it = 0; it < nrthreads; ++it) {\n\t\t\tcamerasoit[it] = cameras;\n\t\t\tPMatricesdd[it] = std::vector<PMatd>(nrimages);\n\t\t\tfor (int i = 0; i < nrimages; ++i) {\n\t\t\t\tPMatricesdd[it][i] = PMatrices[i].cast <double> ();\n\t\t\t} // for i\n\t\t\timgindv[it].resize(nriv[it+1] - nriv[it]);\n\t\t\tstd::cout << \"Thread: \" << it << \" #images \" << nriv[it+1] - nriv[it] << \" indices \" << nriv[it] << ' ' << nriv[it+1] << '\\n';\n\t\t\tfor (int i = 0; i < nriv[it+1] - nriv[it]; ++i) {\n\t\t\t\timgindv[it][i] = imageind[i + nriv[it]];\n\t\t\t\timgindbv[imageind[i + nriv[it]]] = it;\n\t\t\t}\n\t\t\tstd::sort(imgindv[it].begin(),imgindv[it].end());\n\t\t\tsig0vvv[it].resize(nrimages);\n\t\t} // for it\n\n\n\t\tgcpinfo.resize(pxs);\n\t\tstd::vector<int>::iterator pxi;\n\t\tfor (pxi = gcpinfo.begin(); pxi != gcpinfo.end(); ++pxi)\n\t\t\t(*pxi) = -1;\n\n\t\tsig0g = 0.;\n\t\tredundancy = 0;\n\t\tint nrparimages = (nrimages - 2) * 6 + 5 + nrimages * nraddp;\n\n\n\t\tint nrobs;\n\t\tdouble sig0opt = 1.e20;\n\n\t\tint iflag = 1, iter = 1;\n\t\tif (robustflag)\n\t\t\tiflag = 2;\n\t\tbool robustflagit;\n\t\tbool iniflag = true;\n\n\t\tgcpflag = true;\n\n\t\tfor (int i = 0; i < pxs; ++i) {\n\t\t\tif ((int) pointXXv[i].size() > 0) {\n\t\t\t\tpitflagsv[i].resize(nrthreads);\n\t\t\t\tfor (int j = 0; j < nrthreads; ++j)\n\t\t\t\t\tpitflagsv[i][j] = false;\n\t\t\t\tfor (int j = 0; j < (int) pointXXv[i].size(); ++j)\n\t\t\t\t\tpitflagsv[i][imgindbv[pointXXv[i][j].image]] = true;\n\t\t\t} // if pointXXv\n\t\t} // for i\n\n\t\tgcpdatav.resize(nrthreads);\n\n\t\tfloat sig0frac = 1.01f;\n\n\t\twhile (iflag > 0 && iter < 51) {\n\t\t\trobustflagit = false;\n\n\t\t\tif (iter > 1) {\n\t\t\t\tif (iter < 3)\n\t\t\t\t\taddflags[0] = addflags[1] = addflags[2] = false;\n\t\t\t\telse\n\t\t\t\t\taddflags = addflagsold;\n\n\t\t\t\tstd::vector<std::ostringstream> osv(nrthreads);\n\n\t\t\t\t#pragma omp parallel for num_threads(nrthreads)\n\t\t\t\tfor (int it = 0; it < nrthreads; ++it) {\n\t\t\t\t\tif (iter == 2)\n\t\t\t\t\t\tLSAv[it] = new LSA( camerasoit[it], addflags,\n\t\t\t\t\t\t\t\ttrue, imgindv[it], PMatricesdd[it],\n\t\t\t\t\t\t\t\tpointXXvv[it], XXdd[it], (int)pindv[it].size(), xg,\n\t\t\t\t\t\t\t\twx, wy, wxy, W3iji,\n\t\t\t\t\t\t\t\ttrue, gcpinfov[it], gcpdatait,\n\t\t\t\t\t\t\t\tihw2, false);\n\t\t\t\t\telse\n\t\t\t\t\t\tLSAv[it]->InputLSAP(addflags, camerasoit[it], imgindv[it], pointXXvv[it], PMatricesdd[it], XXdd[it], (int) pointXXvv[it].size(),\n\t\t\t\t\t\t\t\tgcpinfov[it]);\n\n\t\t\t\t\tLSAv[it]->Adjust(false, osv[it], true, 0, W3ijiv[it], true, gcpdatav[it]);\n\n\t\t\t\t\tLSAv[it]->OutputLSAP(PMatricesdd[it], pointXXvv[it], XXdd[it], gcpinfov[it], camerasoit[it]);\n\t\t\t\t} // for it\n\n\t\t\t\tfor (int it = 0; it < nrthreads; ++it) {\n\t\t\t\t\tos << osv[it].str();\n\t\t\t\t\tfor (int i = 0; i < (int) imgindv[it].size(); ++i) {\n\t\t\t\t\t\tPMatricesd[imgindv[it][i]] = PMatricesdd[it][imgindv[it][i]];\n\t\t\t\t\t\tconst int iii = imgindv[it][i];\n\t\t\t\t\t\tcameraps[iii] = camerasoit[it][imgindv[it][i]];\n\t\t\t\t\t\tcamerasnew[iii] = camerasoit[it][imgindv[it][i]];\n\t\t\t\t\t} // for i\n\t\t\t\t}\n\t\t\t} // it iter > 1\n\n\t\t\tif (iflag == 1) {\n\t\t\t\trobustflagit = robustflag;\n\t\t\t\tif (robustflag)\n\t\t\t\t\tsig0frac = 1.02f;\n\t\t\t}\n\n\t\t\tconst int nrppt = pxs / nrthreads;\n\t\t\tif (iniflag) {\n\t\t\t\tfor (int itt = 0; itt < nrthreads; ++itt) {\n\t\t\t\t\tbeginv[itt] = nrppt * itt;\n\t\t\t\t\tendv[itt] = nrppt * (itt + 1);\n\t\t\t\t\tif (itt == nrthreads - 1)\n\t\t\t\t\t\tendv[itt] = pxs;\n\n\t\t\t\t\tconst int eb = endv[itt] - beginv[itt];\n\t\t\t\t\tfor (int vv = 0; vv < 6; ++vv) {\n\t\t\t\t\t\tw3dvivv[itt][vv].resize(eb);\n\t\t\t\t\t\tfor (int ebb = 0; ebb < eb; ++ebb)\n\t\t\t\t\t\t\tw3dvivv[itt][vv][ebb].resize(nrthreads);\n\t\t\t\t\t}\n\t\t\t\t\tW3ijiv[itt].resize(6);\n\n\t\t\t\t} // for itt\n\t\t\t} // if iniflag\n\n\t\t\tif (iter > 1) {\n\t\t\t\tfor (int i = 0; i < pxs; ++i)\n\t\t\t\t\tpointXXv[i].resize(0);\n\n\t\t\t\tfor (int it= 0; it < nrthreads; ++it)\n\t\t\t\t\tfor (int i = 0; i < (int) pindv[it].size(); ++i)\n\t\t\t\t\t\tfor (size_t j = 0; j < pointXXvv[it][i].size(); ++j)\n\t\t\t\t\t\t\tpointXXv[pindv[it][i]].push_back(pointXXvv[it][i][j]);\n\n\t\t\t\tfor (int i = 0; i < pxs; ++i)\n\t\t\t\t\tif ((int) pointXXv[i].size() < 2)\n\t\t\t\t\t\tpointXXv[i].clear();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfor (int it = 0; it < nrthreads; ++it) {\n\t\t\t\t\tfor (int i = 0; i < (int) imgindv[it].size(); ++i) {\n\t\t\t\t\t\tconst int iii = imgindv[it][i];\n\t\t\t\t\t\tcameraps[iii] = cameras[iii];\n\t\t\t\t\t\tcamerasnew[iii] =  cameras[iii];\n\t\t\t\t\t} // for i\n\t\t\t\t} // for it\n\t\t\t} // else\n\n\t\t\tfor (int itt = 0; itt < nrthreads; ++itt)\n\t\t\t\tfor (int i = 0; i < 6; ++i)\n\t\t\t\t\tW3ijiv[itt][i].resize(0);\n\t\t\tfor (int i = 0; i < pxs; ++i) {\n\t\t\t\tif ((int) pointXXv[i].size() > 0) {\n\t\t\t\t\tfor (int it = 0; it < nrthreads; ++it)\n\t\t\t\t\t\tpitflagsv[i][it] = false;\n\t\t\t\t\tfor (int j = 0; j < (int) pointXXv[i].size(); ++j)\n\t\t\t\t\t\tpitflagsv[i][imgindbv[pointXXv[i][j].image]] = true;\n\t\t\t\t} // if pointXXv\n\t\t\t} // for i\n\n\t\t\tif (robustflagit) {\n\t\t\t\t#pragma omp parallel for num_threads(nrthreads)\n\t\t\t\tfor (int itt = 0; itt < nrthreads; ++itt) {\n\t\t\t\t\tfor (int iii = 0; iii < nrimages; ++iii)\n\t\t\t\t\t\tsig0vvv[itt][iii].resize(0);\n\t\t\t\t\tsig0gv[itt] = 0.;\n\t\t\t\t\tredundancyv[itt] = 0;\n\t\t\t\t\tfor (int i = beginv[itt], ii = 0; i < endv[itt]; ++i, ++ii) {\n\t\t\t\t\t\tif ((int) pointXXv[i].size() > 0) {\n\t\t\t\t\t\t\tCalcLSAXMulti(cameraps,i,XXd,xg,wx,wy,wxy,pointXXv,PMatricesd,\n\t\t\t\t\t\t\t\t\timgindbv, nrthreads, pitflagsv[i],\n\t\t\t\t\t\t\t\t\tw3dvivv[itt][0][ii],w3dvivv[itt][1][ii],w3dvivv[itt][2][ii],\n\t\t\t\t\t\t\t\t\tw3dvivv[itt][3][ii],w3dvivv[itt][4][ii],w3dvivv[itt][5][ii],\n\t\t\t\t\t\t\t\t\tsig0gv[itt],redundancyv[itt],sig0vvv[itt],sig0wv,1,false,false);\n\t\t\t\t\t\t} // if pointXX\n\t\t\t\t\t} // for i\n\t\t\t\t} // for itt\n\n\t\t\t\tsig0g = 0.;\n\t\t\t\tredundancy = 0;\n\t\t\t\tfor (int itt = 0; itt < nrthreads; ++itt) {\n\t\t\t\t\tsig0g += sig0gv[itt];\n\t\t\t\t\tredundancy += redundancyv[itt];\n\t\t\t\t}\n\n\t\t\t\tfor (int i = 0; i < nrimages; ++i)\n\t\t\t\t\tsig0vvs[i].resize(0);\n\n\t\t\t\tfor (int itt = 0; itt < nrthreads; ++itt)\n\t\t\t\t\tfor (int i = 0; i < nrimages; ++i)\n\t\t\t\t\t\tsig0vvs[i].insert(sig0vvs[i].begin(),sig0vvv[itt][i].begin(),sig0vvv[itt][i].end());\n\t\t\t\tfor (int i = 0; i < nrimages; ++i) {\n\t\t\t\t\tif (sig0vvs[i].size() == 0) {\n\t\t\t\t\t\tstd::cout << \"Image \" << i << \" without observations!!!!!!!!!!!!!!!!!!!!!\\n\\n\";\n\t\t\t\t\t\tsig0wv[i] = 0.f;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tstd::sort(sig0vvs[i].begin(),sig0vvs[i].end());\n\t\t\t\t\t\tsig0wv[i] = 1.f / (sig0vvs[i][(int) sig0vvs[i].size() / 2] * 2.1981f); // 1.4826 // 1.706f - 1.306^2\n\t\t\t\t\t}\n\t\t\t\t} // for i\n\t\t\t} // if robustflagit\n\n\t\t\tint robustmode = 0;\n\t\t\tif (robustflagit)\n\t\t\t\trobustmode = 2;\n\n\n\t\t\tbool weightonlyflag = false;\n\t\t\tif (iter == 1)\n\t\t\t\tweightonlyflag = true;\n\n\t\t\t#pragma omp parallel for num_threads(nrthreads)\n\t\t\tfor (int itt = 0; itt < nrthreads; ++itt) {\n\t\t\t\tsig0gv[itt] = 0.;\n\t\t\t\tredundancyv[itt] = 0;\n\t\t\t\tfor (int i = beginv[itt], ii = 0; i < endv[itt]; ++i, ++ii) {\n\t\t\t\t\tif ((int) pointXXv[i].size() > 0) {\n\t\t\t\t\t\tCalcLSAXMulti(cameraps,i,XXd,xg,wx,wy,wxy,pointXXv,PMatricesd,\n\t\t\t\t\t\t\t\timgindbv, nrthreads, pitflagsv[i],\n\t\t\t\t\t\t\t\tw3dvivv[itt][0][ii],w3dvivv[itt][1][ii],w3dvivv[itt][2][ii],\n\t\t\t\t\t\t\t\tw3dvivv[itt][3][ii],w3dvivv[itt][4][ii],w3dvivv[itt][5][ii],\n\t\t\t\t\t\t\t\tsig0gv[itt],redundancyv[itt],sig0vvv[itt],sig0wv,robustmode,weightonlyflag,true);\n\t\t\t\t\t} // if pointxxv\n\t\t\t\t} // for i\n\t\t\t} // for itt\n\n\n\t\t\tsig0g = 0.;\n\t\t\tredundancy = 0;\n\t\t\tfor (int itt = 0; itt < nrthreads; ++itt) {\n\t\t\t\tsig0g += sig0gv[itt];\n\t\t\t\tredundancy += redundancyv[itt];\n\t\t\t}\n\n\t\t\tnrobs = 0;\n\t\t\tfor (int i = 0; i < pxs; ++i)\n\t\t\t\tnrobs += (int) pointXXv[i].size();\n\t\t\tnrobs *= 2;\n\n\t\t\tsig0g /= (double) (redundancy - nrparimages);\n\n\t\t\tif (iter > 0) {\n\t\t\t\tstd::cout << \"IT: \" << iter << \" \" << iflag << \"  \" << sqrt(sig0g * ihw2) << ' ' << sig0opt / sig0g << \"  \";\n\t\t\t\tstd::cout << sig0g << \" \" << redundancy << \" \" << nrobs << \" \" << nrparimages << \" \" << nraddp << \"  \" << redundancy - nrparimages << '\\n';\n\t\t\t}\n\n\t\t\tif (sig0g <= sig0opt) {\n\t\t\t\tXXdold = XXd;\n\t\t\t\tfor (int i = 0; i < nrimages; ++i)\n\t\t\t\t\tPMatricesdold[i] = PMatricesd[i];\n\t\t\t\tpointXXvold = pointXXv;\n\t\t\t\tcamerasold = camerasnew;\n\t\t\t}\n\n\t\t\tfor (int itt = 0; itt < nrthreads; ++itt) {\n\t\t\t\tcamerasoit[itt] = camerasnew;\n\t\t\t\tfor (int i = 0; i < (int) imgindv[itt].size(); ++i)\n\t\t\t\t\tPMatricesdd[itt][imgindv[itt][i]] = PMatricesd[imgindv[itt][i]];\n\t\t\t\tpointXXvv[itt].resize(0);\n\t\t\t\tpindv[itt].resize(0);\n\t\t\t} // for itt\n\n\t\t\tint nrgcpnew = 0;\n\t\t\tfor (int itt = 0; itt < nrthreads; ++itt)\n\t\t\t\tgcpdatav[itt].resize(0);\n\n\t\t\tfor (int itt = 0; itt < nrthreads; ++itt) {\n\t\t\t\tfor (int i = beginv[itt], ii = 0; i < endv[itt]; ++i, ++ii) {\n\t\t\t\t\tif ((int) pointXXv[i].size() < 2)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tint gnum = 0;\n\t\t\t\t\tfor (int it = 0; it < nrthreads; ++it) {\n\t\t\t\t\t\tif (pitflagsv[i][it])\n\t\t\t\t\t\t\t++gnum;\n\t\t\t\t\t\tif (gnum > 1)\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif (gnum > 1) {\n\t\t\t\t\t\tgcpinfo[i] = nrgcpnew;\n\t\t\t\t\t\tfor (int ittt = 0; ittt < nrthreads; ++ittt) {\n\t\t\t\t\t\t\tgcpdatav[ittt].push_back(std::vector<double>(3));\n\t\t\t\t\t\t\tgcpdatav[ittt][nrgcpnew][0] = XXd(0,i);\n\t\t\t\t\t\t\tgcpdatav[ittt][nrgcpnew][1] = XXd(1,i);\n\t\t\t\t\t\t\tgcpdatav[ittt][nrgcpnew][2] = XXd(2,i);\n\t\t\t\t\t\t} // for ittt\n\t\t\t\t\t\tfor (int ittt = 0; ittt < nrthreads; ++ittt)\n\t\t\t\t\t\t\tif (pitflagsv[i][ittt]) {\n\t\t\t\t\t\t\t\tfor (int vv = 0; vv < 6; ++vv)\n\t\t\t\t\t\t\t\t\tW3ijiv[ittt][vv].push_back(w3dvivv[itt][vv][ii][ittt]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t++nrgcpnew;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tgcpinfo[i] = -1;\n\t\t\t\t\t} // else\n\t\t\t\t} // for i\n\t\t\t} // for itt\n\n\n\t\t\tfor (int i = 0; i < pxs; ++i) {\n\t\t\t\tfor (int it = 0; it < nrthreads; ++it) {\n\t\t\t\t\tpxvvv[it].resize(0);\n\t\t\t\t}\n\t\t\t\tfor (int j = 0; j < (int) pointXXv[i].size(); ++j) {\n\t\t\t\t\tconst int iipi = imgindbv[pointXXv[i][j].image];\n\t\t\t\t\tpxvvv[iipi].push_back(pointXXv[i][j]);\n\t\t\t\t}\n\t\t\t\tfor (int it = 0; it < nrthreads; ++it) {\n\t\t\t\t\tif (pxvvv[it].size() > 0) {\n\t\t\t\t\t\tpointXXvv[it].push_back(pxvvv[it]);\n\t\t\t\t\t\tpindv[it].push_back(i);\n\t\t\t\t\t} // if\n\t\t\t\t} // for\n\t\t\t} // for i\n\n\t\t\tfor (int it = 0; it < nrthreads; ++it)\n\t\t\t\tgcpinfov[it].resize((int) pindv[it].size());\n\n\t\t\t#pragma omp parallel for num_threads(nrthreads)\n\t\t\tfor (int it = 0; it < nrthreads; ++it) {\n\t\t\t\tXXdd[it].resize(4,(int) pindv[it].size());\n\t\t\t\tfor (int j = 0; j < (int) pindv[it].size(); ++j) {\n\t\t\t\t\tXXdd[it].col(j) = XXd.col(pindv[it][j]);\n\t\t\t\t\tgcpinfov[it][j] = gcpinfo[pindv[it][j]];\n\t\t\t\t} // for i\n\t\t\t} // for it\n\n\t\t\tif (iter > 1) {\n\t\t\t\tif (sig0g <= sig0opt) {\n\t\t\t\t\tif (sig0opt < sig0g * sig0frac && iter > 3) { // 1.05\n\t\t\t\t\t\t--iflag;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tsig0opt = sig0g;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (iter > 3)\n\t\t\t\t\t\t--iflag;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t\tiniflag = false;\n\n\t\t\t++iter;\n\n\t\t} // while iflag\n\n\t\tpointXXvio = pointXXvold;\n\n\n\t\tfor (int i = 0; i < nrimages; ++i)\n\t\t\tPMatrices[i] = PMatricesdold[i].cast <float> ();\n\n\t\tXX = XXdold.cast <float> ();\n\n\t\tcameras = camerasold;\n\n\t\tfor (int it = 0; it < nrthreads; ++it)\n\t\t\tdelete LSAv[it];\n\n\t} // if nrimages >\n\telse {\n\n\t\tgcpflag = false;\n\n\t\tLSA *LSA1 = new LSA(cameras, addflags,\n\t\t\t\tfalse, imgind, PMatricesd, pointXXv, XXd, pxs, xg,\n\t\t\t\twx, wy, wxy, W3iji,\n\t\t\t\tgcpflag, gcpinfo, gcpdata,\n\t\t\t\tihw2, robustflag);\n\n\t\tLSA1->Adjust(robustflag, os, false, -1, W3iji, false, gcpdata);\n\n\t\tLSA1->OutputLSAc(PMatrices, pointXXvio, XX, cameras);\n\n\t\tdelete LSA1;\n\n\t} // else\n\n\n\treturn;\n} //void CalcPLSAc\n\n\n\n// Bundle adjustment for points for multiple images\nbool CalcLSAXMulti(const std::vector<Camera> &cameraps,\n\t\tconst int pi, Eigen::MatrixXd &XX,\n\t\tconst std::vector<Eigen::MatrixXf> &xg,\n\t\tconst std::vector<std::vector<float> > &wx, const std::vector<std::vector<float> > &wy,\n\t\tconst std::vector<std::vector<float> > &wxy,\n\t\tstd::vector<std::vector<IMAPNR> > &pointXXvio,\n\t\tconst std::vector<PMatd> &PMatrices,\n\t\tconst std::vector<int> &imgindbv, const int nrthreads, const std::vector<bool> &pitflags,\n\t\tstd::vector<float> &wXXv, std::vector<float> &wYYv, std::vector<float> &wZZv,\n\t\tstd::vector<float> &wXYv, std::vector<float> &wXZv, std::vector<float> &wYZv,\n\t\tdouble &sig0io, long &redundancy, std::vector<std::vector<float> > &sig0vv,\n\t\tconst std::vector<float> &sig0wv, const int robustmode, const bool weightonlyflag, const bool wxyflag) {\n\n\tint js;\n\tint iter = 1;\n\tint iflag = 1;\n\tif (robustmode > 0)\n\t\tiflag = 2;\n\tfloat sig0 = 1.e20f;\n\tfloat X0,X1,X2,Xold0,Xold1,Xold2,X0in,X1in,X2in;\n\tfloat sig0opt = 1.e20f;\n\n\tX0 = Xold0 = X0in = (float) XX(0,pi);\n\tX1 = Xold1 = X1in = (float) XX(1,pi);\n\tX2 = Xold2 = X2in = (float) XX(2,pi);\n\n\tbool convflag = false;\n\n\tconst int pxs = (int) pointXXvio[pi].size();\n\tint pxsd = pxs;\n\tint pxs2 = pxs * 2;\n\n\tstd::vector<float> p1v(pxs), p2v(pxs), p3v(pxs);\n\tstd::vector<float> wxi(pxs),wyi(pxs),wxyi(pxs),wxio(pxs),wyio(pxs),wxyio(pxs),sig0v(pxs);\n\n\tEigen::Matrix3d eNpp, eNppi;\n\tEigen::Vector3d exip;\n\tEigen::Vector2d ecorr2;\n\tEigen::Matrix<double, 2, 3> eBpp2;\n\tEigen::Matrix<double, 3, 2> eNpp12;\n\tEigen::MatrixXd eBpp2wv(2 * pxs, 3);\n\tEigen::MatrixXd eNppv;\n\n\tstd::vector<IMAPNR>::iterator pxvi;\n\tstd::vector<double> corrv(pxs2);\n\tstd::vector<bool> delf(pxs,false);\n\tfloat wsum = 0.f;\n\n\tif (wxyflag)\n\t\teNppv = Eigen::MatrixXd::Constant(nrthreads * 3, 3, -1.);\n\n\tfor(pxvi = pointXXvio[pi].begin(), js = 0; pxvi != pointXXvio[pi].end(); ++pxvi, ++js){\n\t\tconst int j = pxvi->image;\n\t\tconst int pxx = pxvi->pointnr;\n\t\twxi[js] = wxio[js] = wx[j][pxx];\n\t\twyi[js] = wyio[js] = wy[j][pxx];\n\t\twxyi[js] = wxyio[js] = wxy[j][pxx];\n\n\t\twsum += wxi[js] + wyi[js];\n\t} // for pxvi\n\n\tCalcCorrPointMulti(cameraps, X0, X1, X2, pointXXvio[pi],corrv,PMatrices,xg,\n\t\t\twxi,wyi,wxyi,wxio,wyio,wxyio,sig0opt,sig0v,p1v,p2v,p3v);\n\n\tif (weightonlyflag) {\n\t\twsum /= (float) pxs2;\n\t\tsig0io += sig0opt / wsum;\n\t\tredundancy += pxs2 - 3;\n\t}\n\n\twhile((iflag > -1) && (iter < 101)){ // 101\n\n\t\teNpp.setZero();\n\t\tif (wxyflag)\n\t\t\teNppv.setZero();\n\t\tfor(pxvi = pointXXvio[pi].begin(), js = 0; pxvi != pointXXvio[pi].end(); ++pxvi, ++js) {\n\t\t\tconst int j = pxvi->image;\n\n\t\t\tconst double x = p1v[js];\n\t\t\tconst double y = p2v[js];\n\n\t\t\tconst double P3 = p3v[js];\n\t\t\tconst double P1 = p1v[js] * p3v[js];\n\t\t\tconst double P2 = p2v[js] * p3v[js];\n\n\t\t\teBpp2(0,0) = PMatrices[j](0,0) * P3 - PMatrices[j](2,0) * P1;\n\t\t\teBpp2(0,1) = PMatrices[j](0,1) * P3 - PMatrices[j](2,1) * P1;\n\t\t\teBpp2(0,2) = PMatrices[j](0,2) * P3 - PMatrices[j](2,2) * P1;\n\t\t\teBpp2(1,0) = PMatrices[j](1,0) * P3 - PMatrices[j](2,0) * P2;\n\t\t\teBpp2(1,1) = PMatrices[j](1,1) * P3 - PMatrices[j](2,1) * P2;\n\t\t\teBpp2(1,2) = PMatrices[j](1,2) * P3 - PMatrices[j](2,2) * P2;\n\n\n\t\t\tCalcCalibratedDerivatives(eBpp2(0,0), eBpp2(1,0), eBpp2(0,1), eBpp2(1,1), eBpp2(0,2), eBpp2(1,2),\n\t\t\t\t\tx, y, cameraps[j].distpara[0], cameraps[j].distpara[1],\n\t\t\t\t\tcameraps[j].K(0,0), cameraps[j].K(1,1), cameraps[j].K(0,1));\n\n\t\t\tconst int js2 = 2 * js;\n\t\t\tconst int js21 = js2 + 1;\n\t\t\teBpp2wv(js2,0) = eBpp2(0,0) * wxi[js] + eBpp2(1,0) * wxyi[js];\n\t\t\teBpp2wv(js21,0) = eBpp2(1,0) * wyi[js] + eBpp2(0,0) * wxyi[js];\n\t\t\teBpp2wv(js2,1) = eBpp2(0,1) * wxi[js] + eBpp2(1,1) * wxyi[js];\n\t\t\teBpp2wv(js21,1) = eBpp2(1,1) * wyi[js] + eBpp2(0,1) * wxyi[js];\n\t\t\teBpp2wv(js2,2) = eBpp2(0,2) * wxi[js] + eBpp2(1,2) * wxyi[js];\n\t\t\teBpp2wv(js21,2) = eBpp2(1,2) * wyi[js] + eBpp2(0,2) * wxyi[js];\n\n\t\t\teNpp.noalias() += eBpp2.transpose() * eBpp2wv.block<2,3>(js2,0);\n\n\t\t\tif (wxyflag) {\n\t\t\t\tif (nrthreads == 1)\n\t\t\t\t\tcontinue;\n\t\t\t\telse { // if (nn0flag) {\n\t\t\t\t\tconst int ij = imgindbv[j];\n\t\t\t\t\tfor (int i = 0; i < nrthreads; ++i)\n\t\t\t\t\t\tif (pitflags[i] && i != ij) {\n\t\t\t\t\t\t\teNppv.block<3,3>(3 * i,0).noalias() += eBpp2.transpose() * eBpp2wv.block<2,3>(js * 2,0);\n\t\t\t\t\t\t}\n\t\t\t\t} // else\n\t\t\t}\n\n\t\t}\n\n\t\tif (wxyflag) {\n\t\t\tif (nrthreads == 1) {\n\t\t\t\teNppv = eNpp;\n\t\t\t}\n\t\t}\n\n\t\tconst double m1 = 1.001;\n\n\t\teNpp(0,0) *= m1;\n\t\teNpp(1,1) *= m1;\n\t\teNpp(2,2) *= m1;\n\n\t\teNppi = eNpp.inverse();\n\n\t\texip.setZero();\n\t\tfor (int i = 0; i < pxs; ++i) {\n\t\t\tecorr2(0) = corrv[i * 2];\n\t\t\tecorr2(1) = corrv[i * 2 + 1];\n\n\t\t\texip.noalias() += eNppi * eBpp2wv.block<2,3>(i * 2,0).transpose() * ecorr2;\n\t\t}\n\n\t\tX0 = Xold0 + (float) exip(0);\n\t\tX1 = Xold1 + (float) exip(1);\n\t\tX2 = Xold2 + (float) exip(2);\n\n\t\tCalcCorrPointMulti(cameraps, X0, X1, X2, pointXXvio[pi],corrv,PMatrices,xg,\n\t\t\t\twxi,wyi,wxyi,wxio,wyio,wxyio,sig0,sig0v,p1v,p2v,p3v);\n\n\t\tif (iflag == 1 && robustmode == 2) {\n\t\t\tfor(pxvi = pointXXvio[pi].begin(), js = 0; pxvi != pointXXvio[pi].end(); ++pxvi, ++js) {\n\t\t\t\tif (sig0v[js] * sig0wv[pxvi->image] > 16.f) {\n\t\t\t\t\twxi[js] *= 1.e-4f;\n\t\t\t\t\twyi[js] *= 1.e-4f;\n\t\t\t\t\twxyi[js] *= 1.e-4f;\n\t\t\t\t\tif (wxi[js] + wyi[js] < 2.e-8f) {\n\t\t\t\t\t\twxi[js] = wyi[js] = 1.e-8f;\n\t\t\t\t\t\twxyi[js] = 0.f;\n\t\t\t\t\t}\n\t\t\t\t\t--pxsd;\n\t\t\t\t\tdelf[js] = true;\n\t\t\t\t} // if sig0v\n\t\t\t} // for pxvi\n\t\t\tif (pxsd < 2)\n\t\t\t\tbreak;\n\t\t} // if robustflag\n\n\t\tif (sig0 < sig0opt * 1.001) {\n\t\t\tif (sig0opt < sig0 * 1.05f) // 1.01f\n\t\t\t\t--iflag;\n\t\t\tif (!weightonlyflag) {\n\t\t\t\tXX(0,pi) = Xold0 = X0;\n\t\t\t\tXX(1,pi) = Xold1 = X1;\n\t\t\t\tXX(2,pi) = Xold2 = X2;\n\t\t\t}\n\t\t\tsig0opt = sig0;\n\t\t\tconvflag = true;\n\t\t\tif (wxyflag) {\n\t\t\t\tfor (int i = 0; i < nrthreads; ++i) {\n\t\t\t\t\tconst int i3 = 3 * i;\n\t\t\t\t\tconst int i31 = i3 + 1;\n\t\t\t\t\twXXv[i] = (float) eNppv(i3,0);\n\t\t\t\t\twYYv[i] = (float) eNppv(i31,1);\n\t\t\t\t\twZZv[i] = (float) eNppv(i3 + 2,2);\n\t\t\t\t\twXYv[i] = (float) eNppv(i3,1);\n\t\t\t\t\twXZv[i] = (float) eNppv(i3,2);\n\t\t\t\t\twYZv[i] = (float) eNppv(i31,2);\n\t\t\t\t}\n\t\t\t}\n\t\t} //if sig0\n\t\telse {\n\t\t\t--iflag;\n\t\t}\n\n\t\tif (weightonlyflag)\n\t\t\tbreak;\n\n\t\t++iter;\n\t} //while iflag\n\n\n\tif (robustmode == 1) {\n\t\tfor(pxvi = pointXXvio[pi].begin(), js = 0; pxvi != pointXXvio[pi].end(); ++pxvi, ++js)\n\t\t\tsig0vv[pxvi->image].push_back(sig0v[js]);\n\t} // if robustmode\n\n\tif (robustmode == 2) {\n\t\tstd::vector<int> delv;\n\t\tfor (int i = 0; i < pxs; ++i)\n\t\t\tif (delf[i])\n\t\t\t\tdelv.push_back(i);\n\t\tif ((int) delv.size() > 0) {\n\t\t\tpxs2 -= (int) delv.size() * 2;\n\t\t\tfor (int i = (int)(delv.size()) - 1; i > -1; --i) {\n\t\t\t\tpointXXvio[pi].erase(pointXXvio[pi].begin() + delv[i]);\n\t\t\t}\n\t\t}\n\t} // if robustmode\n\n\tif (pointXXvio[pi].size() < 2 || !convflag) {\n\t\tpointXXvio[pi].clear();\n\t\tconvflag = false;\n\t\tXX(0,pi) = X0in;\n\t\tXX(1,pi) = X1in;\n\t\tXX(2,pi) = X2in;\n\t}\n\telse {\n\t\tif (!weightonlyflag) {\n\t\t\twsum /= (float) pxs2;\n\t\t\tsig0io += sig0opt / wsum;\n\t\t\tredundancy += pxs2 - 3;\n\t\t}\n\t}\n\n\treturn(convflag);\n} // bool CalcLSAXMulti\n\n\n\n// Computation of corrections for bundle adjustment for points only for multi image case\nvoid CalcCorrPointMulti(const std::vector<Camera> &cameraps,\n\t\tconst double X0, const double X1, const double X2,\n\t\tstd::vector<IMAPNR> &pxv,\n\t\tstd::vector<double> &corrv,\n\t\tconst std::vector<PMatd> &PM,\n\t\tconst std::vector<Eigen::MatrixXf> &xg,\n\t\tconst std::vector<float> &wx, const std::vector<float> &wy, const std::vector<float> &wxy,\n\t\tconst std::vector<float> &wxo, const std::vector<float> &wyo, const std::vector<float> &wxyo,\n\t\tfloat &sig0, std::vector<float> &sig0v,\n\t\tstd::vector<float> &p1v, std::vector<float> &p2v, std::vector<float> &p3v){\n\n\tint js;\n\n\tsig0 = 0;\n\tstd::vector<IMAPNR>::iterator pxvi;\n\tfor(pxvi = pxv.begin(), js = 0; pxvi != pxv.end(); ++pxvi, ++js){\n\t\tconst int j = pxvi->image;\n\t\tconst int pxx = pxvi->pointnr;\n\t\tconst int js2 = js * 2;\n\n//\t\tif (fabs(PM[j](0,3)) > 1.e5 || fabs(PM[j](1,3)) > 1.e5 || fabs(PM[j](2,3)) > 1.e5)\n//\t\t\tcontinue;\n\n\t\tdouble p1 = PM[j](0,0) * X0 + PM[j](0,1) * X1 + PM[j](0,2) * X2 + PM[j](0,3);\n\t\tdouble p2 = PM[j](1,0) * X0 + PM[j](1,1) * X1 + PM[j](1,2) * X2 + PM[j](1,3);\n\t\tdouble p3 = PM[j](2,0) * X0 + PM[j](2,1) * X1 + PM[j](2,2) * X2 + PM[j](2,3);\n\n\t\tif (fabs(p3) < 1.e-3) {\n\t\t\tif (p3 > 0.)\n\t\t\t\tp3 = 1.e3;\n\t\t\telse\n\t\t\t\tp3 = -1.e3;\n\t\t}\n\t\telse\n\t\t\tp3 = 1. / p3;\n\n\t\tp1 *= p3;\n\t\tp2 *= p3;\n\n\t\tp1v[js] = (float) p1;\n\t\tp2v[js] = (float) p2;\n\t\tp3v[js] = (float) p3;\n\n\t\tRadialReconstructionImage(p1, p2, cameraps[j]);\n\n\t\tp1 *= cameraps[j].K(0,0);\n\t\tp2 *= cameraps[j].K(0,0);\n\n\t\tconst double dx = xg[j](0,pxx) - p1;\n\t\tconst double dy = xg[j](1,pxx) - p2;\n\n\t\tcorrv[js2] = dx;\n\t\tcorrv[js2 + 1] = dy;\n\t\tconst float sig0i = (float) (dx * dx * wx[js] + dy * dy * wy[js] + 2 * dx * dy * wxy[js]);\n\t\tsig0 += sig0i;\n\t\tsig0v[js] = (float) (dx * dx * wxo[js] + dy * dy * wyo[js] + 2 * dx * dy * wxyo[js]);\n\t}\n\n\treturn;\n} //void CalcCorrPointMulti\n\n\n\nvoid CalcCalibratedDerivatives(double &xp0, double &yp0, double &xp1, double &yp1, double &xp2, double &yp2,\n\t\tconst double x, const double y, const double k2, const double k4,\n\t\tconst double fx, const double fy, const double s) {\n\n\tconst double xpo0 = xp0;\n\tconst double ypo0 = yp0;\n\tconst double xpo1 = xp1;\n\tconst double ypo1 = yp1;\n\tconst double xpo2 = xp2;\n\tconst double ypo2 = yp2;\n\n\tconst double xy2 = x * x + y * y;\n\tconst double xy4 = xy2 * xy2;\n\n\tconst double xxpc = k4 * xy4 + x * (2 * k2 * x + 4 * k4 * x * xy2) + k2 * xy2 + 1.;\n\tconst double xypc = x * (4 * k4 * xy2 * y + 2 * k2 * y);\n\tconst double yxpc = y * (4 * k4 * x * xy2 + 2 * k2 * x);\n\tconst double yypc = y * (2 * k2 * y + 4 * k4 * xy2 * y) + k4 * xy4 + k2 * xy2 + 1.;\n\n\txp0 = (xxpc * xpo0 + xypc * ypo0);\n\typ0 = (yypc * ypo0 + yxpc * xpo0);\n\txp0 = xp0 * fx + yp0 * s;\n\typ0 *= fy;\n\n\txp1 = (xxpc * xpo1 + xypc * ypo1);\n\typ1 = (yypc * ypo1 + yxpc * xpo1);\n\txp1 = xp1 * fx + yp1 * s;\n\typ1 *= fy;\n\n\n\txp2 = (xxpc * xpo2 + xypc * ypo2);\n\typ2 = (yypc * ypo2 + yxpc * xpo2);\n\txp2 = xp2 * fx + yp2 * s;\n\typ2 *= fy;\n\n\treturn;\n} // CalcCalibratedDerivatives\n\n\n\n// Evaluation of bundle adjustment for calibrated images\nvoid EvalLSA(const int nraddp, const std::vector<Camera> &cameraps,\n\t\tconst Eigen::MatrixXd &XXd,\n\t\tconst std::vector<Eigen::MatrixXf> &xg,\n\t\tconst std::vector<std::vector<float> > &wxi, const std::vector<std::vector<float> > &wyi,\n\t\tconst std::vector<std::vector<float> > &wxyi,\n\t\tstd::vector<std::vector<IMAPNR> > &pointXXv,\n\t\tconst std::vector<PMatd> &PMatricesd,\n\t\tconst float ihw2) {\n\n\tlong redundancy = 0;\n\tlong nrobs = 0;\n\tfloat sig0g = 0.f;\n\tint ii,jj;\n\tconst int nrimages =  (int) PMatricesd.size();\n\tstd::vector<std::vector<IMAPNR> >::iterator pxv;\n\tstd::vector<IMAPNR>::iterator pxvi;\n\tstd::vector<float> p1v,p2v,p3v;\n\n\tfor (pxv = pointXXv.begin(), ii = 0; pxv != pointXXv.end(); ++pxv, ++ii) {\n\t\tconst int pxss = (int) pxv->size();\n\t\tconst int pxss2 = pxss * 2;\n\n\t\tp1v.resize(pxss);\n\t\tp2v.resize(pxss);\n\t\tp3v.resize(pxss);\n\n\t\tif (pxss > 1) {\n\t\t\tstd::vector<float> wxii(pxss),wyii(pxss),wxyii(pxss),sig0v(pxss);\n\t\t\tstd::vector<double> corrv(pxss2);\n\t\t\tfloat wsum = 0.f;\n\t\t\tfloat sig0optf;\n\t\t\tint js,pxx;\n\t\t\tfor(pxvi = pxv->begin(), js = 0; pxvi != pxv->end(); ++pxvi, ++js) {\n\t\t\t\tjj = pxvi->image;\n\t\t\t\tpxx = pxvi->pointnr;\n\t\t\t\twxii[js] = wxi[jj][pxx];\n\t\t\t\twyii[js] = wyi[jj][pxx];\n\t\t\t\twxyii[js] = wxyi[jj][pxx];\n\n\t\t\t\twsum += wxii[js] + wyii[js];\n\t\t\t} // for pxvi\n\n\t\t\twsum = wsum / (float) pxss2;\n\n\t\t\tstd::vector<bool> pitflags(1);\n\t\t\tstd::vector<int> imgindbv;\n\t\t\tCalcCorrPointMulti(cameraps, XXd(0,ii), XXd(1,ii), XXd(2,ii), (*pxv),corrv,PMatricesd,xg,\n\t\t\t\t\twxii,wyii,wxyii,wxii,wyii,wxyii,sig0optf,sig0v,p1v,p2v,p3v);\n\t\t\tsig0g += sig0optf / wsum;\n\t\t\tredundancy += pxss2 - 3;\n\t\t\tnrobs += pxss2;\n\t\t} // if pxss\n\t} // for pxv\n\n\tsig0g *= 1.f / (float) (redundancy - (nrimages - 2) * 6 - 5 - nrimages * nraddp);\n\n\tstd::cout << \"ITTTT: \" << sqrtf(sig0g * ihw2) << ' ' << nrobs << \" \" << redundancy - (nrimages - 2) * 6 - 5 - nrimages * nraddp << '\\n';\n\n\treturn;\n} // EvalLSA\n\n\n\nvoid PartitionpointXXv(std::vector<std::vector<IMAPNR> > &pointXXv, const int nrimages,\n\t\tconst int nrthreads, std::vector<idx_t> &part,\n\t\tstd::vector<std::vector<int> > &imagesperpart)\n{\n  const int minpointnr = 0; // minimum number of points used for the graph\n\n\n  const System::Time startp = System::getTickCount();\n\n\n  std::vector<std::vector<int> > AM(nrimages);\n  std::vector<int> BM(nrimages,0);\n  for (int i = 0; i < nrimages; ++i) {\n\t  AM[i].resize(nrimages);\n\t  for (int j = 0; j < nrimages; ++j)\n\t  \t  AM[i][j] = 0;\n\t  } // for i\n\n  std::vector<std::vector<IMAPNR> >::iterator pxv;\n  std::vector<IMAPNR>::iterator pxvi,pxvj;\n\n  for (pxv = pointXXv.begin(); pxv != pointXXv.end(); ++pxv) {\n\t  if ((int) pxv->size() < 2)\n\t\t  continue;\n\t  for (pxvi = pxv->begin(); pxvi != pxv->end(); ++pxvi) {\n\t\t  const int fi = pxvi->image;\n\t\t  BM[fi] += (int) pxv->size();\n\t\t  for (pxvj = pxvi + 1; pxvj != pxv->end(); ++pxvj) {\n\t\t\t  const int si = pxvj->image;\n\t\t\t  ++AM[fi][si];\n\t\t\t  ++AM[si][fi];\n\t\t  }\n\t  }\n  }\n\n  int nredges = 0;\n  for (int i = 0; i < nrimages; ++i) {\n\t  for (int j = 0; j < nrimages; ++j) {\n\t\t  if (AM[i][j] > minpointnr)\n\t\t\t  ++nredges;\n\t  }\n  }\n\n  std::vector<idx_t> xadj(nrimages + 1), adjncy(nredges), vwgt(nrimages);\n  xadj[0] = 0;\n\n  int indexadj = -1;\n  for (int i = 0; i < nrimages; ++i) {\n\n    int nrconn = 0;\n    for (int j = 0; j < nrimages; ++j)\n    \tif (AM[i][j] > minpointnr) {\n    \t\tadjncy[++indexadj] = j;\n    \t\t++nrconn;\n    \t}\n\n    xadj[i+1] = xadj[i] + nrconn;\n    vwgt[i] = (idx_t) pow(BM[i],0.3333);\n  } // for\n\n\n  std::cout << \"Preparation time: \" << (float) (System::getTickCount()-startp) / 1000.f << \"s\\n\";\n\n  idx_t nrparts = nrthreads;\n  idx_t inrimages = nrimages;\n  idx_t edgecut;\n\n  idx_t options[METIS_NOPTIONS];\n  METIS_SetDefaultOptions(options);\n  options[METIS_OPTION_CONTIG] = 1;\n\n  // One constraint\n  idx_t ncon = 1;\n\n  METIS_PartGraphRecursive(&inrimages, &ncon, &xadj[0], &adjncy[0],\n\t\t  &vwgt[0], nullptr, nullptr, &nrparts, nullptr,\n\t\t  nullptr, &options[0], &edgecut, &part[0]);\n\n\n  std::cout << \"After partitioning: \" << (float) (System::getTickCount()-startp) / 1000.f << \"s\\n\\n\";\n\n  for (int i = 0; i < nrimages; ++i)\n\t  imagesperpart[part[i]].push_back(i);\n\n  std::cout << \"Images per partition: \";\n  for (int it = 0; it < nrthreads; ++it)\n\t  std::cout << imagesperpart[it].size() << ' ';\n  std::cout << '\\n';\n\n  std::cout << \"After analysis of parts: \" << (float) (System::getTickCount()-startp) / 1000.f << \"s\\n\";\n\n  return;\n} // PartitionpointXXv\n", "meta": {"hexsha": "a4f028e4a2d2d294f9fcdb76e3c6e4715e60b4a7", "size": 30484, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rpbacore.cpp", "max_stars_repo_name": "helmayer/RPBA", "max_stars_repo_head_hexsha": "6b399693671ba75d37b472880a1bf967d82f9e67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 57.0, "max_stars_repo_stars_event_min_datetime": "2019-10-21T16:50:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T03:57:04.000Z", "max_issues_repo_path": "rpbacore.cpp", "max_issues_repo_name": "helmayer/RPBA", "max_issues_repo_head_hexsha": "6b399693671ba75d37b472880a1bf967d82f9e67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-11-19T12:48:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T07:22:56.000Z", "max_forks_repo_path": "rpbacore.cpp", "max_forks_repo_name": "helmayer/RPBA", "max_forks_repo_head_hexsha": "6b399693671ba75d37b472880a1bf967d82f9e67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-10-25T04:36:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-25T02:38:03.000Z", "avg_line_length": 29.3680154143, "max_line_length": 460, "alphanum_fraction": 0.5837160478, "num_tokens": 12044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961013, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.26754760904809805}}
{"text": "/**\n * vi:ts=4:shiftwidth=4:expandtab\n * vim600:fdm=marker\n *\n * maxentmodel.hpp  -  A Conditional Maximun Entropy Model\n *\n * Copyright (C) 2003 by Zhang Le <ejoy@users.sourceforge.net>\n * Begin       : 01-Jan-2003\n * Last Change : 08-Feb-2012.\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\n * GNU 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 program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n */\n\n#ifndef MAXENTMODEL_H\n#define MAXENTMODEL_H\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include <vector>\n#include <utility>\n#include <boost/utility.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/shared_array.hpp>\n#include <ostream>\n#include <iostream>\n\n#include \"itemmap.hpp\"\n#include \"meevent.hpp\"\n\nnamespace boost {\n    class timer;\n}\n\n/**\n * All classes and functions are placed in the namespace maxent.\n */\nnamespace maxent {\nusing namespace std;\nusing boost::shared_ptr;\nusing boost::shared_array;\n\nextern int verbose;  // set this to 0 if you do not want verbose output\n\nstruct maxent_pickle_suite;\n/**\n * This class implements a conditional Maximun Entropy Model.\n *\n * A conditional Maximun Entropy Model (also called log-linear model)has the\n * form:\n * \\f$p(y|x)=\\frac{1}{Z(x)} \\exp \\left[\\sum_{i=1}^k\\lambda_if_i(x,y) \\right]\\f$\n * Where x is a context and y is the outcome tag and p(y|x) is the conditional\n * probability.\n *\n * Normally the context x is composed of a set of contextual predicates.\n */\nclass MaxentModel /*: TODO: we need copyable? boost::noncopyable*/  {\n    friend struct maxent_pickle_suite;\n\n    // private:\n    // virtual ~MaxentModel();\n\n    public:\n//    typedef std::string feature_type;\n//    typedef std::string outcome_type;\n    typedef me::feature_type feature_type;\n    typedef me::feature_type outcome_type;\n    typedef std::vector<pair<feature_type, float> > context_type;\n\n    MaxentModel();\n\n    void load(const string& model);\n\n    void save(const string& model, bool binary = false) const;\n\n    double eval(const context_type& context, const outcome_type& outcome) const;\n\n    void eval_all(const context_type& context,\n            std::vector<pair<outcome_type, double> >& outcomes,\n            bool sort_result = true) const;\n\n    outcome_type predict(const context_type& context) const;\n\n    void begin_add_event();\n\n    void add_event(const context_type& context,\n            const outcome_type& outcome,\n            size_t count = 1);\n\n    void add_heldout_event(const context_type& context,\n            const outcome_type& outcome,\n            size_t count = 1);\n\n    // wrapper functions for binary feature cases, provided for conviences\n    void add_event(const vector<string>& context,\n            const outcome_type& outcome,\n            size_t count = 1);\n\n    void add_heldout_event(const vector<string>& context,\n            const outcome_type& outcome,\n            size_t count = 1);\n\n    double eval(const vector<string>& context, \n            const outcome_type& outcome) const;\n\n    void eval_all(const vector<string>& context,\n            std::vector<pair<outcome_type, double> >& outcomes,\n            bool sort_result = true) const;\n\n    outcome_type predict(const vector<string>& context) const;\n\n    /**\n     * Add a set of events indicated by range [begin, end).\n     * the value type of Iterator must be pair<context_type, outcome_type>\n     */\n    template <typename Iterator>\n        void add_events(Iterator begin, Iterator end) {\n            for (Iterator it = begin; it != end; ++it)\n                this->add_event(it->first, it->second);\n        }\n\n\n    void end_add_event(size_t cutoff = 1);\n\n    void train(size_t iter = 15, const std::string& method = \"lbfgs\",\n            double sigma2 = 0.0, // non-zero enables Gaussian prior smoothing (global variance sigma^2)\n            double tol = 1E-05);\n\n     void dump_events(const string& model, bool binary = false) const;\n\n    const char* __str__() const; // python __str__() \n\n    // Python binding related functions {{{\n#if defined(PYTHON_MODULE)\n\n    // return the whole probabistic distribution [(outcome1, prob1),\n    // (outcome2, prob2), ...] for a given context\n    std::vector<pair<outcome_type, double> > py_eval(const context_type& context) const {\n        static std::vector<pair<outcome_type, double> > outcomes;\n        eval_all(context, outcomes);\n        return outcomes;\n    }\n#endif\n    // end py binding }}}\n\n    private:\n    double build_params(shared_ptr<me::ParamsType>& params, \n            size_t& n_theta) const;\n    double build_params2(shared_ptr<me::ParamsType>& params, \n            size_t& n_theta) const;\n\n            struct featid_hasher {\n                size_t operator()(const pair<size_t, size_t>& p) const {\n                    return p.first + p.second;\n                }\n            };\n\n\n    struct cutoffed_event {\n        cutoffed_event(size_t cutoff):m_cutoff(cutoff) {}\n        bool operator()(const me::Event& ev) const {\n            return ev.m_count < m_cutoff;\n        }\n        size_t m_cutoff;\n    };\n\n    struct cmp_outcome {\n        bool operator()(const pair<outcome_type, double>& lhs,\n                const pair<outcome_type, double>& rhs) const {\n            return lhs.second > rhs.second;\n        }\n    };\n\n    size_t m_n_theta;\n    shared_ptr<me::MEEventSpace> m_es;\n    shared_ptr<me::MEEventSpace> m_heldout_es;\n    shared_ptr<me::PredMapType> m_pred_map;\n    shared_ptr<me::OutcomeMapType> m_outcome_map;\n    shared_ptr<me::ParamsType> m_params;\n    shared_array<double> m_theta; // feature weights\n\n    shared_ptr<boost::timer> m_timer;\n\n    struct param_hasher {\n        size_t operator()(const pair<size_t,size_t>& v) const {\n            return size_t(~(v.first<< 1) + v.second);\n        }\n    };\n};\n\n#if defined(OLD_PYTHON_MODULE) //{{{ old python pickle support through Boost.Python\nstruct maxent_pickle_suite : boost::python::pickle_suite {\n    static boost::python::tuple getstate(const MaxentModel& m)\n    {\n        if (!m.m_params)\n            throw runtime_error(\"can not get state from empty model\");\n        using namespace boost::python;\n        boost::python::list state;\n        size_t i;\n\n        shared_ptr<me::PredMapType> pred_map = m.m_pred_map;\n        shared_ptr<me::OutcomeMapType> outcome_map = m.m_outcome_map;\n        shared_ptr<me::ParamsType> params = m.m_params;\n        size_t n_theta = m.m_n_theta;\n        shared_array<double> theta = m.m_theta;\n\n        // save pred_map\n        state.append(pred_map->size());\n        for (i = 0;i < pred_map->size(); ++i)\n            state.append((*pred_map)[i]);\n\n        // save outcome_map\n        state.append(outcome_map->size());\n        for (i = 0;i < outcome_map->size(); ++i)\n            state.append((*outcome_map)[i]);\n\n        // save params\n        state.append(n_theta);\n        assert(params->size() == pred_map->size());\n        for (i = 0;i < params->size(); ++i) {\n            boost::python::list oids;\n            boost::python::list t;\n            const std::vector<pair<size_t, size_t> >& a = (*params)[i];\n            for (size_t j = 0; j < a.size(); ++j) {\n                oids.append(a[j].first);\n                t.append(a[j].second);\n            }\n            state.append(make_tuple(oids, t));\n        }\n        // save theta\n        for (i = 0;i < n_theta; ++i)\n            state.append(theta[i]);\n        return boost::python::tuple(state);\n    }\n\n    static void setstate(MaxentModel& m, boost::python::tuple state)\n    {\n        using namespace boost::python;\n        assert (!m.m_pred_map);\n        assert (!m.m_outcome_map);\n        assert (!m.m_params);\n        assert (len(state) > 0);\n\n        shared_ptr<me::PredMapType> pred_map(new me::PredMapType);\n        shared_ptr<me::OutcomeMapType> outcome_map(new me::OutcomeMapType);\n        shared_ptr<me::ParamsType> params(new me::ParamsType);\n        size_t n_theta;\n        shared_array<double> theta;\n\n        size_t count;\n        size_t i;\n        size_t index = 0;\n\n        // load pred_map\n        count = extract<size_t>(state[index++]);\n        for (i = 0; i < count; ++i)\n            pred_map->add(extract<std::string>(state[index++]));\n\n        // load outcome_map\n        count = extract<size_t>(state[index++]);\n        for (i = 0; i < count; ++i)\n            outcome_map->add(extract<std::string>(state[index++]));\n\n        // load params\n        n_theta = extract<size_t>(state[index++]);\n        for (i = 0; i < pred_map->size(); ++i) {\n            tuple tmp(state[index++]);\n            boost::python::list oids(tmp[0]);\n            boost::python::list t(tmp[1]);\n            std::vector<pair<size_t, size_t> > a;\n\n            size_t k = extract<size_t>(oids.attr(\"__len__\")());\n            assert (k == len(t));\n\n            for (size_t j = 0; j < k; ++j) {\n                size_t oid = extract<size_t>(oids[j]);\n                size_t fid = extract<size_t>(t[j]);\n                a.push_back(std::make_pair(oid, fid));\n            }\n            params->push_back(a);\n        }\n        // extract theta\n        theta.reset(new double[n_theta]);\n        for (i = 0;i < n_theta; ++i)\n            theta[i] = extract<double>(state[index++]);\n        m.m_pred_map = pred_map;\n        m.m_outcome_map = outcome_map;\n        m.m_params = params;\n        m.m_n_theta = n_theta;\n        m.m_theta = theta;\n    }\n};\n#endif // PYTHON_MODULE }}}\n\n} // namespace maxent\n#endif /* ifndef MAXENTMODEL_H */\n\n", "meta": {"hexsha": "715ae713a07217f8498635dd37be3e1641804184", "size": 9951, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/idmlib/maxent/maxentmodel.hpp", "max_stars_repo_name": "izenecloud/idmlib", "max_stars_repo_head_hexsha": "ec6afd44490170a70ef980afa6d21fba8c77ed9d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-11-14T06:37:25.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-14T06:37:25.000Z", "max_issues_repo_path": "include/idmlib/maxent/maxentmodel.hpp", "max_issues_repo_name": "izenecloud/idmlib", "max_issues_repo_head_hexsha": "ec6afd44490170a70ef980afa6d21fba8c77ed9d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/idmlib/maxent/maxentmodel.hpp", "max_forks_repo_name": "izenecloud/idmlib", "max_forks_repo_head_hexsha": "ec6afd44490170a70ef980afa6d21fba8c77ed9d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-09-06T05:59:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-17T06:11:24.000Z", "avg_line_length": 31.9967845659, "max_line_length": 103, "alphanum_fraction": 0.6175258768, "num_tokens": 2424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.26754760904809805}}
{"text": "// default libraries\n#include \"algorithm\"\n#include \"iomanip\"\n#include \"iostream\"\n#include \"fstream\"\n#include \"string\"\n\n// boost\n#include \"boost/array.hpp\"\n#include \"boost/foreach.hpp\"\n#include \"boost/lexical_cast.hpp\"\n#include \"boost/mpi.hpp\"\n#include \"boost/unordered_set.hpp\"\n\n// load balancing\n#include \"zoltan.h\"\n\n// adaptive grid (loaded with pragmas to avoid error spam)\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\n// vector calculus\n#include <Eigen/Dense>\n\n// own header files\n#include \"cell.hpp\" // Cell class for individual grid cells\n#include \"comm.hpp\" // Domain decomposition communications\n#include \"inject.hpp\" // Particle initializer & injector\n#include \"mesh.hpp\" // Mesh and field related functions\n#include \"field.hpp\" // actual field propagators\n#include \"parameters.hpp\" // simulation variables\n#include \"common.h\" // simulation variables\n#include \"particles.hpp\" // particle spatial & momentum pushers\n#include \"io.hpp\" // Simulation saver\n\n\n// name spaces\nusing namespace std;\nusing namespace boost;\nusing namespace boost::mpi;\nusing namespace dccrg;\nusing namespace Eigen;\n\n\n/// rank-specific switch for MPI data transfers\nint Cell::transfer_mode = Cell::INIT;\n\n\n// Vector and Matrix calculus type definitions\ntypedef Array<double, 4, 1> Vectord4;\ntypedef Array<double, 4, 4> Matrixd44;\ntypedef Array<double, 3, 2> Matrixd32; ///< old compatibility type\n\n\ntypedef Parameters P;\n\n\n/// Underlying adaptive grid framework\nstatic Dccrg<Cell, dccrg::Cartesian_Geometry> mpiGrid;\n\n/** Get local cell IDs. This function creates a cached copy of the \n * cell ID lists to significantly improve performance. The cell ID \n * cache is recalculated every time the mesh partitioning changes.\n * @return Local cell IDs.*/\nconst std::vector<CellID>& getLocalCells() {\n   return P::localCells;\n}\n\n/// Recalculate the cell listing\nvoid recalculateLocalCellsCache() {\n     {\n        vector<CellID> dummy;\n        dummy.swap(P::localCells);\n     }\n   P::localCells = mpiGrid.get_cells();\n}\n\n\nint main(int argc, char* argv[])\n{\n\n\n    cout << \"Starting...\" << endl;\n\n    // Start up MPI\n\tif (MPI_Init(&argc, &argv) != MPI_SUCCESS) {\n\t\tcerr << \"Couldn't initialize MPI.\" << endl;\n\t\tabort();\n\t}\n\tMPI_Comm communicator = MPI_COMM_WORLD;\n\n\tint rank = 0, comm_size = 0;\n\tMPI_Comm_rank(communicator, &rank);\n\tMPI_Comm_size(communicator, &comm_size);\n\n    // create also communicator object\n    Comm comm(rank, comm_size, communicator);\n    cout << rank << \": Initialized MPI...\" << endl;\n\n\n    if(rank == 0) {\n        cout << \"--------------------------------------------------\" << endl;\n        cout << \" Simulation parameters \"<< endl;\n        cout << \"    c: \" << c << endl;\n        cout << \"    e: \" << e << endl;\n        cout << \"   dt: \" << P::dt << endl;\n        cout << \"   me: \" << me << endl;\n        cout << \"   mp: \" << mp << endl;\n\n        cout << \" ----  \" << endl;\n\n        cout << \"   Nx: \" << P::Nx << endl;\n        cout << \"   Ny: \" << P::Ny << endl;\n        cout << \"   Nz: \" << P::Nz << endl;\n        cout << \" xmin: \" << P::grid_xmin << endl;\n        cout << \" xmax: \" << P::grid_xmax << endl;\n        cout << \" ymin: \" << P::grid_ymin << endl;\n        cout << \" ymax: \" << P::grid_ymax << endl;\n        cout << \" zmin: \" << P::grid_zmin << endl;\n        cout << \" zmax: \" << P::grid_zmax << endl;\n        cout << \"--------------------------------------------------\" << endl;\n    } \n\n\n    // print rank, PID, and hostname\n    char hostname[256];\n    gethostname(hostname, sizeof(hostname));\n    cout << rank << \": PID:\" << ::getpid() << \" host:\" << hostname << endl;\n\n\n\n\t// initialize Zoltan\n\tfloat zoltan_version;\n\tif (Zoltan_Initialize(argc, argv, &zoltan_version) != ZOLTAN_OK) {\n\t\tcerr << \"Zoltan_Initialize failed\" << endl;\n\t\tabort();\n\t}\n    cout << rank << \": Initialized Zoltan...\" << endl;\n\n\n    // initialize grid spatial scales\n    dccrg::Cartesian_Geometry::Parameters geom_params;\n\n\tconst std::array<uint64_t, 3> grid_length = {{P::Nx, P::Ny, P::Nz}};\n\tmpiGrid.initialize(grid_length, \n                    communicator, \n                    \"RCB\", \n                    P::N_neighb, \n                    P::max_ref_lvl, \n                    P::Nx_wrap, P::Ny_wrap, P::Nz_wrap);\n\n    geom_params.start[0] = P::grid_xmin;\n    geom_params.start[1] = P::grid_ymin;\n    geom_params.start[2] = P::grid_zmin;\n\n    geom_params.level_0_cell_length[0] = abs(P::grid_xmax - P::grid_xmin)/double(P::Nx);\n    geom_params.level_0_cell_length[1] = abs(P::grid_ymax - P::grid_ymin)/double(P::Ny);\n    geom_params.level_0_cell_length[2] = abs(P::grid_zmax - P::grid_zmin)/double(P::Nz);\n\n    if (!mpiGrid.set_geometry(geom_params)) {\n\t\tcerr << __FILE__ << \":\" << __LINE__ << \": Couldn't set mpiGrid geometry\" << endl;\n\t\tabort();\n\t}\n\n\n    // Neighborhoods\n    //-------------------------------------------------- \n    typedef dccrg::Types<3>::neighborhood_item_t neigh_t;\n\n    // shift with +1/+1/+1 elements\n    std::vector<neigh_t> neighborhood;\n    neighborhood.clear(); \n    neighborhood.push_back({{1,0,0}});\n    neighborhood.push_back({{0,1,0}});\n    neighborhood.push_back({{0,0,1}});\n\n    if (!mpiGrid.add_neighborhood(CP1_SHIFT, neighborhood)) {\n        std::cerr << __FILE__ << \":\" << __LINE__\n            << \" add_neighborhood failed\"\n            << std::endl;\n        abort();\n    }\n\n    // shift with -1/-1/-1 elements\n    neighborhood.clear(); \n    neighborhood.push_back({{-1,0,0}});\n    neighborhood.push_back({{0,-1,0}});\n    neighborhood.push_back({{0,0,-1}});\n    \n    if (!mpiGrid.add_neighborhood(CM1_SHIFT, neighborhood)) {\n        std::cerr << __FILE__ << \":\" << __LINE__\n            << \" add_neighborhood failed\"\n            << std::endl;\n        abort();\n    }\n\n\n\n\n    // Full negative cube (in z-ordering for efficiency)\n    // TODO: currently this is done via default -1/0/+1 neighborhood;\n    //       use this instead; so we can skip +1 cells\n    // std::vector<neigh_t> neighborhood2 = {{ {{1,0,0}},\n    //                                        {{0,1,0}},\n    //                                        {{0,0,1}}\n    //                                      }};\n\n\n\n\n    cout << rank << \": Initialized mpiGrid...\" << endl;\n\n\n    //--------------------------------------------------  \n    cout << rank << \": Injecting particles...\" << endl;\n    /* First we transfer everything to rank 0 for easy initialization. \n       Then inject particles, then load balance back using Zoltan\n    */\n    Injector inject(P::grid_xmin, P::grid_xmax,\n                    P::grid_ymin, P::grid_ymax,\n                    P::grid_zmin, P::grid_zmax\n                    );\n\n\n    comm.move_all_to_master(mpiGrid);\n\n    // inject into cylindrical shape\n    // inject.cylinder(mpiGrid, P::Np, vb);\n\n    // inject uniform background plasma first\n    uint64_t Nbkg = (uint64_t)(P::Np*0.1);\n    double vb_bkg = 1.0;\n    inject.uniform(mpiGrid, Nbkg, vb_bkg);\n\n    // inject thin current sheets\n    uint64_t Nsheets = (uint64_t)(P::Np*0.9);\n    double delta = 0.005; ///< Sheet thickness\n    const double vb = 1.0; ///< Maxwellian temperature\n    inject.two_sheets(mpiGrid, Nsheets, vb, delta);\n\n\n    comm.load_balance(mpiGrid);\n    cout << rank << \": load balanced...\" << endl;\n\n    // Initialize B field\n    double B0 = 10000.0;\n    double alpha = 0.0;\n    inject.Harris_sheet(mpiGrid, B0, alpha, delta);\n\n\n    // Initialize mesh and create fields\n    //-------------------------------------------------- \n    Mesh mesh;\n    mesh.rank = rank;\n\n    // int debugWait = 0;\n    // while (0 == debugWait)\n    //     sleep(5);\n\n\n    mesh.deposit_currents(mpiGrid);\n    comm.update_ghost_zone_currents(mpiGrid);\n\n    mesh.yee_currents(mpiGrid);\n    comm.update_ghost_zone_yee_currents(mpiGrid);\n\n    // initialize field solver \n    Field_Solver field;\n\n    field.push_half_B(mpiGrid);\n    comm.update_ghost_zone_B(mpiGrid);\n\n    field.push_E(mpiGrid);\n    comm.update_ghost_zone_E(mpiGrid);\n\n    field.push_half_B(mpiGrid);\n    comm.update_ghost_zone_B(mpiGrid);\n\n    // TODO\n    // mesh.nodal_fields(mpiGrid);\n\n    Particle_Mover particles;\n\n    particles.update_velocities(mpiGrid); \n    comm.update_ghost_zone_particles(mpiGrid); \n\n    particles.propagate(mpiGrid); \n\n    mesh.sort_particles_into_cells(mpiGrid); \n\n\n    // Simulation save\n    //--------------------------------------------------\n    Save io;\n    io.rank = rank;\n    io.comm_size = comm_size;\n    io.save_dir = \"out/\";\n    io.filename = \"pic\";\n    io.init();\n\n    io.save_grid(mpiGrid);\n    io.save_particles(mpiGrid);\n    io.save_fields(mpiGrid);\n    io.update_master_list();\n    io.step++;\n\n\n    cout << \"Initialized save file\" << endl;\n\n    //-------------------------------------------------- \n    // Initialized everything; now starting main loop\n\n\n\tconst unsigned int max_steps = 50;\n\n    cout << \"Starting particle propagation\" << endl;\n\tfor (unsigned int step = 1; step < max_steps; step++) \n    {\n        cout << \" step: \" << step << endl;\n\n        \n        field.push_half_B(mpiGrid);\n        comm.update_ghost_zone_B(mpiGrid);\n    \n        // update particle velocities and locations\n        particles.update_velocities(mpiGrid); \n        particles.propagate(mpiGrid); \n        comm.update_ghost_zone_particles(mpiGrid); \n\n        mesh.sort_particles_into_cells(mpiGrid); \n    \n        field.push_half_B(mpiGrid);\n        comm.update_ghost_zone_B(mpiGrid);\n\n        field.push_E(mpiGrid);\n        comm.update_ghost_zone_E(mpiGrid);\n\n        mesh.deposit_currents(mpiGrid);\n        comm.update_ghost_zone_currents(mpiGrid);\n\n        mesh.yee_currents(mpiGrid);\n        comm.update_ghost_zone_yee_currents(mpiGrid);\n\n\n        // apply filters\n\n\n\n        // save step\n        io.save_grid(mpiGrid);\n        io.save_particles(mpiGrid);\n        io.save_fields(mpiGrid);\n        io.update_master_list();\n        io.step++;\n\n    }\n\n\n    io.finalize();\n\n\tMPI_Finalize();\n\n    cout << \"Finalized...\" << endl;\n\n\treturn EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "d42dee197527e72e229ba660671aecbecb8b14f5", "size": 10146, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "prototypes/cpp-pic/pic.cpp", "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/pic.cpp", "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/pic.cpp", "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": 27.128342246, "max_line_length": 88, "alphanum_fraction": 0.5905775675, "num_tokens": 2532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.26747122064444284}}
{"text": "// TODO: This is currently double as float causes\n// headaches with PROJ.4.\ntypedef double real;\n\n#ifndef SWIG\n/* The code is horrible. I'm deeply sorry. C++, and especially\n * Boost, is hell. */\n#include <readosm.h>\n#include <malloc.h>\n#include <memory>\n#include <stdexcept>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <iostream>\n#include <cmath>\n#include <cstdlib>\n#include <random>\n#include <ctime>\n#include <queue>\n#include <set>\n#include <list>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/astar_search.hpp>\n#include <boost/graph/random.hpp>\n#include <boost/random/mersenne_twister.hpp>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/geometries/segment.hpp>\n#include <boost/geometry/index/rtree.hpp>\n\n#include <proj_api.h>\n\nusing std::unique_ptr;\nusing std::shared_ptr;\nusing std::vector;\nusing std::string;\nnamespace bst = boost;\nnamespace bg = boost::geometry;\nnamespace bgi = boost::geometry::index;\n\n#endif\ntypedef long long node_id_t;\n#ifndef SWIG\n\ntypedef bst::adjacency_list<bst::vecS, bst::vecS, bst::bidirectionalS,\n\tbst::property<bst::vertex_name_t, node_id_t>,\n\tbst::property<bst::edge_weight_t, real>\n\t> Graph;\ntypedef bst::graph_traits < Graph >::vertex_descriptor Vertex;\ntypedef bst::graph_traits < Graph >::edge_descriptor Edge;\n\nreal rad_to_deg(real rad) {\n\treturn rad / (M_PI/180.0);\n}\n\nreal deg_to_rad(real deg) {\n\treturn deg * (M_PI/180.0);\n}\n\nclass OsmReaderError : public std::runtime_error {\n\tusing std::runtime_error::runtime_error;\n};\n\ntypedef bg::model::point<real, 2, bg::cs::cartesian> Point;\ntypedef bg::model::segment<Point> LineSegment;\ntypedef bg::model::box<Point> Bbox;\n\n\n// OMFG! I have to implement this manually!?!\n// Also giving up on generality, as, you know, Boost.\ninline real vect_norm(Point p) {\n\treal c = p.get<0>();\n\treal result = c*c;\n\tc = p.get<1>();\n\tresult += c*c;\n\n\treturn std::sqrt(result);\n}\n\nstruct LinesegProjectionResult {\n\tPoint projected;\n\treal error;\n\treal t;\n};\n// There's probably something like this in the depths\n// of Boost.Geometry, but couldn't find it, so here we go again.\nLinesegProjectionResult lineseg_point_projection(LineSegment seg, Point p)\n{\n\tauto a = get<0>(seg);\n\tauto b = get<1>(seg);\n\n\t// I guess Boost tries to make the APIs as difficut\n\t// as possible. This should be: auto segd = b - a;\n\t// but boost fucking wants this shit:\n\tauto segd = b; bg::subtract_point(segd, a);\n\tauto seglen = vect_norm(segd);\n\tauto normstart = p; bg::subtract_point(normstart, a);\n\tauto t = bg::dot_product(normstart, segd)/(seglen*seglen);\n\n\treal error;\n\n\tif(t > 1.0) {\n\t\tt = 1.0;\n\t}\n\n\tif(t < 0.0) {\n\t\tt = 0.0;\n\t}\n\t\n\t// Reusing stuff because the boost api is a fucking disaster.\n\t// With Eigen this was: auto proj = a + t*segd;\n\tbg::multiply_value(segd, t);\n\tauto proj = a;\n\tbg::add_point(proj, segd);\n\t\n\tbg::subtract_point(p, proj);\n\terror = vect_norm(p);\n\tLinesegProjectionResult result = {\n\t\t.projected=proj,\n\t\t.error=error,\n\t\t.t=t*seglen};\n\treturn result;\n}\n\ntemplate <class Key, class Value>\nclass default_map\n{\t\n\tpublic:\n\ttypedef std::pair<const Key, Value> value_type;\n\ttypedef Key key_type;\n\n\tprivate:\n\tstd::unordered_map<Key, Value, std::hash<Key>, std::equal_to<Key>> m_map;\n\tValue deflt;\n\n\tpublic:\n\t\n\tdefault_map(const Value def): deflt(def),\n\t\tm_map() {\n\n\t}\n\n\tValue& operator[](const Key& k) {\n\t\tauto it = m_map.find(k);\n\t\tif(it == m_map.end()) {\n\t\t\treturn m_map[k] = deflt;\n\t\t}\n\t\t\n\t\treturn it->second;\n\t}\n\n\tsize_t count(const Key& k) {\n\t\treturn m_map.count(k);\n\t}\n};\n\ntemplate <class Callback>\nvoid reverse_shortest_path(Vertex target, Graph& graph, Callback callback) {\n\tdefault_map<Vertex, real> distances(1.0/0.0);\n\tdefault_map<Vertex, real> cost(1.0/0.0);\n\tstd::unordered_map<Vertex, Vertex> successor;\n\tauto weights = bst::get(bst::edge_weight, graph);\n\n\ttypedef std::pair<real, Vertex> Node;\n\tstd::priority_queue<Node, std::vector<Node>, std::greater<Node>> queue;\n\tqueue.push(std::make_pair(0.0, target));\n\t\n\twhile(!queue.empty()) {\n\t\tauto top = queue.top();\n\t\tauto current = top.second;\n\t\tauto current_dist = top.first;\n\t\tqueue.pop();\n\t\tdistances[current] = current_dist;\n\t\tif(!callback(current, current_dist, successor)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tauto children = bst::in_edges(current, graph);\n\t\tfor(auto edge=children.first; edge!=children.second; edge++) {\n\t\t\tauto alt = current_dist + weights[*edge];\n\t\t\tauto child = bst::source(*edge, graph);\n\t\t\t\n\t\t\tif(distances.count(child)) {\n\t\t\t\t// Sanity check that we don't get a new distance\n\t\t\t\t// for an already finished node\n\t\t\t\tassert(distances[child] <= alt);\n\t\t\t\t// We've already finished this one\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tif(alt < cost[child]) {\n\t\t\t\tcost[child] = alt;\n\t\t\t\tqueue.push(std::make_pair(alt, child));\n\t\t\t\tsuccessor[child] = current;\n\t\t\t}\n\t\t}\n\t}\n}\n\ntemplate <class SuccessorMap>\nvector<Vertex> build_path_from_successors(Vertex start, Graph &g, SuccessorMap& suc) {\n\tvector<Vertex> result;\n\n\tauto end = suc.end();\n\tauto current = suc.find(start);\n\tresult.push_back(start);\n\twhile(current != end) {\n\t\tresult.push_back(current->second);\n\t\tcurrent = suc.find(current->second);\n\t}\n\n\treturn result;\n}\n\nauto single_target_shortest_path = [](Vertex source, Vertex target, Graph& graph) {\n\tvector<Vertex> path;\n\tauto visitor = [&](Vertex current, real distance, \n\t\tstd::unordered_map<Vertex, Vertex>& successors) {\n\t\tif(current != source) return true;\n\t\tpath = build_path_from_successors(source, graph, successors);\n\t\treturn false;\n\t};\n\n\treverse_shortest_path(target, graph, visitor);\n\n\treturn path;\n};\n\n\n#endif // SWIG\n\n// A hack to return stuff to python as the\n// Boost.Geometry Point is too bizarre\nstruct Point2d {\n\treal x; real y;\n\tPoint2d(){}\n\tPoint2d(Point& p) {\n\t\tx = p.get<0>();\n\t\ty = p.get<1>();\n\t}\n\n\tPoint2d(real x, real y)\n\t\t:x(x), y(y){}\n};\n\nclass CoordinateProjector {\n\tprivate:\n\tprojPJ projector;\n\tprojPJ wgs;\n\n\tpublic:\n\tCoordinateProjector(const char* proj_string)\n\t\t\t:projector(NULL), wgs(NULL) {\n\t\tprojector = pj_init_plus(proj_string);\n\t\tif(!projector) {\n\t\t\tthrow OsmReaderError(\"Couldn't initialize coordinate projection\");\n\t\t}\n\n\t\tprojPJ tmp_wgs = pj_init_plus(\"+init=epsg:4326\");\n\t\tif(!tmp_wgs) {\n\t\t\tthrow OsmReaderError(\"Couldn't initialize WGS coordinate system\");\n\t\t}\n\n\t\tif(!(wgs = pj_latlong_from_proj(tmp_wgs))) {\n\t\t\tpj_free(tmp_wgs);\n\t\t\tthrow OsmReaderError(\"Couldn't initialize WGS latlong coordinate system\");\n\t\t}\n\t\tpj_free(tmp_wgs);\n\t}\n\n\tvoid operator()(double latitude, double longitude, real* x, real* y) {\n\t\t*y = deg_to_rad(latitude);\n\t\t*x = deg_to_rad(longitude);\n\t\t\n\t\tif(pj_transform(wgs, projector, 1, 1, x, y, NULL)) {\n\t\t\tthrow OsmReaderError(\"Failed to project a coordinate to XY \" + std::to_string(latitude) + \" \" + std::to_string(longitude));\n\t\t}\n\t}\n\t\n\tvoid inverse(real x, real y, double *latitude, double *longitude) {\n\t\t*latitude = y;\n\t\t*longitude = x;\n\t\t\n\t\tif(pj_transform(projector, wgs, 1, 1, longitude, latitude, NULL)) {\n\t\t\tthrow OsmReaderError(\"Failed to project a coordinate to LatLng \"  + std::to_string(x) + \" \" + std::to_string(y));\n\t\t}\n\n\t\t*latitude = rad_to_deg(*latitude);\n\t\t*longitude = rad_to_deg(*longitude);\n\t}\n\n\t~CoordinateProjector() {\n\t\tif(projector) pj_free(projector);\n\t\tif(wgs) pj_free(wgs);\n\t}\n};\n\nenum WayRole {\n\tWayRoleIgnore = 0,\n\tWayRoleOneWay,\n\tWayRoleTwoWay\n};\n\nWayRole busway_filter(const readosm_way *way) {\n\tconst char *highway = NULL;\n\tconst char *busway = NULL;\n\tconst char *oneway = NULL;\n\tconst char *junction = NULL;\n\tconst char *ferry = NULL;\n\n\tfor(size_t i=0; i < way->tag_count; ++i) {\n\t\tif(string(\"highway\").compare(way->tags[i].key) == 0)\n\t\t\thighway = way->tags[i].value;\n\t\tif(string(\"busway\").compare(way->tags[i].key) == 0)\n\t\t\tbusway = way->tags[i].value;\n\t\tif(string(\"oneway\").compare(way->tags[i].key) == 0)\n\t\t\toneway = way->tags[i].value;\n\t\tif(string(\"junction\").compare(way->tags[i].key) == 0)\n\t\t\tjunction = way->tags[i].value;\n\t\tif(string(\"ferry\").compare(way->tags[i].key) == 0)\n\t\t\tferry = way->tags[i].value;\n\t}\n\n\tif(!(busway || highway || ferry)) return WayRoleIgnore;\n\tif(!highway) return WayRoleTwoWay;\n\n\tif(string(\"footway\").compare(highway) == 0) return WayRoleIgnore;\n\tif(string(\"cycleway\").compare(highway) == 0) return WayRoleIgnore;\n\tif(string(\"steps\").compare(highway) == 0) return WayRoleIgnore;\n\tif(string(\"path\").compare(highway) == 0) return WayRoleIgnore;\n\tif(string(\"construction\").compare(highway) == 0) return WayRoleTwoWay;\n\tif(string(\"proposed\").compare(highway) == 0) return WayRoleIgnore;\n\tif(string(\"bridleway\").compare(highway) == 0) return WayRoleIgnore;\n\n\t\n\tif(string(highway).compare(\"motorway\") == 0) return WayRoleOneWay;\n\tif(oneway && string(oneway).compare(\"yes\") == 0) return WayRoleOneWay;\n\tif(junction && string(junction).compare(\"roundabout\") == 0) return WayRoleOneWay;\n\t\t\n\treturn WayRoleTwoWay;\n}\n\nWayRole train_filter(const readosm_way *way) {\n\tconst char *railway = NULL;\n\tconst char *oneway = NULL;\n\tfor(size_t i=0; i < way->tag_count; ++i) {\n\t\tif(string(\"railway\").compare(way->tags[i].key) == 0)\n\t\t\trailway = way->tags[i].value;\n\t\tif(string(\"oneway\").compare(way->tags[i].key) == 0)\n\t\t\toneway = way->tags[i].value;\n\t};\n\n\tif(!railway) return WayRoleIgnore;\n\tif(string(\"rail\").compare(railway) != 0) return WayRoleIgnore;\n\tif(oneway && string(oneway).compare(\"yes\") == 0) return WayRoleOneWay;\n\treturn WayRoleTwoWay;\n}\n\nWayRole tram_filter(const readosm_way *way) {\n\tconst char *railway = NULL;\n\tconst char *oneway = NULL;\n\tfor(size_t i=0; i < way->tag_count; ++i) {\n\t\tif(string(\"railway\").compare(way->tags[i].key) == 0)\n\t\t\trailway = way->tags[i].value;\n\t\tif(string(\"oneway\").compare(way->tags[i].key) == 0)\n\t\t\toneway = way->tags[i].value;\n\t};\n\n\tif(!railway) return WayRoleIgnore;\n\tif(string(\"tram\").compare(railway) != 0 && string(\"construction\").compare(railway) != 0) return WayRoleIgnore;\n\tif(oneway && string(oneway).compare(\"yes\") == 0) return WayRoleOneWay;\n\treturn WayRoleTwoWay;\n}\n\nWayRole subway_filter(const readosm_way *way) {\n\tconst char *railway = NULL;\n\tfor(size_t i=0; i < way->tag_count; ++i) {\n\t\tif(string(\"railway\").compare(way->tags[i].key) == 0)\n\t\t\trailway = way->tags[i].value;\n\t};\n\n\tif(!railway) return WayRoleIgnore;\n\tif(string(\"subway\").compare(railway) != 0) return WayRoleIgnore;\n\treturn WayRoleTwoWay;\n}\n\nclass OsmGraph {\n\tprivate:\n\tCoordinateProjector& coord_proj;\n\n\tpublic:\n\tGraph graph;\n\tstd::unordered_map<node_id_t, Point> node_coordinates;\n\tstd::unordered_map<node_id_t, Vertex> id_to_vertex;\n\tbgi::rtree< std::pair<Bbox, std::pair<Edge, LineSegment> >, bgi::quadratic<16> > edge_index;\n\t\n\tprivate:\n\tstatic int handle_osm_node(const void *usr_data, const readosm_node *node) {\n\t\tauto self = (OsmGraph*)usr_data;\n\n\t\treal x, y;\n\t\tself->coord_proj(node->latitude, node->longitude, &x, &y);\n\t\tself->node_coordinates[node->id] = Point(x, y);\n\t\t\n\t\t\t\t\n\t\treturn READOSM_OK;\n\t}\n\n\n\n\tvoid ensure_node(node_id_t node_id) {\n\t\tif(id_to_vertex.count(node_id)) return;\n\t\tif(node_coordinates.count(node_id) == 0) return;\n\n\t\tauto node_id_prop = bst::get(bst::vertex_name, graph);\n\t\tVertex v = bst::add_vertex(graph);\n\t\tid_to_vertex[node_id] = v;\n\t\tnode_id_prop[v] = node_id;\n\t}\n\t\n\tvoid add_new_edge(node_id_t src, node_id_t dst) {\n\t\tensure_node(src); ensure_node(dst);\n\t\tif(!(id_to_vertex.count(src) && id_to_vertex.count(dst))) {\n\t\t\treturn;\n\t\t}\n\t\tauto& s = node_coordinates[src];\n\t\tauto& e = node_coordinates[dst];\n\t\tauto seg = LineSegment(s, e);\n\t\t\n\t\tauto new_edge = bst::add_edge(\n\t\t\tid_to_vertex[src],\n\t\t\tid_to_vertex[dst],\n\t\t\tgraph).first;\n\t\t\n\t\tauto length = bg::length(seg);\n\t\tauto edge_id = num_edges(graph);\n\t\t\n\t\tget(bst::edge_weight, graph)[new_edge] = length;\n\t\tBbox bbox;\n\t\tbg::envelope(seg, bbox);\n\t\tauto entry = std::make_pair(bbox, std::make_pair(new_edge, seg));\n\t\tedge_index.insert(entry);\n\n\t}\n\n\tstatic int handle_osm_way(const void *usr_data, const readosm_way *way) {\n\t\tauto self = (OsmGraph*)usr_data;\n\t\treturn self->do_handle_osm_way(way);\n\t}\n\n\tint do_handle_osm_way(const readosm_way *way) {\n\t\t// TODO: The graph search could be optimized quite a bit by\n\t\t//\tjust inserting one edge per way and calculating the\n\t\t//\tedge length from the segments.\n\t\t//\tAlso duplicating both ways in the RTree causes almost\n\t\t//\tdouble the storage/computation. The implementation is\n\t\t//\tsimpler this way though.\n\t\tauto& i2v = id_to_vertex;\n\t\tWayRole role = get_way_role(way);\n\t\tif(role == WayRoleIgnore) {\n\t\t\treturn READOSM_OK;\n\t\t}\n\n\t\tfor(size_t i=0; i < way->node_ref_count - 1; ++i) {\n\t\t\tadd_new_edge(way->node_refs[i], way->node_refs[i+1]);\n\t\t}\n\n\t\tif(role == WayRoleOneWay) return READOSM_OK;\n\t\t\n\t\tfor(size_t i=0; i < way->node_ref_count - 1; ++i) {\n\t\t\tadd_new_edge(way->node_refs[i+1], way->node_refs[i]);\n\t\t}\n\n\n\t\treturn READOSM_OK;\n\t}\n\t\n\tWayRole(&get_way_role)(const readosm_way *);\n\n\tpublic:\n\tOsmGraph(const char *filename, CoordinateProjector& proj, WayRole(*get_way_role)(const readosm_way *))\n\t\t\t:coord_proj(proj), get_way_role(*get_way_role) {\n\t\tconst void *osm_handle;\n\t\tauto status = readosm_open(filename, &osm_handle);\n\t\tif(status != READOSM_OK) {\n\t\t\tthrow new OsmReaderError(\"Failed to open input file\");\n\t\t}\n\t\t// NOTE: Assumes currently that all nodes are read before\n\t\t//\tthe ways. Seems to be so, but not really assured\n\t\t//\tanywhere.\n\t\treadosm_parse(osm_handle, this, handle_osm_node, handle_osm_way, NULL);\n\t\treadosm_close(osm_handle);\n\t}\n\n\tPoint& get_vertex_point(Vertex vertex) {\n\t\tauto node_id = get(bst::vertex_name, graph)[vertex];\n\t\treturn node_coordinates[node_id];\n\t}\n\n\tnode_id_t get_vertex_id(Vertex vertex) {\n\t\treturn get(bst::vertex_name, graph)[vertex];\n\t}\n\t\n\tstd::vector< std::pair<Point2d, Point2d> > get_edge_coordinates() {\n\t\tvector< std::pair<Point2d, Point2d> > result;\n\t\tauto iters = bst::edges(graph);\n\t\tfor(auto edge=iters.first; edge != iters.second; edge++) {\n\t\t\tauto src = Point2d(get_vertex_point(bst::source(*edge, graph)));\n\t\t\tauto dst = Point2d(get_vertex_point(bst::target(*edge, graph)));\n\t\t\tresult.push_back(std::make_pair(src, dst));\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t~OsmGraph() {\n\t}\n};\n\n\n\nstruct PositionHypothesis {\n\tstd::shared_ptr<PositionHypothesis> parent;\n\treal timestamp;\n\treal total_likelihood;\n\treal measurement_likelihood;\n\treal transition_likelihood;\n \treal measurement_error;\n\tEdge edge;\n\treal edge_offset;\n\tstd::vector<Vertex> subpath;\n\tPoint position;\n\tPoint measurement;\n};\n\nreal gaussian_logpdf(real x, real m, real s) {\n\treal normer = std::log(1.0/(s*std::sqrt(2*M_PI)));\n\treturn normer - (x-m)*(x-m)/(2*s*s);\n}\n\nclass StateLikelihoodModel {\n\tpublic:\n\tvirtual real measurement(const Point& m, const Point& p) = 0;\n\tvirtual real transition(const PositionHypothesis& parent, const PositionHypothesis& next, const vector<Vertex>& path, real path_length) = 0;\n\tvirtual ~StateLikelihoodModel() {};\n\n\tvirtual real best_transition_still_possible(real measured_dist, real distance) {\n\t\treturn 0.0;\n\t}\n};\n\ninline real vector_angle(Point& a, Point &b) {\n\tauto cosangle = bg::dot_product(a, b)/(vect_norm(a)*vect_norm(b));\n\t// Avoid acos returning NaNs due to rounding errors\n\tif(cosangle < -1.0) {\n\t\tcosangle = -1.0;\n\t} else if(cosangle > 1.0) {\n\t\tcosangle = 1.0;\n\t}\n\tauto angle = std::acos(cosangle);\n\treturn angle;\n}\n\n#if defined __FAST_MATH__\n#error This will not currently work with fast math due to needed NaN checks\n#endif\nclass DrawnGaussianStateModel : public StateLikelihoodModel {\n\treal measurement_std;\n\treal length_error_std;\n\tOsmGraph& graph;\n\tpublic:\n\n\tDrawnGaussianStateModel(real measurement_std, real length_error_std, OsmGraph& graph)\n\t\t:measurement_std(measurement_std), graph(graph), length_error_std(length_error_std) {}\n\n\treal measurement(const Point& m, const Point& p) {\n\t\tauto dx = m.get<0>() - p.get<0>();\n\t\tauto dy = m.get<1>() - p.get<1>();\n\t\treturn gaussian_logpdf(dx, 0.0, measurement_std) +\n\t\t\tgaussian_logpdf(dy, 0.0, measurement_std);\n\t}\n\n\treal transition(const PositionHypothesis& parent, const PositionHypothesis& next, const vector<Vertex> &path, real path_length) {\n\t\t// The idea here is to calculate how big a share of the\n\t\t// path is in different direction than the measurement.\n\t\t// TODO: I have a hunch that this could be reduced to a very\n\t\t//\tsimple form of just some distance ratios.\n\t\tauto orig_direction = next.measurement;\n\t\tbg::subtract_point(orig_direction, parent.measurement);\n\t\t\n\t\tauto total_angle = 0.0;\n\t\tauto total_length = 0.0;\n\t\tint n_spans = 0;\n\t\t\n\t\tauto evaluate_span = [&](Point& prev_point, Point& next_point) {\n\t\t\tauto direction = next_point;\n\t\t\tbg::subtract_point(direction, prev_point);\n\t\t\tauto length = vect_norm(direction);\n\t\t\tprev_point = next_point;\n\t\t\tauto angle = vector_angle(orig_direction, direction);\n\t\t\tif(std::isnan(angle)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttotal_angle += angle/M_PI*length;\n\t\t\ttotal_length += length;\n\t\t\tn_spans++;\n\n\t\t};\n\n\t\tauto prev_point = parent.position;\n\t\tfor(auto i=0; i < path.size(); i++) {\n\t\t\tauto next_point = graph.get_vertex_point(path[i]);\n\t\t\tevaluate_span(prev_point, next_point);\n\t\t\tprev_point = next_point;\n\t\t}\n\n\t\tif(path.size() > 0) {\n\t\t\tauto next_point = graph.get_vertex_point(bst::source(next.edge, graph.graph));\n\t\t\tevaluate_span(prev_point, next_point);\n\t\t\tprev_point = next_point;\n\t\t}\n\t\t\n\t\tauto next_point = next.position;\n\t\tevaluate_span(prev_point, next_point);\n\t\t\n\t\tif(total_length < 1e-6) {\n\t\t\t// Give some penalty for hanging around in the same\n\t\t\t// node. Otherwise truncates start and endpoints.\n\t\t\t// TODO: Could probably be handled more elegantly.\n\t\t\ttotal_angle = length_error_std;\n\t\t} else {\n\t\t\ttotal_angle /= total_length;\n\t\t}\n\t\t\n\t\treturn gaussian_logpdf(total_angle, 0.0, length_error_std);\n\t\t\n\t\t//auto measured_length = bg::length(LineSegment(parent.measurement, next.measurement));\n\t\t//auto relative_dist = (path_length+length_error_std)/(measured_length+length_error_std);\n\t\t//return gaussian_logpdf(relative_dist-1.0, 0, 0.1);\n\t\t//return gaussian_logpdf(path_length, 0.0, length_error_std);\n\t}\n\n\treal best_transition_still_possible(real measured_length, real path_length) {\n\t\treturn gaussian_logpdf(0.0, 0.0, length_error_std);\n\t\t//auto diff = path_length - measured_length;\n\t\t//if(diff < 0.0) diff = 0.0;\n\t\t//return gaussian_logpdf(path_length/(measured_length+1.0), 0, length_error_std);\n\t\t//return gaussian_logpdf(path_length, 0.0, length_error_std);\n\t}\n};\n\nclass MapMatcher2d {\n\t// TODO: Probably doing a lot of large object copies. Let's hope\n\t//\tfor copy elision, and of course optimize later.\n\t// TODO: There's a huge problem in the approach! By examining just\n\t//\ta single point on the edge, if the noise causes the measurement\n\t//\tto \"backtrack\", the result is very bad! Should consider the whole\n\t//\tedge instead.\n\tOsmGraph& graph;\n\treal search_radius;\n\tvector< shared_ptr<PositionHypothesis> >* hypotheses = NULL;\n\tPoint previous_measurement;\n\tStateLikelihoodModel& state_model;\n\n\tpublic:\n\tint n_outliers = 0;\n\n\tMapMatcher2d(OsmGraph& g, StateLikelihoodModel& state_model, real search_radius=100.0)\n\t\t: graph(g), search_radius(search_radius), state_model(state_model)  {\n\n\t}\n\n\t~MapMatcher2d() {\n\t\tif(hypotheses) delete hypotheses;\n\t}\n\n\n\tvoid measurement(real ts, real x, real y) {\n\t\tBbox search_area(\n\t\t\tPoint(x - search_radius, y - search_radius),\n\t\t\tPoint(x + search_radius, y + search_radius));\n\n\t\tauto query = bgi::intersects(search_area);\n\t\tstd::vector< std::pair<Bbox, std::pair<Edge, LineSegment> > > results;\n\t\tgraph.edge_index.query(query, std::back_inserter(results));\n\t\t\n\t\tauto point = Point(x, y);\n\t\tif(!hypotheses) {\n\t\t\tprevious_measurement = point;\n\t\t}\n\t\tauto measured_dist = bg::length(LineSegment(point, previous_measurement));\n\t\tprevious_measurement = point;\n\n\t\tauto new_hypotheses = new vector< shared_ptr<PositionHypothesis> >;\n\t\tauto best_total_likelihood = -1.0/0.0;\n\t\t\n\t\t#pragma omp parallel for\n\t\tfor(auto i=results.begin(); i < results.end(); i++) {\n\t\t\tauto& result = *i;\n\t\t\tauto edge = result.second.first;\n\t\t\tauto seg = result.second.second;\n\t\t\tauto proj = lineseg_point_projection(seg, Point(x, y));\n\t\t\tauto error = proj.error;\n\t\t\tauto t = proj.t;\n\t\t\tif(error > search_radius) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tauto hypo = shared_ptr<PositionHypothesis>(new PositionHypothesis {\n\t\t\t\t.parent=NULL,\n\t\t\t\t.timestamp=ts,\n\t\t\t\t.total_likelihood=0.0,\n\t\t\t\t.measurement_likelihood=state_model.measurement(point, proj.projected),\n\t\t\t\t.transition_likelihood=0.0,\n\t\t\t\t.measurement_error=error,\n\t\t\t\t.edge=edge,\n\t\t\t\t.edge_offset=t,\n\t\t\t\t.subpath=vector<Vertex>(),\n\t\t\t\t.position=proj.projected,\n\t\t\t\t.measurement=point\n\t\t\t\t});\n\t\t\thypo->total_likelihood = hypo->measurement_likelihood;\n\t\t\tif(!hypotheses) {\n\t\t\t\t// First round, so don't search for\n\t\t\t\t// parents\n\t\t\t\t#pragma omp critical\n\t\t\t\t{\n\t\t\t\tnew_hypotheses->push_back(hypo);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\t\t\t\t\n\t\t\tshared_ptr<PositionHypothesis> best_parent;\n\t\t\tauto best_likelihood = -1.0/0.0;\n\t\t\tauto best_transition = -1.0/0.0;\n\t\t\tvector<Vertex> best_path;\n\t\t\t\n\t\t\t/* No polymorphic lambdas in C++11 yet :( */\n\t\t\tauto consider_parent = [&] (shared_ptr<PositionHypothesis>& parent, real dist,\n\t\t\t\t\tvector<Vertex>& path ) {\n\t\t\t\tauto parent_likelihood = parent->total_likelihood;\n\t\t\t\tauto transition = state_model.transition(*parent, *hypo, path, dist);\n\t\t\t\tauto likelihood = parent_likelihood + transition;\n\t\t\t\tif(likelihood > best_likelihood) {\n\t\t\t\t\tbest_parent = parent;\n\t\t\t\t\tbest_likelihood = likelihood;\n\t\t\t\t\tbest_transition = transition;\n\t\t\t\t\tbest_path = path;\n\t\t\t\t}\n\t\t\t};\n\t\t\t\n\t\t\tstd::unordered_map<Vertex, vector<shared_ptr<PositionHypothesis>> > targets;\n\t\t\tfor(auto& prev: *hypotheses) {\n\t\t\t\tif(prev->edge == hypo->edge) {\n\t\t\t\t\t// The graph search doesn't work in the special case\n\t\t\t\t\t// where the parent and hypo are the same edge.\n\t\t\t\t\tauto real_dist = hypo->edge_offset - prev->edge_offset;\n\t\t\t\t\tif(real_dist < 0.0) {\n\t\t\t\t\t\t// Won't go into reverse direction. This is a prime example\n\t\t\t\t\t\t// of the problem that considering only single point in the\n\t\t\t\t\t\t// edge causes!\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t// No path as it's the same edge\n\t\t\t\t\tvector<Vertex> path;\n\t\t\t\t\tconsider_parent(prev, real_dist, path);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\ttargets[bst::target(prev->edge, graph.graph)].push_back(prev);\n\t\t\t}\n\n\t\t\tauto visit = [&] (Vertex current, real dist, std::unordered_map<Vertex, Vertex>& successors) {\n\t\t\t\tdist += hypo->edge_offset;\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t// TODO: Make configurable!\n\t\t\t\t// TODO: With certain transition likelihood functions we could probably\n\t\t\t\t//\tinfer when no other hypothesis can win the current best,\n\t\t\t\t//\tallowing for an \"optimal\" return and probably a lot earlier.\n\t\t\t\tif(dist > (10.0+measured_dist)*5.0) {\n\t\t\t\t\t//std::cout << \"Hit the limit :(\" << std::endl;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tauto it = targets.find(current);\n\t\t\t\tif(it == targets.end()) return true;\n\t\t\t\tauto hypo = it->second;\n\t\t\t\tauto path = build_path_from_successors(\n\t\t\t\t\t\tcurrent, graph.graph, successors);\n\n\t\t\t\tfor(auto& parent: it->second) {\n\t\t\t\t\tauto parent_left = get(bst::edge_weight, graph.graph)[parent->edge];\n\t\t\t\t\tparent_left -= parent->edge_offset;\n\t\t\t\t\tauto real_dist = dist + parent_left;\n\t\t\t\t\tconsider_parent(parent, real_dist, path);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\ttargets.erase(it);\n\n\t\t\t\t\n\t\t\t\tif(!targets.size()) {\n\t\t\t\t\t// All hypotheses found\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// Prune parents that can't win\n\t\t\t\t// TODO: This would prune a lot more if done\n\t\t\t\t//\tfor each found node and track the current\n\t\t\t\t//\tworst.\n\t\t\t\tauto itr = targets.begin();\n\t\t\t\twhile(itr != targets.end()) {\n\t\t\t\t\tfor(auto& parent: itr->second) {\n\t\t\t\t\t\tauto parent_left = get(bst::edge_weight, graph.graph)[parent->edge];\n\t\t\t\t\t\tparent_left -= parent->edge_offset;\n\t\t\t\t\t\tauto real_dist = dist + parent_left;\n\t\t\t\t\t\tauto best_possible = state_model.best_transition_still_possible(\n\t\t\t\t\t\t\tmeasured_dist, real_dist);\n\t\t\t\t\t\tbest_possible += parent->total_likelihood;\n\t\t\t\t\t\tif(best_possible >= best_likelihood) {\n\t\t\t\t\t\t\tgoto dontremove;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\titr = targets.erase(itr);\n\t\t\t\t\tif(targets.size() == 0) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\n\t\t\t\t\tdontremove:\n\t\t\t\t\t++itr;\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\treturn true;\n\t\t\t};\n\t\t\n\t\t\treverse_shortest_path(\n\t\t\t\tbst::source(hypo->edge, graph.graph), graph.graph,\n\t\t\t\tvisit\n\t\t\t\t);\n\t\t\tif(!best_parent) {\n\t\t\t\t// Not reachable from parents, skipidiskip\n\t\t\t\t// TODO: Getting here is very expensive. A nicer\n\t\t\t\t// way would be to simultaneously do multi-target\n\t\t\t\t// multi-source search (or just parallelise the different searches)\n\t\t\t\t// and give up when the search starts to look too bad.\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\thypo->parent = best_parent;\n\t\t\thypo->transition_likelihood = best_transition;\n\t\t\thypo->total_likelihood += best_likelihood + best_transition;\n\t\t\thypo->subpath = best_path;\n\t\t\t#pragma omp critical\n\t\t\t{\n\t\t\tnew_hypotheses->push_back(hypo);\n\t\t\tif(hypo->total_likelihood > best_total_likelihood) {\n\t\t\t\tbest_total_likelihood = 0.0;\n\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(new_hypotheses->size() == 0) {\n\t\t\t// Found no hypotheses! Let's hope it was an outlier\n\t\t\t// and ignore this round.\n\t\t\tdelete new_hypotheses;\n\t\t\tn_outliers += 1;\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tdelete hypotheses;\n\t\thypotheses = new_hypotheses;\n\t}\n\t\n\tvoid measurement(real ts, Point p) {\n\t\tmeasurement(ts, p.get<0>(), p.get<1>());\n\t}\n\t\n\t\n\tvoid measurements(const std::vector<real>& ts, const std::vector<Point2d>& points) {\n\t\tauto s = ts.size();\n\t\tfor(int i = 0; i < s; i++) {\n\t\t\tmeasurement(ts[i], points[i].x, points[i].y);\n\t\t}\n\t}\n\n\tstd::list<Vertex> route_vertex_path(std::list<shared_ptr<PositionHypothesis> >& path) {\n\t\tstd::list<Vertex> vertices;\n\t\t\n\t\tVertex prev_inserted;\n\t\tauto insert_unique = [&](Vertex vertex) {\n\t\t\tif(vertices.size() and prev_inserted == vertex) return;\n\t\t\tvertices.push_back(vertex);\n\t\t\tprev_inserted = vertex;\n\t\t};\n\n\t\tfor(auto current: path) {\n\t\t\tif(current->subpath.size() == 0) {\n\t\t\t\t// If the subpath length is zero, we are\n\t\t\t\t// on the same edge as the parent, so\n\t\t\t\t// don't add the source.\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor(auto vertex: current->subpath) {\n\t\t\t\tinsert_unique(vertex);\n\t\t\t}\n\t\t\tinsert_unique(bst::source(current->edge, graph.graph));\n\t\t}\n\n\t\treturn vertices;\n\t}\n\n\tstd::list<shared_ptr<PositionHypothesis> > get_hypothesis_path(shared_ptr<PositionHypothesis> current) {\n\t\tstd::list< shared_ptr<PositionHypothesis> > states;\n\t\twhile(current) {\n\t\t\tstates.push_front(current);\n\t\t\tcurrent = current->parent;\n\t\t}\n\n\t\treturn states;\n\t}\n\n\tstd::vector< Point2d > best_match_coordinates() {\n\t\tvector< Point2d > path;\n\t\tauto current = best_current_hypothesis();\t\t\n\t\tauto states = get_hypothesis_path(current);\n\t\tpath.push_back(states.front()->position);\n\t\tstates.pop_front();\n\n\t\tfor(auto vertex: route_vertex_path(states)) {\n\t\t\tauto point = graph.get_vertex_point(vertex);\n\t\t\tpath.push_back(point);\n\t\t}\n\t\tpath.push_back(states.back()->position);\n\n\t\treturn path;\n\t}\n\n\tstd::vector< node_id_t > best_match_node_ids() {\n\t\tvector< node_id_t > path;\n\t\tauto current = best_current_hypothesis();\n\t\tauto states = get_hypothesis_path(current);\n\t\t// OSM id's have to be >= 1, so hacking\n\t\t// zero to be missing.\n\t\tpath.push_back(0);\n\t\tstates.pop_front();\n\n\t\tfor(auto vertex: route_vertex_path(states)) {\n\t\t\tauto point = graph.get_vertex_id(vertex);\n\t\t\tpath.push_back(point);\n\t\t}\n\t\tpath.push_back(0);\n\n\t\treturn path;\n\t}\n\n\tstd::shared_ptr<PositionHypothesis> best_current_hypothesis() {\n\t\tshared_ptr<PositionHypothesis> current;\n\t\tauto max_likelihood = -1.0/0.0;\n\t\t// Find the best current state\n\t\tfor(auto hypo: *hypotheses) {\n\t\t\tif(hypo->total_likelihood < max_likelihood) continue;\n\t\t\tmax_likelihood = hypo->total_likelihood;\n\t\t\tcurrent = hypo;\n\t\t}\n\n\t\treturn current;\n\t}\n\t\n\tstd::vector<std::shared_ptr<PositionHypothesis> > current_hypotheses() {\n\t\treturn *hypotheses;\n\t}\n\t\n};\n\ntemplate<class Rndgen>\nstd::vector<Point2d> get_random_path_custom(OsmGraph& graph, int n_waypoints, Rndgen& gen) {\n\n\tstd::vector<Point2d> result;\n\n\tauto src = bst::random_vertex(graph.graph, gen);\n\tfor(int i=0; i < n_waypoints; ++i) {\n\t\tauto dst = bst::random_vertex(graph.graph, gen);\n\t\tauto path = single_target_shortest_path(src, dst, graph.graph);\n\t\tif(!path.size()) {\n\t\t\t// Recurse until a path is found\n\t\t\treturn get_random_path_custom(graph, n_waypoints, gen);\n\t\t}\n\n\t\tfor(auto node: path) {\n\t\t\tresult.push_back(graph.get_vertex_point(node));\n\t\t}\n\n\t\tsrc = dst;\n\t}\n\n\treturn result;\n}\n\nstd::vector<Point2d> get_random_path(OsmGraph& graph, int n_waypoints=1) {\n\tstd::random_device rd;\n\tstd::mt19937 gen(rd());\n\treturn get_random_path_custom(graph, n_waypoints, gen);\n}\n\nstd::vector<Point2d> get_shortest_node_path(OsmGraph& graph, node_id_t start, node_id_t end) {\n\tstd::vector<Point2d> result;\n\tauto s = graph.id_to_vertex[start];\n\tauto e = graph.id_to_vertex[end];\n\tfor(auto node: single_target_shortest_path(s, e, graph.graph)) {\n\t\tresult.push_back(graph.get_vertex_point(node));\n\t}\n\n\treturn result;\n};\n", "meta": {"hexsha": "683c242355c41e6bc1be9ba6f187d699befcfd00", "size": 28596, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "geometry-matcher/pymapmatch/osmmapmatch.hpp", "max_stars_repo_name": "HSLdevcom/jore-graphql-import", "max_stars_repo_head_hexsha": "0b2db4fbca6c2a23901408148bff64572be57d4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-04T06:11:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-04T06:11:09.000Z", "max_issues_repo_path": "geometry-matcher/pymapmatch/osmmapmatch.hpp", "max_issues_repo_name": "HSLdevcom/jore-graphql-import", "max_issues_repo_head_hexsha": "0b2db4fbca6c2a23901408148bff64572be57d4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-01-15T09:29:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T09:21:03.000Z", "max_forks_repo_path": "geometry-matcher/pymapmatch/osmmapmatch.hpp", "max_forks_repo_name": "HSLdevcom/jore-graphql-import", "max_forks_repo_head_hexsha": "0b2db4fbca6c2a23901408148bff64572be57d4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-10T12:50:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-10T12:50:39.000Z", "avg_line_length": 28.0078354554, "max_line_length": 141, "alphanum_fraction": 0.6904112463, "num_tokens": 7999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710085, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.26742611435739416}}
{"text": "#include <Data/DATA.h>\n#include <Driver/SIMULATION.h>\n#include <Equation/MATRIX_BUNDLE.h>\n#include <Equation/NONLINEAR_EQUATION.h>\n#include <Evolution/EVOLUTION.h>\n#include <Evolution/QUALITY.h>\n#include <Force/FORCE.h>\n#include <Force/FORCE_TYPE.h>\n#include <Utilities/EIGEN_HELPERS.h>\n#include <Utilities/LOG.h>\n#include <iostream>\n#include <vector>\n#include <Eigen/IterativeSolvers>\nusing namespace Mechanics;\n///////////////////////////////////////////////////////////////////////\ntemplate<class TV> Matrix<typename TV::Scalar,Dynamic,1> NONLINEAR_EQUATION<TV>::\nGet_Unknowns(const DATA<TV>& data,const FORCE<TV>& force) const\n{\n    Matrix<T,Dynamic,1> velocities,forces,unknowns;\n    data.Pack_Velocities(velocities);\n    STORED_FORCE<T> stored_force;\n    force.Pack_Forces(stored_force);\n    forces=stored_force.Vector();\n    unknowns.resize(velocities.size()+forces.size());\n    for(int i=0;i<velocities.size();i++){\n        unknowns(i)=velocities(i);}\n    for(int i=0;i<forces.size();i++){\n        unknowns(i+velocities.size())=forces(i);}\n    return unknowns;\n}\n///////////////////////////////////////////////////////////////////////\ntemplate<class TV> void NONLINEAR_EQUATION<TV>::\nIncrement_Unknowns(const Matrix<T,Dynamic,1>& unknowns,DATA<TV>& data,FORCE<TV>& force)\n{\n    int velocity_dof=Velocity_DOF();\n    Matrix<T,Dynamic,1> solve_velocities=unknowns.block(0,0,velocity_dof,1);\n    STORED_FORCE<T> stored_force;\n    force.Pack_Forces(stored_force);\n    stored_force.Set(unknowns.block(velocity_dof,0,unknowns.size()-velocity_dof,1));\n    force.Increment_Forces(stored_force,1);\n\n    Matrix<T,Dynamic,1> current_velocities;\n    data.Pack_Velocities(current_velocities);\n    Matrix<T,Dynamic,1> candidate_velocities=current_velocities+solve_velocities;\n    Unpack_Velocities(data,candidate_velocities);\n    data.Step();\n}\n///////////////////////////////////////////////////////////////////////\ntemplate<class TV> void NONLINEAR_EQUATION<TV>::\nIdentify_DOF(const DATA<TV>& data,const FORCE<TV>& force,int index)\n{\n    int current_index=0;\n    for(int i=0;i<data.size();i++){\n        int data_size=kinematic_projection_matrices[i].rows();//=data[i]->Velocity_DOF();\n        if(index<current_index+data_size){\n            data[i]->Identify_DOF(index-current_index);\n            return;}\n        current_index+=data_size;\n    }\n    for(int i=0;i<force.size();i++){\n        int force_size=force[i]->DOF();\n        if(index<current_index+force_size){\n            force[i]->Identify_DOF(index-current_index);\n            return;}\n        current_index+=force_size;}\n    LOG::cout<<\"Unidentified DOF\"<<std::endl;\n}\n///////////////////////////////////////////////////////////////////////\ntemplate<class TV> void NONLINEAR_EQUATION<TV>::\nUnpack_Velocities(DATA<TV>& data,const Matrix<T,Dynamic,1>& velocities)\n{\n    assert(data.size()==1);\n    Matrix<Matrix<T,Dynamic,1>,Dynamic,1> full_velocities(data.size());\n    int current_index=0;\n    for(int i=0;i<data.size();i++){\n        int compressed_size=kinematic_projection_matrices[i].rows();\n        full_velocities[i]=kinematic_projection_matrices[i].transpose()*velocities.block(current_index,0,current_index+compressed_size,1);\n        current_index+=compressed_size;\n    }\n    Matrix<T,Dynamic,1> full_velocity;\n    Merge_Block_Vectors(full_velocities,full_velocity);\n    data.Unpack_Velocities(full_velocity);\n}\n///////////////////////////////////////////////////////////////////////\ntemplate<class TV> void NONLINEAR_EQUATION<TV>::\nStore_Errors(DATA<TV>& data,const Matrix<T,Dynamic,1>& errors)\n{\n    assert(data.size()==1);\n    Matrix<Matrix<T,Dynamic,1>,Dynamic,1> full_errors(data.size());\n    int current_index=0;\n    for(int i=0;i<data.size();i++){\n        int compressed_size=kinematic_projection_matrices[i].rows();\n        full_errors[i]=kinematic_projection_matrices[i].transpose()*errors.block(current_index,0,current_index+compressed_size,1);\n        current_index+=compressed_size;\n    }\n    Matrix<T,Dynamic,1> full_error;\n    Merge_Block_Vectors(full_errors,full_error);\n    data.Store_Errors(full_error);\n}\n///////////////////////////////////////////////////////////////////////\ntemplate<class TV> void NONLINEAR_EQUATION<TV>::\nInitialize(DATA<TV>& data,FORCE<TV>& force)\n{\n    kinematic_projection_matrices.resize(data.size());\n    for(int i=0;i<data.size();i++){    \n        data[i]->Kinematic_Projection(kinematic_projection_matrices[i]);}\n}\n///////////////////////////////////////////////////////////////////////\ntemplate<class TV> void NONLINEAR_EQUATION<TV>::\nLinearize(DATA<TV>& data,FORCE<TV>& force,const T dt,const T time,const bool stochastic)\n{\n    system.Initialize(data,force);\n    for(int i=0;i<data.size();i++){\n        data[i]->Inertia(dt,system.jacobian_block_terms[i],system.inverse_inertia_matrices[i],system.error_blocks[i]);}\n    for(int i=0;i<force.size();i++){\n        force[i]->Identify_Interactions_And_Compute_Errors(data,force,dt,time,system,stochastic);}\n    system.Scale_Errors(data,force,kinematic_projection_matrices);\n    for(int i=0;i<force.size();i++){\n        force[i]->Compute_Derivatives(data,force,system);}\n    system.Scale_Derivatives(data,force,kinematic_projection_matrices);\n    jacobian.resize(data.Velocity_DOF(),data.Velocity_DOF());\n    Merge_Block_Matrices(system.jacobian_blocks,jacobian);\n    Merge_Block_Vectors(system.error_blocks,error);\n\n    // build the Hessian\n    //SparseMatrix<T> hessian_addition;\n    //Merge_Block_Matrices(system.hessian_blocks,hessian_addition);\n    //accurate_hessian=jacobian.adjoint()*jacobian+hessian_addition;\n    hessian=jacobian.adjoint()*jacobian;\n}\n///////////////////////////////////////////////////////////////////////\nGENERIC_TYPE_DEFINITION(NONLINEAR_EQUATION)\n", "meta": {"hexsha": "2b8c728898a79fbe5de1624d0863e27a498d6550", "size": 5731, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Library/Equation/NONLINEAR_EQUATION.cpp", "max_stars_repo_name": "avimosher/shapesifter", "max_stars_repo_head_hexsha": "8b42200220764b8082fadad9bf5346b5d1844c06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Library/Equation/NONLINEAR_EQUATION.cpp", "max_issues_repo_name": "avimosher/shapesifter", "max_issues_repo_head_hexsha": "8b42200220764b8082fadad9bf5346b5d1844c06", "max_issues_repo_licenses": ["MIT"], "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/Equation/NONLINEAR_EQUATION.cpp", "max_forks_repo_name": "avimosher/shapesifter", "max_forks_repo_head_hexsha": "8b42200220764b8082fadad9bf5346b5d1844c06", "max_forks_repo_licenses": ["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.0902255639, "max_line_length": 138, "alphanum_fraction": 0.6511952539, "num_tokens": 1357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.2672882531144952}}
{"text": "// This file is a part of the OpenSurgSim project.\n// Copyright 2013, SimQuest 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#include <boost/thread/locks.hpp>\n\n#include \"SurgSim/Devices/DeviceFilters/PoseTransform.h\"\n\n#include \"SurgSim/Math/MathConvert.h\"\n#include \"SurgSim/Math/Matrix.h\"\n\nusing SurgSim::DataStructures::DataGroup;\nusing SurgSim::Math::RigidTransform3d;\nusing SurgSim::Math::Vector3d;\n\nnamespace SurgSim\n{\nnamespace Devices\n{\n\nSURGSIM_REGISTER(SurgSim::Input::DeviceInterface, SurgSim::Devices::PoseTransform, PoseTransform);\n\nPoseTransform::PoseTransform(const std::string& name) :\n\tDeviceFilter(name),\n\tm_transform(RigidTransform3d::Identity()),\n\tm_transformInverse(RigidTransform3d::Identity()),\n\tm_translationScale(1.0)\n{\n\tSURGSIM_ADD_SERIALIZABLE_PROPERTY(PoseTransform, double, TranslationScale,\n\t\tgetTranslationScale, setTranslationScale);\n\tSURGSIM_ADD_SERIALIZABLE_PROPERTY(PoseTransform, RigidTransform3d, Transform, getTransform, setTransform);\n}\n\nvoid PoseTransform::filterInput(const std::string& device, const DataGroup& dataToFilter, DataGroup* result)\n{\n\tboost::lock_guard<boost::mutex> lock(m_mutex); // Prevent the transform or scaling from being set simultaneously.\n\n\t*result = dataToFilter;  // Pass on all the data entries.\n\n\tRigidTransform3d pose; // If there is a pose, scale the translation, then transform the result.\n\tif (dataToFilter.poses().get(DataStructures::Names::POSE, &pose))\n\t{\n\t\tpose.translation() *= m_translationScale;\n\t\tpose = m_transform * pose;\n\t\tresult->poses().set(DataStructures::Names::POSE, pose);\n\t}\n\n\t// If there is a linear velocity, scale then rotate it.  The linear velocity is scaled because it is the change\n\t// in translation over time, and the translation is being scaled.\n\tVector3d linearVelocity;\n\tif (dataToFilter.vectors().get(DataStructures::Names::LINEAR_VELOCITY, &linearVelocity))\n\t{\n\t\tlinearVelocity *= m_translationScale;\n\t\tlinearVelocity = m_transform.linear() * linearVelocity;\n\t\tresult->vectors().set(DataStructures::Names::LINEAR_VELOCITY, linearVelocity);\n\t}\n\n\tVector3d angularVelocity; // If there is an angular velocity, rotate it.\n\tif (dataToFilter.vectors().get(DataStructures::Names::ANGULAR_VELOCITY, &angularVelocity))\n\t{\n\t\tangularVelocity = m_transform.linear() * angularVelocity;\n\t\tresult->vectors().set(DataStructures::Names::ANGULAR_VELOCITY, angularVelocity);\n\t}\n}\n\nvoid PoseTransform::filterOutput(const std::string& device, const DataGroup& dataToFilter, DataGroup* result)\n{\n\tboost::lock_guard<boost::mutex> lock(m_mutex); // Prevent the transform or scaling from being set simultaneously.\n\n\t*result = dataToFilter;  // Pass on all the data entries.\n\n\t// Since the haptic devices will compare the data in the output DataGroup to a raw input pose, the filter must\n\t// perform the reverse transform and scaling to data used by the haptic devices.\n\n\t// The force and torque must be transformed into device space.  In order to reliably display the desired\n\t// forces as calculated by the simulation, the nominal forces and torques are not scaled by the translation scaling.\n\t// The benefit is that increasing the translation scaling does not result in larger penetrations for the\n\t// same force, but the downside is that as the translation scaling increases it becomes more likely that the haptic\n\t// feedback loop at a surface will become \"active\" (smaller motions penetrating another object are sufficient to\n\t// create forces ejecting the device's collision representation).  Therefore, a device that is having its\n\t// translation scaled may required a force scaling filter to reduce the forces.\n\tVector3d force;\n\tif (dataToFilter.vectors().get(DataStructures::Names::FORCE, &force))\n\t{\n\t\tforce = m_transformInverse.linear() * force;\n\t\tresult->vectors().set(DataStructures::Names::FORCE, force);\n\t}\n\n\tVector3d torque;\n\tif (dataToFilter.vectors().get(DataStructures::Names::TORQUE, &torque))\n\t{\n\t\ttorque = m_transformInverse.linear() * torque;\n\t\tresult->vectors().set(DataStructures::Names::TORQUE, torque);\n\t}\n\n\t// The Jacobians must be transformed into device space.  The Jacobians are scaled based on the translation scaling,\n\t// so that the forces and torques displayed by the device will be correct for the scene-space motions, not for the\n\t// device-space motions.  Let R be the linear rotation portion of our transform, s be the translation scaling\n\t// factor, and J be the 3x3 upper-left corner of the spring Jacobian.  Then:\n\t// delta-translation-in-scene = s * R * delta-translation-in-device\n\t// delta-force-in-scene = J * delta-translation-in-scene\n\t// So to transform J into the device space, we left-multiply by R^-1, and right-multiply by R.\n\t// Then, because we want the forces to be scaled as in scene-space, we scale J by s.  The bottom-left 3x3 block\n\t// in springJacobian (or damperJacobian) also transforms from delta-translation and is treated the same, while the\n\t// two 3x3 blocks on the right half (of springJacobian or damperJacobian) will be multiplied by the delta-rotation\n\t// (not delta-translation) and so should not be scaled.\n\tDataGroup::DynamicMatrixType springJacobian;\n\tif (dataToFilter.matrices().get(DataStructures::Names::SPRING_JACOBIAN, &springJacobian))\n\t{\n\t\tspringJacobian.block<3,3>(0, 0).applyOnTheLeft(m_transformInverse.linear());\n\t\tspringJacobian.block<3,3>(0, 0).applyOnTheRight(m_transform.linear());\n\t\tspringJacobian.block<3,3>(3, 0).applyOnTheLeft(m_transformInverse.linear());\n\t\tspringJacobian.block<3,3>(3, 0).applyOnTheRight(m_transform.linear());\n\t\tspringJacobian.block<3,3>(0, 3).applyOnTheLeft(m_transformInverse.linear());\n\t\tspringJacobian.block<3,3>(0, 3).applyOnTheRight(m_transform.linear());\n\t\tspringJacobian.block<3,3>(3, 3).applyOnTheLeft(m_transformInverse.linear());\n\t\tspringJacobian.block<3,3>(3, 3).applyOnTheRight(m_transform.linear());\n\t\tspringJacobian.block<6,3>(0, 0) *= m_translationScale;\n\t\tresult->matrices().set(DataStructures::Names::SPRING_JACOBIAN, springJacobian);\n\t}\n\n\tRigidTransform3d inputPose;\n\tif (dataToFilter.poses().get(DataStructures::Names::INPUT_POSE, &inputPose))\n\t{\n\t\tinputPose = m_transformInverse * inputPose;\n\t\tinputPose.translation() /= m_translationScale;\n\t\tresult->poses().set(DataStructures::Names::INPUT_POSE, inputPose);\n\t}\n\n\tDataGroup::DynamicMatrixType damperJacobian;\n\tif (dataToFilter.matrices().get(DataStructures::Names::DAMPER_JACOBIAN, &damperJacobian))\n\t{\n\t\tdamperJacobian.block<3,3>(0, 0).applyOnTheLeft(m_transformInverse.linear());\n\t\tdamperJacobian.block<3,3>(0, 0).applyOnTheRight(m_transform.linear());\n\t\tdamperJacobian.block<3,3>(3, 0).applyOnTheLeft(m_transformInverse.linear());\n\t\tdamperJacobian.block<3,3>(3, 0).applyOnTheRight(m_transform.linear());\n\t\tdamperJacobian.block<3,3>(0, 3).applyOnTheLeft(m_transformInverse.linear());\n\t\tdamperJacobian.block<3,3>(0, 3).applyOnTheRight(m_transform.linear());\n\t\tdamperJacobian.block<3,3>(3, 3).applyOnTheLeft(m_transformInverse.linear());\n\t\tdamperJacobian.block<3,3>(3, 3).applyOnTheRight(m_transform.linear());\n\t\tdamperJacobian.block<6,3>(0, 0) *= m_translationScale;\n\t\tresult->matrices().set(DataStructures::Names::DAMPER_JACOBIAN, damperJacobian);\n\t}\n\n\tVector3d inputLinearVelocity;\n\tif (dataToFilter.vectors().get(DataStructures::Names::INPUT_LINEAR_VELOCITY, &inputLinearVelocity))\n\t{\n\t\tinputLinearVelocity = m_transformInverse.linear() * inputLinearVelocity;\n\t\tinputLinearVelocity /= m_translationScale;\n\t\tresult->vectors().set(DataStructures::Names::INPUT_LINEAR_VELOCITY, inputLinearVelocity);\n\t}\n\n\tVector3d inputAngularVelocity;\n\tif (dataToFilter.vectors().get(DataStructures::Names::INPUT_ANGULAR_VELOCITY, &inputAngularVelocity))\n\t{\n\t\tinputAngularVelocity = m_transformInverse.linear() * inputAngularVelocity;\n\t\tresult->vectors().set(DataStructures::Names::INPUT_ANGULAR_VELOCITY, inputAngularVelocity);\n\t}\n}\n\ndouble PoseTransform::getTranslationScale() const\n{\n\treturn m_translationScale;\n}\n\nvoid PoseTransform::setTranslationScale(double translationScale)\n{\n\tboost::lock_guard<boost::mutex> lock(m_mutex);\n\tm_translationScale = translationScale;\n}\n\nconst RigidTransform3d& PoseTransform::getTransform() const\n{\n\treturn m_transform;\n}\n\nvoid PoseTransform::setTransform(const RigidTransform3d& transform)\n{\n\tboost::lock_guard<boost::mutex> lock(m_mutex);\n\tm_transform = transform;\n\tm_transformInverse = m_transform.inverse();\n}\n\n};  // namespace Devices\n};  // namespace SurgSim\n", "meta": {"hexsha": "82bc63adadf3744179943549e36c810159844e32", "size": 8881, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SurgSim/Devices/DeviceFilters/PoseTransform.cpp", "max_stars_repo_name": "dbungert/opensurgsim", "max_stars_repo_head_hexsha": "bd30629f2fd83f823632293959b7654275552fa9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2015-01-19T16:18:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T03:29:11.000Z", "max_issues_repo_path": "SurgSim/Devices/DeviceFilters/PoseTransform.cpp", "max_issues_repo_name": "dbungert/opensurgsim", "max_issues_repo_head_hexsha": "bd30629f2fd83f823632293959b7654275552fa9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-12-21T14:54:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T12:38:07.000Z", "max_forks_repo_path": "SurgSim/Devices/DeviceFilters/PoseTransform.cpp", "max_forks_repo_name": "dbungert/opensurgsim", "max_forks_repo_head_hexsha": "bd30629f2fd83f823632293959b7654275552fa9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-04-10T19:45:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T17:00:59.000Z", "avg_line_length": 45.0812182741, "max_line_length": 117, "alphanum_fraction": 0.7713095372, "num_tokens": 2292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2672882474464243}}
{"text": "#include <iostream>\n\n#include <boost/program_options.hpp>\n\n#include \"functionality.hpp\"\n#include \"functionality_eigen.hpp\"\n\nnamespace po = boost::program_options;\n\nint main() {\n\n    std::cout << \"Checkpoint 3\" << std::endl;\n    std::cout << \"Hypergeometric probability: \" << hypergeometricPmf(10'000, 4'270, 300, 128) << std::endl;\n    std::cout << \"Random matrix: \" << std::endl;\n    printRandomMatrix();\n\n    // Use boost program options\n    {\n        po::options_description desc(\"Allowed options\");\n        desc.add_options()\n                (\"help\", \"produce help message\")\n                (\"compression\", po::value<int>(), \"set compression level\");\n\n        po::variables_map vm;\n\n        std::cout << desc << std::endl;\n    }\n\n    // int unused_variable = 0;\n\n    return 0;\n}\n", "meta": {"hexsha": "80520f90625fb97cc233dbf8035e9774e1356b15", "size": 783, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "checkpoint_5/exe/main.cpp", "max_stars_repo_name": "OxfordRSE/IntroCMakeCourse", "max_stars_repo_head_hexsha": "3eba68b9955b194a9d432d066c6422ccb006402e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-18T16:08:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-18T16:08:40.000Z", "max_issues_repo_path": "checkpoint_5/exe/main.cpp", "max_issues_repo_name": "OxfordRSE/IntroCMakeCourse", "max_issues_repo_head_hexsha": "3eba68b9955b194a9d432d066c6422ccb006402e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "checkpoint_5/exe/main.cpp", "max_forks_repo_name": "OxfordRSE/IntroCMakeCourse", "max_forks_repo_head_hexsha": "3eba68b9955b194a9d432d066c6422ccb006402e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-24T14:53:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-24T14:53:27.000Z", "avg_line_length": 23.7272727273, "max_line_length": 107, "alphanum_fraction": 0.6040868455, "num_tokens": 194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.2671908672959457}}
{"text": "// External libraries\n#include <boost/property_tree/ptree.hpp>\n\n// Local libraries\n#include <fmath/RungeKutta.h>\n#include <fparameters/SpaceIterator.h>\n#include <fparameters/Dimension.h>\n#include <fparameters/parameters.h>\n\n// Local headers\n#include \"write.h\"\n#include \"State.h\"\n#include \"modelParameters.h\"\n#include \"globalVariables.h\"\n#include \"adafFunctions.h\"\n\n//namespace {\ninline double safeLog10( double x )\t{ return x > 0.0 ? log10(x) : -100.0; }\n//}\nstd::string dataName(std::string id) {\n\treturn id + \".dat\";\n}\n\nvoid generateViewScript(std::string path) {\n\tstd::string filename = path.substr(path.find(\"\\\\\") + 1);\n\tstd::string folder = path.substr(0,path.find(\"\\\\\"));\n\tstd::ofstream file;\n\tfile.open((folder+\"/plots/plot-\"+filename+\".bat\").c_str(), std::ios::out);\n\tfile << \"@../../plot-svg-and-view.bat \" + filename;\n\tfile.close();\n}\n\nvoid writeAllSpaceParam(const std::string& filename, const ParamSpaceValues& data)\n{\n\tstd::ofstream file;\n\tfile.open(dataName(filename).c_str(), std::ios::out);\n\t//const ParamSpace* a = &(data.ps);\n\t\n\t// a.iterate;  no me deja hacer esta operacion\n\t\n\tdata.ps.iterate([&file, &data](const SpaceIterator& i){\n\t\tdouble logE = log10(i.val(DIM_E) / 1.6e-12);\n\t\tdouble logR = (i.val(DIM_R));\n\t\tdouble logT = (i.val(DIM_Rcd));\n\t\tdouble logQ = safeLog10(data.get(i)); //log10(salida.values(i));  // values(i));\n//\t\tsalida.values(i);\n\n\n\t\tfile << logE << '\\t' << logR << '\\t' << logT << '\\t' << \n\t\t\tlogQ << std::endl;\n\t\t\t//logQ << std::endl;\n\t});\n\n\tfile.close();\n\tgenerateViewScript(filename);\n}\n\nvoid writeEandRParamSpace(const std::string& filename, const ParamSpaceValues& data, int t,int vol)\n{\n\n\tstd::ofstream file;\n\tfile.open(dataName(filename).c_str(), std::ios::out);\n\n\t// version acotada\n\t//double time = log10(data.ps[1][t]);\n\t\n\tdata.ps.iterate([&](const SpaceIterator& i) {\n\t\t\n\t\tdouble logE = log10(i.val(DIM_E) / EV_TO_ERG);\n\t\tdouble r = i.val(DIM_R);\n\t\tdouble voll = (vol == 1) ? volume(r) : 1.0;\n\t\tdouble logQ = safeLog10(data.get(i)*voll);\n\t\tfile << logE << '\\t' << i.coord[DIM_R] << '\\t' << safeLog10(r/schwRadius) << '\\t' << logQ << std::endl;\n\t\t\t\n\t}, { -1, -1, t });  \n\n\tfile.close();\n\tgenerateViewScript(filename);\n}\n\nvoid writeRParamSpace(const std::string& filename, const ParamSpaceValues& data, int t, int s)\n{\n\n\tstd::ofstream file;\n\tfile.open(dataName(filename).c_str(), std::ios::out);\n\tdouble Emin = data.ps[DIM_E].first();\n\tdouble Emax = data.ps[DIM_E].last();\n\tdata.ps.iterate([&](const SpaceIterator& iR) {\n\t\tdouble tot = integSimpson(log(Emin),log(Emax),\n\t\t\t\t\t\t[&](double loge)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdouble e = exp(loge);\n\t\t\t\t\t\t\tdouble nPh = data.interpolate({{DIM_E,e}},&iR.coord);\n\t\t\t\t\t\t\treturn e*nPh;\n\t\t\t\t\t\t},100);\n\t\tfile << safeLog10(iR.val(DIM_R)/schwRadius) << '\\t' << safeLog10(tot) << std::endl;\n\t},{t,-1,s});  \n\tfile.close();\n\tgenerateViewScript(filename);\n}\n\nvoid writeEandTParamSpace(const std::string& filename, const ParamSpaceValues& data, int r)\n{\n\n\tstd::ofstream file;\n\tfile.open(dataName(filename).c_str(), std::ios::out);\n\n\t// version acotada\n\tdouble logR = log10(data.ps[1][r]);\n\t\n\tfile << \"log(r)=\" << logR << '\\t' ;\n\n\tfor (size_t t_ix = 0; t_ix < data.ps[2].size(); t_ix++) {\n\t\tdouble time = data.ps[2][t_ix];\n\t\tfile << \"t=\" << log10(time) << '\\t';\n\t}\n\n\n\tfor (int E_ix = 0; E_ix < data.ps[0].size(); E_ix++) {\n\n\t\tfile << std::endl;\n\n\t\tdouble logE = log10(data.ps[0][E_ix]/1.6e-12);\n\n\t\tfile << logE << '\\t';\n\n\t\tdata.ps.iterate([&file, &data](const SpaceIterator& i){\n\n\t\t\t//double logR = log10(i.val(DIM_R));\n\t\t\t//double time = i.val(DIM_T);\n\t\t\tdouble logQ = safeLog10(data.get(i));\n\n\t\t\tfile << logQ << '\\t';\n\t\t\t;\n\t\t}, { E_ix, r, -1 });  //el -1 indica que las E se recorren, no quedan fijas\n\t\t//las otras dos dimensiones quedan fijas en las posiciones r y t (recordar que la primera es 0 )\n\t}\n\tfile.close();\n\tgenerateViewScript(filename);\n}\n\n\nvoid writeRandTParamSpace(const std::string& filename, const ParamSpaceValues& data, int E)\n{\n\n\tstd::ofstream file;\n\tfile.open(dataName(filename).c_str(), std::ios::out);\n\n\n\tdata.ps.iterate([&file, &data](const SpaceIterator& i){\n\n\t\tdouble r = i.val(DIM_R);\n\t\t//double theta = i.val(DIM_THETA);\n\t\t\n\t\tfile << r << '\\t' << '\\t' << data.get(i) << std::endl;\n\t\t\n\t}, { E, -1, -1 });  //el -1 indica que las E se recorren, no quedan fijas\n\t//las otras dos dimensiones quedan fijas en las posiciones r y t (recordar que la primera es 0 )\n\t\n\tfile.close();\n\tgenerateViewScript(filename);\n}\n\n\nvoid writeEnergyFunction(const std::string& filename, const ParamSpaceValues& data, int r, int t)\n{\n\n\tstd::ofstream file;\n\tfile.open(dataName(filename).c_str(), std::ios::out);\n\n\t// version acotada\n\tdouble logR = log10(data.ps[1][r]);\n\t// version larga\n\tdouble logT = log10(data.ps.dimensions[2]->values[t]);\n\n\tfile << \"log(r)=\" << logR << '\\t' << \"log(t)=\" << logT << std::endl;\n\tdata.ps.iterate([&file, &data](const SpaceIterator& i){\n\n\t\tdouble logE = log10(i.val(DIM_E) / 1.6e-12);\n\t\tdouble logQ = safeLog10(data.get(i));\n\n\t\tfile << logE << '\\t' << logQ << std::endl;\n\t\t;\n\t}, { -1, r, t });  //el -1 indica que las E se recorren, no quedan fijas\n\t//las otras dos dimensiones quedan fijas en las posiciones r y t (recordar que la primera es 0 )\n\n\tfile.close();\n\tgenerateViewScript(filename);\n}\n\n\n\n\nvoid writeMatrix(const std::string& filename, Particle& p, Matrix& a)\n{\n\tstd::ofstream file;\n\tfile.open(dataName(filename).c_str(), std::ios::out);\n\n\tint nR = p.ps[DIM_R].size();  //ver el -1\n\n\tfile << '\\t';\n\t\n\tfor (size_t z_j = 0; z_j < nR; z_j++) { \n\t\tconst double r_j = p.ps[DIM_R][z_j];\n\t\tfile << r_j << '\\t' ;\n\t}\n\t\n\tfile << std::endl; \n\t\t\t\n\tfor (size_t z_i = 0; z_i < nR; z_i++) { \n\t\t\n\t\tconst double r_i = p.ps[DIM_R][z_i];\n\t\t\t\t\n\t\tfile << r_i << '\\t';\n\t\t\n\t\tfor (size_t z_j = 0; z_j < nR; z_j++) { \n\t\t\tconst double r_j = p.ps[DIM_R][z_j];\n\t\n\t\t\tfile << a[z_i][z_j] << '\\t' ;\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\tfile << std::endl;  \n\t}\n\t\n\tfile.close();\n\tgenerateViewScript(filename);\n}\n\nvoid writeFields(State& st) {\n\tstd::ofstream fields;\n\tfields.open(\"fields.dat\",std::ios::out);\n\tfields\t\t<< \"r_in [Rs] = \" << exp(logr.front()) << endl;\n\tfields\t\t<< \"r_out [Rs] = \" << exp(logr.back()) << endl << endl;\n\tfields  << \"rB1 [Rs]\" \t<< \"\\t\"\n\t\t\t<< \"r [Rs]\" \t<< \"\\t\"\n\t\t\t<< \"rB2 [Rs]\" \t<< \"\\t\"\n\t\t\t<< \"MdotRIAF\" \t<< \"\\t\"\n\t\t\t<< \"MdotCD\" \t<< \"\\t\"\n\t\t\t<< \"Te\"\t\t\t<< \"\\t\"\n\t\t\t<< \"Ti\"\t\t\t<< \"\\t\"\n\t\t\t<< \"H/R\"\t\t<< \"\\t\"\n\t\t\t<< \"ne\"\t\t\t<< \"\\t\"\n\t\t\t<< \"v/c\"\t\t<< \"\\t\"\n\t\t\t<< \"B\"\t\t\t<< endl;\n\n\tst.photon.ps.iterate([&](const SpaceIterator& iR) {\n\t\tdouble r = iR.val(DIM_R);\n\t\tfields \t<< r/schwRadius/sqrt(paso_r) << \"\\t\"\n\t\t\t\t<< r/schwRadius << \"\\t\"\n\t\t\t\t<< r/schwRadius * sqrt(paso_r) << \"\\t\"\n\t\t\t\t<< gAcc(r) << \"\\t\"\n\t\t\t\t<< accRateColdDisk(r)/accRateOut << \"\\t\"\n\t\t\t\t<< st.tempElectrons.get(iR) << \"\\t\"\n\t\t\t\t<< st.tempIons.get(iR) << \"\\t\"\n\t\t\t\t<< height_fun(r)/r << \"\\t\"\n\t\t\t\t<< electronDensity(r) << \"\\t\"\n\t\t\t\t<< abs(radialVel(r))/cLight <<\"\\t\"\n\t\t\t\t<< st.magf.get(iR) << endl;\n\t},{0,-1,0});\n\tfields.close();\n\t\n\tstd::ofstream SSD;\n\tSSD.open(\"SSD.dat\",std::ios::out);\n\tSSD\t\t<< \"r_tr [Rs] = \" << rTr/schwRadius << endl;\n\tSSD\t\t<< \"r_outCD [Rs] = \" << rOutCD/schwRadius << endl << endl;\n\tSSD  \t<< \"rB1 [Rs]\"\t\t\t<< \"\\t\"\n\t\t\t<< \"r [Rs]\" \t\t\t<< \"\\t\"\n\t\t\t<< \"rB2 [Rs]\"\t\t\t<< \"\\t\"\n\t\t\t<< \"MdotCD/MdotOut\" \t<< endl;\n\t\n\tst.photon.ps.iterate([&](const SpaceIterator& iRcd) {\n\t\tdouble rCD = iRcd.val(DIM_Rcd);\n\t\tSSD \t<< rCD/sqrt(paso_rCD)/schwRadius << \"\\t\"\n\t\t\t\t<< rCD/schwRadius << \"\\t\"\n\t\t\t\t<< rCD*sqrt(paso_rCD)/schwRadius << \"\\t\"\n\t\t\t\t<< accRateColdDisk(rCD)/accRateOut << endl;\n\t},{0,0,-1});\n\tSSD.close();\n}\n\nusing namespace H5;\n\nfloat *toFloatArray(const double *arr, size_t n) {\n  float *ret = new float[n];\n  for (int i = 0; i < n; i++) {\n    ret[i] = float(arr[i]);\n  }\n  return ret;\n}\n\nvoid MultiplyVectorByScalar(Vector v, double s, Vector& w) {\n\t// Multiply vector v by scalar s and stores the data in w\n    transform(v.begin(), v.end(), w.begin(), [s](double &x){ return x*s; });\n}\n\nvoid DivideVectorByVector(Vector v1, Vector v2, Vector& w) {\n\t// Multiply vector v by scalar s and stores the data in w\n    transform(v1.begin(), v1.end(), v2.begin(), w.begin(), divides<double>());\n}\n\nvoid EvaluateFunctionInVector(fun1 f, Vector v, Vector& w) {\n\t// Evaluate f in vector v and stores the data in w\n    transform(v.begin(), v.end(), w.begin(), [f](double &x){ return f(x); });\n}\n\nvoid myH5_write_single_float(const double x, H5File &h5f, H5std_string DATASET_NAME)\n{\n\tfloat y[1];\t*y = float(x);\n\thsize_t dims[1] = { 1 };\n\tDataSpace dataspace(1, dims);\n\tDataSet dataset = h5f.createDataSet(DATASET_NAME, PredType::NATIVE_FLOAT, dataspace);\n\tdataset.write(y, PredType::NATIVE_FLOAT);\n}\n\nvoid myH5_write_single_float(const double x, Group &h5g, H5std_string DATASET_NAME)\n{\n\tfloat y[1];\t*y = float(x);\n\thsize_t dims[1] = { 1 };\n\tDataSpace dataspace(1, dims);\n\tDataSet dataset = h5g.createDataSet(DATASET_NAME, PredType::NATIVE_FLOAT, dataspace);\n\tdataset.write(y, PredType::NATIVE_FLOAT);\n}\n\nvoid myH5_write_1d_float(const Vector v, H5File &h5f, H5std_string DATASET_NAME)\n{\n\tsize_t n = v.size();\n\thsize_t dims[1] = { n };\n\tDataSpace dataspace(1, dims);\n\tDataSet dataset = h5f.createDataSet(DATASET_NAME, PredType::NATIVE_FLOAT, dataspace);\n\tdataset.write(toFloatArray(v.data(), n), PredType::NATIVE_FLOAT);\n}\n\nvoid myH5_write_1d_float(const Vector v, Group &h5g, H5std_string DATASET_NAME)\n{\n\tsize_t n = v.size();\n\thsize_t dims[1] = { n };\n\tDataSpace dataspace(1, dims);\n\tDataSet dataset = h5g.createDataSet(DATASET_NAME, PredType::NATIVE_FLOAT, dataspace);\n\tdataset.write(toFloatArray(v.data(), n), PredType::NATIVE_FLOAT);\n}\n\nvoid myH5_write_single_double(const double x, H5File &h5f, H5std_string DATASET_NAME)\n{\n\tfloat y[1];\t*y = float(x);\n\thsize_t dims[1] = { 1 };\n\tDataSpace dataspace(1, dims);\n\tDataSet dataset = h5f.createDataSet(DATASET_NAME, PredType::NATIVE_DOUBLE, dataspace);\n\tdataset.write(y, PredType::NATIVE_DOUBLE);\n}\n\nvoid myH5_write_single_double(const double x, Group &h5g, H5std_string DATASET_NAME)\n{\n\tdouble y[1];\t*y = double(x);\n\thsize_t dims[1] = { 1 };\n\tDataSpace dataspace(1, dims);\n\tDataSet dataset = h5g.createDataSet(DATASET_NAME, PredType::NATIVE_DOUBLE, dataspace);\n\tdataset.write(y, PredType::NATIVE_DOUBLE);\n}\n\nvoid myH5_write_1d_double(const Vector v, H5File &h5f, H5std_string DATASET_NAME)\n{\n\tsize_t n = v.size();\n\thsize_t dims[1] = { n };\n\tDataSpace dataspace(1, dims);\n\tDataSet dataset = h5f.createDataSet(DATASET_NAME, PredType::NATIVE_DOUBLE, dataspace);\n\tdataset.write(v.data(), PredType::NATIVE_DOUBLE);\n}\n\nvoid myH5_write_1d_double(const Vector v, Group &h5g, H5std_string DATASET_NAME)\n{\n\tsize_t n = v.size();\n\thsize_t dims[1] = { n };\n\tDataSpace dataspace(1, dims);\n\tDataSet dataset = h5g.createDataSet(DATASET_NAME, PredType::NATIVE_DOUBLE, dataspace);\n\tdataset.write(v.data(), PredType::NATIVE_DOUBLE);\n}\n\nint createH5file(const H5std_string FILE_NAME, const State& st)\n{\n\t// Try block to detect exceptions raised by any of the calls inside it\n    try {\n        // Turn off the auto-printing when failure occurs so that we can\n        // handle the errors appropriately\n        Exception::dontPrint();\n\n        // Create a new file using default property lists.\n        H5File h5file(FILE_NAME, H5F_ACC_TRUNC);\n\n\t\t// HEADER ///////////////////////////////////////////////////////////////////////\n\t\t//Group *header_id = new Group(h5file->createGroup(\"Header\"));\n\t\tGroup header_id = h5file.createGroup(\"Header\");\n\t\tmyH5_write_single_float(blackHoleMass/solarMass, header_id, \"M\");\n\t\tmyH5_write_single_float(accRateOut / (1.39e18 * blackHoleMass/solarMass), header_id, \"Mdot_out\");\n\t\tmyH5_write_single_float(s, header_id, \"sWind\");\n\t\tmyH5_write_single_float(delta, header_id, \"delta_e\");\n\t\tmyH5_write_single_float(magFieldPar, header_id, \"beta\");\n\t\tmyH5_write_single_float(alpha, header_id, \"alpha\");\n\t\tmyH5_write_single_float(jAngMom, header_id, \"jAngMom\");\n\n\t\t//delete header_id;\n\t\t/////////////////////////////////////////////////////////////////////////////////\n\n\t\t// RIAF /////////////////////////////////////////////////////////////////////////\n\n\t\tGroup RIAF_id = h5file.createGroup(\"RIAF\");\n\n\t\tVector rVec = st.photon.ps.dimensions[DIM_R]->values;\n\t\tVector w(nR, 0.0);\n\t\n\t\tMultiplyVectorByScalar(rVec, 1.0/schwRadius, w);\n\t\tmyH5_write_1d_float(w, RIAF_id, \"r\");\n\t\tw.assign(w.size(), 0.0);\n\n\t\tEvaluateFunctionInVector([](double r) { return volume(r)/P3(schwRadius); }, rVec, w);\n\t\tmyH5_write_1d_float(w, RIAF_id, \"volume\");\n\t\tw.assign(w.size(), 0.0);\n\n\t\tEvaluateFunctionInVector([](double r) { return accRateADAF(r)/accRateOut; }, rVec, w);\n\t\tmyH5_write_1d_float(w, RIAF_id, \"Mdot\");\n\t\tw.assign(w.size(), 0.0);\n\t\t\n\t\tEvaluateFunctionInVector([](double r)\n\t\t\t\t\t{ return boltzmann/electronRestEnergy * electronTemp(r); }, rVec, w);\n\t\tmyH5_write_1d_float(w, RIAF_id, \"Te\");\n\n\t\tEvaluateFunctionInVector([](double r)\n\t\t\t\t\t{ return boltzmann/protonRestEnergy * ionTemp(r); }, rVec, w);\n\t\tmyH5_write_1d_float(w, RIAF_id, \"Ti\");\n\t\tw.assign(w.size(), 0.0);\n\n\t\tEvaluateFunctionInVector([](double r) { return height_fun(r)/r; }, rVec, w);\n\t\tmyH5_write_1d_float(w, RIAF_id, \"H_R\");\n\t\tw.assign(w.size(), 0.0);\n\n\t\tEvaluateFunctionInVector(electronDensity, rVec, w);\n\t\tmyH5_write_1d_float(w, RIAF_id, \"n_e\");\n\t\tw.assign(w.size(), 0.0);\n\n\t\tEvaluateFunctionInVector([](double r) {return abs(radialVel(r))/cLight; }, rVec, w);\n\t\tmyH5_write_1d_float(w, RIAF_id, \"v_c\");\n\t\tw.assign(w.size(), 0.0);\n\n\t\tEvaluateFunctionInVector(magneticField, rVec, w);\n\t\tmyH5_write_1d_float(w, RIAF_id, \"B\");\n\n\t\tmyH5_write_1d_float(redshift_to_inf, RIAF_id, \"redshift_to_inf\");\n\n\t\tRIAF_id.close();\n\n\t\tGroup SSD_id = h5file.createGroup(\"SSD\");\n\t\tSSD_id.close();\n\n\t\tGroup Particles_id = h5file.createGroup(\"Particles\");\n\t\tfor (const auto &p : st.particles) {\n   \t\t\tGroup p_id = Particles_id.createGroup(p->id);\n\t\t\thsize_t dims[2] = { nR, nE };\n\t\t\tDataSpace dataspace(2, dims);\n\t\t\tp_id.createDataSet(\"Injection\", PredType::NATIVE_FLOAT, dataspace);\n\t\t\tp_id.createDataSet(\"Distribution\", PredType::NATIVE_FLOAT, dataspace);\n\t\t}\n\t\tParticles_id.close();\n\t\th5file.close();\n\n    } // end of try block\n    // catch failure caused by the H5File operations\n    catch (FileIException error) {\n        error.printErrorStack();\n        return -1;\n    }\n    // catch failure caused by the Group operations\n    catch (GroupIException error) {\n        error.printErrorStack();\n        return -1;\n    }\n\tcatch (DataSetIException error) {\n        error.printErrorStack();\n        return -1;\n    }\n    // catch failure caused by the DataSpace operations\n    catch (DataSpaceIException error) {\n        error.printErrorStack();\n        return -1;\n    }\n\treturn 0;\n}", "meta": {"hexsha": "d3bf6d619e6e17050c03fdf0b4502244520527ad", "size": 14494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/adaf/write.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/write.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/write.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.7618069815, "max_line_length": 105, "alphanum_fraction": 0.635918311, "num_tokens": 4646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2671908600156701}}
{"text": "//=======================================================================\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek\n//\n// This file is part of the Boost Graph Library\n//\n// You should have received a copy of the License Agreement for the\n// Boost Graph Library along with the software; see the file LICENSE.\n// If not, contact Office of Research, University of Notre Dame, Notre\n// Dame, IN 46556.\n//\n// Permission to modify the code and to distribute modified code is\n// granted, provided the text of this NOTICE is retained, a notice that\n// the code was modified is included with the above COPYRIGHT NOTICE and\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n// file is distributed with the modified code.\n//\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n// By way of example, but not limitation, Licensor MAKES NO\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\n// OR OTHER RIGHTS.\n//=======================================================================\n\n/*\n  This file implements the function\n\n  template <class VertexAndEdgeListGraph, class DistanceMatrix,\n            class P, class T, class R>\n  bool\n  johnson_all_pairs_shortest_paths\n    (VertexAndEdgeListGraph& g, \n     DistanceMatrix& D,\n     const bgl_named_params<P, T, R>& params)\n */\n\n#ifndef BOOST_GRAPH_JOHNSON_HPP\n#define BOOST_GRAPH_JOHNSON_HPP\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map.hpp>\n#include <boost/graph/bellman_ford_shortest_paths.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n\nnamespace boost {\n\n  namespace detail {\n\n    template <class VertexAndEdgeListGraph, class DistanceMatrix,\n              class P, class T, class R, class VertexID, class Distance,\n              class Weight, class Weight2, class DistanceZero>\n    bool\n    johnson_impl(VertexAndEdgeListGraph& g, \n                 DistanceMatrix& D,\n                 const bgl_named_params<P, T, R>& params,\n                 VertexID id, Distance d, Weight w, Weight2 w_hat,\n                 DistanceZero zero)\n    {\n      typedef graph_traits<VertexAndEdgeListGraph> Traits;\n      typename Traits::vertex_iterator v, v_end, u, u_end;\n      typename Traits::edge_iterator e, e_end;\n      typename Traits::vertex_descriptor s = *vertices(g).first;\n      typedef typename property_traits<Distance>::value_type DT;\n      function_requires< BasicMatrixConcept<DistanceMatrix,\n        typename Traits::vertex_descriptor, DT> >();\n      \n      std::vector<DT> h_vec(num_vertices(g));\n      typedef typename std::vector<DT>::iterator iter_t;\n      iterator_property_map<iter_t, VertexID, DT, DT&> h(h_vec.begin(), id);\n\n      put(d, s, zero);\n      if (bellman_ford_shortest_paths(g, num_vertices(g), params)) {\n        for (tie(v, v_end) = vertices(g); v != v_end; ++v)\n          put(h, *v, get(d, *v));\n        for (tie(e, e_end) = edges(g); e != e_end; ++e)\n          put(w_hat, *e, \n              get(w, *e) + get(h, source(*e,g)) - get(h, target(*e,g)));\n        for (tie(u, u_end) = vertices(g); u != u_end; ++u) {\n          dijkstra_shortest_paths(g, *u, params.weight_map(w_hat));\n          for (tie(v, v_end) = vertices(g); v != v_end; ++v)\n            D[*u][*v] = get(d, *v) + get(h, *v) - get(h, *u);\n        }\n        return true;\n      } else\n        return false;\n    }\n    \n    template <class VertexAndEdgeListGraph, class DistanceMatrix,\n              class P, class T, class R, class Weight, \n              class VertexID>\n    bool\n    johnson_dispatch(VertexAndEdgeListGraph& g, \n                     DistanceMatrix& D,\n                     const bgl_named_params<P, T, R>& params,\n                     Weight w, VertexID id)\n    {\n      typedef typename property_traits<Weight>::value_type WT;\n      typename std::vector<WT>::size_type \n        n = is_default_param(get_param(params, vertex_distance))\n        ? num_vertices(g) : 1;\n      std::vector<WT> distance_map(n);\n      \n      return detail::johnson_impl\n        (g, D, params, id,\n         choose_param(get_param(params, vertex_distance),\n                      make_iterator_property_map\n                      (distance_map.begin(), id, distance_map[0])),\n         w,\n         choose_pmap(get_param(params, edge_weight2), g, edge_weight2),\n         choose_param(get_param(params, distance_zero_t()), \n                      WT()) );\n    }\n\n  } // namespace detail\n\n  template <class VertexAndEdgeListGraph, class DistanceMatrix,\n            class P, class T, class R>\n  bool\n  johnson_all_pairs_shortest_paths\n    (VertexAndEdgeListGraph& g, \n     DistanceMatrix& D,\n     const bgl_named_params<P, T, R>& params)\n  {\n    return detail::johnson_dispatch\n      (g, D, params,\n       choose_const_pmap(get_param(params, edge_weight), g, edge_weight),\n       choose_const_pmap(get_param(params, vertex_index), g, vertex_index)\n       );\n  }\n\n  template <class VertexAndEdgeListGraph, class DistanceMatrix>\n  bool\n  johnson_all_pairs_shortest_paths\n    (VertexAndEdgeListGraph& g, DistanceMatrix& D)\n  {\n    bgl_named_params<int,int> params(1);\n    return detail::johnson_dispatch\n      (g, D, params, get(edge_weight, g), get(vertex_index, g));\n  }\n\n\n} // namespace boost\n\n#endif // BOOST_GRAPH_JOHNSON_HPP\n\n\n", "meta": {"hexsha": "49bc2c3bc84bab3cce263740becdd9f6bf329bec", "size": 5458, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vegastrike/boost/1_28/boost/graph/johnson_all_pairs_shortest.hpp", "max_stars_repo_name": "Ezeer/VegaStrike_win32FR", "max_stars_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vegastrike/boost/1_28/boost/graph/johnson_all_pairs_shortest.hpp", "max_issues_repo_name": "Ezeer/VegaStrike_win32FR", "max_issues_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vegastrike/boost/1_28/boost/graph/johnson_all_pairs_shortest.hpp", "max_forks_repo_name": "Ezeer/VegaStrike_win32FR", "max_forks_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8783783784, "max_line_length": 76, "alphanum_fraction": 0.6390619274, "num_tokens": 1321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136564, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.2669631539764041}}
{"text": "/* \n *            Copyright 2009-2017 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 \"A_ol I_ol\" BA_olI_ol,\n * WITHOUT WARRANTIE_ol OR CONDITION_ol OF ANY KIND, either express or implied.\n * _olee the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n// Overload of uBLAS prod function with MKL/GSL implementations\n#include <votca/tools/linalg.h>\n\n#include <boost/math/constants/constants.hpp>\n#include \"votca/xtp/radial_euler_maclaurin_rule.h\"\n#include \"votca/xtp/aobasis.h\"\n#include <votca/xtp/aomatrix.h>\n\n\n\n\nnamespace votca { namespace xtp { \n    \n    \n    std::vector<double> EulerMaclaurinGrid::getPruningIntervals(string element){\n        \n        std::vector<double> _r;\n        \n        // get Bragg-Slater Radius for this element\n        double BSradius = _BraggSlaterRadii.at(element);\n        \n        // row type of element\n        int RowType = _pruning_set.at(element);\n        \n        if ( RowType == 1 ){\n            \n            \n            _r.push_back( 0.25 * BSradius );\n            _r.push_back( 0.5 * BSradius );\n            _r.push_back( 1.0 * BSradius );\n            _r.push_back( 4.5 * BSradius );\n            \n        } else if ( RowType == 2 ){\n            \n            _r.push_back( 0.1667 * BSradius );\n            _r.push_back( 0.5 * BSradius );\n            _r.push_back( 0.9 * BSradius );\n            _r.push_back( 3.5 * BSradius );            \n            \n            \n        } else if ( RowType == 3 ) {\n            \n            _r.push_back( 0.1 * BSradius );\n            _r.push_back( 0.4 * BSradius );\n            _r.push_back( 0.8 * BSradius );\n            _r.push_back( 2.5 * BSradius );\n            \n        } else {\n            \n            cerr << \"Pruning unsupported for RowType \" << RowType << endl;\n            exit(1);\n        }\n\n        return _r;\n     }\n    \n     \nvoid EulerMaclaurinGrid::getRadialCutoffs(std::vector<ctp::QMAtom* > _atoms, BasisSet* bs, string gridtype) {\n\n            map<string, min_exp>::iterator it;\n            std::vector< ctp::QMAtom* > ::iterator ait;\n            std::vector< ctp::QMAtom* > ::iterator bit;\n\n            double eps = Accuracy[gridtype];\n            double _decaymin;\n            int _lvalue;\n            //  cout << endl << \" Setting cutoffs for grid type \" << gridtype << \" eps = \" << eps << endl;\n            // 1) is only element based\n            // loop over atoms\n            for (ait = _atoms.begin(); ait < _atoms.end(); ++ait) {\n                // get element type of the atom\n                string name = (*ait)->type;\n                // is this element already in map?\n                it = _element_ranges.find(name);\n                // only proceed, if element data does not exist yet\n                if (it == _element_ranges.end()) {\n                    // get first range estimate and add to map\n                    min_exp this_atom;\n                    double range_max = 0.0;\n                    // get the basis set entry for this element\n                    Element* _element = bs->getElement(name);\n                    // and loop over all shells to figure out minimum decay constant and angular momentum of this function\n                    for (Element::ShellIterator its = _element->firstShell(); its != _element->lastShell(); its++) {\n                        Shell* shell = (*its);\n                        _decaymin = 1e7;\n                        _lvalue = 0;\n                        int _lmax = shell->getLmax();\n                        for (Shell::GaussianIterator itg = shell->firstGaussian(); itg != shell->lastGaussian(); itg++) {\n                            GaussianPrimitive* gaussian = *itg;\n                            double _decay = gaussian->decay;\n                            if (_decay < _decaymin) {\n                                _decaymin = _decay;\n                                _lvalue = _lmax;\n                            }\n                        }\n                        double range = DetermineCutoff(2 * _decaymin, 2 * _lvalue + 2, eps);\n                        if (range > range_max) {\n                            this_atom.alpha = _decaymin;\n                            this_atom.l = _lvalue;\n                            this_atom.range = range;\n                            range_max = range;\n                        }\n                    } // shells\n\n                    //   cout << \"Element \" << name << \" alpha \" << this_atom.alpha << \" l \" << this_atom.l << \" Rcut \" << this_atom.range << endl;\n                    _element_ranges[name] = this_atom;\n                } // new element\n            } // atoms\n\n            // calculate overlap matrix\n            AOBasis aobasis;\n            aobasis.AOBasisFill(bs, _atoms);\n            AOOverlap _overlap;\n            // Fill overlap\n            _overlap.Fill(aobasis);\n\n\n\n            // refining by going through all atom combinations\n            // get collapsed index list\n            int atidx = 0;\n            std::vector<int> idxstart;\n            std::vector<int> idxstop;\n            int start = 0;\n            int end = 0;\n            for (AOBasis::AOShellIterator _row = aobasis.firstShell(); _row != aobasis.lastShell(); _row++) {\n\n                const AOShell* _shell_row = aobasis.getShell(_row);\n\n                if (_shell_row->getIndex() == atidx) {\n\n                    end += _shell_row->getNumFunc();\n                } else {\n\n                    idxstart.push_back(start);\n                    idxstop.push_back(end);\n                    atidx++;\n                    start = end;\n                    end += _shell_row->getNumFunc();\n                }\n            }\n\n            idxstart.push_back(start);\n            idxstop.push_back(end);\n\n            int aidx = 0;\n\n            for (ait = _atoms.begin(); ait < _atoms.end(); ++ait) {\n\n                int _a_start = idxstart[aidx];\n                int _a_stop = idxstop[aidx];\n\n                double range_max = 0.0;\n\n                // get preset values for this atom type\n                double exp_iat = _element_ranges.at((*ait)->type).alpha;\n                int l_iat = _element_ranges.at((*ait)->type).l;\n\n                vec pos_a = (*ait)->getPos() * tools::conv::bohr2ang;\n\n\n                string type_diff;\n                int bidx = 0;\n                for (bit = _atoms.begin(); bit < _atoms.end(); ++bit) {\n\n                    int _b_start = idxstart[bidx];\n                    int _b_stop = idxstop[bidx];\n                    vec pos_b = (*bit)->getPos() * tools::conv::bohr2ang;\n                    // now do some overlap gymnastics\n                    double s_max = 10.0;\n                    if (aidx != bidx) {\n\n                        // find overlap block of these two atoms\n                        ub::matrix<double> _overlapblock = ub::project(_overlap.Matrix(), ub::range(_a_start, _a_stop), ub::range(_b_start, _b_stop));\n                        // determine abs max of this block\n                        s_max = 0.0;\n                        for (unsigned i = 0; i < _overlapblock.size1(); i++) {\n                            for (unsigned j = 0; j < _overlapblock.size2(); j++) {\n                                s_max = std::max(s_max, std::abs(_overlapblock(i, j)));\n                            }\n                        }\n                    }\n\n                    if (s_max > 1e-5) {\n                        // cout << \" Atom \" << aidx << \" neighbor \" << bidx << \" s-max \" << s_max << \" exponents \" << exp_iat << \" and \" << _element_ranges.at((*bit)->type).alpha << endl;\n                        double range = DetermineCutoff(exp_iat + _element_ranges.at((*bit)->type).alpha, l_iat + _element_ranges.at((*bit)->type).l + 2, eps);\n                        // now do some update trickery from Gaussian product formula\n                        double dist = abs(pos_b - pos_a);\n                        double shift_2g = dist * exp_iat / (exp_iat + _element_ranges.at((*bit)->type).alpha);\n                        range += shift_2g;\n\n\n                        if (aidx != bidx) range += dist;\n\n                        if (range > range_max) {\n                            //shiftm_2g = shift_2g;\n                            range_max = range;\n                            //iat_diff = bidx;\n                            type_diff = (*bit)->type;\n                        }\n\n                    }\n\n                    bidx++;\n                }\n\n\n                if (round(range_max) > _element_ranges.at((*ait)->type).range) {\n                    _element_ranges.at((*ait)->type).range = round(range_max);\n                }\n                aidx++;\n            }\n           \n          return;  \n        } // getRadialCutoffs\n    \n    \n    \n    \n    \n    \n    void EulerMaclaurinGrid::getRadialGrid(BasisSet* bs , std::vector<ctp::QMAtom* > _atoms, string type, GridContainers& _grid) {\n\n        \n            map<string, min_exp>::iterator it;\n            getRadialCutoffs(_atoms,bs,type);\n            \n            // go through all elements\n            for ( it = _element_ranges.begin() ; it != _element_ranges.end() ; ++it){\n                \n                 // cout << \"Element \" << it->first << \" alpha \" << it->second.alpha << \" l \" << it->second.l << \" Rcut \" << it->second.range <<  \" Rcut (Ang) \" <<  it->second.range  * 0.529177249 << endl;\n                \n                std::vector<double> points;\n                std::vector<double> weights;\n                int numberofpoints = getGrid(it->first, type);\n                //cout << \" Setting grid for element \" << it->first <<  \" with \" << numberofpoints << \" points \" <<  endl ;\n                setGrid( numberofpoints, it->second.range, points, weights );\n                \n                //grid_element this_element;\n                //this_element.gridpoint = points;\n                //this_element.weight = weights;\n                \n                //_element_grids[it->first] = this_element;\n                \n                _grid._radial_grids[it->first].radius = points; \n                _grid._radial_grids[it->first].weight = weights;\n                \n            }\n              \n    }\n    \n    \n    void EulerMaclaurinGrid::setGrid(int np, double cutoff, std::vector<double>& point, std::vector<double>& weight ){\n        \n        double alpha = -cutoff/(log(1.0 - pow(  (1.0 + double(np))/(2.0 + double(np)),3)) );\n        \n        \n        double factor = 3.0/(1.0+double(np));\n        \n        for ( int i = 0; i < np; i++){\n            double q = double(i+1)/(double(np)+1.0);\n            double r = -alpha*log(1.0-pow(q,3));\n            double w = factor * alpha * r*r/( 1.0 - pow(q,3) ) * pow(q,2);\n            \n            point.push_back(r);\n            weight.push_back(w);\n            \n        }\n        \n        \n        \n        \n    }\n    \n    \n    \n    \n    double EulerMaclaurinGrid::DetermineCutoff(double alpha, int l, double eps){\n        \n      // determine norm of function              \n                                                                                                                                                                                                     \n     /* For a function f(r) = r^k*exp(-alpha*r^2) determine                                                                                                                                                          \n        the radial distance r such that the fraction of the                                                                                                                                                          \n        function norm that is neglected if the 3D volume                                                                                                                                                             \n        integration is terminated at a distance r is less                                                                                                                                                            \n        than or equal to eps. */                                                                                                                                                                                       \n   \n        \n        double _cutoff    = 1.0; // initial value\n        double _increment = 0.5; // increment\n\n            while (_increment > 0.01) {\n                double _neglected = getNeglected(alpha,l ,  _cutoff);\n                // cout << \"neglected is \" << _neglected << endl;\n                if (_neglected > eps) {\n                    _cutoff += _increment;\n                } else {\n                    _cutoff -= _increment;\n                    if (_cutoff < 0.0) _cutoff = 0.0;\n                    _increment = 0.5 * _increment;\n                    _cutoff += _increment;\n                }\n            }\n\n        return _cutoff;\n       \n    }\n    \n    \n    \n    \n    double EulerMaclaurinGrid::getNeglected(double alpha, int l, double cutoff){\n        \n        return RadialIntegral(alpha,l+2,cutoff) / RadialIntegral(alpha,l+2, 0.0); \n        \n        \n    }\n\n\n    double EulerMaclaurinGrid::RadialIntegral(double alpha, int l, double cutoff){\n        \n        const double pi = boost::math::constants::pi<double>();\n        int ilo = l % 2;\n        double value = 0.0;\n        double valexp;\n        if ( ilo == 0 ){\n            double expo = sqrt(alpha)*cutoff;\n            if ( expo > 40.0 ) {\n                value = 0.0;\n            } else {\n                value = 0.5 * sqrt(  pi /alpha  ) * erfc(expo);\n            }\n        }\n        \n        double exponent = alpha*cutoff*cutoff;\n        if ( exponent > 500.0 ) {\n            valexp = 0.0;\n            value = 0.0;\n        } else {\n            valexp = exp(-exponent);\n            value = valexp/2.0/alpha;\n        }\n            \n        \n        for (  int i = ilo+2; i <= l; i+=2){\n            value = ((i-1)*value + pow(cutoff,i-1)*valexp)/2.0/alpha;\n        }\n        \n        return value;\n         \n        \n        \n    }\n    \n\n    \n    int EulerMaclaurinGrid::getGrid(string element, string type){\n        \n        if ( type == \"medium\"){\n            \n            return MediumGrid.at(element);            \n            \n        }\n        else if ( type == \"coarse\"){\n            \n            return CoarseGrid.at(element);            \n            \n        }\n        else if ( type == \"xcoarse\"){\n            \n            return XcoarseGrid.at(element);            \n            \n        }\n        else if ( type == \"fine\"){\n            \n            return FineGrid.at(element);            \n            \n        }\n        else if ( type == \"xfine\"){\n            \n            return XfineGrid.at(element);            \n            \n        }\n\n        throw std::runtime_error(\"Grid type \"+type+\" is not implemented\");\n        return -1;\n        \n        \n    }\n    \n\n}\n}\n", "meta": {"hexsha": "796c1f4dc447e73ac23a9eca113296c9556928b6", "size": 15253, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/numerical_integration/radial_euler_maclaurin_rule.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/numerical_integration/radial_euler_maclaurin_rule.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/numerical_integration/radial_euler_maclaurin_rule.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": 37.0218446602, "max_line_length": 215, "alphanum_fraction": 0.4290959156, "num_tokens": 3269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2669302623169275}}
{"text": "/******************************************************************************\n**\n** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>\n** All rights reserved.\n**\n** This file is a part of the chemkit project. For more information\n** see <http://www.chemkit.org>.\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 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 chemkit project 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 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**\n******************************************************************************/\n\n#include \"mmffcalculation.h\"\n\n#include <boost/lexical_cast.hpp>\n\n#include <chemkit/topology.h>\n#include <chemkit/constants.h>\n#include <chemkit/forcefield.h>\n#include <chemkit/cartesiancoordinates.h>\n\n#include \"mmffparameters.h\"\n\n// === MmffCalculation ===================================================== //\nMmffCalculation::MmffCalculation(int type, int atomCount, int parameterCount)\n    : ForceFieldCalculation(type, atomCount, parameterCount)\n{\n}\n\n// === MmffBondStrechCalculation =========================================== //\nMmffBondStrechCalculation::MmffBondStrechCalculation(size_t a, size_t b)\n    : MmffCalculation(BondStrech, 2, 2)\n{\n    setAtom(0, a);\n    setAtom(1, b);\n}\n\nbool MmffBondStrechCalculation::setup(const MmffParameters *parameters)\n{\n    const boost::shared_ptr<chemkit::Topology> &topology = this->topology();\n\n    size_t a = atom(0);\n    size_t b = atom(1);\n\n    int typeA = boost::lexical_cast<int>(topology->type(a));\n    int typeB = boost::lexical_cast<int>(topology->type(b));\n    int bondType = topology->bondedInteractionType(a, b);\n\n    const MmffBondStrechParameters *bondStrechParameters = parameters->bondStrechParameters(bondType, typeA, typeB);\n    if(bondStrechParameters){\n        setParameter(0, bondStrechParameters->kb);\n        setParameter(1, bondStrechParameters->r0);\n        return true;\n    }\n\n    return false;\n}\n\nchemkit::Real MmffBondStrechCalculation::energy(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n\n    chemkit::Real kb = parameter(0);\n    chemkit::Real r0 = parameter(1);\n\n    chemkit::Real r = coordinates->distance(a, b);\n    chemkit::Real dr = r - r0;\n    chemkit::Real cs = -2.0; // cubic strech constant\n\n    // equation 2\n    return 143.9325 * (kb / 2) * (dr*dr) * (1 + cs * dr + ((7.0/12.0)*(cs*cs)) * (dr*dr));\n}\n\nstd::vector<chemkit::Vector3> MmffBondStrechCalculation::gradient(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n\n    chemkit::Real kb = parameter(0);\n    chemkit::Real r0 = parameter(1);\n\n    chemkit::Real r = coordinates->distance(a, b);\n    chemkit::Real dr = r - r0;\n    chemkit::Real cs = -2.0; // cubic strech constant\n\n    // dE/dr\n    chemkit::Real de_dr = 143.9325 * kb * dr * (1 + cs * dr + (7.0/12.0 * (cs*cs) * (dr*dr)) + 0.5 * dr * (cs + (14.0/12.0 * (cs*cs) * dr)));\n\n    boost::array<chemkit::Vector3, 2> gradient = coordinates->distanceGradient(a, b);\n\n    gradient[0] *= de_dr;\n    gradient[1] *= de_dr;\n\n    return std::vector<chemkit::Vector3>(gradient.begin(), gradient.end());\n}\n\n// === MmffAngleBendCalculation ============================================ //\nMmffAngleBendCalculation::MmffAngleBendCalculation(size_t a, size_t b, size_t c)\n    : MmffCalculation(AngleBend, 3, 2)\n{\n    setAtom(0, a);\n    setAtom(1, b);\n    setAtom(2, c);\n}\n\nbool MmffAngleBendCalculation::setup(const MmffParameters *parameters)\n{\n    const boost::shared_ptr<chemkit::Topology> &topology = this->topology();\n\n    size_t a = atom(0);\n    size_t b = atom(1);\n    size_t c = atom(2);\n\n    int typeA = boost::lexical_cast<int>(topology->type(a));\n    int typeB = boost::lexical_cast<int>(topology->type(b));\n    int typeC = boost::lexical_cast<int>(topology->type(c));\n    int angleType = topology->angleInteractionType(a, b, c);\n\n    const MmffAngleBendParameters *angleBendParameters =\n        parameters->angleBendParameters(angleType, typeA, typeB, typeC);\n\n    if(angleBendParameters){\n        setParameter(0, angleBendParameters->ka);\n        setParameter(1, angleBendParameters->theta0);\n        return true;\n    }\n\n    return false;\n}\n\nchemkit::Real MmffAngleBendCalculation::energy(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n    size_t c = atom(2);\n\n    chemkit::Real ka = parameter(0);\n    chemkit::Real t0 = parameter(1);\n\n    chemkit::Real cb = -0.007; // cubic bend constant\n    chemkit::Real t = coordinates->angle(a, b, c);\n    chemkit::Real dt = t - t0;\n\n    // equation 3\n    return 0.043844 * (ka / 2.0) * pow(dt, 2) * (1 + cb * dt);\n}\n\nstd::vector<chemkit::Vector3> MmffAngleBendCalculation::gradient(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n    size_t c = atom(2);\n\n    chemkit::Real ka = parameter(0);\n    chemkit::Real t0 = parameter(1);\n\n    chemkit::Real cb = -0.007; // cubic bend constant\n    chemkit::Real t = coordinates->angle(a, b, c);\n    chemkit::Real dt = t - t0;\n\n    // dE/dt\n    chemkit::Real de_dt = 0.043844 * ka * dt * (1 + cb * dt + 0.5 * cb * dt);\n\n    boost::array<chemkit::Vector3, 3> gradient = coordinates->angleGradient(a, b, c);\n\n    gradient[0] *= de_dt;\n    gradient[1] *= de_dt;\n    gradient[2] *= de_dt;\n\n    return std::vector<chemkit::Vector3>(gradient.begin(), gradient.end());\n}\n\n// === MmffStrechBendCalculation =========================================== //\nMmffStrechBendCalculation::MmffStrechBendCalculation(size_t a, size_t b, size_t c)\n    : MmffCalculation(BondStrech | AngleBend, 3, 5)\n{\n    setAtom(0, a);\n    setAtom(1, b);\n    setAtom(2, c);\n}\n\nbool MmffStrechBendCalculation::setup(const MmffParameters *parameters)\n{\n    const boost::shared_ptr<chemkit::Topology> &topology = this->topology();\n\n    size_t a = atom(0);\n    size_t b = atom(1);\n    size_t c = atom(2);\n\n    int typeA = boost::lexical_cast<int>(topology->type(a));\n    int typeB = boost::lexical_cast<int>(topology->type(b));\n    int typeC = boost::lexical_cast<int>(topology->type(c));\n    int bondTypeAB = topology->bondedInteractionType(a, b);\n    int bondTypeBC = topology->bondedInteractionType(b, c);\n    int angleType = topology->angleInteractionType(a, b, c);\n\n    int strechBendType =\n        parameters->calculateStrechBendType(bondTypeAB, bondTypeBC, angleType);\n\n    bool parametersSwapped = false;\n    const MmffStrechBendParameters *strechBendParameters =\n        parameters->strechBendParameters(strechBendType, typeA, typeB, typeC);\n    if(!strechBendParameters){\n        strechBendType =\n            parameters->calculateStrechBendType(bondTypeBC, bondTypeAB, angleType);\n        strechBendParameters =\n            parameters->strechBendParameters(strechBendType, typeC, typeB, typeA);\n\n        if(strechBendParameters){\n            parametersSwapped = true;\n        }\n        else{\n            strechBendParameters = parameters->defaultStrechBendParameters(typeA, typeB, typeC);\n\n            if(!strechBendParameters){\n                strechBendParameters = parameters->defaultStrechBendParameters(typeC, typeB, typeA);\n                parametersSwapped = true;\n            }\n        }\n    }\n\n    const MmffBondStrechParameters *bondStrechParameters_ab =\n        parameters->bondStrechParameters(bondTypeAB, typeA, typeB);\n    const MmffBondStrechParameters *bondStrechParameters_bc =\n        parameters->bondStrechParameters(bondTypeBC, typeB, typeC);\n    const MmffAngleBendParameters *angleBendParameters =\n        parameters->angleBendParameters(angleType, typeA, typeB, typeC);\n    if(strechBendParameters && bondStrechParameters_ab && bondStrechParameters_bc && angleBendParameters){\n        if(parametersSwapped){\n            setParameter(1, strechBendParameters->kba_ijk);\n            setParameter(0, strechBendParameters->kba_kji);\n        }\n        else{\n            setParameter(0, strechBendParameters->kba_ijk);\n            setParameter(1, strechBendParameters->kba_kji);\n        }\n\n        setParameter(2, bondStrechParameters_ab->r0);\n        setParameter(3, bondStrechParameters_bc->r0);\n        setParameter(4, angleBendParameters->theta0);\n        return true;\n    }\n\n    return false;\n}\n\nchemkit::Real MmffStrechBendCalculation::energy(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n    size_t c = atom(2);\n\n    chemkit::Real kba_ijk = parameter(0);\n    chemkit::Real kba_kji = parameter(1);\n    chemkit::Real r0_ab = parameter(2);\n    chemkit::Real r0_bc = parameter(3);\n    chemkit::Real t0 = parameter(4);\n\n    chemkit::Real r_ab = coordinates->distance(a, b);\n    chemkit::Real r_bc = coordinates->distance(b, c);\n    chemkit::Real dr_ab = r_ab - r0_ab;\n    chemkit::Real dr_bc = r_bc - r0_bc;\n    chemkit::Real t = coordinates->angle(a, b, c);\n    chemkit::Real dt = t - t0;\n\n    // equation 5\n    return 2.51210 * (kba_ijk * dr_ab + kba_kji * dr_bc) * dt;\n}\n\nstd::vector<chemkit::Vector3> MmffStrechBendCalculation::gradient(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n    size_t c = atom(2);\n\n    chemkit::Real kba_ijk = parameter(0);\n    chemkit::Real kba_kji = parameter(1);\n    chemkit::Real r0_ab = parameter(2);\n    chemkit::Real r0_bc = parameter(3);\n    chemkit::Real t0 = parameter(4);\n\n    chemkit::Real r_ab = coordinates->distance(a, b);\n    chemkit::Real r_bc = coordinates->distance(b, c);\n    chemkit::Real dr_ab = r_ab - r0_ab;\n    chemkit::Real dr_bc = r_bc - r0_bc;\n    chemkit::Real t = coordinates->angle(a, b, c);\n    chemkit::Real dt = t - t0;\n\n    std::vector<chemkit::Vector3> gradient(3);\n\n    boost::array<chemkit::Vector3, 2> distanceGradientAB = coordinates->distanceGradient(a, b);\n    boost::array<chemkit::Vector3, 2> distanceGradientBC = coordinates->distanceGradient(b, c);\n    boost::array<chemkit::Vector3, 3> angleGradientABC = coordinates->angleGradient(a, b, c);\n\n    gradient[0] = (distanceGradientAB[0] * kba_ijk * dt + angleGradientABC[0] * (kba_ijk * dr_ab + kba_kji * dr_bc)) * 2.51210;\n    gradient[1] = ((distanceGradientAB[1] * kba_ijk + distanceGradientBC[0] * kba_kji) * dt + angleGradientABC[1] * (kba_ijk * dr_ab + kba_kji * dr_bc)) * 2.51210;\n    gradient[2] = ((distanceGradientBC[1] * kba_kji) * dt + angleGradientABC[2] * (kba_ijk * dr_ab + kba_kji * dr_bc)) * 2.51210;\n\n    return gradient;\n}\n\n// === MmffOutOfPlaneBendingCalculation ==================================== //\nMmffOutOfPlaneBendingCalculation::MmffOutOfPlaneBendingCalculation(size_t a, size_t b, size_t c, size_t d)\n    : MmffCalculation(Inversion, 4, 1)\n{\n    setAtom(0, a);\n    setAtom(1, b);\n    setAtom(2, c);\n    setAtom(3, d);\n}\n\nbool MmffOutOfPlaneBendingCalculation::setup(const MmffParameters *parameters)\n{\n    const boost::shared_ptr<chemkit::Topology> &topology = this->topology();\n\n    size_t a = atom(0);\n    size_t b = atom(1);\n    size_t c = atom(2);\n    size_t d = atom(3);\n\n    int typeA = boost::lexical_cast<int>(topology->type(a));\n    int typeB = boost::lexical_cast<int>(topology->type(b));\n    int typeC = boost::lexical_cast<int>(topology->type(c));\n    int typeD = boost::lexical_cast<int>(topology->type(d));\n\n    const MmffOutOfPlaneBendingParameters *outOfPlaneBendingParameters =\n        parameters->outOfPlaneBendingParameters(typeA, typeB, typeC, typeD);\n    if(!outOfPlaneBendingParameters){\n        return false;\n    }\n\n    setParameter(0, outOfPlaneBendingParameters->koop);\n    return true;\n}\n\nchemkit::Real MmffOutOfPlaneBendingCalculation::energy(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n    size_t c = atom(2);\n    size_t d = atom(3);\n\n    chemkit::Real angle = coordinates->wilsonAngle(a, b, c, d);\n    chemkit::Real koop = parameter(0);\n\n    // equation 6\n    return 0.043844 * (koop / 2.0) * (angle*angle);\n}\n\nstd::vector<chemkit::Vector3> MmffOutOfPlaneBendingCalculation::gradient(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n    size_t c = atom(2);\n    size_t d = atom(3);\n\n    chemkit::Real angle = coordinates->wilsonAngle(a, b, c, d);\n    chemkit::Real koop = parameter(0);\n\n    // dE/dw\n    chemkit::Real de_dw = 0.043844 * koop * angle;\n\n    boost::array<chemkit::Vector3, 4> gradient = coordinates->wilsonAngleGradient(a, b, c, d);\n\n    gradient[0] *= de_dw;\n    gradient[1] *= de_dw;\n    gradient[2] *= de_dw;\n    gradient[3] *= de_dw;\n\n    return std::vector<chemkit::Vector3>(gradient.begin(), gradient.end());\n}\n\n// === MmffTorsionCalculation ============================================== //\nMmffTorsionCalculation::MmffTorsionCalculation(size_t a, size_t b, size_t c, size_t d)\n    : MmffCalculation(Torsion, 4, 3)\n{\n    setAtom(0, a);\n    setAtom(1, b);\n    setAtom(2, c);\n    setAtom(3, d);\n}\n\nbool MmffTorsionCalculation::setup(const MmffParameters *parameters)\n{\n    const boost::shared_ptr<chemkit::Topology> &topology = this->topology();\n\n    size_t a = atom(0);\n    size_t b = atom(1);\n    size_t c = atom(2);\n    size_t d = atom(3);\n\n    int typeA = boost::lexical_cast<int>(topology->type(a));\n    int typeB = boost::lexical_cast<int>(topology->type(b));\n    int typeC = boost::lexical_cast<int>(topology->type(c));\n    int typeD = boost::lexical_cast<int>(topology->type(d));\n    int torsionType = topology->torsionInteractionType(a, b, c, d);\n\n    const MmffTorsionParameters *torsionParameters =\n        parameters->torsionParameters(torsionType, typeA, typeB, typeC, typeD);\n    if(!torsionParameters){\n        return false;\n    }\n\n    setParameter(0, torsionParameters->V1);\n    setParameter(1, torsionParameters->V2);\n    setParameter(2, torsionParameters->V3);\n\n    return true;\n}\n\nchemkit::Real MmffTorsionCalculation::energy(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n    size_t c = atom(2);\n    size_t d = atom(3);\n\n    chemkit::Real angle = coordinates->torsionAngleRadians(a, b, c, d);\n    chemkit::Real V1 = parameter(0);\n    chemkit::Real V2 = parameter(1);\n    chemkit::Real V3 = parameter(2);\n\n    // equation 7\n    return 0.5 * (V1 * (1.0 + cos(angle)) + V2 * (1.0 - cos(2.0 * angle)) + V3 * (1.0 + cos(3.0 * angle)));\n}\n\nstd::vector<chemkit::Vector3> MmffTorsionCalculation::gradient(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n    size_t c = atom(2);\n    size_t d = atom(3);\n\n    chemkit::Real phi = coordinates->torsionAngleRadians(a, b, c, d);\n    chemkit::Real V1 = parameter(0);\n    chemkit::Real V2 = parameter(1);\n    chemkit::Real V3 = parameter(2);\n\n    // dE/dphi\n    chemkit::Real de_dphi = 0.5 * (-V1 * sin(phi) + 2 * V2 * sin(2 * phi) - 3 * V3 * sin(3 * phi));\n\n    boost::array<chemkit::Vector3, 4> gradient = coordinates->torsionAngleGradientRadians(a, b, c, d);\n\n    gradient[0] *= de_dphi;\n    gradient[1] *= de_dphi;\n    gradient[2] *= de_dphi;\n    gradient[3] *= de_dphi;\n\n    return std::vector<chemkit::Vector3>(gradient.begin(), gradient.end());\n}\n\n// === MmffVanDerWaalsCalculation ========================================== //\nMmffVanDerWaalsCalculation::MmffVanDerWaalsCalculation(size_t a, size_t b)\n    : MmffCalculation(VanDerWaals, 2, 2)\n{\n    setAtom(0, a);\n    setAtom(1, b);\n}\n\nbool MmffVanDerWaalsCalculation::setup(const MmffParameters *parameters)\n{\n    const boost::shared_ptr<chemkit::Topology> &topology = this->topology();\n\n    size_t a = atom(0);\n    size_t b = atom(1);\n\n    int typeA = boost::lexical_cast<int>(topology->type(a));\n    int typeB = boost::lexical_cast<int>(topology->type(b));\n\n    const MmffVanDerWaalsParameters *parametersA = parameters->vanDerWaalsParameters(typeA);\n    const MmffVanDerWaalsParameters *parametersB = parameters->vanDerWaalsParameters(typeB);\n    if(!parametersA || !parametersB){\n        return false;\n    }\n\n    chemkit::Real N_a = parametersA->N;\n    chemkit::Real N_b = parametersB->N;\n    chemkit::Real A_a = parametersA->A;\n    chemkit::Real A_b = parametersB->A;\n    chemkit::Real G_a = parametersA->G;\n    chemkit::Real G_b = parametersB->G;\n    chemkit::Real alpha_a = parametersA->alpha;\n    chemkit::Real alpha_b = parametersB->alpha;\n    char DA_a = parametersA->DA;\n    char DA_b = parametersB->DA;\n\n    // equation 9\n    chemkit::Real rs_aa = A_a * pow(alpha_a, (1.0/4.0));\n    chemkit::Real rs_bb = A_b * pow(alpha_b, (1.0/4.0));\n\n    // equation 11\n    chemkit::Real gamma = (rs_aa - rs_bb) / (rs_aa + rs_bb);\n\n    // equation 10\n    chemkit::Real rs;\n\n    if(DA_a == 'D' || (DA_b == 'D')){\n        rs = 0.5 * (rs_aa + rs_bb);\n    }\n    else{\n        rs = 0.5 * (rs_aa + rs_bb) * (1.0 + 0.2 * (1.0 - exp(-12.0 * gamma * gamma)));\n    }\n\n    // equation 12\n    chemkit::Real eps = ((181.16 * G_a * G_b * alpha_a * alpha_b) / (sqrt(alpha_a / N_a) + sqrt(alpha_b / N_b))) * pow(rs, -6.0);\n\n    if((DA_a == 'D' && DA_b == 'A') || (DA_a == 'A' && DA_b == 'D')){\n        rs *= 0.8;\n        eps *= 0.5;\n    }\n\n    setParameter(0, rs);\n    setParameter(1, eps);\n\n    return true;\n}\n\nchemkit::Real MmffVanDerWaalsCalculation::energy(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n\n    chemkit::Real rs = parameter(0);\n    chemkit::Real eps = parameter(1);\n    chemkit::Real r = coordinates->distance(a, b);\n\n    // equation 8\n    return eps * pow(((1.07 * rs) / (r + 0.07 * rs)), 7) * (((1.12 * pow(rs, 7)) / (pow(r, 7) + 0.12 * pow(rs, 7))) - 2);\n}\n\nstd::vector<chemkit::Vector3> MmffVanDerWaalsCalculation::gradient(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n\n    chemkit::Real rs = parameter(0);\n    chemkit::Real eps = parameter(1);\n    chemkit::Real r = coordinates->distance(a, b);\n\n    // dE/dr\n    chemkit::Real de_dr = 7 * eps * pow(1.07 * rs / (r + 0.07 * rs), 6) *\n                           ((-1.07 * rs / pow(r + 0.07 * rs, 2)) * (1.12 * pow(rs, 7) / (pow(r, 7) + 0.12 * pow(rs, 7)) - 2) +\n                           (-1.12 * pow(rs, 7) * pow(r, 6) / pow(pow(r, 7) + 0.12 * pow(rs, 7), 2)) * (1.07 * rs / (r + 0.07 * rs)));\n\n    boost::array<chemkit::Vector3, 2> gradient = coordinates->distanceGradient(a, b);\n\n    gradient[0] *= de_dr;\n    gradient[1] *= de_dr;\n\n    return std::vector<chemkit::Vector3>(gradient.begin(), gradient.end());\n}\n\n// === MmffElectrostaticCalculation ======================================== //\nMmffElectrostaticCalculation::MmffElectrostaticCalculation(size_t a, size_t b)\n    : MmffCalculation(Electrostatic, 2, 3)\n{\n    setAtom(0, a);\n    setAtom(1, b);\n}\n\nbool MmffElectrostaticCalculation::setup(const MmffParameters *parameters)\n{\n    CHEMKIT_UNUSED(parameters);\n\n    const boost::shared_ptr<chemkit::Topology> &topology = this->topology();\n\n    size_t a = atom(0);\n    size_t b = atom(1);\n\n    chemkit::Real oneFourScaling;\n\n    if(topology->isOneFour(a, b)){\n        oneFourScaling = 0.75;\n    }\n    else{\n        oneFourScaling = 1.0;\n    }\n\n    setParameter(0, topology->charge(a));\n    setParameter(1, topology->charge(b));\n    setParameter(2, oneFourScaling);\n\n    return true;\n}\n\nchemkit::Real MmffElectrostaticCalculation::energy(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n\n    chemkit::Real qa = parameter(0);\n    chemkit::Real qb = parameter(1);\n    chemkit::Real oneFourScaling = parameter(2);\n\n    chemkit::Real r = coordinates->distance(a, b);\n    chemkit::Real e = 1.0; // dielectric constant\n    chemkit::Real d = 0.05; // electrostatic buffering constant\n\n    // equation 13\n    return ((332.0716 * qa * qb) / (e * (r + d))) * oneFourScaling;\n}\n\nstd::vector<chemkit::Vector3> MmffElectrostaticCalculation::gradient(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n\n    chemkit::Real qa = parameter(0);\n    chemkit::Real qb = parameter(1);\n    chemkit::Real oneFourScaling = parameter(2);\n\n    chemkit::Real r = coordinates->distance(a, b);\n    chemkit::Real e = 1.0; // dielectric constant\n    chemkit::Real d = 0.05; // electrostatic buffering constant\n\n    chemkit::Real de_dr = 332.0716 * qa * qb * oneFourScaling * (-1.0 / (e * pow(r + d, 2)));\n\n    boost::array<chemkit::Vector3, 2> gradient = coordinates->distanceGradient(a, b);\n\n    gradient[0] *= de_dr;\n    gradient[1] *= de_dr;\n\n    return std::vector<chemkit::Vector3>(gradient.begin(), gradient.end());\n}\n", "meta": {"hexsha": "c4c84f34deca8d7c8cbd21435543b91624ffde39", "size": 21824, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/plugins/mmff/mmffcalculation.cpp", "max_stars_repo_name": "quizzmaster/chemkit", "max_stars_repo_head_hexsha": "803e4688b514008c605cb5c7790f7b36e67b68fc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2015-01-24T23:59:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T13:48:01.000Z", "max_issues_repo_path": "src/plugins/mmff/mmffcalculation.cpp", "max_issues_repo_name": "soplwang/chemkit", "max_issues_repo_head_hexsha": "d62b7912f2d724a05fa8be757f383776fdd5bbcb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-12-28T20:29:16.000Z", "max_issues_repo_issues_event_max_datetime": "2016-01-26T06:48:19.000Z", "max_forks_repo_path": "src/plugins/mmff/mmffcalculation.cpp", "max_forks_repo_name": "soplwang/chemkit", "max_forks_repo_head_hexsha": "d62b7912f2d724a05fa8be757f383776fdd5bbcb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2015-01-23T14:50:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-10T15:43:50.000Z", "avg_line_length": 33.6271186441, "max_line_length": 163, "alphanum_fraction": 0.6430076979, "num_tokens": 6583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283033, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2669302563684573}}
{"text": "#include <cstdint>\n#include <functional>\n#include <limits>\n#include <queue>\n#include <stdexcept>\n#include <unordered_map>\n#include <vector>\n#include <Eigen/Geometry>\n#include <arc_utilities/arc_helpers.hpp>\n\n#ifndef DIJKSTRAS_HPP\n#define DIJKSTRAS_HPP\n\nnamespace arc_dijkstras\n{\n    class GraphEdge\n    {\n        protected:\n\n            int64_t from_index_;\n            int64_t to_index_;\n            double weight_;\n\n        public:\n\n            static uint64_t Serialize(const GraphEdge& edge, std::vector<uint8_t>& buffer)\n            {\n                return edge.SerializeSelf(buffer);\n            }\n\n            static std::pair<GraphEdge, uint64_t> Deserialize(const std::vector<uint8_t>& buffer, const uint64_t current)\n            {\n                GraphEdge temp_edge;\n                const uint64_t bytes_read = temp_edge.DeserializeSelf(buffer, current);\n                return std::make_pair(temp_edge, bytes_read);\n            }\n\n            GraphEdge(const int64_t from_index, const int64_t to_index, const double weight)\n                : from_index_(from_index), to_index_(to_index), weight_(weight)\n            {}\n\n            GraphEdge()\n                : from_index_(-1), to_index_(-1), weight_(0.0)\n            {}\n\n            uint64_t SerializeSelf(std::vector<uint8_t>& buffer) const\n            {\n                const uint64_t start_buffer_size = buffer.size();\n                arc_helpers::SerializeFixedSizePOD<int64_t>(from_index_, buffer);\n                arc_helpers::SerializeFixedSizePOD<int64_t>(to_index_, buffer);\n                arc_helpers::SerializeFixedSizePOD<double>(weight_, buffer);\n                // Figure out how many bytes were written\n                const uint64_t end_buffer_size = buffer.size();\n                const uint64_t bytes_written = end_buffer_size - start_buffer_size;\n                return bytes_written;\n            }\n\n            uint64_t DeserializeSelf(const std::vector<uint8_t>& buffer, const uint64_t current)\n            {\n                uint64_t current_position = current;\n                const std::pair<int64_t, uint64_t> deserialized_from_index = arc_helpers::DeserializeFixedSizePOD<int64_t>(buffer, current_position);\n                from_index_ = deserialized_from_index.first;\n                current_position += deserialized_from_index.second;\n                const std::pair<int64_t, uint64_t> deserialized_to_index = arc_helpers::DeserializeFixedSizePOD<int64_t>(buffer, current_position);\n                to_index_ = deserialized_to_index.first;\n                current_position += deserialized_to_index.second;\n                const std::pair<double, uint64_t> deserialized_weight = arc_helpers::DeserializeFixedSizePOD<double>(buffer, current_position);\n                weight_ = deserialized_weight.first;\n                current_position += deserialized_weight.second;\n                // Figure out how many bytes were read\n                const uint64_t bytes_read = current_position - current;\n                return bytes_read;\n            }\n\n            bool operator==(const GraphEdge& other) const\n            {\n                return (from_index_ == other.GetFromIndex() && to_index_ == other.GetToIndex() && weight_ == other.GetWeight());\n            }\n\n            std::string Print() const\n            {\n                return std::string(\"(\" + std::to_string(from_index_) + \"->\" + std::to_string(to_index_) + \") : \" + std::to_string(weight_));\n            }\n\n            int64_t GetFromIndex() const\n            {\n                return from_index_;\n            }\n\n            int64_t GetToIndex() const\n            {\n                return to_index_;\n            }\n\n            double GetWeight() const\n            {\n                return weight_;\n            }\n\n            void SetFromIndex(const int64_t new_from_index)\n            {\n                from_index_ = new_from_index;\n            }\n\n            void SetToIndex(const int64_t new_to_index)\n            {\n                to_index_ = new_to_index;\n            }\n\n            void SetWeight(const double new_weight)\n            {\n                weight_ = new_weight;\n            }\n    };\n\n    inline std::ostream& operator<< (std::ostream& stream, const GraphEdge& edge)\n    {\n        stream << edge.Print();\n        return stream;\n    }\n\n    template<typename NodeValueType, typename Allocator=std::allocator<NodeValueType>>\n    class GraphNode\n    {\n        protected:\n\n            NodeValueType value_;\n            double distance_;\n            std::vector<GraphEdge> in_edges_;\n            std::vector<GraphEdge> out_edges_;\n\n        public:\n\n            EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n            static uint64_t Serialize(const GraphNode<NodeValueType, Allocator>& node, std::vector<uint8_t>& buffer, const std::function<uint64_t(const NodeValueType&, std::vector<uint8_t>&)>& value_serializer)\n            {\n                return node.SerializeSelf(buffer, value_serializer);\n            }\n\n            static std::pair<GraphNode<NodeValueType, Allocator>, uint64_t> Deserialize(const std::vector<uint8_t>& buffer, const uint64_t current, const std::function<std::pair<NodeValueType, uint64_t>(const std::vector<uint8_t>&, const uint64_t)>& value_deserializer)\n            {\n                GraphNode<NodeValueType, Allocator> temp_node;\n                const uint64_t bytes_read = temp_node.DeserializeSelf(buffer, current, value_deserializer);\n                return std::make_pair(temp_node, bytes_read);\n            }\n\n            GraphNode(const NodeValueType& value, const double distance, const std::vector<GraphEdge>& new_in_edges, const std::vector<GraphEdge>& new_out_edges)\n                : value_(value), distance_(distance), in_edges_(new_in_edges), out_edges_(new_out_edges)\n            {}\n\n            explicit GraphNode(const NodeValueType& value)\n                : value_(value), distance_(std::numeric_limits<double>::infinity())\n            {}\n\n            GraphNode()\n                : distance_(std::numeric_limits<double>::infinity())\n            {}\n\n            uint64_t SerializeSelf(std::vector<uint8_t>& buffer, const std::function<uint64_t(const NodeValueType&, std::vector<uint8_t>&)>& value_serializer) const\n            {\n                const uint64_t start_buffer_size = buffer.size();\n                // Serialize the value\n                value_serializer(value_, buffer);\n                // Serialize the distance\n                arc_helpers::SerializeFixedSizePOD<double>(distance_, buffer);\n                // Serialize the in edges\n                arc_helpers::SerializeVector<GraphEdge>(in_edges_, buffer, GraphEdge::Serialize);\n                // Serialize the in edges\n                arc_helpers::SerializeVector<GraphEdge>(out_edges_, buffer, GraphEdge::Serialize);\n                // Figure out how many bytes were written\n                const uint64_t end_buffer_size = buffer.size();\n                const uint64_t bytes_written = end_buffer_size - start_buffer_size;\n                return bytes_written;\n            }\n\n            uint64_t DeserializeSelf(const std::vector<uint8_t>& buffer, const uint64_t current, const std::function<std::pair<NodeValueType, uint64_t>(const std::vector<uint8_t>&, const uint64_t)>& value_deserializer)\n            {\n                uint64_t current_position = current;\n                // Deserialize the value\n                const std::pair<NodeValueType, uint64_t> value_deserialized = value_deserializer(buffer, current_position);\n                value_ = value_deserialized.first;\n                current_position += value_deserialized.second;\n                // Deserialize the distace\n                const std::pair<double, uint64_t> distance_deserialized = arc_helpers::DeserializeFixedSizePOD<double>(buffer, current_position);\n                distance_ = distance_deserialized.first;\n                current_position += distance_deserialized.second;\n                // Deserialize the in edges\n                const std::pair<std::vector<GraphEdge>, uint64_t> in_edges_deserialized = arc_helpers::DeserializeVector<GraphEdge>(buffer, current_position, GraphEdge::Deserialize);\n                in_edges_ = in_edges_deserialized.first;\n                current_position += in_edges_deserialized.second;\n                // Deserialize the out edges\n                const std::pair<std::vector<GraphEdge>, uint64_t> out_edges_deserialized = arc_helpers::DeserializeVector<GraphEdge>(buffer, current_position, GraphEdge::Deserialize);\n                out_edges_ = out_edges_deserialized.first;\n                current_position += out_edges_deserialized.second;\n                // Figure out how many bytes were read\n                const uint64_t bytes_read = current_position - current;\n                return bytes_read;\n            }\n\n            std::string Print() const\n            {\n                std::ostringstream strm;\n                strm << \"Node : \" << distance_ << \" In Edges : \";\n                if (in_edges_.size() > 0)\n                {\n                    strm << in_edges_[0].Print();\n                    for (size_t idx = 1; idx < in_edges_.size(); idx++)\n                    {\n                        strm << \", \" << in_edges_[idx].Print();\n                    }\n                }\n                strm << \" Out Edges : \";\n                if (out_edges_.size() > 0)\n                {\n                    strm << out_edges_[0].Print();\n                    for (size_t idx = 1; idx < out_edges_.size(); idx++)\n                    {\n                        strm << \", \" << out_edges_[idx].Print();\n                    }\n                }\n                return strm.str();\n            }\n\n            const NodeValueType& GetValueImmutable() const\n            {\n                return value_;\n            }\n\n            NodeValueType& GetValueMutable()\n            {\n                return value_;\n            }\n\n            void AddInEdge(const GraphEdge& new_in_edge)\n            {\n                in_edges_.push_back(new_in_edge);\n            }\n\n            void AddOutEdge(const GraphEdge& new_out_edge)\n            {\n                out_edges_.push_back(new_out_edge);\n            }\n\n            void AddEdgePair(const GraphEdge& new_in_edge, const GraphEdge& new_out_edge)\n            {\n                AddInEdge(new_in_edge);\n                AddOutEdge(new_out_edge);\n            }\n\n            double GetDistance() const\n            {\n                return distance_;\n            }\n\n            void SetDistance(const double distance)\n            {\n                distance_ = distance;\n            }\n\n            const std::vector<GraphEdge>& GetInEdgesImmutable() const\n            {\n                return in_edges_;\n            }\n\n            std::vector<GraphEdge>& GetInEdgesMutable()\n            {\n                return in_edges_;\n            }\n\n            const std::vector<GraphEdge>& GetOutEdgesImmutable() const\n            {\n                return out_edges_;\n            }\n\n            std::vector<GraphEdge>& GetOutEdgesMutable()\n            {\n                return out_edges_;\n            }\n\n            void SetInEdges(const std::vector<GraphEdge>& new_in_edges)\n            {\n                in_edges_ = new_in_edges;\n            }\n\n            void SetOutEdges(const std::vector<GraphEdge>& new_out_edges)\n            {\n                out_edges_ = new_out_edges;\n            }\n    };\n\n    template<typename NodeValueType, typename Allocator=std::allocator<NodeValueType>>\n    class Graph\n    {\n        protected:\n\n            std::vector<GraphNode<NodeValueType, Allocator>> nodes_;\n\n        public:\n\n            static uint64_t Serialize(const Graph<NodeValueType, Allocator>& graph, std::vector<uint8_t>& buffer, const std::function<uint64_t(const NodeValueType&, std::vector<uint8_t>&)>& value_serializer)\n            {\n                return graph.SerializeSelf(buffer, value_serializer);\n            }\n\n            static std::pair<Graph<NodeValueType, Allocator>, uint64_t> Deserialize(const std::vector<uint8_t>& buffer, const uint64_t current, const std::function<std::pair<NodeValueType, uint64_t>(const std::vector<uint8_t>&, const uint64_t)>& value_deserializer)\n            {\n                Graph<NodeValueType, Allocator> temp_graph;\n                const uint64_t bytes_read = temp_graph.DeserializeSelf(buffer, current, value_deserializer);\n                return std::make_pair(temp_graph, bytes_read);\n            }\n\n            Graph(const std::vector<GraphNode<NodeValueType, Allocator>>& nodes)\n            {\n                if (CheckGraphLinkage(nodes))\n                {\n                    nodes_ = nodes;\n                }\n                else\n                {\n                    throw std::invalid_argument(\"Invalid graph linkage\");\n                }\n            }\n\n            Graph(const size_t expected_size)\n            {\n                nodes_.reserve(expected_size);\n            }\n\n            Graph()\n            {}\n\n            uint64_t SerializeSelf(std::vector<uint8_t>& buffer, const std::function<uint64_t(const NodeValueType&, std::vector<uint8_t>&)>& value_serializer) const\n            {\n                const uint64_t start_buffer_size = buffer.size();\n                std::function<uint64_t(const GraphNode<NodeValueType, Allocator>&, std::vector<uint8_t>&)> graph_state_serializer = std::bind(GraphNode<NodeValueType, Allocator>::Serialize, std::placeholders::_1, std::placeholders::_2, value_serializer);\n                arc_helpers::SerializeVector<GraphNode<NodeValueType, Allocator>>(nodes_, buffer, graph_state_serializer);\n                // Figure out how many bytes were written\n                const uint64_t end_buffer_size = buffer.size();\n                const uint64_t bytes_written = end_buffer_size - start_buffer_size;\n                return bytes_written;\n            }\n\n            uint64_t DeserializeSelf(const std::vector<uint8_t>& buffer, const uint64_t current, const std::function<std::pair<NodeValueType, uint64_t>(const std::vector<uint8_t>&, const uint64_t)>& value_deserializer)\n            {\n                const std::function<std::pair<GraphNode<NodeValueType, Allocator>, uint64_t>(const std::vector<uint8_t>&, const uint64_t)> graph_state_deserializer = std::bind(GraphNode<NodeValueType, Allocator>::Deserialize, std::placeholders::_1, std::placeholders::_2, value_deserializer);\n                const std::pair<std::vector<GraphNode<NodeValueType, Allocator>>, uint64_t> deserialized_nodes = arc_helpers::DeserializeVector<GraphNode<NodeValueType, Allocator>>(buffer, current, graph_state_deserializer);\n                nodes_ = deserialized_nodes.first;\n                return deserialized_nodes.second;\n            }\n\n            std::string Print() const\n            {\n                std::ostringstream strm;\n                strm << \"Graph - Nodes : \";\n                if (nodes_.size() > 0)\n                {\n                    strm << nodes_[0].Print();\n                    for (size_t idx = 1; idx < nodes_.size(); idx++)\n                    {\n                        strm << \"\\n\" << nodes_[idx].Print();\n                    }\n                }\n                return strm.str();\n            }\n\n            void ShrinkToFit()\n            {\n                nodes_.shrink_to_fit();\n            }\n\n            bool IndexInRange(const int64_t index) const\n            {\n                if (index >= 0)\n                {\n                    if (index < (int64_t)(nodes_.size()))\n                    {\n                        return true;\n                    }\n                    else\n                    {\n                        return false;\n                    }\n                }\n                else\n                {\n                    return false;\n                }\n            }\n\n            bool CheckGraphLinkage() const\n            {\n                return CheckGraphLinkage(GetNodesImmutable());\n            }\n\n            static bool CheckGraphLinkage(const Graph<NodeValueType, Allocator>& graph)\n            {\n                return CheckGraphLinkage(graph.GetNodesImmutable());\n            }\n\n            static bool CheckGraphLinkage(const std::vector<GraphNode<NodeValueType, Allocator>>& nodes)\n            {\n                // Go through every node and make sure the edges are valid\n                for (size_t idx = 0; idx < nodes.size(); idx++)\n                {\n                    const GraphNode<NodeValueType, Allocator>& current_node = nodes[idx];\n                    // Check the in edges first\n                    const std::vector<GraphEdge>& in_edges = current_node.GetInEdgesImmutable();\n                    for (size_t in_edge_idx = 0; in_edge_idx < in_edges.size(); in_edge_idx++)\n                    {\n                        const GraphEdge& current_edge = in_edges[in_edge_idx];\n                        // Check from index to make sure it's in bounds\n                        const int64_t from_index = current_edge.GetFromIndex();\n                        if (from_index < 0 || from_index >= (int64_t)nodes.size())\n                        {\n                            return false;\n                        }\n                        // Check to index to make sure it matches our own index\n                        const int64_t to_index = current_edge.GetToIndex();\n                        if (to_index != (int64_t)idx)\n                        {\n                            return false;\n                        }\n                        // Check edge validity (edges to ourself are not allowed)\n                        if (from_index == to_index)\n                        {\n                            return false;\n                        }\n                        // Check to make sure that the from index node is linked to us\n                        const GraphNode<NodeValueType, Allocator>& from_node = nodes[(size_t)from_index];\n                        const std::vector<GraphEdge>& from_node_out_edges = from_node.GetOutEdgesImmutable();\n                        bool from_node_connection_valid = false;\n                        // Make sure at least one out edge of the from index node corresponds to the current node\n                        for (size_t from_node_out_edge_idx = 0; from_node_out_edge_idx < from_node_out_edges.size(); from_node_out_edge_idx++)\n                        {\n                            const GraphEdge& current_from_node_out_edge = from_node_out_edges[from_node_out_edge_idx];\n                            if (current_from_node_out_edge.GetToIndex() == (int64_t)idx)\n                            {\n                                from_node_connection_valid = true;\n                            }\n                        }\n                        if (from_node_connection_valid == false)\n                        {\n                            return false;\n                        }\n                    }\n                    // Check the out edges second\n                    const std::vector<GraphEdge>& out_edges = current_node.GetOutEdgesImmutable();\n                    for (size_t out_edge_idx = 0; out_edge_idx < out_edges.size(); out_edge_idx++)\n                    {\n                        const GraphEdge& current_edge = out_edges[out_edge_idx];\n                        // Check from index to make sure it matches our own index\n                        const int64_t from_index = current_edge.GetFromIndex();\n                        if (from_index != (int64_t)idx)\n                        {\n                            return false;\n                        }\n                        // Check to index to make sure it's in bounds\n                        const int64_t to_index = current_edge.GetToIndex();\n                        if (to_index < 0 || to_index >= (int64_t)nodes.size())\n                        {\n                            return false;\n                        }\n                        // Check edge validity (edges to ourself are not allowed)\n                        if (from_index == to_index)\n                        {\n                            return false;\n                        }\n                        // Check to make sure that the to index node is linked to us\n                        const GraphNode<NodeValueType, Allocator>& to_node = nodes[(size_t)to_index];\n                        const std::vector<GraphEdge>& to_node_in_edges = to_node.GetInEdgesImmutable();\n                        bool to_node_connection_valid = false;\n                        // Make sure at least one in edge of the to index node corresponds to the current node\n                        for (size_t to_node_in_edge_idx = 0; to_node_in_edge_idx < to_node_in_edges.size(); to_node_in_edge_idx++)\n                        {\n                            const GraphEdge& current_to_node_in_edge = to_node_in_edges[to_node_in_edge_idx];\n                            if (current_to_node_in_edge.GetFromIndex() == (int64_t)idx)\n                            {\n                                to_node_connection_valid = true;\n                            }\n                        }\n                        if (to_node_connection_valid == false)\n                        {\n                            return false;\n                        }\n                    }\n                }\n                return true;\n            }\n\n            const std::vector<GraphNode<NodeValueType, Allocator>>& GetNodesImmutable() const\n            {\n                return nodes_;\n            }\n\n            std::vector<GraphNode<NodeValueType, Allocator>>& GetNodesMutable()\n            {\n                return nodes_;\n            }\n\n            const GraphNode<NodeValueType, Allocator>& GetNodeImmutable(const int64_t index) const\n            {\n                return nodes_.at((size_t)index);\n            }\n\n            GraphNode<NodeValueType, Allocator>& GetNodeMutable(const int64_t index)\n            {\n                return nodes_.at((size_t)index);\n            }\n\n            int64_t AddNode(const GraphNode<NodeValueType, Allocator>& new_node)\n            {\n                nodes_.push_back(new_node);\n                return (int64_t)(nodes_.size() - 1);\n            }\n\n            int64_t AddNode(const NodeValueType& new_value)\n            {\n                nodes_.push_back(GraphNode<NodeValueType, Allocator>(new_value));\n                return (int64_t)(nodes_.size() - 1);\n            }\n\n            void AddEdgeBetweenNodes(const int64_t from_index, const int64_t to_index, const double edge_weight)\n            {\n                // We retrieve the nodes first, since retrieval performs bounds checks first\n                GraphNode<NodeValueType, Allocator>& from_node = GetNodeMutable(from_index);\n                GraphNode<NodeValueType, Allocator>& to_node = GetNodeMutable(to_index);\n                if (from_index == to_index)\n                {\n                    throw std::invalid_argument(\"Invalid circular edge from==to not allowed\");\n                }\n                const GraphEdge new_edge(from_index, to_index, edge_weight);\n                from_node.AddOutEdge(new_edge);\n                to_node.AddInEdge(new_edge);\n            }\n\n            void AddEdgesBetweenNodes(const int64_t first_index, const int64_t second_index, const double edge_weight)\n            {\n                // We retrieve the nodes first, since retrieval performs bounds checks first\n                GraphNode<NodeValueType, Allocator>& first_node = GetNodeMutable(first_index);\n                GraphNode<NodeValueType, Allocator>& second_node = GetNodeMutable(second_index);\n                if (first_index == second_index)\n                {\n                    throw std::invalid_argument(\"Invalid circular edge first==second not allowed\");\n                }\n                const GraphEdge first_edge(first_index, second_index, edge_weight);\n                first_node.AddOutEdge(first_edge);\n                second_node.AddInEdge(first_edge);\n                const GraphEdge second_edge(second_index, first_index, edge_weight);\n                second_node.AddOutEdge(second_edge);\n                first_node.AddInEdge(second_edge);\n            }\n    };\n\n    template<typename NodeValueType, typename Allocator=std::allocator<NodeValueType>>\n    class SimpleDijkstrasAlgorithm\n    {\n        protected:\n\n            class CompareIndexFn\n            {\n                public:\n\n                    constexpr bool operator()(const std::pair<int64_t, double>& lhs, const std::pair<int64_t, double>& rhs) const\n                    {\n                        return lhs.second > rhs.second;\n                    }\n            };\n\n            SimpleDijkstrasAlgorithm() {}\n\n        public:\n\n            typedef std::pair<Graph<NodeValueType, Allocator>, std::pair<std::vector<int64_t>, std::vector<double>>> DijkstrasResult;\n\n            static DijkstrasResult PerformDijkstrasAlgorithm(const Graph<NodeValueType, Allocator>& graph, const int64_t start_index)\n            {\n                if ((start_index < 0) && (start_index >= (int64_t)graph.GetNodesImmutable().size()))\n                {\n                    throw std::invalid_argument(\"Start index out of range\");\n                }\n                Graph<NodeValueType, Allocator> working_copy = graph;\n                // Setup\n                std::vector<int64_t> previous_index_map(working_copy.GetNodesImmutable().size(), -1);\n                std::vector<double> distances(working_copy.GetNodesImmutable().size(), std::numeric_limits<double>::infinity());\n                std::priority_queue<std::pair<int64_t, double>, std::vector<std::pair<int64_t, double>>, CompareIndexFn> queue;\n                std::unordered_map<int64_t, uint32_t> explored(graph.GetNodesImmutable().size());\n                for (size_t idx = 0; idx < working_copy.GetNodesImmutable().size(); idx++)\n                {\n                    working_copy.GetNodeMutable((int64_t)idx).SetDistance(std::numeric_limits<double>::infinity());\n                    queue.push(std::make_pair((int64_t)idx, std::numeric_limits<double>::infinity()));\n                }\n                working_copy.GetNodeMutable(start_index).SetDistance(0.0);\n                previous_index_map[(size_t)start_index] = start_index;\n                distances[(size_t)start_index] = 0.0;\n                queue.push(std::make_pair(start_index, 0.0));\n                while (queue.size() > 0)\n                {\n                    const std::pair<int64_t, double> top_node = queue.top();\n                    const int64_t& top_node_index = top_node.first;\n                    const double& top_node_distance = top_node.second;\n                    queue.pop();\n                    if (explored[top_node.first] > 0)\n                    {\n                        // We've already been here\n                        continue;\n                    }\n                    else\n                    {\n                        // Note that we've been here\n                        explored[top_node.first] = 1;\n                        // Get our neighbors\n                        const std::vector<GraphEdge>& neighbor_edges = working_copy.GetNodeImmutable(top_node_index).GetInEdgesImmutable();\n                        // Go through our neighbors\n                        for (size_t neighbor_idx = 0; neighbor_idx < neighbor_edges.size(); neighbor_idx++)\n                        {\n                            const int64_t neighbor_index = neighbor_edges[neighbor_idx].GetFromIndex();\n                            const double neighbor_edge_weight = neighbor_edges[neighbor_idx].GetWeight();\n                            const double new_neighbor_distance = top_node_distance + neighbor_edge_weight;\n                            // Check against the neighbor\n                            const double stored_neighbor_distance = working_copy.GetNodeImmutable(neighbor_index).GetDistance();\n                            if (new_neighbor_distance < stored_neighbor_distance)\n                            {\n                                // We've found a better way to get to this node\n                                // Check if it's already been explored\n                                if (explored[neighbor_index] > 0)\n                                {\n                                    // If it's already been explored, we just update it in place\n                                    working_copy.GetNodeMutable(neighbor_index).SetDistance(new_neighbor_distance);\n                                }\n                                else\n                                {\n                                    // If it hasn't been explored, we need to update it and add it to the queue\n                                    working_copy.GetNodeMutable(neighbor_index).SetDistance(new_neighbor_distance);\n                                    queue.push(std::make_pair(neighbor_index, new_neighbor_distance));\n                                }\n                                // Update that we're the best previous node\n                                previous_index_map[(size_t)neighbor_index] = top_node_index;\n                                distances[(size_t)neighbor_index] = new_neighbor_distance;\n                            }\n                            else\n                            {\n                                // Do nothing\n                                continue;\n                            }\n                        }\n                    }\n                }\n                return std::make_pair(working_copy, std::make_pair(previous_index_map, distances));\n            }\n\n            static uint64_t SerializeDijstrasResult(const DijkstrasResult& result, std::vector<uint8_t>& buffer, const std::function<uint64_t(const NodeValueType&, std::vector<uint8_t>&)>& value_serializer)\n            {\n                const uint64_t start_buffer_size = buffer.size();\n                // Serialize the graph\n                result.first.SerializeSelf(buffer, value_serializer);\n                // Serialize the previous index\n                SerializeVector(result.second.first, std::bind(arc_helpers::SerializeFixedSizePOD<uint64_t>, std::placeholders::_1, std::placeholders::_2));\n                // Serialze the distances\n                SerializeVector(result.second.second, std::bind(arc_helpers::SerializeFixedSizePOD<uint64_t>, std::placeholders::_1, std::placeholders::_2));\n                // Figure out how many bytes were written\n                const uint64_t end_buffer_size = buffer.size();\n                const uint64_t bytes_written = end_buffer_size - start_buffer_size;\n                return bytes_written;\n            }\n\n            static std::pair<DijkstrasResult, uint64_t> DijstrasResult(const std::vector<uint8_t>& buffer, const uint64_t current, const std::function<std::pair<NodeValueType, uint64_t>(const std::vector<uint8_t>&, const uint64_t)>& value_deserializer)\n            {\n                uint64_t current_position = current;\n                // Deserialize the graph itself\n                std::pair<DijkstrasResult, uint64_t> deserialized;\n                const std::pair<Graph<NodeValueType, Allocator>, uint64_t> graph_deserialized = Graph<NodeValueType, Allocator>::Deserialize(buffer, current_position, value_deserializer);\n                deserialized.first.first = graph_deserialized.first;\n                current_position += graph_deserialized.second;\n                // Deserialize the previous index\n                const std::pair<std::vector<int64_t>, uint64_t> prev_index_deserialized = arc_helpers::DeserializeVector<int64_t>(buffer, current_position, std::bind(arc_helpers::DeserializeFixedSizePOD<uint64_t>, std::placeholders::_1, std::placeholders::_2));\n                deserialized.first.second.first = prev_index_deserialized.first;\n                current_position += prev_index_deserialized.second;\n                // Deserialize the distances\n                const std::pair<std::vector<double>, uint64_t> distance_deserialized = arc_helpers::DeserializeVector<double>(buffer, current_position, std::bind(arc_helpers::DeserializeFixedSizePOD<double>, std::placeholders::_1, std::placeholders::_2));\n                deserialized.first.second.second = distance_deserialized.first;\n                current_position += distance_deserialized.second;\n                // Figure out how many bytes were read\n                deserialized.second = current_position - current;\n                return deserialized;\n            }\n    };\n\n    template<typename NodeValueType, typename Allocator=std::allocator<NodeValueType>>\n    class SimpleGraphAstar\n    {\n    protected:\n\n        SimpleGraphAstar() {}\n\n    public:\n\n        static arc_helpers::AstarResult PerformLazyAstar(const Graph<NodeValueType, Allocator>& graph, const int64_t start_index, const int64_t goal_index, const std::function<bool(const Graph<NodeValueType, Allocator>&, const GraphEdge&)>& edge_validity_check_fn, const std::function<double(const Graph<NodeValueType, Allocator>&, const GraphEdge&)>& distance_fn, const std::function<double(const NodeValueType&, const NodeValueType&)>& heuristic_fn, const bool limit_pqueue_duplicates)\n        {\n            // Enforced sanity checks\n            if ((start_index < 0) && (start_index >= (int64_t)graph.GetNodesImmutable().size()))\n            {\n                throw std::invalid_argument(\"Start index out of range\");\n            }\n            if ((goal_index < 0) && (goal_index >= (int64_t)graph.GetNodesImmutable().size()))\n            {\n                throw std::invalid_argument(\"Goal index out of range\");\n            }\n            if (start_index == goal_index)\n            {\n                throw std::invalid_argument(\"Start and goal indices must be different\");\n            }\n            // Make helper function\n            const auto heuristic_function = [&] (const int64_t node_index) { return heuristic_fn(graph.GetNodeImmutable(node_index).GetValueImmutable(), graph.GetNodeImmutable(goal_index).GetValueImmutable()); };\n            // Setup\n            std::priority_queue<arc_helpers::AstarPQueueElement, std::vector<arc_helpers::AstarPQueueElement>, arc_helpers::CompareAstarPQueueElementFn> queue;\n            // Optional map to reduce the number of duplicate items added to the pqueue\n            // Key is the node index in the provided graph\n            // Value is cost-to-come\n            std::unordered_map<int64_t, double> queue_members_map;\n            // Key is the node index in the provided graph\n            // Value is a pair<backpointer, cost-to-come>\n            // backpointer is the parent index in the provided graph\n            std::unordered_map<int64_t, std::pair<int64_t, double>> explored;\n            // Initialize\n            queue.push(arc_helpers::AstarPQueueElement(start_index, -1, 0.0, heuristic_function(start_index)));\n            if (limit_pqueue_duplicates)\n            {\n                queue_members_map[start_index] = 0.0;\n            }\n            // Search\n            while (queue.size() > 0)\n            {\n                // Get the top of the priority queue\n                const arc_helpers::AstarPQueueElement top_node = queue.top();\n                queue.pop();\n                // Remove from queue map if necessary\n                if (limit_pqueue_duplicates)\n                {\n                    queue_members_map.erase(top_node.NodeID());\n                }\n                // Check if the node has already been discovered\n                const auto node_explored_find_itr = explored.find(top_node.NodeID());\n                // We have not been here before, or it is cheaper now\n                const bool node_in_explored = (node_explored_find_itr != explored.end());\n                const bool explored_node_is_better = (node_in_explored) ? (top_node.CostToCome() >= node_explored_find_itr->second.second) : false;\n                if (!explored_node_is_better)\n                {\n                    // Add to the explored list\n                    explored[top_node.NodeID()] = std::make_pair(top_node.Backpointer(), top_node.CostToCome());\n                    // Check if we have reached the goal\n                    if (top_node.NodeID() == goal_index)\n                    {\n                        break;\n                    }\n                    // Explore and add the children\n                    const std::vector<GraphEdge>& out_edges = graph.GetNodeImmutable(top_node.NodeID()).GetOutEdgesImmutable();\n                    for (size_t out_edge_idx = 0; out_edge_idx < out_edges.size(); out_edge_idx++)\n                    {\n                        // Get the next potential child node\n                        const GraphEdge& current_out_edge = out_edges[out_edge_idx];\n                        const int64_t child_node_index = current_out_edge.GetToIndex();\n                        // Check if the top node->child edge is valid\n                        if (edge_validity_check_fn(graph, current_out_edge))\n                        {\n                            // Compute the cost-to-come for the new child\n                            const double parent_cost_to_come = top_node.CostToCome();\n                            const double parent_to_child_cost = distance_fn(graph, current_out_edge);\n                            const double child_cost_to_come = parent_cost_to_come + parent_to_child_cost;\n                            // Check if the child state has already been explored\n                            const auto child_explored_find_itr = explored.find(child_node_index);\n                            // It is not in the explored list, or is there with a higher cost-to-come\n                            const bool child_in_explored = (child_explored_find_itr != explored.end());\n                            const bool explored_child_is_better = (child_in_explored) ? (child_cost_to_come >= child_explored_find_itr->second.second) : false;\n                            // Check if the child state is already in the queue\n                            bool queue_is_better = false;\n                            if (limit_pqueue_duplicates)\n                            {\n                                const auto queue_members_map_itr = queue_members_map.find(child_node_index);\n                                const bool in_queue = (queue_members_map_itr != queue_members_map.end());\n                                queue_is_better = (in_queue) ? (child_cost_to_come >= queue_members_map_itr->second) : false;\n                            }\n                            // Only add the new state if we need to\n                            if (!explored_child_is_better && !queue_is_better)\n                            {\n                                // Compute the heuristic for the child\n                                const double child_heuristic = heuristic_function(child_node_index);\n                                // Compute the child value\n                                const double child_value = child_cost_to_come + child_heuristic;\n                                queue.push(arc_helpers::AstarPQueueElement(child_node_index, top_node.NodeID(), child_cost_to_come, child_value));\n                            }\n                        }\n                    }\n                }\n            }\n            return arc_helpers::ExtractAstarResult(explored, start_index, goal_index);\n        }\n\n        static arc_helpers::AstarResult PerformLazyAstar(const Graph<NodeValueType, Allocator>& graph, const int64_t start_index, const int64_t goal_index, const std::function<bool(const NodeValueType&, const NodeValueType&)>& edge_validity_check_fn, const std::function<double(const NodeValueType&, const NodeValueType&)>& distance_fn, const std::function<double(const NodeValueType&, const NodeValueType&)>& heuristic_fn, const bool limit_pqueue_duplicates)\n        {\n            const auto edge_validity_check_function = [&] (const Graph<NodeValueType, Allocator>& search_graph, const GraphEdge& edge) { return edge_validity_check_fn(search_graph.GetNodeImmutable(edge.GetFromIndex()).GetValueImmutable(), search_graph.GetNodeImmutable(edge.GetToIndex()).GetValueImmutable()); };\n            const auto distance_function = [&] (const Graph<NodeValueType, Allocator>& search_graph, const GraphEdge& edge) { return distance_fn(search_graph.GetNodeImmutable(edge.GetFromIndex()).GetValueImmutable(), search_graph.GetNodeImmutable(edge.GetToIndex()).GetValueImmutable()); };\n            return PerformLazyAstar(graph, start_index, goal_index, edge_validity_check_function, distance_function, heuristic_fn, limit_pqueue_duplicates);\n        }\n\n        static arc_helpers::AstarResult PerformAstar(const Graph<NodeValueType, Allocator>& graph, const int64_t start_index, const int64_t goal_index, const std::function<double(const NodeValueType&, const NodeValueType&)>& heuristic_fn, const bool limit_pqueue_duplicates)\n        {\n            const auto edge_validity_check_function = [&] (const Graph<NodeValueType, Allocator>& search_graph, const GraphEdge& edge) { UNUSED(search_graph); if (edge.GetWeight() < std::numeric_limits<double>::infinity()) { return true; } else { return false; } };\n            const auto distance_function = [&] (const Graph<NodeValueType, Allocator>& search_graph, const GraphEdge& edge) { UNUSED(search_graph); return edge.GetWeight(); };\n            return PerformLazyAstar(graph, start_index, goal_index, edge_validity_check_function, distance_function, heuristic_fn, limit_pqueue_duplicates);\n        }\n    };\n\n}\n\n#endif // DIJKSTRAS_HPP\n", "meta": {"hexsha": "41c915fd43187d4c38c5702c2d531af93fd1008d", "size": 41455, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/arc_utilities/dijkstras.hpp", "max_stars_repo_name": "ToyotaResearchInstitute/arc_utilities", "max_stars_repo_head_hexsha": "f15a1dfd9fba5ca83296354bae8b97628895c1c2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/arc_utilities/dijkstras.hpp", "max_issues_repo_name": "ToyotaResearchInstitute/arc_utilities", "max_issues_repo_head_hexsha": "f15a1dfd9fba5ca83296354bae8b97628895c1c2", "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/arc_utilities/dijkstras.hpp", "max_forks_repo_name": "ToyotaResearchInstitute/arc_utilities", "max_forks_repo_head_hexsha": "f15a1dfd9fba5ca83296354bae8b97628895c1c2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-11-06T21:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-06T21:38:23.000Z", "avg_line_length": 50.7405140759, "max_line_length": 487, "alphanum_fraction": 0.5581715113, "num_tokens": 7751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2667604911656573}}
{"text": "#include \"NumberClRA.h\"\n\n#include \"NumberMpq.h\"\n#include \"NumberMpz.h\"\n\n#include <boost/numeric/interval/interval.hpp>\n#include <boost/numeric/interval/policies.hpp>\n#include <boost/numeric/interval/arith2.hpp>\n#include <boost/numeric/interval/checking.hpp>\n\n#include <limits>\n\nnamespace carl {\n\n#ifdef USE_CLN_NUMBERS\n\n\n\t\t//constructs a/b:\n\t\t//(this looks hacky.. seems to be the only really functioning way though: take the integers as strings, put the sign at the front and construct\n\t\t//cl_RA from the string \"[-]a/b\")\n\t\tNumber<cln::cl_RA>::Number(const Number<cln::cl_I>& a, const Number<cln::cl_I>& b):\n\t\t\tNumber(cln::cl_RA(a) / b) {}\n\n\t\n\t\tNumber<cln::cl_RA>::Number(const Number<cln::cl_I>& n): Number(n.getValue()) {}\n\t\t//Number(const cln::cl_I& n) { mData = cln::cl_RA(n); }\n\n\n\t\tNumber<cln::cl_RA>::Number(const Number<mpq_class>& n) : Number(cln::cl_RA(n.toString().c_str())) {} \n\t\tNumber<cln::cl_RA>::Number(const Number<mpz_class>& n) : Number(cln::cl_RA(n.toString().c_str())) {} \n\n\n\n\n\n\n\n\t\t//this can maybe be done such that it's the same as for mpq_class\n    \t   Number<cln::cl_RA>::Number(const std::string& s) {\t\n\t\t//here, we need to distinguish two cases: we want to deal with normal floating point inputs (as \"3.5\") but also fractions (\"7/2\")\n\t\tif (s.find_first_of('/') == std::string::npos) { //this is the floating point case\t\t\t\t\n\t\t\n\t\t\tstd::vector<std::string> strs;\n\t\t\tboost::split(strs, s, boost::is_any_of(\".\"));\n\n\t\t\tif(strs.size() > 2)\n\t\t\t{\n\t\t\t    throw std::invalid_argument(\"More than one delimiter in the string.\");\n\t\t\t}\n\t\t\tcln::cl_RA result(0);\n\t\t\tif(!strs.front().empty())\n\t\t\t{\n\t\t\t    result += cln::cl_RA(strs.front().c_str());\n\t\t\t}\n\t\t\tif(strs.size() > 1)\n\t\t\t{\n\t\t\t    result += (cln::cl_RA(strs.back().c_str())/carl::pow(cln::cl_RA(10),static_cast<unsigned>(strs.back().size())));\n\t\t\t}\n\t\t\tmData = cln::cl_RA(result);\n\t\t} else { //the case where we have a fraction as input\n\t\t\tcln::cl_read_flags flags = {cln::syntax_rational, cln::lsyntax_all, 10, {cln::default_float_format, cln::default_float_format, false}}; \n\t\t\tstd::istringstream istr(s);\n\t\t\tmData = cln::cl_RA(cln::read_rational(istr,flags));\n\t\t}\n\t    } \n\t /*   Number<cln::cl_RA>::Number(double n) {\n\t\tswitch (std::fpclassify(n)) {\n\t\t    case FP_NORMAL: // normalized are fully supported\n\t\t        mData = cln::rationalize(convert<mpq_class, cln::cl_RA>(n));\n\t\t    case FP_SUBNORMAL: { // subnormals result in underflows, hence the value of the double is 0.f, where f is the significand precision\n\t\t\t\t\tstatic_assert(sizeof(n) == 8, \"double is assumed to be eight bytes wide.\");\n\t\t        sint significandBits = reinterpret_cast<sint>(&n);\n\t\t        significandBits = (significandBits << 12) >> 12;\n\t\t        if( n < 0 )\n\t\t            significandBits = -significandBits;\n\t\t        mData = cln::cl_RA( significandBits ) * ONE_DIVIDED_BY_10_TO_THE_POWER_OF_52;\n\t\t}\n\t\tcase FP_ZERO:\n\t\t    mData = cln::cl_RA(0);\n\t\tcase FP_NAN: // NaN and infinite are not supported\n\t\tcase FP_INFINITE:\n\t\t    assert(false);\n\t\t    break;\n\t\t}\n\t\tmData = cln::cl_RA(0);\n\t}\n\n\tNumber<cln::cl_RA>::Number(float n) {\n\t\tswitch (std::fpclassify(n))\n\t\t{\n\t\t    case FP_NORMAL: // normalized are fully supported\n\t\t        mData = cln::rationalize(convert<mpq_class, cln::cl_RA>(n));\n\t\t    case FP_SUBNORMAL: { // subnormals result in underflows, hence the value of the double is 0.f, where f is the significand precision\n\t\t\t\t\tstatic_assert(sizeof(n) == 4, \"float is assumed to be four bytes wide.\");\n\t\t        sint significandBits = reinterpret_cast<sint>(&n);\n\t\t        significandBits = (significandBits << 9) >> 9;\n\t\t        if( n < 0 )\n\t\t            significandBits = -significandBits;\n\t\t        mData = cln::cl_RA( significandBits ) * ONE_DIVIDED_BY_10_TO_THE_POWER_OF_23;\n\t\t}\n\t\tcase FP_ZERO:\n\t\t    mData = cln::cl_RA(0);\n\t\tcase FP_NAN: // NaN and infinite are not supported\n\t\tcase FP_INFINITE:\n\t\t    assert(false);\n\t\t    break;\n\t\t}\n\t\tmData = cln::cl_RA(0);\n\t} */\n\t\n\n\t//TODO: why not use the standard output of cln here?! Surely that works?\n\t    std::string Number<cln::cl_RA>::toString(bool _infix) const\n\t    {\n\n\t\tstd::stringstream s;\n\t\tbool negative = (mData < cln::cl_RA(0));\n\t\tif(negative) s << \"(-\" << (_infix ? \"\" : \" \");\n\t\tif(_infix) s << this->abs().mData;\n\t\telse\n\t\t{\n\t\t    cln::cl_I d = cln::denominator(mData);\n\t\t    if(mData != carl::constant_one<cln::cl_I>().get()) s << \"(/ \" << cln::abs(cln::numerator(mData)) << \" \" << cln::abs(d) << \")\";\n\t\t    else s << this->abs().getValue();\n\t\t}\n\t\tif(negative)\n\t\t    s << \")\";\n\t\treturn s.str();\n\t    } \n\n\n\n\n\n\t bool Number<cln::cl_RA>::sqrt_exact(Number<cln::cl_RA>& b) const\n\t {\n\t\tif( mData < 0 ) return false;\n\t\tcln::cl_RA result;\n\t\tbool boolResult = cln::sqrtp( mData, &result );\n\t\tb = Number(result);\n\t\treturn boolResult;\n\t }\n\n\t\n\t//this is the same as for mpq_class\t\n\t Number<cln::cl_RA> Number<cln::cl_RA>::sqrt() const\n\t {\n\t\tstd::pair<Number<cln::cl_RA>, Number<cln::cl_RA>> r = this->sqrt_safe();\n\t\treturn Number((r.first.getValue() + r.second.getValue()) / 2); //TODO: remove the getValue once operators are implemented!!\n\t }\n\t\n\n\tcln::cl_RA Number<cln::cl_RA>::scaleByPowerOfTwo(const cln::cl_RA& a, int exp) const {\n\t\tif (exp > 0) {\n\t\t\treturn cln::cl_RA(cln::numerator(a) << exp) / cln::denominator(a);\n\t\t} else if (exp < 0) {\n\t\t\treturn cln::cl_RA(cln::numerator(a)) / (cln::denominator(a) << -exp);\n\t\t}\n\t\treturn a;\n\t} \n\n\t    std::pair<Number<cln::cl_RA>, Number<cln::cl_RA>> Number<cln::cl_RA>::sqrt_safe() const\n\t    {\n\t\tassert( mData >= 0 );\n\t\tcln::cl_RA exact_root;\n\t\tif (cln::sqrtp(mData, &exact_root)) {\n\t\t    // root can be computed exactly.\n\t\t    return std::make_pair(Number(exact_root), Number(exact_root));\n\t\t} else {\n\t\t\t\tauto factor = int(cln::integer_length(cln::denominator(mData))) - int(cln::integer_length(cln::numerator(mData)));\n\t\t\t\tif (cln::oddp(factor)) factor += 1;\n\t\t\t\tcln::cl_RA n = scaleByPowerOfTwo(mData, factor);\n\t\t\t\tdouble dn = cln::double_approx(n);\n\t\t\t\tcln::cl_RA nra = cln::rationalize(dn);\n\t\t\t\tboost::numeric::interval<double> i;\n\t\t\t\tif (nra > n) {\n\t\t\t\t\ti.assign(cln::double_approx(2*n-nra), dn);\n\t\t\t\t\tassert(2*n-nra <= n);\n\t\t\t\t} else {\n\t\t\t\t\ti.assign(dn, cln::double_approx(2*n-nra));\n\t\t\t\t\tassert(n <= 2*n-nra);\n\t\t\t\t}\n\t\t\t\ti = boost::numeric::sqrt(i);\n\t\t\t\ti.assign(\n\t\t\t\t\tstd::nexttoward(i.lower(), -std::numeric_limits<double>::infinity()),\n\t\t\t\t\tstd::nexttoward(i.upper(), std::numeric_limits<double>::infinity())\n\t\t\t\t);\n\t\t\t\tfactor = factor / 2;\n\t\t\t\tcln::cl_RA lower = scaleByPowerOfTwo(cln::rationalize(i.lower()), -factor);\n\t\t\t\tcln::cl_RA upper = scaleByPowerOfTwo(cln::rationalize(i.upper()), -factor);\n\t\t\t\tassert(lower*lower <= mData);\n\t\t\t\tassert(mData <= upper*upper);\n\t\t\t\treturn std::make_pair(Number(lower), Number(upper));\n\t\t}\n\t    }\n\n\t    std::pair<Number<cln::cl_RA>, Number<cln::cl_RA>> Number<cln::cl_RA>::sqrt_fast() const\n\t    {\n\t\t\tassert(mData >= 0);\n\t\t\tcln::cl_RA exact_root;\n\t\t\tif (cln::sqrtp(mData, &exact_root)) {\n\t\t\t\t// root can be computed exactly.\n\t\t\t\treturn std::make_pair(Number(exact_root), Number(exact_root));\n\t\t\t} else {\n\t\t\t\t// compute an approximation with sqrt(). we can assume that the surrounding integers contain the actual root.\n\t\t\t\t//auto factor = cln::integer_length(cln::denominator(a)) - cln::integer_length(cln::numerator(a));\n\t\t\t\t//if (cln::oddp(factor)) factor += 1;\n\t\t\t\tcln::cl_I lower = cln::floor1(cln::sqrt(toLF(mData)));\n\t\t\t        cln::cl_I upper = lower + 1;\n\t\t\t        assert(cln::expt_pos(lower,2) < mData);\n\t\t\t        assert(cln::expt_pos(upper,2) > mData);\n\t\t\t        return std::make_pair(Number(lower), Number(upper));\n\t\t\t}\n\t    }\n\n\n\n#endif\n\n}\n", "meta": {"hexsha": "310548607d8468eb2749800e4fa3161540c1691d", "size": 7547, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/carl/numbers/number/NumberClRA.cpp", "max_stars_repo_name": "smtrat/carl-windows", "max_stars_repo_head_hexsha": "22b3a7677477cdbed9adc7619479ce82a0304666", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/carl/numbers/number/NumberClRA.cpp", "max_issues_repo_name": "smtrat/carl-windows", "max_issues_repo_head_hexsha": "22b3a7677477cdbed9adc7619479ce82a0304666", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/carl/numbers/number/NumberClRA.cpp", "max_forks_repo_name": "smtrat/carl-windows", "max_forks_repo_head_hexsha": "22b3a7677477cdbed9adc7619479ce82a0304666", "max_forks_repo_licenses": ["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.149321267, "max_line_length": 145, "alphanum_fraction": 0.6307141911, "num_tokens": 2338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.26674038821829293}}
{"text": "#include <Python.h>\n#include <omp.h>\n#include <vector>\n#include <set>\n#include <map>\n#include <string>\n#include <iostream>\n#include <boost/algorithm/minmax_element.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nconst double machine_epsilon = 1e-8;\n\nusing namespace std;\nusing namespace boost;\nusing namespace boost::numeric;\n\nstruct DATUM_X_T\n{\n    wstring x;\n    double proba;\n};\ntypedef vector<DATUM_X_T> DATA_X_T;\nstruct DATUM_XY_T\n{\n    wstring x;\n    wstring y;\n    double proba;\n};\ntypedef vector<DATUM_XY_T> DATA_XY_T;\nstruct FEATURE1_T\n{\n    wchar_t prev_label;\n    wchar_t label;\n};\nstruct FEATURE2_T\n{\n    vector<int> positions;\n    vector<wchar_t> values;\n    wchar_t label;\n};\ntypedef pair<vector<FEATURE1_T>, vector<FEATURE2_T>> FEATURES_T;\ntypedef map<wchar_t, size_t> YSET_T;\n\nstruct X_MS_ITEM_T\n{\n    wstring x;\n    double proba;\n    vector<ublas::matrix<double>> ms;\n    ublas::matrix<double> alpha;\n    ublas::matrix<double> beta;\n    double logz;\n};\n\ninline double logsumexp(ublas::vector<double>& x )\n{\n    double maxval = *max_element(x.begin(), x.end());\n    double val = 0;\n    for(ublas::vector<double>::iterator it=x.begin(); it<x.end(); ++it)\n        val += exp(*it - maxval);\n    val = maxval + log(val);\n    return val;\n}\n\nYSET_T pyyset_as_cpp(PyObject* pyyset)\n{\n    YSET_T yset;\n    PyObject *key, *value;\n    Py_ssize_t pos = 0;\n    while (PyDict_Next(pyyset, &pos, &key, &value))\n    {\n        wchar_t c;\n        PyUnicode_AsWideChar(key, &c, 1);\n        size_t i = PyLong_AsSize_t(value);\n        yset.insert(make_pair(c, i));\n    }\n    return yset;\n}\n\nDATA_X_T pydata_x_as_cpp(PyObject* pydata_x)\n{\n    DATA_X_T result;\n    for(Py_ssize_t i=0, size = PyList_Size(pydata_x); i<size; ++i)\n    {\n        PyObject* pyxp = PyList_GetItem(pydata_x, i);\n        wstring x( PyUnicode_AsUnicode( PyTuple_GetItem( pyxp, 0) ) );\n        double proba = PyFloat_AsDouble( PyTuple_GetItem( pyxp, 1) );\n        result.push_back({x, proba});\n    }\n    return result;\n}\n\nDATA_XY_T pydata_xy_as_cpp(PyObject* pydata_xy)\n{\n    DATA_XY_T result;\n    for(Py_ssize_t i=0, size=PyList_Size(pydata_xy); i<size; ++i)\n    {\n        PyObject* pyxyp = PyList_GetItem( pydata_xy, i );\n        PyObject* pyxy = PyTuple_GetItem( pyxyp, 0 );\n        wstring x( PyUnicode_AsUnicode( PyTuple_GetItem( pyxy, 0 ) ) );\n        wstring y( PyUnicode_AsUnicode( PyTuple_GetItem( pyxy, 1 ) ) );\n        double proba = PyFloat_AsDouble( PyTuple_GetItem( pyxyp, 1 ) );\n        assert( x.length() == y.length() );\n        //wcout << x << y << proba << endl;\n        result.push_back({x, y, proba});\n    }\n    return result;\n}\n\nvector<ublas::matrix<double>> xmatrices(const YSET_T& yset,const FEATURES_T& features,const ublas::vector<double>& weights,const wstring& x);\nublas::matrix<double> xalphas(const vector<ublas::matrix<double>>& ms);\nublas::matrix<double> xbetas(const vector<ublas::matrix<double>>& ms);\n\nFEATURES_T pyfeatures_as_cpp(PyObject* pyfeatures)\n{\n    vector<FEATURE1_T> features1;\n    vector<FEATURE2_T> features2;\n    Py_ssize_t K = PyList_Size(pyfeatures);\n    for(Py_ssize_t k=0; k<K; ++k)\n    {\n        PyObject* pyfeature = PyList_GetItem(pyfeatures,k);\n        Py_ssize_t t = PyTuple_Size(pyfeature);\n        if(t==2)\n        {\n            wchar_t prev_label = *PyUnicode_AsUnicode(PyTuple_GetItem(pyfeature, 0));\n            wchar_t label = *PyUnicode_AsUnicode(PyTuple_GetItem(pyfeature, 1));\n            features1.push_back({prev_label, label});\n        }\n        else if(t==3)\n        {\n            wchar_t label = *PyUnicode_AsUnicode(PyTuple_GetItem(pyfeature, 2));\n            PyObject* pytemp = PyTuple_GetItem(pyfeature, 0);\n            PyObject* pyValue = PyTuple_GetItem(pyfeature, 1);\n            assert( PyTuple_Size(pytemp) == PyTuple_Size(pyValue) );\n            vector<int> positions;\n            vector<wchar_t> values;\n            for(Py_ssize_t i=0; i<PyTuple_Size(pytemp); ++i)\n            {\n                int pos = PyLong_AsLong(PyTuple_GetItem(pytemp, i));\n                wchar_t value = *PyUnicode_AsUnicode(PyTuple_GetItem(pyValue, i));\n                positions.push_back(pos);\n                values.push_back(value);\n            }\n            features2.push_back({positions, values, label});\n        }\n        else\n        {\n            cout << \"feature size error! \" << t << endl;\n            exit(-1);\n        }\n    }\n    return make_pair(features1, features2);\n}\n\ninline bool fkyyxi(const FEATURES_T& features, const size_t k,const wchar_t prev_label,const wchar_t label,const wstring& x,const size_t i)\n{\n    size_t K1 = features.first.size();\n    if ( k<K1 )\n        return features.first[k].prev_label == prev_label and features.first[k].label == label ? 1 : 0;\n    if( features.second[k-K1].label == label )\n    {\n        size_t k3 = k-K1, n = x.length();\n        for(size_t t=0, T=features.second[k3].positions.size(); t<T; ++t)\n        {\n            int pos = (int)i+features.second[k3].positions[t];\n            if(((pos>=0 && pos<(int)n) ? x[pos] : L'\\0') != features.second[k3].values[t]) return 0;\n        }\n        return 1;\n    }\n    return 0;\n}\n\ninline double featurekxy(const FEATURES_T& features,const  size_t k, const wstring& x,const wstring& y)\n{\n    assert( x.length() == y.length() );\n    double value = 0.0;\n    wchar_t prev_label = L'^';\n    for(size_t i=0, n = x.length(); i<=n; ++i)\n    {\n        wchar_t label = i < n? y.at(i) : L'$';\n        value += fkyyxi(features, k, prev_label, label, x, i);\n        prev_label = label;\n    }\n    return value;\n}\n\nublas::vector<double> stat_all_xy_features_values(const FEATURES_T& features, const DATA_XY_T& data_xy)\n{\n    size_t K1 = features.first.size();\n    size_t K2 = features.second.size();\n    ublas::vector<double> values(K1+K2, 0);\n    #pragma omp parallel for\n    for(size_t k=0; k<K1+K2; ++k)\n    {\n        double value = 0;\n        for(DATA_XY_T::const_iterator it=data_xy.begin(); it<data_xy.end(); ++it)\n            value += it->proba * featurekxy(features, k, it->x, it->y);\n        values(k) = value;\n    }\n    return values;\n}\n\nublas::vector<double> doublelist_as_cpp(PyObject* pydoublelist)\n{\n    ublas::vector<double> vec(PyList_Size(pydoublelist));\n    for(Py_ssize_t i=0; i<PyList_Size(pydoublelist); ++i)\n    {\n        vec(i) = PyFloat_AsDouble(PyList_GetItem(pydoublelist, i));\n    }\n    return vec;\n}\n\nstatic PyObject* stat_all_xy_features_values(PyObject* self, PyObject* args)\n{\n    PyObject* pyfeatures = NULL;\n    PyObject* pydata_xy  = NULL;\n    if (!PyArg_ParseTuple(args, \"OO\", &pyfeatures, &pydata_xy))\n        return NULL;\n    FEATURES_T features = pyfeatures_as_cpp(pyfeatures);\n    DATA_XY_T data_xy = pydata_xy_as_cpp(pydata_xy);\n    ublas::vector<double> values = stat_all_xy_features_values(features, data_xy);\n    ublas::vector<double>::size_type k=0, K=values.size();\n    PyObject* pyvalues = PyList_New(K);\n    for(; k<K; ++k) PyList_SetItem(pyvalues, k, PyFloat_FromDouble( values(k) ) );\n    return pyvalues;\n}\n\ndouble model_values(const ublas::vector<double>& weights,const YSET_T& yset,const FEATURES_T& features, const DATA_X_T& data_x)\n{\n    double val = 0;\n    #pragma omp parallel for reduction(+:val)\n    for( DATA_X_T::const_iterator it=data_x.begin(); it<data_x.end(); ++it )\n    {\n        vector<ublas::matrix<double>> ms = xmatrices(yset, features, weights, it->x);\n        ublas::matrix<double> alpha = xalphas(ms);\n        //ublas::matrix<double> beta = xbetas(ms);\n        ublas::vector<double> alphalastrow = ublas::matrix_row<ublas::matrix<double>>(alpha, alpha.size1()-1);\n        //ublas::vector<double> betalastrow = ublas::matrix_row<ublas::matrix<double>>(beta, 0);\n        double logz1 = logsumexp(alphalastrow);\n        //double logz2 = logsumexp(betalastrow);\n        //cout << logz1 << \" , \" << logz2 << \" abs:\" << abs(logz1 - logz2) << endl;\n        //assert( abs(logz1 - logz2) < machine_epsilon );\n        val += it->proba * logz1;\n    }\n    return val;\n}\n\nstatic PyObject* model_values(PyObject* self, PyObject* args)\n{\n    PyObject* pyweights = NULL;\n    PyObject* pyyset = NULL;\n    PyObject* pyfeatures = NULL;\n    PyObject* pydata_x  = NULL;\n    if (!PyArg_ParseTuple(args, \"OOOO\", &pyweights, &pyyset, &pyfeatures, &pydata_x))\n        return NULL;\n    ublas::vector<double> weights = doublelist_as_cpp(pyweights);\n    YSET_T yset = pyyset_as_cpp(pyyset);\n    FEATURES_T features = pyfeatures_as_cpp(pyfeatures);\n    DATA_X_T data_x = pydata_x_as_cpp(pydata_x);\n    return PyFloat_FromDouble(model_values(weights, yset, features, data_x));\n}\n\ninline double yyxi(const FEATURES_T& features,const ublas::vector<double>& weights,const wchar_t prev_label,const wchar_t label,const wstring& x,const size_t i)\n{\n    static map<tuple<wchar_t, wchar_t, wstring, size_t>, vector<size_t>> yyxi_cache_helper;\n    double val=0;\n    auto key = make_tuple(prev_label, label, x, i);\n    if( yyxi_cache_helper.find(key) != yyxi_cache_helper.end() )\n    {\n        vector<size_t> ks = yyxi_cache_helper[key];\n        for(vector<size_t>::iterator it=ks.begin(); it<ks.end(); ++it)\n            val += weights[*it];\n        return val;\n    }\n    for(size_t k=0; k<weights.size(); ++k)\n    {\n        if( fkyyxi(features, k, prev_label, label, x, i) > 0.5 )\n        {\n            if ( yyxi_cache_helper.find(key) == yyxi_cache_helper.end() )\n            {\n                #pragma omp critical\n                yyxi_cache_helper.insert(make_pair(key, vector<size_t>()));\n            }\n            #pragma omp critical\n            yyxi_cache_helper[key].push_back(k);\n            val += weights[k];\n        }\n    }\n    return val;\n}\n\ninline ublas::matrix<double> xmatrixi(const YSET_T& yset,const FEATURES_T& features,const ublas::vector<double>& weights,const wstring& x,const size_t i)\n{\n    ublas::matrix<double> m(yset.size(), yset.size());\n    for(YSET_T::const_iterator y0it=yset.begin(); y0it!=yset.end(); ++y0it)\n    {\n        for(YSET_T::const_iterator y1it=yset.begin(); y1it!=yset.end(); ++y1it)\n        {\n            if(i==0)\n            {\n                m(y0it->second, y1it->second) = (y0it->second==0) ? yyxi(features, weights, L'^', y1it->first, x, i) : 0;\n            }\n            else if(i==x.length())\n            {\n                m(y0it->second, y1it->second) = (y1it->second==0) ? yyxi(features, weights, y0it->first, L'$', x, i) : 0;\n            }\n            else\n            {\n                m(y0it->second, y1it->second) = yyxi(features, weights, y0it->first, y1it->first, x, i);\n            }\n        }\n    }\n    return m;\n}\n\ninline vector<ublas::matrix<double>> xmatrices(const YSET_T& yset,const FEATURES_T& features,const ublas::vector<double>& weights,const wstring& x)\n{\n    size_t n = x.length();\n    vector<ublas::matrix<double>> ms(n+1);\n    for(size_t i=0; i<=n; ++i)\n        ms.at(i) = xmatrixi(yset, features, weights, x, i);\n    return ms;\n}\n\ninline ublas::matrix<double> xalphas(const vector<ublas::matrix<double>>& ms)\n{\n    size_t mslen = ms.size();\n    ublas::matrix<double> alpha(mslen, ms[0].size1());\n    ublas::row<ublas::matrix<double>>(alpha, 0) = ublas::row<ublas::matrix<double>>(ms[0], 0);\n    for(size_t i=1; i<mslen-1; ++i)\n    {\n        for(size_t j=0; j<ms[i].size2(); ++j)\n        {\n            ublas::vector<double> values = ublas::row<ublas::matrix<double>>(alpha, i-1)\n                                           + ublas::column<ublas::matrix<double>>(ms[i], j);\n            alpha(i, j) = logsumexp( values );\n        }\n    }\n    ublas::row<ublas::matrix<double>>(alpha, mslen-1) = ublas::row<ublas::matrix<double>>(alpha, mslen-2)\n                                   + ublas::column<ublas::matrix<double>>(ms[mslen-1], 0);\n    return alpha;\n}\n\ninline ublas::matrix<double> xbetas(const vector<ublas::matrix<double>>& ms)\n{\n    size_t mslen = ms.size();\n    ublas::matrix<double> beta(mslen, ms[0].size1());\n    ublas::row<ublas::matrix<double>>(beta, mslen-1) = ublas::column<ublas::matrix<double>>(ms[mslen-1], 0);\n    for(size_t i=mslen-2; i>0; --i)\n    {\n        for(size_t j=0; j<ms[i].size1(); ++j)\n        {\n            ublas::vector<double> values = ublas::row<ublas::matrix<double>>(ms[i], j)\n                                           + ublas::row<ublas::matrix<double>>(beta, i+1);\n            beta(i, j) = logsumexp( values );\n        }\n    }\n    ublas::row<ublas::matrix<double>>(beta, 0) = ublas::row<ublas::matrix<double>>(ms[0], 0)\n                                   + ublas::row<ublas::matrix<double>>(beta, 1);\n    return beta;\n}\n\ninline double xyiiproba(const YSET_T& yset,const vector<ublas::matrix<double>>& ms,const ublas::matrix<double>& alpha,const ublas::matrix<double>& beta,const size_t s0,const size_t s1,const size_t i,const double logz)\n{\n    //assert( 0<=i and i<ms.size() );\n    double p = -logz;\n    if (i==0)\n    {\n        p += ms[i](0, s1) + beta(i+1, s1);\n    }\n    else if(i==ms.size()-1)\n    {\n        p += alpha(i-1, s0) + ms[i](s0, 0);\n    }\n    else\n    {\n        p += alpha(i-1, s0) + ms[i](s0, s1) + beta(i+1, s1);\n    }\n    return exp( p );\n}\n\ninline double xyproba(const YSET_T& yset, const vector<ublas::matrix<double>>& ms, const double logz,const wstring& y)\n{\n    double v=0;\n    v += ms.front()(0, yset.at(y.front()));\n    for(size_t i=1; i<y.size(); ++i)\n        v+=ms.at(i)(yset.at(y.at(i-1)), yset.at(y.at(i)));\n    v += ms.back()( yset.at(y.back()), 0);\n    return exp( v - logz );\n}\n\ninline double kx(const YSET_T& yset,const FEATURES_T& features,const size_t k,const wstring& x,const vector<ublas::matrix<double>>& ms,const ublas::matrix<double>& alpha,const ublas::matrix<double>& beta,const double logz)\n{\n    //assert( x.length()+1 == ms.size() );\n    double v = 0;\n    size_t n = x.length();\n\n    for(YSET_T::const_iterator y1it=yset.begin(); y1it!=yset.end(); ++y1it)\n        if( fkyyxi(features, k, L'^', y1it->first, x, 0) )\n            v += xyiiproba(yset, ms, alpha, beta, 0, y1it->second, 0, logz);\n\n    for(size_t i=1; i<n; ++i)\n        for(YSET_T::const_iterator y0it=yset.begin(); y0it!=yset.end(); ++y0it)\n            for(YSET_T::const_iterator y1it=yset.begin(); y1it!=yset.end(); ++y1it)\n                if( fkyyxi(features, k, y0it->first, y1it->first, x, i) )\n                    v += xyiiproba(yset, ms, alpha, beta, y0it->second, y1it->second, i, logz);\n\n    for(YSET_T::const_iterator y0it=yset.begin(); y0it!=yset.end(); ++y0it)\n        if( fkyyxi(features, k, y0it->first, L'$', x, n) )\n            v += xyiiproba(yset, ms, alpha, beta, y0it->second, 0, n, logz);\n\n    return v;\n}\n\ninline double allxv(const YSET_T& yset, const FEATURES_T& features,const size_t k,const vector<X_MS_ITEM_T>& malphabetaz)\n{\n    double grad=0;\n    for(vector<X_MS_ITEM_T>::const_iterator it=malphabetaz.cbegin(); it<malphabetaz.cend(); ++it)\n        grad += it->proba * kx( yset, features, k, it->x, it->ms, it->alpha, it->beta, it->logz );\n    return grad;\n}\n\nublas::vector<double> model_grads(const YSET_T& yset,const FEATURES_T& features,const ublas::vector<double>& weights,const DATA_X_T& data_x)\n{\n    size_t K = weights.size();\n    ublas::vector<double> grads(K);\n    vector<X_MS_ITEM_T> malphabetaz( data_x.size() );\n    #pragma omp parallel for\n    for(DATA_X_T::size_type i=0; i<data_x.size(); ++i)\n    {\n        vector<ublas::matrix<double>> ms = xmatrices( yset, features, weights, data_x.at(i).x );\n        ublas::matrix<double> alpha = xalphas(ms);\n        ublas::matrix<double> beta = xbetas(ms);\n        ublas::vector<double> alphalastrow = ublas::matrix_row<ublas::matrix<double>>(alpha, alpha.size1()-1);\n        ublas::vector<double> betafirstrow = ublas::matrix_row<ublas::matrix<double>>(beta, 0);\n        double logz1 = logsumexp( alphalastrow );\n        double logz2 = logsumexp( betafirstrow );\n        assert( abs(logz1 - logz2) < machine_epsilon );\n        assert( data_x.at(i).x.length()+1 == ms.size() );\n        malphabetaz.at(i) = {data_x.at(i).x, data_x.at(i).proba, ms, alpha, beta, logz1};\n    }\n    #pragma omp parallel for\n    for(size_t k=0; k<K; ++k)\n        grads(k) = allxv(yset, features, k, malphabetaz);\n    return grads;\n}\n\nublas::vector<double> model_grads1(const YSET_T& yset,const FEATURES_T& features,const ublas::vector<double>& weights,const DATA_X_T& data_x)\n{\n    size_t K = weights.size();\n    ublas::vector<double> grads(K);\n    vector<X_MS_ITEM_T> malphabetaz( data_x.size() );\n    #pragma omp parallel for\n    for(DATA_X_T::size_type i=0; i<data_x.size(); ++i)\n    {\n        vector<ublas::matrix<double>> ms = xmatrices( yset, features, weights, data_x.at(i).x );\n        ublas::matrix<double> alpha = xalphas(ms);\n        ublas::matrix<double> beta = xbetas(ms);\n        ublas::vector<double> alphalastrow = ublas::matrix_row<ublas::matrix<double>>(alpha, alpha.size1()-1);\n        ublas::vector<double> betafirstrow = ublas::matrix_row<ublas::matrix<double>>(beta, 0);\n        double logz1 = logsumexp( alphalastrow );\n        double logz2 = logsumexp( betafirstrow );\n        assert( abs(logz1 - logz2) < machine_epsilon );\n        assert( data_x.at(i).x.length()+1 == ms.size() );\n        malphabetaz.at(i) = {data_x.at(i).x, data_x.at(i).proba, ms, alpha, beta, logz1};\n    }\n    struct XS0S1I_T\n    {\n        size_t s0;\n        size_t s1;\n        size_t xi;\n    };\n    typedef vector<XS0S1I_T> XS0S1I_LIST_T;\n    struct KX_T\n    {\n        size_t xnum;\n        XS0S1I_LIST_T pxs;\n    };\n    typedef vector<KX_T> KX_LIST_T;\n    static vector<KX_LIST_T> kxtablecache(K);\n    static bool kxtablecache_flag = 0;\n    if ( !kxtablecache_flag )\n    {\n        #pragma omp parallel for\n        for(size_t k=0; k<K; ++k)\n        {\n            KX_LIST_T kx;\n            for(size_t xnum=0; xnum<data_x.size(); ++xnum)\n            {\n                XS0S1I_LIST_T xs0s1i;\n                wstring x = data_x.at(xnum).x;\n                size_t n = x.length();\n                for(YSET_T::const_iterator y1it=yset.begin(); y1it!=yset.end(); ++y1it)\n                    if( fkyyxi(features, k, L'^', y1it->first, x, 0) )\n                        xs0s1i.push_back({ 0, y1it->second, 0 });\n                for(size_t i=1; i<n; ++i)\n                    for(YSET_T::const_iterator y0it=yset.begin(); y0it!=yset.end(); ++y0it)\n                        for(YSET_T::const_iterator y1it=yset.begin(); y1it!=yset.end(); ++y1it)\n                            if( fkyyxi(features, k, y0it->first, y1it->first, x, i) )\n                                xs0s1i.push_back({ y0it->second, y1it->second, i });\n                for(YSET_T::const_iterator y0it=yset.begin(); y0it!=yset.end(); ++y0it)\n                    if( fkyyxi(features, k, y0it->first, L'$', x, n) )\n                        xs0s1i.push_back( {y0it->second, 0, n});\n                if ( xs0s1i.size() > 0 )\n                    kx.push_back({xnum, xs0s1i});\n            }\n            kxtablecache.at(k) = kx;\n        }\n        kxtablecache_flag = 1;\n    }\n\n    #pragma omp parallel for\n    for(size_t k=0; k<K; ++k)\n    {\n        const KX_LIST_T& kx = kxtablecache.at(k);\n        for( KX_LIST_T::const_iterator kxit=kx.begin(); kxit<kx.end(); ++kxit  )\n        {\n            const X_MS_ITEM_T& xitem = malphabetaz.at(kxit->xnum);\n            const XS0S1I_LIST_T& xs0s1i = kxit->pxs;\n            double v=0;\n            for( XS0S1I_LIST_T::const_iterator it=xs0s1i.begin(); it<xs0s1i.end(); ++it )\n            {\n                v += xyiiproba(yset, xitem.ms, xitem.alpha, xitem.beta, it->s0, it->s1, it->xi, xitem.logz );\n            }\n            grads(k) += xitem.proba * v;\n        }\n    }\n    return grads;\n}\n\nstatic PyObject* model_grads(PyObject* self, PyObject* args)\n{\n    PyObject* pyyset = NULL;\n    PyObject* pyfeatures = NULL;\n    PyObject* pyweights = NULL;\n    PyObject* pydata_x  = NULL;\n    if (!PyArg_ParseTuple(args, \"OOOO\", &pyyset, &pyfeatures, &pyweights, &pydata_x))\n        return NULL;\n    YSET_T yset = pyyset_as_cpp(pyyset);\n    FEATURES_T features = pyfeatures_as_cpp(pyfeatures);\n    ublas::vector<double> weights = doublelist_as_cpp(pyweights);\n    DATA_X_T data_x = pydata_x_as_cpp(pydata_x);\n    ublas::vector<double> grads = model_grads(yset, features, weights, data_x);\n    PyObject* pygrads = PyList_New(grads.size());\n    for(size_t i=0; i<grads.size(); ++i)\n        PyList_SetItem(pygrads, i, PyFloat_FromDouble( grads(i) ) );\n    return pygrads;\n}\n\nstatic PyObject* model_grads1(PyObject* self, PyObject* args)\n{\n    PyObject* pyyset = NULL;\n    PyObject* pyfeatures = NULL;\n    PyObject* pyweights = NULL;\n    PyObject* pydata_x  = NULL;\n    if (!PyArg_ParseTuple(args, \"OOOO\", &pyyset, &pyfeatures, &pyweights, &pydata_x))\n        return NULL;\n    YSET_T yset = pyyset_as_cpp(pyyset);\n    FEATURES_T features = pyfeatures_as_cpp(pyfeatures);\n    ublas::vector<double> weights = doublelist_as_cpp(pyweights);\n    DATA_X_T data_x = pydata_x_as_cpp(pydata_x);\n    ublas::vector<double> grads = model_grads1(yset, features, weights, data_x);\n    PyObject* pygrads = PyList_New(grads.size());\n    for(size_t i=0; i<grads.size(); ++i)\n        PyList_SetItem(pygrads, i, PyFloat_FromDouble( grads(i) ) );\n    return pygrads;\n}\n\nstatic PyMethodDef crfextMethods[] =\n{\n    {\"model_grads\", model_grads, METH_VARARGS, \"grads\"},\n    {\"model_grads1\", model_grads1, METH_VARARGS, \"grads\"},\n    {\"model_values\", model_values, METH_VARARGS, \"\"},\n    {\"stat_all_xy_features_values\", stat_all_xy_features_values, METH_VARARGS, \"stat all features values on all data\"},\n    {NULL, NULL, 0, NULL}        /* Sentinel */\n};\n\nstatic struct PyModuleDef crfextmodule =\n{\n    PyModuleDef_HEAD_INIT,\n    \"crfext\",\n    NULL,\n    -1,\n    crfextMethods\n};\n\nPyMODINIT_FUNC PyInit_crfext(void)\n{\n    return PyModule_Create(&crfextmodule);\n};\n", "meta": {"hexsha": "8ec22c810dea25b0c3ff9cba98a1f0f2ed32a3a3", "size": 21748, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "crf/crfext/main.cpp", "max_stars_repo_name": "shizhuolin/zh-word-segment", "max_stars_repo_head_hexsha": "74765e282c636f9e08cdd22bb1d572ddaf9cd75c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-06-26T02:08:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-30T09:28:47.000Z", "max_issues_repo_path": "crf/crfext/main.cpp", "max_issues_repo_name": "shizhuolin/zh-word-segment", "max_issues_repo_head_hexsha": "74765e282c636f9e08cdd22bb1d572ddaf9cd75c", "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": "crf/crfext/main.cpp", "max_forks_repo_name": "shizhuolin/zh-word-segment", "max_forks_repo_head_hexsha": "74765e282c636f9e08cdd22bb1d572ddaf9cd75c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-03-30T09:28:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-16T09:45:35.000Z", "avg_line_length": 36.6745362563, "max_line_length": 222, "alphanum_fraction": 0.6079179695, "num_tokens": 6478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.26672283058378915}}
{"text": "/**\n * PathSetThreadPool.cpp\n *\n *  Created on: Feb 18, 2014\n *      Author: redheli\n */\n\n\n#include \"PathSetThreadPool.hpp\"\n#include \"Path.hpp\"\n#include \"geospatial/streetdir/A_StarShortestTravelTimePathImpl.hpp\"\n#include \"geospatial/streetdir/A_StarShortestPathImpl.hpp\"\n#include \"logging/Log.hpp\"\n\n#include <pthread.h>\n#include <semaphore.h>\n#include <cstdlib>\n#include <boost/graph/filtered_graph.hpp>\n#include <boost/graph/astar_search.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <iterator>\n#include <algorithm>\n#include <vector>\n\nusing namespace std;\n\nnamespace\n{\n    //sim_mob::BasicLogger & logger = sim_mob::Logger::log(\"pathset.log\");\n}\n\nsim_mob::PathSetWorkerThread::PathSetWorkerThread() :\n        path(NULL), linkLookup(NULL), fromNode(NULL), toNode(NULL), hasPath(false), timeBased(false), dbgStr(std::string()), graph(NULL)\n{\n}\n\nsim_mob::PathSetWorkerThread::~PathSetWorkerThread() { }\n\n//1.Create Blacklist\n//2.clear the shortestWayPointpath\n//3.Populate a vector<WayPoint> with a blacklist involved\n//  or\n//  Populate a vector<WayPoint> without blacklist involvement\n//4.populate a singlepath instance\nvoid sim_mob::PathSetWorkerThread::run()\n{\n    //Convert the blacklist into a list of blocked Vertices.\n    std::set<StreetDirectory::Edge> blacklistEdges;\n    std::map<const Link*, std::set<StreetDirectory::Edge> >::const_iterator lookIt;\n    for (std::set<const Link*>::iterator it = excludedLinks.begin(); it != excludedLinks.end(); it++)\n    {\n        lookIt = linkLookup->find(*it);\n        if (lookIt != linkLookup->end())\n        {\n            blacklistEdges.insert(lookIt->second.begin(), lookIt->second.end());\n        }\n    }\n\n    //used for error checking and validation\n    std::pair<StreetDirectory::Edge, bool> dbgPrevEdge;\n    //output container\n    vector<WayPoint> wps;\n\n    if (blacklistEdges.empty())\n    {\n        if(timeBased)\n        {\n            std::list<StreetDirectory::Vertex> partialRes;\n            //Use A* to search for a path\n            //Taken from: http://www.boost.org/doc/libs/1_38_0/libs/graph/example/astar-cities.cpp\n            vector<StreetDirectory::Vertex> p(boost::num_vertices(*graph)); //Output variable\n            vector<double> d(boost::num_vertices(*graph)); //Output variable\n            try\n            {\n                boost::astar_search(*graph, fromVertex, sim_mob::A_StarShortestTravelTimePathImpl::DistanceHeuristicGraph(graph, toVertex),\n                                    boost::predecessor_map(&p[0]).distance_map(&d[0]).visitor(sim_mob::A_StarShortestTravelTimePathImpl::GoalVisitor(toVertex)));\n            }\n            catch (sim_mob::A_StarShortestTravelTimePathImpl::Goal& goal)\n            {\n                //Build backwards.\n                for (StreetDirectory::Vertex v = toVertex;; v = p[v])\n                {\n                    partialRes.push_front(v);\n                    if (p[v] == v)\n                    {\n                        break;\n                    }\n                }\n                //Now build forwards.\n                std::list<StreetDirectory::Vertex>::const_iterator prev = partialRes.end();\n                for (std::list<StreetDirectory::Vertex>::const_iterator it = partialRes.begin(); it != partialRes.end(); it++)\n                {\n                    //Add this edge.\n                    if (prev != partialRes.end())\n                    {\n                        //This shouldn't fail.\n                        std::pair < StreetDirectory::Edge, bool> edge = boost::edge(*prev, *it, *graph);\n                        if (!edge.second)\n                        {\n                            Warn() << \"ERROR: Boost can't find an edge that it should know about.\" << std::endl;\n                        }\n                        //Retrieve, add this edge's WayPoint.\n                        WayPoint wp = boost::get(boost::edge_name, *graph, edge.first);\n                        wps.push_back(wp);\n                    }\n                    //Save for later.\n                    prev = it;\n                }\n            }\n        }\n        else\n        {\n            std::list<StreetDirectory::Vertex> partialRes;\n            //Use A* to search for a path\n            //Taken from: http://www.boost.org/doc/libs/1_38_0/libs/graph/example/astar-cities.cpp\n            vector<StreetDirectory::Vertex> p(boost::num_vertices(*graph)); //Output variable\n            vector<double> d(boost::num_vertices(*graph)); //Output variable\n            try\n            {\n                boost::astar_search(*graph, fromVertex, sim_mob::A_StarShortestPathImpl::DistanceHeuristicGraph(graph, toVertex),\n                                    boost::predecessor_map(&p[0]).distance_map(&d[0]).visitor(sim_mob::A_StarShortestPathImpl::GoalVisitor(toVertex)));\n            }\n            catch (sim_mob::A_StarShortestPathImpl::Goal& goal)\n            {\n                //Build backwards.\n                for (StreetDirectory::Vertex v = toVertex;; v = p[v])\n                {\n                    partialRes.push_front(v);\n                    if (p[v] == v)\n                    {\n                        break;\n                    }\n                }\n                //Now build forwards.\n                std::list<StreetDirectory::Vertex>::const_iterator prev = partialRes.end();\n                for (std::list<StreetDirectory::Vertex>::const_iterator it = partialRes.begin(); it != partialRes.end(); it++)\n                {\n                    //Add this edge.\n                    if (prev != partialRes.end())\n                    {\n                        //This shouldn't fail.\n                        std::pair < StreetDirectory::Edge, bool> edge = boost::edge(*prev, *it, *graph);\n                        if (!edge.second)\n                        {\n                            Warn() << \"ERROR: Boost can't find an edge that it should know about.\" << std::endl;\n                        }\n                        //Retrieve, add this edge's WayPoint.\n                        WayPoint wp = boost::get(boost::edge_name, *graph, edge.first);\n                        wps.push_back(wp);\n                    }\n                    //Save for later.\n                    prev = it;\n                }\n            }\n        }\n    }\n    else\n    {\n        if (timeBased)\n        {\n            //logger << \"Blacklist NOT empty\" << blacklistV.size() << std::endl;\n            //Filter it.\n\n            sim_mob::A_StarShortestTravelTimePathImpl::BlackListEdgeConstraint filter(blacklistEdges);\n            boost::filtered_graph<StreetDirectory::Graph, sim_mob::A_StarShortestTravelTimePathImpl::BlackListEdgeConstraint> filtered(*graph, filter);\n            ////////////////////////////////////////\n            // TODO: This code is copied (since filtered_graph is not the same as adjacency_list) from searchShortestPath.\n            ////////////////////////////////////////\n            std::list<StreetDirectory::Vertex> partialRes;\n\n            vector<StreetDirectory::Vertex> p(boost::num_vertices(filtered)); //Output variable\n            vector<double> d(boost::num_vertices(filtered)); //Output variable\n\n            //Use A* to search for a path\n            //Taken from: http://www.boost.org/doc/libs/1_38_0/libs/graph/example/astar-cities.cpp\n            //...which is available under the terms of the Boost Software License, 1.0\n            try\n            {\n                if(!p.empty() && !d.empty())\n                {\n                    boost::astar_search(filtered, fromVertex, sim_mob::A_StarShortestTravelTimePathImpl::DistanceHeuristicFiltered(&filtered, toVertex),\n                                        boost::predecessor_map(&p[0]).distance_map(&d[0]).visitor(sim_mob::A_StarShortestTravelTimePathImpl::GoalVisitor(toVertex)));\n                }\n            }\n            catch (sim_mob::A_StarShortestTravelTimePathImpl::Goal& goal)\n            {\n                //Build backwards.\n                for (StreetDirectory::Vertex v = toVertex;; v = p[v])\n                {\n                    partialRes.push_front(v);\n                    if (p[v] == v)\n                    {\n                        break;\n                    }\n                }\n                //Now build forwards.\n                std::list<StreetDirectory::Vertex>::const_iterator prev = partialRes.end();\n                for (std::list<StreetDirectory::Vertex>::const_iterator it = partialRes.begin(); it != partialRes.end(); it++)\n                {\n                    //Add this edge.\n                    if (prev != partialRes.end())\n                    {\n                        //This shouldn't fail.\n                        std::pair < StreetDirectory::Edge, bool> edge = boost::edge(*prev, *it, filtered);\n                        if (!edge.second)\n                        {\n                            std::cerr << \"ERROR: Boost can't find an edge that it should know about.\" << std::endl;\n                        }\n                        //Retrieve, add this edge's WayPoint.\n                        WayPoint wp = boost::get(boost::edge_name, filtered, edge.first);\n                        wps.push_back(wp);\n                    }\n\n                    //Save for later.\n                    prev = it;\n                }\n            } //catch\n        }\n        else\n        {\n            //logger << \"Blacklist NOT empty\" << blacklistV.size() << std::endl;\n            //Filter it.\n            sim_mob::A_StarShortestPathImpl::BlackListEdgeConstraint filter(blacklistEdges);\n            boost::filtered_graph<StreetDirectory::Graph, sim_mob::A_StarShortestPathImpl::BlackListEdgeConstraint> filtered(*graph, filter);\n            ////////////////////////////////////////\n            // TODO: This code is copied (since filtered_graph is not the same as adjacency_list) from searchShortestPath.\n            ////////////////////////////////////////\n            std::list<StreetDirectory::Vertex> partialRes;\n\n            vector<StreetDirectory::Vertex> p(boost::num_vertices(filtered)); //Output variable\n            vector<double> d(boost::num_vertices(filtered)); //Output variable\n\n            //Use A* to search for a path\n            //Taken from: http://www.boost.org/doc/libs/1_38_0/libs/graph/example/astar-cities.cpp\n            //...which is available under the terms of the Boost Software License, 1.0\n            try\n            {\n                if(!p.empty() && !d.empty())\n                {\n                    boost::astar_search(filtered, fromVertex, sim_mob::A_StarShortestPathImpl::DistanceHeuristicFiltered(&filtered, toVertex),\n                                        boost::predecessor_map(&p[0]).distance_map(&d[0]).visitor(sim_mob::A_StarShortestPathImpl::GoalVisitor(toVertex)));\n                }\n            }\n            catch (sim_mob::A_StarShortestPathImpl::Goal& goal)\n            {\n                //Build backwards.\n                for (StreetDirectory::Vertex v = toVertex;; v = p[v])\n                {\n                    partialRes.push_front(v);\n                    if (p[v] == v)\n                    {\n                        break;\n                    }\n                }\n                //Now build forwards.\n                std::list<StreetDirectory::Vertex>::const_iterator prev = partialRes.end();\n                for (std::list<StreetDirectory::Vertex>::const_iterator it = partialRes.begin(); it != partialRes.end(); it++)\n                {\n                    //Add this edge.\n                    if (prev != partialRes.end())\n                    {\n                        //This shouldn't fail.\n                        std::pair < StreetDirectory::Edge, bool> edge = boost::edge(*prev, *it, filtered);\n                        if (!edge.second)\n                        {\n                            std::cerr << \"ERROR: Boost can't find an edge that it should know about.\" << std::endl;\n                        }\n                        //Retrieve, add this edge's WayPoint.\n                        WayPoint wp = boost::get(boost::edge_name, filtered, edge.first);\n                        wps.push_back(wp);\n                    }\n\n                    //Save for later.\n                    prev = it;\n                }\n            }\n        }\n    }\n\n    if (wps.empty())\n    {\n        hasPath = false;\n    }\n    else\n    {\n        // make sp id\n        std::string id = sim_mob::makePathString(wps);\n        if (id.empty())\n        {\n            hasPath = false;\n        }\n        else\n        {\n            path = new sim_mob::SinglePath();\n            // fill data\n            path->isNeedSave2DB = true;\n            hasPath = true;\n            path->pathSetId = pathSet->id;\n            path->scenario = pathSet->scenario + dbgStr;\n            path->init(wps);\n            path->id = id;\n            path->pathSize = 0;\n            if (this->path->path.begin()->link->getFromNodeId() != this->pathSet->subTrip.origin.node->getNodeId())\n            {\n                safe_delete_item(path);\n                hasPath = false;\n            }\n        }\n    }\n}\n\n", "meta": {"hexsha": "1f90b289b62b197719a3579a128a95beeb3a577e", "size": 13005, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dev/Basic/shared/path/PathSetThreadPool.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/shared/path/PathSetThreadPool.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/shared/path/PathSetThreadPool.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.6826923077, "max_line_length": 165, "alphanum_fraction": 0.5027297193, "num_tokens": 2714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2667228248133341}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//  Copyright 2018 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_MULTIPRECISION_MPC_HPP\n#define BOOST_MULTIPRECISION_MPC_HPP\n\n#include <boost/multiprecision/number.hpp>\n#include <boost/cstdint.hpp>\n#include <boost/multiprecision/detail/digits.hpp>\n#include <boost/multiprecision/traits/is_variable_precision.hpp>\n#include <boost/multiprecision/mpfr.hpp>\n#include <boost/multiprecision/logged_adaptor.hpp>\n#include <boost/functional/hash_fwd.hpp>\n#include <mpc.h>\n#include <cmath>\n#include <algorithm>\n#include <complex>\n\n#ifndef BOOST_MULTIPRECISION_MPFI_DEFAULT_PRECISION\n#  define BOOST_MULTIPRECISION_MPFI_DEFAULT_PRECISION 20\n#endif\n\nnamespace boost{\nnamespace multiprecision{\nnamespace backends{\n\ntemplate <unsigned digits10>\nstruct mpc_complex_backend;\n\n} // namespace backends\n\ntemplate <unsigned digits10>\nstruct number_category<backends::mpc_complex_backend<digits10> > : public mpl::int_<number_kind_complex>{};\n\nnamespace backends{\n\nnamespace detail{\n\n\ninline void mpc_copy_precision(mpc_t dest, const mpc_t src)\n{\n   mpfr_prec_t p_dest = mpc_get_prec(dest);\n   mpfr_prec_t p_src = mpc_get_prec(src);\n   if (p_dest != p_src)\n      mpc_set_prec(dest, p_src);\n}\ninline void mpc_copy_precision(mpc_t dest, const mpc_t src1, const mpc_t src2)\n{\n   mpfr_prec_t p_dest = mpc_get_prec(dest);\n   mpfr_prec_t p_src1 = mpc_get_prec(src1);\n   mpfr_prec_t p_src2 = mpc_get_prec(src2);\n   if (p_src2 > p_src1)\n      p_src1 = p_src2;\n   if (p_dest != p_src1)\n      mpc_set_prec(dest, p_src1);\n}\n\n   \ntemplate <unsigned digits10>\nstruct mpc_complex_imp\n{\n#ifdef BOOST_HAS_LONG_LONG\n   typedef mpl::list<long, boost::long_long_type>                     signed_types;\n   typedef mpl::list<unsigned long, boost::ulong_long_type>   unsigned_types;\n#else\n   typedef mpl::list<long>                                signed_types;\n   typedef mpl::list<unsigned long>                       unsigned_types;\n#endif\n   typedef mpl::list<double, long double>                 float_types;\n   typedef long                                           exponent_type;\n\n   mpc_complex_imp()\n   {\n      mpc_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));\n      mpc_set_ui(m_data, 0u, GMP_RNDN);\n   }\n   mpc_complex_imp(unsigned digits2)\n   {\n      mpc_init2(m_data, digits2);\n      mpc_set_ui(m_data, 0u, GMP_RNDN);\n   }\n\n   mpc_complex_imp(const mpc_complex_imp& o)\n   {\n      mpc_init2(m_data, mpc_get_prec(o.m_data));\n      if(o.m_data[0].re[0]._mpfr_d)\n         mpc_set(m_data, o.m_data, GMP_RNDN);\n   }\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\n   mpc_complex_imp(mpc_complex_imp&& o) BOOST_NOEXCEPT\n   {\n      m_data[0] = o.m_data[0];\n      o.m_data[0].re[0]._mpfr_d = 0;\n   }\n#endif\n   mpc_complex_imp& operator = (const mpc_complex_imp& o)\n   {\n      if( (o.m_data[0].re[0]._mpfr_d) && (this != &o) )\n      {\n         if (m_data[0].re[0]._mpfr_d == 0)\n            mpc_init2(m_data, mpc_get_prec(o.m_data));\n         mpc_set(m_data, o.m_data, GMP_RNDD);\n      }\n      return *this;\n   }\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\n   mpc_complex_imp& operator = (mpc_complex_imp&& o) BOOST_NOEXCEPT\n   {\n      mpc_swap(m_data, o.m_data);\n      return *this;\n   }\n#endif\n#ifdef BOOST_HAS_LONG_LONG\n#ifdef _MPFR_H_HAVE_INTMAX_T\n   mpc_complex_imp& operator = (boost::ulong_long_type i)\n   {\n      if(m_data[0].re[0]._mpfr_d == 0)\n         mpc_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));\n      mpc_set_uj(data(), i, GMP_RNDD);\n      return *this;\n   }\n   mpc_complex_imp& operator = (boost::long_long_type i)\n   {\n      if(m_data[0].re[0]._mpfr_d == 0)\n         mpc_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));\n      mpc_set_sj(data(), i, GMP_RNDD);\n      return *this;\n   }\n#else\n   mpc_complex_imp& operator = (boost::ulong_long_type i)\n   {\n      mpfr_float_backend<digits10> f(0uL, mpc_get_prec(m_data));\n      f = i;\n      mpc_set_fr(this->data(), f.data(), GMP_RNDN);\n      return *this;\n   }\n   mpc_complex_imp& operator = (boost::long_long_type i)\n   {\n      mpfr_float_backend<digits10> f(0uL, mpc_get_prec(m_data));\n      f = i;\n      mpc_set_fr(this->data(), f.data(), GMP_RNDN);\n      return *this;\n   }\n#endif\n#endif\n   mpc_complex_imp& operator = (unsigned long i)\n   {\n      if(m_data[0].re[0]._mpfr_d == 0)\n         mpc_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));\n      mpc_set_ui(m_data, i, GMP_RNDN);\n      return *this;\n   }\n   mpc_complex_imp& operator = (long i)\n   {\n      if(m_data[0].re[0]._mpfr_d == 0)\n         mpc_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));\n      mpc_set_si(m_data, i, GMP_RNDN);\n      return *this;\n   }\n   mpc_complex_imp& operator = (double d)\n   {\n      if(m_data[0].re[0]._mpfr_d == 0)\n         mpc_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));\n      mpc_set_d(m_data, d, GMP_RNDN);\n      return *this;\n   }\n   mpc_complex_imp& operator = (long double d)\n   {\n      if (m_data[0].re[0]._mpfr_d == 0)\n         mpc_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));\n      mpc_set_ld(m_data, d, GMP_RNDN);\n      return *this;\n   }\n   mpc_complex_imp& operator = (mpz_t i)\n   {\n      if (m_data[0].re[0]._mpfr_d == 0)\n         mpc_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));\n      mpc_set_z(m_data, i, GMP_RNDN);\n      return *this;\n   }\n   mpc_complex_imp& operator = (gmp_int i)\n   {\n      if (m_data[0].re[0]._mpfr_d == 0)\n         mpc_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));\n      mpc_set_z(m_data, i.data(), GMP_RNDN);\n      return *this;\n   }\n   \n   mpc_complex_imp& operator = (const char* s)\n   {\n      using default_ops::eval_fpclassify;\n\n      if(m_data[0].re[0]._mpfr_d == 0)\n         mpc_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));\n\n      mpfr_float_backend<digits10> a(0uL, mpc_get_prec(m_data)), b(0uL, mpc_get_prec(m_data));\n\n      if(s && (*s == '('))\n      {\n         std::string part;\n         const char* p = ++s;\n         while(*p && (*p != ',') && (*p != ')'))\n            ++p;\n         part.assign(s, p);\n         if(part.size())\n            a = part.c_str();\n         else\n            a = 0uL;\n         s = p;\n         if(*p && (*p != ')'))\n         {\n            ++p;\n            while(*p && (*p != ')'))\n               ++p;\n            part.assign(s + 1, p);\n         }\n         else\n            part.erase();\n         if(part.size())\n            b = part.c_str();\n         else\n            b = 0uL;\n      }\n      else\n      {\n         a = s;\n         b = 0uL;\n      }\n\n      if(eval_fpclassify(a) == (int)FP_NAN)\n      {\n         mpc_set_fr(this->data(), a.data(), GMP_RNDN);\n      }\n      else if(eval_fpclassify(b) == (int)FP_NAN)\n      {\n         mpc_set_fr(this->data(), b.data(), GMP_RNDN);\n      }\n      else\n      {\n         mpc_set_fr_fr(m_data, a.data(), b.data(), GMP_RNDN);\n      }\n      return *this;\n   }\n   void swap(mpc_complex_imp& o) BOOST_NOEXCEPT\n   {\n      mpc_swap(m_data, o.m_data);\n   }\n   std::string str(std::streamsize digits, std::ios_base::fmtflags f)const\n   {\n      BOOST_ASSERT(m_data[0].re[0]._mpfr_d);\n\n      mpfr_float_backend<digits10> a(0uL, mpc_get_prec(m_data)), b(0uL, mpc_get_prec(m_data));\n\n      mpc_real(a.data(), m_data, GMP_RNDD);\n      mpc_imag(b.data(), m_data, GMP_RNDD);\n\n      if(eval_is_zero(b))\n         return a.str(digits, f);\n\n      return \"(\" + a.str(digits, f) + \",\" + b.str(digits, f) + \")\";\n   }\n   ~mpc_complex_imp() BOOST_NOEXCEPT\n   {\n      if(m_data[0].re[0]._mpfr_d)\n         mpc_clear(m_data);\n   }\n   void negate() BOOST_NOEXCEPT\n   {\n      BOOST_ASSERT(m_data[0].re[0]._mpfr_d);\n      mpc_neg(m_data, m_data, GMP_RNDD);\n   }\n   int compare(const mpc_complex_imp& o)const BOOST_NOEXCEPT\n   {\n      BOOST_ASSERT(m_data[0].re[0]._mpfr_d && o.m_data[0].re[0]._mpfr_d);\n      return mpc_cmp(m_data, o.m_data);\n   }\n   int compare(const mpc_complex_backend<digits10>& o)const BOOST_NOEXCEPT\n   {\n      BOOST_ASSERT(m_data[0].re[0]._mpfr_d && o.m_data[0].re[0]._mpfr_d);\n      return mpc_cmp(m_data, o.data());\n   }\n   int compare(long int i)const BOOST_NOEXCEPT\n   {\n      BOOST_ASSERT(m_data[0].re[0]._mpfr_d);\n      return mpc_cmp_si(m_data, i);\n   }\n   int compare(unsigned long int i)const BOOST_NOEXCEPT\n   {\n      BOOST_ASSERT(m_data[0].re[0]._mpfr_d);\n      static const unsigned long int max_val = (std::numeric_limits<long>::max)();\n      if (i > max_val)\n      {\n         mpc_complex_imp d(mpc_get_prec(m_data));\n         d = i;\n         return compare(d);\n      }\n      return mpc_cmp_si(m_data, (long)i);\n   }\n   template <class V>\n   int compare(const V& v)const BOOST_NOEXCEPT\n   {\n      mpc_complex_imp d(mpc_get_prec(m_data));\n      d = v;\n      return compare(d);\n   }\n   mpc_t& data() BOOST_NOEXCEPT\n   {\n      BOOST_ASSERT(m_data[0].re[0]._mpfr_d);\n      return m_data;\n   }\n   const mpc_t& data()const BOOST_NOEXCEPT\n   {\n      BOOST_ASSERT(m_data[0].re[0]._mpfr_d);\n      return m_data;\n   }\nprotected:\n   mpc_t m_data;\n   static unsigned& get_default_precision() BOOST_NOEXCEPT\n   {\n      static unsigned val = BOOST_MULTIPRECISION_MPFI_DEFAULT_PRECISION;\n      return val;\n   }\n};\n\n} // namespace detail\n\ntemplate <unsigned digits10>\nstruct mpc_complex_backend : public detail::mpc_complex_imp<digits10>\n{\n   mpc_complex_backend() : detail::mpc_complex_imp<digits10>() {}\n   mpc_complex_backend(const mpc_complex_backend& o) : detail::mpc_complex_imp<digits10>(o) {}\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\n   mpc_complex_backend(mpc_complex_backend&& o) : detail::mpc_complex_imp<digits10>(static_cast<detail::mpc_complex_imp<digits10>&&>(o)) {}\n#endif\n   template <unsigned D>\n   mpc_complex_backend(const mpc_complex_backend<D>& val, typename enable_if_c<D <= digits10>::type* = 0)\n       : detail::mpc_complex_imp<digits10>()\n   {\n      mpc_set(this->m_data, val.data(), GMP_RNDN);\n   }\n   template <unsigned D>\n   explicit mpc_complex_backend(const mpc_complex_backend<D>& val, typename disable_if_c<D <= digits10>::type* = 0)\n       : detail::mpc_complex_imp<digits10>()\n   {\n      mpc_set(this->m_data, val.data(), GMP_RNDN);\n   }\n   template <unsigned D>\n   mpc_complex_backend(const mpfr_float_backend<D>& val, typename enable_if_c<D <= digits10>::type* = 0)\n       : detail::mpc_complex_imp<digits10>()\n   {\n      mpc_set_fr(this->m_data, val.data(), GMP_RNDN);\n   }\n   template <unsigned D>\n   explicit mpc_complex_backend(const mpfr_float_backend<D>& val, typename disable_if_c<D <= digits10>::type* = 0)\n       : detail::mpc_complex_imp<digits10>()\n   {\n      mpc_set(this->m_data, val.data(), GMP_RNDN);\n   }\n   mpc_complex_backend(const mpc_t val)\n       : detail::mpc_complex_imp<digits10>()\n   {\n      mpc_set(this->m_data, val, GMP_RNDN);\n   }\n   mpc_complex_backend(const std::complex<float>& val)\n       : detail::mpc_complex_imp<digits10>()\n   {\n      mpc_set_d_d(this->m_data, val.real(), val.imag(), GMP_RNDN);\n   }\n   mpc_complex_backend(const std::complex<double>& val)\n       : detail::mpc_complex_imp<digits10>()\n   {\n      mpc_set_d_d(this->m_data, val.real(), val.imag(), GMP_RNDN);\n   }\n   mpc_complex_backend(const std::complex<long double>& val)\n       : detail::mpc_complex_imp<digits10>()\n   {\n      mpc_set_ld_ld(this->m_data, val.real(), val.imag(), GMP_RNDN);\n   }\n   mpc_complex_backend(mpz_srcptr val) : detail::mpc_complex_imp<digits10>()\n   {\n      mpc_set_z(this->m_data, val, GMP_RNDN);\n   }\n   mpc_complex_backend& operator=(mpz_srcptr val)\n   {\n      mpc_set_z(this->m_data, val, GMP_RNDN);\n      return *this;\n   }\n   mpc_complex_backend(gmp_int const& val) : detail::mpc_complex_imp<digits10>()\n   {\n      mpc_set_z(this->m_data, val.data(), GMP_RNDN);\n   }\n   mpc_complex_backend& operator=(gmp_int const& val)\n   {\n      mpc_set_z(this->m_data, val.data(), GMP_RNDN);\n      return *this;\n   }\n   mpc_complex_backend(mpf_srcptr val) : detail::mpc_complex_imp<digits10>()\n   {\n      mpc_set_f(this->m_data, val, GMP_RNDN);\n   }\n   mpc_complex_backend& operator=(mpf_srcptr val)\n   {\n      mpc_set_f(this->m_data, val, GMP_RNDN);\n      return *this;\n   }\n   template <unsigned D10>\n   mpc_complex_backend(gmp_float<D10> const& val) : detail::mpc_complex_imp<digits10>()\n   {\n      mpc_set_f(this->m_data, val.data(), GMP_RNDN);\n   }\n   template <unsigned D10>\n   mpc_complex_backend& operator=(gmp_float<D10> const& val)\n   {\n      mpc_set_f(this->m_data, val.data(), GMP_RNDN);\n      return *this;\n   }\n   mpc_complex_backend(mpq_srcptr val) : detail::mpc_complex_imp<digits10>()\n   {\n      mpc_set_q(this->m_data, val, GMP_RNDN);\n   }\n   mpc_complex_backend& operator=(mpq_srcptr val)\n   {\n      mpc_set_q(this->m_data, val, GMP_RNDN);\n      return *this;\n   }\n   mpc_complex_backend(gmp_rational const& val) : detail::mpc_complex_imp<digits10>()\n   {\n      mpc_set_q(this->m_data, val.data(), GMP_RNDN);\n   }\n   mpc_complex_backend& operator=(gmp_rational const& val)\n   {\n      mpc_set_q(this->m_data, val.data(), GMP_RNDN);\n      return *this;\n   }\n   mpc_complex_backend(mpfr_srcptr val) : detail::mpc_complex_imp<digits10>()\n   {\n      mpc_set_fr(this->m_data, val, GMP_RNDN);\n   }\n   mpc_complex_backend& operator=(mpfr_srcptr val)\n   {\n      mpc_set_fr(this->m_data, val, GMP_RNDN);\n      return *this;\n   }\n   template <unsigned D10, mpfr_allocation_type AllocationType>\n   mpc_complex_backend(mpfr_float_backend<D10, AllocationType> const& val) : detail::mpc_complex_imp<digits10>()\n   {\n      mpc_set_fr(this->m_data, val.data(), GMP_RNDN);\n   }\n   template <unsigned D10, mpfr_allocation_type AllocationType>\n   mpc_complex_backend& operator=(mpfr_float_backend<D10, AllocationType> const& val)\n   {\n      mpc_set_fr(this->m_data, val.data(), GMP_RNDN);\n      return *this;\n   }\n   mpc_complex_backend& operator=(const mpc_complex_backend& o)\n   {\n      *static_cast<detail::mpc_complex_imp<digits10>*>(this) = static_cast<detail::mpc_complex_imp<digits10> const&>(o);\n      return *this;\n   }\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\n   mpc_complex_backend& operator=(mpc_complex_backend&& o) BOOST_NOEXCEPT\n   {\n      *static_cast<detail::mpc_complex_imp<digits10>*>(this) = static_cast<detail::mpc_complex_imp<digits10>&&>(o);\n      return *this;\n   }\n#endif\n   template <class V>\n   mpc_complex_backend& operator=(const V& v)\n   {\n      *static_cast<detail::mpc_complex_imp<digits10>*>(this) = v;\n      return *this;\n   }\n   mpc_complex_backend& operator=(const mpc_t val)\n   {\n      mpc_set(this->m_data, val, GMP_RNDN);\n      return *this;\n   }\n   mpc_complex_backend& operator=(const std::complex<float>& val)\n   {\n      mpc_set_d_d(this->m_data, val.real(), val.imag(), GMP_RNDN);\n      return *this;\n   }\n   mpc_complex_backend& operator=(const std::complex<double>& val)\n   {\n      mpc_set_d_d(this->m_data, val.real(), val.imag(), GMP_RNDN);\n      return *this;\n   }\n   mpc_complex_backend& operator=(const std::complex<long double>& val)\n   {\n      mpc_set_ld_ld(this->m_data, val.real(), val.imag(), GMP_RNDN);\n      return *this;\n   }\n   // We don't change our precision here, this is a fixed precision type:\n   template <unsigned D>\n   mpc_complex_backend& operator=(const mpc_complex_backend<D>& val)\n   {\n      mpc_set(this->m_data, val.data(), GMP_RNDN);\n      return *this;\n   }\n};\n\ntemplate <>\nstruct mpc_complex_backend<0> : public detail::mpc_complex_imp<0>\n{\n   mpc_complex_backend() : detail::mpc_complex_imp<0>() {}\n   mpc_complex_backend(const mpc_t val)\n      : detail::mpc_complex_imp<0>(mpc_get_prec(val))\n   {\n      mpc_set(this->m_data, val, GMP_RNDN);\n   }\n   mpc_complex_backend(const mpc_complex_backend& o) : detail::mpc_complex_imp<0>(o) {}\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\n   mpc_complex_backend(mpc_complex_backend&& o) BOOST_NOEXCEPT : detail::mpc_complex_imp<0>(static_cast<detail::mpc_complex_imp<0>&&>(o)) {}\n#endif\n   mpc_complex_backend(const mpc_complex_backend& o, unsigned digits10)\n      : detail::mpc_complex_imp<0>(multiprecision::detail::digits10_2_2(digits10))\n   {\n      mpc_set(this->m_data, o.data(), GMP_RNDN);\n   }\n   template <unsigned D>\n   mpc_complex_backend(const mpc_complex_backend<D>& val)\n      : detail::mpc_complex_imp<0>(mpc_get_prec(val.data()))\n   {\n      mpc_set(this->m_data, val.data(), GMP_RNDN);\n   }\n   template <unsigned D>\n   mpc_complex_backend(const mpfr_float_backend<D>& val)\n      : detail::mpc_complex_imp<0>(mpfr_get_prec(val.data()))\n   {\n      mpc_set_fr(this->m_data, val.data(), GMP_RNDN);\n   }\n   mpc_complex_backend(mpz_srcptr val) : detail::mpc_complex_imp<0>()\n   {\n      mpc_set_z(this->m_data, val, GMP_RNDN);\n   }\n   mpc_complex_backend& operator=(mpz_srcptr val)\n   {\n      mpc_set_z(this->m_data, val, GMP_RNDN);\n      return *this;\n   }\n   mpc_complex_backend(gmp_int const& val) : detail::mpc_complex_imp<0>() \n   {\n      mpc_set_z(this->m_data, val.data(), GMP_RNDN);\n   }\n   mpc_complex_backend& operator=(gmp_int const& val)\n   {\n      mpc_set_z(this->m_data, val.data(), GMP_RNDN);\n      return *this;\n   }\n   mpc_complex_backend(mpf_srcptr val) : detail::mpc_complex_imp<0>((unsigned)mpf_get_prec(val))\n   {\n      mpc_set_f(this->m_data, val, GMP_RNDN);\n   }\n   mpc_complex_backend& operator=(mpf_srcptr val)\n   {\n      if ((mp_bitcnt_t)mpc_get_prec(data()) != mpf_get_prec(val))\n      {\n         mpc_complex_backend t(val);\n         t.swap(*this);\n      }\n      else\n         mpc_set_f(this->m_data, val, GMP_RNDN);\n      return *this;\n   }\n   template <unsigned digits10>\n   mpc_complex_backend(gmp_float<digits10> const& val) : detail::mpc_complex_imp<0>((unsigned)mpf_get_prec(val.data()))\n   {\n      mpc_set_f(this->m_data, val.data(), GMP_RNDN);\n   }\n   template <unsigned digits10>\n   mpc_complex_backend& operator=(gmp_float<digits10> const& val)\n   {\n      if (mpc_get_prec(data()) != mpf_get_prec(val.data()))\n      {\n         mpc_complex_backend t(val);\n         t.swap(*this);\n      }\n      else\n         mpc_set_f(this->m_data, val.data(), GMP_RNDN);\n      return *this;\n   }\n   mpc_complex_backend(mpq_srcptr val) : detail::mpc_complex_imp<0>()\n   {\n      mpc_set_q(this->m_data, val, GMP_RNDN);\n   }\n   mpc_complex_backend& operator=(mpq_srcptr val)\n   {\n      mpc_set_q(this->m_data, val, GMP_RNDN);\n      return *this;\n   }\n   mpc_complex_backend(gmp_rational const& val) : detail::mpc_complex_imp<0>()\n   {\n      mpc_set_q(this->m_data, val.data(), GMP_RNDN);\n   }\n   mpc_complex_backend& operator=(gmp_rational const& val)\n   {\n      mpc_set_q(this->m_data, val.data(), GMP_RNDN);\n      return *this;\n   }\n   mpc_complex_backend(mpfr_srcptr val) : detail::mpc_complex_imp<0>(mpfr_get_prec(val))\n   {\n      mpc_set_fr(this->m_data, val, GMP_RNDN);\n   }\n   mpc_complex_backend& operator=(mpfr_srcptr val)\n   {\n      if (mpc_get_prec(data()) != mpfr_get_prec(val))\n      {\n         mpc_complex_backend t(val);\n         t.swap(*this);\n      }\n      else\n         mpc_set_fr(this->m_data, val, GMP_RNDN);\n      return *this;\n   }\n   mpc_complex_backend(const std::complex<float>& val)\n      : detail::mpc_complex_imp<0>()\n   {\n      mpc_set_d_d(this->m_data, val.real(), val.imag(), GMP_RNDN);\n   }\n   mpc_complex_backend(const std::complex<double>& val)\n      : detail::mpc_complex_imp<0>()\n   {\n      mpc_set_d_d(this->m_data, val.real(), val.imag(), GMP_RNDN);\n   }\n   mpc_complex_backend(const std::complex<long double>& val)\n      : detail::mpc_complex_imp<0>()\n   {\n      mpc_set_ld_ld(this->m_data, val.real(), val.imag(), GMP_RNDN);\n   }\n   // Construction with precision:\n   template <class T, class U>\n   mpc_complex_backend(const T& a, const U& b, unsigned digits10)\n      : detail::mpc_complex_imp<0>(multiprecision::detail::digits10_2_2(digits10))\n   {\n      // We can't use assign_components here because it copies the precision of\n      // a and b, not digits10....\n      mpfr_float ca(a), cb(b);\n      mpc_set_fr_fr(this->data(), ca.backend().data(), cb.backend().data(), GMP_RNDN);\n   }\n   template <unsigned N>\n   mpc_complex_backend(const mpfr_float_backend<N>& a, const mpfr_float_backend<N>& b, unsigned digits10)\n      : detail::mpc_complex_imp<0>(multiprecision::detail::digits10_2_2(digits10))\n   {\n      mpc_set_fr_fr(this->data(), a.data(), b.data(), GMP_RNDN);\n   }\n\n   mpc_complex_backend& operator=(const mpc_complex_backend& o)\n   {\n      if (this != &o)\n      {\n         detail::mpc_copy_precision(this->m_data, o.data());\n         mpc_set(this->m_data, o.data(), GMP_RNDN);\n      }\n      return *this;\n   }\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\n   mpc_complex_backend& operator=(mpc_complex_backend&& o) BOOST_NOEXCEPT\n   {\n      *static_cast<detail::mpc_complex_imp<0>*>(this) = static_cast<detail::mpc_complex_imp<0> &&>(o);\n      return *this;\n   }\n#endif\n   template <class V>\n   mpc_complex_backend& operator=(const V& v)\n   {\n      *static_cast<detail::mpc_complex_imp<0>*>(this) = v;\n      return *this;\n   }\n   mpc_complex_backend& operator=(const mpc_t val)\n   {\n      mpc_set_prec(this->m_data, mpc_get_prec(val));\n      mpc_set(this->m_data, val, GMP_RNDN);\n      return *this;\n   }\n   template <unsigned D>\n   mpc_complex_backend& operator=(const mpc_complex_backend<D>& val)\n   {\n      mpc_set_prec(this->m_data, mpc_get_prec(val.data()));\n      mpc_set(this->m_data, val.data(), GMP_RNDN);\n      return *this;\n   }\n   template <unsigned D>\n   mpc_complex_backend& operator=(const mpfr_float_backend<D>& val)\n   {\n      mpc_set_prec(this->m_data, mpfr_get_prec(val.data()));\n      mpc_set_fr(this->m_data, val.data(), GMP_RNDN);\n      return *this;\n   }\n   mpc_complex_backend& operator=(const std::complex<float>& val)\n   {\n      mpc_set_d_d(this->m_data, val.real(), val.imag(), GMP_RNDN);\n      return *this;\n   }\n   mpc_complex_backend& operator=(const std::complex<double>& val)\n   {\n      mpc_set_d_d(this->m_data, val.real(), val.imag(), GMP_RNDN);\n      return *this;\n   }\n   mpc_complex_backend& operator=(const std::complex<long double>& val)\n   {\n      mpc_set_ld_ld(this->m_data, val.real(), val.imag(), GMP_RNDN);\n      return *this;\n   }\n   static unsigned default_precision() BOOST_NOEXCEPT\n   {\n      return get_default_precision();\n   }\n   static void default_precision(unsigned v) BOOST_NOEXCEPT\n   {\n      get_default_precision() = v;\n   }\n   unsigned precision()const BOOST_NOEXCEPT\n   {\n      return multiprecision::detail::digits2_2_10(mpc_get_prec(this->m_data));\n   }\n   void precision(unsigned digits10) BOOST_NOEXCEPT\n   {\n      mpfr_prec_round(mpc_realref(this->m_data), multiprecision::detail::digits10_2_2((digits10)), GMP_RNDN);\n      mpfr_prec_round(mpc_imagref(this->m_data), multiprecision::detail::digits10_2_2((digits10)), GMP_RNDN);\n   }\n};\n\ntemplate <unsigned digits10, class T>\ninline typename enable_if<is_arithmetic<T>, bool>::type eval_eq(const mpc_complex_backend<digits10>& a, const T& b) BOOST_NOEXCEPT\n{\n   return a.compare(b) == 0;\n}\ntemplate <unsigned digits10, class T>\ninline typename enable_if<is_arithmetic<T>, bool>::type eval_lt(const mpc_complex_backend<digits10>& a, const T& b) BOOST_NOEXCEPT\n{\n   return a.compare(b) < 0;\n}\ntemplate <unsigned digits10, class T>\ninline typename enable_if<is_arithmetic<T>, bool>::type eval_gt(const mpc_complex_backend<digits10>& a, const T& b) BOOST_NOEXCEPT\n{\n   return a.compare(b) > 0;\n}\n\ntemplate <unsigned D1, unsigned D2>\ninline void eval_add(mpc_complex_backend<D1>& result, const mpc_complex_backend<D2>& o)\n{\n   mpc_add(result.data(), result.data(), o.data(), GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_add(mpc_complex_backend<D1>& result, const mpfr_float_backend<D2>& o)\n{\n   mpc_add_fr(result.data(), result.data(), o.data(), GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_subtract(mpc_complex_backend<D1>& result, const mpc_complex_backend<D2>& o)\n{\n   mpc_sub(result.data(), result.data(), o.data(), GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_subtract(mpc_complex_backend<D1>& result, const mpfr_float_backend<D2>& o)\n{\n   mpc_sub_fr(result.data(), result.data(), o.data(), GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_multiply(mpc_complex_backend<D1>& result, const mpc_complex_backend<D2>& o)\n{\n   if((void*)&result == (void*)&o)\n      mpc_sqr(result.data(), o.data(), GMP_RNDN);\n   else\n      mpc_mul(result.data(), result.data(), o.data(), GMP_RNDN);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_multiply(mpc_complex_backend<D1>& result, const mpfr_float_backend<D2>& o)\n{\n   mpc_mul_fr(result.data(), result.data(), o.data(), GMP_RNDN);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_divide(mpc_complex_backend<D1>& result, const mpc_complex_backend<D2>& o)\n{\n   mpc_div(result.data(), result.data(), o.data(), GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_divide(mpc_complex_backend<D1>& result, const mpfr_float_backend<D2>& o)\n{\n   mpc_div_fr(result.data(), result.data(), o.data(), GMP_RNDD);\n}\ntemplate <unsigned digits10>\ninline void eval_add(mpc_complex_backend<digits10>& result, unsigned long i)\n{\n   mpc_add_ui(result.data(), result.data(), i, GMP_RNDN);\n}\ntemplate <unsigned digits10>\ninline void eval_subtract(mpc_complex_backend<digits10>& result, unsigned long i)\n{\n   mpc_sub_ui(result.data(), result.data(), i, GMP_RNDN);\n}\ntemplate <unsigned digits10>\ninline void eval_multiply(mpc_complex_backend<digits10>& result, unsigned long i)\n{\n   mpc_mul_ui(result.data(), result.data(), i, GMP_RNDN);\n}\ntemplate <unsigned digits10>\ninline void eval_divide(mpc_complex_backend<digits10>& result, unsigned long i)\n{\n   mpc_div_ui(result.data(), result.data(), i, GMP_RNDN);\n}\ntemplate <unsigned digits10>\ninline void eval_add(mpc_complex_backend<digits10>& result, long i)\n{\n   if(i > 0)\n      mpc_add_ui(result.data(), result.data(), i, GMP_RNDN);\n   else\n      mpc_sub_ui(result.data(), result.data(), boost::multiprecision::detail::unsigned_abs(i), GMP_RNDN);\n}\ntemplate <unsigned digits10>\ninline void eval_subtract(mpc_complex_backend<digits10>& result, long i)\n{\n   if(i > 0)\n      mpc_sub_ui(result.data(), result.data(), i, GMP_RNDN);\n   else\n      mpc_add_ui(result.data(), result.data(), boost::multiprecision::detail::unsigned_abs(i), GMP_RNDN);\n}\ntemplate <unsigned digits10>\ninline void eval_multiply(mpc_complex_backend<digits10>& result, long i)\n{\n   mpc_mul_ui(result.data(), result.data(), boost::multiprecision::detail::unsigned_abs(i), GMP_RNDN);\n   if(i < 0)\n      mpc_neg(result.data(), result.data(), GMP_RNDN);\n}\ntemplate <unsigned digits10>\ninline void eval_divide(mpc_complex_backend<digits10>& result, long i)\n{\n   mpc_div_ui(result.data(), result.data(), boost::multiprecision::detail::unsigned_abs(i), GMP_RNDN);\n   if(i < 0)\n      mpc_neg(result.data(), result.data(), GMP_RNDN);\n}\n//\n// Specialised 3 arg versions of the basic operators:\n//\ntemplate <unsigned D1, unsigned D2, unsigned D3>\ninline void eval_add(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, const mpc_complex_backend<D3>& y)\n{\n   mpc_add(a.data(), x.data(), y.data(), GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2, unsigned D3>\ninline void eval_add(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, const mpfr_float_backend<D3>& y)\n{\n   mpc_add_fr(a.data(), x.data(), y.data(), GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2, unsigned D3>\ninline void eval_add(mpc_complex_backend<D1>& a, const mpfr_float_backend<D2>& x, const mpc_complex_backend<D3>& y)\n{\n   mpc_add_fr(a.data(), y.data(), x.data(), GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_add(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, unsigned long y)\n{\n   mpc_add_ui(a.data(), x.data(), y, GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_add(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, long y)\n{\n   if(y < 0)\n      mpc_sub_ui(a.data(), x.data(), boost::multiprecision::detail::unsigned_abs(y), GMP_RNDD);\n   else\n      mpc_add_ui(a.data(), x.data(), y, GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_add(mpc_complex_backend<D1>& a, unsigned long x, const mpc_complex_backend<D2>& y)\n{\n   mpc_add_ui(a.data(), y.data(), x, GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_add(mpc_complex_backend<D1>& a, long x, const mpc_complex_backend<D2>& y)\n{\n   if(x < 0)\n   {\n      mpc_ui_sub(a.data(), boost::multiprecision::detail::unsigned_abs(x), y.data(), GMP_RNDN);\n      mpc_neg(a.data(), a.data(), GMP_RNDD);\n   }\n   else\n      mpc_add_ui(a.data(), y.data(), x, GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2, unsigned D3>\ninline void eval_subtract(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, const mpc_complex_backend<D3>& y)\n{\n   mpc_sub(a.data(), x.data(), y.data(), GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2, unsigned D3>\ninline void eval_subtract(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, const mpfr_float_backend<D3>& y)\n{\n   mpc_sub_fr(a.data(), x.data(), y.data(), GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2, unsigned D3>\ninline void eval_subtract(mpc_complex_backend<D1>& a, const mpfr_float_backend<D2>& x, const mpc_complex_backend<D3>& y)\n{\n   mpc_fr_sub(a.data(), x.data(), y.data(), GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_subtract(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, unsigned long y)\n{\n   mpc_sub_ui(a.data(), x.data(), y, GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_subtract(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, long y)\n{\n   if(y < 0)\n      mpc_add_ui(a.data(), x.data(), boost::multiprecision::detail::unsigned_abs(y), GMP_RNDD);\n   else\n      mpc_sub_ui(a.data(), x.data(), y, GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_subtract(mpc_complex_backend<D1>& a, unsigned long x, const mpc_complex_backend<D2>& y)\n{\n   mpc_ui_sub(a.data(), x, y.data(), GMP_RNDN);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_subtract(mpc_complex_backend<D1>& a, long x, const mpc_complex_backend<D2>& y)\n{\n   if(x < 0)\n   {\n      mpc_add_ui(a.data(), y.data(), boost::multiprecision::detail::unsigned_abs(x), GMP_RNDD);\n      mpc_neg(a.data(), a.data(), GMP_RNDD);\n   }\n   else\n      mpc_ui_sub(a.data(), x, y.data(), GMP_RNDN);\n}\n\ntemplate <unsigned D1, unsigned D2, unsigned D3>\ninline void eval_multiply(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, const mpc_complex_backend<D3>& y)\n{\n   if((void*)&x == (void*)&y)\n      mpc_sqr(a.data(), x.data(), GMP_RNDD);\n   else\n      mpc_mul(a.data(), x.data(), y.data(), GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2, unsigned D3>\ninline void eval_multiply(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, const mpfr_float_backend<D3>& y)\n{\n   mpc_mul_fr(a.data(), x.data(), y.data(), GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2, unsigned D3>\ninline void eval_multiply(mpc_complex_backend<D1>& a, const mpfr_float_backend<D2>& x, const mpc_complex_backend<D3>& y)\n{\n   mpc_mul_fr(a.data(), y.data(), x.data(), GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_multiply(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, unsigned long y)\n{\n   mpc_mul_ui(a.data(), x.data(), y, GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_multiply(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, long y)\n{\n   if(y < 0)\n   {\n      mpc_mul_ui(a.data(), x.data(), boost::multiprecision::detail::unsigned_abs(y), GMP_RNDD);\n      a.negate();\n   }\n   else\n      mpc_mul_ui(a.data(), x.data(), y, GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_multiply(mpc_complex_backend<D1>& a, unsigned long x, const mpc_complex_backend<D2>& y)\n{\n   mpc_mul_ui(a.data(), y.data(), x, GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_multiply(mpc_complex_backend<D1>& a, long x, const mpc_complex_backend<D2>& y)\n{\n   if(x < 0)\n   {\n      mpc_mul_ui(a.data(), y.data(), boost::multiprecision::detail::unsigned_abs(x), GMP_RNDD);\n      mpc_neg(a.data(), a.data(), GMP_RNDD);\n   }\n   else\n      mpc_mul_ui(a.data(), y.data(), x, GMP_RNDD);\n}\n\ntemplate <unsigned D1, unsigned D2, unsigned D3>\ninline void eval_divide(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, const mpc_complex_backend<D3>& y)\n{\n   mpc_div(a.data(), x.data(), y.data(), GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2, unsigned D3>\ninline void eval_divide(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, const mpfr_float_backend<D3>& y)\n{\n   mpc_div_fr(a.data(), x.data(), y.data(), GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2, unsigned D3>\ninline void eval_divide(mpc_complex_backend<D1>& a, const mpfr_float_backend<D2>& x, const mpc_complex_backend<D3>& y)\n{\n   mpc_fr_div(a.data(), x.data(), y.data(), GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_divide(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, unsigned long y)\n{\n   mpc_div_ui(a.data(), x.data(), y, GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_divide(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, long y)\n{\n   if(y < 0)\n   {\n      mpc_div_ui(a.data(), x.data(), boost::multiprecision::detail::unsigned_abs(y), GMP_RNDD);\n      a.negate();\n   }\n   else\n      mpc_div_ui(a.data(), x.data(), y, GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_divide(mpc_complex_backend<D1>& a, unsigned long x, const mpc_complex_backend<D2>& y)\n{\n   mpc_ui_div(a.data(), x, y.data(), GMP_RNDD);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_divide(mpc_complex_backend<D1>& a, long x, const mpc_complex_backend<D2>& y)\n{\n   if(x < 0)\n   {\n      mpc_ui_div(a.data(), boost::multiprecision::detail::unsigned_abs(x), y.data(), GMP_RNDD);\n      mpc_neg(a.data(), a.data(), GMP_RNDD);\n   }\n   else\n      mpc_ui_div(a.data(), x, y.data(), GMP_RNDD);\n}\n\ntemplate <unsigned digits10>\ninline bool eval_is_zero(const mpc_complex_backend<digits10>& val) BOOST_NOEXCEPT\n{\n   return (0 != mpfr_zero_p(mpc_realref(val.data()))) && (0 != mpfr_zero_p(mpc_imagref(val.data())));\n}\ntemplate <unsigned digits10>\ninline int eval_get_sign(const mpc_complex_backend<digits10>&)\n{\n   BOOST_STATIC_ASSERT_MSG(digits10 == UINT_MAX, \"Complex numbers have no sign bit.\"); // designed to always fail\n   return 0;\n}\n\ntemplate <unsigned digits10>\ninline void eval_convert_to(unsigned long* result, const mpc_complex_backend<digits10>& val)\n{\n   if (0 == mpfr_zero_p(mpc_imagref(val.data())))\n   {\n      BOOST_THROW_EXCEPTION(std::runtime_error(\"Could not convert imaginary number to scalar.\"));\n   }\n   mpfr_float_backend<digits10> t;\n   mpc_real(t.data(), val.data(), GMP_RNDN);\n   eval_convert_to(result, t);\n}\ntemplate <unsigned digits10>\ninline void eval_convert_to(long* result, const mpc_complex_backend<digits10>& val)\n{\n   if (0 == mpfr_zero_p(mpc_imagref(val.data())))\n   {\n      BOOST_THROW_EXCEPTION(std::runtime_error(\"Could not convert imaginary number to scalar.\"));\n   }\n   mpfr_float_backend<digits10> t;\n   mpc_real(t.data(), val.data(), GMP_RNDN);\n   eval_convert_to(result, t);\n}\n#ifdef _MPFR_H_HAVE_INTMAX_T\ntemplate <unsigned digits10>\ninline void eval_convert_to(boost::ulong_long_type* result, const mpc_complex_backend<digits10>& val)\n{\n   if (0 == mpfr_zero_p(mpc_imagref(val.data())))\n   {\n      BOOST_THROW_EXCEPTION(std::runtime_error(\"Could not convert imaginary number to scalar.\"));\n   }\n   mpfr_float_backend<digits10> t;\n   mpc_real(t.data(), val.data(), GMP_RNDN);\n   eval_convert_to(result, t);\n}\ntemplate <unsigned digits10>\ninline void eval_convert_to(boost::long_long_type* result, const mpc_complex_backend<digits10>& val)\n{\n   if (0 == mpfr_zero_p(mpc_imagref(val.data())))\n   {\n      BOOST_THROW_EXCEPTION(std::runtime_error(\"Could not convert imaginary number to scalar.\"));\n   }\n   mpfr_float_backend<digits10> t;\n   mpc_real(t.data(), val.data(), GMP_RNDN);\n   eval_convert_to(result, t);\n}\n#endif\ntemplate <unsigned digits10>\ninline void eval_convert_to(double* result, const mpc_complex_backend<digits10>& val) BOOST_NOEXCEPT\n{\n   if (0 == mpfr_zero_p(mpc_imagref(val.data())))\n   {\n      BOOST_THROW_EXCEPTION(std::runtime_error(\"Could not convert imaginary number to scalar.\"));\n   }\n   mpfr_float_backend<digits10> t;\n   mpc_real(t.data(), val.data(), GMP_RNDN);\n   eval_convert_to(result, t);\n}\ntemplate <unsigned digits10>\ninline void eval_convert_to(long double* result, const mpc_complex_backend<digits10>& val) BOOST_NOEXCEPT\n{\n   if (0 == mpfr_zero_p(mpc_imagref(val.data())))\n   {\n      BOOST_THROW_EXCEPTION(std::runtime_error(\"Could not convert imaginary number to scalar.\"));\n   }\n   mpfr_float_backend<digits10> t;\n   mpc_real(t.data(), val.data(), GMP_RNDN);\n   eval_convert_to(result, t);\n}\n\ntemplate <unsigned D1, unsigned D2, mpfr_allocation_type AllocationType>\ninline void assign_components(mpc_complex_backend<D1>& result, const mpfr_float_backend<D2, AllocationType>& a, const mpfr_float_backend<D2, AllocationType>& b)\n{\n   //\n   // This is called from class number's constructors, so if we have variable\n   // precision, then copy the precision of the source variables.\n   //\n   if (!D1)\n   {\n      unsigned long prec = std::max(mpfr_get_prec(a.data()), mpfr_get_prec(b.data()));\n      mpc_set_prec(result.data(), prec);\n   }\n   using default_ops::eval_fpclassify;\n   if(eval_fpclassify(a) == (int)FP_NAN)\n   {\n      mpc_set_fr(result.data(), a.data(), GMP_RNDN);\n   }\n   else if(eval_fpclassify(b) == (int)FP_NAN)\n   {\n      mpc_set_fr(result.data(), b.data(), GMP_RNDN);\n   }\n   else\n   {\n      mpc_set_fr_fr(result.data(), a.data(), b.data(), GMP_RNDN);\n   }\n}\n\ntemplate <unsigned D1, unsigned D2, mpfr_allocation_type AllocationType>\ninline void assign_components(mpc_complex_backend<D1>& result, unsigned long a, unsigned long b)\n{\n   mpc_set_ui_ui(result.data(), a, b, GMP_RNDN);\n}\n\ntemplate <unsigned D1, unsigned D2, mpfr_allocation_type AllocationType>\ninline void assign_components(mpc_complex_backend<D1>& result, long a, long b)\n{\n   mpc_set_si_si(result.data(), a, b, GMP_RNDN);\n}\n\n#if defined(BOOST_HAS_LONG_LONG) && defined(_MPFR_H_HAVE_INTMAX_T)\ntemplate <unsigned D1, unsigned D2, mpfr_allocation_type AllocationType>\ninline void assign_components(mpc_complex_backend<D1>& result, unsigned long long a, unsigned long long b)\n{\n   mpc_set_uj_uj(result.data(), a, b, GMP_RNDN);\n}\n\ntemplate <unsigned D1, unsigned D2, mpfr_allocation_type AllocationType>\ninline void assign_components(mpc_complex_backend<D1>& result, long long a, long long b)\n{\n   mpc_set_sj_sj(result.data(), a, b, GMP_RNDN);\n}\n#endif\n\ntemplate <unsigned D1, unsigned D2, mpfr_allocation_type AllocationType>\ninline void assign_components(mpc_complex_backend<D1>& result, double a, double b)\n{\n   if ((boost::math::isnan)(a))\n   {\n      mpc_set_d(result.data(), a, GMP_RNDN);\n   }\n   else if ((boost::math::isnan)(b))\n   {\n      mpc_set_d(result.data(), b, GMP_RNDN);\n   }\n   else\n   {\n      mpc_set_d_d(result.data(), a, b, GMP_RNDN);\n   }\n}\n\ntemplate <unsigned D1, unsigned D2, mpfr_allocation_type AllocationType>\ninline void assign_components(mpc_complex_backend<D1>& result, long double a, long double b)\n{\n   if ((boost::math::isnan)(a))\n   {\n      mpc_set_d(result.data(), a, GMP_RNDN);\n   }\n   else if ((boost::math::isnan)(b))\n   {\n      mpc_set_d(result.data(), b, GMP_RNDN);\n   }\n   else\n   {\n      mpc_set_ld_ld(result.data(), a, b, GMP_RNDN);\n   }\n}\n\n//\n// Native non-member operations:\n//\ntemplate <unsigned Digits10>\ninline void eval_sqrt(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& val)\n{\n   mpc_sqrt(result.data(), val.data(), GMP_RNDN);\n}\n\ntemplate <unsigned Digits10>\ninline void eval_pow(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& b, const mpc_complex_backend<Digits10>& e)\n{\n   mpc_pow(result.data(), b.data(), e.data(), GMP_RNDN);\n}\n\ntemplate <unsigned Digits10>\ninline void eval_exp(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg)\n{\n   mpc_exp(result.data(), arg.data(), GMP_RNDN);\n}\n\ntemplate <unsigned Digits10>\ninline void eval_log(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg)\n{\n   mpc_log(result.data(), arg.data(), GMP_RNDN);\n}\n\ntemplate <unsigned Digits10>\ninline void eval_log10(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg)\n{\n   mpc_log10(result.data(), arg.data(), GMP_RNDN);\n}\n\ntemplate <unsigned Digits10>\ninline void eval_sin(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg)\n{\n   mpc_sin(result.data(), arg.data(), GMP_RNDN);\n}\n\ntemplate <unsigned Digits10>\ninline void eval_cos(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg)\n{\n   mpc_cos(result.data(), arg.data(), GMP_RNDN);\n}\n\ntemplate <unsigned Digits10>\ninline void eval_tan(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg)\n{\n   mpc_tan(result.data(), arg.data(), GMP_RNDN);\n}\n\ntemplate <unsigned Digits10>\ninline void eval_asin(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg)\n{\n   mpc_asin(result.data(), arg.data(), GMP_RNDN);\n}\n\ntemplate <unsigned Digits10>\ninline void eval_acos(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg)\n{\n   mpc_acos(result.data(), arg.data(), GMP_RNDN);\n}\n\ntemplate <unsigned Digits10>\ninline void eval_atan(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg)\n{\n   mpc_atan(result.data(), arg.data(), GMP_RNDN);\n}\n\ntemplate <unsigned Digits10>\ninline void eval_sinh(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg)\n{\n   mpc_sinh(result.data(), arg.data(), GMP_RNDN);\n}\n\ntemplate <unsigned Digits10>\ninline void eval_cosh(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg)\n{\n   mpc_cosh(result.data(), arg.data(), GMP_RNDN);\n}\n\ntemplate <unsigned Digits10>\ninline void eval_tanh(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg)\n{\n   mpc_tanh(result.data(), arg.data(), GMP_RNDN);\n}\n\ntemplate <unsigned Digits10>\ninline void eval_asinh(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg)\n{\n   mpc_asinh(result.data(), arg.data(), GMP_RNDN);\n}\n\ntemplate <unsigned Digits10>\ninline void eval_acosh(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg)\n{\n   mpc_acosh(result.data(), arg.data(), GMP_RNDN);\n}\n\ntemplate <unsigned Digits10>\ninline void eval_atanh(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg)\n{\n   mpc_atanh(result.data(), arg.data(), GMP_RNDN);\n}\n\ntemplate <unsigned Digits10>\ninline void eval_conj(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg)\n{\n   mpc_conj(result.data(), arg.data(), GMP_RNDN);\n}\n\ntemplate <unsigned Digits10>\ninline void eval_proj(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg)\n{\n   mpc_proj(result.data(), arg.data(), GMP_RNDN);\n}\n\ntemplate <unsigned Digits10>\ninline void eval_real(mpfr_float_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg)\n{\n   mpfr_set_prec(result.data(), mpfr_get_prec(mpc_realref(arg.data())));\n   mpfr_set(result.data(), mpc_realref(arg.data()), GMP_RNDN);\n}\ntemplate <unsigned Digits10>\ninline void eval_imag(mpfr_float_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg)\n{\n   mpfr_set_prec(result.data(), mpfr_get_prec(mpc_imagref(arg.data())));\n   mpfr_set(result.data(), mpc_imagref(arg.data()), GMP_RNDN);\n}\n\ntemplate <unsigned Digits10>\ninline void eval_set_imag(mpc_complex_backend<Digits10>& result, const mpfr_float_backend<Digits10>& arg)\n{\n   mpfr_set(mpc_imagref(result.data()), arg.data(), GMP_RNDN);\n}\n\ntemplate <unsigned Digits10>\ninline void eval_set_real(mpc_complex_backend<Digits10>& result, const mpfr_float_backend<Digits10>& arg)\n{\n   mpfr_set(mpc_realref(result.data()), arg.data(), GMP_RNDN);\n}\ntemplate <unsigned Digits10>\ninline void eval_set_real(mpc_complex_backend<Digits10>& result, const gmp_int& arg)\n{\n   mpfr_set_z(mpc_realref(result.data()), arg.data(), GMP_RNDN);\n}\ntemplate <unsigned Digits10>\ninline void eval_set_real(mpc_complex_backend<Digits10>& result, const gmp_rational& arg)\n{\n   mpfr_set_q(mpc_realref(result.data()), arg.data(), GMP_RNDN);\n}\ntemplate <unsigned Digits10>\ninline void eval_set_real(mpc_complex_backend<Digits10>& result, const unsigned& arg)\n{\n   mpfr_set_ui(mpc_realref(result.data()), arg, GMP_RNDN);\n}\ntemplate <unsigned Digits10>\ninline void eval_set_real(mpc_complex_backend<Digits10>& result, const unsigned long& arg)\n{\n   mpfr_set_ui(mpc_realref(result.data()), arg, GMP_RNDN);\n}\ntemplate <unsigned Digits10>\ninline void eval_set_real(mpc_complex_backend<Digits10>& result, const int& arg)\n{\n   mpfr_set_si(mpc_realref(result.data()), arg, GMP_RNDN);\n}\ntemplate <unsigned Digits10>\ninline void eval_set_real(mpc_complex_backend<Digits10>& result, const long& arg)\n{\n   mpfr_set_si(mpc_realref(result.data()), arg, GMP_RNDN);\n}\ntemplate <unsigned Digits10>\ninline void eval_set_real(mpc_complex_backend<Digits10>& result, const float& arg)\n{\n   mpfr_set_flt(mpc_realref(result.data()), arg, GMP_RNDN);\n}\ntemplate <unsigned Digits10>\ninline void eval_set_real(mpc_complex_backend<Digits10>& result, const double& arg)\n{\n   mpfr_set_d(mpc_realref(result.data()), arg, GMP_RNDN);\n}\ntemplate <unsigned Digits10>\ninline void eval_set_real(mpc_complex_backend<Digits10>& result, const long double& arg)\n{\n   mpfr_set_ld(mpc_realref(result.data()), arg, GMP_RNDN);\n}\n#if defined(BOOST_HAS_LONG_LONG) && defined(_MPFR_H_HAVE_INTMAX_T)\ntemplate <unsigned Digits10>\ninline void eval_set_real(mpc_complex_backend<Digits10>& result, const unsigned long long& arg)\n{\n   mpfr_set_uj(mpc_realref(result.data()), arg, GMP_RNDN);\n}\ntemplate <unsigned Digits10>\ninline void eval_set_real(mpc_complex_backend<Digits10>& result, const long long& arg)\n{\n   mpfr_set_sj(mpc_realref(result.data()), arg, GMP_RNDN);\n}\n#endif\n\ntemplate <unsigned Digits10>\ninline void eval_set_imag(mpc_complex_backend<Digits10>& result, const gmp_int& arg)\n{\n   mpfr_set_z(mpc_imagref(result.data()), arg.data(), GMP_RNDN);\n}\ntemplate <unsigned Digits10>\ninline void eval_set_imag(mpc_complex_backend<Digits10>& result, const gmp_rational& arg)\n{\n   mpfr_set_q(mpc_imagref(result.data()), arg.data(), GMP_RNDN);\n}\ntemplate <unsigned Digits10>\ninline void eval_set_imag(mpc_complex_backend<Digits10>& result, const unsigned& arg)\n{\n   mpfr_set_ui(mpc_imagref(result.data()), arg, GMP_RNDN);\n}\ntemplate <unsigned Digits10>\ninline void eval_set_imag(mpc_complex_backend<Digits10>& result, const unsigned long& arg)\n{\n   mpfr_set_ui(mpc_imagref(result.data()), arg, GMP_RNDN);\n}\ntemplate <unsigned Digits10>\ninline void eval_set_imag(mpc_complex_backend<Digits10>& result, const int& arg)\n{\n   mpfr_set_si(mpc_imagref(result.data()), arg, GMP_RNDN);\n}\ntemplate <unsigned Digits10>\ninline void eval_set_imag(mpc_complex_backend<Digits10>& result, const long& arg)\n{\n   mpfr_set_si(mpc_imagref(result.data()), arg, GMP_RNDN);\n}\ntemplate <unsigned Digits10>\ninline void eval_set_imag(mpc_complex_backend<Digits10>& result, const float& arg)\n{\n   mpfr_set_flt(mpc_imagref(result.data()), arg, GMP_RNDN);\n}\ntemplate <unsigned Digits10>\ninline void eval_set_imag(mpc_complex_backend<Digits10>& result, const double& arg)\n{\n   mpfr_set_d(mpc_imagref(result.data()), arg, GMP_RNDN);\n}\ntemplate <unsigned Digits10>\ninline void eval_set_imag(mpc_complex_backend<Digits10>& result, const long double& arg)\n{\n   mpfr_set_ld(mpc_imagref(result.data()), arg, GMP_RNDN);\n}\n#if defined(BOOST_HAS_LONG_LONG) && defined(_MPFR_H_HAVE_INTMAX_T)\ntemplate <unsigned Digits10>\ninline void eval_set_imag(mpc_complex_backend<Digits10>& result, const unsigned long long& arg)\n{\n   mpfr_set_uj(mpc_imagref(result.data()), arg, GMP_RNDN);\n}\ntemplate <unsigned Digits10>\ninline void eval_set_imag(mpc_complex_backend<Digits10>& result, const long long& arg)\n{\n   mpfr_set_sj(mpc_imagref(result.data()), arg, GMP_RNDN);\n}\n#endif\n\ntemplate <unsigned Digits10>\ninline std::size_t hash_value(const mpc_complex_backend<Digits10>& val)\n{\n   std::size_t result = 0;\n   std::size_t len = val.data()[0].re[0]._mpfr_prec / mp_bits_per_limb;\n   if(val.data()[0].re[0]._mpfr_prec % mp_bits_per_limb)\n      ++len;\n   for(std::size_t i = 0; i < len; ++i)\n      boost::hash_combine(result, val.data()[0].re[0]._mpfr_d[i]);\n   boost::hash_combine(result, val.data()[0].re[0]._mpfr_exp);\n   boost::hash_combine(result, val.data()[0].re[0]._mpfr_sign);\n\n   len = val.data()[0].im[0]._mpfr_prec / mp_bits_per_limb;\n   if(val.data()[0].im[0]._mpfr_prec % mp_bits_per_limb)\n      ++len;\n   for(std::size_t i = 0; i < len; ++i)\n      boost::hash_combine(result, val.data()[0].im[0]._mpfr_d[i]);\n   boost::hash_combine(result, val.data()[0].im[0]._mpfr_exp);\n   boost::hash_combine(result, val.data()[0].im[0]._mpfr_sign);\n   return result;\n}\n\n} // namespace backends\n\n#ifdef BOOST_NO_SFINAE_EXPR\n\nnamespace detail{\n\ntemplate<unsigned D1, unsigned D2>\nstruct is_explicitly_convertible<backends::mpc_complex_backend<D1>, backends::mpc_complex_backend<D2> > : public mpl::true_ {};\n\n}\n#endif\n\nnamespace detail\n{\n   template<>\n   struct is_variable_precision<backends::mpc_complex_backend<0> > : public true_type {};\n}\n\ntemplate<>\nstruct number_category<detail::canonical<mpc_t, backends::mpc_complex_backend<0> >::type> : public mpl::int_<number_kind_floating_point>{};\n\nusing boost::multiprecision::backends::mpc_complex_backend;\n\ntypedef number<mpc_complex_backend<50> >    mpc_complex_50;\ntypedef number<mpc_complex_backend<100> >   mpc_complex_100;\ntypedef number<mpc_complex_backend<500> >   mpc_complex_500;\ntypedef number<mpc_complex_backend<1000> >  mpc_complex_1000;\ntypedef number<mpc_complex_backend<0> >     mpc_complex;\n\ntemplate <unsigned Digits10, expression_template_option ExpressionTemplates>\nstruct component_type<number<mpc_complex_backend<Digits10>, ExpressionTemplates> >\n{\n   typedef number<mpfr_float_backend<Digits10>, ExpressionTemplates> type;\n};\n\ntemplate <unsigned Digits10, expression_template_option ExpressionTemplates>\nstruct component_type<number<logged_adaptor<mpc_complex_backend<Digits10> >, ExpressionTemplates> >\n{\n   typedef number<mpfr_float_backend<Digits10>, ExpressionTemplates> type;\n};\n\ntemplate <unsigned Digits10, expression_template_option ExpressionTemplates>\nstruct complex_result_from_scalar<number<mpfr_float_backend<Digits10>, ExpressionTemplates> >\n{\n   typedef number<mpc_complex_backend<Digits10>, ExpressionTemplates> type;\n};\n\n} // namespace multiprecision\n\n}  // namespaces\n\n#endif\n", "meta": {"hexsha": "100b56cf72010aa23e2b384ccde02e2c5db7b618", "size": 51093, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/boost/multiprecision/mpc.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/multiprecision/mpc.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/multiprecision/mpc.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": 33.5255905512, "max_line_length": 160, "alphanum_fraction": 0.6966120604, "num_tokens": 14738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.26670324212148805}}
{"text": "// This file is part of the dune-gdt project:\n//   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_HYPERBOLIC_PROBLEMS_MOMENTMODELS_BASISFUNCTIONS_BASE_HH\n#define DUNE_GDT_HYPERBOLIC_PROBLEMS_MOMENTMODELS_BASISFUNCTIONS_BASE_HH\n\n#include <memory>\n#include <vector>\n#include <string>\n\n#include <boost/math/special_functions/legendre.hpp>\n#include <boost/math/special_functions/spherical_harmonic.hpp>\n\n#include <dune/xt/common/math.hh>\n#include <dune/xt/common/string.hh>\n#include <dune/xt/common/tuple.hh>\n\n#include <dune/xt/functions/affine.hh>\n\n#include <dune/xt/grid/gridprovider/cube.hh>\n\n#include <dune/xt/la/container.hh>\n\n#include <dune/gdt/discretefunction/default.hh>\n#include <dune/gdt/operators/l2.hh>\n#include <dune/gdt/spaces/cg.hh>\n#include <dune/gdt/test/hyperbolic/problems/momentmodels/triangulation.hh>\n\nnamespace Dune {\nnamespace GDT {\nnamespace Hyperbolic {\nnamespace Problems {\n\n\n// take a DiscreteFunction and return a DiscreteFunction corresponding to component ii\ntemplate <size_t ii, class DiscreteFunctionType>\nauto get_factor_discrete_function(const DiscreteFunctionType& discrete_function) ->\n    typename Dune::GDT::DiscreteFunction<\n        typename XT::Common::tuple_element<ii, typename DiscreteFunctionType::SpaceType::SpaceTupleType>::type,\n        typename DiscreteFunctionType::VectorType>\n{\n  typedef typename Dune::GDT::DiscreteFunction<\n      typename XT::Common::tuple_element<ii, typename DiscreteFunctionType::SpaceType::SpaceTupleType>::type,\n      typename DiscreteFunctionType::VectorType>\n      FactorDiscreteFunctionType;\n  static_assert(ii < DiscreteFunctionType::SpaceType::num_factors, \"This factor does not exist.\");\n  const auto& space = discrete_function.space();\n  const auto& factor_space = space.template factor<ii>();\n  typename DiscreteFunctionType::VectorType factor_vector(factor_space.mapper().size());\n  const auto it_end = space.grid_layer().template end<0>();\n  for (auto it = space.grid_layer().template begin<0>(); it != it_end; ++it) {\n    const auto& entity = *it;\n    for (size_t jj = 0; jj < factor_space.mapper().numDofs(entity); ++jj)\n      factor_vector.set_entry(factor_space.mapper().mapToGlobal(entity, jj),\n                              discrete_function.vector().get_entry(space.mapper().mapToGlobal(ii, entity, jj)));\n  }\n  FactorDiscreteFunctionType factor_discrete_function(factor_space);\n  factor_discrete_function.vector() = factor_vector;\n  //  typedef Dune::GDT::DiscreteFunctionDataHandle<FactorDiscreteFunctionType> DataHandleType;\n  //  DataHandleType handle(factor_discrete_function);\n  //  factor_space.grid_layer().template communicate<DataHandleType>(\n  //      handle, Dune::InteriorBorder_All_Interface, Dune::ForwardCommunication);\n  return factor_discrete_function;\n}\n\n// static for loop to sum components of a DiscreteFunction\ntemplate <size_t index, size_t N>\nstruct static_discrete_function_loop\n{\n  template <class DiscreteFunctionType>\n  static typename DiscreteFunctionType::VectorType sum_vectors(const DiscreteFunctionType& discrete_function)\n  {\n    return static_discrete_function_loop<index, N / 2>::sum_vectors(discrete_function)\n           + static_discrete_function_loop<index + N / 2, N - N / 2>::sum_vectors(discrete_function);\n  }\n\n  template <class DiscreteFunctionType>\n  static typename DiscreteFunctionType::VectorType\n  sum_vectors_divisible_by(const DiscreteFunctionType& discrete_function, const size_t divisor)\n  {\n    return static_discrete_function_loop<index, N / 2>::sum_vectors_divisible_by(discrete_function, divisor)\n           + static_discrete_function_loop<index + N / 2, N - N / 2>::sum_vectors_divisible_by(discrete_function,\n                                                                                               divisor);\n  }\n};\n\n// specialization to end the loop\ntemplate <size_t index>\nstruct static_discrete_function_loop<index, 1>\n{\n  template <class DiscreteFunctionType>\n  static typename DiscreteFunctionType::VectorType sum_vectors(const DiscreteFunctionType& discrete_function)\n  {\n    return get_factor_discrete_function<index, DiscreteFunctionType>(discrete_function).vector();\n  }\n\n  template <class DiscreteFunctionType>\n  static typename DiscreteFunctionType::VectorType\n  sum_vectors_divisible_by(const DiscreteFunctionType& discrete_function, const size_t divisor)\n  {\n    if (!(index % divisor))\n      return get_factor_discrete_function<index, DiscreteFunctionType>(discrete_function).vector();\n    else\n      return typename DiscreteFunctionType::VectorType(\n          discrete_function.space().template factor<index>().mapper().size(), 0.);\n  }\n};\n\n// visualizes sum of components of discrete_function\ntemplate <class DiscreteFunctionType, size_t dimRange>\nvoid sum_visualizer(const DiscreteFunctionType& u_n, const std::string& filename_prefix, const size_t ii)\n{\n  auto sum_function = get_factor_discrete_function<0, DiscreteFunctionType>(u_n);\n  sum_function.vector() = static_discrete_function_loop<0, dimRange>::sum_vectors(u_n);\n  sum_function.visualize(filename_prefix + \"_\" + Dune::XT::Common::to_string(ii));\n}\n\n// visualizes sum of components with index divisible by divisor\ntemplate <class DiscreteFunctionType, size_t dimRange>\nvoid sum_divisible_by_visualizer(const DiscreteFunctionType& u_n,\n                                 const std::string& filename_prefix,\n                                 const size_t ii,\n                                 const size_t divisor)\n{\n  auto sum_function = get_factor_discrete_function<0, DiscreteFunctionType>(u_n);\n  sum_function.vector() = static_discrete_function_loop<0, dimRange>::sum_vectors_divisible_by(u_n, divisor);\n  sum_function.visualize(filename_prefix + \"_\" + Dune::XT::Common::to_string(ii));\n}\n\n// visualizes factor * component of discrete function\ntemplate <class DiscreteFunctionType, size_t dimRange, size_t component>\nvoid component_visualizer(const DiscreteFunctionType& u_n,\n                          const std::string& filename_prefix,\n                          const size_t ii,\n                          const double factor = 1.)\n{\n  auto u_n_comp = get_factor_discrete_function<component, DiscreteFunctionType>(u_n);\n  u_n_comp.vector() *= factor;\n  u_n_comp.visualize(filename_prefix + \"_\" + Dune::XT::Common::to_string(ii));\n}\n\n// see https://en.wikipedia.org/wiki/Tridiagonal_matrix#Inversion\ntemplate <class FieldType, int rows>\nDune::DynamicMatrix<FieldType> tridiagonal_matrix_inverse(const DynamicMatrix<FieldType>& matrix)\n{\n  typedef Dune::DynamicMatrix<FieldType> MatrixType;\n  size_t cols = rows;\n#ifndef NDEBUG\n  for (size_t rr = 0; rr < rows; ++rr)\n    for (size_t cc = 0; cc < cols; ++cc)\n      if ((cc > rr + 1 || cc + 1 < rr) && XT::Common::FloatCmp::ne(matrix[rr][cc], 0.))\n        DUNE_THROW(XT::Common::Exceptions::you_are_using_this_wrong, \"Matrix has to be tridiagonal!\");\n#endif // NDEBUG\n  MatrixType ret(rows, rows, 0);\n  Dune::FieldVector<FieldType, rows + 1> a(0), b(0), c(0), theta(0);\n  Dune::FieldVector<FieldType, rows + 2> phi(0);\n  for (size_t ii = 1; ii < rows + 1; ++ii) {\n    a[ii] = matrix[ii - 1][ii - 1];\n    if (ii < rows) {\n      b[ii] = matrix[ii - 1][ii];\n      c[ii] = matrix[ii][ii - 1];\n    }\n  }\n  theta[0] = 1;\n  theta[1] = a[1];\n  for (size_t ii = 2; ii < rows + 1; ++ii)\n    theta[ii] = a[ii] * theta[ii - 1] - b[ii - 1] * c[ii - 1] * theta[ii - 2];\n  phi[rows + 1] = 1;\n  phi[rows] = a[rows];\n  for (size_t ii = rows - 1; ii > 0; --ii)\n    phi[ii] = a[ii] * phi[ii + 1] - b[ii] * c[ii] * phi[ii + 2];\n  for (size_t ii = 1; ii < rows + 1; ++ii) {\n    for (size_t jj = 1; jj < cols + 1; ++jj) {\n      if (ii == jj)\n        ret[ii - 1][jj - 1] = theta[ii - 1] * phi[jj + 1] / theta[rows];\n      else if (ii < jj) {\n        ret[ii - 1][jj - 1] = std::pow(-1, ii + jj) * theta[ii - 1] * phi[jj + 1] / theta[rows];\n        for (size_t kk = ii; kk < jj; ++kk)\n          ret[ii - 1][jj - 1] *= b[kk];\n      } else if (ii > jj) {\n        ret[ii - 1][jj - 1] = std::pow(-1, ii + jj) * theta[jj - 1] * phi[ii + 1] / theta[rows];\n        for (size_t kk = jj; kk < ii; ++kk)\n          ret[ii - 1][jj - 1] *= c[kk];\n      }\n    } // jj\n  } // ii\n#ifndef NDEBUG\n  for (size_t ii = 0; ii < rows; ++ii)\n    for (size_t jj = 0; jj < cols; ++jj)\n      if (std::isnan(ret[ii][jj]) || std::isinf(ret[ii][jj]))\n        DUNE_THROW(Dune::MathError, \"Inversion of triangular matrix failed!\");\n#endif\n  return ret;\n} // ... tridiagonal_matrix_inverse(...)\n\n// After each refinement step:\n// num_vertices_new = num_vertices_old + num_intersections_old\n// num_intersections_new = 2*num_intersections_old + 3*num_faces_old\n// num_faces_new = 4*num_faces_old\n// Initially, there are 6 vertices, 12 intersections and 8 faces.\ntemplate <size_t refinements>\nstruct OctaederStatistics\n{\n  static constexpr size_t num_faces()\n  {\n    return 8 * (1 << 2 * refinements);\n  }\n\n  static constexpr size_t num_intersections()\n  {\n    return 2 * OctaederStatistics<refinements - 1>::num_intersections()\n           + 3 * OctaederStatistics<refinements - 1>::num_faces();\n  }\n\n  static constexpr size_t num_vertices()\n  {\n    return OctaederStatistics<refinements - 1>::num_vertices()\n           + OctaederStatistics<refinements - 1>::num_intersections();\n  }\n};\n\ntemplate <>\nstruct OctaederStatistics<0>\n{\n  static constexpr size_t num_faces()\n  {\n    return 8;\n  }\n\n  static constexpr size_t num_intersections()\n  {\n    return 12;\n  }\n\n  static constexpr size_t num_vertices()\n  {\n    return 6;\n  }\n};\n\n\ntemplate <class DomainFieldImp,\n          size_t domainDim,\n          class RangeFieldImp,\n          size_t rangeDim,\n          size_t rangeDimCols = 1,\n          size_t fluxDim = domainDim>\nclass BasisfunctionsInterface\n{\npublic:\n  static const size_t dimDomain = domainDim;\n  static const size_t dimRange = rangeDim;\n  static const size_t dimRangeCols = rangeDimCols;\n  static const size_t dimFlux = fluxDim;\n  typedef DomainFieldImp DomainFieldType;\n  typedef XT::Common::FieldVector<DomainFieldType, dimDomain> DomainType;\n  typedef RangeFieldImp RangeFieldType;\n  typedef DynamicMatrix<RangeFieldType> MatrixType;\n  typedef typename XT::Functions::RangeTypeSelector<RangeFieldType, dimRange, dimRangeCols>::type RangeType;\n  template <class DiscreteFunctionType>\n  using VisualizerType = typename std::function<void(const DiscreteFunctionType&, const std::string&, const size_t)>;\n  using StringifierType = std::function<std::string(const RangeType&)>;\n  typedef typename Dune::QuadratureRule<RangeFieldType, dimDomain> QuadratureType;\n\n  virtual ~BasisfunctionsInterface(){};\n\n  virtual RangeType evaluate(const DomainType& v) const = 0;\n\n  virtual RangeType integrated() const = 0;\n\n  virtual MatrixType mass_matrix() const = 0;\n\n  virtual MatrixType mass_matrix_inverse() const = 0;\n\n  virtual FieldVector<MatrixType, dimFlux> mass_matrix_with_v() const = 0;\n\n  static QuadratureRule<RangeFieldType, 2> barycentre_rule()\n  {\n    Dune::QuadratureRule<RangeFieldType, 2> ret;\n    ret.push_back(Dune::QuadraturePoint<RangeFieldType, 2>({1. / 3., 1. / 3.}, 0.5));\n    return ret;\n  }\n\nprotected:\n  std::vector<std::vector<size_t>> create_decomposition(const size_t num_threads, const size_t size) const\n  {\n    std::vector<std::vector<size_t>> decomposition(num_threads);\n    for (size_t ii = 0; ii < num_threads - 1; ++ii) {\n      decomposition[ii].reserve(size / num_threads * (ii + 1) - size / num_threads * ii);\n      for (size_t jj = size / num_threads * ii; jj < size / num_threads * (ii + 1); ++jj)\n        decomposition[ii].push_back(jj);\n    }\n    decomposition[num_threads - 1].reserve(size - (size / num_threads) * (num_threads - 1));\n    for (size_t jj = size / num_threads * (num_threads - 1); jj < size; ++jj)\n      decomposition[num_threads - 1].push_back(jj);\n    return decomposition;\n  }\n\n  virtual void parallel_quadrature(const QuadratureType& quadrature,\n                                   MatrixType& matrix,\n                                   const size_t v_index,\n                                   const bool reflecting = false) const\n  {\n    size_t num_threads = std::min(XT::Common::threadManager().max_threads(), quadrature.size());\n    auto decomposition = create_decomposition(num_threads, quadrature.size());\n    std::vector<std::thread> threads(num_threads);\n    // Launch a group of threads\n    std::vector<MatrixType> local_matrices(num_threads, MatrixType(matrix.N(), matrix.M(), 0.));\n    for (size_t ii = 0; ii < num_threads; ++ii)\n      threads[ii] = std::thread(&BasisfunctionsInterface::calculate_in_thread,\n                                this,\n                                std::cref(quadrature),\n                                std::ref(local_matrices[ii]),\n                                v_index,\n                                std::cref(decomposition[ii]),\n                                reflecting);\n    // Join the threads with the main thread\n    for (size_t ii = 0; ii < num_threads; ++ii)\n      threads[ii].join();\n    // add local matrices\n    matrix *= 0.;\n    for (size_t ii = 0; ii < num_threads; ++ii)\n      matrix += local_matrices[ii];\n  } // void parallel_quadrature(...)\n\n  virtual void calculate_in_thread(const QuadratureType& quadrature,\n                                   MatrixType& local_matrix,\n                                   const size_t v_index,\n                                   const std::vector<size_t>& indices,\n                                   const bool reflecting) const\n  {\n    for (const auto& jj : indices) {\n      const auto& quad_point = quadrature[jj];\n      const auto& v = quad_point.position();\n      auto v_reflected = v;\n      if (reflecting)\n        v_reflected[v_index] *= -1.;\n      const auto basis_evaluated = evaluate(v);\n      const auto basis_reflected = evaluate(v_reflected);\n      const auto& weight = quad_point.weight();\n      const auto factor = (reflecting || v_index == size_t(-1)) ? 1. : v[v_index];\n      for (size_t nn = 0; nn < local_matrix.N(); ++nn)\n        for (size_t mm = 0; mm < local_matrix.M(); ++mm)\n          local_matrix[nn][mm] +=\n              basis_evaluated[nn] * (reflecting ? basis_reflected[mm] : basis_evaluated[mm]) * factor * weight;\n    } // ii\n  } // void calculate_in_thread(...)\n\n  RangeType integrated_initializer(const QuadratureType& quadrature) const\n  {\n    size_t num_threads = std::min(XT::Common::threadManager().max_threads(), quadrature.size());\n    auto decomposition = create_decomposition(num_threads, quadrature.size());\n    std::vector<std::thread> threads(num_threads);\n    std::vector<RangeType> local_vectors(num_threads, RangeType(0.));\n    for (size_t ii = 0; ii < num_threads; ++ii)\n      threads[ii] = std::thread(&BasisfunctionsInterface::integrated_initializer_thread,\n                                this,\n                                std::cref(quadrature),\n                                std::ref(local_vectors[ii]),\n                                std::cref(decomposition[ii]));\n    // Join the threads with the main thread\n    for (size_t ii = 0; ii < num_threads; ++ii)\n      threads[ii].join();\n    // add local matrices\n    RangeType ret(0.);\n    for (size_t ii = 0; ii < num_threads; ++ii)\n      ret += local_vectors[ii];\n    return ret;\n  }\n\n  void integrated_initializer_thread(const QuadratureType& quadrature,\n                                     RangeType& local_range,\n                                     const std::vector<size_t>& indices) const\n  {\n    for (const auto& jj : indices) {\n      const auto& quad_point = quadrature[jj];\n      auto basis_evaluated = evaluate(quad_point.position());\n      basis_evaluated *= quad_point.weight();\n      local_range += basis_evaluated;\n    } // jj\n  } // void calculate_in_thread(...)\n};\n\n\n} // namespace Problems\n} // namespace Hyperbolic\n} // namespace GDT\n} // namespace Dune\n\n#endif // DUNE_GDT_HYPERBOLIC_PROBLEMS_MOMENTMODELS_BASISFUNCTIONS_BASE_HH\n", "meta": {"hexsha": "1977d2fd64bc3f06889931a61f6a0e17a178c503", "size": 16241, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/gdt/test/hyperbolic/problems/momentmodels/basisfunctions/base.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/test/hyperbolic/problems/momentmodels/basisfunctions/base.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/test/hyperbolic/problems/momentmodels/basisfunctions/base.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": 40.8065326633, "max_line_length": 117, "alphanum_fraction": 0.6662767071, "num_tokens": 4148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.26634000471263125}}
{"text": "#define BIORBD_API_EXPORTS\n#include \"Utils/Quaternion.h\"\n\n#include <rbdl/rbdl_math.h>\n#include <Eigen/Dense>\n#include \"Utils/Vector3d.h\"\n#include \"Utils/Vector.h\"\n#include \"Utils/RotoTrans.h\"\n#include \"Utils/Error.h\"\n#include \"Utils/Rotation.h\"\n\nbiorbd::utils::Quaternion::Quaternion (\n        double kStabilizer) :\n    Eigen::Vector4d (1, 0, 0, 0),\n    m_Kstab(kStabilizer) {\n\n}\n\nbiorbd::utils::Quaternion::Quaternion(const biorbd::utils::Quaternion &other) :\n    Eigen::Vector4d (other),\n    m_Kstab(other.m_Kstab) {\n\n}\n\nbiorbd::utils::Quaternion::Quaternion (\n        double w,\n        double x,\n        double y,\n        double z,\n        double kStabilizer) :\n    Eigen::Vector4d(w, x, y, z),\n    m_Kstab(kStabilizer) {\n\n}\n\nbiorbd::utils::Quaternion::Quaternion (\n        double w,\n        const biorbd::utils::Vector3d &vec3,\n        double kStabilizer) :\n    Eigen::Vector4d(w, vec3[0], vec3[1], vec3[2]),\n    m_Kstab(kStabilizer) {\n\n}\n\nbiorbd::utils::Quaternion::Quaternion(\n        const biorbd::utils::Vector &vec,\n        double kStabilizer):\n    Eigen::Vector4d (vec),\n    m_Kstab(kStabilizer) {\n\n}\n\ndouble biorbd::utils::Quaternion::w() const\n{\n    return (*this)(0);\n}\ndouble biorbd::utils::Quaternion::x() const\n{\n    return (*this)(1);\n}\ndouble biorbd::utils::Quaternion::y() const\n{\n    return (*this)(2);\n}\ndouble biorbd::utils::Quaternion::z() const\n{\n    return (*this)(3);\n}\n\nvoid biorbd::utils::Quaternion::setKStab(double newKStab)\n{\n    m_Kstab = newKStab;\n}\n\ndouble biorbd::utils::Quaternion::kStab() const\n{\n    return m_Kstab;\n}\n\nbiorbd::utils::Quaternion biorbd::utils::Quaternion::operator*(\n        const biorbd::utils::Quaternion& q) const\n{\n    return biorbd::utils::Quaternion (\n        (*this)[0] * q[0] - (*this)[1] * q[1] - (*this)[2] * q[2] - (*this)[3] * q[3],\n        (*this)[0] * q[1] + (*this)[1] * q[0] + (*this)[2] * q[3] - (*this)[3] * q[2],\n        (*this)[0] * q[2] + (*this)[2] * q[0] + (*this)[3] * q[1] - (*this)[1] * q[3],\n        (*this)[0] * q[3] + (*this)[3] * q[0] + (*this)[1] * q[2] - (*this)[2] * q[1],\n            (this->m_Kstab + q.m_Kstab) / 2);\n}\n\nbiorbd::utils::Quaternion biorbd::utils::Quaternion::operator*(\n        double scalar) const\n{\n    return biorbd::utils::Quaternion (\n                this->Eigen::Vector4d::operator*(scalar), this->m_Kstab);\n}\n\nbiorbd::utils::Quaternion biorbd::utils::Quaternion::operator*(\n        float scalar) const\n{\n    return biorbd::utils::Quaternion (\n                this->Eigen::Vector4d::operator*(scalar), this->m_Kstab);\n}\n\nbiorbd::utils::Quaternion biorbd::utils::Quaternion::operator+(\n        const biorbd::utils::Quaternion& other) const\n{\n    return biorbd::utils::Quaternion(this->Eigen::Vector4d::operator+(other),\n                                     (this->m_Kstab + other.m_Kstab) / 2);\n}\n\nbiorbd::utils::Quaternion biorbd::utils::Quaternion::operator-(\n        const biorbd::utils::Quaternion& other) const\n{\n    return biorbd::utils::Quaternion(this->Eigen::Vector4d::operator-(other),\n                                     (this->m_Kstab + other.m_Kstab) / 2);\n}\n\nbiorbd::utils::Quaternion biorbd::utils::Quaternion::fromGLRotate(\n        double angle,\n        double x,\n        double y,\n        double z,\n        double kStab) {\n    double st = std::sin (angle * M_PI / 360.);\n    return biorbd::utils::Quaternion (\n                std::cos (angle * M_PI / 360.), st * x, st * y, st * z, kStab);\n}\n\nbiorbd::utils::Quaternion biorbd::utils::Quaternion::fromAxisAngle(\n        double angle,\n        const biorbd::utils::Vector3d &axis,\n        double kStab) {\n    double d = axis.norm();\n    double s2 = std::sin (angle * 0.5) / d;\n    return biorbd::utils::Quaternion (\n                std::cos(angle * 0.5),\n                axis[0] * s2, axis[1] * s2, axis[2] * s2, kStab\n            );\n}\n\nbiorbd::utils::Quaternion biorbd::utils::Quaternion::fromMatrix(\n        const biorbd::utils::RotoTrans &rt,\n        double kStab) {\n    return fromMatrix(rt.rot(), kStab);\n}\n\nbiorbd::utils::Quaternion biorbd::utils::Quaternion::fromMatrix(\n        const biorbd::utils::Rotation &mat,\n        double kStab) {\n    double w = std::sqrt (1. + mat(0,0) + mat(1,1) + mat(2,2)) * 0.5;\n    return Quaternion (\n                w,\n                (mat(2,1) - mat(1,2)) / (w * 4.),\n                (mat(0,2) - mat(2,0)) / (w * 4.),\n                (mat(1,0) - mat(0,1)) / (w * 4.),\n                kStab);\n}\n\nbiorbd::utils::Quaternion biorbd::utils::Quaternion::fromZYXAngles(\n        const biorbd::utils::Vector3d &zyx_angles,\n        double kStab) {\n    return fromAxisAngle (zyx_angles[2], biorbd::utils::Vector3d (0., 0., 1.), kStab)\n            * fromAxisAngle (zyx_angles[1], biorbd::utils::Vector3d (0., 1., 0.), kStab)\n            * fromAxisAngle (zyx_angles[0], biorbd::utils::Vector3d (1., 0., 0.), kStab);\n}\n\nbiorbd::utils::Quaternion biorbd::utils::Quaternion::fromYXZAngles(\n        const biorbd::utils::Vector3d &yxz_angles,\n        double kStab) {\n    return fromAxisAngle (yxz_angles[1], biorbd::utils::Vector3d (0., 1., 0.), kStab)\n            * fromAxisAngle (yxz_angles[0], biorbd::utils::Vector3d (1., 0., 0.), kStab)\n            * fromAxisAngle (yxz_angles[2], biorbd::utils::Vector3d (0., 0., 1.), kStab);\n}\n\nbiorbd::utils::Quaternion biorbd::utils::Quaternion::fromXYZAngles(\n        const biorbd::utils::Vector3d &xyz_angles, double kStab) {\n    return fromAxisAngle (xyz_angles[0], biorbd::utils::Vector3d (1., 0., 0.), kStab)\n            * fromAxisAngle (xyz_angles[1], biorbd::utils::Vector3d (0., 1., 0.), kStab)\n            * fromAxisAngle (xyz_angles[2], biorbd::utils::Vector3d (0., 0., 1.), kStab);\n}\n\nbiorbd::utils::Rotation biorbd::utils::Quaternion::toMatrix(\n        bool skipAsserts) const {\n    if (!skipAsserts) {\n        biorbd::utils::Error::check(fabs(this->squaredNorm() - 1.) < 1e-10,\n                                    \"The Quaternion norm is not equal to one\");\n    }\n\n\n    double w = (*this)[0];\n    double x = (*this)[1];\n    double y = (*this)[2];\n    double z = (*this)[3];\n    biorbd::utils::Rotation out;\n    out <<\n        1 - 2*y*y - 2*z*z,  2*x*y - 2*w*z,      2*x*z + 2*w*y,\n        2*x*y + 2*w*z,      1 - 2*x*x - 2*z*z,  2*y*z - 2*w*x,\n        2*x*z - 2*w*y,      2*y*z + 2*w*x,      1 - 2*x*x - 2*y*y;\n    return out;\n}\n\nbiorbd::utils::Quaternion biorbd::utils::Quaternion::slerp(\n        double alpha,\n        const biorbd::utils::Quaternion &quat) const {\n    // check whether one of the two has 0 length\n    double s = std::sqrt (squaredNorm() * quat.squaredNorm());\n\n    // division by 0.f is unhealthy!\n    assert (s != 0.);\n\n    double angle = acos (dot(quat) / s);\n    if (angle == 0. || std::isnan(angle)) {\n        return *this;\n    }\n    assert(!std::isnan(angle));\n\n    double d = 1. / std::sin (angle);\n    double p0 = std::sin ((1. - alpha) * angle);\n    double p1 = std::sin (alpha * angle);\n\n    if (dot (quat) < 0.) {\n        return Quaternion( ((*this) * p0 - quat * p1) * d, this->m_Kstab);\n    }\n    return Quaternion( ((*this) * p0 + quat * p1) * d,\n                       (this->m_Kstab + quat.m_Kstab) / 2);\n}\n\nbiorbd::utils::Quaternion biorbd::utils::Quaternion::conjugate() const {\n    return biorbd::utils::Quaternion (\n                (*this)[0],\n                -(*this)[1],-(*this)[2],-(*this)[3],\n                this->kStab()\n            );\n}\n\nbiorbd::utils::Quaternion biorbd::utils::Quaternion::timeStep(\n        const biorbd::utils::Vector3d &omega,\n        double dt) {\n    double omega_norm = omega.norm();\n    return fromAxisAngle (\n                dt * omega_norm, omega / omega_norm, this->m_Kstab) * (*this);\n}\n\nbiorbd::utils::Vector3d biorbd::utils::Quaternion::rotate(\n        const biorbd::utils::Vector3d &vec) const {\n    biorbd::utils::Quaternion vec_quat (0., vec);\n\n    biorbd::utils::Quaternion res_quat(vec_quat * (*this));\n    res_quat = conjugate() * res_quat;\n\n    return biorbd::utils::Vector3d(res_quat[1], res_quat[2], res_quat[3]);\n}\n\n#include <iostream>\nbiorbd::utils::Quaternion biorbd::utils::Quaternion::omegaToQDot(\n        const biorbd::utils::Vector3d &omega) const {\n    Eigen::MatrixXd m(4, 3);\n    m(0, 0) = -(*this)[1];   m(0, 1) = -(*this)[2];   m(0, 2) = -(*this)[3];\n    m(1, 0) =  (*this)[0];   m(1, 1) = -(*this)[3];   m(1, 2) =  (*this)[2];\n    m(2, 0) =  (*this)[3];   m(2, 1) =  (*this)[0];   m(2, 2) = -(*this)[1];\n    m(3, 0) = -(*this)[2];   m(3, 1) =  (*this)[1];   m(3, 2) =  (*this)[0];\n    return biorbd::utils::Quaternion(0.5 * m * omega, this->m_Kstab);\n}\n\nbiorbd::utils::Vector3d  biorbd::utils::Quaternion::eulerDotToOmega(\n            const biorbd::utils::Vector3d &eulerDot, \n            const biorbd::utils::Vector3d &euler, \n            const biorbd::utils::String& seq) {\n    \n    biorbd::utils::Vector3d w;\n    double dph, dth, dps, ph, th, ps;\n    dph = eulerDot[0]; dth = eulerDot[1]; dps = eulerDot[2];\n    ph = euler[0]; th = euler[1]; ps = euler[2];\n    if (!seq.compare(\"xyz\")) {          // xyz\n        w[0] = dph*std::cos(th)*std::cos(ps) + dth*std::sin(ps);\n        w[1] = dth*std::cos(ps) - dph*std::cos(th)*std::sin(ps);\n        w[2] = dph*std::sin(th) + dps;\n    } else {\n        biorbd::utils::Error::raise(\"Angle sequence is either nor implemented or not recognized\");\n    }\n    return w;\n}\n\nvoid biorbd::utils::Quaternion::derivate(\n        const biorbd::utils::Vector &w)\n{\n    // Création du quaternion de \"préproduit vectoriel\"\n    double& qw = (*this)(0);\n    double& qx = (*this)(1);\n    double& qy = (*this)(2);\n    double& qz = (*this)(3);\n    Eigen::Matrix4d Q;\n    Q <<    qw, -qx, -qy, -qz,\n            qx,  qw, -qz,  qy,\n            qy,  qz,  qw, -qx,\n            qz, -qy,  qx,  qw;\n\n    // Ajout du paramètre de stabilisation\n    Eigen::Vector4d w_tp (m_Kstab*w.norm()*(1-this->norm()), w(0), w(1), w(2));\n    Eigen::Vector4d newQuat(0.5 * Q * w_tp);\n\n    // Assigning is slightly faster than create a new Quaternion\n    qw = newQuat[0];\n    qx = newQuat[1];\n    qy = newQuat[2];\n    qz = newQuat[3];\n\n}\n\nvoid biorbd::utils::Quaternion::normalize()\n{\n    *this = *this / this->norm();\n}\n", "meta": {"hexsha": "c8333b7f7c4a59b5f1a25bb0c2a6f59b0bddd278", "size": 10066, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Quaternion.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/Utils/Quaternion.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/Utils/Quaternion.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": 31.9555555556, "max_line_length": 98, "alphanum_fraction": 0.5645738128, "num_tokens": 3372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.2663168884693415}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//  Copyright 2018 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_MP_EIGEN_HPP\n#define BOOST_MP_EIGEN_HPP\n\n#include <nil/crypto3/multiprecision/number.hpp>\n\n#include <Eigen/Core>\n\n//\n// Generic Eigen support code:\n//\nnamespace Eigen {\n    template<class Backend, nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>\n    struct NumTraits<nil::crypto3::multiprecision::number<Backend, ExpressionTemplates>> {\n        using self_type = nil::crypto3::multiprecision::number<Backend, ExpressionTemplates>;\n        using Real = typename nil::crypto3::multiprecision::scalar_result_from_possible_complex<self_type>::type;\n        using NonInteger = self_type;    // Not correct but we can't do much better??\n        using Literal = double;\n        using Nested = self_type;\n        enum {\n            IsComplex = nil::crypto3::multiprecision::number_category<self_type>::value ==\n                        nil::crypto3::multiprecision::number_kind_complex,\n            IsInteger = nil::crypto3::multiprecision::number_category<self_type>::value ==\n                        nil::crypto3::multiprecision::number_kind_integer,\n            ReadCost = 1,\n            AddCost = 4,\n            MulCost = 8,\n            IsSigned =\n                std::numeric_limits<self_type>::is_specialized ? std::numeric_limits<self_type>::is_signed : true,\n            RequireInitialization = 1,\n        };\n        static Real epsilon() {\n            return std::numeric_limits<Real>::epsilon();\n        }\n        static Real dummy_precision() {\n            return 1000 * epsilon();\n        }\n        static Real highest() {\n            return (std::numeric_limits<Real>::max)();\n        }\n        static Real lowest() {\n            return (std::numeric_limits<Real>::min)();\n        }\n        static int digits10_imp(const std::integral_constant<bool, true>&) {\n            return std::numeric_limits<Real>::digits10;\n        }\n        template<bool B>\n        static int digits10_imp(const std::integral_constant<bool, B>&) {\n            return Real::default_precision();\n        }\n        static int digits10() {\n            return digits10_imp(\n                std::integral_constant < bool,\n                std::numeric_limits<Real>::digits10 && (std::numeric_limits<Real>::digits10 != INT_MAX) ? true :\n                                                                                                          false > ());\n        }\n    };\n    template<class tag, class Arg1, class Arg2, class Arg3, class Arg4>\n    struct NumTraits<nil::crypto3::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>>\n        : public NumTraits<\n              typename nil::crypto3::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type> { };\n\n#define BOOST_MP_EIGEN_SCALAR_TRAITS_DECL(A)                                                                        \\\n    template<class Backend, nil::crypto3::multiprecision::expression_template_option ExpressionTemplates,           \\\n             typename BinaryOp>                                                                                     \\\n    struct ScalarBinaryOpTraits<nil::crypto3::multiprecision::number<Backend, ExpressionTemplates>, A, BinaryOp> {  \\\n        /*static_assert(nil::crypto3::multiprecision::is_compatible_arithmetic_type<A,                              \\\n         * nil::crypto3::multiprecision::number<Backend, ExpressionTemplates> >::value, \"Interoperability with this \\\n         * arithmetic type is not supported.\");*/                                                                   \\\n        using ReturnType = nil::crypto3::multiprecision::number<Backend, ExpressionTemplates>;                      \\\n    };                                                                                                              \\\n    template<class Backend, nil::crypto3::multiprecision::expression_template_option ExpressionTemplates,           \\\n             typename BinaryOp>                                                                                     \\\n    struct ScalarBinaryOpTraits<A, nil::crypto3::multiprecision::number<Backend, ExpressionTemplates>, BinaryOp> {  \\\n        /*static_assert(nil::crypto3::multiprecision::is_compatible_arithmetic_type<A,                              \\\n         * nil::crypto3::multiprecision::number<Backend, ExpressionTemplates> >::value, \"Interoperability with this \\\n         * arithmetic type is not supported.\");*/                                                                   \\\n        using ReturnType = nil::crypto3::multiprecision::number<Backend, ExpressionTemplates>;                      \\\n    };\n\n    BOOST_MP_EIGEN_SCALAR_TRAITS_DECL(float)\n    BOOST_MP_EIGEN_SCALAR_TRAITS_DECL(double)\n    BOOST_MP_EIGEN_SCALAR_TRAITS_DECL(long double)\n    BOOST_MP_EIGEN_SCALAR_TRAITS_DECL(char)\n    BOOST_MP_EIGEN_SCALAR_TRAITS_DECL(unsigned char)\n    BOOST_MP_EIGEN_SCALAR_TRAITS_DECL(signed char)\n    BOOST_MP_EIGEN_SCALAR_TRAITS_DECL(short)\n    BOOST_MP_EIGEN_SCALAR_TRAITS_DECL(unsigned short)\n    BOOST_MP_EIGEN_SCALAR_TRAITS_DECL(int)\n    BOOST_MP_EIGEN_SCALAR_TRAITS_DECL(unsigned int)\n    BOOST_MP_EIGEN_SCALAR_TRAITS_DECL(long)\n    BOOST_MP_EIGEN_SCALAR_TRAITS_DECL(unsigned long)\n\n#if 0    \n      template<class Backend, nil::crypto3::multiprecision::expression_template_option ExpressionTemplates, class Backend2, nil::crypto3::multiprecision::expression_template_option ExpressionTemplates2, typename BinaryOp>\n   struct ScalarBinaryOpTraits<nil::crypto3::multiprecision::number<Backend, ExpressionTemplates>, nil::crypto3::multiprecision::number<Backend2, ExpressionTemplates2>, BinaryOp>\n   {\n      static_assert(\n         nil::crypto3::multiprecision::is_compatible_arithmetic_type<nil::crypto3::multiprecision::number<Backend2, ExpressionTemplates2>, nil::crypto3::multiprecision::number<Backend, ExpressionTemplates> >::value\n         || nil::crypto3::multiprecision::is_compatible_arithmetic_type<nil::crypto3::multiprecision::number<Backend, ExpressionTemplates>, nil::crypto3::multiprecision::number<Backend2, ExpressionTemplates2> >::value, \"Interoperability with this arithmetic type is not supported.\");\n      using ReturnType = typename std::conditional<std::is_convertible<nil::crypto3::multiprecision::number<Backend2, ExpressionTemplates2>, nil::crypto3::multiprecision::number<Backend, ExpressionTemplates> >::value,\n         nil::crypto3::multiprecision::number<Backend, ExpressionTemplates>, nil::crypto3::multiprecision::number<Backend2, ExpressionTemplates2> >::type;\n   };\n\n   template<unsigned D, typename BinaryOp>\n   struct ScalarBinaryOpTraits<nil::crypto3::multiprecision::number<nil::crypto3::multiprecision::backends::mpc_complex_backend<D>, nil::crypto3::multiprecision::et_on>, nil::crypto3::multiprecision::mpfr_float, BinaryOp>\n   {\n      using ReturnType = nil::crypto3::multiprecision::number<nil::crypto3::multiprecision::backends::mpc_complex_backend<D>, nil::crypto3::multiprecision::et_on>;\n   };\n\n   template<typename BinaryOp>\n   struct ScalarBinaryOpTraits<nil::crypto3::multiprecision::mpfr_float, nil::crypto3::multiprecision::mpc_complex, BinaryOp>\n   {\n      using ReturnType = nil::crypto3::multiprecision::number<nil::crypto3::multiprecision::backends::mpc_complex_backend<0>, nil::crypto3::multiprecision::et_on>;\n   };\n\n   template<class Backend, nil::crypto3::multiprecision::expression_template_option ExpressionTemplates, typename BinaryOp>\n   struct ScalarBinaryOpTraits<nil::crypto3::multiprecision::number<Backend, ExpressionTemplates>, nil::crypto3::multiprecision::number<Backend, ExpressionTemplates>, BinaryOp>\n   {\n      using ReturnType = nil::crypto3::multiprecision::number<Backend, ExpressionTemplates>;\n   };\n#endif\n\n    template<class Backend, nil::crypto3::multiprecision::expression_template_option ExpressionTemplates, class tag,\n             class Arg1, class Arg2, class Arg3, class Arg4, typename BinaryOp>\n    struct ScalarBinaryOpTraits<nil::crypto3::multiprecision::number<Backend, ExpressionTemplates>,\n                                nil::crypto3::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>,\n                                BinaryOp> {\n        static_assert(\n            std::is_convertible<\n                typename nil::crypto3::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type,\n                nil::crypto3::multiprecision::number<Backend, ExpressionTemplates>>::value,\n            \"Interoperability with this arithmetic type is not supported.\");\n        using ReturnType = nil::crypto3::multiprecision::number<Backend, ExpressionTemplates>;\n    };\n\n    template<class tag, class Arg1, class Arg2, class Arg3, class Arg4, class Backend,\n             nil::crypto3::multiprecision::expression_template_option ExpressionTemplates, typename BinaryOp>\n    struct ScalarBinaryOpTraits<nil::crypto3::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>,\n                                nil::crypto3::multiprecision::number<Backend, ExpressionTemplates>, BinaryOp> {\n        static_assert(\n            std::is_convertible<\n                typename nil::crypto3::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type,\n                nil::crypto3::multiprecision::number<Backend, ExpressionTemplates>>::value,\n            \"Interoperability with this arithmetic type is not supported.\");\n        using ReturnType = nil::crypto3::multiprecision::number<Backend, ExpressionTemplates>;\n    };\n\n    namespace internal {\n        template<typename Scalar>\n        struct conj_retval;\n\n        template<typename Scalar, bool IsComplex>\n        struct conj_impl;\n\n        template<class tag, class Arg1, class Arg2, class Arg3, class Arg4>\n        struct conj_retval<nil::crypto3::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>> {\n            using type =\n                typename nil::crypto3::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type;\n        };\n\n        template<class tag, class Arg1, class Arg2, class Arg3, class Arg4>\n        struct conj_impl<nil::crypto3::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>, true> {\n            EIGEN_DEVICE_FUNC\n            static inline\n                typename nil::crypto3::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type\n                run(const typename nil::crypto3::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>& x) {\n                return conj(x);\n            }\n        };\n\n    }    // namespace internal\n\n}    // namespace Eigen\n\n#endif\n", "meta": {"hexsha": "f45011422c93a95ee3464a35fe63ccc8f6ff5f39", "size": 10826, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/multiprecision/include/nil/crypto3/multiprecision/eigen.hpp", "max_stars_repo_name": "Curryrasul/knapsack-snark", "max_stars_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-14T18:09:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T18:09:38.000Z", "max_issues_repo_path": "libs/multiprecision/include/nil/crypto3/multiprecision/eigen.hpp", "max_issues_repo_name": "Curryrasul/knapsack-snark", "max_issues_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/multiprecision/include/nil/crypto3/multiprecision/eigen.hpp", "max_forks_repo_name": "Curryrasul/knapsack-snark", "max_forks_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-12T10:53:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T10:53:21.000Z", "avg_line_length": 59.8121546961, "max_line_length": 283, "alphanum_fraction": 0.6469610198, "num_tokens": 2321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.26616676293171493}}
{"text": "#include <boost/assert.hpp>\n#include \"cblas.h\"\n#include \"blas-wrapper.h\"\n\n\nnamespace argos {\n    namespace blas {\n        template <>\n        void gemm (float const *A, size_t A_rows, size_t A_cols, bool transA,\n                   float const *B, size_t B_rows, size_t B_cols, bool transB,\n                   float *C, size_t C_rows, size_t C_cols, float alpha, float beta) {\n            size_t M, N, K;\n            enum CBLAS_TRANSPOSE TA, TB;\n            if (transA) {\n                M = A_cols;\n                K = A_rows;\n                TA = CblasTrans;\n            } else {\n                M = A_rows;\n                K = A_cols;\n                TA = CblasNoTrans;\n            }\n\n            if (transB) {\n                N = B_rows;\n                BOOST_VERIFY(K == B_cols);\n                TB = CblasTrans;\n            } else {\n                N = B_cols;\n                BOOST_VERIFY(K == B_rows);\n                TB = CblasNoTrans;\n            }\n            BOOST_VERIFY(M == C_rows);\n            BOOST_VERIFY(N == C_cols);\n            cblas_sgemm(CblasRowMajor, TA, TB, M, N, K, alpha, A, A_cols, B, B_cols, beta, C, C_cols);\n        }\n\n        template <>\n        void gemm (double const *A, size_t A_rows, size_t A_cols, bool transA,\n                   double const *B, size_t B_rows, size_t B_cols, bool transB,\n                   double *C, size_t C_rows, size_t C_cols, double alpha, double beta) {\n            size_t M, N, K;\n            enum CBLAS_TRANSPOSE TA, TB;\n            if (transA) {\n                M = A_cols;\n                K = A_rows;\n                TA = CblasTrans;\n            } else {\n                M = A_rows;\n                K = A_cols;\n                TA = CblasNoTrans;\n            }\n\n            if (transB) {\n                N = B_rows;\n                BOOST_VERIFY(K == B_cols);\n                TB = CblasTrans;\n            } else {\n                N = B_cols;\n                BOOST_VERIFY(K == B_rows);\n                TB = CblasNoTrans;\n            }\n            BOOST_VERIFY(M == C_rows);\n            BOOST_VERIFY(N == C_cols);\n            cblas_dgemm(CblasRowMajor, TA, TB, M, N, K, alpha, A, A_cols, B, B_cols, beta, C, C_cols);\n        }\n    }\n}\n", "meta": {"hexsha": "124305a2cabdb25795637ce31935515cc85d5e7f", "size": 2198, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "blas-wrapper.cpp", "max_stars_repo_name": "aaalgo/argos", "max_stars_repo_head_hexsha": "cca6ea32fa14bb7e5d86520f10a67ecd63b06d0c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-03-13T05:04:19.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-13T05:04:19.000Z", "max_issues_repo_path": "blas-wrapper.cpp", "max_issues_repo_name": "aaalgo/argos", "max_issues_repo_head_hexsha": "cca6ea32fa14bb7e5d86520f10a67ecd63b06d0c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "blas-wrapper.cpp", "max_forks_repo_name": "aaalgo/argos", "max_forks_repo_head_hexsha": "cca6ea32fa14bb7e5d86520f10a67ecd63b06d0c", "max_forks_repo_licenses": ["BSD-3-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.8550724638, "max_line_length": 102, "alphanum_fraction": 0.440855323, "num_tokens": 539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2660872841397837}}
{"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#include <Eigen/Dense>\n#include <iostream>\n#include <vector>\n#include \"Lookup/lookup.hpp\"\n#include \"Utils/all_utils.hpp\"\n\n#ifndef NETKET_RBM_SPIN_HPP\n#define NETKET_RBM_SPIN_HPP\n\nnamespace netket {\n\n/** Restricted Boltzmann machine class with spin 1/2 hidden units.\n *\n */\ntemplate <typename T>\nclass RbmSpin : public AbstractMachine<T> {\n  using VectorType = typename AbstractMachine<T>::VectorType;\n  using MatrixType = typename AbstractMachine<T>::MatrixType;\n\n  // number of visible units\n  int nv_;\n\n  // number of hidden units\n  int nh_;\n\n  // number of parameters\n  int npar_;\n\n  // weights\n  MatrixType W_;\n\n  // visible units bias\n  VectorType a_;\n\n  // hidden units bias\n  VectorType b_;\n\n  VectorType thetas_;\n  VectorType lnthetas_;\n  VectorType thetasnew_;\n  VectorType lnthetasnew_;\n\n  bool usea_;\n  bool useb_;\n\n  int mynode_;\n\n  const Hilbert &hilbert_;\n\n public:\n  using StateType = typename AbstractMachine<T>::StateType;\n  using LookupType = typename AbstractMachine<T>::LookupType;\n\n  // constructor\n  explicit RbmSpin(const Hilbert &hilbert, const json &pars)\n      : nv_(hilbert.Size()), hilbert_(hilbert) {\n    from_json(pars);\n  }\n\n  void Init() {\n    W_.resize(nv_, nh_);\n    a_.resize(nv_);\n    b_.resize(nh_);\n\n    thetas_.resize(nh_);\n    lnthetas_.resize(nh_);\n    thetasnew_.resize(nh_);\n    lnthetasnew_.resize(nh_);\n\n    npar_ = nv_ * nh_;\n\n    if (usea_) {\n      npar_ += nv_;\n    } else {\n      a_.setZero();\n    }\n\n    if (useb_) {\n      npar_ += nh_;\n    } else {\n      b_.setZero();\n    }\n\n    MPI_Comm_rank(MPI_COMM_WORLD, &mynode_);\n\n    if (mynode_ == 0) {\n      std::cout << \"# RBM Initizialized with nvisible = \" << nv_\n                << \" and nhidden = \" << nh_ << std::endl;\n      std::cout << \"# Using visible bias = \" << usea_ << std::endl;\n      std::cout << \"# Using hidden bias  = \" << useb_ << std::endl;\n    }\n  }\n\n  int Nvisible() const override { return nv_; }\n\n  int Nhidden() const { return nh_; }\n\n  int Npar() const override { return npar_; }\n\n  void InitRandomPars(int seed, double sigma) override {\n    VectorType par(npar_);\n\n    netket::RandomGaussian(par, seed, sigma);\n\n    SetParameters(par);\n  }\n\n  void InitLookup(const Eigen::VectorXd &v, LookupType &lt) override {\n    if (lt.VectorSize() == 0) {\n      lt.AddVector(b_.size());\n    }\n    if (lt.V(0).size() != b_.size()) {\n      lt.V(0).resize(b_.size());\n    }\n\n    lt.V(0) = (W_.transpose() * v + b_);\n  }\n\n  void UpdateLookup(const Eigen::VectorXd &v, const std::vector<int> &tochange,\n                    const std::vector<double> &newconf,\n                    LookupType &lt) override {\n    if (tochange.size() != 0) {\n      for (std::size_t s = 0; s < tochange.size(); s++) {\n        const int sf = tochange[s];\n        lt.V(0) += W_.row(sf) * (newconf[s] - v(sf));\n      }\n    }\n  }\n\n  VectorType DerLog(const Eigen::VectorXd &v) override {\n    VectorType der(npar_);\n\n    int k = 0;\n\n    if (usea_) {\n      for (; k < nv_; k++) {\n        der(k) = v(k);\n      }\n    }\n\n    RbmSpin::tanh(W_.transpose() * v + b_, lnthetas_);\n\n    if (useb_) {\n      for (int p = 0; p < nh_; p++) {\n        der(k) = lnthetas_(p);\n        k++;\n      }\n    }\n\n    for (int i = 0; i < nv_; i++) {\n      for (int j = 0; j < nh_; j++) {\n        der(k) = lnthetas_(j) * v(i);\n        k++;\n      }\n    }\n    return der;\n  }\n\n  VectorType GetParameters() override {\n    VectorType pars(npar_);\n\n    int k = 0;\n\n    if (usea_) {\n      for (; k < nv_; k++) {\n        pars(k) = a_(k);\n      }\n    }\n\n    if (useb_) {\n      for (int p = 0; p < nh_; p++) {\n        pars(k) = b_(p);\n        k++;\n      }\n    }\n\n    for (int i = 0; i < nv_; i++) {\n      for (int j = 0; j < nh_; j++) {\n        pars(k) = W_(i, j);\n        k++;\n      }\n    }\n\n    return pars;\n  }\n\n  void SetParameters(const VectorType &pars) override {\n    int k = 0;\n\n    if (usea_) {\n      for (; k < nv_; k++) {\n        a_(k) = pars(k);\n      }\n    }\n\n    if (useb_) {\n      for (int p = 0; p < nh_; p++) {\n        b_(p) = pars(k);\n        k++;\n      }\n    }\n\n    for (int i = 0; i < nv_; i++) {\n      for (int j = 0; j < nh_; j++) {\n        W_(i, j) = pars(k);\n        k++;\n      }\n    }\n  }\n\n  // Value of the logarithm of the wave-function\n  T LogVal(const Eigen::VectorXd &v) override {\n    RbmSpin::lncosh(W_.transpose() * v + b_, lnthetas_);\n\n    return (v.dot(a_) + lnthetas_.sum());\n  }\n\n  // Value of the logarithm of the wave-function\n  // using pre-computed look-up tables for efficiency\n  T LogVal(const Eigen::VectorXd &v, LookupType &lt) override {\n    RbmSpin::lncosh(lt.V(0), lnthetas_);\n\n    return (v.dot(a_) + lnthetas_.sum());\n  }\n\n  // Difference between logarithms of values, when one or more visible variables\n  // are being flipped\n  VectorType LogValDiff(\n      const Eigen::VectorXd &v, const std::vector<std::vector<int>> &tochange,\n      const std::vector<std::vector<double>> &newconf) override {\n    const std::size_t nconn = tochange.size();\n    VectorType logvaldiffs = VectorType::Zero(nconn);\n\n    thetas_ = (W_.transpose() * v + b_);\n    RbmSpin::lncosh(thetas_, lnthetas_);\n\n    T logtsum = lnthetas_.sum();\n\n    for (std::size_t k = 0; k < nconn; k++) {\n      if (tochange[k].size() != 0) {\n        thetasnew_ = thetas_;\n\n        for (std::size_t s = 0; s < tochange[k].size(); s++) {\n          const int sf = tochange[k][s];\n\n          logvaldiffs(k) += a_(sf) * (newconf[k][s] - v(sf));\n\n          thetasnew_ += W_.row(sf) * (newconf[k][s] - v(sf));\n        }\n\n        RbmSpin::lncosh(thetasnew_, lnthetasnew_);\n        logvaldiffs(k) += lnthetasnew_.sum() - logtsum;\n      }\n    }\n    return logvaldiffs;\n  }\n\n  // Difference between logarithms of values, when one or more visible variables\n  // are being flipped Version using pre-computed look-up tables for efficiency\n  // on a small number of spin flips\n  T LogValDiff(const Eigen::VectorXd &v, const std::vector<int> &tochange,\n               const std::vector<double> &newconf,\n               const LookupType &lt) override {\n    T logvaldiff = 0.;\n\n    if (tochange.size() != 0) {\n      RbmSpin::lncosh(lt.V(0), lnthetas_);\n\n      thetasnew_ = lt.V(0);\n\n      for (std::size_t s = 0; s < tochange.size(); s++) {\n        const int sf = tochange[s];\n\n        logvaldiff += a_(sf) * (newconf[s] - v(sf));\n\n        thetasnew_ += W_.row(sf) * (newconf[s] - v(sf));\n      }\n\n      RbmSpin::lncosh(thetasnew_, lnthetasnew_);\n      logvaldiff += (lnthetasnew_.sum() - lnthetas_.sum());\n    }\n    return logvaldiff;\n  }\n\n  inline static double lncosh(double x) {\n    const double xp = std::abs(x);\n    if (xp <= 12.) {\n      return std::log(std::cosh(xp));\n    } else {\n      const static double log2v = std::log(2.);\n      return xp - log2v;\n    }\n  }\n\n  // ln(cos(x)) for std::complex argument\n  // the modulus is computed by means of the previously defined function\n  // for real argument\n  inline static std::complex<double> lncosh(std::complex<double> x) {\n    const double xr = x.real();\n    const double xi = x.imag();\n\n    std::complex<double> res = RbmSpin::lncosh(xr);\n    res += std::log(\n        std::complex<double>(std::cos(xi), std::tanh(xr) * std::sin(xi)));\n\n    return res;\n  }\n\n  static void tanh(const VectorType &x, VectorType &y) {\n    assert(y.size() >= x.size());\n    y = Eigen::tanh(x.array());\n  }\n\n  static void lncosh(const VectorType &x, VectorType &y) {\n    assert(y.size() >= x.size());\n    for (int i = 0; i < x.size(); i++) {\n      y(i) = lncosh(x(i));\n    }\n  }\n\n  const Hilbert &GetHilbert() const { return hilbert_; }\n\n  void to_json(json &j) const override {\n    j[\"Machine\"][\"Name\"] = \"RbmSpin\";\n    j[\"Machine\"][\"Nvisible\"] = nv_;\n    j[\"Machine\"][\"Nhidden\"] = nh_;\n    j[\"Machine\"][\"UseVisibleBias\"] = usea_;\n    j[\"Machine\"][\"UseHiddenBias\"] = useb_;\n    j[\"Machine\"][\"a\"] = a_;\n    j[\"Machine\"][\"b\"] = b_;\n    j[\"Machine\"][\"W\"] = W_;\n  }\n\n  void from_json(const json &pars) override {\n    if (pars.at(\"Machine\").at(\"Name\") != \"RbmSpin\") {\n      if (mynode_ == 0) {\n        std::cerr << \"# Error while constructing RbmSpin from Json input\"\n                  << std::endl;\n      }\n      std::abort();\n    }\n\n    if (FieldExists(pars[\"Machine\"], \"Nvisible\")) {\n      nv_ = pars[\"Machine\"][\"Nvisible\"];\n    }\n    if (nv_ != hilbert_.Size()) {\n      if (mynode_ == 0) {\n        std::cerr << \"# Number of visible units is incompatible with given \"\n                     \"Hilbert space\"\n                  << std::endl;\n      }\n      std::abort();\n    }\n\n    if (FieldExists(pars[\"Machine\"], \"Nhidden\")) {\n      nh_ = FieldVal(pars[\"Machine\"], \"Nhidden\");\n    } else {\n      nh_ = nv_ * double(FieldVal(pars[\"Machine\"], \"Alpha\"));\n    }\n\n    usea_ = FieldOrDefaultVal(pars[\"Machine\"], \"UseVisibleBias\", true);\n    useb_ = FieldOrDefaultVal(pars[\"Machine\"], \"UseHiddenBias\", true);\n\n    Init();\n\n    // Loading parameters, if defined in the input\n    if (FieldExists(pars[\"Machine\"], \"a\")) {\n      a_ = pars[\"Machine\"][\"a\"];\n    } else {\n      a_.setZero();\n    }\n\n    if (FieldExists(pars[\"Machine\"], \"b\")) {\n      b_ = pars[\"Machine\"][\"b\"];\n    } else {\n      b_.setZero();\n    }\n    if (FieldExists(pars[\"Machine\"], \"W\")) {\n      W_ = pars[\"Machine\"][\"W\"];\n    }\n  }\n};\n\n}  // namespace netket\n\n#endif\n", "meta": {"hexsha": "c851cf06683873c6b6501a5051e534f6f6f7ed36", "size": 9814, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NetKet/Machine/rbm_spin.hpp", "max_stars_repo_name": "artemborin/netket", "max_stars_repo_head_hexsha": "c7f26d52fdb66d2a8f9f94f2e2cfdc8b4ab41334", "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/Machine/rbm_spin.hpp", "max_issues_repo_name": "artemborin/netket", "max_issues_repo_head_hexsha": "c7f26d52fdb66d2a8f9f94f2e2cfdc8b4ab41334", "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/Machine/rbm_spin.hpp", "max_forks_repo_name": "artemborin/netket", "max_forks_repo_head_hexsha": "c7f26d52fdb66d2a8f9f94f2e2cfdc8b4ab41334", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4738154613, "max_line_length": 80, "alphanum_fraction": 0.5657224373, "num_tokens": 2903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2660492215206509}}
{"text": "//BIOIMAGESUITE_LICENSE  ---------------------------------------------------------------------------------\n//BIOIMAGESUITE_LICENSE  This file is part of the BioImage Suite Software Package.\n//BIOIMAGESUITE_LICENSE\n//BIOIMAGESUITE_LICENSE  X. Papademetris, M. Jackowski, N. Rajeevan, R.T. Constable, and L.H\n//BIOIMAGESUITE_LICENSE  Staib. BioImage Suite: An integrated medical image analysis suite, Section\n//BIOIMAGESUITE_LICENSE  of Bioimaging Sciences, Dept. of Diagnostic Radiology, Yale School of\n//BIOIMAGESUITE_LICENSE  Medicine, http://www.bioimagesuite.org.\n//BIOIMAGESUITE_LICENSE\n//BIOIMAGESUITE_LICENSE  All rights reserved. This file may not be edited/copied/redistributed\n//BIOIMAGESUITE_LICENSE  without the explicit permission of the authors.\n//BIOIMAGESUITE_LICENSE\n//BIOIMAGESUITE_LICENSE  -----------------------------------------------------------------------------------\n\n\n#include <bisvtkMultiThreader.h>\n#include \"bisImageDistanceMatrix.h\"\n#include \"bisJSONParameterList.h\"\n#include \"bisUtil.h\"\n#include <algorithm>\n#include <sstream>\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#ifndef _WIN32\n#include <Spectra/SymEigsSolver.h>\n#include <Spectra/GenEigsSolver.h>\n#include <Spectra/MatOp/SparseGenMatProd.h>\n#endif\n\n\ntypedef double BISTYPE;\n\nnamespace bisImageDistanceMatrix {\n\n  // ------------------------------------------------------------------------------------------------\n  // Payload classes\n\n  class bisMThreadStructure {\n  public:\n    short* wgt_dat;\n    int*   index_dat;\n    float* img_dat;\n    long   numvoxels;\n    int    numframes;\n    long   numbest;\n    long   numgoodvox;\n    long   slicesize;\n\n    // Stuff for radius\n    int dim[3];\n    float spa[3];\n    float DistanceRadius;\n    double maxintensity;\n    double normalization;\n    std::vector<double> output_array[VTK_MAX_THREADS];\n    int numcols;\n\n    bisMThreadStructure() {\n      this->wgt_dat=NULL;\n      this->index_dat=NULL;\n      this->img_dat=NULL;\n      this->numcols=4;\n    }\n\n    ~bisMThreadStructure() {\n      for (int i=0;i<VTK_MAX_THREADS;i++) {\n        this->output_array[i].clear();\n        this->output_array[i].shrink_to_fit();\n      }\n      this->wgt_dat=NULL;\n      this->index_dat=NULL;\n      this->img_dat=NULL;\n      this->numcols=0;\n    }\n  };\n\n  class bisMImagePair {\n  public:\n    float* idata;\n    float* odata;\n    int dim[3];\n    int radius[3];\n    int increment[3];\n    int numframes;\n  };\n\n\n  // ------------------------------------------------------------------------------------------------\n\n  float selectKthLargest(unsigned long k0offset, unsigned long n, float* arr0offset) {\n    std::nth_element(arr0offset,arr0offset+k0offset,arr0offset+n);\n    return arr0offset[k0offset];\n  }\n\n  bisSimpleImage<int>* createIndexMap(bisSimpleImage<short>* objectmap) {\n\n    bisSimpleImage<int>* temp=new bisSimpleImage<int>(\"indexmap\");\n\n    int dim2[5]; objectmap->getDimensions(dim2);\n    float spa[5];objectmap->getSpacing(spa);\n\n    dim2[3]=1; dim2[4]=1;\n    temp->allocate(dim2,spa);\n    temp->fill(0);\n    int index=1;\n    int nt=temp->getLength();\n    int* idata=temp->getData();\n    short* obj=objectmap->getData();\n    for (int voxel=0;voxel<nt;voxel++)\n      {\n        if (obj[voxel]>0)\n          {\n            idata[voxel]=index;\n            ++index;\n          }\n      }\n\n    //    double r1[2];\n    //temp->getRange(r1);\n    //std::cout << \"++++ ImageDistanceMatrix: Index Map range=(\" << r1[0] << \":\" << r1[1] << \")\" << std::endl;\n    return temp;\n  }\n\n\n  int checkInputImages(bisSimpleImage<float>* Input,bisSimpleImage<short>* ObjectMap,bisSimpleImage<int>* IndexMap) {\n\n    int dim[5]; Input->getDimensions(dim);\n    float spa[5]; Input->getSpacing(spa);\n\n    int dim1[5]; ObjectMap->getDimensions(dim1);\n    int dim2[5]; IndexMap->getDimensions(dim2);\n\n\n    int sum=0;\n    for (int i=0;i<=2;i++)\n      {\n        sum+=abs(dim[i]-dim2[i]);\n        sum+=abs(dim[i]-dim1[i]);\n      }\n    if (sum>0)\n      {\n        std::cerr << \"Dim=\" << dim[0] << \",\" << dim[1] << \",\" << dim[2] << std::endl;\n        std::cerr << \"Dim1=\" << dim1[0] << \",\" << dim1[1] << \",\" << dim1[2] << std::endl;\n        std::cerr << \"Dim2=\" << dim2[0] << \",\" << dim2[1] << \",\" << dim2[2] << std::endl;\n\n        std::cerr <<\"Input, ObjectMap IndexMap must have the same dimensions. Cannot run sum=\" << sum << std::endl;\n        return 0;\n      }\n\n\n\n    double r1[2]; ObjectMap->getRange(r1);\n    double r2[2]; IndexMap->getRange(r2);\n    if (r1[1]<1)\n      {\n        std::cerr <<\"Input Object Map has no postive values \" << r1[0] << \":\" << r1[1] << std::endl;\n        return 0;\n      }\n\n    std::cout << \"++++ input checking done \" << dim[0] << \",\" << dim[1] << \",\" << dim[2] << \" maxobj=\" << r1[1] << \" maxindex=\" << r2[1] << std::endl;\n\n    return 1;\n  }\n\n\n  double computeDistance(int index1,int index2,int dim[3],float spa[3]) {\n\n    double dist=0.0;\n    int p1[3],p2[3];\n\n    int slicesize=dim[0]*dim[1];\n    //    std::cout << \"slicesize=\" << slicesize << \" \" << dim[0] << \",\" << dim[1] << \",\" << dim[2] << std::endl;\n    p1[2]=index1/slicesize;\n    p2[2]=index2/slicesize;\n\n    int t1=index1%slicesize;\n    int t2=index2%slicesize;\n\n    p1[0]=t1 % dim[0];\n    p1[1]=t1 / dim[0];\n\n    p2[0]=t2 % dim[0];\n    p2[1]=t2 / dim[0];\n\n    for (int ia=0;ia<=2;ia++)\n      dist+=pow(double(p2[ia]-p1[ia])*spa[ia],2.0);\n\n    return dist;\n  }\n\n  // ------------------------------------------------------------------------------------------------------\n  // Threaded Version Of Code\n  // ------------------------------------------------------------------------------------------------------\n  void combineVectorsToCreateSparseMatrix(bisSimpleMatrix<double>* combined,std::vector<double> output_array[VTK_MAX_THREADS],int nc,int NumberOfThreads)\n  {\n    int nt=0;\n\n    fprintf(stdout,\"++++ \\n++++ Threads completed, combining %d arrays (comp=%d): \",NumberOfThreads,nc);\n    for (int i=0;i<NumberOfThreads;i++)\n      {\n        int n=output_array[i].size()/nc;\n        nt+=n;\n        std::cout << n << \" \";\n      }\n\n    std::cout << \", total rows (pairs)=\" << nt << \" cols=\" << nc <<  std::endl;\n\n    combined->zero(nt,nc);\n\n    double* c_dat=combined->getData();\n\n    int index=0;\n    for (int i=0;i<NumberOfThreads;i++)\n      {\n        int num=output_array[i].size();\n        std::cout << \"+++ Combining thread=\" << i+1 << \" num=\" << num << \" elements=\" << num/nc << std::endl;\n        if (num>0)\n          {\n            for (int j=0;j<num;j++)\n              c_dat[index+j]=output_array[i][j];\n            index+=num;\n          }\n      }\n    return;\n  }\n\n  bisMThreadStructure* createThreadStructure(bisSimpleImage<float>* Input,\n                                             bisSimpleImage<short>* ObjectMap,\n                                             bisSimpleImage<int>* IndexMap,\n                                             int NumberOfThreads,float Sparsity,long NumBest=-1)\n  {\n    bisMThreadStructure* ds=  new bisMThreadStructure();\n    int dim[5]; IndexMap->getDimensions(dim);\n    float spa[3]; IndexMap->getImageSpacing(spa);\n    ds->img_dat=Input->getData();\n    ds->wgt_dat=ObjectMap->getData();\n    ds->index_dat=IndexMap->getData();\n    ds->numvoxels=dim[0]*dim[1]*dim[2];\n    ds->numframes=dim[3]*dim[4];\n    ds->numgoodvox=0;\n    ds->numcols=4;\n\n    for (int i=0;i<ds->numvoxels;i++)\n      {\n        if (ds->index_dat[i]>0)\n          ++ds->numgoodvox;\n      }\n\n\n    if (NumBest<0)\n      {\n        ds->numbest=(ds->numgoodvox*Sparsity*0.01);\n      }\n    else\n      {\n        ds->numbest=NumBest;\n      }\n    if (ds->numbest<2)\n      ds->numbest=2;\n    else if (ds->numbest>ds->numgoodvox)\n      ds->numbest=ds->numgoodvox;\n\n\n    int piecesize=2*(ds->numgoodvox*ds->numbest)/NumberOfThreads;\n    for (int i=0;i<NumberOfThreads;i++)\n      {\n        ds->output_array[i].clear();\n        ds->output_array[i].reserve(piecesize);\n      }\n    return ds;\n  }\n\n  // --------------------------------------------------------------------------------------------------------\n  // Helper Function\n  // --------------------------------------------------------------------------------------------------------\n  void bisImageDistanceMatrix_ComputeFraction(int thread,int numthreads,int numvoxels,int range[2]) {\n    int step=numvoxels/numthreads;\n    range[0]=step*thread;\n    range[1]=range[0]+step;\n    if (thread==numthreads-1)\n      range[1]=numvoxels;\n  }\n  // --------------------------------------------------------------------------------------------------------\n  static void sparseThreadFunction(bisvtkMultiThreader::vtkMultiThreader::ThreadInfo *data)\n  {\n\n    bisMThreadStructure   *ds = (bisMThreadStructure *)(data->UserData);\n    int thread=data->ThreadID;\n    int numthreads=data->NumberOfThreads;\n\n    int voxelrange[2];\n    bisImageDistanceMatrix_ComputeFraction(thread,numthreads,ds->numvoxels,voxelrange);\n    std::cout << \"++++ Sparse Matrix Thread (\" << thread << \") output_array numvoxels= \" << ds->numgoodvox << \" * \" << ds->numbest << \", numframes=\" << ds->numframes <<\n      \". Computing \" << voxelrange[0] << \":\" << voxelrange[1] << std::endl;\n\n    float* d_dist=new float[ds->numgoodvox+10];\n    float* d_tmp =new float[ds->numgoodvox+10];\n    int*   d_index=new  int[ds->numgoodvox+10];\n\n\n    int voxelfraction=(voxelrange[1]-voxelrange[0])/5;\n    int dvoxel=voxelrange[1]-voxelrange[0];\n    if (dvoxel<1)\n      dvoxel=1;\n    if (voxelfraction<1)\n      voxelfraction=1;\n    if (voxelfraction>2500)\n      voxelfraction=2500;\n    //    int first=0;\n\n    for (int voxel1=voxelrange[0];voxel1<voxelrange[1];voxel1++)\n      {\n        /*if ((voxel1-voxelrange[0])%voxelfraction==0 && voxel1>voxelrange[0])\n          {\n            std::cout << \"_____ Thread (\" << thread << \"). Processed \" << 100.0*double(voxel1-voxelrange[0])/double(dvoxel) << \"%, \" <<\n              \"(voxel \" << voxel1 << \" of \" << voxelrange[0] << \"->\" << voxelrange[1] << \").\" << std::endl;\n              }*/\n        int v1=ds->index_dat[voxel1];\n        short w1=ds->wgt_dat[voxel1];\n        //std::cout << \"voxel1=\" << voxel1 << \" (\" << v1 << \",\" << w1 << \")\" << std::endl;\n        if (v1>0)\n          {\n            int num_used=0;\n            for (int voxel2=0;voxel2<ds->numvoxels;voxel2++)\n              {\n                if (voxel2!=voxel1)\n                  {\n                    short w2=ds->wgt_dat[voxel2];\n                    int v2=ds->index_dat[voxel2];\n                    if (v2>0 && (w1==w2))\n                      {\n                        int index1=voxel1*ds->numframes;\n                        int index2=voxel2*ds->numframes;\n                        double sum=0.0;\n                        for (int frame=0;frame<ds->numframes;frame++)\n                          {\n                            sum+=pow(ds->img_dat[index1]-ds->img_dat[index2],2.0f);\n                            ++index1;\n                            ++index2;\n                          }\n                        d_dist[num_used]=sum;\n                        d_tmp[num_used]=sum;\n                        d_index[num_used]=voxel2;\n                        ++num_used;\n                      }\n                  }\n              }\n\n            //std::cout << \"voxel1=\" << voxel1 << \", v1=\" << v1 << \" \" << w1 << \" num_used=\" << num_used << std::endl;\n\n            double thr=selectKthLargest(ds->numbest,num_used,d_tmp);\n            //            ++first;\n            //            if (first<3)\n            //  std::cout << \"***** Thread (\"<< thread << \") thr=\" << thr << \", numbest=\" << ds->numbest\n            //        << \"num_used=\" << num_used << \" numgood=\" << ds->numgoodvox << \" nvox=\" << ds->numvoxels << std::endl;\n\n            for (int ia=0;ia<num_used;ia++)\n              {\n                if (d_dist[ia]<thr)\n                  {\n                    int index1=ds->index_dat[voxel1];\n                    int index2=ds->index_dat[d_index[ia]];\n                    //std::cout << index1 << \",\" << index2 << std::endl;\n                    double dist=computeDistance(index1,index2,ds->dim,ds->spa);\n                    //std::cout << index1 << \",\" << index2 << \":\" << dist << std::endl;\n                    ds->output_array[thread].push_back(index1);\n                    ds->output_array[thread].push_back(index2);\n                    ds->output_array[thread].push_back(d_dist[ia]);\n                    ds->output_array[thread].push_back(dist);\n                  }\n              }\n            // This adds itself as a zero\n            int index=ds->index_dat[voxel1];\n            ds->output_array[thread].push_back(index);\n            ds->output_array[thread].push_back(index);\n            ds->output_array[thread].push_back(0.0);\n            ds->output_array[thread].push_back(0.0);\n          }\n      }\n\n    std::cout << \"++++      Thread (\" << thread << \") done numpairs=\" << ds->output_array[thread].size()/ds->numcols << std::endl;\n\n    delete [] d_dist;\n    delete [] d_index;\n    delete [] d_tmp;\n  }\n  // ---------------------------------------------------------------------------\n  static void radiusThreadFunction(bisvtkMultiThreader::vtkMultiThreader::ThreadInfo *data)\n  {\n    bisMThreadStructure   *ds = (bisMThreadStructure *)(data->UserData);\n    int thread=data->ThreadID;\n    int numthreads=data->NumberOfThreads;\n\n    int slicerange[2];\n    bisImageDistanceMatrix_ComputeFraction(thread,numthreads,ds->dim[2],slicerange);\n    if (slicerange[1]==0)\n      slicerange[1]=1;\n\n    std::cout << \"++++ Radius Matrix Thread(\" << thread << \") radius=\" << ds->DistanceRadius << \" computing slices \" << slicerange[0] << \"->\" << slicerange[1] << std::endl;\n\n    float DistanceRadius2=ds->DistanceRadius*ds->DistanceRadius;\n    int slicesize=ds->dim[0]*ds->dim[1];\n    int dslice=(slicerange[1]-slicerange[0])/5;\n    if (dslice<1)\n      dslice=1;\n    // Normalize maxintensity\n    for (int k=slicerange[0];k<slicerange[1];k++)\n      {\n        int kmin=k-int(ds->DistanceRadius/ds->spa[2]); if (kmin<0) kmin=0;\n        int kmax=k+int(ds->DistanceRadius/ds->spa[2]); if (kmax>=ds->dim[2]) kmax=ds->dim[2]-1;\n        for (int j=0;j<ds->dim[1];j++)\n          {\n            int jmin=j-int(ds->DistanceRadius/ds->spa[1]); if (jmin<0) jmin=0;\n            int jmax=j+int(ds->DistanceRadius/ds->spa[1]); if (jmax>=ds->dim[1]) jmax=ds->dim[1]-1;\n            for (int i=0;i<ds->dim[0];i++)\n              {\n                int imin=i-int(ds->DistanceRadius/ds->spa[0]); if (imin<0) imin=0;\n                int imax=i+int(ds->DistanceRadius/ds->spa[0]); if (imax>=ds->dim[0]) imax=ds->dim[0]-1;\n                int vox_index=i+j*ds->dim[0]+k*slicesize;\n                double v[3];\n                v[0]=ds->index_dat[vox_index];\n                short w0=ds->wgt_dat[vox_index];\n                int index1=vox_index*ds->numframes;\n\n                if (v[0]>0.0)\n                  {\n                    v[1]=v[0];\n                    v[2]=0.0;\n                    //\t\t  v[3]=0.0;\n                    ds->output_array[thread].push_back(v[0]);\n                    ds->output_array[thread].push_back(v[1]);\n                    ds->output_array[thread].push_back(0.0);\n                    ds->output_array[thread].push_back(0.0);\n\n\n                    for (int ka=kmin;ka<=kmax;ka++)\n                      for (int ja=jmin;ja<=jmax;ja++)\n                        for (int ia=imin;ia<=imax;ia++)\n                          {\n                            int sec_index=ia+ja*ds->dim[0]+ka*slicesize;\n                            v[1]=ds->index_dat[sec_index];\n                            short w1=ds->wgt_dat[sec_index];\n\n                            if (v[1]>0.0 && w1==w0)\n                              {\n                                double dist=\n                                  pow(double(ka-k)*ds->spa[2],2.0)+\n                                  pow(double(ja-j)*ds->spa[1],2.0)+\n                                  pow(double(ia-i)*ds->spa[0],2.0);\n                                if (dist<=DistanceRadius2 && dist>0.01)\n                                  {\n                                    int index2=sec_index*ds->numframes;\n                                    v[2]=0.0;\n                                    for (int frame=0;frame<ds->numframes;frame++)\n                                      v[2]+=pow(ds->img_dat[index1+frame]-ds->img_dat[index2+frame],2.0f);\n                                    v[2]=(v[2])*ds->normalization;\n                                    //  v[3]=dist;\n                                    ds->output_array[thread].push_back(v[0]);\n                                    ds->output_array[thread].push_back(v[1]);\n                                    ds->output_array[thread].push_back(v[2]);\n                                    ds->output_array[thread].push_back(dist);\n                                  }\n                              }\n                          }\n                  }\n              }\n          }\n      }\n    std::cout << \"++++      Thread (\" << thread << \") done numpairs=\" << ds->output_array[thread].size()/ds->numcols << std::endl;\n\n  }\n\n\n  // --------------------------------------------------------------------------------------------------------\n  static void temporalSparseThreadFunction(bisvtkMultiThreader::vtkMultiThreader::ThreadInfo *data)\n  {\n    bisMThreadStructure *ds = (bisMThreadStructure *)(data->UserData);\n    int thread=data->ThreadID;\n    int numthreads=data->NumberOfThreads;\n    int framerange[2];\n\n    bisImageDistanceMatrix_ComputeFraction(thread,numthreads,ds->numframes,framerange);\n    std::cout << \"++++ Temporal Sparse Matrix Thread (\" << thread << \"). Computing \" << framerange[0] << \":\" << framerange[1] << std::endl;\n    float* d_dist=new float[ds->numframes];\n    float* d_tmp =new float[ds->numframes];\n\n    for (int frame1=framerange[0];frame1<framerange[1];frame1++)\n      {\n        d_tmp[frame1]=0.0;\n        d_dist[frame1]=0.0;\n\n        for (int frame2=0;frame2<ds->numframes;frame2++)\n          {\n            if (frame2!=frame1)\n              {\n                int index1=frame1*ds->numvoxels;\n                int index2=frame2*ds->numvoxels;\n                double sum=0.0;\n                for (int voxel=0;voxel<ds->numvoxels;voxel++)\n                  sum+=pow(ds->img_dat[index1+voxel]-ds->img_dat[index2+voxel],2.0f);\n                d_dist[frame2]=sum;\n                d_tmp[frame2]=sum;\n              }\n          }\n\n        double thr=selectKthLargest(ds->numbest,ds->numframes,d_tmp);\n\n        for (int frame2=0;frame2<ds->numframes;frame2++)\n          {\n            if (d_dist[frame2]<thr)\n              {\n                ds->output_array[thread].push_back(frame1);\n                ds->output_array[thread].push_back(frame2);\n                ds->output_array[thread].push_back(d_dist[frame2]);\n              }\n          }\n      }\n\n    std::cout << \"++++      Thread (\" << thread << \") done numpairs=\" << ds->output_array[thread].size()/ds->numcols << std::endl;\n\n    delete [] d_dist;\n    delete [] d_tmp;\n  }\n\n  // ---------------------------------------------------------------------------\n  int createSparseMatrixParallel(bisSimpleImage<float>* Input,\n                                 bisSimpleImage<short>* ObjectMap,\n                                 bisSimpleImage<int>* IndexMap,\n                                 bisSimpleMatrix<double>* Output,\n                                 float sparsity,int numthreads)\n  {\n    float Sparsity=bisUtil::frange(sparsity,0.001,50.0);\n    int NumberOfThreads=bisUtil::irange(numthreads,1,VTK_MAX_THREADS);\n\n\n    if (!checkInputImages(Input,ObjectMap,IndexMap))\n      return 0;\n\n    int d[3]; Input->getImageDimensions(d);\n    int nv=d[0]*d[1]*d[2];\n    if (nv<NumberOfThreads)\n      NumberOfThreads=nv;\n\n    std::cout << \"++++ CreateSparseMatrixParallel sparsity=\" << Sparsity << \" Number Of Threads= \"\n              << NumberOfThreads << \" (max=\" << VTK_MAX_THREADS  << \")\" << std::endl;\n    bisMThreadStructure* ds=  createThreadStructure(Input,ObjectMap,IndexMap,NumberOfThreads,Sparsity);\n    Input->getImageDimensions(ds->dim);\n    Input->getImageSpacing(ds->spa);\n\n\n    std::stringstream strss;  strss <<  \"Numgoodvox=\" << ds->numgoodvox << \", expected total size=\" << ds->numgoodvox*ds->numbest;\n    bisvtkMultiThreader::runMultiThreader((bisvtkMultiThreader::vtkThreadFunctionType)&sparseThreadFunction,ds,strss.str(),NumberOfThreads,1);\n    combineVectorsToCreateSparseMatrix(Output,ds->output_array,ds->numcols,NumberOfThreads);\n    double density=100.0*Output->getNumRows()/(double(ds->numgoodvox*ds->numgoodvox));\n    std::cout << \"++++ Sparse matrix done. Final density: num_rows=\" << ds->numgoodvox << \" density=\" << density << \"% (components=\" << Output->getNumCols() << \")\" << std::endl;\n\n\n    delete ds;\n    return 1;\n  }\n\n\n  int createRadiusMatrixParallel(bisSimpleImage<float>* Input,\n                                 bisSimpleImage<short>* ObjectMap,\n                                 bisSimpleImage<int>* IndexMap,\n                                 bisSimpleMatrix<double>* Output,\n                                 float radius,int numthreads)\n  {\n\n    int NumberOfThreads=bisUtil::irange(numthreads,1,VTK_MAX_THREADS);\n    float DistanceRadius=bisUtil::frange(radius,1.0,4000.0);\n\n    if (!checkInputImages(Input,ObjectMap,IndexMap))\n      return 0;\n\n\n    int d[3]; Input->getImageDimensions(d);\n    if (d[2]<NumberOfThreads)\n      NumberOfThreads=d[2];\n\n    std::cout << \"++++ Beginning CreateRadiusMatrixParallel. Radius=\" << DistanceRadius << \", numthreads=\" << NumberOfThreads << std::endl;\n\n    float spa[3]; Input->getImageSpacing(spa);\n\n    int nbest=1;\n    double meanspa=0.0;\n    for (int ia=0;ia<=2;ia++)\n      {\n        nbest=nbest*(2*int(radius/spa[ia]+0.5)+1);\n        meanspa+=spa[ia];\n      }\n    meanspa=meanspa/3.0;\n\n    double r[2]; Input->getRange(r);\n    double minintensity=r[0];\n    double maxintensity=r[1];\n\n    maxintensity=maxintensity-minintensity;\n    if (maxintensity<0.0001)\n      maxintensity=0.0001;\n\n    bisMThreadStructure* ds=createThreadStructure(Input,ObjectMap,IndexMap,NumberOfThreads,0.0,nbest);\n\n    ds->DistanceRadius=DistanceRadius;\n    Input->getImageDimensions(ds->dim);\n    Input->getImageSpacing(ds->spa);\n    ds->maxintensity=maxintensity;\n    ds->normalization=1.0;\n\n    std::cout << \"++++ Parameters: maxintensity\" << ds->maxintensity << \", numframes=\" << ds->numframes << \" distradius=\" <<\n      ds->DistanceRadius << std::endl;\n    std::cout << \"++++ Normalization=\" << ds->normalization << \" Mean spacing=\" << meanspa << std::endl;\n\n    std::stringstream strss;  strss <<  \"Numgoodvox=\" << ds->numgoodvox << \", expected total size=\" << ds->numgoodvox*ds->numbest;\n    bisvtkMultiThreader::runMultiThreader((bisvtkMultiThreader::vtkThreadFunctionType)&radiusThreadFunction,ds,strss.str(),NumberOfThreads,1);\n\n    combineVectorsToCreateSparseMatrix(Output,ds->output_array,ds->numcols,NumberOfThreads);\n    double density=100.0*Output->getNumRows()/(double(ds->numgoodvox*ds->numgoodvox));\n    std::cout << \"++++ Radius matrix done. Final density: num_rows=\" << ds->numgoodvox << \" density=\" << density << \"% (components=\" << Output->getNumCols() << \")\" << std::endl;\n\n    delete ds;\n    return 1;\n  }\n\n  // ---------------------------------------------------------------------------\n  int createSparseMatrixParallelTemporal(bisSimpleImage<float>* Input,\n                                         bisSimpleMatrix<double>* Output,\n                                         float sparsity,int numthreads)\n  {\n    float Sparsity=bisUtil::frange(sparsity,0.001,50.0);\n    int NumberOfThreads=bisUtil::irange(numthreads,1,VTK_MAX_THREADS);\n\n\n    int d[3]; Input->getImageDimensions(d);\n    int nv=d[0]*d[1]*d[2];\n    if (nv<NumberOfThreads)\n      NumberOfThreads=nv;\n\n    std::cout << \"++++ CreateSparseMatrixParallel sparsity=\" << Sparsity << \" Number Of Threads= \"\n              << NumberOfThreads << \" (max=\" << VTK_MAX_THREADS  << \")\" << std::endl;\n\n    bisMThreadStructure* ds=  new bisMThreadStructure();\n    int dim[5]; Input->getDimensions(dim);\n    ds->img_dat=Input->getData();\n    ds->numvoxels=dim[0]*dim[1]*dim[2];\n    ds->numframes=dim[3]*dim[4];\n    ds->numbest=int(sparsity*ds->numframes)+1;\n    ds->numcols=3;\n\n    int piecesize=2*(ds->numbest*ds->numframes)/NumberOfThreads;\n    for (int i=0;i<NumberOfThreads;i++)\n      {\n        ds->output_array[i].clear();\n        ds->output_array[i].reserve(piecesize);\n      }\n\n    std::stringstream strss;  strss <<  \"Numbest=\" << ds->numbest << \", expected total size=\" << ds->numframes*ds->numbest;\n    bisvtkMultiThreader::runMultiThreader((bisvtkMultiThreader::vtkThreadFunctionType)&temporalSparseThreadFunction,ds,strss.str(),NumberOfThreads,1);\n    combineVectorsToCreateSparseMatrix(Output,ds->output_array,ds->numcols,NumberOfThreads);\n    std::cout << \"Total Rows=\" << Output->getNumRows() << \" frames=\" << ds->numframes << std::endl;\n    double density=100.0*Output->getNumRows()/(double(ds->numframes*ds->numframes));\n    std::cout << \"++++ Sparse matrix done. Final density: num_rows=\" << ds->numframes << \" density=\" << density << \"% (components=\" << Output->getNumCols() << \")\" << std::endl;\n    delete ds;\n    return 1;\n  }\n\n\n\n\n\n\n  // ----------------------------------------------------------------------------------\n  //\n  // -------------------------- reformat Image Code -- make patches into frames\n\n\n  static void reformatThreadFunction(bisvtkMultiThreader::vtkMultiThreader::ThreadInfo *data) {\n\n    bisMImagePair   *ds = (bisMImagePair *)(data->UserData);\n    int thread=data->ThreadID;\n    int numthreads=data->NumberOfThreads;\n\n    int slicerange[2];\n    bisImageDistanceMatrix_ComputeFraction(thread,numthreads,ds->dim[2],slicerange);\n    if (slicerange[1]==0)\n      slicerange[1]=1;\n\n    std::cout << \"++++ reformatImage Thread(\" << thread << \") radius=\" << ds->radius[0] << \",\" << ds->radius[1] << \",\" << ds->radius[2];\n    std::cout << \", computing slices \" << slicerange[0] << \"->\" << slicerange[1] << \" numframes=\" << ds->numframes << std::endl;\n\n\n    int volumesize=ds->dim[0]*ds->dim[1]*ds->dim[2];\n    int slicesize=ds->dim[0]*ds->dim[1];\n\n    int voxel=slicerange[0]*slicesize;\n\n    for (int k=slicerange[0];k<slicerange[1];k++) {\n      for (int j=0;j<ds->dim[1];j++) {\n        for (int i=0;i<ds->dim[0];i++) {\n\n          int frame=0;\n\n          for (int ka=-ds->radius[2];ka<=ds->radius[2];ka++) {\n            int newk=k+ka*ds->increment[2];\n            if (newk<0)\n              newk=0;\n            else if (newk>=ds->dim[2])\n              newk=ds->dim[2]-1;\n\n            //std::cout << \"ka = \" << ka << \"-->\" << newk << std::endl;\n\n            for (int ja=-ds->radius[1];ja<=ds->radius[1];ja++) {\n              int newj=j+ja*ds->increment[1];\n              if (newj<0)\n                newj=0;\n              else if (newj>=ds->dim[1])\n                newj=ds->dim[1]-1;\n\n              //std::cout << \"ja = \" << ja << \"-->\" << newj << std::endl;\n\n              for (int ia=-ds->radius[0];ia<=ds->radius[0];ia++) {\n                int newi=i+ia*ds->increment[0];\n                if (newi<0)\n                  newi=0;\n                else if (newi>=ds->dim[0])\n                  newi=ds->dim[0]-1;\n\n\n\n                ds->odata[volumesize*frame+voxel]=ds->idata[newk*slicesize+newj*ds->dim[0]+newi];\n                ++frame;\n              } //ia\n            } //ja\n          } //ka\n          ++voxel;\n        } //i\n      } //j\n    } //k\n\n\n\n  }\n\n\n  int reformatImage(bisSimpleImage<float>* input, bisSimpleImage<float>* output,int radius[3],int increment[3],int NumberOfThreads=4) {\n\n    // First copy data around\n    int numframes=1;\n    for (int i=0;i<=2;i++) {\n      if (increment[i]<1)\n        increment[i]=1;\n      if (increment[i]>4)\n        increment[i]=4;\n      if (radius[i]<1)\n        radius[i]=1;\n      else if (radius[i]>4)\n        radius[i]=4;\n      numframes=numframes*(1+2*radius[i]);\n    }\n\n    int dim[5]; input->getDimensions(dim);\n    dim[3]=numframes; dim[4]=1;\n    float spa[5]; input->getSpacing(spa);\n    output->allocateIfDifferent(dim,spa);\n\n    std::cout << \"++++ Allocating output image \" << dim[0] << \"*\" << dim[1] << \"*\" << dim[2] << \", numframes=\" << numframes << std::endl;\n    std::cout << \"++++ \\t radius = \" << radius[0] << \",\" << radius[1] << \",\" << radius[2] << std::endl;\n\n    bisMImagePair* ds=  new bisMImagePair();\n    ds->idata=input->getImageData();\n    ds->odata=output->getImageData();\n    for (int i=0;i<=2;i++) {\n      ds->dim[i]=dim[i];\n      ds->radius[i]=radius[i];\n      ds->increment[i]=increment[i];\n    }\n    ds->numframes=numframes;\n\n    bisvtkMultiThreader::runMultiThreader((bisvtkMultiThreader::vtkThreadFunctionType)&reformatThreadFunction,ds,\"Reformat Image\",NumberOfThreads);\n    delete ds;\n    return numframes;\n  }\n\n  // End name space\n}\n\n// -----------------------------------------------------------------------------------------------------------------------\n\nnamespace bisSparseEigenSystem {\n\n\n\n  // sparseMatrix is output of createSparseMatrixParallel/createSparseMatrixRadius  4 columns i,j, dist and euc dist\n\n  int computeEigenVectors(bisSimpleMatrix<double>* sparseMatrix,\n                          bisSimpleImage<int>*     indexMap,\n                          bisSimpleImage<float>*   eigenVectors,\n                          int maxeigen=10,\n                          double sigma=1.0, double lambda=0.0,double tolerance=0.001,int maxiter=50,float scale=10000) {\n\n\n#ifndef _WIN32\n\n    int nt=sparseMatrix->getNumRows();\n    int nc=sparseMatrix->getNumCols();\n\n    if (nc!=4 || nt< 4) {\n      std::cerr << \"Bad Distance Matrix \" << nt << \"*\" << nc << std::endl;\n      return 0;\n    }\n\n    double* inp_dat=sparseMatrix->getData();\n    double r[2]; indexMap->getRange(r);\n    int numrows=int(r[1]);\n\n    std::cout << \"+++++ Beginning sparse eigensystem: numelements=\" << nt << \" numrows=\" << numrows << std::endl;\n\n    // Assume I have exponentiated and normalized\n    // 1. Compute Median\n    // 2. Exponentiate\n\n    // Inp_dat is an array of size nt*3\n\n\n\n    // Compute The Median\n    // Take every nth value to compute the median (for now n=1)\n    int samplerate=1;\n    int numvalues=int(nt/samplerate);\n    float* values=new float[numvalues];\n    for(int i=0;i<numvalues;i++) {\n      int offset=i*(nc*samplerate);\n      values[i]=inp_dat[offset+2]+lambda*inp_dat[offset+3];\n    }\n    float median=bisImageDistanceMatrix::selectKthLargest(numvalues/2,numvalues,values);\n    delete [] values;\n    if (median<0.00001)\n      median=0.00001;\n    if (sigma<0.0001)\n      sigma=0.0001;\n    double factor=1.0/(median*sigma);\n\n\n    std::cout << \"+++++ Computing Degree ... median= \" << median << \"factor= \" << factor << \" lamda=\" << lambda << \" sigma=\" << sigma << std::endl;\n\n\n    // remember row,col in input sparse matrix triple are 1-offset so subtract 1 for row,col\n    BISTYPE* D=new BISTYPE[numrows];\n    for (int i=0;i<numrows;i++)\n      D[i]=0.0;\n    int index=0;\n\n    int minrow=(int)inp_dat[0],maxrow=(int)inp_dat[0];\n\n\n    for (int i=0;i<nt;i++)\n      {\n        int row=(long)inp_dat[index]-1;\n        double v2=inp_dat[index+2]+lambda*inp_dat[index+3];\n        double v=exp(-v2*factor);\n\n        //        inp_dat[index+2]=v;\n        //      if (row%step==0 && abs(col-row)<10 )\n        //fprintf(stdout,\"Reporting %d,%d = \\t %f->%f\\n\",row,col,v2,v);\n\n        D[row]+=v;\n        if (row<minrow)\n          minrow=row;\n        else if (row>maxrow)\n          maxrow=row;\n        index+=nc;\n      }\n\n    std::cout << \"++++ Minrow=\" << minrow << \"\\t maxrow=\" << maxrow << std::endl;\n\n    // Compute Dinv plus regularizer\n    int step=numrows/7;\n    for (int row=0;row<numrows;row++)\n      {\n        D[row]=1.0/sqrt(D[row]+1.0);\n        if (row%step == 0 || row==numrows-1)\n          std::cout << \"+++++ 1.0/sqrt(Degree) row=\" << row+1 << \" D=\" << D[row] << std::endl;\n      }\n\n\n    std::cout << \"+++++ Storing in Sparse matrix \" << numrows << \"*\" << numrows << std::endl;\n    // Store in Sparse Matrix\n    // remember row,col in input sparse matrix triple are 1-offset so subtract 1 for row,col -- Ignore\n\n    typedef Eigen::Triplet<BISTYPE> T;\n    std::vector<T> tripletList;\n    tripletList.reserve(nt*2);\n    index=0;\n    std::cout << \"+++++ Allocated in Sparse matrix \" << std::endl;\n    for(int i = 0; i < nt; i++) {\n      long row=(long)inp_dat[index]-1;\n      long col=(long)inp_dat[index+1]-1;\n      double v0=inp_dat[index+2]+lambda*inp_dat[index+3];\n      double v1=exp(-v0*factor);\n\n      if (row==col)\n\t{\n\t  // Add 0.5 regularizer to diagonal ...\n\t  BISTYPE v=D[row]*D[row]*(v1+0.5);\n\t  tripletList.push_back(T(row,col,v));\n\t}\n      else\n\t{\n\t  BISTYPE v=0.5*D[row]*D[col]*v1;\n\t  tripletList.push_back(T(row,col,v));\n\t  tripletList.push_back(T(col,row,v));\n\t}\n      index+=nc;\n    }\n\n    delete [] D;\n\n    std::cout << \"+++++ Beginning eigendecomposition num triplets=\" << tripletList.size() << std::endl;\n    // Now On To Solver from Spectra\n    Eigen::SparseMatrix<BISTYPE> M(numrows,numrows);\n    M.setFromTriplets(tripletList.begin(),tripletList.end());\n    std::cout << \"+++++ Compressed Matrix created\" << std::endl;\n\n\n    Spectra::SparseGenMatProd<BISTYPE> op(M);\n    Spectra::SymEigsSolver< BISTYPE, Spectra::LARGEST_ALGE, Spectra::SparseGenMatProd<BISTYPE> > eigs(&op,  maxeigen, maxeigen*2);\n\n    eigs.init();\n    std::cout << \"+++++ Init Done on to Compute \" << maxeigen << \" Eigenvalues (tolerance=\" << tolerance << \" maxiter=\" << maxiter << \")\" << std::endl;\n\n    int nconv = eigs.compute(maxiter,tolerance);\n\n    // Retrieve results\n    if(eigs.info() != Spectra::SUCCESSFUL) {\n      std::cerr << \"---- Eigen decomposition failed \" << std::endl;\n      return 0;\n    }\n\n    int numeigen=eigs.eigenvalues().size();\n    std::cout << \"+++++ Done with Eigendecomposition (numeigen=\" << numeigen << \"), nconv=\" << nconv << std::endl;\n\n    int tenth=numeigen/10;\n    if (tenth<1)\n      tenth=1;\n    for (int ia=0;ia<numeigen;ia+=tenth) {\n      float l=eigs.eigenvalues().coeff(ia);\n      std::cout << \"+++++\\t Eigenvalue \" << ia+1 << \"/\" << numeigen << \" = \" << l << std::endl;\n    }\n\n    int numeigenrows=eigs.eigenvectors().rows();\n    int numeigencols=eigs.eigenvectors().cols();\n\n    std::cout << \"+++++ numeigenrows*numeigencols=\" << numeigenrows << \"*\" << numeigencols << std::endl;\n    std::cout.flush();\n\n    int dim[5];   indexMap->getDimensions(dim);\n    dim[3]=numeigen; dim[4]=1;\n    float spa[5]; indexMap->getSpacing(spa);\n\n    eigenVectors->allocateIfDifferent(dim,spa);\n    eigenVectors->fill(0.0);\n    float* eig_dat=eigenVectors->getImageData();\n\n    int* ind_dat=indexMap->getImageData();\n    BISTYPE *eigcolmajor=eigs.eigenvectors().data();\n\n    int volumesize=dim[0]*dim[1]*dim[2];\n    int eleventh=volumesize/11;\n    int numgood=0;\n    for (int voxel=0;voxel<volumesize;voxel++)\n      {\n        int index=ind_dat[voxel]-1;\n        if (voxel%eleventh==0 || (index>=0 && numgood < 10 ))\n          std::cout << \"voxel=\" << voxel << \"\\t\" << index << std::endl;\n\n        if (index>=0) {\n          numgood++;\n          for (int frame=0;frame<numeigen;frame++) {\n            int ia=voxel+frame*volumesize;\n            int ib=frame*numeigenrows+index;\n            eig_dat[ia]=eigcolmajor[ib]*scale;\n          }\n        }\n      }\n\n    std::cout << \"++++ Done Assigning numgood=\" << numgood << \" vs \" << volumesize << std::endl;\n    double range[2];\n    eigenVectors->getRange(range);\n    std::cout << \"+++++ Range of eigenvector image =\" << range[0] << \":\" << range[1] << \" Numeigen=\" << numeigen << std::endl;\n    return numeigen;\n#else\n    return 0;\n#endif\n  }\n\n  // ----------------------------------------------------------------------------------\n\n  int eigenvectorDenoiseImage(bisSimpleImage<float>* Input,\n                              bisSimpleImage<float>* Eigenvectors,\n                              bisSimpleImage<float>* Output,\n                              float scale)\n  {\n\n\n    int dim[5]; Input->getDimensions(dim);\n    int dim2[5]; Eigenvectors->getDimensions(dim2);\n    float* idata=Input->getData();\n    float* edata=Eigenvectors->getImageData();\n\n    Output->copyStructure(Input);\n    float* odata=Output->getImageData();\n\n\n\n    int numinputframes=dim[3]*dim[4];\n    int numeigenvectors=dim2[3]*dim2[4];\n\n    std::cout << \"++++ denoiseImageParallel scale=\" << scale << \" numeigenvectors=\" << numeigenvectors << std::endl;\n\n    int volumesize=dim[0]*dim[1]*dim[2];\n    double* coeff=new double[numeigenvectors];\n\n    for (int frame=0;frame<numinputframes;frame++) {\n\n      int i_offset=frame*volumesize;\n      std::cout << \"Frame=\" << frame << \" off=\" << i_offset << std::endl;\n\n      for (int c=0;c<numeigenvectors;c++) {\n        coeff[c]=0.0;\n        int e_offset=c*volumesize;\n        for (int voxel=0;voxel<volumesize;voxel++) {\n          coeff[c]+=idata[i_offset+voxel]*edata[e_offset+voxel];\n        }\n        coeff[c]/=(scale*scale);\n        std::cout << \"Coeff=\" << c << \" = \" << coeff[c] << \" e_offset=\" << e_offset << std::endl;\n      }\n\n      for (int voxel=0;voxel<volumesize;voxel++) {\n        odata[voxel]=0.0;\n        for (int c=0;c<numeigenvectors;c++)\n          odata[voxel]+=edata[c*volumesize+voxel]*coeff[c];\n      }\n    }\n    delete [] coeff;\n    return 1;\n  }\n\n  // -----------------------------------------------------------------------------------------------------------------------\n  // End of namespace\n}\n\n// -----------------------------------------------------------------------------------------------------------------------\n\n// --------------- External stufff --------------------------------------\n\n/** Computes a sparse distance matrix among voxels in the image\n * @param input serialized 4D input file as unsigned char array\n * @param objectmap serialized input objectmap as unsigned char array\n * @param jsonstring the parameter string for the algorithm\n * { \"useradius\" : false, \"radius\" : 2.0, sparsity : 0.01, numthreads: 4}\n * @param debug if > 0 print debug messages\n * @returns a pointer to the sparse distance matrix serialized\n */\n// BIS: { 'computeImageDistanceMatrixWASM', 'bisImage', [ 'bisImage', 'bisImage', 'ParamObj', 'debug' ], {\"checkorientation\" : \"all\"} }\nunsigned char* computeImageDistanceMatrixWASM(unsigned char* input, unsigned char* objectmap,const char* jsonstring,int debug) {\n\n  std::unique_ptr<bisJSONParameterList> params(new bisJSONParameterList());\n  int ok=params->parseJSONString(jsonstring);\n  if (!ok)\n    return 0;\n\n  if (debug)\n    params->print();\n\n  std::unique_ptr<bisSimpleImage<float> > inp_image(new bisSimpleImage<float>(\"inp_image\"));\n  if (!inp_image->linkIntoPointer(input))\n    return 0;\n\n  std::unique_ptr<bisSimpleImage<short> > obj_image(new bisSimpleImage<short>(\"obj_image\"));\n  if (objectmap) {\n    if (!obj_image->linkIntoPointer(objectmap))\n      return 0;\n  } else {\n    std::cout << \"++++ creating mask as none was provided\" << std::endl;\n    int dim[5];   inp_image->getDimensions(dim);\n    float spa[5]; inp_image->getSpacing(spa);\n    dim[3]=1; dim[4]=1;\n    obj_image->allocate(dim,spa);\n    obj_image->fill(1);\n  }\n\n\n  int useradius=params->getBooleanValue(\"useradius\",true);\n  float radius=params->getFloatValue(\"radius\",2.0);\n  float sparsity=params->getFloatValue(\"sparsity\",0.01);\n  int numthreads=params->getIntValue(\"numthreads\",4);\n#ifdef _WIN32\n  if (numthreads>1) {\n\tstd::cout << \".... Windows: forcing numthreads=\" << 1 << std::endl;\n\tnumthreads=1;\n  }\n#endif\n\n  if (debug)  {\n    std::cout << \"........................\" << std::endl;\n    std::cout << \".... Beginning image distance matrix computation \" << std::endl;\n    int dim[5]; inp_image->getDimensions(dim);\n    std::cout << \"....      Input  dimensions=\" << dim[0] << \",\" << dim[1] << \",\" << dim[2] << \",\" << dim[3] << \",\" << dim[4] << std::endl;\n    obj_image->getDimensions(dim);\n    std::cout << \"....      Objectmap  dimensions=\" << dim[0] << \",\" << dim[1] << \",\" << dim[2] << \",\" << dim[3] << \",\" << dim[4] << std::endl;\n    std::cout << \"........................\" << std::endl << std::endl;\n  }\n\n\n  std::unique_ptr<bisSimpleImage<int> > indexmap(bisImageDistanceMatrix::createIndexMap(obj_image.get()));\n  std::unique_ptr<bisSimpleMatrix<double> > Output(new bisSimpleMatrix<double>(\"combined\"));\n\n  if (useradius) {\n    bisImageDistanceMatrix::createRadiusMatrixParallel(inp_image.get(),obj_image.get(),indexmap.get(),Output.get(),radius,numthreads);\n  } else {\n    bisImageDistanceMatrix::createSparseMatrixParallel(inp_image.get(),obj_image.get(),indexmap.get(),Output.get(),sparsity,numthreads);\n  }\n\n  return Output->releaseAndReturnRawArray();\n}\n\n\n/** Computes a sparse temporal distance matrix among frames in the image (patches perhaps)\n * @param input serialized 4D input file as unsigned char array\n * @param jsonstring the parameter string for the algorithm\n * { sparsity : 0.01, numthreads: 4 }\n * @param debug if > 0 print debug messages\n * @returns a pointer to the sparse distance matrix serialized\n */\n// BIS: { 'computeTemporalImageDistanceMatrixWASM', 'Matrix', [ 'bisImage', 'ParamObj', 'debug' ], {\"checkorientation\" : \"all\"} }\nunsigned char* computeTemporalImageDistanceMatrixWASM(unsigned char* input,const char* jsonstring,int debug) {\n\n  std::unique_ptr<bisJSONParameterList> params(new bisJSONParameterList());\n  int ok=params->parseJSONString(jsonstring);\n  if (!ok)\n    return 0;\n\n  if (debug)\n    params->print();\n\n  std::unique_ptr<bisSimpleImage<float> > inp_image(new bisSimpleImage<float>(\"inp_image\"));\n  if (!inp_image->linkIntoPointer(input))\n    return 0;\n\n  float sparsity=params->getFloatValue(\"sparsity\",0.01);\n  int numthreads=params->getIntValue(\"numthreads\",4);\n\n#ifdef _WIN32\n  if (numthreads>1) {\n\tstd::cout << \".... Windows: forcing numthreads=\" << 1 << std::endl;\n\tnumthreads=1;\n  }\n#endif\n\n\n  if (debug)  {\n    std::cout << \"........................\" << std::endl;\n    std::cout << \".... Beginning temporal image distance matrix computation \" << std::endl;\n    int dim[5]; inp_image->getDimensions(dim);\n    std::cout << \"....      Input  dimensions=\" << dim[0] << \",\" << dim[1] << \",\" << dim[2] << \",\" << dim[3] << \",\" << dim[4] << std::endl;\n  }\n\n\n  std::unique_ptr<bisSimpleMatrix<double> > Output(new bisSimpleMatrix<double>(\"combined\"));\n  bisImageDistanceMatrix::createSparseMatrixParallelTemporal(inp_image.get(),Output.get(),sparsity,numthreads);\n  return Output->releaseAndReturnRawArray();\n}\n\n/** Creates an indexmap image\n * @param input objectmap\n * @param debug if > 0 print debug messages\n * @returns a pointer to the serialized index map image (int)\n */\n// BIS: { 'computeImageIndexMapWASM', 'bisIamage', [ 'bisImage', 'debug' ]\nunsigned char* computeImageIndexMapWASM(unsigned char* input,int debug) {\n\n\n  std::unique_ptr<bisSimpleImage<short> > inp_image(new bisSimpleImage<short>(\"inp_image\"));\n  if (!inp_image->linkIntoPointer(input))\n    return 0;\n\n  if (debug)  {\n    std::cout << \"........................\" << std::endl;\n    std::cout << \".... Beginning image indexmap computation \" << std::endl;\n    int dim[5]; inp_image->getDimensions(dim);\n    std::cout << \"....      Input  dimensions=\" << dim[0] << \",\" << dim[1] << \",\" << dim[2] << \",\" << dim[3] << \",\" << dim[4] << std::endl;\n  }\n\n  std::unique_ptr<bisSimpleImage<int> > result(bisImageDistanceMatrix::createIndexMap(inp_image.get()));\n  return result->releaseAndReturnRawArray();\n}\n\n/** Creates a reformatted image where a patch is mapped into frames. This is so as to recycle the ImageDistanceMatrix code for\n * patch distances as opposed to frame comparisons\n * @param input serialized 3D input file as unsigned char array\n * @param jsonstring the parameter string for the algorithm\n * { \"radius\" : 2,  numthreads: 4 }\n * @param debug if > 0 print debug messages\n * @returns a pointer to the reformated image\n */\n// BIS: { 'createPatchReformatedImage', 'bisImage', [ 'bisImage', 'ParamObj',  'debug' ] }\nunsigned char* createPatchReformatedImage(unsigned char* input,const char* jsonstring,int debug) {\n\n  std::unique_ptr<bisJSONParameterList> params(new bisJSONParameterList());\n  int ok=params->parseJSONString(jsonstring);\n  if (!ok)\n    return 0;\n\n  if (debug)\n    params->print();\n\n  std::unique_ptr<bisSimpleImage<float> > inp_image(new bisSimpleImage<float>(\"inp_image\"));\n  if (!inp_image->linkIntoPointer(input))\n    return 0;\n\n  int radius=params->getIntValue(\"radius\",2);\n  int numthreads=params->getIntValue(\"numthreads\",4);\n  int increment=params->getIntValue(\"increment\",1);\n\n#ifdef _WIN32\n  if (numthreads>1) {\n\tstd::cout << \".... Windows: forcing numthreads=\" << 1 << std::endl;\n\tnumthreads=1;\n  }\n#endif\n\n  if (debug)  {\n    std::cout << \"........................\" << std::endl;\n    std::cout << \".... Beginning reformatted image \" << std::endl;\n    int dim[5]; inp_image->getDimensions(dim);\n    std::cout << \"....      Input  dimensions=\" << dim[0] << \",\" << dim[1] << \",\" << dim[2] << \",\" << dim[3] << \",\" << dim[4] << std::endl;\n    std::cout << \"........................\" << std::endl << std::endl;\n  }\n\n  int rad[3] = { radius,radius,radius };\n  int incr[3] = { increment,increment,increment };\n\n  std::unique_ptr<bisSimpleImage<float> > out_image(new bisSimpleImage<float>(\"output\"));\n  bisImageDistanceMatrix::reformatImage(inp_image.get(),out_image.get(),rad,incr,numthreads);\n  return out_image->releaseAndReturnRawArray();\n}\n\n\n\n/** Compute sparse Eigen Vectors based on distance Matrix and IndexMap\n * @param sparseMatrix the sparse Matrix (output of computeImageDistanceMatrix)\n * @param indexMap the indexMap image (output of computeImageIndexMap)\n * @param eigenVectors the output eigenVector image\n * @param jsonstring the parameter string for the algorithm\n * { \"maxeigen\" : 10, \"sigma\" : 1.0, \"lambda\" : 0.0, \"tolerance\" : 0.00001 , \"maxiter\" : 500, \"scale\" : 10000 }\n * @param debug if > 0 print debug messages\n * @returns a pointer to the reformated image\n */\n// BIS: { 'computeSparseImageEigenvectorsWASM', 'bisImage', [ 'Matrix', 'bisImage', 'ParamObj',  'debug' ] }\nunsigned char* computeSparseImageEigenvectorsWASM(unsigned char* input, unsigned char* indexmap,const char* jsonstring,int debug) {\n\n  std::unique_ptr<bisJSONParameterList> params(new bisJSONParameterList());\n  int ok=params->parseJSONString(jsonstring);\n  if (!ok)\n    return 0;\n\n  if (debug)\n    params->print();\n\n  std::unique_ptr<bisSimpleMatrix<double> > dist_matrix(new bisSimpleMatrix<double>(\"inp_matrix\"));\n  if (!dist_matrix->linkIntoPointer(input))\n    return 0;\n\n  std::unique_ptr<bisSimpleImage<int> > obj_image(new bisSimpleImage<int>(\"indexmap_image\"));\n  if (!obj_image->linkIntoPointer(indexmap))\n    return 0;\n\n  int   maxeigen=params->getIntValue(\"maxeigen\",10);\n  float  sigma=params->getFloatValue(\"sigma\",1.0);\n  float  lambda=params->getFloatValue(\"lambda\",0.0);\n  float  tolerance=params->getFloatValue(\"tolerance\",1.0e-5);\n  int iter=params->getIntValue(\"maxiter\",500);\n  float scale=params->getFloatValue(\"scale\",10000);\n\n  if (debug)  {\n    std::cout << \"........................\" << std::endl;\n    std::cout << \".... Beginning image distance matrix computation \" << std::endl;\n    int rows=dist_matrix->getNumRows();\n    int cols=dist_matrix->getNumCols();\n\n    std::cout << \"....      Input  Matrix=\" << rows << \"*\" << cols << std::endl;\n    int dim[5]; obj_image->getDimensions(dim);\n    std::cout << \"....      Indexmap  dimensions=\" << dim[0] << \",\" << dim[1] << \",\" << dim[2] << \",\" << dim[3] << \",\" << dim[4] << std::endl;\n    std::cout << \"........................\" << std::endl << std::endl;\n  }\n\n\n  std::unique_ptr<bisSimpleImage<float> > Output(new bisSimpleImage<float>(\"eigenvect\"));\n  bisSparseEigenSystem::computeEigenVectors(dist_matrix.get(),obj_image.get(),Output.get(),\n                                            maxeigen,sigma,lambda,tolerance,iter,scale);\n  return Output->releaseAndReturnRawArray();\n}\n\n\n\n\n/** Eigenvector denoise image -- project image into eigenspace\n * @param input serialized 3D input file as unsigned char array\n * @param 4D eigenvector image\n * @param jsonstring the parameter string for the algorithm\n * { \"scale\" : 10000 , numthreads: 4 }\n * @param debug if > 0 print debug messages\n * @returns a pointer to the denoise image\n */\n// BIS: { 'computeEigenvectorDenoiseImageWASM', 'bisImage', [ 'bisImage', 'bisImage', 'ParamObj',  'debug' ], {\"checkorientation\" : \"all\"} }\nunsigned char* computeEigenvectorDenoiseImageWASM(unsigned char* input, unsigned char* eigenvectors,const char* jsonstring,int debug) {\n\n  std::unique_ptr<bisJSONParameterList> params(new bisJSONParameterList());\n  int ok=params->parseJSONString(jsonstring);\n  if (!ok)\n    return 0;\n\n  if (debug)\n    params->print();\n\n  std::unique_ptr<bisSimpleImage<float> > inp_image(new bisSimpleImage<float>(\"inp_image\"));\n  if (!inp_image->linkIntoPointer(input))\n    return 0;\n\n  std::unique_ptr<bisSimpleImage<float> > eig_image(new bisSimpleImage<float>(\"obj_image\"));\n  if (!eig_image->linkIntoPointer(eigenvectors))\n    return 0;\n\n  float scale=params->getFloatValue(\"scale\",10000.0);\n\n  if (debug)  {\n    std::cout << \"........................\" << std::endl;\n    std::cout << \".... Beginning image eigenvector denoising \" << std::endl;\n    int dim[5]; inp_image->getDimensions(dim);\n    std::cout << \"....      Input  dimensions=\" << dim[0] << \",\" << dim[1] << \",\" << dim[2] << \",\" << dim[3] << \",\" << dim[4] << std::endl;\n    eig_image->getDimensions(dim);\n    std::cout << \"....      Eigenvector  dimensions=\" << dim[0] << \",\" << dim[1] << \",\" << dim[2] << \",\" << dim[3] << \",\" << dim[4] << std::endl;\n    std::cout << \"........................\" << std::endl << std::endl;\n  }\n\n  std::unique_ptr<bisSimpleImage<float> > Output(new bisSimpleImage<float>(\"output\"));\n  bisSparseEigenSystem::eigenvectorDenoiseImage(inp_image.get(),eig_image.get(),Output.get(),scale);\n  return Output->releaseAndReturnRawArray();\n\n}\n", "meta": {"hexsha": "64ef7f1849dc70f63e8ccd4563d05511ddca8776", "size": 49647, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/bisImageDistanceMatrix.cpp", "max_stars_repo_name": "leej3/bisweb", "max_stars_repo_head_hexsha": "0c08a9cd78d228542a64527d2ad74c1f6f7d0a2b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 66.0, "max_stars_repo_stars_event_min_datetime": "2018-04-28T22:09:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T00:28:14.000Z", "max_issues_repo_path": "cpp/bisImageDistanceMatrix.cpp", "max_issues_repo_name": "leej3/bisweb", "max_issues_repo_head_hexsha": "0c08a9cd78d228542a64527d2ad74c1f6f7d0a2b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2018-08-17T13:57:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T13:20:35.000Z", "max_forks_repo_path": "cpp/bisImageDistanceMatrix.cpp", "max_forks_repo_name": "leej3/bisweb", "max_forks_repo_head_hexsha": "0c08a9cd78d228542a64527d2ad74c1f6f7d0a2b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-05-09T20:14:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T12:54:22.000Z", "avg_line_length": 36.7755555556, "max_line_length": 177, "alphanum_fraction": 0.5601345499, "num_tokens": 13510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.26604920907747726}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2014 Daniele Panozzo <daniele.panozzo@gmail.com>\n//\n// This Source Code Form is subject to the terms of the Mozilla Public License\n// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n// obtain one at http://mozilla.org/MPL/2.0/.\n\n#include \"Viewer.h\"\n\n//#include <chrono>\n#include <thread>\n\n#include <Eigen/LU>\n\n\n#include <cmath>\n#include <cstdio>\n#include <sstream>\n#include <iomanip>\n#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <limits>\n#include <cassert>\n\n#include <igl/project.h>\n//#include <igl/get_seconds.h>\n#include <igl/readOBJ.h>\n#include <igl/readOFF.h>\n#include <igl/adjacency_list.h>\n#include <igl/writeOBJ.h>\n#include <igl/writeOFF.h>\n#include <igl/massmatrix.h>\n#include <igl/file_dialog_open.h>\n#include <igl/file_dialog_save.h>\n#include <igl/quat_mult.h>\n#include <igl/axis_angle_to_quat.h>\n#include <igl/trackball.h>\n#include <igl/two_axis_valuator_fixed_up.h>\n#include <igl/snap_to_canonical_view_quat.h>\n#include <igl/unproject.h>\n#include <igl\\circulation.h>\n#include <igl/serialize.h>\n#include<igl\\edge_collapse_is_valid.h>\n#include <igl\\edge_flaps.h>\n#include <igl\\vertex_triangle_adjacency.h>\n#include <igl/collapse_edge.h>\n\n\n\n// Internal global variables used for glfw event handling\n//static igl::opengl::glfw::Viewer * __viewer;\nstatic double highdpi = 1;\nstatic double scroll_x = 0;\nstatic double scroll_y = 0;\n\n\n\nnamespace igl\n{\nnamespace opengl\n{\nnamespace glfw\n{\n\n  void Viewer::Init(const std::string config)\n  {\n      \n    //  load_mesh_from_configuration(config);\n\n  }\n\n  IGL_INLINE Viewer::Viewer():\n    data_list(1),\n    selected_data_index(0),\n    next_data_id(1),\n\tisPicked(false),\n\tisActive(false)\n  {\n    data_list.front().id = 0;\n\n  \n\n    // Temporary variables initialization\n   // down = false;\n  //  hack_never_moved = true;\n    scroll_position = 0.0f;\n\n    // Per face\n    data().set_face_based(false);\n\n    \n#ifndef IGL_VIEWER_VIEWER_QUIET\n    const std::string usage(R\"(igl::opengl::glfw::Viewer usage:\n  [drag]  Rotate scene\n  A,a     Toggle animation (tight draw loop)\n  F,f     Toggle face based\n  I,i     Toggle invert normals\n  L,l     Toggle wireframe\n  O,o     Toggle orthographic/perspective projection\n  T,t     Toggle filled faces\n  [,]     Toggle between cameras\n  1,2     Toggle between models\n  ;       Toggle vertex labels\n  :       Toggle face labels\n  P    Enable simplefication\n  x    Disable simplefication )\"\n);\n    std::cout<<usage<<std::endl;\n#endif\n  }\n\n  IGL_INLINE Viewer::~Viewer()\n  {\n  }\n\n  /* \n  in order to perform a certian contraction we will need to calculate the cost of a contraction \n  to define this cost we attemp to characterize the error at each vertex in the mesh . \n\n  to do this : we associate a symmatric 4x4 matrix named Q with each vertex .\n\n  and we define the error at a vertix v to be \n\n  v = = [vx vy vz 1]T  to be the quadratic form tirangle(v) = vTQv. \n\n  meaning that the error is equal to vTQv. \n\n  let symbol and name a given constraction (V1,v2) as v~ \n\n  * now we mush derive a new matrix that we call Q~ which approximates the error at v~ \n  * \n  *  the rule is that Q~ = Q1 + Q2 - WHERE Q1 is the associted matrix for v1 and Q2 is the associated matrix of v2 \n  * \n  * \n  * in order to do the constraction we must find a position for v~  - the simple scheme would be to either choose \n  * 1. v1 \n  * 2. v2 \n  * 3. v1+v2 \\2  \n  * \n  * \n  * now it depends on which of these have the lowest value at triangelV \n  * \n  * \n  *  meaning which of the following has the lowest value \n  * \n  * 1. v1T X  Q1 X v1\n  * \n  * 2. v2T X  Q2 X v2 \n  * \n  * 3. ((v1+v2)/2)T  x Q~ x (v1+v2)  \n  * \n  * \n  * now it is mentioned how to calculate the v~ \n  * \n  * \n  * \n  * \n  * \n  * \n\n\n  \n  \n  \n  \n  \n  \n  */\n\n  void calculate_cost(\n      std::vector<Eigen::Matrix<double, 4, 4>>& Qs,\n      const int e,\n      const Eigen::MatrixXd& V,\n      const Eigen::MatrixXi& /*F*/,\n      const Eigen::MatrixXi& E,\n      const Eigen::VectorXi& /*EMAP*/,\n      const Eigen::MatrixXi& /*EF*/,\n      const Eigen::MatrixXi& /*EI*/,\n      double& cost,\n      Eigen::RowVectorXd& p)\n  {\n      auto Q1 = Qs[E.row(e)[0]];\n      auto Q2 = Qs[E.row(e)[1]];\n      Eigen::Matrix4d Q = Q1 + Q2;\n      Q.row(3) = Eigen::Vector4d(0, 0, 0, 1);\n\n\n      bool invertable = false;\n      Eigen::Matrix<double, 4, 4> Qi;\n      Q.computeInverseWithCheck(Qi, invertable, 0);\n\n\n      Eigen::Matrix<double, 4, 1> a;\n      if (invertable) {\n          // this is the v~ \n          a = Qi * Eigen::Matrix<double, 4, 1>(0, 0, 0, 1);\n      }\n      else {\n          // we need to choose the midpoint \n          a = (V.row(E.row(e)[0]) + V.row(E.row(e)[1])) / 2;\n          a(3) = 1;\n      }\n\n\n      cost = a.transpose() * (Q1 + Q2) * a;\n      // new point s\n      p = Eigen::RowVector3d(a(0), a(1), a(2));\n  }\n\n  //Assingment 1 task 6\n  IGL_INLINE void Viewer::init_objs_simpelified() {\n     \n      data().Q = new std::set<std::pair<double, int> >(); // priority Q contains the cost of edges <cost , number of edge > \n      data().EMAP = new Eigen::VectorXi();               // connects faces to edges \n\n      /* \n      E - matrix of edges\n      |1 , 3 |\n      |2 , 5 |\n      |3, 1  |\n      \n       source , destenation \n      \n      \n      */\n\n      data().E = new Eigen::MatrixXi();                   // this is the Edges -> edge is represented by <index of source vertex, index of destinations vertex> - matrix []\n      \n      data().EI = new Eigen::MatrixXi();                  //connects edge to vertex index in triangle (0 1 2) \n\n\n      data().EF = new Eigen::MatrixXi();                    //connects edges to faces this is a matrix that have [index of first face , index of second face ]\n    \n      \n      data().C = new Eigen::MatrixXd();                 //position of the new vertex after collapsing the corresponding edge\n\n\n      data().V1 = new Eigen::MatrixXd(data().V);            // the new back up for v \n\n      data().F1 = new Eigen::MatrixXi(data().F);            // the new backup for F \n\n      data().Qs = std::vector<Eigen::Matrix<double, 4, 4>>();\n      data().Qit = new std::vector<std::set<std::pair<double, int> >::iterator >(); // saved iterator for every dege so that \n   \n\n      //this gets the EMAP EF E EI ready \n      edge_flaps(*data().F1, *data().E, *data().EMAP, *data().EF, *data().EI);\n\n      data().Qit->resize(data().E->rows());\n     \n      data().C->resize(data().E->rows(), data().V.cols());\n   \n      Eigen::VectorXd costs(data().E->rows());\n  \n      data().Q->clear();\n     \n\n\n      auto VF = std::vector<std::vector<int> >(); \n      auto VFi = std::vector<std::vector<int> >();\n\n      vertex_triangle_adjacency(data().V, data().F, VF, VFi);\n   \n      // this is for getting the Q ready \n      for (int v = 0; v < data().V.rows(); v++) {\n\n       \n          std::vector<int> faces = VF[v];\n          Eigen::Matrix4d Q = Eigen::Matrix4d::Zero();\n          \n          for (int face : faces) {\n              auto n = data().F_normals.row(face).normalized();\n              float d = 0;\n              for (int j = 0; j < 3; j++) \n              d += (-n[j] * data().V.row(v)[j]);\n              Eigen::RowVector4d p(n[0], n[1], n[2], d);\n              p = p.transpose();\n              Q += p.transpose() * p;\n          }\n         \n          data().Qs.push_back(Q);\n      }\n      for (int e = 0; e < data().E->rows(); e++)\n      {\n     // here i want to calculate all the edges cost\n          double cost = 0;\n          Eigen::RowVectorXd p(1, 3);\n\n          calculate_cost(data().Qs, e, *data().V1, *data().F1, *data().E, *data().EMAP, *data().EF, *data().EI, cost, p);\n          data().C->row(e) = p;\n          (*data().Qit)[e] = (data().Q->insert(std::pair<double, int>(cost, e))).first;\n      }\n\n     \n  }\n      \n\n  \n\n  // ASSIGNMENT 1 TASK 7 & TASK 9 \n\n  IGL_INLINE void Viewer::simplify_mesh(int num_of_faces_to_delete) {\n\n      printf(\"# of faces to delete %d \\n\", num_of_faces_to_delete);\n      bool something_collapsed = false;\n      int num_of_collapsed_edges = 0; \n      \n      for (int i = 0; i < num_of_faces_to_delete; i++) {\n         \n         \n          if (!collapse_edge(calculate_cost, data().Qs,\n              *data().V1,*data().F1,\n              *data().E, *data().EMAP,\n              *data().EF, *data().EI ,\n              *data().Q, *data().Qit,\n              * data().C))\n          {\n              break;\n\n          }\n          something_collapsed = true;\n          data().num_collapsed++;\n\n      }\n      if (something_collapsed) {\n          printf(\"succesfully collapsed # %d of edges \\n\",data().num_collapsed);\n          data().clear();\n          data().set_mesh(*data().V1, *data().F1);\n          data().set_face_based(true);\n          data().dirty = 157;\n\n\n\n      }\n\n      \n\t\t\t\t\n\n  }\n  IGL_INLINE bool Viewer::collapse_edge(\n      const std::function<void(\n          std::vector<Eigen::Matrix<double, 4, 4>>& Qs,\n          const int,\n          const Eigen::MatrixXd&,\n          const Eigen::MatrixXi&,\n          const Eigen::MatrixXi&,\n          const Eigen::VectorXi&,\n          const Eigen::MatrixXi&,\n          const Eigen::MatrixXi&,\n          double&,\n          Eigen::RowVectorXd&)>& cost_and_placement,\n      std::vector<Eigen::Matrix<double, 4, 4>>& Qs,\n      Eigen::MatrixXd& V,\n      Eigen::MatrixXi& F,\n      Eigen::MatrixXi& E,\n      Eigen::VectorXi& EMAP,\n      Eigen::MatrixXi& EF,\n      Eigen::MatrixXi& EI, \n      std::set<std::pair<double, int> >& Q,\n      std::vector<std::set<std::pair<double, int> >::iterator >& Qit,\n      Eigen::MatrixXd& C)\n   {\n\n      printf(\"in collapse edge func \\n\");\n\n      using namespace Eigen;\n\n      int e; \n      int e1; \n      int e2; \n      int f1; \n      int f2; \n\n\n      if (Q.empty()) {\n          printf(\"Q is empty\");\n          return false;\n      }\n      printf(\"QUEUE SIZE IS %d\", Q.size());\n\n      // now we know that the qeueu is not empty and we have some data in it\n      // we want to get the first pair , meaning the first edge - with the lowest cost? \n\n      std::pair<double, int> p = *(Q.begin());\n\n      if (p.first == std::numeric_limits<double>::infinity())\n      {\n          printf(\"its infinity - returning \\n\");\n          // min cost edge is infinite cost\n          return false;\n      }\n\n      // the first edge is not ininity and we want to remove it \n      // remember that the data of first edge is saved in p\n      Q.erase(Q.begin());\n      e = p.second;\n      Qit[e] = Q.end();\n      std::vector<int> N = igl::circulation(e, true, EMAP, EF, EI);\n      std::vector<int> Nd = igl::circulation(e, false, EMAP, EF, EI);\n      N.insert(N.begin(), Nd.begin(), Nd.end());\n\n \n\n      bool collapsed = this->collapse(e, C.row(e), V, F, E, EMAP, EF, EI, Qs, e1, e2, f1, f2);\n\n\n      if (collapsed) {\n          double cost_of_Edge = p.first;\n\n          printf(\"we collapsed the following edges : e -> %d , cost : %f     e1 -> %d  , cost: %f   e2 ->  , cost:    \", e, cost_of_Edge, e1, Qit[e1]->first);\n          // Erase the two, other collapsed edges\n          Q.erase(Qit[e1]);\n          Qit[e1] = Q.end();\n          Q.erase(Qit[e2]);\n          Qit[e2] = Q.end();\n\n         \n\n          // update local neighbors\n          // loop over original face neighbors\n          for (auto n : N)\n          {\n              if (F(n, 0) != IGL_COLLAPSE_EDGE_NULL ||\n                  F(n, 1) != IGL_COLLAPSE_EDGE_NULL ||\n                  F(n, 2) != IGL_COLLAPSE_EDGE_NULL)\n              {\n                  for (int v = 0; v < 3; v++)\n                  {\n                   \n                      const int ei = EMAP(v * F.rows() + n);\n                  \n                      Q.erase(Qit[ei]);\n                   \n                      double cost;\n                      RowVectorXd place;\n                      cost_and_placement(Qs, ei, V, F, E, EMAP, EF, EI, cost, place);\n                  \n                      Qit[ei] = Q.insert(std::pair<double, int>(cost, ei)).first;\n                      C.row(ei) = place;\n                  }\n              }\n          }\n      }\n      else\n      {\n    \n          p.first = std::numeric_limits<double>::infinity();\n          Qit[e] = Q.insert(p).first;\n      }\n      return collapsed;\n  }\n\n  IGL_INLINE bool Viewer::collapse(\n      const int e,\n      const Eigen::RowVectorXd& p,\n      Eigen::MatrixXd& V,\n      Eigen::MatrixXi& F,\n      Eigen::MatrixXi& E,\n      Eigen::VectorXi& EMAP,\n      Eigen::MatrixXi& EF,\n      Eigen::MatrixXi& EI,\n      std::vector<Eigen::Matrix<double, 4, 4>>& Qs,\n      int& a_e1,\n      int& a_e2,\n      int& a_f1,\n      int& a_f2)\n  {\n      // Assign this to 0 rather than, say, -1 so that deleted elements will get\n                 // draw as degenerate elements at vertex 0 (which should always exist and\n                 // never get collapsed to anything else since it is the smallest index)\n      using namespace Eigen;\n      using namespace std;\n      const int eflip = E(e, 0) > E(e, 1);\n      // source and destination\n      const int s = eflip ? E(e, 1) : E(e, 0);\n      const int d = eflip ? E(e, 0) : E(e, 1);\n\n      if (!igl::edge_collapse_is_valid(e, F, E, EMAP, EF, EI))\n      {\n          return false;\n      }\n\n      // Important to grab neighbors of d before monkeying with edges\n      const std::vector<int> nV2Fd = igl::circulation(e, !eflip, EMAP, EF, EI);\n\n      // The following implementation strongly relies on s<d\n      assert(s < d && \"s should be less than d\");\n      Qs[s] = Qs[s] + Qs[d];\n      // move source and destination to midpoint\n      V.row(s) = p;\n      V.row(d) = p;\n\n      // Helper function to replace edge and associate information with NULL\n      const auto& kill_edge = [&E, &EI, &EF](const int e)\n      {\n          E(e, 0) = IGL_COLLAPSE_EDGE_NULL;\n          E(e, 1) = IGL_COLLAPSE_EDGE_NULL;\n          EF(e, 0) = IGL_COLLAPSE_EDGE_NULL;\n          EF(e, 1) = IGL_COLLAPSE_EDGE_NULL;\n          EI(e, 0) = IGL_COLLAPSE_EDGE_NULL;\n          EI(e, 1) = IGL_COLLAPSE_EDGE_NULL;\n      };\n\n      // update edge info\n      // for each flap\n      const int m = F.rows();\n      for (int side = 0; side < 2; side++)\n      {\n          const int f = EF(e, side);\n          const int v = EI(e, side);\n          const int sign = (eflip == 0 ? 1 : -1) * (1 - 2 * side);\n          // next edge emanating from d\n          const int e1 = EMAP(f + m * ((v + sign * 1 + 3) % 3));\n          // prev edge pointing to s\n          const int e2 = EMAP(f + m * ((v + sign * 2 + 3) % 3));\n          assert(E(e1, 0) == d || E(e1, 1) == d);\n          assert(E(e2, 0) == s || E(e2, 1) == s);\n          // face adjacent to f on e1, also incident on d\n          const bool flip1 = EF(e1, 1) == f;\n          const int f1 = flip1 ? EF(e1, 0) : EF(e1, 1);\n          assert(f1 != f);\n          assert(F(f1, 0) == d || F(f1, 1) == d || F(f1, 2) == d);\n          // across from which vertex of f1 does e1 appear?\n          const int v1 = flip1 ? EI(e1, 0) : EI(e1, 1);\n          // Kill e1\n          kill_edge(e1);\n          // Kill f\n          F(f, 0) = IGL_COLLAPSE_EDGE_NULL;\n          F(f, 1) = IGL_COLLAPSE_EDGE_NULL;\n          F(f, 2) = IGL_COLLAPSE_EDGE_NULL;\n          // map f1's edge on e1 to e2\n          assert(EMAP(f1 + m * v1) == e1);\n          EMAP(f1 + m * v1) = e2;\n          // side opposite f2, the face adjacent to f on e2, also incident on s\n          const int opp2 = (EF(e2, 0) == f ? 0 : 1);\n          assert(EF(e2, opp2) == f);\n          EF(e2, opp2) = f1;\n          EI(e2, opp2) = v1;\n          // remap e2 from d to s\n          E(e2, 0) = E(e2, 0) == d ? s : E(e2, 0);\n          E(e2, 1) = E(e2, 1) == d ? s : E(e2, 1);\n          if (side == 0)\n          {\n              a_e1 = e1;\n              a_f1 = f;\n          }\n          else\n          {\n              a_e2 = e1;\n              a_f2 = f;\n          }\n      }\n\n      // finally, reindex faces and edges incident on d. Do this last so asserts\n      // make sense.\n      //\n      // Could actually skip first and last, since those are always the two\n      // collpased faces.\n      for (auto f : nV2Fd)\n      {\n          for (int v = 0; v < 3; v++)\n          {\n              if (F(f, v) == d)\n              {\n                  const int flip1 = (EF(EMAP(f + m * ((v + 1) % 3)), 0) == f) ? 1 : 0;\n                  const int flip2 = (EF(EMAP(f + m * ((v + 2) % 3)), 0) == f) ? 0 : 1;\n                  assert(\n                      E(EMAP(f + m * ((v + 1) % 3)), flip1) == d ||\n                      E(EMAP(f + m * ((v + 1) % 3)), flip1) == s);\n                  E(EMAP(f + m * ((v + 1) % 3)), flip1) = s;\n                  assert(\n                      E(EMAP(f + m * ((v + 2) % 3)), flip2) == d ||\n                      E(EMAP(f + m * ((v + 2) % 3)), flip2) == s);\n                  E(EMAP(f + m * ((v + 2) % 3)), flip2) = s;\n                  F(f, v) = s;\n                  break;\n              }\n          }\n      }\n      // Finally, \"remove\" this edge and its information\n      kill_edge(e);\n\n      return true;\n  }\n  IGL_INLINE bool Viewer::check_if_infinity(double first) {\n      return first == std::numeric_limits<double>::infinity();\n\n  }\n\n\n\n\n\n  IGL_INLINE bool Viewer::load_mesh_from_file(\n      const std::string & mesh_file_name_string)\n  {\n\n    // Create new data slot and set to selected\n    if(!(data().F.rows() == 0  && data().V.rows() == 0))\n    {\n      append_mesh();\n    }\n    data().clear();\n\n    size_t last_dot = mesh_file_name_string.rfind('.');\n    if (last_dot == std::string::npos)\n    {\n      std::cerr<<\"Error: No file extension found in \"<<\n        mesh_file_name_string<<std::endl;\n      return false;\n    }\n\n    std::string extension = mesh_file_name_string.substr(last_dot+1);\n\n    if (extension == \"off\" || extension ==\"OFF\")\n    {\n      Eigen::MatrixXd V;\n      Eigen::MatrixXi F;\n      if (!igl::readOFF(mesh_file_name_string, V, F))\n        return false;\n      data().set_mesh(V,F);\n    }\n    else if (extension == \"obj\" || extension ==\"OBJ\")\n    {\n      Eigen::MatrixXd corner_normals;\n      Eigen::MatrixXi fNormIndices;\n\n      Eigen::MatrixXd UV_V;\n      Eigen::MatrixXi UV_F;\n      Eigen::MatrixXd V;\n      Eigen::MatrixXi F;\n\n      if (!(\n            igl::readOBJ(\n              mesh_file_name_string,\n              V, UV_V, corner_normals, F, UV_F, fNormIndices)))\n      {\n        return false;\n      }\n\n      data().set_mesh(V,F);\n      if (UV_V.rows() > 0)\n      {\n          data().set_uv(UV_V, UV_F);\n      }\n\n    }\n    else\n    {\n      // unrecognized file type\n      printf(\"Error: %s is not a recognized file type.\\n\",extension.c_str());\n      return false;\n    }\n\n    data().compute_normals();\n    data().uniform_colors(Eigen::Vector3d(51.0/255.0,43.0/255.0,33.3/255.0),\n                   Eigen::Vector3d(255.0/255.0,228.0/255.0,58.0/255.0),\n                   Eigen::Vector3d(255.0/255.0,235.0/255.0,80.0/255.0));\n\n    // Alec: why?\n    if (data().V_uv.rows() == 0)\n    {\n      data().grid_texture();\n    }\n    \n\n    //for (unsigned int i = 0; i<plugins.size(); ++i)\n    //  if (plugins[i]->post_load())\n    //    return true;\n\n    return true;\n  }\n\n  IGL_INLINE bool Viewer::save_mesh_to_file(\n      const std::string & mesh_file_name_string)\n  {\n    // first try to load it with a plugin\n    //for (unsigned int i = 0; i<plugins.size(); ++i)\n    //  if (plugins[i]->save(mesh_file_name_string))\n    //    return true;\n\n    size_t last_dot = mesh_file_name_string.rfind('.');\n    if (last_dot == std::string::npos)\n    {\n      // No file type determined\n      std::cerr<<\"Error: No file extension found in \"<<\n        mesh_file_name_string<<std::endl;\n      return false;\n    }\n    std::string extension = mesh_file_name_string.substr(last_dot+1);\n    if (extension == \"off\" || extension ==\"OFF\")\n    {\n      return igl::writeOFF(\n        mesh_file_name_string,data().V,data().F);\n    }\n    else if (extension == \"obj\" || extension ==\"OBJ\")\n    {\n      Eigen::MatrixXd corner_normals;\n      Eigen::MatrixXi fNormIndices;\n\n      Eigen::MatrixXd UV_V;\n      Eigen::MatrixXi UV_F;\n\n      return igl::writeOBJ(mesh_file_name_string,\n          data().V,\n          data().F,\n          corner_normals, fNormIndices, UV_V, UV_F);\n    }\n    else\n    {\n      // unrecognized file type\n      printf(\"Error: %s is not a recognized file type.\\n\",extension.c_str());\n      return false;\n    }\n    return true;\n  }\n \n  IGL_INLINE bool Viewer::load_scene()\n  {\n    std::string fname = igl::file_dialog_open();\n    if(fname.length() == 0)\n      return false;\n    return load_scene(fname);\n  }\n\n  IGL_INLINE bool Viewer::load_scene(std::string fname)\n  {\n   // igl::deserialize(core(),\"Core\",fname.c_str());\n    igl::deserialize(data(),\"Data\",fname.c_str());\n    return true;\n  }\n\n  IGL_INLINE bool Viewer::save_scene()\n  {\n    std::string fname = igl::file_dialog_save();\n    if (fname.length() == 0)\n      return false;\n    return save_scene(fname);\n  }\n\n  IGL_INLINE bool Viewer::save_scene(std::string fname)\n  {\n    //igl::serialize(core(),\"Core\",fname.c_str(),true);\n    igl::serialize(data(),\"Data\",fname.c_str());\n\n    return true;\n  }\n\n  IGL_INLINE void Viewer::open_dialog_load_mesh()\n  {\n    std::string fname = igl::file_dialog_open();\n\n    if (fname.length() == 0)\n      return;\n    \n    this->load_mesh_from_file(fname.c_str());\n  }\n\n  IGL_INLINE void Viewer::open_dialog_save_mesh()\n  {\n    std::string fname = igl::file_dialog_save();\n\n    if(fname.length() == 0)\n      return;\n\n    this->save_mesh_to_file(fname.c_str());\n  }\n\n  IGL_INLINE ViewerData& Viewer::data(int mesh_id /*= -1*/)\n  {\n    assert(!data_list.empty() && \"data_list should never be empty\");\n    int index;\n    if (mesh_id == -1)\n      index = selected_data_index;\n    else\n      index = mesh_index(mesh_id);\n\n    assert((index >= 0 && index < data_list.size()) &&\n      \"selected_data_index or mesh_id should be in bounds\");\n    return data_list[index];\n  }\n\n  IGL_INLINE const ViewerData& Viewer::data(int mesh_id /*= -1*/) const\n  {\n    assert(!data_list.empty() && \"data_list should never be empty\");\n    int index;\n    if (mesh_id == -1)\n      index = selected_data_index;\n    else\n      index = mesh_index(mesh_id);\n\n    assert((index >= 0 && index < data_list.size()) &&\n      \"selected_data_index or mesh_id should be in bounds\");\n    return data_list[index];\n  }\n\n  IGL_INLINE int Viewer::append_mesh(bool visible /*= true*/)\n  {\n    assert(data_list.size() >= 1);\n\n    data_list.emplace_back();\n    selected_data_index = data_list.size()-1;\n    data_list.back().id = next_data_id++;\n    //if (visible)\n    //    for (int i = 0; i < core_list.size(); i++)\n    //        data_list.back().set_visible(true, core_list[i].id);\n    //else\n    //    data_list.back().is_visible = 0;\n    return data_list.back().id;\n  }\n\n  IGL_INLINE bool Viewer::erase_mesh(const size_t index)\n  {\n    assert((index >= 0 && index < data_list.size()) && \"index should be in bounds\");\n    assert(data_list.size() >= 1);\n    if(data_list.size() == 1)\n    {\n      // Cannot remove last mesh\n      return false;\n    }\n    data_list[index].meshgl.free();\n    data_list.erase(data_list.begin() + index);\n    if(selected_data_index >= index && selected_data_index > 0)\n    {\n      selected_data_index--;\n    }\n\n    return true;\n  }\n\n  IGL_INLINE size_t Viewer::mesh_index(const int id) const {\n    for (size_t i = 0; i < data_list.size(); ++i)\n    {\n      if (data_list[i].id == id)\n        return i;\n    }\n    return 0;\n  }\n\n\n\n  // ASSIGNMENT 1 - TASK 4\n\n  IGL_INLINE bool Viewer::load_mesh_from_configuration(const std::string config , bool assignment2) {\n    \n      if (assignment2)\n          return true;\n          //init_obj_collision();\n     \n     \n      else {\n          std::string mesh_path;\n          std::fstream infile;\n          infile.open(\"configuration.txt\");\n          if (!infile) {\n              std::cout << \"Can't open file configuration.txt\\n\";\n              return false;\n          }\n          else {\n              while (getline(infile, mesh_path)) {\n                  std::cout << \"opening \" << mesh_path << std::endl;\n                  this->load_mesh_from_file(mesh_path);\n                 // if (enable_simplefication) this->init_simplefication_objs();\n              }\n              infile.close();\n              return true;\n          }\n      }\n  }\n    \n\n\n  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n  //////////////////////////////////////////// ASSIGNMENT 2 //////////////////////////////////////////////////////////////////////\n\n\n  IGL_INLINE void Viewer::collission_init(const std::string config) {\n\n\n\n          std::string mesh_path;\n          std::fstream infile;\n        //  this->animating_collision = false;\n          infile.open(config);\n          if (!infile) {\n              std::cout << \"Can't open file configuration.txt\\n\";\n              return;\n          }\n          int mesh = 0; \n\n\n          printf(\"both opened \\n\");\n\n\n          /// <summary>\n          ///  in config we have 2 cubes\n          /// cube 1 and cube 2 \n          /// \n          /// the while will go over both and init trees for both object . \n          /// \n          /// \n          /// \n          /// </summary>\n     /*   while (getline(infile, mesh_path)) {\n\n              this->load_mesh_from_file(mesh_path);\n              this->data().MyTranslate(Eigen::Vector3f((mesh - 0.5) * 0.5, 0, 0), false);\n\n              igl::AABB<Eigen::MatrixXd, 3>* tree = new igl::AABB<Eigen::MatrixXd, 3>();\n              tree->init(this->data().V, this->data().F);\n              this->trees.push_back(tree);\n              this->tree_roots.push_back(tree);\n              this->last_box.push_back(&tree->m_box);\n\n              data().original_V = new Eigen::MatrixXd(this->data().V);\n              data().original_F = new Eigen::MatrixXi(this->data().F);\n\n              this->data().show_overlay_depth = false;\n              this->data().show_lines = false;\n              this->data().point_size = 1;\n              this->data().line_width = 1;\n              Eigen::RowVector3d red_color(1, 0, 0);\n              this->draw_m_box(this->selected_data_index, tree->m_box, red_color);\n              mesh++;\n          }*/\n      \n\n\n  }\n\n\n\n\n  Eigen::Matrix4d Viewer::CalcParentsTrans(int indx) \n  {\n\t  Eigen::Matrix4d prevTrans = Eigen::Matrix4d::Identity();\n\n\t  for (int i = indx; parents[i] >= 0; i = parents[i])\n\t  {\n\t\t  //std::cout << \"parent matrix:\\n\" << scn->data_list[scn->parents[i]].MakeTrans() << std::endl;\n\t\t  prevTrans = data_list[parents[i]].MakeTransd() * prevTrans;\n\t  }\n\n\t  return prevTrans;\n  }\n\n} // end namespace\n} // end namespace\n\n}\n", "meta": {"hexsha": "b3d42ea97b3f72aa865c3b0d97c2f596ab7909a7", "size": 26721, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "igl/opengl/glfw/Viewer.cpp", "max_stars_repo_name": "fadifrancis96/3d-animation-course-projects", "max_stars_repo_head_hexsha": "f35a4b40677e191ffcd0ea548b328c7e8c77160b", "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": "igl/opengl/glfw/Viewer.cpp", "max_issues_repo_name": "fadifrancis96/3d-animation-course-projects", "max_issues_repo_head_hexsha": "f35a4b40677e191ffcd0ea548b328c7e8c77160b", "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": "igl/opengl/glfw/Viewer.cpp", "max_forks_repo_name": "fadifrancis96/3d-animation-course-projects", "max_forks_repo_head_hexsha": "f35a4b40677e191ffcd0ea548b328c7e8c77160b", "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.0094339623, "max_line_length": 171, "alphanum_fraction": 0.5269263875, "num_tokens": 7434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213070736461, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2658476793271963}}
{"text": "/*****************************************************************************/\n/*  Copyright (c) 2015, Alessandro Pieropan                                  */\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 \"../include/pose_estimation.h\"\n#include <opencv2/calib3d/calib3d.hpp>\n#include <boost/math/constants/constants.hpp>\n#include \"../include/utilities.h\"\n#include <eigen3/Eigen/Geometry>\n#include <algorithm>\n#include <stdexcept>\n#include <iostream>\n\nusing namespace std;\nusing namespace cv;\nusing namespace Eigen;\n\nnamespace fato {\n\nvoid getPoseRansac(const std::vector<cv::Point3f>& model_points,\n                   const std::vector<cv::Point2f>& tracked_points,\n                   const cv::Mat& camera_model, int iterations, float distance,\n                   vector<int>& inliers, Mat& rotation, Mat& translation) {\n  if (model_points.size() > 4) {\n    Mat rotation_vect;\n    solvePnPRansac(model_points, tracked_points, camera_model,\n                   Mat::zeros(1, 8, CV_32F), rotation_vect, translation, false,\n                   iterations, distance, model_points.size(), inliers, CV_P3P);\n\n    try {\n      Rodrigues(rotation_vect, rotation);\n      rotation.convertTo(rotation, CV_32FC1);\n    } catch (cv::Exception& e) {\n      cout << \"Error estimating ransac rotation: \" << e.what() << endl;\n    }\n\n  } else {\n    rotation = Mat(3, 3, CV_32FC1, 0.0f);\n    translation = Mat(1, 3, CV_32FC1, 0.0f);\n  }\n}\n\nvoid getMatrices(const std::vector<cv::Point2f>& prev_pts,\n                 const std::vector<float>& prev_depth,\n                 const std::vector<cv::Point2f>& next_pts, float nodal_x,\n                 float nodal_y, float focal_x, float focal_y,\n                 Eigen::MatrixXf& A, Eigen::VectorXf& b) {\n  int valid_points = prev_pts.size();\n\n  A = Eigen::MatrixXf(valid_points * 2, 6);\n  b = Eigen::VectorXf(valid_points * 2);\n\n  float focal = (focal_x + focal_y) / 2.0;\n\n  for (auto i = 0; i < valid_points; ++i) {\n    float mz = prev_depth.at(i);\n    float x = next_pts.at(i).x - nodal_x;\n    float y = next_pts.at(i).y - nodal_y;\n    float xy = x * y / focal;\n\n    int id = 2 * i;\n    int id2 = id + 1;\n    // first equation for X, u flow\n    A(id, 0) = focal / mz;\n    A(id, 1) = 0;\n    A(id, 2) = -x / mz;\n    A(id, 3) = -xy;\n    A(id, 4) = focal + (x * x) / focal;\n    A(id, 5) = -y;\n    // second equation for X, v flow\n    A(id2, 0) = 0;\n    A(id2, 1) = focal / mz;\n    A(id2, 2) = -y / mz;\n    A(id2, 3) = -(focal + (x * x) / focal);\n    A(id2, 4) = xy;\n    A(id2, 5) = x;\n    // setting u,v flow in b vector\n    b[id] = next_pts.at(i).x - prev_pts.at(i).x;\n    b[id2] = next_pts.at(i).y - prev_pts.at(i).y;\n  }\n}\n\nvoid getPoseFromFlow(const std::vector<cv::Point2f>& prev_pts,\n                     const std::vector<float>& prev_depth,\n                     const std::vector<cv::Point2f>& next_pts, float nodal_x,\n                     float nodal_y, float focal_x, float focal_y,\n                     vector<float>& translation, vector<float>& rotation) {\n  int valid_points = prev_pts.size();\n\n  Eigen::MatrixXf A(valid_points * 2, 6);\n  Eigen::VectorXf b(valid_points * 2);\n\n  float focal = (focal_x + focal_y) / 2.0;\n\n  for (auto i = 0; i < prev_pts.size(); ++i) {\n    float mz = prev_depth.at(i);\n    float x = next_pts.at(i).x - nodal_x;\n    float y = next_pts.at(i).y - nodal_y;\n    float xy = x * y / focal;\n\n    int id = 2 * i;\n    int id2 = id + 1;\n    // first equation for X, u flow\n    A(id, 0) = focal / mz;\n    A(id, 1) = 0;\n    A(id, 2) = -x / mz;\n    A(id, 3) = -xy;\n    A(id, 4) = focal + (x * x) / focal;\n    A(id, 5) = -y;\n    // second equation for X, v flow\n    A(id2, 0) = 0;\n    A(id2, 1) = focal / mz;\n    A(id2, 2) = -y / mz;\n    A(id2, 3) = -(focal + (x * x) / focal);\n    A(id2, 4) = xy;\n    A(id2, 5) = x;\n    // setting u,v flow in b vector\n    b[id] = next_pts.at(i).x - prev_pts.at(i).x;\n    b[id2] = next_pts.at(i).y - prev_pts.at(i).y;\n  }\n\n  translation.resize(3, 0);\n  rotation.resize(3, 0);\n  // solving least square to find the 6 unknown parameters: tx,ty, tz, wx, wy,\n  // wz\n  Eigen::VectorXf Y = (A.transpose() * A).ldlt().solve(A.transpose() * b);\n\n  //  cout << \"LQ: \" << fixed << setprecision(3) << Y[0] << \" \" << Y[1] << \" \"\n  //  << Y[2] << \" \"\n  //                 << Y[3] << \" \" << Y[4] << \" \" << Y[5] << endl;\n\n  translation[0] = Y[0];\n  translation[1] = Y[1];\n  translation[2] = Y[2];\n\n  rotation[0] = Y[3];\n  rotation[1] = Y[4];\n  rotation[2] = Y[5];\n}\n\nEigen::VectorXf getPoseFromFlowRobust(const std::vector<cv::Point2f>& prev_pts,\n                           const std::vector<float>& prev_depth,\n                           const std::vector<cv::Point2f>& next_pts,\n                           float nodal_x, float nodal_y, float focal_x,\n                           float focal_y, int num_iters,\n                           std::vector<float>& translation,\n                           std::vector<float>& rotation,\n                           std::vector<int>& outliers) {\n  Eigen::MatrixXf X;\n  Eigen::VectorXf y;\n\n  getMatrices(prev_pts, prev_depth, next_pts, nodal_x, nodal_y, focal_x,\n              focal_y, X, y);\n\n  // during tracking possible to initialize with the previous estimation???\n  Eigen::VectorXf beta = (X.transpose() * X).ldlt().solve(X.transpose() * y);\n\n  Eigen::VectorXf W;\n  Eigen::MatrixXf XW(X.rows(), X.cols());\n\n  for (auto i = 0; i < num_iters; ++i) {\n    // cout << \"iter \" << i;// << endl;\n\n    Eigen::VectorXf residuals = ((X * beta) - y);\n    residuals = residuals.array().abs();\n\n    // cout << residuals << endl;\n\n    std::vector<float> res_vector(residuals.rows(), 0);\n\n    for (int j = 0; j < residuals.rows(); ++j) {\n      res_vector.at(j) = residuals(j);\n    }\n\n    sort(res_vector.begin(), res_vector.end());\n\n    float residual_scale;\n    if (res_vector.size() % 2 != 0)\n      residual_scale = res_vector.at(res_vector.size() / 2);\n    else\n      residual_scale = res_vector.at(res_vector.size() / 2) +\n                       res_vector.at(res_vector.size() / 2 + 1) / 2.0f;\n\n    // avoid division by 0\n    residual_scale = max(residual_scale, 0.0001f);\n\n    residual_scale *=\n        6.9460;  // constant defined in the IRLS and bisquare distance\n\n    W = residuals / residual_scale;\n\n    for (auto j = 0; j < W.rows(); ++j) {\n      if (W(j) > 1) {\n        W(j) = 0;\n      } else {\n        auto tmp = 1 - W(j) * W(j);\n        W(j) = tmp * tmp;\n      }\n    }\n\n    for (auto j = 0; j < XW.rows(); ++j) {\n      for (auto k = 0; k < XW.cols(); ++k) {\n        XW(j, k) = W(j) * X(j, k);\n      }\n    }\n\n    beta = (XW.transpose() * X).ldlt().solve(XW.transpose() * y);\n  }\n\n  // cout << \"\\n here\" << endl;\n\n  int num_points = W.rows() / 2;\n\n  for (auto j = 0; j < num_points; ++j) {\n    int id = 2 * j;\n    if (W(id) == 0 || W(id + 1) == 0) {\n      outliers.push_back(j);\n    }\n  }\n\n  translation.resize(3, 0);\n  rotation.resize(3, 0);\n\n  translation[0] = beta[0];\n  translation[1] = beta[1];\n  translation[2] = beta[2];\n\n  rotation[0] = beta[3];\n  rotation[1] = beta[4];\n  rotation[2] = beta[5];\n\n  return beta;\n}\n\nvoid getPose2D(const std::vector<cv::Point2f*>& model_points,\n               const std::vector<cv::Point2f*>& tracked_points, float& scale,\n               float& angle) {\n  vector<double> angles;\n  vector<float> scales;\n\n  angles.reserve(model_points.size() * 2);\n  scales.reserve(model_points.size() * 2);\n\n  const double pi = boost::math::constants::pi<double>();\n\n  for (size_t i = 0; i < model_points.size(); ++i) {\n    for (size_t j = 0; j < model_points.size(); j++) {\n      // computing angle\n      Point2f a = *tracked_points.at(i) - *tracked_points.at(j);\n      Point2f b = *model_points.at(i) - *model_points.at(j);\n      double val = atan2(a.y, a.x) - atan2(b.y, b.x);\n\n      if (abs(val) > pi) {\n        int sign = (val < 0) ? -1 : 1;\n        val = val - sign * 2 * pi;\n      }\n      angles.push_back(val);\n\n      if (i == j) continue;\n\n      // computing scale\n      auto tracked_dis =\n          getDistance(tracked_points.at(i), tracked_points.at(j));\n      auto model_dis = getDistance(model_points.at(i), model_points.at(j));\n      if (model_dis != 0) scales.push_back(tracked_dis / model_dis);\n    }\n  }\n\n  sort(angles.begin(), angles.end());\n  sort(scales.begin(), scales.end());\n\n  auto angles_size = angles.size();\n  auto scale_size = scales.size();\n\n  if (angles_size == 0)\n    angle = 0;\n\n  else if (angles_size % 2 == 0)\n    angle = (angles[angles_size / 2 - 1] + angles[angles_size / 2]) / 2;\n  else\n    angle = angles[angles_size / 2];\n\n  if (scale_size == 0)\n    scale = 1;\n  else if (scale_size % 2 == 0)\n    scale = (scales[scale_size / 2 - 1] + scales[scale_size / 2]) / 2;\n  else\n    scale = scales[scale_size / 2];\n}\n\n// TODO: implement ransac approach for better SVD estimation\nMat getRigidTransform(Mat& a, Mat& b) {\n  int numRows = a.rows;\n\n  vector<float> srcM = {0, 0, 0};\n  vector<float> dstM = {0, 0, 0};\n\n  // compute centroid of the two sets of points\n  for (int i = 0; i < numRows; i++) {\n    for (int j = 0; j < 3; j++) {\n      srcM[j] += a.at<float>(i, j);\n      dstM[j] += b.at<float>(i, j);\n    }\n  }\n\n  for (int i = 0; i < 3; i++) {\n    srcM[i] = srcM[i] / static_cast<float>(numRows);\n    dstM[i] = dstM[i] / static_cast<float>(numRows);\n  }\n\n  Mat AA, BB, AA_T, BB_T;\n  a.copyTo(AA);\n  b.copyTo(BB);\n  // subtracting centroid from all the points\n  for (int i = 0; i < numRows; i++) {\n    for (int j = 0; j < 3; j++) {\n      AA.at<float>(i, j) -= srcM[j];\n      BB.at<float>(i, j) -= dstM[j];\n    }\n  }\n\n  transpose(AA, AA_T);\n\n  Mat3f H;\n  H = AA_T * BB;\n\n  // cout << \"H\\n\" << H << endl;\n\n  Mat w, u, vt, vt_T, u_T;\n  SVD::compute(H, w, u, vt);\n\n  transpose(vt, vt_T);\n  transpose(u, u_T);\n\n  Mat3f R;\n  R = vt_T * u_T;\n\n  // reflection case\n  if (determinant(R) < 0) {\n    for (size_t i = 0; i < 3; i++) {\n      vt.at<float>(2, i) *= -1;\n    }\n    transpose(vt, vt_T);\n    R = vt_T * u_T;\n  }\n\n  return R;\n}\n\nMat getRigidTransform(Mat& a, Mat& b, vector<float>& cA, vector<float>& cB) {\n  int numRows = a.rows;\n\n  vector<float>& srcM = cA;\n  vector<float>& dstM = cB;\n\n  Mat AA, BB, AA_T, BB_T;\n  a.copyTo(AA);\n  b.copyTo(BB);\n  // subtracting centroid from all the points\n  for (int i = 0; i < numRows; i++) {\n    for (int j = 0; j < 3; j++) {\n      AA.at<float>(i, j) -= srcM[j];\n      BB.at<float>(i, j) -= dstM[j];\n    }\n  }\n\n  transpose(AA, AA_T);\n\n  Mat3f H;\n  H = AA_T * BB;\n\n  Mat w, u, vt, vt_T, u_T;\n  SVD::compute(H, w, u, vt);\n\n  transpose(vt, vt_T);\n  transpose(u, u_T);\n\n  Mat3f R;\n  R = vt_T * u_T;\n\n  // reflection case\n  if (determinant(R) < 0) {\n    for (size_t i = 0; i < 3; i++) {\n      vt.at<float>(2, i) *= -1;\n    }\n    transpose(vt, vt_T);\n    R = vt_T * u_T;\n  }\n\n  return R;\n}\n\nvoid rotateBBox(const vector<Point3f>& bBox, const Mat& rotation,\n                vector<Point3f>& updatedBBox) {\n  Mat a(4, 3, CV_32FC1);\n  Mat b, b_T, a_T;\n\n  for (size_t i = 0; i < 4; i++) {\n    a.at<float>(i, 0) = bBox.at(i).x;\n    a.at<float>(i, 1) = bBox.at(i).y;\n    a.at<float>(i, 2) = bBox.at(i).z;\n  }\n\n  transpose(a, a_T);\n\n  b_T = rotation * a_T;\n  transpose(b_T, b);\n\n  for (size_t i = 0; i < 4; i++) {\n    updatedBBox.push_back(\n        Point3f(b.at<float>(i, 0), b.at<float>(i, 1), b.at<float>(i, 2)));\n  }\n}\n\nvoid rotatePoint(const Point3f& point, const Mat& rotation,\n                 Point3f& updatedPoint) {\n  Mat a(1, 3, CV_32FC1);\n  a.at<float>(0) = point.x;\n  a.at<float>(1) = point.y;\n  a.at<float>(2) = point.z;\n  Mat b, b_T, a_T;\n\n  transpose(a, a_T);\n  b_T = rotation * a_T;\n  transpose(b_T, b);\n\n  updatedPoint.x = b.at<float>(0);\n  updatedPoint.y = b.at<float>(1);\n  updatedPoint.z = b.at<float>(2);\n}\n\nvoid rotatePoint(const Vec3f& point, const Mat& rotation, Vec3f& updatedPoint) {\n  Mat a(1, 3, CV_32FC1);\n  a.at<float>(0) = point[0];\n  a.at<float>(1) = point[1];\n  a.at<float>(2) = point[2];\n  Mat b, b_T, a_T;\n\n  transpose(a, a_T);\n  b_T = rotation * a_T;\n  transpose(b_T, b);\n\n  updatedPoint[0] = b.at<float>(0);\n  updatedPoint[1] = b.at<float>(1);\n  updatedPoint[2] = b.at<float>(2);\n}\n\nvoid rotatePoint(const Vec3f& point, const Mat& rotation,\n                 Point3f& updatedPoint) {\n  Mat a(1, 3, CV_32FC1);\n  a.at<float>(0) = point[0];\n  a.at<float>(1) = point[1];\n  a.at<float>(2) = point[2];\n  Mat b, b_T, a_T;\n\n  transpose(a, a_T);\n  b_T = rotation * a_T;\n  transpose(b_T, b);\n\n  updatedPoint.x = b.at<float>(0);\n  updatedPoint.y = b.at<float>(1);\n  updatedPoint.z = b.at<float>(2);\n}\n\nvoid rotationVecToMat(const Mat& vec, Mat& mat) {}\n\n/**************************************************************/\n/*           POSE CLASS                                       */\n/**************************************************************/\n\nPose::Pose() { pose_ = Matrix4d(4, 4); }\n\nPose::Pose(Mat& r_mat, Mat& t_vect) {\n  pose_ = Matrix4d(4, 4);\n\n  if (t_vect.cols != 3 && t_vect.rows != 3) {\n    cout << t_vect.cols << \" \" << t_vect.rows << endl;\n    throw std::runtime_error(\n        \"Pose: bad translation vector format, 3x1 accepted\");\n  }\n\n  Mat tmp_rot, tmp_t;\n  r_mat.convertTo(tmp_rot, CV_64FC1);\n  t_vect.convertTo(tmp_t, CV_64FC1);\n\n  if (tmp_rot.cols == 3 && tmp_rot.rows == 3) {\n    for (int i = 0; i < 3; ++i) {\n      for (int j = 0; j < 3; ++j) {\n        pose_(i, j) = tmp_rot.at<double>(i, j);\n      }\n      pose_(i, 3) = tmp_t.at<double>(i);\n      pose_(3, i) = 0;\n    }\n    pose_(3, 3) = 1;\n  } else if (r_mat.cols == 3 && r_mat.cols == 1) {\n    Eigen::Matrix3d rot_view;\n    rot_view =\n        Eigen::AngleAxisd(tmp_rot.at<double>(2), Eigen::Vector3d::UnitZ()) *\n        Eigen::AngleAxisd(tmp_rot.at<double>(1), Eigen::Vector3d::UnitY()) *\n        Eigen::AngleAxisd(tmp_rot.at<double>(0), Eigen::Vector3d::UnitX());\n\n    for (int i = 0; i < 3; ++i) {\n      for (int j = 0; j < 3; ++j) {\n        pose_(i, j) = rot_view(i, j);\n      }\n      pose_(i, 3) = tmp_t.at<double>(i);\n      pose_(3, i) = 0;\n    }\n    pose_(3, 3) = 1;\n  } else {\n    throw std::runtime_error(\n        \"Pose: bad rotation matrix format, 3x3 or 1x3 accepted\");\n  }\n\n  init_rot = r_mat;\n  init_tr = t_vect;\n}\n\nPose::Pose(Matrix4d& pose) {\n  pose_ = Matrix4d(4, 4);\n\n  for (auto i = 0; i < 4; ++i) {\n    for (auto j = 0; j < 4; ++j) {\n      pose_(i, j) = pose(i, j);\n    }\n  }\n}\n\nPose::Pose(std::vector<double>& beta) {\n  if (beta.size() != 6) {\n    throw std::runtime_error(\"Pose: bad parameters size, should be 6\");\n  }\n\n  pose_ = Matrix4d(4, 4);\n\n  Eigen::Matrix3d rot_view;\n  rot_view = Eigen::AngleAxisd(beta.at(5), Eigen::Vector3d::UnitZ()) *\n             Eigen::AngleAxisd(beta.at(4), Eigen::Vector3d::UnitY()) *\n             Eigen::AngleAxisd(beta.at(3), Eigen::Vector3d::UnitX());\n\n  for (int i = 0; i < 3; ++i) {\n    for (int j = 0; j < 3; ++j) {\n      pose_(i, j) = rot_view(i, j);\n    }\n    pose_(3, i) = 0;\n  }\n  pose_(3, 3) = 1;\n\n  pose_(0, 3) = beta.at(0);\n  pose_(1, 3) = beta.at(1);\n  pose_(2, 3) = beta.at(2);\n\n  init_beta_ = beta;\n}\n\nPose::Pose(VectorXf &beta)\n{\n    if (beta.rows() != 6) {\n      throw std::runtime_error(\"Pose: bad parameters size, should be 6\");\n    }\n\n    init_beta_.resize(6,0);\n\n    for(auto i = 0; i < 6; ++i)\n        init_beta_[i] = static_cast<double>(beta[i]);\n\n    pose_ = Matrix4d(4, 4);\n\n    Eigen::Matrix3d rot_view;\n    rot_view = Eigen::AngleAxisd(init_beta_.at(5), Eigen::Vector3d::UnitZ()) *\n               Eigen::AngleAxisd(init_beta_.at(4), Eigen::Vector3d::UnitY()) *\n               Eigen::AngleAxisd(init_beta_.at(3), Eigen::Vector3d::UnitX());\n\n    for (int i = 0; i < 3; ++i) {\n      for (int j = 0; j < 3; ++j) {\n        pose_(i, j) = rot_view(i, j);\n      }\n      pose_(3, i) = 0;\n    }\n    pose_(3, 3) = 1;\n\n    pose_(0, 3) = init_beta_.at(0);\n    pose_(1, 3) = init_beta_.at(1);\n    pose_(2, 3) = init_beta_.at(2);\n}\n\nstd::pair<cv::Mat, cv::Mat> Pose::toCV() const {\n  cv::Mat rotation = cv::Mat(3, 3, CV_64FC1, 0.0f);\n  cv::Mat translation = cv::Mat(1, 3, CV_64FC1, 0.0f);\n\n  for (int i = 0; i < 3; ++i) {\n    for (int j = 0; j < 3; ++j) {\n      rotation.at<double>(i, j) = pose_(i, j);\n    }\n    translation.at<double>(i) = pose_(i, 3);\n  }\n\n  return pair<cv::Mat, cv::Mat>(rotation, translation);\n}\n\nstd::pair<Eigen::Matrix3d, Eigen::Vector3d> Pose::toEigen() const\n{\n    Eigen::Matrix3d rotation_temp;\n    Eigen::Vector3d translation_vect;\n    for(auto i = 0; i < 3; ++i)\n    {\n        for(auto j = 0; j < 3; ++j)\n        {\n          rotation_temp(i,j) = pose_(i,j);\n        }\n        translation_vect(i) = pose_(i,3);\n    }\n\n    return pair<Eigen::Matrix3d, Eigen::Vector3d>(rotation_temp, translation_vect);\n}\n\nglm::mat4 Pose::toGL() const\n{\n\n    Eigen::Matrix4d Rx_180 = Eigen::Matrix<double, 4, 4>::Identity();\n          Rx_180(1, 1) = -1.0;\n          Rx_180(2, 2) = -1.0;\n    auto pose = Rx_180 * pose_;\n\n    glm::mat4 pose_glm;\n\n    for(auto i = 0; i < 4; ++i)\n    {\n        for(auto j = 0; j < 4; ++j)\n        {\n          pose_glm[j][i] = pose(i,j);\n        }\n    }\n\n    return pose_glm;\n}\n\n\nvoid Pose::transform(Eigen::Matrix4d& transform) { pose_ = transform * pose_; }\n\n\nvoid Pose::transform(std::vector<double> &beta)\n{\n\n    Eigen::Matrix3d rot_view;\n    rot_view = Eigen::AngleAxisd(beta.at(5), Eigen::Vector3d::UnitZ()) *\n               Eigen::AngleAxisd(beta.at(4), Eigen::Vector3d::UnitY()) *\n               Eigen::AngleAxisd(beta.at(3), Eigen::Vector3d::UnitX());\n\n    Eigen::Matrix4d transform;\n\n    for(auto i = 0; i < 3; ++i)\n    {\n        for(auto j = 0; j < 3; ++j)\n        {\n            transform(i,j) = rot_view(i,j);\n        }\n        transform(i,3) = beta[i];\n        transform(3,i) = 0;\n    }\n    transform(3,3) = 1;\n\n//    Eigen::Matrix4d Rx_180 = Eigen::Matrix<double, 4, 4>::Identity();\n//    Rx_180(1, 1) = -1.0;\n//    Rx_180(2, 2) = -1.0;\n\n//    transform = Rx_180 * transform;\n\n    pose_ = transform * pose_;\n}\n\nvector<double> Pose::getBeta() {\n  Eigen::Matrix3d tmp_mat(3, 3);\n\n  for (auto i = 0; i < 3; ++i) {\n    for (auto j = 0; j < 3; ++j) tmp_mat(i, j) = pose_(i, j);\n  }\n\n  Eigen::Vector3d angles = tmp_mat.eulerAngles(2, 1, 0);\n\n  vector<double> tmp = {pose_(0, 3), pose_(1, 3), pose_(2, 3),\n                        angles(2),   angles(1),   angles(0)};\n\n  return tmp;\n}\n\nvector<double> Pose::translation() const\n{\n    return vector<double>{pose_(0, 3), pose_(1, 3), pose_(2, 3)};\n}\n\nEigen::Quaternionf Pose::rotation() const\n{\n    Eigen::Matrix3f tmp_mat(3, 3);\n\n    for (auto i = 0; i < 3; ++i) {\n      for (auto j = 0; j < 3; ++j) tmp_mat(i, j) = (float)pose_(i, j);\n    }\n\n    return Quaternionf(tmp_mat);\n}\n\nstring Pose::str() const {\n  stringstream ss;\n  ss << fixed << setprecision(3);\n\n  for (auto i = 0; i < 4; ++i) {\n    for (auto j = 0; j < 4; ++j) {\n      ss << pose_(i, j) << \" \";\n    }\n    ss << \"\\n\";\n  }\n\n  return ss.str();\n}\n\n}  // end namespace\n", "meta": {"hexsha": "637354da1a75aa62c5af19b991838df6634dfb5a", "size": 20964, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tracker/src/pose_estimation.cpp", "max_stars_repo_name": "clickcao/fato", "max_stars_repo_head_hexsha": "d2de665e83f82ea1094f488102aba37a8cdd53bb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-07-31T04:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-31T04:11:32.000Z", "max_issues_repo_path": "tracker/src/pose_estimation.cpp", "max_issues_repo_name": "clickcao/fato", "max_issues_repo_head_hexsha": "d2de665e83f82ea1094f488102aba37a8cdd53bb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tracker/src/pose_estimation.cpp", "max_forks_repo_name": "clickcao/fato", "max_forks_repo_head_hexsha": "d2de665e83f82ea1094f488102aba37a8cdd53bb", "max_forks_repo_licenses": ["BSD-3-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.1018766756, "max_line_length": 83, "alphanum_fraction": 0.5324842587, "num_tokens": 6700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.2657990767491}}
{"text": "// polyvec\n#include <polyvec/geometry/winding_number.hpp>\n#include <polyvec/mc/raster_image_connectivity.hpp>\n#include <polyvec/mc/get_bounding_box.hpp>\n#include <polyvec/mc/bit_vector.hpp>\n#include <polyvec/mc/associate_holes.hpp>\n\n// libc++\n#include <cstdio>\n#include <memory>\n\n// eigen\n#include <Eigen/Geometry>\n\nNAMESPACE_BEGIN ( polyfit )\nNAMESPACE_BEGIN ( mc )\n\n\nconstexpr int RasterImageConnectivity::infinite_region;\n\nEigen::Vector2i\nRasterImageConnectivity::pixel_vertex_index_to_pos ( const int index ) {\n    return Eigen::Vector2i ( index % pixel_vertex_dims().x(), index / pixel_vertex_dims().x() );\n}\n\nint\nRasterImageConnectivity::pixel_vertex_pos_to_index ( const Eigen::Vector2i& pos ) {\n    return pos.x() + pos.y() * pixel_vertex_dims().x();\n}\n\n\nint\nRasterImageConnectivity::n_pixel_vertices() {\n    return pixel_vertex_dims().x() * pixel_vertex_dims().y();\n}\n\nconst Eigen::Vector2i&\nRasterImageConnectivity::pixel_vertex_dims() const {\n    return _pixel_vertex_dims;\n}\n\nMesh_connectivity&\nRasterImageConnectivity::connectivity() {\n    return _connectivity;\n}\n\nint\nRasterImageConnectivity::n_polygons() {\n    return connectivity().n_active_faces();\n}\n\nint\nRasterImageConnectivity::n_regions() {\n    return _n_regions;\n}\n\nint\nRasterImageConnectivity::n_region_polygons ( const int region_id ) {\n    assert_break ( region_id < n_regions() );\n    const int ans= _region_to_polygon_xval[region_id+1]-_region_to_polygon_xval[region_id];\n    assert_break ( ans >= 1 );\n    return ans;\n}\n\nint\nRasterImageConnectivity::polygon_to_region ( const int polygon_id ) {\n    assert_break ( polygon_id < n_polygons() );\n    return _polygon_to_region[ polygon_id ];\n}\n\nvoid\nRasterImageConnectivity::region_to_polygon ( const int region_id, int& outer_boundary, std::vector<int>& holes ) {\n    outer_boundary = _region_to_polygon_val[ _region_to_polygon_xval[ region_id ] ];\n    assert_break ( outer_boundary == region_id );\n\n    holes.resize ( 0 );\n    holes.reserve ( std::max ( 0, n_region_polygons ( region_id )-1 ) );\n\n    for ( int j= _region_to_polygon_xval[ region_id ]+1 ; j < _region_to_polygon_xval[ region_id+1 ] ; ++j ) {\n        holes.push_back (  _region_to_polygon_val [j] );\n    }\n}\n\nRasterImageConnectivity::PolygonType\nRasterImageConnectivity::get_polygon_type ( const int polygon_id ) {\n    if ( polygon_id < n_regions() ) {\n        return POLYGON_OUTER_BOUNDARY;\n    } else if ( polygon_id < n_polygons() ) {\n        return POLGYON_HOLE ;\n    } else {\n        assert_break ( 0 );\n        return POLYGON_INVALID;\n    }\n}\n\nEigen::Matrix2Xi\nRasterImageConnectivity::get_polygon_points ( const int pid ) {\n    // Lambda to extract the points on polygon\n    std::vector<int> points;\n\n    Mesh_connectivity::Face_iterator face = connectivity().face_at ( pid );\n    Mesh_connectivity::Half_edge_iterator he_end = face.half_edge();\n    Mesh_connectivity::Half_edge_iterator he = he_end;\n\n    int safe_guard = 0;\n    const int safe_gaurd_cap = 10000;\n\n    do {\n        Eigen::Vector2i pos =  pixel_vertex_index_to_pos ( he.origin().index() );\n        points.push_back ( pos.x() );\n        points.push_back ( pos.y() );\n        assert_break ( safe_guard < safe_gaurd_cap );\n        ++safe_guard;\n        he = he.next();\n    } while ( !he.is_equal ( he_end ) );\n\n    return Eigen::Matrix2Xi::ConstMapType ( points.data(), 2, points.size() /2 );\n}\n\nstd::vector<int>\nRasterImageConnectivity::regions_sorted_by_area() {\n    std::vector<int> by_area(n_regions());\n    std::vector<double> areas(n_regions());\n    for (int i = 0; i < (int)by_area.size(); ++i) {\n      by_area[i] = i;\n      bool _1;\n      Eigen::Matrix2Xi bdry = get_polygon_points(i);\n      polyvec::WindingNumber::compute_orientation(bdry.cast<double>(), _1,\n                                                  areas[i]);\n    }\n    std::sort(by_area.begin(), by_area.end(),\n              [areas](int i, int j) { return areas[i] > areas[j]; });\n\n    return by_area;\n}\n\n\n\n// dump as vtk for debugging\nvoid\nRasterImageConnectivity::dump_as_vtk ( const std::string filename ) {\n\n    // Defrag the mesh\n    Mesh_connectivity::Defragmentation_maps defrag;\n    connectivity().compute_defragmention_maps ( defrag );\n\n\n    FILE* fl = fopen ( filename.c_str(), \"w\" );\n    assert_break ( fl && \"FILE should be open\" );\n\n    /*\n     * Write the vtk file.\n     */\n\n    // write the header\n    fprintf ( fl, \"# vtk DataFile Version 2.0\\n\" );\n    fprintf ( fl, \"Shayan's output mesh\\n\" );\n    fprintf ( fl, \"ASCII\\n\" );\n    fprintf ( fl, \"DATASET UNSTRUCTURED_GRID\\n\" );\n    fprintf ( fl, \"\\n\" );\n\n    // write the vertices\n    fprintf ( fl, \"POINTS %d float\\n\", connectivity().n_active_vertices() );\n\n    for ( int vnidx = 0; vnidx < connectivity().n_active_vertices(); vnidx++ ) {\n        int voidx = defrag.new2old_vertices[vnidx];\n        Eigen::Vector2i pos = pixel_vertex_index_to_pos ( voidx );\n        fprintf ( fl, \"%d %d 0 \\n\",  pos.x(), pos.y() );\n    }\n\n    fprintf ( fl, \"\\n\" );\n\n    //\n    // write the faces\n    //\n\n    // count their total number of vertices.\n    int total_vert_duplicated_per_face = 0;\n\n    for ( int fn = 0; fn < connectivity().n_active_faces(); ++fn ) {\n        int fo = defrag.new2old_faces[fn];\n        Mesh_connectivity::Face_iterator face = connectivity().face_at ( fo );\n        Mesh_connectivity::Half_edge_iterator he_end = face.half_edge();\n        Mesh_connectivity::Half_edge_iterator he = face.half_edge();\n\n        do {\n            ++total_vert_duplicated_per_face;\n            he = he.next();\n        } while ( !he.is_equal ( he_end ) );\n    }\n\n    int face_verts_cache[4096]; // this must be more than maximum number of edges per face.\n    fprintf ( fl, \"CELLS %d %d \\n\", connectivity().n_active_faces(), connectivity().n_active_faces() + total_vert_duplicated_per_face );\n\n    for ( int fn = 0; fn < connectivity().n_active_faces(); ++fn ) {\n        int fo = defrag.new2old_faces[fn];\n        Mesh_connectivity::Face_iterator face = connectivity().face_at ( fo );\n        int n_verts = 0;\n        Mesh_connectivity::Half_edge_iterator he_end = face.half_edge();\n        Mesh_connectivity::Half_edge_iterator he = face.half_edge();\n\n        do {\n            face_verts_cache[n_verts] = defrag.old2new_vertices[he.origin().index()];\n            ++n_verts;\n            he = he.next();\n        } while ( !he.is_equal ( he_end ) );\n\n        fprintf ( fl, \"%d \", n_verts );\n\n        for ( int voffset = 0; voffset < n_verts; ++voffset ) {\n            //\n            fprintf ( fl, \"%d \", face_verts_cache[voffset] );\n        }\n\n        fprintf ( fl, \"\\n\" );\n    }\n\n    fprintf ( fl, \"\\n\" );\n\n    // write the face types\n    fprintf ( fl, \"CELL_TYPES %d \\n\", connectivity().n_active_faces() );\n\n    for ( int f = 0; f < connectivity().n_active_faces(); f++ ) {\n        fprintf ( fl, \"7 \\n\" ); // VTK POLYGON\n    }\n\n    fprintf ( fl, \"\\n\" );\n\n\n    // Now write the pixel indices\n    fprintf ( fl, \"POINT_DATA %d \\n\", connectivity().n_active_vertices() );\n\n//\n    fprintf ( fl, \"SCALARS %s int 1 \\n\", \"pixel_point_index\" );\n    fprintf ( fl, \"LOOKUP_TABLE default \\n\" );\n\n    for ( int i = 0; i < connectivity().n_active_vertices(); i++ ) {\n        int voidx = defrag.new2old_vertices[i];\n        fprintf ( fl, \"%d \\n\", voidx );\n    }\n\n// Write region colors?\n    fprintf ( fl, \"CELL_DATA %d \\n\", connectivity().n_active_faces() );\n\n//\n    fprintf ( fl, \"SCALARS %s int 1 \\n\", \"region_index\" );\n    fprintf ( fl, \"LOOKUP_TABLE default \\n\" );\n\n    for ( int i = 0; i < connectivity().n_active_faces(); i++ ) {\n        fprintf ( fl, \"%d \\n\", i );\n    }\n\n    fclose ( fl );\n}\n\nvoid\nRasterImageConnectivity::enumerate_holes ( Mesh_connectivity& pixconn, std::vector<int>& half_edge_on_hole ) {\n    assert_break ( pixconn.n_active_half_edges() == pixconn.n_total_half_edges() );\n    assert_break ( pixconn.n_active_faces() == pixconn.n_total_faces() );\n\n    // Start marking all the half-edges\n    Bit_vector is_half_edge_marked ( pixconn.n_active_half_edges() );\n\n    // A lambda to traverse a hole and mark all the half edges on it\n    auto traverse_bounday = [&] ( const int seed_he ) {\n        Mesh_connectivity::Half_edge_iterator he_end = pixconn.half_edge_at ( seed_he );\n        Mesh_connectivity::Half_edge_iterator he = he_end;\n        assert_break ( he.face().is_equal ( pixconn.hole() ) );\n\n        int safe_guard = 0;\n        const int safe_gaurd_cap = 10000;\n\n        do {\n            is_half_edge_marked.set ( he.index() );\n            assert_break ( safe_guard < safe_gaurd_cap );\n            ++safe_guard;\n            he = he.next();\n        } while ( !he.is_equal ( he_end ) );\n    };\n\n    // Loop over all half-edges, if not marked and boundary, it is a hole\n    half_edge_on_hole.resize ( 0 );\n\n    for ( int heid = 0 ; heid < pixconn.n_total_half_edges() ; ++heid ) {\n        Mesh_connectivity::Half_edge_iterator he = pixconn.half_edge_at ( heid );\n\n        if ( he.face().is_equal ( pixconn.hole() ) && ( !is_half_edge_marked[heid] ) ) {\n            half_edge_on_hole.push_back ( heid );\n            traverse_bounday ( heid );\n        }\n    }\n}\n\n// constructor\nRasterImageConnectivity\nRasterImageConnectivity::build ( const std::vector<Eigen::Matrix2Xi>& region_boundaries ) {\n\n    RasterImageConnectivity ans;\n\n    //\n    // First find the bounding box of the image\n    //\n    {\n        Eigen::AlignedBox<int, 2> bbox = get_bounding_box ( region_boundaries );\n        // Make sure min is 0,0. This must have been done in get_pixel_regions()\n        assert_break ( bbox.min() == Eigen::Vector2i ( 0, 0 ) );\n        // Set the dims to the max\n        ans._pixel_vertex_dims = bbox.max()+Eigen::Vector2i ( 1, 1 );\n    }\n\n    //\n    // Now bould the connectivity by treating each region as a BIG polygon\n    //\n    {\n        std::vector<int> polygon_verts;\n        std::vector<int> polygon_xadj = {0};\n\n        for ( int i = 0 ; i < ( int ) region_boundaries.size() ; ++i ) {\n            polygon_xadj.push_back ( polygon_xadj.back() );\n            const Eigen::Matrix2Xi& region_boundary = region_boundaries[i];\n\n            for ( int j = 0 ; j < ( int ) region_boundary.cols() ; ++j ) {\n                polygon_verts.push_back ( ans.pixel_vertex_pos_to_index ( region_boundary.col ( j ) ) );\n                ++polygon_xadj.back();\n            }\n        }\n\n        ans._connectivity.build_from_polygons ( ans.n_pixel_vertices(), polygon_verts, polygon_xadj );\n    }\n\n    //\n    // Now get all the holes and add them\n    // Even the outer boundary -- it should be fine\n    //\n    {\n        Mesh_connectivity& pixconn = ans.connectivity();\n\n        // Set number of regions\n        ans._n_regions = ( int ) region_boundaries.size();\n\n        // A lambda to modify the connectivity\n        auto associate_face_and_he = [&] ( const int seed_he, const int parent_face ) {\n            Mesh_connectivity::Half_edge_iterator he_end = pixconn.half_edge_at ( seed_he );\n            Mesh_connectivity::Half_edge_iterator he = he_end;\n            Mesh_connectivity::Face_iterator face = pixconn.face_at ( parent_face );\n            assert_break ( he.face().is_equal ( pixconn.hole() ) );\n\n            int safe_guard = 0;\n            const int safe_gaurd_cap = 10000;\n\n            // Make the association\n            face.data().half_edge = he.index();\n\n            do {\n                he.data().face = face.index();\n                assert_break ( safe_guard < safe_gaurd_cap );\n                ++safe_guard;\n                he = he.next();\n            } while ( !he.is_equal ( he_end ) );\n        };\n\n        // Get all the holes\n        std::vector<int> he_on_holes;\n        enumerate_holes ( pixconn,  he_on_holes );\n\n        for ( int heid: he_on_holes ) {\n            Mesh_connectivity::Face_iterator face =  pixconn.add_face();\n            associate_face_and_he ( heid, face.index() );\n        }\n\n    } // End of creating the hole polygons\n\n\n    // Now associate holes and boundary (polygons to regions)\n    {\n        Mesh_connectivity& pixconn = ans.connectivity();\n\n        // No extract the points\n        // Get the holes and polygons as CCW paths\n        // And also find the areas\n        std::vector<Eigen::Matrix2Xd> outer_boundaries;\n        std::vector<double> outer_boundary_areas;\n        std::vector<Eigen::Matrix2Xd> holes;\n        std::vector<double> hole_areas;\n\n        for ( int i = 0 ; i < ans.n_regions() ; ++i ) {\n            outer_boundaries.push_back ( ans.get_polygon_points ( i ).cast<double>() );\n            bool is_ccw;\n            double area;\n            polyvec::WindingNumber::compute_orientation ( outer_boundaries.back(), is_ccw, area );\n            assert_break ( is_ccw );\n            outer_boundary_areas.push_back ( area );\n        }\n\n        for ( int i = ans.n_regions()  ; i < ans.n_polygons() ; ++i ) {\n            holes.push_back ( ans.get_polygon_points ( i ).cast<double>() );\n            holes.back().rowwise().reverseInPlace(); // make CCW\n            bool is_ccw;\n            double area;\n            polyvec::WindingNumber::compute_orientation ( holes.back(), is_ccw, area );\n            assert_break ( is_ccw );\n            hole_areas.push_back ( area );\n        }\n\n        //\n        // Create lambdas that say if a polygon is inside another\n        //  assumes that out and in are both pixel boundaries\n        // and are ccw\n        // Only works if the area of out is bigger than in\n        //\n        auto is_inside = [&] ( const Eigen::Matrix2Xd &out, const Eigen::Matrix2Xd &in ) {\n            const Eigen::Vector2d mid = (in.col ( 0 ) + in.col ( 1 )) /2.;\n            const Eigen::Vector2d tang = in.col ( 1 ) -  in.col ( 0 );\n            const Eigen::Vector2d normal ( -tang.y(), tang.x() );\n            const Eigen::Vector2d definitely_inside_in = normal/2. + mid;\n\n            bool is_trustable;\n            double winding;\n            ::polyvec::WindingNumber::compute_winding ( out, definitely_inside_in, winding, is_trustable );\n            assert_break ( is_trustable );\n            return std::abs ( winding ) > 1e-5;\n        };\n\n        // Now call the association function\n        std::vector<std::vector<int>> boundary_holes;\n        associate_holes (\n            ( int ) outer_boundaries.size(),\n            ( int ) holes.size(),\n        [&] ( const int bout, const int hin ) {\n            if ( ( int ) outer_boundary_areas[bout] <= ( int ) hole_areas[hin] ) {\n                return false;\n            } else {\n                return  is_inside ( outer_boundaries[bout], holes[hin] );\n            }\n        },\n        [&] ( const int hout, const int hin ) {\n            if ( ( int ) hole_areas[hout] <= ( int ) hole_areas[hin] ) {\n                return false;\n            } else {\n                return  is_inside ( holes[hout], holes[hin] );\n            }\n        },\n        boundary_holes );\n\n        // Now build the adj and xadj\n        ans._polygon_to_region.resize ( ans.n_polygons(), infinite_region );\n        ans._region_to_polygon_xval.resize ( 1, 0 );\n        ans._region_to_polygon_val.resize ( 0 );\n\n        for ( int i = 0 ; i < ans.n_regions() ; ++i ) {\n            const int region_id = i;\n            ans._region_to_polygon_xval.push_back ( ans._region_to_polygon_xval.back() );\n\n            // Don't forget yourself :)\n            ans._polygon_to_region[region_id] = region_id;\n            ++ans._region_to_polygon_xval.back();\n            ans._region_to_polygon_val.push_back ( region_id );\n\n            for ( int  j = 0 ; j < ( int ) boundary_holes[region_id].size() ; ++j ) {\n                const int polygon_id = ans.n_regions() + boundary_holes[region_id][j];\n                ans._polygon_to_region[polygon_id] = region_id;\n                ++ans._region_to_polygon_xval.back();\n                ans._region_to_polygon_val.push_back ( polygon_id );\n            }\n        }\n    } // ALL DONE WITH REGION HOLE ASSOCIATION\n\n    return ans;\n}\n\n\nNAMESPACE_END ( mc )\nNAMESPACE_END ( polyfit )\n", "meta": {"hexsha": "fbaf97356084c9cc380e9ece72d52980e616a247", "size": 15887, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/polyvec/mc/raster_image_connectivity.cpp", "max_stars_repo_name": "ShnitzelKiller/polyfit", "max_stars_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-08-17T17:25:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T05:49:12.000Z", "max_issues_repo_path": "source/polyvec/mc/raster_image_connectivity.cpp", "max_issues_repo_name": "ShnitzelKiller/polyfit", "max_issues_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-08-26T13:54:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T07:19:22.000Z", "max_forks_repo_path": "source/polyvec/mc/raster_image_connectivity.cpp", "max_forks_repo_name": "ShnitzelKiller/polyfit", "max_forks_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-08-26T23:26:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-04T09:06:07.000Z", "avg_line_length": 33.5168776371, "max_line_length": 136, "alphanum_fraction": 0.606785422, "num_tokens": 3995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.26579906319502644}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2007-2015 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Copyright (c) 2008-2015 Bruno Lalande, Paris, France.\r\n// Copyright (c) 2009-2015 Mateusz Loskot, London, UK.\r\n\r\n// This file was modified by Oracle on 2015-2017.\r\n// Modifications copyright (c) 2015-2017, Oracle and/or its affiliates.\r\n\r\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\r\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\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_GEOMETRY_ALGORITHMS_DETAIL_ENVELOPE_SEGMENT_HPP\r\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_ENVELOPE_SEGMENT_HPP\r\n\r\n#include <cstddef>\r\n#include <utility>\r\n\r\n#include <boost/numeric/conversion/cast.hpp>\r\n\r\n#include <boost/geometry/core/assert.hpp>\r\n#include <boost/geometry/core/coordinate_system.hpp>\r\n#include <boost/geometry/core/coordinate_type.hpp>\r\n#include <boost/geometry/core/cs.hpp>\r\n#include <boost/geometry/core/srs.hpp>\r\n#include <boost/geometry/core/point_type.hpp>\r\n#include <boost/geometry/core/radian_access.hpp>\r\n#include <boost/geometry/core/tags.hpp>\r\n\r\n#include <boost/geometry/util/math.hpp>\r\n\r\n#include <boost/geometry/geometries/helper_geometry.hpp>\r\n\r\n#include <boost/geometry/formulas/vertex_latitude.hpp>\r\n\r\n#include <boost/geometry/algorithms/detail/assign_indexed_point.hpp>\r\n\r\n#include <boost/geometry/algorithms/detail/envelope/point.hpp>\r\n#include <boost/geometry/algorithms/detail/envelope/transform_units.hpp>\r\n\r\n#include <boost/geometry/algorithms/detail/expand/point.hpp>\r\n\r\n#include <boost/geometry/algorithms/dispatch/envelope.hpp>\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\n#ifndef DOXYGEN_NO_DETAIL\r\nnamespace detail { namespace envelope\r\n{\r\n\r\ntemplate <typename CalculationType, typename CS_Tag>\r\nstruct envelope_segment_call_vertex_latitude\r\n{\r\n    template <typename T1, typename T2, typename Strategy>\r\n    static inline CalculationType apply(T1 const& lat1,\r\n                                        T2 const& alp1,\r\n                                        Strategy const& )\r\n    {\r\n        return geometry::formula::vertex_latitude<CalculationType, CS_Tag>\r\n            ::apply(lat1, alp1);\r\n    }\r\n};\r\n\r\ntemplate <typename CalculationType>\r\nstruct envelope_segment_call_vertex_latitude<CalculationType, geographic_tag>\r\n{\r\n    template <typename T1, typename T2, typename Strategy>\r\n    static inline CalculationType apply(T1 const& lat1,\r\n                                        T2 const& alp1,\r\n                                        Strategy const& strategy)\r\n    {\r\n        return geometry::formula::vertex_latitude<CalculationType, geographic_tag>\r\n            ::apply(lat1, alp1, strategy.model());\r\n    }\r\n};\r\n\r\ntemplate <typename CS_Tag>\r\nclass envelope_segment_impl\r\n{\r\nprivate:\r\n\r\n    // degrees or radians\r\n    template <typename CalculationType>\r\n    static inline void swap(CalculationType& lon1,\r\n                            CalculationType& lat1,\r\n                            CalculationType& lon2,\r\n                            CalculationType& lat2)\r\n    {\r\n        std::swap(lon1, lon2);\r\n        std::swap(lat1, lat2);\r\n    }\r\n\r\n    // radians\r\n    template <typename CalculationType>\r\n    static inline bool contains_pi_half(CalculationType const& a1,\r\n                                        CalculationType const& a2)\r\n    {\r\n        // azimuths a1 and a2 are assumed to be in radians\r\n        BOOST_GEOMETRY_ASSERT(! math::equals(a1, a2));\r\n\r\n        static CalculationType const pi_half = math::half_pi<CalculationType>();\r\n\r\n        return (a1 < a2)\r\n                ? (a1 < pi_half && pi_half < a2)\r\n                : (a1 > pi_half && pi_half > a2);\r\n    }\r\n\r\n    // radians or degrees\r\n    template <typename Units, typename CoordinateType>\r\n    static inline bool crosses_antimeridian(CoordinateType const& lon1,\r\n                                            CoordinateType const& lon2)\r\n    {\r\n        typedef math::detail::constants_on_spheroid\r\n            <\r\n                CoordinateType, Units\r\n            > constants;\r\n\r\n        return math::abs(lon1 - lon2) > constants::half_period(); // > pi\r\n    }\r\n\r\n    // degrees or radians\r\n    template <typename Units, typename CalculationType, typename Strategy>\r\n    static inline void compute_box_corners(CalculationType& lon1,\r\n                                           CalculationType& lat1,\r\n                                           CalculationType& lon2,\r\n                                           CalculationType& lat2,\r\n                                           Strategy const& strategy)\r\n    {\r\n        // coordinates are assumed to be in radians\r\n        BOOST_GEOMETRY_ASSERT(lon1 <= lon2);\r\n\r\n        CalculationType lon1_rad = math::as_radian<Units>(lon1);\r\n        CalculationType lat1_rad = math::as_radian<Units>(lat1);\r\n        CalculationType lon2_rad = math::as_radian<Units>(lon2);\r\n        CalculationType lat2_rad = math::as_radian<Units>(lat2);\r\n\r\n        CalculationType a1, a2;\r\n        strategy.apply(lon1_rad, lat1_rad, lon2_rad, lat2_rad, a1, a2);\r\n\r\n        if (lat1 > lat2)\r\n        {\r\n            std::swap(lat1, lat2);\r\n            std::swap(lat1_rad, lat2_rad);\r\n            std::swap(a1, a2);\r\n        }\r\n\r\n        if (math::equals(a1, a2))\r\n        {\r\n            // the segment must lie on the equator or is very short\r\n            return;\r\n        }\r\n\r\n        if (contains_pi_half(a1, a2))\r\n        {\r\n            CalculationType p_max = envelope_segment_call_vertex_latitude\r\n                <CalculationType, CS_Tag>::apply(lat1_rad, a1, strategy);\r\n\r\n            CalculationType const mid_lat = lat1 + lat2;\r\n            if (mid_lat < 0)\r\n            {\r\n                // update using min latitude\r\n                CalculationType const lat_min_rad = -p_max;\r\n                CalculationType const lat_min\r\n                    = math::from_radian<Units>(lat_min_rad);\r\n\r\n                if (lat1 > lat_min)\r\n                {\r\n                    lat1 = lat_min;\r\n                }\r\n            }\r\n            else if (mid_lat > 0)\r\n            {\r\n                // update using max latitude\r\n                CalculationType const lat_max_rad = p_max;\r\n                CalculationType const lat_max\r\n                    = math::from_radian<Units>(lat_max_rad);\r\n\r\n                if (lat2 < lat_max)\r\n                {\r\n                    lat2 = lat_max;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    template <typename Units, typename CalculationType, typename Strategy>\r\n    static inline void apply(CalculationType& lon1,\r\n                             CalculationType& lat1,\r\n                             CalculationType& lon2,\r\n                             CalculationType& lat2,\r\n                             Strategy const& strategy)\r\n    {\r\n        typedef math::detail::constants_on_spheroid\r\n            <\r\n                CalculationType, Units\r\n            > constants;\r\n\r\n        bool is_pole1 = math::equals(math::abs(lat1), constants::max_latitude());\r\n        bool is_pole2 = math::equals(math::abs(lat2), constants::max_latitude());\r\n\r\n        if (is_pole1 && is_pole2)\r\n        {\r\n            // both points are poles; nothing more to do:\r\n            // longitudes are already normalized to 0\r\n            // but just in case\r\n            lon1 = 0;\r\n            lon2 = 0;\r\n        }\r\n        else if (is_pole1 && !is_pole2)\r\n        {\r\n            // first point is a pole, second point is not:\r\n            // make the longitude of the first point the same as that\r\n            // of the second point\r\n            lon1 = lon2;\r\n        }\r\n        else if (!is_pole1 && is_pole2)\r\n        {\r\n            // second point is a pole, first point is not:\r\n            // make the longitude of the second point the same as that\r\n            // of the first point\r\n            lon2 = lon1;\r\n        }\r\n\r\n        if (lon1 == lon2)\r\n        {\r\n            // segment lies on a meridian\r\n            if (lat1 > lat2)\r\n            {\r\n                std::swap(lat1, lat2);\r\n            }\r\n            return;\r\n        }\r\n\r\n        BOOST_GEOMETRY_ASSERT(!is_pole1 && !is_pole2);\r\n\r\n        if (lon1 > lon2)\r\n        {\r\n            swap(lon1, lat1, lon2, lat2);\r\n        }\r\n\r\n        if (crosses_antimeridian<Units>(lon1, lon2))\r\n        {\r\n            lon1 += constants::period();\r\n            swap(lon1, lat1, lon2, lat2);\r\n        }\r\n\r\n        compute_box_corners<Units>(lon1, lat1, lon2, lat2, strategy);\r\n    }\r\n\r\npublic:\r\n    template <\r\n            typename Units,\r\n            typename CalculationType,\r\n            typename Box,\r\n            typename Strategy\r\n            >\r\n    static inline void apply(CalculationType lon1,\r\n                             CalculationType lat1,\r\n                             CalculationType lon2,\r\n                             CalculationType lat2,\r\n                             Box& mbr,\r\n                             Strategy const& strategy)\r\n    {\r\n        typedef typename coordinate_type<Box>::type box_coordinate_type;\r\n\r\n        typedef typename helper_geometry\r\n            <\r\n                Box, box_coordinate_type, Units\r\n            >::type helper_box_type;\r\n\r\n        helper_box_type radian_mbr;\r\n\r\n        apply<Units>(lon1, lat1, lon2, lat2, strategy);\r\n\r\n        geometry::set\r\n            <\r\n                min_corner, 0\r\n            >(radian_mbr, boost::numeric_cast<box_coordinate_type>(lon1));\r\n\r\n        geometry::set\r\n            <\r\n                min_corner, 1\r\n            >(radian_mbr, boost::numeric_cast<box_coordinate_type>(lat1));\r\n\r\n        geometry::set\r\n            <\r\n                max_corner, 0\r\n            >(radian_mbr, boost::numeric_cast<box_coordinate_type>(lon2));\r\n\r\n        geometry::set\r\n            <\r\n                max_corner, 1\r\n            >(radian_mbr, boost::numeric_cast<box_coordinate_type>(lat2));\r\n\r\n        transform_units(radian_mbr, mbr);\r\n    }\r\n};\r\n\r\ntemplate <std::size_t Dimension, std::size_t DimensionCount>\r\nstruct envelope_one_segment\r\n{\r\n    template<typename Point, typename Box, typename Strategy>\r\n    static inline void apply(Point const& p1,\r\n                             Point const& p2,\r\n                             Box& mbr,\r\n                             Strategy const& strategy)\r\n    {\r\n        envelope_one_point<Dimension, DimensionCount>::apply(p1, mbr, strategy);\r\n        detail::expand::point_loop\r\n            <\r\n                strategy::compare::default_strategy,\r\n                strategy::compare::default_strategy,\r\n                Dimension,\r\n                DimensionCount\r\n            >::apply(mbr, p2, strategy);\r\n    }\r\n};\r\n\r\n\r\ntemplate <std::size_t DimensionCount>\r\nstruct envelope_segment\r\n{\r\n    template <typename Point, typename Box, typename Strategy>\r\n    static inline void apply(Point const& p1,\r\n                             Point const& p2,\r\n                             Box& mbr,\r\n                             Strategy const& strategy)\r\n    {\r\n        // first compute the envelope range for the first two coordinates\r\n        strategy.apply(p1, p2, mbr);\r\n\r\n        // now compute the envelope range for coordinates of\r\n        // dimension 2 and higher\r\n        envelope_one_segment<2, DimensionCount>::apply(p1, p2, mbr, strategy);\r\n    }\r\n\r\n    template <typename Segment, typename Box>\r\n    static inline void apply(Segment const& segment, Box& mbr)\r\n    {\r\n        typename point_type<Segment>::type p[2];\r\n        detail::assign_point_from_index<0>(segment, p[0]);\r\n        detail::assign_point_from_index<1>(segment, p[1]);\r\n        apply(p[0], p[1], mbr);\r\n    }\r\n};\r\n\r\n}} // namespace detail::envelope\r\n#endif // DOXYGEN_NO_DETAIL\r\n\r\n\r\n#ifndef DOXYGEN_NO_DISPATCH\r\nnamespace dispatch\r\n{\r\n\r\n\r\ntemplate <typename Segment>\r\nstruct envelope<Segment, segment_tag>\r\n{\r\n    template <typename Box, typename Strategy>\r\n    static inline void apply(Segment const& segment,\r\n                             Box& mbr,\r\n                             Strategy const& strategy)\r\n    {\r\n        typename point_type<Segment>::type p[2];\r\n        detail::assign_point_from_index<0>(segment, p[0]);\r\n        detail::assign_point_from_index<1>(segment, p[1]);\r\n        detail::envelope::envelope_segment\r\n            <\r\n               dimension<Segment>::value\r\n            >::apply(p[0], p[1], mbr, strategy);\r\n    }\r\n};\r\n\r\n} // namespace dispatch\r\n#endif // DOXYGEN_NO_DISPATCH\r\n\r\n}} // namespace boost::geometry\r\n\r\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_ENVELOPE_SEGMENT_HPP\r\n", "meta": {"hexsha": "104e5a21f5761a7ee6b1388cbf7fa10e263b4842", "size": 12695, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/algorithms/detail/envelope/segment.hpp", "max_stars_repo_name": "lijgame/boost", "max_stars_repo_head_hexsha": "ec2214a19cdddd1048058321a8105dd0231dac47", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-22T06:23:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-22T06:23:30.000Z", "max_issues_repo_path": "boost/geometry/algorithms/detail/envelope/segment.hpp", "max_issues_repo_name": "lijgame/boost", "max_issues_repo_head_hexsha": "ec2214a19cdddd1048058321a8105dd0231dac47", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/geometry/algorithms/detail/envelope/segment.hpp", "max_forks_repo_name": "lijgame/boost", "max_forks_repo_head_hexsha": "ec2214a19cdddd1048058321a8105dd0231dac47", "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.8886010363, "max_line_length": 83, "alphanum_fraction": 0.5610870421, "num_tokens": 2710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.265734986338817}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// marginal_cells.hpp                                                        //\n//                                                                           //\n//  Copyright 2010 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_CONTINGENCY_TABLE_CELLS_MARGINAL_CELLS_HPP_ER_2010\n#define BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_CONTINGENCY_TABLE_CELLS_MARGINAL_CELLS_HPP_ER_2010\n#include <boost/mpl/fold.hpp>\n#include <boost/mpl/vector/vector0.hpp>\n#include <boost/mpl/vector/vector10.hpp>\n#include <boost/mpl/push_back.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/cells/cells.hpp>\n\nnamespace boost { \nnamespace statistics{\nnamespace detail{\nnamespace contingency_table{\n\n    template<typename Keys>\n    struct marginal_cells : boost::mpl::fold<\n        Keys,\n        boost::mpl::vector0<>,\n        boost::mpl::push_back<\n            boost::mpl::_1,\n            contingency_table::tag::cells<\n                boost::mpl::vector1<boost::mpl::_2>\n            >\n        >\n    >{};\n\n}// contingency_table\n}// detail\n}// statistics\n}// boost\n\n#endif\n\n", "meta": {"hexsha": "be43634957fc6f82459532794e3b67c6535b94ed", "size": 1488, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "non_parametric/boost/statistics/detail/non_parametric/contingency_table/cells/marginal_cells.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "non_parametric/boost/statistics/detail/non_parametric/contingency_table/cells/marginal_cells.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "non_parametric/boost/statistics/detail/non_parametric/contingency_table/cells/marginal_cells.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2926829268, "max_line_length": 97, "alphanum_fraction": 0.5571236559, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.26572858233746804}}
{"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_BN_MPFI_HPP\n#define BOOST_MATH_BN_MPFI_HPP\n\n#include <boost/multiprecision/number.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/cstdint.hpp>\n#include <boost/multiprecision/detail/big_lanczos.hpp>\n#include <boost/multiprecision/detail/digits.hpp>\n#include <boost/multiprecision/mpfr.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <mpfi.h>\n#include <cmath>\n#include <algorithm>\n\nnamespace boost{\nnamespace multiprecision{\nnamespace backends{\n\ntemplate <unsigned digits10>\nstruct mpfi_float_backend;\n\n} // namespace backends\n\ntemplate <unsigned digits10>\nstruct number_category<backends::mpfi_float_backend<digits10> > : public mpl::int_<number_kind_floating_point>{};\n\nstruct interval_error : public std::runtime_error\n{\n   interval_error(const std::string& s) : std::runtime_error(s) {}\n};\n\nnamespace backends{\n\nnamespace detail{\n\ninline int mpfi_sgn(mpfi_srcptr p)\n{\n   if(mpfi_is_zero(p))\n      return 0;\n   if(mpfi_is_strictly_pos(p))\n      return 1;\n   if(mpfi_is_strictly_neg(p))\n      return -1;\n   BOOST_THROW_EXCEPTION(interval_error(\"Sign of interval is ambiguous.\"));\n}\n\ntemplate <unsigned digits10>\nstruct mpfi_float_imp;\n\ntemplate <unsigned digits10>\nstruct mpfi_float_imp\n{\n   typedef mpl::list<long, long long>                     signed_types;\n   typedef mpl::list<unsigned long, unsigned long long>   unsigned_types;\n   typedef mpl::list<double, long double>                 float_types;\n   typedef long                                           exponent_type;\n\n   mpfi_float_imp()\n   {\n      mpfi_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));\n   }\n   mpfi_float_imp(unsigned prec)\n   {\n      mpfi_init2(m_data, prec);\n   }\n\n   mpfi_float_imp(const mpfi_float_imp& o)\n   {\n      mpfi_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));\n      if(o.m_data[0].left._mpfr_d)\n         mpfi_set(m_data, o.m_data);\n   }\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\n   mpfi_float_imp(mpfi_float_imp&& o) BOOST_NOEXCEPT\n   {\n      m_data[0] = o.m_data[0];\n      o.m_data[0].left._mpfr_d = 0;\n   }\n#endif\n   mpfi_float_imp& operator = (const mpfi_float_imp& o)\n   {\n      if(m_data[0].left._mpfr_d == 0)\n         mpfi_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));\n      if(o.m_data[0].left._mpfr_d)\n         mpfi_set(m_data, o.m_data);\n      return *this;\n   }\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\n   mpfi_float_imp& operator = (mpfi_float_imp&& o) BOOST_NOEXCEPT\n   {\n      mpfi_swap(m_data, o.m_data);\n      return *this;\n   }\n#endif\n#ifdef _MPFR_H_HAVE_INTMAX_T\n   mpfi_float_imp& operator = (unsigned long long i)\n   {\n      if(m_data[0].left._mpfr_d == 0)\n         mpfi_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));\n      mpfr_set_uj(left_data(), i, GMP_RNDD);\n      mpfr_set_uj(right_data(), i, GMP_RNDU);\n      return *this;\n   }\n   mpfi_float_imp& operator = (long long i)\n   {\n      if(m_data[0].left._mpfr_d == 0)\n         mpfi_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));\n      mpfr_set_sj(left_data(), i, GMP_RNDD);\n      mpfr_set_sj(right_data(), i, GMP_RNDU);\n      return *this;\n   }\n#else\n   mpfi_float_imp& operator = (unsigned long long i)\n   {\n      if(m_data[0].left._mpfr_d == 0)\n         mpfi_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));\n      unsigned long long mask = ((1uLL << std::numeric_limits<unsigned>::digits) - 1);\n      unsigned shift = 0;\n      mpfi_t t;\n      mpfi_init2(t, (std::max)(static_cast<unsigned>(std::numeric_limits<unsigned long long>::digits), static_cast<unsigned>(multiprecision::detail::digits10_2_2(digits10))));\n      mpfi_set_ui(m_data, 0);\n      while(i)\n      {\n         mpfi_set_ui(t, static_cast<unsigned>(i & mask));\n         if(shift)\n            mpfi_mul_2exp(t, t, shift);\n         mpfi_add(m_data, m_data, t);\n         shift += std::numeric_limits<unsigned>::digits;\n         i >>= std::numeric_limits<unsigned>::digits;\n      }\n      mpfi_clear(t);\n      return *this;\n   }\n   mpfi_float_imp& operator = (long long i)\n   {\n      if(m_data[0].left._mpfr_d == 0)\n         mpfi_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));\n      bool neg = i < 0;\n      *this = boost::multiprecision::detail::unsigned_abs(i);\n      if(neg)\n         mpfi_neg(m_data, m_data);\n      return *this;\n   }\n#endif\n   mpfi_float_imp& operator = (unsigned long i)\n   {\n      if(m_data[0].left._mpfr_d == 0)\n         mpfi_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));\n      mpfi_set_ui(m_data, i);\n      return *this;\n   }\n   mpfi_float_imp& operator = (long i)\n   {\n      if(m_data[0].left._mpfr_d == 0)\n         mpfi_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));\n      mpfi_set_si(m_data, i);\n      return *this;\n   }\n   mpfi_float_imp& operator = (double d)\n   {\n      if(m_data[0].left._mpfr_d == 0)\n         mpfi_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));\n      mpfi_set_d(m_data, d);\n      return *this;\n   }\n   mpfi_float_imp& operator = (long double a)\n   {\n      if(m_data[0].left._mpfr_d == 0)\n         mpfi_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));\n      mpfr_set_ld(left_data(), a, GMP_RNDD);\n      mpfr_set_ld(right_data(), a, GMP_RNDU);\n      return *this;\n   }\n   mpfi_float_imp& operator = (const char* s)\n   {\n      using default_ops::eval_fpclassify;\n   \n      if(m_data[0].left._mpfr_d == 0)\n         mpfi_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));\n\n      if(s && (*s == '{'))\n      {\n         mpfr_float_backend<digits10> a, b;\n         std::string part;\n         const char* p = ++s;\n         while(*p && (*p != ',') && (*p != '}'))\n            ++p;\n         part.assign(s + 1, p);\n         a = part.c_str();\n         s = p;\n         if(*p && (*p != '}'))\n         {\n            ++p;\n            while(*p && (*p != ',') && (*p != '}'))\n               ++p;\n            part.assign(s + 1, p);\n         }\n         else\n            part.erase();\n         b = part.c_str();\n\n         if(eval_fpclassify(a) == (int)FP_NAN)\n         {\n            mpfi_set_fr(this->data(), a.data());\n         }\n         else if(eval_fpclassify(b) == (int)FP_NAN)\n         {\n            mpfi_set_fr(this->data(), b.data());\n         }\n         else\n         {\n            if(a.compare(b) > 0)\n            {\n               BOOST_THROW_EXCEPTION(std::runtime_error(\"Attempt to create interval with invalid range (start is greater than end).\"));\n            }\n            mpfi_interv_fr(m_data, a.data(), b.data());\n         }\n      }\n      else if(mpfi_set_str(m_data, s, 10) != 0)\n      {\n         BOOST_THROW_EXCEPTION(std::runtime_error(std::string(\"Unable to parse string \\\"\") + s + std::string(\"\\\"as a valid floating point number.\")));\n      }\n      return *this;\n   }\n   void swap(mpfi_float_imp& o) BOOST_NOEXCEPT\n   {\n      mpfi_swap(m_data, o.m_data);\n   }\n   std::string str(std::streamsize digits, std::ios_base::fmtflags f)const\n   {\n      BOOST_ASSERT(m_data[0].left._mpfr_d);\n\n      mpfr_float_backend<digits10> a, b;\n\n      mpfi_get_left(a.data(), m_data);\n      mpfi_get_right(b.data(), m_data);\n\n      if(a.compare(b) == 0)\n         return a.str(digits, f);\n\n      return \"{\" + a.str(digits, f) + \",\" + b.str(digits, f) + \"}\";\n   }\n   ~mpfi_float_imp() BOOST_NOEXCEPT\n   {\n      if(m_data[0].left._mpfr_d)\n         mpfi_clear(m_data);\n   }\n   void negate() BOOST_NOEXCEPT\n   {\n      BOOST_ASSERT(m_data[0].left._mpfr_d);\n      mpfi_neg(m_data, m_data);\n   }\n   int compare(const mpfi_float_imp& o)const BOOST_NOEXCEPT\n   {\n      BOOST_ASSERT(m_data[0].left._mpfr_d && o.m_data[0].left._mpfr_d);\n      if(mpfr_cmp(right_data(), o.left_data()) < 0)\n         return -1;\n      if(mpfr_cmp(left_data(), o.right_data()) > 0)\n         return 1;\n      if((mpfr_cmp(left_data(), o.left_data()) == 0) && (mpfr_cmp(right_data(), o.right_data()) == 0))\n         return 0;\n      BOOST_THROW_EXCEPTION(interval_error(\"Ambiguous comparison between two values.\"));\n      return 0;\n   }\n   template <class V>\n   int compare(V v)const BOOST_NOEXCEPT\n   {\n      mpfi_float_imp d;\n      d = v;\n      return compare(d);\n   }\n   mpfi_t& data() BOOST_NOEXCEPT\n   {\n      BOOST_ASSERT(m_data[0].left._mpfr_d);\n      return m_data;\n   }\n   const mpfi_t& data()const BOOST_NOEXCEPT\n   {\n      BOOST_ASSERT(m_data[0].left._mpfr_d);\n      return m_data;\n   }\n   mpfr_ptr left_data() BOOST_NOEXCEPT\n   {\n      BOOST_ASSERT(m_data[0].left._mpfr_d);\n      return &(m_data[0].left);\n   }\n   mpfr_srcptr left_data()const BOOST_NOEXCEPT\n   {\n      BOOST_ASSERT(m_data[0].left._mpfr_d);\n      return &(m_data[0].left);\n   }\n   mpfr_ptr right_data() BOOST_NOEXCEPT\n   {\n      BOOST_ASSERT(m_data[0].left._mpfr_d);\n      return &(m_data[0].right);\n   }\n   mpfr_srcptr right_data()const BOOST_NOEXCEPT\n   {\n      BOOST_ASSERT(m_data[0].left._mpfr_d);\n      return &(m_data[0].right);\n   }\nprotected:\n   mpfi_t m_data;\n   static unsigned& get_default_precision() BOOST_NOEXCEPT\n   {\n      static unsigned val = 50;\n      return val;\n   }\n};\n\n} // namespace detail\n\ntemplate <unsigned digits10>\nstruct mpfi_float_backend : public detail::mpfi_float_imp<digits10>\n{\n   mpfi_float_backend() : detail::mpfi_float_imp<digits10>() {}\n   mpfi_float_backend(const mpfi_float_backend& o) : detail::mpfi_float_imp<digits10>(o) {}\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\n   mpfi_float_backend(mpfi_float_backend&& o) : detail::mpfi_float_imp<digits10>(static_cast<detail::mpfi_float_imp<digits10>&&>(o)) {}\n#endif\n   template <unsigned D>\n   mpfi_float_backend(const mpfi_float_backend<D>& val, typename enable_if_c<D <= digits10>::type* = 0)\n       : detail::mpfi_float_imp<digits10>()\n   {\n      mpfi_set(this->m_data, val.data());\n   }\n   template <unsigned D>\n   explicit mpfi_float_backend(const mpfi_float_backend<D>& val, typename disable_if_c<D <= digits10>::type* = 0)\n       : detail::mpfi_float_imp<digits10>()\n   {\n      mpfi_set(this->m_data, val.data());\n   }\n   mpfi_float_backend(const mpfi_t val)\n       : detail::mpfi_float_imp<digits10>()\n   {\n      mpfi_set(this->m_data, val);\n   }\n   mpfi_float_backend& operator=(const mpfi_float_backend& o)\n   {\n      *static_cast<detail::mpfi_float_imp<digits10>*>(this) = static_cast<detail::mpfi_float_imp<digits10> const&>(o);\n      return *this;\n   }\n   template <unsigned D>\n   mpfi_float_backend(const mpfr_float_backend<D>& val, typename enable_if_c<D <= digits10>::type* = 0)\n       : detail::mpfi_float_imp<digits10>()\n   {\n      mpfi_set_fr(this->m_data, val.data());\n   }\n   template <unsigned D>\n   mpfi_float_backend& operator=(const mpfr_float_backend<D>& val)\n   {\n      mpfi_set_fr(this->m_data, val.data());\n      return *this;\n   }\n   template <unsigned D>\n   explicit mpfi_float_backend(const mpfr_float_backend<D>& val, typename disable_if_c<D <= digits10>::type* = 0)\n       : detail::mpfi_float_imp<digits10>()\n   {\n      mpfi_set_fr(this->m_data, val.data());\n   }\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\n   mpfi_float_backend& operator=(mpfi_float_backend&& o) BOOST_NOEXCEPT\n   {\n      *static_cast<detail::mpfi_float_imp<digits10>*>(this) = static_cast<detail::mpfi_float_imp<digits10>&&>(o);\n      return *this;\n   }\n#endif\n   template <class V>\n   mpfi_float_backend& operator=(const V& v)\n   {\n      *static_cast<detail::mpfi_float_imp<digits10>*>(this) = v;\n      return *this;\n   }\n   mpfi_float_backend& operator=(const mpfi_t val)\n   {\n      mpfi_set(this->m_data, val);\n      return *this;\n   }\n   // We don't change our precision here, this is a fixed precision type:\n   template <unsigned D>\n   mpfi_float_backend& operator=(const mpfi_float_backend<D>& val)\n   {\n      mpfi_set(this->m_data, val.data());\n      return *this;\n   }\n};\n\ntemplate <>\nstruct mpfi_float_backend<0> : public detail::mpfi_float_imp<0>\n{\n   mpfi_float_backend() : detail::mpfi_float_imp<0>() {}\n   mpfi_float_backend(const mpfi_t val)\n      : detail::mpfi_float_imp<0>(mpfi_get_prec(val))\n   {\n      mpfi_set(this->m_data, val);\n   }\n   mpfi_float_backend(const mpfi_float_backend& o) : detail::mpfi_float_imp<0>(o) {}\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\n   mpfi_float_backend(mpfi_float_backend&& o) BOOST_NOEXCEPT : detail::mpfi_float_imp<0>(static_cast<detail::mpfi_float_imp<0>&&>(o)) {}\n#endif\n   mpfi_float_backend(const mpfi_float_backend& o, unsigned digits10)\n      : detail::mpfi_float_imp<0>(digits10)\n   {\n      *this = o;\n   }\n   template <unsigned D>\n   mpfi_float_backend(const mpfi_float_backend<D>& val)\n      : detail::mpfi_float_imp<0>(mpfi_get_prec(val.data()))\n   {\n      mpfi_set(this->m_data, val.data());\n   }\n   mpfi_float_backend& operator=(const mpfi_float_backend& o)\n   {\n      mpfi_set_prec(this->m_data, mpfi_get_prec(o.data()));\n      mpfi_set(this->m_data, o.data());\n      return *this;\n   }\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\n   mpfi_float_backend& operator=(mpfi_float_backend&& o) BOOST_NOEXCEPT\n   {\n      *static_cast<detail::mpfi_float_imp<0>*>(this) = static_cast<detail::mpfi_float_imp<0> &&>(o);\n      return *this;\n   }\n#endif\n   template <class V>\n   mpfi_float_backend& operator=(const V& v)\n   {\n      *static_cast<detail::mpfi_float_imp<0>*>(this) = v;\n      return *this;\n   }\n   mpfi_float_backend& operator=(const mpfi_t val)\n   {\n      mpfi_set_prec(this->m_data, mpfi_get_prec(val));\n      mpfi_set(this->m_data, val);\n      return *this;\n   }\n   template <unsigned D>\n   mpfi_float_backend& operator=(const mpfi_float_backend<D>& val)\n   {\n      mpfi_set_prec(this->m_data, mpfi_get_prec(val.data()));\n      mpfi_set(this->m_data, val.data());\n      return *this;\n   }\n   static unsigned default_precision() BOOST_NOEXCEPT\n   {\n      return get_default_precision();\n   }\n   static void default_precision(unsigned v) BOOST_NOEXCEPT\n   {\n      get_default_precision() = v;\n   }\n   unsigned precision()const BOOST_NOEXCEPT\n   {\n      return multiprecision::detail::digits2_2_10(mpfi_get_prec(this->m_data));\n   }\n   void precision(unsigned digits10) BOOST_NOEXCEPT\n   {\n      mpfi_set_prec(this->m_data, multiprecision::detail::digits2_2_10((digits10)));\n   }\n};\n\ntemplate <unsigned digits10, class T>\ninline typename enable_if<is_arithmetic<T>, bool>::type eval_eq(const mpfi_float_backend<digits10>& a, const T& b) BOOST_NOEXCEPT\n{\n   return a.compare(b) == 0;\n}\ntemplate <unsigned digits10, class T>\ninline typename enable_if<is_arithmetic<T>, bool>::type eval_lt(const mpfi_float_backend<digits10>& a, const T& b) BOOST_NOEXCEPT\n{\n   return a.compare(b) < 0;\n}\ntemplate <unsigned digits10, class T>\ninline typename enable_if<is_arithmetic<T>, bool>::type eval_gt(const mpfi_float_backend<digits10>& a, const T& b) BOOST_NOEXCEPT\n{\n   return a.compare(b) > 0;\n}\n\ntemplate <unsigned D1, unsigned D2>\ninline void eval_add(mpfi_float_backend<D1>& result, const mpfi_float_backend<D2>& o)\n{\n   mpfi_add(result.data(), result.data(), o.data());\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_subtract(mpfi_float_backend<D1>& result, const mpfi_float_backend<D2>& o)\n{\n   mpfi_sub(result.data(), result.data(), o.data());\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_multiply(mpfi_float_backend<D1>& result, const mpfi_float_backend<D2>& o)\n{\n   if((void*)&result == (void*)&o)\n      mpfi_sqr(result.data(), o.data());\n   else\n      mpfi_mul(result.data(), result.data(), o.data());\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_divide(mpfi_float_backend<D1>& result, const mpfi_float_backend<D2>& o)\n{\n   mpfi_div(result.data(), result.data(), o.data());\n}\ntemplate <unsigned digits10>\ninline void eval_add(mpfi_float_backend<digits10>& result, unsigned long i)\n{\n   mpfi_add_ui(result.data(), result.data(), i);\n}\ntemplate <unsigned digits10>\ninline void eval_subtract(mpfi_float_backend<digits10>& result, unsigned long i)\n{\n   mpfi_sub_ui(result.data(), result.data(), i);\n}\ntemplate <unsigned digits10>\ninline void eval_multiply(mpfi_float_backend<digits10>& result, unsigned long i)\n{\n   mpfi_mul_ui(result.data(), result.data(), i);\n}\ntemplate <unsigned digits10>\ninline void eval_divide(mpfi_float_backend<digits10>& result, unsigned long i)\n{\n   mpfi_div_ui(result.data(), result.data(), i);\n}\ntemplate <unsigned digits10>\ninline void eval_add(mpfi_float_backend<digits10>& result, long i)\n{\n   if(i > 0)\n      mpfi_add_ui(result.data(), result.data(), i);\n   else\n      mpfi_sub_ui(result.data(), result.data(), boost::multiprecision::detail::unsigned_abs(i));\n}\ntemplate <unsigned digits10>\ninline void eval_subtract(mpfi_float_backend<digits10>& result, long i)\n{\n   if(i > 0)\n      mpfi_sub_ui(result.data(), result.data(), i);\n   else\n      mpfi_add_ui(result.data(), result.data(), boost::multiprecision::detail::unsigned_abs(i));\n}\ntemplate <unsigned digits10>\ninline void eval_multiply(mpfi_float_backend<digits10>& result, long i)\n{\n   mpfi_mul_ui(result.data(), result.data(), boost::multiprecision::detail::unsigned_abs(i));\n   if(i < 0)\n      mpfi_neg(result.data(), result.data());\n}\ntemplate <unsigned digits10>\ninline void eval_divide(mpfi_float_backend<digits10>& result, long i)\n{\n   mpfi_div_ui(result.data(), result.data(), boost::multiprecision::detail::unsigned_abs(i));\n   if(i < 0)\n      mpfi_neg(result.data(), result.data());\n}\n//\n// Specialised 3 arg versions of the basic operators:\n//\ntemplate <unsigned D1, unsigned D2, unsigned D3>\ninline void eval_add(mpfi_float_backend<D1>& a, const mpfi_float_backend<D2>& x, const mpfi_float_backend<D3>& y)\n{\n   mpfi_add(a.data(), x.data(), y.data());\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_add(mpfi_float_backend<D1>& a, const mpfi_float_backend<D2>& x, unsigned long y)\n{\n   mpfi_add_ui(a.data(), x.data(), y);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_add(mpfi_float_backend<D1>& a, const mpfi_float_backend<D2>& x, long y)\n{\n   if(y < 0)\n      mpfi_sub_ui(a.data(), x.data(), boost::multiprecision::detail::unsigned_abs(y));\n   else\n      mpfi_add_ui(a.data(), x.data(), y);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_add(mpfi_float_backend<D1>& a, unsigned long x, const mpfi_float_backend<D2>& y)\n{\n   mpfi_add_ui(a.data(), y.data(), x);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_add(mpfi_float_backend<D1>& a, long x, const mpfi_float_backend<D2>& y)\n{\n   if(x < 0)\n   {\n      mpfi_ui_sub(a.data(), boost::multiprecision::detail::unsigned_abs(x), y.data());\n      mpfi_neg(a.data(), a.data());\n   }\n   else\n      mpfi_add_ui(a.data(), y.data(), x);\n}\ntemplate <unsigned D1, unsigned D2, unsigned D3>\ninline void eval_subtract(mpfi_float_backend<D1>& a, const mpfi_float_backend<D2>& x, const mpfi_float_backend<D3>& y)\n{\n   mpfi_sub(a.data(), x.data(), y.data());\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_subtract(mpfi_float_backend<D1>& a, const mpfi_float_backend<D2>& x, unsigned long y)\n{\n   mpfi_sub_ui(a.data(), x.data(), y);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_subtract(mpfi_float_backend<D1>& a, const mpfi_float_backend<D2>& x, long y)\n{\n   if(y < 0)\n      mpfi_add_ui(a.data(), x.data(), boost::multiprecision::detail::unsigned_abs(y));\n   else\n      mpfi_sub_ui(a.data(), x.data(), y);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_subtract(mpfi_float_backend<D1>& a, unsigned long x, const mpfi_float_backend<D2>& y)\n{\n   mpfi_ui_sub(a.data(), x, y.data());\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_subtract(mpfi_float_backend<D1>& a, long x, const mpfi_float_backend<D2>& y)\n{\n   if(x < 0)\n   {\n      mpfi_add_ui(a.data(), y.data(), boost::multiprecision::detail::unsigned_abs(x));\n      mpfi_neg(a.data(), a.data());\n   }\n   else\n      mpfi_ui_sub(a.data(), x, y.data());\n}\n\ntemplate <unsigned D1, unsigned D2, unsigned D3>\ninline void eval_multiply(mpfi_float_backend<D1>& a, const mpfi_float_backend<D2>& x, const mpfi_float_backend<D3>& y)\n{\n   if((void*)&x == (void*)&y)\n      mpfi_sqr(a.data(), x.data());\n   else\n      mpfi_mul(a.data(), x.data(), y.data());\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_multiply(mpfi_float_backend<D1>& a, const mpfi_float_backend<D2>& x, unsigned long y)\n{\n   mpfi_mul_ui(a.data(), x.data(), y);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_multiply(mpfi_float_backend<D1>& a, const mpfi_float_backend<D2>& x, long y)\n{\n   if(y < 0)\n   {\n      mpfi_mul_ui(a.data(), x.data(), boost::multiprecision::detail::unsigned_abs(y));\n      a.negate();\n   }\n   else\n      mpfi_mul_ui(a.data(), x.data(), y);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_multiply(mpfi_float_backend<D1>& a, unsigned long x, const mpfi_float_backend<D2>& y)\n{\n   mpfi_mul_ui(a.data(), y.data(), x);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_multiply(mpfi_float_backend<D1>& a, long x, const mpfi_float_backend<D2>& y)\n{\n   if(x < 0)\n   {\n      mpfi_mul_ui(a.data(), y.data(), boost::multiprecision::detail::unsigned_abs(x));\n      mpfi_neg(a.data(), a.data());\n   }\n   else\n      mpfi_mul_ui(a.data(), y.data(), x);\n}\n\ntemplate <unsigned D1, unsigned D2, unsigned D3>\ninline void eval_divide(mpfi_float_backend<D1>& a, const mpfi_float_backend<D2>& x, const mpfi_float_backend<D3>& y)\n{\n   mpfi_div(a.data(), x.data(), y.data());\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_divide(mpfi_float_backend<D1>& a, const mpfi_float_backend<D2>& x, unsigned long y)\n{\n   mpfi_div_ui(a.data(), x.data(), y);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_divide(mpfi_float_backend<D1>& a, const mpfi_float_backend<D2>& x, long y)\n{\n   if(y < 0)\n   {\n      mpfi_div_ui(a.data(), x.data(), boost::multiprecision::detail::unsigned_abs(y));\n      a.negate();\n   }\n   else\n      mpfi_div_ui(a.data(), x.data(), y);\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_divide(mpfi_float_backend<D1>& a, unsigned long x, const mpfi_float_backend<D2>& y)\n{\n   mpfi_ui_div(a.data(), x, y.data());\n}\ntemplate <unsigned D1, unsigned D2>\ninline void eval_divide(mpfi_float_backend<D1>& a, long x, const mpfi_float_backend<D2>& y)\n{\n   if(x < 0)\n   {\n      mpfi_ui_div(a.data(), boost::multiprecision::detail::unsigned_abs(x), y.data());\n      mpfi_neg(a.data(), a.data());\n   }\n   else\n      mpfi_ui_div(a.data(), x, y.data());\n}\n\ntemplate <unsigned digits10>\ninline bool eval_is_zero(const mpfi_float_backend<digits10>& val) BOOST_NOEXCEPT\n{\n   return 0 != mpfi_is_zero(val.data());\n}\ntemplate <unsigned digits10>\ninline int eval_get_sign(const mpfi_float_backend<digits10>& val)\n{\n   return detail::mpfi_sgn(val.data());\n}\n\ntemplate <unsigned digits10>\ninline void eval_convert_to(unsigned long* result, const mpfi_float_backend<digits10>& val)\n{\n   mpfr_float_backend<digits10> t;\n   mpfi_mid(t.data(), val.data());\n   eval_convert_to(result, t);\n}\ntemplate <unsigned digits10>\ninline void eval_convert_to(long* result, const mpfi_float_backend<digits10>& val)\n{\n   mpfr_float_backend<digits10> t;\n   mpfi_mid(t.data(), val.data());\n   eval_convert_to(result, t);\n}\n#ifdef _MPFR_H_HAVE_INTMAX_T\ntemplate <unsigned digits10>\ninline void eval_convert_to(unsigned long long* result, const mpfi_float_backend<digits10>& val)\n{\n   mpfr_float_backend<digits10> t;\n   mpfi_mid(t.data(), val.data());\n   eval_convert_to(result, t);\n}\ntemplate <unsigned digits10>\ninline void eval_convert_to(long long* result, const mpfi_float_backend<digits10>& val)\n{\n   mpfr_float_backend<digits10> t;\n   mpfi_mid(t.data(), val.data());\n   eval_convert_to(result, t);\n}\n#endif\ntemplate <unsigned digits10>\ninline void eval_convert_to(double* result, const mpfi_float_backend<digits10>& val) BOOST_NOEXCEPT\n{\n   *result = mpfi_get_d(val.data());\n}\ntemplate <unsigned digits10>\ninline void eval_convert_to(long double* result, const mpfi_float_backend<digits10>& val) BOOST_NOEXCEPT\n{\n   mpfr_float_backend<digits10> t;\n   mpfi_mid(t.data(), val.data());\n   eval_convert_to(result, t);\n}\n\ntemplate <unsigned D1, unsigned D2, mpfr_allocation_type AllocationType>\ninline void assign_components(mpfi_float_backend<D1>& result, const mpfr_float_backend<D2, AllocationType>& a, const mpfr_float_backend<D2, AllocationType>& b)\n{\n   using default_ops::eval_fpclassify;\n   if(eval_fpclassify(a) == (int)FP_NAN)\n   {\n      mpfi_set_fr(result.data(), a.data());\n   }\n   else if(eval_fpclassify(b) == (int)FP_NAN)\n   {\n      mpfi_set_fr(result.data(), b.data());\n   }\n   else\n   {\n      if(a.compare(b) > 0)\n      {\n         BOOST_THROW_EXCEPTION(std::runtime_error(\"Attempt to create interval with invalid range (start is greater than end).\"));\n      }\n      mpfi_interv_fr(result.data(), a.data(), b.data());\n   }\n}\n\ntemplate <unsigned Digits10, class V>\ninline typename enable_if_c<is_convertible<V, number<mpfr_float_backend<Digits10, allocate_dynamic>, et_on> >::value >::type \n   assign_components(mpfi_float_backend<Digits10>& result, const V& a, const V& b)\n{\n   number<mpfr_float_backend<Digits10, allocate_dynamic>, et_on> x(a), y(b);\n   assign_components(result, x.backend(), y.backend());\n}\n\n//\n// Native non-member operations:\n//\ntemplate <unsigned Digits10>\ninline void eval_sqrt(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& val)\n{\n   mpfi_sqrt(result.data(), val.data());\n}\n\ntemplate <unsigned Digits10>\ninline void eval_abs(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& val)\n{\n   mpfi_abs(result.data(), val.data());\n}\n\ntemplate <unsigned Digits10>\ninline void eval_fabs(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& val)\n{\n   mpfi_abs(result.data(), val.data());\n}\ntemplate <unsigned Digits10>\ninline void eval_ceil(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& val)\n{\n   mpfr_float_backend<Digits10> a, b;\n   mpfr_set(a.data(), val.left_data(), GMP_RNDN);\n   mpfr_set(b.data(), val.right_data(), GMP_RNDN);\n   eval_ceil(a, a);\n   eval_ceil(b, b);\n   if(a.compare(b) != 0)\n   {\n      BOOST_THROW_EXCEPTION(interval_error(\"Attempt to take the ceil of a value that straddles an integer boundary.\"));\n   }\n   mpfi_set_fr(result.data(), a.data());\n}\ntemplate <unsigned Digits10>\ninline void eval_floor(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& val)\n{\n   mpfr_float_backend<Digits10> a, b;\n   mpfr_set(a.data(), val.left_data(), GMP_RNDN);\n   mpfr_set(b.data(), val.right_data(), GMP_RNDN);\n   eval_floor(a, a);\n   eval_floor(b, b);\n   if(a.compare(b) != 0)\n   {\n      BOOST_THROW_EXCEPTION(interval_error(\"Attempt to take the floor of a value that straddles an integer boundary.\"));\n   }\n   mpfi_set_fr(result.data(), a.data());\n}\ntemplate <unsigned Digits10>\ninline void eval_ldexp(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& val, long e)\n{\n   if(e > 0)\n      mpfi_mul_2exp(result.data(), val.data(), e);\n   else if(e < 0)\n      mpfi_div_2exp(result.data(), val.data(), -e);\n   else\n      result = val;\n}\ntemplate <unsigned Digits10>\ninline void eval_frexp(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& val, int* e)\n{\n   mpfr_float_backend<Digits10> t, rt;\n   mpfi_mid(t.data(), val.data());\n   eval_frexp(rt, t, e);\n   eval_ldexp(result, val, -*e);\n}\ntemplate <unsigned Digits10>\ninline void eval_frexp(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& val, long* e)\n{\n   mpfr_float_backend<Digits10> t, rt;\n   mpfi_mid(t.data(), val.data());\n   eval_frexp(rt, t, e);\n   eval_ldexp(result, val, -*e);\n}\n\ntemplate <unsigned Digits10>\ninline int eval_fpclassify(const mpfi_float_backend<Digits10>& val) BOOST_NOEXCEPT\n{\n   return mpfi_inf_p(val.data()) ? FP_INFINITE : mpfi_nan_p(val.data()) ? FP_NAN : mpfi_is_zero(val.data()) ? FP_ZERO : FP_NORMAL;\n}\n\ntemplate <unsigned Digits10>\ninline void eval_pow(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& b, const mpfi_float_backend<Digits10>& e)\n{\n   typedef typename boost::multiprecision::detail::canonical<unsigned, mpfi_float_backend<Digits10> >::type ui_type;\n   using default_ops::eval_get_sign;\n   int s = eval_get_sign(b);\n   if(s == 0)\n   {\n      if(eval_get_sign(e) == 0)\n      {\n         result = ui_type(1);\n      }\n      else\n      {\n         result = ui_type(0);\n      }\n      return;\n   }\n   if(s < 0)\n   {\n      if(eval_get_sign(e) < 0)\n      {\n         mpfi_float_backend<Digits10> t1, t2;\n         t1 = e;\n         t1.negate();\n         eval_pow(t2, b, t1);\n         t1 = ui_type(1);\n         eval_divide(result, t1, t2);\n         return;\n      }\n      typename boost::multiprecision::detail::canonical<boost::uintmax_t, mpfi_float_backend<Digits10> >::type an;\n      try\n      {\n         using default_ops::eval_convert_to;\n         eval_convert_to(&an, e);\n         if(e.compare(an) == 0)\n         {\n            mpfi_float_backend<Digits10> pb(b);\n            pb.negate();\n            eval_pow(result, pb, e);\n            if(an & 1u)\n               result.negate();\n            return;\n         }\n      }\n      catch(const std::exception&)\n      {\n         // conversion failed, just fall through, value is not an integer.\n      }\n      result = std::numeric_limits<number<mpfi_float_backend<Digits10>, et_on> >::quiet_NaN().backend();\n      return;\n   }\n   mpfi_log(result.data(), b.data());\n   mpfi_mul(result.data(), result.data(), e.data());\n   mpfi_exp(result.data(), result.data());\n}\n\ntemplate <unsigned Digits10>\ninline void eval_exp(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg)\n{\n   mpfi_exp(result.data(), arg.data());\n}\n\ntemplate <unsigned Digits10>\ninline void eval_log(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg)\n{\n   mpfi_log(result.data(), arg.data());\n}\n\ntemplate <unsigned Digits10>\ninline void eval_log10(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg)\n{\n   mpfi_log10(result.data(), arg.data());\n}\n\ntemplate <unsigned Digits10>\ninline void eval_sin(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg)\n{\n   mpfi_sin(result.data(), arg.data());\n}\n\ntemplate <unsigned Digits10>\ninline void eval_cos(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg)\n{\n   mpfi_cos(result.data(), arg.data());\n}\n\ntemplate <unsigned Digits10>\ninline void eval_tan(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg)\n{\n   mpfi_tan(result.data(), arg.data());\n}\n\ntemplate <unsigned Digits10>\ninline void eval_asin(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg)\n{\n   mpfi_asin(result.data(), arg.data());\n}\n\ntemplate <unsigned Digits10>\ninline void eval_acos(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg)\n{\n   mpfi_acos(result.data(), arg.data());\n}\n\ntemplate <unsigned Digits10>\ninline void eval_atan(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg)\n{\n   mpfi_atan(result.data(), arg.data());\n}\n\ntemplate <unsigned Digits10>\ninline void eval_atan2(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg1, const mpfi_float_backend<Digits10>& arg2)\n{\n   mpfi_atan2(result.data(), arg1.data(), arg2.data());\n}\n\ntemplate <unsigned Digits10>\ninline void eval_sinh(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg)\n{\n   mpfi_sinh(result.data(), arg.data());\n}\n\ntemplate <unsigned Digits10>\ninline void eval_cosh(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg)\n{\n   mpfi_cosh(result.data(), arg.data());\n}\n\ntemplate <unsigned Digits10>\ninline void eval_tanh(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg)\n{\n   mpfi_tanh(result.data(), arg.data());\n}\n\n} // namespace backends\n\n#ifdef BOOST_NO_SFINAE_EXPR\n\nnamespace detail{\n\ntemplate<unsigned D1, unsigned D2>\nstruct is_explicitly_convertible<backends::mpfi_float_backend<D1>, backends::mpfi_float_backend<D2> > : public mpl::true_ {};\n\n}\n\n#endif\n\ntemplate<>\nstruct number_category<detail::canonical<mpfi_t, backends::mpfi_float_backend<0> >::type> : public mpl::int_<number_kind_floating_point>{};\ntemplate <unsigned Digits10>\nstruct is_interval_number<backends::mpfi_float_backend<Digits10> > : public mpl::true_ {};\n\nusing boost::multiprecision::backends::mpfi_float_backend;\n\ntypedef number<mpfi_float_backend<50> >    mpfi_float_50;\ntypedef number<mpfi_float_backend<100> >   mpfi_float_100;\ntypedef number<mpfi_float_backend<500> >   mpfi_float_500;\ntypedef number<mpfi_float_backend<1000> >  mpfi_float_1000;\ntypedef number<mpfi_float_backend<0> >     mpfi_float;\n\n//\n// Special interval specific functions:\n//\ntemplate <unsigned Digits10, expression_template_option ExpressionTemplates>\ninline number<mpfr_float_backend<Digits10>, ExpressionTemplates> lower(const number<mpfi_float_backend<Digits10>, ExpressionTemplates>& val)\n{\n   number<mpfr_float_backend<Digits10> > result;\n   mpfr_set(result.backend().data(), val.backend().left_data(), GMP_RNDN);\n   return result;\n}\n\ntemplate <unsigned Digits10, expression_template_option ExpressionTemplates>\ninline number<mpfr_float_backend<Digits10>, ExpressionTemplates> upper(const number<mpfi_float_backend<Digits10>, ExpressionTemplates>& val)\n{\n   number<mpfr_float_backend<Digits10> > result;\n   mpfr_set(result.backend().data(), val.backend().right_data(), GMP_RNDN);\n   return result;\n}\n\ntemplate <unsigned Digits10, expression_template_option ExpressionTemplates>\ninline number<mpfr_float_backend<Digits10>, ExpressionTemplates> median(const number<mpfi_float_backend<Digits10>, ExpressionTemplates>& val)\n{\n   number<mpfr_float_backend<Digits10> > result;\n   mpfi_mid(result.backend().data(), val.backend().data());\n   return result;\n}\n\ntemplate <unsigned Digits10, expression_template_option ExpressionTemplates>\ninline number<mpfr_float_backend<Digits10>, ExpressionTemplates> width(const number<mpfi_float_backend<Digits10>, ExpressionTemplates>& val)\n{\n   number<mpfr_float_backend<Digits10> > result;\n   mpfi_diam_abs(result.backend().data(), val.backend().data());\n   return result;\n}\n\ntemplate <unsigned Digits10, expression_template_option ExpressionTemplates>\ninline number<mpfi_float_backend<Digits10>, ExpressionTemplates> intersect(const number<mpfi_float_backend<Digits10>, ExpressionTemplates>& a, const number<mpfi_float_backend<Digits10>, ExpressionTemplates>&  b)\n{\n   number<mpfi_float_backend<Digits10>, ExpressionTemplates> result;\n   mpfi_intersect(result.backend().data(), a.backend().data(), b.backend().data());\n   return result;\n}\n\ntemplate <unsigned Digits10, expression_template_option ExpressionTemplates>\ninline number<mpfi_float_backend<Digits10>, ExpressionTemplates> hull(const number<mpfi_float_backend<Digits10>, ExpressionTemplates>& a, const number<mpfi_float_backend<Digits10>, ExpressionTemplates>&  b)\n{\n   number<mpfi_float_backend<Digits10>, ExpressionTemplates> result;\n   mpfi_union(result.backend().data(), a.backend().data(), b.backend().data());\n   return result;\n}\n\ntemplate <unsigned Digits10, expression_template_option ExpressionTemplates>\ninline bool overlap(const number<mpfi_float_backend<Digits10>, ExpressionTemplates>& a, const number<mpfi_float_backend<Digits10>, ExpressionTemplates>&  b)\n{\n  return (lower(a) <= lower(b) && lower(b) <= upper(a)) ||\n         (lower(b) <= lower(a) && lower(a) <= upper(b));\n}\n\ntemplate <unsigned Digits10, expression_template_option ExpressionTemplates1, expression_template_option ExpressionTemplates2>\ninline bool in(const number<mpfr_float_backend<Digits10>, ExpressionTemplates1>& a, const number<mpfi_float_backend<Digits10>, ExpressionTemplates2>&  b)\n{\n  return mpfi_is_inside_fr(a.backend().data(), b.backend().data()) != 0;\n}\n\ntemplate <unsigned Digits10, expression_template_option ExpressionTemplates>\ninline bool zero_in(const number<mpfi_float_backend<Digits10>, ExpressionTemplates>&  a)\n{\n  return mpfi_has_zero(a.backend().data()) != 0;\n}\n\ntemplate <unsigned Digits10, expression_template_option ExpressionTemplates>\ninline bool subset(const number<mpfi_float_backend<Digits10>, ExpressionTemplates>& a, const number<mpfi_float_backend<Digits10>, ExpressionTemplates>&  b)\n{\n  return mpfi_is_inside(a.backend().data(), b.backend().data()) != 0;\n}\n\ntemplate <unsigned Digits10, expression_template_option ExpressionTemplates>\ninline bool proper_subset(const number<mpfi_float_backend<Digits10>, ExpressionTemplates>& a, const number<mpfi_float_backend<Digits10>, ExpressionTemplates>&  b)\n{\n  return mpfi_is_strictly_inside(a.backend().data(), b.backend().data()) != 0;\n}\n\ntemplate <unsigned Digits10, expression_template_option ExpressionTemplates>\ninline bool empty(const number<mpfi_float_backend<Digits10>, ExpressionTemplates>&  a)\n{\n  return mpfi_is_empty(a.backend().data()) != 0;\n}\n\ntemplate <unsigned Digits10, expression_template_option ExpressionTemplates>\ninline bool singleton(const number<mpfi_float_backend<Digits10>, ExpressionTemplates>&  a)\n{\n  return mpfr_cmp(a.backend().left_data(), a.backend().right_data()) == 0;\n}\n\ntemplate <unsigned Digits10, expression_template_option ExpressionTemplates>\nstruct component_type<number<mpfi_float_backend<Digits10>, ExpressionTemplates> >\n{\n   typedef number<mpfr_float_backend<Digits10>, ExpressionTemplates> type;\n};\n\n} // namespace multiprecision\n\nnamespace math{\n\nnamespace tools{\n\ntemplate <>\ninline int digits<boost::multiprecision::mpfi_float>()\n{\n   return boost::multiprecision::backends::detail::get_default_precision();\n}\ntemplate <>\ninline int digits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, boost::multiprecision::et_off> >()\n{\n   return boost::multiprecision::backends::detail::get_default_precision();\n}\n\n} // namespace tools\n\nnamespace constants{ namespace detail{\n\ntemplate <class T> struct constant_pi;\ntemplate <class T> struct constant_ln_two;\ntemplate <class T> struct constant_euler;\ntemplate <class T> struct constant_catalan;\n\n//\n// Initializer: ensure all our constants are initialized prior to the first call of main:\n//\ntemplate <class T>\nstruct mpfi_initializer\n{\n   struct init\n   {\n      init()\n      {\n         boost::math::constants::pi<T>();\n         boost::math::constants::ln_two<T>();\n         boost::math::constants::euler<T>();\n         boost::math::constants::catalan<T>();\n      }\n      void force_instantiate()const{}\n   };\n   static const init initializer;\n   static void force_instantiate()\n   {\n      initializer.force_instantiate();\n   }\n};\n\ntemplate <class T>\nconst typename mpfi_initializer<T>::init mpfi_initializer<T>::initializer;\n\ntemplate<unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nstruct constant_pi<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >\n{\n   typedef boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> result_type;\n   template<int N>\n   static inline result_type const& get(const mpl::int_<N>&)\n   {\n      mpfi_initializer<result_type>::force_instantiate();\n      static result_type result;\n      static bool has_init = false;\n      if(!has_init)\n      {\n         has_init = true;\n         mpfi_const_pi(result.backend().data());\n      }\n      return result;\n   }\n};\ntemplate<unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nstruct constant_ln_two<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >\n{\n   typedef boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> result_type;\n   template<int N>\n   static inline result_type const& get(const mpl::int_<N>&)\n   {\n      mpfi_initializer<result_type>::force_instantiate();\n      static result_type result;\n      static bool has_init = false;\n      if(!has_init)\n      {\n         has_init = true;\n         mpfi_const_log2(result.backend().data());\n      }\n      return result;\n   }\n};\ntemplate<unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nstruct constant_euler<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >\n{\n   typedef boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> result_type;\n   template<int N>\n   static inline result_type const& get(const mpl::int_<N>&)\n   {\n      mpfi_initializer<result_type>::force_instantiate();\n      static result_type result;\n      static bool has_init = false;\n      if(!has_init)\n      {\n         has_init = true;\n         mpfi_const_euler(result.backend().data());\n      }\n      return result;\n   }\n};\ntemplate<unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nstruct constant_catalan<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >\n{\n   typedef boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> result_type;\n   template<int N>\n   static inline result_type const& get(const mpl::int_<N>&)\n   {\n      mpfi_initializer<result_type>::force_instantiate();\n      static result_type result;\n      static bool has_init = false;\n      if(!has_init)\n      {\n         has_init = true;\n         mpfi_const_catalan(result.backend().data());\n      }\n      return result;\n   }\n};\n\n}} // namespaces\n\n}}  // namespaces\n\nnamespace std{\n\n//\n// numeric_limits [partial] specializations for the types declared in this header:\n//\ntemplate<unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nclass numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >\n{\n   typedef boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> number_type;\npublic:\n   BOOST_STATIC_CONSTEXPR bool is_specialized = true;\n   static number_type (min)()\n   {\n      initializer.do_nothing();\n      static std::pair<bool, number_type> value;\n      if(!value.first)\n      {\n         value.first = true;\n         value.second = 0.5;\n         mpfi_div_2exp(value.second.backend().data(), value.second.backend().data(), -mpfr_get_emin());\n      }\n      return value.second;\n   }\n   static number_type (max)()\n   {\n      initializer.do_nothing();\n      static std::pair<bool, number_type> value;\n      if(!value.first)\n      {\n         value.first = true;\n         value.second = 0.5;\n         mpfi_mul_2exp(value.second.backend().data(), value.second.backend().data(), mpfr_get_emax());\n      }\n      return value.second;\n   }\n   BOOST_STATIC_CONSTEXPR number_type lowest()\n   {\n      return -(max)();\n   }\n   BOOST_STATIC_CONSTEXPR int digits = static_cast<int>((Digits10 * 1000L) / 301L + ((Digits10 * 1000L) % 301 ? 2 : 1));\n   BOOST_STATIC_CONSTEXPR int digits10 = Digits10;\n   // Is this really correct???\n   BOOST_STATIC_CONSTEXPR int max_digits10 = Digits10 + 2;\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()\n   {\n      initializer.do_nothing();\n      static std::pair<bool, number_type> value;\n      if(!value.first)\n      {\n         value.first = true;\n         value.second = 1;\n         mpfi_div_2exp(value.second.backend().data(), value.second.backend().data(), std::numeric_limits<number_type>::digits - 1);\n      }\n      return value.second;\n   }\n   // What value should this be????\n   static number_type round_error()\n   {\n      // returns epsilon/2\n      initializer.do_nothing();\n      static std::pair<bool, number_type> value;\n      if(!value.first)\n      {\n         value.first = true;\n         value.second = 1;\n         mpfi_div_2exp(value.second.backend().data(), value.second.backend().data(), 1);\n      }\n      return value.second;\n   }\n   BOOST_STATIC_CONSTEXPR long min_exponent = MPFR_EMIN_DEFAULT;\n   BOOST_STATIC_CONSTEXPR long min_exponent10 = (MPFR_EMIN_DEFAULT / 1000) * 301L;\n   BOOST_STATIC_CONSTEXPR long max_exponent = MPFR_EMAX_DEFAULT;\n   BOOST_STATIC_CONSTEXPR long max_exponent10 = (MPFR_EMAX_DEFAULT / 1000) * 301L;\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_absent;\n   BOOST_STATIC_CONSTEXPR bool has_denorm_loss = false;\n   static number_type infinity()\n   {\n      initializer.do_nothing();\n      static std::pair<bool, number_type> value;\n      if(!value.first)\n      {\n         boost::multiprecision::mpfr_float_backend<Digits10> t;\n         mpfr_set_inf(t.data(), 1);\n         value.first = true;\n         mpfi_set_fr(value.second.backend().data(), t.data());\n      }\n      return value.second;\n   }\n   static number_type quiet_NaN()\n   {\n      initializer.do_nothing();\n      static std::pair<bool, number_type> value;\n      if(!value.first)\n      {\n         boost::multiprecision::mpfr_float_backend<Digits10> t;\n         mpfr_set_nan(t.data());\n         value.first = true;\n         mpfi_set_fr(value.second.backend().data(), t.data());\n      }\n      return value.second;\n   }\n   BOOST_STATIC_CONSTEXPR number_type signaling_NaN()\n   {\n      return number_type(0);\n   }\n   BOOST_STATIC_CONSTEXPR number_type denorm_min() { return number_type(0); }\n   BOOST_STATIC_CONSTEXPR bool is_iec559 = false;\n   BOOST_STATIC_CONSTEXPR bool is_bounded = true;\n   BOOST_STATIC_CONSTEXPR bool is_modulo = false;\n   BOOST_STATIC_CONSTEXPR bool traps = true;\n   BOOST_STATIC_CONSTEXPR bool tinyness_before = false;\n   BOOST_STATIC_CONSTEXPR float_round_style round_style = round_to_nearest;\n\nprivate:\n   struct data_initializer\n   {\n      data_initializer()\n      {\n         std::numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<digits10> > >::epsilon();\n         std::numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<digits10> > >::round_error();\n         (std::numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<digits10> > >::min)();\n         (std::numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<digits10> > >::max)();\n         std::numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<digits10> > >::infinity();\n         std::numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<digits10> > >::quiet_NaN();\n      }\n      void do_nothing()const{}\n   };\n   static const data_initializer initializer;\n};\n\ntemplate<unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nconst typename numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::data_initializer numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::initializer;\n\n#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION\n\ntemplate <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::digits;\ntemplate <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::digits10;\ntemplate <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::max_digits10;\ntemplate <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::is_signed;\ntemplate <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::is_integer;\ntemplate <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::is_exact;\ntemplate <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::radix;\ntemplate <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST long numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::min_exponent;\ntemplate <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST long numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::min_exponent10;\ntemplate <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST long numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::max_exponent;\ntemplate <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST long numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::max_exponent10;\ntemplate <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::has_infinity;\ntemplate <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::has_quiet_NaN;\ntemplate <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::has_signaling_NaN;\ntemplate <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST float_denorm_style numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::has_denorm;\ntemplate <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::has_denorm_loss;\ntemplate <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::is_iec559;\ntemplate <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::is_bounded;\ntemplate <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::is_modulo;\ntemplate <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::traps;\ntemplate <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::tinyness_before;\ntemplate <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST float_round_style numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::round_style;\n\n#endif\n\n\ntemplate<boost::multiprecision::expression_template_option ExpressionTemplates>\nclass numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >\n{\n   typedef boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> number_type;\npublic:\n   BOOST_STATIC_CONSTEXPR bool is_specialized = false;\n   static number_type (min)() { return number_type(0); }\n   static number_type (max)() { return number_type(0); }\n   static number_type lowest() { return number_type(0); }\n   BOOST_STATIC_CONSTEXPR int digits = 0;\n   BOOST_STATIC_CONSTEXPR int digits10 = 0;\n   BOOST_STATIC_CONSTEXPR int max_digits10 = 0;\n   BOOST_STATIC_CONSTEXPR bool is_signed = false;\n   BOOST_STATIC_CONSTEXPR bool is_integer = false;\n   BOOST_STATIC_CONSTEXPR bool is_exact = false;\n   BOOST_STATIC_CONSTEXPR int radix = 0;\n   static number_type epsilon() { return number_type(0); }\n   static number_type round_error() { return number_type(0); }\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(0); }\n   static number_type quiet_NaN() { return number_type(0); }\n   static number_type signaling_NaN() { return number_type(0); }\n   static number_type denorm_min() { return number_type(0); }\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::mpfi_float_backend<0>, ExpressionTemplates> >::digits;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::digits10;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::max_digits10;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::is_signed;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::is_integer;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::is_exact;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::radix;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::min_exponent;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::min_exponent10;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::max_exponent;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::max_exponent10;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::has_infinity;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::has_quiet_NaN;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, 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::mpfi_float_backend<0>, ExpressionTemplates> >::has_denorm;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::has_denorm_loss;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::is_iec559;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::is_bounded;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::is_modulo;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::traps;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::tinyness_before;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST float_round_style numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::round_style;\n\n#endif\n} // namespace std\n#endif\n", "meta": {"hexsha": "81503f7108aaa32fb65e78fa7c13173c0642d7b5", "size": 61008, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/cinder/include/boost/multiprecision/mpfi.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": 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": "deps/cinder/include/boost/multiprecision/mpfi.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": 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": "deps/cinder/include/boost/multiprecision/mpfi.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": 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": 39.5642023346, "max_line_length": 288, "alphanum_fraction": 0.7307730134, "num_tokens": 15178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.26571804995290604}}
{"text": "/************************************************************************\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2014, Péter Fankhauser, Christian Gehring, Stelian Coros\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 Autonomous Systems Lab nor ETH Zurich\n *     nor the names of its contributors may be used to endorse or\n *     promote products derived from this software without specific\n *     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* @file    OoqpEigenInterface.hpp\n* @author  Péter Fankhauser, Christian Gehring\n* @date    Aug 13, 2013\n* @brief   Uses the Object Oriented QP solver package (OOQP) to solve\n*          convex quadratic optimization problems of the type:\n*          Find x: min 1/2 x' Q x + c' x such that A x = b, d <= Cx <= f, and l <= x <= u\n*          where Q is symmetric positive semidefinite (nxn), x is a vector (nx1),\n*          A and C are (possibly null) matrices and b and d are vectors of appropriate dimensions.\n*          We are using sparse matrices in the Harwell-Boeing row-major format.\n*          Adapted from 'simulationandcontrol' by Stelian Coros.\n*/\n\n#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n\nnamespace ooqpei {\n\nclass OoqpEigenInterface\n{\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  /*!\n   * Solve min 1/2 x' Q x + c' x, such that A x = b, d <= Cx <= f, and l <= x <= u.\n   * @param [in] Q a symmetric positive semidefinite matrix (nxn)\n   * @param [in] c a vector (nx1)\n   * @param [in] A a (possibly null) matrices (m_axn)\n   * @param [in] b a vector (m_ax1)\n   * @param [in] C a (possibly null) matrices (m_cxn)\n   * @param [in] d a vector (m_cx1)\n   * @param [in] f a vector (m_cx1)\n   * @param [in] l a vector (nx1)\n   * @param [in] u a vector (nx1)\n   * @param [out] x a vector of variables (nx1)\n   * @return true if successful\n   */\n  static bool solve(const Eigen::SparseMatrix<double, Eigen::RowMajor>& Q,\n                    const Eigen::VectorXd& c,\n                    const Eigen::SparseMatrix<double, Eigen::RowMajor>& A,\n                    const Eigen::VectorXd& b,\n                    const Eigen::SparseMatrix<double, Eigen::RowMajor>& C,\n                    const Eigen::VectorXd& d, const Eigen::VectorXd& f,\n                    const Eigen::VectorXd& l, const Eigen::VectorXd& u,\n                    Eigen::VectorXd& x,\n                    const bool ignoreUnknownError = false);\n\n  /*!\n   * Solve min 1/2 x' Q x + c' x, such that A x = b, and d <= Cx <= f\n   * @param [in] Q a symmetric positive semidefinite matrix (nxn)\n   * @param [in] c a vector (nx1)\n   * @param [in] A a (possibly null) matrices (m_axn)\n   * @param [in] b a vector (m_ax1)\n   * @param [in] C a (possibly null) matrices (m_cxn)\n   * @param [in] d a vector (m_cx1)\n   * @param [in] f a vector (m_cx1)\n   * @param [out] x a vector of variables (nx1)\n   * @return true if successful\n   */\n  static bool solve(const Eigen::SparseMatrix<double, Eigen::RowMajor>& Q,\n                    const Eigen::VectorXd& c,\n                    const Eigen::SparseMatrix<double, Eigen::RowMajor>& A,\n                    const Eigen::VectorXd& b,\n                    const Eigen::SparseMatrix<double, Eigen::RowMajor>& C,\n                    const Eigen::VectorXd& d, const Eigen::VectorXd& f,\n                    Eigen::VectorXd& x,\n                    const bool ignoreUnknownError = false);\n\n  /*!\n   * Solve min 1/2 x' Q x + c' x, such that A x = b, and l <= x <= u.\n   * @param [in] Q a symmetric positive semidefinite matrix (nxn)\n   * @param [in] c a vector (nx1)\n   * @param [in] A a (possibly null) matrices (m_axn)\n   * @param [in] b a vector (m_ax1)\n   * @param [in] l a vector (nx1)\n   * @param [in] u a vector (nx1)\n   * @param [out] x a vector of variables (nx1)\n   * @return true if successful\n   */\n  static bool solve(const Eigen::SparseMatrix<double, Eigen::RowMajor>& Q,\n                    const Eigen::VectorXd& c,\n                    const Eigen::SparseMatrix<double, Eigen::RowMajor>& A,\n                    const Eigen::VectorXd& b,\n                    const Eigen::VectorXd& l, const Eigen::VectorXd& u,\n                    Eigen::VectorXd& x,\n                    const bool ignoreUnknownError = false);\n\n  /*!\n   * Solve min 1/2 x' Q x + c' x, such that Cx <= f\n   * @param [in] Q a symmetric positive semidefinite matrix (nxn)\n   * @param [in] c a vector (nx1)\n   * @param [in] C a (possibly null) matrices (m_cxn)\n   * @param [in] f a vector (m_cx1)\n   * @param [out] x a vector of variables (nx1)\n   * @return true if successful\n   */\n  static bool solve(const Eigen::SparseMatrix<double, Eigen::RowMajor>& Q,\n                    const Eigen::VectorXd& c,\n                    const Eigen::SparseMatrix<double, Eigen::RowMajor>& C,\n                    const Eigen::VectorXd& f,\n                    Eigen::VectorXd& x,\n                    const bool ignoreUnknownError = false);\n\n  /*!\n   * Solve min 1/2 x' Q x + c' x\n   * @param [in] Q a symmetric positive semidefinite matrix (nxn)\n   * @param [in] c a vector (nx1)\n   * @param [out] x a vector of variables (nx1)\n   * @return true if successful\n   */\n  static bool solve(const Eigen::SparseMatrix<double, Eigen::RowMajor>& Q,\n                    const Eigen::VectorXd& c,\n                    Eigen::VectorXd& x,\n                    const bool ignoreUnknownError = false);\n\n  /*!\n   * Change to true to print debug information.\n   * @return true if in debug mode\n   */\n  static bool isInDebugMode() { return isInDebugMode_; };\n  static void setIsInDebugMode(bool isInDebugMode) {\n    isInDebugMode_ = isInDebugMode;\n  }\n\n private:\n  /*!\n   * Determine which limits are active and which are not.\n   * @param [in]  l\n   * @param [in]  u\n   * @param [out] useLowerLimit\n   * @param [out] useUpperLimit\n   * @param [out] lowerLimit\n   * @param [out] upperLimit\n   */\n  static void generateLimits(const Eigen::VectorXd& l, const Eigen::VectorXd& u,\n                      Eigen::Matrix<char, Eigen::Dynamic, 1>& useLowerLimit,\n                      Eigen::Matrix<char, Eigen::Dynamic, 1>& useUpperLimit,\n                      Eigen::VectorXd& lowerLimit, Eigen::VectorXd& upperLimit);\n\n  static void printProblemFormulation(\n      const Eigen::SparseMatrix<double, Eigen::RowMajor>& Q, const Eigen::VectorXd& c,\n      const Eigen::SparseMatrix<double, Eigen::RowMajor>& A, const Eigen::VectorXd& b,\n      const Eigen::SparseMatrix<double, Eigen::RowMajor>& C, const Eigen::VectorXd& d, const Eigen::VectorXd& f,\n      const Eigen::VectorXd& l, const Eigen::VectorXd& u);\n\n  static void printLimits(const Eigen::Matrix<char, Eigen::Dynamic, 1>& useLowerLimit,\n                          const Eigen::Matrix<char, Eigen::Dynamic, 1>& useUpperLimit,\n                          const Eigen::VectorXd& lowerLimit,\n                          const Eigen::VectorXd& upperLimit);\n\n  static void printSolution(const int status, const Eigen::VectorXd& x);\n\n private:\n  static bool isInDebugMode_;\n};\n\n} /* namespace ooqpei */\n", "meta": {"hexsha": "9c5004c179944aa6bad551722fc722ff18a69281", "size": 8294, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ooqp_eigen_interface/OoqpEigenInterface.hpp", "max_stars_repo_name": "tomlankhorst/ooqp_eigen_interface", "max_stars_repo_head_hexsha": "682bb537946e6ff3bb6d68ed5187bb0f888004c8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2016-04-26T15:41:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T06:49:55.000Z", "max_issues_repo_path": "include/ooqp_eigen_interface/OoqpEigenInterface.hpp", "max_issues_repo_name": "tomlankhorst/ooqp_eigen_interface", "max_issues_repo_head_hexsha": "682bb537946e6ff3bb6d68ed5187bb0f888004c8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2015-02-13T12:40:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-01T08:59:02.000Z", "max_forks_repo_path": "include/ooqp_eigen_interface/OoqpEigenInterface.hpp", "max_forks_repo_name": "ethz-asl/ooqp-eigen_interface", "max_forks_repo_head_hexsha": "682bb537946e6ff3bb6d68ed5187bb0f888004c8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2016-02-17T13:21:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T06:08:12.000Z", "avg_line_length": 42.5333333333, "max_line_length": 112, "alphanum_fraction": 0.6200868097, "num_tokens": 2124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.26571804995290604}}
{"text": "#pragma once\n#include <graph/graph.hpp>\n#include <graph/properties.hpp>\n#include <graph/static_graph.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <graph/queue/DijkstraQueue.hpp>\n#include <limits>\n\nnamespace graph\n{\n\ttemplate <typename PredecessorMapTag, class DisanceMapTag, typename WeightMapTag,\n\t          typename IndexMapTag, typename ColorMapTag, typename BundledVertexProperties,\n\t          typename BundledEdgeProperties>\n\tstruct GenerateDijkstraGraph {};\n\n\n\ttemplate <typename PredecessorMapTag, class DisanceMapTag, typename WeightMapTag,\n\t          typename IndexMapTag, typename ColorMapTag, typename... P1s, typename... P2s>\n\tstruct GenerateDijkstraGraph<PredecessorMapTag, DisanceMapTag, WeightMapTag,\n\t                             IndexMapTag, ColorMapTag, Properties<P1s...>, Properties<P2s...>> {\n\t\tusing type = StaticGraph<\n\t\t\tProperties<\n\t\t\t\tProperty<PredecessorMapTag,\n\t\t\t\t         typename graph_traits<StaticGraph<Properties<>, Properties<>>>::vertex_descriptor>,\n\t\t\t\tProperty<DisanceMapTag, uint32_t>,\n\t\t\t\tProperty<ColorMapTag, boost::two_bit_color_type>,\n\t\t\t\tP1s...>,\n\t\t\tProperties<\n\t\t\t\tProperty<WeightMapTag, uint32_t>,\n\t\t\t\tP2s...>>;\n\t};\n\n\ttemplate <typename DistanceMap>\n\tconstexpr typename DistanceMap::value_type InfinityDistance() {\n\t\treturn std::numeric_limits<typename DistanceMap::value_type>::max();\n\t}\n\n\ttemplate <typename Graph>\n\tstruct IDijkstraVisitor {\n\t\t// This is invoked one each vertex of the graph when it is initialized.\n\t\tvoid initialize_vertex(const typename graph_traits<Graph>::vertex_descriptor&, const Graph&) {};\n\n\t\t// This is invoked on a vertex as it is popped from the queue.\n\t\t// This happens immediately before examine_edge() is invoked on each of the out - edges of vertex u.\n\t\tvoid examine_vertex(const typename graph_traits<Graph>::vertex_descriptor&, const Graph&) {};\n\n\t\t// This is invoked on every out - edge of each vertex after it is discovered.\n\t\tvoid examine_edge(const typename graph_traits<Graph>::edge_descriptor&, const Graph&) {};\n\n\t\t// This is invoked when a vertex is encountered for the first time.\n\t\tvoid discover_vertex(const typename graph_traits<Graph>::vertex_descriptor&, const Graph&) {};\n\n\t\t// Upon examination, if the following condition holds then the edge is relaxed(its distance is reduced), and this method is invoked.\n\t\tvoid edge_relaxed(const typename graph_traits<Graph>::edge_descriptor&, const Graph&) {};\n\n\t\t// Upon examination, if the edge is not relaxed(see above) then this method is invoked.\n\t\tvoid edge_not_relaxed(const typename graph_traits<Graph>::edge_descriptor&, const Graph&) {};\n\n\t\t// This invoked on a vertex after all of its out edges have been added to the search tree and\n\t\t// all of the adjacent vertices have been discovered(but before their out - edges have been examined).\n\t\tvoid finish_vertex(const typename graph_traits<Graph>::vertex_descriptor&, const Graph&) {};\n\n\t\t// A predicate which is invoked on every out - edge of each vertex to check if the algorithm should relax it\n\t\tbool should_relax(const typename graph_traits<Graph>::edge_descriptor&, const Graph&) {\n\t\t\treturn true;\n\t\t};\n\n\t\t// A predicate  which is invoked after finish_vertex to check if the algorithm should continue\n\t\tbool should_continue() {\n\t\t\treturn true;\n\t\t};\n\t};\n\n\ttemplate <typename Graph>\n\tclass LazyVertexInitializer {\n\tprivate:\n\t\tusing VertexType = typename graph_traits<Graph>::vertex_descriptor;\n\t\tusing IterationIdType = uint32_t;\n\t\tstd::vector<IterationIdType> vertexIterationId;\n\t\tIterationIdType currentIterationId;\n\tpublic:\n\n\t\tvoid Initialize(Graph& graph) {\n\t\t\tauto verticesCount = num_vertices(graph);\n\t\t\tvertexIterationId.resize(verticesCount, 0);\n\t\t\tif (currentIterationId == std::numeric_limits<IterationIdType>::max()) {\n\t\t\t\tcurrentIterationId = 0;\n\t\t\t\tvertexIterationId.assign(verticesCount, 0);\n\t\t\t}\n\t\t\t++currentIterationId;\n\t\t}\n\n\t\ttemplate <typename IndexMap>\n\t\tbool IsInitialized(const VertexType& v, const IndexMap& index) const {\n\t\t\tauto vertexIndex = get(index, v);\n\t\t\treturn vertexIterationId[vertexIndex] == currentIterationId;\n\t\t}\n\n\t\ttemplate <typename IndexMap>\n\t\tbool TryInitializeVertex(const VertexType& v, const IndexMap& index) {\n\t\t\tauto vertexIndex = get(index, v);\n\t\t\tif (vertexIterationId[vertexIndex] == currentIterationId)\n\t\t\t\treturn false;\n\t\t\tvertexIterationId[vertexIndex] = currentIterationId;\n\t\t\treturn true;\n\t\t}\n\t};\n\n\ttemplate <typename Graph>\n\tstruct DefaultDijkstraVisitor : public IDijkstraVisitor<Graph> {\n\t\tstruct SharedDataStorage {\n\t\t\tusing QueueType = queue::DijkstraQueue<\n\t\t\t\tuint32_t, \n\t\t\t\ttypename graph_traits<Graph>::vertex_descriptor,\n\t\t\t\ttypename property_map<Graph, vertex_index_t>::type>;\n\t\t\tQueueType Queue;\n\t\t\tLazyVertexInitializer<Graph> VertexInitializer;\n\t\t};\n\n\t\tSharedDataStorage Stored;\n\n\t\tDefaultDijkstraVisitor()\n\t\t\t: Stored() {}\n\n\t\tvoid Initialize(Graph& graph) {\n\t\t\tauto verticesCount = num_vertices(graph);\n\t\t\tStored.Queue.Resize(verticesCount);\n\t\t\tStored.Queue.Clear();\n\n\t\t\tStored.VertexInitializer.Initialize(graph);\n\t\t}\n\t};\n\n\ttemplate <class Graph, class PredecessorMap, class DistanceMap,\n\t          class IndexMap, class ColorMap, class DijkstraVisitor>\n\tvoid EnsureVertexInitialization(Graph& graph,\n\t                                const typename graph_traits<Graph>::vertex_descriptor& v,\n\t                                PredecessorMap& predecessor,\n\t                                DistanceMap& distance,\n\t                                IndexMap& index, ColorMap& color,\n\t                                DijkstraVisitor& visitor) {\n\t\tusing DistanceType = typename DistanceMap::value_type;\n\n\t\tif (!visitor.Stored.VertexInitializer.TryInitializeVertex(v, index))\n\t\t\treturn;\n\n\t\tvisitor.initialize_vertex(v, graph);\n\t\tput(distance, v, InfinityDistance<DistanceMap>());\n\t\tput(predecessor, v, v);\n\t\tput(color, v, boost::two_bit_color_type::two_bit_white);\n\t}\n\n\ttemplate <class Graph, class PredecessorMap, class DistanceMap, class IndexMap,\n\t          class ColorMap, class DijkstraVisitor, class Queue>\n\tvoid init_first_vertex(Graph& graph,\n\t                       const typename graph_traits<Graph>::vertex_descriptor& v,\n\t                       PredecessorMap& predecessor,\n\t                       DistanceMap& distance,\n\t                       IndexMap& index, ColorMap& color,\n\t                       DijkstraVisitor& visitor, Queue& queue) {\n\t\tusing DistanceType = typename DistanceMap::value_type;\n\t\tconst DistanceType startDistance = 0;\n\n\t\tEnsureVertexInitialization(graph, v, predecessor, distance, index, color, visitor);\n\t\tvisitor.discover_vertex(v, graph);\n\t\tput(distance, v, startDistance);\n\t\tput(color, v, boost::two_bit_color_type::two_bit_green);\n\t\tqueue.Insert(startDistance, v, index);\n\t}\n\n\ttemplate <class Graph, class PredecessorMap, class DistanceMap, class WeightMap,\n\t          class IndexMap, class ColorMap, class DijkstraVisitor>\n\tbool dijkstra_iteration(Graph& graph,\n\t                        PredecessorMap& predecessor, DistanceMap& distance, WeightMap& weight,\n\t                        IndexMap& index, ColorMap& color, DijkstraVisitor& visitor) {\n\t\tauto& queue = visitor.Stored.Queue;\n\t\t// Get vertex from queue\n\t\tauto topItem = queue.PeekMin();\n\t\tqueue.DeleteMin();\n\t\tauto& v = topItem.Vertex;\n\t\tauto& vDistance = topItem.Distance;\n\t\tvisitor.examine_vertex(v, graph);\n\n\t\t// Process edges\t\n\t\tfor (const auto& edge : graphUtil::Range(out_edges(v, graph))) {\n\t\t\tvisitor.examine_edge(edge, graph);\n\t\t\tif (!visitor.should_relax(edge, graph))\n\t\t\t\tcontinue;\n\t\t\t// Get edge Properties\n\t\t\tauto to = target(edge, graph);\n\t\t\tEnsureVertexInitialization(graph, to, predecessor, distance, index, color, visitor);\n\t\t\tauto edgeWeight = get(weight, edge);\n\t\t\tauto newDistance = vDistance + edgeWeight;\n\t\t\tauto toDistance = get(distance, to);\n\t\t\tif (newDistance < toDistance) {\n\t\t\t\t// Found better distance -> update\n\t\t\t\tput(distance, to, newDistance);\n\t\t\t\tput(predecessor, to, v);\n\t\t\t\tif (get(color, to) == boost::two_bit_color_type::two_bit_white) {\n\t\t\t\t\t// Vertex is new\n\t\t\t\t\tvisitor.discover_vertex(to, graph);\n\t\t\t\t\tput(color, to, boost::two_bit_color_type::two_bit_green);\n\t\t\t\t\tqueue.Insert(newDistance, to, index);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tqueue.DecreaseKey(newDistance, to, index);\n\t\t\t\t}\n\t\t\t\tvisitor.edge_relaxed(edge, graph);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Found same or worse distance\n\t\t\t\tvisitor.edge_not_relaxed(edge, graph);\n\t\t\t}\n\t\t}\n\n\t\t// Teardown vertex\n\t\tput(color, v, boost::two_bit_color_type::two_bit_black);\n\t\tvisitor.finish_vertex(v, graph);\n\t\treturn visitor.should_continue();\n\t};\n\n\n\ttemplate <class Graph, class PredecessorMap, class DistanceMap, class WeightMap,\n\t          class IndexMap, class ColorMap, class DijkstraVisitor = DefaultDijkstraVisitor<Graph>>\n\tvoid dijkstra(Graph& graph,\n\t              const typename graph_traits<Graph>::vertex_descriptor& s,\n\t              PredecessorMap& predecessor, DistanceMap& distance, WeightMap& weight,\n\t              IndexMap& index, ColorMap& color) {\n\t\tDijkstraVisitor visitor;\n\t\tdijkstra(graph, s, predecessor, distance, weight, index, color, visitor);\n\t}\n\n\ttemplate <class Graph, class PredecessorMap, class DistanceMap, class WeightMap,\n\t          class IndexMap, class ColorMap, class DijkstraVisitor = DefaultDijkstraVisitor<Graph>>\n\tvoid dijkstra(Graph& graph,\n\t              const typename graph_traits<Graph>::vertex_descriptor& s,\n\t              PredecessorMap& predecessor, DistanceMap& distance, WeightMap& weight,\n\t              IndexMap& index, ColorMap& color, DijkstraVisitor& visitor) {\n\t\tusing Vertex = typename graph_traits<Graph>::vertex_descriptor;\n\t\tvisitor.Initialize(graph);\n\t\tauto& queue = visitor.Stored.Queue;\n\n\t\t// Process start vertex\t\t\n\t\tinit_first_vertex(graph, s, predecessor, distance, index, color, visitor, queue);\n\n\t\twhile (!queue.IsEmpty()) {\n\t\t\tauto allRight = dijkstra_iteration(graph, predecessor, distance, weight, index, color, visitor);\n\t\t\tif (!allRight)\n\t\t\t\tbreak;\n\t\t}\n\t};\n}\n", "meta": {"hexsha": "35aa586ea4e794bddfe0560fae23d78d817c4ef4", "size": 9882, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/graph/include/graph/dijkstra.hpp", "max_stars_repo_name": "SkyterX/rpclass", "max_stars_repo_head_hexsha": "5e80ec4e0b876eb498351bcf7d6f5983fe5c7934", "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/graph/include/graph/dijkstra.hpp", "max_issues_repo_name": "SkyterX/rpclass", "max_issues_repo_head_hexsha": "5e80ec4e0b876eb498351bcf7d6f5983fe5c7934", "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/graph/include/graph/dijkstra.hpp", "max_forks_repo_name": "SkyterX/rpclass", "max_forks_repo_head_hexsha": "5e80ec4e0b876eb498351bcf7d6f5983fe5c7934", "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.0592885375, "max_line_length": 134, "alphanum_fraction": 0.7105849018, "num_tokens": 2278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.26571804995290604}}
{"text": "#ifndef __TRIAL_HPP__\n#define __TRIAL_HPP__\n\n#include <armadillo>\n#include <random>\n#include <cmath>\n#include <vector>\n#include <initializer_list>\n#include \"seed.hpp\"\n\nnamespace pauth {\n\n/*! \\brief Trial move for continuous degrees of freedom e.g. positions in space\n */\nclass continuous_trial_move {\npublic:\n  /*! \\brief Trial move generator for a continuous monte carlo phase space\n   *\n   * \\param     delta_max     Maximum step size\n   * \\param     sg            Seed generator\n   * \\return                  Trial move generator\n   */\n  continuous_trial_move(const double delta_max, seed_gen sg = _default_seed_gen) \n    : _delta_dist(-delta_max, delta_max) { _rng.seed(sg()); }\n\n  /*! \\brief Copy constructor for continuous trial move generator\n   *\n   * \\param     ctm           Continuous trial move generator\n   * \\param     sg            Seed generator\n   * \\return                  Copy\n   */\n  continuous_trial_move(const continuous_trial_move &ctm, \n                        seed_gen sg = _default_seed_gen) \n    : _delta_dist(ctm._delta_dist.param()) { _rng.seed(sg()); }\n\n  /*! \\brief Generators trial moves for a continuous phase space\n   *\n   * \\param     positions     Molecular positions\n   * \\param     j             Index of molecule to move\n   * \\return                  Trial move\n   */\n  arma::vec operator()(const arma::mat &positions, const size_t) {\n    arma::vec dx(positions.n_rows);\n    for (size_t i = 0; i < positions.n_rows; ++i) dx(i) = _delta_dist(_rng);\n    return dx;\n  }\n\nprivate:\n  std::uniform_real_distribution<double> _delta_dist;\n  std::default_random_engine _rng;\n};\n\n/*! \\brief Trial move for discrete states as opposed to continuous positions\n */\nclass state_trial_move {\npublic:\n  /*! \\brief Trial move generator for a phase space that consists of \"states\"\n   *\n   * \\param     num_states     Number of available states\n   * \\param     sg             Seed generator\n   * \\return                   Trial move generator\n   */\n  state_trial_move(const unsigned num_states = 2,\n                   seed_gen sg = _default_seed_gen) \n    : _state_dist(0, num_states-1) { _rng.seed(sg()); }\n\n  /*! \\brief Copy constructor for state trial move generator\n   *\n   * \\param     stm           State trial move generator\n   * \\param     sg            Seed generator\n   * \\return                  Copy\n   */\n  state_trial_move(const state_trial_move &stm, seed_gen sg = _default_seed_gen) \n    : _state_dist(stm._state_dist.param()) { _rng.seed(sg()); }\n\n  /*! \\brief Generates trial move for a two-state system\n   *\n   * \\param     positions     Molecular positions\n   * \\param     j             Index of molecule to move\n   * \\return                  Trial move\n   */\n  arma::vec operator()(const arma::mat &positions, const size_t j) {\n    arma::vec dx(1);\n    dx(0) = _state_dist(_rng);\n    return dx - positions(0, j);\n  }\n\nprivate:\n  std::uniform_int_distribution<unsigned> _state_dist;\n  std::default_random_engine _rng;\n};\n\n/*! \\brief Direct sampling trial move generator\n */\ntemplate <class T> class direct_sample {\npublic:\n  /*! \\brief Trial move generator for direct sampling by distributions\n   *\n   * \\param     dists          Sampling distributions\n   * \\param     sg             Seed generator\n   * \\return                   Trial move generator\n   */\n  direct_sample<T>(std::initializer_list<T> dists, \n                   seed_gen sg = _default_seed_gen) : _dof_dists(dists),\n    _choice_dist(0, _dof_dists.size()-1) {\n    _rng.seed(sg());\n  }\n\n  /*! \\brief Trial move generator for direct sampling by a distribution\n   *\n   * \\param     dist           Sampling distribution\n   * \\param     N              Degrees of freedom per particle\n   * \\param     sg             Seed generator\n   * \\return                   Trial move generator\n   */\n  direct_sample<T>(T dist, size_t N, seed_gen sg = _default_seed_gen) : \n    _dof_dists(dist, N), _choice_dist(0, _dof_dists.size()-1) { \n    _rng.seed(sg()); \n  }\n\n  /*! \\brief Generates trial move for a two-state system\n   *\n   * \\param     positions     Molecular positions\n   * \\param     j             Index of molecule to move\n   * \\return                  Trial move\n   */\n  arma::vec operator()(const arma::mat &positions, const size_t j) {\n    auto dx = arma::zeros<arma::vec>(_dof_dists.size());\n    auto choice = _rng(_choice_dist); // choose a degree of freedom\n    // directly sample a degree of freedom from its associated distribution\n    dx(choice) = _rng(_dof_dists(choice)) - positions(choice, j);\n    return dx;\n  }\n\nprivate:\n  std::vector<T> _dof_dists;\n  std::uniform_int_distribution<size_t> _choice_dist;\n  std::default_random_engine _rng;\n};\n\n}\n\n#endif\n", "meta": {"hexsha": "acfcfa93fec661a39686d1c28b57838653035b7f", "size": 4665, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/trial.hpp", "max_stars_repo_name": "grasingerm/port-authority", "max_stars_repo_head_hexsha": "51db6b09d6a1545eafeaf6be037a23d47313c490", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/trial.hpp", "max_issues_repo_name": "grasingerm/port-authority", "max_issues_repo_head_hexsha": "51db6b09d6a1545eafeaf6be037a23d47313c490", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/trial.hpp", "max_forks_repo_name": "grasingerm/port-authority", "max_forks_repo_head_hexsha": "51db6b09d6a1545eafeaf6be037a23d47313c490", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3958333333, "max_line_length": 81, "alphanum_fraction": 0.6261521972, "num_tokens": 1143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2653678593456402}}
{"text": "/**\n * @file\n * This file is part of SeisSol.\n *\n * @author Sebastian Rettenberger (sebastian.rettenberger AT tum.de, http://www5.in.tum.de/wiki/index.php/Sebastian_Rettenberger)\n *\n * @section LICENSE\n * Copyright (c) 2015-2016, 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 <cstring>\n#include <limits>\n#include <string>\n\n#include <pthread.h>\n\n#include <pstream.h>\n\n#include <Eigen/Dense>\n\n#include <netcdf.h>\n\n#include <proj_api.h>\n\n#include \"utils/args.h\"\n#include \"utils/logger.h\"\n#include \"utils/stringutils.h\"\n\nconst static float MIN_VALID = -10000;\n\ntypedef Eigen::Array<unsigned long, 3, 1> ularr3;\ntypedef Eigen::Array<unsigned long, 2, 1> ularr2;\n\nstruct inputData_t\n{\n        Eigen::Array3d minVert;\n        ularr3 gridSize;\n\tEigen::Array3d gridDist;\n\n\tconst char* meshProj;\n\tbool meshIsGeo;\n\tconst char* queryProj;\n\tbool queryIsGeo;\n\n\tredi::rpstream& query;\n};\n\n/**\n * Check netCDF return value for errors\n */\nstatic void checkNcIError(int error)\n{\n\tif (error != NC_NOERR)\n\t\tlogError() << \"Error while reading netCDF file:\" << nc_strerror(error);\n}\n\n/**\n * Check netCDF return value for errors\n */\nstatic void checkNcOError(int error)\n{\n\tif (error != NC_NOERR)\n\t\tlogError() << \"Error while writing netCDF file:\" << nc_strerror(error);\n}\n\n/**\n * The input thread for the query program\n */\nstatic void* runInput(void* p)\n{\n\tinputData_t* i = reinterpret_cast<inputData_t*>(p);\n\n\t// Project from mesh to sample code\n\tunsigned long totalArea = i->gridSize(0) * i->gridSize(1);\n\tdouble* projX = new double[totalArea];\n\tdouble* projY = new double[totalArea];\n\n\tconst bool meshIsGeo = i->meshIsGeo;\n\n\tfor (unsigned long y = 0; y < i->gridSize(1); y++) {\n\t\tfor (unsigned long x = 0; x < i->gridSize(0); x++) {\n\t\t\tularr2 pos(x, y);\n                        Eigen::Array2d coord = i->minVert.block<2,1>(0,0) + pos.cast<double>() * i->gridDist.block<2,1>(0,0);\n\t\t\tif (meshIsGeo)\n\t\t\t\tcoord *= Eigen::Array2d(DEG_TO_RAD, DEG_TO_RAD);\n\n\t\t\tprojX[y*i->gridSize(0) + x] = coord(0);\n\t\t\tprojY[y*i->gridSize(0) + x] = coord(1);\n\t\t}\n\t}\n\n\t// Project coordinates\n\tprojPJ pjMesh = pj_init_plus(i->meshProj);\n\tprojPJ pjQuery = pj_init_plus(i->queryProj);\n\tif (pj_transform(pjMesh, pjQuery, totalArea, 1, projX, projY, 0L) != 0)\n\t\tlogError() << \"Coordinate transformation failed\";\n\n\t// Convert to degree\n\tif (i->queryIsGeo) {\n\t\tfor (unsigned long x = 0; x < totalArea; x++) {\n\t\t\tprojX[x] *= RAD_TO_DEG;\n\t\t\tprojY[x] *= RAD_TO_DEG;\n\t\t}\n\t}\n\n\t// Send the input data\n\ti->query << (totalArea * i->gridSize(2)) << std::endl;\n\tfor (unsigned long z = 0; z < i->gridSize(2); z++) {\n\t\tdouble depth = i->minVert(2) + z * i->gridDist(2);\n\t\tfor (unsigned long x = 0; x < totalArea; x++)\n\t\t\ti->query << projX[x] << ' ' << projY[x] << ' ' << depth << std::endl;\n\t}\n\n\t// Send eof\n\ti->query << redi::peof;\n\n\tdelete [] projX;\n\tdelete [] projY;\n\n\treturn 0L;\n}\n\nstatic float vs2mu(float vs, float rho)\n{\n\treturn vs*vs * rho;\n}\n\nstatic float vp2lambda(float vp, float rho, float mu)\n{\n\treturn vp*vp * rho - 2*mu;\n}\n\nint main(int argc, char* argv[])\n{\n\t// Parse command line arguments\n\tutils::Args args;\n\targs.addOption(\"mesh\", 'm', \"The mesh for which the data should be collected\");\n\targs.addOption(\"border\", 'b', \"Border around the mesh for which data should be included\",\n\t\t\tutils::Args::Required, false);\n\targs.addOption(\"size\", 's', \"Size of the out grid (Format x:y:z)\");\n\targs.addOption(\"query\", 'q', \"Path to the query program (Default: ./scripts/vx_lite_wrapper)\",\n\t\t\tutils::Args::Required, false);\n//\targs.addOption(\"elevation\", 'e', \"Path to x_SRTM3, y_SRTM3, z_SRTM3 containing an elevation map\\n\"\n//\t\t\t\"                              If empty, elevation instead of elevation offset is used for querying.\",\n//\t\t\tutils::Args::Required, false);\n\t// See http://spatialreference.org/\n\targs.addOption(\"mesh-proj\", 0, \"Mesh coordinate projection (Default: UTM11)\",\n\t\t\tutils::Args::Required, false);\n\targs.addOption(\"mesh-proj-geo\", 0, \"Mesh coordinates are geographic locations (Default: No)\",\n\t\t\tutils::Args::Required, false);\n\targs.addOption(\"query-proj\", 0, \"Query coordinate projection (Default: WGS84)\",\n\t\t\tutils::Args::Required, false);\n\targs.addOption(\"query-proj-geo\", 0, \"Query coordinates are geographic locations (Default: Yes)\",\n\t\t\tutils::Args::Required, false);\n\targs.addOption(\"paraview\", 'p', \"Viewable by Paraview\", utils::Args::No, false);\n\targs.addOption(\"chunk-size\", 'c', \"Chunk size for the netCDF file\",\n\t\t\tutils::Args::Required, false);\n\targs.addAdditionalOption(\"output\", \"netCDF output file\");\n\n\t// Parse/check command line arguments\n\tif (!args.parse(argc, argv) == utils::Args::Success)\n\t\treturn 1;\n\n\t// Get the grid size\n\tstd::vector<std::string> sizeVec = utils::StringUtils::split(args.getArgument<std::string>(\"size\"), ':');\n\tif (sizeVec.size() != 3)\n\t\tlogError() << \"Size format must be \\\"x:y:z\\\"\";\n\tularr3 gridSize(utils::StringUtils::parse<unsigned long>(sizeVec[0]),\n\t\t\tutils::StringUtils::parse<unsigned long>(sizeVec[1]),\n\t\t\tutils::StringUtils::parse<unsigned long>(sizeVec[2]));\n\n\tlogInfo() << \"Grid size:\" << utils::nospace\n\t\t\t<< \"[\" << gridSize(0) << \", \" << gridSize(1) << \", \" << gridSize(2) << \"]\";\n\n\t// Read the coordinates from the mesh\n\tconst char* mesh = args.getArgument<const char*>(\"mesh\");\n\n\tint ncFile;\n\tcheckNcIError(nc_open(mesh, NC_NOWRITE, &ncFile));\n\n\t// Get the number of partitions\n\tint ncDimPart;\n\tcheckNcIError(nc_inq_dimid(ncFile, \"partitions\", &ncDimPart));\n\tsize_t partitions;\n\tcheckNcIError(nc_inq_dimlen(ncFile, ncDimPart, &partitions));\n\n\t// Get max number of vertices\n\tint ncDimVertices;\n\tcheckNcIError(nc_inq_dimid(ncFile, \"vertices\", &ncDimVertices));\n\tsize_t maxVertices;\n\tcheckNcIError(nc_inq_dimlen(ncFile, ncDimVertices, &maxVertices));\n\n\t// Get min/max vertices\n\tEigen::Array3d minVert(\n\t\t\tstd::numeric_limits<double>::infinity(),\n\t\t\tstd::numeric_limits<double>::infinity(),\n\t\t\tstd::numeric_limits<double>::infinity());\n\tEigen::Array3d maxVert(\n\t\t\t-std::numeric_limits<double>::infinity(),\n\t\t\t-std::numeric_limits<double>::infinity(),\n\t\t\t-std::numeric_limits<double>::infinity());\n\n\tdouble* vertices = new double[maxVertices*3];\n\n\tint ncVarVrtxSize;\n\tcheckNcIError(nc_inq_varid(ncFile, \"vertex_size\", &ncVarVrtxSize));\n\tint ncVarVrtxCoords;\n\tcheckNcIError(nc_inq_varid(ncFile, \"vertex_coordinates\", &ncVarVrtxCoords));\n\tfor (size_t i = 0; i < partitions; i++) {\n\t\tsize_t start[3] = {i, 0, 0};\n\t\tint size;\n\t\tcheckNcIError(nc_get_var1_int(ncFile, ncVarVrtxSize, start, &size));\n\n\t\tsize_t count[3] = {1, static_cast<size_t>(size), 3};\n\t\tcheckNcIError(nc_get_vara_double(ncFile, ncVarVrtxCoords, start, count, vertices));\n\n\t\tfor (int j = 0; j < size; j++) {\n\t\t\tEigen::Array3d v = Eigen::Map<Eigen::Array3d>(&vertices[j*3]);\n\n\t\t\tminVert = minVert.min(v);\n\t\t\tmaxVert = maxVert.max(v);\n\t\t}\n\t}\n\n\tcheckNcIError(nc_close(ncFile));\n\n\tdelete [] vertices;\n\n\t// Add borders\n\tdouble border = args.getArgument(\"border\", 0.);\n\tminVert -= Eigen::Array3d(border, border, border);\n\tmaxVert += Eigen::Array3d(border, border, border);\n\n\tlogInfo() << \"Grid dimension (incl. border):\" << utils::nospace\n\t\t\t<< \"[\" << minVert(0) << \", \" << minVert(1) << \", \" << minVert(2) << \"] x [\"\n\t\t\t<< maxVert(0) << \", \" << maxVert(1) << \", \" << maxVert(2) << \"]\";\n\n\t// Distance between grid points\n\tEigen::Vector3d gridDist = (maxVert - minVert)\n\t\t\t* (gridSize - ularr3(1, 1, 1)).cast<double>().inverse();\n\n\tlogInfo() << \"Grid interval:\" << utils::nospace\n\t\t\t<< \"[\" << gridDist(0) << \", \" << gridDist(1) << \", \" << gridDist(2) << \"]\";\n\n\t// Create query process\n\tredi::rpstream pstream(args.getArgument(\"query\", \"./scripts/vx_lite_wrapper\"),\n\t\t\tredi::pstreambuf::pstdin | redi::pstreambuf::pstdout);\n\n\t// Start the input and error thread\n\tinputData_t inputData {\n\t\tminVert,\n\t\tgridSize,\n\t\tgridDist,\n\t\targs.getArgument(\"mesh-proj\", \"+proj=utm +zone=11 +ellps=WGS84 +datum=WGS84 +units=m +no_defs\"),\n\t\targs.getArgument(\"mesh-proj-geo\", false),\n\t\targs.getArgument(\"query-proj\", \"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs\"),\n\t\targs.getArgument(\"query-proj-geo\", true),\n\t\tpstream\n\t};\n\n\tpthread_t inputThread;\n\tpthread_create(&inputThread, 0L, runInput, &inputData);\n\n\t// Viewable by Paraview?\n\tbool paraview = args.getArgument(\"paraview\", false);\n\n\t// Open the netCDF file\n\tconst char* outputName = args.getAdditionalArgument<const char*>(\"output\");\n\tcheckNcOError(nc_create(outputName, NC_NETCDF4, &ncFile));\n\n\t// Create dimensions\n\tint ncDims[3];\n\tcheckNcOError(nc_def_dim(ncFile, \"x\", gridSize(0), &ncDims[2]));\n\tcheckNcOError(nc_def_dim(ncFile, \"y\", gridSize(1), &ncDims[1]));\n\tcheckNcOError(nc_def_dim(ncFile, \"z\", gridSize(2), &ncDims[0]));\n\n\t// Create dimension variables\n\tint ncX, ncY, ncZ;\n\tcheckNcOError(nc_def_var(ncFile, \"x\", NC_FLOAT, 1, &ncDims[2], &ncX));\n\tcheckNcOError(nc_def_var(ncFile, \"y\", NC_FLOAT, 1, &ncDims[1], &ncY));\n\tcheckNcOError(nc_def_var(ncFile, \"z\", NC_FLOAT, 1, &ncDims[0], &ncZ));\n\n\t// Create variables\n\tint ncData, ncRho, ncMu, ncLambda;\n\tif (paraview) {\n\t\tcheckNcOError(nc_def_var(ncFile, \"rho\", NC_FLOAT, 3, ncDims, &ncRho));\n\t\tcheckNcOError(nc_def_var(ncFile, \"mu\", NC_FLOAT, 3, ncDims, &ncMu));\n\t\tcheckNcOError(nc_def_var(ncFile, \"lambda\", NC_FLOAT, 3, ncDims, &ncLambda));\n\t} else {\n\t\t// Create compound type\n\t\tint ncType;\n\t\tcheckNcOError(nc_def_compound(ncFile, 3*sizeof(float), \"material\", &ncType));\n\t\tcheckNcOError(nc_insert_compound(ncFile, ncType, \"rho\", 0, NC_FLOAT));\n\t\tcheckNcOError(nc_insert_compound(ncFile, ncType, \"mu\", sizeof(float), NC_FLOAT));\n\t\tcheckNcOError(nc_insert_compound(ncFile, ncType, \"lambda\", 2*sizeof(float), NC_FLOAT));\n\n\t\tcheckNcOError(nc_def_var(ncFile, \"data\", ncType, 3, ncDims, &ncData));\n\n\t\tif (args.isSet(\"chunk-size\")) {\n\t\t\tunsigned int chunkSize = args.getArgument<unsigned int>(\"chunk-size\");\n\n\t\t\tsize_t chunks[3] = {chunkSize, chunkSize, chunkSize};\n\t\t\tcheckNcOError(nc_def_var_chunking(ncFile, ncData, NC_CHUNKED, chunks));\n\t\t}\n\t}\n\n\tcheckNcOError(nc_enddef(ncFile));\n\n\t// Fill dimension variables\n\tfloat* x = new float[gridSize(0)];\n\tfor (unsigned int i = 0; i < gridSize(0); i++) {\n\t\tx[i] = minVert(0) + gridDist(0) * i;\n\t}\n\tcheckNcOError(nc_put_var_float(ncFile, ncX, x));\n\tdelete [] x;\n\n\tfloat* y = new float[gridSize(1)];\n\tfor (unsigned int i = 0; i < gridSize(1); i++) {\n\t\ty[i] = minVert(1) + gridDist(1) * i;\n\t}\n\tcheckNcOError(nc_put_var_float(ncFile, ncY, y));\n\tdelete [] y;\n\n\tfloat* z = new float[gridSize(2)];\n\tfor (unsigned int i = 0; i < gridSize(2); i++) {\n\t\tz[i] = minVert(2) + gridDist(2) * i;\n\t}\n\tcheckNcOError(nc_put_var_float(ncFile, ncZ, z));\n\tdelete [] z;\n\n\t// Read the data from the query tool\n\tunsigned long totalArea = gridSize(0) * gridSize(1);\n\tfloat* data = new float[totalArea*3];\n\n\t// Initialize data with invalid values\n\tfor (unsigned long i = 0; i < totalArea*3; i++)\n\t\tdata[i] = std::numeric_limits<float>::infinity();\n\n\tfor (unsigned long z = 0; z < gridSize(2); z++) {\n\t\tfor (unsigned long i = 0; i < totalArea; i++) {\n\t\t\t// Ignore the coordinates\n\t\t\tfloat x, y, z;\n\t\t\tpstream.out() >> x >> y >> z;\n\n\t\t\tfloat vp, vs, rho;\n\t\t\tpstream.out() >> vp >> vs >> rho;\n\n\t\t\tfloat mu, lambda;\n\t\t\tif (vp >= MIN_VALID && vs >= MIN_VALID && rho >= MIN_VALID) {\n\t\t\t\tmu = vs2mu(vs, rho);\n\t\t\t\tlambda = vp2lambda(vp, rho, mu);\n\n\t\t\t\tif (paraview) {\n\t\t\t\t\tdata[i] = rho;\n\t\t\t\t\tdata[i + totalArea] = mu;\n\t\t\t\t\tdata[i + totalArea*2] = lambda;\n\t\t\t\t} else {\n\t\t\t\t\tdata[i*3] = rho;\n\t\t\t\t\tdata[i*3 + 1] = mu;\n\t\t\t\t\tdata[i*3 + 2] = lambda;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (z == 0)\n\t\t\t\t\tlogError() << \"Invalid value in deepest level.\";\n\t\t\t}\n\t\t}\n\n\t\tsize_t start[3] = {z, 0, 0};\n\t\tsize_t count[3] = {1, gridSize(1), gridSize(0)};\n\n\t\tif (paraview) {\n\t\t\tcheckNcOError(nc_put_vara_float(ncFile, ncRho, start, count, data));\n\t\t\tcheckNcOError(nc_put_vara_float(ncFile, ncMu, start, count, &data[totalArea]));\n\t\t\tcheckNcOError(nc_put_vara_float(ncFile, ncLambda, start, count, &data[totalArea*2]));\n\t\t} else {\n\t\t\tcheckNcOError(nc_put_vara(ncFile, ncData, start, count, data));\n\t\t}\n\t}\n\n\tpthread_join(inputThread, 0L);\n\n\t// Cleanup\n\tcheckNcOError(nc_close(ncFile));\n\n\tdelete [] data;\n\n\tlogInfo() << \"Finished\";\n}\n", "meta": {"hexsha": "4dc3b1dad68feaa4a8d83736bced0f9cc415ddc2", "size": 13530, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "preprocessing/science/asagiconv/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": "preprocessing/science/asagiconv/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": "preprocessing/science/asagiconv/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": 32.3684210526, "max_line_length": 129, "alphanum_fraction": 0.674796748, "num_tokens": 4066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2653678533740204}}
{"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 <deque>\n#include <iostream>\n#include <algorithm>\n#include <boost/math/distributions/chi_squared.hpp>\n#include \"genfile/string_utils.hpp\"\n#include \"appcontext/OptionProcessor.hpp\"\n#include \"appcontext/ApplicationContext.hpp\"\n#include \"appcontext/get_current_time_as_string.hpp\"\n#include \"appcontext/ProgramFlow.hpp\"\n#include \"config/qctool_version_autogenerated.hpp\"\n#include \"config/config.hpp\"\n#if HAVE_MGL\n\t#include \"mgl/mgl.h\"\n\t#include \"mgl/mgl_zb.h\"\n#endif\n\nnamespace globals {\n\tstd::string const program_name = \"inflation\" ;\n\tstd::string const program_version = qctool_revision ;\n}\n\nstruct InflationApplication: public appcontext::ApplicationContext\n{\npublic:\n\tstatic void declare_options( appcontext::OptionProcessor& options ) {\n\t\toptions.set_help_option( \"-help\" ) ;\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_default_value( \"inflation analysis, started \" + appcontext::get_current_time_as_string() ) ;\n\t\toptions [ \"-qq-plot\" ]\n\t\t\t.set_description( \"Specify that \" + globals::program_name + \" should make a qq-plot in the file with the given name.\" )\n\t\t\t.set_takes_single_value() ;\n\t\toptions [ \"-log\" ]\n\t\t\t.set_description( \"Specify that \" + globals::program_name + \" should write a log file to the given file.\" )\n\t\t\t.set_takes_single_value() ;\n\t}\n\npublic:\n\tInflationApplication( appcontext::OptionProcessor::UniquePtr options, int argc, char** argv ):\n\t\tappcontext::ApplicationContext( globals::program_name, globals::program_version , options, argc, argv, \"-log\" )\n\t{\n\t}\n\t\n\tvoid process() {\n\t\tunsafe_process(); \n\t}\nprivate:\n\t\n\tvoid unsafe_process() {\n\t\tget_ui_context().logger() << application_name() << \": reading...\" ;\n\n\t\tstd::string line ;\n\t\tstd::deque< float > numbers ;\n\t\tstd::size_t missing_count = 0 ;\n\t\twhile( std::getline( std::cin, line )) {\n\t\t\tif( line.empty() || line.find_first_not_of( \"0123456789.E+-\" ) != std::string::npos ) {\n\t\t\t\t++missing_count ;\n\t\t\t} else {\n\t\t\t\tnumbers.push_back( genfile::string_utils::to_repr< float >( line ) ) ;\n\t\t\t}\n\n\t\t\tif( ( numbers.size() + missing_count ) % 1000000 == 0 ) {\n\t\t\t\tget_ui_context().logger() << ( numbers.size() + missing_count ) << \"..\" ;\n\t\t\t}\n\t\t}\n\n\t\tget_ui_context().logger() << ( numbers.size() / 1000000 ) << \".\\n\" ;\n\t\tget_ui_context().logger() << \"inflation.cpp: read \" << numbers.size() << \" P-values from std::cin.\\n\" ;\n\t\tget_ui_context().logger() << \"inflation.cpp: converting to chi-squared statistics...\\n\" ;\n\t\tusing namespace boost::math ;\n\t\tchi_squared_distribution< float > chi_square( 1 ) ;\n\t\tfor( std::size_t i = 0; i < numbers.size(); ++i ) {\n\t\t\tnumbers[i] = quantile( complement( chi_square, numbers[i] )) ;\n\t\t}\n\n\t\tget_ui_context().logger() << \"inflation.cpp: finding median...\\n\" ;\n\n\t\tstd::cout << \"analysis,N,missing,median,lambda,1pc_adjusted_median,1pc_adjusted_lambda\\n\" ;\n\t\tstd::cout\n\t\t\t<< options().get< std::string >( \"-analysis-name\" ) << \",\"\n\t\t\t<< numbers.size() << \",\"\n\t\t\t<< missing_count ;\n\t\t// Compute basic lambda\n\t\t{\n\t\t\tstd::size_t const mid = numbers.size() / 2 ;\n\t\t\tstd::nth_element( numbers.begin(), numbers.begin() + mid, numbers.end() ) ;\n\t\t\tdouble const median = numbers[ mid ] ;\n\t\t\tstd::cout << \",\" << median << \",\" << (median / quantile( complement( chi_square, 0.5 ))) ;\n\t\t}\n\n\t\tif( options().check( \"-qq-plot\" )) {\n#if HAVE_MGL\n\t\t\tget_ui_context().logger() << \"inflation.cpp: making qq-plot...\\n\" ;\t\n\t\t\tplot( numbers, options().get< std::string >( \"-qq-plot\" ), options().get< std::string >( \"-analysis-name\" ) ) ;\n#else\n\t\t\tget_ui_context().logger() << \"!! InflationApplication::unsafe_process(): you must build with MathGL support for -qq-plot to be supported.  Skipping plots...\\n\" ;\n#endif\n\t\t}\n\n\t\t// Compute lambda after removing top 99% of signal\n\t\t{\n\t\t\tstd::size_t const top_one_percent = numbers.size() * 0.99 ;\n\t\t\tstd::deque< float >::iterator top_one_percent_i = numbers.begin() + top_one_percent ;\n\t\t\tnumbers.erase( top_one_percent_i, numbers.end() ) ;\n\t\t}\n\n\t\t{\n\t\t\tstd::size_t const mid = numbers.size() / 2 ;\n\t\t\tstd::nth_element( numbers.begin(), numbers.begin() + mid, numbers.end() ) ;\n\t\t\tdouble const median = numbers[ mid ] ;\n\t\t\tstd::cout << \",\" << median << \",\" << (median / quantile( complement( chi_square, 0.5 ))) ;\n\t\t}\n\t\tstd::cout << \"\\n\" ;\n\t}\n\t\n#if HAVE_MGL\n\tvoid plot( std::deque< float >& numbers, std::string const& filename, std::string const& title ) {\n\t\tstd::sort( numbers.begin(), numbers.end() ) ;\n\n\t\tmglData\n\t\t\tobserved( numbers.size() ),\n\t\t\texpected( numbers.size() )\n\t\t;\n\t\t\n\t\tusing namespace boost::math ;\n\t\t{\n\t\t\tchi_squared_distribution< float > chi_squared( 1 ) ;\n\t\t\tfor( std::size_t i = 0; i < numbers.size(); ++i ) {\n\t\t\t\tobserved.a[i] = numbers[i] ;\n\t\t\t\texpected.a[i] = quantile( complement( chi_squared, float( numbers.size() - i ) / ( numbers.size() + 1 ) ) ) ;\n\t\t\t}\n\t\t}\n\t\tmglGraphZB graph( 800, 800 ) ;\n\t\tgraph.Light( true ) ;\n\t\tgraph.Clf( mglColor( 1.0, 1.0, 1.0 ) ) ;\n\t\tgraph.Title( title.c_str(), 0, 4 ) ;\n\t\tgraph.SetTickLen( 0.04 ) ;\n\t\tgraph.SetRanges(\n\t\t\t0.0, 30,\n\t\t\t0.0, 30\n\t\t) ;\n\t\tgraph.Axis( \"x\", true ) ;\n\t\tgraph.Axis( \"y\", true ) ;\n\t\tgraph.CAxis( 0.0, 3.0 ) ;\n\n\t\tgraph.Plot( expected, observed ) ; //, observed ) ;\n\t\tgraph.WritePNG( filename.c_str(), \"\", false ) ;\n\t}\n#endif\n} ;\n\nint main( int argc, char** argv ) {\n\ttry {\n\t\tappcontext::OptionProcessor::UniquePtr options( new appcontext::OptionProcessor ) ;\n\t\tInflationApplication::declare_options( *options ) ;\n\t\tInflationApplication app( options, argc, argv ) ;\n\t\tapp.process() ;\n\t} catch ( appcontext::HaltProgramWithReturnCode const& e ) {\n\t\treturn e.return_code() ;\n\t}\n\treturn 0 ;\n}\n\n", "meta": {"hexsha": "e4ca080d1f96a16099adf16f726de05b12099583", "size": 5915, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/inflation.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/inflation.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/inflation.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": 34.3895348837, "max_line_length": 164, "alphanum_fraction": 0.6561284869, "num_tokens": 1689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.26520692555097297}}
{"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 <map>\n#include <unordered_map>\n#include <iterator>\n#include <future>\n#include <thread>\n#include <algorithm>\n#include <dirent.h>\n#include <armadillo>\n#include <boost/python/call.hpp>\n\nusing namespace std;\n\nFocalGrid::FocalGrid() {\n\t// empty\n}\n\nbool FocalGrid::SetGridParameters(session_data &session, frame_data &frame, int NX, int NY, int NZ, double DS, double X0, double Y0, double Z0) {\n\n\tbool grid_loaded = true;\n\n\t// Set the focal grid parameters:\n\ttry {\n\n\t\t// grid parameters:\n\t\tnx = NX;\n\t\tny = NY;\n\t\tnz = NZ;\n\t\tds = DS;\n\t\tx0 = X0;\n\t\ty0 = Y0;\n\t\tz0 = Z0;\n\n\t\t// load calibration file:\n\t\tstring calib_file = session.session_loc + \"/\" + session.cal_loc + \"/\" + session.cal_name;\n\n\t\tarma::Mat<double> CalibMatrix;\n\n\t\tCalibMatrix.load(calib_file);\n\n\t\t// Clear vectors:\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\t// Set N_cam\n\t\tN_cam = session.N_cam;\n\n\t\tfor (int i=0; i<N_cam; i++) {\n\t\t\timage_size.push_back(make_tuple(get<0>(frame.image_size[i]),get<1>(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\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\tuv_offset.push_back(uv_off_i);\n\t\t}\n\n\n\t}\n\tcatch (...) {\n\t\tcout << \"Could not set focal grid parameters.\" << endl;\n\t\tgrid_loaded = false;\n\t}\n\n\treturn grid_loaded;\n}\n\nbool FocalGrid::ConstructFocalGrid(PyObject* progress_func) {\n\n\tbool grid_build = true;\n\n\tint voxel_ind = 0;\n\n\tint progress = 0;\n\n\ttry {\n\n\t\tpix2vox.clear();\n\t\tvox2pix.clear();\n\n\t\tfor (int k=0; k<nz; k++) {\n\t\t\tprogress = (int) 100.0*(((k+1)*1.0)/(nz*1.0));\n\t\t\tboost::python::call<void>(progress_func,progress);\n\t\t\tfor (int j=0; j<ny; j++) {\n\t\t\t\tfor (int i=0; i<nx; i++) {\n\t\t\t\t\tvector<int> uv_voxel = FocalGrid::CheckVoxel(i, j, k);\n\t\t\t\t\tif (uv_voxel.size()==N_cam) {\n\t\t\t\t\t\tvoxel_ind = k*nx*ny+j*nx+i;\n\t\t\t\t\t\tpix2vox.insert(pair<int,int>(uv_voxel[0],voxel_ind));\n\t\t\t\t\t\tvox2pix.insert(pair<int,vector<int>>(voxel_ind,uv_voxel));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcout << \"focal grid size: \" << pix2vox.size() << endl;\n\t\tcout << \"focal grid has been constructed\" << endl;\n\t}\n\tcatch (...) {\n\t\tgrid_build = false;\n\t\tcout << \"could not construct focal grid\" << endl;\n\t}\n\n\treturn grid_build;\n}\n\nvector<int> FocalGrid::CheckVoxel(int i, int j, int k) {\n\n\tvector<int> uv_out;\n\n\tint uv_ind = -1;\n\n\tarma::Col<double> xyz(4);\n\n\txyz = {x0-((nx-1)/2.0)*ds+i*ds, \n\t\ty0-((ny-1)/2.0)*ds+j*ds,\n\t\tz0-((nz-1)/2.0)*ds+k*ds,\n\t\t1.0};\n\n\tarma::Col<double> uv(3);\n\n\tfor (int n=0; n<N_cam; n++) {\n\t\tuv = X_uv[n]*xyz-uv_offset[n];\n\t\tif (uv(0)>=0.0 && uv(0)<(1.0*get<1>(image_size[n]))) {\n\t\t\tif (uv(1)>=0.0 && uv(1)<(1.0*get<0>(image_size[n]))) {\n\t\t\t\tuv_ind = ((int) uv(1))*get<1>(image_size[n])+((int) uv(0));\n\t\t\t\tuv_out.push_back(uv_ind);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn uv_out;\n}\n\nvector<arma::Col<int>> FocalGrid::ProjectCloud2Frames(arma::Mat<double> &cloud_in) {\n\n\tvector<arma::Col<int>> frame_now;\n\n\tint N_vox = cloud_in.n_cols;\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 = {cloud_in(0,i),cloud_in(1,i),cloud_in(2,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<1>(image_size[j])*v+u)==0) {\n\t\t\t\t\t\tframe_now[j](get<1>(image_size[j])*v+u) = (int) cloud_in(3,i);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (frame_now[j](get<1>(image_size[j])*v+u) > cloud_in(3,i)) {\n\t\t\t\t\t\t\tframe_now[j](get<1>(image_size[j])*v+u) = (int) cloud_in(3,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\treturn frame_now;\n}\n\narma::Mat<double> FocalGrid::ProjectCloud2UVdouble(arma::Mat<double> &cloud_in, int cam_nr) {\n\n\tint N_vox = cloud_in.n_cols;\n\n\tarma::Mat<double> uv_doubles(3,N_vox);\n\n\tarma::Mat<double> xyz_coords = cloud_in;\n\txyz_coords.row(3).fill(1.0);\n\tarma::Mat<double> M_mat =  X_uv[cam_nr];\n\tM_mat.col(3) += -uv_offset[cam_nr];\n\tuv_doubles = M_mat*xyz_coords;\n\n\treturn uv_doubles;\n}\n\nvector<tuple<double,double,double,int>> FocalGrid::ProjectFrames2Cloud(vector<arma::Col<int>> &frame_in) {\n\n\tvector<tuple<double,double,double,int>> pcl_now;\n\n\tunordered_map<int,int> pcl_voxels;\n\n\tint N_row = get<0>(image_size[0]);\n\tint N_col = get<1>(image_size[1]);\n\n\tpair<multimap<int,int>::iterator, multimap<int,int>::iterator> voxels_i;\n\n\tint vox_now;\n\tvector<int> uv_now;\n\n\tint n = 0;\n\tbool is_voxel = true;\n\n\tint frame_val_0 = 0;\n\tint frame_val_n = 0;\n\n\tint code_now = 0;\n\n\tint count = 0;\n\n\t// Insert voxels into an unordered map and give them a segment code:\n\tfor (int i=0; i<(N_row*N_col); i++) {\n\t\tframe_val_0 = frame_in[0](i);\n\t\tif (frame_val_0>0) {\n\t\t\tvoxels_i = pix2vox.equal_range(i);\n\t\t\tfor (multimap<int,int>::iterator it=voxels_i.first; it != voxels_i.second; ++it) {\n\t\t\t\tvox_now = it->second;\n\t\t\t\tuv_now = vox2pix[vox_now];\n\t\t\t\tn = 1;\n\t\t\t\tis_voxel = true;\n\t\t\t\tcode_now = frame_val_0;\n\t\t\t\tint body_view_count = 0;\n\t\t\t\tif (frame_val_0 == 1) {\n\t\t\t\t\tbody_view_count = 1;\n\t\t\t\t}\n\t\t\t\twhile (is_voxel==true && n < N_cam) {\n\t\t\t\t\tframe_val_n = frame_in[n](uv_now[n]);\n\t\t\t\t\tif (frame_val_n>0) {\n\t\t\t\t\t\tcode_now = code_now+pow(max_n_seg,n)*frame_val_n;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tis_voxel = false;\n\t\t\t\t\t}\n\t\t\t\t\t// Reject voxels which have N_cam-1 views formed by the body:\n\t\t\t\t\tif (frame_val_n==1) {\n\t\t\t\t\t\tbody_view_count++;\n\t\t\t\t\t}\n\t\t\t\t\tn++;\n\t\t\t\t}\n\t\t\t\tif (body_view_count == (N_cam-1)) {\n\t\t\t\t\tis_voxel = false;\n\t\t\t\t}\n\t\t\t\tif (is_voxel==true) {\n\t\t\t\t\tcount++;\n\t\t\t\t\tpcl_voxels.insert(pair<int,int>(vox_now,code_now));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// For each voxel in the pcl_voxels map:\n\t// -> find the neighboring voxels\n\t// -> add the voxel to pcl_now if it has more than 1 neighbor and less tan 6 neighbors\n\n\tunordered_map<int,int>::iterator nb_it;\n\n\tarma::Col<int> neighbors(27);\n\n\tint nb_sum;\n\n\tarma::Col<double> xyz_pos(3);\n\n\tfor (nb_it = pcl_voxels.begin(); nb_it != pcl_voxels.end(); nb_it++) {\n\t\tvox_now = nb_it->first;\n\t\tcode_now = nb_it->second;\n\t\tneighbors = FocalGrid::FindNeighbors(vox_now);\n\t\tif (neighbors(13)>0) {\n\t\t\tnb_sum = 0;\n\t\t\tfor (int m=0; m<27; m++) {\n\t\t\t\tif (pcl_voxels.find(neighbors(m)) != pcl_voxels.end()) {\n\t\t\t\t\t// Do nothing\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tnb_sum++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (nb_sum > 2 && nb_sum < 27) {\n\t\t\t\txyz_pos = FocalGrid::CalculatePosition(vox_now);\n\t\t\t\tpcl_now.push_back(make_tuple(xyz_pos(0),xyz_pos(1),xyz_pos(2),code_now));\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\narma::Mat<int> FocalGrid::FindConnectedPointClouds(arma::Mat<double> &pcl_in) {\n\n\tint N_pts = pcl_in.n_cols;\n\n\tarma::Row<double> seg_ids = arma::unique(pcl_in.row(3));\n\tint N_seg = seg_ids.n_cols;\n\n\tarma::Mat<int> connectivity_mat;\n\n\t// Set the diagonals of the connectivity mat to the unique codes:\n\tif (N_seg>1) {\n\n\t\tconnectivity_mat.zeros(N_seg,N_seg);\n\n\t\tfor (int j=0; j<N_seg; j++) {\n\t\t\tconnectivity_mat(j,j) = seg_ids(j);\n\t\t}\n\n\t\tdouble central_x;\n\t\tdouble central_y;\n\t\tdouble central_z;\n\t\tdouble central_code;\n\n\t\tarma::uvec dx_ids;\n\t\tarma::Mat<double> dx_points;\n\n\t\tarma::uvec dxy_ids;\n\t\tarma::Mat<double> dxy_points;\n\n\t\tarma::uvec dxyz_ids;\n\t\tarma::Mat<double> dxyz_points;\n\n\t\tarma::Row<double> neighbor_codes;\n\t\tint N_codes;\n\n\t\tarma::uvec central_code_ind;\n\t\tarma::uvec neighbor_code_ind;\n\n\t\tfor (int i=0; i<N_pts; i++) {\n\t\t\t// Iterate through the voxels, find any points which are at (+dx,-dx) subsequently (+dy,-dy) and finally (+dz,-dz).\n\t\t\t// Points which show up in all 3 conditions are neighboring points.\n\t\t\t// Than check the codes of the neighboring points and add scores to the connectivity mat if their codes differ from the central point.\n\t\t\tcentral_x = pcl_in(0,i);\n\t\t\tcentral_y = pcl_in(1,i);\n\t\t\tcentral_z = pcl_in(2,i);\n\t\t\tcentral_code = pcl_in(3,i);\n\n\t\t\tdx_ids = arma::find((pcl_in.row(0)>(central_x-(1.1*ds))) && (pcl_in.row(0)<(central_x+(1.1*ds))));\n\t\t\tif (dx_ids.n_rows>1) {\n\t\t\t\tdx_points = pcl_in.cols(dx_ids);\n\t\t\t\tdxy_ids = arma::find((dx_points.row(1)>(central_y-(1.1*ds))) && (dx_points.row(1)<(central_y+(1.1*ds))));\n\t\t\t\tif (dxy_ids.n_rows>1) {\n\t\t\t\t\tdxy_points = dx_points.cols(dxy_ids);\n\t\t\t\t\tdxyz_ids = arma::find((dxy_points.row(2)>(central_z-(1.1*ds))) && (dxy_points.row(2)<(central_z+(1.1*ds))));\n\t\t\t\t\tif (dxyz_ids.n_rows>1) {\n\t\t\t\t\t\tdxyz_points = dxy_points.cols(dxyz_ids);\n\t\t\t\t\t\tneighbor_codes = arma::unique(dxyz_points.row(3));\n\t\t\t\t\t\tN_codes = neighbor_codes.n_cols;\n\t\t\t\t\t\tcentral_code_ind = arma::find(seg_ids == central_code);\n\t\t\t\t\t\tfor (int k=0; k<N_codes; k++) {\n\t\t\t\t\t\t\tneighbor_code_ind = arma::find(seg_ids == neighbor_codes(k));\n\t\t\t\t\t\t\tif (central_code_ind(0) != neighbor_code_ind(0)) {\n\t\t\t\t\t\t\t\tconnectivity_mat(central_code_ind,neighbor_code_ind) += 1;\n\t\t\t\t\t\t\t\tconnectivity_mat(neighbor_code_ind,central_code_ind) += 1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse {\n\t\tconnectivity_mat.zeros(1,1);\n\t}\n\treturn connectivity_mat;\n}\n\narma::Mat<double> FocalGrid::ConvertVector2Mat(vector<tuple<double,double,double,int>> pcl_in) {\n\tint N_pts = pcl_in.size();\n\tarma::Mat<double> pcl_out(4,N_pts);\n\tfor (int j=0; j<N_pts; j++) {\n\t\tpcl_out(0,j) = get<0>(pcl_in[j]);\n\t\tpcl_out(1,j) = get<1>(pcl_in[j]);\n\t\tpcl_out(2,j) = get<2>(pcl_in[j]);\n\t\tpcl_out(3,j) = get<3>(pcl_in[j]);\n\t}\n\treturn pcl_out;\n}\n\narma::Col<int> FocalGrid::FindNeighbors(int vox_ind) {\n\n\t// find the neighboring voxels:\n\n\tarma::Col<int> vox_int_mat(27);\n\n\tint i = vox_ind % nx;\n\tint j = ((vox_ind-i)/nx) % ny;\n\tint k = (vox_ind-i-j*nx)/(nx*ny);\n\n\tif ((i>0 && i<(nx-1)) && (j>0 && j<(ny-1)) && (k>0 && k<(nz-1))) {\n\n\t\tvox_int_mat(0) = vox_ind-nx*ny-nx-1;\n\t\tvox_int_mat(1) = vox_ind-nx*ny-nx;\n\t\tvox_int_mat(2) = vox_ind-nx*ny-nx+1;\n\t\tvox_int_mat(3) = vox_ind-nx*ny-1;\n\t\tvox_int_mat(4) = vox_ind-nx*ny;\n\t\tvox_int_mat(5) = vox_ind-nx*ny+1;\n\t\tvox_int_mat(6) = vox_ind-nx*ny+nx-1;\n\t\tvox_int_mat(7) = vox_ind-nx*ny+nx;\n\t\tvox_int_mat(8) = vox_ind-nx*ny+nx+1;\n\t\tvox_int_mat(9) = vox_ind-nx-1;\n\t\tvox_int_mat(10) = vox_ind-nx;\n\t\tvox_int_mat(11) = vox_ind-nx+1;\n\t\tvox_int_mat(12) = vox_ind-1;\n\t\tvox_int_mat(13) = vox_ind;\n\t\tvox_int_mat(14) = vox_ind+1;\n\t\tvox_int_mat(15) = vox_ind+nx-1;\n\t\tvox_int_mat(16) = vox_ind+nx;\n\t\tvox_int_mat(17) = vox_ind+nx+1;\n\t\tvox_int_mat(18) = vox_ind+nx*ny-nx-1;\n\t\tvox_int_mat(19) = vox_ind+nx*ny-nx;\n\t\tvox_int_mat(20) = vox_ind+nx*ny-nx+1;\n\t\tvox_int_mat(21) = vox_ind+nx*ny-1;\n\t\tvox_int_mat(22) = vox_ind+nx*ny;\n\t\tvox_int_mat(23) = vox_ind+nx*ny+1;\n\t\tvox_int_mat(24) = vox_ind+nx*ny+nx-1;\n\t\tvox_int_mat(25) = vox_ind+nx*ny+nx;\n\t\tvox_int_mat(26) = vox_ind+nx*ny+nx+1;\n\n\t}\n\telse {\n\t\tvox_int_mat.zeros();\n\t}\n\n\treturn vox_int_mat;\n}\n\narma::Col<double> FocalGrid::CalculatePosition(int vox_ind) {\n\n\tint i = vox_ind % nx;\n\tint j = ((vox_ind-i)/nx) % ny;\n\tint k = (vox_ind-i-j*nx)/(nx*ny);\n\n\tarma::Col<double> xyz_pos(3);\n\n\txyz_pos(0) = x0-((nx-1)/2.0)*ds+i*ds;\n\txyz_pos(1) = y0-((ny-1)/2.0)*ds+j*ds;\n\txyz_pos(2) = z0-((nz-1)/2.0)*ds+k*ds;\n\n\treturn xyz_pos;\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::Col<double> FocalGrid::CalculateViewVector(int cam_nr) {\n\n\tarma::Col<double> u_vec = {1.0,0.0,0.0};\n\tarma::Col<double> v_vec = {0.0,1.0,0.0};\n\n\tarma::Col<double> u_vec_world = X_xyz[cam_nr]*u_vec;\n\tarma::Col<double> v_vec_world = X_xyz[cam_nr]*v_vec;\n\n\tarma::Col<double> view_vec = arma::cross(v_vec_world.rows(0,2),u_vec_world.rows(0,2))/(arma::norm(u_vec_world.rows(0,2))*arma::norm(v_vec_world.rows(0,2)));\n\n\treturn arma::normalise(view_vec);\n\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": "759a4185ee1f1dbed6edd789ac810252b8746ad7", "size": 14973, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "focal_grid.cpp", "max_stars_repo_name": "jmmelis/DipteraTrack", "max_stars_repo_head_hexsha": "1d267ccd4248635233147f2035b900a433dc4536", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-14T10:19:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-14T10:19:19.000Z", "max_issues_repo_path": "focal_grid.cpp", "max_issues_repo_name": "jmmelis/DipteraTrack", "max_issues_repo_head_hexsha": "1d267ccd4248635233147f2035b900a433dc4536", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "focal_grid.cpp", "max_forks_repo_name": "jmmelis/DipteraTrack", "max_forks_repo_head_hexsha": "1d267ccd4248635233147f2035b900a433dc4536", "max_forks_repo_licenses": ["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.2224168126, "max_line_length": 169, "alphanum_fraction": 0.6298003072, "num_tokens": 5410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.26520691975608224}}
{"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    ForwardDynamicsSolver.cpp\n *\n * \\author  Stefan Scherzinger <scherzin@fzi.de>\n * \\date    2016/02/14\n *\n */\n//-----------------------------------------------------------------------------\n\n// this package\n#include <cartesian_controller_base/ForwardDynamicsSolver.h>\n\n// other\n#include <map>\n#include <sstream>\n#include <boost/algorithm/clamp.hpp>\n#include <eigen_conversions/eigen_kdl.h>\n\n// KDL\n#include <kdl/jntarrayvel.hpp>\n#include <kdl/framevel.hpp>\n\n// DEBUG\n\n\nnamespace cartesian_controller_base{\n\n  ForwardDynamicsSolver::ForwardDynamicsSolver()\n  {\n  }\n\n  ForwardDynamicsSolver::~ForwardDynamicsSolver(){}\n\n  trajectory_msgs::JointTrajectoryPoint ForwardDynamicsSolver::getJointControlCmds(\n        ros::Duration period,\n        const ctrl::Vector6D& net_force)\n  {\n\n    // Compute joint space inertia matrix\n    m_jnt_space_inertia_solver->JntToMass(m_current_positions,m_jnt_space_inertia);\n\n    // Compute joint jacobian\n    m_jnt_jacobian_solver->JntToJac(m_current_positions,m_jnt_jacobian);\n\n    // Compute joint accelerations according to: \\f$ \\ddot{q} = H^{-1} ( J^T f) \\f$\n    m_current_accelerations.data = m_jnt_space_inertia.data.inverse() * m_jnt_jacobian.data.transpose() * net_force;\n\n    // Integrate once, starting with zero motion\n    m_current_velocities.data = 0.5 * m_current_accelerations.data * period.toSec();\n\n    // Integrate twice, 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    for (int i = 0; i < m_number_joints; ++i)\n    {\n      m_current_positions(i) = boost::algorithm::clamp(\n          m_current_positions(i),m_lower_pos_limits(i),m_upper_pos_limits(i));\n    }\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\n  const KDL::Frame& ForwardDynamicsSolver::getEndEffectorPose() const\n  {\n    return m_end_effector_pose;\n  }\n\n  const ctrl::Vector6D& ForwardDynamicsSolver::getEndEffectorVel() const\n  {\n    return m_end_effector_vel;\n  }\n\n  const KDL::JntArray& ForwardDynamicsSolver::getPositions() const\n  {\n    return m_current_positions;\n  }\n\n\n  bool ForwardDynamicsSolver::setStartState(\n      const std::vector<hardware_interface::JointHandle>& joint_handles)\n  {\n    // Copy into internal buffers.\n    for (int i = 0; i < joint_handles.size(); ++i)\n    {\n      m_current_positions(i)      = joint_handles[i].getPosition();\n      m_current_velocities(i)     = joint_handles[i].getVelocity();\n      m_current_accelerations(i)  = 0.0;\n      m_last_positions(i)         = m_current_positions(i);\n    }\n    return true;\n  }\n\n\n  bool ForwardDynamicsSolver::init(\n      const KDL::Chain& chain,\n      const KDL::JntArray& upper_pos_limits,\n      const KDL::JntArray& lower_pos_limits)\n  {\n    if (!buildGenericModel(chain))\n    {\n      ROS_ERROR(\"ForwardDynamicsSolver: Something went wrong in setting up the internal model.\");\n      return false;\n    }\n\n    // Initialize\n    m_number_joints              = m_chain.getNrOfJoints();\n    m_current_positions.data     = ctrl::VectorND::Zero(m_number_joints);\n    m_current_velocities.data    = ctrl::VectorND::Zero(m_number_joints);\n    m_current_accelerations.data = ctrl::VectorND::Zero(m_number_joints);\n    m_last_positions.data        = ctrl::VectorND::Zero(m_number_joints);\n    m_upper_pos_limits           = upper_pos_limits;\n    m_lower_pos_limits           = lower_pos_limits;\n\n    // Forward kinematics\n    m_fk_pos_solver.reset(new KDL::ChainFkSolverPos_recursive(m_chain));\n    m_fk_vel_solver.reset(new KDL::ChainFkSolverVel_recursive(m_chain));\n\n    // Forward dynamics\n    m_jnt_jacobian_solver.reset(new KDL::ChainJntToJacSolver(m_chain));\n    m_jnt_space_inertia_solver.reset(new KDL::ChainDynParam(m_chain,KDL::Vector::Zero()));\n    m_jnt_jacobian.resize(m_number_joints);\n    m_jnt_space_inertia.resize(m_number_joints);\n\n    ROS_INFO(\"Forward dynamics solver initialized\");\n    ROS_INFO(\"Forward dynamics solver has control over %i joints\", m_number_joints);\n\n    return true;\n  }\n\n  bool ForwardDynamicsSolver::buildGenericModel(const KDL::Chain& input_chain)\n  {\n    m_chain = input_chain;\n\n    // Set all masses and inertias to minimal (yet stable) values.\n    double m_min = 0.001;\n    double ip_min = 0.000001;\n    for (size_t i = 0; i < m_chain.segments.size(); ++i)\n    {\n      // Fixed joint segment\n      if (m_chain.segments[i].getJoint().getType() == KDL::Joint::None)\n      {\n        m_chain.segments[i].setInertia(\n            KDL::RigidBodyInertia::Zero());\n      }\n      else  // relatively moving segment\n      {\n        m_chain.segments[i].setInertia(\n            KDL::RigidBodyInertia(\n              m_min,                // mass\n              KDL::Vector::Zero(),  // center of gravity\n              KDL::RotationalInertia(\n                ip_min,             // ixx\n                ip_min,             // iyy\n                ip_min              // izz\n                // ixy, ixy, iyz default to 0.0\n                )));\n      }\n    }\n\n    // Only give the last segment a generic mass and inertia.\n    // See https://arxiv.org/pdf/1908.06252.pdf for a motivation for this setting.\n    double m = 1;\n    double ip = 1;\n    m_chain.segments[m_chain.segments.size()-1].setInertia(\n        KDL::RigidBodyInertia(\n          m,\n          KDL::Vector::Zero(),\n          KDL::RotationalInertia(ip, ip, ip)));\n\n    return true;\n  }\n\n} // namespace\n", "meta": {"hexsha": "79aa2e22e59d2ec6903b1ac5a00d27a1e2beaef5", "size": 7747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cartesian_controller_base/src/ForwardDynamicsSolver.cpp", "max_stars_repo_name": "cesar-vargas88/cartesian_controllers", "max_stars_repo_head_hexsha": "4a7b5fd7d300c9c533602b904a6d00aa405853ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-12-22T12:12:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T07:17:51.000Z", "max_issues_repo_path": "cartesian_controller_base/src/ForwardDynamicsSolver.cpp", "max_issues_repo_name": "cesar-vargas88/cartesian_controllers", "max_issues_repo_head_hexsha": "4a7b5fd7d300c9c533602b904a6d00aa405853ae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cartesian_controller_base/src/ForwardDynamicsSolver.cpp", "max_forks_repo_name": "cesar-vargas88/cartesian_controllers", "max_forks_repo_head_hexsha": "4a7b5fd7d300c9c533602b904a6d00aa405853ae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-04T09:16:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T09:16:28.000Z", "avg_line_length": 35.3744292237, "max_line_length": 116, "alphanum_fraction": 0.6637408029, "num_tokens": 1806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.63341024983754, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.26520691396119134}}
{"text": "/* Copyright 2022 Zuru Tech HK Limited.\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 <chrono>\n#include <stdexcept>\n\n#include <Eigen/Dense>\n\n#include <superlu_dist/superlu_ddefs.h>\n\n#include <solvers/SparseSystem.hpp>\n#include <solvers/SuperLUSolver.hpp>\n\nnamespace solvers {\n\nSuperLUSolver::SuperLUSolver(const SuperLUReorder reorder)\n{\n    /* Set the default input options:\n        options.Fact = DOFACT;\n        options.Equil = YES;\n        options.ColPerm = METIS_AT_PLUS_A;\n        options.RowPerm = LargeDiag_MC64;\n        options.ReplaceTinyPivot = YES;\n        options.Trans = NOTRANS;\n        options.IterRefine = DOUBLE;\n        options.SolveInitialized = NO;\n        options.RefineInitialized = NO;\n        options.PrintStat = YES;\n     */\n    set_default_options_dist(&_options);\n    _options.PrintStat = yes_no_t::NO;\n    _options.ColPerm = static_cast<colperm_t>(reorder);\n    _options.IterRefine = IterRefine_t::NOREFINE;\n    _options.SymPattern = yes_no_t::YES;\n}\n\nEigen::VectorXd SuperLUSolver::solve(const SparseSystem& system,\n                                     double& duration) const\n{\n    auto [ccol_index, row_index, values, b] = system.toStdCSR();\n    // Transfer ownership from vectors to pointers\n    auto* ccol_index_ptr = new int[ccol_index.size()];\n    auto* row_index_ptr = new int[row_index.size()];\n    auto* values_ptr = new double[values.size()];\n    std::copy(ccol_index.begin(), ccol_index.end(), ccol_index_ptr);\n    std::copy(row_index.begin(), row_index.end(), row_index_ptr);\n    std::copy(values.begin(), values.end(), values_ptr);\n\n    const auto n = static_cast<int>(system.dim());\n    const auto nnz = static_cast<int>(system.nnz());\n\n    // Choose a GPU device\n    int rank;\n    int devs;\n    MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n    cudaGetDeviceCount(&devs);\n    cudaSetDevice(rank % devs);\n\n    gridinfo_t grid;\n    constexpr int nprow = 1;\n    constexpr int npcol = 1;\n    superlu_gridinit(MPI_COMM_WORLD, nprow, npcol, &grid);\n\n    // Create A in CSC format\n    SuperMatrix A;\n    dCreate_CompCol_Matrix_dist(&A, n, n, nnz, values_ptr, row_index_ptr,\n                                ccol_index_ptr, Stype_t::SLU_NC, Dtype_t::SLU_D,\n                                Mtype_t::SLU_GE);\n\n    // Initialize variables\n    dScalePermstruct_t scale_perm;\n    dScalePermstructInit(n, n, &scale_perm);\n    dLUstruct_t lu;\n    dLUstructInit(n, &lu);\n    SuperLUStat_t stat;\n    PStatInit(&stat);\n\n    // Call the linear equation solver\n    double error;\n    int info;\n    superlu_dist_options_t options(_options);\n    Eigen::VectorXd result = Eigen::Map<Eigen::VectorXd>(b.data(), n);\n    pdgssvx_ABglobal(&options, &A, &scale_perm, result.data(), n, 1, &grid, &lu,\n                     &error, &stat, &info);\n\n    // Measure execution time in seconds\n    duration = 0.;\n    for (size_t phase = 0; phase < PhaseType::NPHASES; ++phase) {\n        duration += stat.utime[phase];\n    }\n\n    // Destroy MPI objects\n    PStatFree(&stat);\n    Destroy_CompCol_Matrix_dist(&A);\n    dDestroy_LU(n, &grid, &lu);\n    dScalePermstructFree(&scale_perm);\n    dLUstructFree(&lu);\n    superlu_gridexit(&grid);\n    cudaDeviceReset();\n    return result;\n}\n\n}    // namespace solvers", "meta": {"hexsha": "00f6ea7129f24ccb1ddc50b70665d5a44e8e659f", "size": 3726, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "solvers/src/solvers/SuperLUSolver.cpp", "max_stars_repo_name": "zurutech/stand", "max_stars_repo_head_hexsha": "a341f691d991072a61d07aac6fa7e634e2d112d3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2022-01-17T07:30:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T17:27:52.000Z", "max_issues_repo_path": "solvers/src/solvers/SuperLUSolver.cpp", "max_issues_repo_name": "zurutech/stand", "max_issues_repo_head_hexsha": "a341f691d991072a61d07aac6fa7e634e2d112d3", "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": "solvers/src/solvers/SuperLUSolver.cpp", "max_forks_repo_name": "zurutech/stand", "max_forks_repo_head_hexsha": "a341f691d991072a61d07aac6fa7e634e2d112d3", "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.4, "max_line_length": 80, "alphanum_fraction": 0.6672034353, "num_tokens": 951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2651273363791198}}
{"text": "#include <Configuration.h> // Package Path\n#include <avatar_locomanipulation/enable_pinocchio_with_hpp_fcl.h> // Enable HPP FCL\n// Multibody\n#include \"pinocchio/multibody/model.hpp\"\n#include \"pinocchio/multibody/data.hpp\"\n#include \"pinocchio/multibody/geometry.hpp\"\n// Algorithms\n#include \"pinocchio/algorithm/kinematics.hpp\"\n#include \"pinocchio/algorithm/geometry.hpp\"\n#include \"pinocchio/algorithm/model.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/frames.hpp\" // Jacobian Frame Computation \n// Parsers\n#include \"pinocchio/parsers/urdf.hpp\"\n#include \"pinocchio/parsers/srdf.hpp\"\n// Spatial\n#include \"pinocchio/spatial/fcl-pinocchio-conversions.hpp\"\n\n// Standard\n#include <math.h>\n#include <map>\n#include <iostream>\n#include <boost/shared_ptr.hpp>\n\n\nint main(int argc, char ** argv){\n\t// models and geomModels\n\tpinocchio::Model robot_model, cart_model, appended_model;\n  pinocchio::GeometryModel robot_geomModel, cart_geomModel, appended_geomModel;\n  // data and geomdata\n  std::unique_ptr<pinocchio::Data> robot_data, cart_data, appended_data;\n  std::unique_ptr<pinocchio::GeometryData> robot_geomData, cart_geomData, appended_geomData;\n\n  // Define the Robot--------\n\tstd::string filename = THIS_PACKAGE_PATH\"models/valkyrie_simplified_collisions.urdf\";\n  std::string srdf_filename = THIS_PACKAGE_PATH\"models/valkyrie_disable_collisions.srdf\";\n  std::string meshDir  = THIS_PACKAGE_PATH\"../val_model/\";\n  // build model and geomModel\n  pinocchio::urdf::buildModel(filename, pinocchio::JointModelFreeFlyer(),robot_model);\n  pinocchio::urdf::buildGeom(robot_model, filename, pinocchio::COLLISION, robot_geomModel, meshDir );\n  // Add and remove collision pairs\n  robot_geomModel.addAllCollisionPairs();\n  pinocchio::srdf::removeCollisionPairs(robot_model, robot_geomModel, srdf_filename, false);\n  // Define the data and geomData\n  robot_data = std::unique_ptr<pinocchio::Data>(new pinocchio::Data(robot_model));\n\trobot_geomData = std::unique_ptr<pinocchio::GeometryData>(new pinocchio::GeometryData(robot_geomModel));\n\t// Define the configuration of Robot\n  Eigen::VectorXd q_robot;\n  q_robot = Eigen::VectorXd::Zero(robot_model.nq);\n\n  double theta = 0;//M_PI/4.0;\n  Eigen::AngleAxis<double> aa(theta, Eigen::Vector3d(0.0, 0.0, 1.0));\n  Eigen::Quaternion<double> init_quat(1.0, 0.0, 0.0, 0.0); //Initialized to remember the w component comes first\n  init_quat = aa;\n\n  q_robot[3] = init_quat.x(); q_robot[4] = init_quat.y(); q_robot[5] = init_quat.z(); q_robot[6] = init_quat.w(); // Set up the quaternion in q\n\n  q_robot[2] = 1.0; // set z value to 1.0, this is the pelvis location\n\n  q_robot[7 + robot_model.getJointId(\"leftHipPitch\") - 2] = -0.3;\n  q_robot[7 + robot_model.getJointId(\"rightHipPitch\") - 2] = -0.3;\n  q_robot[7 + robot_model.getJointId(\"leftKneePitch\") - 2] = 0.6;\n  q_robot[7 + robot_model.getJointId(\"rightKneePitch\") - 2] = 0.6;\n  q_robot[7 + robot_model.getJointId(\"leftAnklePitch\") - 2] = -0.3;\n  q_robot[7 + robot_model.getJointId(\"rightAnklePitch\") - 2] = -0.3;\n\n  q_robot[7 + robot_model.getJointId(\"rightShoulderPitch\") - 2] = -0.2;\n  q_robot[7 + robot_model.getJointId(\"rightShoulderRoll\") - 2] = 1.1;\n  q_robot[7 + robot_model.getJointId(\"rightElbowPitch\") - 2] = 0.4;\n  q_robot[7 + robot_model.getJointId(\"rightForearmYaw\") - 2] = 1.5;\n\n  q_robot[7 + robot_model.getJointId(\"leftShoulderPitch\") - 2] = -0.2;\n  q_robot[7 + robot_model.getJointId(\"leftShoulderRoll\") - 2] = -1.1;\n  q_robot[7 + robot_model.getJointId(\"leftElbowPitch\") - 2] = -0.4;\n  q_robot[7 + robot_model.getJointId(\"leftForearmYaw\") - 2] = 1.5;\n\n\t// Define the Cart--------\n\tfilename = THIS_PACKAGE_PATH\"models/test_cart.urdf\";\n  meshDir  = THIS_PACKAGE_PATH\"models/cart/\";\n  // build model and geomModel\n  pinocchio::urdf::buildModel(filename, pinocchio::JointModelFreeFlyer(),cart_model);\n  pinocchio::urdf::buildGeom(cart_model, filename, pinocchio::COLLISION, cart_geomModel, meshDir );\n\n  //------ Suggested Fix\n  // Apply a prefix\n  std::string prefix (\"cart/\");\n  for (pinocchio::JointIndex i = 1; i < cart_model.joints.size(); ++i) {\n    cart_model.names[i] = prefix + cart_model.names[i];\n  }\n  for (pinocchio::FrameIndex i = 0; i < cart_model.frames.size(); ++i) {\n    ::pinocchio::Frame& f = cart_model.frames[i];\n    f.name = prefix + f.name;\n  }\n  //----------------------\n  // Add and remove collision pairs\n  cart_geomModel.addAllCollisionPairs();\n  // Define the data and geomData\n  cart_data = std::unique_ptr<pinocchio::Data>(new pinocchio::Data(cart_model));\n\tcart_geomData = std::unique_ptr<pinocchio::GeometryData>(new pinocchio::GeometryData(cart_geomModel));\n\t// Define the configuration of the cart\n  Eigen::VectorXd q_cart;\n  q_cart = Eigen::VectorXd::Zero(cart_model.nq);\n  q_cart[0] = -0.05;  q_cart[1] = 0.0;  q_cart[2] = 0.0;\n  // q_cart[0] = -0.06;  q_cart[1] = -0.0085;  q_cart[2] = -0.04;\n  double theta1 = 0;//M_PI/4.0;\t\n  Eigen::AngleAxis<double> bb(theta1, Eigen::Vector3d(0.0, 0.0, 1.0)); // yaw pi/4 to the left\t\n  Eigen::Quaternion<double> quat_init; quat_init =  bb;\n  q_cart[3] = quat_init.x();// 0.0;\t\n  q_cart[4] = quat_init.y(); //0.0;\n  q_cart[5] = quat_init.z(); //sin(theta/2.0);\n  q_cart[6] = quat_init.w(); //cos(theta/2.0);\n\n\n  // Perform initial forward kinematics\n  pinocchio::forwardKinematics(robot_model, *robot_data, q_robot);\n  // Compute Joint Jacobians\n  pinocchio::computeJointJacobians(robot_model,*robot_data, q_robot);\n  // Update Frame Placements\n  pinocchio::updateFramePlacements(robot_model, *robot_data); \n  // Perform initial forward kinematics\n  pinocchio::forwardKinematics(cart_model, *cart_data, q_cart);\n  // Compute Joint Jacobians\n  pinocchio::computeJointJacobians(cart_model,*cart_data, q_cart);\n  // Update Frame Placements\n  pinocchio::updateFramePlacements(cart_model, *cart_data); \n\n\n  // Append the object onto the robot, and fill appended RobotModel\n  pinocchio::appendModel(robot_model, cart_model, robot_geomModel, cart_geomModel, 0, pinocchio::SE3::Identity(), appended_model, appended_geomModel);\n\n  appended_data = std::unique_ptr<pinocchio::Data>(new pinocchio::Data(appended_model));\n  appended_geomData = std::unique_ptr<pinocchio::GeometryData>(new pinocchio::GeometryData(appended_geomModel));\n\n  Eigen::VectorXd q_appended;\n  q_appended = Eigen::VectorXd::Zero(appended_model.nq);\n\n  for(int i=0; i<cart_model.nq; ++i){\n  \tq_appended[i] = q_cart[i];\n  }\n  int i = cart_model.nq;\n  for(int j=0; j<robot_model.nq; ++j){\n  \tq_appended[i] = q_robot[j];\n  \t++i;\n  }\n\n  // Perform initial forward kinematics\n  pinocchio::forwardKinematics(appended_model, *appended_data, q_appended);\n  // Compute Joint Jacobians\n  pinocchio::computeJointJacobians(appended_model,*appended_data, q_appended);\n  // Update Frame Placements\n  pinocchio::updateFramePlacements(appended_model, *appended_data); \n  // Update geometry Placements\n  pinocchio::updateGeometryPlacements(appended_model, *appended_data, appended_geomModel, *appended_geomData, q_appended);\n\n  std::cout << \"appended_model: \\n\" << appended_model << std::endl;\n  std::cout << \"appended_geomModel: \\n\" << appended_geomModel << std::endl;\n  // List Operational Space Frames\n  for (int k=0 ; k<appended_model.frames.size() ; ++k){\n    std::cout << \"frame:\" << k << \" \" << appended_model.frames[k].name << \" : \" << appended_data->oMf[k].translation().transpose() << std::endl;\n  }\n}", "meta": {"hexsha": "f1415f7a245fc3464634a3476cbb839cab606f8f", "size": 7354, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/collision_test_files/test_minimal_working_example.cpp", "max_stars_repo_name": "stevenjj/icra2020locomanipulation", "max_stars_repo_head_hexsha": "414085b68cc1b3b24f7b920b543bba9d95350c16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-01-06T11:43:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T22:59:09.000Z", "max_issues_repo_path": "test/collision_test_files/test_minimal_working_example.cpp", "max_issues_repo_name": "stevenjj/icra2020locomanipulation", "max_issues_repo_head_hexsha": "414085b68cc1b3b24f7b920b543bba9d95350c16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/collision_test_files/test_minimal_working_example.cpp", "max_forks_repo_name": "stevenjj/icra2020locomanipulation", "max_forks_repo_head_hexsha": "414085b68cc1b3b24f7b920b543bba9d95350c16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-03T16:08:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T11:13:49.000Z", "avg_line_length": 45.6770186335, "max_line_length": 150, "alphanum_fraction": 0.7231438673, "num_tokens": 2249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.2650851120047774}}
{"text": "/*******************************************************************************\n *\n * Data structures for the symbolic manipulation of linear constraints.\n *\n * Author: Arnaud J. Venet (arnaud.j.venet@nasa.gov)\n * Contributor: Jorge A. Navas (jorge.navas@sri.com)\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 <memory>\n#include <optional>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#include <boost/container/flat_map.hpp>\n#include <boost/functional/hash.hpp>\n\n#include \"crab/patricia_trees.hpp\"\n#include \"crab/types.hpp\"\n\nnamespace crab {\n\nclass linear_expression_t final {\n\n  public:\n    using component_t = std::pair<number_t, variable_t>;\n    using variable_set_t = patricia_tree_set<variable_t>;\n\n  private:\n    using map_t = boost::container::flat_map<variable_t, number_t>;\n    using map_ptr = std::shared_ptr<map_t>;\n    using pair_t = typename map_t::value_type;\n\n    map_ptr _map;\n    number_t _cst;\n\n    linear_expression_t(map_ptr map, number_t cst) : _map(std::move(map)), _cst(std::move(cst)) {}\n\n    linear_expression_t(const map_t& map, number_t cst) : _map(std::make_shared<map_t>()), _cst(std::move(cst)) {\n        *this->_map = map;\n    }\n\n    void add(variable_t x, const number_t& n) {\n        typename map_t::iterator it = this->_map->find(x);\n        if (it != this->_map->end()) {\n            number_t r = it->second + n;\n            if (r == 0) {\n                this->_map->erase(it);\n            } else {\n                it->second = r;\n            }\n        } else {\n            if (n != 0) {\n                this->_map->insert(pair_t(x, n));\n            }\n        }\n    }\n\n  public:\n    using iterator = typename map_t::iterator;\n    using const_iterator = typename map_t::const_iterator;\n\n    linear_expression_t() : _map(std::make_shared<map_t>()), _cst(0) {}\n\n    linear_expression_t(linear_expression_t&& other) = default;\n    linear_expression_t(const linear_expression_t& other) = default;\n\n    explicit linear_expression_t(number_t n) : _map(std::make_shared<map_t>()), _cst(std::move(n)) {}\n\n    linear_expression_t(signed long long int n) : _map(std::make_shared<map_t>()), _cst(number_t(n)) {}\n\n    linear_expression_t(variable_t x) : _map(std::make_shared<map_t>()), _cst(0) {\n        this->_map->insert(pair_t(x, number_t(1)));\n    }\n\n    linear_expression_t(const number_t& n, variable_t x) : _map(std::make_shared<map_t>()), _cst(0) {\n        this->_map->insert(pair_t(x, n));\n    }\n\n    linear_expression_t& operator=(const linear_expression_t& e) {\n        if (this != &e) {\n            this->_map = e._map;\n            this->_cst = e._cst;\n        }\n        return *this;\n    }\n\n    const_iterator begin() const { return this->_map->begin(); }\n\n    const_iterator end() const { return this->_map->end(); }\n\n    iterator begin() { return this->_map->begin(); }\n\n    iterator end() { return this->_map->end(); }\n\n    size_t hash() const {\n        size_t res = 0;\n        for (const auto& p : *this) {\n            boost::hash_combine(res, p);\n        }\n        boost::hash_combine(res, _cst);\n        return res;\n    }\n\n    // syntactic equality\n    bool equal(const linear_expression_t& o) const {\n        if (is_constant()) {\n            if (!o.is_constant()) {\n                return false;\n            } else {\n                return (constant() == o.constant());\n            }\n        } else {\n            if (constant() != o.constant()) {\n                return false;\n            }\n\n            if (size() != o.size()) {\n                return false;\n            } else {\n                for (const_iterator it = begin(), jt = o.begin(), et = end(); it != et; ++it, ++jt) {\n                    if (((*it).first != (*jt).first) || ((*it).second != (*jt).second)) {\n                        return false;\n                    }\n                }\n                return true;\n            }\n        }\n    }\n\n    bool is_constant() const { return (this->_map->empty()); }\n\n    number_t constant() const { return this->_cst; }\n\n    std::size_t size() const { return this->_map->size(); }\n\n    number_t operator[](variable_t x) const {\n        typename map_t::const_iterator it = this->_map->find(x);\n        if (it != this->_map->end()) {\n            return it->second;\n        } else {\n            return 0;\n        }\n    }\n\n    template <typename RenamingMap>\n    linear_expression_t rename(const RenamingMap& map) const {\n        number_t cst(this->_cst);\n        linear_expression_t new_exp(cst);\n        for (auto v : this->variables()) {\n            auto const it = map.find(v);\n            if (it != map.end()) {\n                variable_t v_out((*it).second);\n                new_exp = new_exp + linear_expression_t(this->operator[](v), v_out);\n            } else {\n                new_exp = new_exp + linear_expression_t(this->operator[](v), v);\n            }\n        }\n        return new_exp;\n    }\n\n    linear_expression_t operator+(number_t n) const {\n        linear_expression_t r(this->_map, this->_cst + std::move(n));\n        return r;\n    }\n\n    linear_expression_t operator+(int n) const { return this->operator+(number_t(n)); }\n\n    linear_expression_t operator+(variable_t x) const {\n        linear_expression_t r(*this->_map, this->_cst);\n        r.add(x, number_t(1));\n        return r;\n    }\n\n    linear_expression_t operator+(const linear_expression_t& e) const {\n        linear_expression_t r(*this->_map, this->_cst + e._cst);\n        for (typename map_t::const_iterator it = e._map->begin(); it != e._map->end(); ++it) {\n            r.add(it->first, it->second);\n        }\n        return r;\n    }\n\n    linear_expression_t operator-(const number_t& n) const { return this->operator+(-n); }\n\n    linear_expression_t operator-(int n) const { return this->operator+(-number_t(n)); }\n\n    linear_expression_t operator-(variable_t x) const {\n        linear_expression_t r(*this->_map, this->_cst);\n        r.add(x, number_t(-1));\n        return r;\n    }\n\n    linear_expression_t operator-() const { return this->operator*(number_t(-1)); }\n\n    linear_expression_t operator-(const linear_expression_t& e) const {\n        linear_expression_t r(*this->_map, this->_cst - e._cst);\n        for (typename map_t::const_iterator it = e._map->begin(); it != e._map->end(); ++it) {\n            r.add(it->first, -it->second);\n        }\n        return r;\n    }\n\n    linear_expression_t operator*(const number_t& n) const {\n        if (n == 0) {\n            return linear_expression_t();\n        } else {\n            map_ptr map = std::make_shared<map_t>();\n            for (typename map_t::const_iterator it = this->_map->begin(); it != this->_map->end(); ++it) {\n                number_t c = n * it->second;\n                if (c != 0) {\n                    map->insert(pair_t(it->first, c));\n                }\n            }\n            return linear_expression_t(map, n * this->_cst);\n        }\n    }\n\n    linear_expression_t operator*(int n) const { return operator*(number_t(n)); }\n\n    variable_set_t variables() const {\n        variable_set_t variables;\n        for (const auto& v_c : *this) {\n            variables += v_c.first;\n        }\n        return variables;\n    }\n\n    void write(std::ostream& o) const {\n        bool start = true;\n        for (auto [v, n] : *this) {\n            if (n > 0 && !start) {\n                o << \"+\";\n            }\n            if (n == -1) {\n                o << \"-\";\n            } else if (n != 1) {\n                o << n << \"*\";\n            }\n            o << v;\n            start = false;\n        }\n        if (this->_cst > 0 && !this->_map->empty()) {\n            o << \"+\";\n        }\n        if (this->_cst != 0 || this->_map->empty()) {\n            o << this->_cst;\n        }\n    }\n\n    // for dgb\n    void dump() { write(std::cout); }\n\n}; // class linear_expression_t\n\ninline std::ostream& operator<<(std::ostream& o, const linear_expression_t& e) {\n    e.write(o);\n    return o;\n}\n\ninline std::size_t hash_value(const linear_expression_t& e) { return e.hash(); }\n\nstruct linear_expression_hasher_t {\n    size_t operator()(const linear_expression_t& e) const { return e.hash(); }\n};\n\nstruct linear_expression_equal_t {\n    bool operator()(const linear_expression_t& e1, const linear_expression_t& e2) const { return e1.equal(e2); }\n};\n\nusing linear_expression_unordered_set =\n    std::unordered_set<linear_expression_t, linear_expression_hasher_t, linear_expression_equal_t>;\n\ntemplate <typename Value>\nusing linear_expression_unordered_map =\n    std::unordered_map<linear_expression_t, Value, linear_expression_hasher_t, linear_expression_equal_t>;\n\nclass linear_constraint_t final {\n\n  public:\n    using variable_set_t = patricia_tree_set<variable_t>;\n    using constraint_kind_t = enum { EQUALITY, DISEQUATION, INEQUALITY, STRICT_INEQUALITY };\n    using iterator = typename linear_expression_t::iterator;\n    using const_iterator = typename linear_expression_t::const_iterator;\n\n  private:\n    constraint_kind_t _kind;\n    linear_expression_t _expr;\n    // This flag has meaning only if _kind == INEQUALITY or STRICT_INEQUALITY.\n    // If true the inequality is signed otherwise unsigned.\n    // By default all constraints are signed.\n    bool _signedness;\n\n  public:\n    linear_constraint_t() : _kind(EQUALITY), _signedness(true) {}\n    linear_constraint_t(linear_constraint_t&& other) = default;\n    linear_constraint_t(const linear_constraint_t& other) = default;\n\n    linear_constraint_t(linear_expression_t expr, constraint_kind_t kind)\n        : _kind(kind), _expr(std::move(expr)), _signedness(true) {}\n\n    linear_constraint_t(linear_expression_t expr, constraint_kind_t kind, bool signedness)\n        : _kind(kind), _expr(std::move(expr)), _signedness(signedness) {\n        if (_kind != INEQUALITY && _kind != STRICT_INEQUALITY) {\n            CRAB_ERROR(\"Only inequalities can have signedness information\");\n        }\n    }\n\n    static linear_constraint_t get_true() {\n        linear_constraint_t res(linear_expression_t(number_t(0)), EQUALITY);\n        return res;\n    }\n\n    static linear_constraint_t get_false() {\n        linear_constraint_t res(linear_expression_t(number_t(0)), DISEQUATION);\n        return res;\n    }\n\n    bool is_tautology() const {\n        switch (this->_kind) {\n        case DISEQUATION: return (this->_expr.is_constant() && this->_expr.constant() != 0);\n        case EQUALITY: return (this->_expr.is_constant() && this->_expr.constant() == 0);\n        case INEQUALITY: return (this->_expr.is_constant() && this->_expr.constant() <= 0);\n        case STRICT_INEQUALITY: return (this->_expr.is_constant() && this->_expr.constant() < 0);\n        default: CRAB_ERROR(\"Unreachable\");\n        }\n    }\n\n    bool is_contradiction() const {\n        switch (this->_kind) {\n        case DISEQUATION: return (this->_expr.is_constant() && this->_expr.constant() == 0);\n        case EQUALITY: return (this->_expr.is_constant() && this->_expr.constant() != 0);\n        case INEQUALITY: return (this->_expr.is_constant() && this->_expr.constant() > 0);\n        case STRICT_INEQUALITY: return (this->_expr.is_constant() && this->_expr.constant() >= 0);\n        default: CRAB_ERROR(\"Unreachable\");\n        }\n    }\n\n    bool is_inequality() const { return (this->_kind == INEQUALITY); }\n\n    bool is_strict_inequality() const { return (this->_kind == STRICT_INEQUALITY); }\n\n    bool is_equality() const { return (this->_kind == EQUALITY); }\n\n    bool is_disequation() const { return (this->_kind == DISEQUATION); }\n\n    const linear_expression_t& expression() const { return this->_expr; }\n\n    constraint_kind_t kind() const { return this->_kind; }\n\n    bool is_signed() const {\n        if (_kind != INEQUALITY && _kind != STRICT_INEQUALITY) {\n            CRAB_WARN(\"Only inequalities have signedness\");\n        }\n        return _signedness;\n    }\n\n    bool is_unsigned() const { return (!is_signed()); }\n\n    const_iterator begin() const { return this->_expr.begin(); }\n\n    const_iterator end() const { return this->_expr.end(); }\n\n    iterator begin() { return this->_expr.begin(); }\n\n    iterator end() { return this->_expr.end(); }\n\n    std::size_t size() const { return this->_expr.size(); }\n\n    // syntactic equality\n    bool equal(const linear_constraint_t& o) const {\n        return (_kind == o._kind && _signedness == o._signedness && _expr.equal(o._expr));\n    }\n\n    size_t hash() const {\n        size_t res = 0;\n        boost::hash_combine(res, _expr);\n        boost::hash_combine(res, _kind);\n        if (_kind == INEQUALITY || _kind == STRICT_INEQUALITY) {\n            boost::hash_combine(res, _signedness);\n        }\n        return res;\n    }\n\n    index_t index() const {\n        // XXX: to store linear constraints in patricia trees\n        return (index_t)hash();\n    }\n\n    number_t operator[](variable_t x) const { return this->_expr.operator[](x); }\n\n    linear_constraint_t negate() const {\n\n        if (is_tautology()) {\n            return get_false();\n        } else if (is_contradiction()) {\n            return get_true();\n        } else {\n            switch (kind()) {\n            case INEQUALITY: {\n                // try to take advantage if we use z_number_t.\n                // negate(e <= 0) = e >= 1\n                return linear_constraint_t(-(expression() - 1), INEQUALITY, is_signed());\n            }\n            case STRICT_INEQUALITY: {\n                // negate(x + y < 0)  <-->  x + y >= 0 <--> -x -y <= 0\n                linear_expression_t e = -this->_expr;\n                return linear_constraint_t(e, INEQUALITY, is_signed());\n            }\n            case EQUALITY: return linear_constraint_t(this->_expr, DISEQUATION);\n            case DISEQUATION: return linear_constraint_t(this->_expr, EQUALITY);\n            default: CRAB_ERROR(\"Cannot negate linear constraint\");\n            }\n        }\n    }\n\n    template <typename RenamingMap>\n    linear_constraint_t rename(const RenamingMap& map) const {\n        linear_expression_t e = this->_expr.rename(map);\n        return linear_constraint_t(e, this->_kind, is_signed());\n    }\n\n    void write(std::ostream& o) const {\n        if (this->is_contradiction()) {\n            o << \"false\";\n        } else if (this->is_tautology()) {\n            o << \"true\";\n        } else {\n            linear_expression_t e = this->_expr - this->_expr.constant();\n            o << e;\n            switch (this->_kind) {\n            case INEQUALITY: {\n                if (is_signed()) {\n                    o << \" <= \";\n                } else {\n                    o << \" <=_u \";\n                }\n                break;\n            }\n            case STRICT_INEQUALITY: {\n                if (is_signed()) {\n                    o << \" < \";\n                } else {\n                    o << \" <_u \";\n                }\n                break;\n            }\n            case EQUALITY: {\n                o << \" = \";\n                break;\n            }\n            case DISEQUATION: {\n                o << \" != \";\n                break;\n            }\n            }\n            number_t c = -this->_expr.constant();\n            o << c;\n        }\n    }\n\n    // for dgb\n    void dump() { write(std::cout); }\n\n}; // class linear_constraint_t\n\ninline std::ostream& operator<<(std::ostream& o, const linear_constraint_t& c) {\n    c.write(o);\n    return o;\n}\n\ninline std::size_t hash_value(const linear_constraint_t& e) { return e.hash(); }\n\ninline linear_expression_t var_sub(variable_t x, const number_t& n) { return linear_expression_t(x).operator-(n); }\ninline linear_expression_t var_sub(variable_t x, variable_t y) { return linear_expression_t(x).operator-(y); }\ninline linear_expression_t var_add(variable_t x, number_t n) { return linear_expression_t(x).operator+(std::move(n)); }\ninline linear_expression_t var_add(variable_t x, variable_t y) { return linear_expression_t(x).operator+(y); }\ninline linear_expression_t var_mul(const number_t& n, variable_t x) { return linear_expression_t(n, x); }\n} // namespace crab\n", "meta": {"hexsha": "d65b8e95af0d1ea39dd9c66aa9c1e9dcba8a377a", "size": 17877, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/crab/linear_constraints.hpp", "max_stars_repo_name": "oneturkmen/ebpf-verifier", "max_stars_repo_head_hexsha": "fceceea8ca10d7ae011c5105bee08e45c2900e22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/crab/linear_constraints.hpp", "max_issues_repo_name": "oneturkmen/ebpf-verifier", "max_issues_repo_head_hexsha": "fceceea8ca10d7ae011c5105bee08e45c2900e22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/crab/linear_constraints.hpp", "max_forks_repo_name": "oneturkmen/ebpf-verifier", "max_forks_repo_head_hexsha": "fceceea8ca10d7ae011c5105bee08e45c2900e22", "max_forks_repo_licenses": ["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.7126213592, "max_line_length": 119, "alphanum_fraction": 0.5924372098, "num_tokens": 4319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.265071127088915}}
{"text": "#include \"graph_cut.h\"\n\n#include <unordered_map>\n\n#include <boost/graph/stoer_wagner_min_cut.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/typeof/typeof.hpp>\n\nextern \"C\" {\n    #include \"graclus/metisLib/metis.h\"\n}\n\n#include <glog/logging.h>\n\nnamespace GraphSfM {\nnamespace graph {\n\n// Wrapper class for weighted, undirected Graclus graph.\nclass GraclusGraph {\npublic:\n    GraclusGraph(const std::vector<std::pair<int, int>>& edges,\n                 const std::vector<int>& weights) \n    {\n        CHECK_EQ(edges.size(), weights.size());\n\n        std::unordered_map<int, std::vector<std::pair<int, int>>> adjacency_list;\n        for (size_t i = 0; i < edges.size(); ++i) {\n            const auto& edge = edges[i];\n            const auto weight = weights[i];\n            const int vertex_idx1 = GetVertexIdx(edge.first);\n            const int vertex_idx2 = GetVertexIdx(edge.second);\n            adjacency_list[vertex_idx1].emplace_back(vertex_idx2, weight);\n            adjacency_list[vertex_idx2].emplace_back(vertex_idx1, weight);\n        }\n\n        xadj_.reserve(vertex_id_to_idx_.size() + 1);\n        adjncy_.reserve(2 * edges.size());\n        adjwgt_.reserve(2 * edges.size());\n\n        idxtype edge_idx = 0;\n        for (size_t i = 0; i < vertex_id_to_idx_.size(); ++i) {\n            xadj_.push_back(edge_idx);\n\n            if (adjacency_list.count(i) == 0) { continue; }\n\n            for (const auto& edge : adjacency_list[i]) {\n                edge_idx += 1;\n                adjncy_.push_back(edge.first);\n                adjwgt_.push_back(edge.second);\n            }\n        }\n\n        xadj_.push_back(edge_idx);\n\n        CHECK_EQ(edge_idx, 2 * edges.size());\n        CHECK_EQ(xadj_.size(), vertex_id_to_idx_.size() + 1);\n        CHECK_EQ(adjncy_.size(), 2 * edges.size());\n        CHECK_EQ(adjwgt_.size(), 2 * edges.size());\n\n        data.gdata = data.rdata = nullptr;\n\n        data.nvtxs = vertex_id_to_idx_.size();\n        data.nedges = 2 * edges.size();\n        data.mincut = data.minvol = -1;\n\n        data.xadj = xadj_.data();\n        data.adjncy = adjncy_.data();\n\n        data.vwgt = nullptr;\n        data.adjwgt = adjwgt_.data();\n\n        data.adjwgtsum = nullptr;\n        data.label = nullptr;\n        data.cmap = nullptr;\n\n        data.where = data.pwgts = nullptr;\n        data.id = data.ed = nullptr;\n        data.bndptr = data.bndind = nullptr;\n        data.rinfo = nullptr;\n        data.vrinfo = nullptr;\n        data.nrinfo = nullptr;\n\n        data.ncon = 1;\n        data.nvwgt = nullptr;\n        data.npwgts = nullptr;\n\n        data.vsize = nullptr;\n\n        data.coarser = data.finer = nullptr;\n    }\n\n    int GetVertexIdx(const int id) {\n        const auto it = vertex_id_to_idx_.find(id);\n        if (it == vertex_id_to_idx_.end()) {\n            const int idx = vertex_id_to_idx_.size();\n            vertex_id_to_idx_.emplace(id, idx);\n            vertex_idx_to_id_.emplace(idx, id);\n            return idx;\n        } else {\n            return it->second;\n        }\n    }\n\n    int GetVertexId(const int idx) { return vertex_idx_to_id_.at(idx); }\n\n    GraphType data;\n\nprivate:\n    std::unordered_map<int, int> vertex_id_to_idx_;\n    std::unordered_map<int, int> vertex_idx_to_id_;\n    std::vector<idxtype> xadj_;\n    std::vector<idxtype> adjncy_;\n    std::vector<idxtype> adjwgt_;\n};\n\n\n\nvoid ComputeMinGraphCutStoerWagner(\n    const std::vector<std::pair<int, int>>& edges,\n    const std::vector<int>& weights, int* cut_weight,\n    std::vector<char>* cut_labels) \n{\n    CHECK_EQ(edges.size(), weights.size());\n    CHECK_GE(edges.size(), 2);\n\n    typedef boost::property<boost::edge_weight_t, int> edge_weight_t;\n    typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS,\n                                boost::no_property, edge_weight_t>\n        undirected_graph_t;\n\n    int max_vertex_index = 0;\n    for (const auto& edge : edges) {\n        CHECK_GE(edge.first, 0);\n        CHECK_GE(edge.second, 0);\n        max_vertex_index = std::max(max_vertex_index, edge.first);\n        max_vertex_index = std::max(max_vertex_index, edge.second);\n    }\n\n    const undirected_graph_t graph(edges.begin(), edges.end(), weights.begin(),\n                                   max_vertex_index + 1, edges.size());\n\n    const auto parities = boost::make_one_bit_color_map(\n        boost::num_vertices(graph), boost::get(boost::vertex_index, graph));\n\n    *cut_weight = boost::stoer_wagner_min_cut(graph, boost::get(boost::edge_weight, graph),\n                                  boost::parity_map(parities));\n\n    cut_labels->resize(boost::num_vertices(graph));\n    for (size_t i = 0; i < boost::num_vertices(graph); ++i) {\n        (*cut_labels)[i] = boost::get(parities, i);\n    }\n}\n\nstd::unordered_map<int, int> ComputeNormalizedMinGraphCut(\n    const std::vector<std::pair<int, int>>& edges,\n    const std::vector<int>& weights, const int num_parts) \n{\n    GraclusGraph graph(edges, weights);\n\n    const int levels =\n        amax((graph.data.nvtxs) / (40 * log2_metis(num_parts)), 20 * (num_parts));\n\n    std::vector<idxtype> cut_labels(graph.data.nvtxs);\n\n    int options[11];\n    options[0] = 0;\n    int wgtflag = 1;\n    int numflag = 0;\n    int chain_length = 0;\n    int edgecut;\n    int var_num_parts = num_parts;\n\n    MLKKM_PartGraphKway(&graph.data.nvtxs, graph.data.xadj, graph.data.adjncy,\n                        graph.data.vwgt, graph.data.adjwgt, &wgtflag, &numflag,\n                        &var_num_parts, &chain_length, options, &edgecut,\n                        cut_labels.data(), levels);\n\n    float lbvec[MAXNCON];\n    ComputePartitionBalance(&graph.data, num_parts, cut_labels.data(), lbvec);  \n    ComputeNCut(&graph.data, &cut_labels[0], num_parts);    \n    std::unordered_map<int, int> labels;\n    for (size_t idx = 0; idx < cut_labels.size(); ++idx) {\n        labels.emplace(graph.GetVertexId(idx), cut_labels[idx]);\n    }\n\n    return labels;\n}\n\n}  // namespace graph\n}  // namespace GraphSfM\n", "meta": {"hexsha": "fdce24155b05ebc132e5b455ced9d2b498e57d91", "size": 5966, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/graph/graph_cut.cpp", "max_stars_repo_name": "bitlw/EGSfM", "max_stars_repo_head_hexsha": "d5b4260d38237c6bd814648cadcf1fcf2f8f5d31", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "src/graph/graph_cut.cpp", "max_issues_repo_name": "bitlw/EGSfM", "max_issues_repo_head_hexsha": "d5b4260d38237c6bd814648cadcf1fcf2f8f5d31", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "src/graph/graph_cut.cpp", "max_forks_repo_name": "bitlw/EGSfM", "max_forks_repo_head_hexsha": "d5b4260d38237c6bd814648cadcf1fcf2f8f5d31", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 31.2356020942, "max_line_length": 91, "alphanum_fraction": 0.6071069393, "num_tokens": 1524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2649253930937335}}
{"text": "#pragma once\n\n#include <boost/mpl/at.hpp>\n#include <cassert>\n#include <cstdio>\n#include <functional>\n#include <iostream>\n#include \"aux/filtered_range.hpp\"\n#include \"spectral/basis/toolbox/spectral_basis.hpp\"\n#include \"storage/multi_slice.hpp\"\n\n\nnamespace boltzmann {\nnamespace ct_dense {\n\nclass multi_slices_factory\n{\n public:\n  typedef MultiSlice::index_type index_type;\n  // typedef std::tuple<enum TRIG, index_type> key_t;\n  /// key: (angular frequency, _sin_ or _cos_)\n  typedef std::tuple<index_type, enum TRIG> key_t;\n  typedef unsigned int size_type;\n  typedef std::map<key_t, MultiSlice> container_t;\n\n public:\n  template <typename BASIS>\n  static void create(container_t& data, const BASIS& basis);\n};\n\ntemplate <typename BASIS>\nvoid\nmulti_slices_factory::create(container_t& data, const BASIS& basis)\n{\n  typedef std::map<key_t, MultiSlice> container_t;\n  typedef typename BASIS::elem_t elem_t;\n  typedef typename boost::mpl::at_c<typename elem_t::types_t, 0>::type fa_type;\n  typedef typename boost::mpl::at_c<typename elem_t::types_t, 1>::type fr_type;\n  // typename elem_t::Acc::template get<fr_type> fr_accessor;\n  typename elem_t::Acc::template get<fa_type> fa_accessor;\n\n  const index_type L = spectral::get_max_l(basis);\n  const size_type N = basis.n_dofs();\n\n  for (auto elem = basis.begin(); elem != basis.end(); elem++) {\n    auto ang_elem = fa_accessor(*elem);\n\n    const int l = ang_elem.get_id().l;\n    const enum TRIG t = (TRIG)ang_elem.get_id().t;\n    // key_t key(t, l);\n    key_t key(l, t);\n\n    if (data.find(key) != data.end()) continue;  // this element is already done\n\n    typedef std::vector<std::pair<index_type, index_type> > line_t;\n    // line 1 (first line)\n    line_t line1;\n    for (index_type l1 = 0; l1 < l + 1; ++l1) {\n      assert(l - l1 >= 0);\n      line1.push_back(std::make_pair(l1, l - l1));\n    }\n    // line 2 (lower diagonal)\n    line_t line2;\n    for (index_type l1 = l + 1; l1 <= L; ++l1) {\n      line2.push_back(std::make_pair(l1, l1 - l));\n    }\n    // line 3 (upper diagonal)\n    line_t line3;\n\n    if (l > 0) {\n      // hint: if l==0, line2 and line3 are the same\n      for (index_type l1 = 1; l1 <= L - l; ++l1) {\n        line3.push_back(std::make_pair(l1, l1 + l));\n      }\n    }\n\n    auto cmp = [&fa_accessor](const elem_t& e, index_type l, enum TRIG t) {\n      auto id = fa_accessor(e).get_id();\n      return (id.l == l && TRIG(id.t) == t);\n    };\n    // ---------- add lines to data, compute offsets and block sizes ----------\n    // find all elements with given (l, t)-values\n    auto range_z =\n        filtered_range(basis.begin(), basis.end(), std::bind(cmp, std::placeholders::_1, l, t));\n    std::vector<elem_t> elemsz(std::get<0>(range_z), std::get<1>(range_z));\n    size_type size_z = elemsz.size();\n\n    MultiSlice current_mslice(t, l, N);\n\n    auto add_line = [&](const line_t& line) {\n      // process lines\n      for (auto pair : line) {\n        // l1 <-> row\n        const index_type l1 = pair.first;\n        // l2 <-> column\n        const index_type l2 = pair.second;\n        // enum TRIG t1;\n        // enum TRIG t2;\n\n        auto add_range = [&](const std::vector<elem_t>& x, const std::vector<elem_t>& y) {\n          if (x.size() == 0 || y.size() == 0) return;  // nothing to do\n          size_type offset_x = basis.get_dof_index(x.begin()->get_id());\n          size_type size_x = basis.get_dof_index(x.rbegin()->get_id()) - offset_x + 1;\n          assert(size_x == x.size());\n          size_type offset_y = basis.get_dof_index(y.begin()->get_id());\n          size_type size_y = basis.get_dof_index(y.rbegin()->get_id()) - offset_y + 1;\n          assert(size_y == y.size());\n          assert(size_x > 0 && size_y > 0);\n          enum TRIG t1 = TRIG(fa_accessor(x[0]).get_id().t);\n          enum TRIG t2 = TRIG(fa_accessor(y[0]).get_id().t);\n          current_mslice.add_block(l1, t1, l2, t2, offset_x, offset_y, size_x, size_y, size_z);\n        };\n\n        if (t == TRIG::COS) {\n          // Note: range should be contiguous in ordering of elements (this is not ensured here!!)\n          // add range1\n          auto range1x = filteredv(\n              basis.begin(), basis.end(), std::bind(cmp, std::placeholders::_1, l1, TRIG::COS));\n          auto range1y = filteredv(\n              basis.begin(), basis.end(), std::bind(cmp, std::placeholders::_1, l2, TRIG::COS));\n          // aka add block (l1, cos) x (l2, cos) to multi_slice\n          add_range(range1x, range1y);\n\n          auto range2x = filteredv(\n              basis.begin(), basis.end(), std::bind(cmp, std::placeholders::_1, l1, TRIG::SIN));\n          auto range2y = filteredv(\n              basis.begin(), basis.end(), std::bind(cmp, std::placeholders::_1, l2, TRIG::SIN));\n          add_range(range2x, range2y);\n        } else if (t == TRIG::SIN) {\n          // add range1\n          auto range1x = filteredv(\n              basis.begin(), basis.end(), std::bind(cmp, std::placeholders::_1, l1, TRIG::COS));\n          auto range1y = filteredv(\n              basis.begin(), basis.end(), std::bind(cmp, std::placeholders::_1, l2, TRIG::SIN));\n          add_range(range1x, range1y);\n          // add range2\n          auto range2x = filteredv(\n              basis.begin(), basis.end(), std::bind(cmp, std::placeholders::_1, l1, TRIG::SIN));\n          auto range2y = filteredv(\n              basis.begin(), basis.end(), std::bind(cmp, std::placeholders::_1, l2, TRIG::COS));\n          add_range(range2x, range2y);\n        }\n      }\n    };\n\n    add_line(line1);\n    add_line(line2);\n    add_line(line3);\n\n    current_mslice.finalize();\n\n#ifdef DEBUG\n    std::printf(\"MultiSlice finished\\n\\tStats: (l=%3d, t=%3d), size: %6d, blocks: %3d\\n\",\n                l,\n                int(t),\n                current_mslice.size(),\n                current_mslice.nblocks());\n#endif\n    // insert mslice into map\n    data[key] = current_mslice;\n  }\n}\n}  // ct_dense\n}  // end namespace boltzmann\n", "meta": {"hexsha": "fcfa1550d0350037a169480db54e2b5b8e9ef3e4", "size": 5920, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/collision_tensor/dense/multi_slices_factory.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/dense/multi_slices_factory.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/dense/multi_slices_factory.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": 35.8787878788, "max_line_length": 98, "alphanum_fraction": 0.5962837838, "num_tokens": 1678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2649253930937334}}
{"text": "/*\n symmetry_core.cpp\n\n Copyright (c) 2014, 2015, 2016 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 \"symmetry_core.h\"\n#include \"memory.h\"\n#include \"constants.h\"\n#include \"error.h\"\n#include \"system.h\"\n#include <iomanip>\n#include <fstream>\n#include <algorithm>\n#include <set>\n#include \"mathfunctions.h\"\n\n#ifdef _USE_EIGEN\n#include <Eigen/Core>\n#endif\n\nusing namespace PHON_NS;\n\nSymmetry::Symmetry(PHON *phon): Pointers(phon){\n    file_sym = \"SYMM_INFO_PRIM\";\n    time_reversal_sym = false;\n}\nSymmetry::~Symmetry(){}\n\nvoid Symmetry::setup_symmetry()\n{\n    unsigned int natmin = system->natmin;\n    double **xtmp;\n    unsigned int *kdtmp;\n\n    memory->allocate(xtmp, natmin, 3);\n    memory->allocate(kdtmp, natmin);\n\n    unsigned int i, j;\n\n    for (i = 0; i < 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\n        for (j = 0; j < 3; ++j) xtmp[i][j] /= 2.0 * pi;\n\n        kdtmp[i] = system->kd[system->map_p2s[i][0]];\n    }\n\n    SymmList.clear();\n\n    if (mympi->my_rank == 0) {\n        std::cout << \" Symmetry\" << std::endl;\n        std::cout << \" ========\" << std::endl << std::endl;\n        setup_symmetry_operation(natmin, nsym, system->lavec_p, system->rlavec_p, xtmp, kdtmp);\n    }\n\n    MPI_Bcast(&nsym, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);\n    broadcast_symmlist(SymmList);\n\n    if (mympi->my_rank == 0) {\n        std::cout << \"  Number of symmetry operations : \" << nsym << std::endl << std::endl;\n        gensym_withmap(xtmp, kdtmp);\n    }\n}\n\nvoid Symmetry::setup_symmetry_operation(int N, unsigned int &nsym, double aa[3][3], double bb[3][3], \n                                        double **x, unsigned int *kd)\n{\n    int i, j;\n    std::ofstream ofs_sym;\n    std::ifstream ifs_sym;\n    SymmList.clear();\n\n    if (nsym == 0) {\n\n        // Automatically find symmetries.\n\n        std::cout << \"  NSYM = 0 is given: Trying to find symmetry operations.\" << std::endl;\n\n        findsym(N, aa, x, SymmList);\n\n        std::sort(SymmList.begin() + 1, SymmList.end());\n        nsym = SymmList.size();\n\n        if (printsymmetry) {\n            std::cout << \"  PRINTSYMM = 1: Symmetry information will be stored in SYMM_INFO_PRIM file.\" << std::endl << std::endl;\n            ofs_sym.open(file_sym.c_str(), std::ios::out);\n            ofs_sym << nsym << std::endl;\n\n            for (std::vector<SymmetryOperation>::iterator p = SymmList.begin(); p != SymmList.end(); ++p) {\n                for (i = 0; i < 3; ++i) {\n                    for (j = 0; j < 3; ++j) {\n                        ofs_sym << std::setw(4) << (*p).rot[i][j];\n                    }\n                }\n                ofs_sym << \"  \";\n                for (i = 0; i < 3; ++i) {\n                    ofs_sym << std::setprecision(15) << std::setw(20) << (*p).tran[i];\n                }\n                ofs_sym << std::endl;\n            }\n\n            ofs_sym.close();\n        }\n\n    } else if (nsym == 1) {\n\n        // Identity operation only !\n\n        std::cout << \"  NSYM = 1 is given: Only the identity matrix will be considered.\" << std::endl << std::endl;\n\n        int rot_tmp[3][3];\n        double tran_tmp[3];\n\n        for (i = 0; i < 3; ++i){\n            for (j = 0; j < 3; ++j){\n                if(i == j) {\n                    rot_tmp[i][j] = 1;\n                } else {\n                    rot_tmp[i][j] = 0;\n                }\n            }\n            tran_tmp[i] = 0.0;\n        }\n\n        SymmList.push_back(SymmetryOperation(rot_tmp, tran_tmp));\n\n    } else {\n\n        std::cout << \"  NSYM > 1 is given: Symmetry operations will be read from SYMM_INFO_PRIM file\" << std::endl << std::endl;\n\n        int nsym2;\n        int rot_tmp[3][3];\n        double tran_tmp[3];\n\n        ifs_sym.open(file_sym.c_str(), std::ios::in);\n        ifs_sym >> nsym2;\n\n        if(nsym != nsym2) error->exit(\"setup_symmetry_operation\", \"nsym in the given file and the input file are not consistent.\");\n\n        for (i = 0; i < nsym; ++i) {\n            ifs_sym >> rot_tmp[0][0] >> rot_tmp[0][1] >> rot_tmp[0][2]\n            >> rot_tmp[1][0] >> rot_tmp[1][1] >> rot_tmp[1][2] \n            >> rot_tmp[2][0] >> rot_tmp[2][1] >> rot_tmp[2][2]\n            >> tran_tmp[0] >> tran_tmp[1] >> tran_tmp[2];\n\n            SymmList.push_back(SymmetryOperation(rot_tmp, tran_tmp));\n        }\n        ifs_sym.close();\n    }\n}\n\n\nvoid Symmetry::findsym(int N, double aa[3][3], double **x, std::vector<SymmetryOperation> &symop_all) {\n\n    std::vector<RotationMatrix> LatticeSymmList;\n\n    // Generate rotational matrices that don't change the metric tensor\n    LatticeSymmList.clear();\n    find_lattice_symmetry(aa, LatticeSymmList);\n\n    // Generate all the space group operations with translational vectors\n    symop_all.clear();\n    find_crystal_symmetry(N, system->nclassatom, system->atomlist_class, x, \n        LatticeSymmList, symop_all);\n\n    LatticeSymmList.clear();\n}\n\nvoid Symmetry::find_lattice_symmetry(double aa[3][3], std::vector<RotationMatrix> &LatticeSymmList) {\n\n    /*\n    Find the rotational matrices that leave the metric tensor invariant.\n\n    Metric tensor G = (g)_{ij} = a_{i} * a_{j} is invariant under crystal symmetry operations T,\n    i.e. T^{t}GT = G. Since G can be written as G = A^{t}A, the invariance condition is given by\n    (AT)^{t}(AT) = G0 (original).\n    */\n\n    int i, j, k;\n    int m11, m12, m13, m21, m22, m23, m31, m32, m33;\n\n    int nsym_tmp = 0;\n    int mat_tmp[3][3];\n    double det, res;\n    double rot_tmp[3][3];\n    double aa_rot[3][3];\n\n    double metric_tensor[3][3];\n    double metric_tensor_rot[3][3];\n\n\n    for (i = 0; i < 3; ++i) {\n        for (j = 0; j < 3; ++j) {\n            metric_tensor[i][j] = 0.0;\n            for (k = 0; k < 3; ++k) {\n                metric_tensor[i][j] += aa[k][i] * aa[k][j];\n            }\n        }\n    }\n\n    for (i = 0; i < 3; ++i) {\n        for (j = 0; j < 3; ++j) {\n            if (i == j) {\n                mat_tmp[i][i] = 1;\n            } else {\n                mat_tmp[i][j] = 0;\n            }\n        }\n    }\n\n    // Identity matrix should be the first entry.\n    LatticeSymmList.push_back(mat_tmp);\n\n    for (m11 = -1; m11 <= 1; ++m11){\n        for (m12 = -1; m12 <= 1; ++m12) {\n            for (m13 = -1; m13 <= 1; ++m13){\n                for (m21 = -1; m21 <= 1; ++m21){\n                    for (m22 = -1; m22 <= 1; ++m22){\n                        for (m23 = -1; m23 <= 1; ++m23){\n                            for (m31 = -1; m31 <= 1; ++m31){\n                                for (m32 = -1; m32 <= 1; ++m32){\n                                    for (m33 = -1; m33 <= 1; ++m33){\n\n                                        if (m11 == 1 && m12 == 0 && m13 == 0 &&\n                                            m21 == 0 && m22 == 1 && m23 == 0 &&\n                                            m31 == 0 && m32 == 0 && m33 == 1) continue;\n\n                                        det = m11 * (m22 * m33 - m32 * m23)\n                                            - m21 * (m12 * m33 - m32 * m13)\n                                            + m31 * (m12 * m23 - m22 * m13);\n\n                                        if (det != 1 && det != -1) continue;\n\n                                        rot_tmp[0][0] = m11;\n                                        rot_tmp[0][1] = m12;\n                                        rot_tmp[0][2] = m13;\n                                        rot_tmp[1][0] = m21;\n                                        rot_tmp[1][1] = m22;\n                                        rot_tmp[1][2] = m23;\n                                        rot_tmp[2][0] = m31;\n                                        rot_tmp[2][1] = m32;\n                                        rot_tmp[2][2] = m33;\n\n                                        // Here, aa_rot = aa * rot_tmp is correct.\n                                        matmul3(aa_rot, aa, rot_tmp);\n\n                                        for (i = 0; i < 3; ++i) {\n                                            for (j = 0; j < 3; ++j) {\n                                                metric_tensor_rot[i][j] = 0.0;\n                                                for (k = 0; k < 3; ++k) {\n                                                    metric_tensor_rot[i][j] += aa_rot[k][i] * aa_rot[k][j];\n                                                }\n                                            }\n                                        }\n\n                                        res = 0.0;\n                                        for (i = 0; i < 3; ++i) {\n                                            for (j = 0; j < 3; ++j) {\n                                                res += std::pow(metric_tensor[i][j] - metric_tensor_rot[i][j], 2.0);\n                                            }\n                                        }\n\n                                        // Metric tensor is invariant under symmetry operations.\n\n                                        if (res < tolerance * tolerance) {\n                                            ++nsym_tmp;\n                                            for (i = 0; i < 3; ++i) {\n                                                for (j = 0; j < 3; ++j) {\n                                                    mat_tmp[i][j] = static_cast<int>(rot_tmp[i][j]);\n                                                }\n                                            }\n                                            LatticeSymmList.push_back(mat_tmp);\n                                        }\n\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    if (LatticeSymmList.size() > 48) {\n        error->exit(\"find_lattice_symmetry\", \"Number of lattice symmetry is larger than 48.\");\n    }\n}\n\nvoid Symmetry::find_crystal_symmetry(int N, int nclass, std::vector<unsigned int> *atomclass, double **x, \n                                     std::vector<RotationMatrix> LatticeSymmList, std::vector<SymmetryOperation> &CrystalSymmList){\n\n    unsigned int i, j;\n    unsigned int iat, jat, kat, lat;\n    double x_rot[3];\n    double rot[3][3], rot_tmp[3][3], rot_cart[3][3];\n    double tran[3];\n    double x_rot_tmp[3];\n    double tmp[3];\n    double mag[3], mag_rot[3];\n    double diff;\n\n    int rot_int[3][3];\n\n    int ii, jj, kk;\n    unsigned int itype;\n\n    bool is_found;\n    bool isok;\n    bool mag_sym1, mag_sym2;\n\n    bool is_identity_matrix;\n\n\n    // Add identity matrix first.\n    for (i = 0; i < 3; ++i) {\n        for (j = 0; j < 3; ++j) {\n            if (i == j) {\n                rot_int[i][j] = 1;\n            } else {\n                rot_int[i][j] = 0;\n            }\n        }\n        tran[i] = 0.0;\n    }\n\n    CrystalSymmList.push_back(SymmetryOperation(rot_int, tran));\n\n\n    for (std::vector<RotationMatrix>::iterator it_latsym = LatticeSymmList.begin(); it_latsym != LatticeSymmList.end(); ++it_latsym) {\n\n        iat = atomclass[0][0];\n\n        for (i = 0; i < 3; ++i) {\n            for (j = 0; j < 3; ++j) {\n                rot[i][j] = static_cast<double>((*it_latsym).mat[i][j]);\n            }\n        }\n\n        rotvec(x_rot, x[iat], rot);\n\n#ifdef _OPENMP\n#pragma omp parallel for private(jat, tran, isok, kat, x_rot_tmp, is_found, lat, tmp, diff, \\\n    i, j, itype, jj, kk, is_identity_matrix, mag, mag_rot, rot_tmp, rot_cart, mag_sym1, mag_sym2)\n#endif\n        for (ii = 0; ii < atomclass[0].size(); ++ii) {\n            jat = atomclass[0][ii];\n\n            for (i = 0; i < 3; ++i) {\n                tran[i] = x[jat][i] - x_rot[i];\n                tran[i] = tran[i] - nint(tran[i]);\n            }\n\n            isok = true;\n\n            is_identity_matrix = \n                ( std::pow(rot[0][0] - 1.0, 2) + std::pow(rot[0][1], 2) + std::pow(rot[0][2], 2) \n                + std::pow(rot[1][0], 2) + std::pow(rot[1][1] - 1.0, 2) + std::pow(rot[1][2], 2)\n                + std::pow(rot[2][0], 2) + std::pow(rot[2][1], 2) + std::pow(rot[2][2] - 1.0, 2)\n                + std::pow(tran[0], 2) + std::pow(tran[1], 2) + std::pow(tran[2], 2) ) < eps12;\n\n            if (is_identity_matrix) continue;\n\n            for (itype = 0; itype < nclass; ++itype) {\n\n                for (jj = 0; jj < atomclass[itype].size(); ++jj) {\n\n                    kat = atomclass[itype][jj];\n\n                    rotvec(x_rot_tmp, x[kat], rot);\n\n                    for (i = 0; i < 3; ++i) {\n                        x_rot_tmp[i] += tran[i];\n                    }\n\n                    is_found = false;\n\n                    for (kk = 0; kk < atomclass[itype].size(); ++kk) {\n\n                        lat = atomclass[itype][kk];\n\n                        for (i = 0; i < 3; ++i) {\n                            tmp[i] = std::fmod(std::abs(x[lat][i] - x_rot_tmp[i]), 1.0);\n                            tmp[i] = std::min<double>(tmp[i], 1.0 - tmp[i]);\n                        }\n                        diff = tmp[0]*tmp[0] + tmp[1]*tmp[1] + tmp[2]*tmp[2];\n\n                        if (diff < tolerance * tolerance) {\n                            is_found = true;\n                            break;\n                        }\n                    }\n\n                    if (!is_found) isok = false;\n                }\n            }\n\n            if (isok && system->lspin && system->noncollinear) {\n                for (i = 0; i < 3; ++i) {\n                    mag[i] = system->magmom[jat][i];\n                    mag_rot[i] = system->magmom[iat][i];\n                }\n\n                matmul3(rot_tmp, rot, system->rlavec_p);\n                matmul3(rot_cart, system->lavec_p, rot_tmp);\n\n                for (i = 0; i < 3; ++i) {\n                    for (j = 0; j < 3; ++j) {\n                        rot_cart[i][j] /= (2.0 * pi);\n                    }\n                }\n                rotvec(mag_rot, mag_rot, rot_cart);\n\n                // In the case of improper rotation, the factor -1 should be multiplied\n                // because the inversion operation doesn't flip the spin.\n                if (!is_proper(rot_cart)) {\n                    for (i = 0; i < 3; ++i) {\n                        mag_rot[i] = -mag_rot[i];\n                    }\n                }\n\n                mag_sym1 = (std::pow(mag[0] - mag_rot[0], 2.0)\n                    + std::pow(mag[1] - mag_rot[1], 2.0)\n                    + std::pow(mag[2] - mag_rot[2], 2.0) ) < eps6;\n\n                mag_sym2 = (std::pow(mag[0] + mag_rot[0], 2.0)\n                    + std::pow(mag[1] + mag_rot[1], 2.0)\n                    + std::pow(mag[2] + mag_rot[2], 2.0) ) < eps6;\n\n                if (!mag_sym1 && !mag_sym2) {\n                    isok = false;\n                } else if (!mag_sym1 && mag_sym2 && !trev_sym_mag) {\n                    isok = false;\n                }\n            }\n\n\n            if (isok) {\n#ifdef _OPENMP\n#pragma omp critical\n#endif\n                CrystalSymmList.push_back(SymmetryOperation((*it_latsym).mat, tran));\n            }\n        }\n\n    }\n}\n\n\nvoid Symmetry::gensym_withmap(double **x, unsigned int *kd)\n{\n    // Generate symmetry operations in Cartesian coordinate with the atom-mapping information.\n\n    double S[3][3], T[3][3], S_recip[3][3], mat_tmp[3][3];\n    double shift[3], x_mod[3], tmp[3];\n    double diff;\n    unsigned int *map_tmp;\n    int i, j, k;\n    int num_mapped;\n    unsigned int natmin = system->natmin;\n\n    SymmListWithMap.clear();\n\n    memory->allocate(map_tmp, natmin);\n\n    for (std::vector<SymmetryOperation>::iterator isym = SymmList.begin(); isym != SymmList.end(); ++isym) {\n\n        for (i = 0; i < 3; ++i) {\n            for (j = 0; j < 3; ++j) {\n                T[i][j] = static_cast<double>((*isym).rot[i][j]);\n            }\n        }\n\n        for (i = 0; i < 3; ++i) {\n            shift[i] = (*isym).tran[i];\n        }\n\n        invmat3(mat_tmp, T);\n        for (i = 0; i < 3; ++i) {\n            for (j = 0; j < 3; ++j) {\n                S_recip[i][j] = mat_tmp[j][i];\n            }\n        }\n\n        // Convert to Cartesian coordinate\n        matmul3(mat_tmp, T, system->rlavec_p);\n        matmul3(S, system->lavec_p, mat_tmp);\n        for (i = 0; i < 3; ++i) {\n            for (j = 0; j < 3; ++j) {\n                S[i][j] /= 2.0 * pi;\n            }\n        }\n\n        // Generate mapping information\n\n        for (i = 0; i < natmin; ++i) {\n\n            rotvec(x_mod, x[i], T);\n\n            for (j = 0; j < 3; ++j) {\n                x_mod[j] += shift[j];\n            }\n\n            num_mapped = -1;\n\n            for (j = 0; j < natmin; ++j) {\n\n                if (kd[j] == kd[i]) {\n\n                    for (k = 0; k < 3; ++k) {\n                        tmp[k] = std::fmod(std::abs(x_mod[k] - x[j][k]), 1.0);\n                        tmp[k] = std::min<double>(tmp[k], 1.0 - tmp[k]);\t\n                    }\n                    diff = tmp[0] * tmp[0] + tmp[1] * tmp[1] + tmp[2] * tmp[2];\n                    if (diff < tolerance * tolerance) {\n                        num_mapped = j;\n                        break;\n                    }\n                }\n            }\n\n            if (num_mapped == -1) {\n                error->exit(\"gensym_withmap\", \"cannot find a equivalent atom\");\n            }\n            map_tmp[i] = num_mapped;\n        }\n\n        // Add to vector\n\n        SymmListWithMap.push_back(SymmetryOperationWithMapping(S, T, S_recip, map_tmp, natmin, shift));\n    }\n}\n\n\nvoid Symmetry::broadcast_symmlist(std::vector<SymmetryOperation> &sym)\n{\n    int i, j, k;\n    int n;\n    std::vector<int> sym_entry;\n    int ***rot_tmp, rot[3][3];\n    double **tran_tmp, tran[3];\n\n    if (mympi->my_rank == 0) n = sym.size();\n    MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);\n\n    memory->allocate(rot_tmp, n, 3, 3);\n    memory->allocate(tran_tmp, n, 3);\n\n    if (mympi->my_rank == 0) {\n        for (i = 0; i < n; ++i) {\n            for (j = 0; j < 3; ++j) {\n                for (k = 0; k < 3; ++k) {\n                    rot_tmp[i][j][k] = sym[i].rot[j][k];\n                }\n                tran_tmp[i][j] = sym[i].tran[j];\n            }\n        }\n    }\n    MPI_Bcast(&rot_tmp[0][0][0], 9*n, MPI_INT, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&tran_tmp[0][0], 3*n, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n\n    if (mympi->my_rank > 0) {\n        for (i = 0; i < n; ++i) {\n            for (j = 0; j < 3; ++j) {\n                for (k = 0; k < 3; ++k) {\n                    rot[j][k] = rot_tmp[i][j][k];\n                }\n                tran[j] = tran_tmp[i][j];\n            }\n            sym.push_back(SymmetryOperation(rot,tran));\n        }\n    }\n\n    memory->deallocate(rot_tmp);\n    memory->deallocate(tran_tmp);\n}\n\nbool Symmetry::is_proper(double rot[3][3])\n{\n    double det;\n    bool ret;\n\n    det = rot[0][0] * (rot[1][1] * rot[2][2] - rot[2][1] * rot[1][2])\n        - rot[1][0] * (rot[0][1] * rot[2][2] - rot[2][1] * rot[0][2])\n        + rot[2][0] * (rot[0][1] * rot[1][2] - rot[1][1] * rot[0][2]);\n\n    if (std::abs(det - 1.0) < eps12) {\n        ret = true;\n    } else if (std::abs(det + 1.0) < eps12) {\n        ret = false;\n    } else {\n        error->exit(\"is_proper\", \"This cannot happen.\");\n    }\n\n    return ret;\n}\n", "meta": {"hexsha": "d965047950d77f01b1a141a1ac12b2ad10ad27ba", "size": 19259, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "anphon/symmetry_core.cpp", "max_stars_repo_name": "dlnguyen/alamode", "max_stars_repo_head_hexsha": "f99d333262489f28a3ef4838dfbe3147dc239261", "max_stars_repo_licenses": ["MIT"], "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/symmetry_core.cpp", "max_issues_repo_name": "dlnguyen/alamode", "max_issues_repo_head_hexsha": "f99d333262489f28a3ef4838dfbe3147dc239261", "max_issues_repo_licenses": ["MIT"], "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/symmetry_core.cpp", "max_forks_repo_name": "dlnguyen/alamode", "max_forks_repo_head_hexsha": "f99d333262489f28a3ef4838dfbe3147dc239261", "max_forks_repo_licenses": ["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.8857615894, "max_line_length": 134, "alphanum_fraction": 0.4225037645, "num_tokens": 5482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2649253930937334}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2012-2019 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_ALGORITHMS_DETAIL_BUFFER_LINE_LINE_INTERSECTION_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_LINE_LINE_INTERSECTION_HPP\n\n\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/strategies/buffer.hpp>\n#include <boost/geometry/algorithms/detail/buffer/parallel_continue.hpp>\n\nnamespace boost { namespace geometry\n{\n\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace buffer\n{\n\n\n// TODO: once change this to proper strategy\n// It is different from current segment intersection because these are not segments but lines\n// If we have the Line concept, we can create a strategy\n// Assumes a convex corner\nstruct line_line_intersection\n{\n\n    template <typename Point>\n    static inline strategy::buffer::join_selector apply(Point const& pi, Point const& pj,\n        Point const& qi, Point const& qj, Point& ip)\n    {\n        typedef typename coordinate_type<Point>::type ct;\n\n        // Construct lines in general form (ax + by + c = 0),\n        // (will be replaced by a general_form structure in a next PR)\n        ct const pa = get<1>(pi) - get<1>(pj);\n        ct const pb = get<0>(pj) - get<0>(pi);\n        ct const pc = -pa * get<0>(pi) - pb * get<1>(pi);\n\n        ct const qa = get<1>(qi) - get<1>(qj);\n        ct const qb = get<0>(qj) - get<0>(qi);\n        ct const qc = -qa * get<0>(qi) - qb * get<1>(qi);\n\n        ct const denominator = pb * qa - pa * qb;\n\n        // Even if the corner was checked before (so it is convex now), that\n        // was done on the original geometry. This function runs on the buffered\n        // geometries, where sides are generated and might be slightly off. In\n        // Floating Point, that slightly might just exceed the limit and we have\n        // to check it again.\n\n        // For round joins, it will not be used at all.\n        // For miter joins, there is a miter limit\n        // If segments are parallel/collinear we must be distinguish two cases:\n        // they continue each other, or they form a spike\n        ct const zero = ct();\n        if (math::equals(denominator, zero))\n        {\n            return parallel_continue(qb, -qa, pb, -pa)\n                ? strategy::buffer::join_continue\n                : strategy::buffer::join_spike\n                ;\n        }\n\n        set<0>(ip, (pc * qb - pb * qc) / denominator);\n        set<1>(ip, (pa * qc - pc * qa) / denominator);\n\n        return strategy::buffer::join_convex;\n    }\n};\n\n\n}} // namespace detail::buffer\n#endif // DOXYGEN_NO_DETAIL\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_LINE_LINE_INTERSECTION_HPP\n", "meta": {"hexsha": "11f1c689a5d3cd62517ef22c51da09db7c2c81c1", "size": 2920, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/boost/geometry/algorithms/detail/buffer/line_line_intersection.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/algorithms/detail/buffer/line_line_intersection.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/algorithms/detail/buffer/line_line_intersection.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": 33.9534883721, "max_line_length": 93, "alphanum_fraction": 0.6609589041, "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2649221781820489}}
{"text": "/*\n * This file is a part of the TChecker project.\n *\n * See files AUTHORS and LICENSE for copyright details.\n *\n */\n\n#include <boost/dynamic_bitset.hpp>\n\n#include \"tchecker/dbm/refdbm.hh\"\n#include \"tchecker/refzg/semantics.hh\"\n\nnamespace tchecker {\n\nnamespace refzg {\n\n/* standard_semantics_t */\n\ntchecker::state_status_t standard_semantics_t::initial(tchecker::dbm::db_t * rdbm,\n                                                       tchecker::reference_clock_variables_t const & r,\n                                                       boost::dynamic_bitset<> const & delay_allowed,\n                                                       tchecker::clock_constraint_container_t const & invariant)\n{\n  tchecker::refdbm::zero(rdbm, r);\n\n  if (tchecker::refdbm::constrain(rdbm, r, invariant) == tchecker::dbm::EMPTY)\n    return tchecker::STATE_CLOCKS_SRC_INVARIANT_VIOLATED;\n\n  return tchecker::STATE_OK;\n}\n\ntchecker::state_status_t standard_semantics_t::next(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n                                                    boost::dynamic_bitset<> const & src_delay_allowed,\n                                                    tchecker::clock_constraint_container_t const & src_invariant,\n                                                    boost::dynamic_bitset<> const & sync_ref_clocks,\n                                                    tchecker::clock_constraint_container_t const & guard,\n                                                    tchecker::clock_reset_container_t const & clkreset,\n                                                    boost::dynamic_bitset<> const & tgt_delay_allowed,\n                                                    tchecker::clock_constraint_container_t const & tgt_invariant)\n{\n  if (src_delay_allowed.any()) {\n    tchecker::refdbm::asynchronous_open_up(rdbm, r, src_delay_allowed);\n\n    if (tchecker::refdbm::constrain(rdbm, r, src_invariant) == tchecker::dbm::EMPTY)\n      return tchecker::STATE_CLOCKS_SRC_INVARIANT_VIOLATED; // should never occur\n  }\n\n  if (tchecker::refdbm::synchronize(rdbm, r, sync_ref_clocks) == tchecker::dbm::EMPTY)\n    return tchecker::STATE_CLOCKS_EMPTY_SYNC;\n\n  if (tchecker::refdbm::constrain(rdbm, r, guard) == tchecker::dbm::EMPTY)\n    return tchecker::STATE_CLOCKS_GUARD_VIOLATED;\n\n  tchecker::refdbm::reset(rdbm, r, clkreset);\n\n  if (tchecker::refdbm::constrain(rdbm, r, tgt_invariant) == tchecker::dbm::EMPTY)\n    return tchecker::STATE_CLOCKS_TGT_INVARIANT_VIOLATED;\n\n  return tchecker::STATE_OK;\n}\n\n/* elapsed_semantics_t */\n\ntchecker::state_status_t elapsed_semantics_t::initial(tchecker::dbm::db_t * rdbm,\n                                                      tchecker::reference_clock_variables_t const & r,\n                                                      boost::dynamic_bitset<> const & delay_allowed,\n                                                      tchecker::clock_constraint_container_t const & invariant)\n{\n  tchecker::refdbm::zero(rdbm, r);\n\n  if (tchecker::refdbm::constrain(rdbm, r, invariant) == tchecker::dbm::EMPTY)\n    return tchecker::STATE_CLOCKS_SRC_INVARIANT_VIOLATED;\n\n  if (delay_allowed.any()) {\n    tchecker::refdbm::asynchronous_open_up(rdbm, r, delay_allowed);\n\n    if (tchecker::refdbm::constrain(rdbm, r, invariant) == tchecker::dbm::EMPTY)\n      return tchecker::STATE_CLOCKS_SRC_INVARIANT_VIOLATED;\n  }\n\n  return tchecker::STATE_OK;\n}\n\ntchecker::state_status_t elapsed_semantics_t::next(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n                                                   boost::dynamic_bitset<> const & src_delay_allowed,\n                                                   tchecker::clock_constraint_container_t const & src_invariant,\n                                                   boost::dynamic_bitset<> const & sync_ref_clocks,\n                                                   tchecker::clock_constraint_container_t const & guard,\n                                                   tchecker::clock_reset_container_t const & clkreset,\n                                                   boost::dynamic_bitset<> const & tgt_delay_allowed,\n                                                   tchecker::clock_constraint_container_t const & tgt_invariant)\n{\n  if (tchecker::refdbm::constrain(rdbm, r, src_invariant) == tchecker::dbm::EMPTY)\n    return tchecker::STATE_CLOCKS_SRC_INVARIANT_VIOLATED;\n\n  if (tchecker::refdbm::synchronize(rdbm, r, sync_ref_clocks) == tchecker::dbm::EMPTY)\n    return tchecker::STATE_CLOCKS_EMPTY_SYNC;\n\n  if (tchecker::refdbm::constrain(rdbm, r, guard) == tchecker::dbm::EMPTY)\n    return tchecker::STATE_CLOCKS_GUARD_VIOLATED;\n\n  tchecker::refdbm::reset(rdbm, r, clkreset);\n\n  if (tchecker::refdbm::constrain(rdbm, r, tgt_invariant) == tchecker::dbm::EMPTY)\n    return tchecker::STATE_CLOCKS_TGT_INVARIANT_VIOLATED;\n\n  if (tgt_delay_allowed.any()) {\n    tchecker::refdbm::asynchronous_open_up(rdbm, r, tgt_delay_allowed);\n\n    if (tchecker::refdbm::constrain(rdbm, r, tgt_invariant) == tchecker::dbm::EMPTY)\n      return tchecker::STATE_CLOCKS_TGT_INVARIANT_VIOLATED;\n  }\n\n  return tchecker::STATE_OK;\n}\n\n/* factory */\n\ntchecker::refzg::semantics_t * semantics_factory(enum tchecker::refzg::semantics_type_t semantics)\n{\n  switch (semantics) {\n  case tchecker::refzg::STANDARD_SEMANTICS:\n    return new tchecker::refzg::standard_semantics_t{};\n  case tchecker::refzg::ELAPSED_SEMANTICS:\n    return new tchecker::refzg::elapsed_semantics_t{};\n  default:\n    throw std::invalid_argument(\"Unknown semantics over zones with reference clocks\");\n  }\n}\n\n} // end of namespace refzg\n\n} // end of namespace tchecker", "meta": {"hexsha": "c878ea2526abd4fdcff9f4d5b8af541b16bed5da", "size": 5668, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/refzg/semantics.cc", "max_stars_repo_name": "mukherjee-sayan/tchecker", "max_stars_repo_head_hexsha": "c4f37a479a7273c15fc45ccb9741984e72036f2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/refzg/semantics.cc", "max_issues_repo_name": "mukherjee-sayan/tchecker", "max_issues_repo_head_hexsha": "c4f37a479a7273c15fc45ccb9741984e72036f2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/refzg/semantics.cc", "max_forks_repo_name": "mukherjee-sayan/tchecker", "max_forks_repo_head_hexsha": "c4f37a479a7273c15fc45ccb9741984e72036f2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-11T10:01:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T10:01:27.000Z", "avg_line_length": 42.6165413534, "max_line_length": 128, "alphanum_fraction": 0.6217360621, "num_tokens": 1352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.26492217295347203}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_AEQD_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_AEQD_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, 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: 4.9.1\r\n\r\n// Original copyright notice:\r\n\r\n// Purpose:  Implementation of the aeqd (Azimuthal Equidistant) projection.\r\n// Author:   Gerald Evenden\r\n// Copyright (c) 1995, Gerald Evenden\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/config.hpp>\r\n#include <boost/geometry/util/math.hpp>\r\n#include <boost/math/special_functions/hypot.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/aasincos.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_mlfn.hpp>\r\n\r\n#include <boost/geometry/srs/projections/par4.hpp>\r\n\r\n#include <boost/type_traits/is_same.hpp>\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace srs { namespace par4\r\n{\r\n    struct aeqd {};\r\n    //struct aeqd_guam {};\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 aeqd\r\n    {\r\n\r\n            static const double EPS10 = 1.e-10;\r\n            static const double TOL = 1.e-14;\r\n            static const int N_POLE = 0;\r\n            static const int S_POLE = 1;\r\n            static const int EQUIT = 2;\r\n            static const int OBLIQ = 3;\r\n\r\n            template <typename T>\r\n            struct par_aeqd\r\n            {\r\n                T    sinph0;\r\n                T    cosph0;\r\n                T    en[EN_SIZE];\r\n                T    M1;\r\n                T    N1;\r\n                T    Mp;\r\n                T    He;\r\n                T    G;\r\n                int        mode;\r\n            };\r\n\r\n            template <typename T, typename Par, typename ProjParm>\r\n            inline void e_forward(T& lp_lon, T& lp_lat, T& xy_x, T& xy_y, Par const& par, ProjParm const& proj_parm)\r\n            {\r\n                T  coslam, cosphi, sinphi, rho, s, H, H2, c, Az, t, ct, st, cA, sA;\r\n\r\n                coslam = cos(lp_lon);\r\n                cosphi = cos(lp_lat);\r\n                sinphi = sin(lp_lat);\r\n                switch (proj_parm.mode) {\r\n                case N_POLE:\r\n                    coslam = - coslam;\r\n                    BOOST_FALLTHROUGH;\r\n                case S_POLE:\r\n                    xy_x = (rho = fabs(proj_parm.Mp - pj_mlfn(lp_lat, sinphi, cosphi, proj_parm.en))) *\r\n                        sin(lp_lon);\r\n                    xy_y = rho * coslam;\r\n                    break;\r\n                case EQUIT:\r\n                case OBLIQ:\r\n                    if (fabs(lp_lon) < EPS10 && fabs(lp_lat - par.phi0) < EPS10) {\r\n                        xy_x = xy_y = 0.;\r\n                        break;\r\n                    }\r\n                    t = atan2(par.one_es * sinphi + par.es * proj_parm.N1 * proj_parm.sinph0 *\r\n                        sqrt(1. - par.es * sinphi * sinphi), cosphi);\r\n                    ct = cos(t); st = sin(t);\r\n                    Az = atan2(sin(lp_lon) * ct, proj_parm.cosph0 * st - proj_parm.sinph0 * coslam * ct);\r\n                    cA = cos(Az); sA = sin(Az);\r\n                    s = aasin(fabs(sA) < TOL ?\r\n                        (proj_parm.cosph0 * st - proj_parm.sinph0 * coslam * ct) / cA :\r\n                        sin(lp_lon) * ct / sA );\r\n                    H = proj_parm.He * cA;\r\n                    H2 = H * H;\r\n                    c = proj_parm.N1 * s * (1. + s * s * (- H2 * (1. - H2)/6. +\r\n                        s * ( proj_parm.G * H * (1. - 2. * H2 * H2) / 8. +\r\n                        s * ((H2 * (4. - 7. * H2) - 3. * proj_parm.G * proj_parm.G * (1. - 7. * H2)) /\r\n                        120. - s * proj_parm.G * H / 48.))));\r\n                    xy_x = c * sA;\r\n                    xy_y = c * cA;\r\n                    break;\r\n                }\r\n            }\r\n\r\n            template <typename T, typename Par, typename ProjParm>\r\n            inline void e_inverse(T& xy_x, T& xy_y, T& lp_lon, T& lp_lat, Par const& par, ProjParm const& proj_parm)\r\n            {\r\n                static const T HALFPI = detail::HALFPI<T>();\r\n\r\n                T c, Az, cosAz, A, B, D, E, F, psi, t;\r\n\r\n                if ((c = boost::math::hypot(xy_x, xy_y)) < EPS10) {\r\n                    lp_lat = par.phi0;\r\n                    lp_lon = 0.;\r\n                        return;\r\n                }\r\n                if (proj_parm.mode == OBLIQ || proj_parm.mode == EQUIT) {\r\n                    cosAz = cos(Az = atan2(xy_x, xy_y));\r\n                    t = proj_parm.cosph0 * cosAz;\r\n                    B = par.es * t / par.one_es;\r\n                    A = - B * t;\r\n                    B *= 3. * (1. - A) * proj_parm.sinph0;\r\n                    D = c / proj_parm.N1;\r\n                    E = D * (1. - D * D * (A * (1. + A) / 6. + B * (1. + 3.*A) * D / 24.));\r\n                    F = 1. - E * E * (A / 2. + B * E / 6.);\r\n                    psi = aasin(proj_parm.sinph0 * cos(E) + t * sin(E));\r\n                    lp_lon = aasin(sin(Az) * sin(E) / cos(psi));\r\n                    if ((t = fabs(psi)) < EPS10)\r\n                        lp_lat = 0.;\r\n                    else if (fabs(t - HALFPI) < 0.)\r\n                        lp_lat = HALFPI;\r\n                    else\r\n                        lp_lat = atan((1. - par.es * F * proj_parm.sinph0 / sin(psi)) * tan(psi) /\r\n                            par.one_es);\r\n                } else { /* Polar */\r\n                    lp_lat = pj_inv_mlfn(proj_parm.mode == N_POLE ? proj_parm.Mp - c : proj_parm.Mp + c,\r\n                        par.es, proj_parm.en);\r\n                    lp_lon = atan2(xy_x, proj_parm.mode == N_POLE ? -xy_y : xy_y);\r\n                }\r\n            }\r\n\r\n            template <typename T, typename Par, typename ProjParm>\r\n            inline void e_guam_fwd(T& lp_lon, T& lp_lat, T& xy_x, T& xy_y, Par const& par, ProjParm const& proj_parm)\r\n            {\r\n                T cosphi, sinphi, t;\r\n\r\n                cosphi = cos(lp_lat);\r\n                sinphi = sin(lp_lat);\r\n                t = 1. / sqrt(1. - par.es * sinphi * sinphi);\r\n                xy_x = lp_lon * cosphi * t;\r\n                xy_y = pj_mlfn(lp_lat, sinphi, cosphi, proj_parm.en) - proj_parm.M1 +\r\n                    .5 * lp_lon * lp_lon * cosphi * sinphi * t;\r\n            }\r\n\r\n            template <typename T, typename Par, typename ProjParm>\r\n            inline void e_guam_inv(T& xy_x, T& xy_y, T& lp_lon, T& lp_lat, Par const& par, ProjParm const& proj_parm)\r\n            {\r\n                T x2, t;\r\n                int i;\r\n\r\n                x2 = 0.5 * xy_x * xy_x;\r\n                lp_lat = par.phi0;\r\n                for (i = 0; i < 3; ++i) {\r\n                    t = par.e * sin(lp_lat);\r\n                    lp_lat = pj_inv_mlfn(proj_parm.M1 + xy_y -\r\n                        x2 * tan(lp_lat) * (t = sqrt(1. - t * t)), par.es, proj_parm.en);\r\n                }\r\n                lp_lon = xy_x * t / cos(lp_lat);\r\n            }\r\n\r\n            template <typename T, typename Par, typename ProjParm>\r\n            inline void s_forward(T& lp_lon, T& lp_lat, T& xy_x, T& xy_y, Par const& /*par*/, ProjParm const& proj_parm)\r\n            {\r\n                static const T HALFPI = detail::HALFPI<T>();\r\n                    \r\n                T coslam, cosphi, sinphi;\r\n\r\n                sinphi = sin(lp_lat);\r\n                cosphi = cos(lp_lat);\r\n                coslam = cos(lp_lon);\r\n                switch (proj_parm.mode) {\r\n                case EQUIT:\r\n                    xy_y = cosphi * coslam;\r\n                    goto oblcon;\r\n                case OBLIQ:\r\n                    xy_y = proj_parm.sinph0 * sinphi + proj_parm.cosph0 * cosphi * coslam;\r\n            oblcon:\r\n                    if (fabs(fabs(xy_y) - 1.) < TOL)\r\n                        if (xy_y < 0.)\r\n                            BOOST_THROW_EXCEPTION( projection_exception(-20) );\r\n                        else\r\n                            xy_x = xy_y = 0.;\r\n                    else {\r\n                        xy_y = acos(xy_y);\r\n                        xy_y /= sin(xy_y);\r\n                        xy_x = xy_y * cosphi * sin(lp_lon);\r\n                        xy_y *= (proj_parm.mode == EQUIT) ? sinphi :\r\n                                proj_parm.cosph0 * sinphi - proj_parm.sinph0 * cosphi * coslam;\r\n                    }\r\n                    break;\r\n                case N_POLE:\r\n                    lp_lat = -lp_lat;\r\n                    coslam = -coslam;\r\n                    BOOST_FALLTHROUGH;\r\n                case S_POLE:\r\n                    if (fabs(lp_lat - HALFPI) < EPS10)\r\n                        BOOST_THROW_EXCEPTION( projection_exception(-20) );\r\n                    xy_x = (xy_y = (HALFPI + lp_lat)) * sin(lp_lon);\r\n                    xy_y *= coslam;\r\n                    break;\r\n                }\r\n            }\r\n\r\n            template <typename T, typename Par, typename ProjParm>\r\n            inline void s_inverse(T& xy_x, T& xy_y, T& lp_lon, T& lp_lat, Par const& par, ProjParm const& proj_parm)\r\n            {\r\n                static const T ONEPI = detail::ONEPI<T>();\r\n                static const T HALFPI = detail::HALFPI<T>();\r\n                    \r\n                T cosc, c_rh, sinc;\r\n\r\n                if ((c_rh = boost::math::hypot(xy_x, xy_y)) > ONEPI) {\r\n                    if (c_rh - EPS10 > ONEPI)\r\n                        BOOST_THROW_EXCEPTION( projection_exception(-20) );\r\n                    c_rh = ONEPI;\r\n                } else if (c_rh < EPS10) {\r\n                    lp_lat = par.phi0;\r\n                    lp_lon = 0.;\r\n                        return;\r\n                }\r\n                if (proj_parm.mode == OBLIQ || proj_parm.mode == EQUIT) {\r\n                    sinc = sin(c_rh);\r\n                    cosc = cos(c_rh);\r\n                    if (proj_parm.mode == EQUIT) {\r\n                                    lp_lat = aasin(xy_y * sinc / c_rh);\r\n                        xy_x *= sinc;\r\n                        xy_y = cosc * c_rh;\r\n                    } else {\r\n                        lp_lat = aasin(cosc * proj_parm.sinph0 + xy_y * sinc * proj_parm.cosph0 /\r\n                            c_rh);\r\n                        xy_y = (cosc - proj_parm.sinph0 * sin(lp_lat)) * c_rh;\r\n                        xy_x *= sinc * proj_parm.cosph0;\r\n                    }\r\n                    lp_lon = atan2(xy_x, xy_y);\r\n                } else if (proj_parm.mode == N_POLE) {\r\n                    lp_lat = HALFPI - c_rh;\r\n                    lp_lon = atan2(xy_x, -xy_y);\r\n                } else {\r\n                    lp_lat = c_rh - HALFPI;\r\n                    lp_lon = atan2(xy_x, xy_y);\r\n                }\r\n            }\r\n\r\n            // Azimuthal Equidistant\r\n            template <typename Parameters, typename T>\r\n            inline void setup_aeqd(Parameters& par, par_aeqd<T>& proj_parm, bool is_sphere, bool is_guam)\r\n            {\r\n                static const T HALFPI = detail::HALFPI<T>();\r\n\r\n                par.phi0 = pj_param(par.params, \"rlat_0\").f;\r\n                if (fabs(fabs(par.phi0) - HALFPI) < EPS10) {\r\n                    proj_parm.mode = par.phi0 < 0. ? S_POLE : N_POLE;\r\n                    proj_parm.sinph0 = par.phi0 < 0. ? -1. : 1.;\r\n                    proj_parm.cosph0 = 0.;\r\n                } else if (fabs(par.phi0) < EPS10) {\r\n                    proj_parm.mode = EQUIT;\r\n                    proj_parm.sinph0 = 0.;\r\n                    proj_parm.cosph0 = 1.;\r\n                } else {\r\n                    proj_parm.mode = OBLIQ;\r\n                    proj_parm.sinph0 = sin(par.phi0);\r\n                    proj_parm.cosph0 = cos(par.phi0);\r\n                }\r\n                if (is_sphere) {\r\n                } else {\r\n                    if (!pj_enfn(par.es, proj_parm.en))\r\n                        BOOST_THROW_EXCEPTION( projection_exception(0) );\r\n                    if (is_guam) {\r\n                        proj_parm.M1 = pj_mlfn(par.phi0, proj_parm.sinph0, proj_parm.cosph0, proj_parm.en);\r\n                    } else {\r\n                        switch (proj_parm.mode) {\r\n                        case N_POLE:\r\n                            proj_parm.Mp = pj_mlfn<T>(HALFPI, 1., 0., proj_parm.en);\r\n                            break;\r\n                        case S_POLE:\r\n                            proj_parm.Mp = pj_mlfn<T>(-HALFPI, -1., 0., proj_parm.en);\r\n                            break;\r\n                        case EQUIT:\r\n                        case OBLIQ:\r\n                            proj_parm.N1 = 1. / sqrt(1. - par.es * proj_parm.sinph0 * proj_parm.sinph0);\r\n                            proj_parm.G = proj_parm.sinph0 * (proj_parm.He = par.e / sqrt(par.one_es));\r\n                            proj_parm.He *= proj_parm.cosph0;\r\n                            break;\r\n                        }\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_aeqd_e : public base_t_fi<base_aeqd_e<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_aeqd<CalculationType> m_proj_parm;\r\n\r\n                inline base_aeqd_e(const Parameters& par)\r\n                    : base_t_fi<base_aeqd_e<CalculationType, Parameters>,\r\n                     CalculationType, Parameters>(*this, par) {}\r\n\r\n                // FORWARD(e_forward)  elliptical\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                    e_forward(lp_lon, lp_lat, xy_x, xy_y, this->m_par, this->m_proj_parm);\r\n                }\r\n\r\n                // INVERSE(e_inverse)  elliptical\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                    e_inverse(xy_x, xy_y, lp_lon, lp_lat, this->m_par, this->m_proj_parm);\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"aeqd_e\";\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_aeqd_e_guam : public base_t_fi<base_aeqd_e_guam<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_aeqd<CalculationType> m_proj_parm;\r\n\r\n                inline base_aeqd_e_guam(const Parameters& par)\r\n                    : base_t_fi<base_aeqd_e_guam<CalculationType, Parameters>,\r\n                     CalculationType, Parameters>(*this, par) {}\r\n\r\n                // FORWARD(e_guam_fwd)  Guam elliptical\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                    e_guam_fwd(lp_lon, lp_lat, xy_x, xy_y, this->m_par, this->m_proj_parm);\r\n                }\r\n\r\n                // INVERSE(e_guam_inv)  Guam elliptical\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                    e_guam_inv(xy_x, xy_y, lp_lon, lp_lat, this->m_par, this->m_proj_parm);\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"aeqd_e_guam\";\r\n                }\r\n\r\n            };\r\n\r\n            // template class, using CRTP to implement forward/inverse\r\n            template <typename BGParameters, typename CalculationType, typename Parameters>\r\n            struct base_aeqd_e_static : public base_t_fi<base_aeqd_e_static<BGParameters, 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_aeqd<CalculationType> m_proj_parm;\r\n\r\n                static const bool is_guam = ! boost::is_same\r\n                    <\r\n                        typename srs::par4::detail::tuples_find_if\r\n                            <\r\n                                BGParameters,\r\n                                //srs::par4::detail::is_guam\r\n                                srs::par4::detail::is_param<srs::par4::guam>::pred\r\n                            >::type,\r\n                        void\r\n                    >::value;\r\n\r\n                inline base_aeqd_e_static(const Parameters& par)\r\n                    : base_t_fi<base_aeqd_e_static<BGParameters, CalculationType, Parameters>,\r\n                     CalculationType, Parameters>(*this, par)\r\n                {}\r\n\r\n                // FORWARD(e_forward or e_guam_fwd)  elliptical\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                    if (is_guam)\r\n                        e_guam_fwd(lp_lon, lp_lat, xy_x, xy_y, this->m_par, this->m_proj_parm);\r\n                    else\r\n                        e_forward(lp_lon, lp_lat, xy_x, xy_y, this->m_par, this->m_proj_parm);\r\n                }\r\n\r\n                // INVERSE(e_inverse or e_guam_inv)  elliptical\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                    if (is_guam)\r\n                        e_guam_inv(xy_x, xy_y, lp_lon, lp_lat, this->m_par, this->m_proj_parm);\r\n                    else\r\n                        e_inverse(xy_x, xy_y, lp_lon, lp_lat, this->m_par, this->m_proj_parm);\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"aeqd_e_static\";\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_aeqd_s : public base_t_fi<base_aeqd_s<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_aeqd<CalculationType> m_proj_parm;\r\n\r\n                inline base_aeqd_s(const Parameters& par)\r\n                    : base_t_fi<base_aeqd_s<CalculationType, Parameters>,\r\n                     CalculationType, Parameters>(*this, par) {}\r\n\r\n                // FORWARD(s_forward)  spherical\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                    s_forward(lp_lon, lp_lat, xy_x, xy_y, this->m_par, this->m_proj_parm);\r\n                }\r\n\r\n                // INVERSE(s_inverse)  spherical\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                    s_inverse(xy_x, xy_y, lp_lon, lp_lat, this->m_par, this->m_proj_parm);\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"aeqd_s\";\r\n                }\r\n\r\n            };\r\n\r\n    }} // namespace detail::aeqd\r\n    #endif // doxygen\r\n\r\n    /*!\r\n        \\brief Azimuthal Equidistant 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         - Azimuthal\r\n         - Spheroid\r\n         - Ellipsoid\r\n        \\par Projection parameters\r\n         - lat_0: Latitude of origin (degrees)\r\n         - guam (boolean)\r\n        \\par Example\r\n        \\image html ex_aeqd.gif\r\n    */\r\n    template <typename CalculationType, typename Parameters>\r\n    struct aeqd_e : public detail::aeqd::base_aeqd_e<CalculationType, Parameters>\r\n    {\r\n        inline aeqd_e(const Parameters& par) : detail::aeqd::base_aeqd_e<CalculationType, Parameters>(par)\r\n        {\r\n            detail::aeqd::setup_aeqd(this->m_par, this->m_proj_parm, false, false);\r\n        }\r\n    };\r\n\r\n    /*!\r\n        \\brief Azimuthal Equidistant 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         - Azimuthal\r\n         - Spheroid\r\n         - Ellipsoid\r\n        \\par Projection parameters\r\n         - lat_0: Latitude of origin (degrees)\r\n         - guam (boolean)\r\n        \\par Example\r\n        \\image html ex_aeqd.gif\r\n    */\r\n    template <typename CalculationType, typename Parameters>\r\n    struct aeqd_e_guam : public detail::aeqd::base_aeqd_e_guam<CalculationType, Parameters>\r\n    {\r\n        inline aeqd_e_guam(const Parameters& par) : detail::aeqd::base_aeqd_e_guam<CalculationType, Parameters>(par)\r\n        {\r\n            detail::aeqd::setup_aeqd(this->m_par, this->m_proj_parm, false, true);\r\n        }\r\n    };\r\n\r\n    /*!\r\n        \\brief Azimuthal Equidistant 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         - Azimuthal\r\n         - Spheroid\r\n         - Ellipsoid\r\n        \\par Projection parameters\r\n         - lat_0: Latitude of origin (degrees)\r\n         - guam (boolean)\r\n        \\par Example\r\n        \\image html ex_aeqd.gif\r\n    */\r\n    template <typename BGParameters, typename CalculationType, typename Parameters>\r\n    struct aeqd_e_static : public detail::aeqd::base_aeqd_e_static<BGParameters, CalculationType, Parameters>\r\n    {\r\n        inline aeqd_e_static(const Parameters& par) : detail::aeqd::base_aeqd_e_static<BGParameters, CalculationType, Parameters>(par)\r\n        {\r\n            detail::aeqd::setup_aeqd(this->m_par, this->m_proj_parm,\r\n                                     false,\r\n                                     detail::aeqd::base_aeqd_e_static<BGParameters, CalculationType, Parameters>::is_guam);\r\n        }\r\n    };\r\n\r\n    /*!\r\n        \\brief Azimuthal Equidistant 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         - Azimuthal\r\n         - Spheroid\r\n         - Ellipsoid\r\n        \\par Projection parameters\r\n         - lat_0: Latitude of origin (degrees)\r\n         - guam (boolean)\r\n        \\par Example\r\n        \\image html ex_aeqd.gif\r\n    */\r\n    template <typename CalculationType, typename Parameters>\r\n    struct aeqd_s : public detail::aeqd::base_aeqd_s<CalculationType, Parameters>\r\n    {\r\n        inline aeqd_s(const Parameters& par) : detail::aeqd::base_aeqd_s<CalculationType, Parameters>(par)\r\n        {\r\n            detail::aeqd::setup_aeqd(this->m_par, this->m_proj_parm, true, false);\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        template <typename BGP, typename CT, typename P>\r\n        struct static_projection_type<srs::par4::aeqd, srs_sphere_tag, BGP, CT, P>\r\n        {\r\n            typedef aeqd_s<CT, P> type;\r\n        };\r\n        template <typename BGP, typename CT, typename P>\r\n        struct static_projection_type<srs::par4::aeqd, srs_spheroid_tag, BGP, CT, P>\r\n        {\r\n            typedef aeqd_e_static<BGP, CT, P> type;\r\n        };\r\n        //BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::par4::aeqd, aeqd_s, aeqd_e_static)\r\n        //BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::par4::aeqd_guam, aeqd_guam, aeqd_guam)\r\n\r\n        // Factory entry(s)\r\n        template <typename CalculationType, typename Parameters>\r\n        class aeqd_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                    bool const guam = pj_param(par.params, \"bguam\").i != 0;\r\n\r\n                    if (par.es && ! guam)\r\n                        return new base_v_fi<aeqd_e<CalculationType, Parameters>, CalculationType, Parameters>(par);\r\n                    else if (par.es && guam)\r\n                        return new base_v_fi<aeqd_e_guam<CalculationType, Parameters>, CalculationType, Parameters>(par);\r\n                    else\r\n                        return new base_v_fi<aeqd_s<CalculationType, Parameters>, CalculationType, Parameters>(par);\r\n                }\r\n        };\r\n\r\n        template <typename CalculationType, typename Parameters>\r\n        inline void aeqd_init(detail::base_factory<CalculationType, Parameters>& factory)\r\n        {\r\n            factory.add_to_factory(\"aeqd\", new aeqd_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_AEQD_HPP\r\n\r\n", "meta": {"hexsha": "fdfc1b7f81bfd7b634f9888f5179a437d10ee46b", "size": 28247, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/boost/geometry/srs/projections/proj/aeqd.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/aeqd.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/aeqd.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": 43.1251908397, "max_line_length": 135, "alphanum_fraction": 0.5108861118, "num_tokens": 6471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2648479435087974}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <cstdio>\n#include <cstdlib>\n#include <fstream>\n#include <sstream>\n#include <cmath>\n#include <string>\n#include <iostream>\n#include <vector>\n#include <exception>\n#include <GeographicLib/Geodesic.hpp>\n#include <GeographicLib/Constants.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string.hpp>\n#include \"bilinearInterpolation.hpp\"\n#include \"hypoStation.hpp\"\n#include \"h5io.hpp\"\n#include \"blackList.hpp\"\n\nstruct TravelTimeInterpolator\n{\n    double getTime(const double offset, const double depth)\n    {\n        bilin.interpolate(1, &offset, &depth);\n        auto ptr = bilin.getInterpolatedFunctionPointer();\n        return ptr[0];\n    }\n    std::vector<double> getTimes(const std::vector<double> &offsets,\n                                 const std::vector<double> &depths)\n    {\n        if (offsets.size() != depths.size())\n        {\n            throw std::invalid_argument(\"offsets.size() != depths.size()\");\n        }\n        bilin.interpolate(offsets.size(), offsets.data(), depths.data());\n        return bilin.getInterpolatedFunction();\n    }\n    BilinearInterpolation<double> bilin;\n    std::string phaseLabel;\n    std::vector<double> travelTimes;\n    std::vector<double> depths;\n    std::vector<double> offsets;\n};\n\nstruct Receiver\n{\n    std::string network;\n    std::string station;\n    double latitude = 0;\n    double longitude = 0;\n    double depth = 0;\n};\n\nbool operator==(const Receiver &a, const Receiver &b)\n{\n    return (a.network == b.network && a.station == b.station);\n}\n\nstd::vector<Receiver> getReceiverListFromCSV(const std::string &fileName,\n                                             const bool haveHeader = true)\n{\n    std::ifstream infl(fileName);\n    if (!infl){throw std::runtime_error(\"Could not open: \" + fileName);}\n    std::vector<Receiver> receivers;\n    std::string line;\n    std::vector<std::string> split;\n    int lineNumber = 0;\n    while (std::getline(infl, line)) \n    {\n        lineNumber = lineNumber + 1;\n        if (lineNumber == 1 && haveHeader){continue;}\n        //UU,ALT,ENE,ENN,ENZ,01,40.59028,-111.6375,2635.0\n        boost::split(split, line, boost::is_any_of(\",\\n\\t\"),\n                     boost::token_compress_on);\n        Receiver receiver;\n        receiver.network = split[0];\n        receiver.station = split[1];\n        receiver.latitude = std::stod(split[6]);\n        receiver.longitude = std::stod(split[7]);\n        receiver.depth = std::stod(split[8]);\n        bool lnew = true;\n        for (const auto &r : receivers)\n        {\n            if (receiver == r)\n            {\n                lnew = false;\n                break;\n            }\n        }\n        if (lnew){receivers.push_back(receiver);} \n    }\n    infl.close();\n    std::cout << \"Number of receivers: \" << receivers.size() << std::endl; \n    return receivers;\n}\n\nstd::vector<Receiver> getReceiverListFromNodalFile(const std::string &fileName)\n{\n    std::ifstream infl(fileName);\n    if (!infl){throw std::runtime_error(\"Could not open: \" + fileName);}\n    std::vector<Receiver> receivers;\n    std::vector<std::string> split;\n    std::string line;\n    while (std::getline(infl, line))\n    {\n        // -112.02516440 40.75396926 1272.3 001 001 5462 UU001\n        boost::split(split, line, boost::is_any_of(\" ,\\n\\t\"),\n                     boost::token_compress_on);\n        Receiver receiver;\n        receiver.network = \"UU\";\n        receiver.station = split[3];\n        receiver.latitude = std::stod(split[1]);\n        receiver.longitude = std::stod(split[0]);\n        receiver.depth = std::round(std::stod(split[2]));\n//std::cout << receiver.network << \",\" << receiver.station << \",\" << receiver.latitude << \",\" << receiver.longitude << \",\" << receiver.depth << std::endl;\n        if (isBlackListed(receiver.network, receiver.station)){continue;}\n        bool lnew = true;\n        for (const auto &r : receivers)\n        {\n            if (receiver == r)\n            {\n                lnew = false;\n                break;\n            }\n        }\n        if (lnew){receivers.push_back(receiver);}\n    }\n    infl.close();\n    std::cout << \"Number of nodes: \" << receivers.size() << std::endl;\n    return receivers;\n}\n\n/// @brief Creates a travel time table interpolation structure from the\n///        travel time tables computed by GrowClust. \n/// @param[in] fileName   The file name with the travel time table.\n/// @param[in] phaseLabel The phase label (e.g., P or S).\n/// @param[out] interp    This is the travel time with a travel time\n///                       bilinear interpolation method.\nvoid createGrowClustTravelTimeTable(const std::string &fileName,\n                                    const std::string &phaseLabel,\n                                    TravelTimeInterpolator *interp)\n{\n    std::ifstream infl(fileName);\n    if (!infl)\n    {\n        throw std::runtime_error(\"Could not open: \" + fileName);\n    }\n    int lineNumber = 0;\n    std::string line;\n    std::vector<std::string> split;\n    int nDepths = 0;\n    int nDistances = 0;\n    std::vector<double> depths;\n    std::vector<double> offsets;\n    std::vector<double> travelTimes;\n    while (std::getline(infl, line))\n    {\n        lineNumber = lineNumber + 1;\n        if (lineNumber == 1){continue;} // Header\n        // Remove leading blanks and parse\n        boost::algorithm::trim_left(line);\n        boost::split(split, line, boost::is_any_of(\"\\n\\t \"),\n                     boost::token_compress_on);\n        // Read sizes\n        if (lineNumber == 2)\n        {\n            nDistances = std::stoi(split[0]);\n            nDepths = std::stoi(split[1]);\n            offsets.reserve(nDistances);\n            depths.resize(nDepths);\n            travelTimes.resize(nDistances*nDepths, -1);\n            continue;\n        }\n        // Read depths\n        if (lineNumber == 3)\n        {\n            for (int id=0; id<nDepths; ++id)\n            {\n                depths[id] = std::stod(split[id]);\n            }\n            continue;\n       }\n       offsets.push_back(std::stod(split[0]));\n       if (static_cast<int> (split.size() - 1) != nDepths)\n       {\n           throw std::runtime_error(\"Invalid size\");\n       }\n       for (int i=0; i<nDepths; ++i)\n       {\n           auto indx = i*nDistances + offsets.size() - 1;\n           travelTimes.at(indx) = std::stod(split[i+1]);\n       }\n    }\n    infl.close();\n    auto [tmin, tmax]\n        = std::minmax_element(travelTimes.begin(), travelTimes.end());\n    if (*tmin < 0){throw std::runtime_error(\"Failed to unpack ttimes\");}\n    // Create linearly interpolation\n    interp->phaseLabel = phaseLabel;\n    interp->offsets = offsets;\n    interp->depths = depths;\n    interp->travelTimes = travelTimes;\n    interp->bilin.initialize(offsets.size(), offsets.data(),\n                             depths.size(), depths.data(),\n                             travelTimes.size(), travelTimes.data());\n    // Check travel time interpolator works:\n    //std::cout << travelTimes[10*nDistances+12] << \" \"  << interp->getTime(offsets[12], depths[10]) << std::endl;\n}\n\n/// @brief Create a grid in spherical coordinates.\nvoid createGrid(const double lat0, const double lat1, const int nLat,\n                const double lon0, const double lon1, const int nLon,\n                const double z0,   const double z1,   const int nDep,\n                std::vector<double> *lons,\n                std::vector<double> *lats,\n                std::vector<double> *depths)\n{\n    if (nDep < 2 || nLon < 2 || nLat < 2)\n    {\n        throw std::invalid_argument(\"need more than 2 grid points in x, y, z\");\n    }\n    int nPts = nLat*nLon*nDep;\n    std::cout << \"Number of points in grid: \" << nPts << std::endl;\n    auto dLat = (lat1 - lat0)/(nLat - 1);\n    auto dLon = (lon1 - lon0)/(nLon - 1);\n    auto dDep = (z1 - z0)/(nDep - 1);\n    lons->resize(nPts, 0);\n    lats->resize(nPts, 0);\n    depths->resize(nPts, -10);\n    auto lonPtr = lons->data();\n    auto latPtr = lats->data();\n    auto depPtr = depths->data();\n    // x\n    #pragma omp simd collapse(3)\n    for (int iLon=0; iLon<nLon; ++iLon)\n    {\n        // y \n        for (int iLat=0; iLat<nLat; ++iLat)\n        {\n            // z\n            for (int id=0; id<nDep; ++id) \n            {\n                auto indx = iLon*nDep*nLat + iLat*nDep + id; \n                lonPtr[indx] = lon0 + iLon*dLon;\n                latPtr[indx] = lat0 + iLat*dLat;\n                depPtr[indx] = z0   + id*dDep;\n            }\n        }\n    }\n    auto dmin = std::min_element(depths->begin(), depths->end());\n    if (*dmin <=-10){throw std::runtime_error(\"algorithm failure\");}\n}\n\n/// @brief Creates the candidate source points in the grid search.\n/// @param[out] lons     The longitudes in degrees.\n/// @param[out] lats     The latitudes in degrees.\n/// @param[out] depths   The depths in kilometers.\nvoid createSourcePoints(std::vector<double> *lats,\n                        std::vector<double> *lons,\n                        std::vector<double> *depths)\n{\n    double kmPerDeg = 111.195;\n    double deltaCoarse = 4; // 5 km spacing\n    double lat0Coarse = 40.5;\n    double lat1Coarse = 41.0;\n    double lon0Coarse =-112.24;\n    double lon1Coarse =-111.76;\n    double z0Coarse = 1.5; // 1.5 km is sea-level\n    double z1Coarse = 21.5;\n    int nLatCoarse = static_cast<int> (std::round( (lat1Coarse - lat0Coarse)\n                                                  /deltaCoarse*kmPerDeg) );\n    int nLonCoarse = static_cast<int> (std::round( (lon1Coarse - lon0Coarse)\n                                                  /deltaCoarse*kmPerDeg) );\n    int nDepCoarse = static_cast<int> (std::round( (z1Coarse - z0Coarse)\n                                                  /deltaCoarse ));\n \n    double deltaFine = 1.25; // 1 km spacing\n    double lon0Fine =-112.2;\n    double lon1Fine =-111.8;\n    double lat0Fine = 40.6;\n    double lat1Fine = 40.85;\n    double z0Fine = 0;\n    double z1Fine = 18;\n    int nLatFine = static_cast<int> (std::round( (lat1Fine - lat0Fine)\n                                                /deltaFine*kmPerDeg) );\n    int nLonFine = static_cast<int> (std::round( (lon1Fine - lon0Fine)\n                                                /deltaFine*kmPerDeg) );\n    int nDepFine = static_cast<int> (std::round( (z1Fine - z0Fine)\n                                                /deltaFine ));\n\n    std::vector<double> latsCoarse, lonsCoarse, depthsCoarse;\n    createGrid(lat0Coarse, lat1Coarse, nLatCoarse,\n               lon0Coarse, lon1Coarse, nLonCoarse,\n               z0Coarse, z1Coarse, nDepCoarse,\n               &lonsCoarse, &latsCoarse, &depthsCoarse);\n    // Add in Bingham\n    lonsCoarse.push_back(-112.1453);\n    latsCoarse.push_back(40.5162);\n    depthsCoarse.push_back(0);\n    //std::cout << depthsCoarse.size() << std::endl;\n    // Create the fine grid\n    std::vector<double> latsFine, lonsFine, depthsFine;\n    createGrid(lat0Fine, lat1Fine, nLatFine,\n               lon0Fine, lon1Fine, nLonFine,\n               z0Fine,   z1Fine, nDepFine,\n               &lonsFine, &latsFine, &depthsFine);\n    lonsCoarse.insert(std::end(lonsCoarse),\n                      std::begin(lonsFine), std::end(lonsFine));\n    latsCoarse.insert(std::end(latsCoarse),\n                      std::begin(latsFine), std::end(latsFine));\n    depthsCoarse.insert(std::end(depthsCoarse),\n                        std::begin(depthsFine), std::end(depthsFine));\n    //std::cout << depthsCoarse.size() << std::endl;\n    *lons = lonsCoarse;\n    *lats = latsCoarse;\n    *depths = depthsCoarse; \n}\n\n// @brief Compute the source-to-receiver distances.\n/// @param[in] receiverLatitude   The receiver's latitude in degrees.\n/// @param[in] receiverLongitude  The receiver's longitude in degrees.\n/// @param[in] sourceLatitudes    The source latitudes in degrees.\n/// @param[in] sourceLongitudes   The source longitudes in degrees.\n/// @param[out] distances         The source receiver distances in kilometers.\nvoid computeDistances(const double receiverLatitude,\n                      const double receiverLongitude,\n                      const std::vector<double> &sourceLatitudes,\n                      const std::vector<double> &sourceLongitudes,\n                      std::vector<double> *distances)\n{\n    GeographicLib::Geodesic geodesic{GeographicLib::Constants::WGS84_a(),\n                                     GeographicLib::Constants::WGS84_f()};\n    distances->resize(sourceLatitudes.size());\n    auto dPtr = distances->data();\n    for (int i=0; i<static_cast<int> (sourceLatitudes.size()); ++i)\n    {\n        geodesic.Inverse(sourceLatitudes[i], sourceLongitudes[i],\n                         receiverLatitude,   receiverLongitude,\n                         dPtr[i]);\n        dPtr[i] = dPtr[i]*1.e-3; // km\n    }\n}\n\n\nint main()\n{\n    struct TravelTimeInterpolator pTimes;\n    struct TravelTimeInterpolator sTimes;\n/*\n    auto receivers = getReceiverListFromCSV(\"../magna/magna_3c_stations.csv\", true);\n    auto nodes = getReceiverListFromNodalFile(\"../magna/Magna-Locs_2020-SN.txt\");\n    receivers.insert(std::end(receivers), std::begin(nodes), std::end(nodes));\n*/\n    HypoStation stations;\n    stations.read(\"../magna/locate/magna.sta\");\n    std::cout << \"Total number of receivers: \" << stations.networks.size() << std::endl;\n//    std::cout << \"Total number of receivers: \" << receivers.size() << std::endl;\n    createGrowClustTravelTimeTable(\"../magna/TT.wasatch.pg\", \"P\", &pTimes);\n    createGrowClustTravelTimeTable(\"../magna/TT.wasatch.sg\", \"S\", &sTimes);\n    std::vector<double> lons, lats, depths, distances;\n    createSourcePoints(&lats, &lons, &depths);\n    H5IO h5io;\n    h5io.openFileForWriting(\"../magna/travelTimeTables.h5\");\n    h5io.setGeometry(lats.size(), lats.data(), lons.data(), depths.data());\nstd::ofstream locFile(\"locations.txt\");\nstd::ofstream staFile(\"stations.txt\");\n\n    for (int irec=0; irec<static_cast<int> (stations.networks.size()); ++irec)\n    {\n        computeDistances(stations.latitudes[irec], stations.longitudes[irec],\n                         lats, lons, &distances);\n        auto dmax = std::max_element(distances.begin(), distances.end());\n        auto pTravelTimes = pTimes.getTimes(distances, depths);\n        auto sTravelTimes = sTimes.getTimes(distances, depths);\n        auto pmax = std::max_element(pTravelTimes.begin(), pTravelTimes.end());\n        auto smax = std::max_element(sTravelTimes.begin(), sTravelTimes.end());\n        if (irec == 0)\n        {\n           for (int j=0; j<static_cast<int> (lats.size()); ++j)\n           {\n               locFile << lons[j] << \" \" << lats[j] << \" \" << depths[j] << \" \" << distances[j]\n                       << \" \" << pTravelTimes[j] << std::endl;\n           }\n        }\n        staFile << stations.longitudes[irec] << \" \" << stations.latitudes[irec] << std::endl;\n       std::cout << stations.stations[irec] << \" \" << stations.latitudes[irec] << \" \" \n                 << stations.longitudes[irec]\n                 << \" \" << *dmax << \" \" << *pmax << \" \" << *smax << std::endl;\n        h5io.addTravelTimeTable(stations.networks[irec],\n                                stations.stations[irec],\n                                \"P\",\n                                pTravelTimes.size(), pTravelTimes.data());\n        h5io.addTravelTimeTable(stations.networks[irec],\n                                stations.stations[irec],\n                                \"S\",\n                                sTravelTimes.size(), sTravelTimes.data());\n    }\n/*\n    for (int irec=0; irec<static_cast<int> (receivers.size()); ++irec)\n    {\n        computeDistances(receivers[irec].latitude, receivers[irec].longitude,\n                         lats, lons, &distances); \n        auto dmax = std::max_element(distances.begin(), distances.end());\n        auto pTravelTimes = pTimes.getTimes(distances, depths); \n        auto sTravelTimes = sTimes.getTimes(distances, depths);\n        auto pmax = std::max_element(pTravelTimes.begin(), pTravelTimes.end());\n        auto smax = std::max_element(sTravelTimes.begin(), sTravelTimes.end());\nif (irec == 0)\n{\nfor (int j=0; j<lats.size(); ++j)\n{\n   locFile << lons[j] << \" \" << lats[j] << \" \" << distances[j] << \" \" << pTravelTimes[j] << std::endl;\n}\n}\nstaFile << receivers[irec].longitude << \" \" << receivers[irec].latitude << std::endl;\nstd::cout << receivers[irec].station << \" \" << receivers[irec].latitude << \" \" << receivers[irec].longitude << \" \" << *dmax << \" \" << *pmax << \" \" << *smax << std::endl;\n        h5io.addTravelTimeTable(receivers[irec].network,\n                                receivers[irec].station,\n                                \"P\",\n                                pTravelTimes.size(), pTravelTimes.data());\n        h5io.addTravelTimeTable(receivers[irec].network,\n                                receivers[irec].station,\n                                \"S\",\n                                sTravelTimes.size(), sTravelTimes.data());\n    }\n*/\n} \n", "meta": {"hexsha": "07a9011dd2abbe49b050cf8e4acd199287424ea9", "size": 16904, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/magna/ttables.cpp", "max_stars_repo_name": "uofuseismo/massociate", "max_stars_repo_head_hexsha": "18497a1f81d246f76b159da7f47fa3630caf39c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-09T11:16:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T11:16:44.000Z", "max_issues_repo_path": "examples/magna/ttables.cpp", "max_issues_repo_name": "uofuseismo/massociate", "max_issues_repo_head_hexsha": "18497a1f81d246f76b159da7f47fa3630caf39c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-17T21:51:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-17T21:51:33.000Z", "max_forks_repo_path": "examples/magna/ttables.cpp", "max_forks_repo_name": "uofuseismo/massociate", "max_forks_repo_head_hexsha": "18497a1f81d246f76b159da7f47fa3630caf39c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-09T11:16:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T11:16:45.000Z", "avg_line_length": 39.4032634033, "max_line_length": 169, "alphanum_fraction": 0.568208708, "num_tokens": 4343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2648479378924753}}
{"text": "// TODO:\n// 1. init state from file\n// 2. many algo runs\n// 3. save metadata (score)\n// 4. optimize moderator\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <ctime>\n#include <iomanip>\n#include <unordered_map>\n#include <vector>\n#include <algorithm>\n#include <math.h>\n#include <random>\n#include <boost/functional/hash.hpp>\n#include <boost/program_options.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/tokenizer.hpp>\n#include <boost/algorithm/string.hpp>\n\n#include \"schedule.hh\"\n#include \"params.hh\"  \n#include \"utils.hh\"  \n#include \"scorer.hh\"\n\nusing namespace std;\nnamespace po = boost::program_options;\n\n\nvoid usage(const string& name, const string& errmsg) {\n  if (!errmsg.empty()) {\n    cout << \"Error: \" << errmsg << endl << endl;\n  }\n  cout << \"USAGE:\" << endl;\n  cout << \"    \" << name << \" rankings_file\" << endl;\n}\n\nbool parseArgs(int argc, char** argv, Params& params) {\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()\n    (\"help,h\", \"Show help message and exit\")\n    (\"ranking_file,r\", po::value<string>(), \"Rankings CSV file\")\n    (\"results_dir\", po::value<string>()->default_value(\"results\"), \"Directory for saving results\")\n    (\"iterations,i\", po::value<u64>()->default_value(100000), \"Number of iterations\")\n    (\"init_temp\", po::value<double>()->default_value(10.0), \"Initial temperature\")\n    (\"final_temp\", po::value<double>()->default_value(0.00001), \"Final temperature\")\n    (\"timeslots\", po::value<int>()->default_value(18), \"Number of timeslots\")\n    (\"rooms\", po::value<int>()->default_value(9), \"Number of rooms\")\n    (\"room_size\", po::value<int>()->default_value(12), \"Room capacity including speaker\")\n    (\"person_id_col\", po::value<string>()->default_value(\"person_id\"), \"Name of person_id column\")\n    (\"abstract_id_col\", po::value<string>()->default_value(\"abstract_id\"), \"Name of abstract_id column\")\n    (\"score_col\", po::value<string>()->default_value(\"rating\"), \"Name of score column\")\n    (\"input_delimiter\", po::value<string>()->default_value(\",\"), \"Delimiter character of input file\")\n    (\"default_score\", po::value<Score>()->default_value(0), \"Value of empty score\")\n    (\"max_score\", po::value<Score>()->default_value(5), \"Minimum value for single score\")\n    (\"min_score\", po::value<Score>()->default_value(0), \"Maximum value for single score\")\n    (\"score_delta\", po::value<Score>()->default_value(1), \"Delta added per score (to avoid 0 score)\")\n    (\"participation_range\", po::value<u32>()->default_value(2), \"Allowed deviation from mean number of participations per person\")\n    (\"max_presentations\", po::value<u32>()->default_value(3), \"Max number of presentations per abstract\")\n    (\"seed\", po::value<int>(), \"Algorithm random seed (for debugging)\")\n    (\"verbose,v\", \"Verbose mode (for debugging)\")\n    ;\n\n  try {\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n    if (vm.count(\"help\")) {\n      cout << desc << \"\\n\";\n      return false;\n    }\n    setVerboseMode(vm.count(\"verbose\") > 0);\n    params.nTimeslots = vm[\"timeslots\"].as<int>();\n    params.nRooms = vm[\"rooms\"].as<int>();\n    params.roomSize = vm[\"room_size\"].as<int>();\n    params.maxIterations = vm[\"iterations\"].as<u64>();\n    params.initTemp = vm[\"init_temp\"].as<double>();\n    params.finalTemp = vm[\"final_temp\"].as<double>();\n    params.resultsDir = vm[\"results_dir\"].as<string>();\n    params.personIdCol = vm[\"person_id_col\"].as<string>();\n    params.abstractIdCol = vm[\"abstract_id_col\"].as<string>();\n    params.scoreCol = vm[\"score_col\"].as<string>();\n    params.defaultScore = vm[\"default_score\"].as<Score>();\n    params.maxScore = vm[\"max_score\"].as<Score>();\n    params.minScore = vm[\"min_score\"].as<Score>();\n    params.scoreDelta = vm[\"score_delta\"].as<Score>();\n    params.participationRange = vm[\"participation_range\"].as<u32>();\n    params.maxPresentations = vm[\"max_presentations\"].as<u32>();\n    params.maxNormScore = params.scoreDelta + params.maxScore;\n    params.minNormScore = params.scoreDelta + params.minScore;\n    string strDelim = vm[\"input_delimiter\"].as<string>();\n    if (strDelim.size() != 1) {\n      err() << \"input_delimiter should be a single character. Got: \" << strDelim.size() << endl;\n      return false;\n    }\n    params.inputDelimiter = strDelim[0];\n    if (vm.count(\"seed\")) {\n      params.seed = vm[\"seed\"].as<int>();\n    } else {\n      std::random_device rd;\n      params.seed = rd();\n    }\n\n    if (!readRankings(vm[\"ranking_file\"].as<string>(), params))\n      return false;\n\n    params.avgParticipations = round(double(params.nTimeslots * params.nRooms * (params.roomSize - 1)) / params.nPeople);\n    params.minParticipations = ceil(params.avgParticipations - params.participationRange);\n    params.maxParticipations = floor(params.avgParticipations + params.participationRange);\n\n  } catch(po::error& e) {\n    cout << \"Error parsing command line: \" << e.what();\n    return false;\n  }\n\n  return true;\n}\n\nScore maxPotentialScore(const Rankings& rankings) {\n  Score sumScore = 0;\n  for (auto const& x : rankings)\n    sumScore += x;\n  return sumScore;\n}\n\nclass SimAnnealing {\npublic:\n  SimAnnealing(Schedule& sched, const Params& params, Scorer& scorer) :\n    m_sched(sched), m_scorer(scorer), m_params(params), m_iter(0),\n    m_timeslotCapacity(m_params.nRooms * m_params.roomSize), m_bestSched(sched) {}\n\n  bool run() {\n    m_startTime = chrono::system_clock::now();\n    Score maxScore = maxPotentialScore(m_params.rankings);\n    m_bestScore = 0;\n    dbg() << \"maxScore: \" << maxScore << endl;\n    s32 nextOutputSec = 0;\n    m_temperature = m_params.initTemp;\n    for (m_iter = 0; m_iter < m_params.maxIterations; ++m_iter) {\n      if (m_iter % 10000 == 0) {\n        double tempRatio = m_params.finalTemp / m_params.initTemp;\n        m_temperature = m_params.initTemp *\n          (exp(std::log(tempRatio) * (double(m_iter) / m_params.maxIterations)));\n        if (elapsedSecs(m_startTime) >= nextOutputSec) {\n          if (!outputStatus(dbg()))\n            return false;\n          ++nextOutputSec;\n        }\n      }\n      try {\n        oneIteration();\n        if (m_scorer.score() > m_bestScore) {\n          if (!handleNewBest())\n            return false;\n          m_bestScore = m_scorer.score();\n        }\n      } catch(std::exception& e) {\n        cout << \"Error in iter \" << m_iter << \": \" << e.what();\n        return false;\n      }\n    }\n    outputStatus(info());\n    return true;\n  }\n\n  void outputSchedSummary(ostream& s) {\n    s << endl;\n    for (s32 t = 0; t < m_params.nTimeslots; ++t) {\n      Score tScore = 0;\n      s << setw(2) << (t + 1) << \" || \";\n      for (s32 r = 0; r < m_params.nRooms; ++r) {\n        Score rScore = m_scorer.calcRoomScore(t, r);\n        s << setw(3) << m_sched.getAbstractID(t, r) << \" \" << setw(4) << rScore << \" | \";\n        tScore += rScore;\n      }\n      s << tScore << endl;\n    }\n  }\n\n  void outputSchedStats(ostream& s, const Schedule& sched) {\n    // nPeople per number of rated abstracts they got\n    // Score quantiles\n    vector<s32> personParticipations(m_params.nPeople, 0);\n    vector<s32> ratedAbstractsGotPerPerson(m_params.nPeople, 0);\n    vector<s32> abstractPresentations(m_params.nAbstracts, 0);\n    vector<s32> ratingsGotPerAbstract(m_params.nAbstracts, 0);\n    for (s32 t = 0; t < m_params.nTimeslots; ++t) {\n      for (s32 r = 0; r < m_params.nRooms; ++r) {\n        ID abstractID = sched.getAbstractID(t, r);\n        ++abstractPresentations[abstractID];\n        for (s32 s = 1; s < m_params.roomSize; ++s) {\n          ID personID = sched.getID(t, r, s);\n          ++personParticipations[personID];\n          if (getRankingOrig(personID, abstractID, m_params) > 0) {\n            ++ratedAbstractsGotPerPerson[personID];\n            ++ratingsGotPerAbstract[abstractID];\n          }\n        }\n      }\n    }\n    vector<s32> ratedAbstractsPerPerson(m_params.nPeople, 0);\n    vector<s32> ratingsPerAbstract(m_params.nAbstracts, 0);\n    for (ID personID = 0; personID < m_params.nPeople; ++personID) {\n      for (ID abstractID = 0; abstractID < m_params.nAbstracts; ++abstractID) {\n        if (getRankingOrig(personID, abstractID, m_params) > 0) {\n          ++ratedAbstractsPerPerson[personID];\n          ++ratingsPerAbstract[abstractID];\n        }\n      }\n    }\n    s32 unmatchableAbstracts = 0, unmatchablePeople = 0;\n    vector<s32> ratedGotPercentPerPerson(102, 0);\n    vector<s32> ratedGotPercentOfMaxPerPerson(102, 0);\n    for (ID personID = 0; personID < m_params.nPeople; ++personID) {\n      s32 percent = (ratedAbstractsPerPerson[personID] == 0) ? 101 : (\n        (20 * ratedAbstractsGotPerPerson[personID]) / ratedAbstractsPerPerson[personID]) * 5;\n      s32 percentOfMax = (ratedAbstractsPerPerson[personID] == 0) ? 101 : (\n        (20 * ratedAbstractsGotPerPerson[personID]) /\n        min(ratedAbstractsPerPerson[personID], s32(m_params.maxParticipations))) * 5;\n      ++ratedGotPercentPerPerson[percent];\n      ++ratedGotPercentOfMaxPerPerson[percentOfMax];\n      unmatchablePeople += max(0, s32(m_params.minParticipations) - ratedAbstractsPerPerson[personID]);\n    }\n    vector<s32> ratedGotPercentPerAbstract(102, 0);\n    for (ID abstractID = 0; abstractID < m_params.nAbstracts; ++abstractID) {\n      s32 percent = (ratingsPerAbstract[abstractID] == 0) ? 101 : (\n        (20 * ratingsGotPerAbstract[abstractID]) / ratingsPerAbstract[abstractID]) * 5;\n      ++ratedGotPercentPerAbstract[percent];\n      unmatchableAbstracts += max(0, m_params.roomSize - 1 - ratingsPerAbstract[abstractID]);\n    }\n\n    vector<s32> nPeoplePerNParticipations = vectorCount(personParticipations);\n    vector<s32> nPeoplePerNRatedAbstractsGot = vectorCount(ratedAbstractsGotPerPerson);\n    vector<s32> nPeoplePerNRatedAbstracts = vectorCount(ratedAbstractsPerPerson);\n    vector<s32> nAbstractsPerNPresentations = vectorCount(abstractPresentations);\n    vector<s32> nAbstractsPerNRatingsGot = vectorCount(ratingsGotPerAbstract);\n    vector<s32> nAbstractsPerNRatings = vectorCount(ratingsPerAbstract);\n    s32 totalParticipations = m_params.nTimeslots * m_params.nRooms * (m_params.roomSize-1);\n\n    s << \"nPeople:\" << m_params.nPeople;\n    s << \" nAbstracts:\" << m_params.nAbstracts;\n    s << \" nRooms:\" << m_params.nRooms;\n    s << \" nTimeslots:\" << m_params.nTimeslots;\n    s << \" Room size:\" << m_params.roomSize << endl;\n    s << \"nAbstracts ratings:\" << vectorSum(ratedAbstractsPerPerson) << endl;\n    s << \"nAbstracts rated and got:\" << vectorSum(ratedAbstractsGotPerPerson) << endl;\n    s << \"Total participations (excl. presenters): \" << totalParticipations << endl;\n    s << \"Total forced unrated participations (people with less than \" << m_params.minParticipations\n      << \" rankings): \" << unmatchablePeople << \" (max matches: \"\n      << (totalParticipations - unmatchablePeople) << \")\" << endl;\n    s << \"Total forced unrated participations (abstracts with less than \" << (m_params.roomSize - 1)\n      << \" rankings): \" << unmatchableAbstracts << \" (max matches: \"\n      << (totalParticipations - unmatchableAbstracts) << \")\" << endl;\n    s << \"nPeople per number of participations:\";\n    outputVectorCount(s, nPeoplePerNParticipations) << endl;\n    s << \"nPeople per abstracts rated:\";\n    outputVectorCount(s, nPeoplePerNRatedAbstracts) << endl;\n    s << \"nPeople per abstracts rated got:\";\n    outputVectorCount(s, nPeoplePerNRatedAbstractsGot) << endl;\n    s << \"nAbstracts per number of presentations:\";\n    outputVectorCount(s, nAbstractsPerNPresentations) << endl;\n    s << \"nAbstracts per times rated:\";\n    outputVectorCount(s, nAbstractsPerNRatings) << endl;\n    s << \"nAbstracts per times rated and got:\";\n    outputVectorCount(s, nAbstractsPerNRatingsGot) << endl;\n    s << \"nAbstracts per ratings got percent: N/A:\" << ratedGotPercentPerAbstract[101];\n    ratedGotPercentPerAbstract[101] = 0;\n    outputVectorCount(s, ratedGotPercentPerAbstract, \"%\") << endl;\n    s << \"nPeople per ratings got percent: N/A:\" << ratedGotPercentPerPerson[101];\n    ratedGotPercentPerPerson[101] = 0;\n    outputVectorCount(s, ratedGotPercentPerPerson, \"%\") << endl;\n    s << \"nPeople per ratings got of their max percent: N/A:\" << ratedGotPercentOfMaxPerPerson[101];\n    ratedGotPercentOfMaxPerPerson[101] = 0;\n    outputVectorCount(s, ratedGotPercentOfMaxPerPerson, \"%\") << endl;\n  }\n\n  const Schedule& bestSchedule() {\n    m_bestSched.setAllIDs(m_bestSchedule);\n    return m_bestSched;\n  }\n\n  const Schedule& curSchedule() {\n    return m_sched;\n  }\n\nprotected:\n  Schedule& m_sched;\n  Scorer& m_scorer;\n  const Params m_params;\n  u64 m_iter;\n  const s32 m_timeslotCapacity;\n  double m_temperature;\n  Score m_bestScore;\n  vector<ID> m_bestSchedule;\n  Schedule m_bestSched;\n  time_point m_startTime;\n\n  std::string inResultsDir(std::string name) {\n    return (boost::filesystem::path(m_params.resultsDir) / name).c_str();\n  }\n\n  bool handleNewBest() {\n    m_sched.getAllIDs(m_bestSchedule);\n    return true;\n\n  }\n\n  bool saveBest() {\n    if (m_bestSchedule.empty())\n      return true;\n    string schedPath = inResultsDir(\"best_schedule.csv\");\n    ofstream schedFile(schedPath);\n    if (schedFile.bad() || schedFile.fail()) {\n      err() << \"Error opening file '\" << schedPath << \"': \" << strerror(errno) << endl;\n      return false;\n    }\n    m_sched.outputIDs(schedFile, m_bestSchedule);\n\n    string metadataPath = inResultsDir(\"best_schedule.metadata\");\n    ofstream metadataFile(metadataPath);\n    if (metadataFile.bad() || metadataFile.fail()) {\n      err() << \"Error opening file '\" << metadataPath << \"': \" << strerror(errno) << endl;\n      return false;\n    }\n    metadataFile << \"Score: \" << m_scorer.score() << endl;\n    metadataFile << \"Iter: \" << m_iter << endl;\n    metadataFile << \"Temperature: \" << m_temperature << endl;\n    metadataFile << \"Elapsed seconds: \" << elapsedSecs(m_startTime) << endl;\n    outputParams(m_params, metadataFile);\n    outputSchedSummary(metadataFile);\n    outputSchedStats(metadataFile, bestSchedule());\n    return true;    \n  }\n\n  bool oneIteration() {\n    Score curScore = m_scorer.score();\n    s32 t = randInt(m_params.nTimeslots);\n    s32 i1 = randInt(m_params.nPeople), i2 = randInt(m_params.nPeople);\n    if (i2 < i1)\n      swap(i1, i2);\n    if (i1 >= m_timeslotCapacity || i1 == i2)\n      return false;\n    s32 room1 = i1 / m_params.roomSize;\n    s32 seat1 = i1 % m_params.roomSize;\n    ID id1 = m_sched.getID(t, room1, seat1);\n    if (i2 < m_timeslotCapacity) { // Change type 1: swap two seats in time slot\n      s32 room2 = i2 / m_params.roomSize;\n      s32 seat2 = i2 % m_params.roomSize;\n      ID id2 = m_sched.getID(t, room2, seat2);\n      if (room1 == room2 && seat1 > 0 && seat2 > 0)\n        return false;\n      if ((seat1 == 0 && id2 >= m_params.nAbstracts) ||\n          (seat2 == 0 && id1 >= m_params.nAbstracts)) {\n        return false;\n      }\n      m_scorer.prepareSwapChange(t, room1, seat1, t, room2, seat2);\n      if (!swapIfLegal(t, room1, seat1, room2, seat2)) {\n        ASSERT(m_scorer.score() == curScore);\n        return false;\n      }\n      m_scorer.tryChange();\n      // m_scorer.recalcScore();\n      Score newScore = m_scorer.score();\n      if (!shouldAcceptStep(curScore, newScore, m_temperature)) {\n        m_sched.setIDUnsafe(t, room2, seat2, INVALID_ID);\n        m_sched.setIDUnsafe(t, room1, seat1, id1);\n        m_sched.setIDUnsafe(t, room2, seat2, id2);\n        m_scorer.undoChange();\n        // m_scorer.recalcScore();\n        ASSERT(abs(m_scorer.score() - curScore) < (m_params.minNormScore / 1000));\n      }\n    }\n    else {  // Change type 2: Swap seat with a free person in time slot\n      ID id2 = m_sched.getRandomFreePerson(t);\n      if (seat1 == 0 && id2 >= m_params.nAbstracts) {\n        return false;\n      }\n      m_scorer.prepareSetChange(t, room1, seat1, id2);\n      if (!m_sched.setIDIfLegal(t, room1, seat1, id2))\n        return false;\n      m_scorer.tryChange();\n      Score newScore = m_scorer.score();\n      if (!shouldAcceptStep(curScore, newScore, m_temperature)) {\n        m_sched.setIDUnsafe(t, room1, seat1, id1);\n        m_scorer.undoChange();\n        // m_scorer.recalcScore();\n        ASSERT(abs(m_scorer.score() - curScore) < (m_params.minNormScore / 1000));\n      }\n    }\n    return true;\n  }\n\n  bool swapIfLegal(s32 timeslot, s32 room1, s32 seat1, s32 room2, s32 seat2) {\n    ID id1 = m_sched.getID(timeslot, room1, seat1);\n    ID id2 = m_sched.getID(timeslot, room2, seat2);\n    if (!m_sched.setIDIfLegal(timeslot, room2, seat2, INVALID_ID))\n      return false;\n    if (!m_sched.setIDIfLegal(timeslot, room1, seat1, id2)) {\n      m_sched.setIDUnsafe(timeslot, room2, seat2, id2);\n      return false;\n    }\n    if (!m_sched.setIDIfLegal(timeslot, room2, seat2, id1)) {\n      m_sched.setIDUnsafe(timeslot, room1, seat1, id1);\n      m_sched.setIDUnsafe(timeslot, room2, seat2, id2);\n      return false;\n    }\n    return true;\n  }\n\n  vector<s32> vectorCount(const vector<s32>& data) {\n    vector<s32> count(*max_element(begin(data), end(data)) + 1, 0);\n    for (s32 d : data) {\n      ++count[d];\n    }\n    return count;\n  }\n\n  s32 vectorSum(const vector<s32>& data) {\n    s32 sum = 0;\n    for (s32 d : data)\n      sum += d;\n    return sum;\n  }\n\n  ostream& outputVectorCount(ostream& s, const vector<s32>& v, string countSuffix=\"\") {\n    for (s32 i = 0; i < v.size(); ++i) {\n      if (v[i] > 0)\n        s << \" \" << i << countSuffix << \":\" << v[i];\n    }\n    return s;\n  }\n\n  bool outputStatus(ostream& s) {\n    s << \"Iter \" << double(m_iter) << \"/\" << double(m_params.maxIterations)\n      << \" (\" << setprecision(4)\n      << left << (100.0 * m_iter / m_params.maxIterations) << right << \"%) temperature: \"\n      << m_temperature << \" score: \" << m_scorer.score() << \" (dbg:\" << m_scorer.calcScore()\n      << \") best so far:\" << m_bestScore << endl;\n    //outputSchedSummary(s << endl);\n    ASSERT(abs(m_scorer.score() - m_scorer.calcScore()) < (m_params.minNormScore / 1000));\n    return saveBest();\n  }\n\n  bool shouldAcceptStep(Score curScore, Score newScore, double temperature) {\n    if (newScore >= curScore)\n      return true;\n    double normDelta = double(newScore - curScore);\n    return randProb() < exp(normDelta / temperature);\n  }\n};\n\nvoid findSchedule(const Params& params) {\n    outputParams(params, info());\n    dbg() << \"Creating empty schedule\" << endl;\n    Schedule sched = Schedule(params);\n    dbg() << \"Initializing schedule\" << endl;\n    sched.initState();\n    dbg() << \"Initializing scorer\" << endl;\n    SumHappinessScorer scorer(sched, params);\n\n    dbg() << \"Initializing algorithm\" << endl;\n    SimAnnealing sa(sched, params, scorer);\n\n    dbg() << \"Stats:\" << endl;\n    auto& s = dbg();\n    sa.outputSchedStats(s, sa.curSchedule());\n    sa.outputSchedSummary(s);\n    s << \"Score:\" << scorer.score() << endl;\n\n    dbg() << \"Optimizing schedule\" << endl;\n    sa.run();\n//    auto& s = dbg();\n    sa.outputSchedSummary(s);\n\n    SumHappinessScorer scorer2(sched, params);\n    MinHappinessBonusScorer minScorer(sched, params);\n\n    sa.outputSchedStats(s, sa.bestSchedule());\n    s << \"Score:\" << scorer.score() << endl;\n\n    SumScorers sumScorers(scorer2, minScorer);\n    SimAnnealing sa2(sched, params, sumScorers);\n    sa2.run();\n    sa.outputSchedSummary(s);\n    MinHappinessBonusScorer scorer3(sched, params);\n    sa.outputSchedStats(s, sa.bestSchedule());\n    dbg() << \"min person ID: \" << minScorer.calcMinPersonScoreID() << endl;\n    s << \"Score:\" << SumHappinessScorer(sched, params).score() << endl;\n}\n\nint main(int argc, char** argv) {\n  Params params;\n  if (!parseArgs(argc, argv, params))\n    return 2;\n  randSetSeed(params.seed);\n  try {\n    findSchedule(params);\n  } catch (const std::exception& e) {\n    err() << e.what() << '\\n';\n  }\n  return 0;\n}\n\n", "meta": {"hexsha": "596455f7320555d71adb828548751b28bb03295a", "size": 19709, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/main.cc", "max_stars_repo_name": "shygon/alpine_scheduler", "max_stars_repo_head_hexsha": "ff53bbc1d933c8bc80aed2d71f994e8d8c5dd35b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-01T22:41:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-01T22:41:55.000Z", "max_issues_repo_path": "src/main.cc", "max_issues_repo_name": "shygon/alpine_scheduler", "max_issues_repo_head_hexsha": "ff53bbc1d933c8bc80aed2d71f994e8d8c5dd35b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cc", "max_forks_repo_name": "shygon/alpine_scheduler", "max_forks_repo_head_hexsha": "ff53bbc1d933c8bc80aed2d71f994e8d8c5dd35b", "max_forks_repo_licenses": ["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.0277227723, "max_line_length": 130, "alphanum_fraction": 0.6446293571, "num_tokens": 5463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.26484793789247524}}
{"text": "// Copyright 2020 Oscar Higgott\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 \"lemon_mwpm.h\"\n#include <lemon/list_graph.h>\n#include <lemon/matching.h>\n#include <lemon/connectivity.h>\n#include <vector>\n#include <string>\n#include \"matching_graph.h\"\n#include <stdexcept>\n#include <set>\n#include <pybind11/pybind11.h>\n#include <pybind11/numpy.h>\n#include <boost/graph/adjacency_list.hpp>\n\ntypedef lemon::ListGraph UGraph;\ntypedef UGraph::EdgeMap<double> LengthMap;\ntypedef lemon::MaxWeightedPerfectMatching<UGraph,LengthMap> MWPM;\n\n\nconst char * BlossomFailureException::what() const throw() {\n    return \"The Lemon implementation of the blossom algorithm \"\n            \"(lemon::MaxWeightedPerfectMatching) \"\n            \"was unable to find a solution to the minimum-weight \"\n            \"perfect matching problem.\";\n}\n\nMatchingResult::MatchingResult() {}\n\nMatchingResult::MatchingResult(py::array_t<std::uint8_t> correction, double weight)\n    : correction(correction), weight(weight) {}\n\n\nstd::string arr_repr(py::array_t<std::uint8_t> arr) {\n    std::stringstream ss;\n    ss << \"array([\";\n    bool first = true;\n    for (auto i : arr) {\n        if (first){\n            first = false;\n        } else {\n            ss << \", \";\n        }\n        ss << i;\n    }\n    ss << \"], dtype=uint8)\";\n    return ss.str();\n}\n\nstd::string MatchingResult::repr() const {\n    std::stringstream ss;\n    ss << \"pymatching._cpp_mwpm.MatchingResult(correction=\";\n    ss << arr_repr(correction);\n    ss << \", weight=\" << weight << \")\";\n    return ss.str();\n}\n\n\nclass DefectGraph {\n    public:\n        DefectGraph(int num_nodes);\n        void AddEdge(int i, int j, double weight);\n        UGraph g;\n        LengthMap length;\n        int num_nodes;\n};\n\nDefectGraph::DefectGraph(int num_nodes) : num_nodes(num_nodes),\n         length(g)\n{\n    for (int i=0; i<num_nodes; i++){\n        UGraph::Node x;\n        x = g.addNode();\n    }\n}\n\nvoid DefectGraph::AddEdge(int i, int j, double weight){\n    UGraph::Edge e = g.addEdge(g.nodeFromId(i), g.nodeFromId(j));\n    length[e] = weight;\n}\n\n\nMatchingResult ExactMatching(\n    MatchingGraph& graph,\n    const py::array_t<int>& defects,\n    bool return_weight\n    ){\n    MatchingResult matching_result;\n    if (!graph.HasComputedAllPairsShortestPaths()){\n        graph.ComputeAllPairsShortestPaths();\n    }\n    int num_nodes = graph.GetNumNodes();\n\n    auto d = defects.unchecked<1>();\n    std::set<int> defects_set;\n    for (int i=0; i<d.shape(0); i++){\n        if (d(i) >= num_nodes){\n            throw std::invalid_argument(\n            \"Defect id must be less than the number of nodes in the matching graph\"\n            );\n        }\n        defects_set.insert(d(i));\n    }\n    graph.FlipBoundaryNodesIfNeeded(defects_set);\n\n    std::vector<int> defects_vec(defects_set.begin(), defects_set.end());\n\n    int num_defects = defects_vec.size();\n\n    DefectGraph defect_graph(num_defects);\n\n    for (py::size_t i = 0; i<num_defects; i++){\n        for (py::size_t j=i+1; j<num_defects; j++){\n            defect_graph.AddEdge(i, j, -1.0*graph.Distance(\n                defects_vec[i], defects_vec[j]\n                ));\n        }\n    };\n\n    MWPM pm(defect_graph.g, defect_graph.length);\n    bool success = pm.run();\n    if (!success){\n        throw BlossomFailureException();\n    }\n\n    int N = graph.GetNumQubits();\n    auto correction = new std::vector<int>(N, 0);\n    std::set<int> qids;\n    for (py::size_t i = 0; i<num_defects; i++){\n        int j = defect_graph.g.id(pm.mate(defect_graph.g.nodeFromId(i)));\n        if (i<j){\n            std::vector<int> path = graph.ShortestPath(\n                defects_vec[i], defects_vec[j]\n                );\n            for (std::vector<int>::size_type k=0; k<path.size()-1; k++){\n                qids = graph.QubitIDs(path[k], path[k+1]);\n                for (auto qid : qids){\n                    if ((qid != -1) && (qid >= 0) && (qid < N)){\n                        (*correction)[qid] = ((*correction)[qid] + 1) % 2;\n                    }\n                }\n            }\n        }\n    }\n\n    auto capsule = py::capsule(correction, [](void *correction) { delete reinterpret_cast<std::vector<int>*>(correction); });\n    auto corr = py::array_t<int>(correction->size(), correction->data(), capsule);\n\n    if (return_weight) {\n        matching_result.weight = -1*pm.matchingWeight();\n    } else {\n        matching_result.weight = -1.0;\n    }\n\n    matching_result.correction = corr;\n    return matching_result;\n}\n\n\nMatchingResult LocalMatching(\n    MatchingGraph& graph,\n    const py::array_t<int>& defects,\n    int num_neighbours,\n    bool return_weight,\n    int max_attempts\n    ){\n    if (num_neighbours <= 0){\n        throw std::invalid_argument(\"num_neighbours must be greater than zero\");\n    }\n    auto d = defects.unchecked<1>();\n    std::set<int> defects_set;\n    for (int i=0; i<d.shape(0); i++) {\n        defects_set.insert(d(i));\n    }\n    int num_attempts = 0;\n    while (true) {\n        try{\n            return LemonDecodeMatchNeighbourhood(\n                graph,\n                defects_set,\n                num_neighbours,\n                return_weight\n            );\n        } catch (BlossomFailureException& e) {\n            num_attempts++;\n            if (num_neighbours >= defects_set.size() || num_attempts >= max_attempts){\n                throw;\n            } else {\n                num_neighbours *= 2;\n            }\n        }\n    }\n}\n\n\nMatchingResult LemonDecodeMatchNeighbourhood(\n    MatchingGraph& graph,\n    std::set<int>& defects_set,\n    int num_neighbours,\n    bool return_weight\n    ){\n    MatchingResult matching_result;\n\n    int num_nodes = graph.GetNumNodes();\n\n    for (auto d : defects_set){\n        if (d >= num_nodes){\n            throw std::invalid_argument(\n            \"Defect id must be less than the number of nodes in the matching graph\"\n            );\n        }\n    }\n\n    graph.FlipBoundaryNodesIfNeeded(defects_set);\n\n    std::vector<int> defects_vec(defects_set.begin(), defects_set.end());\n    int num_defects = defects_vec.size();\n    std::vector<int> defect_id(num_nodes, -1);\n    for (int i=0; i<num_defects; i++){\n        defect_id[defects_vec[i]] = i;\n    }\n    num_neighbours = std::min(num_neighbours, num_defects-1);\n\n    DefectGraph defect_graph(num_defects);\n\n    std::vector<std::pair<int, double>> neighbours;\n    int j;\n    bool is_in;\n    for (int i=0; i<num_defects; i++){\n        neighbours = graph.GetNearestNeighbours(defects_vec[i], num_neighbours, defect_id);\n        for (const auto &neighbour : neighbours){\n            j = defect_id[neighbour.first];\n            UGraph::Edge FoundEdge = lemon::findEdge(\n                defect_graph.g,\n                defect_graph.g.nodeFromId(i),\n                defect_graph.g.nodeFromId(j));\n            is_in = FoundEdge != lemon::INVALID;\n            if (!is_in && i!=j){\n                defect_graph.AddEdge(i, j, -1.0*neighbour.second);\n            }\n        }\n    }\n\n    MWPM pm(defect_graph.g, defect_graph.length);\n    bool success = pm.run();\n    if (!success){\n        throw BlossomFailureException();\n    }\n\n    int N = graph.GetNumQubits();\n    auto correction = new std::vector<int>(N, 0);\n\n    std::set<int> remaining_defects;\n    for (int i=0; i<num_defects; i++){\n        remaining_defects.insert(i);\n    }\n\n    std::vector<int> path;\n    int i;\n    std::set<int> qids;\n    while (remaining_defects.size() > 0){\n        i = *remaining_defects.begin();\n        remaining_defects.erase(remaining_defects.begin());\n        j = defect_graph.g.id(pm.mate(defect_graph.g.nodeFromId(i)));\n        remaining_defects.erase(j);\n        path = graph.GetPath(defects_vec[i], defects_vec[j]);\n        for (std::vector<int>::size_type k=0; k<path.size()-1; k++){\n            qids = graph.QubitIDs(path[k], path[k+1]);\n            for (auto qid : qids){\n                if ((qid != -1) && (qid >= 0) && (qid < N)){\n                    (*correction)[qid] = ((*correction)[qid] + 1) % 2;\n                }\n            }\n        }\n    }\n    auto capsule = py::capsule(correction, [](void *correction) { delete reinterpret_cast<std::vector<int>*>(correction); });\n    auto corr = py::array_t<int>(correction->size(), correction->data(), capsule);\n\n    if (return_weight) {\n        matching_result.weight = -1*pm.matchingWeight();\n    } else {\n        matching_result.weight = -1.0;\n    }\n    \n    matching_result.correction = corr;\n    return matching_result;\n}", "meta": {"hexsha": "826a7a52935a52de12533255c5921506e5197188", "size": 8960, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pymatching/lemon_mwpm.cpp", "max_stars_repo_name": "jeffdotthompson/PyMatching", "max_stars_repo_head_hexsha": "9190178f5e4c850bbe67b74f7b4623230963ffb1", "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/pymatching/lemon_mwpm.cpp", "max_issues_repo_name": "jeffdotthompson/PyMatching", "max_issues_repo_head_hexsha": "9190178f5e4c850bbe67b74f7b4623230963ffb1", "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/pymatching/lemon_mwpm.cpp", "max_forks_repo_name": "jeffdotthompson/PyMatching", "max_forks_repo_head_hexsha": "9190178f5e4c850bbe67b74f7b4623230963ffb1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-23T22:19:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T22:19:26.000Z", "avg_line_length": 29.8666666667, "max_line_length": 125, "alphanum_fraction": 0.5934151786, "num_tokens": 2241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2645784162676918}}
{"text": "#ifndef N_BODY_TREE_HPP\n#define N_BODY_TREE_HPP\n\n#include \"data.hpp\"\n#include \"logging.hpp\"\n#include \"overloaded.hpp\"\n#include \"space.hpp\"\n#include <array>\n#include <boost/mpi.hpp>\n#include <boost/optional.hpp>\n#include <boost/serialization/access.hpp>\n#include <boost/serialization/nvp.hpp>\n#include <boost/serialization/optional.hpp>\n#include <boost/serialization/variant.hpp>\n#include <boost/serialization/vector.hpp>\n#include <boost/variant.hpp>\n#include <cmath>\n#include <cstddef>\n#include <iostream>\n#include <memory>\n#include <tuple>\n#include <vector>\n\nnamespace n_body::data::tree {\n\nnamespace detail {\n\nconstexpr std::size_t children_number(std::size_t dimension) noexcept {\n  // if exception occurs, process will be terminated\n  return static_cast<std::size_t>(std::pow(2, dimension));\n}\n\n} // namespace detail\n\nenum class NodeType {\n  Inner = 0,\n  Leaf = 1,\n};\n\nstd::ostream &operator<<(std::ostream &os, NodeType node_type) {\n  switch (node_type) {\n  case NodeType::Inner:\n    return os << \"Inner\";\n  case NodeType::Leaf:\n    return os << \"Leaf\";\n  default:\n    return os << \"Invalid node type\";\n  }\n}\n\ntemplate <typename T, std::size_t Dimension> struct BodyTreeInnerNode {\n  inline static constexpr std::size_t CHILDREN_NUMBER =\n      detail::children_number(Dimension);\n\n  using space_type = Space<T, Dimension>;\n\n  std::array<boost::optional<std::size_t>, CHILDREN_NUMBER> children;\n\n  /* serialization */\n  friend class boost::serialization::access;\n  template <typename Archive>\n  void serialize(Archive &ar, const unsigned int /* version */) {\n    ar &BOOST_SERIALIZATION_NVP(children);\n  }\n};\n\ntemplate <typename T, std::size_t Dimension> struct BodyTreeLeafNode {\n  using space_type = Space<T, Dimension>;\n\n  std::size_t body;\n\nprivate:\n  /* serialization */\n  friend class boost::serialization::access;\n  template <typename Archive>\n  void serialize(Archive &ar, const unsigned int /* version */) {\n    ar &BOOST_SERIALIZATION_NVP(body);\n  }\n};\n\ntemplate <typename T, std::size_t Dimension> struct BodyTreeNode {\n  using space_type = Space<T, Dimension>;\n  using inner_node_type = BodyTreeInnerNode<T, Dimension>;\n  using leaf_node_type = BodyTreeLeafNode<T, Dimension>;\n\n  Space<T, Dimension> space;\n  Scalar<T> mass;\n  Vector<T, Dimension> center_of_mass;\n  boost::variant<inner_node_type, leaf_node_type> variant_part;\n\n  NodeType node_type() const {\n    return static_cast<NodeType>(variant_part.which());\n  }\n\nprivate:\n  /* serialization */\n  friend class boost::serialization::access;\n  template <typename Archive>\n  void serialize(Archive &ar, const unsigned int /* version */) {\n    ar &BOOST_SERIALIZATION_NVP(space);\n    ar &BOOST_SERIALIZATION_NVP(mass);\n    ar &BOOST_SERIALIZATION_NVP(center_of_mass);\n    ar &BOOST_SERIALIZATION_NVP(variant_part);\n  }\n};\n\ntemplate <typename T, std::size_t Dimension> struct BodyTree {\n  using node_type = BodyTreeNode<T, Dimension>;\n  using inner_node_type = typename node_type::inner_node_type;\n  using leaf_node_type = typename node_type::leaf_node_type;\n\n  using bodies_type = Bodies<T, Dimension>;\n  using space_type = Space<T, Dimension>;\n\n  std::vector<node_type> tree;\n\n  void push(const bodies_type &bodies, const space_type &root_space,\n            std::size_t body) {\n\n    if (this->tree.empty()) {\n      this->push_new_leaf_node(bodies, body, root_space);\n    } else {\n      // push to the root subtree\n      this->push(0, bodies, body);\n    }\n  }\n\n  void push(std::size_t subtree, const bodies_type &bodies, std::size_t body) {\n    switch (this->node(subtree).node_type()) {\n    case NodeType::Inner: {\n      logging::logger(logging::Level::Trace)\n          << \"push body \" << body << \" to \"\n          << \"inner node \" << subtree << std::endl;\n      data::average_position_by_mass_in_place(\n          this->node(subtree).center_of_mass, this->node(subtree).mass,\n          bodies[body].position, bodies[body].mass);\n\n      auto body_part = space::part_of_space(this->node(subtree).space,\n                                            bodies[body].position);\n      if (auto next = this->child_of_node(subtree, body_part)) {\n        // just push into the node\n        push(*next, bodies, body);\n      } else {\n        // just use the place\n        // root_inner is invalidated by push\n        this->child_of_node(subtree, body_part) = this->push_new_leaf_node(\n            bodies, body,\n            space::subspace(this->node(subtree).space, body_part));\n      }\n      break;\n    }\n    case NodeType::Leaf: {\n      logging::logger(logging::Level::Trace)\n          << \"push body \" << body << \" to \"\n          << \"leaf node \" << subtree << std::endl;\n      if (this->node(subtree).center_of_mass == bodies[body].position) {\n        throw std::runtime_error(\"two points are at exactly same point\");\n      }\n\n      // change the leaf to an inner node\n      this->expand_leaf_to_inner(subtree);\n      // try insert again\n      this->push(subtree, bodies, body);\n      break;\n    }\n    }\n  }\n\n  void expand_leaf_to_inner(std::size_t leaf) {\n\n    auto part = space::part_of_space(this->node(leaf).space,\n                                     this->node(leaf).center_of_mass);\n    auto new_leaf_node = tree.size();\n\n    this->tree.push_back(node_type{\n        space::subspace(this->node(leaf).space, part),\n        this->node(leaf).mass,\n        this->node(leaf).center_of_mass,\n        this->node(leaf).variant_part,\n    }); // node is invalidated\n    inner_node_type inner_node;\n    inner_node.children[part] = new_leaf_node;\n    this->variant_part_of_node(leaf) =\n        inner_node; // finally change the leaf into inner\n\n    logging::logger(logging::Level::Trace)\n        << \"expand leaf \" << leaf << \" to \" << new_leaf_node << std::endl;\n  }\n\n  void merge_tree(const BodyTree<T, Dimension> &other,\n                  const Bodies<T, Dimension> &bodies) {\n    if (this->tree.empty()) {\n      this->tree = other.tree;\n    } else if (other.tree.empty()) {\n      return;\n    } else {\n      this->merge_tree(0, other, 0, bodies);\n    }\n  }\n\n  void merge_tree(std::size_t root, const BodyTree<T, Dimension> &other,\n                  std::size_t other_root, const Bodies<T, Dimension> &bodies) {\n    if (other.tree[other_root].node_type() == NodeType::Leaf) {\n      // if merging a leaf node\n      // just push the body into the place and return\n      this->push(root, bodies, other.body_of_node(other_root));\n    } else {\n      // if merging a inner node\n      if (this->tree[root].node_type() == NodeType::Inner) {\n        // if current node type is inner\n        data::average_position_by_mass_in_place(\n            this->tree[root].center_of_mass, this->tree[root].mass,\n            other.tree[other_root].center_of_mass, other.tree[other_root].mass);\n\n        for (std::size_t i = 0; i < inner_node_type::CHILDREN_NUMBER; ++i) {\n          if (auto other_child = other.child_of_node(other_root, i)) {\n            // if and only if other node's child exists\n            if (auto this_child = this->child_of_node(root, i)) {\n              this->merge_tree(*this_child, other, *other_child, bodies);\n            } else {\n              this->child_of_node(root, i) =\n                  this->copy_tree(other, *other_child);\n            }\n          }\n        }\n      } else {\n        // if current node type is leaf\n        auto body = this->body_of_node(root);\n        copy_tree_in_place(root, other, other_root);\n        this->push(root, bodies, body);\n      }\n    }\n  }\n\n  // copy subtree to the back of the tree vector\n  std::size_t copy_tree(const BodyTree<T, Dimension> &other,\n                        std::size_t other_root) {\n    auto place = this->tree.size();\n    this->tree.push_back(other.node(other_root)); // do copy\n    if (other.node(other_root).node_type() == NodeType::Inner) {\n      for (std::size_t i = 0; i < inner_node_type::CHILDREN_NUMBER; ++i) {\n        if (auto child = other.child_of_node(other_root, i)) {\n          this->child_of_node(place, i) = this->copy_tree(other, *child);\n        }\n      }\n    }\n    return place;\n  }\n\n  // copy subtree into the place of tree vector\n  void copy_tree_in_place(std::size_t place,\n                          const BodyTree<T, Dimension> &other,\n                          std::size_t other_root) {\n    this->node(place) = other.node(other_root); // do copy\n    if (other.node(other_root).node_type() == NodeType::Inner) {\n      for (std::size_t i = 0; i < inner_node_type::CHILDREN_NUMBER; ++i) {\n        if (auto child = other.child_of_node(other_root, i)) {\n          this->child_of_node(place, i) = this->copy_tree(other, *child);\n        }\n      }\n    }\n  }\n\n  // access methods\n  boost::variant<inner_node_type, leaf_node_type> &\n  variant_part_of_node(std::size_t node) {\n    return this->tree[node].variant_part;\n  }\n\n  const boost::variant<inner_node_type, leaf_node_type> &\n  variant_part_of_node(std::size_t node) const {\n    return this->tree[node].variant_part;\n  }\n\n  boost::optional<std::size_t> &child_of_node(std::size_t node,\n                                              std::size_t part) {\n    return boost::get<inner_node_type>(this->tree[node].variant_part)\n        .children[part];\n  }\n\n  const boost::optional<std::size_t> &child_of_node(std::size_t node,\n                                                    std::size_t part) const {\n    return boost::get<inner_node_type>(this->tree[node].variant_part)\n        .children[part];\n  }\n\n  std::size_t &body_of_node(std::size_t node) {\n    return boost::get<leaf_node_type>(this->tree[node].variant_part).body;\n  }\n\n  std::size_t body_of_node(std::size_t node) const {\n    return boost::get<leaf_node_type>(this->tree[node].variant_part).body;\n  }\n\n  node_type &node(std::size_t node) { return this->tree[node]; }\n\n  const node_type &node(std::size_t node) const { return this->tree[node]; }\n\nprivate:\n  std::size_t push_new_leaf_node(const bodies_type &bodies, std::size_t body,\n                                 const Space<T, Dimension> &space) {\n    auto new_node = tree.size();\n    this->tree.push_back(node_type{\n        space,                 // space\n        bodies[body].mass,     // mass\n        bodies[body].position, // center of mass\n        leaf_node_type{\n            body, // body\n        },\n    });\n    logging::logger(logging::Level::Trace)\n        << \"create new leaf node \" << new_node << \" for body \" << body\n        << std::endl;\n    return new_node;\n  }\n\nprivate:\n  /* serialization */\n  friend class boost::serialization::access;\n  template <typename Archive>\n  void serialize(Archive &ar, const unsigned int version) {\n    ar &BOOST_SERIALIZATION_NVP(tree);\n  }\n};\n\n// the root space fo t1 and t2 must be same\ntemplate <typename T, std::size_t Dimension>\nBodyTree<T, Dimension> merge_tree(const BodyTree<T, Dimension> &t1,\n                                  const BodyTree<T, Dimension> &t2,\n                                  const Bodies<T, Dimension> &bodies) {\n  BodyTree<T, Dimension> result;\n  if (t1.tree.empty()) {\n    result.tree = t2.tree;\n  } else if (t2.tree.empty()) {\n    result.tree = t1.tree;\n  } else {\n    result.tree = t1.tree;\n    result.merge_tree(0, t2, 0, bodies);\n  }\n  return result;\n}\n\n// the root space fo t1 and t2 must be same\ntemplate <typename T, std::size_t Dimension>\nBodyTree<T, Dimension> build_tree(const boost::mpi::communicator &comm,\n                                  const Space<T, Dimension> &root_space,\n                                  const Bodies<T, Dimension> &bodies) {\n  communication::Division division(comm, bodies.size());\n\n  BodyTree<T, Dimension> tree;\n  for (auto i = division.begin; i < division.end; ++i) {\n    tree.push(bodies, root_space, i);\n  }\n\n  // merge local trees\n  logging::logger(logging::Level::Trace)\n      << \"start merging local trees\" << std::endl;\n  boost::mpi::all_reduce(comm, boost::mpi::inplace(tree),\n                         [&bodies](const auto &t1, const auto &t2) {\n                           logging::logger(logging::Level::Trace)\n                               << \"merge tree \" << &t1 << \" and \" << &t2\n                               << std::endl;\n                           return merge_tree(t1, t2, bodies);\n                         });\n  return tree;\n}\n\n} // namespace n_body::data::tree\n\n#endif\n", "meta": {"hexsha": "4b0bd9bc6aff235ab4872bce14ddde7fce2a38be", "size": 12205, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/tree.hpp", "max_stars_repo_name": "linyinfeng/n-body", "max_stars_repo_head_hexsha": "e40c859689d76a3f36cd08e072d7ee24685e8be4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-28T15:13:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T15:13:06.000Z", "max_issues_repo_path": "src/tree.hpp", "max_issues_repo_name": "linyinfeng/n-body", "max_issues_repo_head_hexsha": "e40c859689d76a3f36cd08e072d7ee24685e8be4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tree.hpp", "max_forks_repo_name": "linyinfeng/n-body", "max_forks_repo_head_hexsha": "e40c859689d76a3f36cd08e072d7ee24685e8be4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-10T14:01:55.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-10T14:01:55.000Z", "avg_line_length": 32.897574124, "max_line_length": 80, "alphanum_fraction": 0.6234330193, "num_tokens": 3000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878696277512, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2645784162676918}}
{"text": "#include <iostream>\n#include <thread>\n#include <mutex>\n#include <condition_variable>\n#include <atomic>\n\n#include <solver.hpp>\n#include <polynome_reader.hpp>\n#include <args_parser.hpp>\n\n// FloatType for computations can be specified when configuring the project via CMake\n// boost::multiprecision::cpp_dec_float_100 is very accurate but relatively slow in comparison to double\n#ifdef WITH_BOOST_MULTIPRECISION\n#include <boost/multiprecision/cpp_dec_float.hpp>\nusing FloatType = boost::multiprecision::cpp_dec_float_100;\n\n//template Sqrt should be instantiated because we don't want to lose accuracy when using std::sqrt(double)\ntemplate<>\nboost::multiprecision::cpp_dec_float_100 SqrtImpl(const boost::multiprecision::cpp_dec_float_100 &value) {\n    return boost::multiprecision::sqrt(value);\n}\n\n//this template instantiation should be faster than using intermediate stringstream\ntemplate<>\nboost::multiprecision::cpp_dec_float_100 ReadInteger(const char *str) {\n    return boost::multiprecision::cpp_dec_float_100(str);\n}\n#else\nusing FloatType = double;\n#endif\n\n\n// this class holds Producer and Consumer threads and some other entities which is needed for square solving\nclass SquareSolverService\n{\npublic:\n    SquareSolverService(PolynomeReader<FloatType, 3> &reader, bool silent = false, int batchSize = 32):\n        reader(reader),\n        solver(BuildSolver<FloatType>()),\n        kSilent(silent),\n        kBatchSize(batchSize)\n    {\n    }\n    virtual ~SquareSolverService() = default;\n    \n    void Run() {\n        std::thread consumer([&](){ this->ConsumerThread(); });\n        ProducerThread();\n        StopConsumer();\n        consumer.join();\n    }\n\nprivate:\n    PolynomeReader<FloatType, 3> &reader;\n    \n    const std::unique_ptr<EquationSolver<FloatType> > solver;\n    const int kBatchSize = 32;\n    const bool kSilent = false;\n    \n    std::mutex mtx;\n    std::condition_variable cvar;\n    \n    //we don't want to lose too much time because of the overhead of inter-thread synchronization\n    //that's why we send data in batches, which are not too small and not too big\n    using BatchType = std::vector<Polynome<FloatType> >;\n    using BatchPtrType = std::unique_ptr<BatchType>;\n    \n    std::atomic<bool> batchReady = false;\n    BatchPtrType preparedBatch;\n    BatchPtrType formingBatch;\n    \n    void SendBatch() {\n        std::unique_lock<std::mutex> ul(mtx);\n        preparedBatch = std::move(formingBatch);\n        batchReady = true;\n        ul.unlock();\n        cvar.notify_one();\n        \n        //reservation at some extent increases performance here\n        formingBatch = std::make_unique<BatchType>();\n        formingBatch->reserve(kBatchSize);\n        \n        ul.lock();\n        cvar.wait(ul, [&]() { return this->batchReady.load() == false; });\n    }\n    \n    void StopConsumer() {\n        //consumer thread can be stopped via sending empty pointer to batch\n        std::unique_lock<std::mutex> ul(mtx);\n                        \n        batchReady = true;\n        ul.unlock();\n        cvar.notify_one();\n    }\n    \n    void ProducerThread() {\n        formingBatch = std::make_unique<BatchType>();\n        formingBatch->reserve(kBatchSize);\n        \n        Polynome<FloatType> poly;\n        while (reader >> poly) {\n            formingBatch->emplace_back(std::move(poly));\n\n            if (formingBatch->size() >= kBatchSize) {\n                SendBatch();\n            }\n        }\n        \n        //don't forget to process remaining equations\n        if (!formingBatch->empty()) {\n            SendBatch();\n        }\n    }\n    \n    void ConsumerThread() {\n        while (true) {\n            std::unique_lock<std::mutex> ul(mtx);\n            cvar.wait(ul, [&]() { return this->batchReady.load(); });\n            \n            BatchPtrType batch = std::move(preparedBatch);\n            batchReady = false;\n            \n            ul.unlock();\n            cvar.notify_one();\n            \n            //sending empty batch pointer will stop the consumer\n            if (!batch) break;\n            \n            for (const Polynome<FloatType> &poly: (*batch)) {\n                auto res = solver->Solve(poly);\n                //printing results in console can take too much time in comparison to all the algo\n                //so it can be disabled\n                if (!kSilent) {\n                    std::cout << poly << \" => \" << res << std::endl;\n                }\n            }\n        }\n    }\n};\n\n\nint main(int argc, char **argv) {\n    std::cout.precision(std::numeric_limits<FloatType>::digits10);\n    \n    //argc_offset is used to make clear from which point of arguments interesting data is placed\n    int argc_offset;\n    const Configuration config = ParseCmdArgs(argc, argv, argc_offset);\n    \n    clock_t requestStartTime = clock();\n    \n    //interactive mode allows to type coeffs in console in real time\n    PolynomeReader<FloatType, 3> reader = config.interactive ? PolynomeReader<FloatType, 3>(std::cin) : PolynomeReader<FloatType, 3>(argc - argc_offset, argv + argc_offset);\n    SquareSolverService service(reader, config.silent, config.interactive ? 1 : 32);\n    service.Run();\n    \n    clock_t requestEndTime = clock();\n\n    if (config.measurePerformance) {\n        std::cout.precision(6);\n        std::cout << \"request processing time: \" << (requestEndTime - requestStartTime) / double(CLOCKS_PER_SEC) << std::endl;\n    }\n        \n    return 0;\n}\n", "meta": {"hexsha": "6580055ca5672373f1779ea743d3244bb9efda6d", "size": 5391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "678098/square_solver", "max_stars_repo_head_hexsha": "d2c3807d34dda6d0aab17a3d578bdbd4893ef27c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T12:32:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:58:45.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "678098/square_solver", "max_issues_repo_head_hexsha": "d2c3807d34dda6d0aab17a3d578bdbd4893ef27c", "max_issues_repo_licenses": ["MIT"], "max_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": "678098/square_solver", "max_forks_repo_head_hexsha": "d2c3807d34dda6d0aab17a3d578bdbd4893ef27c", "max_forks_repo_licenses": ["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.6727272727, "max_line_length": 173, "alphanum_fraction": 0.6273418661, "num_tokens": 1209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.26455509911581304}}
{"text": "/**\n *    \\file include/geombd/io/parser.hpp\n *    \\author Keny Ordaz\n *    \\version 1.0\n *    \\date 2021\n *\n *    Class to parse a multibody system from URDF\n *    Copyright (c) 2021 Cinvestav\n *    This library is distributed under the MIT License.\n */\n\n#ifndef HEADER_IO_PARSER_HPP\n#define HEADER_IO_PARSER_HPP\n#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <fstream>\n#include <sstream>\n#include <optional>\n#include <memory>\n#include <unordered_map>\n//#include <chrono>\n#include <Eigen/Core>\n//#include \"pugixml.hpp\"\n\nnamespace pugi {\n    class xml_node;\n}\nusing namespace Eigen;\n\n// support {{{1\nRowVectorXd string_to_vector(const std::string& vec, int size=3);\n\nclass Pose\n{\npublic:\n    Pose(): xyz(0, 0, 0), rpy(0, 0, 0) {}\n\n    void init_rpy(double roll, double pitch, double yaw)\n    {\n        auto phi = roll / 2.0;\n        auto the = pitch / 2.0;\n        auto psi = yaw / 2.0;\n        auto sphi = sin(phi);  auto cphi = cos(phi);\n        auto sthe = sin(the);  auto cthe = cos(the);\n        auto spsi = sin(psi);  auto cpsi = cos(psi);\n\n        this->x = sphi * cthe * cpsi - cphi * sthe * spsi;\n        this->y = cphi * sthe * cpsi + sphi * cthe * spsi;\n        this->z = cphi * cthe * spsi - sphi * sthe * cpsi;\n        this->w = cphi * cthe * cpsi + sphi * sthe * spsi;\n\n        this->normalize();\n    };\n    void normalize()\n    {\n        double s = sqrt(this->x * this->x +\n                this->y * this->y +\n                this->z * this->z +\n                this->w * this->w);\n        if (s == 0.0) {\n            this->x = 0.0;\n            this->y = 0.0;\n            this->z = 0.0;\n            this->w = 1.0;\n        } else {\n            this->x /= s;\n            this->y /= s;\n            this->z /= s;\n            this->w /= s;\n        }\n    };\n    double x, y, z, w;\n    RowVector3d xyz;\n    RowVector3d rpy;\n};\n\nclass Axis\n{\npublic:\n    Axis(): xyz(1.0, 0., 0.) {}\n\n    RowVector3d xyz;\n};\n\nclass Inertia { // optional zero inertia\npublic:\n    Inertia(double ixx=0.0, double ixy=0.0, double ixz=0.0, double iyy=0.0, double iyz=0.0, double izz=0.0)\n        : ixx(ixx), ixy(ixy), ixz(ixz), iyy(iyy), iyz(iyz), izz(izz) \n        { setMatrix(ixx, ixy, ixz, iyy, iyz, izz); }\n    void setMatrix(double ixx=0.0, double ixy=0.0, double ixz=0.0, double iyy=0.0, double iyz=0.0, double izz=0.0)\n        { value << ixx, ixy, ixz, ixy, iyy, iyz, ixz, iyz, izz; }\n\n    double ixx;\n    double ixy;\n    double ixz;\n    double iyy;\n    double iyz;\n    double izz;\n    Matrix3d value;\n};\n\nclass Inertial {\npublic:\n    Inertial(): origin(), mass(0.0), inertia(), spatial() {}\n    Inertial(const pugi::xml_node & node);\n    std::string to_string() const {\n        static IOFormat CommaInitFmt(StreamPrecision, DontAlignCols, \", \", \", \", \"\", \"\", \" << \", \";\");\n        static IOFormat OctaveFmt(StreamPrecision, 0, \", \", \";\\n\", \"\", \"\", \"[\", \"]\");\n        std::ostringstream out;\n        out << \"mass (\" << mass << \"),\\n\\t origin[xyz] (\" << origin.xyz.format(CommaInitFmt);\n        out << \"), origin[rpy] (\" << origin.rpy.format(CommaInitFmt) << \"); inertia tensor:\\n\";\n        out << inertia.value.format(OctaveFmt);\n        return out.str();\n \n    }\n    Pose origin;\n    double mass;\n    Inertia inertia;\n    Matrix<double, 6, 6> spatial;\n};\n// support }}}1\n\nclass Element // {{{2\n{\npublic:\n    Element(const std::string& name, int id): name(name), id(id), tree_id(-1) {}\n    std::string name;\n    int id;\n    int tree_id;\n    //~Element() { std::cout << __PRETTY_FUNCTION__ << \"\\n\"; }\n};  // }}}2\n\nclass Body : public Element  // {{{1\n{\npublic:\n    Body(const std::string& name=\"unassigned\", int id=-1);\n    std::string to_string() const;\n    void addChild(int child_id);\n    void addParent(int parent_id);\n    void addJoint(int joint_id);\n    void setInertialProperties(const Inertial& value);\n    bool has_inertial;\n    Inertial inertial_properties;\n    std::vector<int> child_links;\n    std::vector<int> parent_links;\n    std::vector<int> parent_joints;\n    int parent;    \n    std::vector<int> Pre;\n    std::vector<int> Suc;\n};  // }}}1\n\nclass Joint : public Element // {{{1\n{\n    // MAke enum for joint types\npublic:\n    enum joint_type {\n        revolute = 'r',  /*!< The type of the joint is revolute. */\n        prismatic = 'p', /*!< The type of the joint is prismatic. */\n        fixed = 'f',      /*!< The type of the joint is glue. */\n        notype = 'n'      /*!< There is no information about the type. */ \n    };\n\n    Joint(const std::string& name=\"unassigned\", int id=-1): nq(0), Element(name, id) {}\n    Joint(const std::string& name, unsigned int id,\n            const std::string& parent, const std::string& child, const std::string& type)\n        : /*name(name), id(id),*/ predecessor(parent), successor(child)\n        , axis(1.0, 0, 0), Element(name, id) {\n            if (type == \"revolute\") {\n                this->type = Joint::joint_type::revolute;\n            } else if (type == \"prismatic\") {\n                this->type = Joint::joint_type::prismatic;\n            } else if (type == \"fixed\") {\n                this->type = Joint::joint_type::fixed;\n            } else {\n                this->type = Joint::joint_type::notype;\n\n            }\n\n            switch(this->type) {\n            case joint_type::revolute:\n            case joint_type::prismatic:\n                // TODO: check limits\n                setLimit();\n                nq = 1;\n                break;\n            default:\n                nq = 0;// Do nothing?;\n            }\n        }\n    //~Joint() { std::cout << __PRETTY_FUNCTION__ << \"\\n\"; }\n\n    std::string to_string() {\n        std::ostringstream out;\n        out << \"joint \" << name << \", id \" << id << \", type \" << std::string(1, type);\n        out << \", axis \" << axis;\n        if (type == joint_type::revolute || type == joint_type::prismatic) {\n            out << \", limits(\" << upper << \", \" << lower << \", \" << effort << \", \" << velocity << \") \";\n        }\n        out << joint_axis_indicator();\n        out << \"\\t/\" << successor << \"/\" << predecessor << \"/ \";\n        return out.str();\n    }\n\n    std::string joint_axis_indicator() {\n        std::ostringstream out;\n        out << \"[\";\n        switch(type) {\n        case Joint::joint_type::revolute:\n            out << \"⚙\";\n            break;\n        case Joint::joint_type::prismatic:\n            out << \"↕\";\n            break;\n        case Joint::joint_type::fixed:\n            out << \"⚓\";\n            break;\n        case Joint::joint_type::notype:\n            out << \"⦻\";\n        }\n        if (type == joint_type::revolute || type == joint_type::prismatic) {\n            if (axis == RowVector3d(1.0, 0.0, 0.0))\n                out << \"+X\";\n            else if (axis == RowVector3d(0.0, 1.0, 0.0))\n                out << \"+Y\";\n            else if (axis == RowVector3d(-1.0, 0.0, 0.0))\n                out << \"-X\";\n            else if (axis == RowVector3d(0.0, -1.0, 0.0))\n                out << \"-Y\";\n            else if (axis == RowVector3d(0.0, 0.0, 1.0))\n                out << \"+Z\";\n            else if (axis == RowVector3d(0.0, 0.0, -1.0))\n                out << \"-Z\";\n            else\n                out << \"⦻\";\n        }\n\n        out << \"]\";\n        return out.str();\n    }\n\n    void setLimit(double upper=0.0, double lower=0.0, double effort=0.0, double velocity=0.0) {\n        this->upper = upper; this->lower = lower; this->effort = effort; this->velocity = velocity;\n    }\n    \n    void setOrigin(const RowVector3d& xyz, const RowVector3d& rpy) {\n        origin.xyz = xyz;\n        origin.rpy = rpy;\n    }\n\n    void setDampingAndFriction(double damping=0.0, double friction=0.0) {} //FIXME: If required\n    std::string predecessor;\n    std::string successor;\n    joint_type type;\n    RowVector3d axis;\n    Pose origin;\n    double upper, lower, effort, velocity;\n    double damping, friction;\n    int nq;\n};  // }}}1\n\nclass Robot { // {{{1\npublic:\n    Robot(const std::string& name=\"unknown\");\n    void addJoint(const std::string& name, unsigned int id,\n            const std::string& parent, const std::string& child, const std::string& type);\n    void addBody(const std::string& name, unsigned int id);\n    void dump(std::ostream & os);\n    void print_featherstone(std::ostream & os);\n    void print_tree(std::ostream & os, const std::string & prefix, int id, int parent_id=-1);\n    void print_tree(std::ostream & os);\n    int getBodyID(const std::string& frame_name) const;\n    int getJointID(const std::string& name) const;\n    std::shared_ptr<Joint> & operator()(int i) { // robot(j)\n        return joints[i];\n    }\n    std::shared_ptr<Body> & operator[](int i) { // robot[i]\n        return bodies[i];\n    }\n    int getRootBodyID() const;\n    const std::string& getName() const { return name; } \n    static std::optional<std::shared_ptr<Robot>> build_model(const std::string& urdf_file);\n    void add_pre(std::shared_ptr<Body> body, std::shared_ptr<Body> body_s);\n    void add_suc(std::shared_ptr<Body> body, std::shared_ptr<Body> body_p);\n    void build_PSvector( );\n    void build_spatial_inertias( );\nprotected:\n    bool load_from_urdf(const pugi::xml_node & node);\n    void visit_spanning_tree(int root_id);\n    void build_graph();\nprotected:\n    std::string name;\n    std::vector<std::shared_ptr<Joint>> joints;\n    std::vector<std::shared_ptr<Body>> bodies;\n    std::unordered_map<std::string,int> joint_dico;\n    std::unordered_map<std::string,int> joint_pc_dico;\n    std::unordered_map<std::string,int> link_dico;\npublic:\n    std::vector<int> body_l;\n    std::vector<int> body_m;\n    std::vector<int> joint_p;\n    std::vector<int> joint_s;\n    Eigen::RowVectorXi tree_ids;\n    Eigen::RowVectorXi j_tree_ids;\npublic:\n    int nq;\nprivate:\n    int _count;\n};  // }}}1\n\n\n#endif\n", "meta": {"hexsha": "caa95d9e0d0cf6a968953b2c3339599278ce7f3e", "size": 9733, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/geombd/io/parser.hpp", "max_stars_repo_name": "garechav/geombd_crtp", "max_stars_repo_head_hexsha": "c723c0cda841728fcb34fbad634f166e3237d9d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-20T23:11:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T23:11:23.000Z", "max_issues_repo_path": "include/geombd/io/parser.hpp", "max_issues_repo_name": "garechav/geombd_crtp", "max_issues_repo_head_hexsha": "c723c0cda841728fcb34fbad634f166e3237d9d9", "max_issues_repo_licenses": ["MIT"], "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/geombd/io/parser.hpp", "max_forks_repo_name": "garechav/geombd_crtp", "max_forks_repo_head_hexsha": "c723c0cda841728fcb34fbad634f166e3237d9d9", "max_forks_repo_licenses": ["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.0958466454, "max_line_length": 114, "alphanum_fraction": 0.5480324669, "num_tokens": 2786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.264555099115813}}
{"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#ifndef MAIN_HPP\n#define MAIN_HPP\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <stdexcept>\n\n#include <boost/filesystem/operations.hpp>\n#include <boost/thread.hpp>\n\n#include <hashclash/saveload_gz.hpp>\n#include <hashclash/sdr.hpp>\n#include <hashclash/differentialpath.hpp>\n#include <hashclash/booleanfunction.hpp>\n#include <hashclash/timer.hpp>\n\nusing namespace hashclash;\nusing namespace std;\n\nextern boost::mutex mut;\nextern std::string workdir;\nclass path_container;\nvoid dostep(path_container& container);\nbool check_path_collfind(const differentialpath& diffpath, const uint32 mdiff[16]);\n\nstruct connect_bitdata {\n\tuint32 dQt;\n\tuint32 dQtp1;\n\tuint32 dFt;\n\tuint32 dFtp1;\n\tuint32 dFtp2;\n\tuint32 dFtp3;\n\n\tinline bool operator== (const connect_bitdata& r) const {\n\t\treturn dQt==r.dQt && dQtp1==r.dQtp1 && dFt==r.dFt && dFtp1==r.dFtp1 && dFtp2==r.dFtp2 && dFtp3==r.dFtp3;\n\t}\n\tinline bool operator!= (const connect_bitdata& r) const {\n\t\treturn !(*this == r);\n\t}\n\tinline bool operator< (const connect_bitdata& r) const {\n\t\tif (dQt < r.dQt) return true;\n\t\tif (dQt > r.dQt) return false;\n\t\tif (dQtp1 < r.dQtp1) return true;\n\t\tif (dQtp1 > r.dQtp1) return false;\n\t\tif (dFt < r.dFt) return true;\n\t\tif (dFt > r.dFt) return false;\n\t\tif (dFtp1 < r.dFtp1) return true;\n\t\tif (dFtp1 > r.dFtp1) return false;\n\t\tif (dFtp2 < r.dFtp2) return true;\n\t\tif (dFtp2 > r.dFtp2) return false;\n\t\tif (dFtp3 < r.dFtp3) return true;\n\t\treturn false;\n\t}\n};\n\nstruct md5_connect_thread {\n\tmd5_connect_thread(): sw(true), countb(33,0), countbaborted(33,0), countbdepth(33,0)\n\t{}\n\tvoid md5_connect(const vector<differentialpath>& lowerpaths, const differentialpath& upperpath, path_container& container);\n\ttimer sw/*(true)*/;\n\tvector<unsigned> countb/*(33, 0)*/;\n\tvector<unsigned> countbaborted/*(33, 0)*/;\n\tvector<unsigned> countbdepth/*(33, 0)*/;\n\tuint64 count, countall;\n\tvector<unsigned char> isgood;\n\tvector<int> lowerpathsmaxtunnel;\n\n\tunsigned md5_connect_bits(const vector<differentialpath>& lowers, unsigned index, const differentialpath& upper, path_container& container);\n\tconnect_bitdata startbit0;\n\tvector<connect_bitdata> bitdataresults[33];\n\tvector<connect_bitdata> bitdatastart[32];\n\tvector<connect_bitdata> bitdataend[32];\n\tvector<byteconditions>  bitdatanewcond[32];\n\tdifferentialpath newpath2, tmppath;\n\tunsigned bindex[32];\n\n\tvoid connectbits2(const connect_bitdata& in, unsigned b, const differentialpath& lower, const differentialpath& upper);\n\tbf_outcome bfo0, bfo1, bfo2, bfo3;\n\tbf_conditions bfc0, bfc1, bfc2, bfc3;\n\n\tvoid connectbits(const connect_bitdata& in, vector<connect_bitdata>& out, unsigned b, \n\t\tconst differentialpath& lower, const differentialpath& upper, vector<byteconditions>* newconds = 0);\n\tconnect_bitdata result;\n\t//bf_outcome bfo0, bfo1, bfo2, bfo3;\n\t//bf_conditions bfc0, bfc1, bfc2, bfc3;\n\tbitcondition Qt, Qtp1;\n\tbyteconditions newcond;\n\tbool lastdFp1, lastdFp2, lastdFp3;\n\n\tunsigned t;\n\tbooleanfunction* Ft;\n\tbooleanfunction* Ftp1;\n\tbooleanfunction* Ftp2;\n\tbooleanfunction* Ftp3;\n\tvector<uint32> dFt, dFtp1, dFtp2, dFtp3;\n\tuint32 dmt, dmtp1, dmtp2, dmtp3;\n\tuint32 dQtp1, dQtp2, dQtp3, dQtp4;\n\tdifferentialpath newpath;\n\n\tinline bool isinrange(const differentialpath& needle, const differentialpath& haystack, unsigned b)\n\t{\n\t\tfor (unsigned j = t-2; j <= t; ++j)\n\t\t{\n\t\t\tconst wordconditions& nt = needle[j];\n\t\t\tconst wordconditions& ht = haystack[j];\n\t\t\tunsigned k = 0;\n\t\t\twhile (k+7 <= b)\n\t\t\t{\n\t\t\t\tif (nt.bytes[k>>3] != ht.bytes[k>>3])\n\t\t\t\t\treturn false;\n\t\t\t\tk += 8;\n\t\t\t}\n\t\t\tfor (; k <= b; ++k)\n\t\t\t\tif (nt[k] != ht[k])\n\t\t\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\tinline unsigned binary_search_lower_paths(const vector<differentialpath>& lowerpaths,\n\t\t\t\t\t\t\t\t\t   unsigned i, unsigned b)\n\t{\n\t\tconst differentialpath& needle = lowerpaths[i];\n\t\tunsigned l = i, u = lowerpaths.size()-1;\n\t\twhile (l < u)\n\t\t{\n\t\t\tunsigned j = (l+u+1)>>1;\n\t\t\tif (isinrange(needle, lowerpaths[j], b)) {\n\t\t\t\tl = j;\n\t\t\t} else {\n\t\t\t\tu = j-1;\n\t\t\t}\n\t\t}\n\t\treturn l;\n\t}\n};\n\n\nextern vector<uint32> lowdQt, lowdQtm1, lowdQtm2, lowdQtm3;\n\nclass path_container {\npublic:\n\tpath_container()\n\t\t: modn(1), modi(0), inputfilelow(), inputfilehigh()\n\t\t, t(0), noverify(false), noenhancepath(false)\n\t\t, verified(0), verifiedbad(0), bestpathcond(1<<20)\n\t\t, bestmaxtunnel(0), showstats(false), bestmaxcomp(-1000), threads(1)\n\t{\n\t\tfor (unsigned k = 0; k < 16; ++k)\n\t\t\tm_diff[k] = 0;\n\t}\n\n\t~path_container() \n\t{\n\t\tcout << \"Best path: totcompl=\" << bestmaxcomp << \" tottunnel=\" << bestmaxtunnel << \", totcond=\" << bestpathcond << endl;\n\t\tif (!noverify)\n\t\t\tcerr << \"Verified: \" << verifiedbad << \" bad out of \" << verified << endl;\n\t}\n\n\tvoid push_back(const differentialpath& fullpath)\n\t{\n\t\tdifferentialpath pathback = fullpath;\n\t\t//pathback = fullpath;\n\t\ttry {\n\t\tcleanup(pathback);\n\t\t} catch (std::exception& e) {\n\t\t\tcerr << \"hashclash::cleanup(differentialpath&): unknown exception!:\" << endl << e.what() << endl;\n\t\t\tshow_path(pathback, m_diff);\n\t\t}catch (...) {\n\t\t\tcerr << \"hashclash::cleanup(differentialpath&): unknown exception!:\" << endl;\n\t\t\tshow_path(pathback, m_diff);\n\t\t}\n\n//\t\t++verified;\n\t\tif (!noverify && !test_path_fast(pathback, m_diff))\n\t\t{\n\t\t\tmut.lock();\n\t\t\t++verified;\n\t\t\t++verifiedbad;\n\t\t\tmut.unlock();\n\t\t\treturn;\n\t\t}\n\n\t\tunsigned tunnel = totaltunnelstrength(pathback);\n\t\tint tuncompl = tunnel;\n\t\tfor (int k = pathback.tbegin(); k < pathback.tend() && k < 64; ++k)\n\t\t\tif (k >= Qcondstart)\n\t\t\t\ttuncompl -= int(pathback[k].hw());\n\t\tif (tuncompl < bestmaxcomp)\n\t\t\treturn;\n\t\tif (tunnel < bestmaxtunnel)\n\t\t\treturn;\n\t\tunsigned cond = 0;\n\t\tfor (int k = pathback.tbegin(); k < pathback.tend(); ++k)\n\t\t\tcond += pathback[k].hw();\n\t\tif (!(tuncompl >= bestmaxcomp || tunnel >= bestmaxtunnel || cond <= bestpathcond)) \n\t\t\treturn;\n\t\ttry {\n\t\t\tif (!noenhancepath) {\n\t\t\t\tenhancepath(pathback, m_diff);\n\t\t\t\ttunnel = totaltunnelstrength(pathback);\n\t\t\t\ttuncompl = tunnel;\n\t\t\t\tfor (int k = pathback.tbegin(); k < pathback.tend() && k < 64; ++k)\n\t\t\t\t\tif (k >= Qcondstart)\n\t\t\t\t\t\ttuncompl -= int(pathback[k].hw());\n\t\t\t\tif (tuncompl < bestmaxcomp)\n\t\t\t\t\treturn;\n\t\t\t\tif (tunnel < bestmaxtunnel)\n\t\t\t\t\treturn;\n\t\t\t\tcond = 0;\n\t\t\t\tfor (int k = pathback.tbegin(); k < pathback.tend(); ++k)\n\t\t\t\t\tcond += pathback[k].hw();\n\t\t\t\tif (!(tuncompl >= bestmaxcomp || tunnel >= bestmaxtunnel || cond <= bestpathcond))\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t} catch (std::exception&) {\n\t\t\treturn;\n\t\t} catch (...) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (!check_path_collfind(pathback, m_diff)) \n\t\t\treturn;\n\n\t\tif (tuncompl == bestmaxcomp && tunnel == bestmaxtunnel && cond == bestpathcond) {\n\t\t\tmut.lock();\n\t\t\t++verified;\n\t\t\tbestpaths.push_back(pathback);\n\t\t\tif (hw(uint32(bestpaths.size()))==1) {\n\t\t\t\tsave_gz(bestpaths, workdir + \"/bestpaths\", binary_archive);\n\t\t\t\tcout << \"Best paths: \" << bestpaths.size() << endl;\n\t\t\t}\n\t\t\tmut.unlock();\n\t\t\treturn;\n\t\t}\n\t\tif (tuncompl < bestmaxcomp) return;\n\t\tif (tunnel < bestmaxtunnel) return;\n\t\tif (cond > bestpathcond) return;\n\t\tmut.lock();\n\t\t++verified;\n\t\tbestpaths.clear();\n\t\tbestpaths.push_back(pathback);\n\n\t\tbestmaxcomp = tuncompl;\n\t\tbestpathcond = cond;\n\t\tbestpath = pathback;\n\t\tbestmaxtunnel = tunnel;\n\t\tshow_path(pathback, m_diff);\n\t\tdouble p = test_path(pathback, m_diff);\n\t\tcout << \"Best path: totcompl=\" << bestmaxcomp << \" tottunnel=\" << bestmaxtunnel << \", totcond=\" << bestpathcond << \", p=\" << p << endl;\n\t\tsave_gz(pathback, workdir + \"/bestpath_t\" + boost::lexical_cast<string>(tunnel) + \"_c\" + boost::lexical_cast<string>(cond), binary_archive);\n\t\tsave_gz(pathback, workdir + \"/bestpath_new\", binary_archive);\n\t\tsave_gz(bestpaths, workdir + \"/bestpaths_new\", binary_archive);\n\t\ttry { boost::filesystem::rename(workdir + \"/bestpath.bin.gz\", workdir + \"/bestpath_old.bin.gz\"); } catch (...) {}\n\t\ttry { boost::filesystem::rename(workdir + \"/bestpaths.bin.gz\", workdir + \"/bestpaths_old.bin.gz\"); } catch (...) {}\n\t\ttry { boost::filesystem::rename(workdir + \"/bestpath_new.bin.gz\", workdir + \"/bestpath.bin.gz\"); } catch (...) {}\n\t\ttry { boost::filesystem::rename(workdir + \"/bestpaths_new.bin.gz\", workdir + \"/bestpaths.bin.gz\"); } catch (...) {}\n\t\tmut.unlock();\n\t}\n\n\tuint32 m_diff[16];\n\n\tunsigned t;\n\tint Qcondstart;\n\t\n\tbool showstats;\n\tbool noenhancepath;\n\tbool noverify;\n\tunsigned verified, verifiedbad;\n\n\tunsigned modn;\n\tunsigned modi;\n\tstd::string inputfilelow, inputfilehigh;\n\tbool showinputpaths;\n\n\tdifferentialpath bestpath;\n\tvector<differentialpath> bestpaths;\n\tvolatile unsigned bestpathcond;\n\tvolatile unsigned bestmaxtunnel;\n\tvolatile int bestmaxcomp;\n\tint threads;\n};\n\nstruct diffpathlower_less\n\t: public std::binary_function<differentialpath, differentialpath, bool>\n{\n\tbool operator()(const differentialpath& _Left, const differentialpath& _Right) const\n\t{\n\t\tif (_Left.tend() < _Right.tend() || _Left.tbegin() > _Right.tbegin())\n\t\t\treturn true;\n\t\tif (_Left.tend() > _Right.tend() || _Left.tbegin() < _Right.tbegin())\n\t\t\treturn false;\n\t\tif (_Left.path.size() < 3)\n\t\t\tthrow std::runtime_error(\"Lower differential paths of insufficient size\");\n\t\tunsigned t = _Left.tend() - 1;\n\t\tuint32 LdQt   = _Left[t].diff();\n\t\tuint32 RdQt   = _Right[t].diff();\t\t\n\t\tfor (unsigned b = 0; b < 32; ++b)\n\t\t{\n\t\t\tif ((LdQt & (1<<b)) < (RdQt & (1<<b)))\n\t\t\t\treturn true;\n\t\t\tif ((LdQt & (1<<b)) > (RdQt & (1<<b)))\n\t\t\t\treturn false;\n\t\t\tif (_Left[t-2][b] < _Right[t-2][b])\n\t\t\t\treturn true;\n\t\t\tif (_Left[t-2][b] > _Right[t-2][b])\n\t\t\t\treturn false;\n\t\t\tif (_Left[t-1][b] < _Right[t-1][b])\n\t\t\t\treturn true;\n\t\t\tif (_Left[t-1][b] > _Right[t-1][b])\n\t\t\t\treturn false;\n\t\t}\n\t\treturn false;\n\t}\n};\n\nstruct diffpathupper_less\n\t: public std::binary_function<differentialpath, differentialpath, bool>\n{\n\tbool operator()(const differentialpath& _Left, const differentialpath& _Right) const\n\t{\n\t\tif (_Left.tend() < _Right.tend() || _Left.tbegin() > _Right.tbegin())\n\t\t\treturn true;\n\t\tif (_Left.tend() > _Right.tend() || _Left.tbegin() < _Right.tbegin())\n\t\t\treturn false;\n\t\tif (_Left.path.size() < 3)\n\t\t\tthrow std::runtime_error(\"Lower differential paths of insufficient size\");\n\t\tunsigned t = _Left.tbegin() - 1;\n\t\tuint32 LdQtp1   = _Left[t+1].diff();\n\t\tuint32 RdQtp1   = _Right[t+1].diff();\n\t\tif (_Left[t+1].hw() > _Right[t+1].hw()) return true;\n\t\tif (_Left[t+1].hw() < _Right[t+1].hw()) return false;\n\t\tfor (unsigned b = 0; b < 32; ++b)\n\t\t{\n\t\t\tif ((LdQtp1 & (1<<b)) < (RdQtp1 & (1<<b)))\n\t\t\t\treturn true;\n\t\t\tif ((LdQtp1 & (1<<b)) > (RdQtp1 & (1<<b)))\n\t\t\t\treturn false;\n\t\t\tif (_Left[t+2][b] < _Right[t+2][b])\n\t\t\t\treturn true;\n\t\t\tif (_Left[t+2][b] > _Right[t+2][b])\n\t\t\t\treturn false;\n\t\t\tif (_Left[t+3][b] < _Right[t+3][b])\n\t\t\t\treturn true;\n\t\t\tif (_Left[t+3][b] > _Right[t+3][b])\n\t\t\t\treturn false;\n\t\t}\n\t\treturn false;\n\t}\n};\n\n#endif // MAIN_HPP\n", "meta": {"hexsha": "e4eee0d13b7b22c99eaa795326b9de81b0363c55", "size": 11443, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/md5connect/main.hpp", "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/md5connect/main.hpp", "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/md5connect/main.hpp", "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": 30.7607526882, "max_line_length": 142, "alphanum_fraction": 0.6558594774, "num_tokens": 3559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2644753717647745}}
{"text": "#pragma once\n/******************************************************************************\n*\n*   Copyright (c) 2019 AT&T Intellectual Property.\n*   Copyright (c) 2018-2019 Nokia.\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// Standard Includes: ANSI C/C++, MSA, and Third-Party Libraries\n#include <cmath>\n#include <boost/integer/static_log2.hpp>\n\n// Local Includes: Application specific classes, functions, and libraries\n#include \"asn/per/common.hpp\"\n#include \"asn/per/binary_integer.hpp\"\n\nnamespace asn {\nnamespace per {\n\n/***************************************************************************************\n* Encoding of a constrained whole number (X.691 10.5)\n***************************************************************************************/\n\ntemplate<bound_t R, class E = void>\nstruct length_determinant;\n\ntemplate<bound_t R>\nstruct length_determinant<R, std::enable_if_t< R == 0 > > { static constexpr bound_t value = 0; };\n\ntemplate<bound_t R>\nstruct length_determinant<R, std::enable_if_t< R == 1 > > { static constexpr bound_t value = 1; };\n\ntemplate<bound_t R>\nstruct length_determinant<R, std::enable_if_t< (R  > 1) > > { static constexpr bound_t value = boost::static_log2<(R - 1)>::value + 1; };\n\n/***************************************************************************************\n***************************************************************************************/\n\ntemplate <class Range, class V, class Enable = void>\nstruct ConstrainedWholeNumber;\n\n//Bit-field case\ntemplate <class Range, class V>\nstruct ConstrainedWholeNumber<Range, V, std::enable_if_t<(Range::upper_bound < (Range::lower_bound + 255))> >\n{\n\t//non-negative-binary-integer X.691 10.5\n\tstatic void inline run(EncoderCtx& ctx, const V& val)\n\t{\n\t\tTools::bit_accessor::put(static_cast<u8>(val - Range::lower_bound),\n\t\t\tlength_determinant<(Range::upper_bound - Range::lower_bound + 1)>::value,\n\t\t\tctx.refBuffer());\n\t}\n\tstatic V inline run(DecoderCtx& ctx)\n\t{\n\t\treturn Range::lower_bound + Tools::bit_accessor::get(\n\t\t\tlength_determinant<(Range::upper_bound - Range::lower_bound + 1)>::value,\n\t\t\tctx.refBuffer());\n\t}\n};\n\n//One octet case\ntemplate <class Range, class V>\nstruct ConstrainedWholeNumber<Range, V, std::enable_if_t<(Range::upper_bound == (Range::lower_bound + 255))> >\n{\n\t//non-negative-binary-integer X.691 10.5\n\tstatic void inline run(EncoderCtx& ctx, const V& val)\n\t{\n\t\tTools::bit_accessor::padByte(ctx.refBuffer());\n\t\tctx.refBuffer().putByte(static_cast<u8>(val - Range::lower_bound));\n\t}\n\tstatic V inline run(DecoderCtx& ctx)\n\t{\n\t\tV rval = 0;\n\t\tTools::bit_accessor::padByte(ctx.refBuffer());\n\t\tu8 const* data = ctx.refBuffer().getBytes(1);\n\t\tif (data)\n\t\t\trval = Range::lower_bound + data[0];\n\t\treturn rval;\n\t}\n};\n\n//Two octets case\ntemplate <class Range, class V>\nstruct ConstrainedWholeNumber<Range, V, std::enable_if_t<(Range::upper_bound > (Range::lower_bound + 255)) && (Range::upper_bound <= (Range::lower_bound + 65535))> >\n{\n\t//non-negative-binary-integer X.691 10.5\n\tstatic void inline run(EncoderCtx& ctx, const V& v)\n\t{\n\t\tu64 val = static_cast<u64>(v - Range::lower_bound);\n\t\tTools::bit_accessor::padByte(ctx.refBuffer());\n\t\tctx.refBuffer().putByte((u8)(val >> 8));\n\t\tctx.refBuffer().putByte((u8)val);\n\t}\n\tstatic V inline run(DecoderCtx& ctx)\n\t{\n\t\tV rval = 0;\n\t\tTools::bit_accessor::padByte(ctx.refBuffer());\n\t\tu8 const* data = ctx.refBuffer().getBytes(2);\n\t\tif (data) {\n\t\t\trval = data[0];\n\t\t\trval = rval << 8;\n\t\t\trval |= data[1];\n\t\t\trval += Range::lower_bound;\n\t\t}\n\t\treturn rval;\n\t}\n};\n\n//Indefinite case\ntemplate <class Range, class V>\nstruct ConstrainedWholeNumber<Range, V, std::enable_if_t< (Range::upper_bound > Range::lower_bound + 65535) > >\n{\n\tstruct NormalizedValueRange\n\t{\n\t\tusing boundary_type = typename Range::boundary_type;\n\t\tstatic constexpr bool extended = Range::extended;\n\t\tstatic constexpr boundary_type lower_bound = 0;\n\t\tstatic constexpr boundary_type upper_bound = Range::upper_bound - Range::lower_bound;\n\t};\n\t\n\t//non-negative-binary-integer X.691 10.5\n\tstatic void inline run(EncoderCtx& ctx, const V& val)\n\t{\n\t\tNonnegativeBinaryInteger<NormalizedValueRange>::run(val - Range::lower_bound, ctx);\n\t}\n\tstatic V inline run(DecoderCtx& ctx)\n\t{\n\t\tV rval = 0;\n\t\tNonnegativeBinaryInteger<NormalizedValueRange>::run(rval, ctx, false);\n\t\treturn rval + Range::lower_bound;\n\t}\n};\n\n} //namespace per\n} //namespace asn\n", "meta": {"hexsha": "c614998f614e04d374725d4407328ade6cc53cd0", "size": 4959, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/e2/src/ASN1/asn/per/whole_number.hpp", "max_stars_repo_name": "shadansari/onos-cu-cp", "max_stars_repo_head_hexsha": "16cbf4828bd11e4c7319e7a009a26b6f39fde628", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-08-31T08:27:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T10:39:37.000Z", "max_issues_repo_path": "src/e2/src/ASN1/asn/per/whole_number.hpp", "max_issues_repo_name": "shadansari/onos-cu-cp", "max_issues_repo_head_hexsha": "16cbf4828bd11e4c7319e7a009a26b6f39fde628", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-28T23:32:17.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-28T23:32:17.000Z", "max_forks_repo_path": "src/e2/src/ASN1/asn/per/whole_number.hpp", "max_forks_repo_name": "shadansari/onos-cu-cp", "max_forks_repo_head_hexsha": "16cbf4828bd11e4c7319e7a009a26b6f39fde628", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-08-27T23:04:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T01:49:52.000Z", "avg_line_length": 33.5067567568, "max_line_length": 165, "alphanum_fraction": 0.6382335148, "num_tokens": 1261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.26429381076390307}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2020, 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_GEOGRAPHIC_HPP\n#define BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_HPP\n\n\n#include <boost/geometry/strategies/area/geographic.hpp>\n#include <boost/geometry/strategies/convex_hull/geographic.hpp>\n#include <boost/geometry/strategies/envelope/geographic.hpp>\n#include <boost/geometry/strategies/expand/geographic.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n    \nnamespace strategies\n{\n\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 : strategies::detail::geographic_base<Spheroid>\n{\n    using base_t = strategies::detail::geographic_base<Spheroid>;\n\npublic:\n    geographic()\n        : base_t()\n    {}\n\n    explicit geographic(Spheroid const& spheroid)\n        : base_t(spheroid)\n    {}\n\n    // area\n\n    template <typename Geometry>\n    auto area(Geometry const&) const\n    {\n        return strategy::area::geographic\n            <\n                FormulaPolicy, SeriesOrder, Spheroid, CalculationType\n            >(base_t::m_spheroid);\n    }\n\n    // envelope\n\n    template <typename Geometry, typename Box>\n    static auto envelope(Geometry const&, Box const&,\n                         typename util::enable_if_point_t<Geometry> * = nullptr)\n    {\n        return strategy::envelope::spherical_point();\n    }\n\n    template <typename Geometry, typename Box>\n    static auto envelope(Geometry const&, Box const&,\n                         typename util::enable_if_multi_point_t<Geometry> * = nullptr)\n    {\n        return strategy::envelope::spherical_multipoint();\n    }\n\n    template <typename Geometry, typename Box>\n    static auto envelope(Geometry const&, Box const&,\n                         typename util::enable_if_box_t<Geometry> * = nullptr)\n    {\n        return strategy::envelope::spherical_box();\n    }\n\n    template <typename Geometry, typename Box>\n    auto envelope(Geometry const&, Box const&,\n                  typename util::enable_if_segment_t<Geometry> * = nullptr) const\n    {\n        return strategy::envelope::geographic_segment\n            <\n                FormulaPolicy, Spheroid, CalculationType\n            >(base_t::m_spheroid);\n    }\n\n    template <typename Geometry, typename Box>\n    auto envelope(Geometry const&, Box const&,\n                  typename util::enable_if_polysegmental_t<Geometry> * = nullptr) const\n    {\n        return strategy::envelope::geographic\n            <\n                FormulaPolicy, Spheroid, CalculationType\n            >(base_t::m_spheroid);\n    }\n\n    // expand\n\n    template <typename Box, typename Geometry>\n    static auto expand(Box const&, Geometry const&,\n                       typename util::enable_if_point_t<Geometry> * = nullptr)\n    {\n        return strategy::expand::spherical_point();\n    }\n\n    template <typename Box, typename Geometry>\n    static auto expand(Box const&, Geometry const&,\n                       typename util::enable_if_box_t<Geometry> * = nullptr)\n    {\n        return strategy::expand::spherical_box();\n    }\n\n    template <typename Box, typename Geometry>\n    auto expand(Box const&, Geometry const&,\n                typename util::enable_if_segment_t<Geometry> * = nullptr) const\n    {\n        return strategy::expand::geographic_segment\n            <\n                FormulaPolicy, Spheroid, CalculationType\n            >(base_t::m_spheroid);\n    }\n};\n\n\n} // namespace strategies\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_HPP\n", "meta": {"hexsha": "9cbaa714b2a901f97fc254a50e8e99b517497ad3", "size": 3833, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/strategies/geographic.hpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/geometry/strategies/geographic.hpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "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/strategies/geographic.hpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9781021898, "max_line_length": 87, "alphanum_fraction": 0.6548395513, "num_tokens": 851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.2642937998909209}}
{"text": "#include <cstdio>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <unistd.h>\n#include <time.h>\n#include <stdio.h>\n#include <set>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/pending/disjoint_sets.hpp>\n#include <boost/graph/incremental_components.hpp> \n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/filtered_graph.hpp>\n\nusing namespace std;\n\n/* CROCO - Complete Redundant Orthology Clusters */\nnamespace boost {\n\tenum vertex_component_t { vertex_component = 111 };\n\tBOOST_INSTALL_PROPERTY(vertex, component);\n}\nusing namespace boost;\n\ntypedef map<string, int> GeneID;\ntypedef map<string, int> stringcounts;\ntypedef map<int, string> invGeneID;\ntypedef set<string> setstring;\ntypedef set<int> setint;\ntemplate <typename ComponentMap>\nstruct vertexComponent {\n\t\n\tvertexComponent() {}\n\t\n\tvertexComponent(ComponentMap component, int f_component) : m_component(component), m_f_component(f_component) {}\n\t\n\ttemplate <typename Vertex>\n\tbool operator()(const Vertex& v) const {\n\t\treturn (get(m_component, v) == m_f_component);\n\t}\n\t\n\tComponentMap m_component;\n\tint m_f_component;\n};\n\n/* MAIN */\nint main(int argc, char* argv[]) {\n\t/* USAGE */\n\tif (argc != 2) {\n\t\tstd::cerr << \"Usage: \" << argv[0] << \" genelinks (results to STDOUT)\" << std::endl;\n\t\texit(1);\n\t}\n\t\n\t/* DECLARATIONS */\n\tchar      line[200];\n\tchar      scanL[20];\n\tchar      scanR[20];\n\t\n\tint lico = 0;\n\tGeneID ids;\n\tinvGeneID name;\n\tint runningid = 0;\n\t\n\ttypedef adjacency_list<vecS, vecS, undirectedS, property<vertex_component_t, int> > Graph;\n\t\n\ttypedef property_map<Graph, vertex_component_t>::type ComponentMap;\n\ttypedef filtered_graph<Graph, keep_all,\tvertexComponent<ComponentMap> > FilteredGraph;\n\t\n\tgraph_traits < Graph >::vertex_iterator vi, vi_end;\n\tgraph_traits < Graph >::out_edge_iterator oei, oei_end;\n\tgraph_traits < FilteredGraph >::vertex_iterator fvi, fvi_end;\n\tgraph_traits < FilteredGraph >::out_edge_iterator foei, foei_end;\n\t\n\tGraph * g;\n\tFilteredGraph * fg;\n\t\n\tg = new Graph;\n\t\n\t// READ LINK FILE and add edges\n\tstd::ifstream linkFile(argv[1]);\n\tif (linkFile.fail()) {\n\t\tstd::cerr << \"Error: could not read from file \" << argv[1] << std::endl;\n\t\texit(1);\n\t}\n\tstd::cerr << \"Reading gene links \" << argv[1] << std::endl;\n\twhile (!linkFile.eof()) {\n\t\tlinkFile.getline(line, 200);\n\t\tif (linkFile.eof()) break;\n\t\t\n\t\tif (++lico % 1000 == 0) std::cerr << \"\\r\" << lico;\n\t\tsscanf(line, \"%s%s\", scanL, scanR);\n\t\tstring scanLstring = string(scanL);\n\t\tstring scanRstring = string(scanR);\n\t\t\n\t\tif (ids.find(scanLstring) == ids.end()) {\n\t\t\tids.insert(pair<string,int>(scanLstring,++runningid));\n\t\t\tname.insert(pair<int,string>(runningid,scanLstring));\n\t\t}\n\t\tif (ids.find(scanRstring) == ids.end()) {\n\t\t\tids.insert(pair<string,int>(scanRstring,++runningid));\n\t\t\tname.insert(pair<int,string>(runningid,scanRstring));\n\t\t}\n\t\t// add edge\n\t\tadd_edge(ids.find(scanLstring)->second, ids.find(scanRstring)->second, *g);\n\t}\n\tlinkFile.close();\n\tcerr << \"\\r\" << lico << \" gene pairs read\" << std::endl;\n\t\n\t\n\t//// SHOW GRAPH\n\t/*\tstd::cerr<<std::endl<<\"Graph out-edges:\"<<std::endl;\n\t for (tie(vi, vi_end) = vertices(*g); vi != vi_end; ++vi) {\n\t std::cerr<<name[*vi] << \" \" << *vi <<\" outedges - \";\n\t for(tie(oei, oei_end)=out_edges(*vi, *g); oei != oei_end; ++oei) {\n\t std::cerr<<name[source(*oei, *g)]<<\"<->\"<<name[target(*oei, *g)]<<\"  \";\n\t }\n\t std::cerr<<std::endl;\n\t }\n\t std::cerr<<std::endl;\n\t */\t//// SHOW GRAPH\n\t\n\tint numComponents = connected_components(*g, get(vertex_component, *g));\n\t\n\tstd::cerr<<\"Graph has \"<<numComponents<<\" components.\"<<std::endl;\n\n\n\tstring familyprefix = \"GF\";\n\n\tint connex = 0;\n\tint compo = numComponents;\n\tint clusterNumber = 0;\n\tfor(int i=0; i<numComponents; i++) {\n\t\tif (--compo % 100 == 0) std::cerr << \"\\r\" << compo << \" \";\n\t\tkeep_all efilter;\n\t\tvertexComponent<ComponentMap> vfilter(get(vertex_component, *g), i);\n\t\tfg = new FilteredGraph(*g, efilter, vfilter);\n\t\t\n\t\t\n\t\t//std::cerr<<\"Filtered graph (component \"<<i<<\") \";\n\n\t\tsetstring Genes;\n\t\tint elements = 0;\n\t\tfor (tie(fvi, fvi_end) = vertices(*fg); fvi != fvi_end; ++fvi) {\n\t\t\tGenes.insert(name[*fvi]);\n\t\t\t++elements;\n\t\t}\n\t\t// printing\n\t\t++connex;\n\t\tif (elements > 1 && elements == Genes.size()) {\n\t\t\t++clusterNumber;\n\t\t\tfor (setstring::const_iterator it = Genes.begin(); it != Genes.end(); ++it) {\n\t\t\t\tstd::cout << familyprefix << clusterNumber << \"\\t\" << *it << std::endl;\n\t\t\t}\n\t\t}\n\t\telse std::cerr << \"D'oh!\" << endl;\n\n\t\tdelete fg;\n\t\tfg = NULL;\n\t}\n\t\n\tstd::cerr << \"\\rFound \" << clusterNumber << \" (\" << connex << \") connected components (gene families).\"<<std::endl;\n\t\n\tdelete g;\n\tg = NULL;\n\t\n\treturn EXIT_SUCCESS;\n\t\n\t\n\t\n} // END OF MAIN\n\n", "meta": {"hexsha": "bc1b544c9186b3b38c246ef19e8ca1b2307c1ca2", "size": 4739, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/croc/main.cpp", "max_stars_repo_name": "preciserobot/rex", "max_stars_repo_head_hexsha": "91b58e22ea45b56b01a2cdd2ea63b253c9edc467", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/croc/main.cpp", "max_issues_repo_name": "preciserobot/rex", "max_issues_repo_head_hexsha": "91b58e22ea45b56b01a2cdd2ea63b253c9edc467", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/croc/main.cpp", "max_forks_repo_name": "preciserobot/rex", "max_forks_repo_head_hexsha": "91b58e22ea45b56b01a2cdd2ea63b253c9edc467", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.08, "max_line_length": 116, "alphanum_fraction": 0.6568896392, "num_tokens": 1374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.26424934071595463}}
{"text": "//\n// SPDX-License-Identifier: BSD-3-Clause\n// Copyright Contributors to the OpenEXR Project.\n//\n\n// clang-format off\n\n#include <Python.h>\n#include <boost/python.hpp>\n#include <boost/python/make_constructor.hpp>\n#include <boost/format.hpp>\n#include <ImathVec.h>\n#include \"PyImath.h\"\n#include \"PyImathMathExc.h\"\n#include \"PyImathEuler.h\"\n#include \"PyImathDecorators.h\"\n#include \"PyImathExport.h\"\n#include \"PyImathOperators.h\"\n\n// XXX incomplete array wrapping, docstrings missing\n\nnamespace PyImath {\ntemplate<> const char *PyImath::EulerfArray::name() { return \"EulerfArray\"; }\ntemplate<> const char *PyImath::EulerdArray::name() { return \"EulerdArray\"; }\n}\n\nnamespace PyImath {\nusing namespace boost::python;\nusing namespace IMATH_NAMESPACE;\n\ntemplate <class T> struct EulerName { static const char *value; };\ntemplate<> const char *EulerName<float>::value  = \"Eulerf\";\ntemplate<> const char *EulerName<double>::value = \"Eulerd\";\n\ntemplate <class T>\nstatic std::string nameOfOrder(typename IMATH_NAMESPACE::Euler<T>::Order order)\n{\n    switch(order)\n    {\n        case IMATH_NAMESPACE::Euler<T>::XYZ:\n            return \"EULER_XYZ\";\n        case IMATH_NAMESPACE::Euler<T>::XZY:\n            return \"EULER_XZY\";\n        case IMATH_NAMESPACE::Euler<T>::YZX:\n            return \"EULER_YZX\";\n        case IMATH_NAMESPACE::Euler<T>::YXZ:\n            return \"EULER_YXZ\";\n        case IMATH_NAMESPACE::Euler<T>::ZXY:\n            return \"EULER_ZXY\";\n        case IMATH_NAMESPACE::Euler<T>::ZYX:\n            return \"EULER_ZYX\";\n        case IMATH_NAMESPACE::Euler<T>::XZX:\n            return \"EULER_XZX\";\n        case IMATH_NAMESPACE::Euler<T>::XYX:\n            return \"EULER_XYX\";\n        case IMATH_NAMESPACE::Euler<T>::YXY:\n            return \"EULER_YXY\";\n        case IMATH_NAMESPACE::Euler<T>::YZY:\n            return \"EULER_YZY\";\n        case IMATH_NAMESPACE::Euler<T>::ZYZ:\n            return \"EULER_ZYZ\";\n        case IMATH_NAMESPACE::Euler<T>::ZXZ:\n            return \"EULER_ZXZ\";\n        case IMATH_NAMESPACE::Euler<T>::XYZr:\n            return \"EULER_XYZr\";\n        case IMATH_NAMESPACE::Euler<T>::XZYr:\n            return \"EULER_XZYr\";\n        case IMATH_NAMESPACE::Euler<T>::YZXr:\n            return \"EULER_YZXr\";\n        case IMATH_NAMESPACE::Euler<T>::YXZr:\n            return \"EULER_YXZr\";\n        case IMATH_NAMESPACE::Euler<T>::ZXYr:\n            return \"EULER_ZXYr\";\n        case IMATH_NAMESPACE::Euler<T>::ZYXr:\n            return \"EULER_ZYXr\";\n        case IMATH_NAMESPACE::Euler<T>::XZXr:\n            return \"EULER_XZXr\";\n        case IMATH_NAMESPACE::Euler<T>::XYXr:\n            return \"EULER_XYXr\";\n        case IMATH_NAMESPACE::Euler<T>::YXYr:\n            return \"EULER_YXYr\";\n        case IMATH_NAMESPACE::Euler<T>::YZYr:\n            return \"EULER_YZYr\";\n        case IMATH_NAMESPACE::Euler<T>::ZYZr:\n            return \"EULER_ZYZr\";\n        case IMATH_NAMESPACE::Euler<T>::ZXZr:\n            return \"EULER_ZXZr\";\n        default:\n            break;\n    }\n    \n    return \"\";\n}\n\ntemplate <class T>\nstatic std::string Euler_str(const Euler<T> &e)\n{\n    std::stringstream stream;\n    stream << EulerName<T>::value << \"(\" << e.x << \", \" << e.y << \", \" << e.z << \", \" \n           << nameOfOrder<T> (e.order()) << \")\";\n    return stream.str();\n}\n\n// Non-specialized repr is same as str\ntemplate <class T>\nstatic std::string Euler_repr(const Euler<T> &e)\n{\n    return Euler_str(e);\n}\n\n// Specialization for float to full precision\ntemplate <>\nstd::string Euler_repr(const Euler<float> &e)\n{\n    return (boost::format(\"%s(%.9g, %.9g, %.9g, %s)\")\n                        % EulerName<float>::value\n                        % e.x % e.y % e.z\n                        % nameOfOrder<float>(e.order()).c_str()).str();\n}\n\n// Specialization for double to full precision\ntemplate <>\nstd::string Euler_repr(const Euler<double> &e)\n{\n    return (boost::format(\"%s(%.17g, %.17g, %.17g, %s)\")\n                        % EulerName<double>::value\n                        % e.x % e.y % e.z\n                        % nameOfOrder<double>(e.order()).c_str()).str();\n}\n\n\ntemplate <class T>\nstatic bool\nequal(const Euler<T> &e0, const Euler<T> &e1)\n{\n    if(e0.x == e1.x && e0.y == e1.y && e0.z == e1.z && (e0.order())==(e1.order()))\n        return true;\n    else\n        return false;\n}\n\ntemplate <class T>\nstatic bool\nnotequal(const Euler<T> &e0, const Euler<T> &e1)\n{\n    if(e0.x != e1.x || e0.y != e1.y || e0.z != e1.z || (e0.order()) != (e1.order()))\n    {\n        return true;\n    }\n    else\n        return false;\n}\n\ntemplate <class T>\nstatic IMATH_NAMESPACE::Vec3 <int> getAngleOrder(Euler <T> &euler)\n{\n    int i, j, k;\n    euler.angleOrder(i, j, k);\n    return IMATH_NAMESPACE::Vec3 <int> (i, j, k);\n}\n\ntemplate <class T>\nstatic void\nsetXYZTuple(Euler<T> &euler, const tuple &t)\n{\n    MATH_EXC_ON;\n    Vec3<T> v;\n    if(t.attr(\"__len__\")() == 3)\n    {\n        v.x = extract<T>(t[0]);\n        v.y = extract<T>(t[1]);\n        v.z = extract<T>(t[2]); \n        \n        euler.setXYZVector(v);\n    }\n    else\n        throw std::invalid_argument (\"Color3 expects tuple of length 3\");    \n}\n\n// needed to convert Eulerf::Order to Euler<T>::Order\ntemplate <class T>\nstatic typename Euler<T>::Order interpretOrder(typename IMATH_NAMESPACE::Eulerf::Order order)\n{\n    typename Euler<T>::Order o = Euler<T>::XYZ;\n    switch(order)\n    {\n        case IMATH_NAMESPACE::Eulerf::XYZ:\n        {\n            o = Euler<T>::XYZ;\n        }break;\n        case IMATH_NAMESPACE::Eulerf::XZY:\n        {\n            o = Euler<T>::XZY;\n        }break;\n        case IMATH_NAMESPACE::Eulerf::YZX:\n        {\n            o = Euler<T>::YZX;\n        }break;\n        case IMATH_NAMESPACE::Eulerf::YXZ:\n        {\n            o = Euler<T>::YXZ;\n        }break;\n        case IMATH_NAMESPACE::Eulerf::ZXY:\n        {\n            o = Euler<T>::ZXY;\n        }break;\n        case IMATH_NAMESPACE::Eulerf::ZYX:\n        {\n            o = Euler<T>::ZYX;\n        }break;\n        case IMATH_NAMESPACE::Eulerf::XZX:\n        {\n            o = Euler<T>::XZX;\n        }break;\n        case IMATH_NAMESPACE::Eulerf::XYX:\n        {\n            o = Euler<T>::XYX;\n        }break;\n        case IMATH_NAMESPACE::Eulerf::YXY:\n        {\n            o = Euler<T>::YXY;\n        }break;\n        case IMATH_NAMESPACE::Eulerf::YZY:\n        {\n            o = Euler<T>::YZY;\n        }break;\n        case IMATH_NAMESPACE::Eulerf::ZYZ:\n        {\n            o = Euler<T>::ZYZ;\n        }break;\n        case IMATH_NAMESPACE::Eulerf::ZXZ:\n        {\n            o = Euler<T>::ZXZ;\n        }break;\n        case IMATH_NAMESPACE::Eulerf::XYZr:\n        {\n            o = Euler<T>::XYZr;\n        }break;\n        case IMATH_NAMESPACE::Eulerf::XZYr:\n        {\n            o = Euler<T>::XZYr;\n        }break;\n        case IMATH_NAMESPACE::Eulerf::YZXr:\n        {\n            o = Euler<T>::YZXr;\n        }break;\n        case IMATH_NAMESPACE::Eulerf::YXZr:\n        {\n            o = Euler<T>::YXZr;\n        }break;\n        case IMATH_NAMESPACE::Eulerf::ZXYr:\n        {\n            o = Euler<T>::ZXYr;\n        }break;\n        case IMATH_NAMESPACE::Eulerf::ZYXr:\n        {\n            o = Euler<T>::ZYXr;\n        }break;\n        case IMATH_NAMESPACE::Eulerf::XZXr:\n        {\n            o = Euler<T>::XZXr;\n        }break;\n        case IMATH_NAMESPACE::Eulerf::XYXr:\n        {\n            o = Euler<T>::XYXr;\n        }break;\n        case IMATH_NAMESPACE::Eulerf::YXYr:\n        {\n            o = Euler<T>::YXYr;\n        }break;\n        case IMATH_NAMESPACE::Eulerf::YZYr:\n        {\n            o = Euler<T>::YZYr;\n        }break;\n        case IMATH_NAMESPACE::Eulerf::ZYZr:\n        {\n            o = Euler<T>::ZYZr;\n        }break;\n        case IMATH_NAMESPACE::Eulerf::ZXZr:\n        {\n            o = Euler<T>::ZXZr;\n        }break;            \n        default:\n            break;\n    }\n    \n    return o;\n}\n\n// needed to convert Eulerf::Axis to Euler<T>::Axis\ntemplate <class T>\nstatic typename Euler<T>::Axis interpretAxis(typename IMATH_NAMESPACE::Eulerf::Axis axis)\n{\n    if (axis == IMATH_NAMESPACE::Eulerf::X)\n        return Euler<T>::X;\n    else if (axis == IMATH_NAMESPACE::Eulerf::Y)\n        return Euler<T>::Y;\n    else\n        return Euler<T>::Z;\n}\n\ntemplate <class T>\nstatic Euler<T> *\neulerConstructor1(const Vec3<T> &v, typename IMATH_NAMESPACE::Eulerf::Order order)\n{\n    typename Euler<T>::Order o = interpretOrder<T>(order);\n    return new Euler<T>(v, o);\n}\n\ntemplate <class T>\nstatic Euler<T> *\neulerConstructor1a(const Vec3<T> &v)\n{\n    return eulerConstructor1 (v, IMATH_NAMESPACE::Eulerf::Default);\n}\n\ntemplate <class T>\nstatic Euler<T> *\neulerConstructor1b(const Vec3<T> &v, int iorder)\n{\n    typename Euler<T>::Order o = typename Euler<T>::Order (iorder);\n    return new Euler<T>(v, o);\n}\n\ntemplate <class T>\nstatic Euler<T> *\neulerConstructor2(T i, T j, T k, typename IMATH_NAMESPACE::Eulerf::Order order)\n{\n    typename Euler<T>::Order o = interpretOrder<T>(order);\n    return new Euler<T>(i, j, k, o);\n}\n\ntemplate <class T>\nstatic Euler<T> *\neulerConstructor2a(T i, T j, T k)\n{\n    return eulerConstructor2 (i, j, k, IMATH_NAMESPACE::Eulerf::Default);\n}\n\ntemplate <class T>\nstatic Euler<T> *\neulerConstructor2b(T i, T j, T k, int iorder)\n{\n    typename Euler<T>::Order o = typename Euler<T>::Order (iorder);\n    return new Euler<T>(i, j, k, o);\n}\n\ntemplate <class T>\nstatic Euler<T> *\neulerConstructor3(const Matrix33<T> &mat, typename IMATH_NAMESPACE::Eulerf::Order order)\n{\n    typename Euler<T>::Order o = interpretOrder<T>(order);\n    return new Euler<T>(mat, o);\n}\n\ntemplate <class T>\nstatic Euler<T> *\neulerConstructor3a(const Matrix33<T> &mat)\n{\n    return eulerConstructor3 (mat, IMATH_NAMESPACE::Eulerf::Default);\n}\n\ntemplate <class T>\nstatic Euler<T> *\neulerConstructor3b(const Matrix33<T> &mat, int iorder)\n{\n    typename Euler<T>::Order o = typename Euler<T>::Order (iorder);\n    return new Euler<T>(mat, o);\n}\n\ntemplate <class T>\nstatic Euler<T> *\neulerConstructor4(const Matrix44<T> &mat, typename IMATH_NAMESPACE::Eulerf::Order order)\n{\n    typename Euler<T>::Order o = interpretOrder<T>(order);\n    return new Euler<T>(mat, o);\n}\n\ntemplate <class T>\nstatic Euler<T> *\neulerConstructor4a(const Matrix44<T> &mat)\n{\n    return eulerConstructor4 (mat, IMATH_NAMESPACE::Eulerf::Default);\n}\n\ntemplate <class T>\nstatic Euler<T> *\neulerConstructor4b(const Matrix44<T> &mat, int iorder)\n{\n    typename Euler<T>::Order o = typename Euler<T>::Order (iorder);\n    return new Euler<T>(mat, o);\n}\n\ntemplate <class T>\nstatic Euler<T> *\neulerConstructor5(typename IMATH_NAMESPACE::Eulerf::Order order)\n{\n    typename Euler<T>::Order o = interpretOrder<T>(order);\n    return new Euler<T>(o);\n}\n\ntemplate <class T>\nstatic Euler<T> *\neulerConstructor5a()\n{\n    typename Euler<T>::Order o = interpretOrder<T>(IMATH_NAMESPACE::Eulerf::Default);\n    return new Euler<T>(o);\n}\n\ntemplate <class T>\nstatic Euler<T> *\neulerConstructor5b(int iorder)\n{\n    typename Euler<T>::Order o = typename Euler<T>::Order (iorder);\n    return new Euler<T>(o);\n}\n\ntemplate <class T>\nstatic Euler<T> *\neulerConstructor6(T x, T y, T z)\n{\n    return new Euler<T>(Vec3<T>(x,y,z));\n}\n\ntemplate <class T>\nstatic Euler<T> *\neulerConstructor7(const Quat<T> &quat, typename IMATH_NAMESPACE::Eulerf::Order order)\n{\n    Euler<T> *e = eulerConstructor5<T>(order);\n    e->extract(quat);\n    return e;\n}\n\ntemplate <class T>\nstatic Euler<T> *\neulerConstructor7a(const Quat<T> &quat)\n{\n    return eulerConstructor7(quat, IMATH_NAMESPACE::Eulerf::Default);\n}\n\ntemplate <class T>\nstatic Euler<T> *\neulerConstructor7b(const Quat<T> &quat, int iorder)\n{\n    Euler<T> *e = eulerConstructor5b<T>(iorder);\n    e->extract(quat);\n    return e;\n}\n\ntemplate <class T, class S>\nstatic Euler<T> *\neulerConversionConstructor(const Euler<S> &euler)\n{\n    MATH_EXC_ON;\n    Euler<T> *e = new Euler<T>;\n    *e = euler;\n    return e;\n}\n\ntemplate <class T>\nstatic void\neulerMakeNear(Euler<T> &euler, Euler<T> &target)\n{\n    MATH_EXC_ON;\n    euler.makeNear (target);\n}\n\ntemplate <class T>\nstatic void\neulerSetOrder(Euler<T> &euler, typename IMATH_NAMESPACE::Eulerf::Order order)\n{\n    typename Euler<T>::Order o = interpretOrder<T>(order);\n    euler.setOrder (o);\n}\n \ntemplate <class T>\nstatic void\neulerSet(Euler<T> &euler, IMATH_NAMESPACE::Eulerf::Axis axis, int relative, int parityEven, int firstRepeats)\n{\n    MATH_EXC_ON;\n    typename Euler<T>::Axis a = interpretAxis<T>(axis);\n    euler.set (a, relative, parityEven, firstRepeats);\n}\n\ntemplate <class T>\nstatic void \nextract1(Euler<T> &euler, const Matrix33<T> &m)\n{\n    MATH_EXC_ON;\n    euler.extract(m);\n}\n\ntemplate <class T>\nstatic void \nextract2(Euler<T> &euler, const Matrix44<T> &m)\n{\n    MATH_EXC_ON;\n    euler.extract(m);\n}\n\ntemplate <class T>\nstatic void \nextract3(Euler<T> &euler, const Quat<T> &q)\n{\n    MATH_EXC_ON;\n    euler.extract(q);\n}\n\ntemplate <class T>\nstatic Matrix33<T>\ntoMatrix33(Euler<T> &euler)\n{\n    MATH_EXC_ON;\n    return euler.toMatrix33();\n}\n\ntemplate <class T>\nstatic Matrix44<T>\ntoMatrix44(Euler<T> &euler)\n{\n    MATH_EXC_ON;\n    return euler.toMatrix44();\n}\n\ntemplate <class T>\nstatic Quat<T>\ntoQuat(Euler<T> &euler)\n{\n    MATH_EXC_ON;\n    return euler.toQuat();\n}\n\ntemplate <class T>\nstatic Vec3<T>\ntoXYZVector(Euler<T> &euler)\n{\n    MATH_EXC_ON;\n    return euler.toXYZVector();\n}\n\ntemplate <class T>\nclass_<Euler<T>,bases<IMATH_NAMESPACE::Vec3<T> > >\nregister_Euler()\n{\n    class_<Euler<T>,bases<Vec3<T> > > euler_class(EulerName<T>::value,EulerName<T>::value,init<Euler<T> >(\"copy construction\"));\n    euler_class\n        .def(init<>(\"imath Euler default construction\"))\n        .def(\"__init__\", make_constructor(eulerConstructor1<T>))\n        .def(\"__init__\", make_constructor(eulerConstructor1a<T>))\n        .def(\"__init__\", make_constructor(eulerConstructor1b<T>))\n        .def(\"__init__\", make_constructor(eulerConstructor2<T>))\n        .def(\"__init__\", make_constructor(eulerConstructor2a<T>))\n        .def(\"__init__\", make_constructor(eulerConstructor2b<T>))\n        .def(\"__init__\", make_constructor(eulerConstructor3<T>),\n             \"Euler-from-matrix construction assumes, but does\\n\"\n             \"not verify, that the matrix includes no shear or\\n\"\n             \"non-uniform scaling.  If necessary, you can fix\\n\"\n             \"the matrix by calling the removeScalingAndShear()\\n\"\n             \"function.\\n\")\n        .def(\"__init__\", make_constructor(eulerConstructor3a<T>))\n        .def(\"__init__\", make_constructor(eulerConstructor3b<T>))\n        .def(\"__init__\", make_constructor(eulerConstructor4<T>))\n        .def(\"__init__\", make_constructor(eulerConstructor4a<T>))\n        .def(\"__init__\", make_constructor(eulerConstructor4b<T>))\n        .def(\"__init__\", make_constructor(eulerConstructor5<T>))\n        .def(\"__init__\", make_constructor(eulerConstructor5a<T>))\n        .def(\"__init__\", make_constructor(eulerConstructor5b<T>))\n        .def(\"__init__\", make_constructor(eulerConstructor6<T>))\n        .def(\"__init__\", make_constructor(eulerConstructor7<T>))\n        .def(\"__init__\", make_constructor(eulerConstructor7a<T>))\n        .def(\"__init__\", make_constructor(eulerConstructor7b<T>))\n        .def(\"__init__\", make_constructor(eulerConversionConstructor<T, float>))\n        .def(\"__init__\", make_constructor(eulerConversionConstructor<T, double>))\n        \n        .def(\"angleOrder\", &getAngleOrder<T>, \"angleOrder() set the angle order\")\n        \n        .def(\"frameStatic\", &Euler<T>::frameStatic, \n             \"e.frameStatic() -- returns true if the angles of e\\n\"\n             \"are measured relative to a set of fixed axes,\\n\"\n             \"or false if the angles of e are measured relative to\\n\"\n             \"each other\\n\")\n            \n        .def(\"initialAxis\", &Euler<T>::initialAxis, \n             \"e.initialAxis() -- returns the initial rotation\\n\"\n             \"axis of e (EULER_X_AXIS, EULER_Y_AXIS, EULER_Z_AXIS)\")\n        \n        .def(\"initialRepeated\", &Euler<T>::initialRepeated,\n             \"e.initialRepeated() -- returns 1 if the initial\\n\"\n             \"rotation axis of e is repeated (for example,\\n\"\n             \"e.order() == EULER_XYX); returns 0 if the initial\\n\"\n             \"rotation axis is not repeated.\\n\")\n             \n        .def(\"makeNear\", &eulerMakeNear<T>,\n             \"e.makeNear(t) -- adjusts Euler e so that it\\n\"\n             \"represents the same rotation as before, but the\\n\"\n             \"individual angles of e differ from the angles of\\n\"\n             \"t by as little as possible.\\n\"\n             \"This method might not make sense if e.order()\\n\"\n             \"and t.order() are different\\n\")\n        \n        .def(\"order\", &Euler<T>::order,\n             \"e.order() -- returns the rotation order in e\\n\"\n             \"(EULER_XYZ, EULER_XZY, ...)\")\n        \n        .def(\"parityEven\", &Euler<T>::parityEven, \n             \"e.parityEven() -- returns the parity of the\\n\"\n             \"axis permutation of e\\n\")\n        \n        .def(\"set\", &eulerSet<T>,\n             \"e.set(i,r,p,f) -- sets the rotation order in e\\n\"\n             \"according to the following flags:\\n\"\n             \"\\n\"\n             \"   i   initial axis (EULER_X_AXIS,\\n\"\n             \"       EULER_Y_AXIS or EULER_Z_AXIS)\\n\"\n             \"\\n\"\n             \"   r   rotation angles are measured relative\\n\"\n             \"       to each other (r == 1), or relative to a\\n\"\n             \"       set of fixed axes (r == 0)\\n\"\n             \"\\n\"\n             \"   p   parity of axis permutation is even (r == 1)\\n\"\n             \"       or odd (r == 0)\\n\"\n             \"\\n\"\n             \"   f   first rotation axis is repeated (f == 1)\\n\"\n             \"\tor not repeated (f == 0)\\n\")\n        \n        .def(\"setOrder\", &eulerSetOrder<T>,\n             \"e.setOrder(o) -- sets the rotation order in e\\n\"\n             \"to o (EULER_XYZ, EULER_XZY, ...)\")\n             \n        .def(\"setXYZVector\", &Euler<T>::setXYZVector,\n             \"e.setXYZVector(v) -- sets the three rotation\\n\"\n             \"angles in e to v[0], v[1], v[2]\")\n        .def(\"setXYZVector\", &setXYZTuple<T>)\n        \n        .def(\"extract\", &extract1<T>,\n             \"e.extract(m) -- extracts the rotation component\\n\"\n             \"from 3x3 matrix m and stores the result in e.\\n\"\n             \"Assumes that m does not contain shear or non-\\n\"\n             \"uniform scaling.  If necessary, you can fix m\\n\"\n             \"by calling m.removeScalingAndShear().\")\n        \n        .def(\"extract\", &extract2<T>,\n             \"e.extract(m) -- extracts the rotation component\\n\"\n             \"from 4x4 matrix m and stores the result in e.\\n\"\n             \"Assumes that m does not contain shear or non-\\n\"\n             \"uniform scaling.  If necessary, you can fix m\\n\"\n             \"by calling m.removeScalingAndShear().\")\n        \n        .def(\"extract\", &extract3<T>,\n             \"e.extract(q) -- extracts the rotation component\\n\"\n             \"from quaternion q and stores the result in e\")            \n        \n        .def(\"toMatrix33\", &toMatrix33<T>, \"e.toMatrix33() -- converts e into a 3x3 matrix\\n\")\n        \n        .def(\"toMatrix44\", &toMatrix44<T>, \"e.toMatrix44() -- converts e into a 4x4 matrix\\n\")\n        \n        .def(\"toQuat\", &toQuat<T>, \"e.toQuat() -- converts e into a quaternion\\n\")\n        \n        .def(\"toXYZVector\", &toXYZVector<T>, \n             \"e.toXYZVector() -- converts e into an XYZ\\n\"\n             \"rotation vector\")\n        .def(\"__str__\", &Euler_str<T>)\n        .def(\"__repr__\", &Euler_repr<T>)\n        \n        .def(\"__eq__\", &equal<T>)\n        .def(\"__ne__\", &notequal<T>)\n        ;\n    \n    // fill in the Euler scope\n    {\n        scope euler_scope(euler_class);\n        enum_<typename Euler<T>::Order> euler_order(\"Order\");\n        euler_order\n            .value(\"XYZ\",Euler<T>::XYZ)\n            .value(\"XZY\",Euler<T>::XZY)\n            .value(\"YZX\",Euler<T>::YZX)\n            .value(\"YXZ\",Euler<T>::YXZ)\n            .value(\"ZXY\",Euler<T>::ZXY)\n            .value(\"ZYX\",Euler<T>::ZYX)\n            .value(\"XZX\",Euler<T>::XZX)\n            .value(\"XYX\",Euler<T>::XYX)\n            .value(\"YXY\",Euler<T>::YXY)\n            .value(\"YZY\",Euler<T>::YZY)\n            .value(\"ZYZ\",Euler<T>::ZYZ)\n            .value(\"ZXZ\",Euler<T>::ZXZ)\n            .value(\"XYZr\",Euler<T>::XYZr)\n            .value(\"XZYr\",Euler<T>::XZYr)\n            .value(\"YZXr\",Euler<T>::YZXr)\n            .value(\"YXZr\",Euler<T>::YXZr)\n            .value(\"ZXYr\",Euler<T>::ZXYr)\n            .value(\"ZYXr\",Euler<T>::ZYXr)\n            .value(\"XZXr\",Euler<T>::XZXr)\n            .value(\"XYXr\",Euler<T>::XYXr)\n            .value(\"YXYr\",Euler<T>::YXYr)\n            .value(\"YZYr\",Euler<T>::YZYr)\n            .value(\"ZYZr\",Euler<T>::ZYZr)\n            .value(\"ZXZr\",Euler<T>::ZXZr)\n\n            // don't export these, they're not really part of the public interface\n            //.value(\"Legal\",Euler<T>::Legal)\n            //.value(\"Min\",Euler<T>::Min)\n            //.value(\"Max\",Euler<T>::Max)\n\n            // handle Default seperately since boost sets up a 1-1 mapping for enum values\n            //.value(\"Default\",Euler<T>::Default)\n            .export_values()\n            ;\n        // just set it to the XYZ value manually\n        euler_scope.attr(\"Default\") = euler_scope.attr(\"XYZ\");\n\n        enum_<typename Euler<T>::Axis>(\"Axis\")\n            .value(\"X\",Euler<T>::X)\n            .value(\"Y\",Euler<T>::Y)\n            .value(\"Z\",Euler<T>::Z)\n            .export_values()\n            ;\n\n        enum_<typename Euler<T>::InputLayout>(\"InputLayout\")\n            .value(\"XYZLayout\",Euler<T>::XYZLayout)\n            .value(\"IJKLayout\",Euler<T>::IJKLayout)\n            .export_values()\n            ;\n    }\n\n    decoratecopy(euler_class);\n\n    return euler_class;\n}\n\n// XXX fixme - template this\n// really this should get generated automatically...\n\n/*\ntemplate <class T,int index>\nstatic FixedArray<T>\nEulerArray_get(FixedArray<IMATH_NAMESPACE::Euler<T> > &qa)\n{\n    return FixedArray<T>( &(qa[0].r)+index, qa.len(), 4*qa.stride());\n}\n*/\n\ntemplate <class T>\nstatic FixedArray<IMATH_NAMESPACE::Euler<T> > *\nEulerArray_eulerConstructor7a(const FixedArray<IMATH_NAMESPACE::Quat<T> > &q)\n{\n    MATH_EXC_ON;\n    size_t len = q.len();\n    FixedArray<IMATH_NAMESPACE::Euler<T> >* result = new FixedArray<IMATH_NAMESPACE::Euler<T> >(len);\n    for (size_t i = 0; i < len; ++i) {\n        (*result)[i].extract(q[i]);\n    }\n    return result;\n}\n\ntemplate <class T>\nstatic FixedArray<IMATH_NAMESPACE::Euler<T> > *\nEulerArray_eulerConstructor8a(const FixedArray<IMATH_NAMESPACE::Vec3<T> >& v)\n{\n    MATH_EXC_ON;\n    size_t len = v.len();\n    FixedArray<IMATH_NAMESPACE::Euler<T> >* result = new FixedArray<IMATH_NAMESPACE::Euler<T> >(len);\n\n    for (size_t i = 0; i < len; ++i)\n        (*result)[i] = Euler<T>(v[i]);\n\n    return result;\n}\n\ntemplate <class T>\nstatic FixedArray<IMATH_NAMESPACE::Euler<T> > *\nEulerArray_eulerConstructor9a(const FixedArray<IMATH_NAMESPACE::Vec3<T> >& v, typename IMATH_NAMESPACE::Eulerf::Order order)\n{\n    MATH_EXC_ON;\n    size_t len = v.len();\n    FixedArray<IMATH_NAMESPACE::Euler<T> >* result = new FixedArray<IMATH_NAMESPACE::Euler<T> >(len);\n\n    typename Euler<T>::Order o = interpretOrder<T>(order);\n    for (size_t i = 0; i < len; ++i)\n        (*result)[i] = Euler<T>(v[i], o);\n\n    return result;\n}\n\ntemplate <class T>\nstatic FixedArray<IMATH_NAMESPACE::Vec3<T> >\nEulerArray_toXYZVector(const FixedArray<IMATH_NAMESPACE::Euler<T> >& e)\n{\n    MATH_EXC_ON;\n    size_t len = e.len();\n    FixedArray<IMATH_NAMESPACE::Vec3<T> > result(len, UNINITIALIZED);\n    for (size_t i = 0; i < len; ++i)\n        result[i] = e[i].toXYZVector();\n    return result;\n}\n\ntemplate <class T>\nstatic FixedArray<IMATH_NAMESPACE::Quat<T> >\nEulerArray_toQuat(const FixedArray<IMATH_NAMESPACE::Euler<T> >& e)\n{\n    MATH_EXC_ON;\n    size_t len = e.len();\n    FixedArray<IMATH_NAMESPACE::Quat<T> > result(len, UNINITIALIZED);\n    for (size_t i = 0; i < len; ++i)\n        result[i] = e[i].toQuat();\n    return result;\n}\n\n\ntemplate <class T>\nclass_<FixedArray<IMATH_NAMESPACE::Euler<T> > >\nregister_EulerArray()\n{\n    class_<FixedArray<IMATH_NAMESPACE::Euler<T> > > eulerArray_class = FixedArray<IMATH_NAMESPACE::Euler<T> >::register_(\"Fixed length array of IMATH_NAMESPACE::Euler\");\n    eulerArray_class\n        //.add_property(\"x\",&EulerArray_get<T,1>)\n        //.add_property(\"y\",&EulerArray_get<T,2>)\n        //.add_property(\"z\",&EulerArray_get<T,3>)\n        .def(\"__init__\", make_constructor(EulerArray_eulerConstructor7a<T>))\n        .def(\"__init__\", make_constructor(EulerArray_eulerConstructor8a<T>))\n        .def(\"__init__\", make_constructor(EulerArray_eulerConstructor9a<T>))\n        .def(\"toXYZVector\", EulerArray_toXYZVector<T>)\n        .def(\"toQuat\", EulerArray_toQuat<T>)\n        ;\n\n    add_comparison_functions(eulerArray_class);\n    PyImath::add_explicit_construction_from_type<IMATH_NAMESPACE::Matrix33<T> >(eulerArray_class);\n    PyImath::add_explicit_construction_from_type<IMATH_NAMESPACE::Matrix44<T> >(eulerArray_class);\n    return eulerArray_class;\n}\n\ntemplate PYIMATH_EXPORT class_<IMATH_NAMESPACE::Euler<float>,bases<IMATH_NAMESPACE::Vec3<float> > > register_Euler<float>();\ntemplate PYIMATH_EXPORT class_<IMATH_NAMESPACE::Euler<double>,bases<IMATH_NAMESPACE::Vec3<double> > > register_Euler<double>();\n\ntemplate PYIMATH_EXPORT class_<FixedArray<IMATH_NAMESPACE::Euler<float> > > register_EulerArray<float>();\ntemplate PYIMATH_EXPORT class_<FixedArray<IMATH_NAMESPACE::Euler<double> > > register_EulerArray<double>();\n\ntemplate<> PYIMATH_EXPORT IMATH_NAMESPACE::Euler<float> FixedArrayDefaultValue<IMATH_NAMESPACE::Euler<float> >::value() { return IMATH_NAMESPACE::Euler<float>(); }\ntemplate<> PYIMATH_EXPORT IMATH_NAMESPACE::Euler<double> FixedArrayDefaultValue<IMATH_NAMESPACE::Euler<double> >::value() { return IMATH_NAMESPACE::Euler<double>(); }\n\n} // namespace PyImath\n", "meta": {"hexsha": "d53786ff5113953aaee51b1bcf86aee534b42509", "size": 25747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/python/PyImath/PyImathEuler.cpp", "max_stars_repo_name": "JenusL/Imath", "max_stars_repo_head_hexsha": "749a1bfe017b2daccb3eb9759fbe837ea4718a0a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 156.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T06:29:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:55:55.000Z", "max_issues_repo_path": "src/python/PyImath/PyImathEuler.cpp", "max_issues_repo_name": "JenusL/Imath", "max_issues_repo_head_hexsha": "749a1bfe017b2daccb3eb9759fbe837ea4718a0a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 146.0, "max_issues_repo_issues_event_min_datetime": "2020-06-13T18:17:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T16:47:29.000Z", "max_forks_repo_path": "src/python/PyImath/PyImathEuler.cpp", "max_forks_repo_name": "JenusL/Imath", "max_forks_repo_head_hexsha": "749a1bfe017b2daccb3eb9759fbe837ea4718a0a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2020-06-16T18:44:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T20:50:06.000Z", "avg_line_length": 30.614744352, "max_line_length": 169, "alphanum_fraction": 0.5983609741, "num_tokens": 7174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604274, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.26424934071595463}}
{"text": "#include \"boxsampler.hpp\"\n#include \"gibbssampler.hpp\"\n#include \"heliumsampler.hpp\"\n#include \"importancesampler.hpp\"\n#include \"metropolissampler.hpp\"\n#include \"sampler.hpp\"\n\n#include <Eigen/Dense>\n#include <pybind11/eigen.h>\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n\nnamespace py = pybind11;\n\nvoid init_sampler(py::module& main)\n{\n    auto m  = main.def_submodule(\"samplers\");\n    m.doc() = R\"doc(\nSamplers\n--------\n\nThe sampling classes are the foundation of the Monte Carlo machinery that VMC\ndepends on. They provide a way of sampling system configurations (i.e.\npositions of all particles) from a possibly unnormalized probability amplitude\n(i.e. wavefunctions), which in turn allows us to efficiently evaluate\nmultidimensional integrals.\n)doc\";\n\n    py::class_<Sampler>(m, \"Sampler\", R\"doc(\nThe :class:`Sampler` class provides a unified abstraction for the generation of\nsuccessive system instances drawn from some probability distribution (i.e. a\nwavefunction).\n\nAll other code expecting a sampler instance will take a :class:`Sampler` reference.\n\nThe subclasses of :class:`Sampler` will differ only in how they generate new\nsamples, according to their respective algorithms. As such they have different\nparameters that can be set at initialization.\n)doc\")\n        .def(\"next_configuration\", &Sampler::next_configuration, R\"doc(\nReturn a newly sampled system configuration.\n\nThere is no guarantee that this will always differ between successive calls,\nbut with a sufficient number of calls the distribution of outputs,\n:math:`P(\\mathbf{X})` should approximate\n\n.. math::\n\n    P(\\mathbf{X}) \\simeq  |\\Psi(\\mathbf{X})|^2\n\n)doc\")\n\n        .def(\"thermalize\", &Sampler::thermalize, R\"doc(\nGenerate a given number of samples, discarding all.\n\nThis is useful to ensure that the sampler has reached a stable point where\nsamples are representative of the underlying distribution.\n)doc\")\n\n        .def_property_readonly(\"acceptance_rate\", &Sampler::get_acceptance_rate, R\"doc(\nRate at which newly proposed samples where accepted by the algorithm.\n)doc\")\n\n        .def_property_readonly(\"current_system\", &Sampler::get_current_system);\n\n    py::class_<MetropolisSampler, Sampler>(m, \"MetropolisSampler\", R\"doc(\nImplementation of the standard Metropolis-Hastings algorithm, producing a\nMarkov Chain of system configurations. [1]_\n\nEach configuration is a _random_ perturbation of its predecessor if accepted, or\na copy if rejected. The perturbation is defined as a :math:`D` dimensional\nvector of uniform random numbers in :math:`\\frac{1}{2}[-s, s]` for some scale\nparameter :math:`s`.\n\n\nNotes\n-----\nThis implementation only changes the coordinates of one particle at a time. This\nmeans that two successive calls to `next_configuration()` will at most differ\nin one row of the output. This can be trusted to always be the case, and\npotential optimizations can be made based on this knowledge. For instance, if\ncaching of relative distances is employed, only the distances corresponding to\nthe changed particle would have to be recalculated.\n\n\nReferences\n----------\n.. [1] W. K. Hastings; Monte Carlo sampling methods using Markov chains and\n       their applications, Biometrika, Volume 57, Issue 1, 1 April 1970, Pages 97–109,\n       https://doi.org/10.1093/biomet/57.1.97\n\n\nExamples\n--------\n\n    >>> import numpy as np\n    >>> from qflow.samplers import MetropolisSampler\n    >>> from qflow.wavefunctions import SimpleGaussian\n    >>> psi = SimpleGaussian()\n    >>> sampler = MetropolisSampler(np.zeros((2, 3)), psi, step_size=1)\n\nWe can now get samples of the desired size on demand:\n\n    >>> sampler.next_configuration()\n    array([[-0.61370758,  0.08936709,  0.15872668],\n           [ 0.05973557,  0.07445129, -0.29230947]])\n\nThermalize the sampler (equivalent to running `next_configuration` the given number of times, only faster):\n\n    >>> sampler.thermalize(100)\n\nInspect the acceptance rate:\n\n    >>> sampler.acceptance_rate\n    0.7326732673267327\n)doc\")\n        .def(py::init<const System&, Wavefunction&, Real>(),\n             py::arg(\"system\"),\n             py::arg(\"wavefunction\"),\n             py::arg(\"step_size\") = 1,\n             R\"doc(\nConstruct a sampler that uses the standard Metropolis algorithm. The\n`step_size` determines how different successive configurations will be, and\nshould be tuned such that the acceptance rate remains high at all times.\n\nArguments\n---------\n )doc\");\n\n    py::class_<ImportanceSampler, Sampler>(m, \"ImportanceSampler\", R\"doc(\nModified version of the Metropolis-Hastings algorithm, which employs a smarter\nway of generating new samples. [2]_ The variance of integrals computed using\nthis algorithm tends to be significantly lower compared to\n:class:`MetropolisSampler`, at the expense of higher run-time cost.\n\n.. warning::\n    Importance sampling may only be used with wavefunctions that implements the\n    :class:`Wavefunction.drift_force` method. If this is not fulfilled, the\n    program will halt immediately without any way of catching an exception from\n    Python.\n\nNotes\n-----\nThis algorithm differs from Metropolis-Hastings in the perturbations made, with\na corresponding change in the acceptance probability. In our case,\n\n.. math::\n\n    X_k^{(i+1)} = X_k^{(i)} + \\sqrt{t}\\mathcal{n} + t \\frac{1}{\\Psi}\\nabla_k \\Psi,\n\nwhere :math:`X_k^{(i)}` is the coordinates of particle :math:`k` at time step\n:math:`i`, :math:`\\mathcal{n}` is a random number drawn from the standard normal\ndistribution and :math:`t` is the step size parameter used to tune how\ndifferent successive samples are.\n\nSimilarly to :class:`MetropolisSampler`, only one particle is perturbed at a time.\n\n\nReferences\n----------\n.. [2] Reiher, W. (1966), Hammersley, J. M., D. C. Handscomb: Monte Carlo\n       Methods. Methuen & Co., London, and John Wiley & Sons, New York, 1964. VII +\n       178 S., Preis: 25 s. Biom. J., 8: 209-209. doi:10.1002/bimj.19660080314\n\nExamples\n--------\nThis is used exactly like :class:`MetropolisSampler`, with the only exception being the\nmeaning of the `step_size`.\n\n    >>> import numpy as np\n    >>> from qflow.samplers import ImportanceSampler\n    >>> from qflow.wavefunctions import SimpleGaussian\n    >>> psi = SimpleGaussian()\n    >>> sampler = ImportanceSampler(np.zeros((2, 3)), psi, step_size=0.1)\n    >>> sampler.next_configuration()\n    array([[ 0.56938477,  0.25037102, -0.50411809],\n           [-0.8038079 ,  0.15799471, -0.06645576]])\n    >>> sampler.thermalize(100)\n    >>> sampler.acceptance_rate\n    0.9603960396039604\n\n)doc\")\n        .def(py::init<const System&, Wavefunction&, Real>(),\n             py::arg(\"system\"),\n             py::arg(\"wavefunction\"),\n             py::arg(\"step_size\") = 0.1);\n\n    py::class_<GibbsSampler, Sampler>(m, \"GibbsSampler\")\n        .def(py::init<const System&, RBMWavefunction&>(),\n             py::arg(\"system\"),\n             py::arg(\"rbm_wavefunction\"));\n\n    py::class_<BoxMetropolisSampler, MetropolisSampler>(m, \"BoxMetropolisSampler\")\n        .def(py::init<const System&, Wavefunction&, Real, Real>(),\n             py::arg(\"system\"),\n             py::arg(\"wavefunction\"),\n             py::arg(\"box_size\"),\n             py::arg(\"step_size\") = 1)\n        .def(\"initialize_from_system\", &BoxMetropolisSampler::initialize_from_system);\n\n    py::class_<BoxImportanceSampler, ImportanceSampler>(m, \"BoxImportanceSampler\")\n        .def(py::init<const System&, Wavefunction&, Real, Real>(),\n             py::arg(\"system\"),\n             py::arg(\"wavefunction\"),\n             py::arg(\"box_size\"),\n             py::arg(\"step_size\") = 0.1);\n\n    py::class_<HeliumSampler, Sampler>(m, \"HeliumSampler\")\n        .def(py::init<const System&, Wavefunction&, Real, Real>(),\n             py::arg(\"system\"),\n             py::arg(\"wavefunction\"),\n             py::arg(\"step_size\"),\n             py::arg(\"box_size\"));\n}\n", "meta": {"hexsha": "4870d49209bc4d146d884033ba3eff5c21bcf60d", "size": 7822, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "qflow/samplers/pysampler.cpp", "max_stars_repo_name": "johanere/qflow", "max_stars_repo_head_hexsha": "5453cd5c3230ad7f082adf9ec1aea63ab0a4312a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-07-24T21:46:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-11T18:18:24.000Z", "max_issues_repo_path": "qflow/samplers/pysampler.cpp", "max_issues_repo_name": "johanere/qflow", "max_issues_repo_head_hexsha": "5453cd5c3230ad7f082adf9ec1aea63ab0a4312a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2019-02-19T10:49:26.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-18T09:42:13.000Z", "max_forks_repo_path": "qflow/samplers/pysampler.cpp", "max_forks_repo_name": "bsamseth/FYS4411", "max_forks_repo_head_hexsha": "72b879e7978364498c48fc855b5df676c205f211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-24T06:44:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-12T20:34:38.000Z", "avg_line_length": 36.3813953488, "max_line_length": 107, "alphanum_fraction": 0.6950907696, "num_tokens": 1964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2640504811218927}}
{"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#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\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 GroupConcentrationVector& group_concentrations,\n                                              const MixtureConcentrationArray& mixture_concentrations,\n                                              std::vector<LogProbabilityVector> seeds) const\n{\n    Inferences result {};\n    result.approx_log_evidence = std::numeric_limits<double>::lowest();\n    for (auto& seed : seeds) {\n        auto inferences = evaluate(genotype_log_priors, log_likelihoods, group_concentrations, mixture_concentrations, seed);\n        if (inferences.approx_log_evidence > result.approx_log_evidence) {\n            result = std::move(inferences);\n        }\n    }\n    return result;\n}\n\nVariationalBayesMixtureMixtureModel::Inferences\nVariationalBayesMixtureMixtureModel::evaluate(const LogProbabilityVector& genotype_log_priors,\n                                              const HaplotypeLikelihoodMatrix& log_likelihoods,\n                                              const double group_concentration, 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_concentrations, mixture_concentrations, std::move(seeds));\n}\n\n// Private methods\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>\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>\nauto dirichlet_expectation_log(const std::vector<T>& concentrations)\n{\n    std::vector<T> result(concentrations.size());\n    const auto alpha_0= sum(concentrations);\n    std::transform(std::cbegin(concentrations), std::cend(concentrations), std::begin(result),\n                   [=] (auto alpha) { return digamma_diff(alpha, alpha_0); });\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\n} // namespace\n\nVariationalBayesMixtureMixtureModel::Inferences\nVariationalBayesMixtureMixtureModel::evaluate(const LogProbabilityVector& genotype_log_priors,\n                                              const HaplotypeLikelihoodMatrix& log_likelihoods,\n                                              const GroupConcentrationVector& prior_group_concentrations,\n                                              const MixtureConcentrationArray& prior_mixture_concentrations,\n                                              LogProbabilityVector& genotype_log_posteriors) const\n{\n    auto genotype_posteriors = exp(genotype_log_posteriors);\n    auto posterior_group_concentrations = prior_group_concentrations;\n    auto posterior_mixture_concentrations = prior_mixture_concentrations;\n    auto group_responsabilities = init_responsabilities(prior_group_concentrations, prior_mixture_concentrations,\n                                                        genotype_posteriors, log_likelihoods);\n    auto component_responsabilities = init_responsabilities(prior_group_concentrations, prior_mixture_concentrations,\n                                                            genotype_posteriors, group_responsabilities, 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(genotype_log_posteriors, genotype_log_priors,\n                                       group_responsabilities, component_responsabilities,\n                                       log_likelihoods);\n        exp(genotype_log_posteriors, genotype_posteriors);\n        update_group_concentrations(posterior_group_concentrations, prior_group_concentrations, group_responsabilities);\n        update_mixture_concentrations(posterior_mixture_concentrations, prior_mixture_concentrations,\n                                      group_responsabilities, component_responsabilities);\n        auto curr_evidence = calculate_evidence(prior_group_concentrations, posterior_group_concentrations,\n                                                prior_mixture_concentrations, posterior_mixture_concentrations,\n                                                genotype_log_priors, genotype_log_posteriors, genotype_posteriors,\n                                                group_responsabilities, component_responsabilities,\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_responsabilities(group_responsabilities, posterior_group_concentrations, posterior_mixture_concentrations,\n                                genotype_posteriors, component_responsabilities, log_likelihoods);\n        update_responsabilities(component_responsabilities, posterior_group_concentrations, posterior_mixture_concentrations,\n                                genotype_posteriors, group_responsabilities, log_likelihoods);\n    }\n    Inferences result {};\n    result.genotype_log_posteriors = std::move(genotype_log_posteriors);\n    result.genotype_posteriors = std::move(genotype_posteriors);\n    result.group_concentrations = std::move(posterior_group_concentrations);\n    result.mixture_concentrations = std::move(posterior_mixture_concentrations);\n    result.group_responsabilities = std::move(group_responsabilities);\n    result.approx_log_evidence = prev_evidence;\n    return result;\n}\n\nVariationalBayesMixtureMixtureModel::GroupResponsabilityVector\nVariationalBayesMixtureMixtureModel::init_responsabilities(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    GroupResponsabilityVector 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    for (std::size_t s {0}; s < S; ++s) {\n        const auto N = log_likelihoods[s][0][0][0].size();\n        const auto tau = 1.0 / max_K;\n        const auto tau_sum = N * tau;\n        for (std::size_t t {0}; t < T; ++t) {\n            result[s][t] = ln_ex_psi[t];\n            const auto ln_ex_pi = dirichlet_expectation_log(mixture_concentrations[s][t]);\n            const auto K = mixture_concentrations[s][t].size();\n            for (std::size_t k {0}; k < K; ++k) {\n                result[s][t] += ln_ex_pi[k] * tau_sum;\n                for (std::size_t g {0}; g < G; ++g) {\n                    result[s][t] += genotype_priors[g] * tau * sum(log_likelihoods[s][g][t][k]);\n                }\n            }\n        }\n        maths::normalise_exp(result[s]);\n    }\n    return result;\n}\n\nvoid\nVariationalBayesMixtureMixtureModel::update_responsabilities(GroupResponsabilityVector& result,\n                                                             const GroupConcentrationVector& group_concentrations,\n                                                             const MixtureConcentrationArray& mixture_concentrations,\n                                                             const ProbabilityVector& genotype_posteriors,\n                                                             const ComponentResponsabilityMatrix& component_responsabilities,\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        std::vector<double> component_responsability_sums(component_responsabilities[s].size());\n        std::transform(std::cbegin(component_responsabilities[s]), std::cend(component_responsabilities[s]),\n                       std::begin(component_responsability_sums), [] (const auto& taus) { return sum(taus); });\n        for (std::size_t t {0}; t < T; ++t) {\n            result[s][t] = ln_ex_psi[t];\n            const auto ln_ex_pi = dirichlet_expectation_log(mixture_concentrations[s][t]);\n            const auto K = ln_ex_pi.size();\n            for (std::size_t k {0}; k < K; ++k) {\n                result[s][t] += ln_ex_pi[k] * component_responsability_sums[k];\n                for (std::size_t g {0}; g < G; ++g) {\n                    result[s][t] += genotype_posteriors[g] * inner_product(component_responsabilities[s][k], log_likelihoods[s][g][t][k]);\n                }\n            }\n        }\n        maths::normalise_exp(result[s]);\n    }\n}\n\nVariationalBayesMixtureMixtureModel::ComponentResponsabilityMatrix\nVariationalBayesMixtureMixtureModel::init_responsabilities(const GroupConcentrationVector& group_concentrations,\n                                                           const MixtureConcentrationArray& mixture_concentrations,\n                                                           const ProbabilityVector& genotype_priors,\n                                                           const GroupResponsabilityVector& group_responsabilities,\n                                                           const HaplotypeLikelihoodMatrix& 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    ComponentResponsabilityMatrix result(S, ComponentResponsabilityVector(K));\n    for (std::size_t s {0}; s < S; ++s) {\n        const auto N = log_likelihoods[s][0][0][0].size();\n        for (std::size_t k {0}; k < K; ++k) {\n            result[s][k].resize(N);\n        }\n    }\n    update_responsabilities(result, group_concentrations, mixture_concentrations,\n                            genotype_priors, group_responsabilities, 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_responsabilities(ComponentResponsabilityMatrix& result,\n                                                             const GroupConcentrationVector& group_concentrations,\n                                                             const MixtureConcentrationArray& mixture_concentrations,\n                                                             const ProbabilityVector& genotype_posteriors,\n                                                             const GroupResponsabilityVector& group_responsabilities,\n                                                             const HaplotypeLikelihoodMatrix& 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].size();\n    for (std::size_t s {0}; s < S; ++s) {\n        const auto N = log_likelihoods[s][0][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 < K; ++k) {\n                for (std::size_t n {0}; n < N; ++n) {\n                    if (t == 0) result[s][k][n] = 0;\n                    result[s][k][n] += group_responsabilities[s][t] * (ln_exp_pi[k] + inner_product(genotype_posteriors, log_likelihoods[s], t, k, n));\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][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][k][n] = std::exp(ln_rho[k] - ln_rho_norm);\n            }\n        }\n    }\n}\n\nvoid\nVariationalBayesMixtureMixtureModel::update_genotype_log_posteriors(LogProbabilityVector& result,\n                                                                    const LogProbabilityVector& genotype_log_priors,\n                                                                    const GroupResponsabilityVector& group_responsabilities,\n                                                                    const ComponentResponsabilityMatrix& component_responsabilities,\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_responsabilities, component_responsabilities, log_likelihoods, g);\n    }\n    maths::normalise_logs(result);\n}\n\nVariationalBayesMixtureMixtureModel::LogProbability\nVariationalBayesMixtureMixtureModel::marginalise(const GroupResponsabilityVector& group_responsabilities,\n                                                 const ComponentResponsabilityMatrix& component_responsabilities,\n                                                 const HaplotypeLikelihoodMatrix& log_likelihoods,\n                                                 const std::size_t g) const noexcept\n{\n    const auto T = group_responsabilities.front().size();\n    const auto S = component_responsabilities.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_responsabilities[s][t] * marginalise(component_responsabilities[s], log_likelihoods[s][g][t]);\n        }\n    }\n    return result;\n}\n\nVariationalBayesMixtureMixtureModel::LogProbability\nVariationalBayesMixtureMixtureModel::marginalise(const ComponentResponsabilityVector& responsabilities,\n                                                 const HaplotypeLikelihoodVector& log_likelihoods) const noexcept\n{\n    const auto K = log_likelihoods.size();\n    LogProbability result {0};\n    for (std::size_t k {0}; k < K; ++k) {\n        result += inner_product(responsabilities[k], log_likelihoods[k]);\n    }\n    return result;\n}\n\nvoid\nVariationalBayesMixtureMixtureModel::update_group_concentrations(GroupConcentrationVector& result,\n                                                                 const GroupConcentrationVector& prior_group_concentrations,\n                                                                 const GroupResponsabilityVector& group_responsabilities) const\n{\n    assert(result.size() == prior_group_concentrations.size());\n    const auto T = prior_group_concentrations.size();\n    const auto S = group_responsabilities.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_responsabilities[s][t];\n        }\n    }\n}\n\nvoid\nVariationalBayesMixtureMixtureModel::update_mixture_concentrations(MixtureConcentrationArray& result,\n                                                                   const MixtureConcentrationArray& prior_mixture_concentrations,\n                                                                   const GroupResponsabilityVector& group_responsabilities,\n                                                                   const ComponentResponsabilityMatrix& component_responsabilities) const\n{\n    const auto S = prior_mixture_concentrations.size();\n    const auto T = group_responsabilities.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] + group_responsabilities[s][t] * sum(component_responsabilities[s][k]);\n            }\n        }\n    }\n}\n\nnamespace {\n\ntemplate <typename Range1, typename Range2>\nauto inner_inner_product(const Range1& lhs, const Range2& rhs) noexcept\n{\n    using T = decltype(inner_product(lhs[0], rhs[0]));\n    const auto k = std::min(lhs.size(), rhs.size());\n    return std::inner_product(std::cbegin(lhs), std::next(std::cbegin(lhs), k), std::cbegin(rhs), T {}, std::plus<> {},\n                              [] (const auto& a, const auto& b) { return inner_product(a, b); });\n}\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 GroupResponsabilityVector& group_responsabilities,\n                                                        const ComponentResponsabilityMatrix& component_responsabilities,\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_responsabilities.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            for (std::size_t t {0}; t < T; ++t) {\n                w += group_responsabilities[s][t] * inner_inner_product(component_responsabilities[s], log_likelihoods[s][g][t]);\n            }\n        }\n        result += genotype_posteriors[g] * w;\n    }\n    for (std::size_t s {0}; s < S; ++s) {\n        result += shannon_entropy(group_responsabilities[s]);\n        result += shannon_entropy(component_responsabilities[s]);\n        for (std::size_t t {0}; t < T; ++t) {\n            result += maths::log_beta(posterior_mixture_concentrations[s][t]) - maths::log_beta(prior_mixture_concentrations[s][t]);\n        }\n    }\n    result += maths::log_beta(posterior_group_concentrations) - maths::log_beta(prior_group_concentrations);\n    return result;\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 GroupResponsabilityVector& responsabilities) const\n{\n    for (std::size_t s {0}; s < responsabilities.size(); ++s) {\n        for (std::size_t t {0}; t < responsabilities[s].size(); ++t) {\n            std::cout << \"s: \" << s << \" t: \" << t << \" = \" << responsabilities[s][t] << std::endl;\n        }\n    }\n}\n\nvoid VariationalBayesMixtureMixtureModel::print(const ComponentResponsabilityMatrix& responsabilities) const\n{\n    for (std::size_t s {0}; s < responsabilities.size(); ++s) {\n        for (std::size_t k {0}; k < responsabilities[s].size(); ++k) {\n            for (std::size_t n {0}; n < responsabilities[s][k].size(); ++n) {\n                std::cout << \"s: \" << s <<  \" k: \" << k << \" n: \" << n << \" = \" << responsabilities[s][k][n] << std::endl;\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": "3e2910ae67e59b70ddbebd42ee38b905c82238ef", "size": 25882, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/models/genotype/variational_bayes_mixture_mixture_model.cpp", "max_stars_repo_name": "gmagoon/octopus", "max_stars_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/models/genotype/variational_bayes_mixture_mixture_model.cpp", "max_issues_repo_name": "gmagoon/octopus", "max_issues_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_issues_repo_licenses": ["MIT"], "max_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_mixture_model.cpp", "max_forks_repo_name": "gmagoon/octopus", "max_forks_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_forks_repo_licenses": ["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.2053231939, "max_line_length": 151, "alphanum_fraction": 0.6023877598, "num_tokens": 5882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.38491214448393357, "lm_q1q2_score": 0.26403027573478893}}
{"text": "#ifndef INCLUDED_STDDEFX\n#include \"stddefx.h\"\n#define INCLUDED_STDDEFX\n#endif\n\n#ifndef INCLUDED_CALC\n#include \"calc.h\"\n#define INCLUDED_CALC\n#endif\n\n// Library headers.\n#include <utility>\n#ifndef INCLUDED_BOOST_NONCOPYABLE\n#include <boost/noncopyable.hpp>\n#define INCLUDED_BOOST_NONCOPYABLE\n#endif\n#ifndef INCLUDED_BOOST_MATH_SPECIAL_FUNCTIONS_ROUND\n#include <boost/math/special_functions/round.hpp>\n#define INCLUDED_BOOST_MATH_SPECIAL_FUNCTIONS_ROUND\n#endif\n#ifndef INCLUDED_BOOST_MATH_TR1\n#include <boost/math/tr1.hpp>\n#define INCLUDED_BOOST_MATH_TR1\n#endif\n\n\n// PCRaster library headers.\n\n#ifndef INCLUDED_MISC\n#include \"misc.h\"\n#define INCLUDED_MISC\n#endif\n\n#ifndef INCLUDED_COM_MATH\n#include \"com_math.h\"\n#define INCLUDED_COM_MATH\n#endif\n#ifndef INCLUDED_COM_INTERVALTYPES\n#include \"com_intervaltypes.h\"\n#define INCLUDED_COM_INTERVALTYPES\n#endif\n\n#ifndef INCLUDED_GEO_CELLLOCVISITOR\n#include \"geo_celllocvisitor.h\"\n#define INCLUDED_GEO_CELLLOCVISITOR\n#endif\n\n#ifndef INCLUDED_GEO_SCANCONVERSION\n#include \"geo_scanconversion.h\"\n#define INCLUDED_GEO_SCANCONVERSION\n#endif\n\n#ifndef INCLUDED_FIELDAPI_INTERFACE\n#include \"fieldapi_interface.h\"\n#define INCLUDED_FIELDAPI_INTERFACE\n#endif\n\n#ifndef INCLUDED_FIELDAPI_SCALARDOMAINCHECK\n#include \"fieldapi_scalardomaincheck.h\"\n#define INCLUDED_FIELDAPI_SCALARDOMAINCHECK\n#endif\n\n// Module headers.\n\n\n\n/*!\n  \\file\n  This file contains the implementation of the ExtentOfView class.\n*/\n\n\n\ntemplate<class T>\nclass RememberPoints: public boost::noncopyable\n{\n\nprivate:\n\n  const fieldapi::ReadOnly<INT4>& d_classes;\n  INT4 d_class;\n  std::vector<std::pair<T, T> > d_points;\n\npublic:\n\n  RememberPoints(const fieldapi::ReadOnly<INT4>& classes)\n    : d_classes(classes)\n  {\n  }\n\n  RememberPoints(const fieldapi::ReadOnly<INT4>& classes, INT4 currentClass)\n    : d_classes(classes), d_class(currentClass)\n  {\n  }\n\n  void setClass(INT4 currentClass) {\n    d_class = currentClass;\n  }\n\n  bool operator()(T x, T y) {\n    static INT4 value;\n    if(d_classes.get(value, y, x) && value == d_class) {\n      d_points.push_back(std::make_pair(y, x));\n      return true;\n    }\n\n    return false;\n  }\n\n  std::pair<T, T>& operator[](size_t i) {\n    return d_points[i];\n  }\n\n  void clear() {\n    d_points.clear();\n  }\n\n  size_t size() {\n    return d_points.size();\n  }\n\n  // Distance in cells.\n  double distance() {\n    double distance = 0.0;\n\n    if(size()) {\n      const std::pair<T, T>& begin = d_points.front();\n      const std::pair<T, T>& end = d_points.back();\n      double dx = static_cast<double>(end.first - begin.first);\n      double dy = static_cast<double>(end.second - begin.second);\n      // Add one for current cell.\n      distance = boost::math::tr1::hypot(dx,dy) + 1.0;\n    }\n\n    return distance;\n  }\n\n};\n\n\n\nextern \"C\" int ExtentOfView(\n  MAP_REAL8 *m_result,                  // scalar, average extent of view\n  const MAP_INT4* m_classes,            // nominal, classes\n  const MAP_REAL8* m_nrDirections)      // scalar, number of directions\n{\n  ReadWriteReal8_ref(result, m_result);\n\n  std::vector<const fieldapi::Common*> inputs;\n  ReadOnlyInt4_ref(classes, m_classes);\n  inputs.push_back(&classes);\n  ReadOnlyReal8_ref(nrDirectionsInterface, m_nrDirections);\n  inputs.push_back(&nrDirectionsInterface);\n\n  PRECOND(classes.spatial());\n  PRECOND(!nrDirectionsInterface.spatial());\n  size_t nrDirections = static_cast<size_t>(nrDirectionsInterface.value(0,0));\n\n  std::vector<fieldapi::ScalarDomainCheck> nsDomains;\n  nsDomains.push_back(fieldapi::ScalarDomainCheck(nrDirectionsInterface,\n        \"Number of directions\", com::GreaterThan<double>(0)));\n  int nsCheck = fieldapi::checkScalarDomains(nsDomains,geo::CellLoc(0,0));\n  if(nsCheck != -1) {\n    return RetError(1, nsDomains[nsCheck].msg().c_str());\n  }\n\n  size_t nrRows = classes.nrRows();\n  size_t nrCols = classes.nrCols();\n\n  // Result is missing value if any of the inputs is.\n  for(geo::CellLocVisitor visitor(classes); visitor.valid(); ++visitor) {\n\n    if(fieldapi::nonMV(inputs, *visitor)) {\n       result.put(0.0, *visitor);\n    }\n    else {\n      result.putMV(*visitor);\n    }\n  }\n\n  // Determine all direction angles.\n  // Determine max distance in cells in the raster.\n  double maxExtent = MAX(nrRows,nrCols);\n  int offsetX = com::ceil<int, double>(boost::math::tr1::hypot(maxExtent,maxExtent));\n  int offsetY;\n  double subAngle = 360.0 / nrDirections;\n  double angle;\n  typedef std::pair<int, int> Offset;\n  typedef std::vector<std::pair<double, Offset> > Offsets;\n  Offsets offsets;\n\n  for(size_t direction = 0; direction < nrDirections; ++direction) {\n\n    angle = direction * subAngle;\n    PRECOND(angle >= 0 && angle < 360);\n\n    if(angle == 90.0) {\n      offsetX = 0;\n      offsetY = 100;\n    }\n    else if(angle == 270.0) {\n      offsetX = 0;\n      offsetY = -100;\n    }\n    else {\n      if(angle < 90 || angle > 270) {\n        offsetX = 100;\n      }\n      else {\n        offsetX = -100;\n      }\n\n      angle *= M_PI / 180;\n      offsetY = boost::math::iround(std::tan(angle) * offsetX);\n    }\n    offsets.push_back(std::make_pair(angle,\n         std::make_pair(offsetX, offsetY)));\n  }\n\n  int x, y;\n  double sum;\n  RememberPoints<int> points(classes);\n\n  // Loop over each cell.\n  for(geo::CellLocVisitor visitor(classes); visitor.valid(); ++visitor) {\n    x = (*visitor).col();\n    y = (*visitor).row();\n    sum = 0.0;\n\n    // Determine class.\n    if(result.isMV(*visitor)) {\n      continue;\n    }\n\n    points.setClass(classes[*visitor]);\n\n    // Loop over each direction.\n    for(Offsets::const_iterator it = offsets.begin(); it != offsets.end();\n         ++it) {\n\n      points.clear();\n      POSTCOND(!points.size());\n\n      // Determine number of cells with same class.\n      PRECOND(!classes.isMV(*visitor));\n      geo::midpointLine(x, y, x + (*it).second.first, y + (*it).second.second,\n         points);\n      POSTCOND(points.size());\n\n      sum += points.distance();\n    }\n\n    // Write sum to cell.\n    // Check whether --unitcell or --unittrue is set.\n    // unittrue: area is computed in true area represented by cells (default)\n    // unitcell: area is computed in number of cells\n    result.put(Side() * sum, *visitor);\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "bfa1866eb39b6564e0371d5da5b9db67a519791e", "size": 6172, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/calc/calc_extentofview.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/calc/calc_extentofview.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/calc/calc_extentofview.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5572519084, "max_line_length": 85, "alphanum_fraction": 0.6767660402, "num_tokens": 1584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.26403027079244007}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   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_FACTORIZATIONS_QR_HPP_INCLUDED\n#define NT2_LINALG_FUNCTIONS_FACTORIZATIONS_QR_HPP_INCLUDED\n\n#include <nt2/include/functions/qr.hpp>\n#include <boost/dispatch/attributes.hpp>\n#include <nt2/core/container/table/table.hpp>\n#include <nt2/include/functions/colon.hpp>\n#include <nt2/include/functions/expand.hpp>\n#include <nt2/include/functions/eye.hpp>\n#include <nt2/include/functions/geqp3.hpp>\n#include <nt2/include/functions/geqrf.hpp>\n#include <nt2/include/functions/gqr.hpp>\n#include <nt2/include/functions/min.hpp>\n#include <nt2/include/functions/mqr.hpp>\n#include <nt2/include/functions/tie.hpp>\n#include <nt2/include/functions/triu.hpp>\n#include <nt2/include/functions/width.hpp>\n#include <nt2/include/functions/zeros.hpp>\n#include <nt2/linalg/details/utility/lapack_verify.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/core/container/dsl/as_terminal.hpp>\n#include <nt2/core/utility/assign_swap.hpp>\n#include <nt2/core/container/colon/colon.hpp>\n#include <nt2/linalg/options.hpp>\n\nnamespace nt2 { namespace ext\n{\n  //============================================================================\n  //QR Scalar\n  //============================================================================\n  BOOST_DISPATCH_IMPLEMENT  ( qr_, tag::cpu_\n                            , (A0)\n                            , (scalar_<unspecified_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE result_type operator()(const A0& a0) const\n    {\n      return a0;\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( qr_, tag::cpu_\n                            , (A0)(A1)\n                            , (scalar_<unspecified_<A0> >)\n                              (unspecified_<A1>)\n                            )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE result_type operator()(const A0& a0, const A1&) const\n    {\n      return a0;\n    }\n  };\n\n\n\n  //============================================================================\n  //[Q,R] = QR(A)\n  //============================================================================\n  BOOST_DISPATCH_IMPLEMENT  ( qr_, tag::cpu_\n                            , (A0)(N0)(A1)(N1)\n                            , ((node_<A0, nt2::tag::qr_\n                                    , N0, nt2::container::domain\n                                      >\n                              ))\n                              ((node_<A1, nt2::tag::tie_\n                                    , N1, nt2::container::domain\n                                     >\n                              ))\n                            )\n  {\n    typedef void  result_type;\n    typedef typename boost::proto::result_of::child_c<A0&,0>::value_type     child0;\n    typedef typename child0::value_type                                      type_t;\n    typedef typename meta::as_real<type_t>::type                            rtype_t;\n    typedef typename meta::as_integer<rtype_t>::type                        itype_t;\n    typedef nt2::memory::container<tag::table_, type_t, nt2::_2D>        o_semantic;\n    typedef nt2::memory::container<tag::table_, nt2_la_int, nt2::_2D>    i_semantic;\n\n    BOOST_FORCEINLINE result_type operator()( A0& a0, A1& a1 ) const\n    {\n      eval(a0, a1, N0(), N1());\n    }\n\n  private:\n    /// INTERNAL ONLY - x = qr(a)\n    /// return a matrix x such that triu(x) is the upper triangular factor r.\n    /// this is the direct return of LAPACK ?geqp3, however tau is lost (and so q)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<1> const& // 1 input\n              , boost::mpl::long_<1> const& // 1 output\n              ) const\n    {\n      eval1_1(a0, a1, nt2::policy<ext::raw_>());\n    }\n\n    /// INTERNAL ONLY - x = qr(a, econ_/0)\n    /// return a matrix x such that triu(x) is the upper triangular factor r.\n    /// this is the direct return of LAPACK ?geqp3, however tau is lost (and so q)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<2> const& // 2 input\n              , boost::mpl::long_<1> const& // 1 output\n              ) const\n    {\n      eval2_1(a0, a1, boost::proto::value(boost::proto::child_c<1>(a0)));\n    }\n\n    /// INTERNAL ONLY - [q, r] = qr(a)\n    /// where a is m-by-n, produces an m-by-n upper triangular matrix r\n    ///  and an m-by-m unitary matrix q so that a = q*r.\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<1> const&  // 1 input\n              , boost::mpl::long_<2> const&  // 2 output\n              ) const\n    {\n      eval2_2(a0, a1, nt2::policy<ext::matrix_>());\n    }\n\n    /// INTERNAL ONLY - [q, r, e] = qr(a)\n    /// produces unitary q, upper triangular r and a\n    /// permutation row vector e so that a(e, _)= q*r.\n    /// the column permutation e is chosen so that abs(diag_of(r)) is decreasing.\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<1> const&  // 1 input\n              , boost::mpl::long_<3> const&  // 3 output\n              ) const\n    {\n      eval2_3(a0, a1, nt2::policy<ext::matrix_>());\n    }\n\n    /// INTERNAL ONLY - [x, y] = qr(a, raw_/matrix_/vector_/econ_/0 )\n    /// with raw_\n    ///  [x, tau] = qr(a, raw_)\n    /// returns a matrix x such that triu(x) is the upper triangular factor r.\n    /// The elements below the diagonal, together with the array tau, represent the\n    /// unitary matrix Q as a product of min(M,N) elementary reflectors.\n    /// tau contains The scalar factors of the elementary reflectors.\n    /// This is the direct return of LAPACK ?geqp3\n    ///\n    /// with matrix_/vector is the same as  [q, r] = qr(a)\n    /// [q, r] = qr(a, econ_) or  [q, r] = qr(a, 0)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<2> const&\n              , boost::mpl::long_<2> const&\n              ) const\n    {\n      //1_2 means  1 input 2 outputs\n      eval2_2(a0, a1\n             , boost::proto::value(boost::proto::child_c<1>(a0)));\n    }\n\n    /// INTERNAL ONLY - [q, r, e] = qr(a, vector_/matrix_)\n    /// with vector_\n    /// produces unitary q, upper triangular r and a\n    /// permutation row vector e so that a(e, _)= q*r.\n    /// the column permutation e is chosen so that abs(diag_of(r)) is decreasing.\n    /// with matrix_\n    /// produces unitary q, upper triangular r and a\n    /// permutation matrix e so that a*e = q*r.\n    /// the column permutation e is chosen so that abs(diag_of(r)) is decreasing.\n    /// Same as   [q, r, e] = qr(a)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<2> const& // 2 input\n              , boost::mpl::long_<3> const& // 2 output\n              ) const\n    {\n      eval2_3(a0, a1, boost::proto::value(boost::proto::child_c<1>(a0)));\n    }\n\n\n    ///////////////////////////////////////////////////////////////////////////////\n    // evali_j bunch\n    ///////////////////////////////////////////////////////////////////////////////\n\n    ///////////////////////////////////////////////////////////////////////////////\n    /// INTERNAL ONLY: 1i 1o: x  = qr(a)\n    BOOST_FORCEINLINE\n    void eval1_1 ( A0& a0, A1& a1\n                   , const nt2::policy<ext::raw_>&\n                   ) const\n    {\n      NT2_AS_TERMINAL_INOUT(o_semantic, r\n                           , boost::proto::child_c<0>(a0), boost::proto::child_c<0>(a1));\n      o_semantic tau(of_size(height(r), 1));\n      NT2_LAPACK_VERIFY(nt2::geqrf( boost::proto::value(r)\n                                  , tau));\n      assign_swap(boost::proto::child_c<0>(a1), r);\n    }\n\n    /// INTERNAL ONLY: 2i 1o raw_: x  = qr(a, raw_)\n    BOOST_FORCEINLINE\n    void eval2_1 ( A0& a0, A1& a1\n                   , const nt2::policy<ext::raw_>&\n                   ) const\n    {\n      eval1_1(a0, a1, nt2::policy<ext::raw_>());\n    }\n\n    /// INTERNAL ONLY: 2i 1o upper_: x  = qr(a, upper_)\n    BOOST_FORCEINLINE\n    void eval2_1 ( A0& a0, A1& a1\n                   , const nt2::policy<ext::upper_>&\n                   ) const\n    {\n       nt2::container::table<type_t> work;\n       NT2_AS_TERMINAL_INOUT(o_semantic\n                            , r, boost::proto::child_c<0>(a0), work);\n       o_semantic tau(of_size(height(r), 1));\n       NT2_LAPACK_VERIFY(nt2::geqrf( boost::proto::value(r)\n                                   ,tau));\n       boost::proto::child_c<0>(a1) = triu(r);\n    }\n\n    /// INTERNAL ONLY: 2i 1o econ_: x  = qr(a, econ_)\n    BOOST_FORCEINLINE\n    void eval2_1 ( A0& a0, A1& a1\n                   , const nt2::policy<ext::econ_>&\n                   ) const\n    {\n      eval1_1(a0, a1, nt2::policy<ext::raw_>());\n    }\n\n    /// INTERNAL ONLY: 2i 1o 0: x  = qr(a, 0)\n    BOOST_FORCEINLINE\n    void eval2_1 ( A0& a0, A1& a1\n                   , const int&\n                   ) const\n    {\n      eval1_1(a0, a1, nt2::policy<ext::raw_>());\n    }\n\n    ///////////////////////////////////////////////////////////////////////////////\n    /// INTERNAL ONLY: 2i 2o raw_: tie(x, tau) = qr(a, raw_)\n    BOOST_FORCEINLINE\n    void eval2_2 ( A0& a0, A1& a1\n                   , const nt2::policy<ext::raw_>&\n                   ) const\n    {\n      NT2_AS_TERMINAL_INOUT(o_semantic, x\n                           , boost::proto::child_c<0>(a0), boost::proto::child_c<0>(a1));\n      NT2_AS_TERMINAL_OUT(o_semantic, tau\n                         , boost::proto::child_c<1>(a1));\n      tau.resize(of_size(dim(x), 1));\n      NT2_LAPACK_VERIFY(nt2::geqrf( boost::proto::value(x)\n                                  , boost::proto::value(tau)));\n      assign_swap(boost::proto::child_c<0>(a1), x);\n      assign_swap(boost::proto::child_c<1>(a1), tau);\n    }\n\n\n    ///////////////////////////////////////////////////////////////////////////////\n    /// INTERNAL ONLY: 2i 3o raw_: tie(x, tau, ip) = qr(a, nt2::raw_)\n    BOOST_FORCEINLINE\n    void eval2_3 ( A0& a0, A1& a1\n                   , const nt2::policy<ext::raw_>&\n                   ) const\n    {\n      nt2::container::table<type_t> work;\n      NT2_AS_TERMINAL_INOUT(o_semantic, x\n                           , boost::proto::child_c<0>(a0), boost::proto::child_c<0>(a1));\n      NT2_AS_TERMINAL_OUT(o_semantic, tau\n                         , boost::proto::child_c<1>(a1));\n      NT2_AS_TERMINAL_OUT(i_semantic,  ip\n                         , boost::proto::child_c<2>(a1));\n      tau.resize(of_size(dim(x), 1));\n      ip = nt2::zeros(nt2::width(x),1,nt2::meta::as_<nt2_la_int>());\n      NT2_LAPACK_VERIFY(nt2::geqp3( boost::proto::value(x)\n                                  , boost::proto::value(ip)\n                                  , boost::proto::value(tau)));\n      assign_swap(boost::proto::child_c<0>(a1), x);\n      assign_swap(boost::proto::child_c<1>(a1), tau);\n      assign_swap(boost::proto::child_c<2>(a1), ip);\n    }\n\n\n    ///////////////////////////////////////////////////////////////////////////////\n    /// INTERNAL ONLY: 2i 2o matrix_/econ_: tie(q, r) = qr(a, matrix_) or\n    /// tie(q, r) = qr(a, econ_), only extracting phases differ\n    template < class T >\n    BOOST_FORCEINLINE\n    void eval2_2 ( A0& a0, A1& a1\n                 , const T&\n                 ) const\n    {\n      nt2::container::table<type_t> work;\n      NT2_AS_TERMINAL_INOUT(o_semantic\n                           , r, boost::proto::child_c<0>(a0), work);\n      NT2_AS_TERMINAL_OUT  (o_semantic\n                           , x, boost::proto::child_c<0>(a1));\n      nt2::container::table<type_t>     tau;\n      tie(x, tau) = qr(r, nt2::raw_);\n      extract_qr(x, tau, r, T()); // extract raw or econ\n      assign_swap(boost::proto::child_c<0>(a1), x);\n      assign_swap(boost::proto::child_c<1>(a1), r);\n    }\n\n    ///////////////////////////////////////////////////////////////////////////////\n    /// INTERNAL ONLY: 2i 2o vector_: tie(q, r) = qr(a, vector_)\n    /// this is identical to  tie(q, r) = qr(a, matrix_)  ot  tie(q, r) = qr(a)\n    BOOST_FORCEINLINE\n    void eval2_2 ( A0& a0, A1& a1\n                   , const nt2::policy<ext::vector_>&\n                   ) const\n    {\n      eval2_2(a0, a1,  nt2::policy<ext::matrix_>()); //with 2 outputs vector_ is useless\n    }\n\n    ///////////////////////////////////////////////////////////////////////////////\n    /// INTERNAL ONLY: 2i 2o vector_: tie(q, r) = qr(a, 0)\n    BOOST_FORCEINLINE\n    void eval2_2 ( A0& a0, A1& a1\n                   , const int &\n                   ) const\n    {\n      eval2_2(a0, a1, nt2::policy<ext::econ_>()); // 0 and econ_ are equivalent\n    }\n\n    ///////////////////////////////////////////////////////////////////////////////\n    /// INTERNAL ONLY: 2i 3o vector_: tie(q, r, ip) = qr(a, econ_)\n    BOOST_FORCEINLINE\n    void eval2_3 ( A0& a0, A1& a1\n                   , const nt2::policy<ext::econ_>&\n                   ) const\n    {\n      nt2::container::table<type_t> work;\n      NT2_AS_TERMINAL_INOUT(o_semantic, r\n                           , boost::proto::child_c<0>(a0), work);\n      NT2_AS_TERMINAL_OUT  (o_semantic, x\n                           , boost::proto::child_c<0>(a1));\n      NT2_AS_TERMINAL_OUT  (i_semantic, ip\n                           , boost::proto::child_c<2>(a1));\n      nt2::container::table<type_t> tau;\n      tie(x, tau, ip) = qr(r, nt2::raw_);\n\n      extract_qr(x, tau, r, nt2::policy<ext::econ_>());\n      assign_swap(boost::proto::child_c<0>(a1), x);\n      assign_swap(boost::proto::child_c<1>(a1), r);\n      assign_swap(boost::proto::child_c<2>(a1), ip);\n    }\n\n    ///////////////////////////////////////////////////////////////////////////////\n    /// INTERNAL ONLY: 2i 3o vector_: tie(q, r, ip) = qr(a, 0)\n    BOOST_FORCEINLINE\n    void eval2_3 ( A0& a0, A1& a1\n                   , const int &\n                   ) const\n    {\n      eval2_3(a0, a1,  nt2::policy<ext::econ_>()); // 0 and econ_ are equivalent\n    }\n\n    ///////////////////////////////////////////////////////////////////////////////\n    /// INTERNAL ONLY: 2i 3o vector_: tie(q, r, ip) = qr(a, vector_)\n    BOOST_FORCEINLINE\n    void eval2_3 ( A0& a0, A1& a1\n                   , const nt2::policy<ext::vector_>&\n                   ) const\n    {\n      nt2::container::table<type_t> work;\n      NT2_AS_TERMINAL_INOUT(o_semantic, r\n                           , boost::proto::child_c<0>(a0), work);\n      NT2_AS_TERMINAL_OUT  (o_semantic, x\n                           , boost::proto::child_c<0>(a1));\n      NT2_AS_TERMINAL_OUT  (i_semantic, ip\n                           , boost::proto::child_c<2>(a1));\n      nt2::container::table<type_t>     tau;\n      tie(x, tau, ip) = qr(r, nt2::raw_);\n\n      extract_qr(x, tau, r, nt2::policy<ext::raw_>());\n      assign_swap(boost::proto::child_c<0>(a1), x);\n      assign_swap(boost::proto::child_c<1>(a1), r);\n      assign_swap(boost::proto::child_c<2>(a1), ip);\n    }\n\n     ///////////////////////////////////////////////////////////////////////////////\n    /// INTERNAL ONLY: 2i 3o matrix_: tie(q, r, p) = qr(a, matrix_)\n    BOOST_FORCEINLINE\n    void eval2_3 ( A0& a0, A1& a1\n                   , const nt2::policy<ext::matrix_>&\n                   ) const\n    {\n      nt2::container::table<type_t> work;\n      NT2_AS_TERMINAL_INOUT(o_semantic, r\n                           , boost::proto::child_c<0>(a0), work);\n      NT2_AS_TERMINAL_OUT  (o_semantic, x\n                           , boost::proto::child_c<0>(a1));\n      nt2::container::table<type_t>     tau;\n      nt2::container::table<nt2_la_int>  ip;\n      tie(x, tau, ip) = qr(r, nt2::raw_);\n\n      extract_qr(x, tau, r, nt2::policy<ext::raw_>());\n      assign_swap(boost::proto::child_c<0>(a1), x);\n      assign_swap(boost::proto::child_c<1>(a1), r);\n      boost::proto::child_c<2>(a1) = eye(numel(ip), nt2::meta::as_<type_t>())(nt2::_, ip);\n    }\n\n    //////////////////////////////////////////////////////////////////////////////////////////\n    /// extraction helpers\n    //////////////////////////////////////////////////////////////////////////////////////////\n\n    /// INTERNAL ONLY - Helper for Q/R extraction\n    template<typename XQ, typename TAU,typename R, typename CHOICE >\n    BOOST_FORCEINLINE\n    void extract_qr(XQ& xq, TAU& tau, R& r, CHOICE const &) const\n    {\n      nt2_la_int  m  = nt2::height(xq);\n      nt2_la_int  n  = nt2::width(xq);\n      typedef typename XQ::value_type xqtype_t;\n      r = nt2::triu(xq);\n\n      if (m>n)\n      {\n        nt2::container::table<xqtype_t> complete_q = nt2::eye(m,m, nt2::meta::as_<xqtype_t>());\n        nt2::mqr( boost::proto::value(xq)\n                , boost::proto::value(tau)\n                , boost::proto::value(complete_q) );\n        xq = complete_q;\n      }\n      else\n      {\n        if(m < n)\n        {\n          /// TODO: Remove when aliasing works\n          nt2::container::table<xqtype_t> local(xq);\n          xq = nt2::expand(local,nt2::of_size(m,m));\n        }\n        nt2::gqr( boost::proto::value(xq)\n                , boost::proto::value(tau));\n      }\n    }\n\n\n    /// INTERNAL ONLY - Helper for Q/R extraction economy mode\n    template<typename XQ, typename TAU,typename R >\n    BOOST_FORCEINLINE\n    void extract_qr(XQ& xq, TAU& tau, R& r, nt2::policy<ext::econ_> const &) const\n    {\n      nt2_la_int  m  = nt2::height(xq);\n      nt2_la_int  n  = nt2::width(xq);\n      typedef typename XQ::value_type xqtype_t;\n\n      // economy mode\n      r = nt2::triu(xq(_(1,nt2::min(n, m)), _) );\n\n      if(m < n)\n      {\n        /// TODO: Remove when aliasing works\n        nt2::container::table<xqtype_t> local(xq);\n        xq = nt2::expand(local,nt2::of_size(m,m));\n      }\n\n      nt2::gqr( boost::proto::value(xq)\n              , boost::proto::value(tau));\n    }\n\n    ////////////////////////////////////////////////////////////////////////////\n    // some utilitaries\n    ////////////////////////////////////////////////////////////////////////////\n    /// INTERNAL ONLY - Size of L/U\n    template<typename W>\n    BOOST_FORCEINLINE std::size_t dim(W const& work) const\n    {\n      return std::min(nt2::height(work),nt2::width(work));\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "4d3621fbe01af5fd7c22cc4c4352676e20112e3b", "size": 18431, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/functions/factorizations/qr.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/factorizations/qr.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/factorizations/qr.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 38.0020618557, "max_line_length": 95, "alphanum_fraction": 0.4842385112, "num_tokens": 5028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.2639943352241371}}
{"text": "\n#define OFDIS_INTERNAL\n#include <Eigen/Core>\n#include \"litiv/3rdparty/ofdis/refine_variational.hpp\"\n\ninline void local_image_delete(image_t *src) {\n    image_delete(src);\n}\n\ninline void local_image_delete(color_image_t *src) {\n    color_image_delete(src);\n}\n\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nofdis::VarRefClass<eInput,eOutput>::VarRefClass(const float * im_ao_in, const float * im_ao_dx_in, const float * im_ao_dy_in,\n                                                const float * im_bo_in, const float * im_bo_dx_in, const float * im_bo_dy_in,\n                                                const camparam* cpt_in,const camparam* cpo_in,const optparam* op_in, float *flowout) :\n        cpt(cpt_in), cpo(cpo_in), op(op_in) {\n    // initialize parameters\n    tvparams.alpha = op->tv_alpha;\n    tvparams.beta = 0.0f;  // for matching term, not needed for us\n    tvparams.gamma = op->tv_gamma;\n    tvparams.delta = op->tv_delta;\n    tvparams.n_inner_iteration = op->tv_innerit * (cpt->curr_lv+1);\n    tvparams.n_solver_iteration = op->tv_solverit;//5;\n    tvparams.sor_omega = op->tv_sor;\n    tvparams.tmp_quarter_alpha = 0.25f*tvparams.alpha;\n    tvparams.tmp_half_gamma_over3 = tvparams.gamma*0.5f/3.0f;\n    tvparams.tmp_half_delta_over3 = tvparams.delta*0.5f/3.0f;\n    tvparams.tmp_half_beta = tvparams.beta*0.5f;\n    float deriv_filter[3] = {0.0f, -8.0f/12.0f, 1.0f/12.0f};\n    deriv = convolution_new(2, deriv_filter, 0);\n    float deriv_filter_flow[2] = {0.0f, -0.5f};\n    deriv_flow = convolution_new(1, deriv_filter_flow, 0);\n    // copy flow initialization into FV structs\n    static int noparam = (eOutput==ofdis::FlowOutput_OpticalFlow)?2:1; // only horizontal displacements for stereo depth\n    std::vector<image_t*> flow_sep(noparam);\n    for(int i = 0; i < noparam; ++i )\n        flow_sep[i] = image_new(cpt->width,cpt->height);\n    for(int iy = 0; iy < cpt->height; ++iy) {\n        for(int ix = 0; ix<cpt->width; ++ix) {\n            int i = iy*cpt->width+ix;\n            int is = iy*flow_sep[0]->stride+ix;\n            for(int j = 0; j<noparam; ++j)\n                flow_sep[j]->c1[is] = flowout[i*noparam+j];\n        }\n    }\n    // copy image data into FV structs\n    InputImageType* im_ao, *im_bo;\n    im_ao = (InputImageType*)((eInput==ofdis::FlowInput_RGB)?(void*)color_image_new(cpt->width,cpt->height):(void*)image_new(cpt->width,cpt->height));\n    im_bo = (InputImageType*)((eInput==ofdis::FlowInput_RGB)?(void*)color_image_new(cpt->width,cpt->height):(void*)image_new(cpt->width,cpt->height));\n    copyimage(im_ao_in, im_ao);\n    copyimage(im_bo_in, im_bo);\n    // call solver\n    if(eOutput==ofdis::FlowOutput_OpticalFlow)\n        RefLevelOF(flow_sep[0], flow_sep[1], im_ao, im_bo);\n    else\n        RefLevelDE(flow_sep[0], im_ao, im_bo);\n    // copy flow result back\n    for(int iy = 0; iy < cpt->height; ++iy) {\n        for(int ix = 0; ix<cpt->width; ++ix) {\n            int i = iy*cpt->width+ix;\n            int is = iy*flow_sep[0]->stride+ix;\n            for(int j = 0; j<noparam; ++j)\n                flowout[i*noparam+j] = flow_sep[j]->c1[is];\n        }\n    }\n    // free FV structs\n    for(int i = 0; i < noparam; ++i)\n        image_delete(flow_sep[i]);\n    convolution_delete(deriv);\n    convolution_delete(deriv_flow);\n    local_image_delete(im_ao);\n    local_image_delete(im_bo);\n}\n\ninline void local_image_copy_pixel(image_t *img_t, int i, const float* img_st) {\n    img_t->c1[i] = (*img_st);\n}\n\ninline void local_image_copy_pixel(color_image_t *img_t, int i, const float*& img_st) {\n    img_t->c1[i] = (*img_st);\n    ++img_st; img_t->c2[i] =  (*img_st);\n    ++img_st; img_t->c3[i] =  (*img_st);\n}\n\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nvoid ofdis::VarRefClass<eInput,eOutput>::copyimage(const float* img, InputImageType* img_t) {\n    // remove image padding, start at first valid pixel\n    const float* img_st = img+((eInput==ofdis::FlowInput_RGB)?3:1)*(cpt->tmp_w+1)*(cpt->imgpadding);\n    for(int yi = 0; yi<cpt->height; ++yi) {\n        for(int xi = 0; xi<cpt->width; ++xi,++img_st) {\n            local_image_copy_pixel(img_t,yi*img_t->stride+xi,img_st);\n        }\n        img_st += ((eInput==ofdis::FlowInput_RGB)?3:1)*2*cpt->imgpadding;\n    }\n}\n\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nvoid ofdis::VarRefClass<eInput,eOutput>::RefLevelOF(image_t *wx, image_t *wy, const InputImageType* im1, const InputImageType* im2) {\n    int i_inner_iteration;\n    int width  = wx->width;\n    int height = wx->height;\n    int stride = wx->stride;\n    image_t *du = image_new(width,height), *dv = image_new(width,height), // the flow increment\n            *mask = image_new(width,height), // mask containing 0 if a point goes outside image boundary, 1 otherwise\n            *smooth_horiz = image_new(width,height), *smooth_vert = image_new(width,height), // horiz: (i,j) contains the diffusivity coeff. from (i,j) to (i+1,j)\n            *uu = image_new(width,height), *vv = image_new(width,height), // flow plus flow increment\n            *a11 = image_new(width,height), *a12 = image_new(width,height), *a22 = image_new(width,height), // system matrix A of Ax=b for each pixel\n            *b1 = image_new(width,height), *b2 = image_new(width,height); // system matrix b of Ax=b for each pixel\n    const auto lImageCreator = [&](){return (InputImageType*)((eInput==ofdis::FlowInput_RGB)?(void*)color_image_new(width,height):(void*)image_new(width,height));};\n    InputImageType *w_im2 = lImageCreator(), // warped second image\n                   *Ix = lImageCreator(), *Iy = lImageCreator(), *Iz = lImageCreator(), // first order derivatives\n                   *Ixx = lImageCreator(), *Ixy = lImageCreator(), *Iyy = lImageCreator(), *Ixz = lImageCreator(), *Iyz = lImageCreator(); // second order derivatives\n    // warp second image\n    fdf::image_warp<eInput>(w_im2, mask, im2, wx, wy);\n    // compute derivatives\n    fdf::get_derivatives<eInput>(im1, w_im2, deriv, Ix, Iy, Iz, Ixx, Ixy, Iyy, Ixz, Iyz);\n    // erase du and dv\n    image_erase(du);\n    image_erase(dv);\n    // initialize uu and vv\n    memcpy(uu->c1,wx->c1,wx->stride*wx->height*sizeof(float));\n    memcpy(vv->c1,wy->c1,wy->stride*wy->height*sizeof(float));\n    // inner fixed point iterations\n    for(i_inner_iteration=0; i_inner_iteration<tvparams.n_inner_iteration; i_inner_iteration++) {\n        //  compute robust function and system\n        fdf::compute_smoothness(smooth_horiz, smooth_vert, uu, vv, deriv_flow, tvparams.tmp_quarter_alpha );\n        //compute_data_and_match(a11, a12, a22, b1, b2, mask, wx, wy, du, dv, uu, vv, Ix, Iy, Iz, Ixx, Ixy, Iyy, Ixz, Iyz, desc_weight, desc_flow_x, desc_flow_y, tvparams.tmp_half_delta_over3, tvparams.tmp_half_beta, tvparams.tmp_half_gamma_over3);\n        fdf::compute_data<eInput>(a11, a12, a22, b1, b2, mask, wx, wy, du, dv, uu, vv, Ix, Iy, Iz, Ixx, Ixy, Iyy, Ixz, Iyz, tvparams.tmp_half_delta_over3, tvparams.tmp_half_beta, tvparams.tmp_half_gamma_over3);\n        fdf::sub_laplacian(b1, wx, smooth_horiz, smooth_vert);\n        fdf::sub_laplacian(b2, wy, smooth_horiz, smooth_vert);\n        // solve system\n    #ifdef WITH_OPENMP\n        sor_coupled_slow_but_readable(du, dv, a11, a12, a22, b1, b2, smooth_horiz, smooth_vert, tvparams.n_solver_iteration, tvparams.sor_omega); // slower but parallelized\n    #else\n        sor_coupled(du, dv, a11, a12, a22, b1, b2, smooth_horiz, smooth_vert, tvparams.n_solver_iteration, tvparams.sor_omega);\n    #endif\n        // update flow plus flow increment\n        int i;\n        v4sf *uup = (v4sf*) uu->c1, *vvp = (v4sf*) vv->c1, *wxp = (v4sf*) wx->c1, *wyp = (v4sf*) wy->c1, *dup = (v4sf*) du->c1, *dvp = (v4sf*) dv->c1;\n        for(i=0 ; i<height*stride/4 ; i++) {\n            (*uup) = (*wxp) + (*dup);\n            (*vvp) = (*wyp) + (*dvp);\n            uup+=1; vvp+=1; wxp+=1; wyp+=1;dup+=1;dvp+=1;\n        }\n    }\n    // add flow increment to current flow\n    memcpy(wx->c1,uu->c1,uu->stride*uu->height*sizeof(float));\n    memcpy(wy->c1,vv->c1,vv->stride*vv->height*sizeof(float));\n    // free memory\n    image_delete(du);\n    image_delete(dv);\n    image_delete(mask);\n    image_delete(smooth_horiz);\n    image_delete(smooth_vert);\n    image_delete(uu);\n    image_delete(vv);\n    image_delete(a11);\n    image_delete(a12);\n    image_delete(a22);\n    image_delete(b1);\n    image_delete(b2);\n    local_image_delete(w_im2);\n    local_image_delete(Ix);\n    local_image_delete(Iy);\n    local_image_delete(Iz);\n    local_image_delete(Ixx);\n    local_image_delete(Ixy);\n    local_image_delete(Iyy);\n    local_image_delete(Ixz);\n    local_image_delete(Iyz);\n}\n\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nvoid ofdis::VarRefClass<eInput,eOutput>::RefLevelDE(image_t *wx, const InputImageType* im1, const InputImageType* im2) {\n    int i_inner_iteration;\n    int width  = wx->width;\n    int height = wx->height;\n    int stride = wx->stride;\n    image_t *du = image_new(width,height), *wy_dummy = image_new(width,height), // the flow increment\n            *mask = image_new(width,height), // mask containing 0 if a point goes outside image boundary, 1 otherwise\n            *smooth_horiz = image_new(width,height), *smooth_vert = image_new(width,height), // horiz: (i,j) contains the diffusivity coeff. from (i,j) to (i+1,j)\n            *uu = image_new(width,height), // flow plus flow increment\n            *a11 = image_new(width,height), // system matrix A of Ax=b for each pixel\n            *b1 = image_new(width,height); // system matrix b of Ax=b for each pixel\n    image_erase(wy_dummy);\n    const auto lImageCreator = [&](){return (InputImageType*)((eInput==ofdis::FlowInput_RGB)?(void*)color_image_new(width,height):(void*)image_new(width,height));};\n    InputImageType *w_im2 = lImageCreator(), // warped second image\n                   *Ix = lImageCreator(), *Iy = lImageCreator(), *Iz = lImageCreator(), // first order derivatives\n                   *Ixx = lImageCreator(), *Ixy = lImageCreator(), *Iyy = lImageCreator(), *Ixz = lImageCreator(), *Iyz = lImageCreator(); // second order derivatives\n    // warp second image\n    fdf::image_warp<eInput>(w_im2, mask, im2, wx, wy_dummy);\n    // compute derivatives\n    fdf::get_derivatives<eInput>(im1, w_im2, deriv, Ix, Iy, Iz, Ixx, Ixy, Iyy, Ixz, Iyz);\n    // erase du and dv\n    image_erase(du);\n    // initialize uu and vv\n    memcpy(uu->c1,wx->c1,wx->stride*wx->height*sizeof(float));\n    // inner fixed point iterations\n    for(i_inner_iteration=0; i_inner_iteration<tvparams.n_inner_iteration; i_inner_iteration++) {\n        //  compute robust function and system\n        fdf::compute_smoothness(smooth_horiz, smooth_vert, uu, wy_dummy, deriv_flow, tvparams.tmp_quarter_alpha );\n        fdf::compute_data_DE<eInput>(a11, b1, mask, wx, du, uu, Ix, Iy, Iz, Ixx, Ixy, Iyy, Ixz, Iyz, tvparams.tmp_half_delta_over3, tvparams.tmp_half_beta, tvparams.tmp_half_gamma_over3);\n        fdf::sub_laplacian(b1, wx, smooth_horiz, smooth_vert);\n        // solve system\n        sor_coupled_slow_but_readable_DE(du, a11, b1, smooth_horiz, smooth_vert, tvparams.n_solver_iteration, tvparams.sor_omega);\n        // update flow plus flow increment\n        int i;\n        v4sf *uup = (v4sf*) uu->c1, *wxp = (v4sf*) wx->c1, *dup = (v4sf*) du->c1;\n        if(cpt->camlr==0) { // check if right or left camera, needed to truncate values above/below zero\n            for(i=0; i<height*stride/4; i++) {\n                (*uup) = __builtin_ia32_minps(   (*wxp) + (*dup)   ,  op->zero);\n                uup+=1; wxp+=1; dup+=1;\n            }\n        }\n        else {\n            for(i=0 ; i<height*stride/4; i++) {\n                (*uup) = __builtin_ia32_maxps(   (*wxp) + (*dup)   ,  op->zero);\n                uup+=1; wxp+=1; dup+=1;\n            }\n        }\n    }\n    // add flow increment to current flow\n    memcpy(wx->c1,uu->c1,uu->stride*uu->height*sizeof(float));\n    // free memory\n    image_delete(du);\n    image_delete(wy_dummy);\n    image_delete(mask);\n    image_delete(smooth_horiz);\n    image_delete(smooth_vert);\n    image_delete(uu);\n    image_delete(a11);\n    image_delete(b1);\n    local_image_delete(w_im2);\n    local_image_delete(Ix);\n    local_image_delete(Iy);\n    local_image_delete(Iz);\n    local_image_delete(Ixx);\n    local_image_delete(Ixy);\n    local_image_delete(Iyy);\n    local_image_delete(Ixz);\n    local_image_delete(Iyz);\n}\n\ntemplate class ofdis::VarRefClass<ofdis::FlowInput_Grayscale,ofdis::FlowOutput_OpticalFlow>;\ntemplate class ofdis::VarRefClass<ofdis::FlowInput_Gradient,ofdis::FlowOutput_OpticalFlow>;\ntemplate class ofdis::VarRefClass<ofdis::FlowInput_RGB,ofdis::FlowOutput_OpticalFlow>;\ntemplate class ofdis::VarRefClass<ofdis::FlowInput_Grayscale,ofdis::FlowOutput_StereoDepth>;\ntemplate class ofdis::VarRefClass<ofdis::FlowInput_Gradient,ofdis::FlowOutput_StereoDepth>;\ntemplate class ofdis::VarRefClass<ofdis::FlowInput_RGB,ofdis::FlowOutput_StereoDepth>;", "meta": {"hexsha": "35366cb3c84e067749ea9f9f2791018bdf5dd2a8", "size": 12925, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/ofdis/src/refine_variational.cpp", "max_stars_repo_name": "jpjodoin/litiv", "max_stars_repo_head_hexsha": "435556bea20d60816aff492f50587b1a2d748b21", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 97.0, "max_stars_repo_stars_event_min_datetime": "2015-10-16T04:32:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T07:04:02.000Z", "max_issues_repo_path": "3rdparty/ofdis/src/refine_variational.cpp", "max_issues_repo_name": "jpjodoin/litiv", "max_issues_repo_head_hexsha": "435556bea20d60816aff492f50587b1a2d748b21", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2016-07-01T16:37:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-10T06:09:39.000Z", "max_forks_repo_path": "3rdparty/ofdis/src/refine_variational.cpp", "max_forks_repo_name": "jpjodoin/litiv", "max_forks_repo_head_hexsha": "435556bea20d60816aff492f50587b1a2d748b21", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-11-17T05:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T09:30:28.000Z", "avg_line_length": 51.4940239044, "max_line_length": 248, "alphanum_fraction": 0.6561702128, "num_tokens": 3917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2639410808069891}}
{"text": "/*!\n * @file     mppi_new.cpp\n * @author   Giuseppe Rizzi\n * @date     01.07.2020\n * @version  1.0\n * @brief    description\n */\n\n#include <algorithm>\n\n#include <Eigen/Core>\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <random>\n#include <vector>\n\n#include \"mppi/core/config.h\"\n#include \"mppi/core/cost.h\"\n#include \"mppi/core/dynamics.h\"\n#include \"mppi/core/rollout.h\"\n#include \"mppi/core/solver.h\"\n\n#include \"mppi/utils/logging.h\"\n#include \"mppi/utils/savgol_filter.h\"\n\n#ifdef SIGNAL_LOGGER\n#include <signal_logger/signal_logger.hpp>\n#endif\n\nnamespace mppi {\n\nSolver::Solver(dynamics_ptr dynamics, cost_ptr cost, policy_ptr policy,\n               const Config& config)\n    : dynamics_(std::move(dynamics)),\n      cost_(std::move(cost)),\n      policy_(std::move(policy)),\n      config_(config) {\n  init_data();\n  init_threading();\n\n  if (config_.display_update_freq) {\n    start_time_ = std::chrono::high_resolution_clock::now();\n  }\n\n#ifdef SIGNAL_LOGGER\n  signal_logger::add(min_cost_, \"solver/rollouts/min_cost\");\n  signal_logger::add(max_cost_, \"solver/rollouts/max_cost\");\n  signal_logger::add(rollouts_cost_, \"solver/rollouts/costs\");\n  signal_logger::add(delay_steps_, \"solver/delay_steps\");\n  signal_logger::add(rate_, \"solver/rate\");\n  signal_logger::logger->updateLogger();\n#endif\n}\n\nvoid Solver::init_data() {\n  // TODO(giuseppe) this should be automatically computed when config is parsed\n  steps_ = static_cast<int>(std::ceil(config_.horizon / config_.step_size));\n  nx_ = dynamics_->get_state_dimension();\n  nu_ = dynamics_->get_input_dimension();\n\n  opt_roll_ = Rollout(steps_, nu_, nx_);\n  opt_roll_cache_ = Rollout(steps_, nu_, nx_);\n  nominal_.setZero(steps_, nu_);\n\n  weights_.resize(config_.rollouts, 1.0 / config_.rollouts);\n  rollouts_.resize(config_.rollouts, Rollout(steps_, nu_, nx_));\n  cached_rollouts_ = std::ceil(config_.caching_factor * config_.rollouts);\n\n  delay_steps_ = 0;\n  step_count_ = 0;\n  observation_set_ = false;\n  reference_set_ = false;\n}\n\nvoid Solver::init_filter() {}\n\nvoid Solver::init_threading() {\n  if (config_.threads > 1) {\n    std::cout << \"Using multithreading. Number of threads: \" << config_.threads\n              << std::endl;\n    pool_ = std::make_unique<ThreadPool>(config_.threads);\n    futures_.resize(config_.threads);\n\n    for (size_t i = 0; i < config_.threads; i++) {\n      dynamics_v_.push_back(dynamics_->create());\n      cost_v_.push_back(cost_->create());\n    }\n  }\n}\n\nvoid Solver::update_policy() {\n  if (!observation_set_) {\n    log_warning_throttle(1.0,\n                         \"Observation has never been set. Dropping update\");\n  } else if (!reference_set_) {\n    log_warning_throttle(1.0, \"Reference has never been set. Dropping update\");\n  } else {\n    auto start = std::chrono::steady_clock::now();  \n    update_delay();\n    copy_observation();\n\n    for (size_t i = 0; i < config_.substeps; i++) {\n      prepare_rollouts();\n      update_reference();      \n      sample_trajectories();\n      optimize();\n      filter_input();\n\n      stage_cost_ =\n          cost_->get_stage_cost(x0_internal_, opt_roll_.uu[0], t0_internal_);\n    }\n    swap_policies();\n    auto end = std::chrono::steady_clock::now();\n    rate_ = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() / 1e9;\n  }\n}\n\nvoid Solver::time_it() {\n  auto stop = std::chrono::high_resolution_clock::now();\n  auto duration =\n      std::chrono::duration_cast<std::chrono::microseconds>(stop - start_time_)\n          .count();\n  auto timing_string =\n      \"Time since optimization start: \" + std::to_string(duration) + \"[μs], \" +\n      std::to_string(duration / 1000000.0) + \"[s], \" +\n      std::to_string(1 / (duration / 1000000.0)) + \"[Hz]\";\n  log_info(timing_string);\n  start_time_ = std::chrono::high_resolution_clock::now();\n}\n\nvoid Solver::set_observation(const observation_t& x, const double t) {\n  {\n    std::unique_lock<std::shared_mutex> lock(state_mutex_);\n    x0_ = x;\n    reset_time_ = t;\n  }\n\n  // initialization of rollouts data\n  if (first_step_) {\n    copy_observation();\n    initialize_rollouts();\n    first_step_ = false;\n  }\n\n  observation_set_ = true;\n}\n\nvoid Solver::update_delay() {\n  delay_steps_ = std::ceil((reset_time_ - t0_internal_) / config_.step_size);\n  policy_->update_delay(delay_steps_);\n}\n\nvoid Solver::copy_observation() {\n  std::shared_lock<std::shared_mutex> lock(state_mutex_);\n  x0_internal_ = x0_;\n  t0_internal_ = reset_time_;\n}\n\nvoid Solver::initialize_rollouts() {\n  std::shared_lock<std::shared_mutex> lock_state(state_mutex_);\n  opt_roll_.clear();\n  std::fill(opt_roll_.uu.begin(), opt_roll_.uu.end(),\n            dynamics_->get_zero_input(x0_internal_));\n\n  std::shared_lock<std::shared_mutex> lock(rollout_cache_mutex_);\n  std::fill(opt_roll_cache_.xx.begin(), opt_roll_cache_.xx.end(), x0_internal_);\n  std::fill(opt_roll_cache_.uu.begin(), opt_roll_cache_.uu.end(),\n            dynamics_->get_zero_input(x0_internal_));\n  for (int i = 0; i < steps_; i++) {\n    opt_roll_cache_.tt[i] = t0_internal_ + config_.step_size * i;\n  }\n}\n\nvoid Solver::prepare_rollouts() {\n  // cleanup\n  rollouts_cost_.clear();\n  for (auto& roll : rollouts_) {\n    roll.clear_cost();\n    roll.valid = true;\n  }\n}\n\nvoid Solver::set_reference_trajectory(mppi::reference_trajectory_t& ref) {\n  if (ref.rr.size() != ref.tt.size()) {\n    std::stringstream error;\n    error << \"The reference trajectory state and time dimensions do not match: \"\n          << ref.rr.size() << \" != \" << ref.tt.size();\n    throw std::runtime_error(error.str());\n  }\n  std::unique_lock<std::shared_mutex> lock(reference_mutex_);\n  rr_tt_ref_ = ref;\n  reference_set_ = true;\n}\n\nvoid Solver::update_reference() {\n  std::shared_lock<std::shared_mutex> lock(reference_mutex_);\n  cost_->set_reference_trajectory(rr_tt_ref_);\n\n  if (config_.threads > 1) {\n    for (auto& cost : cost_v_) cost->set_reference_trajectory(rr_tt_ref_);\n  }\n\n}\n\nvoid Solver::sample_noise(input_t& noise) { sampler_->get_sample(noise); }\n\nvoid Solver::sample_trajectories_batch(dynamics_ptr& dynamics, cost_ptr& cost,\n                                       const size_t start_idx,\n                                       const size_t end_idx) {\n  observation_t x;\n  for (size_t k = start_idx; k < end_idx; k++) {\n    dynamics->reset(x0_internal_, t0_internal_);\n    x = x0_internal_;\n    double ts;\n    for (int t = 0; t < steps_; t++) {\n      ts = t0_internal_ + t * config_.step_size;\n      rollouts_[k].tt[t] = ts;\n      rollouts_[k].uu[t] = policy_->sample(ts, k);\n\n      // compute input-state stage cost\n      double cost_temp;\n      cost_temp = std::pow(config_.discount_factor, t) *\n                  cost->get_stage_cost(x, rollouts_[k].uu[t], ts);\n\n      if (std::isnan(cost_temp)) {\n        std::stringstream ss;\n        ss << \"Something went wrong ... dynamics diverged?\\n\" << std::endl;\n        ss << \"Rollout#\" << k << std::endl;\n        ss << \"Time  where diverged: \" << t << std::endl;\n        ss << \"State where diverged: \" << x.transpose() << std::endl;\n        ss << \"Previous state: \" << rollouts_[k].xx[t - 1].transpose()\n           << std::endl;\n        ss << \"Input where diverged: \" << rollouts_[k].uu[t].transpose();\n        ss << \"Previous input: \" << rollouts_[k].uu[t - 1].transpose()\n           << std::endl;\n        rollouts_[k].valid = false;\n        rollouts_[k].total_cost = std::numeric_limits<double>::infinity();\n        log_warning(ss.str());\n        break;\n      }\n\n      // store data\n      rollouts_[k].xx[t] = x;\n      rollouts_[k].cc(t) = cost_temp;\n      rollouts_[k].total_cost += cost_temp;\n\n      // integrate dynamics    auto start = std::chrono::steady_clock::now();\n      x = dynamics->step(rollouts_[k].uu[t], config_.step_size);\n    }\n  }\n}\n\nvoid Solver::sample_trajectories() {\n  policy_->shift(t0_internal_);\n  policy_->update_samples(weights_, cached_rollouts_);\n\n  if (config_.threads == 1) {\n    sample_trajectories_batch(dynamics_, cost_, 0, config_.rollouts);\n  } else {\n    for (size_t i = 0; i < config_.threads; i++) {\n      futures_[i] = pool_->enqueue(\n          std::bind(&Solver::sample_trajectories_batch, this,\n                    std::placeholders::_1, std::placeholders::_2,\n                    std::placeholders::_3, std::placeholders::_4),\n          dynamics_v_[i], cost_v_[i],\n          (size_t)i * config_.rollouts / config_.threads,\n          (size_t)(i + 1) * config_.rollouts / config_.threads);\n    }\n\n    for (size_t i = 0; i < config_.threads; i++) futures_[i].get();\n  }\n}\n\nvoid Solver::compute_weights() {\n  // keep all non diverged rollouts\n  double min_cost = std::numeric_limits<double>::max();\n  double max_cost = -min_cost;\n\n  for (size_t k = 0; k < config_.rollouts; k++) {\n    if (rollouts_[k].valid) {\n      const double& cost = rollouts_[k].total_cost;\n      min_cost = (cost < min_cost) ? cost : min_cost;\n      max_cost = (cost > max_cost) ? cost : max_cost;\n    }\n  }\n\n  min_cost_ = min_cost;   //*std::min_element(rollouts_cost_.begin(), rollouts_cost_.end());\n  max_cost_ = max_cost;   //*std::max_element(rollouts_cost_.begin(), rollouts_cost_.end());\n\n  double sum = 0.0;\n  for (size_t k = 0; k < config_.rollouts; k++) {\n    double modified_cost = config_.h * (rollouts_[k].total_cost - min_cost_) /\n                           (max_cost_ - min_cost_);\n\n    weights_[k] = rollouts_[k].valid ? std::exp(-modified_cost) : 0.0;\n    sum += weights_[k];\n  }\n  std::transform(weights_.begin(), weights_.end(), weights_.begin(),\n                 [&sum](double v) -> double { return v / sum; });\n}\n\nvoid Solver::optimize() {\n  // get new rollouts weights\n  compute_weights();\n\n  // update policy according to new weights\n  policy_->update(weights_, config_.alpha);\n\n  // retrieve the nominal policy for each time step\n  for (int t = 0; t < steps_; t++) {\n    opt_roll_.tt[t] = t0_internal_ + t * config_.step_size;\n    opt_roll_.uu[t] = policy_->nominal(t0_internal_ + t * config_.step_size);\n  }\n\n}\n\nvoid Solver::filter_input() {\n  // only if filter is available reset to the initial opt time\n  if (filter_) {\n    filter_->reset(x0_internal_, t0_internal_);\n  }\n\n  // reset the dynamics such that we rollout the dynamics again\n  // with the input we filter step after step (sequentially)\n  dynamics_->reset(x0_internal_, t0_internal_);\n  opt_roll_.xx[0] = x0_internal_;\n\n  // sequential filtering otherwise just nominal rollout\n  for (int t = 0; t < steps_ - 1; t++) {\n    if (filter_) {\n      filter_->apply(opt_roll_.xx[t], opt_roll_.uu[t], opt_roll_.tt[t]);\n      nominal_.row(t) = opt_roll_.uu[t].transpose();\n    }\n    opt_roll_.xx[t + 1] = dynamics_->step(opt_roll_.uu[t], config_.step_size);\n  }\n\n  // filter the last input in the sequence (if filter is available)\n  if (filter_) {\n    filter_->apply(opt_roll_.xx.back(), opt_roll_.uu.back(),\n                   opt_roll_.tt.back());\n    nominal_.bottomRows(1) = opt_roll_.uu.back().transpose();\n    policy_->set_nominal(nominal_);\n  }\n}\n\nvoid Solver::get_input(const observation_t& x, input_t& u, const double t) {\n  static double coeff;\n  static size_t idx;\n  {\n    std::shared_lock<std::shared_mutex> lock(rollout_cache_mutex_);\n    if (t < opt_roll_cache_.tt.front()) {\n      std::stringstream warning;\n      warning << \"Queried time \" << t << \" smaller than first available time \"\n              << opt_roll_cache_.tt.front();\n      log_warning_throttle(1.0, warning.str());\n      u = dynamics_->get_zero_input(x);\n    }\n\n    auto lower = std::lower_bound(opt_roll_cache_.tt.begin(),\n                                  opt_roll_cache_.tt.end(), t);\n    if (lower == opt_roll_cache_.tt.end()) {\n      std::stringstream warning;\n      warning << \"Queried time \" << t << \" larger than last available time \"\n              << opt_roll_cache_.tt.back();\n      log_warning_throttle(1.0, warning.str());\n      u = opt_roll_cache_.uu.back();\n      return;\n    }\n\n    idx = std::distance(opt_roll_cache_.tt.begin(), lower);\n    // first index (time)\n    if (idx == 0) {\n      u = opt_roll_cache_.uu.front();\n    }\n    // last index (time larget then last step)\n    else if (idx > opt_roll_cache_.steps_) {\n      u = opt_roll_cache_.uu.back();\n    }\n    // interpolate\n    else {\n      coeff = (t - *(lower - 1)) / (*lower - *(lower - 1));\n      u = (1 - coeff) * opt_roll_cache_.uu[idx - 1] +\n          coeff * opt_roll_cache_.uu[idx];\n    }\n  }\n}\n\nvoid Solver::get_diagonal_variance(Eigen::VectorXd& var) const {\n  var = sampler_->sigma().diagonal();\n}\n\nvoid Solver::get_input_state(const observation_t& x, observation_t& x_nom,\n                             input_t& u_nom, const double t) {\n  {\n    std::shared_lock<std::shared_mutex> lock(rollout_cache_mutex_);\n    if (t < opt_roll_cache_.tt.front()) {\n      std::stringstream warning;\n      warning << \"Queried time \" << t << \" smaller than first available time \"\n              << opt_roll_cache_.tt.front();\n      log_warning_throttle(1.0, warning.str());\n      x_nom = opt_roll_cache_.xx.front();\n      u_nom = dynamics_->get_zero_input(x);\n      return;\n    }\n\n    auto lower = std::lower_bound(opt_roll_cache_.tt.begin(),\n                                  opt_roll_cache_.tt.end(), t);\n    if (lower == opt_roll_cache_.tt.end()) {\n      std::stringstream warning;\n      warning << \"Queried time \" << t << \" larger than last available time \"\n              << opt_roll_cache_.tt.back();\n      log_warning_throttle(1.0, warning.str());\n      x_nom = opt_roll_cache_.xx.back();\n      u_nom = dynamics_->get_zero_input(x);\n      return;\n    }\n\n    size_t idx = std::distance(opt_roll_cache_.tt.begin(), lower);\n\n    // first\n    if (idx == 0) {\n      x_nom = opt_roll_cache_.xx.front();\n      u_nom = opt_roll_cache_.uu.front();\n    }\n    // last\n    else if (idx > opt_roll_cache_.steps_) {\n      x_nom = opt_roll_cache_.xx.back();\n      u_nom = opt_roll_cache_.uu.back();\n    }\n    // interpolate\n    else {\n      double coeff = (t - *(lower - 1)) / (*lower - *(lower - 1));\n      u_nom = (1 - coeff) * opt_roll_cache_.uu[idx - 1] +\n              coeff * opt_roll_cache_.uu[idx];\n      x_nom = opt_roll_cache_.xx[idx];  // TODO offer a way to also do\n                                        // interpolation of the state\n    }\n  }\n}\n\nbool Solver::get_optimal_rollout(observation_array_t& xx, input_array_t& uu) {\n  std::shared_lock<std::shared_mutex> lock(rollout_cache_mutex_);\n  auto lower = std::lower_bound(opt_roll_cache_.tt.begin(),\n                                opt_roll_cache_.tt.end(), reset_time_);\n  if (lower == opt_roll_cache_.tt.end()) return false;\n  size_t offset = std::distance(opt_roll_cache_.tt.begin(), lower);\n\n  // fill with portion of vector starting from current time\n  xx = observation_array_t(opt_roll_cache_.xx.begin() + offset,\n                           opt_roll_cache_.xx.end());\n  uu = input_array_t(opt_roll_cache_.uu.begin() + offset,\n                     opt_roll_cache_.uu.end());\n  return true;\n}\n\nvoid Solver::get_optimal_rollout(Rollout& r) {\n  std::shared_lock<std::shared_mutex> lock(rollout_cache_mutex_);\n  \n  // fill with portion of vector starting from current reset time\n  r.tt = time_array_t(opt_roll_cache_.tt.begin(),\n                      opt_roll_cache_.tt.end());\n\n  r.xx = observation_array_t(opt_roll_cache_.xx.begin(),\n                             opt_roll_cache_.xx.end());\n  \n  r.uu = input_array_t(opt_roll_cache_.uu.begin(),\n                       opt_roll_cache_.uu.end());\n}\n\nvoid Solver::swap_policies() {\n  std::unique_lock<std::shared_mutex> lock(rollout_cache_mutex_);\n  opt_roll_cache_ = opt_roll_;\n}\n\ntemplate <typename T>\nvoid Solver::shift_back(std::vector<T>& v_out, const T& fill,\n                        const int offset) {\n  std::rotate(v_out.begin(), v_out.begin() + offset, v_out.end());\n  std::fill(v_out.end() - offset, v_out.end(), fill);\n}\n\n// explicit instantiation\ntemplate void Solver::shift_back<Eigen::VectorXd>(\n    std::vector<Eigen::VectorXd>& v_out, const Eigen::VectorXd& fill,\n    const int offset);\n\nvoid Solver::print_cost_histogram() const {\n  constexpr int nbins = 10;\n  double delta = (max_cost_ - min_cost_) / nbins;\n\n  std::cout << \"Rollouts cost histogram \" << std::endl;\n  std::cout << \"Max: \" << max_cost_ << \", Min: \" << min_cost_\n            << \", delta: \" << delta << std::endl;\n  std::map<int, int> hist{};\n  for (const auto& cost : rollouts_cost_) {\n    ++hist[std::round((cost - min_cost_) / delta)];\n  }\n  for (auto p : hist) {\n    std::cout << std::setw(2) << p.first << ' ' << std::string(p.second, '*')\n              << '\\n';\n  }\n  std::cout << std::endl << std::endl;\n}\n\n}  // namespace mppi\n", "meta": {"hexsha": "8c2e32fbdb2b081d75b33015bf732366e5687f0b", "size": 16554, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mppi/src/core/solver.cpp", "max_stars_repo_name": "ethz-asl/sampling_based_control", "max_stars_repo_head_hexsha": "2b6b337e773991b7fe32bc617998dd33131abaa3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2021-12-04T06:59:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T05:16:52.000Z", "max_issues_repo_path": "mppi/src/core/solver.cpp", "max_issues_repo_name": "ethz-asl/sampling_based_control", "max_issues_repo_head_hexsha": "2b6b337e773991b7fe32bc617998dd33131abaa3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-07T20:07:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-07T20:07:20.000Z", "max_forks_repo_path": "mppi/src/core/solver.cpp", "max_forks_repo_name": "ethz-asl/sampling_based_control", "max_forks_repo_head_hexsha": "2b6b337e773991b7fe32bc617998dd33131abaa3", "max_forks_repo_licenses": ["BSD-3-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.5866141732, "max_line_length": 92, "alphanum_fraction": 0.6315090008, "num_tokens": 4377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2639119447734815}}
{"text": "#include <vector>\n#include <iostream>\n#include <stdio.h>      \n#include <stdlib.h>     \n#include <time.h>      \n#include <list>\n#include <string>\n#include <math.h>\n#include <fstream>\n#include <float.h>\n#include <boost/iostreams/stream.hpp> \n#include \"KNN_OpenMP_Code.h\"\n#include \"Metrics.h\"  \n#include <omp.h>\n#include <boost/iostreams/device/mapped_file.hpp> \n#include <boost/iostreams/stream.hpp>    \n\nusing boost::iostreams::mapped_file_source;\nusing boost::iostreams::stream;\t\nusing namespace std;\n\n/**\n * Read the output of linux command execution \n * @param  cmd  is the linux command to be executed\n * @return the output from the execution of the linux command\n */\nstd::string exec(const char* cmd) {\n\tstd::array<char, 128> buffer;\n\tstd::string result;\n\tstd::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, \"r\"), pclose);\n\tif (!pipe) {\n\t\tthrow std::runtime_error(\"popen() failed!\");\n\t}\n\twhile (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {\n\t\tresult += buffer.data();\n\t}\n\treturn result;\n}\n\n/**\n * Compute K-NN following the algorithm for shared-memory K-NN\n * @param filePath The full path to the input file containig the dataset.\n * @param N Size of Dataset without the header (i.e.(#Rows in dataset)-1).\t \n * @param Dim Dimension of Dataset (#Columns) \n * @param K the desired number of Nearest Neighbours to be computed\n * @param sampleRate The rate at which we do sampling\n * @param convThreshold Convergance Threshold\n * @param logFile The errors and informational messages are outputted to the log file \n * @param distanceMetric is the metric to compute the distance between the points in high-D space, by deafult should be euclidean\n * @param distanceV1 is the first optional variable needed for computing distance in some metrics\n * @param distanceV2 is the second optional variable needed for computing distance in some metrics\t\n * @param filePathOptionalArray The full path to optional array for the distance metric computation \t \n * @return B_Index indices of K-NN for each data point \t \n * @return B_Dist corresponding distance for K-NN indices stored in B_Index\t \n */\n//void computeKNNs(string filePath, const int N, const int Dim, const int K, float sampleRate, const int convThreshold,int** B_Index,double** B_Dist, ofstream& logFile){\nvoid computeKNNs(string filePath, const int N, const int Dim, const int K, float sampleRate, const int convThreshold,int** B_Index,double** B_Dist, ofstream& logFile, string distanceMetric, float distanceV1, float distanceV2, string filePathOptionalArray){ \n\n\tlogFile<<\"------------Starting K-NN Solution------------\"<<endl;\n\tcout<<\"------------Starting K-NN Solution------------\"<<endl;\n\t/**\n\t * A 2D Array containing the entire input dataset (read from filePath).\n\t */\n\tdouble** dataPoints = new double*[N];\n\tfor (int i = 0; i < N; ++i) { dataPoints[i] = new double[Dim]; }\n\t/**\n\t * corresponding flag for K-NN indices stored in B_Index\n\t */\n\tshort** B_IsNew = new short*[N];\n\tfor (int i = 0; i < N; ++i) { B_IsNew[i] = new short[K]; }\n\t/**\n\t * Data structure for new[v]\n\t */\n\tvector<int> *New_Index = new std::vector<int>[N];\n\t/**\n\t * Data structure for REVERSE(new[v]) or new'\n\t */\n\tvector<int> *Reverse_New_Index = new vector<int>[N];\n\t/**\n\t * Data Structure for SAMPLE(new'[v],pk)\n\t */\n\tvector<int> *Sampled_Reverse_New_Index = new vector<int>[N];\n\t/**\n\t * Data Structure for new[v] U SAMPLE(new'[v],pk)\n\t */\n\tvector<int> *New_Final_List = new vector<int>[N];\n\t/**\n\t * An approximation of zero in computing distances. Two points with the distance\n\t * smaller than epsilon are considered as one point.\n\t */\n\tdouble epsilon = 1e-10; \n\tshort* allEntriesFilled = new short[N];\n\t/**\n\t * At first, let's Read Dataset from Input File Using Memory Mapping\n\t */\n\tmapped_file_source mmap(filePath);\n    stream<mapped_file_source> is(mmap, std::ios::binary);\n\tif (is.fail())\n\t{\n\t\tlogFile << \"error in Opening Input File\" << endl;\n\t\tcout << \"error in Opening Input File\" << endl;\n\t\treturn ;\n\t}\n\t/**\n\t * Remove the header info\n\t */\n\tstring dummyLine;\n\tgetline(is, dummyLine);\n\t/**\n\t * Reading the Entire Dataset\n\t */\n\tfor (int i = 0; i < N; ++i) {\n\t\tstring temp, temp2;\n\t\tgetline(is, temp);\n\t\tfor (int j = 0; j < Dim; ++j) {\n\t\t\ttemp2 = temp.substr(0, temp.find(\",\"));\n\t\t\tdataPoints[i][j] = atof(temp2.c_str());\n\t\t\ttemp.erase(0, temp.find(\",\") + 1);\n\t\t}\n\t}\n\tmmap.close();\n\t/**\n\t * define a seed for random generator. Using a constant value produces\n\t * the same set of random numbers and is good for debugging. Alternatively,\n\t * we can select the seed number randomly as srand(time(NULL))\n\t */\n\tsrand(17);\n\t/**\n\t * Initialization of Arrays B_IsNew and B_Dist\n\t */\n\tfor (int i = 0; i < N; ++i) {\n\t\tallEntriesFilled[i]=0;\n\t\tfor (int j = 0; j < K; ++j) {\n\t\t\tB_IsNew[i][j] = 1;\n\t\t\tB_Dist[i][j] = -1.0;\n\t\t}\n\t}\n\t/**\n\t * Random Initialization of B_Index\n\t */\n\tint randomIndex, iter;\n\tfor (int i = 0; i < N; ++i) {\n\t\tfor (int j = 0; j < K; ++j) {\n\t\t\titer = 1;\n\t\t\twhile (iter) {\n\t\t\t\trandomIndex = rand() % N;\n\t\t\t\tif (randomIndex != i) {\n\t\t\t\t\tB_Index[i][j] = randomIndex;\n\t\t\t\t\titer = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t/**\n\t * Update list of K-NN indices for u1 (B_Index) if u2 is closer\n\t * <p>\n\t * This method correspondd to UPDATENN(B[u1],<u2,l,true>) in the paper\n\t * </p>\n\t * @param  Dist  represents B_Dist\n\t * @param  Index represents B_Index\n\t * @param  IsNew represents B_IsNew\n\t * @param  u1    the indice of point that we want to potentially update its K-NN with the point u2\n\t * @param  u2    the indice of potential K-NN fpr point u1\n\t * @param  distance the spatial distance between u1 and u2\n\t * @param  flag updates B_IsNew\n\t * @return 1 if B_Index[u1][.] is updated, 0 otherwise\n\t */\n\tauto UpdateNN = [&](int u1, int u2, double distance, int flag = 1) {\n\n\t\tif(allEntriesFilled[u1]==0){\t\t\n\t\t\tfor (int j = 0; j < K; j++) {\t\n\t\t\t\tif (B_Dist[u1][j] < 0) {\n\t\t\t\t\n\t\t\t\t    for (int jj = 0; jj < j; jj++) {if (B_Index[u1][jj] == u2) return 0;}\n\t\t\t\t\n\t\t\t\t\tB_Dist[u1][j] = distance;\n\t\t\t\t\tB_Index[u1][j] = u2;\n\t\t\t\t\tB_IsNew[u1][j] = flag;\n\t\t\t\t\tif (j==K-1) allEntriesFilled[u1]=1;\n\t\t\t\t\treturn 1;}\n\t\t\t}\n\t\t}\n\n\t\telse{\n\t\t\tfor (int j = 0; j < K; j++) {\n\t\t\t\tif (B_Index[u1][j] == u2) return 0;\n\t\t\t}\n\n\t\t\tdouble max = DBL_MIN;\n\t\t\tint index = -1;\n\t\t\tfor (int j = 0; j < K; j++) {\n\t\t\t\tif (B_Dist[u1][j] > max) {\n\t\t\t\t\tmax = B_Dist[u1][j];\n\t\t\t\t\tindex = j;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (index == -1) { logFile << \"Error\"; } \n\t\t\tif (distance < max) {\n\t\t\t\tB_Dist[u1][index] = distance;\n\t\t\t\tB_Index[u1][index] = u2;\n\t\t\t\tB_IsNew[u1][index] = flag;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\telse { return 0; }\n\t\t}\n\t\treturn 0;\n\t};\n\t/**\n\t * Main Loop of the Algorithm\n\t */\n\tbool iterate = true;\n\twhile (iterate) {\n\t\t/**\n\t\t * Create \"New\" for each Datapoint\n\t\t */\n\t\tfor (int i = 0; i < N; ++i) {\n\t\t\tfor (int j = 0; j < K; ++j) {\n\t\t\t\tif (float(rand() % 100) / 100 < sampleRate) {\n\t\t\t\t\tif (B_IsNew[i][j] == 1) {\n\t\t\t\t\t\tNew_Index[i].push_back(B_Index[i][j]);\n\t\t\t\t\t\tB_IsNew[i][j] = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t/**\n\t\t * Create \"New'\"(or REVERSE(\"New\")) for each Datapoint\n\t\t */\n\t\tfor (int i = 0; i < N; ++i) {\n\t\t\tfor (size_t j = 0; j < New_Index[i].size(); ++j) {\n\t\t\t\tReverse_New_Index[New_Index[i][j]].push_back(i);\n\t\t\t}\n\t\t}\n\t\t/**\n\t\t * Random Sampling from \"New'\"\n\t\t */\n\t\tfor (int i = 0; i < N; ++i) {\n\t\t\tfor (size_t j = 0; j < Reverse_New_Index[i].size(); ++j) {\n\t\t\t\tif (float(rand() % 100) / 100 < sampleRate) {\n\t\t\t\t\tSampled_Reverse_New_Index[i].push_back(Reverse_New_Index[i][j]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t/**\n\t\t * \"New\"= \"New\" U SAMPLE(\"New'\", pK)\n\t\t */\n\t\tfor (int i = 0; i < N; ++i) {\n\t\t\tfor (size_t j = 0; j < New_Index[i].size(); ++j) {\n\t\t\t\tNew_Final_List[i].push_back(New_Index[i][j]);\n\t\t\t}\n\t\t\tfor (size_t j = 0; j < Sampled_Reverse_New_Index[i].size(); ++j) {\n\t\t\t\tNew_Final_List[i].push_back(Sampled_Reverse_New_Index[i][j]);\n\t\t\t}\n\t\t}\n\t\t/**\n\t\t * c=c+UPDATENN(B[u1],<u2,l,true>)\n\t\t */\n\t\tint c_criteria = 0;\n\t\tint abort=0;\n\t\t\n\t\tfor (int i = 0; i < N; ++i) {\n\t\t\tif (abort != 0) break;\n\t\t\t\n            #pragma omp parallel for schedule(dynamic) \n\t\t\tfor (int it = 0; it < New_Final_List[i].size(); ++it) {\n\t\t\t\tint par1= New_Final_List[i][it];\n                \n\t\t\t\tfor (int it2 = it+1; it2 < New_Final_List[i].size(); ++it2) {\n\t\t\t\t\tint par2= New_Final_List[i][it2];\n\t\t\t\t\tif (par1 != par2 && abort ==0) {\n\t\t\t\t\t\t/**\n\t\t\t\t\t\t * computes spatial distance between two points based on the chosen Metric\n\t\t\t\t\t\t * @param distanceMetric the metric to compute the distance between the points in high-D space\n\t\t\t\t\t\t * @param dataPoints represents input dataPoints read from filePath\n\t\t\t\t\t\t * @param *it and *it2 indices of the desired points in input dataset\n\t\t\t\t\t\t * @param Dim is #columns (or features) in input dataset\n\t\t\t\t\t\t * @param distanceV1 is the first optional variable needed for computing distance in some metrics\n\t\t\t\t\t\t * @param distanceV2 is the second optional variable needed for computing distance in some metrics\t\n\t\t\t\t\t\t * @param filePathOptionalArray The full path to optional array for the distance metric computation \n\t\t\t\t\t\t * @param logFile The errors and informational messages are outputted to the log file \n\t\t\t\t\t\t * @return spatial distance between points two points \n\t\t\t\t\t\t */\t\t\t\t\t\n\t\t\t\t\t\tdouble dista = computeDistance (distanceMetric, dataPoints, par1, par2, Dim, distanceV1, distanceV2, filePathOptionalArray, logFile);\n\n\t\t\t\t\t\tif (dista < epsilon) {\n\t\t\t\t\t\t\tlogFile << \"Found Duplicate Data for Points \"<< par1 << \" and \" << par2 <<endl;; \n\t\t\t\t\t\t\tcout << \"Found Duplicate Data for Points \"<< par1 << \" and \" << par2 <<endl; \n\t\t\t\t\t\t\tabort=1;\n\t\t\t\t\t\t\titerate = false; \n\t\t\t\t\t\t}\n\t\t\t\t\t\t#pragma omp critical\n\t\t\t\t\t    {\n\t\t\t\t\t\t    c_criteria += UpdateNN(par1, par2, dista, 1);\n\t\t\t\t\t\t    c_criteria += UpdateNN(par2, par1, dista, 1);\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\tlogFile << \"c_criteria = \" << c_criteria << \" With Threshold Convergence of \" << convThreshold << endl;\n\t\tcout << \"c_criteria = \" << c_criteria << \" With Threshold Convergence of \" << convThreshold << endl;\n\t\tif (c_criteria < convThreshold) { iterate = false; }\n\t\t/**\n\t\t * Clear the contents of the used data structures\n\t\t */\n\t\tfor (int i = 0; i < N; ++i) {\n\t\t\tNew_Index[i].clear();\n\t\t\tReverse_New_Index[i].clear();\n\t\t\tSampled_Reverse_New_Index[i].clear();\n\t\t\tNew_Final_List[i].clear();\n\t\t}\n\t}\t\n\n\tdelete[] dataPoints;\n\tlogFile<<\"------------Ending of K-NN Solution------------\"<<endl;\n\tcout<<\"------------Ending of K-NN Solution------------\"<<endl;\n\treturn;\n}\n\n\n", "meta": {"hexsha": "3de88d153478fb2b47155bf1438e70a2ada78b33", "size": 10316, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dimension_reduction/UMAP/Shared-Memory-OpenMP/KNN_OpenMP_Code.cpp", "max_stars_repo_name": "mmvih/polus-plugins", "max_stars_repo_head_hexsha": "c424938e3f35900758f7d74f3dfec2adfb3228fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dimension_reduction/UMAP/Shared-Memory-OpenMP/KNN_OpenMP_Code.cpp", "max_issues_repo_name": "mmvih/polus-plugins", "max_issues_repo_head_hexsha": "c424938e3f35900758f7d74f3dfec2adfb3228fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dimension_reduction/UMAP/Shared-Memory-OpenMP/KNN_OpenMP_Code.cpp", "max_forks_repo_name": "mmvih/polus-plugins", "max_forks_repo_head_hexsha": "c424938e3f35900758f7d74f3dfec2adfb3228fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-26T19:23:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T19:23:57.000Z", "avg_line_length": 32.1370716511, "max_line_length": 257, "alphanum_fraction": 0.6202985653, "num_tokens": 3082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.2638512725916295}}
{"text": "/**\n * $Id$\n *\n * Copyright (C)\n * 2014 - $Date$\n *     Martin Wolf <ndhist@martin-wolf.org>\n *\n * This file is distributed under the BSD 2-Clause Open Source License\n * (See LICENSE file).\n *\n */\n#ifndef NDHIST_AXES_CONSTANT_BIN_WIDTH_AXIS_HPP_INCLUDED\n#define NDHIST_AXES_CONSTANT_BIN_WIDTH_AXIS_HPP_INCLUDED 1\n\n#include <cmath>\n#include <string>\n#include <sstream>\n\n#include <boost/shared_ptr.hpp>\n\n#include <boost/numpy/iterators/flat_iterator.hpp>\n\n#include <ndhist/axis.hpp>\n#include <ndhist/error.hpp>\n\nnamespace bn = boost::numpy;\n\nnamespace ndhist {\nnamespace axes {\n\n/**\n * @class ConstantBinWidthAxis\n *     This class provides an axis with underlaying constant bin widths. To the\n *     user the bin widths could still vary. But as long as there is a value\n *     transformation available that transforms the bin edge values, which\n *     contuct the non-constant bin widths, into a linear scale with constant\n *     bin widths, this class can be used as axis with good performance.\n *\n *     The ValueTransform class must provide two static methods:\n *\n *         AxisValueType transform(AxisValueType const value)\n *\n *     and\n *\n *         AxisValueType back_transform(AxisValueType const value)\n *\n *     for transforming an edge value into linear scale and back.\n */\ntemplate <typename AxisValueType, typename ValueTransform>\nclass ConstantBinWidthAxis\n  : public Axis\n{\n  public:\n    typedef AxisValueType\n            axis_value_type;\n\n    typedef ValueTransform\n            value_transform_type;\n\n    typedef bn::iterators::single_value<axis_value_type>\n            axis_value_type_traits;\n\n    typedef Axis\n            base;\n\n    typedef ConstantBinWidthAxis<axis_value_type, value_transform_type>\n            type;\n\n  protected:\n    /// The number of bins, including the possible under- and overflow bins.\n    intptr_t n_bins_;\n\n    /// The constant width of the bins. Remember, that the widths of the\n    /// possible under- and overflow bins could be different from this value.\n    axis_value_type bin_width_;\n\n    /// The lower edge of the first bin with constant bin width, i.e. excluding\n    /// the underflow bin.\n    axis_value_type min_;\n\n    /// The lower edge of the underflow bin.\n    axis_value_type underflow_edge_;\n\n    /// The upper edge of the overflow bin.\n    axis_value_type overflow_edge_;\n\n    /// The axis value type traits object, needed as temporary storage for\n    /// dereferencing value pointers.\n    axis_value_type_traits mutable avtt_;\n\n  public:\n    ConstantBinWidthAxis(\n        bn::ndarray const & edges\n      , std::string const & label\n      , std::string const & name\n      , bool has_underflow_bin\n      , bool has_overflow_bin\n      , bool is_extendable\n      , intptr_t extension_max_fcap\n      , intptr_t extension_max_bcap\n    )\n      : Axis(\n            edges.get_size()-1\n          , edges.get_dtype()\n          , label\n          , name\n          , has_underflow_bin\n          , has_overflow_bin\n          , is_extendable\n          , extension_max_fcap\n          , extension_max_bcap\n        )\n    {\n        // Set up the axis's function pointers.\n        create_fct_                     = &type::create;\n        get_bin_index_fct_              = &type::get_bin_index;\n        get_binedges_ndarray_fct_       = &type::get_binedges_ndarray;\n        get_lower_binedges_ndarray_fct_ = &base::get_lower_binedges_ndarray<type>;\n        get_upper_binedges_ndarray_fct_ = &base::get_upper_binedges_ndarray<type>;\n        get_bincenters_ndarray_fct_     = &base::get_bincenters_ndarray<type>;\n        get_binwidths_ndarray_fct_      = &base::get_binwidths_ndarray<type>;\n        get_n_bins_fct_                 = &type::get_n_bins;\n        request_extension_fct_          = &type::request_extension;\n        extend_fct_                     = &type::extend;\n        create_axis_slice_fct_          = &base::create_axis_slice<type>;\n        deepcopy_fct_                   = &type::deepcopy;\n\n        //std::cout << \"edges.shape(0): \"<< edges.shape(0)<<std::endl;\n        n_bins_ = edges.shape(0) - 1;\n        //std::cout << \"n_bins_: \"<< n_bins_<<std::endl;\n        if(n_bins_ <= 0)\n        {\n            std::stringstream ss;\n            ss << \"The edges array does not contain enough edges! It must \"\n               << \"contain at least two edges! Remember \"\n               << \"that the edges of the out-of-range bins, need to be \"\n               << \"specified as well, when the axis is not extendable and is \"\n               << \"supposed to have such bins.\";\n            throw ValueError(ss.str());\n        }\n\n        bn::iterators::flat_iterator< axis_value_type_traits > edges_iter(edges);\n\n        // Set and skip the underflow edge.\n        if(has_underflow_bin_)\n        {\n            underflow_edge_ = value_transform_type::transform(*edges_iter);\n            ++edges_iter;\n        }\n\n        min_ = value_transform_type::transform(*edges_iter);\n        ++edges_iter;\n        if(   edges_iter.is_end()\n           || (has_overflow_bin_ && edges_iter.get_iter_index() == n_bins_)\n          )\n        {\n            // Only one bin (ie. the underflow or overflow bin) was given. So\n            // we set the bin width to one.\n            // Note: The bin_width_ property is used only for internal\n            //       calculation. The bin width seen by the user is still\n            //       calculated through the actual bin edges.\n            bin_width_ = axis_value_type(1);\n        }\n        else\n        {\n            axis_value_type const value = value_transform_type::transform(*edges_iter);\n            bin_width_ = value - min_;\n        }\n\n        // Set the overflow edge.\n        if(has_overflow_bin_)\n        {\n            edges_iter.advance(edges_iter.distance_to(edges_iter.end()) - 1);\n            overflow_edge_ = value_transform_type::transform(*edges_iter);\n        }\n    }\n\n    /**\n     * Copy constructor.\n     */\n    ConstantBinWidthAxis(ConstantBinWidthAxis const & other)\n      : Axis(other)\n      , n_bins_((*static_cast<type const *>(&other.get_axis_base())).n_bins_)\n      , bin_width_((*static_cast<type const *>(&other.get_axis_base())).bin_width_)\n      , min_((*static_cast<type const *>(&other.get_axis_base())).min_)\n      , underflow_edge_((*static_cast<type const *>(&other.get_axis_base())).underflow_edge_)\n      , overflow_edge_((*static_cast<type const *>(&other.get_axis_base())).overflow_edge_)\n    {\n        //std::cout << \"ConstantBinWidthAxis:: Copy constructor.\" << std::endl<<std::flush;\n    }\n\n    static\n    boost::shared_ptr<Axis>\n    create(\n        boost::numpy::ndarray const & edges\n      , std::string const & label\n      , std::string const & name\n      , bool has_underflow_bin\n      , bool has_overflow_bin\n      , bool is_extendable\n      , intptr_t extension_max_fcap\n      , intptr_t extension_max_bcap\n    )\n    {\n        return boost::shared_ptr<Axis>(new type(\n            edges\n          , label\n          , name\n          , has_underflow_bin\n          , has_overflow_bin\n          , is_extendable\n          , extension_max_fcap\n          , extension_max_bcap\n        ));\n    }\n\n    static\n    intptr_t\n    get_n_bins(Axis const & axisbase)\n    {\n        type const & axis = *static_cast<type const *>(&axisbase);\n        //std::cout << \"constant_bin_width_axis: get_n_bins, axis_ptr: \"<< &axis<< \", axis.n_bins_=\"<<axis.n_bins_ <<std::endl;\n        return axis.n_bins_;\n    }\n\n    static\n    bn::ndarray\n    get_binedges_ndarray(Axis const & axisbase)\n    {\n        type const & axis = *static_cast<type const *>(&axisbase);\n\n        intptr_t shape[1];\n        shape[0] = axis.n_bins_ + 1;\n        bn::ndarray edges_arr = bn::empty(1, shape, bn::dtype::get_builtin<axis_value_type>());\n        bn::iterators::flat_iterator< axis_value_type_traits > iter(edges_arr);\n        if(axis.has_underflow_bin_)\n        {\n            // Set the underflow edge.\n            iter.set_value(value_transform_type::back_transform(axis.underflow_edge_));\n            ++iter;\n        }\n        intptr_t idx = 0;\n        while(! iter.is_end())\n        {\n            axis_value_type const value = axis.min_ + idx*axis.bin_width_;\n            iter.set_value(value_transform_type::back_transform(value));\n\n            ++idx;\n            ++iter;\n        }\n        if(axis.has_overflow_bin_)\n        {\n            // Set the overflow edge.\n            iter.advance(-1);\n            iter.set_value(value_transform_type::back_transform(axis.overflow_edge_));\n        }\n\n        return edges_arr;\n    }\n\n    static\n    intptr_t\n    get_bin_index(Axis const & axisbase, char * value_ptr, axis::out_of_range_t & oor_flag)\n    {\n        type const & axis = *static_cast<type const *>(&axisbase);\n\n        typename axis_value_type_traits::value_cref_type value_cref = axis_value_type_traits::dereference(axis.avtt_, value_ptr);\n        axis_value_type const value = value_transform_type::transform(value_cref);\n        //std::cout << \"Got value = \"<<value<<std::endl;\n\n        if(axis.has_underflow_bin_)\n        {\n            if(value < axis.underflow_edge_)\n            {\n                // The value falls even left to the underflow bin.\n                oor_flag = axis::OOR_UNDERFLOW;\n                return -1;\n            }\n            if(value < axis.min_)\n            {\n                // The value falls into the underflow bin.\n                //std::cout << \"Got value in underflow bin\"<< std::endl;\n                oor_flag = axis::OOR_NONE;\n                return 0;\n            }\n        }\n        else\n        {\n            if(value < axis.min_)\n            {\n                //std::cout << \"underflow: \" << value << \", min = \"<< data.min_ << std::endl;\n                oor_flag = axis::OOR_UNDERFLOW;\n                return -1;\n            }\n        }\n\n        // The value is >= min_.\n        intptr_t const idx = (value - axis.min_)/axis.bin_width_;\n\n        if(axis.has_overflow_bin_)\n        {\n            if(idx < axis.n_bins_-2)\n            {\n                // The value falls into the axis range (excluding the overflow\n                // bin).\n                //std::cout << \"Got value in normal bin\"<< std::endl;\n                oor_flag = axis::OOR_NONE;\n                return idx + axis.has_underflow_bin_;\n            }\n            if(value < axis.overflow_edge_)\n            {\n                // The value falls into the overflow bin.\n                oor_flag = axis::OOR_NONE;\n                return axis.n_bins_-1;\n            }\n\n            // The value falls even right to the overflow bin.\n            oor_flag = axis::OOR_OVERFLOW;\n            return -1;\n        }\n        else\n        {\n            if(idx >= axis.n_bins_)\n            {\n                //std::cout << \"overflow: \" << value << \", idx = \"<< idx << std::endl;\n                oor_flag = axis::OOR_OVERFLOW;\n                return -1;\n            }\n            //std::cout << \"value \" << value << \" at \" << idx << std::endl;\n            oor_flag = axis::OOR_NONE;\n            return idx + axis.has_underflow_bin_;\n        }\n    }\n\n    // Determines the number of extra bins needed to the left (negative number\n    // returned) or to the right (positive number returned) of the current axis\n    // range.\n    static\n    intptr_t\n    request_extension(Axis const & axisbase, char * value_ptr, axis::out_of_range_t const oor_flag)\n    {\n        type const & axis = *static_cast< type const *>(&axisbase);\n\n        axis_value_type_traits avtt;\n        typename axis_value_type_traits::value_ref_type value_cref = axis_value_type_traits::dereference(avtt, value_ptr);\n        axis_value_type const value = value_transform_type::transform(value_cref);\n\n        if(oor_flag == axis::OOR_UNDERFLOW)\n        {\n            intptr_t const n_extra_bins = std::ceil((std::abs(value - axis.min_) / axis.bin_width_));\n            //std::cout << \"request_autoscale (underflow): \" << n_extra_bins << \" extra bins.\" << std::endl<< std::flush;\n            return -n_extra_bins;\n        }\n        else if(oor_flag == axis::OOR_OVERFLOW)\n        {\n            intptr_t const n_extra_bins = intptr_t((value - axis.min_)/axis.bin_width_) - (axis.n_bins_-1);\n            //std::cout << \"request_autoscale (overflow): \" << n_extra_bins << \" extra bins.\" << std::endl<< std::flush;\n            return n_extra_bins;\n        }\n\n        return 0;\n    }\n\n    static\n    void\n    extend(Axis & axisbase, intptr_t f_n_extra_bins, intptr_t b_n_extra_bins)\n    {\n        type & axis = *static_cast< type *>(&axisbase);\n\n        if(f_n_extra_bins > 0)\n        {\n            axis.n_bins_ += f_n_extra_bins;\n            axis.min_    -= f_n_extra_bins * axis.bin_width_;\n        }\n        if(b_n_extra_bins > 0)\n        {\n            axis.n_bins_ += b_n_extra_bins;\n        }\n    }\n\n    static\n    boost::shared_ptr<Axis>\n    deepcopy(Axis const & axisbase)\n    {\n        type const & axis = *static_cast<type const *>(&axisbase);\n        return boost::shared_ptr<Axis>(new type(axis));\n    }\n};\n\n}//namespace axes\n}//namespace ndhist\n\n#endif // NDHIST_AXES_CONSTANT_BIN_WIDTH_AXIS_HPP_INCLUDED\n", "meta": {"hexsha": "8c2f4f95e07df77081e3427ed02a920c205499ea", "size": 13052, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ndhist/axes/constant_bin_width_axis.hpp", "max_stars_repo_name": "martwo/ndhist", "max_stars_repo_head_hexsha": "193cef3585b5d0277f0721bb9c3a1e78cc67cf1f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/ndhist/axes/constant_bin_width_axis.hpp", "max_issues_repo_name": "martwo/ndhist", "max_issues_repo_head_hexsha": "193cef3585b5d0277f0721bb9c3a1e78cc67cf1f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ndhist/axes/constant_bin_width_axis.hpp", "max_forks_repo_name": "martwo/ndhist", "max_forks_repo_head_hexsha": "193cef3585b5d0277f0721bb9c3a1e78cc67cf1f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1269035533, "max_line_length": 129, "alphanum_fraction": 0.589488201, "num_tokens": 3055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.2638512725916295}}
{"text": "/* \n\tAuthors: Darya Filippova, Geet Duggal, Rob Patro\n\tdfilippo | geet | robp @cs.cmu.edu\n        See LICENSE.txt included with this distribution.\n*/\n\n#include <iostream>\n#include <vector>\n#include <fstream>\n#include <string>\n\n#include <boost/range/irange.hpp>\n#include <boost/iostreams/filtering_streambuf.hpp>\n#include <boost/iostreams/copy.hpp>\n#include <boost/iostreams/filter/gzip.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <cmath>\n#include \"ArmatusUtil.hpp\"\n#include \"ArmatusParams.hpp\"\n#include \"IntervalScheduling.hpp\"\n#include \"ArmatusParams.hpp\"\n#include \"ArmatusDAG.hpp\"\n\n\nMatrixProperties parseGZipMatrix(string path, int resolution, string chrom) {\n\tMatrixProperties prop;\n\n    prop.matrix = std::make_shared<SparseMatrix>();\n\n\tifstream file(path, ios_base::in | ios_base::binary);\n    if (!file.good()) {\n        std::cerr << \"Couldn't read file \" << path << std::endl;\n        std::exit(1);\n    }\n    assert(file.good());\n    boost::iostreams::filtering_streambuf<boost::iostreams::input> in;\n    in.push(boost::iostreams::gzip_decompressor());\n    in.push(file);\n\n    string line;\n    std::istream incoming(&in);\n    bool firstLine = true;\n    size_t i = 0;\n    double tot = 0.0;\n    size_t nedge = 0;\n    while ( getline(incoming, line) ) {\n    \tvector<string> parts;\n        boost::trim(line);\n\t\tboost::split(parts, line, boost::is_any_of(\"\\t\"));\n        \n        if (firstLine) { \n            //if (parts.size() - 3 < 100) {\n            if (parts.size() < 100) {\n                cerr << \"[INFO] Matrix is smaller than the recommended minimum size of 101.\" << endl;\n                // exit(1);\n            }\n            prop.matrix->resize(parts.size(), parts.size(), false);\n            prop.chrom = chrom;\n            prop.resolution = resolution;\n            cerr << prop.chrom << \" at resolution \" << prop.resolution << \"bp\" << endl;\n            firstLine = false;\n        }\n\n        if (parts.size() != prop.matrix->size2()) {\n            std::cerr << \"Error: row \" << i << \" has \" << parts.size() \n                      << \" entries, but I was expecting \" << prop.matrix->size2() << std::endl;\n            std::exit(3);\n        }\n\n        if (i >= prop.matrix->size2()) {\n            std::cerr << \"Error: I was expecting \" << prop.matrix->size2() \n                      << \" rows, but there are more than that in the matrix file.\" << std::endl;\n            std::exit(3);\n        }\n\n        \n        for (size_t j : boost::irange(i, parts.size())) {\n            double e  = stod(parts[j]);\n            if (e > 0.0) {\n                size_t row = j;\n                prop.matrix->insert_element(i, row, e);\n                tot += e;\n                nedge++;\n            }   \n        }\n\n    \t++i;\n        if ( i % 1000 == 0 ) { std::cerr << \"line \" << i << \"\\n\"; }\n        if (incoming.eof()) break;\n    }\n\n    // check that we read # of rows = to the number of columns in the matrix\n    if (prop.matrix->size2() != i) {\n        std::cerr << \"Error: it doesn't look like your matrix file had enough rows.\" << std::endl;\n        std::cerr << \"Error: expecting \" << prop.matrix->size2() << \" but saw \" << i << std::endl;\n        std::exit(1);\n    }\n    return prop;\n}\n\nMatrixProperties parseRaoMatrix(string path, int resolution, string chrom, bool noNormalization) {\n\tMatrixProperties prop;\n    int n;\n    int M = 0;\n    auto rawCountPath = path + \".RAWobserved\";\n\n    {\n\t    ifstream file(rawCountPath);\n        if (!file.good()) {\n            std::cerr << \"Couldn't read file: \" << rawCountPath << std::endl;\n            std::exit(1);\n        }\n        assert(file.good());\n\n        string line;\n        int v, w;\n        double count;\n        int maxv = 0;\n        while ( file >> v >> w >> count )  {\n            if (v > maxv) maxv = v;\n            if (w > maxv) maxv = w;\n            M += 1;\n        }\n        n = maxv/resolution+1;\n        prop.chrom = chrom;\n        prop.resolution = resolution;\n        cerr << \"Building matrix for chromosome \" << prop.chrom << \" at resolution \" << prop.resolution << \"bp with \" << n << \" rows.\" << endl;\n    }\n\n    vector<double> KRnormalization;\n    auto KRPath = path + \".KRnorm\";\n    if (!noNormalization)\n    {\n        cerr << \"Reading KR normalization counts\" << endl;\n\t    ifstream file(KRPath);\n        string line;\n        while( getline(file, line) ) {\n            KRnormalization.push_back(stod(line));\n        }\n    }\n    cout << \"Initializing matrix to zero elements\" << endl;\n    prop.matrix = std::make_shared<SparseMatrix>(n,n,M);\n    for (int i = 0; i < n; i++) {\n        for (int j =0; j < n; j++) {\n            prop.matrix->insert_element(i,j, 0.0);\n        }\n    }\n    {\n\t    ifstream file(rawCountPath);\n\n        string line;\n        int v, w;\n        double count;\n        int m = 0;\n        while ( file >> v >> w >> count )  {\n            size_t i = v/resolution;\n            size_t j = w/resolution;\n            if (noNormalization) {\n                prop.matrix->insert_element(i, j, log(count));\n            }\n            else {\n                double ki = KRnormalization[i];\n                double kj = KRnormalization[j];\n                if (!std::isnan(ki) and !std::isnan(kj) and ki > 0 and kj > 0) {\n                    prop.matrix->insert_element(i, j, log(count/(ki*kj)));\n                    // cout << i << \"\\t\" << j << \"\\t\" << count << \"\\t\" << count/(ki*kj) << endl;\n                }\n                else {\n                    // Maybe write NaN or inf issue to log/warning file\n                }\n            }\n            m++;\n            if ( m % 100000 == 0 ) { std::cerr << \"\" << float(m)/M*100 << \"%\\n\"; }\n        }\n    }\n\n    return prop;\n}\n\nMatrixProperties parseSparseMatrix(string filepath, int resolution, string chrom) {\n  MatrixProperties prop;\n  int n;\n  int M=0;\n  \n  {\n    ifstream file(filepath);\n    if (!file.good()) {\n      std::cerr << \"Couldn't read file: \" << filepath << std::endl;\n      std::exit(1);\n    }\n    assert(file.good());\n\n    string line;\n    int v, w;\n    double count;\n    int maxv = 0;\n    while ( file >> v >> w >> count ) {\n      if (v > maxv) maxv = v;\n      if (w > maxv) maxv = w;\n      M += 1;\n    }\n    n = maxv/resolution+1;\n    prop.chrom = chrom;\n    prop.resolution = resolution;\n    cerr << \"Building matrix for chromosome \" << prop.chrom << \" at resolution \" << prop.resolution << \"bp with \" << n << \" rows.\" << endl;\n  }\n\n  cout << \"Initializing matrix to zero elements\" << endl;\n  prop.matrix = std::make_shared<SparseMatrix>(n,n,M);\n  for (int i=0; i < n; i++) {\n    for (int j=0; j < n; j++) {\n      prop.matrix->insert_element(i,j,0.0);\n    }\n  }\n\n  {\n    ifstream file(filepath);\n\n    string line;\n    int v,w;\n    double count;\n    int m= 0;\n    while ( file >> v >> w >> count ) {\n      size_t i = v/resolution;\n      size_t j = w/resolution;\n      prop.matrix->insert_element(i,j, log(count));\n      m++;\n      if ( m % 100000 == 0 ) { std::cerr << \"\" << float(m)/M*100 << \"%\\n\";}\n    }\n  }\n  return prop;\n}\n\n\n// domain size\ndouble d(size_t const & i, size_t const & j) {return j - i + 1;}\n\nDomain::Domain(size_t s, size_t e) : start(s), end(e) { }\n\nDomainSet consensusDomains(WeightedDomainEnsemble& dEnsemble) {\n    using PersistenceMap = map<Domain, double>;\n    PersistenceMap pmap;\n\n    for (auto dSetIdx : boost::irange(size_t{0}, dEnsemble.domainSets.size())) {\n        auto& dSet = dEnsemble.domainSets[dSetIdx];\n        auto weight = dEnsemble.weights[dSetIdx];\n        for (auto& domain : dSet) {\n            if ( pmap.find(domain) == pmap.end() ) pmap[domain] = 0;\n            pmap[domain] += weight;\n        }\n    }\n\n    Intervals ivals;\n\n    for (auto domainPersistence : pmap) {\n        auto domain = domainPersistence.first;\n        auto persistence = domainPersistence.second;\n        ivals.push_back(WeightedInterval(domain.start, domain.end, persistence));      \n    }\n\n    IntervalScheduler scheduler(ivals);\n    scheduler.computeSchedule();\n\n    DomainSet dSet;\n    for (auto ival : scheduler.extractIntervals()) {\n        dSet.push_back(Domain(ival.start, ival.end));\n    }\n\n    sort(dSet.begin(), dSet.end());\n\n    return dSet;\n}\n\nWeightedDomainEnsemble multiscaleDomains(std::shared_ptr<SparseMatrix> A, \n    float gammaMax, double stepSize, int k, int minMeanSamples, bool justThisGamma) {\n\n    WeightedDomainEnsemble dEnsemble;\n    double eps = 1e-5;\n    double gamma =0.0;\n    if (justThisGamma)  {\n        gamma = gammaMax;\n    }\n\n    for (; gamma <= gammaMax+eps; gamma+=stepSize) {\n\n        cerr << \"gamma=\" << gamma << endl;\n \n        ArmatusParams params(A, gamma, k, minMeanSamples); // k parameter is not used for anything in Params\n        ArmatusDAG G(params); // but is used in the DAG\n        G.build();\n        G.computeTopK();\n\n        auto domainEnsemble = G.extractTopK();\n        auto& domains = domainEnsemble.domainSets;\n        auto& weights = domainEnsemble.weights;\n        dEnsemble.domainSets.insert(dEnsemble.domainSets.end(), domains.begin(), domains.end());\n        dEnsemble.weights.insert(dEnsemble.weights.end(), weights.begin(), weights.end());\n        for (int i = 0; i<k; i++) {\n            dEnsemble.resolutions.push_back(gamma);\n            dEnsemble.optidx.push_back(i);\n        }\n    }\n\n    return dEnsemble;\n}\n\nvoid outputDomains(DomainSet dSet, string fname, MatrixProperties matProp) {\n    ofstream file;\n    file.open(fname);\n    int res = matProp.resolution;\n    for (auto d : dSet) {\n        file << matProp.chrom << \"\\t\" << (d.start)*res << \"\\t\" << (d.end+1)*res-1 << endl;\n    }\n    file.close();\n}\n\nvoid sanityCheck(WeightedDomainEnsemble e) {\n    for (auto dset : e.domainSets) {\n    }\n}\n\n\n\n", "meta": {"hexsha": "eb27722c59f492a38302168ca7cd1f5de756632b", "size": 9762, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ArmatusUtil.cpp", "max_stars_repo_name": "kingsfordgroup/armatus", "max_stars_repo_head_hexsha": "75858e3ce428c1590a07d950f2c5b8a6872ab2ca", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2015-05-21T18:19:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T14:15:04.000Z", "max_issues_repo_path": "src/ArmatusUtil.cpp", "max_issues_repo_name": "kingsfordgroup/armatus", "max_issues_repo_head_hexsha": "75858e3ce428c1590a07d950f2c5b8a6872ab2ca", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2015-01-22T23:24:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-13T13:59:58.000Z", "max_forks_repo_path": "src/ArmatusUtil.cpp", "max_forks_repo_name": "kingsfordgroup/armatus", "max_forks_repo_head_hexsha": "75858e3ce428c1590a07d950f2c5b8a6872ab2ca", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T18:34:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-05T01:46:04.000Z", "avg_line_length": 29.8532110092, "max_line_length": 143, "alphanum_fraction": 0.5502970703, "num_tokens": 2570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2638512725916295}}
{"text": "//\n// Created by kerin on 2019-02-28.\n//\n\n#include \"eigen_utils.hpp\"\n#include \"mpi_utils.hpp\"\n\n#include \"tools/eigen3.3/Dense\"\n#include <boost/iostreams/filtering_stream.hpp>\n#include <boost/iostreams/device/file.hpp>\n#include <boost/iostreams/filter/gzip.hpp>\n\n#include <iostream>\n#include <cmath>\n#include <map>\n#include <vector>\n#include <string>\n#include <set>\n\nnamespace boost_io = boost::iostreams;\n\nEigen::MatrixXd EigenUtils::subset_matrix(const Eigen::MatrixXd &orig,\n                                          const std::vector<int> &valid_points) {\n\tlong n_cols = orig.cols(), n_rows = valid_points.size();\n\tEigen::MatrixXd subset(n_rows, n_cols);\n\n\tfor(int kk = 0; kk < n_rows; kk++) {\n\t\tfor(int jj = 0; jj < n_cols; jj++) {\n\t\t\tsubset(kk, jj) = orig(valid_points[kk], jj);\n\t\t}\n\t}\n\treturn subset;\n}\n\ntemplate <typename EigenMat>\nvoid EigenUtils::write_matrix(boost_io::filtering_ostream& outf,\n                              EigenMat& M,\n                              std::vector<std::string >& col_names,\n                              std::vector<std::string>& row_names){\n\tif(!col_names.empty()) {\n\t\tif (row_names.size() > 0) assert(col_names.size() == M.cols() + 1);\n\t\tif (row_names.size() == 0) assert(col_names.size() == M.cols());\n\t\tfor (int jj = 0; jj < col_names.size(); jj++) {\n\t\t\toutf << col_names[jj];\n\t\t\tif (jj < col_names.size() - 1) {\n\t\t\t\toutf << \" \";\n\t\t\t}\n\t\t}\n\t\toutf << std::endl;\n\t}\n\n\tif(!row_names.empty()) {\n\t\tassert(row_names.size() == M.rows());\n\t\tfor (long ii = 0; ii < M.rows(); ii++) {\n\t\t\toutf << row_names[ii] << \" \";\n\t\t\tfor (long jj = 0; jj < M.cols(); jj++) {\n\t\t\t\toutf << M(ii, jj);\n\t\t\t\tif (jj < M.cols() - 1) {\n\t\t\t\t\toutf << \" \";\n\t\t\t\t}\n\t\t\t}\n\t\t\toutf << std::endl;\n\t\t}\n\t} else {\n\t\toutf << M;\n\t}\n}\n\ntemplate <typename EigenMat>\nvoid EigenUtils::read_matrix( const std::string& filename,\n                              EigenMat& M){\n\tstd::vector<std::string> placeholder;\n\tEigenUtils::read_matrix(filename, M, placeholder);\n}\n\ntemplate <typename EigenMat>\nvoid EigenUtils::read_matrix(const std::string &filename,\n                             EigenMat &M,\n                             std::vector <std::string> &col_names){\n\tstd::map<long, bool> incomplete_row;\n\tEigenUtils::read_matrix(filename, M, col_names, incomplete_row);\n}\n\ntemplate <typename EigenMat>\nvoid EigenUtils::read_matrix(const std::string &filename,\n                             EigenMat &M,\n                             std::vector <std::string> &col_names,\n                             std::map<long, bool> &incomplete_row) {\n\t/* Read txt file into martix. Files can be gzipped. */\n\n\tboost_io::filtering_istream fg;\n\tstd::string gz_str = \".gz\";\n\tif (filename.find(gz_str) != std::string::npos) {\n\t\tfg.push(boost_io::gzip_decompressor());\n\t}\n\tfg.push(boost_io::file_source(filename));\n\tif (!fg) {\n\t\tthrow std::runtime_error(filename+\" could not be opened.\");\n\t}\n\n\t// Read file twice to acertain number of lines\n\tstd::string line;\n\tint n_rows = 0;\n\tgetline(fg, line);\n\twhile (getline(fg, line)) {\n\t\tn_rows++;\n\t}\n\tfg.reset();\n\tif (filename.find(gz_str) != std::string::npos) {\n\t\tfg.push(boost_io::gzip_decompressor());\n\t}\n\tfg.push(boost_io::file_source(filename));\n\n\t// Reading column names\n\tif (!getline(fg, line)) {\n\t\tthrow std::runtime_error(filename+\" contains zero lines.\");\n\t}\n\tstd::stringstream ss;\n\tstd::string s1;\n\tint n_cols = 0;\n\tss.clear();\n\tss.str(line);\n\twhile (ss >> s1) {\n\t\t++n_cols;\n\t\tcol_names.push_back(s1);\n\t}\n\tstd::cout << \"Reading matrix of size \" << n_rows << \" x \" << n_cols << \" from \" << filename << std::endl;\n\n\t// Write remainder of file to Eigen matrix M\n\tincomplete_row.clear();\n\tM.resize(n_rows, n_cols);\n\tint i = 0;\n\tdouble tmp_d;\n\twhile (getline(fg, line)) {\n\t\tif (i >= n_rows) {\n\t\t\tthrow std::runtime_error(\"ERROR: could not convert txt file (too many lines).\");\n\t\t}\n\t\tss.clear();\n\t\tss.str(line);\n\t\tfor (int k = 0; k < n_cols; k++) {\n\t\t\tstd::string sss;\n\t\t\tss >> sss;\n\t\t\tif (sss == \"NA\" || sss == \"NAN\" || sss == \"NaN\" || sss == \"nan\") {\n\t\t\t\ttmp_d = 0;\n\t\t\t\tincomplete_row[i] = true;\n\t\t\t} else {\n\t\t\t\ttry {\n\t\t\t\t\ttmp_d = stod(sss);\n\t\t\t\t} catch (const std::invalid_argument &exc) {\n\t\t\t\t\tstd::cout << sss << \" on line \" << i << std::endl;\n\t\t\t\t\tthrow;\n\t\t\t\t}\n\t\t\t}\n\t\t\tM(i, k) = tmp_d;\n\t\t}\n\t\ti++;\n\t}\n}\n\nvoid EigenUtils::read_matrix_and_skip_cols(const std::string &filename,\n                                           const int& n_skip_cols,\n                                           Eigen::MatrixXd &M,\n                                           std::vector <std::string> &col_names) {\n\t/* Assumptions:\n\t   - dimensions unknown\n\t   - assume no missing values\n\t */\n\n\tboost_io::filtering_istream fg;\n\tstd::string gz_str = \".gz\";\n\tif (filename.find(gz_str) != std::string::npos) {\n\t\tfg.push(boost_io::gzip_decompressor());\n\t}\n\tfg.push(boost_io::file_source(filename));\n\tif (!fg) {\n\t\tthrow std::runtime_error(filename+\" could not be opened.\");\n\t}\n\n\t// Read file twice to acertain number of lines\n\tstd::string line;\n\tint n_rows = 0;\n\tgetline(fg, line);\n\twhile (getline(fg, line)) {\n\t\tn_rows++;\n\t}\n\tfg.reset();\n\tif (filename.find(gz_str) != std::string::npos) {\n\t\tfg.push(boost_io::gzip_decompressor());\n\t}\n\tfg.push(boost_io::file_source(filename));\n\n\t// Reading column names\n\tif (!getline(fg, line)) {\n\t\tthrow std::runtime_error(filename+\" contains zero lines.\");\n\t}\n\tstd::stringstream ss;\n\tstd::string s1;\n\tint n_cols = 0;\n\tss.clear();\n\tss.str(line);\n\twhile (ss >> s1) {\n\t\t++n_cols;\n\t\tcol_names.push_back(s1);\n\t}\n\tstd::cout << \" Reading matrix of size \" << n_rows << \" x \" << n_cols << \" from \" << filename << std::endl;\n\tassert(n_skip_cols < n_cols);\n\n\t// Write remainder of file to Eigen matrix M\n\tM.resize(n_rows, n_cols - n_skip_cols);\n\tint i = 0;\n\tdouble tmp_d;\n\twhile (getline(fg, line)) {\n\t\tif (i >= n_rows) {\n\t\t\tthrow std::runtime_error(\"ERROR: could not convert txt file (too many lines).\");\n\t\t}\n\t\tss.clear();\n\t\tss.str(line);\n\t\tfor (int k = 0; k < n_cols; k++) {\n\t\t\tstd::string s;\n\t\t\tss >> s;\n\t\t\tif (k >= n_skip_cols) {\n\t\t\t\ttry {\n\t\t\t\t\ttmp_d = stod(s);\n\t\t\t\t} catch (const std::invalid_argument &exc) {\n\t\t\t\t\tstd::cout << s << \" on line \" << i << std::endl;\n\t\t\t\t\tthrow;\n\t\t\t\t}\n\t\t\t\tM(i, k - n_skip_cols) = tmp_d;\n\t\t\t}\n\t\t}\n\t\ti++;\n\t}\n\tif (i < n_rows) {\n\t\tthrow std::runtime_error(\"ERROR: could not convert txt file (too few lines).\");\n\t}\n}\n\nEigen::MatrixXf EigenUtils::solve(const Eigen::MatrixXf &A, const Eigen::MatrixXf &b) {\n\tEigen::MatrixXf x = A.colPivHouseholderQr().solve(b);\n\tdouble check = fabs((double)((A * x - b).norm()/b.norm()));\n\tif (check > 1e-6) {\n\t\t// std::string ms = \"ERROR: could not solve covariate scatter matrix (Check = \" +\n\t\t// std::to_string(check) + \").\";\n\t\t// throw std::runtime_error(ms);\n\t\tstd::cout << \"WARNING: Error in solving covariate scatter matrix is: \" << check << std::endl;\n\t}\n\treturn x;\n}\n\nEigen::MatrixXd EigenUtils::solve(const Eigen::MatrixXd &A, const Eigen::MatrixXd &b) {\n\tEigen::MatrixXd x = A.colPivHouseholderQr().solve(b);\n\tdouble check = fabs((double)((A * x - b).norm()/b.norm()));\n\tif (check > 1e-8) {\n\t\tstd::string ms = \"ERROR: could not solve covariate scatter matrix (Check = \" +\n\t\t                 std::to_string(check) + \").\";\n\t\tthrow std::runtime_error(ms);\n\t}\n\treturn x;\n}\n\ntemplate <typename EigenMat>\nvoid EigenUtils::scale_matrix_and_remove_constant_cols(EigenMat &M,\n                                                       long &n_cols,\n                                                       std::vector<std::string> &col_names){\n\t// Scale eigen matrix passed by reference.\n\t// Removes columns with zero variance + updates col_names.\n\t// Only call on matrixes which have been reduced to complete cases,\n\t// as no check for incomplete rows.\n\tdouble Nlocal = M.rows();\n\tdouble Nglobal = mpiUtils::mpiReduce_inplace(&Nlocal);\n\n\tstd::vector<std::size_t> keep;\n\tstd::vector<std::string> keep_names;\n\tstd::vector<std::string> reject_names;\n\tfor (std::size_t k = 0; k < n_cols; k++) {\n\t\tdouble sum_mik2 = M.col(k).array().square().sum();\n\t\tsum_mik2 = mpiUtils::mpiReduce_inplace(&sum_mik2);\n//\t\tdouble sigma = 0.0;\n//\t\tdouble count = 0;\n//\t\tfor (int i = 0; i < n_rows; i++) {\n//\t\t\tdouble val = M(i, k);\n//\t\t\tsigma += val * val;\n//\t\t\tcount += 1;\n//\t\t}\n\t\tdouble sigma = std::sqrt(sum_mik2 / (Nglobal - 1));\n\n//\t\tsigma = sqrt(sigma/(count - 1));\n\t\tif (sigma > 1e-12) {\n\t\t\tM.col(k).array() /= sigma;\n//\t\t\tfor (int i = 0; i < n_rows; i++) {\n//\t\t\t\tM(i, k) /= sigma;\n//\t\t\t}\n\t\t\tkeep.push_back(k);\n\t\t\tkeep_names.push_back(col_names[k]);\n\t\t} else {\n\t\t\treject_names.push_back(col_names[k]);\n\t\t}\n\t}\n\n\tif (keep.size() != n_cols) {\n\t\tstd::cout << \" Removing \" << (n_cols - keep.size())  << \" column(s) with zero variance:\" << std::endl;\n\t\tfor(auto name : reject_names) {\n\t\t\tstd::cout << name << std::endl;\n\t\t}\n\t\t// subset cols\n\t\tfor (std::size_t i = 0; i < keep.size(); i++) {\n\t\t\tM.col(i) = M.col(keep[i]);\n\t\t}\n\t\tM.conservativeResize(M.rows(), keep.size());\n\n\t\tn_cols = keep.size();\n\t\tcol_names = keep_names;\n\t}\n\n\tif (n_cols == 0) {\n\t\tthrow std::runtime_error(\"ERROR: No columns left with nonzero variance after scale_matrix()\");\n\t}\n}\n\ntemplate <typename EigenMat>\nvoid EigenUtils::center_matrix(EigenMat& M){\n\t// Center eigen matrix passed by reference.\n\t// Only call on matrixes which have been reduced to complete cases,\n\t// as no check for incomplete rows.\n\tlong n_cols = M.cols();\n\tlong n_rows = M.rows();\n\tdouble Nlocal = M.rows();\n\tdouble Nglobal = mpiUtils::mpiReduce_inplace(&Nlocal);\n\n\tfor (int k = 0; k < n_cols; k++) {\n\t\tdouble sum_mik = 0.0;\n\t\tfor (int i = 0; i < n_rows; i++) {\n\t\t\tsum_mik += M(i, k);\n\t\t}\n\n\t\tsum_mik = mpiUtils::mpiReduce_inplace(&sum_mik);\n\t\tdouble mu = sum_mik / Nglobal;\n\t\tfor (int i = 0; i < n_rows; i++) {\n\t\t\tM(i, k) -= mu;\n\t\t}\n\t}\n}\n\nEigen::MatrixXd EigenUtils::project_out_covars(Eigen::Ref<Eigen::MatrixXd> rhs, const Eigen::Ref<const Eigen::MatrixXd> &C,\n                                               const Eigen::Ref<const Eigen::MatrixXd> &CtC_inv) {\n\tassert(CtC_inv.cols() == C.cols());\n\tassert(CtC_inv.rows() == C.cols());\n\tassert(C.rows() == rhs.rows());\n\tEigen::MatrixXd CtRHS = C.transpose() * rhs;\n\tCtRHS = mpiUtils::mpiReduce_inplace(CtRHS);\n\tEigen::MatrixXd beta = CtC_inv * CtRHS;\n\tEigen::MatrixXd yhat = C * beta;\n\tEigen::MatrixXd res = rhs - yhat;\n\treturn res;\n}\n\n// Explicit instantiation\n// https://stackoverflow.com/questions/2152002/how-do-i-force-a-particular-instance-of-a-c-template-to-instantiate\n\ntemplate void EigenUtils::read_matrix(const std::string&,\n                                      Eigen::MatrixXf&, std::vector<std::string>&, std::map<long, bool>&);\ntemplate void EigenUtils::read_matrix(const std::string&,\n                                      Eigen::MatrixXd&, std::vector<std::string>&, std::map<long, bool>&);\ntemplate void EigenUtils::read_matrix(const std::string&,\n                                      Eigen::MatrixXf&, std::vector<std::string>&);\ntemplate void EigenUtils::read_matrix(const std::string&,\n                                      Eigen::MatrixXd&, std::vector<std::string>&);\ntemplate void EigenUtils::read_matrix(const std::string&, Eigen::MatrixXf&);\ntemplate void EigenUtils::read_matrix(const std::string&, Eigen::MatrixXd&);\ntemplate void EigenUtils::write_matrix(boost_io::filtering_ostream&,\n                                       Eigen::VectorXd&,\n                                       std::vector<std::string>&,\n                                       std::vector<std::string>&);\ntemplate void EigenUtils::write_matrix(boost_io::filtering_ostream&,\n                                       Eigen::MatrixXd&,\n                                       std::vector<std::string>&,\n                                       std::vector<std::string>&);\ntemplate void EigenUtils::center_matrix(Eigen::MatrixXd&);\ntemplate void EigenUtils::center_matrix(Eigen::MatrixXf&);\ntemplate void EigenUtils::center_matrix(Eigen::VectorXd&);\ntemplate void EigenUtils::center_matrix(Eigen::VectorXf&);\ntemplate void EigenUtils::scale_matrix_and_remove_constant_cols(Eigen::MatrixXf&,\n                                                                long&, std::vector<std::string>&);\ntemplate void EigenUtils::scale_matrix_and_remove_constant_cols(Eigen::MatrixXd&,\n                                                                long&, std::vector<std::string>&);\ntemplate void EigenUtils::scale_matrix_and_remove_constant_cols(Eigen::VectorXd&,\n                                                                long&, std::vector<std::string>&);\n", "meta": {"hexsha": "89b8933d7f4d0e24085e6d93ffa3c1740a284175", "size": 12390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/eigen_utils.cpp", "max_stars_repo_name": "mkerin/LEMMA", "max_stars_repo_head_hexsha": "26deaa5ed343074ac19bfaf5f3254f670647351c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T21:18:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-02T18:46:53.000Z", "max_issues_repo_path": "src/eigen_utils.cpp", "max_issues_repo_name": "lfelipe-ferrao/LEMMA", "max_issues_repo_head_hexsha": "471368ce1e362a64aa3a682075c4d4e4bcd9509b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-09-10T21:18:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-19T18:38:31.000Z", "max_forks_repo_path": "src/eigen_utils.cpp", "max_forks_repo_name": "lfelipe-ferrao/LEMMA", "max_forks_repo_head_hexsha": "471368ce1e362a64aa3a682075c4d4e4bcd9509b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T21:02:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-10T21:02:27.000Z", "avg_line_length": 31.9329896907, "max_line_length": 123, "alphanum_fraction": 0.5918482647, "num_tokens": 3342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.2638512725916295}}
{"text": "/**\n * Some portion of the source code is from the Rodinia benchmark suite.\n *\n * These are the original authors:\n * 2009; Amittai Aviram; entire code written in C;\n * 2010; Jordan Fix and Andrew Wilkes; code converted to CUDA;\n * 2011.10; Lukasz G. Szafaryn; code converted to portable form, to C, OpenMP, CUDA, PGI versions;\n * 2011.12; Lukasz G. Szafaryn; Split different versions for Rodinia.\n * 2011.12; Lukasz G. Szafaryn; code converted to OpenCL;\n * 2012.10; Ke Wang; Change it to non-interactive mode. Use command option read command from file. And also add output for easy verification among different platforms and devices.Merged into Rodinia main distribution 2.2.\n */\n\n#include <boost/program_options.hpp>\n#include <cstdlib>\n#include <cstdio>\n#include <iostream>\n#include <sys/time.h>\n\n#include \"../device_hopper/core.h\"\n\nusing namespace device_hopper;\n\n\n// TODO the following define and structs should be in the common.h header\n// but the source to source cl translation needs them in the benchmark\n\n#define  DEFAULT_ORDER 256\n\ntypedef struct knode {\n\tint location;\n\tint indices [DEFAULT_ORDER + 1];\n\tint  keys [DEFAULT_ORDER + 1];\n\tbool is_leaf;\n\tint num_keys;\n} knode; \n\ntypedef struct record {\n\tint value;\n} record;\n\n// ----------------------------------------------------------------------------------------------------------------------------\n\n\n#include \"./rodinia_src/btree/common.h\"\n#include \"./rodinia_src/btree/kernel_gpu_cuda_wrapper.h\"\n\n#define PREFERRED_DEVICE GPU\n\nusing namespace std::chrono;\n\nknode *knodes;\nrecord *krecords;\nchar *mem;\nlong freeptr;\nlong malloc_size;\nlong size;\nlong maxheight;\nint order = DEFAULT_ORDER;\nnode *queue = NULL;\n\nvoid *kmalloc(int size) {\n    //printf(\"size: %d, current offset: %p\\n\",size,freeptr);\n    void *r = (void *) freeptr;\n    freeptr += size;\n    if (freeptr > malloc_size + (long) mem) {\n        printf(\"Memory Overflow\\n\");\n        exit(1);\n    }\n    return r;\n}\n\nvoid enqueue(node *new_node) {\n    node *c;\n    if (queue == NULL) {\n        queue = new_node;\n        queue->next = NULL;\n    } else {\n        c = queue;\n        while (c->next != NULL) {\n            c = c->next;\n        }\n        c->next = new_node;\n        new_node->next = NULL;\n    }\n}\n\nnode *dequeue(void) {\n    node *n = queue;\n    queue = queue->next;\n    n->next = NULL;\n    return n;\n}\n\nnode *insert(node *root, int key, int value) {\n    record *pointer;\n    node *leaf;\n\n    /* The current implementation ignores duplicates. */\n    if (find(root, key, false) != NULL)\n        return root;\n\n    /* Create a new record for the value. */\n    pointer = make_record(value);\n\n    /* Case: the tree does not exist yet. Start a new tree. */\n    if (root == NULL)\n        return start_new_tree(key, pointer);\n\n    /* Case: the tree already exists. (Rest of function body.) */\n    leaf = find_leaf(root, key, false);\n\n    /* Case: leaf has room for key and pointer. */\n    if (leaf->num_keys < order - 1) {\n        leaf = insert_into_leaf(leaf, key, pointer);\n        return root;\n    }\n\n    /* Case:  leaf must be split. */\n    return insert_into_leaf_after_splitting(root, leaf, key, pointer);\n}\n\nlong transform_to_cuda(node *root, bool verbose) {\n    struct timeval one, two;\n    double time;\n    gettimeofday(&one, NULL);\n    long max_nodes = (long) (pow(order, log(size) / log(order / 2.0) - 1) + 1);\n    malloc_size = size * sizeof(record) + max_nodes * sizeof(knode);\n    mem = (char *) malloc(malloc_size);\n    if (mem == NULL) {\n        printf(\"Initial malloc error\\n\");\n        exit(1);\n    }\n    freeptr = (long) mem;\n\n    krecords = (record *) kmalloc(size * sizeof(record));\n    // printf(\"%d records\\n\", size);\n    knodes = (knode *) kmalloc(max_nodes * sizeof(knode));\n    // printf(\"%d knodes\\n\", max_nodes);\n\n    queue = NULL;\n    enqueue(root);\n    node *n;\n    knode *k;\n    int i;\n    long nodeindex = 0;\n    long recordindex = 0;\n    long queueindex = 0;\n    knodes[0].location = nodeindex++;\n\n    while (queue != NULL) {\n        n = dequeue();\n        k = &knodes[queueindex];\n        k->location = queueindex++;\n        k->is_leaf = n->is_leaf;\n        k->num_keys = n->num_keys + 2;\n        //start at 1 because 0 is set to INT_MIN\n        k->keys[0] = INT_MIN;\n        k->keys[k->num_keys - 1] = INT_MAX;\n        for (i = k->num_keys; i < order; i++)k->keys[i] = INT_MAX;\n        if (!k->is_leaf) {\n            k->indices[0] = nodeindex++;\n            // if(k->indices[0]>3953){\n            // printf(\"ERROR: %d\\n\", k->indices[0]);\n            // }\n            for (i = 1; i < k->num_keys - 1; i++) {\n                k->keys[i] = n->keys[i - 1];\n                enqueue((node *) n->pointers[i - 1]);\n                k->indices[i] = nodeindex++;\n                // if(k->indices[i]>3953){\n                // printf(\"ERROR 1: %d\\n\", k->indices[i]);\n                // }\n                //knodes[nodeindex].location = nodeindex++;\n            }\n            //for final point of n\n            enqueue((node *) n->pointers[i - 1]);\n        } else {\n            k->indices[0] = 0;\n            for (i = 1; i < k->num_keys - 1; i++) {\n                k->keys[i] = n->keys[i - 1];\n                krecords[recordindex].value = ((record *) n->pointers[i - 1])->value;\n                k->indices[i] = recordindex++;\n                // if(k->indices[i]>3953){\n                // printf(\"ERROR 2: %d\\n\", k->indices[i]);\n                // }\n            }\n        }\n\n        k->indices[k->num_keys - 1] = queueindex;\n        // if(k->indices[k->num_keys-1]>3953){\n        // printf(\"ERROR 3: %d\\n\", k->indices[k->num_keys-1]);\n        // }\n\n        if (verbose) {\n            printf(\"Successfully created knode with index %d\\n\", k->location);\n            printf(\"Is Leaf: %d, Num Keys: %d\\n\", k->is_leaf, k->num_keys);\n            printf(\"Pointers: \");\n            for (i = 0; i < k->num_keys; i++)\n                printf(\"%d | \", k->indices[i]);\n            printf(\"\\nKeys: \");\n            for (i = 0; i < k->num_keys; i++)\n                printf(\"%d | \", k->keys[i]);\n            printf(\"\\n\\n\");\n        }\n    }\n    long mem_used = size * sizeof(record) + (nodeindex) * sizeof(knode);\n    if (verbose) {\n        for (i = 0; i < size; i++)\n            printf(\"%d \", krecords[i].value);\n        printf(\"\\nNumber of records = %d, sizeof(record)=%d, total=%d\\n\", size, sizeof(record), size * sizeof(record));\n        printf(\"Number of knodes = %d, sizeof(knode)=%d, total=%d\\n\", nodeindex, sizeof(knode),\n               (nodeindex) * sizeof(knode));\n        printf(\"\\nDone Transformation. Mem used: %d\\n\", mem_used);\n    }\n    gettimeofday(&two, NULL);\n    double oneD = one.tv_sec + (double) one.tv_usec * .000001;\n    double twoD = two.tv_sec + (double) two.tv_usec * .000001;\n    time = twoD - oneD;\n    printf(\"Tree transformation took %f\\n\", time);\n\n    return mem_used;\n}\n\n\n/* Utility function to give the height of the tree, which length in number of edges of the path from the root to any leaf. */\nint height(node *root) {\n    int h = 0;\n    node *c = root;\n    while (!c->is_leaf) {\n        c = (node *) c->pointers[0];\n        h++;\n    }\n    return h;\n}\n\n/* Traces the path from the root to a leaf, searching by key.  Displays information about the path if the verbose flag is set. Returns the leaf containing the given key. */\nnode *find_leaf(node *root, int key, bool verbose) {\n    int i = 0;\n    node *c = root;\n    if (c == NULL) {\n        if (verbose)\n            printf(\"Empty tree.\\n\");\n        return c;\n    }\n    while (!c->is_leaf) {\n        if (verbose) {\n            printf(\"[\");\n            for (i = 0; i < c->num_keys - 1; i++)\n                printf(\"%d \", c->keys[i]);\n            printf(\"%d] \", c->keys[i]);\n        }\n        i = 0;\n        while (i < c->num_keys) {\n            if (key >= c->keys[i])\n                i++;\n            else\n                break;\n        }\n        if (verbose)\n            printf(\"%d ->\\n\", i);\n        c = (node *) c->pointers[i];\n    }\n    if (verbose) {\n        printf(\"Leaf [\");\n        for (i = 0; i < c->num_keys - 1; i++)\n            printf(\"%d \", c->keys[i]);\n        printf(\"%d] ->\\n\", c->keys[i]);\n    }\n    return c;\n\n}\n\n/* Finds and returns the record to which a key refers. */\nrecord *find(node *root, int key, bool verbose) {\n    int i = 0;\n    node *c = find_leaf(root, key, verbose);\n    if (c == NULL)\n        return NULL;\n    for (i = 0; i < c->num_keys; i++)\n        if (c->keys[i] == key)\n            break;\n    if (i == c->num_keys)\n        return NULL;\n    else\n        return (record *) c->pointers[i];\n}\n\n/* Finds the appropriate place to split a node that is too big into two. */\nint cut(int length) {\n    if (length % 2 == 0)\n        return length / 2;\n    else\n        return length / 2 + 1;\n}\n\n//======================================================================================================================================================150\n// INSERTION\n//======================================================================================================================================================150\n\n/* Creates a new record to hold the value to which a key refers. */\nrecord *make_record(int value) {\n    record *new_record = (record *) malloc(sizeof(record));\n    if (new_record == NULL) {\n        perror(\"Record creation.\");\n        exit(EXIT_FAILURE);\n    } else {\n        new_record->value = value;\n    }\n    return new_record;\n}\n\n/* Creates a new general node, which can be adapted to serve as either a leaf or an internal node. */\nnode *make_node(void) {\n    node *new_node;\n    new_node = (node *) malloc(sizeof(node));\n    if (new_node == NULL) {\n        perror(\"Node creation.\");\n        exit(EXIT_FAILURE);\n    }\n    new_node->keys = (int *) malloc((order - 1) * sizeof(int));\n    if (new_node->keys == NULL) {\n        perror(\"New node keys array.\");\n        exit(EXIT_FAILURE);\n    }\n    new_node->pointers = (void **) malloc(order * sizeof(void *));\n    if (new_node->pointers == NULL) {\n        perror(\"New node pointers array.\");\n        exit(EXIT_FAILURE);\n    }\n    new_node->is_leaf = false;\n    new_node->num_keys = 0;\n    new_node->parent = NULL;\n    new_node->next = NULL;\n    return new_node;\n}\n\n/* Creates a new leaf by creating a node and then adapting it appropriately. */\nnode *make_leaf(void) {\n    node *leaf = make_node();\n    leaf->is_leaf = true;\n    return leaf;\n}\n\n/* Helper function used in insert_into_parent to find the index of the parent's pointer to the node to the left of the key to be inserted. */\nint get_left_index(node *parent, node *left) {\n    int left_index = 0;\n    while (left_index <= parent->num_keys &&\n           parent->pointers[left_index] != left)\n        left_index++;\n    return left_index;\n}\n\n/* Inserts a new pointer to a record and its corresponding key into a leaf. Returns the altered leaf. */\nnode *insert_into_leaf(node *leaf, int key, record *pointer) {\n\n    int i, insertion_point;\n\n    insertion_point = 0;\n    while (insertion_point < leaf->num_keys && leaf->keys[insertion_point] < key)\n        insertion_point++;\n\n    for (i = leaf->num_keys; i > insertion_point; i--) {\n        leaf->keys[i] = leaf->keys[i - 1];\n        leaf->pointers[i] = leaf->pointers[i - 1];\n    }\n    leaf->keys[insertion_point] = key;\n    leaf->pointers[insertion_point] = pointer;\n    leaf->num_keys++;\n    return leaf;\n}\n\n/* Inserts a new key and pointer to a new record into a leaf so as to exceed the tree's order, causing the leaf to be split in half. */\nnode *insert_into_leaf_after_splitting(node *root,\n                                       node *leaf,\n                                       int key,\n                                       record *pointer) {\n\n    node *new_leaf;\n    int *temp_keys;\n    void **temp_pointers;\n    int insertion_index, split, new_key, i, j;\n\n    new_leaf = make_leaf();\n\n    temp_keys = (int *) malloc(order * sizeof(int));\n    if (temp_keys == NULL) {\n        perror(\"Temporary keys array.\");\n        exit(EXIT_FAILURE);\n    }\n\n    temp_pointers = (void **) malloc(order * sizeof(void *));\n    if (temp_pointers == NULL) {\n        perror(\"Temporary pointers array.\");\n        exit(EXIT_FAILURE);\n    }\n\n    insertion_index = 0;\n    while (leaf->keys[insertion_index] < key && insertion_index < order - 1)\n        insertion_index++;\n\n    for (i = 0, j = 0; i < leaf->num_keys; i++, j++) {\n        if (j == insertion_index) j++;\n        temp_keys[j] = leaf->keys[i];\n        temp_pointers[j] = leaf->pointers[i];\n    }\n\n    temp_keys[insertion_index] = key;\n    temp_pointers[insertion_index] = pointer;\n\n    leaf->num_keys = 0;\n\n    split = cut(order - 1);\n\n    for (i = 0; i < split; i++) {\n        leaf->pointers[i] = temp_pointers[i];\n        leaf->keys[i] = temp_keys[i];\n        leaf->num_keys++;\n    }\n\n    for (i = split, j = 0; i < order; i++, j++) {\n        new_leaf->pointers[j] = temp_pointers[i];\n        new_leaf->keys[j] = temp_keys[i];\n        new_leaf->num_keys++;\n    }\n\n    free(temp_pointers);\n    free(temp_keys);\n\n    new_leaf->pointers[order - 1] = leaf->pointers[order - 1];\n    leaf->pointers[order - 1] = new_leaf;\n\n    for (i = leaf->num_keys; i < order - 1; i++)\n        leaf->pointers[i] = NULL;\n    for (i = new_leaf->num_keys; i < order - 1; i++)\n        new_leaf->pointers[i] = NULL;\n\n    new_leaf->parent = leaf->parent;\n    new_key = new_leaf->keys[0];\n\n    return insert_into_parent(root, leaf, new_key, new_leaf);\n}\n\n/* Inserts a new key and pointer to a node into a node into which these can fit without violating the B+ tree properties. */\nnode *insert_into_node(node *root,\n                       node *n,\n                       int left_index,\n                       int key,\n                       node *right) {\n\n    int i;\n\n    for (i = n->num_keys; i > left_index; i--) {\n        n->pointers[i + 1] = n->pointers[i];\n        n->keys[i] = n->keys[i - 1];\n    }\n    n->pointers[left_index + 1] = right;\n    n->keys[left_index] = key;\n    n->num_keys++;\n    return root;\n}\n\n/* Inserts a new key and pointer to a node into a node, causing the node's size to exceed the order, and causing the node to split into two. */\nnode *insert_into_node_after_splitting(node *root,\n                                       node *old_node,\n                                       int left_index,\n                                       int key,\n                                       node *right) {\n    int i, j, split, k_prime;\n    node *new_node, *child;\n    int *temp_keys;\n    node **temp_pointers;\n\n    /* First create a temporary set of keys and pointers\n    * to hold everything in order, including\n    * the new key and pointer, inserted in their\n    * correct places.\n    * Then create a new node and copy half of the\n    * keys and pointers to the old node and\n    * the other half to the new.\n    */\n\n    temp_pointers = (node **) malloc((order + 1) * sizeof(node *));\n    if (temp_pointers == NULL) {\n        perror(\"Temporary pointers array for splitting nodes.\");\n        exit(EXIT_FAILURE);\n    }\n    temp_keys = (int *) malloc(order * sizeof(int));\n    if (temp_keys == NULL) {\n        perror(\"Temporary keys array for splitting nodes.\");\n        exit(EXIT_FAILURE);\n    }\n\n    for (i = 0, j = 0; i < old_node->num_keys + 1; i++, j++) {\n        if (j == left_index + 1) j++;\n        temp_pointers[j] = (node *) old_node->pointers[i];\n    }\n\n    for (i = 0, j = 0; i < old_node->num_keys; i++, j++) {\n        if (j == left_index) j++;\n        temp_keys[j] = old_node->keys[i];\n    }\n\n    temp_pointers[left_index + 1] = right;\n    temp_keys[left_index] = key;\n\n    /* Create the new node and copy\n    * half the keys and pointers to the\n    * old and half to the new.\n    */\n    split = cut(order);\n    new_node = make_node();\n    old_node->num_keys = 0;\n    for (i = 0; i < split - 1; i++) {\n        old_node->pointers[i] = temp_pointers[i];\n        old_node->keys[i] = temp_keys[i];\n        old_node->num_keys++;\n    }\n    old_node->pointers[i] = temp_pointers[i];\n    k_prime = temp_keys[split - 1];\n    for (++i, j = 0; i < order; i++, j++) {\n        new_node->pointers[j] = temp_pointers[i];\n        new_node->keys[j] = temp_keys[i];\n        new_node->num_keys++;\n    }\n    new_node->pointers[j] = temp_pointers[i];\n    free(temp_pointers);\n    free(temp_keys);\n    new_node->parent = old_node->parent;\n    for (i = 0; i <= new_node->num_keys; i++) {\n        child = (node *) new_node->pointers[i];\n        child->parent = new_node;\n    }\n\n    /* Insert a new key into the parent of the two\n* nodes resulting from the split, with\n* the old node to the left and the new to the right.\n*/\n\n    return insert_into_parent(root, old_node, k_prime, new_node);\n}\n\n/* Inserts a new node (leaf or internal node) into the B+ tree. Returns the root of the tree after insertion. */\nnode *\ninsert_into_parent(node *root,\n                   node *left,\n                   int key,\n                   node *right) {\n\n    int left_index;\n    node *parent;\n\n    parent = left->parent;\n\n    /* Case: new root. */\n\n    if (parent == NULL)\n        return insert_into_new_root(left, key, right);\n\n    /* Case: leaf or node. (Remainder of\n* function body.)\n*/\n\n    /* Find the parent's pointer to the left\n* node.\n*/\n\n    left_index = get_left_index(parent, left);\n\n\n    /* Simple case: the new key fits into the node.\n*/\n\n    if (parent->num_keys < order - 1)\n        return insert_into_node(root, parent, left_index, key, right);\n\n    /* Harder case:  split a node in order\n* to preserve the B+ tree properties.\n*/\n\n    return insert_into_node_after_splitting(root, parent, left_index, key, right);\n}\n\n/* Creates a new root for two subtrees and inserts the appropriate key into the new root. */\nnode *\ninsert_into_new_root(node *left,\n                     int key,\n                     node *right) {\n\n    node *root = make_node();\n    root->keys[0] = key;\n    root->pointers[0] = left;\n    root->pointers[1] = right;\n    root->num_keys++;\n    root->parent = NULL;\n    left->parent = root;\n    right->parent = root;\n    return root;\n}\n\n/* First insertion: start a new tree. */\nnode *\nstart_new_tree(int key,\n               record *pointer) {\n\n    node *root = make_leaf();\n    root->keys[0] = key;\n    root->pointers[0] = pointer;\n    root->pointers[order - 1] = NULL;\n    root->parent = NULL;\n    root->num_keys++;\n    return root;\n}\n\n//======================================================================================================================================================150\n// DELETION\n//======================================================================================================================================================150\n\n/* Utility function for deletion. Retrieves the index of a node's nearest neighbor (sibling) to the left if one exists.  If not (the node is the leftmost child), returns -1 to signify this special case. */\nint\nget_neighbor_index(node *n) {\n\n    int i;\n\n    /* Return the index of the key to the left\n* of the pointer in the parent pointing\n* to n.\n* If n is the leftmost child, this means\n* return -1.\n*/\n    for (i = 0; i <= n->parent->num_keys; i++)\n        if (n->parent->pointers[i] == n)\n            return i - 1;\n\n    // Error state.\n    printf(\"Search for nonexistent pointer to node in parent.\\n\");\n    //printf(\"Node:  %#x\\n\", (unsigned int)n);\n    exit(EXIT_FAILURE);\n}\n\n/*   */\nnode *\nremove_entry_from_node(node *n,\n                       int key,\n                       node *pointer) {\n\n    int i, num_pointers;\n\n    // Remove the key and shift other keys accordingly.\n    i = 0;\n    while (n->keys[i] != key)\n        i++;\n    for (++i; i < n->num_keys; i++)\n        n->keys[i - 1] = n->keys[i];\n\n    // Remove the pointer and shift other pointers accordingly.\n    // First determine number of pointers.\n    num_pointers = n->is_leaf ? n->num_keys : n->num_keys + 1;\n    i = 0;\n    while (n->pointers[i] != pointer)\n        i++;\n    for (++i; i < num_pointers; i++)\n        n->pointers[i - 1] = n->pointers[i];\n\n\n    // One key fewer.\n    n->num_keys--;\n\n    // Set the other pointers to NULL for tidiness.\n    // A leaf uses the last pointer to point to the next leaf.\n    if (n->is_leaf)\n        for (i = n->num_keys; i < order - 1; i++)\n            n->pointers[i] = NULL;\n    else\n        for (i = n->num_keys + 1; i < order; i++)\n            n->pointers[i] = NULL;\n\n    return n;\n}\n\n/*   */\nnode *\nadjust_root(node *root) {\n\n    node *new_root;\n\n    /* Case: nonempty root.\n* Key and pointer have already been deleted,\n* so nothing to be done.\n*/\n\n    if (root->num_keys > 0)\n        return root;\n\n    /* Case: empty root.\n*/\n\n    // If it has a child, promote\n    // the first (only) child\n    // as the new root.\n\n    if (!root->is_leaf) {\n        new_root = (node *) root->pointers[0];\n        new_root->parent = NULL;\n    }\n\n        // If it is a leaf (has no children),\n        // then the whole tree is empty.\n\n    else\n        new_root = NULL;\n\n    free(root->keys);\n    free(root->pointers);\n    free(root);\n\n    return new_root;\n}\n\n/* Coalesces a node that has become too small after deletion with a neighboring node that can accept the additional entries without exceeding the maximum. */\nnode *\ncoalesce_nodes(node *root,\n               node *n,\n               node *neighbor,\n               int neighbor_index,\n               int k_prime) {\n\n    int i, j, neighbor_insertion_index, n_start, n_end, new_k_prime;\n    node *tmp;\n    bool split;\n\n    /* Swap neighbor with node if node is on the\n* extreme left and neighbor is to its right.\n*/\n\n    if (neighbor_index == -1) {\n        tmp = n;\n        n = neighbor;\n        neighbor = tmp;\n    }\n\n    /* Starting point in the neighbor for copying\n* keys and pointers from n.\n* Recall that n and neighbor have swapped places\n* in the special case of n being a leftmost child.\n*/\n\n    neighbor_insertion_index = neighbor->num_keys;\n\n    /*\n* Nonleaf nodes may sometimes need to remain split,\n* if the insertion of k_prime would cause the resulting\n* single coalesced node to exceed the limit order - 1.\n* The variable split is always false for leaf nodes\n* and only sometimes set to true for nonleaf nodes.\n*/\n\n    split = false;\n\n    /* Case:  nonleaf node.\n* Append k_prime and the following pointer.\n* If there is room in the neighbor, append\n* all pointers and keys from the neighbor.\n* Otherwise, append only cut(order) - 2 keys and\n* cut(order) - 1 pointers.\n*/\n\n    if (!n->is_leaf) {\n\n        /* Append k_prime.\n    */\n\n        neighbor->keys[neighbor_insertion_index] = k_prime;\n        neighbor->num_keys++;\n\n\n        /* Case (default):  there is room for all of n's keys and pointers\n    * in the neighbor after appending k_prime.\n    */\n\n        n_end = n->num_keys;\n\n        /* Case (special): k cannot fit with all the other keys and pointers\n    * into one coalesced node.\n    */\n        n_start = 0; // Only used in this special case.\n        if (n->num_keys + neighbor->num_keys >= order) {\n            split = true;\n            n_end = cut(order) - 2;\n        }\n\n        for (i = neighbor_insertion_index + 1, j = 0; j < n_end; i++, j++) {\n            neighbor->keys[i] = n->keys[j];\n            neighbor->pointers[i] = n->pointers[j];\n            neighbor->num_keys++;\n            n->num_keys--;\n            n_start++;\n        }\n\n        /* The number of pointers is always\n    * one more than the number of keys.\n    */\n\n        neighbor->pointers[i] = n->pointers[j];\n\n        /* If the nodes are still split, remove the first key from\n    * n.\n    */\n        if (split) {\n            new_k_prime = n->keys[n_start];\n            for (i = 0, j = n_start + 1; i < n->num_keys; i++, j++) {\n                n->keys[i] = n->keys[j];\n                n->pointers[i] = n->pointers[j];\n            }\n            n->pointers[i] = n->pointers[j];\n            n->num_keys--;\n        }\n\n        /* All children must now point up to the same parent.\n    */\n\n        for (i = 0; i < neighbor->num_keys + 1; i++) {\n            tmp = (node *) neighbor->pointers[i];\n            tmp->parent = neighbor;\n        }\n    }\n\n        /* In a leaf, append the keys and pointers of\n    * n to the neighbor.\n    * Set the neighbor's last pointer to point to\n    * what had been n's right neighbor.\n    */\n\n    else {\n        for (i = neighbor_insertion_index, j = 0; j < n->num_keys; i++, j++) {\n            neighbor->keys[i] = n->keys[j];\n            neighbor->pointers[i] = n->pointers[j];\n            neighbor->num_keys++;\n        }\n        neighbor->pointers[order - 1] = n->pointers[order - 1];\n    }\n\n    if (!split) {\n        root = delete_entry(root, n->parent, k_prime, n);\n        free(n->keys);\n        free(n->pointers);\n        free(n);\n    } else\n        for (i = 0; i < n->parent->num_keys; i++)\n            if (n->parent->pointers[i + 1] == n) {\n                n->parent->keys[i] = new_k_prime;\n                break;\n            }\n\n    return root;\n\n}\n\n/* Redistributes entries between two nodes when one has become too small after deletion but its neighbor is too big to append the small node's entries without exceeding the maximum */\nnode *\nredistribute_nodes(node *root,\n                   node *n,\n                   node *neighbor,\n                   int neighbor_index,\n                   int k_prime_index,\n                   int k_prime) {\n\n    int i;\n    node *tmp;\n\n    /* Case: n has a neighbor to the left.\n* Pull the neighbor's last key-pointer pair over\n* from the neighbor's right end to n's left end.\n*/\n\n    if (neighbor_index != -1) {\n        if (!n->is_leaf)\n            n->pointers[n->num_keys + 1] = n->pointers[n->num_keys];\n        for (i = n->num_keys; i > 0; i--) {\n            n->keys[i] = n->keys[i - 1];\n            n->pointers[i] = n->pointers[i - 1];\n        }\n        if (!n->is_leaf) {\n            n->pointers[0] = neighbor->pointers[neighbor->num_keys];\n            tmp = (node *) n->pointers[0];\n            tmp->parent = n;\n            neighbor->pointers[neighbor->num_keys] = NULL;\n            n->keys[0] = k_prime;\n            n->parent->keys[k_prime_index] = neighbor->keys[neighbor->num_keys - 1];\n        } else {\n            n->pointers[0] = neighbor->pointers[neighbor->num_keys - 1];\n            neighbor->pointers[neighbor->num_keys - 1] = NULL;\n            n->keys[0] = neighbor->keys[neighbor->num_keys - 1];\n            n->parent->keys[k_prime_index] = n->keys[0];\n        }\n    }\n\n        /* Case: n is the leftmost child.\n    * Take a key-pointer pair from the neighbor to the right.\n    * Move the neighbor's leftmost key-pointer pair\n    * to n's rightmost position.\n    */\n\n    else {\n        if (n->is_leaf) {\n            n->keys[n->num_keys] = neighbor->keys[0];\n            n->pointers[n->num_keys] = neighbor->pointers[0];\n            n->parent->keys[k_prime_index] = neighbor->keys[1];\n        } else {\n            n->keys[n->num_keys] = k_prime;\n            n->pointers[n->num_keys + 1] = neighbor->pointers[0];\n            tmp = (node *) n->pointers[n->num_keys + 1];\n            tmp->parent = n;\n            n->parent->keys[k_prime_index] = neighbor->keys[0];\n        }\n        for (i = 0; i < neighbor->num_keys; i++) {\n            neighbor->keys[i] = neighbor->keys[i + 1];\n            neighbor->pointers[i] = neighbor->pointers[i + 1];\n        }\n        if (!n->is_leaf)\n            neighbor->pointers[i] = neighbor->pointers[i + 1];\n    }\n\n    /* n now has one more key and one more pointer;\n* the neighbor has one fewer of each.\n*/\n\n    n->num_keys++;\n    neighbor->num_keys--;\n\n    return root;\n}\n\n/* Deletes an entry from the B+ tree. Removes the record and its key and pointer from the leaf, and then makes all appropriate changes to preserve the B+ tree properties. */\nnode *\ndelete_entry(node *root,\n             node *n,\n             int key,\n             void *pointer) {\n\n    int min_keys;\n    node *neighbor;\n    int neighbor_index;\n    int k_prime_index, k_prime;\n    int capacity;\n\n    // Remove key and pointer from node.\n\n    n = remove_entry_from_node(n, key, (node *) pointer);\n\n    /* Case:  deletion from the root.\n*/\n\n    if (n == root)\n        return adjust_root(root);\n\n\n    /* Case:  deletion from a node below the root.\n* (Rest of function body.)\n*/\n\n    /* Determine minimum allowable size of node,\n* to be preserved after deletion.\n*/\n\n    min_keys = n->is_leaf ? cut(order - 1) : cut(order) - 1;\n\n    /* Case:  node stays at or above minimum.\n* (The simple case.)\n*/\n\n    if (n->num_keys >= min_keys)\n        return root;\n\n    /* Case:  node falls below minimum.\n* Either coalescence or redistribution\n* is needed.\n*/\n\n    /* Find the appropriate neighbor node with which\n* to coalesce.\n* Also find the key (k_prime) in the parent\n* between the pointer to node n and the pointer\n* to the neighbor.\n*/\n\n    neighbor_index = get_neighbor_index(n);\n    k_prime_index = neighbor_index == -1 ? 0 : neighbor_index;\n    k_prime = n->parent->keys[k_prime_index];\n    neighbor = neighbor_index == -1 ? (node *) n->parent->pointers[1] :\n               (node *) n->parent->pointers[neighbor_index];\n\n    capacity = n->is_leaf ? order : order - 1;\n\n    /* Coalescence. */\n\n    if (neighbor->num_keys + n->num_keys < capacity)\n        return coalesce_nodes(root, n, neighbor, neighbor_index, k_prime);\n\n        /* Redistribution. */\n\n    else\n        return redistribute_nodes(root, n, neighbor, neighbor_index, k_prime_index, k_prime);\n}\n\n/*   */\nvoid\ndestroy_tree_nodes(node *root) {\n    int i;\n    if (root->is_leaf)\n        for (i = 0; i < root->num_keys; i++)\n            free(root->pointers[i]);\n    else\n        for (i = 0; i < root->num_keys + 1; i++)\n            destroy_tree_nodes((node *) root->pointers[i]);\n    free(root->pointers);\n    free(root->keys);\n    free(root);\n}\n\n/**\n* Verify the results calculated using the device hopper programming \n* model using the original benchmark cuda kernel.\n*/\nbool\nverify_results(\n        record *records,\n        long records_mem,\n        knode *knodes,\n        long knodes_elem,\n        long knodes_mem,\n\n        int order,\n        long maxheight,\n        int count,\n\n        long *currKnode,\n        long *offset,\n        int *keys,\n        record *dhopper_ans) {\n\n    // Compute reference results\n    // Zero out buffers for intermediate results\n    memset(currKnode, 0, count * sizeof(long));\n    memset(offset, 0, count * sizeof(long));\n\n    // OUTPUT: ans CPU allocation\n    record *referenceAns = (record *) malloc(sizeof(record) * count);\n    // OUTPUT: ans CPU initialization\n    for (int i = 0; i < count; i++) referenceAns[i].value = -1;\n\n    kernel_gpu_cuda_wrapper(\n            records,\n            records_mem,\n            knodes,\n            knodes_elem,\n            knodes_mem,\n            order,\n            maxheight,\n            count,\n            currKnode,\n            offset,\n            keys,\n            referenceAns);\n\n    bool success = true;\n    for (int i = 0; i < count; ++i) {\n        if (referenceAns[i].value != dhopper_ans[i].value) {\n            std::cout << \"Error at index: \" << i << \" \";\n            std::cout << \"Expected value: \"\n                      << referenceAns[i].value\n                      << \" Computed value: \"\n                      << dhopper_ans[i].value << std::endl;\n            success = false;\n            break;\n        }\n    }\n\n    free(referenceAns);\n\n    return success;\n}\n\n#define REPOSITORY_PATH std::string(std::getenv(\"PLASTICITY_ROOT\"))\n\nDEVICE_HOPPER_MAIN(int argc, char* argv[]) {\n    DEVICE_HOPPER_SETUP\n\n    boost::program_options::options_description desc(\"Options\");\n    desc.add_options()(\"problem-size\", boost::program_options::value<size_t>(), \"Sample count\");\n    boost::program_options::variables_map vm;\n    boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);\n\n    size_t problem_size = 0;\n    if (vm.count(\"problem-size\") == 0) {\n        std::cerr << \"Error: Problem size is missing.\" << std::endl;\n        std::exit(EXIT_FAILURE);\n    } else {\n        problem_size = vm[\"problem-size\"].as<size_t>();\n    }\n\n    std::string path_to_input_file;\n    int count = 0;\n    if (problem_size == 3) {\n        count = 4500000;\n        path_to_input_file = REPOSITORY_PATH + \"/library/benchmarks/input_data/rodinia/b+tree/4500k.txt\";\n    } else if (problem_size == 2) {\n        count = 3000000;\n        path_to_input_file = REPOSITORY_PATH + \"/library/benchmarks/input_data/rodinia/b+tree/3000k.txt\";\n    } else if (problem_size == 1) {\n        count = 1500000;\n        path_to_input_file = REPOSITORY_PATH + \"/library/benchmarks/input_data/rodinia/b+tree/1500k.txt\";\n    } else {\n        std::cerr << \"Error: Unknown problem size\" << std::endl;\n        std::exit(EXIT_FAILURE);\n    }\n\n    // Load inputs\n    node *root = NULL;\n    // open input file\n    FILE *file_pointer = fopen(path_to_input_file.c_str(), \"r\");\n    if (file_pointer == NULL) {\n        std::cerr << \"Error: Failure to open input file.\" << std::endl;\n        std::exit(EXIT_FAILURE);\n    }\n\n    // get # of numbers in the file\n    fscanf(file_pointer, \"%d\\n\", &size);\n    int input = 0;\n    while (!feof(file_pointer)) {\n        fscanf(file_pointer, \"%d\\n\", &input);\n        root = insert(root, input, input);\n    }\n    fclose(file_pointer);\n\n    // NOTE DH: this is done to ease handling the tree data with\n    // CUDA but it can also be seen as a flattening of the tree and is \n    // not necessarily CUDA specific.\n    long mem_used = transform_to_cuda(root, 0);\n    maxheight = height(root);\n    printf(\"Max height: %d\\n\", maxheight);\n    long rootLoc = (long) knodes - (long) mem;\n\n    // Allocate memory\n    // INPUT: records CPU allocation (setting pointer in mem variable)\n    record *records_initial = (record *) mem;\n    long records_elem = (long) rootLoc / sizeof(record);\n    long records_mem = (long) rootLoc;\n    printf(\"records_elem=%d, records_unit_mem=%d, records_mem=%d\\n\", (int) records_elem, (int) sizeof(record), (int) records_mem);\n\n    // INPUT: knodes CPU allocation (setting pointer in mem variable)\n    knode *knodes_initial = (knode *) ((long) mem + (long) rootLoc);\n    long knodes_elem = ((long) (mem_used) - (long) rootLoc) / sizeof(knode);\n    long knodes_mem = (long) (mem_used) - (long) rootLoc;\n    printf(\"knodes_elem=%d, knodes_unit_mem=%d, knodes_mem=%d\\n\", (int) knodes_elem, (int) sizeof(knode), (int) knodes_mem);\n\n    // NOTE DH: buffers are copied to independent memory locations to \n    // integrate better with the current device hopper API.\n    // An alternative and likely prettier approach is not to use \n    // the common memory location in the first place.\n    record *records = (record *) device_hopper::use_existing_buffer(records_elem, sizeof(record), records_initial);\n    knode *knodes = (knode *) device_hopper::use_existing_buffer(knodes_elem, sizeof(knode), knodes_initial);\n\n    // INPUT: currKnode CPU allocation\n    long *currKnode = (long *) device_hopper::malloc(count, sizeof(long));\n    // INPUT: offset CPU initialization\n    memset(currKnode, 0, count * sizeof(long));\n\n    // INPUT: offset CPU allocation\n    long *offset = (long *) device_hopper::malloc(count, sizeof(long));\n    // INPUT: offset CPU initialization\n    memset(offset, 0, count * sizeof(long));\n\n    // INPUT: keys CPU allocation\n    int *keys = (int *) device_hopper::malloc(count, sizeof(int));\n    // INPUT: keys CPU initialization\n    for (int i = 0; i < count; i++) keys[i] = (rand() / (float) RAND_MAX) * size;\n\n    // OUTPUT: ans CPU allocation\n    record *ans = (record *) device_hopper::malloc(count, sizeof(record));\n    // OUTPUT: ans CPU initialization \n    for (int i = 0; i < count; i++) ans[i].value = -1;\n\n    // // Create parallel for\n    parallel_for pf(0, count*order, [=]DEVICE_HOPPER_LAMBDA() {\n        // private thread IDs\n        int thid = GET_ITERATION_WITHIN_BATCH();\n        int bid  = GET_BATCH_ID();\n\n        // processtree levels\n        int i;\n        for(i = 0; i < maxheight; i++){\n\n            // if value is between the two keys\n            if((knodes[currKnode[bid]].keys[thid]) <= keys[bid] && (knodes[currKnode[bid]].keys[thid+1] > keys[bid])){\n                // this conditional statement is inserted to avoid crush due to but in original code\n                // \"offset[bid]\" calculated below that addresses knodes[] in the next iteration goes outside of its bounds cause segmentation fault\n                // more specifically, values saved into knodes->indices in the main function are out of bounds of knodes that they address\n                if(knodes[offset[bid]].indices[thid] < knodes_elem){\n                    offset[bid] = knodes[offset[bid]].indices[thid];\n                }\n            }\n\n            device_hopper::batch_barrier();\n        \n            // set for next tree level\n            if(thid==0){\n                currKnode[bid] = offset[bid];\n            }\n\n            device_hopper::batch_barrier();\n        }\n\n        //At this point, we have a candidate leaf node which may contain\n        //the target record.  Check each key to hopefully find the record\n        if(knodes[currKnode[bid]].keys[thid] == keys[bid]){\n            ans[bid].value = records[knodes[currKnode[bid]].indices[thid]].value;\n        }\n    });\n    // Register buffers and specify access patterns\n    pf.add_buffer_access_patterns(\n        device_hopper::buf(knodes,    direction::IN, pattern::ALL_OR_ANY),\n        device_hopper::buf(records,   direction::IN, pattern::ALL_OR_ANY),\n        device_hopper::buf(currKnode, direction::IN_OUT, data_kind::INTERIM_RESULTS, pattern::SUCCESSIVE_SUBSECTIONS(1)),\n        device_hopper::buf(offset,    direction::IN_OUT, data_kind::INTERIM_RESULTS, pattern::SUCCESSIVE_SUBSECTIONS(1)),\n        device_hopper::buf(keys,      direction::IN,     pattern::SUCCESSIVE_SUBSECTIONS(1)),\n        device_hopper::buf(ans,       direction::IN_OUT, pattern::SUCCESSIVE_SUBSECTIONS(1)));\n    // Add scalar kernel parameters\n    pf.add_scalar_parameters(maxheight, knodes_elem);\n    // Set optional tuning parameters and call run()\n    pf.opt_set_simple_indices(true).opt_set_batch_size(256).run();\n\n    bool success = verify_results(\n                        records,\n                        records_mem,\n                        knodes,\n                        knodes_elem,\n                        knodes_mem,\n                        order,\n                        maxheight,\n                        count,\n                        currKnode,\n                        offset,\n                        keys,\n                        ans);\n    \n    free(currKnode);\n    free(offset);\n    free(keys);\n    free(ans);\n    free(mem);\n\n    if(success) {\n        std::cout << \"Info: The results are correct\" << std::endl;\n        return EXIT_SUCCESS;\n    } else {\n        std::cout << \"Error: The results are incorrect\" << std::endl;\n        return EXIT_FAILURE;\n    }\n}\n", "meta": {"hexsha": "667f31891475a1e9492b600314d825005707e1d4", "size": 38780, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmarks/rodinia_btree_find_k.cpp", "max_stars_repo_name": "paulmetzger/Device-Hopping-Paper", "max_stars_repo_head_hexsha": "323acf941080760990ad58b4ed7418462a3c8e0c", "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": "benchmarks/rodinia_btree_find_k.cpp", "max_issues_repo_name": "paulmetzger/Device-Hopping-Paper", "max_issues_repo_head_hexsha": "323acf941080760990ad58b4ed7418462a3c8e0c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmarks/rodinia_btree_find_k.cpp", "max_forks_repo_name": "paulmetzger/Device-Hopping-Paper", "max_forks_repo_head_hexsha": "323acf941080760990ad58b4ed7418462a3c8e0c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-08T22:51:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-08T22:51:16.000Z", "avg_line_length": 30.8022239873, "max_line_length": 221, "alphanum_fraction": 0.5597215059, "num_tokens": 9965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117165898111865, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.26385126491251293}}
{"text": "/**\n * \\file dcs/testbed/rao2013_dynaqos_application_manager.hpp\n *\n * \\brief Application manager based on the work by (RAO et al., 2013)\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright 2014   Marco Guazzone (marco.guazzone@gmail.com)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef DCS_TESTBED_RAO2013_DYNAQOS_APPLICATION_MANAGER_HPP\n#define DCS_TESTBED_RAO2013_DYNAQOS_APPLICATION_MANAGER_HPP\n\n\n#include <boost/smart_ptr.hpp>\n#include <cmath>\n#include <cstddef>\n#include <dcs/assert.hpp>\n#include <dcs/debug.hpp>\n#include <dcs/exception.hpp>\n#include <dcs/logging.hpp>\n#include <dcs/macro.hpp>\n#include <dcs/math/traits/float.hpp>\n#include <dcs/testbed/application_performance_category.hpp>\n#include <dcs/testbed/base_application_manager.hpp>\n#include <dcs/testbed/data_smoothers.hpp>\n#include <dcs/testbed/virtual_machine_performance_category.hpp>\n#include <fl/Headers.h>\n#include <fstream>\n#include <limits>\n#include <map>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\n\nnamespace dcs { namespace testbed {\n\n/**\n * \\brief Application manager based on the work by (Rao et al., 2013)\n * \n * \\tparam Traits The traits type\n *\n * This class implements the DynaQoS framework proposed in [1,2].\n *\n * References:\n * -# J. Rao and Y. Wei and J. Gong and C.-Z. Xu,\n *    \"QoS Guarantees and Service Differentiation for Dynamic Cloud Applications,\"\n *    IEEE Transactions on Network and Service Management 10(1):43-55, 2013.\n * -# J. Wei and C.-Z. Xu,\n *    \"eQoS: Provisioning of Client-Perceived End-to-End QoS Guarantees in Web Servers,\"\n *    IEEE Transactions on Computers 55(12):1543-1556, 2006.\n * .\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n */\ntemplate <typename TraitsT>\nclass rao2013_dynaqos_application_manager: public base_application_manager<TraitsT>\n{\n\tprivate: typedef base_application_manager<TraitsT> base_type;\n\tpublic: typedef typename base_type::traits_type traits_type;\n\tpublic: typedef typename traits_type::real_type real_type;\n\tprivate: typedef typename base_type::app_type app_type;\n\tprivate: typedef typename base_type::app_pointer app_pointer;\n\tprivate: typedef typename base_type::vm_identifier_type vm_identifier_type;\n\tprivate: typedef typename app_type::sensor_type sensor_type;\n\tprivate: typedef typename app_type::sensor_pointer sensor_pointer;\n\tprivate: typedef ::std::vector<real_type> observation_container;\n\tprivate: typedef ::std::map<application_performance_category,observation_container> observation_map;\n\tprivate: typedef ::std::map<application_performance_category,sensor_pointer> app_sensor_map;\n\tprivate: typedef ::std::map<virtual_machine_performance_category,::std::map<vm_identifier_type,sensor_pointer> > vm_sensor_map;\n\n\n\tprivate: static const ::std::string alpha_fuzzy_var_name;\n\tprivate: static const ::std::string e_fuzzy_var_name;\n\tprivate: static const ::std::string de_fuzzy_var_name;\n\tprivate: static const ::std::string du_fuzzy_var_name;\n\n\n\tpublic: rao2013_dynaqos_application_manager()\n\t: gamma_(0.8),\n\t  Ke_(0),\n\t  Kde_(0),\n\t  p_rc_fuzzy_eng_(new ::fl::Engine()),\n\t  p_sfc_fuzzy_eng_(new ::fl::Engine())\n\t{\n\t\tinit();\n\t}\n\n\tpublic: void discount_factor(real_type value)\n\t{\n\t\tgamma_ = value;\n\t}\n\n\tpublic: real_type discount_factor() const\n\t{\n\t\treturn gamma_;\n\t}\n\n\tpublic: void export_data_to(::std::string const& fname)\n\t{\n\t\tdat_fname_ = fname;\n\t}\n\n\tprivate: void init()\n\t{\n\t\tDCS_DEBUG_ASSERT( p_rc_fuzzy_eng_ );\n\t\tDCS_DEBUG_ASSERT( p_sfc_fuzzy_eng_ );\n\n\t\tconst real_type one_third = 1.0/3.0;\n\t\tconst real_type two_third = 2.0/3.0;\n\t\tconst real_type one_sixth = 1.0/6.0;\n\t\tconst real_type five_sixth = 5.0/6.0;\n\n\t\t::fl::InputVariable* p_iv = 0;\n\t\t::fl::OutputVariable* p_ov = 0;\n\t\t::fl::RuleBlock* p_rules = 0;\n\n\t\t// Setup the Resource Controller\n\t\t//   Membership functions taken from (Wei et al.,2006) [2]\n\n\t\tfor (::std::size_t i = 0; i < 2; ++i)\n\t\t{\n\t\t\tp_iv = new ::fl::InputVariable();\n\t\t\tp_iv->setEnabled(true);\n\t\t\tswitch (i)\n\t\t\t{\n\t\t\t\tcase 0: // \\Delta e(k)\n\t\t\t\t\tp_iv->setName(de_fuzzy_var_name);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1: // e(k)\n\t\t\t\t\tp_iv->setName(e_fuzzy_var_name);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tp_iv->setRange(-1, 1);\n\t\t\tp_iv->addTerm(new ::fl::Ramp(\"NL\", -two_third, -1));\n\t\t\tp_iv->addTerm(new ::fl::Triangle(\"NM\", -1, -two_third, -one_third));\n\t\t\tp_iv->addTerm(new ::fl::Triangle(\"NS\", -two_third, -one_third, 0));\n\t\t\tp_iv->addTerm(new ::fl::Triangle(\"ZE\", -one_third, 0, one_third));\n\t\t\tp_iv->addTerm(new ::fl::Triangle(\"PS\", 0, one_third, two_third));\n\t\t\tp_iv->addTerm(new ::fl::Triangle(\"PM\", one_third, two_third, 1));\n\t\t\tp_iv->addTerm(new ::fl::Ramp(\"PL\", two_third, 1));\n\t\t\tp_rc_fuzzy_eng_->addInputVariable(p_iv);\n\t\t}\n\n\t\tp_ov = new ::fl::OutputVariable();\n\t\tp_ov->setEnabled(true);\n\t\tp_ov->setName(du_fuzzy_var_name);\n\t\tp_ov->setRange(-1, 1);\n#if defined(FL_VERSION) // Until fuzzylite v. 5.x (the FL_VERSION macro was removed since fuzzylite 6.x)\n\t\tp_ov->fuzzyOutput()->setAccumulation(new ::fl::Maximum());\n#else // Since fuzzylite v. 6.x\n\t\tp_ov->fuzzyOutput()->setAggregation(new ::fl::Maximum());\n#endif // FL_VERSION\n\t\tp_ov->setDefuzzifier(new ::fl::Centroid());\n\t\tp_ov->setDefaultValue(::fl::nan);\n\t\tp_ov->setLockPreviousValue(false);\n\t\tp_ov->addTerm(new ::fl::Ramp(\"NL\", -two_third, -1));\n\t\tp_ov->addTerm(new ::fl::Triangle(\"NM\", -1, -two_third, -one_third));\n\t\tp_ov->addTerm(new ::fl::Triangle(\"NS\", -two_third, -one_third, 0));\n\t\tp_ov->addTerm(new ::fl::Triangle(\"ZE\", -one_third, 0, one_third));\n\t\tp_ov->addTerm(new ::fl::Triangle(\"PS\", 0, one_third, two_third));\n\t\tp_ov->addTerm(new ::fl::Triangle(\"PM\", one_third, two_third, 1));\n\t\tp_ov->addTerm(new ::fl::Ramp(\"PL\", two_third, 1));\n\t\tp_rc_fuzzy_eng_->addOutputVariable(p_ov);\n\n\t\tp_rules = new ::fl::RuleBlock();\n\t\tp_rules->setEnabled(true);\n\t\tp_rules->setConjunction(new ::fl::Minimum());\n\t\tp_rules->setDisjunction(new ::fl::Maximum());\n\t\tp_rules->setImplication(new ::fl::Minimum());\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NL and \" + de_fuzzy_var_name + \" is NL then \" + du_fuzzy_var_name + \" is PL\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NL and \" + de_fuzzy_var_name + \" is NM then \" + du_fuzzy_var_name + \" is PL\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NL and \" + de_fuzzy_var_name + \" is NS then \" + du_fuzzy_var_name + \" is PL\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NL and \" + de_fuzzy_var_name + \" is ZE then \" + du_fuzzy_var_name + \" is PL\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NL and \" + de_fuzzy_var_name + \" is PS then \" + du_fuzzy_var_name + \" is PM\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NL and \" + de_fuzzy_var_name + \" is PM then \" + du_fuzzy_var_name + \" is PS\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NL and \" + de_fuzzy_var_name + \" is PL then \" + du_fuzzy_var_name + \" is ZE\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NM and \" + de_fuzzy_var_name + \" is NL then \" + du_fuzzy_var_name + \" is PL\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NM and \" + de_fuzzy_var_name + \" is NM then \" + du_fuzzy_var_name + \" is PL\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NM and \" + de_fuzzy_var_name + \" is NS then \" + du_fuzzy_var_name + \" is PL\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NM and \" + de_fuzzy_var_name + \" is ZE then \" + du_fuzzy_var_name + \" is PM\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NM and \" + de_fuzzy_var_name + \" is PS then \" + du_fuzzy_var_name + \" is PS\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NM and \" + de_fuzzy_var_name + \" is PM then \" + du_fuzzy_var_name + \" is ZE\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NM and \" + de_fuzzy_var_name + \" is PL then \" + du_fuzzy_var_name + \" is NS\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NS and \" + de_fuzzy_var_name + \" is NL then \" + du_fuzzy_var_name + \" is PL\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NS and \" + de_fuzzy_var_name + \" is NM then \" + du_fuzzy_var_name + \" is PL\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NS and \" + de_fuzzy_var_name + \" is NS then \" + du_fuzzy_var_name + \" is PM\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NS and \" + de_fuzzy_var_name + \" is ZE then \" + du_fuzzy_var_name + \" is PS\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NS and \" + de_fuzzy_var_name + \" is PS then \" + du_fuzzy_var_name + \" is ZE\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NS and \" + de_fuzzy_var_name + \" is PM then \" + du_fuzzy_var_name + \" is NS\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NS and \" + de_fuzzy_var_name + \" is PL then \" + du_fuzzy_var_name + \" is NM\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is ZE and \" + de_fuzzy_var_name + \" is NL then \" + du_fuzzy_var_name + \" is PL\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is ZE and \" + de_fuzzy_var_name + \" is NM then \" + du_fuzzy_var_name + \" is PM\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is ZE and \" + de_fuzzy_var_name + \" is NS then \" + du_fuzzy_var_name + \" is PS\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is ZE and \" + de_fuzzy_var_name + \" is ZE then \" + du_fuzzy_var_name + \" is ZE\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is ZE and \" + de_fuzzy_var_name + \" is PS then \" + du_fuzzy_var_name + \" is NS\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is ZE and \" + de_fuzzy_var_name + \" is PM then \" + du_fuzzy_var_name + \" is NM\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is ZE and \" + de_fuzzy_var_name + \" is PL then \" + du_fuzzy_var_name + \" is NL\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PS and \" + de_fuzzy_var_name + \" is NL then \" + du_fuzzy_var_name + \" is PM\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PS and \" + de_fuzzy_var_name + \" is NM then \" + du_fuzzy_var_name + \" is PS\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PS and \" + de_fuzzy_var_name + \" is NS then \" + du_fuzzy_var_name + \" is ZE\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PS and \" + de_fuzzy_var_name + \" is ZE then \" + du_fuzzy_var_name + \" is NS\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PS and \" + de_fuzzy_var_name + \" is PS then \" + du_fuzzy_var_name + \" is NM\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PS and \" + de_fuzzy_var_name + \" is PM then \" + du_fuzzy_var_name + \" is NL\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PS and \" + de_fuzzy_var_name + \" is PL then \" + du_fuzzy_var_name + \" is NL\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PM and \" + de_fuzzy_var_name + \" is NL then \" + du_fuzzy_var_name + \" is PS\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PM and \" + de_fuzzy_var_name + \" is NM then \" + du_fuzzy_var_name + \" is ZE\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PM and \" + de_fuzzy_var_name + \" is NS then \" + du_fuzzy_var_name + \" is NS\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PM and \" + de_fuzzy_var_name + \" is ZE then \" + du_fuzzy_var_name + \" is NM\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PM and \" + de_fuzzy_var_name + \" is PS then \" + du_fuzzy_var_name + \" is NL\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PM and \" + de_fuzzy_var_name + \" is PM then \" + du_fuzzy_var_name + \" is NL\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PM and \" + de_fuzzy_var_name + \" is PL then \" + du_fuzzy_var_name + \" is NL\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PL and \" + de_fuzzy_var_name + \" is NL then \" + du_fuzzy_var_name + \" is ZE\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PL and \" + de_fuzzy_var_name + \" is NM then \" + du_fuzzy_var_name + \" is NS\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PL and \" + de_fuzzy_var_name + \" is NS then \" + du_fuzzy_var_name + \" is NM\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PL and \" + de_fuzzy_var_name + \" is ZE then \" + du_fuzzy_var_name + \" is NL\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PL and \" + de_fuzzy_var_name + \" is PS then \" + du_fuzzy_var_name + \" is NL\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PL and \" + de_fuzzy_var_name + \" is PM then \" + du_fuzzy_var_name + \" is NL\", p_rc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PL and \" + de_fuzzy_var_name + \" is PL then \" + du_fuzzy_var_name + \" is NL\", p_rc_fuzzy_eng_.get()));\n\t\tp_rc_fuzzy_eng_->addRuleBlock(p_rules);\n\n\t\t// Setup the Scaling Factor Controller\n\t\t//   Membership functions taken from (Wei et al.,2006) [2]\n\n\t\tfor (::std::size_t i = 0; i < 2; ++i)\n\t\t{\n\t\t\tp_iv = new ::fl::InputVariable();\n\t\t\tp_iv->setEnabled(true);\n\t\t\tswitch (i)\n\t\t\t{\n\t\t\t\tcase 0: // \\Delta e(k)\n\t\t\t\t\tp_iv->setName(de_fuzzy_var_name);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1: // e(k)\n\t\t\t\t\tp_iv->setName(e_fuzzy_var_name);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tp_iv->setRange(-1, 1);\n\t\t\tp_iv->addTerm(new ::fl::Ramp(\"NL\", -two_third, -1));\n\t\t\tp_iv->addTerm(new ::fl::Triangle(\"NM\", -1, -two_third, -one_third));\n\t\t\tp_iv->addTerm(new ::fl::Triangle(\"NS\", -two_third, -one_third, 0));\n\t\t\tp_iv->addTerm(new ::fl::Triangle(\"ZE\", -one_third, 0, one_third));\n\t\t\tp_iv->addTerm(new ::fl::Triangle(\"PS\", 0, one_third, two_third));\n\t\t\tp_iv->addTerm(new ::fl::Triangle(\"PM\", one_third, two_third, 1));\n\t\t\tp_iv->addTerm(new ::fl::Ramp(\"PL\", two_third, 1));\n\t\t\tp_sfc_fuzzy_eng_->addInputVariable(p_iv);\n\t\t}\n\n\t\tp_ov = new ::fl::OutputVariable();\n\t\tp_ov->setEnabled(true);\n\t\tp_ov->setName(alpha_fuzzy_var_name);\n\t\tp_ov->setRange(0, 1);\n#if defined(FL_VERSION) // Until fuzzylite v. 5.x (the FL_VERSION macro was removed since fuzzylite 6.x)\n\t\tp_ov->fuzzyOutput()->setAccumulation(new ::fl::Maximum());\n#else // Since fuzzylite v. 6.x\n\t\tp_ov->fuzzyOutput()->setAggregation(new ::fl::Maximum());\n#endif // FL_VERSION\n\t\tp_ov->setDefuzzifier(new ::fl::Centroid());\n\t\tp_ov->setDefaultValue(::fl::nan);\n\t\tp_ov->setLockPreviousValue(false);\n\t\tp_ov->addTerm(new ::fl::Ramp(\"ZE\", one_sixth, 0));\n\t\tp_ov->addTerm(new ::fl::Triangle(\"VS\", 0, one_sixth, one_third));\n\t\tp_ov->addTerm(new ::fl::Triangle(\"SM\", one_sixth, one_third, 0.5));\n\t\tp_ov->addTerm(new ::fl::Triangle(\"SL\", one_third, 0.5, two_third));\n\t\tp_ov->addTerm(new ::fl::Triangle(\"ML\", 0.5, two_third, five_sixth));\n\t\tp_ov->addTerm(new ::fl::Triangle(\"LG\", two_third, five_sixth, 1));\n\t\tp_ov->addTerm(new ::fl::Ramp(\"VL\", five_sixth, 1));\n\t\tp_sfc_fuzzy_eng_->addOutputVariable(p_ov);\n\n\t\tp_rules = new ::fl::RuleBlock();\n\t\tp_rules->setEnabled(true);\n\t\tp_rules->setConjunction(new ::fl::Minimum());\n\t\tp_rules->setDisjunction(new ::fl::Maximum());\n\t\tp_rules->setImplication(new ::fl::Minimum());\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NL and \" + de_fuzzy_var_name + \" is NL then \" + alpha_fuzzy_var_name + \" is VL\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NL and \" + de_fuzzy_var_name + \" is NM then \" + alpha_fuzzy_var_name + \" is VL\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NL and \" + de_fuzzy_var_name + \" is NS then \" + alpha_fuzzy_var_name + \" is VL\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NL and \" + de_fuzzy_var_name + \" is ZE then \" + alpha_fuzzy_var_name + \" is SM\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NL and \" + de_fuzzy_var_name + \" is PS then \" + alpha_fuzzy_var_name + \" is VS\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NL and \" + de_fuzzy_var_name + \" is PM then \" + alpha_fuzzy_var_name + \" is VS\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NL and \" + de_fuzzy_var_name + \" is PL then \" + alpha_fuzzy_var_name + \" is ZE\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NM and \" + de_fuzzy_var_name + \" is NL then \" + alpha_fuzzy_var_name + \" is VL\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NM and \" + de_fuzzy_var_name + \" is NM then \" + alpha_fuzzy_var_name + \" is VL\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NM and \" + de_fuzzy_var_name + \" is NS then \" + alpha_fuzzy_var_name + \" is LG\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NM and \" + de_fuzzy_var_name + \" is ZE then \" + alpha_fuzzy_var_name + \" is SL\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NM and \" + de_fuzzy_var_name + \" is PS then \" + alpha_fuzzy_var_name + \" is SM\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NM and \" + de_fuzzy_var_name + \" is PM then \" + alpha_fuzzy_var_name + \" is SM\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NM and \" + de_fuzzy_var_name + \" is PL then \" + alpha_fuzzy_var_name + \" is SM\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NS and \" + de_fuzzy_var_name + \" is NL then \" + alpha_fuzzy_var_name + \" is VL\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NS and \" + de_fuzzy_var_name + \" is NM then \" + alpha_fuzzy_var_name + \" is VL\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NS and \" + de_fuzzy_var_name + \" is NS then \" + alpha_fuzzy_var_name + \" is LG\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NS and \" + de_fuzzy_var_name + \" is ZE then \" + alpha_fuzzy_var_name + \" is ML\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NS and \" + de_fuzzy_var_name + \" is PS then \" + alpha_fuzzy_var_name + \" is VS\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NS and \" + de_fuzzy_var_name + \" is PM then \" + alpha_fuzzy_var_name + \" is SM\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is NS and \" + de_fuzzy_var_name + \" is PL then \" + alpha_fuzzy_var_name + \" is SL\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is ZE and \" + de_fuzzy_var_name + \" is NL then \" + alpha_fuzzy_var_name + \" is LG\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is ZE and \" + de_fuzzy_var_name + \" is NM then \" + alpha_fuzzy_var_name + \" is ML\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is ZE and \" + de_fuzzy_var_name + \" is NS then \" + alpha_fuzzy_var_name + \" is SL\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is ZE and \" + de_fuzzy_var_name + \" is ZE then \" + alpha_fuzzy_var_name + \" is ZE\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is ZE and \" + de_fuzzy_var_name + \" is PS then \" + alpha_fuzzy_var_name + \" is SL\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is ZE and \" + de_fuzzy_var_name + \" is PM then \" + alpha_fuzzy_var_name + \" is ML\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is ZE and \" + de_fuzzy_var_name + \" is PL then \" + alpha_fuzzy_var_name + \" is LG\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PS and \" + de_fuzzy_var_name + \" is NL then \" + alpha_fuzzy_var_name + \" is SL\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PS and \" + de_fuzzy_var_name + \" is NM then \" + alpha_fuzzy_var_name + \" is SM\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PS and \" + de_fuzzy_var_name + \" is NS then \" + alpha_fuzzy_var_name + \" is VS\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PS and \" + de_fuzzy_var_name + \" is ZE then \" + alpha_fuzzy_var_name + \" is ML\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PS and \" + de_fuzzy_var_name + \" is PS then \" + alpha_fuzzy_var_name + \" is LG\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PS and \" + de_fuzzy_var_name + \" is PM then \" + alpha_fuzzy_var_name + \" is LG\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PS and \" + de_fuzzy_var_name + \" is PL then \" + alpha_fuzzy_var_name + \" is VL\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PM and \" + de_fuzzy_var_name + \" is NL then \" + alpha_fuzzy_var_name + \" is SM\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PM and \" + de_fuzzy_var_name + \" is NM then \" + alpha_fuzzy_var_name + \" is SM\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PM and \" + de_fuzzy_var_name + \" is NS then \" + alpha_fuzzy_var_name + \" is SM\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PM and \" + de_fuzzy_var_name + \" is ZE then \" + alpha_fuzzy_var_name + \" is SL\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PM and \" + de_fuzzy_var_name + \" is PS then \" + alpha_fuzzy_var_name + \" is LG\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PM and \" + de_fuzzy_var_name + \" is PM then \" + alpha_fuzzy_var_name + \" is VL\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PM and \" + de_fuzzy_var_name + \" is PL then \" + alpha_fuzzy_var_name + \" is VL\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PL and \" + de_fuzzy_var_name + \" is NL then \" + alpha_fuzzy_var_name + \" is ZE\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PL and \" + de_fuzzy_var_name + \" is NM then \" + alpha_fuzzy_var_name + \" is VS\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PL and \" + de_fuzzy_var_name + \" is NS then \" + alpha_fuzzy_var_name + \" is VS\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PL and \" + de_fuzzy_var_name + \" is ZE then \" + alpha_fuzzy_var_name + \" is SM\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PL and \" + de_fuzzy_var_name + \" is PS then \" + alpha_fuzzy_var_name + \" is VL\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PL and \" + de_fuzzy_var_name + \" is PM then \" + alpha_fuzzy_var_name + \" is VL\", p_sfc_fuzzy_eng_.get()));\n\t\tp_rules->addRule(::fl::Rule::parse(\"if \" + e_fuzzy_var_name + \" is PL and \" + de_fuzzy_var_name + \" is PL then \" + alpha_fuzzy_var_name + \" is VL\", p_sfc_fuzzy_eng_.get()));\n\t\tp_sfc_fuzzy_eng_->addRuleBlock(p_rules);\n\t}\n\n\tprivate: void do_reset()\n\t{\n\t\ttypedef typename base_type::target_value_map::const_iterator target_iterator;\n\t\ttypedef typename app_type::vm_pointer vm_pointer;\n\n\t\tconst ::std::vector<vm_pointer> vms = this->app().vms();\n\t\tconst ::std::size_t nvms = this->app().num_vms();\n\n\t\t// Reset output sensors\n\t\tapp_sensors_.clear();\n\t\tconst target_iterator tgt_end_it = this->target_values().end();\n\t\tfor (target_iterator tgt_it = this->target_values().begin();\n\t\t\t tgt_it != tgt_end_it;\n\t\t\t ++tgt_it)\n\t\t{\n\t\t\tconst application_performance_category cat(tgt_it->first);\n\n\t\t\tapp_sensors_[cat] = this->app().sensor(cat);\n\t\t\tes_[cat] = 0;\n\t\t}\n\n\t\t// Reset input sensors\n\t\tvm_sensors_.clear();\n\t\tfor (::std::size_t i = 0; i < nvms; ++i)\n\t\t{\n\t\t\tconst virtual_machine_performance_category cat = cpu_util_virtual_machine_performance;\n\t\t\tvm_pointer p_vm = vms[i];\n\n\t\t\tvm_sensors_[cat][p_vm->id()] = p_vm->sensor(cat);\n\t\t}\n\n\t\t// Reset counters\n\t\tctl_count_ = ctl_skip_count_\n\t\t\t\t   = ctl_fail_count_\n\t\t\t\t   = 0;\n\n\t\t// Reset fuzzy controllers\n\t\tp_rc_fuzzy_eng_->restart();\n\t\tp_sfc_fuzzy_eng_->restart();\n\n\t\t// Reset input scaling factors\n\t\tKe_ = Kde_ = 0;\n\n\t\t// Reset VCPU util estimator and smoother\n\t\tfor (::std::size_t i = 0; i < nvms; ++i)\n\t\t{\n\t\t\t//this->data_estimator(cpu_util_virtual_machine_performance, vms[i]->id(), ::boost::make_shared< testbed::mean_estimator<real_type> >());\n\t\t\tthis->data_smoother(cpu_util_virtual_machine_performance, vms[i]->id(), ::boost::make_shared< testbed::brown_single_exponential_smoother<real_type> >(0.9));\n\t\t\t//this->data_smoother(cpu_util_virtual_machine_performance, vms[i]->id(), ::boost::make_shared< testbed::holt_winters_double_exponential_smoother<real_type> >(beta_));\n\t\t}\n\n\t\t// Reset output data file and write header\n\t\tif (p_dat_ofs_ && p_dat_ofs_->is_open())\n\t\t{\n\t\t\tp_dat_ofs_->close();\n\t\t}\n\t\tp_dat_ofs_.reset();\n\t\tif (!dat_fname_.empty())\n\t\t{\n\t\t\tp_dat_ofs_ = ::boost::make_shared< ::std::ofstream >(dat_fname_.c_str());\n\t\t\tif (!p_dat_ofs_->good())\n\t\t\t{\n\t\t\t\t::std::ostringstream oss;\n\t\t\t\toss << \"Cannot open output data file '\" << dat_fname_ << \"'\";\n\n\t\t\t\tDCS_EXCEPTION_THROW(::std::runtime_error, oss.str());\n\t\t\t}\n\n\t\t\t*p_dat_ofs_ << \"\\\"ts\\\"\";\n\n\t\t\tconst ::std::size_t nvms = this->app().num_vms();\n\t\t\tfor (::std::size_t i = 0; i < nvms; ++i)\n\t\t\t{\n\t\t\t\t*p_dat_ofs_ << \",\\\"Cap_{\" << vms[i]->id() << \"}\\\",\\\"Share_{\" << vms[i]->id() << \"}\\\",\\\"Util_{\" << vms[i]->id() << \"}\\\"\";\n\t\t\t}\n\t\t\tfor (target_iterator tgt_it = this->target_values().begin();\n\t\t\t\t tgt_it != tgt_end_it;\n\t\t\t\t ++tgt_it)\n\t\t\t{\n\t\t\t\tconst application_performance_category cat = tgt_it->first;\n\n\t\t\t\t*p_dat_ofs_ << \",\\\"y_{\" << cat << \"}\\\",\\\"r_{\" << cat << \"}\\\"\";\n\t\t\t}\n\t\t\t*p_dat_ofs_ << \",\\\"alpha\\\",\\\"Delta u\\\",\\\"K_e\\\",\\\"K_{Delta e}\\\",\\\"# Controls\\\",\\\"# Skip Controls\\\",\\\"# Fail Controls\\\"\";\n\t\t\t*p_dat_ofs_ << ::std::endl;\n\t\t}\n\t}\n\n\tprivate: void do_sample()\n\t{\n\t\ttypedef typename vm_sensor_map::const_iterator vm_sensor_iterator;\n\t\ttypedef typename app_sensor_map::const_iterator app_sensor_iterator;\n\t\ttypedef ::std::vector<typename sensor_type::observation_type> obs_container;\n\t\ttypedef typename obs_container::const_iterator obs_iterator;\n\n\t\tDCS_DEBUG_TRACE(\"(\" << this << \") BEGIN Do SAMPLE - Count: \" << ctl_count_ << \"/\" << ctl_skip_count_ << \"/\" << ctl_fail_count_);\n\n\t\t// Collect VM values\n\t\tconst vm_sensor_iterator vm_sens_end_it = vm_sensors_.end();\n\t\tfor (vm_sensor_iterator vm_sens_it = vm_sensors_.begin();\n\t\t\t vm_sens_it != vm_sens_end_it;\n\t\t\t ++vm_sens_it)\n\t\t{\n\t\t\tconst virtual_machine_performance_category cat = vm_sens_it->first;\n\n\t\t\tconst typename vm_sensor_map::mapped_type::const_iterator vm_end_it = vm_sens_it->second.end();\n\t\t\tfor (typename vm_sensor_map::mapped_type::const_iterator vm_it = vm_sens_it->second.begin();\n\t\t\t\t vm_it != vm_end_it;\n\t\t\t\t ++vm_it)\n\t\t\t{\n\t\t\t\tconst vm_identifier_type vm_id = vm_it->first;\n\t\t\t\tsensor_pointer p_sens = vm_it->second;\n\n\t\t\t\t// check: p_sens != null\n\t\t\t\tDCS_DEBUG_ASSERT( p_sens );\n\n\t\t\t\tp_sens->sense();\n\t\t\t\tif (p_sens->has_observations())\n\t\t\t\t{\n\t\t\t\t\tconst obs_container obs = p_sens->observations();\n\t\t\t\t\tconst obs_iterator end_it = obs.end();\n\t\t\t\t\tfor (obs_iterator it = obs.begin();\n\t\t\t\t\t\t it != end_it;\n\t\t\t\t\t\t ++it)\n\t\t\t\t\t{\n\t\t\t\t\t\t//this->data_estimator(cat, vm_id).collect(it->value());\n\t\t\t\t\t\tthis->data_smoother(cat, vm_id).smooth(it->value());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Collect App values\n\t\tconst app_sensor_iterator app_sens_end_it = app_sensors_.end();\n\t\tfor (app_sensor_iterator app_sens_it = app_sensors_.begin();\n\t\t\t app_sens_it != app_sens_end_it;\n\t\t\t ++app_sens_it)\n\t\t{\n\t\t\tconst application_performance_category cat(app_sens_it->first);\n\n\t\t\tsensor_pointer p_sens(app_sens_it->second);\n\n\t\t\t// check: p_sens != null\n\t\t\tDCS_DEBUG_ASSERT( p_sens );\n\n\t\t\tp_sens->sense();\n\t\t\tif (p_sens->has_observations())\n\t\t\t{\n\t\t\t\tconst obs_container obs = p_sens->observations();\n\t\t\t\tconst obs_iterator end_it = obs.end();\n\t\t\t\tfor (obs_iterator it = obs.begin();\n\t\t\t\t\t it != end_it;\n\t\t\t\t\t ++it)\n\t\t\t\t{\n\t\t\t\t\tthis->data_estimator(cat).collect(it->value());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tDCS_DEBUG_TRACE(\"(\" << this << \") END Do SAMPLE - Count: \" << ctl_count_ << \"/\" << ctl_skip_count_ << \"/\" << ctl_fail_count_);\n\t}\n\n\tprivate: void do_control()\n\t{\n\t\ttypedef typename base_type::target_value_map::const_iterator target_iterator;\n\t\ttypedef typename app_type::vm_pointer vm_pointer;\n\n\t\tDCS_DEBUG_TRACE(\"(\" << this << \") BEGIN Do CONTROL - Count: \" << ctl_count_ << \"/\" << ctl_skip_count_ << \"/\" << ctl_fail_count_);\n\n\t\t++ctl_count_;\n\n\t\tbool skip_ctl = false;\n\n\t\t::std::vector<vm_pointer> vms = this->app().vms();\n\t\tconst ::std::size_t nvms = vms.size();\n\n\t\t//std::map<application_performance_category,real_type> es_;\n\t\tstd::map<application_performance_category,real_type> des;\n\n\t\tconst target_iterator tgt_end_it = this->target_values().end();\n\t\tfor (target_iterator tgt_it = this->target_values().begin();\n\t\t\t tgt_it != tgt_end_it;\n\t\t\t ++tgt_it)\n\t\t{\n\t\t\tconst application_performance_category cat(tgt_it->first);\n\n\t\t\t// Compute a summary statistics of collected observation\n\t\t\tif (this->data_estimator(cat).count() > 0)\n\t\t\t{\n\t\t\t\tconst real_type y = this->data_estimator(cat).estimate();\n\t\t\t\tconst real_type r = this->target_value(cat);\n\n\t\t\t\treal_type e = 0;\n\t\t\t\tswitch (cat)\n\t\t\t\t{\n\t\t\t\t\tcase response_time_application_performance:\n\t\t\t\t\t\tif (dcs::math::float_traits<real_type>::approximately_less_equal(y, 2.0*r))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\te = (r-y)/r;\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\te = -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase throughput_application_performance:\n\t\t\t\t\t\tif (dcs::math::float_traits<real_type>::approximately_greater_equal(y, 0.5*r))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\te = (y-r)/r;\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\te = -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (es_.count(cat) > 0)\n\t\t\t\t{\n\t\t\t\t\tdes[cat] = e-es_.at(cat);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tdes[cat] = e;\n\t\t\t\t}\n\t\t\t\tes_[cat] = e;\nDCS_DEBUG_TRACE(\"APP Performance Category: \" << cat << \" - Y(k): \" << y << \" - R: \" << r << \" -> E(k+1): \" << es_.at(cat) << \" - DeltaE(k+1): \" << des.at(cat));//XXX\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// No observation collected during the last control interval\n\t\t\t\tDCS_DEBUG_TRACE(\"No output observation collected during the last control interval -> Skip control\");\n\t\t\t\tskip_ctl = true;\n\t\t\t\tbreak;\n\t\t\t}\n#ifdef DCSXX_TESTBED_EXP_APP_MGR_RESET_ESTIMATION_EVERY_INTERVAL\n\t\t\tthis->data_estimator(cat).reset();\n#endif // DCSXX_TESTBED_EXP_APP_MGR_RESET_ESTIMATION_EVERY_INTERVAL\n\t\t}\n\n        if (!skip_ctl)\n        {\n\t\t\t//FIXME: actually we only handle SISO systems\n\t\t\tDCS_ASSERT(es_.size() == 1,\n\t\t\t\t\t   DCS_EXCEPTION_THROW(::std::runtime_error,\n\t\t\t\t\t   \"Only SISO system are currently managed\"));\n\n\t\t\t// Compute the input to the RC fuzzy controller\n\t\t\tconst real_type Ke = (ctl_count_ > 1) ? ::std::abs(Ke_) : 1.0;\n\t\t\tconst real_type Kde = (ctl_count_ > 1) ? ::std::abs(Kde_) : 1.0;\n\t\t\tconst real_type e = Ke*es_.begin()->second;\n\t\t\tconst real_type de = Kde*des.begin()->second;\n\n\t\t\t// Update input scaling factors\n\t\t\tKe_ = (1-gamma_)*Ke_ + gamma_*es_.begin()->second;\n\t\t\tKde_ = (1-gamma_)*Kde_ - gamma_*des.begin()->second;\n\n\t\t\t// Perform fuzzy control\n\t\t\tbool ok = false;\n\t\t\treal_type du = 0;\n\t\t\treal_type alpha = 0;\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\t// Compute \\Delta u(k)\n\t\t\t\tp_rc_fuzzy_eng_->setInputValue(e_fuzzy_var_name, e);\n\t\t\t\tp_rc_fuzzy_eng_->setInputValue(de_fuzzy_var_name, de);\n\t\t\t\tp_rc_fuzzy_eng_->process();\n\t\t\t\tdu = p_rc_fuzzy_eng_->getOutputValue(du_fuzzy_var_name);\n\n\t\t\t\t// Compute the \\alpha(k) scaling factor\n\t\t\t\tp_sfc_fuzzy_eng_->setInputValue(e_fuzzy_var_name, e);\n\t\t\t\tp_sfc_fuzzy_eng_->setInputValue(de_fuzzy_var_name, de);\n\t\t\t\tp_sfc_fuzzy_eng_->process();\n\t\t\t\talpha = p_sfc_fuzzy_eng_->getOutputValue(alpha_fuzzy_var_name);\n\n\t\t\t\tok = true;\n\t\t\t}\n\t\t\tcatch (::fl::Exception const& fe)\n\t\t\t{\n\t\t\t\tDCS_DEBUG_TRACE( \"Caught exception: \" << fe.what() );\n\n\t\t\t\t::std::ostringstream oss;\n\t\t\t\toss << \"Unable to compute optimal control: \" << fe.what();\n\t\t\t\t::dcs::log_warn(DCS_LOGGING_AT, oss.str());\n\t\t\t}\n\t\t\tcatch (::std::exception const& se)\n\t\t\t{\n\t\t\t\tDCS_DEBUG_TRACE( \"Caught exception: \" << se.what() );\n\n\t\t\t\t::std::ostringstream oss;\n\t\t\t\toss << \"Unable to compute optimal control: \" << se.what();\n\t\t\t\t::dcs::log_warn(DCS_LOGGING_AT, oss.str());\n\t\t\t}\n\n\t\t\t// Apply fuzzy control results\n\t\t\tif (ok)\n\t\t\t{\n\t\t\t\tfor (::std::size_t i = 0; i < nvms; ++i)\n\t\t\t\t{\n\t\t\t\t\tvm_pointer p_vm = vms[i];\n\n\t\t\t\t\tconst real_type c = p_vm->cpu_share();\n\n\t\t\t\t\t// Compute the output amplifier\n\t\t\t\t\tconst real_type Kdu = c*0.5*::std::abs(e);\n\n\t\t\t\t\tconst real_type u = ::std::max(::std::min(c+alpha*Kdu*du, 1.0), 0.0);\n\n\t\t\t\t\tDCS_DEBUG_TRACE(\"VM '\" << p_vm->id() << \"' - old-share: \" << c << \" - new-share: \" << u);\n\n\t\t\t\t\tif (::std::isfinite(u) && !::dcs::math::float_traits<real_type>::essentially_equal(c, u))\n\t\t\t\t\t{\n\t\t\t\t\t\tp_vm->cpu_share(u);\nDCS_DEBUG_TRACE(\"VM \" << vms[i]->id() << \", Alpha: \" << alpha << \", DeltaU: \" << du << \", K_{DeltaU}: \" << Kdu << \" -> U(k+1): \" << u);//XXX\n\t\t\t\t\t}\n\t\t\t\t}\nDCS_DEBUG_TRACE(\"Optimal control applied\");//XXX\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t++ctl_fail_count_;\n\n\t\t\t\t::std::ostringstream oss;\n\t\t\t\toss << \"Control not applied: failed to solve the control problem\";\n\t\t\t\t::dcs::log_warn(DCS_LOGGING_AT, oss.str());\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t++ctl_skip_count_;\n\t\t}\n\n\t\t// Export to file\n\t\tif (p_dat_ofs_)\n\t\t{\n\t\t\t*p_dat_ofs_ << ::std::time(0) << \",\";\n\t\t\tfor (::std::size_t i = 0; i < nvms; ++i)\n\t\t\t{\n\t\t\t\tconst vm_pointer p_vm = vms[i];\n\n\t\t\t\t// check: p_vm != null\n\t\t\t\tDCS_DEBUG_ASSERT( p_vm );\n\n\t\t\t\tif (i != 0)\n\t\t\t\t{\n\t\t\t\t\t*p_dat_ofs_ << \",\";\n\t\t\t\t}\n\t\t\t\t*p_dat_ofs_ << p_vm->cpu_cap() << \",\" << p_vm->cpu_share() << \",\" << this->data_smoother(cpu_util_virtual_machine_performance, p_vm->id()).forecast(0);\n\t\t\t}\n\t\t\t*p_dat_ofs_ << \",\";\n\t\t\tconst target_iterator tgt_end_it = this->target_values().end();\n\t\t\tfor (target_iterator tgt_it = this->target_values().begin();\n\t\t\t\t tgt_it != tgt_end_it;\n\t\t\t\t ++tgt_it)\n\t\t\t{\n\t\t\t\tconst application_performance_category cat = tgt_it->first;\n\n\t\t\t\tif (tgt_it != this->target_values().begin())\n\t\t\t\t{\n\t\t\t\t\t*p_dat_ofs_ << \",\";\n\t\t\t\t}\n\t\t\t\tconst real_type y = this->data_estimator(cat).estimate();\n\t\t\t\tconst real_type r = tgt_it->second;\n\t\t\t\t*p_dat_ofs_ << y << \",\" << r;\n\t\t\t}\n\t\t\tif (skip_ctl)\n\t\t\t{\n\t\t\t\tconst real_type nan = ::std::numeric_limits<real_type>::quiet_NaN();\n\n\t\t\t\t*p_dat_ofs_ << \",\" << nan << \",\" << nan;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tconst real_type alpha = p_sfc_fuzzy_eng_->getOutputValue(alpha_fuzzy_var_name);\n\t\t\t\tconst real_type du = p_rc_fuzzy_eng_->getOutputValue(du_fuzzy_var_name);\n\n\t\t\t\t*p_dat_ofs_ << \",\" << alpha << \",\" << du;\n\t\t\t}\n\t\t\t*p_dat_ofs_ << \",\" << Ke_ << \",\" << Kde_;\n\t\t\t*p_dat_ofs_ << \",\" << ctl_count_ << \",\" << ctl_skip_count_ << \",\" << ctl_fail_count_;\n\t\t\t*p_dat_ofs_ << ::std::endl;\n\t\t}\n\n\t\tDCS_DEBUG_TRACE(\"(\" << this << \") END Do CONTROL - Count: \" << ctl_count_ << \"/\" << ctl_skip_count_ << \"/\" << ctl_fail_count_);\n\t}\n\n\n\tprivate: real_type gamma_; ///< The EWMA smoothing factor for Cres\n\tprivate: real_type Ke_;\n\tprivate: real_type Kde_;\n\tprivate: ::boost::shared_ptr< ::fl::Engine > p_rc_fuzzy_eng_; ///< The fuzzy resource control engine\n\tprivate: ::boost::shared_ptr< ::fl::Engine > p_sfc_fuzzy_eng_; ///< The fuzzy scaling factor control engine\n\tprivate: ::std::map<application_performance_category,real_type> es_; ///< The e(k) variable, grouped by application performance category\n\tprivate: ::std::size_t ctl_count_; ///< Number of times control function has been invoked\n\tprivate: ::std::size_t ctl_skip_count_; ///< Number of times control has been skipped\n\tprivate: ::std::size_t ctl_fail_count_; ///< Number of times control has failed\n\tprivate: vm_sensor_map vm_sensors_;\n\tprivate: app_sensor_map app_sensors_;\n\tprivate: ::std::string dat_fname_;\n\tprivate: ::boost::shared_ptr< ::std::ofstream > p_dat_ofs_;\n}; // rao2013_dynaqos_application_manager\n\ntemplate <typename T>\nconst ::std::string rao2013_dynaqos_application_manager<T>::alpha_fuzzy_var_name = \"alpha\";\n\ntemplate <typename T>\nconst ::std::string rao2013_dynaqos_application_manager<T>::de_fuzzy_var_name = \"DeltaE\";\n\ntemplate <typename T>\nconst ::std::string rao2013_dynaqos_application_manager<T>::du_fuzzy_var_name = \"DeltaU\";\n\ntemplate <typename T>\nconst ::std::string rao2013_dynaqos_application_manager<T>::e_fuzzy_var_name = \"E\";\n\n}} // Namespace dcs::testbed\n\n#endif // DCS_TESTBED_RAO2013_DYNAQOS_APPLICATION_MANAGER_HPP\n", "meta": {"hexsha": "ef3be4b534a1cab1507a816ca1215c2fde32634a", "size": 38908, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/include/dcs/testbed/rao2013_dynaqos_application_manager.hpp", "max_stars_repo_name": "sguazt/prometheus", "max_stars_repo_head_hexsha": "03cdf3ccb283ed69c6fb84f18d89118abf95f837", "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/include/dcs/testbed/rao2013_dynaqos_application_manager.hpp", "max_issues_repo_name": "sguazt/prometheus", "max_issues_repo_head_hexsha": "03cdf3ccb283ed69c6fb84f18d89118abf95f837", "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/include/dcs/testbed/rao2013_dynaqos_application_manager.hpp", "max_forks_repo_name": "sguazt/prometheus", "max_forks_repo_head_hexsha": "03cdf3ccb283ed69c6fb84f18d89118abf95f837", "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": 51.2621870883, "max_line_length": 175, "alphanum_fraction": 0.6667523389, "num_tokens": 12277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521307073646, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2638190834778372}}
{"text": "/**\n * @file   CamPose.cpp\n * @brief  Implementation of CamPose class for camera pose representation.\n * @author Charlie Li\n * @date   2019.08.23\n */\n\n#include \"CamPose.hpp\"\n\n#include <iostream>\n\n#include <opencv2/calib3d.hpp> // cv::Rodrigues()\n#include <opencv2/core.hpp>\n#include <opencv2/core/eigen.hpp> // cv::cv2eigen()\n#include <Eigen/Core>\n#include <Eigen/Geometry> // for Matrix3f::eulerAngles(), Quaternion\n\nnamespace SLAM_demo {\n\nusing std::endl;\nusing cv::Mat;\n\nCamPose::CamPose() : mTcw(Mat(3, 4, CV_32FC1)), mTwc(Mat(3, 4, CV_32FC1))\n{\n    Mat I = Mat::eye(3, 3, CV_32FC1);\n    Mat zero = Mat::zeros(3, 1, CV_32FC1);\n    I.copyTo(mTcw.rowRange(0, 3).colRange(0, 3));\n    zero.copyTo(mTcw.rowRange(0, 3).col(3));\n    setPoseInv();\n}\n\nCamPose::CamPose(const cv::Mat& Tcw) :\n    mTcw(Tcw.clone()), mTwc(Mat(3, 4, CV_32FC1))\n{\n    setPoseInv();\n}\n\nCamPose::CamPose(const cv::Mat& Rcw, const cv::Mat& tcw) :\n    mTcw(Mat(3, 4, CV_32FC1)), mTwc(Mat(3, 4, CV_32FC1))\n{\n    Rcw.copyTo(mTcw.rowRange(0, 3).colRange(0, 3));\n    tcw.copyTo(mTcw.rowRange(0, 3).col(3));\n    setPoseInv();\n}\n\nCamPose::CamPose(const CamPose& pose)\n{\n    mTcw = pose.mTcw.clone(); // clone the cv::Mat!\n    mTwc = pose.mTwc.clone();\n}\n\nCamPose& CamPose::operator=(const CamPose& pose)\n{\n    mTcw = pose.mTcw.clone(); // clone the cv::Mat!\n    mTwc = pose.mTwc.clone();\n    return *this;\n}\n\nvoid CamPose::setPose(const cv::Mat& Tcw)\n{\n    mTcw = Tcw.clone();\n    setPoseInv();\n}\n\nvoid CamPose::setPose(const cv::Mat& Rcw, const cv::Mat& tcw)\n{\n    setRotation(Rcw);\n    setTranslation(tcw);\n    setPoseInv();\n}\n\ncv::Mat CamPose::getRotationAngleAxis() const\n{\n    Mat RcwAA; // rotation in angle-axis representation\n    Mat Rcw = getRotation();\n    cv::Rodrigues(Rcw, RcwAA, cv::noArray());\n    return RcwAA;\n}\n\n//cv::Mat CamPose::getRotationInvAngleAxis() const\n//{\n//    Mat Rwc = getRotationInv();\n//    Mat RwcAA = cv::Rodrigues(Rcw, RcwAA. cv::noArray());\n//    return RwcAA;\n//}\n\ncv::Mat CamPose::getTranslationSS() const\n{\n    Mat tx = Mat::zeros(3, 3, CV_32FC1);\n    Mat t = getTranslation();\n    tx.at<float>(0, 1) = -t.at<float>(2);\n    tx.at<float>(0, 2) =  t.at<float>(1);\n    tx.at<float>(1, 2) = -t.at<float>(0);\n    tx.at<float>(1, 0) = -tx.at<float>(0, 1);\n    tx.at<float>(2, 0) = -tx.at<float>(0, 2);\n    tx.at<float>(2, 1) = -tx.at<float>(1, 2);\n    return tx;\n}\n\nEigen::Matrix<float, 3, 1> CamPose::getREulerAngleEigen() const\n{\n    Eigen::Matrix<float, 3, 1> ea;\n    Eigen::Matrix<float, 3, 3> R;\n    cv::cv2eigen(getRotation(), R);\n    // construct corresponding Euler angles from rotation matrix representation\n    // (yaw, pitch, roll)^T\n    ea = R.eulerAngles(2, 1, 0);\n    // convert unit from radian to degree\n    ea *= 180.f / M_PI;\n    return ea;\n}\n\nEigen::Quaternion<float> CamPose::getRQuatEigen() const\n{\n    Eigen::Matrix<float, 3, 3> R;\n    cv::cv2eigen(getRotation(), R);\n    Eigen::Quaternionf q(R);\n    return q;\n}\n\nEigen::Quaternion<float> CamPose::getRInvQuatEigen() const\n{\n    Eigen::Matrix<float, 3, 3> RInv;\n    cv::cv2eigen(getRotation().t(), RInv);\n    Eigen::Quaternionf q(RInv);\n    return q;\n}\n\nCamPose& CamPose::operator*=(const CamPose& rhs)\n{\n    Mat RcwL = getRotation();\n    Mat tcwL = getTranslation();\n    Mat RcwR = rhs.getRotation();\n    Mat tcwR = rhs.getTranslation();\n    // (4*4 matrix) T_L * T_R = [R_L*R_R, R_L*t_R + t_L; 0^T, 1] \n    this->setPose(RcwL*RcwR, RcwL*tcwR + tcwL);\n    return *this;\n}\n\nconst CamPose CamPose::operator*(const CamPose& rhs) const\n{\n    CamPose ret = *this;\n    ret *= rhs;\n    return ret;\n}\n\nvoid CamPose::setRotation(const cv::Mat& Rcw)\n{\n    Rcw.copyTo(mTcw.rowRange(0, 3).colRange(0, 3));\n}\n\nvoid CamPose::setTranslation(const cv::Mat& tcw)\n{\n    tcw.copyTo(mTcw.rowRange(0, 3).col(3));\n}\n\nvoid CamPose::setPoseInv()\n{\n    Mat Rcw = getRotation();\n    Mat tcw = getTranslation();\n    Mat Rwc = Rcw.t();\n    Mat twc = -Rwc*tcw;\n    Rwc.copyTo(mTwc.rowRange(0, 3).colRange(0, 3));\n    twc.copyTo(mTwc.rowRange(0, 3).col(3));    \n}\n\nstd::ostream& operator<<(std::ostream& os, const CamPose& pose)\n{\n    //os << \"Pose Tcw = [Rcw | tcw] = \" << endl << pose.getPose() << endl;\n    Eigen::Vector3f ea = pose.getREulerAngleEigen();\n    os << \"Camera origin = \" << pose.getCamOrigin().t() << \"; \";\n    os << \"Rotation {yaw, pitch, roll} = {\"\n       << ea(0) << \", \" << ea(1) << \", \" << ea(2) << \"} (deg); \";\n    //os << \"Translation tcw = \" << pose.getTranslation().t();\n    return os;\n}\n\n} // namespace SLAM_demo\n", "meta": {"hexsha": "acc4075e0d2331ea6c2e8351f082698804b6f367", "size": 4481, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/CamPose.cpp", "max_stars_repo_name": "charlie-lee/slam_demo", "max_stars_repo_head_hexsha": "0bb6cc6d20c6a728eea502a61456f83881144e59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CamPose.cpp", "max_issues_repo_name": "charlie-lee/slam_demo", "max_issues_repo_head_hexsha": "0bb6cc6d20c6a728eea502a61456f83881144e59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CamPose.cpp", "max_forks_repo_name": "charlie-lee/slam_demo", "max_forks_repo_head_hexsha": "0bb6cc6d20c6a728eea502a61456f83881144e59", "max_forks_repo_licenses": ["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.0335195531, "max_line_length": 79, "alphanum_fraction": 0.6110243249, "num_tokens": 1568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2637547436094982}}
{"text": "// Copyright 2004, 2005 The Trustees of Indiana University.\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//  Authors: Jeremiah Willcock\n//           Douglas Gregor\n//           Andrew Lumsdaine\n#ifndef BOOST_GRAPH_ERDOS_RENYI_GENERATOR_HPP\n#define BOOST_GRAPH_ERDOS_RENYI_GENERATOR_HPP\n\n#include <cassert>\n#include <iterator>\n#include <utility>\n#include <boost/shared_ptr.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/random/geometric_distribution.hpp>\n#include <boost/type_traits/is_base_and_derived.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/config/no_tr1/cmath.hpp>\n\nnamespace boost {\n\n  template<typename RandomGenerator, typename Graph>\n  class erdos_renyi_iterator\n  {\n    typedef typename graph_traits<Graph>::directed_category directed_category;\n    typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;\n    typedef typename graph_traits<Graph>::edges_size_type edges_size_type;\n\n    BOOST_STATIC_CONSTANT\n      (bool,\n       is_undirected = (is_base_and_derived<undirected_tag,\n                                            directed_category>::value\n                        || is_same<undirected_tag, directed_category>::value));\n\n  public:\n    typedef std::input_iterator_tag iterator_category;\n    typedef std::pair<vertices_size_type, vertices_size_type> value_type;\n    typedef const value_type& reference;\n    typedef const value_type* pointer;\n    typedef void difference_type;\n\n    erdos_renyi_iterator() : gen(), n(0), edges(0), allow_self_loops(false) {}\n    erdos_renyi_iterator(RandomGenerator& gen, vertices_size_type n, \n                         double fraction = 0.0, bool allow_self_loops = false)\n      : gen(&gen), n(n), edges(edges_size_type(fraction * n * n)),\n        allow_self_loops(allow_self_loops)\n    { \n      if (is_undirected) edges = edges / 2;\n      next(); \n    }\n\n    erdos_renyi_iterator(RandomGenerator& gen, vertices_size_type n, \n                         edges_size_type m, bool allow_self_loops = false)\n      : gen(&gen), n(n), edges(m),\n        allow_self_loops(allow_self_loops)\n    { \n      next(); \n    }\n\n    reference operator*() const { return current; }\n    pointer operator->() const { return &current; }\n    \n    erdos_renyi_iterator& operator++()\n    { \n      --edges;\n      next();\n      return *this;\n    }\n\n    erdos_renyi_iterator operator++(int)\n    {\n      erdos_renyi_iterator temp(*this);\n      ++(*this);\n      return temp;\n    }\n\n    bool operator==(const erdos_renyi_iterator& other) const\n    { return edges == other.edges; }\n\n    bool operator!=(const erdos_renyi_iterator& other) const\n    { return !(*this == other); }\n\n  private:\n    void next()\n    {\n      uniform_int<vertices_size_type> rand_vertex(0, n-1);\n      current.first = rand_vertex(*gen);\n      do {\n        current.second = rand_vertex(*gen);\n      } while (current.first == current.second && !allow_self_loops);\n    }\n\n    RandomGenerator* gen;\n    vertices_size_type n;\n    edges_size_type edges;\n    bool allow_self_loops;\n    value_type current;\n  };\n\n  template<typename RandomGenerator, typename Graph>\n  class sorted_erdos_renyi_iterator\n  {\n    typedef typename graph_traits<Graph>::directed_category directed_category;\n    typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;\n    typedef typename graph_traits<Graph>::edges_size_type edges_size_type;\n\n    BOOST_STATIC_CONSTANT\n      (bool,\n       is_undirected = (is_base_and_derived<undirected_tag,\n                                            directed_category>::value\n                        || is_same<undirected_tag, directed_category>::value));\n\n  public:\n    typedef std::input_iterator_tag iterator_category;\n    typedef std::pair<vertices_size_type, vertices_size_type> value_type;\n    typedef const value_type& reference;\n    typedef const value_type* pointer;\n    typedef void difference_type;\n\n    sorted_erdos_renyi_iterator()\n      : gen(), rand_vertex(0.5), n(0), allow_self_loops(false),\n    src((std::numeric_limits<vertices_size_type>::max)()), tgt(0), prob(0) {}\n    sorted_erdos_renyi_iterator(RandomGenerator& gen, vertices_size_type n, \n                    double prob = 0.0, \n                                bool allow_self_loops = false)\n      : gen(),\n        // The \"1.0 - prob\" in the next line is to work around a Boost.Random\n        // (and TR1) bug in the specification of geometric_distribution.  It\n        // should be replaced by \"prob\" when the issue is fixed.\n        rand_vertex(1.0 - prob),\n    n(n), allow_self_loops(allow_self_loops), src(0), tgt(0), prob(prob)\n    { \n      this->gen.reset(new uniform_01<RandomGenerator>(gen));\n\n      if (prob == 0.0) {src = (std::numeric_limits<vertices_size_type>::max)(); return;}\n      next(); \n    }\n\n    reference operator*() const { return current; }\n    pointer operator->() const { return &current; }\n    \n    sorted_erdos_renyi_iterator& operator++()\n    { \n      next();\n      return *this;\n    }\n\n    sorted_erdos_renyi_iterator operator++(int)\n    {\n      sorted_erdos_renyi_iterator temp(*this);\n      ++(*this);\n      return temp;\n    }\n\n    bool operator==(const sorted_erdos_renyi_iterator& other) const\n    { return src == other.src && tgt == other.tgt; }\n\n    bool operator!=(const sorted_erdos_renyi_iterator& other) const\n    { return !(*this == other); }\n\n  private:\n    void next()\n    {\n      using std::sqrt;\n      using std::floor;\n\n      // In order to get the edges from the generator in sorted order, one\n      // effective (but slow) procedure would be to use a\n      // bernoulli_distribution for each legal (src, tgt) pair.  Because of the\n      // O(n^2) cost of that, a geometric distribution is used.  The geometric\n      // distribution tells how many times the bernoulli_distribution would\n      // need to be run until it returns true.  Thus, this distribution can be\n      // used to step through the edges which are actually present.  Everything\n      // beyond \"tgt += increment\" is done to effectively convert linear\n      // indexing (the partial sums of the geometric distribution output) into\n      // graph edges.\n      assert (src != (std::numeric_limits<vertices_size_type>::max)());\n      vertices_size_type increment = rand_vertex(*gen);\n      tgt += increment;\n      if (is_undirected) {\n    // Update src and tgt based on position of tgt\n    // Basically, we want the greatest src_increment such that (in \\bbQ):\n    // src_increment * (src + allow_self_loops + src_increment - 1/2) <= tgt\n    // The result of the LHS of this, evaluated with the computed\n    // src_increment, is then subtracted from tgt\n    double src_minus_half = (src + allow_self_loops) - 0.5;\n    double disc = src_minus_half * src_minus_half + 2 * tgt;\n    double src_increment_fp = floor(sqrt(disc) - src_minus_half);\n    vertices_size_type src_increment = vertices_size_type(src_increment_fp);\n    if (src + src_increment >= n) {\n      src = n;\n    } else {\n      tgt -= (src + allow_self_loops) * src_increment + \n         src_increment * (src_increment - 1) / 2;\n      src += src_increment;\n    }\n      } else {\n    // Number of out edge positions possible from each vertex in this graph\n    vertices_size_type possible_out_edges = n - (allow_self_loops ? 0 : 1);\n    src += (std::min)(n - src, tgt / possible_out_edges);\n    tgt %= possible_out_edges;\n      }\n      // Set end of graph code so (src, tgt) will be the same as for the end\n      // sorted_erdos_renyi_iterator\n      if (src >= n) {src = (std::numeric_limits<vertices_size_type>::max)(); tgt = 0;}\n      // Copy (src, tgt) into current\n      current.first = src;\n      current.second = tgt;\n      // Adjust for (src, src) edge being forbidden\n      if (!allow_self_loops && tgt >= src) ++current.second;\n    }\n\n    shared_ptr<uniform_01<RandomGenerator> > gen;\n    geometric_distribution<vertices_size_type> rand_vertex;\n    vertices_size_type n;\n    bool allow_self_loops;\n    vertices_size_type src, tgt;\n    value_type current;\n    double prob;\n  };\n\n} // end namespace boost\n\n#endif // BOOST_GRAPH_ERDOS_RENYI_GENERATOR_HPP\n", "meta": {"hexsha": "605b0e1749520840585cc5e0ba68316bde98b65f", "size": 8227, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/erdos_renyi_generator.hpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-12-06T00:55:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T03:05:51.000Z", "max_issues_repo_path": "boost/graph/erdos_renyi_generator.hpp", "max_issues_repo_name": "mike-code/boost_1_38_0", "max_issues_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-03-31T20:56:08.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-18T08:56:40.000Z", "max_forks_repo_path": "boost/graph/erdos_renyi_generator.hpp", "max_forks_repo_name": "mike-code/boost_1_38_0", "max_forks_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9257641921, "max_line_length": 88, "alphanum_fraction": 0.6664640817, "num_tokens": 2007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.26375474360949813}}
{"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 <vector>\n#include <string>\n#include <map>\n\n#include <boost/lexical_cast.hpp>\n\n#include <hashclash/saveload_bz2.hpp>\n#include <hashclash/sha1detail.hpp>\n#include <hashclash/sha1differentialpath.hpp>\n#include <hashclash/booleanfunction.hpp>\n\n#include \"main.hpp\"\n\nusing namespace hashclash;\nusing namespace std;\n\nvoid sha1_backward_differential_step(const sha1differentialpath& path, path_container_autobalance& outpaths)\n{\n\tconst int t = int(outpaths.t);\n\tconst unsigned& maxcond = outpaths.maxcond;\n\tconst unsigned& maxsdrs = outpaths.maxsdrs;\n\tconst unsigned& maxweight = outpaths.maxweight;\n\tconst unsigned& minweight = outpaths.minweight;\n\n\tbooleanfunction* F = 0;\n\tif (t < 20) F = &SHA1_F1_data; // this implementation only works properly for sha1_f1\n\telse if (t < 40) F = &SHA1_F2_data;\n\telse if (t < 60) F = &SHA1_F3_data;\n\telse if (t < 80) F = &SHA1_F4_data;\n\n\tstatic sha1differentialpath newpath;\n\tstatic vector<sdr> sdrs;\n\tstatic bitcondition Qtm1b[32], Qtm2b[32], Qtm3b[32];\n\tstatic vector<unsigned> bval;\n\tstatic uint32 fdiv[32];\n\tstatic bf_outcome foutcomes[32];\t\n//\tstatic std::vector<std::pair<uint32,double> > rotateddiff;\n\tstatic vector<sdr> deltam;\n\tstatic vector<unsigned> Qtm1prev, Qtm1prevn;\n\n\tnewpath = path;\n\tnewpath[t-4].clear();\n\n\tunsigned totprecond = 0;\n\tunsigned totcond = 0;\n\tfor (int k = t; k <= outpaths.tend && k <= 80; ++k)\n\t\tif (k < newpath.tend())\n\t\t\ttotprecond += newpath[k].hw();\n\ttotcond = totprecond + newpath[t-1].hw() + newpath[t-2].hw();\t\n\t\n\tunsigned minextracond = 0;\n\tQtm1prev.clear();\n\tQtm1prevn.clear();\n\tbf_outcome outconstant, outplus, outminus;\n\tfor (unsigned b = 0; b < 32; ++b)\n\t{\n\t\tQtm1b[b] = newpath(t-1,b);\n\t\tif (Qtm1b[b] == bc_prev) {\n\t\t\tQtm1prev.push_back(b);\n\t\t\tQtm1b[b] = bc_constant;\n\t\t\tnewpath[t-1].set(b, bc_constant);\n\t\t} else if (Qtm1b[b] == bc_prevn) {\n\t\t\tQtm1prevn.push_back(b);\n\t\t\tQtm1b[b] = bc_constant;\n\t\t\tnewpath.setbitcondition(t-1,b, bc_constant);\n\t\t}\n\t\tQtm2b[b] = newpath(t-2,(b+2)&31);\n\t\tif (b < 31) {\n\t\t\toutconstant = F->outcome( Qtm1b[b], Qtm2b[b], bc_constant );\n\t\t\toutplus = F->outcome( Qtm1b[b], Qtm2b[b], bc_plus );\n\t\t\toutminus = F->outcome( Qtm1b[b], Qtm2b[b], bc_minus );\n\t\t} else {\n\t\t\toutconstant = msb_bf_outcome(*F, Qtm1b[b], Qtm2b[b], bc_constant );\n\t\t\toutplus = msb_bf_outcome(*F, Qtm1b[b], Qtm2b[b], bc_plus );\n\t\t\toutminus = msb_bf_outcome(*F, Qtm1b[b], Qtm2b[b], bc_minus );\n\t\t}\n\t\tif (outconstant.size() > 1 && outplus.size() > 1 && outminus.size() > 1)\n\t\t\t++minextracond;\n\t}\n\tsdr sdrQtm3 = newpath[t-3].getsdr();\n\tuint32 Qtm3_hwnaf = hwnaf(sdrQtm3.adddiff());\n\tif (totcond + Qtm3_hwnaf + minextracond > maxcond) return;\n\n\t/* table deltam */\n\tsdr mmask = outpaths.m_mask[t];\n\tdeltam.clear();\n\tdeltam.reserve(1<<mmask.hw());\n\tuint32 addmask = (~mmask.mask)+1; \n\tuint32 andmask = mmask.mask & 0x7FFFFFFF;\n\tmmask.sign = 0;\n\tdo {\n\t\tmmask.sign += addmask; mmask.sign &= andmask;\n\t\tdeltam.push_back(mmask);\n\t} while (mmask.sign != 0 && !outpaths.onemessagediff);\n#if 1\n        unsigned minhw = 32;\n        for (unsigned i = 0; i < deltam.size(); ++i)\n                if (hwnaf(deltam[i].adddiff()) < minhw)\n                        minhw = hwnaf(deltam[i].adddiff());\n        unsigned ii = 0;\n        while (ii < deltam.size()) {\n                if (hwnaf(deltam[ii].adddiff()) > minhw) {\n                        swap(deltam[ii], deltam.back());\n                        deltam.pop_back();\n                } else\n                        ++ii;\n        }\n#endif\n\n\t/* table sdrs for delta Qtm1 */\n\tunsigned w = Qtm3_hwnaf+1;\t\n\tif (w < minweight) w = minweight;\n        unsigned mincount = 0;\n        if (minweight > 0)\n                mincount = count_sdrs(sdrQtm3,minweight-1,30);\n\twhile (\n\t\t\t(w < 32) \n\t\t\t&& (w+1 <= maxweight) \n\t\t\t&& (totcond + w + 1 + minextracond <= maxcond) \n\t\t\t&& (count_sdrs(sdrQtm3, w+1,30)-mincount <= maxsdrs)\n\t\t)\n\t\t++w;\n\ttable_sdrs(sdrs, sdrQtm3, w, 30);\n\n\twordconditions pathQtm1 = newpath[t-1];\n\twordconditions& newpathQtm1 = newpath[t-1];\n\twordconditions& newpathQtm2 = newpath[t-2];\n\twordconditions& newpathQtm3 = newpath[t-3];\n\twordconditions& newpathQtm4 = newpath[t-4];\n\n\tuint32 dQtm4pc = newpath[t+1].diff() - newpath[t].getsdr().rotate_left(5).adddiff();\n\n\tvector<sdr>::const_iterator cit = sdrs.begin(), citend = sdrs.end();\n\tfor (; cit != citend; ++cit)\n\t{\n\t\tsdrQtm3 = *cit;\n\t\tunsigned hwQtm3 = sdrQtm3.hw();\n\t\tif (hwQtm3 < minweight) continue;\n\t\tif (totcond + hwQtm3 + minextracond > maxcond) \n\t\t\tcontinue;\n\t\tnewpathQtm3 = sdrQtm3;\n\n\t\tuint32 cnt = 1;\n\t\tuint32 dF_fixed = 0;\n\t\tunsigned maxextracond = 0;\n\t\tbval.clear();\n\t\tfor (unsigned b = 0; b < 32; ++b)\n\t\t{\n\t\t\tQtm3b[b] = newpathQtm3.get((b+2)&31);\n\t\t\tif (b < 31)\n\t\t\t\tfoutcomes[b] = F->outcome( Qtm1b[b], Qtm2b[b], Qtm3b[b] );\n\t\t\telse\n\t\t\t\tfoutcomes[b] = msb_bf_outcome(*F, Qtm1b[b], Qtm2b[b], Qtm3b[b] );\n\t\t\tunsigned fsize = foutcomes[b].size();\n\t\t\tif (fsize > 1)\n\t\t\t{\n\t\t\t\tfdiv[b] = cnt;\n\t\t\t\tif (fsize == 2) cnt <<= 1;\n\t\t\t\telse if (fsize == 3) { cnt += cnt<<1; ++ maxextracond; }\n\t\t\t\tbval.push_back(b);\n\t\t\t} else\n\t\t\t\tdF_fixed += foutcomes[b](0,b);\n\t\t}\n\t\tif (totcond + hwQtm3 + bval.size() > maxcond) \n\t\t\tcontinue;\n\t\tif (outpaths.estimatefactor != 0) \n\t\t{\n\t\t\toutpaths.estimate(totcond + hwQtm3 + bval.size() + ((maxextracond+1)>>1), cnt*deltam.size());\n\t\t\tcontinue;\n\t\t}\n\n\t\tnewpathQtm2 = path[t-2];\n\n\t\tstd::reverse(bval.begin(), bval.end());\n\t\tbf_conditions newconditions;\n\t\tfor (uint32 k = 0; k < cnt; ++k)\n\t\t{\n\t\t\tuint32 m = k;\n\t\t\tuint32 dF = dF_fixed;\n\t\t\tnewpathQtm1 = pathQtm1;\n\t\t\tfor (unsigned j = 0; j < bval.size(); ++j)\n\t\t\t{\n\t\t\t\tconst unsigned b = bval[j];\n\t\t\t\tunsigned i = 0;\n\t\t\t\twhile (m >= fdiv[b])\n\t\t\t\t{\n\t\t\t\t\tm -= fdiv[b];\n\t\t\t\t\t++i;\n\t\t\t\t}\n\t\t\t\tif (b < 31)\n\t\t\t\t\tnewconditions = F->backwardconditions( Qtm1b[b], Qtm2b[b], Qtm3b[b], foutcomes[b][i] );\n\t\t\t\telse {\n\t\t\t\t\tnewconditions = msb_bf_backwardconditions(*F, Qtm1b[b], Qtm2b[b], Qtm3b[b], foutcomes[b][i] );\n\t\t\t\t\tif (msb_bf_outcome(*F, newconditions).size() > 1 || msb_bf_outcome(*F, newconditions)[0] != foutcomes[b][i]) {\n\t\t\t\t\t\tcout << endl << \"[\" << Qtm1b[b] << Qtm2b[b] << Qtm3b[b] <<\"](\" << foutcomes[b][i] <<\")=>[\" << newconditions.first << newconditions.second << newconditions.third << \"]\" << endl;\n\t\t\t\t\t\tbf_outcome tmp = msb_bf_outcome(*F, Qtm1b[b], Qtm2b[b], Qtm3b[b]);\n\t\t\t\t\t\tfor (unsigned i = 0; i < tmp.size(); ++i)\n\t\t\t\t\t\t\tcout << tmp[i] << flush;\n\t\t\t\t\t\tcout << endl;\n\t\t\t\t\t\ttmp = F->outcome(Qtm1b[b], Qtm2b[b], Qtm3b[b]);\n\t\t\t\t\t\tfor (unsigned i = 0; i < tmp.size(); ++i)\n\t\t\t\t\t\t\tcout << tmp[i] << flush;\n\t\t\t\t\t\tcout << endl;\n\t\t\t\t\t\tnewconditions = F->backwardconditions( Qtm1b[b], Qtm2b[b], Qtm3b[b], bc_constant );\n\t\t\t\t\t\tcout << \"(.)=>[\" << newconditions.first << newconditions.second << newconditions.third << \"]\" << endl;\n\t\t\t\t\t\tthrow;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tnewpathQtm1.set(b, newconditions.first);\n\t\t\t\tnewpathQtm2.set((b+2)&31, newconditions.second);\n\t\t\t\tnewpathQtm3.set((b+2)&31, newconditions.third);\n\n\t\t\t\tdF += foutcomes[b](i,b);\n\t\t\t}\n\n\t\t\tbool contradiction = false;\n\t\t\tfor (unsigned i = 0; i < Qtm1prev.size(); ++i) {\n\t\t\t\tconst unsigned b = Qtm1prev[i];\n\t\t\t\tconst bitcondition bcQtm1b = newpathQtm1[b];\n\t\t\t\tswitch (bcQtm1b) {\n\t\t\t\tcase bc_constant:\n\t\t\t\t\tnewpathQtm1.set(b, bc_prev);\n\t\t\t\t\tbreak;\n\t\t\t\tcase bc_one:\n\t\t\t\tcase bc_zero:\n\t\t\t\t\tif (newpathQtm2[b] == bc_prev) {\n\t\t\t\t\t\tnewpathQtm3.set(b, bcQtm1b);\n\t\t\t\t\t} else if (newpathQtm2[b] == bc_prevn) {\n\t\t\t\t\t\tif (bcQtm1b == bc_one)\n\t\t\t\t\t\t\tnewpathQtm3.set(b, bc_zero);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tnewpathQtm3.set(b, bc_one);\n\t\t\t\t\t} else if (newpathQtm2[b] != bc_constant && newpathQtm2[b] != bcQtm1b) {\n\t\t\t\t\t\t//cerr << \"[^\" << newpathQtm1[b] << newpathQtm2[b] << newpathQtm3[b] << \"]\" << flush;\n\t\t\t\t\t\tcontradiction = true;\n\t\t\t\t\t}\n\t\t\t\t\tnewpathQtm2.set(b, bcQtm1b);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tcerr << \"[^\" << newpathQtm1[b] << newpathQtm2[b] << newpathQtm3[b] << \"]\" << flush;\n\t\t\t\t\tcontradiction = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (unsigned i = 0; i < Qtm1prevn.size(); ++i) {\n\t\t\t\tconst unsigned b = Qtm1prevn[i];\n\t\t\t\tconst bitcondition bcQtm1b = newpathQtm1[b];\n\t\t\t\tswitch (bcQtm1b) {\n\t\t\t\tcase bc_constant:\n\t\t\t\t\tnewpathQtm1.set(b, bc_prevn);\n\t\t\t\t\tbreak;\n\t\t\t\tcase bc_one:\n\t\t\t\tcase bc_zero:\n\t\t\t\t\tif (newpathQtm2[b] == bc_prev) {\n\t\t\t\t\t\tif (bcQtm1b == bc_one)\n\t\t\t\t\t\t\tnewpathQtm3.set(b, bc_zero);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tnewpathQtm3.set(b, bc_one);\n\t\t\t\t\t} else if (newpathQtm2[b] == bc_prevn) {\n\t\t\t\t\t\tnewpathQtm3.set(b, bcQtm1b);\n\t\t\t\t\t} else if (newpathQtm2[b] != bc_constant && newpathQtm2[b] == bcQtm1b) {\n\t\t\t\t\t\t//cerr << \"[^\" << newpathQtm1[b] << newpathQtm2[b] << newpathQtm3[b] << \"]\" << flush;\n\t\t\t\t\t\tcontradiction = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (bcQtm1b == bc_one)\n\t\t\t\t\t\tnewpathQtm2.set(b, bc_zero);\n\t\t\t\t\telse\n\t\t\t\t\t\tnewpathQtm2.set(b, bc_one);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tcerr << \"[^\" << newpathQtm1[b] << newpathQtm2[b] << newpathQtm3[b] << \"]\" << flush;\n\t\t\t\t\tcontradiction = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (contradiction)\n\t\t\t\tcontinue;\n\n\t\t\tunsigned ncond = totprecond + newpathQtm1.hw() + newpathQtm2.hw() + newpathQtm3.hw();\n\t\t\tif (ncond > maxcond) return;\n\t\t\tfor (unsigned i = 0; i < deltam.size(); ++i)\n\t\t\t{\n\t\t\t\tnewpath.getme(t) = deltam[i];\n\t\t\t\tuint32 dQtm4 = dQtm4pc - dF - deltam[i].adddiff();\n\t\t\t\tnewpathQtm4 = naf(dQtm4).rotate_right(30);\n\t\t\t\tunsigned ncond2 = ncond;\n\t\t\t\tif (outpaths.includenaf) {\n\t\t\t\t\tif (outpaths.halfnafweight)\n\t\t\t\t\t\tncond2 += (newpathQtm4.hw()>>1);\n\t\t\t\t\telse\n\t\t\t\t\t\tncond2 += newpathQtm4.hw();\n\t\t\t\t}\n\t\t\t\tif (ncond2 <= maxcond)\n\t\t\t\t\toutpaths.push_back(newpath, ncond2);\n\t\t\t}\n\t\t} // for cnt\n\t} // for sdrs\t\n}\n", "meta": {"hexsha": "6496b5ad4855eca109b6f3db13046bea2fa682bf", "size": 10253, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sha1backward/backward.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/sha1backward/backward.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/sha1backward/backward.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.4462025316, "max_line_length": 182, "alphanum_fraction": 0.6021652199, "num_tokens": 3524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2637145463844679}}
{"text": "/*\n\nCopyright (c) 2005-2020, 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 BACKWARDEULERIVPODESOLVER_HPP_\n#define BACKWARDEULERIVPODESOLVER_HPP_\n\n#include \"AbstractOneStepIvpOdeSolver.hpp\"\n#include \"AbstractOdeSystemWithAnalyticJacobian.hpp\"\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n\n#include \"AbstractOneStepIvpOdeSolver.hpp\"\n\n/**\n * A concrete one step ODE solver class that employs the backward Euler\n * method. This numerical method is implicit and hence unconditionally stable.\n */\nclass BackwardEulerIvpOdeSolver  : public AbstractOneStepIvpOdeSolver\n{\nprivate:\n    /** Needed for serialization. */\n    friend class boost::serialization::access;\n    /**\n     * Archive the abstract IVP Solver, never used directly - boost uses this.\n     *\n     * @param archive the 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        // This calls serialize on the base class.\n        archive & boost::serialization::base_object<AbstractOneStepIvpOdeSolver>(*this);\n        //archive & mSizeOfOdeSystem; - this done in save and load construct now.\n        archive & mNumericalJacobianEpsilon;\n        archive & mForceUseOfNumericalJacobian;\n    }\n\n    /** The number of state variables in the ODE system. */\n    unsigned mSizeOfOdeSystem;\n\n    /** The epsilon to use in calculating the numerical Jacobian of the ODE system. */\n    double mNumericalJacobianEpsilon;\n\n    /**\n     * Whether to force the solver to use the numerical Jacobian even if\n     * the ODE system object provides an analytical Jacobian.\n     */\n    bool mForceUseOfNumericalJacobian;\n\n    /*\n     * NOTE: we use (unsafe) double pointers here rather than\n     * std::vectors because using std::vectors would lead to a\n     * slow down by a factor of about 4.\n     */\n\n    /** Working memory : residual vector */\n    double* mResidual;\n\n    /** Working memory : Jacobian matrix */\n    double** mJacobian;\n\n    /** Working memory : update vector */\n    double* mUpdate;\n\n    /**\n     * Compute the current residual.\n     *\n     * @param pAbstractOdeSystem  the ODE system to solve\n     * @param timeStep  dt\n     * @param time  the current time\n     * @param rCurrentYValues  the current (initial) state\n     * @param rCurrentGuess  current guess for the state at the next timestep\n     */\n    void ComputeResidual(AbstractOdeSystem* pAbstractOdeSystem,\n                         double timeStep,\n                         double time,\n                         std::vector<double>& rCurrentYValues,\n                         std::vector<double>& rCurrentGuess);\n\n    /**\n     * Compute the Jacobian of the ODE system.\n     *\n     * @param pAbstractOdeSystem  the ODE system to solve\n     * @param timeStep  dt\n     * @param time  the current time\n     * @param rCurrentYValues  the current (initial) state\n     * @param rCurrentGuess  current guess for the state at the next timestep\n     */\n    void ComputeJacobian(AbstractOdeSystem* pAbstractOdeSystem,\n                         double timeStep,\n                         double time,\n                         std::vector<double>& rCurrentYValues,\n                         std::vector<double>& rCurrentGuess);\n\n    /**\n     * Solve a linear system of equations to update the\n     * current guess for the solution to the ODE system at\n     * the next timestep.\n     * Used by the method CalculateNextYValue.\n     */\n    void SolveLinearSystem();\n\n    /**\n     * Compute the infinity/maximum norm of a vector.\n     * Used by the method CalculateNextYValue.\n     *\n     * @param pVector  a pointer to a vector\n     * @return the vector's norm.\n     */\n    double ComputeNorm(double* pVector);\n\n    /**\n     * Compute the Jacobian of the ODE system numerically.\n     *\n     * @param pAbstractOdeSystem  the ODE system to solve\n     * @param timeStep  dt\n     * @param time  the current time\n     * @param rCurrentYValues  the current (initial) state\n     * @param rCurrentGuess  current guess for the state at the next timestep\n     */\n    void ComputeNumericalJacobian(AbstractOdeSystem* pAbstractOdeSystem,\n                                  double timeStep,\n                                  double time,\n                                  std::vector<double>& rCurrentYValues,\n                                  std::vector<double>& rCurrentGuess);\n\nprotected:\n\n    /**\n     * Calculate the solution to the ODE system at the next timestep.\n     *\n     * A usage example:\n     *     BackwardEulerIvpOdeSolver mySolver;\n     *     OdeSolution solution = mySolver.Solve(pMyOdeSystem, yInit, StartTime, EndTime, TimeStep, SamplingTime);\n     *\n     * @param pAbstractOdeSystem  the ODE system to solve\n     * @param timeStep  dt\n     * @param time  the current time\n     * @param rCurrentYValues  the current (initial) state\n     * @param rNextYValues  the state at the next timestep\n     */\n    void CalculateNextYValue(AbstractOdeSystem* pAbstractOdeSystem,\n                             double timeStep,\n                             double time,\n                             std::vector<double>& rCurrentYValues,\n                             std::vector<double>& rNextYValues);\n\npublic:\n\n    /**\n     * Constructor.\n     *\n     * @param sizeOfOdeSystem  the number of state variables in the ODE system\n     */\n    BackwardEulerIvpOdeSolver(unsigned sizeOfOdeSystem);\n\n    /**\n     * Destructor.\n     */\n    ~BackwardEulerIvpOdeSolver();\n\n    /**\n     * Set the epsilon to use in calculating the\n     * numerical Jacobian of the ODE system.\n     *\n     * @param epsilon\n     */\n    void SetEpsilonForNumericalJacobian(double epsilon);\n\n    /**\n     * Force the solver to use the numerical Jacobian even if\n     * the ODE system object provides an analytical Jacobian.\n     */\n    void ForceUseOfNumericalJacobian();\n\n    /**\n     * Public method used in archiving.\n     *\n     * @return the size of the system\n     */\n     unsigned GetSystemSize() const {return mSizeOfOdeSystem;};\n};\n\n#include \"SerializationExportWrapper.hpp\"\nCHASTE_CLASS_EXPORT(BackwardEulerIvpOdeSolver)\n\nnamespace boost\n{\nnamespace serialization\n{\n/**\n * Allow us to not need a default constructor, by specifying how Boost should\n * instantiate a BackwardEulerIvpOdeSolver instance.\n */\ntemplate<class Archive>\ninline void save_construct_data(\n    Archive & ar, const BackwardEulerIvpOdeSolver * t, const unsigned int file_version)\n{\n    const unsigned system_size = t->GetSystemSize();\n    ar & system_size;\n}\n\n/**\n * Allow us to not need a default constructor, by specifying how Boost should\n * instantiate a BackwardEulerIvpOdeSolver instance (using existing constructor)\n *\n * NB this constructor allocates memory for the other member variables too.\n */\ntemplate<class Archive>\ninline void load_construct_data(\n    Archive & ar, BackwardEulerIvpOdeSolver * t, const unsigned int file_version)\n{\n     unsigned ode_system_size;\n     ar >> ode_system_size;\n     ::new(t)BackwardEulerIvpOdeSolver(ode_system_size);\n}\n}\n} // namespace ...\n\n#endif /*BACKWARDEULERIVPODESOLVER_HPP_*/\n", "meta": {"hexsha": "0913b7f0a7cfac73a99c68da430b98f2f822dc7e", "size": 8777, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ode/src/solver/BackwardEulerIvpOdeSolver.hpp", "max_stars_repo_name": "SoftMatterMechanics/ApicalStressFibers", "max_stars_repo_head_hexsha": "17d343c09a246a50f9e3a3cbfc399ca6bef353ce", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-10T16:12:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-10T16:12:13.000Z", "max_issues_repo_path": "ode/src/solver/BackwardEulerIvpOdeSolver.hpp", "max_issues_repo_name": "SoftMatterMechanics/ApicalStressFibers", "max_issues_repo_head_hexsha": "17d343c09a246a50f9e3a3cbfc399ca6bef353ce", "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": "ode/src/solver/BackwardEulerIvpOdeSolver.hpp", "max_forks_repo_name": "SoftMatterMechanics/ApicalStressFibers", "max_forks_repo_head_hexsha": "17d343c09a246a50f9e3a3cbfc399ca6bef353ce", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T16:12:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-10T16:12:21.000Z", "avg_line_length": 34.4196078431, "max_line_length": 114, "alphanum_fraction": 0.6839466788, "num_tokens": 1978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5, "lm_q1q2_score": 0.26365826168978357}}
{"text": "//\n//\n// The MIT License (MIT)\n//\n// Copyright (c) 2015  Peter Fisk, Michael J. Wouters\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 <cmath>\n#include <cstring>\n#include <time.h>\n#include <gsl/gsl_multifit.h>\n\n#include <boost/regex.hpp>\n\n#include \"Utility.h\"\n\nstd::string Utility::trim(std::string const& str)\n{\n\tstd::size_t first = str.find_first_not_of(' ');\n\n\t// If there is no non-whitespace character, both first and last will be std::string::npos (-1)\n\t// There is no point in checking both, since if either doesn't work, the\n\t// other won't work, either.\n\tif(first == std::string::npos)\n\t\treturn \"\";\n\n\tstd::size_t last  = str.find_last_not_of(' ');\n\n\treturn str.substr(first, last-first+1);\n}\n\n\nvoid Utility::MJDtoDate(int mjd,int *year,int *mon, int *mday, int *yday)\n{\n\ttime_t tt = (mjd - 40587)*86400;\n\tstruct tm *utc = gmtime(&tt);\n\t*year = 1900 + utc->tm_year;\n\t*mon  = utc->tm_mon+1;\n\t*mday = utc->tm_mday;\n\t*yday = utc->tm_yday+1;\n}\n\nbool Utility::TODStrtoTOD(std::string const& todstr,int *hh,int *mm,int *ss)\n{\n\t// Two formats OK\n\t// HHMMSS or HH:MM:SS\n\tboost::regex re1(\"^(\\\\d{2})(\\\\d{2})(\\\\d{2})$\");\n\tboost::smatch matches;\n\tif (boost::regex_search(todstr,matches,re1)){\n\t\t*hh = atoi(matches[1].str().c_str()); // regex has already checked input is valid\n\t\t*mm = atoi(matches[2].str().c_str());\n\t\t*ss = atoi(matches[3].str().c_str());\n\t\treturn (*hh <= 23 && *mm <= 59 && *ss <= 59);\n\t}\n\tboost::regex re2(\"^(\\\\d{2}):(\\\\d{2}):(\\\\d{2})$\");\n\tif (boost::regex_search(todstr,matches,re2)){\n\t\t*hh = atoi(matches[1].str().c_str()); // regex has already checked input is valid\n\t\t*mm = atoi(matches[2].str().c_str());\n\t\t*ss = atoi(matches[3].str().c_str());\n\t\treturn (*hh <= 23 && *mm <= 59 && *ss <= 59);\n\t}\n\treturn false;\n}\n\nbool Utility::linearFit(double x[], double y[],int n,double xinterp,double *yinterp,double *c,double *m,double *rmsResidual)\n{\n\tdouble sx = 0, sy = 0, sr2 = 0, xbar, ybar, sxxbary=0,sxxbarsq=0;\n\t\n\tfor (int i=0;i<n;i++){\n\t\tsx += x[i];\n\t\tsy += y[i];\n\t}\n\t\n\txbar = sx/n;\n\tybar = sy/n;\n\n\tfor (int i=0;i<n;i++){\n\t\tsxxbary += (x[i] - xbar) * y[i];\n\t\tsxxbarsq += (x[i] - xbar)*(x[i] - xbar);\n\t}\n\n\t// Slope and intercept\n\t*m = sxxbary/sxxbarsq;\n\t*c = ybar - *m * xbar;\n\n\t// Sum of residuals^2\n\n\tfor (int i=0;i<n;i++)\n\t\tsr2 += pow(y[i] - *m * x[i] - *c,2);\n\n\t// RMS residuals\n\t*rmsResidual = sqrt(sr2/n);\n\t\n\t*yinterp = *m * xinterp + *c;\n\t\n\treturn true;\n}\n\nbool Utility::quadFit(double x[], double y[],int n,double xinterp,double *yinterp){\n\t//double c,m,rmsResidual;\n\t//linearFit(x,y,n,xinterp,yinterp,&c,&m,&rmsResidual); // FIXME\n\t\n\tdouble chisq;\n  gsl_matrix *X, *cov;\n  gsl_vector *Y, *c;\n\t\n\tX = gsl_matrix_alloc (n, 3);\n\tY = gsl_vector_alloc (n);\n\tc = gsl_vector_alloc (3);\n\tcov = gsl_matrix_alloc (3, 3);\n\n\tfor (int i = 0; i < n; i++){    \n\t\tgsl_matrix_set (X, i, 0, 1.0);\n\t\tgsl_matrix_set (X, i, 1, x[i]);\n\t\tgsl_matrix_set (X, i, 2, x[i]*x[i]);\n\t\tgsl_vector_set (Y, i, y[i]);\n\t}\n  \n\tgsl_multifit_linear_workspace * work = gsl_multifit_linear_alloc (n, 3);\n\tgsl_multifit_linear (X, Y, c, cov,&chisq, work);\n\tgsl_multifit_linear_free (work);\n\t\n\t#define C(i) (gsl_vector_get(c,(i)))\n\t\n\t*yinterp = C(0) + C(1)*xinterp + C(2)*xinterp*xinterp;\n\t\n\tgsl_matrix_free (X);\n  gsl_vector_free (Y);\n  gsl_vector_free (c);\n  gsl_matrix_free (cov);\n\t\n\treturn true;\n}\n\nvoid Utility::ECEFtoLatLonH(double X, double Y, double Z, \n\tdouble *lat, double *lon, double *ht)\n{\n\t// Parameters for WGS84 ellipsoid\n\tdouble a = 6378137.00; // semi-major axis\n\tdouble inverse_flattening = 298.257223563;\n\tdouble latitude,longitude;\n\tdouble p=sqrt(X*X + Y*Y);\n\tdouble r=sqrt(p*p + Z*Z);\n\tdouble f=1/inverse_flattening;\n\tdouble esq=2*f-f*f;\n\tdouble u=atan2(Z/p , 1.0/(1-f+esq*a/r));\n\n\tlongitude = atan2(Y,X);\n\tlatitude = atan2(Z*(1-f) + esq * a * pow(sin(u),3) ,\n\t\t(1-f)*(p  - esq * a * pow(cos(u),3)));\n\t*ht = p*cos(latitude) + Z*sin(latitude) - \n\t\t\ta*sqrt(1-esq* pow(sin(latitude),2));\n\n\t// Convert to degrees\n\t*lat=latitude*180.0/M_PI;\n\t*lon=longitude*180.0/M_PI;\n\t\n\treturn;\n} \n", "meta": {"hexsha": "b1d62a76f99ead81d87d98ca524bd3c5776db03d", "size": 5024, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "software/gpscv/common/process/mktimetx/Utility.cpp", "max_stars_repo_name": "openttp/openttp", "max_stars_repo_head_hexsha": "34c7641ddace2bfaa13175367d4f5dfc4861d2dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-08-15T03:15:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-16T09:32:40.000Z", "max_issues_repo_path": "software/gpscv/common/process/mktimetx/Utility.cpp", "max_issues_repo_name": "openttp/openttp", "max_issues_repo_head_hexsha": "34c7641ddace2bfaa13175367d4f5dfc4861d2dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2016-03-24T04:02:50.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-12T01:15:00.000Z", "max_forks_repo_path": "software/gpscv/common/process/mktimetx/Utility.cpp", "max_forks_repo_name": "openttp/openttp", "max_forks_repo_head_hexsha": "34c7641ddace2bfaa13175367d4f5dfc4861d2dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-06-18T19:48:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T05:54:48.000Z", "avg_line_length": 28.384180791, "max_line_length": 124, "alphanum_fraction": 0.6508757962, "num_tokens": 1638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5, "lm_q1q2_score": 0.26365826168978357}}
{"text": "// Copyright Nick Thompson, 2020\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_MATH_INTERPOLATORS_CUBIC_HERMITE_HPP\r\n#define BOOST_MATH_INTERPOLATORS_CUBIC_HERMITE_HPP\r\n#include <memory>\r\n#include <boost/math/interpolators/detail/cubic_hermite_detail.hpp>\r\n\r\nnamespace boost::math::interpolators {\r\n\r\ntemplate<class RandomAccessContainer>\r\nclass cubic_hermite {\r\npublic:\r\n    using Real = typename RandomAccessContainer::value_type;\r\n\r\n    cubic_hermite(RandomAccessContainer && x, RandomAccessContainer && y, RandomAccessContainer && dydx) \r\n    : impl_(std::make_shared<detail::cubic_hermite_detail<RandomAccessContainer>>(std::move(x), std::move(y), std::move(dydx)))\r\n    {}\r\n\r\n    inline Real operator()(Real x) const {\r\n        return impl_->operator()(x);\r\n    }\r\n\r\n    inline Real prime(Real x) const {\r\n        return impl_->prime(x);\r\n    }\r\n\r\n    friend std::ostream& operator<<(std::ostream & os, const cubic_hermite & m)\r\n    {\r\n        os << *m.impl_;\r\n        return os;\r\n    }\r\n\r\n    void push_back(Real x, Real y, Real dydx)\r\n    {\r\n        impl_->push_back(x, y, dydx);\r\n    }\r\n\r\n    int64_t bytes() const\r\n    {\r\n        return impl_->bytes() + sizeof(impl_);\r\n    }\r\n\r\n    std::pair<Real, Real> domain() const\r\n    {\r\n        return impl_->domain();\r\n    }\r\n\r\nprivate:\r\n    std::shared_ptr<detail::cubic_hermite_detail<RandomAccessContainer>> impl_;\r\n};\r\n\r\ntemplate<class RandomAccessContainer>\r\nclass cardinal_cubic_hermite {\r\npublic:\r\n    using Real = typename RandomAccessContainer::value_type;\r\n\r\n    cardinal_cubic_hermite(RandomAccessContainer && y, RandomAccessContainer && dydx, Real x0, Real dx) \r\n    : impl_(std::make_shared<detail::cardinal_cubic_hermite_detail<RandomAccessContainer>>(std::move(y), std::move(dydx), x0, dx))\r\n    {}\r\n\r\n    inline Real operator()(Real x) const\r\n    {\r\n        return impl_->operator()(x);\r\n    }\r\n\r\n    inline Real prime(Real x) const\r\n    {\r\n        return impl_->prime(x);\r\n    }\r\n\r\n    friend std::ostream& operator<<(std::ostream & os, const cardinal_cubic_hermite & m)\r\n    {\r\n        os << *m.impl_;\r\n        return os;\r\n    }\r\n\r\n    int64_t bytes() const\r\n    {\r\n        return impl_->bytes() + sizeof(impl_);\r\n    }\r\n\r\n    std::pair<Real, Real> domain() const\r\n    {\r\n        return impl_->domain();\r\n    }\r\n\r\nprivate:\r\n    std::shared_ptr<detail::cardinal_cubic_hermite_detail<RandomAccessContainer>> impl_;\r\n};\r\n\r\n\r\ntemplate<class RandomAccessContainer>\r\nclass cardinal_cubic_hermite_aos {\r\npublic:\r\n    using Point = typename RandomAccessContainer::value_type;\r\n    using Real = typename Point::value_type;\r\n\r\n    cardinal_cubic_hermite_aos(RandomAccessContainer && data, Real x0, Real dx) \r\n    : impl_(std::make_shared<detail::cardinal_cubic_hermite_detail_aos<RandomAccessContainer>>(std::move(data), x0, dx))\r\n    {}\r\n\r\n    inline Real operator()(Real x) const\r\n    {\r\n        return impl_->operator()(x);\r\n    }\r\n\r\n    inline Real prime(Real x) const\r\n    {\r\n        return impl_->prime(x);\r\n    }\r\n\r\n    friend std::ostream& operator<<(std::ostream & os, const cardinal_cubic_hermite_aos & m)\r\n    {\r\n        os << *m.impl_;\r\n        return os;\r\n    }\r\n\r\n    int64_t bytes() const\r\n    {\r\n        return impl_->bytes() + sizeof(impl_);\r\n    }\r\n\r\n    std::pair<Real, Real> domain() const\r\n    {\r\n        return impl_->domain();\r\n    }\r\n\r\nprivate:\r\n    std::shared_ptr<detail::cardinal_cubic_hermite_detail_aos<RandomAccessContainer>> impl_;\r\n};\r\n\r\n\r\n}\r\n#endif", "meta": {"hexsha": "05526923baa7a36a7c2773822fda34a2edcc2f45", "size": 3607, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/math/interpolators/cubic_hermite.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/interpolators/cubic_hermite.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/interpolators/cubic_hermite.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": 26.1376811594, "max_line_length": 131, "alphanum_fraction": 0.6406986415, "num_tokens": 895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.26352969228783424}}
{"text": "#pragma once\n#include <Eigen/Dense>\n\n///\n/// @struct Vechicle 3D Twist in rectangular coordinate system\n///\nstruct Twist\n{\n    double x;  // Vehicle Longitudinal speed\n    double y;  // Vehicle Lateral Speed\n    double z;\n    double roll;\n    double pitch;\n    double yaw;\n\n    Twist(const double& x, const double& y, const double& z, const double& roll, const double& pitch, const double& yaw) : x(x), y(y), z(z), roll(roll), pitch(pitch), yaw(yaw)\n    {\n    }\n    Twist() : x(0), y(0), z(0), roll(0), pitch(0), yaw(0)\n    {\n    }\n\n    inline Twist operator=(const Twist& p)\n    {\n        this->x     = p.x;\n        this->y     = p.y;\n        this->z     = p.z;\n        this->roll  = p.roll;\n        this->pitch = p.pitch;\n        this->yaw   = p.yaw;\n        return *this;\n    }\n\n    inline Twist operator-(const Twist& p) const\n    {\n        Twist diff;\n        diff.x     = this->x - p.x;\n        diff.y     = this->y - p.y;\n        diff.z     = this->z - p.z;\n        diff.roll  = this->roll - p.roll;\n        diff.pitch = this->pitch - p.pitch;\n        diff.yaw   = this->yaw - p.yaw;\n        return diff;\n    }\n\n    inline Twist operator+(const Twist& p) const\n    {\n        Twist diff;\n        diff.x     = this->x + p.x;\n        diff.y     = this->y + p.y;\n        diff.z     = this->z + p.z;\n        diff.roll  = this->roll + p.roll;\n        diff.pitch = this->pitch + p.pitch;\n        diff.yaw   = this->yaw + p.yaw;\n        return diff;\n    }\n\n    inline Twist operator+=(const Twist& p)\n    {\n        this->x += p.x;\n        this->y += p.y;\n        this->z += p.z;\n        this->roll += p.roll;\n        this->pitch += p.pitch;\n        this->yaw += p.yaw;\n        return *this;\n    }\n\n    inline Twist operator*(double d) const\n    {\n        Twist diff;\n        diff.x     = this->x * d;\n        diff.y     = this->y * d;\n        diff.z     = this->z * d;\n        diff.roll  = this->roll * d;\n        diff.pitch = this->pitch * d;\n        diff.yaw   = this->yaw * d;\n        return diff;\n    }\n\n    inline Twist operator/(double d) const\n    {\n        Twist diff;\n        diff.x     = this->x / d;\n        diff.y     = this->y / d;\n        diff.z     = this->z / d;\n        diff.roll  = this->roll / d;\n        diff.pitch = this->pitch / d;\n        diff.yaw   = this->yaw / d;\n        return diff;\n    }\n\n    inline Twist operator/=(double d)\n    {\n        this->x /= d;\n        this->y /= d;\n        this->z /= d;\n        this->roll /= d;\n        this->pitch /= d;\n        this->yaw /= d;\n        return *this;\n    }\n\n    inline bool operator==(const Twist& p)\n    {\n        bool is_equal = true;\n        is_equal      = is_equal && (this->x == p.x);\n        is_equal      = is_equal && (this->y == p.y);\n        is_equal      = is_equal && (this->z == p.z);\n        is_equal      = is_equal && (this->roll == p.roll);\n        is_equal      = is_equal && (this->pitch == p.pitch);\n        is_equal      = is_equal && (this->yaw == p.yaw);\n        return is_equal;\n    }\n\n    Eigen::Vector3d xyz() const;\n    Eigen::Vector2d xy() const;\n    Eigen::Vector3d rpy() const;\n    Eigen::Vector3d xyyaw() const;\n};\n\ninline Eigen::Vector3d Twist::xyz() const\n{\n    return Eigen::Vector3d(x, y, z);\n}\n\ninline Eigen::Vector2d Twist::xy() const\n{\n    return Eigen::Vector2d(x, y);\n}\n\ninline Eigen::Vector3d Twist::rpy() const\n{\n    return Eigen::Vector3d(roll, pitch, yaw);\n}\n\ninline Eigen::Vector3d Twist::xyyaw() const\n{\n    return Eigen::Vector3d(x, y, yaw);\n}\n", "meta": {"hexsha": "368a67e20d0ef71c3e5539d00e46f1bdec20d037", "size": 3465, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Twist.hpp", "max_stars_repo_name": "kohonda/pathtrack_tools", "max_stars_repo_head_hexsha": "5523dc7785823709c5caebfdc75390f4cccc968c", "max_stars_repo_licenses": ["MIT"], "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/Twist.hpp", "max_issues_repo_name": "kohonda/pathtrack_tools", "max_issues_repo_head_hexsha": "5523dc7785823709c5caebfdc75390f4cccc968c", "max_issues_repo_licenses": ["MIT"], "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/Twist.hpp", "max_forks_repo_name": "kohonda/pathtrack_tools", "max_forks_repo_head_hexsha": "5523dc7785823709c5caebfdc75390f4cccc968c", "max_forks_repo_licenses": ["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.5744680851, "max_line_length": 175, "alphanum_fraction": 0.4923520924, "num_tokens": 1006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.2635296922878342}}
{"text": "#include <cstdio>\n#include <cstdlib>\n#include <cmath>\n\n#include <boost/numeric/odeint.hpp>\n#include <boost/numeric/odeint/stepper/dense_output_runge_kutta.hpp>\n#include <boost/numeric/odeint/stepper/runge_kutta_dopri5.hpp>\n#include \"ch_ethz_bhepp_ode_boost_AdaptiveBoostOdeintSolver.h\"\n\n#include \"ch_ethz_bhepp_ode_boost_NativeStepperType.h\"\n#include \"Utilities.hpp\"\n\nusing namespace boost::numeric::odeint;\n\ntypedef boost::numeric::ublas::vector<double> vector_type;\ntypedef double time_type;\ntypedef vector_type state_type;\n\n\ntemplate< class ode_system >\nclass stepper_wrapper {\npublic:\n\n\tvirtual ~stepper_wrapper() { };\n\n\tvirtual void initialize(const state_type& x0, const time_type t0, const time_type dt0) = 0;\n\n\tvirtual std::pair< time_type, time_type > do_step(ode_system& sys) = 0;\n\n\tvirtual void calc_state(const time_type t_inter, state_type& x) = 0;\n\n\tvirtual const time_type current_time() = 0;\n\n\tvirtual const state_type& current_state() = 0;\n\n\tvirtual const time_type current_time_step() = 0;\n\n};\n\ntemplate < typename base_stepper_type, typename ode_system >\nclass stepper_wrapper_impl : public stepper_wrapper< ode_system > {\n\tbase_stepper_type base_stepper;\n\npublic:\n\n\tstepper_wrapper_impl(base_stepper_type base_stepper)\n\t: base_stepper(base_stepper) { }\n\n\tvoid initialize(const state_type& x0, const time_type t0, const time_type dt0) {\n\t\tbase_stepper.initialize(x0, t0, dt0);\n\t}\n\n\tstd::pair< time_type, time_type > do_step(ode_system& sys) {\n\t\treturn base_stepper.do_step(sys);\n\t}\n\n\tvoid calc_state(const time_type t_inter, state_type& x) {\n\t\tbase_stepper.calc_state(t_inter, x);\n\t}\n\n\tconst time_type current_time() {\n\t\treturn base_stepper.current_time();\n\t}\n\n\tconst state_type& current_state() {\n\t\treturn base_stepper.current_state();\n\t}\n\n\tconst time_type current_time_step() {\n\t\treturn base_stepper.current_time_step();\n\t}\n\n};\n\nstruct ode_system_wrapper;\n\nstruct boost_solver_data {\n\n//\tdense_output_runge_kutta< runge_kutta_dopri5< state_type > > stepper;\n//\trunge_kutta_dopri5< state_type > stepper;\n\tstepper_wrapper< ode_system_wrapper >* stepper;\n\tode_system_wrapper* ode_system;\n//\tdense_dopri5_stepper_type stepper;\n    JNIEnv* env;\n    jobject ode;\n    jmethodID vectorFieldMethodID;\n    jdouble initialStepSize;\n    jdouble t;\n    jdouble t1;\n    jdouble* x;\n    jdouble* xTmp;\n    jdouble* xDot;\n    state_type y;\n    state_type yTmp;\n    state_type yDot;\n\tjdouble lastStepSize;\n\tjdouble currentStepSize;\n\n\tvoid operator()(const state_type &x, state_type &dxdt, double t) {\n//\t    for (state_type::const_iterator it=x.begin(); it != x.end(); ++it) {\n\t\tfor (int i=0; i < x.size(); i++)\n\t    \txTmp[i] = x[i];\n\t    env->CallVoidMethod(ode, vectorFieldMethodID, t);\n\t    if (env->ExceptionCheck() == JNI_TRUE) {\n\t        fprintf(stderr, \"f_direct_bridge: Failed to call computeVectorField!\\n\");\n\t        return;\n\t    }\n//\t    for (state_type::const_iterator it=x.begin(); it != x.end(); ++it)\n\t\tfor (int i=0; i < dxdt.size(); i++)\n\t    \tdxdt[i] = xDot[i];\n    }\n\n};\n\nstruct ode_system_wrapper {\n\tboost_solver_data* data;\n\n\tode_system_wrapper(boost_solver_data* data)\n\t: data(data) { }\n\n\tvoid operator()(const state_type &x, state_type &dxdt, double t) {\n\t\tdata->operator()(x, dxdt, t);\n\t}\n};\n\ntypedef result_of::make_dense_output<\n    runge_kutta_dopri5< state_type > >::type dense_dopri5_stepper_type;\ntypedef bulirsch_stoer_dense_out< state_type > dense_bulirsch_stoer_stepper_type;\n//typedef result_of::make_dense_output<\n//    bulirsch_stoer< state_type > >::type dense_bulirsch_stoer_stepper_type;\n//typedef result_of::make_dense_output<\n//\trosenbrock4< double > >::type dense_rosenbrock4_stepper_type;\n\ntemplate class stepper_wrapper_impl< dense_dopri5_stepper_type, ode_system_wrapper >;\ntemplate class stepper_wrapper_impl< dense_bulirsch_stoer_stepper_type, ode_system_wrapper >;\n//template class stepper_wrapper_impl< dense_rosenbrock4_stepper_type, ode_system_wrapper >;\n\n/*\n * Class:     ch_ethz_bhepp_ode_boost_AdaptiveBoostOdeintSolver\n * Method:    jni_initialize\n * Signature: (Lch/ethz/bhepp/ode/BufferOdeAdapter;Ljava/nio/DoubleBuffer;Ljava/nio/DoubleBuffer;Ljava/nio/DoubleBuffer;DDDI)J\n */\nJNIEXPORT jlong JNICALL Java_ch_ethz_bhepp_ode_boost_AdaptiveBoostOdeintSolver_jni_1initialize\n\t(JNIEnv *env, jobject obj, jobject ode, jobject xBuffer, jobject xTmpBuffer, jobject xDotBuffer,\n\t\t\tjdouble initialStepSize, jdouble relTol, jdouble absTol, jint stepperType) {\n    jclass odeCls = env->GetObjectClass(ode);\n    if (env->ExceptionCheck() == JNI_TRUE) {\n        fprintf(stderr, \"jni_initialize: Failed to get class of ode object\\n\");\n        return 0;\n    }\n    jmethodID methodID = env->GetMethodID(odeCls, \"getDimensionOfVectorField\", \"()I\");\n    if (env->ExceptionCheck() == JNI_TRUE) {\n        fprintf(stderr, \"jni_initialize: Failed to get method ID of getDimensionOfVectorField\\n\");\n        return 0;\n    }\n    jint jdimension = env->CallIntMethod(ode, methodID);\n    state_type::size_type dimension = jdimension;\n    if (env->ExceptionCheck() == JNI_TRUE) {\n        fprintf(stderr, \"jni_initialize: Failed to call getDimensionOfVectorField\\n\");\n        return 0;\n    }\n\n    // Allocate and initialize boost_solver_data\n    boost_solver_data* data = new boost_solver_data();\n\n    // FIXME\n    if (env->ExceptionCheck() == JNI_TRUE) {\n        fprintf(stderr, \"jni_initialize: Failed to allocate boost_solver_data\\n\");\n        return 0;\n    }\n\n    switch (stepperType) {\n    case ch_ethz_bhepp_ode_boost_NativeStepperType_BOOSTSTEPPERTYPE_DORMANDPRINCE5:\n    {\n    \tdense_dopri5_stepper_type base_stepper1 = make_dense_output< runge_kutta_dopri5< state_type > >(absTol, relTol);\n    \tdata->stepper = new stepper_wrapper_impl< dense_dopri5_stepper_type, ode_system_wrapper >(base_stepper1);\n    \tbreak;\n    }\n    case ch_ethz_bhepp_ode_boost_NativeStepperType_BOOSTSTEPPERTYPE_BULIRSCHSTOER:\n    {\n    \tdense_bulirsch_stoer_stepper_type base_stepper2 = dense_bulirsch_stoer_stepper_type(absTol, relTol);\n    \tdata->stepper = new stepper_wrapper_impl< dense_bulirsch_stoer_stepper_type, ode_system_wrapper >(base_stepper2);\n    \tbreak;\n    }\n//    case ch_ethz_bhepp_ode_boost_NativeStepperType_BOOSTSTEPPERTYPE_ROSENBROCK4:\n//    {\n//    \tdense_rosenbrock4_stepper_type base_stepper3 = make_dense_output< rosenbrock4< double > >(absTol, relTol);\n//    \tdata->stepper = new stepper_wrapper_impl< dense_rosenbrock4_stepper_type, ode_system_wrapper >(base_stepper3);\n//    \tbreak;\n//    }\n    default:\n\t{\n        throw_java_exception(env, \"Unknown stepper type\\n\");\n    \tdelete data;\n    \treturn 0;\n\t}\n    }\n\n    // FIXME\n    data->ode_system = new ode_system_wrapper(data);\n    data->initialStepSize = initialStepSize;\n\n    data->env = env;\n    // Acquire method IDs of callbacks and put them into boost_solver_data\n    data->ode = env->NewGlobalRef(ode);\n    if (env->ExceptionCheck() == JNI_TRUE) {\n        fprintf(stderr, \"jni_initialize: Failed to create global reference to ode object\\n\");\n        delete data;\n        return 0;\n    }\n    data->vectorFieldMethodID = env->GetMethodID(odeCls, \"computeVectorField\", \"(D)V\");\n    if (env->ExceptionCheck() == JNI_TRUE) {\n        fprintf(stderr, \"jni_initialize: Failed to get method ID of computeVectorField\\n\");\n        // Delete global java references\n        env->DeleteGlobalRef(data->ode);\n        delete data;\n        return 0;\n    }\n\n    // Check capacities of direct buffer objects\n    if (env->GetDirectBufferCapacity(xBuffer) < dimension) {\n        throw_java_exception(env, \"jni_initialize: Direct buffer xBuffer is not big enough\\n\");\n        // Delete global java references\n        env->DeleteGlobalRef(data->ode);\n        delete data;\n        return 0;\n    }\n    if (env->GetDirectBufferCapacity(xTmpBuffer) < dimension) {\n        throw_java_exception(env, \"jni_initialize: Direct buffer xTmpBuffer is not big enough\\n\");\n        // Delete global java references\n        env->DeleteGlobalRef(data->ode);\n        delete data;\n        return 0;\n    }\n    if (env->GetDirectBufferCapacity(xDotBuffer) < dimension) {\n        throw_java_exception(env, \"jni_initialize: Direct buffer xDotBuffer is not big enough\\n\");\n        // Delete global java references\n        env->DeleteGlobalRef(data->ode);\n        delete data;\n        return 0;\n    }\n    // Get addresses of direct buffer objects\n    data->x = static_cast<jdouble*>(env->GetDirectBufferAddress(xBuffer));\n    if (data->x == NULL) {\n        fprintf(stderr, \"jni_initialize: Failed to get direct address of xBuffer\\n\");\n        // Delete global java references\n        env->DeleteGlobalRef(data->ode);\n        delete data;\n        return 0;\n    }\n    data->xTmp = static_cast<jdouble*>(env->GetDirectBufferAddress(xTmpBuffer));\n    if (data->xTmp == NULL) {\n        fprintf(stderr, \"jni_initialize: Failed to get direct address of xTmpBuffer\\n\");\n        // Delete global java references\n        env->DeleteGlobalRef(data->ode);\n        delete data;\n        return 0;\n    }\n    data->xDot = static_cast<jdouble*>(env->GetDirectBufferAddress(xDotBuffer));\n    if (data->xDot == NULL) {\n        fprintf(stderr, \"jni_initialize: Failed to get direct address of xDotBuffer\\n\");\n        // Delete global java references\n        env->DeleteGlobalRef(data->ode);\n        delete data;\n        return 0;\n    }\n\n    data->y.resize(dimension, false);\n    data->yTmp.resize(dimension, false);\n    data->yDot.resize(dimension, false);\n\n    data->lastStepSize = data->initialStepSize;\n    data->currentStepSize = data->initialStepSize;\n\n    // Pass pointer-address of boost_solver_data back to Java\n    jlong jni_pointer = (jlong)data;\n    return jni_pointer;\n}\n\n/*\n * Class:     ch_ethz_bhepp_ode_boost_AdaptiveBoostOdeintSolver\n * Method:    jni_dispose\n * Signature: (J)V\n */\nJNIEXPORT void JNICALL Java_ch_ethz_bhepp_ode_boost_AdaptiveBoostOdeintSolver_jni_1dispose\n  (JNIEnv *env, jobject obj, jlong jni_pointer) {\n    boost_solver_data* data = (boost_solver_data*)jni_pointer;\n    if (data != NULL) {\n        // Delete global java references\n        if (data->ode != NULL)\n            env->DeleteGlobalRef(data->ode);\n        // Free data structure\n        delete data;\n    }\n}\n\n/*\n * Class:     ch_ethz_bhepp_ode_boost_AdaptiveBoostOdeintSolver\n * Method:    jni_prepareStep\n * Signature: (JDD)V\n */\nJNIEXPORT void JNICALL Java_ch_ethz_bhepp_ode_boost_AdaptiveBoostOdeintSolver_jni_1prepareStep\n\t(JNIEnv *env, jobject obj, jlong jni_pointer, jdouble t0, jdouble t1) {\n    boost_solver_data* data = reinterpret_cast< boost_solver_data* >(jni_pointer);\n    data->t = t0;\n    data->t1 = t1;\n    for (int i=0; i < data->y.size(); i++)\n    \tdata->y[i] = data->x[i];\n    data->stepper->initialize(data->y, data->t, data->currentStepSize);\n}\n\n/*\n * Class:     ch_ethz_bhepp_ode_boost_AdaptiveBoostOdeintSolver\n * Method:    jni_getCurrentState\n * Signature: (J)D\n */\nJNIEXPORT jdouble JNICALL Java_ch_ethz_bhepp_ode_boost_AdaptiveBoostOdeintSolver_jni_1getCurrentState\n  (JNIEnv *env, jobject obj, jlong jni_pointer) {\n    boost_solver_data* data = reinterpret_cast< boost_solver_data* >(jni_pointer);\n    const dense_dopri5_stepper_type::state_type& current_state = data->stepper->current_state();\n    for (int i=0; i < data->y.size(); i++)\n    \tdata->xTmp[i] = current_state[i];\n    return data->stepper->current_time();\n}\n\n/*\n * Class:     ch_ethz_bhepp_ode_boost_AdaptiveBoostOdeintSolver\n * Method:    jni_integrateStep\n * Signature: (J)D\n */\nJNIEXPORT jdouble JNICALL Java_ch_ethz_bhepp_ode_boost_AdaptiveBoostOdeintSolver_jni_1integrateStep\n(JNIEnv *env, jobject obj, jlong jni_pointer) {\n    boost_solver_data* data = reinterpret_cast< boost_solver_data* >(jni_pointer);\n    std::pair< double , double > times = data->stepper->do_step(*data->ode_system);\n    data->lastStepSize = data->currentStepSize;\n    data->currentStepSize = data->stepper->current_time_step();\n    return times.second;\n}\n\n/*\n * Class:     ch_ethz_bhepp_ode_boost_AdaptiveBoostOdeintSolver\n * Method:    jni_computeInterpolatedSolution\n * Signature: (JD)V\n */\nJNIEXPORT void JNICALL Java_ch_ethz_bhepp_ode_boost_AdaptiveBoostOdeintSolver_jni_1computeInterpolatedSolution\n  (JNIEnv *env, jobject obj, jlong jni_pointer, jdouble t) {\n    boost_solver_data* data = reinterpret_cast< boost_solver_data* >(jni_pointer);\n    data->stepper->calc_state(t, data->yTmp);\n    for (int i=0; i < data->yTmp.size(); i++)\n    \tdata->xTmp[i] = data->yTmp[i];\n}\n\n/*\n * Class:     ch_ethz_bhepp_ode_boost_AdaptiveBoostOdeintSolver\n * Method:    jni_setCurrentStepSize\n * Signature: (JD)V\n */\nJNIEXPORT void JNICALL Java_ch_ethz_bhepp_ode_boost_AdaptiveBoostOdeintSolver_jni_1setCurrentStepSize\n  (JNIEnv *env, jobject obj, jlong jni_pointer, jdouble stepSize) {\n    boost_solver_data* data = reinterpret_cast< boost_solver_data* >(jni_pointer);\n    data->currentStepSize = stepSize;\n}\n\n/*\n * Class:     ch_ethz_bhepp_ode_boost_AdaptiveBoostOdeintSolver\n * Method:    jni_getCurrentStepSize\n * Signature: (J)D\n */\nJNIEXPORT jdouble JNICALL Java_ch_ethz_bhepp_ode_boost_AdaptiveBoostOdeintSolver_jni_1getCurrentStepSize\n  (JNIEnv *env, jobject obj, jlong jni_pointer) {\n    boost_solver_data* data = reinterpret_cast< boost_solver_data* >(jni_pointer);\n    return data->currentStepSize;\n}\n\n/*\n * Class:     ch_ethz_bhepp_ode_boost_AdaptiveBoostOdeintSolver\n * Method:    jni_getLastStepSize\n * Signature: (J)D\n */\nJNIEXPORT jdouble JNICALL Java_ch_ethz_bhepp_ode_boost_AdaptiveBoostOdeintSolver_jni_1getLastStepSize\n(JNIEnv *env, jobject obj, jlong jni_pointer) {\n  boost_solver_data* data = reinterpret_cast< boost_solver_data* >(jni_pointer);\n  return data->lastStepSize;\n}\n", "meta": {"hexsha": "38ee3c21d10817db205223387d22d59120e5bb38", "size": 13590, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "JavaOde/jni/boost/src/AdaptiveBoostOdeintSolver.cpp", "max_stars_repo_name": "bennihepp/HybridStochasticSimulation", "max_stars_repo_head_hexsha": "a19a777339be375a7301b69fbf1c0d840040e471", "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": "JavaOde/jni/boost/src/AdaptiveBoostOdeintSolver.cpp", "max_issues_repo_name": "bennihepp/HybridStochasticSimulation", "max_issues_repo_head_hexsha": "a19a777339be375a7301b69fbf1c0d840040e471", "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": "JavaOde/jni/boost/src/AdaptiveBoostOdeintSolver.cpp", "max_forks_repo_name": "bennihepp/HybridStochasticSimulation", "max_forks_repo_head_hexsha": "a19a777339be375a7301b69fbf1c0d840040e471", "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.2987012987, "max_line_length": 126, "alphanum_fraction": 0.7233995585, "num_tokens": 3668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.26352968492426154}}
{"text": "//\n// Created by christoph on 02.10.18.\n//\n\n#include <fstream>\n#include <iostream>\n#include <chrono>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/algorithm/string/split.hpp>\n\n#include <GL/glew.h>\n\n#include <Utils/Convert.hpp>\n#include <Utils/File/Logfile.hpp>\n#include <Math/Math.hpp>\n#include <Graphics/Renderer.hpp>\n#include <Graphics/Shader/ShaderManager.hpp>\n#include <Graphics/Texture/TextureManager.hpp>\n#include <Graphics/OpenGL/GeometryBuffer.hpp>\n#include <Graphics/OpenGL/Texture.hpp>\n\n#include \"Utils/HairLoader.hpp\"\n#include \"Utils/TrajectoryFile.hpp\"\n#include \"VoxelCurveDiscretizer.hpp\"\n\n#define BIAS 0.001\n\n/**\n * Helper function for rayBoxIntersection (see below).\n */\nbool rayBoxPlaneIntersection(float rayOriginX, float rayDirectionX, float lowerX, float upperX,\n                             float &tNear, float &tFar)\n{\n    if (std::abs(rayDirectionX) < BIAS) {\n        // Ray is parallel to the x planes\n        if (rayOriginX < lowerX || rayOriginX > upperX) {\n            return false;\n        }\n    } else {\n        // Not parallel to the x planes. Compute the intersection distance to the planes.\n        float t0 = (lowerX - rayOriginX) / rayDirectionX;\n        float t1 = (upperX - rayOriginX) / rayDirectionX;\n        if (t0 > t1) {\n            // Since t0 intersection with near plane\n            float tmp = t0;\n            t0 = t1;\n            t1 = tmp;\n        }\n\n        if (t0 > tNear) {\n            // We want the largest tNear\n            tNear = t0;\n        }\n        if (t1 < tFar) {\n            // We want the smallest tFar\n            tFar = t1;\n        }\n        if (tNear > tFar) {\n            // Box is missed\n            return false;\n        }\n        if (tFar < 0) {\n            // Box is behind ray\n            return false;\n        }\n    }\n    return true;\n}\n\n/**\n * Implementation of ray-box intersection (idea from A. Glassner et al., \"An Introduction to Ray Tracing\").\n * For more details see: https://www.siggraph.org//education/materials/HyperGraph/raytrace/rtinter3.htm\n */\nbool rayBoxIntersection(glm::vec3 rayOrigin, glm::vec3 rayDirection, glm::vec3 lower, glm::vec3 upper,\n                        float &tNear, float &tFar)\n{\n    tNear = -1e7;\n    tFar = 1e7;\n    for (int i = 0; i < 3; i++) {\n        if (!rayBoxPlaneIntersection(rayOrigin[i], rayDirection[i], lower[i], upper[i], tNear, tFar)) {\n            return false;\n        }\n    }\n\n    //entrancePoint = rayOrigin + tNear * rayDirection;\n    //exitPoint = rayOrigin + tFar * rayDirection;\n    return true;\n}\n\n\n\n\nbool VoxelDiscretizer::addPossibleIntersections(const glm::vec3 &v1, const glm::vec3 &v2, float a1, float a2)\n{\n    float tNear, tFar;\n    glm::vec3 voxelLower = glm::vec3(index);\n    glm::vec3 voxelUpper = glm::vec3(index + glm::ivec3(1,1,1));\n    if (rayBoxIntersection(v1, (v2 - v1), voxelLower, voxelUpper, tNear, tFar)) {\n        bool intersectionNear = 0.0f <= tNear && tNear <= 1.0f;\n        bool intersectionFar = 0.0f <= tFar && tFar <= 1.0f;\n        if (intersectionNear) {\n            glm::vec3 entrancePoint = v1 + tNear * (v2 - v1);\n            float interpolatedAttribute = a1 + tNear * (a2 - a1);\n            currentCurveIntersections.emplace_back(entrancePoint, interpolatedAttribute);\n        }\n        if (intersectionFar) {\n            glm::vec3 exitPoint = v1 + tFar * (v2 - v1);\n            float interpolatedAttribute = a1 + tFar * (a2 - a1);\n            currentCurveIntersections.emplace_back(exitPoint, interpolatedAttribute);\n        }\n        if (intersectionNear || intersectionFar) {\n            return true; // Intersection found\n        }\n    }\n\n    return false;\n}\n\nvoid VoxelDiscretizer::setIndex(glm::ivec3 index)\n{\n    this->index = index;\n}\n\nfloat VoxelDiscretizer::computeDensity(float maxVorticity)\n{\n    float density = 0.0f;\n    for (LineSegment &line : lines) {\n        density += line.length() * line.avgOpacity(maxVorticity);\n    }\n    return density;\n}\n\nfloat VoxelDiscretizer::computeDensityHair(float opacity)\n{\n    float density = 0.0f;\n    for (LineSegment &line : lines) {\n        density += line.length() * opacity;\n    }\n    return density;\n}\n\n\n\n\n\n\n\nVoxelCurveDiscretizer::VoxelCurveDiscretizer(const glm::ivec3 &gridResolution, const glm::ivec3 &quantizationResolution)\n        : gridResolution(gridResolution), quantizationResolution(quantizationResolution)\n{\n    voxels = nullptr;\n}\n\nVoxelCurveDiscretizer::~VoxelCurveDiscretizer()\n{\n    delete[] voxels;\n}\n\nvoid VoxelCurveDiscretizer::setVoxelGrid(const sgl::AABB3 &aabb)\n{\n    glm::vec3 gridDimensions = aabb.getDimensions();\n    glm::vec3 gridResolutionCubic = gridResolution;\n\n    float maxDimensionLength = 0.0f;\n    for (int i = 0; i < 3; i++) {\n        maxDimensionLength = std::max(maxDimensionLength, gridDimensions[i]);\n    }\n    for (int i = 0; i < 3; i++) {\n        float sideLengthFactor = gridDimensions[i] / maxDimensionLength;\n        gridResolution[i] = (int)std::ceil(gridResolution[i] * sideLengthFactor);\n    }\n\n    voxels = new VoxelDiscretizer[gridResolution.x * gridResolution.y * gridResolution.z];\n    for (int z = 0; z < gridResolution.z; z++) {\n        for (int y = 0; y < gridResolution.y; y++) {\n            for (int x = 0; x < gridResolution.x; x++) {\n                int index = x + y*gridResolution.x + z*gridResolution.x*gridResolution.y;\n                voxels[index].setIndex(glm::ivec3(x, y, z));\n            }\n        }\n    }\n}\n\n\nVoxelGridDataCompressed VoxelCurveDiscretizer::createFromTrajectoryDataset(const std::string &filename,\n        TrajectoryType trajectoryType, std::vector<float> &attributes, float &_maxVorticity,\n        unsigned int maxNumLinesPerVoxel, bool useGPU)\n{\n    linesBoundingBox = sgl::AABB3();\n    std::vector<Curve> curves;\n    Curve currentCurve;\n    maxVorticity = 0.0f;\n    isHairDataset = false;\n    uint64_t numLineSegments = 0;\n    uint64_t numLines = 0;\n\n    bool isRings = boost::starts_with(filename, \"Data/Rings\");\n    bool isConvectionRolls = boost::starts_with(filename, \"Data/ConvectionRolls/output\");\n    bool isConvectionRollsSmall = boost::starts_with(filename, \"Data/ConvectionRolls/turbulence20000\");\n\n\n    Trajectories trajectories = loadTrajectoriesFromFile(filename, trajectoryType);\n\n    for (size_t i = 0; i < trajectories.size(); i++) {\n        Trajectory &trajectory = trajectories.at(i);\n\n        currentCurve = Curve();\n        for (size_t j = 0; j < trajectory.positions.size(); j++) {\n            glm::vec3 &position = trajectory.positions.at(j);\n            linesBoundingBox.combine(position);\n            currentCurve.points.push_back(position);\n            currentCurve.attributes.push_back(trajectory.attributes.at(0).at(j));\n        }\n\n        currentCurve.lineID = numLines;\n        curves.push_back(currentCurve);\n        numLineSegments += currentCurve.points.size() - 1;\n        numLines++;\n    }\n\n\n    std::cout << \"Num Lines: \" << numLines << std::endl;\n    std::cout << \"Num LineSegments: \" << numLineSegments << std::endl << std::flush;\n\n\n    /*if (isRings) {\n        linesBoundingBox = sgl::AABB3();\n        linesBoundingBox.combine(glm::vec3(-2));\n        linesBoundingBox.combine(glm::vec3(2));\n    } else if (isConvectionRolls) {\n        linesBoundingBox = sgl::AABB3();\n        //linesBoundingBox.combine(glm::vec3(-1.5, -0.5, -1.5));\n        //linesBoundingBox.combine(glm::vec3( 1.5, 0.5, 1.5));\n        linesBoundingBox.combine(glm::vec3(-1.5, -1.5, -1.5));\n        linesBoundingBox.combine(glm::vec3( 1.5, 1.5, 1.5));\n    } else if (isConvectionRollsSmall) {\n        linesBoundingBox = sgl::AABB3();\n        linesBoundingBox.combine(glm::vec3(0.0, 0.0, 0.0));\n        linesBoundingBox.combine(glm::vec3(1.0, 1.0, 1.0)); // 1.0, 1.0, 0.03\n    }*/\n\n    _maxVorticity = maxVorticity;\n    this->attributes = attributes;\n\n\n    // Move to origin and scale to range from (0, 0, 0) to (rx, ry, rz).\n    setVoxelGrid(linesBoundingBox);\n    linesToVoxel = sgl::matrixScaling(1.0f / linesBoundingBox.getDimensions() * glm::vec3(gridResolution))\n            * sgl::matrixTranslation(-linesBoundingBox.getMinimum());\n    voxelToLines = glm::inverse(linesToVoxel);\n\n    std::cout << \"Grid resolution: \" << gridResolution.x << \" \" << gridResolution.y\n              << \" \" << gridResolution.z << std::endl;\n    std::cout << \"Bounding box: \" << linesBoundingBox.getMaximum().x << \" \" << linesBoundingBox.getMaximum().y\n              << \" \" << linesBoundingBox.getMaximum().z << std::endl << std::flush;\n\n    // Transform curves to voxel grid space\n    for (Curve &curve : curves) {\n        for (glm::vec3 &v : curve.points) {\n            v = sgl::transformPoint(linesToVoxel, v);\n        }\n    }\n\n    if (!useGPU) {\n        // Insert lines into voxel representation\n        //int lineNum = 0;\n        for (const Curve &curve : curves) {\n            /*if (lineNum == 1000) {\n                break;\n            }*/\n            nextStreamline(curve);\n            //lineNum++;\n        }\n        return compressData();\n    } else {\n        return createVoxelGridGPU(curves, maxNumLinesPerVoxel);\n    }\n}\n\n\nVoxelGridDataCompressed VoxelCurveDiscretizer::createFromHairDataset(const std::string &filename, float &lineRadius,\n        glm::vec4 &hairStrandColor, unsigned int maxNumLinesPerVoxel, bool useGPU)\n{\n    HairData hairData;\n    loadHairFile(filename, hairData);\n    downscaleHairData(hairData, HAIR_MODEL_SCALING_FACTOR);\n\n    // Assume default thickness, opacity and color for now to simplify the implementation\n    lineRadius = hairData.defaultThickness;\n    hairStrandColor = glm::vec4(hairData.defaultColor, hairData.defaultOpacity);\n    this->hairThickness = lineRadius;\n    this->hairStrandColor = hairStrandColor;\n    this->hairOpacity = hairData.defaultOpacity;\n\n\n    linesBoundingBox = sgl::AABB3();\n    std::vector<Curve> curves;\n    Curve currentCurve;\n    maxVorticity = 0.0f;\n    int lineCounter = 0;\n    isHairDataset = true;\n\n    // Process all strands and convert them to curves\n    for (HairStrand &strand : hairData.strands) {\n        lineCounter++;\n        if (lineCounter % 1000 == 999) {\n            sgl::Logfile::get()->writeInfo(std::string() + \"Parsing hair strand \" + sgl::toString(lineCounter) + \"...\");\n        }\n\n        for (glm::vec3 point : strand.points) {\n            glm::vec3 scaledPoint = point;\n            currentCurve.points.push_back(scaledPoint);\n            currentCurve.attributes.push_back(this->hairOpacity);\n            linesBoundingBox.combine(scaledPoint);\n        }\n\n        curves.push_back(currentCurve);\n        currentCurve = Curve();\n        currentCurve.lineID = lineCounter;\n    }\n\n    // Move to origin and scale to range from (0, 0, 0) to (rx, ry, rz).\n    setVoxelGrid(linesBoundingBox);\n    linesToVoxel = sgl::matrixScaling(1.0f / linesBoundingBox.getDimensions() * glm::vec3(gridResolution))\n                   * sgl::matrixTranslation(-linesBoundingBox.getMinimum());\n    voxelToLines = glm::inverse(linesToVoxel);\n\n    // Transform curves to voxel grid space\n    for (Curve &curve : curves) {\n        for (glm::vec3 &v : curve.points) {\n            v = sgl::transformPoint(linesToVoxel, v);\n        }\n    }\n\n    if (!useGPU) {\n        // Insert lines into voxel representation\n        for (const Curve &curve : curves) {\n            nextStreamline(curve);\n        }\n        return compressData();\n    } else {\n        return createVoxelGridGPU(curves, maxNumLinesPerVoxel);\n    }\n}\n\n\nVoxelGridDataCompressed VoxelCurveDiscretizer::compressData()\n{\n    VoxelGridDataCompressed dataCompressed;\n    dataCompressed.gridResolution = gridResolution;\n    dataCompressed.quantizationResolution = quantizationResolution;\n    dataCompressed.worldToVoxelGridMatrix = this->getWorldToVoxelGridMatrix();\n    dataCompressed.dataType = isHairDataset ? 1u : 0u;\n\n    if (isHairDataset) {\n        dataCompressed.hairStrandColor = hairStrandColor;\n        dataCompressed.hairThickness = hairThickness;\n    } else {\n        dataCompressed.attributes = attributes;\n        dataCompressed.maxVorticity = maxVorticity;\n    }\n\n    int n = gridResolution.x * gridResolution.y * gridResolution.z;\n    std::vector<float> voxelDensities;\n    std::vector<uint32_t> usedVoxels;\n    voxelDensities.reserve(n);\n    usedVoxels.reserve(n);\n\n    size_t lineOffset = 0;\n    dataCompressed.voxelLineListOffsets.reserve(n);\n    dataCompressed.numLinesInVoxel.reserve(n);\n    dataCompressed.lineSegments.clear();\n\n    for (int i = 0; i < n; i++) {\n        dataCompressed.voxelLineListOffsets.push_back(lineOffset);\n        size_t numLines = voxels[i].lines.size();\n        dataCompressed.numLinesInVoxel.push_back(numLines);\n        if (isHairDataset) {\n            voxelDensities.push_back(voxels[i].computeDensityHair(hairOpacity));\n        } else {\n            voxelDensities.push_back(voxels[i].computeDensity(maxVorticity));\n        }\n        usedVoxels.push_back(numLines > 0 ? 1 : 0);\n\n#ifdef PACK_LINES\n        std::vector<LineSegmentCompressed> lineSegments;\n        lineSegments.resize(voxels[i].lines.size());\n        for (size_t j = 0; j < voxels[i].lines.size(); j++) {\n            compressLine(voxels[i].getIndex(), voxels[i].lines[j], lineSegments[j]);\n\n            // Test\n            /*LineSegment originalLine = voxels[i].lines[j];\n            LineSegment decompressedLine;\n            decompressLine(glm::vec3(voxels[i].getIndex()), lineSegments[j], decompressedLine);\n            if (!checkLinesEqual(originalLine, decompressedLine)) {\n                compressLine(voxels[i].getIndex(), voxels[i].lines[j], lineSegments[j]);\n                decompressLine(glm::vec3(voxels[i].getIndex()), lineSegments[j], decompressedLine);\n            }*/\n        }\n        dataCompressed.lineSegments.insert(dataCompressed.lineSegments.end(),\n                lineSegments.begin(), lineSegments.end());\n#else\n        dataCompressed.lineSegments.insert(dataCompressed.lineSegments.end(),\n                voxels[i].lines.begin(), voxels[i].lines.end());\n#endif\n\n        lineOffset += numLines;\n    }\n\n    std::vector<float> voxelAOFactors;\n    voxelAOFactors.resize(n);\n    generateVoxelAOFactorsFromDensity(voxelDensities, voxelAOFactors, gridResolution, isHairDataset);\n\n    dataCompressed.voxelDensities = voxelDensities;\n    dataCompressed.voxelAOFactors = voxelAOFactors;\n    return dataCompressed;\n}\n\n\n\nstd::vector<VoxelDiscretizer*> VoxelCurveDiscretizer::getVoxelsInAABB(const sgl::AABB3 &aabb)\n{\n    std::vector<VoxelDiscretizer*> voxelsInAABB;\n    glm::vec3 minimum = aabb.getMinimum();\n    glm::vec3 maximum = aabb.getMaximum();\n\n    glm::ivec3 lower = glm::ivec3(minimum); // Round down\n    glm::ivec3 upper = glm::ivec3(ceil(maximum.x), ceil(maximum.y), ceil(maximum.z)); // Round up\n    lower = glm::max(lower, glm::ivec3(0));\n    upper = glm::min(upper, gridResolution - glm::ivec3(1));\n\n    for (int z = lower.z; z <= upper.z; z++) {\n        for (int y = lower.y; y <= upper.y; y++) {\n            for (int x = lower.x; x <= upper.x; x++) {\n                int index = x + y*gridResolution.x + z*gridResolution.x*gridResolution.y;\n                voxelsInAABB.push_back(voxels + index);\n            }\n        }\n    }\n    return voxelsInAABB;\n}\n\nvoid VoxelCurveDiscretizer::nextStreamline(const Curve &line)\n{\n    int N = line.points.size();\n\n    // Add intersections to voxels\n    std::set<VoxelDiscretizer*> usedVoxels;\n    for (int i = 0; i < N-1; i++) {\n        // Get line segment\n        glm::vec3 v1 = line.points.at(i);\n        glm::vec3 v2 = line.points.at(i+1);\n        float a1 = line.attributes.at(i);\n        float a2 = line.attributes.at(i+1);\n\n        // Remove invalid line points (used in many scientific datasets to indicate invalid lines).\n        const float MAX_VAL = 1e10;\n        if (std::fabs(v1.x) > MAX_VAL || std::fabs(v1.y) > MAX_VAL || std::fabs(v1.z) > MAX_VAL\n                || std::fabs(v2.x) > MAX_VAL || std::fabs(v2.y) > MAX_VAL || std::fabs(v2.z) > MAX_VAL) {\n            continue;\n        }\n\n        // Compute AABB of current segment\n        sgl::AABB3 segmentAABB = sgl::AABB3();\n        segmentAABB.combine(v1);\n        segmentAABB.combine(v2);\n\n        // Iterate over all voxels with possible intersections\n        std::vector<VoxelDiscretizer*> voxelsInAABB = getVoxelsInAABB(segmentAABB);\n\n        for (VoxelDiscretizer *voxel : voxelsInAABB) {\n            // Line-voxel intersection\n            if (voxel->addPossibleIntersections(v1, v2, a1, a2)) {\n                // Intersection(s) added to \"currentLineIntersections\", voxel used\n                usedVoxels.insert(voxel);\n            }\n        }\n    }\n\n    // Convert intersections to clipped line segments\n    for (VoxelDiscretizer *voxel : usedVoxels) {\n        if (voxel->currentCurveIntersections.size() < 2) {\n            voxel->currentCurveIntersections.clear();\n            continue;\n        }\n        auto it1 = voxel->currentCurveIntersections.begin();\n        auto it2 = voxel->currentCurveIntersections.begin();\n        it2++;\n        while (it2 != voxel->currentCurveIntersections.end()) {\n            voxel->lines.push_back(LineSegment(it1->v, it1->a, it2->v, it2->a, line.lineID));\n            it1++; it1++;\n            if (it1 == voxel->currentCurveIntersections.end()) break;\n            it2++; it2++;\n        }\n        voxel->currentCurveIntersections.clear();\n    }\n}\n\ntemplate<typename T>\nT clamp(T x, T a, T b) {\n    if (x < a) {\n        return a;\n    } else if (x > b) {\n        return b;\n    } else {\n        return x;\n    }\n}\n\nvoid VoxelCurveDiscretizer::quantizeLine(const glm::vec3 &voxelPos, const LineSegment &line,\n        LineSegmentQuantized &lineQuantized, int faceIndex1, int faceIndex2)\n{\n    lineQuantized.a1 = line.a1;\n    lineQuantized.a2 = line.a2;\n\n    glm::ivec2 facePosition3D1, facePosition3D2;\n    quantizePoint(line.v1 - voxelPos, facePosition3D1, faceIndex1);\n    quantizePoint(line.v2 - voxelPos, facePosition3D2, faceIndex2);\n    lineQuantized.lineID = line.lineID;\n    lineQuantized.faceIndex1 = faceIndex1;\n    lineQuantized.faceIndex2 = faceIndex2;\n    lineQuantized.facePositionQuantized1 = facePosition3D1.x + facePosition3D1.y*quantizationResolution.x;\n    lineQuantized.facePositionQuantized2 = facePosition3D2.x + facePosition3D2.y*quantizationResolution.x;\n}\n\nint intlog2(int x) {\n    int exponent = 0;\n    while (x > 1) {\n        x /= 2;\n        exponent++;\n    }\n    return exponent;\n}\n\nvoid VoxelCurveDiscretizer::compressLine(const glm::ivec3 &voxelIndex, const LineSegment &line,\n        LineSegmentCompressed &lineCompressed)\n{\n    LineSegmentQuantized lineQuantized;\n    int faceIndex1 = computeFaceIndex(line.v1, voxelIndex);\n    int faceIndex2 = computeFaceIndex(line.v2, voxelIndex);\n    quantizeLine(glm::vec3(voxelIndex), line, lineQuantized, faceIndex1, faceIndex2);\n\n    uint8_t attr1Unorm = std::round(lineQuantized.a1*255.0f);\n    uint8_t attr2Unorm = std::round(lineQuantized.a2*255.0f);\n\n    int c = round(2*intlog2(quantizationResolution.x));\n    lineCompressed.linePosition = lineQuantized.faceIndex1;\n    lineCompressed.linePosition |= lineQuantized.faceIndex2 << 3;\n    lineCompressed.linePosition |= lineQuantized.facePositionQuantized1 << 6;\n    lineCompressed.linePosition |= lineQuantized.facePositionQuantized2 << (6 + c);\n    lineCompressed.attributes = 0;\n    if (c > 12) {\n        // Quantization resolution of 128 or 256\n        lineCompressed.attributes |= lineQuantized.facePositionQuantized2 >> (c - (6 + 2*c - 32));\n    }\n    lineCompressed.attributes |= (lineQuantized.lineID & 31u) << 11;\n    lineCompressed.attributes |= attr1Unorm << 16;\n    lineCompressed.attributes |= attr2Unorm << 24;\n}\n\nvoid VoxelCurveDiscretizer::quantizePoint(const glm::vec3 &v, glm::ivec2 &qv, int faceIndex)\n{\n    int dimensions[2];\n    if (faceIndex == 0 || faceIndex == 1) {\n        // x face\n        dimensions[0] = 1;\n        dimensions[1] = 2;\n    } else if (faceIndex == 2 || faceIndex == 3) {\n        // y face\n        dimensions[0] = 0;\n        dimensions[1] = 2;\n    } else {\n        // z face\n        dimensions[0] = 0;\n        dimensions[1] = 1;\n    }\n\n    // Iterate over all dimensions\n    for (int i = 0; i < 2; i++) {\n        int quantizationPos = std::floor(v[dimensions[i]] * quantizationResolution[dimensions[i]]);\n        qv[i] = glm::clamp(quantizationPos, 0, quantizationResolution[dimensions[i]]-1);\n    }\n}\n\nint VoxelCurveDiscretizer::computeFaceIndex(const glm::vec3 &v, const glm::ivec3 &voxelIndex)\n{\n    glm::ivec3 lower = voxelIndex, upper = voxelIndex + glm::ivec3(1);\n    for (int i = 0; i < 3; i++) {\n        if (std::abs(v[i] - lower[i]) < 0.00001f) {\n            return 2*i;\n        }\n        if (std::abs(v[i] - upper[i]) < 0.00001f) {\n            return 2*i+1;\n        }\n    }\n    sgl::Logfile::get()->writeError(std::string() + \"Error in VoxelCurveDiscretizer::computeFaceIndex: \"\n            + \"Invalid position.\");\n    return 0;\n}\n\n\n\n\nglm::vec3 VoxelCurveDiscretizer::getQuantizedPositionOffset(uint32_t faceIndex, uint32_t quantizedPos1D)\n{\n    glm::vec2 quantizedFacePosition = glm::vec2(\n            float(quantizedPos1D % quantizationResolution.x),\n            float(quantizedPos1D / quantizationResolution.x))\n                    / float(quantizationResolution.x);\n\n    // Whether the face is the face in x/y/z direction with greater dimensions (offset factor)\n    float face0or1 = float(faceIndex % 2);\n\n    glm::vec3 offset;\n    if (faceIndex <= 1) {\n        offset = glm::vec3(face0or1, quantizedFacePosition.x, quantizedFacePosition.y);\n    } else if (faceIndex <= 3) {\n        offset = glm::vec3(quantizedFacePosition.x, face0or1, quantizedFacePosition.y);\n    } else if (faceIndex <= 5) {\n        offset = glm::vec3(quantizedFacePosition.x, quantizedFacePosition.y, face0or1);\n    }\n    return offset;\n}\n\n\nvoid VoxelCurveDiscretizer::decompressLine(const glm::vec3 &voxelPosition, const LineSegmentCompressed &compressedLine,\n        LineSegment &decompressedLine)\n{\n    const uint32_t c = 2*intlog2(quantizationResolution.x);\n    const uint32_t bitmaskQuantizedPos = quantizationResolution.x*quantizationResolution.x-1;\n    uint32_t faceStartIndex = compressedLine.linePosition & 0x7u;\n    uint32_t faceEndIndex = (compressedLine.linePosition >> 3) & 0x7u;\n    uint32_t quantizedStartPos1D = (compressedLine.linePosition >> 6) & bitmaskQuantizedPos;\n    uint32_t quantizedEndPos1D = (compressedLine.linePosition >> 6+c) & bitmaskQuantizedPos;\n    if (c > 12) {\n        quantizedEndPos1D |= (compressedLine.attributes << (c - (6 + 2*c - 32))) & bitmaskQuantizedPos;\n    }\n    uint32_t lineID = (compressedLine.attributes >> 11) & 31u;\n    uint32_t attr1 = (compressedLine.attributes >> 16) & 0xFFu;\n    uint32_t attr2 = (compressedLine.attributes >> 24) & 0xFFu;\n\n    decompressedLine.v1 = voxelPosition + getQuantizedPositionOffset(faceStartIndex, quantizedStartPos1D);\n    decompressedLine.v2 = voxelPosition + getQuantizedPositionOffset(faceEndIndex, quantizedEndPos1D);\n    decompressedLine.a1 = float(attr1) / 255.0f;\n    decompressedLine.a2 = float(attr2) / 255.0f;\n    decompressedLine.lineID = lineID;\n}\n\nbool VoxelCurveDiscretizer::checkLinesEqual(const LineSegment &originalLine, const LineSegment &decompressedLine)\n{\n    bool linesEqual = true;\n    if (originalLine.lineID % 256 != decompressedLine.lineID) {\n        linesEqual = false;\n        sgl::Logfile::get()->writeError(\"VoxelCurveDiscretizer::checkLinesEqual: lineID\");\n    }\n\n    if (std::abs(originalLine.a1 - decompressedLine.a1) > 0.01f\n            || std::abs(originalLine.a2 - decompressedLine.a2) > 0.01f) {\n        linesEqual = false;\n        sgl::Logfile::get()->writeError(\"VoxelCurveDiscretizer::checkLinesEqual: attribute\");\n    }\n\n    if (glm::length(originalLine.v1 - decompressedLine.v1) > 0.5f) {\n        linesEqual = false;\n        sgl::Logfile::get()->writeError(std::string() + \"VoxelCurveDiscretizer::checkLinesEqual: position2, error: \"\n                + sgl::toString(glm::length(originalLine.v2 - decompressedLine.v2)));\n    }\n\n    if (glm::length(originalLine.v2 - decompressedLine.v2) > 0.5f) {\n        linesEqual = false;\n        sgl::Logfile::get()->writeError(std::string() + \"VoxelCurveDiscretizer::checkLinesEqual: position1, error: \"\n                                        + sgl::toString(glm::length(originalLine.v2 - decompressedLine.v2)));\n    }\n\n    return linesEqual;\n}\n\n\nstruct LinePoint {\n    LinePoint(glm::vec3 linePoint, float lineAttribute) : linePoint(linePoint), lineAttribute(lineAttribute) {}\n    glm::vec3 linePoint;\n    float lineAttribute;\n};\n\nstd::string ivec3ToString(const glm::ivec3 &v) {\n    return std::string() + \"ivec3(\" + sgl::toString(v.x) + \", \" + sgl::toString(v.y) + \", \" + sgl::toString(v.z) + \")\";\n}\n\nvoid VoxelCurveDiscretizer::recreateDensityAndAOFactors(VoxelGridDataCompressed &dataCompressed,\n        VoxelGridDataGPU &dataGPU, unsigned int maxNumLinesPerVoxel)\n{\n    glm::ivec3 numWorkGroupsVoxel = glm::ivec3(sgl::iceil(gridResolution.x, 64), sgl::iceil(gridResolution.y, 4),\n                                               gridResolution.z);\n    uint32_t gridSize1D = gridResolution.x *gridResolution.y *gridResolution.z;\n    uint32_t zeroData = 0u;\n    void *bufferMemory;\n\n    // Set preprocessor defines for the shaders.\n    sgl::ShaderManager->addPreprocessorDefine(\"MAX_NUM_LINES_PER_VOXEL\", maxNumLinesPerVoxel);\n    sgl::ShaderManager->addPreprocessorDefine(\"gridResolution\", ivec3ToString(gridResolution));\n    sgl::ShaderManager->addPreprocessorDefine(\n            \"GRID_RESOLUTION_LOG2\", sgl::toString(sgl::intlog2(gridResolution.x)));\n    sgl::ShaderManager->addPreprocessorDefine(\"GRID_RESOLUTION\", gridResolution.x);\n    sgl::ShaderManager->addPreprocessorDefine(\"quantizationResolution\", ivec3ToString(quantizationResolution));\n    sgl::ShaderManager->addPreprocessorDefine(\"QUANTIZATION_RESOLUTION\", sgl::toString(quantizationResolution.x));\n    sgl::ShaderManager->addPreprocessorDefine(\n            \"QUANTIZATION_RESOLUTION_LOG2\", sgl::toString(sgl::intlog2(quantizationResolution.x)));\n\n\n    // PART 3: Compute the densities\n    auto startDensity = std::chrono::system_clock::now();\n\n    sgl::ShaderProgramPtr computeDensityShader = sgl::ShaderManager->getShaderProgram({\"RecomputeDensity.Compute\"});\n    computeDensityShader->setUniformImageTexture(0, dataGPU.densityTexture, GL_R32F, GL_READ_WRITE, 0, true, 0);\n    computeDensityShader->dispatchCompute(numWorkGroupsVoxel.x, numWorkGroupsVoxel.y, numWorkGroupsVoxel.z);\n    glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);\n\n    auto endDensity = std::chrono::system_clock::now();\n    auto elapsedDensity = std::chrono::duration_cast<std::chrono::milliseconds>(endDensity - startDensity);\n    sgl::Logfile::get()->writeInfo(std::string() + \"Computational time to compute the densities: \"\n                                   + std::to_string(elapsedDensity.count()));\n\n\n    // PART 5: Compute the ambient occlusion factors on the GPU using the density texture.\n    auto startAO_GPU = std::chrono::system_clock::now();\n\n    const int FILTER_SIZE = 7;\n    const int FILTER_EXTENT = (FILTER_SIZE - 1) / 2;\n    const int FILTER_NUM_FIELDS = FILTER_SIZE*FILTER_SIZE*FILTER_SIZE;\n    float blurKernel[FILTER_NUM_FIELDS];\n    generateGaussianBlurKernel(blurKernel, FILTER_SIZE, FILTER_EXTENT);\n    sgl::GeometryBufferPtr gaussianKernelBuffer = sgl::Renderer->createGeometryBuffer(\n            FILTER_NUM_FIELDS * sizeof(float), &blurKernel,\n            sgl::UNIFORM_BUFFER, sgl::BUFFER_STATIC);\n\n    sgl::ShaderProgramPtr computeAOShader = sgl::ShaderManager->getShaderProgram({\"ComputeAO.Compute\"});\n    computeAOShader->setUniformImageTexture(0, dataGPU.densityTexture, GL_R32F, GL_READ_WRITE, 0, true, 0);\n    computeAOShader->setUniform(\"densityTexture\", dataGPU.densityTexture, 0);\n    sgl::ShaderManager->bindShaderStorageBuffer(6, gaussianKernelBuffer);\n    computeAOShader->dispatchCompute(numWorkGroupsVoxel.x, numWorkGroupsVoxel.y, numWorkGroupsVoxel.z);\n    glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);\n\n    auto endAO_GPU = std::chrono::system_clock::now();\n    auto elapsedAO_GPU = std::chrono::duration_cast<std::chrono::milliseconds>(endAO_GPU - startAO_GPU);\n    sgl::Logfile::get()->writeInfo(std::string() + \"Computational time to compute the ambient occlusion factors (GPU): \"\n                                   + std::to_string(elapsedAO_GPU.count()));\n\n    glUseProgram(0); // For ImGui to stop complaining when binding last_program...\n}\n\nVoxelGridDataCompressed VoxelCurveDiscretizer::createVoxelGridGPU(\n        std::vector<Curve> &curves, unsigned int maxNumLinesPerVoxel)\n{\n    glm::ivec3 numWorkGroupsVoxel = glm::ivec3(sgl::iceil(gridResolution.x, 64), sgl::iceil(gridResolution.y, 4),\n            gridResolution.z);\n    uint32_t gridSize1D = gridResolution.x *gridResolution.y *gridResolution.z;\n    uint32_t zeroData = 0u;\n    void *bufferMemory;\n\n\n    // Set preprocessor defines for the shaders.\n    sgl::ShaderManager->addPreprocessorDefine(\"MAX_NUM_LINES_PER_VOXEL\", maxNumLinesPerVoxel);\n    sgl::ShaderManager->addPreprocessorDefine(\"gridResolution\", ivec3ToString(gridResolution));\n    sgl::ShaderManager->addPreprocessorDefine(\n            \"GRID_RESOLUTION_LOG2\", sgl::toString(sgl::intlog2(gridResolution.x)));\n    sgl::ShaderManager->addPreprocessorDefine(\"GRID_RESOLUTION\", gridResolution.x);\n    sgl::ShaderManager->addPreprocessorDefine(\"quantizationResolution\", ivec3ToString(quantizationResolution));\n    sgl::ShaderManager->addPreprocessorDefine(\"QUANTIZATION_RESOLUTION\", sgl::toString(quantizationResolution.x));\n    sgl::ShaderManager->addPreprocessorDefine(\n            \"QUANTIZATION_RESOLUTION_LOG2\", sgl::toString(sgl::intlog2(quantizationResolution.x)));\n    if (isHairDataset) {\n        sgl::ShaderManager->addPreprocessorDefine(\"HAIR_RENDERING\", maxNumLinesPerVoxel);\n    } else {\n        sgl::ShaderManager->removePreprocessorDefine(\"HAIR_RENDERING\");\n    }\n\n    // PART 1: Create the LinePointBuffer, LineOffsetBuffer, NumSegmentsBuffer (empty) and LineSegmentsBuffer.\n    auto startBuffers = std::chrono::system_clock::now();\n    std::vector<LinePoint> linePoints;\n    std::vector<uint32_t> lineOffsets;\n    lineOffsets.push_back(0);\n    uint32_t offsetCounter = 0;\n    for (Curve &curve : curves) {\n        size_t curveNumPoints = curve.points.size();\n        for (size_t i = 0; i < curveNumPoints; i++) {\n            linePoints.push_back(LinePoint(curve.points.at(i), curve.attributes.at(i)));\n        }\n        offsetCounter += curveNumPoints;\n        lineOffsets.push_back(offsetCounter);\n    }\n    sgl::GeometryBufferPtr linePointBuffer = sgl::Renderer->createGeometryBuffer(\n            (linePoints.size()+1) * sizeof(LinePoint), &linePoints.front(),\n            sgl::SHADER_STORAGE_BUFFER, sgl::BUFFER_STATIC);\n    sgl::GeometryBufferPtr lineOffsetBuffer = sgl::Renderer->createGeometryBuffer(\n            (curves.size()+1) * sizeof(uint32_t), &lineOffsets.front(),\n            sgl::SHADER_STORAGE_BUFFER, sgl::BUFFER_STATIC);\n    sgl::GeometryBufferPtr numSegmentsBuffer = sgl::Renderer->createGeometryBuffer(\n            gridSize1D * sizeof(uint32_t),\n            sgl::SHADER_STORAGE_BUFFER, sgl::BUFFER_STATIC);\n    GLuint bufferID = ((sgl::GeometryBufferGL*)numSegmentsBuffer.get())->getBuffer();\n    glClearNamedBufferData(bufferID, GL_R32UI, GL_RED_INTEGER, GL_UNSIGNED_INT, (const void*)&zeroData);\n    sgl::GeometryBufferPtr lineSegmentsBuffer = sgl::Renderer->createGeometryBuffer(\n            maxNumLinesPerVoxel * gridSize1D * sizeof(LineSegmentCompressed),\n            sgl::SHADER_STORAGE_BUFFER, sgl::BUFFER_STATIC);\n\n    auto endBuffers = std::chrono::system_clock::now();\n    auto elapsedBuffers = std::chrono::duration_cast<std::chrono::milliseconds>(endBuffers - startBuffers);\n    sgl::Logfile::get()->writeInfo(std::string() + \"Computational time to create the buffers: \"\n                                   + std::to_string(elapsedBuffers.count()));\n\n\n    // PART 2: Discretize, quantize and voxelize the lines.\n    auto startVoxelize = std::chrono::system_clock::now();\n    unsigned int numWorkGroupsLines = sgl::iceil(curves.size(), 256);\n    sgl::ShaderProgramPtr discretizeLinesShader = sgl::ShaderManager->getShaderProgram({\"DiscretizeLines.Compute\"});\n    sgl::ShaderManager->bindShaderStorageBuffer(2, linePointBuffer);\n    sgl::ShaderManager->bindShaderStorageBuffer(3, lineOffsetBuffer);\n    sgl::ShaderManager->bindShaderStorageBuffer(4, numSegmentsBuffer);\n    sgl::ShaderManager->bindShaderStorageBuffer(5, lineSegmentsBuffer);\n    discretizeLinesShader->setUniform(\"numLines\", (unsigned int)curves.size());\n    discretizeLinesShader->dispatchCompute(numWorkGroupsLines);\n    glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);\n    glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);\n\n    // End of PART 2: Read the line segment buffer & number of line segments per voxel buffer back from the GPU.\n    std::vector<LineSegmentCompressed> compressedLineSegments;\n    bufferMemory = lineSegmentsBuffer->mapBuffer(sgl::BUFFER_MAP_READ_ONLY);\n    compressedLineSegments.resize(maxNumLinesPerVoxel * gridSize1D);\n    memcpy(&compressedLineSegments.front(), bufferMemory, compressedLineSegments.size() * sizeof(LineSegmentCompressed));\n    lineSegmentsBuffer->unmapBuffer();\n\n    std::vector<uint32_t> numSegmentsPerVoxel;\n    bufferMemory = numSegmentsBuffer->mapBuffer(sgl::BUFFER_MAP_READ_ONLY);\n    numSegmentsPerVoxel.resize(gridSize1D);\n    memcpy(&numSegmentsPerVoxel.front(), bufferMemory, numSegmentsPerVoxel.size() * sizeof(uint32_t));\n    numSegmentsBuffer->unmapBuffer();\n\n    auto endVoxelize = std::chrono::system_clock::now();\n    auto elapsedVoxelize = std::chrono::duration_cast<std::chrono::milliseconds>(endVoxelize - startVoxelize);\n    sgl::Logfile::get()->writeInfo(std::string() + \"Computational time to voxelize the lines: \"\n                                   + std::to_string(elapsedVoxelize.count()));\n\n\n    // PART 3: Compute the densities\n    auto startDensity = std::chrono::system_clock::now();\n\n    sgl::TextureSettings densityTextureSettings = sgl::TextureSettings();\n    densityTextureSettings.type = sgl::TEXTURE_3D;\n    densityTextureSettings.internalFormat = GL_R32F;\n    sgl::TexturePtr densityTexture = sgl::TextureManager->createEmptyTexture(\n            gridResolution.x, gridResolution.y, gridResolution.z, densityTextureSettings);\n    sgl::ShaderProgramPtr computeDensityShader = sgl::ShaderManager->getShaderProgram({\"ComputeDensity.Compute\"});\n    computeDensityShader->setUniformImageTexture(0, densityTexture, GL_R32F, GL_READ_WRITE, 0, true, 0);\n    computeDensityShader->dispatchCompute(numWorkGroupsVoxel.x, numWorkGroupsVoxel.y, numWorkGroupsVoxel.z);\n    glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);\n\n    // End of PART 3: Read the density values back from the GPU.\n    std::vector<float> voxelDensities;\n    voxelDensities.resize(gridSize1D);\n    sgl::TextureGL *densityTextureGL = (sgl::TextureGL*)densityTexture.get();\n    glGetTextureImage(densityTextureGL->getTexture(), 0, GL_RED, GL_FLOAT,\n            sizeof(float) * gridSize1D, (void*)&voxelDensities.front());\n\n    auto endDensity = std::chrono::system_clock::now();\n    auto elapsedDensity = std::chrono::duration_cast<std::chrono::milliseconds>(endDensity - startDensity);\n    sgl::Logfile::get()->writeInfo(std::string() + \"Computational time to compute the densities: \"\n                                   + std::to_string(elapsedDensity.count()));\n\n\n    // PART 4: Reduce the size of the buffer using a prefix sum (on the CPU for now).\n    auto startPrefixSum = std::chrono::system_clock::now();\n\n    uint32_t lineSegmentOffset = 0;\n    std::vector<uint32_t> lineSegmentOffsets;\n    std::vector<LineSegmentCompressed> reducedLineSegmentBuffer;\n    for (size_t i = 0; i < numSegmentsPerVoxel.size(); i++) {\n        lineSegmentOffsets.push_back(lineSegmentOffset);\n        size_t numSegmentsCurrentVoxel = numSegmentsPerVoxel.at(i);\n        for (size_t j = 0; j < numSegmentsCurrentVoxel; j++) {\n            reducedLineSegmentBuffer.push_back(compressedLineSegments.at(i*maxNumLinesPerVoxel+j));\n        }\n        lineSegmentOffset += numSegmentsCurrentVoxel;\n    }\n\n    uint32_t offsetTest = lineSegmentOffsets.back();\n    LineSegmentCompressed lineSegmentTest = reducedLineSegmentBuffer.back();\n    std::vector<LineSegmentCompressed> testArray = reducedLineSegmentBuffer;\n    std::reverse(testArray.begin(), testArray.end());\n\n    auto endPrefixSum = std::chrono::system_clock::now();\n    auto elapsedPrefixSum = std::chrono::duration_cast<std::chrono::milliseconds>(endPrefixSum - startPrefixSum);\n    sgl::Logfile::get()->writeInfo(std::string() + \"Computational time to reduce the buffers: \"\n                                   + std::to_string(elapsedPrefixSum.count()));\n\n\n    // PART 5: Compute the ambient occlusion factors. For now, do this on CPU (legacy).\n    /*auto startAO_CPU = std::chrono::system_clock::now();\n\n    std::vector<float> voxelAOFactors;\n    voxelAOFactors.resize(gridSize1D);\n    generateVoxelAOFactorsFromDensity(voxelDensities, voxelAOFactors, gridResolution, isHairDataset);\n\n    auto endAO_CPU = std::chrono::system_clock::now();\n    auto elapsedAO_CPU = std::chrono::duration_cast<std::chrono::milliseconds>(endAO_CPU - startAO_CPU);\n    sgl::Logfile::get()->writeInfo(std::string() + \"Computational time to compute the ambient occlusion factors (CPU): \"\n                                   + std::to_string(elapsedAO_CPU.count()));*/\n\n\n    // PART 5: Compute the ambient occlusion factors on the GPU using the density texture.\n    auto startAO_GPU = std::chrono::system_clock::now();\n    const int FILTER_SIZE = 7;\n    const int FILTER_EXTENT = (FILTER_SIZE - 1) / 2;\n    const int FILTER_NUM_FIELDS = FILTER_SIZE*FILTER_SIZE*FILTER_SIZE;\n    float blurKernel[FILTER_NUM_FIELDS];\n    generateGaussianBlurKernel(blurKernel, FILTER_SIZE, FILTER_EXTENT);\n    sgl::GeometryBufferPtr gaussianKernelBuffer = sgl::Renderer->createGeometryBuffer(\n            FILTER_NUM_FIELDS * sizeof(float), &blurKernel,\n            sgl::SHADER_STORAGE_BUFFER, sgl::BUFFER_STATIC);\n\n    sgl::TextureSettings aoTextureSettings = sgl::TextureSettings();\n    aoTextureSettings.type = sgl::TEXTURE_3D;\n    aoTextureSettings.internalFormat = GL_R32F;\n    sgl::TexturePtr aoTexture = sgl::TextureManager->createEmptyTexture(\n            gridResolution.x, gridResolution.y, gridResolution.z, aoTextureSettings);\n    sgl::ShaderProgramPtr computeAOShader = sgl::ShaderManager->getShaderProgram({\"ComputeAO.Compute\"});\n    computeAOShader->setUniformImageTexture(0, aoTexture, GL_R32F, GL_READ_WRITE, 0, true, 0);\n    computeAOShader->setUniform(\"densityTexture\", densityTexture, 0);\n    sgl::ShaderManager->bindShaderStorageBuffer(6, gaussianKernelBuffer);\n    computeAOShader->dispatchCompute(numWorkGroupsVoxel.x, numWorkGroupsVoxel.y, numWorkGroupsVoxel.z);\n    glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);\n\n    // End of PART 5: Read the AO factors back from the GPU.\n    std::vector<float> voxelAOFactors;\n    voxelAOFactors.resize(gridSize1D);\n    sgl::TextureGL *aoTextureGL = (sgl::TextureGL*)aoTexture.get();\n    glGetTextureImage(aoTextureGL->getTexture(), 0, GL_RED, GL_FLOAT,\n                      sizeof(float) * gridSize1D, (void*)&voxelAOFactors.front());\n    normalizeVoxelAOFactors(voxelAOFactors, gridResolution, isHairDataset);\n\n    auto endAO_GPU = std::chrono::system_clock::now();\n    auto elapsedAO_GPU = std::chrono::duration_cast<std::chrono::milliseconds>(endAO_GPU - startAO_GPU);\n    sgl::Logfile::get()->writeInfo(std::string() + \"Computational time to compute the ambient occlusion factors (GPU): \"\n                                   + std::to_string(elapsedAO_GPU.count()));\n\n\n    glUseProgram(0); // For ImGui to stop complaining when binding last_program...\n\n    // FINAL STEP: Now, write the data to the struct.\n    VoxelGridDataCompressed dataCompressed;\n    dataCompressed.gridResolution = gridResolution;\n    dataCompressed.quantizationResolution = quantizationResolution;\n    dataCompressed.worldToVoxelGridMatrix = this->getWorldToVoxelGridMatrix();\n    dataCompressed.dataType = isHairDataset ? 1u : 0u;\n\n    if (isHairDataset) {\n        dataCompressed.hairStrandColor = hairStrandColor;\n        dataCompressed.hairThickness = hairThickness;\n    } else {\n        dataCompressed.attributes = attributes;\n        dataCompressed.maxVorticity = maxVorticity;\n    }\n\n    dataCompressed.voxelLineListOffsets = lineSegmentOffsets;\n    dataCompressed.numLinesInVoxel = numSegmentsPerVoxel;\n    dataCompressed.lineSegments = reducedLineSegmentBuffer;\n\n    dataCompressed.voxelDensities = voxelDensities;\n    dataCompressed.voxelAOFactors = voxelAOFactors;\n    return dataCompressed;\n}", "meta": {"hexsha": "8ab84703fdf2c9b4bcb8c324b6038bd579c10a32", "size": 40652, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/VoxelRaytracing/VoxelCurveDiscretizer.cpp", "max_stars_repo_name": "chrismile/PixelSyncOIT", "max_stars_repo_head_hexsha": "a90353c5a19f911fc470f065cdc91b7b41299c43", "max_stars_repo_licenses": ["Apache-2.0", "BSD-2-Clause"], "max_stars_count": 44.0, "max_stars_repo_stars_event_min_datetime": "2019-01-15T09:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T08:37:22.000Z", "max_issues_repo_path": "src/VoxelRaytracing/VoxelCurveDiscretizer.cpp", "max_issues_repo_name": "chrismile/PixelSyncOIT", "max_issues_repo_head_hexsha": "a90353c5a19f911fc470f065cdc91b7b41299c43", "max_issues_repo_licenses": ["Apache-2.0", "BSD-2-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-07-25T11:17:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-06T09:51:39.000Z", "max_forks_repo_path": "src/VoxelRaytracing/VoxelCurveDiscretizer.cpp", "max_forks_repo_name": "chrismile/PixelSyncOIT", "max_forks_repo_head_hexsha": "a90353c5a19f911fc470f065cdc91b7b41299c43", "max_forks_repo_licenses": ["Apache-2.0", "BSD-2-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2020-04-13T10:02:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T09:34:23.000Z", "avg_line_length": 41.8661174047, "max_line_length": 121, "alphanum_fraction": 0.6762274919, "num_tokens": 10628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.263482513122497}}
{"text": "// This is an independent project of an individual developer. Dear PVS-Studio, please check it.\n// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com\n\n/** \n * File:   PnlAction.cpp\n * Author: kan\n * \n * Created on 2015.11.11\n * @lastupdate 2018.05.18\n */\n\n#include <map>\n#include <list>\n#include <vector>\n#include <set>\n#include <cassert>\n#include <cmath>\n#include <algorithm>\n#include <cassert>\n#include <numeric>\n#include <climits>\n#include <stdlib.h>     /* srand, rand */\n#include <time.h>       /* time */\n#include <boost/math/distributions/students_t.hpp>\n\n#include \"DelphisRound.h\"\n#include \"Comparers.h\"\n\n//#define FULLDATA\n#ifdef FULLDATA\n    #include <iostream>\n    #include \"Indicators.h\"\n#endif\n\n#include \"PnlAction.h\"\n\n//------------------------------------------------------------------------------------------\nTPriceSeries DealsToPnLs( const TDeals & aDeals ) {\n    \n    //<editor-fold desc=\"Удалить все пустые сделки\">\n    TDeals lDeals( aDeals );\n    auto it = lDeals.begin();\n    while( it != lDeals.end() ) {\n        if( isZero( it->ClosePrice - it->OpenPrice ) ) {\n            it = lDeals.erase( it );\n        } else {\n            ++it;\n        }\n    }\n    //</editor-fold>\n    \n    TPriceSeries lPnLs; //( lDeals.size() );\n    lPnLs.reserve(lDeals.size());\n\n    //<editor-fold desc=\"Собственно конвертация\">\n    for( const TDeal& lDeal : lDeals ) {\n        lPnLs.emplace_back(\n            lDeal.CloseTime,\n            ( (lDeal.DealSide == TDealSide::Buy) ? (lDeal.ClosePrice - lDeal.OpenPrice) : (lDeal.OpenPrice - lDeal.ClosePrice) ),\n            ToDouble( lDeal.Volume )\n        );\n    }\n    //</editor-fold>\n\n    return lPnLs;\n}\n\n//------------------------------------------------------------------------------------------\nbool CalcDrawDown(\n    const TPriceSeries & aPnL,\n    TPrice & aoMaxDD,\n    TInnerDate & aoBegin,\n    TInnerDate & aoReturn ) {\n\n    aoBegin = -1;\n    aoReturn = -1;\n\n    if( aPnL.empty() ) {\n        aoMaxDD = -1;\n        return false;\n    }\n\n    TPrice lMax = 0.0;\n    TPrice lMin = 0.0;\n    TPrice lPnl = 0.0;\n    TPrice lDelta = 0.0;\n    size_t lBegin = 0;\n    bool lHaveMin = false;\n    bool lResult = false;\n\n    for( size_t i = 0; i < aPnL.size() ; ++i ) {\n        lPnl += aPnL[i].Price;\n\n        if( IsGreat( lPnl, lMax ) ) { //очередной максимум\n            lMax = lPnl;\n            lMin = lPnl;\n\n            if( lHaveMin ) {\n                    aoBegin = aPnL[ lBegin ].DateTime;\n                    aoReturn = aPnL[ i ].DateTime;\n                    lHaveMin = false;\n                    lResult = true;\n            }\n\n            lBegin = i;\n\n        } else if( IsGreat( lMin, lPnl ) ) { //новый минимум\n            lMin = lPnl;\n\n            if( IsGreat( lMax - lMin, lDelta ) ) {\n                lDelta = lMax - lMin;\n                lHaveMin = true;\n            }\n        }\n    }\n\n    aoMaxDD = lDelta;\n\n    return lResult;\n}\n\n//------------------------------------------------------------------------------------------\nTPriceSeries ReductionOfTheIncome(\n    const TPriceSeries & aPnL,\n    const size_t aProfitNum,\n    const double aProfitCoef,\n    const size_t aLossNum,\n    const double aLossCoef ) {\n\n    std::multimap< TPrice, size_t > lProfits;\n    for( size_t i = 0; i < aPnL.size(); ++i ) {\n\n        TPrice lValue = aPnL[ i ].Price ;\n        //lProfits.insert( std::pair< TPrice, size_t >( lValue, i ) ) ;\n        lProfits.emplace( lValue, i ) ;\n    }\n\n    TPriceSeries lPnLVector( aPnL );\n    size_t i = aProfitNum;\n    for( auto it = lProfits.rbegin(); it != lProfits.rend(); ++it ) {\n        if( it->first > 0 ) {\n            const size_t lRealID = it->second ;\n            TSimpleTick lTick = aPnL[ lRealID ] ;\n            lTick.Price  /= aProfitCoef ;\n            lPnLVector[ lRealID ] = lTick;\n        }\n        if( --i == 0 ) break;\n    }\n\n    i = aLossNum;\n    for( auto it = lProfits.begin(); it != lProfits.end() ;++it ) {\n        if( it->first < 0 ) {\n            const size_t lRealID = it->second ;\n            TSimpleTick lTick = aPnL[ lRealID ] ;\n            lTick.Price  *= aLossCoef ;\n            lPnLVector[ lRealID ] = lTick;\n        }\n        if( --i == 0 ) break;\n    }\n\n    return lPnLVector;\n}\n\n//------------------------------------------------------------------------------------------\nTPrice PnLsToMoneyResult( const TPriceSeries & aPnls, const bool aUseVolume ) {\n    TPrice lResult = 0.0;\n    for( const TSimpleTick& lPnl : aPnls ) {\n        lResult += lPnl.Price * ( aUseVolume ? lPnl.Volume : 1.0 );\n    }\n    \n    return lResult;\n}\n\n//------------------------------------------------------------------------------------------\ndouble Student_t_value( const size_t Sn, const double tail=0.2 ){//80%\n    using boost::math::students_t;\n    students_t dist( ToDouble(Sn) - 1 );\n    const double T = quantile(complement(dist, tail / 2.0));\n    \n    return T;\n}\n\n//------------------------------------------------------------------------------------------\nTPrice PnLsToMoneyStatValue( const TPriceSeries & aPnl, const bool aUseVolume, const size_t N, const double aQuantile ) {\n    const size_t lSize = aPnl.size();\n    if( lSize < 2 or N < 2 ) {\n        return 0.0;\n    }\n    \n    std::vector< TPrice > lPnl( lSize );\n    TPrice sum = 0.0;\n    for( size_t i=0; i<lSize; ++i ){\n        const TPrice lValue = aPnl[i].Price * ( aUseVolume ? aPnl[i].Volume : 1.0 );\n        sum += lValue;\n        lPnl[i] = lValue;\n    }\n    \n    const TPrice mean = sum / ToDouble(lSize);\n    \n    TPrice lstdev = 0.0;\n    for( size_t i=0; i<lSize; ++i ){\n        lstdev += pow(lPnl[i] - mean, 2);\n    }\n    \n    lstdev /= ToDouble(lSize);\n    \n    const double lStudAN = Student_t_value( lSize, aQuantile ) / sqrt( ToDouble(N) );\n\n    return (mean - sqrt(lstdev)*lStudAN)*ToDouble(N);\n}\n\n//------------------------------------------------------------------------------------------\nTPrice PnLsToMoneyStatValueGost( const TPriceSeries & aPnl, const bool aUseVolume, const size_t N ) {\n    const size_t lSize = aPnl.size();\n    if( lSize < 2 ) {\n        return 0.0;\n    }\n    \n    std::vector< TPrice > lPnl( lSize );\n    TPrice sum = 0.0;\n    for( size_t i=0; i<lSize; ++i ){\n        const TPrice lValue = aPnl[i].Price * ( aUseVolume ? aPnl[i].Volume : 1.0 );\n        sum += lValue;\n        lPnl[i] = lValue;\n    }\n    \n    const TPrice mean = sum / ToDouble(lSize);\n    \n    TPrice lstdev = 0.0;\n    for( size_t i=0; i<lSize; ++i ){\n        lstdev += pow(lPnl[i] - mean, 2);\n    }\n    \n    lstdev /= (ToDouble(lSize) - 1.5);//ГОСТ Р 8.736-2011\n    \n    return ( mean - sqrt( lstdev ) / sqrt( ToDouble(lSize) ) )*ToDouble(N);\n}\n\n//------------------------------------------------------------------------------------------\nTPrice PnLsToMoneyMonteCarlo( const TPriceSeries & aPnl, const bool aUseVolume, const size_t N, const size_t aSamples ){\n    const size_t lSize = aPnl.size();\n    if( lSize < 2 or N < 2 ) {\n        return 0.0;\n    }\n    \n    TPrice lResult = ToDouble( ULLONG_MAX ); //очень большое число\n    \n    for( size_t i=0; i<aSamples; ++i ){\n        TPrice lPnlTest = 0.0;\n        for( size_t j=0; j<N; ++j ){\n            const size_t lID = rand() % lSize;\n            const TPrice lPnlSample = aPnl[lID].Price * (aUseVolume ? aPnl[lID].Volume : 1.0);\n            lPnlTest += lPnlSample;\n        }\n        lPnlTest /= ToDouble(N);\n        \n        lResult = std::min(lResult, lPnlTest);\n    }\n    \n    return lResult * ToDouble(N);\n}\n\n//------------------------------------------------------------------------------------------\nTPrice PnLsToMoneyMonteCarloQuantile( const TPriceSeries & aPnl, const bool aUseVolume, const size_t N, const size_t aSamples, const double aQuantile ) {\n    const size_t lSize = aPnl.size();\n    if( lSize < 2 or N < 2 or IsGreat( aQuantile, 1.0 ) ) {\n        return 0.0;\n    }\n    \n    std::multiset<TPrice> lData;\n    \n    for( size_t i=0; i<aSamples; ++i ){\n        TPrice lPnlTest = 0.0;\n        for( size_t j=0; j<N; ++j ){\n            const size_t lID = rand() % lSize;\n            const TPrice lPnlSample = aPnl[lID].Price * (aUseVolume ? aPnl[lID].Volume : 1.0);\n            lPnlTest += lPnlSample;\n        }\n        lPnlTest /= ToDouble(N);\n        \n        lData.insert( lPnlTest );\n    }\n    \n    const size_t lID = RoundToSize_t( aQuantile * ToDouble( aSamples ) );\n    \n    auto iter = lData.cbegin();\n    std::advance(iter, lID);\n    \n    const TPrice lResult = *iter;\n    \n    return lResult * ToDouble(N);    \n}\n\n//------------------------------------------------------------------------------------------\nTPrice DealsToPNLCoefficientQuick(\n    const TDeals & aDeals,\n    const TPrice aFirstPrice,\n    const size_t aMinDeals ) {\n    \n    TPriceSeries lPnL( DealsToPnLs( aDeals ) );\n    if( lPnL.size() <= aMinDeals ) {\n        return gMaxBedAttraction;\n    }\n\n    TPrice lMaxDD = -1;\n    TInnerDate lBegin;\n    TInnerDate lReturn;\n\n    bool lDDOk = CalcDrawDown( lPnL, lMaxDD, lBegin, lReturn );\n    bool lGoodResult = lDDOk or ( isZero( lMaxDD ) );\n\n    if( not lGoodResult ) { return gMaxBedAttraction; }\n\n    const size_t lDealsToReduction = std::max( std::min( aMinDeals / 2, 3UL ), 1UL );\n    const double lReductionCoeff = 2.0;\n    const TPriceSeries lPnLPes( ReductionOfTheIncome( lPnL, lDealsToReduction, lReductionCoeff, lDealsToReduction, lReductionCoeff ) );\n    const TPrice lPnlMoneyReduction = PnLsToMoneyResult( lPnLPes );\n    \n    const TPrice lPnlMoney = PnLsToMoneyResult( lPnL );\n    const TPrice lResult =  lPnlMoneyReduction / ( lMaxDD + std::abs( lPnlMoney ) );\n//    TPrice lResult =  lPnlMoney / ( lMaxDD + std::abs( lPnlMoney ) );\n//    TPrice lResult =  lPnlMoney / ( lMaxDD + 1 );\n    \n    return lResult ;\n}\n\n//------------------------------------------------------------------------------------------\nTPrice DealsToPNLCoefficient(\n    const TDeals & aDeals,\n    const TInnerDate aFirstPoint,\n    const TInnerDate aLastPoint,\n    const TPrice aMinPnl,\n    const size_t aMinDeals,\n    const size_t aQuantTime ) {\n\n    if( aDeals.size() < aMinDeals ) {\n        return gMaxBedAttraction;\n    }\n\n    //region перевести список сделок в список d_pnl\n    TPrice lResult = gMaxBedAttraction ;\n    TPrice lPnLValue = 0.0;\n    //TInnerDate lPnLTime = 0.0;\n    std::list< TSimpleTick > lPnLs;\n    lPnLs.push_back( {aFirstPoint, 0.0, 0} );\n\n    for( const auto &lDeal : aDeals ) {\n        TInnerDate lEmptyDate = lDeal.OpenTime;\n        TSimpleTick lEmptyTick = { lEmptyDate, 0.0, 0 };\n        lPnLs.push_back( lEmptyTick );\n\n        TInnerDate lBeginDate = lDeal.CloseTime;\n\n        const TPrice lDealPnl =\n            (lDeal.DealSide == TDealSide::Buy) ?\n                (lDeal.ClosePrice - lDeal.OpenPrice) :\n                (lDeal.OpenPrice - lDeal.ClosePrice);\n        \n        TSimpleTick lRealTick = { lBeginDate, lDealPnl, 1 };\n        lPnLs.push_back( lRealTick );\n\n        lPnLValue += lDealPnl;\n        //lPnLTime += ( lDeal.CloseTime - lDeal.OpenTime );\n    }\n\n    lPnLs.push_back( {aLastPoint, 0.0, 0} );\n    //endregion\n\n    // рассчитать общий pnl, учесть aMinPnl\n    if( lPnLValue <= aMinPnl ) {\n        return gMaxBedAttraction;\n    }\n\n    //region  рассчитать ср. и макс. d_pnl, число сделок\n    const size_t lWeekCouner = CeilToSize_t( ( aLastPoint - aFirstPoint ) / static_cast< double >( aQuantTime ) );\n    std::vector< TPrice > lQuantPnL( lWeekCouner );\n    size_t lIdx=0;\n    TInnerDate lNextDate = aFirstPoint + static_cast<TInnerDate>( aQuantTime );\n\n    std::list< TSimpleTick > lPnLsToQuanting( lPnLs );\n    while( not lPnLsToQuanting.empty() ) {\n        auto lTick = lPnLsToQuanting.front();\n        lPnLsToQuanting.pop_front();\n\n        if( lTick.DateTime > lNextDate ) {\n            lNextDate += static_cast<TInnerDate>( aQuantTime );\n            lIdx++;\n        }\n        lQuantPnL[ lIdx ] += lTick.Price;\n    }\n\n    TPrice lMaxPnl = 0.0; //если lPnLValue>0 значит точно есть положительный pnl за интервал\n    TPrice lMidPnl = 0.0;\n    size_t lDealCounter = 0 ;\n    for( const auto ldPnl : lQuantPnL ) {\n        if( ldPnl > lMaxPnl ){ lMaxPnl = ldPnl; }\n\n        lMidPnl += ldPnl ;\n        lDealCounter++ ;\n    }\n    //endregion\n\n    // ... рассчитать разброс pnl,\n    TPrice lPnLValatility = ( lMidPnl / ToDouble( lDealCounter ) ) / lMaxPnl;\n\n    //region расчитать d_DD, учесть DD==0\n    TInnerDate lDD_begin ;\n    TPrice lCurrDD = 0.0;\n    TPrice lSumCurrDD = 0.0;\n    TInnerDate lPrioreDate = aFirstPoint ;\n    for( const auto& lTick : lPnLs ) {\n\n        if( isZero( lCurrDD ) and lTick.Price < 0.0 ) {\n\n            lCurrDD = lTick.Price;\n            lDD_begin = lPrioreDate ;\n\n            lSumCurrDD += lCurrDD * ( lTick.DateTime - lDD_begin ) ;// 86400.0;\n\n        } else if( lCurrDD < 0.0 ) {\n            TPrice lPriorDD = lCurrDD;\n            lCurrDD += lTick.Price;\n\n            if( lCurrDD > 0.0 ) {\n                lCurrDD = 0.0;\n\n            } else {\n                lPriorDD = lCurrDD;\n            }\n\n            lSumCurrDD += lPriorDD * ( lTick.DateTime - lPrioreDate ) ;// 86400.0;\n        }\n\n        lPrioreDate = lTick.DateTime ;\n    }\n    //endregion\n\n    if( isPositiveValue( lSumCurrDD ) ) {\n        return gMaxBedAttraction;\n    }\n\n    // ... рассчитать ср.DD\n    const TPrice lTW_DD = -lSumCurrDD / ( aLastPoint - aFirstPoint );\n\n    // Расчитать коэффициент            Это среднеинтервальный заработок\n    lResult = lPnLValatility / ( lTW_DD + 1.0 ) * lMidPnl /  ToDouble( lDealCounter ) ; //lPnLValue / lPnLTime ;\n\n    return lResult ;\n}\n\n//------------------------------------------------------------------------------------------\nTPrice DealsToCoeff(\n    const TBarSeries & aBars,\n    const TDeals & aDeals,\n    const size_t aMinDeals,\n    TPrice & aoPnl,\n    TPrice & aoMaxDD,\n    size_t & aoMaxPos,\n    size_t & aoMeadPos ) {\n    #ifdef FULLDATA\n        std::cout << \"aDeals.size() = \" << aDeals.size() << std::endl;\n    #endif\n    \n    if( aDeals.size() <= aMinDeals ) {\n        aoPnl = GetBadPrice(); \n        aoMaxDD = GetBadPrice();\n        aoMaxPos = 0; \n        aoMeadPos = 0;\n        return gMaxBedAttraction;\n    }\n    \n    TPriceSeries lBalance( aBars.size() );\n    \n    for( size_t i=0; i<aBars.size(); ++i ){\n        lBalance[i]={aBars[i].DateTime,0.0,0.0};\n    }\n    \n    auto lTickCompare = []( const TSimpleTick& aLeft, const TSimpleTick& aRigth )->bool {\n        return aLeft.DateTime < aRigth.DateTime;\n    };\n    \n    #ifdef FULLDATA\n        std::cout << \"\\nDeals\" << std::endl;\n    #endif\n    \n    for( auto it=aDeals.begin(); it!=aDeals.end(); ++it ) {\n        \n        const TInnerDate lOpenTime = it->OpenTime;\n        const TInnerDate lCloseTime = it->CloseTime;\n        const TPrice lOpenPrice = it->OpenPrice;\n        const TPrice lClosePrice = it->ClosePrice;\n        \n        auto itBegin = std::lower_bound ( \n            lBalance.begin(), \n            lBalance.end(),\n            TSimpleTick{ lOpenTime,0.0,0.0 },\n            lTickCompare \n        );\n        assert( itBegin != lBalance.end() );\n        \n        auto itEnd = std::upper_bound( \n            itBegin, \n            lBalance.end(),\n            TSimpleTick{ lCloseTime,0.0,0.0 },\n            lTickCompare \n        );\n        \n        TPrice lBalanceVolume = 0.0;\n            \n        if( it->DealSide == TDealSide::Buy ) {\n            for( auto itBalance=itBegin; itBalance != std::prev( itEnd ) ; ++itBalance ){\n                itBalance->Volume += 1.0;\n                itBalance->Price -= lOpenPrice;\n            }\n            lBalanceVolume = lClosePrice - lOpenPrice ;\n        \n        } else {\n            for( auto itBalance=itBegin; itBalance != std::prev( itEnd ) ; ++itBalance ) {\n                itBalance->Volume -= 1.0;\n                itBalance->Price += lOpenPrice;\n            }\n            lBalanceVolume = lOpenPrice - lClosePrice;\n        }\n        \n        for( auto itBalance=std::prev( itEnd ); itBalance != lBalance.end(); ++itBalance ) {\n            itBalance->Price += lBalanceVolume;\n        }\n    }\n    \n    if( not isZero( lBalance.rbegin()->Volume ) ) { ///\\todo вообще-то нужно учесть сторону для каждой конкретной сделки\n        const TPrice lClosePrice = aBars.rbegin()->Close;\n        const TPrice lBalancedSide = ( aDeals.rbegin()->DealSide == TDealSide::Buy ) ? 1.0 : -1.0;\n        lBalance.rbegin()->Price += lBalancedSide * lBalance.rbegin()->Volume * lClosePrice;\n        lBalance.rbegin()->Volume = 0;\n    }\n    \n    TPrice lMax = 0.0;\n    TPrice lMin = 0.0;\n    aoPnl = 0.0;\n    aoMaxDD = 0.0;\n    \n    #ifdef FULLDATA\n    std::cout << \"\\nDD\" << std::endl;\n    #endif\n    \n    std::vector< size_t > lPosition( aBars.size(), 0 );\n    \n    for( size_t i=0; i<aBars.size(); ++i ) {\n        lPosition[ i ] = ToSize_t( std::fabs( lBalance[i].Volume ) );\n        aoPnl = lBalance[i].Price + aBars[i].Close * lBalance[i].Volume;\n        \n        if( IsGreat( aoPnl, lMax ) ) { //очередной максимум\n            lMax = aoPnl;\n            lMin = aoPnl;\n\n        } else if( IsGreat( lMin, aoPnl ) ) { //новый минимум\n            lMin = aoPnl;\n            const TPrice lCurrentDD = lMax - lMin;\n            if( IsGreat( lCurrentDD, aoMaxDD ) ) {\n                aoMaxDD = lCurrentDD;\n            }\n        }\n        #ifdef FULLDATA\n        std::cout << RoundToSize_t( aBars[i].DateTime ) << \" \" << aBars[i].Close << \" \" << lBalance[i].Volume << \" \" << aoPnl << \" \" << lMax << \" \" << lMin << \" \" << aoMaxDD << std::endl;\n        #endif\n    }\n    \n    std::sort( lPosition.begin(), lPosition.end() );\n    aoMaxPos = *lPosition.rbegin();\n    aoMeadPos = lPosition[ lPosition.size() / 2 ];\n\n    const TPrice lResult = isZero( std::abs( aoPnl ) + aoMaxDD ) ? gMaxBedAttraction : (aoPnl / ( std::abs( aoPnl ) + aoMaxDD )) ;\n    #ifdef FULLDATA\n    std::cout << \"lResult = \" << lResult << std::endl;\n    #endif\n    \n    return lResult;\n}\n\n//------------------------------------------------------------------------------------------\nTDoubles ToDoublesArray( const TPriceSeries & aPriceSeries ) {\n    const size_t lArraySize = aPriceSeries.size();\n    TDoubles lResult( lArraySize );\n    \n    for( size_t i=0; i<lArraySize; ++i ) {\n        lResult[i]=aPriceSeries[i].Price;\n    }\n    \n    return lResult;\n}\n\n//------------------------------------------------------------------------------------------\nTPriceSeries PnlsToDaily( const TPriceSeries & aPnls ) {\n    \n    if( aPnls.empty() ) {\n        return TPriceSeries();\n    }\n    TInnerDate lMinDate = gMaxInteger;\n    TInnerDate lMaxDate = 0;\n    \n    for( const auto &lDeal : aPnls ) {\n        const TInnerDate lDealDate = Trunc( lDeal.DateTime / gOneDay );\n        lMinDate = IsLess( lMinDate, lDealDate ) ? lMinDate : lDealDate;\n        lMaxDate = IsGreat( lMaxDate, lDealDate ) ? lMaxDate : lDealDate;\n    }\n    \n    TPriceSeries lResult( ToSize_t( lMaxDate-lMinDate+1 ) );\n    for( const auto &lDeal : aPnls ) {\n        const size_t lDealDate = ToSize_t( Trunc( lDeal.DateTime / gOneDay ) - lMinDate );\n        const TPrice lDealPnl = lDeal.Price * ((lDeal.Volume == 0) ? 1.0 : lDeal.Volume );\n        \n        TSimpleTick lDayDeal = lResult[ lDealDate ];\n        lDayDeal.DateTime = ToDouble( Trunc( lDeal.DateTime / gOneDay ) * gOneDay );\n        lDayDeal.Price += lDealPnl;\n        lDayDeal.Volume += 1.0;\n        \n        lResult[ lDealDate ] = lDayDeal;\n    }\n    \n    for( size_t i = 1; i < lResult.size(); ++i ){\n        lResult[i].Price += lResult[i-1].Price;\n    }\n    \n    return lResult;\n}\n\n//------------------------------------------------------------------------------------------\nbool IsGrows( const TPriceSeries & aDailyPnls, const size_t aPeriod, const size_t aTollerance ) {\n    if( aPeriod == 0 ){\n        throw std::logic_error( \"aPeriod can be positive\" );\n    }\n    \n    if( aDailyPnls.size() <= aPeriod ) {\n        return false;\n    }\n    \n    size_t lTollerance = ( aTollerance == 0 ) ? 1 : aTollerance;\n    \n    for( size_t i=0; i < aDailyPnls.size() - aPeriod; ++i ) {\n        if( IsGreat( aDailyPnls[i].Price, aDailyPnls[ i+aPeriod ].Price ) ) {\n            if( --lTollerance == 0 ) {\n                return false;\n            }\n        }\n    }\n    \n    return true;\n}\n\n//------------------------------------------------------------------------------------------\nTPriceSeries PnLsAmplifier( const TPriceSeries &aPnl, const std::vector<double> &aAmplifiers, const TInnerDate aBegin, const TInnerDate aEnd ) {\n    \n    if( aAmplifiers.size() < 2UL ){\n        return aPnl;\n    }\n    \n    //sort deals\n    TPriceSeries lPnls( aPnl );\n    std::sort( lPnls.begin(), lPnls.end(),\n        []( const TSimpleTick& lh, const TSimpleTick& rh ){\n            return IsLess( lh.DateTime, rh.DateTime );\n        }\n    );\n    \n    //days range detect\n    const TInnerDate lMinDate =  trunc( (isPositiveValue( aBegin ) ? aBegin : lPnls.begin()->DateTime) / gOneDay );\n    const TInnerDate lMaxDate =  trunc( (isPositiveValue( aEnd ) ? aEnd : lPnls.rbegin()->DateTime) / gOneDay );\n    \n    if( CeilToSize_t(lMaxDate-lMinDate) < aAmplifiers.size() ){\n        return aPnl;\n    }\n    \n    const double lMinDelta = trunc( (lMaxDate-lMinDate) / ToDouble( aAmplifiers.size() ) );\n    if( IsLess( lMinDelta, 1.0 ) ){\n        return aPnl;\n    }\n    \n    std::vector<TInnerDate> ldates( aAmplifiers.size() );\n    for( size_t i=0; i<aAmplifiers.size(); ++i ) {\n        ldates[i] = lMinDate + lMinDelta * ToDouble(i+1) ;\n    }\n    \n    TPriceSeries lPnls_result;\n    lPnls_result.reserve( ToSize_t(*aAmplifiers.rbegin()) * aPnl.size() );\n    for( auto it = lPnls.begin(); it != lPnls.end(); ++it ){\n        const TSimpleTick lTick( *it );\n        \n        for( size_t i=0; i < ldates.size(); ++i ){\n            if( not IsGreat( trunc(lTick.DateTime / gOneDay), ldates[i] ) ){\n                for( size_t j=0; j < ToSize_t(aAmplifiers[i]); ++j ){\n                    lPnls_result.push_back( lTick );\n                }\n                break;\n            }\n        }\n    }\n    \n    lPnls_result.shrink_to_fit();\n    return lPnls_result;\n}\n\n//------------------------------------------------------------------------------------------\n", "meta": {"hexsha": "be0d3c9784d7f2044ce1dd88633fefbd2a0a5d40", "size": 22018, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PnlAction.cpp", "max_stars_repo_name": "kansoftware/TradingBasics", "max_stars_repo_head_hexsha": "f49bf6c3fa9103b97745d3bf4ce838bf27f817fe", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-11-26T15:41:03.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-26T15:41:03.000Z", "max_issues_repo_path": "src/PnlAction.cpp", "max_issues_repo_name": "kansoftware/TradingBasics", "max_issues_repo_head_hexsha": "f49bf6c3fa9103b97745d3bf4ce838bf27f817fe", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-15T14:53:50.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-15T14:53:50.000Z", "max_forks_repo_path": "src/PnlAction.cpp", "max_forks_repo_name": "kansoftware/TradingBasics", "max_forks_repo_head_hexsha": "f49bf6c3fa9103b97745d3bf4ce838bf27f817fe", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-09-15T08:05:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-15T17:29:14.000Z", "avg_line_length": 31.320056899, "max_line_length": 187, "alphanum_fraction": 0.5266600055, "num_tokens": 6610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.26336909801285907}}
{"text": "#include <iostream>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/timer.hpp>\n\n\n#include <vector>\n#include <math.h>\n\n// extern \"C\"{\n//   #include <cblas.h>\n// }\n\n#define INVALID -1\n\n\n#include \"NRGclasses.hpp\"\n#include \"NRGfunctions.hpp\"\n\nvoid UpdateMatrices_uBLAS(CNRGbasisarray* pSingleSite,\n\t\t\t  CNRGbasisarray* pAeigCut, \n\t\t\t  CNRGbasisarray* pAbasis,\n\t\t\t  CNRGmatrix* NRGMats, int NumNRGMats, bool display){\n\n  // Boost matrices\n  boost::numeric::ublas::matrix<double> Zibl;\n  boost::numeric::ublas::matrix<double> Zjbl;\n  boost::numeric::ublas::matrix<double> fnbasis;\n\n\n  boost::numeric::ublas::matrix<complex<double> > cZibl;\n  boost::numeric::ublas::matrix<complex<double> > cZjbl;\n  boost::numeric::ublas::matrix<complex<double> > cfnbasis;\n\n\n  boost::numeric::ublas::matrix<double> fnw;\n  boost::numeric::ublas::matrix<complex<double> > cfnw;\n\n  // Check that eigenvectors are properly normalized!\n\n  boost::numeric::ublas::matrix<complex<double> > cOneTest;\n\n\n  // Check time\n  boost::timer t;\n  double time_elapsed;\n\n  boost::timer t2;\n  double time_lap2;\n\n  \n  CNRGmatrix* MatOLD = new CNRGmatrix [NumNRGMats];\n\n  //Clear all\n  for (int imats=0;imats<NumNRGMats;imats++){\n    if (NRGMats[imats].NeedOld) MatOLD[imats]=NRGMats[imats];\n    NRGMats[imats].ClearAll();\n    NRGMats[imats].SyncNRGarray(*pAeigCut);\n  }\n  // end for\n\n  // Note: assumes  Abasis and Aeig have \n  // EXACTLY the same block structure... should check.\n\n  // Loop over blocks (icount counts for each matrix)\n  int icount[NumNRGMats];\n  for (int ii=0;ii<NumNRGMats;ii++) icount[ii]=0;\n\n  t2.restart();\n  time_lap2=0.0;\n  // Note Aeig can be a \"cut\" array\n  for (int ibl=0;ibl<pAeigCut->NumBlocks();ibl++){\n    int Nstibl=pAeigCut->GetBlockSize(ibl);\n\n    cout << \"Block i : \" << ibl << \"/\" << pAeigCut->NumBlocks()-1\n\t << \" (sz=\" <<  Nstibl << \") Nshell=\" << pAeigCut->Nshell << endl;\n    // Corresponding block size in pAbasis\n    int iblBC=FindMatchBlock(pAeigCut,ibl,pAbasis);\n    int NstiblBC=pAbasis->GetBlockSize(iblBC);\n\n\n    for (int jbl=0;jbl<pAeigCut->NumBlocks();jbl++){\n      int Nstjbl=pAeigCut->GetBlockSize(jbl);\n\t  \n      cout << \"  Block j : \" << jbl << \"/\" << pAeigCut->NumBlocks()-1\n\t   << \" (sz=\" <<  Nstjbl \n\t   << \") Time to here \" << t2.elapsed() \n\t   << \"; last lap \" << t2.elapsed()-time_lap2 << endl;\n      time_lap2=t2.elapsed();\n\n      int jblBC=FindMatchBlock(pAeigCut,jbl,pAbasis);\n      int NstjblBC=pAbasis->GetBlockSize(jblBC);\n\n\n      //Loop matrices: check if the matrix elements are non-zero\n      for (int imats=0;imats<NumNRGMats;imats++){\n\tif ( NRGMats[imats].CheckForMatEl(pAeigCut,ibl,jbl)   ){\n\t  cout << \"   Updating Op imats=: \" << imats << \" of \" << NumNRGMats-1 << endl;\n\t  // Set Zi,Zj\n\t  if (display){\n\t    cout << \" Nshell = \" << pAeigCut->Nshell << endl;\n\t    //cout << \" Updating Op imats=: \" << imats << \" of \" << NumNRGMats-1 << endl;\n\t    cout << \" icount = \" << icount[imats] << \" to \" \n\t\t << icount[imats]+Nstibl*Nstjbl-1 << endl;\n\t    cout << \"  Setting up Block i : \" << ibl \n\t\t << \" (size \" <<  Nstibl \n\t\t << \"  was bl \" << iblBC << \" sz \" << NstiblBC\n\t\t << \") x Block j \" << jbl\n\t\t << \" (size \" << Nstjbl \n\t\t << \"  was bl \" << jblBC << \" sz \" << NstjblBC\n\t\t << \") of \" << pAeigCut->NumBlocks() << endl;\n\t  }\n\t  NRGMats[imats].MatBlockMap.push_back(ibl);\n\t  NRGMats[imats].MatBlockMap.push_back(jbl);\n\t  NRGMats[imats].MatBlockBegEnd.push_back(icount[imats]);\n\t  icount[imats]+=Nstibl*Nstjbl;\n\t  NRGMats[imats].MatBlockBegEnd.push_back(icount[imats]-1);\n\n\t  // \t\t  cout << \"    Setting up BLAS matrices...\" << endl;\n\t  //boost::numeric::ublas::matrix<double> Zibl(Nstibl,Nstibl);\n\t  //boost::numeric::ublas::matrix<double> Zjbl(Nstjbl,Nstjbl);\n\t  if (NRGMats[imats].IsComplex){\n\t    cZibl.resize(Nstibl,NstiblBC);\n\t    cZjbl.resize(Nstjbl,NstjblBC);\n\t    cZibl=pAeigCut->cEigVecCut2BLAS(ibl);\n\t    cZjbl=pAeigCut->cEigVecCut2BLAS(jbl);\n\t    cfnbasis.resize(NstiblBC,NstjblBC);\n\t  }else{\n\t    Zibl.resize(Nstibl,NstiblBC);\n\t    Zjbl.resize(Nstjbl,NstjblBC);\n\t    Zibl=pAeigCut->EigVecCut2BLAS(ibl);\n\t    Zjbl=pAeigCut->EigVecCut2BLAS(jbl);\n\t    fnbasis.resize(NstiblBC,NstjblBC);\n\t  }\n\n\t  if (display) cout << \"    ...Zs done ...\" << endl;\n\n// \t  fnbasis.resize(NstiblBC,NstjblBC);\n\t  // Set-up fn basis: Loop in the basis states\n\t  int istbl=0;\n\t  for (int ist=pAbasis->GetBlockLimit(iblBC,0);\n\t       ist<=pAbasis->GetBlockLimit(iblBC,1);ist++){\n\t    //int typei=pAbasis->iType[ist];\n\t    //int stcfi=pAbasis->StCameFrom[ist];\n\n\t    int jstbl=0;\n\t    for (int jst=pAbasis->GetBlockLimit(jblBC,0);\n\t\t jst<=pAbasis->GetBlockLimit(jblBC,1);jst++){\n\t      //int typej=pAbasis->iType[jst];\n\t      //int stcfj=pAbasis->StCameFrom[jst];\n\n\t      \t  \n\t      if (NRGMats[imats].IsComplex) \n\t\tcfnbasis(istbl,jstbl)=ZeroC;\n\t      else fnbasis(istbl,jstbl)=0.0;\n\n\t      //Calculate fbasis\n\t      if (NRGMats[imats].NeedOld){\n\t\tint iold=pAbasis->StCameFrom[ist];\n\t\tint jold=pAbasis->StCameFrom[jst];\n\t\tif (NRGMats[imats].IsComplex){\n\t\t  cfnbasis(istbl,jstbl)=(NRGMats[imats].CalcMatElCplx(pAbasis,pSingleSite,ist,jst))*MatOLD[imats].cGetMatEl(iold,jold);\n\t\t}\n\t\t  else\n\t\tfnbasis(istbl,jstbl)=(NRGMats[imats].CalcMatEl(pAbasis,pSingleSite,ist,jst))*MatOLD[imats].GetMatEl(iold,jold);\n\t      }\n\t      else{\n\t\tif (NRGMats[imats].IsComplex)\n\t\t  cfnbasis(istbl,jstbl)=NRGMats[imats].CalcMatElCplx(pAbasis,pSingleSite,ist,jst);\n \n\t\telse\n\t\t  fnbasis(istbl,jstbl)=NRGMats[imats].CalcMatEl(pAbasis,pSingleSite,ist,jst);\n\t      }\n\t      jstbl++;\n\t    }\n\t    // end jst loop\n\t    istbl++;\n\t  }\n\t  // end ist loop\n\t  if (display) cout << \"    ...fnbasis done.\" << endl;\n\n\t  if (display) cout << \"    Multiplying BLAS matrices (final size:\" \n\t\t\t    << Nstibl << \" x \" << Nstjbl << \") ... \" << endl;\n\n\t  t.restart();\n\t  if (NRGMats[imats].IsComplex){\n\t    cfnw.resize(Nstibl,Nstjbl);\n// \t    noalias(cfnw)=prod (cZibl, \n// \t\t     boost::numeric::ublas::matrix<complex<double> >(prod(cfnbasis,trans(cZjbl))) );\n\t    // Wrong. It should be:\n\t    noalias(cfnw)=prod (cZibl, \n\t\t     boost::numeric::ublas::matrix<complex<double> >(prod(cfnbasis,herm(cZjbl))) );\n\n\t  }\n\t  else{\n\t    fnw.resize(Nstibl,Nstjbl);\n\t    noalias(fnw)=prod (Zibl, \n\t\t     boost::numeric::ublas::matrix<double>(prod(fnbasis,trans(Zjbl))) );\n\t  }\n\t  time_elapsed=t.elapsed();\n\t  if (display) cout << \"    ...done. Elapsed time:\" << time_elapsed << endl;\n\t  // Debug\n\t  // if ( (display)&&(pAeigCut->Nshell==1)&&\n\t  //      ( (ibl==1)||(jbl==1) )&&\n\t  //      ( (imats==1) )\n\t  //      ) {\n\t  //   cout << \"Z(i=\"<<ibl<<\")  : \" <<  Zibl << endl;\n\t  //   cout << \"Z(j=\"<<jbl<<\")  : \" <<  Zjbl << endl;\n\t  //   cout << \"fbasis   :\" <<  fnbasis << endl;\n\t  //   cout << \"Zi.fbasis.ZjT : \" <<  fnw << endl;\n\t  //   ///\n\t  //   // cout << \"cZ(i=\"<<ibl<<\")  : \" <<  cZibl << endl;\n\t  //   // cout << \"cZ(j=\"<<jbl<<\")  : \" <<  cZjbl << endl;\n\n\t  //   // cOneTest.resize(NstiblBC,NstiblBC);\n\t  //   // noalias(cOneTest)=prod (herm(cZibl), cZibl);    \n\n\t  //   // cout << \"cZi+.cZi   : \" <<  cOneTest << endl;\n\n\t  //   // cOneTest.resize(NstjblBC,NstjblBC);\n\t  //   // noalias(cOneTest)=prod (herm(cZjbl), cZjbl);    \n\n\t  //   // cout << \"cZj+.cZj   : \" <<  cOneTest << endl;\n\n\t  //   // cout << \"cfbasis   :\" <<  cfnbasis << endl;\n\t  //   // cout << \"cZi.cfbasis.cZjT : \" <<  cfnw << endl;\n\t  //   //cout << \"faux   :\" <<  faux << endl;\n\t  //  }\n\t  // end debug\n\n\t  // Add to NRGMats[imats-1]\n\t  if (NRGMats[imats].IsComplex){\n\t    for (int ii=0;ii<cfnw.size1();ii++)\n\t      for (int jj=0;jj<cfnw.size2();jj++)\n\t\tNRGMats[imats].MatElCplx.push_back(cfnw(ii,jj));\n\t  }\n\t  else{\n\t    for (int ii=0;ii<fnw.size1();ii++)\n\t      for (int jj=0;jj<fnw.size2();jj++)\n\t\tNRGMats[imats].MatEl.push_back(fnw(ii,jj));\n\t  }\n\t  // end if is complex \n\t}\n\t//end if Q=Q'+1 etc\n\n      }\n      // end imats loop\n\n\n\n    }\n    // end jbl loop\n\n  }\n  // end ibl loop\n\n  // Release MatOLD\n  delete[] MatOLD;\n\n  cout << \" DONE updating operators in Nshell = \" << pAeigCut->Nshell << endl; \n\n}\n// END subroutine\n\n//////////////////////////////////\n//////////////////////////////////\n//////////////////////////////////\n//////////////////////////////////\n\nvoid UpdateMatrices(CNRGbasisarray* pSingleSite,CNRGbasisarray* pAeigCut, \n\t\t    CNRGbasisarray* pAbasis,\n\t\t    CNRGmatrix* NRGMats, int NumNRGMats, bool display){\n\n  // STL vectors \n  vector<double> fnbasis;\n  vector<complex<double> > cfnbasis;\n\n  vector<double> fnw;\n  vector<complex<double> > cfnw;\n\n  vector<double> auxMat1;\n  vector<complex<double> > cauxMat1;\n\n  \n  double auxEl;\n  complex<double> cauxEl;\n\n  int ibegZibl,ibegZjbl; // Point where the blocks begin\n\n  int ldaBC,lda,ldaaux; //=max(SizeBl,SizeBl2);\n\n  // cblas_dgemm variables\n  double ALPHA=1.0, BETA=0.0;\n  //   C <- ALPHA*A.B + BETA*C\n\n  //typedef CBLAS_ORDER CBLAS_LAYOUT; // this for backward compatibility \n\n  // Check that eigenvectors are properly normalized!\n\n  //boost::numeric::ublas::matrix<complex<double> > cOneTest;\n\n\n  // Check time\n  boost::timer t;\n  double time_elapsed;\n\n  boost::timer t2;\n  double time_lap2;\n\n  \n  CNRGmatrix* MatOLD = new CNRGmatrix [NumNRGMats];\n\n  //Clear all\n  for (int imats=0;imats<NumNRGMats;imats++){\n    if (NRGMats[imats].NeedOld) MatOLD[imats]=NRGMats[imats];\n    NRGMats[imats].ClearAll();\n    NRGMats[imats].SyncNRGarray(*pAeigCut);\n  }\n  // end for\n\n  // Note: assumes  Abasis and Aeig have \n  // EXACTLY the same block structure... should check.\n\n  // Loop over blocks (icount counts for each matrix)\n  int icount[NumNRGMats];\n  for (int ii=0;ii<NumNRGMats;ii++) icount[ii]=0;\n\n  t2.restart();\n  time_lap2=0.0;\n  // Note Aeig can be a \"cut\" array\n  for (int ibl=0;ibl<pAeigCut->NumBlocks();ibl++){\n    int Nstibl=pAeigCut->GetBlockSize(ibl);\n\n    cout << \"Block i : \" << ibl << \"/\" << pAeigCut->NumBlocks()-1\n\t << \" (sz=\" <<  Nstibl << \") Nshell=\" << pAeigCut->Nshell << endl;\n    // Corresponding block size in pAbasis\n    int iblBC=FindMatchBlock(pAeigCut,ibl,pAbasis);\n    int NstiblBC=pAbasis->GetBlockSize(iblBC);\n\n\n    for (int jbl=0;jbl<pAeigCut->NumBlocks();jbl++){\n      int Nstjbl=pAeigCut->GetBlockSize(jbl);\n\t  \n      cout << \"  Block j : \" << jbl << \"/\" << pAeigCut->NumBlocks()-1\n\t   << \" (sz=\" <<  Nstjbl \n\t   << \") Time to here \" << t2.elapsed() \n\t   << \"; last lap \" << t2.elapsed()-time_lap2 << endl;\n      time_lap2=t2.elapsed();\n\n      int jblBC=FindMatchBlock(pAeigCut,jbl,pAbasis);\n      int NstjblBC=pAbasis->GetBlockSize(jblBC);\n\n\n      //Loop matrices: check if the matrix elements are non-zero\n      for (int imats=0;imats<NumNRGMats;imats++){\n\tif ( NRGMats[imats].CheckForMatEl(pAeigCut,ibl,jbl)   ){\n\t  cout << \"   Updating Op imats=: \" << imats << \" of \" << NumNRGMats-1 << endl;\n\t  // Set Zi,Zj\n\t  if (display){\n\t    cout << \" Nshell = \" << pAeigCut->Nshell << endl;\n\t    //cout << \" Updating Op imats=: \" << imats << \" of \" << NumNRGMats-1 << endl;\n\t    cout << \" icount = \" << icount[imats] << \" to \" \n\t\t << icount[imats]+Nstibl*Nstjbl-1 << endl;\n\t    cout << \"  Setting up Block i : \" << ibl \n\t\t << \" (size \" <<  Nstibl \n\t\t << \"  was bl \" << iblBC << \" sz \" << NstiblBC\n\t\t << \") x Block j \" << jbl\n\t\t << \" (size \" << Nstjbl \n\t\t << \"  was bl \" << jblBC << \" sz \" << NstjblBC\n\t\t << \") of \" << pAeigCut->NumBlocks() << endl;\n\t  }\n\t  NRGMats[imats].MatBlockMap.push_back(ibl);\n\t  NRGMats[imats].MatBlockMap.push_back(jbl);\n\t  NRGMats[imats].MatBlockBegEnd.push_back(icount[imats]);\n\t  icount[imats]+=Nstibl*Nstjbl;\n\t  NRGMats[imats].MatBlockBegEnd.push_back(icount[imats]-1);\n\n\t  ibegZibl=pAeigCut->GetBlockLimitEigv(ibl,0);\n\t  ibegZjbl=pAeigCut->GetBlockLimitEigv(jbl,0);\n\n\t  cfnbasis.clear();\n\t  fnbasis.clear();\t  \n\n\t  if (display) cout << \"    ...Zs done ...\" << endl;\n\n\t  // Set-up fn basis: Loop in the basis states\n\t  int istbl=0;\n\t  for (int ist=pAbasis->GetBlockLimit(iblBC,0);\n\t       ist<=pAbasis->GetBlockLimit(iblBC,1);ist++){\n\t    //int typei=pAbasis->iType[ist];\n\t    //int stcfi=pAbasis->StCameFrom[ist];\n\n\t    int jstbl=0;\n\t    for (int jst=pAbasis->GetBlockLimit(jblBC,0);\n\t\t jst<=pAbasis->GetBlockLimit(jblBC,1);jst++){\n\t      //int typej=pAbasis->iType[jst];\n\t      //int stcfj=pAbasis->StCameFrom[jst];\n\n\t      //Calculate fbasis\n\t      if (NRGMats[imats].NeedOld){\n\t\tint iold=pAbasis->StCameFrom[ist];\n\t\tint jold=pAbasis->StCameFrom[jst];\n\t\tif (NRGMats[imats].IsComplex){\n\t\t  cauxEl=(NRGMats[imats].CalcMatElCplx(pAbasis,pSingleSite,ist,jst))*MatOLD[imats].cGetMatEl(iold,jold);\n\t\t  cfnbasis.push_back(cauxEl);\n\t\t}\n\t\telse{\n\t\t  auxEl=(NRGMats[imats].CalcMatEl(pAbasis,pSingleSite,ist,jst))*MatOLD[imats].GetMatEl(iold,jold);\n\t\t  fnbasis.push_back(auxEl);\n\t\t}\n\t      }\n\t      else{\n\t\tif (NRGMats[imats].IsComplex){\n\t\t  cauxEl=NRGMats[imats].CalcMatElCplx(pAbasis,pSingleSite,ist,jst);\n\t\t  cfnbasis.push_back(cauxEl);\n\t\t}\n\t\telse{\n\t\t  auxEl=NRGMats[imats].CalcMatEl(pAbasis,pSingleSite,ist,jst);\n\t\t  fnbasis.push_back(auxEl);\n\t\t}\n\t      }// end if NeedOld else\n\t      jstbl++;\n\t    }\n\t    // end jst loop\n\t    istbl++;\n\t  }\n\t  // end ist loop\n\t  if (display) cout << \"    ...fnbasis done.\" << endl;\n\n\t  if (display) cout << \"    Multiplying BLAS matrices (final size:\" \n\t\t\t    << Nstibl << \" x \" << Nstjbl << \") ... \" << endl;\n\n\t  t.restart();\n\n\t  // Let's see:\n\t  // LDA-> No. of cols of the ORIGINAL matrix\n\t  //\n\t  //   Zibl -> (Nstibl x NstiblBC) matrix -> LDA=NstiblBC\n\t  //   Zjbl -> (Nstjbl x NstjblBC) matrix -> LDA=NstjblBC\n\t  //   fnbasis -> (NstiblBC x NstjblBC) matrix -> LDA=NstjblBC\n\t  //   fnw -> (Nstibl x Nstjbl) matrix    -> LDA=Nstjbl\n\t  // auxMat1 -> (NstiblBC x Nstjbl) matrix -> LDA=Nstjbl\n\t  // auxMat1 = cfnbasis_(NstiblBC x NstjblBC) . herm(cZjbl)_(NstjblBC x Nstjbl)\n\t  // \n\t  //  -> (NstiblBC x Nstjbl) matrix\n\t  // cfnw = cZibl_(Nstibl x NstiblBC) . auxMat1_(NstiblBC x Nstjbl) \n\t  \n\t  if (NRGMats[imats].IsComplex){\n\n\t    cauxMat1.clear();\n\t    cauxMat1.resize(NstiblBC*Nstjbl,ZeroC);\n\n\t    // fnbasis_NstiblBC x NstjblBC) x [Zjbl_(Nstjbl x NstjblBC)]^+\n\t    // -> cMat1_(NstiblBC x Nstjbl)\n\t    cblas_zgemm(CblasRowMajor,  CblasNoTrans, CblasConjTrans,\n\t\t\tNstiblBC, Nstjbl, NstjblBC,\n\t\t\t&ALPHA, &cfnbasis[0], NstjblBC, &(pAeigCut->cEigVec[ibegZjbl]), NstjblBC,\n\t\t\t&BETA, &cauxMat1[0], Nstjbl);\n\n\t    \n\t    cfnw.clear();\n\t    cfnw.resize(Nstibl*Nstjbl,ZeroC);\n\n\n\t    //  Zibl_(Nstibl x NstiblBC) x cMat1_(NstiblBC x Nstjbl)\n\t    //  -> fnw_(Nstibl x Nstjbl)\n\t    cblas_zgemm(CblasRowMajor,  CblasNoTrans, CblasNoTrans,\n\t\t\tNstibl, Nstjbl, NstiblBC,\n\t\t\t&ALPHA, &(pAeigCut->cEigVec[ibegZibl]), NstiblBC,\n\t\t\t&cauxMat1[0], Nstjbl, &BETA, &cfnw[0], Nstjbl );\n\n\t  }else{\n\n\t    auxMat1.clear();\n\t    auxMat1.resize(NstiblBC*Nstjbl,0.0);\n\n\t    // fnbasis_NstiblBC x NstjblBC) x [Zjbl_(Nstjbl x NstjblBC)]^+\n\t    // -> cMat1_(NstiblBC x Nstjbl)\n\t    cblas_dgemm(CblasRowMajor,  CblasNoTrans, CblasConjTrans,\n\t\t\tNstiblBC, Nstjbl, NstjblBC,\n\t\t\tALPHA, &fnbasis[0], NstjblBC, &(pAeigCut->dEigVec[ibegZjbl]), NstjblBC,\n\t\t\tBETA, &auxMat1[0], Nstjbl);\n\n\t    fnw.clear();\n\t    fnw.resize(Nstibl*Nstjbl,0.0);\n\n\t    //  Zibl_(Nstibl x NstiblBC) x auxMat1_(NstiblBC x Nstjbl)\n\t    //  -> fnw_(Nstibl x Nstjbl)\n\t    cblas_dgemm(CblasRowMajor,  CblasNoTrans, CblasNoTrans,\n\t\t\tNstibl, Nstjbl, NstiblBC,\n\t\t\tALPHA, &(pAeigCut->dEigVec[ibegZibl]), NstiblBC,\n\t\t\t&auxMat1[0], Nstjbl, BETA, &fnw[0], Nstjbl );\n\n\n\t  }\n\t  time_elapsed=t.elapsed();\n\t  if (display) cout << \"    ...done. Elapsed time:\" << time_elapsed << endl;\n\t  // Debug\n\t  // if ( (display)&&(pAeigCut->Nshell==1)&&\n\t  //      ( (ibl==1)||(jbl==1) )&&\n\t  //      ( (imats==1) )\n\t  //      ) {\n\t  //   cout << \" ibl= \" << ibl\n\t  // \t << \" jbl= \" << jbl\n\t  // \t << endl;\n\t  //   cout << \" Nstibl=\" << Nstibl\n\t  // \t << \" NstiblBC=\" << NstiblBC\n\t  // \t << \" Nstjbl=\" << Nstjbl\n\t  // \t << \" NstjblBC=\" << NstjblBC\n\t  // \t << endl;\n\t  //   cout << \" fnbasis = \";\n\t  //   for (int ii=0; ii<fnbasis.size(); ii++){\n\t  //     if ( ii % NstjblBC ==0) cout << endl;\n\t  //     cout << fnbasis[ii] << \" \";\n\t  //   }\n\t  //   cout<< endl;\n\t  //   cout << \" fnw = \";\n\t  //   for (int ii=0; ii<fnw.size(); ii++){\n\t  //     if ( ii % Nstjbl ==0) cout << endl;\n\t  //     cout << fnw[ii] << \" \";\n\t  //   }\n\t  //   cout<< endl;\n\n\t    // cout << \" cfnbasis = \";\n\t    // for (int ii=0; ii<cfnbasis.size(); ii++){\n\t    //   if ( ii % NstjblBC ==0) cout << endl;\n\t    //   cout << cfnbasis[ii] << \" \";\n\t    // }\n\t    // cout<< endl;\n\t    // cout << \" cfnw = \";\n\t    // for (int ii=0; ii<cfnw.size(); ii++){\n\t    //   if ( ii % Nstjbl ==0) cout << endl;\n\t    //   cout << cfnw[ii] << \" \";\n\t    // }\n\t    // cout<< endl;\n\n\t  // }\n\t// end debug\n\n\t  // Add to NRGMats[imats-1]\n\t  if (NRGMats[imats].IsComplex){\n\t    for (int ii=0;ii<cfnw.size();ii++)\n\t      NRGMats[imats].MatElCplx.push_back(cfnw[ii]);\n\t  }\n\t  else{\n\t    for (int ii=0;ii<fnw.size();ii++)\n\t      NRGMats[imats].MatEl.push_back(fnw[ii]);\n\t  }\n\t  // end if is complex \n\t}\n\t//end if Q=Q'+1 etc\n\n      }\n      // end imats loop\n\n    }\n    // end jbl loop\n  }\n  // end ibl loop\n\n  // Release MatOLD\n  delete[] MatOLD;\n\n  cout << \" DONE updating operators in Nshell = \" << pAeigCut->Nshell << endl; \n\n}\n// END subroutine\n\n\n\n//////////////////////////////////\n//////////////////////////////////\n//////////////////////////////////\n\n\n", "meta": {"hexsha": "0190d2324516362906a1965cb0a5c2c54282f875", "size": 17191, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/UpdateMatrices.cpp", "max_stars_repo_name": "lgds/NRG_USP", "max_stars_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-21T20:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-20T01:21:41.000Z", "max_issues_repo_path": "src/UpdateMatrices.cpp", "max_issues_repo_name": "lgds/NRG_USP", "max_issues_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/UpdateMatrices.cpp", "max_forks_repo_name": "lgds/NRG_USP", "max_forks_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_forks_repo_licenses": ["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.7422145329, "max_line_length": 121, "alphanum_fraction": 0.5864696644, "num_tokens": 6392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175139669998, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.26324298655096307}}
{"text": "//Released under the MIT License - https://opensource.org/licenses/MIT\n//\n//Copyright (c) 2019 AIT Austrian Institute of Technology GmbH\n//\n//Permission is hereby granted, free of charge, to any person obtaining\n//a 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,\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 CLAIM,\n//DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n//OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n//USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n//Author: Josef Maier (josefjohann-dot-maier-at-gmail-dot-at)\n/**********************************************************************************************************\n FILE: pose_helper.cpp\n\n PLATFORM: Windows 7, MS Visual Studio 2010, OpenCV 2.4.9\n\n CODE: C++\n\n AUTOR: Josef Maier, AIT Austrian Institute of Technology\n\n DATE: May 2016\n\n LOCATION: TechGate Vienna, Donau-City-Strasse 1, 1220 Vienna\n\n VERSION: 1.0\n\n DISCRIPTION: This file provides helper functions for the estimation and optimization of poses between\n              two camera views (images).\n**********************************************************************************************************/\n\n#include \"poselib/pose_helper.h\"\n\n#include <Eigen/SVD>\n#include <Eigen/Dense>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/calib3d.hpp>\n#include <opencv2/imgproc.hpp>\n#include <string>\n#include <chrono>\n#include <thread>\n\nusing namespace cv;\nusing namespace std;\n\nnamespace poselib\n{\n\n/* --------------------------- Defines --------------------------- */\n\n\n\n/* --------------------- Function prototypes --------------------- */\n\n//This function undistorts an image point\nbool LensDist_Oulu(const cv::Point2f& distorted, cv::Point2f& corrected, cv::Mat dist, int iters = 10);\n//Calculation of the rectifying matrices\nint rectifyFusiello(cv::InputArray K1, cv::InputArray K2, cv::InputArray R, cv::InputArray t,\n                    cv::InputArray distcoeffs1, cv::InputArray distcoeffs2, const cv::Size& imageSize,\n                    cv::OutputArray Rect1, cv::OutputArray Rect2, cv::OutputArray K12new,\n                    double alpha = -1, cv::Size newImgSize=cv::Size(), cv::Rect *roi1 = nullptr, cv::OutputArray P1new = cv::noArray(),\n                    cv::OutputArray P2new = cv::noArray());\n//OpenCV interface function for cvStereoRectify. This code was copied from the OpenCV without changes.\nvoid stereoRectify2( InputArray cameraMatrix1, InputArray distCoeffs1,\n                               InputArray cameraMatrix2, InputArray distCoeffs2,\n                               Size imageSize, InputArray _Rmat, InputArray T,\n                               OutputArray _Rmat1, OutputArray _Rmat2,\n                               OutputArray _Pmat1, OutputArray _Pmat2,\n                               OutputArray _Qmat, int flags=CALIB_ZERO_DISPARITY,\n                               double alpha=-1, Size newImageSize=Size(),\n                               CV_OUT Rect* validPixROI1=nullptr, CV_OUT Rect* validPixROI2=nullptr );\n//Slightly changed version of the OpenCV rectification function cvStereoRectify.\nvoid cvStereoRectify2( const cv::Mat* _cameraMatrix1, const cv::Mat* _cameraMatrix2,\n                      const cv::Mat* _distCoeffs1, const cv::Mat* _distCoeffs2,\n                      const cv::Size& imageSize, const cv::Mat* matR, const cv::Mat* matT,\n                      cv::Mat* _R1, cv::Mat* _R2, cv::Mat* _P1, cv::Mat* _P2,\n                      cv::Mat* matQ, int flags, double alpha, cv::Size newImgSize,\n                      cv::Rect* roi1, cv::Rect* roi2 );\n//Slightly changed version of the OpenCV undistortion function cvUndistortPoints.\nvoid cvUndistortPoints2(const cv::Mat& src_, cv::Mat& dst_, const cv::Mat& cameraMatrix_,\n                        const cv::Mat* distCoeffs_,\n                        const cv::Mat* matR, const cv::Mat* matP, cv::OutputArray mask );\n// Estimates the inner rectangle of a distorted image containg only valid/available image information and an outer rectangle countaing all image information\nvoid icvGetRectanglesV0( const cv::Mat* cameraMatrix, const cv::Mat* distCoeffs,\n                 const cv::Mat* R, const cv::Mat* newCameraMatrix, const cv::Size& imgSize,\n                 cv::Rect_<float>& inner, cv::Rect_<float>& outer );\n// Helping function - Takes some actions on a mouse move\nvoid on_mouse_move(int event, int x, int y, int flags, void* param);\n\n/* --------------------- Functions --------------------- */\n\n/* Calculates the Sampson L1-distance for a point correspondence and returns the invers of the\n * denominator (in denom1) and the numerator of the Sampson L1-distance. To calculate the\n * Sampson distance, simply multiply these two. For the Sampson error, multiply and square them.\n *\n * Mat x1\t\t\t\t\t\t\tInput  -> Image projection of the lweft image\n * Mat x2\t\t\t\t\t\t\tInput  -> Image projection of the right image\n * Mat E\t\t\t\t\t\t\tInput  -> Essential matrix\n * double & denom1\t\t\t\t\tOutput -> invers of the denominator of the Sampson distance\n * double & num\t\t\t\t\t\tOutput -> numerator of the Sampson distance\n *\n * Return value:\t\t\t\t\tnone\n */\nvoid SampsonL1(const cv::Mat &x1, const cv::Mat &x2, const cv::Mat &E, double & denom1, double & num)\n{\n    Mat X1, X2;\n    if(x1.rows > x1.cols)\n    {\n        X1 = (Mat_<double>(3, 1) << x1.at<double>(0,0), x1.at<double>(1,0), 1.0);\n        X2 = (Mat_<double>(3, 1) << x2.at<double>(0,0), x2.at<double>(1,0), 1.0);\n    }\n    else\n    {\n        X1 = (Mat_<double>(3, 1) << x1.at<double>(0,0), x1.at<double>(0,1), 1.0);\n        X2 = (Mat_<double>(3, 1) << x2.at<double>(0,0), x2.at<double>(0,1), 1.0);\n    }\n    Mat xpE = X2.t() * E;\n    xpE = xpE.t();\n    num = xpE.dot(X1);\n    //num = X2.dot(E * X1);\n    Mat Ex1 = E * X1;\n    //Ex1 /= Ex1.at<double>(2);\n    //xpE /= xpE.at<double>(2);\n    //Mat Etx2 = E.t() * X2;\n    double a = Ex1.at<double>(0,0) * Ex1.at<double>(0,0);\n    double b = Ex1.at<double>(1,0) * Ex1.at<double>(1,0);\n    double c = xpE.at<double>(0,0) * xpE.at<double>(0,0);\n    double d = xpE.at<double>(1,0) * xpE.at<double>(1,0);\n\n    denom1 = 1 / (std::sqrt(a + b + c + d) + 1e-8);\n}\n\n/* Calculates the closest essential matrix by enforcing the singularity constraint (third\n * singular value is zero).\n *\n * Mat x1\t\t\t\t\t\t\tInput & Output  -> Essential matrix\n *\n * Return value:\t\t\t\t\t0:\t\t  Everything ok\n *\t\t\t\t\t\t\t\t\t-1:\t\t  E is no essential matrix\n */\nint getClosestE(Eigen::Matrix3d & E)\n{\n    //double avgSingVal;\n    Eigen::JacobiSVD<Eigen::Matrix3d> svdE(E, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n    if(!nearZero(svdE.singularValues()[2])){\n        return -1; // E is no essential matrix\n    }\n    if((svdE.singularValues()[0]/svdE.singularValues()[1] > 1.5) ||\n            (svdE.singularValues()[0]/svdE.singularValues()[1] < 0.66)){\n        return -1; // E is no essential matrix\n    }\n\n    Eigen::Matrix3d D;\n    D.setZero();\n    /*avgSingVal = svdE.singularValues().segment(0,2).sum()/2;\n    D(0,0) = D(1,1) = avgSingVal;*/\n    D(0,0) = svdE.singularValues()[0];\n    D(1,1) = svdE.singularValues()[1];\n\n    E = svdE.matrixU() * D * svdE.matrixV().transpose();\n\n    return 0;\n}\n\n\n/* Validate the Essential/Fundamental matrix with the oriented epipolar constraint (this should\n * be extensively tested if it makes sence) and optionally checks the correctness of the singular\n * values of the essential matrix.\n *\n * Mat p1\t\t\t\t\t\t\tInput  -> Image projections (n rows) of the left image\n * Mat p2\t\t\t\t\t\t\tInput  -> Corresponding image projections of the right image\n * Eigen::Matrix3d E\t\t\t\tInput  -> Essential matrix\n * bool EfullCheck\t\t\t\t\tInput  -> If true, the correctness of the singular values of\n *\t\t\t\t\t\t\t\t\t\t\t  the essential matrix is checked\n * InputOutputArray _mask\t\t\tI/O    -> If provided, a mask marking invalid correspondences\n *\t\t\t\t\t\t\t\t\t\t\t  is returned\n * bool tryOrientedEpipolar\t\t\tInput  -> Optional input [DEFAULT = false] to specify if a essential matrix\n *\t\t\t\t\t\t\t\t\t\t\t  should be evaluated by the oriented epipolar constraint. Maybe this\n *\t\t\t\t\t\t\t\t\t\t\t  is only possible for a fundamental matrix?\n *\n * Return value:\t\t\t\t\ttrue:\t\t  Essential/Fundamental matrix is valid\n *\t\t\t\t\t\t\t\t\tfalse:\t\t  Essential/Fundamental matrix is invalid\n */\nbool validateEssential(const cv::Mat &p1,\n                       const cv::Mat &p2,\n                       Eigen::Matrix3d E,\n                       bool EfullCheck,\n                       cv::InputOutputArray _mask,\n                       bool tryOrientedEpipolar)\n{\n    //Eigen::Matrix3d E;\n    Eigen::Vector3d e2, x1, x2;\n\n    Mat _p1, _p2;\n    if(p1.channels() == 2)\n    {\n        if(p1.cols > p1.rows)\n        {\n            _p1 = p1.clone();\n            _p2 = p2.clone();\n            _p1 = _p1.t();\n            _p2 = _p2.t();\n            _p1 = _p1.reshape(1);\n            _p2 = _p2.reshape(1);\n        }\n        else\n        {\n            _p1 = p1.reshape(1);\n            _p2 = p2.reshape(1);\n        }\n    }\n    else\n    {\n        if(p1.cols > p1.rows)\n        {\n            _p1 = p1.clone();\n            _p2 = p2.clone();\n            _p1 = _p1.t();\n            _p2 = _p2.t();\n        }\n        else\n        {\n            _p1 = p1;\n            _p2 = p2;\n        }\n    }\n\n    int cnt = 0, n = _p1.rows;\n    float badPtsRatio;\n    Mat mask = Mat::ones(1,n,CV_8UC1);\n\n    //cv2eigen(Ecv, E);\n\n//tryagain:\n    bool exitfor = true;\n    while (exitfor)\n    {\n        if (EfullCheck)\n        {\n            Eigen::Matrix3d V;\n            Eigen::JacobiSVD<Eigen::Matrix3d > svdE(E.transpose(), Eigen::ComputeFullV);\n\n            if (svdE.singularValues()(0) / svdE.singularValues()(1) > 1.2)\n                return false;\n            if (!nearZero(0.01*svdE.singularValues()(2) / svdE.singularValues()(1)))\n                return false;\n\n            V = svdE.matrixV();\n            e2 = V.col(2);\n        }\n        else\n        {\n            Eigen::MatrixXd ker = E.transpose().fullPivLu().kernel();\n            if (ker.cols() != 1)\n                return false;\n            e2 = ker.col(0);\n        }\n\n        //Does this improve something or only need time?\n        exitfor = false;\n        if (tryOrientedEpipolar)\n        {\n            for (int i = 0; i < n; i++)\n            {\n                Eigen::Vector3d e2_line1, e2_line2;\n                x1 << _p1.at<double>(i, 0),\n                    _p1.at<double>(i, 1),\n                    1.0;\n                x2 << _p2.at<double>(i, 0),\n                    _p2.at<double>(i, 1),\n                    1.0;\n                e2_line1 = e2.cross(x2);\n                e2_line2 = E * x1;\n                for (int j = 0; j < 3; j++)\n                {\n                    if (nearZero(0.1*e2_line1(j)) || nearZero(0.1*e2_line2(j)))\n                        continue;\n                    if (e2_line1(j)*e2_line2(j) < 0)\n                    {\n                        if (cnt < 3)\n                            cnt++;\n                        else if ((cnt == 3) && (i == cnt))\n                        {\n                            E *= -1.0;\n                            for (int k = 0; k < cnt; k++)\n                                mask.at<bool>(k) = true;\n                            cnt++;\n                            //goto tryagain;\n                            exitfor = true;\n                            break;\n                        }\n                        mask.at<bool>(i) = false;\n                        break;\n                    }\n                }\n                if (exitfor)\n                    break;\n            }\n        }\n    }\n    badPtsRatio = 1.0f - (float)cv::countNonZero(mask) / (float)n;\n    if (badPtsRatio > 0.4f)\n        return false;\n\n    if(_mask.needed())\n    {\n        Mat mask1 = _mask.getMat();\n        if(mask1.empty())\n        {\n            _mask.create(1, n, CV_8UC1, -1, true);\n            mask1 = _mask.getMat();\n            mask1 = Mat::ones(1, n, CV_8UC1);\n        }\n        bitwise_and(mask, mask1, mask1);\n    }\n\n    return true;\n}\n\n/* Checks, if determinants, etc. are too close to 0\n *\n * double d\t\t\t\t\t\t\tInput  -> The value which should be checked\n *\n * Return value:\t\t\t\t\tTRUE:  Value is too close to zero\n *\t\t\t\t\t\t\t\t\tFALSE: Value is ok.\n */\n//inline bool nearZero(double d)\n//{\n//    //Decide if determinants, etc. are too close to 0 to bother with\n//    const double EPSILON = 1e-3;\n//    return (d<EPSILON) && (d>-EPSILON);\n//}\n\n\n/* Calculates statistical parameters for the given values in the vector. The following parameters\n * are calculated: median, arithmetic mean value, standard deviation and median absolute deviation (MAD).\n *\n * vector<double> vals\t\tInput  -> Input vector from which the statistical parameters should be calculated\n * statVals* stats\t\t\tOutput -> Structure holding the statistical parameters\n * bool rejQuartiles\t\tInput  -> If true [Default=false], the lower and upper quartiles are rejected before calculating\n *\t\t\t\t\t\t\t\t\t  the parameters\n * bool roundStd\t\t\tInput  -> If true [Default], an standard deviation below 1e-6 is set to 0\n *\n * Return value:\t\t none\n */\nvoid getStatsfromVec(const std::vector<double> &vals, statVals *stats, bool rejQuartiles, bool roundStd)\n{\n    if(vals.empty())\n    {\n        stats->arithErr = 0;\n        stats->arithStd = 0;\n        stats->medErr = 0;\n        stats->medStd = 0;\n        return;\n    }\n    int n = (int)vals.size();\n    int qrt_si = (int)floor(0.25 * (double)n);\n    std::vector<double> vals_tmp(vals);\n\n    std::sort(vals_tmp.begin(),vals_tmp.end(),[](double const & first, double const & second){\n        return first < second;});\n\n    if(n % 2)\n        stats->medErr = vals_tmp[(n-1)/2];\n    else\n        stats->medErr = (vals_tmp[n/2] + vals_tmp[n/2-1]) / 2.0;\n\n    stats->arithErr = 0.0;\n    double err2sum = 0.0;\n    //double medstdsum = 0.0;\n    double hlp;\n    std::vector<double> madVec;\n    for(int i = rejQuartiles ? qrt_si:0; i < (rejQuartiles ? (n-qrt_si):n); i++)\n    {\n        stats->arithErr += vals_tmp[i];\n        err2sum += vals_tmp[i] * vals_tmp[i];\n\n        madVec.push_back(std::abs(vals_tmp[i] - stats->medErr));\n\n        //medstdsum += hlp * hlp;\n    }\n    if(rejQuartiles)\n        n -= 2 * qrt_si;\n    stats->arithErr /= (double)n;\n\n    std::sort(madVec.begin(),madVec.end(),[](double const & first, double const & second){\n        return first < second;});\n\n    if(n % 2)\n        stats->medStd = 1.4826 * madVec[(n-1)/2]; //1.4826 corresponds to a scale factor for transform the MAD to approximately\n                                                    //the standard deviation for a standard normal distribution, see https://en.wikipedia.org/wiki/Median_absolute_deviation\n    else\n        stats->medStd = 1.4826 * (madVec[n/2] + madVec[n/2-1]) / 2.0;\n\n    hlp = err2sum - (double)n * (stats->arithErr) * (stats->arithErr);\n\n    if(roundStd && std::abs(hlp) < 1e-6)\n        stats->arithStd = 0.0;\n    else\n        stats->arithStd = std::sqrt(hlp/((double)n - 1.0));\n}\n\n/* Extracts the 3D translation vector from the translation essential matrix. It is possible that the\n * resulting vector points in the opposite direction.\n *\n * Mat Et\t\t\t\t\t\t\t\tInput  -> The translation essential matrix\n *\n * Return value:\t\t\t\t\t\tThe 3D translation vector (+-)\n */\ncv::Mat getTfromTransEssential(cv::Mat Et)\n{\n    CV_Assert(!Et.empty() && (Et.type() == CV_64FC1) && nearZero(Et.at<double>(0,1) / Et.at<double>(1,0) + 1.0)\n                && nearZero(Et.at<double>(0,2) / Et.at<double>(2,0) + 1.0) && nearZero(Et.at<double>(1,2) / Et.at<double>(2,1) + 1.0));\n\n    Mat t = (Mat_<double>(3, 1) << Et.at<double>(1,2), Et.at<double>(2,0), Et.at<double>(0,1));\n    double t_norm = normFromVec(t);\n    if(std::abs(t_norm - 1.0) > 1e-3)\n        t /= t_norm;\n\n    return t;\n}\n\n/* Calculates the vector norm.\n *\n * cv::Mat vec\t\t\t\t\t\tInput  -> Vector for which the norm should be calculated\n *\t\t\t\t\t\t\t\t\t\t\t  (size must be 1 x n or n x 1)\n *\n * Return value:\t\t\t\t\tVector norm\n */\ndouble normFromVec(const cv::Mat& vec)\n{\n    int n;\n    double norm = 0;\n    Mat tmp;\n    if(vec.type() != CV_64FC1)\n        vec.convertTo(tmp,CV_64FC1);\n    else\n        tmp = vec;\n\n    n = tmp.rows > tmp.cols ? tmp.rows : tmp.cols;\n\n    for(int i = 0; i < n; i++)\n        norm += tmp.at<double>(i) * tmp.at<double>(i);\n\n    return std::sqrt(norm);\n}\n\n/* Calculates the vector norm.\n *\n * vector<double> vec\t\t\t\tInput  -> Vector for which the norm should be calculated\n *\n * Return value:\t\t\t\t\tVector norm\n */\ndouble normFromVec(std::vector<double> vec)\n{\n    size_t n = vec.size();\n    double norm = 0;\n\n    for(size_t i = 0; i < n; i++)\n        norm += vec[i] * vec[i];\n\n    return std::sqrt(norm);\n}\n\n/* Calculates the statistics on the reprojection errors for the given correspondences and a given\n * essential matrix. If a (normalized) fundamental matrix is used, EisF and takeImageCoords must be true\n * and the correspondences must be normalized. If \"takeImageCoords\" is true and EisF=false [Default], the\n * correspondences which are in the camera (or world) coordinate system are transferred into the image\n * coordinate system (Thus, K1 and K2 must be provided). The following parameters are calculated from\n * the correspondences (if qp != NULL): median, arithmetic mean value, standard deviation and median\n * absolute deviation (MAD) which is scaled to match the standard deviation of a standard normal\n * distribution.\n *\n * Mat Essential\t\t\tInput  -> Essential matrix\n * bool takeImageCoords\t\tInput  -> If true, the image coordinate system is used instead of the camera\n *\t\t\t\t\t\t\t\t\t  coordinate system.\n * qualityParm* qp\t\t\tOutput -> If this pointer is not NULL, the result is stored here\n * vector<double> *repErr\tOutput -> If this pointer is not NULL, only the error-vector is returned and\n *\t\t\t\t\t\t\t\t\t  no quality parameters are calculated\n * InputArray p1\t\t\tInput  -> Image projections of the first image (n rows x 2 cols)\n * InputArray p2\t\t\tInput  -> Image projections of the second image (n rows x 2 cols)\n * InputArray K1\t\t\tInput  -> Camera matrix of the first camera (must be provided if an essential matrix\n *\t\t\t\t\t\t\t\t\t  is provided and an error in pixel units should be calculated\n *\t\t\t\t\t\t\t\t\t  (takeImageCoords=true, EisF=false))\n * InputArray K2\t\t\tInput  -> Camera matrix of the second camera (must be provided if an essential matrix\n *\t\t\t\t\t\t\t\t\t  is provided and an error in pixel units should be calculated\n *\t\t\t\t\t\t\t\t\t  (takeImageCoords=true, EisF=false))\n * bool EisF\t\t\t\tInput  -> If true [Default=false], a fundamental matrix is given instead of an\n *\t\t\t\t\t\t\t\t\t  essential matrix (takeImageCoords must be set to true)\n *\n * Return value:\t\t none\n */\nvoid getReprojErrors(const cv::Mat& Essential, cv::InputArray p1, cv::InputArray p2, bool takeImageCoords, statVals* qp, std::vector<double> *repErr, cv::InputArray K1, cv::InputArray K2, bool EisF)\n{\n    CV_Assert(!p1.empty() && !p2.empty());\n    CV_Assert(!(takeImageCoords && !K1.empty() && !K2.empty()) || EisF);\n    CV_Assert(!((qp == nullptr) && (repErr == nullptr)));\n\n    if(EisF && !takeImageCoords)\n        takeImageCoords = true;\n\n    std::vector<double> error;\n    int n;\n    n = p1.getMat().rows;\n\n    Mat x1, x2, FE, x1_tmp, x2_tmp, K1_, K2_;\n\n    if(!K1.empty() && !K2.empty())\n    {\n        K1_ = K1.getMat();\n        K2_ = K2.getMat();\n    }\n\n    if(takeImageCoords)\n    {\n        if(EisF)\n        {\n            x1 = p1.getMat();\n            x2 = p2.getMat();\n            FE = Essential;\n        }\n        else\n        {\n            x1 = Mat::ones(3,n,CV_64FC1);\n            x1_tmp = p1.getMat().t();\n            x1_tmp.copyTo(x1.rowRange(0,2));\n            x1 = K1_*x1;\n            x1.row(0) /= x1.row(2);\n            x1.row(1) /= x1.row(2);\n            x1 = x1.rowRange(0,2).t();\n\n            x2 = Mat::ones(3,n,CV_64FC1);\n            x2_tmp = p2.getMat().t();\n            x2_tmp.copyTo(x2.rowRange(0,2));\n            x2 = K2_*x2;\n            x2.row(0) /= x2.row(2);\n            x2.row(1) /= x2.row(2);\n            x2 = x2.rowRange(0,2).t();\n\n            FE = K2_.inv().t()*Essential*K1_.inv();\n        }\n    }\n    else\n    {\n        x1 = p1.getMat();\n        x2 = p2.getMat();\n\n        FE = Essential;\n    }\n\n    if(repErr != nullptr)\n        computeReprojError2(x1, x2, FE, *repErr);\n\n    if(qp != nullptr)\n    {\n        if(repErr == nullptr)\n        {\n            computeReprojError2(x1, x2, FE, error);\n            getStatsfromVec(error, qp);\n        }\n        else\n        {\n            getStatsfromVec(*repErr, qp);\n        }\n    }\n}\n\n/* Computes the Sampson distance (first-order geometric error) for the provided point correspondences.\n * If the fundamental matrix is used, the homogeneous points have to be in (normalized) camera\n * coordinate system units. If the essential matrix is used for computing the error, the homogeneous\n * points have to be in world coordinate system units (K^-1 * x).\n *\n * Mat X1\t\t\t\t\tInput  -> Points in the left (first) camera of the form 2 rows x n cols\n * Mat X2\t\t\t\t\tInput  -> Points in the right (second) camera of the form 2 rows x n cols\n * Mat E\t\t\t\t\tInput  -> Essential matrix or fundamental matrix -> depends on coordinate\n *\t\t\t\t\t\t\t\t\t  system\n * vector<double> error\t\tOutput -> Vector of errors corresponding to the point correspondences if\n *\t\t\t\t\t\t\t\t\t  the pointer to error1 equals NULL\n * double *error1\t\t\tOutput -> If this pointer is not NULL and X1 & X2 hold only 1 correspondence,\n *\t\t\t\t\t\t\t\t\t  then the error is returned here and NOT in the vector\n *\n * Return value:\t\tnone\n */\nvoid computeReprojError1(cv::Mat X1, cv::Mat X2, const cv::Mat& E, std::vector<double> & error, double *error1)\n{\n    CV_Assert((X1.cols >= X1.rows) || ((X1.cols == 1) && (X1.rows == 2)));\n    int n = X1.cols;\n    Mat Et = E.t();\n\n    for (int i = 0; i < n; i++)\n    {\n        Mat x1 = (Mat_<double>(3, 1) << X1.at<double>(0, i), X1.at<double>(1, i), 1.0);\n        Mat x2 = (Mat_<double>(3, 1) << X2.at<double>(0, i), X2.at<double>(1, i), 1.0);\n        //Mat x1 = X1.col(i);\n        //Mat x2 = X2.col(i);\n        double x2tEx1 = x2.dot(E * x1);\n        Mat Ex1 = E * x1;\n        Mat Etx2 = Et * x2;\n        double a = Ex1.at<double>(0) * Ex1.at<double>(0);\n        double b = Ex1.at<double>(1) * Ex1.at<double>(1);\n        double c = Etx2.at<double>(0) * Etx2.at<double>(0);\n        double d = Etx2.at<double>(1) * Etx2.at<double>(1);\n\n        if(error1 && (n == 1))\n            *error1 = x2tEx1 * x2tEx1 / (a + b + c + d);\n        else\n            error.push_back(x2tEx1 * x2tEx1 / (a + b + c + d));\n    }\n}\n\n/* Computes the Sampson distance (first-order geometric error) for the provided point correspondences.\n * If the fundamental matrix is used, the homogeneous points have to be in (normalized) camera\n * coordinate system units. If the essential matrix is used for computing the error, the homogeneous\n * points have to be in world coordinate system units (K^-1 * x).\n *\n * Mat X1\t\t\t\t\tInput  -> Points in the left (first) camera of the form n rows x 2 cols\n * Mat X2\t\t\t\t\tInput  -> Points in the right (second) camera of the form n rows x 2 cols\n * Mat E\t\t\t\t\tInput  -> Essential matrix or fundamental matrix -> depends on coordinate\n *\t\t\t\t\t\t\t\t\t  system\n * vector<double> error\t\tOutput -> Vector of errors corresponding to the point correspondences if\n *\t\t\t\t\t\t\t\t\t  the pointer to error1 equals NULL\n * double *error1\t\t\tOutput -> If this pointer is not NULL and X1 & X2 hold only 1 correspondence,\n *\t\t\t\t\t\t\t\t\t  then the error is returned here and NOT in the vector\n *\n * Return value:\t\tnone\n */\nvoid computeReprojError2(cv::Mat X1, cv::Mat X2, const cv::Mat& E, std::vector<double> & error, double *error1)\n{\n    CV_Assert((X1.cols <= X1.rows) || ((X1.cols == 2) && (X1.rows == 1)));\n    int n = X1.rows;\n    Mat Et = E.t();\n\n    for (int i = 0; i < n; i++)\n    {\n        Mat x1 = (Mat_<double>(3, 1) << X1.at<double>(i, 0), X1.at<double>(i, 1), 1.0);\n        Mat x2 = (Mat_<double>(3, 1) << X2.at<double>(i, 0), X2.at<double>(i, 1), 1.0);\n        //Mat x1 = X1.col(i);\n        //Mat x2 = X2.col(i);\n        double x2tEx1 = x2.dot(E * x1);\n        Mat Ex1 = E * x1;\n        Mat Etx2 = Et * x2;\n        double a = Ex1.at<double>(0) * Ex1.at<double>(0);\n        double b = Ex1.at<double>(1) * Ex1.at<double>(1);\n        double c = Etx2.at<double>(0) * Etx2.at<double>(0);\n        double d = Etx2.at<double>(1) * Etx2.at<double>(1);\n\n        if(error1 && (n == 1))\n            *error1 = x2tEx1 * x2tEx1 / (a + b + c + d);\n        else\n            error.push_back(x2tEx1 * x2tEx1 / (a + b + c + d));\n    }\n}\n\n/* Calculates the euler angles from a given rotation matrix. As default the angles are returned in degrees.\n *\n * InputArray R\t\t\t\t\t\t\tInput  -> Rotation matrix\n * double roll\t\t\t\t\t\t\tOutput -> Roll angle or Bank (rotation about x-axis)\n * double pitch\t\t\t\t\t\t\tOutput -> Pitch angle or Heading (rotation about y-axis)\n * double yaw\t\t\t\t\t\t\tOutput -> Yaw angle or Attitude (rotation about z-axis)\n * bool useDegrees\t\t\t\t\t\tInput  -> If true (default), the angles are returned in degrees. Otherwise in radians.\n *\n * Return value:\t\t\t\t\t\tnone\n */\nvoid getAnglesRotMat(cv::InputArray R, double & roll, double & pitch, double & yaw, bool useDegrees)\n{\n    Mat m = R.getMat();\n    const double radDegConv = 180.0 / PI;\n\n    /** this conversion uses conventions as described on page:\n*   http://www.euclideanspace.com/maths/geometry/rotations/euler/index.htm\n*   Coordinate System: right hand\n*   Positive angle: right hand\n*   Order of euler angles: pitch first, then yaw, then roll\n*   matrix row column ordering:\n*   [m00 m01 m02]\n*   [m10 m11 m12]\n*   [m20 m21 m22]*/\n\n    // Assuming the angles are in radians.\n    if (m.at<double>(1,0) > 0.998) { // singularity at north pole\n        pitch = std::atan2(m.at<double>(0,2),m.at<double>(2,2));\n        yaw = PI/2;\n        roll = 0;\n    }\n    else if (m.at<double>(1,0) < -0.998) { // singularity at south pole\n        pitch = std::atan2(m.at<double>(0,2),m.at<double>(2,2));\n        yaw = -PI/2;\n        roll = 0;\n    }\n    else\n    {\n        pitch = std::atan2(-m.at<double>(2,0),m.at<double>(0,0));\n        roll = std::atan2(-m.at<double>(1,2),m.at<double>(1,1));\n        yaw = std::asin(m.at<double>(1,0));\n    }\n    if(useDegrees)\n    {\n        pitch *= radDegConv;\n        roll *= radDegConv;\n        yaw *= radDegConv;\n        pitch = round(1e6 * pitch) / 1e6;\n        roll = round(1e6 * roll) / 1e6;\n        yaw = round(1e6 * yaw) / 1e6;\n    }\n}\n\n/* Calculates the difference (roation angle) between two rotation quaternions and the distance between\n * two 3D translation vectors back-rotated by the matrices R and Rcalib (therefore, this error represents\n * the full error caused by the different rotations and translations)\n *\n * Mat R                    Input  -> First rotation quaternion (e.g. result from pose estimation)\n * Mat Rcalib               Input  -> Second rotation quaternion (e.g. from offline calibration)\n * Mat T                    Input  -> First 3D (translation) vector (e.g. result from pose estimation)\n * Mat Tcalib               Input  -> Second 3D (translation) vector (e.g. from offline calibration)\n * double rdiff\t\t\t\tOutput -> Rotation angle (from Angle-axis-representation) between the two rotations\n * double tdiff\t\t\t\tOutput -> Distance between the two translation vectors back-rotated by the matrices\n *\t\t\t\t\t\t\t\t\t  R and Rcalib\n *\n * Return value:\t\t\tnone\n */\nvoid getRTQuality(cv::Mat & R, cv::Mat & Rcalib, cv::Mat & T,\n                  cv::Mat & Tcalib, double* rdiff, double* tdiff)\n{\n    CV_Assert((R.rows == 4) && (R.cols == 1) && (Rcalib.rows == 4) && (Rcalib.cols == 1) &&\n              (T.rows == 3) && (T.cols == 1) && (Tcalib.rows == 3) && (Tcalib.cols == 1) &&\n              (R.type() == CV_64FC1) && (Rcalib.type() == CV_64FC1) && (T.type() == CV_64FC1) && (Tcalib.type() == CV_64FC1) &&\n              rdiff && tdiff);\n    Eigen::Vector4d Re, Rcalibe;\n    Eigen::Vector3d Te, Tcalibe;\n    cv::cv2eigen(R, Re);\n    cv::cv2eigen(Rcalib, Rcalibe);\n    cv::cv2eigen(T, Te);\n    cv::cv2eigen(Tcalib, Tcalibe);\n    getRTQuality(Re, Rcalibe, Te, Tcalibe, rdiff, tdiff);\n}\n\n/* Calculates the difference (roation angle) between two rotation quaternions and the distance between\n * two 3D translation vectors back-rotated by the matrices R and Rcalib (therefore, this error represents\n * the full error caused by the different rotations and translations)\n *\n * Eigen::Vector4d R\t\tInput  -> First rotation quaternion (e.g. result from pose estimation)\n * Eigen::Vector4d Rcalib\tInput  -> Second rotation quaternion (e.g. from offline calibration)\n * Eigen::Vector3d T\t\tInput  -> First 3D (translation) vector (e.g. result from pose estimation)\n * Eigen::Vector3d Tcalib\tInput  -> Second 3D (translation) vector (e.g. from offline calibration)\n * double rdiff\t\t\t\tOutput -> Rotation angle (from Angle-axis-representation) between the two rotations\n * double tdiff\t\t\t\tOutput -> Distance between the two translation vectors back-rotated by the matrices\n *\t\t\t\t\t\t\t\t\t  R and Rcalib\n *\n * Return value:\t\t\tnone\n */\nvoid getRTQuality(Eigen::Vector4d & R, Eigen::Vector4d & Rcalib, Eigen::Vector3d & T,\n                  Eigen::Vector3d & Tcalib, double* rdiff, double* tdiff)\n{\n    Eigen::Vector4d t1, t2;\n\n    *rdiff = rotDiff(R, Rcalib);\n\n    Eigen::Vector3d Tdiff1;\n    Tdiff1 = quatMult3DPt(quatConj(R), T);\n    Tdiff1 -= quatMult3DPt(quatConj(Rcalib), Tcalib); //Error vecot includes both, the error from R and T\n\n    *tdiff = std::sqrt(Tdiff1(0)*Tdiff1(0) + Tdiff1(1)*Tdiff1(1) + Tdiff1(2)*Tdiff1(2));\n}\n\n/* Calculates the essential matrix from the rotation matrix R and the translation\n * vector t: E = [t]x * R\n *\n * cv::Mat R\t\t\t\t\t\tInput  -> Rotation matrix R\n * cv::Mat t\t\t\t\t\t\tInput  -> Translation vector t\n *\n * Return value:\t\t\t\t\tEssential matrix\n */\ncv::Mat getEfromRT(const cv::Mat& R, const cv::Mat& t)\n{\n    return getSkewSymMatFromVec(t/normFromVec(t)) * R;\n}\n\n/* Generates a 3x3 skew-symmetric matrix from a 3-vector (allows multiplication\n * instead of cross-product)\n *\n * Eigen::Vector4d & Q1\t\t\t\tInput  -> Quaternion in the form [w,x,y,z]\n *\n * Return value:\t\t\t\t\tThe resulting quaternion in the form [w,x,y,z]\n */\ncv::Mat getSkewSymMatFromVec(cv::Mat t)\n{\n    if(t.type() != CV_64FC1)\n        t.convertTo(t,CV_64FC1);\n\n    return (Mat_<double>(3, 3) << 0, -t.at<double>(2), t.at<double>(1),\n                                  t.at<double>(2), 0, -t.at<double>(0),\n                                  -t.at<double>(1), t.at<double>(0), 0);\n}\n\n/* Converts a (Rotation) Quaternion to a (Rotation) matrix\n *\n * Mat q\t\t\t\t\t\t\tInput  -> Quaternion vector of the form [w,x,y,z]\n * Mat R\t\t\t\t\t\t\tOutput -> 3x3 Rotation matrix\n *\n * Return value:\t\t\t\t\tnone\n */\nvoid quatToMatrix(cv::Mat & R, cv::Mat q)\n{\n    R.create(3,3,CV_64FC1);\n    double sqw = q.at<double>(0)*q.at<double>(0);\n    double sqx = q.at<double>(1)*q.at<double>(1);\n    double sqy = q.at<double>(2)*q.at<double>(2);\n    double sqz = q.at<double>(3)*q.at<double>(3);\n\n    // invs (inverse square length) is only required if quaternion is not already normalised\n    double invs = 1 / (sqx + sqy + sqz + sqw);\n    R.at<double>(0,0) = ( sqx - sqy - sqz + sqw)*invs ; // since sqw + sqx + sqy + sqz =1/invs*invs\n    R.at<double>(1,1) = (-sqx + sqy - sqz + sqw)*invs ;\n    R.at<double>(2,2) = (-sqx - sqy + sqz + sqw)*invs ;\n\n    double tmp1 = q.at<double>(1)*q.at<double>(2);\n    double tmp2 = q.at<double>(3)*q.at<double>(0);\n    R.at<double>(1,0) = 2.0 * (tmp1 + tmp2)*invs ;\n    R.at<double>(0,1) = 2.0 * (tmp1 - tmp2)*invs ;\n\n    tmp1 = q.at<double>(1)*q.at<double>(3);\n    tmp2 = q.at<double>(2)*q.at<double>(0);\n    R.at<double>(2,0) = 2.0 * (tmp1 - tmp2)*invs ;\n    R.at<double>(0,2) = 2.0 * (tmp1 + tmp2)*invs ;\n    tmp1 = q.at<double>(2)*q.at<double>(3);\n    tmp2 = q.at<double>(1)*q.at<double>(0);\n    R.at<double>(2,1) = 2.0 * (tmp1 + tmp2)*invs ;\n    R.at<double>(1,2) = 2.0 * (tmp1 - tmp2)*invs ;\n}\n\n\n/* Converts a (Rotation) matrix to a (Rotation) quaternion\n *\n * Matrix3d rot\t\t\t\t\t\tInput  -> 3x3 Rotation matrix\n * Vector4d quat\t\t\t\t\tOutput -> Quaternion vector of the form [w,x,y,z]\n *\n * Return value:\t\t\t\t\tnone\n */\nvoid MatToQuat(const Eigen::Matrix3d & rot, Eigen::Vector4d & quat) {\n    /*    double trace = rot.trace();\n\n        MAT_TO_QUAT(ACCESS_EIGENMAT_AS_MAT)\n\n        normalise();\n        lengthOk();\n\n        BROKEN -- try this from boost instead\n     */\n\n    double fTrace = rot.trace();\n    double fRoot;\n\n    //From http://www.geometrictools.com/LibFoundation/Mathematics/Wm4Quaternion.inl\n    double m_afTuple[4];\n    if (fTrace > (double) 0.0) //0 is w\n    {\n        // |w| > 1/2, may as well choose w > 1/2\n        fRoot = sqrt(fTrace + (double) 1.0); // 2w\n        m_afTuple[0] = ((double) 0.5) * fRoot;\n        fRoot = ((double) 0.5) / fRoot; // 1/(4w)\n        m_afTuple[1] = (rot(2, 1) - rot(1, 2)) * fRoot;\n        m_afTuple[2] = (rot(0, 2) - rot(2, 0)) * fRoot;\n        m_afTuple[3] = (rot(1, 0) - rot(0, 1)) * fRoot;\n    } else {\n        // |w| <= 1/2\n        int i = 0;\n        if (rot(1, 1) > rot(0, 0)) {\n            i = 1;\n        }\n        if (rot(2, 2) > rot(i, i)) {\n            i = 2;\n        }\n        //        int j = ms_iNext[i];\n        //        int k = ms_iNext[j];\n        int j = (i + 1);\n        j %= 3;\n        int k = (j + 1);\n        k %= 3;\n\n        fRoot = sqrt(rot(i, i) - rot(j, j) - rot(k, k)+(double) 1.0);\n        //double* apfQuat[3] = { &m_afTuple[1], &m_afTuple[2], &m_afTuple[3] };\n        m_afTuple[i + 1] = ((double) 0.5) * fRoot;\n        fRoot = ((double) 0.5) / fRoot;\n        m_afTuple[0] = (rot(k, j) - rot(j, k)) * fRoot;\n        m_afTuple[j + 1] = (rot(j, i) + rot(i, j)) * fRoot;\n        m_afTuple[k + 1] = (rot(k, i) + rot(i, k)) * fRoot;\n    }\n\n    quat(0) = m_afTuple[0];\n    quat(1) = m_afTuple[1];\n    quat(2) = m_afTuple[2];\n    quat(3) = m_afTuple[3];\n}\n\n/* Converts a quaternion to axis angle representation.\n *\n * Vector4d quat\t\t\t\t\tInput  -> Quaternion vector of the form [w,x,y,z]\n * Vector3d axis\t\t\t\t\tOutput -> Rotation axis [x,y,z]\n * double angle\t\t\t\t\t\tOutput -> Rotation angle\n *\n * Return value:\t\t\t\t\tnone\n */\nvoid QuatToAxisAngle(Eigen::Vector4d quat, Eigen::Vector3d axis, double & angle)\n{\n    //From http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm\n\n    Eigen::Vector4d quat_n = quat;\n    if(quat_n(0) > 1.0) // if w>1 acos and sqrt will produce errors, this cant happen if quaternion is normalised\n        quat_n.normalize();\n    angle = 2.0 * std::acos(quat_n(0));\n    double s = std::sqrt(1.0 - quat_n(0) * quat_n(0)); // assuming quaternion normalised then w is less than 1, so term always positive.\n    if (s < 0.001) { // test to avoid divide by zero, s is always positive due to sqrt\n     // if s close to zero then direction of axis not important\n     axis(0) = quat_n(1); // if it is important that axis is normalised then replace with x=1; y=z=0;\n     axis(1) = quat_n(2);\n     axis(2) = quat_n(3);\n   } else {\n     axis(0) = quat_n(1) / s; // normalise axis\n     axis(1) = quat_n(2) / s;\n     axis(2) = quat_n(3) / s;\n   }\n}\n\n/* Calculates the product of a quaternion and a conjugated quaternion. This is used e.g. to calculate the\n * angular difference between two rotation quaternions\n *\n * Eigen::Vector4d Q1\t\t\t\tInput  -> The first quaternion in the form [w,x,y,z]\n * Eigen::Vector4d Q2\t\t\t\tInput  -> The second quaternion in the form [w,x,y,z]\n * Eigen::Vector4d & Qres\t\t\tOutput -> The resulting quaternion in the form [w,x,y,z]\n *\n * Return value:\t\t\t\t\tnone\n */\nvoid quatMultConj(const Eigen::Vector4d & Q1, const Eigen::Vector4d & Q2, Eigen::Vector4d & Qres)\n{\n    //v(4)=dotproduct(a,quatConj(b));\n    //v.rows(1,3)=crossproduct(a_vec,b_vec)   +   a(4)*b_vec    +   b(4)*a_vec;\n\n    Qres(1) = ((Q1(3) * Q2(2) - Q1(2) * Q2(3)) - Q1(0) * Q2(1)) + Q2(0) * Q1(1);\n    Qres(2) = ((Q1(1) * Q2(3) - Q1(3) * Q2(1)) - Q1(0) * Q2(2)) + Q2(0) * Q1(2);\n    Qres(3) = ((Q1(2) * Q2(1) - Q1(1) * Q2(2)) - Q1(0) * Q2(3)) + Q2(0) * Q1(3);\n\n    Qres(0) = Q1(1) * Q2(1) + Q1(2) * Q2(2) + Q1(3) * Q2(3) + Q1(0) * Q2(0); //just dot prod\n}\n\n/* Normalizes the provided quaternion.\n *\n * Eigen::Vector4d Q1\t\t\t\tInput & Output  -> A quaternion in the form [w,x,y,z] must be provided.\n *\t\t\t\t\t\t\t\t\t\t\t\t\t   The normalized quaternion is also returned here.\n *\n * Return value:\t\t\t\t\tnone\n */\nvoid quatNormalise(Eigen::Vector4d & Q)\n{\n    double length = Q(0) * Q(0) + Q(1) * Q(1) + Q(2) * Q(2) + Q(3) * Q(3);\n    double check = length - 1;\n    if (check > 0.0000001 || check < -0.0000001) {\n        double scale = 1.0 / sqrt(length);\n        Q(0) *= scale;\n        Q(1) *= scale;\n        Q(2) *= scale;\n        Q(3) *= scale;\n    }\n}\n\n/* Calculates the angle of a quaternion.\n *\n * Eigen::Vector4d Q1\t\t\t\tInput  -> Quaternion in the form [w,x,y,z]\n *\n * Return value:\t\t\t\t\tThe angle in RAD.\n */\ndouble quatAngle(Eigen::Vector4d & Q)\n{\n    double cosAng = fabs(Q(0));\n    if (cosAng > 1.0) cosAng = 1.0;\n    double ang = 2 * acos(cosAng);\n    if(ang < 0)\n        cout << \"acos returning val less than 0\" << endl;\n    //if(isnan(ang))\n    //\tcout << \"acos returning nan\" << endl;\n    if (ang > PI) ang -= 2 * PI;\n    return ang;\n}\n\n/* Multiplies a quaternion with a 3D-point (e.g. translation vector)\n *\n * Eigen::Vector4d q\t\t\t\tInput  -> Quaternion in the form [w,x,y,z]\n * Eigen::Vector3d p\t\t\t\tInput  -> 3D-point in the form [x,y,z]\n *\n * Return value:\t\t\t\t\tThe new 3D-point or translation vector\n */\nEigen::Vector3d quatMult3DPt(const Eigen::Vector4d & q, const Eigen::Vector3d & p)\n{\n    Eigen::Vector3d multPoint;\n\n    //v=q*v*q_conjugate\n\n    Eigen::Vector4d temp;\n    quatMultByVec(q, p, temp);\n    quatMultConjIntoVec(temp, q, multPoint);\n\n    return multPoint;\n}\n\n/* Multiplies a quaternion with a vector\n *\n * Eigen::Vector4d & Q1\t\t\t\tInput  -> Quaternion in the form [w,x,y,z]\n * Eigen::Vector3d & vec\t\t\tInput  -> Vector in the form [x,y,z]\n * Eigen::Vector4d & Qres\t\t\tOutput -> The resulting quaternion vector in the form [w,x,y,z]\n *\n * Return value:\t\t\t\t\tnone\n */\nvoid quatMultByVec(const Eigen::Vector4d & Q1, const Eigen::Vector3d & vec, Eigen::Vector4d & Qres)\n{\n    //v(4)=dotproduct(a,quatConj(b));\n    //v.rows(1,3)=crossproduct(a_vec,b_vec)   +   a(4)*b_vec    +   b(4)*a_vec;\n\n    Qres(1) = Q1(2) * vec(2) - Q1(3) * vec(1) + Q1(0) * vec(0);\n    Qres(2) = Q1(3) * vec(0) - Q1(1) * vec(2) + Q1(0) * vec(1);\n    Qres(3) = Q1(1) * vec(1) - Q1(2) * vec(0) + Q1(0) * vec(2);\n\n    Qres(0) = -(Q1(1) * vec(0) + Q1(2) * vec(1) + Q1(3) * vec(2));\n}\n\n/* Multiplies a quaternion with a conj. quaternion\n *\n * Eigen::Vector4d & Q1\t\t\t\tInput  -> Quaternion in the form [w,x,y,z]\n * Eigen::Vector4d & Q2\t\t\t\tInput  -> Quaternion in the form [w,x,y,z]\n * Eigen::Vector3d & Qres\t\t\tOutput -> The resulting vector or 3D-point in the form [x,y,z]\n *\n * Return value:\t\t\t\t\tnone\n */\nvoid quatMultConjIntoVec(const Eigen::Vector4d & Q1, const Eigen::Vector4d & Q2, Eigen::Vector3d & Qres)\n{\n\n    //v(4)=dotproduct(a,quatConj(b));\n    //v.rows(1,3)=crossproduct(a_vec,b_vec)   +   a(4)*b_vec    +   b(4)*a_vec;\n\n    Qres(0) = ((Q1(3) * Q2(2) - Q1(2) * Q2(3)) - Q1(0) * Q2(1)) + Q2(0) * Q1(1);\n    Qres(1) = ((Q1(1) * Q2(3) - Q1(3) * Q2(1)) - Q1(0) * Q2(2)) + Q2(0) * Q1(2);\n    Qres(2) = ((Q1(2) * Q2(1) - Q1(1) * Q2(2)) - Q1(0) * Q2(3)) + Q2(0) * Q1(3);\n\n    if(!nearZero(Q1(0) * Q2(0) + Q1(1) * Q2(1) + Q1(2) * Q2(2) + Q1(3) * Q2(3)))\n        cout << \"Bad rotation (probably scale overflow creating a massive vector)\" << endl; //just dot prod\n}\n\n/* Calculates the difference (roation angle) between two rotation quaternions.\n *\n * Eigen::Vector4d R\t\tInput  -> First rotation quaternion (e.g. result from pose estimation)\n * Eigen::Vector4d Rcalib\tInput  -> Second rotation quaternion (e.g. from offline calibration)\n *\n * Return value:\t\t\tRotation angle (from Angle-axis-representation) between the two rotations\n */\ndouble rotDiff(Eigen::Vector4d & R, Eigen::Vector4d & Rcalib)\n{\n    Eigen::Vector4d Rdiff1;\n    quatMultConj(R,Rcalib,Rdiff1);\n    quatNormalise(Rdiff1);\n    return quatAngle(Rdiff1);\n}\n\n/* Calculates the transponse (inverse rotation) of a quaternion\n *\n * Eigen::Vector4d & Q1\t\t\t\tInput  -> Quaternion in the form [w,x,y,z]\n *\n * Return value:\t\t\t\t\tThe resulting quaternion in the form [w,x,y,z]\n */\nEigen::Vector4d quatConj(const Eigen::Vector4d & Q) //'transpose' -- inverse rotation\n{\n    Eigen::Vector4d invertedRot;\n\n    for (int i = 1; i < 4; i++)\n        invertedRot(i) = -Q(i);\n\n    invertedRot(0) = Q(0);\n\n    return invertedRot;\n}\n\n/* Normalizes the image coordinates and transfers the image coordinates into\n * cameracoordinates, respectively.\n *\n * vector<Point2f> points\t\t\tI/O    -> Input: Image coordinates (in pixels)\n *\t\t\t\t\t\t\t\t\t\t\t  Output: Camera coordinates\n * Mat K\t\t\t\t\t\t\tInput  -> Camera matrix\n *\n * Return value:\t\t\t\t\tnone\n */\nvoid ImgToCamCoordTrans(std::vector<cv::Point2f>& points, cv::Mat K)\n{\n    size_t n = points.size();\n\n    for(size_t i = 0; i < n; i++)\n    {\n        points[i].x = (float)(((double)points[i].x - K.at<double>(0,2))/K.at<double>(0,0));\n        points[i].y = (float)(((double)points[i].y - K.at<double>(1,2))/K.at<double>(1,1));\n    }\n}\n\n/* Transfers coordinates from the camera coordinate system into the the image coordinate system.\n *\n * vector<Point2f> points\t\t\tI/O    -> Input: Camera coordinates\n *\t\t\t\t\t\t\t\t\t\t\t  Output: Image coordinates (in pixels)\n * Mat K\t\t\t\t\t\t\tInput  -> Camera matrix\n *\n * Return value:\t\t\t\t\tnone\n */\nvoid CamToImgCoordTrans(std::vector<cv::Point2f>& points, cv::Mat K)\n{\n    size_t n = points.size();\n\n    for(size_t i = 0; i < n; i++)\n    {\n        points[i].x = (float)((double)points[i].x * K.at<double>(0,0) + K.at<double>(0,2));\n        points[i].y = (float)((double)points[i].y * K.at<double>(1,1) + K.at<double>(1,2));\n    }\n}\n\n/* Transfers coordinates from the camera coordinate system into the the image coordinate system.\n *\n * Mat points\t\t\t\t\t\tI/O    -> Input: Camera coordinates (n rows x 2 cols)\n *\t\t\t\t\t\t\t\t\t\t\t  Output: Image coordinates (in pixels)\n * Mat K\t\t\t\t\t\t\tInput  -> Camera matrix\n *\n * Return value:\t\t\t\t\tnone\n */\nvoid CamToImgCoordTrans(cv::Mat& points, cv::Mat K)\n{\n    CV_Assert(((points.rows > points.cols) || ((points.rows <= 2) && (points.cols == 2))) && (points.type() == CV_64FC1));\n    int n = points.rows;\n\n    for(int i = 0; i < n; i++)\n    {\n        points.at<double>(i,0) = points.at<double>(i,0) * K.at<double>(0,0) + K.at<double>(0,2);\n        points.at<double>(i,1) = points.at<double>(i,1) * K.at<double>(1,1) + K.at<double>(1,2);\n    }\n}\n\n/* This function removes the lens distortion for corresponding points in the first (left) and second (right) image.\n * Moreover, correspondences for which undistortion with subsequent distortion does not lead to the original\n * coordinate, are removed. Thus, the point set might be smaller. The same lens distortion models as within the OpenCV\n * library are supported (max. 8 coefficients including 2 for tangential distortion).\n *\n * vector<Point2f> points1\t\t\tI/O\t   -> Points in the first (left) image using the camera coordinate system\n * vector<Point2f> points2\t\t\tI/O\t   -> Points in the second (right) image using the camera coordinate system\n * cv::Mat dist1\t\t\t\t\tInput  -> Distortion coefficients of the first (left) image. The ordering of the\n *\t\t\t\t\t\t\t\t\t\t\t  coefficients is compliant with the OpenCV library. A number of 8\n *\t\t\t\t\t\t\t\t\t\t\t  coefficients is required. If higher order coefficients are not\n *\t\t\t\t\t\t\t\t\t\t\t  available, set them to 0.\n * cv::Mat dist2\t\t\t\t\tInput  -> Distortion coefficients of the second (right) image. The ordering of the\n *\t\t\t\t\t\t\t\t\t\t\t  coefficients is compliant with the OpenCV library. A number of 8\n *\t\t\t\t\t\t\t\t\t\t\t  coefficients is required. If higher order coefficients are not\n *\t\t\t\t\t\t\t\t\t\t\t  available, set them to 0.\n *\n * Return value:\t\t\t\t\ttrue:  Everything ok.\n *\t\t\t\t\t\t\t\t\tfalse: Undistortion failed\n */\nbool Remove_LensDist(std::vector<cv::Point2f>& points1,\n                     std::vector<cv::Point2f>& points2,\n                     const cv::Mat& dist1,\n                     const cv::Mat& dist2)\n{\n    CV_Assert(points1.size() == points2.size());\n\n    if(nearZero(sum(dist1)[0]) && nearZero(sum(dist2)[0])){\n        return true;\n    }\n\n    vector<Point2f> distpoints1, distpoints2;\n    int n1, n = (int)points1.size();\n    cv::Mat mask = cv::Mat::ones(1, n, CV_8UC1);\n\n    //Remove the lens distortion on the normalized coordinates (camera coordinate system)\n    distpoints1 = points1;\n    distpoints2 = points2;\n    for(int i = 0;i < n;i++)\n    {\n        if(!LensDist_Oulu(distpoints1[i], points1[i], dist1))\n        {\n            mask.at<bool>(i) = false;\n            continue;\n        }\n        if(!LensDist_Oulu(distpoints2[i], points2[i], dist2))\n            mask.at<bool>(i) = false;\n    }\n\n    n1 = cv::countNonZero(mask);\n\n    if(n1 < 16)\n        return false;\n\n    if((float)n1/(float)n < 0.75f)\n        cout << \"There is a problem with the distortion parameters! Check your internal calibration parameters!\" << endl;\n\n    //Remove invalid correspondences\n    if(n1 < n)\n    {\n        vector<Point2f> validPoints1, validPoints2;\n        for(int i = 0;i < n;i++)\n        {\n            if(mask.at<bool>(i))\n            {\n                validPoints1.push_back(points1[i]);\n                validPoints2.push_back(points2[i]);\n            }\n        }\n        points1 = validPoints1;\n        points2 = validPoints2;\n    }\n\n    return true;\n}\n\n\n/* This function undistorts an image point using distortion parameters (intended for distorting a\n * point) and the methode of the Oulu University\n *\n * Point2f* distorted\t\t\t\tInput  -> Distorted point\n * Point2f* corrected\t\t\t\tOutput -> Corrected (undistorted) point\n * cv::Mat dist\t\t\t\t\t\tInput  -> Distortion coefficients. The ordering of the coefficients\n *\t\t\t\t\t\t\t\t\t\t\t  is compliant with the OpenCV library.\n * int iters\t\t\t\t\t\tInput  -> Number of iterations used to correct the point:\n *\t\t\t\t\t\t\t\t\tthe higher the number, the better the solution (use a number\n *\t\t\t\t\t\t\t\t\tbetween 3 and 20). The number 3 typically results in an error\n *\t\t\t\t\t\t\t\t\tof 0.1 pixels.\n *\n * Return value:\t\t\t\t\ttrue:  Everything ok.\n *\t\t\t\t\t\t\t\t\tfalse: Undistortion failed\n */\nbool LensDist_Oulu(const cv::Point2f& distorted, cv::Point2f& corrected, cv::Mat dist, int iters)\n{\n    CV_Assert(dist.cols == 8);\n\n    double r2, _2xy, rad_corr, delta[2], k1, k2, k3, k4, k5, k6, p1, p2;\n    k1 = dist.at<double>(0);\n    k2 = dist.at<double>(1);\n    p1 = dist.at<double>(2);\n    p2 = dist.at<double>(3);\n    k3 = dist.at<double>(4);\n    k4 = dist.at<double>(5);\n    k5 = dist.at<double>(6);\n    k6 = dist.at<double>(7);\n\n    for(int i = 0;i < iters;i++)\n    {\n        r2 = (double)corrected.x * (double)corrected.x + (double)corrected.y * (double)corrected.y;\n        _2xy = 2.0 * (double)corrected.x * (double)corrected.y;\n        rad_corr = (1.0 + ((k3 * r2 + k2) * r2 + k1) * r2) / (1.0 + ((k6 * r2 + k5) * r2 + k4) * r2);\n        delta[0] = p1 * _2xy + p2 * (r2 + 2.0 * (double)corrected.x * (double)corrected.x);\n        delta[1] = p1 * (r2 + 2.0 * (double)corrected.y * (double)corrected.y) + p2 * _2xy;\n        corrected.x = (float)(((double)distorted.x - delta[0]) / rad_corr);\n        corrected.y = (float)(((double)distorted.y - delta[1]) / rad_corr);\n    }\n\n    //proof\n    Point2f proofdist;\n    r2 = (double)corrected.x * (double)corrected.x + (double)corrected.y * (double)corrected.y;\n    _2xy = 2.0 * (double)corrected.x * (double)corrected.y;\n    rad_corr = (1.0 + ((k3 * r2 + k2) * r2 + k1) * r2) / (1.0 + ((k6 * r2 + k5) * r2 + k4) * r2);\n    delta[0] = p1 * _2xy + p2 * (r2 + 2.0 * (double)corrected.x * (double)corrected.x);\n    delta[1] = p1 * (r2 + 2.0 * (double)corrected.y * (double)corrected.y) + p2 * _2xy;\n    proofdist.x = (float)((double)corrected.x * rad_corr + delta[0] - (double)distorted.x);\n    proofdist.y = (float)((double)corrected.y * rad_corr + delta[1] - (double)distorted.y);\n    if( std::sqrt(proofdist.x * proofdist.x + proofdist.y * proofdist.y) > 0.25f)\n        return false;\n\n    return true;\n}\n\n/* Calculates the difference (roation angle) between two rotation matrices and the distance between\n * two 3D translation vectors back-rotated by the matrices R1 and R2 (therefore, this error represents\n * the full error caused by the different rotations and translations)\n *\n * Mat R1\t\t\t\tInput  -> First rotation matrix (e.g. result from pose estimation)\n * Mat R2\t\t\t\tInput  -> Second rotation matrix (e.g. from offline calibration)\n * Mat t1\t\t\t\tInput  -> First 3D (translation) vector (e.g. result from pose estimation)\n * Mat t2\t\t\t\tInput  -> Second 3D (translation) vector (e.g. from offline calibration)\n * double rdiff\t\t\tOutput -> Rotation angle (from Angle-axis-representation) between the two rotations\n * double tdiff\t\t\tOutput -> Distance between the two translation vectors back-rotated by the matrices\n *\t\t\t\t\t\t\t\t  R and Rcalib\n * bool printDiff\t\tInput  -> If true, the results are printed to std::out [Default=false]\n *\n * Return value:\t\tnone\n */\nvoid compareRTs(const cv::Mat& R1, const cv::Mat& R2, cv::Mat t1, cv::Mat t2, double *rdiff, double *tdiff, bool printDiff)\n{\n    Eigen::Matrix3d R1e, R2e;\n    Eigen::Vector4d r1quat, r2quat;\n    Eigen::Vector3d t1e, t2e;\n\n    cv::cv2eigen(R1,R1e);\n    cv::cv2eigen(R2,R2e);\n\n    MatToQuat(R1e, r1quat);\n    MatToQuat(R2e, r2quat);\n\n    t1e << t1.at<double>(0), t1.at<double>(1), t1.at<double>(2);\n    t2e << t2.at<double>(0), t2.at<double>(1), t2.at<double>(2);\n\n    getRTQuality(r1quat, r2quat, t1e, t2e, rdiff, tdiff);\n\n    if(printDiff)\n    {\n        cout << \"Angle between rotation matrices: \" << *rdiff / PI * 180.0 << char(248) << endl;\n        cout << \"Distance between translation vectors: \" << *tdiff << endl;\n    }\n}\n\n/* Calculation of the rectifying matrices based on the extrinsic and intrinsic camera parameters. There are 2 methods available\n * for calculating the rectifying matrices: 1st method (Default: globRectFunct=true): A. Fusiello, E. Trucco and A. Verri: \"A compact\n * algorithm for rectification of stereo pairs\", 2000. This methode can be used for the rectification of cameras with a general form\n * of the extrinsic parameters. 2nd method (globRectFunct=false): A slightly changed version (to be more robust) of the OpenCV\n * stereoRectify-function for stereo cameras with no or only a small differnce in the vertical position and small rotations (the cameras\n * should be nearly parallel). Moreover, an new camera matrix is calculated based on the image areas. Therefore, alpha specifies if all\n * valid pixels, only valid pixels (no black areas) or something inbetween should be present in the rectified images.\n *\n * InputArray R\t\t\t\t\t\t\tInput  -> Rotation matrix\n * InputArray t\t\t\t\t\t\t\tInput  -> Translation matrix\n * InputArray K1\t\t\t\t\t\tInput  -> Input camera matrix of the left camera\n * InputArray K2\t\t\t\t\t\tInput  -> Input camera matrix of the right camera\n * InputArray distcoeffs1\t\t\t\tInput  -> Distortion coeffitients of the left camera\n * InputArray distcoeffs2\t\t\t\tInput  -> Distortion coeffitients of the right camera\n * Size imageSize\t\t\t\t\t\tInput  -> Size of the input image\n * OutputArray Rect1\t\t\t\t\tOutput -> Rectification matrix for the left camera\n * OutputArray Rect2\t\t\t\t\tOutput -> Rectification matrix for the right camera\n * OutputArray K1new\t\t\t\t\tOutput -> New camera matrix for the left camera (equal to K2new if globRectFunct=true)\n * OutputArray K2new\t\t\t\t\tOutput -> New camera matrix for the right camera (equal to K1new if globRectFunct=true)\n * double alpha\t\t\t\t\t\t\tInput  -> Free scaling parameter. If it is -1 or absent [Default=-1], the function performs the default\n *\t\t\t\t\t\t\t\t\t\t\t\t  scaling. Otherwise, the parameter should be between 0 and 1. alpha=0 means that the rectified\n *\t\t\t\t\t\t\t\t\t\t\t\t  images are zoomed and shifted so that only valid pixels are visible (no black areas after\n *\t\t\t\t\t\t\t\t\t\t\t\t  rectification). alpha=1 means that the rectified image is decimated and shifted so that all\n *\t\t\t\t\t\t\t\t\t\t\t\t  the pixels from the original images from the cameras are retained in the rectified images\n *\t\t\t\t\t\t\t\t\t\t\t\t  (no source image pixels are lost). Obviously, any intermediate value yields an intermediate\n *\t\t\t\t\t\t\t\t\t\t\t\t  result between those two extreme cases.\n * bool globRectFunct\t\t\t\t\tInput  -> Used method for rectification [Default=true]. If true, the method from A. Fusiello, E. Trucco\n *\t\t\t\t\t\t\t\t\t\t\t\t  and A. Verri: \"A compact algorithm for rectification of stereo pairs\", 2000. This methode can\n *\t\t\t\t\t\t\t\t\t\t\t\t  be used for the rectification of cameras with a general form of the extrinsic parameters.\n *\t\t\t\t\t\t\t\t\t\t\t\t  If false, a slightly changed version (to be more robust) of the OpenCV stereoRectify-function\n *\t\t\t\t\t\t\t\t\t\t\t\t  is used. This method can be used for stereo cameras with only a small differnce in the\n *\t\t\t\t\t\t\t\t\t\t\t\t  vertical position and small rotations only (the cameras should be nearly parallel).\n * Size newImgSize\t\t\t\t\t\tInput  -> Optional new image resolution after rectification. The same size should be passed to\n *\t\t\t\t\t\t\t\t\t\t\t\t  initUndistortRectifyMap() (see the stereo_calib.cpp sample in OpenCV samples directory).\n *\t\t\t\t\t\t\t\t\t\t\t\t  When (0,0) is passed (default), it is set to the original imageSize . Setting it to larger\n *\t\t\t\t\t\t\t\t\t\t\t\t  value can help you preserve details in the original image, especially when there is a big\n *\t\t\t\t\t\t\t\t\t\t\t\t  radial distortion.\n * Rect *roi1\t\t\t\t\t\t\tOutput -> Optional output rectangles inside the rectified images where all the pixels are valid.\n *\t\t\t\t\t\t\t\t\t\t\t\t  If alpha=0 , the ROIs cover the whole images. Otherwise, they are likely to be smaller.\n * Rect *roi2\t\t\t\t\t\t\tOutput -> Optional output rectangles inside the rectified images where all the pixels are valid.\n *\t\t\t\t\t\t\t\t\t\t\t\t  If alpha=0 , the ROIs cover the whole images. Otherwise, they are likely to be smaller.\n * OutputArray P1new\t\t\t\t\tOutput -> Optional new projection matrix for the left camera (only available if globRectFunct=true)\n * OutputArray P2new\t\t\t\t\tOutput -> Optional new projection matrix for the right camera (only available if globRectFunct=true)\n *\n * Return value:\t\t\t\t\t\t0 :\t\tEverything ok\n */\nint getRectificationParameters(cv::InputArray R,\n                              cv::InputArray t,\n                              cv::InputArray K1,\n                              cv::InputArray K2,\n                              cv::InputArray distcoeffs1,\n                              cv::InputArray distcoeffs2,\n                              const cv::Size& imageSize,\n                              cv::OutputArray Rect1,\n                              cv::OutputArray Rect2,\n                              cv::OutputArray K1new,\n                              cv::OutputArray K2new,\n                              double alpha,\n                              bool globRectFunct,\n                              const cv::Size& newImgSize,\n                              cv::Rect *roi1,\n                              cv::Rect *roi2,\n                              cv::OutputArray P1new,\n                              cv::OutputArray P2new)\n{\n    CV_Assert(!R.empty() && !t.empty() && !K1.empty() && !K2.empty() &&\n              (!P1new.needed() || globRectFunct) && (!P2new.needed() || globRectFunct));\n\n    Mat _R, _t;\n    Mat R1, R2, P1, P2, Q, t_tmp;\n\n    _R = R.getMat();\n    _t = t.getMat();\n\n    double t_norm = normFromVec(_t);\n    t_tmp = _t.clone();\n    if(std::abs(t_norm-1.0) > 1e-4)\n        t_tmp /= t_norm;\n\n    if(globRectFunct)\n    {\n        //rectifyFusiello(K1, K2, _R.t(), -1.0 * _R.t() * t_tmp, distcoeffs1, distcoeffs2, imageSize, Rect1, Rect2, K1new, alpha, newImgSize, roi1, P1new, P2new);\n        rectifyFusiello(K1, K2, _R, t_tmp, distcoeffs1, distcoeffs2, imageSize, Rect1, Rect2, K1new, alpha, newImgSize, roi1, P1new, P2new);\n\n        Mat _K2new, _K1new;\n        if(K2new.empty())\n        {\n            K2new.create(3, 3, K1new.type());\n        }\n        _K2new = K2new.getMat();\n        _K1new = K1new.getMat();\n        _K1new.copyTo(_K2new);\n\n        roi2 = roi1;\n    }\n    else\n    {\n        //stereoRectify2(K1, distcoeffs1, K2, distcoeffs2, imageSize, _R.t(), -1.0 * _R.t() * t_tmp, Rect1, Rect2, K1new, K2new, Q, /*0*/CV_CALIB_ZERO_DISPARITY, alpha, newImgSize, roi1, roi2);\n        stereoRectify2(K1, distcoeffs1, K2, distcoeffs2, imageSize, _R, t_tmp, Rect1, Rect2, K1new, K2new, Q, /*0*/cv::CALIB_ZERO_DISPARITY, alpha, newImgSize, roi1, roi2);\n    }\n\n    return 0;\n}\n\n/* Calculation of the rectifying matrices based on the extrinsic and intrinsic camera parameters based on the methode from\n * A. Fusiello, E. Trucco and A. Verri: \"A compact algorithm for rectification of stereo pairs\", 2000. This methode can be used\n * for the rectification of cameras with a general form of the extrinsic parameters. Moreover, an new camera matrix is calculated\n * based on the image areas. Therefore, alpha specifies if all valid pixels, only valid pixels (no black areas) or something\n * inbetween should be present in the rectified images.\n *\n * InputArray K1\t\t\t\t\t\tInput  -> Input camera matrix of the left camera\n * InputArray K2\t\t\t\t\t\tInput  -> Input camera matrix of the right camera\n * InputArray R\t\t\t\t\t\t\tInput  -> Rotation matrix\n * InputArray t\t\t\t\t\t\t\tInput  -> Translation matrix\n * InputArray distcoeffs1\t\t\t\tInput  -> Distortion coeffitients of the left camera\n * InputArray distcoeffs2\t\t\t\tInput  -> Distortion coeffitients of the right camera\n * Size imageSize\t\t\t\t\t\tInput  -> Size of the input image\n * OutputArray Rect1\t\t\t\t\tOutput -> Rectification matrix for the left camera\n * OutputArray Rect2\t\t\t\t\tOutput -> Rectification matrix for the right camera\n * OutputArray K12new\t\t\t\t\tOutput -> New camera matrix for both cameras\n * double alpha\t\t\t\t\t\t\tInput  -> Free scaling parameter. If it is -1 or absent, the function performs the default scaling.\n *\t\t\t\t\t\t\t\t\t\t\t\t  Otherwise, the parameter should be between 0 and 1. alpha=0 means that the rectified images\n *\t\t\t\t\t\t\t\t\t\t\t\t  are zoomed and shifted so that only valid pixels are visible (no black areas after\n *\t\t\t\t\t\t\t\t\t\t\t\t  rectification). alpha=1 means that the rectified image is decimated and shifted so that all\n *\t\t\t\t\t\t\t\t\t\t\t\t  the pixels from the original images from the cameras are retained in the rectified images\n *\t\t\t\t\t\t\t\t\t\t\t\t  (no source image pixels are lost). Obviously, any intermediate value yields an intermediate\n *\t\t\t\t\t\t\t\t\t\t\t\t  result between those two extreme cases.\n * Size newImgSize\t\t\t\t\t\tInput  -> New image resolution after rectification. The same size should be passed to\n *\t\t\t\t\t\t\t\t\t\t\t\t  initUndistortRectifyMap() (see the stereo_calib.cpp sample in OpenCV samples directory).\n *\t\t\t\t\t\t\t\t\t\t\t\t  When (0,0) is passed (default), it is set to the original imageSize . Setting it to larger\n *\t\t\t\t\t\t\t\t\t\t\t\t  value can help you preserve details in the original image, especially when there is a big\n *\t\t\t\t\t\t\t\t\t\t\t\t  radial distortion.\n * Rect *roi1\t\t\t\t\t\t\tOutput -> Optional output rectangles inside the rectified images where all the pixels are valid.\n *\t\t\t\t\t\t\t\t\t\t\t\t  If alpha=0 , the ROIs cover the whole images. Otherwise, they are likely to be smaller.\n * OutputArray P1new\t\t\t\t\tOutput -> Optional new projection matrix for the left camera\n * OutputArray P2new\t\t\t\t\tOutput -> Optional new projection matrix for the right camera\n *\n * Return value:\t\t\t\t\t\t0 :\t\tEverything ok\n */\nint rectifyFusiello(cv::InputArray K1, cv::InputArray K2, cv::InputArray R, cv::InputArray t,\n                    cv::InputArray distcoeffs1, cv::InputArray distcoeffs2, const cv::Size& imageSize,\n                    cv::OutputArray Rect1, cv::OutputArray Rect2, cv::OutputArray K12new,\n                    double alpha, cv::Size newImgSize, cv::Rect *roi1, cv::OutputArray P1new,\n                    cv::OutputArray P2new)\n{\n    Mat c1, c2, v1, v2, v3, Rv, Pn1, Pn2, Rect1_, Rect2_, K1_, K2_, R_, t_, dk1_, dk2_;\n\n    K1_ = K1.getMat();\n    K2_ = K2.getMat();\n    R_ = R.getMat();\n    t_ = t.getMat();\n    dk1_ = distcoeffs1.getMat();\n    dk2_ = distcoeffs2.getMat();\n    auto nx = (double)imageSize.width, ny = (double)imageSize.height;\n\n\n    Mat Po1, Po2;\n    //Calculate projection matrix of camera 1\n    Po1 = cv::Mat::zeros(3,4,K1_.type());\n    Po1.colRange(0,3) = cv::Mat::eye(3,3,K1_.type());\n    Po1 = K1_ * Po1;\n\n    //Calculate projection matrix of camera 2\n    Po2 = cv::Mat(3,4,K2_.type());\n    R_.copyTo(Po2.colRange(0,3));\n    t_.copyTo(Po2.col(3));\n    Po2 = K2_ * Po2;\n\n    /*Mat Q, Ucv, Bcv, R1, t1, K11, R2, t2, K21;\n    Eigen::Matrix3d U, B, Qe;\n    Eigen::MatrixXd test, P;\n\n    //Recalculate extrinsic and intrinsic paramters from camera 1\n    cv::invert(Po1.colRange(0,3),Q);\n    cv::cv2eigen(Q,Qe);\n    Eigen::ColPivHouseholderQR<Eigen::Matrix3d> qr(Qe);\n    //Eigen::HouseholderQR<Eigen::Matrix3d> qr(Qe);\n    U = qr.householderQ();\n    B = U.inverse()*Qe;\n    cv::eigen2cv(U,Ucv);\n    cv::eigen2cv(B,Bcv);\n    invert(Ucv,R1);\n    t1 = Bcv*Po1.col(3);\n    invert(Bcv, K11);\n    K11 = K11 / K11.at<double>(2,2);\n\n    //Recalculate extrinsic and intrinsic paramters from camera 2\n    cv::invert(Po2.colRange(0,3),Q);\n    cv::cv2eigen(Q,Qe);\n    qr.compute(Qe);\n    B = qr.matrixQR().triangularView<Eigen::Upper>();\n    U = qr.householderQ();\n    P = qr.colsPermutation(); //Permutation matrix must be integrated before it works\n    test = U*B;\n    cv::eigen2cv(U,Ucv);\n    cv::eigen2cv(B,Bcv);\n    invert(Ucv,R2);\n    t2 = Bcv*Po2.col(3);\n    invert(Bcv, K21);\n    K21 = K21 / K21.at<double>(2,2);*/\n\n    unsigned int idx = fabs(t_.at<double>(0)) > fabs(t_.at<double>(1)) ? 0 : 1;\n    auto fc_new = DBL_MAX;\n    vector<cv::Point2d> cc_new = vector<cv::Point2d>(2, cv::Point2d(0,0));\n\n    for(int k = 0; k < 2; k++ ) {\n        Mat A = k == 0 ? K1_ : K2_;\n        Mat Dk = k == 0 ? dk1_ : dk2_;\n        double dk1 = Dk.empty() ? 0 : Dk.at<double>(0);\n        double fc = A.at<double>(idx^1,idx^1);\n        if( dk1 < 0 ) {\n            fc *= 1.0 + dk1 * (nx * nx + ny * ny) / (4.0 * fc * fc);\n        }\n        fc_new = std::min(fc_new, fc);\n    }\n\n    newImgSize = newImgSize.width * newImgSize.height != 0 ? newImgSize : imageSize;\n    cc_new[0].x = cc_new[1].x = (nx - 1.0) / 2.0;\n    cc_new[0].y = cc_new[1].y = (ny - 1.0) / 2.0;\n    cc_new[0].x = cc_new[1].x = (double)newImgSize.width * cc_new[0].x / (double)imageSize.width;\n    cc_new[0].y = cc_new[1].y = (double)newImgSize.height * cc_new[0].y/ (double)imageSize.height;\n\n    Mat Knew = (Mat_<double>(3, 3) << fc_new, 0, cc_new[0].x,\n                                      0, fc_new, cc_new[0].y,\n                                      0, 0, 1);\n\n    //The rectification is done using the algorithm from A. Fusiello, E. Trucco and A. Verri: \"A compact algorithm for rectification of stereo pairs\", 2000\n\n    //Calculate optical centers from unchanged cameras\n    c1 = -1.0 * K1_.inv() * Po1.col(3);\n    c2 = -1.0 * R_.t() * K2_.inv() * Po2.col(3);\n\n    /*c1 = -1.0 * Po1.colRange(0,3).inv() * Po1.col(3);\n    c2 = -1.0 * Po2.colRange(0,3).inv() * Po2.col(3);*/\n\n    //New x axis (=direction of baseline)\n    v1 = c2 - c1;//c1 - c2;\n\n    //New y axis (orthogonal to new x and old z)\n    Mat r1_tmp = (Mat_<double>(3, 1) << 0, 0, 1.0);\n    v2 = r1_tmp.cross(v1);\n\n    //New z axis (orthogonal to baseline and y)\n    v3 = v1.cross(v2);\n\n    //New extrinsic parameters (translation is left unchanged)\n    Rv = Mat(3,3,CV_64FC1);\n    Rv.row(0) = v1.t()/cv::norm(v1);\n    Rv.row(1) = v2.t()/cv::norm(v2);\n    Rv.row(2) = v3.t()/cv::norm(v3);\n\n    //Calc new camera matrices\n    Mat K1new, K2new;\n    K2_.copyTo(K1new);\n    K2_.copyTo(K2new);\n    K1new.at<double>(0,1) = 0.0;\n    K2new.at<double>(0,1) = 0.0;\n\n    //New projection matrices\n    Mat Ptmp = Mat(3,4,CV_64FC1);\n    Rv.copyTo(Ptmp.colRange(0,3));\n    Ptmp.col(3) = -1.0 * Rv * c1;\n    Pn1 = K1new * Ptmp;\n    Ptmp.col(3) = -1.0 * Rv * c2;\n    Pn2 = K2new * Ptmp;\n\n    //Rectifying image transformation\n    Rect1_ = Pn1.colRange(0,3) * Po1.colRange(0,3).inv();\n    Rect2_ = Pn2.colRange(0,3) * Po2.colRange(0,3).inv();\n\n    //Center left image\n    double _imc[3] = {(nx - 1.0) / 2.0, (ny - 1.0) / 2.0, 1.0};\n    double _imcr1[3], _imcr2[3];\n    Mat imcr1 = Mat(3,1,CV_64FC1,_imcr1);\n    Mat imcr2 = Mat(3,1,CV_64FC1,_imcr2);\n    Mat imc = Mat(3,1,CV_64FC1,_imc);\n    imcr1 = Rect1_ * imc;\n    imcr1 = imcr1 / imcr1.at<double>(2);\n    Mat d_imc1 = imc - imcr1;\n\n    //Center right image\n    imcr2 = Rect2_ * imc;\n    imcr2 = imcr2 / imcr2.at<double>(2);\n    Mat d_imc2 = imc - imcr2;\n    //d_imc1.at<double>(1) = d_imc2.at<double>(1);\n\n    //Take the mean from the shifts\n    d_imc1 = (d_imc1 + d_imc2) / 2.0;\n\n    //Recalculate camera matrix\n    Knew.rowRange(0,2).col(2) = Knew.rowRange(0,2).col(2) + d_imc1.rowRange(0,2);\n    //K1new.rowRange(0,2).col(2) = K1new.rowRange(0,2).col(2) + d_imc1.rowRange(0,2);\n    //K2new.rowRange(0,2).col(2) = K2new.rowRange(0,2).col(2) + d_imc2.rowRange(0,2);\n\n    //New projection matrices\n    Ptmp.col(3) = -1.0 * Rv * c1;\n    Pn1 = Knew * Ptmp;\n    Ptmp.col(3) = -1.0 * Rv * c2;\n    Pn2 = Knew * Ptmp;\n\n    //Rectifying image transformation\n    Rect1_ = Pn1.colRange(0,3) * Po1.colRange(0,3).inv();\n    Rect2_ = Pn2.colRange(0,3) * Po2.colRange(0,3).inv();\n\n    //Calculate new camera matrix like transformation matrix to asure the right image size\n    imcr1 = Rect1_ * imc;\n    imcr1 = imcr1 / imcr1.at<double>(2);\n    imcr2 = Rect2_ * imc;\n    imcr2 = imcr2 / imcr2.at<double>(2);\n\n    //double scaler = 0, ro2 = _imc[0]*_imc[0]+_imc[1]*_imc[1];\n    //double xmin = DBL_MAX, xmax = -1.0*DBL_MAX, ymin = DBL_MAX, ymax = -1.0*DBL_MAX;\n    //for(int i = 0; i < 4; i++ )\n    //{\n    //\tint j = (i<2) ? 0 : 1;\n    //\tdouble r_tmp1, r_tmp2, _corners[3], _corners1[3];\n    //\tMat corners = Mat(3,1,CV_64FC1,_corners);\n    //\tMat corners1 = Mat(3,1,CV_64FC1,_corners1);\n    //\t_corners[0] = (double)((i % 2)*(nx-1));\n    //\t_corners[1] = (double)(j*(ny-1));\n    //\t_corners[2] = 1.0;\n    //\tcorners1 = Rect1_ * corners;\n    //\tcorners1 /= _corners1[2];\n    //\txmin = std::min(xmin,_corners1[0]);\n    //\tymin = std::min(ymin,_corners1[1]);\n    //\txmax = std::max(xmax,_corners1[0]);\n    //\tymax = std::max(ymax,_corners1[1]);\n    //\tr_tmp1 = _corners1[0] - _imcr1[0];\n    //\tr_tmp1 *= r_tmp1;\n    //\tr_tmp2 = _corners1[1] - _imcr1[1];\n    //\tr_tmp2 *= r_tmp2;\n    //\tscaler += std::sqrt(ro2/(r_tmp1 + r_tmp2));\n    //\tcorners1 = Rect2_ * corners;\n    //\tcorners1 /= _corners1[2];\n    //\txmin = std::min(xmin,_corners1[0]);\n    //\tymin = std::min(ymin,_corners1[1]);\n    //\txmax = std::max(xmax,_corners1[0]);\n    //\tymax = std::max(ymax,_corners1[1]);\n    //\tr_tmp1 = _corners1[0] - _imcr2[0];\n    //\tr_tmp1 *= r_tmp1;\n    //\tr_tmp2 = _corners1[1] - _imcr2[1];\n    //\tr_tmp2 *= r_tmp2;\n    //\tscaler += std::sqrt(ro2/(r_tmp1 + r_tmp2));\n    //}\n    //scaler /= 8;\n\n    ////Scale the rectifying matrix\n    //Mat Kst = (Mat_<double>(3, 3) << scaler, 0, 0,\n    //\t\t\t\t\t\t\t\t0, scaler, 0,\n    //\t\t\t\t\t\t\t\t0, 0, 1);\n\n    //Rect1_ = Kst * Rect1_;\n    //Rect2_ = Kst * Rect2_;\n\n    //Recalculate camera matrix\n    /*Knew.at<double>(0,2) = scaler*(xmax-xmin)/2.0;\n    Knew.at<double>(1,2) = scaler*(ymax-ymin)/2.0;*/\n\n    //Take the 2D rectifying transformations into 3D space\n    Rect1_ = Knew.inv() * (Rect1_ * K1_);\n    Rect2_ = Knew.inv() * (Rect2_ * K2_);\n\n    //Calculate optimal new camera matrix (extracted from OpenCV)\n//    CvPoint2D64f cc_tmp = {DBL_MAX, DBL_MAX};\n    cv::Mat _cameraMatrix1 = K1_, _cameraMatrix2 = K2_;\n    cv::Mat _distCoeffs1 = dk1_, _distCoeffs2 = dk2_;\n    double _z[3] = {0,0,0}, _pp[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};\n    cv::Mat Z = cv::Mat(3, 1, CV_64FC1, _z);\n    cv::Rect_<float> inner1, inner2, outer1, outer2;\n    cv::Mat pp  = cv::Mat(3, 3, CV_64FC1, _pp);\n    double cx1_0, cy1_0, cx1, cy1, s;\n\n    vector<cv::Point2f> _pts1 = vector<cv::Point2f>(4, cv::Point2f(0, 0));\n    vector<cv::Point2f> _pts2 = vector<cv::Point2f>(4, cv::Point2f(0, 0));\n    cv::Mat pts1 = cv::Mat(_pts1, false);\n    cv::Mat pts2 = cv::Mat(_pts2, false);\n    for(int k = 0; k < 2; k++ )\n    {\n        const cv::Mat A = k == 0 ? _cameraMatrix1 : _cameraMatrix2;\n        const cv::Mat Dk = k == 0 ? _distCoeffs1 : _distCoeffs2;\n        vector<cv::Point2f>& _pts = k == 0 ? _pts1 : _pts2;\n        cv::Mat& pts = k == 0 ? pts1 : pts2;\n\n        for(int i = 0; i < 4; i++ )\n        {\n            int j = (i<2) ? 0 : 1;\n            _pts[i].x = (float)((i % 2)*(nx-1));\n            _pts[i].y = (float)(j*(ny-1));\n        }\n        {\n            int valid_nr;\n            double reduction = 0.01;\n            cv::Point2d imgCent = cv::Point2d(nx / 2.0, ny / 2.0);\n            vector<cv::Point2f> _pts_sv = _pts;\n            do\n            {\n                Mat mask;\n                cvUndistortPoints2( pts, pts, A, &Dk, nullptr, nullptr, mask );\n                valid_nr = cv::countNonZero(mask);\n                if(valid_nr < 4)\n                {\n                    for(int i = 0; i < 4; i++ )\n                    {\n                        int j = (i<2) ? 0 : 1;\n                        if(!mask.at<bool>(i))\n                        {\n                            _pts_sv[i].x = _pts[i].x = (float)((floor((1.0 - reduction) * ((i % 2) * nx - imgCent.x)) + imgCent.x - 1.0));\n                            _pts_sv[i].y = _pts[i].y = (float)((floor((1.0 - reduction) * (j * ny - imgCent.y)) + imgCent.y - 1.0));\n                        }\n                        else\n                        {\n                            _pts[i].x = _pts_sv[i].x;\n                            _pts[i].y = _pts_sv[i].y;\n                        }\n                    }\n                    reduction += 0.01;\n                }\n            }while((valid_nr < 4) && (reduction < 0.25));\n\n            if(reduction >= 0.25)\n            {\n                Mat mask;\n                cvUndistortPoints2( pts, pts, A, nullptr, nullptr, nullptr, mask );\n            }\n        }\n    }\n\n    cv::Mat R1_ = Rect1_.clone(), R2_ = Rect2_.clone();\n    for(int k = 0; k < 2; k++ )\n    {\n//        vector<cv::Point3f> _pts_3 = vector<cv::Point3f>(4, cv::Point3f(0, 0, 0));\n//        vector<cv::Point2f> _pts_tmp = vector<cv::Point2f>(4, cv::Point2f(0, 0));\n        cv::Mat pts_3, pts12; //= cv::Mat(_pts_3, false);\n        cv::Mat& pts = k == 0 ? pts1 : pts2;\n        cv::Mat pts_tmp;// = cv::Mat(_pts_tmp, false);\n        pts.convertTo(pts12, CV_64FC1);\n        cv::convertPointsToHomogeneous( pts12, pts_3 );\n\n        //Change camera matrix to have cc=[0,0] and fc = fc_new\n        double _a_tmp[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};\n        cv::Mat A_tmp  = cv::Mat(3, 3, CV_64FC1, _a_tmp);\n        _a_tmp[0][0]=fc_new;\n        _a_tmp[1][1]=fc_new;\n        _a_tmp[0][2]=0.0;\n        _a_tmp[1][2]=0.0;\n        _a_tmp[2][2]=1.0;\n        cv::projectPoints(pts_3, k == 0 ? R1_ : R2_, Z, A_tmp, cv::noArray(), pts_tmp );\n        cv::Scalar avg = cv::mean(pts_tmp);\n        cc_new[k].x = (nx-1)/2 - avg[0];\n        cc_new[k].y = (ny-1)/2 - avg[1];\n    }\n\n    // For simplicity, set the principal points for both cameras to be the average\n    // of the two principal points\n    cc_new[0].x = cc_new[1].x = (cc_new[0].x + cc_new[1].x)*0.5;\n    cc_new[0].y = cc_new[1].y = (cc_new[0].y + cc_new[1].y)*0.5;\n\n    pp.setTo(cv::Scalar::all(0));\n    _pp[0][0] = _pp[1][1] = fc_new;\n    _pp[0][2] = cc_new[0].x;\n    _pp[1][2] = cc_new[0].y;\n    _pp[2][2] = 1;\n\n    alpha = std::min(alpha, 1.);\n\n    icvGetRectanglesV0(&_cameraMatrix1, &_distCoeffs1, &R1_, &pp, imageSize, inner1, outer1 );\n    icvGetRectanglesV0(&_cameraMatrix2, &_distCoeffs2, &R2_, &pp, imageSize, inner2, outer2 );\n\n    cx1_0 = cc_new[0].x;\n    cy1_0 = cc_new[0].y;\n    cx1 = (double)newImgSize.width * cx1_0 / (double)imageSize.width;\n    cy1 = (double)newImgSize.height * cy1_0/ (double)imageSize.height;\n    s = 1.;\n\n    if( alpha >= 0 )\n    {\n        double s0 = std::max(std::max(std::max((double)cx1/(cx1_0 - inner1.x), (double)cy1/(cy1_0 - inner1.y)),\n                                        (double)(newImgSize.width - cx1)/(inner1.x + inner1.width - cx1_0)),\n                                (double)(newImgSize.height - cy1)/(inner1.y + inner1.height - cy1_0));\n\n        double s1 = std::min(std::min(std::min((double)cx1/(cx1_0 - outer1.x), (double)cy1/(cy1_0 - outer1.y)),\n                                        (double)(newImgSize.width - cx1)/(outer1.x + outer1.width - cx1_0)),\n                                (double)(newImgSize.height - cy1)/(outer1.y + outer1.height - cy1_0));\n\n        s = s0*(1.0 - alpha) + s1*alpha;\n        if((s > 2.0) || (s < 0.5)) //added to OpenCV function\n            s = 1.0;\n    }\n\n    fc_new *= s;\n    cc_new[0] = cv::Point2d(cx1, cy1);\n\n    Knew = (Mat_<double>(3, 3) << fc_new, 0, cc_new[0].x,\n                                    0, fc_new, cc_new[0].y,\n                                    0, 0, 1.0);\n\n    if(roi1)\n    {\n        //Intersection of rectangles\n        *roi1 = cv::Rect((int)std::ceil(((double)inner1.x - cx1_0) * s + cx1),\n                         (int)std::ceil(((double)inner1.y - cy1_0) * s + cy1),\n                         (int)std::floor((double)inner1.width * s),\n                         (int)std::floor((double)inner1.height * s))\n            & cv::Rect(0, 0, newImgSize.width, newImgSize.height);\n    }\n\n    Rect1.create(3,3,CV_64FC1);\n    Mat Rect1_tmp = Rect1.getMat();\n    Rect1_.copyTo(Rect1_tmp);\n\n    Rect2.create(3,3,CV_64FC1);\n    Rect1_tmp = Rect2.getMat();\n    Rect2_.copyTo(Rect1_tmp);\n\n    K12new.create(3,3,CV_64FC1);\n    Rect1_tmp = K12new.getMat();\n    Knew.copyTo(Rect1_tmp);\n\n    if(P1new.needed())\n    {\n        Ptmp.col(3) = -1.0 * Rv * c1;\n        Pn1 = Knew * Ptmp;\n        P1new.create(3,4,CV_64FC1);\n        Rect1_tmp = P1new.getMat();\n        Pn1.copyTo(Rect1_tmp);\n    }\n\n    if(P2new.needed())\n    {\n        Ptmp.col(3) = -1.0 * Rv * c2;\n        Pn2 = Knew * Ptmp;\n        P2new.create(3,4,CV_64FC1);\n        Rect1_tmp = P2new.getMat();\n        Pn2.copyTo(Rect1_tmp);\n    }\n\n    return 0;\n}\n\n/* OpenCV interface function for cvStereoRectify. This code was copied from the OpenCV without changes. Check the OpenCV documentation\n * for more information. This function was copied to be able to change a few details on the core functionality of the rectification -\n * especiallly the undistortion functionality to estimate the new virtual cameras.\n *\n * InputArray _cameraMatrix1\t\t\tInput  -> Camera matrix of the first (left) camera\n * InputArray _distCoeffs1\t\t\t\tInput  -> Distortion parameters of the first camera\n * InputArray _cameraMatrix2\t\t\tInput  -> Camera matrix of the second (right) camera\n * InputArray _distCoeffs2\t\t\t\tInput  -> Distortion parameters of the second camera\n * Size imageSize\t\t\t\t\t\tInput  -> Size of the original image\n * InputArray _Rmat\t\t\t\t\t\tInput  -> Rotation matrix to specify the 3D rotation from the first to the second camera\n * InputArray _Tmat\t\t\t\t\t\tInput  -> Translation vector specifying the translational direction from the first to the\n *\t\t\t\t\t\t\t\t\t\t\t\t  second camera (the norm of the vector must be 1.0)\n * OutputArray _Rmat1\t\t\t\t\tOutput -> Rectification transform (rotation matrix) for the first camera\n * OutputArray _Rmat2\t\t\t\t\tOutput -> Rectification transform (rotation matrix) for the second camera\n * OutputArray _Pmat1\t\t\t\t\tOutput -> Projection matrix in the new (rectified) coordinate systems for the first camera\n * OutputArray _Pmat2\t\t\t\t\tOutput -> Projection matrix in the new (rectified) coordinate systems for the second camera\n * OutputArray _Qmat\t\t\t\t\tOutput -> Output 4x4 disparity-to-depth mapping matrix (see reprojectImageTo3D() ).\n * int flags\t\t\t\t\t\t\tInput  -> Operation flags that may be zero or CV_CALIB_ZERO_DISPARITY . If the flag is set,\n *\t\t\t\t\t\t\t\t\t\t\t\t  the function makes the principal points of each camera have the same pixel\n *\t\t\t\t\t\t\t\t\t\t\t\t  coordinates in the rectified views. And if the flag is not set, the function may\n *\t\t\t\t\t\t\t\t\t\t\t\t  still shift the images in the horizontal or vertical direction (depending on the\n *\t\t\t\t\t\t\t\t\t\t\t\t  orientation of epipolar lines) to maximize the useful image area.\n * double alpha\t\t\t\t\t\t\tInput  -> Free scaling parameter. If it is -1 or absent, the function performs the default scaling.\n *\t\t\t\t\t\t\t\t\t\t\t\t  Otherwise, the parameter should be between 0 and 1. alpha=0 means that the rectified images\n *\t\t\t\t\t\t\t\t\t\t\t\t  are zoomed and shifted so that only valid pixels are visible (no black areas after\n *\t\t\t\t\t\t\t\t\t\t\t\t  rectification). alpha=1 means that the rectified image is decimated and shifted so that all\n *\t\t\t\t\t\t\t\t\t\t\t\t  the pixels from the original images from the cameras are retained in the rectified images\n *\t\t\t\t\t\t\t\t\t\t\t\t  (no source image pixels are lost). Obviously, any intermediate value yields an intermediate\n *\t\t\t\t\t\t\t\t\t\t\t\t  result between those two extreme cases.\n * Size newImageSize\t\t\t\t\tInput  -> New image resolution after rectification. The same size should be passed to\n *\t\t\t\t\t\t\t\t\t\t\t\t  initUndistortRectifyMap() (see the stereo_calib.cpp sample in OpenCV samples directory).\n *\t\t\t\t\t\t\t\t\t\t\t\t  When (0,0) is passed (default), it is set to the original imageSize . Setting it to larger\n *\t\t\t\t\t\t\t\t\t\t\t\t  value can help you preserve details in the original image, especially when there is a big\n *\t\t\t\t\t\t\t\t\t\t\t\t  radial distortion.\n * Rect* validPixROI1\t\t\t\t\tOutput -> Optional output rectangles inside the rectified images where all the pixels are valid.\n *\t\t\t\t\t\t\t\t\t\t\t\t  If alpha=0 , the ROIs cover the whole images. Otherwise, they are likely to be smaller.\n * Rect* validPixROI2\t\t\t\t\tOutput -> Optional output rectangles inside the rectified images where all the pixels are valid.\n *\t\t\t\t\t\t\t\t\t\t\t\t  If alpha=0 , the ROIs cover the whole images. Otherwise, they are likely to be smaller.\n *\n * Return value:\t\t\t\t\t\tnone\n */\nvoid stereoRectify2( InputArray _cameraMatrix1, InputArray _distCoeffs1,\n                        InputArray _cameraMatrix2, InputArray _distCoeffs2,\n                        Size imageSize, InputArray _Rmat, InputArray _Tmat,\n                        OutputArray _Rmat1, OutputArray _Rmat2,\n                        OutputArray _Pmat1, OutputArray _Pmat2,\n                        OutputArray _Qmat, int flags,\n                        double alpha, Size newImageSize,\n                        Rect* validPixROI1, Rect* validPixROI2 )\n{\n    Mat cameraMatrix1 = _cameraMatrix1.getMat(), cameraMatrix2 = _cameraMatrix2.getMat();\n    Mat distCoeffs1 = _distCoeffs1.getMat(), distCoeffs2 = _distCoeffs2.getMat();\n    Mat Rmat = _Rmat.getMat(), Tmat = _Tmat.getMat();\n    cv::Mat c_cameraMatrix1 = cameraMatrix1;\n    cv::Mat c_cameraMatrix2 = cameraMatrix2;\n    cv::Mat c_distCoeffs1 = distCoeffs1;\n    cv::Mat c_distCoeffs2 = distCoeffs2;\n    cv::Mat c_R = Rmat, c_T = Tmat;\n\n    int rtype = CV_64F;\n    _Rmat1.create(3, 3, rtype);\n    _Rmat2.create(3, 3, rtype);\n    _Pmat1.create(3, 4, rtype);\n    _Pmat2.create(3, 4, rtype);\n    cv::Mat c_R1 = _Rmat1.getMat(), c_R2 = _Rmat2.getMat(), c_P1 = _Pmat1.getMat(), c_P2 = _Pmat2.getMat();\n    cv::Mat c_Q, *p_Q = nullptr;\n\n    if( _Qmat.needed() )\n    {\n        _Qmat.create(4, 4, rtype);\n        p_Q = &(c_Q = _Qmat.getMat());\n    }\n\n    cvStereoRectify2( &c_cameraMatrix1, &c_cameraMatrix2, &c_distCoeffs1, &c_distCoeffs2,\n        imageSize, &c_R, &c_T, &c_R1, &c_R2, &c_P1, &c_P2, p_Q, flags, alpha,\n        newImageSize, (cv::Rect*)validPixROI1, (cv::Rect*)validPixROI2);\n}\n\n\n/* Slightly changed version of the OpenCV rectification function cvStereoRectify. Check the OpenCV documentation\n * for more information. This function was copied to be able to change a few details on the core functionality of the rectification -\n * especiallly the undistortion functionality to estimate the new virtual cameras.\n *\n * CvMat* _cameraMatrix1\t\t\t\tInput  -> Camera matrix of the first (left) camera\n * CvMat* _cameraMatrix2\t\t\t\tInput  -> Camera matrix of the second (right) camera\n * CvMat* _distCoeffs1\t\t\t\t\tInput  -> Distortion parameters of the first camera\n * CvMat* _distCoeffs2\t\t\t\t\tInput  -> Distortion parameters of the second camera\n * CvSize imageSize\t\t\t\t\t\tInput  -> Size of the original image\n * CvMat* matR\t\t\t\t\t\t\tInput  -> Rotation matrix to specify the 3D rotation from the first to the second camera\n * CvMat* matT\t\t\t\t\t\t\tInput  -> Translation vector specifying the translational direction from the first to the\n *\t\t\t\t\t\t\t\t\t\t\t\t  second camera (the norm of the vector must be 1.0)\n * CvMat* _R1\t\t\t\t\t\t\tOutput -> Rectification transform (rotation matrix) for the first camera\n * CvMat* _R2\t\t\t\t\t\t\tOutput -> Rectification transform (rotation matrix) for the second camera\n * CvMat* _P1\t\t\t\t\t\t\tOutput -> Projection matrix in the new (rectified) coordinate systems for the first camera\n * CvMat* _P2\t\t\t\t\t\t\tOutput -> Projection matrix in the new (rectified) coordinate systems for the second camera\n * CvMat* matQ\t\t\t\t\t\t\tOutput -> Output 4x4 disparity-to-depth mapping matrix (see reprojectImageTo3D() ).\n * int flags\t\t\t\t\t\t\tInput  -> Operation flags that may be zero or CV_CALIB_ZERO_DISPARITY . If the flag is set,\n *\t\t\t\t\t\t\t\t\t\t\t\t  the function makes the principal points of each camera have the same pixel\n *\t\t\t\t\t\t\t\t\t\t\t\t  coordinates in the rectified views. And if the flag is not set, the function may\n *\t\t\t\t\t\t\t\t\t\t\t\t  still shift the images in the horizontal or vertical direction (depending on the\n *\t\t\t\t\t\t\t\t\t\t\t\t  orientation of epipolar lines) to maximize the useful image area.\n * double alpha\t\t\t\t\t\t\tInput  -> Free scaling parameter. If it is -1 or absent, the function performs the default scaling.\n *\t\t\t\t\t\t\t\t\t\t\t\t  Otherwise, the parameter should be between 0 and 1. alpha=0 means that the rectified images\n *\t\t\t\t\t\t\t\t\t\t\t\t  are zoomed and shifted so that only valid pixels are visible (no black areas after\n *\t\t\t\t\t\t\t\t\t\t\t\t  rectification). alpha=1 means that the rectified image is decimated and shifted so that all\n *\t\t\t\t\t\t\t\t\t\t\t\t  the pixels from the original images from the cameras are retained in the rectified images\n *\t\t\t\t\t\t\t\t\t\t\t\t  (no source image pixels are lost). Obviously, any intermediate value yields an intermediate\n *\t\t\t\t\t\t\t\t\t\t\t\t  result between those two extreme cases.\n * CvSize newImgSize\t\t\t\t\tInput  -> New image resolution after rectification. The same size should be passed to\n *\t\t\t\t\t\t\t\t\t\t\t\t  initUndistortRectifyMap() (see the stereo_calib.cpp sample in OpenCV samples directory).\n *\t\t\t\t\t\t\t\t\t\t\t\t  When (0,0) is passed (default), it is set to the original imageSize . Setting it to larger\n *\t\t\t\t\t\t\t\t\t\t\t\t  value can help you preserve details in the original image, especially when there is a big\n *\t\t\t\t\t\t\t\t\t\t\t\t  radial distortion.\n * CvRect* roi1\t\t\t\t\t\t\tOutput -> Optional output rectangles inside the rectified images where all the pixels are valid.\n *\t\t\t\t\t\t\t\t\t\t\t\t  If alpha=0 , the ROIs cover the whole images. Otherwise, they are likely to be smaller.\n * CvRect* roi2\t\t\t\t\t\t\tOutput -> Optional output rectangles inside the rectified images where all the pixels are valid.\n *\t\t\t\t\t\t\t\t\t\t\t\t  If alpha=0 , the ROIs cover the whole images. Otherwise, they are likely to be smaller.\n *\n * Return value:\t\t\t\t\t\tnone\n */\nvoid cvStereoRectify2( const cv::Mat* _cameraMatrix1, const cv::Mat* _cameraMatrix2,\n                      const cv::Mat* _distCoeffs1, const cv::Mat* _distCoeffs2,\n                      const cv::Size& imageSize, const cv::Mat* matR, const cv::Mat* matT,\n                      cv::Mat* _R1, cv::Mat* _R2, cv::Mat* _P1, cv::Mat* _P2,\n                      cv::Mat* matQ, int flags, double alpha, cv::Size newImgSize,\n                      cv::Rect* roi1, cv::Rect* roi2 )\n{\n    double _om[3], _t[3], _uu[3]={0,0,0}, _r_r[3][3], _pp[3][4];\n    double _ww[3], _wr[3][3], _z[3] = {0,0,0}, _ri[3][3];\n    cv::Rect_<float> inner1, inner2, outer1, outer2;\n\n    cv::Mat om  = cv::Mat(3, 1, CV_64F, _om);\n    cv::Mat t   = cv::Mat(3, 1, CV_64F, _t);\n    cv::Mat uu  = cv::Mat(3, 1, CV_64F, _uu);\n    cv::Mat r_r = cv::Mat(3, 3, CV_64F, _r_r);\n    cv::Mat pp  = cv::Mat(3, 4, CV_64F, _pp);\n    cv::Mat ww  = cv::Mat(3, 1, CV_64F, _ww); // temps\n    cv::Mat wR  = cv::Mat(3, 3, CV_64F, _wr);\n    cv::Mat Z   = cv::Mat(3, 1, CV_64F, _z);\n    cv::Mat Ri  = cv::Mat(3, 3, CV_64F, _ri);\n    double nx = imageSize.width, ny = imageSize.height;\n    int i, k;\n\n    if( matR->rows == 3 && matR->cols == 3 )\n        cv::Rodrigues(*matR, om);// get vector rotation\n    else\n        matR->convertTo(om, CV_64F);// it's already a rotation vector\n    om.convertTo(om, CV_64F, -0.5);// get average rotation\n    cv::Rodrigues(om, r_r);// rotate cameras to same orientation by averaging\n    t = r_r * *matT;\n//    cvConvertScale(&om, &om, -0.5); // get average rotation\n//    cvRodrigues2(&om, &r_r);        // rotate cameras to same orientation by averaging\n//    cvMatMul(&r_r, matT, &t);\n\n    unsigned int idx = fabs(_t[0]) > fabs(_t[1]) ? 0 : 1;\n    double c = _t[idx], nt = cv::norm(t, cv::NORM_L2);\n    _uu[idx] = c > 0 ? 1 : -1;\n\n    // calculate global Z rotation\n//    cvCrossProduct(&t,&uu,&ww);\n    ww = t.cross(uu);\n//    double nw = cvNorm(&ww, 0, CV_L2);\n    double nw = cv::norm(ww, cv::NORM_L2);\n    if (nw > 0.0) {\n        ww.convertTo(ww, CV_64F, acos(fabs(c) / nt) / nw);\n//        cvConvertScale(&ww, &ww, acos(fabs(c) / nt) / nw);\n    }\n    cv::Rodrigues(ww, wR);\n//    cvRodrigues2(&ww, &wR);\n\n    // apply to both views\n    Ri = wR * r_r.t();\n    Ri.convertTo(*_R1, _R1->type());\n    Ri = wR * r_r;\n    Ri.convertTo(*_R2, _R2->type());\n    t = Ri * *matT;\n//    cvGEMM(&wR, &r_r, 1, 0, 0, &Ri, CV_GEMM_B_T);\n//    cvConvert( &Ri, _R1 );\n//    cvGEMM(&wR, &r_r, 1, 0, 0, &Ri, 0);\n//    cvConvert( &Ri, _R2 );\n//    cvMatMul(&Ri, matT, &t);\n\n    // calculate projection/camera matrices\n    // these contain the relevant rectified image internal params (fx, fy=fx, cx, cy)\n    auto fc_new = DBL_MAX;\n    std::vector<cv::Point2d> cc_new = std::vector<cv::Point2d>(2, cv::Point2d(0, 0));\n//    CvPoint2D64f cc_new[2] = {{0,0}, {0,0}};\n\n    for( k = 0; k < 2; k++ ) {\n        const cv::Mat* A = k == 0 ? _cameraMatrix1 : _cameraMatrix2;\n        const cv::Mat* Dk = k == 0 ? _distCoeffs1 : _distCoeffs2;\n        double dk1 = Dk ? Dk->at<double>(0) : 0;\n        double fc = A->at<double>(idx^1,idx^1);\n        if( dk1 < 0 ) {\n            fc *= 1 + dk1*(nx*nx + ny*ny)/(4*fc*fc);\n        }\n        fc_new = MIN(fc_new, fc);\n    }\n\n    for( k = 0; k < 2; k++ )\n    {\n        const cv::Mat* A = k == 0 ? _cameraMatrix1 : _cameraMatrix2;\n        const cv::Mat* Dk = k == 0 ? _distCoeffs1 : _distCoeffs2;\n        std::vector<cv::Point2f> _pts(4), _pts_3(4);\n//        CvPoint2D32f _pts[4];\n//        CvPoint3D32f _pts_3[4];\n        cv::Mat pts = cv::Mat(_pts);\n        cv::Mat pts_3 = cv::Mat(_pts_3);\n\n        for( i = 0; i < 4; i++ )\n        {\n            int j = (i<2) ? 0 : 1;\n            _pts[i].x = (float)((i % 2)*(nx-1));\n            _pts[i].y = (float)(j*(ny-1));\n        }\n        { //From OpenCV deviating implementation starts here\n            int valid_nr;\n            double reduction = 0.01;\n            cv::Point2d imgCent = cv::Point2d(nx / 2.0, ny / 2.0);\n            std::vector<cv::Point2f> _pts_sv = _pts;\n//            CvPoint2D64f imgCent = cvPoint2D64f(nx / 2.0, ny / 2.0);\n//            CvPoint2D32f _pts_sv[4];\n//            memcpy(_pts_sv, _pts, 4 * sizeof(CvPoint2D32f));\n            //cv::Mat pts_sv = cv::Mat(1, 4, CV_32FC2, _pts_sv);\n            //pts_sv = cvCloneMat(&pts);\n            do\n            {\n                Mat mask;\n                cvUndistortPoints2( pts, pts, *A, Dk, nullptr, nullptr, mask );\n                valid_nr = cv::countNonZero(mask);\n                if(valid_nr < 4)\n                {\n                    for( i = 0; i < 4; i++ )\n                    {\n                        int j = (i<2) ? 0 : 1;\n                        if(!mask.at<bool>(i))\n                        {\n                            _pts_sv[i].x = _pts[i].x = (float)((floor((1.0 - reduction) * ((i % 2) * nx - imgCent.x)) + imgCent.x - 1));\n                            _pts_sv[i].y = _pts[i].y = (float)((floor((1.0 - reduction) * (j * ny - imgCent.y)) + imgCent.y - 1));\n                        }\n                        else\n                        {\n                            _pts[i].x = _pts_sv[i].x;\n                            _pts[i].y = _pts_sv[i].y;\n                        }\n                    }\n                    reduction += 0.01;\n                }\n            }while((valid_nr < 4) && (reduction < 0.25));\n\n            if(reduction >= 0.25)\n            {\n                Mat mask;\n                cvUndistortPoints2( pts, pts, *A, nullptr, nullptr, nullptr, mask );\n            }\n        } //From OpenCV deviating implementation ends here\n\n\n//        cvConvertPointsHomogeneous( &pts, &pts_3 );\n        cv::convertPointsHomogeneous( pts, pts_3 );\n\n        //Change camera matrix to have cc=[0,0] and fc = fc_new\n        double _a_tmp[3][3];\n        cv::Mat A_tmp  = cv::Mat(3, 3, CV_64F, _a_tmp);\n        _a_tmp[0][0]=fc_new;\n        _a_tmp[1][1]=fc_new;\n        _a_tmp[0][2]=0.0;\n        _a_tmp[1][2]=0.0;\n//        cvProjectPoints2( &pts_3, k == 0 ? _R1 : _R2, &Z, &A_tmp, 0, &pts );\n        cv::projectPoints( pts_3, k == 0 ? *_R1 : *_R2, Z, A_tmp, 0, pts );\n//        CvScalar avg = cvAvg(&pts);\n        cv::Scalar avg = cv::mean(pts);\n        cc_new[k].x = (nx - 1.)/2. - avg[0];\n        cc_new[k].y = (ny - 1.)/2. - avg[1];\n    }\n\n    // vertical focal length must be the same for both images to keep the epipolar constraint\n    // (for horizontal epipolar lines -- TBD: check for vertical epipolar lines)\n    // use fy for fx also, for simplicity\n\n    // For simplicity, set the principal points for both cameras to be the average\n    // of the two principal points (either one of or both x- and y- coordinates)\n    if( flags & cv::CALIB_ZERO_DISPARITY )\n    {\n        cc_new[0].x = cc_new[1].x = (cc_new[0].x + cc_new[1].x)*0.5;\n        cc_new[0].y = cc_new[1].y = (cc_new[0].y + cc_new[1].y)*0.5;\n    }\n    else if( idx == 0 ) // horizontal stereo\n        cc_new[0].y = cc_new[1].y = (cc_new[0].y + cc_new[1].y)*0.5;\n    else // vertical stereo\n        cc_new[0].x = cc_new[1].x = (cc_new[0].x + cc_new[1].x)*0.5;\n\n//    cvZero( &pp );\n    pp.setTo(cv::Scalar::all(0));\n    _pp[0][0] = _pp[1][1] = fc_new;\n    _pp[0][2] = cc_new[0].x;\n    _pp[1][2] = cc_new[0].y;\n    _pp[2][2] = 1.;\n    pp.convertTo(*_P1, _P1->type());\n//    cvConvert(&pp, _P1);\n\n    _pp[0][2] = cc_new[1].x;\n    _pp[1][2] = cc_new[1].y;\n    _pp[idx][3] = _t[idx]*fc_new; // baseline * focal length\n//    cvConvert(&pp, _P2);\n    pp.convertTo(*_P2, _P2->type());\n\n    alpha = std::min(alpha, 1.);\n\n    icvGetRectanglesV0( _cameraMatrix1, _distCoeffs1, _R1, _P1, imageSize, inner1, outer1 );\n    icvGetRectanglesV0( _cameraMatrix2, _distCoeffs2, _R2, _P2, imageSize, inner2, outer2 );\n\n    {\n    newImgSize = newImgSize.width*newImgSize.height != 0 ? newImgSize : imageSize;\n    double cx1_0 = cc_new[0].x;\n    double cy1_0 = cc_new[0].y;\n    double cx2_0 = cc_new[1].x;\n    double cy2_0 = cc_new[1].y;\n    double cx1 = newImgSize.width*cx1_0/imageSize.width;\n    double cy1 = newImgSize.height*cy1_0/imageSize.height;\n    double cx2 = newImgSize.width*cx2_0/imageSize.width;\n    double cy2 = newImgSize.height*cy2_0/imageSize.height;\n    double s = 1.;\n\n    if( alpha >= 0 )\n    {\n        double s0 = std::max(std::max(std::max((double)cx1/(cx1_0 - inner1.x), (double)cy1/(cy1_0 - inner1.y)),\n                            (double)(newImgSize.width - cx1)/(inner1.x + inner1.width - cx1_0)),\n                        (double)(newImgSize.height - cy1)/(inner1.y + inner1.height - cy1_0));\n        s0 = std::max(std::max(std::max(std::max((double)cx2/(cx2_0 - inner2.x), (double)cy2/(cy2_0 - inner2.y)),\n                         (double)(newImgSize.width - cx2)/(inner2.x + inner2.width - cx2_0)),\n                     (double)(newImgSize.height - cy2)/(inner2.y + inner2.height - cy2_0)),\n                 s0);\n\n        double s1 = std::min(std::min(std::min((double)cx1/(cx1_0 - outer1.x), (double)cy1/(cy1_0 - outer1.y)),\n                            (double)(newImgSize.width - cx1)/(outer1.x + outer1.width - cx1_0)),\n                        (double)(newImgSize.height - cy1)/(outer1.y + outer1.height - cy1_0));\n        s1 = std::min(std::min(std::min(std::min((double)cx2/(cx2_0 - outer2.x), (double)cy2/(cy2_0 - outer2.y)),\n                         (double)(newImgSize.width - cx2)/(outer2.x + outer2.width - cx2_0)),\n                     (double)(newImgSize.height - cy2)/(outer2.y + outer2.height - cy2_0)),\n                 s1);\n\n        s = s0*(1. - alpha) + s1*alpha;\n        if((s > 2.) || (s < 0.5)) //added to OpenCV function\n            s = 1.0;\n    }\n\n    fc_new *= s;\n//    cc_new[0] = cvPoint2D64f(cx1, cy1);\n//    cc_new[1] = cvPoint2D64f(cx2, cy2);\n    cc_new[0] = cv::Point2d(cx1, cy1);\n    cc_new[1] = cv::Point2d(cx2, cy2);\n\n    _P1->at<double>(0,0) = fc_new;\n    _P1->at<double>(1,1) = fc_new;\n    _P1->at<double>(0,2) = cx1;\n    _P1->at<double>(1,2) = cy1;\n//    cvmSet(_P1, 0, 0, fc_new);\n//    cvmSet(_P1, 1, 1, fc_new);\n//    cvmSet(_P1, 0, 2, cx1);\n//    cvmSet(_P1, 1, 2, cy1);\n\n    _P2->at<double>(0,0) = fc_new;\n    _P2->at<double>(1,1) = fc_new;\n    _P2->at<double>(0,2) = cx2;\n    _P2->at<double>(1,2) = cy2;\n    _P2->at<double>(idx,3) = s * _P2->at<double>(idx, 3);\n//    cvmSet(_P2, 0, 0, fc_new);\n//    cvmSet(_P2, 1, 1, fc_new);\n//    cvmSet(_P2, 0, 2, cx2);\n//    cvmSet(_P2, 1, 2, cy2);\n//    cvmSet(_P2, idx, 3, s*cvmGet(_P2, idx, 3));\n\n    if(roi1)\n    {\n        *roi1 = cv::Rect((int)std::ceil(((double)inner1.x - cx1_0)*s + cx1),\n                         (int)std::ceil(((double)inner1.y - cy1_0)*s + cy1),\n                         (int)std::floor((double)inner1.width*s),\n                         (int)std::floor((double)inner1.height*s))\n            & cv::Rect(0, 0, newImgSize.width, newImgSize.height);\n    }\n\n    if(roi2)\n    {\n        *roi2 = cv::Rect((int)std::ceil(((double)inner2.x - cx2_0)*s + cx2),\n                         (int)std::ceil(((double)inner2.y - cy2_0)*s + cy2),\n                         (int)std::floor((double)inner2.width*s),\n                         (int)std::floor((double)inner2.height*s))\n            & cv::Rect(0, 0, newImgSize.width, newImgSize.height);\n    }\n    }\n\n    if( matQ )\n    {\n        double q[] =\n        {\n            1, 0, 0, -cc_new[0].x,\n            0, 1, 0, -cc_new[0].y,\n            0, 0, 0, fc_new,\n            0, 0, -1./_t[idx],\n            (idx == 0 ? cc_new[0].x - cc_new[1].x : cc_new[0].y - cc_new[1].y)/_t[idx]\n        };\n        cv::Mat Q = cv::Mat(4, 4, CV_64F, q);\n        Q.convertTo(*matQ, matQ->type());\n//        cvConvert( &Q, matQ );\n    }\n}\n\n/* Slightly changed version of the OpenCV undistortion function cvUndistortPoints. Check the OpenCV documentation\n * for more information. Here a check was added to identify errors during undistortion. Therefore a mask is provided\n * which marks coordinates for which the undistortion was not possible due to a too large error.\n *\n * CvMat* _src\t\t\t\t\t\t\tInput  -> Observed point coordinates (distorted), 1xN or Nx1 2-channel (CV_32FC2 or CV_64FC2).\n * CvMat* dst_\t\t\t\t\t\t\tOutput -> Output ideal point coordinates after undistortion and reverse perspective\n *\t\t\t\t\t\t\t\t\t\t\t\t  transformation. If matrix P is identity or omitted, dst will contain normalized\n *\t\t\t\t\t\t\t\t\t\t\t\t  point coordinates.\n * CvMat* _cameraMatrix\t\t\t\t\tInput  -> Camera matrix\n * CvMat* _distCoeffs\t\t\t\t\tInput  -> Input vector of distortion coefficients (k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6]])\n *\t\t\t\t\t\t\t\t\t\t\t\t  of 4, 5, or 8 elements. If the vector is NULL/empty, the zero distortion coefficients\n *\t\t\t\t\t\t\t\t\t\t\t\t  are assumed.\n * CvMat* matR\t\t\t\t\t\t\tInput  -> Rectification transform (rotation matrix) in the object space (3x3 matrix). R1 or R2\n *\t\t\t\t\t\t\t\t\t\t\t\t  computed by stereoRectify() can be passed here. If the matrix is empty, the identity\n *\t\t\t\t\t\t\t\t\t\t\t\t  transformation is used.\n * CvMat* matP\t\t\t\t\t\t\tInput  -> New camera matrix (3x3) or new projection matrix (3x4). P1 or P2 computed by\n *\t\t\t\t\t\t\t\t\t\t\t\t  stereoRectify() can be passed here. If the matrix is empty, the identity new camera\n *\t\t\t\t\t\t\t\t\t\t\t\t  matrix is used.\n * OutputArray mask\t\t\t\t\t\tOutput -> Mask marking coordinates for which the undistortion was not possible due to a too\n *\t\t\t\t\t\t\t\t\t\t\t\t  large error\n *\n * Return value:\t\t\t\t\t\tnone\n */\nvoid cvUndistortPoints2(const cv::Mat& src_, cv::Mat& dst_, const cv::Mat& cameraMatrix_,\n                        const cv::Mat* distCoeffs_,\n                        const cv::Mat* matR, const cv::Mat* matP, cv::OutputArray mask ) //the mask was added here\n{\n    double A[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}, RR[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}, k[8]={0,0,0,0,0,0,0,0}, fx, fy, ifx, ify, cx, cy;\n    cv::Mat matA=cv::Mat(3, 3, CV_64F, A), Dk_;\n    cv::Mat RR_ =cv::Mat(3, 3, CV_64F, RR);\n    std::vector<cv::Point2d> srcd;\n    int stype, dtype;\n    int sstep;\n    int i, j, n, iters = 1;\n\n    CV_Assert((src_.rows == 1 || src_.cols == 1) &&\n              (dst_.rows == 1 || dst_.cols == 1) &&\n              src_.cols + src_.rows - 1 == dst_.rows + dst_.cols - 1 &&\n              (src_.type() == CV_32FC2 || src_.type() == CV_64FC2) &&\n              (dst_.type() == CV_32FC2 || dst_.type() == CV_64FC2));\n\n    CV_Assert(cameraMatrix_.rows == 3 && cameraMatrix_.cols == 3 );\n\n    cameraMatrix_.convertTo(matA, CV_64F);\n\n    if( distCoeffs_ ){\n        CV_Assert((distCoeffs_->rows == 1 || distCoeffs_->cols == 1) &&\n                  (distCoeffs_->rows * distCoeffs_->cols == 4 ||\n                   distCoeffs_->rows * distCoeffs_->cols == 5 ||\n                   distCoeffs_->rows * distCoeffs_->cols == 8));\n\n        Dk_ = cv::Mat(distCoeffs_->rows, distCoeffs_->cols, CV_64FC(distCoeffs_->channels()), k);\n\n        distCoeffs_->convertTo(Dk_, CV_64F);\n        iters = 5;\n    }\n\n    if( matR ){\n        CV_Assert( matR->rows == 3 && matR->cols == 3 );\n        matR->convertTo(RR_, CV_64F);\n    }\n    else{\n        RR_ = cv::Mat::eye(3, 3, CV_64FC1);\n    }\n\n    if( matP ){\n        double PP[3][3];\n        cv::Mat PP_=cv::Mat(3, 3, CV_64F, PP);\n        CV_Assert( matP->rows == 3 && (matP->cols == 3 || matP->cols == 4));\n        matP->colRange(0,3).convertTo(PP_, CV_64F);\n        RR_ = PP_ * RR_;\n    }\n\n    stype = src_.type();\n    sstep = src_.rows == 1 ? 1 : src_.step / CV_ELEM_SIZE(stype);\n    src_.reshape(2).convertTo(srcd, CV_64F);\n    if(dst_.empty()){\n        src_.copyTo(dst_);\n    }\n    dtype = dst_.type();\n\n    n = static_cast<int>(srcd.size());\n\n    fx = A[0][0];\n    fy = A[1][1];\n    ifx = 1./fx;\n    ify = 1./fy;\n    cx = A[0][2];\n    cy = A[1][2];\n\n    //Generate a mask to check if the undistortion generates valid results\n    mask.create(1,n,CV_8UC1);\n    Mat _mask = mask.getMat();\n    _mask = cv::Mat::ones(1,n,CV_8UC1);\n\n    for( i = 0; i < n; i++ )\n    {\n        double x, y, x0, y0;\n        x = srcd[i].x;\n        y = srcd[i].y;\n\n        x0 = x = (x - cx)*ifx;\n        y0 = y = (y - cy)*ify;\n\n        // compensate distortion iteratively\n        for( j = 0; j < iters; j++ )\n        {\n            double r2 = x*x + y*y;\n            double icdist = (1. + ((k[7]*r2 + k[6])*r2 + k[5])*r2)/(1. + ((k[4]*r2 + k[1])*r2 + k[0])*r2);\n            double deltaX = 2. * k[2]*x*y + k[3]*(r2 + 2. * x*x);\n            double deltaY = k[2]*(r2 + 2. * y*y) + 2. * k[3]*x*y;\n            x = (x0 - deltaX)*icdist;\n            y = (y0 - deltaY)*icdist;\n        }\n\n        //check the error of the undistortion\n        {\n            Point2f proofdist;\n            double r2 = x*x + y*y;\n            double icdist = (1. + ((k[4]*r2 + k[1])*r2 + k[0])*r2)/(1. + ((k[7]*r2 + k[6])*r2 + k[5])*r2);\n            double deltaX = 2. * k[2]*x*y + k[3]*(r2 + 2. * x*x);\n            double deltaY = k[2]*(r2 + 2. * y*y) + 2. * k[3]*x*y;\n            proofdist.x = x * icdist + deltaX - x0;\n            proofdist.y = y * icdist + deltaY - y0;\n            if( std::sqrt(proofdist.x * proofdist.x + proofdist.y * proofdist.y) > 0.25)\n                _mask.at<bool>(i) = false;\n        }\n\n        double xx = RR[0][0]*x + RR[0][1]*y + RR[0][2];\n        double yy = RR[1][0]*x + RR[1][1]*y + RR[1][2];\n        double ww = 1./(RR[2][0]*x + RR[2][1]*y + RR[2][2]);\n        x = xx*ww;\n        y = yy*ww;\n\n        if( dtype == CV_32FC2 )\n        {\n            dst_.at<float>(i * 2) = static_cast<float>(x);\n            dst_.at<float>(i * 2 + 1) = static_cast<float>(y);\n        }\n        else\n        {\n            dst_.at<double>(i * 2) = x;\n            dst_.at<double>(i * 2 + 1) = y;\n        }\n    }\n}\n\n/* Estimates the inner rectangle of a distorted image containg only valid/available image information and an outer rectangle countaing all\n * image information. This function was copied from the OpenCV (calibration.cpp) and modified such that the image coordinates used for\n * undistortion are checked afterwards to be valid. If not, the initial coordinates are changed as long as only valid undistorted\n * coordinates are used.\n *\n * CvMat* cameraMatrix\t\t\t\t\tInput  -> Original camera matrix\n * CvMat* distCoeffs\t\t\t\t\tInput  -> Distortion parameters of the camera\n * CvMat* R\t\t\t\t\t\t\t\tInput  -> Rectification transform (rotation matrix) for the camera\n * CvMat* newCameraMatrix\t\t\t\tInput  -> Camera matrix of the new (virtual) camera\n * CvSize imgSize\t\t\t\t\t\tInput  -> Size of the original image\n * Rect_<float>& inner\t\t\t\t\tOutput -> Inner rectangle containing only valid image information\n * Rect_<float>& outer\t\t\t\t\tOutput -> Outer rectangle containing all the image information\n *\n * Return value:\t\t\t\t\t\tnone\n */\nvoid icvGetRectanglesV0( const cv::Mat* cameraMatrix, const cv::Mat* distCoeffs,\n                 const cv::Mat* R, const cv::Mat* newCameraMatrix, const cv::Size& imgSize,\n                 cv::Rect_<float>& inner, cv::Rect_<float>& outer )\n{\n    const int N = 9;\n    int x, y, k;\n//    cv::Ptr<cv::Mat> _pts = cvCreateMat(1, N*N, CV_32FC2);\n    cv::Mat _pts = Mat(1, N*N, CV_32FC2);\n    std::vector<cv::Point2f> pts = (std::vector<cv::Point2f>)(_pts.reshape(2));\n//    CvPoint2D32f* pts = (CvPoint2D32f*)(_pts->data.ptr);\n\n    for( y = k = 0; y < N; y++ )\n        for( x = 0; x < N; x++ )\n            pts[k++] = cv::Point2f((float)x*imgSize.width/(N-1),\n                                   (float)y*imgSize.height/(N-1));\n\n    { //From OpenCV deviating implementation starts here\n        int valid_nr;\n        float reduction = 0.01f;\n        cv::Point2f imgCent = cv::Point2f((float)imgSize.width / 2.f,(float)imgSize.height / 2.f);\n        std::vector<cv::Point2f> pts_sv = pts;\n//        memcpy(pts_sv, pts, N * N * sizeof(CvPoint2D32f));\n        do\n        {\n            Mat mask;\n            cvUndistortPoints2(_pts, _pts, *cameraMatrix, distCoeffs, R, newCameraMatrix, mask);\n            valid_nr = cv::countNonZero(mask);\n            if(valid_nr < N*N)\n            {\n                for( y = k = 0; y < N; y++ )\n                    for( x = 0; x < N; x++ )\n                    {\n                        if(!mask.at<bool>(k))\n                            pts_sv[k] = pts[k] = cv::Point2f((1.0 - reduction) * ((float)x*imgSize.width/(N-1) - imgCent.x) + imgCent.x,\n                                                              (1.0 - reduction) * ((float)y*imgSize.height/(N-1) - imgCent.y) + imgCent.y);\n                        else\n                            pts[k] = pts_sv[k];\n                        k++;\n                    }\n                reduction += 0.01f;\n            }\n        }while((valid_nr < N*N) && (reduction < 0.25));\n\n        if(reduction >= 0.25)\n        {\n            Mat mask;\n            cvUndistortPoints2(_pts, _pts, *cameraMatrix, nullptr, R, newCameraMatrix, mask);\n        }\n    } //From OpenCV deviating implementation ends here\n\n    float iX0=-FLT_MAX, iX1=FLT_MAX, iY0=-FLT_MAX, iY1=FLT_MAX;\n    float oX0=FLT_MAX, oX1=-FLT_MAX, oY0=FLT_MAX, oY1=-FLT_MAX;\n    // find the inscribed rectangle.\n    // the code will likely not work with extreme rotation matrices (R) (>45%)\n    for( y = k = 0; y < N; y++ )\n        for( x = 0; x < N; x++ )\n        {\n            cv::Point2f p = pts[k++];\n            oX0 = min(oX0, p.x);\n            oX1 = max(oX1, p.x);\n            oY0 = min(oY0, p.y);\n            oY1 = max(oY1, p.y);\n\n            if( x == 0 )\n                iX0 = max(iX0, p.x);\n            if( x == N-1 )\n                iX1 = min(iX1, p.x);\n            if( y == 0 )\n                iY0 = max(iY0, p.y);\n            if( y == N-1 )\n                iY1 = min(iY1, p.y);\n        }\n    inner = cv::Rect_<float>(iX0, iY0, iX1-iX0, iY1-iY0);\n    outer = cv::Rect_<float>(oX0, oY0, oX1-oX0, oY1-oY0);\n}\n\n/* Estimates the vergence (shift of starting point) for correspondence search in the stereo engine. To get the right values, the\n * first camera centre must be at the orign of the coordinate system.\n *\n * Mat R\t\t\t\t\t\t\t\tInput  -> Rotation matrix between the cameras.\n * Mat RR1\t\t\t\t\t\t\t\tInput  -> Rectification transform (rotation matrix) for the first camera\n * Mat RR2\t\t\t\t\t\t\t\tInput  -> Rectification transform (rotation matrix) for the second camera\n * Mat PR1\t\t\t\t\t\t\t\tInput  -> Camera (Projection) matrix in the new (rectified) coordinate systems for the first camera\n * Mat PR2\t\t\t\t\t\t\t\tInput  -> Camera (Projection) matrix in the new (rectified) coordinate systems for the second camera\n *\n * Return value:\t\t\t\t\t\tVergence\n */\nint estimateVergence(const cv::Mat& R, const cv::Mat& RR1, const cv::Mat& RR2, const cv::Mat& PR1, const cv::Mat& PR2)\n{\n    Mat a = R.row(2).t();\n    Mat K1 = PR1.colRange(0,3);\n    Mat K2 = PR2.colRange(0,3);\n    Mat ar1 = K1 * RR1 * a;\n    Mat ar2 = K2 * RR2.col(2);\n    ar1 = ar1 / ar1.at<double>(2);\n    ar2 = ar2 / ar2.at<double>(2);\n    double vergence = ar1.at<double>(0) - ar2.at<double>(0);\n    if(nearZero(vergence))\n        return 0;\n    vergence = std::ceil(1.1 * vergence);\n\n    if(vergence < 0.0)\n        cout << \"Vergence is negative!\" << endl;\n\n    return (int)vergence;\n}\n\n\n/* Estimates the optimal scale for the focal length of the virtuel camera. This is a slightly changed version of the same functionality\n * implemented in the function cvStereoRectify of the OpenCV. In contrast to the original OpenCV function, the result of the undistortion\n * is checked to be valid.\n *\n * double alpha\t\t\t\t\t\t\tInput  -> Free scaling parameter. If it is -1 or absent, the function performs the default scaling.\n *\t\t\t\t\t\t\t\t\t\t\t\t  Otherwise, the parameter should be between 0 and 1. alpha=0 means that the rectified images\n *\t\t\t\t\t\t\t\t\t\t\t\t  are zoomed and shifted so that only valid pixels are visible (no black areas after\n *\t\t\t\t\t\t\t\t\t\t\t\t  rectification). alpha=1 means that the rectified image is decimated and shifted so that all\n *\t\t\t\t\t\t\t\t\t\t\t\t  the pixels from the original images from the cameras are retained in the rectified images\n *\t\t\t\t\t\t\t\t\t\t\t\t  (no source image pixels are lost). Obviously, any intermediate value yields an intermediate\n *\t\t\t\t\t\t\t\t\t\t\t\t  result between those two extreme cases.\n * Mat K1\t\t\t\t\t\t\t\tInput  -> Camera matrix of the first (left) camera\n * Mat K2\t\t\t\t\t\t\t\tInput  -> Camera matrix of the second (right) camera\n * Mat R1\t\t\t\t\t\t\t\tInput  -> Rectification transform (rotation matrix) for the first camera\n * Mat R2\t\t\t\t\t\t\t\tInput  -> Rectification transform (rotation matrix) for the second camera\n * Mat P1\t\t\t\t\t\t\t\tInput  -> Camera (Projection) matrix in the new (rectified) coordinate systems for the first camera\n * Mat P2\t\t\t\t\t\t\t\tInput  -> Camera (Projection) matrix in the new (rectified) coordinate systems for the second camera\n * Mat dist1\t\t\t\t\t\t\tInput  -> Distortion parameters of the first camera\n * Mat dist2\t\t\t\t\t\t\tInput  -> Distortion parameters of the second camera\n * Size imageSize\t\t\t\t\t\tInput  -> Size of the original image\n * Size newImageSize\t\t\t\t\tInput  -> Size of the new image (from the virtual camera)\n *\n * Return value:\t\t\t\t\t\tScaling parameter for the focal length\n */\ndouble estimateOptimalFocalScale(double alpha, cv::Mat K1, cv::Mat K2, cv::Mat R1, cv::Mat R2, cv::Mat P1, cv::Mat P2,\n                                 cv::Mat dist1, cv::Mat dist2, const cv::Size& imageSize, cv::Size newImgSize)\n{\n    alpha = MIN(alpha, 1.);\n\n    cv::Mat _cameraMatrix1 = K1;\n    cv::Mat _cameraMatrix2 = K2;\n    cv::Mat _distCoeffs1 = dist1;\n    cv::Mat _distCoeffs2 = dist2;\n    cv::Mat _R1 = R1;\n    cv::Mat _R2 = R2;\n    cv::Mat _P1 = P1;\n    cv::Mat _P2 = P2;\n\n    cv::Rect_<float> inner1, inner2, outer1, outer2;\n\n    icvGetRectanglesV0( &_cameraMatrix1, &_distCoeffs1, &_R1, &_P1, imageSize, inner1, outer1 );\n    icvGetRectanglesV0( &_cameraMatrix2, &_distCoeffs2, &_R2, &_P2, imageSize, inner2, outer2 );\n\n    newImgSize = newImgSize.width*newImgSize.height != 0 ? newImgSize : imageSize;\n    double cx1_0 = K1.at<double>(0,2);\n    double cy1_0 = K1.at<double>(1,2);\n    double cx2_0 = K2.at<double>(0,2);\n    double cy2_0 = K2.at<double>(1,2);\n    double cx1 = newImgSize.width*cx1_0/imageSize.width;\n    double cy1 = newImgSize.height*cy1_0/imageSize.height;\n    double cx2 = newImgSize.width*cx2_0/imageSize.width;\n    double cy2 = newImgSize.height*cy2_0/imageSize.height;\n    double s = 1.;\n\n    if( alpha >= 0 )\n    {\n        double s0 = std::max(std::max(std::max((double)cx1/(cx1_0 - inner1.x), (double)cy1/(cy1_0 - inner1.y)),\n                            (double)(newImgSize.width - cx1)/(inner1.x + inner1.width - cx1_0)),\n                        (double)(newImgSize.height - cy1)/(inner1.y + inner1.height - cy1_0));\n        s0 = std::max(std::max(std::max(std::max(cx2/(cx2_0 - (double)inner2.x), cy2/(cy2_0 - (double)inner2.y)),\n                         ((double)newImgSize.width - cx2)/((double)inner2.x + (double)inner2.width - cx2_0)),\n                     ((double)newImgSize.height - cy2)/((double)inner2.y + (double)inner2.height - cy2_0)),\n                 s0);\n\n        double s1 = std::min(std::min(std::min((double)cx1/(cx1_0 - outer1.x), (double)cy1/(cy1_0 - outer1.y)),\n                            (double)(newImgSize.width - cx1)/(outer1.x + outer1.width - cx1_0)),\n                        (double)(newImgSize.height - cy1)/(outer1.y + outer1.height - cy1_0));\n        s1 = std::min(std::min(std::min(std::min((double)cx2/(cx2_0 - outer2.x), (double)cy2/(cy2_0 - outer2.y)),\n                         (double)(newImgSize.width - cx2)/(outer2.x + outer2.width - cx2_0)),\n                     (double)(newImgSize.height - cy2)/(outer2.y + outer2.height - cy2_0)),\n                 s1);\n\n        s = s0*(1 - alpha) + s1*alpha;\n    }\n\n    return s;\n}\n\n/* This function shows the rectified images\n *\n * InputArray img1\t\t\t\tInput  -> Image from the first camera\n * InputArray img2\t\t\t\tInput  -> Image from the second camera\n * InputArray mapX1\t\t\t\tInput  -> Rectification map for the x-coordinates of the first image\n * InputArray mapY1\t\t\t\tInput  -> Rectification map for the y-coordinates of the first image\n * InputArray mapX2\t\t\t\tInput  -> Rectification map for the x-coordinates of the second image\n * InputArray mapY2\t\t\t\tInput  -> Rectification map for the y-coordinates of the second image\n * InputArray t\t\t\t\t\t\tInput  -> Translation vector of the pose. Take translation vector for\n *\t\t\t\t\t\t\t\t\t\t\t  mapping a position of the left camera x to the a position of\n *\t\t\t\t\t\t\t\t\t\t\t  the right camera x' (x' = R^T * x - R^T * t0) with t0 the\n *\t\t\t\t\t\t\t\t\t\t\t  translation vector after pose estimation and t = -1 * R^T * t0\n *\t\t\t\t\t\t\t\t\t\t\t  the translation vector that should be provided.\n * Size newImgSize\t\t\t\tInput  -> Size of the new image (must be the same as specified at the\n *\t\t\t\t\t\t\t\t\t\t\t  rectification function and initUndistortRectifyMap()). If not\n *\t\t\t\t\t\t\t\t\t\t\t  specified, the same size from the input images is used.\n * string path            Input -> output path for rectified images (e.g.: c:\\temp\\results)\n *                        if \"\", no images are saved\n *\n * Return:\t\t\t\t\t\t\t0:\t\t  Success\n */\nint ShowRectifiedImages(cv::InputArray img1,\n                        cv::InputArray img2,\n                        cv::InputArray mapX1,\n                        cv::InputArray mapY1,\n                        cv::InputArray mapX2,\n                        cv::InputArray mapY2,\n                        cv::InputArray t,\n                        const std::string& path,\n                        const std::string& imgName1,\n                        const std::string& imgName2,\n                        bool showResult,\n                        cv::Size newImgSize)\n{\n    CV_Assert(!img1.empty() && !img2.empty() && !mapX1.empty() && !mapY1.empty() && !mapX2.empty() && !mapY2.empty() && !t.empty());\n    CV_Assert((img1.rows() == img2.rows()) && (img1.cols() == img2.cols()));\n\n    if(newImgSize == cv::Size())\n    {\n        newImgSize = img1.size();\n    }\n\n    Mat _t;\n    _t = t.getMat();\n\n    Mat imgRect1, imgRect2, composed, comCopy;\n    remap(img1, imgRect1, mapX1, mapY1, cv::BORDER_CONSTANT);\n    remap(img2, imgRect2, mapX2, mapY2, cv::BORDER_CONSTANT);\n\n    cv::namedWindow(\"Rectification\");\n\n    // save rectified images\n    if (!path.empty())\n    {\n        string path1;\n        if(path.rfind('/') + 1 == path.size()){\n            path1 = path;\n        }else{\n            path1 = path + \"/\";\n        }\n        std::string namel, namer;\n        if(imgName1.empty() || imgName2.empty()) {\n            static int count = 0;\n            char buffer[15];\n            sprintf(buffer, \"left_%04d.jpg\", count);\n            namel = path1 + buffer;\n            sprintf(buffer, \"right_%04d.jpg\", count);\n            namer = path1 + buffer;\n            count++;\n        }else{\n            namel = path1 + imgName1 + \".jpg\";\n            namer = path1 + imgName2 + \".jpg\";\n        }\n\n        cv::imwrite(namel, imgRect1);\n        cv::imwrite(namer, imgRect2);\n    }\n\n    if(showResult) {\n        int maxHorImgSize, maxVerImgSize;\n        int r, c;\n        int rc;\n        if (std::abs(_t.at<double>(0)) > std::abs(_t.at<double>(1))) {\n            r = 1;\n            c = 2;\n            rc = 1;\n            if (_t.at<double>(0) < 0) {\n                Mat imgRect1_tmp;\n                imgRect1_tmp = imgRect1.clone();\n                imgRect1 = imgRect2.clone();\n                imgRect2 = imgRect1_tmp.clone();\n            }\n        } else {\n            r = 2;\n            c = 1;\n            rc = 0;\n            if (_t.at<double>(1) > 0) {\n                Mat imgRect1_tmp;\n                imgRect1_tmp = imgRect1.clone();\n                imgRect1 = imgRect2.clone();\n                imgRect2 = imgRect1_tmp.clone();\n            }\n        }\n\n        //Allocate memory for composed image\n        maxHorImgSize = 800;\n        if (newImgSize.width > maxHorImgSize) {\n            maxVerImgSize = (int) ((float) maxHorImgSize * (float) newImgSize.height / (float) newImgSize.width);\n            composed = cv::Mat(cv::Size(maxHorImgSize * c, maxVerImgSize * r), CV_8UC3);\n            comCopy = cv::Mat(cv::Size(maxHorImgSize, maxVerImgSize), CV_8UC3);\n        } else {\n            composed = cv::Mat(cv::Size(newImgSize.width * c, newImgSize.height * r), CV_8UC3);\n            comCopy = cv::Mat(cv::Size(newImgSize.width, newImgSize.height), CV_8UC3);\n        }\n\n        // create images to display\n        string str;\n        vector<cv::Mat> show_rect(2);\n        cv::cvtColor(imgRect1, show_rect[0], cv::COLOR_GRAY2RGB);\n        cv::cvtColor(imgRect2, show_rect[1], cv::COLOR_GRAY2RGB);\n        for (int j = 0; j < 2; j++) {\n            cv::resize(show_rect[j], comCopy, cv::Size(comCopy.cols, comCopy.rows));\n            if (j == 0) str = \"CAM 1\";\n            else str = \"CAM 2\";\n            cv::putText(comCopy, str, cv::Point2d(25, 25), cv::FONT_HERSHEY_SIMPLEX | cv::FONT_ITALIC, 0.7,\n                        cv::Scalar(0, 0, 255));\n            comCopy.copyTo(\n                    composed(cv::Rect(j * rc * comCopy.cols, j * (rc ^ 1) * comCopy.rows, comCopy.cols, comCopy.rows)));\n        }\n\n        cv::setMouseCallback(\"Rectification\", on_mouse_move, (void *) (&composed));\n        cv::imshow(\"Rectification\", composed);\n        cv::waitKey(0);\n        cv::destroyWindow(\"Rectification\");\n    }\n\n    return 0;\n}\n\n/* This function returns the rectified images\n *\n * InputArray img1\t\t\t\tInput  -> Image from the first camera\n * InputArray img2\t\t\t\tInput  -> Image from the second camera\n * InputArray mapX1\t\t\t\tInput  -> Rectification map for the x-coordinates of the first image\n * InputArray mapY1\t\t\t\tInput  -> Rectification map for the y-coordinates of the first image\n * InputArray mapX2\t\t\t\tInput  -> Rectification map for the x-coordinates of the second image\n * InputArray mapY2\t\t\t\tInput  -> Rectification map for the y-coordinates of the second image\n * InputArray t\t\t\t\t\t\tInput  -> Translation vector of the pose. Take translation vector for\n *\t\t\t\t\t\t\t\t\t\t\t  mapping a position of the left camera x to the a position of\n *\t\t\t\t\t\t\t\t\t\t\t  the right camera x' (x' = R^T * x - R^T * t0) with t0 the\n *\t\t\t\t\t\t\t\t\t\t\t  translation vector after pose estimation and t = -1 * R^T * t0\n *\t\t\t\t\t\t\t\t\t\t\t  the translation vector that should be provided.\n * OutputArray outImg1\t\t\tOutput -> Rectified Image from the first camera\n * OutputArray outImg2\t\t\tOutput -> Rectified Image from the second camera\n * Size newImgSize\t\t\t\tInput  -> Size of the new image (must be the same as specified at the\n *\t\t\t\t\t\t\t\t\t\t\t  rectification function and initUndistortRectifyMap()). If not\n *\t\t\t\t\t\t\t\t\t\t\t  specified, the same size from the input images is used.\n *\n * Return:\t\t\t\t\t\t\t0:\t\t  Success\n */\nint GetRectifiedImages(cv::InputArray img1, cv::InputArray img2, cv::InputArray mapX1, cv::InputArray mapY1, cv::InputArray mapX2, cv::InputArray mapY2, cv::InputArray t, cv::OutputArray outImg1, cv::OutputArray outImg2, cv::Size newImgSize)\n{\n    CV_Assert(!img1.empty() && !img2.empty() && !mapX1.empty() && !mapY1.empty() && !mapX2.empty() && !mapY2.empty() && !t.empty());\n    CV_Assert((img1.rows() == img2.rows()) && (img1.cols() == img2.cols()));\n\n    if(newImgSize == cv::Size())\n    {\n        newImgSize = img1.size();\n    }\n\n    Mat _t;\n    _t = t.getMat();\n\n    Mat composed, comCopy;\n    remap(img1, outImg1, mapX1, mapY1, cv::INTER_LINEAR, cv::BORDER_CONSTANT);\n    remap(img2, outImg2, mapX2, mapY2, cv::INTER_LINEAR, cv::BORDER_CONSTANT);\n\n    return 0;\n}\n\n/*------------------------------------------------------------------------------------------\nFunctionname: on_mouse_move\nParameters: refer to OpenCV documentation (cvSetMouseCallback())\nReturn: none\nDescription: draws crosslines over images saved in Mat* composed from int ShowRectifiedImages(...)\n------------------------------------------------------------------------------------------*/\nvoid on_mouse_move(int event, int x, int y, int flags, void* param)\n{\n    Mat composed = *((Mat*)param);\n    Mat tmpCopy = cv::Mat(cv::Size(composed.cols, composed.rows), CV_8UC3);\n    composed.copyTo(tmpCopy);\n    cv::line(tmpCopy, cv::Point2d(0, y), cv::Point2d(tmpCopy.cols, y), cv::Scalar(0, 0, 255));\n    cv::line(tmpCopy, cv::Point2d(x, 0), cv::Point2d(x, tmpCopy.rows), cv::Scalar(0, 0, 255));\n    cv::imshow(\"Rectification\", tmpCopy);\n    bool isAlive = cv::getWindowProperty(\"Rectification\", WND_PROP_VISIBLE) >= 1. - DBL_EPSILON;\n    if(isAlive) {\n        std::this_thread::sleep_for(std::chrono::milliseconds(33));\n    }\n//    cv::waitKey(4);\n}\n\n/* This function estimates an initial delta value for the SPRT test used within USAC.\n* It estimates the initial propability of a keypoint to be classified as an inlier of\n* an invalid model (e.g. essential matrix). This initial value is estimated dividing the\n* area around the longest possible epipolar line e (length of e * 2 * inlier threshold) by\n* the area of the convex hull defined by the found correspondences.\n*\n* vector<DMatch> matches\t\tInput  -> Matches (ascending queries)\n* vector<KeyPoint> kp1\t\t\tInput  -> Keypoints in the left/first image\n* vector<KeyPoint> kp2\t\t\tInput  -> Keypoints in the right/second image\n* double th\t\t\t\t\t\tInput  -> Inlier threshold in pixels\n* Size imgSize\t\t\t\t\tInput  -> Size of the image\n*\n* Return:\t\t\t\t\t\tinitial delta for SPRT\n*/\ndouble estimateSprtDeltaInit(const std::vector<cv::DMatch> &matches,\n                             const std::vector<cv::KeyPoint> &kp1,\n                             const std::vector<cv::KeyPoint> &kp2,\n                             const double &th,\n                             const cv::Size &imgSize)\n{\n    //Extract coordinates from keypoints\n    vector<cv::Point2f> points1, points2;\n    vector<cv::Point2f> hull1, hull2;\n    double area[2] = { 0, 0 };\n    double maxEpipoleArea = 0, sprt_delta = 0;\n    for (auto matche : matches)\n    {\n        points1.push_back(kp1[matche.queryIdx].pt);\n        points2.push_back(kp2[matche.trainIdx].pt);\n    }\n\n    //Convex hull of the keypoints\n    cv::convexHull(points1, hull1);\n    cv::convexHull(points2, hull2);\n\n    //Area of the convex hull\n    area[0] = cv::contourArea(hull1);\n    area[1] = cv::contourArea(hull2);\n    area[0] = area[0] > area[1] ? area[1] : area[0];\n\n    //max length of an epipolar line within image\n    maxEpipoleArea = std::sqrt((double)(imgSize.width * imgSize.width + imgSize.height * imgSize.height));\n    //max area for a keypoint to be classified as inlier\n    maxEpipoleArea *= 2 * th;\n    area[0] = area[0] < (6 * maxEpipoleArea) ? (6 * maxEpipoleArea) : area[0];\n    sprt_delta = maxEpipoleArea / area[0];\n    sprt_delta = sprt_delta < 0.001 ? 0.001 : sprt_delta;\n\n    return sprt_delta;\n}\n\n/* This function estimates an initial epsilon value for the SPRT test used within USAC.\n* It estimates the probability that a data point is consistent with a good model (e.g. essential matrix)\n* which corresponds approximately to the inlier ratio. To estimate the inlier ratio, VFC has to be applied\n* to the matches which should reject most false matches (additionally removes matches at borders) as the\n* filtering only allows smooth changes of the optical flow. VFC does not work well for low inlier ratios.\n* Thus, the inlier ratio is bounded between 0.1 and 0.75.\n*\n* vector<DMatch> matches\t\t\t\tInput  -> Matches\n* unsigned int nrMatchesVfcFiltered\t\tInput  -> Number of remaining matches after filtering with VFC\n*\n* Return:\t\t\t\t\t\tinitial epsilon for SPRT\n*/\ndouble estimateSprtEpsilonInit(const std::vector<cv::DMatch> &matches, const unsigned int &nrMatchesVfcFiltered)\n{\n    auto nrMatches = (double)matches.size();\n    double epsilonInit = 0.8 * (double)nrMatchesVfcFiltered / nrMatches;\n    epsilonInit = epsilonInit > 0.4 ? 0.4 : epsilonInit;\n    epsilonInit = epsilonInit < 0.1 ? 0.1 : epsilonInit;\n\n    return epsilonInit;\n}\n\n/* This function generates an index of the matches with the lowest matching costs first. It is used\n* within PROSAC of the USAC framework. To work correctly, the order of the queries within \"matches\"\n* should be ascending. The used correspondences within USAC must be in the same order than \"matches\".\n*\n* vector<DMatch> matches\t\t\t\tInput  -> Matches\n* unsigned int nrMatchesVfcFiltered\t\tOutput -> Indices of matches sorted corresponding to the\n*\t\t\t\t\t\t\t\t\t\t\t\t  matching costs in ascending order\n*\n* Return:\t\t\t\t\t\tnone\n*/\nvoid getSortedMatchIdx(std::vector<cv::DMatch> matches, std::vector<unsigned int> & sortedMatchIdx)\n{\n    size_t i = 0;\n    for (i = 0; i < matches.size(); i++)\n    {\n        if (matches[i].queryIdx != static_cast<int>(i))\n            break;\n    }\n    if (i < matches.size())\n    {\n        for (i = 0; i < matches.size(); i++)\n        {\n            matches[i].queryIdx = static_cast<int>(i);\n        }\n    }\n\n    std::sort(matches.begin(), matches.end(), [](cv::DMatch const & first, cv::DMatch const & second) {\n        return first.distance < second.distance; });\n\n    sortedMatchIdx.resize(matches.size());\n    for (i = 0; i < matches.size(); i++)\n    {\n        sortedMatchIdx[i] = (unsigned int)matches[i].queryIdx;\n    }\n}\n\n/* Checks if a 3x3 matrix is a rotation matrix\n*\n* cv::Mat R\t\t\t\tInput  -> Rotation matrix\n*\n* Return:\t\t\t\ttrue or false\n*/\nbool isMatRoationMat(const cv::Mat& R)\n{\n    CV_Assert(!R.empty());\n\n    Eigen::Matrix3d Re;\n    cv::cv2eigen(R, Re);\n\n    return isMatRoationMat(Re);\n}\n\n/* Checks if a 3x3 matrix is a rotation matrix\n*\n* Matrix3d R\t\t\tInput  -> Rotation matrix\n*\n* Return:\t\t\t\ttrue or false\n*/\nbool isMatRoationMat(Eigen::Matrix3d R)\n{\n    //Check if R is a rotation matrix\n    Eigen::Matrix3d R_check = (R.transpose() * R) - Eigen::Matrix3d::Identity();\n    double r_det = R.determinant() - 1.0;\n\n    return R_check.isZero(1e-3) && poselib::nearZero(r_det);\n}\n\n/* Calculates the Sampson L2 error for 1 correspondence\n*\n* InputArray E\t\t\tInput  -> Essential matrix\n* InputArray x1\t\t\tInput  -> First point correspondence\n* InputArray x2\t\t\tInput  -> Second point correspondence\n*\n* Return:\t\t\t\tSampson L2 error\n*/\ndouble getSampsonL2Error(cv::InputArray E, cv::InputArray x1, cv::InputArray x2)\n{\n    CV_Assert(x1.rows() == x2.rows() && x1.cols() == x2.cols() && ((x1.cols() < 4 && x1.rows() == 1) || (x1.cols() == 1 && x1.rows() < 4)) && x1.type() == CV_64FC1 && x2.type() == CV_64FC1);\n    Eigen::Vector3d x1e, x2e;\n    Eigen::Matrix3d Ee;\n    cv::Mat x1_ = cv::Mat::ones(3, 1, CV_64FC1);\n    cv::Mat x2_ = cv::Mat::ones(3, 1, CV_64FC1);\n    if (x1.cols() > x1.rows())\n    {\n        if (x1.cols() == 2)\n        {\n            x1_.rowRange(0, 2) = x1.getMat().t();\n            x2_.rowRange(0, 2) = x2.getMat().t();\n        }\n        else\n        {\n            x1_ = x1.getMat().t();\n            x2_ = x2.getMat().t();\n        }\n    }\n    else\n    {\n        if (x1.rows() == 2)\n        {\n            x1_.rowRange(0, 2) = x1.getMat();\n            x2_.rowRange(0, 2) = x2.getMat();\n        }\n        else\n        {\n            x1_ = x1.getMat();\n            x2_ = x2.getMat();\n        }\n    }\n    cv::cv2eigen(E.getMat(), Ee);\n    cv::cv2eigen(x1_, x1e);\n    cv::cv2eigen(x2_, x2e);\n    return getSampsonL2Error(Ee, x1e, x2e);\n}\n\n/* Calculates the Sampson L2 error for 1 correspondence\n*\n* Matrix3d E\t\t\tInput  -> Essential matrix\n* Vector3d x1\t\t\tInput  -> First point correspondence\n* Vector3d x2\t\t\tInput  -> Second point correspondence\n*\n* Return:\t\t\t\tSampson L2 error\n*/\ndouble getSampsonL2Error(Eigen::Matrix3d E, const Eigen::Vector3d& x1, Eigen::Vector3d x2)\n{\n    double r, rx, ry, temp_err;\n    Eigen::Vector3d x2E = x2.transpose() * E;\n    r = x2E.dot(x1);\n    rx = E.row(0).dot(x1);\n    ry = E.row(1).dot(x1);\n    temp_err = r*r / (x2E(0)*x2E(0) + x2E(1)*x2E(1) + rx*rx + ry*ry);\n    return temp_err;\n}\n\n/* Checks for a given vector of error values if they are inliers or not in respect to threshold th.\n*\n* vector<double> error\t\tInput  -> Error values\n* double th\t\t\t\t\tInput  -> Threshold (should be squared beforehand to fit for L2)\n* Mat inliers\t\t\t\tOutput -> Inlier mask\n*\n* Return value:\t\tnumber of inliers\n*/\nsize_t getInlierMask(const std::vector<double> &error, const double &th, cv::Mat & mask)\n{\n    size_t n = error.size(), nr_inliers = 0;\n    mask = cv::Mat::zeros(1, n, CV_8UC1);\n    for (size_t i = 0; i < n; i++)\n    {\n        if (error[i] < th)\n        {\n            mask.at<bool>(i) = true;\n            nr_inliers++;\n        }\n    }\n\n    return nr_inliers;\n}\n\n/* Calculates the angle between two vectors\n*\n* Mat v1\t\t\t\t\tInput  -> First vector\n* Mat v1\t\t\t\t\tInput  -> Second vector\n* bool degree\t\t\t\tInput  -> If true [Default], the angle is returned in degrees. Otherwise in rad.\n*\n* Return value:\t\t\t\tAngle\n*/\ndouble getAnglesBetwVectors(cv::Mat v1, cv::Mat v2, bool degree)\n{\n    CV_Assert(v1.type() == v2.type());\n    if (v1.cols > v1.rows)\n        v1 = v1.t();\n    if (v2.cols > v2.rows)\n        v2 = v2.t();\n    CV_Assert((v1.cols == v2.cols) && (v1.rows == v2.rows));\n    double angle = v1.dot(v2);// std::acos(v1.dot(v2) / (cv::norm(v1) * cv::norm(v2)));\n    angle /= cv::norm(v1) * cv::norm(v2);\n    if(poselib::nearZero(1e5 * (angle - 1.0))){\n        return 0;\n    }\n    angle = std::acos(angle);\n    if (degree)\n        angle *= 180.0 / PI;\n    return angle;\n}\n}\n", "meta": {"hexsha": "1579d52bc1b88b662741373cf14ecbf56a494da3", "size": 127828, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matchinglib_poselib/source/poselib/source/pose_helper.cpp", "max_stars_repo_name": "josefmaierfl/matchinglib_poselib", "max_stars_repo_head_hexsha": "3bd7125a1ddfea68dfa95c8b3f978cba4a678348", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-30T14:58:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T14:58:18.000Z", "max_issues_repo_path": "matchinglib_poselib/source/poselib/source/pose_helper.cpp", "max_issues_repo_name": "josefmaierfl/matchinglib_poselib", "max_issues_repo_head_hexsha": "3bd7125a1ddfea68dfa95c8b3f978cba4a678348", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-19T16:11:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-19T16:11:15.000Z", "max_forks_repo_path": "matchinglib_poselib/source/poselib/source/pose_helper.cpp", "max_forks_repo_name": "josefmaierfl/matchinglib_poselib", "max_forks_repo_head_hexsha": "3bd7125a1ddfea68dfa95c8b3f978cba4a678348", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-28T13:20:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T10:56:02.000Z", "avg_line_length": 41.5971363488, "max_line_length": 241, "alphanum_fraction": 0.5847936289, "num_tokens": 38910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.2631765570048666}}
{"text": "/* Copyright © 2017 Apple Inc. All rights reserved.\n *\n * Use of this source code is governed by a BSD-3-clause license that can\n * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause\n */\n#ifndef TURI_FAST_MULTINOMIAL_HPP\n#define TURI_FAST_MULTINOMIAL_HPP\n\n#include <vector>\n#include <algorithm>\n\n\n#include <boost/integer.hpp>\n#include <boost/random.hpp>\n\n#include <core/parallel/pthread_tools.hpp>\n#include <core/parallel/atomic.hpp>\n\n#include <core/generics/float_selector.hpp>\n\n\n\n\nnamespace turi {\n\n\n  /// \\ingroup util_internal\n  class fast_multinomial {\n    // system word length float\n    typedef float_selector<sizeof(size_t)>::float_type float_t;\n\n    //! First leaf index\n    size_t first_leaf_index;\n\n    //! The number of assignments to the multinomial\n    size_t num_asg;\n\n    //! The tree datastructure\n    std::vector<float_t> tree;\n\n    //! the number of positive probability elements\n    atomic<size_t> num_support;\n\n\n\n\n    // Helper routines\n    // ========================================================>\n\n    //! Compute the next power of 2\n    //     size_t next_powerof2(size_t val) {\n    //       size_t powof2 = 1;\n    //       while(powof2 < val) powof2 = powof2 * 2;\n    //       return powof2;\n    //     }\n\n    //! Clever next power of two bit magic\n    uint64_t next_powerof2(uint64_t val) {\n      --val;\n      val = val | (val >> 1);\n      val = val | (val >> 2);\n      val = val | (val >> 4);\n      val = val | (val >> 8);\n      val = val | (val >> 16);\n      val = val | (val >> 32);\n      return val + 1;\n    }\n\n\n\n\n    //! Returns the index of the left child of the supplied index.\n    size_t left_child(size_t i) const { return 2 * i + 1; }\n\n    //! Returns the index of the right child of the supplied index.\n    size_t right_child(size_t i) const { return 2 * i + 2; }\n\n    //! Returns the index of the parent of the supplied index.\n    size_t parent(size_t i) const { return (i-1) / 2; }\n\n    //! returns the sibling of\n    size_t sibling(size_t i) const {\n      // the binary here is equivalent to (+1) if leaf is odd and (-1) if\n      // leaf is even\n      return i + (i & 1)*2 - 1;\n    }\n\n    //! get the tree location of the assignment\n    size_t tree_loc_from_asg(size_t asg) const {\n      size_t loc = asg + first_leaf_index;\n      assert(loc < tree.size());\n      assert(is_leaf(loc));\n      return loc;\n    }\n\n    //! determine the assignment from the location in the tree\n    size_t asg_from_tree_loc(size_t i) const {\n      assert(is_leaf(i));\n      size_t asg = i - first_leaf_index;\n      assert(asg < num_asg);\n      return asg;\n    }\n\n\n    //! Returns true if the index corresponds to a leaf\n    bool is_leaf(size_t i) const {\n      return i >= first_leaf_index;\n      //      return left_child(i) > tree.size();\n    }\n\n    //! Returns true if the location is the root\n    bool is_root(size_t i) const { return i == 0; }\n\n\n    /// Returns the index of a leaf sampled proportionate to its\n    /// priority.  Returns false on failure\n    bool try_sample(size_t& asg, size_t cpuid) {\n      size_t loc = 0;\n      while ( !is_leaf(loc) ) {\n        // get the left and right priorities\n        float_t left_p = tree.at(left_child(loc));\n        float_t right_p = tree.at(right_child(loc));\n        // if both are zero, the sample has failed. Return\n        if (left_p + right_p == 0) return false;\n        else if (right_p == 0) loc = left_child(loc);\n        else if (left_p == 0)  loc = right_child(loc);\n        else {\n          // pick from a bernoulli trial\n          float_t childsum = left_p + right_p;\n          float_t rndnumber = turi::random::uniform<float_t>(0,1);\n          if((childsum * rndnumber)  < left_p)\n            loc = left_child(loc);\n          else\n            loc = right_child(loc);\n        }\n      }\n      assert(is_leaf(loc));\n      asg = asg_from_tree_loc(loc);\n      assert(asg < num_asg);\n      return true;\n    } // end of sample index\n\n\n    /// Propagates a cumulative sum update up the tree.\n    void propagate_change(size_t loc) {\n      // Loop while the location is not the root each time moving up\n      // the tree\n      for( ; !is_root(loc); loc = parent(loc) ) {\n        // Get the sibbling of this location\n        size_t sibling_loc = sibling(loc);\n        assert(sibling_loc < tree.size());\n        // Get the parent\n        size_t parent_loc = parent(loc);\n        assert(parent_loc < tree.size());\n        // Assert that the sibling is infact the sibling\n        assert(parent_loc == parent(sibling_loc));\n        // Get the priority of this location and the sibling\n        // and the parent\n        volatile float_t* sibling1 = &(tree[loc]);\n        volatile float_t* sibling2 = &(tree[sibling_loc]);\n        volatile float_t* parent = &(tree[parent_loc]);\n\n        // write to the parent. Use a concurrent write mechanism\n        // size_t spin_count = 0;\n        //float_t old_value = *parent;\n        //        float_t new_value = *sibling1 + *sibling2;\n        //        while(!atomic_compare_and_swap(tree[parent_loc], old_value, new_value)) {\n        //          old_value = *parent;\n        //          new_value = *sibling1 + *sibling2;\n        // if(++spin_count % 10 == 0) {\n        //   std::cerr << \"Propagate_change: \" << spin_count << std::endl;\n        // }\n        //      }\n        while(true) {\n          float_t sum = (*sibling1) + (*sibling2);\n          (*parent) = sum;\n          __asm(\"mfence\");\n          float_t sum2 = (*sibling1) + (*sibling2);\n          float_t parentval = (*parent);\n          if (sum2 == parentval) break;\n        }\n        // If the update was successful accomplished by anothe thread\n        // than return\n        //if(old_value == new_value) return;\n      } // end of for loop\n    } // end of propagate change\n\n\n  public:\n\n    /** initialize a fast multinomail */\n    fast_multinomial(size_t num_asg,\n                     size_t ncpus) :\n      first_leaf_index(0),\n      num_asg(num_asg) {\n      // // initialize the generators\n      // for(size_t i = 0; i < rngs.size(); ++i) {\n      //   rngs[i].seed(rand());\n      //   distributions.push_back(distribution_type(rngs[i]));\n      // }\n      // Determine the size of the tree\n      first_leaf_index = next_powerof2(num_asg) - 1;\n      size_t tree_size = first_leaf_index + next_powerof2(num_asg);\n      tree.resize(tree_size, 0.0);\n    }\n\n    void zero(size_t asg) {\n      assert(asg < num_asg);\n      size_t loc = tree_loc_from_asg(asg);\n      // Use CAS\n      float_t old_value = tree[loc];\n      float_t new_value = 0;\n      while(!atomic_compare_and_swap(tree[loc], old_value, new_value)){\n        old_value = tree[loc];\n      }\n      propagate_change(loc);\n      if(old_value > 0) {\n        num_support.dec();\n      }\n    }\n\n    //! Set a leaf value\n    void set(size_t asg, float_t value) {\n      assert(asg < num_asg);\n      assert(value >= 0);\n      size_t loc = tree_loc_from_asg(asg);\n      // Use atomic compare and swap to update the value\n      float_t old_value = tree[loc];\n      float_t new_value = value;\n      while(!atomic_compare_and_swap(tree[loc], old_value, new_value)){\n        old_value = tree[loc];\n      }\n      if(old_value == 0 && new_value > 0) {\n        num_support.inc();\n      }\n      propagate_change(loc);\n      // Update support count\n      if(old_value > 0 && new_value == 0) {\n        num_support.dec();\n      }\n    } // end of set\n\n    //! Set a leaf value\n    void add(size_t asg, float_t value) {\n      assert(asg < num_asg);\n      assert(value >= 0);\n      size_t loc = tree_loc_from_asg(asg);\n      // Use atomic compare and swap to update the value\n      float_t old_value = tree[loc];\n      float_t new_value = value + old_value;\n      while(!atomic_compare_and_swap(tree[loc], old_value, new_value)){\n        old_value = tree[loc];\n        new_value = value + old_value;\n      }\n      // Update support count\n      if(old_value == 0 && new_value > 0) {\n        num_support.inc();\n      }\n      propagate_change(loc);\n    } // end of add\n\n    //! Set a leaf value\n    void max(size_t asg, float_t value) {\n      assert(asg < num_asg);\n      assert(value >= 0);\n      size_t loc = tree_loc_from_asg(asg);\n      // Use atomic compare and swap to update the value\n      float_t old_value = tree[loc];\n      float_t new_value = std::max(value, old_value);\n      while(!atomic_compare_and_swap(tree[loc], old_value, new_value)){\n        old_value = tree[loc];\n        new_value = std::max(value, old_value);\n      }\n      if(old_value == 0 && new_value > 0) {\n        num_support.inc();\n      }\n      propagate_change(loc);\n      // Update support count\n      if(old_value > 0 && new_value == 0) {\n        num_support.dec();\n      }\n    } // end of set\n\n    /**\n     * Try to draw a sample from the multinomial.  If everything has\n     * probability zero then return false.\n     */\n    bool sample(size_t& ret_asg, size_t cpuid) {\n      // While there is positive support for some assignment\n      // size_t spin_count = 0;\n      volatile float_t *root = &(tree[0]);\n      while(num_support.value > 0 || (*root) > 0) {\n        // Try and get a sample\n        if(try_sample(ret_asg, cpuid)) {\n          assert(ret_asg < num_asg);\n          return true;\n        }\n\n        //         if(++spin_count % 10000 == 0) {\n        //           std::cerr // << THREAD_ID() << \": \"\n        //                     << \"  Sample: \" << spin_count\n        //                     << \", \" << tree[0]\n        //                     << \", \" << num_support.value\n        //                     << std::endl;\n        //           float_t sum = 0;\n        //           for(size_t i = first_leaf_index; i < tree.size(); ++i) {\n        //             sum += tree[i];\n        //           }\n        //           std::cerr << \"Tree Sum: \" << sum << std::endl;\n        //           std::getchar();\n        //         }\n\n      }  // End of While loop\n\n      //       if(spin_count >= 10){\n      //         std::cerr // << THREAD_ID() << \": \"\n      //                   << \"  Sample_recover: \" << spin_count << std::endl;\n      //       }\n\n      return false;\n    } // end of sample\n\n\n    /**\n     * Try to draw a sample from the multinomial and zero out the\n     * probability of the element that was drawn.  If everything has\n     * probability zero then return false.\n     */\n    bool pop(size_t& ret_asg, size_t cpuid) {\n      if(tree.empty()) return false;\n      // While there is positive support for some assignment\n      while(num_support.value > 0 || tree[0] > 0) {\n        // Try and get a sample\n        if(try_sample(ret_asg, cpuid)) {\n          assert(ret_asg < num_asg);\n          // We have a sample but it is possible that another thread\n          // also go this sample so we will use CAS to see who \"wins\"\n          // and gets to keep the sample and who has to try again\n          size_t loc = tree_loc_from_asg(ret_asg);\n          // Use CAS\n          float_t old_value = tree[loc];\n          float_t new_value = 0;\n          while(!atomic_compare_and_swap(tree[loc], old_value, new_value)){\n            old_value = tree[loc];\n          }\n          // Figure out if we won and get to keep the sample or if\n          // some other thread won and zeroed out the sample before we\n          // got it.\n          if(old_value > 0) {\n            // We win!!! and keep the sample :-)\n            propagate_change(loc);\n            num_support.dec();\n            return true;\n          }\n          // The other thread wins and we have to try agian :-(.\n        }\n      }\n\n      std::cerr << \"Queue emptied!: \" << tree[0]\n                << \", \" << num_support.value << std::endl;\n      print_tree();\n      return false;\n    } // end of pop\n\n    /** Get the number of assignments with positive support */\n    size_t positive_support() {\n      return num_support.value;\n    }\n\n    /** print the tree */\n    void print_tree() {\n      for (size_t i = 0; i < std::min(tree.size(), size_t(1000)); ++i) {\n        if(is_leaf(i)) {\n          std::cout << \"Leaf(\" << asg_from_tree_loc(i)\n                    << \", [\" << parent(i) << \"], \"\n                    << tree[i] << \") \";\n        } else {\n          std::cout << \"Node(\" << i <<  \", \"\n                    << \"[\" << left_child(i) << \", \"\n                    << right_child(i) << \"], \"\n                    << tree[i] << \") \";\n        }\n      }\n      std::cout << std::endl;\n    }\n\n    float_t get_weight(size_t asg) const {\n      size_t loc = tree_loc_from_asg(asg);\n      return tree[loc];\n    }\n\n    bool has_support(size_t asg) const {\n      size_t loc = tree_loc_from_asg(asg);\n      return tree[loc] > 0;\n    }\n\n    void clear() {\n      // not thread safe\n      std::fill(tree.begin(), tree.end(), 0.0);\n      num_support.value = 0;\n    }\n  }; // end of fast_multinomial\n\n} // end of namespace\n\n#undef float_t\n#endif\n", "meta": {"hexsha": "70b05cffd455ab306463d7cb6f3b3e33a38c7e2a", "size": 12813, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/util/fast_multinomial.hpp", "max_stars_repo_name": "pappasG/turicreate", "max_stars_repo_head_hexsha": "494e313957a6c01333628b182a7d5bc6efea18f8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-02-08T08:45:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-07T05:55:18.000Z", "max_issues_repo_path": "src/core/util/fast_multinomial.hpp", "max_issues_repo_name": "pappasG/turicreate", "max_issues_repo_head_hexsha": "494e313957a6c01333628b182a7d5bc6efea18f8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-02-15T04:42:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T01:05:15.000Z", "max_forks_repo_path": "src/core/util/fast_multinomial.hpp", "max_forks_repo_name": "pappasG/turicreate", "max_forks_repo_head_hexsha": "494e313957a6c01333628b182a7d5bc6efea18f8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-23T09:47:24.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-23T09:47:24.000Z", "avg_line_length": 31.4044117647, "max_line_length": 91, "alphanum_fraction": 0.5499102474, "num_tokens": 3256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961013, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.26314290643913113}}
{"text": "/***********************************************************************\n\nCopyright (c) 2014, Carnegie Mellon University\nAll rights reserved.\n\nAuthors: Jennifer King <jeking04@gmail.com>\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\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\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(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 <vector>\n#include <Eigen/Geometry>\n#include <ompl/util/RandomNumbers.h>\n#include <or_ompl/TSR.h>\n\nusing namespace or_ompl;\n\nTSR::TSR()\n    : _initialized(false)\n{\n}\n\nTSR::TSR(\n        const Eigen::Affine3d &T0_w,\n        const Eigen::Affine3d &Tw_e,\n        const Eigen::Matrix<double, 6, 2> &Bw)\n    : _T0_w(T0_w)\n    , _Tw_e(Tw_e)\n    , _Bw(Bw)\n    , _manipulator_index(-1)\n    , _relative_body_name(\"NULL\")\n    , _relative_link_name(\"\")\n    , _initialized(true)\n{\n    _T0_w_inv = _T0_w.inverse();\n    _Tw_e_inv = _Tw_e.inverse();\n}\n\nbool TSR::deserialize(std::stringstream &ss)\n{\n    return deserialize(static_cast<std::istream &>(ss));\n}\n\nbool TSR::deserialize(std::istream &ss)\n{\n    // Set _initialized to false in case an error occurs.\n    _initialized = false;\n\n    ss >> _manipulator_index\n       >> _relative_body_name;\n\n    if(_relative_body_name != \"NULL\")\n        ss >> _relative_link_name;\n\n    // Read in the T0_w matrix\n    for(unsigned int c=0; c < 3; c++)\n    for(unsigned int r=0; r < 3; r++)\n        ss >> _T0_w.matrix()(r,c);\n\n    for(unsigned int idx=0; idx < 3; idx++)\n        ss >> _T0_w.translation()(idx);\n\n    // Read in the Tw_e matrix\n    for(unsigned int c=0; c < 3; c++)\n    for(unsigned int r=0; r < 3; r++)\n        ss >> _Tw_e.matrix()(r,c);\n\n    for(unsigned int idx=0; idx < 3; idx++)\n        ss >> _Tw_e.translation()(idx);\n\n    // Read in the Bw matrix\n    for(unsigned int r=0; r < 6; r++)\n    for(unsigned int c=0; c < 2; c++)\n        ss >> _Bw(r,c);\n\n    // Check for an error.\n    if (!ss)\n        return false;\n\n    _T0_w_inv = _T0_w.inverse();\n    _Tw_e_inv = _Tw_e.inverse();\n    _initialized = true;\n\n    return true;\n}\n\nvoid TSR::serialize(std::ostream& ss)\n{\n    if (!_initialized)\n        throw std::runtime_error(\"TSR is not initialized.\");\n\n    ss << _manipulator_index\n       << ' ' << _relative_body_name;\n\n    if(_relative_body_name != \"NULL\")\n        ss << ' ' << _relative_link_name;\n\n    // T0_w matrix\n    for(unsigned int c=0; c < 3; c++)\n    for(unsigned int r=0; r < 3; r++)\n        ss << ' ' << _T0_w.matrix()(r, c);\n\n    for(unsigned int idx=0; idx < 3; idx++)\n        ss << ' ' << _T0_w.translation()(idx);\n\n    // Tw_e matrix\n    for(unsigned int c=0; c < 3; c++)\n    for(unsigned int r=0; r < 3; r++)\n        ss << ' ' << _Tw_e.matrix()(r, c);\n\n    for(unsigned int idx=0; idx < 3; idx++)\n        ss << ' ' << _Tw_e.translation()(idx);\n\n    // Read in the Bw matrix\n    for(unsigned int r=0; r < 6; r++)\n    for(unsigned int c=0; c < 2; c++)\n        ss << ' ' << _Bw(r, c);\n}\n\nEigen::Matrix<double, 6, 1> TSR::distance(const Eigen::Affine3d &ee_pose) const {\n    Eigen::Matrix<double, 6, 1> dist = Eigen::Matrix<double, 6, 1>::Zero();\n\n    // First compute the pose of the w frame in world coordinates, given the ee_pose\n    Eigen::Affine3d w_in_world = ee_pose * _Tw_e_inv;\n\n    // Next compute the pose of the w frame relative to its original pose (as specified by T0_w)\n    Eigen::Affine3d w_offset = _T0_w_inv * w_in_world;\n\n    // Now compute the elements of the distance matrix\n    dist(0,0) = w_offset.translation()(0);\n    dist(1,0) = w_offset.translation()(1);\n    dist(2,0) = w_offset.translation()(2);\n    dist(3,0) = atan2(w_offset.rotation()(2,1), w_offset.rotation()(2,2));\n    dist(4,0) = -asin(w_offset.rotation()(2,0));\n    dist(5,0) = atan2(w_offset.rotation()(1,0), w_offset.rotation()(0,0));\n\n    return dist;\n}\n\nEigen::Matrix<double, 6, 1> TSR::displacement(const Eigen::Affine3d &ee_pose) const {\n\n    Eigen::Matrix<double, 6, 1> dist = distance(ee_pose);\n    Eigen::Matrix<double, 6, 1> disp = Eigen::Matrix<double, 6, 1>::Zero();\n\n    for(unsigned int idx=0; idx < 6; idx++){\n        if(dist(idx,0) < _Bw(idx,0)){\n            disp(idx,0) = dist(idx,0) - _Bw(idx,0);\n        }else if(dist(idx,0) > _Bw(idx,1)){\n            disp(idx,0) = dist(idx,0) - _Bw(idx,1);\n        }\n    }\n\n    return disp;\n}\n\nEigen::Affine3d TSR::sampleDisplacementTransform(void) const {\n\n    // First sample uniformly betwee each of the bounds of Bw\n    std::vector<double> d_sample(6);\n\n    ompl::RNG rng;\n    for(unsigned int idx=0; idx < d_sample.size(); idx++){\n        if(_Bw(idx,1) > _Bw(idx,0)){\n            d_sample[idx] = rng.uniformReal(_Bw(idx,0), _Bw(idx,1));\n        }\n    }\n\n    Eigen::Affine3d return_tf;\n    return_tf.translation() << d_sample[0], d_sample[1], d_sample[2];\n\n    // Convert to a transform matrix\n    double roll = d_sample[3];\n    double pitch = d_sample[4];\n    double yaw = d_sample[5];\n\n    double A = cos(yaw);\n    double B = sin(yaw);\n    double C = cos(pitch);\n    double D = sin(pitch);\n    double E = cos(roll);\n    double F = sin(roll);\n    return_tf.linear() << A*C, A*D*F - B*E, B*F + A*D*E,\n        B*C, A*E + B*D*F, B*D*E - A*F,\n        -D, C*F, C*E;\n\n    return return_tf;\n}\n\nEigen::Affine3d TSR::sample() const {\n\n    Eigen::Affine3d tf = sampleDisplacementTransform();\n\n    return _T0_w * tf * _Tw_e;\n}\n", "meta": {"hexsha": "afe06a02f9605b7e518ae009741636491995abed", "size": 6429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/TSR.cpp", "max_stars_repo_name": "robots-helpinghandslab/or_ompl", "max_stars_repo_head_hexsha": "1e02092cfbff6e21c8050eb807017124a43deae9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T09:22:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T15:34:50.000Z", "max_issues_repo_path": "src/TSR.cpp", "max_issues_repo_name": "robots-helpinghandslab/or_ompl", "max_issues_repo_head_hexsha": "1e02092cfbff6e21c8050eb807017124a43deae9", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2015-01-09T21:28:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-04T04:19:26.000Z", "max_forks_repo_path": "src/TSR.cpp", "max_forks_repo_name": "robots-helpinghandslab/or_ompl", "max_forks_repo_head_hexsha": "1e02092cfbff6e21c8050eb807017124a43deae9", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2015-02-03T17:09:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-27T13:04:26.000Z", "avg_line_length": 29.6267281106, "max_line_length": 96, "alphanum_fraction": 0.6178254783, "num_tokens": 1845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.26299195241612344}}
{"text": "#ifndef STAN_MATH_PRIM_FUNCTOR_ODE_RK45_HPP\n#define STAN_MATH_PRIM_FUNCTOR_ODE_RK45_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/functor/apply.hpp>\n#include <stan/math/prim/functor/coupled_ode_system.hpp>\n#include <stan/math/prim/functor/ode_store_sensitivities.hpp>\n#include <stan/math/prim/fun/Eigen.hpp>\n#include <boost/numeric/odeint.hpp>\n#include <ostream>\n#include <tuple>\n#include <vector>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Solve the ODE initial value problem y' = f(t, y), y(t0) = y0 at a set of\n * times, { t1, t2, t3, ... } using the non-stiff Runge-Kutta 45 solver in\n * Boost.\n *\n * If the system of equations is stiff, <code>ode_bdf</code> will likely be\n * faster.\n *\n * \\p f must define an operator() with the signature as:\n *   template<typename T_t, typename T_y, typename... T_Args>\n *   Eigen::Matrix<stan::return_type_t<T_t, T_y, T_Args...>, Eigen::Dynamic, 1>\n *     operator()(const T_t& t, const Eigen::Matrix<T_y, Eigen::Dynamic, 1>& y,\n *     std::ostream* msgs, const T_Args&... args);\n *\n * t is the time, y is the vector-valued state, msgs is a stream for error\n * messages, and args are optional arguments passed to the ODE solve function\n * (which are passed through to \\p f without modification).\n *\n * @tparam F Type of ODE right hand side\n * @tparam T_y0 Type of initial condition\n * @tparam T_t0 Type of initial time\n * @tparam T_ts Type of output times\n * @tparam T_Args Types of pass-through parameters\n *\n * @param function_name Calling function name (for printing debugging messages)\n * @param f Right hand side of the ODE\n * @param y0_arg Initial state\n * @param t0 Initial time\n * @param ts Times at which to solve the ODE at. All values must be sorted and\n *   greater than t0.\n * @param relative_tolerance Relative tolerance passed to Boost\n * @param absolute_tolerance Absolute tolerance passed to Boost\n * @param max_num_steps Upper limit on the number of integration steps to\n *   take between each output (error if exceeded)\n * @param[in, out] msgs the print stream for warning messages\n * @param args Extra arguments passed unmodified through to ODE right hand side\n * @return Solution to ODE at times \\p ts\n */\ntemplate <typename F, typename T_y0, typename T_t0, typename T_ts,\n          typename... Args, require_eigen_vector_t<T_y0>* = nullptr>\nstd::vector<Eigen::Matrix<stan::return_type_t<T_y0, T_t0, T_ts, Args...>,\n                          Eigen::Dynamic, 1>>\node_rk45_tol_impl(const char* function_name, const F& f, const T_y0& y0_arg,\n                  T_t0 t0, const std::vector<T_ts>& ts,\n                  double relative_tolerance, double absolute_tolerance,\n                  long int max_num_steps,  // NOLINT(runtime/int)\n                  std::ostream* msgs, const Args&... args) {\n  using boost::numeric::odeint::integrate_times;\n  using boost::numeric::odeint::make_dense_output;\n  using boost::numeric::odeint::max_step_checker;\n  using boost::numeric::odeint::no_progress_error;\n  using boost::numeric::odeint::runge_kutta_dopri5;\n  using boost::numeric::odeint::vector_space_algebra;\n\n  using T_y0_t0 = return_type_t<T_y0, T_t0>;\n\n  Eigen::Matrix<T_y0_t0, Eigen::Dynamic, 1> y0\n      = y0_arg.template cast<T_y0_t0>();\n\n  check_finite(function_name, \"initial state\", y0);\n  check_finite(function_name, \"initial time\", t0);\n  check_finite(function_name, \"times\", ts);\n\n  std::tuple<ref_type_t<Args>...> args_ref_tuple(args...);\n\n  apply(\n      [&](const auto&... args_ref) {\n        // Code from https://stackoverflow.com/a/17340003\n        std::vector<int> unused_temp{\n            0,\n            (check_finite(function_name, \"ode parameters and data\", args_ref),\n             0)...};\n      },\n      args_ref_tuple);\n\n  check_nonzero_size(function_name, \"initial state\", y0);\n  check_nonzero_size(function_name, \"times\", ts);\n  check_sorted(function_name, \"times\", ts);\n  check_less(function_name, \"initial time\", t0, ts[0]);\n\n  check_positive_finite(function_name, \"relative_tolerance\",\n                        relative_tolerance);\n  check_positive_finite(function_name, \"absolute_tolerance\",\n                        absolute_tolerance);\n  check_positive(function_name, \"max_num_steps\", max_num_steps);\n\n  using return_t = return_type_t<T_y0, T_t0, T_ts, Args...>;\n  // creates basic or coupled system by template specializations\n  auto&& coupled_system = apply(\n      [&](const auto&... args_ref) {\n        return coupled_ode_system<F, T_y0_t0, ref_type_t<Args>...>(f, y0, msgs,\n                                                                   args_ref...);\n      },\n      args_ref_tuple);\n\n  // first time in the vector must be time of initial state\n  std::vector<double> ts_vec(ts.size() + 1);\n  ts_vec[0] = value_of(t0);\n  for (size_t i = 0; i < ts.size(); ++i)\n    ts_vec[i + 1] = value_of(ts[i]);\n\n  std::vector<Eigen::Matrix<return_t, Eigen::Dynamic, 1>> y;\n  y.reserve(ts.size());\n  bool observer_initial_recorded = false;\n  size_t time_index = 0;\n\n  // avoid recording of the initial state which is included by the\n  // conventions of odeint in the output\n  auto filtered_observer\n      = [&](const std::vector<double>& coupled_state, double t) -> void {\n    if (!observer_initial_recorded) {\n      observer_initial_recorded = true;\n      return;\n    }\n    apply(\n        [&](const auto&... args_ref) {\n          y.emplace_back(ode_store_sensitivities(\n              f, coupled_state, y0, t0, ts[time_index], msgs, args_ref...));\n        },\n        args_ref_tuple);\n    time_index++;\n  };\n\n  // the coupled system creates the coupled initial state\n  std::vector<double> initial_coupled_state = coupled_system.initial_state();\n\n  const double step_size = 0.1;\n  try {\n    integrate_times(\n        make_dense_output(absolute_tolerance, relative_tolerance,\n                          runge_kutta_dopri5<std::vector<double>, double,\n                                             std::vector<double>, double>()),\n        std::ref(coupled_system), initial_coupled_state, std::begin(ts_vec),\n        std::end(ts_vec), step_size, filtered_observer,\n        max_step_checker(max_num_steps));\n  } catch (const no_progress_error& e) {\n    throw_domain_error(function_name, \"\", ts_vec[time_index + 1],\n                       \"Failed to integrate to next output time (\",\n                       \") in less than max_num_steps steps\");\n  }\n\n  return y;\n}\n\n/**\n * Solve the ODE initial value problem y' = f(t, y), y(t0) = y0 at a set of\n * times, { t1, t2, t3, ... } using the non-stiff Runge-Kutta 45 solver in\n * Boost.\n *\n * If the system of equations is stiff, <code>ode_bdf</code> will likely be\n * faster.\n *\n * \\p f must define an operator() with the signature as:\n *   template<typename T_t, typename T_y, typename... T_Args>\n *   Eigen::Matrix<stan::return_type_t<T_t, T_y, T_Args...>, Eigen::Dynamic, 1>\n *     operator()(const T_t& t, const Eigen::Matrix<T_y, Eigen::Dynamic, 1>& y,\n *     std::ostream* msgs, const T_Args&... args);\n *\n * t is the time, y is the vector-valued state, msgs is a stream for error\n * messages, and args are optional arguments passed to the ODE solve function\n * (which are passed through to \\p f without modification).\n *\n * @tparam F Type of ODE right hand side\n * @tparam T_0 Type of initial time\n * @tparam T_ts Type of output times\n * @tparam T_Args Types of pass-through parameters\n *\n * @param f Right hand side of the ODE\n * @param y0_arg Initial state\n * @param t0 Initial time\n * @param ts Times at which to solve the ODE at. All values must be sorted and\n *   greater than t0.\n * @param relative_tolerance Relative tolerance passed to Boost\n * @param absolute_tolerance Absolute tolerance passed to Boost\n * @param max_num_steps Upper limit on the number of integration steps to\n *   take between each output (error if exceeded)\n * @param[in, out] msgs the print stream for warning messages\n * @param args Extra arguments passed unmodified through to ODE right hand side\n * @return Solution to ODE at times \\p ts\n */\ntemplate <typename F, typename T_y0, typename T_t0, typename T_ts,\n          typename... Args, require_eigen_vector_t<T_y0>* = nullptr>\nstd::vector<Eigen::Matrix<stan::return_type_t<T_y0, T_t0, T_ts, Args...>,\n                          Eigen::Dynamic, 1>>\node_rk45_tol(const F& f, const T_y0& y0_arg, T_t0 t0,\n             const std::vector<T_ts>& ts, double relative_tolerance,\n             double absolute_tolerance,\n             long int max_num_steps,  // NOLINT(runtime/int)\n             std::ostream* msgs, const Args&... args) {\n  return ode_rk45_tol_impl(\"ode_rk45_tol\", f, y0_arg, t0, ts,\n                           relative_tolerance, absolute_tolerance,\n                           max_num_steps, msgs, args...);\n}\n\n/**\n * Solve the ODE initial value problem y' = f(t, y), y(t0) = y0 at a set of\n * times, { t1, t2, t3, ... } using the non-stiff Runge-Kutta 45 solver in Boost\n * with defaults for relative_tolerance, absolute_tolerance, and max_num_steps.\n *\n * If the system of equations is stiff, <code>ode_bdf</code> will likely be\n * faster.\n *\n * \\p f must define an operator() with the signature as:\n *   template<typename T_t, typename T_y, typename... T_Args>\n *   Eigen::Matrix<stan::return_type_t<T_t, T_y, T_Args...>, Eigen::Dynamic, 1>\n *     operator()(const T_t& t, const Eigen::Matrix<T_y, Eigen::Dynamic, 1>& y,\n *     std::ostream* msgs, const T_Args&... args);\n *\n * t is the time, y is the vector-valued state, msgs is a stream for error\n * messages, and args are optional arguments passed to the ODE solve function\n * (which are passed through to \\p f without modification).\n *\n * @tparam F Type of ODE right hand side\n * @tparam T_y0 Type of initial time\n * @tparam T_ts Type of output times\n * @tparam T_Args Types of pass-through parameters\n *\n * @param f Right hand side of the ODE\n * @param y0 Initial state\n * @param t0 Initial time\n * @param ts Times at which to solve the ODE at. All values must be sorted and\n *   greather than t0.\n * @param[in, out] msgs the print stream for warning messages\n * @param args Extra arguments passed unmodified through to ODE right hand side\n * @return Solution to ODE at times \\p ts\n */\ntemplate <typename F, typename T_y0, typename T_t0, typename T_ts,\n          typename... Args, require_eigen_vector_t<T_y0>* = nullptr>\nstd::vector<Eigen::Matrix<stan::return_type_t<T_y0, T_t0, T_ts, Args...>,\n                          Eigen::Dynamic, 1>>\node_rk45(const F& f, const T_y0& y0, T_t0 t0, const std::vector<T_ts>& ts,\n         std::ostream* msgs, const Args&... args) {\n  double relative_tolerance = 1e-6;\n  double absolute_tolerance = 1e-6;\n  long int max_num_steps = 1e6;  // NOLINT(runtime/int)\n\n  return ode_rk45_tol_impl(\"ode_rk45\", f, y0, t0, ts, relative_tolerance,\n                           absolute_tolerance, max_num_steps, msgs, args...);\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "8a90bd1e2c79910c48a83b05b56ffda1b3b09adf", "size": 10837, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/functor/ode_rk45.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T14:33:37.000Z", "max_issues_repo_path": "stan/math/prim/functor/ode_rk45.hpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/functor/ode_rk45.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-10T12:55:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T12:55:07.000Z", "avg_line_length": 41.6807692308, "max_line_length": 80, "alphanum_fraction": 0.6721417366, "num_tokens": 2876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2629521700187601}}
{"text": "//\n//  kfilter.hpp\n//  carma_pack\n//\n//  Created by Brandon Kelly on 6/27/13.\n//  Copyright (c) 2013 Brandon Kelly. All rights reserved.\n//\n\n#ifndef __carma_pack__kfilter__\n#define __carma_pack__kfilter__\n\n#include <armadillo>\n#include <utility>\n#include <boost/assert.hpp>\n\n// Global random number generator object, instantiated in random.cpp\nextern boost::random::mt19937 rng;\n\n// Object containing some common random number generators.\nextern RandomGenerator RandGen;\n\n\n/*\n Abstract base class for the Kalman Filter of a CARMA(p,q) process.\n */\n\ntemplate <class OmegaType>\nclass KalmanFilter {\npublic:\n    // Kalman mean and variance\n    arma::vec mean;\n    arma::vec var;\n\n    // Constructor\n    KalmanFilter() {};\n    KalmanFilter(arma::vec& time, arma::vec& y, arma::vec& yerr) :\n    time_(time), y_(y), yerr_(yerr)\n    {\n        init();\n    }\n\n    // Initialize arrays\n    void init() {\n        int ndata = time_.n_elem;\n        dt_ = time_(arma::span(1,ndata-1)) - time_(arma::span(0,ndata-2));\n\n        // Make sure the time vector is strictly increasing\n        if (dt_.min() < 0) {\n            std::cout << \"Time vector is not sorted in increasing order. Sorting the data vectors...\"\n            << std::endl;\n            // Sort the time values such that dt > 0\n            arma::uvec sorted_indices = arma::sort_index(time_);\n            time_ = time_.elem(sorted_indices);\n            y_ = y_.elem(sorted_indices);\n            yerr_ = yerr_.elem(sorted_indices);\n            dt_ = time_.rows(1,ndata-1) - time_.rows(0,ndata-2);\n        }\n        // Make sure there are no duplicate values of time\n        if (dt_.min() == 0) {\n            std::cout << \"Found duplicate values of time, removing them...\" << std::endl;\n            // Find the unique values of time\n            arma::uvec unique_values = 1 + arma::find(dt_ != 0);\n            // Add extra row in to keep time(0), y(0), yerr(0)\n            unique_values.insert_rows(0, arma::zeros<arma::uvec>(1));\n            time_ = time_.elem(unique_values);\n            y_ = y_.elem(unique_values);\n            yerr_ = yerr_.elem(unique_values);\n            ndata = time_.n_elem;\n            dt_.set_size(ndata-1);\n            dt_ = time_.rows(1,time_.n_elem-1) - time_.rows(0,time_.n_elem-2);\n        }\n        \n        // Set the size of the Kalman Filter mean and variance vectors\n        mean.zeros(time_.n_elem);\n        var.zeros(time_.n_elem);\n    }\n    \n    // Methods to set and get the data\n    void SetTime(arma::vec& time) {\n        time_ = time;\n    }\n    arma::vec GetTime() {\n        return time_;\n    }\n    void SetTimeSeries(arma::vec& y) {\n        y_ = y;\n    }\n    arma::vec GetTimeSeries() {\n        return y_;\n    }\n    void SetTimeSeriesErr(arma::vec& yerr) {\n        yerr_ = yerr;\n    }\n    arma::vec GetTimeSeriesErr() {\n        return yerr_;\n    }\n    \n    // Methods to set and get the parameter values\n    void SetSigsqr(double sigsqr) {\n        sigsqr_ = sigsqr;\n    }\n    double GetSigsqr() {\n        return sigsqr_;\n    }\n    virtual void SetOmega(OmegaType omega) {\n        omega_ = omega;\n    }\n    OmegaType GetOmega() {\n        return omega_;\n    }\n    virtual void SetMA(arma::vec ma_coefs) {}\n        \n    double GetConst() { return yconst_; }\n    double GetSlope() { return yslope_; }\n\n    std::vector<double> GetMeanSvec() { return arma::conv_to<std::vector<double> >::from(mean); }\n    std::vector<double> GetVarSvec() { return arma::conv_to<std::vector<double> >::from(var); }\n\n    /*\n     Methods to perform the Kalman Filter operations \n     */\n    virtual void Reset() = 0;\n    virtual void Update() = 0;\n    virtual std::pair<double, double> Predict(double time) = 0;\n\n    void Filter() {\n        // Run the Kalman Filter\n        Reset();\n        for (int i=1; i<time_.n_elem; i++) {\n            Update();\n        }\n    }\n    \n    // simulate a CARMA process, conditional on the measured time series\n    std::vector<double> Simulate(arma::vec time) {\n        // first save old values since we will overwrite them later\n        arma::vec time0 = time_;\n        arma::vec y0 = y_;\n        arma::vec yerr0 = yerr_;\n        \n        arma::vec ysimulated(time.n_elem);\n        \n        time = arma::sort(time);\n        unsigned int insert_idx = 0;\n        arma::vec tinsert(1);\n        arma::vec dt_insert(1);\n        arma::vec yinsert(1);\n        arma::vec yerr_insert(1);\n        yerr_insert(0) = 0.0;\n        for (int i=0; i<time.n_elem; i++) {\n            insert_idx = 0;\n            // first simulate the value at time(i)\n            std::pair<double, double> ypredict = this->Predict(time(i));\n            ysimulated(i) = RandGen.normal(ypredict.first, sqrt(ypredict.second));\n            // find the index where time_[insert_idx-1] < time(i) < time_[insert_idx]\n            while (time_(insert_idx) < time(i)) {\n                insert_idx++;\n                if (insert_idx == (time_.n_elem)) {\n                    break;\n                }\n            }\n            // insert the simulated value into the measured time series array. these values are used in subsequent\n            // calls to Predict(time(i)).\n            tinsert(0) = time(i);\n            time_.insert_rows(insert_idx, tinsert);\n            dt_ = time_(arma::span(1,time_.n_elem-1)) - time_(arma::span(0,time_.n_elem-2));\n            yinsert(0) = ysimulated(i);\n            y_.insert_rows(insert_idx, yinsert);\n            yerr_.insert_rows(insert_idx, yerr_insert);\n            mean.zeros(time_.n_elem);\n            var.zeros(time_.n_elem);\n        }\n        \n        // restore values of measured time series\n        time_ = time0;\n        dt_ = time_(arma::span(1,time_.n_elem-1)) - time_(arma::span(0,time_.n_elem-2));\n        y_ = y0;\n        yerr_ = yerr0;\n        // restore the original sizes of the kalman mean and variance arrays\n        mean.zeros(time_.n_elem);\n        var.zeros(time_.n_elem);\n        \n        return arma::conv_to<std::vector<double> >::from(ysimulated);\n    }\n    \n    // Methods needed for interpolation and backcasting\n    virtual void InitializeCoefs(double time, unsigned int itime, double ymean, double yvar) = 0;\n    virtual void UpdateCoefs() = 0;\n\nprotected:\n    // Data\n    arma::vec time_;\n    arma::vec dt_;\n    arma::vec y_;\n    arma::vec yerr_;\n    // The Kalman Filter parameters\n    double sigsqr_;\n    OmegaType omega_;\n    unsigned int current_index_;\n    // linear coefficients needed for doing interpolation or backcasting\n    double yconst_, yslope_;\n};\n\n/*\n Class to perform the Kalman Filter and related operations for a zero-mean CAR(1) process (see below).\n This class will calculate the Kalman Filter, needed to calculate the log-likelihood in the CAR1\n parameter class. It will also provide interpolated, extrapolated, and simulated values given a\n CAR(1) model and a measured time series.\n */\n\nclass KalmanFilter1 : public KalmanFilter<double> {\npublic:\n    // Constructors\n    KalmanFilter1() : KalmanFilter<double>() {}\n    KalmanFilter1(arma::vec& time, arma::vec& y, arma::vec& yerr) : KalmanFilter<double>(time, y, yerr) {}\n    KalmanFilter1(arma::vec& time, arma::vec& y, arma::vec& yerr, double sigsqr, double omega) :\n        KalmanFilter<double>(time, y, yerr)\n    {\n        sigsqr_ = sigsqr;\n        omega_ = omega;\n    }\n    KalmanFilter1(std::vector<double> time, std::vector<double> y, std::vector<double> yerr) : \n        KalmanFilter<double>() \n    {\n        arma::vec armatime = arma::conv_to<arma::vec>::from(time);\n        arma::vec armay    = arma::conv_to<arma::vec>::from(y);\n        arma::vec armady   = arma::conv_to<arma::vec>::from(yerr);\n        time_ = armatime;\n        y_ = armay;\n        yerr_ = armady;\n        init();\n    }\n    KalmanFilter1(std::vector<double> time, std::vector<double> y, std::vector<double> yerr, double sigsqr, double omega) :\n        KalmanFilter<double>()\n    {\n        arma::vec armatime = arma::conv_to<arma::vec>::from(time);\n        arma::vec armay    = arma::conv_to<arma::vec>::from(y);\n        arma::vec armady   = arma::conv_to<arma::vec>::from(yerr);\n        time_ = armatime;\n        y_ = armay;\n        yerr_ = armady;\n        sigsqr_ = sigsqr;\n        omega_ = omega;\n        init();\n    }\n\n    // Methods to perform the Kalman Filter operations\n    void Reset();\n    void Update();\n    std::pair<double, double> Predict(double time);\n    void InitializeCoefs(double time, unsigned int itime, double ymean, double yvar);\n    void UpdateCoefs();\n\n    std::vector<double> Simulate(std::vector<double> time) {\n        arma::vec armatime = arma::conv_to<arma::vec>::from(time);\n        arma::vec armasimulate = KalmanFilter<double>::Simulate(armatime);\n        std::vector<double> vecsimulate = arma::conv_to<std::vector<double> >::from(armasimulate);\n        return vecsimulate;\n    }\n};\n\n/*\n Same as KalmanFilter1 but for a CARMA(p,q) process\n */\n\nclass KalmanFilterp : public KalmanFilter<arma::cx_vec> {\npublic:\n    // Constructors\n    KalmanFilterp() : KalmanFilter<arma::cx_vec>() {}\n    KalmanFilterp(arma::vec& time, arma::vec& y, arma::vec& yerr) : KalmanFilter<arma::cx_vec>(time, y, yerr) {init();}\n    KalmanFilterp(arma::vec& time, arma::vec& y, arma::vec& yerr, double sigsqr, arma::cx_vec& omega, arma::vec& ma_coefs) :\n        KalmanFilter<arma::cx_vec>(time, y, yerr)\n    {\n        sigsqr_ = sigsqr;\n        omega_ = omega; // omega are the roots of the AR characteristic polynomial\n        p_ = omega_.n_elem;\n        if (p_ > ma_coefs.n_elem) {\n            ma_coefs.resize(p_);\n        }\n        SetMA(ma_coefs);\n        \n        // set sizes of arrays\n        state_vector_.zeros(p_);\n        StateVar_.zeros(p_,p_);\n        PredictionVar_.zeros(p_,p_);\n        kalman_gain_.zeros(p_);\n        rho_.zeros(p_);\n        state_const_.zeros(p_);\n        state_slope_.zeros(p_);        \n        rotated_ma_coefs_.zeros(p_);\n    }\n    KalmanFilterp(std::vector<double> time, std::vector<double> y, std::vector<double> yerr) :\n        KalmanFilter<arma::cx_vec>()\n    {\n        arma::vec armatime = arma::conv_to<arma::vec>::from(time);\n        arma::vec armay    = arma::conv_to<arma::vec>::from(y);\n        arma::vec armady   = arma::conv_to<arma::vec>::from(yerr);\n        time_ = armatime;\n        y_ = armay;\n        yerr_ = armady;\n        init();\n    }\n   KalmanFilterp(std::vector<double> time, std::vector<double> y, std::vector<double> yerr, double sigsqr, \n                 std::vector<std::complex<double> > omega, std::vector<double> ma_coefs) :\n        KalmanFilter<arma::cx_vec>()\n    {\n        arma::vec armatime  = arma::conv_to<arma::vec>::from(time);\n        arma::vec armay     = arma::conv_to<arma::vec>::from(y);\n        arma::vec armady    = arma::conv_to<arma::vec>::from(yerr);\n        arma::cx_vec armaomega = arma::conv_to<arma::cx_vec>::from(omega);\n        arma::vec armacoefs = arma::conv_to<arma::vec>::from(ma_coefs);\n        time_ = armatime;\n        y_ = armay;\n        yerr_ = armady;\n        sigsqr_ = sigsqr;\n        omega_ = armaomega;\n        p_ = omega_.n_elem;\n        if (p_ > armacoefs.n_elem) {\n            armacoefs.resize(p_);\n        }\n        SetMA(armacoefs);\n        \n        // set sizes of arrays\n        state_vector_.zeros(p_);\n        StateVar_.zeros(p_,p_);\n        PredictionVar_.zeros(p_,p_);\n        kalman_gain_.zeros(p_);\n        rho_.zeros(p_);\n        state_const_.zeros(p_);\n        state_slope_.zeros(p_);\n        rotated_ma_coefs_.zeros(p_);\n\n        init();\n    }\n\n    // Set and get and moving average terms\n    void SetMA(arma::vec ma_coefs) {\n        ma_coefs_ = ma_coefs.st();\n    }\n    arma::vec GetMA() {\n        return ma_coefs_.st();\n    }\n\n    // set the AR parameters\n    void SetOmega(arma::cx_vec omega) {\n        omega_ = omega;\n        // resize arrays\n        p_ = omega_.n_elem;\n        state_vector_.zeros(p_);\n        StateVar_.zeros(p_,p_);\n        PredictionVar_.zeros(p_,p_);\n        kalman_gain_.zeros(p_);\n        rho_.zeros(p_);\n        state_const_.zeros(p_);\n        state_slope_.zeros(p_);\n        rotated_ma_coefs_.zeros(p_);\n    }\n\n    \n    // Methods to perform the Kalman Filter operations\n    void Reset();\n    void Update();\n    std::pair<double, double> Predict(double time);\n    void InitializeCoefs(double time, unsigned int itime, double ymean, double yvar);\n    void UpdateCoefs();\n    \n    std::vector<double> Simulate(std::vector<double> time) {\n        arma::vec armatime = arma::conv_to<arma::vec>::from(time);\n        arma::vec armasimulate = KalmanFilter<arma::cx_vec>::Simulate(armatime);\n        std::vector<double> vecsimulate = arma::conv_to<std::vector<double> >::from(armasimulate);\n        return vecsimulate;\n    }\n    \nprivate:\n    // parameters\n    arma::rowvec ma_coefs_; // moving average terms\n    unsigned int p_; // the orders of the CARMA process\n    // quantities defining the current state of the kalman filter\n    arma::cx_vec state_vector_; // current value of the rotated state vector\n    arma::cx_mat StateVar_; // stationary covariance matrix of the rotated state vector\n    arma::cx_rowvec rotated_ma_coefs_; // rotated moving average coefficients\n    arma::cx_mat PredictionVar_; // covariance matrix of the predicted rotated state vector\n    arma::cx_vec kalman_gain_;\n    arma::cx_vec rho_;\n    double innovation_;\n    // linear coefficients needed for doing interpolation or backcasting\n    arma::cx_vec state_const_;\n    arma::cx_vec state_slope_;    \n};\n\n\n#endif /* defined(__carma_pack__kfilter__) */\n", "meta": {"hexsha": "7c1ad1c7c79d7f9be42b64d4bc8b45a98cd0d8c7", "size": 13455, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/include/kfilter.hpp", "max_stars_repo_name": "Jamieryan/carma_pack", "max_stars_repo_head_hexsha": "347ea78818cc808e53e4a46d341829f787198df5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2015-01-25T19:24:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T11:55:28.000Z", "max_issues_repo_path": "src/include/kfilter.hpp", "max_issues_repo_name": "Jamieryan/carma_pack", "max_issues_repo_head_hexsha": "347ea78818cc808e53e4a46d341829f787198df5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2015-04-29T12:37:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-28T23:31:29.000Z", "max_forks_repo_path": "src/include/kfilter.hpp", "max_forks_repo_name": "Jamieryan/carma_pack", "max_forks_repo_head_hexsha": "347ea78818cc808e53e4a46d341829f787198df5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2015-09-15T00:41:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-28T07:28:47.000Z", "avg_line_length": 34.2366412214, "max_line_length": 124, "alphanum_fraction": 0.6015607581, "num_tokens": 3585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.542863297964157, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.26295217001876003}}
{"text": "/**  \\file boundingbox.hpp \\brief Module for box constrain management */\n/*\n-----------------------------------------------------------------------------\n   Copyright (C) 2011-2015 Ruben Martinez-Cantin <rmcantin@unizar.es>\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 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 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*/\n#ifndef  _BOUNDING_BOX_HPP_\n#define  _BOUNDING_BOX_HPP_\n\n// BOOST Libraries\n#include <boost/numeric/ublas/vector.hpp>\n#include \"ublas_elementwise.hpp\"\n\nnamespace bayesopt {\n  \n  namespace utils {\n    /** Defines a bounding box or axis-alligned bound constraints. */\n    template <class V>\n    class BoundingBox\n    {\n    public:\n      BoundingBox(const V &lbound, const V &ubound):\n\tmLowerBound(lbound), mRangeBound(ubound - lbound)\n      {};\n    \n      virtual ~BoundingBox(){};\n\n      inline V unnormalizeVector( const V &vin )\n      {\n\treturn ublas_elementwise_prod(vin,mRangeBound) + mLowerBound;\n      };  // unnormalizeVector\n\n      inline V normalizeVector( const V &vin )\n      {\n\treturn ublas_elementwise_div(vin - mLowerBound, mRangeBound);\n      }  // normalizeVector\n  \n    protected:\n      V mLowerBound; ///< Lower bound of the input space\n      V mRangeBound; ///< Range (up-low) of the input space\n    };\n    \n  } //namespace utils\n\n\n} //namespace bayesopt\n\n#endif\n", "meta": {"hexsha": "4f465c01b7e5ef46da7e1474c388431002c70e36", "size": 1951, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/bayesopt/utils/boundingbox.hpp", "max_stars_repo_name": "pchrapka/brain-modelling", "max_stars_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-13T19:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-13T19:37:52.000Z", "max_issues_repo_path": "external/bayesopt/utils/boundingbox.hpp", "max_issues_repo_name": "pchrapka/brain-modelling", "max_issues_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/bayesopt/utils/boundingbox.hpp", "max_forks_repo_name": "pchrapka/brain-modelling", "max_forks_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-25T12:22:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-25T12:22:05.000Z", "avg_line_length": 31.4677419355, "max_line_length": 78, "alphanum_fraction": 0.6468477704, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2629521628539785}}
{"text": "/****************************************************************\n  compute_unit_tensor_rmes.cpp\n\n  compute relative unit tensor rmes in spncci basis using recurrance\n\n  WARNING: Will not build since requires old version of\n  lgi::GenerateLGIExpansion with stream arguments.\n                                  \n  Anna E. McCoy and Mark A. Caprio\n  University of Notre Dame\n\n  12/3/16 (aem): Created.  Based on unit_tensor_test.cpp\n  1/6/17 (aem) : Added contraction of unit tensors and interaction\n  4/20/17 (aem) : Legacy code removed from build\n****************************************************************/\n#include <cstdio>\n#include <ctime>\n#include <fstream>\n#include <sys/resource.h>\n\n#include <Eigen/Core>\n#include <SymEigsSolver.h>  // Also includes <MatOp/DenseSymMatProd.h>\n\n\n#include \"cppformat/format.h\"\n#include \"am/am.h\"\n\n#include \"lgi/lgi.h\"\n#include \"lgi/lgi_solver.h\"\n#include \"lsu3shell/lsu3shell_basis.h\"\n#include \"lsu3shell/lsu3shell_rme.h\"\n#include \"mcutils/eigen.h\"\n#include \"sp3rlib/u3coef.h\"\n#include \"sp3rlib/vcs.h\" \n#include \"spncci/unit_tensor.h\"\n#include \"spncci/branching_u3s.h\"\n#include \"spncci/branching_u3lsj.h\"\n#include \"spncci/explicit_construction.h\"\n#include \"u3shell/relative_operator.h\"\n#include \"u3shell/upcoupling.h\"\n\n\nnamespace spncci\n{\n  // typedef std:: map< std::pair<int,int>, std::map<std::pair<int,int>,spncci::UnitTensorSectorsCache >\n  //                     > LGIUnitTensorSectorCache;\n  typedef spncci::UnitTensorMatricesByIrrepFamily LGIUnitTensorSectorCache;\n\n\n  // void \n  // ConstructSpNCCIBasisExplicit(\n  //   const spncci::SpNCCISpace& sp_irrep_vector,\n  //   basis::MatrixVector& lgi_expansion_matrix_vector,\n  //   const u3shell::SpaceU3SPN& space,\n  //   const u3shell::SectorsU3SPN& arel_sectors,\n  //   basis::MatrixVector& Arel_matrices,\n  //   std::unordered_map<u3::U3,vcs::MatrixCache, boost::hash<u3::U3>>& k_matrix_map\n  // )\n  // {\n\n  //   for(int irrep_index=0; irrep_index<sp_irrep_vector.size(); ++irrep_index)\n  //       {\n  //         u3shell::U3SPN lgi_labels=sp_irrep_vector[irrep_index];\n\n  //         const u3::U3& sigma=lgi_labels.U3();\n  //         Eigen::MatrixXd& lgi_expansion=lgi_expansion_matrix_vector[irrep_index];\n\n  //         const spncci::SpNCCIIrrepFamily& sp_irrep=sp_irrep_vector[irrep_index];\n  //         const sp3r::Sp3RSpace& sp_space=sp_irrep.Sp3RSpace();\n\n\n  //         // Act A on bra lgi\n  //         for(int a=0; a<arel_sectors.size(); ++a)\n  //           {\n  //             auto& sector=arel_sectors.GetSector(a);\n  //             int ket_index=sector.ket_subspace_index();\n  //             u3shell::U3SPN ket_subspace_labels=space.GetSubspace(ket_index).labels();\n  //             u3::U3 omega=ket_subspace_labels.U3();\n  //             HalfInt S=ket_subspace_labels.S();\n              \n\n  //             if(\n  //                 (not (omega==sigma))\n  //                 ||(S!=lgi_labels.S())\n  //                 ||(ket_subspace_labels.Sp()!=lgi_labels.Sp())\n  //                 ||(ket_subspace_labels.Sn()!=lgi_labels.Sn())\n  //               )\n  //               continue;\n\n\n  //             int bra_index=sector.bra_subspace_index();\n  //             u3shell::U3SPN bra_subspace_labels=space.GetSubspace(bra_index).labels();\n  //             u3::U3 omegap=bra_subspace_labels.U3();\n\n  //             // Check if omegap is in irrep\n  //             if(not sp_space.ContainsSubspace(omegap))\n  //             {\n  //               std::cout<<omegap.Str()<<\" is not in irrep \"<<sigma.Str()<<std::endl;\n  //               continue;\n  //             }\n\n  //             HalfInt Sp=bra_subspace_labels.S();\n  //             assert(Sp==S);\n\n  //             Eigen::MatrixXd Kmatrix_inverse=k_matrix_map[sigma][omegap].inverse();\n  //             double k_inverse=Kmatrix_inverse(0,0);\n              \n  //             Eigen::MatrixXd omega_expansion\n  //             =ParitySign(u3::ConjugationGrade(omega.SU3())+u3::ConjugationGrade(lgi_labels.U3().SU3()))\n  //               *k_inverse\n  //               *Arel_matrices[a]*lgi_expansion;\n\n  //             std::cout<<fmt::format(\"{} in irrep {} \",omegap.Str(), lgi_labels.Str())<<std::endl;\n  //             std::cout<<omega_expansion.transpose()*omega_expansion<<std::endl;\n  //             // std::cout<<lgi_expansion.transpose()*lgi_expansion<<std::endl;\n  //             // std::cout<<Arel_matrices[a].transpose()*Arel_matrices[a]<<std::endl;\n  //             // std::cout<<k_matrix_map[sigma][omegap]*k_matrix_map[sigma][omegap]<<std::endl;\n\n  //           }\n  //       }\n  // }\n\n\n  // void\n  // ComputeUnitTensorSectorsExplicit(\n  //   const spncci::SpNCCISpace& sp_irrep_vector,\n  //   basis::MatrixVector& lgi_expansion_matrix_vector,\n  //   const u3shell::SpaceU3SPN& space,\n  //   const u3shell::SectorsU3SPN& sectors,\n  //   const u3shell::SectorsU3SPN& arel_sectors,\n  //   basis::MatrixVector& Arel_matrices,\n  //   std::unordered_map<u3::U3,vcs::MatrixCache, boost::hash<u3::U3>>& k_matrix_map,\n  //   const u3shell::RelativeUnitTensorLabelsU3ST& unit_tensor,\n  //   basis::MatrixVector& lsu3shell_operator_matrices,\n  //   spncci::LGIUnitTensorSectorCache& unit_tensor_sector_cache_explicit,\n  //   double zero_threshold\n  // )\n  // // Compute unit tensor sectors using SpNCCI basis states explicityly constructed in terms of \n  // // lsu3shell states. \n  // //\n  // // Arguemnts:\n  // //  \n  // {\n  //   // REMOVE \n  //   int d=0;\n  //   // Get operator labels \n  //   for(int m=0; m<sp_irrep_vector.size(); ++m)\n  //     for(int n=0; n<sp_irrep_vector.size(); ++n)\n  //       {\n  //         // Get lgi expansion \n  //         std::pair<int,int> lgi_pair(m,n);\n  //         u3shell::U3SPN bra_lgi_labels=sp_irrep_vector[m];\n  //         u3shell::U3SPN ket_lgi_labels=sp_irrep_vector[n];\n\n  //         if(not am::AllowedTriangle(ket_lgi_labels.S(),unit_tensor.S0(), bra_lgi_labels.S()))\n  //           continue;\n\n  //         const HalfInt& Nsigmap=bra_lgi_labels.N();\n  //         const HalfInt& Nsigma=ket_lgi_labels.N();\n  //         Eigen::MatrixXd& bra_lgi_expansion=lgi_expansion_matrix_vector[m];\n  //         Eigen::MatrixXd& ket_lgi_expansion=lgi_expansion_matrix_vector[n];\n  //         // Act A on bra lgi\n  //         for(int s=0; s<sectors.size(); ++s)\n  //           {\n  //             auto& sector=sectors.GetSector(s);\n  //             int bra_index=sector.bra_subspace_index();\n  //             int ket_index=sector.ket_subspace_index();\n  //             u3shell::U3SPN ket_subspace_labels=space.GetSubspace(ket_index).labels();\n  //             u3shell::U3SPN bra_subspace_labels=space.GetSubspace(bra_index).labels();\n  //             u3::U3 omega=ket_subspace_labels.U3();\n  //             u3::U3 omegap=bra_subspace_labels.U3();\n  //             HalfInt S=ket_subspace_labels.S();\n  //             HalfInt Sp=bra_subspace_labels.S();\n  //             // Checking if omegaS and omegapS are contained in irreps in question\n  //             if(\n  //                 (omegap.N()<Nsigmap)\n  //                 ||(Sp!=bra_lgi_labels.S())\n  //                 ||(bra_subspace_labels.Sp()!=bra_lgi_labels.Sp())\n  //                 ||(bra_subspace_labels.Sn()!=bra_lgi_labels.Sn())\n  //                 ||(omega.N()<Nsigma)\n  //                 ||(ket_subspace_labels.Sp()!=ket_lgi_labels.Sp())\n  //                 ||(ket_subspace_labels.Sn()!=ket_lgi_labels.Sn())\n  //                 ||(ket_subspace_labels.S()!=ket_lgi_labels.S())\n  //               )\n  //               continue;\n\n  //             if((omegap.N()==Nsigmap)&&(not (bra_subspace_labels==bra_lgi_labels)))\n  //               continue;\n\n  //             if((omega.N()==Nsigma)&&(not (ket_subspace_labels==ket_lgi_labels)))\n  //               continue;\n\n\n  //             int rho0=sector.multiplicity_index();\n  //             spncci::UnitTensorU3Sector unit_U3Sector(omegap,omega,unit_tensor,rho0);\n  //             std::pair<int,int> NnpNn(int(omegap.N()-Nsigmap),int(omega.N()-Nsigma));\n\n  //             Eigen::MatrixXd unit_rmes;\n  //             Eigen::MatrixXd& operator_matrix=lsu3shell_operator_matrices[s];\n              \n  //             // Act A on ket LGI\n  //             if(Nsigmap==(Nsigma+unit_tensor.N0()+2))\n  //               {\n                  \n  //                 int arel_index=arel_sectors.LookUpSectorIndex(ket_index,n,1);\n  //                 // Check if there is a valid arel sector that will yield the omegap\n  //                 // subspace\n  //                 if(arel_index==-1)\n  //                   if(u3::OuterMultiplicity(ket_lgi_labels.U3().SU3(),u3::SU3(2,0),omega.SU3()))\n  //                     {\n  //                       // std::cout<<unit_tensor.Str()<<std::endl;\n  //                       // std::cout<<bra_lgi_labels.Str()<<\"  \"<<omegap.Str()<<Sp<<\"  \"<<ket_lgi_labels.Str()<<\"  \"<<omega.Str()\n  //                       //   <<S<<\"  \"<<arel_index<<std::endl;\n  //                       // std::cout<<ket_index<<\"  \"<<n<<std::endl;\n  //                     }\n  //                 if(arel_index!=-1)\n  //                   {\n  //                     // std::cout<<\"hi\"<<std::endl;\n  //                     Eigen::MatrixXd Kmatrix_inverse=k_matrix_map[ket_lgi_labels.U3()][omega].inverse();\n  //                     double k_inverse=Kmatrix_inverse(0,0);\n  //                     Eigen::MatrixXd omega_expansion\n  //                     =ParitySign(u3::ConjugationGrade(omega.SU3())+u3::ConjugationGrade(ket_lgi_labels.U3().SU3()))\n  //                       *k_inverse*Arel_matrices[arel_index]*ket_lgi_expansion;\n  //                     // std::cout<<k_inverse\n  //                     // <<std::endl<<std::endl\n  //                     // <<Arel_matrices[arel_index]<<std::endl<<std::endl<<ket_lgi_expansion<<std::endl;\n  //                     // std::cout<<\"operator\"<<std::endl;\n  //                     // std::cout<<operator_matrix<<std::endl;\n  //                     unit_rmes\n  //                       =bra_lgi_expansion.transpose()*operator_matrix*omega_expansion;\n  //                     // std::cout<<\"unit_rmes\"<<std::endl<<unit_rmes<<std::endl<<std::endl;                    \n  //                   }\n  //               }\n  //             // Act A on both lgi\n  //             if(Nsigmap==(Nsigma+unit_tensor.N0()))\n  //               {\n\n  //                 int arel_index_bra=arel_sectors.LookUpSectorIndex(bra_index,m,1);\n  //                 int arel_index_ket=arel_sectors.LookUpSectorIndex(ket_index,n,1);\n    \n  //                 // if((arel_index_bra==-1)&&(arel_index_ket==-1))\n  //                 //   if(u3::OuterMultiplicity(ket_lgi_labels.U3().SU3(),u3::SU3(2,0),omega.SU3()))\n  //                 //     if(u3::OuterMultiplicity(bra_lgi_labels.U3().SU3(),u3::SU3(2,0),omegap.SU3()))\n  //                 //       {\n  //                 //         std::cout<<unit_tensor.Str()<<std::endl;\n  //                 //         std::cout<<bra_lgi_labels.Str()<<\"  \"<<omegap.Str()<<Sp<<\"  \"<<ket_lgi_labels.Str()\n  //                 //         <<\"  \"<<omega.Str()<<S<<\"  \"<<arel_index_bra<<\"  \"<<arel_index_ket<<std::endl;\n  //                 //         std::cout<<bra_index<<\"   \"<<m<<\"  \"<<ket_index<<\"  \"<<n<<std::endl;\n  //                 //       }\n\n  //                 if((arel_index_bra!=-1)&&(arel_index_ket!=-1))\n  //                   {\n  //                     Eigen::MatrixXd Kmatrixp_inverse=k_matrix_map[bra_lgi_labels.U3()][omegap].inverse();\n  //                     double kp_inverse=Kmatrixp_inverse(0,0);\n\n  //                     Eigen::MatrixXd Kmatrix_inverse=k_matrix_map[ket_lgi_labels.U3()][omega].inverse();\n  //                     double k_inverse=Kmatrix_inverse(0,0);\n\n  //                     Eigen::MatrixXd omegap_expansion\n  //                     =ParitySign(u3::ConjugationGrade(omegap.SU3())+u3::ConjugationGrade(bra_lgi_labels.U3().SU3()))\n  //                       *kp_inverse*Arel_matrices[arel_index_bra]*bra_lgi_expansion;\n  //                     Eigen::MatrixXd omega_expansion\n  //                     =ParitySign(u3::ConjugationGrade(omega.SU3())+u3::ConjugationGrade(ket_lgi_labels.U3().SU3()))\n  //                       *k_inverse*Arel_matrices[arel_index_ket]*ket_lgi_expansion;\n                      \n\n  //                     unit_rmes=omegap_expansion.transpose()*operator_matrix*omega_expansion;\n  //                     // if(m==0 && n==0 && d<2)\n  //                     //   {\n  //                     //     std::cout<<omegap.Str()<<\"  \"<<unit_tensor.Str()<<\"  \"<<omega.Str()<<std::endl;\n  //                     //     std::cout<<\"operator\"<<std::endl;\n  //                     //     std::cout<<operator_matrix<<std::endl<<std::endl;\n  //                     //     std::cout<<\"bra \"<<std::endl;\n  //                     //     std::cout<<(Arel_matrices[arel_index_bra]*bra_lgi_expansion).transpose()<<std::endl<<std::endl;\n  //                     //     std::cout<<\"ket \"<<std::endl;\n  //                     //     std::cout<<(Arel_matrices[arel_index_ket]*ket_lgi_expansion)<<std::endl<<std::endl;\n  //                     //     std::cout<<\"rme\"<<std::endl;\n  //                     //     std::cout<<(Arel_matrices[arel_index_bra]*bra_lgi_expansion).transpose()\n  //                     //     *operator_matrix*Arel_matrices[arel_index_ket]*ket_lgi_expansion\n  //                     //     <<std::endl<<\"  \"<<kp_inverse<<\"  \"<<k_inverse<<std::endl;\n  //                     //     std::cout<<\"unit tensors\"<<std::endl;\n  //                     //     std::cout<<unit_rmes<<std::endl<<std::endl;\n  //                     //     ++d;\n  //                     //   }\n  //                   }\n  //               }\n  //             // Act A on ket lgi\n  //             if(Nsigmap==(Nsigma+unit_tensor.N0()-2))\n  //               {\n\n  //                 int arel_index=arel_sectors.LookUpSectorIndex(bra_index,m,1);\n  //                 if(arel_index!=-1)\n  //                   {\n  //                     Eigen::MatrixXd Kmatrix_inverse=k_matrix_map[bra_lgi_labels.U3()][omegap].inverse();\n  //                     double k_inverse=Kmatrix_inverse(0,0);\n\n  //                     Eigen::MatrixXd omegap_expansion\n  //                     =ParitySign(u3::ConjugationGrade(omegap.SU3())+u3::ConjugationGrade(bra_lgi_labels.U3().SU3()))\n  //                       *k_inverse*Arel_matrices[arel_index]*bra_lgi_expansion;\n\n  //                     unit_rmes=omegap_expansion.transpose()\n  //                               *operator_matrix\n  //                               *ket_lgi_expansion;\n  //                   }\n  //               }\n  //                 if(not CheckIfZeroMatrix(unit_rmes,zero_threshold))\n  //                   // If nonzero, save unit tensor rmes to cache\n  //                   unit_tensor_sector_cache_explicit[lgi_pair][NnpNn][unit_U3Sector]\n  //                      =unit_rmes;      \n  //           }\n  //       }\n\n  // }\n}// end namespace\n\nint main(int argc, char **argv)\n{\n      // //REMOVE\n      // int testb=3;\n      // int testk=3;\n\n  u3::U3CoefInit();\n  //unit tensor cache \n  u3::UCoefCache u_coef_cache;\n  u3::PhiCoefCache phi_coef_cache;\n\n\tu3::g_u_cache_enabled = true;\n  double zero_threshold=1e-8;\n  // For GenerateRelativeUnitTensors\n  // should be consistant with lsu3shell tensors\n  int T0=0;\n  int J0=-1;\n  // parse arguments\n  if (argc<8)\n    {\n      std::cout << \"Syntax: A twice_Nsigma0 Nsigma0_ex_max N1B Nmax <basis filename> <Nrel filename> <Brel filename> <Arel filename>\" \n                << std::endl;\n      std::exit(1);\n    }\n  int A = std::stoi(argv[1]); \n  int twice_Nsigma0= std::stoi(argv[2]);\n  int Nsigma0_ex_max=std::stoi(argv[3]);\n  int N1b=std::stoi(argv[4]);\n  int Nmax = std::stoi(argv[5]);\n  std::string lsu3_filename = argv[6];\n  std::string nrel_filename = argv[7];\n  std::string brel_filename = argv[8];\n  std::string arel_filename = argv[9];\n\n  HalfInt Nsigma_0=HalfInt(twice_Nsigma0,2);\n  //initializing map that will store map containing unit tensors {SpIrrep pair : {}  \n  // inner map is keyed by unit tensor matrix element labels of type UnitTensorRME\n  // SpIrrep pair -> NnpNn -> UnitTensorRME -> v'v subsector\n  spncci::LGIUnitTensorSectorCache unit_tensor_sector_cache;\n  // Texting cache for rme's computed from explicit basis construction\n  spncci::LGIUnitTensorSectorCache unit_tensor_sector_cache_explicit;\n\n  //////////////////////////////////////////////////////////////////////////////////////////\n  // Get LGI's and populate sector map with LGI rme's\n  //////////////////////////////////////////////////////////////////////////////////////////\n  // Generating LGI matrix elements \n  lsu3shell::LSU3ShellBasisTable basis_table;\n  lsu3shell::U3SPNBasisLSU3Labels basis_provenance;\n  u3shell::SpaceU3SPN space;\n  // Read in lsu3shell basis \n  lsu3shell::ReadLSU3ShellBasis(Nsigma_0,lsu3_filename, basis_table, basis_provenance, space);\n\n  // // Writing out lsu3shell basis\n  // std::cout<<\"lsu3shell basis\"<<std::endl;\n  // for(int subspace_index=0; subspace_index<space.size(); ++subspace_index)\n  //   {\n  //     const u3shell::SubspaceU3SPN& subspace = space.GetSubspace(subspace_index);\n  //     std::cout\n  //       << fmt::format(\"subspace {} labels {} dim {}\",\n  //                      subspace_index,\n  //                      subspace.U3SPN().Str(),\n  //                      subspace.size()\n  //         )\n  //       << std::endl;\n  //   }\n\n  //Get LGI expansion by solving for null space of Brel and Ncm\n  std::ifstream is_brel(brel_filename.c_str());\n  std::ifstream is_nrel(nrel_filename.c_str());\n  lgi::MultiplicityTaggedLGIVector lgi_vector;\n  basis::MatrixVector lgi_expansion_matrix_vector;\n  lgi::GenerateLGIExpansion(A,Nsigma_0,basis_table,space, is_brel,is_nrel,lgi_vector,lgi_expansion_matrix_vector);\n  is_brel.close();\n  is_nrel.close();\n\n\n  // Read in Arel for unit tensor rme check\n  // TODO: comment out once rme's are validated\n  basis::MatrixVector Arel_matrices;\n  u3shell::OperatorLabelsU3ST arel_labels(2,u3::SU3(2,0),0,0,0);\n  u3shell::SectorsU3SPN arel_sectors(space,arel_labels,true);\n\n  std::ifstream is_arel(arel_filename.c_str());\n  if(not is_arel)\n    std::cout<<fmt::format(\"{} not found\",arel_filename)<<std::endl;\n\n  lsu3shell::ReadLSU3ShellRMEs(\n    is_arel,arel_labels,basis_table,space,\n    arel_sectors,Arel_matrices);\n  is_arel.close();\n\n  // for(auto arel : Arel_matrices)\n  //   std::cout<<arel<<std::endl<<std::endl;\n\n  // Extract LGI labels and store in lgi_vector\n  // lgi::GetLGILabels(Nsigma_0,space,lgi_expansion_matrix_vector, lgi_vector);\n  int i=0;\n  for(auto lgi_tagged : lgi_vector)\n  {\n    std::cout<<i<<\"  \"<<lgi_tagged.Str()<<\"  \"<<lgi_tagged.tag<<std::endl;\n    ++i;\n  }\n\n  // Setting up the symplectic basis containers\n  spncci::SigmaIrrepMap sigma_irrep_map;\n  spncci::SpNCCISpace sp_irrep_vector;\n  spncci::NmaxTruncator truncator(Nsigma_0,Nmax);\n  // Generating sp3r irreps\n  spncci::GenerateSpNCCISpace(lgi_vector,truncator,sp_irrep_vector,sigma_irrep_map);\n\n  //////////////////////////////////////////////////////////////////////////////////////////\n  //Precomputing Kmatrices \n  //////////////////////////////////////////////////////////////////////////////////////////\n  std::unordered_set<u3::U3,boost::hash<u3::U3> >sigma_set;\n  for(int l=0; l<sp_irrep_vector.size(); l++)\n    {\n      sigma_set.insert(sp_irrep_vector[l].sigma());\n    }\n  std::unordered_map<u3::U3,vcs::MatrixCache, boost::hash<u3::U3>> k_matrix_map;\n  for( const auto& s : sigma_set)\n    {\n      vcs::MatrixCache& k_map=k_matrix_map[s];\n      // int Nex=int(s.N()-Nsigma_0);\n      // vcs::GenerateKMatricesOpenMP(sigma_irrep_map[s], k_map);\n      bool is_intrinsic=true;\n      vcs::GenerateKMatrices(sigma_irrep_map[s], k_map,is_intrinsic);\n\n      std::cout<<\"kmap \"<<s.Str()<<std::endl;\n      for(auto it=k_map.begin(); it!=k_map.end(); ++it)\n        std::cout<<it->first.Str()<<\"  \"<<it->second<<std::endl;\n    }\n\n  // Labels of relative unit tensors computed between LGI's\n  std::vector<u3shell::RelativeUnitTensorLabelsU3ST> LGI_unit_tensor_labels;  \n  std::cout<<\"Nsigma0_ex_max \"<<Nsigma0_ex_max<<std::endl;\n\n  //////////////////////////////////////////////////////////////////////////////////////////\n  //Explicit construction of basis\n  //////////////////////////////////////////////////////////////////////////////////////////\n  // std::cout<<\"Explicit construction of basis\"<<std::endl;\n  // basis::MatrixVector spncci_expansions;\n  // spncci::BabySpNCCISpace baby_spncci_space2(sp_irrep_vector);\n  // ConstructSpNCCIBasisExplicit(space,sp_irrep_vector,lgi_expansion_matrix_vector,\n  //     baby_spncci_space2,k_matrix_map,\n  //     arel_sectors,Arel_matrices,\n  //     spncci_expansions\n  //   );\n\n  //////////////////////////////////////////////////////////////////////////////////////////\n  //Transform unit tensors\n  //////////////////////////////////////////////////////////////////////////////////////////\n\n  // -1 is all J0, T0=0 and false->don't restrict N0 to positive (temp)\n  u3shell::GenerateRelativeUnitTensorLabelsU3ST(Nsigma0_ex_max,N1b, LGI_unit_tensor_labels,J0,T0,false);\n\n  // For each operator, transform from lsu3shell basis to spncci basis\n  std::cout<<\"Number of lgi unit tensors \"<<LGI_unit_tensor_labels.size()<<std::endl;\n  \n  for(int i=0; i<LGI_unit_tensor_labels.size(); ++i)\n    {\n      //Get unit tensor labels\n      u3shell::RelativeUnitTensorLabelsU3ST unit_tensor(LGI_unit_tensor_labels[i]);\n      // std::cout<<\"unit tensor \"<<i<<\"  \"<<unit_tensor.Str()<<std::endl;\n      u3shell::OperatorLabelsU3ST operator_labels(unit_tensor);\n      // Generate sectors from labels\n      u3shell::SectorsU3SPN operator_sectors(space,operator_labels,false);\n      // Read in lsu3shell rme's of unit tensor\n      std::ifstream is_operator(fmt::format(\"relative_unit_{:06d}.rme\",i));\n      // If operator is not found, print name and continue;\n      if(not is_operator)\n        {\n          std::cout<<fmt::format(\"relative_unit_{:06d}.rme not found\",i)<<std::endl;\n          continue;\n        }\n\n      // Read in operator from file\n      // std::cout<<fmt::format(\"Transforming relative_unit_{:06d}.rme\",i)<<std::endl;\n      // std::cout<< LGI_unit_tensor_labels[i].Str()<<std::endl;\n      // std::cout<<\"  Reading in rmes\"<<std::endl;\n      basis::MatrixVector lsu3shell_operator_matrices(operator_sectors.size());\n      lsu3shell::ReadLSU3ShellRMEs(\n        is_operator,operator_labels, basis_table,space, \n        operator_sectors,lsu3shell_operator_matrices\n        );\n\n        basis::MatrixVector spncci_operator_matrices;\n        lgi::TransformOperatorToSpBasis(\n          operator_sectors,lgi_expansion_matrix_vector,\n          lsu3shell_operator_matrices,spncci_operator_matrices\n          );\n\n\n      // explicit basis construction unit tensor matrix elements\n      // for comparison with Sp-NCCI\n      //\n      // spncci::ComputeUnitTensorSectorsExplicit(\n      //   unit_tensor,space,operator_sectors,lsu3shell_operator_matrices,\n      //   baby_spncci_space2,spncci_expansions,unit_tensor_sector_cache_explicit);\n\n\n\n      // std::cout<<\"traversing the explicit map\"<<std::endl;\n      //   for(auto it=unit_tensor_sector_cache_explicit.begin(); it!=unit_tensor_sector_cache_explicit.end(); ++it)\n      //     {\n      //       if((it->first.first!=0)||(it->first.second!=0))\n      //         continue;\n      //       std::cout<<it->first.first<<\"  \"<<it->first.second<<std::endl;\n      //       for(auto it2=it->second.begin(); it2!=it->second.end(); ++it2)\n      //         {\n      //           std::cout<<\"  \"<<it2->first.first<<\"  \"<<it2->first.second<<std::endl;\n      //           for(auto it3=it2->second.begin(); it3!=it2->second.end();++ it3)\n      //             {\n      //               std::cout<<it3->first.Str()<<std::endl;\n      //               std::cout<<it3->second<<std::endl;\n      //             }\n      //         }\n      //     }\n\n      // std::cout<<\"lgi expansions\"<<std::endl;\n      // for(auto matrix :lgi_expansion_matrix_vector)\n      //   std::cout<<matrix<<std::endl<<std::endl;\n\n      // Populate unit tensor map with sectors\n      // std::cout<<\"Populating lgi sectors\"<<std::endl;\n      std::pair<int,int> N0_pair(0,0);\n\n      for(int s=0; s<operator_sectors.size(); ++s)\n        {\n          int i=operator_sectors.GetSector(s).bra_subspace_index();\n          int j=operator_sectors.GetSector(s).ket_subspace_index();\n          int rho0=operator_sectors.GetSector(s).multiplicity_index();\n          std::pair<int,int>sp_irrep_pair(i,j);\n          u3::U3 sigmap=sp_irrep_vector[i].sigma();\n          u3::U3 sigma=sp_irrep_vector[j].sigma();\n\n          // //REMOVE\n          // if(sp_irrep_vector[i].Sp()!=HalfInt(1,2) || sp_irrep_vector[i].Sn()!=HalfInt(1,2) || sp_irrep_vector[i].S()!=0)\n          //   continue;\n          // if(sp_irrep_vector[j].Sp()!=HalfInt(1,2) || sp_irrep_vector[j].Sn()!=HalfInt(1,2) || sp_irrep_vector[j].S()!=0)\n          //   continue;\n\n          if(Nmax==0 && sigma.N()>Nsigma_0)\n            continue;\n          if(Nmax==0 && sigmap.N()>Nsigma_0)\n            continue;\n          spncci::UnitTensorU3Sector u3_sector(sigmap,sigma,unit_tensor,rho0);\n          if(not CheckIfZeroMatrix(spncci_operator_matrices[s],zero_threshold))\n            {\n              unit_tensor_sector_cache[sp_irrep_pair][N0_pair][u3_sector]\n                  =spncci_operator_matrices[s];\n              \n              unit_tensor_sector_cache_explicit[sp_irrep_pair][N0_pair][u3_sector]\n                  =spncci_operator_matrices[s];\n              \n              // if((i==0) && (j==0))\n              // {\n              // std::cout<<i<<\"  \"<<j<<std::endl;\n              // std::cout<<u3_sector.Str()<<std::endl;\n              // std::cout<<spncci_operator_matrices[s]<<std::endl;\n              // }\n            }\n        }\n    }\n\n\n  // spncci::ConstructSpNCCIBasisExplicit(sp_irrep_vector,\n  //   lgi_expansion_matrix_vector,\n  //   space,\n  //   arel_sectors,\n  //   Arel_matrices,\n  //   k_matrix_map\n  // );\n\n \n\n\n  // for(auto it=unit_tensor_sector_cache.begin(); it!=unit_tensor_sector_cache.end(); ++it)\n  //   {\n  //     std::cout<<\"Irreps \"<<it->first.first<<\" and \"<<it->first.second<<std::endl;\n  //   }\n\n  // std::cout<<\"traversing the map\"<<std::endl;\n  // auto it_ending=unit_tensor_sector_cache.begin();\n  // for(int i=0; i<unit_tensor_sector_cache.size(); ++i) \n  //   it_ending++;\n\n  // for(auto it=unit_tensor_sector_cache.begin(); it!=unit_tensor_sector_cache.end(); ++it)\n  //   {\n\n  //     // //REMOVE\n  //     // if(it->first.first!=0 || it->first.second!=3)\n  //     //   continue;\n  //     // //\n\n  //     std::cout<<it->first.first<<\"  \"<<it->first.second<<std::endl;\n\n  //     for(auto it2=it->second.begin(); it2!=it->second.end(); ++it2)\n  //       {\n  //         std::cout<<\"  \"<<it2->first.first<<\"  \"<<it2->first.second<<std::endl;\n  //         for(auto it3=it2->second.begin(); it3!=it2->second.end();++ it3)\n  //           {\n  //             std::cout<<it3->first.Str()<<std::endl;\n  //             std::cout<<it3->second<<std::endl;\n  //           }\n  //       }\n  //   }\n\n  std::cout<<\"Entering the recurrence\"<<std::endl;\n  //////////////////////////////////////////////////////////////////////////////////////////\n  // Computing unit tensor sectors\n  //////////////////////////////////////////////////////////////////////////////////////////\n  // if true, unit tensors restricted to N0>=0\n  // Nrel_max=Nmax+2N1b\n\n  std::map<int,std::vector<u3shell::RelativeUnitTensorLabelsU3ST>> unit_tensor_labels;\n  u3shell::GenerateRelativeUnitTensorLabelsU3ST(Nmax, N1b, unit_tensor_labels, J0,T0, false);\n  if(Nmax!=0)\n  {\n    std::map<int,double> timing_map;\n    std::map<int,std::vector<std::pair<int,int>>> lgi_distribution;\n    std::map<int,std::vector<int>>  sector_count_map;\n    std::map<int,std::vector<double>> individual_times;\n    std::map<int,u3::UCoefCache> u_cache_map;\n    std::pair<int,int> N0_pair(0,0);\n    int num_nodes=1;\n    int counter=0; \n    for(int n=0; n<num_nodes; ++n)\n      timing_map[n]=0;\n\n    for(auto it=unit_tensor_sector_cache.begin(); it!=unit_tensor_sector_cache.end(); ++it)\n    {\n      clock_t start_time=std::clock();\n\n      // //REMOVE\n      // if((it->first.first!=3 ) || (it->first.second!=0))\n      //   continue;\n\n      int node=counter%num_nodes;\n      assert(node<num_nodes);\n      //Timing data\n      spncci::GenerateUnitTensorMatrix(\n        N1b,Nmax,it->first,sp_irrep_vector,u_cache_map[node], phi_coef_cache,k_matrix_map,\n        unit_tensor_labels,unit_tensor_sector_cache);\n\n      double duration=(std::clock()-start_time)/(double) CLOCKS_PER_SEC;\n      int num_sector=unit_tensor_sector_cache[it->first][N0_pair].size();\n\n      timing_map[node]+=duration;\n      individual_times[node].push_back(duration);\n      lgi_distribution[node].push_back(it->first);\n      sector_count_map[node].push_back(num_sector);\n      counter++;\n\n    }\n    // std::cout<<\"individual pairs\"<<std::endl;\n    // for(int n=0; n<num_nodes; ++n)\n    //   {\n    //     std::cout<<\"node\"<<n<<std::endl;\n    //     int i_stop=lgi_distribution[n].size();\n    //     for(int i=0; i<i_stop; ++i)\n    //       {\n    //         std::cout<<lgi_distribution[n][i].first<<\" \"<<lgi_distribution[n][i].second<<\"  \"\n    //         <<sector_count_map[n][i]<<\"  \"<<individual_times[n][i]<<std::endl;\n    //       }\n    //     std::cout<<\"  \"<<std::endl;\n\n    //   }\n\n    // std::cout<<\"summarizing\"<<std::endl;\n    // for(int n=0; n<num_nodes; ++n)\n    //   {\n    //     std::cout<<\"node \"<<n<<std::endl;\n    //     std::cout<<\" time \"<<timing_map[n]<<std::endl;\n    //     std::cout<<\" U cache size \"<<u_cache_map[n].size()<<std::endl;\n    //   } \n  }\n  bool assert_trap=true;\n\n  std::cout<<\"exiting the recurrence\"<<std::endl;\n  // std::cout<<\"traversing the map\"<<std::endl;\n  // std::cout<<\"cache size \"<<unit_tensor_sector_cache.size()<<std::endl;\n  for(auto it=unit_tensor_sector_cache_explicit.begin(); it!=unit_tensor_sector_cache_explicit.end(); ++it)\n    {\n      // if(it->first.first!=3 || it->first.second!=0)\n      //   continue;\n      // std::cout<<it->first.first<<\"  \"<<it->first.second<<std::endl;\n      for(auto it2=it->second.begin(); it2!=it->second.end(); ++it2)\n        {\n          if(it2->first.first!=0)\n            continue;\n          if(it2->first.second!=2)\n            continue;\n          // std::cout<<\"  \"<<it2->first.first<<\"  \"<<it2->first.second<<std::endl;\n          auto& explicit_cache=unit_tensor_sector_cache[it->first][it2->first];\n          for(auto it3=it2->second.begin(); it3!=it2->second.end();++ it3)\n            {\n              assert(assert_trap);\n\n              int rho0;\n              u3shell::RelativeUnitTensorLabelsU3ST tensor;\n              std::tie(std::ignore,std::ignore,tensor,rho0)=it3->first.Key();\n              // if(not (tensor.x0()==u3::SU3(0,0)))\n              //   continue;\n\n              // std::cout<<\"     \"<<it3->first.Str()<<std::endl;\n              // std::cout<<\"       \"<<it3->second<<std::endl;\n\n              if(explicit_cache.count(it3->first))\n              {\n                Eigen::MatrixXd& recurrence_matrix=it3->second;\n                \n                Eigen::MatrixXd& explicit_matrix=explicit_cache[it3->first];\n                if(not mcutils::IsZero(recurrence_matrix-explicit_matrix,1e-3))\n                {\n                  u3::U3 omega,omegap;\n                  std::tie(omegap,omega,std::ignore, std::ignore)=it3->first.Key();\n                  // if((omegap.N()==15)&&(omega.N()==15))\n                  //   continue;\n                  // // std::cout<<it->first.first<<\"  \"<<it->first.second<<std::endl;\n\n                  // if((it->first.first!=0 )|| (it->first.second!=24))\n                  //   continue;\n\n                  // if((it->first.first!=0 )&& (it->first.second!=0))\n                  //   continue;\n                  // if((it->first.first!=24 )&& (it->first.second!=24))\n                  //   continue;\n\n\n                  std::cout<<it->first.first<<\"  \"<<it->first.second<<std::endl;\n                  std::cout<<\"  \"<<it2->first.first<<\"  \"<<it2->first.second<<std::endl;\n                  std::cout<<\"     \"<<it3->first.Str()<<std::endl;\n\n                  std::cout<<\"recurrence\"<<std::endl;\n                  std::cout<<recurrence_matrix<<std::endl<<std::endl;\n                  std::cout<<\"explicit\"<<std::endl;\n                  std::cout<<explicit_matrix<<std::endl<<std::endl;\n                  \n                  Eigen::MatrixXd ratios(recurrence_matrix.rows(),recurrence_matrix.cols());\n                  for(int i=0; i<recurrence_matrix.rows(); ++i)\n                    for(int j=0; j<recurrence_matrix.cols(); ++j)\n                      ratios(i,j)=recurrence_matrix(i,j)/explicit_matrix(i,j);\n                  \n                  std::cout<<ratios<<std::endl<<std::endl;\n\n                  // assert_trap=false;\n                }\n              }\n              else \n              {\n                if(mcutils::IsZero(it3->second,1e-3))\n                  continue;\n                std::cout<<\"Explicit sector not found \"<<std::endl;\n                std::cout<<it->first.first<<\"  \"<<it->first.second<<std::endl;\n                std::cout<<\"  \"<<it2->first.first<<\"  \"<<it2->first.second<<std::endl;\n                std::cout<<\"     \"<<it3->first.Str()<<std::endl;\n                std::cout<<\"     \"<<it3->second<<std::endl<<std::endl;\n              }\n            }\n        }\n     }\n\n  //////////////////////////////////////////////////////////////////////////////////////////\n  // // Getting interaction\n  // //////////////////////////////////////////////////////////////////////////////////////////\n  // //TODO make input \n  // std::string interaction_file=\"JISP16_u3st.dat\";\n  // std::string interaction_file= \"K2intr_u3st.dat\";\n\n  // std::string interaction_file=\"Tintr_hw20.0_Nmax10_u3st.dat\";\n  // std::string interaction_file=\"r2intr_hw20.0_Nmax02_u3st.dat\";\n  // std::string interaction_file=\"spin_hw20.0_Nmax04_u3st.dat\";\n  std::string interaction_file=\"Hamiltonian_hw20.0_Nmax04_u3st.dat\";\n  // std::string interaction_file=\"Nintr_u3st.dat\";\n\n  // std::string interaction_file=\"trel_SU3_Nmax06.dat\";\n  // std::string interaction_file= \"Trel_upcouled\";\n\n  // std::string interaction_file=\"id_SU3_Nmax16.dat\";\n\n  // std::string interaction_file=\"Identity_u3st.dat\";\n \n  // std::string interaction_file=\"unit.dat\";\n  std::ifstream interaction_stream(interaction_file.c_str());\n  assert(interaction_stream);\n  \n  std::cout<<\"reading in interaction\"<<std::endl;\n  u3shell::RelativeRMEsU3ST interaction_rme_cache;\n  u3shell::ReadRelativeOperatorU3ST(interaction_stream, interaction_rme_cache);\n\n  // for(auto it=interaction_rme_cache.begin(); it!=interaction_rme_cache.end(); ++it)\n  //   std::cout<<it->second<<std::endl;\n\n  std::vector<u3shell::IndexedOperatorLabelsU3S> operator_u3s_list;\n  u3shell::GetInteractionTensorsU3S(interaction_rme_cache,operator_u3s_list);\n\n  // get baby SpNCCI space\n  spncci::BabySpNCCISpace baby_spncci_space(sp_irrep_vector);\n  \n  // Get U3S space \n  spncci::SpaceU3S u3s_space(baby_spncci_space);\n  // Storage for sectors, value gives sector index\n  \n  // spncci::SectorLabelsU3SCache u3s_sectors;\n  std::vector<spncci::SectorLabelsU3S> u3s_sector_vector;\n  // for(auto tensor : operator_u3s_list)\n  //   {\n  //     int kappa0, L0;\n  //     u3shell::OperatorLabelsU3S tensor_u3st;\n  //     std::tie(tensor_u3st,kappa0,L0)=tensor;\n  //     std::cout<<tensor_u3st.Str()<<\"  \"<<kappa0<<\"  \"<<L0<<std::endl;\n  //   }\n\n  spncci::GetSectorsU3S(u3s_space,operator_u3s_list,u3s_sector_vector);\n\n  std::cout<<\"contracting\"<<std::endl;\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  // Contracting\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  basis::MatrixVector matrix_vector;\n  basis::MatrixVector matrix_vector_explicit;\n  \n  spncci::ContractAndRegroupU3S(\n    Nmax, N1b,u3s_sector_vector,interaction_rme_cache,baby_spncci_space,\n    u3s_space,unit_tensor_sector_cache, matrix_vector);\n\n  // spncci::ContractAndRegroupU3S(\n  //   Nmax, N1b,u3s_sector_vector,interaction_rme_cache,baby_spncci_space,\n  //   u3s_space,unit_tensor_sector_cache_explicit, matrix_vector_explicit);\n\n\n  ZeroOutMatrix(matrix_vector,1e-4);\n  // ZeroOutMatrix(matrix_vector_explicit,1e-4);\n  \n  basis::MatrixVector difference_vector;\n  // for(int i=0; i<matrix_vector.size();++i)\n  //   difference_vector.push_back(matrix_vector_explicit[i]-matrix_vector[i]);\n  // ZeroOutMatrix(difference_vector,1e-4);\n\n  // std::cout<<\"printing\"<<std::endl;\n  // for(int i=0; i<u3s_space.size(); ++i)\n  //   std::cout<<i<<\"  \"<<u3s_space.GetSubspace(i).labels().Str()<<std::endl;\n  // for(int s=0; s<matrix_vector.size();  ++s)\n  //   {\n  //     if (not CheckIfZeroMatrix(matrix_vector[s], 1e-4))\n  //     {\n        \n  //       std::cout<<u3s_sector_vector[s].Str()<<\"  \"<<s<<std::endl;\n  //       std::cout<<matrix_vector[s]<<std::endl<<std::endl;\n        \n\n  //       // Eigen::MatrixXd difference=matrix_vector_explicit[s]-matrix_vector[s];\n        \n  //       // std::cout<<matrix_vector[s]<<std::endl<<std::endl;\n  //       // std::cout<<matrix_vector_explicit[s]<<std::endl<<std::endl;\n\n  //       // std::cout<<difference_vector[s]<<std::endl<<std::endl;\n  //     }\n  //   }\n\n\n  HalfInt J=1;\n  J0=0;\n  spncci::SpaceLS space_LS(u3s_space,J);\n  std::cout<<\"target_space size \"<<space_LS.size()<<std::endl;\n  basis::MatrixVector sectors_LS;\n\n  std::vector<spncci::OperatorLabelsLS> tensor_labels_LS;\n  spncci::GenerateOperatorLabelsLS(J0, tensor_labels_LS);\n  std::vector<spncci::SectorLabelsLS> sector_labels_LS;\n\n  // for(auto tensor_labels : tensor_labels_LS)\n  //   std::cout<<\"tensor \"<<tensor_labels.first<<\"  \"<<tensor_labels.second<<std::endl;\n\n  spncci::GetSectorsLS(space_LS,space_LS, tensor_labels_LS,sector_labels_LS);\n\n  // std::cout<<\"sectors\"<<std::endl;\n  // for(auto sector :target_sector_labels_LS)\n  //   std::cout<<sector.Str()<<std::endl;\n\n  spncci::ContractAndRegroupLSJ(\n    J,J0,J,\n    u3s_space,u3s_sector_vector,matrix_vector,\n    space_LS,space_LS,sector_labels_LS,sectors_LS\n  );\n\n  // ZeroOutMatrix(sectors_LS,1e-4);\n  // std::cout<<\"printing LS\"<<std::endl;\n  // for(int i=0; i<space_LS.size(); ++i)\n  //   std::cout<<i<<\"  \"<<space_LS.GetSubspace(i).Str()<<std::endl;\n    \n  // for(int s=0; s<sectors_LS.size();  ++s)\n  //   {\n  //     if (not CheckIfZeroMatrix(sectors_LS[s], 1e-4))\n  //     {\n  //       std::cout<<sector_labels_LS[s].Str()<<std::endl;\n  //       std::cout<<sectors_LS[s]<<std::endl<<std::endl;\n  //     }\n  //   }\n\n  Eigen::MatrixXd operator_matrix;\n\n  ConstructOperatorMatrix(space_LS,space_LS,sector_labels_LS,\n    sectors_LS,operator_matrix);\n\n  // for(auto it=unit_tensor_labels.begin(); it!=unit_tensor_labels.end(); ++it)\n  //   for(auto tensor : it->second)\n  //     std::cout<<tensor.Str()<<std::endl;\n  \n  // Mask matrix for sparsity\n  int num_nonzero=0;\n  int total=0;\n  // for(int i=0; i<operator_matrix.rows(); ++i)\n  //   for(int j=0; j<operator_matrix.cols(); ++j)\n  //     {\n  //       if(fabs(operator_matrix(i,j))>10e-6)\n  //       {\n  //         operator_matrix(i,j)=1;\n  //         num_nonzero++;\n  //       }\n  //       else\n  //         operator_matrix(i,j)=0;\n  //       total++;\n  //     }\n\n  // std::cout<<operator_matrix<<std::endl;\n\n\n\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(operator_matrix);\n  for(int i=0; i<10; ++i)\n    std::cout<<\"eigenvalues are \"<<es.eigenvalues()[i]<<std::endl;\n\n\n    // Spectra::DenseSymMatProd<double> op(operator_matrix);\n\n    // // Construct eigen solver object, requesting the largest three eigenvalues\n    // Spectra::SymEigsSolver< double, Spectra::SMALLEST_ALGE, Spectra::DenseSymMatProd<double> > eigs(&op, 5, 6);\n\n    // // Initialize and compute\n    // eigs.init();\n    // int nconv = eigs.compute();\n\n    // // Retrieve result\n    // Eigen::VectorXd evalues;\n    // if(eigs.info() == Spectra::SUCCESSFUL)\n    //     evalues = eigs.eigenvalues();\n    // else\n    //   std::cout<<\"failed\"<<std::endl;\n\n    // std::cout << \"Eigenvalues found:\\n\" << evalues << std::endl;\n\n\n\n\n  // std::cout<<std::endl<<\"total \"<<total<<\"  non-zero \"<<num_nonzero<<\"  percentage \"<<1.*num_nonzero/total<<std::endl;\n}\n", "meta": {"hexsha": "efda34a9aacf191aea1f02e393bd324521c2feff", "size": 40176, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "programs/unit_tensors/compute_unit_tensor_rmes.cpp", "max_stars_repo_name": "nd-nuclear-theory/spncci", "max_stars_repo_head_hexsha": "18b30e63ca62bfeea9bfadaf2bad3bfb166ce3e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-17T22:58:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-17T22:58:31.000Z", "max_issues_repo_path": "programs/unit_tensors/compute_unit_tensor_rmes.cpp", "max_issues_repo_name": "nd-nuclear-theory/spncci", "max_issues_repo_head_hexsha": "18b30e63ca62bfeea9bfadaf2bad3bfb166ce3e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-16T03:16:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-16T19:46:18.000Z", "max_forks_repo_path": "programs/unit_tensors/compute_unit_tensor_rmes.cpp", "max_forks_repo_name": "nd-nuclear-theory/spncci", "max_forks_repo_head_hexsha": "18b30e63ca62bfeea9bfadaf2bad3bfb166ce3e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-27T17:26:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-28T17:04:07.000Z", "avg_line_length": 41.2908530319, "max_line_length": 134, "alphanum_fraction": 0.5591397849, "num_tokens": 10905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.26286523886107827}}
{"text": "//\n// Copyright (c) 2017 CNRS\n//\n// This file is part of tsid\n// tsid is free software: you can redistribute it\n// and/or modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation, either version\n// 3 of the License, or (at your option) any later version.\n// tsid is distributed in the hope that it will be\n// useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// General Lesser Public License for more details. You should have\n// received a copy of the GNU Lesser General Public License along with\n// tsid If not, see\n// <http://www.gnu.org/licenses/>.\n//\n\n#ifndef EIQUADPROGFAST_HH_\n#define EIQUADPROGFAST_HH_\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n#define OPTIMIZE_STEP_1_2  // compute s(x) = ci^T * x + ci0\n#define OPTIMIZE_COMPUTE_D\n#define OPTIMIZE_UPDATE_Z\n#define OPTIMIZE_HESSIAN_INVERSE\n#define OPTIMIZE_UNCONSTR_MINIM\n//#define TRACE_SOLVER 1\n\n//#define USE_WARM_START\n//#define PROFILE_EIQUADPROG\n\n//#define DEBUG_STREAM(msg) std::cout<<msg;\n#define DEBUG_STREAM(msg)\n\n#ifdef PROFILE_EIQUADPROG\n#define START_PROFILER_EIQUADPROG_FAST START_PROFILER\n#define STOP_PROFILER_EIQUADPROG_FAST STOP_PROFILER\n#else\n#define START_PROFILER_EIQUADPROG_FAST\n#define STOP_PROFILER_EIQUADPROG_FAST\n#endif\n\n#define EIQUADPROG_FAST_CHOWLESKY_DECOMPOSITION \"EIQUADPROG_FAST Chowlesky dec\"\n#define EIQUADPROG_FAST_CHOWLESKY_INVERSE \"EIQUADPROG_FAST Chowlesky inv\"\n#define EIQUADPROG_FAST_ADD_EQ_CONSTR \"EIQUADPROG_FAST ADD_EQ_CONSTR\"\n#define EIQUADPROG_FAST_ADD_EQ_CONSTR_1 \"EIQUADPROG_FAST ADD_EQ_CONSTR_1\"\n#define EIQUADPROG_FAST_ADD_EQ_CONSTR_2 \"EIQUADPROG_FAST ADD_EQ_CONSTR_2\"\n#define EIQUADPROG_FAST_STEP_1 \"EIQUADPROG_FAST STEP_1\"\n#define EIQUADPROG_FAST_STEP_1_1 \"EIQUADPROG_FAST STEP_1_1\"\n#define EIQUADPROG_FAST_STEP_1_2 \"EIQUADPROG_FAST STEP_1_2\"\n#define EIQUADPROG_FAST_STEP_1_UNCONSTR_MINIM \"EIQUADPROG_FAST STEP_1_UNCONSTR_MINIM\"\n#define EIQUADPROG_FAST_STEP_2 \"EIQUADPROG_FAST STEP_2\"\n#define EIQUADPROG_FAST_STEP_2A \"EIQUADPROG_FAST STEP_2A\"\n#define EIQUADPROG_FAST_STEP_2B \"EIQUADPROG_FAST STEP_2B\"\n#define EIQUADPROG_FAST_STEP_2C \"EIQUADPROG_FAST STEP_2C\"\n\n#define DEFAULT_MAX_ITER 1000\n\nnamespace tsid {\n\nnamespace solvers {\n\n/**\n * Possible states of the solver.\n */\nenum EiquadprogFast_status {\n  EIQUADPROG_FAST_OPTIMAL = 0,\n  EIQUADPROG_FAST_INFEASIBLE = 1,\n  EIQUADPROG_FAST_UNBOUNDED = 2,\n  EIQUADPROG_FAST_MAX_ITER_REACHED = 3,\n  EIQUADPROG_FAST_REDUNDANT_EQUALITIES = 4\n};\n\nclass EiquadprogFast {\n public:\n  typedef Eigen::MatrixXd MatrixXd;\n  typedef Eigen::VectorXd VectorXd;\n  typedef Eigen::VectorXi VectorXi;\n\n  typedef Eigen::SparseMatrix<double> SpMat;\n  typedef Eigen::SparseVector<double> SpVec;\n  typedef Eigen::SparseVector<int> SpVeci;\n\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  EiquadprogFast();\n  virtual ~EiquadprogFast();\n\n  void reset(int dim_qp, int num_eq, int num_ineq);\n\n  int getMaxIter() const { return m_maxIter; }\n\n  bool setMaxIter(int maxIter) {\n    if (maxIter < 0) return false;\n    m_maxIter = maxIter;\n    return true;\n  }\n\n  /**\n   * @return The size of the active set, namely the number of\n   * active constraints (including the equalities).\n   */\n  int getActiveSetSize() const { return q; }\n\n  /**\n   * @return The number of active-set iteratios.\n   */\n  int getIteratios() const { return iter; }\n\n  /**\n   * @return The value of the objective function.\n   */\n  double getObjValue() const { return f_value; }\n\n  /**\n   * @return The Lagrange multipliers\n   */\n  const VectorXd& getLagrangeMultipliers() const { return u; }\n  /**\n   * Return the active set, namely the indeces of active constraints.\n   * The first nEqCon indexes are for the equalities and are negative.\n   * The last nIneqCon indexes are for the inequalities and start from 0.\n   * Only the first q elements of the return vector are valid, where q\n   * is the size of the active set.\n   * @return The set of indexes of the active constraints.\n   */\n  const VectorXi& getActiveSet() const { return A; }\n\n  /**\n   * solves the problem\n   * min. x' Hess x + 2 g0' x\n   * s.t. CE x + ce0 = 0\n   *      CI x + ci0 >= 0\n   */\n  EiquadprogFast_status solve_quadprog(const MatrixXd& Hess, const VectorXd& g0, const MatrixXd& CE,\n                                       const VectorXd& ce0, const MatrixXd& CI, const VectorXd& ci0, VectorXd& x);\n  /**\n   * solves the sparse problem\n   * min. x' Hess x + 2 g0' x\n   * s.t. CE x + ce0 = 0\n   *      CI x + ci0 >= 0\n   */\n  EiquadprogFast_status solve_quadprog_sparse(const SpMat& Hess, const VectorXd& g0, const MatrixXd& CE,\n                                              const VectorXd& ce0, const MatrixXd& CI, const VectorXd& ci0,\n                                              VectorXd& x);\n\n  MatrixXd m_J;  // J * J' = Hessian <nVars,nVars>::d\n  bool is_inverse_provided_;\n\n private:\n  int m_nVars;\n  int m_nEqCon;\n  int m_nIneqCon;\n\n  int m_maxIter;   /// max number of active-set iterations\n  double f_value;  /// current value of cost function\n\n  Eigen::LLT<MatrixXd, Eigen::Lower> chol_;  // <nVars,nVars>::d\n  // Eigen::LLT<MatrixXd,Eigen::Lower> chol_; // <nVars,nVars>::d\n\n  /// from QR of L' N, where L is Cholewsky factor of Hessian, and N is the matrix of active constraints\n  MatrixXd R;  // <nVars,nVars>::d\n\n  /// CI*x+ci0\n  VectorXd s;  // <nIneqCon>::d\n\n  /// infeasibility multipliers, i.e. negative step direction in dual space\n  VectorXd r;  // <nIneqCon+nEqCon>::d\n\n  /// Lagrange multipliers\n  VectorXd u;  // <nIneqCon+nEqCon>::d\n\n  /// step direction in primal space\n  VectorXd z;  // <nVars>::d\n\n  /// J' np\n  VectorXd d;  //<nVars>::d\n\n  /// current constraint normal\n  VectorXd np;  //<nVars>::d\n\n  /// active set (indeces of active constraints)\n  /// the first nEqCon indeces are for the equalities and are negative\n  /// the last nIneqCon indeces are for the inequalities are start from 0\n  VectorXi A;  // <nIneqCon+nEqCon>\n\n  /// initialized as K \\ A\n  /// iai(i)=-1 iff inequality constraint i is in the active set\n  /// iai(i)=i otherwise\n  VectorXi iai;  // <nIneqCon>::i\n\n  /// initialized as [1, ..., 1, .]\n  /// if iaexcl(i)!=1 inequality constraint i cannot be added to the active set\n  /// if adding ineq constraint i fails => iaexcl(i)=0\n  /// iaexcl(i)=0 iff ineq constraint i is linearly dependent to other active constraints\n  /// iaexcl(i)=1 otherwise\n  VectorXi iaexcl;  //<nIneqCon>::i\n\n  VectorXd x_old;  // old value of x <nVars>::d\n  VectorXd u_old;  // old value of u <nIneqCon+nEqCon>::d\n  VectorXi A_old;  // old value of A <nIneqCon+nEqCon>::i\n\n#ifdef OPTIMIZE_ADD_CONSTRAINT\n  VectorXd T1;  /// tmp variable used in add_constraint\n#endif\n\n  /// size of the active set A (containing the indices of the active constraints)\n  int q;\n\n  /// number of active-set iterations\n  int iter;\n\n  inline void compute_d(VectorXd& d, const MatrixXd& J, const VectorXd& np) {\n#ifdef OPTIMIZE_COMPUTE_D\n    d.noalias() = J.adjoint() * np;\n#else\n    d = J.adjoint() * np;\n#endif\n  }\n\n  inline void update_z(VectorXd& z, const MatrixXd& J, const VectorXd& d, int iq) {\n#ifdef OPTIMIZE_UPDATE_Z\n    z.noalias() = J.rightCols(z.size() - iq) * d.tail(z.size() - iq);\n#else\n    z = J.rightCols(J.cols() - iq) * d.tail(J.cols() - iq);\n#endif\n  }\n\n  inline void update_r(const MatrixXd& R, VectorXd& r, const VectorXd& d, int iq) {\n    r.head(iq) = d.head(iq);\n    R.topLeftCorner(iq, iq).triangularView<Eigen::Upper>().solveInPlace(r.head(iq));\n  }\n\n  inline bool add_constraint(MatrixXd& R, MatrixXd& J, VectorXd& d, int& iq, double& R_norm);\n\n  inline void delete_constraint(MatrixXd& R, MatrixXd& J, VectorXi& A, VectorXd& u, int nEqCon, int& iq, int l);\n};\n\n} /* namespace solvers */\n} /* namespace tsid */\n\n#endif /* EIQUADPROGFAST_HH_ */\n", "meta": {"hexsha": "168bd04b3567c009cfbce31928acf3d7476fe379", "size": 7798, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hpp/bezier-com-traj/solver/eiquadprog-fast.hpp", "max_stars_repo_name": "nim65s/hpp-bezier-com-traj", "max_stars_repo_head_hexsha": "7cb25463a353cd917468af12e5b325c8366af66e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-09-17T13:06:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T22:52:40.000Z", "max_issues_repo_path": "include/hpp/bezier-com-traj/solver/eiquadprog-fast.hpp", "max_issues_repo_name": "nim65s/hpp-bezier-com-traj", "max_issues_repo_head_hexsha": "7cb25463a353cd917468af12e5b325c8366af66e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-01-16T10:02:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-16T17:14:00.000Z", "max_forks_repo_path": "include/hpp/bezier-com-traj/solver/eiquadprog-fast.hpp", "max_forks_repo_name": "nim65s/hpp-bezier-com-traj", "max_forks_repo_head_hexsha": "7cb25463a353cd917468af12e5b325c8366af66e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-02-04T14:36:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-20T15:42:17.000Z", "avg_line_length": 31.6991869919, "max_line_length": 114, "alphanum_fraction": 0.7065914337, "num_tokens": 2361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883592602049, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2627765675789146}}
{"text": "//------------------------------------------------------------------------------\n/*\n    This file is part of jbcoind: https://github.com/jbcoin/jbcoind\n    Copyright (c) 2012, 2013 JBCoin Labs Inc.\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\n    ANY  SPECIAL ,  DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n    WHATSOEVER  RESULTING  FROM  LOSS  OF USE, DATA OR PROFITS, WHETHER IN AN\n    ACTION  OF  CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n*/\n//==============================================================================\n\n#include <jbcoin/basics/contract.h>\n#include <jbcoin/protocol/IOUAmount.h>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <algorithm>\n#include <numeric>\n#include <iterator>\n#include <stdexcept>\n\nnamespace jbcoin {\n\n/* The range for the mantissa when normalized */\nstatic std::int64_t const minMantissa = 1000000000000000ull;\nstatic std::int64_t const maxMantissa = 9999999999999999ull;\n/* The range for the exponent when normalized */\nstatic int const minExponent = -96;\nstatic int const maxExponent = 80;\n\nvoid\nIOUAmount::normalize ()\n{\n    if (mantissa_ == 0)\n    {\n        *this = beast::zero;\n        return;\n    }\n\n    bool const negative = (mantissa_ < 0);\n\n    if (negative)\n        mantissa_ = -mantissa_;\n\n    while ((mantissa_ < minMantissa) && (exponent_ > minExponent))\n    {\n        mantissa_ *= 10;\n        --exponent_;\n    }\n\n    while (mantissa_ > maxMantissa)\n    {\n        if (exponent_ >= maxExponent)\n            Throw<std::overflow_error> (\"IOUAmount::normalize\");\n\n        mantissa_ /= 10;\n        ++exponent_;\n    }\n\n    if ((exponent_ < minExponent) || (mantissa_ < minMantissa))\n    {\n        *this = beast::zero;\n        return;\n    }\n\n    if (exponent_ > maxExponent)\n        Throw<std::overflow_error> (\"value overflow\");\n\n    if (negative)\n        mantissa_ = -mantissa_;\n}\n\nIOUAmount&\nIOUAmount::operator+= (IOUAmount const& other)\n{\n    if (other == beast::zero)\n        return *this;\n\n    if (*this == beast::zero)\n    {\n        *this = other;\n        return *this;\n    }\n\n    auto m = other.mantissa_;\n    auto e = other.exponent_;\n\n    while (exponent_ < e)\n    {\n        mantissa_ /= 10;\n        ++exponent_;\n    }\n\n    while (e < exponent_)\n    {\n        m /= 10;\n        ++e;\n    }\n\n    // This addition cannot overflow an std::int64_t but we may throw from\n    // normalize if the result isn't representable.\n    mantissa_ += m;\n\n    if (mantissa_ >= -10 && mantissa_ <= 10)\n    {\n        *this = beast::zero;\n        return *this;\n    }\n\n    normalize ();\n\n    return *this;\n}\n\nbool\nIOUAmount::operator<(IOUAmount const& other) const\n{\n    // If the two amounts have different signs (zero is treated as positive)\n    // then the comparison is true iff the left is negative.\n    bool const lneg = mantissa_ < 0;\n    bool const rneg = other.mantissa_ < 0;\n\n    if (lneg != rneg)\n        return lneg;\n\n    // Both have same sign and the left is zero: the right must be\n    // greater than 0.\n    if (mantissa_ == 0)\n        return other.mantissa_ > 0;\n\n    // Both have same sign, the right is zero and the left is non-zero.\n    if (other.mantissa_ == 0)\n        return false;\n\n    // Both have the same sign, compare by exponents:\n    if (exponent_ > other.exponent_)\n        return lneg;\n    if (exponent_ < other.exponent_)\n        return !lneg;\n\n    // If equal exponents, compare mantissas\n    return mantissa_ < other.mantissa_;\n}\n\nstd::string\nto_string (IOUAmount const& amount)\n{\n    // keep full internal accuracy, but make more human friendly if possible\n    if (amount == beast::zero)\n        return \"0\";\n\n    int const exponent = amount.exponent ();\n    auto mantissa = amount.mantissa ();\n\n    // Use scientific notation for exponents that are too small or too large\n    if (((exponent != 0) && ((exponent < -25) || (exponent > -5))))\n    {\n        std::string ret = std::to_string (mantissa);\n        ret.append (1, 'e');\n        ret.append (std::to_string (exponent));\n        return ret;\n    }\n\n    bool negative = false;\n\n    if (mantissa < 0)\n    {\n        mantissa = -mantissa;\n        negative = true;\n    }\n\n    assert (exponent + 43 > 0);\n\n    size_t const pad_prefix = 27;\n    size_t const pad_suffix = 23;\n\n    std::string const raw_value (std::to_string (mantissa));\n    std::string val;\n\n    val.reserve (raw_value.length () + pad_prefix + pad_suffix);\n    val.append (pad_prefix, '0');\n    val.append (raw_value);\n    val.append (pad_suffix, '0');\n\n    size_t const offset (exponent + 43);\n\n    auto pre_from (val.begin ());\n    auto const pre_to (val.begin () + offset);\n\n    auto const post_from (val.begin () + offset);\n    auto post_to (val.end ());\n\n    // Crop leading zeroes. Take advantage of the fact that there's always a\n    // fixed amount of leading zeroes and skip them.\n    if (std::distance (pre_from, pre_to) > pad_prefix)\n        pre_from += pad_prefix;\n\n    assert (post_to >= post_from);\n\n    pre_from = std::find_if (pre_from, pre_to,\n        [](char c)\n        {\n            return c != '0';\n        });\n\n    // Crop trailing zeroes. Take advantage of the fact that there's always a\n    // fixed amount of trailing zeroes and skip them.\n    if (std::distance (post_from, post_to) > pad_suffix)\n        post_to -= pad_suffix;\n\n    assert (post_to >= post_from);\n\n    post_to = std::find_if(\n        std::make_reverse_iterator (post_to),\n        std::make_reverse_iterator (post_from),\n        [](char c)\n        {\n            return c != '0';\n        }).base();\n\n    std::string ret;\n\n    if (negative)\n        ret.append (1, '-');\n\n    // Assemble the output:\n    if (pre_from == pre_to)\n        ret.append (1, '0');\n    else\n        ret.append(pre_from, pre_to);\n\n    if (post_to != post_from)\n    {\n        ret.append (1, '.');\n        ret.append (post_from, post_to);\n    }\n\n    return ret;\n}\n\nIOUAmount\nmulRatio (\n    IOUAmount const& amt,\n    std::uint32_t num,\n    std::uint32_t den,\n    bool roundUp)\n{\n    using namespace boost::multiprecision;\n\n    if (!den)\n        Throw<std::runtime_error> (\"division by zero\");\n\n    // A vector with the value 10^index for indexes from 0 to 29\n    // The largest intermediate value we expect is 2^96, which\n    // is less than 10^29\n    static auto const powerTable = []\n    {\n        std::vector<uint128_t> result;\n        result.reserve (30);  // 2^96 is largest intermediate result size\n        uint128_t cur (1);\n        for (int i = 0; i < 30; ++i)\n        {\n            result.push_back (cur);\n            cur *= 10;\n        };\n        return result;\n    }();\n\n    // Return floor(log10(v))\n    // Note: Returns -1 for v == 0\n    static auto log10Floor = [](uint128_t const& v)\n    {\n        // Find the index of the first element >= the requested element, the index\n        // is the log of the element in the log table.\n        auto const l = std::lower_bound (powerTable.begin (), powerTable.end (), v);\n        int index = std::distance (powerTable.begin (), l);\n        // If we're not equal, subtract to get the floor\n        if (*l != v)\n            --index;\n        return index;\n    };\n\n    // Return ceil(log10(v))\n    static auto log10Ceil = [](uint128_t const& v)\n    {\n        // Find the index of the first element >= the requested element, the index\n        // is the log of the element in the log table.\n        auto const l = std::lower_bound (powerTable.begin (), powerTable.end (), v);\n        return int(std::distance (powerTable.begin (), l));\n    };\n\n    static auto const fl64 =\n        log10Floor (std::numeric_limits<std::int64_t>::max ());\n\n    bool const neg = amt.mantissa () < 0;\n    uint128_t const den128 (den);\n    // a 32 value * a 64 bit value and stored in a 128 bit value. This will never overflow\n    uint128_t const mul =\n        uint128_t (neg ? -amt.mantissa () : amt.mantissa ()) * uint128_t (num);\n\n    auto low = mul / den128;\n    uint128_t rem (mul - low * den128);\n\n    int exponent = amt.exponent ();\n\n    if (rem)\n    {\n        // Mathematically, the result is low + rem/den128. However, since this\n        // uses integer division rem/den128 will be zero. Scale the result so\n        // low does not overflow the largest amount we can store in the mantissa\n        // and (rem/den128) is as large as possible. Scale by multiplying low\n        // and rem by 10 and subtracting one from the exponent. We could do this\n        // with a loop, but it's more efficient to use logarithms.\n        auto const roomToGrow = fl64 - log10Ceil (low);\n        if (roomToGrow > 0)\n        {\n            exponent -= roomToGrow;\n            low *= powerTable[roomToGrow];\n            rem *= powerTable[roomToGrow];\n        }\n        auto const addRem = rem / den128;\n        low += addRem;\n        rem = rem - addRem * den128;\n    }\n\n    // The largest result we can have is ~2^95, which overflows the 64 bit\n    // result we can store in the mantissa. Scale result down by dividing by ten\n    // and adding one to the exponent until the low will fit in the 64-bit\n    // mantissa. Use logarithms to avoid looping.\n    bool hasRem = bool(rem);\n    auto const mustShrink = log10Ceil (low) - fl64;\n    if (mustShrink > 0)\n    {\n        uint128_t const sav (low);\n        exponent += mustShrink;\n        low /= powerTable[mustShrink];\n        if (!hasRem)\n            hasRem = bool(sav - low * powerTable[mustShrink]);\n    }\n\n    std::int64_t mantissa = low.convert_to<std::int64_t> ();\n\n    // normalize before rounding\n    if (neg)\n        mantissa *= -1;\n\n    IOUAmount result (mantissa, exponent);\n\n    if (hasRem)\n    {\n        // handle rounding\n        if (roundUp && !neg)\n        {\n            if (!result)\n            {\n                return IOUAmount (minMantissa, minExponent);\n            }\n            // This addition cannot overflow because the mantissa is already normalized\n            return IOUAmount (result.mantissa () + 1, result.exponent ());\n        }\n\n        if (!roundUp && neg)\n        {\n            if (!result)\n            {\n                return IOUAmount (-minMantissa, minExponent);\n            }\n            // This subtraction cannot underflow because `result` is not zero\n            return IOUAmount (result.mantissa () - 1, result.exponent ());\n        }\n    }\n\n    return result;\n}\n\n\n}\n", "meta": {"hexsha": "b43bb97354540288a7c1c8074b71358d0e57c38e", "size": 10744, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/jbcoin/protocol/impl/IOUAmount.cpp", "max_stars_repo_name": "gyas-kk/JBcoin", "max_stars_repo_head_hexsha": "b2cdc126d4db4f2913dac34ad3ba83c4e1543ce6", "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/jbcoin/protocol/impl/IOUAmount.cpp", "max_issues_repo_name": "gyas-kk/JBcoin", "max_issues_repo_head_hexsha": "b2cdc126d4db4f2913dac34ad3ba83c4e1543ce6", "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/jbcoin/protocol/impl/IOUAmount.cpp", "max_forks_repo_name": "gyas-kk/JBcoin", "max_forks_repo_head_hexsha": "b2cdc126d4db4f2913dac34ad3ba83c4e1543ce6", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-18T08:07:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-18T08:07:00.000Z", "avg_line_length": 27.9791666667, "max_line_length": 90, "alphanum_fraction": 0.5891660462, "num_tokens": 2768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244837, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.26271164077314424}}
{"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\nvoid Approximation::posterior_inference()\n{\n    if(WORKER == 0)\n    {\n        gettimeofday(&timeNow, NULL);\n        cout<<\"===========================> Processor 1: calculating posterior quantities 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\n    //Set WORKING_REGION_FLAG to false for all regions before the second finest level\n    memset(WORKING_REGION_FLAG,false,partition->nRegionsInTotal-partition->nRegionsAtEachLevel[NUM_LEVELS_M-1]-partition->nRegionsAtEachLevel[NUM_LEVELS_M-2]);\n\n    //Allocate memory for KCholTimesCurrentw (vector size: partition->nKnots)\n    KCholTimesCurrentw = new vec [partition->nRegionsInTotal];\n\n    //Allocate memory for KCholTimesCurrentA (cube size: first dimension: partition->nKnots, second dimesnion: partition->nKnots, third dimension or the number of slices: (partition->nRegionsInTotal-1)*partition->nRegionsInTotal/2)\n    KCholTimesCurrentA = new cube [partition->nRegionsInTotal-partition->nRegionsAtEachLevel[NUM_LEVELS_M-1]];\n\n    //Allocate memory for temporary variables\n    int maxOpenMPThreads=omp_get_max_threads();\n    vec* w = new vec [maxOpenMPThreads];\n    mat* A = new mat [maxOpenMPThreads];\n    double **tempMemory = new double* [maxOpenMPThreads];\n    for(int i = 0; i < maxOpenMPThreads; i++)\n    {\n            w[i].set_size(partition->nKnots);\n            A[i].set_size(partition->nKnots,partition->nKnots);\n            tempMemory[i] =  new double [partition->nKnots*partition->nKnots];\n    }\n\n    //Temporary variables if load ATilde from disk \n    int size=(NUM_LEVELS_M-1)*NUM_LEVELS_M/2;\n    unsigned long offset = partition->nRegionsInTotal-partition->nRegionsAtEachLevel[NUM_LEVELS_M-1];\n\n    //From the second finest to the coarsest level\n    for(int currentLevel = NUM_LEVELS_M-2; currentLevel > -1 ; currentLevel--)\n    {\n        double loglikelihoodThisLevel = 0;\n\n        #pragma omp parallel for num_threads(maxOpenMPThreads) reduction(+:loglikelihoodThisLevel) schedule(dynamic,1)\n        for(unsigned long iRegion = REGION_START[currentLevel]; iRegion < REGION_END[currentLevel] + 1; iRegion++)\n        {   \n            //Skip regions that are not dealt with by this worker\n            if( !WORKING_REGION_FLAG[iRegion] ) continue;\n\n            int rankOpenMP = omp_get_thread_num();\n\n            double loglikelihoodToAdd;\n            bool supervisor = true;\n            bool synchronizeFlag = false;\n\n            unsigned long indexReginAtThisLevel = iRegion - REGION_START[currentLevel];\n\n            //Deal with this region\n            if(SAVE_TO_DISK_FLAG) load_ATilde_from_disk(iRegion*NUM_PARTITIONS_J+1, iRegion*NUM_PARTITIONS_J+NUM_PARTITIONS_J, currentLevel == NUM_LEVELS_M-2, partition->nKnotsAtFinestLevel, offset, partition->nKnots, size);\n\n            aggregate_w_and_A(w[rankOpenMP], A[rankOpenMP], tempMemory[rankOpenMP], currentLevel, (currentLevel+1)*(currentLevel+2)/2-1, iRegion*NUM_PARTITIONS_J+1, iRegion*NUM_PARTITIONS_J+NUM_PARTITIONS_J, iRegion, supervisor, synchronizeFlag);\n\n            if(supervisor)\n            {\n                if(CALCULATION_MODE != \"prediction\")\n                    loglikelihoodToAdd = -2*sum(log(RChol[iRegion].diag()));\n\n                //Compute the posterior conditional variance-covariance matrix\n                RChol[iRegion] = chol( RChol[iRegion]*RChol[iRegion].t()+A[rankOpenMP],\"lower\");\n\n                //Compute KCholTimesCurrentw that is the Cholesky factor of the inverse of the conditional posterior variance-covariance matrix times w\n                KCholTimesCurrentw[iRegion].set_size(partition->nKnots);\n                KCholTimesCurrentw[iRegion] = solve(trimatl(RChol[iRegion]),w[rankOpenMP]);\n\n                //Compute KCholTimesCurrentA that is the Cholesky factor of the inverse of the conditional posterior variance-covariance matrix times A\n                KCholTimesCurrentA[iRegion].set_size(partition->nKnots,partition->nKnots,currentLevel);\n            }\n\n            //Get wTilde and ATilde\n            if(currentLevel != 0)\n                get_wTilde_and_ATilde_in_posterior(w[rankOpenMP],A[rankOpenMP], tempMemory[rankOpenMP], partition->nKnots, KCholTimesCurrentA[iRegion], KCholTimesCurrentw[iRegion], iRegion, currentLevel, supervisor, synchronizeFlag);\n\n            if(CALCULATION_MODE != \"prediction\")\n                KCholTimesCurrentA[iRegion].reset();\n\n            //Free wTilde and ATilde of the children to save memory\n            free_wTilde_and_ATilde(iRegion*NUM_PARTITIONS_J+1, iRegion*NUM_PARTITIONS_J+NUM_PARTITIONS_J);\n            if(!supervisor)\n            {\n                INDICES_REGIONS_AT_CURRENT_LEVEL.erase(iRegion);\n                WORKING_REGION_FLAG[iRegion] = false;\n            }\n            \n            if(supervisor && CALCULATION_MODE != \"prediction\")\n                loglikelihoodToAdd += 2*sum(log(RChol[iRegion].diag()))-dot(KCholTimesCurrentw[iRegion],KCholTimesCurrentw[iRegion]);\n            \n            if(supervisor && CALCULATION_MODE != \"prediction\")\n                loglikelihoodThisLevel += loglikelihoodToAdd;\n\n            if(CALCULATION_MODE != \"prediction\") \n                KCholTimesCurrentw[iRegion].reset();\n\n            if(supervisor && SAVE_TO_DISK_FLAG)\n            {\n                //save ATilde of the current region to disk\n                std::string fileName=TMP_DIRECTORY+\"/\"+std::to_string(iRegion)+\".bin\";\n                ATilde[iRegion].save(fileName,arma_binary);\n                ATilde[iRegion].reset();\n            }\n            \n        }\n        \n\n        if(currentLevel > 0)\n            synchronizeIndicesRegionsForEachWorker();\n\n        loglikelihood += loglikelihoodThisLevel;\n\n        timeval timeNow;\n        gettimeofday(&timeNow, NULL);\n\n        MPI_Barrier(WORLD);\n        if(WORKER == 0) cout<<\"Posterior: Level \"<<currentLevel+1<<\" 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    MPI_Request request;\n\n    if(CALCULATION_MODE!=\"prediction\")\n    {\n        if(WORKER != 0)\n            MPI_Isend(&loglikelihood,1,MPI_DOUBLE,0,MPI_TAG_LIKELIHOOD,WORLD, &request);\n        else\n        {\n            double likelihoodComponent;\n            for(int i = 1; i < MPI_SIZE; i++)\n            {\n                MPI_Recv(&likelihoodComponent,1,MPI_DOUBLE,i,MPI_TAG_LIKELIHOOD,WORLD,MPI_STATUS_IGNORE);\n                loglikelihood += likelihoodComponent;\n            }\n            cout<<\"The obtained loglikelihood is: \"<<-0.5*(loglikelihood+NUM_OBSERVATIONS*log(2*3.14159265359))<<endl;\n        }\n    }\n    \n\n    //Deallocate temporary memory\n    for(int i = 0; i < maxOpenMPThreads; i++)\n    {\n        w[i].reset();\n        A[i].reset();\n        delete[] tempMemory[i];\n    }\n    delete[] w;\n    delete[] A;\n    delete[] tempMemory;\n\n    if(WORKER == 0)\n    {\n        gettimeofday(&timeNow, NULL);\n        cout<<\"===========================>  Processor 1: calculating posterior quantities 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}", "meta": {"hexsha": "07342e7dad6ef73af8cbe27b0783281c700d0705", "size": 7494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "parallel_MRA/src/class_approximation-posterior-inference.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-posterior-inference.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-posterior-inference.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": 44.0823529412, "max_line_length": 248, "alphanum_fraction": 0.654657059, "num_tokens": 1875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.26269602450392293}}
{"text": "#include <pybind11/functional.h>\n#include <pybind11/operators.h>\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n\n#include <algorithm>\n#include <sstream>\n#include <stdexcept>\n#include <unordered_set>\n\n#define BOOST_POLYGON_NO_DEPS\n#define BOOST_NO_USER_CONFIG\n#define BOOST_NO_COMPILER_CONFIG\n#define BOOST_NO_STDLIB_CONFIG\n#define BOOST_NO_PLATFORM_CONFIG\n#define BOOST_HAS_STDINT_H\n\n#define __GLIBC__ 0\n\n#define private public\n\n#include <boost/polygon/voronoi.hpp>\n\nnamespace py = pybind11;\n\n#define MODULE_NAME _voronoi\n#define C_STR_HELPER(a) #a\n#define C_STR(a) C_STR_HELPER(a)\n#define BEACH_LINE_KEY_NAME \"BeachLineKey\"\n#define BEACH_LINE_VALUE_NAME \"BeachLineValue\"\n#define BIG_FLOAT_NAME \"BigFloat\"\n#define BIG_INT_NAME \"BigInt\"\n#define CIRCLE_EVENT_NAME \"CircleEvent\"\n#define COMPARISON_RESULT_NAME \"ComparisonResult\"\n#define GEOMETRY_CATEGORY_NAME \"GeometryCategory\"\n#define ORIENTATION_NAME \"Orientation\"\n#define POINT_NAME \"Point\"\n#define ROBUST_DIFFERENCE_NAME \"RobustDifference\"\n#define ROBUST_FLOAT_NAME \"RobustFloat\"\n#define SEGMENT_NAME \"Segment\"\n#define SITE_EVENT_NAME \"SiteEvent\"\n#define SOURCE_CATEGORY_NAME \"SourceCategory\"\n#define BUILDER_NAME \"Builder\"\n#define CELL_NAME \"Cell\"\n#define DIAGRAM_NAME \"Diagram\"\n#define EDGE_NAME \"Edge\"\n#define VERTEX_NAME \"Vertex\"\n#ifndef VERSION_INFO\n#define VERSION_INFO \"dev\"\n#endif\n\nusing coordinate_t = boost::polygon::detail::int32;\nusing Builder = boost::polygon::default_voronoi_builder;\nusing Diagram = boost::polygon::voronoi_diagram<double>;\nusing Cell = boost::polygon::voronoi_cell<double>;\nusing CircleEvent = boost::polygon::detail::circle_event<double>;\nusing UlpComparator = boost::polygon::detail::ulp_comparison<double>;\nusing ComparisonResult = UlpComparator::Result;\nusing CTypeTraits = boost::polygon::detail::voronoi_ctype_traits<coordinate_t>;\nusing BigFloat = CTypeTraits::efpt_type;\nusing BigInt = CTypeTraits::big_int_type;\nusing Edge = boost::polygon::voronoi_edge<double>;\nusing GeometryCategory = boost::polygon::GeometryCategory;\nusing Point = boost::polygon::detail::point_2d<coordinate_t>;\nusing RobustFloat = boost::polygon::detail::robust_fpt<double>;\nusing RobustDifference = boost::polygon::detail::robust_dif<RobustFloat>;\nusing RobustSumExpression = boost::polygon::detail::robust_sqrt_expr<\n    BigInt, BigFloat, boost::polygon::detail::type_converter_efpt>;\nusing SiteEvent = boost::polygon::detail::site_event<coordinate_t>;\nusing BeachLineKey = boost::polygon::detail::beach_line_node_key<SiteEvent>;\nusing SourceCategory = boost::polygon::SourceCategory;\nusing BeachLineValue =\n    boost::polygon::detail::beach_line_node_data<Edge, CircleEvent>;\nusing Predicates = boost::polygon::detail::voronoi_predicates<CTypeTraits>;\nusing EventComparisonPredicate =\n    Predicates::event_comparison_predicate<SiteEvent, CircleEvent>;\nusing Orientation = Predicates::orientation_test::Orientation;\nusing Vertex = boost::polygon::voronoi_vertex<double>;\n\nstatic int to_sign(coordinate_t value) {\n  return value > 0 ? 1 : (value < 0 ? -1 : 0);\n}\n\nstatic std::string bool_repr(bool value) { return py::str(py::bool_(value)); }\n\ntemplate <class Object>\nstd::string to_repr(const Object& object) {\n  std::ostringstream stream;\n  stream.precision(std::numeric_limits<double>::digits10 + 2);\n  stream << object;\n  return stream.str();\n}\n\ntemplate <class Object>\nstatic void write_pointer(std::ostream& stream, Object* value) {\n  if (value == nullptr)\n    stream << py::none();\n  else\n    stream << *value;\n}\n\ntemplate <typename Sequence>\nstatic void write_sequence(std::ostream& stream, const Sequence& sequence) {\n  stream << \"[\";\n  if (!sequence.empty()) {\n    stream << sequence[0];\n    std::for_each(std::next(std::begin(sequence)), std::end(sequence),\n                  [&stream](const typename Sequence::value_type& value) {\n                    stream << \", \" << value;\n                  });\n  }\n  stream << \"]\";\n};\n\nstruct Segment {\n  Point start, end;\n  Segment(const Point& start_, const Point& end_) : start(start_), end(end_) {}\n};\n\nnamespace boost {\nnamespace polygon {\nstatic std::ostream& operator<<(std::ostream& stream,\n                                const SourceCategory& source_category) {\n  stream << C_STR(MODULE_NAME) \".\" SOURCE_CATEGORY_NAME \".\";\n  switch (source_category) {\n    case SourceCategory::SOURCE_CATEGORY_SINGLE_POINT:\n      stream << \"SINGLE_POINT\";\n      break;\n    case SourceCategory::SOURCE_CATEGORY_SEGMENT_START_POINT:\n      stream << \"SEGMENT_START_POINT\";\n      break;\n    case SourceCategory::SOURCE_CATEGORY_SEGMENT_END_POINT:\n      stream << \"SEGMENT_END_POINT\";\n      break;\n    case SourceCategory::SOURCE_CATEGORY_INITIAL_SEGMENT:\n      stream << \"INITIAL_SEGMENT\";\n      break;\n    case SourceCategory::SOURCE_CATEGORY_REVERSE_SEGMENT:\n      stream << \"REVERSE_SEGMENT\";\n      break;\n    default:\n      stream << \"???\";\n      break;\n  }\n  return stream;\n}\n\nstatic std::ostream& operator<<(std::ostream& stream, const Builder& builder) {\n  stream << C_STR(MODULE_NAME) \".\" BUILDER_NAME \"(\" << builder.index_ << \", \";\n  write_sequence(stream, builder.site_events_);\n  return stream << \")\";\n}\n\nstatic std::ostream& operator<<(std::ostream& stream, const Cell& cell) {\n  return stream << C_STR(MODULE_NAME) \".\" CELL_NAME \"(\" << cell.source_index()\n                << \", \" << cell.source_category() << \")\";\n}\n\nstatic std::ostream& operator<<(std::ostream& stream, const Vertex& vertex) {\n  return stream << C_STR(MODULE_NAME) \".\" VERTEX_NAME \"(\" << vertex.x() << \", \"\n                << vertex.y() << \")\";\n}\n\nstatic std::ostream& operator<<(std::ostream& stream, const Edge& edge) {\n  stream << C_STR(MODULE_NAME) \".\" EDGE_NAME \"(\";\n  write_pointer(stream, edge.vertex0());\n  stream << \", \";\n  write_pointer(stream, edge.cell());\n  return stream << \", \" << bool_repr(edge.is_linear()) << \", \"\n                << bool_repr(edge.is_primary()) << \")\";\n}\n\nstatic bool operator==(const Vertex& left, const Vertex& right) {\n  static const voronoi_diagram_traits<double>::vertex_equality_predicate_type\n      comparator;\n  return comparator(left, right);\n}\n\nstatic std::ostream& operator<<(std::ostream& stream, const Diagram& diagram) {\n  stream << C_STR(MODULE_NAME) \".\" DIAGRAM_NAME \"(\";\n  write_sequence(stream, diagram.cells_);\n  stream << \", \";\n  write_sequence(stream, diagram.edges_);\n  stream << \", \";\n  write_sequence(stream, diagram.vertices_);\n  return stream << \")\";\n}\n\nnamespace detail {\nstatic std::ostream& operator<<(std::ostream& stream, const BigFloat& float_) {\n  return stream << C_STR(MODULE_NAME) \".\" BIG_FLOAT_NAME \"(\" << float_.val_\n                << \", \" << float_.exp_ << \")\";\n}\n\nstatic std::ostream& operator<<(std::ostream& stream, const BigInt& int_) {\n  stream << C_STR(MODULE_NAME) \".\" BIG_INT_NAME \"(\" << to_sign(int_.count())\n         << \", [\";\n  std::size_t size = int_.size();\n  const auto& chunks = int_.chunks();\n  if (size != 0) {\n    stream << chunks[0];\n    for (std::size_t index = 1; index < size; ++index)\n      stream << \", \" << chunks[index];\n  }\n  return stream << \"])\";\n}\n\nstatic bool operator==(const CircleEvent& left, const CircleEvent& right) {\n  return left.x() == right.x() && left.y() == right.y() &&\n         left.lower_x() == right.lower_x() &&\n         left.is_active() == right.is_active();\n}\n\nstatic std::ostream& operator<<(std::ostream& stream,\n                                const CircleEvent& event) {\n  return stream << C_STR(MODULE_NAME) \".\" CIRCLE_EVENT_NAME \"(\" << event.x()\n                << \", \" << event.y() << \", \" << event.lower_x() << \", \"\n                << bool_repr(event.is_active()) << \")\";\n}\n\nstatic std::ostream& operator<<(std::ostream& stream, const Point& point) {\n  return stream << C_STR(MODULE_NAME) \".\" POINT_NAME \"(\" << point.x() << \", \"\n                << point.y() << \")\";\n}\n\nstatic std::ostream& operator<<(std::ostream& stream,\n                                const RobustFloat& float_) {\n  return stream << C_STR(MODULE_NAME) \".\" ROBUST_FLOAT_NAME \"(\" << float_.fpv()\n                << \", \" << float_.re() << \")\";\n}\n\nstatic std::ostream& operator<<(std::ostream& stream,\n                                const RobustDifference& difference) {\n  return stream << C_STR(MODULE_NAME) \".\" ROBUST_DIFFERENCE_NAME \"(\"\n                << difference.pos() << \", \" << difference.neg() << \")\";\n}\n\nstatic std::ostream& operator<<(std::ostream& stream, const SiteEvent& event) {\n  return stream << C_STR(MODULE_NAME) \".\" SITE_EVENT_NAME \"(\" << event.point0()\n                << \", \" << event.point1() << \", \" << event.sorted_index()\n                << \", \" << event.initial_index() << \", \"\n                << bool_repr(event.is_inverse()) << \", \"\n                << event.source_category() << \")\";\n}\n\nstatic std::ostream& operator<<(std::ostream& stream, const BeachLineKey& key) {\n  return stream << C_STR(MODULE_NAME) \".\" BEACH_LINE_KEY_NAME \"(\"\n                << key.left_site() << \", \" << key.right_site() << \")\";\n}\n\nstatic std::ostream& operator<<(std::ostream& stream,\n                                const BeachLineValue& value) {\n  stream << C_STR(MODULE_NAME) \".\" BEACH_LINE_VALUE_NAME \"(\";\n  write_pointer(stream, value.edge());\n  stream << \", \";\n  write_pointer(stream, value.circle_event());\n  return stream << \")\";\n}\n}  // namespace detail\n\ntemplate <>\nstruct geometry_concept<Point> {\n  typedef point_concept type;\n};\n\ntemplate <>\nstruct point_traits<Point> {\n  typedef int coordinate_type;\n\n  static inline coordinate_type get(const Point& point, orientation_2d orient) {\n    return (orient == HORIZONTAL) ? point.x() : point.y();\n  }\n};\n\ntemplate <>\nstruct geometry_concept<Segment> {\n  typedef segment_concept type;\n};\n\ntemplate <>\nstruct segment_traits<Segment> {\n  typedef Segment segment_type;\n  typedef Point point_type;\n  typedef int coordinate_type;\n\n  static point_type get(const segment_type& segment, direction_1d dir) {\n    return dir.to_int() ? segment.end : segment.start;\n  }\n};\n}  // namespace polygon\n}  // namespace boost\n\nstatic std::ostream& operator<<(std::ostream& stream, const Segment& segment) {\n  return stream << C_STR(MODULE_NAME) \".\" SEGMENT_NAME \"(\" << segment.start\n                << \", \" << segment.end << \")\";\n}\n\nstatic bool operator==(const Segment& left, const Segment& right) {\n  return left.start == right.start && left.end == right.end;\n}\n\nPYBIND11_MODULE(MODULE_NAME, m) {\n  m.doc() = R\"pbdoc(Python binding of boost/polygon library.)pbdoc\";\n  m.attr(\"__version__\") = C_STR(VERSION_INFO);\n\n  py::enum_<ComparisonResult>(m, COMPARISON_RESULT_NAME)\n      .value(\"LESS\", ComparisonResult::LESS)\n      .value(\"EQUAL\", ComparisonResult::EQUAL)\n      .value(\"MORE\", ComparisonResult::MORE);\n\n  py::enum_<GeometryCategory>(m, GEOMETRY_CATEGORY_NAME)\n      .value(\"POINT\", GeometryCategory::GEOMETRY_CATEGORY_POINT)\n      .value(\"SEGMENT\", GeometryCategory::GEOMETRY_CATEGORY_SEGMENT);\n\n  py::enum_<Orientation>(m, ORIENTATION_NAME)\n      .value(\"RIGHT\", Orientation::RIGHT)\n      .value(\"COLLINEAR\", Orientation::COLLINEAR)\n      .value(\"LEFT\", Orientation::LEFT);\n\n  py::enum_<SourceCategory>(m, SOURCE_CATEGORY_NAME)\n      .value(\"SINGLE_POINT\", SourceCategory::SOURCE_CATEGORY_SINGLE_POINT)\n      .value(\"SEGMENT_START_POINT\",\n             SourceCategory::SOURCE_CATEGORY_SEGMENT_START_POINT)\n      .value(\"SEGMENT_END_POINT\",\n             SourceCategory::SOURCE_CATEGORY_SEGMENT_END_POINT)\n      .value(\"INITIAL_SEGMENT\", SourceCategory::SOURCE_CATEGORY_INITIAL_SEGMENT)\n      .value(\"REVERSE_SEGMENT\", SourceCategory::SOURCE_CATEGORY_REVERSE_SEGMENT)\n      .def(\"belongs\", &boost::polygon::belongs);\n\n  py::class_<BeachLineKey>(m, BEACH_LINE_KEY_NAME)\n      .def(py::init<SiteEvent>(), py::arg(\"site\"))\n      .def(py::init<SiteEvent, SiteEvent>(), py::arg(\"left_site\"),\n           py::arg(\"right_site\"))\n      .def(\"__repr__\", to_repr<BeachLineKey>)\n      .def(\n          \"__lt__\",\n          [](const BeachLineKey& self, const BeachLineKey& other) {\n            static const Predicates::node_comparison_predicate<BeachLineKey>\n                comparator;\n            return comparator(self, other);\n          },\n          py::is_operator())\n      .def(\n          \"to_comparison_y\",\n          [](const BeachLineKey& self, bool is_new_node) {\n            static const Predicates::node_comparison_predicate<BeachLineKey>\n                comparator;\n            return comparator.get_comparison_y(self, is_new_node);\n          },\n          py::arg(\"is_new_node\") = true)\n      .def_property_readonly(\n          \"comparison_site\",\n          [](const BeachLineKey& self) {\n            static const Predicates::node_comparison_predicate<BeachLineKey>\n                comparator;\n            return comparator.get_comparison_site(self);\n          })\n      .def_property_readonly(\n          \"left_site\",\n          [](const BeachLineKey& self) { return self.left_site(); })\n      .def_property_readonly(\"right_site\", [](const BeachLineKey& self) {\n        return self.right_site();\n      });\n\n  py::class_<BeachLineValue>(m, BEACH_LINE_VALUE_NAME)\n      .def(py::init([](Edge* edge, CircleEvent* circle_event) {\n             return BeachLineValue{edge}.circle_event(circle_event);\n           }),\n           py::arg(\"edge\"), py::arg(\"circle_event\") = nullptr)\n      .def(\"__repr__\", to_repr<BeachLineValue>)\n      .def_property_readonly(\n          \"edge\", [](const BeachLineValue& self) { return self.edge(); })\n      .def_property_readonly(\"circle_event\", [](const BeachLineValue& self) {\n        return self.circle_event();\n      });\n\n  py::class_<BigFloat>(m, BIG_FLOAT_NAME)\n      .def(py::init<double, int>(), py::arg(\"mantissa\"), py::arg(\"exponent\"))\n      .def(-py::self)\n      .def(py::self + py::self)\n      .def(py::self - py::self)\n      .def(py::self * py::self)\n      .def(py::self / py::self)\n      .def(py::self += py::self)\n      .def(py::self -= py::self)\n      .def(py::self *= py::self)\n      .def(py::self /= py::self)\n      .def(\"__bool__\",\n           [](const BigFloat& self) {\n             return !boost::polygon::detail::is_zero(self);\n           })\n      .def(\"__float__\", &BigFloat::d)\n      .def(\"__repr__\", to_repr<BigFloat>)\n      .def(\"sqrt\", &BigFloat::sqrt)\n      .def_readonly(\"exponent\", &BigFloat::exp_)\n      .def_readonly(\"mantissa\", &BigFloat::val_);\n\n  py::class_<BigInt>(m, BIG_INT_NAME)\n      .def(py::init<boost::polygon::detail::int64>(), py::arg(\"value\"))\n      .def(py::init<>(\n               [](std::int8_t sign, const std::vector<std::uint32_t>& digits) {\n                 auto result = std::make_unique<BigInt>();\n                 result->count_ = to_sign(sign) * digits.size();\n                 std::copy(digits.begin(), digits.end(), result->chunks_);\n                 return result;\n               }),\n           py::arg(\"sign\"), py::arg(\"digits\"))\n      .def(-py::self)\n      .def(py::self + py::self)\n      .def(py::self - py::self)\n      .def(py::self * py::self)\n      .def(py::self + coordinate_t())\n      .def(py::self - coordinate_t())\n      .def(py::self * coordinate_t())\n      .def(\"__bool__\",\n           [](const BigInt& self) {\n             return !boost::polygon::detail::is_zero(self);\n           })\n      .def(\"__float__\", &BigInt::d)\n      .def(\"__repr__\", to_repr<BigInt>)\n      .def(\"frexp\", &BigInt::p)\n      .def_property_readonly(\n          \"digits\",\n          [](const BigInt& self) -> std::vector<std::uint32_t> {\n            std::size_t size = self.size();\n            std::vector<std::uint32_t> result;\n            const auto& chunks = self.chunks();\n            for (std::size_t index = 0; index < size; ++index)\n              result.push_back(chunks[index]);\n            return result;\n          })\n      .def_property_readonly(\"sign\", [](const BigInt& self) {\n        const auto count = self.count();\n        return to_sign(count);\n      });\n\n  py::class_<Builder>(m, BUILDER_NAME)\n      .def(py::init([](std::size_t index,\n                       const std::vector<SiteEvent>& site_events) {\n             auto result = std::make_unique<Builder>();\n             result->index_ = index;\n             result->site_events_ = site_events;\n             result->site_event_index_ =\n                 std::numeric_limits<std::size_t>::max();\n             return result;\n           }),\n           py::arg(\"index\") = 0,\n           py::arg(\"site_events\") = std::vector<SiteEvent>{})\n      .def(\"__repr__\", to_repr<Builder>)\n      .def(\"clear\", &Builder::clear)\n      .def(\"construct\", &Builder::construct<Diagram>, py::arg(\"diagram\"))\n      .def(\"init_beach_line\", &Builder::init_beach_line<Diagram>,\n           py::arg(\"diagram\"))\n      .def(\"init_sites_queue\", &Builder::init_sites_queue)\n      .def(\"insert_new_arc\",\n           [](Builder& self, const SiteEvent& arc_first_site,\n              const SiteEvent& arc_second_site, const SiteEvent& site,\n              Diagram* diagram) {\n             self.insert_new_arc(arc_first_site, arc_second_site, site,\n                                 self.beach_line_.end(), diagram);\n           })\n      .def(\n          \"insert_point\",\n          [](Builder* builder, const Point& point) {\n            return boost::polygon::insert(point, builder);\n          },\n          py::arg(\"point\"))\n      .def(\n          \"insert_segment\",\n          [](Builder* builder, const Segment& segment) {\n            return boost::polygon::insert(segment, builder);\n          },\n          py::arg(\"segment\"))\n      .def(\"process_circle_event\", &Builder::process_circle_event<Diagram>,\n           py::arg(\"diagram\"))\n      .def(\"process_site_event\", &Builder::process_site_event<Diagram>,\n           py::arg(\"diagram\"))\n      .def_property_readonly(\n          \"beach_line\",\n          [](Builder& self) {\n            std::vector<std::pair<BeachLineKey, BeachLineValue>> result;\n            for (auto& item : self.beach_line_) {\n              auto& value = item.second;\n              result.push_back(\n                  {item.first, BeachLineValue{static_cast<Edge*>(value.edge())}\n                                   .circle_event(value.circle_event())});\n            }\n            return result;\n          })\n      .def_property_readonly(\n          \"end_points\",\n          [](const Builder& self) {\n            auto queue = self.end_points_;\n            std::vector<\n                std::pair<Point, std::pair<BeachLineKey, BeachLineValue>>>\n                result;\n            while (!queue.empty()) {\n              const auto element = queue.top();\n              auto raw_value = element.second->second;\n              result.push_back(\n                  {element.first,\n                   {element.second->first,\n                    BeachLineValue(static_cast<Edge*>(raw_value.edge()))\n                        .circle_event(raw_value.circle_event())}});\n              queue.pop();\n            }\n            return result;\n          })\n      .def_property_readonly(\n          \"site_event_index\",\n          [](const Builder& self) {\n            return self.site_event_index_ ==\n                           std::numeric_limits<std::size_t>::max()\n                       ? self.site_events_.size()\n                       : self.site_event_index_;\n          })\n      .def_readonly(\"index\", &Builder::index_)\n      .def_readonly(\"site_events\", &Builder::site_events_);\n\n  py::class_<Cell, std::unique_ptr<Cell, py::nodelete>>(m, CELL_NAME)\n      .def(py::init<std::size_t, SourceCategory>(), py::arg(\"source_index\"),\n           py::arg(\"source_category\"))\n      .def(\"__repr__\", to_repr<Cell>)\n      .def_property_readonly(\"contains_point\", &Cell::contains_point)\n      .def_property_readonly(\"contains_segment\", &Cell::contains_segment)\n      .def_property(\n          \"incident_edge\",\n          [](const Cell& self) { return self.incident_edge(); },\n          [](Cell& self, Edge* value) { self.incident_edge(value); })\n      .def_property_readonly(\"is_degenerate\", &Cell::is_degenerate)\n      .def_property_readonly(\"source_index\", &Cell::source_index)\n      .def_property_readonly(\"source_category\", &Cell::source_category);\n\n  py::class_<CircleEvent, std::unique_ptr<CircleEvent, py::nodelete>>(\n      m, CIRCLE_EVENT_NAME)\n      .def(py::init([](double center_x, double center_y, double lower_x,\n                       bool is_active) {\n             CircleEvent result{center_x, center_y, lower_x};\n             return (is_active ? result : result.deactivate());\n           }),\n           py::arg(\"center_x\"), py::arg(\"center_y\"), py::arg(\"lower_x\"),\n           py::arg(\"is_active\") = true)\n      .def(py::self == py::self)\n      .def(\n          \"__lt__\",\n          [](const CircleEvent& self, const CircleEvent& other) {\n            static const EventComparisonPredicate comparator;\n            return comparator(self, other);\n          },\n          py::is_operator())\n      .def(\n          \"__lt__\",\n          [](const CircleEvent& self, const SiteEvent& other) {\n            static const EventComparisonPredicate comparator;\n            return comparator(self, other);\n          },\n          py::is_operator())\n      .def(\"__repr__\", to_repr<CircleEvent>)\n      .def(\"deactivate\", &CircleEvent::deactivate)\n      .def(\"lies_outside_vertical_segment\",\n           [](const CircleEvent& self, const SiteEvent& site) {\n             static Predicates::circle_formation_predicate<SiteEvent,\n                                                           CircleEvent>\n                 predicate;\n             return predicate.lies_outside_vertical_segment(self, site);\n           })\n      .def_property_readonly(\"center_x\",\n                             [](const CircleEvent& self) { return self.x(); })\n      .def_property_readonly(\"center_y\",\n                             [](const CircleEvent& self) { return self.y(); })\n      .def_property_readonly(\"is_active\", &CircleEvent::is_active)\n      .def_property_readonly(\n          \"lower_x\", [](const CircleEvent& self) { return self.lower_x(); })\n      .def_property_readonly(\"lower_y\", &CircleEvent::lower_y)\n      .def_property_readonly(\"x\",\n                             [](const CircleEvent& self) { return self.x(); })\n      .def_property_readonly(\"y\",\n                             [](const CircleEvent& self) { return self.y(); });\n\n  py::class_<Diagram>(m, DIAGRAM_NAME)\n      .def(py::init([](const std::vector<Cell>& cells,\n                       const std::vector<Edge>& edges,\n                       const std::vector<Vertex>& vertices) {\n             auto result = std::make_unique<Diagram>();\n             result->cells_ = cells;\n             result->edges_ = edges;\n             result->vertices_ = vertices;\n             return result;\n           }),\n           py::arg(\"cells\") = std::vector<Cell>{},\n           py::arg(\"edges\") = std::vector<Edge>{},\n           py::arg(\"vertices\") = std::vector<Vertex>{})\n      .def(\"__repr__\", to_repr<Diagram>)\n      .def(\"clear\", &Diagram::clear)\n      .def(\n          \"construct\",\n          [](Diagram* self, const std::vector<Point>& points,\n             const std::vector<Segment>& segments) {\n            boost::polygon::construct_voronoi(points.begin(), points.end(),\n                                              segments.begin(), segments.end(),\n                                              self);\n          },\n          py::arg(\"points\"), py::arg(\"segments\"))\n      .def(\"is_linear_edge\", &Diagram::is_linear_edge<SiteEvent>,\n           py::arg(\"first_event\"), py::arg(\"second_event\"))\n      .def(\"is_primary_edge\", &Diagram::is_primary_edge<SiteEvent>,\n           py::arg(\"first_event\"), py::arg(\"second_event\"))\n      .def(\"remove_edge\", &Diagram::remove_edge, py::arg(\"edge\").none(false))\n      .def(\"_build\", &Diagram::_build)\n      .def(\n          \"_insert_new_edge\",\n          [](Diagram& self, const SiteEvent& first_event,\n             const SiteEvent& second_event) {\n            auto result = self._insert_new_edge(first_event, second_event);\n            return std::make_pair(static_cast<Edge*>(result.first),\n                                  static_cast<Edge*>(result.second));\n          },\n          py::arg(\"first_event\"), py::arg(\"second_event\"))\n      .def(\n          \"_insert_new_edge_from_intersection\",\n          [](Diagram& self, const SiteEvent& first_site_event,\n             const SiteEvent& second_site_event,\n             const CircleEvent& circle_event, Edge* first_bisector,\n             Edge* second_bisector) {\n            auto result = self._insert_new_edge(\n                first_site_event, second_site_event, circle_event,\n                first_bisector, second_bisector);\n            return std::make_pair(static_cast<Edge*>(result.first),\n                                  static_cast<Edge*>(result.second));\n          },\n          py::arg(\"first_site_event\"), py::arg(\"second_site_event\"),\n          py::arg(\"circle_event\"), py::arg(\"first_bisector\"),\n          py::arg(\"second_bisector\"))\n      .def(\"_process_single_site\", &Diagram::_process_single_site<coordinate_t>,\n           py::arg(\"site\"))\n      .def(\"_reserve\", &Diagram::_reserve, py::arg(\"sites_count\"))\n      .def_property_readonly(\"cells\", &Diagram::cells)\n      .def_property_readonly(\"edges\", &Diagram::edges)\n      .def_property_readonly(\"vertices\", &Diagram::vertices);\n\n  py::class_<Edge, std::unique_ptr<Edge, py::nodelete>>(m, EDGE_NAME)\n      .def(py::init(\n               [](Vertex* start, Cell* cell, bool is_linear, bool is_primary) {\n                 Edge result{is_linear, is_primary};\n                 result.vertex0(start);\n                 result.cell(cell);\n                 return result;\n               }),\n           py::arg(\"start\"), py::arg(\"cell\").none(false), py::arg(\"is_linear\"),\n           py::arg(\"is_primary\"))\n      .def(\"__repr__\", to_repr<Edge>)\n      .def_property_readonly(\"cell\",\n                             [](const Edge& self) { return self.cell(); })\n      .def_property_readonly(\"end\",\n                             [](const Edge& self) {\n                               return self.twin() == nullptr ? nullptr\n                                                             : self.vertex1();\n                             })\n      .def_property_readonly(\"is_curved\", &Edge::is_curved)\n      .def_property_readonly(\"is_finite\",\n                             [](const Edge& self) {\n                               return self.twin() == nullptr ? false\n                                                             : self.is_finite();\n                             })\n      .def_property_readonly(\n          \"is_infinite\",\n          [](const Edge& self) {\n            return self.twin() == nullptr ? true : self.is_infinite();\n          })\n      .def_property_readonly(\"is_linear\", &Edge::is_linear)\n      .def_property_readonly(\"is_primary\", &Edge::is_primary)\n      .def_property_readonly(\"is_secondary\", &Edge::is_secondary)\n      .def_property(\n          \"next\", [](const Edge& self) { return self.next(); },\n          [](Edge& self, Edge* value) { self.next(value); })\n      .def_property(\n          \"prev\", [](const Edge& self) { return self.prev(); },\n          [](Edge& self, Edge* value) { self.prev(value); })\n      .def_property_readonly(\"rot_next\",\n                             [](const Edge& self) {\n                               return self.prev() == nullptr ? nullptr\n                                                             : self.rot_next();\n                             })\n      .def_property_readonly(\"rot_prev\",\n                             [](const Edge& self) {\n                               return self.prev() == nullptr ? nullptr\n                                                             : self.rot_prev();\n                             })\n      .def_property_readonly(\"start\",\n                             [](const Edge& self) { return self.vertex0(); })\n      .def_property(\n          \"twin\", [](const Edge& self) { return self.twin(); },\n          [](Edge& self, Edge* value) { self.twin(value); });\n\n  py::class_<Point>(m, POINT_NAME)\n      .def(py::init<coordinate_t, coordinate_t>(), py::arg(\"x\"), py::arg(\"y\"))\n      .def(py::self == py::self)\n      .def(\n          \"__lt__\",\n          [](const Point& self, const Point& other) {\n            static const Predicates::point_comparison_predicate<Point>\n                comparator;\n            return comparator(self, other);\n          },\n          py::is_operator())\n      .def(\"__repr__\", to_repr<Point>)\n      .def_property_readonly(\"x\", [](const Point& self) { return self.x(); })\n      .def_property_readonly(\"y\", [](const Point& self) { return self.y(); });\n\n  py::class_<RobustFloat>(m, ROBUST_FLOAT_NAME)\n      .def(py::init<>())\n      .def(py::init<double>(), py::arg(\"value\"))\n      .def(py::init<double, double>(), py::arg(\"value\"),\n           py::arg(\"relative_error\"))\n      .def(-py::self)\n      .def(py::self + py::self)\n      .def(py::self - py::self)\n      .def(py::self * py::self)\n      .def(py::self / py::self)\n      .def(py::self += py::self)\n      .def(py::self -= py::self)\n      .def(py::self *= py::self)\n      .def(py::self /= py::self)\n      .def(\"__bool__\",\n           [](const RobustFloat& self) {\n             return !boost::polygon::detail::is_zero(self);\n           })\n      .def(\"__repr__\", to_repr<RobustFloat>)\n      .def(\"sqrt\", &RobustFloat::sqrt)\n      .def_property_readonly(\"value\", &RobustFloat::fpv)\n      .def_property_readonly(\"relative_error\", &RobustFloat::re);\n\n  py::class_<RobustDifference>(m, ROBUST_DIFFERENCE_NAME)\n      .def(py::init<>())\n      .def(py::init<RobustFloat, RobustFloat>(), py::arg(\"minuend\"),\n           py::arg(\"subtrahend\"))\n      .def(-py::self)\n      .def(py::self + RobustFloat())\n      .def(py::self - RobustFloat())\n      .def(py::self * RobustFloat())\n      .def(py::self / RobustFloat())\n      .def(py::self += RobustFloat())\n      .def(py::self -= RobustFloat())\n      .def(py::self *= RobustFloat())\n      .def(py::self /= RobustFloat())\n      .def(py::self + RobustDifference())\n      .def(py::self - RobustDifference())\n      .def(py::self * RobustDifference())\n      .def(py::self += RobustDifference())\n      .def(py::self -= RobustDifference())\n      .def(py::self *= RobustDifference())\n      .def(\"__repr__\", to_repr<RobustDifference>)\n      .def(\"evaluate\", &RobustDifference::dif)\n      .def_property_readonly(\"minuend\", &RobustDifference::pos)\n      .def_property_readonly(\"subtrahend\", &RobustDifference::neg);\n\n  py::class_<Segment>(m, SEGMENT_NAME)\n      .def(py::init<Point, Point>(), py::arg(\"start\"), py::arg(\"end\"))\n      .def(\"__repr__\", to_repr<Segment>)\n      .def(py::self == py::self)\n      .def_readonly(\"start\", &Segment::start)\n      .def_readonly(\"end\", &Segment::end);\n\n  py::class_<SiteEvent>(m, SITE_EVENT_NAME)\n      .def(py::init([](const Point& start, const Point& end,\n                       std::size_t sorted_index, std::size_t initial_index,\n                       bool is_inverse, SourceCategory source_category) {\n             return (is_inverse ? SiteEvent{end, start}.inverse()\n                                : SiteEvent{start, end})\n                 .sorted_index(sorted_index)\n                 .initial_index(initial_index)\n                 .source_category(source_category);\n           }),\n           py::arg(\"start\"), py::arg(\"end\"), py::arg(\"sorted_index\") = 0,\n           py::arg(\"initial_index\") = 0, py::arg(\"is_inverse\") = false,\n           py::arg(\"source_category\") =\n               SourceCategory::SOURCE_CATEGORY_SINGLE_POINT)\n      .def(py::self == py::self)\n      .def(\n          \"__lt__\",\n          [](const SiteEvent& self, const CircleEvent& other) {\n            static const EventComparisonPredicate comparator;\n            return comparator(self, other);\n          },\n          py::is_operator())\n      .def(\n          \"__lt__\",\n          [](const SiteEvent& self, const SiteEvent& other) {\n            static const EventComparisonPredicate comparator;\n            return comparator(self, other);\n          },\n          py::is_operator())\n      .def(\"__repr__\", to_repr<SiteEvent>)\n      .def_property_readonly(\n          \"comparison_point\",\n          [](const SiteEvent& self) {\n            static const Predicates::node_comparison_predicate<BeachLineKey>\n                comparator;\n            return comparator.get_comparison_point(self);\n          })\n      .def(\"inverse\", &SiteEvent::inverse)\n      .def_property_readonly(\n          \"end\", [](const SiteEvent& self) { return self.point1(); })\n      .def_property_readonly(\n          \"initial_index\",\n          [](const SiteEvent& self) { return self.initial_index(); })\n      .def_property_readonly(\"is_inverse\", &SiteEvent::is_inverse)\n      .def_property_readonly(\"is_point\", &SiteEvent::is_point)\n      .def_property_readonly(\"is_segment\", &SiteEvent::is_segment)\n      .def_property_readonly(\n          \"is_vertical\",\n          [](const SiteEvent& self) { return Predicates::is_vertical(self); })\n      .def_property_readonly(\n          \"sorted_index\",\n          [](const SiteEvent& self) { return self.sorted_index(); })\n      .def_property_readonly(\n          \"source_category\",\n          [](const SiteEvent& self) { return self.source_category(); })\n      .def_property_readonly(\n          \"start\", [](const SiteEvent& self) { return self.point0(); });\n\n  py::class_<Vertex, std::unique_ptr<Vertex, py::nodelete>>(m, VERTEX_NAME)\n      .def(py::init<double, double>(), py::arg(\"x\"), py::arg(\"y\"))\n      .def(\"__repr__\", to_repr<Vertex>)\n      .def(py::self == py::self)\n      .def_property(\n          \"incident_edge\",\n          [](const Vertex& self) { return self.incident_edge(); },\n          [](Vertex& self, Edge* value) { self.incident_edge(value); })\n      .def_property_readonly(\"is_degenerate\", &Vertex::is_degenerate)\n      .def_property_readonly(\"x\", &Vertex::x)\n      .def_property_readonly(\"y\", &Vertex::y);\n\n  m.def(\n      \"compare_floats\",\n      [](double left, double right, unsigned int max_ulps) {\n        static const UlpComparator comparator;\n        return comparator(left, right, max_ulps);\n      },\n      py::arg(\"left\"), py::arg(\"right\"), py::arg(\"max_ulps\"));\n\n  m.def(\n      \"compute_circle_event\",\n      [](CircleEvent& circle_event, const SiteEvent& first_site,\n         const SiteEvent& second_site, const SiteEvent& third_site) {\n        static Predicates::circle_formation_predicate<SiteEvent, CircleEvent>\n            predicate;\n        return predicate(first_site, second_site, third_site, circle_event);\n      },\n      py::arg(\"circle_event\"), py::arg(\"first_site\"), py::arg(\"second_site\"),\n      py::arg(\"third_site\"));\n\n  m.def(\n      \"compute_point_point_point_circle_event\",\n      [](CircleEvent& circle_event, const SiteEvent& first_site,\n         const SiteEvent& second_site, const SiteEvent& third_site) {\n        static Predicates::lazy_circle_formation_functor<SiteEvent, CircleEvent>\n            functor;\n        functor.ppp(first_site, second_site, third_site, circle_event);\n      },\n      py::arg(\"circle_event\"), py::arg(\"first_site\"), py::arg(\"second_site\"),\n      py::arg(\"third_site\"));\n\n  m.def(\n      \"compute_point_point_segment_circle_event\",\n      [](CircleEvent& circle_event, const SiteEvent& first_site,\n         const SiteEvent& second_site, const SiteEvent& third_site,\n         int segment_index) {\n        static Predicates::lazy_circle_formation_functor<SiteEvent, CircleEvent>\n            functor;\n        functor.pps(first_site, second_site, third_site, segment_index,\n                    circle_event);\n      },\n      py::arg(\"circle_event\"), py::arg(\"first_site\"), py::arg(\"second_site\"),\n      py::arg(\"third_site\"), py::arg(\"segment_index\"));\n\n  m.def(\n      \"compute_point_segment_segment_circle_event\",\n      [](CircleEvent& circle_event, const SiteEvent& first_site,\n         const SiteEvent& second_site, const SiteEvent& third_site,\n         int point_index) {\n        static Predicates::lazy_circle_formation_functor<SiteEvent, CircleEvent>\n            functor;\n        functor.pss(first_site, second_site, third_site, point_index,\n                    circle_event);\n      },\n      py::arg(\"circle_event\"), py::arg(\"first_site\"), py::arg(\"second_site\"),\n      py::arg(\"third_site\"), py::arg(\"point_index\"));\n\n  m.def(\n      \"compute_segment_segment_segment_circle_event\",\n      [](CircleEvent& circle_event, const SiteEvent& first_site,\n         const SiteEvent& second_site, const SiteEvent& third_site) {\n        static Predicates::lazy_circle_formation_functor<SiteEvent, CircleEvent>\n            functor;\n        functor.sss(first_site, second_site, third_site, circle_event);\n      },\n      py::arg(\"circle_event\"), py::arg(\"first_site\"), py::arg(\"second_site\"),\n      py::arg(\"third_site\"));\n\n  m.def(\n      \"distance_to_point_arc\",\n      [](const SiteEvent& site, const Point& point) {\n        static const Predicates::distance_predicate<SiteEvent> comparator;\n        return comparator.find_distance_to_point_arc(site, point);\n      },\n      py::arg(\"site\"), py::arg(\"point\"));\n\n  m.def(\n      \"distance_to_segment_arc\",\n      [](const SiteEvent& site, const Point& point) {\n        static const Predicates::distance_predicate<SiteEvent> comparator;\n        return comparator.find_distance_to_segment_arc(site, point);\n      },\n      py::arg(\"site\"), py::arg(\"point\"));\n\n  m.def(\n      \"horizontal_goes_through_right_arc_first\",\n      [](const SiteEvent& left_site, const SiteEvent& right_site,\n         const Point& point) {\n        static const Predicates::distance_predicate<SiteEvent> comparator;\n        return comparator(left_site, right_site, point);\n      },\n      py::arg(\"left_site\"), py::arg(\"right_site\"), py::arg(\"point\"));\n\n  m.def(\n      \"point_point_horizontal_goes_through_right_arc_first\",\n      [](const SiteEvent& left_site, const SiteEvent& right_site,\n         const Point& point) {\n        static const Predicates::distance_predicate<SiteEvent> comparator;\n        return comparator.pp(left_site, right_site, point);\n      },\n      py::arg(\"left_site\"), py::arg(\"right_site\"), py::arg(\"point\"));\n\n  m.def(\n      \"point_point_point_circle_exists\",\n      [](const SiteEvent& first_site, const SiteEvent& second_site,\n         const SiteEvent& third_site) {\n        static const Predicates::circle_existence_predicate<SiteEvent>\n            predicate;\n        return predicate.ppp(first_site, second_site, third_site);\n      },\n      py::arg(\"first_site\"), py::arg(\"second_site\"), py::arg(\"third_site\"));\n\n  m.def(\n      \"point_point_segment_circle_exists\",\n      [](const SiteEvent& first_site, const SiteEvent& second_site,\n         const SiteEvent& third_site, int segment_index) {\n        static const Predicates::circle_existence_predicate<SiteEvent>\n            predicate;\n        return predicate.pps(first_site, second_site, third_site,\n                             segment_index);\n      },\n      py::arg(\"first_site\"), py::arg(\"second_site\"), py::arg(\"third_site\"),\n      py::arg(\"segment_index\"));\n\n  m.def(\n      \"point_segment_horizontal_goes_through_right_arc_first\",\n      [](const SiteEvent& left_site, const SiteEvent& right_site,\n         const Point& point, bool reverse_order) {\n        static const Predicates::distance_predicate<SiteEvent> comparator;\n        return comparator.ps(left_site, right_site, point, reverse_order);\n      },\n      py::arg(\"left_site\"), py::arg(\"right_site\"), py::arg(\"point\"),\n      py::arg(\"reverse_order\"));\n\n  m.def(\n      \"point_segment_segment_circle_exists\",\n      [](const SiteEvent& first_site, const SiteEvent& second_site,\n         const SiteEvent& third_site, int point_index) {\n        static const Predicates::circle_existence_predicate<SiteEvent>\n            predicate;\n        return predicate.pss(first_site, second_site, third_site, point_index);\n      },\n      py::arg(\"first_site\"), py::arg(\"second_site\"), py::arg(\"third_site\"),\n      py::arg(\"point_index\"));\n\n  m.def(\n      \"recompute_point_point_point_circle_event\",\n      [](CircleEvent& circle_event, const SiteEvent& first_site,\n         const SiteEvent& second_site, const SiteEvent& third_site,\n         bool recompute_center_x, bool recompute_center_y,\n         bool recompute_lower_x) {\n        static Predicates::mp_circle_formation_functor<SiteEvent, CircleEvent>\n            functor;\n        functor.ppp(first_site, second_site, third_site, circle_event,\n                    recompute_center_x, recompute_center_y, recompute_lower_x);\n      },\n      py::arg(\"circle_event\"), py::arg(\"first_site\"), py::arg(\"second_site\"),\n      py::arg(\"third_site\"), py::arg(\"recompute_center_x\") = true,\n      py::arg(\"recompute_center_y\") = true,\n      py::arg(\"recompute_lower_x\") = true);\n\n  m.def(\n      \"recompute_point_point_segment_circle_event\",\n      [](CircleEvent& circle_event, const SiteEvent& first_site,\n         const SiteEvent& second_site, const SiteEvent& third_site,\n         int segment_index, bool recompute_center_x, bool recompute_center_y,\n         bool recompute_lower_x) {\n        static Predicates::mp_circle_formation_functor<SiteEvent, CircleEvent>\n            functor;\n        functor.pps(first_site, second_site, third_site, segment_index,\n                    circle_event, recompute_center_x, recompute_center_y,\n                    recompute_lower_x);\n      },\n      py::arg(\"circle_event\"), py::arg(\"first_site\"), py::arg(\"second_site\"),\n      py::arg(\"third_site\"), py::arg(\"segment_index\"),\n      py::arg(\"recompute_center_x\") = true,\n      py::arg(\"recompute_center_y\") = true,\n      py::arg(\"recompute_lower_x\") = true);\n\n  m.def(\n      \"recompute_point_segment_segment_circle_event\",\n      [](CircleEvent& circle_event, const SiteEvent& first_site,\n         const SiteEvent& second_site, const SiteEvent& third_site,\n         int point_index, bool recompute_center_x, bool recompute_center_y,\n         bool recompute_lower_x) {\n        static Predicates::mp_circle_formation_functor<SiteEvent, CircleEvent>\n            functor;\n        functor.pss(first_site, second_site, third_site, point_index,\n                    circle_event, recompute_center_x, recompute_center_y,\n                    recompute_lower_x);\n      },\n      py::arg(\"circle_event\"), py::arg(\"first_site\"), py::arg(\"second_site\"),\n      py::arg(\"third_site\"), py::arg(\"point_index\"),\n      py::arg(\"recompute_center_x\") = true,\n      py::arg(\"recompute_center_y\") = true,\n      py::arg(\"recompute_lower_x\") = true);\n\n  m.def(\n      \"recompute_segment_segment_segment_circle_event\",\n      [](CircleEvent& circle_event, const SiteEvent& first_site,\n         const SiteEvent& second_site, const SiteEvent& third_site,\n         bool recompute_center_x, bool recompute_center_y,\n         bool recompute_lower_x) {\n        static Predicates::mp_circle_formation_functor<SiteEvent, CircleEvent>\n            functor;\n        functor.sss(first_site, second_site, third_site, circle_event,\n                    recompute_center_x, recompute_center_y, recompute_lower_x);\n      },\n      py::arg(\"circle_event\"), py::arg(\"first_site\"), py::arg(\"second_site\"),\n      py::arg(\"third_site\"), py::arg(\"recompute_center_x\") = true,\n      py::arg(\"recompute_center_y\") = true,\n      py::arg(\"recompute_lower_x\") = true);\n\n  m.def(\"robust_cross_product\", &Predicates::robust_cross_product,\n        py::arg(\"first_dx\"), py::arg(\"first_dy\"), py::arg(\"second_dx\"),\n        py::arg(\"second_dy\"));\n\n  m.def(\n      \"robust_product_with_sqrt\",\n      [](BigInt& left, BigInt& right) {\n        RobustSumExpression expression;\n        return expression.eval1(&left, &right);\n      },\n      py::arg(\"left\"), py::arg(\"right\"));\n\n  m.def(\n      \"robust_sum_of_products_with_sqrt_pairs\",\n      [](std::array<BigInt, 2>& left, std::array<BigInt, 2>& right) {\n        RobustSumExpression expression;\n        return expression.eval2(left.data(), right.data());\n      },\n      py::arg(\"left\"), py::arg(\"right\"));\n\n  m.def(\n      \"robust_sum_of_products_with_sqrt_triplets\",\n      [](std::array<BigInt, 3>& left, std::array<BigInt, 3>& right) {\n        RobustSumExpression expression;\n        return expression.eval3(left.data(), right.data());\n      },\n      py::arg(\"left\"), py::arg(\"right\"));\n\n  m.def(\n      \"robust_sum_of_products_with_sqrt_quadruplets\",\n      [](std::array<BigInt, 4>& left, std::array<BigInt, 4>& right) {\n        RobustSumExpression expression;\n        return expression.eval4(left.data(), right.data());\n      },\n      py::arg(\"left\"), py::arg(\"right\"));\n\n  m.def(\n      \"segment_segment_horizontal_goes_through_right_arc_first\",\n      [](const SiteEvent& left_site, const SiteEvent& right_site,\n         const Point& point) {\n        static const Predicates::distance_predicate<SiteEvent> comparator;\n        return comparator.ss(left_site, right_site, point);\n      },\n      py::arg(\"left_site\"), py::arg(\"right_site\"), py::arg(\"point\"));\n\n  m.def(\n      \"segment_segment_segment_circle_exists\",\n      [](const SiteEvent& first_site, const SiteEvent& second_site,\n         const SiteEvent& third_site) {\n        static const Predicates::circle_existence_predicate<SiteEvent>\n            predicate;\n        return predicate.sss(first_site, second_site, third_site);\n      },\n      py::arg(\"first_site\"), py::arg(\"second_site\"), py::arg(\"third_site\"));\n\n  m.def(\"to_first_point_segment_segment_quadruplets_expression\",\n        [](std::array<BigInt, 4> left, std::array<BigInt, 4> right) {\n          static Predicates::mp_circle_formation_functor<SiteEvent, CircleEvent>\n              functor;\n          return functor.sqrt_expr_evaluator_pss3<BigInt, BigFloat>(\n              left.data(), right.data());\n        });\n\n  m.def(\n      \"to_orientation\",\n      [](const Point& vertex, const Point& first_ray_point,\n         const Point& second_ray_point) {\n        return Predicates::ot::eval(vertex, first_ray_point, second_ray_point);\n      },\n      py::arg(\"vertex\"), py::arg(\"first_ray_point\"),\n      py::arg(\"second_ray_point\"));\n\n  m.def(\"to_second_point_segment_segment_quadruplets_expression\",\n        [](std::array<BigInt, 4> left, std::array<BigInt, 4> right) {\n          static Predicates::mp_circle_formation_functor<SiteEvent, CircleEvent>\n              functor;\n          return functor.sqrt_expr_evaluator_pss4<BigInt, BigFloat>(\n              left.data(), right.data());\n        });\n}\n", "meta": {"hexsha": "d092a190ea6fe5c70f333e1ae82ece609d577918", "size": 46081, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "lycantropos/voronoi", "max_stars_repo_head_hexsha": "977e0b3e5eff2dd294e2e6ce1a8030c763e86233", "max_stars_repo_licenses": ["MIT"], "max_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": "lycantropos/voronoi", "max_issues_repo_head_hexsha": "977e0b3e5eff2dd294e2e6ce1a8030c763e86233", "max_issues_repo_licenses": ["MIT"], "max_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": "lycantropos/voronoi", "max_forks_repo_head_hexsha": "977e0b3e5eff2dd294e2e6ce1a8030c763e86233", "max_forks_repo_licenses": ["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.9245115453, "max_line_length": 80, "alphanum_fraction": 0.6060198346, "num_tokens": 10740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.26242635593599284}}
{"text": "/**\n * @file   DL_MPL.cpp\n * @author Wei Li \n * @date   Oct 2019\n */\n#include <algorithm>\n#include <vector>\n#include <boost/timer/timer.hpp>\n#include\"DL_MPL.h\"\n\nSIMPLEMPL_BEGIN_NAMESPACE\n\nstd::vector<std::list<Edge_Simple> >  Read_Graph_File(std::string filename, int & vertex_numbers, int & edge_numbers)\n{\n\tstd::ifstream filein(filename.c_str());\n\t// std::cout << \"filename : \" << filename << std::endl;\n\tfilein >> vertex_numbers >> edge_numbers; // >> mask_numbers;\n\t/*\n\tstd::cout << \"vertex_numbers : \" << vertex_numbers << std::endl;\n\tstd::cout << \"edge_numbers : \" << edge_numbers << std::endl;\n\tstd::cout << \"mask_numbers : \" << mask_numbers << std::endl;\n\t*/\n\n\tint source, target;\n\tstd::vector<std::list<Edge_Simple> > edge_list;\n\tedge_list.resize(vertex_numbers + 1);\n\tfor (int i = 1; i <= edge_numbers; i++)\n\t{\n\t\tfilein >> source >> target;\n\t\tedge_list[source].push_back(Edge_Simple{ target, i });\n\t\tedge_list[target].push_back(Edge_Simple{ source, i });\n\t}\n\tfilein.close();\n\treturn edge_list;\n}\n\nstd::vector<std::list<Edge_Simple> >  Read_Stitch_Graph_File(std::string filename, int & vertex_numbers, int & edge_numbers)\n{\n\tstd::ifstream filein(filename.c_str());\n\tint total_vertex_numbers;\n\t// std::cout << \"filename : \" << filename << std::endl;\n\tfilein >> total_vertex_numbers; // >> mask_numbers;\n\t/*\n\tstd::cout << \"vertex_numbers : \" << vertex_numbers << std::endl;\n\tstd::cout << \"edge_numbers : \" << edge_numbers << std::endl;\n\tstd::cout << \"mask_numbers : \" << mask_numbers << std::endl;\n\t*/\n\n\n\tint source, target;\n\tdouble weight;\n\tstd::vector<Vertex*> node_list;\n\tnode_list.resize(total_vertex_numbers);\n\tvertex_numbers = 0;\n\tedge_numbers = 0;\n\twhile (filein >> source >> target >> weight){\n\t\t//if node source and node target is not created. New one/\n\t\tif(!node_list[source]){\n\t\t\tVertex* source_vertex = new Vertex;\n\t\t\tassert(source_vertex->Conflicts.empty());\n\t\t\tnode_list[source] = source_vertex;\n\t\t\tvertex_numbers ++;\n\t\t}\n\t\tif(!node_list[target]){\n\t\t\tVertex* target_vertex = new Vertex;\n\t\t\tnode_list[target] = target_vertex;\n\t\t\tvertex_numbers ++;\n\t\t}\n\n\t\t//if two nodes are stitch relationships and both of them are parent\n\t\tif(weight < 0){\n\t\t\tVertex* parent_vertex = new Vertex;\n\t\t\tassert(parent_vertex->Childs.empty());\n\t\t\tparent_vertex->parentOf(node_list[source]);\n\t\t\tparent_vertex->parentOf(node_list[target]);\n\t\t\tvertex_numbers -= 1;\n\t\t\tcontinue;\n\t\t}\n\t\tnode_list[source]->Conflicts.insert(node_list[target]);\n\t}\n\tfilein.close();\n\n\t//need to store node list, which does not contain child node\n\tstd::set<Vertex*> node_wo_stitch_list;\n\tint index = 1;\n\tfor(std::vector<Vertex*>::iterator it = node_list.begin(); it != node_list.end(); ++it) {\n\t\t//if the node in parent node, means it has no stitch relations\n\t\tif((*it)->Is_Parent){\n\t\t\tnode_wo_stitch_list.insert((*it));\n\t\t\t(*it)->updateConflicts();\n\t\t\t(*it)->No = index;\n\t\t\tindex ++;\n\t\t}\n\t\t//else, add its parent node if it has not been added into node_wo_stitch_list\n\t\telse{\n\t\t\tassert((*it)->parent->Is_Parent);\n\t\t\tif(node_wo_stitch_list.find((*it)->parent) == node_wo_stitch_list.end()){\n\t\t\t\tnode_wo_stitch_list.insert((*it)->parent);\n\t\t\t\t(*it)->parent->updateConflicts();\n\t\t\t\t(*it)->parent->No = index;\n\t\t\t\tindex ++;\n\t\t\t}\n\n\t\t}\n\t}\n    mplAssert(node_wo_stitch_list.size() == (unsigned int)vertex_numbers);\n\n\tstd::vector<std::list<Edge_Simple> >  edge_list;\n\tedge_list.resize(vertex_numbers + 1);\n\tfor(std::set<Vertex*>::iterator it = node_wo_stitch_list.begin(); it != node_wo_stitch_list.end(); ++it) {\n\t\tassert((*it)->No != 0);\n\t\tfor(std::set<Vertex*>::iterator itconflict = (*it)->Conflicts_in_LG.begin(); itconflict != (*it)->Conflicts_in_LG.end(); ++itconflict) {\n\t\t\tif((*itconflict)->Is_Parent){\n\t\t\t\tassert((*itconflict)->No != 0);\n\t\t\t\tedge_numbers++;\n\t\t\t\tedge_list[(*it)->No].push_back(Edge_Simple{ (*itconflict)->No, edge_numbers });\n\t\t\t\tedge_list[(*itconflict)->No].push_back(Edge_Simple{ (*it)->No, edge_numbers });\t\n\t\t\t}\n\t\t\telse{\n\t\t\t\tassert((*itconflict)->parent->Is_Parent);\n\t\t\t\t//avoid repeat (conflicts of stitch realation nodes may represent same conflict)\n\t\t\t\tedge_numbers++;\t\n\t\t\t\tedge_list[(*it)->No].push_back(Edge_Simple{ (*itconflict)->parent->No, edge_numbers });\n\t\t\t\tedge_list[(*itconflict)->parent->No].push_back(Edge_Simple{ (*it)->No, edge_numbers });\n\t\t\t}\n\t\t}\n\t\t}\n\tstd::cout<<\"EDGE list generated with size: \"<<edge_numbers<<std::endl;\n\treturn edge_list;\n}\n\nstd::vector<int> BFS_Order_no_stitch_first(std::vector<std::list<Edge_Simple> >  & edge_list,DancingLink & dl ){\n\tstd::vector<int> result_vector;\n\tstd::queue<int> intermediate_queue;\n\tstd::set<int> nonexistent;\n\tstd::vector<int> node_degree;\n\tnode_degree.assign(edge_list.size(),0); //edge_list.size() == vertex_number + 1\n\t//int first_vertex = find_max_degree_node(edge_list);\n\tcalcualte_degree_of_each_node(edge_list,node_degree);\n\tint max_degree = find_max_degree(edge_list);\n\tstd::vector<int> rows_num;\n\trows_num.assign(edge_list.size(),0); \n\tint max_rows = 0;\n\tint min_rows = INT_MAX;\n\tfor(auto i = 1; i<(int)edge_list.size();i++){\n\t\trows_num[i] = dl.Col_Header_Table[i].Children_Number;\n\t\tif(max_rows < dl.Col_Header_Table[i].Children_Number){max_rows = dl.Col_Header_Table[i].Children_Number;}\n\t\tif(min_rows > dl.Col_Header_Table[i].Children_Number){min_rows = dl.Col_Header_Table[i].Children_Number;}\n\t}\n\t// std::cout<<\"rows_num \";\n\t// for (auto i = rows_num.begin(); i != rows_num.end(); ++i)\n\t// \tstd::cout << *i << ' ';\n\t// std::cout<<std::endl;\n\t//we calculate the case of each node as the root and return the smallest calculation costs\n\tint smallest_cost = INT_MAX;\n\tint smallest_cost_node = -1;\n\tstd::vector<int> tmp_result_vector;\n\tfor(auto root_node = 1; root_node < (int)edge_list.size(); root_node++){\n\t\ttmp_result_vector.clear();\n\t\tnonexistent.clear();\n\t\tintermediate_queue.push(root_node);\n\t\ttmp_result_vector.push_back(root_node);\n\t\twhile (!intermediate_queue.empty())\n\t\t{\n\t\t\tint next = intermediate_queue.front();\n\t\t\tintermediate_queue.pop();\n\t\t\tif (nonexistent.find(next) == nonexistent.end())\n\t\t\t{\n\t\t\t\tnonexistent.insert(next);\n\t\t\t\ttmp_result_vector.push_back(next);\n\t\t\t\t// for (auto i = edge_list[next].begin(); i != edge_list[next].end(); i++)\n\t\t\t\t// \tintermediate_queue.push(i->target);\n\t\t\t\t//push the nodes to the queue by small-degree firstly order\n\t\t\t\tfor(int row_num = min_rows; row_num <= max_rows; row_num++){\n\t\t\t\t\tfor(int d = 1; d<= max_degree;d++){\n\t\t\t\t\t\tfor (auto i = edge_list[next].begin(); i != edge_list[next].end(); i++){\n\t\t\t\t\t\t\tif(node_degree[i->target] == d && rows_num[i->target] == row_num){\n\t\t\t\t\t\t\t\tintermediate_queue.push(i->target);\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}\n\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse\n\t\t\t\tcontinue;\n\t\t}\n\t\t//calculate the cost of each node : calculation function is \\sum rows_num[node] * (node_num - index) (largest rows_num, we want to put it into the final location)\n\t\tint total_cost = 0;\n\t\tfor(auto index = 1; index <edge_list.size();index++){\n\t\t\ttotal_cost += rows_num[tmp_result_vector[index]] * (edge_list.size() - index);\n\t\t}\n\t\tif(total_cost < smallest_cost){\n\t\t\tresult_vector= tmp_result_vector;\n\t\t\tsmallest_cost = total_cost;\n\t\t\tsmallest_cost_node = root_node;\n\t\t}\n\t\t// std::cout<<\"total_cost \" <<total_cost<<std::endl;\n\t\t// std::cout<<\"TMP RESULT IS\"<<std::endl;\n\t\t// for (auto i = tmp_result_vector.begin(); i != tmp_result_vector.end(); ++i)\n    \t// \tstd::cout << *i << ' ';\n\t\t// std::cout<<std::endl;\n\t}\n\treturn result_vector;\n}\nstd::vector<int> BFS_Order(std::vector<std::list<Edge_Simple> >  & edge_list)\n{\n\tstd::vector<int> result_vector;\n\tstd::queue<int> intermediate_queue;\n\tstd::set<int> nonexistent;\n\tstd::vector<int> node_degree;\n\tnode_degree.assign(edge_list.size(),0); //edge_list.size() == vertex_number + 1\n\t//int first_vertex = find_max_degree_node(edge_list);\n\tint first_vertex = calcualte_degree_of_each_node(edge_list,node_degree);\n\tintermediate_queue.push(first_vertex);\n\tresult_vector.push_back(first_vertex);\n\n\tint max_degree = find_max_degree(edge_list);\n\twhile (!intermediate_queue.empty())\n\t{\n\t\tint next = intermediate_queue.front();\n\t\tintermediate_queue.pop();\n\t\tif (nonexistent.find(next) == nonexistent.end())\n\t\t{\n\t\t\tnonexistent.insert(next);\n\t\t\tresult_vector.push_back(next);\n\t\t\t// for (auto i = edge_list[next].begin(); i != edge_list[next].end(); i++)\n\t\t\t// \tintermediate_queue.push(i->target);\n\t\t\t//push the nodes to the queue by small-degree firstly order\n\t\t\tfor(int d = 1; d<= max_degree;d++){\n\t\t\t\tfor (auto i = edge_list[next].begin(); i != edge_list[next].end(); i++){\n\t\t\t\t\tif(node_degree[i->target] == d){\n\t\t\t\t\t\tintermediate_queue.push(i->target);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcontinue;\n\t\t}\n\t\telse\n\t\t\tcontinue;\n\t}\n\treturn result_vector;\n}\n\nstd::vector<int> BFS_Order_max_first(std::vector<std::list<Edge_Simple> >  & edge_list)\n{\n\tstd::vector<int> result_vector;\n\tstd::queue<int> intermediate_queue;\n\tstd::set<int> nonexistent;\n\tstd::vector<int> node_degree;\n\tnode_degree.assign(edge_list.size(),0); //edge_list.size() == vertex_number + 1\n\tint first_vertex = find_max_degree_node(edge_list);\n\t//int first_vertex = calcualte_degree_of_each_node(edge_list,node_degree);\n\tintermediate_queue.push(first_vertex);\n\tresult_vector.push_back(first_vertex);\n\t//int first_vertex = find_max_degree_node(edge_list);\n\tcalcualte_degree_of_each_node(edge_list,node_degree);\n\tint max_degree = find_max_degree(edge_list);\n\twhile (!intermediate_queue.empty())\n\t{\n\t\tint next = intermediate_queue.front();\n\t\tintermediate_queue.pop();\n\t\tif (nonexistent.find(next) == nonexistent.end())\n\t\t{\n\t\t\tnonexistent.insert(next);\n\t\t\tresult_vector.push_back(next);\n\t\t\tfor (auto i = edge_list[next].begin(); i != edge_list[next].end(); i++)\n\t\t\t\tintermediate_queue.push(i->target);\n\t\t\t//push the nodes to the queue by max-degree firstly order\n\n\n\t\t\t// for(int d = max_degree; d>= 1;d--){\n\t\t\t// \tfor (auto i = edge_list[next].begin(); i != edge_list[next].end(); i++){\n\t\t\t// \t\tif(node_degree[i->target] == d){\n\t\t\t// \t\t\tintermediate_queue.push(i->target);\n\t\t\t// \t\t}\n\t\t\t// \t}\n\t\t\t// }\n\n\t\t\t// for(int d = 1; d<= max_degree;d++){\n\t\t\t// \tfor (auto i = edge_list[next].begin(); i != edge_list[next].end(); i++){\n\t\t\t// \t\tif(node_degree[i->target] == d){\n\t\t\t// \t\t\tintermediate_queue.push(i->target);\n\t\t\t// \t\t}\n\t\t\t// \t}\n\t\t\t// }\n\t\t\tcontinue;\n\t\t}\n\t\telse\n\t\t\tcontinue;\n\t}\n\treturn result_vector;\n}\nint  find_max_degree_node(std::vector<std::list<Edge_Simple> >  & edge_list){\n\tint max_degree = 0;\n\tint vertex_node = 1;\n\tfor ( int it = 1; it < edge_list.size(); ++it){\n\t\tif(edge_list[it].size()> max_degree){\n\t\t\tmax_degree = edge_list[it].size();\n\t\t\tvertex_node = it;\n\t\t}\n\t}\n\treturn vertex_node;\n}\n\nint  find_max_degree(std::vector<std::list<Edge_Simple> >  & edge_list){\n\tint max_degree = 0;\n\tint vertex_node = 1;\n\tfor ( int it = 1; it < edge_list.size(); ++it){\n\t\tif(edge_list[it].size()> max_degree){\n\t\t\tmax_degree = edge_list[it].size();\n\t\t\tvertex_node = it;\n\t\t}\n\t}\n\treturn max_degree;\n}\n\nint calcualte_degree_of_each_node(std::vector<std::list<Edge_Simple> >  & edge_list, std::vector<int> & node_degree){\n\tint min_degree = std::numeric_limits<int>::max();\n\tint vertex_node = 1;\n\tfor ( int it = 1; it < edge_list.size(); ++it){\n\t\tif(edge_list[it].size()< min_degree){\n\t\t\tmin_degree = edge_list[it].size();\n\t\t\tvertex_node = it;\n\t\t}\n\t\tnode_degree[it] = edge_list[it].size();\n\t}\n\treturn vertex_node;\n}\nstd::vector<int> Simple_Order(int size)\n{\n\tstd::vector<int> result_vector;\n\tresult_vector.reserve(size);\n\tresult_vector.push_back(1);\n\tfor (int i = 1; i < size; i++)\n\t{\n\t\tresult_vector.push_back(i);\n\t}\n\treturn result_vector;\n}\n\nint Sorting_Queue(DancingLink & dl)\n{\n\tint col_no = std::numeric_limits<int>::max();\n\tint max = std::numeric_limits<int>::max();\n\tfor (auto c = dl.DL_Header.Right; c != &dl.DL_Header; c = c->Right)\n\t{\n\t\tif (c->Children_Number < max)\n\t\t{\n\t\t\tmax = c->Children_Number;\n\t\t\tcol_no = c->Col;\n\t\t}\n\t}\n\treturn col_no;\n}\n\nvoid Convert_to_Exat_Cover(int & row_numbers, int & col_numbers, std::string infilename, std::string Exact_Cover_Filename, bool whether_BFS,\n\tint & vertex_numbers, int & edge_numbers, int & mask_numbers, std::vector<int> & MPLD_search_vector)\n{\n\tstd::ofstream fileout(Exact_Cover_Filename);\n\n\tstd::vector<std::list<Edge_Simple> >  edge_list = Read_Stitch_Graph_File(infilename, vertex_numbers, edge_numbers); //, mask_numbers);\n\n\tif (whether_BFS)\n\t\tMPLD_search_vector = BFS_Order(edge_list);\n\telse\n\t\tMPLD_search_vector = Simple_Order(edge_list.size());\n\trow_numbers = vertex_numbers * mask_numbers + 1;\n\tcol_numbers = edge_numbers * mask_numbers + vertex_numbers;\n\tfileout << row_numbers << std::endl;\n\tfileout << col_numbers << std::endl;\n\tint count = 0;\n\tint total_edge = 0;\n\tfor (auto it = edge_list.begin(); it != edge_list.end(); it++)\n\t{\n\t\tif(it == edge_list.begin()){continue;}\n\t\tstd::cout<<it->size()<<std::endl;\n\t\ttotal_edge += it->size();\n \t\tint temp = (it->size() + 1) * mask_numbers;\n\t\tcount += temp;\n\t}\n\tstd::cout<<total_edge<<std::endl;\n\tassert(total_edge == 2 * edge_numbers );\n\tcount += edge_numbers*mask_numbers;\n\n\tfileout << count << std::endl;\n\tfor (unsigned int it = 1; it < edge_list.size(); ++it)\n\t{\n\t\tfor (int i = 1; i <= mask_numbers; ++i)\n\t\t{\n\t\t\tfileout << (it - 1)*mask_numbers + i << \" \" << it << std::endl;\n\t\t\tfor (auto j = edge_list[it].begin(); j != edge_list[it].end(); ++j)\n\t\t\t{\n\t\t\t\tfileout << (it - 1)*mask_numbers + i << \" \" << vertex_numbers + (j->No - 1)*mask_numbers + i << std::endl;\n\t\t\t}\n\t\t}\n\t}\n\tfor (int i = 0; i < edge_numbers; ++i)\n\t{\n\t\tfor (int j = 1; j <= mask_numbers; ++j)\n\t\t\tfileout << vertex_numbers * mask_numbers + 1 << \" \" << vertex_numbers + i * mask_numbers + j << std::endl;\n\t}\n\tfileout.close();\n\treturn;\n}\n\nint Next_Column(std::vector<int> & MPLD_search_vector, int depth)\n{\n\treturn MPLD_search_vector[depth];\n}\n\nint Next_Column_stitch(DancingLink & dl,std::vector<int> & MPLD_search_vector)\n{\n\tbool not_find_last_uncovered_col = true;\n\tint last_col = 0;\n\tfor(unsigned int i = 0; i< MPLD_search_vector.size(); i++){\n\t\tCell *col = &dl.Col_Header_Table[MPLD_search_vector[i]];\n\t\t//if the column(vertex) has been removed(selected)\n\t\t//if(col_cover_vector[MPLD_search_vector[i]])\tcontinue;\n\t\tif(col->Left->Right != col) continue;\n\t\telse{\n\t\t\tmplAssert(col->InDLX);\n\t\t\tif(not_find_last_uncovered_col){\n\t\t\t\tlast_col = MPLD_search_vector[i];\n\t\t\t\tnot_find_last_uncovered_col = false;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(col-> Children_Number == 1){\n\t\t\treturn MPLD_search_vector[i];\n\t\t}\n\t}\n\tassert(not_find_last_uncovered_col == false);\n\treturn last_col;\n}\nbool Vertices_All_Covered(DancingLink & dl, int& vertex_numbers)\n{\n\tif (dl.DL_Header.Right->Col > vertex_numbers)\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\nvoid store_intermediate_process(DancingLink & dl, int this_col, std::set<int> & row_set,\n\t\t\t\t\t\t\t\tstd::vector<int> & Delete_the_Row_in_which_Col,\n\t\t\t\t\t\t\t\tstd::vector<std::list<int> >  & Order_of_Row_Deleted_in_Col,std::vector<int>  &  conflict_col_table,std::vector<int>  &last_rows)\n{\n\tfor (auto row_it = row_set.begin(); row_it != row_set.end(); ++row_it) {\n\t\tDelete_the_Row_in_which_Col[*row_it] = this_col;\n\t\tfor (auto row_ele = dl.Row_Header_Table[*row_it].Right; row_ele != &dl.Row_Header_Table[*row_it]; row_ele = row_ele->Right)\n\t\t\t{\t//std::cout<<\"row deleted is \"<<*row_it<<\"in column \"<<this_col<<std::endl;\n\t\t\t\t\t\t\tOrder_of_Row_Deleted_in_Col[row_ele->Col].push_back(*row_it);\n\t\t\tconflict_col_table[row_ele->Col] = this_col;\n\t\t\tlast_rows[row_ele->Col] = (*row_it);}\n\t}\n}\n\nvoid efficient_store_intermediate_process(DancingLink & dl, int this_col, std::set<int> & row_set,\n\t\t\t\t\t\t\t\tstd::vector<int> & Delete_the_Row_in_which_Col,\n\t\t\t\t\t\t\t\tstd::vector<std::list<int> >  & Order_of_Row_Deleted_in_Col)\n{\n\tfor (auto row_it = row_set.begin(); row_it != row_set.end(); ++row_it) {\n\t\tDelete_the_Row_in_which_Col[*row_it] = this_col;\n\t\tfor (auto row_ele = dl.Row_Header_Table[*row_it].Right; row_ele != &dl.Row_Header_Table[*row_it]; row_ele = row_ele->Right)\n\t\t\t{\t//std::cout<<\"row deleted is \"<<*row_it<<\"in column \"<<this_col<<std::endl;\n\t\t\t\t\t\t\tOrder_of_Row_Deleted_in_Col[row_ele->Col].push_back(*row_it);}\n\t}\n}\n\nvoid recover_intermediate_process(DancingLink & dl, int this_col, std::set<int>& row_set,\n\t\t\t\t\t\t\t\tstd::vector<int> & Delete_the_Row_in_which_Col,\n\t\t\t\t\t\t\t\tstd::vector<std::list<int> >  & Order_of_Row_Deleted_in_Col,std::vector<int>  &  conflict_col_table,std::vector<int>  &last_rows)\n{\n\t(void)this_col;\n\tfor (auto row_it = row_set.begin(); row_it != row_set.end(); ++row_it)\n\t{\n\t\t Delete_the_Row_in_which_Col[*row_it] = 0;\n\t\tfor (auto row_ele = dl.Row_Header_Table[*row_it].Right; row_ele != &dl.Row_Header_Table[*row_it]; row_ele = row_ele->Right)\n\t\t\t{Order_of_Row_Deleted_in_Col[row_ele->Col].pop_back();\n\t\t\tconflict_col_table[row_ele->Col] = Order_of_Row_Deleted_in_Col[row_ele->Col].back();\n\t\t\tlast_rows[row_ele->Col] =  0;}\n\t}\n}\n\nvoid efficient_recover_intermediate_process(DancingLink & dl, int this_col, std::set<int>& row_set,\n\t\t\t\t\t\t\t\tstd::vector<int> & Delete_the_Row_in_which_Col,\n\t\t\t\t\t\t\t\tstd::vector<std::list<int> >  & Order_of_Row_Deleted_in_Col)\n{\n\t(void)this_col;\n\tfor (auto row_it = row_set.begin(); row_it != row_set.end(); ++row_it)\n\t{\n\t\t Delete_the_Row_in_which_Col[*row_it] = 0;\n\t\tfor (auto row_ele = dl.Row_Header_Table[*row_it].Right; row_ele != &dl.Row_Header_Table[*row_it]; row_ele = row_ele->Right)\n\t\t\t{Order_of_Row_Deleted_in_Col[row_ele->Col].pop_back();}\n\t}\n}\n\nbool MPLD_X_Solver(DancingLink & dl, std::vector<int8_t>& color_vector,std::vector<int> & result_vec, std::pair<int, int>  & conflict_pair, \n\t\t\tint vertex_numbers, int mask_numbers,\n\t\t\tstd::vector<int> & Delete_the_Row_in_which_Col,\n\t\t\tstd::vector<std::list<int> >  & Order_of_Row_Deleted_in_Col, int depth, std::vector<int> & MPLD_search_vector, const char* result_file,\n\t\t\tstd::vector<bool>& col_cover_vector,std::vector<int>& row_select_vector,\n\t\t\tstd::vector<int> & partial_conflict_col_table,\n\t\t\tstd::vector<int>  &  conflict_col_table,std::vector<int>  &partial_last_rows,std::vector<int>  &last_rows)\n{\n\t// If there is no columns left or all the verteices are covered, then the algorithm terminates.\n\tif (dl.DL_Header.Right == &dl.DL_Header || Vertices_All_Covered(dl, vertex_numbers))\n\t{\n\t\t//Decode_OpenMPL(vertex_numbers, mask_numbers,color_vector,result_vec, conflict_pair, result_file);\n\t\treturn true;\n\t}\n\t/* \n\tif (dl.DL_Header.Right->Col > vertex_numbers )\n\t{\n\t\tthis_col = Sorting_Queue(dl);\n\t}\n\telse\n\t{\n\t*/\n\tCell *col;\n\t//TODO: this depth should be a bug cause sometimes it is not by order (need a bool vector to record the col cover information)\n\tint this_col = Next_Column_stitch(dl,MPLD_search_vector);\n\t\n\tcol = &dl.Col_Header_Table[this_col];\n\tLR_remove(*col);\n\tcol_cover_vector[this_col] = true;\n\tif (col->Children_Number == 0)\n\t{\n\t\t// int last_row = Order_of_Row_Deleted_in_Col[this_col].back();\n\t\t// int conflict_col = Delete_the_Row_in_which_Col[last_row];\n\t\t//std::cout<<\"last row is \"<<last_row<<std::endl;\n\t\t//mplAssert(conflict_col == conflict_col_table[this_col]);\n\t\tconflict_pair = std::make_pair(conflict_col_table[this_col], this_col);\n\t\t//Also,  record the partial results (rows) in the last detected conflict\n\t\trow_select_vector.assign(result_vec.begin(),result_vec.end());\n\t\trow_select_vector.push_back(last_rows[this_col]);\n\t\t//We should should push back the last row(coloring result of this conflict col)\n\t\tpartial_last_rows.assign(last_rows.begin(), last_rows.end());\n\t\tpartial_conflict_col_table.assign(conflict_col_table.begin(), conflict_col_table.end());\n\t\t// if (MPLD_X_Solver(dl, color_vector,result_vec, conflict_pair, vertex_numbers, mask_numbers, Delete_the_Row_in_which_Col, Order_of_Row_Deleted_in_Col, depth + 1, MPLD_search_vector, result_file))\n\t\t// \treturn true;\n\t}\n\tfor (Cell *j = col->Down; j != col; j = j->Down)\n\t{\n\t\tstd::set<int> row_set;\n\t\tstd::set<int> col_set;\n\t\tresult_vec.push_back(j->Row);\n\t\tSelect_All_Rows_Cols(dl, j->Row, row_set, col_set);\n\t\tstore_intermediate_process(dl, this_col, row_set, Delete_the_Row_in_which_Col, Order_of_Row_Deleted_in_Col,conflict_col_table,last_rows);\n\n\t\tRemove_Rows_Cols(dl, row_set, col_set);\n\t\tif (MPLD_X_Solver(dl, color_vector,result_vec, conflict_pair, vertex_numbers, mask_numbers, Delete_the_Row_in_which_Col, Order_of_Row_Deleted_in_Col, depth + 1, \n\t\tMPLD_search_vector, result_file,col_cover_vector,row_select_vector,partial_conflict_col_table,conflict_col_table,partial_last_rows,last_rows))\n\t\t\treturn true;\n\n\t\tresult_vec.pop_back();\n\t\trecover_intermediate_process(dl, this_col, row_set, Delete_the_Row_in_which_Col, Order_of_Row_Deleted_in_Col,conflict_col_table,last_rows);\n\t\tRecover_Rows_Cols(dl, row_set, col_set);\n\t}\n\tLR_recover(*col);\n\tcol_cover_vector[this_col] = false;\n\t\n\treturn false;\n}\n\nbool Efficient_MPLD_X_Solver(DancingLink & dl,std::vector<int8_t>& color_vector, std::vector<int> & result_vec, std::pair<int, int>  & conflict_pair, \n\t\t\tint vertex_numbers, int mask_numbers,\n\t\t\tstd::vector<int> & Delete_the_Row_in_which_Col,\n\t\t\tstd::vector<std::list<int> >  & Order_of_Row_Deleted_in_Col, int depth, std::vector<int> & MPLD_search_vector, const char* result_file,\n\t\t\tstd::vector<int> & partial_row_results, std::vector<int> & partial_col_results,std::vector<int> & col_results)\n{\n\tif (dl.DL_Header.Right == &dl.DL_Header || Vertices_All_Covered(dl, vertex_numbers))\n\t{\n\t\t//Decode_OpenMPL(vertex_numbers, mask_numbers,color_vector,result_vec, conflict_pair, result_file);\n\t\treturn true;\n\t}\n\n\tCell *col;\n\tint this_col = Next_Column_stitch(dl,MPLD_search_vector);\n#ifdef DEBUG_DANCINGLINKCOLORING\n    mplPrint(kDEBUG, \"BEGIN: this_col : %d depth : %d\\n\", this_col, depth);\n#endif\n\n\tcol = &dl.Col_Header_Table[this_col];\n\tLR_remove(*col);\n\tcol_results.push_back(this_col);\n\tif (col->Children_Number == 0)\n\t{\n\t\tint last_row = Order_of_Row_Deleted_in_Col[this_col].back();\n\t\tint conflict_col = Delete_the_Row_in_which_Col[last_row];\n\t\tconflict_pair = std::make_pair(conflict_col, this_col);\n\t\tpartial_row_results.assign(result_vec.begin(),result_vec.end());\n\t\tpartial_row_results.push_back(last_row);\n\t\tpartial_col_results.assign(col_results.begin(), col_results.end());\n\t}\n\t\n\tfor (Cell *j = col->Down; j != col; j = j->Down)\n\t{\n\t\tstd::set<int> row_set;\n\t\tstd::set<int> col_set;\n\t\tresult_vec.push_back(j->Row);\n\t\tSelect_All_Rows_Cols(dl, j->Row, row_set, col_set);\n\t\tefficient_store_intermediate_process(dl, this_col, row_set, Delete_the_Row_in_which_Col, Order_of_Row_Deleted_in_Col);\n\t\tRemove_Rows_Cols(dl, row_set, col_set);\n\t\tif (Efficient_MPLD_X_Solver(dl,color_vector, result_vec, conflict_pair, vertex_numbers, mask_numbers, Delete_the_Row_in_which_Col, Order_of_Row_Deleted_in_Col, depth + 1, \n\t\tMPLD_search_vector, result_file,partial_row_results,partial_col_results,col_results))\n\t\t\treturn true;\n\n\t\tresult_vec.pop_back();\n\t\tefficient_recover_intermediate_process(dl, this_col, row_set, Delete_the_Row_in_which_Col, Order_of_Row_Deleted_in_Col);\n\t\tRecover_Rows_Cols(dl, row_set, col_set);\n\t}\n\tLR_recover(*col);\n#ifdef DEBUG_DANCINGLINKCOLORING\n    mplPrint(kDEBUG, \"END: this_col : %d depth : %d\\n\", this_col, depth);\n#endif\n\tcol_results.pop_back();\n\treturn false;\n}\n\nbool Efficient_MPLD_X_Solver_v2(DancingLink & dl, std::vector<int> & result_vec, std::pair<int, int>  & conflict_pair, \n\t\t\tint vertex_numbers, std::vector<int> & Delete_the_Row_in_which_Col,\n\t\t\tstd::vector<std::list<int> >  & Order_of_Row_Deleted_in_Col, int depth, std::vector<int> & MPLD_search_vector,\n\t\t\tstd::vector<int> & partial_row_results, std::vector<int> & partial_col_results,std::vector<int> & col_results,\n\t\t\tstd::vector<std::vector<int>> &early_quit_count,bool & early_quit)\n{\n\tif (dl.DL_Header.Right == &dl.DL_Header || Vertices_All_Covered(dl, vertex_numbers))\n\t{\n\t\treturn true;\n\t}\n\n\tCell *col;\n\tint this_col = Next_Column_stitch(dl,MPLD_search_vector);\n\n\tcol = &dl.Col_Header_Table[this_col];\n\tLR_remove(*col);\n\tcol_results.push_back(this_col);\n\tif (col->Children_Number == 0)\n\t{\n\t\tint last_row = Order_of_Row_Deleted_in_Col[this_col].back();\n\t\tint conflict_col = Delete_the_Row_in_which_Col[last_row];\n\t\tconflict_pair = std::make_pair(conflict_col, this_col);\n\t\tpartial_row_results.assign(result_vec.begin(),result_vec.end());\n\t\tpartial_row_results.push_back(last_row);\n\t\tpartial_col_results.assign(col_results.begin(), col_results.end());\n\t\tearly_quit_count[conflict_col][this_col] ++;\n\t\tearly_quit_count[this_col][conflict_col] ++;\n\t\tif(early_quit_count[this_col][conflict_col] > 500 || early_quit_count[conflict_col][this_col]> 500){\n\t\t\tearly_quit = true;\n\t\t\tLR_recover(*col);\n\t\t\tcol_results.pop_back();\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tfor (Cell *j = col->Down; j != col; j = j->Down)\n\t{\n\t\tstd::set<int> row_set;\n\t\tstd::set<int> col_set;\n\t\tresult_vec.push_back(j->Row);\n\t\tSelect_All_Rows_Cols(dl, j->Row, row_set, col_set);\n\t\tefficient_store_intermediate_process(dl, this_col, row_set, Delete_the_Row_in_which_Col, Order_of_Row_Deleted_in_Col);\n\t\tRemove_Rows_Cols(dl, row_set, col_set);\n\t\tif (Efficient_MPLD_X_Solver_v2(dl, result_vec, conflict_pair, vertex_numbers, Delete_the_Row_in_which_Col, Order_of_Row_Deleted_in_Col, depth + 1, \n\t\tMPLD_search_vector,partial_row_results,partial_col_results,col_results,early_quit_count,early_quit))\n\t\t\treturn true;\n\t\telse{\n\t\t\tif(early_quit){\n\t\t\t\tresult_vec.pop_back();\n\t\t\t\tefficient_recover_intermediate_process(dl, this_col, row_set, Delete_the_Row_in_which_Col, Order_of_Row_Deleted_in_Col);\n\t\t\t\tRecover_Rows_Cols(dl, row_set, col_set);\n\t\t\t\tLR_recover(*col);\n\t\t\t\tcol_results.pop_back();\n#ifdef DEBUG_DANCINGLINKCOLORING\n                mplPrint(kDEBUG, \"END by early stop: this_col : %d depth : %d\\n\", this_col, depth);\n#endif\n\t\t\t\treturn false;\n\t\t\t}\t\n\t\t}\n\n\t\tresult_vec.pop_back();\n\t\tefficient_recover_intermediate_process(dl, this_col, row_set, Delete_the_Row_in_which_Col, Order_of_Row_Deleted_in_Col);\n\t\tRecover_Rows_Cols(dl, row_set, col_set);\n\t}\n\tLR_recover(*col);\n\tcol_results.pop_back();\n\treturn false;\n}\n\n\n/***\n * The core function to solve one dl.\n * Typically, this function may run MPLD_X_Solver  multiple times due to the existence of some exact conflicts\n * Return : selected row \n * **/\nstd::vector<int> core_solve_dl(DancingLink & dl, std::vector<std::list<Edge_Simple> > & edge_list,  int  row_numbers,  int  col_numbers,\n int  vertex_numbers, int mask_number){\n\t//the total conflict pairs \n\t// boost::timer::cpu_timer dancing_link_timer;\n\t// //dancing_link_timer.start();\n\tstd::pair<int, int>  conflict_pair;\n\t//the conflict pair if MPLD_X_Solver has NO a conflict-free solution\n\tstd::set<std::pair<int, int> >  final_conflict;\n\t//selected result rows if MPLD_X_Solver has a conflict-free solution\n\tstd::vector<int> selected_rows;\n\t//the final selected cols;\n\tstd::vector<int> selected_cols;\n\t//the partial selected rows(coloring results actually) if MPLD_X_Solver has NO a conflict-free solution\n\tstd::vector<int> partial_selected_rows;\n\t//the partial selected cols(selected )  if MPLD_X_Solver has NO a conflict-free solution\n\tstd::vector<int> partial_selected_cols;\n\t//the final selected rows\n\tstd::vector<int> final_result;\n\t//middle information for recover partial results\n\tstd::vector<int> Delete_the_Row_in_which_Col;\n\tstd::vector<std::list<int> >  Order_of_Row_Deleted_in_Col;\n\tOrder_of_Row_Deleted_in_Col.resize(col_numbers + 1);\n\tDelete_the_Row_in_which_Col.resize(row_numbers + 1);\n\tstd::vector<int> MPLD_search_vector;\n\t//MPLD_search_vector = BFS_Order(edge_list);\n\t//MPLD_search_vector = Simple_Order(edge_list.size());\n\tMPLD_search_vector = BFS_Order_no_stitch_first(edge_list,dl);\n\t//MPLD_search_vector = BFS_Order_max_first(edge_list);\n\t// for(auto i = 0; i<MPLD_search_vector.size(); i++){\n\t// \tstd::cout<<MPLD_search_vector[i]<<\" \";\n\t// }\n\t// std::cout<<std::endl;\n\tint depth = 1;\n\tstd::vector<std::vector<int>> early_quit_count;\n\tfor(auto i = 0; i <= vertex_numbers; i++){\n\t\tstd::vector<int> row_early_quite_count;\n\t\trow_early_quite_count.assign(vertex_numbers+1,0);\n\t\tearly_quit_count.push_back(row_early_quite_count);\n\t}\n\tbool early_quit = false;\n\tbool result = Efficient_MPLD_X_Solver_v2(dl, selected_rows, conflict_pair, vertex_numbers, Delete_the_Row_in_which_Col, Order_of_Row_Deleted_in_Col, depth, \n\t\tMPLD_search_vector,partial_selected_rows,partial_selected_cols,selected_cols,early_quit_count, early_quit);\n\tint iteration = 1;\n\t//std::cout<< \"IN MPL:::::::::::::::::::::first try solve \" << dancing_link_timer.format(6)<<std::endl;\n\t//dancing_link_timer.start();\n\twhile(result==false && partial_selected_rows.size()< vertex_numbers){\n\t\tmplAssert(partial_selected_rows.size() == partial_selected_cols.size());\n\t\titeration++;\n#ifdef DEBUG_DANCINGLINKCOLORING\n        mplPrint(kDEBUG, \"iteration %d\\n\", iteration);\n#endif\n\t\tfinal_conflict.insert(conflict_pair);\n\t\tint col_edge = -1;\n\t\tfor(std::list<Edge_Simple>::iterator conflict_edge = edge_list[conflict_pair.first].begin();conflict_edge != edge_list[conflict_pair.first].end();++conflict_edge){\n\t\t\tif((*conflict_edge).target == conflict_pair.second){\n\t\t\t\tcol_edge  = (*conflict_edge).No;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(col_edge==-1){\n\t\t\tstd::cout<<\"bug found!\"<<std::endl;\n\t\t}\n\t\tmplAssert(col_edge!=-1);\n\t\tmplAssert(selected_rows.size() == 0);\n\t\tfor(int i = 1;i<=mask_number;i++){\n\t\t\tint this_col = vertex_numbers + (col_edge -1)*(mask_number) + i;\n\t\t\t//Cell *col = &dl.Col_Header_Table[this_col];\n\t\t\tRemove_Single_Col(dl,this_col);\n\t\t}\n\t\t//std::cout<< \"IN MPL:::::::::::::::::::::remove conflict cols \" << dancing_link_timer.format(6)<<std::endl;\n\t\t//dancing_link_timer.start();\n\t\tfinal_result.insert( final_result.end(), partial_selected_rows.begin(), partial_selected_rows.end() );\n\t\t//NOTE that the order between the two parts (remove edges and recover partial results are important! Cause some rows won't be removed this time due to the exact conflict edge is removed)\n\t\tfor(int i = 0; i < partial_selected_rows.size(); i++){\n\t\t\t//if the row is selected ( in the partial result), recover the partial results\n\t\t\t\tstd::set<int> row_set;\n\t\t\t\tstd::set<int> col_set;\n\t\t\t\tSelect_All_Rows_Cols(dl, partial_selected_rows[i], row_set, col_set);\n\t\t\t\tefficient_store_intermediate_process(dl, partial_selected_cols[i], row_set, Delete_the_Row_in_which_Col, Order_of_Row_Deleted_in_Col);\n\t\t\t\tRemove_Rows_Cols(dl, row_set, col_set);\n\t\t}\n\t\t//std::cout<< \"IN MPL:::::::::::::::::::::recover partial results \" << dancing_link_timer.format(6)<<std::endl;\n\t\t//dancing_link_timer.start();\n\t\tpartial_selected_rows.clear();\n\t\tpartial_selected_cols.swap(selected_cols);\n\t\tselected_cols.clear();\n\t\tdepth = 1;\n\t\tfor (auto &v: early_quit_count) {\n\t\t\tstd::fill(v.begin(), v.end(), 0);\n\t\t}\n\t\tearly_quit = false;\n\t\tresult = Efficient_MPLD_X_Solver_v2(dl, selected_rows, conflict_pair, vertex_numbers, Delete_the_Row_in_which_Col, Order_of_Row_Deleted_in_Col, depth, \n\t\tMPLD_search_vector,partial_selected_rows,partial_selected_cols,selected_cols,early_quit_count, early_quit);\n\t\t//std::cout<< \"IN MPL:::::::::::::::::::::second try solve \" << dancing_link_timer.format(6)<<std::endl;\n\t\t//dancing_link_timer.start();\n\t}\n\tif(selected_rows.size() != 0){\n\t\tfinal_result.insert( final_result.end(), selected_rows.begin(), selected_rows.end() );\n\t\tmplAssert(final_result.size() == vertex_numbers);\n\t}\n\telse final_result.insert( final_result.end(), partial_selected_rows.begin(), partial_selected_rows.end() );\n\treturn final_result;\n}\n/***\n * The function to decode and calculate the cost of the results of DL.\n * Args: selected rows\n * Return : selected row \n * **/\n\nvoid decode_row_results(std::vector<int> & final_result, std::vector<int8_t>& color_vector, int vertex_number,\nint  mask_number, std::vector<std::vector<std::pair<uint32_t,uint32_t>>>& decode_mat, std::vector<Vertex*> & node_list ){\n\tstd::vector<int8_t> color_results_wo_stitch (vertex_number);\n\tfor (auto i = final_result.begin(); i != final_result.end(); i++)\n\t{\n\t\t// if the selected row is in the range of parent node (no stitch)\n\t\t// std::cout << *i << std::endl;\n\t\tif((*i) < vertex_number * mask_number + 1){\n\t\tint No = ((*i) - 1) / mask_number + 1;\n\t\tint mask = (*i + 2) % mask_number;\n\t\tcolor_results_wo_stitch[No-1] = mask; }\n\t\t// std::cout<<\"selected rows: \"<<(*i)<<std::endl;\n\t\t//if the selected_rows represent some stitches rows \n\t\tif((*i) > (vertex_number * (uint32_t)(mask_number) + (uint32_t)1)){\n\t\t\tstd::vector<std::pair<uint32_t,uint32_t>>& row_decoder = decode_mat[(*i)- vertex_number * mask_number -2];\n\t\t\tfor(std::vector<std::pair<uint32_t,uint32_t>>::iterator it = row_decoder.begin(); it != row_decoder.end(); ++it) {\n\t\t\t\tcolor_vector[(*it).first] = (*it).second;\n\t\t\t\t// std::cout<<\"Corresponding color \"<<(*it).first<<\" \"<<(*it).second<<std::endl;\n\t\t\t}\n\t\t}\n\t}\n\t// std::cout<<\"Finished\"<<std::endl;\n\n\tfor(std::vector<Vertex*>::iterator it = node_list.begin(); it != node_list.end(); ++it) {\n\t\tif(color_vector[(*it)->Stitch_No]!= -1){continue;}\n\t\tif((*it)->No == 0){\n\t\t\tmplAssert((*it)->Is_Parent == false);\n\t\t\tmplAssert((*it)->parent->Stitch_No == -1);\n\t\t\tmplAssert(color_results_wo_stitch[(*it)->parent->No -1]!= -1);\n\t\t\tcolor_vector[(*it)->Stitch_No] = color_results_wo_stitch[(*it)->parent->No -1];\n\t\t}\n\t\telse{\n\t\t\tmplAssert(color_results_wo_stitch[(*it)->No -1]!=-1);\n\t\t\tcolor_vector[(*it)->Stitch_No] = color_results_wo_stitch[(*it)->No -1];\n\t\t}\n\t}\n\treturn;\n}\n\nvoid decode_row_results_wo_skeleton(std::vector<int> & final_result, std::vector<int8_t>& color_vector, int vertex_number,\nint  mask_number, std::vector<std::vector<std::pair<uint32_t,uint32_t>>>& decode_mat, std::vector<Vertex*> & node_list ){\n\tstd::vector<int8_t> color_results_wo_stitch (vertex_number);\n\tfor (auto i = final_result.begin(); i != final_result.end(); i++)\n\t{\n\t\t// if the selected row is in the range of parent node (no stitch)\n\t\t// std::cout << *i << std::endl;\n\t\tif((*i) < vertex_number * mask_number + 1){\n\t\tint No = ((*i) - 1) / mask_number + 1;\n\t\tint mask = (*i + 2) % mask_number;\n\t\tcolor_results_wo_stitch[No-1] = mask; }\n\n\t\t//if the selected_rows represent some stitches rows \n\t\tif((*i) > (vertex_number * (uint32_t)(mask_number))){\n\t\t\tstd::vector<std::pair<uint32_t,uint32_t>>& row_decoder = decode_mat[(*i)- vertex_number * mask_number -1];\n\t\t\tfor(std::vector<std::pair<uint32_t,uint32_t>>::iterator it = row_decoder.begin(); it != row_decoder.end(); ++it) {\n\t\t\t\tcolor_vector[(*it).first] = (*it).second;\n\t\t\t}\n\t\t}\n\t}\n\n\n\tfor(std::vector<Vertex*>::iterator it = node_list.begin(); it != node_list.end(); ++it) {\n\t\tif(color_vector[(*it)->Stitch_No]!= -1){continue;}\n\t\tif((*it)->No == 0){\n\t\t\tmplAssert((*it)->Is_Parent == false);\n\t\t\tmplAssert((*it)->parent->Stitch_No == -1);\n\t\t\tmplAssert(color_results_wo_stitch[(*it)->parent->No -1]!= -1);\n\t\t\tcolor_vector[(*it)->Stitch_No] = color_results_wo_stitch[(*it)->parent->No -1];\n\t\t}\n\t\telse{\n\t\t\tmplAssert(color_results_wo_stitch[(*it)->No -1]!=-1);\n\t\t\tcolor_vector[(*it)->Stitch_No] = color_results_wo_stitch[(*it)->No -1];\n\t\t}\n\t}\n\treturn;\n}\nvoid Decode(int vertex_numbers, int mask_numbers, std::vector<int> result_vec, std::pair<int, int> conflict_pair, std::string filename)\n{\n\t(void)conflict_pair;\n\t(void)filename;\n\t(void)vertex_numbers;\n\tstd::map<int, int> Final_Color;\n\tstd::ofstream fileout(filename);\n\tfileout << \"Solution : \" << std::endl;\n\tfor (auto i = result_vec.begin(); i != result_vec.end(); i++)\n\t{\n\t\t// std::cout << *i << std::endl;\n\t\tint No = ((*i) - 1) / mask_numbers + 1;\n\t\tint mask = (*i + 2) % mask_numbers + 1;\n\t\tFinal_Color.insert(std::make_pair(No, mask));\n\t}\n\tfor (auto i = Final_Color.begin(); i != Final_Color.end(); i++)\n\t{\n\t\tfileout << \"Vertex \" << i->first << \" \\t : \" << i->second << std::endl;\n\t}\n\tfileout << \"=============================================\" << std::endl;\n\n\t// if (conflict_pair!=nullptr)\n\t// {\n\t// \tfileout << \"Conflicts: \" << std::endl;\n\t// \tfileout << \"No\\t Source\\t Target\" << std::endl;\n\t// \tfileout << count++ << \"\\t \" << conflict_pair->first << \"\\t \" <<conflict_pair->second << std::endl;\n\t// \tfileout << \"=============================================\" << std::endl;\n\t// }\n\t\n\tfileout.close();\n} \n\nvoid Decode_OpenMPL(int vertex_numbers, int mask_numbers, std::vector<int8_t>& color_vector,std::vector<int> result_vec, std::pair<int, int> conflict_pair,  char* filename)\n{\n\t(void)filename;\n\t(void)conflict_pair;\n\tfor (auto i = result_vec.begin(); i != result_vec.end(); i++)\n\t{\n\t\t//std::cout << *i << std::endl;\n\t\tif((*i) < vertex_numbers * mask_numbers + 1){\n\t\tint No = ((*i) - 1) / mask_numbers + 1;\n\t\tint mask = (*i + 2) % mask_numbers;\n\t\tcolor_vector[No-1] = mask; }\n\t}\n\n\t// if (!conflict_pair.empty())\n\t// {\n\t// \tstd::cout << \"Conflicts: \" << std::endl;\n\t// \tstd::cout << \"No\\t Source\\t Target\" << std::endl;\n\t// \tint count = 1;\n\t// \tfor (auto i = conflict_pair.begin(); i != conflict_pair.end(); i++)\n\t// \t\t{color_vector[i->second-1] = color_vector[i->first-1];\n\t// \t\tstd::cout << count++ << \"\\t \" << i->first << \"\\t \" << i->second << std::endl;}\n\t// \tstd::cout << \"=============================================\" << std::endl;\n\t// }\n} \n\nvoid MPLD_Solver(std::string Graph_Filename, std::string Exact_Cover_Filename, bool whether_BFS, int mask_numbers,  const char* result_file)\n{\n\t(void)result_file;\n\tint vertex_numbers;\n\tint edge_numbers;\n\tint row_numbers;\n\tint col_numbers;\n\tstd::vector<int8_t> color_vec;\n\tstd::vector<int> result_vec;\n\tstd::pair<int, int>  conflict_pair;\n\tstd::vector<int> Delete_the_Row_in_which_Col;\n\tstd::vector<std::list<int> >  Order_of_Row_Deleted_in_Col;\n\tstd::vector<int> MPLD_search_vector;\n\tDancingLink dl;\n\tstd::cout<<\"Ready to generate cover matrix\"<<std::endl;\n\tConvert_to_Exat_Cover(row_numbers, col_numbers, Graph_Filename, Exact_Cover_Filename, whether_BFS, vertex_numbers, edge_numbers, mask_numbers, MPLD_search_vector);\n\tOrder_of_Row_Deleted_in_Col.resize(col_numbers + 1);\n\tDelete_the_Row_in_which_Col.resize(row_numbers + 1);\n\tDL_Load(dl, Exact_Cover_Filename);\n\t//int depth = 1;\n\t//MPLD_X_Solver(dl, color_vec,result_vec, conflict_pair, vertex_numbers, mask_numbers, Delete_the_Row_in_which_Col, Order_of_Row_Deleted_in_Col, depth, MPLD_search_vector, result_file,col_cover_vector);\n}\n\nSIMPLEMPL_END_NAMESPACE\n", "meta": {"hexsha": "a06c9091ee24e8ccf9756cc969b7d7ed0f1619bc", "size": 37728, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/DL_MPL.cpp", "max_stars_repo_name": "limbo018/OpenMPL", "max_stars_repo_head_hexsha": "de0702ba2f13f921417c42978b6f16e9ccf736fd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 42.0, "max_stars_repo_stars_event_min_datetime": "2018-09-22T17:06:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T15:26:13.000Z", "max_issues_repo_path": "src/DL_MPL.cpp", "max_issues_repo_name": "limbo018/SimpleMPL", "max_issues_repo_head_hexsha": "ef3acec986a3435b81039701b795a2edb640883f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-05T06:59:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-11T08:17:21.000Z", "max_forks_repo_path": "src/DL_MPL.cpp", "max_forks_repo_name": "limbo018/OpenMPL", "max_forks_repo_head_hexsha": "de0702ba2f13f921417c42978b6f16e9ccf736fd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2018-09-25T10:10:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:16:30.000Z", "avg_line_length": 39.1369294606, "max_line_length": 203, "alphanum_fraction": 0.7009117897, "num_tokens": 10688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.26240825911103616}}
{"text": "// --------------------------------------------------------------------------\n//                   OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2015.\n//\n// This software is released under a three-clause BSD license:\n//  * Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n//  * Redistributions in binary form must reproduce the above copyright\n//    notice, this list of conditions and the following disclaimer in the\n//    documentation and/or other materials provided with the distribution.\n//  * Neither the name of any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\n// --------------------------------------------------------------------------\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: Hannes Roest $\n// $Authors: Hannes Roest $\n// --------------------------------------------------------------------------\n\n#include <OpenMS/ANALYSIS/OPENSWATH/OPENSWATHALGO/ALGO/Scoring.h>\n#include <OpenMS/ANALYSIS/OPENSWATH/OPENSWATHALGO/Macros.h>\n#include <cmath>\n\n#include <boost/numeric/conversion/cast.hpp>\n\nnamespace OpenSwath\n{\n  namespace Scoring\n  {\n\n    void normalize_sum(double x[], unsigned int n)\n    {\n      double sumx = std::accumulate(&x[0], &x[0] + n, 0.0);\n      if (sumx == 0.0)\n      {\n        return;\n      } // do not divide by zero\n      for (unsigned int i = 0; i < n; i++)\n      {\n        x[i] = x[i] / sumx;\n      }\n    }\n\n    double NormalizedManhattanDist(double x[], double y[], int n)\n    {\n      OPENSWATH_PRECONDITION(n > 0, \"Need at least one element\");\n\n      double delta_ratio_sum = 0;\n      normalize_sum(x, n);\n      normalize_sum(y, n);\n      for (int i = 0; i < n; i++)\n      {\n        delta_ratio_sum += std::fabs(x[i] - y[i]);\n      }\n      return delta_ratio_sum / n;\n    }\n\n    double RootMeanSquareDeviation(double x[], double y[], int n)\n    {\n      OPENSWATH_PRECONDITION(n > 0, \"Need at least one element\");\n\n      double result = 0;\n      for (int i = 0; i < n; i++)\n      {\n\n        result += (x[i] - y[i]) * (x[i] - y[i]);\n      }\n      return std::sqrt(result / n);\n    }\n\n    double SpectralAngle(double x[], double y[], int n)\n    {\n      OPENSWATH_PRECONDITION(n > 0, \"Need at least one element\");\n\n      double dotprod = 0;\n      double x_len = 0;\n      double y_len = 0;\n      for (int i = 0; i < n; i++)\n      {\n        dotprod += x[i] * y[i];\n        x_len += x[i] * x[i];\n        y_len += y[i] * y[i];\n      }\n      x_len = std::sqrt(x_len);\n      y_len = std::sqrt(y_len);\n\n      return std::acos(dotprod / (x_len * y_len));\n    }\n\n    XCorrArrayType::iterator xcorrArrayGetMaxPeak(XCorrArrayType& array)\n    {\n      OPENSWATH_PRECONDITION(array.size() > 0, \"Cannot get highest apex from empty array.\");\n\n      XCorrArrayType::iterator max_it = array.begin();\n      double max = array.begin()->second;\n      for (XCorrArrayType::iterator it = array.begin(); it != array.end(); ++it)\n      {\n        if (it->second > max)\n        {\n          max = it->second;\n          max_it = it;\n        }\n      }\n      return max_it;\n    }\n\n    void standardize_data(std::vector<double>& data)\n    {\n      OPENSWATH_PRECONDITION(data.size() > 0, \"Need non-empty array.\");\n\n      // subtract the mean and divide by the standard deviation\n      double mean = std::accumulate(data.begin(), data.end(), 0.0) / (double) data.size();\n      double sqsum = 0;\n      for (std::vector<double>::iterator it = data.begin(); it != data.end(); ++it)\n      {\n        sqsum += (*it - mean) * (*it - mean);\n      }\n      double std = sqrt(sqsum / data.size()); // standard deviation\n\n      for (std::size_t i = 0; i < data.size(); i++)\n      {\n        data[i] = (data[i] - mean) / std;\n      }\n    }\n\n    XCorrArrayType normalizedCrossCorrelation(std::vector<double>& data1,\n                                              std::vector<double>& data2, int maxdelay, int lag = 1)\n    {\n      OPENSWATH_PRECONDITION(data1.size() != 0 && data1.size() == data2.size(), \"Both data vectors need to have the same length\");\n\n      // normalize the data\n      standardize_data(data1);\n      standardize_data(data2);\n      std::map<int, double> result = calculateCrossCorrelation(data1, data2, maxdelay, lag);\n      for (std::map<int, double>::iterator it = result.begin(); it != result.end(); ++it)\n      {\n        it->second = it->second / data1.size();\n      }\n      return result;\n    }\n\n    XCorrArrayType calculateCrossCorrelation(std::vector<double>& data1,\n                                             std::vector<double>& data2, int maxdelay, int lag)\n    {\n      OPENSWATH_PRECONDITION(data1.size() != 0 && data1.size() == data2.size(), \"Both data vectors need to have the same length\");\n\n      XCorrArrayType result;\n      int datasize = boost::numeric_cast<int>(data1.size());\n      int i, j, delay;\n\n      for (delay = -maxdelay; delay <= maxdelay; delay = delay + lag)\n      {\n        double sxy = 0;\n        for (i = 0; i < datasize; ++i)\n        {\n          j = i + delay;\n          if (j < 0 || j >= datasize)\n          {\n            continue;\n          }\n          sxy += (data1[i]) * (data2[j]);\n        }\n        result[delay] = sxy;\n      }\n      return result;\n    }\n\n    XCorrArrayType calcxcorr_legacy_mquest_(std::vector<double>& data1,\n                                            std::vector<double>& data2, bool normalize)\n    {\n      OPENSWATH_PRECONDITION(!data1.empty() && data1.size() == data2.size(), \"Both data vectors need to have the same length\");\n      int maxdelay = boost::numeric_cast<int>(data1.size());\n      int lag = 1;\n\n      XCorrArrayType result;\n      double mean1 = std::accumulate(data1.begin(), data1.end(), 0.) / (double)data1.size();\n      double mean2 = std::accumulate(data2.begin(), data2.end(), 0.) / (double)data2.size();\n      double denominator = 1.0;\n      int datasize = boost::numeric_cast<int>(data1.size());\n      int i, j, delay;\n\n      // Normalized cross-correlation = subtract the mean and divide by the standard deviation\n      if (normalize)\n      {\n        double sqsum1 = 0;\n        double sqsum2 = 0;\n        for (std::vector<double>::iterator it = data1.begin(); it != data1.end(); ++it)\n        {\n          sqsum1 += (*it - mean1) * (*it - mean1);\n        }\n\n        for (std::vector<double>::iterator it = data2.begin(); it != data2.end(); ++it)\n        {\n          sqsum2 += (*it - mean2) * (*it - mean2);\n        }\n        // sigma_1 * sigma_2 * n\n        denominator = sqrt(sqsum1 * sqsum2);\n      }\n\n      for (delay = -maxdelay; delay <= maxdelay; delay = delay + lag)\n      {\n        double sxy = 0;\n        for (i = 0; i < datasize; i++)\n        {\n          j = i + delay;\n          if (j < 0 || j >= datasize)\n          {\n            continue;\n          }\n          if (normalize)\n          {\n            sxy += (data1[i] - mean1) * (data2[j] - mean2);\n          }\n          else\n          {\n            sxy += (data1[i]) * (data2[j]);\n          }\n        }\n\n        if (denominator > 0)\n        {\n          result[delay] = sxy / denominator;\n        }\n        else\n        {\n          // e.g. if all datapoints are zero\n          result[delay] = 0;\n        }\n      }\n      return result;\n    }\n\n  } //end namespace Scoring\n}\n", "meta": {"hexsha": "4432c804ba6eb2587ea13d7d38ee991a80075fe4", "size": 8428, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openswathalgo/source/ANALYSIS/OPENSWATH/OPENSWATHALGO/ALGO/Scoring.cpp", "max_stars_repo_name": "tomas-pluskal/openms", "max_stars_repo_head_hexsha": "136ec9057435f6d45d65a8e1465b2a6cff9621a8", "max_stars_repo_licenses": ["Zlib", "Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/openswathalgo/source/ANALYSIS/OPENSWATH/OPENSWATHALGO/ALGO/Scoring.cpp", "max_issues_repo_name": "tomas-pluskal/openms", "max_issues_repo_head_hexsha": "136ec9057435f6d45d65a8e1465b2a6cff9621a8", "max_issues_repo_licenses": ["Zlib", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/openswathalgo/source/ANALYSIS/OPENSWATH/OPENSWATHALGO/ALGO/Scoring.cpp", "max_forks_repo_name": "tomas-pluskal/openms", "max_forks_repo_head_hexsha": "136ec9057435f6d45d65a8e1465b2a6cff9621a8", "max_forks_repo_licenses": ["Zlib", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.712, "max_line_length": 130, "alphanum_fraction": 0.5461556716, "num_tokens": 2103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.26236750062085035}}
{"text": "#include \"CompliantStaticSolver.h\"\n\n#include <sofa/core/ObjectFactory.h>\n\n#include <boost/math/tools/minima.hpp>\n#include <tuple>\n\n#include \"../utils/nr.h\"\n#include \"../utils/scoped.h\"\n\n#include \"../constraint/Constraint.h\"\n\nnamespace sofa {\nnamespace component {\nnamespace odesolver {\n\n// TODO use std::numeric_limits\n\nCompliantStaticSolver::CompliantStaticSolver()\n    : epsilon(initData(&epsilon, (SReal)1e-16, \"epsilon\", \"division by zero threshold\")),\n      line_search(initData(&line_search, unsigned(LS_SECANT), \"line_search\",\n                           \"line search method, 0: none (use dt), 1: brent, 2: secant (default). (warning: brent does not work with constraints.\")),\n      conjugate(initData(&conjugate, true, \"conjugate\", \"conjugate descent directions\")),\n      ls_precision(initData(&ls_precision, (SReal)1e-8, \"ls_precision\", \"line search precision\")),\n      ls_iterations(initData(&ls_iterations, unsigned(10), \"ls_iterations\",\n                             \"line search iterations\")),\n      ls_step(initData(&ls_step, (SReal)1e-8, \"ls_step\",\n                       \"line search bracketing step (should not cross any extrema from current position\"))\n{\n    \n}\n\n\nstruct CompliantStaticSolver::helper {\n\n    simulation::common::VectorOperations vec;\n    simulation::common::MechanicalOperations mec;\n\n    core::behavior::MultiVecDeriv dx;\n    core::behavior::MultiVecDeriv f;\n    \n    \n    helper(const core::ExecParams* params,\n           core::objectmodel::BaseContext* ctx) : vec(params, ctx),\n                                                  mec(params, ctx),\n                                                  dx( &vec, core::VecDerivId::dx() ),\n                                                  f( &vec, core::VecDerivId::force() )    {\n    }\n\n    // TODO const args ?\n    SReal dot(core::MultiVecDerivId lhs, core::MultiVecDerivId rhs)  {\n        vec.v_dot(lhs, rhs);\n        return vec.finish();\n    }\n\n    // arg can't be dx !\n    void K(core::MultiVecDerivId res, core::MultiVecDerivId arg) {\n        vec.v_eq(dx, arg);\n        vec.v_clear( res );\n        \n        mec.addMBKdx( res , 0, 0, -1, true, true);\n        mec.projectResponse( res );\n    }\n\n    void forces(core::MultiVecDerivId res) {\n        mec.computeForce( res );\n        mec.projectResponse( res );\n    }\n\n    template<class Vec>\n    void realloc(Vec& res) {\n        res.realloc( &vec, false, true );\n    }\n\n    \n    template<class Res, class A, class B>\n    void set(Res& res,\n             A& a,\n             B& b,\n             SReal lambda) {\n        vec.v_op(res, a, b, lambda);\n    }\n\n    template<class A, class B>\n    void set(A& res,\n             B& b) {\n        vec.v_eq(res, b);\n    }\n    \n};\n\n\n\n\n\n\nCompliantStaticSolver::ls_info::ls_info()\n    : eps(0),\n      iterations(15),\n      precision(1e-7),\n      fixed_step(1e-5),\n      bracket_step(1e-8) {\n    \n}\n\n\n// minimizes (implicit) potential function in direction dir) by\n// zeroing g = grad^T dir using secant method\n\n// precond:\n// - op.f contains forces for current pos\nvoid CompliantStaticSolver::ls_secant(helper& op,\n                                      core::MultiVecCoordId pos,\n                                      core::MultiVecDerivId dir,\n                                      const ls_info& info) {\n    scoped::timer step(\"ls_secant\");\n    \n    SReal dg = 0;\n    SReal dx = 0;\n\n    SReal g_prev = 0;\n    SReal total = 0;\n\n    // slightly damp newton iterations TODO hardcode\n    static const SReal damping = 1e-14;\n\n    SReal fixed = info.fixed_step;\n    \n    for(unsigned k = 0, n = info.iterations; k < n; ++k) {\n\n        if( k ) {\n            // update forces\n            op.mec.propagateX(pos, true);\n            op.forces( op.f );\n        }\n        \n        const SReal g = op.dot(op.f, dir);\n\n        // std::cout << \"line search (secant) \" << k << \" \"  << total << \" \" << g << std::endl;\n\n        // are we done ?\n        if( std::abs(g) <= info.precision ) break;\n        \n        dg = g - g_prev;\n        \n        const SReal dx_prev = dx;\n\n        // fallback on fixed step\n        dx = fixed;\n\n        // (damped) secant method\n        if( k && (std::abs(dg) > info.eps)) {\n            dx = -(dx_prev / (dg + damping)) * g;\n        } else {\n            \n            // try to move more to change function\n            fixed *= 2;\n            \n        }\n        \n        total += dx;\n        \n        // move dx along dir\n        op.set(pos, pos, dir, dx);\n            \n        // next\n        g_prev = g;\n    }\n    \n}\n\n\n\nstruct CompliantStaticSolver::potential_energy {\n\n    // WARNING: backup/restore pos on scope entry/exit\n    potential_energy(helper& op,\n                     const core::MultiVecCoordId& pos,\n                     const core::MultiVecDerivId& dir,\n                     const core::MultiVecCoordId& tmp,\n                     bool restore = true)\n        : op(op),\n          pos(pos),\n          dir(dir),\n          tmp(tmp),\n          restore(restore) {\n\n        // backup start position\n        op.set(tmp, pos);\n    }\n    \n    \n    helper& op;\n\n    const core::MultiVecCoordId& pos;\n    const core::MultiVecDerivId& dir;\n    const core::MultiVecCoordId& tmp;    \n\n    // do we restore pos in dtor ?\n    bool restore;\n    \n    SReal operator()(SReal x) const {\n\n        // move to x along dir\n        op.set(pos, tmp, dir, x);\n        \n        // update forces/energy\n        op.mec.propagateX(pos, true);\n\n        // TODO apparently, this is not needed\n        // op.forces(op.f);\n\n        // note: potential energy only works for pos !\n        SReal dummy, result;\n        op.mec.computeEnergy(dummy, result);\n\n        // std::cout << \"potential energy: \" << x << \", \" << result << std::endl;\n        \n        return result;\n    }\n\n    \n    ~potential_energy() {\n        if( restore ) {\n            op.set(pos, tmp);\n        }\n    }\n    \n};\n\nvoid CompliantStaticSolver::ls_brent(helper& op,\n                                     core::MultiVecCoordId pos,\n                                     core::MultiVecDerivId dir,\n                                     const ls_info& info,\n                                     core::MultiVecCoordId tmp) {\n    scoped::timer step(\"ls_brent\");\n    typedef utils::nr::optimization<SReal> opt;\n    \n    opt::func_call a, b, c;\n    \n    a.x = 0;\n    b.x = info.bracket_step;\n\n    opt::func_call res;\n\n    {\n        // we need the scope because f might reset pos on scope exit\n        const potential_energy f(op, pos, dir, tmp, false);\n\n        opt::minimum_bracket(a, b, c, f);\n\n        // std::cout << \"bracketing: \" << a.x << \", \" << c.x << std::endl;\n    \n        // TODO compute this from precision\n        const int bits = 32;\n        {\n            boost::uintmax_t iter = info.iterations;\n            std::tie(res.x, res.f) = boost::math::tools::brent_find_minima(f,\n                                                               a.x, c.x,\n                                                               bits,\n                                                               iter);\n            // std::cout << \"brent: \" << res.x << std::endl;\n        }\n\n    }\n    \n    // TODO make sure the last function call is the closest to the optimium\n    // op.set(pos, pos, dir, res.x);\n    \n    // TODO do we want to do this ?\n    // op.mec.propagateX(pos, true);\n    // op.forces(op.f);\n    \n}\n\n\n// accumulate force in an external vector\nclass AugmentedLagrangianVisitor : public simulation::MechanicalVisitor {\n\npublic:\n    AugmentedLagrangianVisitor(const sofa::core::MechanicalParams* mparams,\n                               core::MultiVecId id)\n        : MechanicalVisitor(mparams),\n          id(id) { }\n\n    core::MultiVecId id;\n    \n    Result mstate(simulation::Node* node,\n                  core::behavior::BaseMechanicalState* mm) {\n\n        linearsolver::Constraint* c = node->get<linearsolver::Constraint>(core::objectmodel::BaseContext::Local);\n\n\n        if( c ) {\n            // TODO project ?\n            \n            // add force to external force\n            mm->vOp(params, id.getId(mm), core::ConstVecId::force() );            \n        }\n\n        return RESULT_CONTINUE;\n    }\n    \n    virtual Result fwdMappedMechanicalState(simulation::Node* node,\n                                            core::behavior::BaseMechanicalState* mm) {\n        return mstate(node, mm);\n    }\n\n    virtual Result fwdMechanicalState(simulation::Node* node,\n                                      core::behavior::BaseMechanicalState* mm) {\n        return mstate(node, mm);\n    }\n\n};\n\n\n// somehow setting external force directly does not work \nclass WriteExternalForceVisitor : public simulation::MechanicalVisitor {\npublic:\n    WriteExternalForceVisitor(const sofa::core::MechanicalParams* mparams,\n                              core::MultiVecId id)\n        : MechanicalVisitor(mparams),\n          id(id) { }\n\n\n    core::MultiVecId id;\n    \n    Result mstate(simulation::Node* /*node*/,\n                  core::behavior::BaseMechanicalState* mm) {\n\n        // add force to external force\n\n        // we need to add to externalForce (gravity)\n        mm->vOp(params, core::VecId::externalForce(), id.getId(mm));\n        // core::VecId::externalForce(),\n        // , 1.0 );\n        \n        return RESULT_CONTINUE;\n    }\n    \n    virtual Result fwdMappedMechanicalState(simulation::Node* node,\n                                            core::behavior::BaseMechanicalState* mm) {\n        return mstate(node, mm);\n    }\n\n    virtual Result fwdMechanicalState(simulation::Node* node,\n                                      core::behavior::BaseMechanicalState* mm) {\n        return mstate(node, mm);\n    }\n\n};\n\n\nSOFA_DECL_CLASS(CompliantStaticSolver)\nint CompliantStaticSolverClass = core::RegisterObject(\"Static solver\")\n    .add< CompliantStaticSolver >();\n\n\n    void CompliantStaticSolver::solve(const core::ExecParams* params,\n                                SReal dt,\n                                core::MultiVecCoordId pos,\n                                core::MultiVecDerivId vel) {\n\n        helper op(params, getContext() );\n\n        // mparams setup\n        op.mec.mparams.setImplicit(false);\n        op.mec.mparams.setEnergy(true);\n        \n        // descent direction\n        op.realloc(dir);\n\n        // lagrange multipliers\n        op.realloc(lambda);\n\n        // some work vector for postions\n        op.realloc(tmp);\n\n        // first iteration\n        if(!iteration) {\n            op.vec.v_clear( lambda );\n            previous = 0;\n            \n        }\n        \n        // why on earth does this dot work ?!\n\n        // core::behavior::MultiVecDeriv ext(&op.vec, core::VecDerivId::externalForce() );\n        // op.set(ext, lambda);\n        {\n            WriteExternalForceVisitor vis(&op.mec.mparams, lambda.id());\n            getContext()->executeVisitor(&vis, true);\n\n            // core::behavior::MultiVecDeriv ext(&op.vec, core::VecDerivId::externalForce() );\n            // std::cout << ext << std::endl;\n        }\n        \n        // obtain (projected) gradient\n        op.forces( op.f );\n        \n        // note: we *could* skip the above when line-search is on\n        // after the first iteration, but we would miss any change in\n        // the scene (e.g. mouse interaction)\n\n        // polar-ribiere\n        const SReal current = op.dot(op.f, op.f);\n\n        if(!iteration) {\n            // something large at first ?\n            \n            // TODO figure out a reasonable default\n            augmented = std::sqrt(current) / 2.0;\n        }\n\n\n        \n        SReal beta = 0;\n\n        const SReal eps = epsilon.getValue();\n        if( conjugate.getValue() && std::abs(previous) > eps ) {\n\n            {\n                if(iteration > 0) {\n                    // polak-ribiere\n                    beta = (current - op.dot(vel, op.f) ) / previous;\n\n                    // dai-yuan\n                    // beta = current / (op.dot(dir, vel) - op.dot(dir, op.f) );\n                }\n\n                // direction reset\n                // beta = std::max(0.0, beta);\n            }\n            \n        }\n\n        // conjugation\n        op.set(dir, op.f, dir, beta);\n\n        // polak-ribiere\n        {\n            // backup previous f to vel\n            op.set(vel, op.f);\n        }\n\n        \n        // line search\n        const unsigned ls = line_search.getValue();\n        if( ls ) {\n            ls_info info;\n\n            info.eps = eps;\n            info.precision = ls_precision.getValue();\n            info.iterations = ls_iterations.getValue();\n            info.fixed_step = dt; \n            info.bracket_step = ls_step.getValue();\n            \n            switch( ls ) {\n                \n            case LS_SECANT:\n                ls_secant(op, pos, dir.id(), info);\n                break;\n                \n            case LS_BRENT:\n                ls_brent(op, pos, dir.id(), info, tmp.id());\n                break;\n                \n            default:\n                throw std::runtime_error(\"bad line-search\");\n            }\n            \n        } else {\n            // fixed step\n            op.set(pos, pos, dir.id(), dt);\n        }\n\n        const SReal error = std::sqrt( op.dot(op.f, op.f) );\n\n        if( f_printLog.getValue() ) {\n            sout << \"forces norm: \" << error << sendl;\n        }\n        \n        // augmented lagrangian\n        if( error <= augmented ) {\n            \n            // TODO don't waste time if we have no constraints\n            op.mec.propagateX(pos, true);\n            op.forces(op.f);\n\n            AugmentedLagrangianVisitor vis(&op.mec.mparams, lambda.id() );\n            getContext()->executeVisitor( &vis, true );\n\n            // TODO should we reset CG ?\n            // op.vec.v_clear(dir);\n            \n            augmented /= 2;\n\n            if( f_printLog.getValue() ) {\n                sout << \"augmented lagrangian threshold: \" << augmented << sendl;\n            }\n                    \n        }\n\n\n        // next iteration\n        previous = current;\n\n        ++iteration;\n    }\n\n\n\n\n    void CompliantStaticSolver::reset() {\n        iteration = 0;\n\n    }\n\n    void CompliantStaticSolver::init() {\n        \n    }\n\n\n\n\n\n\n\n}\n}\n}\n", "meta": {"hexsha": "69c3949ccc76b09e5c50ff410c26381b249172d8", "size": 14144, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/plugins/Compliant/odesolver/CompliantStaticSolver.cpp", "max_stars_repo_name": "sofa-framework/issofa", "max_stars_repo_head_hexsha": "94855f488465bc3ed41223cbde987581dfca5389", "max_stars_repo_licenses": ["OML"], "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/plugins/Compliant/odesolver/CompliantStaticSolver.cpp", "max_issues_repo_name": "sofa-framework/issofa", "max_issues_repo_head_hexsha": "94855f488465bc3ed41223cbde987581dfca5389", "max_issues_repo_licenses": ["OML"], "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/plugins/Compliant/odesolver/CompliantStaticSolver.cpp", "max_forks_repo_name": "sofa-framework/issofa", "max_forks_repo_head_hexsha": "94855f488465bc3ed41223cbde987581dfca5389", "max_forks_repo_licenses": ["OML"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5864661654, "max_line_length": 148, "alphanum_fraction": 0.504736991, "num_tokens": 3256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376236, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.26236749419176625}}
{"text": "#include <merely3d/mesh.hpp>\n\n#include <Eigen/Dense>\n\n#include <array>\n\n\nusing Eigen::Vector3f;\n\nnamespace merely3d\n{\n    StaticMesh::StaticMesh(std::vector<float> vertices_and_normals, std::vector<unsigned int> faces)\n            : _data(new detail::StaticMeshData(std::move(vertices_and_normals),\n                                               std::move(faces)))\n    {\n        if (_data->faces.size() % 3 != 0)\n        {\n            throw std::invalid_argument(\"Faces must have size divisible by 3\");\n        }\n        if (_data->vertices_and_normals.size() % 6 != 0)\n        {\n            throw std::invalid_argument(\"Vertices and normals must have size divisible by 6\");\n        }\n    }\n\n    StaticMesh::StaticMesh(std::vector<float> vertices,\n                                  std::vector<float> normals,\n                                  std::vector<unsigned int> faces)\n    {\n        if (vertices.size() % 3 != 0)\n        {\n            throw std::invalid_argument(\"Vertices must have size divisible by 3\");\n        }\n        if (normals.size() % 3 != 0)\n        {\n            throw std::invalid_argument(\"Normals must have size divisible by 3\");\n        }\n        if (faces.size() % 3 != 0)\n        {\n            throw std::invalid_argument(\"Faces must have size divisible by 3\");\n        }\n        if (vertices.size() != normals.size())\n        {\n            throw std::invalid_argument(\"Number of vertices and normals must be the same.\");\n        }\n\n        const auto num_vertices = vertices.size() / 3;\n        decltype(vertices) vertices_and_normals;\n        auto & vn = vertices_and_normals;\n\n        for (size_t i = 0; i < num_vertices; ++i)\n        {\n            const auto vbegin = vertices.begin() + 3 * i;\n            const auto nbegin = normals.begin() + 3 * i;\n            vn.insert(vn.end(), vbegin, vbegin + 3);\n            vn.insert(vn.end(), nbegin, nbegin + 3);\n        }\n        _data = std::make_shared<detail::StaticMeshData>(std::move(vertices_and_normals), std::move(faces));\n    }\n\n    StaticMesh StaticMesh::with_angle_weighted_normals(std::vector<float> vertices, std::vector<unsigned int> faces)\n    {\n        if (vertices.size() % 3 != 0)\n        {\n            throw std::invalid_argument(\"Vertices must have size divisible by 3\");\n        }\n        if (faces.size() % 3 != 0)\n        {\n            throw std::invalid_argument(\"Faces must have size divisible by 3\");\n        }\n\n        std::vector<float> normals(vertices.size(), 0.0f);\n\n        for (size_t i = 0; i < faces.size(); i += 3)\n        {\n            const auto triangle = std::array<unsigned int, 3> { faces[i], faces[i + 1], faces[i + 2] };\n\n            const auto v0 = Vector3f(vertices[3 * triangle[0]], vertices[3 * triangle[0] + 1], vertices[3 * triangle[0] + 2]);\n            const auto v1 = Vector3f(vertices[3 * triangle[1]], vertices[3 * triangle[1] + 1], vertices[3 * triangle[1] + 2]);\n            const auto v2 = Vector3f(vertices[3 * triangle[2]], vertices[3 * triangle[2] + 1], vertices[3 * triangle[2] + 2]);\n\n            const auto face_vertices = std::array<Vector3f, 3> { v0, v1, v2 };\n            const Vector3f face_normal = (v1 - v0).cross(v2 - v0);\n\n            // For each vertex in the face, compute contribution to angle-weighted vertex normals\n            for (size_t j = 0; j < 3; ++j)\n            {\n                // Compute left and right edge vectors that meet in local vertex (j + 1)\n                const Vector3f left = (face_vertices[j] - face_vertices[(j + 1) % 3]).normalized();\n                const Vector3f right = (face_vertices[(j + 2) % 3] - face_vertices[(j + 1) % 3]).normalized();\n                const float dot = left.dot(right);\n                // Rounding errors may push the dot product beyond the domain of acos, so we clamp the result\n                // to the allowed range [-1, 1]\n                const float angle = std::acos(std::max(-1.0f, std::min(dot, 1.0f)));\n                const auto vertex_index = triangle[(j + 1) % 3];\n                assert(vertex_index < vertices.size() / 3);\n                assert(std::isfinite(angle));\n                normals[3 * vertex_index + 0] += angle * face_normal[0];\n                normals[3 * vertex_index + 1] += angle * face_normal[1];\n                normals[3 * vertex_index + 2] += angle * face_normal[2];\n            }\n        }\n\n        for (size_t i = 0; i < normals.size(); i += 3)\n        {\n            const Vector3f normal = Vector3f(normals[i], normals[i + 1], normals[i + 2]).normalized();\n            normals[i + 0] = normal[0];\n            normals[i + 1] = normal[1];\n            normals[i + 2] = normal[2];\n        }\n\n        return StaticMesh(std::move(vertices), std::move(normals), std::move(faces));\n    }\n}", "meta": {"hexsha": "62dbdf39cf31c1d27a53bf73a3b2146884c6073d", "size": 4726, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mesh.cpp", "max_stars_repo_name": "digitalillusions/merely3d", "max_stars_repo_head_hexsha": "c14326d4bef325b64da25fb8bf79c32665299549", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-01-07T12:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-31T04:47:16.000Z", "max_issues_repo_path": "src/mesh.cpp", "max_issues_repo_name": "digitalillusions/merely3d", "max_issues_repo_head_hexsha": "c14326d4bef325b64da25fb8bf79c32665299549", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2018-10-18T13:54:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-06T13:48:24.000Z", "max_forks_repo_path": "src/mesh.cpp", "max_forks_repo_name": "digitalillusions/merely3d", "max_forks_repo_head_hexsha": "c14326d4bef325b64da25fb8bf79c32665299549", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-02-03T19:10:31.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-05T14:10:15.000Z", "avg_line_length": 41.4561403509, "max_line_length": 126, "alphanum_fraction": 0.5408379179, "num_tokens": 1199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.26216657965274737}}
{"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_PLAYGROUND_OPERATORS_RECONSTRUCTIONS_HH\n#define DUNE_GDT_PLAYGROUND_OPERATORS_RECONSTRUCTIONS_HH\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <dune/gdt/playground/localevaluation/swipdg.hh>\n#include <dune/gdt/operators/fluxreconstruction.hh>\n\nnamespace Dune {\nnamespace GDT {\nnamespace Operators {\n\n\ntemplate< class GridViewType, class DiffusionFactorType, class DiffusionTensorType >\nclass DiffusiveFluxReconstruction\n{\n  static_assert(GridViewType::dimension == 2, \"Only implemented for dimDomain 2 at the moment!\");\n  static_assert(std::is_base_of< Stuff::IsLocalizableFunction, DiffusionFactorType >::value,\n                \"DiffusionFactorType has to be tagged as Stuff::IsLocalizableFunction!\");\n  static_assert(std::is_base_of< Stuff::IsLocalizableFunction, DiffusionTensorType >::value,\n                \"DiffusionTensorType has to be tagged as Stuff::IsLocalizableFunction!\");\npublic:\n  typedef typename GridViewType::template Codim< 0 >::Entity EntityType;\n  typedef typename GridViewType::ctype DomainFieldType;\n  static const size_t dimDomain = GridViewType::dimension;\n  typedef typename DiffusionFactorType::RangeFieldType FieldType;\n  typedef typename DiffusionFactorType::DomainType DomainType;\n\nprivate:\n  static_assert(dimDomain == 2, \"Not implemented!\");\n\npublic:\n  DiffusiveFluxReconstruction(const GridViewType& grid_view,\n                              const DiffusionFactorType& diffusion_factor,\n                              const DiffusionTensorType& diffusion_tensor,\n                              const size_t over_integrate = 0)\n    : grid_view_(grid_view)\n    , diffusion_factor_(diffusion_factor)\n    , diffusion_tensor_(diffusion_tensor)\n    , over_integrate_(over_integrate)\n  {}\n\n  template< class GV, class V >\n  void apply(const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, FieldType, 1 >& source,\n             DiscreteFunction< Spaces::RT::PdelabBased< GV, 0, FieldType, dimDomain >, V >& range) const\n  {\n    const auto& rtn0_space = range.space();\n    auto& range_vector = range.vector();\n    const FieldType infinity = std::numeric_limits< FieldType >::infinity();\n    for (size_t ii = 0; ii < range_vector.size(); ++ii)\n      range_vector[ii] = infinity;\n    const LocalEvaluation::SWIPDG::Inner< DiffusionFactorType, DiffusionTensorType >\n        inner_evaluation(diffusion_factor_, diffusion_tensor_);\n    const LocalEvaluation::SWIPDG::BoundaryLHS< DiffusionFactorType, DiffusionTensorType >\n        boundary_evaluation(diffusion_factor_, diffusion_tensor_);\n    const Stuff::Functions::Constant< EntityType, DomainFieldType, dimDomain, FieldType, 1 > constant_one(1);\n    DomainType normal(0);\n    DomainType xx_entity(0);\n    DynamicMatrix< FieldType > tmp_matrix(1, 1, 0);\n    DynamicMatrix< FieldType > tmp_matrix_en_en(1, 1, 0);\n    DynamicMatrix< FieldType > tmp_matrix_en_ne(1, 1, 0);\n    std::vector< typename Spaces::RT::PdelabBased< GV, 0, FieldType, dimDomain >::BaseFunctionSetType::RangeType >\n        basis_values(rtn0_space.mapper().maxNumDofs(),\n                     typename Spaces::RT::PdelabBased< GV, 0, FieldType, dimDomain >::BaseFunctionSetType::RangeType(0));\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 >(); entity_it != entity_it_end; ++entity_it) {\n      const auto& entity = *entity_it;\n      const auto local_DoF_indices = rtn0_space.local_DoF_indices(entity);\n      const auto global_DoF_indices = rtn0_space.mapper().globalIndices(entity);\n      assert(global_DoF_indices.size() == local_DoF_indices.size());\n      const auto local_diffusion_factor = diffusion_factor_.local_function(entity);\n      const auto local_diffusion_tensor = diffusion_tensor_.local_function(entity);\n      const auto local_source = source.local_function(entity);\n      const auto local_basis = rtn0_space.base_function_set(entity);\n      const auto local_constant_one = constant_one.local_function(entity);\n      // walk the intersections\n      const auto intersection_it_end = grid_view_.iend(entity);\n      for (auto intersection_it = grid_view_.ibegin(entity);\n           intersection_it != intersection_it_end;\n           ++intersection_it) {\n        const auto& intersection = *intersection_it;\n        if (intersection.neighbor() && !intersection.boundary()) {\n          const auto neighbor_ptr = intersection.outside();\n          const auto& neighbor = *neighbor_ptr;\n          if (grid_view_.indexSet().index(entity) < grid_view_.indexSet().index(neighbor)) {\n            const auto local_diffusion_factor_neighbor = diffusion_factor_.local_function(neighbor);\n            const auto local_diffusion_tensor_neighbor = diffusion_tensor_.local_function(neighbor);\n            const auto local_source_neighbor = source.local_function(neighbor);\n            const auto local_constant_one_neighbor = constant_one.local_function(neighbor);\n            const size_t local_intersection_index = intersection.indexInInside();\n            const size_t local_DoF_index = local_DoF_indices[local_intersection_index];\n            // do a face quadrature\n            FieldType lhs = 0;\n            FieldType rhs = 0;\n            const size_t integrand_order = inner_evaluation.order(*local_diffusion_factor,\n                                                                  *local_diffusion_tensor,\n                                                                  *local_diffusion_factor_neighbor,\n                                                                  *local_diffusion_tensor_neighbor,\n                                                                  *local_constant_one,\n                                                                  *local_source,\n                                                                  *local_constant_one_neighbor,\n                                                                  *local_source_neighbor);\n            const auto& quadrature = QuadratureRules< DomainFieldType, dimDomain - 1 >::rule(\n                  intersection.type(), boost::numeric_cast< int >(integrand_order + over_integrate_));\n            const auto quadrature_it_end = quadrature.end();\n            for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) {\n              const auto& xx_intersection = quadrature_it->position();\n              xx_entity = intersection.geometryInInside().global(xx_intersection);\n              normal = intersection.unitOuterNormal(xx_intersection);\n              const FieldType integration_factor = intersection.geometry().integrationElement(xx_intersection);\n              const FieldType weigth = quadrature_it->weight();\n              // evalaute\n              local_basis.evaluate(xx_entity, basis_values);\n              const auto& basis_value = basis_values[local_DoF_index];\n              tmp_matrix *= 0.0;\n              tmp_matrix_en_en *= 0.0;\n              tmp_matrix_en_ne *= 0.0;\n              inner_evaluation.evaluate(*local_diffusion_factor,\n                                        *local_diffusion_tensor,\n                                        *local_diffusion_factor_neighbor,\n                                        *local_diffusion_tensor_neighbor,\n                                        *local_constant_one,\n                                        *local_source,\n                                        *local_constant_one_neighbor,\n                                        *local_source_neighbor,\n                                        intersection,\n                                        xx_intersection,\n                                        tmp_matrix_en_en, // <- we are interested in this one\n                                        tmp_matrix,\n                                        tmp_matrix_en_ne, // <- and this one\n                                        tmp_matrix);\n              // compute integrals\n              assert(tmp_matrix_en_en.rows() >= 1);\n              assert(tmp_matrix_en_en.cols() >= 1);\n              assert(tmp_matrix_en_ne.rows() >= 1);\n              assert(tmp_matrix_en_ne.cols() >= 1);\n              lhs += integration_factor * weigth * (basis_value * normal);\n              rhs += integration_factor * weigth * (tmp_matrix_en_en[0][0] + tmp_matrix_en_ne[0][0]);\n            } // do a face quadrature\n            // set DoF\n            const size_t global_DoF_index = global_DoF_indices[local_DoF_index];\n            // and make sure we are the first to do so\n            assert(!(range_vector[global_DoF_index] < infinity));\n            range_vector[global_DoF_index] = rhs / lhs;\n          }\n        } else if (intersection.boundary() && !intersection.neighbor()) {\n          const size_t local_intersection_index = intersection.indexInInside();\n          const size_t local_DoF_index = local_DoF_indices[local_intersection_index];\n          // do a face quadrature\n          FieldType lhs = 0;\n          FieldType rhs = 0;\n          const size_t integrand_order = boundary_evaluation.order(*local_diffusion_factor,\n                                                                   *local_diffusion_tensor,\n                                                                   *local_source,\n                                                                   *local_constant_one);\n          const auto& quadrature = QuadratureRules< DomainFieldType, dimDomain - 1 >::rule(\n                intersection.type(), boost::numeric_cast< int >(integrand_order + over_integrate_));\n          const auto quadrature_it_end = quadrature.end();\n          for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) {\n            const auto xx_intersection = quadrature_it->position();\n            normal = intersection.unitOuterNormal(xx_intersection);\n            const FieldType integration_factor = intersection.geometry().integrationElement(xx_intersection);\n            const FieldType weigth = quadrature_it->weight();\n            xx_entity = intersection.geometryInInside().global(xx_intersection);\n            // evalaute\n            local_basis.evaluate(xx_entity, basis_values);\n            const auto& basis_value = basis_values[local_DoF_index];\n            tmp_matrix *= 0.0;\n            boundary_evaluation.evaluate(*local_diffusion_factor,\n                                         *local_diffusion_tensor,\n                                         *local_constant_one,\n                                         *local_source,\n                                         intersection,\n                                         xx_intersection,\n                                         tmp_matrix);\n            // compute integrals\n            assert(tmp_matrix.rows() >= 1);\n            assert(tmp_matrix.cols() >= 1);\n            lhs += integration_factor * weigth * (basis_value * normal);\n            rhs += integration_factor * weigth * tmp_matrix[0][0];\n          } // do a face quadrature\n          // set DoF\n          const size_t global_DoF_index = global_DoF_indices[local_DoF_index];\n          assert(!(range_vector[global_DoF_index] < infinity));\n          // and make sure we are the first to do so\n          range_vector[global_DoF_index] = rhs / lhs;\n        } else\n          DUNE_THROW(Stuff::Exceptions::internal_error, \"Unknown intersection type!\");\n      } // walk the intersections\n    } // walk the grid\n  } // ... apply(...)\n\nprivate:\n  const GridViewType& grid_view_;\n  const DiffusionFactorType& diffusion_factor_;\n  const DiffusionTensorType& diffusion_tensor_;\n  const size_t over_integrate_;\n}; // class DiffusiveFluxReconstruction\n\n\ntemplate< class GV, class DF, class DT >\nDiffusiveFluxReconstruction< GV, DF, DT > make_diffusive_flux_reconstruction(const GV& grid_view,\n                                                                             const DF& diffusion_factor,\n                                                                             const DT& diffusion_tensor,\n                                                                             const size_t over_integrate = 0)\n{\n  return DiffusiveFluxReconstruction< GV, DF, DT >(grid_view, diffusion_factor, diffusion_tensor, over_integrate);\n}\n\n\n} // namespace Operators\n} // namespace GDT\n} // namespace Dune\n\n#endif // DUNE_GDT_PLAYGROUND_OPERATORS_RECONSTRUCTIONS_HH\n", "meta": {"hexsha": "49037e604219f3737b7f746e42ad68b4933dcb31", "size": 12581, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/gdt/playground/operators/fluxreconstruction.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/playground/operators/fluxreconstruction.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/playground/operators/fluxreconstruction.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": 56.6711711712, "max_line_length": 121, "alphanum_fraction": 0.6102853509, "num_tokens": 2429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.4339814648038986, "lm_q1q2_score": 0.26209522184209594}}
{"text": "/*\n * Copyright 2018 James Dyer\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * 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 under\n * the License.\n *\n * This is being developed for the TANGO Project: http://tango-project.eu\n */\n\n#include <jsoncpp/json/json.h>\n#include <NTL/ZZ.h>\n#include \"GACDDecrypter.h\"\n\nNTL::ZZ GACDDecrypter::decrypt(NTL::ZZ& ciphertext){\n\treturn ciphertext/k;\n}\n\nvoid GACDDecrypter::readSecretsFromJSON(std::string& secrets){\n\tJson::Value root;\n\tJson::Reader reader;\n\tbool parsingSuccessful = reader.parse(secrets,root);\n\tif (parsingSuccessful){\n\t\tk = NTL::conv<NTL::ZZ>(root[\"key\"].asCString());\n\t}\n}\n", "meta": {"hexsha": "b25f93a975e3d15cf037e2f2e5f20d620db2ad2c", "size": 1064, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/GACDDecrypter.cpp", "max_stars_repo_name": "TANGO-Project/cryptsdc", "max_stars_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/GACDDecrypter.cpp", "max_issues_repo_name": "TANGO-Project/cryptsdc", "max_issues_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GACDDecrypter.cpp", "max_forks_repo_name": "TANGO-Project/cryptsdc", "max_forks_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4, "max_line_length": 80, "alphanum_fraction": 0.7330827068, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.2620952218420958}}
{"text": "/// @brief Eigen wrappers for different CCD methods\n\n#pragma once\n\n#include <array>\n\n#include <Eigen/Core>\n\nnamespace ccd {\n\n/// Methods of continuous collision detection.\nenum CCDMethod {\n    /// Etienne Vouga's CCD using a root finder in floating points\n    FLOATING_POINT_ROOT_FINDER = 0,\n    /// Floating-point root-finder minimum separation CCD of [Lu et al. 2018]\n    MIN_SEPARATION_ROOT_FINDER,\n    /// Root parity method of [Brochu et al. 2012]\n    ROOT_PARITY,\n    /// Teseo's reimplementation of [Brochu et al. 2012] using rationals\n    RATIONAL_ROOT_PARITY,\n    /// Root parity with and fixes\n    FLOATING_POINT_ROOT_PARITY,\n    /// Rational root parity with fixes\n    RATIONAL_FIXED_ROOT_PARITY,\n    /// Bernstein sign classification method of [Tang et al. 2014]\n    BSC,\n    /// TightCCD method of [Wang et al. 2015]\n    TIGHT_CCD,\n    // SafeCCD\n    SAFE_CCD,\n    /// Interval based CCD of [Redon et al. 2002]\n    UNIVARIATE_INTERVAL_ROOT_FINDER,\n    /// Interval based CCD of [Redon et al. 2002] solved using [Snyder 1992]\n    MULTIVARIATE_INTERVAL_ROOT_FINDER,\n    /// Custom inclusion based CCD of [Wang et al. 2020]\n    TIGHT_INCLUSION,\n    /// WARNING: Not a method! Counts the number of methods.\n    NUM_CCD_METHODS\n};\n\nstatic const char* method_names[CCDMethod::NUM_CCD_METHODS] = {\n    \"FloatingPointRootFinder\",\n    \"MinSeparationRootFinder\",\n    \"RootParity\",\n    \"RationalRootParity\",\n    \"FloatingPointRootParity\",\n    \"RationalFixedRootParity\",\n    \"BSC\",\n    \"TightCCD\",\n    \"SafeCCD\",\n    \"UnivariateIntervalRootFinder\",\n    \"MultivariateIntervalRootFinder\",\n    \"TightInclusion\",\n};\n\n/// Minimum separation distance used when looking for 0 distance collisions.\nstatic const double DEFAULT_MIN_DISTANCE = 1e-8;\n\n/**\n * @brief Detect collisions between a vertex and a triangular face.\n *\n * Looks for collisions between a point and triangle as they move linearily\n * with constant velocity. Returns true if the vertex and face collide.\n *\n * @param[in]  vertex_start        Start position of the vertex.\n * @param[in]  face_vertex0_start  Start position of the first vertex of the\n *                                 face.\n * @param[in]  face_vertex1_start  Start position of the second vertex of the\n *                                 face.\n * @param[in]  face_vertex2_start  Start position of the third vertex of the\n *                                 face.\n * @param[in]  vertex_end          End position of the vertex.\n * @param[in]  face_vertex0_end    End position of the first vertex of the\n *                                 face.\n * @param[in]  face_vertex1_end    End position of the second vertex of the\n *                                 face.\n * @param[in]  face_vertex2_end    End position of the third vertex of the\n *                                 face.\n * @param[in]  method              Method of exact CCD.\n *\n * @returns  True if the vertex and face collide.\n */\nbool vertexFaceCCD(\n    const Eigen::Vector3d& vertex_start,\n    const Eigen::Vector3d& face_vertex0_start,\n    const Eigen::Vector3d& face_vertex1_start,\n    const Eigen::Vector3d& face_vertex2_start,\n    const Eigen::Vector3d& vertex_end,\n    const Eigen::Vector3d& face_vertex0_end,\n    const Eigen::Vector3d& face_vertex1_end,\n    const Eigen::Vector3d& face_vertex2_end,\n    const CCDMethod method,\n    const double tolerance = 1e-6,\n    const long max_iter = 1e6,\n    const std::array<double, 3>& err = { { -1, 0, 0 } });\n\n/**\n * @brief Detect collisions between two edges as they move.\n *\n * Looks for collisions between edges as they move linearly with constant\n * velocity. Returns true if the edges collide.\n *\n * @param[in]  edge0_vertex0_start  Start position of the first edge's first\n *                                  vertex.\n * @param[in]  edge0_vertex1_start  Start position of the first edge's second\n *                                  vertex.\n * @param[in]  edge1_vertex0_start  Start position of the second edge's first\n *                                  vertex.\n * @param[in]  edge1_vertex1_start  Start position of the second edge's second\n *                                  vertex.\n * @param[in]  edge0_vertex0_end    End position of the first edge's first\n *                                  vertex.\n * @param[in]  edge0_vertex1_end    End position of the first edge's second\n *                                  vertex.\n * @param[in]  edge1_vertex0_end    End position of the second edge's first\n *                                  vertex.\n * @param[in]  edge1_vertex1_end    End position of the second edge's second\n *                                  vertex.\n * @param[in]  method               Method of exact CCD.\n *\n * @returns True if the edges collide.\n */\nbool edgeEdgeCCD(\n    const Eigen::Vector3d& edge0_vertex0_start,\n    const Eigen::Vector3d& edge0_vertex1_start,\n    const Eigen::Vector3d& edge1_vertex0_start,\n    const Eigen::Vector3d& edge1_vertex1_start,\n    const Eigen::Vector3d& edge0_vertex0_end,\n    const Eigen::Vector3d& edge0_vertex1_end,\n    const Eigen::Vector3d& edge1_vertex0_end,\n    const Eigen::Vector3d& edge1_vertex1_end,\n    const CCDMethod method,\n    const double tolerance = 1e-6,\n    const long max_iter = 1e6,\n    const std::array<double, 3>& err = { { -1, 0, 0 } });\n\n/**\n * @brief Detect proximity collisions between a vertex and a triangular face.\n *\n * Looks for collisions between a point and triangle as they move linearily\n * with constant velocity. Returns true if the vertex and face collide.\n *\n * @param[in]  vertex_start        Start position of the vertex.\n * @param[in]  face_vertex0_start  Start position of the first vertex of the\n *                                 face.\n * @param[in]  face_vertex1_start  Start position of the second vertex of the\n *                                 face.\n * @param[in]  face_vertex2_start  Start position of the third vertex of the\n *                                 face.\n * @param[in]  vertex_end          End position of the vertex.\n * @param[in]  face_vertex0_end    End position of the first vertex of the\n *                                 face.\n * @param[in]  face_vertex1_end    End position of the second vertex of the\n *                                 face.\n * @param[in]  face_vertex2_end    End position of the third vertex of the\n *                                 face.\n * @param[in]  method              Method of minimum separation CCD.\n *\n * @returns  True if the vertex and face collide.\n */\nbool vertexFaceMSCCD(\n    const Eigen::Vector3d& vertex_start,\n    const Eigen::Vector3d& face_vertex0_start,\n    const Eigen::Vector3d& face_vertex1_start,\n    const Eigen::Vector3d& face_vertex2_start,\n    const Eigen::Vector3d& vertex_end,\n    const Eigen::Vector3d& face_vertex0_end,\n    const Eigen::Vector3d& face_vertex1_end,\n    const Eigen::Vector3d& face_vertex2_end,\n    const double min_distance,\n    const CCDMethod method,\n    const double tolerance = 1e-6,\n    const long max_iter = 1e6,\n    const std::array<double, 3>& err = { { -1, 0, 0 } });\n\n/**\n * @brief Detect proximity collisions between two edges as they move.\n *\n * Looks for collisions between edges as they move linearly with constant\n * velocity. Returns true if the edges collide.\n *\n * @param[in]  edge0_vertex0_start  Start position of the first edge's first\n *                                  vertex.\n * @param[in]  edge0_vertex1_start  Start position of the first edge's second\n *                                  vertex.\n * @param[in]  edge1_vertex0_start  Start position of the second edge's first\n *                                  vertex.\n * @param[in]  edge1_vertex1_start  Start position of the second edge's second\n *                                  vertex.\n * @param[in]  edge0_vertex0_end    End position of the first edge's first\n *                                  vertex.\n * @param[in]  edge0_vertex1_end    End position of the first edge's second\n *                                  vertex.\n * @param[in]  edge1_vertex0_end    End position of the second edge's first\n *                                  vertex.\n * @param[in]  edge1_vertex1_end    End position of the second edge's second\n *                                  vertex.\n * @param[in]  method               Method of minimum separation CCD.\n *\n * @returns True if the edges collide.\n */\nbool edgeEdgeMSCCD(\n    const Eigen::Vector3d& edge0_vertex0_start,\n    const Eigen::Vector3d& edge0_vertex1_start,\n    const Eigen::Vector3d& edge1_vertex0_start,\n    const Eigen::Vector3d& edge1_vertex1_start,\n    const Eigen::Vector3d& edge0_vertex0_end,\n    const Eigen::Vector3d& edge0_vertex1_end,\n    const Eigen::Vector3d& edge1_vertex0_end,\n    const Eigen::Vector3d& edge1_vertex1_end,\n    const double min_distance,\n    const CCDMethod method,\n    const double tolerance = 1e-6,\n    const long max_iter = 1e6,\n    const std::array<double, 3>& err = { { -1, 0, 0 } });\n\ninline bool is_minimum_separation_method(const CCDMethod& method)\n{\n    switch (method) {\n    case CCDMethod::MIN_SEPARATION_ROOT_FINDER:\n    case CCDMethod::TIGHT_INCLUSION:\n        return true;\n    default:\n        return false;\n    }\n}\n\ninline bool is_conservative_method(const CCDMethod& method)\n{\n    switch (method) {\n    // MIN_SEPARATION_ROOT_FINDER is conservative because minimum separation\n    // distance of zero does not work well.\n    case CCDMethod::MIN_SEPARATION_ROOT_FINDER:\n    case CCDMethod::TIGHT_CCD:\n    case CCDMethod::UNIVARIATE_INTERVAL_ROOT_FINDER:\n    case CCDMethod::MULTIVARIATE_INTERVAL_ROOT_FINDER:\n    case CCDMethod::TIGHT_INCLUSION:\n        return true;\n    default:\n        return false;\n    }\n}\n\ninline bool is_time_of_impact_computed(const CCDMethod& method)\n{\n    switch (method) {\n    case CCDMethod::FLOATING_POINT_ROOT_FINDER:\n    case CCDMethod::MIN_SEPARATION_ROOT_FINDER:\n    case CCDMethod::UNIVARIATE_INTERVAL_ROOT_FINDER:\n    case CCDMethod::MULTIVARIATE_INTERVAL_ROOT_FINDER:\n    case CCDMethod::TIGHT_INCLUSION:\n        return true;\n    default:\n        return false;\n    }\n}\n\ninline bool is_method_enabled(const CCDMethod& method)\n{\n    switch (method) {\n    case FLOATING_POINT_ROOT_FINDER:\n        return CCD_WRAPPER_WITH_FPRF;\n\n    case MIN_SEPARATION_ROOT_FINDER:\n        return CCD_WRAPPER_WITH_MSRF;\n\n    case ROOT_PARITY:\n        return CCD_WRAPPER_WITH_RP;\n\n    case RATIONAL_ROOT_PARITY:\n        return CCD_WRAPPER_WITH_RRP;\n\n    case FLOATING_POINT_ROOT_PARITY:\n        return CCD_WRAPPER_WITH_FPRP;\n\n    case RATIONAL_FIXED_ROOT_PARITY:\n        return CCD_WRAPPER_WITH_RFRP;\n\n    case BSC:\n        return CCD_WRAPPER_WITH_BSC;\n\n    case TIGHT_CCD:\n        return CCD_WRAPPER_WITH_TIGHT_CCD;\n\n    case SAFE_CCD:\n        return CCD_WRAPPER_WITH_SAFE_CCD;\n\n    case UNIVARIATE_INTERVAL_ROOT_FINDER:\n    case MULTIVARIATE_INTERVAL_ROOT_FINDER:\n        return CCD_WRAPPER_WITH_INTERVAL;\n\n    case TIGHT_INCLUSION:\n        return CCD_WRAPPER_WITH_TIGHT_INCLUSION;\n\n    default:\n        return false;\n    }\n}\n} // namespace ccd\n", "meta": {"hexsha": "b1d27ead5101f0915a8fab0e7208a1d88f67af79", "size": 10957, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ccd.hpp", "max_stars_repo_name": "zfergus/ccd", "max_stars_repo_head_hexsha": "23907dadf3e1eef606e38450ada4aa4f96fd9f71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-09-24T11:45:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:40:28.000Z", "max_issues_repo_path": "src/ccd.hpp", "max_issues_repo_name": "zfergus/ccd-wrapper", "max_issues_repo_head_hexsha": "23907dadf3e1eef606e38450ada4aa4f96fd9f71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-16T12:07:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T11:24:11.000Z", "max_forks_repo_path": "src/ccd.hpp", "max_forks_repo_name": "zfergus/ccd-wrapper", "max_forks_repo_head_hexsha": "23907dadf3e1eef606e38450ada4aa4f96fd9f71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-07-30T01:27:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T02:28:06.000Z", "avg_line_length": 36.5233333333, "max_line_length": 78, "alphanum_fraction": 0.6531897417, "num_tokens": 2665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2620890201009035}}
{"text": "/*\n\n * ex10.cpp\n\n *\n\n *\n\n *  Author: Daniel Rehfeldt\n\n *\n\n *  Compile: g++ ex10.cpp -o ex10 -O3 -march=native -std=c++14 -lboost_timer  -lboost_system  -pedantic -Wall\n *\n *  Compile with OpenMP:  g++ ex10.cpp -o ex10 -O3 -march=native -std=c++14 -lboost_timer  -lboost_system  -pedantic -Wall -fopenmp\n *\n *\n */\n\n#define NDEBUG\n#define SEQHEAP\n\n#include <limits>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <cassert>\n#include <memory>\n#include <string>\n#include <array>\n#include <algorithm>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/timer/timer.hpp>\n#ifdef SEQHEAP\n#include \"knheap.C\"\n#else\n#include \"binheap.h\"\n#endif\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\n\n\nusing Weight = long long;\n\nstruct IntInt\n{\n      int index;\n      int prededge;\n};\n\n\n\nclass Graph{\n\n    public:\n        int* deg = nullptr;\n        int* term = nullptr;\n        int* head = nullptr;\n        int* tail = nullptr;\n        int* headcprs = nullptr;\n        int* tailcprs = nullptr;\n        int* startcprs = nullptr;\n        int* weightcprs = nullptr;\n        int* orgedgecprs = nullptr;\n        Weight* edgeweight = nullptr;\n        Weight* edgeweightcprs = nullptr;\n\n        int nterms = -1;\n        int nnodes = -1;\n        int nedges = -1;\n        int nmaxedges = -1;\n\n        Graph(int nodes, int maxedges)\n        {\n            assert(nodes >= 1);\n            assert(maxedges >= 0);\n            nedges = 0;\n            nterms = 0;\n            nnodes = nodes;\n            nmaxedges = maxedges;\n\n            if( maxedges > 0 )\n            {\n               // initialize with 0\n               deg = new int[nnodes]();\n               term = new int[nnodes]();\n\n               head = new int[maxedges];\n               tail = new int[maxedges];\n               edgeweight = new Weight[maxedges];\n            }\n        }\n\n        bool isTerm(int i) const;\n\n        void makeTerm(int i);\n\n        void addEdge(int etail, int ehead, Weight eweight);\n\n        // initialize compressed data structures\n        void initCompressed();\n\n        // check whether compression was successful\n        bool compressedValid() const;\n\n        bool isConnected() const;\n\n        ~Graph()\n        {\n           delete[] orgedgecprs;\n           delete[] weightcprs;\n           delete[] edgeweightcprs;\n           delete[] headcprs;\n           delete[] tailcprs;\n           delete[] startcprs;\n           delete[] edgeweight;\n           delete[] deg;\n           delete[] head;\n           delete[] tail;\n        }\n};\n\n\n\nbool Graph::isConnected() const\n{\n     assert(startcprs);\n     assert(headcprs);\n\n     bool* visited = new bool[nnodes];\n     int* stack = new int[nnodes];\n\n     int size = 0;\n\n     std::fill_n(visited, nnodes, false);\n\n     stack[size++] = 0;\n     visited[0] = true;\n\n     int nodecount = 0;\n\n     // DFS\n     while( size )\n     {\n        const int k = stack[--size];\n        nodecount++;\n\n        //traverse adjacent edges of k\n        const int end = startcprs[k + 1];\n        for( int e = startcprs[k]; e != end; e++ )\n        {\n            const int head = headcprs[e];\n            if( !visited[head] )\n            {\n               visited[head] = true;\n               stack[size++] = head;\n            }\n        }\n     }\n\n     delete[] visited;\n     delete[] stack;\n\n     if( nodecount != nnodes )\n         return false;\n\n     return true;\n}\n\ninline bool Graph::isTerm(\n     int i\n) const\n{\n   assert(i >= 0 && i < nnodes);\n   assert(term);\n\n   return (term[i] != 0);\n}\n\ninline void Graph::makeTerm(\n    int i\n)\n{\n   assert(i >= 0 && i < nnodes);\n   assert(term);\n\n   if( !term[i] )\n   {\n      nterms++;\n      term[i] = 1;\n   }\n}\n\n\ninline void Graph::addEdge(\n    int etail,\n    int ehead,\n    Weight eweight\n)\n{\n    assert(ehead >= 0 && ehead < nnodes );\n    assert(etail >= 0 && etail < nnodes );\n    assert(nedges < nmaxedges);\n    assert(eweight >= Weight(0));\n\n    head[nedges] = ehead;\n    tail[nedges] = etail;\n    edgeweight[nedges++] = eweight;\n    deg[ehead]++;\n    deg[etail]++;\n}\n\n\nvoid Graph::initCompressed()\n{\n    tailcprs = new int[2 * nedges];\n    headcprs = new int[2 * nedges];\n    orgedgecprs = new int[2 * nedges];\n    startcprs = new int[nnodes + 1];\n    edgeweightcprs = new Weight[2 * nedges];\n\n    startcprs[0] = deg[0];\n\n    for( int i = 1; i < nnodes; i++ )\n        startcprs[i] = startcprs[i - 1] + deg[i];\n\n    assert(startcprs[nnodes - 1] == 2 * nedges);\n\n    startcprs[nnodes] = 2 * nedges;\n\n    auto update_cprs = [this](int node, int adjnode, int edge)\n    {\n        const int e = --startcprs[node];\n        assert(e >= 0);\n        assert(node == 0 || e >= startcprs[node - 1]);\n        edgeweightcprs[e] = edgeweight[edge];\n        tailcprs[e] = node;\n        headcprs[e] = adjnode;\n        orgedgecprs[e] = edge;\n    };\n\n    for( int e = 0; e < nedges; e++ )\n    {\n        update_cprs(tail[e], head[e], e);\n        update_cprs(head[e], tail[e], e);\n    }\n\n    assert(startcprs[nnodes - 1] + deg[nnodes - 1] == 2 * nedges);\n}\n\n\n\nbool Graph::compressedValid() const\n{\n   if( !startcprs || !edgeweightcprs || !tailcprs || !headcprs || !orgedgecprs )\n      return false;\n\n   auto is_adjacent = [this](int node, int nodeadj)\n   {\n      for( int e = startcprs[node], end = startcprs[node + 1]; e != end; e++ )\n         if( tailcprs[e] != node )\n            return false;\n\n      for( int e = startcprs[node], end = startcprs[node + 1]; e != end; e++ )\n         if( headcprs[e] == nodeadj )\n            return true;\n\n      return false;\n   };\n\n   for( int e = 0; e < nedges; e++ )\n       if( !is_adjacent(tail[e], head[e]) || !is_adjacent(head[e], tail[e]) )\n          return false;\n\n   return true;\n}\n\n// fills array that marks whether edge i is part of the tree (steineredge[i] = true) or not (steineredge[i] = false)\nstatic std::unique_ptr<bool[]> computeSteinerTree(\n    const Graph& graph,\n    const int root\n)\n{\n    const int nnodes = graph.nnodes;\n    const int nedges = graph.nedges;\n    const int nterms = graph.nterms;\n\n    assert(nnodes >= 1);\n    assert(nedges >= 1);\n    assert(nterms >= 1);\n    assert(root >= 0 && root < nnodes);\n\n    auto steineredge = std::make_unique<bool[]>(nedges);\n\n    if( nterms == 1 && graph.isTerm(root) )\n       return move(steineredge);\n\n    const int* orgarr = graph.orgedgecprs;\n    const int* tailarr = graph.tailcprs;\n    const int* headarr = graph.headcprs;\n    const int* startarr = graph.startcprs;\n    const Weight* weightarr = graph.edgeweightcprs;\n\n    assert(orgarr);\n    assert(tailarr);\n    assert(startarr);\n    assert(headarr);\n    assert(weightarr);\n\n    // predecessor and distance array to store incoming edge and distance for each node todo unique pointer\n    bool* steinernode = new bool[nnodes];\n    int* predarr = new int[nnodes];\n    Weight* distarr = new Weight[nnodes];\n\n    // initialize array for Dijkstra calculations\n    std::fill_n(distarr, nnodes, std::numeric_limits<Weight>::max());\n    std::fill_n(predarr, nnodes, -1);\n    std::fill_n(steinernode, nnodes, false);\n\n#ifdef SEQHEAP\n    KNHeap<Weight, IntInt> heap(std::numeric_limits<Weight>::max(), std::numeric_limits<Weight>::min());\n#else\n    BinHeap<Weight, IntInt> heap(2 * nedges);\n#endif\n\n    assert(heap.getSize() == 0);\n\n    IntInt dummy;\n    dummy.index = root;\n    dummy.prededge  = -1;\n    heap.insert(Weight(0), dummy);\n\n    distarr[root] = Weight(0);\n    steinernode[root] = true;\n\n    int termcount = 0;\n    if( graph.isTerm(root) )\n       termcount++;\n\n    while( heap.getSize() != 0 )\n    {\n        Weight distk;\n\n#ifdef SEQHEAP\n        heap.deleteMin(&distk, &dummy);\n#else\n        heap.deleteMin(distk, dummy);\n#endif\n\n        assert(distk >= Weight(0));\n\n        const int node = dummy.index;\n\n        assert(node >= 0);\n\n        if( distarr[node] >= distk )\n        {\n           distarr[node] = distk;\n           predarr[node] = dummy.prededge;\n\n           if( graph.isTerm(node) && !steinernode[node] )\n           {\n              int k = node;\n\n              // add path to current tree\n              do\n              {\n                 int pred;\n                 steinernode[k] = true;\n                 pred = predarr[k];\n\n                 assert(pred >= 0);\n                 assert(headarr[pred] == k);\n\n                 steineredge[orgarr[pred]] = true;\n                 dummy.index = k;\n                 dummy.prededge = pred;\n\n                 distarr[k] = Weight(0);\n\n                 heap.insert(Weight(0), dummy);\n\n                 k = tailarr[pred];\n\n              }\n              while( !steinernode[k] );\n\n              // all terminals connected?\n              if( ++termcount == nterms )\n                 break;\n           }\n\n           // traverse adjacent edges of node\n           const int end = startarr[node + 1];\n           for( int e = startarr[node]; e != end; e++ )\n           {\n               const int head = headarr[e];\n\n               if( distarr[head] > distk + weightarr[e] )\n               {\n                  // update\n                  distarr[head] = distk + weightarr[e];\n                  dummy.index = head;\n                  dummy.prededge = e;\n                  heap.insert(distarr[head], dummy);\n                  //heap.insert(distarr[head], e);\n               }\n           }\n        }\n    }\n\n    delete[] steinernode;\n    delete[] distarr;\n    delete[] predarr;\n\n    return move(steineredge);\n}\n\nstatic bool isTreeValid(\n      const Graph& graph,\n      bool* steinertree,\n      const int root\n)\n{\n   assert(steinertree);\n\n   const int nnodes = graph.nnodes;\n   const int nedges = graph.nedges;\n   const int nterms = graph.nterms;\n   const int* orgarr = graph.orgedgecprs;\n   const int* headarr = graph.headcprs;\n   const int* startarr = graph.startcprs;\n\n   assert(orgarr);\n   assert(startarr);\n   assert(headarr);\n\n   bool* visited = new bool[nnodes];\n   int* stack = new int[nnodes];\n\n   int size = 0;\n   int nsolnodes = 0;\n   int termcount = 0;\n\n   std::fill_n(visited, nnodes, false);\n\n   stack[size++] = root;\n   visited[root] = true;\n\n   // DFS\n   while( size )\n   {\n      const int k = stack[--size];\n\n      nsolnodes++;\n\n      if( graph.isTerm(k) )\n         termcount++;\n\n      //traverse adjacent edges of k\n      const int end = startarr[k + 1];\n      for( int e = startarr[k]; e != end; e++ )\n      {\n          const int head = headarr[e];\n          if( !visited[head] && steinertree[orgarr[e]] )\n          {\n             visited[head] = true;\n             stack[size++] = head;\n          }\n      }\n   }\n\n   delete[] visited;\n   delete[] stack;\n\n   int nsoledges = 0;\n\n   for( int e = 0; e < nedges; e++ )\n      if( steinertree[e] )\n         nsoledges++;\n\n   if( nsoledges != nsolnodes - 1 )\n   {\n       std::cout << \"not a tree \"  << std::endl;\n       return false;\n   }\n\n   if( termcount != nterms )\n   {\n       std::cout << \"not all terminals reached \" << termcount << \" < \" << nterms <<  std::endl;\n       return false;\n   }\n\n   return true;\n}\n\n// adds prime vertices as terminals\nstatic void addTermsPrime(\n      Graph& graph\n)\n{\n   const int nnodes = graph.nnodes;\n\n   // Sieve's prime algorithm\n\n   bool* primecands = new bool[nnodes + 1];\n\n   std::fill_n(primecands, nnodes + 1, true);\n\n   const int sqrn = sqrt(nnodes);\n\n   for( int k = 4; k <= nnodes; k += 2 )\n      primecands[k] = false;\n\n   for( int i = 3; i <= sqrn; i += 2 )\n      if( primecands[i] )\n      {\n         const int currprime = i;\n\n         for( int k = currprime * currprime; k <= nnodes; k += 2 * currprime )\n            primecands[k] = false;\n      }\n\n   if( nnodes >= 2 )\n      graph.makeTerm(1);\n\n   for( int i = 3; i <= nnodes; i += 2 )\n      if( primecands[i] )\n         graph.makeTerm(i - 1);\n\n   delete[] primecands;\n\n}\n\n\nstatic Graph loadGraph(\n   const char* filename\n)\n{\n    std::ifstream file (filename, std::ifstream::in);\n\n    if( file.fail() )\n    {\n       std::cerr << \"file could not be opened\" << std::endl;\n       exit(EXIT_FAILURE);\n    }\n\n    int nnodes;\n    int nedges;\n\n    if( !(file >> nnodes >> nedges) || nedges <= 0 || nnodes <= 1 )\n    {\n        std::cerr << \"file syntax error\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n\n    Graph graph(nnodes, nedges);\n\n    std::string strline;\n\n    using namespace boost::spirit;\n    using qi::int_;\n    using qi::phrase_parse;\n    using ascii::space;\n\n    int etail, ehead;\n    Weight eweight;\n\n    while( std::getline(file, strline) )\n    {\n        auto it = strline.begin();\n\n        bool success = phrase_parse(it, strline.end(),\n                 int_[([&etail](int i){ etail = i; })] >> int_[([&ehead](int i){ ehead = i; })] >> int_[([&eweight](Weight i){ eweight = Weight(i); })]\n                          , space);\n\n        if( success && it == strline.end() )\n           graph.addEdge(etail - 1, ehead - 1, eweight);\n    }\n\n    file.close();\n\n    std::cout << \"loaded graph;\" << \" nodes: \" << nnodes << \", edges: \" << nedges  << \" ... \";\n\n    return graph;\n}\n\n\nint main(\n    int argc,\n    char* argv[]\n)\n{\n    // check number of parameters\n    if( argc != 3 )\n    {\n       // tell the user how to run the program\n       std::cerr << \"Usage: \" << argv[0] << \" filename \" << \"number_of_starting_nodes\"  << std::endl;\n       exit(EXIT_FAILURE);\n    }\n\n    const int nstarts = std::stoi(argv[2]);\n\n    if( nstarts <= 0 )\n    {\n       std::cout << \"number of starting nodes should be >= 1\" << std::endl;\n       exit(EXIT_FAILURE);\n    }\n\n    Graph graph = loadGraph(argv[1]);\n    addTermsPrime(graph);\n\n    std::cout << \"terminals: \" << graph.nterms << std::endl;\n\n    graph.initCompressed();\n    assert(graph.compressedValid());\n\n    if( !graph.isConnected() )\n    {\n       std::cout << \"graph unconnected\" << std::endl;\n       exit(EXIT_FAILURE);\n    }\n\n    const int nedges = graph.nedges;\n    const int nruns = std::min(nstarts, graph.nterms);\n\n    bool* incumbent(new bool[nedges]);\n    int* startterms(new int[graph.nnodes]);\n\n    for( int i = 0, t = 0; t < nruns; i++ )\n       if( graph.isTerm(i) )\n          startterms[t++] = i;\n\n    int bestroot = -1;\n    Weight bestobj = std::numeric_limits<Weight>::max();\n\n\n    using namespace boost::timer;\n    cpu_timer timer;\n\n    // run heuristic from first nruns many terminals (prime nodes)\n    #pragma omp parallel for\n    for( int r = 0; r < nruns; r++ )\n    {\n       const int root = startterms[r];\n\n       assert(graph.isTerm(root));\n\n       std::unique_ptr<bool[]> steinertree = computeSteinerTree(graph, root);\n\n       assert(isTreeValid(graph, steinertree, root));\n\n       Weight obj = Weight(0);\n       for( int e = 0; e < nedges; e++ )\n          if( steinertree[e] )\n             obj += graph.edgeweight[e];\n\n#ifdef _OPENMP\n#pragma omp critical\n       {\n          int t = omp_get_thread_num();\n          int tcount = omp_get_num_threads();\n          std::cout << \"thread \" << t  << \" of \" << tcount << \" finished\" << std::endl;\n       }\n#endif\n\n       #pragma omp critical\n       if( obj < bestobj )\n       {\n          bestobj = obj;\n          bestroot = root;\n          for( int i = 0; i < nedges; i++ )\n             incumbent[i] = steinertree[i];\n       }\n    }\n\n    cpu_times times = timer.elapsed();\n\n    delete[] startterms;\n\n    assert(bestroot >= 0);\n\n    if( !isTreeValid(graph, incumbent, bestroot) )\n       std::cout << \"FAILED WITH FINAL TREE\" << std::endl;\n    else\n       std::cout << \"FINAL TREE OK!\" << std::endl;\n\n    delete[] incumbent;\n    assert(bestobj < std::numeric_limits<Weight>::max());\n\n    std::cout << \"TLEN: \" << bestobj << std::endl;\n    std::cout << \"TIME: \"  << times.user / 1e9 << \" s\" << std::endl;\n    std::cout << \"WALL: \"  << times.wall / 1e9 << \" s\" << std::endl;\n\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "7f78922fef81c0052d447c75b1d7bc4b870e34f7", "size": 15585, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "10_Exercise/ex10.cpp", "max_stars_repo_name": "appfs/appfs", "max_stars_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T11:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T20:25:18.000Z", "max_issues_repo_path": "10_Exercise/ex10.cpp", "max_issues_repo_name": "appfs/appfs", "max_issues_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2017-04-26T09:30:38.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-01T11:31:21.000Z", "max_forks_repo_path": "10_Exercise/ex10.cpp", "max_forks_repo_name": "appfs/appfs", "max_forks_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2017-04-20T16:16:11.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-19T12:53:01.000Z", "avg_line_length": 22.2642857143, "max_line_length": 151, "alphanum_fraction": 0.5330766763, "num_tokens": 4320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.26185388352995903}}
{"text": "//=======================================================================\n// Copyright (c) 2013 Piotr Smulewicz\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 suffix_array.hpp\n * @brief\n * @author Piotr Smulewicz\n * @version 1.0\n * @date 2013-08-29\n */\n#ifndef PAAL_SUFFIX_ARRAY_HPP\n#define PAAL_SUFFIX_ARRAY_HPP\n\n#include \"paal/utils/irange.hpp\"\n\n#include <boost/range/algorithm/fill.hpp>\n#include <boost/range/algorithm/max_element.hpp>\n#include <boost/range/numeric.hpp>\n\n/*\n * algorithm from:\n *\n * http://www.cs.cmu.edu/~guyb/realworld/papersS04/KaSa03.pdf\n *\n */\n\nnamespace paal {\n\nnamespace detail {\n/**\n * @param a1\n * @param a2\n * @param b1\n * @param b2\n * @brief return true if pair (a1,a2) is smaller than pair (b1,b2) in\n * lexicographic order\n * and false otherwise\n * @tparam Letter\n */\n// class suffix_array{\ntemplate <typename Letter>\ninline bool leq(Letter a1, int a2, Letter b1,\n                int b2) { // lexic. order for pairs\n    return (a1 < b1 || (a1 == b1 && a2 <= b2));\n}\n/**\n * @param a1\n * @param a2\n * @param a3\n * @param b1\n * @param b2\n * @param b3\n * @brief return true if triple (a1,a2,a3) is smaller than triple (b1,b2,b3) in\n * lexicographic order\n * and false otherwise\n * @tparam Letter\n */\ntemplate <typename Letter>\ninline bool leq(Letter a1, Letter a2, int a3, Letter b1, Letter b2, int b3) {\n    return (a1 < b1 || (a1 == b1 && leq(a2, a3, b2, b3)));\n}\n\nstruct radix_pass {\n\n    template <typename Letter>\n    radix_pass(int max_letter, const std::vector<Letter> & text) {\n        if (max_letter == 0) {\n            max_letter = *boost::max_element(text);\n        }\n        c.resize(max_letter + 2);\n    }\n\n    // stably sort sortFrom[0..n-1] to sortTo[0..n-1] with keys in 0..K from r\n    template <typename Iterator>\n    void operator()(std::vector<int> const &sortFrom,\n            std::vector<int> &sortTo, Iterator r, int n) { // count occurrences\n        boost::fill(c, 0);\n        for (auto i : irange(n)) {\n            ++c[r[sortFrom[i]] + 1]; // count occurrences\n        }\n\n        boost::partial_sum(c, c.begin());\n\n        for (auto i : irange(n)) {\n            sortTo[c[r[sortFrom[i]]]++] = sortFrom[i]; // sort\n        }\n    }\nprivate:\n    std::vector<int> c;\n};\n\n/**\n *\n * @brief\n * require text[n]=text[n+1]=text[n+2]=0, n>=2\n * fill suffix_array\n * suffix_array[i] contains the starting position of the i-1'th smallest suffix\n* in Word\n * @tparam Letter\n * @param text - text\n * @param SA place for suffix_array\n * @param max_letter optional parameter max_letter in alphabet\n */\n// find the suffix array SA of text[0..n-1] in {1..max_letter}^n\ntemplate <typename Letter>\nvoid suffix_array(std::vector<Letter> &text, std::vector<int> &SA,\n                   Letter max_letter) {\n    int n = text.size() - 3;\n    assert(n >= 0);\n    int n0 = (n + 2) / 3, n1 = (n + 1) / 3, n2 = n / 3, n02 = n0 + n2;\n    text.resize(text.size() + 3);\n    std::vector<int> text12;\n    std::vector<int> SA12;\n    std::vector<int> text0;\n    std::vector<int> SA0;\n    radix_pass radix{max_letter, text};\n    // generate positions of mod 1 and mod  2 suffixes\n    // the \"+(n0-n1)\" adds a dummy mod 1 suffix if n%3 == 1\n    for (auto i : irange(n + (n0 - n1))) {\n        if (i % 3 != 0) {\n            text12.push_back(i);\n        }\n    }\n    SA0.resize(n0);\n    SA12.resize(n02 + 3);\n    text12.resize(n02 + 3);\n    // lsb radix sort the mod 1 and mod 2 triples\n    radix(text12, SA12, text.begin() + 2, n02);\n    radix(SA12, text12, text.begin() + 1, n02);\n    radix(text12, SA12, text.begin(), n02);\n\n    // find lexicographic names of triples\n    int name = 0;\n    Letter c0 = Letter{}, c1 = Letter{}, c2 = Letter{};\n    for (auto i : irange(n02)) {\n        if (text[SA12[i]] != c0 || text[SA12[i] + 1] != c1 ||\n            text[SA12[i] + 2] != c2 || name == 0) {\n            name++;\n            c0 = text[SA12[i]];\n            c1 = text[SA12[i] + 1];\n            c2 = text[SA12[i] + 2];\n        }\n        if (SA12[i] % 3 == 1) {\n            text12[SA12[i] / 3] = name; // left half\n        } else {\n            text12[SA12[i] / 3 + n0] = name; // right half\n        }\n    }\n\n    // recurse if names are not yet unique\n    if (name < n02) {\n        suffix_array<int>(text12, SA12, name); // parametrized by int intentionally\n        // store unique names in s12 using the suffix array\n        for (auto i : irange(n02)) {\n            text12[SA12[i]] = i + 1;\n        }\n    } else { // generate the suffix array of s12 directly\n        for (auto i : irange(n02)) {\n            SA12[text12[i] - 1] = i;\n        }\n    }\n\n    // stably sort the mod 0 suffixes from SA12 by their first character\n    for (auto i : irange(n02)) {\n        if (SA12[i] < n0) {\n            text0.push_back(3 * SA12[i]);\n        }\n    }\n    radix(text0, SA0, text.begin(), n0);\n    auto GetI = [&](int t)->int {\n        return SA12[t] < n0 ? SA12[t] * 3 + 1 : (SA12[t] - n0) * 3 + 2;\n    };\n\n    // merge sorted SA0 suffixes and sorted SA12 suffixes\n    auto p = SA0.begin();\n    int t = n0 - n1;\n    for (auto k = SA.begin(); k < SA.begin() + n; k++) {\n        int i = GetI(t); // pos of current offset 12 suffix\n        int j = (*p);    // pos of current offset 0  suffix\n        if (SA12[t] < n0\n                ? leq(text[i], text12[SA12[t] + n0], text[j], text12[j / 3])\n                : leq(text[i], text[i + 1], text12[SA12[t] - n0 + 1], text[j],\n                      text[j + 1], text12[j / 3 + n0])) { // suffix from SA12 is\n                                                          // smaller\n            (*k) = i;\n            t++;\n            if (t == n02) { // done --- only SA0 suffixes left\n                k++;\n                if (p < SA0.end()) {\n                    k = std::copy(p, SA0.end(), k);\n                    p = SA0.end();\n                }\n            }\n        } else {\n            (*k) = j;\n            p++;\n            if (p == SA0.end()) { // done --- only SA12 suffixes left\n                for (k++; t < n02; t++, k++) {\n                    (*k) = GetI(t);\n                }\n            }\n        }\n    }\n}\n\n}//!detail\n\n\n/**\n *\n * @brief\n * require text.size()>=2\n * fill suffix_array\n * suffix_array[i] contains the starting position of the i-1'th smallest suffix\n* in Word\n * @tparam Letter\n * @param text - text\n * @param SA place for suffix_array\n * @param max_letter optional parameter max_letter in alphabet\n */\n// find the suffix array SA of text[0..n-1] in {1..max_letter}^n\ntemplate <typename Letter>\nvoid suffix_array(std::vector<Letter> &text, std::vector<int> &SA,\n                  Letter max_letter = 0) {\n    text.resize(text.size() + 3);\n    detail::suffix_array(text, SA, max_letter);\n    text.resize(text.size() - 3);\n}\n\n} //!paal\n#endif // PAAL_SUFFIX_ARRAY_HPP\n", "meta": {"hexsha": "b93fc1d99ff7362e9920ac850d5967ad3b255af5", "size": 6928, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/utils/algorithms/suffix_array/suffix_array.hpp", "max_stars_repo_name": "Kommeren/AA", "max_stars_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/paal/utils/algorithms/suffix_array/suffix_array.hpp", "max_issues_repo_name": "Kommeren/AA", "max_issues_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/paal/utils/algorithms/suffix_array/suffix_array.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": 29.3559322034, "max_line_length": 83, "alphanum_fraction": 0.5278579677, "num_tokens": 2108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118791767283, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.2618379183442508}}
{"text": "// Compares two outfiles from phase2, adds appropriate labels\n//#include <boost/algorithm/string/replace.hpp>\n\n#include <iostream>\n#include <cstdlib>\n#include <vector>\n#include <algorithm>\n\n#include <TMath.h>\n#include <TH1.h>\n#include <TH2.h>\n#include <TFile.h>\n#include <TString.h>\n#include <TRegexp.h>\n#include <TGraph.h>\n#include <TGraphErrors.h>\n#include <TMultiGraph.h>\n#include <TProfile.h>\n#include <TCanvas.h>\n#include <TLegend.h>\n#include <TSystem.h>\n#include <TSystemDirectory.h>\n#include <TColor.h>\n#include <TStyle.h>\n#include <TKey.h>\n\n#include \"analysis_params.h\"\n\nint nTriggerPtBins = nJetPtBins;\nstd::vector<double> fTriggerPtBins = jetPtBins;\n\nvoid set_plot_style() {\n    const Int_t NRGBs = 5;\n    const Int_t NCont = 255;\n\n    Double_t stops[NRGBs] = { 0.00, 0.34, 0.61, 0.84, 1.00 };\n    Double_t red[NRGBs]   = { 0.00, 0.00, 0.87, 1.00, 0.51 };\n    Double_t green[NRGBs] = { 0.00, 0.81, 1.00, 0.20, 0.00 };\n    Double_t blue[NRGBs]  = { 0.51, 1.00, 0.12, 0.00, 0.00 };\n    TColor::CreateGradientColorTable(NRGBs, stops, red, green, blue, NCont);\n    gStyle->SetNumberContours(NCont);\n}\n\n\n\nusing namespace std;\n\nstruct fileLabel {\n  fileLabel(TString _filepath, TString _label): filepath(_filepath),label(_label) {}\n  TString filepath;\n  TString label;\n};\n\n/** \n  * Calculates the systematic fractional uncertainty in the tgraphs in the input matrices by using k =1,2, nVersions\n  * trials.  Saves them to the parameter output file\n  */\nvoid  CalculateSystematicUncertaintyN(vector <vector<TGraphErrors * >> tGraphs, TFile * f){\n  // tGraphs expected to be indexed by k = 0,1, .., nVersions, then j = 0,1, .. nJetPtBins\n\tint nModes = tGraphs.size();\n\n  for (int i = 0; i < nTriggerPtBins; i++) {\n    int n;\n    TGraph * SysErr;\n    n = tGraphs[0][i]->GetN();\n    SysErr = new TGraph(n);\n    SysErr->SetName(Form(\"%s_SysUncert\",tGraphs[0][i]->GetName()));\n    for (int j = 0; j < n; j++) {\n      double sumOfSquares = 0;\n      double sum = 0;\n      double x = 0;\n      double y;\n      for (int k = 0; k < nModes; k++) {\n        y=0;\n        tGraphs[k][i]->GetPoint(j,x,y);\n        sumOfSquares += y*y;\n        sum += y;\n      }\n\t\t\t//y = sum / nModes;// New Fix\n\t\t\ttGraphs[0][i]->GetPoint(j,x,y); // Newer Fix, use the first value as the primary value to be reported.\n      if (y != 0) SysErr->SetPoint(j,x,(sqrt((sumOfSquares - sum*sum/(nModes))/(nModes-1))/abs(y))); \n    }\n    f->Add(SysErr);\n  }\n\n}\n\n\n\nvoid cleanName(TString &str) {\n\t\tstr.ReplaceAll(\" \",\"_\");\n\t\tstr.ReplaceAll(\"%\",\"_\");\n\t\tstr.ReplaceAll(\"#\",\"_\");\n\t\tstr.ReplaceAll(\",\",\"_\");\n\t\tstr.ReplaceAll(\"-\",\"_\");\n\t\tstr.ReplaceAll(\"=\",\"_\");\n}\n\nvector <vector<TGraphErrors * >> extractTGraphArray(TString name, vector<TFile *> * files) {\n\n\tint nModes = files->size();\n\tvector <vector<TGraphErrors * >> tGraphArray;// = new vector <vector<TGraphErrors * >>;\n\n\tfor (int k = 0; k < nModes; k++) {\n\t\tTFile * f1 = files->at(k);\n\n\t\tvector<TGraphErrors *> tGraphSubArray;\n\t\tfor (int i = 0; i < nTriggerPtBins; i++) {\n\t\t\tTGraphErrors * tGraph = (TGraphErrors *) f1->Get(Form(name,fTriggerPtBins.at(i), fTriggerPtBins.at(i+1)));\n\t\t\tif (!tGraph) {\n\t\t\t\tfprintf(stderr,\"Error: Could not find %s\\n\",Form(name,fTriggerPtBins.at(i),fTriggerPtBins.at(i+1)));\n\t\t\t\texit(1);\n\t\t\t}\n//\t\t\tprintf(\"Found %s in file %s\\n\",tGraph->GetName(),f1->GetTitle());\n\t\t\ttGraphSubArray.push_back(tGraph);\n\t\t}\n\t\ttGraphArray.push_back(tGraphSubArray);\n\t}\n\t\n\treturn tGraphArray;\n}\n\n\n\nconst Int_t nTypeList = 9;\n\nvoid calcSystUncert(vector<fileLabel> *fileLabels, char * fSystematicUncertOutFilePath)  {\n\n\n  Int_t colorList[nTypeList] = {kBlack,kRed,kOrange-3,kGreen-3,kBlue,kViolet,kMagenta-5,kRed-10,kGray};\n  Int_t markerList[nTypeList] = {kFullSquare,kFullCircle,kFullDiamond,kOpenSquare,kOpenCircle,kOpenDiamond,kFullStar,23,34};\n\n  double c_width = 600;\n  double c_height = 600;\n\n\n\tTFile * fSystematicUncertOutFile = TFile::Open(fSystematicUncertOutFilePath,\"RECREATE\");\n\tif (!fSystematicUncertOutFile) {\n\t\tfprintf(stderr,\"Error: Unable to open systematic error output file!\\n\");\n\t\texit(1);\n\t}\n\n\n  vector<TFile *> *files = new vector<TFile *>;\n\n  for (int i = 0 ; i < fileLabels->size(); i++ ) {\n    fileLabel fl = fileLabels->at(i);\n    printf(\"Opening File %s [%s] ... \\n\",fl.filepath.Data(),fl.label.Data());  \n    TFile *f = TFile::Open(fl.filepath.Data(),\"READ\");\n    if (!f) {\n      fprintf(stderr,\"Error: file %s not found!\\nExiting.\\n\",fl.filepath.Data());\n      exit(1);\n    }\n\t\tTString nameNoSpace  = fl.label;\n\t\tcleanName(nameNoSpace);\n//\t\tprintf(\"MHO nameNoSpace = %s\\n\",nameNoSpace.Data());\n    f->SetTitle(fl.label.Data());\n\t\tf->SetName(nameNoSpace);\n    files->push_back(f);\n    \n    printf(\"file %s, title %s\\n\",f->GetName(),f->GetTitle());\n\n  }\n\n  if ( !files->size()) exit(0);\n  TFile *f0 = files->at(0);\n   \n  TCanvas *canvas = new TCanvas(\"canvas\",\"canvas\",c_width,c_height);\n  gStyle->SetOptStat(0);\n\n\t// Need to construct arrays of objects, with an arbitrary first index,\n  // second index is jetpt\n\n\tint iTrigger = 0; // 0 for jet, 1 for pi0Pt, 2 for pi0Zt\n\n  TString jetClass = \"jetPt_%.0f_%.0f\";\n\n\tTString triggerClass = jetClass;\n\n\tif (iTrigger > 0) {\n\t\ttriggerClass = \"pi0Pt_%.0f_%.0f\";\n\t\tnTriggerPtBins = nPi0PtBins;\n\t\tfTriggerPtBins = pi0PtBins;\n\t}\n\n\tvector <vector<TGraphErrors * >> ptBinASIntegralsGraphsEP_0 = extractTGraphArray(triggerClass + \"_EP_0_AS_Integrals\", files);\n\tvector <vector<TGraphErrors * >> ptBinASIntegralsGraphsEP_1 = extractTGraphArray(triggerClass + \"_EP_1_AS_Integrals\", files);\n\tvector <vector<TGraphErrors * >> ptBinASIntegralsGraphsEP_2 = extractTGraphArray(triggerClass + \"_EP_2_AS_Integrals\", files);\n\tvector <vector<TGraphErrors * >> ptBinASIntegralsGraphsEP_3 = extractTGraphArray(triggerClass + \"_EP_3_AS_Integrals\", files);\n\n\tCalculateSystematicUncertaintyN(ptBinASIntegralsGraphsEP_0,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(ptBinASIntegralsGraphsEP_1,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(ptBinASIntegralsGraphsEP_2,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(ptBinASIntegralsGraphsEP_3,fSystematicUncertOutFile);\n\n\n\tvector <vector<TGraphErrors * >> ptBinNSIntegralsGraphsEP_0 = extractTGraphArray(triggerClass + \"_EP_0_NS_Integrals\", files);\n\tvector <vector<TGraphErrors * >> ptBinNSIntegralsGraphsEP_1 = extractTGraphArray(triggerClass + \"_EP_1_NS_Integrals\", files);\n\tvector <vector<TGraphErrors * >> ptBinNSIntegralsGraphsEP_2 = extractTGraphArray(triggerClass + \"_EP_2_NS_Integrals\", files);\n\tvector <vector<TGraphErrors * >> ptBinNSIntegralsGraphsEP_3 = extractTGraphArray(triggerClass + \"_EP_3_NS_Integrals\", files);\n\t\n\tCalculateSystematicUncertaintyN(ptBinNSIntegralsGraphsEP_0,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(ptBinNSIntegralsGraphsEP_1,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(ptBinNSIntegralsGraphsEP_2,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(ptBinNSIntegralsGraphsEP_3,fSystematicUncertOutFile);\n\n\n\tvector <vector<TGraphErrors * >> ptBinASYieldsGraphsEP_0 = extractTGraphArray(triggerClass + \"_EP_0_AS_Yields\", files);\n\tvector <vector<TGraphErrors * >> ptBinASYieldsGraphsEP_1 = extractTGraphArray(triggerClass + \"_EP_1_AS_Yields\", files);\n\tvector <vector<TGraphErrors * >> ptBinASYieldsGraphsEP_2 = extractTGraphArray(triggerClass + \"_EP_2_AS_Yields\", files);\n\tvector <vector<TGraphErrors * >> ptBinASYieldsGraphsEP_3 = extractTGraphArray(triggerClass + \"_EP_3_AS_Yields\", files);\n\n\tCalculateSystematicUncertaintyN(ptBinASYieldsGraphsEP_0,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(ptBinASYieldsGraphsEP_1,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(ptBinASYieldsGraphsEP_2,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(ptBinASYieldsGraphsEP_3,fSystematicUncertOutFile);\n\n\n\tvector <vector<TGraphErrors * >> ptBinASRmsGraphsEP_0 = extractTGraphArray(triggerClass + \"_EP_0_AS_Rms\", files);\n\tvector <vector<TGraphErrors * >> ptBinASRmsGraphsEP_1 = extractTGraphArray(triggerClass + \"_EP_1_AS_Rms\", files);\n\tvector <vector<TGraphErrors * >> ptBinASRmsGraphsEP_2 = extractTGraphArray(triggerClass + \"_EP_2_AS_Rms\", files);\n\tvector <vector<TGraphErrors * >> ptBinASRmsGraphsEP_3 = extractTGraphArray(triggerClass + \"_EP_3_AS_Rms\", files);\n\n\tCalculateSystematicUncertaintyN(ptBinASRmsGraphsEP_0,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(ptBinASRmsGraphsEP_1,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(ptBinASRmsGraphsEP_2,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(ptBinASRmsGraphsEP_3,fSystematicUncertOutFile);\n\n\n\tvector <vector<TGraphErrors * >> ptBinNSRmsGraphsEP_0 = extractTGraphArray(triggerClass + \"_EP_0_NS_Rms\", files);\n\tvector <vector<TGraphErrors * >> ptBinNSRmsGraphsEP_1 = extractTGraphArray(triggerClass + \"_EP_1_NS_Rms\", files);\n\tvector <vector<TGraphErrors * >> ptBinNSRmsGraphsEP_2 = extractTGraphArray(triggerClass + \"_EP_2_NS_Rms\", files);\n\tvector <vector<TGraphErrors * >> ptBinNSRmsGraphsEP_3 = extractTGraphArray(triggerClass + \"_EP_3_NS_Rms\", files);\n\t\n\tCalculateSystematicUncertaintyN(ptBinNSRmsGraphsEP_0,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(ptBinNSRmsGraphsEP_1,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(ptBinNSRmsGraphsEP_2,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(ptBinNSRmsGraphsEP_3,fSystematicUncertOutFile);\n\n\n\tvector <vector<TGraphErrors * >> ptBinASWidthsGraphsEP_0 = extractTGraphArray(triggerClass + \"_EP_0_AS_Widths\", files);\n\tvector <vector<TGraphErrors * >> ptBinASWidthsGraphsEP_1 = extractTGraphArray(triggerClass + \"_EP_1_AS_Widths\", files);\n\tvector <vector<TGraphErrors * >> ptBinASWidthsGraphsEP_2 = extractTGraphArray(triggerClass + \"_EP_2_AS_Widths\", files);\n\tvector <vector<TGraphErrors * >> ptBinASWidthsGraphsEP_3 = extractTGraphArray(triggerClass + \"_EP_3_AS_Widths\", files);\n\n\tCalculateSystematicUncertaintyN(ptBinASWidthsGraphsEP_0,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(ptBinASWidthsGraphsEP_1,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(ptBinASWidthsGraphsEP_2,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(ptBinASWidthsGraphsEP_3,fSystematicUncertOutFile);\n\n\n\n\t// Now doing the Ratios \n\tvector <vector<TGraphErrors * >> OutOverIn_AS = extractTGraphArray(\"OutOverIn_AS_\" + triggerClass, files);\n\tvector <vector<TGraphErrors * >> MidOverIn_AS = extractTGraphArray(\"MidOverIn_AS_\" + triggerClass, files);\n\tvector <vector<TGraphErrors * >> OutOverIn_NS = extractTGraphArray(\"OutOverIn_NS_\" + triggerClass, files);\n\tvector <vector<TGraphErrors * >> MidOverIn_NS = extractTGraphArray(\"MidOverIn_NS_\" + triggerClass, files);\n\tvector <vector<TGraphErrors * >> OutOverInPar_AS = extractTGraphArray(\"OutOverInPar_AS_\" + triggerClass, files);\n\tvector <vector<TGraphErrors * >> MidOverInPar_AS = extractTGraphArray(\"MidOverInPar_AS_\" + triggerClass, files);\n\n\tCalculateSystematicUncertaintyN(OutOverIn_AS,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(MidOverIn_AS,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(OutOverIn_NS,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(MidOverIn_NS,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(OutOverInPar_AS,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(MidOverInPar_AS,fSystematicUncertOutFile);\n\n\n\tvector <vector<TGraphErrors * >> OutMinusIn_AS = extractTGraphArray(\"OutMinusIn_AS_\" + triggerClass, files);\n\tvector <vector<TGraphErrors * >> MidMinusIn_AS = extractTGraphArray(\"MidMinusIn_AS_\" + triggerClass, files);\n\tvector <vector<TGraphErrors * >> OutMinusIn_NS = extractTGraphArray(\"OutMinusIn_NS_\" + triggerClass, files);\n\tvector <vector<TGraphErrors * >> MidMinusIn_NS = extractTGraphArray(\"MidMinusIn_NS_\" + triggerClass, files);\n\n\tCalculateSystematicUncertaintyN(OutMinusIn_AS,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(MidMinusIn_AS,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(OutMinusIn_NS,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(MidMinusIn_NS,fSystematicUncertOutFile);\n\n\tvector <vector<TGraphErrors * >> RMSOutOverIn_AS = extractTGraphArray(\"RMSOutOverIn_AS_\" + triggerClass, files);\n\tvector <vector<TGraphErrors * >> RMSMidOverIn_AS = extractTGraphArray(\"RMSMidOverIn_AS_\" + triggerClass, files);\n\tvector <vector<TGraphErrors * >> RMSOutOverIn_NS = extractTGraphArray(\"RMSOutOverIn_NS_\" + triggerClass, files);\n\tvector <vector<TGraphErrors * >> RMSMidOverIn_NS = extractTGraphArray(\"RMSMidOverIn_NS_\" + triggerClass, files);\n\n\tCalculateSystematicUncertaintyN(RMSOutOverIn_AS,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(RMSMidOverIn_AS,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(RMSOutOverIn_NS,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(RMSMidOverIn_NS,fSystematicUncertOutFile);\n\n\n\t// FIXME add width ratios?\n\tvector <vector<TGraphErrors * >> WidthsOutOverIn_AS = extractTGraphArray(\"WidthsOutOverIn_AS_\" + triggerClass, files);\n\tvector <vector<TGraphErrors * >> WidthsMidOverIn_AS = extractTGraphArray(\"WidthsMidOverIn_AS_\" + triggerClass, files);\n\n\tCalculateSystematicUncertaintyN(WidthsOutOverIn_AS,fSystematicUncertOutFile);\n\tCalculateSystematicUncertaintyN(WidthsMidOverIn_AS,fSystematicUncertOutFile);\n\n// MidOverIn_AS_pi0Pt\n\n  /*\n  vector <vector<TGraphErrors *> > ptBinASWidthsGraphsEP;\n  vector <vector<TGraphErrors *> > ptBinASRmsGraphsEP;\n  vector <vector<TGraphErrors *> > ptBinASIntegralsGraphsEP;\n  vector <vector<TGraphErrors *> > ptBinASFwhmGraphsEP;\n  vector <vector<TGraphErrors *> > ptBinASFwhmRescaledGraphsEP;\n  vector <vector<TGraphErrors *> > ptBinASYieldsGraphsEP;\n*/\n \n\tfSystematicUncertOutFile->Write();\n\n\tprintf(\"Finished calculating systematic uncertainties for integrals,yields,rms,width\\n\");\n\n}\n\nint main(int argc, char * argv[]) {\n\n  if (argc < 3) {\n    printf(\"Usage: %s <SystematicUncertaintyRootFile> [Filepath_1] [Label_1] [Filepath_2] [Label_2] ... \\n\",argv[0]);\n//    printf(\"    Or %s -p [PATTERN] [Filepath_1] [Label_1] [Filepath_2] [Label_2] ... \\n\",argv[0]);\n    exit(0);\n  }\n\n\n\n  int num = ((argc) / 2) ;\n  vector<fileLabel> *fileLabels = new vector<fileLabel>;\n  for (int i = 1; i < num; i++) {\n    fileLabels->push_back(fileLabel(TString(argv[2*i]),TString(argv[2*i+1])));\n  }\n\tprintf(\"Starting calculation of systematic uncertainties using files:\");\n\tfor (int i = 0; i < num - 1 ; i++) {\n\t\tprintf(\"%s \",fileLabels->at(i).filepath.Data());\n\t}\n\tprintf(\"\\n\");\n  calcSystUncert(fileLabels,argv[1]);\n}\n\n\n\n\n", "meta": {"hexsha": "d41a4056cda77701092587afe33e1e1778053d0a", "size": 14460, "ext": "cc", "lang": "C++", "max_stars_repo_path": "analysis/calcSystUncert.cc", "max_stars_repo_name": "moliver813/MyEventGeneratorCode", "max_stars_repo_head_hexsha": "31c4e82c7f8d2f7fb66af8b1ef32226dafd76e11", "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": "analysis/calcSystUncert.cc", "max_issues_repo_name": "moliver813/MyEventGeneratorCode", "max_issues_repo_head_hexsha": "31c4e82c7f8d2f7fb66af8b1ef32226dafd76e11", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "analysis/calcSystUncert.cc", "max_forks_repo_name": "moliver813/MyEventGeneratorCode", "max_forks_repo_head_hexsha": "31c4e82c7f8d2f7fb66af8b1ef32226dafd76e11", "max_forks_repo_licenses": ["BSD-3-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.5294117647, "max_line_length": 126, "alphanum_fraction": 0.7584370678, "num_tokens": 4400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.2617899998530847}}
{"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/make_maximal_planar.hpp>\n#include <boost/graph/make_biconnected_planar.hpp>\n#include <boost/graph/boyer_myrvold_planar_test.hpp>\n\nusing namespace std;\nusing namespace boost;\nusing namespace graph_tool;\n\nstruct mark_planar_edge\n{\n    template <typename Graph, typename Vertex>\n    void visit_vertex_pair(Vertex u, Vertex v, Graph& g)\n    {\n        if (!is_adjacent(u, v, g))\n            add_edge(u, v, g);\n    }\n};\n\nstruct do_maximal_planar\n{\n    template <class Graph, class VertexIndex, class EdgeIndex>\n    void operator()(Graph& g, VertexIndex vertex_index, EdgeIndex edge_index) const\n    {\n\n        unchecked_vector_property_map\n            <vector<typename graph_traits<Graph>::edge_descriptor>, VertexIndex>\n            embedding(vertex_index, num_vertices(g));\n        bool 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\n        if (!is_planar)\n            throw GraphException(\"Graph is not planar!\");\n\n        mark_planar_edge vis;\n        make_biconnected_planar(g, embedding, edge_index, vis);\n        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        make_maximal_planar(g, embedding, vertex_index, edge_index, vis);\n    }\n\n};\n\n\nvoid maximal_planar(GraphInterface& gi)\n{\n    run_action<graph_tool::detail::never_directed, mpl::true_>()\n        (gi, std::bind(do_maximal_planar(), placeholders::_1, gi.GetVertexIndex(),\n                       gi.GetEdgeIndex()))();\n}\n", "meta": {"hexsha": "8f1d42eca308ee05a4011d4082816644b578cb4c", "size": 2594, "ext": "cc", "lang": "C++", "max_stars_repo_path": "graph-tool/src/graph/topology/graph_maximal_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_maximal_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_maximal_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": 34.5866666667, "max_line_length": 83, "alphanum_fraction": 0.7031611411, "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.26176483855874827}}
{"text": "///\n/// \\file\n///  \\author Hao Li hao.li@live.co.uk \n///  \\version 1.0\n///  \\date 2017\n///  \\pre OpenCV and Boost libraries\n///\n\n#include \"Detection.h\"\n#include <iostream>\n#include <vector>\n#include <math.h>\n#include <deque>\n#include <numeric>\n#include <algorithm>\n#include <functional>\n#include <boost/foreach.hpp>\n#include <boost/lexical_cast.hpp>\n#include \"Utils/Exception.h\"\n#include \"Serialisation/json.h\"\n\nusing namespace std;\nusing namespace cv;\n\nnamespace {\n\tclass LessRegion : public unary_function<vector<Point>, bool>\n    {\n    public:\n        LessRegion(int minWidth, int minHeight): m_area(minWidth*minHeight) {}\n        bool operator()(const vector<Point>& val) const\n        {\n            return static_cast<int>(val.size()) < m_area;\n        }\n\n    private:\n        int m_area;\n    };\n}\n\nnamespace FG {\n    /// Struct definition of GMM based background model\n    class CGmmModelParam\n    {\n    public:\n        // Tuning parameters\n        int     m_windowSize;                ///< reciprocal of update rate (300-600)\n        int     m_numberGmm;                 ///< number of Gaussians (3-5)\n        float   m_stdThreshold;              ///< define in normal Gaussian distribution (mu-std_thre < x < mu+std_thre), m_stdThreshold = 2.5 means 99% included\n        float   m_bgThreshold;               ///< threshold of weight sum (0.8-0.9)\n        float   m_gradientThreshold;         ///< threshold for pixel gradient similarity measurement (0.7-0.9)\n        float   m_shadowBrightThreshold;     ///< threshold for shadow brightness distortion (0.7-0.9)\n        float   m_highlightThreshold;        ///< threshold for sudden lighting change (1.1-1.3)\n        int     m_globalUpdateRate;          ///< update rate for non-moving regions (5-10)\n        int     m_minRegionWidth;            ///< minimum foreground width (5-10) for removing small regions\n        int     m_minRegionHeight;           ///< minimum foreground height (10-20)\n\n        // Fixed parameters\n        float   m_initSigma2;                ///< Square of standard deviation for each cluster (10)\n        float   m_supportRate;               ///< percentage of samples that supports an existed cluster (0.05)\n        float   m_shadowChromaThreshold;     ///< threshold for shadow chroma distortion (3.0)\n        int     m_gridSize;                  ///< grid size for coarse FG mask generation\n        int     m_medfiltSize;               ///< size of 2D median filter\n    };\n        \n    /// CGmmBgModelParam implementation details\n    class CGmmBgModelParam::Impl\n    {\n    public:\n        /// helper to set default BgModelParam\n        void BgModelParamDefault()\n        {\n            m_param.m_windowSize = 300;\n            m_param.m_numberGmm = 3;\n            m_param.m_stdThreshold = 3;\n            m_param.m_bgThreshold = 0.90f;\n            m_param.m_gradientThreshold = 0.80f;\n            m_param.m_shadowBrightThreshold = 0.70f;\n            m_param.m_highlightThreshold = 1.20f;\n            m_param.m_globalUpdateRate = 10;\n            m_param.m_minRegionWidth = 5;\n            m_param.m_minRegionHeight = 10;\n            m_param.m_initSigma2 = 10;\n            m_param.m_supportRate = 0.05f;\n            m_param.m_shadowChromaThreshold = 3.0f;\n            m_param.m_gridSize = 4;\n            m_param.m_medfiltSize = 7;\n        }\n\n\t\tvoid BgModelParamFromConfig(const string& configFile)\n\t\t{\n\t\t\tCREQUIRE(!configFile.empty(), \"No configuration file specified\");\n\n\t\t\tJson::Reader reader;\n\t\t\tJson::Value root;\n\t\t\tstd::ifstream ifs(configFile.c_str());\n\t\t\tCREQUIRE(ifs.is_open(), \"Error opening configuration file: \" + configFile);\n\t\t\tCREQUIRE(reader.parse(ifs, root), \"Error parsing configuration file: \" + reader.getFormattedErrorMessages());\n\n\t\t\tconst auto& config = root[\"ForegroundDetection\"];\n\t\t\tconst auto& preGmm = config[\"Preprocessing\"];\n\t\t\tconst auto& gmm = config[\"GMM\"];\n\t\t\tconst auto& postGmm = config[\"Postprocessing\"];\n\t\t\tm_param.m_gradientThreshold = preGmm[\"GradientThreshold\"].asFloat();\n\t\t\tm_param.m_globalUpdateRate = preGmm[\"GlobalUpdateRate\"].asInt();\n\t\t\tm_param.m_gridSize = preGmm[\"GridSize\"].asInt();\n\t\t\tm_param.m_windowSize = gmm[\"WindowSize\"].asInt();\n\t\t\tm_param.m_numberGmm = gmm[\"NumberGmms\"].asInt();\n\t\t\tm_param.m_stdThreshold = gmm[\"StdThreshold\"].asFloat();\n\t\t\tm_param.m_initSigma2 = gmm[\"InitSigma2\"].asFloat();\n\t\t\tm_param.m_bgThreshold = gmm[\"BackgroundThreshold\"].asFloat();\n\t\t\tm_param.m_supportRate = gmm[\"SupportRate\"].asFloat();\n\t\t\tm_param.m_shadowBrightThreshold = postGmm[\"ShadowBrightThreshold\"].asFloat();\n\t\t\tm_param.m_shadowChromaThreshold = postGmm[\"ShadowChromaThreshold\"].asFloat();\n\t\t\tm_param.m_highlightThreshold = postGmm[\"HighlightThreshold\"].asFloat();\n\t\t\tm_param.m_minRegionWidth = postGmm[\"MinRegionWidth\"].asInt();\n\t\t\tm_param.m_minRegionHeight = postGmm[\"MinRegionHeight\"].asInt();\n\t\t\tm_param.m_medfiltSize = postGmm[\"MedianFilterSize\"].asInt();\n\t\t}\n\n        CGmmModelParam m_param;\n    };\n\n\n    CGmmBgModelParam::CGmmBgModelParam() : m_impl(new CGmmBgModelParam::Impl())\n    {\n        m_impl->BgModelParamDefault ();\n    }\n\n    CGmmBgModelParam::CGmmBgModelParam (const std::string& configFile) : m_impl(new CGmmBgModelParam::Impl())\n    {\n\t\tm_impl->BgModelParamFromConfig(configFile);\n    }\n\n    // Get all background model parameters\n    int     CGmmBgModelParam::WindowSize() const                 {return m_impl->m_param.m_windowSize;}\n    int     CGmmBgModelParam::NumberGmm() const                  {return m_impl->m_param.m_numberGmm;}\n    float   CGmmBgModelParam::StdThreshold() const               {return m_impl->m_param.m_stdThreshold;}\n    float   CGmmBgModelParam::BgThreshold() const                {return m_impl->m_param.m_bgThreshold;}\n    float   CGmmBgModelParam::GradientThreshold() const          {return m_impl->m_param.m_gradientThreshold;}\n    float   CGmmBgModelParam::ShadowBrightThreshold() const      {return m_impl->m_param.m_shadowBrightThreshold;}\n    float   CGmmBgModelParam::HighlightThreshold() const         {return m_impl->m_param.m_highlightThreshold;}\n    int     CGmmBgModelParam::GlobalUpdateRate() const           {return m_impl->m_param.m_globalUpdateRate;}\n    int     CGmmBgModelParam::MinRegionWidth() const             {return m_impl->m_param.m_minRegionWidth;}\n    int     CGmmBgModelParam::MinRegionHeight() const            {return m_impl->m_param.m_minRegionHeight;}\n    float   CGmmBgModelParam::InitSigma2() const                 {return m_impl->m_param.m_initSigma2;} \n    float   CGmmBgModelParam::SupportRate() const                {return m_impl->m_param.m_supportRate;}\n    float   CGmmBgModelParam::ShadowChromaThreshold() const      {return m_impl->m_param.m_shadowChromaThreshold;}\n    int     CGmmBgModelParam::GridSize() const                   {return m_impl->m_param.m_gridSize;}\n    int     CGmmBgModelParam::MedfiltSize() const                {return m_impl->m_param.m_medfiltSize;}\n\n\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n     \n    /// CGmmBgModel implementation details\n    class CGmmBgModel::Impl\n    {\n    public:\n\n        /// Store GMM information at each pixel position\n        class CGmmInfo\n        {\n        public:\n            long m_matchCout;\t\t\t\t///< number of match times, used before window size reaches predefined value\n            float m_updateRate;\t\t///< update rate of current pixel location, can be changed through process\n            float m_weight;\t\t\t\t\t///<weight of each Gaussian cluster\n            float m_mu[CGmmBgModel::GMM_DIMENSION];\t\t///<store mu of each color channel\n            float m_sigma2[CGmmBgModel::GMM_DIMENSION];\t///<store Sigma of each color channel\n        };\n\n        /// Store GMM information of the model \n        class CGmmPixelInfo\n        {\n        public:\n            int M;      ///< number of Gaussian used in current pixel position\n            CGmmInfo* m_info;\n        };\n\n        /// Hold grid based coarse foreground detection results\n        class CGmmTempInfo\n        {\n        public:\n            shared_ptr<Mat> m_frameGray;\n\t\t\tshared_ptr<Mat> m_backgroundGray;\n\t\t\tshared_ptr<Mat> m_frameGradientX;\n\t\t\tshared_ptr<Mat> m_frameGradientY;\n\t\t\tshared_ptr<Mat> m_backgroundGradientX;\n\t\t\tshared_ptr<Mat> m_backgroundGradientY;\n\t\t\tshared_ptr<Mat> m_frameGradientMag;\n\t\t\tshared_ptr<Mat> m_frameGradientMag2;\n\t\t\tshared_ptr<Mat> m_backgroundGradientMag;\n\t\t\tshared_ptr<Mat> m_backgroundGradientMag2;\n\t\t\tshared_ptr<Mat> m_gradientDotProduct;\n\t\t\tshared_ptr<Mat> m_temp1;\n\t\t\tshared_ptr<Mat> m_temp2;\n\n        };\n\n        /// Calculate similarity gradient mask\n        void SgMaskCalculation(const Mat& frame)\n        {\n            int gradSize = m_param.GridSize();\n            int channels = frame.channels();\n            if (channels == 3)  // covert to gray scale\n            {\n                cvtColor (frame, *mpTempInfo->m_frameGray, CV_BGR2GRAY);\n                cvtColor (*mpBackground, *mpTempInfo->m_backgroundGray, CV_BGR2GRAY);\n            }\n            else    // store to temporal place\n            {\n                frame.copyTo(*mpTempInfo->m_frameGray);\n                mpBackground->copyTo(*mpTempInfo->m_backgroundGray);\n            }\n                \n            // calculate the image derivatives using sobel filter\n            // TODO gpu::GpuMat to accrelate speed\n            Sobel (*mpTempInfo->m_frameGray, *mpTempInfo->m_frameGradientX, CV_32F, 1, 0, 3, 1.0/8);    //scaling\n            Sobel (*mpTempInfo->m_frameGray, *mpTempInfo->m_frameGradientY, CV_32F, 0, 1, 3, 1.0/8);\n            Sobel (*mpTempInfo->m_backgroundGray, *mpTempInfo->m_backgroundGradientX, CV_32F, 1, 0, 3, 1.0/8);\n            Sobel (*mpTempInfo->m_backgroundGray, *mpTempInfo->m_backgroundGradientY, CV_32F, 0, 1, 3, 1.0/8);\n\n            // find the square of magnitude of gradient\n            multiply(*mpTempInfo->m_frameGradientX, *mpTempInfo->m_frameGradientX, *mpTempInfo->m_temp1);\n            multiply(*mpTempInfo->m_frameGradientY, *mpTempInfo->m_frameGradientY, *mpTempInfo->m_temp2);\n            add (*mpTempInfo->m_temp1, *mpTempInfo->m_temp2, *mpTempInfo->m_frameGradientMag2);\n            multiply(*mpTempInfo->m_backgroundGradientX, *mpTempInfo->m_backgroundGradientX, *mpTempInfo->m_temp1);\n            multiply(*mpTempInfo->m_backgroundGradientY, *mpTempInfo->m_backgroundGradientY, *mpTempInfo->m_temp2);\n            add (*mpTempInfo->m_temp1, *mpTempInfo->m_temp2, *mpTempInfo->m_backgroundGradientMag2);\n\n            Size fsize = frame.size();\n            // calculate the dot product and magnitude of gradient;\n            float* pGradientDotProduct = mpTempInfo->m_gradientDotProduct->ptr<float>();\n            float* pBackgroundGradientX =  mpTempInfo->m_backgroundGradientX->ptr<float>();\n            float* pBackgroundGradientY = mpTempInfo->m_backgroundGradientY->ptr<float>();\n            float* pFrameGradientMag = mpTempInfo->m_frameGradientMag->ptr<float>();\n            float* pFrameGradientMag2 = mpTempInfo->m_frameGradientMag2->ptr<float>();\n            float* pBackgroundGradientMag = mpTempInfo->m_backgroundGradientMag->ptr<float>();\n            float* pBackgroundGradientMag2 = mpTempInfo->m_backgroundGradientMag2->ptr<float>();\n            for (int i = 0, n = 0; i < fsize.height; ++i)\n            {\n                for (int j = 0; j < fsize.width; ++j, ++n)\n                {\n                    // dot product\n                    pGradientDotProduct[n] = pBackgroundGradientX[n]*pBackgroundGradientX[n] + pBackgroundGradientY[n]*pBackgroundGradientY[n];\n                    // gradient\n                    pFrameGradientMag[n] = sqrt(pFrameGradientMag2[n]);\n                    pBackgroundGradientMag[n] = sqrt(pBackgroundGradientMag2[n]);\n                }\n            }\n\n            //Scalar_<float> frameGradientMean = mean(*mpTempInfo->m_frameGradientMag);\n            //Scalar_<float> backgroundGradientMean = mean(*mpTempInfo->m_backgroundGradientMag);\n            //cout << \"\\\"\" << frameGradientMean(0) << \" \" << backgroundGradientMean(0) << \"\\\"\";\n            // calculate similarity mask SgMask == 1 for gradient dissimilar regions, 0 for similar regions and gradient homogeneous regions\n            int gridSize = m_param.GridSize ();\n            //int nElems = gridSize*gridSize;\n            uchar* pSgMask = mpSgMask->ptr<uchar>();\n            for (int i = 0, n = 0; i < fsize.height/gridSize; ++i)\n            {\n                for (int j = 0; j < fsize.width/gridSize; ++j, ++n)\n                {\n                    float sum1 = 0.0f;\n                    float sum2 = 0.0f;\n                    //float sum3 = 0.0f;  /// mean of magnitude of each grid in frame\n                    //float sum4 = 0.0f;  /// mean of magnitude of each grid in background\n                    for (int x = 0; x < gridSize; ++x)\n                    {\n                        for (int y = 0; y < gridSize; ++y)\n                        {\n                            int index = (i*gridSize+x)*fsize.width+j*gridSize+y;\n                            //sum1 += 2*mpTempInfo->m_gradientDotProduct->at<float>(i*gridSize+x, j*gridSize+y);\n                            //sum2 += mpTempInfo->m_frameGradientMag2->at<float>(i*gridSize+x, j*gridSize+y) + mpTempInfo->m_backgroundGradientMag2->at<float>(i*gridSize+x, j*gridSize+y);\n                            sum1 += 2*pGradientDotProduct[index];\n                            sum2 += pFrameGradientMag2[index]+pBackgroundGradientMag2[index];\n                            //sum3 += pFrameGradientMag[n];\n                            //sum4 += pBackgroundGradientMag[n];\n                        }\n                    }\n\n                    //sum3 /= nElems;\n                    //sum4 /= nElems;\n\n                    //float thres = 0.5f; /// to remove homogeneous regions\n                    if (/*(sum3 > thres || sum4 > thres) && */sum1/sum2 < m_param.GradientThreshold ())\n                    {\n                        pSgMask[n] = static_cast<uchar>(255);\n                    } else\n                    {\n                        pSgMask[n] = static_cast<uchar>(0);\t//TODO\n                    }\n\n                }\n            }\n\n        }\n\n        /// Coarse foreground detection based on single Gaussian model\n        void CoarseForegroundDetection(const Mat& frame)\n        {\n            Size fsize = frame.size();\n            int channels = frame.channels ();\n            int gridSize = m_param.GridSize ();\n            int nElems = gridSize*gridSize;\n            float stdThres = m_param.StdThreshold ();\n            const uchar* pdata = frame.ptr<uchar>();\n            uchar* pCFMaskS = mpCFMaskS->ptr<uchar>();\n            float* pCBMu = mpCBMu->ptr<float>();\n            float* pCBSigma2 = mpCBSigma2->ptr<float>();\n            float* pCFMu = mpCFMu->ptr<float>(); \n            // Gaussian based detection\n            for (int i = 0, n = 0; i < fsize.height/gridSize; ++i)\n            {\n                for (int j = 0; j < fsize.width/gridSize; ++j, ++n)\n                {\n                    float sumCBMu[CGmmBgModel::GMM_DIMENSION] = {0.0f};\n                    float sumCBSigma2[CGmmBgModel::GMM_DIMENSION] = {0.0f};\n                    float sumCFMu[CGmmBgModel::GMM_DIMENSION] = {0.0f};\n\n                    // sum in each grid, take the 1st Gaussian in the GMM as the current background\n                    for (int x = 0; x < gridSize; ++x)\n                    {\n                        for (int y = 0; y < gridSize; ++y)\n                        {\n                            int index = (i*gridSize+x)*fsize.width + j*gridSize+y;\n                            int p = index*channels;\n\n                            for (int d = 0; d < channels; ++d)\n                            {\n                                sumCBMu[d] += mpPixelInfo[index].m_info[0].m_mu[d];\n                                sumCBSigma2[d] += mpPixelInfo[index].m_info[0].m_sigma2[d];\n                                sumCFMu[d] += static_cast<float>(pdata[p+d]);\n                            }\n                        }\n                    }\n\n                    float sumDelta2 = 0.0f;\n                    float sum_sigma2 = 0.0f;\n                    // average each grid and do single Gaussian detection\n                    for (int d = 0; d < channels; ++d)\n                    {\n                        pCBMu[n+d] = sumCBMu[d]/nElems;\n                        pCBSigma2[n+d] = sumCBSigma2[d]/nElems;\n                        pCFMu[n+d] = sumCFMu[d]/nElems;\n\n                        float delta = sumCFMu[d] - sumCBMu[d];\n                        sumDelta2 += delta*delta;\n                        sum_sigma2 += sumCBSigma2[d];\n                    }\n                    sum_sigma2 = stdThres*stdThres*sum_sigma2;\n\n                    // generate coarse foreground mask\n                    if (sumDelta2 >= sum_sigma2)\n                    {\n                        pCFMaskS[n] = static_cast<uchar>(255);\n                    } else\n                    {\n                        pCFMaskS[n] = static_cast<uchar>(0);\n                    }\n                }\n            }\n\n            // extend CFMaskS to full size CFMaskF and generate a updateMask based on CFMaskF and SgMask\n            Size sMaskSize = mpCFMaskS->size();\n            uchar* pCFMaskF = mpCFMaskF->ptr<uchar>();\n            uchar* pUpdateMask = mpUpdateMask->ptr<uchar>();\n            uchar* pSgMask = mpSgMask->ptr<uchar>();\n            for (int i = 0, n = 0; i < fsize.height; ++i)\n            {\n                for (int j = 0; j < fsize.width; ++j, ++n)\n                {\n                    int index = i/gridSize*sMaskSize.width + j/gridSize;\n                    pCFMaskF[n] = pCFMaskS[index];\n                    pUpdateMask[n] = pSgMask[index];\n                }\n            }\n                \n            Mat key = Mat::ones(3, 3, CV_8U);\n\n            dilate(*mpCFMaskF, *mpCFMaskF, key, Point(-1, -1), 1);\n            bitwise_or(*mpCFMaskF, *mpUpdateMask, *mpUpdateMask);\n\n\n        }\n\n        /// Calculate probability of pixel follows a Gaussian distribution\n        /** @param[in] pixel pixel value in a \\b d dimensional vector\n            ** @param[in] pInfo reference to CGmmInfo\n            ** @param[in] channels number of dimensions of the pixel\n            ** \\return Gaussian probability\n            */\n        float GaussianPDF(const float* pixel, const CGmmInfo& pInfo, int channels = 3)\n        {\n            static const float pi = 3.14159f;\n            float invSigma2 = 0.0f;\n            float invDetSigma2 = 1.0;\n            float delta = 0.0f;\n            float sumVec = 0.0f;\n\n            for (int d = 0; d < channels; ++d)\n            {\n                delta = pixel[d] - pInfo.m_mu[d];\n                invSigma2 = 1.0f/pInfo.m_sigma2[d];\n                invDetSigma2 *= invSigma2;\n                sumVec += delta*delta*invSigma2;\n            }\n\n            return static_cast<float>(sqrt(pow(2.0*pi, -channels)*invDetSigma2)*exp(-0.5*sumVec));\n        }\n\n        /// Test if current pixel matches any Gaussian in the model\n        /** @param[in] pixel pixel value\n            ** @param[in] pPixelInfo pointer to CGmmPixelInfo\n            ** @param[in] channels number of dimensions of the pixel\n            ** @param[out] matchIndex a <b>1 x M</b> array (\\b M is the number of Gaussians in GMM). The \n            ** corresponding match position is set to 1, otherwise all 0\n            ** \\return \\b true if has match, otherwise \\b false\n            ***/\n        bool GmmMatchTest(const float* pixel, const CGmmPixelInfo* pPixelInfo, int* matchIndex, int channels = 3)\n        {\n            bool isMatch = false;\n            const int M = pPixelInfo->M;\n            float stdThres = m_param.StdThreshold ();\n            // each Gaussian is already sorted in descending order\n            for (int k = 0; k < M; ++k)\n            {\n                float sumDelta2 = 0.0f;\n                float sum_sigma2 = 0.0f;\n                for (int d = 0; d < channels; ++d)\n                {\n                    float delta = pixel[d] - pPixelInfo->m_info[k].m_mu[d];\n                    sumDelta2 += delta*delta;\n                    sum_sigma2 += pPixelInfo->m_info[k].m_sigma2[d];\n                }\n                sum_sigma2 = stdThres*stdThres*sum_sigma2;\n\n                // match measure under Euclidean distance and extract the number of first matched Gaussian\n                if (sumDelta2 < sum_sigma2)\n                {\n                    matchIndex [k] = 1;\n                    isMatch = true;\n                    break;\n                }\n            }\n\n            return isMatch;\n\n        }\n\n        /// Update the GMM model at each pixel position if has matched input\n        void Gm_mupdateMatch(const float* pixel, CGmmPixelInfo* pPixelInfo, const int* matchIndex, bool isGlobalUpdate, uchar updateMask, long frameCount, int channels = 3)\n        {\n            \n            int windowSize = m_param.WindowSize();\n            float supportRate = m_param.SupportRate ();\n            float learningRate;\n            if (isGlobalUpdate && !updateMask)\n            {\n                learningRate = frameCount < windowSize ? 1.0f/frameCount : m_param.GlobalUpdateRate()*1.0f/windowSize;\n            }\n            else\n            {\n                learningRate = frameCount < windowSize ? 1.0f/frameCount : 1.0f/windowSize;\n            }\n            float weightSum = 0.0f;\n            float delta = 0.0f;\n            const int M = pPixelInfo->M;\n            float updateRate = 0.0f;\n            float probGaussian = 0.0f;\n            float eat = 0.0f;\n\n            for (int k = 0; k < M; ++k)\n            {\n                pPixelInfo->m_info[k].m_matchCout += static_cast<long>(matchIndex[k]);\n\n                // gmm initialisation stage\n                if (frameCount < windowSize)    \n                {\n                    pPixelInfo->m_info[k].m_weight += learningRate*(static_cast<float>(matchIndex[k]) - pPixelInfo->m_info[k].m_weight);\n                } \n                else  // gmm enters stable stage\n                {\n                    pPixelInfo->m_info[k].m_weight += learningRate*(static_cast<float>(matchIndex[k]) - pPixelInfo->m_info[k].m_weight) - learningRate*supportRate;\n                    // delete negative weighted clusters\n                    if ( pPixelInfo->m_info[k].m_weight < 0)\n                    {\n                        pPixelInfo->M--;\n                        pPixelInfo->m_info[k].m_matchCout = 0;\n                        pPixelInfo->m_info[k].m_weight = 0;\n\n                        for (int d = 0; d < channels; ++d)\n                        {\n                            pPixelInfo->m_info[k].m_mu[d] = 0;\n                            pPixelInfo->m_info[k].m_sigma2[d] = 0;\n                        }\n                    }\n                }\n\n                weightSum += pPixelInfo->m_info[k].m_weight;\n                    \n                if (matchIndex[k])\n                {\n                    updateRate = frameCount < windowSize ? static_cast<float>(matchIndex[k])/static_cast<float>(pPixelInfo->m_info[k].m_matchCout) : learningRate*GaussianPDF (pixel, pPixelInfo->m_info[k], channels);\n\n                        \n                    for (int d = 0; d < channels; ++d)\n                    {\n                        delta = pixel[d] - pPixelInfo->m_info[k].m_mu[d];\n                        pPixelInfo->m_info[k].m_mu[d] += updateRate*delta;\n                        pPixelInfo->m_info[k].m_sigma2[d] += updateRate*(delta*delta - pPixelInfo->m_info[k].m_sigma2[d]);\n\n                        // avoid divergence? TODO?\n                    }\n                }\n            }\n\n            // normalise the weight of each Gaussian\n            for (int k = 0; k < M; ++k)\n            {\n                pPixelInfo->m_info[k].m_weight /= weightSum;\n            }\n\n        }\n\n        /// Update GMM information at each pixel position if no matched input found\n        void Gm_mupdateNoMatch(const float* pixel, CGmmPixelInfo* pPixelInfo, long frameCount, int channels = 3)\n        {\n            int windowSize = m_param.WindowSize();\n            float learningRate = frameCount < windowSize ? 1.0f/frameCount : 1.0f/windowSize;\n            int M = pPixelInfo->M;\n            float initSigma2 = m_param.InitSigma2 ();\n            float weightTemp = 0.0f;\n                \n            if (M < m_param.NumberGmm ())\n            {\n                pPixelInfo->M++;\n                M++;\n            }\n            else\n            {\n                weightTemp = pPixelInfo->m_info[M-1].m_weight;\n            }\n\n            pPixelInfo->m_info[M-1].m_matchCout = 1;\n            pPixelInfo->m_info[M-1].m_weight = learningRate;\n\n            for (int d = 0; d < channels; ++d)\n            {\n                pPixelInfo->m_info[M-1].m_mu[d] = pixel[d];\n                pPixelInfo->m_info[M-1].m_sigma2[d] = initSigma2;\n            }\n\n            for (int k = 0; k < M; ++k)\n            {\n                pPixelInfo->m_info[k].m_weight /= 1.0f - weightTemp + learningRate;\n            }\n\n        }\n\n        /// Sort the GMM at each pixel position in descending order according to each Gaussian's weight/Sigma2\n        void GmmSort(CGmmPixelInfo* pPixelInfo, int* matchIndex, int channels = 3)\n        {\n            const int M = pPixelInfo->M;\n            float sortIndex[CGmmBgModel::GMM_MAX_NUMBER] = {0.0f};\n            for (int k = 0; k < M; ++k)\n            {\n                // avoid divided by zero in initial step and after delete some clusters\n                if (pPixelInfo->m_info[k].m_matchCout > 0)\n                {\n                    float sum_sigma2 = 0.0f;\n                    for (int d = 0; d < channels; ++d)\n                    {\n                        sum_sigma2 += pPixelInfo->m_info[k].m_sigma2[d];\n                    }\n\n                    sortIndex[k] = pPixelInfo->m_info[k].m_weight/sum_sigma2;\n                }\n\n            }\n\n            // reorder Gaussians according to the index\n            for (int k = 1; k < M; ++k)\n            {\n                for (int i = k; i > 0 && (sortIndex[i-1] < sortIndex[k]); --i)\n                {\n                    float sortIndexTemp = sortIndex[i];\n                    sortIndex[i] = sortIndex[i-1];\n                    sortIndex[i-1] = sortIndexTemp;\n\n                    int matchIndexTemp = matchIndex[i];\n                    matchIndex[i] = matchIndex[i-1];\n                    matchIndex[i-1] = matchIndexTemp;\n\n                    // using pointer change to speed up?\n                    CGmmInfo infoTemp = pPixelInfo->m_info[i];\n                    pPixelInfo->m_info[i] = pPixelInfo->m_info[i-1];\n                    pPixelInfo->m_info[i-1] = infoTemp;\n                }\n            }\n\n        }\n\n        /// Generate current background image from GMM model\n        void GmmBackground()\n        {\n            Size fsize = mpBackground->size();\n            int channels = mpBackground->channels ();\n            uchar* pBackground = mpBackground->ptr<uchar>();\n            for (int i = 0, n = 0; i < fsize.height; ++i)\n            {\n                for (int j = 0; j < fsize.width; ++j, ++n)\n                {\n                    int p = n*channels;\n                    for (int d = 0; d < channels; ++d)\n                    {\n                        pBackground[p+d] = static_cast<uchar>(mpPixelInfo[n].m_info[0].m_mu[d]+0.5);\n                    }\n                }\n            }\n        }\n\n        /// Calculate if current pixel position belongs to foreground and set the corresponding mask in mpForeground\n        void GmmForegourndPixel(const CGmmPixelInfo* pPixelInfo, const int* matchIndex, int n, int regionMask)\n        {\n            uchar foregroundPixel = static_cast<uchar>(255);\n            float weightSum = 0.0f;\n            int M = pPixelInfo->M;\n            float bgThres = m_param.BgThreshold ();\n            for (int k = 0; k < M; ++k)\n            {\n                if (matchIndex[k])\n                {\n                    foregroundPixel = 0;\n                }\n\n                weightSum += pPixelInfo->m_info[k].m_weight;\n                if (weightSum > bgThres)\n                    break;\n            }\n\n            if (mIsCoarseDetection)\n                mpForeground->at<uchar>(n) = foregroundPixel & mpCFMaskF->at<uchar>(n) & regionMask;\n            else\n                mpForeground->at<uchar>(n) = foregroundPixel & regionMask;\n\n        }\n\n        /// Find connected regions from foreground\n        void Neighbours(const cv::Mat& foreground, std::vector<cv::Point>& points, int previndex, int index, int nNeighbours = 8)\n        {\n            Size fsize = foreground.size();\n            const uchar* pdata = foreground.ptr<uchar>();\n            uchar* ptemp = mpTempMat->ptr<uchar>(); // to record if the current foreground pixel has been looped\n\n            if (index < 0 || index >= fsize.height*fsize.width)\n            {\n                return;\n            }\n            else\n            {\n                if (pdata[index] > 0 && ptemp[index] == 0)  // good to go\n                {\n                    if (index%fsize.width == 0 && previndex%fsize.width == fsize.width-1) // central pixel at right boundary\n                        return;\n                    if (index%fsize.width == fsize.width-1 && previndex%fsize.width == 0) // left boundary\n                        return;\n\n                    ptemp[index] = 1;\n                    Point point;\n                    point.x = index%fsize.width;\n                    point.y = index/fsize.width;\n                    points.push_back (point);\n\n                    if (nNeighbours == 4)\n                    {\n                        Neighbours (foreground, points, index, index-1, 4);\n                        Neighbours (foreground, points, index, index+1, 4);\n                        Neighbours (foreground, points, index, index-fsize.width, 4);\n                        Neighbours (foreground, points, index, index+fsize.width, 4);\n                    }\n                    else if (nNeighbours == 8)\n                    {\n                        Neighbours (foreground, points, index, index-1, 8);\n                        Neighbours (foreground, points, index, index+1, 8);\n                        Neighbours (foreground, points, index, index-fsize.width, 8);\n                        Neighbours (foreground, points, index, index+fsize.width, 8);\n                        Neighbours (foreground, points, index, index-fsize.width-1, 8);\n                        Neighbours (foreground, points, index, index-fsize.width+1, 8);\n                        Neighbours (foreground, points, index, index+fsize.width-1, 8);\n                        Neighbours (foreground, points, index, index+fsize.width+1, 8);\n                    }\n                }\n                return;\n            }\n        }\n\n        CGmmBgModelParam        m_param;                 ///< store parameters\n        long                    mFrameCount;            ///< number of frames that has been processed\n        bool                    mIsCoarseDetection;     ///< if ture, do coarse pre-detection, otherwise do simple GMM\n        CGmmPixelInfo*          mpPixelInfo;            ///< pointer to array of CGmmPixelInfo (equal to frame size)\n        shared_ptr<Mat>                    mpBackground;           ///< store background of the model (channel = channel of frame)\n        shared_ptr<Mat>                    mpForeground;           ///< detected foreground (single channel)\n        shared_ptr<Mat>                    mpUpdateMask;           ///< mask to indicate which pixel to be updated\n        shared_ptr<Mat>                    mpSgMask;               ///< similar gradient mask, smaller sized image, depend on param.gridsize\n        shared_ptr<Mat>                    mpCFMaskS;              ///< coarse foreground mask smaller sized\n        shared_ptr<Mat>                    mpCFMaskF;              ///< coarse foreground mask full sized\n        shared_ptr<Mat>                    mpCBMu;                 ///< coarse background mu\n        shared_ptr<Mat>                    mpCBSigma2;             ///< coarse background Sigma2\n        shared_ptr<Mat>                    mpCFMu;                 ///< coarse frame mu\n        shared_ptr<Mat>                    mpTempMat;              ///< same size as frame for any temp useage\n        shared_ptr<CGmmTempInfo>           mpTempInfo;             ///< store intermediate results\n        vector<vector<Point> >  mFgContours;            ///< store each individual foreground contours, default initialisation equals to 0\n        vector<vector<Point> >  mFgRegions;               ///< store all foreground pixels in each individual foreground regions\n        vector<Rect>            mFgBoxes;                 ///< foreground bounding boxes\n    };\n\n\n    CGmmBgModel::CGmmBgModel(const cv::Mat& frame, const CGmmBgModelParam& param, bool isCoarseDetection)\n        : m_impl(new CGmmBgModel::Impl())\n    {\n        // allocate corresponding memories for foreground detection\n        int channels = frame.channels (); // number of channel of frame\n        Size fsize = frame.size();    // height and width of frame\n\n        m_impl->m_param = param;\n        m_impl->mFrameCount = 0;\n        m_impl->mIsCoarseDetection = isCoarseDetection;\n        m_impl->mpPixelInfo = new Impl::CGmmPixelInfo[fsize.height*fsize.width];\n        //const int sizeND1[] = {fsize.height, fsize.width, channels};\n        //m_impl->mpBackground = new Mat(channels, sizeND1, CV_8U);\n        //frame.copyTo(*m_impl->mpBackground);\n        if (1 == channels)\n        {\n            m_impl->mpBackground.reset(new Mat(fsize.height, fsize.width, CV_8UC1));\n        }\n        else if (3 == channels)\n        {\n            m_impl->mpBackground.reset(new Mat(fsize.height, fsize.width, CV_8UC3));\n        }\n\n        m_impl->mpForeground.reset(new Mat(fsize.height, fsize.width, CV_8UC1));\n        m_impl->mpTempMat.reset(new Mat(fsize.height, fsize.width, CV_8UC1));\n        m_impl->mpUpdateMask.reset(new Mat(fsize.height, fsize.width, CV_8UC1));\n\n        if (isCoarseDetection)   // do my method, otherwise pure GMM\n        {\n            m_impl->mpSgMask.reset(new Mat(fsize.height/param.GridSize (), fsize.width/param.GridSize (), CV_8UC1));\n            m_impl->mpCFMaskS.reset(new Mat(fsize.height/param.GridSize (), fsize.width/param.GridSize (), CV_8UC1));\n            m_impl->mpCFMaskF.reset(new Mat(fsize.height, fsize.width, CV_8UC1));\n            if (1 == channels)\n            {                \n                m_impl->mpCBMu.reset(new Mat(fsize.height/param.GridSize (), fsize.width/param.GridSize (), CV_32FC1));\n                m_impl->mpCBSigma2.reset(new Mat(fsize.height/param.GridSize (), fsize.width/param.GridSize (), CV_32FC1));\n                m_impl->mpCFMu.reset(new Mat(fsize.height/param.GridSize (), fsize.width/param.GridSize (), CV_32FC1));\n            } else if (3 == channels)\n            {\n                m_impl->mpCBMu.reset(new Mat(fsize.height/param.GridSize (), fsize.width/param.GridSize (), CV_32FC3));\n                m_impl->mpCBSigma2.reset(new Mat(fsize.height/param.GridSize (), fsize.width/param.GridSize (), CV_32FC3));\n                m_impl->mpCFMu.reset(new Mat(fsize.height/param.GridSize (), fsize.width/param.GridSize (), CV_32FC3));\n            }\n\n        }\n\n\n        // allocate memories for CGmmInfo class in each pixel position\n        //for (int i = 0; i < fsize.height; ++i)\n        //{\n        //    for (int j = 0; j < fsize.width; ++j)\n        //    {\n        //        m_impl->mspPixelInfo[i*fsize.width+j].m_info = new Impl::CGmmInfo[param.NumberGmm()];\n        //    }\n        //}\n            \n        // assign memories for CGmmInfo as a chunk to reduce assign and delete time\n        m_impl->mpPixelInfo[0].m_info = new Impl::CGmmInfo[param.NumberGmm ()*fsize.height*fsize.width];\n\n\n        const uchar* pdata = frame.ptr();   // pointer to image\n        uchar* pbackground = m_impl->mpBackground->ptr ();\n        // assign initial value to the model. Foreground, UpdateMask, SgMask, CFMask can be kept as default\n        for (int i = 0, n=0; i < fsize.height; ++i)\n        {\n            for (int j = 0; j < fsize.width; ++j, ++n)\n            {\n                int p = n*channels;\n                m_impl->mpPixelInfo[n].M = 1;\n                // pointer offset assigned to m_info in each mpPixelInfo\n                m_impl->mpPixelInfo[n].m_info = m_impl->mpPixelInfo[0].m_info + n*param.NumberGmm ();\n                m_impl->mpPixelInfo[n].m_info[0].m_matchCout = 1;\n                m_impl->mpPixelInfo[n].m_info[0].m_weight = 1;\n                m_impl->mpPixelInfo[n].m_info[0].m_updateRate = 1.0f/param.WindowSize();\n                for (int d = 0; d < channels; ++d)\n                {\n                    m_impl->mpPixelInfo[n].m_info[0].m_mu[d] = pdata[p+d];\n                    m_impl->mpPixelInfo[n].m_info[0].m_sigma2[d] = param.InitSigma2();\n                    pbackground[p+d] = pdata[p+d];\n                }\n\n\n                for (int m = 1; m < param.NumberGmm(); ++m)\n                {\n                    m_impl->mpPixelInfo[n].m_info[m].m_weight = 0;\n                    m_impl->mpPixelInfo[n].m_info[m].m_matchCout = 0;\n                    for (int d = 0; d < channels; ++d)\n                    {\n                        m_impl->mpPixelInfo[n].m_info[m].m_mu[d] = 0.0f;\n                        m_impl->mpPixelInfo[n].m_info[m].m_sigma2[d] = 0.0f;\n                    }\n                }\n            }\n        }\n\n        if (isCoarseDetection)\n        {\n            \n            int gridSzie = param.GridSize();\n            int nElems = gridSzie*gridSzie;\n            float* pCBMu = m_impl->mpCBMu->ptr<float>();\n            float* pCBSigma2 = m_impl->mpCBSigma2->ptr<float>();\n            float* pCFMu = m_impl->mpCFMu->ptr<float>();\n            for (int i = 0, n = 0; i < fsize.height/gridSzie; ++i)\n            {\n                for (int j = 0; j < fsize.width/gridSzie; ++j, ++n)\n                {\n                    int p = n*channels;\n                    float sumCBMu[CGmmBgModel::GMM_DIMENSION] = {0.0f};\n                    float sumCBSigma2[CGmmBgModel::GMM_DIMENSION] = {0.0f};\n                    float sumCFMu[CGmmBgModel::GMM_DIMENSION] = {0.0f};\n\n                    for (int x = 0; x < gridSzie; ++x)\n                    {\n                        for (int y = 0; y < gridSzie; ++y)\n                        {\n                            int n = (i*gridSzie+x)*fsize.width+(j*gridSzie+y);\n                            int p = n*channels;\n                            for (int d = 0; d < channels; ++d)\n                            {\n                                sumCBMu[d] +=  m_impl->mpPixelInfo[n].m_info[0].m_mu[d];\n                                sumCBSigma2[d] +=  m_impl->mpPixelInfo[n].m_info[0].m_sigma2[d];\n                                sumCFMu[d] += pdata[p+d];\n                            }\n                        }\n                    }\n\n                    // average value within each grid for coarse single Gaussian detection\n                    for (int d = 0; d < channels; ++d)\n                    {\n                        sumCBMu[d] /= nElems;\n                        sumCBSigma2[d] /= nElems;\n                        sumCFMu[d] /= nElems;\n\n                        pCBMu[p+d] = sumCBMu[d];\n                        pCBSigma2[p+d] = sumCBSigma2[d];\n                        pCFMu[p+d] = sumCFMu[d];\n\n                    }\n                }\n            }\n        }\n\n        if (isCoarseDetection)\n        {\n            m_impl->mpTempInfo.reset(new Impl::CGmmTempInfo());\n\t\t\tm_impl->mpTempInfo->m_frameGray.reset(new Mat(fsize.height, fsize.width, CV_8UC1));\n            m_impl->mpTempInfo->m_backgroundGray.reset(new Mat(fsize.height, fsize.width, CV_8UC1));\n            m_impl->mpTempInfo->m_frameGradientX.reset(new Mat(fsize.height, fsize.width, CV_32FC1));\n            m_impl->mpTempInfo->m_frameGradientY.reset(new Mat(fsize.height, fsize.width, CV_32FC1));\n            m_impl->mpTempInfo->m_backgroundGradientX.reset(new Mat(fsize.height, fsize.width, CV_32FC1));\n            m_impl->mpTempInfo->m_backgroundGradientY.reset(new Mat(fsize.height, fsize.width, CV_32FC1));\n            m_impl->mpTempInfo->m_frameGradientMag.reset(new Mat(fsize.height, fsize.width, CV_32FC1));\n            m_impl->mpTempInfo->m_frameGradientMag2.reset(new Mat(fsize.height, fsize.width, CV_32FC1));\n            m_impl->mpTempInfo->m_backgroundGradientMag.reset(new Mat(fsize.height, fsize.width, CV_32FC1));\n            m_impl->mpTempInfo->m_backgroundGradientMag2.reset(new Mat(fsize.height, fsize.width, CV_32FC1));\n            m_impl->mpTempInfo->m_gradientDotProduct.reset(new Mat(fsize.height, fsize.width, CV_32FC1));\n            m_impl->mpTempInfo->m_temp1.reset(new Mat(fsize.height, fsize.width, CV_32FC1));\n            m_impl->mpTempInfo->m_temp2.reset(new Mat(fsize.height, fsize.width, CV_32FC1));\n        }\n\n\n        m_impl->mFrameCount++;\n        //cout << \"CGmmBgModel constructor called\" << endl;\n    }\n    \n    CGmmBgModel::~CGmmBgModel()\n    {\n\n        //Size fsize = m_impl->mpBackground->size();\n        //for (int i = 0; i < fsize.height; ++i)\n        //{\n        //    for (int j = 0; j < fsize.width; ++j)\n        //    {\n        //        delete[] m_impl->mpPixelInfo[i*fsize.width+j].m_info;\n        //    }\n        //}\n        delete[] m_impl->mpPixelInfo[0].m_info;\n        delete[] m_impl->mpPixelInfo;\n\n    }\n\n    void CGmmBgModel::BgModelUpdate (const cv::Mat& frame, const cv::Mat* regionMask)\n    {\n        m_impl->mpForeground->setTo(0);   // reset foreground\n        m_impl->mpTempMat->setTo (0); // to record if the current foreground pixel has been looped in Neighbours()\n\n        bool isGlobalUpdate;\n        if (m_impl->mIsCoarseDetection)\n        {\n            m_impl->SgMaskCalculation (frame);\n\n            m_impl->CoarseForegroundDetection (frame);\n\n            isGlobalUpdate = !(m_impl->mFrameCount%m_impl->m_param.GlobalUpdateRate ());    // if true, do global update\n        }\n        else\n        {\n            isGlobalUpdate = true;\n        }\n\n        Size fsize = frame.size();\n        int channels = frame.channels ();\n        int windowSize = m_impl->m_param.WindowSize ();\n        //int gridSize = m_impl->m_param.GridSize ();\n        const uchar* pdata = frame.ptr<uchar>();\n\t\tconst uchar* pregionMask = regionMask == nullptr ? nullptr : regionMask->ptr<uchar>();\n        uchar* pUpdateMask = m_impl->mpUpdateMask->ptr<uchar>();\n\n        for (int i = 0, n = 0; i < fsize.height; ++i)\n        {\n            for (int j = 0; j < fsize.width; ++j, ++n)\n            {\n                //int m = i/gridSize*fsize.width/gridSize + j/gridSize;   /// corresponding position in the coarse image\n\n                // selective update pixel information  updateMask regions + global update rate + if in initialisation stage update all\n                if (m_impl->mFrameCount < windowSize || isGlobalUpdate || pUpdateMask[n])\n                {\n                    int p = n*channels;\n                    Impl::CGmmPixelInfo* pPixelInfo = &m_impl->mpPixelInfo[n];\n\n                    float pixel[CGmmBgModel::GMM_DIMENSION] = {0.0f};\n                    for (int d = 0; d < channels; ++d)\n                    {\n                        pixel[d] = static_cast<float>(pdata[p+d]);      /// extract pixel value\n                    }\n\n                    int matchIndex[CGmmBgModel::GMM_MAX_NUMBER] = {0};\n                    // test if current pixel matches any Gaussian in the model, if has match isMatch == true and matchIndex[] set the corresponding match position to 1\n                    bool isMatch = m_impl->GmmMatchTest (pixel, pPixelInfo, matchIndex, channels);\n                        \n                    if (isMatch)\n                        m_impl->Gm_mupdateMatch (pixel, pPixelInfo, matchIndex, isGlobalUpdate, pUpdateMask[n], m_impl->mFrameCount, channels);\n                    else\n                        m_impl->Gm_mupdateNoMatch (pixel, pPixelInfo, m_impl->mFrameCount, channels);\n\n                    // sorting index for sorting each gaussian after update (in descending order according to weight/Sigma2)\n                    m_impl->GmmSort (pPixelInfo, matchIndex, channels);\n\n                    // generate foreground mask at each pixel position \n                    m_impl->GmmForegourndPixel(pPixelInfo, matchIndex, n, pregionMask == nullptr ? 255 : pregionMask[n]);\n                        \n                }\n            }\n        }\n\n        m_impl->GmmBackground ();\n\n        m_impl->mFrameCount++;\n\n    }\n\n\n\n    // Remove shadows and highlights\n    void CGmmBgModel::ShadowHighlightRemoval(const Mat& frame)\n    {\n        Size fsize = frame.size();\n        int channels = frame.channels ();\n        int gridSize = m_impl->m_param.GridSize ();\n        float shadowBrightThres = m_impl->m_param.ShadowBrightThreshold ();\n        float shadowChromaThres = m_impl->m_param.ShadowChromaThreshold ();\n        float highightThreshold = m_impl->m_param.HighlightThreshold ();\n        const uchar* pdata = frame.ptr<uchar>();\n        uchar* pForeground = m_impl->mpForeground->ptr<uchar> ();\n        uchar* pSgMask = NULL;\n        if (m_impl->mIsCoarseDetection)\n            pSgMask = m_impl->mpSgMask->ptr<uchar>();\n\n        for (int i = 0, n = 0; i < fsize.height; ++i)\n        {\n            for (int j = 0; j < fsize.width; ++j, ++n)\n            {\n                int p = n*channels;\n                int m = i/gridSize*fsize.width/gridSize + j/gridSize;\n\n                // per pixel based shadow detection\n                if (pForeground[n] != 0)\n                {\n                    float sumTemp1 = 0.0f;\n                    float sumTemp2 = 0.0f;\n                    float sum_sigma2 = 0.0f;\n\n                    for (int d = 0; d < channels; ++d)\n                    {\n                        sumTemp1 += pdata[p+d]*m_impl->mpPixelInfo[n].m_info[0].m_mu[d]/m_impl->mpPixelInfo[n].m_info[0].m_sigma2[d];\n                        sumTemp2 += m_impl->mpPixelInfo[n].m_info[0].m_mu[d]*m_impl->mpPixelInfo[n].m_info[0].m_mu[d]/m_impl->mpPixelInfo[n].m_info[0].m_sigma2[d];\n                        sum_sigma2 += m_impl->mpPixelInfo[n].m_info[0].m_sigma2[d];\n                    }\n\n                    float brightDistortion = sumTemp1/sumTemp2;\n                    float chromaDistrotion = 0.0f;\n                    for (int d = 0; d < channels; ++d)\n                    {\n                        chromaDistrotion += (pdata[p+d] - brightDistortion*m_impl->mpPixelInfo[n].m_info[0].m_mu[d])*(pdata[p+d] - brightDistortion*m_impl->mpPixelInfo[n].m_info[0].m_mu[d]);\n                    }\n\n                    // removal shadow and highlight\n                    if (m_impl->mIsCoarseDetection)\n                    {\n                        if (brightDistortion > shadowBrightThres && brightDistortion < highightThreshold && chromaDistrotion < shadowChromaThres*shadowChromaThres*sum_sigma2)\n                        {\n                            pForeground[n] = 0;\n                        } else if (brightDistortion > highightThreshold && chromaDistrotion < shadowChromaThres*shadowChromaThres*sum_sigma2 && pSgMask[m] == 0)\n                        {\n                            pForeground[n] = 0;\n                        }\n                    }\n                    else\n                    {\n                        if (brightDistortion > shadowBrightThres && brightDistortion < highightThreshold && chromaDistrotion < shadowChromaThres*shadowChromaThres*sum_sigma2)\n                        {\n                            pForeground[n] = 0;\n                        }\n                    }\n\n                }\n            }\n        }\n    }\n\n    // Remove small regions and fill holes\n    void CGmmBgModel::ForegroundNoiseRemoval()\n    {\n        // foreground median filtering\n        medianBlur(*m_impl->mpForeground, *m_impl->mpForeground, m_impl->m_param.MedfiltSize ());\n\n        //// dilate foreground to include more boundary\n        //dilate(*m_impl->mpForeground, *m_impl->mpForeground, Mat());\n\n        // find each separated foreground region using findContours\n        //findContours (*m_impl->mpForeground, m_impl->mFgContours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);\n        findContours (*m_impl->mpForeground, m_impl->mFgContours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);\n\n            \n        m_impl->mpTempMat->setTo (0); // to record if the current foreground pixel has been looped in Neighbours()\n        //FindForegroundRegions(*m_impl->mpForeground, m_impl->mFgRegions);\n\n\t\t// approximate contours to polygons + get bounding rects\n\t\tvector<vector<Point> > contoursPoly(m_impl->mFgContours.size());\n\t\t//vector<Rect> boundRect(m_impl->mFgContours.size());\n\t\tvector<Rect>().swap(m_impl->mFgBoxes);\n\t\tm_impl->mFgBoxes.reserve(m_impl->mFgContours.size());\n\t\tfor (size_t i = 0; i < m_impl->mFgContours.size(); ++i)\n\t\t{\n\t\t\tapproxPolyDP(Mat(m_impl->mFgContours[i]), contoursPoly[i], 3, true);\n\t\t\tm_impl->mFgBoxes.push_back(boundingRect(Mat(contoursPoly[i])));\n\t\t}\n\n\n        // delete small regions\n        //m_impl->mFgRegions.erase (remove_if(m_impl->mFgRegions.begin (), m_impl->mFgRegions.end(), LessRegion(m_impl->m_param.MinRegionWidth (), m_impl->m_param.MinRegionHeight ())), m_impl->mFgRegions.end());\n\n\n        //vector<vector<Point> >::iterator it = m_impl->mFgRegions.begin ();\n        //while (it != m_impl->mFgRegions.end())\n        //{\n        //    if (static_cast<int>((*it).size()) < m_impl->m_param.MinArea())\n        //        it = m_impl->mFgRegions.erase(it);\n        //    else\n        //        ++it;\n        //}\n\n        //FindForegroundBoxes(m_impl->mFgRegions, m_impl->mFgBoxes);\n\n        // delete small regions\n        //vector<vector<Point> >::iterator itP = m_impl->mFgRegions.begin ();\n        vector<Rect>::iterator itR = m_impl->mFgBoxes.begin ();\n        while (itR != m_impl->mFgBoxes.end())\n        {\n            if (static_cast<int>((*itR).width) < m_impl->m_param.MinRegionWidth () || static_cast<int>((*itR).height) < m_impl->m_param.MinRegionHeight ())\n            {\n                itR = m_impl->mFgBoxes.erase(itR);\n                //itP = m_impl->mFgRegions.erase (itP);\n            }\n            else\n            {\n                ++itR;\n                //++itP;\n            }\n        }\n\n\t\t// find FgRegions\n\t\t//BOOST_FOREACH(const Rect& rect, m_impl->mFgBoxes)\n\t\t//{\n\t\t//\tfor (int x = rect.tl().x; x <= rect.br().x; ++x)\n\t\t//\t\tfor (int y = rect.tl().y; y <= rect.br().y; ++y)\n\t\t//\t\t\tif (m_impl->mpForeground->\n\t\t//}\n    }\n\n    void CGmmBgModel::ForegroundFillHoles ()\n    {\n        m_impl->mpForeground->setTo(0);   // reset foreground\n\n        // fill holes within each foreground region\n        drawContours (*m_impl->mpForeground, m_impl->mFgContours, -1, Scalar(255, 255, 255), CV_FILLED);\n\n        Mat foreground;\n        m_impl->mpForeground->copyTo (foreground);\n        //// find the filled regions  ????? IT IS CONTOURS NOT WHOLE PIXELS WITHIN REGIONS\n        //findContours (foreground, m_impl->mFgRegions, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);\n\n    }\n\n    void CGmmBgModel::BgModelPostUpdate (const Mat& frame)\n    {\n\t\t//if(FrameCount() > 50)\n  //      {\n\t\t\tShadowHighlightRemoval (frame);\n\t\t\tForegroundNoiseRemoval ();\n\t\t\tForegroundFillHoles ();\n\t\t//}\n    }\n\n    void CGmmBgModel::FindForegroundRegions (const cv::Mat& foreground, std::vector<std::vector<cv::Point> >& regions)\n    {\n        Size fsize = foreground.size();\n        regions.clear ();\n        for (int i = 0; i < fsize.width*fsize.height; ++i)\n        {\n            vector<Point> points;\n            m_impl->Neighbours (foreground, points, i, i);\n\n            if (points.size() > 0)\n            {\n                regions.push_back (points);\n            }\n        }\n        vector<vector<Point> >(regions).swap(regions);  // crop capacity\n    }\n\n\n    void CGmmBgModel::FindForegroundBoxes(std::vector<std::vector<cv::Point> >& regions, std::vector<cv::Rect>& boxes)\n    {\n        vector<Rect>().swap(boxes);    // clear and reduce boxes' capacity\n        boxes.reserve(regions.size());\n        for (size_t i = 0; i < regions.size(); ++i)\n        {\n            Point tl(100000, 100000);\n            Point br(0,0);\n\n            for (size_t j = 0; j < regions[i].size(); ++j)\n            {\n                tl.x = tl.x < regions[i][j].x ? tl.x : regions[i][j].x;\n                tl.y = tl.y < regions[i][j].y ? tl.y : regions[i][j].y;\n                br.x = br.x > regions[i][j].x ? br.x : regions[i][j].x;\n                br.y = br.y > regions[i][j].y ? br.y : regions[i][j].y;\n            }\n            Rect temp(tl, br);\n\n            boxes.push_back(temp);\n        }\n    }\n\n\n    void CGmmBgModel::GetForegroundPoints(const std::vector<std::vector<cv::Point> >& regions, std::vector<cv::Point2f>& points)\n    {\n        vector<Point2f>().swap (points);\n        for (size_t i = 0; i < regions.size(); ++i)\n        {\n            /*for (cv::vector<cv::Point>::const_iterator it = regions[i].begin(); it != regions[i].end(); ++it)\n            {\n                points.push_back (*it);\n            }*/\n\n            vector<Point>::size_type exsize = regions[i].size();\n            size_t psize = points.size();\n            points.resize(psize+exsize);\n            copy(regions[i].begin(), regions[i].end(), points.begin()+psize);\n        }\n\n    }\n\n\n\tbool CGmmBgModel::IsForgroundOverCrowded() const\n\t{\n\t\treturn static_cast<float>(cv::sum(*m_impl->mpForeground)[0]) / (m_impl->mpForeground->size().height * m_impl->mpForeground->size().width * 255) > 0.25;\n\t}\n\n\n    const long CGmmBgModel::FrameCount() const\n    {\n        return m_impl->mFrameCount;\n    }\n\n\n    const Mat& CGmmBgModel::Background () const\n    {\n        return *(m_impl->mpBackground);\n    }\n    Mat& CGmmBgModel::Background ()\n    {\n        return *(m_impl->mpBackground);\n    }\n\n    const Mat& CGmmBgModel::Foreground () const\n    {\n        return *(m_impl->mpForeground);\n    }\n    Mat& CGmmBgModel::Foreground ()\n    {\n        return *(m_impl->mpForeground);\n    }\n\n    const Mat* CGmmBgModel::SgMask () const\n    {\n\t\tif (m_impl->mpSgMask)\n\t\t\treturn m_impl->mpSgMask.get();\n\t\telse\n\t\t\treturn NULL;\n    }\n        \n    const Mat* CGmmBgModel::FrameGray() const\n    {\n        if (m_impl->mpTempInfo)\n            return m_impl->mpTempInfo->m_frameGray.get();\n        else\n            return NULL;\n    }\n\n    const Mat* CGmmBgModel::BackgroundGray () const\n    {\n        if (m_impl->mpTempInfo)\n            return m_impl->mpTempInfo->m_backgroundGray.get();\n        else\n            return NULL;\n    }\n\n\n    const cv::Mat* CGmmBgModel::FrameGradientX() const\n    {\n        if (m_impl->mpTempInfo)\n            return m_impl->mpTempInfo->m_frameGradientX.get();\n        else\n            return NULL;\n    }\n\n    const cv::Mat* CGmmBgModel::FrameGradientY() const\n    {\n        if (m_impl->mpTempInfo)\n            return m_impl->mpTempInfo->m_frameGradientY.get();\n        else\n            return NULL;\n    }\n\n    const cv::Mat* CGmmBgModel::FrameGradientMag() const\n    {\n        if (m_impl->mpTempInfo)\n            return m_impl->mpTempInfo->m_frameGradientMag.get();\n        else\n            return NULL;\n    }\n\n\n    const cv::Mat* CGmmBgModel::BackgroundGradientX() const\n    {\n        if (m_impl->mpTempInfo)\n            return m_impl->mpTempInfo->m_backgroundGradientX.get();\n        else\n            return NULL;\n    }\n\n    const cv::Mat* CGmmBgModel::BackgroundGradientY() const\n    {\n        if (m_impl->mpTempInfo)\n            return m_impl->mpTempInfo->m_backgroundGradientY.get();\n        else\n            return NULL;\n    }\n\n    const cv::Mat* CGmmBgModel::BackgroundGradientMag() const\n    {\n        if (m_impl->mpTempInfo)\n            return m_impl->mpTempInfo->m_backgroundGradientMag.get();\n        else\n            return NULL;\n    }\n\n    const Mat* CGmmBgModel::CFMaskF() const\n    {\n        if (m_impl->mpTempInfo)\n            return m_impl->mpCFMaskF.get();\n        else\n            return NULL;\n    }\n    const Mat* CGmmBgModel::UpdateMask() const\n    {\n        if (m_impl->mpTempInfo)\n            return m_impl->mpUpdateMask.get();\n        else\n            return NULL;\n    }\n\n    //const vector<vector<Point> >& CGmmBgModel::ForegroundRegions() const\n    //{\n    //    return m_impl->mFgRegions;\n    //}\n\n    const vector<Rect>& CGmmBgModel::ForegroundBoxes () const\n    {\n        return m_impl->mFgBoxes;\n    }\n\n}", "meta": {"hexsha": "d4ae5629a190458f4e1a2ca2dc00811de8959319", "size": 56348, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/FG/Detection.cpp", "max_stars_repo_name": "superlee1999/demo", "max_stars_repo_head_hexsha": "6d450e07071084b8c7e8e7526869c954ae4d4adf", "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": "Source/FG/Detection.cpp", "max_issues_repo_name": "superlee1999/demo", "max_issues_repo_head_hexsha": "6d450e07071084b8c7e8e7526869c954ae4d4adf", "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": "Source/FG/Detection.cpp", "max_forks_repo_name": "superlee1999/demo", "max_forks_repo_head_hexsha": "6d450e07071084b8c7e8e7526869c954ae4d4adf", "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.6232980333, "max_line_length": 215, "alphanum_fraction": 0.5365407823, "num_tokens": 13900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.44167300566462564, "lm_q1q2_score": 0.26176483855874827}}
{"text": "#pragma once\n\n// system includes ---------------------------------------------------------\n#include <malloc.h>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <cassert>\n#include <complex>\n#include <type_traits>\n#include <vector>\n// own includes ------------------------------------------------------------\n#include \"base/types.hpp\"\n//#include \"fft/fft2.hpp\"\n#include \"fft/fft2_r2c.hpp\"\n#include \"fft/ft_grid_helpers.hpp\"\n// local includes ----------------------------------------------------------\n#include \"fold.hpp\"\n#include \"init_fftw.hpp\"\n#include \"lambda.hpp\"\n#include \"ridgelet_cell_array.hpp\"\n\n\nnamespace internal {\n\n/**\n * @brief dst = src1*src2\n *\n * @param[out] dst\n * @param[in] src1\n * @param[in] src2\n */\ntemplate <typename ARRAY, typename DERIVED>\nvoid\nmtimes(ARRAY &dst,\n       const Eigen::SparseMatrix<double, Eigen::RowMajor> &src1,\n       const Eigen::DenseBase<DERIVED> &src2)\n{\n  typedef Eigen::SparseMatrix<double, Eigen::RowMajor> sp_mat_t;\n\n  assert(src1.rows() == src2.rows());\n  assert(src1.cols() == src2.cols());\n  assert(dst.rows() == src1.rows());\n  assert(dst.cols() == src1.cols());\n\n  dst.setZero();\n\n  for (int k = 0; k < src1.outerSize(); ++k) {\n    for (typename sp_mat_t::InnerIterator it(src1, k); it; ++it) {\n      int row = it.row();\n      int col = it.col();\n      double val = it.value();\n      dst(row, col) = val * src2(row, col);\n    }\n  }\n}\n}  // internal\n\n// forward declaration\nclass RidgeletFrame;\n\n/**\n * @brief Fast Fourier Ridgelet Transform\n *\n */\ntemplate <typename NUMERIC_T = std::complex<double>,\n          typename FRAME = RidgeletFrame,\n          typename FFT_TYPE = FFTr2c<PlannerR2COD>>\nclass RT\n{\n public:\n  typedef Eigen::Array<std::complex<double>, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>\n      complex_array_t;\n  typedef Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> array_t;\n  typedef Eigen::Array<NUMERIC_T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> rt_coeff_t;\n  typedef FRAME rt_frame_t;\n  typedef FFT_TYPE fft_t;\n  typedef NUMERIC_T numeric_t;\n\n public:\n  RT(const rt_frame_t &rt_frame)\n      : rt_frame_(rt_frame)\n  { /* empty */\n  }\n\n  RT(const RT<NUMERIC_T, FRAME, FFT_TYPE> &other)\n      : rt_frame_(other.rt_frame)\n  { /*  empty  */\n  }\n\n  RT(RT<NUMERIC_T, FRAME, FFT_TYPE> &&other)\n      : rt_frame_(std::move(other.rt_frame))\n  { /*  empty  */\n  }\n\n  RT<NUMERIC_T, FRAME, FFT_TYPE> &operator=(RT<NUMERIC_T, FRAME, FFT_TYPE> &&other);\n\n  RT<NUMERIC_T, FRAME, FFT_TYPE> &operator=(const RT<NUMERIC_T, FRAME, FFT_TYPE> &other);\n\n  RT() {}\n\n  /**\n   * @brief\n   *\n   * @param[out] dst  Ridgelet coefficients\n   * @param[in]  src  Fourier coefficients in _centered zero-frequency_\n   * convection\n   */\n  template <typename DERIVED>\n  void rt(std::vector<rt_coeff_t> &dst, const Eigen::DenseBase<DERIVED> &src) const;\n\n  template <typename DERIVED>\n  void rt(RidgeletCellArray<rt_coeff_t> &dst, const Eigen::DenseBase<DERIVED> &src) const;\n\n  /**\n   * @brief\n   *\n   * @param[out] dst  Fourier coefficients in _centered zero-frequency_\n   * convention\n   * @param[in]  src  Ridgelet coefficients (real-valued)\n   */\n  template <typename DERIVED>\n  void irt(Eigen::DenseBase<DERIVED> &dst, const std::vector<rt_coeff_t> &src) const;\n\n  template <typename DERIVED>\n  void irt(Eigen::DenseBase<DERIVED> &dst, const RidgeletCellArray<rt_coeff_t> &src) const;\n\n  const rt_frame_t &frame() const { return rt_frame_; }\n\n private:\n  rt_frame_t rt_frame_;\n  // buffers\n  thread_local static ArrayBuffer<> buf1_;\n  thread_local static ArrayBuffer<> buf2_;\n};\n\ntemplate <typename NUMERIC_T, typename FRAME, typename FFT_TYPE>\nthread_local ArrayBuffer<> RT<NUMERIC_T, FRAME, FFT_TYPE>::buf1_;\n\ntemplate <typename NUMERIC_T, typename FRAME, typename FFT_TYPE>\nthread_local ArrayBuffer<> RT<NUMERIC_T, FRAME, FFT_TYPE>::buf2_;\n\n// --------------------------------------------------------------------------------\n// --------------------------------------------------------------------------------\ntemplate <typename NUMERIC_T, typename FRAME, typename FFT_TYPE>\nRT<NUMERIC_T, FRAME, FFT_TYPE> &\nRT<NUMERIC_T, FRAME, FFT_TYPE>::operator=(RT<NUMERIC_T, FRAME, FFT_TYPE> &&other)\n{\n  rt_frame_ = std::move(other.rt_frame_);\n}\n\ntemplate <typename NUMERIC_T, typename FRAME, typename FFT_TYPE>\nRT<NUMERIC_T, FRAME, FFT_TYPE> &\nRT<NUMERIC_T, FRAME, FFT_TYPE>::operator=(const RT<NUMERIC_T, FRAME, FFT_TYPE> &other)\n{\n  rt_frame_ = other.rt_frame_;\n}\n\ntemplate <typename NUMERIC_T, typename FRAME, typename FFT_TYPE>\ntemplate <typename DERIVED>\nvoid\nRT<NUMERIC_T, FRAME, FFT_TYPE>::rt(std::vector<rt_coeff_t> &dst,\n                                   const Eigen::DenseBase<DERIVED> &src) const\n{\n  static_assert(std::is_same<typename DERIVED::Scalar, complex_array_t::Scalar>::value,\n                \"type mismatch\");\n  const auto &lambdas = rt_frame_.lambdas();\n  fft_t fft;\n\n  const unsigned int rho_x = rt_frame_.rho_x();\n  const unsigned int rho_y = rt_frame_.rho_y();\n\n  for (int i = 0; i < lambdas.size(); ++i) {\n    auto &lambda = lambdas[i];\n\n    if (lambda.t == rt_type::S) {\n      auto &RF = rt_frame_.get_dense(lambda);\n      auto tmp = buf1_.get<complex_array_t>(RF.cols(), RF.rows());\n      tmp = ftcut(src, RF.rows(), RF.cols()).array() * RF;\n      fft.ift(dst[i], tmp);\n    } else {\n      // ridgelet coefficients are stored as sparse matrix\n      auto &RF = rt_frame_.get_sparse(lambda);\n      auto tmp = buf1_.get<complex_array_t>(RF.rows(), RF.cols());\n      internal::mtimes(tmp, RF, ftcut(src, RF.rows(), RF.cols()));\n      if (lambda.t == rt_type::X) {\n        auto tmp2 = buf2_.get<complex_array_t>(8 * rho_y, tmp.cols());\n        fold(tmp2, tmp, 8 * rho_y, 0);\n        fft.ift(dst[i], tmp2);\n      } else if (lambda.t == rt_type::Y) {\n        auto tmp2 = buf2_.get<complex_array_t>(tmp.rows(), 8 * rho_x);\n        fold(tmp2, tmp, 8 * rho_x, 1);\n        fft.ift(dst[i], tmp2);\n      } else if (lambda.t == rt_type::D) {\n        auto tmp2 = buf2_.get<complex_array_t>(8 * rho_y, tmp.cols());\n        fold(tmp2, tmp, 8 * rho_x, 0);\n        fft.ift(dst[i], tmp2);\n      } else {\n        assert(false);\n      }\n    }\n  }\n}\n\n// --------------------------------------------------------------------------------\ntemplate <typename NUMERIC_T, typename FRAME, typename FFT_TYPE>\ntemplate <typename DERIVED>\nvoid\nRT<NUMERIC_T, FRAME, FFT_TYPE>::rt(RidgeletCellArray<rt_coeff_t> &dst,\n                                   const Eigen::DenseBase<DERIVED> &src) const\n{\n  this->rt(dst.coeffs(), src);\n}\nnamespace local_ {\n\ntemplate <typename DERIVED, typename T>\nvoid\nadd_to_dst(Eigen::DenseBase<DERIVED> &dst, const Eigen::Map<T> &out)\n{\n  int right_nrows = out.rows();\n  int right_ncols = out.cols();\n  int nrows = dst.rows();\n  int ncols = dst.cols();\n  int row_offset = nrows / 2 - right_nrows / 2;\n  int col_offset = ncols / 2 - right_ncols / 2;\n  assert(row_offset >= 0);\n  assert(col_offset >= 0);\n  dst.block(row_offset, col_offset, right_nrows, right_ncols) += out;\n}\n\n}  // local_\n// --------------------------------------------------------------------------------\ntemplate <typename NUMERIC_T, typename FRAME, typename FFT_TYPE>\ntemplate <typename DERIVED>\nvoid\nRT<NUMERIC_T, FRAME, FFT_TYPE>::irt(Eigen::DenseBase<DERIVED> &dst,\n                                    const std::vector<rt_coeff_t> &src) const\n{\n  static_assert(std::is_same<typename DERIVED::Scalar, complex_array_t::Scalar>::value,\n                \"type mismatch\");\n\n  assert(dst.rows() == rt_frame_.Ny());\n  assert(dst.cols() == rt_frame_.Nx());\n\n  const auto &lambdas = rt_frame_.lambdas();\n\n  dst.setZero();\n  fft_t fft;\n\n  for (int i = 0; i < lambdas.size(); ++i) {\n    auto &lambda = lambdas[i];\n    const bool ft_scale = false;\n    auto f_tilde_hat = buf1_.get<complex_array_t>(src[i].rows(), src[i].cols());\n    fft.ft(f_tilde_hat, src[i], ft_scale);\n    if (lambda.t == rt_type::S) {\n      auto &ridge = rt_frame_.get_dense(lambda);\n      auto out = buf2_.get<complex_array_t>(ridge.rows(), ridge.cols());\n      out = f_tilde_hat * ridge;\n      local_::add_to_dst(dst.derived(), out);\n    } else if (lambda.t == rt_type::X) {\n      auto &ridge = rt_frame_.get_sparse(lambda);\n      auto tmp = buf2_.get<complex_array_t>(ridge.rows(), ridge.cols());\n      unfold(tmp, f_tilde_hat, ridge.rows(), 0);\n      auto out = buf1_.get<complex_array_t>(ridge.rows(), ridge.cols());\n      internal::mtimes(out, ridge, tmp);\n      local_::add_to_dst(dst.derived(), out);\n    } else if (lambda.t == rt_type::Y) {\n      auto &ridge = rt_frame_.get_sparse(lambda);\n      auto tmp = buf2_.get<complex_array_t>(ridge.rows(), ridge.cols());\n      unfold(tmp, f_tilde_hat, ridge.cols(), 1);\n      auto out = buf1_.get<complex_array_t>(ridge.rows(), ridge.cols());\n      internal::mtimes(out, ridge, tmp);\n      local_::add_to_dst(dst.derived(), out);\n    } else if (lambda.t == rt_type::D) {\n      auto &ridge = rt_frame_.get_sparse(lambda);\n      auto tmp = buf2_.get<complex_array_t>(ridge.rows(), ridge.cols());\n      unfold(tmp, f_tilde_hat, ridge.rows(), 0);\n      auto out = buf1_.get<complex_array_t>(ridge.rows(), ridge.cols());\n      internal::mtimes(out, ridge, tmp);\n      local_::add_to_dst(dst.derived(), out);\n    }\n  }\n}\n\n// --------------------------------------------------------------------------------\ntemplate <typename NUMERIC_T, typename FRAME, typename FFT_TYPE>\ntemplate <typename DERIVED>\nvoid\nRT<NUMERIC_T, FRAME, FFT_TYPE>::irt(Eigen::DenseBase<DERIVED> &dst,\n                                    const RidgeletCellArray<rt_coeff_t> &src) const\n{\n  this->irt(dst, src.coeffs());\n}\n", "meta": {"hexsha": "523915f0c9957d04ad39f28aaba931d6fc3b14af", "size": 9576, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ridgelet/rt.hpp", "max_stars_repo_name": "simonpp/2dRidgeletBTE", "max_stars_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T03:15:56.000Z", "max_issues_repo_path": "ridgelet/rt.hpp", "max_issues_repo_name": "simonpp/2dRidgeletBTE", "max_issues_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ridgelet/rt.hpp", "max_forks_repo_name": "simonpp/2dRidgeletBTE", "max_forks_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-08T03:15:56.000Z", "avg_line_length": 32.6825938567, "max_line_length": 94, "alphanum_fraction": 0.6130952381, "num_tokens": 2573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.26176483855874816}}
{"text": "#include \"b18TrafficJohnson.h\"\n\n#include <boost/graph/johnson_all_pairs_shortest.hpp>\n#include <boost/graph/exterior_property.hpp>\n#include <iostream>\n#include <fstream>\nusing namespace std;\n#include \"src/linux_host_memory_logger.h\"\n\n#define ROUTE_DEBUG 0\n//#define DEBUG_JOHNSON 0\n\nnamespace LC {\n\n\n////////////////\n/////////////////////////////\nusing namespace boost;\n\ninline bool fileExists(const std::string& fileName) {\n  std::ifstream f(fileName.c_str());\n  return f.good();\n}\n\ntypedef exterior_vertex_property<RoadGraph::roadBGLGraph_BI, float>\nDistanceProperty;\ntypedef DistanceProperty::matrix_type DistanceMatrix;\ntypedef DistanceProperty::matrix_map_type DistanceMatrixMap;\n\nvoid B18TrafficJohnson::generateRoutes(\n    LC::RoadGraph::roadBGLGraph_BI &roadGraph,\n    std::vector<B18TrafficPerson> &trafficPersonVec,\n    std::vector<uint>& indexPathVec,\n    std::map<RoadGraph::roadGraphEdgeDesc_BI, uint> &edgeDescToLaneMapNum,\n    int weigthMode, float sample) {\n  if (trafficPersonVec.empty()) {\n    printf(\"ERROR generateRoutes: people empty\");\n    return;\n  }\n\n  printf(\">> generatePathRoutes\\n\");\n  QTime timer;\n  timer.start();\n  \n  uint currIndexPath = 0;\n  std::vector<uint> oldIndexPathVec = indexPathVec; // std::move(indexPathVec); // avoid copying\n  indexPathVec.clear(); // = std::vector<uint>();\n\n  // 1. Update weight edges\n  printf(\">> generateRoutes Update weight edges\\n\");\n  int numEdges = 0;\n  property_map<RoadGraph::roadBGLGraph_BI, float RoadGraphEdge::*>::type\n    weight_pmap = boost::get(&RoadGraphEdge::edge_weight, roadGraph);\n\n  RoadGraph::roadGraphEdgeIter_BI ei, eiEnd;\n  float minTravelTime = FLT_MAX;\n  float maxTravelTime = -FLT_MAX;\n  float minLength = FLT_MAX;\n  float maxLength = -FLT_MAX;\n  float minSpeed = FLT_MAX;\n  float maxSpeed = -FLT_MAX;\n  for (boost::tie(ei, eiEnd) = boost::edges(roadGraph); ei != eiEnd; ++ei) {\n    numEdges++;\n    if ((edgeDescToLaneMapNum.size() > 20) && (numEdges % (edgeDescToLaneMapNum.size() / 20)) == 0) {\n      printf(\"Edge %d of %d (%2.0f%%)\\n\", numEdges, edgeDescToLaneMapNum.size(), (100.0f * numEdges) / edgeDescToLaneMapNum.size());\n    }\n    if (roadGraph[*ei].numberOfLanes > 0) {\n      float speed;\n      if (weigthMode == 0 || roadGraph[*ei].averageSpeed.size() <= 0) {\n        speed = roadGraph[*ei].maxSpeedMperSec;//(p0-p1).length();\n\n      } else {\n        // Use the avarage speed sampled in a former step\n        float avOfAv = 0;\n        for (int avOfAvN = 0; avOfAvN < roadGraph[*ei].averageSpeed.size(); avOfAvN++) {\n          avOfAv += roadGraph[*ei].averageSpeed[avOfAvN];\n        }\n        speed = avOfAv / roadGraph[*ei].averageSpeed.size();\n      }\n      float travelTime = roadGraph[*ei].edgeLength / speed;\n      roadGraph[*ei].edge_weight = travelTime;\n      weight_pmap[*ei] = travelTime;\n\n      minTravelTime = minTravelTime>travelTime ? travelTime : minTravelTime;\n      maxTravelTime = maxTravelTime < travelTime ? travelTime : maxTravelTime;\n\n      minLength = minLength > roadGraph[*ei].edgeLength ? roadGraph[*ei].edgeLength : minLength;\n      maxLength = maxLength < roadGraph[*ei].edgeLength ? roadGraph[*ei].edgeLength : maxLength;\n\n      minSpeed = minSpeed > speed ? speed : minSpeed;\n      maxSpeed = maxSpeed < speed ? speed : maxSpeed;\n    } else {\n      roadGraph[*ei].edge_weight =\n        100000000.0; //FLT_MAX;// if it has not lines, then the weight is inf\n    }\n  }\n  printf(\"Travel time Min: %f Max: %f\\n\", minTravelTime, maxTravelTime);\n  printf(\"Length Min: %f Max: %f\\n\", minLength, maxLength);\n  printf(\"Speed Min: %f Max: %f\\n\", minSpeed, maxSpeed);\n\n  //2. Generate route for each person\n  printf(\">> generateRoutesGenerate\\n\");\n  int numVertex = boost::num_vertices(roadGraph);\n  //vertex\n  typedef LC::RoadGraph::roadGraphVertexDesc_BI VertexDescriptor;\n  typedef std::map<VertexDescriptor, size_t> VertexIndexMap;\n  VertexIndexMap mapVertexIndex;\n  boost::associative_property_map<VertexIndexMap> pmVertexIndex(mapVertexIndex);\n\n  DistanceMatrix distances(numVertex);\n  DistanceMatrixMap dm(distances, roadGraph);\n\n\n  ////////////////////////\n  // CALL JOHNSON\n  //const bool tryReadWriteFirstJohnsonArray = false;\n  const bool tryReadWriteFirstJohnsonArray = weigthMode == 0;\n  std::string fileName = \"johnson_numVertex_\" + std::to_string(numVertex) + \"_maxTravelTime_\" + std::to_string(maxTravelTime) + \".bin\"; // encode num vertext and travel time to \"check\" is the same input\n  bool johnsonReadCorrectly = false;\n  if (tryReadWriteFirstJohnsonArray && fileExists(fileName)) {\n    printf(\"Loading Johnson...\\n\");\n    // if exists try to read.\n    std::ifstream in(fileName, std::ios::in | std::ios::binary);\n    for (int vN = 0; vN < numVertex; vN++) {\n      in.read((char *) &dm[vN][0], numVertex * sizeof(float));\n    }\n    printf(\"Johnson Loaded\\n\");\n    johnsonReadCorrectly = true;\n  }\n\n  // Run Johnson since we could not find it or it is not the first iteration\n  if (johnsonReadCorrectly == false) {\n    printf(\"Call Johnson\\n\");\n    memory_logger.ChangeMessageTo(\"Computing Johnson\");\n    boost::johnson_all_pairs_shortest_paths(roadGraph, dm, weight_map(weight_pmap));\n    memory_logger.ChangeMessageTo(\"Storing Johnson\");\n    if (tryReadWriteFirstJohnsonArray) {\n      // write to file\n      printf(\"Johnson start writing...\\n\");\n      std::ofstream out(fileName, std::ios::out | std::ios::binary);\n      if (!out) {\n        printf(\"ERROR: Tried to save %s but failed\\n\", fileName.c_str());\n      } else {\n        for (int vN = 0; vN < numVertex; vN++) {\n          out.write((char *) &dm[vN][0], numVertex * sizeof(float));\n        }\n        printf(\"Johnson saved to file: %s\\n\", fileName.c_str());\n      }\n    }\n  }\n  memory_logger.ChangeMessageTo(\"End\");\n\n  #ifdef DEBUG_JOHNSON\n  std::cerr << std::fixed << std::setprecision(2);\n  for (int i = 0; i < numVertex; i++) {\n    for (int j = 0; j < numVertex; j++) {\n      std::cerr << \" \" << std::setw(10) << dm[i][j];\n    }\n    std::cerr << std::endl;\n  }\n  #endif\n  \n  printf(\"Create Johnson numVertex %d Time %d ms\\n\", numVertex, timer.elapsed());\n\n  ////////////////////////\n  // Create routes\n  uint noAccesible = 0;\n  uint sameSrcDst = 0;\n  QTime timer2;\n  timer2.start();\n  const int kMaxNumPath = 250;\n\n  for (int p = 0; p < trafficPersonVec.size(); p++) {\n    if (trafficPersonVec.size() > 200) {\n      if ((p % (trafficPersonVec.size() / 20)) == 0) {\n        printf(\"Route %d of %d (%2.0f%%)\\n\", p, trafficPersonVec.size(), (100.0f * p) / trafficPersonVec.size());\n      }\n    }\n\n    ////////////////////////////////////////////////////////////////////////////////////////////\n    // Some people do not change route.\n    if (sample != 1.0f) {\n      if (sample > (((float) qrand()) / RAND_MAX)) { // not recalculate\n        printf(\"Person %d does not change route\\n\", p);\n        // Copy route directly\n        uint oldIndex = trafficPersonVec[p].indexPathInit;\n        trafficPersonVec[p].indexPathInit = currIndexPath;\n        uint index = 0;\n        while (oldIndexPathVec[oldIndex + index] != -1) {\n          indexPathVec.push_back(oldIndexPathVec.at(oldIndex + index));\n          currIndexPath++;\n          index++;\n        }\n        indexPathVec.push_back(-1);\n        currIndexPath++;\n        continue;\n      }\n    }\n\n    ////////////////////////////////////////////////////////////////////////////////////////////\n    trafficPersonVec[p].indexPathInit = currIndexPath;\n\n    LC::RoadGraph::roadGraphVertexDesc_BI srcvertex = trafficPersonVec[p].init_intersection;\n    LC::RoadGraph::roadGraphVertexDesc_BI tgtvertex = trafficPersonVec[p].end_intersection;\n\n    // check whether source same than target (we have arrived)\n    if (tgtvertex == srcvertex) {\n      //trafficPersonVec[p].indexPathInit = 0; // that index points to -1\n      indexPathVec.push_back(-1);\n      currIndexPath++;\n      sameSrcDst++;\n      continue;\n    }\n\n    // check if accesible\n    if (dm[srcvertex][tgtvertex] == (std::numeric_limits < float >::max)()) {\n      //trafficPersonVec[p].indexPathInit = 0; // that index points to -1\n      indexPathVec.push_back(-1);\n      currIndexPath++;\n      noAccesible++;\n      continue;\n    }\n\n    // find path\n    LC::RoadGraph::roadGraphVertexDesc_BI currvertex = srcvertex;//init\n    RoadGraph::out_roadGraphEdgeIter_BI Oei, Oei_end;\n    LC::RoadGraph::roadGraphVertexDesc_BI srcPosEdgeV, tgtPosEdgeV;\n\n    int currIndex = 0;\n\n    while (currvertex != tgtvertex) {\n      // check all outedges from currvertex which one continues to shortest path\n      bool cont = false;\n\n      for (boost::tie(Oei, Oei_end) = boost::out_edges(currvertex, roadGraph); Oei != Oei_end; ++Oei) {\n        srcPosEdgeV = boost::source(*Oei, roadGraph);\n        tgtPosEdgeV = boost::target(*Oei, roadGraph);\n\n        if (std::abs<float>(dm[currvertex][tgtPosEdgeV] + dm[tgtPosEdgeV][tgtvertex] - dm[currvertex][tgtvertex]) < 0.1f) {  // link found\n          std::pair<RoadGraph::roadGraphEdgeDesc_BI, bool> edge_pair = boost::edge(srcPosEdgeV, tgtPosEdgeV, roadGraph);\n\n          if (edge_pair.second == false) {\n            printf(\"****edge not found\\n\");//this should not happen\n            currvertex = tgtPosEdgeV;\n            break;//break for\n          } else {\n            if (edgeDescToLaneMapNum.find(edge_pair.first) == edgeDescToLaneMapNum.end()) {\n              printf(\"****Unknown edge\\n\");//this should not happen\n              currvertex = tgtvertex;//end loop\n              break;//break for\n            }\n\n            uint lane = edgeDescToLaneMapNum[edge_pair.first];\n            indexPathVec.push_back(lane);\n            currIndexPath++;\n            currIndex++;  // this person number jumps.\n\n            if (currIndex >= kMaxNumPath - 1) {  // This is very uncommon (just finish person).\n              // printf(\"currIndex > 250\\n\");\n              currvertex = tgtvertex;//end loop\n              break;//break for\n            }\n\n            currvertex = tgtPosEdgeV;\n            cont = true;\n            break;//break for\n          }\n        }\n      }\n\n      if (cont == true) {\n        continue;\n      }\n\n      // not foudn edge\n      //printf(\"****none edge works or > 250\\n\");  //this should not happen\n      //exit(0);//!!! REMOVE\n      break;\n    }//while find tgt\n\n    indexPathVec.push_back(-1);\n    currIndexPath++;\n    ////////////////////////////////////////////////////////////////////////////////////////////\n  }\n printf(\"Final Path Size %u\\n\", currIndexPath);\n  for (int p = 0; p < trafficPersonVec.size(); p++) {\n    trafficPersonVec[p].indexPathCurr = trafficPersonVec[p].indexPathInit;\n  }\n\n  std::cerr\n    << \"Finished with Johnson routing:\" << std::endl\n    << \"- No accesible ODs: \" << noAccesible << std::endl\n    << \"- Sames src dst ODs: \" << sameSrcDst << std::endl\n    << \"- Shortest path length (distance -> amount of ODs): \" << std::endl;\n\n  std::vector<int> amountOfEdges(300, 0);\n  for (const auto p : trafficPersonVec) {\n    int d = 0;\n    int cur = p.indexPathInit;\n    while (indexPathVec.at(cur) != -1) { cur++; d++; }\n    amountOfEdges.at(d)++;\n  }\n  for (int i = 0; i < 300; i++) {\n    if (amountOfEdges.at(i) != 0)\n      std::cerr << '\\t' << i << \" -> \" << amountOfEdges.at(i) << std::endl;\n  }\n\n\n  #ifdef DEBUG_JOHNSON\n  std::cerr << \"indexPathVec: \" << std::endl;\n  int i = 0;\n  for (const auto x : indexPathVec) {\n    std::cerr << i++ << \" \" << x << \" \" << std::endl;\n  }\n  std::cerr << \"trafficPersonVec: \" << std::endl;\n  for (const auto p : trafficPersonVec) {\n    std::cerr << p.indexPathInit << \" \" << p.indexPathCurr << std::endl;\n  }\n  #endif\n\n}\n\n\n}  // Closing namespace LC\n\n", "meta": {"hexsha": "6ffc299ca6ed61644df6cb3034749983b5076bc1", "size": 11552, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "LivingCity/traffic/b18TrafficJohnson.cpp", "max_stars_repo_name": "pavyedav/manta", "max_stars_repo_head_hexsha": "575d4395ad8a6000e8ca1de8c450fad2a541f19b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-08-12T12:45:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T03:05:00.000Z", "max_issues_repo_path": "LivingCity/traffic/b18TrafficJohnson.cpp", "max_issues_repo_name": "pavyedav/manta", "max_issues_repo_head_hexsha": "575d4395ad8a6000e8ca1de8c450fad2a541f19b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2020-08-19T18:19:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:55:34.000Z", "max_forks_repo_path": "LivingCity/traffic/b18TrafficJohnson.cpp", "max_forks_repo_name": "pavyedav/manta", "max_forks_repo_head_hexsha": "575d4395ad8a6000e8ca1de8c450fad2a541f19b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-06-05T03:40:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T01:55:02.000Z", "avg_line_length": 35.4355828221, "max_line_length": 202, "alphanum_fraction": 0.6134868421, "num_tokens": 3099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.26175661644444137}}
{"text": "/*\n\nCopyright (c) 2005-2022, University of Oxford.\nAll rights reserved.\n\nUniversity of Oxford means the Chancellor, Masters and Scholars of the\nUniversity of Oxford, having an administrative office at Wellington\nSquare, Oxford OX1 2JD, UK.\n\nThis file is part of Chaste.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n * Neither the name of the University of Oxford nor the names of its\n   contributors may be used to endorse or promote products derived from this\n   software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\nGOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\nOF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n\n\n#ifndef ABSTRACTBACKWARDEULERCARDIACCELL_HPP_\n#define ABSTRACTBACKWARDEULERCARDIACCELL_HPP_\n\n#include <cassert>\n#include <cmath>\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n#include \"ClassIsAbstract.hpp\"\n\n#include \"AbstractCardiacCell.hpp\"\n#include \"Exception.hpp\"\n#include \"PetscTools.hpp\"\n#include \"TimeStepper.hpp\"\n\n/**\n * This is the base class for cardiac cells solved using a (decoupled) backward\n * Euler approach (see http://dx.doi.org/10.1109/TBME.2006.879425).\n *\n * The basic approach to solving such models is:\n *  \\li Update the transmembrane potential, either from solving an external PDE,\n *      or using a forward Euler step.\n *  \\li Update any gating variables (or similar) using a backward euler step.\n *      Suitable ODEs can be written in the form  \\f$du/dt = g(V) + h(V)*u\\f$.  The update\n *      expression is then \\f$u_n = ( u_{n-1} + g(V_n)*dt ) / ( 1 - h(V_n)*dt )\\f$.\n *  \\li Update the remaining state variables using Newton's method to solve the\n *      nonlinear system \\f$U_n - U_{n-1} = dt*F(U_n, V_n)\\f$.\n *      The template parameter to the class specifies the size of this nonlinear system.\n */\ntemplate<unsigned SIZE>\nclass AbstractBackwardEulerCardiacCell : public AbstractCardiacCell\n{\n    private:\n    /** Needed for serialization. */\n    friend class boost::serialization::access;\n    /**\n     * Archive the member variables.\n     *\n     * @param archive\n     * @param version\n     */\n    template<class Archive>\n    void serialize(Archive & archive, const unsigned int version)\n    {\n        // This calls serialize on the base class.\n        archive & boost::serialization::base_object<AbstractCardiacCell>(*this);\n    }\npublic:\n\n    /**\n     * Standard constructor for a cell.\n     *\n     * @param numberOfStateVariables  the size of the ODE system\n     * @param voltageIndex  the index of the variable representing the transmembrane\n     *     potential within the state variable vector\n     * @param pIntracellularStimulus  the intracellular stimulus function\n     *\n     * Some notes for future reference:\n     *  \\li We may want to remove the timestep from this class, and instead pass it to\n     *      the Compute* methods, especially if variable timestepping is to be used.\n     *  \\li It's a pity that inheriting from AbstractCardiacCell forces us to store a\n     *      null pointer (for the unused ODE solver) in every instance.  We may want\n     *      to revisit this design decision at a later date.\n     */\n    AbstractBackwardEulerCardiacCell(\n        unsigned numberOfStateVariables,\n        unsigned voltageIndex,\n        boost::shared_ptr<AbstractStimulusFunction> pIntracellularStimulus);\n\n    /** Virtual destructor */\n    virtual ~AbstractBackwardEulerCardiacCell();\n\n    /**\n     * Compute the residual of the nonlinear system portion of the cell model.\n     *\n     * @param time  the current time\n     * @param rCurrentGuess  the current guess for \\f$U_n\\f$\n     * @param rResidual  to be filled in with the residual vector\n     */\n    virtual void ComputeResidual(double time, const double rCurrentGuess[SIZE], double rResidual[SIZE])=0;\n\n    /**\n     * Compute the Jacobian matrix for the nonlinear system portion of the cell model.\n     *\n     * @param time  the current time\n     * @param rCurrentGuess  the current guess for \\f$U_n\\f$\n     * @param rJacobian  to be filled in with the Jacobian matrix\n     */\n    virtual void ComputeJacobian(double time, const double rCurrentGuess[SIZE], double rJacobian[SIZE][SIZE])=0;\n\n    /**\n     * Simulates this cell's behaviour between the time interval [tStart, tEnd],\n     * with timestep #mDt.  Uses a forward Euler step to update the transmembrane\n     * potential at each timestep.\n     *\n     * The length of the time interval must be a multiple of the timestep.\n     *\n     * @param tStart  beginning of the time interval to simulate\n     * @param tEnd  end of the time interval to simulate\n     * @param tSamp  sampling interval for returned results (defaults to #mDt)\n     * @return  the values of each state variable, at intervals of tSamp.\n     */\n    OdeSolution Compute(double tStart, double tEnd, double tSamp=0.0);\n\n    /**\n     * Simulates this cell's behaviour between the time interval [tStart, tEnd],\n     * with timestep #mDt.  The transmembrane potential is kept fixed throughout.\n     *\n     * The length of the time interval must be a multiple of the timestep.\n     *\n     * @param tStart  beginning of the time interval to simulate\n     * @param tEnd  end of the time interval to simulate\n     */\n    void ComputeExceptVoltage(double tStart, double tEnd);\n\n    /**\n     * Simulate this cell's behaviour between the time interval [tStart, tEnd],\n     * with timestemp #mDt, updating the internal state variable values.\n     *\n     * @param tStart  beginning of the time interval to simulate\n     * @param tEnd  end of the time interval to simulate\n     */\n    void SolveAndUpdateState(double tStart, double tEnd);\n\nprivate:\n// LCOV_EXCL_START\n    /**\n     * This function should never be called - the cell class incorporates its own solver.\n     *\n     * @param time\n     * @param rY\n     * @param rDY\n     */\n    void EvaluateYDerivatives(double time, const std::vector<double> &rY, std::vector<double> &rDY)\n    {\n        NEVER_REACHED;\n    }\n// LCOV_EXCL_STOP\n\nprotected:\n    /**\n     * Compute the values of all state variables, except the voltage, using backward Euler,\n     * for one timestep from tStart.\n     *\n     * \\note This method must be provided by subclasses.\n     *\n     * @param tStart  start of this timestep\n     */\n    virtual void ComputeOneStepExceptVoltage(double tStart)=0;\n\n    /**\n     * Perform a forward Euler step to update the transmembrane potential.\n     *\n     * \\note This method must be provided by subclasses.\n     *\n     * @param time  start of this timestep\n     */\n    virtual void UpdateTransmembranePotential(double time)=0;\n};\n\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n/*\n * NOTE: Explicit instantiation is not used for this class, because the SIZE\n * template parameter could take arbitrary values.\n */\n\n\ntemplate <unsigned SIZE>\nAbstractBackwardEulerCardiacCell<SIZE>::AbstractBackwardEulerCardiacCell(\n    unsigned numberOfStateVariables,\n    unsigned voltageIndex,\n    boost::shared_ptr<AbstractStimulusFunction> pIntracellularStimulus)\n        : AbstractCardiacCell(boost::shared_ptr<AbstractIvpOdeSolver>(),\n                              numberOfStateVariables,\n                              voltageIndex,\n                              pIntracellularStimulus)\n{}\n\ntemplate <unsigned SIZE>\nAbstractBackwardEulerCardiacCell<SIZE>::~AbstractBackwardEulerCardiacCell()\n{}\n\ntemplate <unsigned SIZE>\nOdeSolution AbstractBackwardEulerCardiacCell<SIZE>::Compute(double tStart, double tEnd, double tSamp)\n{\n    // In this method, we iterate over timesteps, doing the following for each:\n    //   - update V using a forward Euler step\n    //   - call ComputeExceptVoltage(t) to update the remaining state variables\n    //     using backward Euler\n\n    // Check length of time interval\n    if (tSamp < mDt)\n    {\n        tSamp = mDt;\n    }\n    double _n_steps = (tEnd - tStart) / tSamp;\n    const unsigned n_steps = (unsigned) floor(_n_steps+0.5);\n    assert(fabs(tStart+n_steps*tSamp - tEnd) < 1e-12);\n    const unsigned n_small_steps = (unsigned) floor(tSamp/mDt+0.5);\n    assert(fabs(mDt*n_small_steps - tSamp) < 1e-12);\n\n    // Initialise solution store\n    OdeSolution solutions;\n    solutions.SetNumberOfTimeSteps(n_steps);\n    solutions.rGetSolutions().push_back(rGetStateVariables());\n    solutions.rGetTimes().push_back(tStart);\n    solutions.SetOdeSystemInformation(this->mpSystemInfo);\n\n    // Loop over time\n    double curr_time = tStart;\n    for (unsigned i=0; i<n_steps; i++)\n    {\n        for (unsigned j=0; j<n_small_steps; j++)\n        {\n            curr_time = tStart + i*tSamp + j*mDt;\n\n            // Compute next value of V\n            UpdateTransmembranePotential(curr_time);\n\n            // Compute other state variables\n            ComputeOneStepExceptVoltage(curr_time);\n\n            // check gating variables are still in range\n            VerifyStateVariables();\n        }\n\n        // Update solutions\n        solutions.rGetSolutions().push_back(rGetStateVariables());\n        solutions.rGetTimes().push_back(curr_time+mDt);\n    }\n\n    return solutions;\n}\n\ntemplate <unsigned SIZE>\nvoid AbstractBackwardEulerCardiacCell<SIZE>::ComputeExceptVoltage(double tStart, double tEnd)\n{\n    // This method iterates over timesteps, calling ComputeExceptVoltage(t) at\n    // each one, to update all state variables except for V, using backward Euler.\n\n    // Check length of time interval\n    unsigned n_steps = (unsigned)((tEnd - tStart) / mDt + 0.5);\n    assert(fabs(tStart + n_steps*mDt - tEnd) < 1e-12);\n\n    // Loop over time\n    double curr_time;\n    for (unsigned i=0; i<n_steps; i++)\n    {\n        curr_time = tStart + i*mDt;\n\n        // Compute other state variables\n        ComputeOneStepExceptVoltage(curr_time);\n\n#ifndef NDEBUG\n        // Check gating variables are still in range\n        VerifyStateVariables();\n#endif // NDEBUG\n    }\n}\n\ntemplate<unsigned SIZE>\nvoid AbstractBackwardEulerCardiacCell<SIZE>::SolveAndUpdateState(double tStart, double tEnd)\n{\n    TimeStepper stepper(tStart, tEnd, mDt);\n\n    while (!stepper.IsTimeAtEnd())\n    {\n        double time = stepper.GetTime();\n\n        // Compute next value of V\n        UpdateTransmembranePotential(time);\n\n        // Compute other state variables\n        ComputeOneStepExceptVoltage(time);\n\n        // check gating variables are still in range\n        VerifyStateVariables();\n\n        stepper.AdvanceOneTimeStep();\n    }\n}\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Specialization for the case where there are no non-linear ODEs in the model.\n */\ntemplate<>\nclass AbstractBackwardEulerCardiacCell<0u> : public AbstractCardiacCell\n{\nprivate:\n    /** Needed for serialization. */\n    friend class boost::serialization::access;\n    /**\n     * Archive the member variables.\n     *\n     * @param archive\n     * @param version\n     */\n    template<class Archive>\n    void serialize(Archive & archive, const unsigned int version)\n    {\n        // This calls serialize on the base class.\n        archive & boost::serialization::base_object<AbstractCardiacCell>(*this);\n    }\n\npublic:\n    /**\n     * Standard constructor for a cell.\n     *\n     * @param numberOfStateVariables  the size of the ODE system\n     * @param voltageIndex  the index of the variable representing the transmembrane\n     *     potential within the state variable vector\n     * @param pIntracellularStimulus  the intracellular stimulus function\n     */\n    AbstractBackwardEulerCardiacCell(unsigned numberOfStateVariables,\n                                     unsigned voltageIndex,\n                                     boost::shared_ptr<AbstractStimulusFunction> pIntracellularStimulus)\n        : AbstractCardiacCell(boost::shared_ptr<AbstractIvpOdeSolver>(),\n                              numberOfStateVariables,\n                              voltageIndex,\n                              pIntracellularStimulus)\n    {}\n\n    /** Virtual destructor */\n    virtual ~AbstractBackwardEulerCardiacCell()\n    {}\n\n    /**\n     * Simulates this cell's behaviour between the time interval [tStart, tEnd],\n     * with timestep #mDt.  Uses a forward Euler step to update the transmembrane\n     * potential at each timestep.\n     *\n     * The length of the time interval must be a multiple of the timestep.\n     *\n     * @param tStart  beginning of the time interval to simulate\n     * @param tEnd  end of the time interval to simulate\n     * @param tSamp  sampling interval for returned results (defaults to #mDt)\n     * @return  the values of each state variable, at intervals of tSamp.\n     */\n    OdeSolution Compute(double tStart, double tEnd, double tSamp=0.0)\n    {\n        // In this method, we iterate over timesteps, doing the following for each:\n        //   - update V using a forward Euler step\n        //   - call ComputeExceptVoltage(t) to update the remaining state variables\n        //     using backward Euler\n\n        // Check length of time interval\n        if (tSamp < mDt)\n        {\n            tSamp = mDt;\n        }\n        double _n_steps = (tEnd - tStart) / tSamp;\n        const unsigned n_steps = (unsigned) floor(_n_steps+0.5);\n        assert(fabs(tStart+n_steps*tSamp - tEnd) < 1e-12);\n        const unsigned n_small_steps = (unsigned) floor(tSamp/mDt+0.5);\n        assert(fabs(mDt*n_small_steps - tSamp) < 1e-12);\n\n        // Initialise solution store\n        OdeSolution solutions;\n        solutions.SetNumberOfTimeSteps(n_steps);\n        solutions.rGetSolutions().push_back(rGetStateVariables());\n        solutions.rGetTimes().push_back(tStart);\n        solutions.SetOdeSystemInformation(this->mpSystemInfo);\n\n        // Loop over time\n        double curr_time = tStart;\n        for (unsigned i=0; i<n_steps; i++)\n        {\n            for (unsigned j=0; j<n_small_steps; j++)\n            {\n                curr_time = tStart + i*tSamp + j*mDt;\n\n                // Compute next value of V\n                UpdateTransmembranePotential(curr_time);\n\n                // Compute other state variables\n                ComputeOneStepExceptVoltage(curr_time);\n\n                // check gating variables are still in range\n                VerifyStateVariables();\n            }\n\n            // Update solutions\n            solutions.rGetSolutions().push_back(rGetStateVariables());\n            solutions.rGetTimes().push_back(curr_time+mDt);\n        }\n\n        return solutions;\n    }\n\n    /**\n     * Simulates this cell's behaviour between the time interval [tStart, tEnd],\n     * with timestep #mDt.  The transmembrane potential is kept fixed throughout.\n     *\n     * The length of the time interval must be a multiple of the timestep.\n     *\n     * @param tStart  beginning of the time interval to simulate\n     * @param tEnd  end of the time interval to simulate\n     */\n    void ComputeExceptVoltage(double tStart, double tEnd)\n    {\n        // This method iterates over timesteps, calling ComputeExceptVoltage(t) at\n        // each one, to update all state variables except for V, using backward Euler.\n\n        // Check length of time interval\n        unsigned n_steps = (unsigned)((tEnd - tStart) / mDt + 0.5);\n        assert(fabs(tStart + n_steps*mDt - tEnd) < 1e-12);\n\n        // Loop over time\n        double curr_time;\n        for (unsigned i=0; i<n_steps; i++)\n        {\n            curr_time = tStart + i*mDt;\n\n            // Compute other state variables\n            ComputeOneStepExceptVoltage(curr_time);\n\n#ifndef NDEBUG\n            // Check gating variables are still in range\n            VerifyStateVariables();\n#endif // NDEBUG\n        }\n    }\n\n    /**\n     * Simulate this cell's behaviour between the time interval [tStart, tEnd],\n     * with timestemp #mDt, updating the internal state variable values.\n     *\n     * @param tStart  beginning of the time interval to simulate\n     * @param tEnd  end of the time interval to simulate\n     */\n    void SolveAndUpdateState(double tStart, double tEnd)\n    {\n        TimeStepper stepper(tStart, tEnd, mDt);\n\n        while (!stepper.IsTimeAtEnd())\n        {\n            double time = stepper.GetTime();\n\n            // Compute next value of V\n            UpdateTransmembranePotential(time);\n\n            // Compute other state variables\n            ComputeOneStepExceptVoltage(time);\n\n            // Check gating variables are still in range\n            VerifyStateVariables();\n\n            stepper.AdvanceOneTimeStep();\n        }\n    }\n\nprivate:\n// LCOV_EXCL_START\n    /**\n     * This function should never be called - the cell class incorporates its own solver.\n     *\n     * @param time\n     * @param rY\n     * @param rDY\n     */\n    void EvaluateYDerivatives(double time, const std::vector<double> &rY, std::vector<double> &rDY)\n    {\n        NEVER_REACHED;\n    }\n// LCOV_EXCL_STOP\n\nprotected:\n    /**\n     * Compute the values of all state variables, except the voltage, using backward Euler,\n     * for one timestep from tStart.\n     *\n     * \\note This method must be provided by subclasses.\n     *\n     * @param tStart  start of this timestep\n     */\n    virtual void ComputeOneStepExceptVoltage(double tStart)=0;\n\n    /**\n     * Perform a forward Euler step to update the transmembrane potential.\n     *\n     * \\note This method must be provided by subclasses.\n     *\n     * @param time  start of this timestep\n     */\n    virtual void UpdateTransmembranePotential(double time)=0;\n};\n\n\n// Debugging\n#ifndef NDEBUG\n#include \"OutputFileHandler.hpp\"\n#include <boost/foreach.hpp>\ntemplate<unsigned SIZE>\nvoid DumpJacobianToFile(double time, const double rCurrentGuess[SIZE], double rJacobian[SIZE][SIZE],\n                        const std::vector<double>& rY)\n{\n    OutputFileHandler handler(\"DumpJacs\", false);\n    out_stream p_file = handler.OpenOutputFile(\"J.txt\", std::ios::app);\n    (*p_file) << \"At \" << time << \" \" << SIZE << std::endl;\n    (*p_file) << \"rY\";\n    BOOST_FOREACH(double y, rY)\n    {\n        (*p_file) << \" \" << y;\n    }\n    (*p_file) << std::endl;\n    (*p_file) << \"rCurrentGuess\";\n    for (unsigned i=0; i<SIZE; i++)\n    {\n        (*p_file) << \" \" << rCurrentGuess[i];\n    }\n    (*p_file) << std::endl;\n    (*p_file) << \"rJacobian\";\n    for (unsigned i=0; i<SIZE; i++)\n    {\n        for (unsigned j=0; j<SIZE; j++)\n        {\n            (*p_file) << \" \" << rJacobian[i][j];\n        }\n    }\n    (*p_file) << std::endl;\n}\n#endif\n\nTEMPLATED_CLASS_IS_ABSTRACT_1_UNSIGNED(AbstractBackwardEulerCardiacCell)\n\n#endif /*ABSTRACTBACKWARDEULERCARDIACCELL_HPP_*/\n", "meta": {"hexsha": "f5258645b30173870ab1699215a5bbaef58e1858", "size": 19856, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "heart/src/odes/AbstractBackwardEulerCardiacCell.hpp", "max_stars_repo_name": "stu-l/Chaste", "max_stars_repo_head_hexsha": "8efa8b440660553af66804067639f237c855f557", "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/odes/AbstractBackwardEulerCardiacCell.hpp", "max_issues_repo_name": "stu-l/Chaste", "max_issues_repo_head_hexsha": "8efa8b440660553af66804067639f237c855f557", "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/odes/AbstractBackwardEulerCardiacCell.hpp", "max_forks_repo_name": "stu-l/Chaste", "max_forks_repo_head_hexsha": "8efa8b440660553af66804067639f237c855f557", "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": 34.8350877193, "max_line_length": 112, "alphanum_fraction": 0.6469077357, "num_tokens": 4578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2617566164444413}}
{"text": "// This file is part of the dune-gdt project:\n//   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      (2017 - 2018)\n//   Tobias Leibner (2017)\n\n#ifndef DUNE_GDT_OPERATORS_FV_RECONSTRUCTION_LINEAR_HH\n#define DUNE_GDT_OPERATORS_FV_RECONSTRUCTION_LINEAR_HH\n\n#include <boost/multi_array.hpp>\n\n#include <dune/geometry/quadraturerules.hh>\n\n#include <dune/xt/common/fvector.hh>\n#include <dune/xt/common/lapacke.hh>\n#include <dune/xt/common/parallel/threadstorage.hh>\n#include <dune/xt/common/parameter.hh>\n\n#include <dune/xt/grid/walker.hh>\n\n#include <dune/xt/la/algorithms/qr.hh>\n#include <dune/xt/la/eigen-solver.hh>\n\n#include <dune/gdt/operators/interfaces.hh>\n\n#include \"../quadrature.hh\"\n#include \"reconstructed_function.hh\"\n#include \"slopelimiters.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace internal {\n\ntemplate <class AnalyticalFluxType, class MatrixImp, class VectorImp>\nclass JacobianWrapperBase\n{\npublic:\n  using MatrixType = MatrixImp;\n  using VectorType = VectorImp;\n  static constexpr size_t dimDomain = AnalyticalFluxType::dimDomain;\n  static constexpr size_t dimRange = AnalyticalFluxType::dimRange;\n  using DomainType = typename AnalyticalFluxType::DomainType;\n  using RangeFieldType = typename AnalyticalFluxType::RangeFieldType;\n  using EntityType = typename AnalyticalFluxType::EntityType;\n  using JacobianType = FieldVector<MatrixType, dimDomain>;\n  using StateRangeType = typename AnalyticalFluxType::StateRangeType;\n\n  JacobianWrapperBase()\n    : computed_(false)\n  {\n  }\n\n  virtual ~JacobianWrapperBase()\n  {\n  }\n\n  virtual void get_jacobian(const size_t dd,\n                            const EntityType& entity,\n                            const AnalyticalFluxType& analytical_flux,\n                            const DomainType& x_in_inside_coords,\n                            const StateRangeType& u,\n                            const XT::Common::Parameter& param) = 0;\n\n  virtual void get_jacobian(const EntityType& entity,\n                            const AnalyticalFluxType& analytical_flux,\n                            const DomainType& x_in_inside_coords,\n                            const StateRangeType& u,\n                            const XT::Common::Parameter& param) = 0;\n\n  virtual void compute(const size_t dd) = 0;\n\n  virtual void compute()\n  {\n    for (size_t dd = 0; dd < dimDomain; ++dd)\n      compute(dd);\n  }\n\n  virtual bool computed(const size_t dd) const\n  {\n    return computed_[dd];\n  }\n\n  virtual bool computed() const\n  {\n    for (size_t dd = 0; dd < dimDomain; ++dd)\n      if (!computed(dd))\n        return false;\n    return true;\n  }\n\n  virtual std::unique_ptr<JacobianType>& jacobian()\n  {\n    return jacobian_;\n  }\n\n  virtual const std::unique_ptr<JacobianType>& jacobian() const\n  {\n    return jacobian_;\n  }\n\n  virtual MatrixType& jacobian(const size_t dd)\n  {\n    return (*jacobian_)[dd];\n  }\n\n  virtual const MatrixType& jacobian(const size_t dd) const\n  {\n    return (*jacobian_)[dd];\n  }\n\n  virtual void apply_eigenvectors(const size_t dd, const VectorType& x, VectorType& ret) const = 0;\n\n  virtual void apply_inverse_eigenvectors(const size_t dd, const VectorType& x, VectorType& ret) const = 0;\n\nprotected:\n  template <class MatImp>\n  static XT::Common::Configuration create_eigensolver_opts()\n  {\n    using EigenSolverOptionsType = typename XT::LA::EigenSolverOptions<MatImp>;\n    using MatrixInverterOptionsType = typename XT::LA::MatrixInverterOptions<MatImp>;\n    XT::Common::Configuration eigensolver_options = EigenSolverOptionsType::options(EigenSolverOptionsType::types()[0]);\n    //    XT::Common::Configuration eigensolver_options = EigenSolverOptionsType::options(\"shifted_qr\");\n    eigensolver_options[\"assert_eigendecomposition\"] = \"1e-6\";\n    eigensolver_options[\"assert_real_eigendecomposition\"] = \"1e-6\";\n    eigensolver_options[\"disable_checks\"] =\n#ifdef NDEBUG\n        \"true\";\n#else\n        \"false\";\n#endif\n    XT::Common::Configuration matrix_inverter_options = MatrixInverterOptionsType::options();\n    matrix_inverter_options[\"post_check_is_left_inverse\"] = \"1e-6\";\n    matrix_inverter_options[\"post_check_is_right_inverse\"] = \"1e-6\";\n    eigensolver_options.add(matrix_inverter_options, \"matrix-inverter\");\n    return eigensolver_options;\n  } // ... create_eigensolver_opts()\n\n  std::unique_ptr<JacobianType> jacobian_;\n  FieldVector<bool, dimDomain> computed_;\n}; // class JacobianWrapperBase<...>\n\n\ntemplate <class AnalyticalFluxType,\n          class MatrixType = FieldMatrix<typename AnalyticalFluxType::RangeFieldType,\n                                         AnalyticalFluxType::dimRange,\n                                         AnalyticalFluxType::dimRange>,\n          class VectorType = FieldVector<typename AnalyticalFluxType::RangeFieldType, AnalyticalFluxType::dimRange>>\nclass JacobianWrapper : public JacobianWrapperBase<AnalyticalFluxType, MatrixType, VectorType>\n{\n  using BaseType = JacobianWrapperBase<AnalyticalFluxType, MatrixType, VectorType>;\n\nprotected:\n  using V = XT::Common::VectorAbstraction<VectorType>;\n  using M = XT::Common::MatrixAbstraction<MatrixType>;\n  using EigenSolverType = typename XT::LA::EigenSolver<MatrixType>;\n  using typename BaseType::RangeFieldType;\n\npublic:\n  static constexpr size_t dimDomain = AnalyticalFluxType::dimDomain;\n  static constexpr size_t dimRange = AnalyticalFluxType::dimRange;\n  using typename BaseType::JacobianType;\n  using typename BaseType::EntityType;\n  using typename BaseType::DomainType;\n  using typename BaseType::StateRangeType;\n\n  using BaseType::jacobian;\n\n  JacobianWrapper()\n    : work_(1)\n    , scale_(dimRange)\n    , rconde_(dimRange)\n    , rcondv_(dimRange)\n    , iwork_(2 * dimRange - 2)\n    , eigenvalues_(std::vector<RangeFieldType>(dimRange))\n    , tau_(V::create(dimRange))\n  {\n    jacobian() = std::make_unique<JacobianType>(eigenvectors_);\n#if HAVE_MKL || HAVE_LAPACKE\n    int ilo, ihi;\n    double norm;\n    if (M::storage_layout == XT::Common::StorageLayout::dense_row_major) {\n      // get optimal working size in work[0] (requested by lwork = -1)\n      int info = XT::Common::Lapacke::dgeevx_work(XT::Common::Lapacke::row_major(),\n                                                  /*both diagonally scale and permute*/ 'B',\n                                                  /*do_not_compute_left_eigenvectors:*/ 'N',\n                                                  /*compute_right_eigenvectors:*/ 'V',\n                                                  'N',\n                                                  static_cast<int>(dimRange),\n                                                  M::data(jacobian(0)),\n                                                  static_cast<int>(dimRange),\n                                                  &(eigenvalues_[0][0]),\n                                                  &(dummy_complex_eigenvalues_[0]),\n                                                  nullptr,\n                                                  static_cast<int>(dimRange),\n                                                  M::data(eigenvectors_[0]),\n                                                  static_cast<int>(dimRange),\n                                                  &ilo,\n                                                  &ihi,\n                                                  scale_.data(),\n                                                  &norm,\n                                                  rconde_.data(),\n                                                  rcondv_.data(),\n                                                  work_.data(),\n                                                  -1,\n                                                  iwork_.data());\n      if (info != 0)\n        DUNE_THROW(Dune::XT::LA::Exceptions::eigen_solver_failed, \"The lapack backend reported '\" << info << \"'!\");\n      work_.resize(work_[0]);\n    }\n#endif\n  }\n\n  virtual void get_jacobian(const size_t dd,\n                            const EntityType& entity,\n                            const AnalyticalFluxType& analytical_flux,\n                            const DomainType& x_in_inside_coords,\n                            const StateRangeType& u,\n                            const XT::Common::Parameter& param) override\n  {\n    analytical_flux.local_function(entity)->partial_u_col(dd, x_in_inside_coords, u, jacobian(dd), param);\n  }\n\n  virtual void get_jacobian(const EntityType& entity,\n                            const AnalyticalFluxType& analytical_flux,\n                            const DomainType& x_in_inside_coords,\n                            const StateRangeType& u,\n                            const XT::Common::Parameter& param) override\n  {\n    analytical_flux.local_function(entity)->partial_u(x_in_inside_coords, u, *jacobian(), param);\n  }\n\n  using BaseType::compute;\n\n  virtual void compute(const size_t dd) override\n  {\n    if (false) {\n      ;\n#if HAVE_MKL || HAVE_LAPACKE\n    } else if (M::storage_layout == XT::Common::StorageLayout::dense_row_major) {\n      int ilo, ihi;\n      double norm;\n      int info = XT::Common::Lapacke::dgeevx_work(XT::Common::Lapacke::row_major(),\n                                                  /*both diagonally scale and permute*/ 'B',\n                                                  /*do_not_compute_left_eigenvectors:*/ 'N',\n                                                  /*compute_right_eigenvectors:*/ 'V',\n                                                  'N',\n                                                  static_cast<int>(dimRange),\n                                                  M::data(jacobian(dd)),\n                                                  static_cast<int>(dimRange),\n                                                  eigenvalues_[dd].data(),\n                                                  &(dummy_complex_eigenvalues_[0]),\n                                                  nullptr,\n                                                  static_cast<int>(dimRange),\n                                                  M::data(eigenvectors_[dd]),\n                                                  static_cast<int>(dimRange),\n                                                  &ilo,\n                                                  &ihi,\n                                                  scale_.data(),\n                                                  &norm,\n                                                  rconde_.data(),\n                                                  rcondv_.data(),\n                                                  work_.data(),\n                                                  static_cast<int>(work_.size()),\n                                                  iwork_.data());\n      if (info != 0)\n        DUNE_THROW(Dune::XT::LA::Exceptions::eigen_solver_failed, \"The lapack backend reported '\" << info << \"'!\");\n#endif // HAVE_MKL || HAVE_LAPACKE\n    } else {\n      static auto eigensolver_options = BaseType::template create_eigensolver_opts<MatrixType>();\n      const auto eigensolver = EigenSolverType(jacobian(dd), &eigensolver_options);\n      eigenvectors_[dd] = eigensolver.real_eigenvectors();\n      eigenvalues_[dd] = eigensolver.real_eigenvalues();\n    }\n    QR_[dd] = eigenvectors_[dd];\n    XT::LA::qr(QR_[dd], tau_[dd], permutations_[dd]);\n    computed_[dd] = true;\n  }\n\n  virtual void apply_eigenvectors(const size_t dd, const VectorType& x, VectorType& ret) const override\n  {\n    eigenvectors_[dd].mv(x, ret);\n  }\n\n  virtual void apply_inverse_eigenvectors(const size_t dd, const VectorType& x, VectorType& ret) const override\n  {\n    VectorType work = V::create(dimRange);\n    XT::LA::solve_qr_factorized(QR_[dd], tau_[dd], permutations_[dd], ret, x, &work);\n  }\n\nprotected:\n  std::vector<RangeFieldType> work_, scale_, rconde_, rcondv_;\n  std::vector<int> iwork_;\n  using BaseType::computed_;\n  JacobianType eigenvectors_;\n  FieldVector<std::vector<RangeFieldType>, dimDomain> eigenvalues_;\n  FieldVector<RangeFieldType, dimRange> dummy_complex_eigenvalues_;\n  JacobianType QR_;\n  FieldVector<VectorType, dimDomain> tau_;\n  FieldVector<FieldVector<int, dimRange>, dimDomain> permutations_;\n}; // class JacobianWrapper<...>\n\n\ntemplate <class AnalyticalFluxType, size_t block_size = (AnalyticalFluxType::dimDomain == 1) ? 2 : 4>\nclass BlockedJacobianWrapper\n    : public JacobianWrapperBase<AnalyticalFluxType,\n                                 FieldVector<FieldMatrix<typename AnalyticalFluxType::RangeFieldType,\n                                                         block_size,\n                                                         block_size>,\n                                             AnalyticalFluxType::dimRange / block_size>,\n                                 typename AnalyticalFluxType::StateRangeType>\n{\n  using BaseType =\n      JacobianWrapperBase<AnalyticalFluxType,\n                          FieldVector<FieldMatrix<typename AnalyticalFluxType::RangeFieldType, block_size, block_size>,\n                                      AnalyticalFluxType::dimRange / block_size>,\n                          typename AnalyticalFluxType::StateRangeType>;\n\npublic:\n  using typename BaseType::RangeFieldType;\n  using BaseType::dimDomain;\n  using BaseType::dimRange;\n  static constexpr size_t num_blocks = dimRange / block_size;\n  static_assert(dimRange % block_size == 0, \"dimRange has to be a multiple of block_size\");\n  using LocalRangeType = FieldVector<RangeFieldType, block_size>;\n  using LocalMatrixType = FieldMatrix<RangeFieldType, block_size, block_size>;\n  using MatrixType = FieldVector<LocalMatrixType, num_blocks>;\n  using EigenSolverType = typename XT::LA::EigenSolver<LocalMatrixType>;\n  using typename BaseType::DomainType;\n  using typename BaseType::EntityType;\n  using typename BaseType::JacobianType;\n  using typename BaseType::StateRangeType;\n  using typename BaseType::VectorType;\n\n  BlockedJacobianWrapper()\n    : work_(1)\n  {\n    jacobian() = std::make_unique<JacobianType>();\n    nonblocked_jacobians_ = std::make_unique<FieldVector<FieldMatrix<RangeFieldType, dimRange, dimRange>, dimDomain>>();\n#if HAVE_MKL || HAVE_LAPACKE\n    // get optimal working size in work[0] (requested by lwork = -1)\n    int info = XT::Common::Lapacke::dgeev_work(XT::Common::Lapacke::row_major(),\n                                               /*do_not_compute_left_eigenvectors: */ 'N',\n                                               /*compute_right_eigenvectors: */ 'V',\n                                               static_cast<int>(block_size),\n                                               &(jacobian(0)[0][0][0]),\n                                               static_cast<int>(block_size),\n                                               &(eigenvalues_[0][0][0]),\n                                               &(dummy_complex_eigenvalues_[0]),\n                                               nullptr,\n                                               static_cast<int>(block_size),\n                                               &(jacobian(0)[0][0][0]),\n                                               static_cast<int>(block_size),\n                                               work_.data(),\n                                               -1);\n    if (info != 0)\n      DUNE_THROW(Dune::XT::LA::Exceptions::eigen_solver_failed, \"The lapack backend reported '\" << info << \"'!\");\n    work_.resize(work_[0]);\n#endif\n  }\n\n  using BaseType::jacobian;\n  using BaseType::compute;\n\n  virtual void compute(const size_t dd) override\n  {\n    for (size_t jj = 0; jj < num_blocks; ++jj) {\n      if (block_size == 2) {\n        const auto& jac = jacobian(dd)[jj];\n        const auto trace = jac[0][0] + jac[1][1];\n        const auto det = jac[0][0] * jac[1][1] - jac[0][1] * jac[1][0];\n        const auto sqrt_val = std::sqrt(0.25 * trace * trace - det);\n        const auto eigval1 = 0.5 * trace + sqrt_val;\n        const auto eigval2 = 0.5 * trace - sqrt_val;\n        if (std::abs(jac[1][0]) > std::abs(jac[0][1])) {\n          if (XT::Common::FloatCmp::ne(jac[1][0], 0.)) {\n            eigenvectors_[dd][jj][0][0] = eigval1 - jac[1][1];\n            eigenvectors_[dd][jj][0][1] = eigval2 - jac[1][1];\n            eigenvectors_[dd][jj][1][0] = eigenvectors_[dd][jj][1][1] = jac[1][0];\n          } else {\n            eigenvectors_[dd][jj][0][0] = eigenvectors_[dd][jj][1][1] = 1.;\n            eigenvectors_[dd][jj][0][1] = eigenvectors_[dd][jj][1][0] = 0.;\n          }\n        } else {\n          if (XT::Common::FloatCmp::ne(jac[0][1], 0.)) {\n            eigenvectors_[dd][jj][1][0] = eigval1 - jac[0][0];\n            eigenvectors_[dd][jj][1][1] = eigval2 - jac[0][0];\n            eigenvectors_[dd][jj][0][0] = eigenvectors_[dd][jj][0][1] = jac[0][1];\n          } else {\n            eigenvectors_[dd][jj][0][0] = eigenvectors_[dd][jj][1][1] = 1.;\n            eigenvectors_[dd][jj][0][1] = eigenvectors_[dd][jj][1][0] = 0.;\n          }\n        }\n      } else {\n#if HAVE_MKL || HAVE_LAPACKE\n        int info = XT::Common::Lapacke::dgeev_work(XT::Common::Lapacke::row_major(),\n                                                   /*do_not_compute_left_eigenvectors: */ 'N',\n                                                   /*compute_right_eigenvectors: */ 'V',\n                                                   static_cast<int>(block_size),\n                                                   &(jacobian(dd)[jj][0][0]),\n                                                   static_cast<int>(block_size),\n                                                   &(eigenvalues_[jj][0][0]),\n                                                   &(dummy_complex_eigenvalues_[0]),\n                                                   nullptr,\n                                                   static_cast<int>(block_size),\n                                                   &(eigenvectors_[dd][jj][0][0]),\n                                                   static_cast<int>(block_size),\n                                                   work_.data(),\n                                                   static_cast<int>(work_.size()));\n        if (info != 0)\n          DUNE_THROW(Dune::XT::LA::Exceptions::eigen_solver_failed, \"The lapack backend reported '\" << info << \"'!\");\n#else // HAVE_MKL || HAVE_LAPACKE\n        static XT::Common::Configuration eigensolver_options =\n            BaseType::template create_eigensolver_opts<LocalMatrixType>();\n        const auto eigensolver = EigenSolverType(jacobian(dd)[jj], &eigensolver_options);\n        eigenvectors_[dd][jj] = eigensolver.real_eigenvectors();\n#endif // HAVE_MKL || HAVE_LAPACKE\n      } // else (block_size == 2)\n      QR_[dd][jj] = eigenvectors_[dd][jj];\n      XT::LA::qr(QR_[dd][jj], tau_[dd][jj], permutations_[dd][jj]);\n    } // jj\n    computed_[dd] = true;\n  }\n\n  virtual void apply_eigenvectors(const size_t dd, const StateRangeType& x, StateRangeType& ret) const override\n  {\n    std::fill(ret.begin(), ret.end(), 0.);\n    for (size_t jj = 0; jj < num_blocks; ++jj) {\n      const auto offset = block_size * jj;\n      for (size_t ll = 0; ll < block_size; ++ll)\n        for (size_t mm = 0; mm < block_size; ++mm)\n          ret[offset + ll] += eigenvectors_[dd][jj][ll][mm] * x[offset + mm];\n    } // jj\n  }\n\n  virtual void get_jacobian(const size_t dd,\n                            const EntityType& entity,\n                            const AnalyticalFluxType& analytical_flux,\n                            const DomainType& x_in_inside_coords,\n                            const StateRangeType& u,\n                            const XT::Common::Parameter& param) override\n  {\n    const auto local_func = analytical_flux.local_function(entity);\n    local_func->partial_u_col(dd, x_in_inside_coords, u, (*nonblocked_jacobians_)[dd], param);\n    for (size_t jj = 0; jj < num_blocks; ++jj) {\n      const auto offset = jj * block_size;\n      for (size_t ll = 0; ll < block_size; ++ll)\n        for (size_t mm = 0; mm < block_size; ++mm)\n          jacobian(dd)[jj][ll][mm] = (*nonblocked_jacobians_)[dd][offset + ll][offset + mm];\n    } // jj\n  }\n\n  virtual void get_jacobian(const EntityType& entity,\n                            const AnalyticalFluxType& analytical_flux,\n                            const DomainType& x_in_inside_coords,\n                            const StateRangeType& u,\n                            const XT::Common::Parameter& param) override\n  {\n    const auto local_func = analytical_flux.local_function(entity);\n    local_func->partial_u(x_in_inside_coords, u, *nonblocked_jacobians_, param);\n    for (size_t dd = 0; dd < dimDomain; ++dd) {\n      for (size_t jj = 0; jj < num_blocks; ++jj) {\n        const auto offset = jj * block_size;\n        for (size_t ll = 0; ll < block_size; ++ll)\n          for (size_t mm = 0; mm < block_size; ++mm)\n            jacobian(dd)[jj][ll][mm] = (*nonblocked_jacobians_)[dd][offset + ll][offset + mm];\n      } // jj\n    } // dd\n  }\n\n  virtual void apply_inverse_eigenvectors(const size_t dd, const VectorType& x, VectorType& ret) const override\n  {\n    LocalRangeType work;\n    LocalRangeType tmp_ret, tmp_x;\n    for (size_t jj = 0; jj < num_blocks; ++jj) {\n      for (size_t ll = 0; ll < block_size; ++ll)\n        tmp_x[ll] = x[jj * block_size + ll];\n      XT::LA::solve_qr_factorized(QR_[dd][jj], tau_[dd][jj], permutations_[dd][jj], tmp_ret, tmp_x, &work);\n      for (size_t ll = 0; ll < block_size; ++ll)\n        ret[jj * block_size + ll] = tmp_ret[ll];\n    }\n  }\n\nprotected:\n  std::vector<RangeFieldType> work_;\n  std::unique_ptr<FieldVector<FieldMatrix<RangeFieldType, dimRange, dimRange>, dimDomain>> nonblocked_jacobians_;\n  using BaseType::computed_;\n  FieldVector<FieldVector<FieldVector<RangeFieldType, block_size>, num_blocks>, dimDomain> eigenvalues_;\n  FieldVector<RangeFieldType, dimRange> dummy_complex_eigenvalues_;\n  FieldVector<MatrixType, dimDomain> eigenvectors_;\n  FieldVector<MatrixType, dimDomain> QR_;\n  FieldVector<FieldVector<LocalRangeType, num_blocks>, dimDomain> tau_;\n  FieldVector<FieldVector<FieldVector<int, block_size>, num_blocks>, dimDomain> permutations_;\n}; // BlockedJacobianWrapper<...>\n\n\n} // namespace internal\n\n\ntemplate <class MultiArrayType>\nclass MultiIndexIterator\n{\npublic:\n  static constexpr size_t dim = MultiArrayType::dimensionality;\n  static constexpr size_t array_dim = dim == 0 ? 1 : dim;\n  using IndicesType = std::array<size_t, array_dim>;\n\n  MultiIndexIterator(const MultiArrayType& multi_array, const IndicesType& indices)\n    : multi_array_(multi_array)\n    , indices_(indices)\n  {\n  }\n\n  IndicesType& operator*()\n  {\n    return indices_;\n  }\n\n  const IndicesType& operator*() const\n  {\n    return indices_;\n  }\n\n  MultiIndexIterator& operator++()\n  {\n    size_t ii = 0;\n    for (; ii < array_dim; ++ii) {\n      indices_[ii]++;\n      if (indices_[ii] < (dim == 0 ? 1 : multi_array_.shape()[ii]))\n        break;\n      indices_[ii] = 0;\n    }\n    if (ii == array_dim) {\n      if (dim == 0)\n        indices_[0] = 1;\n      else\n        std::copy_n(multi_array_.shape(), array_dim, indices_.begin());\n    }\n    return *this;\n  } // ... operator++()\n\n  MultiIndexIterator operator++(int)\n  {\n    MultiIndexIterator ret = *this;\n    this->operator++();\n    return ret;\n  } // ... operator++(int)\n\n  bool operator==(const MultiIndexIterator& other) const\n  {\n    return indices_ == other.indices_;\n  }\n\n  bool operator!=(const MultiIndexIterator& other) const\n  {\n    return indices_ != other.indices_;\n  }\n\nprivate:\n  const MultiArrayType& multi_array_;\n  IndicesType indices_;\n}; // class MultiIndexIterator<...>\n\ntemplate <class MultiArrayType>\nclass MultiIndexProvider\n{\npublic:\n  using IteratorType = MultiIndexIterator<MultiArrayType>;\n  using IndicesType = typename IteratorType::IndicesType;\n\n  MultiIndexProvider(const MultiArrayType& multi_array)\n    : multi_array_(multi_array)\n  {\n  }\n\n  IteratorType begin()\n  {\n    static const IndicesType zero_indices = []() {\n      IndicesType ret;\n      ret.fill(0);\n      return ret;\n    }();\n    return IteratorType(multi_array_, zero_indices);\n  }\n\n  IteratorType end()\n  {\n    IndicesType indices;\n    if (MultiArrayType::dimensionality == 0)\n      indices[0] = 1; // for dimension 0, the end iterator has index 1\n    else\n      std::copy_n(multi_array_.shape(), MultiArrayType::dimensionality, indices.begin());\n    return IteratorType(multi_array_, indices);\n  }\n\nprivate:\n  const MultiArrayType& multi_array_;\n}; // class MultiIndexProvider<...>\n\n// Helper functor to build indices.\ntemplate <typename RangeArrayType, size_t num_ranges, size_t dimension>\nstruct IndicesBuilder\n{\n  static boost::detail::multi_array::index_gen<num_ranges, dimension> build(const RangeArrayType& ranges)\n  {\n    return boost::detail::multi_array::index_gen<num_ranges, dimension>(\n        IndicesBuilder<RangeArrayType, num_ranges - 1, dimension>::build(ranges), ranges[num_ranges - 1]);\n  }\n};\n\n// Helper functor specialization to terminate recursion.\ntemplate <typename RangeArrayType, size_t dimension>\nstruct IndicesBuilder<RangeArrayType, 0, dimension>\n{\n  static boost::detail::multi_array::index_gen<0, dimension> build(const RangeArrayType& /*ranges*/)\n  {\n    return boost::detail::multi_array::index_gen<0, dimension>();\n  }\n};\n\ntemplate <class RangeType, size_t dimDomain>\nclass Slice : public boost::multi_array<RangeType, dimDomain - 1>\n{\n};\n\ntemplate <class RangeType>\nclass Slice<RangeType, 1>\n{\npublic:\n  template <class MultiIndexType>\n  RangeType& operator()(const MultiIndexType&)\n  {\n    return value_;\n  }\n\n  template <class IndicesType>\n  void resize(const IndicesType&)\n  {\n  }\n\nprivate:\n  RangeType value_;\n};\n\ntemplate <class AnalyticalFluxType,\n          class BoundaryValueType,\n          class GridLayerType,\n          SlopeLimiters slope_limiter,\n          class JacobianWrapperType>\nclass LocalLinearReconstructionOperator : public XT::Grid::Functor::Codim0<GridLayerType>\n{\n  // stencil is (i-r, i+r) in all dimensions, where r = polOrder + 1\n  static constexpr size_t dimDomain = BoundaryValueType::dimDomain;\n  static constexpr size_t dimRange = BoundaryValueType::dimRange;\n  static constexpr size_t axis_size = 3;\n  typedef typename GridLayerType::template Codim<0>::Entity EntityType;\n  typedef typename GridLayerType::IndexSet IndexSetType;\n  typedef typename BoundaryValueType::DomainType DomainType;\n  typedef typename BoundaryValueType::DomainFieldType DomainFieldType;\n  typedef typename BoundaryValueType::RangeType RangeType;\n  typedef typename BoundaryValueType::RangeFieldType RangeFieldType;\n  typedef Dune::QuadratureRule<DomainFieldType, 1> Quadrature1dType;\n  typedef typename GridLayerType::Intersection IntersectionType;\n  typedef FieldVector<IntersectionType, 2 * dimDomain> IntersectionVectorType;\n  typedef typename IntersectionType::Geometry::LocalCoordinate IntersectionLocalCoordType;\n  typedef typename AnalyticalFluxType::LocalfunctionType AnalyticalFluxLocalfunctionType;\n  typedef typename AnalyticalFluxLocalfunctionType::StateRangeType StateRangeType;\n  typedef typename XT::Grid::BoundaryInfo<IntersectionType> BoundaryInfoType;\n  using ReconstructedFunctionType =\n      ReconstructedLocalizableFunction<GridLayerType, DomainFieldType, dimDomain, RangeFieldType, dimRange, 1>;\n  using StencilType = boost::multi_array<boost::optional<RangeType>, dimDomain>;\n  using MultiArrayType = boost::multi_array<RangeType, dimDomain>;\n  using SliceType = Slice<RangeType, dimDomain>;\n  using CoordsType = std::array<size_t, dimDomain>;\n\npublic:\n  explicit LocalLinearReconstructionOperator(const std::vector<RangeType>& source_values,\n                                             const AnalyticalFluxType& analytical_flux,\n                                             const BoundaryValueType& boundary_values,\n                                             const GridLayerType& grid_layer,\n                                             const XT::Common::Parameter& param,\n                                             const Quadrature1dType& quadrature,\n                                             ReconstructedFunctionType& reconstructed_function,\n                                             XT::Common::PerThreadValue<JacobianWrapperType>& jacobian_wrapper)\n    : source_values_(source_values)\n    , analytical_flux_(analytical_flux)\n    , boundary_values_(boundary_values)\n    , grid_layer_(grid_layer)\n    , param_(param)\n    , quadrature_(quadrature)\n    , reconstructed_function_(reconstructed_function)\n    , jacobian_wrapper_(jacobian_wrapper)\n  {\n    param_.set(\"boundary\", {0.});\n  }\n\n  virtual void apply_local(const EntityType& entity) override final\n  {\n    static const CoordsType stencil_sizes = []() {\n      CoordsType ret;\n      const auto ax_size = axis_size; // avoid linker error\n      ret.fill(ax_size);\n      return ret;\n    }();\n    thread_local StencilType stencil(stencil_sizes);\n    bool valid = fill_stencil(stencil, entity);\n    // In a MPI parallel run, if entity is on boundary of overlap, we do not have to reconstruct\n    if (!valid)\n      return;\n    // get intersections\n    FieldVector<typename GridLayerType::Intersection, 2 * dimDomain> intersections;\n    for (const auto& intersection : Dune::intersections(grid_layer_, entity))\n      intersections[intersection.indexInInside()] = intersection;\n    const auto entity_index = grid_layer_.indexSet().index(entity);\n    auto& reconstructed_values_map = reconstructed_function_.values()[entity_index];\n\n    // get jacobian\n    auto& jac = *jacobian_wrapper_;\n    if (!jac.computed() || !analytical_flux_.is_affine()) {\n      const auto& u_entity = source_values_[entity_index];\n      const DomainType x_in_inside_coords = entity.geometry().local(entity.geometry().center());\n      jac.get_jacobian(entity, analytical_flux_, x_in_inside_coords, u_entity, param_);\n      jac.compute();\n      if (analytical_flux_.is_affine())\n        jac.jacobian() = nullptr;\n    }\n\n    for (size_t dd = 0; dd < dimDomain; ++dd) {\n      if (quadrature_.size() == 1) {\n        // no need to reconstruct in all directions, as we are only regarding the center of the face, which will always\n        // have the same value assigned, independent of the slope in the other directions\n        std::array<size_t, dimDomain> indices;\n        indices.fill(1);\n        FieldVector<RangeType, axis_size> stencil_1d;\n        FieldVector<RangeType, 2> reconstructed_values;\n        for (size_t ii = 0; ii < axis_size; ++ii) { // transform to characteristic variables\n          indices[dd] = ii;\n          jac.apply_inverse_eigenvectors(dd, *stencil(indices), stencil_1d[ii]);\n        }\n        // perform the actual reconstruction\n        linear_reconstruction_1d(stencil_1d, reconstructed_values);\n        // convert back to non-characteristic variables\n        auto tmp_value = reconstructed_values[0];\n        jac.apply_eigenvectors(dd, tmp_value, reconstructed_values[0]);\n        tmp_value = reconstructed_values[1];\n        jac.apply_eigenvectors(dd, tmp_value, reconstructed_values[1]);\n\n        // store reconstructed values\n        reconstructed_values_map.emplace(intersections[2 * dd].geometryInInside().center(), reconstructed_values[0]);\n        reconstructed_values_map.emplace(intersections[2 * dd + 1].geometryInInside().center(),\n                                         reconstructed_values[1]);\n      } else {\n        thread_local MultiArrayType reconstructed_values(stencil_sizes);\n        thread_local auto tmp_multiarray = reconstructed_values;\n        tmp_multiarray.resize(stencil_sizes);\n\n        // Transform values on stencil to characteristic variables of the current coordinate direction dd\n        for (size_t ii = 0; ii < stencil.num_elements(); ++ii)\n          jac.apply_inverse_eigenvectors(dd, *stencil.data()[ii], tmp_multiarray.data()[ii]);\n\n        size_t curr_dir = dd;\n        size_t last_dir = curr_dir;\n        RangeType tmp_value;\n        CoordsType current_sizes;\n        for (size_t dir = 0; dir < dimDomain; ++dir) {\n          curr_dir = (dd + dir) % dimDomain;\n          // Transform to characteristic variables of the current reconstruction direction.\n          if (dir > 0) {\n            std::copy_n(reconstructed_values.shape(), dimDomain, current_sizes.begin());\n            tmp_multiarray.resize(current_sizes);\n            tmp_multiarray = reconstructed_values;\n            std::for_each(\n                tmp_multiarray.data(), tmp_multiarray.data() + tmp_multiarray.num_elements(), [&](RangeType& value) {\n                  jac.apply_eigenvectors(last_dir, value, tmp_value);\n                  jac.apply_inverse_eigenvectors(curr_dir, tmp_value, value);\n                });\n          } // if (dir > 0)\n          // perform the actual reconstruction\n          const auto& curr_quadrature = dir > 0 ? quadrature_ : get_left_right_quadrature();\n          linear_reconstruction(curr_dir, curr_quadrature, tmp_multiarray, reconstructed_values);\n          last_dir = curr_dir;\n        } // dir\n        // convert back to non-characteristic variables\n        std::for_each(reconstructed_values.data(),\n                      reconstructed_values.data() + reconstructed_values.num_elements(),\n                      [&](RangeType& value) {\n                        tmp_value = value;\n                        jac.apply_eigenvectors(last_dir, tmp_value, value);\n                      });\n\n        // Convert coordinates on face to local entity coordinates and store reconstructed values\n        MultiIndexProvider<MultiArrayType> multi_indices(reconstructed_values);\n        for (const auto& multi_index : multi_indices) {\n          IntersectionLocalCoordType quadrature_point;\n          for (size_t ii = 0; ii < dimDomain; ++ii)\n            if (ii != dd)\n              quadrature_point[ii < dd ? ii : ii - 1] = quadrature_[multi_index[ii]].position();\n          reconstructed_values_map.emplace(\n              intersections[2 * dd + multi_index[dd]].geometryInInside().global(quadrature_point),\n              reconstructed_values(multi_index));\n        } // multi_indices\n      }\n    } // dd\n  } // void apply_local(...)\n\n  static void linear_reconstruction_1d(const FieldVector<RangeType, axis_size>& stencil,\n                                       FieldVector<RangeType, 2>& reconstructed_values)\n  {\n    const auto& u_left = stencil[0];\n    const auto& u_entity = stencil[1];\n    const auto& u_right = stencil[2];\n    const auto slope_left = u_entity - u_left;\n    const auto slope_center = 0.5 * (u_right - u_left);\n    const auto slope_right = u_right - u_entity;\n    auto slope = internal::ChooseLimiter<slope_limiter>::limit(slope_left, slope_right, slope_center);\n    slope *= 0.5;\n    reconstructed_values[0] = u_entity - slope;\n    reconstructed_values[1] = u_entity + slope;\n  } // static void linear_reconstruction(...)\n\n  static void linear_reconstruction(const size_t dir,\n                                    const Quadrature1dType& quadrature,\n                                    const MultiArrayType& stencil,\n                                    MultiArrayType& reconstructed_values)\n  {\n    // resize the reconstructed_values array\n    CoordsType new_shape;\n    std::copy_n(stencil.shape(), dimDomain, new_shape.begin());\n    new_shape[dir] = quadrature.size();\n    reconstructed_values.resize(new_shape);\n\n    // get array_views corresponding to the left, center and right values\n    using IndexRangeType = typename MultiArrayType::index_range;\n    using RangeArrayType = XT::Common::FieldVector<IndexRangeType, dimDomain>;\n    using IndicesBuilderType = IndicesBuilder<RangeArrayType, dimDomain, dimDomain - 1>;\n\n    assert(stencil.shape()[dir] == 3);\n    RangeArrayType ranges;\n    for (size_t ii = 0; ii < dimDomain; ++ii)\n      ranges[ii] = IndexRangeType(0, stencil.shape()[ii]);\n    ranges[dir] = IndexRangeType(0);\n    const auto u_left = stencil[IndicesBuilderType::build(ranges)];\n    ranges[dir] = IndexRangeType(1);\n    const auto u_entity = stencil[IndicesBuilderType::build(ranges)];\n    ranges[dir] = IndexRangeType(2);\n    const auto u_right = stencil[IndicesBuilderType::build(ranges)];\n\n    // calculate slopes\n    thread_local SliceType slope;\n    std::array<size_t, dimDomain - 1> slope_sizes;\n    std::copy_n(u_entity.shape(), dimDomain - 1, slope_sizes.begin());\n    slope.resize(slope_sizes);\n    MultiIndexProvider<decltype(u_left)> multi_indices(u_left);\n    for (const auto& multi_index : multi_indices) {\n      const auto slope_left = u_entity(multi_index) - u_left(multi_index);\n      const auto slope_center = 0.5 * (u_right(multi_index) - u_left(multi_index));\n      const auto slope_right = u_right(multi_index) - u_entity(multi_index);\n      slope(multi_index) = internal::ChooseLimiter<slope_limiter>::limit(slope_left, slope_right, slope_center);\n    }\n\n    // calculate reconstructed values\n    for (size_t ii = 0; ii < dimDomain; ++ii)\n      ranges[ii] = IndexRangeType(0, new_shape[ii]);\n    for (size_t ii = 0; ii < quadrature.size(); ++ii) {\n      ranges[dir] = IndexRangeType(ii);\n      auto reconstructed_ii = reconstructed_values[IndicesBuilderType::build(ranges)];\n      for (const auto& multi_index : multi_indices) {\n        reconstructed_ii(multi_index) = slope(multi_index);\n        reconstructed_ii(multi_index) *= (quadrature[ii].position() - 0.5);\n        reconstructed_ii(multi_index) += u_entity(multi_index);\n      }\n    } // ii (quadrature.size())\n  } // static void linear_reconstruction(...)\n\nprivate:\n  CoordsType center(const StencilType& stencil) const\n  {\n    CoordsType ret;\n    for (size_t ii = 0; ii < dimDomain; ++ii) {\n      assert(stencil.shape()[ii] % 2 && \"Center not well-defined if one of the axis_sizes is even!\");\n      ret[ii] = stencil.shape()[ii] / 2;\n    }\n    return ret;\n  }\n\n  bool fill_stencil(StencilType& stencil, const EntityType& entity)\n  {\n    const int dir = -2;\n    auto coords = center(stencil);\n    std::fill_n(stencil.data(), stencil.num_elements(), boost::none);\n    return fill_impl(stencil, entity, dir, coords);\n  } // void fill(...)\n\nprivate:\n  bool fill_impl(StencilType& stencil, const EntityType& entity, const int dir, const CoordsType& coords)\n  {\n    bool ret = true;\n    const auto entity_index = grid_layer_.indexSet().index(entity);\n    stencil(coords) = source_values_[entity_index];\n    std::vector<int> boundary_dirs;\n    for (const auto& intersection : Dune::intersections(grid_layer_, entity)) {\n      const auto new_dir = intersection.indexInInside();\n      if (direction_allowed(dir, new_dir) && !end_of_stencil(stencil, new_dir, coords)) {\n        auto new_coords = coords;\n        if (intersection.boundary() && !intersection.neighbor()) { // boundary intersections\n          boundary_dirs.push_back(new_dir);\n          auto boundary_value = boundary_values_.local_function(entity)->evaluate(\n              intersection, entity.geometry().local(intersection.geometry().center()), source_values_[entity_index]);\n          while (!end_of_stencil(stencil, new_dir, new_coords)) {\n            next_coords_in_dir(new_dir, new_coords);\n            stencil(new_coords) = boundary_value;\n          }\n        } else if (intersection.neighbor()) { // inner and periodic intersections\n          const auto& outside = intersection.outside();\n          next_coords_in_dir(new_dir, new_coords);\n          ret = ret && fill_impl(stencil, outside, new_dir, new_coords);\n        } else if (!intersection.neighbor() && !intersection.boundary()) { // processor boundary\n          return false;\n        }\n      } // if (!end_of_stencil(...))\n    } // intersections\n\n    assert(boundary_dirs.size() <= dimDomain);\n    if (boundary_dirs.size() > 1) {\n      auto new_coords = coords;\n      next_coords_in_dir(boundary_dirs[0], new_coords);\n      const auto& boundary_value = stencil(new_coords);\n\n      std::for_each(stencil.data(),\n                    stencil.data() + stencil.num_elements(),\n                    [&boundary_value](boost::optional<RangeType>& value) {\n                      if (!value)\n                        value = boundary_value;\n                    });\n    } // if (boundary_dirs.size() > 1)\n    return ret;\n  }\n\n  //  get next coords in direction dir (increase or decrease coords in that direction)\n  static void next_coords_in_dir(const int dir, CoordsType& coords)\n  {\n    dir % 2 ? coords[dir / 2]++ : coords[dir / 2]--;\n  }\n\n  // Direction is allowed if end of stencil is not reached and direction is not visited by another iterator.\n  // Iterators never change direction, they may only spawn new iterators in the directions that have a higher\n  // index (i.e. iterators that walk in x direction will spawn iterators going in y and z direction,\n  // iterators going in y direction will only spawn iterators in z-direction and z iterators only walk\n  // without emitting new iterators).\n  static bool direction_allowed(const int dir, const int new_dir)\n  {\n    return new_dir == dir || new_dir / 2 > dir / 2;\n  }\n\n  bool end_of_stencil(const StencilType& stencil, const int dir, const CoordsType& coords)\n  {\n    return coords[dir / 2] == stencil.shape()[dir / 2] - 1 || coords[dir / 2] == 0;\n  }\n\n\n  // quadrature rule containing left and right interface points\n  static const Quadrature1dType& get_left_right_quadrature()\n  {\n    static const Quadrature1dType ret = left_right_quadrature();\n    return ret;\n  }\n\n  static Quadrature1dType left_right_quadrature()\n  {\n    Quadrature1dType ret;\n    ret.push_back(Dune::QuadraturePoint<DomainFieldType, 1>(0., 0.5));\n    ret.push_back(Dune::QuadraturePoint<DomainFieldType, 1>(1., 0.5));\n    return ret;\n  }\n\n  const std::vector<RangeType>& source_values_;\n  const AnalyticalFluxType& analytical_flux_;\n  const BoundaryValueType& boundary_values_;\n  const GridLayerType& grid_layer_;\n  XT::Common::Parameter param_;\n  const Quadrature1dType& quadrature_;\n  ReconstructedFunctionType& reconstructed_function_;\n  XT::Common::PerThreadValue<JacobianWrapperType>& jacobian_wrapper_;\n}; // class LocalLinearReconstructionOperator\n\n\ntemplate <class AnalyticalFluxImp,\n          class BoundaryValueImp,\n          SlopeLimiters slope_limiter,\n          class JacobianWrapperImp,\n          class Traits>\nclass LinearReconstructionOperator;\n\n\nnamespace internal {\n\n\ntemplate <class AnalyticalFluxImp, class BoundaryValueImp, SlopeLimiters slope_lim, class JacobianWrapperImp>\nstruct LinearReconstructionOperatorTraits\n{\n  using AnalyticalFluxType = AnalyticalFluxImp;\n  using BoundaryValueType = BoundaryValueImp;\n  static const SlopeLimiters slope_limiter = slope_lim;\n  using JacobianWrapperType = JacobianWrapperImp;\n  using DomainFieldType = typename BoundaryValueType::DomainFieldType;\n  using RangeFieldType = typename BoundaryValueType::DomainFieldType;\n  using FieldType = DomainFieldType;\n  using JacobianType = NoJacobian;\n  static constexpr size_t dimDomain = BoundaryValueType::dimDomain;\n  static constexpr size_t dimRange = BoundaryValueType::dimRange;\n  using ProductQuadratureType = QuadratureRule<DomainFieldType, dimDomain - 1>;\n  using Quadrature1dType = Dune::QuadratureRule<DomainFieldType, 1>;\n  using derived_type = LinearReconstructionOperator<AnalyticalFluxType,\n                                                    BoundaryValueType,\n                                                    slope_limiter,\n                                                    JacobianWrapperType,\n                                                    LinearReconstructionOperatorTraits>;\n};\n\n\n} // namespace internal\n\n\ntemplate <class AnalyticalFluxImp,\n          class BoundaryValueImp,\n          SlopeLimiters slope_limiter = SlopeLimiters::minmod,\n          class JacobianWrapperImp = internal::JacobianWrapper<AnalyticalFluxImp,\n                                                               FieldMatrix<typename BoundaryValueImp::RangeFieldType,\n                                                                           BoundaryValueImp::dimRange,\n                                                                           BoundaryValueImp::dimRange>,\n                                                               FieldVector<typename BoundaryValueImp::RangeFieldType,\n                                                                           BoundaryValueImp::dimRange>>,\n          class Traits = internal::LinearReconstructionOperatorTraits<AnalyticalFluxImp,\n                                                                      BoundaryValueImp,\n                                                                      slope_limiter,\n                                                                      JacobianWrapperImp>>\nclass LinearReconstructionOperator : public OperatorInterface<Traits>\n{\npublic:\n  using AnalyticalFluxType = typename Traits::AnalyticalFluxType;\n  using BoundaryValueType = typename Traits::BoundaryValueType;\n  using JacobianWrapperType = typename Traits::JacobianWrapperType;\n  using Quadrature1dType = typename Traits::Quadrature1dType;\n  using ProductQuadratureType = typename Traits::ProductQuadratureType;\n  using DomainFieldType = typename Traits::DomainFieldType;\n  using RangeFieldType = typename Traits::RangeFieldType;\n  static constexpr size_t dimDomain = Traits::dimDomain;\n  static constexpr size_t dimRange = Traits::dimRange;\n\n  LinearReconstructionOperator(const AnalyticalFluxType& analytical_flux,\n                               const BoundaryValueType& boundary_values,\n                               const Quadrature1dType& quadrature_1d = default_1d_quadrature<DomainFieldType>(1))\n    : analytical_flux_(analytical_flux)\n    , boundary_values_(boundary_values)\n    , quadrature_1d_(quadrature_1d)\n    , product_quadrature_(product_quadrature_on_intersection<DomainFieldType, dimDomain>(quadrature_1d))\n  {\n  }\n\n  const ProductQuadratureType& quadrature() const\n  {\n    return product_quadrature_;\n  }\n\n  template <class SourceType, class RangeType>\n  void apply(const SourceType& source, RangeType& range, const XT::Common::Parameter& param) const\n  {\n    static_assert(is_reconstructed_localizable_function<RangeType>::value,\n                  \"RangeType has to be derived from ReconstructedLocalizableFunction!\");\n    // evaluate cell averages\n    const auto& grid_layer = source.space().grid_layer();\n    const auto& index_set = grid_layer.indexSet();\n    std::vector<typename SourceType::RangeType> source_values(index_set.size(0));\n    for (const auto& entity : Dune::elements(grid_layer)) {\n      const auto entity_index = index_set.index(entity);\n      const auto local_source = source.local_function(entity);\n      source_values[entity_index] = local_source->evaluate(entity.geometry().local(entity.geometry().center()));\n    }\n\n    // do reconstruction\n    auto local_reconstruction_operator =\n        LocalLinearReconstructionOperator<AnalyticalFluxType,\n                                          BoundaryValueType,\n                                          typename SourceType::SpaceType::GridLayerType,\n                                          slope_limiter,\n                                          JacobianWrapperType>(source_values,\n                                                               analytical_flux_,\n                                                               boundary_values_,\n                                                               grid_layer,\n                                                               param,\n                                                               quadrature_1d_,\n                                                               range,\n                                                               jacobian_wrapper_);\n    auto walker = XT::Grid::Walker<typename SourceType::SpaceType::GridLayerType>(grid_layer);\n    walker.append(local_reconstruction_operator);\n    walker.walk(true);\n  } // void apply(...)\n\nprivate:\n  const AnalyticalFluxType& analytical_flux_;\n  const BoundaryValueType& boundary_values_;\n  const Quadrature1dType quadrature_1d_;\n  const ProductQuadratureType product_quadrature_;\n  mutable XT::Common::PerThreadValue<JacobianWrapperType> jacobian_wrapper_;\n}; // class LinearReconstructionOperator<...>\n\n\n} // namespace GDT\n} // namespace Dune\n\n#endif // DUNE_GDT_OPERATORS_FV_RECONSTRUCTION_LINEAR_HH\n", "meta": {"hexsha": "87ce2e00a0332ab6d12806b5f29a5d4add562856", "size": 48410, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/gdt/operators/fv/reconstruction/linear.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/reconstruction/linear.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/reconstruction/linear.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": 43.4170403587, "max_line_length": 120, "alphanum_fraction": 0.6128692419, "num_tokens": 10736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.26159848079697073}}
{"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/cbr_control/blob/master/LICENSE\n\n#ifndef CBR_CONTROL__PID_HPP_\n#define CBR_CONTROL__PID_HPP_\n\n#include <boost/hana/adapt_struct.hpp>\n\n#include <cbr_utils/cyber_timer.hpp>\n\n#include <sophus/so2.hpp>\n\n#include <memory>\n#include <type_traits>\n#include <utility>\n\n#include \"cbr_control/derivator.hpp\"\n\nnamespace cbr\n{\n\nstruct PIDClampParams\n{\n  bool active{true};\n  double max{1.};\n  double min{-1.};\n\n  void check_correctness() const\n  {\n    if (min > max) {\n      throw std::invalid_argument(\"max must be less or equal to min\");\n    }\n  }\n};\n\nstruct PIDParams\n{\n  double P{1.};\n  double I{1.};\n  double D{1.};\n\n  double der_tau{0.};\n\n  PIDClampParams clamp;\n\n  void check_correctness() const\n  {\n    clamp.check_correctness();\n  }\n};\n\ntemplate<typename _clock_t = std::chrono::high_resolution_clock>\nclass PID\n{\npublic:\n  using clock_t = _clock_t;\n  using timer_t = CyberTimerNoAvg<std::ratio<1>, double, clock_t>;\n  using derivator_t = Derivator<double, clock_t>;\n\n  // Constructors\n  PID() = default;\n  PID(const PID &) = default;\n  PID(PID &) = default;\n  PID(PID &&) = default;\n  PID & operator=(const PID &) = default;\n  PID & operator=(PID &) = default;\n  PID & operator=(PID &&) = default;\n  ~PID() = default;\n\n  template<typename T>\n  explicit PID(T && clock, const PIDParams & prm = {}, const double errInt = 0.)\n  : timer_(std::forward<T>(clock)),\n    prm_(prm),\n    errInt_(errInt)\n  {\n    prm_.check_correctness();\n    der_.set_params({prm_.der_tau});\n  }\n\n  explicit PID(const PIDParams & prm, const double errInt = 0.)\n  : prm_(prm),\n    errInt_(errInt)\n  {\n    prm_.check_correctness();\n    der_.set_params({prm_.der_tau});\n  }\n\n  template<typename T>\n  PID(T && clock, const double errInt)\n  : timer_(std::forward<T>(clock)),\n    errInt_(errInt)\n  {}\n\n  explicit PID(const double errInt)\n  : errInt_(errInt)\n  {}\n\n  template<typename T>\n  void set_clock(T && clock)\n  {\n    timer_.set_clock(std::forward<T>(clock));\n  }\n\n  void set_params(const PIDParams & prm)\n  {\n    prm.check_correctness();\n    prm_ = prm;\n    der_.set_params({prm_.der_tau});\n  }\n\n  const PIDParams & get_params() const\n  {\n    return prm_;\n  }\n\n  const double & update(const double desired, const double actual)\n  {\n    return update_impl(desired - actual, actual);\n  }\n\n  const double & update(const Sophus::SO2d & desired, const Sophus::SO2d & actual)\n  {\n    return update_impl((actual.inverse() * desired).log(), actual.log());\n  }\n\n  const double & operator()(const double desired, const double actual)\n  {\n    return update(desired, actual);\n  }\n\n  const double & operator()(const Sophus::SO2d & desired, const Sophus::SO2d & actual)\n  {\n    return update(desired, actual);\n  }\n\n  const double & getValue() const\n  {\n    return output_;\n  }\n\n  void reset(const double errInt = 0.)\n  {\n    der_.reset();\n    errInt_ = prm_.I * errInt;\n    if (prm_.clamp.active) {\n      errInt_ = std::clamp(errInt_, prm_.clamp.min, prm_.clamp.max);\n    }\n    output_ = errInt_;\n    timer_.tic();\n  }\n\nprotected:\n  const double & update_impl(const double err, const double actual)\n  {\n    const auto tNow = timer_.now();\n    const double errDot = der_.update(actual, tNow);\n    output_ = prm_.P * err + prm_.D * errDot + errInt_;\n\n    if (init_) {\n      const double dt = timer_.toctic(tNow);\n      const double dt_err = dt * err * prm_.I;\n      const double errIntTmp = errInt_ + dt_err;\n      const double outputTmp = output_ + dt_err;\n      if (!prm_.clamp.active || (outputTmp < prm_.clamp.max && outputTmp > prm_.clamp.min)) {\n        errInt_ = errIntTmp;\n        output_ = outputTmp;\n      }\n    } else {\n      init_ = true;\n      timer_.tic(tNow);\n    }\n\n    if (prm_.clamp.active) {\n      output_ = std::clamp(output_, prm_.clamp.min, prm_.clamp.max);\n    }\n    return output_;\n  }\n\n  timer_t timer_ = timer_t(clock_t{});\n  PIDParams prm_;\n  double errInt_{0.};\n  double output_{0.};\n  bool init_{false};\n  derivator_t der_;\n};\n\n}    // namespace cbr\n\n// cppcheck-suppress unknownMacro\nBOOST_HANA_ADPAT_STRUCT(\n  cbr::PIDClampParams,\n  active,\n  max,\n  min\n);\n\n// cppcheck-suppress unknownMacro\nBOOST_HANA_ADAPT_STRUCT(\n  cbr::PIDParams,\n  P,\n  I,\n  D,\n  der_tau,\n  clamp\n);\n\n#endif  // CBR_CONTROL__PID_HPP_\n", "meta": {"hexsha": "3f29e5ebfe6b9b0ba234226f7585aeca2227494d", "size": 4265, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cbr_control/pid.hpp", "max_stars_repo_name": "yamaha-bps/cbr_control", "max_stars_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/cbr_control/pid.hpp", "max_issues_repo_name": "yamaha-bps/cbr_control", "max_issues_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/cbr_control/pid.hpp", "max_forks_repo_name": "yamaha-bps/cbr_control", "max_forks_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4066985646, "max_line_length": 93, "alphanum_fraction": 0.6478311841, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2615984734266611}}
{"text": "#ifndef FSTMODELMULTINOM_H\n#define FSTMODELMULTINOM_H\n\n/*!======================================================================\n   Feature Selection Toolbox 3 source code\n   ---------------------------------------\n\t\n   \\file    model_multinom.hpp\n   \\brief   Implements multinomial model\n   \\author  Petr Somol (somol@utia.cas.cz) with collaborators, see Contacts at http://fst.utia.cz\n   \\date    March 2011\n   \\version 3.1.0.beta\n   \\note    FST3 was developed using gcc 4.3 and requires\n   \\note    \\li Boost library (http://www.boost.org/, tested with versions 1.33.1 and 1.44),\n   \\note    \\li (\\e optionally) LibSVM (http://www.csie.ntu.edu.tw/~cjlin/libsvm/, \n                tested with version 3.00)\n   \\note    Note that LibSVM is required for SVM related tools only,\n            as demonstrated in demo12t.cpp, demo23.cpp, demo25t.cpp, demo32t.cpp, etc.\n\n*/ /* \n=========================================================================\nCopyright:\n  * FST3 software (with exception of any externally linked libraries) \n    is copyrighted by Institute of Information Theory and Automation (UTIA), \n    Academy of Sciences of the Czech Republic.\n  * FST3 source codes as presented here do not contain code of third parties. \n    FST3 may need linkage to external libraries to exploit its functionality\n    in full. For details on obtaining and possible usage restrictions \n    of external libraries follow their original sources (referenced from\n    FST3 documentation wherever applicable).\n  * FST3 software is available free of charge for non-commercial use. \n    Please address all inquires concerning possible commercial use \n    of FST3, or if in doubt, to FST3 maintainer (see http://fst.utia.cz).\n  * Derivative works based on FST3 are permitted as long as they remain\n    non-commercial only.\n  * Re-distribution of FST3 software is not allowed without explicit\n    consent of the copyright holder.\nDisclaimer of Warranty:\n  * FST3 software is presented \"as is\", without warranty of any kind, \n    either expressed or implied, including, but not limited to, the implied \n    warranties of merchantability and fitness for a particular purpose. \n    The entire risk as to the quality and performance of the program \n    is with you. Should the program prove defective, you assume the cost \n    of all necessary servicing, repair or correction.\nLimitation of Liability:\n  * The copyright holder will in no event be liable to you for damages, \n    including any general, special, incidental or consequential damages \n    arising out of the use or inability to use the code (including but not \n    limited to loss of data or data being rendered inaccurate or losses \n    sustained by you or third parties or a failure of the program to operate \n    with any other programs).\n========================================================================== */\n\n#include <boost/smart_ptr.hpp>\n#include <iostream>\n#include <sstream>\n#include <limits>\n#include <cmath>\n#include <cstring> // memcpy\n#include \"error.hpp\"\n#include \"global.hpp\"\n#include \"model.hpp\"\n#include \"indexed_vector.hpp\"\n#include \"indexed_matrix.hpp\"\n\n/*============== Template parameter type naming conventions ==============\n--------- Numeric types: -------------------------------------------------\nDATATYPE - data sample values - usually real numbers (but may be integers\n          in text processing etc.)\nREALTYPE - must be real numbers - for representing intermediate results of \n          calculations like mean, covariance etc.\nIDXTYPE - index values for enumeration of data samples - (nonnegative) integers, \n          extent depends on numbers of samples in data\nDIMTYPE - index values for enumeration of features (dimensions), or classes (not \n          class sizes) - (nonnegative) integers, usually lower extent than IDXTYPE, \n          but be aware of expressions like _classes*_features*_features ! \n          in linearized representations of feature matrices for all classes\nBINTYPE - feature selection marker type - represents ca. <10 different feature \n          states (selected, deselected, sel./desel. temporarily 1st nested loop, 2nd...)\nRETURNTYPE - criterion value: real value, but may be extended in future to support \n          multiple values \n--------- Class types: ---------------------------------------------------\nSUBSET       - class of class type Subset \nCLASSIFIER   - class implementing interface defined in abstract class Classifier \nEVALUATOR    - class implementing interface defined in abstract class Sequential_Step \nDISTANCE     - class implementing interface defined in abstract class Distance \nDATAACCESSOR - class implementing interface defined in abstract class Data_Accessor \nINTERVALCONTAINER - class of class type TIntervaller \nCONTAINER    - STL container of class type TInterval  \n========================================================================== */\n\nnamespace FST {\n\n//! Implements multinomial model\n//\n// \\note only non-negative integers assumed as data\ntemplate<typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nclass Model_Multinomial : public Model<SUBSET,DATAACCESSOR> {\npublic:\n\ttypedef boost::shared_ptr<DATAACCESSOR> PDataAccessor;\n\ttypedef boost::shared_ptr<SUBSET> PSubset;\n\tModel_Multinomial() : _classes(0), _n_max(0), _n(0), _d(0), _allpatterns(0), _doc_avg_length(0) {notify(\"Model_Multinomial constructor\");}\n\tModel_Multinomial(const Model_Multinomial& mm); // copy-constructor\n\tvirtual ~Model_Multinomial() {notify(\"Model_Multinomial destructor\");}\n\n\tvirtual void learn(PDataAccessor da); // learn model of full dimensionality\n\tvirtual void learn(PDataAccessor da, const PSubset sub); // learn model of lower dimensionality\n\n\tvoid narrow_to(const PSubset sub); // fill _index[] -> access to data is then mapped to sub-matrix\n\tvoid denarrow(); // reset _index[] -> access is reset to the full matrix\n\n\tvoid compute_theta();\n\tvoid compute_MI(); // Mutual Information of individual features\n\tvoid compute_IB(); // Individual Bhattacharyya of individual features\n\n\tDIMTYPE get_n_max() const {return _n_max;}\n\tDIMTYPE get_n() const {return _n;}\n\tDIMTYPE get_d() const {return _d;}\n\tDIMTYPE get_classes() const {return _classes;}\n\t\n\tREALTYPE get_doc_avg_length() const {return _doc_avg_length;}\n\t// NOTE: caller must ensure any access takes place only during _theta, _IB, _MI and _Pc existence\n\tREALTYPE get_Pc(const DIMTYPE c) const {assert(c>=0 && c<_classes); return _Pc[c];}\nprotected:\n\ttemplate<class, class, class, class, class, class, class> friend class Criterion_Multinomial_Bhattacharyya;\n\ttemplate<class, class, class, class, class, class, class> friend class Classifier_Multinomial_NaiveBayes;\n\tconst boost::scoped_array<REALTYPE>& get_theta() const {return _theta;}\n\tconst boost::scoped_array<REALTYPE>& get_IB() const {return _IB;}\n\tconst boost::scoped_array<REALTYPE>& get_MI() const {return _MI;}\nprotected:\n\tDIMTYPE _classes; // initialized in learn(), WARNING: int sufficient ? note expressions like _classes*_n*_n\n\t// NOTE: matrix size is defined by:\n\t//       _n_max - hard constant representing maximum allocated space of size _n_max*_n_max\n\t//       _n     - \"full feature set\" dimensionality, _n<=_n_max. If Indexed_Matrix servers as output buffer\n\t//                to store matrices of various (reduced) dimensionalites, this is needed for correct functionality\n\t//                of at(), at_raw() etc. (both \"raw\" and \"non-raw\" matrix item access methods)\n\t//       _d     - \"virtual subset\" dimensionality, _d<=_n. Assuming the matrix holds _n*_n values (_n consecutively stored\n\t//                rows of _n values each), a virtual sub-matrix can be defined and accessed using at() (\"non-raw\" methods)\n\tDIMTYPE _n_max;\n\tDIMTYPE _n; // initialized in learn(), WARNING: int sufficient ? note expressions like _classes*_n*_n\n\tvoid compute_Nsuminclass(PDataAccessor da);\n\tboost::scoped_array<DATATYPE> _Nsuminclass;\n\tboost::scoped_array<REALTYPE> _theta;// actually P(term|class)\n\tboost::scoped_array<REALTYPE> _Pc;\n\tboost::scoped_array<REALTYPE> _Pc_d; // for compute_MI\n\tboost::scoped_array<REALTYPE> _Pv;\n\tboost::scoped_array<REALTYPE> _MI;\n\tboost::scoped_array<REALTYPE> _IB;\n\n\tDIMTYPE _d;\n\t// NOTE: _index defines a sub-space of subs-space defined in _learn_index\n\tboost::scoped_array<DIMTYPE> _index; //!< maps feature subset indexes to raw (full set) feature indexes, used for narrow()ing\n\n\tIDXTYPE _allpatterns; // initialized in learn()\n\tREALTYPE _doc_avg_length; // initialized in compute__theta(), needed in compute_IB()\n\n\t// NOTE: _learn_index here is not used for narrow()ing, but for learn(da,sub)\n\tboost::scoped_array<DIMTYPE> _learn_index; // maps virtual sub-space _n dimensions to original _n_max dimensions\n};\n\ntemplate<typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nModel_Multinomial<DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::Model_Multinomial(const Model_Multinomial& mm) : // copy-constructor\n\tModel<SUBSET,DATAACCESSOR>(mm),\n\t_classes(mm._classes),\n\t_n_max(mm._n_max),\n\t_n(mm._n),\n\t_d(mm._d),\n\t_allpatterns(mm._allpatterns),\n\t_doc_avg_length(mm._doc_avg_length)\n{\n\tnotify(\"Model_Multinomial copy-constructor.\");\n\tif(_classes>0) {\n\t\t_Pc.reset(new REALTYPE[_classes]); memcpy((void *)_Pc.get(),(void *)(mm._Pc).get(),sizeof(REALTYPE)*_classes);\n\t\t_Pc_d.reset(new REALTYPE[_classes]); memcpy((void *)_Pc_d.get(),(void *)(mm._Pc_d).get(),sizeof(REALTYPE)*_classes);\n\t\tif(_n_max>0) {\n\t\t\t_Nsuminclass.reset(new DATATYPE[_n_max*_classes]); memcpy((void *)_Nsuminclass.get(),(void *)(mm._Nsuminclass).get(),sizeof(DATATYPE)*_n_max*_classes);\n\t\t\t_theta.reset(new REALTYPE[_n_max*_classes]); memcpy((void *)_theta.get(),(void *)(mm._theta).get(),sizeof(REALTYPE)*_n_max*_classes);\n\t\t}\n\t}\n\tif(_n_max>0)\n\t{\n\t\t_Pv.reset(new REALTYPE[_n_max]); memcpy((void *)_Pv.get(),(void *)(mm._Pv).get(),sizeof(REALTYPE)*_n_max);\n\t\t_MI.reset(new REALTYPE[_n_max]); memcpy((void *)_MI.get(),(void *)(mm._MI).get(),sizeof(REALTYPE)*_n_max);\n\t\t_IB.reset(new REALTYPE[_n_max]); memcpy((void *)_IB.get(),(void *)(mm._IB).get(),sizeof(REALTYPE)*_n_max);\n\t\t// to store subsubspace info of the (possibly subspace-learned) learned model\n\t\t_index.reset(new DIMTYPE[_n_max]); memcpy((void *)_index.get(),(void *)(mm._index).get(),sizeof(DIMTYPE)*_n_max);\n\t\t// to store subspace info for the to-be-learned model\n\t\t_learn_index.reset(new DIMTYPE[_n_max]); memcpy((void *)_learn_index.get(),(void *)(mm._learn_index).get(),sizeof(DIMTYPE)*_n_max);\n\t}\n}\n\ntemplate<typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nvoid Model_Multinomial<DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::learn(PDataAccessor da)\n{\n\tassert(da);\n\tassert(da->getNoOfClasses()>0);\n\tassert(da->getNoOfFeatures()>0);\n\tPSubset fullset(new SUBSET(da->getNoOfFeatures()));\n\tfullset->select_all();\n#ifdef DEBUG\n\t{std::ostringstream sos; sos << \"fullset = \"<< *fullset << std::endl; syncout::print(std::cout,sos);}\n#endif\n\tlearn(da,fullset);\n}\n\ntemplate<typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nvoid Model_Multinomial<DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::learn(PDataAccessor da, const PSubset sub)\n{\n#ifdef DEBUG\n\t{std::ostringstream sos; sos <<\"Model_Multinomial::learn():\"<<std::endl; syncout::print(std::cout,sos);}\n#endif\n\tassert(sub);\n\tassert(da->getNoOfClasses()>0);\n\tassert(da->getNoOfFeatures()>0);\n\tassert(sub->get_n_raw()==da->getNoOfFeatures());\n\n\tif(_classes!=da->getNoOfClasses() || sub->get_n_raw()>_n_max) // insufficient buffers - reset constants and reallocate\n\t{\n\t\t_classes=da->getNoOfClasses();\n\t\t_n_max=sub->get_n_raw();\n\n\t\t_learn_index.reset(new DIMTYPE[_n_max]); // to store subspace info about the to-be-learned model\n\t\t_index.reset(new DIMTYPE[_n_max]); for(DIMTYPE f=0;f<_n_max;f++) _index[f]=f; // to store subsubspace info of the (possibly subspace-learned) learned model\n\t\t_Nsuminclass.reset(new DATATYPE[_n_max*_classes]);\n\t\t_theta.reset(new REALTYPE[_n_max*_classes]);\n\t\t_Pv.reset(new REALTYPE[_n_max]);\n\t\t_MI.reset(new REALTYPE[_n_max]);\n\t\t_IB.reset(new REALTYPE[_n_max]);\n\t\t_Pc.reset(new REALTYPE[_classes]);\n\t\t_Pc_d.reset(new REALTYPE[_classes]);\n\t\t// NOTE: class priors are estimated from complete data available through da.\n\t\t//       Note that when only parts of data are processed (i.e., using data splits), the\n\t\t//       estimates below would possibly not precisely depict the relative frequency of documents\n\t\t//       in stratified class parts, esp. if class sizes are small\n\t\tIDXTYPE _classsizesum=da->getClassSizeSum();\n\t\tassert(_classsizesum>0);\n\t\tif(_classsizesum==0) throw FST::fst_error(\"Model_Multinomial::learn: zero _classsizesum\");\n\t\tfor(DIMTYPE c=0;c<_classes;c++) _Pc[c]=(REALTYPE)da->getClassSize(c)/(REALTYPE)_classsizesum;\n\t}\n\t_n=sub->get_d_raw(); // actual to-be-learned model dimensionality is to be the one defined by the subset defined in sub\n\t_d=_n; // access to learned model is initially not narrow()ed\n\tDIMTYPE f, fi=0;\n\tfor(bool b=sub->getFirstFeature(f);b==true;b=sub->getNextFeature(f)) {_learn_index[fi++]=f;}\n\tassert(fi==_n);\n\t\n#ifdef DEBUG\n\t{\n\t\tstd::ostringstream sos; sos << \"_Pc:\"<<std::endl;\n\t\tfor(DIMTYPE c=0;c<_classes;c++) sos << _Pc[c] << \" \"; sos << std::endl;\n\t\tsyncout::print(std::cout,sos);\n\t}\n#endif\n\tcompute_Nsuminclass(da); // sub info passed in form of _learn_index\n\t\n\tDATATYPE total_sum_length=0;\n\tDIMTYPE wCV=0;\n\tfor(DIMTYPE c=0;c<_classes;c++) {\n\t\tfor(DIMTYPE f=0;f<_n;f++) total_sum_length+=_Nsuminclass[wCV+f];\n\t\twCV+=_n;\n\t}\n\tif(total_sum_length==0) {\n\t\tfor(DIMTYPE c=0;c<_classes;c++) _Pc_d[c]=1.0/(REALTYPE)_classes; // workaround to prevent division by zero below\n\t} else {\n\t\twCV=0;\n\t\tfor(DIMTYPE c=0;c<_classes;c++) {\n\t\t\tDATATYPE class_sum_length=0;\n\t\t\tfor(DIMTYPE f=0;f<_n;f++) class_sum_length+=_Nsuminclass[wCV+f]; // in subset case this is done only for selected features\n\t\t\t_Pc_d[c]=(REALTYPE)class_sum_length/(REALTYPE)total_sum_length;\n\t\t\twCV+=_n;\n\t\t}\n\t}\n}\n\ntemplate<typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nvoid Model_Multinomial<DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::compute_Nsuminclass(PDataAccessor da)\n{\n\tassert(_learn_index);\n\tassert(_Nsuminclass);\n\tfor(DIMTYPE i=0;i<_classes*_n;i++) _Nsuminclass[i]=0;\n\ttypename DATAACCESSOR::PPattern p;\n\tIDXTYPE cnt;\n\tassert(da->getSplitIndex()>0); // \n\tDIMTYPE wCV=0;\n\tDIMTYPE _features=da->getNoOfFeatures();\n\t_allpatterns=0;\n\tfor(DIMTYPE c=0;c<_classes;c++) {\n\t\tda->setClass(c);\n\t\tfor(bool b=da->getFirstBlock(TRAIN,p,cnt);b!=false;b=da->getNextBlock(TRAIN,p,cnt)) {\n\t\t\tfor(IDXTYPE i=0;i<cnt;i++) {\n\t\t\t\tfor(DIMTYPE f=0;f<_n;f++) {_Nsuminclass[wCV+f]+=p[i*_features+_learn_index[f]];}\n\t\t\t}\n\t\t\t_allpatterns+=cnt;\n\t\t}\n\t\twCV+=_n;\n\t}\n#ifdef DEBUG\n\t{\n\t\tstd::ostringstream sos; sos <<\"_Nsuminclass:\"<<std::endl;\n\t\tfor(DIMTYPE c=0;c<_classes;c++) {for(DIMTYPE f=0;f<_n;f++) sos << _Nsuminclass[c*_n+f] << \" \"; sos << std::endl;}\n\t\tsyncout::print(std::cout,sos);\n\t}\n#endif\n}\n\ntemplate<typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nvoid Model_Multinomial<DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::compute_theta()\n{\n\tassert(_classes>0);\n\tassert(_n>0);\n\tassert(_d>0 || _d<=_n);\n\tassert(_index);\n\tassert(_allpatterns>0);\n\tassert(_Nsuminclass);\n\tassert(_theta);\n\tDATATYPE total_sum_length=0;\n\tDIMTYPE wCV=0, wCd=0;\n\tfor(DIMTYPE c=0;c<_classes;c++) {\n\t\tDATATYPE class_sum_length=0;\n\t\tfor(DIMTYPE f=0;f<_d;f++) class_sum_length+=_Nsuminclass[wCV+_index[f]]; // in subset case this is done only for selected features\n\t\ttotal_sum_length+=class_sum_length;\n\t\tfor(DIMTYPE f=0;f<_d;f++) { // in subset case this is done only for selected features\n\t\t\t_theta[wCd++]=(1.0+(REALTYPE)_Nsuminclass[wCV+_index[f]])/((REALTYPE)_d+(REALTYPE)class_sum_length); // in subset case substitute d (subset size) for _n\n\t\t}\n\t\twCV+=_n;\n\t}\n\tif(_allpatterns==0) throw FST::fst_error(\"Model_Multinomial::compute_theta: division by zero _allpatterns\");\n\t_doc_avg_length=(REALTYPE)total_sum_length/(REALTYPE)_allpatterns;\n#ifdef DEBUG\n\t{\n\t\tstd::ostringstream sos; sos <<\"_theta:\"<<std::endl;\n\t\tfor(DIMTYPE c=0;c<_classes;c++) {\n\t\t\tREALTYPE tmp=0.0;\n\t\t\tfor(DIMTYPE f=0;f<_d;f++) {tmp+=_theta[c*_d+f]; sos << _theta[c*_d+f] << \" \"; sos << std::endl;}\n\t\t\tsos << \"theta sum over class<\"<<c<<\">: \"<<tmp<<std::endl;\n\t\t}\n\t\tsos << \"total_sum_length=\"<<total_sum_length<<\", doc_avg_length=\"<<_doc_avg_length<<std::endl;\n\t\tsyncout::print(std::cout,sos);\n\t}\n#endif\n}\n\ntemplate<typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nvoid Model_Multinomial<DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::narrow_to(const PSubset sub)\n{\n\tassert(_index);\n\tassert(sub);\n\tassert(sub->get_n_raw()==_n); // NOTE: sub should represent subspace of the learned subspace ! not of the full space\n\tassert(sub->get_d_raw()>0);\n\tDIMTYPE f;\n\t_d=0;\n\tfor(bool b=sub->getFirstFeature(f);b!=false;b=sub->getNextFeature(f)) _index[_d++]=f;\n\tassert(_d>0 && _d<=_n);\n}\n\ntemplate<typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nvoid Model_Multinomial<DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::denarrow()\n{\n\tassert(_index);\n\tfor(DIMTYPE i=0;i<_n;i++) _index[i]=i;\n\t_d=_n;\n}\n\ntemplate<typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nvoid Model_Multinomial<DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::compute_MI()\n{\n\t// NOTE: needs _theta computed for full feature set\n\tassert(_classes>0);\n\tassert(_n>0);\n\tassert(_Nsuminclass);\n\tassert(_theta);\n\tassert(_Pc);\n\tassert(_Pv);\n\tassert(_MI);\n\tfor(DIMTYPE f=0;f<_n;f++) _MI[f]=0.0;\n\tDIMTYPE wCV=0;\n\tDATATYPE sum=0;\n\tfor(DIMTYPE c=0;c<_classes;c++) {\n\t\tfor(DIMTYPE f=0;f<_n;f++) {\n\t\t\t_MI[f]+=_Nsuminclass[wCV+f];\n\t\t\tsum+=_Nsuminclass[wCV+f];\n\t\t}\n\t\twCV+=_n;\n\t}\n\tfor(DIMTYPE f=0;f<_n;f++) {if(sum>0.0) _Pv[f]=(_MI[f])/((REALTYPE)sum); else _Pv[f]=0.0;}\n\t\n\tfor(DIMTYPE f=0;f<_n;f++) {\n\t\t_MI[f]=0.0;\n\t\tif(_Pv[f]>0.0) {\n\t\t\twCV=0;\n\t\t\tfor(DIMTYPE c=0;c<_classes;c++) {\n\t\t\t\t//_MI[f]+=_theta[wCV+f]*_Pc_d[c]*fabs( (REALTYPE)log(_theta[wCV+f]/_Pv[f]) ); // IG abs\n\t\t\t\t//_MI[f]+=_theta[wCV+f]*_Pc_d[c]*(REALTYPE)log(_theta[wCV+f]/_Pv[f]); // IG\n\t\t\t\t//_MI[f]+=_Pc_d[c]*fabs( (REALTYPE)log(_theta[wCV+f]/_Pv[f]) ); // MI abs\n\t\t\t\t_MI[f]+=_Pc_d[c]*(REALTYPE)log(_theta[wCV+f]/_Pv[f]); // MI\n\t\t\t\twCV+=_n;\n\t\t\t}\n\t\t}\n\t}\n#ifdef DEBUG\n\t{\n\t\tstd::ostringstream sos; sos <<\"_MI:\"<<std::endl;\n\t\tfor(DIMTYPE f=0;f<_n;f++) sos << _MI[f] << \" \"; sos << std::endl;\n\t\tsyncout::print(std::cout,sos);\n\t}\n#endif\n}\n\ntemplate<typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nvoid Model_Multinomial<DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::compute_IB()\n{\n\t// NOTE: needs _theta computed for full feature set\n\tassert(_classes>0);\n\tassert(_n>0);\n\tassert(_doc_avg_length>0);\n\tassert(_theta);\n\tassert(_Pc);\n\tassert(_IB);\n\tfor(DIMTYPE f=0;f<_n;f++) _IB[f]=0.0;\n\tDIMTYPE wCV1,wCV2;\n\tDIMTYPE combs;\n\tREALTYPE _thetasum, value;\n\tfor(DIMTYPE f=0;f<_n;f++) {\n\t\tvalue=0.0; combs=0;\n\t\twCV1=0;\n\t\tfor(DIMTYPE c1=0;c1<_classes;c1++) {\n\t\t\twCV2=wCV1+_n;\n\t\t\tfor(DIMTYPE c2=c1+1;c2<_classes;c2++) {\n\t\t\t\t_thetasum=sqrt(_theta[wCV1+f]*_theta[wCV2+f])+sqrt((1.0-_theta[wCV1+f])*(1.0-_theta[wCV2+f]));\n#ifdef DEBUG\n\t\t\t\t{std::ostringstream sos; sos << _thetasum<< std::endl; syncout::print(std::cout,sos);}\n#endif\n\t\t\t\tvalue+=((-_doc_avg_length)*(REALTYPE)log(_thetasum))*_Pc_d[c1]*_Pc_d[c2];\n\t\t\t\tcombs++;\n\t\t\t\twCV2+=_n;\n\t\t\t}\n\t\t\twCV1+=_n;\n\t\t}\n\t\tassert(combs>0);\n\t\tif(combs==0) throw FST::fst_error(\"Model_Multinomial::compute_IB: division by zero combs\");\n\t\t_IB[f]=value/(REALTYPE)combs; \n\t}\n#ifdef DEBUG\n\t{\n\t\tstd::ostringstream sos; sos <<\"_IB:\"<<std::endl;\n\t\tfor(DIMTYPE f=0;f<_n;f++) sos << _IB[f] << \" \"; sos << std::endl;\n\t\tsyncout::print(std::cout,sos);\n\t}\n#endif\n}\n\n\n} // namespace\n#endif // FSTMODELMULTINOM_H ///:~\n", "meta": {"hexsha": "c0039ab68d4dccec62619af515a8a817b672b08c", "size": 20117, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "extern/FST3lib/_src_criteria/model_multinom.hpp", "max_stars_repo_name": "boussaffawalid/FeatureSelection", "max_stars_repo_head_hexsha": "9768a044c0c0dc2c4a2dc0f6e65413d19e92766c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-07-07T20:18:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-23T06:46:02.000Z", "max_issues_repo_path": "extern/FST3lib/_src_criteria/model_multinom.hpp", "max_issues_repo_name": "boussaffawalid/FeatureSelection", "max_issues_repo_head_hexsha": "9768a044c0c0dc2c4a2dc0f6e65413d19e92766c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T08:35:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-10T08:57:35.000Z", "max_forks_repo_path": "extern/FST3lib/_src_criteria/model_multinom.hpp", "max_forks_repo_name": "boussaffawalid/FeatureSelection", "max_forks_repo_head_hexsha": "9768a044c0c0dc2c4a2dc0f6e65413d19e92766c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-04-13T13:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-02-26T08:18:47.000Z", "avg_line_length": 44.3105726872, "max_line_length": 157, "alphanum_fraction": 0.704975891, "num_tokens": 5808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.26138470744939374}}
{"text": "#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\n#include <cmath>\n#include <memory>\n#include <vector>\n#include <limits>\n#include <algorithm>\n#include <utility>\n#include <iterator>\n\n#include \"statespace.hpp\"\n\nusing namespace boost::numeric::ublas;\n\n\nCompactSupportSSM::CompactSupportSSM(\\\n       const vector<int> & start_idxs, const vector <int > & end_idxs,\n       const vector<int> & identities, const matrix<double> & basis_prototypes,\n       const vector<double> & coef_means,  const vector<double> & coef_vars,\n       double obs_noise, double bias) : start_idxs(start_idxs), end_idxs(end_idxs),\n\t\t\t\t\tidentities(identities), basis_prototypes(basis_prototypes),\n\t\t\t\t\tcoef_means(coef_means), coef_vars(coef_vars),\n\t\t\t\t\tobs_noise(obs_noise), bias(bias) {\n\n  this->is_cssm = true;\n  this->n_basis = start_idxs.size();\n  this->n_steps = *(std::max_element(end_idxs.begin(), end_idxs.end()));\n\n  if (coef_means.size() != this->n_basis) {\n    printf(\"ERROR: coef prior mean length must match size of basis\\n\");\n    exit(-1);\n  }\n  if (coef_vars.size() != this->n_basis) {\n    printf(\"ERROR: coef prior vars length must match size of basis\\n\");\n    exit(-1);\n  }\n\n  std::vector< std::vector<int> > tmp_active_basis(this->n_steps);\n\n  this->active_indices.set_empty_key(std::make_pair(-1,-1) );\n\n  unsigned int i;\n  vector<int>::const_iterator st;\n  vector<int>::const_iterator et;\n  for( i = 0, st = this->start_idxs.begin(), et = this->end_idxs.begin() ;\n       i < this->n_basis && st < this->start_idxs.end() && et < this->end_idxs.end();\n       ++i, ++st, ++et ) {\n\n    for (unsigned j= std::max(*st, 0); j < std::min((unsigned int)*et, this->n_steps); ++j) {\n      tmp_active_basis[j].push_back(i);\n      (this->active_indices)[std::make_pair(i,j)] = int(tmp_active_basis[j].size()-1);\n    }\n  }\n\n  int max_dimension = 0;\n  for (unsigned i=0; i < this->n_steps; ++i) {\n    max_dimension = std::max(max_dimension, int(tmp_active_basis[i].size()));\n  }\n  this->max_dimension = max_dimension;\n\n  this->active_basis = matrix<int>(this->n_steps, max_dimension);\n  for (unsigned i=0; i < this->n_steps; ++i) {\n    int j = 0;\n    for(j=0; j < int(tmp_active_basis[i].size()); ++j) {\n      this->active_basis(i,j) = tmp_active_basis[i][j];\n    }\n    if (j < max_dimension) {\n      this->active_basis(i,j) = -1;\n    }\n  }\n\n  // printf(\"identities len %d\\n\", this->identities.size());\n\n\n}\n\nCompactSupportSSM::~CompactSupportSSM() {\n  return;\n};\n\n\nint CompactSupportSSM::apply_transition_matrix( const double * x, int k, double * result) {\n  /* compute F_k*x for the given x, where\n     F_k is the transition matrix from time\n     k-1 to k. The result is stored in\n     the provided vector x_new. If x_new\n     has extra dimensions, they are not\n     touched (so may still contain garbage).*/\n\n  if (k <= 0) {\n    printf(\"error: applying CSSM transition at invalid index %d.\\n\", k);\n    exit(-1);\n  }\n\n  for (int i=0; i < this->max_dimension; ++i) {\n    result[i] = 0;\n  }\n\n  if (k >= this->n_steps) {\n    return 0;\n  }\n\n\n  const matrix_row< matrix<int> > active = row(this->active_basis, k);\n  matrix_row< matrix<int> >::const_iterator idx;\n  int i = 0;\n  for (i=0, idx = active.begin();\n       idx < active.end() && *idx >= 0;\n       ++i, ++idx) {\n    // if this basis is new at this timestep, initialize to zero.\n    // otherwise, use its previous value.\n    std::pair<int,int> key = std::make_pair(int(*idx), k-1);\n    dense_hash_map< std::pair<int, int>, int, boost::hash< std::pair< int,int> >  >::iterator contains = this->active_indices.find(key);\n    if (contains == this->active_indices.end()) {\n      result[i] = 0;\n      D(printf(\"transition k %d basis %d idx %d prev_idx %d x_new[i] %.4f\\n\", k, *idx, i, -1, 0.0);)\n    } else {\n      int prev_idx = this->active_indices[key];\n      result[i] =x[prev_idx];\n      D(printf(\"transition k %d basis %d idx %d prev_idx %d x_new[i] %.4f\\n\", k, *idx, i, prev_idx, x[prev_idx]);)\n    }\n  }\n  return i;\n}\n\n/* Each column of the input X gives a column of the result matrix */\nint CompactSupportSSM::apply_transition_matrix( const matrix<double> &X,\n\t\t\t\t\t\tunsigned int x_row_offset,\n\t\t\t\t\t\tint k,\n\t\t\t\t\t\tmatrix<double> &result,\n\t\t\t\t\t\tunsigned int r_row_offset,\n\t\t\t\t\t\tunsigned int n) {\n  if (k <= 0) {\n    printf(\"error: applying CSSM transition at invalid index %d.\\n\", k);\n    exit(-1);\n  }\n\n  for (int i=r_row_offset; i < r_row_offset+this->max_dimension; ++i) {\n    for (int j =0; j < n; ++j) {\n      result(i,j) = 0;\n    }\n  }\n\n  if (k >= this->n_steps) {\n    return 0;\n  }\n\n\n\n  const matrix_row< matrix<int> > active = row(this->active_basis, k);\n  matrix_row< matrix<int> >::const_iterator idx;\n  unsigned i = r_row_offset;\n\n  for (i=r_row_offset, idx = active.begin();\n       idx < active.end() && *idx >= 0;\n       ++i, ++idx) {\n\n    // if this basis is new at this timestep, initialize to zero.\n    // otherwise, use its previous value.\n    std::pair<int,int> key = std::make_pair(int(*idx), k-1);\n    dense_hash_map< std::pair<int, int>, int, boost::hash< std::pair< int,int> >  >::iterator contains = this->active_indices.find(key);\n\n    if (contains == this->active_indices.end()) {\n      for (unsigned j=0; j < n; ++j) result(i, j) = 0;\n      // printf(\"MATR0 transition k %d i %d idx %d prev_idx %d x_new[i,i] %.4f\\n\", k, i, *idx, -1, 0.0);\n    } else {\n      int prev_idx = this->active_indices[key] + x_row_offset;\n      for (unsigned j=0; j < n; ++j) result(i, j) = X(prev_idx, j);\n      //printf(\"MATR1 transition k %d i %d idx %d prev_idx %d x_new[i, i] %.4f\\n\", k, i, *idx, prev_idx, X(prev_idx, prev_idx));\n    }\n  }\n  return i-r_row_offset;\n}\n\n\nvoid CompactSupportSSM::transition_bias(int k, double * result) {\n  if (k >= this->n_steps) {\n    return;\n  }\n\n  const matrix_row< matrix<int> > active = row(this->active_basis, k);\n  matrix_row< matrix<int> >::const_iterator idx;\n  int i = 0;\n  for (i=0, idx = active.begin();\n       idx < active.end() && *idx >= 0;\n       ++i, ++idx) {\n\n    // if this basis is new at this timestep, initialize to zero.\n    // otherwise, use its previous value.\n    std::pair<int,int> key = std::make_pair(*idx, k-1);\n    dense_hash_map< std::pair<int, int>, int, boost::hash< std::pair< int,int> >  >::iterator contains = this->active_indices.find(key);\n    if (contains == this->active_indices.end()) {\n      result[i] += this->coef_means(*idx);\n    }\n  }\n}\n\n\nvoid CompactSupportSSM::transition_noise_diag(int k, double * result) {\n  if (k >= this->n_steps) {\n    return;\n  }\n\n  unsigned int i = 0;\n  for (i; i < this->max_dimension; ++i) {\n    result[i] = 0.0;\n  }\n\n\n  const matrix_row< matrix<int> > active = row(this->active_basis, k);\n  matrix_row< matrix<int> >::const_iterator idx;\n  for (i=0, idx = active.begin();\n       idx < active.end() && *idx >= 0;\n       ++i, ++idx) {\n    std::pair<int,int> key = std::make_pair(*idx, k-1);\n    dense_hash_map< std::pair<int, int>, int, boost::hash< std::pair< int,int> >  >::iterator contains = this->active_indices.find(key);\n    if (contains == this->active_indices.end()) {\n      result[i] = this->coef_vars(*idx);\n      //D(printf(\"time %d instantiating coef %d into state %d with noise variance %f\\n\", k, *idx, i, result[i]);)\n    } else {\n      result[i] = 0.0;\n    }\n  }\n}\n\ndouble CompactSupportSSM::apply_observation_matrix(const double * x, int k) {\n  // const matrix_row< matrix<int> > active = row(this->active_basis, k);\n\n  double result = 0;\n\n  if (k >= this->n_steps) {\n    return 0;\n  }\n\n\n  matrix_row< matrix<int> >::const_iterator idx;\n  unsigned int i = 0;\n  for (i=0; i < this->active_basis.size2() && this->active_basis(k, i) >= 0; ++i) {\n    int basis = this->active_basis(k, i);\n\n    int prototype = (this->identities)(basis);\n    int st = (this->start_idxs)(basis);\n\n    result += x[i] * (this->basis_prototypes)(prototype, k-st);\n  }\n\n  return result;\n}\n\nvoid CompactSupportSSM::apply_observation_matrix(const matrix<double> &X,\n\t\t\t\t\t\t unsigned int row_offset, int k,\n\t\t\t\t\t\t double *result, double *result_tmp, unsigned int n) {\n  //const matrix_row< matrix<int> > active = row(this->active_basis, k);\n  //matrix_row< matrix<int> >::const_iterator idx;\n\n\n  for (unsigned j=0; j < n; ++j) {\n    result[j] = 0;\n  }\n\n  if (k >= this->n_steps) {\n    return;\n  }\n\n  unsigned int i = 0;\n  for (i=0; i < this->active_basis.size2() && this->active_basis(k, i) >= 0; ++i) {\n    int basis = this->active_basis(k, i);\n\n    int prototype = this->identities(basis);\n    int st = this->start_idxs(basis);\n\n    for (unsigned j=0; j < n; ++j) {\n      result[j] += X(row_offset+i,j) * this->basis_prototypes(prototype, k-st);\n    }\n  }\n}\n\n\ndouble CompactSupportSSM::observation_bias(int k) {\n  return this->bias;\n}\n\ndouble CompactSupportSSM::observation_noise(int k) {\n  return this->obs_noise;\n}\n\nbool CompactSupportSSM::stationary(int k) {\n  return k >= this->n_steps;\n}\n\nint CompactSupportSSM::prior_mean(double *result) {\n  const matrix_row< matrix<int> > active = row(this->active_basis, 0);\n  matrix_row< matrix<int> >::const_iterator idx;\n  int i = 0;\n\n  for (i=0, idx = active.begin();\n       idx < active.end() && *idx >= 0;\n       ++i, ++idx) {\n    result[i] = this->coef_means(*idx);\n  }\n  for (unsigned ii=i; ii < this->max_dimension; ++ii) {\n    result[ii] = 0.0;\n  }\n  return i;\n}\n\nint CompactSupportSSM::prior_vars(double *result) {\n  const matrix_row< matrix<int> > active = row(this->active_basis, 0);\n  matrix_row< matrix<int> >::const_iterator idx;\n  int i = 0;\n  for (i=0, idx = active.begin();\n       idx < active.end() && *idx >= 0;\n       ++i, ++idx) {\n    result[i] = this->coef_vars(*idx);\n  }\n  for (unsigned ii=i; ii < this->max_dimension; ++ii) {\n    result[ii] = 0.0;\n  }\n\n  return i;\n}\n\n\nvoid CompactSupportSSM::extract_coefs(const vector<double> &x,\n\t\t\t\t      const matrix<double> &P,\n\t\t\t\t      unsigned int state_offset,\n\t\t\t\t      int k,\n\t\t\t\t      vector<double> & coef_means,\n\t\t\t\t      vector<double> & coef_vars) {\n\n  if (k >= this->n_steps) {\n    return;\n  }\n\n\n  /* given a state estimate at some time k, extract marginals for\n   * whatever coefficients we can reasonably do so for at the\n   * current time. Earlier estimates will always be overwritten\n   * by later ones. */\n  const matrix_row< matrix<int> > active = row(this->active_basis, k);\n  matrix_row< matrix<int> >::const_iterator idx;\n  unsigned int i;\n\n  for (i=0, idx = active.begin();\n       idx < active.end() && *idx >= 0;\n       ++i, ++idx) {\n    int basis_idx = *idx;\n    std::pair<int,int> key = std::make_pair(basis_idx, k);\n\n    dense_hash_map< std::pair<int, int>, int, boost::hash< std::pair< int,int> >  >::iterator contains = this->active_indices.find(key);\n    if (contains == this->active_indices.end()) {\n      printf(\"\\nWAAT, no key found for basis %d\\n\", basis_idx);\n      exit(-1);\n    } else {\n      int state_idx = this->active_indices[key] + state_offset;\n      coef_means(basis_idx) = x(state_idx);\n      coef_vars(basis_idx) = P(state_idx,state_idx);\n\n\n      //printf(\"extracted coef %d var %f from state %d at cssm-local time %d\\n\", basis_idx, coef_vars(basis_idx), state_idx, k);\n      /*if (coef_vars(basis_idx) == 0) {\n\tprintf(\"WARNING: posterior coef var is zero for basis %d at state %d at time %d, this doesn't seem right....\\n\", basis_idx, state_idx, k);\n\t//exit(-1);\n\t}*/\n    }\n  }\n}\n", "meta": {"hexsha": "f65d05c4a685fecec69015670c1ea40e6a561f59", "size": 11306, "ext": "cc", "lang": "C++", "max_stars_repo_path": "models/statespace/fast_c/compact_support.cc", "max_stars_repo_name": "davmre/sigvisa", "max_stars_repo_head_hexsha": "91a1f163b8f3a258dfb78d88a07f2a11da41bd04", "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/statespace/fast_c/compact_support.cc", "max_issues_repo_name": "davmre/sigvisa", "max_issues_repo_head_hexsha": "91a1f163b8f3a258dfb78d88a07f2a11da41bd04", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/statespace/fast_c/compact_support.cc", "max_forks_repo_name": "davmre/sigvisa", "max_forks_repo_head_hexsha": "91a1f163b8f3a258dfb78d88a07f2a11da41bd04", "max_forks_repo_licenses": ["BSD-3-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.6395663957, "max_line_length": 139, "alphanum_fraction": 0.6198478684, "num_tokens": 3337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.26138469522438035}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2012-21 John Maddock.\n//  Copyright 2021 Iskandarov Lev. 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_INTEGER_HPP\n#define BOOST_MP_INTEGER_HPP\n\n#include <type_traits>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/detail/bitscan.hpp>\n#include <boost/multiprecision/detail/no_exceptions_support.hpp>\n#include <boost/multiprecision/detail/standalone_config.hpp>\n\nnamespace boost {\nnamespace multiprecision {\n\ntemplate <class Integer, class I2>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_integral<Integer>::value && boost::multiprecision::detail::is_integral<I2>::value, Integer&>::type\nmultiply(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>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_integral<Integer>::value && boost::multiprecision::detail::is_integral<I2>::value, Integer&>::type\nadd(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>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_integral<Integer>::value && boost::multiprecision::detail::is_integral<I2>::value, Integer&>::type\nsubtract(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>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::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>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_integral<I1>::value && boost::multiprecision::detail::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 long long),\n// otherwise synthesize a cpp_int to do the job.\n//\ntemplate <class I>\nstruct double_integer\n{\n   static constexpr const unsigned int_t_digits =\n       2 * sizeof(I) <= sizeof(long long) ? std::numeric_limits<I>::digits * 2 : 1;\n\n   using type = typename std::conditional<\n       2 * sizeof(I) <= sizeof(long long),\n       typename std::conditional<\n           boost::multiprecision::detail::is_signed<I>::value && boost::multiprecision::detail::is_integral<I>::value,\n           typename boost::multiprecision::detail::int_t<int_t_digits>::least,\n           typename boost::multiprecision::detail::uint_t<int_t_digits>::least>::type,\n       typename std::conditional<\n           2 * sizeof(I) <= sizeof(double_limb_type),\n           typename std::conditional<\n               boost::multiprecision::detail::is_signed<I>::value && boost::multiprecision::detail::is_integral<I>::value,\n               signed_double_limb_type,\n               double_limb_type>::type,\n           number<cpp_int_backend<sizeof(I) * CHAR_BIT * 2, sizeof(I) * CHAR_BIT * 2, (boost::multiprecision::detail::is_signed<I>::value ? signed_magnitude : unsigned_magnitude), unchecked, void> > >::type>::type;\n};\n\n} // namespace detail\n\ntemplate <class I1, class I2, class I3>\nBOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_integral<I1>::value && boost::multiprecision::detail::is_unsigned<I2>::value && boost::multiprecision::detail::is_integral<I3>::value, I1>::type\npowm(const I1& a, I2 b, I3 c)\n{\n   using double_type = typename detail::double_integer<I1>::type;\n\n   I1          x(1), y(a);\n   double_type result(0);\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 BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_integral<I1>::value && boost::multiprecision::detail::is_signed<I2>::value && boost::multiprecision::detail::is_integral<I2>::value && boost::multiprecision::detail::is_integral<I3>::value, I1>::type\npowm(const I1& a, I2 b, I3 c)\n{\n   if (b < 0)\n   {\n      BOOST_MP_THROW_EXCEPTION(std::runtime_error(\"powm requires a positive exponent.\"));\n   }\n   return powm(a, static_cast<typename boost::multiprecision::detail::make_unsigned<I2>::type>(b), c);\n}\n\ntemplate <class Integer>\nBOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_integral<Integer>::value, std::size_t>::type lsb(const Integer& val)\n{\n   if (val <= 0)\n   {\n      if (val == 0)\n      {\n         BOOST_MP_THROW_EXCEPTION(std::domain_error(\"No bits were set in the operand.\"));\n      }\n      else\n      {\n         BOOST_MP_THROW_EXCEPTION(std::domain_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>\nBOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_integral<Integer>::value, std::size_t>::type msb(Integer val)\n{\n   if (val <= 0)\n   {\n      if (val == 0)\n      {\n         BOOST_MP_THROW_EXCEPTION(std::domain_error(\"No bits were set in the operand.\"));\n      }\n      else\n      {\n         BOOST_MP_THROW_EXCEPTION(std::domain_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>\nBOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_integral<Integer>::value, bool>::type bit_test(const Integer& val, std::size_t 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>\nBOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_integral<Integer>::value, Integer&>::type bit_set(Integer& val, std::size_t 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>\nBOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_integral<Integer>::value, Integer&>::type bit_unset(Integer& val, std::size_t 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>\nBOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_integral<Integer>::value, Integer&>::type bit_flip(Integer& val, std::size_t 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\nnamespace detail {\n\ntemplate <class Integer>\nBOOST_MP_CXX14_CONSTEXPR Integer karatsuba_sqrt(const Integer& x, Integer& r, size_t bits)\n{\n   //\n   // Define the floating point type used for std::sqrt, in our tests, sqrt(double) and sqrt(long double) take\n   // about the same amount of time as long as long double is not an emulated 128-bit type (ie the same type\n   // as __float128 from libquadmath).  So only use long double if it's an 80-bit type:\n   //\n#ifndef __clang__\n   typedef typename std::conditional<(std::numeric_limits<long double>::digits == 64), long double, double>::type real_cast_type;\n#else\n   // clang has buggy __int128 -> long double conversion:\n   typedef double real_cast_type;\n#endif\n   //\n   // As per the Karatsuba sqrt algorithm, the low order bits/4 bits pay no part in the result, only in the remainder,\n   // so define the number of bits our argument must have before passing to std::sqrt is safe, even if doing so\n   // looses a few bits:\n   //\n   constexpr std::size_t cutoff = (std::numeric_limits<real_cast_type>::digits * 4) / 3;\n   //\n   // Type which can hold at least \"cutoff\" bits:\n   // \n#ifdef BOOST_HAS_INT128\n   using cutoff_t = typename std::conditional<(cutoff > 64), uint128_type, std::uint64_t>::type;\n#else\n   using cutoff_t = std::uint64_t;\n#endif\n   //\n   // See if we can take the fast path:\n   //\n   if (bits <= cutoff)\n   {\n      constexpr cutoff_t half_bits = (cutoff_t(1u) << ((sizeof(cutoff_t) * CHAR_BIT) / 2)) - 1;\n      cutoff_t       val = static_cast<cutoff_t>(x);\n      real_cast_type real_val = static_cast<real_cast_type>(val);\n      cutoff_t       s64 = static_cast<cutoff_t>(std::sqrt(real_val));\n      // converting to long double can loose some precision, and `sqrt` can give eps error, so we'll fix this\n      // this is needed\n      while ((s64 > half_bits) || (s64 * s64 > val))\n         s64--;\n      // in my tests this never fired, but theoretically this might be needed\n      while ((s64 < half_bits) && ((s64 + 1) * (s64 + 1) <= val))\n         s64++;\n      r = static_cast<Integer>(val - s64 * s64);\n      return static_cast<Integer>(s64);\n   }\n   // https://hal.inria.fr/file/index/docid/72854/filename/RR-3805.pdf\n   std::size_t b = bits / 4;\n   Integer q = x;\n   q >>= b * 2;\n   Integer s = karatsuba_sqrt(q, r, bits - b * 2);\n   Integer t = 0u;\n   bit_set(t, static_cast<unsigned>(b * 2));\n   r <<= b;\n   t--;\n   t &= x;\n   t >>= b;\n   t += r;\n   s <<= 1;\n   divide_qr(t, s, q, r);\n   r <<= b;\n   t = 0u;\n   bit_set(t, static_cast<unsigned>(b));\n   t--;\n   t &= x;\n   r += t;\n   s <<= (b - 1); // we already <<1 it before\n   s += q;\n   q *= q;\n   // we substract after, so it works for unsigned integers too\n   if (r < q)\n   {\n      t = s;\n      t <<= 1;\n      t--;\n      r += t;\n      s--;\n   }\n   r -= q;\n   return s;\n}\n\ntemplate <class Integer>\nBOOST_MP_CXX14_CONSTEXPR Integer bitwise_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   std::ptrdiff_t 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   } while (g >= 0);\n   return s;\n}\n\n} // namespace detail\n\ntemplate <class Integer>\nBOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_integral<Integer>::value, Integer>::type sqrt(const Integer& x, Integer& r)\n{\n#ifndef BOOST_MP_NO_CONSTEXPR_DETECTION\n   // recursive Karatsuba sqrt can cause issues in constexpr context:\n   if (BOOST_MP_IS_CONST_EVALUATED(x))\n      return detail::bitwise_sqrt(x, r);\n#endif\n   if (x == 0u) {\n      r = 0u;\n      return 0u;\n   }\n\n   return detail::karatsuba_sqrt(x, r, msb(x) + 1);\n}\n\ntemplate <class Integer>\nBOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_integral<Integer>::value, Integer>::type sqrt(const Integer& x)\n{\n   Integer r(0);\n   return sqrt(x, r);\n}\n\n}} // namespace boost::multiprecision\n\n#endif\n", "meta": {"hexsha": "a8f07d64336e7f45c136a85f19cf7f1701f24847", "size": 11905, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/multiprecision/integer.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/integer.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/integer.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": 33.6299435028, "max_line_length": 289, "alphanum_fraction": 0.6615707686, "num_tokens": 3229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2613567386510007}}
{"text": "/*\n * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n *     https://www.orfeo-toolbox.org/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include \"itkNumericTraits.h\"\n\n#include \"otbSailModel.h\"\n#include \"otb_boost_expint_header.h\"\n#include <boost/shared_ptr.hpp>\n#include \"otbMath.h\"\n\n//TODO check EPSILON matlab\n#define EPSILON 0.0000000000000000000000001\n\nnamespace otb\n{\n\n/** Constructor */\nSailModel\n::SailModel() : m_LAI(2), m_Angl(50), m_PSoil(1), m_Skyl(70), m_HSpot(0.2),\n                m_TTS(30), m_TTO(0), m_PSI(0), m_FCoverView(0.0), m_UseSoilFile(false), m_SoilIndex(0)\n{\n  this->ProcessObject::SetNumberOfRequiredInputs(2);\n  this->ProcessObject::SetNumberOfRequiredOutputs(4);\n\n  SpectralResponseType::Pointer vRefl = static_cast<SpectralResponseType *>(this->MakeOutput(0).GetPointer());\n  this->itk::ProcessObject::SetNthOutput(0, vRefl.GetPointer());\n\n  SpectralResponseType::Pointer hRefl = static_cast<SpectralResponseType *>(this->MakeOutput(1).GetPointer());\n  this->itk::ProcessObject::SetNthOutput(1, hRefl.GetPointer());\n\n  SpectralResponseType::Pointer vAbs = static_cast<SpectralResponseType *>(this->MakeOutput(2).GetPointer());\n  this->itk::ProcessObject::SetNthOutput(2, vAbs.GetPointer());\n\n  SpectralResponseType::Pointer hAbs = static_cast<SpectralResponseType *>(this->MakeOutput(3).GetPointer());\n  this->itk::ProcessObject::SetNthOutput(3, hAbs.GetPointer());\n}\n\n/** Destructor */\nSailModel\n::~SailModel()\n{}\n\n/** Set/Get input reflectance */\nvoid\nSailModel\n::SetReflectance(const SpectralResponseType * object)\n{\n  this->itk::ProcessObject::SetNthInput(0, const_cast<SpectralResponseType *>(object));\n}\n\nSailModel::SpectralResponseType *\nSailModel\n::GetReflectance()\n                  {\n                    if(this->GetNumberOfInputs() != 2)\n                      {\n                      //exit\n                      return nullptr;\n                      }\n                    return static_cast<SpectralResponseType *>(this->itk::ProcessObject::GetInput(0));\n                  }\n\n/** Set/Get input transmittance */\n                  void\n                  SailModel\n                  ::SetTransmittance(const SpectralResponseType * object)\n                  {\n                    this->itk::ProcessObject::SetNthInput(1, const_cast<SpectralResponseType *>(object));\n                  }\n\n                  SailModel::SpectralResponseType *\n                  SailModel\n                  ::GetTransmittance()\n                  {\n                    if(this->GetNumberOfInputs() != 2)\n                      {\n                      //exit\n                      return nullptr;\n                      }\n                    return static_cast<SpectralResponseType *>(this->itk::ProcessObject::GetInput(1));\n                  }\n\n/** Make output */\n                  SailModel::DataObjectPointer\n                  SailModel\n                  ::MakeOutput(DataObjectPointerArraySizeType)\n                  {\n                    return static_cast<itk::DataObject*>(SpectralResponseType::New().GetPointer());\n                  }\n\n/** Get output viewing reflectance */\n                  SailModel::SpectralResponseType *\n                  SailModel\n                  ::GetViewingReflectance()\n                  {\n                    if(this->GetNumberOfOutputs() < 4)\n                      {\n                      //exit\n                      return nullptr;\n                      }\n                    return static_cast<SpectralResponseType *>(this->itk::ProcessObject::GetOutput(0));\n                  }\n\n/** Get output hemispherical reflectance */\n                  SailModel::SpectralResponseType *\n                  SailModel\n                  ::GetHemisphericalReflectance()\n                  {\n                    if(this->GetNumberOfOutputs() < 4)\n                      {\n                      //exit\n                      return nullptr;\n                      }\n                    return static_cast<SpectralResponseType *>(this->itk::ProcessObject::GetOutput(1));\n                  }\n\n/** Get output viewing absorptance */\n                  SailModel::SpectralResponseType *\n                  SailModel\n                  ::GetViewingAbsorptance()\n                  {\n                    if(this->GetNumberOfOutputs() < 4)\n                      {\n                      //exit\n                      return nullptr;\n                      }\n                    return static_cast<SpectralResponseType *>(this->itk::ProcessObject::GetOutput(2));\n                  }\n\n/** Get output hemispherical absorptance */\n                  SailModel::SpectralResponseType *\n                  SailModel\n                  ::GetHemisphericalAbsorptance()\n                  {\n                    if(this->GetNumberOfOutputs() < 4)\n                      {\n                      //exit\n                      return nullptr;\n                      }\n                    return static_cast<SpectralResponseType *>(this->itk::ProcessObject::GetOutput(3));\n                  }\n\n\n/** Set Parameters */\n                  void\n                  SailModel\n                  ::SetInput(const ParametersType & params)\n                  {\n\n                    if(params.Size()!=8) itkExceptionMacro( << \"Must have 8 parameters in that order : LAI, Angl, PSoil, Skyl, HSpot, TTS, TTO, PSI\" );\n                    this->SetParameters(params);\n                    m_LAI=params[0];\n                    m_Angl=params[1];\n   m_PSoil=params[2];\n   m_Skyl=params[3];\n   m_HSpot=params[4];\n   m_TTS=params[5];\n   m_TTO=params[6];\n   m_PSI=params[7];\n}\n\n/** Get Parameters */\nconst SailModel::ParametersType\nSailModel\n::GetInput()\n{\n  ParametersType parameters=this->GetParameters();\n   if(parameters.Size()!=8)\n   {\n      parameters[0]=m_LAI;\n      parameters[1]=m_Angl;\n      parameters[2]=m_PSoil;\n      parameters[3]=m_Skyl;\n      parameters[4]=m_HSpot;\n      parameters[5]=m_TTS;\n      parameters[6]=m_TTO;\n      parameters[7]=m_PSI;\n      this->SetParameters(parameters);\n   }\n   return this->GetParameters();\n}\n\n\n/** Generate data */\nvoid\nSailModel\n::GenerateData()\n{\n\n   SpectralResponseType::Pointer inRefl = this->GetReflectance();\n   SpectralResponseType::Pointer inTrans = this->GetTransmittance();\n   SpectralResponseType::Pointer outVRefl = this->GetViewingReflectance();\n   SpectralResponseType::Pointer outHRefl = this->GetHemisphericalReflectance();\n   SpectralResponseType::Pointer outVAbs = this->GetViewingAbsorptance();\n   SpectralResponseType::Pointer outHAbs = this->GetHemisphericalAbsorptance();\n\n   // LEAF ANGLE DISTRIBUTION\n   double rd = CONST_PI/180;\n   VectorType lidf;\n   this->Calc_LIDF(m_Angl, lidf);\n\n   double cts, cto, ctscto, tants, tanto, cospsi, dso;\n   cts = std::cos(rd*m_TTS);\n   cto = std::cos(rd*m_TTO);\n   ctscto = cts*cto;\n   tants = std::tan(rd*m_TTS);\n   tanto = std::tan(rd*m_TTO);\n   cospsi = std::cos(rd*m_PSI);\n   dso = std::sqrt(tants*tants+tanto*tanto-2.*tants*tanto*cospsi);\n\n   // angular distance, compensation of shadow length\n   // Calculate geometric factors associated with extinction and scattering\n   // Initialise sums\n   double ks = 0;\n   double ko = 0;\n   double bf = 0;\n   double sob = 0;\n   double sof = 0;\n   double ttl, ctl, ksli, koli, sobli, sofli, bfli;\n   double chi_s, chi_o, frho, ftau;\n   VectorType result(4);\n\n   // Weighted sums over LIDF\n   for(unsigned int i=0; i<lidf.size(); ++i)\n   {\n      ttl = 2.5+5*i;       // leaf inclination discrete values\n      ctl = std::cos(rd*ttl);\n      // SAIL volume scattering phase function gives interception and portions to be\n      // multiplied by rho and tau\n\n      this->Volscatt(m_TTS, m_TTO, m_PSI, ttl, result);\n      chi_s = result[0];\n      chi_o = result[1];\n      frho = result[2];\n      ftau = result[3];\n\n      //********************************************************************************\n      //*                   SUITS SYSTEM COEFFICIENTS\n      //*\n      //*       ks  : Extinction coefficient for direct solar flux\n      //*       ko  : Extinction coefficient for direct observed flux\n      //*       att : Attenuation coefficient for diffuse flux\n      //*       sigb : Backscattering coefficient of the diffuse downward flux\n      //*       sigf : Forwardscattering coefficient of the diffuse upward flux\n      //*       sf  : Scattering coefficient of the direct solar flux for downward diffuse flux\n      //*       sb  : Scattering coefficient of the direct solar flux for upward diffuse flux\n      //*       vf   : Scattering coefficient of upward diffuse flux in the observed direction\n      //*       vb   : Scattering coefficient of downward diffuse flux in the observed direction\n      //*       w   : Bidirectional scattering coefficient\n      //********************************************************************************\n\n      // Extinction coefficients\n      ksli = chi_s/cts;\n      koli = chi_o/cto;\n\n      // Area scattering coefficient fractions\n      sobli       = frho*CONST_PI/ctscto;\n      sofli       = ftau*CONST_PI/ctscto;\n      bfli       = ctl*ctl;\n      ks       = ks+ksli*lidf[i];\n      ko       = ko+koli*lidf[i];\n      bf       = bf+bfli*lidf[i];\n      sob       = sob+sobli*lidf[i];\n      sof       = sof+sofli*lidf[i];\n   }\n\n   // Geometric factors to be used later with rho and tau\n   double sdb, sdf, dob, dof, ddb, ddf;\n   sdb       = 0.5*(ks+bf);\n   sdf       = 0.5*(ks-bf);\n   dob       = 0.5*(ko+bf);\n   dof       = 0.5*(ko-bf);\n   ddb       = 0.5*(1.+bf);\n   ddf       = 0.5*(1.-bf);\n\n   double lambda, Es, Ed, Rsoil1, Rsoil2, rsoil0, rho, tau, PARdiro, PARdifo;\n   double sigb, sigf, att, m2, m, sb, sf, vb, vf, w;\n   double tss, too, tsstoo, rdd, tdd, rsd, tsd, rdo, tdo, rsos, rsod;\n   double rddt, rsdt, rdot, rsodt, rsost, rsot, dn;\n   double e1, e2, rinf, rinf2, re, denom, J1ks, J2ks, J1ko, J2ko;\n   double Ps, Qs, Pv, Qv, z, g1, g2, Tv1, Tv2, T1, T2, T3;\n   double alf, sumint, fhot, x1, y1, f1, fint, x2, y2, f2;\n   double resh, resv, absh, absv;\n\n   int nbdata = sizeof(DataSpecP5B) / sizeof(DataSpec);\n   for (int i = 0; i < nbdata; ++i)\n   {\n      lambda = DataSpecP5B[i].lambda;\n      Es = DataSpecP5B[i].directLight; //8\n      Ed = DataSpecP5B[i].diffuseLight; //9\n      Rsoil1 = DataSpecP5B[i].drySoil; //10\n      Rsoil2 = DataSpecP5B[i].wetSoil; //11\n      rho = inRefl->GetResponse()[i].second; //rho = LRT[1][i];\n      tau = inTrans->GetResponse()[i].second; //tau = LRT[2][i];\n\n      // direct/diffuse light\n      //Es = direct\n      //Ed = diffuse\n      PARdiro = (1-m_Skyl/100.)*Es;\n      PARdifo = (m_Skyl/100.)*Ed;\n\n      // Soil Reflectance Properties\n      //rsoil1 = dry soil\n      //rsoil2 = wet soil\n      if(!m_UseSoilFile)\n        {\n        rsoil0 = m_PSoil*Rsoil1+(1-m_PSoil)*Rsoil2;\n        }\n      else\n        {\n        rsoil0 = m_SoilDataBase->GetReflectance(m_SoilIndex, lambda)*m_PSoil;\n        }\n\n      // Here rho and tau come in\n      sigb = ddb*rho+ddf*tau;\n      sigf = ddf*rho+ddb*tau;\n      att = 1.-sigf;\n      m2 = (att+sigb)*(att-sigb);\n      if(m2<=0) m2 = 0;\n      m = std::sqrt(m2);\n\n\n      sb = sdb*rho+sdf*tau;\n      sf = sdf*rho+sdb*tau;\n      vb = dob*rho+dof*tau;\n      vf = dof*rho+dob*tau;\n      w = sob*rho+sof*tau;\n\n      // Here the LAI comes in\n      // Outputs for the case LAI = 0\n      if (m_LAI<0)\n          {\n          //tss = 1;\n          too = 1;\n          tsstoo = 1;\n          rdd = 0;\n          tdd = 1;\n          rsd = 0;\n          tsd = 0;\n          rdo = 0;\n          tdo = 0;\n          //rso = 0;\n          rsos = 0;\n          rsod = 0;\n\n          rddt = rsoil0;\n          rsdt = rsoil0;\n          rdot = rsoil0;\n          rsodt = 0;\n          rsost = rsoil0;\n          //rsot = rsoil0;\n          }\n\n        // Other cases (LAI > 0)\n        e1 = exp(-m*m_LAI);\n        e2 = e1*e1;\n        rinf = (att-m)/sigb;\n        rinf2 = rinf*rinf;\n        re = rinf*e1;\n        denom = 1.-rinf2*e2;\n\n        J1ks=Jfunc1(ks, m, m_LAI);\n        J2ks=Jfunc2(ks, m, m_LAI);\n        J1ko=Jfunc1(ko, m, m_LAI);\n        J2ko=Jfunc2(ko, m, m_LAI);\n\n        Ps = (sf+sb*rinf)*J1ks;\n        Qs = (sf*rinf+sb)*J2ks;\n        Pv = (vf+vb*rinf)*J1ko;\n        Qv = (vf*rinf+vb)*J2ko;\n\n        rdd = rinf*(1.-e2)/denom;\n        tdd = (1.-rinf2)*e1/denom;\n        tsd = (Ps-re*Qs)/denom;\n        rsd = (Qs-re*Ps)/denom;\n        tdo = (Pv-re*Qv)/denom;\n        rdo = (Qv-re*Pv)/denom;\n\n        tss = exp(-ks*m_LAI);\n        too = exp(-ko*m_LAI);\n        z = Jfunc3(ks, ko, m_LAI);\n        g1 = (z-J1ks*too)/(ko+m);\n        g2 = (z-J1ko*tss)/(ks+m);\n\n        Tv1 = (vf*rinf+vb)*g1;\n        Tv2 = (vf+vb*rinf)*g2;\n        T1 = Tv1*(sf+sb*rinf);\n        T2 = Tv2*(sf*rinf+sb);\n        T3 = (rdo*Qs+tdo*Ps)*rinf;\n\n        // Multiple scattering contribution to bidirectional canopy reflectance\n        rsod = (T1+T2-T3)/(1.-rinf2);\n\n        // Treatment of the hotspot-effect\n        alf=1e6;\n        // Apply correction 2/(K+k) suggested by F.-M. Bron\n        if (m_HSpot>0) alf=(dso/m_HSpot)*2./(ks+ko);\n        if (alf>200) alf=200;\n        if (alf==0)\n          {\n          // The pure hotspot - no shadow\n          tsstoo = tss;\n          sumint = (1-tss)/(ks*m_LAI);\n          }\n        else\n          {\n          // Outside the hotspot\n          fhot=m_LAI*std::sqrt(ko*ks);\n          // Integrate by exponential Simpson method in 20 steps\n          // the steps are arranged according to equal partitioning\n          // of the slope of the joint probability function\n          x1=0;\n          y1=0;\n          f1=1;\n          fint=(1.-exp(-alf))*0.05;\n          sumint=0;\n\n          for(unsigned int j=1; j<=20; ++j)\n            {\n            if (j<20) x2 = -std::log(1.-j*fint)/alf;\n            else x2 = 1;\n            y2 = -(ko+ks)*m_LAI*x2+fhot*(1.-exp(-alf*x2))/alf;\n            f2 = exp(y2);\n            sumint = sumint+(f2-f1)*(x2-x1)/(y2-y1);\n            x1=x2;\n            y1=y2;\n            f1=f2;\n            }\n          tsstoo=f1;\n          }\n\n        // Bidirectional reflectance\n        // Single scattering contribution\n        rsos = w*m_LAI*sumint;\n      // Total canopy contribution\n      // rso=rsos+rsod;\n      //Interaction with the soil\n      dn=1.-rsoil0*rdd;\n\n      rddt = rdd+tdd*rsoil0*tdd/dn;\n      rsdt = rsd+(tsd+tss)*rsoil0*tdd/dn;\n      rdot = rdo+tdd*rsoil0*(tdo+too)/dn;\n\n      rsodt = rsod+((tss+tsd)*tdo+(tsd+tss*rsoil0*rdd)*too)*rsoil0/dn;\n      rsost = rsos+tsstoo*rsoil0;\n      rsot = rsost+rsodt;\n\n      resh = (rddt*PARdifo+rsdt*PARdiro)/(PARdiro+PARdifo);\n      resv = (rdot*PARdifo+rsot*PARdiro)/(PARdiro+PARdifo);\n\n      absh = (1-rddt-(1-rsoil0)*(tdd+(tdd*rdd*rsoil0)/dn));\n      absv = (1-rsdt-(1-rsoil0)*(tss+(tss*rsoil0*rdd+tsd)/dn));\n\n      SpectralResponseType::PairType response;\n      response.first=lambda/1000.0;\n      response.second=resh;\n      outHRefl->GetResponse().push_back(response);\n      response.second=resv;\n      outVRefl->GetResponse().push_back(response);\n      response.second=absh;\n      outHAbs->GetResponse().push_back(response);\n      response.second=absv;\n      outVAbs->GetResponse().push_back(response);\n   }\n   m_FCoverView = 1-too;\n}\n\n\nvoid\nSailModel\n::Calc_LIDF(const double a, VectorType &lidf) const\n{\n   int ala=a;\n   VectorType freq;\n   Campbell(ala, freq);\n   lidf=freq;\n\n}\n\n\nvoid\nSailModel\n::Campbell(const double ala, VectorType &freq) const\n{\n   unsigned int n=18;\n   double excent = exp(-1.6184e-5*std::pow(ala, 3)+2.1145e-3*ala*ala-1.2390e-1*ala+3.2491);\n   double sum=0;\n   unsigned int tx2, tx1;\n   double tl1, tl2, x1, x2, v, alpha, alpha2, x12, x22, alpx1, alpx2, dum, almx1, almx2;\n   VectorType temp;\n\n   for(unsigned int i=0; i<n; ++i)\n   {\n      tx2 = 5*i;\n      tx1 = 5*(i+1);\n      tl1 = tx1*CONST_PI/180;\n      tl2 = tx2*CONST_PI/180;\n\n\n      x1 = excent/sqrt(1.+excent*excent*std::tan(tl1)*std::tan(tl1));\n      x2 = excent/sqrt(1.+excent*excent*std::tan(tl2)*std::tan(tl2));\n      if(excent==1)\n      {\n         v = std::abs(cos(tl1)-cos(tl2));\n         temp.push_back( v );\n         sum = sum + v;\n      }\n      else\n      {\n         alpha = excent/std::sqrt(std::abs(1.-excent*excent));\n         alpha2 = alpha*alpha;\n         x12 = x1*x1;\n         x22 = x2*x2;\n         if(excent>1)\n         {\n            alpx1 = std::sqrt(alpha2+x12);\n            alpx2 = std::sqrt(alpha2+x22);\n            dum   = x1*alpx1+alpha2*log(x1+alpx1);\n            v = std::abs(dum-(x2*alpx2+alpha2*log(x2+alpx2)));\n            temp.push_back( v );\n            sum = sum + v;\n         }\n         else\n         {\n            almx1 = sqrt(alpha2-x12);\n            almx2 = sqrt(alpha2-x22);\n            dum   = x1*almx1+alpha2*asin(x1/alpha);\n            v = std::abs(dum-(x2*almx2+alpha2*asin(x2/alpha)));\n            temp.push_back( v );\n            sum = sum + v;\n         }\n      }\n   }\n\n   for(unsigned int i=0; i<n; ++i)\n   {\n      freq.push_back(temp[i]/sum);\n   }\n\n}\n\n\nvoid\nSailModel\n::Volscatt(const double tts, const double tto, const double psi, const double ttl, VectorType &result) const\n{\n\n   double rd = CONST_PI/180;\n   double costs = std::cos(rd*tts);\n   double costo = std::cos(rd*tto);\n   double sints = std::sin(rd*tts);\n   double sinto = std::sin(rd*tto);\n   double cospsi = std::cos(rd*psi);\n   double psir = rd*psi;\n   double costl = std::cos(rd*ttl);\n   double sintl = std::sin(rd*ttl);\n   double cs = costl*costs;\n   double co = costl*costo;\n   double ss = sintl*sints;\n   double so = sintl*sinto;\n\n   // ..............................................................................\n   //     betas -bts- and betao -bto- computation\n   //     Transition angles (beta) for solar (betas) and view (betao) directions\n   //     if thetav+thetal>pi/2, bottom side of the leaves is observed for leaf azimut\n   //     interval betao+phi<leaf azimut<2pi-betao+phi.\n   //     if thetav+thetal<pi/2, top side of the leaves is always observed, betao=pi\n   //     same consideration for solar direction to compute betas\n   // ..............................................................................\n   double cosbts, cosbto, bts, ds, chi_s, bto, doo, chi_o;\n   double btran1, btran2, bt1, bt2, bt3, t1, t2 , denom, frho, ftau;\n\n   cosbts = 5;\n   if (std::abs(ss)>1e-6) cosbts = -cs/ss;\n\n   cosbto=5;\n   if (std::abs(so)>1e-6) cosbto = -co/so;\n\n\n   if (std::abs(cosbts)<1)\n   {\n      bts = std::acos(cosbts);\n      ds = ss;\n   }\n   else\n   {\n      bts = CONST_PI;\n      ds = cs;\n   }\n\n   chi_s = 2./CONST_PI*((bts-CONST_PI*0.5)*cs+std::sin(bts)*ss);\n\n   if (std::abs(cosbto)<1)\n   {\n      bto = std::acos(cosbto);\n      doo = so;\n   }\n   else if(tto<90)\n   {\n      bto = CONST_PI;\n      doo = co;\n   }\n   else\n   {\n      bto = 0;\n      doo = -co;\n   }\n   chi_o = 2./CONST_PI*((bto-CONST_PI*0.5)*co+std::sin(bto)*so);\n\n   // ..............................................................................\n   //   Computation of auxiliary azimut angles bt1, bt2, bt3 used\n   //   for the computation of the bidirectional scattering coefficient w\n   // .............................................................................\n\n   btran1 = std::abs(bts-bto);\n   btran2 = CONST_PI - std::abs(bts+bto-CONST_PI);\n\n   if (psir<=btran1)\n   {\n      bt1=psir;\n      bt2=btran1;\n      bt3=btran2;\n   }\n   else\n   {\n      bt1=btran1;\n      if (psir<=btran2)\n      {\n         bt2=psir;\n         bt3=btran2;\n      }\n      else\n      {\n         bt2=btran2;\n         bt3=psir;\n      }\n   }\n\n   t1 = 2.*cs*co+ss*so*cospsi;\n   t2 = 0;\n   if (bt2>0) t2=sin(bt2)*(2.*ds*doo+ss*so*cos(bt1)*cos(bt3));\n   denom = 2.*CONST_PI*CONST_PI;\n   frho = ((CONST_PI-bt2)*t1+t2)/denom;\n   ftau = (-bt2*t1+t2)/denom;\n\n   if (frho<0) frho = 0;\n   if (ftau<0) ftau = 0;\n\n   result[0] = chi_s;\n   result[1] = chi_o;\n   result[2] = frho;\n   result[3] = ftau;\n\n}\n\n\ndouble\nSailModel\n::Jfunc1(const double k, const double l, const double t) const\n{\n   //J1 function with avoidance of singularity problem\n   double v;\n   double del=(k-l)*t;\n   if(std::abs(del)>1e-3)\n   {\n      v = (exp(-l*t)-exp(-k*t))/(k-l);\n      return v;\n   }\n   else\n   {\n      v = 0.5*t*(exp(-k*t)+exp(-l*t))*(1.-del*del/12.);\n      return v;\n   }\n}\n\n\ndouble\nSailModel\n::Jfunc2(const double k, const double l, const double t) const\n{\n   double v;\n   v = (1.-exp(-(k+l)*t))/(k+l);\n   return v;\n}\n\n\ndouble\nSailModel\n::Jfunc3(const double k, const double l, const double t) const\n{\n   double v;\n   v =  (1.-exp(-(k+l)*t))/(k+l);\n   return v;\n}\n\n\nvoid\nSailModel\n::PrintSelf(std::ostream& os, itk::Indent indent) const\n{\n   Superclass::PrintSelf(os, indent);\n\n}\n\nvoid SailModel::UseExternalSoilDB(std::shared_ptr<SoilDataBase> SoilDB, \n                                  size_t SoilIndex)\n{\n  m_UseSoilFile = true;\n  m_SoilIndex = SoilIndex;\n  m_SoilDataBase = SoilDB;\n}\n} // end namespace otb\n", "meta": {"hexsha": "208437df03204c632c853f4bbfa3c7f2fdfc76d2", "size": 21231, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Modules/Radiometry/Simulation/src/otbSailModel.cxx", "max_stars_repo_name": "xcorail/OTB", "max_stars_repo_head_hexsha": "092a93654c3b5d009e420f450fe9b675f737cdca", "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/Radiometry/Simulation/src/otbSailModel.cxx", "max_issues_repo_name": "xcorail/OTB", "max_issues_repo_head_hexsha": "092a93654c3b5d009e420f450fe9b675f737cdca", "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/Radiometry/Simulation/src/otbSailModel.cxx", "max_forks_repo_name": "xcorail/OTB", "max_forks_repo_head_hexsha": "092a93654c3b5d009e420f450fe9b675f737cdca", "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.0835616438, "max_line_length": 151, "alphanum_fraction": 0.5374687956, "num_tokens": 6394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297745935070808, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.26129275195821705}}
{"text": "#include <iostream>\n#include <fstream>\n#include <queue>\n#include <string>\n#include <limits>\n\n#include <boost/random.hpp>\n#include <boost/generator_iterator.hpp>\n\n#include <glog/logging.h>\n\nusing boost::variate_generator;\nusing boost::mt19937;\nusing boost::exponential_distribution;\n\n#define ONLY_EVENT_TYPE     0\n#define NUMBER_EVENT_TYPES  3   //NEED TO MAKE SURE THIS IS 1 MORE THAN THE LAST DEFINED EVENT\n\nconst std::string event_names[NUMBER_EVENT_TYPES] = {\n    \"ARRIVE\",\n    \"DEPART\",\n    \"CLOSE\"\n};\n\nbool closed = false;\n\nstd::vector<bool> servers_idle;\nstd::vector< std::queue<double>* > servers_queue;\n\n// Stats vectors\nstd::vector<double> times_after_close;\nstd::vector<double> average_times_in_queue;\nstd::vector< std::vector<double>* > average_server_utilizations;\nstd::vector< std::vector<double>* > average_length_of_queues;\n\n// Output File\nstd::ofstream outfile;\n\n/**\n *  A class for an event, which holds an int for the event type, a double for simulation time and possibly other data.\n *  We may want to subclass this with our own events\n */\nclass Event {\n    public:\n        const double time;\n        const double server_start_time;\n        const int server_index;\n        const int type;\n\n        Event(double time, int type) : time(time), server_start_time(0), server_index(-1), type(type) {\n            //cout << \"created an event with simulation time: \" << this->time << endl;\n            //cout << \"created an event with event type: \" << this->type << endl;\n        }\n\n        Event(double time, double server_start_time, int server_index, int type) : time(time), server_start_time(server_start_time), server_index(server_index), type(type) {\n            //cout << \"created an event with simulation time: \" << this->time << endl;\n            //cout << \"created an event with event type: \" << this->type << endl;\n        }\n\n        bool operator<( const Event& e ) const {\n            return time < e.time;\n        }\n\n        bool operator>( const Event& e ) const {\n            return time > e.time;\n        }\n\n        bool less( const Event& e) const {\n            return time < e.time;\n        }\n\n        friend std::ostream& operator<< (std::ostream& out, Event& event);\n};\n\nclass CompareEvent {\n    public:\n        bool operator()(Event* &e1, Event* &e2) {\n            return e1->time > e2->time;\n            //return false;\n        }\n};\n\n// Print event\nstd::ostream& operator<< ( std::ostream& out, Event& event) {\n    out << \"[sim_time: \" << std::setw(10) << std::setprecision(3) << std::fixed << event.time << \", type: \" << std::setw(4) << event.type;\n    if (event.type < NUMBER_EVENT_TYPES) {\n        out << \" - \" << std::left << std::setw(50) << event_names[event.type];\n    } else {\n        out << std::left << std::setw(50) << \" - UNKNOWN\";\n    }\n    out << std::right << \"]\";\n    return out;\n}\n\n\nbool server_idle(int &idle_index) {\n    for (int i = 0; i < servers_idle.size(); i++) {\n        if (servers_idle[i] == true) {\n            idle_index = i;\n            return true;\n        }\n    }\n    return false;\n}\n\nvoid addToQueue(double enqueue_time) {\n    std::queue<double> *shortest = NULL;\n    for (int i = 0; i < servers_queue.size(); i++) {\n        if (shortest == NULL || servers_queue[i]->size() < shortest->size()) {\n            shortest = servers_queue[i];\n        }\n    }\n    shortest->push(enqueue_time);\n}\n\nvoid jockey(const int &departed_queue) {\n    for (int i = 1; i < servers_queue.size(); i++) {\n        int pos = departed_queue - i;\n        if (pos < 0) pos = servers_queue.size() + pos;\n        if (servers_queue[departed_queue]->size() < servers_queue[pos]->size()) {\n            servers_queue[departed_queue]->push(servers_queue[pos]->front());\n            servers_queue[pos]->pop();\n        }\n    }\n}\n\nvoid run_simulation(\n        const double close_time,\n        variate_generator< mt19937, exponential_distribution<> > &arrival_generator,\n        variate_generator< mt19937, exponential_distribution<> > &departure_generator) {\n    double simulation_time_s = 0;\n    double previous_time_s = 0;\n\n    std::vector<double> servers_work_time;\n    std::vector<double> servers_time_queue_length;\n    for (int i = 0; i < servers_idle.size(); i++) {\n        servers_work_time.push_back(0);\n        servers_time_queue_length.push_back(0);\n    }\n\n    double total_queue_time = 0;\n    double total_departures = 0;\n\n\n    std::priority_queue<Event*, std::vector<Event*>, CompareEvent> heap;\n\n    // Put initial event in the heap\n    heap.push(new Event(simulation_time_s + arrival_generator(), 0));\n    heap.push(new Event(close_time, 2));\n\n    VLOG(2) << \"Start Simulation...\";\n\n    while (!heap.empty()) {\n        Event *current_event = heap.top();\n        heap.pop();\n\n        if (current_event == NULL) {\n            LOG(ERROR) << \"Simulation not complete and there are no events in the min heap.\";\n            LOG(ERROR) << \"\\tsimulation time: \" << simulation_time_s;\n            exit(0);\n        }\n\n        previous_time_s = simulation_time_s;\n        simulation_time_s = current_event->time;\n\n        // Calculate average time stuff\n        double time_since_last = simulation_time_s - previous_time_s;\n        // Calculate sum of time queue length for all servers\n        for (int i = 0; i < servers_idle.size(); i++) {\n            servers_time_queue_length[i] += servers_queue[i]->size() * time_since_last;\n        }\n\n        int idle_index = -1;\n        switch (current_event->type) {\n            case 0: // ARRIVE\n                // If the server is busy add new arrival to waiting queue\n                // otherwise set the server as busy and add new departure time.\n                VLOG(2) << \"Arrival Begin\";\n                if (!server_idle(idle_index)) {\n                    addToQueue(simulation_time_s);\n                } else {\n                    VLOG(2) << \"Idle Index: \" << idle_index;\n                    servers_idle[idle_index] = false;\n                    heap.push(new Event(simulation_time_s + departure_generator(), simulation_time_s, idle_index, 1));\n                }\n                if (!closed) {\n                    // Add next arrival event\n                    heap.push(new Event(simulation_time_s + arrival_generator(), 0));\n                }\n                VLOG(2) << \"Arrival End\";\n                break;\n            case 1: // DEPART\n                // Add server busy time.\n                // Which server is busy?\n                servers_work_time[current_event->server_index] += simulation_time_s - current_event->server_start_time;\n                jockey(current_event->server_index);\n                // If the queue is empty set the server to idle otherwise\n                // get the next person from the queue and set their departure\n                // time.\n                VLOG(2) << \"Depart Begin\";\n                if (servers_queue[current_event->server_index]->empty()) {\n                    servers_idle[current_event->server_index] = true;\n                } else {\n                    // Add current simulation time minus time stored in the\n                    // queue to the total queue time.\n                    total_queue_time += simulation_time_s - servers_queue[current_event->server_index]->front();\n                    servers_queue[current_event->server_index]->pop();\n                    // Add a new depature to the heap.\n                    heap.push(new Event(simulation_time_s + departure_generator(), simulation_time_s, current_event->server_index, 1));\n                }\n                total_departures++;\n                VLOG(2) << \"Depart End\";\n                break;\n            case 2: // CLOSE\n                // Set flag to stop arrivals\n                VLOG(2) << \"Closed\";\n                closed = true;\n                break;\n            default:\n                LOG(ERROR) << \"Simulation had an event with an unknown type: \" << current_event->type;\n                LOG(ERROR) << \"\\tsimulation time: \" << simulation_time_s;\n                exit(0);\n        }\n\n        VLOG(3) << *current_event << \", h: \" << heap.size();\n\n        delete current_event; // Event's are created with new, so we need to delete them when we're done with them\n    }\n\n    assert(heap.empty());\n\n    VLOG(1) << \"The simulation ended at time: \" << simulation_time_s;\n    times_after_close.push_back(simulation_time_s - close_time);\n    VLOG(1) << \"The simulation ended \" << simulation_time_s - close_time << \" after close.\";\n    average_server_utilizations.push_back(new std::vector<double>());\n    average_length_of_queues.push_back(new std::vector<double>());\n    VLOG(1) << \"Server util vector size: \" << average_server_utilizations.size();\n    for (int i = 0; i < servers_idle.size(); i++) {\n        VLOG(1) << \"The server \" << i+1 << \" was busy for time: \" << servers_work_time[i];\n        average_server_utilizations.back()->push_back(servers_work_time[i] / simulation_time_s);\n        VLOG(1) << \"The server \" << i+1 << \" utilization was: \" << servers_work_time[i] / simulation_time_s;\n        average_length_of_queues.back()->push_back(servers_time_queue_length[i] / simulation_time_s);\n        VLOG(1) << \"The average length of server \" << i+1 << \" queue was: \" << servers_time_queue_length[i] / simulation_time_s;\n        VLOG(1) << \"Server util size: \" << average_server_utilizations.back()->size();\n    }\n    VLOG(1) << \"Total time spent in the queue: \" << total_queue_time;\n    VLOG(1) << \"Total departures: \" << total_departures;\n    average_times_in_queue.push_back(total_queue_time / total_departures);\n    VLOG(1) << \"The average time spent in queue: \" << total_queue_time / total_departures;\n}\n\nint main(int argc, char **argv) {\n    // Initialize Google Logging\n    google::InitGoogleLogging(argv[0]);\n    // Log to Stderr\n    FLAGS_logtostderr = 1;\n\n    int seed = time(0);\n    double arrival_mean = 1.0;\n    double departure_mean = 4.5;\n    variate_generator< mt19937, exponential_distribution<> > arrival_generator(mt19937(seed), exponential_distribution<>(1/arrival_mean));\n    variate_generator< mt19937, exponential_distribution<> > departure_generator(mt19937(seed+1), exponential_distribution<>(1/departure_mean));\n\n    // Intiate\n    int duration = 480;\n    int min_servers = 4;\n    int max_servers = 7;\n    int num_iterations = 10;\n\n    // Open files\n    std::stringstream filename;\n    filename << \"servers_stats\" << \".dat\";\n    outfile.open(filename.str());\n\n    for (int sev = min_servers; sev <= max_servers; sev++) {\n        int num_servers = sev;\n        for (int j = 0; j < num_iterations; j++) {\n            closed = false;\n            servers_idle.clear();\n            servers_queue.clear();\n            for (int k = 0; k < num_servers; k++) {\n                servers_idle.push_back(true);\n                servers_queue.push_back(new std::queue<double>());\n            }\n            run_simulation(duration, arrival_generator, departure_generator);\n\n            for (int j = 0; j < num_servers; j++) {\n                delete servers_queue[j];\n            }\n        }\n\n        // Collect and print statistics.\n\n        double sum_average_queue_time = std::accumulate(average_times_in_queue.begin(), average_times_in_queue.end(), 0.0);\n        double min_average_queue_time = *std::min_element(average_times_in_queue.begin(), average_times_in_queue.end());\n        double max_average_queue_time = *std::max_element(average_times_in_queue.begin(), average_times_in_queue.end());\n        double avg_average_queue_time = sum_average_queue_time / average_times_in_queue.size();\n        double sqr_average_queue_time = std::inner_product(average_times_in_queue.begin(), average_times_in_queue.end(), average_times_in_queue.begin(), 0.0);\n        double std_average_queue_time = std::sqrt(sqr_average_queue_time / average_times_in_queue.size() - avg_average_queue_time * avg_average_queue_time);\n\n        double sum_times_after_close = std::accumulate(times_after_close.begin(), times_after_close.end(), 0.0);\n        double min_times_after_close = *std::min_element(times_after_close.begin(), times_after_close.end());\n        double max_times_after_close = *std::max_element(times_after_close.begin(), times_after_close.end());\n        double avg_times_after_close = sum_times_after_close / average_times_in_queue.size();\n        double sqr_times_after_close = std::inner_product(times_after_close.begin(), times_after_close.end(), times_after_close.begin(), 0.0);\n        double std_times_after_close = std::sqrt(sqr_times_after_close / times_after_close.size() - avg_times_after_close * avg_times_after_close);\n\n        double min_server_utilization = std::numeric_limits<double>::max();\n        double max_server_utilization = std::numeric_limits<double>::min();\n        double sum_server_utilization = 0;\n        double sqr_server_utilization = 0;\n\n        double min_average_length = std::numeric_limits<double>::max();\n        double max_average_length = std::numeric_limits<double>::min();\n        double sum_average_length = 0;\n        double sqr_average_length = 0;\n\n        for (int i = 0; i < num_iterations; i++) {\n            double temp_avg_server_utilization = 0;\n            double temp_avg_average_length = 0;\n\n            // Find the average server utilization of the queues;\n            for (int j = 0; j < num_servers; j++) {\n                double current_utilization = average_server_utilizations.at(i)->at(j);\n                VLOG(2) << \"Server \" << j+1 << \" utilization: \" << current_utilization;\n                temp_avg_server_utilization += current_utilization;\n\n                double current_average_length = average_length_of_queues.at(i)->at(j);\n                VLOG(2) << \"Server \" << j+1 << \" average length: \" << current_average_length;\n                temp_avg_average_length += current_average_length;\n                temp_avg_average_length = temp_avg_average_length / num_servers;\n            }\n            delete average_server_utilizations.at(i);\n            delete average_length_of_queues.at(i);\n\n            temp_avg_server_utilization = temp_avg_server_utilization / num_servers;\n            sum_server_utilization += temp_avg_server_utilization;\n            if (temp_avg_server_utilization > max_server_utilization) max_server_utilization = temp_avg_server_utilization;\n            if (temp_avg_server_utilization < min_server_utilization) min_server_utilization = temp_avg_server_utilization;\n            sqr_server_utilization += temp_avg_server_utilization * temp_avg_server_utilization;\n\n            temp_avg_average_length = temp_avg_average_length / num_servers;\n            sum_average_length += temp_avg_average_length;\n            if (temp_avg_average_length > max_average_length) max_average_length = temp_avg_average_length;\n            if (temp_avg_average_length < min_average_length) min_average_length = temp_avg_average_length;\n            sqr_average_length += temp_avg_average_length * temp_avg_average_length;\n        }\n        average_server_utilizations.clear();\n        average_length_of_queues.clear();\n\n        double avg_server_utilization = sum_server_utilization / num_iterations;\n        double std_server_utilization = std::sqrt(sqr_server_utilization / num_iterations - avg_server_utilization * avg_server_utilization);\n\n        double avg_average_length = sum_average_length / (num_servers * num_iterations);\n        double std_average_length = std::sqrt(sqr_average_length / (num_servers * num_iterations) - avg_average_length * avg_average_length);\n\n\n        outfile << \"------------------------------------------\" << std::endl;\n        outfile << \"---------------- \" << num_servers << \" SERVERS\" << \" ---------------\" << std::endl;\n        outfile << \"------------------------------------------\" << std::endl;\n        outfile << std::endl;\n\n        outfile << \"-----------------------------------------\" << std::endl;\n        outfile << \"------- AVERAGE SERVER UTILIZATION ------\" << std::endl;\n        outfile << \"-----------------------------------------\" << std::endl;\n        outfile << \"Min server utiliation: \" << min_server_utilization << std::endl;\n        outfile << \"Max server utiliation: \" << max_server_utilization << std::endl;\n        outfile << \"Average server utilization: \" << avg_server_utilization << std::endl;\n        outfile << \"Standard deviation of server utilization: \" << std_server_utilization << std::endl;\n        outfile << std::endl;\n\n        outfile << \"-----------------------------------------\" << std::endl;\n        outfile << \"---------- AVERAGE QUEUE LENGTH ---------\" << std::endl;\n        outfile << \"-----------------------------------------\" << std::endl;\n        outfile << \"Min queue length: \" << min_average_length << std::endl;\n        outfile << \"Max queue length: \" << max_average_length << std::endl;\n        outfile << \"Average queue length: \" << avg_average_length << std::endl;\n        outfile << \"Standard deviation of queue length: \" << std_average_length << std::endl;\n        outfile << std::endl;\n\n        outfile << \"-----------------------------------------\" << std::endl;\n        outfile << \"---------- AVERAGE QUEUE TIMES ----------\" << std::endl;\n        outfile << \"-----------------------------------------\" << std::endl;\n        outfile << \"Min of average queue times: \" << min_average_queue_time << std::endl;\n        outfile << \"Max of average queue times: \" << max_average_queue_time << std::endl;\n        outfile << \"Mean of average queue times: \" << avg_average_queue_time << std::endl;\n        outfile << \"Standard deviation of average queue times: \" << std_average_queue_time << std::endl;\n        outfile << std::endl;\n\n        outfile << \"------------------------------------------\" << std::endl;\n        outfile << \"-------- AVERAGE TIME AFTER CLOSE --------\" << std::endl;\n        outfile << \"------------------------------------------\" << std::endl;\n        outfile << \"Min of times after close: \" << min_times_after_close << std::endl;\n        outfile << \"Max of times after close: \" << max_times_after_close << std::endl;\n        outfile << \"Mean of times after close: \" << avg_times_after_close << std::endl;\n        outfile << \"Standard deviation of times after close: \" << std_times_after_close << std::endl;\n        outfile << std::endl;\n        outfile << std::endl;\n        outfile << std::endl;\n\n    }\n    outfile.close();\n}\n\n", "meta": {"hexsha": "993a821ef17ae80ee2be1086622dd90ecabf32ae", "size": 18325, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/hw2.cpp", "max_stars_repo_name": "Kazz47/cs445", "max_stars_repo_head_hexsha": "eb991eda50e395a2f10ea943eabe7f74b30f38f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/hw2.cpp", "max_issues_repo_name": "Kazz47/cs445", "max_issues_repo_head_hexsha": "eb991eda50e395a2f10ea943eabe7f74b30f38f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hw2.cpp", "max_forks_repo_name": "Kazz47/cs445", "max_forks_repo_head_hexsha": "eb991eda50e395a2f10ea943eabe7f74b30f38f7", "max_forks_repo_licenses": ["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.2469135802, "max_line_length": 173, "alphanum_fraction": 0.6062210095, "num_tokens": 4045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.26123332732715493}}
{"text": "#include <fstream>\n#include <iostream>\n//#include <boost/foreach.hpp>\n\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/Nef_polyhedron_3.h>\n//#include <CGAL/iterator.h>\n//#include <CGAL/squared_distance_3.h>\n\ntypedef CGAL::Exact_predicates_exact_constructions_kernel       Kernel;\ntypedef CGAL::Polyhedron_3<Kernel>                              Polyhedron;\ntypedef CGAL::Nef_polyhedron_3<Kernel>                          Nef_polyhedron;\ntypedef Polyhedron::HalfedgeDS                                  HalfedgeDS;\n//typedef Polyhedron::Vertex_iterator                             Vertex_iterator;\n//typedef Polyhedron::Halfedge_iterator                           Halfedge_iterator;\ntypedef Polyhedron::Facet_iterator                              Facet_iterator;\ntypedef Kernel::Point_3                                         Point_3;\n\n//typedef Polyhedron::Halfedge_handle                             Halfedge_handle;\n//typedef Polyhedron::Facet_handle                                Facet_handle;\n//typedef Polyhedron::Vertex_handle                               Vertex_handle;\ntypedef Polyhedron::Halfedge_around_facet_circulator            Halfedge_facet_circulator;\n//typedef CGAL::Inverse_index<Vertex_iterator>                    Index;\n\n#include \"gewebe_CGALBooleanOperations3.h\"\n\nusing namespace std;\n\nconst bool M_DEBUG              = false;\nconst int NOT_FOUND             = -1;\nconst int INTERSECTION          = 0;\nconst int JOIN                  = 1;\nconst int DIFFERENCE            = 2;\nconst int SYMMETRIC_DIFFERENCE   = 3;\n\n/**\n * @TODO\n *\n * - read CGAL doc : http://doc.cgal.org/latest/Polyhedron/classCGAL_1_1Polyhedron__3.html + http://doc.cgal.org/latest/Polyhedron/index.html\n * - check polyhedron + builder : http://doc.cgal.org/latest/Polyhedron/classCGAL_1_1Polyhedron__incremental__builder__3.html\n * - read on traits : http://doc.cgal.org/latest/Manual/devman_traits_classes.html\n * - look at example code in CGAL\n *\n */\n\n// from http://cgal-discuss.949826.n4.nabble.com/attachment/4661367/0/union_and_intersection.cpp\n// from http://jamesgregson.blogspot.de/2012/05/example-code-for-building.html\n// from https://github.com/yusuketomoto/ofxCGAL/blob/master/src/ofxCGALBooleanOp.cpp\n\ntemplate <class HDS>\nclass PolyhedronBuilder : public CGAL::Modifier_base<HDS> {\npublic:\n    \n    vector<Point_3> & vertices;\n    vector<int> & indices;\n    const float kPointScale = 1.0f;\n    \n    PolyhedronBuilder(vector<Point_3> & _vertices, vector<int> & _indices) : vertices(_vertices), indices(_indices) {}\n    \n    void operator()(HDS & hds) {\n        \n        CGAL::Polyhedron_incremental_builder_3<HDS> mBuilder(hds, true);\n        \n        int numOfVertices = vertices.size();\n        int numOfIndices = indices.size();\n        \n        mBuilder.begin_surface(numOfVertices, numOfIndices / 3);\n        \n        typedef typename HDS::Vertex Vertex;\n        typedef typename Vertex::Point Point;\n        \n        for(int i=0; i<vertices.size(); i++) {\n            mBuilder.add_vertex(Point(vertices[i].x(),\n                                      vertices[i].y(),\n                                      vertices[i].z()));\n        }\n        \n        \n        for(int i=0; i<numOfIndices; i+=3) {\n            mBuilder.begin_facet();\n            mBuilder.add_vertex_to_facet(indices[i + 0]);\n            mBuilder.add_vertex_to_facet(indices[i + 1]);\n            mBuilder.add_vertex_to_facet(indices[i + 2]);\n            mBuilder.end_facet();\n        }\n        \n        mBuilder.end_surface();\n    }\n};\n\nbool near(Point_3 v0, Point_3 v1, double pMinDistance) {\n    if (pMinDistance == 0) {\n        return v0.x() == v1.x() && v0.y() == v1.y() && v0.z() == v1.z();\n    } else {\n        double x = CGAL::to_double(v0.x() - v1.x());\n        double y = CGAL::to_double(v0.y() - v1.y());\n        double z = CGAL::to_double(v0.z() - v1.z());\n        double mDistance = sqrt(x*x+y*y+z*z);\n        return mDistance < pMinDistance;\n    }\n}\n\nint findVertexInIndexList(vector<Point_3> vertices_opt, Point_3 v, float pEpsilon) {\n    for (int j = 0; j < vertices_opt.size(); j++) {\n        Point_3 vo = vertices_opt[j];\n        bool isNear = near(v, vo, pEpsilon);\n        if (isNear) {\n            return j;\n        }\n    }\n    return NOT_FOUND;\n}\n\nvoid optimizeIndexList(vector<Point_3> & coords_raw, vector<Point_3> & coords_opt, vector<int> & indices_opt) {\n    int mIndexCounter = 0;\n    for (int i=0; i<coords_raw.size(); i++) {\n        Point_3 v = coords_raw[i];\n        int mExistingIndex = findVertexInIndexList(coords_opt, v, 0.0f);\n        if (mExistingIndex == NOT_FOUND) {\n            coords_opt.push_back(v);\n            indices_opt.push_back(mIndexCounter);\n            mIndexCounter++;\n        } else {\n            indices_opt.push_back(mExistingIndex);\n        }\n    }\n}\n\nvoid convertToPolyhedron(vector<Point_3> vertices, vector<int> indices, Polyhedron & polyhedron) {\n    PolyhedronBuilder<HalfedgeDS> builder(vertices, indices);\n    polyhedron.delegate(builder);\n}\n\nvoid extract_vertices(vector<Point_3> & vertices, JNIEnv * env, jfloatArray & j_coords) {\n    jboolean iscopy;\n    jfloat* jcoords_A_array = env->GetFloatArrayElements(j_coords, &iscopy);\n    const int mNumberOfPoints_A = (env->GetArrayLength(j_coords)) / 3;\n    \n    if (M_DEBUG) cout << \"--- A has points: \" << mNumberOfPoints_A << endl;\n    \n    for(int i=0; i < mNumberOfPoints_A; i++) {\n        double x = (double)*jcoords_A_array;\n        jcoords_A_array++;\n        double y = (double)*jcoords_A_array;\n        jcoords_A_array++;\n        double z = (double)*jcoords_A_array;\n        jcoords_A_array++;\n        vertices.push_back(Point_3(x, y, z));\n    }\n}\n\nJNIEXPORT jfloatArray JNICALL Java_gewebe_CGALBooleanOperations3_boolean_1operation\n(JNIEnv * env, jobject jobj, jint class_type, jfloatArray coords_A_array, jfloatArray coords_B_array )\n{\n    if (M_DEBUG) cout << \"--- boolean_operation\" << endl;\n    \n    /* evaluate command */\n\n    int mBooleanOperation;\n    if ( class_type == JOIN ) {\n        if (M_DEBUG) cout << \"--- type: JOIN\" << endl;\n        mBooleanOperation = JOIN;\n    } else if ( class_type == INTERSECTION ) {\n        if (M_DEBUG) cout << \"--- type: INTERSECTION\" << endl;\n        mBooleanOperation = INTERSECTION;\n    } else if ( class_type == DIFFERENCE ) {\n        if (M_DEBUG) cout << \"--- type: DIFFERENCE\" << endl;\n        mBooleanOperation = DIFFERENCE;\n    } else if ( class_type == SYMMETRIC_DIFFERENCE ) {\n        if (M_DEBUG) cout << \"--- type: SYMMETRIC_DIFFERENCE\" << endl;\n        mBooleanOperation = SYMMETRIC_DIFFERENCE;\n    } else {\n        if (M_DEBUG) cout << \"--- type: (DEFAULT) ?: \" << class_type << endl;\n        mBooleanOperation = INTERSECTION;\n    }\n\n    \n    /* ------ */\n    \n    vector<Point_3> vertices_raw_A;\n    extract_vertices(vertices_raw_A, env, coords_A_array);\n    if (M_DEBUG) cout << \"coords_raw_A: \" << vertices_raw_A.size() << endl;\n    \n    vector<Point_3> vertices_raw_B;\n    extract_vertices(vertices_raw_B, env, coords_B_array);\n    \n    /* build polyhedrons */\n    \n    Polyhedron polyhedronA;\n    vector<Point_3> vertices_opt_A;\n    vector<int> indices_opt_A;\n    optimizeIndexList(vertices_raw_A, vertices_opt_A, indices_opt_A);\n    convertToPolyhedron(vertices_opt_A, indices_opt_A, polyhedronA);\n    \n    Polyhedron polyhedronB;\n    vector<Point_3> vertices_opt_B;\n    vector<int> indices_opt_B;\n    optimizeIndexList(vertices_raw_B, vertices_opt_B, indices_opt_B);\n    convertToPolyhedron(vertices_opt_B, indices_opt_B, polyhedronB);\n    \n    /* check validity of polyhedra */\n    \n    if (!polyhedronA.is_pure_triangle() || !polyhedronB.is_pure_triangle()){\n        cerr << \"Inputs polyhedra must be triangulated.\" << std::endl;\n        cerr << \"A.is_pure_triangle() \" << polyhedronA.is_pure_triangle() << endl;\n        cerr << \"B.is_pure_triangle() \" << polyhedronB.is_pure_triangle() << endl;\n    }\n    \n    if (!polyhedronA.size_of_vertices() || !polyhedronB.size_of_vertices()){\n        cerr << \"Inputs polyhedra must not be empty.\" << std::endl;\n    }\n    \n    if (!polyhedronA.is_valid() || !polyhedronB.is_valid()){\n        cerr << \"Inputs polyhedra must be valid.\" << std::endl;\n    }\n    \n    if(!polyhedronA.is_closed()) {\n        cerr << \"input mesh A is not closed.\" << endl;\n    }\n    \n    if(!polyhedronB.is_closed()) {\n        cerr << \"input mesh B is not closed.\" << endl;\n    }\n    \n    Nef_polyhedron Nef_A(polyhedronA);\n    Nef_polyhedron Nef_B(polyhedronB);\n    \n    if (M_DEBUG) cout << \"Nef_A (op) Nef_B\" << endl;\n    \n    /*\n     operator *= :: intersection\n     operator += :: join\n     operator -= :: difference\n     operator ^= :: symmetric_difference\n     */\n\n    if (mBooleanOperation == INTERSECTION) {\n        Nef_A *= Nef_B;\n    } else if (mBooleanOperation == JOIN) {\n        Nef_A += Nef_B;\n    } else if (mBooleanOperation == DIFFERENCE) {\n        Nef_A -= Nef_B;\n    } else if (mBooleanOperation == SYMMETRIC_DIFFERENCE) {\n        Nef_A ^= Nef_B;\n    }\n\n    if (M_DEBUG) cout << \"Nef_A.is_simple(): \" << Nef_A.is_simple() << endl;\n    \n    Polyhedron polyhedron_result;\n    Nef_A.convert_to_polyhedron(polyhedron_result);\n    if(Nef_A.is_simple()) {\n        Nef_A.convert_to_Polyhedron(polyhedron_result);\n    } else {\n        cerr << \"analyze/process n1 and do something...\" << endl;\n    }\n    \n    /* build jfloatarray */\n    \n    const int mNumberOfMeshData = distance(polyhedron_result.facets_begin(), polyhedron_result.facets_end()) * 3 * 3;\n    jfloat mMeshData[mNumberOfMeshData];\n    if (M_DEBUG) cout << \"mNumberOfMeshData: \" << mNumberOfMeshData << endl;\n    \n    int i = 0;\n    for(Facet_iterator f = polyhedron_result.facets_begin();\n        f != polyhedron_result.facets_end();\n        ++f )\n    {\n        Halfedge_facet_circulator j = f->facet_begin();\n        //        // Facets in polyhedral surfaces are at least triangles.\n        //        CGAL_assertion( CGAL::circulator_size(j) >= 3);\n        //        cout << CGAL::circulator_size(j) << ' ';\n        do {\n            if (M_DEBUG) cout << j->vertex()->point() << endl;\n            mMeshData[i] = (float)CGAL::to_double(j->vertex()->point().x());\n            i++;\n            mMeshData[i] = (float)CGAL::to_double(j->vertex()->point().y());\n            i++;\n            mMeshData[i] = (float)CGAL::to_double(j->vertex()->point().z());\n            i++;\n        } while ( ++j != f->facet_begin());\n    }\n    \n    jfloatArray mResultMeshData;\n    mResultMeshData = env->NewFloatArray(mNumberOfMeshData);\n    env->SetFloatArrayRegion(mResultMeshData, 0, mNumberOfMeshData, mMeshData);\n    \n    return mResultMeshData;\n}\n\n//    int size = std::distance(C.vertices_begin(), C.vertices_end());\n//    cout << \"number of points : \" << size << endl;\n//\n//\n//    //    if (/* DISABLES CODE */ (false)) {\n//    cout << \"coref ... \";\n//\n//    coref(new_A, new_B,\n//          polyline_output,\n//          std::back_inserter(result),\n//          operation_type);\n//\n//    cout << \"done.\" << endl;\n//\n//    //    }\n//\n//    //    int union_index = result[0].second == Corefinement::Join_tag ? 0:1;\n//    //    int intersection_index = (union_index+1)%2;\n//    //\n//    //    cout << union_index << endl;\n//    //    cout << intersection_index << endl;\n//\n//    //    cout << *( result[union_index].first );\n//    //    cout << endl;\n//    //    cout << *( result[intersection_index].first );\n//\n//    //    cout << *( result[0].first );\n//\n//    //    /* return results */\n//\n//    //    CGAL::Vertex_iterator begin = result[union_index].first->vertices_begin();\n//    //    CGAL::Vertex_iterator end = result[union_index].first->vertices_end();\n//\n//    //    std::list<Vertex>::iterator itb = result[union_index]->vertices_begin();\n//    //    for(; result[union_index].first->vertices_begin() != result[union_index].first->vertices_end(); itb++) {\n//    //\n//    //    }\n\n//    /* populate vectors */\n//    {\n//        jfloat* jcoords_A_array = env->GetFloatArrayElements(coords_A_array, &iscopy);\n//        const int mNumberOfPoints_A = (env->GetArrayLength(coords_A_array)) / 3;\n//\n//        if (M_DEBUG) cout << \"--- A has points: \" << mNumberOfPoints_A << endl;\n//\n//        for(int i=0; i < mNumberOfPoints_A; i++) {\n//            double x = (double)*jcoords_A_array;\n//            jcoords_A_array++;\n//            double y = (double)*jcoords_A_array;\n//            jcoords_A_array++;\n//            double z = (double)*jcoords_A_array;\n//            jcoords_A_array++;\n//            coords_A.push_back(x);\n//            coords_A.push_back(y);\n//            coords_A.push_back(z);\n//            //            cout << x << \", \" << y << \", \" << z << endl;\n//        }\n//    }\n//    {\n//        jfloat* jcoords_B_array = env->GetFloatArrayElements(coords_B_array, &iscopy);\n//        const int mNumberOfPoints_B = (env->GetArrayLength(coords_B_array)) / 3;\n//\n//        if (M_DEBUG) cout << \"--- B has points: \" << mNumberOfPoints_B << endl;\n//\n//        for(int i=0; i < mNumberOfPoints_B; i++) {\n//            double x = (double)*jcoords_B_array;\n//            jcoords_B_array++;\n//            double y = (double)*jcoords_B_array;\n//            jcoords_B_array++;\n//            double z = (double)*jcoords_B_array;\n//            jcoords_B_array++;\n//            coords_B.push_back(x);\n//            coords_B.push_back(y);\n//            coords_B.push_back(z);\n//            //            cout << x << \", \" << y << \", \" << z << endl;\n//        }\n//    }\n\n\n//    Vertex_iterator v;\n//    for( v = polyhedron_result.vertices_begin();\n//        v != polyhedron_result.vertices_end();\n//        ++v )     {\n//        cout << v->point() << endl;\n//    }\n\n//    vector<Alpha_shape_3::Facet> a_facets;\n//    as->get_alpha_shape_facets(std::back_inserter(a_facets), facets_type);\n//    const jsize nb_facets_indices = 3 * 3 * a_facets.size();\n//\n//    if (M_DEBUG) cout << \"--- number of points: \" << nb_facets_indices << endl;\n//\n//    Index index(as->vertices_begin(), as->vertices_end());\n//    jfloat m_mesh_points [nb_facets_indices];\n//\n//    size_t nbf=a_facets.size();\n//    for (size_t i=0;i<nbf;++i) {\n//        if ( as->classify( a_facets[i].first )!=Alpha_shape_3::EXTERIOR ) {\n//            a_facets[i]=as->mirror_facet( a_facets[i] );\n//        }\n//\n//        int indices[3]={\n//            (a_facets[i].second+1)%4,\n//            (a_facets[i].second+2)%4,\n//            (a_facets[i].second+3)%4,\n//        };\n//\n//        /// according to the encoding of vertex indices, this is needed to get\n//        /// a consistent orienation\n//        if ( a_facets[i].second%2==0 ) {\n//            swap(indices[0], indices[1]);\n//        }\n//\n//        m_mesh_points[i * 9 + 0] = a_facets[i].first->vertex(indices[0])->point()[0];\n//        m_mesh_points[i * 9 + 1] = a_facets[i].first->vertex(indices[0])->point()[1];\n//        m_mesh_points[i * 9 + 2] = a_facets[i].first->vertex(indices[0])->point()[2];\n//        m_mesh_points[i * 9 + 3] = a_facets[i].first->vertex(indices[1])->point()[0];\n//        m_mesh_points[i * 9 + 4] = a_facets[i].first->vertex(indices[1])->point()[1];\n//        m_mesh_points[i * 9 + 5] = a_facets[i].first->vertex(indices[1])->point()[2];\n//        m_mesh_points[i * 9 + 6] = a_facets[i].first->vertex(indices[2])->point()[0];\n//        m_mesh_points[i * 9 + 7] = a_facets[i].first->vertex(indices[2])->point()[1];\n//        m_mesh_points[i * 9 + 8] = a_facets[i].first->vertex(indices[2])->point()[2];\n//    }\n//\n//    jfloatArray result;\n//    result = env->NewFloatArray( nb_facets_indices);\n//    env->SetFloatArrayRegion(result, 0, nb_facets_indices, m_mesh_points);\n//\n//    return result;\n\n\n//    /* build jfloatarray */\n//\n//    const int mNumberOfMeshData = distance(polyhedron_result.vertices_begin(), polyhedron_result.vertices_end()) * 3;\n//    jfloat mMeshData[mNumberOfMeshData];\n//\n//    Vertex_iterator v;\n//    int i = 0;\n//    for( v = polyhedron_result.vertices_begin();\n//        v != polyhedron_result.vertices_end();\n//        ++v )\n//    {\n//        mMeshData[i] = (float)CGAL::to_double(v->point().x());\n//        i++;\n//        mMeshData[i] = (float)CGAL::to_double(v->point().y());\n//        i++;\n//        mMeshData[i] = (float)CGAL::to_double(v->point().z());\n//        i++;\n//    }\n//\n//    if (M_DEBUG) cout << \"--- build array \" << endl;\n//\n//    jfloatArray mResultMeshData;\n//    mResultMeshData = env->NewFloatArray(mNumberOfMeshData);\n//    env->SetFloatArrayRegion(mResultMeshData, 0, mNumberOfMeshData, mMeshData);\n//\n//    if (M_DEBUG) cout << \"--- return array \" << endl;\n//\n//    return mResultMeshData;\n\nJNIEXPORT jint JNICALL Java_gewebe_CGALBooleanOperations3_version\n(JNIEnv * env, jobject)\n{\n    int mVersion = 20210130;\n    int mTime = 141015;\n    return mVersion;\n}\n\n", "meta": {"hexsha": "7029c6d80ba355ee9e8728de32f2e63207811f60", "size": 16763, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/CGALBooleanOperations3/cpp/CGALBooleanOperations3.cpp", "max_stars_repo_name": "dennisppaul/gewebe", "max_stars_repo_head_hexsha": "32d80f130eb4fed855c2442256d50f45d4edc73e", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-14T08:38:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-14T08:38:49.000Z", "max_issues_repo_path": "lib/CGALBooleanOperations3/cpp/CGALBooleanOperations3.cpp", "max_issues_repo_name": "dennisppaul/gewebe", "max_issues_repo_head_hexsha": "32d80f130eb4fed855c2442256d50f45d4edc73e", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-05-18T10:16:18.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-17T12:27:29.000Z", "max_forks_repo_path": "lib/CGALBooleanOperations3/cpp/CGALBooleanOperations3.cpp", "max_forks_repo_name": "dennisppaul/gewebe", "max_forks_repo_head_hexsha": "32d80f130eb4fed855c2442256d50f45d4edc73e", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5206971678, "max_line_length": 141, "alphanum_fraction": 0.5895126171, "num_tokens": 4520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.26123332732715493}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// Copyright 2021 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    cartesian_trajectory_segment.cpp\n *\n * \\author  Stefan Scherzinger <scherzin@fzi.de>\n * \\date    2021/01/20\n *\n */\n//-----------------------------------------------------------------------------\n\n#include <cartesian_trajectory_interpolation/cartesian_trajectory_segment.h>\n#include <algorithm>\n#include <cmath>\n#include \"Eigen/src/Core/GlobalFunctions.h\"\n#include \"Eigen/src/Core/Matrix.h\"\n#include \"Eigen/src/Core/util/Constants.h\"\n#include \"Eigen/src/Geometry/Quaternion.h\"\n#include <Eigen/Dense>\n\nnamespace cartesian_ros_control\n{\n  using Time = CartesianTrajectorySegment::Time;\n  using SplineState = CartesianTrajectorySegment::SplineState;\n\n  CartesianTrajectorySegment::CartesianTrajectorySegment(const Time&  start_time,\n      const CartesianState& start_state,\n      const Time&  end_time,\n      const CartesianState& end_state)\n    : QuinticSplineSegment(start_time, convert(start_state), end_time, convert(end_state))\n  {\n  };\n\n\n  void CartesianTrajectorySegment::sample(const Time& time, CartesianState& state) const\n  {\n    // Sample from the underlying spline segment.\n    SplineState s(7);\n    QuinticSplineSegment::sample(time, s);\n\n    if (time < this->startTime() || time > this->endTime())\n    {\n      state.p = Eigen::Vector3d(s.position[0], s.position[1], s.position[2]);\n      state.q = Eigen::Quaterniond(s.position[3], s.position[4], s.position[5], s.position[6]).normalized();\n\n      state.v = Eigen::Vector3d::Zero();\n      state.w = Eigen::Vector3d::Zero();\n      state.v_dot = Eigen::Vector3d::Zero();\n      state.w_dot = Eigen::Vector3d::Zero();\n    }\n    else\n    {\n      state = convert(s);\n    }\n  }\n\n\n  SplineState convert(const CartesianState& state)\n  {\n    SplineState spline_state;\n\n    // Note: The pre-multiplication of velocity and acceleration terms with\n    // `state.q.inverse()` transforms them into the body-local reference frame.\n    // This is required for computing quaternion-based velocities and\n    // accelerations below.\n\n    // Convenience method\n    auto fill = [](auto& vec, const auto& first, const auto& second)\n    {\n      vec.push_back(first.x());\n      vec.push_back(first.y());\n      vec.push_back(first.z());\n\n      vec.push_back(second.w());\n      vec.push_back(second.x());\n      vec.push_back(second.y());\n      vec.push_back(second.z());\n    };\n\n    // Spline positions\n    fill(spline_state.position, state.p, state.q);\n\n    // Spline velocities\n    if(std::isnan(state.v.x()) || std::isnan(state.v.y()) || std::isnan(state.v.z())\n          || std::isnan(state.w.x()) || std::isnan(state.w.y()) || std::isnan(state.w.z()))\n    {\n      return spline_state;  // with uninitialized velocity/acceleration data\n    }\n    Eigen::Quaterniond q_dot;\n    Eigen::Vector3d tmp = state.q.inverse() * state.w;\n    Eigen::Quaterniond omega(0, tmp.x(), tmp.y(), tmp.z());\n    q_dot.coeffs() = 0.5 * (omega * state.q).coeffs();\n\n    fill(spline_state.velocity, state.q.inverse() * state.v, q_dot);\n\n    // Spline accelerations\n    if(std::isnan(state.v_dot.x()) || std::isnan(state.v_dot.y()) || std::isnan(state.v_dot.z())\n          || std::isnan(state.w_dot.x()) || std::isnan(state.w_dot.y()) || std::isnan(state.w_dot.z()))\n    {\n      return spline_state;  // with uninitialized acceleration data\n    }\n    Eigen::Quaterniond q_ddot;\n    tmp = state.q.inverse() * state.w_dot;\n    Eigen::Quaterniond omega_dot(0, tmp.x(), tmp.y(), tmp.z());\n    q_ddot.coeffs() = 0.5 * (omega_dot * state.q).coeffs() + 0.5 * (omega * q_dot).coeffs();\n\n    fill(spline_state.acceleration, state.q.inverse() * state.v_dot, q_ddot);\n\n    return spline_state;\n  };\n\n\n  CartesianState convert(const SplineState& s)\n  {\n    CartesianState state;\n\n    // Cartesian positions\n    if (s.position.empty())\n    {\n      return state;  // with positions/velocities/accelerations zero initialized\n    }\n    state.p = Eigen::Vector3d(s.position[0], s.position[1], s.position[2]);\n    state.q = Eigen::Quaterniond(s.position[3], s.position[4], s.position[5], s.position[6]).normalized();\n\n    // Cartesian velocities\n    if (s.velocity.empty())\n    {\n      return state;  // with velocities/accelerations zero initialized\n    }\n    Eigen::Quaterniond q_dot(s.velocity[3], s.velocity[4], s.velocity[5], s.velocity[6]);\n\n    Eigen::Quaterniond omega;\n    omega.coeffs() = 2.0 * (q_dot * state.q.inverse()).coeffs();\n\n    state.v = Eigen::Vector3d(s.velocity[0], s.velocity[1], s.velocity[2]);\n    state.w = Eigen::Vector3d(omega.x(), omega.y(), omega.z());\n\n    // Cartesian accelerations\n    if (s.acceleration.empty())\n    {\n      return state;  // with accelerations zero initialized\n    }\n    Eigen::Quaterniond q_ddot(s.acceleration[3], s.acceleration[4], s.acceleration[5], s.acceleration[6]);\n\n    Eigen::Quaterniond omega_dot;\n    omega_dot.coeffs() = 2.0 * (\n        (q_ddot * state.q.inverse()).coeffs() -\n        ((q_dot * state.q.inverse()) * (q_dot * state.q.inverse())).coeffs()\n        );\n\n    state.v_dot = Eigen::Vector3d(s.acceleration[0], s.acceleration[1], s.acceleration[2]);\n    state.w_dot = Eigen::Vector3d(omega_dot.x(), omega_dot.y(), omega_dot.z());\n\n    // Re-transform vel and acc to the correct reference frame.\n    state.v = state.q * state.v;\n    state.w = state.q * state.w;\n    state.v_dot = state.q * state.v_dot;\n    state.w_dot = state.q * state.w_dot;\n\n    return state;\n  }\n\n  std::ostream& operator<<(std::ostream &out, const CartesianTrajectorySegment::SplineState& state)\n  {\n    out << \"pos:\\n\";\n    for (size_t i = 0; i < state.position.size(); ++i)\n    {\n      out << state.position[i] << '\\n';\n    }\n    out << \"vel:\\n\";\n    for (size_t i = 0; i < state.velocity.size(); ++i)\n    {\n      out << state.velocity[i] << '\\n';\n    }\n    out << \"acc:\\n\";\n    for (size_t i = 0; i < state.acceleration.size(); ++i)\n    {\n      out << state.acceleration[i] << '\\n';\n    }\n\n    return out;\n  }\n}\n", "meta": {"hexsha": "6f6b346385b7372fc58307be55581400fbd02a9d", "size": 7677, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cartesian_trajectory_interpolation/src/cartesian_trajectory_segment.cpp", "max_stars_repo_name": "fzi-forschungszentrum-informatik/cartesian_ros_control", "max_stars_repo_head_hexsha": "08909710bf4587db5c6072541cb21e7820993998", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2021-02-14T08:35:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:18:21.000Z", "max_issues_repo_path": "cartesian_trajectory_interpolation/src/cartesian_trajectory_segment.cpp", "max_issues_repo_name": "fzi-forschungszentrum-informatik/cartesian_ros_control", "max_issues_repo_head_hexsha": "08909710bf4587db5c6072541cb21e7820993998", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2021-03-05T18:35:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-10T11:11:03.000Z", "max_forks_repo_path": "cartesian_trajectory_interpolation/src/cartesian_trajectory_segment.cpp", "max_forks_repo_name": "fzi-forschungszentrum-informatik/cartesian_ros_control", "max_forks_repo_head_hexsha": "08909710bf4587db5c6072541cb21e7820993998", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-02-18T08:24:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-07T14:44:14.000Z", "avg_line_length": 36.2122641509, "max_line_length": 108, "alphanum_fraction": 0.6390517129, "num_tokens": 1850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.26123332080774275}}
{"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/Norm/PAlphaDPW08.h\"\n#include \"latbuilder/WeightsDispatcher.h\"\n#include \"latbuilder/Util.h\"\n\n#include <boost/math/special_functions/zeta.hpp>\n\nnamespace LatBuilder { namespace Norm {\n\nnamespace SumHelperPAlphaDPW08{\n\n   template <typename WEIGHTS>\n   class SumHelper {\n   public:\n      Real operator()(\n            const WEIGHTS& weights,\n            Real normType,\n            Real z,\n            Real lambda,\n            Dimension dimension\n            ) const\n      { throw std::logic_error(\"DPW08 norm not implemented for this type of weights\"); }\n   };\n\n#define DECLARE_PALPHA_DPW08_SUM(weight_type) \\\n      template <> \\\n      class SumHelper<weight_type> { \\\n      public: \\\n         Real operator()( \\\n               const weight_type& weights, \\\n               Real normType, \\\n               Real z, \\\n               Real lambda, \\\n               Dimension dimension \\\n               ) const; \\\n      }\n\n   DECLARE_PALPHA_DPW08_SUM(LatticeTester::ProductWeights);\n   DECLARE_PALPHA_DPW08_SUM(LatBuilder::CombinedWeights);\n\n#undef DECLARE_PALPHA_DPW08_SUM\n\n   //===========================================================================\n   // combined weights\n   //===========================================================================\n\n   // Separating sumCombined() from\n   // SumHelper<LatBuilder::CombinedWeights>::operator() is a workaround for\n   // LLVM/clang++.\n   Real sumCombined(\n         const CombinedWeights& weights,\n         Real normType,\n         Real z,\n         Real lambda,\n         Dimension dimension\n         )\n   {\n      Real val = 0.0;\n      for (const auto& w : weights.list())\n         val += WeightsDispatcher::dispatch<SumHelper>(*w, normType, z, lambda, dimension);\n      return val;\n   }\n\n   Real SumHelper<LatBuilder::CombinedWeights>::operator()(\n         const CombinedWeights& weights,\n         Real normType,\n         Real z,\n         Real lambda,\n         Dimension dimension\n         ) const\n   {\n      return sumCombined(weights, normType, z, lambda, dimension);\n   }\n\n\n   //===========================================================================\n   // product weights\n   //===========================================================================\n\n   Real SumHelper<LatticeTester::ProductWeights>::operator()(\n         const LatticeTester::ProductWeights& weights,\n         Real normType,\n         Real z,\n         Real lambda,\n         Dimension dimension\n         ) const\n   {\n      Real val = 1.0;\n      for (Dimension coord = 0; coord < dimension; coord++) {\n         Real weight = weights.getWeightForCoordinate(coord);\n         if (weight)\n            // weights are assumed to already be to the power normType; map\n            // them to power 2\n            val *= 1.0 + z * pow(weight, lambda * 2 / normType);\n      }\n      val -= 1.0;\n      return val;\n   }\n}\n\nPAlphaDPW08::PAlphaDPW08(unsigned int alpha, const LatticeTester::Weights& weights, Real normType):\n   NormAlphaBase<PAlphaDPW08>(alpha, normType),\n   m_weights(weights)\n{}\n\ntemplate <LatticeType LR, EmbeddingType L>\nReal PAlphaDPW08::value(\n      Real lambda,\n      const SizeParam<LR, L>& sizeParam,\n      Dimension dimension,\n      Real norm\n      ) const\n{\n   norm = 1.0 / (norm * sizeParam.numPoints());\n   const auto kappa = primeFactors(sizeParam.numPoints()).size();\n   // 2^(kappa+1), where kappa is the number of distinct prime factors of n\n   const auto k = intPow(2, kappa + 1);\n   Real z = static_cast<Real>(k * boost::math::zeta<Real>(this->alpha() * lambda));\n   Real val = WeightsDispatcher::dispatch<SumHelperPAlphaDPW08::SumHelper>(\n         m_weights,\n         this->normType(),\n         z,\n         lambda,\n         dimension\n         );\n\n   return pow(norm * val, 1.0 / lambda);\n}\n\ntemplate Real PAlphaDPW08::value<LatticeType::ORDINARY, EmbeddingType::UNILEVEL>(Real, const SizeParam<LatticeType::ORDINARY, EmbeddingType::UNILEVEL>&, Dimension, Real) const;\ntemplate Real PAlphaDPW08::value<LatticeType::ORDINARY, EmbeddingType::MULTILEVEL>(Real, const SizeParam<LatticeType::ORDINARY, EmbeddingType::MULTILEVEL>&, Dimension, Real) const;\n\ntemplate Real PAlphaDPW08::value<LatticeType::POLYNOMIAL, EmbeddingType::UNILEVEL>(Real, const SizeParam<LatticeType::POLYNOMIAL, EmbeddingType::UNILEVEL>&, Dimension, Real) const;\ntemplate Real PAlphaDPW08::value<LatticeType::POLYNOMIAL, EmbeddingType::MULTILEVEL>(Real, const SizeParam<LatticeType::POLYNOMIAL, EmbeddingType::MULTILEVEL>&, Dimension, Real) const;\n\n}}\n", "meta": {"hexsha": "00c73669f93d5e06bfc944281091d2d707458bbd", "size": 5198, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/LatBuilder/Norm/PAlphaDPW08.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/Norm/PAlphaDPW08.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/Norm/PAlphaDPW08.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": 34.1973684211, "max_line_length": 184, "alphanum_fraction": 0.6158137745, "num_tokens": 1218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2611324470852709}}
{"text": "#include <vector>\n\n#include <armadillo>\n\n#include <plink/plink_file.hpp>\n\nclass lars_variables\n{\npublic:\n    virtual arma::vec get_centered_phenotype( ) const = 0;\n    virtual size_t get_num_samples( ) const = 0;\n    virtual size_t get_num_variables( ) const = 0;\n    virtual std::string get_name(size_t index) const = 0;\n    virtual void calculate_cor(const arma::vec &residual, arma::vec &c) const = 0;\n    virtual arma::vec eig_prod(const arma::vec &u) const = 0;\n    virtual arma::mat get_active(const arma::uvec &active) const = 0;\n};\n\nclass null_lars : public lars_variables\n{\n    public:\n        null_lars(const arma::mat &X, const arma::vec &y)\n            : m_X( X ),\n              m_y( y )\n        {\n        }\n    \n        arma::vec get_centered_phenotype() const\n        {\n            return m_y - arma::mean( m_y );\n        }\n        \n        size_t get_num_samples() const\n        {\n            return m_y.n_elem;\n        }\n\n        size_t get_num_variables() const\n        {\n            return m_X.n_cols;\n        }\n        \n        std::string get_name(size_t index) const\n        {\n            return \"\";\n        }\n    \n        void calculate_cor(const arma::vec &residual, arma::vec &c) const\n        {\n            for(int i = 0; i < m_X.n_cols; i++)\n            {\n                c[ i ] = arma::dot( m_X.col( i ), residual );\n            }\n        }\n\n        arma::vec eig_prod(const arma::vec &u) const\n        {\n            return m_X.t( ) * u;\n        }\n        \n        arma::mat get_active(const arma::uvec &active) const\n        {\n            return m_X.cols( active );\n        }\n\n    private:\n        arma::mat m_X;\n        arma::vec m_y;\n};\n\n/**\n * This class is responsible for both genetic and environmental data, along\n * with computing certain properties of this data that relates to the LARS\n * algorithm. Primarily, to avoid passing and operating on each data type\n * separately within the algorithm.\n */\nclass gene_environment : public lars_variables\n{\npublic:\n    /**\n     * Constructor.\n     *\n     * @param genotypes A matrix of genotypes.\n     * @param cov A matrix of covariates.\n     * @param phenotype A vector of phenotypes.\n     * @param cov_names Names of the covariates.\n     * @param only_main Exclude gene-environment.\n     */\n    gene_environment(genotype_matrix_ptr genotypes, const arma::mat &cov, const arma::vec &phenotype, const std::vector<std::string> &cov_names, bool only_main);\n    /**\n     * Imputes the missing genotypes, covariates and phenotypes.\n     */\n    void impute_missing();\n\n    /**\n     * Centers a phenotype and returns it.\n     *\n     * @return Returns a centered phenotype.\n     */\n    arma::vec get_centered_phenotype() const;\n\n    /**\n     * Returns the number of samples.\n     *\n     * @return the number of samples.\n     */\n    size_t get_num_samples() const;\n\n    /**\n     * Returns the number of variables.\n     *\n     * @return the number of variables.\n     */\n    size_t get_num_variables() const;\n   \n    /**\n     * Returns the name of the variable with the given index.\n     *\n     * @param index Index of the variable whoose name to return.\n     *\n     * @return The name of the variable with the given index.\n     */ \n    std::string get_name(size_t index) const;\n   \n    /**\n     * Returns the complete list of variable names.\n     *\n     * @return List of variables.\n     */ \n    std::vector<std::string> get_names() const;\n\n    /**\n     * Returns the number of minor alleles for the given index, and\n     * 0 if index is out of bounds.\n     *\n     * @param index Index to the genotype.\n     * \n     * @return The number of minor alleles for the given index, and\n     * 0 if the index is out of bounds.\n     */\n    unsigned int compute_num_minor(size_t index) const;\n\n    /**\n     * Calculates the correlation between each variable and\n     * the given vector of residuals. The results are stored\n     * in the supplied vector c.\n     *\n     * @param residual A vector of residuals.\n     * @param c A vector of at least the size of the number of variables,\n     *          to store the computed correlations in.\n     */\n    void calculate_cor(const arma::vec &residual, arma::vec &c) const;\n    \n    /**\n     * Computes the vector a from the LARS paper from the\n     * vector u.\n     *\n     * @param u The u-vector from the LARS paper.\n     *\n     * @return The a-vector from the LARS paper.\n     */\n    arma::vec eig_prod(const arma::vec &u) const;\n\n    /**\n     * Returns a matrix of standardized variables according to the\n     * given vector of indicides of active variables.\n     *\n     * @param active  Indicies of active variables.\n     *\n     * @return Matrix of standardized active variables.\n     */\n    arma::mat get_active(const arma::uvec &active) const;\n    \n    /**\n     * Returns a matrix of raw variables according to the\n     * given vector of indicides of active variables.\n     *\n     * @param active  Indicies of active variables.\n     *\n     * @return Matrix of standardized active variables.\n     */\n    arma::mat get_active_raw(const arma::uvec &active) const;\n\nprivate:\n    /**\n     * Assigns missing genotypes with genotype mean.\n     */\n    void fill_missing_genotypes();\n\n    /**\n     * Assigns missing phenotypes with phenotype mean.\n     */\n    void fill_missing_phenotypes();\n\n    /**\n     * Assigns missing covariates with covariate mean.\n     */\n    void fill_missing_cov();\n\n    /**\n     * Computes the mean and standard deviation of each variable\n     * and stores it in the m_mean and m_sd vectors. This is performed\n     * in this way because it is too expensive to store the genotypes\n     * as floats.\n     */\n    void compute_mean_sd();\n\nprivate:\n    /**\n     * Matrix of genotypes.\n     */\n    genotype_matrix_ptr m_genotypes;\n\n    /**\n     * Matrix of covariates.\n     */\n    arma::mat m_cov;\n\n    /**\n     * Vector of phenotypes.\n     */\n    arma::vec m_phenotype;\n\n    /**\n     * Vector of mean values for each variable.\n     */\n    arma::vec m_mean;\n\n    /**\n     * Vector of standard deviation for each variable.\n     */\n    arma::vec m_sd;\n\n    /**\n     * Vector variable names.\n     */\n    std::vector<std::string> m_names;\n\n    /**\n     * Only consider main effects.\n     */\n    bool m_only_main;\n};\n", "meta": {"hexsha": "b3a618a9805bdd198730062db0c2855634ba07be", "size": 6236, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/gene_environment.hpp", "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/gene_environment.hpp", "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/gene_environment.hpp", "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": 25.5573770492, "max_line_length": 161, "alphanum_fraction": 0.5950930083, "num_tokens": 1501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.26113244708527084}}
{"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\nclass Plane {\n    PS::F64vec nvec;    // Normal vector of the projection surface\n    PS::F64    cnst;    // Distance of the projection surface from the origin\n    PS::F64vec base;    // The nearest point on the projection surface from the origin\n    PS::F64vec axis[2]; // Newly defined vectors of the projection surface\n    PS::F64vec pdsp;    // Vector of pallaral displacement on the projection surface\n    PS::F64    wdth;    // Width of the projection surface\n\n    void normalize() {\n        PS::F64 vabs = sqrt(this->nvec * this->nvec);\n        this->nvec = this->nvec / vabs;\n        this->cnst = this->cnst / vabs;\n    }\n\n    void defineAxis() {\n        if(this->nvec[0] == 0. && this->nvec[1] == 0. && this->nvec[2] == 1.) {\n            this->axis[0] = PS::F64vec(1., 0., 0.);\n            this->axis[1] = PS::F64vec(0., 1., 0.);\n        } else if (this->nvec[0] == 0. && this->nvec[1] == 1. && this->nvec[2] == 0.) {\n            this->axis[0] = PS::F64vec(1., 0., 0.);\n            this->axis[1] = PS::F64vec(0., 0., 1.);\n        } else if (this->nvec[0] == 1. && this->nvec[1] == 0. && this->nvec[2] == 0.) {\n            this->axis[0] = PS::F64vec(0., 1., 0.);\n            this->axis[1] = PS::F64vec(0., 0., 1.);\n        } else {\n            assert(NULL);\n        }\n    }\n\npublic:\n\n    Plane() {\n        this->nvec    = 0.;\n        this->cnst    = 0.;\n        this->base    = 0.;\n        this->axis[0] = 0.;\n        this->axis[1] = 0.;\n        this->pdsp    = 0.;\n        this->wdth    = 0.;\n    }\n\n    PS::F64 readData(FILE *fp) {\n        fscanf(fp, \"%lf%lf%lf%lf\",\n               &this->nvec[0], &this->nvec[1], &this->nvec[2], &this->cnst);\n        fscanf(fp, \"%lf%lf\", &this->pdsp[0], &this->pdsp[1]);\n        fscanf(fp, \"%lf\", &this->wdth);\n        this->normalize();\n        this->base = this->cnst * this->nvec;\n        this->defineAxis();\n    }\n\n    PS::F64 writeData(FILE *fp) {\n        if(PS::Comm::getRank() == 0) {\n            fprintf(fp, \"nvec: %+e %+e %+e\\n\",\n                    this->nvec[0], this->nvec[1], this->nvec[2]);\n            fprintf(fp, \"cnst: %+e\\n\", this->cnst);\n            fprintf(fp, \"base: %+e %+e %+e\\n\",\n                    this->base[0], this->base[1], this->base[2]);\n            fprintf(fp, \"axis[0]: %+e %+e %+e\\n\",\n                    this->axis[0][0], this->axis[0][1], this->axis[0][2]);\n            fprintf(fp, \"axis[1]: %+e %+e %+e\\n\",\n                    this->axis[1][0], this->axis[1][1], this->axis[1][2]);\n            fprintf(fp, \"pdsp: %+e %+e %+e\\n\",\n                    this->pdsp[0], this->pdsp[1], this->pdsp[2]);\n            fprintf(fp, \"wdth: %+e\\n\", this->wdth);\n        }\n    }\n\n    inline PS::F64 calcDistance(PS::F64vec pos) {\n        return fabs(this->nvec * (pos - this->base));\n    }\n\n    inline PS::F64vec calcCoordinateOnPlane(PS::F64vec pos) {\n        PS::F64 px = this->axis[0] * (pos - this->base) + pdsp[0];\n        PS::F64 py = this->axis[1] * (pos - this->base) + pdsp[1];\n        return PS::F64vec(px, py, 0.);\n    }\n\n    PS::F64 getWidth() {\n        return this->wdth;\n    }\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    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\ntemplate <class Tsph>\nvoid calcDensityCenter(Tsph  & sph,\n                       PS::F64vec & xdens_g,\n                       PS::F64vec & vdens_g,\n                       PS::F64vec & adens_g) {\n    PS::F64    tdens = 0.;\n    PS::F64vec xdens = 0.;\n    PS::F64vec vdens = 0.;\n    PS::F64vec adens = 0.;\n\n    for(PS::S64 i = 0; i < sph.getNumberOfParticleLocal(); i++) {\n        if(sph[i].istar != 0) {\n            continue;\n        }\n        tdens += sph[i].dens;\n        xdens += sph[i].dens * sph[i].pos;\n        vdens += sph[i].dens * sph[i].vel;\n        adens += sph[i].dens * sph[i].acc;\n    }\n\n    PS::F64    tdens_g = PS::Comm::getSum(tdens);\n    xdens_g = PS::Comm::getSum(xdens);\n    vdens_g = PS::Comm::getSum(vdens);\n    adens_g = PS::Comm::getSum(adens);\n\n    xdens_g = xdens_g / tdens_g;\n    vdens_g = vdens_g / tdens_g;\n    adens_g = adens_g / tdens_g;\n\n    return;\n}\n\ntemplate <class Tsph>\nvoid projectOnPlane(char * ofile,\n                    Plane & plane,\n                    Tsph  & sph) {\n    const  PS::S64 nmax = 256;\n    static PS::S64 ptcl[nmax][nmax];\n    static PS::F64 dens[nmax][nmax];\n    static PS::F64 temp[nmax][nmax];\n    static PS::F64 omgz[nmax][nmax];\n    static PS::F64 entr[nmax][nmax];\n    static PS::F64 istr[nmax][nmax];\n    \n    PS::F64 wdth  = plane.getWidth();\n    PS::F64 dx    = wdth / (PS::F64)nmax;\n    PS::F64 dxinv = 1. / dx;\n    \n    for(PS::S64 i = 0; i < nmax; i++) {\n        for(PS::S64 j = 0; j < nmax; j++) {\n            ptcl[i][j] = 0;\n            dens[i][j] = 0.;\n            temp[i][j] = 0.;\n            omgz[i][j] = 0.;\n            entr[i][j] = 0.;\n            istr[i][j] = 0.;\n        }\n    }\n\n    PS::F64vec xdens = 0.;\n    PS::F64vec vdens = 0.;\n    PS::F64vec adens = 0.;\n    calcDensityCenter(sph, xdens, vdens, adens);\n\n    for(PS::S64 i = 0; i < sph.getNumberOfParticleLocal(); i++) {\n        sph[i].pos -= xdens;\n        sph[i].vel -= vdens;\n        sph[i].acc -= adens;\n        PS::F64vec omg_i  = sph[i].pos ^ sph[i].vel;\n        PS::F64    omgz_i = (1. / (sph[i].pos[0] * sph[i].pos[0] + sph[i].pos[1] * sph[i].pos[1])) * omg_i[2];\n        if(plane.calcDistance(sph[i].pos) > sph[i].ksr) {\n            continue;\n        }\n        PS::F64vec pvec  = plane.calcCoordinateOnPlane(sph[i].pos);\n        PS::S64    ix    = (PS::S64)((pvec[0] + 0.5 * wdth) * dxinv);\n        PS::S64    iy    = (PS::S64)((pvec[1] + 0.5 * wdth) * dxinv);\n        if(ix < 0 || nmax <= ix) {\n            continue;\n        }\n        if(iy < 0 || nmax <= iy) {\n            continue;\n        }\n        ptcl[ix][iy] += 1;\n        dens[ix][iy] += sph[i].dens;\n        temp[ix][iy] += sph[i].temp;\n        omgz[ix][iy] += omgz_i;\n        entr[ix][iy] += sph[i].entr;\n        istr[ix][iy] += (sph[i].istar + 1);\n    }\n\n    static PS::S64 ptcl_g[nmax][nmax];\n    static PS::F64 dens_g[nmax][nmax];\n    static PS::F64 temp_g[nmax][nmax];\n    static PS::F64 omgz_g[nmax][nmax];\n    static PS::F64 entr_g[nmax][nmax];\n    static PS::F64 istr_g[nmax][nmax];\n\n    PS::S64 ierr = 0;\n    ierr = MPI_Allreduce(ptcl, ptcl_g, nmax*nmax, MPI_LONG_LONG, MPI_SUM, MPI_COMM_WORLD);\n    ierr = MPI_Allreduce(dens, dens_g, nmax*nmax, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n    ierr = MPI_Allreduce(temp, temp_g, nmax*nmax, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n    ierr = MPI_Allreduce(omgz, omgz_g, nmax*nmax, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n    ierr = MPI_Allreduce(entr, entr_g, nmax*nmax, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n    ierr = MPI_Allreduce(istr, istr_g, nmax*nmax, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n\n    for(PS::S64 i = 0; i < nmax; i++) {\n        for(PS::S64 j = 0; j < nmax; j++) {\n            PS::F64 pinv = ((ptcl_g[i][j] != 0) ? (1. / ptcl_g[i][j]) : 0.);\n            dens_g[i][j] *= pinv;\n            temp_g[i][j] *= pinv;\n            omgz_g[i][j] *= pinv;\n            entr_g[i][j] *= pinv;\n            istr_g[i][j] *= pinv;\n        }\n    }\n\n    if(PS::Comm::getRank() == 0) {\n        FILE * fp = fopen(ofile, \"w\");\n        for(PS::S64 i = 0; i < nmax; i++) {\n            for(PS::S64 j = 0; j < nmax; j++) {\n                PS::F64 px = dx * (PS::F64)i - 0.5 * wdth;\n                PS::F64 pz = dx * (PS::F64)j - 0.5 * wdth;\n                fprintf(fp, \"%+e %+e %+e %+e %+e %+e %+e\\n\",\n                        px, pz,\n                        dens_g[i][j], temp_g[i][j], omgz_g[i][j],\n                        entr_g[i][j], istr_g[i][j]);\n            }\n        }\n        fclose(fp);\n    }\n\n}\n\nint main(int argc, char ** argv) {\n    PS::Initialize(argc, argv);\n\n    PS::ParticleSystem<SPHAnalysis> sph;\n    sph.initialize();\n    sph.createParticle(0);\n    sph.setNumberOfParticleLocal(0);\n\n    char idir[1024], odir[1024];\n    PS::S64 ibgn, iend, dsnp;\n    Plane plane;\n    FILE * fp = fopen(argv[1], \"r\");\n    fscanf(fp, \"%s\", idir);\n    fscanf(fp, \"%s\", odir);\n    fscanf(fp, \"%lld%lld%lld\", &ibgn, &iend, &dsnp);\n    plane.readData(fp);\n    fclose(fp);\n    plane.writeData(stdout);\n\n    for(PS::S64 itime = ibgn; itime <= iend; itime += dsnp) {        \n        char tfile[1024];\n        FILE *fp = NULL;\n        PS::S64 tdir = 0;\n        for(PS::S64 iidir = 0; iidir < 100; iidir++) {\n            sprintf(tfile, \"%s/t%02d/sph_t%04d_p%06d_i%06d.dat\", idir, iidir, itime,\n                    PS::Comm::getNumberOfProc(), 0);\n            fp = fopen(tfile, \"r\");\n            if(fp != NULL) {\n                tdir = iidir;\n                break;\n            }\n        }\n        if(fp == NULL) {\n            if(PS::Comm::getRank() == 0) {\n                fprintf(stderr, \"Not found %s\\n\", tfile);\n            }\n            continue;\n        }\n        fclose(fp);\n\n        char sfile[1024];\n        sprintf(sfile, \"%s/t%02d/sph_t%04d\", idir, tdir, itime);\n        sph.readParticleAscii(sfile, \"%s_p%06d_i%06d.dat\");\n\n        char ofile[1024];\n        sprintf(ofile, \"%s/anim_%04d.dat\", odir, itime);\n        projectOnPlane(ofile, plane, sph);\n    }\n\n    PS::Finalize();\n\n    return 0;\n}\n", "meta": {"hexsha": "f02b3c60f3f094eeec70d7bc699677a5c95c9629", "size": 11170, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tool.anim/remnant/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.anim/remnant/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.anim/remnant/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.6445783133, "max_line_length": 110, "alphanum_fraction": 0.4856759176, "num_tokens": 3826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2609523809432667}}
{"text": "#include <GL/freeglut.h>\n#include <vector>\n#include <Eigen/Eigen>\n#include <iostream>\n#include <iomanip>\n\n#include \"../../example_func_xy_jacobian.h\"\n#include \"../../constraints_jacobian.h\"\n\n#define RENDER_PSI 0\n#define RENDER_OBJECTIVE_FUNC 1\n#define RENDER_OBJECTIVE_FUNC_WITH_CONTRAINT 2\n\nint render_type = RENDER_PSI;\n\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 = -20.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\ndouble x_result = 5;\ndouble y_result = 5;\n\ndouble psi_trg = 0.99;\n\nstd::vector<std::pair<double, double>> path_result;\ndouble contraint_a = 1;\ndouble contraint_x_trg = 0;\ndouble contraint_y_trg = 0;\ndouble weight_constraint = 1;\nint constraint_type = 0;\ndouble angle_heading = 0;\ndouble update_scale = 1.0;\ndouble w_longitudal_motion = 0.01;\n\nvoid obs_eq_constraint(double &delta, double a, double x, double x_trg, int type)\n{\n\tif(type == 0){\n\t\tobservation_equation_constraint(delta, a, x, x_trg);\n\t}else{\n\t\tobservation_equation_sq_constraint(delta, a, x, x_trg);\n\t}\n}\nvoid obs_eq_constraint_jacobian(Eigen::Matrix<double, 1, 1> &j, double a, double x, double x_trg, int type)\n{\n\tif(type == 0){\n\t\tobservation_equation_constraint_jacobian(j, a, x, x_trg);\n\t}else{\n\t\tobservation_equation_sq_constraint_jacobian(j, a, x, x_trg);\n\t}\n}\n\nint main(int argc, char *argv[]){\n\tpath_result.emplace_back(x_result, y_result);\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(\"simple_optimization_problem_func_xy_with_constraints\");\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\tglLineWidth(1);\n\n\t/*glBegin(GL_LINES);\n\tglColor3f(1.0f, 0.0f, 0.0f);\n\tglVertex3f(0.0f, 0.0f, 0.0f);\n\tglVertex3f(100.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, 100.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, 100.0f);\n\tglEnd();*/\n\n\tfloat scale = 10;\n\tswitch(render_type){\n\t\tcase RENDER_PSI:{\n\t\t\tglColor3f(1,0,0);\n\n\t\t\tfloat step = 0.1;\n\t\t\tfor(double x = -10; x <=10; x+=step){\n\t\t\t\tfor(double y = -10; y <=10; y+=step){\n\t\t\t\t\tdouble psi1;\n\t\t\t\t\texample_func_xy(psi1, x, y);\n\n\t\t\t\t\tdouble psi2;\n\t\t\t\t\texample_func_xy(psi2, x+step, y);\n\n\t\t\t\t\tdouble psi3;\n\t\t\t\t\texample_func_xy(psi3, x+step, y+step);\n\n\t\t\t\t\tdouble psi4;\n\t\t\t\t\texample_func_xy(psi4, x, y+step);\n\n\t\t\t\t\tglColor3f(psi1,1-psi1,0);\n\t\t\t\t\tglBegin(GL_LINE_STRIP);\n\t\t\t\t\t\tglVertex3f(x,y,psi1*scale);\n\t\t\t\t\t\tglVertex3f(x+step,y,psi2*scale);\n\t\t\t\t\t\tglVertex3f(x+step,y+step,psi3*scale);\n\t\t\t\t\t\tglVertex3f(x,y+step,psi4*scale);\n\t\t\t\t\t\tglVertex3f(x,y,psi1*scale);\n\t\t\t\t\tglEnd();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tglPointSize(20);\n\t\t\tglColor3f(0,0,1);\n\t\t\tglBegin(GL_POINTS);\n\t\t\t\tdouble psi;\n\t\t\t\texample_func_xy(psi,x_result,y_result);\n\t\t\t\tglVertex3f(x_result, y_result, psi*scale);\n\t\t\tglEnd();\n\t\t\tglPointSize(1);\n\n\t\t\t//heading\n\t\t\tglLineWidth(3);\n\t\t\tEigen::Affine2d m_rot = Eigen::Affine2d::Identity();\n\n\t\t\tdouble angle_rad = angle_heading * M_PI/180.0;\n\t\t\tdouble sh = sin(angle_rad);\n\t\t\tdouble ch = cos(angle_rad);\n\n\t\t\tm_rot(0,0) = ch;\n\t\t\tm_rot(1,0) = sh;\n\n\t\t\tm_rot(0,1) = -sh;\n\t\t\tm_rot(1,1) =  ch;\n\n\t\t\tglColor3f(0.1,0.5,0.6);\n\t\t\tglBegin(GL_LINES);\n\t\t\t\tEigen::Vector2d v(1,0);\n\t\t\t\tEigen::Vector2d vt = m_rot * v;\n\t\t\t\texample_func_xy(psi,x_result,y_result);\n\t\t\t\tglVertex3f(x_result, y_result, psi*scale);\n\t\t\t\tglVertex3f(x_result + vt.x(), y_result + vt.y(), psi*scale);\n\t\t\tglEnd();\n\t\t\tglLineWidth(1);\n\n\n\n\t\t\tglLineWidth(2);\n\t\t\tglColor3f(0,0,1);\n\t\t\tglBegin(GL_LINE_STRIP);\n\t\t\tfor(const auto &p:path_result){\n\t\t\t\tdouble psi;\n\t\t\t\texample_func_xy(psi,p.first,p.second);\n\t\t\t\tglVertex3f(p.first,p.second, psi*scale);\n\t\t\t}\n\t\t\tglEnd();\n\t\t\tglLineWidth(1);\n\n\t\t\tglColor3f(0,0,0);\n\t\t\tglBegin(GL_LINES);\n\t\t\tfor(float x = -10; x <= 10; x+=1){\n\t\t\t\tglVertex3f(-10, x, psi_trg*scale);\n\t\t\t\tglVertex3f(10, x, psi_trg*scale);\n\n\t\t\t\tglVertex3f(x, -10, psi_trg*scale);\n\t\t\t\tglVertex3f(x, 10, psi_trg*scale);\n\t\t\t}\n\t\t\tglEnd();\n\t\tbreak;\n\t\t}\n\t\tcase RENDER_OBJECTIVE_FUNC:{\n\n\t\t\tglColor3f(1,0,0);\n\t\t\tfloat step = 0.1;\n\t\t\tfor(double x = -10; x <=10; x+=step){\n\t\t\t\tfor(double y = -10; y <=10; y+=step){\n\t\t\t\t\tdouble psi;\n\t\t\t\t\texample_func_xy(psi, x, y);\n\t\t\t\t\tglColor3f(psi,1-psi,0);\n\n\t\t\t\t\tglBegin(GL_LINE_STRIP);\n\t\t\t\t\t    double psi1;\n\t\t\t\t\t\tobservation_equation_example_func_xy(psi1, x, y, psi_trg);\n\n\t\t\t\t\t\tdouble psi2;\n\t\t\t\t\t\tobservation_equation_example_func_xy(psi2, x+step, y, psi_trg);\n\n\t\t\t\t\t\tdouble psi3;\n\t\t\t\t\t\tobservation_equation_example_func_xy(psi3, x+step, y+step, psi_trg);\n\n\t\t\t\t\t\tdouble psi4;\n\t\t\t\t\t\tobservation_equation_example_func_xy(psi4, x, y+step, psi_trg);\n\n\t\t\t\t\t\tglVertex3f(x,y,           psi1*psi1*scale);\n\t\t\t\t\t\tglVertex3f(x+step,y,      psi2*psi2*scale);\n\t\t\t\t\t\tglVertex3f(x+step,y+step, psi3*psi3*scale);\n\t\t\t\t\t\tglVertex3f(x,y+step,      psi4*psi4*scale);\n\t\t\t\t\t\tglVertex3f(x,y,           psi1*psi1*scale);\n\t\t\t\t\tglEnd();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor(double x = -10; x <=10; x+=step){\n\t\t\t\tfor(double y = -10; y <=10; y+=step){\n\t\t\t\t\tdouble cx_delta1;\n\t\t\t\t\tobs_eq_constraint(cx_delta1, contraint_a, x, contraint_x_trg, constraint_type);\n\n\t\t\t\t\tdouble cy_delta1;\n\t\t\t\t\tobs_eq_constraint(cy_delta1, contraint_a, y, contraint_y_trg, constraint_type);\n\n\t\t\t\t\tdouble cx_delta2;\n\t\t\t\t\tobs_eq_constraint(cx_delta2, contraint_a, x+step, contraint_x_trg, constraint_type);\n\n\t\t\t\t\tdouble cy_delta2;\n\t\t\t\t\tobs_eq_constraint(cy_delta2, contraint_a, y, contraint_y_trg, constraint_type);\n\n\t\t\t\t\tdouble cx_delta3;\n\t\t\t\t\tobs_eq_constraint(cx_delta3, contraint_a, x+step, contraint_x_trg, constraint_type);\n\n\t\t\t\t\tdouble cy_delta3;\n\t\t\t\t\tobs_eq_constraint(cy_delta3, contraint_a, y+step, contraint_y_trg, constraint_type);\n\n\t\t\t\t\tdouble cx_delta4;\n\t\t\t\t\tobs_eq_constraint(cx_delta4, contraint_a, x, contraint_x_trg, constraint_type);\n\n\t\t\t\t\tdouble cy_delta4;\n\t\t\t\t\tobs_eq_constraint(cy_delta4, contraint_a, y+step, contraint_y_trg, constraint_type);\n\n\t\t\t\t\tdouble psi;\n\t\t\t\t\texample_func_xy(psi, x, y);\n\t\t\t\t\tglColor3f(psi,1-psi,0);\n\t\t\t\t\tglBegin(GL_LINE_STRIP);\n\t\t\t\t\t\tglVertex3f(x,y,           cx_delta1*cx_delta1 + cy_delta1 * cy_delta1);\n\t\t\t\t\t\tglVertex3f(x+step,y,      cx_delta2*cx_delta2 + cy_delta2 * cy_delta2);\n\t\t\t\t\t\tglVertex3f(x+step,y+step, cx_delta3*cx_delta3 + cy_delta3 * cy_delta3);\n\t\t\t\t\t\tglVertex3f(x,y+step,      cx_delta4*cx_delta4 + cy_delta4 * cy_delta4);\n\t\t\t\t\t\tglVertex3f(x,y,           cx_delta1*cx_delta1 + cy_delta1 * cy_delta1);\n\t\t\t\t\tglEnd();\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t\tglPointSize(20);\n\t\t\tglColor3f(0,0,1);\n\t\t\tglBegin(GL_POINTS);\n\t\t\t\tdouble psi;\n\t\t\t\tobservation_equation_example_func_xy(psi, x_result, y_result, psi_trg);\n\t\t\t\tglVertex3f(x_result, y_result, psi*psi*scale);\n\t\t\tglEnd();\n\t\t\tglPointSize(1);\n\n\t\t\t//heading\n\t\t\tglLineWidth(3);\n\t\t\tEigen::Affine2d m_rot = Eigen::Affine2d::Identity();\n\n\t\t\tdouble angle_rad = angle_heading * M_PI/180.0;\n\t\t\tdouble sh = sin(angle_rad);\n\t\t\tdouble ch = cos(angle_rad);\n\n\t\t\tm_rot(0,0) = ch;\n\t\t\tm_rot(1,0) = sh;\n\n\t\t\tm_rot(0,1) = -sh;\n\t\t\tm_rot(1,1) =  ch;\n\n\t\t\tglColor3f(0.1,0.5,0.6);\n\t\t\tglBegin(GL_LINES);\n\t\t\t\tEigen::Vector2d v(1,0);\n\t\t\t\tEigen::Vector2d vt = m_rot * v;\n\t\t\t\tobservation_equation_example_func_xy(psi, x_result, y_result, psi_trg);\n\t\t\t\tglVertex3f(x_result, y_result, psi*psi*scale);\n\t\t\t\tglVertex3f(x_result + vt.x(), y_result + vt.y(), psi*psi*scale);\n\t\t\tglEnd();\n\t\t\tglLineWidth(1);\n\n\n\t\t\tglLineWidth(2);\n\t\t\tglColor3f(0,0,1);\n\t\t\tglBegin(GL_LINE_STRIP);\n\t\t\tfor(const auto &p:path_result){\n\t\t\t\tdouble psi;\n\t\t\t\tobservation_equation_example_func_xy(psi, p.first, p.second, psi_trg);\n\t\t\t\tglVertex3f(p.first, p.second, psi*psi*scale);\n\t\t\t}\n\t\t\tglEnd();\n\t\t\tglLineWidth(1);\n\t\t\tbreak;\n\t\t}\n\t\tcase RENDER_OBJECTIVE_FUNC_WITH_CONTRAINT:{\n\t\t\tglColor3f(1,0,0);\n\t\t\tfloat step = 0.1;\n\t\t\tfor(double x = -10; x <=10; x+=step){\n\t\t\t\tfor(double y = -10; y <=10; y+=step){\n\t\t\t\t\tdouble delta1;\n\t\t\t\t\tobservation_equation_example_func_xy(delta1, x, y, psi_trg);\n\n\t\t\t\t\tdouble cx_delta1;\n\t\t\t\t\tobs_eq_constraint(cx_delta1, contraint_a, x, contraint_x_trg, constraint_type);\n\n\t\t\t\t\tdouble cy_delta1;\n\t\t\t\t\tobs_eq_constraint(cy_delta1, contraint_a, y, contraint_y_trg, constraint_type);\n\n\t\t\t\t\tdouble delta2;\n\t\t\t\t\tobservation_equation_example_func_xy(delta2, x+step, y, psi_trg);\n\n\t\t\t\t\tdouble cx_delta2;\n\t\t\t\t\tobs_eq_constraint(cx_delta2, contraint_a, x+step, contraint_x_trg, constraint_type);\n\n\t\t\t\t\tdouble cy_delta2;\n\t\t\t\t\tobs_eq_constraint(cy_delta2, contraint_a, y, contraint_y_trg, constraint_type);\n\n\t\t\t\t\tdouble delta3;\n\t\t\t\t\tobservation_equation_example_func_xy(delta3, x+step, y+step, psi_trg);\n\n\t\t\t\t\tdouble cx_delta3;\n\t\t\t\t\tobs_eq_constraint(cx_delta3, contraint_a, x+step, contraint_x_trg, constraint_type);\n\n\t\t\t\t\tdouble cy_delta3;\n\t\t\t\t\tobs_eq_constraint(cy_delta3, contraint_a, y+step, contraint_y_trg, constraint_type);\n\n\t\t\t\t\tdouble delta4;\n\t\t\t\t\tobservation_equation_example_func_xy(delta4, x, y+step, psi_trg);\n\n\t\t\t\t\tdouble cx_delta4;\n\t\t\t\t\tobs_eq_constraint(cx_delta4, contraint_a, x, contraint_x_trg, constraint_type);\n\n\t\t\t\t\tdouble cy_delta4;\n\t\t\t\t\tobs_eq_constraint(cy_delta4, contraint_a, y+step, contraint_y_trg, constraint_type);\n\n\t\t\t\t\tdouble psi;\n\t\t\t\t\texample_func_xy(psi, x, y);\n\t\t\t\t\tglColor3f(psi,1-psi,0);\n\t\t\t\t\tglBegin(GL_LINE_STRIP);\n\t\t\t\t\t\tglVertex3f(x,y,           delta1*delta1 + cx_delta1*cx_delta1 + cy_delta1 * cy_delta1);\n\t\t\t\t\t\tglVertex3f(x+step,y,      delta2*delta2 + cx_delta2*cx_delta2 + cy_delta2 * cy_delta2);\n\t\t\t\t\t\tglVertex3f(x+step,y+step, delta3*delta3 + cx_delta3*cx_delta3 + cy_delta3 * cy_delta3);\n\t\t\t\t\t\tglVertex3f(x,y+step,      delta4*delta4 + cx_delta4*cx_delta4 + cy_delta4 * cy_delta4);\n\t\t\t\t\t\tglVertex3f(x,y,           delta1*delta1 + cx_delta1*cx_delta1 + cy_delta1 * cy_delta1);\n\t\t\t\t\tglEnd();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tglPointSize(20);\n\t\t\tglColor3f(0,0,1);\n\t\t\tglBegin(GL_POINTS);\n\t\t\t\tdouble delta;\n\t\t\t\tobservation_equation_example_func_xy(delta, x_result, y_result, psi_trg);\n\n\t\t\t\tdouble cx_delta;\n\t\t\t\tobs_eq_constraint(cx_delta, contraint_a, x_result, contraint_x_trg, constraint_type);\n\n\t\t\t\tdouble cy_delta;\n\t\t\t\tobs_eq_constraint(cy_delta, contraint_a, y_result, contraint_y_trg, constraint_type);\n\n\n\t\t\t\tglVertex3f(x_result, y_result, delta*delta + cx_delta * cx_delta + cy_delta * cy_delta);\n\t\t\tglEnd();\n\t\t\tglPointSize(1);\n\n\t\t\t//heading\n\t\t\tglLineWidth(3);\n\t\t\tEigen::Affine2d m_rot = Eigen::Affine2d::Identity();\n\n\t\t\tdouble angle_rad = angle_heading * M_PI/180.0;\n\t\t\tdouble sh = sin(angle_rad);\n\t\t\tdouble ch = cos(angle_rad);\n\n\t\t\tm_rot(0,0) = ch;\n\t\t\tm_rot(1,0) = sh;\n\n\t\t\tm_rot(0,1) = -sh;\n\t\t\tm_rot(1,1) =  ch;\n\n\t\t\tglColor3f(0.1,0.5,0.6);\n\t\t\tglBegin(GL_LINES);\n\t\t\t\tobservation_equation_example_func_xy(delta, x_result, y_result, psi_trg);\n\t\t\t\tobs_eq_constraint(cx_delta, contraint_a, x_result, contraint_x_trg, constraint_type);\n\t\t\t\tobs_eq_constraint(cy_delta, contraint_a, y_result, contraint_y_trg, constraint_type);\n\n\t\t\t\tEigen::Vector2d v(1,0);\n\t\t\t\tEigen::Vector2d vt = m_rot * v;\n\n\t\t\t\tglVertex3f(x_result, y_result, delta*delta + cx_delta * cx_delta + cy_delta * cy_delta);\n\t\t\t\tglVertex3f(x_result+vt.x(), y_result+vt.y(), delta*delta + cx_delta * cx_delta + cy_delta * cy_delta);\n\t\t\tglEnd();\n\t\t\tglLineWidth(1);\n\n\t\t\tglLineWidth(2);\n\t\t\tglColor3f(0,0,1);\n\t\t\tglBegin(GL_LINE_STRIP);\n\t\t\tfor(const auto &p:path_result){\n\t\t\t\tobservation_equation_example_func_xy(delta, p.first, p.second, psi_trg);\n\t\t\t\tobs_eq_constraint(cx_delta, contraint_a, p.first, contraint_x_trg, constraint_type);\n\t\t\t\tobs_eq_constraint(cy_delta, contraint_a, p.second, contraint_y_trg, constraint_type);\n\n\t\t\t\tglVertex3f(p.first, p.second, delta*delta + cx_delta * cx_delta + cy_delta * cy_delta);\n\t\t\t}\n\t\t\tglEnd();\n\t\t\tglLineWidth(1);\n\t\t\tbreak;\n\t\t}\n\t}\n\tglutSwapBuffers();\n}\n\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 'o':{\n\t\t\tx_result += ((rand()%1000000)/1000000.0f - 0.5) * 2.0 * 0.0001;\n\t\t\ty_result += ((rand()%1000000)/1000000.0f - 0.5) * 2.0 * 0.0001;\n\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\tdouble delta;\n\t\t\tobservation_equation_example_func_xy(delta, x_result, y_result, psi_trg);\n\n\t\t\tEigen::Matrix<double, 1, 2> jacobian;\n\t\t\tobservation_equation_example_func_xy_jacobian(jacobian, x_result, y_result);\n\n\t\t\tif(jacobian(0,0) == 0.0 || jacobian(0,1) == 0.0 || delta == 0){\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tint ir = 0;\n\t\t\tint ic = 0;\n\n\t\t\ttripletListA.emplace_back(ir + 0, ic + 0, -jacobian(0,0));\n\t\t\ttripletListA.emplace_back(ir + 0, ic + 1, -jacobian(0,1));\n\t\t\ttripletListP.emplace_back(ir + 0, ir + 0,  1.0);\n\t\t\ttripletListB.emplace_back(ir + 0, 0,  delta);\n\n\t\t\tic = 0;\n\t\t\tir = tripletListB.size();\n\t\t\ttripletListA.emplace_back(ir, ic,  1);\n\t\t\ttripletListP.emplace_back(ir, ir,  0.000000001);\n\t\t\ttripletListB.emplace_back(ir, 0,  0);\n\n\t\t\tic = 1;\n\t\t\tir = tripletListB.size();\n\t\t\ttripletListA.emplace_back(ir, ic,  1);\n\t\t\ttripletListP.emplace_back(ir, ir,  0.000000001);\n\t\t\ttripletListB.emplace_back(ir, 0,  0);\n\n\t\t\tint number_of_columns = 2;\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), number_of_columns);\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\t\t\tEigen::SparseMatrix<double> AtPA(number_of_columns, number_of_columns);\n\t\t\tEigen::SparseMatrix<double> AtPB(number_of_columns, 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\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\tif(h_x.size() == number_of_columns){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tx_result += h_x[0] * update_scale;\n\t\t\t\ty_result += h_x[1] * update_scale;\n\t\t\t\tpath_result.emplace_back(x_result, y_result);\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'c':{\n\t\t\tx_result += ((rand()%1000000)/1000000.0f - 0.5) * 2.0 * 0.0001;\n\t\t\ty_result += ((rand()%1000000)/1000000.0f - 0.5) * 2.0 * 0.0001;\n\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\tdouble delta;\n\t\t\tobservation_equation_example_func_xy(delta, x_result, y_result, psi_trg);\n\n\t\t\tEigen::Matrix<double, 1, 2> jacobian;\n\t\t\tobservation_equation_example_func_xy_jacobian(jacobian, x_result, y_result);\n\n\t\t\tif(jacobian(0,0) == 0.0 || jacobian(0,1) == 0.0 || delta == 0){\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tint ir = 0;\n\t\t\tint ic = 0;\n\n\t\t\ttripletListA.emplace_back(ir + 0, ic + 0, -jacobian(0,0));\n\t\t\ttripletListA.emplace_back(ir + 0, ic + 1, -jacobian(0,1));\n\t\t\ttripletListP.emplace_back(ir + 0, ir + 0,  1.0);\n\t\t\ttripletListB.emplace_back(ir + 0, 0,  delta);\n\n\t\t\tic = 0;\n\t\t\tir = tripletListB.size();\n\t\t\tdouble c_delta;\n\t\t\tEigen::Matrix<double, 1, 1> c_jacobian;\n\t\t\tobs_eq_constraint(c_delta, contraint_a, x_result, contraint_x_trg, constraint_type);\n\t\t\tobs_eq_constraint_jacobian(c_jacobian, contraint_a, x_result, contraint_x_trg, constraint_type);\n\t\t\ttripletListA.emplace_back(ir, ic,  -c_jacobian(0,0));\n\t\t\ttripletListP.emplace_back(ir, ir,  weight_constraint);\n\t\t\ttripletListB.emplace_back(ir, 0,  c_delta);\n\n\t\t\tic = 1;\n\t\t\tir = tripletListB.size();\n\t\t\tobs_eq_constraint(c_delta, contraint_a, y_result, contraint_y_trg, constraint_type);\n\t\t\tobs_eq_constraint_jacobian(c_jacobian, contraint_a, y_result, contraint_y_trg, constraint_type);\n\t\t\ttripletListA.emplace_back(ir, ic,  -c_jacobian(0,0));\n\t\t\ttripletListP.emplace_back(ir, ir,  weight_constraint);\n\t\t\ttripletListB.emplace_back(ir, 0,  c_delta);\n\n\t\t\tint number_of_columns = 2;\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), number_of_columns);\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\t\t\tEigen::SparseMatrix<double> AtPA(number_of_columns, number_of_columns);\n\t\t\tEigen::SparseMatrix<double> AtPB(number_of_columns, 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\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\tif(h_x.size() == number_of_columns){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tx_result += h_x[0] * update_scale;\n\t\t\t\ty_result += h_x[1] * update_scale;\n\t\t\t\tpath_result.emplace_back(x_result, y_result);\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'z':{\n\t\t\tx_result += ((rand()%1000000)/1000000.0f - 0.5) * 2.0 * 0.0001;\n\t\t\ty_result += ((rand()%1000000)/1000000.0f - 0.5) * 2.0 * 0.0001;\n\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\tdouble delta;\n\t\t\tobservation_equation_example_func_xy(delta, x_result, y_result, psi_trg);\n\n\t\t\tEigen::Matrix<double, 1, 2> jacobian;\n\t\t\tobservation_equation_example_func_xy_jacobian(jacobian, x_result, y_result);\n\n\t\t\tif(jacobian(0,0) == 0.0 || jacobian(0,1) == 0.0 || delta == 0){\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tint ir = 0;\n\t\t\tint ic = 0;\n\n\t\t\ttripletListA.emplace_back(ir + 0, ic + 0, -jacobian(0,0));\n\t\t\ttripletListA.emplace_back(ir + 0, ic + 1, -jacobian(0,1));\n\t\t\ttripletListP.emplace_back(ir + 0, ir + 0,  1.0);\n\t\t\ttripletListB.emplace_back(ir + 0, 0,  delta);\n\n\t\t\t//anizotropic motion weights\n\t\t\tEigen::Matrix2d m_rot = Eigen::Matrix2d::Identity();\n\n\t\t\tdouble angle_rad = angle_heading * M_PI/180.0;\n\t\t\tdouble sh = sin(angle_rad);\n\t\t\tdouble ch = cos(angle_rad);\n\n\t\t\tm_rot(0,0) = ch;\n\t\t\tm_rot(1,0) = sh;\n\n\t\t\tm_rot(0,1) = -sh;\n\t\t\tm_rot(1,1) =  ch;\n\n\t\t\tEigen::Matrix2d m_w = Eigen::Matrix2d::Identity();\n\t\t\tm_w(0,0) = w_longitudal_motion;\n\t\t\tm_w(1,1) = 1;\n\n\t\t\tEigen::Matrix2d m_c = (m_rot*m_w)*m_rot.transpose();\n\n\t\t\tic = 0;\n\t\t\tir = tripletListB.size();\n\t\t\ttripletListA.emplace_back(ir, ic,  1);\n\t\t\ttripletListP.emplace_back(ir, ir,  m_c(0,0));\n\t\t\ttripletListP.emplace_back(ir, ir+1,  m_c(0,1));\n\t\t\ttripletListB.emplace_back(ir, 0,  0);\n\n\t\t\tic = 1;\n\t\t\tir = tripletListB.size();\n\t\t\ttripletListA.emplace_back(ir, ic,  1);\n\t\t\ttripletListP.emplace_back(ir, ir-1,  m_c(1,0));\n\t\t\ttripletListP.emplace_back(ir, ir,  m_c(1,1));\n\t\t\ttripletListB.emplace_back(ir, 0,  0);\n\n\t\t\tint number_of_columns = 2;\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), number_of_columns);\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\t\t\tEigen::SparseMatrix<double> AtPA(number_of_columns, number_of_columns);\n\t\t\tEigen::SparseMatrix<double> AtPB(number_of_columns, 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\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\tif(h_x.size() == number_of_columns){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tx_result += h_x[0] * update_scale;\n\t\t\t\ty_result += h_x[1] * update_scale;\n\t\t\t\tpath_result.emplace_back(x_result, y_result);\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'x':{\n\t\t\tx_result += ((rand()%1000000)/1000000.0f - 0.5) * 2.0 * 0.0001;\n\t\t\ty_result += ((rand()%1000000)/1000000.0f - 0.5) * 2.0 * 0.0001;\n\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\tdouble delta;\n\t\t\tobservation_equation_example_func_xy(delta, x_result, y_result, psi_trg);\n\n\t\t\tEigen::Matrix<double, 1, 2> jacobian;\n\t\t\tobservation_equation_example_func_xy_jacobian(jacobian, x_result, y_result);\n\n\t\t\tif(jacobian(0,0) == 0.0 || jacobian(0,1) == 0.0 || delta == 0){\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tint ir = 0;\n\t\t\tint ic = 0;\n\n\t\t\ttripletListA.emplace_back(ir + 0, ic + 0, -jacobian(0,0));\n\t\t\ttripletListA.emplace_back(ir + 0, ic + 1, -jacobian(0,1));\n\t\t\ttripletListP.emplace_back(ir + 0, ir + 0,  1.0);\n\t\t\ttripletListB.emplace_back(ir + 0, 0,  delta);\n\n\t\t\t//anizotropic motion weights\n\t\t\tEigen::Matrix2d m_rot = Eigen::Matrix2d::Identity();\n\n\t\t\tdouble angle_rad = angle_heading * M_PI/180.0;\n\t\t\tdouble sh = sin(angle_rad);\n\t\t\tdouble ch = cos(angle_rad);\n\n\t\t\tm_rot(0,0) = ch;\n\t\t\tm_rot(1,0) = sh;\n\n\t\t\tm_rot(0,1) = -sh;\n\t\t\tm_rot(1,1) =  ch;\n\n\t\t\tEigen::Matrix2d m_w = Eigen::Matrix2d::Identity();\n\t\t\tm_w(0,0) = w_longitudal_motion;\n\t\t\tm_w(1,1) = 1;\n\n\t\t\tEigen::Matrix2d m_c = (m_rot*m_w)*m_rot.transpose();\n\n\t\t\tic = 0;\n\t\t\tir = tripletListB.size();\n\t\t\ttripletListA.emplace_back(ir, ic,  1);\n\t\t\ttripletListP.emplace_back(ir, ir,  m_c(0,0));\n\t\t\ttripletListP.emplace_back(ir, ir+1,  m_c(0,1));\n\t\t\ttripletListB.emplace_back(ir, 0,  0);\n\n\t\t\tic = 1;\n\t\t\tir = tripletListB.size();\n\t\t\ttripletListA.emplace_back(ir, ic,  1);\n\t\t\ttripletListP.emplace_back(ir, ir-1,  m_c(1,0));\n\t\t\ttripletListP.emplace_back(ir, ir,  m_c(1,1));\n\t\t\ttripletListB.emplace_back(ir, 0,  0);\n\n\t\t\tic = 0;\n\t\t\tir = tripletListB.size();\n\t\t\tdouble c_delta;\n\t\t\tEigen::Matrix<double, 1, 1> c_jacobian;\n\t\t\tobs_eq_constraint(c_delta, contraint_a, x_result, contraint_x_trg, constraint_type);\n\t\t\tobs_eq_constraint_jacobian(c_jacobian, contraint_a, x_result, contraint_x_trg, constraint_type);\n\t\t\ttripletListA.emplace_back(ir, ic,  -c_jacobian(0,0));\n\t\t\ttripletListP.emplace_back(ir, ir,  weight_constraint);\n\t\t\ttripletListB.emplace_back(ir, 0,  c_delta);\n\n\t\t\tic = 1;\n\t\t\tir = tripletListB.size();\n\t\t\tobs_eq_constraint(c_delta, contraint_a, y_result, contraint_y_trg, constraint_type);\n\t\t\tobs_eq_constraint_jacobian(c_jacobian, contraint_a, y_result, contraint_y_trg, constraint_type);\n\t\t\ttripletListA.emplace_back(ir, ic,  -c_jacobian(0,0));\n\t\t\ttripletListP.emplace_back(ir, ir,  weight_constraint);\n\t\t\ttripletListB.emplace_back(ir, 0,  c_delta);\n\n\t\t\tint number_of_columns = 2;\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), number_of_columns);\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\t\t\tEigen::SparseMatrix<double> AtPA(number_of_columns, number_of_columns);\n\t\t\tEigen::SparseMatrix<double> AtPB(number_of_columns, 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\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\tif(h_x.size() == number_of_columns){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tx_result += h_x[0] * update_scale;\n\t\t\t\ty_result += h_x[1] * update_scale;\n\t\t\t\tpath_result.emplace_back(x_result, y_result);\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'r':{\n\t\t\tx_result = ((rand()%1000000)/1000000.0f - 0.5) * 2.0 * 10;\n\t\t\ty_result = ((rand()%1000000)/1000000.0f - 0.5) * 2.0 * 10;\n\t\t\tpath_result.clear();\n\t\t\tpath_result.emplace_back(x_result, y_result);\n\t\t\tbreak;\n\t\t}\n\t\tcase '-':{\n\t\t\tcontraint_a -= 0.01;\n\t\t\tif(contraint_a < 0)contraint_a= 0.01;\n\t\t\tbreak;\n\t\t}\n\t\tcase '=':{\n\t\t\tcontraint_a += 0.01;\n\t\t\tbreak;\n\t\t}\n\t\tcase 'd':{\n\t\t\tcontraint_x_trg -= 0.1;\n\t\t\tbreak;\n\t\t}\n\t\tcase 'i':{\n\t\t\tcontraint_x_trg += 0.1;\n\t\t\tbreak;\n\t\t}\n\t\tcase 'f':{\n\t\t\tcontraint_y_trg -= 0.1;\n\t\t\tbreak;\n\t\t}\n\t\tcase 'g':{\n\t\t\tcontraint_y_trg += 0.1;\n\t\t\tbreak;\n\t\t}\n\t\tcase '1':{\n\t\t\trender_type = RENDER_PSI;\n\t\t\tbreak;\n\t\t}\n\t\tcase '2':{\n\t\t\trender_type = RENDER_OBJECTIVE_FUNC;\n\t\t\tbreak;\n\t\t}\n\t\tcase '3':{\n\t\t\trender_type = RENDER_OBJECTIVE_FUNC_WITH_CONTRAINT;\n\t\t\tbreak;\n\t\t}\n\t\tcase 'y':{\n\t\t\tpsi_trg += 0.01;\n\t\t\tstd::cout << \"psi_trg: \" << psi_trg << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase 't':{\n\t\t\tpsi_trg -= 0.01;\n\t\t\tstd::cout << \"psi_trg: \" << psi_trg << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase 'q':{\n\t\t\tx_result-=0.1;\n\t\t\tpath_result.clear();\n\t\t\tpath_result.emplace_back(x_result, y_result);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'w':{\n\t\t\tx_result+=0.1;\n\t\t\tpath_result.clear();\n\t\t\tpath_result.emplace_back(x_result, y_result);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'a':{\n\t\t\ty_result-=0.1;\n\t\t\tpath_result.clear();\n\t\t\tpath_result.emplace_back(x_result, y_result);\n\t\t\tbreak;\n\t\t}\n\t\tcase 's':{\n\t\t\ty_result+=0.1;\n\t\t\tpath_result.clear();\n\t\t\tpath_result.emplace_back(x_result, y_result);\n\t\t\tbreak;\n\t\t}\n\t\tcase '4':{\n\t\t\tconstraint_type = 0;\n\t\t\tbreak;\n\t\t}\n\t\tcase '5':{\n\t\t\tconstraint_type = 1;\n\t\t\tbreak;\n\t\t}\n\t\tcase '6':{\n\t\t\tweight_constraint /=10;\n\t\t\tstd::cout << \"weight_constraint: \" << weight_constraint << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase '7':{\n\t\t\tweight_constraint *=10;\n\t\t\tstd::cout << \"weight_constraint: \" << weight_constraint << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase '8':{\n\t\t\tangle_heading += 1;\n\t\t\tbreak;\n\t\t}\n\t\tcase '9':{\n\t\t\tangle_heading -= 1;\n\t\t\tbreak;\n\t\t}\n\t\tcase '[':{\n\t\t\tupdate_scale -= 0.01;\n\t\t\tif(update_scale <= 0) update_scale = 0.01;\n\t\t\tstd::cout << \"update_scale: \" << update_scale << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase ']':{\n\t\t\tupdate_scale += 0.01;\n\t\t\tstd::cout << \"update_scale: \" << update_scale << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase 'k':{\n\t\t\tw_longitudal_motion *= 10;\n\t\t\tstd::cout << \"w_longitudal_motion: \" << w_longitudal_motion << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase 'l':{\n\t\t\tw_longitudal_motion /= 10;\n\t\t\tstd::cout << \"w_longitudal_motion: \" << w_longitudal_motion << std::endl;\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 << \"o: optimize\" << std::endl;\n\tstd::cout << \"c: optimize with constaint\" << std::endl;\n\tstd::cout << \"z: optimize with anizotropic motion constaint\" << std::endl;\n\tstd::cout << \"x: optimize with constaint and anizotropic motion constaint\" << std::endl;\n\tstd::cout << \"-: contraint_a -= 0.01\" << std::endl;\n\tstd::cout << \"=: contraint_a += 0.01\" << std::endl;\n\tstd::cout << \"d: contraint_x_trg -= 0.1\" << std::endl;\n\tstd::cout << \"i: contraint_x_trg += 0.1\" << std::endl;\n\tstd::cout << \"f: contraint_y_trg -= 0.1\" << std::endl;\n\tstd::cout << \"g: contraint_y_trg += 0.1\" << std::endl;\n\tstd::cout << \"1: RENDER_PSI\" << std::endl;\n\tstd::cout << \"2: RENDER_OBJECTIVE_FUNC\" << std::endl;\n\tstd::cout << \"3: RENDER_OBJECTIVE_FUNC_WITH_CONTRAINT\" << std::endl;\n\tstd::cout << \"y: psi_trg += 0.01\" << std::endl;\n\tstd::cout << \"t: psi_trg -= 0.01\" << std::endl;\n\tstd::cout << \"q: x_result-=0.1\" << std::endl;\n\tstd::cout << \"w: x_result+=0.1\" << std::endl;\n\tstd::cout << \"a: y_result-=0.1\" << std::endl;\n\tstd::cout << \"s: y_result+=0.1\" << std::endl;\n\tstd::cout << \"4: constraint_type linear\" << std::endl;\n\tstd::cout << \"5: constraint_type squared\" << std::endl;\n\tstd::cout << \"6: weight_constraint /=10\" << std::endl;\n\tstd::cout << \"7: weight_constraint *=10\" << std::endl;\n\tstd::cout << \"8: angle_heading += 1\" << std::endl;\n\tstd::cout << \"9: angle_heading -= 1\" << std::endl;\n\tstd::cout << \"[: pdate_scale -= 0.01\" << std::endl;\n\tstd::cout << \"]: pdate_scale += 0.01\" << std::endl;\n\tstd::cout << \"k: w_longitudal_motion *= 10\" << std::endl;\n\tstd::cout << \"l: w_longitudal_motion /= 10\" << std::endl;\n\tstd::cout << \"r: random initial guess\" << std::endl;\n}\n\n\n\n\n\n\n\n", "meta": {"hexsha": "e18fca5b15603397dd938936b62649768f9002be", "size": 31928, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "codes/c++Examples/src/simple_optimization_problem_func_xy_with_constraints.cpp", "max_stars_repo_name": "michalpelka/observation_equations", "max_stars_repo_head_hexsha": "023ba4cd57d738447ed118279fdb4c06ae5746f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "codes/c++Examples/src/simple_optimization_problem_func_xy_with_constraints.cpp", "max_issues_repo_name": "michalpelka/observation_equations", "max_issues_repo_head_hexsha": "023ba4cd57d738447ed118279fdb4c06ae5746f8", "max_issues_repo_licenses": ["MIT"], "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/simple_optimization_problem_func_xy_with_constraints.cpp", "max_forks_repo_name": "michalpelka/observation_equations", "max_forks_repo_head_hexsha": "023ba4cd57d738447ed118279fdb4c06ae5746f8", "max_forks_repo_licenses": ["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.0783242259, "max_line_length": 107, "alphanum_fraction": 0.6547544475, "num_tokens": 10728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2608342326594719}}
{"text": "#include <iostream>\n#include <iomanip>\n#include \"PSMoveController.h\"\n#include \"ServerLog.h\"\n#include \"PSEyeVideoCapture.h\"\n#include \"opencv2/opencv.hpp\"\n#include <algorithm>\n#include <Eigen/Dense>\n\n#ifndef HAVE_M_PI\n#ifndef M_PI\n#define M_PI    3.14159265358979323846264338327950288   /* pi */\n#endif\n#endif\n\nconst int HUE_RANGE = 25;\nconst int SAT_RANGE = 50;\nconst int VAL_RANGE = 32;\n\ntypedef cv::Vec< unsigned char, 3 > cvBGR;\ntypedef cv::Vec< unsigned char, 3 > cvRGB;\ntypedef cv::Vec< unsigned char, 3 > cvHSV;\n\ncvHSV\nbgr2hsv(cvBGR bgr_in)\n{\n    static cv::Mat img_bgr(1, 1, CV_8UC3, bgr_in);\n    static cv::Mat img_hsv(1, 1, CV_8UC3);\n    cv::cvtColor(img_bgr, img_hsv, CV_BGR2HSV);\n    return img_hsv.at<cvHSV>(0, 0);\n}\n\nvoid hsv_range(cvHSV hsv_in, cvHSV& min_out, cvHSV& max_out)\n{\n    min_out.val[0] = MAX(hsv_in.val[0] - HUE_RANGE, 0);  //0-180\n    min_out.val[1] = MAX(hsv_in.val[1] - SAT_RANGE, 0);  //0-255\n    min_out.val[2] = MAX(hsv_in.val[2] - VAL_RANGE, 0);  //0-255\n    \n    max_out.val[0] = MIN(hsv_in.val[0] + HUE_RANGE, 180);\n    max_out.val[1] = MIN(hsv_in.val[1] + SAT_RANGE, 255);\n    max_out.val[2] = MIN(hsv_in.val[2] + VAL_RANGE, 255);\n}\n\nvoid onMouse(int evt, int x, int y, int flags, void* param) {\n    if(evt == CV_EVENT_LBUTTONDOWN) {\n        cv::Point *ptPtr = (cv::Point*)param;\n        *ptPtr = cv::Point(x, y);\n    }\n}\n\nint main()\n{\n    log_init(\"info\");\n\n    if (hid_init() == -1)\n    {\n        std::cerr << \"Failed to initialize hidapi\" << std::endl;\n        return -1;\n    }\n    \n    PSMoveController psmove;\n    PSEyeVideoCapture cap(0); // open the default camera\n    cv::namedWindow(\"bgr video\");\n    cv::namedWindow(\"hsv video\");\n    cv::namedWindow(\"result\");\n    \n    cv::Point clickPoint;\n    cv::setMouseCallback(\"hsv video\", onMouse, (void*)&clickPoint);\n\n\tstd::cout << \"Opening PSMoveController...\" << std::endl;\n\tif (psmove.open() && cap.isOpened())\n\t{\n        const PSMoveControllerState *psmstate= nullptr;\n\n        cap.set(cv::CAP_PROP_EXPOSURE, 16);\n        cap.set(cv::CAP_PROP_GAIN, 64);\n\n        psmove.poll();\n        psmstate= static_cast<const PSMoveControllerState *>(psmove.getState());\n\n\t\tunsigned char r = 255;\n\t\tunsigned char g = 0;\n\t\tunsigned char b = 255;\n        psmove.setLED(r, g, b);\n        psmove.setRumbleIntensity(0);\n        \n        cv::Mat bgrFrame;\n        cv::Mat hsvFrame;\n        cv::Mat intGsFrame;\n        cv::Mat gsFrame;\n        cvHSV led_min, led_max;\n        cvHSV psmoveHSVColour = bgr2hsv(cvBGR(b, g, r));\n        \n        // HACK FOR TESTING\n        psmoveHSVColour = cvHSV(140, 25, 255);\n        \n        hsv_range(psmoveHSVColour, led_min, led_max);\n        \n\n\t\twhile (psmove.getIsBluetooth() && psmstate->Move != CommonControllerState::Button_DOWN)\n\t\t{\n            psmove.poll();\n            psmstate= static_cast<const PSMoveControllerState *>(psmove.getState());\n            \n            psmove.setLED(r, g, b); // TODO: Rate-limit LED update\n\n            cap >> bgrFrame; // get a new frame from camera\n            \n            if (!bgrFrame.empty())\n            {\n                cv::cvtColor(bgrFrame, hsvFrame, CV_BGR2HSV);       // Convert frame to HSV colour space\n                cv::inRange(hsvFrame, led_min, led_max, gsFrame);  // Filter based on led HSV range\n                \n//                cv::GaussianBlur(intGsFrame, gsFrame, cv::Size(3, 3), 0);\n//                cv::blur(intGsFrame, gsFrame, cv::Size(3, 3));  // Fastest\n//                cv::bilateralFilter(intGsFrame, gsFrame, 3, 6.0, 1.5);  // Preserves edges\n                \n                imshow(\"result\", gsFrame);\n                \n//                if (clickPoint.x > 0)\n//                {\n//                    cvHSV hsv_bulb = hsvFrame.at<cvHSV>(clickPoint);\n//                    std::cout << clickPoint << \";\" << hsv_bulb << std::endl;\n//                }\n                \n                std::vector<std::vector<cv::Point> > contours;\n                cv::findContours(gsFrame, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);\n                \n                cv::Scalar contCol = cv::Scalar( 255, 0, 0 );\n                for (int i=0; i<contours.size(); ++i) {\n                    cv::drawContours(bgrFrame, contours, i, contCol);\n                }\n\n                std::vector<cv::Point> biggest_contour;\n                if (contours.size() > 0)\n                {\n                    double contArea = 0;\n                    double newArea = 0;\n                    for (auto it = contours.begin(); it != contours.end(); ++it) {\n                        newArea = cv::contourArea(*it);\n                        if (newArea > contArea)\n                        {\n                            contArea = newArea;\n                            biggest_contour = *it;\n                        }\n                    }\n                }\n                \n                //TODO: If our contour is suddenly much smaller than last frame,\n                // but is next to an almost-as-big contour, then maybe these\n                // 2 contours should be joined.\n                // (i.e. if a finger is blocking the middle of the bulb)\n\n                if (biggest_contour.size() > 6)\n                {\n                    // Remove any points in contour on edge of camera/ROI\n                    std::vector<cv::Point>::iterator it = biggest_contour.begin();\n                    while (it != biggest_contour.end()) {\n                        if (it->x == 320 || it->x == -320 || it->y == 240 || it->y == -240) {\n                            it = biggest_contour.erase(it);\n                        }\n                        else {\n                            ++it;\n                        }\n                    }\n\n                    // Get the convex hull\n                    std::vector<cv::Point> hull;\n                    cv::convexHull(biggest_contour, hull);\n                    \n\n//                    // If our hull has lots of points, select the N consecutive\n//                    // points that are furthest, because furthest are least\n//                    // likely to be occluded (assuming player is near middle of FOV).\n//                    int N = 10;\n//                    if (hull.size() > N)\n//                    {\n//                        std::deque<float> dists;\n//                        float max_dist = 0;\n//                        float sum_dists = 0;\n//                        int best_i = 0;\n//                        for (int i=0; i < (hull.size()-N); i++) {\n//                            float new_dist = hull[i].x*hull[i].x + hull[i].y*hull[i].y;\n//                            sum_dists += new_dist;\n//                            dists.push_back(new_dist);\n//                            if (i >= N)\n//                            {\n//                                sum_dists -= dists.front();\n//                                dists.pop_front();\n//                                if (sum_dists > max_dist)\n//                                {\n//                                    best_i = i;\n//                                    max_dist = sum_dists;\n//                                }\n//                            }\n//                        }\n//                        hull = std::vector<cv::Point>(&hull[best_i], &hull[best_i+N]);\n//                    }\n                    \n                    {\n                        std::vector< std::vector<cv::Point> > contours;\n                        \n                        contours.push_back(hull);\n                        cv::drawContours(bgrFrame, contours, 0, cv::Scalar(255, 0, 255));\n                    }\n\n                    \n                    // Fit ellipse to reduced hull\n                    \n                    // Subtract midpoint from each point.\n                    std::for_each(hull.begin(), hull.end(), [](cv::Point& p) { p.x -= 320; p.y = 240 - p.y;});\n                    \n                    \n                    \n                    if (hull.size() > 5)\n                    {\n                        // http://autotrace.sourceforge.net/WSCG98.pdf\n                        std::vector<float> conic_params(6);\n                        \n                        Eigen::MatrixXf D1(hull.size(), 3);\n                        Eigen::MatrixXf D2(hull.size(), 3);\n                        for (int ix=0; ix < hull.size(); ++ix) {\n                            D1.row(ix)[0] = hull[ix].x * hull[ix].x;\n                            D1.row(ix)[1] = hull[ix].x * hull[ix].y;\n                            D1.row(ix)[2] = hull[ix].y * hull[ix].y;\n                            D2.row(ix)[0] = hull[ix].x;\n                            D2.row(ix)[1] = hull[ix].y;\n                            D2.row(ix)[2] = 1;\n                        }\n                        // std::cout << \"\\n\\n\\n\\n\" << hull << \"\\n\\n\\n\\n\" << std::endl;\n                        Eigen::Matrix3f S1 = D1.transpose() * D1;\n                        Eigen::Matrix3f S2 = D1.transpose() * D2;\n                        Eigen::Matrix3f S3 = D2.transpose() * D2;\n                        Eigen::Matrix3f T = -S3.colPivHouseholderQr().solve(S2.transpose());\n//                        Eigen::Matrix3f T = -S3.inverse() * S2.transpose();\n                        Eigen::Matrix3f M = S2*T + S1;\n                        Eigen::Matrix3f Mout;\n                        Mout.block<1, 3>(0, 0) = M.block<1, 3>(2, 0) / 2;\n                        Mout.block<1, 3>(1, 0) = -M.block<1, 3>(1, 0);\n                        Mout.block<1, 3>(2, 0) = M.block<1, 3>(0, 0) / 2;\n                        Eigen::EigenSolver<Eigen::Matrix3f> eigsolv(Mout);\n                        for (int row_ix=0; row_ix<3; ++row_ix) {\n                            Eigen::Vector3f evec = eigsolv.eigenvectors().col(row_ix).real();\n                            //cond = 4 * evec(1, :) .* evec(3, :) - evec(2, :).^2; % evaluate a'Ca\n                            if ((4.0 * evec[0] * evec[2]) - (evec[1] * evec[1]) > 0)\n                            {\n                                conic_params[0] = evec[0];\n                                conic_params[1] = evec[1];\n                                conic_params[2] = evec[2];\n                                Eigen::Vector3f Tevec = T*evec;\n                                conic_params[3] = Tevec[0];\n                                conic_params[4] = Tevec[1];\n                                conic_params[5] = Tevec[2];\n                            }\n                        }\n\n                        cv::RotatedRect cvFitEllipse= cv::fitEllipse(hull);\n                        cv::ellipse(\n                            bgrFrame, \n                            cv::Point(cvFitEllipse.center.x + 320, 240 - cvFitEllipse.center.y),\n                            cv::Size(cvFitEllipse.size.width/2, cvFitEllipse.size.height/2),\n                            cvFitEllipse.angle,\n                            0, 360, \n                            cv::Scalar(0, 255, 255));\n                        \n                        // Convert to parametric params\n                        float A = conic_params[0];\n                        float B = conic_params[1] / 2;\n                        float C = conic_params[2];\n                        float D = conic_params[3] / 2;\n                        float F = conic_params[4] / 2;\n                        float G = conic_params[5];\n                        float BB = B*B;\n                        float AC = A*C;\n                        float FF = F*F;\n                        float off_d = BB - AC;\n                        float h = (C*D - B*F) / off_d;\n                        float k = (A*F - B*D) / off_d;\n                        float semi_n = A*FF + C*D*D + G*BB - 2*B*D*F - AC*G;\n                        float dAC = A-C;\n                        float dACsq = dAC*dAC;\n                        float semi_d_2 = sqrtf(dACsq + 4*BB);\n                        float semi_d_3 = -A - C;\n                        float a_sqrd = (2 * semi_n) / (off_d * (semi_d_3 + semi_d_2));\n                        float b_sqrd = (2 * semi_n) / (off_d * (semi_d_3 - semi_d_2));\n\n                        if (a_sqrd > FLT_EPSILON && b_sqrd > FLT_EPSILON)\n                        {\n                            // b and tau are only needed for drawing an ellipse.\n                            float a = sqrt(a_sqrd);\n                            float b = sqrt(b_sqrd);\n                            double tau = atan2(2 * B, dAC) / 2;  //acot((A-C)/(2*B))/2;\n                            if (A > C)\n                            {\n                                tau += M_PI/2;\n                            }\n//                            if (tau < 0)\n//                            {\n//                                float oldb = b;\n//                                b = a;\n//                                a = oldb;\n//                                tau += M_PI;\n//                            }\n                            cv::ellipse(bgrFrame, cv::Point(h+320, 240-k), cv::Size(a, b), tau, 0, 360, cv::Scalar(0, 255, 0));\n\n                            //Get sphere coordinates from parametric\n                            float F_PX = 554.2563;\n                            float R = 2.25;\n                            float L_px = sqrt(h*h + k*k);\n                            float m = L_px / F_PX;\n                            float fl = F_PX / L_px;\n                            float j = (L_px + a) / F_PX;\n                            float l = (j - m) / (1 + j*m);\n                            float D_cm = R * sqrt(1 + l*l) / l;\n                            float z = D_cm * fl / sqrt(1 + fl*fl);\n                            float L_cm = z * m;\n                            float x = L_cm * h / L_px;\n                            float y = L_cm * k / L_px;\n\n                            std::cout << \"X: \" << x << \" Y: \" << y << \" Z: \" << z << std::endl;\n                        }\n                    }\n                    \n                }\n\n                imshow(\"bgr video\", bgrFrame);\n                imshow(\"hsv video\", hsvFrame);\n            }\n\n\t\t\tint myw = 4;\n\t\t\tstd::cout << '\\r' <<\n\t\t\t\t\"# \" << std::setw(myw) << std::left << psmstate->RawSequence <<\n\t\t\t\t\" A(1): \" <<\n\t\t\t\tstd::setw(myw) << std::right << psmstate->RawAccel[0][0] << \",\" <<\n                std::setw(myw) << std::right << psmstate->RawAccel[0][1] << \",\" <<\n                std::setw(myw) << std::right << psmstate->RawAccel[0][2] <<\n\t\t\t\t\"; A(2): \" <<\n                std::setw(myw) << std::right << psmstate->RawAccel[1][0] << \",\" <<\n                std::setw(myw) << std::right << psmstate->RawAccel[1][1] << \",\" <<\n                std::setw(myw) << std::right << psmstate->RawAccel[1][2] <<\n\t\t\t\t\"; G(1): \" <<\n                std::setw(myw) << std::right << psmstate->RawGyro[0][0] << \",\" <<\n                std::setw(myw) << std::right << psmstate->RawGyro[0][1] << \",\" <<\n                std::setw(myw) << std::right << psmstate->RawGyro[0][2] <<\n\t\t\t\t\"; G(2): \" <<\n                std::setw(myw) << std::right << psmstate->RawGyro[1][0] << \",\" <<\n                std::setw(myw) << std::right << psmstate->RawGyro[1][1] << \",\" <<\n                std::setw(myw) << std::right << psmstate->RawGyro[1][2] <<\n\t\t\t\t\"; M: \" <<\n                std::setw(myw) << std::right << psmstate->RawMag[0] << \",\" <<\n                std::setw(myw) << std::right << psmstate->RawMag[1] << \",\" <<\n                std::setw(myw) << std::right << psmstate->RawMag[2] <<\n\t\t\t\tstd::flush;\n\n            cv::waitKey(16);\n\t\t}\n        std::cout << std::endl;\n\n        psmove.close();\n\t}\n    \n    // Tear-down hid api\n    hid_exit();\n\n\tlog_dispose();\n    \n    return 0;\n}", "meta": {"hexsha": "c9a519230fae0556b23a8ecd15422ffe6a954213", "size": 15523, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/test_optical_tracker.cpp", "max_stars_repo_name": "wuyou33/PS", "max_stars_repo_head_hexsha": "b254a10a532c11eb1c45138ea6dab57e9a8595f2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tests/test_optical_tracker.cpp", "max_issues_repo_name": "wuyou33/PS", "max_issues_repo_head_hexsha": "b254a10a532c11eb1c45138ea6dab57e9a8595f2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/test_optical_tracker.cpp", "max_forks_repo_name": "wuyou33/PS", "max_forks_repo_head_hexsha": "b254a10a532c11eb1c45138ea6dab57e9a8595f2", "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": 42.1820652174, "max_line_length": 127, "alphanum_fraction": 0.403594666, "num_tokens": 3886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2606798387366968}}
{"text": "#include \"find_doors.h\"\n\n#include <boost/geometry/arithmetic/arithmetic.hpp>\n#include <boost/geometry/algorithms/intersection.hpp>\n#include <boost/geometry/algorithms/length.hpp>\n#include <boost/geometry/index/rtree.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/version.hpp>\n\n#include <cstring>\n#include <cstdlib>\n#include <cmath>\n#include <cstdint>\n\n#include <algorithm>\n#include <string>\n#include <iostream>\n#include <limits>\n#include <set>\n#include <map>\n#include <list>\n#include <utility>\n#include <array>\n#include <iterator>\n\nusing namespace cslibs_vectormaps;\n\nnamespace {\n\n// some utility boost::geometry is lacking\npoint_t add(const point_t& p1, const point_t& p2)\n{\n    point_t p = p1;\n    boost::geometry::add_point(p, p2);\n    return p;\n}\n\npoint_t subtract(const point_t& p1, const point_t& p2)\n{\n    point_t p = p1;\n    boost::geometry::subtract_point(p, p2);\n    return p;\n}\n\npoint_t multiply(const point_t& p, double v)\n{\n    point_t p2 = p;\n    boost::geometry::multiply_value(p2, v);\n    return p2;\n}\n\npoint_t divide(const point_t& p, double v)\n{\n    point_t p2 = p;\n    boost::geometry::divide_value(p2, v);\n    return p2;\n}\n\nbool equal(const point_t& a, const point_t& b)\n{\n    return a.x() == b.x() && a.y() == b.y();\n}\n\n}\n\nFindDoors::FindDoors(const FindDoorsParameter& parameter) : parameter_(parameter)\n{\n\n}\n\nstd::vector<segment_t> FindDoors::round_segments(const std::vector<segment_t>& segments, double precision)\n{\n    double p = precision;\n    if (p != 0.) {\n        std::vector<segment_t> rounded_segments = segments;\n        for (segment_t& toround : rounded_segments) {\n            toround.first.x(std::round(toround.first.x() * p) / p);\n            toround.first.y(std::round(toround.first.y() * p) / p);\n            toround.second.x(std::round(toround.second.x() * p) / p);\n            toround.second.y(std::round(toround.second.y() * p) / p);\n        }\n        return rounded_segments;\n    } else {\n        return segments;\n    }\n}\n\nstd::vector<segment_t> FindDoors::clean_segments(const std::vector<segment_t>& rounded_segments)\n{\n    // make a new vector that only contains successive segments, no overlapping\n    // segments. we can only replace exact vertical or exact horizontal\n    // overlappings at the moment.\n    std::vector<segment_t> non_overlapping_segments;\n\n    // sort original segments into std::vectors (vertical, horizontal, other)\n    std::vector<segment_t> vertical, horizontal;\n    for (const segment_t& segment : rounded_segments) {\n        if (segment.first.x() == segment.second.x()) {\n            segment_t s = {\n                {segment.first.x(), std::min(segment.first.y(), segment.second.y())},\n                {segment.second.x(), std::max(segment.first.y(), segment.second.y())}\n            };\n            vertical.push_back(s);\n        } else if (segment.first.y() == segment.second.y()) {\n            segment_t s = {\n                {std::min(segment.first.x(), segment.second.x()), segment.first.y()},\n                {std::max(segment.first.x(), segment.second.x()), segment.second.y()}\n            };\n            horizontal.push_back(s);\n        } else {\n            non_overlapping_segments.push_back(segment);\n        }\n    }\n    // sort the std::vectors\n    std::sort(vertical.begin(), vertical.end(), [](const segment_t& s1, const segment_t& s2) {\n        return s1.first.x() < s2.first.x()\n               || s1.first.x() == s2.first.x()\n                  && (s1.first.y() < s2.first.y()/*\n                      || s1.first.y() == s2.first.y()\n                         && s1.second.y() < s2.second.y()*/);\n    });\n    std::sort(horizontal.begin(), horizontal.end(), [](const segment_t& s1, const segment_t& s2) {\n        return s1.first.y() < s2.first.y()\n               || s1.first.y() == s2.first.y()\n                  && (s1.first.x() < s2.first.x()/*\n                      || s1.first.x() == s2.first.x()\n                         && s1.second.x() < s2.second.x()*/);\n    });\n    // finally, detect overlapping segments and replace those by single segments\n    std::size_t overlaps = 0;\n    for (std::size_t i = 0, n = vertical.size(), j; i < n; i = j) {\n        double miny = vertical[i].first.y();\n        double maxy = vertical[i].second.y();\n        for (j = i + 1; j < n && vertical[i].first.x() == vertical[j].first.x(); j++) {\n            if (vertical[j].first.y() < maxy) {\n                if (vertical[j].second.y() > maxy)\n                    maxy = vertical[j].second.y();\n                overlaps++;\n            } else {\n                break;\n            }\n        }\n        segment_t s = {{vertical[i].first.x(), miny}, {vertical[i].first.x(), maxy}};\n        non_overlapping_segments.push_back(s);\n    }\n    for (std::size_t i = 0, n = horizontal.size(), j; i < n; i = j) {\n        double minx = horizontal[i].first.x();\n        double maxx = horizontal[i].second.x();\n        for (j = i + 1; j < n && horizontal[i].first.y() == horizontal[j].first.y(); j++) {\n            if (horizontal[j].first.x() < maxx) {\n                if (horizontal[j].second.x() > maxx)\n                    maxx = horizontal[j].second.x();\n                overlaps++;\n            } else {\n                break;\n            }\n        }\n        segment_t s = {{minx, horizontal[i].first.y()}, {maxx, horizontal[i].first.y()}};\n        non_overlapping_segments.push_back(s);\n    }\n    std::cout << \"Merged \" << overlaps << \" overlapping segments\\n\";\n\n    // TODO: workaround for older Boost using bounding boxes\n#if BOOST_VERSION < 105600\n    std::cerr << \"Boost version >= 1.56.0 is required for creating the segment graph! The results are probably unusable.\\n\";\n    return non_overlapping_segments;\n#else\n    // replace intersecting line segments by multiple new segments that end in a common intersection point\n    // use a spatial index to ease finding those intersecting line segments\n    namespace bgi = boost::geometry::index;\n    bgi::rtree<segment_t, bgi::rstar<16>> rtree(non_overlapping_segments);\n    std::vector<segment_t> clean_segments;\n    for (const segment_t& query_segment : non_overlapping_segments) {\n        std::vector<point_t> intersections;\n        for (auto qit = rtree.qbegin(bgi::intersects(query_segment)), end = rtree.qend(); qit != end; ++qit) {\n            const segment_t& result_segment = *qit;\n            boost::geometry::intersection(result_segment, query_segment, intersections);\n        }\n        std::set<point_t, point_compare> newpoints(intersections.begin(), intersections.end());\n        for (auto pit1 = newpoints.begin(), pit2 = std::next(pit1), end = newpoints.end(); pit2 != end; ++pit1, ++pit2) {\n            clean_segments.push_back({*pit1, *pit2});\n        }\n    }\n    std::cout << \"Created \" << (clean_segments.size() - non_overlapping_segments.size()) << \" new segments because of intersections\\n\";\n\n    return clean_segments;\n#endif\n}\n\nstd::vector<FindDoors::door_t> FindDoors::find_doors(const std::vector<segment_t>& cleaned_segments)\n{\n    const FindDoorsParameter& params = parameter_;\n\n    // find doors\n    double door_depth_min = params.door_depth_min;\n    double door_depth_max = params.door_depth_max;\n    double door_width_min = params.door_width_min;\n    double door_width_max = params.door_width_max;\n\n    auto check_length = [](const point_t& v, double min, double max) {\n        // checks the length of a vector\n        double d = v.x() * v.x() + v.y() * v.y();\n        return d >= min * min && d <= max * max;\n    };\n    auto check_angle = [&params](const point_t& v1, const point_t& v2) {\n        double angle = std::atan2(v2.y(), v2.x()) - std::atan2(v1.y(), v1.x());\n        if (angle < 0)\n            angle += boost::math::double_constants::two_pi;\n        return angle >= boost::math::double_constants::half_pi - params.door_angle_diff_max\n            && angle <= boost::math::double_constants::half_pi + params.door_angle_diff_max;\n    };\n    /*auto check_door_side = [&door_depth_min, &door_depth_max, &check_length, &check_angle](const point_t& v1, const point_t& v2, const point_t& v3) {\n        // Checks if v1, v2, v3 could form the side of a door like this:\n        //     v1\n        //  +<----+\n        //        |v2\n        //        v\n        //  +<----+\n        //     v3\n        // This could be the left side of a door. The length of v2 is\n        // checked. angle(v1, v2) and angle(v3, v2) are checked to be\n        // approximately 90 deg. 270 deg does not count! This is so that\n        // v2's direction is consistent and so that no duplicates occur\n        // when considering edges in both directions.\n        // The angles are not checked anymore right now.\n        return check_length(v2, door_depth_min, door_depth_max);\n            //&& check_angle(v1, v2) && check_angle(v3, v2);\n    };\n    auto check_node = [&check_door_side](const node_t& firstnode, const edge_t& e1, const edge_t& e2) {\n        // checks if edge e2 from firstnode to secondnode could form\n        // the side of a door as explained in check_door_side() above\n        const node_t* secondnode = e2.target->node;\n        if (secondnode->edges.size() == 2) {\n            const edge_t& e3 = secondnode->edges[\n                secondnode->edges[0].target->node == &firstnode ? 1 : 0\n            ];\n            auto edge_to_vector = [](const edge_t& e) {\n                return subtract(e.target->point, e.start->point);\n            };\n            if (check_door_side(edge_to_vector(e1), edge_to_vector(e2), edge_to_vector(e3)))\n                return true;\n        }\n        return false;\n    };*/\n    std::vector<segment_t> side_candidates;\n    /*for (const node_t& firstnode : graph.nodes) {\n        // find all nodes that connect exactly two edges. those can be corner points of doors.\n        if (firstnode.edges.size() != 2)\n            continue;\n        // if one of the connected nodes also has exactly two edges, the\n        // three edges might form one of the two walls on either side of\n        // the door\n        if (check_node(firstnode, firstnode.edges[1], firstnode.edges[0]))\n            side_candidates.emplace_back(firstnode.edges[0].start->point, firstnode.edges[0].target->point);\n        if (check_node(firstnode, firstnode.edges[0], firstnode.edges[1]))\n            side_candidates.emplace_back(firstnode.edges[1].start->point, firstnode.edges[1].target->point);\n    }*/\n    // here, segments become door side candidates if their length fits.\n    // just forget the madness above.\n    for (const segment_t& segment : cleaned_segments) {\n        if (check_length(subtract(segment.second, segment.first), door_depth_min, door_depth_max)) {\n            side_candidates.push_back(segment);\n            side_candidates.emplace_back(segment.second, segment.first);\n        }\n    }\n    std::cout << \"Found \" << side_candidates.size() << \" door side candidates\\n\";\n    \n    std::size_t ncandidates = side_candidates.size();\n    std::vector<std::size_t> side_candidate_partners(ncandidates, static_cast<std::size_t>(-1));\n    std::vector<double> side_candidate_distances(ncandidates, std::numeric_limits<double>::max());\n    for (std::size_t i1 = 0; i1 < ncandidates; i1++) {\n        // we search for the other side of the door frame by drawing\n        // a ray r from the middle of the edge like this:\n        //     v1\n        //  +<----+          +---->+\n        //        |  v       ^\n        //      v2|----->----|--- r\n        //        v          |w2\n        //  +<----+          +---->+\n        //     v3\n        // If r cuts another possible door frame side nearly\n        // perpendicularly and that intersection point is not too far\n        // and not too close from v2, we found a door.\n        const point_t& v21 = side_candidates[i1].first;\n        const point_t& v22 = side_candidates[i1].second;\n        // r = middle + t * v\n        point_t middle = multiply(add(v21, v22), .5);\n        point_t v2 = subtract(v22, v21);\n        point_t v = {-v2.y(), v2.x()}; // 90 deg turn\n        double v_length = std::sqrt(v.x() * v.x() + v.y() * v.y());\n\n        // check all other candidates\n        for (std::size_t i2 = 0; i2 < ncandidates; i2++) {\n            if (i2 == i1)\n                continue;\n            // line intersection adapted from https://stackoverflow.com/a/565282/1007605\n            auto cross = [](const point_t& v, const point_t& w) {\n                return v.x() * w.y() - v.y() * w.x();\n            };\n            const point_t& w21 = side_candidates[i2].first;\n            const point_t& w22 = side_candidates[i2].second;\n            point_t w2 = subtract(w22, w21);\n            double det = cross(v, w2);\n            // check if vectors are neither parallel nor collinear\n            if (det == 0.)\n                continue;\n            // check that second side is cut by ray\n            double u = cross(subtract(w21, middle), v) / det;\n            if (u < 0. || u > 1.)\n                continue;\n            // check distance to second side\n            double d = cross(subtract(w21, middle), w2) * v_length / det;\n            if (d < door_width_min || d > door_width_max)\n                continue;\n            // check that sides are approximately parallel\n            if (!check_angle(v, w2))\n                continue;\n            // we found a match! if there are multiple matches we only keep the closest\n            if (d < side_candidate_distances[i1]) {\n                side_candidate_distances[i1] = d;\n                side_candidate_partners[i1] = i2;\n            }\n            if (d < side_candidate_distances[i2]) {\n                side_candidate_distances[i2] = d;\n                side_candidate_partners[i2] = i1;\n            }\n        }\n    }\n\n    // match side candidate pairs\n    std::vector<door_t> door_candidates;\n    std::vector<double> door_candidate_distances;\n    for (std::size_t i1 = 0; i1 < ncandidates; i1++) {\n        std::size_t i2 = side_candidate_partners[i1];\n        if (i2 != static_cast<std::size_t>(-1) && i1 < i2\n        && side_candidate_partners[i2] == i1) {\n            const point_t& v21 = side_candidates[i1].first;\n            const point_t& v22 = side_candidates[i1].second;\n            const point_t& w21 = side_candidates[i2].first;\n            const point_t& w22 = side_candidates[i2].second;\n            door_t door_candidate = {segment_t{v21, v22}, segment_t{w21, w22}};\n            door_candidates.push_back(door_candidate);\n            door_candidate_distances.push_back(side_candidate_distances[i1]);\n        }\n    }\n    std::cout << \"Found \" << door_candidates.size() << \" door candidates\\n\";\n\n#if BOOST_VERSION < 105600\n    std::cerr << \"Boost version >= 1.56.0 is required for checking space between door frames, so you might get more false positives\\n\";\n    return door_candidates;\n#else\n    // check if area between door frame sides is unobstructed\n    std::vector<door_t> doors;\n    namespace bgi = boost::geometry::index;\n    bgi::rtree<segment_t, bgi::rstar<16>> rtree(cleaned_segments);\n    for (std::size_t i = 0; i < door_candidates.size(); i++) {\n        const door_t& door_candidate = door_candidates[i];\n        double d1 = boost::geometry::distance(door_candidate[0].first, door_candidate[0].second);\n        double d2 = boost::geometry::distance(door_candidate[1].first, door_candidate[1].second);\n\n        // aligned at the middle of the longer door frame side, create a\n        // rectangle between the door sides. it looks like this:\n        //      door_width\n        //      +---------+\n        //\n        //        +-----+             +\n        //  ----+ |     | +----       |\n        // frame| |rect | |frame      | door_width * unobstructed_area_depth\n        //  ----+ |     | +----       |\n        //        +-----+             +\n        //\n        //        +-----+\n        // door_width * unobstructed_area_width\n        const segment_t& longer_side = door_candidate[d1 > d2 ? 0 : 1];\n        double longer_side_length = d1 > d2 ? d1 : d2;\n        const point_t& v21 = longer_side.first;\n        const point_t& v22 = longer_side.second;\n        // r = middle + t * v\n        point_t middle = multiply(add(v21, v22), .5);\n        point_t v2 = subtract(v22, v21);\n        point_t v = {-v2.y(), v2.x()}; // 90 deg turn\n        double factor = door_candidate_distances[i] / longer_side_length;\n        // t2 and t are as long as the door is wide, t2 points in direction of\n        // the first door side, t points perpendicularly to the other door side\n        point_t t2 = multiply(v2, factor);\n        point_t t = multiply(v, factor);\n        double rectangle_length = params.unobstructed_area_depth;\n        double width_padding = .5 - params.unobstructed_area_width * .5;\n        point_t p1 = add(add(middle, multiply(t,      width_padding)), multiply(t2, -.5 * rectangle_length));\n        point_t p2 = add(add(middle, multiply(t, 1. - width_padding)), multiply(t2, -.5 * rectangle_length));\n        point_t p3 = add(add(middle, multiply(t, 1. - width_padding)), multiply(t2,  .5 * rectangle_length));\n        point_t p4 = add(add(middle, multiply(t,      width_padding)), multiply(t2,  .5 * rectangle_length));\n\n        // if this rectangle is not obstructed, we found an actual door\n        ring_t unobstructed_area;\n        unobstructed_area.insert(unobstructed_area.end(), {p1, p2, p3, p4, p1});\n        std::vector<segment_t> result;\n        bgi::query(rtree, bgi::intersects(unobstructed_area), std::back_inserter(result));\n        if (result.size() == 0) {\n            door_t d = {\n                segment_t{door_candidate[0].second, door_candidate[1].first},\n                segment_t{door_candidate[1].second, door_candidate[0].first}\n            };\n            doors.push_back(d);\n        }\n    }\n\n    // near the door frames, the door might still intersect the map. prune door sides appropriately\n    for (door_t& door : doors) {\n        for (segment_t& side : door) {\n            std::vector<segment_t> intersections;\n            bgi::query(rtree, bgi::intersects(side), std::back_inserter(intersections));\n            for (const segment_t& intersection : intersections) {\n                // work around buggy boost::geometry::intersection rarely giving incorrect result\n                if (equal(intersection.first, side.first) || equal(intersection.first, side.second)\n                || equal(intersection.second, side.first) || equal(intersection.second, side.second))\n                    continue;\n                std::vector<point_t> intersection_points;\n                boost::geometry::intersection(side, intersection, intersection_points);\n                for (const point_t& intersection_point : intersection_points) {\n                    segment_t newside1 = {side.first, intersection_point};\n                    segment_t newside2 = {intersection_point, side.second};\n                    side = boost::geometry::length(newside1) > boost::geometry::length(newside2)\n                         ? newside1 : newside2;\n                }\n            }\n        }\n    }\n    std::cout << \"Found \" << doors.size() << \" doors!\\n\";\n    return doors;\n#endif\n}\n", "meta": {"hexsha": "aaae609feffbaf9f86af90def88e4ba26f5a3395", "size": 19052, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/map_viewer/algorithms/find_doors.cpp", "max_stars_repo_name": "cogsys-tuebingen/cslibs_vectormaps", "max_stars_repo_head_hexsha": "bafdea3e25db51a1324634ded30c69322faa02bb", "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/map_viewer/algorithms/find_doors.cpp", "max_issues_repo_name": "cogsys-tuebingen/cslibs_vectormaps", "max_issues_repo_head_hexsha": "bafdea3e25db51a1324634ded30c69322faa02bb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-31T02:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-31T02:12:27.000Z", "max_forks_repo_path": "src/map_viewer/algorithms/find_doors.cpp", "max_forks_repo_name": "cogsys-tuebingen/cslibs_vectormaps", "max_forks_repo_head_hexsha": "bafdea3e25db51a1324634ded30c69322faa02bb", "max_forks_repo_licenses": ["BSD-3-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.0, "max_line_length": 151, "alphanum_fraction": 0.5871299601, "num_tokens": 4751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.26062180403864277}}
{"text": "#include \"process.h\"\n#include \"data.h\"\n#include \"linear.h\"\n#include \"Sample.h\"\n#include \"RIRL.h\"\n#include \"DETree.h\"\n\n#include <iostream>\n#include <cstdlib>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <fstream>\n#include <limits>\n#include <cfloat>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/serialization/vector.hpp>\n\nusing namespace std;\n\nProcess::Process()\n{\n\n}\n\nProcess::~Process()\n{\n\n}\n\n//each sample is a tuple <x,y>\nvector<vector<double> > Process::getContinuousSamples(Data &data,vector<double> previousPoint,vector<double> currentPoint){\n    int numberOfSamples = data.getNumberOfSamples();\n\n    double startPointX = previousPoint.at(0);\n    double startPointY = previousPoint.at(1);\n\n    double endPointX = currentPoint.at(0);\n    double endPointY = currentPoint.at(1);\n\n    double deltaX = abs((startPointX - endPointX)) / ((double) (numberOfSamples));\n    double deltaY = abs((startPointY - endPointY)) / ((double) (numberOfSamples));\n\n    double xSample = startPointX;\n    double ySample = startPointY;\n\n    vector<vector<double> > samplesList;\n\n    for (int i = 0 ; i < numberOfSamples ; i++){\n        vector<double> sample;\n        sample.push_back(xSample);\n        sample.push_back(ySample);\n\n        samplesList.push_back(sample);\n\n        xSample = xSample + deltaX;\n\n        if(deltaX != 0.0){\n            ySample = ((startPointY - endPointY) / (startPointX - endPointX)) * xSample\n                    + (startPointY - ((startPointY - endPointY) /\n                                      (startPointX - endPointX)) * startPointX);\n        }else if(deltaX == 0.0 && deltaY != 0.0){\n            ySample = ySample + deltaY;\n        }else{\n            ySample = ySample;\n        }\n    }\n\n    return samplesList;\n}\n\ndouble Process::getDistanceToPowerTwo(vector <double> sample){\n    return (pow ((sample.at(0) - 10), 2) + pow ((sample.at(1) - 10), 2));\n}\n\nvector<double> Process::getObsSampleList(Data &data,vector<double> previousPoint,vector<double> currentPoint){\n    //for debugging\n    //    if(currentPoint == previousPoint){\n    //        cout << \"we are turnning!\" << endl;\n    //    }\n\n    //list of <x,y> between two points\n    vector< vector<double> > continuousSampleList = getContinuousSamples(data, previousPoint, currentPoint);\n\n    vector<double> obsList;\n\n    // parameters of the normal distribution\n    double sigma = data.getSigma();\n    double mean = data.getMean();\n    double obs;\n    double accNoise = 0.0;\n    for (int i = 0 ; i < (int)continuousSampleList.size() ; i++){\n        vector<double> sample = continuousSampleList.at(i);\n\n        double r2 = getDistanceToPowerTwo(sample);\n        double p = data.getP(); // presure in intensity formula\n\n        unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n        default_random_engine generator(seed);\n        normal_distribution<double> distribution(mean,sigma);\n        double noise = distribution(generator);\n        //        double noise = 0.0; // for debugging noise free\n        //        cout << (p / (4 * M_PI * r2)) << \" + \" << noise << endl;\n\n        obs = (p / (4 * M_PI * r2)) + noise;\n        accNoise = accNoise + noise * noise;\n        obsList.push_back(obs);\n    }\n\n    data.updateNoise(accNoise);\n    return obsList;\n}\n\n//changed\n// don't make continus trajectory any more just the discrete one. center to center move\nvoid Process::bulidData(Data &data, int lenghtOfTrajectory, bool forTrainingObs){\n\n    vector<double> initialPoint;\n    vector<double> firstPoint;\n\n    vector<int> firstState;\n    int initialAction;\n    int action;\n    vector<int> initialState; //at 0 facing east\n    initialState.push_back(0);\n    initialState.push_back(0);\n\n    if(forTrainingObs == true){\n        initialAction = randomPolicy(data);\n    }else{\n        //call rational policy here\n        map<vector<int>,map<int,double>> ExpertPolicy = data.getExpertPolicy();\n        vector<int> listOfActions = data.getListOfActions();\n        double max = -DBL_MAX;\n\n        for(int j = 0 ; j < (int)(listOfActions.size()) ; j++ ){\n            int a = listOfActions.at(j);\n            if(max < ExpertPolicy[initialState][a]){\n                max = ExpertPolicy[initialState][a];\n                initialAction = a;\n            }\n        }\n        //print the T for debugging\n        cout << \"[< \" << initialState.at(0) << \" , \"\n             << initialState.at(1) << \" > , \" <<\n                initialAction << \" ]\" << endl;\n    }\n    initialPoint = getCenterPointInState(initialState.at(0));\n    firstPoint = initialPoint;\n\n\n    firstState = initialState;\n    action = initialAction;\n\n    int counter = 0;\n\n    bool done = false;\n\n    while(!done){\n        vector<double> secondPoint;\n\n        vector<int> secondState = transitionFunction(data, firstState, action);\n\n        if(firstState == secondState){\n            secondPoint = firstPoint;\n        }else{\n            secondPoint = getCenterPointInState(secondState.at(0));\n        }\n\n        vector<double> obs = getObsSampleList(data,firstPoint, secondPoint);\n        updateFlatObsList(data,firstState,action,obs,forTrainingObs);\n\n        firstState = secondState;\n        firstPoint = secondPoint;\n        counter++;\n\n        if(counter == lenghtOfTrajectory){\n            done = true;\n        }else{\n            if(forTrainingObs == true){\n                action = randomPolicy(data);\n            }else{\n                //call rational policy here\n                map<vector<int>,map<int,double>> ExpertPolicy = data.getExpertPolicy();\n                vector<int> listOfActions = data.getListOfActions();\n                double max = -DBL_MAX;\n\n                for(int j = 0 ; j < (int)(listOfActions.size()) ; j++ ){\n                    int a = listOfActions.at(j);\n                    if(max < ExpertPolicy[firstState][a]){\n                        max = ExpertPolicy[firstState][a];\n                        action = a;\n                    }\n                }\n                //print the T for debugging\n                cout << \"[< \" << firstState.at(0) << \" , \"\n                     << firstState.at(1) << \" > , \" <<\n                        action << \" ]\" << endl;\n            }\n        }\n    }\n}\n\n// copress that to above function\nvoid Process::updateFlatObsList(Data &data, vector<int> state, int action, vector<double> obs, bool forTrainingObs){\n    int numberOfSamples = data.getNumberOfSamples();\n\n    vector<double> time_x = data.getTimeChunk();\n    Sample obsTuple;\n    Maths::Regression::Linear linearRegression(numberOfSamples, time_x, obs); //Intensity_y = Obs\n    double slope =linearRegression.getSlope();\n    obsTuple.values.push_back(slope);\n    double intercept =linearRegression.getIntercept();\n    obsTuple.values.push_back(intercept);\n    if(forTrainingObs){\n        obsTuple.values.push_back(state.at(0)); // adding state.position\n        obsTuple.values.push_back(state.at(1)); // adding state.orientation\n        obsTuple.values.push_back(action); // adding action\n    }\n\n    obsTuple.p = data.getNormalizerFactorForP(); //uniform\n    data.updateFlatObsList(obsTuple);\n}\n\n//changed\n//just consider the center\n//rawstate = S_0 to S_n\nvector<double> Process::getCenterPointInState(int rawState){\n    vector<double> result;\n\n    double x = (rawState + 1) * 20 +10;\n    double y = 30;\n\n    result.push_back(x);\n    result.push_back(y);\n\n    return result;\n}\n\nvector<int> Process::calcStateBoundaries(Data &data, int state){\n    vector<int> result;\n\n    int stepSize = data.getStepSize();\n    int remainder = state % stepSize;\n    int quotient = state / stepSize;\n\n    int stateLowerX = remainder * stepSize;\n    int stateUpperX = remainder  * stepSize + stepSize;\n    int stateLowerY = quotient * stepSize - stepSize;\n    int stateUpperY = quotient * stepSize;\n\n    result.push_back(stateLowerX);\n    result.push_back(stateUpperX);\n    result.push_back(stateLowerY);\n    result.push_back(stateUpperY);\n\n    return result;\n}\n\n//return a random action\n//done\nint Process::randomPolicy(Data &data){\n    vector<int> listOfActions = data.getListOfActions();\n    int randomAction = listOfActions.at(getRandomIntNumber(listOfActions.size()));\n    return randomAction;\n}\n\n//I have to chagne it later\ndouble Process::probablityOfNextStateGivenCurrentStateAction(Data &data,vector<int> nextState, vector<int> currentState, int currentAction){\n    double stochasticity = data.getStochasticity();\n    vector<int> idealNextState = returnNextState(data,currentState,currentAction);\n    double pr = 0.0;\n    if (nextState == idealNextState){\n        pr = 1.0 - stochasticity;\n    }/*else if(areAdj(currentState,nextState) &&\n             currentState.at(0) != 0 &&\n             currentState.at(0) != data.getNumberOfRawStates()-1){ //if in the middle of hallway\n        pr = stochasticity / 2.0; //confirm it with ken\n    }else if(areAdj(currentState,nextState)){ //if at the end of the hallway\n        pr = stochasticity / 1.0; //confirm it with ken\n    }*/else if(nextState == currentState){\n        pr = stochasticity;\n    }\n\n    return pr;\n}\n\n//changed\nvector<int> Process::returnNextState(Data &data,vector<int> currentState, int currentAction){\n    vector<int> nextState;\n    if(/*(currentState.at(1) == 0 && currentAction == -1) ||*/ //facing east going backward\n            (currentState.at(1) == 1 && currentAction == 1)){ //facing west going forward\n        int nextPosition = currentState.at(0) - 1;\n        //check if the next position in the range of possible positions\n        if(nextPosition < 0){\n            nextPosition = 0;\n        }else if(nextPosition > data.getNumberOfRawStates() - 1){\n            nextPosition = data.getNumberOfRawStates() - 1;\n        }\n        nextState.push_back(nextPosition);\n        nextState.push_back(currentState.at(1));\n    }else if(currentAction == 0){ //turning\n        int nextOrientation;\n        if(currentState.at(1) == 0){\n            nextOrientation = 1;\n        }else{\n            nextOrientation = 0;\n        }\n        nextState.push_back(currentState.at(0));\n        nextState.push_back(nextOrientation);\n    }else if((currentState.at(1) == 0 && currentAction == 1) /*|| //facing east going forward\n                                                                                                                                                                      (currentState.at(1) == 1 && currentAction == -1)*/){ //facing west going backward\n        int nextPosition = currentState.at(0) + 1;\n        //check if the next position (rawState) in the range of possible positions\n        if(nextPosition < 0){\n            nextPosition = 0;\n        }else if(nextPosition > data.getNumberOfRawStates() - 1){\n            nextPosition = data.getNumberOfRawStates() - 1;\n        }\n        nextState.push_back(nextPosition);\n        nextState.push_back(currentState.at(1));\n    }else{\n        cout << \"missing something!\" << endl;\n    }\n\n\n    return nextState;\n}\n\n//changed\nvector<int> Process::transitionFunction(Data &data,vector<int> currentState, int currentAction){\n    vector<int> nextState;\n    double stochasticity = data.getStochasticity();\n    //    vector<int> listOfActions = data.getListOfActions();\n    double stochasticityIndicator = getRandomDoubleNumber(0,1);\n\n    if(stochasticityIndicator < stochasticity ){\n        //        int randomAction = listOfActions.at(getRandomIntNumber(listOfActions.size()));\n        //        while(randomAction == currentAction){\n        //            randomAction = listOfActions.at(getRandomIntNumber(listOfActions.size()));\n        //        }\n        //        //generate next state here\n        //        nextState = returnNextState(data, currentState, randomAction);\n        nextState = currentState;\n    }else{\n        //generate next state here\n        nextState = returnNextState(data, currentState, currentAction);\n    }\n\n    return nextState;\n}\n\n\ndouble Process::getRandomDoubleNumber(int lowerBound, int upperBound){\n    double min = (double) lowerBound;\n    double max = (double) upperBound;\n    return (max - min) * ((double)rand() / (double)RAND_MAX) + min;\n}\n\nint Process::getRandomIntNumber(int upperBound){\n\n    return  rand() % upperBound;\n}\n\nvector<double> Process::rowNormalizer(vector<int> row){\n    vector<double> result;\n    int sum = 0;\n    for (int i = 0 ; i < (int)row.size() ; i++){\n        sum = sum + row.at(i);\n    }\n\n    if (sum != 0){\n        for (int i = 0 ; i < (int)row.size() ; i++){\n            result.push_back((double) row.at(i) / (double) sum);\n        }\n    }else{\n        for (int i = 0 ; i < (int)row.size() ; i++){\n            result.push_back(0);\n        }\n    }\n\n\n    return result;\n}\n\nvoid Process::trainObs(Data &data){\n    vector<double> * low  = data.getLow();\n    vector<double> * high = data.getHigh();\n    DETree observationModel(data.getFlatObsList(), low, high);\n    data.setObsModel(observationModel);\n}\n\n//changed\nvoid Process::generateTrajectories(Data &data, int lenghtOfT, bool forTrainingObs){\n    data.setSampleLength(lenghtOfT);\n    //setting up expert's policy\n    if(!forTrainingObs){\n        map<vector<int>,map<int,double>> qValuesForExpert = qValueSoftMaxSolver(data, 0.001, data.getExpertWeights());\n        constructExpertPolicy(data,qValuesForExpert);\n    }\n    cout << \"Generating data!\" << endl;\n    data.setNormalizerFactorForP(lenghtOfT);\n    bulidData(data, lenghtOfT, forTrainingObs);\n    cout << \"Data generated!\" << endl;\n    // claculating noise in relative mean square error fashion\n    double rmsNoise = data.getNoise() / ((double)lenghtOfT * (double)data.getNumberOfSamples());\n    cout << \"Average Noise Added to observation = \" << rmsNoise << endl;\n\n    if(forTrainingObs){\n        saveObsModel(data);\n        cout << \"Saving obsModel!\\n\";\n        saveObsModel(data);\n        cout << \"obsModel saved!\\n\";\n    }\n}\n\n//changed\nvector<double> Process::getFeatures(Data &data, vector<int> state, int action){\n    vector<double> features(data.getNumberOfFeatures(), 0.0);\n    int rawState = state.at(0);\n    int orientation = state.at(1);\n    int activatedFeatureForTurningIndex;\n    //    if(rawState == 9){\n    //        cout << (data.getNumberOfRawStates() - 1) << endl;\n    //    }\n    if(action == 0){\n        if (rawState < (data.getNumberOfRawStates() - 1) / 2 && orientation == 1){ //first half should face west\n            activatedFeatureForTurningIndex = rawState;\n            features.at(activatedFeatureForTurningIndex) = 1.0;\n        }else if(rawState > (data.getNumberOfRawStates() - 1) / 2 && orientation == 0) { //second half should face east\n            activatedFeatureForTurningIndex = data.getNumberOfRawStates() - rawState - 1;\n            features.at(activatedFeatureForTurningIndex) = 1.0;\n        }else if(rawState == (data.getNumberOfRawStates() - 1) / 2){\n            activatedFeatureForTurningIndex = (data.getNumberOfRawStates() - 1) / 2;\n            features.at(activatedFeatureForTurningIndex) = 1.0;\n        }else{\n            //            cout << \"I missing some Feature!!\" << endl;\n            activatedFeatureForTurningIndex = features.size()-2;\n            features.at(activatedFeatureForTurningIndex) = 1.0;\n        }\n    }else{\n        //construct the feature vector here\n        //last feature is for moving forward\n        //I may change this part if i want to add moving backward!\n        //I have to check if I am bangging the wall it should be no reward\n        if(rawState == 0 || rawState == data.getNumberOfRawStates() - 1){\n            //by not activating feature ==> no reward by going into the wall\n            //            activatedFeatureForTurningIndex = features.size()-2;\n            //            features.at(activatedFeatureForTurningIndex) = 1.0;\n        }else{\n            features.at(features.size()-1) = 1.0;\n        }\n    }\n\n    return features;\n}\n\n//new\nmap<vector<int>,map<int,double>> Process::qValueSoftMaxSolver(Data &data, double err, vector<double> weights){\n\n    map<vector<int>,double> V; //[State] //[State] ==> vector<int>\n    map<vector<int>,map<int,double>> Q; //[State][Action] //[State] ==> vector<int> & [Action] ==> int\n    vector<vector<int>> listOfStates = data.getListOfStates();\n    vector<int> listOfActions = data.getListOfActions();\n\n    for(int i = 0 ; i < (int)(listOfStates.size()) ; i++ ){ //foreach (State s ; model.S()) {\n        vector<int> s = listOfStates.at(i);\n        V[s] = 0.0;\n\n        for(int j = 0 ; j < (int)(listOfActions.size()) ; j++ ){//foreach (a; model.A(s)) {\n            int a = listOfActions.at(j);\n            Q[s][a] = 0;\n        }\n    }\n    //    V = V.rehash;\n    //    Q = Q.rehash;\n    double delta = 0;\n    int iteration = 0; //size_t\n    while (true) {\n        delta = 0;\n\n        for(int i = 0 ; i < (int)(listOfStates.size()) ; i++ ){ //foreach (State s ; model.S()) {\n            vector<int> s = listOfStates.at(i);\n\n            for(int j = 0 ; j < (int)(listOfActions.size()) ; j++ ){//foreach (a; model.A(s)) {\n                int a = listOfActions.at(j);\n                double r = reward(data,s,a,weights);//add reward function later\n                //double[State] T = model.T(s, a);\n\n                double expected_rewards = 0;\n                for (int k = 0 ; k < int(listOfStates.size()) ; k++){ //foreach (s_prime, p; T){\n                    vector<int> s_prime = listOfStates.at(k);\n                    //p ==> probabilityOfTheNextState\n                    double p  = probablityOfNextStateGivenCurrentStateAction(data,s_prime, s, a);\n                    expected_rewards += p*V[s_prime];\n                }\n\n                Q[s][a] = r + data.getGamma() * expected_rewards;\n            }\n        }\n\n        map<vector<int>,double> v;\n        v = V;\n        for(int i = 0 ; i < (int)(listOfStates.size()) ; i++ ){ //foreach (State s ; model.S()) {\n            vector<int> s = listOfStates.at(i);\n            double maxx = -DBL_MAX;\n            for(int j = 0 ; j < (int)(listOfActions.size()) ; j++ ){//foreach (a; model.A(s)) {\n                int a = listOfActions.at(j);\n                maxx = max(maxx, Q[s][a]);\n            }\n\n            double e_sum = DBL_MIN;\n\n            for(int j = 0 ; j < (int)(listOfActions.size()) ; j++ ){//foreach (a; model.A(s)) {\n                int a = listOfActions.at(j);\n                e_sum += exp(Q[s][a] - maxx);\n            }\n\n            v[s] = maxx - log(e_sum);\n            delta = max(delta, abs(V[s] - v[s]));\n        }\n\n\n        V = v;\n        //cout << \"Current Iteration: \" <<  delta << endl;\n\n        if (delta < err || iteration > data.getMaxIter()) {\n            map<vector<int>,map<int,double>> returnval; //[state][action]\n\n            //doing this part to avoid overfelow problem when do e to the power in softmax!!\n            for(int i = 0 ; i < (int)(listOfStates.size()) ; i++ ){ //foreach(state, actvalue; Q) {\n                vector<int> state = listOfStates.at(i);\n\n                for(int j = 0 ; j < (int)(listOfActions.size()) ; j++ ){//foreach(action, value; actvalue) {\n                    int action = listOfActions.at(j);\n                    double value = Q[state][action];\n                    returnval[state][action] = value - v[state];\n                }\n            }\n            //\t\t\t\twriteln(\"Finished Q-Value\");\n            return returnval;\n        }\n        iteration ++;\n    }\n}\n\n//new\n//this function calculate the reward reciving state and action\ndouble Process::reward(Data &data,vector<int> state, int action, vector<double> weights){\n    double reward;\n    vector<double> features = getFeatures(data,state,action);\n    reward = calcInnerProduct(features,weights);\n    return reward;\n}\n\n//construct the expert policy using the actual weights\n//using softmax\nvoid Process::constructExpertPolicy(Data &data, map<vector<int>,map<int,double>> Q_value){\n    map<vector<int>,map<int,double>> policy; //[State][Action]\n    vector<vector<int>> listOfStates = data.getListOfStates();\n    vector<int> listOfActions = data.getListOfActions();\n\n    for(int i = 0 ; i < (int)(listOfStates.size()) ; i++ ){ //foreach (State s ; model.S()) {\n        vector<int> s = listOfStates.at(i);\n        double normalizer = 0.0; //[State]\n\n        for(int j = 0 ; j < (int)(listOfActions.size()) ; j++ ){//foreach (Action a; model.A(s)) {\n            int a = listOfActions.at(j);\n            normalizer = normalizer + exp(Q_value[s][a]);\n        }\n\n        for(int j = 0 ; j < (int)(listOfActions.size()) ; j++ ){//foreach (Action a; model.A(s)) {\n            int a = listOfActions.at(j);\n            policy[s][a] = exp(Q_value[s][a]) / normalizer;\n        }\n    }\n    data.setExpertPolicy(policy);\n}\n\ndouble Process::calcInnerProduct(vector<double> v1, vector<double> v2){\n\n    double result = 0.0;\n    if(int(v1.size()) != int(v2.size())){\n        cout << \"Something is wrong in Process::calcInnerProduct\" << endl;\n        return 0.0;\n    }\n    for (int i = 0 ; i < int(v1.size()) ; i++){\n        result = result + v1.at(i) * v2.at(i);\n    }\n    return result;\n}\n\nvoid Process::printPolicy(map<vector<int>,map<int,double>> policy){\n    //    std::map< std::string, std::map<std::string, std::string> > m;\n\n    for (auto i : policy){\n        for (auto j : i.second){\n            cout << \" < \" << i.first.at(0) << \" , \" << i.first.at(1) << \" > , \" << j.first << \" ==> Pr = \" << j.second << endl;\n        }\n        cout << \"--------------------------------------------\" << endl;\n    }\n\n}\n\nvector<double> Process::multiply(double scalar, vector<double> v){\n    vector<double> result;\n    for (int i = 0 ; i < int(v.size()) ; i++){\n        result.push_back(scalar * v.at(i));\n    }\n    return result;\n}\n\nvector<double> Process::divide(double scalar, vector<double> v){\n    vector<double> result;\n    for (int i = 0 ; i < int(v.size()) ; i++){\n        result.push_back(v.at(i) / scalar);\n    }\n    return result;\n}\n\nvector<double> Process::add(vector<double> v1, vector<double> v2){\n    vector<double> result;\n    for (int i = 0 ; i < int(v1.size()) ; i++){\n        result.push_back(v1.at(i) + v2.at(i));\n    }\n    return result;\n}\n\ndouble Process::l1norm(vector<double> v){\n    double returnval = 0;\n    for (int i = 0 ; i < int(v.size()) ; i++){\n        returnval += abs(v.at(i));\n    }\n    return returnval;\n}\n\ndouble Process::l2norm(vector<double> v){\n    return sqrt(calcInnerProduct(v,v));\n}\n\nvoid Process::loadObsModel(Data &data){\n    vector<Sample> flatObsList;\n    string fileAddress = data.getObsModelAddress();\n    std::ifstream ifs(fileAddress);\n    boost::archive::text_iarchive ia(ifs);\n    ia >> flatObsList;\n    vector<double> * low  = data.getLow();\n    vector<double> * high = data.getHigh();\n    DETree observationModel(flatObsList, low, high);\n    data.setObsModel(observationModel);\n}\n\n\nvoid Process::saveObsModel(Data &data){\n    vector<Sample> flatObsList = data.getFlatObsList();\n    ofstream myfile;\n    string fileAddress = data.getObsModelAddress();\n    myfile.open (fileAddress.c_str());\n    std::ofstream ofs(fileAddress.c_str());\n    boost::archive::text_oarchive oa(ofs);\n    // write class instance to archive\n    oa << flatObsList;\n}\n\n//changed\nbool  Process::areAdj(vector<int> currentState, vector<int> nextState){\n    int rawState1 = currentState.at(0);\n    int rawState2 = nextState.at(0);\n    if(rawState1 - rawState2 == 0){\n        return true;\n    }else if(rawState2 - rawState1 == 1 && currentState.at(1) == nextState.at(1)){\n        return true;\n    }\n    return false;\n}\n\nvector<double> Process::normalize(vector<double> v){\n    double sum = 0;\n    vector<double> result;\n    for (int i = 0 ; i < int(v.size()) ; i++){\n        sum = sum + v.at(i);\n    }\n    for (int i = 0 ; i < int(v.size()) ; i++){\n        result.push_back(v.at(i) / sum);\n    }\n    return result;\n}\n\nvector<double> Process::getFeatureVectorOfT(Data &data,vector<vector<int>> t){\n    vector<double> fv(data.getNumberOfFeatures(),0.0);\n    for(int i = 0 ; i < int(t.size()) ; i++){\n        vector<int> state;\n        state.push_back(t.at(i).at(0));\n        state.push_back(t.at(i).at(1));\n        int action = t.at(i).at(2);\n        fv = add(fv, getFeatures(data,state,action));\n    }\n    return fv;\n}\n\nvoid Process::saveDeterministicObsModel(Data &data){\n    vector<vector<int>> listOfStates = data.getListOfStates();\n    vector<int> listOfActions = data.getListOfActions();\n\n    for(int i = 0 ; i < int(listOfStates.size()) ; i++){\n        vector<int> firstState = listOfStates.at(i);\n        for(int j = 0 ; j < int(listOfActions.size()) ; j++){\n            int action = listOfActions.at(j);\n            vector<int> secondState = returnNextState(data,firstState,action);\n            vector<double> firstPoint = getCenterPointInState(firstState.at(0));\n            vector<double> secondPoint = getCenterPointInState(secondState.at(0));\n            vector<double> obs = getObsSampleList(data,firstPoint, secondPoint);\n            updateFlatObsList(data,firstState,action,obs,true);\n        }\n    }\n    vector<Sample> flatObsList = data.getFlatObsList();\n    ofstream myfile;\n    string fileAddress = data.getObsModelAddress();\n    myfile.open (fileAddress.c_str());\n    std::ofstream ofs(fileAddress.c_str());\n    boost::archive::text_oarchive oa(ofs);\n    // write class instance to archive\n    oa << flatObsList;\n}\n\nvoid Process::loadDeterministicObsModel(Data &data){\n    vector<Sample> dObsModel;\n    string fileAddress = data.getObsModelAddress();\n    std::ifstream ifs(fileAddress);\n    boost::archive::text_iarchive ia(ifs);\n    ia >> dObsModel;\n    data.setDeterministicObsModel(dObsModel);\n}\n\nvoid Process::saveClusteringObsModel(Data &data, int dataPerStateActionPair){\n    vector<vector<int>> listOfStates = data.getListOfStates();\n    vector<int> listOfActions = data.getListOfActions();\n    int numberOfSamples = data.getNumberOfSamples();\n    vector<Sample> clusteringObsModel;\n    for(int i = 0 ; i < int(listOfStates.size()) ; i++){\n        vector<int> firstState = listOfStates.at(i);\n        for(int j = 0 ; j < int(listOfActions.size()) ; j++){\n            int action = listOfActions.at(j);\n            Sample centroid;\n            centroid.p = 0; //I not using p in here so just assign zero\n            double slopeSum = 0.0;\n            double intercepSum = 0.0;\n\n            for(int k = 0 ; k < dataPerStateActionPair ; k++){\n                // I was using returnNextState(data,firstState,action)\n                // I have to use transitionFunction(data,firstState,action);\n                // to handle stochastic T in observation\n                //                vector<int> secondState = returnNextState(data,firstState,action);\n                vector<int> secondState = transitionFunction(data,firstState,action);\n                vector<double> firstPoint = getCenterPointInState(firstState.at(0));\n                vector<double> secondPoint = getCenterPointInState(secondState.at(0));\n                vector<double> obs = getObsSampleList(data,firstPoint, secondPoint);\n                vector<double> time_x = data.getTimeChunk();\n\n                Maths::Regression::Linear linearRegression(numberOfSamples, time_x, obs); //Intensity_y = Obs\n                double slope =linearRegression.getSlope();\n                slopeSum = slopeSum + slope;\n                double intercept =linearRegression.getIntercept();\n                intercepSum = intercepSum + intercept;\n            }\n            centroid.values.push_back(slopeSum / dataPerStateActionPair);\n            centroid.values.push_back(intercepSum / dataPerStateActionPair);\n            centroid.values.push_back(firstState.at(0));\n            centroid.values.push_back(firstState.at(1));\n            centroid.values.push_back(action);\n            clusteringObsModel.push_back(centroid);\n        }\n    }\n\n    ofstream myfile;\n    string fileAddress = data.getObsModelAddress();\n    myfile.open (fileAddress.c_str());\n    std::ofstream ofs(fileAddress.c_str());\n    boost::archive::text_oarchive oa(ofs);\n    // write class instance to archive\n    oa << clusteringObsModel;\n}\n\nvoid Process::loadClusteringObsModel(Data &data){\n    vector<Sample> cObsModel;\n    string fileAddress = data.getObsModelAddress();\n    std::ifstream ifs(fileAddress);\n    boost::archive::text_iarchive ia(ifs);\n    ia >> cObsModel;\n    data.setClusteringObsModel(cObsModel);\n}\n", "meta": {"hexsha": "cf31e8469802fcf1407523b4deff274a687ce662", "size": 28295, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/process.cpp", "max_stars_repo_name": "shervinf66/Robust_IRL_TOY", "max_stars_repo_head_hexsha": "2dcab9178be7ba1093033d7e8b11957c184a888d", "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/process.cpp", "max_issues_repo_name": "shervinf66/Robust_IRL_TOY", "max_issues_repo_head_hexsha": "2dcab9178be7ba1093033d7e8b11957c184a888d", "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/process.cpp", "max_forks_repo_name": "shervinf66/Robust_IRL_TOY", "max_forks_repo_head_hexsha": "2dcab9178be7ba1093033d7e8b11957c184a888d", "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.6360201511, "max_line_length": 247, "alphanum_fraction": 0.5998586323, "num_tokens": 6884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.26056428473556403}}
{"text": "#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n\n#include <cmath>\n#include <cstring>\n#include <memory>\n#include <vector>\n#include <limits>\n#include <algorithm>\n#include <utility>\n#include <iterator>\n\n#include \"statespace.hpp\"\n\nusing namespace boost::numeric::ublas;\n\nclass ChangeEvent {\n  /* struct (supporting comparison) representing\n     a change-of-active-SSMs event. */\npublic:\n  int t;\n  int i_ssm;\n  bool is_start;\n  friend bool operator< (const ChangeEvent &c1, const ChangeEvent &c2);\n};\n\nbool operator< (const ChangeEvent &c1, const ChangeEvent &c2) {\n    if (c1.t < c2.t) {\n      return true;\n    } else if (c1.t == c2.t) {\n      // ends come before starts\n      return c1.is_start > c2.is_start;\n    }\n    return false;\n  }\n\n\n\nint active_set_dimension(const std::vector<StateSpaceModel *> & ssms, vector<int> & active_set) {\n  vector<int>::const_iterator it;\n  int dimension = 0;\n  for (it = active_set.begin(); it < active_set.end(); ++it) {\n    if (*it < 0) continue;\n    StateSpaceModel *ssm = ssms[*it];\n    if (!ssm) continue;\n    dimension += ssm->max_dimension;\n  }\n  return dimension;\n}\n\n\nTransientCombinedSSM::TransientCombinedSSM(\\\n       std::vector<StateSpaceModel *> & ssms, const vector<int> & start_idxs,\n       const vector<int> & end_idxs, const std::vector<const double * > & scales,\n       double obs_noise) : ssms(ssms), start_idxs(start_idxs),\n\t\t\t   end_idxs(end_idxs), scales(scales),\n\t\t\t   obs_noise(obs_noise), n_ssms(ssms.size()),\n\t\t\t   active_ssm_cache1_k(-1), active_ssm_cache2_k(-1) {\n\n  this->ssms_tmp.resize(this->n_ssms);\n  this->n_steps = *(max_element(end_idxs.begin(), end_idxs.end()));\n\n  /* Compute a list of ChangeEvents, each representing the\n   * activation or deactivation of a component SSM. The\n   * list is sorted by the timestep at which the event\n   * occurs (and secondarily, with deactivation events at\n   * a timestep before activation events). */\n  std::vector<ChangeEvent> events(start_idxs.size() + end_idxs.size());\n  for (unsigned i=0; i < n_ssms; ++i) {\n    events[2*i].t = start_idxs[i];\n    events[2*i].i_ssm = i;\n    events[2*i].is_start = true;\n\n    events[2*i+1].t = end_idxs[i];\n    events[2*i+1].i_ssm = i;\n    events[2*i+1].is_start = false;\n  }\n  std::sort(events.begin(), events.end());\n\n  /*\n     Build a sorted list of changepoints (timesteps at which the set of active\n     SSMs changes), along with the set of active SSMs at each changepoint.\n     Also compute the max total dimension of the state space, by computing the\n     dimension of each active set as we add it to the active_sets matrix.\n   */\n  // allocate the active_sets matrix by first computing the largest number of\n  // SSMs that might be active at one time\n  unsigned int n_active = 0;\n  unsigned int max_active = 0;\n  for(std::vector<ChangeEvent>::const_iterator idx = events.begin(); idx < events.end(); ++idx) {\n    if (idx->is_start) n_active++; else n_active--;\n    if (n_active > max_active) max_active = n_active;\n  }\n  active_sets.resize(2*n_ssms, max_active);\n\n  vector<int> active_set(max_active);\n  for (unsigned i=0; i < max_active; ++i) active_set(i) = -1;\n  int t_prev = events[0].t, max_dimension = 0, i=0;\n  std::vector<ChangeEvent>::const_iterator idx;\n  for(i=0, idx = events.begin();\n      idx < events.end(); ++idx) {\n\n    // printf(\"event t %d i_ssm %d start %s\\n\", idx->t, idx->i_ssm, idx->is_start ? \"true\" : \"false\");\n\n    // if this represents a change, add a new changepoint\n    if (idx->t != t_prev) {\n      changepoints.push_back(t_prev);\n\n      // printf(\" change detected (t_prev %d), copying to active_set %d\\n\", t_prev, i);\n\n      // copy the current active set of SSMs\n      // into the active_sets matrix (terminated with -1)\n      for (unsigned k=0, j=0; k < max_active; ++k) {\n\tif (active_set(k) >= 0) {\n\t  active_sets(i, j++) = active_set(k);\n\t}\n\tif (j < max_active) {\n\t  active_sets(i, j) = -1;\n\t}\n      }\n\n      /*printf(\"matr active set(%d, ...) is\", i);\n      for(int tmpi=0; tmpi < max_active; ++tmpi) {\n\tprintf(\" %d\", active_sets(i, tmpi));\n      }\n      printf(\"\\n\");*/\n\n\n      t_prev = idx->t;\n      i++;\n\n      int current_dim = active_set_dimension(this->ssms, active_set);\n      if (current_dim > max_dimension) max_dimension = current_dim;\n    }\n\n    // update the active set: add the new SSM if this\n    // is a start event, otherwise remove it from\n    // the active set.\n    vector<int>::iterator it;\n    if (idx->is_start) {\n      it = std::find (active_set.begin(), active_set.end(), -1);\n      if (it == active_set.end()) {\n\tprintf(\"ERROR: need to start new SSM but no room in active_set vector!\\n\");\n\texit(-1);\n      } else {\n\t*it = idx->i_ssm;\n      }\n    } else {\n      it = std::find (active_set.begin(), active_set.end(), idx->i_ssm);\n      if (it == active_set.end()) {\n\tprintf(\"ERROR: trying to remove SSM %d but it is not present in the active_set vector!\\n\", idx->i_ssm);\n\texit(-1);\n      } else {\n\t*it = -1;\n      }\n    }\n\n\n  }\n\n  this->max_dimension = max_dimension;\n  this->is_cssm = false;\n}\n\nTransientCombinedSSM::~TransientCombinedSSM() {\n\n\n  return;\n};\n\nint TransientCombinedSSM::active_set_idx(int k) {\n  if (k == this->active_ssm_cache1_k)\n    return this->active_ssm_cache1_v;\n  else if (k == this->active_ssm_cache2_k)\n    return this->active_ssm_cache2_v;\n\n  std::vector<int>::iterator it = std::upper_bound(this->changepoints.begin(), this->changepoints.end(), k);\n  int i = it - this->changepoints.begin() - 1;\n\n  /*printf(\"active set at time k=%d is %d, changepoints %d %d %d %d\\n\", k, i,\n\t i-1 >= 0 ? this->changepoints[i-1] : -1,\n\t i >= 0 ? this->changepoints[i] : -1,\n\t i+1 < this->changepoints.size() ? this->changepoints[i+1] : -1,\n\t i+2 < this->changepoints.size() ? this->changepoints[i+2] : -1);*/\n\n  this->active_ssm_cache2_k = this->active_ssm_cache1_k;\n  this->active_ssm_cache2_v = this->active_ssm_cache1_v;\n  this->active_ssm_cache1_k = k;\n  this->active_ssm_cache1_v = i;\n  return i;\n}\n\n\nunsigned int TransientCombinedSSM::state_size_at_timestep(unsigned int k) {\n\n  unsigned int total_state_size = 0;\n\n  int asidx = this->active_set_idx(k);\n  if (asidx < 0) {\n    return 0;\n  }\n\n  matrix_row < matrix<int> > ssm_indices = row(this->active_sets, asidx);\n  for (matrix_row < matrix<int> >::const_iterator it = ssm_indices.begin();\n       it < ssm_indices.end() && *it >= 0; ++it) {\n\n    int i_ssm = *it;\n    StateSpaceModel * ssm = this->ssms[i_ssm];\n    if (!ssm) continue;\n\n    unsigned int state_size = ssm->max_dimension;\n    total_state_size += state_size;\n  }\n  return total_state_size;\n}\n\nint TransientCombinedSSM::apply_transition_matrix(const double * x, int k, double * result) {\n\n  // first, loop over ssms active at the *previous*\n  // timestep in order to cache the location of each\n  // ssm in the previous state space.\n  int j = 0;\n  int asidx_prev = this->active_set_idx(k-1);\n  int asidx = this->active_set_idx(k);\n  bool same_active_set = (asidx==asidx_prev);\n\n  if (k == 0) {\n    printf(\"ERROR: requested transition INTO timestep 0 (invalid)!\");\n    exit(-1);\n  }\n\n  if (asidx < 0) {\n    return 0;\n  }\n\n  if (!same_active_set) {\n    matrix_row < matrix<int> > old_ssm_indices = row(this->active_sets, asidx_prev);\n    for (matrix_row < matrix<int> >::const_iterator it = old_ssm_indices.begin();\n\t it < old_ssm_indices.end() && *it >= 0; ++it) {\n\n      // skip any null SSMs\n      int i_ssm = *it;\n      StateSpaceModel * ssm = this->ssms[i_ssm];\n      if (!ssm) continue;\n\n      this->ssms_tmp[i_ssm] = j;\n      j += ssm->max_dimension;\n    }\n  }\n\n  //printf(\"transition to time %d (asidx %d, %d):\\n\",  k, asidx_prev, asidx);\n\n  // now apply the transition to the current time\n  int i=0;\n  matrix_row < matrix<int> > ssm_indices = row(this->active_sets, asidx);\n  for (matrix_row < matrix<int> >::const_iterator it = ssm_indices.begin();\n       it < ssm_indices.end() && *it >= 0; ++it) {\n\n    // skip any null SSMs\n    int i_ssm = *it;\n    StateSpaceModel * ssm = this->ssms[i_ssm];\n    if (!ssm) continue;\n\n    unsigned int state_size = ssm->max_dimension;\n    if (this->start_idxs[i_ssm] == k) {\n      /* new ssms just get filled in as zero\n         (prior means will be added by the\n         transition_bias operator) */\n      for (unsigned j=i; j < i+state_size; ++j) {\n\tresult[j] = 0;\n      }\n      //printf(\"   new ssm %d active from %d to %d\\n\", i_ssm, i, i+state_size);\n\n    } else {\n      /* this ssm is persisting from the\n       * previous timestep, so just run the\n       * transition */\n      unsigned int j = same_active_set ? i : this->ssms_tmp[i_ssm];\n\n      ssm->apply_transition_matrix(x+j, k-this->start_idxs[i_ssm], result+i);\n      //printf(\"   transitioning ssm %d, prev %d, in state %d to %d (sidx %d eidx %d)\\n\", i_ssm, j, i, i+state_size, this->start_idxs[i_ssm], this->end_idxs[i_ssm]);\n    }\n    i += state_size;\n  }\n  return i;\n}\n\nint TransientCombinedSSM::apply_transition_matrix( const matrix<double> &X,\n\t\t\t\t\t\t   unsigned int x_row_offset,\n\t\t\t\t\t\t   int k,\n\t\t\t\t\t\t   matrix<double> &result,\n\t\t\t\t\t\t   unsigned int r_row_offset,\n\t\t\t\t\t\t   unsigned int n) {\n  int j = x_row_offset;\n  int asidx_prev = this->active_set_idx(k-1);\n  int asidx = this->active_set_idx(k);\n  bool same_active_set = (asidx==asidx_prev);\n\n  if (asidx < 0) {\n    return 0;\n  }\n\n\n  if (!same_active_set) {\n    matrix_row < matrix<int> > old_ssm_indices = row(this->active_sets, asidx_prev);\n    for (matrix_row < matrix<int> >::const_iterator it = old_ssm_indices.begin();\n\t it < old_ssm_indices.end() && *it >= 0; ++it) {\n\n      // skip any null SSMs\n      int i_ssm = *it;\n      StateSpaceModel * ssm = this->ssms[i_ssm];\n      if (!ssm) continue;\n\n      this->ssms_tmp[i_ssm] = j;\n      j += ssm->max_dimension;\n    }\n  }\n\n  int i=x_row_offset;\n  matrix_row < matrix<int> > ssm_indices = row(this->active_sets, asidx);\n  for (matrix_row < matrix<int> >::const_iterator it = ssm_indices.begin();\n       it < ssm_indices.end() && *it >= 0; ++it) {\n\n    int i_ssm = *it;\n    StateSpaceModel * ssm = this->ssms[i_ssm];\n    if (!ssm) continue;\n\n    unsigned int state_size = ssm->max_dimension;\n    if (this->start_idxs[i_ssm] == k) {\n      /* new ssms just get filled in as zero\n         (prior means will be added by the\n         transition_bias operator) */\n      for (unsigned j=i; j < i+state_size; ++j) {\n\tfor (unsigned jj=0; jj < n; ++jj) result(j, jj) = 0;\n      }\n    } else {\n      unsigned int j = same_active_set ? i : this->ssms_tmp[i_ssm];\n      //printf(\"MATR transitioning ssm %d, prev %d, in state %d to %d (sidx %d eidx %d)\\n\", i_ssm, j, i, i+state_size, this->start_idxs[i_ssm], this->end_idxs[i_ssm]);\n      ssm->apply_transition_matrix(X, j, k-this->start_idxs[i_ssm], result, i, n);\n    }\n    i += state_size;\n  }\n  return i-x_row_offset;\n}\n\n\nvoid TransientCombinedSSM::transition_bias(int k, double *result) {\n\n  int asidx = this->active_set_idx(k);\n  if (asidx < 0) return;\n\n  matrix_row < matrix<int> > ssm_indices = row(this->active_sets, asidx);\n  for (matrix_row < matrix<int> >::const_iterator it = ssm_indices.begin();\n       it < ssm_indices.end() && *it >= 0; ++it) {\n\n    // skip any null SSMs\n    int j = *it;\n    StateSpaceModel * ssm = this->ssms[j];\n    if (!ssm) continue;\n\n    if (this->start_idxs[j] == k) {\n      ssm->prior_mean(result);\n    } else {\n      ssm->transition_bias(k-this->start_idxs[j], result);\n    }\n    result += ssm->max_dimension;\n  }\n}\n\n\nvoid TransientCombinedSSM::transition_noise_diag(int k, double *result) {\n  int asidx = this->active_set_idx(k);\n  if (asidx < 0) return;\n  matrix_row < matrix<int> > ssm_indices = row(this->active_sets, asidx);\n  for (matrix_row < matrix<int> >::const_iterator it = ssm_indices.begin();\n       it < ssm_indices.end() && *it >= 0; ++it) {\n\n    // skip any null SSMs\n    int j = *it;\n    StateSpaceModel * ssm = this->ssms[j];\n    if (!ssm) continue;\n\n    if (this->start_idxs[j] == k) {\n      ssm->prior_vars(result);\n    } else {\n      ssm->transition_noise_diag(k-this->start_idxs[j], result);\n    }\n    result += ssm->max_dimension;\n  }\n}\n\ndouble TransientCombinedSSM::apply_observation_matrix(const double *x, int k) {\n\n  double r = 0;\n\n  int asidx = this->active_set_idx(k);\n  if (asidx < 0) return 0.0;\n  matrix_row < matrix<int> > ssm_indices = row(this->active_sets, asidx);\n  for (matrix_row < matrix<int> >::const_iterator it = ssm_indices.begin();\n       it < ssm_indices.end() && *it >= 0; ++it) {\n\n    int j = *it;\n    StateSpaceModel * ssm = this->ssms[j];\n    if (!ssm) continue;\n    const double * scale = this->scales[j];\n    double ri = ssm->apply_observation_matrix(x, k - this->start_idxs[j]);\n    if (scale) ri *= scale[k - this->start_idxs[j]];\n    r += ri;\n    if (ssm) x += ssm->max_dimension;\n  }\n  return r;\n}\n\nvoid TransientCombinedSSM::apply_observation_matrix(const matrix<double> &X,\n\t\t\t\t\t\t    unsigned int row_offset, int k,\n\t\t\t\t\t\t    double *result, double *result_tmp, unsigned int n) {\n\n  for (unsigned i=0; i < n; ++i) {\n    result[i] = 0;\n    result_tmp[i] = 0;\n  }\n\n  int asidx = this->active_set_idx(k);\n  if (asidx < 0) return;\n\n  matrix_row < matrix<int> > ssm_indices = row(this->active_sets, asidx);\n  for (matrix_row < matrix<int> >::const_iterator it = ssm_indices.begin();\n       it < ssm_indices.end() && *it >= 0; ++it) {\n    int j = *it;\n    StateSpaceModel * ssm = this->ssms[j];\n    if (!ssm) continue;\n    const double * scale = this->scales[j];\n\n    unsigned int state_size = ssm->max_dimension;\n    ssm->apply_observation_matrix(X, row_offset,\n\t\t\t\t  k-this->start_idxs[j],\n\t\t\t\t  result_tmp, NULL, n);\n    // printf(\"TSSM step %d applying obs matrix on ssm %d state_size %d start_idx %d at row_offset %d n %d scale[%d] %f result[0] %f\\n\", k, j, state_size, this->start_idxs[j], row_offset, n, k-this->start_idxs[j], scale? scale[k-this->start_idxs[j]] : 1.0, result_tmp[0]);\n    if (scale) {\n      for (unsigned ii=0; ii < n; ++ii) {\n\tresult[ii] += scale[k-this->start_idxs[j]] * result_tmp[ii];\n      }\n    } else {\n      for (unsigned ii=0; ii < n; ++ii) {\n\tresult[ii] += result_tmp[ii];\n      }\n    }\n    row_offset += state_size;\n  }\n\n\n}\n\ndouble TransientCombinedSSM::observation_bias(int k) {\n  double bias = 0;\n\n  int asidx = this->active_set_idx(k);\n  if (asidx < 0) return 0.0;\n  matrix_row < matrix<int> > ssm_indices = row(this->active_sets, asidx);\n  for (matrix_row < matrix<int> >::const_iterator it = ssm_indices.begin();\n       it < ssm_indices.end() && *it >= 0; ++it) {\n\n    // skip any null SSMs\n    int j = *it;\n    StateSpaceModel * ssm = this->ssms[j];\n    const double * scale = this->scales[j];\n    int kk = k - this->start_idxs[j];\n\n    double b = ssm ? ssm->observation_bias(kk) : 1.0;\n    if (scale) b *= scale[kk];\n    bias += b;\n  }\n  return bias;\n}\n\ndouble TransientCombinedSSM::observation_noise(int k) {\n  return this->obs_noise;\n}\n\nbool TransientCombinedSSM::stationary(int k) {\n\n  matrix_row < matrix<int> > s1 = row(this->active_sets, this->active_set_idx(k));\n  if (k > 0) {\n    matrix_row < matrix<int> > s2 = row(this->active_sets, this->active_set_idx(k-1));\n    for (unsigned i=0; i < s1.size() && !(s1(i) == -1 && s2(i) == -1); ++i) {\n      if (s1(i) != s2(i)) return false;\n    }\n  }\n\n  for (matrix_row < matrix<int> >::const_iterator it = s1.begin();\n       it < s1.end() && *it >= 0; ++it) {\n    // skip any null SSMs\n    int j = *it;\n    if (this->scales[j]) return false;\n\n    StateSpaceModel * ssm = this->ssms[j];\n    if (ssm && !ssm->stationary(k-this->start_idxs[j])) return false;\n  }\n  return true;\n}\n\nint TransientCombinedSSM::prior_mean(double *result) {\n\n  /*\n     TODO: propagate through the forward model whenever\n   */\n\n  double * r1 = result;\n  int asidx = this->active_set_idx(0);\n  if (asidx < 0) return 0;\n  matrix_row < matrix<int> > ssm_indices = row(this->active_sets, asidx);\n  for (matrix_row < matrix<int> >::const_iterator it = ssm_indices.begin();\n       it < ssm_indices.end() && *it >= 0; ++it) {\n\n    int j = *it;\n    StateSpaceModel * ssm = this->ssms[j];\n    if (!ssm) continue;\n\n    int state_size = ssm->max_dimension;\n    for(int i=0; i < state_size; ++i) {\n      result[i] = 0;\n    }\n    ssm->prior_mean(result);\n\n    /* if this component starts at a negative time, push the\n     * prior through the transition model to get the induced\n     * distribution at time zero */\n    if (this->start_idxs[j] < 0) {\n      double * tmp_result = (double *) malloc(sizeof(double) * ssm->max_dimension);\n      if (tmp_result==NULL) {\n\tprintf(\"memory error, malloc failed!\\n\");\n\texit(-1);\n      }\n      for (unsigned k=1; k <= -this->start_idxs[j]; ++k) {\n\tssm->apply_transition_matrix(result, k, tmp_result);\n\tssm->transition_bias(k, tmp_result);\n\tmemcpy(result, tmp_result, ssm->max_dimension);\n      }\n      free(tmp_result);\n    }\n\n    result += state_size;\n  }\n  return result-r1;\n}\n\nint TransientCombinedSSM::prior_vars(double *result) {\n  double * r1 = result;\n  int asidx = this->active_set_idx(0);\n  if (asidx < 0) return 0;\n  matrix_row < matrix<int> > ssm_indices = row(this->active_sets, asidx);\n  for (matrix_row < matrix<int> >::const_iterator it = ssm_indices.begin();\n       it < ssm_indices.end() && *it >= 0; ++it) {\n\n    int j = *it;\n    StateSpaceModel * ssm = this->ssms[j];\n    if (!ssm) continue;\n    ssm->prior_vars(result);\n\n    /*printf(\"ssm %d max dimension %d\\n\", j, ssm->max_dimension);\n    for (double * q = result; q < result+ssm->max_dimension; ++q) {\n      printf(\" initial var %d = %f\\n\", q-result, *q);\n      }*/\n\n    if (this->start_idxs[j] < 0) {\n      matrix<double> P (ssm->max_dimension, ssm->max_dimension);\n      matrix<double> P2 (ssm->max_dimension, ssm->max_dimension);\n      P.clear();\n      for (int i=0; i < ssm->max_dimension; ++i) {\n\tP(i,i) = result[i];\n      }\n\n      for (unsigned k=1; k <= -this->start_idxs[j]; ++k) {\n\tssm->apply_transition_matrix(P, 0, k, P2, 0, ssm->max_dimension); // P2 = FP\n\tnoalias(P) = trans(P2); // P = PF'\n\tssm->apply_transition_matrix(P, 0, k, P2, 0, ssm->max_dimension); // P2 = FPF'\n\tP = P2;\n\tssm->transition_noise_diag(k, result);\n\tfor (int i=0; i < ssm->max_dimension; ++i) P(i,i) += result[i];\n      }\n      for (int i=0; i < ssm->max_dimension; ++i) result[i] = P(i,i);\n    }\n\n    /*for (double * q = result; q < result+ssm->max_dimension; ++q) {\n      printf(\" post-prop var %d = %f\\n\", q-result, *q);\n      }*/\n\n\n    result += ssm->max_dimension;\n  }\n\n\n  /*for (double * q = r1; q < result; ++q) {\n    printf(\"prior var %d = %f\\n\", q-r1, *q);\n    }*/\n\n  return result-r1;\n}\n\nvoid TransientCombinedSSM::init_coef_priors(std::vector<vector<double> > & cmeans,\n\t\t\t\t\t    std::vector<vector<double> > & cvars) {\n  for (unsigned j=0; j < this->n_ssms; ++j) {\n    StateSpaceModel * ssm = this->ssms[j];\n    if (ssm && ssm->is_cssm) {\n      CompactSupportSSM *cssm = (CompactSupportSSM *) ssm;\n      vector<double> mean(cssm->coef_means);\n      vector<double> var(cssm->coef_vars);\n      cmeans.push_back(mean);\n      cvars.push_back(var);\n    } else {\n      vector<double> mean;\n      vector<double> var;\n      cmeans.push_back(mean);\n      cvars.push_back(var);\n    }\n  }\n}\n\n\nvoid TransientCombinedSSM::extract_all_coefs(FilterState &cache, int k,\n\t\t\t\t\t     std::vector<vector<double> > & cmeans,\n\t\t\t\t\t     std::vector<vector<double> > & cvars) {\n  /*\n    Assumes cache has a valid, current P matrix.\n   */\n  int asidx = this->active_set_idx(k);\n  if (asidx < 0) return;\n  matrix_row < matrix<int> > ssm_indices = row(this->active_sets, asidx);\n  unsigned int state_offset = 0;\n  for (matrix_row < matrix<int> >::const_iterator it = ssm_indices.begin();\n       it < ssm_indices.end() && *it >= 0; ++it) {\n\n    int j = *it;\n    StateSpaceModel * ssm = this->ssms[j];\n    if (!ssm) continue;\n    if (ssm->is_cssm) {\n      CompactSupportSSM *cssm = (CompactSupportSSM *) ssm;\n      cssm->extract_coefs(cache.xk, cache.P,\n\t\t\t state_offset, k - this->start_idxs[j],\n\t\t\t cmeans[j],\n\t\t\t cvars[j]);\n    }\n    state_offset += ssm->max_dimension;\n  }\n}\n\nvoid TransientCombinedSSM::extract_component_means(double *xk, int k,\n\t\t\t\t\t\t   std::vector<vector<double> > & means) {\n  int asidx = this->active_set_idx(k);\n  if (asidx < 0) return;\n  matrix_row < matrix<int> > ssm_indices = row(this->active_sets, asidx);\n  unsigned int state_offset = 0;\n  for (matrix_row < matrix<int> >::const_iterator it = ssm_indices.begin();\n       it < ssm_indices.end() && *it >= 0; ++it) {\n\n    int j = *it;\n    StateSpaceModel * ssm = this->ssms[j];\n    int kk = k - this->start_idxs[j];\n    means[j](kk) = ssm ? ssm->apply_observation_matrix(xk + state_offset, kk) : 1.0;\n    means[j](kk) += ssm ? ssm->observation_bias(kk) : 0.0;\n    if (ssm) state_offset += ssm->max_dimension;\n  }\n}\n\nvoid TransientCombinedSSM::extract_component_vars(matrix<double> &P, matrix<double> &P_tmp, int k,\n\t\t\t\t\t\t  std::vector<vector<double> > & vars) {\n  int asidx = this->active_set_idx(k);\n  if (asidx < 0) return;\n  matrix_row < matrix<int> > ssm_indices = row(this->active_sets, asidx);\n  unsigned int state_offset = 0;\n\n  double * v_tmp = (double *) malloc(sizeof(double) * P.size1());\n  double * v_tmp2 = (double *) malloc(sizeof(double) * P.size1());\n  if (!v_tmp || !v_tmp2) {\n    printf(\"memory allocation error in extract_component_vars!\");\n    exit(-1);\n  }\n\n\n  for (matrix_row < matrix<int> >::const_iterator it = ssm_indices.begin();\n       it < ssm_indices.end() && *it >= 0; ++it) {\n\n    int j = *it;\n    StateSpaceModel * ssm = this->ssms[j];\n    int kk = k - this->start_idxs[j];\n\n    if (ssm) {\n      // just be lazy and copy the submatrix for this component into its own matrix.\n      subrange(P_tmp, 0, ssm->max_dimension, 0, ssm->max_dimension) = subrange(P, state_offset, state_offset+ssm->max_dimension, state_offset, state_offset+ssm->max_dimension);\n      ssm->apply_observation_matrix(P_tmp, 0, kk, v_tmp, v_tmp2, ssm->max_dimension);\n      vars[j](kk) = ssm->apply_observation_matrix(v_tmp, kk);\n      state_offset += ssm->max_dimension;\n      //printf(\"%d: set var at ssm %d kk %d = %f\\n\", k, j, kk, vars[j](kk));\n    } else {\n      vars[j](kk) = 0.0;\n    }\n  }\n\n  free(v_tmp);\n  free(v_tmp2);\n}\n", "meta": {"hexsha": "888fb6da2f3f9d92199e55594465861cb872c42b", "size": 22163, "ext": "cc", "lang": "C++", "max_stars_repo_path": "models/statespace/fast_c/transient_combined.cc", "max_stars_repo_name": "davmre/sigvisa", "max_stars_repo_head_hexsha": "91a1f163b8f3a258dfb78d88a07f2a11da41bd04", "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/statespace/fast_c/transient_combined.cc", "max_issues_repo_name": "davmre/sigvisa", "max_issues_repo_head_hexsha": "91a1f163b8f3a258dfb78d88a07f2a11da41bd04", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/statespace/fast_c/transient_combined.cc", "max_forks_repo_name": "davmre/sigvisa", "max_forks_repo_head_hexsha": "91a1f163b8f3a258dfb78d88a07f2a11da41bd04", "max_forks_repo_licenses": ["BSD-3-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.4815340909, "max_line_length": 272, "alphanum_fraction": 0.6242837161, "num_tokens": 6735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.2605642776960263}}
{"text": "/* pcmsolver_copyright_start */\n/*\n *     PCMSolver, an API for the Polarizable Continuum Model\n *     Copyright (C) 2013-2016 Roberto Di Remigio, Luca Frediani and contributors\n *     \n *     This file is part of PCMSolver.\n *     \n *     PCMSolver is free software: you can redistribute it and/or modify\n *     it under the terms of the GNU Lesser General Public License as published by\n *     the Free Software Foundation, either version 3 of the License, or\n *     (at your option) any later version.\n *     \n *     PCMSolver is distributed in the hope that it will be useful,\n *     but WITHOUT ANY WARRANTY; without even the implied warranty of\n *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *     GNU Lesser General Public License for more details.\n *     \n *     You should have received a copy of the GNU Lesser General Public License\n *     along with PCMSolver.  If not, see <http://www.gnu.org/licenses/>.\n *     \n *     For information on the complete list of contributors to the\n *     PCMSolver API, see: <http://pcmsolver.readthedocs.io/>\n */\n/* pcmsolver_copyright_end */\n\n#ifndef GREENUTILS_HPP\n#define GREENUTILS_HPP\n\n#include \"Config.hpp\"\n\n#include <Eigen/Core>\n\n#include \"DerivativeTypes.hpp\"\n#include \"utils/Stencils.hpp\"\n\nnamespace GreenUtils {\n/*! Returns value of the directional derivative of the function passed for the pair of points p1, p2:\n *  \\f$ \\nabla_{\\mathbf{p_2}}G(\\mathbf{p}_1, \\mathbf{p}_2)\\cdot \\mathbf{n}_{\\mathbf{p}_2}\\f$\n *  Notice that this method returns the directional derivative with respect\n *  to the probe point.\n *  \\tparam DerivativeTraits evaluation strategy for the function and its derivatives\n *  \\param[in] functor   function-object handle to the evaluation of the differentiable function\n *  \\param[in] normal_p2 the normal vector to p2\n *  \\param[in]        p1 first point\n *  \\param[in]        p2 second point\n */\ntemplate <typename DerivativeTraits>\ndouble derivativeProbe(const pcm::function<DerivativeTraits(DerivativeTraits *, DerivativeTraits *)> & functor,\n                       const Eigen::Vector3d & normal_p2, const Eigen::Vector3d & p1, const Eigen::Vector3d & p2)\n{\n    DerivativeTraits t1[3], t2[3], der;\n    t1[0] = p1(0); t1[1] = p1(1); t1[2] = p1(2);\n    t2[0] = p2(0); t2[1] = p2(1); t2[2] = p2(2);\n    t2[0][1] = normal_p2(0); t2[1][1] = normal_p2(1); t2[2][1] = normal_p2(2);\n    der = functor(t1, t2);\n    return der[1];\n}\n\n/*! Returns value of the directional derivative of the function passed for the pair of points p1, p2:\n *  \\f$ \\nabla_{\\mathbf{p_1}}G(\\mathbf{p}_1, \\mathbf{p}_2)\\cdot \\mathbf{n}_{\\mathbf{p}_1}\\f$\n *  Notice that this method returns the directional derivative with respect\n *  to the source point.\n *  \\tparam DerivativeTraits evaluation strategy for the function and its derivatives\n *  \\param[in] functor   function-object handle to the evaluation of the differentiable function\n *  \\param[in] normal_p1 the normal vector to p1\n *  \\param[in]        p1 first point\n *  \\param[in]        p2 second point\n */\ntemplate <typename DerivativeTraits>\ndouble derivativeSource(const pcm::function<DerivativeTraits(DerivativeTraits *, DerivativeTraits *)> & functor,\n                        const Eigen::Vector3d & normal_p1, const Eigen::Vector3d & p1, const Eigen::Vector3d & p2)\n{\n    DerivativeTraits t1[3], t2[3], der;\n    t1[0] = p1(0); t1[1] = p1(1); t1[2] = p1(2);\n    t1[0][1] = normal_p1(0); t1[1][1] = normal_p1(1); t1[2][1] = normal_p1(2);\n    t2[0] = p2(0); t2[1] = p2(1); t2[2] = p2(2);\n    der = functor(t1, t2);\n    return der[1];\n}\n\n/*! Returns value of the directional derivative of the function passed for the pair of points p1, p2:\n *  \\f$ \\nabla_{\\mathbf{p_2}}G(\\mathbf{p}_1, \\mathbf{p}_2)\\cdot \\mathbf{n}_{\\mathbf{p}_2}\\f$\n *  Notice that this method returns the directional derivative with respect\n *  to the probe point.\n *  \\param[in] functor   function-object handle to the evaluation of the differentiable function\n *  \\param[in] normal_p2 the normal vector to p2\n *  \\param[in]        p1 first point\n *  \\param[in]        p2 second point\n */\ndouble derivativeProbe(const DifferentiableFunction & functor, const Eigen::Vector3d & normal_p2, const Eigen::Vector3d & p1, const Eigen::Vector3d & p2)\n{\n    return threePointStencil(pcm::bind(functor, pcm::_1, _2), p2, p1, normal_p2);\n}\n\n/*! Returns value of the directional derivative of the function passed for the pair of points p1, p2:\n *  \\f$ \\nabla_{\\mathbf{p_1}}G(\\mathbf{p}_1, \\mathbf{p}_2)\\cdot \\mathbf{n}_{\\mathbf{p}_1}\\f$\n *  Notice that this method returns the directional derivative with respect\n *  to the source point.\n *  \\param[in] functor   function-object handle to the evaluation of the differentiable function\n *  \\param[in] normal_p1 the normal vector to p1\n *  \\param[in]        p1 first point\n *  \\param[in]        p2 second point\n */\ndouble derivativeSource(const DifferentiableFunction & functor, const Eigen::Vector3d & normal_p1, const Eigen::Vector3d & p1, const Eigen::Vector3d & p2)\n{\n        return threePointStencil(pcm::bind(functor,_1, _2), p1, p2, normal_p1);\n}\n\n/*! Returns full gradient of the function passed for the pair of points p1, p2:\n *  \\f$ \\nabla_{\\mathbf{p_1}}G(\\mathbf{p}_1, \\mathbf{p}_2)\\f$\n *  Notice that this method returns the gradient with respect to the source point.\n *  \\tparam DerivativeTraits evaluation strategy for the function and its derivatives\n *  \\param[in] functor   function-object handle to the evaluation of the differentiable function\n *  \\param[in] p1 first point\n *  \\param[in] p2 second point\n */\ntemplate <typename DerivativeTraits>\nEigen::Vector3d gradientSource(const pcm::function<DerivativeTraits(DerivativeTraits *, DerivativeTraits *)> & functor,\n                               const Eigen::Vector3d & p1, const Eigen::Vector3d & p2)\n{\n    return (Eigen::Vector3d() << derivativeSource(functor, Eigen::Vector3d::UnitX(), p1, p2),\n                                 derivativeSource(functor, Eigen::Vector3d::UnitY(), p1, p2),\n                                 derivativeSource(functor, Eigen::Vector3d::UnitZ(), p1, p2)).finished();\n}\n\n/*! Returns full gradient of the function passed for the pair of points p1, p2:\n *  \\f$ \\nabla_{\\mathbf{p_2}}G(\\mathbf{p}_1, \\mathbf{p}_2)\\f$\n *  Notice that this method returns the gradient with respect to the probe point.\n *  \\tparam DerivativeTraits evaluation strategy for the function and its derivatives\n *  \\param[in] functor   function-object handle to the evaluation of the differentiable function\n *  \\param[in] p1 first point\n *  \\param[in] p2 second point\n */\ntemplate <typename DerivativeTraits>\nEigen::Vector3d gradientProbe(const pcm::function<DerivativeTraits(DerivativeTraits *, DerivativeTraits *)> & functor,\n                              const Eigen::Vector3d & p1, const Eigen::Vector3d & p2)\n{\n    return (Eigen::Vector3d() << derivativeProbe(functor, Eigen::Vector3d::UnitX(), p1, p2),\n                                 derivativeProbe(functor, Eigen::Vector3d::UnitY(), p1, p2),\n                                 derivativeProbe(functor, Eigen::Vector3d::UnitZ(), p1, p2)).finished();\n}\n\n/*! Returns full gradient of the function passed for the pair of points p1, p2:\n *  \\f$ \\nabla_{\\mathbf{p_1}}G(\\mathbf{p}_1, \\mathbf{p}_2)\\f$\n *  Notice that this method returns the gradient with respect to the source point.\n *  \\param[in] functor   function-object handle to the evaluation of the differentiable function\n *  \\param[in] p1 first point\n *  \\param[in] p2 second point\n */\nEigen::Vector3d gradientSource(const DifferentiableFunction & functor, const Eigen::Vector3d & p1, const Eigen::Vector3d & p2)\n{\n    return (Eigen::Vector3d() << derivativeSource(functor, Eigen::Vector3d::UnitX(), p1, p2),\n                                 derivativeSource(functor, Eigen::Vector3d::UnitY(), p1, p2),\n                                 derivativeSource(functor, Eigen::Vector3d::UnitZ(), p1, p2)).finished();\n}\n\n/*! Returns full gradient of the function passed for the pair of points p1, p2:\n *  \\f$ \\nabla_{\\mathbf{p_2}}G(\\mathbf{p}_1, \\mathbf{p}_2)\\f$\n *  Notice that this method returns the gradient with respect to the probe point.\n *  \\param[in] functor   function-object handle to the evaluation of the differentiable function\n *  \\param[in] p1 first point\n *  \\param[in] p2 second point\n */\nEigen::Vector3d gradientProbe(const DifferentiableFunction & functor, const Eigen::Vector3d & p1, const Eigen::Vector3d & p2)\n{\n    return (Eigen::Vector3d() << derivativeProbe(functor, Eigen::Vector3d::UnitX(), p1, p2),\n                                 derivativeProbe(functor, Eigen::Vector3d::UnitY(), p1, p2),\n                                 derivativeProbe(functor, Eigen::Vector3d::UnitZ(), p1, p2)).finished();\n}\n} // namespace GreenUtils\n\n#endif // GREENUTILS_HPP\n", "meta": {"hexsha": "e6f27efdaa04797c64819d41be67234a5699b832", "size": 8788, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/PCMSolver/PCMSolver-source/src/green/GreenUtils.hpp", "max_stars_repo_name": "robertodr/externalize", "max_stars_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-02-15T22:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-15T22:16:34.000Z", "max_issues_repo_path": "external/PCMSolver/PCMSolver-source/src/green/GreenUtils.hpp", "max_issues_repo_name": "robertodr/externalize", "max_issues_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/PCMSolver/PCMSolver-source/src/green/GreenUtils.hpp", "max_forks_repo_name": "robertodr/externalize", "max_forks_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.7976878613, "max_line_length": 154, "alphanum_fraction": 0.6781975421, "num_tokens": 2502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.26047062330999227}}
{"text": "/*\n\n   Copyright (c) 2006-2010, The Scripps Research Institute\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\n   Author: Dr. Oleg Trott <ot14@columbia.edu>, \n           The Olson Lab, \n           The Scripps Research Institute\n\n*/\n\n#include \"monte_carlo.h\"\n#include \"coords.h\"\n#include \"mutate.h\"\n#include \"quasi_newton.h\"\n\n#include \"commonMacros.h\"\n#include \"wrapcl.h\"\n#include \"random.h\"\n#include <iostream>\n\n#include <fstream>\n#include <boost/progress.hpp>\n#include <thread>\n\n//#define DISPLAY_ANALYSIS\n//#define DATA_DISTRIBUTION_TEST\n//#define BUILD_KERNEL_FROM_SOURCE\noutput_type monte_carlo::operator()(model& m, const precalculate& p, const igrid& ig, const precalculate& p_widened, const igrid& ig_widened, const vec& corner1, const vec& corner2, incrementable* increment_me, rng& generator) const {\n\toutput_container tmp;\n\tthis->operator()(m, tmp, p, ig, p_widened, ig_widened, corner1, corner2, increment_me, generator); // call the version that produces the whole container\n\tVINA_CHECK(!tmp.empty());\n\treturn tmp.front();\n}\n\nbool metropolis_accept(fl old_f, fl new_f, fl temperature, rng& generator) {\n\tif(new_f < old_f) return true;\n\tconst fl acceptance_probability = std::exp((old_f - new_f) / temperature);\n\treturn random_fl(0, 1, generator) < acceptance_probability;\n}\n\nvoid monte_carlo::single_run(model& m, output_type& out, const precalculate& p, const igrid& ig, rng& generator) const {\n\tconf_size s = m.get_size();\n\tchange g(s);\n\tvec authentic_v(1000, 1000, 1000);\n\tout.e = max_fl;\n\toutput_type current(out);\n\tquasi_newton quasi_newton_par; quasi_newton_par.max_steps = ssd_par.evals;\n\tVINA_U_FOR(step, num_steps) {\n\t\toutput_type candidate(current.c, max_fl);\n\t\tmutate_conf(candidate.c, m, mutation_amplitude, generator);\n\t\tquasi_newton_par(m, p, ig, candidate, g, hunt_cap);\n\t\tif(step == 0 || metropolis_accept(current.e, candidate.e, temperature, generator)) {\n\t\t\tquasi_newton_par(m, p, ig, candidate, g, authentic_v);\n\t\t\tcurrent = candidate;\n\t\t\tif(current.e < out.e)\n\t\t\t\tout = current;\n\t\t}\n\t}\n\tquasi_newton_par(m, p, ig, out, g, authentic_v);\n}\n\nvoid monte_carlo::many_runs(model& m, output_container& out, const precalculate& p, const igrid& ig, const vec& corner1, const vec& corner2, sz num_runs, rng& generator) const {\n\tconf_size s = m.get_size();\n\tVINA_FOR(run, num_runs) {\n\t\toutput_type tmp(s, 0);\n\t\ttmp.c.randomize(corner1, corner2, generator);\n\t\tsingle_run(m, tmp, p, ig, generator);\n\t\tout.push_back(new output_type(tmp));\n\t}\n\tout.sort();\n}\n\nstd::vector<output_type> monte_carlo::cl_to_vina(output_type_cl result_ptr[], int exhaus) const {\n\tstd::vector<output_type> results_vina;\n\tfor (int i = 0; i < exhaus; i++) {\n\t\toutput_type_cl tmp_cl = result_ptr[i];\n\t\tconf tmp_c;\n\t\ttmp_c.ligands.resize(1);\n\t\t// Position\n\t\tfor (int j = 0; j < 3; j++)tmp_c.ligands[0].rigid.position[j] = tmp_cl.position[j];\n\t\t// Orientation\n\t\tqt q(tmp_cl.orientation[0], tmp_cl.orientation[1], tmp_cl.orientation[2], tmp_cl.orientation[3]);\n\t\ttmp_c.ligands[0].rigid.orientation = q;\n\t\toutput_type tmp_vina(tmp_c, tmp_cl.e);\n\t\t// torsion\n\t\tfor (int j = 0; j < tmp_cl.lig_torsion_size; j++)tmp_vina.c.ligands[0].torsions.push_back(tmp_cl.lig_torsion[j]);\n\t\t// coords\n\t\tfor (int j = 0; j < MAX_NUM_OF_ATOMS; j++) {\n\t\t\tvec v_tmp(tmp_cl.coords[j][0], tmp_cl.coords[j][1], tmp_cl.coords[j][2]);\n\t\t\tif (v_tmp[0] * v_tmp[1] * v_tmp[2] != 0) tmp_vina.coords.push_back(v_tmp);\n\t\t}\n\t\tresults_vina.push_back(tmp_vina);\n\t}\n\treturn results_vina;\n}\n\nvoid monte_carlo::generate_uniform_position(const vec corner1, const vec corner2, std::vector<vec>& uniform_data, int exhaustiveness) const{\n\tassert(exhaustiveness == 125);\n\tint counter = 0;\n\tint n = 5;\n\tfor (int i = 0; i < n; i++) {\n\t\tdouble p0 = (corner1.data[0] - corner2.data[0]) / n * i + corner2.data[0];\n\t\tfor (int j = 0; j < n; j++) {\n\t\t\tdouble p1 = (corner1.data[1] - corner2.data[1]) / n * j + corner2.data[1];\n\t\t\tfor (int k = 0; k < n; k++) {\n\t\t\t\tdouble p2 = (corner1.data[2] - corner2.data[2]) / n * k + corner2.data[2];\n\t\t\t\tuniform_data[counter] = vec(p0, p1, p2);\n\t\t\t\tcounter++;\n\t\t\t}\n\t\t}\n\t}\n\tassert(counter == exhaustiveness);\n}\n\n#ifndef OPENCL_PART_2\n// out is sorted\nvoid monte_carlo::operator()(model& m, output_container& out, const precalculate& p, const igrid& ig, const precalculate& p_widened, const igrid& ig_widened, const vec& corner1, const vec& corner2, incrementable* increment_me, rng& generator) const {\n\tvec authentic_v(1000, 1000, 1000); // FIXME? this is here to avoid max_fl/max_fl\n\tconf_size s = m.get_size();\n\tchange g(s);\n\toutput_type tmp(s, 0);\n\ttmp.c.randomize(corner1, corner2, generator);\n\tfl best_e = max_fl;\n\tquasi_newton quasi_newton_par; quasi_newton_par.max_steps = ssd_par.evals;\n\toutput_type origin = tmp;\n\n\tVINA_U_FOR(step, num_steps) {\n\t\tif (increment_me)\n\t\t\t++(*increment_me);\n\t\toutput_type candidate = tmp;\n\t\tmutate_conf(candidate.c, m, mutation_amplitude, generator);\n\t\tquasi_newton_par(m, p, ig, candidate, g, hunt_cap);\n\t\tif (step == 0 || metropolis_accept(tmp.e, candidate.e, temperature, generator)) {\n\t\t\ttmp = candidate;\n\n\t\t\tm.set(tmp.c); // FIXME? useless?\n\n\t\t\t// FIXME only for very promising ones\n\t\t\tif (tmp.e < best_e || out.size() < num_saved_mins) {\n\t\t\t\tquasi_newton_par(m, p, ig, tmp, g, authentic_v);\n\t\t\t\tm.set(tmp.c); // FIXME? useless?\n\t\t\t\ttmp.coords = m.get_heavy_atom_movable_coords();\n\t\t\t\tadd_to_output_container(out, tmp, min_rmsd, num_saved_mins); // 20 - max size\n\t\t\t\tif (tmp.e < best_e)\n\t\t\t\t\tbest_e = tmp.e;\n\t\t\t}\n\t\t}\n\t}\n\tVINA_CHECK(!out.empty());\n\tVINA_CHECK(out.front().e <= out.back().e); // make sure the sorting worked in the correct order\n}\n#else\n\nvolatile bool finished = false; //20211119 Glinttsd\nvoid print_process() {\n\tint count = 0;\n\tprintf(\"\\n\");\n\tdo\n\t{\n#ifdef WIN32\n\t\tSleep(100);\n#else\n\t\tsleep(1);\n#endif\n\t\tprintf(\"\\rPerform docking|\");\n\t\tfor (int i = 0; i < count; i++)printf(\" \");\n\t\tprintf(\"=======\");\n\t\tfor (int i = 0; i < 30 - count; i++)printf(\" \");\n\t\tprintf(\"|\"); fflush(stdout);\n\n\t\tcount++;\n\t\tcount %= 30;\n\t} while (finished != true);\n\tprintf(\"\\rPerform docking|\");\n\tfor (int i = 0; i < 16; i++)printf(\"=\");\n\tprintf(\"done\");\n\tfor (int i = 0; i < 17; i++)printf(\"=\");\n\tprintf(\"|\\n\"); fflush(stdout);\n}\n\n\n\nvoid monte_carlo::operator()(model& m, output_container& out, const precalculate& p, const igrid& ig, const precalculate& p_widened, const igrid& ig_widened, const vec& corner1, const vec& corner2, incrementable* increment_me, rng& generator) const {\n\t/**************************************************************************/\n\t/***************************    OpenCL Init    ****************************/\n\t/**************************************************************************/\n\n\n\tcl_int err;\n\tcl_platform_id* platforms;\n\tcl_device_id* devices;\n\tcl_context context;\n\tcl_command_queue queue;\n\tcl_int gpu_platform_id;\n\tSetupPlatform(&platforms, &gpu_platform_id);\n\tSetupDevice(platforms, &devices, gpu_platform_id);\n\tSetupContext(platforms, devices, &context, 1, gpu_platform_id);\n\tSetupQueue(&queue, context, devices);\n\tchar* program_file;\n\tcl_program program_cl;\n\tcl_program program;\n\tsize_t program_size;\n\n\n\t\n\t//Read kernel source code\n#ifdef BUILD_KERNEL_FROM_SOURCE\n\tprintf(\"\\nBuild kernels from source\"); fflush(stdout);\n\tconst std::string default_work_path = \".\";\n\tconst std::string include_path = default_work_path + \"/OpenCL/inc\"; //FIX it\n\tconst std::string addtion = \"\";\n\n\tchar* program_file_n[NUM_OF_FILES];\n\tsize_t program_size_n[NUM_OF_FILES];\n\tstd::string file_paths[NUM_OF_FILES] = {\tdefault_work_path + \"/OpenCL/src/kernels/code_head.cpp\",\n\t\t\t\t\t\t\t\t\t\t\t\tdefault_work_path + \"/OpenCL/src/kernels/mutate_conf.cpp\",\n\t\t\t\t\t\t\t\t\t\t\t\tdefault_work_path + \"/OpenCL/src/kernels/matrix.cpp\",\n\t\t\t\t\t\t\t\t\t\t\t\tdefault_work_path + \"/OpenCL/src/kernels/quasi_newton.cpp\",\n\t\t\t\t\t\t\t\t\t\t\t\tdefault_work_path + \"/OpenCL/src/kernels/kernel2.cl\"}; // The order of files is important!\n\n\tread_n_file(program_file_n, program_size_n, file_paths, NUM_OF_FILES);\n\tstd::string final_file;\n\tsize_t final_size = NUM_OF_FILES - 1; // count '\\n'\n\tfor (int i = 0; i < NUM_OF_FILES; i++) {\n\t\tif (i == 0) final_file = program_file_n[0];\n\t\telse final_file = final_file + '\\n' + (std::string)program_file_n[i];\n\t\tfinal_size += program_size_n[i];\n\t}\n\tconst char* final_files_char = final_file.data();\t\n\n\tprogram_cl = clCreateProgramWithSource(context, 1, (const char**)&final_files_char, &final_size, &err); checkErr(err);\n\tSetupBuildProgramWithSource(program_cl, NULL, devices, include_path, addtion);\n\tSaveProgramToBinary(program_cl, \"Kernel2_Opt.bin\");\n#endif\n\n\t\n\t//Display the progress\n\tprintf(\"\\nSearch depth is set to %d\",search_depth);\n\tstd::thread console_thread(print_process);\n\t\n\n\tprogram_cl = SetupBuildProgramWithBinary(context, devices, \"Kernel2_Opt.bin\");\n\n\terr = clUnloadPlatformCompiler(platforms[gpu_platform_id]); checkErr(err);\n\t//Set kernel arguments\n\tcl_kernel kernels[1];\n\tchar kernel_name[][50] = { \"kernel2\" };\n\tSetupKernel(kernels, program_cl, 1, kernel_name);\n\tsize_t max_wg_size; // max work item within one work group\n\tsize_t max_wi_size[3]; // max work item within each dimension(global)\n\terr = clGetDeviceInfo(devices[0], CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(size_t), &max_wg_size, NULL); checkErr(err);\n\terr = clGetDeviceInfo(devices[0], CL_DEVICE_MAX_WORK_ITEM_SIZES, 3 * sizeof(size_t), &max_wi_size, NULL); checkErr(err);\n\n\t/**************************************************************************/\n\t/************************    Original Vina code    ************************/\n\t/**************************************************************************/\n\n\tvec authentic_v(1000, 1000, 1000); // FIXME? this is here to avoid max_fl/max_fl\n\tconf_size s = m.get_size();\n\tchange g(s);\n\toutput_type tmp(s, 0);\n\tquasi_newton quasi_newton_par; const int quasi_newton_par_max_steps = ssd_par.evals;\n\n\t/**************************************************************************/\n\t/************************    Allocate CPU memory    ***********************/\n\t/**************************************************************************/\n\n\t// Preparing m related data\n\tm_cl m_cl;\n\tassert(m.atoms.size() < MAX_NUM_OF_ATOMS);\n\n\tfor (int i = 0; i < m.atoms.size(); i++) {\n\t\tm_cl.atoms[i].types[0] = m.atoms[i].el;// To store 4 atoms types (el, ad, xs, sy)\n\t\tm_cl.atoms[i].types[1] = m.atoms[i].ad;\n\t\tm_cl.atoms[i].types[2] = m.atoms[i].xs;\n\t\tm_cl.atoms[i].types[3] = m.atoms[i].sy;\n\t\tfor (int j = 0; j < 3; j++) {\n\t\t\tm_cl.atoms[i].coords[j] = m.atoms[i].coords[j];// To store atom coords\n\t\t}\n\t}\n\n\t// To store atoms coords\n\tfor (int i = 0; i < m.coords.size(); i++) {\n\t\tfor (int j = 0; j < 3; j++) {\n\t\t\tm_cl.m_coords.coords[i][j] = m.coords[i].data[j];\n\t\t}\n\t}\n\n\t//To store minus forces\n\tfor (int i = 0; i < m.coords.size(); i++) {\n\t\tfor (int j = 0; j < 3; j++) {\n\t\t\tm_cl.minus_forces.coords[i][j] = m.minus_forces[i].data[j];\n\t\t}\n\t}\n\n\t// Preparing ligand data\n\tassert(m.num_other_pairs() == 0); // m.other_paris is not supported!\n\tassert(m.ligands.size() == 1); // Only one ligand supported!\n\tm_cl.ligand.pairs.num_pairs = m.ligands[0].pairs.size();\n\tfor (int i = 0; i < m_cl.ligand.pairs.num_pairs; i++) {\n\t\tm_cl.ligand.pairs.type_pair_index[i]\t= m.ligands[0].pairs[i].type_pair_index;\n\t\tm_cl.ligand.pairs.a[i]\t\t\t\t\t= m.ligands[0].pairs[i].a;\n\t\tm_cl.ligand.pairs.b[i]\t\t\t\t\t= m.ligands[0].pairs[i].b;\n\t}\n\tm_cl.ligand.begin = m.ligands[0].begin; // 0\n\tm_cl.ligand.end = m.ligands[0].end; // 29\n\tligand m_ligand = m.ligands[0]; // Only support one ligand \n\tassert(m_ligand.end < MAX_NUM_OF_ATOMS);\n\n\t// Store root node\n\tm_cl.ligand.rigid.atom_range[0][0] = m_ligand.node.begin;\n\tm_cl.ligand.rigid.atom_range[0][1] = m_ligand.node.end;\n\tfor (int i = 0; i < 3; i++) m_cl.ligand.rigid.origin[0][i] = m_ligand.node.get_origin()[i];\n\tfor (int i = 0; i < 9; i++) m_cl.ligand.rigid.orientation_m[0][i] = m_ligand.node.get_orientation_m().data[i];\n\tm_cl.ligand.rigid.orientation_q[0][0] = m_ligand.node.orientation().R_component_1();\n\tm_cl.ligand.rigid.orientation_q[0][1] = m_ligand.node.orientation().R_component_2();\n\tm_cl.ligand.rigid.orientation_q[0][2] = m_ligand.node.orientation().R_component_3();\n\tm_cl.ligand.rigid.orientation_q[0][3] = m_ligand.node.orientation().R_component_4();\n\tfor (int i = 0; i < 3; i++) {m_cl.ligand.rigid.axis[0][i] = 0;m_cl.ligand.rigid.relative_axis[0][i] = 0;m_cl.ligand.rigid.relative_origin[0][i] = 0;}\n\n\t// Store children nodes (in depth-first order)\n\tstruct tmp_struct { \n\t\tint start_index = 0;\n\t\tint parent_index = 0;\n\t\tvoid store_node(tree<segment>& child_ptr, rigid_cl& rigid) {\n\t\t\tstart_index++; // start with index 1, index 0 is root node\n\t\t\trigid.parent[start_index] = parent_index;\n\t\t\trigid.atom_range[start_index][0] = child_ptr.node.begin;\n\t\t\trigid.atom_range[start_index][1] = child_ptr.node.end;\n\t\t\tfor (int i = 0; i < 9; i++) rigid.orientation_m[start_index][i] = child_ptr.node.get_orientation_m().data[i];\n\t\t\trigid.orientation_q[start_index][0] = child_ptr.node.orientation().R_component_1();\n\t\t\trigid.orientation_q[start_index][1] = child_ptr.node.orientation().R_component_2();\n\t\t\trigid.orientation_q[start_index][2] = child_ptr.node.orientation().R_component_3();\n\t\t\trigid.orientation_q[start_index][3] = child_ptr.node.orientation().R_component_4();\n\t\t\tfor (int i = 0; i < 3; i++) {\n\t\t\t\trigid.origin[start_index][i] = child_ptr.node.get_origin()[i];\n\t\t\t\trigid.axis[start_index][i] = child_ptr.node.get_axis()[i];\n\t\t\t\trigid.relative_axis[start_index][i] = child_ptr.node.relative_axis[i];\n\t\t\t\trigid.relative_origin[start_index][i] = child_ptr.node.relative_origin[i];\n\t\t\t}\n\t\t\tif (child_ptr.children.size() == 0) return;\n\t\t\telse {\n\t\t\t\tassert(start_index < MAX_NUM_OF_RIGID);\n\t\t\t\tint parent_index_tmp = start_index;\n\t\t\t\tfor (int i = 0; i < child_ptr.children.size(); i++) {\n\t\t\t\t\tthis->parent_index = parent_index_tmp; // Update parent index\n\t\t\t\t\tthis->store_node(child_ptr.children[i], rigid);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\ttmp_struct ts;\n\tfor (int i = 0; i < m_ligand.children.size(); i++) {\n\t\tts.parent_index = 0; // Start a new branch, whose parent is 0\n\t\tts.store_node(m_ligand.children[i], m_cl.ligand.rigid);\n\t}\n\tm_cl.ligand.rigid.num_children = ts.start_index;\n\n\t// set children_map\n\tfor (int i = 0; i < MAX_NUM_OF_RIGID; i++)\n\t\tfor (int j = 0; j < MAX_NUM_OF_RIGID; j++)\n\t\t\tm_cl.ligand.rigid.children_map[i][j] = false;\n\tfor (int i = 1; i < m_cl.ligand.rigid.num_children + 1; i++) {\n\t\tint parent_index = m_cl.ligand.rigid.parent[i];\n\t\tm_cl.ligand.rigid.children_map[parent_index][i] = true;\n\t}\n\tm_cl.m_num_movable_atoms = m.num_movable_atoms();\n\tsize_t m_cl_size = sizeof(m_cl);\n\n\t// Preparing ig related data\n\tig_cl* ig_cl_ptr = (ig_cl*)malloc(sizeof(ig_cl));\n\tig_cl_ptr->atu = ig.get_atu(); // atu\n\tig_cl_ptr->slope = ig.get_slope(); // slope\n\tstd::vector<grid> tmp_grids = ig.get_grids();\n\tint grid_size = tmp_grids.size();\n\tassert(GRIDS_SIZE == grid_size); // grid_size has to be 17\n\n\tfor (int i = 0; i < grid_size; i++) {\n\t\tfor (int j = 0; j < 3; j++) {\n\t\t\tig_cl_ptr->grids[i].m_init[j] = tmp_grids[i].m_init[j];\n\t\t\tig_cl_ptr->grids[i].m_factor[j] = tmp_grids[i].m_factor[j];\n\t\t\tig_cl_ptr->grids[i].m_dim_fl_minus_1[j] = tmp_grids[i].m_dim_fl_minus_1[j];\n\t\t\tig_cl_ptr->grids[i].m_factor_inv[j] = tmp_grids[i].m_factor_inv[j];\n\t\t}\n\t\tif (tmp_grids[i].m_data.dim0() != 0) {\n\t\t\tig_cl_ptr->grids[i].m_i = tmp_grids[i].m_data.dim0(); assert(MAX_NUM_OF_GRID_MI >= ig_cl_ptr->grids[i].m_i);\n\t\t\tig_cl_ptr->grids[i].m_j = tmp_grids[i].m_data.dim1(); assert(MAX_NUM_OF_GRID_MJ >= ig_cl_ptr->grids[i].m_j);\n\t\t\tig_cl_ptr->grids[i].m_k = tmp_grids[i].m_data.dim2(); assert(MAX_NUM_OF_GRID_MK >= ig_cl_ptr->grids[i].m_k);\n\n\t\t\t//for (int j = 0; j < ig_cl_ptr->grids[i].m_i * ig_cl_ptr->grids[i].m_j * ig_cl_ptr->grids[i].m_k; j++) {\n\t\t\t//\tig_cl_ptr->grids[i].m_data[j] = tmp_grids[i].m_data.m_data[j];\n\t\t\t//}\n\n\t\t\tint m_i = tmp_grids[i].m_data.dim0();\n\t\t\tint m_j = tmp_grids[i].m_data.dim1();\n\t\t\tint m_k = tmp_grids[i].m_data.dim2();\n\t\t\tfor (sz idx0 = 0; idx0 < m_i - 1; idx0++)\n\t\t\t\tfor (sz idx1 = 0; idx1 < m_j - 1; idx1++)\n\t\t\t\t\tfor (sz idx2 = 0; idx2 < m_k - 1; idx2++) {\n\t\t\t\t\t\tint base = (idx0 + m_i * (idx1 + m_j * idx2)) * 8;\n\t\t\t\t\t\tig_cl_ptr->grids[i].m_data[base] = tmp_grids[i].m_data(idx0, idx1, idx2); // f000\n\t\t\t\t\t\tig_cl_ptr->grids[i].m_data[base + 1] = tmp_grids[i].m_data(idx0 + 1, idx1, idx2); // f100\n\t\t\t\t\t\tig_cl_ptr->grids[i].m_data[base + 2] = tmp_grids[i].m_data(idx0, idx1 + 1, idx2); // f010\n\t\t\t\t\t\tig_cl_ptr->grids[i].m_data[base + 3] = tmp_grids[i].m_data(idx0 + 1, idx1 + 1, idx2); // f110\n\t\t\t\t\t\tig_cl_ptr->grids[i].m_data[base + 4] = tmp_grids[i].m_data(idx0, idx1, idx2 + 1); // f001\n\t\t\t\t\t\tig_cl_ptr->grids[i].m_data[base + 5] = tmp_grids[i].m_data(idx0 + 1, idx1, idx2 + 1); // f101\n\t\t\t\t\t\tig_cl_ptr->grids[i].m_data[base + 6] = tmp_grids[i].m_data(idx0, idx1 + 1, idx2 + 1); // f011\n\t\t\t\t\t\tig_cl_ptr->grids[i].m_data[base + 7] = tmp_grids[i].m_data(idx0 + 1, idx1 + 1, idx2 + 1); // f111\n\t\t\t\t\t}\n\n\t\t\n\t\t}\n\t\telse {\n\t\t\tig_cl_ptr->grids[i].m_i = 0;\n\t\t\tig_cl_ptr->grids[i].m_j = 0;\n\t\t\tig_cl_ptr->grids[i].m_k = 0;\n\t\t}\n\t}\n\tsize_t ig_cl_size = sizeof(*ig_cl_ptr);\n\t\n\t// Generating random ligand structures\n\tstd::vector<output_type_cl*> rand_molec_struc_vec; rand_molec_struc_vec.resize(thread);\n\tfor (int i = 0; i < thread; i++) {\n\t\trand_molec_struc_vec[i] = (output_type_cl*)malloc(sizeof(output_type_cl));\n\t}\n\n\t//std::vector<output_type_cl> rand_molec_struc_vec; \n\t//rand_molec_struc_vec.resize(thread);\n\tint lig_torsion_size = tmp.c.ligands[0].torsions.size();\n\tint flex_torsion_size; if (tmp.c.flex.size() != 0) flex_torsion_size = tmp.c.flex[0].torsions.size(); else flex_torsion_size = 0;\n\tstd::vector<vec> uniform_data;\n\tuniform_data.resize(thread);\n\t\n\tfor (int i = 0; i < thread; i++) {\n\t\ttmp.c.randomize(corner1, corner2, generator); // generate a random structure\n\t\t//Generate positions with uniform probability\n\t\t//generate_uniform_position(corner1, corner2, uniform_data, exhaustiveness);\n\t\t//for (int j = 0; j < 3; j++) rand_molec_struc_vec[i].position[j] = uniform_data[i].data[j];\n\t\tfor (int j = 0; j < 3; j++) rand_molec_struc_vec[i]->position[j] = tmp.c.ligands[0].rigid.position[j];\n\t\tassert(lig_torsion_size < MAX_NUM_OF_LIG_TORSION);\n\t\tfor (int j = 0; j < lig_torsion_size; j++) rand_molec_struc_vec[i]->lig_torsion[j] = tmp.c.ligands[0].torsions[j];// Only support one ligand\n\t\tassert(flex_torsion_size < MAX_NUM_OF_FLEX_TORSION);\n\t\tfor (int j = 0; j < flex_torsion_size; j++) rand_molec_struc_vec[i]->flex_torsion[j] = tmp.c.flex[0].torsions[j];// Only support one flex\n\n\t\trand_molec_struc_vec[i]->orientation[0] = (float)tmp.c.ligands[0].rigid.orientation.R_component_1();\n\t\trand_molec_struc_vec[i]->orientation[1] = (float)tmp.c.ligands[0].rigid.orientation.R_component_2();\n\t\trand_molec_struc_vec[i]->orientation[2] = (float)tmp.c.ligands[0].rigid.orientation.R_component_3();\n\t\trand_molec_struc_vec[i]->orientation[3] = (float)tmp.c.ligands[0].rigid.orientation.R_component_4();\n\n\t\trand_molec_struc_vec[i]->lig_torsion_size = lig_torsion_size;\n\t}\n\n\t// Preaparing p related data\n\tp_cl p_cl;\n\tp_cl.m_cutoff_sqr = p.cutoff_sqr();\n\tp_cl.factor = p.factor;\n\tp_cl.n = p.n;\n\tassert(MAX_P_DATA_M_DATA_SIZE > p.data.m_data.size());\n\tfor (int i = 0; i < p.data.m_data.size(); i++) {\n\t\tp_cl.m_data[i].factor = p.data.m_data[i].factor;\n\t\tassert(FAST_SIZE == p.data.m_data[i].fast.size());\n\t\tassert(SMOOTH_SIZE == p.data.m_data[i].smooth.size());\n\t\tfor (int j = 0; j < FAST_SIZE; j++) {\n\t\t\tp_cl.m_data[i].fast[j] = p.data.m_data[i].fast[j];\n\t\t}\n\t\tfor (int j = 0; j < SMOOTH_SIZE; j++) {\n\t\t\tp_cl.m_data[i].smooth[j][0] = p.data.m_data[i].smooth[j].first;\n\t\t\tp_cl.m_data[i].smooth[j][1] = p.data.m_data[i].smooth[j].second;\n\t\t}\n\t}\n\tsize_t p_cl_size = sizeof(p_cl);\n\n\t// Generate random maps\n\trandom_maps* rand_maps = (random_maps*)malloc(sizeof(random_maps));\n\tfor (int i = 0; i < MAX_NUM_OF_RANDOM_MAP; i++) {\n\t\trand_maps->int_map[i] = random_int(0, int(lig_torsion_size), generator);\n\t\trand_maps->pi_map[i] = random_fl(-pi, pi, generator);\n\t}\n\tfor (int i = 0; i < MAX_NUM_OF_RANDOM_MAP; i++) {\n\t\tvec rand_coords = random_inside_sphere(generator);\n\t\tfor (int j = 0; j < 3 ; j ++) {\n\t\t\trand_maps->sphere_map[i][j] = rand_coords[j];\n\t\t}\n\t}\n\tsize_t rand_maps_size = sizeof(*rand_maps);\n\n\n\tfloat hunt_cap_float[3] = {hunt_cap[0], hunt_cap[1], hunt_cap[2]};\n\tfloat authentic_v_float[3] = { authentic_v[0],authentic_v[1], authentic_v[2] };\n\tfloat mutation_amplitude_float = mutation_amplitude;\n\tfloat epsilon_fl_float = epsilon_fl;\n\tint\ttotal_wi = max_wi_size[0] * max_wi_size[1];\n\t/**************************************************************************/\n\t/************************    Allocate GPU memory    ***********************/\n\t/**************************************************************************/\n\n\tcl_mem rand_molec_struc_vec_gpu;\n\tCreateDeviceBuffer(&rand_molec_struc_vec_gpu, CL_MEM_READ_ONLY, thread* SIZE_OF_MOLEC_STRUC, context);\n\tfor (int i = 0; i < thread; i++) {\n\t\tstd::vector<float> pos(rand_molec_struc_vec[i]->position, rand_molec_struc_vec[i]->position + 3);\n\t\tstd::vector<float> ori(rand_molec_struc_vec[i]->orientation, rand_molec_struc_vec[i]->orientation + 4);\n\t\tstd::vector<float> lig_tor(rand_molec_struc_vec[i]->lig_torsion, rand_molec_struc_vec[i]->lig_torsion + MAX_NUM_OF_LIG_TORSION);\n\t\tstd::vector<float> flex_tor(rand_molec_struc_vec[i]->flex_torsion, rand_molec_struc_vec[i]->flex_torsion + MAX_NUM_OF_FLEX_TORSION);\n\t\tfloat lig_tor_size = rand_molec_struc_vec[i]->lig_torsion_size;\n\t\terr = clEnqueueWriteBuffer(\tqueue, rand_molec_struc_vec_gpu, false, i * SIZE_OF_MOLEC_STRUC,\n\t\t\t\t\t\t\t\t\tpos.size() * sizeof(float), pos.data(), 0, NULL, NULL); checkErr(err);\n\t\terr = clEnqueueWriteBuffer(\tqueue, rand_molec_struc_vec_gpu, false, i * SIZE_OF_MOLEC_STRUC + pos.size() * sizeof(float),\n\t\t\t\t\t\t\t\t\tori.size() * sizeof(float), ori.data(), 0, NULL, NULL); checkErr(err);\n\t\terr = clEnqueueWriteBuffer(\tqueue, rand_molec_struc_vec_gpu, false, i * SIZE_OF_MOLEC_STRUC + (pos.size() + ori.size() ) * sizeof(float),\n\t\t\t\t\t\t\t\t\tlig_tor.size() * sizeof(float), lig_tor.data(), 0, NULL, NULL); checkErr(err);\n\t\terr = clEnqueueWriteBuffer(queue, rand_molec_struc_vec_gpu, false, i * SIZE_OF_MOLEC_STRUC + (pos.size() + ori.size() + MAX_NUM_OF_LIG_TORSION) * sizeof(float),\n\t\t\t\t\t\t\t\t\tflex_tor.size() * sizeof(float), flex_tor.data(), 0, NULL, NULL); checkErr(err);\n\t\terr = clEnqueueWriteBuffer(queue, rand_molec_struc_vec_gpu, false, i * SIZE_OF_MOLEC_STRUC + (pos.size() + ori.size() + MAX_NUM_OF_LIG_TORSION + MAX_NUM_OF_FLEX_TORSION) * sizeof(float),\n\t\t\tsizeof(float), &lig_tor_size, 0, NULL, NULL); checkErr(err);\n\t}\n\n\tcl_mem best_e_gpu;\n\tCreateDeviceBuffer(&best_e_gpu, CL_MEM_READ_WRITE, thread * sizeof(float), context);\n\terr = clEnqueueFillBuffer(queue, best_e_gpu, &max_fl, sizeof(float), 0, thread * sizeof(float), 0, NULL, NULL); checkErr(err);\n\n\tcl_mem rand_maps_gpu;\n\tCreateDeviceBuffer(&rand_maps_gpu, CL_MEM_READ_ONLY, rand_maps_size, context);\n\terr = clEnqueueWriteBuffer(\tqueue, rand_maps_gpu, false, 0,\trand_maps_size, rand_maps, 0, NULL, NULL); checkErr(err);\n\n\tcl_mem hunt_cap_gpu;\n\tCreateDeviceBuffer(&hunt_cap_gpu, CL_MEM_READ_ONLY, 3 * sizeof(float), context);\n\terr = clEnqueueWriteBuffer(queue, hunt_cap_gpu, false, 0, 3 * sizeof(float), hunt_cap_float, 0, NULL, NULL); checkErr(err);\n\n\t// Preparing m related data\n\tcl_mem m_cl_gpu;\n\tCreateDeviceBuffer(&m_cl_gpu, CL_MEM_READ_WRITE, m_cl_size, context);\n\terr = clEnqueueWriteBuffer(queue, m_cl_gpu, false, 0, m_cl_size, &m_cl, 0, NULL, NULL); checkErr(err);\n\n\t// Preparing p related data\n\tcl_mem p_cl_gpu;\n\tCreateDeviceBuffer(&p_cl_gpu, CL_MEM_READ_ONLY, p_cl_size, context);\n\terr = clEnqueueWriteBuffer(queue, p_cl_gpu, false, 0, p_cl_size, &p_cl, 0, NULL, NULL); checkErr(err);\n\n\t// Preparing ig related data (cache related data)\n\tcl_mem ig_cl_gpu;\n\tCreateDeviceBuffer(&ig_cl_gpu, CL_MEM_READ_ONLY, ig_cl_size, context);\n\terr = clEnqueueWriteBuffer(queue, ig_cl_gpu, false, 0, ig_cl_size, ig_cl_ptr, 0, NULL, NULL); checkErr(err);\n\n\tcl_mem authentic_v_gpu;\n\tCreateDeviceBuffer(&authentic_v_gpu, CL_MEM_READ_ONLY, 3 * sizeof(float), context);\n\terr = clEnqueueWriteBuffer(queue, authentic_v_gpu, false, 0, 3 * sizeof(float), authentic_v_float, 0, NULL, NULL); checkErr(err);\n\n\t// Preparing result data\n\tcl_mem results;\n\tCreateDeviceBuffer(&results, CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR, thread * sizeof(output_type_cl), context);\n\t\n\tclFinish(queue);\n\n\t/**************************************************************************/\n\t/************************   Set kernel arguments    ***********************/\n\t/**************************************************************************/\n\tSetKernelArg(kernels[0], 0, sizeof(cl_mem),\t\t&m_cl_gpu);\n\tSetKernelArg(kernels[0], 1, sizeof(cl_mem),\t\t&ig_cl_gpu);\n\tSetKernelArg(kernels[0], 2, sizeof(cl_mem),\t\t&p_cl_gpu);\n\tSetKernelArg(kernels[0], 3,\tsizeof(cl_mem),\t\t&rand_molec_struc_vec_gpu);\n\tSetKernelArg(kernels[0], 4, sizeof(cl_mem),\t\t&best_e_gpu);\n\tSetKernelArg(kernels[0], 5, sizeof(int),\t\t&quasi_newton_par_max_steps);\n\tSetKernelArg(kernels[0], 6, sizeof(unsigned int),\t&num_steps);\n\tSetKernelArg(kernels[0], 7, sizeof(float),\t\t&mutation_amplitude_float);\n\tSetKernelArg(kernels[0], 8, sizeof(cl_mem),\t\t&rand_maps_gpu); \n\tSetKernelArg(kernels[0], 9, sizeof(float),\t\t&epsilon_fl_float);\n\tSetKernelArg(kernels[0], 10, sizeof(cl_mem),\t&hunt_cap_gpu);\n\tSetKernelArg(kernels[0], 11, sizeof(cl_mem),\t&authentic_v_gpu);\n\tSetKernelArg(kernels[0], 12, sizeof(cl_mem),\t&results);\n\tSetKernelArg(kernels[0], 13, sizeof(int),\t\t&search_depth);\n\tSetKernelArg(kernels[0], 14, sizeof(int),\t\t&thread); \n\tSetKernelArg(kernels[0], 15, sizeof(int),\t&total_wi);\n\t/**************************************************************************/\n\t/****************************   Start kernel    ***************************/\n\t/**************************************************************************/\n\tsize_t global_size[2] = {512, 32 };\n\tsize_t local_size[2] = { 16,2 };\n\tcl_event monte_clarlo_cl;\n\terr = clEnqueueNDRangeKernel(queue, kernels[0], 2, 0, global_size, local_size, 0, NULL, &monte_clarlo_cl); checkErr(err);\n\n\tclWaitForEvents(1, &monte_clarlo_cl);\n\n\tfinished = true;\n\tconsole_thread.join(); // wait the thread finish\n\n\t//getchar();\n\n\t// Maping result data\n \toutput_type_cl* result_ptr = (output_type_cl*)clEnqueueMapBuffer(queue, results, CL_TRUE, CL_MAP_READ, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t0, thread * sizeof(output_type_cl),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t0, NULL, NULL, &err); checkErr(err);\n\n\tstd::vector<output_type> result_vina = cl_to_vina(result_ptr, thread);\n\t// if empty, something goes wrong in the device part\n\tif (result_vina.size() == 0) {\n\t\tprintf(\"Error in the device part\\n\"); exit(-1);\n\t}\n\n\n\t// Unmaping result data\n\terr = clEnqueueUnmapMemObject(queue, results, result_ptr, 0, NULL, NULL); checkErr(err);\n\n\t// Write back to vina\n\tfor (int i = 0; i < thread; i++) {\n\t\tadd_to_output_container(out, result_vina[i], min_rmsd, num_saved_mins);\n\t}\n\tVINA_CHECK(!out.empty());\n\tVINA_CHECK(out.front().e <= out.back().e);\n\n\t/**************************************************************************/\n\t/*******************************   Finish    ******************************/\n\t/**************************************************************************/\n\t// Memory objects release\n\terr = clReleaseMemObject(m_cl_gpu); checkErr(err);\n\terr = clReleaseMemObject(ig_cl_gpu); checkErr(err);\n\terr = clReleaseMemObject(p_cl_gpu); checkErr(err);\n\terr = clReleaseMemObject(rand_molec_struc_vec_gpu); checkErr(err);\n\terr = clReleaseMemObject(best_e_gpu); checkErr(err);\n\terr = clReleaseMemObject(hunt_cap_gpu); checkErr(err);\n\terr = clReleaseMemObject(authentic_v_gpu); checkErr(err);\n\terr = clReleaseMemObject(results); checkErr(err);\n\n\tfree(ig_cl_ptr);\n\tfree(rand_maps);\n\tfor (int i = 0; i < thread; i++)free(rand_molec_struc_vec[i]);\n\n\n\n\t// Output Analysis\n\tcl_ulong time_start, time_end;\n\tdouble total_time;\n\terr = clGetEventProfilingInfo(monte_clarlo_cl, CL_PROFILING_COMMAND_START, sizeof(time_start), &time_start, NULL); checkErr(err);\n\terr = clGetEventProfilingInfo(monte_clarlo_cl, CL_PROFILING_COMMAND_END, sizeof(time_end), &time_end, NULL); checkErr(err);\n\ttotal_time = time_end - time_start;\n\tprintf(\"GPU monte carlo runtime: %0.3f s\", (total_time / 1000000000.0));\n\n#ifdef DISPLAY_ANALYSIS\n\t// Output Analysis\n\tcl_ulong time_start, time_end;\n\tdouble total_time;\n\terr = clGetEventProfilingInfo(monte_clarlo_cl, CL_PROFILING_COMMAND_START, sizeof(time_start), &time_start, NULL); checkErr(err);\n\terr = clGetEventProfilingInfo(monte_clarlo_cl, CL_PROFILING_COMMAND_END, sizeof(time_end), &time_end, NULL); checkErr(err);\n\ttotal_time = time_end - time_start;\n\tprintf(\"\\nGPU monte carlo runtime = %0.3f s\\n\", (total_time / 1000000000.0));\n\n\tstd::ofstream file(\"gpu_runtime.txt\");\n\tif (file.is_open())\n\t{\n\t\tfile << \"GPU monte carlo runtime = \" << (double)(total_time / 1000000000.0) << \" s\" << std::endl;\n\t\tfile.close();\n\t}\n\n\tcl_ulong private_mem_size;\n\terr = clGetKernelWorkGroupInfo(kernels[0], devices[0], CL_KERNEL_PRIVATE_MEM_SIZE, sizeof(cl_ulong), &private_mem_size, NULL); checkErr(err);\n\tprintf(\"\\nprivate mem used = %f KBytes\", (double)private_mem_size / 1024);\n\n\tcl_ulong local_mem_size;\n\terr = clGetKernelWorkGroupInfo(kernels[0], devices[0], CL_KERNEL_LOCAL_MEM_SIZE, sizeof(cl_ulong), &local_mem_size, NULL); checkErr(err);\n\tprintf(\"\\nlocal mem used = %d Bytes\", (int)local_mem_size);\n\n\tprintf(\"\\nconstant mem used = %0.3f MBytes \\n\", (double)(\tp_cl_size + ig_cl_size + thread * SIZE_OF_MOLEC_STRUC) / (1024 * 1024));\n#endif\n\t//getchar();\n}\n#endif // OPENCL_VERSION\n", "meta": {"hexsha": "c31933b33ed50aad4692a5b26264eab21c36a9e4", "size": 29895, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/monte_carlo.cpp", "max_stars_repo_name": "DeltaGroupNJUPT/Vina-GPU", "max_stars_repo_head_hexsha": "f314354bbdf34559b4f6d8cef93e3598c45ba5bc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2021-11-16T06:18:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T14:21:00.000Z", "max_issues_repo_path": "lib/monte_carlo.cpp", "max_issues_repo_name": "DeltaGroupNJUPT/VINA-GPU", "max_issues_repo_head_hexsha": "f314354bbdf34559b4f6d8cef93e3598c45ba5bc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2021-11-22T12:34:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T14:02:40.000Z", "max_forks_repo_path": "lib/monte_carlo.cpp", "max_forks_repo_name": "DeltaGroupNJUPT/VINA-GPU", "max_forks_repo_head_hexsha": "f314354bbdf34559b4f6d8cef93e3598c45ba5bc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-11-22T02:05:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T00:08:38.000Z", "avg_line_length": 44.092920354, "max_line_length": 250, "alphanum_fraction": 0.6682722863, "num_tokens": 8987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4339814648038986, "lm_q1q2_score": 0.26047062330999227}}
{"text": "/*\nanharmonic_core.cpp\n\nCopyright (c) 2014, 2015, 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 \"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 \"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    im = std::complex<double>(0.0, 1.0);\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    exp_phase = nullptr;\n    exp_phase3 = nullptr;\n    phi3_reciprocal = nullptr;\n    phi4_reciprocal = nullptr;\n}\n\nvoid AnharmonicCore::deallocate_variables()\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 (phi3_reciprocal) {\n        memory->deallocate(phi3_reciprocal);\n    }\n    if (phi4_reciprocal) {\n        memory->deallocate(phi4_reciprocal);\n    }\n}\n\n\nvoid AnharmonicCore::setup()\n{\n    if (fcs_phonon->maxorder >= 2) setup_cubic();\n    if (fcs_phonon->maxorder >= 3) setup_quartic();\n\n    sym_permutation = true;\n    use_tuned_ver = true;\n\n    if (!mode_analysis->calc_fstate_k && kpoint->kpoint_mode == 2) {\n        int nk_tmp[3];\n        nk_tmp[0] = kpoint->nkx;\n        nk_tmp[1] = kpoint->nky;\n        nk_tmp[2] = kpoint->nkz;\n        store_exponential_for_acceleration(nk_tmp,\n                                           nk_represent,\n                                           exp_phase,\n                                           exp_phase3);\n    }\n}\n\n\nvoid AnharmonicCore::prepare_relative_vector(const std::vector<FcsArrayWithCell> &fcs_in,\n                                             const unsigned int N,\n                                             double ***vec_out) const\n{\n    int i, j;\n\n    double vec[3];\n    double **xshift_s;\n\n    std::vector<unsigned int> atm_super, atm_prim;\n    std::vector<unsigned int> xyz;\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 (int 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    memory->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    unsigned int icount = 0;\n\n    for (const auto &it : fcs_in) {\n\n        atm_super.clear();\n        atm_prim.clear();\n        xyz.clear();\n        cells.clear();\n\n        for (i = 0; i < it.pairs.size(); ++i) {\n            auto atm_p = it.pairs[i].index / 3;\n            const auto tran_tmp = it.pairs[i].tran;\n            auto atm_s = system->map_p2s_anharm[atm_p][tran_tmp];\n\n            atm_prim.push_back(atm_p);\n            atm_super.push_back(atm_s);\n            cells.push_back(it.pairs[i].cell_s);\n        }\n\n\n        for (i = 0; i < N - 1; ++i) {\n\n            for (j = 0; j < 3; ++j) {\n                vec[j] = system->xr_s_anharm[atm_super[i + 1]][j] + xshift_s[cells[i + 1]][j]\n                         - system->xr_s_anharm[system->map_p2s_anharm[atm_prim[i + 1]][0]][j];\n            }\n\n            rotvec(vec, vec, mat_convert);\n\n            for (j = 0; j < 3; ++j) {\n                vec_out[icount][i][j] = vec[j];\n            }\n        }\n        ++icount;\n    }\n    memory->deallocate(xshift_s);\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    memory->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    memory->deallocate(xshift_s);\n}\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    memory->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              dynamical->eval_phonon,\n              dynamical->evec_phonon);\n}\n\nstd::complex<double> AnharmonicCore::V4(const unsigned int ks[4])\n{\n    return V4(ks,\n              dynamical->eval_phonon,\n              dynamical->evec_phonon);\n}\n\nstd::complex<double> AnharmonicCore::Phi3(const unsigned int ks[3])\n{\n    return Phi3(ks,\n                dynamical->eval_phonon,\n                dynamical->evec_phonon);\n}\n\nstd::complex<double> AnharmonicCore::Phi4(const unsigned int ks[4])\n{\n    return Phi4(ks,\n                dynamical->eval_phonon,\n                dynamical->evec_phonon);\n}\n\n\nstd::complex<double> AnharmonicCore::V3(const unsigned int ks[3],\n                                        double **eval_phonon,\n                                        std::complex<double> ***evec_phonon)\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_phonon[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(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_phonon[kn[0]][sn[0]][evec_index_v3[i][0]]\n              * evec_phonon[kn[1]][sn[1]][evec_index_v3[i][1]]\n              * evec_phonon[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                                          double **eval_phonon,\n                                          std::complex<double> ***evec_phonon)\n{\n    int i;\n    unsigned int kn[3], sn[3];\n    int 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_phonon[kn[i]][sn[i]];\n    }\n\n    if (kn[1] != kindex_phi3_stored[0] || kn[2] != kindex_phi3_stored[1]) {\n        calc_phi3_reciprocal(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_phonon[kn[0]][sn[0]][evec_index_v3[i][0]]\n              * evec_phonon[kn[1]][sn[1]][evec_index_v3[i][1]]\n              * evec_phonon[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\n\nvoid AnharmonicCore::calc_phi3_reciprocal(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    unsigned int ielem = 0;\n\n    if (use_tuned_ver) {\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] * kpoint->xk[ik1][0]\n                            + relvec_v3[i][j].vecs[0][1] * kpoint->xk[ik1][1]\n                            + relvec_v3[i][j].vecs[0][2] * kpoint->xk[ik1][2]\n                            + relvec_v3[i][j].vecs[1][0] * kpoint->xk[ik2][0]\n                            + relvec_v3[i][j].vecs[1][1] * kpoint->xk[ik2][1]\n                            + relvec_v3[i][j].vecs[1][2] * kpoint->xk[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] * kpoint->xk[ik1][ii]\n                                  + relvec_v3[i][j].vecs[1][ii] * kpoint->xk[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    } else {\n        // Original version\n#pragma omp parallel for private(ret_in, nsize_group, 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\n                phase\n                        = relvec_v3[i][j].vecs[0][0] * kpoint->xk[ik1][0]\n                          + relvec_v3[i][j].vecs[0][1] * kpoint->xk[ik1][1]\n                          + relvec_v3[i][j].vecs[0][2] * kpoint->xk[ik1][2]\n                          + relvec_v3[i][j].vecs[1][0] * kpoint->xk[ik2][0]\n                          + relvec_v3[i][j].vecs[1][1] * kpoint->xk[ik2][1]\n                          + relvec_v3[i][j].vecs[1][2] * kpoint->xk[ik2][2];\n\n                ret_in += fcs_group_v3[i][j] * std::exp(im * phase);\n            }\n            ret[i] = ret_in;\n        }\n    }\n}\n\n\nstd::complex<double> AnharmonicCore::V4(const unsigned int ks[4],\n                                        double **eval_phonon,\n                                        std::complex<double> ***evec_phonon)\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_phonon[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(kn[1],\n                             kn[2],\n                             kn[3],\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_phonon[kn[0]][sn[0]][evec_index_v4[i][0]]\n              * evec_phonon[kn[1]][sn[1]][evec_index_v4[i][1]]\n              * evec_phonon[kn[2]][sn[2]][evec_index_v4[i][2]]\n              * evec_phonon[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                                        double **eval_phonon,\n                                        std::complex<double> ***evec_phonon)\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_phonon[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(kn[1],\n                             kn[2],\n                             kn[3],\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_phonon[kn[0]][sn[0]][evec_index_v4[i][0]]\n              * evec_phonon[kn[1]][sn[1]][evec_index_v4[i][1]]\n              * evec_phonon[kn[2]][sn[2]][evec_index_v4[i][2]]\n              * evec_phonon[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 unsigned int ik1,\n                                          const unsigned int ik2,\n                                          const unsigned int ik3,\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    unsigned int ielem = 0;\n\n    if (use_tuned_ver) {\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_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\n                    phase = relvec_v4[i][j].vecs[0][0] * kpoint->xk[ik1][0]\n                            + relvec_v4[i][j].vecs[0][1] * kpoint->xk[ik1][1]\n                            + relvec_v4[i][j].vecs[0][2] * kpoint->xk[ik1][2]\n                            + relvec_v4[i][j].vecs[1][0] * kpoint->xk[ik2][0]\n                            + relvec_v4[i][j].vecs[1][1] * kpoint->xk[ik2][1]\n                            + relvec_v4[i][j].vecs[1][2] * kpoint->xk[ik2][2]\n                            + relvec_v4[i][j].vecs[2][0] * kpoint->xk[ik3][0]\n                            + relvec_v4[i][j].vecs[2][1] * kpoint->xk[ik3][1]\n                            + relvec_v4[i][j].vecs[2][2] * kpoint->xk[ik3][2];\n\n                    unsigned int iloc = nint(phase * dnk_represent) % nk_represent + nk_represent - 1;\n                    ret_in += fcs_group_v4[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_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\n                    for (auto ii = 0; ii < 3; ++ii) {\n                        phase3[ii]\n                                = relvec_v4[i][j].vecs[0][ii] * kpoint->xk[ik1][ii]\n                                  + relvec_v4[i][j].vecs[1][ii] * kpoint->xk[ik2][ii]\n                                  + relvec_v4[i][j].vecs[2][ii] * kpoint->xk[ik3][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_v4[i][j] * exp_phase3[loc[0]][loc[1]][loc[2]];\n                }\n                ret[i] = ret_in;\n            }\n        }\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\n                phase\n                        = relvec_v4[i][j].vecs[0][0] * kpoint->xk[ik1][0]\n                          + relvec_v4[i][j].vecs[0][1] * kpoint->xk[ik1][1]\n                          + relvec_v4[i][j].vecs[0][2] * kpoint->xk[ik1][2]\n                          + relvec_v4[i][j].vecs[1][0] * kpoint->xk[ik2][0]\n                          + relvec_v4[i][j].vecs[1][1] * kpoint->xk[ik2][1]\n                          + relvec_v4[i][j].vecs[1][2] * kpoint->xk[ik2][2]\n                          + relvec_v4[i][j].vecs[2][0] * kpoint->xk[ik3][0]\n                          + relvec_v4[i][j].vecs[2][1] * kpoint->xk[ik3][1]\n                          + relvec_v4[i][j].vecs[2][2] * kpoint->xk[ik3][2];\n\n                ret_in += fcs_group_v4[i][j] * std::exp(im * phase);\n            }\n            ret[i] = ret_in;\n        }\n    }\n}\n\n\nstd::complex<double> AnharmonicCore::V3_mode(int mode,\n                                             double *xk2,\n                                             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\n\nvoid AnharmonicCore::calc_damping_smearing(const unsigned int N,\n                                           double *T,\n                                           const double omega,\n                                           const unsigned int ik_in,\n                                           const unsigned int snum,\n                                           double *ret)\n{\n    // This function returns the imaginary part of phonon self-energy \n    // for the given frequency omega.\n    // Lorentzian or Gaussian smearing will be used.\n    // This version employs the crystal symmetry to reduce the computational cost\n\n    const int nk = kpoint->nk;\n    const int 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 < N; ++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    kpoint->get_unique_triplet_k(ik_in,\n                                 use_triplet_symmetry,\n                                 sym_permutation,\n                                 triplet);\n\n    const int npair_uniq = triplet.size();\n\n    memory->allocate(v3_arr, npair_uniq, ns * ns);\n    memory->allocate(delta_arr, npair_uniq, ns * ns, 2);\n\n    const int knum = kpoint->kpoint_irred_all[ik_in][0].knum;\n    const int knum_minus = kpoint->knum_minus[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 + snum;\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] = dynamical->eval_phonon[k1][is];\n\n            for (js = 0; js < ns; ++js) {\n                arr[2] = ns * k2 + js;\n                omega_inner[1] = dynamical->eval_phonon[k2][js];\n\n                if (integration->ismear == 0) {\n                    delta_arr[ik][ns * is + js][0]\n                            = delta_lorentz(omega - omega_inner[0] - omega_inner[1], epsilon)\n                              - delta_lorentz(omega + omega_inner[0] + omega_inner[1], epsilon);\n                    delta_arr[ik][ns * is + js][1]\n                            = delta_lorentz(omega - omega_inner[0] + omega_inner[1], epsilon)\n                              - delta_lorentz(omega + 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 - omega_inner[0] - omega_inner[1], epsilon)\n                              - delta_gauss(omega + omega_inner[0] + omega_inner[1], epsilon);\n                    delta_arr[ik][ns * is + js][1]\n                            = delta_gauss(omega - omega_inner[0] + omega_inner[1], epsilon)\n                              - delta_gauss(omega + 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 + snum;\n            arr[1] = ns * k1 + is;\n            arr[2] = ns * k2 + js;\n\n            v3_arr[ik][ib] = std::norm(V3(arr,\n                                          dynamical->eval_phonon,\n                                          dynamical->evec_phonon)) * multi;\n        }\n    }\n\n    for (i = 0; i < N; ++i) {\n        T_tmp = T[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] = dynamical->eval_phonon[k1][is];\n\n                for (js = 0; js < ns; ++js) {\n\n                    omega_inner[1] = dynamical->eval_phonon[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    memory->deallocate(v3_arr);\n    memory->deallocate(delta_arr);\n    triplet.clear();\n\n    for (i = 0; i < N; ++i) ret[i] *= pi * std::pow(0.5, 4) / static_cast<double>(nk);\n}\n\n\nvoid AnharmonicCore::calc_damping_tetrahedron(const unsigned int N,\n                                              double *T,\n                                              const double omega,\n                                              const unsigned int ik_in,\n                                              const unsigned int snum,\n                                              double *ret)\n{\n    // This function returns the imaginary part of phonon self-energy \n    // for the given frequency omega.\n    // Tetrahedron method will be used.\n    // This version employs the crystal symmetry to reduce the computational cost\n\n    const int nk = kpoint->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    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 < N; ++i) ret[i] = 0.0;\n\n    kpoint->get_unique_triplet_k(ik_in,\n                                 use_triplet_symmetry,\n                                 sym_permutation,\n                                 triplet);\n\n    const auto npair_uniq = triplet.size();\n\n    memory->allocate(v3_arr, npair_uniq, ns2);\n    memory->allocate(delta_arr, npair_uniq, ns2, 2);\n\n    const int knum = kpoint->kpoint_irred_all[ik_in][0].knum;\n    const int knum_minus = kpoint->knum_minus[knum];\n\n    memory->allocate(kmap_identity, nk);\n\n    for (i = 0; i < nk; ++i) kmap_identity[i] = i;\n\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        memory->allocate(energy_tmp, 3, nk);\n        memory->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] = kpoint->xk[knum][i] - kpoint->xk[k1][i];\n\n                k2 = kpoint->get_knum(xk_tmp[0], xk_tmp[1], xk_tmp[2]);\n\n                energy_tmp[0][k1] = dynamical->eval_phonon[k1][is] + dynamical->eval_phonon[k2][js];\n                energy_tmp[1][k1] = dynamical->eval_phonon[k1][is] - dynamical->eval_phonon[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,\n                                                     kmap_identity,\n                                                     weight_tetra[i],\n                                                     energy_tmp[i],\n                                                     omega);\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        memory->deallocate(energy_tmp);\n        memory->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 + snum;\n                arr[1] = ns * k1 + is;\n                arr[2] = ns * k2 + js;\n\n                v3_arr[ik][ib] = std::norm(V3(arr,\n                                              dynamical->eval_phonon,\n                                              dynamical->evec_phonon)) * multi;\n\n            } else {\n                v3_arr[ik][ib] = 0.0;\n            }\n        }\n    }\n\n    for (i = 0; i < N; ++i) {\n        T_tmp = T[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] = dynamical->eval_phonon[k1][is];\n\n                for (js = 0; js < ns; ++js) {\n\n                    omega_inner[1] = dynamical->eval_phonon[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    memory->deallocate(v3_arr);\n    memory->deallocate(delta_arr);\n    memory->deallocate(kmap_identity);\n\n    for (i = 0; i < N; ++i) ret[i] *= pi * std::pow(0.5, 4);\n}\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    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    prepare_relative_vector(fcs_phonon->force_constant_with_cell[1],\n                            3,\n                            ngroup_v3,\n                            fcs_group_v3,\n                            relvec_v3);\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    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    memory->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    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    prepare_relative_vector(fcs_phonon->force_constant_with_cell[2],\n                            4,\n                            ngroup_v4,\n                            fcs_group_v4,\n                            relvec_v4);\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    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\nvoid AnharmonicCore::store_exponential_for_acceleration(const int nk_in[3],\n                                                        int &nkrep_out,\n                                                        std::complex<double> *exp_out,\n                                                        std::complex<double> ***exp3_out)\n{\n    // For accelerating function V3 and V4 by avoiding continual call of std::exp.\n\n    MPI_Bcast(&use_tuned_ver, 1, MPI_LOGICAL, 0, MPI_COMM_WORLD);\n\n    if (use_tuned_ver) {\n\n        nk_grid[0] = nk_in[0];\n        nk_grid[1] = nk_in[1];\n        nk_grid[2] = nk_in[2];\n\n        for (int 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            nkrep_out = nk_grid[0];\n            tune_type = 0;\n\n        } else if (nk_grid[0] == nk_grid[1] && nk_grid[2] == 1) {\n            nkrep_out = nk_grid[0];\n            tune_type = 0;\n\n        } else if (nk_grid[1] == nk_grid[2] && nk_grid[0] == 1) {\n            nkrep_out = nk_grid[1];\n            tune_type = 0;\n\n        } else if (nk_grid[2] == nk_grid[0] && nk_grid[1] == 1) {\n            nkrep_out = nk_grid[2];\n            tune_type = 0;\n\n        } else if (nk_grid[0] == 1 && nk_grid[1] == 1) {\n            nkrep_out = nk_grid[2];\n            tune_type = 0;\n\n        } else if (nk_grid[1] == 1 && nk_grid[2] == 1) {\n            nkrep_out = nk_grid[0];\n            tune_type = 0;\n\n        } else if (nk_grid[2] == 1 && nk_grid[0] == 1) {\n            nkrep_out = nk_grid[1];\n            tune_type = 0;\n\n        } else {\n            tune_type = 1;\n        }\n\n        int ii, jj, kk;\n\n        if (tune_type == 0) {\n\n            double phase;\n\n            memory->allocate(exp_phase, 2 * nkrep_out - 1);\n#ifdef _OPENMP\n#pragma omp parallel for private(phase)\n#endif\n            for (ii = 0; ii < 2 * nkrep_out - 1; ++ii) {\n                phase = 2.0 * pi * static_cast<double>(ii - nkrep_out + 1)\n                        / static_cast<double>(nkrep_out);\n                exp_phase[ii] = std::exp(im * phase);\n            }\n\n        } else if (tune_type == 1) {\n\n            double phase[3];\n\n            memory->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] = 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}\n\n\nvoid AnharmonicCore::calc_self3omega_tetrahedron(const double Temp,\n                                                 double **eval,\n                                                 std::complex<double> ***evec,\n                                                 const unsigned int ik_in,\n                                                 const unsigned int snum,\n                                                 const unsigned int nomega,\n                                                 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 int nk = kpoint->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    int *kmap_identity, **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 = kpoint->kpoint_irred_all[ik_in][0].knum;\n    const int knum_minus = kpoint->knum_minus[knum];\n    double omega0 = eval[knum_minus][snum];\n\n    kpoint->get_unique_triplet_k(ik_in,\n                                 false,\n                                 false,\n                                 triplet);\n\n    const auto npair_uniq = triplet.size();\n\n    if (npair_uniq != nk) {\n        error->exit(\"calc_self3omega_tetrahedron\", \"Something is wrong.\");\n    }\n\n    memory->allocate(kpairs, nk, 2);\n    memory->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    memory->allocate(v3_arr_loc, ns2);\n    memory->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                                              dynamical->eval_phonon,\n                                              dynamical->evec_phonon));\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    memory->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            memory->allocate(energy_tmp, 2, nk);\n            memory->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                memory->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[k1][is] + eval[k2][js];\n                    energy_tmp[1][ik] = eval[k1][is] - eval[k2][js];\n                }\n                for (iomega = 0; iomega < nomega; ++iomega) {\n                    for (i = 0; i < 2; ++i) {\n                        integration->calc_weight_tetrahedron(nk,\n                                                             kmap_identity,\n                                                             weight_tetra[i],\n                                                             energy_tmp[i],\n                                                             omega[iomega]);\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[k1][is];\n                        omega_inner[1] = eval[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            memory->deallocate(energy_tmp);\n            memory->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        memory->deallocate(ret_private);\n    }\n\n    memory->deallocate(v3_arr);\n    memory->deallocate(kmap_identity);\n    memory->deallocate(kpairs);\n}\n", "meta": {"hexsha": "f810c0e8b711eeeaf48b6fb83158e01809248630", "size": 49769, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "anphon/anharmonic_core.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/anharmonic_core.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/anharmonic_core.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": 32.1090322581, "max_line_length": 112, "alphanum_fraction": 0.4747935462, "num_tokens": 14357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.63341027751814, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.26040184977107134}}
{"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_COS_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_COS_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-trigonometric\n    This function object returns the cosine of the input in radians.\n\n\n    @par Header <boost/simd/function/cos.hpp>\n\n    @par Notes\n      The regular call to this functor is `cos(x)`,  but\n    @c cos can also be called with two parameters as\n      `cos(x, range_)` or with a decorator as `std_(cos)(x)` or `restricted_(cos)(x)`\n\n\n    @c range_ is a tag that allows some control on the computation\n      accuracy and speed.\n\n      The control is on the reduction routine of the angle to the\n      \\f$[-\\pi/4, \\pi/4]\\f$ interval.\n\n      They actually are 3 reduction routines that respectly are\n      sufficient for small_, medium_ and big_ angle values respecttively,\n      to have (within\n      cover test) one ulp of difference with the according crlibm\n      (correctly rounded math library) result.\n\n      Each tag covers respectively intervals \\f$[-A, A]\\f$ with :\n\n      <center>\n        |             |   float  A       |  double  A     |\n        |:-----------:|:----------------:|:--------------:|\n        |    small_   |    \\f$20\\pi\\f$   | \\f$20\\pi\\f$    |\n        |    medium_  |   \\f$2^6\\pi\\f$   | \\f$2^{18}\\pi\\f$|\n        |     big_    |   \\f$\\infty\\f$   | \\f$\\infty\\f$   |\n      </center>\n\n       In fact for each scalar singleton or simd vector of angles\n       there are two possibilities :\n       \\arg one is to test if all vector element(s) are in the proper range\n       for the consecutive increasing values of A until we reach a good\n       one or the last :\n       the corresponding template tags are @c small_, @c medium_ and @c big_\n       \\arg the second is to force directly a reduction method:\n       the corresponding template tags are @c direct_small_, @c direct_medium_\n       and @c direct_big_\n\n\n       @par\n       direct_small_ is NOT equivalent to small_ because there are also\n       two other methods for \\f$[0, \\pi/4]\\f$ (no reduction)\n       and \\f$[\\pi/4, \\pi/2]\\f$\n       (straight reduction) that are not considered in direct small_\n\n       Note that for float the direct_big_ case is both early an hyper costly and\n       shall be avoided whenever possible. To partially achieve this aim\n       when double are available on the platform, this part of reduction\n       is delegated to the double precision routines.\n\n    @par Advices\n       \\arg If there is no restrictions ever on your angles and you care for precision\n       use the default @c cos(x) or equivalently `cos(x, big_)`.\n       \\arg if you do not care for precision you can use\n       `cos(x, medium_)` or `cos(x, small_)`\n       that will be accurate for their proper range and degrade in accuracy\n       with greater values.\n\n       @par\n       Now, the choice of direct or not relies on probabilities\n       computations:\n       assuming that a vector contains k elements and that testing all\n       values that are in an interval takes c cycles and the probability of a value\n       to be in interval \\f$[a, b]\\f$ is \\f$p(a, b)\\f$\n       the number of cycles used by a\n       direct\\f${}_i\\f$ method is simply the reduction time:\n       \\f$N(\\f$direct\\f${}_i)\\f$\n       On the other side the number of cycles for the non-direct methods will have a more\n       complicated expression :\n\n       \\f$\\hspace{5em}\\sum_{i=1}^{m} p(A_{i-1}, A_i)^k N(\\f$direct\\f${}_i)\\f$\n\n       @par\n       So the non direct methods will be interesting only if you want accurate\n       results everywhere and have anyhow a big proportion of small angles.\n       This is even more true (if possible) in simd and the more k is big, because\n       of the kth power.\n\n       @par\n       For instance in the medium_ float case:\n\n       \\arg if angles are equidistributed  on \\f$[0, 2^{16} \\pi]\\f$,\n       the \\f$p(0, 20\\pi)\\f$ will be\n       less than \\f$2^{-11}\\f$ and thus (for example) if \\f$k=4\\f$,\n       there will be 1 quadruple over 1.76e+13 falling in the small_ case...\n\n       \\arg Even sorting will do no good because the sort cost will be against\n       the ratio of 1 successful quadruplet over 2048.\n       \\arg  Contrarily if your angles have a gaussian distribution with 0 mean and\n       \\f$10\\pi\\f$ standard deviation,  80% of the intervals will be in the \"small_\"\n       case (95% of the values).\n       \\arg Finally for those that are sure of their angles taking place in a fixed\n       range and want speed, three other template tags can be of choice as they use\n       the chosen reduction, but return Nan for any outsider.\n\n       <center>\n         `clipped_very_small_`, `clipped_small_` and `clipped_medium_`\n       </center>\n\n    @par Decorators\n\n       - std_ provides access to std::cos\n\n       - restricted_ is equivalent to the clipped_very_small_ tag\n\n    @see  sincos, cosd, cospi\n\n    @par Example:\n\n      @snippet cos.cpp cos\n\n    @par Possible output:\n\n      @snippet cos.txt cos\n\n  **/\n  IEEEValue cos(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/cos.hpp>\n#include <boost/simd/function/simd/cos.hpp>\n\n#endif\n", "meta": {"hexsha": "39f5bfb29e20bcbf1a067f3da7498f46ef9e8b79", "size": 5537, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/cos.hpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/function/cos.hpp", "max_issues_repo_name": "TobiasLudwig/boost.simd", "max_issues_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/function/cos.hpp", "max_forks_repo_name": "TobiasLudwig/boost.simd", "max_forks_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-02-16T09:58:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:22:43.000Z", "avg_line_length": 37.1610738255, "max_line_length": 100, "alphanum_fraction": 0.6229004876, "num_tokens": 1406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2602630037940149}}
{"text": "//=======================================================================\n// Copyright (c)\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n  * @file thorup_2kminus1.hpp\n  * @brief\n  * @author Jakub Ocwieja\n  * @version 1.0\n  * @date 2014-04-28\n  */\n\n#ifndef PAAL_THORUP_2KMINUS1_HPP\n#define PAAL_THORUP_2KMINUS1_HPP\n\n#include \"paal/utils/functors.hpp\"\n#include \"paal/utils/irange.hpp\"\n#include \"paal/utils/assign_updates.hpp\"\n\n#include <boost/range/as_array.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/dijkstra_shortest_paths_no_color_map.hpp>\n\n#include <queue>\n#include <unordered_map>\n#include <limits>\n#include <random>\n#include <cmath>\n\nnamespace paal {\n\n/**\n* @brief 2k-1 approximate distance oracle\n*\n* @tparam Graph graph\n* @tparam EdgeWeightMap edge weight map\n* @tparam VertexIndexMap vertex index map\n* @tparam Rand random engine\n*/\ntemplate <  typename Graph,\n            typename VertexIndexMap,\n            typename EdgeWeightMap,\n            typename Rand=std::default_random_engine\n            >\nclass distance_oracle_thorup2kminus1approximation {\n    using DT = typename boost::property_traits<EdgeWeightMap>::value_type;\n    using VT = typename boost::graph_traits<Graph>::vertex_descriptor;\n\n    //! List of pairs (vertex index, distance to vertex)\n    using DVect = std::vector< std::pair<int, DT> >;\n\n    //! Maps vertex in a bunch into a distance to it\n    using BunchMap = std::unordered_map<int, DT>;\n\n    //! Index map stored to access internal structures\n    VertexIndexMap m_index;\n\n    //! For each vertex v a maximal layer number for which v belongs\n    /** A_0 = V\n    *   A_{i+1} \\subset A_i\n    *   A_k = \\emptyset\n    */\n    std::vector< int > m_layer_num;\n\n    //! For each vertex v a list of vertices of consecutive layers closest to v\n    std::vector< DVect > m_parent;\n\n    //! For each vertex v a set of vertices w closer to v than any vertex in layer m_layer_num[w]+1\n    std::vector< BunchMap > m_bunch;\n\n    /**\n    * @brief Fills m_layer_num\n    *\n    * @param g Graph\n    * @param k Approximation parameter = maximal number of layers\n    * @param p Probability of being chosen to a next layer\n    * @param random_engine Random engine\n    *\n    * @return Number of nonempty layers\n    */\n    int choose_layers(const Graph& g, int k, long double p, Rand & random_engine) {\n        std::uniform_real_distribution<> dist(0,1);\n\n        int max_layer_num = 0;\n        long double logp = log(p);\n\n        for (int ind: irange(num_vertices(g))) {\n            m_layer_num[ind] = std::min(k-1, (int)(log(dist(random_engine)) / logp));\n            assign_max(max_layer_num, m_layer_num[ind]);\n        }\n\n        return max_layer_num+1;\n    }\n\n    /**\n     * @brief A visitor implementation for compute_parents Dijkstra's algorithm call\n     *\n     * @tparam NearestMap\n     * @tparam Tag\n     */\n    template <typename NearestMap, typename Tag>\n    class nearest_recorder : boost::base_visitor< nearest_recorder<NearestMap, Tag> > {\n\n        //! Stores distances to the closest vertex in a particular layer\n        NearestMap m_nearest_map;\n\n    public:\n        using event_filter = Tag;\n\n        //! Constructor\n        explicit nearest_recorder(NearestMap const nearest_map) : m_nearest_map(nearest_map) {}\n\n        //! Copies nearest value from precdessor\n        template <typename Edge>\n        void operator()(Edge const e, Graph const &g) const {\n            auto nearest = get(m_nearest_map, source(e,g));\n            put(m_nearest_map, target(e,g), nearest);\n        }\n\n    };\n\n    //! Constructs a visitor for compute_parents Dijkstra's algorithm call\n    template <typename NearestMap, typename Tag>\n    nearest_recorder<NearestMap, Tag>\n    make_nearest_recorder(NearestMap nearest_map, Tag) {\n        return nearest_recorder<NearestMap, Tag>{nearest_map};\n    }\n\n    /**\n    * @brief Fills m_parent for a single layer\n    *\n    * @param g Graph\n    * @param layer_num Number of layer\n    */\n    void compute_parents(const Graph& g, EdgeWeightMap edge_weight, int layer_num) {\n        std::vector<DT> distance(num_vertices(g), std::numeric_limits<DT>::max());\n        std::vector<int> nearest(num_vertices(g), -1);\n        std::vector<VT> roots;\n\n        for (auto v: boost::as_array(vertices(g))) {\n            int v_ind = m_index[v];\n            if (m_layer_num[v_ind] >= layer_num) {\n                nearest[v_ind] = v_ind;\n                distance[v_ind] = DT{};\n                roots.push_back(v);\n            }\n        }\n\n        boost::dijkstra_shortest_paths_no_init(\n                g,\n                roots.begin(),\n                roots.end(),\n                boost::dummy_property_map(),\n                make_iterator_property_map(distance.begin(), m_index, distance[0]),\n                edge_weight,\n                m_index,\n                utils::less{},\n                boost::closed_plus<DT>(),\n                DT{},\n                boost::make_dijkstra_visitor(make_nearest_recorder(\n                        make_iterator_property_map(nearest.begin(), m_index, nearest[0]),\n                        boost::on_edge_relaxed{})\n                    )\n            );\n\n        for (int ind: irange(num_vertices(g))) {\n            m_parent[ind].push_back(std::make_pair(nearest[ind], distance[ind]));\n        }\n    }\n\n     //! A distance type crafted to control logic of compute_cluster Dijkstra's algorithm call\n    class cluster_dist {\n        //! An actual distance\n        DT m_value;\n        //! Marks unmodified vertices\n        bool m_unmodified;\n\n        //! Private constructor\n        cluster_dist(DT value, bool unmodified) :\n            m_value(value), m_unmodified(unmodified) {}\n\n    public:\n        //! Public constructor\n        cluster_dist(DT value = DT{}) :\n            m_value(value), m_unmodified(false) {}\n\n        //! Allows to create unmodified distances\n        static cluster_dist\n        make_limit(DT value = std::numeric_limits<DT>::max()) {\n            return cluster_dist(value, true);\n        }\n\n        //! A comparator struct adjusted to recognize unmodified values\n        /** Unmodified values are not smaller then any modified value. To recognize an umodified value we compare it\n         *  with a maximal modified value of DT\n         */\n        struct less {\n            //! A comparison operator\n            bool operator()(cluster_dist a, cluster_dist b) const {\n                return (a.m_value < b.m_value) && (b.m_unmodified || !a.m_unmodified);\n            }\n        };\n\n        //! Plus operation struct\n        struct plus {\n            //! Sum operator\n            cluster_dist operator()(cluster_dist a, cluster_dist b) const {\n                return cluster_dist(a.m_value + b.m_value, a.m_unmodified || b.m_unmodified);\n            }\n        };\n\n        //! An accessor to the distance\n        const DT value() const {\n            return m_value;\n        }\n    };\n\n    /**\n     * @brief A property_map with lazy initialization of distances\n     *\n     * For each vertex of a graph a distance is initialized with an upper limit on a value which causes edge\n     * relaxation in compute_cluster Dijkstra's algorithm.\n     */\n    class cluster_distance_wrapper :\n        public boost::put_get_helper<cluster_dist&, cluster_distance_wrapper>\n    {\n        //! A wrapped distance table\n        std::vector< cluster_dist > *m_distance;\n\n        //! An index map stored to access table structures\n        VertexIndexMap m_index;\n\n        //! A pointer to a parent table containing initial values of fields of m_distance\n        /** The values stored here are copied into m_distance table when m_distance fields are accessed for the\n         *  first time. For each vertex of a graph it contains an upper limit on a value which causes edge relaxation\n         *  in compute_cluster Dijkstra's algorithm.\n         */\n        std::vector< DT > *m_limit;\n\n        //! A table storing last access time to m_distance fields\n        std::vector<int> *m_last_accessed;\n\n        //! A value necessary to interpret m_last_accessed\n        /** The value is initially different than any value in m_last_accessed.\n         *  However, it is not necessarily bigger.\n         */\n        int m_now;\n\n    public:\n        typedef VT key_type;\n        typedef cluster_dist value_type;\n        typedef value_type& reference;\n        typedef boost::lvalue_property_map_tag category;\n\n        /**\n         * @brief Constructor\n         *\n         * @param distance A helper vector - required to have num_vertices(g) fields\n         * @param index An index map\n         * @param limit Compute_cluster Dijkstra's algorithm relaxation limits\n         * @param last_accessed A helper vector - required to have num_vertices(g) fields\n         * @param now Required to be different than any last_accessed value\n         */\n        cluster_distance_wrapper(\n                std::vector< cluster_dist > *distance,\n                VertexIndexMap index,\n                std::vector< DT > *limit,\n                std::vector< int > *last_accessed,\n                int now) :\n            m_distance(distance),\n            m_index(index),\n            m_limit(limit),\n            m_last_accessed(last_accessed),\n            m_now(now) {}\n\n        /**\n         * @brief Map values accessor\n         *\n         * @param key Key\n         *\n         * @return Value\n         */\n        reference operator[](const key_type& key) const {\n            int k_ind = m_index[key];\n            if ((*m_last_accessed)[k_ind] != m_now) {\n                (*m_last_accessed)[k_ind] = m_now;\n                (*m_distance)[k_ind] = cluster_dist::make_limit((*m_limit)[k_ind]);\n            }\n            return (*m_distance)[k_ind];\n        }\n    };\n\n    /**\n     * @brief A visitor implementation for a compute_cluster Dijkstra's algorithm call\n     *\n     * @tparam DistanceMap\n     * @tparam Tag\n     */\n    template <typename DistanceMap, typename Tag>\n    class cluster_recorder : boost::base_visitor< cluster_recorder<DistanceMap, Tag> > {\n        //! Vertex whose cluster is recorded\n        int m_w_ind;\n\n        //! A pointer to m_bunch field of the oracle\n        std::vector< BunchMap >* m_bunch;\n\n        //! Index map stored to access internal structures\n        VertexIndexMap m_index;\n\n        //! A distance map\n        DistanceMap m_distance;\n\n    public:\n        using event_filter = Tag;\n\n        explicit cluster_recorder(int w_ind, std::vector<BunchMap> *bunch,\n                VertexIndexMap index, DistanceMap distance) :\n            m_w_ind(w_ind), m_bunch(bunch), m_index(index), m_distance(distance) {}\n\n        template <typename Vertex>\n        void operator()(Vertex const v, Graph const &g) const {\n            (*m_bunch)[m_index[v]].insert(std::make_pair(m_w_ind, m_distance[v].value()));\n        }\n    };\n\n    /**\n     * @brief\n     *\n     * @tparam DistanceMap\n     * @tparam Tag\n     * @param cluster\n     * @param index\n     * @param distance\n     * @param Tag\n     *\n     * @return A visitor for a compute_cluster Dijkstra's algorithm call\n     */\n    template <typename DistanceMap, typename Tag>\n    cluster_recorder<DistanceMap, Tag>\n    make_cluster_recorder(int w_ind, std::vector<BunchMap> *bunch, VertexIndexMap index,\n            DistanceMap distance, Tag) {\n        return cluster_recorder<DistanceMap, Tag>{w_ind, bunch, index, distance};\n    };\n\n    /**\n     * @brief Fills bunchs with vertices inside a cluster - a set of vertices\n     *        which contains w in its bunch\n     *\n     * @param g Graph\n     * @param edge_weight Edge weights\n     * @param w Vertex\n     * @param k Number of layers\n     * @param limit Dijkstra's algorithm relaxation limits for each layer\n     * @param distance A helper vector - required to have num_vertices(g) fields\n     * @param last_accessed A helper vector - require to be initialized with negative values\n     */\n    void compute_cluster(const Graph& g, EdgeWeightMap edge_weight, VT w, int k,\n            std::vector< std::vector<DT> > &limit,\n            std::vector<cluster_dist> &distance, std::vector<int> &last_accessed) {\n        DVect cluster;\n        int w_ind = m_index[w];\n        int w_layer_num = m_layer_num[w_ind];\n\n        cluster_distance_wrapper distance_wrapper(\n                &distance, m_index, &limit[w_layer_num + 1],\n                &last_accessed, w_ind);\n        distance_wrapper[w] = cluster_dist(DT{});\n\n        boost::dijkstra_shortest_paths_no_color_map_no_init(\n                g,\n                w,\n                boost::dummy_property_map(),\n                distance_wrapper,\n                edge_weight,\n                m_index,\n                typename cluster_dist::less(),\n                typename cluster_dist::plus(),\n                cluster_dist(std::numeric_limits<DT>::max()),\n                cluster_dist(DT{}),\n                boost::make_dijkstra_visitor(make_cluster_recorder(\n                        w_ind, &m_bunch, m_index, distance_wrapper,\n                        boost::on_examine_vertex{})\n                    )\n            );\n    }\n\n    /**\n    * @brief Fills m_bunch\n    *\n    * @param g Graph\n    * @param edge_weight Edge weight\n    * @param k Number of layers\n    */\n    void compute_bunchs(const Graph& g, EdgeWeightMap edge_weight, int k) {\n        //! Initialization of reusable structures\n        std::vector< std::vector<DT> > limit(k+1,\n                std::vector<DT>(num_vertices(g), std::numeric_limits<DT>::max()));\n        for (int l: irange(k)) {\n            for (int i: irange(num_vertices(g))) {\n                limit[l][i] = m_parent[i][l].second;\n            }\n        }\n        std::vector<cluster_dist> distance(num_vertices(g));\n        std::vector<int> last_accessed(num_vertices(g), -1);\n\n        for (auto v: boost::as_array(vertices(g))) {\n            compute_cluster(g, edge_weight, v, k, limit, distance, last_accessed);\n        }\n    }\n\npublic:\n\n    /**\n    * @brief Constructor\n    *\n    * @param g graph\n    * @param index vertex index map\n    * @param edge_weight edge weight map\n    * @param k approximation parameter\n    * @param random_engine random engine\n    */\n    distance_oracle_thorup2kminus1approximation(const Graph &g,\n            VertexIndexMap index,\n            EdgeWeightMap edge_weight,\n            int k,\n            Rand && random_engine = Rand(5426u)) :\n        m_index(index),\n        m_layer_num(num_vertices(g)),\n        m_parent(num_vertices(g)),\n        m_bunch(num_vertices(g))\n            {\n        long double p = powl(num_vertices(g), -1./k);\n        k = choose_layers(g, k, p, random_engine);\n        for (int layer_num: irange(k)) {\n            compute_parents(g, edge_weight, layer_num);\n        }\n        compute_bunchs(g, edge_weight, k);\n    }\n\n    //! Returns an 2k-1 approximate distance between two vertices in O(k) time\n    /** Returns a distance of path going through one of parents of u or v */\n    DT operator()(VT u, VT v) const {\n        int u_ind = m_index[u], v_ind = m_index[v];\n        typename std::unordered_map<int, DT>::const_iterator it;\n        int l = 0;\n        std::pair<int, DT> middle_vertex = m_parent[u_ind][l];\n        while ((it = m_bunch[v_ind].find(middle_vertex.first)) == m_bunch[v_ind].end()) {\n            ++l;\n            middle_vertex = m_parent[v_ind][l];\n            std::swap(u_ind, v_ind);\n        }\n        //! Returns d(v, middle) + d(middle, u)\n        return it->second + middle_vertex.second;\n    }\n};\n\n/**\n* @brief\n*\n* @tparam Graph\n* @tparam EdgeWeightMap\n* @tparam VertexIndexMap\n* @tparam Rand\n* @param g - given graph\n* @param k - approximation parameter\n* @param index - graph index map\n* @param edge_weight - graph edge weight map\n* @param random_engine - random engine\n*\n* @return 2k-1 approximate distance oracle\n*/\ntemplate <  typename Graph,\n            typename EdgeWeightMap,\n            typename VertexIndexMap,\n            typename Rand=std::default_random_engine\n         >\ndistance_oracle_thorup2kminus1approximation<Graph, VertexIndexMap, EdgeWeightMap, Rand>\nmake_distance_oracle_thorup2kminus1approximation(\n        const Graph &g,\n        const int k,\n        VertexIndexMap index,\n        EdgeWeightMap edge_weight,\n        Rand && random_engine = Rand(5426u)) {\n    return distance_oracle_thorup2kminus1approximation<Graph,\n    VertexIndexMap,\n    EdgeWeightMap,\n    Rand>(g, index, edge_weight, k, std::move(random_engine));\n}\n\n/**\n* @brief\n*\n* @tparam Graph\n* @tparam P\n* @tparam T\n* @tparam R\n* @tparam Rand\n* @param g - given graph\n* @param k - approximation parameter\n* @param params - named parameters\n* @param random_engine - random engine\n*\n* @return 2k-1 approximate distance oracle\n*/\ntemplate <  typename Graph,\n            typename P = char,\n            typename T = boost::detail::unused_tag_type,\n            typename R = boost::no_property,\n            typename Rand=std::default_random_engine\n         >\nauto\nmake_distance_oracle_thorup2kminus1approximation(\n        const Graph &g,\n        const int k,\n        const boost::bgl_named_params<P, T, R>& params = boost::no_named_parameters(),\n        Rand && random_engine = Rand(5426u))\n    -> distance_oracle_thorup2kminus1approximation<Graph,\n    decltype(choose_const_pmap(get_param(params, boost::vertex_index), g, boost::vertex_index)),\n    decltype(choose_const_pmap(get_param(params, boost::edge_weight), g, boost::edge_weight)),\n    Rand> {\n    return make_distance_oracle_thorup2kminus1approximation(g,\n            k,\n            choose_const_pmap(get_param(params, boost::vertex_index), g, boost::vertex_index),\n            choose_const_pmap(get_param(params, boost::edge_weight), g, boost::edge_weight),\n            std::move(random_engine));\n}\n\n} //paal\n\n#endif // PAAL_THORUP_2KMINUS1_HPP\n", "meta": {"hexsha": "3625a49c4749381db64a3d66f1df5177735f70e8", "size": 18055, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/distance_oracle/vertex_vertex/thorup_2kminus1.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/distance_oracle/vertex_vertex/thorup_2kminus1.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/distance_oracle/vertex_vertex/thorup_2kminus1.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": 33.6219739292, "max_line_length": 117, "alphanum_fraction": 0.6099141512, "num_tokens": 4190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891307678319, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.260096432389457}}
{"text": "/*\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 *\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 Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\n * The Original Code is Copyright (C) 2015 Blender Foundation.\n * All rights reserved.\n */\n\n#ifndef __EIGEN3_EIGENVALUES_C_API_CC__\n#define __EIGEN3_EIGENVALUES_C_API_CC__\n\n/* Eigen gives annoying huge amount of warnings here, silence them! */\n#if defined(__GNUC__) && !defined(__clang__)\n#  pragma GCC diagnostic ignored \"-Wlogical-op\"\n#endif\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n\n#include \"eigenvalues.h\"\n\nusing Eigen::SelfAdjointEigenSolver;\n\nusing Eigen::Map;\nusing Eigen::MatrixXf;\nusing Eigen::VectorXf;\n\nusing Eigen::Success;\n\nbool EIG_self_adjoint_eigen_solve(const int size,\n                                  const float *matrix,\n                                  float *r_eigen_values,\n                                  float *r_eigen_vectors)\n{\n  SelfAdjointEigenSolver<MatrixXf> eigen_solver;\n\n  /* Blender and Eigen matrices are both column-major. */\n  eigen_solver.compute(Map<MatrixXf>((float *)matrix, size, size));\n\n  if (eigen_solver.info() != Success) {\n    return false;\n  }\n\n  if (r_eigen_values) {\n    Map<VectorXf>(r_eigen_values, size) = eigen_solver.eigenvalues().transpose();\n  }\n\n  if (r_eigen_vectors) {\n    Map<MatrixXf>(r_eigen_vectors, size, size) = eigen_solver.eigenvectors();\n  }\n\n  return true;\n}\n\n#endif /* __EIGEN3_EIGENVALUES_C_API_CC__ */\n", "meta": {"hexsha": "8a48ae5f17ad549a2f62d41c87cb430ab2c2798f", "size": 2017, "ext": "cc", "lang": "C++", "max_stars_repo_path": "intern/eigen/intern/eigenvalues.cc", "max_stars_repo_name": "rbabari/blender", "max_stars_repo_head_hexsha": "6daa85f14b2974abfc3d0f654c5547f487bb3b74", "max_stars_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_stars_count": 365.0, "max_stars_repo_stars_event_min_datetime": "2015-02-10T15:10:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T15:50:51.000Z", "max_issues_repo_path": "intern/eigen/intern/eigenvalues.cc", "max_issues_repo_name": "rbabari/blender", "max_issues_repo_head_hexsha": "6daa85f14b2974abfc3d0f654c5547f487bb3b74", "max_issues_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_issues_count": 45.0, "max_issues_repo_issues_event_min_datetime": "2015-01-09T15:34:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-05T14:44:23.000Z", "max_forks_repo_path": "intern/eigen/intern/eigenvalues.cc", "max_forks_repo_name": "rbabari/blender", "max_forks_repo_head_hexsha": "6daa85f14b2974abfc3d0f654c5547f487bb3b74", "max_forks_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_forks_count": 172.0, "max_forks_repo_forks_event_min_datetime": "2015-01-25T15:16:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T08:25:36.000Z", "avg_line_length": 30.1044776119, "max_line_length": 81, "alphanum_fraction": 0.7089737234, "num_tokens": 488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.26002653512844814}}
{"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_DISCRETIZATIONS_SWIPDG_HH\n#define DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_SWIPDG_HH\n\n#include <memory>\n#include <vector>\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <dune/common/timer.hh>\n#include <dune/common/static_assert.hh>\n\n#include <dune/stuff/common/disable_warnings.hh>\n# if HAVE_ALUGRID\n#   include <dune/grid/alugrid.hh>\n# endif\n#include <dune/stuff/common/reenable_warnings.hh>\n\n#if HAVE_DUNE_GRID_MULTISCALE\n# include <dune/grid/multiscale/provider/interface.hh>\n#endif\n\n#include <dune/stuff/common/configuration.hh>\n#include <dune/stuff/common/timedlogging.hh>\n#include <dune/stuff/grid/layers.hh>\n#include <dune/stuff/grid/provider.hh>\n#include <dune/stuff/la/container.hh>\n#include <dune/stuff/la/solver.hh>\n#include <dune/stuff/grid/walker/functors.hh>\n\n#include <dune/gdt/assembler/system.hh>\n#include <dune/gdt/assembler/tmp-storage.hh>\n#include <dune/gdt/discretefunction/default.hh>\n#include <dune/gdt/functionals/l2.hh>\n#include <dune/gdt/operators/oswaldinterpolation.hh>\n#include <dune/gdt/operators/projections.hh>\n#include <dune/gdt/playground/functionals/swipdg.hh>\n#include <dune/gdt/playground/operators/elliptic-swipdg.hh>\n#include <dune/gdt/playground/operators/fluxreconstruction.hh>\n#include <dune/gdt/playground/products/swipdgpenalty.hh>\n#include <dune/gdt/spaces/fv/default.hh>\n#include <dune/gdt/spaces/rt/pdelab.hh>\n#include <dune/gdt/spaces/dg.hh>\n\n#include \"base.hh\"\n\nnamespace Dune {\nnamespace HDD {\nnamespace LinearElliptic {\nnamespace Discretizations {\n\n\n// forward, for friendlyness\ntemplate< class GridImp, class RangeFieldImp, int rangeDim, int polynomialOrder, Stuff::LA::ChooseBackend la_backend >\nclass BlockSWIPDG;\n\n\n// forward, needed in the Traits\ntemplate< class GridImp, Stuff::Grid::ChooseLayer layer, class RangeFieldImp, int rangeDim, int polynomialOrder = 1,\n#if HAVE_DUNE_FEM\n          GDT::ChooseSpaceBackend space_backend = GDT::ChooseSpaceBackend::fem,\n#else\n# error No suitable space backend available!\n#endif\n          Stuff::LA::ChooseBackend la_backend  = Stuff::LA::default_sparse_backend >\nclass SWIPDG;\n\n\nnamespace internal {\n\n\ntemplate< class GridImp, Stuff::Grid::ChooseLayer layer, class RangeFieldImp, int rangeDim, int polynomialOrder,\n          GDT::ChooseSpaceBackend space_backend,\n          Stuff::LA::ChooseBackend la_backend >\nclass SWIPDGTraits\n  : public internal::ContainerBasedDefaultTraits< typename Stuff::LA::Container< RangeFieldImp, la_backend >::MatrixType,\n                                                  typename Stuff::LA::Container< RangeFieldImp, la_backend >::VectorType>\n{\npublic:\n  typedef SWIPDG< GridImp, layer, RangeFieldImp, rangeDim, polynomialOrder, space_backend, la_backend > derived_type;\n  typedef GridImp GridType;\n  typedef RangeFieldImp RangeFieldType;\n  static const unsigned int dimRange = rangeDim;\n  static const unsigned int polOrder = polynomialOrder;\n\nprivate:\n  typedef GDT::Spaces::DGProvider< GridType, layer, space_backend, polOrder, RangeFieldType, dimRange > SpaceProvider;\n\n  friend class SWIPDG< GridImp, layer, RangeFieldImp, rangeDim, polynomialOrder, space_backend, la_backend >;\n\npublic:\n  typedef typename SpaceProvider::Type TestSpaceType;\n  typedef TestSpaceType AnsatzSpaceType;\n  typedef typename TestSpaceType::GridViewType GridViewType;\n}; // class SWIPDGTraits\n\n\n} // namespace internal\n\n\ntemplate< class GridImp, Stuff::Grid::ChooseLayer layer, class RangeFieldImp, int rangeDim, int polynomialOrder,\n          GDT::ChooseSpaceBackend space_backend,\n          Stuff::LA::ChooseBackend la_backend >\nclass SWIPDG\n  : public ContainerBasedDefault< internal::SWIPDGTraits< GridImp, layer, RangeFieldImp, rangeDim, polynomialOrder,\n                                                          space_backend, la_backend > >\n{\n  typedef ContainerBasedDefault< internal::SWIPDGTraits< GridImp, layer, RangeFieldImp, rangeDim, polynomialOrder,\n                                                         space_backend, la_backend > > BaseType;\n  typedef SWIPDG< GridImp, layer, RangeFieldImp, rangeDim, polynomialOrder, space_backend, la_backend > ThisType;\npublic:\n  typedef internal::SWIPDGTraits< GridImp, layer, RangeFieldImp, rangeDim, polynomialOrder, space_backend, la_backend >\n      Traits;\n  typedef GridImp GridType;\n  using typename BaseType::ProblemType;\n  using typename BaseType::BoundaryInfoType;\n  using typename BaseType::TestSpaceType;\n  using typename BaseType::AnsatzSpaceType;\n  using typename BaseType::MatrixType;\n  using typename BaseType::VectorType;\n  using typename BaseType::GridViewType;\n  using typename BaseType::RangeFieldType;\n\n  typedef typename TestSpaceType::PatternType PatternType;\n\n  static const unsigned int dimDomain = BaseType::dimDomain;\n  static const unsigned int dimRange = BaseType::dimRange;\n\nprivate:\n  typedef typename Traits::SpaceProvider SpaceProvider;\n\n  typedef Stuff::Grid::ProviderInterface< GridType >      GridProviderType;\n#if HAVE_DUNE_GRID_MULTISCALE\n  typedef grid::Multiscale::ProviderInterface< GridType > MsGridProviderType;\n#endif\n  using typename BaseType::AffinelyDecomposedMatrixType;\n  using typename BaseType::AffinelyDecomposedVectorType;\n\n  typedef typename ProblemType::DiffusionFactorType::NonparametricType DiffusionFactorType;\n  typedef typename ProblemType::DiffusionTensorType::NonparametricType DiffusionTensorType;\n  typedef GDT::Operators::EllipticSWIPDG< DiffusionFactorType, MatrixType\n                                        , TestSpaceType, AnsatzSpaceType\n                                        , GridViewType, DiffusionTensorType > EllipticOperatorType;\n\npublic:\n  static std::string static_id();\n\n  template< Stuff::Grid::ChooseLayer lr = layer >\n  SWIPDG(GridProviderType& grid_provider,\n         const Stuff::Common::Configuration& bound_inf_cfg,\n         const ProblemType& prob,\n         const int level_or_subdomain = 0,\n         const std::vector< std::string >& only_these_products = {}\n#if HAVE_DUNE_GRID_MULTISCALE\n       , typename std::enable_if<    (lr != Stuff::Grid::ChooseLayer::local)\n                                  && (lr != Stuff::Grid::ChooseLayer::local_oversampled), void >::type* /*disable_for_local_grid_parts*/ = nullptr\n#endif\n        );\n\n#if HAVE_DUNE_GRID_MULTISCALE\n\n  SWIPDG(const MsGridProviderType& grid_provider,\n         const Stuff::Common::Configuration& bound_inf_cfg,\n         const ProblemType& prob,\n         const int level_or_subdomain = 0,\n         const std::vector< std::string >& only_these_products = {});\n\n#endif // HAVE_DUNE_GRID_MULTISCALE\n\n  void init(const bool prune = false);\n\nprivate:\n  friend class BlockSWIPDG< GridImp, RangeFieldImp, rangeDim, polynomialOrder, la_backend >;\n\n  const RangeFieldType beta_;\n  using BaseType::pattern_;\n  const std::vector< std::string > only_these_products_;\n}; // class SWIPDG\n\n\n#if HAVE_ALUGRID && HAVE_DUNE_FEM\n# if HAVE_DUNE_ISTL\n\nextern template class SWIPDG< ALUGrid< 2, 2, simplex, conforming, No_Comm >,\n                              Stuff::Grid::ChooseLayer::leaf,\n                              double,\n                              1,\n                              1,\n                              GDT::ChooseSpaceBackend::fem,\n                              Stuff::LA::ChooseBackend::istl_sparse >;\nextern template SWIPDG< ALUGrid< 2, 2, simplex, conforming, No_Comm >,\n                        Stuff::Grid::ChooseLayer::leaf,\n                        double,\n                        1,\n                        1,\n                        GDT::ChooseSpaceBackend::fem,\n                        Stuff::LA::ChooseBackend::istl_sparse >\n    ::SWIPDG< Stuff::Grid::ChooseLayer::leaf >(GridProviderType&,\n                                               const Stuff::Common::Configuration&,\n                                               const ProblemType&,\n                                               const int level_or_subdomain,\n                                               const std::vector< std::string >&,\n                                               void*);\n\nextern template class SWIPDG< ALUGrid< 2, 2, simplex, conforming, No_Comm >,\n                              Stuff::Grid::ChooseLayer::level,\n                              double,\n                              1,\n                              1,\n                              GDT::ChooseSpaceBackend::fem,\n                              Stuff::LA::ChooseBackend::istl_sparse >;\nextern template SWIPDG< ALUGrid< 2, 2, simplex, conforming, No_Comm >,\n                        Stuff::Grid::ChooseLayer::level,\n                        double,\n                        1,\n                        1,\n                        GDT::ChooseSpaceBackend::fem,\n                        Stuff::LA::ChooseBackend::istl_sparse >\n    ::SWIPDG< Stuff::Grid::ChooseLayer::level >(GridProviderType&,\n                                                const Stuff::Common::Configuration&,\n                                                const ProblemType&,\n                                                const int level_or_subdomain,\n                                                const std::vector< std::string >&,\n                                                void*);\n\n#   if HAVE_MPI\n\nextern template class SWIPDG< ALUGrid< 2, 2, simplex, conforming, MPI_Comm  >,\n                              Stuff::Grid::ChooseLayer::leaf,\n                              double,\n                              1,\n                              1,\n                              GDT::ChooseSpaceBackend::fem,\n                              Stuff::LA::ChooseBackend::istl_sparse >;\nextern template SWIPDG< ALUGrid< 2, 2, simplex, conforming, MPI_Comm  >,\n                        Stuff::Grid::ChooseLayer::leaf,\n                        double,\n                        1,\n                        1,\n                        GDT::ChooseSpaceBackend::fem,\n                        Stuff::LA::ChooseBackend::istl_sparse >\n    ::SWIPDG< Stuff::Grid::ChooseLayer::leaf >(GridProviderType&,\n                                               const Stuff::Common::Configuration&,\n                                               const ProblemType&,\n                                               const int level_or_subdomain,\n                                               const std::vector< std::string >&,\n                                               void*);\n\nextern template class SWIPDG< ALUGrid< 2, 2, simplex, conforming, MPI_Comm  >,\n                              Stuff::Grid::ChooseLayer::level,\n                              double,\n                              1,\n                              1,\n                              GDT::ChooseSpaceBackend::fem,\n                              Stuff::LA::ChooseBackend::istl_sparse >;\nextern template SWIPDG< ALUGrid< 2, 2, simplex, conforming, MPI_Comm  >,\n                        Stuff::Grid::ChooseLayer::level,\n                        double,\n                        1,\n                        1,\n                        GDT::ChooseSpaceBackend::fem,\n                        Stuff::LA::ChooseBackend::istl_sparse >\n    ::SWIPDG< Stuff::Grid::ChooseLayer::level >(GridProviderType&,\n                                                const Stuff::Common::Configuration&,\n                                                const ProblemType&,\n                                                const int level_or_subdomain,\n                                                const std::vector< std::string >&,\n                                                void*);\n\n#   endif // HAVE_MPI\n#   if HAVE_DUNE_GRID_MULTISCALE\n\nextern template class SWIPDG< ALUGrid< 2, 2, simplex, conforming, No_Comm >,\n                              Stuff::Grid::ChooseLayer::local,\n                              double,\n                              1,\n                              1,\n                              GDT::ChooseSpaceBackend::fem,\n                              Stuff::LA::ChooseBackend::istl_sparse >;\n\nextern template class SWIPDG< ALUGrid< 2, 2, simplex, conforming, No_Comm >,\n                              Stuff::Grid::ChooseLayer::local_oversampled,\n                              double,\n                              1,\n                              1,\n                              GDT::ChooseSpaceBackend::fem,\n                              Stuff::LA::ChooseBackend::istl_sparse >;\n\n#     if HAVE_MPI\n\nextern template class SWIPDG< ALUGrid< 2, 2, simplex, conforming, MPI_Comm >,\n                              Stuff::Grid::ChooseLayer::local,\n                              double,\n                              1,\n                              1,\n                              GDT::ChooseSpaceBackend::fem,\n                              Stuff::LA::ChooseBackend::istl_sparse >;\n\nextern template class SWIPDG< ALUGrid< 2, 2, simplex, conforming, MPI_Comm >,\n                              Stuff::Grid::ChooseLayer::local_oversampled,\n                              double,\n                              1,\n                              1,\n                              GDT::ChooseSpaceBackend::fem,\n                              Stuff::LA::ChooseBackend::istl_sparse >;\n\n#     endif // HAVE_MPI\n#   endif // HAVE_DUNE_GRID_MULTISCALE\n# endif // HAVE_DUNE_ISTL\n# if HAVE_EIGEN\n\nextern template class SWIPDG< ALUGrid< 2, 2, simplex, conforming, No_Comm >,\n                              Stuff::Grid::ChooseLayer::leaf,\n                              double,\n                              1,\n                              1,\n                              GDT::ChooseSpaceBackend::fem,\n                              Stuff::LA::ChooseBackend::eigen_sparse >;\nextern template SWIPDG< ALUGrid< 2, 2, simplex, conforming, No_Comm >,\n                        Stuff::Grid::ChooseLayer::leaf,\n                        double,\n                        1,\n                        1,\n                        GDT::ChooseSpaceBackend::fem,\n                        Stuff::LA::ChooseBackend::eigen_sparse >\n    ::SWIPDG< Stuff::Grid::ChooseLayer::leaf >(GridProviderType&,\n                                               const Stuff::Common::Configuration&,\n                                               const ProblemType&,\n                                               const int level_or_subdomain,\n                                               const std::vector< std::string >&,\n                                               void*);\n\nextern template class SWIPDG< ALUGrid< 2, 2, simplex, conforming, No_Comm >,\n                              Stuff::Grid::ChooseLayer::level,\n                              double,\n                              1,\n                              1,\n                              GDT::ChooseSpaceBackend::fem,\n                              Stuff::LA::ChooseBackend::eigen_sparse >;\nextern template SWIPDG< ALUGrid< 2, 2, simplex, conforming, No_Comm >,\n                        Stuff::Grid::ChooseLayer::level,\n                        double,\n                        1,\n                        1,\n                        GDT::ChooseSpaceBackend::fem,\n                        Stuff::LA::ChooseBackend::eigen_sparse >\n    ::SWIPDG< Stuff::Grid::ChooseLayer::level >(GridProviderType&,\n                                                const Stuff::Common::Configuration&,\n                                                const ProblemType&,\n                                                const int level_or_subdomain,\n                                                const std::vector< std::string >&,\n                                                void*);\n\n#   if HAVE_MPI\n\nextern template class SWIPDG< ALUGrid< 2, 2, simplex, conforming, MPI_Comm  >,\n                              Stuff::Grid::ChooseLayer::leaf,\n                              double,\n                              1,\n                              1,\n                              GDT::ChooseSpaceBackend::fem,\n                              Stuff::LA::ChooseBackend::eigen_sparse >;\nextern template SWIPDG< ALUGrid< 2, 2, simplex, conforming, MPI_Comm  >,\n                        Stuff::Grid::ChooseLayer::leaf,\n                        double,\n                        1,\n                        1,\n                        GDT::ChooseSpaceBackend::fem,\n                        Stuff::LA::ChooseBackend::eigen_sparse >\n    ::SWIPDG< Stuff::Grid::ChooseLayer::leaf >(GridProviderType&,\n                                               const Stuff::Common::Configuration&,\n                                               const ProblemType&,\n                                               const int level_or_subdomain,\n                                               const std::vector< std::string >&,\n                                               void*);\n\nextern template class SWIPDG< ALUGrid< 2, 2, simplex, conforming, MPI_Comm  >,\n                              Stuff::Grid::ChooseLayer::level,\n                              double,\n                              1,\n                              1,\n                              GDT::ChooseSpaceBackend::fem,\n                              Stuff::LA::ChooseBackend::eigen_sparse >;\nextern template SWIPDG< ALUGrid< 2, 2, simplex, conforming, MPI_Comm  >,\n                        Stuff::Grid::ChooseLayer::level,\n                        double,\n                        1,\n                        1,\n                        GDT::ChooseSpaceBackend::fem,\n                        Stuff::LA::ChooseBackend::eigen_sparse >\n    ::SWIPDG< Stuff::Grid::ChooseLayer::level >(GridProviderType&,\n                                                const Stuff::Common::Configuration&,\n                                                const ProblemType&,\n                                                const int level_or_subdomain,\n                                                const std::vector< std::string >&,\n                                                void*);\n\n#   endif // HAVE_MPI\n#   if HAVE_DUNE_GRID_MULTISCALE\n\nextern template class SWIPDG< ALUGrid< 2, 2, simplex, conforming, No_Comm >,\n                              Stuff::Grid::ChooseLayer::local,\n                              double,\n                              1,\n                              1,\n                              GDT::ChooseSpaceBackend::fem,\n                              Stuff::LA::ChooseBackend::eigen_sparse >;\n\nextern template class SWIPDG< ALUGrid< 2, 2, simplex, conforming, No_Comm >,\n                              Stuff::Grid::ChooseLayer::local_oversampled,\n                              double,\n                              1,\n                              1,\n                              GDT::ChooseSpaceBackend::fem,\n                              Stuff::LA::ChooseBackend::eigen_sparse >;\n\n#     if HAVE_MPI\n\nextern template class SWIPDG< ALUGrid< 2, 2, simplex, conforming, MPI_Comm >,\n                              Stuff::Grid::ChooseLayer::local,\n                              double,\n                              1,\n                              1,\n                              GDT::ChooseSpaceBackend::fem,\n                              Stuff::LA::ChooseBackend::eigen_sparse >;\n\nextern template class SWIPDG< ALUGrid< 2, 2, simplex, conforming, MPI_Comm >,\n                              Stuff::Grid::ChooseLayer::local_oversampled,\n                              double,\n                              1,\n                              1,\n                              GDT::ChooseSpaceBackend::fem,\n                              Stuff::LA::ChooseBackend::eigen_sparse >;\n\n#     endif // HAVE_MPI\n#   endif // HAVE_DUNE_GRID_MULTISCALE\n# endif // HAVE_EIGEN\n#endif // HAVE_ALUGRID && HAVE_DUNE_FEM\n\n\n} // namespace Discretizations\n} // namespace LinearElliptic\n} // namespace HDD\n} // namespace Dune\n\n#endif // DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_SWIPDG_HH\n", "meta": {"hexsha": "b2d078565efb1a6a8778290b0807a57914e1cb7e", "size": 19900, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/hdd/linearelliptic/discretizations/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/discretizations/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/discretizations/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": 44.1241685144, "max_line_length": 146, "alphanum_fraction": 0.5224120603, "num_tokens": 4054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2600265285209796}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   MonteCarlo_ComptonProfilePolicy_def.hpp\n//! \\author Alex Robinson\n//! \\brief  Policies (defs.) for using Compton profiles\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef MONTE_CARLO_COMPTON_PROFILE_POLICY_DEF_HPP\n#define MONTE_CARLO_COMPTON_PROFILE_POLICY_DEF_HPP\n\n// Std Lib Includes\n#include <cmath>\n\n// Boost Includes\n#include <boost/units/cmath.hpp>\n\n// FRENSIE Includes\n#include \"MonteCarlo_ComptonProfile.hpp\"\n#include \"Utility_RandomNumberGenerator.hpp\"\n\nnamespace MonteCarlo{\n\n// Check if the full Compton profile is valid\n/*! \\details A full Compton profile must have a range between +/- m_e*c. The\n * upper bound can be greater than m_e*c but no less.\n */\ninline bool FullComptonProfilePolicy::isValidProfile(\n                                                const ComptonProfile& profile )\n{\n  return profile.getLowerBoundOfMomentum() == -1.0*ComptonProfile::MomentumUnit()\n    && profile.getUpperBoundOfMomentum() >= 1.0*ComptonProfile::MomentumUnit();\n}\n\n// Get the lower bound of the momentum\ninline ComptonProfile::MomentumQuantity\nFullComptonProfilePolicy::getLowerBoundOfMomentum(\n                                                const ComptonProfile& profile )\n{\n  return profile.getLowerBoundOfMomentum();\n}\n\n// Get the upper bound of the momentum\ninline ComptonProfile::MomentumQuantity\nFullComptonProfilePolicy::getUpperBoundOfMomentum(\n                                                const ComptonProfile& profile )\n{\n  return profile.getUpperBoundOfMomentum();\n}\n\n// Get lower limit of integration\n/*! \\details For a full profile the lower limit of integration will always\n * be -1.0\n */\ninline ComptonProfile::MomentumQuantity\nFullComptonProfilePolicy::getLowerLimitOfIntegration(\n                           const ComptonProfile::MomentumQuantity upper_limit )\n{\n  return -1.0*ComptonProfile::MomentumUnit();\n}\n\n// Get upper limit of integration\n/*! \\details This method simply checks if the upper limit passed is less than\n * the table max. If it is greater, the table max is returned.\n */\ninline ComptonProfile::MomentumQuantity\nFullComptonProfilePolicy::getUpperLimitOfIntegration(\n                           const ComptonProfile& profile,\n                           const ComptonProfile::MomentumQuantity upper_limit )\n{\n  if( upper_limit > profile.getUpperBoundOfMomentum() )\n    return profile.getUpperBoundOfMomentum();\n  else\n    return upper_limit;\n}  \n  \n// Evaluate a full Compton profile\ninline ComptonProfile::ProfileQuantity FullComptonProfilePolicy::evaluate(\n                              const ComptonProfile& profile,\n                              const ComptonProfile::MomentumQuantity momentum )\n{\n  return profile.evaluate( momentum );\n}\n\n// Evaluate a full Compton profile using the max momentum as a limit\n/*! \\details With a full Compton profile there is no check to see if the\n * momentum is greater than -max_momentum (as with the half profiles).\n */\ninline ComptonProfile::ProfileQuantity\nFullComptonProfilePolicy::evaluateWithPossibleLimit(\n                          const ComptonProfile& profile,\n                          const ComptonProfile::MomentumQuantity momentum,\n                          const ComptonProfile::MomentumQuantity max_momentum )\n{\n  if( momentum <= max_momentum )\n    return profile.evaluate( momentum );\n  else\n    return 0.0*ComptonProfile::ProfileUnit();\n} \n  \n// Sample from a full Compton profile\ninline ComptonProfile::MomentumQuantity FullComptonProfilePolicy::sample(\n                          const ComptonProfile& profile,\n                          const ComptonProfile::MomentumQuantity max_momentum )\n{\n  // Make sure the max momentum is valid\n  testPrecondition( max_momentum >= -1.0*ComptonProfile::MomentumUnit() );\n  \n  if( max_momentum >= profile.getUpperBoundOfMomentum() )\n    return profile.sample();\n  else\n    return profile.sampleInSubrange( max_momentum );\n}\n\n// Check if the half Compton profile is valid\n/*! \\details Using only half of the profile is a way to approximate the\n * true profile. The lower momentum bound must be zero. The upper bound\n * can be anything (since this is an approximation).\n */\ninline bool HalfComptonProfilePolicyHelper::isValidProfile(\n                                               const ComptonProfile& profile )\n{\n  return profile.getLowerBoundOfMomentum() == 0.0*ComptonProfile::MomentumUnit()\n    && profile.getUpperBoundOfMomentum() <= 1.0*ComptonProfile::MomentumUnit();\n}\n\n// Get the lower bound of the momentum\ninline ComptonProfile::MomentumQuantity\nHalfComptonProfilePolicyHelper::getLowerBoundOfMomentum(\n                                                const ComptonProfile& profile )\n{\n  return -profile.getUpperBoundOfMomentum();\n}\n\n// Get the upper bound of the momentum\ninline ComptonProfile::MomentumQuantity\nHalfComptonProfilePolicyHelper::getUpperBoundOfMomentum(\n                                                const ComptonProfile& profile )\n{\n  return profile.getUpperBoundOfMomentum();\n}\n\n// Get lower limit of integration\n/*! \\details For a half profile the lower limit of integration will be\n * -upper_limit unless the upper limit is <= 0.0, in which case it is equal\n * to the upper_limit (which ensures that the integral is zero).\n */\ninline ComptonProfile::MomentumQuantity\nHalfComptonProfilePolicyHelper::getLowerLimitOfIntegration(\n                           const ComptonProfile::MomentumQuantity upper_limit )\n{\n  if( upper_limit > 0.0*ComptonProfile::MomentumUnit() )\n    return -upper_limit;\n  else\n    return upper_limit;\n}\n\n// Get upper limit of integration\n/*! \\details This method simply checks if the upper limit passed is less than\n * the table max. If it is greater, the table max is returned.\n */\ninline ComptonProfile::MomentumQuantity\nHalfComptonProfilePolicyHelper::getUpperLimitOfIntegration(\n                           const ComptonProfile& profile,\n                           const ComptonProfile::MomentumQuantity upper_limit )\n{\n  if( upper_limit > profile.getUpperBoundOfMomentum() )\n    return profile.getUpperBoundOfMomentum();\n  else\n    return upper_limit;\n} \n\n// Sample from a half Compton profile\n/*! \\details Using only half of the profile is a way to approximate the\n * true profile. The momentum sampled from the half distribution will be\n * randomly multiplied by -1 to account for the other half of the distribution\n * (part of it at least). As the max momentum approaches zero this\n * approximation of the true distribution becomes poor. If the max momentum\n * is negative, which is physically acceptable, a momentum of zero is returned,\n * which is the value associated with no Doppler broadening (it corresponds\n * to the Compton line photon energy).\n */\ninline ComptonProfile::MomentumQuantity HalfComptonProfilePolicyHelper::sample(\n                          const ComptonProfile& profile,\n                          const ComptonProfile::MomentumQuantity max_momentum )\n{\n  // Make sure the max momentum is valid\n  testPrecondition( max_momentum >= -1.0*ComptonProfile::MomentumUnit() );\n  \n  if( max_momentum > 0.0*ComptonProfile::MomentumUnit() )\n  {\n    ComptonProfile::MomentumQuantity pz;\n\n    if( max_momentum >= profile.getUpperBoundOfMomentum() )\n      pz = profile.sample();\n    else\n      pz = profile.sampleInSubrange( max_momentum );\n\n    if( Utility::RandomNumberGenerator::getRandomNumber<double>() <= 0.5 )\n      pz *= -1.0;\n\n    return pz;\n  }\n  else\n    return 0.0*ComptonProfile::MomentumUnit();\n}\n\n// Evaluate a half Compton profile\n/*! \\details The absolute value of the momentum will be used to\n * evaluate the profile.\n */\ninline ComptonProfile::ProfileQuantity HalfComptonProfilePolicy::evaluate(\n                              const ComptonProfile& profile,\n                              const ComptonProfile::MomentumQuantity momentum )\n{\n  return profile.evaluate( boost::units::fabs( momentum ) );\n}\n\n// Evaluate a half Compton profile using the max momentum as a limit\n/*! \\details The half Compton profile will only be evaluated between\n * [-max_momentum,max_momentum]. If max_momentum is < 0.0, a value of \n * 0.0 will be returned.\n */\ninline ComptonProfile::ProfileQuantity\nHalfComptonProfilePolicy::evaluateWithPossibleLimit(\n                          const ComptonProfile& profile,\n                          const ComptonProfile::MomentumQuantity momentum,\n                          const ComptonProfile::MomentumQuantity max_momentum )\n{\n  if( max_momentum >= 0.0*ComptonProfile::MomentumUnit() )\n  {\n    if( momentum <= max_momentum && momentum >= -max_momentum )\n      return profile.evaluate( boost::units::fabs( momentum ) );\n    else\n      return 0.0*ComptonProfile::ProfileUnit();\n  }\n  else\n    return 0.0*ComptonProfile::ProfileUnit();\n}\n\n// Evaluate a double half Compton profile\n/*! \\details The doubled half Compton profile has been doubled so that it\n * remains normalized. The evaluated profile value will be divided by two to\n * account for the doubling. The absolute value of the momentum will be used\n * to evaluate the profile.\n */\ninline ComptonProfile::ProfileQuantity\nDoubledHalfComptonProfilePolicy::evaluate(\n                              const ComptonProfile& profile,\n                              const ComptonProfile::MomentumQuantity momentum )\n{\n  return profile.evaluate( boost::units::fabs( momentum ) )/2.0;\n}\n\n// Evaluate a doubled half Compton profile using the max momentum as a limit\n/*! \\details The half Compton profile will only be evaluated between\n * [-max_momentum,max_momentum]. If max_momentum is < 0.0, a value of \n * 0.0 will be returned.\n */\ninline ComptonProfile::ProfileQuantity\nDoubledHalfComptonProfilePolicy::evaluateWithPossibleLimit(\n                          const ComptonProfile& profile,\n                          const ComptonProfile::MomentumQuantity momentum,\n                          const ComptonProfile::MomentumQuantity max_momentum )\n{\n  if( max_momentum >= 0.0*ComptonProfile::MomentumUnit() )\n  {\n    if( momentum <= max_momentum && momentum >= -max_momentum )\n      return profile.evaluate( boost::units::fabs( momentum ) )/2.0;\n    else\n      return 0.0*ComptonProfile::ProfileUnit();\n  }\n  else\n    return 0.0*ComptonProfile::ProfileUnit();\n}\n\n} // end MonteCarlo namespace\n\n#endif // end MONTE_CARLO_COMPTON_PROFILE_POLICY_DEF_HPP\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_ComptonProfilePolicy_def.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "335a866b55c3a491cc9f44076b35dfd002465bd1", "size": 10580, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/collision/photon/src/MonteCarlo_ComptonProfilePolicy_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/monte_carlo/collision/photon/src/MonteCarlo_ComptonProfilePolicy_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/monte_carlo/collision/photon/src/MonteCarlo_ComptonProfilePolicy_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": 37.2535211268, "max_line_length": 81, "alphanum_fraction": 0.6774102079, "num_tokens": 2302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2598774697734579}}
{"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#ifndef MTL_MAT_MAT_TIMES_EXPR_INCLUDE\n#define MTL_MAT_MAT_TIMES_EXPR_INCLUDE\n\n#include <boost/mpl/if.hpp>\n#include <boost/mpl/and.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/type_traits/is_base_of.hpp>\n\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/matrix/mat_mat_op_expr.hpp>\n#include <boost/numeric/mtl/operation/sfunctor.hpp>\n#include <boost/numeric/mtl/operation/compute_factors.hpp>\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/mtl/matrix/parameter.hpp>\n#include <boost/numeric/mtl/matrix/dense2D.hpp>\n#include <boost/numeric/mtl/matrix/compressed2D.hpp>\n#include <boost/numeric/mtl/concept/std_concept.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/utility/category.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n\n\nnamespace mtl { namespace mat {\n\ntemplate <typename E1, typename E2>\nstruct mat_mat_times_expr \n  : public mat_mat_op_expr< E1, E2, mtl::sfunctor::times<typename Collection<E1>::value_type, typename Collection<E2>::value_type> >,\n    public mat_expr< mat_mat_times_expr<E1, E2> >\n{\n    typedef mat_mat_op_expr< E1, E2, mtl::sfunctor::times<typename Collection<E1>::value_type, typename Collection<E2>::value_type> > op_base;\n    typedef mat_expr< mat_mat_times_expr<E1, E2> >                                                       crtp_base;\n    typedef mat_mat_times_expr                   self;\n    typedef E1                                   first_argument_type ;\n    typedef E2                                   second_argument_type ;\n    typedef typename E1::orientation             orientation;\n    typedef mtl::non_fixed::dimensions           dim_type;\n    typedef typename E1::key_type                key_type;\n\n\n    typedef typename Collection<E1>::value_type  first_value_type;\n    typedef typename Collection<E2>::value_type  second_value_type;\n    typedef typename Multiplicable<first_value_type, second_value_type>::result_type result_value_type;\n    \n#if 0 // Just an idea\n    typedef typename boost::mpl::if_<\n                boost::mpl::and_<\n\t            boost::is_base_of<tag::sparse, typename traits::category<E1>::type>\n\t          , boost::is_base_of<tag::sparse, typename traits::category<E2>::type>\n\t\t> \n\t      , compressed2D<result_value_type>\n\t      , dense2D<result_value_type, parameters<> >\n            >::type                                       evaluated_result_type;\n    \n    // Convert into matrix\n\n    operator evaluated_result_type() const\n    {\n\treturn evaluated_result_type(first * second);\n    }\n#endif\n\n    mat_mat_times_expr( E1 const& v1, E2 const& v2 )\n      : op_base( v1, v2 ), crtp_base(*this), first(v1), second(v2)\n    {}\n\n    // To prevent that cout << A * B prints the element-wise product, suggestion by Hui Li\n    // It is rather inefficient, esp. for multiple products (complexity increases with the number of arguments :-!)\n    //    or sparse matrices. \n    // Better compute your product first and print it then when compute time is an issue,\n    // this is ONLY for convenience.\n    result_value_type\n    operator()(std::size_t r, std::size_t c) const\n    {\n\tusing math::zero;\n\tMTL_THROW_IF(num_cols(first) != num_rows(second), incompatible_size());\n\n\tresult_value_type ref, sum(zero(ref));\n\tfor (std::size_t i= 0; i < num_cols(first); i++)\n\t    sum+= first(r, i) * second(i, c);\n\treturn sum;\n    }\n\n    \n    result_value_type\n    operator()(std::size_t r, std::size_t c)\n    {\n\treturn (*const_cast<const self*>(this))(r, c);\n    }\n\n    first_argument_type const&  first ;\n    second_argument_type const& second ;\n};\n\ntemplate <typename E1, typename E2>\nstd::size_t inline num_rows(const mat_mat_times_expr<E1, E2>& expr) \n{ return num_rows(expr.first); }\n\ntemplate <typename E1, typename E2>\nstd::size_t inline num_cols(const mat_mat_times_expr<E1, E2>& expr) \n{ return num_cols(expr.second); }\n\ntemplate <typename E1, typename E2>\nstd::size_t inline size(const mat_mat_times_expr<E1, E2>& expr) \n{ return num_rows(expr) * num_cols(expr); }\n\n}} // Namespace mtl::matrix\n\n#endif // MTL_MAT_MAT_TIMES_EXPR_INCLUDE\n", "meta": {"hexsha": "98f8d73f5f71277d617c468bee1e2eaefcadf1c2", "size": 4540, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/matrix/mat_mat_times_expr.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": "boost/numeric/mtl/matrix/mat_mat_times_expr.hpp", "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": "boost/numeric/mtl/matrix/mat_mat_times_expr.hpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 37.520661157, "max_line_length": 142, "alphanum_fraction": 0.6872246696, "num_tokens": 1128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.25985576301744695}}
{"text": "// Copyright (C) 2015 Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n#include <dlib/python.h>\n#include <dlib/geometry.h>\n#include <pybind11/stl_bind.h>\n#include \"indexing.h\"\n#include \"opaque_types.h\"\n#include <dlib/filtering.h>\n\nusing namespace dlib;\nusing namespace std;\n\nnamespace py = pybind11;\n\n\n// ----------------------------------------------------------------------------------------\n\nlong left(const rectangle& r) { return r.left(); }\nlong top(const rectangle& r) { return r.top(); }\nlong right(const rectangle& r) { return r.right(); }\nlong bottom(const rectangle& r) { return r.bottom(); }\nlong width(const rectangle& r) { return r.width(); }\nlong height(const rectangle& r) { return r.height(); }\nunsigned long area(const rectangle& r) { return r.area(); }\n\ndouble dleft(const drectangle& r) { return r.left(); }\ndouble dtop(const drectangle& r) { return r.top(); }\ndouble dright(const drectangle& r) { return r.right(); }\ndouble dbottom(const drectangle& r) { return r.bottom(); }\ndouble dwidth(const drectangle& r) { return r.width(); }\ndouble dheight(const drectangle& r) { return r.height(); }\ndouble darea(const drectangle& r) { return r.area(); }\n\ntemplate <typename rect_type>\nbool is_empty(const rect_type& r) { return r.is_empty(); }\n\ntemplate <typename rect_type>\npoint center(const rect_type& r) { return center(r); }\n\ntemplate <typename rect_type>\npoint dcenter(const rect_type& r) { return dcenter(r); }\n\ntemplate <typename rect_type, typename ptype>\nbool contains(const rect_type& r, const ptype& p) { return r.contains(p); }\n\ntemplate <typename rect_type>\nbool contains_xy(const rect_type& r, const long x, const long y) { return r.contains(point(x, y)); }\n\ntemplate <typename rect_type>\nbool contains_rec(const rect_type& r, const rect_type& r2) { return r.contains(r2); }\n\ntemplate <typename rect_type>\nrect_type intersect(const rect_type& r, const rect_type& r2) { return r.intersect(r2); }\n\ntemplate <typename rect_type>\nstring print_rectangle_str(const rect_type& r)\n{\n    std::ostringstream sout;\n    sout << r;\n    return sout.str();\n}\n\nstring print_rectangle_repr(const rectangle& r)\n{\n    std::ostringstream sout;\n    sout << \"rectangle(\" << r.left() << \",\" << r.top() << \",\" << r.right() << \",\" << r.bottom() << \")\";\n    return sout.str();\n}\n\nstring print_drectangle_repr(const drectangle& r)\n{\n    std::ostringstream sout;\n    sout << \"drectangle(\" << r.left() << \",\" << r.top() << \",\" << r.right() << \",\" << r.bottom() << \")\";\n    return sout.str();\n}\n\nstring print_rect_filter(const rect_filter& r)\n{\n    std::ostringstream sout;\n    sout << \"rect_filter(\";\n    sout << \"measurement_noise=\"<<r.get_left().get_measurement_noise();\n    sout << \", typical_acceleration=\"<<r.get_left().get_typical_acceleration();\n    sout << \", max_measurement_deviation=\"<<r.get_left().get_max_measurement_deviation();\n    sout << \")\";\n    return sout.str();\n}\n\n\n\n// ----------------------------------------------------------------------------------------\n\nvoid bind_rectangles(py::module& m)\n{\n    {\n    typedef rectangle type;\n    py::class_<type>(m, \"rectangle\", \"This object represents a rectangular area of an image.\")\n        .def(py::init<long,long,long,long>(), py::arg(\"left\"),py::arg(\"top\"),py::arg(\"right\"),py::arg(\"bottom\"))\n        .def(py::init<drectangle>(), py::arg(\"rect\"))\n        .def(py::init<rectangle>(), py::arg(\"rect\"))\n        .def(py::init())\n        .def(\"area\",   &::area)\n        .def(\"left\",   &::left)\n        .def(\"top\",    &::top)\n        .def(\"right\",  &::right)\n        .def(\"bottom\", &::bottom)\n        .def(\"width\",  &::width)\n        .def(\"height\", &::height)\n        .def(\"tl_corner\", &type::tl_corner, \"Returns the top left corner of the rectangle.\")\n        .def(\"tr_corner\", &type::tr_corner, \"Returns the top right corner of the rectangle.\")\n        .def(\"bl_corner\", &type::bl_corner, \"Returns the bottom left corner of the rectangle.\")\n        .def(\"br_corner\", &type::br_corner, \"Returns the bottom right corner of the rectangle.\")\n        .def(\"is_empty\", &::is_empty<type>)\n        .def(\"center\", &::center<type>)\n        .def(\"dcenter\", &::dcenter<type>)\n        .def(\"contains\", &::contains<type,point>, py::arg(\"point\"))\n        .def(\"contains\", &::contains<type,dpoint>, py::arg(\"point\"))\n        .def(\"contains\", &::contains_xy<type>, py::arg(\"x\"), py::arg(\"y\"))\n        .def(\"contains\", &::contains_rec<type>, py::arg(\"rectangle\"))\n        .def(\"intersect\", &::intersect<type>, py::arg(\"rectangle\"))\n        .def(\"__str__\", &::print_rectangle_str<type>)\n        .def(\"__repr__\", &::print_rectangle_repr)\n        .def(py::self += point())\n        .def(py::self + point())\n        .def(py::self += rectangle())\n        .def(py::self + rectangle())\n        .def(py::self == py::self)\n        .def(py::self != py::self)\n        .def(py::pickle(&getstate<type>, &setstate<type>));\n    }\n    {\n    typedef drectangle type;\n    py::class_<type>(m, \"drectangle\", \"This object represents a rectangular area of an image with floating point coordinates.\")\n        .def(py::init<double,double,double,double>(), py::arg(\"left\"), py::arg(\"top\"), py::arg(\"right\"), py::arg(\"bottom\"))\n        .def(py::init<rectangle>(), py::arg(\"rect\"))\n        .def(py::init<drectangle>(), py::arg(\"rect\"))\n        .def(py::init<>())\n        .def(\"area\",   &::darea)\n        .def(\"left\",   &::dleft)\n        .def(\"top\",    &::dtop)\n        .def(\"right\",  &::dright)\n        .def(\"bottom\", &::dbottom)\n        .def(\"width\",  &::dwidth)\n        .def(\"height\", &::dheight)\n        .def(\"is_empty\", &::is_empty<type>)\n        .def(\"center\", &::center<type>)\n        .def(\"dcenter\", &::dcenter<type>)\n        .def(\"tl_corner\", &type::tl_corner, \"Returns the top left corner of the rectangle.\")\n        .def(\"tr_corner\", &type::tr_corner, \"Returns the top right corner of the rectangle.\")\n        .def(\"bl_corner\", &type::bl_corner, \"Returns the bottom left corner of the rectangle.\")\n        .def(\"br_corner\", &type::br_corner, \"Returns the bottom right corner of the rectangle.\")\n        .def(\"contains\", &::contains<type,point>, py::arg(\"point\"))\n        .def(\"contains\", &::contains<type,dpoint>, py::arg(\"point\"))\n        .def(\"contains\", &::contains_xy<type>, py::arg(\"x\"), py::arg(\"y\"))\n        .def(\"contains\", &::contains_rec<type>, py::arg(\"rectangle\"))\n        .def(\"intersect\", &::intersect<type>, py::arg(\"rectangle\"))\n        .def(\"__str__\", &::print_rectangle_str<type>)\n        .def(\"__repr__\", &::print_drectangle_repr)\n        .def(py::self == py::self)\n        .def(py::self != py::self)\n        .def(py::pickle(&getstate<type>, &setstate<type>));\n    }\n\n    {\n        typedef rect_filter type;\n        py::class_<type>(m, \"rect_filter\",\n            R\"asdf( \n                This object is a simple tool for filtering a rectangle that\n                measures the location of a moving object that has some non-trivial\n                momentum.  Importantly, the measurements are noisy and the object can\n                experience sudden unpredictable accelerations.  To accomplish this\n                filtering we use a simple Kalman filter with a state transition model of:\n\n                    position_{i+1} = position_{i} + velocity_{i} \n                    velocity_{i+1} = velocity_{i} + some_unpredictable_acceleration\n\n                and a measurement model of:\n                    \n                    measured_position_{i} = position_{i} + measurement_noise\n\n                Where some_unpredictable_acceleration and measurement_noise are 0 mean Gaussian \n                noise sources with standard deviations of typical_acceleration and\n                measurement_noise respectively.\n\n                To allow for really sudden and large but infrequent accelerations, at each\n                step we check if the current measured position deviates from the predicted\n                filtered position by more than max_measurement_deviation*measurement_noise \n                and if so we adjust the filter's state to keep it within these bounds.\n                This allows the moving object to undergo large unmodeled accelerations, far\n                in excess of what would be suggested by typical_acceleration, without\n                then experiencing a long lag time where the Kalman filter has to \"catches\n                up\" to the new position.  )asdf\"\n        )\n        .def(py::init<double,double,double>(), py::arg(\"measurement_noise\"), py::arg(\"typical_acceleration\"), py::arg(\"max_measurement_deviation\"))\n        .def(\"measurement_noise\",   [](const rect_filter& a){return a.get_left().get_measurement_noise();})\n        .def(\"typical_acceleration\",   [](const rect_filter& a){return a.get_left().get_typical_acceleration();})\n        .def(\"max_measurement_deviation\",   [](const rect_filter& a){return a.get_left().get_max_measurement_deviation();})\n        .def(\"__call__\", [](rect_filter& f, const dlib::rectangle& r){return rectangle(f(r)); }, py::arg(\"rect\"))\n        .def(\"__repr__\", print_rect_filter)\n        .def(py::pickle(&getstate<type>, &setstate<type>));\n    }\n\n    m.def(\"find_optimal_rect_filter\",\n        [](const std::vector<rectangle>& rects, const double smoothness ) { return find_optimal_rect_filter(rects, smoothness); },\n        py::arg(\"rects\"),\n        py::arg(\"smoothness\")=1,\n\"requires \\n\\\n    - rects.size() > 4 \\n\\\n    - smoothness >= 0 \\n\\\nensures \\n\\\n    - This function finds the \\\"optimal\\\" settings of a rect_filter based on recorded \\n\\\n      measurement data stored in rects.  Here we assume that rects is a complete \\n\\\n      track history of some object's measured positions.  Essentially, what we do \\n\\\n      is find the rect_filter that minimizes the following objective function: \\n\\\n         sum of abs(predicted_location[i] - measured_location[i]) + smoothness*abs(filtered_location[i]-filtered_location[i-1]) \\n\\\n         Where i is a time index. \\n\\\n      The sum runs over all the data in rects.  So what we do is find the \\n\\\n      filter settings that produce smooth filtered trajectories but also produce \\n\\\n      filtered outputs that are as close to the measured positions as possible. \\n\\\n      The larger the value of smoothness the less jittery the filter outputs will \\n\\\n      be, but they might become biased or laggy if smoothness is set really high. \" \n    /*!\n        requires\n            - rects.size() > 4\n            - smoothness >= 0\n        ensures\n            - This function finds the \"optimal\" settings of a rect_filter based on recorded\n              measurement data stored in rects.  Here we assume that rects is a complete\n              track history of some object's measured positions.  Essentially, what we do\n              is find the rect_filter that minimizes the following objective function:\n                 sum of abs(predicted_location[i] - measured_location[i]) + smoothness*abs(filtered_location[i]-filtered_location[i-1])\n                 Where i is a time index.\n              The sum runs over all the data in rects.  So what we do is find the\n              filter settings that produce smooth filtered trajectories but also produce\n              filtered outputs that are as close to the measured positions as possible.\n              The larger the value of smoothness the less jittery the filter outputs will\n              be, but they might become biased or laggy if smoothness is set really high. \n    !*/\n    );\n\n    {\n    typedef std::vector<rectangle> type;\n    py::bind_vector<type>(m, \"rectangles\", \"An array of rectangle objects.\")\n        .def(py::init<size_t>(), py::arg(\"initial_size\"))\n        .def(\"clear\", &type::clear)\n        .def(\"resize\", resize<type>)\n        .def(\"extend\", extend_vector_with_python_list<rectangle>)\n        .def(py::pickle(&getstate<type>, &setstate<type>));\n    }\n\n    {\n    typedef std::vector<std::vector<rectangle>> type;\n    py::bind_vector<type>(m, \"rectangless\", \"An array of arrays of rectangle objects.\")\n        .def(py::init<size_t>(), py::arg(\"initial_size\"))\n        .def(\"clear\", &type::clear)\n        .def(\"resize\", resize<type>)\n        .def(\"extend\", extend_vector_with_python_list<rectangle>)\n        .def(py::pickle(&getstate<type>, &setstate<type>));\n    }\n\n    m.def(\"translate_rect\", [](const rectangle& rect, const point& p){return translate_rect(rect,p);},\n\" returns rectangle(rect.left()+p.x, rect.top()+p.y, rect.right()+p.x, rect.bottom()+p.y) \\n\\\n  (i.e. moves the location of the rectangle but doesn't change its shape)\",\n        py::arg(\"rect\"), py::arg(\"p\"));\n\n    m.def(\"translate_rect\", [](const drectangle& rect, const point& p){return translate_rect(rect,p);},\n\" returns rectangle(rect.left()+p.x, rect.top()+p.y, rect.right()+p.x, rect.bottom()+p.y) \\n\\\n  (i.e. moves the location of the rectangle but doesn't change its shape)\",\n        py::arg(\"rect\"), py::arg(\"p\"));\n\n    m.def(\"translate_rect\", [](const rectangle& rect, const dpoint& p){return translate_rect(rect,point(p));},\n\" returns rectangle(rect.left()+p.x, rect.top()+p.y, rect.right()+p.x, rect.bottom()+p.y) \\n\\\n  (i.e. moves the location of the rectangle but doesn't change its shape)\",\n        py::arg(\"rect\"), py::arg(\"p\"));\n\n    m.def(\"translate_rect\", [](const drectangle& rect, const dpoint& p){return translate_rect(rect,p);},\n\" returns rectangle(rect.left()+p.x, rect.top()+p.y, rect.right()+p.x, rect.bottom()+p.y) \\n\\\n  (i.e. moves the location of the rectangle but doesn't change its shape)\",\n        py::arg(\"rect\"), py::arg(\"p\"));\n\n\n\n    m.def(\"shrink_rect\", [](const rectangle& rect, long num){return shrink_rect(rect,num);},\n\" returns rectangle(rect.left()+num, rect.top()+num, rect.right()-num, rect.bottom()-num) \\n\\\n  (i.e. shrinks the given rectangle by shrinking its border by num)\",\n        py::arg(\"rect\"), py::arg(\"num\"));\n\n    m.def(\"grow_rect\", [](const rectangle& rect, long num){return grow_rect(rect,num);},\n\"- return shrink_rect(rect, -num) \\n\\\n  (i.e. grows the given rectangle by expanding its border by num)\",\n        py::arg(\"rect\"), py::arg(\"num\"));\n\n    m.def(\"scale_rect\", [](const rectangle& rect, double scale){return scale_rect(rect,scale);},\n\"- return scale_rect(rect, scale) \\n\\\n(i.e. resizes the given rectangle by a scale factor)\",\n        py::arg(\"rect\"), py::arg(\"scale\"));\n\n    m.def(\"centered_rect\", [](const point& p, unsigned long width, unsigned long height) {\n        return centered_rect(p, width, height); },\n        py::arg(\"p\"), py::arg(\"width\"), py::arg(\"height\"));\n\n    m.def(\"centered_rects\", [](const std::vector<point>& p, unsigned long width, unsigned long height) {\n        return centered_rects(p, width, height); },\n        py::arg(\"pts\"), py::arg(\"width\"), py::arg(\"height\"));\n\n    m.def(\"centered_rect\", [](const dpoint& p, unsigned long width, unsigned long height) {\n        return centered_rect(p, width, height); },\n        py::arg(\"p\"), py::arg(\"width\"), py::arg(\"height\"));\n\n    m.def(\"centered_rect\", [](const rectangle& rect, unsigned long width, unsigned long height) {\n        return centered_rect(rect, width, height); },\n        py::arg(\"rect\"), py::arg(\"width\"), py::arg(\"height\"));\n\n    m.def(\"centered_rect\", [](const drectangle& rect, unsigned long width, unsigned long height) {\n        return centered_rect(rect, width, height); },\n        py::arg(\"rect\"), py::arg(\"width\"), py::arg(\"height\"));\n\n\n    m.def(\"center\", [](const rectangle& rect){return center(rect); }, py::arg(\"rect\"),\n        \"    returns the center of the given rectangle\");\n    m.def(\"center\", [](const drectangle& rect){return center(rect); }, py::arg(\"rect\"),\n        \"    returns the center of the given rectangle\");\n}\n\n// ----------------------------------------------------------------------------------------\n", "meta": {"hexsha": "ed2f54f3ea2d2f92e7d71510304325b8b481bd5c", "size": 15747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/tools/python/src/rectangles.cpp", "max_stars_repo_name": "asm-jaime/facerec", "max_stars_repo_head_hexsha": "e5e101b9f478168ead179e6b08b5605ea7607da2", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 11719.0, "max_stars_repo_stars_event_min_datetime": "2015-01-03T22:38:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:45:04.000Z", "max_issues_repo_path": "tools/python/src/rectangles.cpp", "max_issues_repo_name": "KiLJ4EdeN/dlib", "max_issues_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2518.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T04:38:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:55:43.000Z", "max_forks_repo_path": "tools/python/src/rectangles.cpp", "max_forks_repo_name": "KiLJ4EdeN/dlib", "max_forks_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3308.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T14:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:20:07.000Z", "avg_line_length": 48.3036809816, "max_line_length": 147, "alphanum_fraction": 0.617450943, "num_tokens": 3883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.25982405718051205}}
{"text": "#pragma once\n\n#include <boost/dynamic_bitset.hpp>\n#include <regex>\n#include <vector>\n\n#include \"state.hpp\"\n#include \"type.hpp\"\n\nenum {\n    PAULI_ID_I = 0,\n    PAULI_ID_X = 1,\n    PAULI_ID_Y = 2,\n    PAULI_ID_Z = 3,\n};\n\nclass DllExport MultiQubitPauliOperator {\nprivate:\n    std::vector<UINT> _target_index;\n    std::vector<UINT> _pauli_id;\n    boost::dynamic_bitset<> _x;\n    boost::dynamic_bitset<> _z;\n\n    void set_bit(const UINT pauli_id, const UINT target_index);\n\npublic:\n    MultiQubitPauliOperator(){};\n\n    MultiQubitPauliOperator(const std::vector<UINT>& target_qubit_index_list,\n        const std::vector<UINT>& pauli_id_list)\n        : _target_index(target_qubit_index_list), _pauli_id(pauli_id_list) {\n        for (ITYPE i = 0; i < pauli_id_list.size(); i++) {\n            set_bit(pauli_id_list[i], target_qubit_index_list[i]);\n        }\n    };\n\n    explicit MultiQubitPauliOperator(std::string pauli_string) {\n        std::string pattern = \"([IXYZ])\\\\s*([0-9]+)\\\\s*\";\n        std::regex re(pattern);\n        std::cmatch result;\n        while (std::regex_search(pauli_string.c_str(), result, re)) {\n            std::string pauli = result[1].str();\n            UINT index = (UINT)std::stoul(result[2].str());\n            _target_index.push_back(index);\n            UINT pauli_id;\n            if (pauli == \"I\")\n                pauli_id = PAULI_ID_I;\n            else if (pauli == \"X\")\n                pauli_id = PAULI_ID_X;\n            else if (pauli == \"Y\")\n                pauli_id = PAULI_ID_Y;\n            else if (pauli == \"Z\")\n                pauli_id = PAULI_ID_Z;\n            else\n                assert(false && \"Error in regex\");\n            _pauli_id.push_back(pauli_id);\n            set_bit(pauli_id, index);\n            pauli_string = result.suffix();\n        }\n        assert(_target_index.size() == _pauli_id.size());\n    }\n\n    MultiQubitPauliOperator(\n        const boost::dynamic_bitset<>& x, const boost::dynamic_bitset<>& z)\n        : _x(x), _z(z) {\n        ITYPE index;\n        _z.resize(_x.size());\n        for (index = 0; index < this->_x.size(); index++) {\n            UINT pauli_id;\n            if (!this->_x[index] && !this->_z[index])\n                pauli_id = PAULI_ID_I;\n            else if (!this->_x[index] && this->_z[index])\n                pauli_id = PAULI_ID_Z;\n            else if (this->_x[index] && !this->_z[index])\n                pauli_id = PAULI_ID_X;\n            else if (this->_x[index] && this->_z[index])\n                pauli_id = PAULI_ID_Y;\n            if (pauli_id != PAULI_ID_I) {\n                _target_index.push_back(index);\n                _pauli_id.push_back(pauli_id);\n            }\n        }\n    };\n\n    ~MultiQubitPauliOperator(){};\n\n    const std::vector<UINT>& get_pauli_id_list() const;\n    const std::vector<UINT>& get_index_list() const;\n    const boost::dynamic_bitset<>& get_x_bits() const { return this->_x; }\n    const boost::dynamic_bitset<>& get_z_bits() const { return this->_z; }\n\n    void add_single_Pauli(UINT qubit_index, UINT pauli_type);\n\n    CPPCTYPE get_expectation_value(const QuantumStateBase* state) const;\n\n    CPPCTYPE get_transition_amplitude(const QuantumStateBase* state_bra,\n        const QuantumStateBase* state_ket) const;\n\n    MultiQubitPauliOperator* copy() const;\n\n    bool operator==(const MultiQubitPauliOperator& target) const;\n\n    MultiQubitPauliOperator operator*(\n        const MultiQubitPauliOperator& target) const;\n\n    MultiQubitPauliOperator& operator*=(const MultiQubitPauliOperator& target);\n\n    std::string to_string() const;\n};\n\nusing PauliOperator = MultiQubitPauliOperator;\n", "meta": {"hexsha": "397fbfe9ed4ab2da079633aef2dbc4191f21dfbe", "size": 3599, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cppsim_experimental/pauli_operator.hpp", "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_experimental/pauli_operator.hpp", "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_experimental/pauli_operator.hpp", "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": 32.1339285714, "max_line_length": 79, "alphanum_fraction": 0.6010002779, "num_tokens": 983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.25982405718051205}}
{"text": "/*\n==============================================================================\nKratos\nA General Purpose Software for Multi-Physics Finite Element Analysis\nVersion 1.0 (Released on march 05, 2007).\n\nCopyright 2007\nPooyan Dadvand, Riccardo Rossi\npooyan@cimne.upc.edu\nrrossi@cimne.upc.edu\nCIMNE (International Center for Numerical Methods in Engineering),\nGran Capita' s/n, 08034 Barcelona, Spain\n\nPermission is hereby granted, free  of charge, to any person obtaining\na  copy  of this  software  and  associated  documentation files  (the\n\"Software\"), to  deal in  the Software without  restriction, including\nwithout limitation  the rights to  use, copy, modify,  merge, publish,\ndistribute,  sublicense and/or  sell copies  of the  Software,  and to\npermit persons to whom the Software  is furnished to do so, subject to\nthe following condition:\n\nDistribution of this code for  any  commercial purpose  is permissible\nONLY BY DIRECT ARRANGEMENT WITH THE COPYRIGHT OWNER.\n\nThe  above  copyright  notice  and  this permission  notice  shall  be\nincluded in all copies or substantial portions of the Software.\n\nTHE  SOFTWARE IS  PROVIDED  \"AS  IS\", WITHOUT  WARRANTY  OF ANY  KIND,\nEXPRESS OR  IMPLIED, INCLUDING  BUT NOT LIMITED  TO THE  WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT  SHALL THE AUTHORS OR COPYRIGHT HOLDERS  BE LIABLE FOR ANY\nCLAIM, DAMAGES OR  OTHER LIABILITY, WHETHER IN AN  ACTION OF CONTRACT,\nTORT  OR OTHERWISE, ARISING  FROM, OUT  OF OR  IN CONNECTION  WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n==============================================================================\n*/\n \n//   \n//   Project Name:        Kratos       \n//   Last modified by:    $Author: janosch $\n//   Date:                $Date: 2007-12-13 14:50:05 $\n//   Revision:            $Revision: 1.4 $\n//\n//\n\n\n// System includes \n#include <cstddef>\n\n// External includes \n#include <boost/python.hpp>\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n\n\n// Project includes\n#include \"includes/define.h\"\n#include \"integration/quadrature.h\" // to bo changed to the new version below.\n#include \"integration/gauss_legendre_integration_points.h\"\n//#include \"quadratures/gauss_legendre_integration_points.h\"\n//#include \"quadratures/quadrature.h\"\n#include \"python/container_from_python.h\"\n\nnamespace Kratos\n{\n\n\ttemplate<std::size_t TDimension>\n  std::stringstream& operator << (std::stringstream& rOStream,\n\t\t\t\t  std::vector<IntegrationPoint<TDimension> > const & rThis)\n    { \n \ttypename std::vector<IntegrationPoint<TDimension> >::size_type i;\n \tfor(i = 0 ; i < rThis.size() - 1 ; i++)\n\t  rOStream << rThis[i] << \" , \" << std::endl;\n \trOStream << rThis[i];\n      return rOStream;\n    }\n\nnamespace Python\n{\n\n  using namespace boost::python;\n\n  template<class TArrayType>\n  void AddIntegrationPointsArray(std::string const& rArrayName, TArrayType const & Dummy)\n  {\n    ContainerFromPython< TArrayType >();\n\n     class_<TArrayType>(rArrayName.c_str(), init<int>())\n\t.def(init<const TArrayType&>())\n\t.def(vector_indexing_suite<TArrayType>())\n \t.def(self_ns::str(self))\n\t;\n\n  }\n\n  void  AddQuadraturesToPython()\n  {\n    AddIntegrationPointsArray(\"IntegrationPointsArray\", Kratos::Quadrature<Kratos::GaussLegendreIntegrationPoints1,1,Kratos::IntegrationPoint<3> >::IntegrationPointsArrayType());\n    //AddIntegrationPointsArray(\"IntegrationPoint2DsArray\", Kratos::Quadrature<Kratos::GaussLegendreIntegrationPoints<1>,2,Kratos::IntegrationPoint<3> >::IntegrationPointsArrayType());\n    //AddIntegrationPointsArray(\"IntegrationPoint3DsArray\", Kratos::Quadrature<Kratos::GaussLegendreIntegrationPoints<1>,3,Kratos::IntegrationPoint<3> >::IntegrationPointsArrayType());\n    //AddIntegrationPointsArray(\"IntegrationPoint4DsArray\", Kratos::Quadrature<Kratos::GaussLegendreIntegrationPoints<1>,4,Kratos::IntegrationPoint<3> >::IntegrationPointsArrayType());\n\n    scope().attr(\"GaussLegendreQuadrature1D1\") = Kratos::Quadrature<Kratos::GaussLegendreIntegrationPoints1,1,Kratos::IntegrationPoint<3> >::IntegrationPoints();\n    scope().attr(\"GaussLegendreQuadrature1D2\") = Kratos::Quadrature<Kratos::GaussLegendreIntegrationPoints2,1,Kratos::IntegrationPoint<3> >::IntegrationPoints();\n    scope().attr(\"GaussLegendreQuadrature1D3\") = Kratos::Quadrature<Kratos::GaussLegendreIntegrationPoints3,1,Kratos::IntegrationPoint<3> >::IntegrationPoints();\n    scope().attr(\"GaussLegendreQuadrature2D1\") = Kratos::Quadrature<Kratos::GaussLegendreIntegrationPoints1,2,Kratos::IntegrationPoint<3> >::IntegrationPoints();\n    scope().attr(\"GaussLegendreQuadrature2D2\") = Kratos::Quadrature<Kratos::GaussLegendreIntegrationPoints2,2,Kratos::IntegrationPoint<3> >::IntegrationPoints();\n    scope().attr(\"GaussLegendreQuadrature2D3\") = Kratos::Quadrature<Kratos::GaussLegendreIntegrationPoints3,2,Kratos::IntegrationPoint<3> >::IntegrationPoints();\n    scope().attr(\"GaussLegendreQuadrature3D1\") = Kratos::Quadrature<Kratos::GaussLegendreIntegrationPoints1,3,Kratos::IntegrationPoint<3> >::IntegrationPoints();\n    scope().attr(\"GaussLegendreQuadrature3D2\") = Kratos::Quadrature<Kratos::GaussLegendreIntegrationPoints2,3,Kratos::IntegrationPoint<3> >::IntegrationPoints();\n    scope().attr(\"GaussLegendreQuadrature3D3\") = Kratos::Quadrature<Kratos::GaussLegendreIntegrationPoints3,3,Kratos::IntegrationPoint<3> >::IntegrationPoints();\n  }\n\t\n}  // namespace Python.\n\n} // Namespace Kratos\n\n", "meta": {"hexsha": "b1b19252c58f85ef26a697333b10208facf55500", "size": 5431, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kratos/python/add_quadratures_to_python.cpp", "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": "kratos/python/add_quadratures_to_python.cpp", "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": "kratos/python/add_quadratures_to_python.cpp", "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": 46.0254237288, "max_line_length": 184, "alphanum_fraction": 0.7368808691, "num_tokens": 1411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.259824057180512}}
{"text": "/*!\n*\t@file\tpsalm.cpp\n*\t@brief\tMain file for \"psalm\"\n*\n*\t\"psalm\" (Pretty Subdivision ALgorithms on Meshes) is a CLI tool that\n*\timplements the Doo-Sabin and Catmull-Clark subdivision schemes.\n*/\n\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <algorithm>\n#include <set>\n\n#include <boost/program_options.hpp>\n\n#include <cerrno>\n#include <cstring>\n\n#include <unistd.h>\n#include <getopt.h>\n#include <libgen.h>\n\n#include \"SubdivisionAlgorithms/CatmullClark.h\"\n#include \"SubdivisionAlgorithms/DooSabin.h\"\n#include \"SubdivisionAlgorithms/Loop.h\"\n#include \"SubdivisionAlgorithms/Liepa.h\"\n\n#include \"FairingAlgorithms/FairingAlgorithm.h\"\n\n// FIXME: This should be conditional\n#if 0\n  #include \"FairingAlgorithms/CurvatureFlow.h\"\n#endif\n\n#include \"mesh.h\"\n\npsalm::mesh scene_mesh;\nstd::string input;\nstd::string output;\n\nnamespace po = boost::program_options;\n\n/*!\n*\tReads a map of weights for a sudivision algorithm from a file. Each\n*\tline of the file must be of the following form:\n*\n*\t\t<k> <a_1> ... <a_k>\n*\n*\tWhere <k> is the number of vertices for a face and <a_i> are the\n*\tweights that are used for the vertices of the face. The weights are\n*\tsupposed to be arranged in counterclockwise order.\n*\n*\t@param filename Filename of weights map\n*\t@return Associative array for quickly looking up the weights.\n*/\n\npsalm::weights_map load_weights_map(const std::string& filename)\n{\n\tpsalm::weights_map res;\n\n\tstd::ifstream in;\n\terrno = 0;\n\tin.open(filename.c_str());\n\n\tif(!in.good() || errno)\n\t{\n\t\tstd::string error = strerror(errno);\n\t\tstd::cerr\t<< \"psalm: Could not load weights map file \\\"\"\n\t\t\t\t<< filename << \"\\\": \"\n\t\t\t\t<< error << \"\\n\";\n\n\t\treturn(res);\n\t}\n\n\tstd::string line;\n\tstd::istringstream converter;\n\twhile(getline(in, line))\n\t{\n\t\tconverter.clear();\n\t\tconverter.str(line);\n\n\t\tstd::vector<double> weights;\n\t\tsize_t k = 0;\n\n\t\t// Read k and try to read k weights afterwards\n\n\t\tconverter >> k;\n\t\tif(converter.fail())\n\t\t{\n\t\t\tstd::cerr\t<< \"psalm: Unable to read number of weights \"\n\t\t\t\t\t<< \"from line \\\"\" << line << \"\\\"\\n\";\n\t\t\treturn(res);\n\t\t}\n\n\t\tdouble w = 0.0;\n\t\tfor(size_t i = 0; i < k; i++)\n\t\t{\n\t\t\tconverter >> w;\n\t\t\tif(converter.fail())\n\t\t\t{\n\t\t\t\tstd::cerr\t<< \"psalm: Unable to read weights \"\n\t\t\t\t\t\t<< \"from line \\\"\" << line << \"\\\"\\n\";\n\t\t\t\treturn(res);\n\t\t\t}\n\n\t\t\tweights.push_back(w);\n\t\t}\n\n\t\tres[k] = weights;\n\t}\n\n\treturn(res);\n}\n\n/*!\n*\tParses a string of comma-separated numbers.\n*\n*\t@param\targument Argument string\n*\t@return Set of numbers.\n*/\n\nstd::set<size_t> parse_value_string(std::string argument)\n{\n\tstd::set<size_t> res;\n\n\tstd::istringstream val_stream(argument);\n\tstd::istringstream converter;\n\tstd::string val_str;\n\twhile(getline(val_stream, val_str, ','))\n\t{\n\t\tconverter.clear();\n\t\tconverter.str(val_str);\n\n\t\tsize_t value;\n\t\tconverter >> value;\n\t\tif(converter.fail())\n\t\t{\n\t\t\tstd::cerr << \"psalm: Unable to convert \\\"\" << val_str << \"\\\" to a number.\\n\";\n\t\t\treturn(res);\n\t\t}\n\n\t\tres.insert(value);\n\t}\n\n\treturn(res);\n}\n\n/*!\n*\tHandles user interaction.\n*\n*\t@param argc Number of command-line arguments\n*\t@param argv Vector of command-line arguments\n*/\n\nint main(int argc, char* argv[])\n{\n\tpsalm::mesh::file_type type = psalm::mesh::TYPE_EXT;\n\n\tstd::set<size_t> remove_faces;\n\tstd::set<size_t> remove_vertices;\n\tpsalm::weights_map extra_weights;\n\n\tsize_t steps\t= 0;\n\n\tpsalm::SubdivisionAlgorithm* subdivision_algorithm\t= NULL;\n\tpsalm::FairingAlgorithm* fairing_algorithm\t\t= NULL;\n\n\t// Add general program options\n\n\tpo::options_description general(\"General\", 80);\n\tgeneral.add_options()\n\t\t(\t\"algorithm,a\",\n\t\t\tpo::value<std::string>(),\n\t\t\t\"Selects subdivision algorithm to use on the input mesh. Valid values:\\n\"\\\n\t\t\t\"* catmull-clark, catmull, clark, cc [default]\\n\"\\\n\t\t\t\"* doo-sabin, doo, sabin, ds\\n\"\\\n\t\t\t\"* loop, l\")\n\n\t\t(\t\"type,t\",\n\t\t\tpo::value<std::string>(),\n\t\t\t\"Selects type of input data. Valid values:\\n\"\\\n\t\t\t\"* ply (Stanford PLY files)\\n\"\\\n\t\t\t\"* obj (Wavefront OBJ files)\\n\"\\\n\t\t\t\"* off (Geomview object files)\")\n\n\t\t(\t\"output,o\",\n\t\t\tpo::value<std::string>(&output)->default_value(\"\"),\n\t\t\t\"Sets output file\")\n\n\t\t(\t\"steps,n\",\n\t\t\tpo::value<size_t>(&steps),\n\t\t\t\"Sets number of subdivision steps to perform on the input mesh.\")\n\n\t\t(\t\"statistics,s\",\n\t\t\t\"Prints statistics to STDERR\")\n\n\t\t(\t\"help,h\",\n\t\t\t\"Shows this screen\");\n\n\t// Add tuning program options\n\n\tpo::options_description tuning(\"Algorithm tuning\", 80);\n\ttuning.add_options()\n\t\t(\t\"preserve-boundaries,p\",\n\t\t\t\"Forces subdivision algorithms to preserve the original boundaries of a mesh. \"\\\n\t\t\t\"This is especially useful for open meshes. This flag is not taken into \"\\\n\t\t\t\"account by every subdivision algorithm.\")\n\n\t\t(\t\"handle-creases,c\",\n\t\t\t\"Subdivides crease and boundary edges whenever the algorithm supports this. \"\\\n\t\t\t\"For the Catmull-Clark scheme, for example, midpoints of edges are used for \"\\\n\t\t\t\"the new control points\")\n\n\t\t(\t\"geometric,g\",\n\t\t\t\"Forces algorithms to compute new points using \"\\\n\t\t\t\"geometric methods and forbids the use of parametric (i.e. weight-based) ones.\")\n\n\t\t(\t\"b-spline-weights,b\",\n\t\t\t\"Forces algorithms to use the B-spline weights in regular cases, thereby \"\\\n\t\t\t\"overriding any other weights scheme.\")\n\n\t\t(\t\"extra-weights,e\",\n\t\t\tpo::value<std::string>(),\n\t\t\t\"Overrides default weights of subdivision schemes by reading them from <arg>. \"\\\n\t\t\t\"The exact format of this file depends on the subdivision algorithm that is used.\")\n\n\t\t(\t\"weights,w\",\n\t\t\tpo::value<std::string>(),\n\t\t\t\"Selects type of weights that are used for the subdivision scheme. Algorithms \"\\\n\t\t\t\"may ignore unknown values. Valid values:\\n\"\\\n\t\t\t\"* catmull-clark, catmull, clark, cc\\n\"\\\n\t\t\t\"* default\\n\"\\\n\t\t\t\"* degenerate\\n\"\\\n\t\t\t\"* doo-sabin, doo, sabin, ds\\n\")\n\n\t\t(\t\"fair,f\",\n\t\t\t\"Performs a fairing step after working with the mesh.\");\n\n\t// Add pruning program options\n\n\tpo::options_description pruning(\"Pruning\", 80);\n\tpruning.add_options()\n\t\t(\t\"remove-faces\",\n\t\t\tpo::value<std::string>(),\n\t\t\t\"Remove faces whose number of sides matches one of the numbers in the list. \"\\\n\t\t\t\"Use commas to separate list values.\")\n\n\t\t(\t\"remove-vertices\",\n\t\t\tpo::value<std::string>(),\n\t\t\t\"Remove vertices whose valency matches one of the numbers in the list. \"\\\n\t\t\t\"Use commas to separate list values.\");\n\n\t// Add hidden program options that are used for multiple input files\n\n\tpo::options_description hidden_options(\"\");\n\thidden_options.add_options()\n\t\t(\t\"input\",\n\t\t\tpo::value< std::vector<std::string> >());\n\n\t// Describe visible options of the program and parse the command-line\n\t// using _all_ available options\n\n\tpo::options_description visible_options(\"Usage: psalm [arguments] [files]\");\n\tpo::options_description all_options(\"\");\n\n\tvisible_options.add(general);\n\tvisible_options.add(tuning);\n\tvisible_options.add(pruning);\n\n\tall_options.add(visible_options);\n\tall_options.add(hidden_options);\n\n\tpo::positional_options_description p;\n\tp.add(\"input\", -1);\n\n\tpo::variables_map vm;\n\ttry\n\t{\n\t\tpo::store(po::command_line_parser(argc, argv)\t.options(all_options)\n\t\t\t\t\t\t\t\t.positional(p)\n\t\t\t\t\t\t\t\t.run(), vm);\n\t\tpo::notify(vm);\n\t}\n\tcatch(const boost::program_options::error& e)\n\t{\n\t\tstd::cerr << \"psalm: Options error: \" << e.what() << \"\\n\";\n\t\treturn(-1);\n\t}\n\n\t// Actual handling of command-line options; mostly, parameters are set\n\n\tif(vm.count(\"help\"))\n\t{\n\t\tstd::cerr << all_options << \"\\n\";\n\t\treturn(0);\n\t}\n\n\tif(vm.count(\"type\"))\n\t{\n\t\tstd::string type_str = vm[\"type\"].as<std::string>();\n\t\tstd::transform(type_str.begin(), type_str.end(), type_str.begin(), (int(*)(int)) tolower);\n\t\tif(type_str == \"ply\")\n\t\t\ttype = psalm::mesh::TYPE_PLY;\n\t\telse if(type_str == \"obj\")\n\t\t\ttype = psalm::mesh::TYPE_OBJ;\n\t\telse if(type_str == \"off\")\n\t\t\ttype = psalm::mesh::TYPE_OFF;\n\t\telse\n\t\t{\n\t\t\tstd::cerr << \"psalm: \\\"\" << type_str << \"\\\" is an unknown mesh data type.\\n\";\n\t\t\treturn(-1);\n\t\t}\n\t}\n\n\t// As there is currently only _one_ fairing algorithm, there is really\n\t// not much choice here\n\tif(vm.count(\"fair\"))\n        {\n// FIXME: Should be conditionally disabled...\n#if 0\n\t\tfairing_algorithm = new psalm::CurvatureFlow();\n#endif\n        }\n\n\t// We use this instance to create an instance of a subdivision\n\t// algorithm class. Further class parameters are set _afterwards_,\n\t// sometimes depending on the type of subdivision algorithm.\n\tif(vm.count(\"algorithm\"))\n\t{\n\t\tstd::string algorithm_str = vm[\"algorithm\"].as<std::string>();\n\t\tstd::transform(algorithm_str.begin(), algorithm_str.end(), algorithm_str.begin(), (int(*)(int)) tolower);\n\n\t\tif(\talgorithm_str == \"catmull-clark\"\t||\n\t\t\talgorithm_str == \"catmull\"\t\t||\n\t\t\talgorithm_str == \"clark\"\t\t||\n\t\t\talgorithm_str == \"cc\")\n\t\t{\n\t\t\tsubdivision_algorithm = new psalm::CatmullClark();\n\t\t}\n\t\telse if(algorithm_str == \"doo-sabin\"\t\t||\n\t\t\talgorithm_str == \"doo\"\t\t\t||\n\t\t\talgorithm_str == \"sabin\"\t\t||\n\t\t\talgorithm_str == \"ds\")\n\t\t{\n\t\t\tsubdivision_algorithm = new psalm::DooSabin();\n\t\t}\n\t\telse if(algorithm_str == \"loop\"\t||\n\t\t\talgorithm_str == \"l\")\n\t\t{\n\t\t\tsubdivision_algorithm = new psalm::Loop();\n\t\t}\n\t\telse if(algorithm_str == \"liepa\")\n\t\t{\n\t\t\tsubdivision_algorithm = new psalm::Liepa();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cerr << \"psalm: \\\"\" << algorithm_str << \"\\\" is an unknown algorithm.\\n\";\n\t\t\treturn(-1);\n\t\t}\n\t}\n\n\t// Only applicable if the subdivision algorithm is the Doo-Sabin\n\t// subdivision scheme\n\tif(vm.count(\"extra-weights\"))\n\t{\n\t\tpsalm::DooSabin* ds_algorithm = dynamic_cast<psalm::DooSabin*>(subdivision_algorithm);\n\t\tif(ds_algorithm)\n\t\t{\n\t\t\textra_weights = load_weights_map(vm[\"extra-weights\"].as<std::string>());\n\t\t\tif(extra_weights.size() == 0)\n\t\t\t{\n\t\t\t\tstd::cerr << \"psalm: Unwilling to continue with empty weights file.\\n\";\n\t\t\t\treturn(-1);\n\t\t\t}\n\n\t\t\tds_algorithm->set_custom_weights(extra_weights);\n\t\t}\n\t\telse\n\t\t\tstd::cerr << \"psalm: Warning: Weights file specified, but no Doo-Sabin algorithm.\\n\";\n\t}\n\n\tif(vm.count(\"weights\"))\n\t{\n\t\tstd::string weights_str = vm[\"weights\"].as<std::string>();\n\t\tstd::transform(weights_str.begin(), weights_str.end(), weights_str.begin(), (int(*)(int)) tolower);\n\n\t\tif(\tweights_str == \"catmull-clark\"\t||\n\t\t\tweights_str == \"catmull\"\t||\n\t\t\tweights_str == \"clark\"\t\t||\n\t\t\tweights_str == \"cc\")\n\t\t{\n\t\t\tsubdivision_algorithm->set_weights(psalm::SubdivisionAlgorithm::catmull_clark);\n\t\t}\n\t\telse if(weights_str == \"doo-sabin\"\t||\n\t\t\tweights_str == \"doo\"\t\t||\n\t\t\tweights_str == \"sabin\"\t\t||\n\t\t\tweights_str == \"ds\")\n\t\t{\n\t\t\tsubdivision_algorithm->set_weights(psalm::SubdivisionAlgorithm::doo_sabin);\n\t\t}\n\t\telse if(weights_str == \"degenerate\")\n\t\t{\n\t\t\tsubdivision_algorithm->set_weights(psalm::SubdivisionAlgorithm::degenerate);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cerr << \"psalm: \\\"\" << weights_str << \"\\\" is an unknown weight scheme.\\n\";\n\t\t\treturn(-1);\n\t\t}\n\t}\n\n\t// This is parsed using an external function because the parameter\n\t// string consists of comma-separated values\n\n\tif(vm.count(\"remove-faces\"))\n\t\tremove_faces = parse_value_string(vm[\"remove-faces\"].as<std::string>());\n\n\tif(vm.count(\"remove-vertices\"))\n\t\tremove_vertices = parse_value_string(vm[\"remove-vertices\"].as<std::string>());\n\n\t// Various small flags\n\n\tif(vm.count(\"handle-creases\"))\n\t\tsubdivision_algorithm->set_crease_handling_flag();\n\n\tif(vm.count(\"geometric\"))\n\t\tsubdivision_algorithm->set_geometric_point_creation_flag();\n\n\tif(vm.count(\"preserve-boundaries\"))\n\t\tsubdivision_algorithm->set_boundary_preservation_flag();\n\n\tif(vm.count(\"statistics\"))\n\t\tsubdivision_algorithm->set_statistics_flag();\n\n\t// This only works for B-spline-based subdivision algorithms, hence the\n\t// dynamic_cast.\n\tif(vm.count(\"b-spline-weights\"))\n\t{\n\t\tpsalm::BsplineSubdivisionAlgorithm* b_spline_algorithm = dynamic_cast<psalm::BsplineSubdivisionAlgorithm*>(subdivision_algorithm);\n\t\tif(b_spline_algorithm)\n\t\t\tb_spline_algorithm->set_bspline_weights_usage();\n\t}\n\n\t// Read further command-line parameters; these are all supposed to be\n\t// input files. If the user already specified an output file, only one\n\t// input file will be accepted.\n\n\tstd::vector<std::string> files;\n\tif(vm.count(\"input\"))\n\t{\n\t\tfiles = vm[\"input\"].as< std::vector<std::string> >();\n\t\tif(output.length() != 0 && files.size() > 1)\n\t\t{\n\t\t\tstd::cerr << \"psalm: Output file specified, but more than one input file present.\\n\";\n\t\t\treturn(-1);\n\t\t}\n\n\t}\n\n\t// Replace the special file \"-\" by an empty string, thereby signalling\n\t// that standard input and standard output are to be used as file\n\t// streams.\n\n\tfor(std::vector<std::string>::iterator it = files.begin(); it != files.end(); it++)\n\t{\n\t\tif(it->length() == 1 && (*it)[0] == '-')\n\t\t\t*it = \"\";\n\t}\n\n\tbool output_set = (output.length() > 0);\n\tif(output.length() == 1 && output[0] == '-')\n\t\toutput = \"\";\n\n\t// Try to read from STDIN if no input files have been specified\n\tif(files.size() == 0)\n\t\tfiles.push_back(\"\");\n\n\t// Apply subdivision algorithm to all files\n\n\tfor(std::vector<std::string>::iterator it = files.begin(); it != files.end(); it++)\n\t{\n\t\tscene_mesh.load(*it, type);\n\n\t\t// It is possible that the user did not choose a subdivision\n\t\t// algorithm. psalm tries to work as a mesh converter in this\n\t\t// instance.\n\t\tif(subdivision_algorithm)\n\t\t\tsubdivision_algorithm->apply_to(scene_mesh, steps);\n\n\t\t// Ditto for the fairing algorithm.\n\t\tif(fairing_algorithm)\n\t\t\tfairing_algorithm->apply_to(scene_mesh);\n\n\t\tscene_mesh.prune(remove_faces, remove_vertices);\n\n\t\t// If an output file has been set (even if it is empty), it\n\t\t// will be used.\n\t\tif(output_set)\n\t\t\tscene_mesh.save(output, type);\n\n\t\t// If no output file has been set and the input file name is\n\t\t// not empty, the output will be written to a file.\n\t\telse if(it->length() > 0)\n\t\t{\n\t\t\tsize_t ext_pos = (*it).find_last_of(\".\");\n\t\t\tif(ext_pos == std::string::npos)\n\t\t\t\tscene_mesh.save(*it+\".subdivided\", type);\n\t\t\telse\n\t\t\t\tscene_mesh.save( (*it).substr(0, ext_pos) + \"_subdivided\"\n\t\t\t\t\t\t+(*it).substr(ext_pos));\n\t\t}\n\n\t\t// If no output file has been set and the input file name is\n\t\t// empty, the output will be written to STDOUT.\n\t\telse\n\t\t\tscene_mesh.save(\"\", type);\n\t}\n\n\tdelete(subdivision_algorithm);\n\tdelete(fairing_algorithm);\n\n\treturn(0);\n}\n", "meta": {"hexsha": "134477e08be5169f76d3d99b47de7c38b04a3aa1", "size": 13883, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "psalm.cpp", "max_stars_repo_name": "Pseudomanifold/psalm", "max_stars_repo_head_hexsha": "b9c3bc83950efb6efab8bb4775bf0421bee474d3", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-07-21T14:53:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T09:12:54.000Z", "max_issues_repo_path": "psalm.cpp", "max_issues_repo_name": "Pseudomanifold/psalm", "max_issues_repo_head_hexsha": "b9c3bc83950efb6efab8bb4775bf0421bee474d3", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "psalm.cpp", "max_forks_repo_name": "Pseudomanifold/psalm", "max_forks_repo_head_hexsha": "b9c3bc83950efb6efab8bb4775bf0421bee474d3", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-08T01:25:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-29T17:37:29.000Z", "avg_line_length": 26.3935361217, "max_line_length": 132, "alphanum_fraction": 0.6734855579, "num_tokens": 3836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.259824057180512}}
{"text": "//\n//  IglUtils.hpp\n//  IPC\n//\n//  Created by Minchen Li on 8/30/17.\n//\n\n#ifndef IglUtils_hpp\n#define IglUtils_hpp\n\n#include \"Mesh.hpp\"\n\n#ifdef USE_CLOSEDFORMSVD2D\n#include \"ClosedFormSVD2d.hpp\"\n#else\n#include \"AutoFlipSVD.hpp\"\n#endif\n\n#include \"LinSysSolver.hpp\"\n\n#ifdef USE_PREDICATES\n#include <igl/predicates/predicates.h>\n// #include <ECCD.hpp>\n#endif\n\n#include <Eigen/Eigen>\n\n#include <iostream>\n#include <fstream>\n\nnamespace IPC {\n\n// a static class implementing basic geometry processing operations that are not provided in libIgl\nclass IglUtils {\n\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\npublic:\n    template <int dim>\n    static void addBlockToMatrix(const Eigen::Matrix<double, dim, dim*(dim + 1)>& block,\n        const Eigen::Matrix<int, 1, dim + 1>& index, int rowIndI,\n        LinSysSolver<Eigen::VectorXi, Eigen::VectorXd>* linSysSolver)\n    {\n        int rowStart = index[rowIndI] * dim;\n        if (rowStart < 0) {\n            rowStart = -rowStart - dim;\n            linSysSolver->setCoeff(rowStart, rowStart, 1.0);\n            linSysSolver->setCoeff(rowStart + 1, rowStart + 1, 1.0);\n            if constexpr (dim == 3) {\n                linSysSolver->setCoeff(rowStart + 2, rowStart + 2, 1.0);\n            }\n            return;\n        }\n\n        if (index[0] >= 0) {\n            int _dimIndex0 = index[0] * dim;\n            linSysSolver->addCoeff(rowStart, _dimIndex0, block(0, 0));\n            linSysSolver->addCoeff(rowStart, _dimIndex0 + 1, block(0, 1));\n            linSysSolver->addCoeff(rowStart + 1, _dimIndex0, block(1, 0));\n            linSysSolver->addCoeff(rowStart + 1, _dimIndex0 + 1, block(1, 1));\n            if constexpr (dim == 3) {\n                linSysSolver->addCoeff(rowStart, _dimIndex0 + 2, block(0, 2));\n                linSysSolver->addCoeff(rowStart + 1, _dimIndex0 + 2, block(1, 2));\n                linSysSolver->addCoeff(rowStart + 2, _dimIndex0, block(2, 0));\n                linSysSolver->addCoeff(rowStart + 2, _dimIndex0 + 1, block(2, 1));\n                linSysSolver->addCoeff(rowStart + 2, _dimIndex0 + 2, block(2, 2));\n            }\n        }\n\n        if (index[1] >= 0) {\n            int _dimIndex1 = index[1] * dim;\n            linSysSolver->addCoeff(rowStart, _dimIndex1, block(0, dim));\n            linSysSolver->addCoeff(rowStart, _dimIndex1 + 1, block(0, dim + 1));\n            linSysSolver->addCoeff(rowStart + 1, _dimIndex1, block(1, dim));\n            linSysSolver->addCoeff(rowStart + 1, _dimIndex1 + 1, block(1, dim + 1));\n            if constexpr (dim == 3) {\n                linSysSolver->addCoeff(rowStart, _dimIndex1 + 2, block(0, dim + 2));\n                linSysSolver->addCoeff(rowStart + 1, _dimIndex1 + 2, block(1, dim + 2));\n                linSysSolver->addCoeff(rowStart + 2, _dimIndex1, block(2, dim));\n                linSysSolver->addCoeff(rowStart + 2, _dimIndex1 + 1, block(2, dim + 1));\n                linSysSolver->addCoeff(rowStart + 2, _dimIndex1 + 2, block(2, dim + 2));\n            }\n        }\n\n        if (index[2] >= 0) {\n            int _2dim = 2 * dim;\n            int _dimIndex2 = index[2] * dim;\n            linSysSolver->addCoeff(rowStart, _dimIndex2, block(0, _2dim));\n            linSysSolver->addCoeff(rowStart, _dimIndex2 + 1, block(0, _2dim + 1));\n            linSysSolver->addCoeff(rowStart + 1, _dimIndex2, block(1, _2dim));\n            linSysSolver->addCoeff(rowStart + 1, _dimIndex2 + 1, block(1, _2dim + 1));\n            if constexpr (dim == 3) {\n                linSysSolver->addCoeff(rowStart, _dimIndex2 + 2, block(0, _2dim + 2));\n                linSysSolver->addCoeff(rowStart + 1, _dimIndex2 + 2, block(1, _2dim + 2));\n                linSysSolver->addCoeff(rowStart + 2, _dimIndex2, block(2, _2dim));\n                linSysSolver->addCoeff(rowStart + 2, _dimIndex2 + 1, block(2, _2dim + 1));\n                linSysSolver->addCoeff(rowStart + 2, _dimIndex2 + 2, block(2, _2dim + 2));\n            }\n        }\n\n        if constexpr (dim == 3) {\n            if (index[3] >= 0) {\n                int _3dim = 3 * dim;\n                int _dimIndex3 = index[3] * dim;\n                linSysSolver->addCoeff(rowStart, _dimIndex3, block(0, _3dim));\n                linSysSolver->addCoeff(rowStart, _dimIndex3 + 1, block(0, _3dim + 1));\n                linSysSolver->addCoeff(rowStart, _dimIndex3 + 2, block(0, _3dim + 2));\n                linSysSolver->addCoeff(rowStart + 1, _dimIndex3, block(1, _3dim));\n                linSysSolver->addCoeff(rowStart + 1, _dimIndex3 + 1, block(1, _3dim + 1));\n                linSysSolver->addCoeff(rowStart + 1, _dimIndex3 + 2, block(1, _3dim + 2));\n                linSysSolver->addCoeff(rowStart + 2, _dimIndex3, block(2, _3dim));\n                linSysSolver->addCoeff(rowStart + 2, _dimIndex3 + 1, block(2, _3dim + 1));\n                linSysSolver->addCoeff(rowStart + 2, _dimIndex3 + 2, block(2, _3dim + 2));\n            }\n        }\n    }\n\n    // project a symmetric real matrix to the nearest SPD matrix\n    template <typename Scalar, int size>\n    static void makePD(Eigen::Matrix<Scalar, size, size>& symMtr)\n    {\n        Eigen::SelfAdjointEigenSolver<Eigen::Matrix<Scalar, size, size>> eigenSolver(symMtr);\n        if (eigenSolver.eigenvalues()[0] >= 0.0) {\n            return;\n        }\n        Eigen::DiagonalMatrix<Scalar, size> D(eigenSolver.eigenvalues());\n        int rows = ((size == Eigen::Dynamic) ? symMtr.rows() : size);\n        for (int i = 0; i < rows; i++) {\n            if (D.diagonal()[i] < 0.0) {\n                D.diagonal()[i] = 0.0;\n            }\n            else {\n                break;\n            }\n        }\n        symMtr = eigenSolver.eigenvectors() * D * eigenSolver.eigenvectors().transpose();\n    }\n    template <typename Scalar, int size>\n    static void makePD2d(Eigen::Matrix<Scalar, size, size>& symMtr)\n    {\n        // based on http://www.math.harvard.edu/archive/21b_fall_04/exhibits/2dmatrices/\n\n        if (size == Eigen::Dynamic) {\n            assert(symMtr.rows() == 2);\n        }\n        else {\n            assert(size == 2);\n        }\n\n        const double a = symMtr(0, 0);\n        const double b = (symMtr(0, 1) + symMtr(1, 0)) / 2.0;\n        const double d = symMtr(1, 1);\n\n        double b2 = b * b;\n        const double D = a * d - b2;\n        const double T_div_2 = (a + d) / 2.0;\n        const double sqrtTT4D = std::sqrt(T_div_2 * T_div_2 - D);\n        const double L2 = T_div_2 - sqrtTT4D;\n        if (L2 < 0.0) {\n            const double L1 = T_div_2 + sqrtTT4D;\n            if (L1 <= 0.0) {\n                symMtr.setZero();\n            }\n            else {\n                if (b2 == 0.0) {\n                    symMtr << L1, 0.0, 0.0, 0.0;\n                }\n                else {\n                    const double L1md = L1 - d;\n                    const double L1md_div_L1 = L1md / L1;\n                    symMtr(0, 0) = L1md_div_L1 * L1md;\n                    symMtr(0, 1) = symMtr(1, 0) = b * L1md_div_L1;\n                    symMtr(1, 1) = b2 / L1;\n                }\n            }\n        }\n    }\n    template <typename Scalar, int size>\n    static void flipDet_SVD(Eigen::Matrix<Scalar, size, size>& mtr)\n    {\n        Eigen::JacobiSVD<Eigen::Matrix<Scalar, size, size>> svd(mtr, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n        Eigen::Matrix<Scalar, size, size> U = svd.matrixU(), V = svd.matrixV();\n        if (U.determinant() < 0) {\n            U.col(U.cols() - 1) *= -1.0;\n        }\n        if (V.determinant() < 0) {\n            V.col(V.cols() - 1) *= -1.0;\n        }\n        mtr = U * Eigen::DiagonalMatrix<Scalar, size>(svd.singularValues()) * V.transpose();\n    }\n\n    static void writeSparseMatrixToFile(const std::string& filePath,\n        const Eigen::SparseMatrix<double>& mtr,\n        bool MATLAB = false);\n    static void writeSparseMatrixToFile(const std::string& filePath,\n        const std::map<std::pair<int, int>, double>& mtr,\n        bool MATLAB = false);\n    static void writeSparseMatrixToFile(const std::string& filePath,\n        LinSysSolver<Eigen::VectorXi, Eigen::VectorXd>* linSysSolver,\n        bool MATLAB = false);\n    static void loadSparseMatrixFromFile(const std::string& filePath,\n        Eigen::SparseMatrix<double>& mtr);\n\n    static void writeVectorToFile(const std::string& filePath,\n        const Eigen::VectorXd& vec);\n    static void readVectorFromFile(const std::string& filePath,\n        Eigen::VectorXd& vec);\n\n    // read segment mesh file\n    static bool readSEG(const std::string& filePath, Eigen::MatrixXd& V, Eigen::MatrixXi& E);\n    static void writeSEG(const std::string& filePath, const Eigen::MatrixXd& V, const Eigen::MatrixXi& E);\n\n    static bool segTriIntersect(const Eigen::RowVector3d& ve0, const Eigen::RowVector3d& ve1,\n        const Eigen::RowVector3d& vt0, const Eigen::RowVector3d& vt1, const Eigen::RowVector3d& vt2)\n    {\n        Eigen::Matrix3d coefMtr;\n        coefMtr.col(0) = vt1 - vt0;\n        coefMtr.col(1) = vt2 - vt0;\n        coefMtr.col(2) = ve0 - ve1;\n\n#ifdef USE_PREDICATES\n        igl::predicates::exactinit();\n        const auto ori1 = igl::predicates::orient3d(vt0, vt1, vt2, ve0);\n        const auto ori2 = igl::predicates::orient3d(vt0, vt1, vt2, ve1);\n        if (ori1 == igl::predicates::Orientation::COPLANAR || ori2 == igl::predicates::Orientation::COPLANAR) {\n            // coplanar, we can detect it by d(EE)=0 or d(PT)=0\n            return false;\n        }\n\n        if (ori1 == ori2) {\n            // edge is on one side of the plane that triangle is in\n            return false;\n        }\n#else\n        Eigen::RowVector3d n = coefMtr.col(0).cross(coefMtr.col(1));\n        if (n.dot(ve0 - vt0) * n.dot(ve1 - vt0) > 0.0) {\n            return false; // edge is on one side of the plane that triangle is in\n        }\n\n        if (coefMtr.determinant() == 0.0) {\n            return false; // coplanar, we can detect it by d(EE)=0 or d(PT)=0\n        }\n#endif\n\n#ifdef USE_PREDICATES\n        // int res = eccd::segment_triangle_inter(ve0, ve1, vt0, vt1, vt2);\n        // if(res == 1){\n        // std::cout << ve0 << std::endl;\n        // std::cout << ve1 << std::endl;\n        // std::cout << vt0 << std::endl;\n        // std::cout << vt1 << std::endl;\n        // std::cout << vt2 << std::endl;\n        // exit(0);\n        // }\n        // return res == 1 ? true : false;\n#endif\n        Eigen::Vector3d uvt = coefMtr.fullPivLu().solve((ve0 - vt0).transpose());\n        if (uvt[0] >= 0.0 && uvt[1] >= 0.0 && uvt[0] + uvt[1] <= 1.0 && uvt[2] >= 0.0 && uvt[2] <= 1.0) {\n            return true;\n        }\n        else {\n            return false;\n        }\n    }\n\n    static bool\n    pointBehindTri(\n        const Eigen::RowVector3d& vt0, const Eigen::RowVector3d& vt1,\n        const Eigen::RowVector3d& vt2, const Eigen::RowVector3d& v0)\n    {\n        return (vt1 - vt0).cross(vt2 - vt0).dot(v0 - vt0) <= 0.0;\n    }\n\n    static bool\n    pointInsideTetrahedron(const Eigen::RowVector3d& v0,\n        const Eigen::RowVector3d& vt0, const Eigen::RowVector3d& vt1,\n        const Eigen::RowVector3d& vt2, const Eigen::RowVector3d& vt3)\n    {\n#ifdef USE_PREDICATES\n        igl::predicates::exactinit();\n        const auto ori1 = igl::predicates::orient3d(vt0, vt2, vt1, v0);\n        if (ori1 != igl::predicates::Orientation::NEGATIVE) {\n            const auto ori2 = igl::predicates::orient3d(vt0, vt3, vt2, v0);\n            if (ori2 != igl::predicates::Orientation::NEGATIVE) {\n                const auto ori3 = igl::predicates::orient3d(vt0, vt1, vt3, v0);\n                if (ori3 != igl::predicates::Orientation::NEGATIVE) {\n                    const auto ori4 = igl::predicates::orient3d(vt1, vt2, vt3, v0);\n                    if (ori4 != igl::predicates::Orientation::NEGATIVE) {\n                        return true;\n                    }\n                }\n            }\n        }\n#else\n        const bool ori1 = pointBehindTri(vt0, vt2, vt1, v0);\n        if (ori1) {\n            const bool ori2 = pointBehindTri(vt0, vt3, vt2, v0);\n            if (ori2) {\n                const bool ori3 = pointBehindTri(vt0, vt1, vt3, v0);\n                if (ori3) {\n                    const bool ori4 = pointBehindTri(vt1, vt2, vt3, v0);\n                    if (ori4) {\n                        return true;\n                    }\n                }\n            }\n        }\n#endif\n        return false;\n    }\n\n    static void findSurfaceTris(const Eigen::MatrixXi& TT, Eigen::MatrixXi& F);\n    static void buildSTri2Tet(const Eigen::MatrixXi& F, const Eigen::MatrixXi& SF,\n        std::vector<int>& sTri2Tet);\n\n    static void saveTetMesh(const std::string& filePath,\n        const Eigen::MatrixXd& TV, const Eigen::MatrixXi& TT,\n        const Eigen::MatrixXi& F = Eigen::MatrixXi(),\n        bool findSurface = true);\n    static void saveTetMesh_msh4(const std::string& filePath,\n        const Eigen::MatrixXd& TV, const Eigen::MatrixXi& TT,\n        const Eigen::MatrixXi& F = Eigen::MatrixXi(),\n        bool findSurface = true);\n    static void saveTetMesh_vtk(const std::string& filePath,\n        const Eigen::MatrixXd& TV, const Eigen::MatrixXi& TT);\n    static bool readTetMesh(const std::string& filePath,\n        Eigen::MatrixXd& TV, Eigen::MatrixXi& TT,\n        Eigen::MatrixXi& F, bool findSurface = true);\n    static bool readTetMesh_msh4(const std::string& filePath,\n        Eigen::MatrixXd& TV, Eigen::MatrixXi& TT,\n        Eigen::MatrixXi& F, bool findSurface = true);\n    static void readNodeEle(const std::string& filePath,\n        Eigen::MatrixXd& TV, Eigen::MatrixXi& TT,\n        Eigen::MatrixXi& F);\n\n    template <int colSize>\n    static void dF_div_dx_mult(const Eigen::Matrix<double, DIM * DIM, colSize>& right,\n        const Eigen::Matrix<double, DIM, DIM>& A,\n        Eigen::Matrix<double, DIM*(DIM + 1), colSize>& result,\n        bool symmetric)\n    {\n        if (colSize == Eigen::Dynamic) {\n            assert(right.cols() > 0);\n        }\n        else {\n            assert(colSize > 0);\n        }\n#if (DIM == 2)\n        if (symmetric) {\n            if (colSize == Eigen::Dynamic) {\n                assert(right.cols() == 6);\n            }\n            else {\n                assert(colSize == 6);\n            }\n            // int colI = 0;\n            const double _0000 = right(0, 0) * A(0, 0);\n            const double _0010 = right(0, 0) * A(1, 0);\n            const double _1001 = right(1, 0) * A(0, 1);\n            const double _1011 = right(1, 0) * A(1, 1);\n            const double _2000 = right(2, 0) * A(0, 0);\n            const double _2010 = right(2, 0) * A(1, 0);\n            const double _3001 = right(3, 0) * A(0, 1);\n            const double _3011 = right(3, 0) * A(1, 1);\n            result(2, 0) = result(0, 2) = _0000 + _1001;\n            result(3, 0) = result(0, 3) = _2000 + _3001;\n            result(4, 0) = result(0, 4) = _0010 + _1011;\n            result(5, 0) = result(0, 5) = _2010 + _3011;\n            result(0, 0) = -result(2, 0) - result(4, 0);\n            result(1, 0) = result(0, 1) = -result(3, 0) - result(5, 0);\n            // colI = 1;\n            const double _2100 = right(2, 1) * A(0, 0);\n            const double _2110 = right(2, 1) * A(1, 0);\n            const double _3101 = right(3, 1) * A(0, 1);\n            const double _3111 = right(3, 1) * A(1, 1);\n            result(2, 1) = result(1, 2) = right(0, 1) * A(0, 0) + right(1, 1) * A(0, 1);\n            result(3, 1) = result(1, 3) = _2100 + _3101;\n            result(4, 1) = result(1, 4) = right(0, 1) * A(1, 0) + right(1, 1) * A(1, 1);\n            result(5, 1) = result(1, 5) = _2110 + _3111;\n            result(1, 1) = -result(3, 1) - result(5, 1);\n            // colI = 2;\n            result(2, 2) = right(0, 2) * A(0, 0) + right(1, 2) * A(0, 1);\n            result(3, 2) = result(2, 3) = right(2, 2) * A(0, 0) + right(3, 2) * A(0, 1);\n            result(4, 2) = result(2, 4) = right(0, 2) * A(1, 0) + right(1, 2) * A(1, 1);\n            result(5, 2) = result(2, 5) = right(2, 2) * A(1, 0) + right(3, 2) * A(1, 1);\n            // colI = 3;\n            result(3, 3) = right(2, 3) * A(0, 0) + right(3, 3) * A(0, 1);\n            result(4, 3) = result(3, 4) = right(0, 3) * A(1, 0) + right(1, 3) * A(1, 1);\n            result(5, 3) = result(3, 5) = right(2, 3) * A(1, 0) + right(3, 3) * A(1, 1);\n            // colI = 4;\n            result(4, 4) = right(0, 4) * A(1, 0) + right(1, 4) * A(1, 1),\n                      result(5, 4) = result(4, 5) = right(2, 4) * A(1, 0) + right(3, 4) * A(1, 1);\n            // colI = 5;\n            result(5, 5) = right(2, 5) * A(1, 0) + right(3, 5) * A(1, 1);\n        }\n        else {\n            for (int colI = 0; colI < right.cols(); colI++) {\n                const double _000 = right(0, colI) * A(0, 0);\n                const double _010 = right(0, colI) * A(1, 0);\n                const double _101 = right(1, colI) * A(0, 1);\n                const double _111 = right(1, colI) * A(1, 1);\n                const double _200 = right(2, colI) * A(0, 0);\n                const double _210 = right(2, colI) * A(1, 0);\n                const double _301 = right(3, colI) * A(0, 1);\n                const double _311 = right(3, colI) * A(1, 1);\n\n                result(2, colI) = _000 + _101;\n                result(3, colI) = _200 + _301;\n                result(4, colI) = _010 + _111;\n                result(5, colI) = _210 + _311;\n                result(0, colI) = -result(2, colI) - result(4, colI);\n                result(1, colI) = -result(3, colI) - result(5, colI);\n            }\n        }\n#else\n        for (int colI = 0; colI < right.cols(); colI++) {\n            result(3, colI) = (A.row(0) * right.block(0, colI, DIM, 1))[0];\n            result(4, colI) = (A.row(0) * right.block(DIM, colI, DIM, 1))[0];\n            result(5, colI) = (A.row(0) * right.block(DIM * 2, colI, DIM, 1))[0];\n            result(6, colI) = (A.row(1) * right.block(0, colI, DIM, 1))[0];\n            result(7, colI) = (A.row(1) * right.block(DIM, colI, DIM, 1))[0];\n            result(8, colI) = (A.row(1) * right.block(DIM * 2, colI, DIM, 1))[0];\n            result(9, colI) = (A.row(2) * right.block(0, colI, DIM, 1))[0];\n            result(10, colI) = (A.row(2) * right.block(DIM, colI, DIM, 1))[0];\n            result(11, colI) = (A.row(2) * right.block(DIM * 2, colI, DIM, 1))[0];\n            result(0, colI) = -result(3, colI) - result(6, colI) - result(9, colI);\n            result(1, colI) = -result(4, colI) - result(7, colI) - result(10, colI);\n            result(2, colI) = -result(5, colI) - result(8, colI) - result(11, colI);\n        }\n#endif\n    }\n    static void dF_div_dx_mult(const Eigen::Matrix<double, DIM, DIM>& right,\n        const Eigen::Matrix<double, DIM, DIM>& A,\n        Eigen::Matrix<double, DIM*(DIM + 1), 1>& result);\n    template <int dim>\n    static void computeCofactorMtr(const Eigen::Matrix<double, dim, dim>& F,\n        Eigen::Matrix<double, dim, dim>& A)\n    {\n        switch (dim) {\n        case 2:\n            A(0, 0) = F(1, 1);\n            A(0, 1) = -F(1, 0);\n            A(1, 0) = -F(0, 1);\n            A(1, 1) = F(0, 0);\n            break;\n\n        case 3:\n            A(0, 0) = F(1, 1) * F(2, 2) - F(1, 2) * F(2, 1);\n            A(0, 1) = F(1, 2) * F(2, 0) - F(1, 0) * F(2, 2);\n            A(0, 2) = F(1, 0) * F(2, 1) - F(1, 1) * F(2, 0);\n            A(1, 0) = F(0, 2) * F(2, 1) - F(0, 1) * F(2, 2);\n            A(1, 1) = F(0, 0) * F(2, 2) - F(0, 2) * F(2, 0);\n            A(1, 2) = F(0, 1) * F(2, 0) - F(0, 0) * F(2, 1);\n            A(2, 0) = F(0, 1) * F(1, 2) - F(0, 2) * F(1, 1);\n            A(2, 1) = F(0, 2) * F(1, 0) - F(0, 0) * F(1, 2);\n            A(2, 2) = F(0, 0) * F(1, 1) - F(0, 1) * F(1, 0);\n            break;\n\n        default:\n            assert(0 && \"dim not 2 or 3\");\n            break;\n        }\n    }\n\n    static void findBorderVerts(const Eigen::MatrixXd& V,\n        std::vector<std::vector<int>>& borderVerts,\n        double ratio);\n\n    static void Init_Dirichlet(\n        const Eigen::MatrixXd& X,\n        const Eigen::Vector3d& relBoxMin,\n        const Eigen::Vector3d& relBoxMax,\n        const std::vector<bool>& isNodeOnBoundary,\n        std::vector<int>& selectedVerts);\n}; // namespace IPC\n\n} // namespace IPC\n\n#endif /* IglUtils_hpp */\n", "meta": {"hexsha": "162b02270b98f3559931d0732d7d97bb065ecac0", "size": 20129, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Utils/IglUtils.hpp", "max_stars_repo_name": "Andlon/IPC", "max_stars_repo_head_hexsha": "3cdc29dac8486c0d62425290b4c23d03ee1d64b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 344.0, "max_stars_repo_stars_event_min_datetime": "2020-07-03T14:08:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:01:11.000Z", "max_issues_repo_path": "src/Utils/IglUtils.hpp", "max_issues_repo_name": "Andlon/IPC", "max_issues_repo_head_hexsha": "3cdc29dac8486c0d62425290b4c23d03ee1d64b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2020-07-05T15:56:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:56:39.000Z", "max_forks_repo_path": "src/Utils/IglUtils.hpp", "max_forks_repo_name": "Andlon/IPC", "max_forks_repo_head_hexsha": "3cdc29dac8486c0d62425290b4c23d03ee1d64b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 46.0, "max_forks_repo_forks_event_min_datetime": "2020-07-04T05:04:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T02:09:23.000Z", "avg_line_length": 41.8482328482, "max_line_length": 112, "alphanum_fraction": 0.5182572408, "num_tokens": 6701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2597796831365564}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   MonteCarlo_ElasticBasicBivariateDistribution.hpp\n//! \\author Luke Kersting\n//! \\brief  The elastic basic bivariate dist. class decl.\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef MONTE_CARLO_ELASTIC_BASIC_BIVARIATE_DISTRIBUTION_HPP\n#define MONTE_CARLO_ELASTIC_BASIC_BIVARIATE_DISTRIBUTION_HPP\n\n// Boost Includes\n#include <boost/units/physical_dimensions/energy.hpp>\n\n// FRENSIE Includes\n#include \"Utility_InterpolatedFullyTabularBasicBivariateDistribution.hpp\"\n\nnamespace MonteCarlo{\n\n/*! The unit-aware interpolated fully tabular two-dimensional distribution\n * \\ingroup two_d_distribution\n */\ntemplate<typename TwoDGridPolicy,\n         typename PrimaryIndependentUnit,\n         typename SecondaryIndependentUnit,\n         typename DependentUnit>\nclass UnitAwareElasticBasicBivariateDistribution : public Utility::UnitAwareInterpolatedFullyTabularBasicBivariateDistribution<TwoDGridPolicy,PrimaryIndependentUnit,SecondaryIndependentUnit,DependentUnit>\n{\n  // Only allow construction when the primary independent unit corresponds to energy\n  RESTRICT_UNIT_TO_BOOST_DIMENSION( PrimaryIndependentUnit, energy_dimension );\n\n  // The typedef for this type\n  typedef UnitAwareElasticBasicBivariateDistribution<TwoDGridPolicy,PrimaryIndependentUnit,SecondaryIndependentUnit,DependentUnit> ThisType;\n\n  // The parent distribution type\n  typedef Utility::UnitAwareInterpolatedFullyTabularBasicBivariateDistribution<TwoDGridPolicy,PrimaryIndependentUnit,SecondaryIndependentUnit,DependentUnit> BaseType;\n\n  // The base one-dimensional distribution type (UnitAwareTabularUnivariateDist)\n  typedef typename BaseType::BaseUnivariateDistributionType BaseUnivariateDistributionType;\n\n  // Typedef for QuantityTraits<double>\n  typedef typename BaseType::QT QT;\n\n  // Typedef for QuantityTraits<PrimaryIndepQuantity>\n  typedef typename BaseType::PIQT PIQT;\n\n  // Typedef for QuantityTraits<SecondaryIndepQuantity>\n  typedef typename BaseType::SIQT SIQT;\n\n  // Typedef for QuantityTriats<InverseSecondaryIndepQuantity>\n  typedef typename BaseType::ISIQT ISIQT;\n\n  // Typedef for QuantityTraits<DepQuantity>\n  typedef typename BaseType::DQT DQT;\n\n  // The primary independent variable processing tag\n  typedef typename TwoDGridPolicy::TwoDInterpPolicy::FirstIndepVarProcessingTag FirstIndepVarProcessingTag;\n\n  // The secondary independent quantity type\n  typedef typename TwoDGridPolicy::TwoDInterpPolicy::SecondIndepVarProcessingTag SecondIndepVarProcessingTag;\n\n  // The distribution data const iterator\n  typedef typename BaseType::DistributionDataConstIterator DistributionDataConstIterator;\n\npublic:\n\n  //! The primary independent quantity type\n  typedef typename BaseType::PrimaryIndepQuantity PrimaryIndepQuantity;\n\n  //! The secondary independent quantity type\n  typedef typename BaseType::SecondaryIndepQuantity SecondaryIndepQuantity;\n\n  //! The inverse secondary independent quantity type\n  typedef typename BaseType::InverseSecondaryIndepQuantity InverseSecondaryIndepQuantity;\n\n  //! The dependent quantity type\n  typedef typename BaseType::DepQuantity DepQuantity;\n\n  //! Constructor\n  UnitAwareElasticBasicBivariateDistribution(\n        const std::vector<PrimaryIndepQuantity>& primary_indep_grid,\n        const std::vector<std::shared_ptr<const Utility::UnitAwareTabularUnivariateDistribution<SecondaryIndependentUnit,DependentUnit> > >& secondary_distributions,\n        const SecondaryIndepQuantity upper_bound_conditional_indep_var = SIQT::one(),\n        const double fuzzy_boundary_tol = 1e-7,\n        const double evaluate_relative_error_tol = 1e-7,\n        const double evaluate_error_tol = 1e-12 );\n\n  //! Destructor\n  ~UnitAwareElasticBasicBivariateDistribution()\n  { /* ... */ }\n\n  //! Evaluate the distribution\n  DepQuantity evaluate(\n       const PrimaryIndepQuantity primary_indep_var_value,\n       const SecondaryIndepQuantity secondary_indep_var_value ) const override;\n\n  //! Evaluate the secondary conditional PDF\n  InverseSecondaryIndepQuantity evaluateSecondaryConditionalPDF(\n       const PrimaryIndepQuantity primary_indep_var_value,\n       const SecondaryIndepQuantity secondary_indep_var_value ) const override;\n\n  //! Evaluate the secondary conditional PDF\n  InverseSecondaryIndepQuantity evaluateSecondaryConditionalPDF(\n            const PrimaryIndepQuantity primary_indep_var_value,\n            const SecondaryIndepQuantity secondary_indep_var_value,\n            const std::function<SecondaryIndepQuantity(PrimaryIndepQuantity)>&\n            min_secondary_indep_var_functor,\n            const std::function<SecondaryIndepQuantity(PrimaryIndepQuantity)>&\n            max_secondary_indep_var_functor ) const override;\n\n  //! Evaluate the secondary conditional CDF\n  double evaluateSecondaryConditionalCDF(\n       const PrimaryIndepQuantity primary_indep_var_value,\n       const SecondaryIndepQuantity secondary_indep_var_value ) const override;\n\n  //! Return a random sample from the secondary conditional PDF\n  SecondaryIndepQuantity sampleSecondaryConditional(\n           const PrimaryIndepQuantity primary_indep_var_value ) const override;\n\n  //! Return a random sample from the secondary conditional PDF\n  SecondaryIndepQuantity sampleSecondaryConditional(\n            const PrimaryIndepQuantity primary_indep_var_value,\n            const std::function<SecondaryIndepQuantity(PrimaryIndepQuantity)>&\n            min_secondary_indep_var_functor,\n            const std::function<SecondaryIndepQuantity(PrimaryIndepQuantity)>&\n            max_secondary_indep_var_functor ) const override;\n\n  //! Return a random sample and record the number of trials\n  SecondaryIndepQuantity sampleSecondaryConditionalAndRecordTrials(\n            const PrimaryIndepQuantity primary_indep_var_value,\n            Utility::DistributionTraits::Counter& trials ) const override;\n\n// Return a random sample from the secondary conditional PDF and the index\n  SecondaryIndepQuantity sampleSecondaryConditionalAndRecordBinIndices(\n            const PrimaryIndepQuantity primary_indep_var_value,\n            size_t& primary_bin_index,\n            size_t& secondary_bin_index ) const override;\n\n  //! Return a random sample from the secondary conditional PDF and the index\n  SecondaryIndepQuantity sampleSecondaryConditionalAndRecordBinIndices(\n            const PrimaryIndepQuantity primary_indep_var_value,\n            SecondaryIndepQuantity& raw_sample,\n            size_t& primary_bin_index,\n            size_t& secondary_bin_index ) const override;\n\n  //! Return a random sample from the secondary conditional PDF at the CDF val\n  SecondaryIndepQuantity sampleSecondaryConditionalWithRandomNumber(\n                const PrimaryIndepQuantity primary_indep_var_value,\n                const double random_number ) const override;\n\n  //! Return a random sample from the secondary conditional PDF in the subrange\n  SecondaryIndepQuantity sampleSecondaryConditionalInSubrange(\n   const PrimaryIndepQuantity primary_indep_var_value,\n   const SecondaryIndepQuantity max_secondary_indep_var_value ) const override;\n\n  //! Return a random sample from the secondary conditional PDF in the subrange\n  SecondaryIndepQuantity sampleSecondaryConditionalWithRandomNumberInSubrange(\n   const PrimaryIndepQuantity primary_indep_var_value,\n   const double random_number,\n   const SecondaryIndepQuantity max_secondary_indep_var_value ) const override;\n\n  //! Return the lower bound of the conditional distribution\n  SecondaryIndepQuantity getLowerBoundOfSecondaryConditionalIndepVar(\n           const PrimaryIndepQuantity primary_indep_var_value ) const override;\n\n  //! Return the upper bound of the conditional distribution\n  SecondaryIndepQuantity getUpperBoundOfSecondaryConditionalIndepVar(\n           const PrimaryIndepQuantity primary_indep_var_value ) const override;\n\n  //! Method for placing the object in an output stream\n  void toStream( std::ostream& os ) const override;\n\nprivate:\n\n  //! Default constructor\n  UnitAwareElasticBasicBivariateDistribution();\n\n  //! Evaluate the distribution using the desired evaluation method\n  template<typename ReturnType,\n           typename EvaluationMethod>\n  ReturnType evaluateImpl(\n                    const PrimaryIndepQuantity incoming_energy,\n                    const SecondaryIndepQuantity angle_cosine,\n                    EvaluationMethod evaluate ) const;\n\n  //! Evaluate the distribution using the desired evaluation method\n  template<typename ReturnType,\n           typename EvaluationMethod>\n  ReturnType evaluateImpl(\n    const PrimaryIndepQuantity incoming_energy,\n    const SecondaryIndepQuantity angle_cosine,\n    const std::function<SecondaryIndepQuantity(PrimaryIndepQuantity)>&\n      min_secondary_indep_var_functor,\n    const std::function<SecondaryIndepQuantity(PrimaryIndepQuantity)>&\n      max_secondary_indep_var_functor,\n    EvaluationMethod evaluate,\n    unsigned max_number_of_iterations = 500 ) const;\n\n  //! Evaluate the distribution using the desired evaluation method\n  template<typename EvaluationMethod>\n  double evaluateCDFImpl(\n                    const PrimaryIndepQuantity incoming_energy,\n                    const SecondaryIndepQuantity angle_cosine,\n                    EvaluationMethod evaluateCDF ) const;\n\n  //! Evaluate the distribution using the desired evaluation method\n  template<typename EvaluationMethod>\n  double evaluateCDFImpl(\n    const PrimaryIndepQuantity incoming_energy,\n    const SecondaryIndepQuantity angle_cosine,\n    const std::function<SecondaryIndepQuantity(PrimaryIndepQuantity)>&\n      min_secondary_indep_var_functor,\n    const std::function<SecondaryIndepQuantity(PrimaryIndepQuantity)>&\n      max_secondary_indep_var_functor,\n    EvaluationMethod evaluateCDF,\n    unsigned max_number_of_iterations = 500 ) const;\n\n  //! Sample from the distribution using the desired sampling functor\n  template<typename SampleFunctor>\n  SecondaryIndepQuantity sampleDetailedImpl(\n                        const PrimaryIndepQuantity primary_indep_var_value,\n                        SampleFunctor sample_functor,\n                        SecondaryIndepQuantity& raw_sample,\n                        size_t& primary_bin_index ) const;\n\n  //! Sample from the distribution using the desired sampling functor\n  template<typename SampleFunctor>\n  SecondaryIndepQuantity sampleImpl(\n                        const PrimaryIndepQuantity primary_indep_var_value,\n                        SampleFunctor sample_functor ) const;\n\n  //! Verify that the second independent variable processing type is compatible with Cosine processing\n  static void verifyValidSecondIndepVarProcessingType();\n\n  // Save the distribution to an archive\n  template<typename Archive>\n  void save( Archive& ar, const unsigned version ) const;\n\n  // Load the distribution from an archive\n  template<typename Archive>\n  void load( Archive& ar, const unsigned version );\n\n  BOOST_SERIALIZATION_SPLIT_MEMBER();\n\n  // Declare the boost serialization access object as a friend\n  friend class boost::serialization::access;\n\n  // The max upper bound of the conditional distribution ( 1.0 )\n  SecondaryIndepQuantity d_max_upper_bound_conditional_indep_var;\n\n  // The upper bound of the conditional distribution ( -1.0 < mu_cut <= 1.0 )\n  SecondaryIndepQuantity d_upper_bound_conditional_indep_var;\n\n  // The lower bound of the conditional distribution ( -1.0 )\n  SecondaryIndepQuantity d_lower_bound_conditional_indep_var;\n};\n\n/*! \\brief The interpolated fully tabular two-dimensional distribution\n * (unit-agnostic)\n * \\ingroup two_d_distributions\n */\ntemplate<typename TwoDGridPolicy> using ElasticBasicBivariateDistribution =\n  UnitAwareElasticBasicBivariateDistribution<TwoDGridPolicy,void,void,void>;\n\n} // end MonteCarlo namespace\n\nBOOST_SERIALIZATION_CLASS4_VERSION( UnitAwareElasticBasicBivariateDistribution, MonteCarlo, 0 );\n\n#define BOOST_SERIALIZATION_ELASTIC_BASIC_BIVARIATE_DISTRIBUTION_EXPORT_STANDARD_KEY() \\\n  BOOST_SERIALIZATION_CLASS4_EXPORT_STANDARD_KEY( UnitAwareElasticBasicBivariateDistribution, MonteCarlo ) \\\n  BOOST_SERIALIZATION_TEMPLATE_CLASS_EXPORT_KEY_IMPL(                   \\\n    UnitAwareElasticBasicBivariateDistribution, MonteCarlo, \\\n    __BOOST_SERIALIZATION_FORWARD_AS_SINGLE_ARG__( std::string( \"ElasticBasicBivariateDistribution<\" ) + Utility::typeName<GridPolicy>() + \">\" ), \\\n    __BOOST_SERIALIZATION_FORWARD_AS_SINGLE_ARG__( typename GridPolicy ), \\\n    __BOOST_SERIALIZATION_FORWARD_AS_SINGLE_ARG__( GridPolicy, void, void, void ) )\n\nBOOST_SERIALIZATION_ELASTIC_BASIC_BIVARIATE_DISTRIBUTION_EXPORT_STANDARD_KEY();\n\n//---------------------------------------------------------------------------//\n// Template Includes\n//---------------------------------------------------------------------------//\n\n#include \"MonteCarlo_ElasticBasicBivariateDistribution_def.hpp\"\n\n//---------------------------------------------------------------------------//\n\n#endif // end MONTE_CARLO_ELASTIC_BASIC_BIVARIATE_DISTRIBUTION_HPP\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_ElasticBasicBivariateDistribution.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "8a704feaaee69702c7d016d16ba35aea15f6dcbc", "size": 13251, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/collision/electron/src/MonteCarlo_ElasticBasicBivariateDistribution.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/monte_carlo/collision/electron/src/MonteCarlo_ElasticBasicBivariateDistribution.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/monte_carlo/collision/electron/src/MonteCarlo_ElasticBasicBivariateDistribution.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": 45.3801369863, "max_line_length": 204, "alphanum_fraction": 0.7559429477, "num_tokens": 2602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2597781926683861}}
{"text": "#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n#include <iostream>\n#include <iterator>\n#include <map>\n#include <set>\n#include <sstream>\n#include <string>\n#include <vector>\n\n#include <Eigen/Core>\n\n#include \"igl/AABB.h\"\n#include \"igl/adjacency_list.h\"\n#include \"igl/adjacency_matrix.h\"\n#include \"igl/ambient_occlusion.h\"\n#include \"igl/components.h\"\n#include \"igl/cotmatrix.h\"\n#include \"igl/decimate.h\"\n#include \"igl/dijkstra.h\"\n#include \"igl/embree/ambient_occlusion.h\"\n#include \"igl/embree/EmbreeIntersector.h\"\n#include \"igl/embree/unproject_onto_mesh.h\"\n#include \"igl/gaussian_curvature.h\"\n#include \"igl/invert_diag.h\"\n#include \"igl/jet.h\"\n#include \"igl/per_vertex_attribute_smoothing.h\"\n#include \"igl/per_vertex_normals.h\"\n#include \"igl/polygon_mesh_to_triangle_mesh.h\"\n#include \"igl/principal_curvature.h\"\n#include \"igl/ray_mesh_intersect.h\"\n#include \"igl/readOFF.h\"\n#include \"igl/unproject_onto_mesh.h\"\n#include \"igl/viewer/Viewer.h\"\n#include \"igl/writeOFF.h\"\n\n#include \"GLFW/glfw3.h\"\n\n#include \"dijkstra.hxx\"\n\nconst double mOCC_MAX_RAY_DIST = 10.0;\nconst int mOCC_NUM_RAYS = 20;\nconst double mDECIMATE_PERC = 0.6;\n\nenum SelectionType { CURVATURE, DARKNESS };\n\n// Split a string into words.\nstd::vector<std::string> split(const std::string &input) {\n  using namespace std;\n  istringstream iss(input);\n  vector<string> tokens{istream_iterator<string>{iss},\n                        istream_iterator<string>{}};\n  return tokens;\n}\n\nstd::string prettyprint(const std::string &input, int width, int trailing_spaces) {\n  using namespace std;\n  vector<string> words = split(input);\n  \n  string ret;\n  int cur_width = 0;\n  for (const string &s : words) {\n    if (cur_width + s.size() > width) {\n      ret += \"\\n\";\n      for (int i = 0; i < trailing_spaces; ++i) {\n        ret += \" \";\n      }\n      cur_width = 0;\n    }\n    ret += s + \" \";\n    cur_width += s.size() + 1;\n  }\n\n  return ret;\n}\n\nvoid buildChoiceSide(std::vector<std::string> &prompts,\n                     std::vector<SelectionType> &types,\n                     std::string side) {\n  using namespace std;\n  prompts.push_back(string(\"Insert points along the squamous suture [patient \")\n                    + side + \"]\");\n  types.push_back(DARKNESS);\n  types.push_back(CURVATURE);\n  prompts.push_back(string(\"Insert points from the squamous x lambdoid sutures \"\n                           \"to the tip of the mastoid process [patient \")\n                    + side + \"]\");\n  types.push_back(CURVATURE);\n  prompts.push_back(string(\"Insert points from the tip of the mastoid process \"\n                           \"along the zygomatic bone to the top of the skull \"\n                           \"[patient \")\n                    + side + \"]\");\n}\n\nvoid buildChoiceTop(std::vector<std::string> &prompts,\n                    std::vector<SelectionType> &types) {\n  using namespace std;\n\n  prompts.push_back(\"Insert points along the coronal suture, \"\n                    \"starting at the sphenoid bone on one side, \"\n                    \"and ending at the sphenoid bone on the other side.\");\n  types.push_back(DARKNESS);\n  prompts.push_back(\"Insert points along the sagittal suture.\");\n  types.push_back(DARKNESS);\n  prompts.push_back(\"Insert points along the lambdoid suture\");\n  types.push_back(DARKNESS);\n}\n\nvoid buildChoiceFront(std::vector<std::string> &prompts,\n                      std::vector<SelectionType> &types) {\n  prompts.push_back(\"Insert points along the chin, starting at the jaw attachment \"\n                    \"point on one side, ending on the other side\");\n  types.push_back(CURVATURE);\n  prompts.push_back(\"Insert points along the outside of the left eye\");\n  types.push_back(CURVATURE);\n  prompts.push_back(\"Insert points along the outside of the right eye\");\n  types.push_back(CURVATURE);\n  prompts.push_back(\"Insert points along the outside of the nose\");\n  types.push_back(CURVATURE);\n}\n\nvoid buildChoices(std::vector<std::string> &prompts,\n                  std::vector<SelectionType> &types) {\n  buildChoiceTop(prompts, types);\n  buildChoiceSide(prompts, types, \"left\");\n  buildChoiceSide(prompts, types, \"right\");\n  buildChoiceFront(prompts, types);\n}\n\nvoid printChoice(int ptnum, const std::vector<std::string> &prompts) {\n  if (ptnum >= prompts.size()) {\n    printf(\"Press 'w' to write points to an output file\\n\");\n  } else {\n    std::string msg = prettyprint(prompts[ptnum], 74, 8);\n    printf(\"%2d/%2d -- %s\\n\", ptnum + 1, prompts.size(), msg.c_str());\n  }\n}\n\n// Select all points between a and b, given mesh V,F with edge weights defined by w.\n// Will output indices to new_points.\nvoid selectPointsBetween(int a, int b,\n                         const Eigen::MatrixXd &V, const Eigen::MatrixXi &F,\n                         const std::vector<std::vector<int> > &VV,\n                         const std::vector<std::vector<double> > &w,\n                         std::vector<int> &new_points) {\n  // Call the Dijkstra's code.\n  Eigen::VectorXd min_distance;\n  Eigen::VectorXi previous;\n  std::set<int> targets;\n  targets.insert(b);\n  int vertex_found = \n      from_igl::dijkstra_compute_paths(a, targets, VV, w, min_distance,previous);\n      //igl::dijkstra_compute_paths(a, targets, VV, min_distance,previous);\n  if (vertex_found == -1) {\n    // ERROR\n    printf(\"ERROR: No path found!!\\n\");\n  } else {\n    igl::dijkstra_get_shortest_path_to(vertex_found, previous, new_points);\n  }\n}\n\nvoid getMeanCurvature(const Eigen::MatrixXd &V, const Eigen::MatrixXi &F,\n                      Eigen::VectorXd &VCs) {\n  Eigen::MatrixXd PD1,PD2;\n  Eigen::VectorXd PV1,PV2;\n  //igl::principal_curvature(V,F,PD1,PD2,PV1,PV2, 5);\n  igl::principal_curvature(V,F,PD1,PD2,PV1,PV2, 8);\n  //mean_curve = 0.5 * (PV1 + PV2);\n  VCs = PV1.cwiseProduct(PV1) + PV2.cwiseProduct(PV2);\n  VCs = VCs.cwiseMin(0.1);\n  VCs /= VCs.maxCoeff();\n\n  Eigen::VectorXd ones = Eigen::VectorXd::Constant(VCs.rows(), 1, 1);\n  VCs = ones - VCs;\n\n\n  /*\n  // Get the laplacian\n  Eigen::SparseMatrix<double> L,M,Minv;\n  //   from the cotangent matrix\n  igl::cotmatrix(V,F, L);\n  //   and the mass matrix\n  igl::massmatrix(V,F, igl::MASSMATRIX_TYPE_VORONOI, M);\n  igl::invert_diag(M, Minv);\n\n  Eigen::MatrixXd HN = -Minv*(L * V);\n  // Mean curviture is this value.\n  Eigen::VectorXd VC = HN.rowwise().norm();\n\n  // Smooth this out a bit.\n  igl::per_vertex_attribute_smoothing(VC,F, VCs);\n  // Cutoff at 1 (to avoid overpowering by high curvature)\n  VCs = VCs.cwiseMin(1.0);\n\n  // Normalize\n  VCs /= VCs.maxCoeff();\n  // Invert so high curvature has low weight.\n  Eigen::VectorXd ones = Eigen::VectorXd::Constant(VCs.rows(), 1, 1);\n  // Sqrt before switching\n  VCs = VCs.cwiseSqrt();\n  VCs = ones - VCs;\n  //std::cout << VCs;\n  */\n  \n}\n\nvoid printHelp(int ptnum) {\n  printf(\"Press 'u' to undo previous selection\\n\");\n  printf(\"Press '[' or ']' to adjust scene lighting\\n\");\n  printf(\"Press 'c' to show colors for curvature\\n\");\n  printf(\"Press 'd' to switch back to current selected points\\n\");\n  printf(\"Press ' ' (space) to complete the current task\\n\");\n  printf(\"Press '?' to repeat this message (and the requested user input).\\n\");\n}\n\nint main(int argc, char* argv[]) {\n  if (argc < 3) {\n    fprintf(stderr, \"Used for selecting points on the surface of a mesh. Will write the\\n\"\n                    \"corresponding vertices to output.off\\n\");\n    fprintf(stderr, \"usage: %s <input.off> <output.off> [decimate perc]\\n\",\n            argv[0]);\n    return -1;\n  }\n\n  Eigen::MatrixXd V,V2;\n  Eigen::MatrixXi F,F2;\n  igl::embree::EmbreeIntersector ei;\n\n  printf(\"Reading in mesh...\\n\");\n  // Read in the input file.\n  igl::readOFF(argv[1], V, F);\n  \n  if (argc == 4) {\n    float dec_perc = atof(argv[3]);\n    int new_faces = dec_perc * F.rows();\n    printf(\"Decimating by %f to %d faces...\\n\", dec_perc, new_faces);\n    // First things first: decimate the mesh\n    Eigen::VectorXi J;\n    igl::decimate(V,F, new_faces, V2,F2,J);\n    printf(\"Decimated from V:%d,F:%d to V:%d,F:%d\\n\",\n           V.rows(), F.rows(), V2.rows(), F2.rows());\n    V = V2; F = F2;\n  }\n\n  // Colors are all white to start.\n  Eigen::MatrixXd VC = Eigen::MatrixXd::Constant(V.rows(),3,1);\n  // Initialize this thing so we can get the vertices.\n  ei.init(V.cast<float>(), F);\n\n  // Ambient occlusion\n  Eigen::VectorXd AO;\n  Eigen::MatrixXd N;\n  igl::per_vertex_normals(V,F,N);\n  // Compute ambient occlusion factor using embree\n  printf(\"Building AABB tree...\\n\");\n  igl::AABB<Eigen::MatrixXd, 3> aabb;\n  aabb.init(V, F);\n  const auto & shoot_ray = [&aabb,&V,&F](\n      const Eigen::Vector3f& _s,\n      const Eigen::Vector3f& dir)->bool\n  {\n    Eigen::Vector3f s = _s+1e-4*dir;\n    igl::Hit hit;\n    if (aabb.intersect_ray(V,F, s.cast<double>().eval(),dir.cast<double>().eval(), hit)) {\n      return hit.t < mOCC_MAX_RAY_DIST;\n    } \n    return false;\n  };\n\n  printf(\"Now setting ambient occlusion vertices to improve contrast (patience)...\\n\");\n  //igl::embree::ambient_occlusion(V,F,V,N,300,AO);\n  igl::ambient_occlusion(shoot_ray, V,N, mOCC_NUM_RAYS,AO);\n  AO = 1.0 - AO.array();\n  for (int i = 0; i < V.rows(); ++i) {\n    VC.row(i) *= AO(i);\n  }\n  \n  printf(\"Constructing adjacency list...\\n\");\n  // Need the adjacency list\n  std::vector<std::vector<int> > VV;\n  igl::adjacency_list(F, VV);\n\n  std::vector<std::vector<double> > darkWeight;\n  darkWeight.resize(VV.size());\n  //std::vector<std::vector<double> > curveWeight;\n  //curveWeight.resize(VV.size());\n  for (int i = 0; i < VV.size(); ++i) {\n    for (int j = 0; j < VV[i].size(); ++j) {\n      // Just use the value of the ambient occlusion.\n      darkWeight[i].push_back(AO(VV[i][j]));\n      //curveWeight[i].push_back(1.0 - AO(VV[i][j]));\n    }\n  }\n\n  // Also caluculate the curvature values.\n  printf(\"Calculating mean curvature...\\n\");\n  Eigen::VectorXd mean_curve;\n  getMeanCurvature(V,F, mean_curve);\n  std::vector<std::vector<double> > curveWeight;\n  curveWeight.resize(VV.size());\n  double maxCurve = 0;\n  double minCurve = 0;\n  for (int i = 0; i < VV.size(); ++i) {\n    for (int j = 0; j < VV[i].size(); ++j) {\n      // Difference in gausssian curvature\n      //double diff = std::abs(VCs(i) - VCs(j));\n      double diff = mean_curve(VV[i][j]);\n      curveWeight[i].push_back(diff);\n      maxCurve = std::max(diff, maxCurve);\n      minCurve = std::min(diff, minCurve);\n    }\n  }\n\n  // Create the colors for mean curviture to use\n  Eigen::MatrixXd curve_colors;\n  igl::jet(mean_curve, true, curve_colors);\n  \n\n  // Prompts and types\n  std::vector<std::string> prompts;\n  std::vector<SelectionType> types;\n  buildChoices(prompts, types);\n\n  int point_num = 0;\n  std::vector<int> all_points;  // will contain all points, once the entire mesh has been selected.\n\n  std::vector<int> selected_points;\n  std::vector<int> additional_points;\n\n  igl::viewer::Viewer viewer;\n  viewer.callback_key_down = [&](igl::viewer::Viewer& viewer, unsigned char key, int modifier)->bool {\n    printf(\"key: '%c' modifier: '%d'\\n\", key, modifier);\n    switch(key) {\n      case ']':\n        viewer.core.lighting_factor += 0.1;\n        printf(\"Turning lighting up to %f\\n\", viewer.core.lighting_factor);\n        break;\n      case '[':\n        viewer.core.lighting_factor -= 0.1;\n        printf(\"Turning lighting down to %f\\n\", viewer.core.lighting_factor);\n        break;\n      case 'U':\n      {\n        printf(\"Undoing last point...\\n\");\n        // Undo the last choice\n        int last = selected_points.back();\n        printf(\"Undoing last choice... %d\\n\", last);\n        selected_points.pop_back();\n        VC.row(last) << 1,1,1;\n        VC.row(last) *= AO(last);\n        // Also remove points from additional_points\n        int this_p = -1;\n        while ( this_p != last && additional_points.size() > 0 ) {\n          // Get the last point.\n          this_p = additional_points.back();\n          // Set the color\n          VC.row(this_p) << 1,1,1;\n          VC.row(this_p) *= AO(this_p);\n          // Remove the point.\n          additional_points.pop_back();\n        }\n        \n        // Need to add in any colors we might have removed\n        for (int i : additional_points) {\n          VC.row(i) << 1,0,0;\n        }\n        for (int i : selected_points) {\n          VC.row(i) << 1,0,0;\n        }\n\n        // Set the colors back to what they were.\n        viewer.data.set_colors(VC);\n        printChoice(point_num, prompts);\n        break;\n      }\n      case ' ':\n      {\n        printf(\"Finished with current curve...Moving on to next\\n\");\n        // Add all the points to all_points\n        all_points.insert(all_points.end(), \n                          additional_points.begin(),\n                          additional_points.end());\n        additional_points.clear();\n        selected_points.clear();\n\n        point_num++;\n        printChoice(point_num, prompts);\n        break;\n      }\n      case 'C':\n        printf(\"Setting curvature colors...\\n\");\n        viewer.data.set_colors(curve_colors);\n        break;\n      case 'D':\n        printf(\"Setting colors to highlight darkness...\\n\");\n        viewer.data.set_colors(VC);\n        break;\n      case 'W':\n      {\n        printf(\"Writing output to %s\\n\", argv[2]);\n        // Write to output file\n        FILE* ofs = fopen(argv[2], \"w\");\n        fprintf(ofs, \"OFF\\n\");\n        fprintf(ofs, \"%d 0 0\\n\", all_points.size());\n        for (int idx : all_points) {\n          fprintf(ofs, \"%f %f %f\\n\", V(idx, 0), V(idx, 1), V(idx, 2));\n        }\n        fclose(ofs);\n        // You can quit now.\n        printf(\"Finished! Please close the program.\\n\");\n        break;\n      }\n      default:\n        // Question mark ('?')\n        if (key == '/' && modifier == GLFW_MOD_SHIFT) {\n          printHelp(selected_points.size());\n          printChoice(point_num, prompts);\n        }\n    }\n\n    // Make sure this stays the same.\n    viewer.core.lighting_factor = \n        std::min(std::max(viewer.core.lighting_factor,0.f),1.f);\n    return false;\n  };\n  viewer.callback_mouse_down = \n      [&](igl::viewer::Viewer &viewer, int, int)->bool\n      {\n        // fid will be the face ID. Need to get the vertex ID\n        int fid, vid;\n        // Cast a ray in the view direction starting from the mouse position\n        double x = viewer.current_mouse_x;\n        double y = viewer.core.viewport(3) - viewer.current_mouse_y;\n        if(igl::embree::unproject_onto_mesh(Eigen::Vector2f(x,y), F, \n                                            viewer.core.view * viewer.core.model,\n                                            viewer.core.proj,\n                                            viewer.core.viewport,\n                                            ei,\n                                            fid, vid)) {\n\n          selected_points.push_back(vid);\n          VC.row(vid) << 1,0,0;\n\n          // Update all the colors\n          //Eigen::MatrixXd vcol;\n          //igl::jet(VC, false, vcol);\n          if (selected_points.size() > 1) {\n            std::vector<int> path;\n            if (types[point_num] == DARKNESS) {\n              printf(\"Using light shading...\\n\");\n              selectPointsBetween(selected_points[selected_points.size() - 2],\n                                  selected_points[selected_points.size() - 1],\n                                  V,F, VV, darkWeight,\n                                  path);\n            } else {\n              printf(\"Using curvature...\\n\");\n              selectPointsBetween(selected_points[selected_points.size() - 2],\n                                  selected_points[selected_points.size() - 1],\n                                  V,F, VV, curveWeight,\n                                  path);\n            }\n            printf(\"Setting colors of %d...\\n\", path.size());\n            for (int i = 0; i < path.size(); ++i) {\n              VC.row(path[i]) << 1,0,0;\n            }\n            additional_points.insert(additional_points.end(), path.begin(), path.end());\n          }\n          \n          viewer.data.set_colors(VC);\n\n\n          return true;\n        }\n        return false;\n      };\n\n  printHelp(0);\n  viewer.data.set_mesh(V, F);\n  viewer.data.set_colors(curve_colors);\n  viewer.core.show_lines = false;\n  viewer.launch();\n}\n\n", "meta": {"hexsha": "5826437904ae0ab6afc30651e20278ba6ad32293", "size": 16091, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cgal_mesh_generation/point_selector.cpp", "max_stars_repo_name": "chipbuster/skull-atlas", "max_stars_repo_head_hexsha": "7f3ee009e1d5f65f101fe853a2cf6e12662970ee", "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": "cgal_mesh_generation/point_selector.cpp", "max_issues_repo_name": "chipbuster/skull-atlas", "max_issues_repo_head_hexsha": "7f3ee009e1d5f65f101fe853a2cf6e12662970ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cgal_mesh_generation/point_selector.cpp", "max_forks_repo_name": "chipbuster/skull-atlas", "max_forks_repo_head_hexsha": "7f3ee009e1d5f65f101fe853a2cf6e12662970ee", "max_forks_repo_licenses": ["BSD-3-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.1090534979, "max_line_length": 102, "alphanum_fraction": 0.5949909888, "num_tokens": 4239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2597606609760465}}
{"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 EIGEN_UTILS_H\n#define EIGEN_UTILS_H\n\n#include \"compare.hpp\"\n#include <Eigen/Core>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <limits>\n\nnamespace flexiblesusy {\n\ntemplate <typename Derived>\nunsigned closest_index(double mass, const Eigen::ArrayBase<Derived>& v)\n{\n   unsigned pos;\n   typename Derived::PlainObject tmp;\n   tmp.setConstant(mass);\n\n   (v - tmp).abs().minCoeff(&pos);\n\n   return pos;\n}\n\n/**\n * Divides a by b element wise.  If the quotient is not finite, it is\n * set to zero.\n *\n * @param a numerator\n * @param b denominator\n */\ntemplate <typename Scalar, int M, int N>\nEigen::Matrix<Scalar,M,N> div_save(\n   const Eigen::Matrix<Scalar,M,N>& a, const Eigen::Matrix<Scalar,M,N>& b)\n{\n   Eigen::Matrix<Scalar,M,N> result(Eigen::Matrix<Scalar,M,N>::Zero());\n\n   for (int i = 0; i < M; i++) {\n      for (int k = 0; k < N; k++) {\n         const double quotient = a(i,k) / b(i,k);\n         if (std::isfinite(quotient))\n            result(i,k) = quotient;\n      }\n   }\n\n   return result;\n}\n\ntemplate <class BinaryOp, class Derived>\nDerived binary_map(\n   const Eigen::ArrayBase<Derived>& a, const Eigen::ArrayBase<Derived>& b, BinaryOp op)\n{\n   typename Derived::PlainObject result(a.rows(), b.cols());\n\n   assert(a.rows() == b.rows());\n   assert(a.cols() == b.cols());\n\n   for (int i = 0; i < a.rows(); i++)\n      for (int k = 0; k < a.cols(); k++)\n         result(i,k) = op(a(i,k), b(i,k));\n\n   return result;\n}\n\n/**\n * The element of v, which is closest to mass, is moved to the\n * position idx.\n *\n * @param idx new index of the mass eigenvalue\n * @param mass mass to compare against\n * @param v vector of masses\n * @param z corresponding mixing matrix\n */\ntemplate <typename DerivedArray, typename DerivedMatrix>\nvoid move_goldstone_to(int idx, double mass, Eigen::ArrayBase<DerivedArray>& v,\n                       Eigen::MatrixBase<DerivedMatrix>& z)\n{\n   int pos = closest_index(mass, v);\n   if (pos == idx)\n      return;\n\n   const int sign = (idx - pos) < 0 ? -1 : 1;\n   int steps = std::abs(idx - pos);\n\n   // now we shuffle the states\n   while (steps--) {\n      const int new_pos = pos + sign;\n      v.row(new_pos).swap(v.row(pos));\n      z.row(new_pos).swap(z.row(pos));\n      pos = new_pos;\n   }\n}\n\n/**\n * Copies all elements from src to dst which are not close to the\n * elements in cmp.\n *\n * @param src source vector\n * @param cmp vector with elements to compare against\n * @param dst destination vector\n */\ntemplate<class Real, int Nsrc, int Ncmp, int Ndst>\nvoid remove_if_equal(const Eigen::Array<Real,Nsrc,1>& src,\n                     const Eigen::Array<Real,Ncmp,1>& cmp,\n                     Eigen::Array<Real,Ndst,1>& dst)\n{\n   static_assert(Nsrc == Ncmp + Ndst,\n                 \"Error: remove_if_equal: vectors have incompatible length!\");\n\n   Eigen::Array<Real,Nsrc,1> non_equal(src);\n\n   for (int i = 0; i < Ncmp; i++) {\n      const int idx = closest_index(cmp(i), non_equal);\n      non_equal(idx) = std::numeric_limits<double>::infinity();\n   }\n\n   std::remove_copy_if(non_equal.data(), non_equal.data() + Nsrc,\n                       dst.data(), Is_not_finite<Real>());\n}\n\n/**\n * @brief reorders vector v according to ordering in vector v2\n * @param v vector with elementes to be reordered\n * @param v2 vector with reference ordering\n */\ntemplate<class Real, int N>\nvoid reorder_vector(\n   Eigen::Array<Real,N,1>& v,\n   const Eigen::Array<Real,N,1>& v2)\n{\n   Eigen::PermutationMatrix<N> p;\n   p.setIdentity();\n   std::sort(p.indices().data(), p.indices().data() + p.indices().size(),\n             CompareAbs<Real, N>(v2));\n\n#if EIGEN_VERSION_AT_LEAST(3,1,4)\n   v.matrix().transpose() *= p.inverse();\n#else\n   Eigen::Map<Eigen::Matrix<Real,N,1> >(v.data()).transpose() *= p.inverse();\n#endif\n}\n\n/**\n * @brief reorders vector v according to ordering of diagonal elements in mass_matrix\n * @param v vector with elementes to be reordered\n * @param matrix matrix with diagonal elements with reference ordering\n */\ntemplate<class Derived>\nvoid reorder_vector(\n   Eigen::Array<double,Eigen::MatrixBase<Derived>::RowsAtCompileTime,1>& v,\n   const Eigen::MatrixBase<Derived>& matrix)\n{\n   reorder_vector(v, matrix.diagonal().array().eval());\n}\n\ntemplate<class Derived>\nstd::string print_scientific(const Eigen::DenseBase<Derived>& v,\n                             unsigned number_of_digits = std::numeric_limits<typename Derived::Scalar>::digits10 + 1)\n{\n   std::ostringstream sstr;\n\n   for (std::size_t i = 0; i < v.rows(); i++) {\n      for (std::size_t k = 0; k < v.cols(); k++) {\n         sstr << std::setprecision(number_of_digits)\n              << std::scientific << v(i,k) << ' ';\n      }\n      sstr << '\\n';\n   }\n\n   return sstr.str();\n}\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "0641c2120e966d4b25587e236f617c74edd35c58", "size": 5572, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/src/eigen_utils.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/src/eigen_utils.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/src/eigen_utils.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": 28.7216494845, "max_line_length": 117, "alphanum_fraction": 0.6288585786, "num_tokens": 1417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521307073646, "lm_q2_score": 0.5, "lm_q1q2_score": 0.259760653536823}}
{"text": "#ifndef SPIRIT_USE_CUDA\n\n#include <engine/Hamiltonian_Heisenberg.hpp>\n#include <engine/Vectormath.hpp>\n#include <engine/Neighbours.hpp>\n#include <data/Spin_System.hpp>\n#include <utility/Constants.hpp>\n\n#include <Eigen/Dense>\n\nusing namespace Data;\nusing namespace Utility;\nusing Utility::Constants::mu_B;\nusing Utility::Constants::mu_0;\nusing Utility::Constants::Pi;\nusing Engine::Vectormath::check_atom_type;\nusing Engine::Vectormath::idx_from_pair;\n\nnamespace Engine\n{\n    // Construct a Heisenberg Hamiltonian with pairs\n    Hamiltonian_Heisenberg::Hamiltonian_Heisenberg(\n        scalarfield mu_s,\n        scalar external_field_magnitude, Vector3 external_field_normal,\n        intfield anisotropy_indices, scalarfield anisotropy_magnitudes, vectorfield anisotropy_normals,\n        pairfield exchange_pairs, scalarfield exchange_magnitudes,\n        pairfield dmi_pairs, scalarfield dmi_magnitudes, vectorfield dmi_normals,\n        scalar ddi_radius,\n        quadrupletfield quadruplets, scalarfield quadruplet_magnitudes,\n        std::shared_ptr<Data::Geometry> geometry,\n        intfield boundary_conditions\n    ) :\n        Hamiltonian(boundary_conditions),\n        geometry(geometry),\n        mu_s(mu_s),\n        external_field_magnitude(external_field_magnitude * mu_B), external_field_normal(external_field_normal),\n        anisotropy_indices(anisotropy_indices), anisotropy_magnitudes(anisotropy_magnitudes), anisotropy_normals(anisotropy_normals),\n        exchange_pairs_in(exchange_pairs), exchange_magnitudes_in(exchange_magnitudes), exchange_shell_magnitudes(0),\n        dmi_pairs_in(dmi_pairs), dmi_magnitudes_in(dmi_magnitudes), dmi_normals_in(dmi_normals), dmi_shell_magnitudes(0), dmi_shell_chirality(0),\n        quadruplets(quadruplets), quadruplet_magnitudes(quadruplet_magnitudes),\n        ddi_cutoff_radius(ddi_radius)\n    {\n        // Generate interaction pairs, constants etc.\n        this->Update_Interactions();\n    }\n\n    // Construct a Heisenberg Hamiltonian from shells\n    Hamiltonian_Heisenberg::Hamiltonian_Heisenberg(\n        scalarfield mu_s,\n        scalar external_field_magnitude, Vector3 external_field_normal,\n        intfield anisotropy_indices, scalarfield anisotropy_magnitudes, vectorfield anisotropy_normals,\n        scalarfield exchange_shell_magnitudes,\n        scalarfield dmi_shell_magnitudes, int dm_chirality,\n        scalar ddi_radius,\n        quadrupletfield quadruplets, scalarfield quadruplet_magnitudes,\n        std::shared_ptr<Data::Geometry> geometry,\n        intfield boundary_conditions\n    ) :\n        Hamiltonian(boundary_conditions),\n        geometry(geometry),\n        mu_s(mu_s),\n        external_field_magnitude(external_field_magnitude * mu_B), external_field_normal(external_field_normal),\n        anisotropy_indices(anisotropy_indices), anisotropy_magnitudes(anisotropy_magnitudes), anisotropy_normals(anisotropy_normals),\n        exchange_pairs_in(0), exchange_magnitudes_in(0), exchange_shell_magnitudes(exchange_shell_magnitudes),\n        dmi_pairs_in(0), dmi_magnitudes_in(0), dmi_normals_in(0), dmi_shell_magnitudes(dmi_shell_magnitudes), dmi_shell_chirality(dm_chirality),\n        quadruplets(quadruplets), quadruplet_magnitudes(quadruplet_magnitudes),\n        ddi_cutoff_radius(ddi_radius)\n    {\n        // Generate interaction pairs, constants etc.\n        this->Update_Interactions();\n    }\n\n    void Hamiltonian_Heisenberg::Update_Interactions()\n    {\n        #if defined(SPIRIT_USE_OPENMP)\n        // When parallelising (cuda or openmp), we need all neighbours per spin\n        const bool use_redundant_neighbours = true;\n        #else\n        // When running on a single thread, we can ignore redundant neighbours\n        const bool use_redundant_neighbours = false;\n        #endif\n\n        // Exchange\n        this->exchange_pairs      = pairfield(0);\n        this->exchange_magnitudes = scalarfield(0);\n        if( exchange_shell_magnitudes.size() > 0 )\n        {\n            // Generate Exchange neighbours\n            intfield exchange_shells(0);\n            Neighbours::Get_Neighbours_in_Shells(*geometry, exchange_shell_magnitudes.size(), exchange_pairs, exchange_shells, use_redundant_neighbours);\n            for (unsigned int ipair = 0; ipair < exchange_pairs.size(); ++ipair)\n            {\n                this->exchange_magnitudes.push_back(exchange_shell_magnitudes[exchange_shells[ipair]]);\n            }\n        }\n        else\n        {\n            // Use direct list of pairs\n            this->exchange_pairs      = this->exchange_pairs_in;\n            this->exchange_magnitudes = this->exchange_magnitudes_in;\n            if( use_redundant_neighbours )\n            {\n                for (int i = 0; i < exchange_pairs_in.size(); ++i)\n                {\n                    auto& p = exchange_pairs_in[i];\n                    auto& t = p.translations;\n                    this->exchange_pairs.push_back(Pair{p.j, p.i, {-t[0], -t[1], -t[2]}});\n                    this->exchange_magnitudes.push_back(exchange_magnitudes_in[i]);\n                }\n            }\n        }\n\n        // DMI\n        this->dmi_pairs      = pairfield(0);\n        this->dmi_magnitudes = scalarfield(0);\n        this->dmi_normals    = vectorfield(0);\n        if( dmi_shell_magnitudes.size() > 0 )\n        {\n            // Generate DMI neighbours and normals\n            intfield dmi_shells(0);\n            Neighbours::Get_Neighbours_in_Shells(*geometry, dmi_shell_magnitudes.size(), dmi_pairs, dmi_shells, use_redundant_neighbours);\n            for (unsigned int ineigh = 0; ineigh < dmi_pairs.size(); ++ineigh)\n            {\n                this->dmi_normals.push_back(Neighbours::DMI_Normal_from_Pair(*geometry, dmi_pairs[ineigh], this->dmi_shell_chirality));\n                this->dmi_magnitudes.push_back(dmi_shell_magnitudes[dmi_shells[ineigh]]);\n            }\n        }\n        else\n        {\n            // Use direct list of pairs\n            this->dmi_pairs      = this->dmi_pairs_in;\n            this->dmi_magnitudes = this->dmi_magnitudes_in;\n            this->dmi_normals    = this->dmi_normals_in;\n            if( use_redundant_neighbours )\n            {\n                for (int i = 0; i < dmi_pairs_in.size(); ++i)\n                {\n                    auto& p = dmi_pairs_in[i];\n                    auto& t = p.translations;\n                    this->dmi_pairs.push_back(Pair{p.j, p.i, {-t[0], -t[1], -t[2]}});\n                    this->dmi_magnitudes.push_back(dmi_magnitudes_in[i]);\n                    this->dmi_normals.push_back(-dmi_normals_in[i]);\n                }\n            }\n        }\n\n        // Dipole-dipole\n        this->ddi_pairs      = Engine::Neighbours::Get_Pairs_in_Radius(*this->geometry, this->ddi_cutoff_radius);\n        this->ddi_magnitudes = scalarfield(this->ddi_pairs.size());\n        this->ddi_normals    = vectorfield(this->ddi_pairs.size());\n\n        scalar magnitude;\n        Vector3 normal;\n\n        for (unsigned int i = 0; i < this->ddi_pairs.size(); ++i)\n        {\n            Engine::Neighbours::DDI_from_Pair(\n                *this->geometry,\n                { this->ddi_pairs[i].i, this->ddi_pairs[i].j, this->ddi_pairs[i].translations },\n                this->ddi_magnitudes[i], this->ddi_normals[i]);\n        }\n\n        // Update, which terms still contribute\n        this->Update_Energy_Contributions();\n    }\n\n    void Hamiltonian_Heisenberg::Update_Energy_Contributions()\n    {\n        this->energy_contributions_per_spin = std::vector<std::pair<std::string, scalarfield>>(0);\n\n        // External field\n        if (this->external_field_magnitude > 0)\n        {\n            this->energy_contributions_per_spin.push_back({\"Zeeman\", scalarfield(0)});\n            this->idx_zeeman = this->energy_contributions_per_spin.size()-1;\n        }\n        else this->idx_zeeman = -1;\n        // Anisotropy\n        if (this->anisotropy_indices.size() > 0)\n        {\n            this->energy_contributions_per_spin.push_back({\"Anisotropy\", scalarfield(0) });\n            this->idx_anisotropy = this->energy_contributions_per_spin.size()-1;\n        }\n        else this->idx_anisotropy = -1;\n        // Exchange\n        if (this->exchange_pairs.size() > 0)\n        {\n            this->energy_contributions_per_spin.push_back({\"Exchange\", scalarfield(0) });\n            this->idx_exchange = this->energy_contributions_per_spin.size()-1;\n        }\n        else this->idx_exchange = -1;\n        // DMI\n        if (this->dmi_pairs.size() > 0)\n        {\n            this->energy_contributions_per_spin.push_back({\"DMI\", scalarfield(0) });\n            this->idx_dmi = this->energy_contributions_per_spin.size()-1;\n        }\n        else this->idx_dmi = -1;\n        // Dipole-Dipole\n        if (this->ddi_pairs.size() > 0)\n        {\n            this->energy_contributions_per_spin.push_back({\"DD\", scalarfield(0) });\n            this->idx_ddi = this->energy_contributions_per_spin.size()-1;\n        }\n        else this->idx_ddi = -1;\n        // Quadruplets\n        if (this->quadruplets.size() > 0)\n        {\n            this->energy_contributions_per_spin.push_back({\"Quadruplets\", scalarfield(0) });\n            this->idx_quadruplet = this->energy_contributions_per_spin.size()-1;\n        }\n        else this->idx_quadruplet = -1;\n    }\n\n    void Hamiltonian_Heisenberg::Energy_Contributions_per_Spin(const vectorfield & spins, std::vector<std::pair<std::string, scalarfield>> & contributions)\n    {\n        if (contributions.size() != this->energy_contributions_per_spin.size())\n        {\n            contributions = this->energy_contributions_per_spin;\n        }\n        \n        int nos = spins.size();\n        for (auto& contrib : contributions)\n        {\n            // Allocate if not already allocated\n            if (contrib.second.size() != nos) contrib.second = scalarfield(nos, 0);\n            // Otherwise set to zero\n            else Vectormath::fill(contrib.second, 0);\n        }\n\n        // External field\n        if (this->idx_zeeman >=0 )     E_Zeeman(spins, contributions[idx_zeeman].second);\n\n        // Anisotropy\n        if (this->idx_anisotropy >=0 ) E_Anisotropy(spins, contributions[idx_anisotropy].second);\n\n        // Exchange\n        if (this->idx_exchange >=0 )   E_Exchange(spins, contributions[idx_exchange].second);\n        // DMI\n        if (this->idx_dmi >=0 )        E_DMI(spins,contributions[idx_dmi].second);\n        // DD\n        if (this->idx_ddi >=0 )        E_DDI(spins, contributions[idx_ddi].second);\n        // Quadruplets\n        if (this->idx_quadruplet >=0 ) E_Quadruplet(spins, contributions[idx_quadruplet].second);\n    }\n\n    void Hamiltonian_Heisenberg::E_Zeeman(const vectorfield & spins, scalarfield & Energy)\n    {\n        const int N = geometry->n_cell_atoms;\n\n        #pragma omp parallel for\n        for (int icell = 0; icell < geometry->n_cells_total; ++icell)\n        {\n            for (int ibasis = 0; ibasis < N; ++ibasis)\n            {\n                int ispin = icell*N + ibasis;\n                if (check_atom_type(this->geometry->atom_types[ispin]))\n                    Energy[ispin] -= this->mu_s[ibasis] * this->external_field_magnitude * this->external_field_normal.dot(spins[ispin]);\n            }\n        }\n    }\n\n    void Hamiltonian_Heisenberg::E_Anisotropy(const vectorfield & spins, scalarfield & Energy)\n    {\n        const int N = geometry->n_cell_atoms;\n\n        #pragma omp parallel for\n        for (int icell = 0; icell < geometry->n_cells_total; ++icell)\n        {\n            for (int iani = 0; iani < anisotropy_indices.size(); ++iani)\n            {\n                int ispin = icell*N + anisotropy_indices[iani];\n                if (check_atom_type(this->geometry->atom_types[ispin]))\n                    Energy[ispin] -= this->anisotropy_magnitudes[iani] * std::pow(anisotropy_normals[iani].dot(spins[ispin]), 2.0);\n            }\n        }\n    }\n\n    void Hamiltonian_Heisenberg::E_Exchange(const vectorfield & spins, scalarfield & Energy)\n    {\n        #pragma omp parallel for\n        for (unsigned int icell = 0; icell < geometry->n_cells_total; ++icell)\n        {\n            for (unsigned int i_pair = 0; i_pair < exchange_pairs.size(); ++i_pair)\n            {\n                int ispin = exchange_pairs[i_pair].i + icell*geometry->n_cell_atoms;\n                int jspin = idx_from_pair(ispin, boundary_conditions, geometry->n_cells, geometry->n_cell_atoms, geometry->atom_types, exchange_pairs[i_pair]);\n                if (jspin >= 0)\n                {\n                    Energy[ispin] -= 0.5 * exchange_magnitudes[i_pair] * spins[ispin].dot(spins[jspin]);\n                    #ifndef _OPENMP\n                    Energy[jspin] -= 0.5 * exchange_magnitudes[i_pair] * spins[ispin].dot(spins[jspin]);\n                    #endif\n                }\n            }\n        }\n    }\n\n    void Hamiltonian_Heisenberg::E_DMI(const vectorfield & spins, scalarfield & Energy)\n    {\n        #pragma omp parallel for\n        for (unsigned int icell = 0; icell < geometry->n_cells_total; ++icell)\n        {\n            for (unsigned int i_pair = 0; i_pair < dmi_pairs.size(); ++i_pair)\n            {\n                int ispin = dmi_pairs[i_pair].i + icell*geometry->n_cell_atoms;\n                int jspin = idx_from_pair(ispin, boundary_conditions, geometry->n_cells, geometry->n_cell_atoms, geometry->atom_types, dmi_pairs[i_pair]);\n                if (jspin >= 0)\n                {\n                    Energy[ispin] -= 0.5 * dmi_magnitudes[i_pair] * dmi_normals[i_pair].dot(spins[ispin].cross(spins[jspin]));\n                    #ifndef _OPENMP\n                    Energy[jspin] -= 0.5 * dmi_magnitudes[i_pair] * dmi_normals[i_pair].dot(spins[ispin].cross(spins[jspin]));\n                    #endif\n                }\n            }\n        }\n    }\n\n    void Hamiltonian_Heisenberg::E_DDI(const vectorfield & spins, scalarfield & Energy)\n    {\n        // The translations are in angstr�m, so the |r|[m] becomes |r|[m]*10^-10\n        const scalar mult = mu_0 * std::pow(mu_B, 2) / ( 4*Pi * 1e-30 );\n\n        scalar result = 0.0;\n\n        for (unsigned int i_pair = 0; i_pair < ddi_pairs.size(); ++i_pair)\n        {\n            if (ddi_magnitudes[i_pair] > 0.0)\n            {\n                for (int da = 0; da < geometry->n_cells[0]; ++da)\n                {\n                    for (int db = 0; db < geometry->n_cells[1]; ++db)\n                    {\n                        for (int dc = 0; dc < geometry->n_cells[2]; ++dc)\n                        {\n                            std::array<int, 3 > translations = { da, db, dc };\n                            int i = ddi_pairs[i_pair].i;\n                            int j = ddi_pairs[i_pair].j;\n                            int ispin = i + Vectormath::idx_from_translations(geometry->n_cells, geometry->n_cell_atoms, translations);\n                            int jspin = idx_from_pair(ispin, boundary_conditions, geometry->n_cells, geometry->n_cell_atoms, geometry->atom_types, ddi_pairs[i_pair]);\n                            if (jspin >= 0)\n                            {\n                                Energy[ispin] -= 0.5 * this->mu_s[i] * this->mu_s[j] * mult / std::pow(ddi_magnitudes[i_pair], 3.0) *\n                                    (3 * spins[ispin].dot(ddi_normals[i_pair]) * spins[ispin].dot(ddi_normals[i_pair]) - spins[ispin].dot(spins[ispin]));\n                                Energy[jspin] -= 0.5 * this->mu_s[i] * this->mu_s[j] * mult / std::pow(ddi_magnitudes[i_pair], 3.0) *\n                                    (3 * spins[ispin].dot(ddi_normals[i_pair]) * spins[ispin].dot(ddi_normals[i_pair]) - spins[ispin].dot(spins[ispin]));\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }// end DipoleDipole\n\n\n    void Hamiltonian_Heisenberg::E_Quadruplet(const vectorfield & spins, scalarfield & Energy)\n    {\n        for (unsigned int iquad = 0; iquad < quadruplets.size(); ++iquad)\n        {\n            for (int da = 0; da < geometry->n_cells[0]; ++da)\n            {\n                for (int db = 0; db < geometry->n_cells[1]; ++db)\n                {\n                    for (int dc = 0; dc < geometry->n_cells[2]; ++dc)\n                    {\n                        std::array<int, 3 > translations = { da, db, dc };\n                        int ispin = quadruplets[iquad].i + Vectormath::idx_from_translations(geometry->n_cells, geometry->n_cell_atoms, translations);\n                        int jspin = quadruplets[iquad].j + Vectormath::idx_from_translations(geometry->n_cells, geometry->n_cell_atoms, translations, quadruplets[iquad].d_j);\n                        int kspin = quadruplets[iquad].k + Vectormath::idx_from_translations(geometry->n_cells, geometry->n_cell_atoms, translations, quadruplets[iquad].d_k);\n                        int lspin = quadruplets[iquad].l + Vectormath::idx_from_translations(geometry->n_cells, geometry->n_cell_atoms, translations, quadruplets[iquad].d_l);\n                        \n                        if ( check_atom_type(this->geometry->atom_types[ispin]) && check_atom_type(this->geometry->atom_types[jspin]) &&\n                                check_atom_type(this->geometry->atom_types[kspin]) && check_atom_type(this->geometry->atom_types[lspin]) )\n                        {\n                            Energy[ispin] -= 0.25*quadruplet_magnitudes[iquad] * (spins[ispin].dot(spins[jspin])) * (spins[kspin].dot(spins[lspin]));\n                            Energy[jspin] -= 0.25*quadruplet_magnitudes[iquad] * (spins[ispin].dot(spins[jspin])) * (spins[kspin].dot(spins[lspin]));\n                            Energy[kspin] -= 0.25*quadruplet_magnitudes[iquad] * (spins[ispin].dot(spins[jspin])) * (spins[kspin].dot(spins[lspin]));\n                            Energy[lspin] -= 0.25*quadruplet_magnitudes[iquad] * (spins[ispin].dot(spins[jspin])) * (spins[kspin].dot(spins[lspin]));\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n\n    scalar Hamiltonian_Heisenberg::Energy_Single_Spin(int ispin_in, const vectorfield & spins)\n    {\n        int icell  = ispin_in / this->geometry->n_cell_atoms;\n        int ibasis = ispin_in - icell*this->geometry->n_cell_atoms;\n        scalar Energy = 0;\n\n        // External field\n        if (this->idx_zeeman >= 0)\n        {\n            if (check_atom_type(this->geometry->atom_types[ispin_in]))\n                Energy -= this->mu_s[ibasis] * this->external_field_magnitude * this->external_field_normal.dot(spins[ispin_in]);\n        }\n\n        // Anisotropy\n        if (this->idx_anisotropy >= 0)\n        {\n            for (int iani = 0; iani < anisotropy_indices.size(); ++iani)\n            {\n                if (anisotropy_indices[iani] == ibasis)\n                {\n                    if (check_atom_type(this->geometry->atom_types[ispin_in]))\n                        Energy -= this->anisotropy_magnitudes[iani] * std::pow(anisotropy_normals[iani].dot(spins[ispin_in]), 2.0);\n                }\n            }\n        }\n\n        // Exchange\n        if (this->idx_exchange >= 0)\n        {\n            for (unsigned int ipair = 0; ipair < exchange_pairs.size(); ++ipair)\n            {\n                if (exchange_pairs[ipair].i == ibasis)\n                {\n                    int ispin = exchange_pairs[ipair].i + icell*geometry->n_cell_atoms;\n                    int jspin = idx_from_pair(ispin, boundary_conditions, geometry->n_cells, geometry->n_cell_atoms, geometry->atom_types, exchange_pairs[ipair]);\n                    if (jspin >= 0)\n                    {\n                        Energy -= 0.5 * this->exchange_magnitudes[ipair] * spins[ispin].dot(spins[jspin]);\n                    }\n                    #ifndef _OPENMP\n                    jspin = idx_from_pair(ispin, boundary_conditions, geometry->n_cells, geometry->n_cell_atoms, geometry->atom_types, exchange_pairs[ipair], true);\n                    if (jspin >= 0)\n                    {\n                        Energy -= 0.5 * this->exchange_magnitudes[ipair] * spins[ispin].dot(spins[jspin]);\n                    }\n                    #endif\n                }\n            }\n        }\n\n        // DMI\n        if (this->idx_dmi >= 0)\n        {\n            for (unsigned int ipair = 0; ipair < dmi_pairs.size(); ++ipair)\n            {\n                if (dmi_pairs[ipair].i == ibasis)\n                {\n                    int ispin = dmi_pairs[ipair].i + icell*geometry->n_cell_atoms;\n                    int jspin = idx_from_pair(ispin, boundary_conditions, geometry->n_cells, geometry->n_cell_atoms, geometry->atom_types, dmi_pairs[ipair]);\n                    if (jspin >= 0)\n                    {\n                        Energy -= 0.5 * this->dmi_magnitudes[ipair] * this->dmi_normals[ipair].dot(spins[ispin].cross(spins[jspin]));\n                    }\n                    #ifndef _OPENMP\n                    jspin = idx_from_pair(ispin, boundary_conditions, geometry->n_cells, geometry->n_cell_atoms, geometry->atom_types, dmi_pairs[ipair], true);\n                    if (jspin >= 0)\n                    {\n                        Energy += 0.5 * this->dmi_magnitudes[ipair] * this->dmi_normals[ipair].dot(spins[ispin].cross(spins[jspin]));\n                    }\n                    #endif\n                }\n            }\n        }\n\n        // DDI\n        if (this->idx_ddi >= 0)\n        {\n            for (unsigned int ipair = 0; ipair < ddi_pairs.size(); ++ipair)\n            {\n                if (ddi_pairs[ipair].i == ibasis)\n                {\n                    // The translations are in angstr�m, so the |r|[m] becomes |r|[m]*10^-10\n                    const scalar mult = 0.5 * this->mu_s[ddi_pairs[ipair].i] * this->mu_s[ddi_pairs[ipair].j]\n                        * Utility::Constants::mu_0 * std::pow(Utility::Constants::mu_B, 2) / ( 4*Utility::Constants::Pi * 1e-30 );\n\n                    int ispin = ddi_pairs[ipair].i + icell*geometry->n_cell_atoms;\n                    int jspin = idx_from_pair(ispin, boundary_conditions, geometry->n_cells, geometry->n_cell_atoms, geometry->atom_types, ddi_pairs[ipair]);\n\n                    if (jspin >= 0)\n                    {\n                        Energy -= mult / std::pow(this->ddi_magnitudes[ipair], 3.0) *\n                            (3 * spins[ispin].dot(this->ddi_normals[ipair]) * spins[ispin].dot(this->ddi_normals[ipair]) - spins[ispin].dot(spins[ispin]));\n\n                    }\n                    #ifndef _OPENMP\n                    jspin = idx_from_pair(ispin, boundary_conditions, geometry->n_cells, geometry->n_cell_atoms, geometry->atom_types, dmi_pairs[ipair], true);\n                    if (jspin >= 0)\n                    {\n                        Energy += mult / std::pow(this->ddi_magnitudes[ipair], 3.0) *\n                            (3 * spins[ispin].dot(this->ddi_normals[ipair]) * spins[ispin].dot(this->ddi_normals[ipair]) - spins[ispin].dot(spins[ispin]));\n                    }\n                    #endif\n                }\n            }\n        }\n\n        // Quadruplets\n        if (this->idx_quadruplet >= 0) \n        {\n            for (unsigned int iquad = 0; iquad < quadruplets.size(); ++iquad)\n            {\n                auto translations = Vectormath::translations_from_idx(geometry->n_cells, geometry->n_cell_atoms, icell);\n                int ispin = quadruplets[iquad].i + icell*geometry->n_cell_atoms;\n                int jspin = quadruplets[iquad].j + Vectormath::idx_from_translations(geometry->n_cells, geometry->n_cell_atoms, translations, quadruplets[iquad].d_j);\n                int kspin = quadruplets[iquad].k + Vectormath::idx_from_translations(geometry->n_cells, geometry->n_cell_atoms, translations, quadruplets[iquad].d_k);\n                int lspin = quadruplets[iquad].l + Vectormath::idx_from_translations(geometry->n_cells, geometry->n_cell_atoms, translations, quadruplets[iquad].d_l);\n                \n                if ( check_atom_type(this->geometry->atom_types[ispin]) && check_atom_type(this->geometry->atom_types[jspin]) &&\n                     check_atom_type(this->geometry->atom_types[kspin]) && check_atom_type(this->geometry->atom_types[lspin]) )\n                {\n                    Energy -= 0.25*quadruplet_magnitudes[iquad] * (spins[ispin].dot(spins[jspin])) * (spins[kspin].dot(spins[lspin]));\n                }\n\n                #ifndef _OPENMP\n                // TODO: mirrored quadruplet when unique quadruplets are used\n                // jspin = quadruplets[iquad].j + Vectormath::idx_from_translations(geometry->n_cells, geometry->n_cell_atoms, translations, quadruplets[iquad].d_j, true);\n                // kspin = quadruplets[iquad].k + Vectormath::idx_from_translations(geometry->n_cells, geometry->n_cell_atoms, translations, quadruplets[iquad].d_k, true);\n                // lspin = quadruplets[iquad].l + Vectormath::idx_from_translations(geometry->n_cells, geometry->n_cell_atoms, translations, quadruplets[iquad].d_l, true);\n                \n                // if ( check_atom_type(this->geometry->atom_types[ispin]) && check_atom_type(this->geometry->atom_types[jspin]) &&\n                //      check_atom_type(this->geometry->atom_types[kspin]) && check_atom_type(this->geometry->atom_types[lspin]) )\n                // {\n                //     Energy -= 0.25*quadruplet_magnitudes[iquad] * (spins[ispin].dot(spins[jspin])) * (spins[kspin].dot(spins[lspin]));\n                // }\n                #endif\n            }\n        }\n\n        return Energy;\n    }\n\n\n    void Hamiltonian_Heisenberg::Gradient(const vectorfield & spins, vectorfield & gradient)\n    {\n        // Set to zero\n        Vectormath::fill(gradient, {0,0,0});\n\n        // External field\n        Gradient_Zeeman(gradient);\n\n        // Anisotropy\n        Gradient_Anisotropy(spins, gradient);\n\n        // Exchange\n        this->Gradient_Exchange(spins, gradient);\n        // DMI\n        this->Gradient_DMI(spins, gradient);\n        // DD\n        this->Gradient_DDI(spins, gradient);\n\n        // Quadruplets\n        this->Gradient_Quadruplet(spins, gradient);\n    }\n\n    void Hamiltonian_Heisenberg::Gradient_Zeeman(vectorfield & gradient)\n    {\n        const int N = geometry->n_cell_atoms;\n\n        #pragma omp parallel for\n        for (int icell = 0; icell < geometry->n_cells_total; ++icell)\n        {\n            for (int ibasis = 0; ibasis < N; ++ibasis)\n            {\n                int ispin = icell*N + ibasis;\n                if (check_atom_type(this->geometry->atom_types[ispin]))\n                    gradient[ispin] -= this->mu_s[ibasis] * this->external_field_magnitude * this->external_field_normal;\n            }\n        }\n    }\n\n    void Hamiltonian_Heisenberg::Gradient_Anisotropy(const vectorfield & spins, vectorfield & gradient)\n    {\n        const int N = geometry->n_cell_atoms;\n\n        #pragma omp parallel for\n        for (int icell = 0; icell < geometry->n_cells_total; ++icell)\n        {\n            for (int iani = 0; iani < anisotropy_indices.size(); ++iani)\n            {\n                int ispin = icell*N + anisotropy_indices[iani];\n                if (check_atom_type(this->geometry->atom_types[ispin]))\n                    gradient[ispin] -= 2.0 * this->anisotropy_magnitudes[iani] * this->anisotropy_normals[iani] * anisotropy_normals[iani].dot(spins[ispin]);\n            }\n        }\n    }\n\n    void Hamiltonian_Heisenberg::Gradient_Exchange(const vectorfield & spins, vectorfield & gradient)\n    {\n        #pragma omp parallel for\n        for (int icell = 0; icell < geometry->n_cells_total; ++icell)\n        {\n            for (unsigned int i_pair = 0; i_pair < exchange_pairs.size(); ++i_pair)\n            {\n                int ispin = exchange_pairs[i_pair].i + icell*geometry->n_cell_atoms;\n                int jspin = idx_from_pair(ispin, boundary_conditions, geometry->n_cells, geometry->n_cell_atoms, geometry->atom_types, exchange_pairs[i_pair]);\n                if (jspin >= 0)\n                {\n                    gradient[ispin] -= exchange_magnitudes[i_pair] * spins[jspin];\n                    #ifndef _OPENMP\n                    gradient[jspin] -= exchange_magnitudes[i_pair] * spins[ispin];\n                    #endif\n                }\n            }\n        }\n    }\n\n    void Hamiltonian_Heisenberg::Gradient_DMI(const vectorfield & spins, vectorfield & gradient)\n    {\n        #pragma omp parallel for\n        for (int icell = 0; icell < geometry->n_cells_total; ++icell)\n        {\n            for (unsigned int i_pair = 0; i_pair < dmi_pairs.size(); ++i_pair)\n            {\n                int ispin = dmi_pairs[i_pair].i + icell*geometry->n_cell_atoms;\n                int jspin = idx_from_pair(ispin, boundary_conditions, geometry->n_cells, geometry->n_cell_atoms, geometry->atom_types, dmi_pairs[i_pair]);\n                if (jspin >= 0)\n                {\n                    gradient[ispin] -= dmi_magnitudes[i_pair] * spins[jspin].cross(dmi_normals[i_pair]);\n                    #ifndef _OPENMP\n                    gradient[jspin] += dmi_magnitudes[i_pair] * spins[ispin].cross(dmi_normals[i_pair]);\n                    #endif\n                }\n            }\n        }\n    }\n\n    void Hamiltonian_Heisenberg::Gradient_DDI(const vectorfield & spins, vectorfield & gradient)\n    {\n        // The translations are in angstr�m, so the |r|[m] becomes |r|[m]*10^-10\n        const scalar mult = mu_0 * std::pow(mu_B, 2) / ( 4*Pi * 1e-30 );\n        \n        for (unsigned int i_pair = 0; i_pair < ddi_pairs.size(); ++i_pair)\n        {\n            if (ddi_magnitudes[i_pair] > 0.0)\n            {\n                for (int da = 0; da < geometry->n_cells[0]; ++da)\n                {\n                    for (int db = 0; db < geometry->n_cells[1]; ++db)\n                    {\n                        for (int dc = 0; dc < geometry->n_cells[2]; ++dc)\n                        {\n                            scalar skalar_contrib = mult / std::pow(ddi_magnitudes[i_pair], 3.0);\n                            std::array<int, 3 > translations = { da, db, dc };\n\n                            int i = ddi_pairs[i_pair].i;\n                            int j = ddi_pairs[i_pair].j;\n                            int ispin = i + Vectormath::idx_from_translations(geometry->n_cells, geometry->n_cell_atoms, translations);\t\n                            int jspin = idx_from_pair(ispin, boundary_conditions, geometry->n_cells, geometry->n_cell_atoms, geometry->atom_types, ddi_pairs[i_pair]);\n                            if (jspin >= 0)\n                            {\n                                gradient[ispin] -= this->mu_s[j] * skalar_contrib * (3 * ddi_normals[i_pair] * spins[jspin].dot(ddi_normals[i_pair]) - spins[jspin]);\n                                gradient[jspin] -= this->mu_s[i] * skalar_contrib * (3 * ddi_normals[i_pair] * spins[ispin].dot(ddi_normals[i_pair]) - spins[ispin]);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }//end Field_DipoleDipole\n\n\n    void Hamiltonian_Heisenberg::Gradient_Quadruplet(const vectorfield & spins, vectorfield & gradient)\n    {\n        for (unsigned int iquad = 0; iquad < quadruplets.size(); ++iquad)\n        {\n            int i = quadruplets[iquad].i;\n            int j = quadruplets[iquad].j;\n            int k = quadruplets[iquad].k;\n            int l = quadruplets[iquad].l;\n            for (int da = 0; da < geometry->n_cells[0]; ++da)\n            {\n                for (int db = 0; db < geometry->n_cells[1]; ++db)\n                {\n                    for (int dc = 0; dc < geometry->n_cells[2]; ++dc)\n                    {\n                        std::array<int, 3 > translations = { da, db, dc };\n                        int ispin = i + Vectormath::idx_from_translations(geometry->n_cells, geometry->n_cell_atoms, translations);\n                        int jspin = j + Vectormath::idx_from_translations(geometry->n_cells, geometry->n_cell_atoms, translations, quadruplets[iquad].d_j);\n                        int kspin = k + Vectormath::idx_from_translations(geometry->n_cells, geometry->n_cell_atoms, translations, quadruplets[iquad].d_k);\n                        int lspin = l + Vectormath::idx_from_translations(geometry->n_cells, geometry->n_cell_atoms, translations, quadruplets[iquad].d_l);\n                        \n                        if ( check_atom_type(this->geometry->atom_types[ispin]) && check_atom_type(this->geometry->atom_types[jspin]) &&\n                                check_atom_type(this->geometry->atom_types[kspin]) && check_atom_type(this->geometry->atom_types[lspin]) )\n                        {\n                            gradient[ispin] -= quadruplet_magnitudes[iquad] * spins[jspin] * (spins[kspin].dot(spins[lspin]));\n                            gradient[jspin] -= quadruplet_magnitudes[iquad] * spins[ispin] * (spins[kspin].dot(spins[lspin]));\n                            gradient[kspin] -= quadruplet_magnitudes[iquad] * (spins[ispin].dot(spins[jspin])) * spins[lspin];\n                            gradient[lspin] -= quadruplet_magnitudes[iquad] * (spins[ispin].dot(spins[jspin])) * spins[kspin];\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n\n    void Hamiltonian_Heisenberg::Hessian(const vectorfield & spins, MatrixX & hessian)\n    {\n        int nos = spins.size();\n\n        // Set to zero\n        hessian.setZero();\n\n        // Single Spin elements\n        for (int da = 0; da < geometry->n_cells[0]; ++da)\n        {\n            for (int db = 0; db < geometry->n_cells[1]; ++db)\n            {\n                for (int dc = 0; dc < geometry->n_cells[2]; ++dc)\n                {\n                    std::array<int, 3 > translations = { da, db, dc };\n                    int icell = Vectormath::idx_from_translations(geometry->n_cells, geometry->n_cell_atoms, translations);\n                    for (int alpha = 0; alpha < 3; ++alpha)\n                    {\n                        for ( int beta = 0; beta < 3; ++beta )\n                        {\n                            for (unsigned int i = 0; i < anisotropy_indices.size(); ++i)\n                            {\n                                if ( check_atom_type(this->geometry->atom_types[anisotropy_indices[i]]) )\n                                {\n                                    int idx_i = 3 * icell + anisotropy_indices[i] + alpha;\n                                    int idx_j = 3 * icell + anisotropy_indices[i] + beta;\n                                    // scalar x = -2.0*this->anisotropy_magnitudes[i] * std::pow(this->anisotropy_normals[i][alpha], 2);\n                                    hessian( idx_i, idx_j ) += -2.0 * this->anisotropy_magnitudes[i] * \n                                                                    this->anisotropy_normals[i][alpha] * \n                                                                    this->anisotropy_normals[i][beta];\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        // Spin Pair elements\n        // Exchange\n        for (int da = 0; da < geometry->n_cells[0]; ++da)\n        {\n            for (int db = 0; db < geometry->n_cells[1]; ++db)\n            {\n                for (int dc = 0; dc < geometry->n_cells[2]; ++dc)\n                {\n                    std::array<int, 3 > translations = { da, db, dc };\n                    for (unsigned int i_pair = 0; i_pair < this->exchange_pairs.size(); ++i_pair)\n                    {\n                        int ispin = exchange_pairs[i_pair].i + Vectormath::idx_from_translations(geometry->n_cells, geometry->n_cell_atoms, translations);\n                        int jspin = idx_from_pair(ispin, boundary_conditions, geometry->n_cells, geometry->n_cell_atoms, geometry->atom_types, exchange_pairs[i_pair]);\n                        if (jspin >= 0)\n                        {\n                            for (int alpha = 0; alpha < 3; ++alpha)\n                            {\n                                int i = 3 * ispin + alpha;\n                                int j = 3 * jspin + alpha;\n\n                                hessian(i, j) += -exchange_magnitudes[i_pair];\n                                #ifndef _OPENMP\n                                hessian(j, i) += -exchange_magnitudes[i_pair];\n                                #endif\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        // DMI\n        for (int da = 0; da < geometry->n_cells[0]; ++da)\n        {\n            for (int db = 0; db < geometry->n_cells[1]; ++db)\n            {\n                for (int dc = 0; dc < geometry->n_cells[2]; ++dc)\n                {\n                    std::array<int, 3 > translations = { da, db, dc };\n                    for (unsigned int i_pair = 0; i_pair < this->dmi_pairs.size(); ++i_pair)\n                    {\n                        int ispin = dmi_pairs[i_pair].i + Vectormath::idx_from_translations(geometry->n_cells, geometry->n_cell_atoms, translations);\n                        int jspin = idx_from_pair(ispin, boundary_conditions, geometry->n_cells, geometry->n_cell_atoms, geometry->atom_types, dmi_pairs[i_pair]);\n                        if (jspin >= 0)\n                        {\n                            int i = 3*ispin;\n                            int j = 3*jspin;\n\n                            hessian(i+2, j+1) +=  dmi_magnitudes[i_pair] * dmi_normals[i_pair][0];\n                            hessian(i+1, j+2) += -dmi_magnitudes[i_pair] * dmi_normals[i_pair][0];\n                            hessian(i, j+2)   +=  dmi_magnitudes[i_pair] * dmi_normals[i_pair][1];\n                            hessian(i+2, j)   += -dmi_magnitudes[i_pair] * dmi_normals[i_pair][1];\n                            hessian(i+1, j)   +=  dmi_magnitudes[i_pair] * dmi_normals[i_pair][2];\n                            hessian(i, j+1)   += -dmi_magnitudes[i_pair] * dmi_normals[i_pair][2];\n\n                            #ifndef _OPENMP\n                            hessian(j+1, i+2) +=  dmi_magnitudes[i_pair] * dmi_normals[i_pair][0];\n                            hessian(j+2, i+1) += -dmi_magnitudes[i_pair] * dmi_normals[i_pair][0];\n                            hessian(j+2, i)   +=  dmi_magnitudes[i_pair] * dmi_normals[i_pair][1];\n                            hessian(j, i+2)   += -dmi_magnitudes[i_pair] * dmi_normals[i_pair][1];\n                            hessian(j, i+1)   +=  dmi_magnitudes[i_pair] * dmi_normals[i_pair][2];\n                            hessian(j+1, i)   += -dmi_magnitudes[i_pair] * dmi_normals[i_pair][2];\n                            #endif\n                        }\n                    }\n                }\n            }\n        }\n\n        //// Dipole-Dipole\n        //for (unsigned int i_pair = 0; i_pair < this->DD_indices.size(); ++i_pair)\n        //{\n        //\t// indices\n        //\tint idx_1 = DD_indices[i_pair][0];\n        //\tint idx_2 = DD_indices[i_pair][1];\n        //\t// prefactor\n        //\tscalar prefactor = 0.0536814951168\n        //\t\t* this->mu_s[idx_1] * this->mu_s[idx_2]\n        //\t\t/ std::pow(DD_magnitude[i_pair], 3);\n        //\t// components\n        //\tfor (int alpha = 0; alpha < 3; ++alpha)\n        //\t{\n        //\t\tfor (int beta = 0; beta < 3; ++beta)\n        //\t\t{\n        //\t\t\tint idx_h = idx_1 + alpha*nos + 3 * nos*(idx_2 + beta*nos);\n        //\t\t\tif (alpha == beta)\n        //\t\t\t\thessian[idx_h] += prefactor;\n        //\t\t\thessian[idx_h] += -3.0*prefactor*DD_normal[i_pair][alpha] * DD_normal[i_pair][beta];\n        //\t\t}\n        //\t}\n        //}\n\n        // Quadruplets\n    }\n\n    // Hamiltonian name as string\n    static const std::string name = \"Heisenberg\";\n    const std::string& Hamiltonian_Heisenberg::Name() { return name; }\n}\n\n#endif", "meta": {"hexsha": "e08f57a442bbd1ad5a2667b5da87548b4550e298", "size": 39718, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/src/engine/Hamiltonian_Heisenberg.cpp", "max_stars_repo_name": "Zeleznyj/spirit", "max_stars_repo_head_hexsha": "5e23bf3be5aa4bacf5aae24514b0b22cbd395619", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core/src/engine/Hamiltonian_Heisenberg.cpp", "max_issues_repo_name": "Zeleznyj/spirit", "max_issues_repo_head_hexsha": "5e23bf3be5aa4bacf5aae24514b0b22cbd395619", "max_issues_repo_licenses": ["MIT"], "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/Hamiltonian_Heisenberg.cpp", "max_forks_repo_name": "Zeleznyj/spirit", "max_forks_repo_head_hexsha": "5e23bf3be5aa4bacf5aae24514b0b22cbd395619", "max_forks_repo_licenses": ["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.7954271961, "max_line_length": 174, "alphanum_fraction": 0.5433808349, "num_tokens": 9892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.661922862511608, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.259696717692943}}
{"text": "/*ckwg +29\n * Copyright 2015-2020 by Kitware, 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 *  * 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 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 name of Kitware, Inc. nor the names of any contributors may be used\n *    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''\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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR\n * 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\n// The immediately following copyright notice applies to code in the methods\n// Triangulate_DLT, find_optimal_image_points and triangulate_fast_two_view.\n\n // Copyright (C) 2013 The Regents of the University of California (Regents).\n // All rights reserved.\n //\n // Redistribution and use in source and binary forms, with or without\n // modification, are permitted provided that the following conditions are\n // met:\n //\n //     * Redistributions of source code must retain the above copyright\n //       notice, this list of conditions and the following disclaimer.\n //\n //     * Redistributions in binary form must reproduce the above\n //       copyright notice, this list of conditions and the following\n //       disclaimer in the documentation and/or other materials provided\n //       with the distribution.\n //\n //     * Neither the name of The Regents or University of California nor the\n //       names of its contributors may be used to endorse or promote products\n //       derived from this software without specific prior written permission.\n //\n // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n // POSSIBILITY OF SUCH DAMAGE.\n //\n // Please contact the author of this library if you have any questions.\n // Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n\n/**\n * \\file\n * \\brief Implementation of triangulation function\n */\n\n#include \"triangulate.h\"\n#include <Eigen/SVD>\n#include <arrows/mvg/epipolar_geometry.h>\n\n\nnamespace kwiver {\nnamespace arrows {\nnamespace mvg {\n\n// Triangulates 2 views\nvoid\nTriangulate_DLT( kwiver::vital::matrix_3x4d const& pose1,\n                 kwiver::vital::matrix_3x4d const& pose2,\n                 kwiver::vital::vector_2d const& point1,\n                 kwiver::vital::vector_2d const& point2,\n                 kwiver::vital::vector_4d &triangulated_point)\n{\n  // code modified from code found at\n  // https://github.com/sweeneychris/TheiaSfM/blob/master/src/theia/sfm/triangulation/triangulation.h\n\n  kwiver::vital::matrix_4x4d design_matrix;\n  design_matrix.row(0) = point1[0] * pose1.row(2) - pose1.row(0);\n  design_matrix.row(1) = point1[1] * pose1.row(2) - pose1.row(1);\n  design_matrix.row(2) = point2[0] * pose2.row(2) - pose2.row(0);\n  design_matrix.row(3) = point2[1] * pose2.row(2) - pose2.row(1);\n\n  // Extract nullspace.\n  Eigen::JacobiSVD<Eigen::Matrix<double,4,4>> svd(design_matrix, Eigen::ComputeFullV);\n  triangulated_point = svd.matrixV().rightCols<1>();\n}\n\n// Given either a fundamental or essential matrix and two corresponding images\n// points such that ematrix * point2 produces a line in the first image,\n// this method finds corrected image points such that\n// corrected_point1^t * ematrix * corrected_point2 = 0.\nvoid\nfind_optimal_image_points(kwiver::vital::essential_matrix_sptr ematrix,\n                          const vital::vector_2d &point1,\n                          const vital::vector_2d &point2,\n                          vital::vector_2d &corrected_point1,\n                          vital::vector_2d &corrected_point2)\n{\n  // code modified from code found at\n  // https://github.com/sweeneychris/TheiaSfM/blob/master/src/theia/sfm/triangulation/triangulation.cc\n  auto E = ematrix->matrix();\n\n  vital::vector_3d point1_homog = point1.homogeneous();\n  vital::vector_3d point2_homog = point2.homogeneous();\n\n  // A helper matrix to isolate certain coordinates.\n  Eigen::Matrix<double, 2, 3> s_matrix;\n  s_matrix << 1, 0, 0, 0, 1, 0;\n\n  const Eigen::Matrix2d e_submatrix = E.topLeftCorner<2, 2>();\n\n  // The epipolar line from one image point in the other image.\n  vital::vector_2d epipolar_line1 = s_matrix * E * point2_homog;\n  vital::vector_2d epipolar_line2 = s_matrix * E.transpose() * point1_homog;\n\n  const double a = epipolar_line1.transpose() * e_submatrix * epipolar_line2;\n  const double b =\n    (epipolar_line1.squaredNorm() + epipolar_line2.squaredNorm()) / 2.0;\n  const double c = point1_homog.transpose() * E * point2_homog;\n\n  const double d = sqrt(b * b - a * c);\n\n  double lambda = c / (b + d);\n  epipolar_line1 -= e_submatrix * lambda * epipolar_line1;\n  epipolar_line2 -= e_submatrix.transpose() * lambda * epipolar_line2;\n\n  lambda *=\n    (2.0 * d) / (epipolar_line1.squaredNorm() + epipolar_line2.squaredNorm());\n\n  corrected_point1 =\n    (point1_homog - s_matrix.transpose() * lambda * epipolar_line1)\n    .hnormalized();\n  corrected_point2 =\n    (point2_homog - s_matrix.transpose() * lambda * epipolar_line2)\n    .hnormalized();\n}\n\ntemplate <typename T>\nEigen::Matrix<T, 3, 1>\ntriangulate_fast_two_view(const vital::simple_camera_perspective &camera0,\n                          const vital::simple_camera_perspective &camera1,\n                          const Eigen::Matrix<T, 2, 1> &point0,\n                          const Eigen::Matrix<T, 2, 1> &point1)\n{\n  // code modified from code found at\n  // https://github.com/sweeneychris/TheiaSfM/blob/master/src/theia/sfm/triangulation/triangulation.cc\n\n  auto E = essential_matrix_from_cameras(camera0, camera1);\n\n  const vital::vector_2d pt0 = camera0.get_intrinsics()->unmap(point0.template cast<double>());\n  const vital::vector_2d pt1 = camera1.get_intrinsics()->unmap(point1.template cast<double>());\n\n  vital::vector_2d corrected_pt0, corrected_pt1;\n\n  find_optimal_image_points(E, pt0, pt1, corrected_pt0, corrected_pt1);\n\n  vital::vector_4d triangulated_point;\n  Triangulate_DLT(camera0.pose_matrix(), camera1.pose_matrix(), corrected_pt0, corrected_pt1, triangulated_point);\n  return triangulated_point.hnormalized().template cast<T>();\n}\n\n/// Triangulate a 3D point from a set of cameras and 2D image points\ntemplate <typename T>\nEigen::Matrix<T,3,1>\ntriangulate_inhomog(const std::vector<vital::simple_camera_perspective >& cameras,\n                    const std::vector<Eigen::Matrix<T,2,1> >& points)\n{\n  typedef Eigen::Matrix<T,2,1> vector_2;\n  typedef Eigen::Matrix<T,3,1> vector_3;\n  typedef Eigen::Matrix<T,3,3> matrix_3x3;\n  typedef Eigen::Matrix<T, Eigen::Dynamic, 3> data_matrix_t;\n  typedef Eigen::Matrix<T, Eigen::Dynamic, 1> data_vector_t;\n  const unsigned int num_rows = 2*static_cast<unsigned int>(points.size());\n  data_matrix_t A(num_rows, 3);\n  data_vector_t b(num_rows);\n  for ( unsigned int i=0; i<points.size(); ++i )\n  {\n    // the camera\n    const vital::simple_camera_perspective& cam = cameras[i];\n    const matrix_3x3 R(cam.get_rotation().matrix().cast<T>());\n    const vector_3 t(cam.translation().cast<T>());\n    // the point in normalized coordinates\n    const vital::vector_2d p2d = points[i].template cast<double>();\n    const vector_2 pt = cam.get_intrinsics()->unmap(p2d).template cast<T>();\n    A(2*i,   0) = R(0,0) - pt.x() * R(2,0);\n    A(2*i,   1) = R(0,1) - pt.x() * R(2,1);\n    A(2*i,   2) = R(0,2) - pt.x() * R(2,2);\n    A(2*i+1, 0) = R(1,0) - pt.y() * R(2,0);\n    A(2*i+1, 1) = R(1,1) - pt.y() * R(2,1);\n    A(2*i+1, 2) = R(1,2) - pt.y() * R(2,2);\n    b[2*i  ] = t.z()*pt.x() - t.x();\n    b[2*i+1] = t.z()*pt.y() - t.y();\n  }\n  Eigen::JacobiSVD<data_matrix_t> svd(A, Eigen::ComputeFullU |\n                                         Eigen::ComputeFullV);\n  return svd.solve(b);\n}\n\n/// Triangulate a homogeneous 3D point from a set of cameras and 2D image points\ntemplate <typename T>\nEigen::Matrix<T,4,1>\ntriangulate_homog(const std::vector<vital::simple_camera_perspective >& cameras,\n                  const std::vector<Eigen::Matrix<T,2,1> >& points)\n{\n  typedef Eigen::Matrix<T,2,1> vector_2;\n  typedef Eigen::Matrix<T,3,1> vector_3;\n  typedef Eigen::Matrix<T,3,3> matrix_3x3;\n  typedef Eigen::Matrix<T, Eigen::Dynamic, 4> data_matrix_t;\n  const unsigned int num_rows = 2*static_cast<unsigned int>(points.size());\n  data_matrix_t A(num_rows, 4);\n  for ( unsigned int i=0; i<points.size(); ++i )\n  {\n    // the camera\n    const vital::simple_camera_perspective& cam = cameras[i];\n    const matrix_3x3 R(cam.get_rotation().matrix().cast<T>());\n    const vector_3 t(cam.translation().cast<T>());\n    // the point in normalized coordinates\n    const vital::vector_2d p2d = points[i].template cast<double>();\n    const vector_2 pt = cam.get_intrinsics()->unmap(p2d).template cast<T>();\n    A(2*i,   0) = R(0,0) - pt.x() * R(2,0);\n    A(2*i,   1) = R(0,1) - pt.x() * R(2,1);\n    A(2*i,   2) = R(0,2) - pt.x() * R(2,2);\n    A(2*i,   3) = t.x()  - pt.x() * t.z();\n    A(2*i+1, 0) = R(1,0) - pt.y() * R(2,0);\n    A(2*i+1, 1) = R(1,1) - pt.y() * R(2,1);\n    A(2*i+1, 2) = R(1,2) - pt.y() * R(2,2);\n    A(2*i+1, 3) = t.y()  - pt.y() * t.z();\n  }\n  Eigen::JacobiSVD<data_matrix_t > svd(A, Eigen::ComputeFullV);\n  return svd.matrixV().col(3);\n}\n\n/// Triangulate a 3D point from a set of RPC cameras and 2D image points\ntemplate <typename T>\nEigen::Matrix<T,3,1>\ntriangulate_rpc(const std::vector<vital::simple_camera_rpc >& cameras,\n                const std::vector<Eigen::Matrix<T,2,1> >& points)\n{\n  // Get the pairs of points to define the rays\n  std::vector< std::pair< vital::vector_3d, vital::vector_3d > > pts;\n\n  Eigen::Array3d curr_scale = cameras[0].world_scale().array();\n  Eigen::Array3d curr_offset = cameras[0].world_offset().array();\n  Eigen::Array3d min_pos = curr_offset - curr_scale;\n  Eigen::Array3d max_pos = curr_offset + curr_scale;\n\n  for ( unsigned int i = 0; i < points.size(); ++i )\n  {\n    // Get world offset and scale to set normalization and sample heights\n    curr_scale = cameras[i].world_scale().array();\n    curr_offset = cameras[i].world_offset().array();\n\n    min_pos = min_pos.min( curr_offset - curr_scale );\n    max_pos = max_pos.max( curr_offset + curr_scale );\n\n    double h1 = ( curr_offset - curr_scale )[2];\n    double h2 = ( curr_offset + curr_scale )[2];\n\n    vital::vector_3d pt1 =\n      cameras[i].back_project( points[i].template cast<double>(), h1 );\n    vital::vector_3d pt2 =\n      cameras[i].back_project( points[i].template cast<double>(), h2 );\n    pts.push_back(\n      std::pair< vital::vector_3d, vital::vector_3d >( pt1, pt2 ) );\n  }\n\n  // Get normalization factors for full point set\n  vital::vector_3d scale = 0.5*( max_pos.matrix() - min_pos.matrix() );\n  vital::vector_3d offset = 0.5*( max_pos.matrix() + min_pos.matrix() );\n\n  vital::matrix_3x3d M = vital::matrix_3x3d::Zero();\n  vital::vector_3d v(0., 0., 0.);\n\n  for ( auto& pt : pts )\n  {\n    // Normalize points\n    vital::vector_3d p = ( pt.first - offset ).cwiseQuotient( scale );\n    vital::vector_3d x = ( pt.second - offset ).cwiseQuotient( scale );\n\n    // Unit vector along ray\n    vital::vector_3d unit_vec = ( x - p ).normalized();\n\n    vital::matrix_3x3d tmp_mat =\n      vital::matrix_3x3d::Identity() - unit_vec * unit_vec.transpose();\n    M += tmp_mat;\n    v += tmp_mat * p;\n  }\n\n  // Un-normalize before return\n  return ( scale.cwiseProduct(\n    M.colPivHouseholderQr().solve( v ) ) + offset ).cast<T>();\n}\n\n/// \\cond DoxygenSuppress\n#define INSTANTIATE_TRIANGULATE(T) \\\ntemplate KWIVER_ALGO_MVG_EXPORT Eigen::Matrix<T,3,1> \\\n         triangulate_fast_two_view( \\\n            const vital::simple_camera_perspective &camera0, \\\n            const vital::simple_camera_perspective &camera1, \\\n            const Eigen::Matrix<T, 2, 1> &point0, \\\n            const Eigen::Matrix<T, 2, 1> &point1); \\\ntemplate KWIVER_ALGO_MVG_EXPORT Eigen::Matrix<T,4,1> \\\n         triangulate_homog( \\\n            const std::vector<vital::simple_camera_perspective >& cameras, \\\n            const std::vector<Eigen::Matrix<T,2,1> >& points); \\\ntemplate KWIVER_ALGO_MVG_EXPORT Eigen::Matrix<T,3,1> \\\n         triangulate_inhomog( \\\n            const std::vector<vital::simple_camera_perspective >& cameras, \\\n            const std::vector<Eigen::Matrix<T,2,1> >& points); \\\ntemplate KWIVER_ALGO_MVG_EXPORT Eigen::Matrix<T,3,1> \\\n         triangulate_rpc( \\\n            const std::vector<vital::simple_camera_rpc >& cameras, \\\n            const std::vector<Eigen::Matrix<T,2,1> >& points);\n\nINSTANTIATE_TRIANGULATE(double);\nINSTANTIATE_TRIANGULATE(float);\n\n#undef INSTANTIATE_TRIANGULATE\n/// \\endcond\n\n} // end namespace mvg\n} // end namespace arrows\n} // end namespace kwiver\n", "meta": {"hexsha": "44e9c37430c24ddc750a6c1067b485455d0db784", "size": 14272, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "arrows/mvg/triangulate.cxx", "max_stars_repo_name": "tao558/kwiver", "max_stars_repo_head_hexsha": "51d671228ada60dd41e465cf9c282cba8614b057", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-14T18:22:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-14T18:22:42.000Z", "max_issues_repo_path": "arrows/mvg/triangulate.cxx", "max_issues_repo_name": "tao558/kwiver", "max_issues_repo_head_hexsha": "51d671228ada60dd41e465cf9c282cba8614b057", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "arrows/mvg/triangulate.cxx", "max_forks_repo_name": "tao558/kwiver", "max_forks_repo_head_hexsha": "51d671228ada60dd41e465cf9c282cba8614b057", "max_forks_repo_licenses": ["BSD-3-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.730994152, "max_line_length": 114, "alphanum_fraction": 0.6795123318, "num_tokens": 4002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2596656053268259}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2020-2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020-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_ALGEBRA_CURVES_HASH_TO_CURVE_EXPAND_HPP\n#define CRYPTO3_ALGEBRA_CURVES_HASH_TO_CURVE_EXPAND_HPP\n\n#include <nil/crypto3/algebra/curves/detail/h2c/h2c_suites.hpp>\n#include <nil/crypto3/algebra/curves/detail/h2c/h2c_sgn0.hpp>\n\n#include <nil/crypto3/algebra/algorithms/strxor.hpp>\n\n#include <nil/crypto3/algebra/curves/bls12.hpp>\n\n#include <nil/crypto3/hash/algorithm/hash.hpp>\n#include <nil/crypto3/hash/accumulators/hash.hpp>\n\n#include <boost/assert.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/concept/assert.hpp>\n\n#include <array>\n#include <type_traits>\n#include <iterator>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace algebra {\n            namespace curves {\n                namespace detail {\n                    using namespace nil::crypto3::detail;\n                    template<std::size_t k, typename HashType,\n                             /// HashType::digest_type is required to be uint8_t[]\n                             typename = typename std::enable_if<\n                                 std::is_same<std::uint8_t, typename HashType::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                        BOOST_STATIC_ASSERT_MSG(HashType::block_bits % 8 == 0, \"r_in_bytes is not a multiple of 8\");\n                        BOOST_STATIC_ASSERT_MSG(HashType::digest_bits % 8 == 0, \"b_in_bytes is not a multiple of 8\");\n                        BOOST_STATIC_ASSERT_MSG(HashType::digest_bits >= 2 * k,\n                                                \"k-bit collision resistance is not fulfilled\");\n\n                        constexpr static const std::size_t b_in_bytes = HashType::digest_bits / 8;\n                        constexpr static const std::size_t r_in_bytes = HashType::block_bits / 8;\n\n                        constexpr static const std::array<std::uint8_t, r_in_bytes> Z_pad {0};\n\n                    public:\n                        template<typename InputMsgType, typename InputDstType, typename OutputType,\n                                 typename = typename std::enable_if<\n                                     std::is_same<std::uint8_t, typename InputMsgType::value_type>::value &&\n                                     std::is_same<std::uint8_t, typename InputDstType::value_type>::value &&\n                                     std::is_same<std::uint8_t, typename OutputType::value_type>::value>::type>\n                        static inline void process(const std::size_t len_in_bytes, const InputMsgType &msg,\n                                                   const InputDstType &dst, OutputType &uniform_bytes) {\n                            BOOST_CONCEPT_ASSERT((boost::SinglePassRangeConcept<InputMsgType>));\n                            BOOST_CONCEPT_ASSERT((boost::SinglePassRangeConcept<InputDstType>));\n                            BOOST_CONCEPT_ASSERT((boost::SinglePassRangeConcept<OutputType>));\n                            BOOST_CONCEPT_ASSERT((boost::WriteableRangeConcept<OutputType>));\n\n                            // https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-10#section-5.4.1\n                            BOOST_ASSERT(len_in_bytes < 0x10000);\n                            BOOST_ASSERT(std::distance(dst.begin(), dst.end()) >= 16 &&\n                                         std::distance(dst.begin(), dst.end()) <= 255);\n                            BOOST_ASSERT(std::distance(uniform_bytes.begin(), uniform_bytes.end()) >= len_in_bytes);\n\n                            const std::array<std::uint8_t, 2> l_i_b_str = {\n                                static_cast<std::uint8_t>(len_in_bytes >> 8u),\n                                static_cast<std::uint8_t>(len_in_bytes % 0x100)};\n                            const 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\n                            // https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-10#section-5.4.1\n                            BOOST_ASSERT(ell <= 255);\n\n                            // TODO: use accumulators when they will be fixed\n                            // accumulator_set<HashType> b0_acc;\n                            // hash<HashType>(Z_pad, b0_acc);\n                            // hash<HashType>(msg, b0_acc);\n                            // hash<HashType>(l_i_b_str, b0_acc);\n                            // hash<HashType>(std::array<std::uint8_t, 1> {0}, b0_acc);\n                            // hash<HashType>(dst, b0_acc);\n                            // hash<HashType>(std::array<std::uint8_t, 1> {static_cast<std::uint8_t>(dst.size())},\n                            // b0_acc); typename HashType::digest_type b0 =\n                            // accumulators::extract::hash<HashType>(b0_acc);\n                            std::vector<std::uint8_t> msg_prime;\n                            msg_prime.insert(msg_prime.end(), Z_pad.begin(), Z_pad.end());\n                            msg_prime.insert(msg_prime.end(), msg.begin(), msg.end());\n                            msg_prime.insert(msg_prime.end(), l_i_b_str.begin(), l_i_b_str.end());\n                            msg_prime.insert(msg_prime.end(), static_cast<std::uint8_t>(0));\n                            msg_prime.insert(msg_prime.end(), dst.begin(), dst.end());\n                            msg_prime.insert(msg_prime.end(),\n                                             static_cast<std::uint8_t>(std::distance(dst.begin(), dst.end())));\n                            typename HashType::digest_type b0 = hash<HashType>(msg_prime);\n\n                            // TODO: use accumulators when they will be fixed\n                            // accumulator_set<HashType> bi_acc;\n                            // hash<HashType>(b0, bi_acc);\n                            // hash<HashType>(std::array<std::uint8_t, 1> {1}, bi_acc);\n                            // hash<HashType>(dst, bi_acc);\n                            // hash<HashType>(std::array<std::uint8_t, 1> {static_cast<std::uint8_t>(dst.size())},\n                            // bi_acc); typename HashType::digest_type bi =\n                            // accumulators::extract::hash<HashType>(bi_acc); std::copy(bi.begin(), bi.end(),\n                            // uniform_bytes.begin());\n                            std::vector<std::uint8_t> b_i_str;\n                            b_i_str.insert(b_i_str.end(), b0.begin(), b0.end());\n                            b_i_str.insert(b_i_str.end(), static_cast<std::uint8_t>(1));\n                            b_i_str.insert(b_i_str.end(), dst.begin(), dst.end());\n                            b_i_str.insert(b_i_str.end(),\n                                           static_cast<std::uint8_t>(std::distance(dst.begin(), dst.end())));\n                            typename HashType::digest_type bi = hash<HashType>(b_i_str);\n                            std::copy(bi.begin(), bi.end(), uniform_bytes.begin());\n\n                            typename HashType::digest_type xored_b;\n                            for (std::size_t i = 2; i <= ell; i++) {\n                                // TODO: use accumulators when they will be fixed\n                                // accumulator_set<HashType> bi_acc;\n                                // strxor(b0, bi, xored_b);\n                                // hash<HashType>(xored_b, bi_acc);\n                                // hash<HashType>(std::array<std::uint8_t, 1> {static_cast<std::uint8_t>(i)}, bi_acc);\n                                // hash<HashType>(dst, bi_acc);\n                                // hash<HashType>(std::array<std::uint8_t, 1> {static_cast<std::uint8_t>(dst.size())},\n                                //                bi_acc);\n                                // bi = accumulators::extract::hash<HashType>(bi_acc);\n                                // std::copy(bi.begin(), bi.end(), uniform_bytes.begin() + (i - 1) * b_in_bytes);\n                                strxor(b0, bi, xored_b);\n                                std::vector<std::uint8_t> b_i_str;\n                                b_i_str.insert(b_i_str.end(), xored_b.begin(), xored_b.end());\n                                b_i_str.insert(b_i_str.end(), static_cast<std::uint8_t>(i));\n                                b_i_str.insert(b_i_str.end(), dst.begin(), dst.end());\n                                b_i_str.insert(b_i_str.end(),\n                                               static_cast<std::uint8_t>(std::distance(dst.begin(), dst.end())));\n                                bi = hash<HashType>(b_i_str);\n                                std::copy(bi.begin(), bi.end(), uniform_bytes.begin() + (i - 1) * b_in_bytes);\n                            }\n                        }\n                    };\n                }    // namespace detail\n            }        // namespace curves\n        }            // namespace algebra\n    }                // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_ALGEBRA_CURVES_HASH_TO_CURVE_EXPAND_HPP\n", "meta": {"hexsha": "1c897642a34153472a7c506900f75b856773f394", "size": 10525, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/algebra/curves/detail/h2c/h2c_expand.hpp", "max_stars_repo_name": "JasonCoombs/crypto3-algebra", "max_stars_repo_head_hexsha": "3ddb4eb0ed65dc046660cc49811d17a140a4c72f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-09-20T18:56:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T06:58:28.000Z", "max_issues_repo_path": "include/nil/crypto3/algebra/curves/detail/h2c/h2c_expand.hpp", "max_issues_repo_name": "JasonCoombs/crypto3-algebra", "max_issues_repo_head_hexsha": "3ddb4eb0ed65dc046660cc49811d17a140a4c72f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2020-08-27T18:11:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-20T21:01:55.000Z", "max_forks_repo_path": "include/nil/crypto3/algebra/curves/detail/h2c/h2c_expand.hpp", "max_forks_repo_name": "NilFoundation/algebra", "max_forks_repo_head_hexsha": "f211b0ffb2c7d817d44d2a6d1cc586a6db62dc03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-07-05T13:50:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T03:09:12.000Z", "avg_line_length": 63.4036144578, "max_line_length": 118, "alphanum_fraction": 0.5163895487, "num_tokens": 2160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2596656053268259}}
{"text": "\n#ifndef ISOLATOR_SHREDDER_HPP\n#define ISOLATOR_SHREDDER_HPP\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/random/uniform_01.hpp>\n\n#include \"common.hpp\"\n#include \"nlopt/nlopt.h\"\n\n\n// A fast, generic, univariate slice sampler implementatation.\nclass Shredder\n{\n    public:\n        Shredder(double lower_limit, double upper_limit, double tolerance);\n        virtual ~Shredder();\n\n        // change the tolerance\n        void set_tolerance(double tolerance);\n\n        // Generate a new sample given the current value x0.\n        double sample(rng_t& rng, double x0);\n\n        // Generate a maximum likelihood estimate\n        double optimize(double x0);\n\n        // These are kept as public fields to ease debugging and diagnostics.\n        double x_min, x_max;\n\n    protected:\n        // Probability function. Return the log-probibility at x, as well as the\n        // derivative d.\n        virtual double f(double x, double& d) = 0;\n\n        // Bounds on the parameter being sampled over\n        double lower_limit, upper_limit, tolerance;\n\n        boost::random::uniform_01<double> random_uniform_01;\n\n    private:\n        double find_slice_edge(double x0, double slice_height, double lp0,\n                               double d0, int direction);\n\n        nlopt_opt opt;\n\n        friend double shredder_opt_objective(unsigned int _n, const double* _x,\n                                             double* _grad, void* data);\n};\n\n\n// Some common distribution functions, with derivatives\n//\n\n#if 0\nclass PoissonLogPdf\n{\n    public:\n        double f(float lambda, unsigned int k);\n        double df_dlambda(float lambda, unsigned int k);\n};\n#endif\n\n\nclass NormalLogPdf\n{\n    public:\n        double f(double mu, double sigma, const double* xs, size_t n);\n        float f(float mu, float sigma, const float* xs, size_t n);\n\n        double df_dx(double mu, double sigma, const double* xs, size_t n);\n\n        double df_dmu(double mu, double sigma, const double* xs, size_t n);\n        float df_dmu(float mu, float sigma, const float* xs, size_t n);\n\n        double df_dsigma(double mu, double sigma, const double* xs, size_t n);\n        float df_dsigma(float mu, float sigma, const float* xs, size_t n);\n\n        double f(double mu, double sigma, double x);\n        double df_dx(double mu, double sigma, double x);\n};\n\n\nclass LogNormalLogPdf\n{\n    public:\n        double f(double mu, double sigma, const double* xs, size_t n);\n        double df_dx(double mu, double sigma, double x);\n        double df_dmu(double mu, double sigma, const double* xs, size_t n);\n        double df_dsigma(double mu, double sigma, const double* xs, size_t n);\n};\n\n\n#if 0\nclass StudentsTLogPdf\n{\n    public:\n        double f(double nu, double mu, double sigma, const double* xs, size_t n);\n        float f(float nu, float mu, float sigma, const float* xs, size_t n);\n        double df_dx(double nu, double mu, double sigma, const double* xs, size_t n);\n        double df_dmu(double nu, double mu, double sigma, const double* xs, size_t n);\n        float df_dmu(float nu, float mu, float sigma, const float* xs, size_t n);\n        double df_dsigma(double nu, double mu, double sigma, const double* xs, size_t n);\n};\n#endif\n\n\n#if 0\nclass GammaLogPdf\n{\n    public:\n        double f(double alpha, double beta, const double* xs, size_t n);\n        float f(float alpha, float beta, const float* xs, size_t n);\n        double df_dx(double alpha, double beta, const double* xs, size_t n);\n        double df_dalpha(double alpha, double beta, const double* xs, size_t n);\n        double df_dbeta(double alpha, double beta, const double* xs, size_t n);\n        float df_dbeta(float alpha, float beta, const float* xs, size_t n);\n};\n#endif\n\n\n#if 0\n// Gamma parameterized by mean and shape\nclass AltGammaLogPdf\n{\n    public:\n        double f(double mean, double shape, const double* xs, size_t n);\n        float f(float mean, float shape, const float* xs, size_t n);\n        double f(double mean, double shape, double x);\n        float f(float mean, float shape, float x);\n        double df_dx(double mean, double shape, const double* xs, size_t n);\n        double df_dx(double mean, double shape, double x);\n        double df_dmean(double mean, double shape, const double* xs, size_t n);\n        float df_dmean(float mean, float shape, const float* xs, size_t n);\n        double df_dshape(double shape, double mean, const double* xs, size_t n);\n        float df_dshape(float shape, float mean, const float* xs, size_t n);\n        float df_dshape(float mean, float shape, float x);\n};\n#endif\n\n\nclass InvGammaLogPdf\n{\n    public:\n        double f(double alpha, double beta, const double* xs, size_t n);\n        double df_dx(double alpha, double beta, const double* xs, size_t n);\n        double df_dalpha(double alpha, double beta, const double* xs, size_t n);\n        double df_dbeta(double alpha, double beta, const double* xs, size_t n);\n};\n\n\nclass SqInvGammaLogPdf\n{\n    public:\n        double f(double alpha, double beta, const double* xs, size_t n);\n        double df_dx(double alpha, double beta, const double* xs, size_t n);\n        double df_dalpha(double alpha, double beta, const double* xs, size_t n);\n        double df_dbeta(double alpha, double beta, const double* xs, size_t n);\n};\n\n\nclass BetaLogPdf\n{\n    public:\n        double f(double alpha, double beta, double x);\n        double df_dx(double alpha, double beta, double x);\n        double df_dgamma(double gamma, double c, double x);\n};\n\n\nclass DirichletLogPdf\n{\n    public:\n        double f(double alpha,\n                 const boost::numeric::ublas::matrix<double>* mean,\n                 const boost::numeric::ublas::matrix<double>* data,\n                 size_t n, size_t m);\n\n        double df_dalpha(double alpha,\n                         const boost::numeric::ublas::matrix<double>* mean,\n                         const boost::numeric::ublas::matrix<double>* data,\n                         size_t n, size_t m);\n};\n\n\n// 1-d logistic normal\nclass LogisticNormalLogPdf\n{\n    public:\n        double f(double mu, double sigma, double x);\n        double df_dx(double mu, double sigma, double x);\n\n        // TODO: do these when we need them\n        //double df_dmu(double x, double mu, double sigma);\n        //double df_dsigma(double x, double mu ,double sigma);\n};\n\n\n#endif\n\n", "meta": {"hexsha": "8898de6e8eb6dbe484bf0d206e55deb782a3f0d5", "size": 6320, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/shredder.hpp", "max_stars_repo_name": "dcjones/isolator", "max_stars_repo_head_hexsha": "24bafc0a102dce213bfc2b5b9744136ceadaba03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2015-07-13T03:00:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-20T08:49:07.000Z", "max_issues_repo_path": "src/shredder.hpp", "max_issues_repo_name": "dcjones/isolator", "max_issues_repo_head_hexsha": "24bafc0a102dce213bfc2b5b9744136ceadaba03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2016-11-29T00:04:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-10T17:46:01.000Z", "max_forks_repo_path": "src/shredder.hpp", "max_forks_repo_name": "dcjones/isolator", "max_forks_repo_head_hexsha": "24bafc0a102dce213bfc2b5b9744136ceadaba03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-09-10T15:49:34.000Z", "max_forks_repo_forks_event_max_datetime": "2017-03-09T05:14:06.000Z", "avg_line_length": 31.4427860697, "max_line_length": 89, "alphanum_fraction": 0.6465189873, "num_tokens": 1526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.25956709700669656}}
{"text": "#include \"stdafx.h\"\n#include \"pop.h\"\n#include \"params.h\"\n#include \"data.h\"\n#include \"rnd.h\"\n#include \"state.h\"\n#include \"Line2Eqn.h\"\n#include \"EvalEqnStr.h\"\n#include <unordered_map>\n#if defined(_WIN32)\n\t#include <regex>\n#else\n\t#include <boost/regex.hpp>\n#endif\n#include \"FitnessEstimator.h\"\n#include \"Fitness.h\"\n\n//void getEqnForm(std::string& eqn,std::string& eqn_form);\n//float getCorr(vector<float>& output,vector<float>& target,float meanout,float meantarget,int off);\n//int getComplexity(string& eqn);\n\n//void getEqnForm(std::string& eqn,std::string& eqn_form)\n//{\n////replace numbers with the letter c\n//#if defined(_WIN32)\n//\tstd::regex e (\"(([0-9]+)(\\.)([0-9]+))|([0-9]+)\");\n//\tstd::basic_string<char> tmp = \"c\";\n//\tstd::regex_replace (std::back_inserter(eqn_form), eqn.begin(), eqn.end(), e,tmp);\n//#else\n//\tboost::regex e (\"(([0-9]+)(\\.)([0-9]+))|([0-9]+)\");\n//\teqn_form = boost::regex_replace(eqn,e,\"c\");\n//#endif \n//\t//(\\d+\\.\\d+)|(\\d+)\n//\t//eqn_form = eqn;\n//\t//eqn_form=std::tr1::regex_replace(eqn,e,tmp.c_str(),std::tr1::regex_constants::match_default);\n//\t//std::string result;\n//\n//\n//\t//std::regex_replace(std::back_inserter(eqn_form),eqn.begin(),eqn.end(),e,\"c\",std::regex_constants::match_default);\n//\t//std::regex_replace(std::back_inserter(eqn_form),eqn.begin(),eqn.end(),e,\"c\",std::tr1::regex_constants::match_default\n//    //std::cout << result;\n//\t//std::cout << eqn << \"\\t\" << eqn_form <<\"\\n\";\n//}\n//int getComplexity(string& eqn)\n//{\n//\tint complexity=0;\n//\tchar c;\n//\tfor(int m=0;m<eqn.size();m++){\n//\t\tc=eqn[m];\n//\t\t\n//\t\tif(c=='/')\n//\t\t\tcomplexity=complexity+2;\n//\t\telse if (c=='s'){\n//\t\t\tif(m+2<eqn.size()){\n//\t\t\t\tif ( eqn[m+1]=='i' && eqn[m+2] == 'n'){\n//\t\t\t\t\tcomplexity=complexity+3;\n//\t\t\t\t\tm=m+2;\n//\t\t\t\t}\n//\t\t\t}\n//\t\t}\n//\t\telse if (c=='c'){\n//\t\t\tif(m+2<eqn.size()){\n//\t\t\t\tif ( eqn[m+1]=='o' && eqn[m+2] == 's'){\n//\t\t\t\t\tcomplexity=complexity+3;\n//\t\t\t\t\tm=m+2;\n//\t\t\t\t}\n//\t\t\t}\n//\t\t}\n//\t\telse if (c=='e'){\n//\t\t\tif(m+2<eqn.size()){\n//\t\t\t\tif ( eqn[m+1]=='x' && eqn[m+2] == 'p'){\n//\t\t\t\t\tcomplexity=complexity+4;\n//\t\t\t\t\tm=m+2;\n//\t\t\t\t}\n//\t\t\t}\n//\t\t}\n//\t\telse if (c=='l'){\n//\t\t\tif(m+2<eqn.size()){\n//\t\t\t\tif ( eqn[m+1]=='o' && eqn[m+2] == 'g'){\n//\t\t\t\t\tcomplexity=complexity+4;\n//\t\t\t\t\tm=m+2;\n//\t\t\t\t}\n//\t\t\t}\n//\t\t}\n//\t\telse if (isalpha(c) && (m+1)<eqn.size()){\n//\t\t\tbool pass=true;\n//\t\t\twhile ((m+1)<eqn.size() && pass){\n//\t\t\t\tif (isalpha(eqn[m+1])) m++; \n//\t\t\t\telse pass=0;\n//\t\t\t}\n//\t\t\tcomplexity++;\n//\t\t}\n//\t\telse\n//\t\t\tcomplexity++;\n//\t}\n//\n//\treturn complexity;\n//}\n//void eval(node& n,vector<float>& outstack)\n//{\n//\tswitch(n.type) \n//\t{\n//\tcase 'n':\n//\t\toutstack.push_back(n.value);\n//\t\tbreak;\n//\tcase 'v':\n//\t\tif (n.valpt==NULL)\n//\t\t\tcout<<\"problem\";\n//\t\telse\n//\t\t\toutstack.push_back(*n.valpt);\n//\t\tbreak;\n//\tcase '+':\n//\t\tif(outstack.size()>=2){\n//\t\t\t\tfloat n1 = outstack.back(); outstack.pop_back();\n//\t\t\t\tfloat n2 = outstack.back(); outstack.pop_back();\n//\n//\t\t\t\toutstack.push_back(n2+n1);\n//\t\t}\n//\t\tbreak;\n//\tcase '-':\n//\t\tif(outstack.size()>=2){\n//\t\t\t\tfloat n1 = outstack.back(); outstack.pop_back();\n//\t\t\t\tfloat n2 = outstack.back(); outstack.pop_back();\n//\n//\t\t\t\toutstack.push_back(n2-n1);\n//\t\t}\n//\t\tbreak;\n//\tcase '*':\n//\t\tif(outstack.size()>=2){\n//\t\t\t\tfloat n1 = outstack.back(); outstack.pop_back();\n//\t\t\t\tfloat n2 = outstack.back(); outstack.pop_back();\n//\n//\t\t\t\toutstack.push_back(n2*n1);\n//\t\t}\n//\t\tbreak;\n//\tcase '/':\n//\t\tif(outstack.size()>=2){\n//\t\t\t\tfloat n1 = outstack.back(); outstack.pop_back();\n//\t\t\t\tfloat n2 = outstack.back(); outstack.pop_back();\n//\t\t\t\tif(abs(n1)<0.0001)\n//\t\t\t\t\toutstack.push_back(0);\n//\t\t\t\telse\n//\t\t\t\t\toutstack.push_back(n2/n1);\n//\t\t}\n//\t\tbreak;\n//\tcase 's':\n//\t\tif(outstack.size()>=1){\n//\t\t\t\tfloat n1 = outstack.back(); outstack.pop_back();\n//\t\t\t\toutstack.push_back(sin(n1));\n//\t\t}\n//\t\tbreak;\n//\tcase 'c':\n//\t\tif(outstack.size()>=1){\n//\t\t\t\tfloat n1 = outstack.back(); outstack.pop_back();\n//\t\t\t\toutstack.push_back(cos(n1));\n//\t\t}\n//\t\tbreak;\n//\tcase 'e':\n//\t\tif(outstack.size()>=1){\n//\t\t\t\tfloat n1 = outstack.back(); outstack.pop_back();\n//\t\t\t\toutstack.push_back(exp(n1));\n//\t\t}\n//\t\tbreak;\n//\tcase 'l':\n//\t\tif(outstack.size()>=1){\n//\t\t\t\tfloat n1 = outstack.back(); outstack.pop_back();\n//\t\t\t\tif (abs(n1)<0.0001)\n//\t\t\t\t\toutstack.push_back(0);\n//\t\t\t\telse\n//\t\t\t\t\toutstack.push_back(log(n1));\n//\t\t}\n//\t\tbreak;\n//\t}\n//}\n\n", "meta": {"hexsha": "845bbcdafa95bb7820f17568a420409b471f6930", "size": 4277, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "afp-eplex/ellen/SlimFitness.cpp", "max_stars_repo_name": "lacava/regression-benchmark", "max_stars_repo_head_hexsha": "f20ef3dd1083b273f5777975f2e1f366060ec2fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "afp-eplex/ellen/SlimFitness.cpp", "max_issues_repo_name": "lacava/regression-benchmark", "max_issues_repo_head_hexsha": "f20ef3dd1083b273f5777975f2e1f366060ec2fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "afp-eplex/ellen/SlimFitness.cpp", "max_forks_repo_name": "lacava/regression-benchmark", "max_forks_repo_head_hexsha": "f20ef3dd1083b273f5777975f2e1f366060ec2fd", "max_forks_repo_licenses": ["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.3011363636, "max_line_length": 121, "alphanum_fraction": 0.5492167407, "num_tokens": 1490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2595389365769605}}
{"text": "// CHAP - The Channel Annotation Package\n// \n// Copyright (c) 2016 - 2018 Gianni Klesse, Shanlin Rao, Mark S. P. Sansom, and \n// Stephen J. Tucker\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 <algorithm>\n#include <iostream>\n#include <functional>\n#include <limits>\n#include <ctime>\n\n#include <boost/math/tools/minima.hpp>\n\n#include <gromacs/pbcutil/pbc.h>\n#include <gromacs/selection/nbsearch.h>\n#include <gromacs/selection/selection.h>\n\n#include \"geometry/cubic_spline_interp_1D.hpp\"\n#include \"geometry/cubic_spline_interp_3D.hpp\"\n#include \"geometry/spline_curve_1D.hpp\"\n#include \"geometry/spline_curve_3D.hpp\"\n\n#include \"path-finding/molecular_path.hpp\"\n\n\n/*!\n * Constructor to generate a MolecularPath object from a set of centre line \n * points and corresponding radii.\n *\n * This uses CubicSplineInterp3D to perform cubic spline interpolation and \n * build a \\f$ C^2 \\f$-continuous curve connecting all given centre line \n * points. This uses the Euclidean distance between centre line points as \n * interpolation parameter.\n *\n * Subsequently, CubicSplineInterp1D is used to smoothly interpolate the radius\n * between the given support points. Consequently, the input vectors must have\n * the same number of elements. This uses the arc length distance between \n * centre line points as interpolation parameter.\n * \n * Finally, the centre-line curve is re-parameterised in terms of arc length\n * and the length of the path is computed as the arc length distance between\n * the first and last centre line points.\n */\nMolecularPath::MolecularPath(std::vector<gmx::RVec> &pathPoints, \n                             std::vector<real> &pathRadii)\n{\n    // assign internal containers for original path data:\n    pathPoints_ = pathPoints;\n    pathRadii_ = pathRadii;\n\n    // construct centre line spline by interpolation of path points:\n    CubicSplineInterp3D Interp3D;\n    centreLine_ = Interp3D(pathPoints_, eSplineInterpBoundaryHermite);\n\n    // get arc length at original control points:\n    std::vector<real> arcLen = centreLine_.ctrlPointArcLength();\n    openingLo_ = arcLen.front();\n    openingHi_ = arcLen.back();\n    length_ = std::abs(openingHi_ - openingLo_);\n\n    // interpolate radius:\n    CubicSplineInterp1D Interp1D;\n    poreRadius_ =  Interp1D(arcLen, pathRadii_, eSplineInterpBoundaryHermite);\n\n    // re-parameterise centre line spline by arc length:\n    centreLine_.arcLengthParam();\n}\n\n\n/*!\n * Constructor for creating MolcularPath from a JSON document.\n */\nMolecularPath::MolecularPath(\n        const rapidjson::Document &doc)\n    : centreLine_()\n    , poreRadius_()\n{\n    // make sure document is valid object:\n    if( !doc.IsObject() )\n    {\n        throw std::logic_error(\"JSON document passed to MolecularPath\"\n        \"constructor is not a valid JSON object.\");\n    }\n\n    // make sure radius spline data is given:\n    if( !doc.HasMember(\"molPathRadiusSpline\") )\n    {\n        throw std::logic_error(\"JSON document passed to MolecularPath\"\n        \"constructor does not have required member molPathRadiusSpline.\");\n    }\n    if( !doc[\"molPathRadiusSpline\"].HasMember(\"knots\") )\n    {\n        throw std::logic_error(\"Could not find knots in molPathRadiusSpline.\");\n    }\n    if( !doc[\"molPathRadiusSpline\"].HasMember(\"ctrl\") )\n    {\n        throw std::logic_error(\"Could not find ctrl in molPathRadiusSpline.\");\n    }\n\n    // make sure centre line spline data is given:\n    if( !doc.HasMember(\"molPathCentreLineSpline\") )\n    {\n        throw std::logic_error(\"JSON document passed to MolecularPath\"\n        \"constructor does not have required member molPathCentreLineSpline.\");\n    }\n    if( !doc[\"molPathCentreLineSpline\"].HasMember(\"knots\") )\n    {\n        throw std::logic_error(\"Could not find knots in molPathCentreLineSpline.\");\n    }\n    if( !doc[\"molPathCentreLineSpline\"].HasMember(\"ctrlX\") )\n    {\n        throw std::logic_error(\"Could not find ctrlX in molPathCentreLineSpline.\");\n    }\n    if( !doc[\"molPathCentreLineSpline\"].HasMember(\"ctrlY\") )\n    {\n        throw std::logic_error(\"Could not find ctrlY in molPathCentreLineSpline.\");\n    }\n    if( !doc[\"molPathCentreLineSpline\"].HasMember(\"ctrlZ\") )\n    {\n        throw std::logic_error(\"Could not find ctrlZ in malPathCentreLineSpline.\");\n    }\n\n    // make sure original points are present:\n    if( !doc.HasMember(\"molPathOrigPoints\") )\n    {\n        throw std::logic_error(\"JSON document passed to MolecularPath\"\n        \"constructor does not have required member molPathOrigPoints.\");\n    }\n    if( !doc[\"molPathOrigPoints\"].HasMember(\"x\") )\n    {\n        throw std::logic_error(\"Could not find x in molPathRadiusSpline.\");\n    }\n    if( !doc[\"molPathOrigPoints\"].HasMember(\"y\") )\n    {\n        throw std::logic_error(\"Could not find y in molPathRadiusSpline.\");\n    }\n    if( !doc[\"molPathOrigPoints\"].HasMember(\"z\") )\n    {\n        throw std::logic_error(\"Could not find z in molPathRadiusSpline.\");\n    }\n    if( !doc[\"molPathOrigPoints\"].HasMember(\"r\") )\n    {\n        throw std::logic_error(\"Could not find r in molPathRadiusSpline.\");\n    }\n\n    // extract original point and radius data from JSON:\n    for(size_t i = 0; i < doc[\"molPathOrigPoints\"][\"r\"].Size(); i++)\n    {\n         pathPoints_.push_back(\n                gmx::RVec(doc[\"molPathOrigPoints\"][\"x\"][i].GetDouble(), \n                          doc[\"molPathOrigPoints\"][\"y\"][i].GetDouble(),\n                          doc[\"molPathOrigPoints\"][\"z\"][i].GetDouble()));\n         pathRadii_.push_back(doc[\"molPathOrigPoints\"][\"r\"][i].GetDouble());\n    }\n\n    // extract pore radius spline from data:\n    std::vector<real> poreRadiusKnots;\n    std::vector<real> poreRadiusCtrlPoints;\n    for(size_t i = 0; i < doc[\"molPathRadiusSpline\"][\"knots\"].Size(); i++)\n    {\n        poreRadiusKnots.push_back( \n                doc[\"molPathRadiusSpline\"][\"knots\"][i].GetDouble() );\n        poreRadiusCtrlPoints.push_back( \n                doc[\"molPathRadiusSpline\"][\"ctrl\"][i].GetDouble() );\n    } \n\n    // add duplicate knots at endpoints:\n    int poreRadiusSplineDegree = 3; // TODO: should not be hardcoded\n    poreRadiusKnots.insert(\n            poreRadiusKnots.end(),\n            poreRadiusSplineDegree - 1,\n            poreRadiusKnots.back());\n    poreRadiusKnots.insert(\n            poreRadiusKnots.begin(),\n            poreRadiusSplineDegree - 1,\n            poreRadiusKnots.front());\n\n    // create radius spline curve:\n    poreRadius_ = SplineCurve1D(\n            poreRadiusSplineDegree,\n            poreRadiusKnots,\n            poreRadiusCtrlPoints);\n\n    // extract centre line spline from data:\n    std::vector<real> centreLineKnots;\n    std::vector<gmx::RVec> centreLineCtrlPoints;\n    for(size_t i = 0; i < doc[\"molPathCentreLineSpline\"][\"knots\"].Size(); i++)\n    {\n        centreLineKnots.push_back( \n                doc[\"molPathCentreLineSpline\"][\"knots\"][i].GetDouble() );\n        centreLineCtrlPoints.push_back( \n                gmx::RVec(doc[\"molPathCentreLineSpline\"][\"ctrlX\"][i].GetDouble(),\n                          doc[\"molPathCentreLineSpline\"][\"ctrlY\"][i].GetDouble(),\n                          doc[\"molPathCentreLineSpline\"][\"ctrlZ\"][i].GetDouble()));\n    } \n\n    // add duplicate knots at endpoints:\n    int centreLineSplineDegree = 3; // TODO: should not be hardcoded\n    centreLineKnots.insert(\n            centreLineKnots.end(),\n            centreLineSplineDegree - 1,\n            centreLineKnots.back());\n    centreLineKnots.insert(\n            centreLineKnots.begin(),\n            centreLineSplineDegree - 1,\n            centreLineKnots.front());\n\n    // create centre line spline curve:\n    centreLine_ = SplineCurve3D(\n            centreLineSplineDegree,\n            centreLineKnots,\n            centreLineCtrlPoints);\n\n    // set position of openings and pore length:\n    openingLo_ = poreRadiusKnots.front();\n    openingHi_ = poreRadiusKnots.back();\n    length_ = openingHi_ - openingLo_;\n\n    // sanity check:\n    if( openingLo_ > openingHi_ )\n    {\n        throw std::logic_error(\"Pore opening coordinates out of order.\");\n    }\n}\n\n\n/*!\n * Destructor.\n */\nMolecularPath::~MolecularPath()\n{\n\n}\n\n\n/*!\n * Function for mapping a set of Cartesian positions onto the centre line \n * spline curve.\n *\n * The return value is a vector of points in spline coordinates ordered in the \n * same way as the input vector. Internally, this uses mapPosition() for each \n * input position.\n */\nstd::vector<gmx::RVec>\nMolecularPath::mapPositions(const std::vector<gmx::RVec> &positions)\n{\n    // map all input positions onto centre line:\n    std::vector<gmx::RVec> mappedPositions;\n    mappedPositions.reserve(positions.size());\n    for(auto pos : positions)\n    {\n        mappedPositions.push_back(centreLine_.cartesianToCurvilinear(pos));\n    }\n \n    // return mapped positions:\n    return mappedPositions;\n}\n\n\n/*!\n * Maps all positions in a selection onto molecular pathway.\n *\n * This function does essentially the same as mapPositions, except that the \n * input may be provided as a selection of particles and the output will be \n * a map associating each refId in the selection with a set of curvilinear \n * coordinates.\n */\nstd::map<int, gmx::RVec>\nMolecularPath::mapSelection(const gmx::Selection &mapSel)\n{\n    // build map of pathway mapped coordinates:\n    std::map<int, gmx::RVec> mappedCoords;\n    for(int i = 0; i < mapSel.posCount(); i++)\n    {\n        unsigned int idx = mapSel.position(i).refId();\n        mappedCoords[idx] = centreLine_.cartesianToCurvilinear(\n                mapSel.position(i).x());\n    }\n\n    // return mapped coordinates:\n    return mappedCoords;\n}\n\n\n/*!\n * Checks if points described by a set of mapped coordinates lie within the \n * MolecularPath. \n *\n * The input is taken to be a map of points in centre line coordinates, i.e.\n * a tuple of \\f$ (s_i, \\rho_i, \\phi_i) \\f$ values for the \\f$ i \\f$ -th point,\n * where \\f$ s \\f$ is the distance along the centre line, \\f$ \\rho \\f$ is the \n * (orthogonal) distance from the centre line, and \\f$ \\phi \\f$ an angular \n * coordinate which is ignored in this function. To obtain a set of mapped\n * points the mapSelection() method can be used.\n *\n * The output is a map of booleans indicating whether or not a point lies \n * inside the MolecularPath. The integer key is the same as in the input map\n * and will usually correspond to the ID of a particle.\n *\n * To test whether a point lies within the MolecularPath, its distance from \n * the centre line is compared to to path radius at this point plus a margin,\n * i.e.\n *\n * \\f[\n *      \\gamma_i = \\left\\{ \n *                 \\begin{array}{ll}\n *                     1 & \\text{ if } \\rho_i < R(s_i) + m \\\\\n *                     0 & \\text{ otherwise }\n *                 \\end{array}\n *                 \\right.\n * \\f]\n *\n * with \\f$ \\gamma_i \\f$ being a binary indicator function.\n */\nstd::map<int, bool>\nMolecularPath::checkIfInside(const std::map<int, gmx::RVec> &mappedCoords,\n                             real margin)\n{\n    // create map for check results:\n    std::map<int, bool> isInside;\n\n    for(auto it = mappedCoords.begin(); it != mappedCoords.end(); it++)\n    {\n        real evalPoint = it -> second[0];\n        real thres = (poreRadius_.evaluate(evalPoint, 0)) + margin;\n        // threshold needs to be squared here because radial coordinate is!\n        isInside[it -> first] = (it -> second[1] < thres*thres);\n    }\n\n    // return assessment:\n    return isInside;\n}\n\n\n/*!\n * Checks if a given set of coordinates lies within the pathway.\n */\nstd::map<int, bool>\nMolecularPath::checkIfInside(const std::map<int, gmx::RVec> &mappedCoords,\n                             real margin,\n                             real sLo,\n                             real sHi)\n{\n    // first make decision based on margin:\n    std::map<int, bool> isInside = checkIfInside(mappedCoords, margin);\n\n    // now erase all elements that do not fall in given range:\n    for(auto it = isInside.begin(); it != isInside.end(); it++)\n    {\n        // obtain mapped s value:\n        real s = mappedCoords.at(it->first)[0];\n\n        // does it fall in target interval?\n        if( s < sLo || s > sHi )\n        {\n            it -> second = false;\n        }\n    }\n\n    // return resulting map:\n    return isInside;\n}\n\n\n/*!\n * Adds a scalar property to the MolecularPath. Note that property names must\n * be unique and already existing properties will be overwritten.\n */\nvoid\nMolecularPath::addScalarProperty(\n        std::string name,\n        SplineCurve1D property,\n        bool divergent)\n{\n    properties_[name] = std::pair<SplineCurve1D, bool>(property, divergent);\n}\n\n\n/*!\n * Returns map of scalar properties associated with the MolecularPath.\n */\nstd::map<std::string, std::pair<SplineCurve1D, bool>>\nMolecularPath::scalarProperties() const\n{\n    return properties_;\n}\n\n\n/*! \n * Simple getter function for access to original path points used to construct\n * the path.\n */\nstd::vector<gmx::RVec>\nMolecularPath::pathPoints()\n{\n    return pathPoints_;\n}\n\n\n/*!\n * Simple getter function for access to original radii used to construct the \n * path.\n */\nstd::vector<real>\nMolecularPath::pathRadii()\n{\n    return pathRadii_;\n}\n\n\n/*!\n * Returns a copy of the internal pore radius spline.\n */\nSplineCurve1D\nMolecularPath::pathRadius()\n{\n    return poreRadius_;\n}\n\n\n/*!\n * Returns a copy of the internal centre line spline.\n */\nSplineCurve3D\nMolecularPath::centreLine()\n{\n    return centreLine_;\n}\n\n\n/*! \n * Returns length of the pathway, defined as the the arc length distance \n * between the first and last control point\n */\nreal\nMolecularPath::length() const\n{\n    return length_;\n}\n\n\n/*!\n * Returns the pore radius \\f$ R(s) \\f$ at a given value of the centre line's\n * spline parameter \\f$ s \\f$.\n */\nreal\nMolecularPath::radius(real s)\n{\n    return poreRadius_.evaluate(s, 0);\n}\n\n\n/*!\n * Returns coordinates of the lower opening of the pore.\n */\nreal\nMolecularPath::sLo()\n{\n    return openingLo_;\n}\n\n\n/*!\n * Returns the coordinates of the upper opening of the pore.\n */\nreal\nMolecularPath::sHi()\n{\n    return openingHi_;\n}\n\n\n/*!\n * Getter method for access to the radius spline's knot vector. This returns \n * the complete knot vector including duplicate points at the ends.\n */\nstd::vector<real>\nMolecularPath::poreRadiusKnots() const\n{\n    return poreRadius_.knotVector();\n}\n\n\n/*!\n * Getter method for access to the radius spline's knot vector. This does strip\n * the knot vector of repeated knots at end points so that the resulting vector \n * has as many elements as the vector of control points.\n */\nstd::vector<real>\nMolecularPath::poreRadiusUniqueKnots() const\n{           \n    std::vector<real> allKnots = poreRadius_.knotVector();\n    std::vector<real> uniqueKnots(\n        allKnots.begin() + poreRadius_.degree() - 1, \n        allKnots.end() - poreRadius_.degree() + 1);\n    return uniqueKnots;\n}\n\n\n/*!\n * Getter method for access to the radius spline's control points.\n */\nstd::vector<real>\nMolecularPath::poreRadiusCtrlPoints() const\n{\n    return poreRadius_.ctrlPoints();\n}\n\n\n/*!\n * Getter method for access to the centre line spline's knot vector. \n * This returns  the complete knot vector including duplicate points at the \n * ends.\n */\nstd::vector<real>\nMolecularPath::centreLineKnots() const\n{\n    return centreLine_.knotVector();\n}\n\n\n/*!\n * Getter method for access to the centre line spline's knot vector. This does \n * strip the knot vector of repeated knots at end points so that the resulting \n * vector has as many elements as the vector of control points.\n */\nstd::vector<real>\nMolecularPath::centreLineUniqueKnots() const\n{\n    std::vector<real> allKnots = centreLine_.knotVector();\n    std::vector<real> uniqueKnots(\n            allKnots.begin() + centreLine_.degree() - 1,\n            allKnots.end() - centreLine_.degree() + 1);\n    return uniqueKnots;\n}\n\n\n/*!\n * Getter method for access to the centre line spline's control points.\n */\nstd::vector<gmx::RVec>\nMolecularPath::centreLineCtrlPoints() const\n{\n    return centreLine_.ctrlPoints();\n}\n\n\n\n/*!\n * Finds the minimum radius of the path and the location along the centre line\n * (in the current parameterisation) of this minimum. \n *\n * This is achieved by first sampling a set of trial points no more than 0.1\n * nm apart along the centreline and evaluating the path radius at all of these\n * points. The position of the minimum radius sample point is then used to \n * create input to Brent's minimisation algorithm. The initial bracketing \n * interval for Brent's algorithm is taken as one sampling point above and \n * below the minimum radius sampling point, if this point lies somewhere in \n * between the the centre line's endpoints. If the minimum radius sampling\n * point falls on either endpoint of the centeline, this point itself is taken\n * as one of the bracketing interval's limits.\n *\n * Note that Brent's algorithm is currently limited to a hardcoded limit of\n * 100 iterations.\n */\nstd::pair<real, real>\nMolecularPath::minRadius()\n{\n    // internal parameters:\n    real maxSampleDist = 0.1;\n    boost::uintmax_t maxIter = 100;\n\n    // draw radius samples along path:\n    int nSamples = std::ceil(length_/maxSampleDist);\n    std::vector<real> s = sampleArcLength(nSamples, 0.0);\n    std::vector<real> r = sampleRadii(s);\n   \n    // find smallest sample radius:\n    auto itMin = std::min_element(r.begin(), r.end());\n    int idxMin = std::distance(r.begin(), itMin);\n\n    // determine bracketing interval:\n    real sMin = s[idxMin - 1];\n    real sMax = s[idxMin + 1];\n    if( itMin == r.begin() )\n    {\n        sMin = s[idxMin];\n        sMax = s[idxMin + 1];\n    }\n    else if( itMin == r.end() )\n    {\n        sMin = s[idxMin - 1];\n        sMax = s[idxMin];\n    }\n\n    // return minimum and arg min:    \n    return boost::math::tools::brent_find_minima(\n            std::bind(&MolecularPath::radius, this, std::placeholders::_1), \n            sMin, \n            sMax, \n            std::numeric_limits<real>::digits,\n            maxIter);\n}\n\n\n/*!\n *  Returns the volume of the path defined as the volume of the spline tube\n *  between the upper and lower opening of the path, i.e.\n *\n *  \\f[\n *\n *      V = \\pi \\int_{s_0}^{s_1} \\left( R(s) \\right)^2 ds\n *\n *  \\f]\n *\n *  where \\f$ R(s) \\f$ denotes the radius at a given point along the spline.\n *\n *  This integral is solved numerically by applying a sixth order Newton-Cotes\n *  scheme (Weddle's rule) in each interval between two subsequent knots. Since\n *  the path radius is \\f$ \\mathcal{O}(s^3) \\f$ by construction, the integrand \n *  is guaranteed to be of order \\f$ \\mathcal{O}(s^6) \\f$ so the integration\n *  is exact.\n *\n *  The volume is nonetheless an estimate due to (i) the cross-sectional area\n *  of a path not being truly circular and (ii) the dependency of radius on\n *  centre line parameter not being \\f$ \\mathcal{O}(s^3) \\f$ necessarily. The \n *  former effect is likely stronger so that the volume estimate should be \n *  viewed as a lower bound.\n */\nreal\nMolecularPath::volume()\n{\n    // initialise number of intervals larger than number of spline intervals:\n    // (this ensures that function is polynomial on each interval)\n    size_t numIntervals = (poreRadius_.nKnots()) - 2*poreRadius_.degree() - 1;\n\n    // integration interval:\n    real h = length_/numIntervals;\n\n    // sample path radii:\n    int numPoints = 6*numIntervals + 1;\n    std::vector<real> radii = sampleRadii(numPoints, 0.0);\n    std::vector<real> s = sampleArcLength(numPoints, 0.0);\n  \n    // calculate squared radii:\n    std::vector<real> sqRadii;\n    sqRadii.reserve(radii.size());\n    for(size_t i = 0; i < radii.size(); i++)\n    {\n        sqRadii.push_back(radii[i]*radii[i]);\n    }\n\n    // evaluate integral using fine grained support points:\n    real integral = 0.0;\n    for(size_t i = 0; i < numIntervals; i++)\n    {\n        // index to vector of radii:\n        int idx = 6*i;\n\n        // integrate this interval using Weddle's Rule:\n        integral +=  41.0*sqRadii[idx] + \n                    216.0*sqRadii[idx+1] +\n                     27.0*sqRadii[idx+2] +\n                    272.0*sqRadii[idx+3] + \n                     27.0*sqRadii[idx+4] +\n                    216.0*sqRadii[idx+5] +\n                     41.0*sqRadii[idx+6];\n    }\n    integral *= h/840.0;\n\n    // multiply in constant factor:\n    integral *= PI_;\n\n    // return value of integral:\n    return integral;\n}\n\n\n/*!\n * Returns a vector of equally spaced arc length points that extends a \n * specified distance beyond the openings of the pore.\n */\nstd::vector<real>\nMolecularPath::sampleArcLength(size_t nPoints,\n                               real extrapDist) const\n{\n    // get spacing of points in arc length:\n    real arcLenStep = sampleArcLenStep(nPoints, extrapDist);\n\n    // evaluate spline to obtain sample points:\n    std::vector<real> arcLengthSample;\n    arcLengthSample.reserve(nPoints);\n    for(size_t i = 0; i < nPoints; i++)\n    {\n        // calculate evaluation point:\n        arcLengthSample.push_back( openingLo_ - extrapDist + i*arcLenStep );  \n    }\n\n    // return vector of points:\n    return arcLengthSample;\n}\n\n\n\n/*!\n * Returns a vector of point on the molecular path's centre line. The points \n * will be equally spaced in arc length and sampling will extend beyond the \n * pore openings for the specified distance. All points are given in\n * Cartesian coordinates.\n */\nstd::vector<gmx::RVec>\nMolecularPath::samplePoints(size_t nPoints,\n                            real extrapDist)\n{\n    // sample equidistant arc length values:\n    std::vector<real> arcLengthSteps = sampleArcLength(nPoints, extrapDist);\n\n    // return vector of points at these values:\n    return samplePoints(arcLengthSteps);\n}\n\n\n/*! \n * Returns a vector of points on the path's centre line at the given arc length\n * parameter values. All points are given in Cartesian coordinates.\n */\nstd::vector<gmx::RVec>\nMolecularPath::samplePoints(std::vector<real> arcLengthSample)\n{\n    // evaluate spline to obtain sample points:\n    std::vector<gmx::RVec> points;\n    points.reserve(arcLengthSample.size());\n    for(size_t i = 0; i < arcLengthSample.size(); i++)\n    {\n        // evaluate spline at this point:\n        points.push_back( centreLine_.evaluate(arcLengthSample[i], 0) );\n    }\n\n    // return vector of points:\n    return points;\n}\n\n\n/*!\n * Returns vector of \\p nPoints tangents to the centre line. The samples are \n * taken from equidistant points along the spline, extending \\p extrapDist into \n * the extrapolation range on either side. \n */\nstd::vector<gmx::RVec>\nMolecularPath::sampleTangents(size_t nPoints, real extrapDist)\n{\n    // sample equidistant arc length values:\n    std::vector<real> arcLengthSteps = sampleArcLength(nPoints, extrapDist);\n\n    // return vector of tangents at these values:\n    return sampleTangents(arcLengthSteps);\n}\n\n\n/*!\n * Returns vector of tangents to the centre line. These are calculated at the \n * evaluation points given on \\p arcLengthSample.\n */\nstd::vector<gmx::RVec>\nMolecularPath::sampleTangents(std::vector<real> arcLengthSample)\n{    \n    // evaluate spline to obtain sample points:\n    std::vector<gmx::RVec> tangents;\n    tangents.reserve(arcLengthSample.size());\n    for(size_t i = 0; i < arcLengthSample.size(); i++)\n    {\n        // evaluate spline at this point:\n        tangents.push_back( centreLine_.tangentVec(arcLengthSample[i]) );\n    }\n\n    // return vector of points:\n    return tangents;\n}\n\n\n/*!\n * Returns vector of \\p nPoints tangents to the centre line. The samples are \n * taken from equidistant points along the spline, extending \\p extrapDist into \n * the extrapolation range on either side. All tangents are explicitly \n * normalised in this function.\n */\n\nstd::vector<gmx::RVec>\nMolecularPath::sampleNormTangents(size_t nPoints, real extrapDist)\n{\n    // sample equidistant arc length values:\n    std::vector<real> arcLengthSteps = sampleArcLength(nPoints, extrapDist);\n\n    // return vector of tangents at these values:\n    std::vector<gmx::RVec> tangents = sampleTangents(arcLengthSteps);\n\n    // normalise all tangent vectors:\n    std::vector<gmx::RVec>::iterator it;\n    for(it = tangents.begin(); it != tangents.end(); it++)\n    {\n        unitv(*it, *it);\n    }\n\n    return tangents;\n}\n\n/*!\n * Returns vector of tangents to the centre line. These are calculate at the \n * evaluation points given on \\p arcLengthSample. All tangents are explicitly\n * normalised in this function.\n */\nstd::vector<gmx::RVec>\nMolecularPath::sampleNormTangents(std::vector<real> arcLengthSample)\n{    \n    // evaluate spline to obtain sample points:\n    std::vector<gmx::RVec> tangents;\n    tangents.reserve(arcLengthSample.size());\n    for(size_t i = 0; i < arcLengthSample.size(); i++)\n    {\n        // evaluate spline at this point:\n        tangents.push_back( centreLine_.tangentVec(arcLengthSample[i]) );\n\n        // normalise tangent vector:\n        unitv(tangents.back(), tangents.back());\n    }\n\n    // return vector of points:\n    return tangents;\n}\n\n\n/*!\n * \\todo This needs to be implemented.\n */\nstd::vector<gmx::RVec>\nMolecularPath::sampleNormals(size_t nPoints, real extrapDist)\n{\n    // sample equidistant arc length values:\n    std::vector<real> arcLengthSteps = sampleArcLength(nPoints, extrapDist);\n\n    // return vector of normals at these values:\n    return sampleNormals(arcLengthSteps);\n}\n\n\n/*!\n * \\todo This needs to be implemented.\n */\nstd::vector<gmx::RVec>\nMolecularPath::sampleNormals(std::vector<real> /* arcLengthSample */)\n{\n    // evaluate spline to obtain sample points:\n    std::vector<gmx::RVec> normals;\n\n    // return vector of points:\n    return normals;\n}\n\n\n/*!\n * Returns a vector of radius values at equally spaced points a long the path.\n * Sampling extends the specified distance beyond the openings of the pore.\n */\nstd::vector<real>\nMolecularPath::sampleRadii(size_t nPoints,\n                           real extrapDist)\n{\n    // get spacing of points in arc length:\n    real arcLenStep = sampleArcLenStep(nPoints, extrapDist);\n\n    // evaluate spline to obtain sample points:\n    std::vector<real> radii;\n    for(size_t i = 0; i < nPoints; i++)\n    {\n        // calculate evaluation point:\n        real evalPoint = openingLo_ - extrapDist + i*arcLenStep;  \n\n        // evaluate spline at this point:\n        radii.push_back( poreRadius_.evaluate(evalPoint, 0) );\n    }\n\n    // return vector of points:\n    return radii;\n}\n\n\n/*!\n * Returns a vector of radius values at the given arc length parameter values.\n */\nstd::vector<real>\nMolecularPath::sampleRadii(std::vector<real> arcLengthSample)\n{\n    // evaluate spline to obtain sample points:\n    std::vector<real> radii;\n    for(size_t i = 0; i < arcLengthSample.size(); i++)\n    {\n        // evaluate spline at this point:\n        radii.push_back( poreRadius_.evaluate(arcLengthSample[i], 0) );\n    }\n\n    // return vector of points:\n    return radii;\n}\n\n\n/*!\n * Shift the s-coordinate by the given number.\n */\nvoid\nMolecularPath::shift(const gmx::RVec &shift)\n{\n    // shift both the centre line and the radius spline:\n    centreLine_.shift(shift);  \n    poreRadius_.shift(shift);\n\n    // adjust convenience variables defined in MolecularPath itself:\n    openingLo_ -= shift[SS];\n    openingHi_ -= shift[SS];\n}\n\n\n/*!\n * Auxiliary function that computes the step length along the arc for sampling\n * a given property at \\f$ N \\f$ points and reaching \\f$ d \\f$ into the \n * extrapolation region at either side of the pore. The step length is computed\n * as\n *\n * \\f[\n *      \\Delta s = \\frac{L + 2 d}{N - 1}\n * \\f]\n *\n * where \\f$ L \\f$ denotes the length of the path between its first and last\n * control points.\n */\nreal\nMolecularPath::sampleArcLenStep(size_t nPoints, real extrapDist) const\n{\n    // get spacing of points in arc length:\n    return (this -> length() + 2.0*extrapDist)/(nPoints - 1);\n}\n\n", "meta": {"hexsha": "70c1e983a2ee315b6c89ef32103096962acf26ce", "size": 28792, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/path-finding/molecular_path.cpp", "max_stars_repo_name": "bigginlab/chap", "max_stars_repo_head_hexsha": "17de36442e2e80cb01432e84050c4dfce31fc3a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-06-28T00:21:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:31:32.000Z", "max_issues_repo_path": "src/path-finding/molecular_path.cpp", "max_issues_repo_name": "bigginlab/chap", "max_issues_repo_head_hexsha": "17de36442e2e80cb01432e84050c4dfce31fc3a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2019-03-19T21:54:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T02:20:42.000Z", "max_forks_repo_path": "src/path-finding/molecular_path.cpp", "max_forks_repo_name": "bigginlab/chap", "max_forks_repo_head_hexsha": "17de36442e2e80cb01432e84050c4dfce31fc3a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-10-27T19:35:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T01:10:39.000Z", "avg_line_length": 29.9604578564, "max_line_length": 83, "alphanum_fraction": 0.6647332592, "num_tokens": 7263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2594839138358107}}
{"text": "#include \"pauli_operator.hpp\"\n\n#include <boost/dynamic_bitset.hpp>\n#include <csim/stat_ops_dm.hpp>\n#include <vector>\n\n#ifdef _USE_GPU\n#include <gpusim/stat_ops.h>\n#endif\n\n#include \"state.hpp\"\n#include \"type.hpp\"\n\nvoid MultiQubitPauliOperator::set_bit(\n    const UINT pauli_id, const UINT target_index) {\n    while (this->_x.size() <= target_index) {\n        this->_x.resize(this->_x.size() * 2 + 1);\n    }\n    this->_z.resize(this->_x.size());\n    if (pauli_id == PAULI_ID_X) {\n        this->_x.set(target_index);\n    } else if (pauli_id == PAULI_ID_Y) {\n        this->_x.set(target_index);\n        this->_z.set(target_index);\n    } else if (pauli_id == PAULI_ID_Z) {\n        this->_z.set(target_index);\n    }\n}\n\nconst std::vector<UINT>& MultiQubitPauliOperator::get_pauli_id_list() const {\n    return _pauli_id;\n}\n\nconst std::vector<UINT>& MultiQubitPauliOperator::get_index_list() const {\n    return _target_index;\n}\n\nvoid MultiQubitPauliOperator::add_single_Pauli(\n    UINT qubit_index, UINT pauli_type) {\n    if (pauli_type >= 4)\n        throw std::invalid_argument(\"pauli type must be any of 0,1,2,3\");\n    _target_index.push_back(qubit_index);\n    _pauli_id.push_back(pauli_type);\n    set_bit(pauli_type, qubit_index);\n}\n\nCPPCTYPE MultiQubitPauliOperator::get_expectation_value(\n    const QuantumStateBase* state) const {\n    if (state->get_device_type() == DEVICE_CPU) {\n        if (state->is_state_vector()) {\n            return expectation_value_multi_qubit_Pauli_operator_partial_list(\n                this->_target_index.data(), this->_pauli_id.data(),\n                static_cast<UINT>(this->_target_index.size()), state->data_c(),\n                state->dim);\n        } else {\n            return dm_expectation_value_multi_qubit_Pauli_operator_partial_list(\n                this->_target_index.data(), this->_pauli_id.data(),\n                static_cast<UINT>(this->_target_index.size()), state->data_c(),\n                state->dim);\n        }\n    } else if (state->get_device_type() == DEVICE_GPU) {\n#ifdef _USE_GPU\n        if (state->is_state_vector()) {\n            return expectation_value_multi_qubit_Pauli_operator_partial_list_host(\n                this->get_index_list().data(), this->get_pauli_id_list().data(),\n                (UINT)this->get_index_list().size(), state->data(), state->dim,\n                state->get_cuda_stream(), state->device_number);\n        } else {\n            throw std::runtime_error(\n                \"Get expectation value for DensityMatrix on GPU is not \"\n                \"supported\");\n        }\n#else\n        throw std::invalid_argument(\"GPU is not supported in this build\");\n#endif\n    } else {\n        throw std::invalid_argument(\"Unsupported device type\");\n    }\n}\n\nCPPCTYPE MultiQubitPauliOperator::get_transition_amplitude(\n    const QuantumStateBase* state_bra,\n    const QuantumStateBase* state_ket) const {\n    if (state_bra->get_device_type() != state_ket->get_device_type())\n        throw std::invalid_argument(\"Device type is different\");\n    if (state_bra->is_state_vector() != state_ket->is_state_vector())\n        throw std::invalid_argument(\"is_state_vector is not matched\");\n    if (state_bra->dim != state_ket->dim)\n        throw std::invalid_argument(\"state_bra->dim != state_ket->dim\");\n\n    if (state_bra->get_device_type() == DEVICE_CPU) {\n        if (state_bra->is_state_vector()) {\n            return transition_amplitude_multi_qubit_Pauli_operator_partial_list(\n                this->_target_index.data(), this->_pauli_id.data(),\n                (UINT)this->_target_index.size(), state_bra->data_c(),\n                state_ket->data_c(), state_bra->dim);\n        } else {\n            throw std::invalid_argument(\n                \"TransitionAmplitude for density matrix is not implemtend\");\n        }\n    } else if (state_bra->get_device_type() == DEVICE_GPU) {\n#ifdef _USE_GPU\n        if (state_bra->is_state_vector()) {\n            return transition_amplitude_multi_qubit_Pauli_operator_partial_list_host(\n                this->get_index_list().data(), this->get_pauli_id_list().data(),\n                (UINT)this->get_index_list().size(), state_bra->data(),\n                state_ket->data(), state_bra->dim, state_bra->get_cuda_stream(),\n                state_bra->device_number);\n        } else {\n            throw std::runtime_error(\n                \"Get expectation value for DensityMatrix on GPU is not \"\n                \"supported\");\n        }\n#else\n        throw std::invalid_argument(\"GPU is not supported in this build\");\n#endif\n    } else {\n        throw std::invalid_argument(\"Unsupported device\");\n    }\n}\n\nMultiQubitPauliOperator* MultiQubitPauliOperator::copy() const {\n    auto pauli =\n        new MultiQubitPauliOperator(this->_target_index, this->_pauli_id);\n    return pauli;\n}\n\nbool MultiQubitPauliOperator::operator==(\n    const MultiQubitPauliOperator& target) const {\n    auto x = this->_x;\n    auto z = this->_z;\n    auto target_x = target.get_x_bits();\n    auto target_z = target.get_z_bits();\n    if (target_x.size() != this->_x.size()) {\n        size_t max_size = std::max(this->_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    return x == target_x && z == target_z;\n}\n\nMultiQubitPauliOperator MultiQubitPauliOperator::operator*(\n    const MultiQubitPauliOperator& target) const {\n    auto x = this->_x;\n    auto z = this->_z;\n    auto target_x = target.get_x_bits();\n    auto target_z = target.get_z_bits();\n    if (target_x.size() != this->_x.size()) {\n        size_t 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    MultiQubitPauliOperator res(x ^ target_x, z ^ target_z);\n    return res;\n}\n\nMultiQubitPauliOperator& MultiQubitPauliOperator::operator*=(\n    const MultiQubitPauliOperator& target) {\n    auto target_x = target.get_x_bits();\n    auto target_z = target.get_z_bits();\n    size_t max_size = std::max(this->_x.size(), target_x.size());\n    if (target_x.size() != this->_x.size()) {\n        this->_x.resize(max_size);\n        this->_z.resize(max_size);\n        target_x.resize(max_size);\n        target_z.resize(max_size);\n    }\n    this->_x ^= target_x;\n    this->_z ^= target_z;\n    _target_index.clear();\n    _pauli_id.clear();\n    ITYPE i;\n    for (i = 0; i < max_size; i++) {\n        UINT pauli_id = PAULI_ID_I;\n        if (this->_x[i] && !this->_z[i]) {\n            pauli_id = PAULI_ID_X;\n        } else if (this->_x[i] && this->_z[i]) {\n            pauli_id = PAULI_ID_Y;\n        } else if (!this->_x[i] && this->_z[i]) {\n            pauli_id = PAULI_ID_Z;\n        }\n        _target_index.push_back(i);\n        _pauli_id.push_back(pauli_id);\n    }\n    return *this;\n}\n\nstd::string MultiQubitPauliOperator::to_string() const {\n    std::string res;\n    std::string id;\n    ITYPE i;\n    for (i = 0; i < _x.size(); i++) {\n        if (!_x[i] && !_z[i]) {\n            id = \"I\";\n        } else if (_x[i] && !_z[i]) {\n            id = \"X\";\n        } else if (_x[i] && _z[i]) {\n            id = \"Y\";\n        } else if (!_x[i] && _z[i]) {\n            id = \"Z\";\n        }\n        if (id != \"I\") {\n            res += id + \" \" + std::to_string(i) + \" \";\n        }\n    }\n    return res;\n}", "meta": {"hexsha": "13ba1921aefb90ab674520048bb4d882cc6af5ea", "size": 7350, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cppsim_experimental/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_experimental/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_experimental/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.8341232227, "max_line_length": 85, "alphanum_fraction": 0.6107482993, "num_tokens": 1901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2594833646000077}}
{"text": "////\n////  ExpressionFit.cpp\n////  Face AR\n////\n////  Created by shiwei zhou on 2018/1/31.\n////  Copyright © 2018年 shiwei zhou. All rights reserved.\n////\n//\n//#include <stdio.h>\n//#include <Eigen/Eigen>\n//#ifndef __ANDROID__\n//#include \"nnls.h\"\n//#endif\n//#include <opencv2/core/core.hpp>\n//\n//\n//using namespace std;\n//using namespace cv;\n//auto FitExpressionBlendshape(cv::Mat &currentShape,cv::Mat &blenshape,std::vector<cv::Point2f> &landmarks,std::vector<int> &mapping_3d,cv::Mat &affine_matrix)\n//{\n//\n//    int num=(int)landmarks.size();\n//    int num_coeffs_to_fit=(int)blenshape.cols;\n//    cv::Mat A(3*num,num_coeffs_to_fit,CV_32FC1,Scalar(0));\n//    //    cv::Mat current_hat_h = cv::Mat::zeros(4, num_coeffs_to_fit, CV_32FC1);\n//    cv::Mat affine_matrix_ROI=affine_matrix(cv::Rect(0,0,3,3));\n//    for (int i=0; i<mapping_3d.size(); i++) {\n//\n//        int index=(int)mapping_3d.at(i)*3;\n//        //        cv::Mat vertex_basis=blenshape.rowRange(index, index+3);\n//        cv::Mat vertex_basis=blenshape(cv::Rect(0,index,num_coeffs_to_fit,3));\n//        //        vertex_basis.copyTo(current_hat_h.rowRange(0,3));\n//        Mat B=affine_matrix_ROI*vertex_basis;\n//        Mat roi=A(cv::Rect(0,i*3,num_coeffs_to_fit,3));\n//        B.copyTo(roi);\n//    }\n//\n//    //    cv::Mat V_hat_h = cv::Mat::zeros(4 *num, num_coeffs_to_fit, CV_32FC1);\n//    //    int rowIndex=0;\n//    //    for (int i=0; i<mapping_3d.size(); i++) {\n//    //        int index=(int)mapping_3d.at(i)*3;\n//    //        cv::Mat vertex_basis=blenshape.rowRange(index, index+3);\n//    //        vertex_basis.colRange(0,num_coeffs_to_fit).copyTo(V_hat_h.rowRange(rowIndex, rowIndex+3));\n//    //        rowIndex +=4;\n//    //    }\n//\n//    //    cv::Mat camera_matrix=affine_matrix;\n//    ////  affine_matrix.convertTo(camera_matrix,CV_32F);\n//    //\n//    //    cv::Mat Project_matrix(3*num,4*num,CV_32FC1,Scalar(0));\n//    //    for (int i = 0; i < num; ++i) {\n//    //        Mat submatrix_to_replace = Project_matrix.colRange(4 * i, (4 * i) + 4).rowRange(3 * i, (3 * i) + 3);\n//    //        camera_matrix.copyTo(submatrix_to_replace);\n//    //    }\n//\n//    cv::Mat y = Mat::ones(3 * num, 1, CV_32FC1);\n//    for (int i = 0; i < num; ++i) {\n//        y.at<float>(3 * i, 0) = landmarks.at(i).x;\n//        y.at<float>((3 * i) + 1, 0) = landmarks.at(i).y;\n//    }\n//    cv::Mat AffineMat= Mat::ones(3*num,1,CV_32FC1);\n//    cv::Mat cur_v_bar = Mat::ones(4, 1, CV_32FC1);\n//    for (int i = 0; i < num; ++i) {\n//\n//        int index=(int)mapping_3d.at(i)*3;\n//        cv::Mat cur_num_roi=currentShape(cv::Rect(0,index,1,3));\n//        cur_num_roi.copyTo(cur_v_bar(cv::Rect(0,0,1,3)));\n//        Mat tranform=affine_matrix*cur_v_bar;\n//        tranform.copyTo(AffineMat(cv::Rect(0,i*3,1,3)));\n//\n//\n//    }\n//\n//    //    cv::Mat v_bar = Mat::ones(4 * num, 1, CV_32FC1);\n//    //    for (int i = 0; i < num; ++i) {\n//    //        int index=(int)mapping_3d.at(i)*3;\n//    //        cv::Vec4f model_mean(currentShape.at<float>(index+0,0), currentShape.at<float>(index + 1,0), currentShape.at<float>(index + 2,0), 1.0f);\n//    //        v_bar.at<float>(4 * i, 0) = model_mean[0];\n//    //        v_bar.at<float>((4 * i) + 1, 0) = model_mean[1];\n//    //        v_bar.at<float>((4 * i) + 2, 0) = model_mean[2];\n//    //        //  v_bar.at<float>((4 * i) + 3, 0) = 1;\n//    //        //    cout<<mean.at<float>(index+0,0)<<\"  \"<< mean.at<float>(index + 1,0)<<\"   \"<<mean.at<float>(index + 2,0)<<endl;\n//    //    }\n//\n//    //  cv::Mat A = Project_matrix * V_hat_h;\n//    //    cv::Mat b = Project_matrix * v_bar - y;\n//    cv::Mat b = AffineMat - y;\n//\n//\n//\n//    //    // Solve using NNLS:\n//    using RowMajorMatrixXf = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n//    Eigen::Map<RowMajorMatrixXf> A_Eigen(A.ptr<float>(), A.rows, A.cols);\n//    Eigen::Map<RowMajorMatrixXf> b_Eigen(b.ptr<float>(), b.rows, b.cols);\n//\n//    // Meathod one\n//    //#ifndef __ANDROID__\n//    //    Eigen::VectorXf x;\n//    //    Eigen::NNLS<Eigen::MatrixXf>::solve(A_Eigen, -b_Eigen, x);\n//    //    cv::Mat c_s((int)x.rows(), (int)x.cols(), CV_32FC1, x.data());\n//    //    return std::vector<float>(c_s);\n//    //#else\n//\n//    // Meathod two\n//    int num_blendshapes=num_coeffs_to_fit;\n//    float lambda =200.0f;\n//    const Eigen::MatrixXf AtAReg =\n//    A_Eigen.transpose() * A_Eigen + lambda * Eigen::MatrixXf::Identity(num_blendshapes, num_blendshapes);\n//    const Eigen::MatrixXf rhs = -A_Eigen.transpose() * b_Eigen;\n//    Eigen::VectorXf coefficients = AtAReg.colPivHouseholderQr().solve(rhs);\n//    return std::vector<float>(coefficients.data(), coefficients.data() + coefficients.size());\n//\n//    // Meathod three\n//    //    const int num_shape_pc = num_coeffs_to_fit;\n//    //    float lambda=15.0f;//50\n//    //    Mat AtOmegaA = A.t() * Omega * A;\n//    //    Mat AtOmegaAReg = AtOmegaA + lambda * Mat::eye(num_shape_pc, num_shape_pc, CV_32FC1);\n//    //    Mat c_s;\n//    //    bool non_singular = cv::solve(AtOmegaAReg, -A.t() * Omega.t() * b, c_s, cv::DECOMP_SVD);\n//    //    return std::vector<float>(c_s);\n//    // #endif\n//\n//}\n//\n", "meta": {"hexsha": "74d3dad1a81229b9ffadc2d554eb3d9efb151949", "size": 5148, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Face3D.framework/Headers/ExpressionFit.hpp", "max_stars_repo_name": "aliyunvideo/AliyunLivePusherWithPlayer_iOS", "max_stars_repo_head_hexsha": "f1911b52a1bc9b8e77126f0a38df7b0f423bfa4e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-08-06T06:16:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-16T08:22:53.000Z", "max_issues_repo_path": "Face3D.framework/Headers/ExpressionFit.hpp", "max_issues_repo_name": "aliyunvideo/AliyunLivePusherWithPlayer_iOS", "max_issues_repo_head_hexsha": "f1911b52a1bc9b8e77126f0a38df7b0f423bfa4e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-03-26T10:32:35.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-26T10:32:35.000Z", "max_forks_repo_path": "Face3D.framework/Headers/ExpressionFit.hpp", "max_forks_repo_name": "aliyunvideo/AliyunLivePusherWithPlayer_iOS", "max_forks_repo_head_hexsha": "f1911b52a1bc9b8e77126f0a38df7b0f423bfa4e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-24T07:40:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-24T07:40:52.000Z", "avg_line_length": 41.184, "max_line_length": 160, "alphanum_fraction": 0.567016317, "num_tokens": 1743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421276, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.25938295443425086}}
{"text": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <vector>\n#include <map>\n#include <boost/python.hpp>\n#include <boost/python/numpy.hpp>\n#include \"kernel.hpp\"\n#include \"vector.hpp\"\n#include \"io.hpp\"\n#include \"cosmology.hpp\"\n#include \"spectra.hpp\"\n\n\nnamespace p = boost::python;\nnamespace np = boost::python::numpy;\n\n/* This function coverts vector to ndarray */\ntemplate<class T>\nnp::ndarray vec_to_ndarray(vector<T> &vec){\n    size_t size;\n\n    size = vec.size();\n    np::dtype dt = np::dtype::get_builtin<double>();\n    p::tuple shape = p::make_tuple(size);\n    np::ndarray a = np::zeros(shape, dt);\n\n\n    for(int i=0;i<size;++i) a[i] = vec[i];\n\n    return a;\n}\n\n/* This function checks the given array is compatible */\nvoid check_array(np::ndarray a){\n    if(a.get_nd() != 1){\n        cerr << \"[ERROR] array must be 1-dimensional\" << endl;\n        exit(1);\n    }\n\n    if(a.get_dtype() != np::dtype::get_builtin<double>()){\n        cerr << \"[ERROR] array must be float64 array\" << endl;\n        exit(1);\n    }\n\n    return;\n}\n\nclass pyspectrum\n{\nprivate:\n  cosmology *Cosmo;\n  spectra *Spectra;\n  params Params;\npublic:\n  void set_cosmology(p::dict &py_dict, np::ndarray k, np::ndarray Tk);\n  np::ndarray calc_linear(np::ndarray k);\n  np::ndarray calc_no_wiggle(np::ndarray k);\n  np::ndarray calc_RegPT_2loop(np::ndarray k);\n  np::ndarray calc_SPT_2loop(np::ndarray k);\n  np::ndarray calc_RegPT_1loop(np::ndarray k);\n  np::ndarray calc_SPT_1loop(np::ndarray k);\n};\n\n\nvoid pyspectrum::set_cosmology(p::dict &py_dict, np::ndarray k, np::ndarray Tk){\n  int N;\n  bool flag_smoothing = false;\n  vector<double> k_set, Tk_set;\n\n\n  check_array(k);\n  check_array(Tk);\n\n  if(k.shape(0) != Tk.shape(0)){\n      cerr << \"[ERROR] The length of k and Tk should be the same.\" << endl;\n      exit(1);\n  }\n\n  N = k.shape(0);\n\n  for(int i=0;i<N;++i){\n    k_set.push_back(p::extract<double>(k[i]));\n    Tk_set.push_back(p::extract<double>(Tk[i]));\n  }\n\n  p::list keys = py_dict.keys();\n  for(int i=0;i<len(keys);++i){\n    p::extract<string> extracted_key(keys[i]);\n    if(!extracted_key.check()){\n      cout << \"[NOTE] Key invalid, map might be incomplete\" << endl;\n      continue;\n    }\n\n    string key = extracted_key;\n    if(key == \"smoothing\"){\n      p::extract<bool> extracted_val(py_dict[key]);\n      if(extracted_val) flag_smoothing = true;\n    }\n    else{\n      p::extract<double> extracted_val(py_dict[key]);\n      if(!extracted_val.check()){\n        cout << \"[NOTE] Value invalid, map might be incomplete\" << endl;\n        continue;\n      }\n      double value = extracted_val;\n      Params.dparams[key] = value;\n    }\n  }\n\n\n  Params.bparams[\"output\"] = false; // no output\n\n  Cosmo = new cosmology(Params);\n  Cosmo->set_transfer(k_set, Tk_set);\n  Cosmo->set_spectra();\n  if(flag_smoothing){\n    cout << \"[NOTE] Smoothed linear power spectrum is set.\" << endl;\n    Cosmo->set_smoothed_spectra();\n  }\n\n  Spectra = new spectra(*Cosmo);\n\n  return;\n}\n\nnp::ndarray pyspectrum::calc_linear(np::ndarray k){\n  double ki, Pi;\n  size_t N;\n  vector<double> res;\n\n  check_array(k);\n  N = k.shape(0);\n\n  for(int i=0;i<N;++i){\n    ki = p::extract<double>(k[i]);\n    Pi = Spectra->Plin(ki);\n    res.push_back(Pi);\n  }\n\n  return vec_to_ndarray(res);\n}\n\nnp::ndarray pyspectrum::calc_no_wiggle(np::ndarray k){\n  double ki, Pi;\n  size_t N;\n  vector<double> res;\n\n  check_array(k);\n  N = k.shape(0);\n\n  for(int i=0;i<N;++i){\n    ki = p::extract<double>(k[i]);\n    Pi = Spectra->Pno_wiggle(ki);\n    res.push_back(Pi);\n  }\n\n  return vec_to_ndarray(res);\n}\n\nnp::ndarray pyspectrum::calc_RegPT_2loop(np::ndarray k){\n  double ki, Pi;\n  size_t N;\n  vector<double> res;\n\n  check_array(k);\n  N = k.shape(0);\n\n  for(int i=0;i<N;++i){\n    ki = p::extract<double>(k[i]);\n    Pi = Spectra->Preg_2loop(DENS, DENS, ki);\n    res.push_back(Pi);\n  }\n\n  return vec_to_ndarray(res);\n}\n\nnp::ndarray pyspectrum::calc_SPT_2loop(np::ndarray k){\n  double ki, Pi;\n  size_t N;\n  vector<double> res;\n\n  check_array(k);\n  N = k.shape(0);\n\n  for(int i=0;i<N;++i){\n    ki = p::extract<double>(k[i]);\n    Pi = Spectra->Pspt_2loop(DENS, DENS, ki);\n    res.push_back(Pi);\n  }\n\n  return vec_to_ndarray(res);\n}\n\nnp::ndarray pyspectrum::calc_RegPT_1loop(np::ndarray k){\n  double ki, Pi;\n  size_t N;\n  vector<double> res;\n\n  check_array(k);\n  N = k.shape(0);\n\n  for(int i=0;i<N;++i){\n    ki = p::extract<double>(k[i]);\n    Pi = Spectra->Preg_1loop(DENS, DENS, ki);\n    res.push_back(Pi);\n  }\n\n  return vec_to_ndarray(res);\n}\n\nnp::ndarray pyspectrum::calc_SPT_1loop(np::ndarray k){\n  double ki, Pi;\n  size_t N;\n  vector<double> res;\n\n  check_array(k);\n  N = k.shape(0);\n\n  for(int i=0;i<N;++i){\n    ki = p::extract<double>(k[i]);\n    Pi = Spectra->Pspt_1loop(DENS, DENS, ki);\n    res.push_back(Pi);\n  }\n\n  return vec_to_ndarray(res);\n}\n\nBOOST_PYTHON_MODULE(pyeclairs){\n  np::initialize();\n\n  p::class_<pyspectrum>(\"pyspectrum\")\n      .def(\"set_cosmology\", &pyspectrum::set_cosmology)\n      .def(\"calc_linear\", &pyspectrum::calc_linear)\n      .def(\"calc_no_wiggle\", &pyspectrum::calc_no_wiggle)\n      .def(\"calc_RegPT_2loop\", &pyspectrum::calc_RegPT_2loop)\n      .def(\"calc_SPT_2loop\", &pyspectrum::calc_SPT_2loop)\n      .def(\"calc_RegPT_1loop\", &pyspectrum::calc_RegPT_1loop)\n      .def(\"calc_SPT_1loop\", &pyspectrum::calc_SPT_1loop)\n  ;\n\n}\n", "meta": {"hexsha": "2299fc9bb4cde60cd6a1015f27565f20418053d1", "size": 5290, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pyeclairs.cpp", "max_stars_repo_name": "0satoken/Eclairs", "max_stars_repo_head_hexsha": "a4332c495914edb94a03f29ab332d84f053f5543", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-07T13:22:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-07T13:22:36.000Z", "max_issues_repo_path": "pyeclairs.cpp", "max_issues_repo_name": "0satoken/Eclairs", "max_issues_repo_head_hexsha": "a4332c495914edb94a03f29ab332d84f053f5543", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyeclairs.cpp", "max_forks_repo_name": "0satoken/Eclairs", "max_forks_repo_head_hexsha": "a4332c495914edb94a03f29ab332d84f053f5543", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7695473251, "max_line_length": 80, "alphanum_fraction": 0.631758034, "num_tokens": 1643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2593807164439105}}
{"text": "#include <fstream>\n#include <iostream>\n\n#include <boost/functional/hash.hpp>\n#include <boost/program_options.hpp>\n\n#include <yaml-cpp/yaml.h>\n\n#include <ecbs.hpp>\n#include \"timer.hpp\"\n\nusing libMultiRobotPlanning::ECBS;\nusing libMultiRobotPlanning::Neighbor;\nusing libMultiRobotPlanning::PlanResult;\n\nstruct State {\n  State(int time, int x, int y, int z) : time(time), x(x), y(y), z(z) {}\n\n  bool operator==(const State& s) const {\n    return time == s.time && x == s.x && y == s.y && z == s.z;\n  }\n\n  bool equalExceptTime(const State& s) const { return x == s.x && y == s.y && z == s.z; }\n\n  friend std::ostream& operator<<(std::ostream& os, const State& s) {\n    return os << s.time << \": (\" << s.x << \",\" << s.y << s.z << \")\";\n    // return os << \"(\" << s.x << \",\" << s.y << s.z <<\")\";\n  }\n\n  int time;\n  int x;\n  int y;\n  int z;\n};\n\nnamespace std {\ntemplate <>\nstruct hash<State> {\n  size_t operator()(const State& s) const {\n    size_t seed = 0;\n    boost::hash_combine(seed, s.time);\n    boost::hash_combine(seed, s.x);\n    boost::hash_combine(seed, s.y);\n    boost::hash_combine(seed, s.z);\n    return seed;\n  }\n};\n}  // namespace std\n\n///\nenum class Action {\n  Up,\n  Down,\n  Left,\n  Right,\n  Top,\n  Bottom,\n  Wait,\n};\n\nstd::ostream& operator<<(std::ostream& os, const Action& a) {\n  switch (a) {\n    case Action::Up:\n      os << \"Up\";\n      break;\n    case Action::Down:\n      os << \"Down\";\n      break;\n    case Action::Left:\n      os << \"Left\";\n      break;\n    case Action::Right:\n      os << \"Right\";\n      break;\n    case Action::Top:\n        os << \"Top\";\n        break;\n    case Action::Bottom:\n        os << \"Bottom\";\n        break;\n    case Action::Wait:\n      os << \"Wait\";\n      break;\n  }\n  return os;\n}\n\n///\n\nstruct Conflict {\n  enum Type {\n    Vertex,\n    Edge,\n  };\n\n  int time;\n  size_t agent1;\n  size_t agent2;\n  Type type;\n\n  int x1;\n  int y1;\n  int x2;\n  int y2;\n  int z1;\n  int z2;\n\n  friend std::ostream& operator<<(std::ostream& os, const Conflict& c) {\n    switch (c.type) {\n      case Vertex:\n        return os << c.time << \": Vertex(\" << c.x1 << \",\" << c.y1 << c.z1 << \")\";\n      case Edge:\n        return os << c.time << \": Edge(\" << c.x1 << \",\" << c.y1 << c.z1 << \",\" << c.x2\n                  << \",\" << c.y2 << c.z2 << \")\";\n    }\n    return os;\n  }\n};\n\nstruct VertexConstraint {\n  VertexConstraint(int time, int x, int y, int z) : time(time), x(x), y(y), z(z) {}\n  int time;\n  int x;\n  int y;\n  int z;\n\n  bool operator<(const VertexConstraint& other) const {\n    return std::tie(time, x, y, z) < std::tie(other.time, other.x, other.y, other.z);\n  }\n\n  bool operator==(const VertexConstraint& other) const {\n    return std::tie(time, x, y, z) == std::tie(other.time, other.x, other.y, other.z);\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, const VertexConstraint& c) {\n    return os << \"VC(\" << c.time << \",\" << c.x << \",\" << c.y << c.z << \")\";\n  }\n};\n\nnamespace std {\ntemplate <>\nstruct hash<VertexConstraint> {\n  size_t operator()(const VertexConstraint& s) const {\n    size_t seed = 0;\n    boost::hash_combine(seed, s.time);\n    boost::hash_combine(seed, s.x);\n    boost::hash_combine(seed, s.y);\n    boost::hash_combine(seed, s.z);\n    return seed;\n  }\n};\n}  // namespace std\n\nstruct EdgeConstraint {\n  EdgeConstraint(int time, int x1, int y1, int x2, int y2, int z1, int z2)\n      : time(time), x1(x1), y1(y1), x2(x2), y2(y2), z1(z1), z2(z2) {}\n  int time;\n  int x1;\n  int y1;\n  int x2;\n  int y2;\n  int z1;\n  int z2;\n\n  bool operator<(const EdgeConstraint& other) const {\n    return std::tie(time, x1, y1, x2, y2, z1, z2) <\n           std::tie(other.time, other.x1, other.y1, other.x2, other.y2, other.z1, other.z2);\n  }\n\n  bool operator==(const EdgeConstraint& other) const {\n    return std::tie(time, x1, y1, x2, y2, z1, z2) ==\n           std::tie(other.time, other.x1, other.y1, other.x2, other.y2, other.z1, other.z2);\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, const EdgeConstraint& c) {\n    return os << \"EC(\" << c.time << \",\" << c.x1 << \",\" << c.y1 << \",\" << c.z1 << \",\"\n              << c.x2 << \",\" << c.y2 << c.z2 << \")\";\n  }\n};\n\nnamespace std {\ntemplate <>\nstruct hash<EdgeConstraint> {\n  size_t operator()(const EdgeConstraint& s) const {\n    size_t seed = 0;\n    boost::hash_combine(seed, s.time);\n    boost::hash_combine(seed, s.x1);\n    boost::hash_combine(seed, s.y1);\n    boost::hash_combine(seed, s.x2);\n    boost::hash_combine(seed, s.y2);\n    boost::hash_combine(seed, s.z1);\n    boost::hash_combine(seed, s.z2);\n    return seed;\n  }\n};\n}  // namespace std\n\nstruct Constraints {\n  std::unordered_set<VertexConstraint> vertexConstraints;\n  std::unordered_set<EdgeConstraint> edgeConstraints;\n\n  void add(const Constraints& other) {\n    vertexConstraints.insert(other.vertexConstraints.begin(),\n                             other.vertexConstraints.end());\n    edgeConstraints.insert(other.edgeConstraints.begin(),\n                           other.edgeConstraints.end());\n  }\n\n  bool overlap(const Constraints& other) {\n    std::vector<VertexConstraint> vertexIntersection;\n    std::vector<EdgeConstraint> edgeIntersection;\n    std::set_intersection(vertexConstraints.begin(), vertexConstraints.end(),\n                          other.vertexConstraints.begin(),\n                          other.vertexConstraints.end(),\n                          std::back_inserter(vertexIntersection));\n    std::set_intersection(edgeConstraints.begin(), edgeConstraints.end(),\n                          other.edgeConstraints.begin(),\n                          other.edgeConstraints.end(),\n                          std::back_inserter(edgeIntersection));\n    return !vertexIntersection.empty() || !edgeIntersection.empty();\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, const Constraints& c) {\n    for (const auto& vc : c.vertexConstraints) {\n      os << vc << std::endl;\n    }\n    for (const auto& ec : c.edgeConstraints) {\n      os << ec << std::endl;\n    }\n    return os;\n  }\n};\n\nstruct Location {\n  Location(int x, int y, int z) : x(x), y(y), z(z) {}\n  int x;\n  int y;\n  int z;\n\n  bool operator<(const Location& other) const {\n    return std::tie(x, y, z) < std::tie(other.x, other.y, other.z);\n  }\n\n  bool operator==(const Location& other) const {\n    return std::tie(x, y, z) == std::tie(other.x, other.y, other.z);\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, const Location& c) {\n    return os << \"(\" << c.x << \",\" << c.y << c.z << \")\";\n  }\n};\n\nnamespace std {\ntemplate <>\nstruct hash<Location> {\n  size_t operator()(const Location& s) const {\n    size_t seed = 0;\n    boost::hash_combine(seed, s.x);\n    boost::hash_combine(seed, s.y);\n    boost::hash_combine(seed, s.z);\n    return seed;\n  }\n};\n}  // namespace std\n\n///\nclass Environment {\n public:\n  Environment(size_t dimx, size_t dimy, size_t dimz,\n              std::unordered_set<Location> obstacles,\n              std::vector<Location> goals)\n      : m_dimx(dimx),\n        m_dimy(dimy),\n        m_dimz(dimz),\n        m_obstacles(std::move(obstacles)),\n        m_goals(std::move(goals)),\n        m_agentIdx(0),\n        m_constraints(nullptr),\n        m_lastGoalConstraint(-1),\n        m_highLevelExpanded(0),\n        m_lowLevelExpanded(0) {}\n\n  Environment(const Environment&) = delete;\n  Environment& operator=(const Environment&) = delete;\n\n  //find last goal constraint!\n  void setLowLevelContext(size_t agentIdx, const Constraints* constraints) {\n    assert(constraints);\n    m_agentIdx = agentIdx;\n    m_constraints = constraints;\n    m_lastGoalConstraint = -1;\n    for (const auto& vc : constraints->vertexConstraints) {\n      if (vc.x == m_goals[m_agentIdx].x && vc.y == m_goals[m_agentIdx].y && vc.z == m_goals[m_agentIdx].z) {\n        m_lastGoalConstraint = std::max(m_lastGoalConstraint, vc.time);\n      }\n    }\n  }\n\n  int admissibleHeuristic(const State& s) {\n    return std::abs(s.x - m_goals[m_agentIdx].x) +\n           std::abs(s.y - m_goals[m_agentIdx].y) +\n           std::abs(s.z - m_goals[m_agentIdx].z);\n  }\n\n  // low-level, get numConflict(equal state) from given solution\n  int focalStateHeuristic(\n      const State& s, int /*gScore*/,\n      const std::vector<PlanResult<State, Action, int> >& solution) {\n    int numConflicts = 0;\n    for (size_t i = 0; i < solution.size(); ++i) {\n      if (i != m_agentIdx && !solution[i].states.empty()) {\n        State state2 = getState(i, solution, s.time);\n        if (s.equalExceptTime(state2)) {\n          ++numConflicts;\n        }\n      }\n    }\n    return numConflicts;\n  }\n\n  // low-level, get numConflict(s1a <-> s1b) from given solution\n  int focalTransitionHeuristic(\n      const State& s1a, const State& s1b, int /*gScoreS1a*/, int /*gScoreS1b*/,\n      const std::vector<PlanResult<State, Action, int> >& solution) {\n    int numConflicts = 0;\n    for (size_t i = 0; i < solution.size(); ++i) {\n      if (i != m_agentIdx && !solution[i].states.empty()) {\n        State s2a = getState(i, solution, s1a.time);\n        State s2b = getState(i, solution, s1b.time);\n        if (s1a.equalExceptTime(s2b) && s1b.equalExceptTime(s2a)) {\n          ++numConflicts;\n        }\n      }\n    }\n    return numConflicts;\n  }\n\n  // Count all conflicts\n  int focalHeuristic(\n      const std::vector<PlanResult<State, Action, int> >& solution) {\n    int numConflicts = 0;\n\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\n    for (int t = 0; t < max_t; ++t) {\n      // check drive-drive vertex 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.equalExceptTime(state2)) {\n            ++numConflicts;\n          }\n        }\n      }\n      // drive-drive edge (swap)\n      for (size_t i = 0; i < solution.size(); ++i) {\n        State state1a = getState(i, solution, t);\n        State state1b = getState(i, solution, t + 1);\n        for (size_t j = i + 1; j < solution.size(); ++j) {\n          State state2a = getState(j, solution, t);\n          State state2b = getState(j, solution, t + 1);\n          if (state1a.equalExceptTime(state2b) &&\n              state1b.equalExceptTime(state2a)) {\n            ++numConflicts;\n          }\n        }\n      }\n    }\n    return numConflicts;\n  }\n\n  bool isSolution(const State& s) {\n    return s.x == m_goals[m_agentIdx].x && s.y == m_goals[m_agentIdx].y && s.z == m_goals[m_agentIdx].z &&\n           s.time > m_lastGoalConstraint;\n  }\n\n  void getNeighbors(const State& s,\n                    std::vector<Neighbor<State, Action, int> >& neighbors) {\n    // std::cout << \"#VC \" << constraints.vertexConstraints.size() << std::endl;\n    // for(const auto& vc : constraints.vertexConstraints) {\n    //   std::cout << \"  \" << vc.time << \",\" << vc.x << \",\" << vc.y << \",\" << vc.z <<\n    //   std::endl;\n    // }\n    neighbors.clear();\n    {\n      State n(s.time + 1, s.x, s.y, s.z);\n      if (stateValid(n) && transitionValid(s, n)) {\n        neighbors.emplace_back(\n            Neighbor<State, Action, int>(n, Action::Wait, 1));\n      }\n    }\n    {\n      State n(s.time + 1, s.x - 1, s.y, s.z);\n      if (stateValid(n) && transitionValid(s, n)) {\n        neighbors.emplace_back(\n            Neighbor<State, Action, int>(n, Action::Left, 1));\n      }\n    }\n    {\n      State n(s.time + 1, s.x + 1, s.y, s.z);\n      if (stateValid(n) && transitionValid(s, n)) {\n        neighbors.emplace_back(\n            Neighbor<State, Action, int>(n, Action::Right, 1));\n      }\n    }\n    {\n      State n(s.time + 1, s.x, s.y + 1, s.z);\n      if (stateValid(n) && transitionValid(s, n)) {\n        neighbors.emplace_back(\n            Neighbor<State, Action, int>(n, Action::Up, 1));\n      }\n    }\n    {\n      State n(s.time + 1, s.x, s.y - 1, s.z);\n      if (stateValid(n) && transitionValid(s, n)) {\n        neighbors.emplace_back(\n            Neighbor<State, Action, int>(n, Action::Down, 1));\n      }\n    }\n    {\n      State n(s.time + 1, s.x, s.y, s.z + 1);\n      if (stateValid(n) && transitionValid(s, n)) {\n        neighbors.emplace_back(\n            Neighbor<State, Action, int>(n, Action::Top, 1));\n      }\n    }\n    {\n      State n(s.time + 1, s.x, s.y, s.z - 1);\n      if (stateValid(n) && transitionValid(s, n)) {\n        neighbors.emplace_back(\n            Neighbor<State, Action, int>(n, Action::Bottom, 1));\n      }\n    }\n  }\n\n  bool getFirstConflict(\n      const std::vector<PlanResult<State, Action, int> >& 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\n    for (int t = 0; t < max_t; ++t) {\n      // check drive-drive vertex 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.equalExceptTime(state2)) {\n            result.time = t;\n            result.agent1 = i;\n            result.agent2 = j;\n            result.type = Conflict::Vertex;\n            result.x1 = state1.x;\n            result.y1 = state1.y;\n            result.z1 = state1.z;\n            // std::cout << \"VC \" << t << \",\" << state1.x << \",\" << state1.y << \",\" << state1.z <<\n            // std::endl;\n            return true;\n          }\n        }\n      }\n      // drive-drive edge (swap)\n      for (size_t i = 0; i < solution.size(); ++i) {\n        State state1a = getState(i, solution, t);\n        State state1b = getState(i, solution, t + 1);\n        for (size_t j = i + 1; j < solution.size(); ++j) {\n          State state2a = getState(j, solution, t);\n          State state2b = getState(j, solution, t + 1);\n          if (state1a.equalExceptTime(state2b) &&\n              state1b.equalExceptTime(state2a)) {\n            result.time = t;\n            result.agent1 = i;\n            result.agent2 = j;\n            result.type = Conflict::Edge;\n            result.x1 = state1a.x;\n            result.y1 = state1a.y;\n            result.z1 = state1a.z;\n            result.x2 = state1b.x;\n            result.y2 = state1b.y;\n            result.z2 = state1b.z;\n            return true;\n          }\n        }\n      }\n    }\n\n    return false;\n  }\n\n  void createConstraintsFromConflict(\n      const Conflict& conflict, std::map<size_t, Constraints>& constraints) {\n    if (conflict.type == Conflict::Vertex) {\n      Constraints c1;\n      c1.vertexConstraints.emplace(\n          VertexConstraint(conflict.time, conflict.x1, conflict.y1, conflict.z1));\n      constraints[conflict.agent1] = c1;\n      constraints[conflict.agent2] = c1;\n    } else if (conflict.type == Conflict::Edge) {\n      Constraints c1;\n      c1.edgeConstraints.emplace(EdgeConstraint(\n          conflict.time, conflict.x1, conflict.y1, conflict.z1, conflict.x2, conflict.y2, conflict.z2));\n      constraints[conflict.agent1] = c1;\n      Constraints c2;\n      c2.edgeConstraints.emplace(EdgeConstraint(\n          conflict.time, conflict.x2, conflict.y2, conflict.z2, conflict.x1, conflict.y1, conflict.z1));\n      constraints[conflict.agent2] = c2;\n    }\n  }\n\n  void onExpandHighLevelNode(int /*cost*/) { m_highLevelExpanded++; }\n\n  void onExpandLowLevelNode(const State& /*s*/, int /*fScore*/,\n                            int /*gScore*/) {\n    m_lowLevelExpanded++;\n  }\n\n  int highLevelExpanded() { return m_highLevelExpanded; }\n\n  int lowLevelExpanded() const { return m_lowLevelExpanded; }\n\n private:\n  State getState(size_t agentIdx,\n                 const std::vector<PlanResult<State, Action, int> >& 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    assert(m_constraints);\n    const auto& con = m_constraints->vertexConstraints;\n    return s.x >= 0 && s.x < m_dimx && s.y >= 0 && s.y < m_dimy && s.z >= 0 && s.z < m_dimz &&\n           m_obstacles.find(Location(s.x, s.y, s.z)) == m_obstacles.end() &&\n           con.find(VertexConstraint(s.time, s.x, s.y, s.z)) == con.end();\n  }\n\n  bool transitionValid(const State& s1, const State& s2) {\n    assert(m_constraints);\n    const auto& con = m_constraints->edgeConstraints;\n    return con.find(EdgeConstraint(s1.time, s1.x, s1.y, s1.z, s2.x, s2.y, s2.z)) ==\n           con.end();\n  }\n\n private:\n  int m_dimx;\n  int m_dimy;\n  int m_dimz;\n  std::unordered_set<Location> m_obstacles;\n  std::vector<Location> m_goals;\n  size_t m_agentIdx;\n  const Constraints* m_constraints;\n  int m_lastGoalConstraint;\n  int m_highLevelExpanded;\n  int m_lowLevelExpanded;\n};\n\nint main(int argc, char* argv[]) {\n  namespace po = boost::program_options;\n  // Declare the supported options.\n  po::options_description desc(\"Allowed options\");\n  std::string inputFile;\n  std::string outputFile;\n  float w;\n  desc.add_options()(\"help\", \"produce help message\")(\n      \"input,i\", po::value<std::string>(&inputFile)->required(),\n      \"input file (YAML)\")(\"output,o\",\n                           po::value<std::string>(&outputFile)->required(),\n                           \"output file (YAML)\")(\n      \"suboptimality,w\", po::value<float>(&w)->default_value(1.0),\n      \"suboptimality bound\");\n\n  try {\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\") != 0u) {\n      std::cout << desc << \"\\n\";\n      return 0;\n    }\n  } catch (po::error& e) {\n    std::cerr << e.what() << std::endl << std::endl;\n    std::cerr << desc << std::endl;\n    return 1;\n  }\n\n  YAML::Node config = YAML::LoadFile(inputFile);\n\n  std::unordered_set<Location> obstacles;\n  std::vector<Location> goals;\n  std::vector<State> startStates;\n\n  const auto& dim = config[\"map\"][\"dimensions\"];\n  int dimx = dim[0].as<int>();\n  int dimy = dim[1].as<int>();\n  int dimz = dim[2].as<int>();\n\n  for (const auto& node : config[\"map\"][\"obstacles\"]) {\n    obstacles.insert(Location(node[0].as<int>(), node[1].as<int>(), node[2].as<int>()));\n  }\n\n  for (const auto& node : config[\"agents\"]) {\n    const auto& start = node[\"start\"];\n    const auto& goal = node[\"goal\"];\n    startStates.emplace_back(State(0, start[0].as<int>(), start[1].as<int>(), start[2].as<int>()));\n    // std::cout << \"s: \" << startStates.back() << std::endl;\n    goals.emplace_back(Location(goal[0].as<int>(), goal[1].as<int>(), goal[2].as<int>()));\n  }\n\n  Environment mapf(dimx, dimy, dimz, obstacles, goals);\n  ECBS<State, Action, int, Conflict, Constraints, Environment> cbs(mapf, w);\n  std::vector<PlanResult<State, Action, int> > solution;\n\n  Timer timer;\n  bool success = cbs.search(startStates, solution);\n  timer.stop();\n\n  if (success) {\n    std::cout << \"Planning successful! \" << std::endl;\n    int cost = 0;\n    int makespan = 0;\n    for (const auto& s : solution) {\n      cost += s.cost;\n      makespan = std::max<int>(makespan, s.cost);\n    }\n\n    std::ofstream out(outputFile);\n    out << \"statistics:\" << std::endl;\n    out << \"  cost: \" << cost << std::endl;\n    out << \"  makespan: \" << makespan << std::endl;\n    out << \"  runtime: \" << timer.elapsedSeconds() << std::endl;\n    out << \"  highLevelExpanded: \" << mapf.highLevelExpanded() << std::endl;\n    out << \"  lowLevelExpanded: \" << mapf.lowLevelExpanded() << std::endl;\n    out << \"schedule:\" << std::endl;\n    for (size_t a = 0; a < solution.size(); ++a) {\n      // std::cout << \"Solution for: \" << a << std::endl;\n      // for (size_t i = 0; i < solution[a].actions.size(); ++i) {\n      //   std::cout << solution[a].states[i].second << \": \" <<\n      //   solution[a].states[i].first << \"->\" << solution[a].actions[i].first\n      //   << \"(cost: \" << solution[a].actions[i].second << \")\" << std::endl;\n      // }\n      // std::cout << solution[a].states.back().second << \": \" <<\n      // solution[a].states.back().first << std::endl;\n\n      out << \"  agent\" << a << \":\" << std::endl;\n      for (const auto& state : solution[a].states) {\n        out << \"    - x: \" << state.first.x << std::endl\n            << \"      y: \" << state.first.y << std::endl\n            << \"      z: \" << state.first.z << std::endl\n            << \"      t: \" << state.second << std::endl;\n      }\n    }\n  } else {\n    std::cout << \"Planning NOT successful!\" << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "b4f4f1313cc17d917d7cc94bf33630c60bfc3159", "size": 20483, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "multi_robot_traj_planner/third_party/ecbs/src/ecbs.cpp", "max_stars_repo_name": "gaows123/multi_robot_traj_planner", "max_stars_repo_head_hexsha": "28b02ae174895461149f15cb398b0892adcc3c45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 111.0, "max_stars_repo_stars_event_min_datetime": "2020-12-15T08:04:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T04:31:39.000Z", "max_issues_repo_path": "multi_robot_traj_planner/third_party/ecbs/src/ecbs.cpp", "max_issues_repo_name": "KiddoSansai/multi_robot_traj_planner", "max_issues_repo_head_hexsha": "9b9afda08fa7f981426a43358e01f1bc8efdca0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-31T12:33:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-08T15:42:12.000Z", "max_forks_repo_path": "multi_robot_traj_planner/third_party/ecbs/src/ecbs.cpp", "max_forks_repo_name": "KiddoSansai/multi_robot_traj_planner", "max_forks_repo_head_hexsha": "9b9afda08fa7f981426a43358e01f1bc8efdca0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-12-15T08:04:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T08:42:48.000Z", "avg_line_length": 30.6173393124, "max_line_length": 108, "alphanum_fraction": 0.5648586633, "num_tokens": 5692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2591910291368992}}
{"text": "/**\n * @file kmedoids_ucb.cpp\n * @date 2020-06-10\n *\n * This file contains the primary C++ implementation of the BanditPAM code.\n *\n */\n#include \"kmedoids_ucb.hpp\"\n\n#include <carma.h>\n#include <armadillo>\n#include <unordered_map>\n#include <regex>\n//#include <sstream>\n\n/**\n *  \\brief Class implementation for running KMedoids methods.\n *\n *  KMedoids class. Creates a KMedoids object that can be used to find the medoids\n *  for a particular set of input data.\n *\n *  @param n_medoids Number of medoids/clusters to create\n *  @param algorithm Algorithm used to find medoids; options are \"BanditPAM\" for\n *  the \"Bandit-PAM\" algorithm, or \"naive\" to use the naive method\n *  @param verbosity Verbosity of the algorithm, 0 will have no log file\n *  emitted, 1 will emit a log file\n *  @param max_iter The maximum number of iterations the algorithm runs for\n *  @param logFilename The name of the output log file\n */\nKMedoids::KMedoids(int n_medoids, std::string algorithm, int verbosity,\n                                          int max_iter, std::string logFilename\n    ): n_medoids(n_medoids),\n       algorithm(algorithm),\n       max_iter(max_iter),\n       verbosity(verbosity),\n       logFilename(logFilename) {\n  KMedoids::checkAlgorithm(algorithm);\n}\n\n/**\n *  \\brief Destroys KMedoids object.\n *\n *  Destructor for the KMedoids class.\n */\nKMedoids::~KMedoids() {;}\n\n/**\n *  \\brief Checks whether algorithm input is valid\n *\n *  Checks whether the user's selected algorithm is a valid option.\n *\n *  @param algorithm Name of the algorithm input by the user.\n */\nvoid KMedoids::checkAlgorithm(std::string algorithm) {\n  if (algorithm == \"BanditPAM\") {\n    fitFn = &KMedoids::fit_bpam;\n  } else if (algorithm == \"naive\") {\n    fitFn = &KMedoids::fit_naive;\n  } else {\n    throw \"unrecognized algorithm\";\n  }\n}\n\n/**\n *  \\brief Returns the final medoids\n *\n *  Returns the final medoids at the end of the SWAP step after KMedoids::fit\n *  has been called.\n */\narma::rowvec KMedoids::getMedoidsFinal() {\n  return medoid_indices_final;\n}\n\n/**\n *  \\brief Returns the build medoids\n *\n *  Returns the build medoids at the end of the BUILD step after KMedoids::fit\n *  has been called.\n */\narma::rowvec KMedoids::getMedoidsBuild() {\n  return medoid_indices_build;\n}\n\n/**\n *  \\brief Returns the medoid assignments for each datapoint\n *\n *  Returns the medoid each input datapoint is assigned to after KMedoids::fit\n *  has been called and the final medoids have been identified\n */\narma::rowvec KMedoids::getLabels() {\n  return labels;\n}\n\n/**\n *  \\brief Returns the number of swap steps\n *\n *  Returns the number of SWAP steps completed during the last call to\n *  KMedoids::fit\n */\nint KMedoids::getSteps() {\n  return steps;\n}\n\n/**\n *  \\brief Sets the loss function\n *\n *  Sets the loss function used during KMedoids::fit\n *\n *  @param loss Loss function to be used e.g. L2\n */\nvoid KMedoids::setLossFn(std::string loss) {\n  if (std::regex_match(loss, std::regex(\"L\\\\d*\"))) {\n      loss = loss.substr(1);\n  }\n  try {\n    if (loss == \"manhattan\") {\n        lossFn = &KMedoids::manhattan;\n    } else if (loss == \"cos\") {\n        lossFn = &KMedoids::cos;\n    } else if (loss == \"inf\") {\n        lossFn = &KMedoids::LINF;\n    } else if (std::isdigit(loss.at(0))) {\n        lossFn = &KMedoids::LP;\n        lp     = atoi(loss.c_str());\n    } else {\n        throw std::invalid_argument(\"error: unrecognized loss function\");\n    }\n  } catch (std::invalid_argument& e) {\n      std::cout << e.what() << std::endl;\n    }\n}\n\n/**\n *  \\brief Returns the number of medoids\n *\n *  Returns the number of medoids to be identified during KMedoids::fit\n */\nint KMedoids::getNMedoids() {\n  return n_medoids;\n}\n\n/**\n *  \\brief Sets the number of medoids\n *\n *  Sets the number of medoids to be identified during KMedoids::fit\n */\nvoid KMedoids::setNMedoids(int new_num) {\n  n_medoids = new_num;\n}\n\n/**\n *  \\brief Returns the algorithm for KMedoids\n *\n *  Returns the algorithm used for identifying the medoids during KMedoids::fit\n */\nstd::string KMedoids::getAlgorithm() {\n  return algorithm;\n}\n\n/**\n *  \\brief Sets the algorithm for KMedoids\n *\n *  Sets the algorithm used for identifying the medoids during KMedoids::fit\n *\n *  @param new_alg New algorithm to use\n */\nvoid KMedoids::setAlgorithm(std::string new_alg) {\n  algorithm = new_alg;\n}\n\n/**\n *  \\brief Returns the verbosity for KMedoids\n *\n *  Returns the verbosity used during KMedoids::fit, with 0 not creating a\n *  logfile, and >0 creating a detailed logfile.\n */\nint KMedoids::getVerbosity() {\n  return verbosity;\n}\n\n/**\n *  \\brief Sets the verbosity for KMedoids\n *\n *  Sets the verbosity used during KMedoids::fit, with 0 not creating a\n *  logfile, and >0 creating a detailed logfile.\n *\n *  @param new_ver New verbosity to use\n */\nvoid KMedoids::setVerbosity(int new_ver) {\n  verbosity = new_ver;\n}\n\n/**\n *  \\brief Returns the maximum number of iterations for KMedoids\n *\n *  Returns the maximum number of iterations that can be run during\n *  KMedoids::fit\n */\nint KMedoids::getMaxIter() {\n  return max_iter;\n}\n\n/**\n *  \\brief Sets the maximum number of iterations for KMedoids\n *\n *  Sets the maximum number of iterations that can be run during KMedoids::fit\n *\n *  @param new_max New maximum number of iterations to use\n */\nvoid KMedoids::setMaxIter(int new_max) {\n  max_iter = new_max;\n}\n\n/**\n *  \\brief Returns the log filename for KMedoids\n *\n *  Returns the name of the logfile that will be output at the end of\n *  KMedoids::fit if verbosity is >0\n */\nstd::string KMedoids::getLogfileName() {\n  return logFilename;\n}\n\n/**\n *  \\brief Sets the log filename for KMedoids\n *\n *  Sets the name of the logfile that will be output at the end of\n *  KMedoids::fit if verbosity is >0\n *\n *  @param new_lname New logfile name\n */\nvoid KMedoids::setLogFilename(std::string new_lname) {\n  logFilename = new_lname;\n}\n\n/**\n * \\brief Finds medoids for the input data under identified loss function\n *\n * Primary function of the KMedoids class. Identifies medoids for input dataset\n * after both the SWAP and BUILD steps, and outputs logs if verbosity is >0\n *\n * @param input_data Input data to find the medoids of\n * @param loss The loss function used during medoid computation\n */\nvoid KMedoids::fit(arma::mat input_data, std::string loss) {\n  KMedoids::setLossFn(loss);\n  (this->*fitFn)(input_data);\n  if (verbosity > 0) {\n      logHelper.init(logFilename);\n      logHelper.writeProfile(medoid_indices_build, medoid_indices_final, steps,\n                                                        logHelper.loss_swap.back());\n      logHelper.close();\n  }\n}\n\n\n/**\n * \\brief Runs naive PAM algorithm.\n *\n * Run the naive PAM algorithm to identify a dataset's medoids.\n *\n * @param input_data Input data to find the medoids of\n */\nvoid KMedoids::fit_naive(arma::mat input_data) {\n  data = input_data;\n  data = arma::trans(data);\n  arma::rowvec medoid_indices(n_medoids);\n  // runs build step\n  KMedoids::build_naive(data, medoid_indices);\n  steps = 0;\n\n  medoid_indices_build = medoid_indices;\n  arma::rowvec assignments(data.n_cols);\n  size_t i = 0;\n  bool medoidChange = true;\n  while (i < max_iter && medoidChange) {\n    auto previous(medoid_indices);\n    // runs swa step as necessary\n    KMedoids::swap_naive(data, medoid_indices, assignments);\n    medoidChange = arma::any(medoid_indices != previous);\n    i++;\n  }\n  medoid_indices_final = medoid_indices;\n  labels = assignments;\n  steps = i;\n}\n\n/**\n * \\brief Build step for the naive algorithm\n *\n * Runs build step for the naive PAM algorithm. Loops over all datapoint and\n * checks its distance from every other datapoint in the dataset, then checks if\n * the total cost is less than that of the medoid (if a medoid exists yet).\n *\n * @param data Transposed input data to find the medoids of\n * @param medoid_indices Uninitialized array of medoids that is modified in place\n * as medoids are identified\n */\nvoid KMedoids::build_naive(\n  arma::mat& data, \n  arma::rowvec& medoid_indices)\n{ \n  size_t N = data.n_cols;\n  int p = (buildConfidence * N); // reciprocal\n  bool use_absolute = true;\n  arma::rowvec estimates(N, arma::fill::zeros);\n  arma::rowvec best_distances(N);\n  best_distances.fill(std::numeric_limits<double>::infinity());\n  arma::rowvec sigma(N); // standard deviation of induced losses on reference points\n  for (size_t k = 0; k < n_medoids; k++) {\n    double minDistance = std::numeric_limits<double>::infinity();\n    int best = 0;\n    KMedoids::build_sigma(\n           data, best_distances, sigma, batchSize, use_absolute); // computes std dev amongst batch of reference points\n    // fixes a base datapoint\n    for (int i = 0; i < data.n_cols; i++) {\n      double total = 0;\n      for (size_t j = 0; j < data.n_cols; j++) {\n        // computes distance between base and all other points\n        double cost = (this->*lossFn)(data, i, j);\n        for (size_t medoid = 0; medoid < k; medoid++) {\n          double current = (this->*lossFn)(data, medoid_indices(medoid), j);\n          // compares this for cost of the medoid\n          if (current < cost) {\n            cost = current;\n          }\n        }\n        total += cost;\n      }\n      if (total < minDistance) {\n        minDistance = total;\n        best = i;\n      }\n    }\n    // updates the medoid index for that of lowest cost.\n    medoid_indices(k) = best;\n\n    // don't need to do this on final iteration\n    for (size_t l = 0; l < N; l++) {\n        double cost = (this->*lossFn)(data, l, medoid_indices(k));\n        if (cost < best_distances(l)) {\n            best_distances(l) = cost;\n        }\n    }\n    use_absolute = false; // use difference of loss for sigma and sampling,\n                          // not absolute\n    logHelper.loss_build.push_back(minDistance/N);\n    logHelper.p_build.push_back((float)1/(float)p);\n    logHelper.comp_exact_build.push_back(N);\n  }\n}\n\n/**\n * \\brief Swap step for the naive algorithm\n *\n * Runs build step for the naive PAM algorithm. Loops over all datapoint and\n * checks its distance from every other datapoint in the dataset, then checks if\n * the total cost is less than that of the medoid.\n *\n * @param data Transposed input data to find the medoids of\n * @param medoid_indices Array of medoid indices created from the build step\n * that is modified in place as better medoids are identified\n * @param assignments Uninitialized array of indices corresponding to each\n * datapoint assigned the index of the medoid it is closest to\n */\nvoid KMedoids::swap_naive(\n  arma::mat& data, \n  arma::rowvec& medoid_indices,\n  arma::rowvec& assignments)\n{\n  double minDistance = std::numeric_limits<double>::infinity();\n  size_t best = 0;\n  size_t medoid_to_swap = 0;\n  size_t N = data.n_cols;\n  int p = (N * n_medoids * swapConfidence); // reciprocal\n  arma::mat sigma(n_medoids, N, arma::fill::zeros);\n  arma::rowvec best_distances(N);\n  arma::rowvec second_distances(N);\n\n  // calculate quantities needed for swap, best_distances and sigma\n  calc_best_distances_swap(\n    data, medoid_indices, best_distances, second_distances, assignments);\n\n  swap_sigma(data,\n              sigma,\n              batchSize,\n              best_distances,\n              second_distances,\n              assignments);\n  \n  // write the sigma distribution to logfile\n  sigma_log(sigma);\n\n  // iterate across the current medoids\n  for (size_t k = 0; k < n_medoids; k++) {\n    // for every point in our dataset, let it serve as a \"base\" point\n    for (size_t i = 0; i < data.n_cols; i++) {\n      double total = 0;\n      for (size_t j = 0; j < data.n_cols; j++) {\n        // compute distance between base point and every other datapoint\n        double cost = (this->*lossFn)(data, i, j);\n        for (size_t medoid = 0; medoid < n_medoids; medoid++) {\n          if (medoid == k) {\n            continue;\n          }\n          double current = (this->*lossFn)(data, medoid_indices(medoid), j);\n          if (current < cost) {\n            cost = current;\n          }\n        }\n        total += cost;\n      }\n      // if total distance for new base point is better than that of the medoid,\n      // update the best index identified so far\n      if (total < minDistance) {\n        minDistance = total;\n        best = i;\n        medoid_to_swap = k;\n      }\n    }\n  }\n  medoid_indices(medoid_to_swap) = best;\n  logHelper.loss_swap.push_back(minDistance/N);\n  logHelper.p_swap.push_back((float)1/(float)p);\n  logHelper.comp_exact_swap.push_back(N*n_medoids);\n}\n\n/**\n * \\brief Runs BanditPAM algorithm.\n *\n * Run the BanditPAM algorithm to identify a dataset's medoids.\n *\n * @param input_data Input data to find the medoids of\n */\nvoid KMedoids::fit_bpam(arma::mat input_data) {\n  data = input_data;\n  data = arma::trans(data);\n  arma::mat medoids_mat(data.n_rows, n_medoids);\n  arma::rowvec medoid_indices(n_medoids);\n  // runs build step\n  KMedoids::build(data, medoid_indices, medoids_mat);\n  steps = 0;\n\n  medoid_indices_build = medoid_indices;\n  arma::rowvec assignments(data.n_cols);\n  // runs swap step\n  KMedoids::swap(data, medoid_indices, medoids_mat, assignments);\n  medoid_indices_final = medoid_indices;\n  labels = assignments;\n}\n\n/**\n * \\brief Build step for BanditPAM\n *\n * Runs build step for the BanditPAM algorithm. Draws batch sizes with replacement\n * from reference set, and uses the estimated reward of the potential medoid\n * solutions on the reference set to update the reward confidence intervals and\n * accordingly narrow the solution set.\n *\n * @param data Transposed input data to find the medoids of\n * @param medoid_indices Uninitialized array of medoids that is modified in place\n * as medoids are identified\n * @param medoids Matrix of possible medoids that is updated as the bandit\n * learns which datapoints will be unlikely to be good candidates\n */\nvoid KMedoids::build(\n  arma::mat& data,\n  arma::rowvec& medoid_indices,\n  arma::mat& medoids)\n{\n    // Parameters\n    size_t N = data.n_cols;\n    arma::rowvec N_mat(N);\n    N_mat.fill(N);\n    int p = (buildConfidence * N); // reciprocal of\n    bool use_absolute = true;\n    arma::rowvec estimates(N, arma::fill::zeros);\n    arma::rowvec best_distances(N);\n    best_distances.fill(std::numeric_limits<double>::infinity());\n    arma::rowvec sigma(N); // standard deviation of induced losses on reference points\n    arma::urowvec candidates(\n      N,\n      arma::fill::ones); // one hot encoding of candidates -- points not filtered out yet\n    arma::rowvec lcbs(N);\n    arma::rowvec ucbs(N);\n    arma::rowvec T_samples(N, arma::fill::zeros); // number of times calculating induced loss for reference point\n    arma::rowvec exact_mask(N, arma::fill::zeros); // computed the loss exactly for this datapoint\n\n    for (size_t k = 0; k < n_medoids; k++) {\n        // instantiate medoids one-by-online\n        size_t step_count = 0;\n        candidates.fill(1);\n        T_samples.fill(0);\n        exact_mask.fill(0);\n        estimates.fill(0);\n        KMedoids::build_sigma(\n           data, best_distances, sigma, batchSize, use_absolute); // computes std dev amongst batch of reference points\n\n        while (arma::sum(candidates) > precision) { // while some candidates exist\n            arma::umat compute_exactly =\n              ((T_samples + batchSize) >= N_mat) != exact_mask;\n            if (arma::accu(compute_exactly) > 0) {\n                arma::uvec targets = find(compute_exactly);\n                logHelper.comp_exact_build.push_back(targets.n_rows);\n                arma::rowvec result =\n                  build_target(data, targets, N, best_distances, use_absolute); // induced loss for these targets over all reference points\n                estimates.cols(targets) = result;\n                ucbs.cols(targets) = result;\n                lcbs.cols(targets) = result;\n                exact_mask.cols(targets).fill(1);\n                T_samples.cols(targets) += N;\n                candidates.cols(targets).fill(0);\n            }\n            if (arma::sum(candidates) < precision) {\n                break;\n            }\n            arma::uvec targets = arma::find(candidates);\n            arma::rowvec result = build_target(\n              data, targets, batchSize, best_distances, use_absolute); // induced loss for the targets (sample)\n            estimates.cols(targets) =\n              ((T_samples.cols(targets) % estimates.cols(targets)) +\n               (result * batchSize)) /\n              (batchSize + T_samples.cols(targets)); // update the running average\n            T_samples.cols(targets) += batchSize;\n            arma::rowvec adjust(targets.n_rows);\n            adjust.fill(p);\n            adjust = arma::log(adjust);\n            arma::rowvec cb_delta =\n              sigma.cols(targets) %\n              arma::sqrt(adjust / T_samples.cols(targets));\n            ucbs.cols(targets) = estimates.cols(targets) + cb_delta;\n            lcbs.cols(targets) = estimates.cols(targets) - cb_delta;\n            candidates = (lcbs < ucbs.min()) && (exact_mask == 0);\n            step_count++;\n        }\n\n        medoid_indices.at(k) = lcbs.index_min();\n        medoids.unsafe_col(k) = data.unsafe_col(medoid_indices(k));\n\n        // don't need to do this on final iteration\n        for (size_t i = 0; i < N; i++) {\n            double cost = (this->*lossFn)(data, i, medoid_indices(k));\n            if (cost < best_distances(i)) {\n                best_distances(i) = cost;\n            }\n        }\n        use_absolute = false; // use difference of loss for sigma and sampling,\n                              // not absolute\n        logHelper.loss_build.push_back(arma::mean(arma::mean(best_distances)));\n        logHelper.p_build.push_back((float)1/(float)p);\n    }\n}\n\n/**\n * \\brief Calculates confidence intervals in build step\n *\n * Calculates the confidence intervals about the reward for each arm\n *\n * @param data Transposed input data to find the medoids of\n * @param sigma Dispersion paramater for each datapoint\n * @param batch_size Number of datapoints sampled for updating confidence\n * intervals\n * @param best_distances Array of best distances from each point to previous set\n * of medoids\n * @param use_aboslute Determines whether the absolute cost is added to the total\n */\nvoid KMedoids::build_sigma(\n  arma::mat& data,\n  arma::rowvec& best_distances,\n  arma::rowvec& sigma,\n  arma::uword batch_size,\n  bool use_absolute)\n{\n    size_t N = data.n_cols;\n    // without replacement, requires updated version of armadillo\n    arma::uvec tmp_refs = arma::randperm(N, batch_size);\n    arma::vec sample(batch_size);\n// for each possible swap\n#pragma omp parallel for\n    for (size_t i = 0; i < N; i++) {\n        // gather a sample of points\n        for (size_t j = 0; j < batch_size; j++) {\n            double cost = (this->*lossFn)(data, i, tmp_refs(j));\n            if (use_absolute) {\n                sample(j) = cost;\n            } else {\n                sample(j) = cost < best_distances(tmp_refs(j))\n                              ? cost\n                              : best_distances(tmp_refs(j));\n                sample(j) -= best_distances(tmp_refs(j));\n            }\n        }\n        sigma(i) = arma::stddev(sample);\n    }\n    arma::rowvec P = {0.25, 0.5, 0.75};\n    arma::rowvec Q = arma::quantile(sigma, P);\n    std::ostringstream sigma_out;\n    sigma_out << \"min: \" << arma::min(sigma)\n              << \", 25th: \" << Q(0)\n              << \", median: \" << Q(1)\n              << \", 75th: \" << Q(2)\n              << \", max: \" << arma::max(sigma)\n              << \", mean: \" << arma::mean(sigma);\n    logHelper.sigma_build.push_back(sigma_out.str());\n}\n\n/**\n * \\brief Estimates the mean reward for each arm in build step\n *\n * Estimates the mean reward (or loss) for each arm in the identified targets\n * in the build step and returns a list of the estimated reward.\n *\n * @param data Transposed input data to find the medoids of\n * @param target Set of target datapoints to be estimated\n * @param batch_size Number of datapoints sampled for updating confidence\n * intervals\n * @param best_distances Array of best distances from each point to previous set\n * of medoids\n * @param use_absolute Determines whether the absolute cost is added to the total\n */\narma::rowvec KMedoids::build_target(\n  arma::mat& data,\n  arma::uvec& target,\n  size_t batch_size,\n  arma::rowvec& best_distances,\n  bool use_absolute)\n{\n    size_t N = data.n_cols;\n    arma::rowvec estimates(target.n_rows, arma::fill::zeros);\n    arma::uvec tmp_refs = arma::randperm(N,\n                                   batch_size); // without replacement, requires\n                                                // updated version of armadillo\n#pragma omp parallel for\n    for (size_t i = 0; i < target.n_rows; i++) {\n        double total = 0;\n        for (size_t j = 0; j < tmp_refs.n_rows; j++) {\n            double cost =\n              (this->*lossFn)(data, tmp_refs(j), target(i));\n            if (use_absolute) {\n                total += cost;\n            } else {\n                total += cost < best_distances(tmp_refs(j))\n                           ? cost\n                           : best_distances(tmp_refs(j));\n                total -= best_distances(tmp_refs(j));\n            }\n        }\n        estimates(i) = total / batch_size;\n    }\n    return estimates;\n}\n\n/**\n * \\brief Swap step for BanditPAM\n *\n * Runs Swap step for the BanditPAM algorithm. Draws batch sizes with replacement\n * from reference set, and uses the estimated reward of the potential medoid\n * solutions on the reference set to update the reward confidence intervals and\n * accordingly narrow the solution set.\n *\n * @param data Transposed input data to find the medoids of\n * @param medoid_indices Array of medoid indices created from the build step\n * that is modified in place as better medoids are identified\n * @param medoids Matrix of possible medoids that is updated as the bandit\n * learns which datapoints will be unlikely to be good candidates\n * @param assignments Uninitialized array of indices corresponding to each\n * datapoint assigned the index of the medoid it is closest to\n */\nvoid KMedoids::swap(\n  arma::mat& data,\n  arma::rowvec& medoid_indices,\n  arma::mat& medoids,\n  arma::rowvec& assignments)\n{\n    size_t N = data.n_cols;\n    int p = (N * n_medoids * swapConfidence); // reciprocal\n\n    arma::mat sigma(n_medoids, N, arma::fill::zeros);\n\n    arma::rowvec best_distances(N);\n    arma::rowvec second_distances(N);\n    size_t iter = 0;\n    bool swap_performed = true;\n    arma::umat candidates(n_medoids, N, arma::fill::ones);\n    arma::umat exact_mask(n_medoids, N, arma::fill::zeros);\n    arma::mat estimates(n_medoids, N, arma::fill::zeros);\n    arma::mat lcbs(n_medoids, N);\n    arma::mat ucbs(n_medoids, N);\n    arma::umat T_samples(n_medoids, N, arma::fill::zeros);\n\n    // continue making swaps while loss is decreasing\n    while (swap_performed && iter < max_iter) {\n        iter++;\n\n        // calculate quantities needed for swap, best_distances and sigma\n        calc_best_distances_swap(\n          data, medoid_indices, best_distances, second_distances, assignments);\n\n        swap_sigma(data,\n                   sigma,\n                   batchSize,\n                   best_distances,\n                   second_distances,\n                   assignments);\n\n        candidates.fill(1);\n        exact_mask.fill(0);\n        estimates.fill(0);\n        T_samples.fill(0);\n\n        // while there is at least one candidate (double comparison issues)\n        while (arma::accu(candidates) > 0.5) {\n            calc_best_distances_swap(\n              data, medoid_indices, best_distances, second_distances, assignments);\n\n            // compute exactly if it's been samples more than N times and hasn't\n            // been computed exactly already\n            arma::umat compute_exactly =\n              ((T_samples + batchSize) >= N) != (exact_mask);\n            arma::uvec targets = arma::find(compute_exactly);\n\n            if (targets.size() > 0) {\n                logHelper.comp_exact_swap.push_back(targets.size());\n                arma::vec result = swap_target(data,\n                                               medoid_indices,\n                                               targets,\n                                               N,\n                                               best_distances,\n                                               second_distances,\n                                               assignments);\n                estimates.elem(targets) = result;\n                ucbs.elem(targets) = result;\n                lcbs.elem(targets) = result;\n                exact_mask.elem(targets).fill(1);\n                T_samples.elem(targets) += N;\n\n                candidates = (lcbs < ucbs.min()) && (exact_mask == 0);\n            }\n            if (arma::accu(candidates) < precision) {\n                break;\n            }\n            targets = arma::find(candidates);\n            arma::vec result = swap_target(data,\n                                           medoid_indices,\n                                           targets,\n                                           batchSize,\n                                           best_distances,\n                                           second_distances,\n                                           assignments);\n            estimates.elem(targets) =\n              ((T_samples.elem(targets) % estimates.elem(targets)) +\n               (result * batchSize)) /\n              (batchSize + T_samples.elem(targets));\n            T_samples.elem(targets) += batchSize;\n            arma::vec adjust(targets.n_rows);\n            adjust.fill(p);\n            adjust = arma::log(adjust);\n            arma::vec cb_delta = sigma.elem(targets) %\n                                 arma::sqrt(adjust / T_samples.elem(targets));\n\n            ucbs.elem(targets) = estimates.elem(targets) + cb_delta;\n            lcbs.elem(targets) = estimates.elem(targets) - cb_delta;\n            candidates = (lcbs < ucbs.min()) && (exact_mask == 0);\n            targets = arma::find(candidates);\n        }\n        // now switch medoids\n        arma::uword new_medoid = lcbs.index_min();\n        // extract medoid of swap\n        size_t k = new_medoid % medoids.n_cols;\n\n        // extract data point of swap\n        size_t n = new_medoid / medoids.n_cols;\n        swap_performed = medoid_indices(k) != n;\n        steps++;\n\n        medoid_indices(k) = n;\n        medoids.col(k) = data.col(medoid_indices(k));\n        calc_best_distances_swap(\n          data, medoid_indices, best_distances, second_distances, assignments);\n        sigma_log(sigma);\n        logHelper.loss_swap.push_back(arma::mean(arma::mean(best_distances)));\n        logHelper.p_swap.push_back((float)1/(float)p);\n    }\n}\n\n/**\n * \\brief Calculates distances in swap step\n *\n * Calculates the best and second best distances for each datapoint to one of\n * the medoids in the current medoid set.\n *\n * @param data Transposed input data to find the medoids of\n * @param medoid_indices Array of medoid indices corresponding to dataset entries\n * @param best_distances Array of best distances from each point to previous set\n * of medoids\n * @param second_best_distances Array of second smallest distances from each\n * point to previous set of medoids\n * @param assignments Assignments of datapoints to their closest medoid\n */\nvoid KMedoids::calc_best_distances_swap(\n  arma::mat& data,\n  arma::rowvec& medoid_indices,\n  arma::rowvec& best_distances,\n  arma::rowvec& second_distances,\n  arma::rowvec& assignments)\n{\n#pragma omp parallel for\n    for (size_t i = 0; i < data.n_cols; i++) {\n        double best = std::numeric_limits<double>::infinity();\n        double second = std::numeric_limits<double>::infinity();\n        for (size_t k = 0; k < medoid_indices.n_cols; k++) {\n            double cost = (this->*lossFn)(data, medoid_indices(k), i);\n            if (cost < best) {\n                assignments(i) = k;\n                second = best;\n                best = cost;\n            } else if (cost < second) {\n                second = cost;\n            }\n        }\n        best_distances(i) = best;\n        second_distances(i) = second;\n    }\n}\n\n/**\n * \\brief Estimates the mean reward for each arm in swap step\n *\n * Estimates the mean reward (or loss) for each arm in the identified targets\n * in the swap step and returns a list of the estimated reward.\n *\n * @param data Transposed input data to find the medoids of\n * @param sigma Dispersion paramater for each datapoint\n * @param targets Set of target datapoints to be estimated\n * @param batch_size Number of datapoints sampled for updating confidence\n * intervals\n * @param best_distances Array of best distances from each point to previous set\n * of medoids\n * @param second_best_distances Array of second smallest distances from each\n * point to previous set of medoids\n * @param assignments Assignments of datapoints to their closest medoid\n */\narma::vec KMedoids::swap_target(\n  arma::mat& data,\n  arma::rowvec& medoid_indices,\n  arma::uvec& targets,\n  size_t batch_size,\n  arma::rowvec& best_distances,\n  arma::rowvec& second_best_distances,\n  arma::rowvec& assignments)\n{\n    size_t N = data.n_cols;\n    arma::vec estimates(targets.n_rows, arma::fill::zeros);\n    arma::uvec tmp_refs = arma::randperm(N,\n                                   batch_size); // without replacement, requires\n                                                // updated version of armadillo\n\n// for each considered swap\n#pragma omp parallel for\n    for (size_t i = 0; i < targets.n_rows; i++) {\n        double total = 0;\n        // extract data point of swap\n        size_t n = targets(i) / medoid_indices.n_cols;\n        size_t k = targets(i) % medoid_indices.n_cols;\n        // calculate total loss for some subset of the data\n        for (size_t j = 0; j < batch_size; j++) {\n            double cost = (this->*lossFn)(data, n, tmp_refs(j));\n            if (k == assignments(tmp_refs(j))) {\n                if (cost < second_best_distances(tmp_refs(j))) {\n                    total += cost;\n                } else {\n                    total += second_best_distances(tmp_refs(j));\n                }\n            } else {\n                if (cost < best_distances(tmp_refs(j))) {\n                    total += cost;\n                } else {\n                    total += best_distances(tmp_refs(j));\n                }\n            }\n            total -= best_distances(tmp_refs(j));\n        }\n        estimates(i) = total / tmp_refs.n_rows;\n    }\n    return estimates;\n}\n\n/**\n * \\brief Calculates confidence intervals in swap step\n *\n * Calculates the confidence intervals about the reward for each arm\n *\n * @param data Transposed input data to find the medoids of\n * @param sigma Dispersion paramater for each datapoint\n * @param batch_size Number of datapoints sampled for updating confidence\n * intervals\n * @param best_distances Array of best distances from each point to previous set\n * of medoids\n * @param second_best_distances Array of second smallest distances from each\n * point to previous set of medoids\n * @param assignments Assignments of datapoints to their closest medoid\n */\nvoid KMedoids::swap_sigma(\n  arma::mat& data,\n  arma::mat& sigma,\n  size_t batch_size,\n  arma::rowvec& best_distances,\n  arma::rowvec& second_best_distances,\n  arma::rowvec& assignments)\n{\n    size_t N = data.n_cols;\n    size_t K = sigma.n_rows;\n    arma::uvec tmp_refs = arma::randperm(N,\n                                   batch_size); // without replacement, requires\n                                                // updated version of armadillo\n\n    arma::vec sample(batch_size);\n// for each considered swap\n#pragma omp parallel for\n    for (size_t i = 0; i < K * N; i++) {\n        // extract data point of swap\n        size_t n = i / K;\n        size_t k = i % K;\n\n        // calculate change in loss for some subset of the data\n        for (size_t j = 0; j < batch_size; j++) {\n            double cost = (this->*lossFn)(data, n,tmp_refs(j));\n\n            if (k == assignments(tmp_refs(j))) {\n                if (cost < second_best_distances(tmp_refs(j))) {\n                    sample(j) = cost;\n                } else {\n                    sample(j) = second_best_distances(tmp_refs(j));\n                }\n            } else {\n                if (cost < best_distances(tmp_refs(j))) {\n                    sample(j) = cost;\n                } else {\n                    sample(j) = best_distances(tmp_refs(j));\n                }\n            }\n            sample(j) -= best_distances(tmp_refs(j));\n        }\n        sigma(k, n) = arma::stddev(sample);\n    }\n}\n\n/**\n* \\brief Write the sigma distribution into logfile\n*\n* Calculates the statistical measures of the sigma distribution\n* and writes the results to the log file. \n*\n* @param sigma Dispersion paramater for each datapoint\n*/\nvoid KMedoids::sigma_log(arma::mat& sigma) {\n  arma::rowvec flat_sigma = sigma.as_row(); \n  arma::rowvec P = {0.25, 0.5, 0.75};\n  arma::rowvec Q = arma::quantile(flat_sigma, P);\n  std::ostringstream sigma_out;\n  sigma_out << \"min: \" << arma::min(flat_sigma)\n            << \", 25th: \" << Q(0)\n            << \", median: \" << Q(1)\n            << \", 75th: \" << Q(2)\n            << \", max: \" << arma::max(flat_sigma)\n            << \", mean: \" << arma::mean(flat_sigma);\n  logHelper.sigma_swap.push_back(sigma_out.str());\n};\n\n/**\n * \\brief Calculate loss for medoids\n *\n * Calculates the loss under the previously identified loss function of the\n * medoid indices.\n *\n * @param data Transposed input data to find the medoids of\n * @param medoid_indices Indices of the medoids in the dataset.\n */\ndouble KMedoids::calc_loss(\n  arma::mat& data,\n  arma::rowvec& medoid_indices)\n{\n    double total = 0;\n\n    for (size_t i = 0; i < data.n_cols; i++) {\n        double cost = std::numeric_limits<double>::infinity();\n        for (size_t k = 0; k < n_medoids; k++) {\n            double currCost = (this->*lossFn)(data, medoid_indices(k), i);\n            if (currCost < cost) {\n                cost = currCost;\n            }\n        }\n        total += cost;\n    }\n    return total;\n}\n\n// Loss and miscellaneous functions\n\n/**\n * \\brief LP loss\n *\n * Calculates the LP loss between the datapoints at index i and j of the dataset\n *\n * @param data Transposed input data to find the medoids of\n * @param i Index of first datapoint\n * @param j Index of second datapoint\n */\ndouble KMedoids::LP(arma::mat& data, int i, int j) const {\n    return arma::norm(data.col(i) - data.col(j), lp);\n}\n\n/**\n * \\brief L2 loss\n *\n * Calculates the L2 loss between the datapoints at index i and j of the dataset\n *\n * @param i Index of first datapoint\n * @param j Index of second datapoint\n */\n//double KMedoids::L2(int i, int j) const {\n//    return arma::norm(data.col(i) - data.col(j), 2);\n//}\n\n/**\n * \\brief cos loss\n *\n * Calculates the cosine loss between the datapoints at index i and j of the\n * dataset\n *\n * @param data Transposed input data to find the medoids of\n * @param i Index of first datapoint\n * @param j Index of second datapoint\n */\ndouble KMedoids::cos(arma::mat& data, int i, int j) const {\n    return arma::dot(data.col(i), data.col(j)) / (arma::norm(data.col(i))\n                                                    * arma::norm(data.col(j)));\n}\n\n/**\n * \\brief Manhattan loss\n *\n * Calculates the Manhattan loss between the datapoints at index i and j of the\n * dataset\n *\n * @param data Transposed input data to find the medoids of\n * @param i Index of first datapoint\n * @param j Index of second datapoint\n */\ndouble KMedoids::manhattan(arma::mat& data, int i, int j) const {\n    return arma::accu(arma::abs(data.col(i) - data.col(j)));\n}\n\n/**\n * \\brief L_INFINITY loss\n *\n * Calculates the Manhattan loss between the datapoints at index i and j of the\n * dataset\n *\n * @param data Transposed input data to find the medoids of\n * @param i Index of first datapoint\n * @param j Index of second datapoint\n */\ndouble KMedoids::LINF(arma::mat& data, int i, int j) const {\n    return arma::max(arma::abs(data.col(i) - data.col(j)));\n}\n", "meta": {"hexsha": "dc816d853b70622ed9906ca51f272955558c53bc", "size": 35994, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/kmedoids_ucb.cpp", "max_stars_repo_name": "dhaval737/BanditPAM", "max_stars_repo_head_hexsha": "a84d86f839dd824f0f1b562547b1282ca72af318", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kmedoids_ucb.cpp", "max_issues_repo_name": "dhaval737/BanditPAM", "max_issues_repo_head_hexsha": "a84d86f839dd824f0f1b562547b1282ca72af318", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kmedoids_ucb.cpp", "max_forks_repo_name": "dhaval737/BanditPAM", "max_forks_repo_head_hexsha": "a84d86f839dd824f0f1b562547b1282ca72af318", "max_forks_repo_licenses": ["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.7338331771, "max_line_length": 139, "alphanum_fraction": 0.6213535589, "num_tokens": 8726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.25919102195464}}
{"text": "/*\n  Copyright 2008 Larry Gritz and the other authors and contributors.\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  * 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 software's owners 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  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\n  (This is the Modified BSD License)\n*/\n\n/// \\file\n/// ImageBufAlgo functions for filtered transformations\n\n\n#include <boost/bind.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include <OpenEXR/half.h>\n#include <OpenEXR/ImathMatrix.h>\n#include <OpenEXR/ImathBox.h>\n\n#include <cmath>\n\n#include \"OpenImageIO/imagebuf.h\"\n#include \"OpenImageIO/imagebufalgo.h\"\n#include \"OpenImageIO/imagebufalgo_util.h\"\n#include \"OpenImageIO/dassert.h\"\n#include \"OpenImageIO/filter.h\"\n#include \"OpenImageIO/thread.h\"\n\nOIIO_NAMESPACE_ENTER {\n\n\nnamespace {\n\n// Poor man's Dual2<float> makes it easy to compute with differentials. For\n// a rich man's implementation and full documentation, see\n// OpenShadingLanguage (dual2.h).\nclass Dual2 {\npublic:\n    float val() const { return m_val; }\n    float dx() const { return m_dx; }\n    float dy() const { return m_dy; }\n    Dual2 (float val) : m_val(val), m_dx(0.0f), m_dy(0.0f) {}\n    Dual2 (float val, float dx, float dy) : m_val(val), m_dx(dx), m_dy(dy) {}\n    Dual2& operator= (float f) { m_val = f; m_dx = 0.0f; m_dy = 0.0f; return *this; }\n    friend Dual2 operator+ (const Dual2 &a, const Dual2 &b) {\n        return Dual2 (a.m_val+b.m_val, a.m_dx+b.m_dx, a.m_dy+b.m_dy);\n    }\n    friend Dual2 operator+ (const Dual2 &a, float b) {\n        return Dual2 (a.m_val+b, a.m_dx, a.m_dy);\n    }\n    friend Dual2 operator* (const Dual2 &a, float b) {\n        return Dual2 (a.m_val*b, a.m_dx*b, a.m_dy*b);\n    }\n    friend Dual2 operator* (const Dual2 &a, const Dual2 &b) {\n        // Use the chain rule\n        return Dual2 (a.m_val*b.m_val,\n                      a.m_val*b.m_dx + a.m_dx*b.m_val,\n                      a.m_val*b.m_dy + a.m_dy*b.m_val);\n    }\n    friend Dual2 operator/ (const Dual2 &a, const Dual2 &b) {\n        float bvalinv = 1.0f / b.m_val;\n        float aval_bval = a.m_val * bvalinv;\n        return Dual2 (aval_bval,\n                      bvalinv * (a.m_dx - aval_bval * b.m_dx),\n                      bvalinv * (a.m_dy - aval_bval * b.m_dy));\n    }\nprivate:\n    float m_val, m_dx, m_dy;\n};\n\n/// Transform a 2D point (x,y) with derivatives by a 3x3 affine matrix to\n/// obtain a transformed point with derivatives.\ninline void\nrobust_multVecMatrix (const Imath::M33f &M,\n                      const Dual2 &x, const Dual2 &y,\n                      Dual2 &outx, Dual2 &outy)\n{\n    Dual2 a = x * M[0][0] + y * M[1][0] + M[2][0];\n    Dual2 b = x * M[0][1] + y * M[1][1] + M[2][1];\n    Dual2 w = x * M[0][2] + y * M[1][2] + M[2][2];\n\n    if (w.val() != 0.0f) {\n       outx = a / w;\n       outy = b / w;\n    } else {\n       outx = 0.0f;\n       outy = 0.0f;\n    }\n}\n\n\n\n// Transform an ROI by an affine matrix.\nROI\ntransform (const Imath::M33f &M, ROI roi)\n{\n    Imath::V2f ul (roi.xbegin+0.5f, roi.ybegin+0.5f);\n    Imath::V2f ur (roi.xend-0.5f, roi.ybegin+0.5f);\n    Imath::V2f ll (roi.xbegin+0.5f, roi.yend-0.5f);\n    Imath::V2f lr (roi.xend-0.5f, roi.yend-0.5f);\n    M.multVecMatrix (ul, ul);\n    M.multVecMatrix (ur, ur);\n    M.multVecMatrix (ll, ll);\n    M.multVecMatrix (lr, lr);\n    Imath::Box2f box (ul);\n    box.extendBy (ll);\n    box.extendBy (ur);\n    box.extendBy (lr);\n    int xmin = int (floorf(box.min.x));\n    int ymin = int (floorf(box.min.y));\n    int xmax = int (floorf(box.max.x)) + 1;\n    int ymax = int (floorf(box.max.y)) + 1;\n    return ROI (xmin, xmax, ymin, ymax, roi.zbegin, roi.zend, roi.chbegin, roi.chend);\n}\n\n\n\n// Given s,t image space coordinates and their derivatives, compute a \n// filtered sample using the derivatives to guide the size of the filter\n// footprint.\ntemplate<typename SRCTYPE>\ninline void\nfiltered_sample (const ImageBuf &src, float s, float t,\n                 float dsdx, float dtdx, float dsdy, float dtdy,\n                 const Filter2D *filter, ImageBuf::WrapMode wrap,\n                 float *result)\n{\n    DASSERT (filter);\n    // Just use isotropic filtering\n    float ds = std::max (1.0f, std::max (fabsf(dsdx), fabsf(dsdy)));\n    float dt = std::max (1.0f, std::max (fabsf(dtdx), fabsf(dtdy)));\n    float ds_inv = 1.0f / ds;\n    float dt_inv = 1.0f / dt;\n    float filterrad_s = 0.5f * ds * filter->width();\n    float filterrad_t = 0.5f * dt * filter->width();\n    ImageBuf::ConstIterator<SRCTYPE> samp (src, \n                      (int)floorf(s-filterrad_s), (int)ceilf(s+filterrad_s),\n                      (int)floorf(t-filterrad_t), (int)ceilf(t+filterrad_t),\n                      0, 1, wrap);\n    int nc = src.nchannels();\n    float *sum = ALLOCA (float, nc);\n    memset (sum, 0, nc*sizeof(float));\n    float total_w = 0.0f;\n    for ( ; ! samp.done(); ++samp) {\n        float w = (*filter) (ds_inv*(samp.x()+0.5f-s), dt_inv*(samp.y()+0.5f-t));\n        for (int c = 0; c < nc; ++c)\n            sum[c] += w * samp[c];\n        total_w += w;\n    }\n    if (total_w != 0.0f)\n        for (int c = 0; c < nc; ++c)\n            result[c] = sum[c] / total_w;\n    else\n        for (int c = 0; c < nc; ++c)\n            result[c] = 0.0f;\n}\n\n} // end anon namespace\n\n\n\n\ntemplate<typename DSTTYPE, typename SRCTYPE>\nstatic bool\nresize_ (ImageBuf &dst, const ImageBuf &src,\n         Filter2D *filter, ROI roi, int nthreads)\n{\n    if (nthreads != 1 && roi.npixels() >= 1000) {\n        // Lots of pixels and request for multi threads? Parallelize.\n        ImageBufAlgo::parallel_image (\n            boost::bind(resize_<DSTTYPE,SRCTYPE>, boost::ref(dst),\n                        boost::cref(src), filter,\n                        _1 /*roi*/, 1 /*nthreads*/),\n            roi, nthreads);\n        return true;\n    }\n\n    // Serial case\n\n    const ImageSpec &srcspec (src.spec());\n    const ImageSpec &dstspec (dst.spec());\n    int nchannels = dstspec.nchannels;\n\n    // Local copies of the source image window, converted to float\n    float srcfx = srcspec.full_x;\n    float srcfy = srcspec.full_y;\n    float srcfw = srcspec.full_width;\n    float srcfh = srcspec.full_height;\n\n    // Ratios of dst/src size.  Values larger than 1 indicate that we\n    // are maximizing (enlarging the image), and thus want to smoothly\n    // interpolate.  Values less than 1 indicate that we are minimizing\n    // (shrinking the image), and thus want to properly filter out the\n    // high frequencies.\n    float xratio = float(dstspec.full_width) / srcfw; // 2 upsize, 0.5 downsize\n    float yratio = float(dstspec.full_height) / srcfh;\n\n    float dstfx = dstspec.full_x;\n    float dstfy = dstspec.full_y;\n    float dstfw = dstspec.full_width;\n    float dstfh = dstspec.full_height;\n    float dstpixelwidth = 1.0f / dstfw;\n    float dstpixelheight = 1.0f / dstfh;\n    float *pel = ALLOCA (float, nchannels);\n    float filterrad = filter->width() / 2.0f;\n\n    // radi,radj is the filter radius, as an integer, in source pixels.  We\n    // will filter the source over [x-radi, x+radi] X [y-radj,y+radj].\n    int radi = (int) ceilf (filterrad/xratio);\n    int radj = (int) ceilf (filterrad/yratio);\n    int xtaps = 2*radi + 1;\n    int ytaps = 2*radj + 1;\n    bool separable = filter->separable();\n    float *xfiltval = NULL, *yfiltval = NULL;\n    if (separable) {\n        // Allocate temp space to cache the filter weights\n        xfiltval = ALLOCA (float, xtaps);\n        yfiltval = ALLOCA (float, ytaps);\n    }\n#if 0\n    std::cerr << \"Resizing \" << srcspec.full_width << \"x\" << srcspec.full_height\n              << \" to \" << dstspec.full_width << \"x\" << dstspec.full_height << \"\\n\";\n    std::cerr << \"ratios = \" << xratio << \", \" << yratio << \"\\n\";\n    std::cerr << \"examining src filter support radius of \" << radi << \" x \" << radj << \" pixels\\n\";\n    std::cerr << \"dst range \" << roi << \"\\n\";\n    std::cerr << \"separable filter\\n\";\n#endif\n\n\n    // We're going to loop over all output pixels we're interested in.\n    //\n    // (s,t) = NDC space coordinates of the output sample we are computing.\n    //     This is the \"sample point\".\n    // (src_xf, src_xf) = source pixel space float coordinates of the\n    //     sample we're computing. We want to compute the weighted sum\n    //     of all the source image pixels that fall under the filter when\n    //     centered at that location.\n    // (src_x, src_y) = image space integer coordinates of the floor,\n    //     i.e., the closest pixel in the source image.\n    // src_xf_frac and src_yf_frac are the position within that pixel\n    //     of our sample.\n    ImageBuf::Iterator<DSTTYPE> out (dst, roi);\n    for (int y = roi.ybegin;  y < roi.yend;  ++y) {\n        float t = (y-dstfy+0.5f)*dstpixelheight;\n        float src_yf = srcfy + t * srcfh;\n        int src_y;\n        float src_yf_frac = floorfrac (src_yf, &src_y);\n\n        // If using separable filters, our vertical set of filter tap\n        // weights will be the same for the whole scanline we're on.  Just\n        // compute and normalize them once.\n        float totalweight_y = 0.0f;\n        if (separable) {\n            for (int j = 0;  j < ytaps;  ++j) {\n                float w = filter->yfilt (yratio * (j-radj-(src_yf_frac-0.5f)));\n                yfiltval[j] = w;\n                totalweight_y += w;\n            }\n            for (int i = 0;  i < ytaps;  ++i)\n                yfiltval[i] /= totalweight_y;\n        }\n\n        for (int x = roi.xbegin;  x < roi.xend;  ++x) {\n            float s = (x-dstfx+0.5f)*dstpixelwidth;\n            float src_xf = srcfx + s * srcfw;\n            int src_x;\n            float src_xf_frac = floorfrac (src_xf, &src_x);\n            for (int c = 0;  c < nchannels;  ++c)\n                pel[c] = 0.0f;\n            if (separable) {\n                // Cache and normalize the horizontal filter tap weights\n                // just once for this (x,y) position, reuse for all vertical\n                // taps.\n                float totalweight_x = 0.0f;\n                for (int i = 0;  i < xtaps;  ++i) {\n                    float w = filter->xfilt (xratio * (i-radi-(src_xf_frac-0.5f)));\n                    xfiltval[i] = w;\n                    totalweight_x += w;\n                }\n\n                if (totalweight_x != 0.0f) {\n                    for (int i = 0;  i < xtaps;  ++i)  // normalize x filter\n                        xfiltval[i] /= totalweight_x;  // weights\n                    ImageBuf::ConstIterator<SRCTYPE> srcpel (src, src_x-radi, src_x+radi+1,\n                                                             src_y-radj, src_y+radj+1,\n                                                             0, 1, ImageBuf::WrapClamp);\n                    for (int j = -radj;  j <= radj;  ++j) {\n                        float wy = yfiltval[j+radj];\n                        if (wy == 0.0f) {\n                            // 0 weight for this y tap -- move to next line\n                            srcpel.pos (srcpel.x(), srcpel.y()+1, srcpel.z());\n                            continue;\n                        }\n                        for (int i = 0;  i < xtaps; ++i, ++srcpel) {\n                            float w = wy * xfiltval[i];\n                            for (int c = 0;  c < nchannels;  ++c)\n                                pel[c] += w * srcpel[c];\n                        }\n                    }\n                }\n                // Copy the pixel value (already normalized) to the output.\n                DASSERT (out.x() == x && out.y() == y);\n                if (totalweight_y == 0.0f) {\n                    // zero it out\n                    for (int c = 0;  c < nchannels;  ++c)\n                        out[c] = 0.0f;\n                } else {\n                    for (int c = 0;  c < nchannels;  ++c)\n                        out[c] = pel[c];\n                }\n            } else {\n                // Non-separable\n                float totalweight = 0.0f;\n                ImageBuf::ConstIterator<SRCTYPE> srcpel (src, src_x-radi, src_x+radi+1,\n                                                       src_y-radi, src_y+radi+1,\n                                                       0, 1, ImageBuf::WrapClamp);\n                for (int j = -radj;  j <= radj;  ++j) {\n                    for (int i = -radi;  i <= radi;  ++i, ++srcpel) {\n                        float w = (*filter)(xratio * (i-(src_xf_frac-0.5f)),\n                                            yratio * (j-(src_yf_frac-0.5f)));\n                        totalweight += w;\n                        if (w == 0.0f)\n                            continue;\n                        DASSERT (! srcpel.done());\n                        for (int c = 0;  c < nchannels;  ++c)\n                            pel[c] += w * srcpel[c];\n                    }\n                }\n                DASSERT (srcpel.done());\n                // Rescale pel to normalize the filter and write it to the\n                // output image.\n                DASSERT (out.x() == x && out.y() == y);\n                if (totalweight == 0.0f) {\n                    // zero it out\n                    for (int c = 0;  c < nchannels;  ++c)\n                        out[c] = 0.0f;\n                } else {\n                    for (int c = 0;  c < nchannels;  ++c)\n                        out[c] = pel[c] / totalweight;\n                }\n            }\n\n            ++out;\n        }\n    }\n\n    return true;\n}\n\n\n\nbool\nImageBufAlgo::resize (ImageBuf &dst, const ImageBuf &src,\n                      Filter2D *filter, ROI roi, int nthreads)\n{\n    if (! IBAprep (roi, &dst, &src,\n            IBAprep_REQUIRE_SAME_NCHANNELS | IBAprep_NO_SUPPORT_VOLUME |\n            IBAprep_NO_COPY_ROI_FULL))\n        return false;\n\n    // Set up a shared pointer with custom deleter to make sure any\n    // filter we allocate here is properly destroyed.\n    boost::shared_ptr<Filter2D> filterptr ((Filter2D*)NULL, Filter2D::destroy);\n    bool allocfilter = (filter == NULL);\n    if (allocfilter) {\n        // If no filter was provided, punt and just linearly interpolate.\n        const ImageSpec &srcspec (src.spec());\n        const ImageSpec &dstspec (dst.spec());\n        float wratio = float(dstspec.full_width) / float(srcspec.full_width);\n        float hratio = float(dstspec.full_height) / float(srcspec.full_height);\n        float w = 2.0f * std::max (1.0f, wratio);\n        float h = 2.0f * std::max (1.0f, hratio);\n        filter = Filter2D::create (\"triangle\", w, h);\n        filterptr.reset (filter);\n    }\n\n    bool ok;\n    OIIO_DISPATCH_TYPES2 (ok, \"resize\", resize_,\n                          dst.spec().format, src.spec().format,\n                          dst, src, filter, roi, nthreads);\n    return ok;\n}\n\n\n\nbool\nImageBufAlgo::resize (ImageBuf &dst, const ImageBuf &src,\n                      string_view filtername_, float fwidth,\n                      ROI roi, int nthreads)\n{\n    if (! IBAprep (roi, &dst, &src,\n            IBAprep_REQUIRE_SAME_NCHANNELS | IBAprep_NO_SUPPORT_VOLUME |\n            IBAprep_NO_COPY_ROI_FULL))\n        return false;\n    const ImageSpec &srcspec (src.spec());\n    const ImageSpec &dstspec (dst.spec());\n\n    // Resize ratios\n    float wratio = float(dstspec.full_width) / float(srcspec.full_width);\n    float hratio = float(dstspec.full_height) / float(srcspec.full_height);\n\n    // Set up a shared pointer with custom deleter to make sure any\n    // filter we allocate here is properly destroyed.\n    boost::shared_ptr<Filter2D> filter ((Filter2D*)NULL, Filter2D::destroy);\n    std::string filtername = filtername_;\n    if (filtername.empty()) {\n        // No filter name supplied -- pick a good default\n        if (wratio > 1.0f || hratio > 1.0f)\n            filtername = \"blackman-harris\";\n        else\n            filtername = \"lanczos3\";\n    }\n    for (int i = 0, e = Filter2D::num_filters();  i < e;  ++i) {\n        FilterDesc fd;\n        Filter2D::get_filterdesc (i, &fd);\n        if (fd.name == filtername) {\n            float w = fwidth > 0.0f ? fwidth : fd.width * std::max (1.0f, wratio);\n            float h = fwidth > 0.0f ? fwidth : fd.width * std::max (1.0f, hratio);\n            filter.reset (Filter2D::create (filtername, w, h));\n            break;\n        }\n    }\n    if (! filter) {\n        dst.error (\"Filter \\\"%s\\\" not recognized\", filtername);\n        return false;\n    }\n\n    bool ok;\n    OIIO_DISPATCH_TYPES2 (ok, \"resize\", resize_,\n                          dstspec.format, srcspec.format,\n                          dst, src, filter.get(), roi, nthreads);\n    return ok;\n}\n\n\n\ntemplate<typename DSTTYPE, typename SRCTYPE>\nstatic bool\nresample_ (ImageBuf &dst, const ImageBuf &src, bool interpolate,\n           ROI roi, int nthreads)\n{\n    if (nthreads != 1 && roi.npixels() >= 1000) {\n        // Lots of pixels and request for multi threads? Parallelize.\n        ImageBufAlgo::parallel_image (\n            boost::bind(resample_<DSTTYPE,SRCTYPE>, boost::ref(dst),\n                        boost::cref(src), interpolate,\n                        _1 /*roi*/, 1 /*nthreads*/),\n            roi, nthreads);\n        return true;\n    }\n\n    // Serial case\n\n    const ImageSpec &srcspec (src.spec());\n    const ImageSpec &dstspec (dst.spec());\n    int nchannels = src.nchannels();\n\n    // Local copies of the source image window, converted to float\n    float srcfx = srcspec.full_x;\n    float srcfy = srcspec.full_y;\n    float srcfw = srcspec.full_width;\n    float srcfh = srcspec.full_height;\n\n    float dstfx = dstspec.full_x;\n    float dstfy = dstspec.full_y;\n    float dstfw = dstspec.full_width;\n    float dstfh = dstspec.full_height;\n    float dstpixelwidth = 1.0f / dstfw;\n    float dstpixelheight = 1.0f / dstfh;\n    float *pel = ALLOCA (float, nchannels);\n\n    ImageBuf::Iterator<DSTTYPE> out (dst, roi);\n    ImageBuf::ConstIterator<SRCTYPE> srcpel (src);\n    for (int y = roi.ybegin;  y < roi.yend;  ++y) {\n        // s,t are NDC space\n        float t = (y-dstfy+0.5f)*dstpixelheight;\n        // src_xf, src_xf are image space float coordinates\n        float src_yf = srcfy + t * srcfh - 0.5f;\n        // src_x, src_y are image space integer coordinates of the floor\n        int src_y;\n        (void) floorfrac (src_yf, &src_y);\n        for (int x = roi.xbegin;  x < roi.xend;  ++x) {\n            float s = (x-dstfx+0.5f)*dstpixelwidth;\n            float src_xf = srcfx + s * srcfw - 0.5f;\n            int src_x;\n            (void) floorfrac (src_xf, &src_x);\n\n            if (interpolate) {\n                src.interppixel (src_xf, src_yf, pel);\n                for (int c = roi.chbegin; c < roi.chend; ++c)\n                    out[c] = pel[c];\n            } else {\n                srcpel.pos (src_x, src_y, 0);\n                for (int c = roi.chbegin; c < roi.chend; ++c)\n                    out[c] = srcpel[c];\n            }\n            ++out;\n        }\n    }\n\n    return true;\n}\n\n\n\nbool\nImageBufAlgo::resample (ImageBuf &dst, const ImageBuf &src,\n                        bool interpolate, ROI roi, int nthreads)\n{\n    if (! IBAprep (roi, &dst, &src,\n            IBAprep_REQUIRE_SAME_NCHANNELS | IBAprep_NO_SUPPORT_VOLUME |\n            IBAprep_NO_COPY_ROI_FULL))\n        return false;\n    bool ok;\n    OIIO_DISPATCH_TYPES2 (ok, \"resample\", resample_,\n                          dst.spec().format, src.spec().format,\n                          dst, src, interpolate, roi, nthreads);\n    return ok;\n}\n\n\n\n#if 0\ntemplate<typename DSTTYPE, typename SRCTYPE>\nstatic bool\naffine_resample_ (ImageBuf &dst, const ImageBuf &src, const Imath::M33f &Minv,\n                  ROI roi, int nthreads)\n{\n    if (nthreads != 1 && roi.npixels() >= 1000) {\n        // Possible multiple thread case -- recurse via parallel_image\n        ImageBufAlgo::parallel_image (\n            boost::bind(affine_resample_<DSTTYPE,SRCTYPE>,\n                        boost::ref(dst), boost::cref(src), Minv,\n                        _1 /*roi*/, 1 /*nthreads*/),\n            roi, nthreads);\n        return true;\n    }\n\n    // Serial case\n    ImageBuf::Iterator<DSTTYPE,DSTTYPE> d (dst, roi);\n    ImageBuf::ConstIterator<SRCTYPE,DSTTYPE> s (src);\n    for (  ;  ! d.done();  ++d) {\n        Imath::V2f P (d.x()+0.5f, d.y()+0.5f);\n        Minv.multVecMatrix (P, P);\n        s.pos (int(floorf(P.x)), int(floorf(P.y)), d.z());\n        for (int c = roi.chbegin;  c < roi.chend;  ++c)\n            d[c] = s[c];\n    }\n    return true;\n}\n#endif\n\n\n\ntemplate<typename DSTTYPE, typename SRCTYPE>\nstatic bool\nwarp_ (ImageBuf &dst, const ImageBuf &src, const Imath::M33f &M,\n       const Filter2D *filter, ImageBuf::WrapMode wrap,\n       ROI roi, int nthreads)\n{\n    if (nthreads != 1 && roi.npixels() >= 1000) {\n        // Possible multiple thread case -- recurse via parallel_image\n        ImageBufAlgo::parallel_image (\n            boost::bind(warp_<DSTTYPE,SRCTYPE>,\n                        boost::ref(dst), boost::cref(src), M,\n                        filter, wrap, _1 /*roi*/, 1 /*nthreads*/),\n            roi, nthreads);\n        return true;\n    }\n\n    // Serial case\n    int nc = dst.nchannels();\n    float *pel = ALLOCA (float, nc);\n    memset (pel, 0, nc*sizeof(float));\n    Imath::M33f Minv = M.inverse();\n    ImageBuf::Iterator<DSTTYPE> out (dst, roi);\n    for (  ;  ! out.done();  ++out) {\n        Dual2 x (out.x()+0.5f, 1.0f, 0.0f);\n        Dual2 y (out.y()+0.5f, 0.0f, 1.0f);\n        robust_multVecMatrix (Minv, x, y, x, y);\n        filtered_sample<SRCTYPE> (src, x.val(), y.val(),\n                                  x.dx(), y.dx(), x.dy(), y.dy(),\n                                  filter, wrap, pel);\n        for (int c = roi.chbegin;  c < roi.chend;  ++c)\n            out[c] = pel[c];\n \n    }\n    return true;\n}\n\n\n\nbool\nImageBufAlgo::warp (ImageBuf &dst, const ImageBuf &src,\n                    const Imath::M33f &M,\n                    const Filter2D *filter,\n                    bool recompute_roi, ImageBuf::WrapMode wrap,\n                    ROI roi, int nthreads)\n{\n    ROI src_roi_full = src.roi_full();\n    ROI dst_roi, dst_roi_full;\n    if (dst.initialized()) {\n        dst_roi = roi.defined() ? roi : dst.roi();\n        dst_roi_full = dst.roi_full();\n    } else {\n        dst_roi = roi.defined() ? roi : (recompute_roi ? transform (M, src.roi()) : src.roi());\n        dst_roi_full = src_roi_full;\n    }\n    dst_roi.chend = std::min (dst_roi.chend, src.nchannels());\n    dst_roi_full.chend = std::min (dst_roi_full.chend, src.nchannels());\n\n    if (! IBAprep (dst_roi, &dst, &src, IBAprep_NO_SUPPORT_VOLUME))\n        return false;\n\n    // Set up a shared pointer with custom deleter to make sure any\n    // filter we allocate here is properly destroyed.\n    boost::shared_ptr<Filter2D> filterptr ((Filter2D*)NULL, Filter2D::destroy);\n    if (filter == NULL) {\n        // If no filter was provided, punt and just linearly interpolate.\n        filterptr.reset (Filter2D::create (\"lanczos3\", 6.0f, 6.0f));\n        filter = filterptr.get();\n    }\n\n    bool ok;\n    OIIO_DISPATCH_TYPES2 (ok, \"warp\", warp_,\n                          dst.spec().format, src.spec().format,\n                          dst, src, M, filter, wrap, dst_roi, nthreads);\n    return ok;\n}\n\n\n\nbool\nImageBufAlgo::warp (ImageBuf &dst, const ImageBuf &src,\n                    const Imath::M33f &M,\n                    string_view filtername_, float filterwidth,\n                    bool recompute_roi, ImageBuf::WrapMode wrap,\n                    ROI roi, int nthreads)\n{\n    // Set up a shared pointer with custom deleter to make sure any\n    // filter we allocate here is properly destroyed.\n    boost::shared_ptr<Filter2D> filter ((Filter2D*)NULL, Filter2D::destroy);\n    std::string filtername = filtername_.size() ? filtername_ : \"lanczos3\";\n    for (int i = 0, e = Filter2D::num_filters();  i < e;  ++i) {\n        FilterDesc fd;\n        Filter2D::get_filterdesc (i, &fd);\n        if (fd.name == filtername) {\n            float w = filterwidth > 0.0f ? filterwidth : fd.width;\n            float h = filterwidth > 0.0f ? filterwidth : fd.width;\n            filter.reset (Filter2D::create (filtername, w, h));\n            break;\n        }\n    }\n    if (! filter) {\n        dst.error (\"Filter \\\"%s\\\" not recognized\", filtername);\n        return false;\n    }\n\n    return warp (dst, src, M, filter.get(), recompute_roi, wrap, roi, nthreads);\n}\n\n\n\nbool\nImageBufAlgo::rotate (ImageBuf &dst, const ImageBuf &src,\n                      float angle, float center_x, float center_y,\n                      Filter2D *filter, bool recompute_roi,\n                      ROI roi, int nthreads)\n{\n    // Calculate the rotation matrix\n    Imath::M33f M;\n    M.translate(Imath::V2f(-center_x, -center_y));\n    M.rotate(angle);\n    M *= Imath::M33f().translate(Imath::V2f(center_x, center_y));\n    return ImageBufAlgo::warp (dst, src, M, filter,\n                               recompute_roi, ImageBuf::WrapBlack,\n                               roi, nthreads);\n}\n\n\n\nbool\nImageBufAlgo::rotate (ImageBuf &dst, const ImageBuf &src,\n                      float angle, float center_x, float center_y,\n                      string_view filtername, float filterwidth,\n                      bool recompute_roi, ROI roi, int nthreads)\n{\n    // Calculate the rotation matrix\n    Imath::M33f M;\n    M.translate(Imath::V2f(-center_x, -center_y));\n    M.rotate(angle);\n    M *= Imath::M33f().translate(Imath::V2f(center_x, center_y));\n    return ImageBufAlgo::warp (dst, src, M, filtername, filterwidth,\n                               recompute_roi, ImageBuf::WrapBlack,\n                               roi, nthreads);\n}\n\n\n\nbool\nImageBufAlgo::rotate (ImageBuf &dst, const ImageBuf &src, float angle,\n                      Filter2D *filter,\n                      bool recompute_roi, ROI roi, int nthreads)\n{\n    ROI src_roi_full = src.roi_full();\n    float center_x = 0.5f * (src_roi_full.xbegin + src_roi_full.xend);\n    float center_y = 0.5f * (src_roi_full.ybegin + src_roi_full.yend);\n    return ImageBufAlgo::rotate (dst, src, angle, center_x, center_y,\n                                 filter, recompute_roi, roi, nthreads);\n}\n\n\n\nbool\nImageBufAlgo::rotate (ImageBuf &dst, const ImageBuf &src, float angle,\n                      string_view filtername, float filterwidth,\n                      bool recompute_roi,\n                      ROI roi, int nthreads)\n{\n    ROI src_roi_full = src.roi_full();\n    float center_x = 0.5f * (src_roi_full.xbegin + src_roi_full.xend);\n    float center_y = 0.5f * (src_roi_full.ybegin + src_roi_full.yend);\n    return ImageBufAlgo::rotate (dst, src, angle, center_x, center_y,\n                                 filtername, filterwidth, recompute_roi,\n                                 roi, nthreads);\n}\n\n\n} OIIO_NAMESPACE_EXIT\n", "meta": {"hexsha": "c87732d40ded651b9d86b7fcb2994e33571d39db", "size": 27833, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libOpenImageIO/imagebufalgo_xform.cpp", "max_stars_repo_name": "nburtnyk/oiio", "max_stars_repo_head_hexsha": "2c766a26f77cfe43196f9dade9021befdace90fb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-28T13:14:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-28T13:14:43.000Z", "max_issues_repo_path": "src/libOpenImageIO/imagebufalgo_xform.cpp", "max_issues_repo_name": "sobotka/oiio", "max_issues_repo_head_hexsha": "7f1f1d64933a51e1610da22a26f80528e3dd6dd8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libOpenImageIO/imagebufalgo_xform.cpp", "max_forks_repo_name": "sobotka/oiio", "max_forks_repo_head_hexsha": "7f1f1d64933a51e1610da22a26f80528e3dd6dd8", "max_forks_repo_licenses": ["BSD-3-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.0119680851, "max_line_length": 99, "alphanum_fraction": 0.5563898969, "num_tokens": 7651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.259172799843438}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-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_RIJNDAEL_IMPL_HPP\n#define CRYPTO3_RIJNDAEL_IMPL_HPP\n\n#include <boost/crypto3/block/algorithm/move.hpp>\n\n#include <boost/crypto3/detail/stream_endian.hpp>\n#include <boost/crypto3/detail/pack.hpp>\n\nnamespace boost {\n    namespace crypto3 {\n        namespace block {\n            /*!\n             * @cond DETAIL_IMPL\n             */\n            namespace detail {\n                template<std::size_t KeyBitsImpl, std::size_t BlockBitsImpl, typename PolicyType>\n                class rijndael_impl {\n                    typedef PolicyType policy_type;\n\n                    typedef typename policy_type::key_type key_type;\n                    typedef typename policy_type::key_schedule_type key_schedule_type;\n                    typedef typename policy_type::key_schedule_word_type key_schedule_word_type;\n\n                    typedef typename policy_type::block_type block_type;\n\n                    typedef typename policy_type::constants_type constants_type;\n                    typedef typename policy_type::shift_offsets_type shift_offsets_type;\n                    typedef typename policy_type::mm_type mm_type;\n\n                    BOOST_STATIC_ASSERT(KeyBitsImpl == PolicyType::key_bits);\n                    BOOST_STATIC_ASSERT(BlockBitsImpl == PolicyType::block_bits);\n\n                    static inline key_schedule_word_type sub_word(const key_schedule_word_type &x,\n                                                                  const constants_type &constants) {\n                        key_schedule_word_type result = {0};\n#pragma clang loop unroll(full)\n                        for (std::size_t i = 0; i < policy_type::word_bytes; ++i) {\n                            result =\n                                result << CHAR_BIT | constants[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(x, i)];\n                        }\n\n                        return result;\n                    }\n\n                    static inline void sub_bytes(block_type &state, const constants_type &sbox) {\n#pragma clang loop unroll(full)\n                        for (std::size_t i = 0; i < policy_type::word_bytes * policy_type::block_words; ++i) {\n                            state[i] = sbox[state[i]];\n                        }\n                    }\n\n                    static inline void shift_rows(block_type &state, const shift_offsets_type &offset) {\n                        std::array<typename policy_type::byte_type, policy_type::block_words> tmp = {0};\n\n                        // row 0 never gets shifted\n#pragma clang loop unroll(full)\n                        for (std::size_t row = 1; row < policy_type::word_bytes; ++row) {\n                            const std::size_t off = offset[row - 1];\n#pragma clang loop unroll(full)\n                            for (std::size_t i = 0; i < off; ++i) {\n                                tmp[i] = state[i * policy_type::word_bytes + row];\n                            }\n#pragma clang loop unroll(full)\n                            for (std::size_t i = 0; i < policy_type::block_words - 1; ++i) {\n                                state[i * policy_type::word_bytes + row] =\n                                    state[(i + off) * policy_type::word_bytes + row];\n                            }\n#pragma clang loop unroll(full)\n                            for (std::size_t i = 0; i < off; ++i) {\n                                state[(policy_type::block_words - 1 - i) * policy_type::word_bytes + row] =\n                                    tmp[off - 1 - i];\n                            }\n                        }\n                    }\n\n                    template<typename StateType>\n                    static inline block_type mix_columns(const StateType &state, const mm_type &mm) {\n                        block_type tmp = {0};\n\n#pragma clang loop unroll(full)\n                        for (std::size_t col = 0; col < policy_type::block_words; ++col) {\n#pragma clang loop unroll(full)\n                            for (std::size_t row = 0; row < policy_type::word_bytes; ++row) {\n#pragma clang loop unroll(full)\n                                for (std::size_t k = 0; k < policy_type::word_bytes; ++k) {\n                                    tmp[col * policy_type::word_bytes + row] ^=\n                                        policy_type::mul(mm[row * policy_type::word_bytes + k],\n                                                         state[col * policy_type::word_bytes + k]);\n                                }\n                            }\n                        }\n\n                        return tmp;\n                    }\n\n                    template<typename InputIterator>\n                    static inline void add_round_key(block_type &state, InputIterator first, InputIterator last) {\n                        BOOST_ASSERT(std::distance(first, last) == policy_type::block_words &&\n                                     state.size() == policy_type::block_bytes);\n\n#pragma clang loop unroll(full)\n                        for (std::size_t i = 0; i < policy_type::block_words && first != last; ++i && ++first) {\n#pragma clang loop unroll(full)\n                            for (std::size_t j = 0; j < policy_type::word_bytes; ++j) {\n                                state[i * policy_type::word_bytes + j] ^=\n                                    ::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(*first,\n                                                                                     policy_type::word_bytes - (j + 1));\n                            }\n                        }\n                    }\n\n                    static inline void apply_round(std::uint8_t round, block_type &state, const key_schedule_type &w,\n                                                   const constants_type &sbox, const shift_offsets_type &offsets,\n                                                   const mm_type &mm) {\n                        sub_bytes(state, sbox);\n                        shift_rows(state, offsets);\n                        state = mix_columns(state, mm);\n                        add_round_key(state, w.begin() + round * policy_type::block_words,\n                                      w.begin() + (round + 1) * policy_type::block_words);\n                    }\n\n                public:\n                    static typename policy_type::block_type encrypt_block(const block_type &plaintext,\n                                                                          const key_schedule_type &encryption_key) {\n                        block_type state = plaintext;\n\n                        add_round_key(state, encryption_key.begin(), encryption_key.begin() + policy_type::block_words);\n\n#pragma clang loop unroll(full)\n                        for (std::size_t round = 1; round < policy_type::rounds; ++round) {\n                            apply_round(round, state, encryption_key, policy_type::constants,\n                                        policy_type::shift_offsets, policy_type::mm);\n                        }\n\n                        sub_bytes(state, policy_type::constants);\n                        shift_rows(state, policy_type::shift_offsets);\n                        add_round_key(state, encryption_key.begin() + policy_type::rounds * policy_type::block_words,\n                                      encryption_key.begin() + (policy_type::rounds + 1) * policy_type::block_words);\n\n                        return state;\n                    }\n\n                    static typename policy_type::block_type decrypt_block(const block_type &plaintext,\n                                                                          const key_schedule_type &decryption_key) {\n                        block_type state = plaintext;\n\n                        add_round_key(state, decryption_key.begin() + policy_type::rounds * policy_type::block_words,\n                                      decryption_key.begin() + (policy_type::rounds + 1) * policy_type::block_words);\n\n#pragma clang loop unroll(full)\n                        for (std::size_t round = policy_type::rounds - 1; round > 0; --round) {\n                            apply_round(round, state, decryption_key, policy_type::inverted_constants,\n                                        policy_type::inverted_shift_offsets, policy_type::inverted_mm);\n                        }\n\n                        sub_bytes(state, policy_type::inverted_constants);\n                        shift_rows(state, policy_type::inverted_shift_offsets);\n                        add_round_key(state, decryption_key.begin(), decryption_key.begin() + policy_type::block_words);\n\n                        return state;\n                    }\n\n                    static void schedule_key(const key_type &key, key_schedule_type &encryption_key,\n                                             key_schedule_type &decryption_key) {\n                        // the first key_words words are the original key\n                        ::boost::crypto3::detail::pack<stream_endian::big_octet_big_bit,\n                                                     stream_endian::little_octet_big_bit, CHAR_BIT,\n                                                     policy_type::word_bits>(\n                            key.begin(), key.begin() + policy_type::key_words * policy_type::word_bytes,\n                            encryption_key.begin());\n\n#pragma clang loop unroll(full)\n                        for (std::size_t i = policy_type::key_words; i < policy_type::key_schedule_words; ++i) {\n                            typename policy_type::key_schedule_word_type tmp = encryption_key[i - 1];\n                            if (i % policy_type::key_words == 0) {\n                                tmp = sub_word(policy_type::rotate_left(tmp), policy_type::constants) ^\n                                      policy_type::round_constants[i / policy_type::key_words - 1];\n                            } else if (policy_type::key_words > 6 && i % policy_type::key_words == 4) {\n                                tmp = sub_word(tmp, policy_type::constants);\n                            }\n                            encryption_key[i] = encryption_key[i - policy_type::key_words] ^ tmp;\n                        }\n\n                        std::array<typename policy_type::byte_type, policy_type::key_schedule_bytes> bekey = {0};\n                        ::boost::crypto3::detail::pack<stream_endian::little_octet_big_bit,\n                                                     stream_endian::big_octet_big_bit, policy_type::word_bits,\n                                                     CHAR_BIT>(encryption_key.begin(), encryption_key.end(),\n                                                               bekey.begin());\n\n#pragma clang loop unroll(full)\n                        for (std::uint8_t round = 1; round < policy_type::rounds; ++round) {\n                            move(mix_columns(boost::adaptors::slice(bekey, round * policy_type::block_bytes,\n                                                                    (round + 1) * policy_type::block_bytes),\n                                             policy_type::inverted_mm),\n                                 bekey.begin() + round * policy_type::block_bytes);\n                        }\n\n                        ::boost::crypto3::detail::pack<stream_endian::big_octet_big_bit,\n                                                     stream_endian::little_octet_big_bit, CHAR_BIT,\n                                                     policy_type::word_bits>(bekey.begin(), bekey.end(),\n                                                                             decryption_key.begin());\n                    }\n                };\n            }    // namespace detail\n            /*!\n             * @endcond\n             */\n        }    // namespace block\n    }        // namespace crypto3\n}    // namespace boost\n\n#endif    // CRYPTO3_RIJNDAEL_IMPL_HPP\n", "meta": {"hexsha": "cd2c72da56398593095bdb8f31f0aeec8fbb3e47", "size": 12236, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/crypto3/block/detail/rijndael/rijndael_impl.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/block/detail/rijndael/rijndael_impl.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/block/detail/rijndael/rijndael_impl.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": 55.3665158371, "max_line_length": 121, "alphanum_fraction": 0.4745831971, "num_tokens": 2154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.25908145517832126}}
{"text": "// Copyright (c) 2016 Jack Grigg\n// Copyright (c) 2016 The Zcash developers\n// Copyright (c) 2019 BTC.COM\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#pragma once\n\n#include \"sodium.h\"\n\n#include <cstring>\n#include <exception>\n#include <functional>\n#include <memory>\n#include <set>\n#include <vector>\n\n#include <boost/static_assert.hpp>\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wsign-compare\"\n#pragma GCC diagnostic ignored \"-Wunused-variable\"\n\nnamespace equihash_zcash {\n\ntypedef crypto_generichash_blake2b_state eh_HashState;\ntypedef uint32_t eh_index;\ntypedef uint8_t eh_trunc;\n\nvoid ExpandArray(const unsigned char* in, size_t in_len,\n                 unsigned char* out, size_t out_len,\n                 size_t bit_len, size_t byte_pad=0);\nvoid CompressArray(const unsigned char* in, size_t in_len,\n                   unsigned char* out, size_t out_len,\n                   size_t bit_len, size_t byte_pad=0);\n\neh_index ArrayToEhIndex(const unsigned char* array);\neh_trunc TruncateIndex(const eh_index i, const unsigned int ilen);\n\nstd::vector<eh_index> GetIndicesFromMinimal(std::vector<unsigned char> minimal,\n                                            size_t cBitLen);\nstd::vector<unsigned char> GetMinimalFromIndices(std::vector<eh_index> indices,\n                                                 size_t cBitLen);\n\ntemplate<size_t WIDTH>\nclass StepRow\n{\n    template<size_t W>\n    friend class StepRow;\n    friend class CompareSR;\n\nprotected:\n    unsigned char hash[WIDTH];\n\npublic:\n    StepRow(const unsigned char* hashIn, size_t hInLen,\n            size_t hLen, size_t cBitLen);\n    ~StepRow() { }\n\n    template<size_t W>\n    StepRow(const StepRow<W>& a);\n\n    bool IsZero(size_t len);\n    std::string GetHex(size_t len) { return HexStr(hash, hash+len); }\n\n    template<size_t W>\n    friend bool HasCollision(StepRow<W>& a, StepRow<W>& b, int l);\n};\n\nclass CompareSR\n{\nprivate:\n    size_t len;\n\npublic:\n    CompareSR(size_t l) : len {l} { }\n\n    template<size_t W>\n    inline bool operator()(const StepRow<W>& a, const StepRow<W>& b) { return memcmp(a.hash, b.hash, len) < 0; }\n};\n\ntemplate<size_t WIDTH>\nbool HasCollision(StepRow<WIDTH>& a, StepRow<WIDTH>& b, int l);\n\ntemplate<size_t WIDTH>\nclass FullStepRow : public StepRow<WIDTH>\n{\n    template<size_t W>\n    friend class FullStepRow;\n\n    using StepRow<WIDTH>::hash;\n\npublic:\n    FullStepRow(const unsigned char* hashIn, size_t hInLen,\n                size_t hLen, size_t cBitLen, eh_index i);\n    ~FullStepRow() { }\n\n    FullStepRow(const FullStepRow<WIDTH>& a) : StepRow<WIDTH> {a} { }\n    template<size_t W>\n    FullStepRow(const FullStepRow<W>& a, const FullStepRow<W>& b, size_t len, size_t lenIndices, int trim);\n    FullStepRow& operator=(const FullStepRow<WIDTH>& a);\n\n    inline bool IndicesBefore(const FullStepRow<WIDTH>& a, size_t len, size_t lenIndices) const { return memcmp(hash+len, a.hash+len, lenIndices) < 0; }\n    std::vector<unsigned char> GetIndices(size_t len, size_t lenIndices,\n                                          size_t cBitLen) const;\n\n    template<size_t W>\n    friend bool DistinctIndices(const FullStepRow<W>& a, const FullStepRow<W>& b,\n                                size_t len, size_t lenIndices);\n    template<size_t W>\n    friend bool IsValidBranch(const FullStepRow<W>& a, const size_t len, const unsigned int ilen, const eh_trunc t);\n};\n\ntemplate<size_t WIDTH>\nclass TruncatedStepRow : public StepRow<WIDTH>\n{\n    template<size_t W>\n    friend class TruncatedStepRow;\n\n    using StepRow<WIDTH>::hash;\n\npublic:\n    TruncatedStepRow(const unsigned char* hashIn, size_t hInLen,\n                     size_t hLen, size_t cBitLen,\n                     eh_index i, unsigned int ilen);\n    ~TruncatedStepRow() { }\n\n    TruncatedStepRow(const TruncatedStepRow<WIDTH>& a) : StepRow<WIDTH> {a} { }\n    template<size_t W>\n    TruncatedStepRow(const TruncatedStepRow<W>& a, const TruncatedStepRow<W>& b, size_t len, size_t lenIndices, int trim);\n    TruncatedStepRow& operator=(const TruncatedStepRow<WIDTH>& a);\n\n    inline bool IndicesBefore(const TruncatedStepRow<WIDTH>& a, size_t len, size_t lenIndices) const { return memcmp(hash+len, a.hash+len, lenIndices) < 0; }\n    std::shared_ptr<eh_trunc> GetTruncatedIndices(size_t len, size_t lenIndices) const;\n};\n\nenum EhSolverCancelCheck\n{\n    ListGeneration,\n    ListSorting,\n    ListColliding,\n    RoundEnd,\n    FinalSorting,\n    FinalColliding,\n    PartialGeneration,\n    PartialSorting,\n    PartialSubtreeEnd,\n    PartialIndexEnd,\n    PartialEnd\n};\n\nclass EhSolverCancelledException : public std::exception\n{\n    virtual const char* what() const throw() {\n        return \"Equihash solver was cancelled\";\n    }\n};\n\ninline constexpr const size_t max(const size_t A, const size_t B) { return A > B ? A : B; }\n\ninline constexpr size_t equihash_solution_size(unsigned int N, unsigned int K) {\n    return (1 << K)*(N/(K+1)+1)/8;\n}\n\ntemplate<unsigned int N, unsigned int K>\nclass Equihash\n{\nprivate:\n    BOOST_STATIC_ASSERT(K < N);\n    BOOST_STATIC_ASSERT(N % 8 == 0);\n    BOOST_STATIC_ASSERT((N/(K+1)) + 1 < 8*sizeof(eh_index));\n\npublic:\n    enum : size_t { IndicesPerHashOutput=512/N };\n    enum : size_t { HashOutput=IndicesPerHashOutput*N/8 };\n    enum : size_t { CollisionBitLength=N/(K+1) };\n    enum : size_t { CollisionByteLength=(CollisionBitLength+7)/8 };\n    enum : size_t { HashLength=(K+1)*CollisionByteLength };\n    enum : size_t { FullWidth=2*CollisionByteLength+sizeof(eh_index)*(1 << (K-1)) };\n    enum : size_t { FinalFullWidth=2*CollisionByteLength+sizeof(eh_index)*(1 << (K)) };\n    enum : size_t { TruncatedWidth=max(HashLength+sizeof(eh_trunc), 2*CollisionByteLength+sizeof(eh_trunc)*(1 << (K-1))) };\n    enum : size_t { FinalTruncatedWidth=max(HashLength+sizeof(eh_trunc), 2*CollisionByteLength+sizeof(eh_trunc)*(1 << (K))) };\n    enum : size_t { SolutionWidth=(1 << K)*(CollisionBitLength+1)/8 };\n\n    Equihash() { }\n\n    int InitialiseState(eh_HashState& base_state);\n#ifdef ENABLE_MINING\n    bool BasicSolve(const eh_HashState& base_state,\n                    const std::function<bool(std::vector<unsigned char>)> validBlock,\n                    const std::function<bool(EhSolverCancelCheck)> cancelled);\n    bool OptimisedSolve(const eh_HashState& base_state,\n                        const std::function<bool(std::vector<unsigned char>)> validBlock,\n                        const std::function<bool(EhSolverCancelCheck)> cancelled);\n#endif\n    bool IsValidSolution(const eh_HashState& base_state, std::vector<unsigned char> soln);\n};\n\n} // namespace\n\n#include \"equihash_zcash.tcc\"\n#include \"equihash_zcash.inl\"\n\nnamespace equihash_zcash {\n\nstatic Equihash<96,3> Eh96_3;\nstatic Equihash<200,9> Eh200_9;\nstatic Equihash<96,5> Eh96_5;\nstatic Equihash<48,5> Eh48_5;\n\n#define EhZecInitialiseState(n, k, base_state)  \\\n    if (n == 96 && k == 3) {                 \\\n        equihash_zcash::Eh96_3.InitialiseState(base_state);  \\\n    } else if (n == 200 && k == 9) {         \\\n        equihash_zcash::Eh200_9.InitialiseState(base_state); \\\n    } else if (n == 96 && k == 5) {          \\\n        equihash_zcash::Eh96_5.InitialiseState(base_state);  \\\n    } else if (n == 48 && k == 5) {          \\\n        equihash_zcash::Eh48_5.InitialiseState(base_state);  \\\n    } else {                                 \\\n        throw std::invalid_argument(\"Unsupported Equihash parameters\"); \\\n    }\n\n#ifdef ENABLE_MINING\ninline bool EhBasicSolve(unsigned int n, unsigned int k, const eh_HashState& base_state,\n                    const std::function<bool(std::vector<unsigned char>)> validBlock,\n                    const std::function<bool(EhSolverCancelCheck)> cancelled)\n{\n    if (n == 96 && k == 3) {\n        return Eh96_3.BasicSolve(base_state, validBlock, cancelled);\n    } else if (n == 200 && k == 9) {\n        return Eh200_9.BasicSolve(base_state, validBlock, cancelled);\n    } else if (n == 96 && k == 5) {\n        return Eh96_5.BasicSolve(base_state, validBlock, cancelled);\n    } else if (n == 48 && k == 5) {\n        return Eh48_5.BasicSolve(base_state, validBlock, cancelled);\n    } else {\n        throw std::invalid_argument(\"Unsupported Equihash parameters\");\n    }\n}\n\ninline bool EhBasicSolveUncancellable(unsigned int n, unsigned int k, const eh_HashState& base_state,\n                    const std::function<bool(std::vector<unsigned char>)> validBlock)\n{\n    return EhBasicSolve(n, k, base_state, validBlock,\n                        [](EhSolverCancelCheck pos) { return false; });\n}\n\ninline bool EhOptimisedSolve(unsigned int n, unsigned int k, const eh_HashState& base_state,\n                    const std::function<bool(std::vector<unsigned char>)> validBlock,\n                    const std::function<bool(EhSolverCancelCheck)> cancelled)\n{\n    if (n == 96 && k == 3) {\n        return Eh96_3.OptimisedSolve(base_state, validBlock, cancelled);\n    } else if (n == 200 && k == 9) {\n        return Eh200_9.OptimisedSolve(base_state, validBlock, cancelled);\n    } else if (n == 96 && k == 5) {\n        return Eh96_5.OptimisedSolve(base_state, validBlock, cancelled);\n    } else if (n == 48 && k == 5) {\n        return Eh48_5.OptimisedSolve(base_state, validBlock, cancelled);\n    } else {\n        throw std::invalid_argument(\"Unsupported Equihash parameters\");\n    }\n}\n\ninline bool EhOptimisedSolveUncancellable(unsigned int n, unsigned int k, const eh_HashState& base_state,\n                    const std::function<bool(std::vector<unsigned char>)> validBlock)\n{\n    return EhOptimisedSolve(n, k, base_state, validBlock,\n                            [](EhSolverCancelCheck pos) { return false; });\n}\n#endif // ENABLE_MINING\n\n#define EhZecIsValidSolution(n, k, base_state, soln, ret)   \\\n    if (n == 96 && k == 3) {                             \\\n        ret = equihash_zcash::Eh96_3.IsValidSolution(base_state, soln);  \\\n    } else if (n == 200 && k == 9) {                     \\\n        ret = equihash_zcash::Eh200_9.IsValidSolution(base_state, soln); \\\n    } else if (n == 96 && k == 5) {                      \\\n        ret = equihash_zcash::Eh96_5.IsValidSolution(base_state, soln);  \\\n    } else if (n == 48 && k == 5) {                      \\\n        ret = equihash_zcash::Eh48_5.IsValidSolution(base_state, soln);  \\\n    } else {                                             \\\n        throw std::invalid_argument(\"Unsupported Equihash parameters\"); \\\n    }\n\n} // namespace\n\n#pragma GCC diagnostic pop\n", "meta": {"hexsha": "9661cfb1687498c11dc08e8e73ac89a2b404b1e6", "size": 10492, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdparty/equihash/zcash/equihash_zcash.hpp", "max_stars_repo_name": "duguyifang/btcpool", "max_stars_repo_head_hexsha": "0127a750b3b26a515e66261cbd9ad7f95c54de01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 585.0, "max_stars_repo_stars_event_min_datetime": "2016-08-20T22:25:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-11T15:13:54.000Z", "max_issues_repo_path": "3rdparty/equihash/zcash/equihash_zcash.hpp", "max_issues_repo_name": "immense055/btcpool", "max_issues_repo_head_hexsha": "0127a750b3b26a515e66261cbd9ad7f95c54de01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 335.0, "max_issues_repo_issues_event_min_datetime": "2016-09-22T02:58:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-08T07:19:13.000Z", "max_forks_repo_path": "3rdparty/equihash/zcash/equihash_zcash.hpp", "max_forks_repo_name": "immense055/btcpool", "max_forks_repo_head_hexsha": "0127a750b3b26a515e66261cbd9ad7f95c54de01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 443.0, "max_forks_repo_forks_event_min_datetime": "2016-08-20T17:56:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-11T04:10:42.000Z", "avg_line_length": 36.1793103448, "max_line_length": 157, "alphanum_fraction": 0.6501143729, "num_tokens": 2781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.25905992423747265}}
{"text": "/* Copyright 2015 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/\n\n// Loss Op\n\n#include <stdio.h>\n#include <cfloat>\n#include <math.h> \n#include <vector>\n#include <ctime>\n#include <cstdlib>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"third_party/eigen3/Eigen/Core\"\n#include \"third_party/eigen3/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\n#define POSE_CHANNELS 4\n\nusing namespace tensorflow;\ntypedef Eigen::ThreadPoolDevice CPUDevice;\n\nREGISTER_OP(\"Averagedistance\")\n    .Attr(\"T: {float, double}\")\n    .Attr(\"margin: float\")\n    .Input(\"bottom_prediction: T\")\n    .Input(\"bottom_target: T\")\n    .Input(\"bottom_weight: T\")\n    .Input(\"bottom_point: T\")\n    .Input(\"bottom_symmetry: T\")\n    .Output(\"loss: T\")\n    .Output(\"bottom_diff: T\");\n\nREGISTER_OP(\"AveragedistanceGrad\")\n    .Attr(\"T: {float, double}\")\n    .Attr(\"margin: float\")\n    .Input(\"bottom_diff: T\")\n    .Input(\"grad: T\")\n    .Output(\"output: T\");\n\ntemplate <typename Device, typename T>\nclass AveragedistanceOp : public OpKernel {\n public:\n  explicit AveragedistanceOp(OpKernelConstruction* context) : OpKernel(context) \n  {\n    // Get the margin\n    OP_REQUIRES_OK(context,\n                   context->GetAttr(\"margin\", &margin_));\n    // Check that margin is positive\n    OP_REQUIRES(context, margin_ >= 0,\n                errors::InvalidArgument(\"Need margin >= 0, got \", margin_));\n  }\n\n  // bottom_prediction: (batch_size, 4 * num_classes)\n  // bottom_point: (num_classes, num_points, 3)\n  void Compute(OpKernelContext* context) override \n  {\n    // Grab the input tensor\n    const Tensor& bottom_prediction = context->input(0);\n    const T* prediction = bottom_prediction.flat<T>().data();\n\n    const Tensor& bottom_target = context->input(1);\n    const T* target = bottom_target.flat<T>().data();\n\n    const Tensor& bottom_weight = context->input(2);\n    const T* weight = bottom_weight.flat<T>().data();\n\n    const Tensor& bottom_point = context->input(3);\n    const T* point = bottom_point.flat<T>().data();\n\n    const Tensor& bottom_symmetry = context->input(4);\n    const T* symmetry = bottom_symmetry.flat<T>().data();\n\n    // data should have 4 dimensions.\n    OP_REQUIRES(context, bottom_prediction.dims() == 2,\n                errors::InvalidArgument(\"prediction must be 2-dimensional\"));\n\n    OP_REQUIRES(context, bottom_target.dims() == 2,\n                errors::InvalidArgument(\"target must be 2-dimensional\"));\n\n    OP_REQUIRES(context, bottom_weight.dims() == 2,\n                errors::InvalidArgument(\"weight must be 2-dimensional\"));\n\n    OP_REQUIRES(context, bottom_point.dims() == 3,\n                errors::InvalidArgument(\"point must be 3-dimensional\"));\n\n    OP_REQUIRES(context, bottom_symmetry.dims() == 1,\n                errors::InvalidArgument(\"symmetry must be 1-dimensional\"));\n\n    // batch size\n    int batch_size = bottom_prediction.dim_size(0);\n    int num_classes = bottom_point.dim_size(0);\n    int num_points = bottom_point.dim_size(1);\n\n    // Create output loss tensor\n    int dim = 1;\n    TensorShape output_shape;\n    TensorShapeUtils::MakeShape(&dim, 1, &output_shape);\n\n    Tensor* top_data_tensor = NULL;\n    OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &top_data_tensor));\n    auto top_data = top_data_tensor->template flat<T>();\n\n    // bottom diff\n    TensorShape output_shape_diff = bottom_prediction.shape();\n    Tensor* bottom_diff_tensor = NULL;\n    OP_REQUIRES_OK(context, context->allocate_output(1, output_shape_diff, &bottom_diff_tensor));\n    T* bottom_diff = bottom_diff_tensor->template flat<T>().data();\n    memset(bottom_diff, 0, batch_size * POSE_CHANNELS * num_classes *sizeof(T));\n\n    T loss = 0;\n    // for each object\n    for (int n = 0; n < batch_size; n++)\n    {\n      // find the class label and pose of this object\n      int index_cls = -1;\n      Eigen::Quaternionf pose_gt;\n      Eigen::Quaternionf pose_u;\n      for (int i = 0; i < POSE_CHANNELS * num_classes; i += POSE_CHANNELS)\n      {\n        int index = n * POSE_CHANNELS * num_classes + i;\n        if (weight[index] > 0)\n        {\n          index_cls = i / POSE_CHANNELS;\n\n          pose_gt.w() = target[index + 0];\n          pose_gt.x() = target[index + 1];\n          pose_gt.y() = target[index + 2];\n          pose_gt.z() = target[index + 3];\n\n          pose_u.w() = prediction[index + 0];\n          pose_u.x() = prediction[index + 1];\n          pose_u.y() = prediction[index + 2];\n          pose_u.z() = prediction[index + 3];\n          break;\n        }\n      }\n      if (index_cls == -1)\n        continue;\n\n      // rotation matrix\n      Eigen::Matrix3f Rgt = pose_gt.toRotationMatrix();\n      Eigen::Matrix3f Ru = pose_u.toRotationMatrix();\n\n      // derivatives of Ru to quaternion\n      Eigen::Matrix3f Ru_w;\n      Ru_w << 2 * pose_u.w(), -2 * pose_u.z(), 2 * pose_u.y(),\n              2 * pose_u.z(), 2 * pose_u.w(), -2 * pose_u.x(),\n              -2 * pose_u.y(), 2 * pose_u.x(), 2 * pose_u.w();\n\n      Eigen::Matrix3f Ru_x;\n      Ru_x << 2 * pose_u.x(), 2 * pose_u.y(), 2 * pose_u.z(),\n              2 * pose_u.y(), -2 * pose_u.x(), -2 * pose_u.w(),\n              2 * pose_u.z(), 2 * pose_u.w(), -2 * pose_u.x();\n\n      Eigen::Matrix3f Ru_y;\n      Ru_y << -2 * pose_u.y(), 2 * pose_u.x(), 2 * pose_u.w(),\n              2 * pose_u.x(), 2 * pose_u.y(), 2 * pose_u.z(),\n              -2 * pose_u.w(), 2 * pose_u.z(), -2 * pose_u.y();\n\n      Eigen::Matrix3f Ru_z;\n      Ru_z << -2 * pose_u.z(), -2 * pose_u.w(), 2 * pose_u.x(),\n              2 * pose_u.w(), -2 * pose_u.z(), 2 * pose_u.y(),\n              2 * pose_u.x(), 2 * pose_u.y(), 2 * pose_u.z();\n\n      // for each point\n      for (int i = 0; i < num_points; i++)\n      {\n        int index = index_cls * num_points * 3 + i * 3;\n        Eigen::Vector3f x3d(point[index], point[index + 1], point[index + 2]);\n        Eigen::Vector3f diff = Ru * x3d - Rgt * x3d;\n        T distance = diff.dot(diff);\n        if (distance < margin_)\n          continue;\n        loss += (distance - margin_) / 2.0;\n\n        // compute the gradient from this point\n        Eigen::Matrix3f f0;\n        f0 << x3d[0], x3d[1], x3d[2],\n              0, 0, 0,\n              0, 0, 0;\n\n        Eigen::Matrix3f f1;\n        f1 << 0, 0, 0,\n              x3d[0], x3d[1], x3d[2],\n              0, 0, 0;\n\n        Eigen::Matrix3f f2;\n        f2 << 0, 0, 0,\n              0, 0, 0,\n              x3d[0], x3d[1], x3d[2];\n\n        Eigen::Matrix3f f = diff[0] * f0 + diff[1] * f1 + diff[2] * f2;\n\n        int index_diff = n * POSE_CHANNELS * num_classes + POSE_CHANNELS * index_cls;\n        bottom_diff[index_diff + 0] += f.cwiseProduct(Ru_w).sum() / (batch_size * num_points);\n        bottom_diff[index_diff + 1] += f.cwiseProduct(Ru_x).sum() / (batch_size * num_points);\n        bottom_diff[index_diff + 2] += f.cwiseProduct(Ru_y).sum() / (batch_size * num_points);\n        bottom_diff[index_diff + 3] += f.cwiseProduct(Ru_z).sum() / (batch_size * num_points);\n      }\n    }\n    loss /= batch_size * num_points;\n    top_data(0) = loss;\n  }\n private:\n  float margin_;\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"Averagedistance\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), AveragedistanceOp<CPUDevice, float>);\nREGISTER_KERNEL_BUILDER(Name(\"Averagedistance\").Device(DEVICE_CPU).TypeConstraint<double>(\"T\"), AveragedistanceOp<CPUDevice, double>);\n\n// GPU implementation for forward pass\nbool AveragedistanceForwardLaucher(OpKernelContext* context,\n    const float* bottom_prediction, const float* bottom_target, const float* bottom_weight, const float* bottom_point,\n    const float* bottom_symmetry, const int batch_size, const int num_classes, const int num_points, const float margin,\n    float* top_data, float* bottom_diff, const Eigen::GpuDevice& d);\n\nstatic void AveragedistanceKernel(\n    OpKernelContext* context, const Tensor* bottom_prediction, const Tensor* bottom_target, const Tensor* bottom_weight,\n    const Tensor* bottom_point, const Tensor* bottom_symmetry, const int batch_size, const int num_classes, const int num_points, const float margin,\n    const TensorShape& tensor_output_shape, const TensorShape& tensor_output_shape_diff) \n{\n  Tensor* top_data = nullptr;\n  Tensor* bottom_diff = nullptr;\n  OP_REQUIRES_OK(context, context->allocate_output(0, tensor_output_shape, &top_data));\n  OP_REQUIRES_OK(context, context->allocate_output(1, tensor_output_shape_diff, &bottom_diff));\n\n  if (!context->status().ok()) {\n    return;\n  }\n\n   AveragedistanceForwardLaucher(context,\n    bottom_prediction->flat<float>().data(), bottom_target->flat<float>().data(), bottom_weight->flat<float>().data(),\n    bottom_point->flat<float>().data(), bottom_symmetry->flat<float>().data(), batch_size, num_classes, num_points, margin,\n    top_data->flat<float>().data(), bottom_diff->flat<float>().data(), context->eigen_device<Eigen::GpuDevice>());\n}\n\ntemplate <class T>\nclass AveragedistanceOp<Eigen::GpuDevice, T> : public OpKernel {\n public:\n  typedef Eigen::GpuDevice Device;\n\n  explicit AveragedistanceOp(OpKernelConstruction* context) : OpKernel(context) \n  {\n    // Get the margin\n    OP_REQUIRES_OK(context,\n                   context->GetAttr(\"margin\", &margin_));\n    // Check that margin is positive\n    OP_REQUIRES(context, margin_ >= 0,\n                errors::InvalidArgument(\"Need margin >= 0, got \", margin_));\n  }\n\n  void Compute(OpKernelContext* context) override \n  {\n    // Grab the input tensor\n    const Tensor& bottom_prediction = context->input(0);\n    const Tensor& bottom_target = context->input(1);\n    const Tensor& bottom_weight = context->input(2);\n    const Tensor& bottom_point = context->input(3);\n    const Tensor& bottom_symmetry = context->input(4);\n\n    // data should have 4 dimensions.\n    OP_REQUIRES(context, bottom_prediction.dims() == 2,\n                errors::InvalidArgument(\"prediction must be 2-dimensional\"));\n\n    OP_REQUIRES(context, bottom_target.dims() == 2,\n                errors::InvalidArgument(\"target must be 2-dimensional\"));\n\n    OP_REQUIRES(context, bottom_weight.dims() == 2,\n                errors::InvalidArgument(\"weight must be 2-dimensional\"));\n\n    OP_REQUIRES(context, bottom_point.dims() == 3,\n                errors::InvalidArgument(\"point must be 3-dimensional\"));\n\n    OP_REQUIRES(context, bottom_symmetry.dims() == 1,\n                errors::InvalidArgument(\"symmetry must be 1-dimensional\"));\n\n    // batch size\n    int batch_size = bottom_prediction.dim_size(0);\n    int num_classes = bottom_point.dim_size(0);\n    int num_points = bottom_point.dim_size(1);\n\n//    int num_dimensions = bottom_prediction.shape().dims();\n//    std::cout << \"DIMS: \" << num_dimensions << std::endl;\n//    for(int ii_dim=0; ii_dim<num_dimensions; ii_dim++) {\n//        std::cout << bottom_prediction.shape().dim_size(ii_dim)) << std::endl;\n//    }\n\n    // Create output tensors\n    // loss\n    int dim = 1;\n    TensorShape output_shape;\n// SLoss\n//    TensorShapeUtils::MakeShape(&dim, 1, &output_shape);\n// SLoss modified\n    TensorShapeUtils::MakeShape(&batch_size, 1, &output_shape);\n\n    // bottom diff\n    TensorShape output_shape_diff = bottom_prediction.shape();\n\n    AveragedistanceKernel(context, &bottom_prediction, &bottom_target, &bottom_weight, &bottom_point, &bottom_symmetry, batch_size, num_classes,\n      num_points, margin_, output_shape, output_shape_diff);\n  }\n private:\n  float margin_;\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"Averagedistance\").Device(DEVICE_GPU).TypeConstraint<float>(\"T\"), AveragedistanceOp<Eigen::GpuDevice, float>);\n\n// compute gradient\ntemplate <class Device, class T>\nclass AveragedistanceGradOp : public OpKernel {\n public:\n  explicit AveragedistanceGradOp(OpKernelConstruction* context) : OpKernel(context) \n  {\n    // Get the margin\n    OP_REQUIRES_OK(context,\n                   context->GetAttr(\"margin\", &margin_));\n    // Check that margin is positive\n    OP_REQUIRES(context, margin_ >= 0,\n                errors::InvalidArgument(\"Need margin >= 0, got \", margin_));\n  }\n\n  void Compute(OpKernelContext* context) override \n  {\n    const Tensor& bottom_diff = context->input(0);\n    auto bottom_diff_flat = bottom_diff.flat<T>();\n    \n    const Tensor& out_backprop = context->input(1);\n    T loss = out_backprop.flat<T>()(0);\n\n    // data should have 4 dimensions.\n    OP_REQUIRES(context, bottom_diff.dims() == 2,\n                errors::InvalidArgument(\"bottom diff must be 2-dimensional\"));\n\n    // batch size\n    int batch_size = bottom_diff.dim_size(0);\n    // number of channels\n    int num_channels = bottom_diff.dim_size(1);\n\n    // construct the output shape\n    TensorShape output_shape = bottom_diff.shape();\n    Tensor* output = nullptr;\n    OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));\n    auto top_data = output->template flat<T>();\n\n    for (int i = 0; i < batch_size * num_channels; i++)\n      top_data(i) = loss * bottom_diff_flat(i);\n  }\n private:\n  float margin_;\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"AveragedistanceGrad\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), AveragedistanceGradOp<CPUDevice, float>);\n\nbool AveragedistanceBackwardLaucher(const float* top_diff, const float* bottom_diff, const int batch_size,\n    const int channels, float* output, const Eigen::GpuDevice& d);\n\nstatic void AveragedistanceGradKernel(\n    OpKernelContext* context, const Tensor* bottom_diff, const Tensor* out_backprop,\n    const int batch_size, const int channels,\n    const TensorShape& tensor_output_shape) \n{\n  Tensor* output = nullptr;\n  OP_REQUIRES_OK(context, context->allocate_output(0, tensor_output_shape, &output));\n\n  if (!context->status().ok()) {\n    return;\n  }\n\n  AveragedistanceBackwardLaucher(\n    out_backprop->flat<float>().data(), bottom_diff->flat<float>().data(),\n    batch_size, channels, output->flat<float>().data(), context->eigen_device<Eigen::GpuDevice>());\n}\n\n\ntemplate <class T>\nclass AveragedistanceGradOp<Eigen::GpuDevice, T> : public OpKernel {\n public:\n  typedef Eigen::GpuDevice Device;\n\n  explicit AveragedistanceGradOp(OpKernelConstruction* context) : OpKernel(context) \n  {\n    // Get the margin\n    OP_REQUIRES_OK(context,\n                   context->GetAttr(\"margin\", &margin_));\n    // Check that margin is positive\n    OP_REQUIRES(context, margin_ >= 0,\n                errors::InvalidArgument(\"Need margin >= 0, got \", margin_));\n  }\n\n  void Compute(OpKernelContext* context) override \n  {\n    const Tensor& bottom_diff = context->input(0);\n    const Tensor& out_backprop = context->input(1);\n\n    // data should have 2 dimensions.\n    OP_REQUIRES(context, bottom_diff.dims() == 2,\n                errors::InvalidArgument(\"bottom diff must be 2-dimensional\"));\n\n    // batch size\n    int batch_size = bottom_diff.dim_size(0);\n    // number of channels\n    int num_channels = bottom_diff.dim_size(1);\n\n    // construct the output shape\n    TensorShape output_shape = bottom_diff.shape();\n\n    // run the kernel\n    AveragedistanceGradKernel(\n      context, &bottom_diff, &out_backprop, batch_size, num_channels, output_shape);\n  }\n private:\n  float margin_;\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"AveragedistanceGrad\").Device(DEVICE_GPU).TypeConstraint<float>(\"T\"), AveragedistanceGradOp<Eigen::GpuDevice, float>);\n", "meta": {"hexsha": "04edb297684c675fb4893094786f14af9d17e170", "size": 15871, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/average_distance_loss/average_distance_loss_op.cc", "max_stars_repo_name": "Kaju-Bubanja/PoseCNN", "max_stars_repo_head_hexsha": "c2f7c4e8f98bc7c67d5cbc0be3167d3cb3bea396", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2018-08-30T08:02:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-15T12:22:22.000Z", "max_issues_repo_path": "lib/average_distance_loss/average_distance_loss_op.cc", "max_issues_repo_name": "Kaju-Bubanja/PoseCNN", "max_issues_repo_head_hexsha": "c2f7c4e8f98bc7c67d5cbc0be3167d3cb3bea396", "max_issues_repo_licenses": ["MIT"], "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/average_distance_loss/average_distance_loss_op.cc", "max_forks_repo_name": "Kaju-Bubanja/PoseCNN", "max_forks_repo_head_hexsha": "c2f7c4e8f98bc7c67d5cbc0be3167d3cb3bea396", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-10-16T15:01:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-29T03:52:51.000Z", "avg_line_length": 36.6535796767, "max_line_length": 149, "alphanum_fraction": 0.656417365, "num_tokens": 4070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2589972738248425}}
{"text": "#ifndef GUNEROTRANSACTIONRECEIVE_GADGET_H_\n#define GUNEROTRANSACTIONRECEIVE_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 RECEIVE PROOF /////\n// Public Parameters:\n// Authorization Root Hash (W)\n// Token UID (T)\n// Sender Account View Hash (V_S)\n// Receiver Account View Hash (V_R)\n// Current Transaction Hash (L)\n\n// Private Parameters:\n// Receiver Account Secret Key (s_R)\n// Receiver Account View Randomizer (r_R)\n// Sender Account Address (A_S)\n// Sender Account View Randomizer (r_S)\n// Firearm Serial Number (F)\n// Firearm View Randomizer (j)\n// alt: Receiver Account (A_R)\n// alt: Sender Proof Public Key (P_proof_S)\n\n//1) Obtain A_R from s_R through EDCSA operations\n//1 alt) Obtain P_proof_R from s_R 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 T == hash(F, j) (Both parties know the serial number)\n//5) Validate L == hash(A_S, hash(s_R, hash(T, W)) (The send proof is consistent, not forged)\ntemplate<typename FieldT, typename BaseT, typename HashT>\nclass gunerotransactionreceive_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;\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_R;\n    std::shared_ptr<digest_variable<FieldT>> r_R;\n    std::shared_ptr<digest_variable<FieldT>> A_S;\n    std::shared_ptr<digest_variable<FieldT>> r_S;\n    std::shared_ptr<digest_variable<FieldT>> F;\n    std::shared_ptr<digest_variable<FieldT>> j;\n    std::shared_ptr<digest_variable<FieldT>> A_R;//alt\n    std::shared_ptr<digest_variable<FieldT>> P_proof_S;//alt\n\n    // Computed variables\n    std::shared_ptr<digest_variable<FieldT>> P_proof_R;\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<HashT> token_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    gunerotransactionreceive_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);\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_R.reset(new digest_variable<FieldT>(pb, 256, \"\"));//252\n\n        r_R.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        A_S.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        r_S.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        F.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        j.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        A_R.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        P_proof_S.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        P_proof_R.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_R->bits,\n        //     P_proof_R\n        // ));\n        spend_authority.reset(new HashT(\n            pb,\n            *s_R,\n            *ZERO,\n            *P_proof_R,\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        //T == hash(F, j)\n        token_hasher.reset(new HashT(\n            pb,\n            *F,\n            *j,\n            *T,\n            \"token_hasher\"));\n\n        //L == hash(A_S, hash(s_R, hash(T, W))\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,\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_R,\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_S,\n            *transaction_hash_2_digest,\n            *L,\n            \"transaction_hash_3_hasher\"));\n    }\n\n    ~gunerotransactionreceive_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\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_R->generate_r1cs_constraints();\n\n        r_R->generate_r1cs_constraints();\n\n        A_S->generate_r1cs_constraints();\n\n        r_S->generate_r1cs_constraints();\n\n        F->generate_r1cs_constraints();\n\n        j->generate_r1cs_constraints();\n\n        A_R->generate_r1cs_constraints();\n\n        P_proof_S->generate_r1cs_constraints();\n\n        P_proof_R->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        token_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    // Authorization Root Hash (W)\n    // Token UID (T)\n    // Sender Account View Hash (V_S)\n    // Receiver Account View Hash (V_R)\n    // Current Transaction Hash (L)\n\n    // Private Parameters:\n    // Receiver Private Key (s_R)\n    // Receiver Account View Randomizer (r_R)\n    // Sender Account Address (A_S)\n    // Sender Account View Randomizer (r_S)\n    // Firearm Serial Number (F)\n    // Firearm View Randomizer (j)\n    // alt: Account (A_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,\n        const uint252& ps_R,\n        const uint256& pr_R,\n        const uint160& pA_S,\n        const uint256& pr_S,\n        const uint256& pF,\n        const uint256& pj,\n        const uint160& pA_R,\n        const uint256& pP_proof_S\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. This is not a sanity check.\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->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(pL)\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_R for the input\n        s_R->bits.fill_with_bits(\n            this->pb,\n            uint252_to_bool_vector_256(ps_R)\n        );\n\n        // Witness P_proof_R for s_R with PRF_addr\n        spend_authority->generate_r1cs_witness();\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_S for the input\n        A_S->bits.fill_with_bits(\n            this->pb,\n            uint160_to_bool_vector_256_rpad(pA_S)\n        );\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 F for the input\n        F->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(pF)\n        );\n\n        // Witness j for the input\n        j->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(pj)\n        );\n\n        // Witness A_R for the input\n        A_R->bits.fill_with_bits(\n            this->pb,\n            uint160_to_bool_vector_256_rpad(pA_R)\n        );\n\n        // Witness P_proof_S for the input\n        P_proof_S->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(pP_proof_S)\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 hash(F, j) = T\n        token_hasher->generate_r1cs_witness();\n\n        // Witness //transaction_hash_1_digest = hash(T, W)\n        transaction_hash_1_hasher->generate_r1cs_witness();\n\n        // Witness //transaction_hash_2_digest = hash(s_R, transaction_hash_1_digest)\n        transaction_hash_2_hasher->generate_r1cs_witness();\n\n        // Witness //L == hash(A_S, 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        T->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(pT)\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_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->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(pL)\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\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);\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 /* GUNEROTRANSACTIONRECEIVE_GADGET_H_ */", "meta": {"hexsha": "d19f75bfddb00fd1343b715f372673e5f8ebeb3a", "size": 19451, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/gunerotransactionreceive_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/gunerotransactionreceive_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/gunerotransactionreceive_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": 32.7457912458, "max_line_length": 124, "alphanum_fraction": 0.6347745617, "num_tokens": 4900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.2589953820692792}}
{"text": "#include \"model_class.h\"\n\n#include \"frame_data.h\"\n#include \"focal_grid.h\"\n\n#include <string>\n#include <stdint.h>\n#include <iostream>\n#include <iomanip>\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <chrono>\n#include <vector>\n#include <list>\n#include <ctime>\n#include <algorithm>\n#include <dirent.h>\n#include <armadillo>\n#include \"json.hpp\"\n\n#include <vtkPolyData.h>\n#include <vtkSTLReader.h>\n#include <vtkSmartPointer.h>\n#include <vtkPolyDataMapper.h>\n#include <vtkPolyDataSilhouette.h>\n#include <vtkMatrix4x4.h>\n#include <vtkTransform.h>\n#include <vtkTransformPolyDataFilter.h>\n#include <vtkPoints.h>\n#include <vtkLine.h>\n#include <vtkCellArray.h>\n#include <vtkExtractEdges.h>\n#include <vtkCleanPolyData.h>\n#include <vtkPolyDataConnectivityFilter.h>\n\n#include <vtkPointData.h>\n#include <vtkSelectEnclosedPoints.h>\n#include <vtkIntArray.h>\n#include <vtkDataArray.h>\n#include <vtkVertexGlyphFilter.h>\n#include <vtkProperty.h>\n\n#include <vtkSurfaceReconstructionFilter.h>\n#include <vtkProgrammableSource.h>\n#include <vtkContourFilter.h>\n#include <vtkReverseSense.h>\n\n#include <vtkBooleanOperationPolyDataFilter.h>\n\n#include <vtkCenterOfMass.h>\n\n#include <CGAL/basic.h>\n//#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n#include <CGAL/Boolean_set_operations_2.h>\n#include <CGAL/algorithm.h>\n#include <CGAL/assertions.h>\n#include <CGAL/Line_2.h>\n#include <CGAL/Polygon_2.h>\n#include <CGAL/Polygon_with_holes_2.h>\n#include <CGAL/Polygon_set_2.h>\n#include <CGAL/connect_holes.h>\n\n#include <CGAL/Cartesian.h>\n#include <CGAL/MP_Float.h>\n#include <CGAL/Quotient.h>\n#include <CGAL/Arr_segment_traits_2.h>\n#include <CGAL/Arrangement_2.h>\n#include <CGAL/Arr_walk_along_line_point_location.h>\n//#include \"arr_print.h\"\n\n#include <boost/math/special_functions/factorials.hpp>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel KI;\ntypedef CGAL::Exact_predicates_exact_constructions_kernel KE;\n\ntypedef KI::Point_2 \t\t\t\t   Point_2;\ntypedef KI::Line_2\t\t\t\t\t   Line_2;\ntypedef CGAL::Polygon_2<KI>            Polygon_2;\ntypedef CGAL::Polygon_with_holes_2<KI> Polygon_with_holes_2;\ntypedef CGAL::Polygon_set_2<KI> \t   Polygon_set_2;\n\ntypedef Polygon_2::Vertex_iterator \t\t\tVertexIterator;\ntypedef Polygon_2::Edge_const_iterator \t\tEdgeIterator;\ntypedef Polygon_2::Edge_const_circulator \tEdgeCirculator;\n\ntypedef CGAL::Quotient<int>                                     Number_type;\ntypedef CGAL::Cartesian<Number_type>                            Kernel;\ntypedef CGAL::Arr_segment_traits_2<KE>                      \tTraits_2;\ntypedef Traits_2::Point_2                                       Point_arr_2;\ntypedef Traits_2::X_monotone_curve_2                            Segment_2;\ntypedef CGAL::Arrangement_2<Traits_2>                           Arrangement_2;\ntypedef CGAL::Arr_walk_along_line_point_location<Arrangement_2> Walk_pl;\ntypedef CGAL::Arr_segment_traits_2<KE> \t\t\t\t\t\t\tSegment_traits_2;\n\n\n\n#define PI 3.14159265\n\nusing namespace std;\n\nusing json = nlohmann::json;\n\nModelClass::ModelClass() {\n\t// empty\n}\n\nbool ModelClass::LoadModel(session_data &session) {\n\tbool model_loaded = true;\n\ttry {\n\n\t\tstring mdl_name = session.model_name;\n\t\tsize_t dot_pos = mdl_name.find(\".\");\n\n\t\tcout << mdl_name.erase(dot_pos,5) << endl;\n\t\t\n\t\tchdir(session.model_loc.c_str());\n\n\t\t// Load JSON file:\n\t\tifstream in_file(session.model_name.c_str());\n\t\tjson loaded_file;\n\t\tin_file >> loaded_file;\n\n\t\t// Set parameters:\n\t\tmodel_name = mdl_name.erase(dot_pos,5);\n\n\t\tN_components = loaded_file[\"N_components\"];\n\t\tN_joints = loaded_file[\"N_joints\"];\n\n\t\tstl_list.clear();\n\t\tparent_list.clear();\n\n\t\tfor (int i=0; i<N_components; i++) {\n\t\t\tstl_list.push_back(loaded_file[\"stl_list\"][i]);\n\t\t\tint N_temp = loaded_file[\"parent_list\"][i].size();\n\t\t\tvector<int> kin_tree;\n\t\t\tfor (int k=0; k<N_temp; k++) {\n\t\t\t\tkin_tree.push_back(loaded_file[\"parent_list\"][i][k]);\n\t\t\t}\n\t\t\tparent_list.push_back(kin_tree);\n\t\t}\n\n\t\tjoint_type_list.clear();\n\t\tjoint_param_parent.clear();\n\t\tjoint_param_child.clear();\n\n\t\tfor (int j=0; j<N_joints; j++) {\n\t\t\tjoint_type_list.push_back(loaded_file[\"joint_type_list\"][j]);\n\t\t\tint N_temp = loaded_file[\"joint_param_parent\"][j].size();\n\t\t\tvector<double> parent_param;\n\t\t\tvector<double> child_param;\n\t\t\tfor (int k=0; k<N_temp; k++) {\n\t\t\t\tparent_param.push_back(loaded_file[\"joint_param_parent\"][j][k]);\n\t\t\t\tchild_param.push_back(loaded_file[\"joint_param_child\"][j][k]);\n\t\t\t}\n\t\t\tjoint_param_parent.push_back(parent_param);\n\t\t\tjoint_param_child.push_back(child_param);\n\t\t}\n\n\t\t\n\t\tdrag_point_labels.clear();\n\t\tdrag_point_symbols.clear();\n\t\tdrag_point_colors.clear();\n\t\tdrag_point_start_pos.clear();\n\n\t\tint N_drag_pts = loaded_file[\"drag_point_labels\"].size();\n\n\t\tfor (int i=0; i<N_drag_pts; i++) {\n\t\t\tdrag_point_labels.push_back(loaded_file[\"drag_point_labels\"][i]);\n\t\t\tdrag_point_symbols.push_back(loaded_file[\"drag_point_symbols\"][i]);\n\t\t\tvector<int> pt_color;\n\t\t\tvector<double> start_pos;\n\t\t\tfor (int k=0; k<3; k++) {\n\t\t\t\tpt_color.push_back(loaded_file[\"drag_point_colors\"][i][k]);\n\t\t\t\tstart_pos.push_back(loaded_file[\"drag_point_start_pos\"][i][k]);\n\t\t\t}\n\t\t\tdrag_point_colors.push_back(pt_color);\n\t\t\tdrag_point_start_pos.push_back(start_pos);\n\t\t}\n\n\n\t\tdrag_line_connectivity.clear();\n\t\tdrag_line_colors.clear();\n\t\tscale_calc.clear();\n\n\t\tint N_drag_lns = loaded_file[\"drag_line_connectivity\"].size();\n\n\t\tfor (int j=0; j<N_drag_lns; j++) {\n\t\t\tvector<int> connectivity;\n\t\t\tvector<int> line_color;\n\t\t\tfor (int k=0; k<5; k++) {\n\t\t\t\tif (k<2) {\n\t\t\t\t\tconnectivity.push_back(loaded_file[\"drag_line_connectivity\"][j][k]);\n\t\t\t\t}\n\t\t\t\tline_color.push_back(loaded_file[\"drag_line_colors\"][j][k]);\n\t\t\t}\n\t\t\tdrag_line_connectivity.push_back(connectivity);\n\t\t\tdrag_line_colors.push_back(line_color);\n\t\t}\n\n\t\tscale_texts.clear();\n\t\tscale_calc.clear();\n\n\t\tfor (int i=0; i<loaded_file[\"scale_calc\"].size(); i++) {\n\t\t\tscale_texts.push_back(loaded_file[\"scale_texts\"][i]);\n\t\t\tscale_calc.push_back(loaded_file[\"scale_calc\"][i]);\n\t\t}\n\n\t\tlength_calc.clear();\n\n\t\tfor (int j=0; j<loaded_file[\"length_calc\"].size(); j++) {\n\t\t\tlength_calc.push_back(loaded_file[\"length_calc\"][j]);\n\t\t}\n\n\t\torigin_ind.clear();\n\n\t\tfor (int i=0; i<loaded_file[\"origin_indices\"].size(); i++) {\n\t\t\torigin_ind.push_back(loaded_file[\"origin_indices\"][i]);\n\t\t}\n\n\t\tcontour_calc.clear();\n\n\t\tfor (int j=0; j<loaded_file[\"contour_calc\"].size(); j++) {\n\t\t\tcontour_calc.push_back(loaded_file[\"contour_calc\"][j]);\n\t\t}\n\n\t\tsrf_angle = loaded_file[\"srf_angle\"];\n\n\t\tstate_calc.clear();\n\n\t\tfor (int i=0; i<loaded_file[\"state_calc\"].size(); i++) {\n\t\t\tstate_calc.push_back(loaded_file[\"state_calc\"][i]);\n\t\t}\n\n\t}\n\tcatch(...) {\n\t\tmodel_loaded = false;\n\t}\n\treturn model_loaded;\n}\n\nvector<arma::Mat<double>> ModelClass::ReturnStartState() {\n\tint N_parents;\n\tdouble scale_now;\n\tdouble scale_parent;\n\tdouble scale_child;\n\tarma::Col<double> state_parent(7);\n\tarma::Col<double> state_child(7);\n\tarma::Mat<double> M_parent(4,4);\n\tarma::Mat<double> M_child(4,4);\n\tarma::Mat<double> M_out;\n\tvector<arma::Mat<double>> M_start;\n\tfor (int i=0; i<N_components; i++) {\n\t\tN_parents = parent_list[i].size();\n\t\tM_out.eye(4,4);\n\t\tfor (int j=0; j<N_parents; j++) {\n\t\t\tif (j>0) {\n\t\t\t\tscale_parent = model_scale[parent_list[i][j-1]];\n\t\t\t\tstate_parent(0) = joint_param_parent[parent_list[i][j]][0];\n\t\t\t\tstate_parent(1) = joint_param_parent[parent_list[i][j]][1];\n\t\t\t\tstate_parent(2) = joint_param_parent[parent_list[i][j]][2];\n\t\t\t\tstate_parent(3) = joint_param_parent[parent_list[i][j]][3];\n\t\t\t\tstate_parent(4) = joint_param_parent[parent_list[i][j]][4]*scale_parent;\n\t\t\t\tstate_parent(5) = joint_param_parent[parent_list[i][j]][5]*scale_parent;\n\t\t\t\tstate_parent(6) = joint_param_parent[parent_list[i][j]][6]*scale_parent;\n\t\t\t\tM_parent = ModelClass::GetM(state_parent);\n\t\t\t\tscale_child = model_scale[parent_list[i][j]];\n\t\t\t\tstate_child(0) = joint_param_child[parent_list[i][j]][0];\n\t\t\t\tstate_child(1) = joint_param_child[parent_list[i][j]][1];\n\t\t\t\tstate_child(2) = joint_param_child[parent_list[i][j]][2];\n\t\t\t\tstate_child(3) = joint_param_child[parent_list[i][j]][3];\n\t\t\t\tstate_child(4) = joint_param_child[parent_list[i][j]][4]*scale_child;\n\t\t\t\tstate_child(5) = joint_param_child[parent_list[i][j]][5]*scale_child;\n\t\t\t\tstate_child(6) = joint_param_child[parent_list[i][j]][6]*scale_child;\n\t\t\t\tM_child = ModelClass::GetM(state_child);\n\t\t\t\tM_out = ModelClass::MultiplyM(M_out,ModelClass::MultiplyM(M_parent,M_child));\n\t\t\t}\n\t\t\telse {\n\t\t\t\t//scale_now = model_scale[parent_list[i][j]];\n\t\t\t\tscale_parent = 1.0;\n\t\t\t\tstate_parent(0) = joint_param_parent[parent_list[i][j]][0];\n\t\t\t\tstate_parent(1) = joint_param_parent[parent_list[i][j]][1];\n\t\t\t\tstate_parent(2) = joint_param_parent[parent_list[i][j]][2];\n\t\t\t\tstate_parent(3) = joint_param_parent[parent_list[i][j]][3];\n\t\t\t\tstate_parent(4) = joint_param_parent[parent_list[i][j]][4]*scale_parent;\n\t\t\t\tstate_parent(5) = joint_param_parent[parent_list[i][j]][5]*scale_parent;\n\t\t\t\tstate_parent(6) = joint_param_parent[parent_list[i][j]][6]*scale_parent;\n\t\t\t\tM_parent = ModelClass::GetM(state_parent);\n\t\t\t\tscale_child = model_scale[parent_list[i][j]];\n\t\t\t\tstate_child(0) = joint_param_child[parent_list[i][j]][0];\n\t\t\t\tstate_child(1) = joint_param_child[parent_list[i][j]][1];\n\t\t\t\tstate_child(2) = joint_param_child[parent_list[i][j]][2];\n\t\t\t\tstate_child(3) = joint_param_child[parent_list[i][j]][3];\n\t\t\t\tstate_child(4) = joint_param_child[parent_list[i][j]][4]*scale_child;\n\t\t\t\tstate_child(5) = joint_param_child[parent_list[i][j]][5]*scale_child;\n\t\t\t\tstate_child(6) = joint_param_child[parent_list[i][j]][6]*scale_child;\n\t\t\t\tM_child = ModelClass::GetM(state_child);\n\t\t\t\tM_out = ModelClass::MultiplyM(M_out,ModelClass::MultiplyM(M_parent,M_child));\n\t\t\t}\n\t\t}\n\t\tM_start.push_back(M_out);\n\t}\n\treturn M_start;\n}\n\nvector<double> ModelClass::ReturnSRCState(vector<double> state_in) {\n\n\tint N_parents;\n\tdouble scale_now;\n\tdouble scale_parent;\n\tdouble scale_child;\n\tvector<double> state_out;\n\n\tarma::Mat<double> X_mat;\n\tX_mat.zeros(7,5);\n\t\n\tX_mat(0,0) = state_in[0];\n\tX_mat(1,0) = state_in[1];\n\tX_mat(2,0) = state_in[2];\n\tX_mat(3,0) = state_in[3];\n\tX_mat(4,0) = state_in[4];\n\tX_mat(5,0) = state_in[5];\n\tX_mat(6,0) = state_in[6];\n\tX_mat(0,3) = state_in[7];\n\tX_mat(1,3) = state_in[8];\n\tX_mat(2,3) = state_in[9];\n\tX_mat(3,3) = state_in[10];\n\tX_mat(0,4) = state_in[11];\n\tX_mat(1,4) = state_in[12];\n\tX_mat(2,4) = state_in[13];\n\tX_mat(3,4) = state_in[14];\n\n\tarma::Col<double> state_now;\n\tstate_now.zeros(7);\n\tarma::Col<double> state_parent;\n\tstate_parent.zeros(7);\n\tarma::Col<double> state_child;\n\tstate_child.zeros(7);\n\tarma::Mat<double> M_parent(4,4);\n\tarma::Mat<double> M_child(4,4);\n\tarma::Mat<double> M_state(4,4);\n\tarma::Mat<double> M_out;\n\tfor (int i=0; i<N_components; i++) {\n\t\tN_parents = parent_list[i].size();\n\t\tM_out.eye(4,4);\n\t\tfor (int j=0; j<N_parents; j++) {\n\t\t\tif (j>0) {\n\t\t\t\tif (state_calc[parent_list[i][j]] >= 0) {\n\t\t\t\t\tstate_now = X_mat.col(parent_list[i][j]);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tstate_now = {1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};\n\t\t\t\t}\n\t\t\t\tM_state = ModelClass::GetM(state_now);\n\t\t\t\tscale_parent = model_scale[parent_list[i][j-1]];\n\t\t\t\tstate_parent(0) = joint_param_parent[parent_list[i][j]][0];\n\t\t\t\tstate_parent(1) = joint_param_parent[parent_list[i][j]][1];\n\t\t\t\tstate_parent(2) = joint_param_parent[parent_list[i][j]][2];\n\t\t\t\tstate_parent(3) = joint_param_parent[parent_list[i][j]][3];\n\t\t\t\tstate_parent(4) = joint_param_parent[parent_list[i][j]][4]*scale_parent;\n\t\t\t\tstate_parent(5) = joint_param_parent[parent_list[i][j]][5]*scale_parent;\n\t\t\t\tstate_parent(6) = joint_param_parent[parent_list[i][j]][6]*scale_parent;\n\t\t\t\tM_parent = ModelClass::GetM(state_parent);\n\t\t\t\tscale_child = model_scale[parent_list[i][j]];\n\t\t\t\tstate_child(0) = joint_param_child[parent_list[i][j]][0];\n\t\t\t\tstate_child(1) = joint_param_child[parent_list[i][j]][1];\n\t\t\t\tstate_child(2) = joint_param_child[parent_list[i][j]][2];\n\t\t\t\tstate_child(3) = joint_param_child[parent_list[i][j]][3];\n\t\t\t\tstate_child(4) = joint_param_child[parent_list[i][j]][4]*scale_child;\n\t\t\t\tstate_child(5) = joint_param_child[parent_list[i][j]][5]*scale_child;\n\t\t\t\tstate_child(6) = joint_param_child[parent_list[i][j]][6]*scale_child;\n\t\t\t\tM_child = ModelClass::GetM(state_child);\n\t\t\t\tM_out = ModelClass::MultiplyM(M_out,ModelClass::MultiplyM(M_parent,ModelClass::MultiplyM(M_state,M_child)));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (state_calc[parent_list[i][j]] >= 0) {\n\t\t\t\t\tstate_now = X_mat.col(parent_list[i][j]);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tstate_now = {1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};\n\t\t\t\t}\n\t\t\t\tM_state = ModelClass::GetM(state_now);\n\t\t\t\tscale_child = model_scale[parent_list[i][j]];\n\t\t\t\tstate_child(0) = joint_param_child[parent_list[i][j]][0];\n\t\t\t\tstate_child(1) = joint_param_child[parent_list[i][j]][1];\n\t\t\t\tstate_child(2) = joint_param_child[parent_list[i][j]][2];\n\t\t\t\tstate_child(3) = joint_param_child[parent_list[i][j]][3];\n\t\t\t\tstate_child(4) = joint_param_child[parent_list[i][j]][4]*scale_child;\n\t\t\t\tstate_child(5) = joint_param_child[parent_list[i][j]][5]*scale_child;\n\t\t\t\tstate_child(6) = joint_param_child[parent_list[i][j]][6]*scale_child;\n\t\t\t\tM_child = ModelClass::GetM(state_child);\n\t\t\t\tM_out = ModelClass::MultiplyM(M_out,ModelClass::MultiplyM(M_state,M_child));\n\t\t\t}\n\t\t}\n\t\tarma::Col<double> state_vec =  ModelClass::GetStateFromM(M_out);\n\t\tstate_out.push_back(state_vec(0));\n\t\tstate_out.push_back(state_vec(1));\n\t\tstate_out.push_back(state_vec(2));\n\t\tstate_out.push_back(state_vec(3));\n\t\tstate_out.push_back(state_vec(4));\n\t\tstate_out.push_back(state_vec(5));\n\t\tstate_out.push_back(state_vec(6));\n\t}\n\treturn state_out;\n}\n\nvector<arma::Mat<double>> ModelClass::ReturnInitState(frame_data &frame_in) {\n\tint N_parents;\n\tdouble scale_now;\n\tdouble scale_parent;\n\tdouble scale_child;\n\tarma::Col<double> state_now(7);\n\tarma::Col<double> state_parent(7);\n\tarma::Col<double> state_child(7);\n\tarma::Mat<double> M_parent(4,4);\n\tarma::Mat<double> M_child(4,4);\n\tarma::Mat<double> M_state(4,4);\n\tarma::Mat<double> M_out;\n\tvector<arma::Mat<double>> M_init;\n\tfor (int i=0; i<N_components; i++) {\n\t\tN_parents = parent_list[i].size();\n\t\tM_out.eye(4,4);\n\t\tfor (int j=0; j<N_parents; j++) {\n\t\t\tif (j>0) {\n\t\t\t\tif (state_calc[parent_list[i][j]] >= 0) {\n\t\t\t\t\tstate_now = frame_in.init_state.col(state_calc[parent_list[i][j]]);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tstate_now = {1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};\n\t\t\t\t}\n\t\t\t\tM_state = ModelClass::GetM(state_now);\n\t\t\t\tscale_parent = model_scale[parent_list[i][j-1]];\n\t\t\t\tstate_parent(0) = joint_param_parent[parent_list[i][j]][0];\n\t\t\t\tstate_parent(1) = joint_param_parent[parent_list[i][j]][1];\n\t\t\t\tstate_parent(2) = joint_param_parent[parent_list[i][j]][2];\n\t\t\t\tstate_parent(3) = joint_param_parent[parent_list[i][j]][3];\n\t\t\t\tstate_parent(4) = joint_param_parent[parent_list[i][j]][4]*scale_parent;\n\t\t\t\tstate_parent(5) = joint_param_parent[parent_list[i][j]][5]*scale_parent;\n\t\t\t\tstate_parent(6) = joint_param_parent[parent_list[i][j]][6]*scale_parent;\n\t\t\t\tM_parent = ModelClass::GetM(state_parent);\n\t\t\t\tscale_child = model_scale[parent_list[i][j]];\n\t\t\t\tstate_child(0) = joint_param_child[parent_list[i][j]][0];\n\t\t\t\tstate_child(1) = joint_param_child[parent_list[i][j]][1];\n\t\t\t\tstate_child(2) = joint_param_child[parent_list[i][j]][2];\n\t\t\t\tstate_child(3) = joint_param_child[parent_list[i][j]][3];\n\t\t\t\tstate_child(4) = joint_param_child[parent_list[i][j]][4]*scale_child;\n\t\t\t\tstate_child(5) = joint_param_child[parent_list[i][j]][5]*scale_child;\n\t\t\t\tstate_child(6) = joint_param_child[parent_list[i][j]][6]*scale_child;\n\t\t\t\tM_child = ModelClass::GetM(state_child);\n\t\t\t\tM_out = ModelClass::MultiplyM(M_out,ModelClass::MultiplyM(M_parent,ModelClass::MultiplyM(M_state,M_child)));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (state_calc[parent_list[i][j]] >= 0) {\n\t\t\t\t\tstate_now = frame_in.init_state.col(state_calc[parent_list[i][j]]);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tstate_now = {1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};\n\t\t\t\t}\n\t\t\t\tM_state = ModelClass::GetM(state_now);\n\t\t\t\tscale_child = model_scale[parent_list[i][j]];\n\t\t\t\tstate_child(0) = joint_param_child[parent_list[i][j]][0];\n\t\t\t\tstate_child(1) = joint_param_child[parent_list[i][j]][1];\n\t\t\t\tstate_child(2) = joint_param_child[parent_list[i][j]][2];\n\t\t\t\tstate_child(3) = joint_param_child[parent_list[i][j]][3];\n\t\t\t\tstate_child(4) = joint_param_child[parent_list[i][j]][4]*scale_child;\n\t\t\t\tstate_child(5) = joint_param_child[parent_list[i][j]][5]*scale_child;\n\t\t\t\tstate_child(6) = joint_param_child[parent_list[i][j]][6]*scale_child;\n\t\t\t\tM_child = ModelClass::GetM(state_child);\n\t\t\t\tM_out = ModelClass::MultiplyM(M_out,ModelClass::MultiplyM(M_state,M_child));\n\t\t\t}\n\t\t}\n\t\tM_init.push_back(M_out);\n\t}\n\treturn M_init;\n}\n\nvector<Polygon_2> ModelClass::ReturnSilhouette(FocalGrid &fg, vector<arma::Mat<double>> M_state, arma::Col<double> view_vec, int cam_nr) {\n\tvector<Polygon_2> silhouette_vec;\n\n\tfor (int i=0; i<N_components; i++) {\n\t\tdouble view_vector[3] = {view_vec(0),view_vec(1),view_vec(2)};\n\t\tvtkSmartPointer<vtkPolyData> polyDataTrans = ModelClass::TransformPolyData(model_polydata[i],M_state[i],model_scale[i]);\n\t\tsilhouette_vec.push_back(ModelClass::GetSilhouette(fg, polyDataTrans, view_vector, cam_nr));\n\t}\n\n\treturn silhouette_vec;\n}\n\nvector<Polygon_2> ModelClass::ReturnSilhouette2(FocalGrid &fg, vector<double> state_vec, int cam_nr) {\n\tvector<Polygon_2> silhouette_vec;\n\tarma::Col<double> view_vec = fg.CalculateViewVector(cam_nr);\n\tfor (int i=0; i<N_components; i++) {\n\t\tarma::Col<double> state_in = {state_vec[i*7],state_vec[i*7+1],state_vec[i*7+2],state_vec[i*7+3],state_vec[i*7+4],state_vec[i*7+5],state_vec[i*7+6]};\n\t\tdouble view_vector[3] = {view_vec(0),view_vec(1),view_vec(2)};\n\t\tvtkSmartPointer<vtkPolyData> polyDataTrans = ModelClass::TransformPolyData(model_polydata[i],ModelClass::GetM(state_in),model_scale[i]);\n\t\tsilhouette_vec.push_back(ModelClass::GetSilhouette(fg, polyDataTrans, view_vector, cam_nr));\n\t}\n\n\treturn silhouette_vec;\n}\n\nvoid ModelClass::SetStrokeBounds(double StrokeBound) {\n\tstroke_bound = StrokeBound;\n}\n\nvoid ModelClass::SetDeviationBounds(double DeviationBound) {\n\tdeviation_bound = DeviationBound;\n}\n\nvoid ModelClass::SetWingPitchBounds(double WingPitchBound) {\n\twing_pitch_bound = WingPitchBound;\n}\n\nbool ModelClass::SetModel(session_data &session) {\n\tbool success = true;\n\ttry {\n\t\tModelClass::LoadModelMesh(session);\n\t}\n\tcatch(...) {\n\t\tsuccess = false;\n\t}\n\treturn success;\n}\n\nbool ModelClass::LoadModelMesh(session_data &session) {\n\tbool success = true;\n\ttry {\n\t\tmodel_polydata.clear();\n\t\tfor (int i=0; i<N_components; i++) {\n\t\t\tmodel_polydata.push_back(ModelClass::LoadSTLFile(session.model_loc,stl_list[i]));\n\t\t}\n\t}\n\tcatch(...) {\n\t\tsuccess = false;\n\t}\n\treturn success;\n}\n\nvoid ModelClass::TestPointInsidePolygonSpeed(arma::Mat<double> &pcl_in) {\n\n\tint N_points = pcl_in.n_cols;\n\n\tcout << \"N_points \" << N_points << endl;\n\n\tvtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();\n\n\tfor (int i=0; i<N_points; i++) {\n\t\tdouble t_point[3] = {pcl_in(0,i), pcl_in(1,i), pcl_in(2,i)};\n\t\tpoints->InsertNextPoint(t_point);\n\t}\n\n\tvtkSmartPointer<vtkPolyData> pointsPolydata = vtkSmartPointer<vtkPolyData>::New();\n  \tpointsPolydata->SetPoints(points);\n\n\t//Points inside test\n\tvtkSmartPointer<vtkSelectEnclosedPoints> selectEnclosedPoints = vtkSmartPointer<vtkSelectEnclosedPoints>::New();\n\n\tselectEnclosedPoints->SetInputData(pointsPolydata);\n\n\tselectEnclosedPoints->SetSurfaceData(model_polydata[0]);\n\n\tselectEnclosedPoints->Update();\n\n\t// Select enclosed points\n\tvtkDataArray* insideArray = vtkDataArray::SafeDownCast(selectEnclosedPoints->GetOutput()->GetPointData()->GetArray(\"SelectedPoints\"));\n\n\tarma::Row<int> pts_inside_array(insideArray->GetNumberOfTuples());\n\n  \tfor(vtkIdType j = 0; j < insideArray->GetNumberOfTuples(); j++)\n    { \n    \tpts_inside_array(j) = insideArray->GetComponent(j,0);\n    }\n\n}\n\nvoid ModelClass::Test3DIntersection() {\n\n\tvtkSmartPointer<vtkBooleanOperationPolyDataFilter> booleanOperation = vtkSmartPointer<vtkBooleanOperationPolyDataFilter>::New();\n\tbooleanOperation->SetOperationToIntersection();\n\tbooleanOperation->SetInputData( 0, model_polydata[0] );\n\tbooleanOperation->SetInputData( 1, model_polydata[2] );\n\tbooleanOperation->Update();\n\n}\n\nvoid ModelClass::TestPoissonSurfaceReconstruction(arma::Mat<double> &pcl_in) {\n\n\tint N_points = pcl_in.n_cols;\n\n\tcout << \"N_points \" << N_points << endl;\n\n\tvtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();\n\n\tfor (int i=0; i<N_points; i++) {\n\t\tdouble t_point[3] = {pcl_in(0,i), pcl_in(1,i), pcl_in(2,i)};\n\t\tpoints->InsertNextPoint(t_point);\n\t}\n\n\tvtkSmartPointer<vtkPolyData> pointsPolydata = vtkSmartPointer<vtkPolyData>::New();\n  \tpointsPolydata->SetPoints(points);\n\n  \t// Construct the surface and create isosurface.\t\n\tvtkSmartPointer<vtkSurfaceReconstructionFilter> surf = vtkSmartPointer<vtkSurfaceReconstructionFilter>::New();\\\n\tsurf->SetInputData(pointsPolydata);\n\n\tvtkSmartPointer<vtkContourFilter> cf = vtkSmartPointer<vtkContourFilter>::New();\n\tcf->SetInputConnection(surf->GetOutputPort());\n\tcf->SetValue(0, 0.0);\n\n\tcf->Update();\n\n\t// Sometimes the contouring algorithm can create a volume whose gradient\n  \t// vector and ordering of polygon (using the right hand rule) are\n  \t// inconsistent. vtkReverseSense cures this problem.\n  \tvtkSmartPointer<vtkReverseSense> reverse = vtkSmartPointer<vtkReverseSense>::New();\n\treverse->SetInputConnection(cf->GetOutputPort());\n\treverse->ReverseCellsOn();\n\treverse->ReverseNormalsOn();\n\n\treverse->Update();\n\n\t//vtkSmartPointer<vtkPolyData> poissonPoly = vtkSmartPointer<vtkPolyData>::New();\n\t//poissonPoly->SetPoints(reverse);\n\n\tvtkSmartPointer<vtkCenterOfMass> centerOfMassFilter = vtkSmartPointer<vtkCenterOfMass>::New();\n\n\tcenterOfMassFilter->SetInputConnection(reverse->GetOutputPort());\n\n\tcenterOfMassFilter->SetUseScalarsAsWeights(false);\n\tcenterOfMassFilter->Update();\n\t \n\tdouble center[3];\n\tcenterOfMassFilter->GetCenter(center);\n\n\tstd::cout << \"Center of mass is \" << center[0] << \" \" << center[1] << \" \" << center[2] << std::endl;\n\n}\n\nvtkSmartPointer<vtkPolyData> ModelClass::LoadSTLFile(string FileLoc, string FileName) {\n\n\tvtkSmartPointer<vtkPolyData> polyData = ModelClass::stlReader(FileLoc, FileName);\n\n\treturn polyData;\n}\n\nvector<arma::Mat<double>> ModelClass::ReturnModelPCL(vector<arma::Mat<double>> M_in) {\n\n\tvector<arma::Mat<double>> pcl_out;\n\n\tarma::Mat<double> pcl_now;\n\n\tfor (int i=0; i<N_components; i++) {\n\t\tpcl_now = model_pcls[i];\n\t\tpcl_out.push_back(M_in[i]*pcl_now);\n\t}\n\n\treturn pcl_out;\n}\n\nvector<arma::Mat<double>> ModelClass::ReturnInitPCL(vector<arma::Mat<double>> M_in) {\n\n\tarma::Mat<double> init_body_pcl;\n\tarma::Mat<double> init_wing_L_pcl;\n\tarma::Mat<double> init_wing_R_pcl;\n\n\tarma::Mat<double> pcl_now;\n\tarma::Mat<double> pcl_scaled;\n\n\tfor (int i=0; i<N_components; i++) {\n\t\tif (state_calc[i] == 0) {\n\t\t\tpcl_now = model_pcls[i];\n\t\t\tpcl_scaled = pcl_now*model_scale[i];\n\t\t\tpcl_scaled.row(3).fill(1.0);\n\t\t\tinit_body_pcl = M_in[i]*pcl_scaled;\n\t\t}\n\t\telse if (state_calc[i] == 1) {\n\t\t\tpcl_now = model_pcls[i];\n\t\t\tpcl_scaled = pcl_now*model_scale[i];\n\t\t\tpcl_scaled.row(3).fill(1.0);\n\t\t\tinit_wing_L_pcl = M_in[i]*pcl_scaled;\n\t\t}\n\t\telse if (state_calc[i] == 2) {\n\t\t\tpcl_now = model_pcls[i];\n\t\t\tpcl_scaled = pcl_now*model_scale[i];\n\t\t\tpcl_scaled.row(3).fill(1.0);\n\t\t\tinit_wing_R_pcl = M_in[i]*pcl_scaled;\n\t\t}\n\t\telse {\n\t\t\tpcl_now = model_pcls[i];\n\t\t\tpcl_scaled = pcl_now*model_scale[i];\n\t\t\tpcl_scaled.row(3).fill(1.0);\n\t\t\tinit_body_pcl = arma::join_rows(init_body_pcl,M_in[i]*pcl_scaled);\n\t\t}\n\t}\n\n\tvector<arma::Mat<double>> pcl_out;\n\n\tpcl_out.push_back(init_body_pcl);\n\tpcl_out.push_back(init_wing_L_pcl);\n\tpcl_out.push_back(init_wing_R_pcl);\n\n\treturn pcl_out;\n\n}\n\nvtkSmartPointer<vtkPolyData> ModelClass::TransformPolyData(vtkSmartPointer<vtkPolyData> polyData, arma::Mat<double> M_in, double scale_in) {\n\n\tvtkSmartPointer<vtkMatrix4x4> M_t = vtkSmartPointer<vtkMatrix4x4>::New();\n\n\tM_t->SetElement(0,0,M_in(0,0));\n\tM_t->SetElement(0,1,M_in(0,1));\n\tM_t->SetElement(0,2,M_in(0,2));\n\tM_t->SetElement(0,3,M_in(0,3));\n\tM_t->SetElement(1,0,M_in(1,0));\n\tM_t->SetElement(1,1,M_in(1,1));\n\tM_t->SetElement(1,2,M_in(1,2));\n\tM_t->SetElement(1,3,M_in(1,3));\n\tM_t->SetElement(2,0,M_in(2,0));\n\tM_t->SetElement(2,1,M_in(2,1));\n\tM_t->SetElement(2,2,M_in(2,2));\n\tM_t->SetElement(2,3,M_in(2,3));\n\tM_t->SetElement(3,0,M_in(3,0));\n\tM_t->SetElement(3,1,M_in(3,1));\n\tM_t->SetElement(3,2,M_in(3,2));\n\tM_t->SetElement(3,3,M_in(3,3));\n\n\tvtkSmartPointer<vtkTransform> transform = vtkSmartPointer<vtkTransform>::New();\n\n\ttransform->SetMatrix(M_t);\n\ttransform->Scale(scale_in,scale_in,scale_in);\n\n\tvtkSmartPointer<vtkTransformPolyDataFilter> transformPD = vtkSmartPointer<vtkTransformPolyDataFilter>::New();\n\n\ttransformPD->SetInputData(polyData);\n\ttransformPD->SetTransform(transform);\n\ttransformPD->Update();\n\n\t//vtkPolyData* polyDataOut = transformPD->GetOutput();\n\n\treturn transformPD->GetOutput();\n}\n\nPolygon_2 ModelClass::GetSilhouette(FocalGrid &fg, vtkSmartPointer<vtkPolyData> polyData, double view_vector[3], int cam_nr) {\n \n\tvtkSmartPointer<vtkPolyDataSilhouette> silhouette = vtkSmartPointer<vtkPolyDataSilhouette>::New();\n\tsilhouette->SetInputData(polyData);\n\tsilhouette->SetDirectionToSpecifiedVector();\n\tsilhouette->SetVector(view_vector);\n\tsilhouette->SetEnableFeatureAngle(0);\n\t//silhouette->BorderEdgesOff();\n\tsilhouette->Update();\n\n\tvtkPolyData* silhdata = silhouette->GetOutput();\n\n\tint N_lines = silhdata->GetNumberOfLines();\n\n\tarma::Mat<double> sil_mat(4,N_lines*2);\n\tarma::Row<int> id_list(N_lines*2);\n\n\tdouble p1[3];\n\tdouble p2[3];\n\n\tvtkSmartPointer<vtkIdList> idList = vtkSmartPointer<vtkIdList>::New();\n\tint iter = 0;\n\twhile (silhdata->GetLines()->GetNextCell(idList)) {\n\t\tsilhdata->GetPoint(idList->GetId(0),p1);\n\t\tsilhdata->GetPoint(idList->GetId(1),p2);\n\t\tid_list(iter*2) = idList->GetId(0);\n\t\tid_list(iter*2+1) = idList->GetId(1);\n\t\tsil_mat(0,iter*2) = p1[0];\n\t\tsil_mat(1,iter*2) = p1[1];\n\t\tsil_mat(2,iter*2) = p1[2];\n\t\tsil_mat(3,iter*2) = 1.0;\n\t\tsil_mat(0,iter*2+1) = p2[0];\n\t\tsil_mat(1,iter*2+1) = p2[1];\n\t\tsil_mat(2,iter*2+1) = p2[2];\n\t\tsil_mat(3,iter*2+1) = 1.0;\n\t\titer++;\n\t}\n\n\tarma::Mat<double> silh_pts = fg.ProjectCloud2UVdouble(sil_mat,cam_nr);\n\n\t// Insert the 2d segments in a 2d arrangement\n\tArrangement_2 arr;\n\tWalk_pl pl(arr);\n\tfor (int i=0; i<N_lines; i++) {\n\t\tSegment_2 s_now (Point_arr_2 (silh_pts(0,i*2), silh_pts(1,i*2)), Point_arr_2 (silh_pts(0,i*2+1), silh_pts(1,i*2+1)));\n\t\tinsert(arr, s_now, pl);\n\t}\n\n\tArrangement_2::Vertex_const_iterator vit;\n\n\tarma::Row<int> vertex_degree;\n\tvertex_degree.zeros(arr.number_of_vertices());\n\tarma::Mat<double> vertex_mat;\n\tvertex_mat.zeros(2,arr.number_of_vertices());\n\titer = 0;\n\tfor (vit = arr.vertices_begin(); vit != arr.vertices_end(); ++vit) {\n  \t\tvertex_degree(iter) = vit->degree();\n  \t\tvertex_mat(0,iter) = CGAL::to_double((vit->point()).x());\n  \t\tvertex_mat(1,iter) = CGAL::to_double((vit->point()).y());\n  \t\titer++;\n  \t}\n\n  \t//cout << vertex_mat << endl;\n\n  \t//cout << vertex_degree << endl;\n\n  \t// Find open ends:\n  \tarma::uvec open_ends = arma::find(vertex_degree==1);\n\n  \t//cout << open_ends << endl;\n\n  \tif (open_ends.is_empty()) {\n  \t\t//cout << \"no open ends\" << endl;\n  \t}\n  \telse {\n\t  \tint N_open_ends = open_ends.n_rows;\n\t  \t//cout << \"no of open ends: \" << N_open_ends << endl;\n\t  \tif (N_open_ends%2==0) {\n\t  \t\tint comb_arr[N_open_ends];\n\t  \t\tfor (int k=0; k<N_open_ends; k++) {\n\t  \t\t\tcomb_arr[k] = k;\n\t  \t\t}\n\n\t  \t\tsort(comb_arr,comb_arr+N_open_ends);\n\n\t  \t\tdo {\n\t  \t\t\tint add_2_mat = 0;\n\t\t\t\tfor (int i=0; i<(N_open_ends/2); i++) {\n\t\t\t\t\tif (comb_arr[i*2]<comb_arr[i*2+1]) {\n\t\t\t\t\t\tadd_2_mat++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (add_2_mat==(N_open_ends/2)) {\n\t\t    \t\tfor (int j=0; j<(N_open_ends/2); j++) {\n\t\t    \t\t\t//cout << comb_arr[j*2] << \" \" << comb_arr[j*2+1] << \" \";\n\t\t    \t\t\tSegment_2 s_now (Point_arr_2 (vertex_mat(0,open_ends(comb_arr[j*2])), vertex_mat(1,open_ends(comb_arr[j*2]))), \n\t\t    \t\t\tPoint_arr_2 (vertex_mat(0,open_ends(comb_arr[j*2+1])), vertex_mat(1,open_ends(comb_arr[j*2+1]))));\n\t\t    \t\t\tinsert(arr, s_now, pl);\n\t\t    \t\t}\n\t\t    \t\t//cout << endl;\n\t\t    \t}\n\t  \t\t} while (next_permutation(comb_arr,comb_arr+N_open_ends-1));\n\n\n  \t\t}\n  \t\telse {\n  \t\t\tcout << \"odd number of open ends\" << endl;\n  \t\t}\n  \t}\n\n  \t// Remove internal edges:\n  \tArrangement_2::Face_handle unb_face = arr.unbounded_face();\n  \tArrangement_2::Edge_iterator eit;\n  \tfor (eit = arr.edges_begin(); eit!=arr.edges_end(); ++eit) {\n  \t\tArrangement_2::Halfedge_handle he = eit;\n  \t\tif ((he->face()!=unb_face)&&(he->twin()->face()!=unb_face)) {\n  \t\t\tarr.remove_edge(eit);\n  \t\t}\n  \t}\n\n  \tPolygon_2 P_out;\n\n  \t//cout << \"Bounded faces: \" << endl;\n  \tArrangement_2::Face_iterator fit;\n  \tArrangement_2::Ccb_halfedge_const_circulator  curr;\n  \tfor (fit = arr.faces_begin(); fit != arr.faces_end(); ++fit) {\n  \t\tif(fit->is_unbounded()) {\n  \t\t\t//cout << \"unbounded face\" << endl;\n  \t\t}\n  \t\telse {\n  \t\t\t//cout << \"bounded face\" << endl;\n  \t\t\tcurr = fit->outer_ccb();\n  \t\t\t//cout << \"Direction \" << curr->direction() << endl;\n      \t\t//cout << curr->source()->point();\n      \t\t//P_out.push_back(Point_2 (CGAL::to_double((curr->source()->point()).x()), CGAL::to_double((curr->source()->point()).y())));\n      \t\tdo {\n        \t\t//cout << \" --> \" << curr->target()->point();\n        \t\t//cout << \"  direction \" << curr->direction();\n        \t\tP_out.push_back(Point_2 (CGAL::to_double((curr->target()->point()).x()), CGAL::to_double((curr->target()->point()).y())));\n        \t\t++curr;\n      \t\t} while (curr != fit->outer_ccb());\n      \t\t//cout << endl;\n  \t\t}\n  \t}\n\n\t//cout << \"N lines = \" << N_lines << endl;\n\n\t// Print the size of the arrangement.\n\t//cout << \"The arrangement size:\" << std::endl\n    //\t<< \"   V = \" << arr.number_of_vertices()\n    //    << \",  E = \" << arr.number_of_edges()\n    //    << \",  F = \" << arr.number_of_faces() << endl;\n\n    //Polygon_2 P_out;\n    \n    //Arrangement_2::Vertex_iterator vit2;\n    \n    //for (vit2 = arr.vertices_begin(); vit2 != arr.vertices_end(); ++vit2) {\n  \t\t//Arrangement_2::Vertex_handle ve = vit2;\n  \t\t//P_out.push_back(Point_2 (CGAL::to_double((vit2->point()).x()), CGAL::to_double((vit2->point()).y())));\n  \t\t//cout << vit2->point() << endl;\n  \t//}\n\n  \t//cout << \"P_out is simple: \" << P_out.is_simple() << endl;\n\n    //arma::uvec unique_ids = arma::find_unique(id_list);\n    //arma::Mat<double> unique_pts = silh_pts.cols(unique_ids);\n\n    //for (int j=0; j<unique_pts.n_cols; j++) {\n    //\tP_out.push_back(Point_2 (unique_pts(0,j), unique_pts(1,j)));\n    //}\n\n    return P_out;\n}\n\n/*\n\nPolygon_2 ModelClass::GetSilhouette(FocalGrid &fg, vtkSmartPointer<vtkPolyData> polyData, double view_vector[3], int cam_nr) {\n \n\tvtkSmartPointer<vtkPolyDataSilhouette> silhouette = vtkSmartPointer<vtkPolyDataSilhouette>::New();\n\tsilhouette->SetInputData(polyData);\n\tsilhouette->SetDirectionToSpecifiedVector();\n\tsilhouette->SetVector(view_vector);\n\tsilhouette->SetEnableFeatureAngle(0);\n\t//silhouette->BorderEdgesOff();\n\tsilhouette->Update();\n\n\tvtkPolyData* silhdata = silhouette->GetOutput();\n\n\t//vtkSmartPointer<vtkPolyDataConnectivityFilter> connectivityFilter = \n    //vtkSmartPointer<vtkPolyDataConnectivityFilter>::New();\n  \t//connectivityFilter->SetInputConnection(silhouette->GetOutputPort());\n  \t//connectivityFilter->SetExtractionModeToLargestRegion(); \n  \t//connectivityFilter->SetExtractionModeToClosestPointRegion();\n  \t//connectivityFilter->SetExtractionModeToAllRegions();\n  \t//connectivityFilter->Update();\n\n  \t//vtkPolyData* silhdata = connectivityFilter->GetOutput();\n\n  \t//vtkSmartPointer<vtkCleanPolyData> cleaner = vtkSmartPointer<vtkCleanPolyData>::New();\n  \t//cleaner->SetInputConnection(silhouette->GetOutputPort());\n  \t//cleaner->Update();\n\n  \t//vtkPolyData* silhdata = cleaner->GetOutput();\n\n\tint N_lines = silhdata->GetNumberOfLines();\n\n\tarma::Mat<double> sil_mat(4,N_lines*2);\n\tarma::Row<int> id_list(N_lines*2);\n\n\tdouble p1[3];\n\tdouble p2[3];\n\n\tvtkSmartPointer<vtkIdList> idList = vtkSmartPointer<vtkIdList>::New();\n\tint iter = 0;\n\twhile (silhdata->GetLines()->GetNextCell(idList)) {\n\t\tsilhdata->GetPoint(idList->GetId(0),p1);\n\t\tsilhdata->GetPoint(idList->GetId(1),p2);\n\t\tid_list(iter*2) = idList->GetId(0);\n\t\tid_list(iter*2+1) = idList->GetId(1);\n\t\tsil_mat(0,iter*2) = p1[0];\n\t\tsil_mat(1,iter*2) = p1[1];\n\t\tsil_mat(2,iter*2) = p1[2];\n\t\tsil_mat(3,iter*2) = 1.0;\n\t\tsil_mat(0,iter*2+1) = p2[0];\n\t\tsil_mat(1,iter*2+1) = p2[1];\n\t\tsil_mat(2,iter*2+1) = p2[2];\n\t\tsil_mat(3,iter*2+1) = 1.0;\n\t\titer++;\n\t}\n\n\tcout << \"id list\" << endl;\n\tcout << id_list << endl;\n\n\tarma::Mat<double> silh_pts = fg.ProjectCloud2UVdouble(sil_mat,cam_nr);\n\n\tvector<list<int>> line_seg_vec;\n\tlist<int> line_seg;\n\n\tint prev_id = id_list(0);\n\tint next_id = id_list(1);\n\tid_list(0) = -1;\n\tid_list(1) = -1;\n\tint count = 0;\n\n\twhile (count<(silh_pts.n_cols/2)) {\n\n\t\tif (prev_id<0 && next_id<0) {\n\t\t\tline_seg_vec.push_back(line_seg);\n\t\t\tline_seg.clear();\n\t\t\tarma::uvec ids_left = arma::find(id_list>-1);\n\t\t\tif (ids_left.is_empty()) {\n\t\t\t\tcount = silh_pts.n_cols/2;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprev_id = id_list(ids_left(0));\n\t\t\t\tnext_id = id_list(ids_left(0)+1);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tarma::uvec found_prev_ids = arma::find(id_list==prev_id);\n\n\t\t\tif (found_prev_ids.is_empty()) {\n\t\t\t\tprev_id = -10;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\tif (found_prev_ids(0)%2==0) {\n\t\t\t\t\t\tline_seg.push_front(found_prev_ids(0));\n\t\t\t\t\t\tprev_id = id_list(found_prev_ids(0)+1);\n\t\t\t\t\t\tid_list(found_prev_ids(0)) = -1;\n\t\t\t\t\t\tid_list(found_prev_ids(0)+1) = -1;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tline_seg.push_front(found_prev_ids(0)-1);\n\t\t\t\t\t\tprev_id = id_list(found_prev_ids(0)-1);\n\t\t\t\t\t\tid_list(found_prev_ids(0)) = -1;\n\t\t\t\t\t\tid_list(found_prev_ids(0)-1) = -1;\n\t\t\t\t\t}\n\t\t\t\t\tcount++;\n\t\t\t}\n\n\t\t\tarma::uvec found_next_ids = arma::find(id_list==next_id);\n\n\t\t\tif (found_next_ids.is_empty()) {\n\t\t\t\tnext_id = -10;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\tif (found_next_ids(0)%2==0) {\n\t\t\t\t\t\tline_seg.push_back(found_next_ids(0)+1);\n\t\t\t\t\t\tnext_id = id_list(found_next_ids(0)+1);\n\t\t\t\t\t\tid_list(found_next_ids(0)) = -1;\n\t\t\t\t\t\tid_list(found_next_ids(0)+1) = -1;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tline_seg.push_back(found_next_ids(0)-1);\n\t\t\t\t\t\tnext_id = id_list(found_next_ids(0)-1);\n\t\t\t\t\t\tid_list(found_next_ids(0)) = -1;\n\t\t\t\t\t\tid_list(found_next_ids(0)-1) = -1;\n\t\t\t\t\t}\n\t\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\n\t\tif (prev_id==next_id && prev_id+next_id>=0) {\n\t\t\tlist<int>::iterator it1 = line_seg.begin();\n\t\t\tit1 = line_seg.erase(it1);\n\t\t}\n\n\t}\n\n\tcout << \"finished\" << endl;\n\n\tint N_seg = line_seg_vec.size();\n\n\tarma::Row<int> connectivity_vec;\n\tconnectivity_vec.zeros(2*N_seg);\n\n\tif (N_seg>1) {\n\n\t\tarma::Mat<double> connectivity_pts(3,2*N_seg);\n\t\tarma::Row<int> connectivity_ids(2*N_seg);\n\t\tint connectivity_arr[2*(N_seg-1)];\n\t\tfor (int i=0; i<N_seg; i++) {\n\t\t\tif (i==0) {\n\t\t\t\tconnectivity_pts.col(i*2) = silh_pts.col(line_seg_vec[i].front());\n\t\t\t\tconnectivity_pts.col(i*2+1) = silh_pts.col(line_seg_vec[i].back());\n\t\t\t\tconnectivity_ids(i*2) = line_seg_vec[i].front();\n\t\t\t\tconnectivity_ids(i*2+1) = line_seg_vec[i].back();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconnectivity_arr[(i-1)*2] = i*2;\n\t\t\t\tconnectivity_arr[(i-1)*2+1] = i*2+1;\n\t\t\t\tconnectivity_pts.col(i*2) = silh_pts.col(line_seg_vec[i].front());\n\t\t\t\tconnectivity_pts.col(i*2+1) = silh_pts.col(line_seg_vec[i].back());\n\t\t\t\tconnectivity_ids(i*2) = line_seg_vec[i].front();\n\t\t\t\tconnectivity_ids(i*2+1) = line_seg_vec[i].back();\n\t\t\t}\n\t\t}\n\n\t\tsort(connectivity_arr, connectivity_arr+2*(N_seg-1));\n\n\t\tarma::Mat<int> connectivity_mat;\n\t\tconnectivity_mat.zeros(1,2*N_seg);\n\n\t\tint row_count = 0;\n\t\tdo {\n\t\t\tint add_2_mat = 0;\n\t\t\tfor (int j=0; j<(N_seg-1); j++) {\n\t\t\t\tif (abs(connectivity_arr[j*2]-connectivity_arr[j*2+1])==1) {\n\t\t\t\t\tadd_2_mat++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (add_2_mat==(N_seg-1)) {\n\t\t\t\tif (row_count==0) {\n\t\t\t\t\tconnectivity_mat(row_count,0) = 0;\n\t\t\t\t\tconnectivity_mat(row_count,1) = 1;\n\t\t\t\t\tfor (int j=0; j<(N_seg-1); j++) {\n\t\t\t\t\t\tconnectivity_mat(row_count,(j+1)*2) = connectivity_arr[j*2];\n\t\t\t\t\t\tconnectivity_mat(row_count,(j+1)*2+1) = connectivity_arr[j*2+1];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tarma::Row<int> temp_row(2*N_seg);\n\t\t\t\t\ttemp_row(0) = 0;\n\t\t\t\t\ttemp_row(1) = 1;\n\t\t\t\t\tfor (int j=0; j<(N_seg-1); j++) {\n\t\t\t\t\t\ttemp_row((j+1)*2) = connectivity_arr[j*2];\n\t\t\t\t\t\ttemp_row((j+1)*2+1) = connectivity_arr[j*2+1];\n\t\t\t\t\t}\n\t\t\t\t\tconnectivity_mat.insert_rows(row_count,temp_row);\n\t\t\t\t}\n\n\t\t\t\t// Check if lines intersect:\n\t\t\t\tPolygon_2 P_test;\n\t\t\t\tdouble pt_diff;\n\t\t\t\tfor (int i=0; i<N_seg; i++) {\n\t\t\t\t\tif (connectivity_ids(connectivity_mat(row_count,i*2))==connectivity_ids(connectivity_mat(row_count,i*2+1))) {\n\t\t\t\t\t\tP_test.push_back(Point_2 (connectivity_pts(0,connectivity_mat(row_count,i*2)), connectivity_pts(1,connectivity_mat(row_count,i*2))));\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tP_test.push_back(Point_2 (connectivity_pts(0,connectivity_mat(row_count,i*2)), connectivity_pts(1,connectivity_mat(row_count,i*2))));\n\t\t\t\t\t\tP_test.push_back(Point_2 (connectivity_pts(0,connectivity_mat(row_count,i*2+1)), connectivity_pts(1,connectivity_mat(row_count,i*2+1))));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (P_test.is_simple()==true) {\n\t\t\t\t\tconnectivity_vec = connectivity_mat.row(row_count);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\trow_count++;\n\t\t\t}\n\t\t} while (next_permutation(connectivity_arr, connectivity_arr+2*(N_seg-1)));\n\n\t}\n\telse {\n\t\tconnectivity_vec(0) = 0;\n\t\tconnectivity_vec(1) = 1;\n\t}\n\n\tcout << connectivity_vec << endl;\n\n\tPolygon_2 P_temp;\n\n\tint list_nr;\n\n\tlist<Segment_2> segment_list;\n\n\tcout << \"printing segments\" << endl;\n\tcout << N_seg << endl;\n\n\tfor (int i=0; i<N_seg; i++) {\n\t\tif (connectivity_vec(i*2)<connectivity_vec(i*2+1)) {\n\t\t\tlist_nr = connectivity_vec(i*2)/2;\n\t\t\tfor (list<int>::iterator it=line_seg_vec[i].begin(); it!=line_seg_vec[i].end(); ++it) {\n\t\t\t\tcout << \" \" << *it;\n\t\t\t\tPoint_2 t_p1 (silh_pts(0,*it), silh_pts(1,*it));\n\t\t\t\tPoint_2 t_p2 (silh_pts(0,next(*it)), silh_pts(1,next(*it)));\n\t\t\t\tsegment_list.push_back(Segment_2 (t_p1, t_p2));\n\t\t\t\tP_temp.push_back(Point_2 (silh_pts(0,*it), silh_pts(1,*it)));\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tlist_nr = (connectivity_vec(i*2)-1)/2;\n\t\t\tfor (list<int>::reverse_iterator rit=line_seg_vec[i].rbegin(); rit!=line_seg_vec[i].rend(); ++rit) {\n\t\t\t\tcout << \" \" << *rit;\n\t\t\t\tsegment_list.push_back(Point_2 (silh_pts(0,*rit), silh_pts(1,*rit)));\n\t\t\t\tP_temp.push_back(Point_2 (silh_pts(0,*rit), silh_pts(1,*rit)));\n\t\t\t}\n\t\t}\n\t}\n\n\tArrangement_2 arr;\n\tinsert(arr, segment_list.begin(), segment_list.end());\n\tfor (auto it = arr.begin_vertices(); it != arr.end_vertices(); ++it) {\n\t\tif (4 == it->degree()) {\n\t\t\tcout << \"intersection vertex \" << *it << endl;\n\t\t}\n\t}\n\n\tPolygon_2 P_temp;\n\n\tcout << \"printing segments\" << endl;\n\tcout << N_seg << endl;\n\n\tint list_nr;\n\n\tfor (int i=0; i<N_seg; i++) {\n\t\tif (connectivity_vec(i*2)<connectivity_vec(i*2+1)) {\n\t\t\tlist_nr = connectivity_vec(i*2)/2;\n\t\t\tfor (list<int>::iterator it=line_seg_vec[i].begin(); it!=line_seg_vec[i].end(); ++it) {\n\t\t\t\tcout << \" \" << *it;\n\t\t\t\tP_temp.push_back(Point_2 (silh_pts(0,*it), silh_pts(1,*it)));\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tlist_nr = (connectivity_vec(i*2)-1)/2;\n\t\t\tfor (list<int>::reverse_iterator rit=line_seg_vec[i].rbegin(); rit!=line_seg_vec[i].rend(); ++rit) {\n\t\t\t\tcout << \" \" << *rit;\n\t\t\t\tP_temp.push_back(Point_2 (silh_pts(0,*rit), silh_pts(1,*rit)));\n\t\t\t}\n\t\t}\n\t}\n\n\t// Iterate through the vertices, remove vertices which lay inside the contour:\n\t//for (VertexIterator vi = P_temp.vertices_begin(); vi != P_temp.vertices_end(); ++vi) {\n\t\t//cout << P_temp.bounded_side(*vi) << endl;\n\t\t//cout << CGAL::bounded_side_2(P_temp.vertices_begin(), P_temp.vertices_end(), *vi, KI()) << endl;\n\t//}\n\n\t//Polygon_with_holes_2 P_holes(P_temp);\n\n\tPolygon_2 P_out = P_temp;\n\n\tcout << \" \" << endl;\n\n\tcout << \"P_out is simple : \" << P_out.is_simple() << endl;\n\n\treturn P_out;\n}\n\n*/\n\nvtkSmartPointer<vtkPolyData> ModelClass::stlReader(string FileLoc, string FileName) {\n\n\tvtkSmartPointer<vtkPolyData> polyData;\n\n\tstring inputFilename = FileLoc + \"/\" + FileName;\n\tvtkSmartPointer<vtkSTLReader> reader = vtkSmartPointer<vtkSTLReader>::New();\n\treader->SetFileName(inputFilename.c_str());\n\treader->Update();\n\n\tvtkSmartPointer<vtkCleanPolyData> clean = vtkSmartPointer<vtkCleanPolyData>::New();\n\tclean->SetInputConnection(reader->GetOutputPort());\n\tclean->Update();\n\n\tpolyData = clean->GetOutput();\n\n\treturn polyData;\n}\n\nvoid ModelClass::SetScale(vector<double> scale_in) {\n\tmodel_scale.clear();\n\tcout << \"\" << endl;\n\tcout << \"------------------------------------------------\" << endl;\n\tcout << \"\" << endl;\n\tcout << \"model scales: \" << endl;\n\tfor (int i=0; i<N_components; i++) {\n\t\tcout << stl_list[i] << \": \" << to_string(scale_in[i]) << endl;\n\t\tmodel_scale.push_back(scale_in[i]);\n\t}\n\tcout << \"\" << endl;\n\tcout << \"------------------------------------------------\" << endl;\n\tcout << \"\" << endl;\n}\n\nvector<double> ModelClass::GetModelScale() {\n\treturn model_scale;\n}\n\nbool ModelClass::ScaleModelPCL() {\n\tbool success = true;\n\ttry {\n\t\tfor (int i=0; i<N_components; i++) {\n\t\t\tarma::Mat<double> scale_mat;\n\t\t\tscale_mat.eye(4,4);\n\t\t\tscale_mat(0,0) = model_scale[i];\n\t\t\tscale_mat(1,1) = model_scale[i];\n\t\t\tscale_mat(2,2) = model_scale[i];\n\t\t\tmodel_pcls[i] = scale_mat*model_pcls[i];\n\t\t}\n\t}\n\tcatch(...) {\n\t\tsuccess = false;\n\t}\n\treturn success;\n}\n\narma::Mat<double> ModelClass::GetM(arma::Col<double> state_in) {\n\n\tarma::Col<double> q_vec = {state_in(0),state_in(1),state_in(2),state_in(3)};\n\tq_vec = q_vec/sqrt(pow(q_vec(0),2)+pow(q_vec(1),2)+pow(q_vec(2),2)+pow(q_vec(3),2));\n\n\tdouble q0 = q_vec(0);\n\tdouble q1 = q_vec(1);\n\tdouble q2 = q_vec(2);\n\tdouble q3 = q_vec(3);\n\tdouble tx = state_in(4);\n\tdouble ty = state_in(5);\n\tdouble tz = state_in(6);\n\n\tarma::Mat<double> M = {{2.0*pow(q0,2.0)-1.0+2.0*pow(q1,2.0), 2.0*q1*q2+2.0*q0*q3, 2.0*q1*q3-2.0*q0*q2, tx},\n\t\t{2.0*q1*q2-2.0*q0*q3, 2.0*pow(q0,2.0)-1.0+2.0*pow(q2,2.0), 2.0*q2*q3+2.0*q0*q1, ty},\n\t\t{2.0*q1*q3+2.0*q0*q2, 2.0*q2*q3-2.0*q0*q1, 2.0*pow(q0,2.0)-1.0+2.0*pow(q3,2.0), tz},\n\t\t{0.0, 0.0, 0.0, 1.0}};\n\n\treturn M;\n}\n\narma::Col<double> ModelClass::GetStateFromM(arma::Mat<double> M_in) {\n\n\tdouble q0 = 0.5*sqrt(M_in(0,0)+M_in(1,1)+M_in(2,2)+1.0);\n\tdouble q1 = (M_in(1,2)-M_in(2,1))/(4.0*q0);\n\tdouble q2 = (M_in(2,0)-M_in(0,2))/(4.0*q0);\n\tdouble q3 = (M_in(0,1)-M_in(1,0))/(4.0*q0);\n\tdouble tx = M_in(0,3);\n\tdouble ty = M_in(1,3);\n\tdouble tz = M_in(2,3);\n\n\tarma::Col<double> q = {q0, q1, q2, q3};\n\tq = q/arma::norm(q);\n\n\tarma::Col<double> state_out = {q(0), q(1), q(2), q(3), tx, ty, tz};\n\n\treturn state_out;\n}\n\narma::Mat<double> ModelClass::MultiplyM(arma::Mat<double> MA, arma::Mat<double> MB) {\n\n\tarma::Mat<double> RA = MA.submat(0,0,2,2);\n\tarma::Mat<double> RB = MB.submat(0,0,2,2);\n\tarma::Mat<double> RC = RA*RB;\n\tarma::Mat<double> MC;\n\tMC.eye(4,4);\n\tMC.submat(0,0,2,2) = RC;\n\tarma::Col<double> TA(3);\n\tarma::Col<double> TB(3);\n\tTA(0) = MA(0,3);\n\tTA(1) = MA(1,3);\n\tTA(2) = MA(2,3);\n\tTB(0) = MB(0,3);\n\tTB(1) = MB(1,3);\n\tTB(2) = MB(2,3);\n\tarma::Col<double> TC = TA+RA*TB;\n\tMC(0,3) = TC(0);\n\tMC(1,3) = TC(1);\n\tMC(2,3) = TC(2);\n\treturn MC;\n}\n\narma::Mat<double> ModelClass::TransposeM(arma::Mat<double> M_in) {\n\tarma::Mat<double> M_out;\n\tM_out.eye(4,4);\n\tM_out.submat(0,0,2,2) = M_in.submat(0,0,2,2).t();\n\tM_out(0,3) = M_in(0,3);\n\tM_out(1,3) = M_in(1,3);\n\tM_out(2,3) = M_in(2,3);\n\treturn M_out;\n}\n\nvector<string> ModelClass::GetPointLabels() {\n\treturn drag_point_labels;\n}\n\nvector<string> ModelClass::GetPointSymbols() {\n\treturn drag_point_symbols;\n}\n\nvector<vector<int>> ModelClass::GetPointColors() {\n\treturn drag_point_colors;\n}\n\nvector<vector<double>> ModelClass::GetPointStartPos() {\n\treturn drag_point_start_pos;\n}\n\nvector<vector<int>> ModelClass::GetLineConnectivity() {\n\treturn drag_line_connectivity;\n}\n\nvector<vector<int>> ModelClass::GetLineColors() {\n\treturn drag_line_colors;\n}\n\nvector<string> ModelClass::GetScaleTexts() {\n\treturn scale_texts;\n}\n\nvector<vector<int>> ModelClass::GetScaleCalc() {\n\treturn scale_calc;\n}\n\nvector<vector<int>> ModelClass::GetLengthCalc() {\n\treturn length_calc;\n}\n\nvector<int> ModelClass::GetContourCalc() {\n\treturn contour_calc;\n}\n\nvector<int> ModelClass::GetOriginInd() {\n\treturn origin_ind;\n}", "meta": {"hexsha": "426fa47bd723d2ea3414504617886a453d4bc032", "size": 43653, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "model_class.cpp", "max_stars_repo_name": "jmmelis/DipteraTrack", "max_stars_repo_head_hexsha": "1d267ccd4248635233147f2035b900a433dc4536", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-14T10:19:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-14T10:19:19.000Z", "max_issues_repo_path": "model_class.cpp", "max_issues_repo_name": "jmmelis/DipteraTrack", "max_issues_repo_head_hexsha": "1d267ccd4248635233147f2035b900a433dc4536", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model_class.cpp", "max_forks_repo_name": "jmmelis/DipteraTrack", "max_forks_repo_head_hexsha": "1d267ccd4248635233147f2035b900a433dc4536", "max_forks_repo_licenses": ["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.2700573066, "max_line_length": 150, "alphanum_fraction": 0.6774563031, "num_tokens": 13610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.25898770215519706}}
{"text": "#include <stdexcept>\n#include <algorithm>\n#include <functional>\n#include <iterator>\n#include <cmath>\n\n#ifdef DEBUG\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <sstream>\n#endif\n\n#include \"maxtri.h\"\n#include \"intersection.h\"\n\n#include <boost/graph/bron_kerbosch_all_cliques.hpp>\n#ifdef MAXTRI_DEBUG\n#include <boost/graph/graphviz.hpp>\n#endif\n\nusing namespace std;\nusing namespace boost;\n\n// competitive facility location algorithms\nnamespace cfla { namespace tri\n{\n\ntemplate<class Tp_>\nMaxTri<Tp_>::~MaxTri(void)\n{\n  status.clear();\n  tris.clear();\n  polys.clear();\n  if (graph)\n  {\n    delete graph;\n    graph = nullptr;\n  }\n}\n\ntemplate<class Tp_>\ntemplate<typename Iter>\nvoid\nMaxTri<Tp_>::\nintersect_range(status_seg_type const& segment, Iter begin, Iter end)\n{\n  // Check intersection with each segment from [neighbor, end).\n  point_type current_point = status_compare::isect_sweep(segment, current_y());\n\n  // See the comments on IXEvent for why this is a loop.\n  while (begin != end)\n  {\n#ifdef MAXTRI_DEBUG_INTERSECT\n    cerr << \"    checking intersection with \" << *begin << endl;\n#endif\n\n    // Check for intersections and queue any we find.\n    // Do not queue filthy degenerates or points we've already visited.\n    point_type pt;\n    char code = intersect(segment.edge(), begin->edge(), pt);\n    if ('0' != code && 'v' != code && 'e' != code\n        && event_point_ycompare()(pt, current_point))\n    {\n#ifdef MAXTRI_DEBUG_INTERSECT\n      cerr << \"    found intersection '\" << code << \"' \" << pt << endl;\n#endif\n\n      // We need to look up the intersection in the intersection map to see if\n      // we've already found an intersection here.\n      auto ixit = intersections.find(pt);\n\n      // If it doesn't exist yet, this is the first intersection at this point.\n      if (ixit == intersections.end())\n      {\n        auto insert = intersections.insert(make_pair(pt, isect_event_type(pt)));\n        assert(insert.second);\n        ixit = insert.first; // ref to the newly inserted pair.\n\n        // Queue the intersection the first time we find it.\n        // Subsequent intersections at the same point will just add segments.\n        queue().emplace(ixit->second);\n      }\n\n      // Record that these segments also form this intersection.\n      ixit->second.insert(segment, *begin);\n    }\n\n    ++begin;\n  }\n}\n\n// Check new intersections for a segment based on the current status.\ntemplate<class Tp_>\nvoid MaxTri<Tp_>::\ncheck_intersections(status_iterator center)\n{\n  // don't call us with a bad segment!\n  assert(center != status.end());\n\n#ifdef MAXTRI_DEBUG_INTERSECT\n  cerr << \"    looking for intersections around \" << *center << endl;\n#endif\n\n  auto range = status.equal_range(*center);\n\n  // Innner bounds.\n  status_iterator right = range.second;\n  status_iterator left = range.first;\n\n  /* The following diagram illustrates the iterators below referring to\n   * segments in the sweep status, where the same letter indicates segments in\n   * the same equal_range:\n   *\n   *      0  1  2      3  4  5      6  7  8      9 10 11     12 13 14\n   *    ---------------------------------------------------------------\n   *   |  X  X  X      L  L  L      C  C  C      R  R  R      Z  Z  Z  |\n   *    ---------------------------------------------------------------\n   *            ^      ^     ^      ^  ^         ^            ^\n   *     left_end      |     |      |  | center  |            right_end\n   *         left_last |     |      | left       | right (upper_bound)\n   *              left_begin |    (lower_bound)  | right_begin\n   *\n   * Ultimately, we want to check *center for intersections with all the\n   * left (L) and right (R) segments, but not the segments in its own range (C).\n   * We use reverse iterators in the left direction, and forward iterators in\n   * the right direction so the actual checking code in intersect_range can be\n   * the same.\n   */\n\n  // Look for intersections with the left-adjacent edge(s).\n  if (left != status.end() && left != status.begin())\n  {\n    // Move out of the lower_bound on center into the range to the left.\n    // Nb. converting to reverse_iterator subtracts 1 from the pointer.\n    status_riterator left_begin = status_riterator(left);\n\n    status_iterator left_last = status.lower_bound(*left_begin);\n    status_riterator left_end = status.rend();\n\n    if (left_last != status.end())\n      left_end = status_riterator(left_last);\n\n#ifdef MAXTRI_DEBUG_INTERSECT\n      cerr << \"      left: from \" << *left_begin << \" up to \";\n      if (left_end != status.rend())\n        cerr << *left_end;\n      else\n        cerr << \"REND\" << endl;\n#endif\n\n    intersect_range(*center, left_begin, left_end);\n  }\n\n  // Look for intersections with the right-adjacent edge(s).\n  if (right != status.end())\n  {\n    // The upper_bound is already in the right-adjacent range.\n    // Upper-bounding that range already puts us past the end like we want.\n    status_iterator right_begin = right;\n    status_iterator right_end = status.upper_bound(*right_begin);\n\n#ifdef MAXTRI_DEBUG_INTERSECT\n    cerr << \"      right: from \" << *right_begin << \" up to \";\n    if (right_end != status.end())\n      cerr << *right_end;\n    else\n      cerr << \"END\" << endl;\n#endif\n\n    intersect_range(*center, right_begin, right_end);\n  }\n}\n\ntemplate<class Tp_>\nvoid MaxTri<Tp_>::\ninsert_edge(edge_type const& e)\n{\n#ifdef MAXTRI_DEBUG_INTERSECT\n  cerr << \"  inserting \" << e << endl;\n#endif\n\n  // Insert the edge by its top point.\n  // It is always inserted as the upper bound of any equal_range.\n  status_iterator eit = status.insert(e);\n  assert(eit != status.end());\n\n  check_intersections(eit);\n}\n\ntemplate<class Tp_>\nvoid MaxTri<Tp_>::\nremove_edge(edge_type const& e)\n{\n#ifdef MAXTRI_DEBUG_INTERSECT\n  size_t status_size = status.size();\n  cerr << \"  removing \" << e << endl;\n#endif\n\n  // Remove the edge from the status.\n  status_seg_type edge_segment(e);\n  status_iterator eub, elb = find_unique(edge_segment);\n\n  // Nb. If this is not the bottom edge ([2]) in the triangle, we will\n  // immediately be adding another edge, but it is already done in\n  // handle_tripoint.\n\n#ifndef MAXTRI_DEBUG_INTERSECT\n  assert (elb != status.end());\n#else\n  // this should always be true: if it's not, handle_tripoint should catch it\n  if (elb == status.end())\n    MTFAIL(\"edge not found!\");\n#endif\n\n  eub = elb = status.erase(elb);\n  if (elb != status.begin())\n    --elb;\n\n#ifdef MAXTRI_DEBUG_INTERSECT\n  if (status.size() != status_size - 1)\n    MTFAIL(\"failed to remove edge!\");\n#endif\n\n  // Now elb, eub refer to the edges immediately left and right of the removed\n  // edge. Theoretically we only need to check for intersections between these\n  // two edges, but pass them both to the helper anyway.\n  // It's okay if we find the same intersection twice, because it should end up\n  // collapsing in the unordered_set used by IXEvent.\n  if (elb != status.end())\n    check_intersections(elb);\n\n  if (eub != status.end() && elb != eub)\n    check_intersections(eub);\n}\n\ntemplate<class Tp_>\nvoid MaxTri<Tp_>::\nhandle_intersection(point_type const& isect_point)\n{\n  // The first step is to reorder all the segments which form the intersection.\n  //\n  // Because we don't have access to the internal tree nodes of a C++ set,\n  // we have to do this by removing the segments, modifying the comparator,\n  // then re-inserting the segments so they'll be sorted correctly by the\n  // updated comparator.\n  //\n  // This sounds like bad news, but it's actually fine, since the algorithm is\n  // designed so that the change in comparison criteria happens only after each\n  // intersection point, and affects only the intersecting segments! Therefore\n  // we are not modifying the sort order of any nodes existing in the tree.\n\n#ifdef MAXTRI_DEBUG_INTERSECT\n  size_t status_size;\n#endif\n\n  // Lookup the actual intersection event from its point.\n  auto ixit = intersections.find(isect_point);\n  assert(ixit != intersections.end());\n  isect_event_type const& isect = ixit->second;\n\n#ifdef MAXTRI_DEBUG_INTERSECT\n  cerr << \"handling \" << isect;\n#endif\n\n  // Remove the segments forming the intersection (so we can add them later).\n  for (auto it = isect.begin(); it != isect.end(); ++it)\n  {\n#ifdef MAXTRI_DEBUG_INTERSECT\n    status_size = status.size();\n    cerr << \"    removing old segment \" << *it << endl;\n#endif\n\n    /* While we're at it, mark every triangle composing this point as\n     * intersecting if their lines actually do intersect.\n     *\n     * Many of the iterations of this loop will be duplicates, but an\n     * undirected adjacency matrix will squash those.\n     * In the common case, this line runs twice, once for each line.  */\n    for (auto it2 = isect.begin(); it2 != isect.end(); ++it2)\n      if (it2 != it && (status.key_comp()(*it, *it2)\n            || status.key_comp()(*it2, *it)))\n        add_edge(it->edge().tridata()->id, it2->edge().tridata()->id, *graph);\n\n    status_iterator segit = find_unique(*it);\n\n#ifdef MAXTRI_DEBUG_INTERSECT\n    if (segit == status.end())\n      MTFAIL(\"failed to find old segment \" << *it);\n#endif\n\n    status.erase(segit);\n\n#ifdef MAXTRI_DEBUG_INTERSECT\n    if (status.size() != status_size - 1)\n      MTFAIL(\"failed to remove old segment \" << *it);\n#endif\n  }\n\n  // Update the sweep line to the intersection point now that we've removed the\n  // intersecting segments. This changes the sorting criteria, since the\n  // comparator refers to us for the y-position of the sweep line.\n  // Now when we insert the segments again they should be in the correct order.\n  // Classically this equates to a single swap.\n  update_sweep(isect_point);\n\n  // Perform the reordering by inserting the intersecting segments again.\n  // This time they will follow the new world order.\n  // We need to remember each segment that is inserted, so we can check for\n  // intersections after they're all added again.\n  std::vector<status_iterator> new_segments;\n  for (auto it = isect.begin(); it != isect.end(); ++it)\n  {\n#ifdef MAXTRI_DEBUG_INTERSECT\n    status_size = status.size();\n    cerr << \"    re-inserting segment \" << *it << endl;\n#endif\n\n    status_iterator newit = status.insert(*it);\n    new_segments.push_back(newit);\n\n#ifdef MAXTRI_DEBUG_INTERSECT\n    if (status.size() != status_size + 1)\n      MTFAIL(\"failed to insert new segment!\");\n#endif\n  }\n\n  // Now that the sweep line has been updated to the intersection point and the\n  // intersecting segments have been reordered, we have to check each of these\n  // segments for their next point of intersection below the sweep line.\n  // Technically this will make too many comparisons, as each newly inserted\n  // segment will be compared to the segment it just intersected, but\n  // classically they should only look in the opposite direction.\n  // That's fine, as it's easier than keeping track of which segments ended up\n  // on which side of the intersection.\n  for (auto const& segiter : new_segments)\n    check_intersections(segiter);\n}\n\ntemplate<class Tp_>\nvoid MaxTri<Tp_>::\nhandle_tripoint(tri_point_type const& tpoint)\n{\n  // Update the sweep line to the point of this event.\n  // Though this implicitly modifies the status comparator, no segments can be\n  // reordered in the status as a result because of the invariants of the\n  // algorithm.\n  update_sweep(tpoint.value());\n\n  // We could queue all points twice (once for the top of each segment, once\n  // for the bottom of each segment) but handling each point of the triangle\n  // is clearer and simplifies event ordering. The diagram from the header\n  // is reproduced below for reference.\n  switch (tpoint.height)               /*                                 */\n  {                                    /*       [0]                TOP    */\n  case TOP:                            /* (0,1)  *                        */\n    insert_edge(tpoint.top_edge());    /* V E0  /  \\  E1 V                */\n    insert_edge(tpoint.bottom_edge()); /*      /     \\  (0,2)             */\n    break;                             /* [1] *- _    \\            MIDDLE */\n                                       /*         - _   \\                 */\n  case MIDDLE:                         /*             - _\\                */\n    remove_edge(tpoint.top_edge());    /*        E2 >     * [2]    BOTTOM */\n    insert_edge(tpoint.bottom_edge()); /*        (1,2) or (2,1)           */\n    break;\n\n  case BOTTOM:\n    remove_edge(tpoint.top_edge());\n    remove_edge(tpoint.bottom_edge());\n    break;\n\n  default:\n    MTFAIL(\"bad tpoint index!\");\n  }\n}\n\n#ifdef MAXTRI_DEBUG\n\ntemplate<class Tp_>\nvoid MaxTri<Tp_>::\ndump_tris_to_octave(ostream& os) const\n{\n  os << \"hold on;\" << endl;\n\n  int color_id = 1;\n  for (const triangle_type &t : tris)\n  {\n    cerr << \"    [\" << setw(2) << setfill(' ') << (color_id-1) << \"] \"\n      << t.point(0) << \" \" << t.point(1) << \" \" << t.point(2) << endl;\n\n    os << \"tri = [ \";\n    for (auto const& point : t.points())\n      os << getx(point) << \" , \" << gety(point) << \" ; \";\n    os << \" ];\" << endl\n       << \"fill(tri(:,1), tri(:,2), \" << color_id++ << \");\" << endl;\n  }\n}\n\ntemplate<class Tp_>\nvoid MaxTri<Tp_>::\ndump_solution_to_octave(ostream& os, std::set<int> const& indexes,\n    solution_cell_type const& solution) const\n{\n  os << \"hold on;\" << endl;\n\n  // Fill all composite triangles\n  int color_id = 1;\n  for (int idx : indexes)\n  {\n    os << \"tri = [ \";\n    const triangle_type &t = tris[idx];\n    for (auto const& point : t.points())\n      os << getx(point) << \" , \" << gety(point) << \" ; \";\n    os << \" ];\" << endl\n       << \"fill(tri(:,1), tri(:,2), \" << color_id++ << \");\" << endl;\n  }\n\n  // Then fill the solution\n  os << \"sol = [ \";\n  for (auto const& point : solution)\n    os << getx(point) << \" , \" << gety(point) << \" ; \";\n  os << \" ];\" << endl\n    << \"fill(sol(:,1), sol(:,2), 'k');\" << endl;\n}\n\n#endif\n\n#ifdef MAXTRI_DEBUG_INTERSECT\n\ntemplate<class Tp_>\nvoid MaxTri<Tp_>::\ndump_status_to_octave(ostream& os) const\n{\n  vector<coordinate_type> xs, ys;\n  coordinate_type minx = numeric_limits<coordinate_type>::max()\n                , maxx = numeric_limits<coordinate_type>::lowest();\n  xs.reserve(status.size());\n  ys.reserve(status.size());\n  for (auto const& segment : status)\n  {\n    coordinate_type x1 = getx(segment.first()), x2 = getx(segment.second());\n\n    if (x1 < minx)\n      minx = x1;\n    if (x1 > maxx)\n      maxx = x1;\n    if (x2 < minx)\n      minx = x2;\n    if (x2 > maxx)\n      maxx = x2;\n\n    xs.push_back(x1);\n    xs.push_back(x2);\n    ys.push_back(gety(segment.first()));\n    ys.push_back(gety(segment.second()));\n  }\n\n  os << \"figure();\" << endl\n    << \"hold on;\" << endl;\n  // draw the sweep line itself if we have anything\n  if (status.size() > 0)\n  {\n    os << \"plot([ \" << minx << \" ; \" << maxx << \" ], \"\n               \"[ \" << current_y() << \" ; \" << current_y() << \" ]\"\n               \", 'Color', 'red', 'LineWidth', 2);\" << endl\n       << \"xlim([ \" << minx << \" ; \" << maxx << \" ]);\" << endl;\n  }\n\n  // scatter plot for all endpoints\n  os << \"scatter([\";\n  for (auto const& x : xs)\n    os << x << \" ; \";\n  os << \"] , [\";\n  for (auto const& y : ys)\n    os << y << \" ; \";\n  os << \"]);\" << endl;\n\n  // also, plot each segment separately\n  for (auto const& segment : status)\n  {\n    os << \"plot([\"\n      << getx(segment.first()) << \" ; \"\n      << getx(segment.second())\n      << \"], [\"\n      << gety(segment.first()) << \" ; \"\n      << gety(segment.second())\n      << \"]);\" << endl;\n  }\n}\n\ntemplate<class Tp_>\nvoid MaxTri<Tp_>::\ndebug_status(void) const\n{\n  static int status_cnt = 0;\n\n  stringstream ofname_s;\n  ofname_s << \"./scripts/status_\" // %02d\n    << dec << setw(2) << setfill('0') << status_cnt << \".m\";\n  string ofname(ofname_s.str());\n\n  cerr << ofname << \":\" << endl;\n  int i = 0;\n  for (auto const& segment : status)\n  {\n    cerr << \"    [\" << setw(2) << dec << setfill(' ') << i << \"] \"\n      << segment << endl;\n    ++i;\n  }\n\n  ofstream ofstatus(ofname);\n  dump_status_to_octave(ofstatus);\n  ofstatus.close();\n\n  ++status_cnt;\n}\n\n#endif\n\ntemplate<class Tp_>\nvoid MaxTri<Tp_>::\nhandle_event(EventType type, event_point_type const& event)\n{\n  switch (type)\n  {\n  case INTERSECTION:\n    {\n      point_type const& isect_point(event.isect());\n\n      handle_intersection(isect_point);\n    }\n    break;\n\n  case TRIPOINT:\n    {\n      tri_point_type const& tri_point(event.point());\n\n#ifdef MAXTRI_DEBUG_INTERSECT\n      cerr << \"handling point \" << tri_point << endl;\n#endif\n\n      handle_tripoint(tri_point);\n    }\n    break;\n\n  default:\n    MTFAIL(\"unhandled event type!\");\n  }\n\n#ifdef MAXTRI_DEBUG_INTERSECT\n  debug_status();\n#endif\n}\n\ntemplate<class Tp_>\nvoid MaxTri<Tp_>::\ninitialize(void)\n{\n  if (graph)\n    delete graph;\n\n#ifdef MAXTRI_DEBUG\n  string tri_path(\"./scripts/triangles.m\");\n  cerr << \"dumping triangles to \" << tri_path << endl;\n  ofstream trif(tri_path);\n  dump_tris_to_octave(trif);\n  trif.close();\n#endif\n\n  // One slot per triangle.\n  graph = new components_graph(tris.size());\n}\n\nstruct clique_visitor\n{\n  clique_visitor(std::set<int> &clique_ref, size_t &depth_ref)\n    : max_clique(clique_ref), max_depth(depth_ref)\n  {}\n\n  template<typename Clique, typename Graph>\n  void clique(Clique const& c, Graph const& g)\n  {\n    std::set<int> current_clique;\n    size_t current_depth = 0u;\n\n    for (auto it = c.begin(); it != c.end(); ++it)\n    {\n      current_clique.insert(*it);\n      ++current_depth;\n    }\n\n    if (current_depth > max_depth)\n    {\n      max_depth = current_depth;\n      max_clique = current_clique;\n    }\n  }\n\n  std::set<int> &max_clique;\n  size_t &max_depth;\n};\n\n\ntemplate<class Tp_>\nvoid MaxTri<Tp_>::\nfinalize(void)\n{\n  // Re-orient triangles to make boost happy.\n  std::vector<solution_cell_type> new_triangles;\n  new_triangles.reserve(tris.size());\n  for (triangle_type const &t : tris)\n  {\n    new_triangles.emplace_back();\n    bg::assign(new_triangles.back(), t);\n    bg::correct(new_triangles.back());\n  }\n\n  // Get the index set of the max clique.\n  // This is the group of maximally intersecting triangles.\n  // We could modify our clique visitor to track all cells at the max depth...\n  // But for now we'll just choose the first one we encounter.\n#ifdef MAXTRI_DEBUG\n  string graph_path(\"./data/adjacency.gvz\");\n  cerr << \"dumping graph to \" << graph_path << endl;\n  ofstream graphf(graph_path);\n  boost::write_graphviz(graphf, *graph);\n  graphf.close();\n#endif\n\n  std::set<int> max_clique;\n  size_t max_size = 0u;\n  clique_visitor visitor(max_clique, max_size);\n  bron_kerbosch_all_cliques(*graph, visitor);\n\n  // Pull the solution triangles from the index set.\n  std::vector<solution_cell_type> max_clique_triangles;\n  max_clique_triangles.reserve(new_triangles.size());\n  for (int triangle_index : max_clique)\n    max_clique_triangles.push_back(new_triangles[triangle_index]);\n\n  // Intersect all the triangles together.\n  solution_cell_type s;\n  intersection(max_clique_triangles.begin(), max_clique_triangles.end(), s);\n\n#ifdef MAXTRI_DEBUG\n  cerr << \"solution from triangles: \" << endl;\n  for (int index : max_clique)\n  {\n    triangle_type const& tri = tris[index];\n    cerr << \"    [\" << setw(2) << setfill(' ') << index << \"] \"\n      << tri.point(0) << \"  \" << tri.point(1) << \"  \" << tri.point(2)\n      << endl;\n  }\n\n  cerr << \"with bounds: \";\n  for (auto const& point : s)\n    cerr << point << \" \";\n  cerr << endl;\n\n  ofstream ofsol(\"./scripts/solution.m\");\n  dump_solution_to_octave(ofsol, max_clique, s);\n  ofsol.close();\n#endif\n\n  solutions().push_back(s);\n}\n\ntemplate class MaxTri<double>;\ntemplate class MaxTri<float>;\n\n} } // end namespace cfla::tri\n", "meta": {"hexsha": "fa29a239bca680b731a0733ae386a30fc15cd52c", "size": 19568, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/maxtri.cc", "max_stars_repo_name": "fritzr/voronoi-game", "max_stars_repo_head_hexsha": "77fcc6a40076ab092795445f4e2a73f475338090", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/maxtri.cc", "max_issues_repo_name": "fritzr/voronoi-game", "max_issues_repo_head_hexsha": "77fcc6a40076ab092795445f4e2a73f475338090", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/maxtri.cc", "max_forks_repo_name": "fritzr/voronoi-game", "max_forks_repo_head_hexsha": "77fcc6a40076ab092795445f4e2a73f475338090", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-12T03:44:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-12T03:44:53.000Z", "avg_line_length": 29.1624441133, "max_line_length": 80, "alphanum_fraction": 0.6245911693, "num_tokens": 5112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.25898769569182756}}
{"text": "// Copyright (c) 2019, Tom Westerhout\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#pragma once\n\n#include \"detail/lattice.hpp\"\n#include \"detail/magnetic_cluster.hpp\"\n#include \"detail/simulated_annealing.hpp\"\n#include \"detail/utility.hpp\"\n#include <boost/align/aligned_allocator.hpp>\n#include <gsl/gsl-lite.hpp>\n#include <sleef.h>\n#include <sys/user.h>\n#include <vector>\n\n#if !defined(__AVX__)\n#    error \"Thermalisation relies on AVX\"\n#endif\n\nTCM_NAMESPACE_BEGIN\n\nusing size_t = std::size_t;\n\nnamespace detail {\n/// Wrapping to [0, 2pi).\nstruct to_0_2pi_fn {\n    static constexpr float one_over_two_pi = 0.15915494f;\n    static constexpr float two_pi          = 6.2831855f;\n\n    auto operator()(float const x) const noexcept -> float\n    {\n        return x - two_pi * std::floor(one_over_two_pi * x);\n    }\n\n    auto operator()(__m256 const x) const noexcept -> __m256\n    {\n        return x\n               - _mm256_set1_ps(two_pi)\n                     * Sleef_floorf8_avx(_mm256_set1_ps(one_over_two_pi) * x);\n    }\n};\n\n#if 0\n/// Performs the actual computation of energy\n///\n/// NOTE: Uses AVX intrinsics.\ninline auto energy_kernel(\n    gsl::span<float const> const                     spin,\n    gsl::span<std::pair<size_t, size_t> const> const edges) TCM_NOEXCEPT\n    -> float\n{ // {{{\n    auto const load_angles =\n        [s = spin.data()](auto const* const d, auto const n)\n            TCM_NOEXCEPT -> __m256 {\n        switch (n) {\n        case 0: return _mm256_set1_ps(0);\n        case 1:\n            return _mm256_set_ps(0, 0, 0, 0, 0, 0, 0, //\n                                 s[d[0].first] - s[d[0].second]);\n        case 2:\n            return _mm256_set_ps(0, 0, 0, 0, 0, 0,               //\n                                 s[d[1].first] - s[d[1].second], //\n                                 s[d[0].first] - s[d[0].second]);\n        case 3:\n            return _mm256_set_ps(0, 0, 0, 0, 0,                  //\n                                 s[d[2].first] - s[d[2].second], //\n                                 s[d[1].first] - s[d[1].second], //\n                                 s[d[0].first] - s[d[0].second]);\n        case 4:\n            return _mm256_set_ps(0, 0, 0, 0,                     //\n                                 s[d[3].first] - s[d[3].second], //\n                                 s[d[2].first] - s[d[2].second], //\n                                 s[d[1].first] - s[d[1].second], //\n                                 s[d[0].first] - s[d[0].second]);\n        case 5:\n            return _mm256_set_ps(0, 0, 0,                        //\n                                 s[d[4].first] - s[d[4].second], //\n                                 s[d[3].first] - s[d[3].second], //\n                                 s[d[2].first] - s[d[2].second], //\n                                 s[d[1].first] - s[d[1].second], //\n                                 s[d[0].first] - s[d[0].second]);\n        case 6:\n            return _mm256_set_ps(0, 0,                           //\n                                 s[d[5].first] - s[d[5].second], //\n                                 s[d[4].first] - s[d[4].second], //\n                                 s[d[3].first] - s[d[3].second], //\n                                 s[d[2].first] - s[d[2].second], //\n                                 s[d[1].first] - s[d[1].second], //\n                                 s[d[0].first] - s[d[0].second]);\n        case 7:\n            return _mm256_set_ps(0,                              //\n                                 s[d[6].first] - s[d[6].second], //\n                                 s[d[5].first] - s[d[5].second], //\n                                 s[d[4].first] - s[d[4].second], //\n                                 s[d[3].first] - s[d[3].second], //\n                                 s[d[2].first] - s[d[2].second], //\n                                 s[d[1].first] - s[d[1].second], //\n                                 s[d[0].first] - s[d[0].second]);\n\n        case 8:\n            return _mm256_set_ps(s[d[7].first] - s[d[7].second], //\n                                 s[d[6].first] - s[d[6].second], //\n                                 s[d[5].first] - s[d[5].second], //\n                                 s[d[4].first] - s[d[4].second], //\n                                 s[d[3].first] - s[d[3].second], //\n                                 s[d[2].first] - s[d[2].second], //\n                                 s[d[1].first] - s[d[1].second], //\n                                 s[d[0].first] - s[d[0].second]);\n        default: TCM_ASSERT(false, \"Bug! This should never have happened.\");\n        } // end switch\n    };\n\n    constexpr auto vector_size = 8;\n    auto const     chunks      = edges.size() / vector_size;\n    auto const     rest        = edges.size() % vector_size;\n\n    auto        energy = _mm256_set1_ps(0);\n    auto const* data   = edges.data();\n\n    for (auto i = std::size_t{0}; i < chunks; ++i, data += vector_size) {\n        energy += Sleef_cosf8_u35avx(load_angles(data, vector_size));\n    }\n    if (rest != 0) { energy += Sleef_cosf8_u35avx(load_angles(data, rest)); }\n\n    return energy[0] + energy[1] + energy[2] + energy[3] + energy[4] + energy[5]\n           + energy[6] + energy[7] - static_cast<float>(rest);\n} // }}}\n#endif\n\ninline auto\nenergy_kernel(gsl::span<float const> const                         spin,\n              gsl::span<std::pair<unsigned, unsigned> const> const edges,\n              gsl::span<float const> const coeffs) TCM_NOEXCEPT -> float\n{ // {{{\n    auto const load_chunk = [s = spin, d = edges](auto const n)\n                                TCM_NOEXCEPT -> __m256 {\n        TCM_ASSERT(8 * (n + 1) <= d.size(), \"Index out of bounds\");\n        auto const i = 8 * n;\n        auto const x = _mm256_set_ps(s[d[i + 7].first], s[d[i + 6].first],\n                                     s[d[i + 5].first], s[d[i + 4].first],\n                                     s[d[i + 3].first], s[d[i + 2].first],\n                                     s[d[i + 1].first], s[d[i + 0].first]);\n        auto const y = _mm256_set_ps(s[d[i + 7].second], s[d[i + 6].second],\n                                     s[d[i + 5].second], s[d[i + 4].second],\n                                     s[d[i + 3].second], s[d[i + 2].second],\n                                     s[d[i + 1].second], s[d[i + 0].second]);\n        return _mm256_sub_ps(x, y);\n    };\n\n    auto const load_part = [s = spin, d = edges](auto const n, auto const rest)\n                               TCM_NOEXCEPT -> __m256 {\n        TCM_ASSERT(0 < rest && rest < 8, \"Precondition violated\");\n        TCM_ASSERT(8 * n + rest <= d.size(), \"Index out of bounds\");\n        auto const i = 8 * n;\n        switch (rest) {\n        case 1:\n            return _mm256_set_ps(0, 0, 0, 0, 0, 0, 0, //\n                                 s[d[i + 0].first] - s[d[i + 0].second]);\n        case 2:\n            return _mm256_set_ps(0, 0, 0, 0, 0, 0,                       //\n                                 s[d[i + 1].first] - s[d[i + 1].second], //\n                                 s[d[i + 0].first] - s[d[i + 0].second]);\n        case 3:\n            return _mm256_set_ps(0, 0, 0, 0, 0,                          //\n                                 s[d[i + 2].first] - s[d[i + 2].second], //\n                                 s[d[i + 1].first] - s[d[i + 1].second], //\n                                 s[d[i + 0].first] - s[d[i + 0].second]);\n        case 4:\n            return _mm256_set_ps(0, 0, 0, 0,                             //\n                                 s[d[i + 3].first] - s[d[i + 3].second], //\n                                 s[d[i + 2].first] - s[d[i + 2].second], //\n                                 s[d[i + 1].first] - s[d[i + 1].second], //\n                                 s[d[i + 0].first] - s[d[i + 0].second]);\n        case 5:\n            return _mm256_set_ps(0, 0, 0,                                //\n                                 s[d[i + 4].first] - s[d[i + 4].second], //\n                                 s[d[i + 3].first] - s[d[i + 3].second], //\n                                 s[d[i + 2].first] - s[d[i + 2].second], //\n                                 s[d[i + 1].first] - s[d[i + 1].second], //\n                                 s[d[i + 0].first] - s[d[i + 0].second]);\n        case 6:\n            return _mm256_set_ps(0, 0,                                   //\n                                 s[d[i + 5].first] - s[d[i + 5].second], //\n                                 s[d[i + 4].first] - s[d[i + 4].second], //\n                                 s[d[i + 3].first] - s[d[i + 3].second], //\n                                 s[d[i + 2].first] - s[d[i + 2].second], //\n                                 s[d[i + 1].first] - s[d[i + 1].second], //\n                                 s[d[i + 0].first] - s[d[i + 0].second]);\n        case 7:\n            return _mm256_set_ps(0,                                      //\n                                 s[d[i + 6].first] - s[d[i + 6].second], //\n                                 s[d[i + 5].first] - s[d[i + 5].second], //\n                                 s[d[i + 4].first] - s[d[i + 4].second], //\n                                 s[d[i + 3].first] - s[d[i + 3].second], //\n                                 s[d[i + 2].first] - s[d[i + 2].second], //\n                                 s[d[i + 1].first] - s[d[i + 1].second], //\n                                 s[d[i + 0].first] - s[d[i + 0].second]);\n        default: TCM_ASSERT(false, \"Bug! This should never have happened.\");\n        } // end switch\n    };\n\n    constexpr auto vector_size = 8;\n    auto const     chunks      = edges.size() / vector_size;\n    auto const     rest        = edges.size() % vector_size;\n\n    auto energy = _mm256_set1_ps(0.0f);\n    for (auto i = size_t{0}; i < chunks; ++i) {\n        energy += _mm256_mul_ps(_mm256_load_ps(coeffs.data() + i * vector_size),\n                                Sleef_cosf8_u35avx(load_chunk(i)));\n    }\n    auto energy_rest = 0.0f;\n    if (rest != 0) {\n        auto const begin = chunks * vector_size;\n        auto const end   = begin + rest;\n        for (auto i = begin; i < end; ++i) {\n            energy_rest +=\n                coeffs[i]\n                * Sleef_cosf_u35(spin[edges[i].first] - spin[edges[i].second]);\n        }\n    }\n    return energy[0] + energy[1] + energy[2] + energy[3] + energy[4] + energy[5]\n           + energy[6] + energy[7] + energy_rest;\n} // }}}\n} // namespace detail\n\n#if 0\nstruct energy_buffers_t {\n\n    struct energy_fn_type {\n        gsl::span<std::pair<unsigned, unsigned> const> edges;\n        gsl::span<float const>                         coeffs;\n        unsigned                                       number_sites;\n\n        auto operator()(gsl::span<float const> const spin) TCM_NOEXCEPT -> float\n        {\n            TCM_ASSERT(spin.size() == number_sites, \"\");\n            return detail::energy_kernel(spin, edges, coeffs);\n        }\n    };\n\n  private:\n    template <class T>\n    using buffer_type =\n        std::vector<T, boost::alignment::aligned_allocator<T, PAGE_SIZE>>;\n\n    static constexpr auto empty = std::numeric_limits<unsigned>::max();\n\n    buffer_type<unsigned> _g_to_l; ///< Mapping of global to local indices.\n    buffer_type<std::pair<unsigned, unsigned>>\n                       _edges;  ///< Edges (given in terms of local indices)\n    buffer_type<float> _coeffs; ///< Couplings (+1 for antiferromagnetic\n                                ///< connections and -1 for ferromagnetic ones)\n\n  public:\n    explicit energy_buffers_t(size_t const size)\n        : _g_to_l(size)\n        , _edges(size)  // NOTE: This is just an initial estimate\n        , _coeffs(size) // And this as well\n    {}\n\n    energy_buffers_t(const energy_buffers_t&)     = delete;\n    energy_buffers_t(energy_buffers_t&&) noexcept = default;\n    energy_buffers_t& operator=(energy_buffers_t const&) = delete;\n    energy_buffers_t& operator=(energy_buffers_t&&) noexcept = default;\n\n    template <class System>\n    auto energy_fn(System const& system) -> energy_fn_type;\n\n  private:\n    template <class System>\n    auto set_initial_state(sa_buffers_t const& sa_buffers) -> energy_fn_type;\n\n    auto global_to_local(size_t const i) const TCM_NOEXCEPT -> size_t\n    {\n        TCM_ASSERT(i < _g_to_l.size(), \"Index out of bounds\");\n        TCM_ASSERT(_g_to_l[i] != empty, \"Site does not belong to the cluster\");\n        return _g_to_l[i];\n    }\n};\n#endif\n\n#if 0\n// {{{ energy_buffers_t::energy_fn IMPLEMENTATION\ntemplate <class Lattice>\nTCM_NOINLINE auto energy_buffers_t::energy_fn(gsl::span<size_t const> sites,\n                                              Lattice const&          lattice)\n    -> energy_fn_type\n{\n    using std::begin, std::end;\n    if (::TCM_NAMESPACE::size(lattice) != _g_to_l.size()) {\n        _g_to_l.resize(::TCM_NAMESPACE::size(lattice));\n    }\n\n    std::fill(begin(_g_to_l), end(_g_to_l), empty);\n    for (auto local_i = size_t{0}; local_i < sites.size(); ++local_i) {\n        auto const global_i = sites[local_i];\n        _g_to_l[global_i]   = local_i;\n    }\n\n    _fm_edges.clear();\n    _afm_edges.clear();\n    for (auto local_i = size_t{0}; local_i < sites.size(); ++local_i) {\n        auto const global_i = sites[local_i];\n        for (std::int64_t const _global_j :\n             ::TCM_NAMESPACE::neighbours(lattice, global_i)) {\n            // We want signed comparison here, because j may denote a\n            // boundary and thus be negative. This condition ensures that\n            // every edge is counted only once.\n            if (static_cast<std::int64_t>(global_i) < _global_j) {\n                // Here we know that _global_j > 0\n                TCM_ASSERT(_global_j > 0, \"\");\n                auto const global_j = static_cast<size_t>(_global_j);\n                auto const local_j  = _g_to_l[global_j];\n                if (local_j != empty) {\n                    switch (::TCM_NAMESPACE::interaction(lattice, global_i,\n                                                         global_j)) {\n                    case interaction_t::Ferromagnetic:\n                        _fm_edges.emplace_back(local_i, local_j);\n                        break;\n                    case interaction_t::Antiferromagnetic:\n                        _afm_edges.emplace_back(local_i, local_j);\n                        break;\n                    } // end switch\n                }\n            }\n        }\n    }\n\n    return {{_fm_edges}, {_afm_edges}};\n}\n#endif\n\n#if 0\ntemplate <class System>\nTCM_NOINLINE auto energy_buffers_t::energy_fn(System const& system)\n    -> energy_fn_type\n{\n    using std::begin, std::end;\n\n    auto const& lattice = system.lattice();\n    if (::TCM_NAMESPACE::size(system.lattice()) != _g_to_l.size()) {\n        _g_to_l.resize(::TCM_NAMESPACE::size(lattice));\n    }\n    std::fill(begin(_g_to_l), end(_g_to_l), empty);\n    _edges.clear();\n    _coeffs.clear();\n\n    auto number_sites = unsigned{0};\n    for (auto i = size_t{0}; i < ::TCM_NAMESPACE::size(lattice); ++i) {\n        if (!system.is_empty(i)) {\n            for (auto const _j : ::TCM_NAMESPACE::neighbours(lattice, i)) {\n                if (_j >= 0) {\n                    auto const j = static_cast<size_t>(_j);\n                    if (!system.is_empty(j)\n                        && system.get_magnetic_cluster(i)\n                               == system.get_magnetic_cluster(j)) {\n                        if (_g_to_l[i] == empty) {\n                            _g_to_l[i] = number_sites++;\n                        }\n                        if (j < i) {\n                            TCM_ASSERT(\n                                _g_to_l[j] != empty && _g_to_l[i] != empty, \"\");\n                            _coeffs.emplace_back(\n                                ::TCM_NAMESPACE::coupling(lattice, j, i));\n                            _edges.emplace_back(_g_to_l[j], _g_to_l[i]);\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    return {{_edges}, {_coeffs}, number_sites};\n}\n// }}}\n#endif\n\nstruct thermaliser_t {\n\n    struct energy_fn_type {\n        gsl::span<std::pair<unsigned, unsigned> const> edges;\n        gsl::span<float const>                         coeffs;\n        size_t                                         number_sites;\n\n        auto operator()(gsl::span<float const> const spin) TCM_NOEXCEPT -> float\n        {\n            TCM_ASSERT(spin.size() == number_sites, \"\");\n            return detail::energy_kernel(spin, edges, coeffs);\n        }\n    };\n\n  private:\n    template <class T>\n    using buffer_type =\n        std::vector<T, boost::alignment::aligned_allocator<T, PAGE_SIZE>>;\n\n    static constexpr auto empty = std::numeric_limits<unsigned>::max();\n\n    sa_buffers_t          _sa_buffers; ///< Simulated Annealing buffers.\n    buffer_type<unsigned> _l_to_g; ///< Mapping from local to global indices.\n    buffer_type<unsigned> _g_to_l; ///< Mapping from global to local indices.\n    buffer_type<std::pair<unsigned, unsigned>>\n                       _edges;  ///< Edges (given in terms of local indices)\n    buffer_type<float> _coeffs; ///< Couplings (+1 for antiferromagnetic\n                                ///< connections and -1 for ferromagnetic ones)\n\n  public:\n    explicit thermaliser_t(size_t const size)\n        : _sa_buffers{size}\n        , _l_to_g(size)\n        , _g_to_l(size)\n        , _edges(size)  // NOTE: This is just an initial estimate\n        , _coeffs(size) // And this as well\n    {}\n\n    thermaliser_t(const thermaliser_t&)     = delete;\n    thermaliser_t(thermaliser_t&&) noexcept = default;\n    thermaliser_t& operator=(thermaliser_t const&) = delete;\n    thermaliser_t& operator=(thermaliser_t&&) noexcept = default;\n\n    template <class System>\n    TCM_NOINLINE auto thermalise(magnetic_cluster_t<System>& cluster,\n                                 sa_pars_t const& parameters) -> void;\n\n    template <class System>\n    TCM_NOINLINE auto thermalise(System& system, sa_pars_t const& parameters)\n        -> void;\n\n  private:\n    template <class System>\n    TCM_NOINLINE auto reset(System const& system) -> void;\n\n    template <class System>\n    TCM_NOINLINE auto reset(magnetic_cluster_t<System> const& cluster) -> void;\n\n    template <class System>\n    TCM_NOINLINE auto store(gsl::span<float const>      best,\n                            magnetic_cluster_t<System>& cluster) -> void;\n\n    template <class System>\n    TCM_NOINLINE auto store(gsl::span<float const> best, System& system)\n        -> void;\n};\n\ntemplate <class System>\nauto thermaliser_t::thermalise(magnetic_cluster_t<System>& cluster,\n                               sa_pars_t const&            parameters) -> void\n{\n    reset(cluster);\n    auto&      system    = cluster.system();\n    auto       energy_fn = energy_fn_type{{_edges}, {_coeffs}, _l_to_g.size()};\n    auto       wrap_fn   = detail::to_0_2pi_fn{};\n    sa_chain_t chain{_sa_buffers, parameters, energy_fn, wrap_fn,\n                     system.rng_stream()};\n    for (auto i = 0u; i < parameters.n; ++i) {\n        chain();\n    }\n    store(chain.best(), system);\n}\n\ntemplate <class System>\nauto thermaliser_t::thermalise(System& system, sa_pars_t const& parameters)\n    -> void\n{\n    reset(system);\n    auto       energy_fn = energy_fn_type{{_edges}, {_coeffs}, _l_to_g.size()};\n    auto       wrap_fn   = detail::to_0_2pi_fn{};\n    sa_chain_t chain{_sa_buffers, parameters, energy_fn, wrap_fn,\n                     system.rng_stream()};\n    for (auto i = 0u; i < parameters.n; ++i) {\n        chain();\n    }\n    store(chain.best(), system);\n}\n\ntemplate <class System>\nauto thermaliser_t::reset(magnetic_cluster_t<System> const& cluster) -> void\n{\n    auto const& system  = cluster.system();\n    auto const& lattice = system.lattice();\n    if (::TCM_NAMESPACE::size(lattice) != _g_to_l.size()) {\n        _g_to_l.resize(::TCM_NAMESPACE::size(lattice));\n    }\n    std::fill(begin(_g_to_l), end(_g_to_l), empty);\n    _l_to_g.clear();\n    _edges.clear();\n    _coeffs.clear();\n\n    for (auto const i : cluster.sites()) {\n        if (!system.is_empty(i)) {\n            for (auto const _j : ::TCM_NAMESPACE::neighbours(lattice, i)) {\n                if (_j >= 0) {\n                    auto const j = static_cast<unsigned>(_j);\n                    if (!system.is_empty(j)\n                        && (&system.get_magnetic_cluster(j) == &cluster)) {\n                        if (_g_to_l[i] == empty) {\n                            _g_to_l[i] = static_cast<unsigned>(_l_to_g.size());\n                            _l_to_g.push_back(i);\n                        }\n                        if (j < i) {\n                            TCM_ASSERT(\n                                _g_to_l[j] != empty && _g_to_l[i] != empty, \"\");\n                            _coeffs.push_back(\n                                ::TCM_NAMESPACE::coupling(lattice, j, i));\n                            _edges.emplace_back(_g_to_l[j], _g_to_l[i]);\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    _sa_buffers.resize(_l_to_g.size());\n    auto initial = _sa_buffers.current();\n    for (auto const i : _l_to_g) {\n        initial[i] = system.get_angle(i);\n    }\n}\n\ntemplate <class System> auto thermaliser_t::reset(System const& system) -> void\n{\n    auto const& lattice = system.lattice();\n    if (::TCM_NAMESPACE::size(lattice) != _g_to_l.size()) {\n        _g_to_l.resize(::TCM_NAMESPACE::size(lattice));\n    }\n    std::fill(begin(_g_to_l), end(_g_to_l), empty);\n    _l_to_g.clear();\n    _edges.clear();\n    _coeffs.clear();\n\n    for (auto i = 0u; i < ::TCM_NAMESPACE::size(lattice); ++i) {\n        if (!system.is_empty(i)) {\n            for (auto const _j : ::TCM_NAMESPACE::neighbours(lattice, i)) {\n                if (_j >= 0) {\n                    auto const j = static_cast<unsigned>(_j);\n                    if (!system.is_empty(j)\n                        && system.get_magnetic_cluster(i)\n                               == system.get_magnetic_cluster(j)) {\n                        if (_g_to_l[i] == empty) {\n                            _g_to_l[i] = static_cast<unsigned>(_l_to_g.size());\n                            _l_to_g.push_back(i);\n                        }\n                        if (j < i) {\n                            TCM_ASSERT(\n                                _g_to_l[j] != empty && _g_to_l[i] != empty, \"\");\n                            _coeffs.push_back(\n                                ::TCM_NAMESPACE::coupling(lattice, j, i));\n                            _edges.emplace_back(_g_to_l[j], _g_to_l[i]);\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    _sa_buffers.resize(_l_to_g.size());\n    auto initial = _sa_buffers.current();\n    for (auto const i : _l_to_g) {\n        initial[i] = system.get_angle(i);\n    }\n}\n\ntemplate <class System>\nauto thermaliser_t::store(gsl::span<float const>      best,\n                          magnetic_cluster_t<System>& cluster) -> void\n{\n    auto const& system = cluster.system();\n    for (auto i = 0u; i < _l_to_g.size(); ++i) {\n        system.set_angle(_l_to_g[i], angle_t{best[i]});\n    }\n}\n\ntemplate <class System>\nauto thermaliser_t::store(gsl::span<float const> best, System& system) -> void\n{\n    for (auto i = 0u; i < _l_to_g.size(); ++i) {\n        system.set_angle(_l_to_g[i], angle_t{best[i]});\n    }\n}\n\n#if 0\ntemplate <class EnergyFn, class InitFn>\ninline auto optimise(EnergyFn&& energy, sa_pars_t const& parameters,\n                     sa_buffers_t& buffers, VSLStreamStatePtr stream,\n                     InitFn&& init_fn)\n{\n    std::forward<InitFn>(init_fn)(buffers.current());\n    sa_chain_t chain{buffers, parameters, std::forward<EnergyFn>(energy),\n                     detail::to_0_2pi_fn{}, stream};\n    for (auto i = 0u; i < parameters.n; ++i) {\n        chain();\n    }\n    return chain.best();\n}\n#endif\n\nTCM_NAMESPACE_END\n", "meta": {"hexsha": "c9b0a0131408f77c93687254c7f3d9532a360eb0", "size": 25310, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/detail/thermalisation.hpp", "max_stars_repo_name": "twesterhout/percolation", "max_stars_repo_head_hexsha": "f82358ce628c2b48cf7f8435673af17eab08c527", "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/detail/thermalisation.hpp", "max_issues_repo_name": "twesterhout/percolation", "max_issues_repo_head_hexsha": "f82358ce628c2b48cf7f8435673af17eab08c527", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/detail/thermalisation.hpp", "max_forks_repo_name": "twesterhout/percolation", "max_forks_repo_head_hexsha": "f82358ce628c2b48cf7f8435673af17eab08c527", "max_forks_repo_licenses": ["BSD-3-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.6260032103, "max_line_length": 81, "alphanum_fraction": 0.4966416436, "num_tokens": 6278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.25898769569182756}}
{"text": "#include \"camera.h\"\n\n#include <atomic>\n#include <glm/common.hpp>\n#include <memory>\n#include <boost/asio/executor.hpp>\n#include <boost/asio/post.hpp>\n#include <glm/glm.hpp>\n#include \"light.h\"\n#include \"scene.h\"\n#include \"ray.h\"\n#include \"object.h\"\n\nnamespace {\n\nglm::vec3 shadow(const Scene &scene, const Ray &r,\n\t\t\t\t const PointLight *source) noexcept {\n\tIntersection i;\n\tif (!scene.intersect(r, i))\n\t\treturn {1, 1, 1};\n\tif (i.object == source)\n\t\treturn {1, 1, 1};\n\tif (glm::length(i.object->transmissivity) < 1e-5)\n\t\treturn {0, 0, 0};\n\treturn i.object->transmissivity\n\t\t\t* shadow(scene, Ray{r.at(i.t) + 1e-5f*r.dir, r.dir}, source);\n}\n\nglm::vec3 shade(const Object &o, float shininess,\n                const Scene &scene,\n                glm::vec3 Q, glm::vec3 N, glm::vec3 V) noexcept {\n    glm::vec3 I = o.emissive;                            // emissive\n    I += scene.ambiant * o.color;                        // ambient\n    for (const PointLight *pl : scene.point_lights) {\n\t\tglm::vec3 diff = pl->pos() - Q;\n\t\tglm::vec3 L = glm::normalize(diff);\n\t\tfloat dis = glm::length(diff);\n\t\tif (glm::dot(N, L) >= 0) {\n\t\t\tfloat atten = 1.0f / (dis * dis);\n\t\t\tglm::vec3 I_l = atten * pl->emissive\n\t\t\t\t\t* shadow(scene, Ray(Q + 1e-5f*L, L), pl);\n\t\t\tglm::vec3 H = glm::normalize(V + L);\n\t\t\tI += glm::dot(N, L) * I_l * o.color;          // diffuse\n\t\t\tI += glm::pow(glm::max(0.0f, glm::dot(H, N)),\n\t\t\t\t\t\t  shininess) * I_l * o.specular;  // specular\n\t\t}\n\t}\n\tfor (const auto &dl : scene.dir_lights) {\n\t\tglm::vec3 L = -glm::normalize(dl->direction);\n\t\tif (glm::dot(N, L) >= 0) {\n\t\t\tglm::vec3 I_l = dl->color * shadow(scene, Ray(Q + 1e-5f*L, L), nullptr);\n\t\t\tglm::vec3 H = glm::normalize(V + L);\n\t\t\tI += glm::dot(N, L) * I_l * o.color;          // diffuse\n\t\t\tI += glm::pow(glm::max(0.0f, glm::dot(H, N)),\n\t\t\t\t\t\t  shininess) * I_l * o.specular;  // specular\n\t\t}\n\t}\n    return I;\n}\n\nglm::vec3 trace(const Scene &scene,\n\t\t\t\tconst Ray &r,\n\t\t\t\tint32_t depth) noexcept {\n\tif (depth == 0)\n\t\treturn {0, 0, 0};\n\tIntersection i;\n\tif (scene.intersect(r, i)) {\n\t\tconst Object &o = *i.object;\n\t\tconst float shininess = i.object->shininess;\n\t\tconst glm::vec3 Q = r.at(i.t);\n\t\tconst glm::vec3 D = r.dir;\n\t\tconst bool exit = glm::dot(D, i.normal) > 0.0;\n\t\tconst glm::vec3 N = exit ? -i.normal : i.normal;\n\n\t\t// direct\n\t\tconst glm::vec3 I_direct = shade(o, shininess, scene, Q, N, -D);\n\n\t\tconst float d_dot_n = glm::dot(D, N);\n\n\t\t// reflection\n\t\tglm::vec3 I_reflected = {0, 0, 0};\n\t\tif (glm::length(o.specular) > 1e-5) {\n\t\t\tglm::vec3 R = D - 2.0f * d_dot_n * N;\n\t\t\tI_reflected = o.specular * trace(scene, Ray(Q, R), depth - 1);\n\t\t}\n\n\t\t// refraction\n\t\tglm::vec3 I_refracted = {0, 0, 0};\n\t\tif (glm::length(o.transmissivity) > 1e-5) {\n\t\t\tfloat ni, nt;\n\t\t\tif (exit) {\n\t\t\t\t// exiting object\n\t\t\t\tni = o.ior;\n\t\t\t\tnt = 1.00029;\n\t\t\t} else {\n\t\t\t\t// entering object\n\t\t\t\tni = 1.00029;\n\t\t\t\tnt = o.ior;\n\t\t\t}\n\t\t\tconst auto sqr = [](float x) { return x * x; };\n\t\t\tfloat inside_sqrt = 1.0f -\n\t\t\t\t\tsqr(ni) / sqr(nt) * (1.0f - sqr(d_dot_n));\n\t\t\tif (inside_sqrt > 0.0f) {\n\t\t\t\t// not total internal reflection\n\t\t\t\tglm::vec3 T =\n\t\t\t\t\t\t(ni / nt) * (D - d_dot_n * N)\n\t\t\t\t\t\t- (glm::sqrt(inside_sqrt) * N);\n\t\t\t\tI_refracted = o.transmissivity\n\t\t\t\t\t\t* trace(scene, Ray(Q, T), depth - 1);\n\t\t\t}\n\t\t}\n\n\t\treturn glm::clamp(I_direct + I_reflected + I_refracted, 0.0f, 1.0f);\n\t} else if (scene.envmap != nullptr) {\n\t\treturn scene.envmap->get_color(r.dir);\n\t} else {\n\t\treturn {0, 0, 0};\n\t}\n}\n\ntemplate<typename It, typename F>\nvoid parallelForEach(boost::asio::executor exec, It begin, It end, F f) {\n\tif (begin + 1 == end) {\n\t\tf(begin);\n\t} else {\n\t\tIt mid = begin + (end - begin) / 2;\n\t\tboost::asio::post(\n\t\t\t\texec,\n\t\t\t\t[=]() { parallelForEach(exec, begin, mid, f); });\n\t\tparallelForEach(exec, mid, end, f);\n\t}\n}\n\n}  // namespace\n\nvoid Camera::trace_rays(\n\t\tconst Scene &root,\n\t\tstd::function<void(std::vector<glm::vec3>)> completion) const noexcept {\n\tauto results = std::make_shared<std::vector<glm::vec3>>(rays.size());\n\tauto finished = std::make_shared<std::atomic_int32_t>(0);\n\t\tauto task = [this, finished, results, &root, completion](int32_t i) {\n\t\t\t(*results)[i] = trace(\n\t\t\t\t\troot,\n\t\t\t\t\tRay{inner_to_world({0, 0, 0, 1}), inner_to_world({rays[i], 0})},\n\t\t\t\t\tdepth);\n\t\t\tif (finished->fetch_add(1, std::memory_order_relaxed) + 1\n\t\t\t\t\t== rays.size())\n\t\t\t\tcompletion(*results);\n\t\t};\n\tparallelForEach<int32_t>(exec_, 0, rays.size(), task);\n}\n", "meta": {"hexsha": "e644c94c05bddad0783a576759afa1a974eade55", "size": 4379, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/camera.cpp", "max_stars_repo_name": "zhihengq/tracer", "max_stars_repo_head_hexsha": "63853d96b755fd26e50398a9dccb5d372bda08a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/camera.cpp", "max_issues_repo_name": "zhihengq/tracer", "max_issues_repo_head_hexsha": "63853d96b755fd26e50398a9dccb5d372bda08a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/camera.cpp", "max_forks_repo_name": "zhihengq/tracer", "max_forks_repo_head_hexsha": "63853d96b755fd26e50398a9dccb5d372bda08a9", "max_forks_repo_licenses": ["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.8092105263, "max_line_length": 75, "alphanum_fraction": 0.582781457, "num_tokens": 1514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2589876956918275}}
{"text": "/*\n * Copyright (c) 2017, Doug Smith, KEBA Corp\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 * 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 * 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 OWNER 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\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 *  Created on: Aug 25, 2017\n *      Author: Doug Smith\n */\n\n#include \"rmi_driver/util.h\"\n\n#include <boost/algorithm/string.hpp>\n#include <boost/tokenizer.hpp>\n\n#include <boost/spirit/include/qi.hpp>\n\nnamespace rmi_driver\n{\nnamespace util\n{\ndouble radToDeg(double rad)\n{\n  return rad * (180.0 / M_PI);\n}\n\ndouble degToRad(double degrees)\n{\n  return degrees * (M_PI / 180.0);\n}\n\nstd::string floatToStringNoTrailing(float fval, int precision)\n{\n  // Convert the value to a string with fixed precision\n  std::ostringstream oss;\n  oss << std::setprecision(precision) << std::fixed;\n  oss << fval;\n  auto str = oss.str();\n  // Remove extra trailing 0s or .\n  boost::trim_right_if(str, boost::is_any_of(\"0\"));\n  boost::trim_right_if(str, boost::is_any_of(\".\"));\n\n  return str;\n}\n\nusing boost::spirit::qi::double_;\nusing boost::spirit::qi::parse;\n\nnamespace qi = boost::spirit::qi;\n\nstd::vector<double> stringToDoubleVec(const std::string& s)\n{\n  std::vector<double> doubleVec;\n\n  // So, boost::split is the least efficient thing ever.  Use qi instead.\n\n  // std::vector<std::string> strVec;\n\n  //\n  //  // Split the string at spaces into a vector of strings\n  //  // boost::split(strVec, s, boost::is_any_of(\" \"), boost::token_compress_on);\n  //  boost::split(strVec, s, boost::is_space(), boost::token_compress_on);\n  //  t.stop();\n  //\n  //  auto time_total = t.getTime();\n  //  std::cout << \"duration boost::split \" << t.getTime() << \" \";\n  //\n  //  t.reset();\n  //  t.start();\n  //  // Insert the double value of each entry\n  //\n  //  doubleVec.reserve(10);\n  //  std::transform(strVec.begin(), strVec.end(), std::back_inserter(doubleVec),\n  //                 [](const std::string& val) { return boost::lexical_cast<double>(val); });\n  //  t.stop();\n  //\n  //  time_total += t.getTime();\n  //  std::cout << \"duration transform: \" << t.getTime() << \" total: \" << time_total << \" (\" << s << \")\" << std::endl;\n  //\n  //  // Clock::time_point t0 = Clock::now();\n  //\n  //  {\n  //    std::vector<double> doubleVec;\n  //    t.reset();\n  //    t.start();\n  //    auto s_trim = boost::trim_copy(s);\n  //    doubleVec.reserve(10);\n  //    std::stringstream ss(s_trim);\n  //\n  //    double d;\n  //    while (ss >> d)\n  //      doubleVec.push_back(d);\n  //\n  //    t.stop();\n  //    std::cout << \"duration ss: \" << t.getTime() << std::endl;\n  //  }\n\n  std::string::const_iterator start = s.begin();\n  std::string::const_iterator end = s.end();\n\n  std::string s_trim;\n\n  // If it starts or ends with whitespace, trim it\n  if (*start == ' ' || *end == ' ')\n  {\n    s_trim = boost::trim_copy(s);\n    start = s_trim.begin();\n    end = s_trim.end();\n  }\n\n  bool r;\n\n  r = qi::parse(start, end, (double_ % ' '), doubleVec);\n\n  return doubleVec;\n}\n\nbool usedAndNotEqualIdx(int entry_index, const std::vector<float>& sample, const std::vector<float>& msg)\n{\n  // If there is a message then there must be a valid index\n  // @todo This seems safer, but then it's not \"ignoring\" the entry.\n  //  if (msg.size() > 0)\n  //  {\n  //    if (entry_index < 0 || entry_index >= sample.size())\n  //      return true;\n  //  }\n\n  // Check if the sample has anything\n  if (sample.size() == 0)\n    return false;\n\n  // Make sure the index is valid\n  if (entry_index < 0 || entry_index >= sample.size())\n    return true;\n\n  // Get the value stored in sample[entry_index] and compare it with the size of msg\n  auto expected_size = std::lround(sample[entry_index]);\n\n  return msg.size() != expected_size;\n}\n\nbool usedAndNotEqual(const std::string& sample, const std::string& msg, int* entry_index)\n{\n  if (entry_index)\n    *entry_index = 0;\n\n  if (sample.length() <= 0)\n    return false;\n\n  boost::char_separator<char> sep(\"|\", \"\", boost::keep_empty_tokens);\n  boost::tokenizer<boost::char_separator<char>, std::string::const_iterator, std::string> tok(sample, sep);\n\n  // Eclipse complains about auto&& with a tokenizer?\n  for (const std::string& entry : tok)\n  {\n    // Found an entry that matches.\n    if (entry.compare(msg) == 0)\n      return false;\n\n    if (entry_index)\n      (*entry_index)++;\n  }\n\n  // A sample was given but no match was found.\n  if (entry_index)\n    *entry_index = -1;  // Redundant since commandhandler matching will stop after the 1st fail?\n\n  return true;\n}\n\n}  // namespace util\n\n}  // namespace rmi_driver\n", "meta": {"hexsha": "412630b1c8ee6fbe0ff91fcfc140ba914d835945", "size": 5675, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rmi_driver/src/util.cpp", "max_stars_repo_name": "smith-doug/rmi_driver", "max_stars_repo_head_hexsha": "50b0bb09fc15d033f8dcb3656d668106980c8107", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-08-28T05:52:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T04:28:03.000Z", "max_issues_repo_path": "rmi_driver/src/util.cpp", "max_issues_repo_name": "Psyche-mia/rmi_driver", "max_issues_repo_head_hexsha": "56d8305e26a712054dabeb97b0f30055ac12aff5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2017-11-21T18:20:40.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-03T19:25:09.000Z", "max_forks_repo_path": "rmi_driver/src/util.cpp", "max_forks_repo_name": "Psyche-mia/rmi_driver", "max_forks_repo_head_hexsha": "56d8305e26a712054dabeb97b0f30055ac12aff5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-11-20T06:31:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-05T01:13:33.000Z", "avg_line_length": 29.4041450777, "max_line_length": 118, "alphanum_fraction": 0.6544493392, "num_tokens": 1488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4804786780479071, "lm_q1q2_score": 0.25896994536602186}}
{"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_CWISE_BINARY_HPP\n#define AMA_TENSOR_DETAIL_TENSOR_CWISE_BINARY_HPP 1\n\n#include <ama/tensor/detail/is_same_tensor.hpp>\n#include <ama/tensor/detail/tensor_base.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/mpl/bool.hpp>\n#include <boost/mpl/if.hpp>\n\nnamespace ama\n{\n  namespace tensor_\n  {\n\n    /* this class represent a unary component-wise operation */\n    template <typename LEFT, typename RIGHT, typename OPERATOR> class tensor_cwise_binary;\n\n\n    /* specialization of tensor_traits */\n    template <typename LEFT, typename RIGHT, typename OPERATOR>\n    struct tensor_traits< tensor_cwise_binary<LEFT, RIGHT, OPERATOR> >\n    {\n      typedef typename OPERATOR::result_type value_type;\n\n      typedef typename LEFT::dimension_type dimension_type;\n\n      typedef typename LEFT::controvariant_type controvariant_type;\n      typedef typename LEFT::covariant_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, typename OPERATOR>\n    class tensor_cwise_binary:\n        public tensor_base< tensor_cwise_binary<LEFT, RIGHT, OPERATOR> >\n    {\n      BOOST_MPL_ASSERT_MSG(\n            (tensor_::is_same_tensor<LEFT, RIGHT>::value)\n          , COMPONENT_WISE_BINARY_OPERATION_BETWEEN_DIFFERENT_TENSORS_ARE_NOT_ALLOWED\n          , (LEFT, RIGHT));\n\n    protected:\n      typedef tensor_base< tensor_cwise_binary<LEFT, RIGHT, OPERATOR> > base_type;\n      typedef tensor_cwise_binary<LEFT, RIGHT, OPERATOR> derived_type;\n\n    protected:\n      typedef LEFT left_operand_type;\n      typedef RIGHT right_operand_type;\n      typedef OPERATOR operator_type;\n\n    public:\n      typedef typename base_type::value_type value_type;\n\n    public:\n      /* constructor */\n      tensor_cwise_binary(left_operand_type const & left_operand,\n                          right_operand_type const & right_operand,\n                          operator_type const & op = operator_type())\n          : m_left_operand(left_operand),\n            m_right_operand(right_operand),\n            m_operator(op) { }\n\n    public:\n      /* retrieve the value */\n      template <typename ILIST>\n      value_type at() const\n      {\n        return m_operator(\n                 m_left_operand.template at<ILIST>(),\n                 m_right_operand.template at<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_operand;\n      const_right_operand_type m_right_operand;\n      operator_type const m_operator;\n    };\n\n  }\n}\n\n#endif /* AMA_TENSOR_DETAIL_TENSOR_CWISE_BINARY_HPP */\n", "meta": {"hexsha": "f16e92965d2679efa91c2474948dc64ba56106ad", "size": 4978, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ama/tensor/detail/tensor_cwise_binary.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_cwise_binary.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_cwise_binary.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": 38.0, "max_line_length": 90, "alphanum_fraction": 0.7099236641, "num_tokens": 1029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2589699453660218}}
{"text": "/**  \\file ublas_elementwise.hpp \\brief Elementwise operations for ublas vector/matrix */\n/*\n-------------------------------------------------------------------------\n   This file is part of BayesOpt, an efficient C++ library for \n   Bayesian optimization.\n\n   Copyright (C) 2011-2015 Ruben Martinez-Cantin <rmcantin@unizar.es>\n \n   BayesOpt is free software: you can redistribute it and/or modify it \n   under the terms of the GNU Affero General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   BayesOpt is distributed in the hope that it will be useful, but \n   WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU Affero General Public License for more details.\n\n   You should have received a copy of the GNU Affero General Public License\n   along with BayesOpt.  If not, see <http://www.gnu.org/licenses/>.\n------------------------------------------------------------------------\n*/\n\n#ifndef  _ELEMENTWISE_UBLAS_HPP_\n#define  _ELEMENTWISE_UBLAS_HPP_\n\n#include <algorithm>\n#include <boost/numeric/ublas/vector.hpp>\n\nnamespace bayesopt\n{\n  namespace utils\n  {\n\n    /** \n     * Computes the elementwise product of two vectors or matrices.\n     *             c_i = a_i * b_i\n     */\n    template <class v1, class v2>\n    v1 ublas_elementwise_prod(const v1& a, const v2& b)\n    {\n      typedef typename v1::value_type D;\n      v1 c(a.size());\n      std::transform(a.begin(),a.end(),b.begin(),c.begin(),std::multiplies<D>());\n      return c;\n    }\n\n    /** \n     * Computes the elementwise division of two vectors or matrices.\n     *            c_i = a_i / b_i\n     */\n    template <class v1, class v2>\n    v1 ublas_elementwise_div(const v1& a, const v2& b)\n    {\n      typedef typename v1::value_type D;\n      v1 c(a.size());\n      std::transform(a.begin(),a.end(),b.begin(),c.begin(),std::divides<D>());\n      return c;\n    }\n\n  } //namespace utils\n} //namespace bayesopt\n\n#endif\n", "meta": {"hexsha": "d7ee8d9697f32d6123e6eb6f5f0f2ce7e9eee380", "size": 2052, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/bayesopt/utils/ublas_elementwise.hpp", "max_stars_repo_name": "pchrapka/brain-modelling", "max_stars_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-13T19:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-13T19:37:52.000Z", "max_issues_repo_path": "external/bayesopt/utils/ublas_elementwise.hpp", "max_issues_repo_name": "pchrapka/brain-modelling", "max_issues_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/bayesopt/utils/ublas_elementwise.hpp", "max_forks_repo_name": "pchrapka/brain-modelling", "max_forks_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-25T12:22:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-25T12:22:05.000Z", "avg_line_length": 31.5692307692, "max_line_length": 89, "alphanum_fraction": 0.6242690058, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.2589699453660218}}
{"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/**\n * @file standard_model.hpp\n *\n * @brief contains class for Standard model running and self-energies\n *\n */\n\n#ifndef STANDARD_MODEL_H\n#define STANDARD_MODEL_H\n\n#include \"betafunction.hpp\"\n#include \"standard_model_physical.hpp\"\n#include \"two_loop_corrections.hpp\"\n#include \"problems.hpp\"\n#include \"config.h\"\n#include \"lowe.h\"\n#include \"physical_input.hpp\"\n\n#include <iosfwd>\n#include <string>\n\n#ifdef ENABLE_THREADS\n#include <mutex>\n#endif\n\n#include <gsl/gsl_vector.h>\n#include <Eigen/Core>\n\nnamespace flexiblesusy {\n\nclass EWSB_solver;\n\nnamespace standard_model_info {\n\nenum Particles : unsigned {VG, Hp, Fv, Ah, hh, VP, VZ, Fd, Fu, Fe, VWp,\n   NUMBER_OF_PARTICLES};\n\nenum Parameters : unsigned {g1, g2, g3, Lambdax, Yu0_0, Yu0_1, Yu0_2, Yu1_0,\n   Yu1_1, Yu1_2, Yu2_0, Yu2_1, Yu2_2, Yd0_0, Yd0_1, Yd0_2, Yd1_0, Yd1_1, Yd1_2\n   , Yd2_0, Yd2_1, Yd2_2, Ye0_0, Ye0_1, Ye0_2, Ye1_0, Ye1_1, Ye1_2, Ye2_0,\n   Ye2_1, Ye2_2, mu2, v, NUMBER_OF_PARAMETERS};\n\nextern const char* particle_names[NUMBER_OF_PARTICLES];\n\nextern const char* parameter_names[NUMBER_OF_PARAMETERS];\n\n} // namespace standard_model_info\n\nnamespace standard_model {\n\n/**\n * @class Standard_model\n * @brief model class with routines for SM running and self-energies\n */\nclass Standard_model : public Beta_function {\npublic:\n\n   Standard_model();\n   Standard_model(double scale_, double loops_, double thresholds_\n   , double g1_, double g2_, double g3_, double Lambdax_, const Eigen::Matrix<\n   double,3,3>& Yu_, const Eigen::Matrix<double,3,3>& Yd_, const Eigen::Matrix<\n   double,3,3>& Ye_, double mu2_, double v_);\n\n   virtual ~Standard_model();\n\n   /// number of EWSB equations\n   static const std::size_t number_of_ewsb_equations = 1;\n\n   void calculate_DRbar_masses();\n   void calculate_DRbar_parameters();\n   void calculate_pole_masses();\n   void check_pole_masses_for_tachyons();\n   void do_force_output(bool);\n   bool do_force_output() const;\n   void set_ewsb_iteration_precision(double);\n   void set_ewsb_loop_order(unsigned);\n   void set_two_loop_corrections(const Two_loop_corrections&);\n   const Two_loop_corrections& get_two_loop_corrections() const;\n   void set_number_of_ewsb_iterations(std::size_t);\n   void set_number_of_mass_iterations(std::size_t);\n   std::size_t get_number_of_ewsb_iterations() const;\n   std::size_t get_number_of_mass_iterations() const;\n   void set_pole_mass_loop_order(unsigned);\n   unsigned get_pole_mass_loop_order() const;\n   void set_physical(const Standard_model_physical&);\n   double get_ewsb_iteration_precision() const;\n   double get_ewsb_loop_order() const;\n   const Standard_model_physical& get_physical() const;\n   Standard_model_physical& get_physical();\n   const Problems<standard_model_info::NUMBER_OF_PARTICLES>& get_problems() const;\n   Problems<standard_model_info::NUMBER_OF_PARTICLES>& get_problems();\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   virtual Eigen::ArrayXd beta() const;\n   virtual Eigen::ArrayXd get() const;\n   void print(std::ostream&) const;\n   virtual void set(const Eigen::ArrayXd&);\n\n   Standard_model calc_beta() const;\n   void clear();\n   void clear_running_parameters();\n   void clear_DRbar_parameters();\n   void clear_problems();\n\n   void calculate_spectrum();\n   std::string name() const;\n   void run_to(double scale, double eps = -1.0);\n   void set_precision(double);\n   double get_precision() const;\n\n   void set_low_energy_data(const softsusy::QedQcd& qedqcd_) { qedqcd = qedqcd_; }\n   const softsusy::QedQcd& get_low_energy_data() const { return qedqcd; }\n   softsusy::QedQcd& get_low_energy_data() { return qedqcd; }\n   void set_physical_input(const Physical_input& input_) { input = input_; }\n   const Physical_input& get_physical_input() const { return input; }\n   Physical_input& get_physical_input() { return input; }\n\n   void initialise_from_input();\n\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_Lambdax(double Lambdax_) { Lambdax = Lambdax_; }\n   void set_Yu(const Eigen::Matrix<double,3,3>& Yu_) { Yu = Yu_; }\n   void set_Yu(int i, int k, double value) { Yu(i,k) = value; }\n   void set_Yd(const Eigen::Matrix<double,3,3>& Yd_) { Yd = Yd_; }\n   void set_Yd(int i, int k, 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, double value) { Ye(i,k) = value; }\n   void set_mu2(double mu2_) { mu2 = mu2_; }\n   void set_v(double v_) { v = v_; }\n\n   double get_g1() const { return g1; }\n   double get_g2() const { return g2; }\n   double get_g3() const { return g3; }\n   double get_Lambdax() const { return Lambdax; }\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   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   double get_mu2() const { return mu2; }\n   double get_v() const { return v; }\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   double get_MVP() const { return MVP; }\n   double get_MVZ() const { return MVZ; }\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   const Eigen::Array<double,2,1>& get_MVPVZ() const { return MVPVZ; }\n   double get_MVPVZ(int i) const { return MVPVZ(i); }\n\n   const Eigen::Matrix<std::complex<double>,3,3>& get_Vd() const { return Vd; }\n   const 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   const 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   const 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   const 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   const 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   const 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   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   double get_mass_matrix_VP() const;\n   void calculate_MVP();\n   double get_mass_matrix_VZ() const;\n   void calculate_MVZ();\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 CpconjHpHphh() const;\n   double CpconjHpVWpVP() const;\n   double CpconjHpVZVWp() const;\n   double CpHpgWpCbargZ() const;\n   double CpconjHpbargWpCgZ() const;\n   double CpHpgZbargWp() const;\n   double CpconjHpbargZgWp() const;\n   double CpHpconjHpAhAh() const;\n   double CpHpconjHphhhh() const;\n   double CpHpconjHpconjHpHp() const;\n   std::complex<double> CpconjHpVWpAh() const;\n   double CpconjHpVWphh() const;\n   double CpconjHpVPHp() const;\n   double CpconjHpVZHp() const;\n   double CpHpconjHpconjVWpVWp() const;\n   std::complex<double> CpHpconjHpVZVZ() const;\n   std::complex<double> CpconjHpbarFdFuPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpconjHpbarFdFuPL(unsigned gI1, unsigned gI2) const;\n   double CpconjHpbarFeFvPR(unsigned , unsigned ) const;\n   std::complex<double> CpconjHpbarFeFvPL(unsigned gI1, unsigned gI2) const;\n   double CpAhhhAh() const;\n   std::complex<double> CpAhbargWpgWp() const;\n   std::complex<double> CpAhbargWpCgWpC() const;\n   double CpAhAhAhAh() const;\n   double CpAhAhhhhh() const;\n   double CpAhAhconjHpHp() const;\n   std::complex<double> CpAhVZhh() const;\n   std::complex<double> CpAhconjVWpHp() const;\n   double CpAhAhconjVWpVWp() const;\n   std::complex<double> CpAhAhVZVZ() const;\n   std::complex<double> CpAhbarFdFdPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpAhbarFdFdPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpAhbarFeFePR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpAhbarFeFePL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpAhbarFuFuPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpAhbarFuFuPL(unsigned gI1, unsigned gI2) const;\n   double CphhAhAh() const;\n   double Cphhhhhh() const;\n   double CphhVZVZ() const;\n   double CphhbargWpgWp() const;\n   double CphhbargWpCgWpC() const;\n   double CphhbargZgZ() const;\n   double CphhconjHpHp() const;\n   double CphhconjVWpVWp() const;\n   double CphhhhAhAh() const;\n   double Cphhhhhhhh() const;\n   double CphhhhconjHpHp() const;\n   std::complex<double> CphhVZAh() const;\n   double CphhconjVWpHp() const;\n   double CphhhhconjVWpVWp() const;\n   std::complex<double> CphhhhVZVZ() const;\n   std::complex<double> CphhbarFdFdPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CphhbarFdFdPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CphhbarFeFePR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CphhbarFeFePL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CphhbarFuFuPR(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CphhbarFuFuPL(unsigned gI1, unsigned gI2) const;\n   std::complex<double> CpVZhhAh() const;\n   double CpVZVZhh() const;\n   double CpVZbargWpgWp() const;\n   double CpVZbargWpCgWpC() const;\n   double CpVZconjHpHp() const;\n   double CpVZconjVWpHp() const;\n   std::complex<double> CpVZVZAhAh() const;\n   std::complex<double> CpVZVZhhhh() const;\n   std::complex<double> CpVZVZconjHpHp() const;\n   double CpVZconjVWpVWp() const;\n   double CpVZbarFdFdPL(unsigned gI1, unsigned gI2) const;\n   double CpVZbarFdFdPR(unsigned gI1, unsigned gI2) const;\n   double CpVZbarFeFePL(unsigned gI1, unsigned gI2) const;\n   double CpVZbarFeFePR(unsigned gI1, unsigned gI2) const;\n   double CpVZbarFuFuPL(unsigned gI1, unsigned gI2) const;\n   double CpVZbarFuFuPR(unsigned gI1, unsigned gI2) const;\n   double CpVZbarFvFvPL(unsigned gI1, unsigned gI2) const;\n   double CpVZbarFvFvPR(unsigned , unsigned ) const;\n   double CpVZVZconjVWpVWp1() const;\n   double CpVZVZconjVWpVWp2() const;\n   double CpVZVZconjVWpVWp3() const;\n   std::complex<double> CpconjVWpHpAh() const;\n   double CpconjVWpHphh() const;\n   double CpconjVWpVPHp() const;\n   double CpconjVWpVWphh() const;\n   double CpconjVWpVZHp() const;\n   double CpconjVWpbargPgWp() const;\n   double CpconjVWpbargWpCgP() const;\n   double CpconjVWpbargWpCgZ() const;\n   double CpconjVWpbargZgWp() const;\n   double CpVWpconjVWpAhAh() const;\n   double CpVWpconjVWphhhh() const;\n   double CpVWpconjVWpconjHpHp() const;\n   double CpconjVWpVWpVP() const;\n   double CpconjVWpVZVWp() const;\n   std::complex<double> CpconjVWpbarFdFuPL(unsigned gI1, unsigned gI2) const;\n   double CpconjVWpbarFdFuPR(unsigned , unsigned ) const;\n   std::complex<double> CpconjVWpbarFeFvPL(unsigned gI1, unsigned gI2) const;\n   double CpconjVWpbarFeFvPR(unsigned , unsigned ) const;\n   double CpVWpconjVWpVPVP1() const;\n   double CpVWpconjVWpVPVP2() const;\n   double CpVWpconjVWpVPVP3() const;\n   double CpVWpconjVWpVZVZ1() const;\n   double CpVWpconjVWpVZVZ2() const;\n   double CpVWpconjVWpVZVZ3() const;\n   double CpVWpconjVWpconjVWpVWp1() const;\n   double CpVWpconjVWpconjVWpVWp2() const;\n   double CpVWpconjVWpconjVWpVWp3() const;\n   std::complex<double> CpbarUFdFdAhPL(unsigned gO2, unsigned gI1) const;\n   std::complex<double> CpbarUFdFdAhPR(unsigned gO1, unsigned gI1) const;\n   std::complex<double> CpbarUFdhhFdPL(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFdhhFdPR(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFdVGFdPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFdVGFdPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFdVPFdPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFdVPFdPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFdVZFdPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFdVZFdPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFdconjHpFuPL(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFdconjHpFuPR(unsigned gO1, unsigned gI2) const;\n   double CpbarUFdconjVWpFuPR(unsigned , unsigned ) const;\n   std::complex<double> CpbarUFdconjVWpFuPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFuFuAhPL(unsigned gO2, unsigned gI1) const;\n   std::complex<double> CpbarUFuFuAhPR(unsigned gO1, unsigned gI1) const;\n   std::complex<double> CpbarUFuhhFuPL(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFuhhFuPR(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFuHpFdPL(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFuHpFdPR(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFuVGFuPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFuVGFuPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFuVPFuPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFuVPFuPL(unsigned gO1, unsigned gI2) const;\n   double CpbarUFuVWpFdPR(unsigned , unsigned ) const;\n   std::complex<double> CpbarUFuVWpFdPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFuVZFuPR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFuVZFuPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFeFeAhPL(unsigned gO2, unsigned gI1) const;\n   std::complex<double> CpbarUFeFeAhPR(unsigned gO1, unsigned gI1) const;\n   std::complex<double> CpbarUFehhFePL(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFehhFePR(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFeVPFePR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFeVPFePL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFeVZFePR(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarUFeVZFePL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarUFeconjHpFvPL(unsigned gO2, unsigned gI2) const;\n   double CpbarUFeconjHpFvPR(unsigned , unsigned ) const;\n   double CpbarUFeconjVWpFvPR(unsigned , unsigned ) const;\n   double CpbarUFeconjVWpFvPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarFdFdAhPL(unsigned gO2, unsigned gI1) const;\n   std::complex<double> CpbarFdFdAhPR(unsigned gO1, unsigned gI1) const;\n   std::complex<double> CpbarFdhhFdPL(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarFdhhFdPR(unsigned gO1, unsigned gI2) const;\n   double CpbarFdVZFdPR(unsigned gO2, unsigned gI2) const;\n   double CpbarFdVZFdPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarFdconjHpFuPL(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarFdconjHpFuPR(unsigned gO1, unsigned gI2) const;\n   double CpbarFdconjVWpFuPR(unsigned , unsigned ) const;\n   std::complex<double> CpbarFdconjVWpFuPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarFeFeAhPL(unsigned gO2, unsigned gI1) const;\n   std::complex<double> CpbarFeFeAhPR(unsigned gO1, unsigned gI1) const;\n   std::complex<double> CpbarFehhFePL(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarFehhFePR(unsigned gO1, unsigned gI2) const;\n   double CpbarFeVZFePR(unsigned gO2, unsigned gI2) const;\n   double CpbarFeVZFePL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarFeconjHpFvPL(unsigned gO2, unsigned gI2) const;\n   double CpbarFeconjHpFvPR(unsigned , unsigned ) const;\n   double CpbarFeconjVWpFvPR(unsigned , unsigned ) const;\n   std::complex<double> CpbarFeconjVWpFvPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarFuFuAhPL(unsigned gO2, unsigned gI1) const;\n   std::complex<double> CpbarFuFuAhPR(unsigned gO1, unsigned gI1) const;\n   std::complex<double> CpbarFuhhFuPL(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarFuhhFuPR(unsigned gO1, unsigned gI2) const;\n   std::complex<double> CpbarFuHpFdPL(unsigned gO2, unsigned gI2) const;\n   std::complex<double> CpbarFuHpFdPR(unsigned gO1, unsigned gI2) const;\n   double CpbarFuVPFuPR(unsigned gO2, unsigned gI2) const;\n   double CpbarFuVPFuPL(unsigned gO1, unsigned gI2) const;\n   double CpbarFuVWpFdPR(unsigned , unsigned ) const;\n   std::complex<double> CpbarFuVWpFdPL(unsigned gO1, unsigned gI2) const;\n   double CpbarFuVZFuPR(unsigned gO2, unsigned gI2) const;\n   double CpbarFuVZFuPL(unsigned gO1, unsigned gI2) const;\n   std::complex<double> self_energy_Hp(double p ) const;\n   std::complex<double> self_energy_Ah(double p ) const;\n   std::complex<double> self_energy_hh(double p ) const;\n   std::complex<double> self_energy_VZ(double p ) const;\n   std::complex<double> self_energy_VWp(double p ) const;\n   std::complex<double> self_energy_Fd_1(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fd_PR(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fd_PL(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_1(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_PR(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_PL(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fe_1(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fe_PR(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fe_PL(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_VZ_heavy(double p ) const;\n   std::complex<double> self_energy_VWp_heavy(double p ) const;\n   std::complex<double> self_energy_Fd_1_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fd_PR_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fd_PL_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fe_1_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fe_PR_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fe_PL_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_1_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_PR_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_PL_heavy_rotated(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_1_heavy(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_PR_heavy(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> self_energy_Fu_PL_heavy(double p , unsigned gO1, unsigned gO2) const;\n   std::complex<double> tadpole_hh() const;\n\n   /// calculates the tadpoles at current loop order\n   void tadpole_equations(double[number_of_ewsb_equations]) const;\n\n   void self_energy_hh_2loop(double result[1]) 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   double calculate_Mhh_DRbar(double);\n\n   double ThetaW() const;\n\nprivate:\n\n   static const int numberOfParameters = 33;\n\n   struct Beta_traces {\n      double traceYdAdjYd;\n      double traceYeAdjYe;\n      double traceYuAdjYu;\n      double traceYdAdjYdYdAdjYd;\n      double traceYeAdjYeYeAdjYe;\n      double traceYuAdjYuYuAdjYu;\n      double traceYdAdjYuYuAdjYd;\n      double traceYdAdjYdYdAdjYdYdAdjYd;\n      double traceYdAdjYdYdAdjYuYuAdjYd;\n      double traceYdAdjYuYuAdjYdYdAdjYd;\n      double traceYdAdjYuYuAdjYuYuAdjYd;\n      double traceYeAdjYeYeAdjYeYeAdjYe;\n      double traceYuAdjYuYuAdjYuYuAdjYu;\n   };\n   void calc_beta_traces(Beta_traces&) const;\n\n   double calc_beta_g1_one_loop(const Beta_traces&) const;\n   double calc_beta_g1_two_loop(const Beta_traces&) const;\n   double calc_beta_g1_three_loop(const Beta_traces&) const;\n   double calc_beta_g2_one_loop(const Beta_traces&) const;\n   double calc_beta_g2_two_loop(const Beta_traces&) const;\n   double calc_beta_g2_three_loop(const Beta_traces&) const;\n   double calc_beta_g3_one_loop(const Beta_traces&) const;\n   double calc_beta_g3_two_loop(const Beta_traces&) const;\n   double calc_beta_g3_three_loop(const Beta_traces&) const;\n   double calc_beta_Lambdax_one_loop(const Beta_traces&) const;\n   double calc_beta_Lambdax_two_loop(const Beta_traces&) const;\n   double calc_beta_Lambdax_three_loop(const Beta_traces&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Yu_one_loop(const Beta_traces&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Yu_two_loop(const Beta_traces&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Yu_three_loop(const Beta_traces&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Yd_one_loop(const Beta_traces&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Yd_two_loop(const Beta_traces&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Yd_three_loop(const Beta_traces&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Ye_one_loop(const Beta_traces&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Ye_two_loop(const Beta_traces&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Ye_three_loop(const Beta_traces&) const;\n   double calc_beta_mu2_one_loop(const Beta_traces&) const;\n   double calc_beta_mu2_two_loop(const Beta_traces&) const;\n   double calc_beta_mu2_three_loop(const Beta_traces&) const;\n   double calc_beta_v_one_loop(const Beta_traces&) const;\n   double calc_beta_v_two_loop(const Beta_traces&) const;\n   double calc_beta_v_three_loop(const Beta_traces&) const;\n\n   struct EWSB_args {\n      Standard_model* model;\n      unsigned ewsb_loop_order;\n   };\n\n#ifdef ENABLE_THREADS\n   struct Thread {\n      typedef void(Standard_model::*Memfun_t)();\n      Standard_model* model;\n      Memfun_t fun;\n\n      Thread(Standard_model* model_, Memfun_t fun_)\n         : model(model_), fun(fun_) {}\n      void operator()() {\n         try {\n            (model->*fun)();\n         } catch (...) {\n            model->thread_exception = std::current_exception();\n         }\n      }\n   };\n#endif\n\n   std::size_t number_of_ewsb_iterations;\n   std::size_t number_of_mass_iterations;\n   unsigned ewsb_loop_order;\n   unsigned pole_mass_loop_order;\n   bool force_output;             ///< switch to force output of pole masses\n   double precision;              ///< RG running precision\n   double ewsb_iteration_precision;\n   Standard_model_physical physical; ///< contains the pole masses and mixings\n   Problems<standard_model_info::NUMBER_OF_PARTICLES> problems;\n   Two_loop_corrections two_loop_corrections; ///< used 2-loop corrections\n   softsusy::QedQcd qedqcd;\n   Physical_input input;\n#ifdef ENABLE_THREADS\n   std::exception_ptr thread_exception;\n   static std::mutex mtx_fortran; /// locks fortran functions\n#endif\n\n   int solve_ewsb_iteratively();\n   int solve_ewsb_iteratively(unsigned);\n   int solve_ewsb_iteratively_with(EWSB_solver*, const double[number_of_ewsb_equations]);\n   void ewsb_initial_guess(double[number_of_ewsb_equations]);\n   int ewsb_step(double[number_of_ewsb_equations]) const;\n   static int ewsb_step(const gsl_vector*, void*, gsl_vector*);\n   static int tadpole_equations(const gsl_vector*, void*, gsl_vector*);\n   void copy_DRbar_masses_to_pole_masses();\n\n   void initial_guess_for_parameters();\n   void calculate_Yu_DRbar();\n   void calculate_Yd_DRbar();\n   void calculate_Ye_DRbar();\n   void calculate_Lambdax_DRbar();\n   double calculate_delta_alpha_em(double alphaEm) const;\n   double calculate_delta_alpha_s(double alphaS) const;\n   double calculate_theta_w(double alpha_em_drbar);\n   void recalculate_mw_pole();\n   bool check_convergence(const Standard_model& old) const;\n\n   // Passarino-Veltman loop functions\n   double A0(double) const;\n   double B0(double, double, double) const;\n   double B1(double, double, double) const;\n   double B00(double, double, double) const;\n   double B22(double, double, double) const;\n   double H0(double, double, double) const;\n   double F0(double, double, double) const;\n   double G0(double, double, double) const;\n\n   // Running parameters\n   double g1;\n   double g2;\n   double g3;\n   double Lambdax;\n   Eigen::Matrix<double,3,3> Yu;\n   Eigen::Matrix<double,3,3> Yd;\n   Eigen::Matrix<double,3,3> Ye;\n   double mu2;\n   double v;\n\n   // DR-bar masses\n   double MVG;\n   double MHp;\n   Eigen::Array<double,3,1> MFv;\n   double MAh;\n   double Mhh;\n   double MVP;\n   double MVZ;\n   Eigen::Array<double,3,1> MFd;\n   Eigen::Array<double,3,1> MFu;\n   Eigen::Array<double,3,1> MFe;\n   double MVWp;\n   Eigen::Array<double,2,1> MVPVZ;\n\n   // DR-bar mixing matrices\n   Eigen::Matrix<std::complex<double>,3,3> Vd;\n   Eigen::Matrix<std::complex<double>,3,3> Ud;\n   Eigen::Matrix<std::complex<double>,3,3> Vu;\n   Eigen::Matrix<std::complex<double>,3,3> Uu;\n   Eigen::Matrix<std::complex<double>,3,3> Ve;\n   Eigen::Matrix<std::complex<double>,3,3> Ue;\n   Eigen::Matrix<double,2,2> ZZ;\n\n\n};\n\nstd::ostream& operator<<(std::ostream&, const Standard_model&);\n\n} // namespace standard_model\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "84b59bfbf24a61288ef7a42a92528e9054fe4d8c", "size": 27908, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/src/standard_model.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/src/standard_model.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/src/standard_model.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": 44.7243589744, "max_line_length": 101, "alphanum_fraction": 0.73527304, "num_tokens": 8568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.25890718627037573}}
{"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\n  std::vector<std::string> choices = {\"forward\", \"central\"};\n  _force_method =\n      options.ifExistsAndinListReturnElseThrowRuntimeError<std::string>(\n          \".method\", choices);\n\n  _displacement = options.ifExistsReturnElseReturnDefault<double>(\n      \".displacement\", 0.001);  // Angstrom\n  _displacement *= tools::conv::ang2bohr;\n\n  _remove_total_force = options.ifExistsReturnElseReturnDefault<bool>(\n      \".CoMforce_removal\", _remove_total_force);\n  return;\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.QMAtoms()[atom_index].setPos(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.QMAtoms()[atom_index].setPos(\n        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.QMAtoms()[atom_index].setPos(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.QMAtoms()[atom_index].setPos(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.QMAtoms()[atom_index].setPos(\n        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": "646635260f740b8f799c4ad9f48617df5299a5df", "size": 5687, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/forces.cc", "max_stars_repo_name": "fossabot/xtp", "max_stars_repo_head_hexsha": "e82cc53f23e213d09da15da80ada6e32ac031a07", "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/forces.cc", "max_issues_repo_name": "fossabot/xtp", "max_issues_repo_head_hexsha": "e82cc53f23e213d09da15da80ada6e32ac031a07", "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/forces.cc", "max_forks_repo_name": "fossabot/xtp", "max_forks_repo_head_hexsha": "e82cc53f23e213d09da15da80ada6e32ac031a07", "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.1049382716, "max_line_length": 79, "alphanum_fraction": 0.6720590821, "num_tokens": 1542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.25884093047352}}
{"text": "\r\n#ifndef SGM_RP_HANSER96_HH_\r\n#define SGM_RP_HANSER96_HH_\r\n\r\n\r\n#include <boost/graph/adjacency_list.hpp>\r\n\r\n#include \"sgm/RingPerception.hh\"\r\n\r\n#include <limits>\r\n#include <set>\r\n\r\n\r\nnamespace sgm {\r\n\r\n\t /*! @brief Ring enumeration ala Hanser et al.\r\n\t  *\r\n\t  * Implementation of the exhaustive ring perception algorithm by\r\n\t  * Hanser et al. (1996)\r\n\t  *\r\n\t  *   A New Algorithm for Exhaustive Ring Perception in a Molecular Graph\r\n\t  *   T. Hanser, P. Jauffret, and G. Kaufmann\r\n\t  *   J. Chem. Inf. Comput. Sci., 1996, 36, 1146-1152\r\n\t  *\r\n\t  * @author Martin Mann - 2010 - http://www.bioinf.uni-freiburg.de/~mmann/\r\n\t  *\r\n\t  */\r\n\tclass RP_Hanser96 : public RingPerception {\r\n\tpublic:\r\n\r\n\t\ttypedef std::set< std::pair<size_t,size_t> > BondSet;\r\n\r\n\t\t  //! construction\r\n\t\tRP_Hanser96();\r\n\r\n\t\t  //! destruction\r\n\t\tvirtual ~RP_Hanser96();\r\n\r\n\r\n\t\t  /*!\r\n\t\t   * Finds ALL rings within the given graph and reports each found\r\n\t\t   * ring to the assigned reporter. The enumeration can be restricted\r\n\t\t   * to rings up to a given ring size, ie. number of nodes per ring.\r\n\t\t   *\r\n\t\t   * @param graph the graph to be analyzed\r\n\t\t   * @param reporter the RingReporter to report all found rings to\r\n\t\t   * @param maxRingSize the maximal size of rings to report\r\n\t\t   * @return the number of all rings within the gaph\r\n\t\t   */\r\n\t\tsize_t\r\n\t\tfindRings( const Graph_Interface & graph,\r\n\t\t\t\t\tRingReporter & reporter,\r\n\t\t\t\t\tconst size_t maxRingSize = std::numeric_limits<size_t>::max());\r\n\r\n\t\t  /*!\r\n\t\t   * Identifies all bonds participating in rings and stores the\r\n\t\t   * according vertex index pairs in the provided container.\r\n\t\t   *\r\n\t\t   * @param graph the graph to search for ring bonds\r\n\t\t   * @param ringBonds OUT : the container to fill with the ring bonds.\r\n\t\t   *   NOTE: the container is cleared at the beginning of the call.\r\n\t\t   * @param maxRingSize the maximal size of rings to consider\r\n\t\t   *\r\n\t\t   * @return the number of ring bonds within the graph\r\n\t\t   */\r\n\t\tsize_t\r\n\t\tfindRingBonds( const Graph_Interface & graph\r\n\t\t\t\t\t, BondSet & ringBonds\r\n\t\t\t\t\t, const size_t maxRingSize = std::numeric_limits<size_t>::max() );\r\n\r\n\r\n\tprotected:\r\n\r\n\t\t  //! information on the current ring part\r\n\t\tstruct RingInfo {\r\n\t\tpublic:\r\n\t\t\tRingReporter::RingNodes nodes;\r\n\t\t\tRingReporter::RingList path;\r\n\t\t};\r\n\r\n\r\n\t\t  //! The properties available for the nodes of the P-graph\r\n\t\ttypedef\tboost::property<\tboost::vertex_index_t, size_t >\r\n\t\t\t\t\t\tGraph_NodeProperties;\r\n\r\n\t\t  //! The properties available for the edges of the P-graph\r\n\t\ttypedef\tboost::property<\tboost::edge_name_t, RingInfo >\r\n\t\t\t\t\t\tGraph_EdgeProperties;\r\n\r\n\t\t  //! the P-graph type that is used to detect all rings\r\n\t\ttypedef boost::adjacency_list<\r\n\t\t\t\t\t\t\tboost::multisetS,      \t\t\t// store edges\r\n\t\t\t\t\t\t\tboost::vecS,       \t\t\t\t// store vertices\r\n\t\t\t\t\t\t\tboost::undirectedS,\t\t\t\t// is an undirected graph\r\n\t\t\t\t\t\t\tGraph_NodeProperties,  \t\t\t// index information\r\n\t\t\t\t\t\t\tGraph_EdgeProperties   \t\t\t// ring information\r\n\t\t\t\t\t\t>\r\n\t\t\t\t\t\t\tP_Graph;\r\n\r\n\tprotected:\r\n\r\n\t\t  //! the P-graph to be compressed during the ring perception\r\n\t\tP_Graph pGraph;\r\n\r\n\t\t  //! the index access for pGraph\r\n\t\tboost::property_map<P_Graph, boost::vertex_index_t>::type pGraphIndex;\r\n\t\t  //! the edge label access for pGraph, i.e. the according RingList\r\n\t\tboost::property_map<P_Graph, boost::edge_name_t>::type pGraphPath;\r\n\r\n\t\t  //! the degree of each node in pGraph\r\n\t\tstd::vector<size_t> pGraphDegree;\r\n\t\t  //! the nodes to be removed during the ring perception from pGraph\r\n\t\tstd::vector<size_t> toRemove;\r\n\r\n\tprotected:\r\n\r\n\t\t  /*!\r\n\t\t   * Initializes the pGraph member with the given graph. If direct loops\r\n\t\t   * are found, these are directly reported and counted.\r\n\t\t   *\r\n\t\t   * @param graph the graph to be encoded in the pGraph member\r\n\t\t   * @param reporter the RingReporter to report all rings to\r\n\t\t   * @return the number of rings found\r\n\t\t   */\r\n\t\tsize_t\r\n\t\tinitializeP_Graph( const Graph_Interface & graph\r\n\t\t\t\t\t\t\t, RingReporter& reporter);\r\n\r\n\t\t  /*!\r\n\t\t   * Virtually removes the vertex nextToRemove from the pGraph and\r\n\t\t   * reports all found rings to the given reporter.\r\n\t\t   * The removal is only virtual, since the node remains within the\r\n\t\t   * pGraph but all adjacent edges are removed, i.e. it is not\r\n\t\t   * accessible anymore in later iterations. This is to ease the\r\n\t\t   * maintenance of the temporary data structures.\r\n\t\t   *\r\n\t\t   * @param nextToRemove the index of the vertex to be removed\r\n\t\t   * @param graph the graph searched (needed for ring report)\r\n\t\t   * @param reporter the RingReporter to report all rings to\r\n\t\t   * @param maxRingSize the maximal ring size to consider\r\n\t\t   * @return the number of rings found\r\n\t\t   */\r\n\t\tsize_t\r\n\t\tremove_vertex( const size_t nextToRemove\r\n\t\t\t\t\t\t, const Graph_Interface& graph\r\n\t\t\t\t\t\t, RingReporter& reporter\r\n\t\t\t\t\t\t, const size_t maxRingSize);\r\n\r\n\t\tstruct degree_sort {\r\n\t\t\tconst std::vector<size_t> & degree;\r\n\t\t\tdegree_sort( const std::vector<size_t> & degree_ )\r\n\t\t\t : degree(degree_)\r\n\t\t\t{}\r\n\t\t\tbool operator()(const size_t& i1, const size_t& i2 ) const {\r\n\t\t\t\treturn degree[i1] > degree[i2];\r\n\t\t\t}\r\n\t\t};\r\n\r\n\r\n\t\t/**\r\n\t\t * Stores the bond information for loops.\r\n\t\t */\r\n\t\tclass LoopBondReporter : public RingReporter {\r\n\r\n\t\tprotected:\r\n\r\n\t\t\tBondSet & bondSet;\r\n\r\n\t\tpublic:\r\n\t\t\t  //! construction\r\n\t\t\tLoopBondReporter( BondSet & bondSet );\r\n\t\t\t  //! destruction\r\n\t\t\tvirtual ~LoopBondReporter();\r\n\r\n\t\t\t  /*!\r\n\t\t\t   * Is called to report a ring.\r\n\t\t\t   * @param graph the graph that contains the ring\r\n\t\t\t   * @param ringList the ring to report\r\n\t\t\t   */\r\n\t\t\tvirtual\r\n\t\t\tvoid\r\n\t\t\treportRing( const Graph_Interface& graph, const RingList & ringList );\r\n\r\n\t\t};\r\n\r\n\t};\r\n\r\n} // namespace sgm\r\n\r\n#endif /* SGM_RP_HANSER96_HH_ */\r\n", "meta": {"hexsha": "fe2a271ae1aff981598a6682e3d08df7f260f173", "size": 5733, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/sgm/RP_Hanser96.hh", "max_stars_repo_name": "michaelapeterka/GGL", "max_stars_repo_head_hexsha": "99e585b773ad8f33e39160d2cbd71c00e036fa37", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2017-05-09T15:37:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T10:51:02.000Z", "max_issues_repo_path": "src/sgm/RP_Hanser96.hh", "max_issues_repo_name": "michaelapeterka/GGL", "max_issues_repo_head_hexsha": "99e585b773ad8f33e39160d2cbd71c00e036fa37", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-05-24T08:00:25.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-24T08:01:01.000Z", "max_forks_repo_path": "src/sgm/RP_Hanser96.hh", "max_forks_repo_name": "michaelapeterka/GGL", "max_forks_repo_head_hexsha": "99e585b773ad8f33e39160d2cbd71c00e036fa37", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-05-29T10:55:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-04T14:24:51.000Z", "avg_line_length": 30.0157068063, "max_line_length": 76, "alphanum_fraction": 0.6525379383, "num_tokens": 1420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.25871759406963407}}
{"text": "/**\n *  sim_onlineca_replan.cpp\n *\n *  Simulate the LTL motion planning with collision avoidance\n *  with moving obstacles.\n *  Additional replanning if the robot is blocked.\n *\n *  Created by Yinan Li on Feb. 19, 2021.\n *  Hybrid Systems Group, University of Waterloo.\n */\n\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <algorithm>\n#include <utility>\n#include <cmath>\n#include <sys/stat.h>\n#include <boost/numeric/odeint.hpp>\n#include <cstdlib>\n#include <ctime>\n\n#include \"src/grid.h\"\n#include \"src/definitions.h\"\n#include \"src/abstraction.hpp\"\n#include \"src/DBAparser.h\"\n#include \"src/bsolver.hpp\"\n#include \"src/patcher.h\"\n#include \"src/hdf5io.h\"\n\n#include \"car.hpp\"\n#include \"odes.hpp\"\n\n\nint main(int argc, char *argv[])\n{\n    std::string specfile, ctlrfile, cafile, graphfile;\n    specfile = \"dba1.txt\";\n    ctlrfile = \"controller_dba1_0.2-0.2-0.2.h5\";\n    graphfile = \"gwin.h5\";\n    const double eta[] = {0.2, 0.2, 0.2};\n\n    cafile = \"controller_safety_abst-0.8-0.9-0.1-0.1.h5\";\n    const double eta_r[] = {0.1, 0.1, 0.1};\n\n    /* Input arguments:\n     * ./simRe (dbafile ctlrfile cafile graphfile eta[0] eta_r[0])\n     */\n    if(argc!=1) {\n\tif(argc==7) {\n\t    specfile = std::string(argv[1]);\n\t    ctlrfile = std::string(argv[2]);\n\t    cafile = std::string(argv[3]);\n\t    graphfile = std::string(argv[4]);\n\t    eta[0] = std::atof(argv[5]);\n\t    eta[1] = std::atof(argv[5]);\n\t    eta[2] = std::atof(argv[5]);\n\t    eta_r[0] = std::atof(argv[6]);\n\t    eta_r[1] = std::atof(argv[6]);\n\t    eta_r[2] = std::atof(argv[6]);\n\t} else {\n\t    std::cout << \"Improper number of arguments.\\n\";\n\t    std::exit(1);\n\t}\n    }\n    std::cout << \"Simulate \" << specfile << \" with controller \" << ctlrfile << '\\n';\n\n\n    /**\n     * Setup the motion planning workspace\n     **/\n    const int x_dim = 3;\n    const double theta = 3.5;\n    const double xlb[] = {0, 0, -theta};\n    const double xub[] = {10, 10, theta};\n    /* set the control values */\n    const int u_dim = 2;\n    const double ulb[] = {-1.0, -1.0};\n    double uub[] = {1.0, 1.0};\n    /* discretization precision */\n    double mu[] = {0.3, 0.3};\n    /* generate grid */\n    rocs::grid x_grid(x_dim,eta,xlb,xub);\n    x_grid.gridding();\n    rocs::grid u_grid(u_dim,mu,ulb,uub);\n    std::cout << \"Number of discrete states: \" << x_grid._nv << \"\\n\";\n    std::cout << \"Number of discrete inputs: \" << u_grid._nv << \"\\n\";\n\n    clock_t tb, te;\n\n\n    /**\n     * Load specification\n     **/\n    std::cout << \"\\nReading the specification...\\n\";\n    rocs::UintSmall nAP = 0, nNodes = 0, q0 = 0;\n    std::vector<rocs::UintSmall> acc;\n    std::vector<std::vector<rocs::UintSmall>> arrayM;\n    if (!rocs::read_spec(specfile, nNodes, nAP, q0, arrayM, acc))\n\tstd::exit(1);\n    boost::dynamic_bitset<> isacc(nNodes, false);\n    for (rocs::UintSmall i = 0; i < acc.size(); ++i)\n\tisacc[acc[i]] = true;\n\n\n    /**\n     * Load global controller\n     **/\n    std::cout << \"\\nLoading global controller...\\n\";\n    std::vector<long long> w_x0, encode3;\n    std::vector<NODE_POST> nts_ctrlr;\n    std::vector<CTRL> ctrl;\n    std::vector<int> q_prime;\n    rocs::h5FileHandler planRdr(ctlrfile, H5F_ACC_RDONLY);\n    planRdr.read_discrete_controller(w_x0, encode3, nts_ctrlr, ctrl, q_prime);\n\n\n    /**\n     * Load local safety controller\n     **/\n    std::cout << \"\\nLoading local safety controller...\\n\";\n    rocs::h5FileHandler reader(cafile, H5F_ACC_RDONLY);\n    std::vector<size_t> optCtlr;\n    std::vector<double> value;\n    boost::dynamic_bitset<> safeCtlr;\n    boost::dynamic_bitset<> win;\n    size_t cdims[2];\n    reader.read_discrete_controller(win, safeCtlr, cdims, optCtlr, value);\n    double xrlb[] = {-3, -3, -theta};\n    double xrub[] = {3, 3, theta};\n    rocs::grid rel_grid(3, eta_r, xrlb, xrub);\n    rel_grid.gridding();\n\n\n\n    /**\n     * Launch patcher\n     **/\n    rocs::Patcher local;\n    struct stat buffer;\n    if(stat(graphfile.c_str(), &buffer) == 0) {\n    \t/* Read from a file */\n    \tstd::cout << \"\\nReading winning graph...\\n\";\n    \trocs::h5FileHandler graphRdr(graphfile, H5F_ACC_RDONLY);\n    \ttb = clock();\n    \tgraphRdr.read_winning_graph(local);\n    \tte = clock();\n    \tstd::cout << \"Time of reading graph: \" << (float)(te - tb)/CLOCKS_PER_SEC << '\\n';\n    } else {\n    \tstd::cout << \"Graph file doesn't exist.\\n\";\n    \treturn 1;\n    }\n    int horizon = 3;  //set forward propagation horizon\n\n\n\n    /**\n     * Target and avoid region selection for replanning\n     */\n    rocs::UintSmall q = 0;\n    const double ro = 0.8;\n    const double rt = 0.35;\n    double per = 0.8;\n    std::vector<long long> avoid, target;\n    std::vector< std::pair<size_t, int> > replan;\n    boost::dynamic_bitset<> plhdr(cdims[1], true);\n    auto local_region = [&x_grid, q, nNodes](const rocs::Rn &xo, const double ro,\n\t\t\t\t\t     const std::vector<long long> &encode) {\n\t\t\t    /* collect the grid points intersect with the box */\n\t\t\t    rocs::ivec box{rocs::interval(xo[0]-ro, xo[0]+ro),\n\t\t\t\t\t   rocs::interval(xo[1]-ro, xo[1]+ro),\n\t\t\t\t\t   x_grid._bds[2]};\n\t\t\t    // std::cout << \"The box enclose the region: \" << box << '\\n';\n\t\t\t    std::vector<size_t> ids = x_grid.subset(box, 0, 0);\n\t\t\t    std::vector<long long> ix(ids.begin(), ids.end());\n\n\t\t\t    /* determine the grid cell intersect with the r-ball around xo */\n\t\t\t    double xl, xr, yr, yl, xsqr, ysqr;\n\t\t\t    double rx = x_grid._gw[0]/2.0;\n\t\t\t    double ry = x_grid._gw[1]/2.0;\n\t\t\t    std::vector<double> x(x_grid._dim);\n\t\t\t    for(auto &id:ix) {\n\t\t\t\tx_grid.id_to_val(x, id);\n\t\t\t\t// std::cout << x[0] << ' ' << x[1] << ' ' << x[2] <<'\\n';\n\t\t\t\txl = x[0]-xo[0] - rx;\n\t\t\t\txr = x[0]-xo[0] + rx;\n\t\t\t\tyl = x[1]-xo[1] - ry;\n\t\t\t\tyr = x[1]-xo[1] + ry;\n\t\t\t\txsqr = (xr*xr) > (xl*xl) ? (xl*xl) : (xr*xr);\n\t\t\t\tysqr = (yr*yr) > (yl*yl) ? (yl*yl) : (yr*yr);\n\t\t\t\tif(xsqr+ysqr <= ro*ro) {\n\t\t\t\t    // std::cout << id <<',';\n\t\t\t\t    id = encode[id*nNodes+q]; //n0xn1->np\n\t\t\t\t} else\n\t\t\t\t    id = -1;\n\t\t\t    }\n\n\t\t\t    return std::move(ix);\n\t\t\t};\n\n    auto local_target = [&local, &local_region]\n\t(const rocs::Rn &xr, const double ro, const double rt,\n\t const rocs::Rn &x0, const std::vector<long long> &encode) {\n\t\t\t    if(xr[0]<0) {\n\t\t\t\treturn std::vector<long long>();\n\t\t\t    }\n\t\t\t    double drsqr = xr[0]*xr[0]+xr[1]*xr[1];\n\t\t\t    double dr = std::sqrt(drsqr);\n\t\t\t    double dt = 2*ro;\n\t\t\t    double a = std::asin(ro/dr);\n\t\t\t    double b = std::atan2(xr[1], xr[0]);\n\t\t\t    double c = std::atan2(dr, dt);\n\n\t\t\t    double rho, theta;\n\t\t\t    if(c > a) {\n\t\t\t\ttheta = c;\n\t\t\t\trho = std::sqrt(drsqr+dt*dt);\n\t\t\t    } else {\n\t\t\t\ttheta = a;\n\t\t\t\trho = dr/std::cos(a);\n\t\t\t    }\n\t\t\t    // double rho1 = 2*std::sqrt(drsqr-ro*ro);\n\t\t\t    // double rho2 = dr/std::cos(a);\n\t\t\t    // double rho = rho1>rho2 ? rho1:rho2;\n\n\t\t\t    double xt1 = rho*std::cos(b+theta);\n\t\t\t    double yt1 = rho*std::sin(b+theta);\n\t\t\t    double xt2 = rho*std::cos(b-theta);\n\t\t\t    double yt2 = rho*std::sin(b-theta);\n\t\t\t    rocs::Rn z1{xt1, yt1, 0};\n\t\t\t    rocs::Rn z2{xt2, yt2, 0};\n\t\t\t    /********** Logging **********/\n\t\t\t    std::cout << dr << ',' << b << ',' << a << ',' << c << ','\n\t\t\t\t      << theta << ',' << rho << '\\n';\n\t\t\t    std::cout << \"z1=(\" << xt1 << ' ' << yt1 << ' ' << 0;\n\t\t\t    std::cout << \", z2=(\" << xt2 << ' ' << yt2 << ' ' << 0 << \")\\n\";\n\t\t\t    /********** Logging **********/\n\n\t\t\t    body_to_inertia(z1, x0);\n\t\t\t    body_to_inertia(z2, x0);\n\t\t\t    std::cout << \"Converting to inertia: \";\n\t\t\t    std::cout << \"z1=(\";\n\t\t\t    for(int i = 0; i < 3; ++i) {\n\t\t\t\tz1[i] += x0[i];\n\t\t\t\tstd::cout << z1[i] << ' ';\n\t\t\t    }\n\t\t\t    std::cout << \"), z2=(\";\n\t\t\t    for(int i = 0; i < 3; ++i) {\n\t\t\t\tz2[i] += x0[i];\n\t\t\t\tstd::cout << z2[i] << ' ';\n\t\t\t    }\n\t\t\t    std::cout << \")\\n\";\n\n\t\t\t    /********** Logging **********/\n\t\t\t    std::ofstream logger;\n\t\t\t    logger.open(\"logs_newgoals.txt\", std::ios::out);\n\t\t\t    for(auto &i:z1)\n\t\t\t    \tlogger << i << ' ';\n\t\t\t    logger << '\\n';\n\t\t\t    for(auto &i:z2)\n\t\t\t    \tlogger << i << ' ';\n\t\t\t    logger.close();\n\t\t\t    /********** Logging **********/\n\n\t\t\t    std::vector<long long> target1 = local_region(z1, rt, encode);\n\t\t\t    std::vector<long long> target2 = local_region(z2, rt, encode);\n\t\t\t    int n1 = std::count_if(target1.begin(), target1.end(),\n\t\t\t\t\t\t   [&local](long long i){\n\t\t\t\t\t\t       return i>-1?local._idmap[i]:0;\n\t\t\t\t\t\t   });\n\t\t\t    int n2 = std::count_if(target2.begin(), target2.end(),\n\t\t\t\t\t\t   [&local](long long i){\n\t\t\t\t\t\t       return i>-1?local._idmap[i]:0;\n\t\t\t\t\t\t   });\n\n\t\t\t    std::cout << n1 << ',' << n2 << '\\n';\n\n\t\t\t    if(n1 >= n2) // return the target set with more winning nodes\n\t\t\t\treturn std::move(target1);\n\t\t\t    else\n\t\t\t\treturn std::move(target2);\n\t\t\t};\n\n\n    /**\n     * Simulation\n     **/\n    const double drange[] = {3.0, 3.0};\n    /* set ode solver */\n    const double tsim = 0.1; //simulation time\n    const double dt = 0.001; //integration step size for odeint\n    boost::numeric::odeint::runge_kutta_cash_karp54<rocs::Rn> rk45;\n\n    /* Initial condition of the ego robot */\n    rocs::Rn x{1, 1, M_PI/3.0};\n    rocs::Rn u{0, 0};\n    long long x_index = x_grid.val_to_id(x);\n    std::vector<long long>::iterator p1;\n    p1 = std::lower_bound(w_x0.begin(), w_x0.end(), x_index);\n    if(*p1 != x_index) {\n\tstd::cout << x[0] <<  \" \"  << x[1] << \" \" << x[2];\n\tstd::cout << \" is not in the winning set, change a new initial state.\" << std::endl;\n\treturn 1;\n    }\n    /* Initial condition of the other robot */\n    rocs::Rn uomax{0.8, 0.8};\n    rocs::Rn uomin{-0.8, -0.8};\n    double v;\n    rocs::Rn xo{0.0, 3.0, 0};\n    rocs::Rn uo{0.0, 0.0};\n    /* State in local relative coordinate */\n    rocs::Rn xr{0,0,0};\n    long long xr_id;\n    boost::dynamic_bitset<> u_safe(cdims[1]);\n    rocs::Rn ui{0.3, 0.0};\n\n    /* Test case 1: a designed pattern for the obstacle */\n    auto obstacle_behavior1 = [&uo, &xo, tsim](int j) {\n\t\t\t\t  double t = tsim*j;\n\t\t\t\t  if(t >= 0) {\n\t\t\t\t      if(t == 0) {\n\t\t\t\t\t  rocs::Rn xi{0.0, 3.0, 0};\n\t\t\t\t\t  xo.assign(xi.begin(), xi.end());\n\t\t\t\t      }\n\t\t\t\t      if(t < 1.5) {\n\t\t\t\t\t  uo[0] = 0.33;\n\t\t\t\t\t  uo[1] = 0.0;\n\t\t\t\t      } else if(t < 3.0) {\n\t\t\t\t\t  uo[0] = 0.8;\n\t\t\t\t\t  uo[1] = 0.7;\n\t\t\t\t      } else if(t < 10.8) {\n\t\t\t\t\t  uo[0] = 0.7;\n\t\t\t\t\t  uo[1] = 0;\n\t\t\t\t      } else if(t < 18.0) {\n\t\t\t\t\t  uo[0] = 0.7;\n\t\t\t\t\t  uo[1] = -0.6;\n\t\t\t\t      } else if(t < 21) {\n\t\t\t\t\t  uo[0] = 0.7;\n\t\t\t\t\t  uo[1] = 0.6;\n\t\t\t\t      } else {\n\t\t\t\t\t  uo[0] = 0.5;\n\t\t\t\t\t  uo[1] = 0.0;\n\t\t\t\t      }\n\t\t\t\t  }\n\t\t\t      };\n\n    /* Test case 2: circular trajectory for the obstacle */\n    auto obstacle_behavior2 = [&uo, &xo, tsim](int j) {\n\t\t\t\t  double t = tsim*j;\n\t\t\t\t  if(t >= 0) {\n\t\t\t\t      if(t == 0) {\n\t\t\t\t\t  rocs::Rn xi{4.5, 0.0, M_PI/2.0};\n\t\t\t\t\t  xo.assign(xi.begin(), xi.end());\n\t\t\t\t      }\n\t\t\t\t      if(t < 8.1) {\n\t\t\t\t\t  uo[0] = 0.65;\n\t\t\t\t\t  uo[1] = 0.0;\n\t\t\t\t      } else if(t < 9.0) {\n\t\t\t\t\t  uo[0] = 0.4;\n\t\t\t\t\t  uo[1] = -0.3;\n\t\t\t\t      } else {\n\t\t\t\t\t  uo[0] = 0.4;\n\t\t\t\t\t  uo[1] = 0.3;\n\t\t\t\t      }\n\t\t\t\t  }\n\t\t\t      };\n\n    /* Test case 3: random v, w for the obstacle */\n    double th = 0;\n    auto obstacle_behavior3 = [&th,&uo, &xo, tsim, &uomin, &uomax](int j) {\n\t\t\t\t  double t = tsim*j;\n\t\t\t\t  double t1 = 15.9;\n\t\t\t\t  double t2 = 2.1;\n\t\t\t\t  if(t >= 0) {\n\t\t\t\t      if(t == 0) {\n\t\t\t\t\t  rocs::Rn xi{10.0, 6.4, M_PI};\n\t\t\t\t\t  xo.assign(xi.begin(), xi.end());\n\t\t\t\t      }\n\t\t\t\t      if(t < t1) {\n\t\t\t\t\t  uo[0] = 0.4;\n\t\t\t\t\t  uo[1] = 0.0;\n\t\t\t\t      } else if(t < t1+t2) {\n\t\t\t\t\t  uo[0] = 0.4;\n\t\t\t\t\t  uo[1] = 0.3;\n\t\t\t\t      } else {\n\t\t\t\t\t  uo[1] = 0.0;\n\t\t\t\t\t  if(th>=8*tsim) {\n\t\t\t\t\t      uo[0] = -uo[0];\n\t\t\t\t\t      th = 0;\n\t\t\t\t\t  }\n\t\t\t\t\t  th += tsim;\n\t\t\t\t      }\n\t\t\t\t      // if(t < 18.9) { // straight line, constant speed\n\t\t\t\t      // \t  uo[0] = 0.4;\n\t\t\t\t      // \t  uo[1] = 0.0;\n\t\t\t\t      // } else { // random v, w\n\t\t\t\t      // \t  uo[0] = (uomax[0]-uomin[0])*((double)rand()/RAND_MAX)\n\t\t\t\t      // \t      - (uomax[0]-uomin[0])/2;\n\t\t\t\t      // \t  uo[1] = (uomax[1]-uomin[1])*((double)rand()/RAND_MAX)\n\t\t\t\t      // \t      - (uomax[1]-uomin[1])/2;\n\t\t\t\t      // }\n\t\t\t\t  }\n\t\t\t      };\n\n\n    /* Open files for writing results and logs */\n    std::string simfile = \"traj_closedloop_ca_3_t.txt\";\n    std::ofstream ctlrWtr(simfile);\n    if(!ctlrWtr.is_open())\n\tctlrWtr.open(simfile, std::ios::out);\n    std::string simother = \"traj_other_robot_3_t.txt\";\n    std::ofstream otherWtr(simother);\n    if(!otherWtr.is_open())\n    \totherWtr.open(simother, std::ios::out);\n    /********** Logging **********/\n    std::ofstream logger;\n    logger.open(\"logs_3_t.txt\", std::ios::out);\n    /********** Logging **********/\n\n\n    /* Simulation loop */\n    srand(time(NULL));\n    float tpat = 0;\n    int max_num_achieve_acc=5, max_num_iteration=1500; //3000000;\n    // rocs::UintSmall q;\n    int i, j;\n    double t0, tc; //record the time when an obstacle detected\n    bool entry = false;\n    rocs::Rn xb(xr); //record the position of the robot when an obstacle detected\n    bool replanned = false;\n    std::vector<CTRL>::iterator p7;\n    NODE_POST p5;\n    std::cout << \"\\nLaunching simulation...\\n\";\n    for(q = q0, i = j = 0; i<max_num_achieve_acc && j<max_num_iteration; ++j) {\n\t/* choose obstacle trajectory */\n\tobstacle_behavior3(j);\n\n\t/* Determine the control u by the product state (x_index, q) */\n\tp5 = nts_ctrlr[encode3[x_index]];\n\tp7 = std::lower_bound(ctrl.begin()+p5.pos, ctrl.begin()+p5.pos+p5.num_a,\n\t\t\t      q, [](const CTRL &item, const int val) {\n\t\t\t\t     return item.q < val;});\n\tif(p7->q != q) {\n\t    // std::cout << j << \"th iteration: \" << \"Reach accepting state \" << i << \" times.\\n\";\n\t    // std::cout << \"Automaton state: \" << q << '\\n';\n\t    // std::cout << \"Position in ctrl list: \" << p5.pos << \", number of actions: \" << p5.num_a << '\\n';\n\t    std::cout << \"Error in ctrl\" << std::endl;\n\t    break;\n\t}\n\tu_grid.id_to_val(u, p7->u);\n\n\t/* Print to screen */\n\tstd::cout << \"# \" << j << \":\\n\";\n\tstd::cout << \"x: [\" << x[0] <<  ','  << x[1] << ',' << x[2] << \"]\\n\";\n\tstd::cout << \"Nominal control: \" << p7->u << '('\n\t\t  << '[' << u[0] << ',' << u[1] << \"])\\n\";\n\tstd::cout << \"current dba state: \" << q << \"\\n\";\n\n\n\t/* Get the relative state xr */\n\txr[0] = xo[0]-x[0];\n\txr[1] = xo[1]-x[1];\n\txr[2] = xo[2]-x[2];\n\tif(xr[2] > M_PI) //convert angle into [-pi, pi]\n\t    xr[2] -= 2*M_PI;\n\tif(xr[2] < -M_PI)\n\t    xr[2] += 2*M_PI;\n\tinertia_to_body(xr, x); //convert from the inertial to body frame\n\n\t/* Deal with obstacles */\n\tif(std::fabs(xr[0])*std::fabs(xr[0]) +\n\t   std::fabs(xr[1])*std::fabs(xr[1]) < drange[0]*drange[1]) {\n\t// if(std::fabs(xr[0])<drange[0] && std::fabs(xr[1])<drange[1]) {\n\t    if(!entry) {\n\t\tentry = true;\n\t\tt0 = j*tsim; //record the first time an obstacle is detected\n\t\txb = x;\n\t\t/********** Logging **********/\n\t\tlogger << \"t0=\" << t0 << \",xb=\"\n\t\t       << '(' << xb[0] << ',' << xb[1] << ',' << xb[2] << \")\\n\";\n\t\t/********** Logging **********/\n\t    }\n\t    tc = j*tsim; //record the current time\n\n\t    std::cout << \"An obstacle detected.\\n\";\n\t    std::cout << \"Relative coordinate: \";\n\t    if(rel_grid._bds.isout(xr)) { // xr is the out-of-domain node\n\t\tstd::cout << rel_grid._nv;\n\t    } else {\n\t\txr_id = rel_grid.val_to_id(xr); //uniform grid rel_grid\n\t\tstd::cout << xr_id;\n\t    }\n\t    std::cout << \"([\" << xr[0] << ',' << xr[1] << ',' << xr[2] << \"])\\n\";\n\n\t    /********** Logging **********/\n\t    logger << tc << '(' << j << \"):\"\n\t\t   << x_index << '(' << x[0] << ',' << x[1] << ',' << x[2] << \"),\"\n\t\t   << xr_id << '(' << xr[0] << ',' << xr[1] << ',' << xr[2] << \")\\n\";\n\t    /********** Logging **********/\n\n\t    size_t xp = x_index*nNodes+q; // (idx,idq)=idx*nNodes+idq (buchi.c)\n\t    size_t uid;\n\n\t    /********** Logging **********/\n\t    size_t row, key = local._encode[xp];\n\t    row = local._idmap[key];\n\t    // std::cout << \"id_n0n1: \" << xp << ',' << \" id_np: \" << key << '\\n';\n\t    for(size_t k = 0; k < u_grid._nv; ++k) {\n\t\tif(local._winfts._npost[row*local._na+k]) {//outdeg>0\n\t\t    logger << k << ' ';\n\t\t}\n\t    }\n\t    logger << \", \";\n\t    /********** Logging **********/\n\n\t    /* Determine if a replanning is needed to avoid stuck */\n\t    if(tc-t0>3) {\n\t\tif(std::fabs(x[0]-xb[0])<0.4 && std::fabs(x[1]-xb[1])<0.4) {\n\t\t    if(!replanned) {//replanning\n\t\t\tstd::cout << \"Replanning...\\n\";\n\t\t\tavoid = local_region(xo, ro, local._encode); // np-based id's\n\t\t\ttarget = local_target(xr, ro, rt, x, local._encode);\n\t\t\tif(!target.empty()) {\n\t\t\t    // /********** Logging **********/\n\t\t\t    // rocs::h5FileHandler wtr(\"logs_replan.h5\", H5F_ACC_TRUNC);\n\t\t\t    // long long ix;\n\t\t\t    // std::vector<long long> wa, wt;\n\t\t\t    // for(auto id:avoid) {\n\t\t\t    // \tif(id>-1?local._idmap[id]:0) {\n\t\t\t    // \t    ix = local._decode[id]/nNodes;\n\t\t\t    // \t    wa.push_back(ix);\n\t\t\t    // \t}\n\t\t\t    // }\n\t\t\t    // wtr.write_array<long long>(wa, \"avoid\");\n\t\t\t    // for(auto id:target) {\n\t\t\t    // \tif(id>-1?local._idmap[id]:0) {\n\t\t\t    // \t    ix = local._decode[id]/nNodes;\n\t\t\t    // \t    wt.push_back(ix);\n\t\t\t    // \t}\n\t\t\t    // }\n\t\t\t    // wtr.write_array<long long>(wt, \"target\");\n\t\t\t    // wtr.write_array<double>(x, \"x\");\n\t\t\t    // wtr.write_array<double>(xo, \"xo\");\n\n\t\t\t    // // std::cin.get();\n\t\t\t    // /********** Logging **********/\n\t\t\t    tb = clock();\n\t\t\t    replan = local.solve_local_reachavoid(xp, per*target.size(), avoid, target, plhdr);\n\t\t\t    te = clock();\n\t\t\t    tpat += (float)(te - tb)/CLOCKS_PER_SEC;\n\t\t\t    std::cout << \"Average time for Detouring: \"\n\t\t\t\t      << tpat/(j+1) << \".\\n\";\n\t\t\t    if(replan[0].first == xp)\n\t\t\t\treplanned = true;\n\t\t\t    else\n\t\t\t\tstd::cout << \"Replanning failed.\\n\";\n\t\t\t} else {\n\t\t\t    std::cout << \"Replanning failed: no target points.\\n\";\n\t\t\t}\n\t\t    }\n\t\t} else {\n\t\t    entry = false; //reset t0 if robot make progress in 3 secs\n\t\t}\n\t    }\n\t    /* Perform replan if replan is activated. Replan is activated when\n\t     * - replanning is successful, and\n\t     * - local target hasn't reached. */\n\t    std::vector<std::pair<size_t, int> >::iterator uiter;\n\t    if(replanned && std::find(target.begin(),target.end(),local._encode[xp])==target.end()) {\n\t\t/* If replan succeeds and the local target hasn't been reached */\n\t\tuiter = std::find_if(replan.begin(), replan.end(),\n\t\t\t\t     [&xp](std::pair<size_t, int> &item){return item.first==xp;});\n\t\tif(uiter != replan.end()) {//replan can be followed correctly\n\t\t    std::cout << \"Apply the replanned reach control.\\n\";\n\t\t    uid = uiter->second;\n\t\t    u_grid.id_to_val(u, uid);\n\t\t    /********** Logging **********/\n\t\t    logger << uid << ' ';\n\t\t    /********** Logging **********/\n\t\t} else {\n\t\t    replanned = false;\n\t\t    std::cout << \"Error in executing replan. Abort replan and follow RH.\\n\";\n\t\t}\n\t    } else {\n\t\treplanned = false;\n\t    }\n\n\t    /* Perform RH (receding horizon) module if replan is not activated. */\n\t    if(!replanned) {\n\t\t/* Determine safe inputs for RH module */\n\t\tstd::cout << \"Use RH to find safe control inputs: \";\n\t\tint nSafeAct = 0;\n\t\trocs::Rn uu(u_dim);\n\t\tdouble dtemp, u_dist=(uub[0]-ulb[0])*(uub[0]-ulb[0])+(uub[1]-ulb[1])*(uub[1]-ulb[1]);\n\t\tfor(size_t k = 0; k < cdims[1]; ++k) {\n\t\t    u_safe[k] = safeCtlr[xr_id*cdims[1]+k];\n\t\t    /************* Logging **************/\n\t\t    if(u_safe[k]) {\n\t\t\t// std::cout << k << ',';\n\t\t\t// std::cout << \"Outdeg: \"\n\t\t\t// \t      << local._winfts._npost[row*local._na+k]\n\t\t\t// \t      << '\\n';\n\t\t\tif(local._winfts._npost[row*local._na+k]) {//outdeg>0\n\t\t\t    ++nSafeAct; //count the # of safe valid controls\n\t\t\t    /* take the closest to the original one */\n\t\t\t    u_grid.id_to_val(uu, k);\n\t\t\t    dtemp = (uu[0]-u[0])*(uu[0]-u[0])+(uu[1]-u[1])*(uu[1]-u[1]);\n\t\t\t    if(dtemp < u_dist) {\n\t\t\t\tuid = k;\n\t\t\t\tu_dist= dtemp;\n\t\t\t    }\n\t\t\t    // std::cout << \"Post nodes: \";\n\t\t\t    // size_t pidstart=local._winfts._ptrpost[row*local._na+k];\n\t\t\t    // for(size_t pid=pidstart; pid<pidstart+local._winfts._npost[row*local._na+k]; ++pid)\n\t\t\t    //     std::cout << local._winfts._idpost[pid] << ' ';\n\t\t\t    // std::cout << '\\n';\n\t\t\t}\n\t\t\tlogger << k << ' ';\n\t\t    }\n\t\t    /************* Logging **************/\n\t\t}\n\t\t/********** Logging **********/\n\t\tu_grid.id_to_val(uu, uid);\n\t\tlogger << '\\n'\n\t\t       << p7->u << ' ' << u[0] << ',' << u[1] << ';'\n\t\t       << uid << ' ' << uu[0] << ',' << uu[1] << ' ' << u_dist << ';';\n\t\t/********** Logging **********/\n\n\t\t/* Get a safe control from patcher */\n\t\tif(u_safe[p7->u]) {\n\t\t// if(safeCtlr[xr_id*cdims[1]+uid]) {\n\t\t    std::cout << \"The static strategy is safe.\\n\";\n\t\t    // u_grid.id_to_val(u, uid);\n\t\t    // logger << uid << ' ';\n\t\t    logger << p7->u << ' ';\n\t\t} else if(nSafeAct > 1) {\n\t\t    tb = clock();\n\t\t    int suc = local.solve_local_reachability(xp, horizon, u_safe);\n\t\t    te = clock();\n\t\t    tpat += (float)(te - tb)/CLOCKS_PER_SEC;\n\t\t    std::cout << \"Average time for RH: \"\n\t\t\t      << tpat/(j+1) << \".\\n\";\n\t\t    if(!suc) {//if fails in re-planning, use the closest u\n\t\t\tstd::cout << \"Apply the safe control input closest to the original one.\\n\";\n\t\t\tu_grid.id_to_val(u, uid);\n\t\t\tlogger << uid << ' ';\n\t\t    } else {\n\t\t\tstd::cout << \"Apply controls returned by local reachability.\\n\";\n\t\t\tu_grid.id_to_val(u, local._ctlr);\n\t\t\tlogger << local._ctlr << ' ';\n\t\t    }\n\t\t} else if(nSafeAct > 0) {\n\t\t    std::cout << \"Apply the only one safe control.\\n\";\n\t\t    u_grid.id_to_val(u, uid);\n\t\t    logger << uid << ' ';\n\t\t} else {\n\t\t    std::cout << \"No safe controls. Freeze.\\n\";\n\t\t    u[0] = 0;\n\t\t    u[1] = 0;\n\t\t    logger << p7->u << ' ';\n\t\t}\n\t    }//end RH\n\t    /********** Logging **********/\n\t    logger << u[0] << ',' << u[1] << \"\\n\\n\";\n\t    /********** Logging **********/\n\n\t} else {\n\t    entry = false;\n\t    replanned = false; //reset replanning flag\n\t}//end if obstacle is within range\n\n\t/* Write to txt file */\n\t// ctlrWtr << j << ':';\n\tfor(int d = 0; d < x_dim; ++d) {\n\t    /* the controlled state */\n\t    ctlrWtr << x[d];\n\t    /* the state of the other robot */\n\t    otherWtr << xo[d];\n\t    if(d<x_dim-1) {\n\t\tctlrWtr << ',';\n\t\totherWtr << ',';\n\t    }\n\t}\n\tctlrWtr << ';';\n\totherWtr << ';';\n\tfor(int d = 0; d < u_dim; ++d) {\n\t    ctlrWtr << u[d];\n\t    otherWtr << uo[d];\n\t    if(d<u_dim-1) {\n\t\tctlrWtr << ',';\n\t\totherWtr << ',';\n\t    }\n\t}\n\tctlrWtr << '\\n';\n\totherWtr << '\\n';\n\n\t/* Integrate ego robot trajectory */\n\tboost::numeric::odeint::integrate_const(rk45, car_dynamics(u), x, 0.0, tsim, dt);\n\tif(x[2] > M_PI) //convert angle into [-pi, pi]\n\t    x[2] -= 2*M_PI;\n\tif(x[2] < -M_PI)\n\t    x[2] += 2*M_PI;\n\n\t/* integrate obstacle trajectory after it appears */\n\tboost::numeric::odeint::integrate_const(rk45, car_dynamics(uo), xo, 0.0, tsim, dt);\n\tif(xo[2] > M_PI) //convert angle into [-pi, pi]\n\t    xo[2] -= 2*M_PI;\n\tif(xo[2] < -M_PI)\n\t    xo[2] += 2*M_PI;\n\n\t/* Update automaton state q */\n\tx_index = x_grid.val_to_id(x);\n\tq = q_prime[p5.label*nNodes + q];\n\tif(isacc[q])\n\t    std::cout << \"******** achieve acc \\'\" << q << \"\\' \" << ++i << \" time ********\" << std::endl;\n    }\n\n    ctlrWtr.close();\n    otherWtr.close();\n    logger.close();\n\n    return 0;\n}\n", "meta": {"hexsha": "c7cda223317e2ad230b47d7d94776b317b8d0d9a", "size": 22722, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/collision-avoid/sim_onlineca_replan.cpp", "max_stars_repo_name": "yinanl/rocs", "max_stars_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "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/collision-avoid/sim_onlineca_replan.cpp", "max_issues_repo_name": "yinanl/rocs", "max_issues_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/collision-avoid/sim_onlineca_replan.cpp", "max_forks_repo_name": "yinanl/rocs", "max_forks_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "max_forks_repo_licenses": ["BSD-3-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.2975206612, "max_line_length": 104, "alphanum_fraction": 0.5055012763, "num_tokens": 7612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2584233853947827}}
{"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_DISCRETE_DISTANCE_GEOGRAPHIC_HPP\n#define BOOST_GEOMETRY_STRATEGIES_DISCRETE_DISTANCE_GEOGRAPHIC_HPP\n\n\n#include <boost/geometry/strategies/detail.hpp>\n#include <boost/geometry/strategies/discrete_distance/services.hpp>\n#include <boost/geometry/strategies/distance/comparable.hpp>\n#include <boost/geometry/strategies/distance/detail.hpp>\n\n#include <boost/geometry/strategies/geographic/distance.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\nnamespace boost { namespace geometry\n{\n\nnamespace strategies { namespace discrete_distance\n{\n\ntemplate\n<\n    typename FormulaPolicy = strategy::andoyer,\n    typename Spheroid = srs::spheroid<double>,\n    typename CalculationType = void\n>\nclass geographic\n    : public strategies::detail::geographic_base<Spheroid>\n{\n    using base_t = strategies::detail::geographic_base<Spheroid>;\n\npublic:\n    geographic() = default;\n\n    explicit geographic(Spheroid const& spheroid)\n        : base_t(spheroid)\n    {}\n\n    template <typename Geometry1, typename Geometry2>\n    auto distance(Geometry1 const&, Geometry2 const&,\n                  distance::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\n\nnamespace services\n{\n\ntemplate <typename Geometry1, typename Geometry2>\nstruct default_strategy<Geometry1, Geometry2, geographic_tag, geographic_tag>\n{\n    using type = strategies::discrete_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::discrete_distance::geographic<FP, 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::discrete_distance::geographic<strategy::andoyer, 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::discrete_distance::geographic<strategy::thomas, 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::discrete_distance::geographic<strategy::vincenty, S, CT>(s.model());\n    }\n};\n\n\n} // namespace services\n\n}} // namespace strategies::discrete_distance\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_DISCRETE_DISTANCE_GEOGRAPHIC_HPP\n", "meta": {"hexsha": "f5cb1df641b6683108b6f5293fc34e2bf8a8bbfa", "size": 3469, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/boost/geometry/strategies/discrete_distance/geographic.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/strategies/discrete_distance/geographic.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/strategies/discrete_distance/geographic.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": 29.9051724138, "max_line_length": 95, "alphanum_fraction": 0.7316229461, "num_tokens": 818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2583214298375215}}
{"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, 2016, 2017.\n// Modifications copyright (c) 2013-2017 Oracle and/or its affiliates.\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_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 boost { namespace geometry\n{\n\nnamespace strategy { namespace within\n{\n\n// 1 deg or pi/180 rad\ntemplate <typename Point,\n          typename CalculationType = typename coordinate_type<Point>::type>\nstruct winding_small_angle\n{\n    typedef typename coordinate_system<Point>::type cs_t;\n    typedef math::detail::constants_on_spheroid\n        <\n            CalculationType,\n            typename cs_t::units\n        > constants;\n\n    static inline CalculationType apply()\n    {\n        return constants::half_period() / CalculationType(180);\n    }\n};\n\n\n// Fix for https://svn.boost.org/trac/boost/ticket/9628\n// For floating point coordinates, the <D> 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// Below picture assuming D = 1, if D = 0 horiz<->vert, E<->N, RIGHT<->UP.\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// _____/\n// In the code below actually D = 0, so segments are nearly-vertical\n// Called when the point is on the same level as one of the segment's points\n// but the point is not aligned with a vertical segment\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 <typename Point, typename PointOfSegment>\n    static inline int apply(Point const& point,\n                            PointOfSegment const& se,\n                            int count)\n    {\n        typedef typename coordinate_type<PointOfSegment>::type scoord_t;\n        typedef typename coordinate_system<PointOfSegment>::type::units units_t;\n\n        if (math::equals(get<1>(point), get<1>(se)))\n            return 0;\n\n        // Create a horizontal segment intersecting the original segment's endpoint\n        // equal to the point, with the derived direction (E/W).\n        PointOfSegment ss1, ss2;\n        set<1>(ss1, get<1>(se));\n        set<0>(ss1, get<0>(se));\n        set<1>(ss2, get<1>(se));\n        scoord_t ss20 = get<0>(se);\n        if (count > 0)\n        {\n            ss20 += winding_small_angle<PointOfSegment>::apply();\n        }\n        else\n        {\n            ss20 -= winding_small_angle<PointOfSegment>::apply();\n        }\n        math::normalize_longitude<units_t>(ss20);\n        set<0>(ss2, ss20);\n\n        // Check the side using this vertical segment\n        return strategy_side_type::apply(ss1, ss2, point);\n    }\n};\n// The optimization for cartesian\ntemplate <>\nstruct winding_side_equal<cartesian_tag>\n{\n    template <typename Point, typename PointOfSegment>\n    static inline int apply(Point const& point,\n                            PointOfSegment const& se,\n                            int count)\n    {\n        // NOTE: for D=0 the signs would be reversed\n        return math::equals(get<1>(point), get<1>(se)) ?\n                0 :\n                get<1>(point) < get<1>(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 Point,\n          typename CalculationType,\n          typename CSTag = typename cs_tag<Point>::type>\nstruct winding_check_touch\n{\n    typedef CalculationType calc_t;\n    typedef typename coordinate_system<Point>::type::units units_t;\n    typedef math::detail::constants_on_spheroid<CalculationType, units_t> constants;\n\n    template <typename PointOfSegment, typename State>\n    static inline int apply(Point const& point,\n                            PointOfSegment const& seg1,\n                            PointOfSegment const& seg2,\n                            State& state,\n                            bool& eq1,\n                            bool& eq2)\n    {\n        calc_t const pi = constants::half_period();\n        calc_t const pi2 = pi / calc_t(2);\n\n        calc_t const px = get<0>(point);\n        calc_t const s1x = get<0>(seg1);\n        calc_t const s2x = get<0>(seg2);\n        calc_t const py = get<1>(point);\n        calc_t const s1y = get<1>(seg1);\n        calc_t const s2y = get<1>(seg2);\n\n        // NOTE: lat in {-90, 90} and arbitrary lon\n        //  it doesn't matter what lon it is if it's a pole\n        //  so e.g. if one of the segment endpoints is a pole\n        //  then only the other lon matters\n        \n        bool eq1_strict = math::equals(s1x, px);\n        bool eq2_strict = math::equals(s2x, px);\n\n        eq1 = eq1_strict // lon strictly equal to s1\n           || math::equals(s1y, pi2) || math::equals(s1y, -pi2); // s1 is pole\n        eq2 = eq2_strict // lon strictly equal to s2\n           || math::equals(s2y, pi2) || math::equals(s2y, -pi2); // s2 is pole\n        \n        // segment overlapping pole\n        calc_t s1x_anti = s1x + constants::half_period();\n        math::normalize_longitude<units_t, calc_t>(s1x_anti);\n        bool antipodal = math::equals(s2x, s1x_anti);\n        if (antipodal)\n        {\n            eq1 = eq2 = eq1 || eq2;\n\n            // segment overlapping pole and point is pole\n            if (math::equals(py, pi2) || math::equals(py, -pi2))\n            {\n                eq1 = eq2 = true;\n            }\n        }\n        \n        // Both equal p -> segment vertical\n        // The only thing which has to be done is check if point is ON segment\n        if (eq1 && eq2)\n        {\n            // segment endpoints on the same sides of the globe\n            if (! antipodal\n                // p's lat between segment endpoints' lats\n                ? (s1y <= py && s2y >= py) || (s2y <= py && s1y >= py)\n                // going through north or south pole?\n                : (pi - s1y - s2y <= pi\n                    ? (eq1_strict && s1y <= py) || (eq2_strict && s2y <= py) // north\n                        || math::equals(py, pi2) // point on north pole\n                    : (eq1_strict && s1y >= py) || (eq2_strict && s2y >= py)) // south\n                        || math::equals(py, -pi2) // point on south pole\n                )\n            {\n                state.m_touches = true;\n            }\n            return true;\n        }\n        return false;\n    }\n};\n// The optimization for cartesian\ntemplate <typename Point, typename CalculationType>\nstruct winding_check_touch<Point, CalculationType, cartesian_tag>\n{\n    typedef CalculationType calc_t;\n\n    template <typename PointOfSegment, typename State>\n    static inline bool apply(Point const& point,\n                             PointOfSegment const& seg1,\n                             PointOfSegment const& seg2,\n                             State& state,\n                             bool& eq1,\n                             bool& eq2)\n    {\n        calc_t const px = get<0>(point);\n        calc_t const s1x = get<0>(seg1);\n        calc_t const s2x = get<0>(seg2);\n\n        eq1 = math::equals(s1x, px);\n        eq2 = math::equals(s2x, px);\n\n        // Both equal p -> segment vertical\n        // The only thing which has to be done is check if point is ON segment\n        if (eq1 && eq2)\n        {\n            calc_t const py = get<1>(point);\n            calc_t const s1y = get<1>(seg1);\n            calc_t const s2y = get<1>(seg2);\n            if ((s1y <= py && s2y >= py) || (s2y <= py && s1y >= py))\n            {\n                state.m_touches = true;\n            }\n            return true;\n        }\n        return false;\n    }\n};\n\n\n// Called if point is not aligned with a vertical segment\ntemplate <typename Point,\n          typename CalculationType,\n          typename CSTag = typename cs_tag<Point>::type>\nstruct winding_calculate_count\n{\n    typedef CalculationType calc_t;\n    typedef typename coordinate_system<Point>::type::units units_t;\n\n    static inline bool greater(calc_t const& l, calc_t const& r)\n    {\n        calc_t diff = l - r;\n        math::normalize_longitude<units_t, calc_t>(diff);\n        return diff > calc_t(0);\n    }\n\n    static inline int apply(calc_t const& p,\n                            calc_t const& s1, calc_t const& s2,\n                            bool eq1, bool eq2)\n    {\n        // Probably could be optimized by avoiding normalization for some comparisons\n        // e.g. s1 > p could be calculated from p > s1\n\n        // If both segment endpoints were poles below checks wouldn't be enough\n        // but this means that either both are the same or that they are N/S poles\n        // and therefore the segment is not valid.\n        // If needed (eq1 && eq2 ? 0) could be returned\n\n        return\n              eq1 ? (greater(s2, p) ?  1 : -1)      // Point on level s1, E/W depending on s2\n            : eq2 ? (greater(s1, p) ? -1 :  1)      // idem\n            : greater(p, s1) && greater(s2, p) ?  2 // Point between s1 -> s2 --> E\n            : greater(p, s2) && greater(s1, p) ? -2 // Point between s2 -> s1 --> W\n            : 0;\n    }\n};\n// The optimization for cartesian\ntemplate <typename Point, typename CalculationType>\nstruct winding_calculate_count<Point, CalculationType, cartesian_tag>\n{\n    typedef CalculationType calc_t;\n    \n    static inline int apply(calc_t const& p,\n                            calc_t const& s1, calc_t const& s2,\n                            bool eq1, bool eq2)\n    {\n        return\n              eq1 ? (s2 > p ?  1 : -1)  // Point on level s1, E/W depending on s2\n            : eq2 ? (s1 > p ? -1 :  1)  // idem\n            : s1 < p && s2 > p ?  2     // Point between s1 -> s2 --> E\n            : s2 < p && s1 > p ? -2     // Point between s2 -> s1 --> W\n            : 0;\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 SideStrategy Side strategy\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 SideStrategy = typename strategy::side::services::default_strategy\n                                <\n                                    typename cs_tag<Point>::type\n                                >::type,\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    /*! 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        template <typename P, typename CT, typename CST>\n        friend struct winding_check_touch;\n\n        inline counter()\n            : m_count(0)\n            , m_touches(false)\n        {}\n\n    };\n\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        if (winding_check_touch<Point, calculation_type>\n                ::apply(point, seg1, seg2, state, eq1, eq2))\n        {\n            return 0;\n        }\n\n        calculation_type const p = get<0>(point);\n        calculation_type const s1 = get<0>(seg1);\n        calculation_type const s2 = get<0>(seg2);\n        return winding_calculate_count<Point, calculation_type>\n                    ::apply(p, s1, s2, eq1, eq2);\n    }\n\n\npublic:\n    winding()\n    {}\n\n    explicit winding(SideStrategy const& side_strategy)\n        : m_side_strategy(side_strategy)\n    {}\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    inline bool apply(Point const& point,\n                      PointOfSegment const& s1, PointOfSegment const& s2,\n                      counter& state) const\n    {\n        typedef typename cs_tag<Point>::type cs_t;\n\n        bool eq1 = false;\n        bool eq2 = false;\n        boost::ignore_unused(eq2);\n\n        int count = check_segment(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>::apply(point, eq1 ? s1 : s2, count);\n            }\n            else // count == 2 || count == -2\n            {\n                // 1 left, -1 right\n                side = m_side_strategy.apply(s1, s2, point);\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\nprivate:\n    SideStrategy m_side_strategy;\n};\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\nnamespace services\n{\n\ntemplate <typename Point, typename Geometry, typename AnyTag>\nstruct default_strategy<Point, Geometry, point_tag, AnyTag, pointlike_tag, polygonal_tag, cartesian_tag, cartesian_tag>\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, Geometry, point_tag, AnyTag, pointlike_tag, polygonal_tag, spherical_tag, spherical_tag>\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, Geometry, point_tag, AnyTag, pointlike_tag, linear_tag, cartesian_tag, cartesian_tag>\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, Geometry, point_tag, AnyTag, pointlike_tag, linear_tag, spherical_tag, spherical_tag>\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#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace strategy { namespace covered_by { namespace services\n{\n\ntemplate <typename Point, typename Geometry, typename AnyTag>\nstruct default_strategy<Point, Geometry, point_tag, AnyTag, pointlike_tag, polygonal_tag, cartesian_tag, cartesian_tag>\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, Geometry, point_tag, AnyTag, pointlike_tag, polygonal_tag, spherical_tag, spherical_tag>\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, Geometry, point_tag, AnyTag, pointlike_tag, linear_tag, cartesian_tag, cartesian_tag>\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, Geometry, point_tag, AnyTag, pointlike_tag, linear_tag, spherical_tag, spherical_tag>\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 boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGY_AGNOSTIC_POINT_IN_POLY_WINDING_HPP\n", "meta": {"hexsha": "3e7e258788d7656f49aa651e2ed23b61650b8f2a", "size": 17906, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/include/boost/geometry/strategies/agnostic/point_in_poly_winding.hpp", "max_stars_repo_name": "Manu343726/boost-cmake", "max_stars_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2017-07-03T18:36:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T14:57:19.000Z", "max_issues_repo_path": "libs/geometry/include/boost/geometry/strategies/agnostic/point_in_poly_winding.hpp", "max_issues_repo_name": "Manu343726/boost-cmake", "max_issues_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2017-07-22T14:05:34.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-06T20:01:30.000Z", "max_forks_repo_path": "libs/geometry/include/boost/geometry/strategies/agnostic/point_in_poly_winding.hpp", "max_forks_repo_name": "Manu343726/boost-cmake", "max_forks_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2017-07-04T14:15:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-12T04:50:41.000Z", "avg_line_length": 33.7849056604, "max_line_length": 119, "alphanum_fraction": 0.6033173238, "num_tokens": 4295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.25831172334201086}}
{"text": "#include <iostream>\r\n#include <fstream>\r\n#include <iomanip>\r\n#include <boost/lexical_cast.hpp>\r\n#include <boost/program_options.hpp>\r\n#include \"RayTrace.h\"\r\n#include \"RayTrace_IceModels.h\"\r\n\r\nstruct underline{\r\n\tstatic char esc;\r\n\tconst std::string& str;\r\n\tunderline(const std::string& s):str(s){}\r\n\tfriend std::ostream& operator<<(std::ostream& os, const underline& u);\r\n};\r\n\r\nchar underline::esc=0x1B;\r\n\r\nstd::ostream& operator<<(std::ostream& os, const underline& u){\r\n\treturn(os << underline::esc << \"[4m\" << u.str << underline::esc << \"[0m\");\r\n}\r\n\r\ntemplate<typename positionType>\r\nclass pathPrinter{\r\npublic:\r\n\tpathPrinter(){}\r\n\tvoid operator()(const positionType& p, RayTrace::RKStepType stepType){\r\n\t\tstd::cout << p.x << ' ' << p.z << '\\n';\r\n\t}\r\n};\r\n\r\nint main(int argc, char* argv[]){\r\n\tdouble ns,nd,nc;\r\n\tdouble src_x, src_y, src_z, trg_x, trg_y, trg_z;\r\n\tVector src,trg;\r\n\tbool showLabels=true;\r\n\tbool dumpPaths=false;\r\n\tbool surface_reflect;\r\n\tbool bedrock_reflect;\r\n\tdouble requiredAccuracy;\r\n\tdouble frequency;\r\n\tdouble polarization;\r\n\tboost::shared_ptr<RayTrace::indexOfRefractionModel> refractionModel;\r\n\tstd::string refractionName;\r\n\tboost::shared_ptr<RayTrace::attenuationModel> attenuationModel;\r\n\tstd::string attenuationName;\r\n\t\r\n\tboost::program_options::options_description desc(\"Allowed options\");\r\n\tdesc.add_options()\r\n\t\t(\"help,h\",\"print usage information\")\r\n\t\t(\"src_x\",boost::program_options::value<double>(&src_x),\"source x coordinate\")\r\n\t\t(\"src_y\",boost::program_options::value<double>(&src_y),\"source y coordinate\")\r\n\t\t(\"src_z\",boost::program_options::value<double>(&src_z),\"source z coordinate\")\r\n\t\t(\"trg_x\",boost::program_options::value<double>(&trg_x),\"target x coordinate\")\r\n\t\t(\"trg_y\",boost::program_options::value<double>(&trg_y),\"target y coordinate\")\r\n\t\t(\"trg_z\",boost::program_options::value<double>(&trg_z),\"target z coordinate\")\r\n\t\t(\"quiet,q\",\"quiet, hide column labels\")\r\n\t\t(\"show_paths,p\",\"show paths; print out x and z coordinates of points visited along each path. Suppresses ordinary output\")\r\n\t\t(\"n_s\",boost::program_options::value<double>(&ns)->default_value(1.35),\"surface index of refraction\")\r\n\t\t(\"n_d\",boost::program_options::value<double>(&nd)->default_value(1.78),\"deep index of refraction\")\r\n\t\t(\"n_c\",boost::program_options::value<double>(&nc)->default_value(.0132),\"index of refraction transition coefficient\")\r\n\t\t(\"reflect_surface\",boost::program_options::value<bool>(&surface_reflect)->default_value(true),\"whether to search for surface\\nreflected solutions\")\r\n\t\t(\"reflect_bedrock\",boost::program_options::value<bool>(&bedrock_reflect)->default_value(false),\"whether to search for bedrock\\nreflected solutions\")\r\n\t\t(\"accuracy\",boost::program_options::value<double>(&requiredAccuracy)->default_value(0.1),\"the maximum acceptable vertical miss distance in meters\")\r\n\t\t(\"frequency\",boost::program_options::value<double>(&frequency)->default_value(300),\"the frequency of the signal, in MHz\")\r\n\t\t(\"polarization\",boost::program_options::value<double>(&polarization)->default_value(RayTrace::pi/2),\"the angle of the signal polarization, relative to the plane of propagation, in radians\")\r\n\t\t(\"index_of_refraction\",boost::program_options::value<std::string>(&refractionName)->default_value(\"exponential\"),\r\n\t\t \"the index of refraction function of the ice, recognized values are 'exponential', 'inverse_exponential', 'quadratic', 'todor_linear', 'todor_chi', and 'todor_LL'\")\r\n\t\t(\"attenuation\",boost::program_options::value<std::string>(&attenuationName)->default_value(\"besson\"),\"the attenuation function of the ice, recognized values are 'negligible' and 'besson'\")\r\n\t;\r\n\tboost::program_options::positional_options_description p;\r\n\tp.add(\"src_x\", 1);\r\n\tp.add(\"src_y\", 1);\r\n\tp.add(\"src_z\", 1);\r\n\tp.add(\"trg_x\", 1);\r\n\tp.add(\"trg_y\", 1);\r\n\tp.add(\"trg_z\", 1);\r\n\t\r\n\tboost::program_options::variables_map vm;\r\n\ttry{\r\n\t\tboost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);\r\n\t\tboost::program_options::notify(vm);\r\n\t}catch(std::exception& except){\r\n\t\tstd::cerr << \"Caught an exception during argument parsing: \" << except.what() << std::endl;\r\n\t\treturn(1);\r\n\t}catch(...){\r\n\t\tstd::cerr << \"An unknown exception was caught during argument parsing\" << std::endl;\r\n\t\treturn(1);\r\n\t}\r\n\t\r\n\tif (vm.count (\"help\") || argc < 2) {\r\n\t\tstd::cout << \"Usage: ray_solver [OPTION]... \" << underline(\"src.x\") << ' ' << underline(\"src.y\") << ' ' << underline(\"src.z\") << ' '\r\n\t\t<< underline(\"trg.x\") << ' ' << underline(\"trg.y\") << ' ' << underline(\"trg.z\") << std::endl;\r\n\t\tstd::cout << desc << std::endl;\r\n\t\tstd::cout << \"Angles are measured in radians from the downward vertical\" << std::endl;\r\n\t\tstd::cout << \"The reported attenuation includes the effects of the ice attenuation model and reflections.\" << std::endl;\r\n\t\tstd::cout << \"The (electric field) amplitude value reported combines the attenuation with the divergence of rays.\" << std::endl;\r\n\t\treturn(0);\r\n\t}\r\n\tif(vm.count(\"quiet\"))\r\n\t   showLabels=false;\r\n\tif(vm.count(\"show_paths\")){\r\n\t\tdumpPaths=true;\r\n\t\tshowLabels=false;\r\n\t}\r\n\tif(refractionName==\"exponential\")\r\n\t\trefractionModel=boost::shared_ptr<exponentialRefractiveIndex>(new exponentialRefractiveIndex(ns,nd,nc));\r\n\t\t//refractionModel=boost::make_shared<exponentialRefractiveIndex>(ns,nd,nc);\r\n\telse if(refractionName==\"inverse_exponential\")\r\n\t\trefractionModel=boost::shared_ptr<inverseExponentialRefractiveIndex>(new inverseExponentialRefractiveIndex(ns,nd,nc));\r\n\t\t//refractionModel=boost::make_shared<inverseExponentialRefractiveIndex>(ns,nd,nc);\r\n\telse if(refractionName==\"quadratic\")\r\n\t\trefractionModel=boost::shared_ptr<quadraticRefractiveIndex>(new quadraticRefractiveIndex(ns,nd,nc));\r\n\t\t//refractionModel=boost::make_shared<quadraticRefractiveIndex>(ns,nd,nc);\r\n\telse if(refractionName==\"todor_linear\")\r\n\t\trefractionModel=boost::shared_ptr<todorLinearRefractiveIndex>(new todorLinearRefractiveIndex(ns,nd));\r\n\t\t//refractionModel=boost::make_shared<todorLinearRefractiveIndex>(ns,nd);\r\n\telse if(refractionName==\"todor_chi\")\r\n\t\trefractionModel=boost::shared_ptr<todorChiRefractiveIndex>(new todorChiRefractiveIndex(ns,nd));\r\n\t\t//refractionModel=boost::make_shared<todorChiRefractiveIndex>(ns,nd);\r\n\telse if(refractionName==\"todor_LL\")\r\n\t\trefractionModel=boost::shared_ptr<todorLLRefractiveIndex>(new todorLLRefractiveIndex(ns,nd));\r\n\t\t//refractionModel=boost::make_shared<todorLLRefractiveIndex>(ns,nd);\r\n\telse{\r\n\t\tstd::cerr << \"Unrecognized refraction model name '\" << refractionName << \"'\" << std::endl;\r\n\t\treturn(1);\r\n\t}\r\n\tif(attenuationName==\"besson\")\r\n\t\tattenuationModel=boost::shared_ptr<basicAttenuationModel>(new basicAttenuationModel);\r\n\t\t//attenuationModel=boost::make_shared<basicAttenuationModel>();\r\n\telse if(attenuationName==\"negligible\")\r\n\t\tattenuationModel=boost::shared_ptr<negligibleAttenuationModel>(new negligibleAttenuationModel);\r\n\t\t//attenuationModel=boost::make_shared<negligibleAttenuationModel>();\r\n\telse{\r\n\t\tstd::cerr << \"Unrecognized attenuation model name '\" << attenuationName << \"'\" << std::endl;\r\n\t\treturn(1);\r\n\t}\r\n\t\r\n\tunsigned short refl = RayTrace::NoReflection;\r\n\tif(surface_reflect)\r\n\t\trefl|=RayTrace::SurfaceReflection;\r\n\tif(bedrock_reflect)\r\n\t\trefl|=RayTrace::BedrockReflection;\r\n\t\r\n\tsrc.SetX(src_x);\r\n\tsrc.SetY(src_y);\r\n\tsrc.SetZ(src_z);\r\n\ttrg.SetX(trg_x);\r\n\ttrg.SetY(trg_y);\r\n\ttrg.SetZ(trg_z);\r\n\r\n\tstd::vector<RayTrace::TraceRecord> paths;\r\n\t\r\n\tRayTrace::TraceFinder tf(refractionModel,attenuationModel);\r\n\t\r\n\tpaths=tf.findPaths(src,trg,frequency/1.0e3,polarization,refl,requiredAccuracy);\r\n\tif(showLabels){\r\n\t\tif(!paths.empty()){\r\n\t\t\tstd::cout << std::fixed \r\n\t\t\t<< \"path length (m) \"\r\n\t\t\t<< \"path time (ns) \"\r\n\t\t\t<< \"launch angle \"\r\n\t\t\t<< \"recipt angle \"\r\n\t\t\t<< \"reflect angle \"\r\n\t\t\t<< \"miss dist. \"\r\n\t\t\t<< \"attenuation \"\r\n\t\t\t<< \"amplitude\"\r\n\t\t\t<< std::endl;\r\n\t\t}\r\n\t\telse\r\n\t\t\tstd::cout << \"No solutions\" << std::endl;\r\n\t}\r\n\tif(!dumpPaths){\r\n\t\tfor(std::vector<RayTrace::TraceRecord>::const_iterator it=paths.begin(); it!=paths.end(); ++it){\r\n\t\t\tdouble signal = tf.signalStrength(*it,src,trg,refl);\r\n\t\t\tstd::cout << std::left << std::fixed \r\n\t\t\t<< std::setprecision(2) << std::setw(15) << it->pathLen << ' '\r\n\t\t\t<< std::setprecision(2) << std::setw(14) << 1e9*it->pathTime << ' '\r\n\t\t\t<< std::setprecision(4) << std::setw(12) << it->launchAngle << ' '\r\n\t\t\t<< std::setprecision(4) << std::setw(12) << it->receiptAngle << ' '\r\n\t\t\t<< std::setprecision(3) << std::setw(13) << it->reflectionAngle << ' '\r\n\t\t\t<< std::setprecision(2) << std::setw(10) << it->miss << ' ' \r\n\t\t\t<< std::scientific << std::setprecision(4) << std::setw(11) << it->attenuation << ' '\r\n\t\t\t//amplitude calculation, ignoring frequency response at both ends, angular response of receiver\r\n\t\t\t<< std::setw(10) << (it->attenuation*signal)\r\n\t\t\t<< std::endl;\r\n\t\t}\r\n\t}\r\n\telse{ //do write out path data\r\n\t\tpathPrinter<RayTrace::minimalRayPosition> print;\r\n\t\tfor(std::vector<RayTrace::TraceRecord>::const_iterator it=paths.begin(); it!=paths.end(); ++it){\r\n\t\t\ttf.doTrace<RayTrace::minimalRayPosition>(src_z, it->launchAngle, RayTrace::rayTargetRecord(trg_z,sqrt((trg_x-src_x)*(trg_x-src_x)+(trg_y-src_y)*(trg_y-src_y))), refl, 0.0, 0.0, &print);\r\n\t\t\tstd::cout << \"\\n\\n\";\r\n\t\t}\r\n\t}\r\n\treturn(0);\r\n}\r\n", "meta": {"hexsha": "ba9ccad684ea815f097b2fc011cc38dea35e1c0e", "size": 9217, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ray_solver.cpp", "max_stars_repo_name": "shrishabh/phasedArray", "max_stars_repo_head_hexsha": "bbcf1edfc1098499b4ba34c0a41b9d863298c0ff", "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": "ray_solver.cpp", "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": "ray_solver.cpp", "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": 46.7868020305, "max_line_length": 192, "alphanum_fraction": 0.7009873061, "num_tokens": 2543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2583117173586231}}
{"text": "#if HAVE_CONFIG_H\n# include <config.h>\n#endif\n\n\n#include <boost/bind.hpp>\nusing boost::cref;\n\n\n#include \"Cosmology.h\"\n#include \"PowerSpectrum.h\"\n#include \"Quadrature.h\"\n#include \"BSPT.h\"\n#include \"BSPTN.h\"\n#include \"SPT.h\"\n#include \"RegPT.h\"\n\n#include \"Spline.h\"\n#include \"SpecialFunctions.h\"\n#include \"LinearPS.h\"\n#include \"CMBc.h\"\n\n\n#include <cerrno>\n#include <cstdio>\n#include <cstdlib>\n#include <sys/stat.h>\n#include <math.h>       /* pow */\n#include <boost/math/tools/roots.hpp>\n#include <random>\n\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_deriv.h>\n\n\n// bottom limit of comoving distance integral\nconst double xim = 10.;\n\nCMBc::CMBc(const Cosmology& C_, const PowerSpectrum& P_L_, real epsrel_)\n: C(C_), P_L(P_L_)\n{\n    epsrel = epsrel_;\n}\n\n//////////////////////////////////////////\n /* Functions used in initialisation */\n//////////////////////////////////////////\n\n// Hubble function\ndouble HAc(double omega0, double z){\n\tdouble omegaL= 1.-omega0;\n\treturn  1./sqrt(omega0*pow(1.+z,3)+omegaL);}\n\n// Functions for GM or SC formula\n// neff(k)\n  static double myfuncnw(double k,void * params){\n    (void)(params);\n    return log(neffnw(k));\n  }\n\n  static double myfuncehu(double k,void * params){\n    (void)(params);\n    return log(neffehu(k));\n  }\n\n  static double myfunclin(double k,void * params){\n    (void)(params);\n    return log(mylinearps(k));\n  }\n\nstatic double myneff(double k){\n  gsl_function F;\n  double result, abserr;\n    F.params = 0;\n    F.function = &myfuncnw;\n    gsl_deriv_central(&F, k, 1e-6, &result, &abserr);\nreturn k*result;\n}\n\n\n// Find K_nl\n  double myknls(const PowerSpectrum& P_L)\n  {\n      std::mt19937 gen(2);\n       const double lower_bound =  1e-4;\n       const double upper_bound =  1000.;\n      std::uniform_real_distribution<> dis(lower_bound, upper_bound);\n\n      double pos_pt = dis(gen);\n      double neg_pt = dis(gen);\n\n      while ( (pow2(D_spt/dnorm_spt)*P_L(pos_pt)*pow3(pos_pt)/2./M_PI/M_PI  - 1.) < 0.){\n          pos_pt = dis(gen);}\n\n      while ( (pow2(D_spt/dnorm_spt)*P_L(neg_pt)*pow3(neg_pt)/2./M_PI/M_PI- 1.) > 0.){\n          neg_pt = dis(gen);}\n\n       const double about_zero_mag = 1e-5;\n      for (;;)\n      {\n          double mid_pt = (pos_pt + neg_pt)/2.0;\n          double f_mid_pt =  pow2(D_spt/dnorm_spt)*P_L(mid_pt)*pow3(mid_pt)/2./M_PI/M_PI -1.;\n\n          if (fabs(f_mid_pt)  < about_zero_mag){\n              return mid_pt;\n                }\n\n          if (f_mid_pt >= 0.){\n              pos_pt = mid_pt;}\n          else{\n              neg_pt = mid_pt;}\n\n      }\n  }\n\n// regpt damp term for post born prediction\nstatic real regpt_exp(const PowerSpectrum& P_l, double q){\n    return  P_l(q)/(6.*pow2(M_PI));\n  }\n\n// Calculate sigma_8 at some redshift\nstatic double sigma8int(const PowerSpectrum& P_L, double k){\n  return pow2(3.*((sin(k*8.) - k*8.*cos(k*8.))/pow2(k*8.))/k/8.) * pow2(k) * pow2(D_spt/dnorm_spt) * P_L(k)/2./M_PI/M_PI;\n}\n\nstatic double mysigma8(const PowerSpectrum& P_L){\n  return sqrt(Integrate(bind(sigma8int,cref(P_L),_1),0.0001,30.,1e-4));\n}\n\n// Spline function z->comoving distance\nSpline zofc;\n// Spline linear growth factor + F2_dgp\nSpline Dlin, Dlingr, F2DGP;\n// Splines for HALOFIT\nSpline phpars0,phpars1,phpars2,phpars3,phpars4,phpars5,phpars6,phpars7,phpars8,phpars9,phpars10,phpars11,phpars12;\n// Splines for dgp 1-loop matter power Spectrum\nSpline fdgps, cdgps, idgps, kldgps, p22spl,p13spl, damp_termcmb;\n// Comoving distance to z=1000 (~CMB)\ndouble xis;\n// comoving distance to z=40 as in TN's computation\ndouble xis40;\n\n// Splines for GM formula\nSpline myneffspl, mys8spl, myknlspl;\n\n// Initialize z(comoving_dist) and xi_star = comoving distance to CMB\n// a = 1 linear\n// a = 2 1-loop (+ initialises regpt components)\n// a = 3 Gil-Marin or Scoccimaro [+ initialises all halofit params, n_eff(k), k_nl(z) and sigma_8(z)]\n void CMBc::comdist_init(int a, double omega0, double mg1){\n  SPT spt(C, P_L, 1e-3);\n  RegPT rpt(C, P_L, 1e-3);\n  BSPT bspt(C, P_L, 1e-3);\n  IOW iow;\n\n  // initialise damping factor for regpt\n  if(a==2){\n  rpt.sigmad_init();\n    }\n\n   // initialise EHU PS and Fonseca NW\n    if(a==3){\n      bspt.mypspline(2);\n    }\n\n  double h0inv = 2997.92;\n  const double zmin = 1e-4;\n  const double zmax = 1100.;\n  const double kmin = 1e-4;\n  const double kmax = 100.;\n\n  vector<double> ztable, ktable, ctable, dtable, dgrtable, f2table;\n  // Halofit tables\n  vector<double> phtable0,phtable1,phtable2,phtable3,phtable4,phtable5,phtable6,phtable7,phtable8,phtable9,phtable10,phtable11,phtable12;\n  // 1-LOOP SPT nDGP GROWTH TABLES\n  vector<double> ftab,ctab,itab,kltab;\n  // 1-Loop k-components\n  vector<double> p13tab,p22tab, dampt;\n  // GM formula tables\n  vector<double> nefftab, knltab, sig8tab;\n\n\n  xis =  h0inv*Integrate(bind(HAc,omega0,_1),0.,zmax,1e-4);\n  xis40 = h0inv*Integrate(bind(HAc,omega0,_1),0.,40.,1e-4);\n\n  const int n1 = 1000;\n  double cval,zval,scalef,kval,sigd;\n\n  for(int i = 0; i<n1; i++ ){\n    zval = zmin*exp(i*log(zmax/zmin)/(n1-1.));\n    kval = kmin*exp(i*log(kmax/kmin)/(n1-1.));\n\n    scalef = 1./(1.+zval);\n    iow.inite(scalef,omega0,mg1,1.,1.);\n\n    cval = h0inv*Integrate(bind(HAc,omega0,_1),zmin,zval,1e-4);\n\n    ztable.push_back(zval);\n    ktable.push_back(kval);\n    ctable.push_back(cval);\n\n    dtable.push_back(D_spt/dnorm_spt);\n    dgrtable.push_back(Dl_spt/dnorm_spt);\n    f2table.push_back(F_spt/pow2(dnorm_spt));\n\n    if (a==2) {\n        p22tab.push_back(pow4(dnorm_spt/Dl_spt)*spt.P22_dd(kval));\n        p13tab.push_back(pow4(dnorm_spt/Dl_spt)*spt.P13_dd(kval));\n        sigd = pow2(kval)*Integrate<ExpSub>(bind(regpt_exp, cref(P_L), _1), kmin, kval/2., 1e-4);\n        dampt.push_back(sigd);\n    }\n\n    if (a ==3 ) {\n      spt.phinit(scalef,omega0);\n      phtable0.push_back(phpars[0]);\n      phtable1.push_back(phpars[1]);\n      phtable2.push_back(phpars[2]);\n      phtable3.push_back(phpars[3]);\n      phtable4.push_back(phpars[4]);\n      phtable5.push_back(phpars[5]);\n      phtable6.push_back(phpars[6]);\n      phtable7.push_back(phpars[7]);\n      phtable8.push_back(phpars[8]);\n      phtable9.push_back(phpars[9]);\n      phtable10.push_back(phpars[10]);\n      phtable11.push_back(phpars[11]);\n      phtable12.push_back(phpars[12]);\n\n        if (i==0) {\n          knltab.push_back(myknls(cref(P_L)));\n          }\n        else if( knltab[i-1] > 200. ){\n           knltab.push_back(knltab[i-1]);\n        }\n        else{\n           knltab.push_back(myknls(cref(P_L)));\n              }\n             printf(\"%d %e \\n\", i, knltab[i]);\n\n      sig8tab.push_back(mysigma8(cref(P_L)));\n      nefftab.push_back(myneff(kval));\n\n    }\n      }\n\n      zofc = LinearSpline(ctable,ztable);\n      Dlin = LinearSpline(ztable,dtable);\n      Dlingr = LinearSpline(ztable,dgrtable);\n      F2DGP = LinearSpline(ztable,f2table);\n\n      if (a==2) {\n        p22spl=LinearSpline(ktable,p22tab);\n        p13spl=LinearSpline(ktable,p13tab);\n        damp_termcmb = LinearSpline(ktable,dampt);\n            }\n      if (a==3) {\n        phpars0 = LinearSpline(ztable,phtable0);\n        phpars1 = LinearSpline(ztable,phtable1);\n        phpars2 = LinearSpline(ztable,phtable2);\n        phpars3 = LinearSpline(ztable,phtable3);\n        phpars4 = LinearSpline(ztable,phtable4);\n        phpars5 = LinearSpline(ztable,phtable5);\n        phpars6 = LinearSpline(ztable,phtable6);\n        phpars7 = LinearSpline(ztable,phtable7);\n        phpars8 = LinearSpline(ztable,phtable8);\n        phpars9 = LinearSpline(ztable,phtable9);\n        phpars10 = LinearSpline(ztable,phtable10);\n        phpars11 = LinearSpline(ztable,phtable11);\n        phpars12 = LinearSpline(ztable,phtable12);\n\n        myknlspl = LinearSpline(ztable,knltab);\n        mys8spl = LinearSpline(ztable,sig8tab);\n        myneffspl = LinearSpline(ktable,nefftab);\n\n      }\n}\n\n// B_LSS integrands\n// tree analytic\nstatic double btlssa_integrand(const Cosmology& C, const PowerSpectrum& P_L, int a, double params[], double l1, double l2, double x, double xi ){\n   BSPT bspt(C, P_L, 1e-4);\n   IOW iow;\n   double bis, kernel, F2A, F2B, F2C, growth;\n   double h0 = 1./2997.92;\n   double lensingk = (xis-xi)/xi/xis;\n   double myz = zofc(xi);\n   double scalef = 1./(1.+myz);\n   double prefactor = pow3(3.*params[0]*pow2(h0)/(2.*scalef) * lensingk);\n   double k1 = l1/xi;\n   double k2 = l2/xi;\n\n   D_spt = Dlin(myz) * dnorm_spt;\n   Dl_spt = Dlin(myz) * dnorm_spt; //Dlingr(myz) * dnorm_spt;\n   F_spt = F2DGP(myz) * dnorm_spt;\n   bis = bspt.Btree(a, k1, k2, x);\n\n   return prefactor * bis * pow2(xi);\n}\n\n// 1-loop analytic\nstatic double bllssa_integrand(const Cosmology& C,const PowerSpectrum& P_L, int a, double params[], double l1, double l2, double x, double xi ){\n   BSPT bspt(C, P_L, 1e-2);\n   IOW iow;\n   double bis, kernel;\n   double h0 = 1./2997.92;\n   double lensingk = (xis-xi)/xi/xis;\n   double myz = zofc(xi);\n   double scalef = 1./(1.+myz);\n   double prefactor = pow3(3.*params[0]*pow2(h0)/(2.*scalef) * lensingk);\n   switch (a) {\n     case 1:\n      Dl_spt = Dlin(myz) * dnorm_spt;\n      break;\n      case 2:\n   iow.inite2(scalef,params[0],params[1],params[2],params[3]);\n      break;\n }\n   double k1 = l1/xi;\n   double k2 = l2/xi;\n   bis = bspt.Bloop(a, k1, k2, x);\n   return prefactor * bis * pow2(xi);\n}\n\n// Gil-Marin formula\nstatic double bgmlssa_integrand(const Cosmology& C,const PowerSpectrum& P_L,  double params[], double l1, double l2, double x, double xi ){\n   SPT spt(C, P_L, 1e-3);\n   double vars[6],F2A,F2B,F2C,p1,p2,p3;\n\n   double h0 = 1./2997.92;\n   double lensingk = (xis-xi)/xi/xis;\n   double myz = zofc(xi);\n   double scalef = 1./(1.+myz);\n   double prefactor = pow3(3.*params[0]*pow2(h0)/(2.*scalef) * lensingk);\n\n\n   double k1 = l1/xi;\n   double k2 = l2/xi;\n   double k3 = sqrt(pow2(k1) + pow2(k2) + 2.*k2*k1*x);\n\n\n    D_spt =  Dlin(myz) * dnorm_spt;\n    F_spt =  F2DGP(myz) * pow2(dnorm_spt);\n    vars[0] = mys8spl(myz);\n    vars[1] = myknlspl(myz);\n    vars[2] = 1.;\n    vars[3] = (1.- F_spt * 7./2./pow2(D_spt));\n\n     vars[4] = myneffspl(k1);\n     vars[5] = myneffspl(k2);\n     F2A = F2fit(vars,k1,k2,x);\n\n     vars[4] = myneffspl(k1);\n     vars[5] = myneffspl(k3);\n     F2B = F2fit(vars,k1,k3,-(k2*x+k1)/k3);\n\n     vars[4] = myneffspl(k2);\n     vars[5] = myneffspl(k3);\n     F2C = F2fit(vars,k2,k3,-(k1*x+k2)/k3);\n\n    phpars[0] = phpars0(myz);\n    phpars[1] = phpars1(myz);\n    phpars[2] = phpars2(myz);\n    phpars[3] = phpars3(myz);\n    phpars[4] = phpars4(myz);\n    phpars[5] = phpars5(myz);\n    phpars[6] = phpars6(myz);\n    phpars[7] = phpars7(myz);\n    phpars[8] = phpars8(myz);\n    phpars[9] = phpars9(myz);\n    phpars[10] = phpars10(myz);\n    phpars[11] = phpars11(myz);\n    phpars[12] = phpars12(myz);\n\n     if (k1>100.) {\n      p1 = spt.PHALO(100.);\n     }\n     else{\n     p1 = spt.PHALO(k1);\n        }\n        if (k2>100.) {\n          p2 = spt.PHALO(100.);\n        }\n        else{\n        p2 = spt.PHALO(k2);\n           }\n\n           if (k3>100.) {\n              p3 = spt.PHALO(100.);\n           }\n           else{\n           p3 = spt.PHALO(k3);\n              }\n\n    double bis =2.*(p1*p2*F2A + p3*p1*F2B + p2*p3*F2C);\n\n    return prefactor * bis * pow2(xi);\n}\n\n\n// SC fitting formula\nstatic double bsclssa_integrand(const Cosmology& C,const PowerSpectrum& P_L,  double params[], double l1, double l2, double x, double xi ){\n   SPT spt(C, P_L, 1e-3);\n   double vars[6],F2A,F2B,F2C,p1,p2,p3;\n\n   double h0 = 1./2997.92;\n   double lensingk = (xis-xi)/xi/xis;\n   double myz = zofc(xi);\n   double scalef = 1./(1.+myz);\n   double prefactor = pow3(3.*params[0]*pow2(h0)/(2.*scalef) * lensingk);\n\n\n   double k1 = l1/xi;\n   double k2 = l2/xi;\n   double k3 = sqrt(pow2(k1) + pow2(k2) + 2.*k2*k1*x);\n\n    D_spt =  Dlin(myz) * dnorm_spt;\n    F_spt =  F2DGP(myz) * pow2(dnorm_spt);\n    vars[0] = mys8spl(myz);\n    vars[1] = myknlspl(myz);\n    vars[2] = 1.;\n    vars[3] = (1.- F_spt * 7./2./pow2(D_spt));\n\n     vars[4] = myneffspl(k1);\n     vars[5] = myneffspl(k2);\n     F2A = F2fitsc(vars,k1,k2,x);\n\n     vars[4] = myneffspl(k1);\n     vars[5] = myneffspl(k3);\n     F2B = F2fitsc(vars,k1,k3,-(k2*x+k1)/k3);\n\n     vars[4] = myneffspl(k2);\n     vars[5] = myneffspl(k3);\n     F2C = F2fitsc(vars,k2,k3,-(k1*x+k2)/k3);\n\n    phpars[0] = phpars0(myz);\n    phpars[1] = phpars1(myz);\n    phpars[2] = phpars2(myz);\n    phpars[3] = phpars3(myz);\n    phpars[4] = phpars4(myz);\n    phpars[5] = phpars5(myz);\n    phpars[6] = phpars6(myz);\n    phpars[7] = phpars7(myz);\n    phpars[8] = phpars8(myz);\n    phpars[9] = phpars9(myz);\n    phpars[10] = phpars10(myz);\n    phpars[11] = phpars11(myz);\n    phpars[12] = phpars12(myz);\n\n     if (k1>100.) {\n      p1 = spt.PHALO(100.);\n     }\n     else{\n     p1 = spt.PHALO(k1);\n        }\n        if (k2>100.) {\n          p2 = spt.PHALO(100.);\n        }\n        else{\n        p2 = spt.PHALO(k2);\n           }\n\n           if (k3>100.) {\n              p3 = spt.PHALO(100.);\n           }\n           else{\n           p3 = spt.PHALO(k3);\n              }\n\n    double bis =2.*(p1*p2*F2A + p3*p1*F2B + p2*p3*F2C);\n\n    return prefactor * bis * pow2(xi);\n}\n\n// Numerical tree level\nstatic double btnlssa_integrand(const Cosmology& C, const PowerSpectrum& P_L, int a, double params[], double l1, double l2, double x, double xi ){\n   BSPT bspt(C, P_L, 1e-3);\n   IOW iow;\n   double bis, kernel, F2A, F2B, F2C, growth;\n   double h0 = 1./2997.92;\n   double lensingk = (xis-xi)/xi/xis;\n   double myz = zofc(xi);\n   double scalef = 1./(1.+myz);\n   double prefactor = pow3(3.*params[0]*pow2(h0)/(2.*scalef) * lensingk);\n   double k1 = l1/xi;\n   double k2 = l2/xi;\n   double k3 = sqrt(pow2(k1) + pow2(k2) + 2.*k2*k1*x);\n\n   double vars[6];\n   vars[0] = params[0];\n   vars[1] = params[1];\n   vars[2] = params[2];\n   vars[3] = params[3];\n   vars[4] = scalef;\n   vars[5] = 1.*a; // doubling as choice of dgp (1), ide (2) , fr(3)\n\n   bis = bspt.Btreen(vars, k1, k2, x);\n   return prefactor * bis * pow2(xi);\n}\n\n\n// numerical 1-loop level\nstatic double blnlssa_integrand(const Cosmology& C, const PowerSpectrum& P_L, int a, double params[], double l1, double l2, double x, double xi ){\n   BSPT bspt(C, P_L, 1e-4);\n   IOW iow;\n   double bis, kernel, F2A, F2B, F2C, growth;\n   double h0 = 1./2997.92;\n   double lensingk = (xis-xi)/xi/xis;\n   double myz = zofc(xi);\n   double scalef = 1./(1.+myz);\n   double prefactor = pow3(3.*params[0]*pow2(h0)/(2.*scalef) * lensingk);\n   double k1 = l1/xi;\n   double k2 = l2/xi;\n   double vars[9];\n   vars[0] = params[0];\n   vars[1] = params[1];\n   vars[2] = params[2];\n   vars[3] = params[3];\n   vars[4] = scalef;\n   vars[5] = 1.*a; // doubling as choice of dgp (1), ide (2) , fr(3)\n   vars[6] = params[4];\n   vars[7] = params[5];\n   vars[8] = params[6];\n   bis = bspt.Bloopn(vars, k1, k2, x);\n   return prefactor * bis * pow2(xi);\n}\n\n\n// POST BORN STUFF\n\n// C_l(xi1, xi2) integrands\n// linear\nstatic double cl_integrandt(const Cosmology& C, const PowerSpectrum& P_L, double omega0, double l2, double xi1, double xi2){\n  double h0 = 1./2997.92;\n  double k2 = l2/xi2;\n  double lenker1 = (xi1 - xi2)/xi2/xi1 ;\n  double lenker2 = (xis - xi2)/xi2/xis;\n  double weylpot2 =  pow2(Dlin(zofc(xi2))) * P_L(k2) * pow2(3. * omega0 * pow2(h0) * (1.+zofc(xi2)) / 2. / pow2(k2));\n\n  return  lenker1 * lenker2 / pow2(xi2) * weylpot2 ;\n}\n\n// 1-loop (regpt)\nstatic double cl_integrandl(const Cosmology& C, const PowerSpectrum& P_L, double omega0, double l2, double xi1, double xi2){\n  double D0, D0sqr, D2, expon, p13, pl,  ploop,ploopr,h0,k2,weylpot2,lenker1,lenker2;\n   D0 =  pow2(Dlin(zofc(xi2)));\n   h0 = 1./2997.92;\n   k2 = l2/xi2;\n\n  expon = D0 * damp_termcmb(k2) ;\n  if(expon >= 80.){\n   return 0.;\n  }\n  else{\n\n   lenker1 = (xi1 - xi2)/xi2/xi1;\n   lenker2 = (xis - xi2)/xi2/xis;\n\n  D0sqr = pow2(D0);\n  pl = D0 * P_L(k2);\n  p13 =  D0sqr*p13spl(k2);\n  ploop = pl+ D0sqr*p22spl(k2) + p13;\n  D2 = pow2(p13/pl/2.)*D0;\n\n  ploopr = exp(-expon)*(ploop + expon/2.*(2.*pl + p13) + pow2(expon)/4.*pl + P_L(k2)*D2);\n\n  weylpot2 =   ploopr * pow2(3. * omega0 * pow2(h0) * (1.+zofc(xi2)) / 2. / pow2(k2));\n\n  return  lenker1 * lenker2 / pow2(xi2) * weylpot2 ;\n}\n}\n\n\n// 1-loop (spt)\nstatic double cl_integrandspt(const Cosmology& C, const PowerSpectrum& P_L, double omega0, double l2, double xi1, double xi2){\n  double D0, D0sqr, D2, expon, p13, pl,  ploop,ploopr,h0,k2,weylpot2,lenker1,lenker2;\n   D0 =  pow2(Dlin(zofc(xi2)));\n   h0 = 1./2997.92;\n   k2 = l2/xi2;\n   lenker1 = (xi1 - xi2)/xi2/xi1;\n   lenker2 = (xis - xi2)/xi2/xis;\n\n  D0sqr = pow2(D0);\n  pl = D0 * P_L(k2);\n  p13 =  D0sqr*p13spl(k2);\n  ploop = pl+ D0sqr*p22spl(k2) + p13;\n\n  weylpot2 =   ploop * pow2(3. * omega0 * pow2(h0) * (1.+zofc(xi2)) / 2. / pow2(k2));\n\n  return  lenker1 * lenker2 / pow2(xi2) * weylpot2 ;\n}\n\n\n\n// halofit\nstatic double cl_integrandh(const Cosmology& C, const PowerSpectrum& P_L, double omega0, double l2, double xi1, double xi2){\n  SPT spt(C, P_L, 1e-3);\n\n  double h0 = 1./2997.92;\n  double k2 = l2/xi2;\n  double lenker1 = (xi1 - xi2)/xi2/xi1 ;\n  double lenker2 = (xis - xi2)/xi2/xis;\n  double myz = zofc(xi2);\n\n    D_spt =  Dlin(myz) * dnorm_spt;\n    phpars[0] = phpars0(myz);\n    phpars[1] = phpars1(myz);\n    phpars[2] = phpars2(myz);\n    phpars[3] = phpars3(myz);\n    phpars[4] = phpars4(myz);\n    phpars[5] = phpars5(myz);\n    phpars[6] = phpars6(myz);\n    phpars[7] = phpars7(myz);\n    phpars[8] = phpars8(myz);\n    phpars[9] = phpars9(myz);\n    phpars[10] = phpars10(myz);\n    phpars[11] = phpars11(myz);\n    phpars[12] = phpars12(myz);\n\n  double weylpot2 =   spt.PHALO(k2) * pow2(3. * omega0 * pow2(h0) * (1.+zofc(xi2)) / 2. / pow2(k2));\n\n  return  lenker1 * lenker2 / pow2(xi2) * weylpot2 ;\n}\n\n\n// M(l1,l2) function integrands\n// tree level\nstatic double mfunc_integrandt(const Cosmology& C, const PowerSpectrum& P_L, double omega0, double l1, double l2, double xi1){\n  double h0 = 1./2997.92;\n  double mycl = pow4(l2)*Integrate(bind(cl_integrandt,cref(C),cref(P_L), omega0, l2, xi1, _1), xim,xi1,1e-4);  // C_l2 (xi1, xis)\n  double k1 = l1/xi1;\n  double weylpot1 =  pow2(Dlin(zofc(xi1))) * P_L(k1) * pow2(3. * omega0 * pow2(h0) * (1.+zofc(xi1)) / 2. / pow2(k1));\n\n  return pow2((xis - xi1)/pow2(xi1)/xis) * weylpot1 * mycl;\n}\n\n// 1-loop level (RegPT implementation)\nstatic double mfunc_integrandl(const Cosmology& C, const PowerSpectrum& P_L, double omega0, double l1, double l2, double xi1){\n  double D0,D0sqr, D2, expon, p13, pl,  ploop,ploopr,h0,mycl,k1,weylpot1;\n  h0 = 1./2997.92;\n  D0 =  pow2(Dlin(zofc(xi1)));\n  k1 = l1/xi1;\n  expon = D0 * damp_termcmb(k1) ;\n  if(expon >= 80. ){\n   return 0.;\n  }\n  else{\n     mycl = pow4(l2) * Integrate(bind(cl_integrandl, cref(C), cref(P_L), omega0, l2, xi1, _1), xim,xi1,1e-2);   // C_l2 (xi1, xis)\n     D0sqr = pow2(D0);\n     pl = D0 * P_L(k1);\n     p13 =  D0sqr*p13spl(k1);\n     ploop = pl+ D0sqr*p22spl(k1) + p13;\n     D2 = pow2(p13/pl/2.)*D0;\n\n     ploopr = exp(-expon)*(ploop + expon/2.*(2.*pl + p13) + pow2(expon)/4.*pl + P_L(k1)*D2);\n\n     weylpot1 =  ploopr * pow2(3. * omega0 * pow2(h0) * (1.+zofc(xi1)) / 2. / pow2(k1));\n\n  return pow2( (xis - xi1)/pow2(xi1)/xis ) * weylpot1 * mycl;\n}\n}\n\n// pure spt\nstatic double mfunc_integrandspt(const Cosmology& C, const PowerSpectrum& P_L, double omega0, double l1, double l2, double xi1){\n  double D0,D0sqr, D2, expon, p13, pl,  ploop,ploopr,h0,mycl,k1,weylpot1;\n  h0 = 1./2997.92;\n  D0 =  pow2(Dlin(zofc(xi1)));\n  k1 = l1/xi1;\n\n     mycl = pow4(l2) * Integrate(bind(cl_integrandspt, cref(C), cref(P_L), omega0, l2, xi1, _1), xim,xi1,1e-2);   // C_l2 (xi1, xis)\n     D0sqr = pow2(D0);\n     pl = D0 * P_L(k1);\n     p13 =  D0sqr*p13spl(k1);\n     ploop = pl+ D0sqr*p22spl(k1) + p13;\n\n     weylpot1 =  ploop * pow2(3. * omega0 * pow2(h0) * (1.+zofc(xi1)) / 2. / pow2(k1));\n\n  return pow2( (xis - xi1)/pow2(xi1)/xis ) * weylpot1 * mycl;\n}\n\n\n\n// halofit\nstatic double mfunc_integrandh(const Cosmology& C, const PowerSpectrum& P_L, double omega0, double l1, double l2, double xi1){\n  SPT spt(C, P_L, 1e-2);\n\n  double h0 = 1./2997.92;\n  double mycl = pow4(l2)*Integrate(bind(cl_integrandh,cref(C), cref(P_L), omega0, l2, xi1, _1), xim,xi1,1e-4);   // C_l2 (xi1, xis)\n  double k1 = l1/xi1;\n  double myz = zofc(xi1);\n\n    D_spt =  Dlin(myz) * dnorm_spt;\n    phpars[0] = phpars0(myz);\n    phpars[1] = phpars1(myz);\n    phpars[2] = phpars2(myz);\n    phpars[3] = phpars3(myz);\n    phpars[4] = phpars4(myz);\n    phpars[5] = phpars5(myz);\n    phpars[6] = phpars6(myz);\n    phpars[7] = phpars7(myz);\n    phpars[8] = phpars8(myz);\n    phpars[9] = phpars9(myz);\n    phpars[10] = phpars10(myz);\n    phpars[11] = phpars11(myz);\n    phpars[12] = phpars12(myz);\n\n  double weylpot1 =  spt.PHALO(k1) * pow2(3. * omega0 * pow2(h0) * (1.+zofc(xi1)) / 2. / pow2(k1));\n\n  return pow2( (xis - xi1)/pow2(xi1)/xis ) * weylpot1 * mycl;\n}\n\n// M(l1,l2) as in Eq.4.5 of 1605.05662\nstatic double Mfunc(int a, const Cosmology& C, const PowerSpectrum& P_L, double omega0, double l1, double l2){\n    switch (a) {\n      case 1:\n      return pow4(l1) * Integrate(bind(mfunc_integrandt,cref(C),cref(P_L), omega0, l1, l2, _1), xim,xis40,1e-3); // tree level\n      break;\n      case 2:\n      return pow4(l1) * Integrate(bind(mfunc_integrandl,cref(C),cref(P_L), omega0, l1, l2, _1), xim,xis40,1e-3); // 1-loop (regpt)\n      break;\n      case 3:\n      return pow4(l1) * Integrate(bind(mfunc_integrandh,cref(C),cref(P_L), omega0, l1, l2, _1), xim,xis,1e-3); // halofit\n      break;\n      case 4:\n      return pow4(l1) * Integrate(bind(mfunc_integrandspt,cref(C),cref(P_L), omega0, l1, l2, _1), xim,xis40,1e-3); // 1-loop (spt)\n      break;\n}}\n\n// B_LSS contribution\n// a chooses LCDM (1) or nDGP/MG analytic (2) (tree or 1-loop only) or 3(IDE) or 4 [f(R)] (only numerical)\n// b chooses tree analytic (1) or 1-loop analytic (2) or Gil-Marin (3) or Scoccimaro (4) or tree numerical (5) or 1-loop numerical (6)\n// params[0] = omega0, params[1]=mg1, params[2]=mg2, params[3] =mg3\n\n// LSS bispectrum\ndouble CMBc::BLSS(int a, int b,  double params[], double l1, double l2, double x) const{\nswitch (b) {\n  case 1:\n   return   Integrate(bind(btlssa_integrand,cref(C),cref(P_L), a, params, l1, l2, x, _1),xim,xis,epsrel); // tree level EdS\n   break;\n  case 2:\n    return  Integrate(bind(bllssa_integrand,cref(C),cref(P_L),a, params, l1, l2, x, _1),xim,xis40,epsrel); // 1-loop EdS\n    break;\n  case 3:\n    return  Integrate(bind(bgmlssa_integrand,cref(C),cref(P_L), params, l1, l2, x, _1),xim,xis,epsrel); // Gil-Marin fit\n    break;\n  case 4:\n    return  Integrate(bind(bsclssa_integrand,cref(C),cref(P_L), params, l1, l2, x, _1),xim,xis40,epsrel); // Scoccimaro fit\n    break;\n  case 5:\n  if (a==1) {\n    return  Integrate(bind(btlssa_integrand,cref(C),cref(P_L), a, params, l1, l2, x, _1),xim,xis40,epsrel); // For GR we use EdS\n    }\n  else{\n    return  Integrate(bind(btnlssa_integrand,cref(C),cref(P_L),a-1, params, l1, l2, x, _1),xim,xis40,epsrel); // tree level numerical\n  }\n  break;\n  case 6:\n  if (a==1) {\n    return  Integrate(bind(bllssa_integrand,cref(C),cref(P_L), a, params, l1, l2, x, _1),xim,xis40,epsrel);  // For GR we use EdS\n    }\n  else{\n    return  Integrate(bind(blnlssa_integrand,cref(C),cref(P_L),a-1, params, l1, l2, x, _1),xim,xis40,epsrel); // 1-loop level numerical\n  }\n    break;\n  }\n}\n\n// BLSS lensing kernel\ndouble CMBc::BLSS_kernel(int a, int b, double params[], double l1, double l2, double x, double xi) const{\n  switch (b) {\n    case 1:\n     return   btlssa_integrand(cref(C),cref(P_L), a, params, l1, l2, x, xi); // tree level EdS\n     break;\n    case 2:\n      return   bllssa_integrand(cref(C),cref(P_L), a, params, l1, l2, x, xi); // 1-loop EdS\n      break;\n    case 3:\n      return   bgmlssa_integrand(cref(C),cref(P_L), params, l1, l2, x, xi); // Gil-Marin fit\n      break;\n    }\n}\n\n\n// post born correction\ndouble CMBc::BPB(int a, double omega0, double l1, double l2, double x) const{\n   double l1sqr = pow2(l1);\n   double l2sqr = pow2(l2);\n   double l3 = sqrt(l1sqr + l2sqr + 2.*l1*l2*x);\n   double l3sqr = pow2(l3);\n   double l1l3 = -(l1sqr + l1*l2*x);\n   double l2l3 = -(l2sqr + l1*l2*x);\n   return   2.*x/l1/l2 * (l1l3 * Mfunc(a, cref(C), cref(P_L), omega0, l1,l2) + l2l3 * Mfunc(a,cref(C), cref(P_L), omega0, l2,l1))\n           +2.*l2l3/l2sqr/l3sqr * (l2*l1*x * Mfunc(a,cref(C), cref(P_L), omega0, l2,l3) + l1l3 * Mfunc(a,cref(C), cref(P_L), omega0, l3,l2))\n           +2.*l1l3/l3sqr/l1sqr * (l2l3 * Mfunc(a,cref(C), cref(P_L), omega0, l3,l1) + l2*l1*x * Mfunc(a,cref(C), cref(P_L), omega0, l1,l3));\n    }\n\n\n// CMB lensing spectrum\n// nDGP or LCDM are chosen via comdist_init(int a, double omega0, double mg1) function (Only linear growth dependence - 1-loop uses UsA + EdS)\ndouble CMBc::CMBla(int a, int b, double params[],double l1, double l2, double x) const{\n  double l1sqr = pow2(l1);\n  double l2sqr = pow2(l2);\n  double l3 = sqrt(l1sqr + l2sqr + 2.*l1*l2*x);\n  int lw1,lw2,lw3;\n  lw1 = (int)l1;\n  lw2 = (int)l2;\n  lw3 = (int)round(l3);\n  return  wigner3j(lw1, lw2, lw3) * sqrt((2.*l1+1.)*(2.*l2+1.)*(2.*l3+1.)/4./M_PI) * (BLSS(a,b, params, l1,l2,x) + BPB(a, params[0], l1,l2,x));\n}\n", "meta": {"hexsha": "c81d93c2462503727513a9730e0792bba44c602c", "size": 24890, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "reactions/src/extra_libraries/CMBc.cpp", "max_stars_repo_name": "PedroCarrilho/ReACT", "max_stars_repo_head_hexsha": "507866e9462ecf10c298fcd3e2c81249f32e7d50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-07-07T11:34:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T12:48:05.000Z", "max_issues_repo_path": "reactions/src/extra_libraries/CMBc.cpp", "max_issues_repo_name": "PedroCarrilho/ReACT", "max_issues_repo_head_hexsha": "507866e9462ecf10c298fcd3e2c81249f32e7d50", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-05-29T16:26:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T08:59:52.000Z", "max_forks_repo_path": "reactions/src/extra_libraries/CMBc.cpp", "max_forks_repo_name": "PedroCarrilho/ReACT", "max_forks_repo_head_hexsha": "507866e9462ecf10c298fcd3e2c81249f32e7d50", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T15:35:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T15:35:28.000Z", "avg_line_length": 30.7283950617, "max_line_length": 146, "alphanum_fraction": 0.609039775, "num_tokens": 9732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819591324418, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2583117113752353}}
{"text": "//\n//  Scheduler.cpp\n//  \n//\n//  Created by Ben Lengerich on 1/27/16.\n//\n//\n\n#include \"Scheduler.hpp\"\n\n#include <Eigen/Dense>\n#include <stdexcept>\n#include <iostream>\n#include <memory>\n#include <mutex>\n#include <node.h>\n#include <stdio.h>\n#include <thread>\n#include <typeinfo>\n#include <unistd.h>\n#include <unordered_map>\n#include <uv.h>\n\n#ifdef BAZEL\n#include \"Algorithms/Algorithm.hpp\"\n#include \"Algorithms/AlgorithmOptions.hpp\"\n#include \"Algorithms/BrentSearch.hpp\"\n#include \"Algorithms/GridSearch.hpp\"\n#include \"Algorithms/IterativeUpdate.hpp\"\n#include \"Algorithms/ProximalGradientDescent.hpp\"\n#include \"Algorithms/HypoTestPlaceHolder.h\"\n#include \"Models/AdaMultiLasso.hpp\"\n#include \"Models/GFlasso.h\"\n#include \"Models/lasso.hpp\"\n#include \"Models/LinearRegression.hpp\"\n#include \"Models/Model.hpp\"\n#include \"Models/ModelOptions.hpp\"\n#include \"Models/MultiPopLasso.hpp\"\n#include \"Models/TreeLasso.hpp\"\n#include \"Models/LinearMixedModel.hpp\"\n#include \"Models/SparseLMM.h\"\n#include \"Stats/FisherTest.h\"\n#include \"Stats/Chi2Test.h\"\n#include \"Stats/WaldTest.h\"\n#include \"Graph/NeighborSelection.hpp\"\n#include \"Graph/GraphicalLasso.hpp\"\n#include \"Scheduler/Job.hpp\"\n#else\n#include \"../Algorithms/Algorithm.hpp\"\n#include \"../Algorithms/AlgorithmOptions.hpp\"\n#include \"../Algorithms/BrentSearch.hpp\"\n#include \"../Algorithms/GridSearch.hpp\"\n#include \"../Algorithms/IterativeUpdate.hpp\"\n#include \"../Algorithms/ProximalGradientDescent.hpp\"\n#include \"../Algorithms/HypoTestPlaceHolder.h\"\n#include \"../Models/AdaMultiLasso.hpp\"\n#include \"../Models/GFlasso.h\"\n#include \"../Models/lasso.hpp\"\n#include \"../Models/LinearRegression.hpp\"\n#include \"../Models/Model.hpp\"\n#include \"../Models/ModelOptions.hpp\"\n#include \"../Models/MultiPopLasso.hpp\"\n#include \"../Models/LinearMixedModel.hpp\"\n#include \"../Models/SparseLMM.h\"\n#include \"../Models/TreeLasso.hpp\"\n#include \"../Stats/FisherTest.h\"\n#include \"../Stats/Chi2Test.h\"\n#include \"../Stats/WaldTest.h\"\n#include \"../Graph/NeighborSelection.hpp\"\n#include \"../Graph/GraphicalLasso.hpp\"\n#include \"../Scheduler/Job.hpp\"\n#endif\n\nusing namespace std;\n\n\n//////////////////////////////////////////\n// Constructors\n//////////////////////////////////////////\n\nScheduler::Scheduler()\n: next_algorithm_id(1)\n, next_model_id(1)\n, next_job_id(1) {\n\talgorithms_map = std::unordered_map<algorithm_id_t, shared_ptr<Algorithm>>();\n\tmodels_map = std::unordered_map<model_id_t, shared_ptr<Model>>();\n\tjobs_map = std::unordered_map<job_id_t, shared_ptr<Job_t>>();\n}\n\nScheduler& Scheduler::operator=(Scheduler const& s) {\n    return Scheduler::Instance();\n}\n\nScheduler& Scheduler::Instance() {\t\n\tstatic Scheduler s_instance;\n\treturn s_instance;\n}\n\n/////////////////////////////////////////////////////////\n// Public Functions\n/////////////////////////////////////////////////////////\n\nalgorithm_id_t Scheduler::newAlgorithm(const AlgorithmOptions_t& options) {\n\tconst algorithm_id_t id = getNewAlgorithmId();\n\t// Determine the type of algorithm to create.\n\tif (ValidAlgorithmId(id)) {\n\t\tswitch(options.type) {\n\t\t\tcase algorithm_type::brent_search:\n\t\t\t\talgorithms_map[id] = shared_ptr<BrentSearch>(new BrentSearch(options.options));\n\t\t\t\tbreak;\n\t\t\tcase algorithm_type::grid_search:\n\t\t\t\talgorithms_map[id] = shared_ptr<GridSearch>(new GridSearch(options.options));\n\t\t\t\tbreak;\n\t\t\tcase algorithm_type::iterative_update:\n\t\t\t\talgorithms_map[id] = shared_ptr<IterativeUpdate>(new IterativeUpdate(options.options));\n\t\t\t\tbreak;\n\t\t\tcase algorithm_type::proximal_gradient_descent:\n\t\t\t\talgorithms_map[id] = shared_ptr<ProximalGradientDescent>(new ProximalGradientDescent(options.options));\n\t\t\t\tbreak;\n\t\t\tcase algorithm_type::hypo_test:\n\t\t\t\talgorithms_map[id] = shared_ptr<HypoTestPlaceHolder>(new HypoTestPlaceHolder(options.options));\n\t\t\t\tbreak;\n\t\t\tcase algorithm_type::neighbor_selection:\n\t\t\t\talgorithms_map[id] = shared_ptr<NeighborSelection>(new NeighborSelection(options.options));\n\t\t\t\tbreak;\n            case algorithm_type::graphical_lasso:\n\t\t\t\talgorithms_map[id] = shared_ptr<GraphicalLasso>(new GraphicalLasso(options.options));\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn 0;\n\t\t}\n\t}\n\n\treturn id;\n}\n\nmodel_id_t Scheduler::newModel(const ModelOptions_t& options) {\n\tconst model_id_t id = getNewModelId();\n\tif (ValidModelId(id)) {\n\t\tswitch(options.type) {\n\t\t\tcase ada_multi_lasso: {\n\t\t\t\tmodels_map[id] = shared_ptr<AdaMultiLasso>(new AdaMultiLasso(options.options));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase gf_lasso: {\n\t\t\t\tmodels_map[id] = shared_ptr<Gflasso>(new Gflasso(options.options));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase linear_regression: {\n\t\t\t\tmodels_map[id] = shared_ptr<LinearRegression>(new LinearRegression(options.options));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase multi_pop_lasso: {\n\t\t\t\tmodels_map[id] = shared_ptr<MultiPopLasso>(new MultiPopLasso(options.options));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase tree_lasso: {\n\t\t\t\tmodels_map[id] = shared_ptr<TreeLasso>(new TreeLasso(options.options));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase fisher_test: {\n\t\t\t\tmodels_map[id] = shared_ptr<FisherTest>(new FisherTest(options.options));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase chi2_test: {\n\t\t\t\tmodels_map[id] = shared_ptr<Chi2Test>(new Chi2Test(options.options));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase wald_test: {\n\t\t\t\tmodels_map[id] = shared_ptr<WaldTest>(new WaldTest(options.options));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase lmm: {\n\t\t\t\tmodels_map[id] = shared_ptr<LinearMixedModel>(new LinearMixedModel(options.options));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase slmm: {\n\t\t\t\tmodels_map[id] = shared_ptr<SparseLMM>(new SparseLMM(options.options));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn 0;\n\t\t}\n\t}\n\n\treturn id;\n}\n\nbool Scheduler::imputation(const job_id_t job_id) {\n    if (JobIdUsed(job_id) && getJob(job_id)->model) {\n        getJob(job_id)->model->imputation();\n        return true;\n    }\n    return false;\n}\n\nbool Scheduler::setMetaData(const job_id_t job_id, const string& filename, vector<string>& marker_ids) {\n    if (JobIdUsed(job_id)) {\n        shared_ptr<Job_t> job = getJob(job_id);\n        job->filename = filename;\n        job->marker_ids = marker_ids;\n    }\n    return false;\n}\n\nbool Scheduler::setX(const job_id_t job_id, const Eigen::MatrixXf& X) {\n\tif (JobIdUsed(job_id) && getJob(job_id)->model) {\n\t\tgetJob(job_id)->model->setX(X);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n\nbool Scheduler::setY(const job_id_t job_id, const Eigen::MatrixXf& Y) {\n\tif (JobIdUsed(job_id) && getJob(job_id)->model) {\n\t\tgetJob(job_id)->model->setY(Y);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n// TODO: merge setX and setY into this function?\nbool Scheduler::setModelAttributeMatrix(const job_id_t job_id, const string& str, Eigen::MatrixXf* Z) {\n\ttry {\n\t\tif (JobIdUsed(job_id) && getJob(job_id)->model) {\n\t\t\tgetJob(job_id)->model->setAttributeMatrix(str, Z);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t} catch (const exception & e) {\n\t\trethrow_exception(current_exception());\n\t\treturn false;\n\t}\n}\n\n\njob_id_t Scheduler::newJob(const JobOptions_t& options) {\n\tJob_t* my_job = new Job_t();\n\tconst job_id_t job_id = getNewJobId();\n\tif (ValidJobId(job_id)) {\n\t\tmy_job->job_id = job_id;\n\t\ttry {\n\t\t\talgorithm_id_t algorithm_id = newAlgorithm(options.alg_opts);\n\t\t\tmy_job->algorithm = getAlgorithm(algorithm_id);\n\t\t} catch (const exception& e) {\n\t\t\tthrow runtime_error(\"Error creating algorithm\");\n\t\t\treturn 0;\n\t\t}\n\t\ttry {\n\t\t\tmodel_id_t model_id = newModel(options.model_opts);\n\t\t\tmy_job->model = getModel(model_id);\n\t\t\tjobs_map[my_job->job_id] = shared_ptr<Job_t>(my_job);\n\t\t\treturn job_id;\n\t\t} catch (const exception& e) {\n\t\t\tthrow runtime_error(\"Error creating model\");\n\t\t\treturn 0;\n\t\t} \n\t} else {\n\t\tthrow runtime_error(\"could not get a new job id (queue may be full)\");\n\t}\n\n\tdelete my_job;\n\treturn 0;\n}\n\n\nbool Scheduler::startJob(const job_id_t job_id, void (*completion)(uv_work_t*, int)) {\n\tif (!ValidJobId(job_id)) {\n\t\tthrow runtime_error(\"Job id must correspond to a job that has been created.\");\n\t\treturn false;\n\t}\n\tshared_ptr<Job_t> job = getJob(job_id);\n\n\tif (!job.get()) {\n\t\tthrow runtime_error(\"Job must not be null.\");\n\t\treturn false;\n\t} else if (!job->algorithm || !job->model) {\n\t\tthrow runtime_error(\"Job must have an algorithm and a model.\");\n\t\treturn false;\n\t} else if (job->algorithm->getIsRunning()) {\n\t\tthrow runtime_error(\"Job is already running.\");\n\t\treturn false;\n\t}\n\ttry {\n\t\tjob->algorithm->assertReadyToRun();\n\t\tjob->model->assertReadyToRun();\n\t\tjob->request.data = job.get();\n\t\tuv_queue_work(uv_default_loop(), &(job->request), trainAlgorithmThread, completion);\n\t\treturn true;\n\t} catch (const exception& ex) {\n\t\trethrow_exception(current_exception());\n\t\treturn false;\n\t}\n}\n\n\n// Runs in libuv thread spawned by startJob\nvoid trainAlgorithmThread(uv_work_t* req) {\n\tJob_t* job = static_cast<Job_t*>(req->data);\n\tif (!job) {\n\t\tthrow runtime_error(\"Job must not be null\");\n\t\treturn;\n\t}\n\n\tjob->thread_id = std::this_thread::get_id();\n\t// TODO: as more algorithm/model types are created, add them here.\n\ttry {\n\t\tif (!job->algorithm || !job->model) {\n\t\t\tthrow runtime_error(\"Job must have an algorithm and a model\");\n\t\t}\n\t\tjob->algorithm->assertReadyToRun();\n\t\tjob->model->assertReadyToRun();\n\t\t// Object slicing makes this annoying\n\t\tif (shared_ptr<BrentSearch> alg = dynamic_pointer_cast<BrentSearch>(job->algorithm)) {\n\t\t\talg->setUpRun();\n\t\t\tif (shared_ptr<AdaMultiLasso> model = dynamic_pointer_cast<AdaMultiLasso>(job->model)) {\n\t\t        alg->run(model);\n\t\t    } else if (shared_ptr<Gflasso> model = dynamic_pointer_cast<Gflasso>(job->model)) {\n\t\t        alg->run(model);\n\t\t    } else if (shared_ptr<LinearRegression> model = dynamic_pointer_cast<LinearRegression>(job->model)) {\n\t\t        alg->run(model);\n\t\t    } else if (shared_ptr<MultiPopLasso> model = dynamic_pointer_cast<MultiPopLasso>(job->model)) {\n\t\t        alg->run(model);\n\t\t    } else if (shared_ptr<SparseLMM> model = dynamic_pointer_cast<SparseLMM>(job->model)) {\n\t\t        alg->sub_run(model);\n\t\t    } else if (shared_ptr<TreeLasso> model = dynamic_pointer_cast<TreeLasso>(job->model)) {\n\t\t        alg->run(model);\n\t\t    } else if (shared_ptr<LinearMixedModel> model = dynamic_pointer_cast<LinearMixedModel>(job->model)) {\n\t\t\t\talg->sub_run(model);\n\t\t\t} else {\n\t\t        throw runtime_error(\"Requested model type not implemented for the requested algorithm\");\n\t\t    }\n\t\t    alg->finishRun();\n\t\t} else if (shared_ptr<GridSearch> alg = dynamic_pointer_cast<GridSearch>(job->algorithm)) {\n\t\t\talg->setUpRun();\n\t\t    if (shared_ptr<AdaMultiLasso> model = dynamic_pointer_cast<AdaMultiLasso>(job->model)) {\n\t\t        alg->run(model);\n\t\t    } else if (shared_ptr<Gflasso> model = dynamic_pointer_cast<Gflasso>(job->model)) {\n\t\t        alg->run(model);\n\t\t    } else if (shared_ptr<LinearRegression> model = dynamic_pointer_cast<LinearRegression>(job->model)) {\n\t\t        alg->run(model);\n\t\t    } else if (shared_ptr<MultiPopLasso> model = dynamic_pointer_cast<MultiPopLasso>(job->model)) {\n\t\t        alg->run(model);\n\t\t    } else if (shared_ptr<SparseLMM> model = dynamic_pointer_cast<SparseLMM>(job->model)) {\n\t\t        alg->sub_run(model);\n\t\t    } else if (shared_ptr<TreeLasso> model = dynamic_pointer_cast<TreeLasso>(job->model)) {\n\t\t        alg->run(model);\n\t\t    } else if (shared_ptr<LinearMixedModel> model = dynamic_pointer_cast<LinearMixedModel>(job->model)) {\n\t\t\t\talg->run(model);\n\t\t\t} else {\n\t\t        throw runtime_error(\"Requested model type not implemented for the requested algorithm\");\n\t\t    }\n\t\t    alg->finishRun();\n\t\t} else if (shared_ptr<IterativeUpdate> alg = dynamic_pointer_cast<IterativeUpdate>(job->algorithm)) {\n\t\t\talg->setUpRun();\n\t\t\tif (shared_ptr<AdaMultiLasso> model = dynamic_pointer_cast<AdaMultiLasso>(job->model)) {\n\t\t        alg->run(model);\n\t\t    } else if (shared_ptr<Gflasso> model = dynamic_pointer_cast<Gflasso>(job->model)) {\n\t\t        alg->run(model);\n\t\t    } else if (shared_ptr<LinearRegression> model = dynamic_pointer_cast<LinearRegression>(job->model)) {\n\t\t        alg->run(model);\n\t\t    } else if (shared_ptr<MultiPopLasso> model = dynamic_pointer_cast<MultiPopLasso>(job->model)) {\n\t\t        alg->run(model);\n\t\t    } else if (shared_ptr<SparseLMM> model = dynamic_pointer_cast<SparseLMM>(job->model)) {\n\t\t        alg->run(model);\n\t\t    } else if (shared_ptr<TreeLasso> model = dynamic_pointer_cast<TreeLasso>(job->model)) {\n\t\t        alg->run(model);\n\t\t    } else {\n\t\t        throw runtime_error(\"Requested model type not implemented for the requested algorithm\");\n\t\t    }\n\t\t    alg->finishRun();\n\t\t} else if (shared_ptr<ProximalGradientDescent> alg = dynamic_pointer_cast<ProximalGradientDescent>(job->algorithm)) {\n\t\t\talg->setUpRun();\n\t\t\tif (shared_ptr<AdaMultiLasso> model = dynamic_pointer_cast<AdaMultiLasso>(job->model)) {\n\t\t        alg->run(model);\n\t\t    } else if (shared_ptr<Gflasso> model = dynamic_pointer_cast<Gflasso>(job->model)) {\n\t\t        alg->run(model);\n\t\t    } else if (shared_ptr<LinearRegression> model = dynamic_pointer_cast<LinearRegression>(job->model)) {\n\t\t        alg->run(model);\n\t\t    } else if (shared_ptr<MultiPopLasso> model = dynamic_pointer_cast<MultiPopLasso>(job->model)) {\n\t\t        alg->run(model);\n\t\t    } else if (shared_ptr<SparseLMM> model = dynamic_pointer_cast<SparseLMM>(job->model)) {\n\t\t        alg->run(model);\n\t\t    } else if (shared_ptr<TreeLasso> model = dynamic_pointer_cast<TreeLasso>(job->model)) {\n\t\t        alg->run(model);\n\t\t    } else {\n\t\t        throw runtime_error(\"Requested model type not implemented for the requested algorithm\");\n\t\t    }\n\t\t    alg->finishRun();\n\t\t} else if (shared_ptr<HypoTestPlaceHolder> alg = dynamic_pointer_cast<HypoTestPlaceHolder>(job->algorithm)){\n\t\t\talg->setUpRun();\n\t\t\tif (shared_ptr<FisherTest> model = dynamic_pointer_cast<FisherTest>(job->model)) {\n\t\t\t\talg->run(model);\n\t\t\t} else if (shared_ptr<Chi2Test> model = dynamic_pointer_cast<Chi2Test>(job->model)) {\n\t\t\t\talg->run(model);\n\t\t\t} else if (shared_ptr<WaldTest> model = dynamic_pointer_cast<WaldTest>(job->model)) {\n\t\t\t\talg->run(model);\n\t\t\t} else {\n\t\t\t\tthrow runtime_error(\"Requested model type not implemented for the requested algorithm\");\n\t\t\t}\n\t\t\talg->finishRun();\n\t\t} else if (shared_ptr<NeighborSelection> alg = dynamic_pointer_cast<NeighborSelection>(job->algorithm)) {\n\t\t\talg->setUpRun();\n\t\t\tif (shared_ptr<LinearRegression> model = dynamic_pointer_cast<LinearRegression>(job->model)) {\n\t\t\t\talg->run(model);\n\t\t\t} else {\n\t\t\t\tthrow runtime_error(\"Requested model type not implemented for the requested algorithm\");\n\t\t\t}\n\t\t\talg->finishRun();\n\t\t} else if (shared_ptr<GraphicalLasso> alg = dynamic_pointer_cast<GraphicalLasso>(job->algorithm)) {\n\t\t\talg->setUpRun();\n\t\t\tif (shared_ptr<LinearRegression> model = dynamic_pointer_cast<LinearRegression>(job->model)) {\n\t\t\t\talg->run(model);\n\t\t\t} else {\n\t\t\t\tthrow runtime_error(\"Requested model type not implemented for the requested algorithm\");\n\t\t\t}\n\t\t\talg->finishRun();\n\t\t} else {\n\t\t\tthrow runtime_error(\"Requested algorithm type not implemented\");\n\t\t}\n\t} catch (const exception& ex) {\n\t\tjob->exception = current_exception();\t// Must save the exception so that it can be passed between threads.\n\t}\n}\n\n\nfloat Scheduler::checkJobProgress(const job_id_t job_id) {\n\tif (JobIdUsed(job_id) && getJob(job_id)->algorithm) {\n\t\treturn getJob(job_id)->algorithm->getProgress();\n\t}\n\treturn -1;\n}\n\n\nbool Scheduler::cancelJob(const job_id_t job_id) {\n\tif (JobIdUsed(job_id) && getJob(job_id)->algorithm) {\n\t\tgetJob(job_id)->algorithm->stop();\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n\nbool Scheduler::deleteAlgorithm(const algorithm_id_t algorithm_id) {\n\tif (getAlgorithm(algorithm_id) && !getAlgorithm(algorithm_id)->getIsRunning()) {\n\t\tgetAlgorithm(algorithm_id)->mtx.lock();\n\t\talgorithms_map[algorithm_id].reset();\n\t\talgorithms_map.erase(algorithm_id);\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}\n\n\nbool Scheduler::deleteModel(const model_id_t model_id) {\n\tif (getModel(model_id)) {\n\t\t/*getModel(model_id)->mtx.lock();*/\n\t\tmodels_map[model_id].reset();\n\t\tmodels_map.erase(model_id);\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}\n\n\nbool Scheduler::deleteJob(const job_id_t job_id) {\n\tif (JobIdUsed(job_id) && cancelJob(job_id)) {\n\t\t// Make sure the job is not currently running.\n\t\tgetJob(job_id)->algorithm->mtx.lock();\n\t\tjobs_map[job_id].reset();\n\t\tjobs_map.erase(job_id);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n\nshared_ptr<Algorithm> Scheduler::getAlgorithm(const algorithm_id_t algorithm_id) {\n\tif (AlgorithmIdUsed(algorithm_id)) {\n\t\treturn algorithms_map[algorithm_id];\n\t} \n\tthrow runtime_error(\"Algorithm ID does not match any algorithms.\");\n\treturn shared_ptr<Algorithm>(nullptr);\n}\n\n\nshared_ptr<Model> Scheduler::getModel(const model_id_t model_id) {\n\tif (ModelIdUsed(model_id)) {\n\t\treturn models_map[model_id];\n\t} \n\tthrow runtime_error(\"Model ID does not match any models.\");\n\treturn shared_ptr<Model>(nullptr);\n}\n\n\nshared_ptr<Job_t> Scheduler::getJob(const job_id_t job_id) {\n\tif (JobIdUsed(job_id)) {\n\t\treturn jobs_map[job_id];\n\t}\n\tthrow runtime_error(\"Job ID does not match any jobs.\");\n\treturn shared_ptr<Job_t>(nullptr);\n}\n\n\nMatrixXf Scheduler::getJobResult(const job_id_t job_id) {\n\tif (JobIdUsed(job_id)) {\n\t\tshared_ptr<Job_t> job = getJob(job_id);\n\t\tif (shared_ptr<AdaMultiLasso> model = dynamic_pointer_cast<AdaMultiLasso>(job->model)) {\n\t        return model->getBeta();\n\t    } else if (shared_ptr<Gflasso> model = dynamic_pointer_cast<Gflasso>(job->model)) {\n\t        return model->getBeta();\n\t    } else if (shared_ptr<LinearRegression> model = dynamic_pointer_cast<LinearRegression>(job->model)) {\n\t        return model->getBeta();\n\t    } else if (shared_ptr<MultiPopLasso> model = dynamic_pointer_cast<MultiPopLasso>(job->model)) {\n\t        return model->getBeta();\n\t    } else if (shared_ptr<SparseLMM> model = dynamic_pointer_cast<SparseLMM>(job->model)) {\n\t        return model->getBeta();\n\t    } else if (shared_ptr<TreeLasso> model = dynamic_pointer_cast<TreeLasso>(job->model)) {\n\t        return model->getBeta();\n\t    } else if (shared_ptr<LinearMixedModel> model = dynamic_pointer_cast<LinearMixedModel>(job->model)) {\n\t\t\treturn model->getBeta();\n\t\t} else if (shared_ptr<FisherTest> model = dynamic_pointer_cast<FisherTest>(job->model)) {\n\t\t\treturn model->getBeta();\n\t\t} else if (shared_ptr<Chi2Test> model = dynamic_pointer_cast<Chi2Test>(job->model)) {\n\t\t\treturn model->getBeta();\n\t\t} else if (shared_ptr<WaldTest> model = dynamic_pointer_cast<WaldTest>(job->model)) {\n\t\t\treturn model->getBeta();\n\t\t} else {\n\t    \treturn model->getBeta();\n\t    }\n\t} else {\n\t\treturn MatrixXf();\n\t}\n}\n\n////////////////////////////////////////////////////////\n// Private Functions\n////////////////////////////////////////////////////////\n\nmodel_id_t Scheduler::getNewModelId() {\n\tmodel_id_t candidate_model_id = next_model_id;\n\tfor (unsigned int i = 1; i < kMaxModelId; i++) {\n\t\tcandidate_model_id = (candidate_model_id + 1) % kMaxModelId + 1;\n\t\tif (!ModelIdUsed(candidate_model_id)) {\n\t\t\tmodel_id_t retval = next_model_id;\n\t\t\tnext_model_id = candidate_model_id;\n\t\t\treturn retval;\n\t\t}\n\t}\n\treturn 0;\n}\n\n\nalgorithm_id_t Scheduler::getNewAlgorithmId() {\n\talgorithm_id_t candidate_algorithm_id = next_algorithm_id;\n\tfor (unsigned int i = 1; i < kMaxAlgorithmId; i++) {\n\t\tcandidate_algorithm_id = (candidate_algorithm_id + 1) % kMaxAlgorithmId + 1;\n\t\tif (!AlgorithmIdUsed(candidate_algorithm_id)) {\n\t\t\talgorithm_id_t retval = next_algorithm_id;\n\t\t\tnext_algorithm_id = candidate_algorithm_id;\n\t\t\treturn retval;\n\t\t}\n\t}\n\treturn 0;\n}\n\n\njob_id_t Scheduler::getNewJobId() {\n\tjob_id_t candidate_job_id = next_job_id;\n\tfor (unsigned int i = 1; i < kMaxJobId; i++) {\n\t\tcandidate_job_id = (candidate_job_id + i) % kMaxJobId + 1;\n\t\tif (!JobIdUsed(candidate_job_id)) {\n\t\t\tjob_id_t retval = next_job_id;\n\t\t\tnext_job_id = candidate_job_id;\n\t\t\treturn retval;\n\t\t}\n\t}\n\treturn 0;\n}\n\n\nbool Scheduler::ValidAlgorithmId(const algorithm_id_t id) {\n\treturn (id > 0 && id <= kMaxAlgorithmId);\n}\n\nbool Scheduler::ValidModelId(const model_id_t id) {\n\treturn (id > 0 && id <= kMaxModelId);\n}\n\nbool Scheduler::ValidJobId(const job_id_t id) {\n\treturn (id > 0 && id <= kMaxJobId);\n}\n\nbool Scheduler::AlgorithmIdUsed(const algorithm_id_t id) {\n\treturn (ValidAlgorithmId(id) && algorithms_map[id] && algorithms_map[id].get());\n}\n\nbool Scheduler::ModelIdUsed(const model_id_t id) {\n\treturn (ValidModelId(id) && models_map[id] && models_map[id].get());\n}\n\nbool Scheduler::JobIdUsed(const job_id_t id) {\n\treturn (ValidJobId(id) && jobs_map[id] && jobs_map[id].get());\n}\n", "meta": {"hexsha": "9d5c6b82a4a0cbff405a574500471fe3226bd9cf", "size": 20192, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Scheduler/Scheduler.cpp", "max_stars_repo_name": "blengerich/jenkins_test", "max_stars_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-10-20T00:36:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-06T16:40:52.000Z", "max_issues_repo_path": "src/Scheduler/Scheduler.cpp", "max_issues_repo_name": "blengerich/jenkins_test", "max_issues_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2016-11-11T22:41:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-04T21:55:57.000Z", "max_forks_repo_path": "src/Scheduler/Scheduler.cpp", "max_forks_repo_name": "blengerich/jenkins_test", "max_forks_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-02-01T09:19:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-28T14:40:43.000Z", "avg_line_length": 33.2105263158, "max_line_length": 119, "alphanum_fraction": 0.6933438986, "num_tokens": 5250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.25829247249875215}}
{"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_TOOLBOX_TRIGONOMETRIC_FUNCTIONS_SIMD_COMMON_IMPL_TRIGO_F_TRIG_REDUCTION_HPP_INCLUDED\n#define NT2_TOOLBOX_TRIGONOMETRIC_FUNCTIONS_SIMD_COMMON_IMPL_TRIGO_F_TRIG_REDUCTION_HPP_INCLUDED\n\n#include <nt2/include/functions/simd/rem_pio2_medium.hpp>\n#include <nt2/include/functions/simd/rem_pio2_cephes.hpp>\n#include <nt2/include/functions/simd/rem_pio2_straight.hpp>\n#include <nt2/include/functions/simd/rem_pio2.hpp>\n#include <nt2/include/functions/simd/toint.hpp>\n#include <nt2/include/functions/simd/inrad.hpp>\n#include <nt2/include/functions/simd/round.hpp>\n#include <nt2/include/functions/simd/is_odd.hpp>\n#include <nt2/include/functions/simd/is_not_less.hpp>\n#include <nt2/include/functions/simd/is_not_greater.hpp>\n#include <nt2/include/functions/simd/is_inf.hpp>\n#include <nt2/include/functions/simd/bitwise_andnot.hpp>\n#include <nt2/include/functions/simd/logical_and.hpp>\n#include <nt2/include/functions/simd/is_invalid.hpp>\n#include <nt2/include/functions/simd/is_flint.hpp>\n#include <nt2/include/functions/simd/rec.hpp>\n#include <nt2/include/functions/simd/all.hpp>\n#include <nt2/include/functions/simd/split.hpp>\n#include <nt2/include/functions/simd/group.hpp>\n#include <nt2/include/constants/false.hpp>\n#include <nt2/sdk/simd/logical.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/mpl/not.hpp>\n#include <boost/mpl/bool.hpp>\n\nnamespace nt2\n{\n  namespace details\n  {\n    namespace internal\n    {\n      // This class exposes the public static member:\n      // reduce:                to provide range reduction\n      //\n      // unit_tag allows to choose statically the scaling  among radian_tag, pi_tag, degree_tag\n      // meaning that the cosa function will (for example) define respectively\n      // x-->cos(x)          (radian_tag),\n      // x-->cos(pi*x)       (pi_tag)\n      // x-->cos((pi/180)*x) (degree_tag)\n      //\n\n      // trigonometric reduction strategies to the [-pi/4, pi/4] range.\n      // these reductions are used in the accurate and fast\n      // trigonometric functions with different policies\n\n      template<class A0, class mode>\n      struct trig_reduction < A0, radian_tag,  tag::simd_type, mode, float>\n      {\n        typedef typename meta::as_logical<A0>::type              bA0;\n        typedef typename meta::as_integer<A0, signed>::type int_type;\n        static inline bA0 isalreadyreduced(const A0&a0) { return is_ngt(a0, Pio_4<A0>()); }\n        static inline bA0 ismedium (const A0&a0)  { return le(a0,single_constant<A0,0x43490fdb>()); }\n        static inline bA0 issmall  (const A0&a0)  { return le(a0,single_constant<A0,0x427b53d1>()); }\n        static inline bA0 islessthanpi_2  (const A0&a0)  { return le(a0,Pio_2<A0>()); }\n        typedef typename boost::mpl::not_<boost::is_same<A0,typename meta::upgrade<A0>::type> >::type conversion_allowed;\n\n        static inline bA0 cot_invalid(const A0&) { return False<bA0>(); }\n        static inline bA0 tan_invalid(const A0&) { return False<bA0>(); }\n        static inline int_type reduce(const A0& x, A0& xr, A0& xc){ return inner_reduce(x, xr, xc, mode()); }\n      private:\n        static inline int_type inner_reduce(const typename A0::native_type x_n, A0& xr, A0& xc, const big_& b)\n        {\n          const A0 x = x_n;\n          // x is always positive here\n          if (nt2::all(isalreadyreduced(x))) // all of x are in [0, pi/4], no reduction\n            {\n              xr = x;\n              xc = Zero<A0>();\n              return Zero<int_type>();\n            }\n          else if (nt2::all(islessthanpi_2(x))) // all of x are in [pi/4, pi/2],  straight algorithm is sufficient for 1 ulp\n              return rem_pio2_straight(x, xr, xc);\n          else if (nt2::all(issmall(x))) // all of x are in [0, 20*pi],  cephes algorithm is sufficient for 1 ulp\n              return rem_pio2_cephes(x, xr, xc);\n          else if (nt2::all(ismedium(x))) // all of x are in [0, 2^7*pi/2],  fdlibm medium_ way\n              return rem_pio2_medium(x, xr, xc);\n          else\n              return inner_reduce_big(x, xr, xc, b, conversion_allowed());\n        }\n\n        template<class m>\n        static inline int_type inner_reduce_big(const A0& x, A0& xr, A0& xc, const m&, boost::mpl::true_)\n        {\n          //if (nt2::all(isnotsobig(x))) // all of x are in [0, 2^18*pi],  conversion to double is used to reduce\n          typedef typename meta::upgrade<A0>::type uA0;\n          typedef typename meta::upgrade<int_type>::type uint_type;\n          typedef trig_reduction< uA0, radian_tag,  tag::simd_type, mode, double> aux_reduction;\n          uA0 ux1, ux2, uxr1, uxr2, uxc1, uxc2;\n          nt2::split(x, ux1, ux2);\n          uint_type n1 = aux_reduction::reduce(ux1, uxr1, uxc1);\n          uint_type n2 = aux_reduction::reduce(ux2, uxr2, uxc2);\n          xr = nt2::group(uxr1, uxr2);\n          nt2::split(xr, ux1, ux2);\n          xc = nt2::group((uxr1-ux1)+uxc1, (uxr2-ux2)+uxc2);\n          return nt2::group(n1, n2);\n        }\n\n        static inline int_type inner_reduce_big(const A0& x, A0& xr, A0& xc, const big_&, boost::mpl::false_)\n        {\n          // all of x are in [0, inf],  standard big_ way\n          return rem_pio2(x, xr, xc);\n        }\n\n        static inline int_type inner_reduce_big(const A0& x, A0& xr, A0& xc, const direct_big_&, boost::mpl::false_)\n        {\n          return rem_pio2_big(x, xr, xc);\n        }\n\n        static inline int_type inner_reduce(const typename A0::native_type x_n, A0& xr, A0& xc, const medium_&)\n        {\n          const A0 x = x_n;\n          // x is always positive here\n          if (nt2::all(isalreadyreduced(x))) // all of x are in [0, pi/4], no reduction\n            {\n              xr = x;\n              xc = Zero<A0>();\n              return Zero<int_type>();\n            }\n          else if (nt2::all(islessthanpi_2(x))) // all of x are in [pi/4, pi/2],  straight algorithm is sufficient for 1 ulp\n              return rem_pio2_straight(x, xr, xc);\n          else if (nt2::all(issmall(x))) // all of x are in [0, 20*pi],  cephes algorithm is sufficient for 1 ulp\n              return rem_pio2_cephes(x, xr, xc);\n          else // correct only if all of x are in [0, 2^7*pi/2],  fdlibm medium_ way\n              return rem_pio2_medium(x, xr, xc);\n        }\n        static inline int_type inner_reduce(const typename A0::native_type x_n, A0& xr, A0& xc, const small_&)\n        {\n          const A0 x = x_n;\n          // x is always positive here\n          if (nt2::all(isalreadyreduced(x))) // all of x are in [0, pi/4], no reduction\n            {\n              xr = x;\n              xc = Zero<A0>();\n              return Zero<int_type>();\n            }\n          else if (nt2::all(islessthanpi_2(x))) // all of x are in [pi/4, pi/2],  straight algorithm is sufficient for 1 ulp\n              return rem_pio2_straight(x, xr, xc);\n          else //  correct only if all of x are in [0, 20*pi],  cephes algorithm is sufficient for 1 ulp\n              return rem_pio2_cephes(x, xr, xc);\n         }\n        static inline int_type inner_reduce(const typename A0::native_type x_n, A0& xr, A0& xc, const direct_small_&)\n        {\n          const A0 x = x_n;\n          return rem_pio2_cephes(x, xr, xc);\n        }\n        static inline int_type inner_reduce(const typename A0::native_type x_n, A0& xr, A0& xc, const direct_medium_&)\n        {\n          const A0 x = x_n;\n          return rem_pio2_medium(x, xr, xc);\n        }\n        static inline int_type inner_reduce(const typename A0::native_type x_n, A0& xr, A0& xc, const direct_big_& b)\n        {\n          const A0 x = x_n;\n          inner_reduce_big(x, xr, xc, b);\n        }\n        static inline int_type inner_reduce(const typename A0::native_type x_n, A0& xr, A0& xc, const clipped_pio4_&)\n        {\n          const A0 x = x_n;\n          xr = sel(isalreadyreduced(nt2::abs(x)), x, Nan<A0>());\n          xc = Zero<A0>();\n          return Zero<int_type>();\n        }\n        static inline int_type inner_reduce(const typename A0::native_type x_n, A0& xr, A0& xc, const clipped_small_&)\n        {\n          const A0 x = x_n;\n          xr = sel(issmall(nt2::abs(x)), x, Nan<A0>());\n          return inner_reduce(xr, xr, xc, small_());\n        }\n        static inline int_type inner_reduce(const typename A0::native_type x_n, A0& xr, A0& xc, const clipped_medium_&)\n        {\n          const A0 x = x_n;\n          xr = sel(ismedium(nt2::abs(x)), x, Nan<A0>());\n          return inner_reduce(xr, xr, xc, medium_());\n        }\n\n      };\n\n\n      template<class A0>\n      struct trig_reduction<A0,degree_tag, tag::simd_type,big_, float>\n      {\n        typedef typename meta::as_integer<A0, signed>::type int_type;\n        typedef typename meta::as_logical<A0>::type              bA0;\n\n        static inline bA0 cot_invalid(const A0& x) { return logical_and(is_nez(x), is_flint(x/_180<A0>())); }\n        static inline bA0 tan_invalid(const A0& x) { return is_flint((x-_90<A0>())/_180<A0>()); }\n\n        static inline int_type reduce(const typename A0::native_type x_n, A0& xr, A0& xc)\n        {\n          const A0 x = x_n;\n          A0 xi = round(x*single_constant<A0,0x3c360b61>()); //  1.111111111111111e-02f\n          A0 x2 = x - xi * _90<A0>();//90.0f\n          xr =  x2*single_constant<A0,0x3c8efa35>(); //0.0174532925199432957692f\n          xc = Zero<A0>();\n          return toint(xi);\n        }\n      };\n\n      // TODO put a medium_ case with a fast_round ?\n       template < class A0>\n       struct trig_reduction < A0, pi_tag,  tag::simd_type, big_, float>\n      {\n        typedef typename meta::as_integer<A0, signed>::type int_type;\n        typedef typename meta::as_logical<A0>::type              bA0;\n\n        static inline bA0 cot_invalid(const A0& x) { return logical_and(is_nez(x), is_flint(x)); }\n        static inline bA0 tan_invalid(const A0& x) { return is_flint(x-Half<A0>()) ; }\n\n        static inline int_type reduce(const typename A0::native_type x_n,  A0& xr, A0&xc)\n        {\n          const A0 x = x_n;\n          A0 xi = round(x*Two<A0>());\n          A0 x2 = x - xi * Half<A0>();\n          xr = x2*Pi<A0>();\n          xc = Zero<A0>();\n          return toint(xi);\n        }\n      };\n    }\n  }\n}\n\n#endif\n\n// /////////////////////////////////////////////////////////////////////////////\n// End of f_trig_reduction.hpp\n// /////////////////////////////////////////////////////////////////////////////\n", "meta": {"hexsha": "edc4058d1d4a4428c7d70caa9f3094c2d4f8dbe9", "size": 10848, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/toolbox/trigonometric/functions/simd/common/impl/trigo/f_trig_reduction.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/trigonometric/include/nt2/toolbox/trigonometric/functions/simd/common/impl/trigo/f_trig_reduction.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/trigonometric/include/nt2/toolbox/trigonometric/functions/simd/common/impl/trigo/f_trig_reduction.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": 45.3891213389, "max_line_length": 124, "alphanum_fraction": 0.587020649, "num_tokens": 3003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2582924658764485}}
{"text": "#include \"PCAModelBuilder.h\"\n#include \"StatisticalModel.h\"\n#include \"vtkPolyData.h\"\n#include <boost/scoped_ptr.hpp>\n#include <iostream>\n#include \"vtkStandardMeshRepresenter.h\"\n#include \"DataManager.h\"\n#include \"vtkPolyDataReader.h\"\n#include \"saveModelCLP.h\"\n#include <fstream>\n#include \"vtkCellArray.h\"\n\nusing namespace statismo;\ntypedef vtkStandardMeshRepresenter RepresenterType;\ntypedef DataManager<vtkPolyData> DataManagerType;\ntypedef PCAModelBuilder<vtkPolyData> ModelBuilderType;\ntypedef StatisticalModel<vtkPolyData> StatisticalModelType;\n\nvtkSmartPointer<vtkPolyData> loadVTKPolyData(const std::string& filename) {\n    vtkSmartPointer<vtkPolyDataReader> reader = vtkSmartPointer<vtkPolyDataReader>::New();\n    reader->SetFileName(filename.c_str());\n    reader->Update();\n    vtkSmartPointer<vtkPolyData> pd = vtkSmartPointer<vtkPolyData>::New();\n    pd->ShallowCopy(reader->GetOutput());\n    return pd;\n}\n\nint main(int argc, char ** argv)\n{\n    PARSE_ARGS;\n\n    if(argc < 7)\n    {\n        std::cout << \"Usage \" << argv[0] << \" [--groupnumber <int>] [--vtkfilelist <std::vector<std::string>>] [--resultdir <std::string>]\" << std::endl;\n        return 1;\n    }\n\n    // Average of all the VTK meshes\n    //   Mean of the 3 coordinates\n    vtkSmartPointer<vtkPolyData> polydata0 = loadVTKPolyData(vtkfilelist[0]);\n    int numPts = loadVTKPolyData(vtkfilelist[0])->GetPoints()->GetNumberOfPoints();\n    vtkSmartPointer<vtkCellArray> verts = polydata0->GetVerts();\n    vtkSmartPointer<vtkCellArray> lines = polydata0->GetLines();\n    vtkSmartPointer<vtkCellArray> polys = polydata0->GetPolys();\n    vtkSmartPointer<vtkCellArray> strips = polydata0->GetStrips();\n\n    vtkSmartPointer<vtkPolyData> polydata_MeanGroup = vtkSmartPointer<vtkPolyData>::New();\n    vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();\n    points = polydata0->GetPoints();\n    for(int meshID = 1; meshID < vtkfilelist.size(); meshID++)\n    {\n        vtkSmartPointer<vtkPolyData> polydata = vtkSmartPointer<vtkPolyData>::New();\n        polydata = loadVTKPolyData(vtkfilelist[meshID]);\n        for(int ptID = 0; ptID < numPts; ptID++)\n        {\n            double coord[3];\n            polydata->GetPoint(ptID, coord);\n            double sum[3];\n            points->GetPoint(ptID, sum);\n            for(int dim = 0; dim < 3; dim++)\n            {\n                sum[dim] = sum[dim] + coord[dim];\n            }\n            points->InsertPoint(ptID, sum);\n        }\n    }\n    double mean[3];\n    for(int ptID = 0; ptID < numPts; ptID++)\n    {\n        for(int dim = 0; dim < 3; dim++)\n        {\n            double sum[3];\n            points->GetPoint(ptID, sum);\n            mean[dim] = sum[dim]/vtkfilelist.size();\n        }\n        points->InsertPoint(ptID, mean);\n    }\n\n    //   Creation of the polydata of the mean of the given group\n    polydata_MeanGroup->SetPoints(points);\n    polydata_MeanGroup->SetVerts(verts);\n    polydata_MeanGroup->SetLines(lines);\n    polydata_MeanGroup->SetPolys(polys);\n    polydata_MeanGroup->SetStrips(strips);\n\n    // Creation of the shape model\n    vtkSmartPointer<vtkPolyData> reference = polydata_MeanGroup;\n\n    boost::scoped_ptr<RepresenterType> representer(RepresenterType::Create(reference));\n    boost::scoped_ptr<DataManagerType> dataManager(DataManagerType::Create(representer.get()));\n    for(int j = 0; j < vtkfilelist.size(); j++)\n    {\n        dataManager->AddDataset(loadVTKPolyData(vtkfilelist[j]), vtkfilelist[j]);\n    }\n    boost::scoped_ptr<ModelBuilderType> modelBuilder(ModelBuilderType::Create());\n    boost::scoped_ptr<StatisticalModelType> model(modelBuilder->BuildNewModel(dataManager->GetData(), 0.01));\n    \n    // Once we have built the model, we can save in the directory choosen by the user.\n    std::string H5File = resultdir + \"/G\" + std::to_string(groupnumber) + \".h5\";\n    model->Save(H5File);\n    std::cout << \"Successfully saved shape model as \" << \"G\" << groupnumber << \".h5\" << std::endl;\n    \n    return 0;\n}", "meta": {"hexsha": "9894cc75fc92b4721fef5ec5385dbb462b8e984d", "size": 3976, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/CLI/saveModel/saveModel.cxx", "max_stars_repo_name": "laurapascal/DiagnosticIndex", "max_stars_repo_head_hexsha": "3dc783fc85b1b94ed983e0d7230cdbfc9863fc37", "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/CLI/saveModel/saveModel.cxx", "max_issues_repo_name": "laurapascal/DiagnosticIndex", "max_issues_repo_head_hexsha": "3dc783fc85b1b94ed983e0d7230cdbfc9863fc37", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-07-13T16:23:06.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-15T15:25:38.000Z", "max_forks_repo_path": "src/CLI/saveModel/saveModel.cxx", "max_forks_repo_name": "laurapascal/DiagnosticIndex", "max_forks_repo_head_hexsha": "3dc783fc85b1b94ed983e0d7230cdbfc9863fc37", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-06-14T18:43:47.000Z", "max_forks_repo_forks_event_max_datetime": "2016-07-15T15:26:47.000Z", "avg_line_length": 38.2307692308, "max_line_length": 153, "alphanum_fraction": 0.6705231388, "num_tokens": 1044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2582924658764485}}
{"text": "/*\r\n boost/numeric/odeint/stepper/detail/pid_step_adjuster_coefficients.hpp\r\n\r\n [begin_description]\r\n Coefficients for the PID stepsize controller.\r\n [end_description]\r\n\r\n Copyright 2017 Valentin Noah Hartmann\r\n\r\n Distributed under the Boost Software License, Version 1.0.\r\n (See accompanying file LICENSE_1_0.txt or\r\n copy at http://www.boost.org/LICENSE_1_0.txt)\r\n */\r\n\r\n#ifndef BOOST_NUMERIC_ODEINT_STEPPER_DETAIL_PID_STEP_ADJUSTER_COEFFICIENTS_HPP_INCLUDED\r\n#define BOOST_NUMERIC_ODEINT_STEPPER_DETAIL_PID_STEP_ADJUSTER_COEFFICIENTS_HPP_INCLUDED\r\n\r\n#include <boost/array.hpp>\r\n\r\nnamespace boost {\r\nnamespace numeric {\r\nnamespace odeint {\r\nnamespace detail {\r\n\r\nenum adjuster_type{\r\n    BASIC,\r\n    H0211,\r\n    H211b,\r\n    H211PI,\r\n    H0312,\r\n    H312b,\r\n    H312PID,\r\n    H0321,\r\n    H321\r\n};\r\n\r\ntemplate<int Type>\r\nclass pid_step_adjuster_coefficients;\r\n\r\ntemplate<>\r\nclass pid_step_adjuster_coefficients<BASIC> : public boost::array<double, 5>\r\n{\r\npublic:\r\n    pid_step_adjuster_coefficients()\r\n    : boost::array<double, 5>()\r\n    {\r\n        (*this)[0] = 1.0;\r\n        (*this)[1] = 0.0;\r\n        (*this)[2] = 0.0;\r\n        (*this)[3] = 0.0;\r\n        (*this)[4] = 0.0;\r\n    }\r\n};\r\n\r\ntemplate<>\r\nclass pid_step_adjuster_coefficients<H0211> : public boost::array<double, 5>\r\n{\r\npublic:\r\n    pid_step_adjuster_coefficients()\r\n    : boost::array<double, 5>()\r\n    {\r\n        (*this)[0] = 1.0 / 2.0;\r\n        (*this)[1] = 1.0 / 2.0;\r\n        (*this)[2] = 0.0;\r\n        (*this)[3] = 1.0 / 2.0;\r\n        (*this)[4] = 0.0;\r\n    }\r\n};\r\n\r\ntemplate<>\r\nclass pid_step_adjuster_coefficients<H211b> : public boost::array<double, 5>\r\n{\r\npublic:\r\n    pid_step_adjuster_coefficients()\r\n    : boost::array<double, 5>()\r\n    {\r\n        (*this)[0] = 1.0 / 5.0;\r\n        (*this)[1] = 2.0 / 5.0;\r\n        (*this)[2] = 0.0;\r\n        (*this)[3] = 1.0 / 5.0;\r\n        (*this)[4] = 0.0;\r\n    }\r\n};\r\n\r\ntemplate<>\r\nclass pid_step_adjuster_coefficients<H211PI> : public boost::array<double, 5>\r\n{\r\npublic:\r\n    pid_step_adjuster_coefficients()\r\n    : boost::array<double, 5>()\r\n    {\r\n        (*this)[0] = 1.0 / 6.0;\r\n        (*this)[1] = 2.0 / 6.0;\r\n        (*this)[2] = 0.0;\r\n        (*this)[3] = 0.0;\r\n        (*this)[4] = 0.0;\r\n    }\r\n};\r\n\r\ntemplate<>\r\nclass pid_step_adjuster_coefficients<H0312> : public boost::array<double, 5>\r\n{\r\npublic:\r\n    pid_step_adjuster_coefficients()\r\n    : boost::array<double, 5>()\r\n    {\r\n        (*this)[0] = 1.0 / 4.0;\r\n        (*this)[1] = 2.0 / 2.0;\r\n        (*this)[2] = 1.0 / 4.0;\r\n        (*this)[3] = 3.0 / 4.0;\r\n        (*this)[4] = 1.0 / 4.0;\r\n    }\r\n};\r\n\r\ntemplate<>\r\nclass pid_step_adjuster_coefficients<H312b> : public boost::array<double, 5>\r\n{\r\npublic:\r\n    pid_step_adjuster_coefficients()\r\n    : boost::array<double, 5>()\r\n    {\r\n        (*this)[0] = 1.0 / 6.0;\r\n        (*this)[1] = 2.0 / 6.0;\r\n        (*this)[2] = 1.0 / 6.0;\r\n        (*this)[3] = 3.0 / 6.0;\r\n        (*this)[4] = 1.0 / 6.0;\r\n    }\r\n};\r\n\r\ntemplate<>\r\nclass pid_step_adjuster_coefficients<H312PID> : public boost::array<double, 5>\r\n{\r\npublic:\r\n    pid_step_adjuster_coefficients()\r\n    : boost::array<double, 5>()\r\n    {\r\n        (*this)[0] = 1.0 / 18.0;\r\n        (*this)[1] = 2.0 / 9.0;\r\n        (*this)[2] = 1.0 / 18.0;\r\n        (*this)[3] = 0.0;\r\n        (*this)[4] = 0.0;\r\n    }\r\n};\r\n\r\ntemplate<>\r\nclass pid_step_adjuster_coefficients<H0321> : public boost::array<double, 5>\r\n{\r\npublic:\r\n    pid_step_adjuster_coefficients()\r\n    : boost::array<double, 5>()\r\n    {\r\n        (*this)[0] =  5.0 / 4.0;\r\n        (*this)[1] =  1.0 / 2.0;\r\n        (*this)[2] = -3.0 / 4.0;\r\n        (*this)[3] = -1.0 / 4.0;\r\n        (*this)[4] = -3.0 / 4.0;\r\n    }\r\n};\r\n\r\ntemplate<>\r\nclass pid_step_adjuster_coefficients<H321> : public boost::array<double, 5>\r\n{\r\npublic:\r\n    pid_step_adjuster_coefficients()\r\n    : boost::array<double, 5>()\r\n    {\r\n        (*this)[0] =  1.0 / 3.0;\r\n        (*this)[1] =  1.0 / 18.0;\r\n        (*this)[2] = -5.0 / 18.0;\r\n        (*this)[3] = -5.0 / 16.0;\r\n        (*this)[4] = -1.0 / 6.0;\r\n    }\r\n};\r\n\r\n} // detail\r\n} // odeint\r\n} // numeric\r\n} // boost\r\n\r\n#endif", "meta": {"hexsha": "db70f28a35b91f9a0196692706cda6a90e142f22", "size": 4077, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/numeric/odeint/stepper/detail/pid_step_adjuster_coefficients.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/numeric/odeint/stepper/detail/pid_step_adjuster_coefficients.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/numeric/odeint/stepper/detail/pid_step_adjuster_coefficients.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": 22.65, "max_line_length": 88, "alphanum_fraction": 0.5344616139, "num_tokens": 1385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2582924592541448}}
{"text": "#include <stdlib.h>\n#include <stdio.h>\n#include <omp.h>\n#include <chrono>\n#include <vector>\n#include <string>\n#include <sstream>\n#include <iostream>\n#include <stdexcept>\n#include <Eigen/Geometry>\n#include <visualization_msgs/Marker.h>\n#include <arc_utilities/eigen_helpers.hpp>\n#include <arc_utilities/voxel_grid.hpp>\n#include <arc_utilities/pretty_print.hpp>\n#include <sdf_tools/sdf.hpp>\n\n#ifndef SDF_GENERATION_HPP\n#define SDF_GENERATION_HPP\n\nnamespace sdf_generation\n{\nstruct bucket_cell\n{\n  double distance_square;\n  int32_t update_direction;\n  uint32_t location[3];\n  uint32_t closest_point[3];\n};\n\ntypedef VoxelGrid::VoxelGrid<bucket_cell> DistanceField;\n\ninline int32_t GetDirectionNumber(\n    const int32_t dx, const int32_t dy, const int32_t dz)\n{\n  return ((dx + 1) * 9) + ((dy + 1) * 3) + (dz + 1);\n}\n\ninline std::vector<std::vector<std::vector<std::vector<int32_t>>>>\nMakeNeighborhoods()\n{\n  // First vector<>: 2 - the first bucket queue, the points we know are zero\n  // distance, start with a complete set of neighbors to check. Every other\n  // bucket queue checks fewer neighbors.\n  // Second vector<>: 27 (# of source directions in fully-connected 3d grid).\n  // Third vector<>:\n  std::vector<std::vector<std::vector<std::vector<int32_t>>>> neighborhoods;\n  // I don't know why there are 2 initial neighborhoods.\n  neighborhoods.resize(2);\n  for (size_t n = 0; n < neighborhoods.size(); n++)\n  {\n    neighborhoods[n].resize(27);\n    // Loop through the source directions.\n    for (int32_t dx = -1; dx <= 1; dx++)\n    {\n      for (int32_t dy = -1; dy <= 1; dy++)\n      {\n        for (int32_t dz = -1; dz <= 1; dz++)\n        {\n          const int32_t direction_number = GetDirectionNumber(dx, dy, dz);\n          // Loop through the target directions.\n          for (int32_t tdx = -1; tdx <= 1; tdx++)\n          {\n            for (int32_t tdy = -1; tdy <= 1; tdy++)\n            {\n              for (int32_t tdz = -1; tdz <= 1; tdz++)\n              {\n                // Ignore the case of ourself.\n                if (tdx == 0 && tdy == 0 && tdz == 0)\n                {\n                  continue;\n                }\n                // Why is one set of neighborhoods larger than the other?\n                if (n >= 1)\n                {\n                  if ((abs(tdx) + abs(tdy) + abs(tdz)) != 1)\n                  {\n                    continue;\n                  }\n                  if ((dx * tdx) < 0 || (dy * tdy) < 0 || (dz * tdz) < 0)\n                  {\n                    continue;\n                  }\n                }\n                std::vector<int32_t> new_point;\n                new_point.resize(3);\n                new_point[0] = tdx;\n                new_point[1] = tdy;\n                new_point[2] = tdz;\n                neighborhoods[n][direction_number].push_back(new_point);\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n  return neighborhoods;\n}\n\ninline double ComputeDistanceSquared(\n    const int32_t x1, const int32_t y1, const int32_t z1,\n    const int32_t x2, const int32_t y2, const int32_t z2)\n{\n  const int32_t dx = x1 - x2;\n  const int32_t dy = y1 - y2;\n  const int32_t dz = z1 - z2;\n  return double((dx * dx) + (dy * dy) + (dz * dz));\n}\n\nclass MultipleThreadIndexQueueWrapper\n{\npublic:\n\n  explicit MultipleThreadIndexQueueWrapper(const size_t max_queues)\n  {\n    per_thread_queues_.resize(\n          GetNumOMPThreads(), ThreadIndexQueues(max_queues));\n  }\n\n  const VoxelGrid::GRID_INDEX& Query(\n      const int32_t distance_squared, const size_t idx) const\n  {\n    size_t working_index = idx;\n    for (size_t thread = 0; thread < per_thread_queues_.size(); thread++)\n    {\n      const auto& current_thread_queue =\n          per_thread_queues_.at(thread).at(distance_squared);\n      const size_t current_thread_queue_size = current_thread_queue.size();\n      if (working_index < current_thread_queue_size)\n      {\n        return current_thread_queue.at(working_index);\n      }\n      else\n      {\n        working_index -= current_thread_queue_size;\n      }\n    }\n    throw std::runtime_error(\"Failed to find item\");\n  }\n\n  size_t NumQueues() const\n  {\n    return per_thread_queues_.at(0).size();\n  }\n\n  size_t Size(const int32_t distance_squared) const\n  {\n    size_t total_size = 0;\n    for (size_t thread = 0; thread < per_thread_queues_.size(); thread++)\n    {\n      total_size += per_thread_queues_.at(thread).at(distance_squared).size();\n    }\n    return total_size;\n  }\n\n  void Enqueue(\n      const int32_t distance_squared, const VoxelGrid::GRID_INDEX& index)\n  {\n#if defined(_OPENMP)\n    const size_t thread_num = (size_t)omp_get_thread_num();\n#else\n    const size_t thread_num = 0;\n#endif\n    per_thread_queues_.at(thread_num).at(distance_squared).push_back(index);\n  }\n\n  void ClearCompletedQueues(const int32_t distance_squared)\n  {\n    for (size_t thread = 0; thread < per_thread_queues_.size(); thread++)\n    {\n      per_thread_queues_.at(thread).at(distance_squared).clear();\n    }\n  }\n\nprivate:\n\n  inline static size_t GetNumOMPThreads()\n  {\n#if defined(_OPENMP)\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  typedef std::vector<std::vector<VoxelGrid::GRID_INDEX>> ThreadIndexQueues;\n  std::vector<ThreadIndexQueues> per_thread_queues_;\n\n};\n\ninline DistanceField BuildDistanceFieldSerial(\n    const Eigen::Isometry3d& grid_origin_transform,\n    const double grid_resolution,\n    const int64_t grid_num_x_cells,\n    const int64_t grid_num_y_cells,\n    const int64_t grid_num_z_cells,\n    const std::vector<VoxelGrid::GRID_INDEX>& points)\n{\n  const std::chrono::time_point<std::chrono::steady_clock> start_time\n      = std::chrono::steady_clock::now();\n  // Make the DistanceField container\n  bucket_cell default_cell;\n  default_cell.distance_square = std::numeric_limits<double>::infinity();\n  DistanceField distance_field(grid_origin_transform, grid_resolution,\n                               grid_num_x_cells, grid_num_y_cells,\n                               grid_num_z_cells, default_cell);\n  // Compute maximum distance square\n  const int64_t max_distance_square =\n      (distance_field.GetNumXCells() * distance_field.GetNumXCells())\n      + (distance_field.GetNumYCells() * distance_field.GetNumYCells())\n      + (distance_field.GetNumZCells() * distance_field.GetNumZCells());\n  // Make bucket queue\n  std::vector<std::vector<bucket_cell>> bucket_queue(max_distance_square + 1);\n  bucket_queue[0].reserve(points.size());\n  // Set initial update direction\n  int32_t initial_update_direction = GetDirectionNumber(0, 0, 0);\n  // Mark all provided points with distance zero and add to the bucket queue\n  for (size_t index = 0; index < points.size(); index++)\n  {\n    const VoxelGrid::GRID_INDEX& current_index = points[index];\n    auto query = distance_field.GetMutable(current_index);\n    if (query)\n    {\n      query.Value().location[0] = (uint32_t)current_index.x;\n      query.Value().location[1] = (uint32_t)current_index.y;\n      query.Value().location[2] = (uint32_t)current_index.z;\n      query.Value().closest_point[0] = (uint32_t)current_index.x;\n      query.Value().closest_point[1] = (uint32_t)current_index.y;\n      query.Value().closest_point[2] = (uint32_t)current_index.z;\n      query.Value().distance_square = 0.0;\n      query.Value().update_direction = initial_update_direction;\n      bucket_queue[0].push_back(query.Value());\n    }\n    // If the point is outside the bounds of the SDF, skip\n    else\n    {\n      throw std::runtime_error(\"Point for BuildDistanceField out of bounds\");\n    }\n  }\n  // HERE BE DRAGONS\n  // Process the bucket queue\n  const std::vector<std::vector<std::vector<std::vector<int>>>> neighborhoods =\n      MakeNeighborhoods();\n  for (size_t bq_idx = 0; bq_idx < bucket_queue.size(); bq_idx++)\n  {\n    for (const auto& cur_cell : bucket_queue[bq_idx])\n    {\n      // Get the current location\n      const double x = cur_cell.location[0];\n      const double y = cur_cell.location[1];\n      const double z = cur_cell.location[2];\n      // Pick the update direction\n      // Only the first bucket queue gets the larger set of neighborhoods?\n      // Don't really userstand why.\n      const size_t direction_switch = (bq_idx > 0) ? 1 : 0;\n      // Make sure the update direction is valid\n      if (cur_cell.update_direction < 0 || cur_cell.update_direction > 26)\n      {\n        continue;\n      }\n      // Get the current neighborhood list\n      const std::vector<std::vector<int>>& neighborhood =\n          neighborhoods[direction_switch][cur_cell.update_direction];\n      // Update the distance from the neighboring cells\n      for (size_t nh_idx = 0; nh_idx < neighborhood.size(); nh_idx++)\n      {\n        // Get the direction to check\n        const int dx = neighborhood[nh_idx][0];\n        const int dy = neighborhood[nh_idx][1];\n        const int dz = neighborhood[nh_idx][2];\n        const int nx = x + dx;\n        const int ny = y + dy;\n        const int nz = z + dz;\n        auto neighbor_query =\n            distance_field.GetMutable((int64_t)nx, (int64_t)ny, (int64_t)nz);\n        if (!neighbor_query)\n        {\n          // \"Neighbor\" is outside the bounds of the SDF\n          continue;\n        }\n        // Update the neighbor's distance based on the current\n        const int32_t new_distance_square =\n            (int32_t)ComputeDistanceSquared(nx, ny, nz,\n                                            cur_cell.closest_point[0],\n                                            cur_cell.closest_point[1],\n                                            cur_cell.closest_point[2]);\n        if (new_distance_square > max_distance_square)\n        {\n          // Skip these cases\n          continue;\n        }\n        if (new_distance_square < neighbor_query.Value().distance_square)\n        {\n          // If the distance is better, time to update the neighbor\n          neighbor_query.Value().distance_square = new_distance_square;\n          neighbor_query.Value().closest_point[0] = cur_cell.closest_point[0];\n          neighbor_query.Value().closest_point[1] = cur_cell.closest_point[1];\n          neighbor_query.Value().closest_point[2] = cur_cell.closest_point[2];\n          neighbor_query.Value().location[0] = nx;\n          neighbor_query.Value().location[1] = ny;\n          neighbor_query.Value().location[2] = nz;\n          neighbor_query.Value().update_direction =\n              GetDirectionNumber(dx, dy, dz);\n          // Add the neighbor into the bucket queue\n          bucket_queue[new_distance_square].push_back(neighbor_query.Value());\n        }\n      }\n    }\n    // Clear the current queue now that we're done with it\n    bucket_queue[bq_idx].clear();\n  }\n  const std::chrono::time_point<std::chrono::steady_clock> end_time\n      = std::chrono::steady_clock::now();\n  const std::chrono::duration<double> elapsed = end_time - start_time;\n  std::cout << \"Computed DistanceField for grid size (\" << grid_num_x_cells\n            << \", \" << grid_num_y_cells << \", \" << grid_num_z_cells << \") in \"\n            << elapsed.count() << \" seconds\" << std::endl;\n  return distance_field;\n}\n\ninline DistanceField BuildDistanceFieldParallel(\n    const Eigen::Isometry3d& grid_origin_transform,\n    const double grid_resolution,\n    const int64_t grid_num_x_cells,\n    const int64_t grid_num_y_cells,\n    const int64_t grid_num_z_cells,\n    const std::vector<VoxelGrid::GRID_INDEX>& points)\n{\n  const std::chrono::time_point<std::chrono::steady_clock> start_time\n      = std::chrono::steady_clock::now();\n  // Make the DistanceField container\n  bucket_cell default_cell;\n  default_cell.distance_square = std::numeric_limits<double>::infinity();\n  DistanceField distance_field(grid_origin_transform, grid_resolution,\n                               grid_num_x_cells, grid_num_y_cells,\n                               grid_num_z_cells, default_cell);\n  // Compute maximum distance square\n  const int64_t max_distance_square =\n      (distance_field.GetNumXCells() * distance_field.GetNumXCells())\n      + (distance_field.GetNumYCells() * distance_field.GetNumYCells())\n      + (distance_field.GetNumZCells() * distance_field.GetNumZCells());\n  // Make bucket queue\n  std::vector<std::vector<bucket_cell>> bucket_queue(max_distance_square + 1);\n  bucket_queue[0].reserve(points.size());\n  MultipleThreadIndexQueueWrapper bucket_queues(max_distance_square + 1);\n  // Set initial update direction\n  int32_t initial_update_direction = GetDirectionNumber(0, 0, 0);\n  // Mark all provided points with distance zero and add to the bucket queues\n  // points MUST NOT CONTAIN DUPLICATE ENTRIES!\n#if defined(_OPENMP)\n#pragma omp parallel for\n#endif\n  for (size_t index = 0; index < points.size(); index++)\n  {\n    const VoxelGrid::GRID_INDEX& current_index = points[index];\n    auto query = distance_field.GetMutable(current_index);\n    if (query)\n    {\n      query.Value().location[0] = (uint32_t)current_index.x;\n      query.Value().location[1] = (uint32_t)current_index.y;\n      query.Value().location[2] = (uint32_t)current_index.z;\n      query.Value().closest_point[0] = (uint32_t)current_index.x;\n      query.Value().closest_point[1] = (uint32_t)current_index.y;\n      query.Value().closest_point[2] = (uint32_t)current_index.z;\n      query.Value().distance_square = 0.0;\n      query.Value().update_direction = initial_update_direction;\n      bucket_queues.Enqueue(0, current_index);\n    }\n    // If the point is outside the bounds of the SDF, skip\n    else\n    {\n      throw std::runtime_error(\"Point for BuildDistanceField out of bounds\");\n    }\n  }\n  // HERE BE DRAGONS\n  // Process the bucket queue\n  const std::vector<std::vector<std::vector<std::vector<int>>>> neighborhoods =\n      MakeNeighborhoods();\n  for (int32_t current_distance_square = 0;\n       current_distance_square < (int32_t)bucket_queues.NumQueues();\n       current_distance_square++)\n  {\n#if defined(_OPENMP)\n#pragma omp parallel for\n#endif\n    for (size_t idx = 0; idx < bucket_queues.Size(current_distance_square);\n         idx++)\n    {\n      const VoxelGrid::GRID_INDEX& current_index =\n          bucket_queues.Query(current_distance_square, idx);\n      // Get the current location\n      const bucket_cell& cur_cell =\n          distance_field.GetImmutable(current_index).Value();\n      const double x = cur_cell.location[0];\n      const double y = cur_cell.location[1];\n      const double z = cur_cell.location[2];\n      // Pick the update direction\n      // Only the first bucket queue gets the larger set of neighborhoods?\n      // Don't really userstand why.\n      const size_t direction_switch = (current_distance_square > 0) ? 1 : 0;\n      // Make sure the update direction is valid\n      if (cur_cell.update_direction < 0 || cur_cell.update_direction > 26)\n      {\n        continue;\n      }\n      // Get the current neighborhood list\n      const std::vector<std::vector<int32_t>>& neighborhood =\n          neighborhoods[direction_switch][cur_cell.update_direction];\n      // Update the distance from the neighboring cells\n      for (size_t nh_idx = 0; nh_idx < neighborhood.size(); nh_idx++)\n      {\n        // Get the direction to check\n        const int32_t dx = neighborhood[nh_idx][0];\n        const int32_t dy = neighborhood[nh_idx][1];\n        const int32_t dz = neighborhood[nh_idx][2];\n        const int32_t nx = (int32_t)(x + dx);\n        const int32_t ny = (int32_t)(y + dy);\n        const int32_t nz = (int32_t)(z + dz);\n        const VoxelGrid::GRID_INDEX neighbor_index(\n              (int64_t)nx, (int64_t)ny, (int64_t)nz);\n        auto neighbor_query = distance_field.GetMutable(neighbor_index);\n        if (!neighbor_query)\n        {\n          // \"Neighbor\" is outside the bounds of the SDF\n          continue;\n        }\n        // Update the neighbor's distance based on the current\n        const int32_t new_distance_square =\n            (int32_t)ComputeDistanceSquared(nx, ny, nz,\n                                            cur_cell.closest_point[0],\n                                            cur_cell.closest_point[1],\n                                            cur_cell.closest_point[2]);\n        if (new_distance_square > max_distance_square)\n        {\n          // Skip these cases\n          continue;\n        }\n        if (new_distance_square < neighbor_query.Value().distance_square)\n        {\n          // If the distance is better, time to update the neighbor\n          neighbor_query.Value().distance_square = new_distance_square;\n          neighbor_query.Value().closest_point[0] = cur_cell.closest_point[0];\n          neighbor_query.Value().closest_point[1] = cur_cell.closest_point[1];\n          neighbor_query.Value().closest_point[2] = cur_cell.closest_point[2];\n          neighbor_query.Value().location[0] = nx;\n          neighbor_query.Value().location[1] = ny;\n          neighbor_query.Value().location[2] = nz;\n          neighbor_query.Value().update_direction =\n              GetDirectionNumber(dx, dy, dz);\n          // Add the neighbor into the bucket queue\n          bucket_queues.Enqueue(new_distance_square, neighbor_index);\n        }\n      }\n    }\n    // Clear the current queues now that we're done with it\n    bucket_queues.ClearCompletedQueues(current_distance_square);\n  }\n  const std::chrono::time_point<std::chrono::steady_clock> end_time\n      = std::chrono::steady_clock::now();\n  const std::chrono::duration<double> elapsed = end_time - start_time;\n  std::cout << \"Computed DistanceField for grid size (\" << grid_num_x_cells\n            << \", \" << grid_num_y_cells << \", \" << grid_num_z_cells << \") in \"\n            << elapsed.count() << \" seconds\" << std::endl;\n  return distance_field;\n}\n\n#define COMPARE_DISTANCE_FIELD_GENERATION\n\ninline DistanceField BuildDistanceField(\n    const Eigen::Isometry3d& grid_origin_transform,\n    const double grid_resolution,\n    const int64_t grid_num_x_cells,\n    const int64_t grid_num_y_cells,\n    const int64_t grid_num_z_cells,\n    const std::vector<VoxelGrid::GRID_INDEX>& points)\n{\n#ifdef COMPARE_DISTANCE_FIELD_GENERATION\n  const DistanceField legacy_field =\n      BuildDistanceFieldSerial(grid_origin_transform, grid_resolution,\n                               grid_num_x_cells, grid_num_y_cells,\n                               grid_num_z_cells, points);\n  const DistanceField new_field =\n      BuildDistanceFieldParallel(grid_origin_transform, grid_resolution,\n                                 grid_num_x_cells, grid_num_y_cells,\n                                 grid_num_z_cells, points);\n  for (int64_t x_index = 0; x_index < grid_num_x_cells; x_index++)\n  {\n    for (int64_t y_index = 0; y_index < grid_num_y_cells; y_index++)\n    {\n      for (int64_t z_index = 0; z_index < grid_num_z_cells; z_index++)\n      {\n        const bucket_cell& legacy_cell =\n            legacy_field.GetImmutable(x_index, y_index, z_index).Value();\n        const bucket_cell& new_cell =\n            new_field.GetImmutable(x_index, y_index, z_index).Value();\n        const double legacy_distance = legacy_cell.distance_square;\n        const double new_distance = new_cell.distance_square;\n        const double new_delta = std::abs(new_distance - legacy_distance);\n        assert(new_delta < 1e-6);\n      }\n    }\n  }\n  return new_field;\n#else\n  // Should we use the parallelizable new variant or the serial legacy variant?\n  if (points.size() > 1000)\n  {\n    return BuildDistanceFieldParallel(grid_origin_transform, grid_resolution,\n                                      grid_num_x_cells, grid_num_y_cells,\n                                      grid_num_z_cells, points);\n  }\n  else\n  {\n    return BuildDistanceFieldSerial(grid_origin_transform, grid_resolution,\n                                    grid_num_x_cells, grid_num_y_cells,\n                                    grid_num_z_cells, points);\n  }\n#endif\n}\n\ntemplate<typename T>\ninline std::pair<sdf_tools::SignedDistanceField, std::pair<double, double>>\nExtractSignedDistanceField(\n    const Eigen::Isometry3d& grid_origin_tranform,\n    const double grid_resolution,\n    const int64_t grid_num_x_cells,\n    const int64_t grid_num_y_cells,\n    const int64_t grid_num_z_cells,\n    const std::function<bool(const VoxelGrid::GRID_INDEX&)>& is_filled_fn,\n    const float oob_value,\n    const std::string& frame)\n{\n  const std::chrono::time_point<std::chrono::steady_clock> start_time\n      = std::chrono::steady_clock::now();\n  std::vector<VoxelGrid::GRID_INDEX> filled;\n  std::vector<VoxelGrid::GRID_INDEX> free;\n  for (int64_t x_index = 0; x_index < grid_num_x_cells; x_index++)\n  {\n    for (int64_t y_index = 0; y_index < grid_num_y_cells; y_index++)\n    {\n      for (int64_t z_index = 0; z_index < grid_num_z_cells; z_index++)\n      {\n        const VoxelGrid::GRID_INDEX current_index(x_index, y_index, z_index);\n        if (is_filled_fn(current_index))\n        {\n          // Mark as filled\n          filled.push_back(current_index);\n        }\n        else\n        {\n          // Mark as free space\n          free.push_back(current_index);\n        }\n      }\n    }\n  }\n  // Make two distance fields, one for distance to filled voxels, one for\n  // distance to free voxels.\n  const DistanceField filled_distance_field =\n      BuildDistanceField(grid_origin_tranform, grid_resolution,\n                         grid_num_x_cells, grid_num_y_cells, grid_num_z_cells,\n                         filled);\n  const DistanceField free_distance_field =\n      BuildDistanceField(grid_origin_tranform, grid_resolution,\n                         grid_num_x_cells, grid_num_y_cells, grid_num_z_cells,\n                         free);\n  // Generate the SDF\n  sdf_tools::SignedDistanceField new_sdf(\n        grid_origin_tranform, frame, grid_resolution, grid_num_x_cells,\n        grid_num_y_cells, grid_num_z_cells, oob_value);\n  double max_distance = -std::numeric_limits<double>::infinity();\n  double min_distance = std::numeric_limits<double>::infinity();\n  for (int64_t x_index = 0; x_index < new_sdf.GetNumXCells(); x_index++)\n  {\n    for (int64_t y_index = 0; y_index < new_sdf.GetNumYCells(); y_index++)\n    {\n      // Parallelize across the Z-axis, since VoxelGrid ensures Z-axis cells are\n      // contiguous in memory.\n#if defined(_OPENMP)\n#pragma omp parallel for\n#endif\n      for (int64_t z_index = 0; z_index < new_sdf.GetNumZCells(); z_index++)\n      {\n        const double distance1 =\n            std::sqrt(\n              filled_distance_field.GetImmutable(x_index, y_index, z_index)\n                .Value().distance_square)\n            * new_sdf.GetResolution();\n        const double distance2 =\n            std::sqrt(\n              free_distance_field.GetImmutable(x_index, y_index, z_index)\n                .Value().distance_square)\n            * new_sdf.GetResolution();\n        const double distance = distance1 - distance2;\n        if (distance > max_distance)\n        {\n          max_distance = distance;\n        }\n        if (distance < min_distance)\n        {\n          min_distance = distance;\n        }\n        new_sdf.SetValue(x_index, y_index, z_index, (float)distance);\n      }\n    }\n  }\n  const std::chrono::time_point<std::chrono::steady_clock> end_time\n      = std::chrono::steady_clock::now();\n  const std::chrono::duration<double> elapsed = end_time - start_time;\n  std::cout << \"Computed SDF for grid size (\" << grid_num_x_cells << \", \"\n            << grid_num_y_cells << \", \" << grid_num_z_cells << \") in \"\n            << elapsed.count() << \" seconds\" << std::endl;\n  std::pair<double, double> extrema(max_distance, min_distance);\n  return std::pair<sdf_tools::SignedDistanceField,\n                   std::pair<double, double>>(new_sdf, extrema);\n}\n\ntemplate<typename T, typename BackingStore=std::vector<T>>\ninline std::pair<sdf_tools::SignedDistanceField, std::pair<double, double>>\nExtractSignedDistanceField(\n    const VoxelGrid::VoxelGrid<T, BackingStore>& grid,\n    const std::function<bool(const VoxelGrid::GRID_INDEX&)>& is_filled_fn,\n    const float oob_value, const std::string& frame,\n    const bool add_virtual_border)\n{\n  (void)(add_virtual_border);\n  const Eigen::Vector3d cell_sizes = grid.GetCellSizes();\n  if ((cell_sizes.x() != cell_sizes.y()) || (cell_sizes.x() != cell_sizes.z()))\n  {\n    throw std::invalid_argument(\"Grid must have uniform resolution\");\n  }\n  if (add_virtual_border == false)\n  {\n    // This is the conventional single-pass result\n    return ExtractSignedDistanceField<T>(\n          grid.GetOriginTransform(), cell_sizes.x(), grid.GetNumXCells(),\n          grid.GetNumYCells(), grid.GetNumZCells(), is_filled_fn, oob_value,\n          frame);\n  }\n  else\n  {\n    const int64_t x_axis_size_offset =\n        (grid.GetNumXCells() > 1) ? (int64_t)2 : (int64_t)0;\n    const int64_t x_axis_query_offset =\n        (grid.GetNumXCells() > 1) ? (int64_t)1 : (int64_t)0;\n    const int64_t y_axis_size_offset =\n        (grid.GetNumYCells() > 1) ? (int64_t)2 : (int64_t)0;\n    const int64_t y_axis_query_offset =\n        (grid.GetNumYCells() > 1) ? (int64_t)1 : (int64_t)0;\n    const int64_t z_axis_size_offset =\n        (grid.GetNumZCells() > 1) ? (int64_t)2 : (int64_t)0;\n    const int64_t z_axis_query_offset =\n        (grid.GetNumZCells() > 1) ? (int64_t)1 : (int64_t)0;\n    // We need to lie about the size of the grid to add a virtual border\n    const int64_t num_x_cells = grid.GetNumXCells() + x_axis_size_offset;\n    const int64_t num_y_cells = grid.GetNumYCells() + y_axis_size_offset;\n    const int64_t num_z_cells = grid.GetNumZCells() + z_axis_size_offset;\n    // Make some deceitful helper functions that hide our lies about size\n    // For the free space SDF, we lie and say the virtual border is filled\n    const std::function<bool(const VoxelGrid::GRID_INDEX&)> free_is_filled_fn\n        = [&] (const VoxelGrid::GRID_INDEX& virtual_border_grid_index)\n    {\n      // Is there a virtual border on our axis?\n      if (x_axis_size_offset > 0)\n      {\n        // Are we a virtual border cell?\n        if ((virtual_border_grid_index.x == 0)\n            || (virtual_border_grid_index.x == (num_x_cells - 1)))\n        {\n          return true;\n        }\n      }\n      // Is there a virtual border on our axis?\n      if (y_axis_size_offset > 0)\n      {\n        // Are we a virtual border cell?\n        if ((virtual_border_grid_index.y == 0)\n            || (virtual_border_grid_index.y == (num_y_cells - 1)))\n        {\n          return true;\n        }\n      }\n      // Is there a virtual border on our axis?\n      if (z_axis_size_offset > 0)\n      {\n        // Are we a virtual border cell?\n        if ((virtual_border_grid_index.z == 0)\n            || (virtual_border_grid_index.z == (num_z_cells - 1)))\n        {\n          return true;\n        }\n      }\n      const VoxelGrid::GRID_INDEX real_grid_index(\n            virtual_border_grid_index.x - x_axis_query_offset,\n            virtual_border_grid_index.y - y_axis_query_offset,\n            virtual_border_grid_index.z - z_axis_query_offset);\n      return is_filled_fn(real_grid_index);\n    };\n    // For the filled space SDF, we lie and say the virtual border is empty\n    const std::function<bool(const VoxelGrid::GRID_INDEX&)> filled_is_filled_fn\n        = [&] (const VoxelGrid::GRID_INDEX& virtual_border_grid_index)\n    {\n      // Is there a virtual border on our axis?\n      if (x_axis_size_offset > 0)\n      {\n        // Are we a virtual border cell?\n        if ((virtual_border_grid_index.x == 0)\n            || (virtual_border_grid_index.x == (num_x_cells - 1)))\n        {\n          return false;\n        }\n      }\n      // Is there a virtual border on our axis?\n      if (y_axis_size_offset > 0)\n      {\n        // Are we a virtual border cell?\n        if ((virtual_border_grid_index.y == 0)\n            || (virtual_border_grid_index.y == (num_y_cells - 1)))\n        {\n          return false;\n        }\n      }\n      // Is there a virtual border on our axis?\n      if (z_axis_size_offset > 0)\n      {\n        // Are we a virtual border cell?\n        if ((virtual_border_grid_index.z == 0)\n            || (virtual_border_grid_index.z == (num_z_cells - 1)))\n        {\n          return false;\n        }\n      }\n      const VoxelGrid::GRID_INDEX real_grid_index(\n            virtual_border_grid_index.x - x_axis_query_offset,\n            virtual_border_grid_index.y - y_axis_query_offset,\n            virtual_border_grid_index.z - z_axis_query_offset);\n      return is_filled_fn(real_grid_index);\n    };\n    // Make both SDFs\n    auto free_sdf_result = ExtractSignedDistanceField<T>(\n                             grid.GetOriginTransform(), cell_sizes.x(),\n                             num_x_cells, num_y_cells, num_z_cells,\n                             free_is_filled_fn, oob_value, frame);\n    auto filled_sdf_result = ExtractSignedDistanceField<T>(\n                               grid.GetOriginTransform(), cell_sizes.x(),\n                               num_x_cells, num_y_cells, num_z_cells,\n                               filled_is_filled_fn, oob_value, frame);\n    // Combine to make a single SDF\n    sdf_tools::SignedDistanceField combined_sdf(\n          grid.GetOriginTransform(), frame, cell_sizes.x(), grid.GetNumXCells(),\n          grid.GetNumYCells(), grid.GetNumZCells(), oob_value);\n    for (int64_t x_idx = 0; x_idx < combined_sdf.GetNumXCells(); x_idx++)\n    {\n      for (int64_t y_idx = 0; y_idx < combined_sdf.GetNumYCells(); y_idx++)\n      {\n        // Parallelize across the Z-axis, since VoxelGrid ensures Z-axis cells\n        // are contiguous in memory.\n#if defined(_OPENMP)\n#pragma omp parallel for\n#endif\n        for (int64_t z_idx = 0; z_idx < combined_sdf.GetNumZCells(); z_idx++)\n        {\n          const int64_t query_x_idx = x_idx + x_axis_query_offset;\n          const int64_t query_y_idx = y_idx + y_axis_query_offset;\n          const int64_t query_z_idx = z_idx + z_axis_query_offset;\n          const float free_sdf_value\n              = free_sdf_result.first.GetImmutable(\n                  query_x_idx, query_y_idx, query_z_idx).Value();\n          const float filled_sdf_value\n              = filled_sdf_result.first.GetImmutable(\n                  query_x_idx, query_y_idx, query_z_idx).Value();\n          if (free_sdf_value >= 0.0)\n          {\n            combined_sdf.SetValue(x_idx, y_idx, z_idx, free_sdf_value);\n          }\n          else if (filled_sdf_value <= -0.0)\n          {\n            combined_sdf.SetValue(x_idx, y_idx, z_idx, filled_sdf_value);\n          }\n          else\n          {\n            combined_sdf.SetValue(x_idx, y_idx, z_idx, 0.0f);\n          }\n        }\n      }\n    }\n    // Get the combined max/min values\n    const std::pair<double, double> combined_extrema(\n          free_sdf_result.second.first, filled_sdf_result.second.second);\n    return std::make_pair(combined_sdf, combined_extrema);\n  }\n}\n\ntemplate<typename T, typename BackingStore=std::vector<T>>\ninline std::pair<sdf_tools::SignedDistanceField, std::pair<double, double>>\nExtractSignedDistanceField(const VoxelGrid::VoxelGrid<T, BackingStore>& grid,\n                           const std::function<bool(const T&)>& is_filled_fn,\n                           const float oob_value, const std::string& frame)\n{\n  const std::function<bool(const VoxelGrid::GRID_INDEX&)> real_is_filled_fn =\n      [&] (const VoxelGrid::GRID_INDEX& index)\n  {\n    const T& stored = grid.GetImmutable(index).Value();\n    // If it matches an object to use OR there are no objects supplied\n    if (is_filled_fn(stored))\n    {\n      // Mark as filled\n      return true;\n    }\n    else\n    {\n      // Mark as free space\n      return false;\n    }\n  };\n  return ExtractSignedDistanceField(\n        grid, real_is_filled_fn, oob_value, frame, false);\n}\n}\n\n#endif // SDF_GENERATION_HPP\n", "meta": {"hexsha": "f01214d147c16a46f3727bb679e84200da2583e9", "size": 31644, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sdf_tools/sdf_generation.hpp", "max_stars_repo_name": "calderpg/sdf_tools", "max_stars_repo_head_hexsha": "3c12a1fa6975b76c1b82cd2525ac50593e3da76d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/sdf_tools/sdf_generation.hpp", "max_issues_repo_name": "calderpg/sdf_tools", "max_issues_repo_head_hexsha": "3c12a1fa6975b76c1b82cd2525ac50593e3da76d", "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/sdf_tools/sdf_generation.hpp", "max_forks_repo_name": "calderpg/sdf_tools", "max_forks_repo_head_hexsha": "3c12a1fa6975b76c1b82cd2525ac50593e3da76d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-11-06T21:39:27.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-06T21:39:27.000Z", "avg_line_length": 38.2636033857, "max_line_length": 80, "alphanum_fraction": 0.6363291619, "num_tokens": 7602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.25816942523552405}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   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_FACTORIZATIONS_SYMEIG_HPP_INCLUDED\n#define NT2_LINALG_FUNCTIONS_FACTORIZATIONS_SYMEIG_HPP_INCLUDED\n\n#include <nt2/include/functions/symeig.hpp>\n#include <boost/dispatch/attributes.hpp>\n#include <nt2/include/functions/from_diag.hpp>\n#include <nt2/include/functions/height.hpp>\n#include <nt2/include/functions/hsev_w.hpp>\n#include <nt2/include/functions/hsev_wu.hpp>\n#include <nt2/include/functions/of_size.hpp>\n#include <nt2/include/functions/real.hpp>\n#include <nt2/include/functions/resize.hpp>\n#include <nt2/include/functions/tie.hpp>\n#include <nt2/sdk/meta/as_real.hpp>\n#include <nt2/linalg/options.hpp>\n#include <nt2/linalg/details/utility/lapack_verify.hpp>\n#include <nt2/core/utility/assign_swap.hpp>\n#include <nt2/core/container/dsl/as_terminal.hpp>\n#include <nt2/core/container/table/table.hpp>\n\nnamespace nt2 { namespace ext\n{\n  //============================================================================\n  //SYMEIG Scalar\n  //============================================================================\n  BOOST_DISPATCH_IMPLEMENT  ( symeig_, tag::cpu_\n                            , (A0)\n                            , (scalar_<unspecified_<A0> >)\n                            )\n  {\n    typedef typename nt2::meta::as_real<A0>::type result_type;\n\n    BOOST_FORCEINLINE result_type operator()(const A0& a0) const\n    {\n      return real(a0);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( symeig_, tag::cpu_\n                            , (A0)(A1)\n                            , (scalar_<unspecified_<A0> >)\n                              (unspecified_<A1>)\n                            )\n  {\n    typedef typename nt2::meta::as_real<A0>::type result_type;\n\n    BOOST_FORCEINLINE result_type operator()(const A0& a0, const A1&) const\n    {\n      return real(a0);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( symeig_, tag::cpu_\n                            , (A0)(A1)(A2)\n                            , (scalar_<unspecified_<A0> >)\n                              (unspecified_<A1>)\n                              (unspecified_<A2>)\n                            )\n  {\n    typedef typename nt2::meta::as_real<A0>::type result_type;\n\n    BOOST_FORCEINLINE result_type operator()(const A0& a0, const A1&, const A2&) const\n    {\n      return real(a0);\n    }\n  };\n\n\n  //============================================================================\n  //SYMEIG\n  //============================================================================\n  BOOST_DISPATCH_IMPLEMENT  ( symeig_, tag::cpu_\n                            , (A0)(N0)(A1)(N1)\n                            , ((node_<A0, nt2::tag::symeig_\n                                    , N0, nt2::container::domain\n                                      >\n                              ))\n                              ((node_<A1, nt2::tag::tie_\n                                    , N1, nt2::container::domain\n                                     >\n                              ))\n                            )\n  {\n    typedef void  result_type;\n    typedef typename boost::proto::result_of::child_c<A0&,0>::value_type child0;\n    typedef typename child0::value_type                                  type_t;\n    typedef typename nt2::meta::as_real<type_t>::type                   rtype_t;\n    typedef nt2::memory::container<tag::table_,  type_t, nt2::_2D>   o_semantic;\n    typedef nt2::memory::container<tag::table_, rtype_t, nt2::_2D>   r_semantic;\n\n    BOOST_FORCEINLINE result_type operator()( A0& a0, A1& a1 ) const\n    {\n      eval(a0, a1, N0(), N1());\n    }\n  private:\n    //==========================================================================\n    /// INTERNAL ONLY - W = SYMEIG(A)\n    // returns eigenvalues as a vector\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<1> const&\n              , boost::mpl::long_<1> const&\n              ) const\n    {\n      eval1_3(a0, a1\n             , nt2::policy<ext::vector_>()\n             , nt2::policy<ext::upper_>());\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - W = SYMEIG(A, matrix_/vector_/upper_/lower_/raw_)\n    // returns eigenvalues as a vector\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n                , boost::mpl::long_<2> const&\n                , boost::mpl::long_<1> const&\n                ) const\n    {\n      eval1_2(a0, a1\n             , boost::proto::value(boost::proto::child_c<1>(a0)));\n    }\n\n    BOOST_FORCEINLINE\n    void eval1_2 ( A0& a0, A1& a1\n                    , nt2::policy<ext::vector_>\n                   ) const\n    {\n      eval1_3(a0, a1\n             , nt2::policy<ext::vector_>()\n             , nt2::policy<ext::upper_>());\n    }\n\n    BOOST_FORCEINLINE\n    void eval1_2 ( A0& a0, A1& a1\n                    , nt2::policy<ext::raw_>\n                   ) const\n    {\n      eval1_3(a0, a1\n             , nt2::policy<ext::vector_>()\n             , nt2::policy<ext::upper_>());\n    }\n\n    BOOST_FORCEINLINE\n    void eval1_2 ( A0& a0, A1& a1\n                    , nt2::policy<ext::matrix_>\n                   ) const\n    {\n      eval1_3(a0, a1\n             , nt2::policy<ext::matrix_>()\n             , nt2::policy<ext::upper_>());\n    }\n\n    BOOST_FORCEINLINE\n    void eval1_2 ( A0& a0, A1& a1\n                    , nt2::policy<ext::upper_>\n                   ) const\n    {\n      eval1_3(a0, a1\n             , nt2::policy<ext::vector_>()\n             , nt2::policy<ext::upper_>());\n    }\n\n    BOOST_FORCEINLINE\n    void eval1_2 ( A0& a0, A1& a1\n                    , nt2::policy<ext::lower_>\n                   ) const\n    {\n      eval1_3(a0, a1\n             , nt2::policy<ext::vector_>()\n             , nt2::policy<ext::lower_>());\n    }\n\n\n    //==========================================================================\n    /// INTERNAL ONLY - W = SYMEIG(A, matrix_/vector_, upper_/lower_)\n    // returns eigenvalues as a vector\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<3> const&\n              , boost::mpl::long_<1> const&\n              ) const\n    {\n      eval1_3(a0, a1\n             , boost::proto::value(boost::proto::child_c<1>(a0))\n             , boost::proto::value(boost::proto::child_c<2>(a0))\n             );\n    }\n\n    BOOST_FORCEINLINE\n    void eval1_3 ( A0& a0, A1& a1\n                 , nt2::policy<ext::vector_> const &\n                 , nt2::policy<ext::lower_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> work;\n      NT2_AS_TERMINAL_INOUT(o_semantic, a\n                           , boost::proto::child_c<0>(a0), work);\n      NT2_AS_TERMINAL_OUT  (r_semantic, w\n                           , boost::proto::child_c<0>(a1));\n      w.resize(nt2::of_size(height(a), 1));\n      NT2_LAPACK_VERIFY(nt2::hsev_w( boost::proto::value(a)\n                                   , boost::proto::value(w)\n                                   , 'L'));\n      assign_swap(boost::proto::child_c<0>(a1), w);\n    }\n\n    BOOST_FORCEINLINE\n    void eval1_3 ( A0& a0, A1& a1\n                 , nt2::policy<ext::vector_> const &\n                 , nt2::policy<ext::upper_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> work;\n      NT2_AS_TERMINAL_INOUT(o_semantic, a\n                           , boost::proto::child_c<0>(a0), work);\n      NT2_AS_TERMINAL_OUT  (r_semantic, w\n                           , boost::proto::child_c<0>(a1));\n      w.resize(nt2::of_size(height(a), 1));\n      NT2_LAPACK_VERIFY(nt2::hsev_w( boost::proto::value(a)\n                                   , boost::proto::value(w)\n                                   , 'U'));\n      assign_swap(boost::proto::child_c<0>(a1), w);\n    }\n\n    BOOST_FORCEINLINE\n    void eval1_3 ( A0& a0, A1& a1\n                 , nt2::policy<ext::matrix_> const &\n                 , nt2::policy<ext::lower_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> work;\n      NT2_AS_TERMINAL_INOUT(o_semantic, a\n                           , boost::proto::child_c<0>(a0), work);\n      nt2::container::table<rtype_t> w(of_size(height(a), 1));\n      NT2_LAPACK_VERIFY(nt2::hsev_w( boost::proto::value(a)\n                                   , boost::proto::value(w)\n                                   , 'L'));\n      boost::proto::child_c<0>(a1) = from_diag(w);\n    }\n\n    BOOST_FORCEINLINE\n    void eval1_3 ( A0& a0, A1& a1\n                 , nt2::policy<ext::matrix_> const &\n                 , nt2::policy<ext::upper_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> work;\n      NT2_AS_TERMINAL_INOUT(o_semantic, a\n                           , boost::proto::child_c<0>(a0), work);\n      nt2::container::table<rtype_t>  w(of_size(height(a), 1));\n      NT2_LAPACK_VERIFY(nt2::hsev_w( boost::proto::value(a)\n                                   , boost::proto::value(w)\n                                   , 'U'));\n      boost::proto::child_c<0>(a1) = from_diag(w);\n    }\n\n    BOOST_FORCEINLINE\n    void eval1_3 ( A0& a0, A1& a1\n                 , nt2::policy<ext::raw_>\n                 , nt2::policy<ext::upper_>\n                 ) const\n    {\n      eval1_3(a0, a1\n             , nt2::policy<ext::vector_>(), nt2::policy<ext::upper_>());\n    }\n\n    BOOST_FORCEINLINE\n    void eval1_3 ( A0& a0, A1& a1\n                 , nt2::policy<ext::raw_>\n                 , nt2::policy<ext::lower_>\n                 ) const\n    {\n      eval1_3(a0, a1\n             , nt2::policy<ext::vector_>(), nt2::policy<ext::lower_>());\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [W, V]= SYMEIG(A, matrix_/vector_/upper_/lower_/raw_)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<2> const&\n              , boost::mpl::long_<2> const&\n              ) const\n    {\n      eval2_2(a0, a1\n             , boost::proto::value(boost::proto::child_c<1>(a0)));\n\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [W, U]= SYMEIG(A)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<1> const&\n              , boost::mpl::long_<2> const&\n              ) const\n    {\n      eval2_3(a0, a1, nt2::matrix_, nt2::upper_);\n    }\n\n    BOOST_FORCEINLINE\n    void eval2_2 ( A0& a0, A1& a1\n                 , nt2::policy<ext::matrix_>\n                 ) const\n    {\n      NT2_AS_TERMINAL_INOUT(o_semantic, u\n                           , boost::proto::child_c<0>(a0)\n                           , boost::proto::child_c<1>(a1));\n      nt2::container::table<rtype_t> w(of_size(height(u), 1));\n      NT2_LAPACK_VERIFY(nt2::hsev_wu( boost::proto::value(u)\n                                    , boost::proto::value(w)\n                                    , 'U'));\n      boost::proto::child_c<0>(a1) = from_diag(w);\n      assign_swap(boost::proto::child_c<1>(a1), u);\n    }\n\n    BOOST_FORCEINLINE\n    void eval2_2 ( A0& a0, A1& a1\n                 , nt2::policy<ext::vector_>\n                 ) const\n    {\n      NT2_AS_TERMINAL_INOUT(o_semantic, u\n                           , boost::proto::child_c<0>(a0)\n                           , boost::proto::child_c<1>(a1));\n      NT2_AS_TERMINAL_OUT  (r_semantic, w, boost::proto::child_c<0>(a1));\n      w.resize(nt2::of_size(height(u), 1));\n      NT2_LAPACK_VERIFY(nt2::hsev_wu( boost::proto::value(u)\n                                    , boost::proto::value(w)\n                                    , 'U'));\n      assign_swap(boost::proto::child_c<0>(a1), w);\n      assign_swap(boost::proto::child_c<1>(a1), u);\n    }\n\n    BOOST_FORCEINLINE\n    void eval2_2 ( A0& a0, A1& a1\n                 , nt2::policy<ext::raw_>\n                 ) const\n    {\n      eval2_2(a0, a1, nt2::policy<ext::vector_>());\n    }\n\n    BOOST_FORCEINLINE\n    void eval2_2 ( A0& a0, A1& a1\n                 , nt2::policy<ext::lower_>\n                 ) const\n    {\n      eval2_3(a0, a1\n             , nt2::policy<ext::matrix_>()\n             , nt2::policy<ext::lower_>());\n    }\n\n\n    BOOST_FORCEINLINE\n    void eval2_2 ( A0& a0, A1& a1\n                 , nt2::policy<ext::upper_>\n                 ) const\n    {\n      eval2_3(a0, a1\n             , nt2::policy<ext::matrix_>()\n             , nt2::policy<ext::upper_>());\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [W, V]= SYMEIG(A, matrix_/vector_, lower_/upper_)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<3> const&\n              , boost::mpl::long_<2> const&\n              ) const\n    {\n      eval2_3( a0, a1\n             , boost::proto::value(boost::proto::child_c<1>(a0))\n             , boost::proto::value(boost::proto::child_c<2>(a0))\n             );\n\n    }\n\n    BOOST_FORCEINLINE\n    void eval2_3 ( A0& a0, A1& a1\n                 , nt2::policy<ext::matrix_>\n                 , nt2::policy<ext::lower_>\n                 ) const\n    {\n      NT2_AS_TERMINAL_INOUT(o_semantic, u\n                           , boost::proto::child_c<0>(a0)\n                           , boost::proto::child_c<1>(a1));\n      nt2::container::table<rtype_t> w(of_size(height(u), 1));\n      NT2_LAPACK_VERIFY(nt2::hsev_wu( boost::proto::value(u)\n                                    , boost::proto::value(w)\n                                    , 'L'));\n      boost::proto::child_c<0>(a1) = from_diag(w);\n      assign_swap(boost::proto::child_c<1>(a1), u);\n    }\n\n    BOOST_FORCEINLINE\n    void eval2_3 ( A0& a0, A1& a1\n                 , nt2::policy<ext::matrix_>\n                 , nt2::policy<ext::upper_>\n                 ) const\n    {\n      NT2_AS_TERMINAL_INOUT(o_semantic, u\n                           , boost::proto::child_c<0>(a0)\n                           , boost::proto::child_c<1>(a1));\n      nt2::container::table<rtype_t> w(of_size(height(u), 1));\n      NT2_LAPACK_VERIFY(nt2::hsev_wu( boost::proto::value(u)\n                                    , boost::proto::value(w)\n                                    , 'U'));\n      boost::proto::child_c<0>(a1) = from_diag(w);\n      assign_swap(boost::proto::child_c<1>(a1), u);\n    }\n\n    BOOST_FORCEINLINE\n    void eval2_3 ( A0& a0, A1& a1\n                 , nt2::policy<ext::vector_>\n                 , nt2::policy<ext::upper_>\n                 ) const\n    {\n      NT2_AS_TERMINAL_INOUT(o_semantic, u\n                           , boost::proto::child_c<0>(a0)\n                           , boost::proto::child_c<1>(a1));\n      NT2_AS_TERMINAL_OUT  (r_semantic, w\n                           , boost::proto::child_c<0>(a1));\n      w.resize(of_size(height(u), 1));\n      NT2_LAPACK_VERIFY(nt2::hsev_wu( boost::proto::value(u)\n                                    , boost::proto::value(w)\n                                    , 'U'));\n      assign_swap(boost::proto::child_c<0>(a1), w);\n      assign_swap(boost::proto::child_c<1>(a1), u);\n    }\n\n    BOOST_FORCEINLINE\n    void eval2_3 ( A0& a0, A1& a1\n                 , nt2::policy<ext::raw_>\n                 , nt2::policy<ext::upper_>\n                 ) const\n    {\n      eval2_3(a0, a1\n             , nt2::policy<ext::vector_>(), nt2::policy<ext::upper_>());\n    }\n\n    BOOST_FORCEINLINE\n    void eval2_3 ( A0& a0, A1& a1\n                 , nt2::policy<ext::raw_>\n                 , nt2::policy<ext::lower_>\n                 ) const\n    {\n      eval2_3(a0, a1\n             , nt2::policy<ext::vector_>(), nt2::policy<ext::lower_>());\n    }\n\n    BOOST_FORCEINLINE\n    void eval2_3 ( A0& a0, A1& a1\n                 , nt2::policy<ext::vector_>\n                 , nt2::policy<ext::lower_>\n                 ) const\n    {\n      NT2_AS_TERMINAL_INOUT(o_semantic, u\n                           , boost::proto::child_c<0>(a0)\n                           , boost::proto::child_c<1>(a1));\n      NT2_AS_TERMINAL_OUT  (r_semantic, w\n                           , boost::proto::child_c<0>(a1));\n      w.resize(of_size(height(u), 1));\n      NT2_LAPACK_VERIFY(nt2::hsev_wu( boost::proto::value(u)\n                                    , boost::proto::value(w)\n                                    , 'L'));\n      assign_swap(boost::proto::child_c<0>(a1), w);\n      assign_swap(boost::proto::child_c<1>(a1), u);\n    }\n\n#define MORE_OPTIONS(PARAM, OPT1, OPT2)        \\\n    BOOST_FORCEINLINE                          \\\n      void eval##PARAM( A0& a0, A1& a1         \\\n                      , nt2::policy<ext::OPT1> \\\n                      , nt2::policy<ext::OPT2> \\\n                      ) const                  \\\n    {                                          \\\n      eval##PARAM(a0, a1                       \\\n                 , nt2::policy<ext::OPT2>()    \\\n                 , nt2::policy<ext::OPT1>()    \\\n                 );                            \\\n    }                                          \\\n    /**/\n\n    MORE_OPTIONS(2_3, lower_, raw_)\n    MORE_OPTIONS(2_3, upper_, raw_)\n    MORE_OPTIONS(2_3, lower_, vector_)\n    MORE_OPTIONS(2_3, upper_, vector_)\n    MORE_OPTIONS(2_3, lower_, matrix_)\n    MORE_OPTIONS(2_3, upper_, matrix_)\n    MORE_OPTIONS(1_3, lower_, vector_)\n    MORE_OPTIONS(1_3, upper_, vector_)\n    MORE_OPTIONS(1_3, lower_, raw_)\n    MORE_OPTIONS(1_3, upper_, raw_)\n    MORE_OPTIONS(1_3, lower_, matrix_)\n    MORE_OPTIONS(1_3, upper_, matrix_)\n\n#undef MORE_OPTIONS\n  };\n} }\n\n#endif\n\n\n", "meta": {"hexsha": "e950d758ddf11187b791f6b8ea779548ab0ce2e1", "size": 17741, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/functions/factorizations/symeig.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/factorizations/symeig.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/factorizations/symeig.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": 34.650390625, "max_line_length": 86, "alphanum_fraction": 0.4575841272, "num_tokens": 4755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2581195788282526}}
{"text": "#include <algorithm>\n#include <chrono>\n#include <cmath>\n#include <exception>\n#include <map>\n#include <string>\n#include <sstream>\n#include <thread>\n#include <utility>\n#include <vector>\n\n#include <boost/log/trivial.hpp>\n#include <casadi/casadi.hpp>\n#include <yavl-cpp/yavl.h>\n\n#include \"mimir/algorithm/PursePlannerFormulation.hpp\"\n#include \"mimir/algorithm/PursePlanner.hpp\"\n#include \"mimir/StateMachineFwd.hpp\"\n#include \"mimir/FkinDds.hpp\"\n\n// ReaderLifespan\n#include <dds/core/detail/ProprietaryApi.hpp>\n#include <dds/sub/AnyDataReader.hpp>\n#include <dds/pub/AnyDataWriter.hpp>\n\n\n#ifdef MIMIR_WITH_GNUPLOT\n#include \"gnuplot-iostream.h\"\n#include <tuple>\n#endif\n\nnamespace mimir\n{\n  namespace algorithm\n  {\n\n    class PursePlanner::Impl\n    {\n    public:\n      Impl(\n          const YAML::Node& conf,\n          dds::pub::Publisher publisher,\n          dds::sub::Subscriber subscriber)\n      {\n\n        const YAML::Node config = conf[\"config\"];\n        const YAML::Node schema = conf[\"schema\"];\n        YAVL::Validator checkNode(schema, config);\n\n        if(!checkNode.validate())\n        {\n          std::stringstream oss;\n          oss << checkNode.get_errors();\n\n          BOOST_LOG_TRIVIAL(debug) << \"PursePlanner config:\\n\" << config;\n          BOOST_LOG_TRIVIAL(debug) << \"PursePlanner schema:\\n\" << schema;\n\n          throw YAML::Exception(YAML::Mark(), oss.str());\n        }\n\n        // set initial condition for planner state vector\n        x_0 = casadi::DM(config[\"initial_condition\"][\"x0\"].as<std::vector<double>>());\n\n        // Function for mapping gps to local coordinate system\n        toNED = define_gps_to_ned();\n\n        // === Create instance of the purse planner nlp formulation ===\n        BOOST_LOG_TRIVIAL(trace) << \"Instantiate formulation\";\n        formulation.reset(new PursePlannerFormulation(conf));\n\n        decide_idx = formulation->nlp_builder.decision_parameter_slice;\n        state1_idx = formulation->nlp_builder.state_slice.at(\"x_1\");\n        state2_idx = formulation->nlp_builder.state_slice.at(\"x_2\");\n        input1_idx = formulation->nlp_builder.input_slice.at(\"x_1\");\n        input2_idx = formulation->nlp_builder.input_slice.at(\"x_2\");\n        x1_dim = formulation->nlp_builder.state_dimension.at(\"x_1\");\n        x2_dim = formulation->nlp_builder.state_dimension.at(\"x_2\");\n        v_dim = formulation->nlp_builder.decision_parameter_dimension;\n\n        if (x_0.nnz() != x2_dim)\n        {\n          BOOST_LOG_TRIVIAL(error)\n           << \"Mismatching dimensions: x_0 in config vs. expected from formulation: x_0:\"\n           << x_0.nnz() << \" vs. \" << x2_dim;\n        }\n\n        // === DDS subscribers for parameters defined in YAML config ===\n        setup_parameters(config, subscriber);\n\n        // === DDS subscribers for inputs defined in YAML config ===\n        setup_inputs(config, subscriber);\n\n        // === DDS publishers for outputs defined in YAML config ===\n        setup_outputs(config, publisher);\n\n        // === Enable gnuplot debug plotting ===\n        plot_on = config[\"settings\"][\"plot\"].as<bool>();\n\n#ifdef MIMIR_WITH_GNUPLOT\n        if(plot_on)\n        {\n          gnuplot //<< \"set yrange [-200:200]\\n\"\n                  << \"set title 'PursePlanner'\\n\"\n                  << \"set ylabel 'Various [-]'\\n\"\n                  << \"set xlabel 'Time [s]'\\n\";\n\n          ne_plot << \"set title 'Map plot'\\n\"\n                  << \"set size square\\n\"\n                  << \"set size ratio -1\\n\"\n                  << \"set ylabel 'North [m]'\\n\"\n                  << \"set xlabel 'East [m]'\\n\";\n        }\n#endif\n\n      }\n      ~Impl() {}\n      std::map<std::string, dds::sub::AnyDataReader> parameter_inputs;\n      std::map<std::string, dds::sub::AnyDataReader> input_readers;\n      std::map<std::string, dds::pub::AnyDataWriter> output_writers;\n      std::map<std::string, casadi::Slice>\n        decide_idx, param_idx, input1_idx, input2_idx, state1_idx, state2_idx;\n      std::unique_ptr<PursePlannerFormulation> formulation;\n      std::string outputId;              ///< DDS outputs identifier\n      casadi::DM parameters;             ///< Parameters p\n      casadi::DM x_0, x_k;               ///< State at t_0 and t_k\n      double t_k;                        ///< Simulation time of x_k [seconds]\n      casadi::DM T, X, Tu, U;            ///< Solution trajectories\n      std::vector<double> lamb_g;        ///< Lagrange multipliers: inequality constraints\n      casadi::DM gps_origin;             ///< GPS coordinate of NED origin reference frame\n      casadi::DM T1, X1;                 ///< To be removed\n      bool plot_on;                      ///< To plot with gnuplot or not\n      casadi::Function toNED;\n      casadi_int x1_dim, x2_dim, v_dim, p_dim;\n#ifdef MIMIR_WITH_GNUPLOT\n      Gnuplot gnuplot, ne_plot;\n#endif\n    private:\n\n      casadi::Function define_gps_to_ned()\n      {\n        using casadi::SX;\n        typedef std::vector<std::string> vstr;\n        typedef std::vector<SX> SXvec;\n\n        double PI180 = std::atan(1)*4./180.;\n\n        SX lat = SX::sym(\"lat\");\n        SX lon = SX::sym(\"lon\");\n        SX h = SX::sym(\"height\");\n\n        SX mu = lat*PI180;\n        SX l = lon*PI180;\n\n        // Fossen 2002 p.42\n        SX re = 6378137; // Equatorial radius of ellipsoid\n        SX rp = 6356752; // Polar axis radius of ellipsoid\n\n        SX re2 = re*re;\n        SX rp2 = rp*rp;\n\n        SX N = (re2)/(sqrt(re2*pow(cos(mu),2) + rp2*pow(sin(mu),2)));\n\n        // ECEF\n        SX xe = (N + h)*cos(mu)*cos(l);\n        SX ye = (N + h)*cos(mu)*sin(l);\n        SX ze = ((rp2/re2)*N + h)*sin(mu);\n\n        SX ecef = vertcat(xe, ye, ze);\n\n        casadi::Function toECEF(\"toECEF\", SXvec{lat,lon,h}, SXvec{ecef});\n\n        SX lat0 = SX::sym(\"lat0\");\n        SX lon0 = SX::sym(\"lon0\");\n        SX h0 = SX::sym(\"h0\");\n\n        SX cosl = cos(lon*PI180);\n        SX sinl = sin(lon*PI180);\n        SX cosmu = cos(lat*PI180);\n        SX sinmu = sin(lat*PI180);\n\n        SX Tne = SX::zeros(3,3);\n        Tne(0,0) = -cosl*sinmu;\n        Tne(0,1) = -sinl;\n        Tne(0,2) = -cosl*cosmu;\n        Tne(1,0) = -sinl*sinmu;\n        Tne(1,1) = cosl;\n        Tne(1,2) = -sinl*cosmu;\n        Tne(2,0) = cosmu;\n        Tne(2,2) = -sinmu;\n\n        SX diff = toECEF(SXvec{lat,lon,0})[0] - toECEF(SXvec{lat0,lon0, 0})[0];\n\n        auto ned = mtimes(Tne.T(), diff);\n\n        auto ret = casadi::Function(\"toNED\",\n         {vertcat(lat, lon), vertcat(lat0, lon0)},\n         {ned},\n         vstr{\"GPS\", \"GPS0\"}, vstr{\"NED\"});\n\n        /*\n        typedef std::vector<double> vdob;\n        auto res = ret(casadi::DMDict{{\"GPS\", casadi::DM(vdob{63.45917,    10.3683367})},\n                                      {\"GPS0\", casadi::DM(vdob{63.4581027, 10.3683367})}});\n        BOOST_LOG_TRIVIAL(info) << \"Zero transform is: \" << res[\"NED\"];\n        */\n\n        return ret;\n\n      }\n\n      void setup_parameters(const YAML::Node& config, dds::sub::Subscriber subscriber)\n      {\n        BOOST_LOG_TRIVIAL(trace) << \"setup parameters\";\n        typedef std::vector<double> vdob;\n        using casadi::Slice;\n        auto readerQos = subscriber.default_datareader_qos();\n        const auto config_param = config[\"parameters\"];\n\n        p_dim = formulation->nlp_builder.parameter_dimension;\n        parameters = casadi::DM::zeros(p_dim, 1);\n        param_idx = formulation->nlp_builder.parameter_slice;\n\n        parameters(param_idx.at(\"setting_speed_U_v\"))   = config_param[\"setting_speed_U_v\"][\"default\"].as<double>();\n        parameters(param_idx.at(\"setting_radii\"))       = config_param[\"setting_radii\"][\"default\"].as<vdob>();\n        parameters(param_idx.at(\"aim_distance_D_s\"))    = config_param[\"aim_distance_D_s\"][\"default\"].as<double>();\n        parameters(param_idx.at(\"fish_margin_d_f\"))     = config_param[\"fish_margin_d_f\"][\"default\"].as<double>();\n        parameters(param_idx.at(\"fish_depth_z_s\"))      = config_param[\"fish_depth_z_s\"][\"default\"].as<double>();\n        parameters(param_idx.at(\"leadline_tau_ll_z_d\")) = config_param[\"leadline_tau_ll_z_d\"][\"default\"].as<vdob>();\n        parameters(param_idx.at(\"sink_margin_z_min\"))   = config_param[\"sink_margin_z_min\"][\"default\"].as<double>();\n\n        auto add_parameter_IdVec1d =\n         [=](const std::string& variable){\n\n           auto topicName = config_param[variable][\"topic\"].as<std::string>();\n           auto id = config_param[variable][\"id\"].as<std::string>();\n           parameter_inputs.emplace(\n               variable,\n               dds::sub::DataReader<fkin::IdVec1d>(\n                   subscriber,\n                   dds::topic::ContentFilteredTopic<fkin::IdVec1d>(\n                       dds::topic::Topic<fkin::IdVec1d>(\n                           subscriber.participant(),\n                           topicName),\n                       topicName + id,\n                       dds::topic::Filter(\"id = %0\", {id})),\n                   readerQos));\n         };\n\n        auto add_parameter_IdVec2d =\n         [=](const std::string& variable){\n\n           auto topicName = config_param[variable][\"topic\"].as<std::string>();\n           auto id = config_param[variable][\"id\"].as<std::string>();\n           parameter_inputs.emplace(\n               variable,\n               dds::sub::DataReader<fkin::IdVec2d>(\n                   subscriber,\n                   dds::topic::ContentFilteredTopic<fkin::IdVec2d>(\n                       dds::topic::Topic<fkin::IdVec2d>(\n                           subscriber.participant(),\n                           topicName),\n                       topicName + id,\n                       dds::topic::Filter(\"id = %0\", {id})),\n                   readerQos));\n         };\n\n        auto add_parameter_Double1 =\n         [=](const std::string& variable){\n\n           auto topicName = config_param[variable][\"topic\"].as<std::string>();\n           parameter_inputs.emplace(\n               variable,\n               dds::sub::DataReader<ratatosk::types::DoubleVal>(\n                   subscriber,\n                   dds::topic::Topic<ratatosk::types::DoubleVal>(\n                       subscriber.participant(),\n                       topicName),\n                   readerQos));\n         };\n\n        auto add_parameter_Double2 =\n         [=](const std::string& variable){\n\n           auto topicName = config_param[variable][\"topic\"].as<std::string>();\n           parameter_inputs.emplace(\n               variable,\n               dds::sub::DataReader<ratatosk::types::Double2>(\n                   subscriber,\n                   dds::topic::Topic<ratatosk::types::Double2>(\n                       subscriber.participant(),\n                       topicName),\n                   readerQos));\n         };\n\n        auto add_parameter_Double3 =\n         [=](const std::string& variable){\n\n           auto topicName = config_param[variable][\"topic\"].as<std::string>();\n           parameter_inputs.emplace(\n               variable,\n               dds::sub::DataReader<ratatosk::types::Double3>(\n                   subscriber,\n                   dds::topic::Topic<ratatosk::types::Double3>(\n                       subscriber.participant(),\n                       topicName),\n                   readerQos));\n         };\n\n        // These are subscribed parameters for which we read from\n        add_parameter_IdVec1d(\"setting_speed_U_v\");\n        add_parameter_Double2(\"current_surface\");\n        add_parameter_IdVec2d(\"setting_radii\");\n        add_parameter_IdVec1d(\"aim_distance_D_s\");\n        add_parameter_IdVec1d(\"fish_margin_d_f\");\n        add_parameter_Double2(\"fish_velocity_over_ground\");\n        add_parameter_Double2(\"current_fish\");\n        add_parameter_IdVec1d(\"fish_depth_z_s\");\n        add_parameter_IdVec2d(\"leadline_tau_ll_z_d\");\n        add_parameter_IdVec1d(\"sink_margin_z_min\");\n\n        // some parameters are not read directly from DDS, they are calculated based on other\n\n        auto current_surface = casadi::DM(config_param[\"current_surface\"][\"default\"].as<vdob>());\n        double W = double(norm_2(current_surface));\n        double alpha = std::atan2(\n            double(current_surface(1)),\n            double(current_surface(0))); // atan2(v_E, v_N)\n\n        parameters(param_idx.at(\"current_speed_surface_W\")) = W;\n        parameters(param_idx.at(\"current_dir_surface_alpha\")) = alpha;\n\n        auto fish_NED_velocity =\n         casadi::DM(config_param[\"fish_velocity_over_ground\"][\"default\"].as<vdob>());\n        auto current_fish =\n         casadi::DM(config_param[\"current_fish\"][\"default\"].as<vdob>());\n\n        double V_s = double(norm_2(fish_NED_velocity));\n        double chi_s = std::atan2(\n            double(fish_NED_velocity(1)),\n            double(fish_NED_velocity(0))); // atan2(v_sE, v_sN)\n\n        // fish course in water frame (surface current)\n        double psi_s = atan2(V_s*sin(chi_s)-W*sin(alpha),V_s*cos(chi_s)-W*cos(alpha));\n\n        parameters(param_idx.at(\"fish_speed_NE_V_s\")) = V_s;\n        parameters(param_idx.at(\"fish_course_NED_chi_s\")) = chi_s;\n        parameters(param_idx.at(\"fish_course_WF_psi_s\")) = psi_s;\n      }\n\n      void setup_inputs(const YAML::Node& config, dds::sub::Subscriber subscriber)\n      {\n        BOOST_LOG_TRIVIAL(trace) << \"setup inputs\";\n        // inputs:\n        // - GPS origin as Double2\n        // - Vessel pos vel: PosInfo\n        // - Vessel heading rot: GyroInfo\n        // - Vessel water speed? LogInfo\n\n        // - Fish pos vel: PosInfo\n        // - Fish relative Double3\n        // - Keep as Bit\n\n        typedef std::vector<double> vdob;\n        using casadi::Slice;\n        auto readerQos = subscriber.default_datareader_qos();\n        const auto config_input = config[\"inputs\"];\n\n        auto add_input_Bit =\n         [=](const std::string& variable){\n\n           auto topicName = config_input[variable][\"topic\"].as<std::string>();\n           input_readers.emplace(\n               variable,\n               dds::sub::DataReader<fkin::Bit>(\n                   subscriber,\n                   dds::topic::Topic<fkin::Bit>(\n                       subscriber.participant(),\n                       topicName),\n                   readerQos));\n         };\n\n        auto add_input_Double2 =\n         [=](const std::string& variable){\n\n           auto topicName = config_input[variable][\"topic\"].as<std::string>();\n           input_readers.emplace(\n               variable,\n               dds::sub::DataReader<ratatosk::types::Double2>(\n                   subscriber,\n                   dds::topic::Topic<ratatosk::types::Double2>(\n                       subscriber.participant(),\n                       topicName),\n                   readerQos));\n         };\n\n        auto add_input_Double3 =\n         [=](const std::string& variable){\n\n           auto topicName = config_input[variable][\"topic\"].as<std::string>();\n           input_readers.emplace(\n               variable,\n               dds::sub::DataReader<ratatosk::types::Double3>(\n                   subscriber,\n                   dds::topic::Topic<ratatosk::types::Double3>(\n                       subscriber.participant(),\n                       topicName),\n                   readerQos));\n         };\n\n        auto add_input_PosInfo =\n         [=](const std::string& variable){\n\n           auto topicName = config_input[variable][\"topic\"].as<std::string>();\n           input_readers.emplace(\n               variable,\n               dds::sub::DataReader<ratatosk::types::PosInfo>(\n                   subscriber,\n                   dds::topic::Topic<ratatosk::types::PosInfo>(\n                       subscriber.participant(),\n                       topicName),\n                   readerQos));\n         };\n\n        auto add_input_GyroInfo =\n         [=](const std::string& variable){\n\n           auto topicName = config_input[variable][\"topic\"].as<std::string>();\n           input_readers.emplace(\n               variable,\n               dds::sub::DataReader<ratatosk::types::GyroInfo>(\n                   subscriber,\n                   dds::topic::Topic<ratatosk::types::GyroInfo>(\n                       subscriber.participant(),\n                       topicName),\n                   readerQos));\n         };\n\n        add_input_Double2(\"GPS_origin\");\n        add_input_PosInfo(\"vessel_pos_info\");\n        add_input_GyroInfo(\"vessel_gyro_info\");\n        add_input_PosInfo(\"fish_pos_info\");\n        add_input_Double3(\"fish_relative_pos\");\n        add_input_Bit(\"keep_solution\");\n\n        gps_origin = casadi::DM(config_input[\"GPS_origin\"][\"default\"].as<vdob>());\n\n        // If sample with limited duration is to be used:\n        //auto input_age = input_config[\"max_age_ms\"].as<std::int64_t>();\n        //readerQos << org::opensplice::core::policy::ReaderLifespan(\n        //true,\n        //    dds::core::Duration::from_millisecs(input_age));\n\n      }\n\n      void setup_outputs(const YAML::Node& config, dds::pub::Publisher publisher)\n      {\n        BOOST_LOG_TRIVIAL(trace) << \"setup outputs\";\n        auto writerQos = publisher.default_datawriter_qos();\n        outputId = config[\"outputs\"][\"id\"].as<std::string>();\n\n        output_writers.emplace(\n            \"vessel_speed\",\n            dds::pub::DataWriter<ratatosk::types::DoubleVal>(\n                publisher,\n                dds::topic::Topic<ratatosk::types::DoubleVal>(\n                    publisher.participant(),\n                    config[\"outputs\"][\"vessel_speed\"][\"topic\"].as<std::string>()),\n                writerQos));\n\n        output_writers.emplace(\n            \"vessel_course_rate\",\n            dds::pub::DataWriter<ratatosk::types::DoubleVal>(\n                publisher,\n                dds::topic::Topic<ratatosk::types::DoubleVal>(\n                    publisher.participant(),\n                    config[\"outputs\"][\"vessel_course_rate\"][\"topic\"].as<std::string>()),\n                writerQos));\n\n        output_writers.emplace(\n            \"deploy_position\",\n            dds::pub::DataWriter<ratatosk::types::Double2>(\n                publisher,\n                dds::topic::Topic<ratatosk::types::Double2>(\n                    publisher.participant(),\n                    config[\"outputs\"][\"deploy_position\"][\"topic\"].as<std::string>()),\n                writerQos));\n\n        output_writers.emplace(\n            \"collide_position\",\n            dds::pub::DataWriter<ratatosk::types::Double2>(\n                publisher,\n                dds::topic::Topic<ratatosk::types::Double2>(\n                    publisher.participant(),\n                    config[\"outputs\"][\"collide_position\"][\"topic\"].as<std::string>()),\n                writerQos));\n\n        output_writers.emplace(\n            \"deploy_time\",\n            dds::pub::DataWriter<ratatosk::types::DoubleVal>(\n                publisher,\n                dds::topic::Topic<ratatosk::types::DoubleVal>(\n                    publisher.participant(),\n                    config[\"outputs\"][\"deploy_time\"][\"topic\"].as<std::string>()),\n                writerQos));\n\n        // x(t) for t: [t0, tf] for vessel\n        output_writers.emplace(\n            \"trajectory_vessel\",\n            dds::pub::DataWriter<fkin::BatchKinematics2D>(\n                publisher,\n                dds::topic::Topic<fkin::BatchKinematics2D>(\n                    publisher.participant(),\n                    config[\"outputs\"][\"trajectory_vessel\"][\"topic\"].as<std::string>()),\n                writerQos));\n\n        // rate of turn for t: [t0, tf] for vessel\n        output_writers.emplace(\n            \"trajectory_vessel_rot\",\n            dds::pub::DataWriter<fkin::BatchIdVec1d>(\n                publisher,\n                dds::topic::Topic<fkin::BatchIdVec1d>(\n                    publisher.participant(),\n                    config[\"outputs\"][\"trajectory_vessel_rot\"][\"topic\"].as<std::string>()),\n                writerQos));\n\n\n        // x(t) for t: [t0, tf] for fish\n        output_writers.emplace(\n            \"trajectory_fish\",\n            dds::pub::DataWriter<fkin::BatchKinematics2D>(\n                publisher,\n                dds::topic::Topic<fkin::BatchKinematics2D>(\n                    publisher.participant(),\n                    config[\"outputs\"][\"trajectory_fish\"][\"topic\"].as<std::string>()),\n                writerQos));\n\n        // nlp configuration info\n        output_writers.emplace(\n            \"nlp_config\",\n            dds::pub::DataWriter<fkin::NlpConfig>(\n                publisher,\n                dds::topic::Topic<fkin::NlpConfig>(\n                    publisher.participant(),\n                    config[\"outputs\"][\"nlp_config\"][\"topic\"].as<std::string>()),\n                writerQos));\n\n        // nlp statistics\n        output_writers.emplace(\n            \"nlp_stats\",\n            dds::pub::DataWriter<fkin::OptiStats>(\n                publisher,\n                dds::topic::Topic<fkin::OptiStats>(\n                    publisher.participant(),\n                    config[\"outputs\"][\"nlp_stats\"][\"topic\"].as<std::string>()),\n                writerQos));\n\n      }\n    };\n\n    PursePlanner::PursePlanner(\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 PursePlanner::Impl(config, publisher, subscriber)),\n      m_scheduler(scheduler),\n      m_stateMachine(machine),\n      m_time_step(std::chrono::milliseconds(\n           config[\"config\"][\"settings\"][\"time_step_ms\"].as<std::int32_t>())),\n      m_next_step(std::chrono::steady_clock::now()),\n      m_config(config),\n      m_retries(10),\n      m_keep_solution(false)\n    {}\n\n    void PursePlanner::solve(const std::atomic<bool>& cancel_token)\n    {\n      // solve() performs the following :\n      // I.    Fetches DDS input and parameters, x(t0), p into local variables\n      // II.   Shifts solution from previous step for warm starting optimization problem\n      // III.  Sets initial condition for x(t0) in optimization problem\n      // IV.   Solves the optimization problem\n      // V.    Verify that the solve succeeded (publish stats) TODO: failure action\n      // VI.   Updates solution in nlp problem data structure\n      // VII.  Evaluates solution trajectory  (prepare for publish)\n      // VIII. Publish solution trajectory and desired now\n\n\n      using casadi::DM, casadi::DMDict;\n      namespace sc = std::chrono;\n      using namespace fkin;\n\n      try\n      {\n        BOOST_LOG_TRIVIAL(trace) << \"Solving \" << name();\n\n        // I. == Read DDS data =====================================================\n        BOOST_LOG_TRIVIAL(debug) << \"  I. read DDS data\";\n        // Data are put into data structures that are used further below\n\n        read_inputs();      // Fetch inputs, sample and hold\n        read_parameters();  // Fetch user-configurable parameters from DDS\n\n        // Get constant parameters that are needed in output of BatchKinematics2D (fish course, speeds)\n        double U_v = double(model()->parameters(model()->param_idx.at(\"setting_speed_U_v\")));\n        double fish_sog = double(model()->parameters(model()->param_idx.at(\"fish_speed_NE_V_s\")));\n        double W = double(model()->parameters(model()->param_idx.at(\"current_speed_surface_W\")));\n        double alpha = double(model()->parameters(model()->param_idx.at(\"current_dir_surface_alpha\")));\n        double D_s = double(model()->parameters(model()->param_idx.at(\"aim_distance_D_s\")));\n        double R_x = double(model()->parameters(model()->param_idx.at(\"setting_Rx\")));\n        double R_y = double(model()->parameters(model()->param_idx.at(\"setting_Ry\")));\n        double t_d = 0.; // set properly later\n\n        // II. == Warm start ==================================================\n        BOOST_LOG_TRIVIAL(debug) << \"  II. warm start\";\n        auto nlp_input = DMDict{{\"w\", DM(model()->formulation->nlp_problem.x_init)}};\n\n        auto d_param = model()->formulation->mpc.at(\"v\").at(\"extractor\")(nlp_input).at(\"v\");\n        auto sys_1 = model()->formulation->mpc.at(\"x_1\").at(\"shifter\")(nlp_input).at(\"w_out\");\n        auto sys_2 = model()->formulation->mpc.at(\"x_2\").at(\"shifter\")(nlp_input).at(\"w_out\");\n\n        model()->formulation->nlp_problem.x_init = vertcat(d_param, sys_1, sys_2).get_elements();\n\n        // III. == Set variable guesses in NLP ==================================\n        BOOST_LOG_TRIVIAL(debug) << \"  III. set variable guesses in NLP\";\n        model()->formulation->set_variable(\"v\", d_param);\n        model()->formulation->set_variable(\"x_1_0\", casadi::DM::zeros(model()->x1_dim, 1));\n        model()->formulation->set_variable(\"x_2_0\", model()->x_k);\n        model()->t_k = sc::duration_cast<sc::seconds>(m_next_step - m_t0).count();\n\n        DM t0_opt = DM(model()->t_k); // if formulation has explicit time else, 0 is ok\n        //t0_opt(0) = 0; // Need to be tested more.\n\n        // IV. == Solve NLP =====================================================\n        BOOST_LOG_TRIVIAL(debug) << \"  IV. solve NLP\";\n        model()->formulation->set_abort(cancel_token);\n\n        BOOST_LOG_TRIVIAL(debug) << \"Skip new solution: \" << m_keep_solution;\n\n        if (!m_keep_solution){\n\n          const auto& prob = model()->formulation->nlp_problem;\n          auto result = model()->formulation->nlp_solver(\n              DMDict({{\"x0\", prob.x_init},\n                      {\"lbx\", prob.x_lb},\n                      {\"ubx\", prob.x_ub},\n                      {\"lbg\", prob.g_lb},\n                      {\"ubg\", prob.g_ub},\n                      {\"p\", vertcat(model()->parameters, t0_opt, t0_opt)},\n                      {\"lam_x0\", prob.lambda_init},\n                      {\"lam_g0\", model()->lamb_g}}));\n\n          // TODO: may need clever multi-evaluation\n          // Maybe parallel evaluation with futures?\n\n          // V. == Check status =================================================\n          BOOST_LOG_TRIVIAL(debug) << \"  V. check status\";\n          fkin::OptiStats opti_stats(model()->formulation->stats());\n          opti_stats.obj() = double(result[\"f\"]);\n          opti_stats.id() = model()->outputId;\n          opti_stats.p() = vertcat(model()->parameters, model()->t_k).get_elements();\n          opti_stats.x0() = model()->x_k.get_elements();\n\n          static_cast<dds::pub::DataWriter<fkin::OptiStats>>(\n              model()->output_writers.at(\"nlp_stats\"))->write(opti_stats);\n\n          if (cancel_token)\n          {\n            BOOST_LOG_TRIVIAL(info) << \"Solve was interrupted by user\";\n            event(new mimir::EvInterrupt());\n            return;\n          }\n\n\n          if(!model()->formulation->nlp_solver.stats().at(\"success\").as_bool())\n          {\n            BOOST_LOG_TRIVIAL(debug) << model()->formulation->nlp_solver.stats();\n\n            if(--m_retries > 0) {\n              // reset initial guess of Lagrange multipliers and decision parameters\n              auto v_guess = casadi::DM::zeros(model()->v_dim, 1);\n              model()->formulation->set_variable(\"v\", v_guess);\n              model()->lamb_g = std::vector<double>(model()->formulation->nlp_problem.g_lb.size(), 0);\n              step_time();\n              event(new mimir::EvReady());\n              return;\n            }\n\n            // Max number of failed attempts in a row, giving up.\n            event(new mimir::EvInterrupt());\n            return;\n          }\n          else{\n            m_retries = 10; // Reset retries to magic number\n          }\n\n          // VI. == Update nlp problem  =========================================\n          BOOST_LOG_TRIVIAL(debug) << \"  VI. update NLP problem\";\n          model()->formulation->nlp_problem.x_init = result[\"x\"].get_elements();\n          model()->formulation->nlp_problem.lambda_init = result[\"lam_x\"].get_elements();\n          model()->lamb_g = result[\"lam_g\"].get_elements();\n          const auto& nlp_output = model()->formulation->nlp_problem.x_init;\n\n\n          // VII. == Set solution data  =========================================\n          // (maybe unpacker + timegrid as optional for collocation)\n          BOOST_LOG_TRIVIAL(debug) << \"  VII. set solution data\";\n\n          auto decide_param =\n           model()->formulation->mpc.at(\"v\").at(\"extractor\")(DMDict({{\"w\", nlp_output}})).at(\"v\");\n\n          auto unpacked_x1 =\n           model()->formulation->mpc.at(\"x_1\").at(\"unpacker\")(DMDict({{\"w\", nlp_output}}));\n\n          auto solT_x1 =\n           model()->formulation->mpc.at(\"x_1\").at(\"timegrid\")(DMDict({{\"t0\", DM(model()->t_k)},\n                                                                      {\"v\", decide_param}}));\n          auto unpacked_x2 =\n           model()->formulation->mpc.at(\"x_2\").at(\"unpacker\")(DMDict({{\"w\", nlp_output}}));\n\n          auto solT_x2 =\n           model()->formulation->mpc.at(\"x_2\").at(\"timegrid\")(DMDict({{\"t0\", DM(model()->t_k)},\n                                                                      {\"v\", decide_param}}));\n\n          BOOST_LOG_TRIVIAL(info) << \"Decided parameters: \" << decide_param;\n\n          t_d = double(model()->formulation->mpc.at(\"x_2\").at(\"Tf\")(DMDict{{\"w\", nlp_output}}).at(\"Tf\"));\n\n          double tmp_h = std::pow(R_x - R_y, 2) / std::pow(R_x + R_y, 2);\n          double Pi = 2*std::acos(0.0);\n          // Ramanujan, second approximation:\n          double ellipse_circum = Pi*(R_x + R_y)*(1 + 3*tmp_h/(10 + std::pow(4 - 3*tmp_h, 0.5)));\n\n          double s_pd = 0.5*ellipse_circum; // We use half ellipse circumference approximation..\n\n          // Time interval of interest to provide trajectories\n          double t_f = ceil(t_d + (D_s + s_pd)/U_v); // t0 = 0, tf = t_pd = t_d + (D_s + s_pd)/Uv\n          // We can use the trajectory function, since x_2 has variable step and no control input\n          double deltaT = t_f/model()->formulation->N2;\n\n          if (unpacked_x2[\"U\"].nnz() > 0)\n            throw std::runtime_error(\"PursePlanner assumes that x_2 subsystem has no input u\");\n\n          auto decide_param_traj = decide_param;\n          decide_param_traj(model()->decide_idx.at(\"x_2_DT\")) = deltaT;\n\n          // Unused:\n          /*auto trajx1 = model()->formulation->mpc.at(\"x_1\").at(\"trajectory\")(\n            DMDict({{\"U\", unpacked_x1[\"U\"]},\n            {\"X0\", unpacked_x1[\"X0\"]},\n            {\"p\", model()->parameters},\n            {\"v\", decide_param},\n            {\"t0\", t0_opt}}));*/\n\n          if(!(model()->formulation->nlp_config().technique() == \"single-shooting\"))\n          {\n            model()->x_k = unpacked_x2[\"Xc\"](casadi::Slice(), 0); // TO BE REMOVED\n            model()->T = solT_x2[\"T\"];\n            model()->X = horzcat(unpacked_x2[\"X0\"], unpacked_x2[\"Xc\"]);\n            throw std::runtime_error(\"PursePlanner assumes the technique is single-shooting\");\n          }\n          else\n          {\n            auto trajectory =\n             model()->formulation->mpc.at(\"x_2\").at(\"trajectory\")(\n                 DMDict({{\"U\", unpacked_x2[\"U\"]},\n                         {\"X0\", unpacked_x2[\"X0\"]},\n                         {\"p\", model()->parameters},\n                         {\"v\", decide_param_traj},\n                         {\"t0\", t0_opt}}));\n\n            model()->x_k = trajectory[\"X\"](casadi::Slice(), 0); // TO BE REMOVED\n            model()->T = trajectory[\"T\"];\n            model()->X = trajectory[\"X\"];\n\n            BOOST_LOG_TRIVIAL(trace) << \"T_traj: \" << trajectory[\"T\"];\n            BOOST_LOG_TRIVIAL(trace) << \"X_traj: \" << trajectory[\"X\"];\n            BOOST_LOG_TRIVIAL(trace) << \"Trajectory elements: \" << trajectory[\"T\"].nnz();\n\n            // Update output\n            model()->T1 = trajectory[\"T\"];\n            model()->X1 = trajectory[\"X\"];\n\n          }\n\n          // Control input solution\n          model()->U = unpacked_x2[\"U\"];\n          model()->Tu = solT_x2[\"Tu\"];\n\n          BOOST_LOG_TRIVIAL(trace) << \"T: \" << model()->T;\n          BOOST_LOG_TRIVIAL(trace) << \"Xc: \" << unpacked_x2[\"Xc\"];\n          BOOST_LOG_TRIVIAL(trace) << \"U: \" << model()->U;\n          BOOST_LOG_TRIVIAL(trace) << \"Tu: \" << model()->Tu;\n\n        }\n\n\n        // VIII. == Publish solution trajectory and desired now ================\n        BOOST_LOG_TRIVIAL(debug) << \"  VIII. publish solution trajectory and desired now\";\n\n        if(model()->T.nnz() > 0)\n        {\n          auto Tx = model()->T.get_elements();\n          auto Tu = model()->Tu.get_elements();\n\n          //auto vessel_rot_idx_u = casadi::Slice(0,1);\n          fkin::BatchKinematics2D vessel_traj, fish_traj;\n          fkin::BatchIdVec1d vessel_rot;//, vessel_acc;\n          std::string id = model()->outputId;\n          vessel_traj.id() = id;\n          fish_traj.id() = id;\n          vessel_rot.id() = id;\n          vessel_traj.timestamps().reserve(Tx.size());\n          vessel_rot.timestamps().reserve(Tx.size());\n          fish_traj.timestamps().reserve(Tx.size());\n\n          // Find the time point in solution closest to now\n          // Use {Tx, Tu} resp. if a {state, input} variable is to be found\n          auto t_expected = m_next_step - m_t0; // Expected time now in optimization\n          auto t_now_sim_epoch = std::chrono::steady_clock::now() - m_t0; // Actual time now\n\n          // First time in solution vector that are not less than t_now\n          auto time_it = std::lower_bound(\n              Tx.begin(), Tx.end(),\n              sc::duration_cast<sc::seconds>(t_now_sim_epoch).count());\n\n          // If it is found, publish vessel commands\n          if(time_it != Tx.end()){\n\n            // Index of the solution\n            auto idx = std::distance(Tx.begin(), time_it);\n\n            // Forward diff (f(idx+1) - f(idx))/deltaT\n            auto idx_1 = idx+1;\n            auto idx_2 = idx;\n            if (static_cast<size_t>(idx + 1) == Tx.size()) {\n              // Backward diff (f(idx) - f(idx-1))/deltaT\n              idx_1 = idx;\n              idx_2 = idx-1;\n            }\n\n            double rad_2_deg = 180./(2*std::acos(0.0)); // (180/pi)\n            auto course_1 = double(model()->X(model()->state2_idx.at(\"vessel_course\"), idx_1));\n            auto course_2 = double(model()->X(model()->state2_idx.at(\"vessel_course\"), idx_2));\n            auto time_1 = Tx[idx_1];\n            auto time_2 = Tx[idx_2];\n            double vessel_course_rate = (course_1 - course_2)/(time_1 - time_2);\n            double capped_turn_rate = std::fmin(\n                std::fmax(double(vessel_course_rate), -model()->formulation->omega_max),\n                model()->formulation->omega_max);\n            capped_turn_rate *= rad_2_deg;\n\n            double chi_v = double(model()->X(model()->state2_idx.at(\"vessel_course\"), idx));\n            double beta = asin((W/U_v)*sin(alpha - chi_v)); // Side slip.\n            // speed over ground\n            double vessel_sog = sqrt(U_v*U_v + W*W + 2*U_v*W*cos(chi_v - beta - alpha));\n\n            BOOST_LOG_TRIVIAL(trace) << \"Simulation time for commanded output: \" << (*time_it);\n\n            static_cast<dds::pub::DataWriter<ratatosk::types::DoubleVal>>(\n                model()->output_writers.at(\"vessel_speed\"))->write(\n                    ratatosk::types::DoubleVal(vessel_sog));\n\n            static_cast<dds::pub::DataWriter<ratatosk::types::DoubleVal>>(\n                model()->output_writers.at(\"vessel_course_rate\"))->write(\n                    ratatosk::types::DoubleVal(capped_turn_rate));\n\n            BOOST_LOG_TRIVIAL(debug) << \"Commands are: \" << vessel_sog << \", \" << capped_turn_rate;\n\n          }\n\n          if(m_keep_solution)\n          {\n            step_time();\n            event(new mimir::EvReady());\n            return;\n          }\n\n          auto t_overtime = t_now_sim_epoch - t_expected; // Is the optimization late?\n          // Find deployment position\n          auto t_deploy = t_now_sim_epoch - t_overtime + sc::milliseconds(static_cast<int64_t>(t_d*1000));\n\n          double t_late =  sc::duration_cast<sc::milliseconds>(t_overtime).count();\n          BOOST_LOG_TRIVIAL(warning) << \" Overtime: \" << t_late;\n\n          static_cast<dds::pub::DataWriter<ratatosk::types::DoubleVal>>(\n              model()->output_writers.at(\"deploy_time\"))->write(\n                  ratatosk::types::DoubleVal(double(t_d - t_late/1000)));\n\n          BOOST_LOG_TRIVIAL(debug) << \"Deploy in: \" << t_d - t_late/1000 << \" sec\";\n\n          time_it = std::lower_bound(\n              Tx.begin(), Tx.end(),\n              sc::duration_cast<sc::seconds>(t_deploy).count());\n\n          if(time_it != Tx.end()) {\n\n            auto idx = std::distance(Tx.begin(), time_it);\n            auto deploy_pos = model()->X(model()->state2_idx.at(\"vessel_NE\"), idx);\n\n            BOOST_LOG_TRIVIAL(debug) << \"Deploy pos is: \" << deploy_pos;\n\n            static_cast<dds::pub::DataWriter<ratatosk::types::Double2>>(\n                model()->output_writers.at(\"deploy_position\"))->write(\n                    ratatosk::types::Double2(double(deploy_pos(0)), double(deploy_pos(1))));\n\n          }\n\n          // Find collision point\n          auto t_collide = t_deploy + sc::seconds(static_cast<int64_t>(D_s/U_v));\n\n\n          time_it = std::lower_bound(\n              Tx.begin(), Tx.end(),\n              sc::duration_cast<sc::seconds>(t_collide).count());\n\n          if(time_it != Tx.end()) {\n\n            auto idx = std::distance(Tx.begin(), time_it);\n            auto collide_pos = model()->X(model()->state2_idx.at(\"vessel_NE\"), idx);\n\n            static_cast<dds::pub::DataWriter<ratatosk::types::Double2>>(\n                model()->output_writers.at(\"collide_position\"))->write(\n                    ratatosk::types::Double2(double(collide_pos(0)), double(collide_pos(1))));\n\n          }\n\n          auto end_idx = model()->X.size2();\n\n          // Convert simulation time to wall clock time\n          for (casadi_int i = 0; i < end_idx; ++ i) //auto& t : Tx)\n          {\n            auto steady_time = m_t0 + sc::milliseconds(static_cast<int64_t>(double(Tx[i])*1000));\n            auto wall_time = (steady_time - m_t0 + m_t0_wall); // drifts if system_clock changes\n            auto epoch_time = sc::duration_cast<sc::milliseconds>(wall_time.time_since_epoch()).count();\n            vessel_traj.timestamps().push_back(fkin::Timestamp(epoch_time));\n            fish_traj.timestamps().push_back(fkin::Timestamp(epoch_time));\n            vessel_rot.timestamps().push_back(fkin::Timestamp(epoch_time));\n          }\n\n          // Calculate rate of turn with finite difference\n          casadi_int n_elem = model()->X.size2();\n          std::vector<casadi_int> last_row{n_elem - 1};\n          std::vector<casadi_int> secnd_last_col{n_elem - 2};\n          // Shifts one and keeps last element (band(n,1) is sub diagonal, so we transpose)\n          casadi::DM shift_operator = casadi::DM(casadi::Sparsity::band(n_elem,1).T()\n           + casadi::Sparsity::triplet(n_elem, n_elem, last_row, secnd_last_col));\n\n          casadi::DM vessel_courses = model()->X(model()->state2_idx.at(\"vessel_course\"),\n           casadi::Slice()).T();\n          casadi::DM courses_shifted = mtimes(shift_operator, vessel_courses);\n          casadi::DM delta_courses = courses_shifted - vessel_courses;\n          casadi::DM delta_times = mtimes(shift_operator, Tx) - Tx;\n          casadi::DM vessel_turn_rate = delta_courses/delta_times;\n\n          BOOST_LOG_TRIVIAL(trace) << \"calc vessel_turn_rate are: \" << vessel_turn_rate;\n\n          // Loop over columns of X to fetch solution trajectory\n          for(casadi_int i = 0; i < end_idx /* model()->X.size2() */; ++i)\n          {\n            casadi::DM stateX = model()->X(casadi::Slice(), i);\n\n            casadi::DM vessel_NE(stateX(model()->state2_idx.at(\"vessel_NE\")));\n            casadi::DM fish_NE(stateX(model()->state2_idx.at(\"fish_NE\")));\n\n            casadi::DM vessel_course(stateX(model()->state2_idx.at(\"vessel_course\")));\n\n            double capped_turn_rate = std::fmin(\n                std::fmax(double(vessel_turn_rate(i)), -model()->formulation->omega_max),\n                model()->formulation->omega_max);\n\n            double chi_v = double(vessel_course);\n            double beta = asin((W/U_v)*sin(alpha - chi_v)); // Side slip.\n            // speed over ground\n            double vessel_sog = sqrt(U_v*U_v + W*W + 2*U_v*W*cos(chi_v - beta - alpha));\n\n            vessel_traj.batch().push_back( Kinematics2D(\n                 id,\n                 Vector2d(double(vessel_NE(0)), double(vessel_NE(1))),\n                 Vector1d(double(stateX(model()->state2_idx.at(\"vessel_course\")))),\n                 Vector1d(vessel_sog)));\n\n            fish_traj.batch().push_back( Kinematics2D(\n                 id,\n                 Vector2d(double(fish_NE(0)), double(fish_NE(1))),\n                 Vector1d(0.),\n                 Vector1d(double(fish_sog))));\n\n            vessel_rot.batch().push_back( IdVec1d(id, Vector1d(double(capped_turn_rate))) );\n\n          }\n\n          static_cast<dds::pub::DataWriter<fkin::BatchKinematics2D>>(\n              model()->output_writers.at(\"trajectory_vessel\"))->write(vessel_traj);\n\n          static_cast<dds::pub::DataWriter<fkin::BatchKinematics2D>>(\n              model()->output_writers.at(\"trajectory_fish\"))->write(fish_traj);\n\n          static_cast<dds::pub::DataWriter<fkin::BatchIdVec1d>>(\n              model()->output_writers.at(\"trajectory_vessel_rot\"))->write(vessel_rot);\n\n        }\n\n        plot(model()->plot_on);\n        step_time();\n        event(new mimir::EvReady());\n      }\n      catch (casadi::CasadiException &e)\n      {\n        BOOST_LOG_TRIVIAL(fatal) << \"Casadi threw exception in \" << name() << \": \" << e.what();\n        event(new mimir::EvError());\n        throw;\n      }\n      catch (std::out_of_range &e)\n      {\n        BOOST_LOG_TRIVIAL(fatal) << \"Out of bounds: \" << name() << \": \" << e.what();\n        event(new mimir::EvError());\n        throw;\n      }\n      catch (std::exception &e)\n      {\n        BOOST_LOG_TRIVIAL(fatal) << name() << \": \" << e.what();\n        event(new mimir::EvError());\n        throw;\n      }\n      catch (...)\n      {\n        BOOST_LOG_TRIVIAL(fatal) << name() << \" exception thrown\";\n        event(new mimir::EvError());\n        throw;\n      }\n    }\n\n    void PursePlanner::read_inputs()\n    {\n      using casadi::DM;\n      using casadi::DMDict;\n      typedef std::vector<double> vdob;\n\n      auto readBit =\n       [=](const std::string& key) -> std::pair<bool, bool>\n       {\n        auto samples = static_cast<dds::sub::DataReader<fkin::Bit>>(\n            model()->input_readers.at(key))->read();\n        if (samples.length() > 0){\n          auto sample = (--samples.end());\n          if(sample->info().valid()){\n            return std::make_pair(\n                true,\n                sample->data().value());\n          }\n        }\n        return std::make_pair(false, false);\n       };\n\n      auto readDouble2 =\n       [=](const std::string& key) -> std::pair<bool, casadi::DM>\n       {\n         auto samples = static_cast<dds::sub::DataReader<ratatosk::types::Double2>>(\n             model()->input_readers.at(key))->read();\n         if (samples.length() > 0){\n           auto sample = (--samples.end());\n           if(sample->info().valid()){\n             return std::make_pair(\n                 true,\n                 casadi::DM(std::vector<double>{sample->data().x(), sample->data().y()}));\n           }\n         }\n         return std::make_pair(false, casadi::DM());\n       };\n\n      /*\n      auto readDouble3 =\n       [=](const std::string& key) -> std::pair<bool, casadi::DM>\n       {\n        auto samples = static_cast<dds::sub::DataReader<ratatosk::types::Double3>>(\n            model()->input_readers.at(key))->read();\n        if (samples.length() > 0){\n          auto sample = (--samples.end());\n          if(sample->info().valid()){\n            return std::make_pair(\n                true,\n                casadi::DM(std::vector<double>{\n                   sample->data().x(), sample->data().y(), sample->data().z()}));\n          }\n        }\n        return std::make_pair(false, casadi::DM());\n       }; */\n\n      auto readPosInfo =\n       [=](const std::string& key) -> std::pair<bool, ratatosk::types::PosInfo>\n       {\n        auto samples = static_cast<dds::sub::DataReader<ratatosk::types::PosInfo>>(\n            model()->input_readers.at(key))->read();\n        if (samples.length() > 0){\n          auto sample = (--samples.end());\n          if(sample->info().valid()){\n\n            return std::make_pair(true, sample->data());\n          }\n        }\n        return std::make_pair(false, ratatosk::types::PosInfo());\n       };\n\n      auto readGyroInfo =\n       [=](const std::string& key) -> std::pair<bool, ratatosk::types::GyroInfo>\n       {\n        auto samples = static_cast<dds::sub::DataReader<ratatosk::types::GyroInfo>>(\n            model()->input_readers.at(key))->read();\n        if (samples.length() > 0){\n          auto sample = (--samples.end());\n          if(sample->info().valid()){\n\n            return std::make_pair(true, sample->data());\n          }\n        }\n        return std::make_pair(false, ratatosk::types::GyroInfo());\n       };\n\n      auto resD2 = readDouble2(\"GPS_origin\");\n      if(resD2.first)\n        model()->gps_origin = resD2.second;\n\n      auto vesselPosInfo = readPosInfo(\"vessel_pos_info\");\n      auto fishPosInfo = readPosInfo(\"fish_pos_info\");\n      auto vesselGyroInfo = readGyroInfo(\"vessel_gyro_info\");\n\n      // States of path planner are defined in ::formulate_dynamics:\n\n      casadi::DM xk = model()->x_k;\n      BOOST_LOG_TRIVIAL(debug) << \"STATE before: \" << xk;\n\n      double PI180 = 2.*std::acos(0.0)/180.; //std::atan(1)*4./180.;\n\n      if(vesselPosInfo.first)\n      {\n        auto res = model()->toNED(\n            DMDict{{\"GPS\", DM(vdob{vesselPosInfo.second.lat(), vesselPosInfo.second.lon()})},\n                   {\"GPS0\", model()->gps_origin}}).at(\"NED\");\n\n        xk(model()->state2_idx.at(\"vessel_NE\")) = res(casadi::Slice(0,2));\n      }\n\n      if(vesselGyroInfo.first)\n      {\n        // This may be wrong. Is true heading the same as course?\n        xk(model()->state2_idx.at(\"vessel_course\")) = vesselGyroInfo.second.hdt()*PI180;\n      }\n\n      if(fishPosInfo.first)\n      {\n        auto resPI = model()->toNED(\n            DMDict{{\"GPS\", DM(vdob{fishPosInfo.second.lat(), fishPosInfo.second.lon()})},\n                   {\"GPS0\", model()->gps_origin}}).at(\"NED\");\n\n        BOOST_LOG_TRIVIAL(trace) << \"NED fish: \" << resPI;\n        xk(model()->state2_idx.at(\"fish_NE\")) = resPI(casadi::Slice(0,2));\n      }\n\n      // Set water frame to origin\n      xk(model()->state2_idx.at(\"water_NE\")) = casadi::DM::zeros(2,1);\n\n\n      BOOST_LOG_TRIVIAL(debug) << \"STATE after: \" << xk;\n\n      model()->x_k = xk;\n\n      // Parameters, which in reality are initial conditions..\n      model()->parameters(model()->param_idx.at(\"vessel_NE_q0\")) =\n       xk(model()->state2_idx.at(\"vessel_NE\"));\n\n      model()->parameters(model()->param_idx.at(\"fish_NE_p_s0\")) =\n       xk(model()->state2_idx.at(\"fish_NE\"));\n\n      // Whether the user requests to keep the suggested trajectory or not.\n      auto keep_solution = readBit(\"keep_solution\");\n      if (keep_solution.first)\n        m_keep_solution = keep_solution.second;\n\n    }\n\n    void PursePlanner::read_parameters()\n    {\n\n      auto readIdVec1 =\n       [=](const std::string& key){\n         auto samples = static_cast<dds::sub::DataReader<fkin::IdVec1d>>(\n             model()->parameter_inputs.at(key))->read();\n         if (samples.length() > 0){\n           auto sample = (--samples.end());\n           if(sample->info().valid()){\n             model()->parameters(model()->param_idx.at(key)) = sample->data().vec().x();\n           }\n         }\n       };\n\n      auto readIdVec2 =\n       [=](const std::string& key){\n         auto samples = static_cast<dds::sub::DataReader<fkin::IdVec2d>>(\n             model()->parameter_inputs.at(key))->read();\n         if (samples.length() > 0){\n           auto sample = (--samples.end());\n           if(sample->info().valid()){\n             model()->parameters(model()->param_idx.at(key)) =\n              casadi::DM(std::vector<double>{sample->data().vec().x(), sample->data().vec().y()});\n           }\n         }\n       };\n\n      /*\n      auto readDouble1 =\n       [=](const std::string& key){\n         auto samples = static_cast<dds::sub::DataReader<ratatosk::types::DoubleVal>>(\n             model()->parameter_inputs.at(key))->read();\n         if (samples.length() > 0){\n           auto sample = (--samples.end());\n           if(sample->info().valid()){\n             model()->parameters(model()->param_idx.at(key)) = sample->data().val();\n           }\n         }\n       };\n\n      auto readDouble3 =\n       [=](const std::string& key){\n         auto samples = static_cast<dds::sub::DataReader<ratatosk::types::Double3>>(\n             model()->parameter_inputs.at(key))->read();\n         if (samples.length() > 0){\n           auto sample = (--samples.end());\n           if(sample->info().valid()){\n             model()->parameters(model()->param_idx.at(key)) =\n              casadi::DM(std::vector<double>{\n                   sample->data().x(), sample->data().y(), sample->data().z()});\n           }\n         }\n       };\n      */\n\n      auto readDouble2 =\n       [=](const std::string& key) -> std::pair<bool, casadi::DM>\n       {\n         auto samples = static_cast<dds::sub::DataReader<ratatosk::types::Double2>>(\n             model()->parameter_inputs.at(key))->read();\n         if (samples.length() > 0){\n           auto sample = (--samples.end());\n           if(sample->info().valid()){\n             //model()->parameters(model()->param_idx.at(key)) =\n              return std::make_pair(\n                  true,\n                  casadi::DM(std::vector<double>{sample->data().x(), sample->data().y()}));\n           }\n         }\n         return std::make_pair(false, casadi::DM());\n       };\n\n      readIdVec1(\"setting_speed_U_v\");\n      readIdVec2(\"setting_radii\");\n      readIdVec1(\"aim_distance_D_s\");\n      readIdVec1(\"fish_margin_d_f\");\n      readIdVec1(\"fish_depth_z_s\");\n      readIdVec2(\"leadline_tau_ll_z_d\");\n      readIdVec1(\"sink_margin_z_min\");\n\n      auto surf_current = readDouble2(\"current_surface\");\n      auto fish_vog = readDouble2(\"fish_velocity_over_ground\");\n      auto fish_current = readDouble2(\"current_fish\");\n\n      if(surf_current.first)\n      {\n        double W = double(norm_2(surf_current.second));\n        double alpha = std::atan2(\n            double(surf_current.second(1)),\n            double(surf_current.second(0))); // atan2(v_E, v_N)\n\n        model()->parameters(model()->param_idx.at(\"current_speed_surface_W\")) = W;\n        model()->parameters(model()->param_idx.at(\"current_dir_surface_alpha\")) = alpha;\n\n      }\n\n      if(fish_vog.first && fish_current.first)\n      {\n        auto current_fish = fish_current.second;\n        auto fish_NED_velocity = fish_vog.second;\n\n        double V_s = double(norm_2(fish_NED_velocity));\n        double chi_s = std::atan2(\n            double(fish_NED_velocity(1)),\n            double(fish_NED_velocity(0))); // atan2(v_sE, v_sN)\n\n        double W = double(model()->parameters(model()->param_idx.at(\"current_speed_surface_W\")));\n        double alpha = double(model()->parameters(model()->param_idx.at(\"current_dir_surface_alpha\")));\n        // fish course in water frame (surface current)\n        double psi_s = atan2(V_s*sin(chi_s)-W*sin(alpha),V_s*cos(chi_s)-W*cos(alpha));\n\n        model()->parameters(model()->param_idx.at(\"fish_speed_NE_V_s\")) = V_s;\n        model()->parameters(model()->param_idx.at(\"fish_course_NED_chi_s\")) = chi_s;\n        model()->parameters(model()->param_idx.at(\"fish_course_WF_psi_s\")) = psi_s;\n\n      }\n\n      // Note: some parameters are set in set_input, because they depend on xk (initial conditions).\n\n      BOOST_LOG_TRIVIAL(debug) << \"Parameter vector is: \" << model()->parameters;\n\n    }\n\n    void PursePlanner::initialize(const std::atomic<bool>&)\n    {\n      try\n      {\n        using namespace std::chrono_literals;\n        BOOST_LOG_TRIVIAL(debug) << name() << \" is initializing\";\n        std::this_thread::sleep_for(2s); // use waitset instead for inputs\n\n        m_retries = 10; // Magic number of retries before giving up;\n        model()->x_k = model()->x_0;\n        model()->t_k = 0.;\n\n        // TODO: Need check to confirm that required signals are available\n        read_inputs(); // sets state vector x_k for planner formulation\n        read_parameters(); // sets parameter vector for planner formulation\n\n        m_t0 = std::chrono::steady_clock::now(); // https://stackoverflow.com/a/35282833\n        m_t0_wall = std::chrono::system_clock::now();\n\n        // Cold start parameter guesses\n        auto v_guess = casadi::DM::zeros(model()->v_dim, 1);\n        model()->formulation->set_variable(\"v\", v_guess);\n        model()->lamb_g = std::vector<double>(model()->formulation->nlp_problem.g_lb.size(), 0);\n        model()->formulation->set_variable(\"x_1_0\", casadi::DM::zeros(model()->x1_dim, 1));\n        model()->formulation->set_variable(\"x_2_0\", model()->x_k);\n\n        // DDS Publish configured nlp settings\n        static_cast<dds::pub::DataWriter<fkin::NlpConfig>>(\n            model()->output_writers.at(\"nlp_config\"))->write(model()->formulation->nlp_config());\n\n        m_next_step = std::chrono::steady_clock::now();\n        event(new mimir::EvReady());\n      }\n      catch (...)\n      {\n        event(new mimir::EvError());\n        throw;\n      }\n    }\n\n    void PursePlanner::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);\n      BOOST_LOG_TRIVIAL(debug) << \"Time left until next step: \" << timeleft.count() << \" ms\";\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 PursePlanner::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    PursePlanner::~PursePlanner() = default;\n\n\n    void PursePlanner::plot(bool do_plot)\n    {\n      if(!do_plot)\n        return;\n\n#ifdef MIMIR_WITH_GNUPLOT\n      using casadi::Slice;\n      model()->gnuplot << \"plot '-' with lines ls 1 title 'chi'\\n\"//, \"\n                       //<< \" '-' with steps ls 2 title 'psi_{dot}'\\n\";//, \"\n                       //<< \" '-' with lines ls 3 title 'slack'\\n\";\n      model()->gnuplot.send1d(std::make_tuple(\n           model()->T.get_elements(),\n           model()->X(model()->state2_idx.at(\"vessel_course\"), Slice()).get_elements()));\n      /*model()->gnuplot.send1d(std::make_tuple(\n           model()->Tu.get_elements(),\n           model()->U(model()->input2_idx.at(\"vessel_acc\"), Slice()).get_elements()));*/\n      /*model()->gnuplot.send1d(std::make_tuple(\n           model()->Tu.get_elements(),\n           model()->U(model()->input2_idx.at(\"slack_dist\"), Slice()).get_elements()));*/\n\n\n      model()->gnuplot.flush();\n\n      model()->ne_plot << \"plot '-' with lines ls 1 title 'vessel', \"\n                       << \" '-' with lines ls 2 title 'fish'\\n\";\n      model()->ne_plot.send1d(std::make_tuple(\n           model()->X(model()->state2_idx.at(\"vessel_NE\").start + 1, Slice()).get_elements(),\n           model()->X(model()->state2_idx.at(\"vessel_NE\").start, Slice()).get_elements()));\n      model()->ne_plot.send1d(std::make_tuple(\n           model()->X(model()->state2_idx.at(\"fish_NE\").start + 1, Slice()).get_elements(),\n           model()->X(model()->state2_idx.at(\"fish_NE\").start, Slice()).get_elements()));\n\n      model()->ne_plot.flush();\n\n#else\n      BOOST_LOG_TRIVIAL(trace) << \"Gnuplot not available\";\n#endif\n    }\n  }\n}\n", "meta": {"hexsha": "1ba9f72585ff8c7aaa3b9ae92d031a147f580a31", "size": 56453, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mimir/algorithm/PursePlanner.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/PursePlanner.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/PursePlanner.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": 39.3126740947, "max_line_length": 116, "alphanum_fraction": 0.5526898482, "num_tokens": 13674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017746, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.25798093220302865}}
{"text": "// Copyright 2019 the Autoware Foundation\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#ifndef OPTIMIZATION__OPTIMIZATION_PROBLEM_HPP_\n#define OPTIMIZATION__OPTIMIZATION_PROBLEM_HPP_\n\n#include <common/types.hpp>\n#include <optimization/visibility_control.hpp>\n#include <optimization/utils.hpp>\n#include <helper_functions/crtp.hpp>\n#include <Eigen/Core>\n#include <vector>\n#include <cstddef>\n#include <memory>\n#include <tuple>\n#include <utility>\n\nusing autoware::common::types::bool8_t;\n\nnamespace autoware\n{\nnamespace common\n{\nnamespace optimization\n{\n/// CRTP base class for a mathematical expression.\n/// \\tparam Derived Implementation class. Must implement `score_(..)`, `jacobian_()` and\n/// `hessian(..)`.\n/// \\tparam DomainValueT Parameter type.\n/// \\tparam NumJacobianColsT Number of columns in the jacobian matrix.\n/// \\tparam NumVarsT Number of variables.\ntemplate<typename Derived, typename DomainValueT, int NumJacobianColsT, int NumVarsT>\nclass OPTIMIZATION_PUBLIC Expression : public common::helper_functions::crtp<Derived>\n{\npublic:\n  static constexpr auto NumJacobianCols = NumJacobianColsT;\n  static constexpr auto NumVars = NumVarsT;\n  using DomainValue = DomainValueT;\n  using Value = autoware::common::types::float64_t;\n  using Jacobian = Eigen::Matrix<Value, NumVars, NumJacobianCols>;\n  using Hessian = Eigen::Matrix<Value, NumVars, NumVars>;\n  using JacobianRef = Eigen::Ref<Jacobian>;\n  using HessianRef = Eigen::Ref<Hessian>;\n\n  /// Get the result of an expression for a given parameter value.\n  /// \\param x Parameter value\n  /// \\return Evaluated score\n  Value operator()(const DomainValue & x)\n  {\n    return this->impl().score_(x);\n  }\n\n  /// Get the jacobian at a given parameter value.\n  /// \\param x Parameter value.\n  /// \\param out Evaluated jacobian matrix.\n  void jacobian(const DomainValue & x, JacobianRef out)\n  {\n    this->impl().jacobian_(x, out);\n  }\n\n  /// Get the hessian at a given parameter value.\n  /// \\param x Parameter value.{\n  /// \\param out Evaluated hessian matrix.\n  void hessian(const DomainValue & x, HessianRef out)\n  {\n    this->impl().hessian_(x, out);\n  }\n\n  /// Pre-compute and cache the score/jacobian/hessian values. Which terms are to be computed is\n  /// specified with the `ComputeMode` argument. By default, this function does nothing. You can\n  /// implement and hide this function in your implementation to allow for some caching behavior.\n  /// Though it is encouraged to use `CachedExpression` which already handles a big portion of the\n  /// cache state management.\n  /// \\param x Parameter value.\n  /// \\param mode Computation mode. Which terms (score, jacobian, hessian) are to be computed\n  /// can be set within this element.\n  void evaluate(const DomainValue & x, const ComputeMode & mode)\n  {\n    (void)x;\n    (void)mode;\n  }\n};\n\n/// Expression class for cases when pre-evaluating elements or computing elements together\n/// may be more efficient. This class implements the necessary boilerplate to manage the cache\n/// state book-keeping.\n/// This class implements `score_(..)`, `jacobian_(..)` and `hessian_(..)`; hence the\n/// implementation must only implement `evaluate_(..)`\n/// \\tparam Derived CRTP implementation class. This class should implement `evaluate_()`.\n/// \\tparam DomainValueT Parameter type.\n/// \\tparam NumJacobianColsT Number of columns in the jacobian matrix.\n/// \\tparam NumVarsT Number of variables.\n/// \\tparam ComparatorT Comparator function for `DomainValueT`\ntemplate<typename Derived, typename DomainValueT, int NumJacobianColsT, int NumVarsT,\n  typename ComparatorT>\nclass CachedExpression : public\n  Expression<CachedExpression<Derived, DomainValueT,\n    NumJacobianColsT, NumVarsT, ComparatorT>,\n    DomainValueT, NumJacobianColsT, NumVarsT>\n{\npublic:\n  static constexpr auto NumJacobianCols = NumJacobianColsT;\n  static constexpr auto NumVars = NumVarsT;\n  using DomainValue = DomainValueT;\n  using Value = autoware::common::types::float64_t;\n  using Jacobian = Eigen::Matrix<Value, NumVars, NumJacobianCols>;\n  using Hessian = Eigen::Matrix<Value, NumVars, NumVars>;\n  using JacobianRef = Eigen::Ref<Eigen::Matrix<Value, NumVars, NumJacobianCols>>;\n  using HessianRef = Eigen::Ref<Eigen::Matrix<Value, NumVars, NumVars>>;\n\n  explicit CachedExpression(const ComparatorT & comparator = ComparatorT())\n  : m_score{0.0}, m_jacobian(Jacobian::Zero()), m_hessian{Hessian::Zero()},\n    m_cache_state(comparator) {}\n\n  Value score_(const DomainValue & x)\n  {\n    if (!m_cache_state.is_cached(x, common::optimization::ExpressionTerm::SCORE)) {\n      evaluate(x, ComputeMode{}.set_score());\n    }\n    return m_score;\n  }\n\n  void jacobian_(const DomainValue & x, JacobianRef out)\n  {\n    if (!m_cache_state.is_cached(x, common::optimization::ExpressionTerm::JACOBIAN)) {\n      evaluate(x, ComputeMode{}.set_jacobian());\n    }\n    out = m_jacobian;\n  }\n\n  void hessian_(const DomainValue & x, HessianRef out)\n  {\n    if (!m_cache_state.is_cached(x, common::optimization::ExpressionTerm::SCORE)) {\n      evaluate(x, ComputeMode{}.set_hessian());\n    }\n    out = m_hessian;\n  }\n\n  void evaluate(const DomainValue & x, const ComputeMode & mode)\n  {\n    if (!mode.score() && !mode.jacobian() && !mode.hessian()) {\n      return;\n    }\n    m_cache_state.update(x, mode);\n    // Call the implementation method.\n    static_cast<Derived *>(this)->evaluate_(x, mode);\n  }\n\nprotected:\n  void set_score(Value score)\n  {\n    m_score = score;\n  }\n\n  void set_jacobian(const JacobianRef & jacobian)\n  {\n    m_jacobian = jacobian;\n  }\n\n  void set_hessian(const HessianRef & hessian)\n  {\n    m_hessian = hessian;\n  }\n\nprivate:\n  Value m_score;\n  Jacobian m_jacobian;\n  Hessian m_hessian;\n  CacheStateMachine<DomainValue, ComparatorT> m_cache_state;\n};\n\n/// A generalized representation of an optimization problem. Constrained\n/// implementation classes must implement the following methods:\n/// score_opt_(x);\n/// jacobian_opt_(x, out);\n/// hessian_opt_(x, out);\n/// \\tparam Derived Implementation class\n/// \\tparam DomainValueT The type for parameter to be optimized for.\n/// \\tparam NumJacobianColsT Number of columns in the jacobian matrix.\n/// \\tparam NumVarsT Number of variables.\n/// \\tparam ObjectiveT Objective implementation class.\n/// \\tparam EqualityConstraintsT A tuple of equality constraint expressions.\n/// \\tparam InequalityConstraintsT A tuple of inequality constraint expressions.\ntemplate<typename Derived, typename DomainValueT, int NumJacobianColsT, int NumVarsT,\n  typename ObjectiveT, typename EqualityConstraintsT, typename InequalityConstraintsT>\nclass OPTIMIZATION_PUBLIC OptimizationProblem;\n\n\n// Definition of OptimizationProblem.\n// Template specialization is used for type deduction and forwarding constraint parameter packs\n// to the tuples. This way \"std::tuple\" is enforced to be used on the constrained\n// OptimizationProblem implementations.\ntemplate<typename Derived,\n  typename ... EqualityConstraints,\n  typename ... InequalityConstraints,\n  typename ObjectiveT, typename DomainValueT, int NumJacobianColsT, int NumVarsT>\nclass OPTIMIZATION_PUBLIC OptimizationProblem<Derived, DomainValueT, NumJacobianColsT, NumVarsT,\n    ObjectiveT,\n    std::tuple<EqualityConstraints...>,\n    std::tuple<InequalityConstraints...>>\n  : public Expression<Derived, DomainValueT, NumJacobianColsT, NumVarsT>\n{\npublic:\n  using EqualityConstraintsT = std::tuple<EqualityConstraints...>;\n  using InequalityConstraintsT = std::tuple<InequalityConstraints...>;\n  using Value = autoware::common::types::float64_t;\n  using Jacobian = Eigen::Matrix<Value, NumVarsT, NumJacobianColsT>;\n  using Hessian = Eigen::Matrix<Value, NumVarsT, NumVarsT>;\n  using JacobianRef = Eigen::Ref<Jacobian>;\n  using HessianRef = Eigen::Ref<Hessian>;\n  static constexpr bool8_t is_unconstrained{(std::tuple_size<EqualityConstraintsT>::value == 0U) &&\n    (std::tuple_size<InequalityConstraintsT>::value == 0U)};\n\n  OptimizationProblem(\n    ObjectiveT && objective,\n    EqualityConstraintsT && eq_constraints,\n    InequalityConstraintsT && ineq_constraints\n  )\n  : m_objective(std::forward<ObjectiveT>(objective)),\n    m_equality_constraints(std::forward<EqualityConstraintsT>(eq_constraints)),\n    m_inequality_constraints(std::forward<InequalityConstraintsT>(ineq_constraints))\n  {\n  }\n\n  template<typename ... Args, typename Dummy = void, typename = std::enable_if_t<\n      is_unconstrained, Dummy>>\n  OptimizationProblem(\n    Args && ... args\n  )\n  : m_objective(std::forward<Args>(args)...)\n  {\n  }\n\n  template<bool8_t enabled = is_unconstrained>\n  typename std::enable_if_t<enabled, Value> score_(const DomainValueT & x)\n  {\n    return m_objective(x);\n  }\n\n  template<bool8_t enabled = is_unconstrained>\n  typename std::enable_if_t<!enabled, Value> score_(const DomainValueT & x)\n  {\n    return opt_impl()->score_opt_(x);\n  }\n\n  template<bool8_t enabled = is_unconstrained>\n  typename std::enable_if_t<enabled, void> jacobian_(const DomainValueT & x, JacobianRef out)\n  {\n    m_objective.jacobian(x, out);\n  }\n\n  template<bool8_t enabled = is_unconstrained>\n  typename std::enable_if_t<!enabled, void> jacobian_(const DomainValueT & x, JacobianRef out)\n  {\n    opt_impl()->jacobian_opt_(x, out);\n  }\n\n  template<bool8_t enabled = is_unconstrained>\n  typename std::enable_if_t<enabled, void> hessian_(const DomainValueT & x, HessianRef out)\n  {\n    m_objective.hessian(x, out);\n  }\n\n  template<bool8_t enabled = is_unconstrained>\n  typename std::enable_if_t<!enabled, void> hessian_(const DomainValueT & x, HessianRef out)\n  {\n    opt_impl()->hessian_opt_(x, out);\n  }\n\n  template<bool8_t enabled = is_unconstrained>\n  typename std::enable_if_t<enabled, void> evaluate(\n    const DomainValueT & x,\n    const ComputeMode & mode)\n  {\n    m_objective.evaluate(x, mode);\n  }\n\n  template<bool8_t enabled = is_unconstrained>\n  typename std::enable_if_t<!enabled, void> evaluate(\n    const DomainValueT & x,\n    const ComputeMode & mode)\n  {\n    opt_impl()->evaluate_(x, mode);\n  }\n\nprotected:\n  ObjectiveT & objective()\n  {\n    return m_objective;\n  }\n\n  EqualityConstraintsT & equality_constraints()\n  {\n    return m_equality_constraints;\n  }\n\n  InequalityConstraintsT & inequality_constraints()\n  {\n    return m_inequality_constraints;\n  }\n\nprivate:\n  Derived * opt_impl()\n  {\n    return static_cast<Derived *>(this);\n  }\n\n  ObjectiveT m_objective;\n  EqualityConstraintsT m_equality_constraints;\n  InequalityConstraintsT m_inequality_constraints;\n};\n\n/// Convenience class for unconstrained optimization problems. This is a thin wrapper\n/// around the objective expression.\n/// \\tparam ObjectiveT Objective of the optimization problem.\n/// \\tparam DomainValueT Parameter type.\n/// \\tparam NumVarsT Number of variables.\ntemplate<typename ObjectiveT, typename DomainValueT, int NumVarsT>\nclass UnconstrainedOptimizationProblem : public\n  OptimizationProblem<UnconstrainedOptimizationProblem<ObjectiveT, DomainValueT, NumVarsT>,\n    DomainValueT, 1U, NumVarsT, ObjectiveT, std::tuple<>, std::tuple<>>\n{\n  using OptimizationProblem<UnconstrainedOptimizationProblem<ObjectiveT, DomainValueT, NumVarsT>,\n    DomainValueT, 1U, NumVarsT, ObjectiveT, std::tuple<>, std::tuple<>>::OptimizationProblem;\n};\n\n}  // namespace optimization\n}  // namespace common\n}  // namespace autoware\n\n#endif  // OPTIMIZATION__OPTIMIZATION_PROBLEM_HPP_\n", "meta": {"hexsha": "91937d8417d11209e07704e3181c6bc3fdbedfeb", "size": 11867, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/common/optimization/include/optimization/optimization_problem.hpp", "max_stars_repo_name": "fanyu2021/fyAutowareAuto", "max_stars_repo_head_hexsha": "073661c0634de671ff01bda8a316a5ce10c96ca9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-12-04T00:38:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T05:48:58.000Z", "max_issues_repo_path": "src/common/optimization/include/optimization/optimization_problem.hpp", "max_issues_repo_name": "fanyu2021/fyAutowareAuto", "max_issues_repo_head_hexsha": "073661c0634de671ff01bda8a316a5ce10c96ca9", "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/optimization/include/optimization/optimization_problem.hpp", "max_forks_repo_name": "fanyu2021/fyAutowareAuto", "max_forks_repo_head_hexsha": "073661c0634de671ff01bda8a316a5ce10c96ca9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-04T00:38:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-04T00:38:56.000Z", "avg_line_length": 34.3971014493, "max_line_length": 99, "alphanum_fraction": 0.7395297885, "num_tokens": 2940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2578571546726192}}
{"text": "#include \"include/MMVII_all.h\"\n\n// #include <Eigen/Dense>\n\nnamespace MMVII\n{\n\n/* ========================== */\n/*          ::                */\n/* ========================== */\n\n/// Computation to get the point we have at end of iterating a rectangle\ntemplate <const int Dim> cPtxd<int,Dim> CalPEnd(const cPtxd<int,Dim> & aP0,const cPtxd<int,Dim> & aP1)\n{\n    cPtxd<int,Dim> aRes = aP0;\n    aRes[Dim-1] = aP1[Dim-1] ;\n    return aRes;\n}\n\n\n/* ========================== */\n/*   cBorderPixBoxIterator    */\n/* ========================== */\n\ntemplate <const int Dim>  \n  cBorderPixBoxIterator<Dim>::cBorderPixBoxIterator(tBPB & aBPB,const  tPt & aP0) :\n      cPixBoxIterator<Dim>  (aBPB.PB(),aP0),\n      mBPB                  (&aBPB)\n{\n}\n\ntemplate <const int Dim>  \n  cBorderPixBoxIterator<Dim>  & cBorderPixBoxIterator<Dim>::operator ++(int)\n{\n   return ++(*this);\n}\n\n\ntemplate <const int Dim>  \n  cBorderPixBoxIterator<Dim>  & cBorderPixBoxIterator<Dim>::operator ++()\n{\n    //cPixBoxIterator<Dim>::operator ++ ();\n    tPBI::operator ++ ();\n \n    mBPB->IncrPt(tPBI::mPCur);\n    return *this;\n}\n\n\n\n/* ========================== */\n/*      cBorderPixBox         */\n/* ========================== */\n\n\ntemplate <const int Dim>  \n  cBorderPixBox<Dim>::cBorderPixBox(const tPB & aPB,const tPt & aSz) :\n    mPB     (aPB),\n    mSz     (aSz),\n    mBoxInt (mPB.Dilate(-mSz)),\n    mX0     (mBoxInt.P0().x()),\n    mX1     (mBoxInt.P1().x()),\n    mBegin  (*this,mPB.P0()),\n    mEnd    (*this,CalPEnd(mPB.P0(),mPB.P1()))\n{\n}\ntemplate <const int Dim>  \n  cBorderPixBox<Dim>::cBorderPixBox(const tPB & aPB,int aSz) :\n      cBorderPixBox<Dim>(aPB,tPt::PCste(aSz))\n{\n}\n\ntemplate <const int Dim>  \n  cBorderPixBox<Dim>::cBorderPixBox(const cBorderPixBox<Dim> & aBPB) :\n    cBorderPixBox<Dim>(mPB,mSz)\n{\n}\n\ntemplate <const int Dim>  cPixBox<Dim> &   cBorderPixBox<Dim>::PB() {return mPB;}\n\n\ntemplate <const int Dim>  void cBorderPixBox<Dim>::IncrPt(tPt & aP)\n{\n   if  ((aP.x()==mX0) && (mBoxInt.Inside(aP)))\n      aP.x() = mX1;\n     \n}\n\n\n\n\n/* ========================== */\n/*          cPtxd             */\n/* ========================== */\n\nint NbPixVign(const int & aVign){return 1+2*aVign;}\n\ntemplate <const int Dim> int NbPixVign(const cPtxd<int,Dim> & aVign)\n{\n   int aRes = NbPixVign(aVign[0]);\n   for (int aD=1 ;aD<Dim ; aD++)\n       aRes *= NbPixVign(aVign[aD]);\n   return aRes;\n}\n\n// static const int VeryBig = 1e9;\n// const cPt2di  ThePSupImage( VeryBig, VeryBig);\n// const cPt2di  ThePInfImage(-VeryBig,-VeryBig);\n\n\ncPt2di  TAB4Corner[4] = {{1,1},{-1,1},{-1,-1},{1,-1}};\n\ntemplate <class Type,const int Dim> cPtxd<Type,Dim>  cPtxd<Type,Dim>::PCste(const Type & aVal)\n{\n   cPtxd<Type,Dim> aRes;\n   for (int aK=0 ; aK<Dim; aK++)\n       aRes.mCoords[aK]= aVal;\n   return aRes;\n}\n\ntemplate <class Type,const int Dim> cPtxd<Type,Dim>  cPtxd<Type,Dim>::FromPtInt(const cPtxd<int,Dim> & aPInt)\n{\n   cPtxd<Type,Dim> aRes;\n   for (int aK=0 ; aK<Dim; aK++)\n       aRes.mCoords[aK]= aPInt[aK];\n   return aRes;\n}\n\n/*\nvoid ff()\n{\n    cPtxd<double,3>::FromPtInt(cPt3di(0,0,0));\n}\n*/\n\n\ntemplate <class Type,const int Dim> cPtxd<Type,Dim>  cPtxd<Type,Dim>::PRand()\n{\n   cPtxd<Type,Dim> aRes;\n   for (int aK=0 ; aK<Dim; aK++)\n       aRes.mCoords[aK]= tNumTrait<Type>::RandomValue();\n   return aRes;\n}\n\ntemplate <class Type,const int Dim> cPtxd<Type,Dim>  cPtxd<Type,Dim>::PRandC()\n{\n   cPtxd<Type,Dim> aRes;\n   for (int aK=0 ; aK<Dim; aK++)\n       aRes.mCoords[aK]= RandUnif_C();\n   return aRes;\n}\n\ntemplate <class Type,const int Dim> cPtxd<Type,Dim>  cPtxd<Type,Dim>::PRandUnit()\n{\n   cPtxd<Type,Dim> aRes = PRandC();\n   while (NormInf(aRes)<1e-2)\n        aRes = PRandC();\n   return VUnit(aRes);\n}\n\ntemplate <class Type,const int Dim> cPtxd<Type,Dim>  cPtxd<Type,Dim>::PRandInSphere()\n{\n   cPtxd<Type,Dim> aRes = PRandC();\n   while (Norm2(aRes)>1.0)\n        aRes = PRandC();\n   return aRes;\n}\n\n\n\ntemplate <class Type,const int Dim> cPtxd<Type,Dim>  \n      cPtxd<Type,Dim>::PRandUnitDiff(const cPtxd<Type,Dim>& aP0,const Type & aDist)\n{\n   cPtxd<Type,Dim> aRes = PRandUnit();\n   while (NormInf(aRes-aP0)<aDist)\n        aRes = PRandUnit();\n   return aRes;\n}\n\n\ntemplate <class Type,const int Dim> \n   typename cPtxd<Type,Dim>::tBigNum cPtxd<Type,Dim>::MinSqN2(const std::vector<tPt> & aVecPts,bool SVP) const\n{\n   if (aVecPts.empty())\n   {\n       MMVII_INTERNAL_ASSERT_medium(SVP,\"MinSqN2 on empty vect, no def\");\n       return -1;\n   }\n   tBigNum aRes = SqN2(aVecPts[0]-*this);\n   for (size_t  aKPts=1 ; aKPts<aVecPts.size() ; aKPts++)\n       aRes = std::min(aRes, SqN2(aVecPts[aKPts]-*this));\n   return aRes;\n}\n\n\ntemplate <class Type,const int Dim> double NormK(const cPtxd<Type,Dim> & aPt,double anExp) \n{\n   double aRes = pow(std::abs(aPt[0]),anExp);\n   for (int aD=1 ; aD<Dim; aD++)\n      aRes += pow(std::abs(aPt[aD]),anExp);\n   return pow(aRes,1/anExp);\n}\n\ntemplate <class Type,const int Dim> double Norm2(const cPtxd<Type,Dim> & aPt)\n{\n   double aRes = Square(aPt[0]);\n   for (int aD=1 ; aD<Dim; aD++)\n      aRes += Square(aPt[aD]);\n   return sqrt(aRes);\n}\n\ntemplate <class Type,const int Dim> Type Norm1(const cPtxd<Type,Dim> & aPt)\n{\n   Type aRes = std::abs(aPt[0]);\n   for (int aD=1 ; aD<Dim; aD++)\n      aRes += std::abs(aPt[aD]);\n   return aRes;\n}\n\ntemplate <class Type,const int Dim> Type NormInf(const cPtxd<Type,Dim> & aPt)\n{\n   Type aRes = std::abs(aPt[0]);\n   for (int aD=1 ; aD<Dim; aD++)\n      aRes = std::max(aRes,std::abs(aPt[aD]));\n   return aRes;\n}\n\ntemplate <class Type,const int Dim> Type MinAbsCoord(const cPtxd<Type,Dim> & aPt)\n{\n   Type aRes = std::abs(aPt[0]);\n   for (int aD=1 ; aD<Dim; aD++)\n      aRes = std::min(aRes,std::abs(aPt[aD]));\n   return aRes;\n}\n\n\ntemplate <class T,const int Dim>  \n   typename  tNumTrait<T>::tBig Scal(const cPtxd<T,Dim> &aP1,const cPtxd<T,Dim> & aP2)\n{\n   typename tNumTrait<T>::tBig  aRes = aP1[0]*aP2[0];\n   for (int aD=1 ; aD<Dim; aD++)\n      aRes +=  aP1[aD]*aP2[aD];\n   return aRes;\n}\n\ntemplate <class T,const int Dim>  T Cos(const cPtxd<T,Dim> &aP1,const cPtxd<T,Dim> & aP2)\n{\n   return T(Scal(aP1,aP2)) / (Norm2(aP1)*Norm2(aP2));\n}\n\n\ntemplate <class Type,const int Dim> std::ostream & operator << (std::ostream & OS,const cPtxd<Type,Dim> &aP)\n{\n    OS << \"[\" << aP.x();\n    for (int aD=1; aD<Dim; aD++)\n       OS << \",\" << aP[aD];\n    OS << \"]\" ;\n    return OS;\n}\n\ntemplate<class T,const int Dim> cPtxd<T,Dim>  VUnit(const cPtxd<T,Dim> & aP)\n{\n   return aP / T(Norm2(aP));  // Check by 0 is made in operator\n}\n\ntemplate <class Type,const int DimOut,const int DimIn> cPtxd<Type,DimOut> CastDim(const cPtxd<Type,DimIn> & aPt)\n{\n    MMVII_INTERNAL_ASSERT_tiny(DimIn==DimOut,\"CastDim : different dim\");\n\n    return  cPtxd<Type,DimOut>(aPt.PtRawData());\n   \n}\n\n\n\ntemplate <const int Dim>  class cAllocNeighourhood\n{\n\n   public :\n      typedef  cPtxd<int,Dim>    tPt;\n      typedef  std::vector<tPt>  tVecPt;\n      typedef  std::vector<tVecPt>  tVVPt;\n\n      static  const tVVPt & AllocTabGrowNeigh(int aDMax)\n      {\n           static  tVVPt aRes;;\n           if (int(aRes.size()) > aDMax) return aRes;\n\n           aRes = tVVPt(1+aDMax,tVecPt());\n           \n           for (const auto & aP :  cPixBox(tPt::PCste(-aDMax),tPt::PCste(aDMax+1)))\n               aRes.at(NormInf(aP)).push_back(aP);\n\n           return aRes;\n      }\n\n\n      static const tVecPt &  Alloc(int aNbPix)\n      {\n// StdOut() <<  \"----------------======================\\n\";\n            static  std::vector<tVecPt> aBufRes(Dim);\n            MMVII_INTERNAL_ASSERT_tiny((aNbPix>0)&&(aNbPix<=Dim),\"Bad Nb in neighbourhood\");\n\n            // If alreay computed all fine\n            tVecPt & aRes = aBufRes[aNbPix-1];\n            if (! aRes.empty()) return aRes;\n\n            // Usee full neighboor\n            cPixBox<Dim> aPB(tPt::PCste(-1),tPt::PCste(2));\n            for (const auto & aP : aPB)\n            {\n                int aN = Norm1(aP);\n                if ((aN>0) && (aN<=aNbPix))\n                {\n                    aRes.push_back(aP);\n                    // StdOut() << aP << \"\\n\";\n                }\n            }\n\n            return aRes;\n      }\n};\n\ntemplate <const int Dim>  const std::vector<cPtxd<int,Dim>> & AllocNeighbourhood(int aNbVois)\n{\n   return  cAllocNeighourhood<Dim>::Alloc(aNbVois);\n}\n\n\ntemplate <const int Dim>  const std::vector<std::vector<cPtxd<int,Dim>>> & TabGrowNeigh(int aDistMax)\n{\n   return  cAllocNeighourhood<Dim>::AllocTabGrowNeigh(aDistMax);\n}\n\n\n\n\n\n\n/*\ntemplate <class Type> std::ostream & operator << (std::ostream & OS,const cPtxd<Type,1> &aP)\n{ return  OS << \"[\" << aP.x() << \"]\"; }\ntemplate <class Type> std::ostream & operator << (std::ostream & OS,const cPtxd<Type,2> &aP)\n{ return  OS << \"[\" << aP.x() << \",\" << aP.y() << \"]\"; }\ntemplate <class Type> std::ostream & operator << (std::ostream & OS,const cPtxd<Type,3> &aP)\n{ return  OS << \"[\" << aP.x() << \",\" << aP.y() << \",\" << aP.z()<< \"]\"; }\ntemplate <class Type> std::ostream & operator << (std::ostream & OS,const cPtxd<Type,4> &aP)\n{ return  OS << \"[\" << aP.x() << \",\" << aP.y() << \",\" << aP.z() << \",\" << aP.t() << \"]\"; }\n*/\n\n\n\n\n\n/* ========================== */\n/*          ::                */\n/* ========================== */\n    //  To test Error_Handler mecanism\n\nstatic std::string MesNegSz=\"Negative size in rect object\";\n/*\nstatic std::string  TestErHandler;\nvoid TestBenchRectObjError(const std::string & aType,const std::string &  aMes,const char * aFile,int aLine)\n{\n   TestErHandler = aMes;\n}\n*/\n\n/* ========================== */\n/*          cPixBox           */\n/* ========================== */\n\n\ntemplate <const int Dim>   cPixBox<Dim>::cPixBox(const cPtxd<int,Dim> & aP0,const cPtxd<int,Dim> & aP1,bool AllowEmpty) :\n     cTplBox<int,Dim>(aP0,aP1,AllowEmpty),\n     mBegin  (*this,aP0),\n     mEnd    (*this,CalPEnd(aP0,aP1))\n{\n}\n\ntemplate <const int Dim>   cPixBox<Dim>::cPixBox(const cPixBox<Dim> & aR) :\n   cPixBox<Dim>(aR.mP0,aR.mP1,true)\n{\n}\n\n\ntemplate <const int Dim> cPixBox<Dim>  cPixBox<Dim>::BoxWindow(const tPt & aC,int aSz)\n{\n    return cPixBox<Dim>(aC-cPtxd<int,Dim>::PCste(aSz),aC+cPtxd<int,Dim>::PCste(aSz+1));\n}\n\ntemplate <const int Dim> cPixBox<Dim>  cPixBox<Dim>::BoxWindow(int aSz)\n{\n    return BoxWindow(cPtxd<int,Dim>::PCste(0),aSz);\n}\n\ntemplate <const int Dim>   cPixBox<Dim>::cPixBox(const cTplBox<int,Dim> & aR) :\n   cPixBox<Dim>(aR.P0(),aR.P1(),true)\n{\n}\n\ntemplate <const int Dim> tINT8  cPixBox<Dim>::IndexeLinear(const tPt & aP) const\n{\n   tINT8 aRes = 0;\n   for (int aK=0 ; aK<Dim ; aK++)\n      aRes += tINT8(aP[aK]-tBox::mP0[aK]) * tINT8(tBox::mSzCum[aK]);\n   return aRes;\n}\n\ntemplate <const int Dim> bool  cPixBox<Dim>::SignalAtFrequence(const tPt & anIndex,double aFreq) const\n{\n   return MMVII::SignalAtFrequence(IndexeLinear(anIndex),aFreq,this->mNbElem-1);\n}\n\n\ntemplate <const int Dim> cPtxd<int,Dim>  cPixBox<Dim>::FromIndexeLinear(tINT8  anIndexe) const\n{\n   tPt aRes;\n   for (int aK=0 ; aK<Dim ; aK++)\n   {\n      aRes[aK]  = tBox::mP0[aK] + anIndexe % tBox::mSz[aK];\n      anIndexe /= tBox::mSz[aK];\n   }\n   return aRes;\n}\n\n\n\n\ntemplate <const int Dim> int cPixBox<Dim>::Interiority(const int  aCoord,int aD) const\n{\n   return std::min(aCoord-tBox::mP0[aD],tBox::mP1[aD]-1-aCoord);\n}\n\ntemplate <const int Dim> int cPixBox<Dim>::Interiority(const tPt &  aP,int aD) const\n{\n   return Interiority(aP[aD],aD);\n}\n\ntemplate <const int Dim> int cPixBox<Dim>::Interiority(const tPt& aP  ) const\n{\n   int aRes = Interiority(aP,0);\n   for (int aD=1 ; aD<Dim ; aD++)\n       aRes = std::min(aRes,Interiority(aP,aD));\n\n   return aRes;\n}\n\ntemplate <const int Dim> int cPixBox<Dim>::WinInteriority(const tPt& aP,const tPt& aWin,int aD) const\n{\n   return Interiority(aP,aD)-aWin[aD];\n}\n\ntemplate <const int Dim> cBorderPixBox<Dim>  cPixBox<Dim>::Border(int aSz) const\n{\n   return  cBorderPixBox<Dim>(*this,aSz);\n}\n\ntemplate <const int Dim> cPtxd<int,Dim>  cPixBox<Dim>::CircNormProj(const tPt & aPt) const\n{\n    cPtxd<int,Dim>  aRes;\n    for (int aD=0 ; aD<Dim ; aD++)\n       aRes[aD] = tBox::mP0[aD] + mod(aPt[aD]-tBox::mP0[aD],tBox::mSz[aD]);\n    return aRes;\n}\n\n\n\n/* ========================== */\n/*       cParseBoxInOut       */\n/* ========================== */\n\n\ntemplate <const int Dim> cParseBoxInOut<Dim>::cParseBoxInOut(const tBox & aBoxGlob,const tBox & aBoxIndexe) :\n    mBoxGlob (aBoxGlob),\n    mBoxIndex (aBoxIndexe)\n{\n}\n        // static tThis  CreateFromMem(const tBox&, double AvalaibleMem);\n\ntemplate <const int Dim> cParseBoxInOut<Dim> cParseBoxInOut<Dim>::CreateFromSize(const tBox & aBox,const tPt & aSzTile)\n{\n   return  tThis(aBox,tBox(tPt::PCste(0),CByC2P(aBox.Sz(),aSzTile,DivSup<int>)));\n}\ntemplate <const int Dim> cParseBoxInOut<Dim> cParseBoxInOut<Dim>::CreateFromSizeCste(const tBox & aBox,int aSz)\n{\n    return CreateFromSize(aBox,tPt::PCste(aSz));\n}\n\ntemplate <const int Dim> cParseBoxInOut<Dim> cParseBoxInOut<Dim>::CreateFromSzMem(const tBox & aBox,double aSzMem)\n{\n    return CreateFromSizeCste(aBox,round_ni(pow(aSzMem,1/double(Dim))));\n}\n\n\ntemplate <const int Dim>  const cPixBox<Dim> &  cParseBoxInOut<Dim>::BoxIndex() const\n{\n      return  mBoxIndex;\n}\n\ntemplate <const int Dim>  cPtxd<int,Dim>  cParseBoxInOut<Dim>::Index2Glob(const tPt & anIndex) const\n{\n      return  CByC1P(mBoxGlob.FromNormaliseCoord(mBoxIndex.ToNormaliseCoord(anIndex)),round_ni);\n}\n\ntemplate <const int Dim>  cPixBox<Dim> cParseBoxInOut<Dim>::BoxOut(const tPt & anIndex) const\n{\n      return  cPixBox<Dim> \n              (\n                   Index2Glob(anIndex),\n                   Index2Glob(anIndex+tPt::PCste(1))\n              );\n}\n\ntemplate <const int Dim>  cPixBox<Dim> cParseBoxInOut<Dim>::BoxIn(const tPt & anIndex,const tPt& aDil) const\n{\n   return mBoxGlob.Inter(BoxOut(anIndex).Dilate(aDil));\n}\n\ntemplate <const int Dim>  cPixBox<Dim> cParseBoxInOut<Dim>::BoxIn(const tPt & anIndex,int aDil) const\n{\n   return mBoxGlob.Inter(BoxOut(anIndex).Dilate(tPt::PCste(aDil)));\n}\n\n/* ========================== */\n/*          cTplBox           */\n/* ========================== */\n\n\ntemplate <class Type,const int Dim>   \n   cTplBox<Type,Dim>::cTplBox\n   (\n       const cPtxd<Type,Dim> & aP0,\n       const cPtxd<Type,Dim> & aP1,\n       bool AllowEmpty\n   ) :\n       mP0  (aP0),\n       mP1  (aP1),\n       mSz  (aP0),\n       mNbElem (1)\n{\n    //for (int aK=Dim-1 ; aK>=0 ; aK--)\n    for (int aK=0 ; aK<Dim ; aK++)\n    {\n       mSz[aK] = mP1[aK] - mP0[aK];\n       if (AllowEmpty)\n       {\n          // make coherent but empty\n          if (mSz[aK] <0)\n          {\n             mP1[aK] = mP0[aK];\n             mSz[aK] = 0;\n          }\n       }\n       else\n       {\n          MMVII_INTERNAL_ASSERT_strong(mSz[aK]>0,MesNegSz);\n       }\n       mSzCum[aK] = mNbElem;\n       mNbElem *= mSz[aK];\n    }\n}\n\ntemplate <class Type,const int Dim>   \n   cTplBox<Type,Dim>::cTplBox\n   (\n       const cPtxd<Type,Dim> & aSz,\n       bool AllowEmpty\n   ) :\n     cTplBox<Type,Dim>(tPt::PCste(0),aSz,AllowEmpty)\n{\n}\n\n\ntemplate <class Type,const int Dim> bool  cTplBox<Type,Dim>::IsEmpty() const\n{\n   return mNbElem == 0;\n}\n\ntemplate <class Type,const int Dim> cTplBox<Type,Dim>  cTplBox<Type,Dim>::Empty()\n{\n   return  cTplBox<Type,Dim>(tPt::PCste(0),true);\n}\n\ntemplate <class Type,const int Dim> cTplBox<Type,Dim>  cTplBox<Type,Dim>::Inter(const tBox & aBox)const\n{\n  return tBox(PtSupEq(mP0,aBox.mP0),PtInfEq(mP1,aBox.mP1),true);\n}\n\ntemplate <class Type,const int Dim> cTplBox<Type,Dim>  cTplBox<Type,Dim>::Sup(const tBox & aB2)const\n{\n  if (IsEmpty() && aB2.IsEmpty()) \n     return  Empty();\n  if (IsEmpty())     return aB2;\n  if (aB2.IsEmpty()) return *this;\n\n  return tBox(PtInfEq(mP0,aB2.mP0),PtSupEq(mP1,aB2.mP1),true);\n}\n\n\n\n\ntemplate <class Type,const int Dim> cTplBox<Type,Dim>  cTplBox<Type,Dim>::Dilate(const tPt & aPt) const\n{\n   return tBox(mP0-aPt,mP1+aPt);\n}\n\n\ntemplate <class Type,const int Dim> cTplBox<Type,Dim>  cTplBox<Type,Dim>::Dilate(const Type & aVal) const\n{\n   return Dilate(tPt::PCste(aVal));\n}\n\ntemplate <class Type,const int Dim> cTplBox<Type,Dim>  cTplBox<Type,Dim>::ScaleCentered(const Type & aVal) const\n{\n   tPt aMil = (mP0+mP1)/Type(2.0);\n   tPt anAmpl = (mP1-mP0)* Type(aVal/2.0);\n   return tBox(aMil-anAmpl,aMil+anAmpl);\n}\n\n\ntemplate <class Type,const int Dim> void cTplBox<Type,Dim>::AssertSameArea(const cTplBox<Type,Dim> & aR2) const\n{\n    MMVII_INTERNAL_ASSERT_strong((*this)==aR2,\"Rect obj were expected to have identic area\");\n}\ntemplate <class Type,const int Dim> void cTplBox<Type,Dim>::AssertSameSz(const cTplBox<Type,Dim> & aR2) const\n{\n    MMVII_INTERNAL_ASSERT_strong(Sz()==aR2.Sz(),\"Rect obj were expected to have identic size\");\n}\n\n\ntemplate <class Type,const int Dim> bool cTplBox<Type,Dim>::operator == (const tBox & aR2) const \n{\n    return (mP0==aR2.mP0) && (mP1==aR2.mP1);\n}\n\ntemplate <class Type,const int Dim> bool cTplBox<Type,Dim>::IncludedIn(const tBox & aR2) const\n{\n    return SupEq(mP0,aR2.mP0) && InfEq(mP1,aR2.mP1) ;\n}\n\ntemplate <class Type,const int Dim> cTplBox<Type,Dim> cTplBox<Type,Dim>::Translate(const cPtxd<Type,Dim> & aTr) const\n{\n   return cTplBox<Type,Dim>(mP0+aTr,mP1+aTr);\n}\n\n\ntemplate <class Type,const int Dim> cPtxd<Type,Dim>  cTplBox<Type,Dim>::FromNormaliseCoord(const cPtxd<double,Dim> & aPN) const \n{\n    // MMVII_INTERNAL_ASSERT_strong(false,\"To Change \n    cPtxd<Type,Dim> aRes;\n    for (int aK=0 ; aK<Dim ; aK++)\n    {\n        // aRes[aK] = mP0[aK] + round_down(mSz[aK]*aPN[aK]);\n        aRes[aK] = mP0[aK] + tBaseNumTrait<Type>::RoundNearestToType(mSz[aK]*aPN[aK]);\n    }\n    return aRes;\n    // return Proj(aRes);\n}\n\ntemplate <class Type,const int Dim> void  cTplBox<Type,Dim>::Corners(tCorner & aRes) const\n{\n    for (size_t aKpt=0; aKpt<(1<<Dim)  ; aKpt++)\n    {\n        for (size_t aD=0 ; aD<Dim ; aD++)\n        {\n            aRes[aKpt][aD] = (aKpt & (1<<aD)) ? mP0[aD] : mP1[aD];\n        }\n    }\n}\n\ntemplate <class Type,const int Dim> cPtxd<double,Dim>  cTplBox<Type,Dim>::ToNormaliseCoord(const cPtxd<Type,Dim> & aP) const \n{\n    cPtxd<double,Dim> aRes;\n    for (int aK=0 ; aK<Dim ; aK++)\n    {\n        aRes[aK] = (aP[aK]-mP0[aK]) / double(mSz[aK]);\n    }\n    return aRes;\n}\n\n\ntemplate <class Type,const int Dim>  cPtxd<double,Dim>  cTplBox<Type,Dim>::RandomNormalised() \n{\n   cPtxd<double,Dim>  aRes;\n   for (int aK=0 ; aK<Dim ; aK++)\n   {\n        aRes[aK] = RandUnif_0_1();\n   }\n   return aRes;\n}\n\ntemplate <class Type,const int Dim> cPtxd<Type,Dim>   cTplBox<Type,Dim>::GeneratePointInside() const\n{\n/*\n   cPtxd<double,Dim> aP0 = RandomNormalised();\n   cPtxd<Type,Dim>  aP1 = FromNormaliseCoord(aP0);\n   cPtxd<Type,Dim> aP2 = Proj(aP1);\nStdOut() << \"BOX \" << mP0 << \" \" << mP1 << \"\\n\";\nStdOut() <<  aP0 << aP1 << aP2 << \"\\n\"; getchar();\n   return aP2;\n*/\n   return Proj(FromNormaliseCoord(RandomNormalised()));\n}\n\ntemplate <class Type,const int Dim> cTplBox<Type,Dim>  cTplBox<Type,Dim>::GenerateRectInside(double aPowSize) const\n{\n    cPtxd<Type,Dim> aP0;\n    cPtxd<Type,Dim> aP1;\n    for (int aK=0 ; aK<Dim ; aK++)\n    {\n        double aSzRed = pow(RandUnif_0_1(),aPowSize);\n        double aX0 = (1-aSzRed) * RandUnif_0_1();\n        double aX1 = aX0 + aSzRed;\n        // int aI0 = round_down(aX0*mSz[aK]);\n        // int aI1 = round_down(aX1*mSz[aK]);\n        Type aI0 =  tBaseNumTrait<Type>::RoundNearestToType(aX0*mSz[aK]);\n        Type aI1 =  tBaseNumTrait<Type>::RoundNearestToType(aX1*mSz[aK]);\n        aI1 = std::min((mP1[aK]-1),std::max(aI1,aI0+1));\n        aI0  = std::max((mP0[aK]),std::min(aI0,aI1-1));\n        aP0[aK] = aI0;\n        aP1[aK] = aI1;\n\n    }\n    return cTplBox<Type,Dim>(aP0,aP1);\n}\n\ncBox2dr ToR(const cBox2di & aBox)\n{\n   return cBox2dr(ToR(aBox.P0()),ToR(aBox.P1()));\n}\n\ncBox2di ToI(const cBox2dr & aBox)\n{\n    return cBox2di(Pt_round_down(aBox.P0()),Pt_round_up(aBox.P1()));\n}\n\ncBox2dr operator * (const cBox2dr & aBox,double aScale)\n{\n    return cBox2dr(aBox.P0()*aScale,aBox.P1()*aScale);\n}\n\n//        x0,y1        x1,y1\n//        x0,y0        x1,y0     \n\ntemplate <class Type> \n    void CornersTrigo(typename cTplBox<Type,2>::tCorner & aRes,const  cTplBox<Type,2>& aBox)\n{\n   aRes[0] = cPtxd<Type,2>(aBox.P1().x(),aBox.P1().y());\n   aRes[1] = cPtxd<Type,2>(aBox.P0().x(),aBox.P1().y());\n   aRes[2] = cPtxd<Type,2>(aBox.P0().x(),aBox.P0().y());\n   aRes[3] = cPtxd<Type,2>(aBox.P1().x(),aBox.P0().y());\n}\n\n\n\n\n/* ========================== */\n/*       cTpxBoxOfPts         */\n/* ========================== */\n\ntemplate <class Type,const int Dim>   cTplBoxOfPts<Type,Dim>::cTplBoxOfPts() :\n   mNbPts (0),\n   mP0    (tPt::PCste(0)),\n   mP1    (tPt::PCste(0))\n{\n}\n\ntemplate <class Type,const int Dim>  int  cTplBoxOfPts<Type,Dim>::NbPts() const {return mNbPts;}\n\ntemplate <class Type,const int Dim>  const cPtxd<Type,Dim> &  cTplBoxOfPts<Type,Dim>::P0() const\n{\n   MMVII_INTERNAL_ASSERT_medium(mNbPts,\"cTplBoxOfPts<Type,Dim>::P0()\")\n   return  mP0;\n}\n\ntemplate <class Type,const int Dim>  const cPtxd<Type,Dim> &  cTplBoxOfPts<Type,Dim>::P1() const\n{\n   MMVII_INTERNAL_ASSERT_medium(mNbPts,\"cTplBoxOfPts<Type,Dim>::P1()\")\n   return  mP1;\n}\n\ntemplate <class Type,const int Dim>  cTplBox<Type,Dim>  cTplBoxOfPts<Type,Dim>::CurBox() const\n{\n    return  cTplBox<Type,Dim>(mP0,mP1);\n}\n\ntemplate <class Type,const int Dim>  void  cTplBoxOfPts<Type,Dim>::Add(const tPt & aP)\n{\n   if (mNbPts==0)\n   {\n      mP0 = aP;\n      mP1 = aP;\n   }\n   else\n   {\n      SetInfEq(mP0,aP);\n      SetSupEq(mP1,aP);\n   }\n   mNbPts++;\n}\n\ntemplate <class Type,const int Dim>  cPtxd<int,Dim> Pt_round_down(const cPtxd<Type,Dim>  aP)\n{\n   return ICByC1P(aP,round_down);\n}\ntemplate <class Type,const int Dim>  cPtxd<int,Dim> Pt_round_up(const cPtxd<Type,Dim>  aP)\n{\n   return ICByC1P(aP,round_up);\n}\ntemplate <class Type,const int Dim>  cPtxd<int,Dim> Pt_round_ni(const cPtxd<Type,Dim>  aP)\n{\n   return ICByC1P(aP,round_ni);\n}\n\n\ntemplate <class Type> bool WindInside4BL(const cBox2di & aBox,const cPtxd<Type,2> & aPt,const  cPt2di & aSzW)\n{\n   return\n\t   (aPt.x() >= aBox.P0().x() + aSzW.x())\n       &&  (aPt.y() >= aBox.P0().y() + aSzW.y())\n       &&  (aPt.x() <  aBox.P1().x() - aSzW.x()-1)\n       &&  (aPt.y() <  aBox.P1().y() - aSzW.y()-1) ;\n}\n\n\n/* ========================== */\n/*       INSTANTIATION        */\n/* ========================== */\n\ntemplate void CornersTrigo(typename cTplBox<tREAL8,2>::tCorner & aRes,const  cTplBox<tREAL8,2>&);\ntemplate void CornersTrigo(typename cTplBox<tINT4,2>::tCorner & aRes,const  cTplBox<tINT4,2>&);\n\ntemplate  bool WindInside4BL(const cBox2di & aBox,const cPtxd<tINT4,2> & aPt,const  cPt2di & aSzW);\ntemplate  bool WindInside4BL(const cBox2di & aBox,const cPtxd<tREAL8,2> & aPt,const  cPt2di & aSzW);\n\n#define MACRO_INSTATIATE_PTXD_2DIM(TYPE,DIMIN,DIMOUT)\\\ntemplate  cPtxd<TYPE,DIMOUT> CastDim<TYPE,DIMOUT,DIMIN>(const cPtxd<TYPE,DIMIN> & aPt);\n\n#define MACRO_INSTATIATE_PTXD(TYPE,DIM)\\\nMACRO_INSTATIATE_PTXD_2DIM(TYPE,DIM,1);\\\nMACRO_INSTATIATE_PTXD_2DIM(TYPE,DIM,2);\\\nMACRO_INSTATIATE_PTXD_2DIM(TYPE,DIM,3);\\\nMACRO_INSTATIATE_PTXD_2DIM(TYPE,DIM,4);\\\ntemplate  std::ostream & operator << (std::ostream & OS,const cPtxd<TYPE,DIM> &aP);\\\ntemplate  cPtxd<TYPE,DIM> cPtxd<TYPE,DIM>::PCste(const TYPE&);\\\ntemplate  cPtxd<TYPE,DIM> cPtxd<TYPE,DIM>::PRand();\\\ntemplate  cPtxd<TYPE,DIM> cPtxd<TYPE,DIM>::PRandC();\\\ntemplate  cPtxd<TYPE,DIM> cPtxd<TYPE,DIM>::PRandUnit();\\\ntemplate  cPtxd<TYPE,DIM> cPtxd<TYPE,DIM>::PRandInSphere();\\\ntemplate typename cPtxd<TYPE,DIM>::tBigNum cPtxd<TYPE,DIM>::MinSqN2(const std::vector<tPt> &,bool SVP) const;\\\ntemplate  cPtxd<TYPE,DIM>  cPtxd<TYPE,DIM>::PRandUnitDiff(const cPtxd<TYPE,DIM>& ,const TYPE&);\\\ntemplate  double NormK(const cPtxd<TYPE,DIM> & aPt,double anExp);\\\ntemplate  double Norm2(const cPtxd<TYPE,DIM> & aPt);\\\ntemplate  TYPE Norm1(const cPtxd<TYPE,DIM> & aPt);\\\ntemplate  TYPE NormInf(const cPtxd<TYPE,DIM> & aPt);\\\ntemplate  TYPE MinAbsCoord(const cPtxd<TYPE,DIM> & aPt);\\\ntemplate  typename  tNumTrait<TYPE>::tBig Scal(const cPtxd<TYPE,DIM> &,const cPtxd<TYPE,DIM> &);\\\ntemplate  TYPE Cos(const cPtxd<TYPE,DIM> &,const cPtxd<TYPE,DIM> &);\\\ntemplate  cPtxd<TYPE,DIM>  VUnit(const cPtxd<TYPE,DIM> & aP);\\\ntemplate  cPtxd<TYPE,DIM>  cPtxd<TYPE,DIM>::FromPtInt(const cPtxd<int,DIM> & aPInt);\n\n// template  cPtxd<TYPE,DIM>  PCste(const DIM & aVal);\n\n#define MACRO_INSTATIATE_POINT(DIM)\\\nMACRO_INSTATIATE_PTXD(tINT4,DIM)\\\nMACRO_INSTATIATE_PTXD(tREAL4,DIM)\\\nMACRO_INSTATIATE_PTXD(tREAL8,DIM)\\\nMACRO_INSTATIATE_PTXD(tREAL16,DIM)\n\n#define MACRO_INSTATIATE_PRECT_DIM(DIM)\\\nMACRO_INSTATIATE_POINT(DIM)\\\ntemplate const std::vector<std::vector<cPtxd<int,DIM>>> & TabGrowNeigh(int);\\\ntemplate const std::vector<cPtxd<int,DIM>> & AllocNeighbourhood(int);\\\ntemplate cPtxd<int,DIM> Pt_round_down(const cPtxd<double,DIM>  aP);\\\ntemplate cPtxd<int,DIM> Pt_round_up(const cPtxd<double,DIM>  aP);\\\ntemplate cPtxd<int,DIM> Pt_round_ni(const cPtxd<double,DIM>  aP);\\\ntemplate class cBorderPixBoxIterator<DIM>;\\\ntemplate class cBorderPixBox<DIM>;\\\ntemplate class cTplBox<tINT4,DIM>;\\\ntemplate class cTplBoxOfPts<tINT4,DIM>;\\\ntemplate  class cParseBoxInOut<DIM>;\\\ntemplate class cTplBox<tREAL8,DIM>;\\\ntemplate class cTplBoxOfPts<tREAL8,DIM>;\\\ntemplate class cPixBox<DIM>;\\\ntemplate  int NbPixVign(const cPtxd<int,DIM> & aVign);\\\ntemplate class cDataGenUnTypedIm<DIM>;\\\ntemplate <> const cPixBox<DIM> cPixBox<DIM>::TheEmptyBox(cPtxd<int,DIM>::PCste(0),cPtxd<int,DIM>::PCste(0),true);\n\n\n/*\nvoid F()\n{\n   cPtxd<tINT4,2>::T_PCste(2);\n}\n*/\n\nMACRO_INSTATIATE_PRECT_DIM(1)\nMACRO_INSTATIATE_PRECT_DIM(2)\nMACRO_INSTATIATE_PRECT_DIM(3)\nMACRO_INSTATIATE_POINT(4)\n\n\n\n};\n", "meta": {"hexsha": "00ea7523227d47aef17acae89cda311b01e116e8", "size": 25345, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MMVII/src/ImagesBase/PtsBox.cpp", "max_stars_repo_name": "micmacIGN/micmac", "max_stars_repo_head_hexsha": "4aba7eb1b330d5dfd87afdb88ce40ac3372aff26", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": 451.0, "max_stars_repo_stars_event_min_datetime": "2016-11-25T09:40:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T04:20:42.000Z", "max_issues_repo_path": "MMVII/src/ImagesBase/PtsBox.cpp", "max_issues_repo_name": "Pandinosaurus/micmac", "max_issues_repo_head_hexsha": "4aba7eb1b330d5dfd87afdb88ce40ac3372aff26", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": 143.0, "max_issues_repo_issues_event_min_datetime": "2016-11-25T20:35:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T11:58:02.000Z", "max_forks_repo_path": "MMVII/src/ImagesBase/PtsBox.cpp", "max_forks_repo_name": "micmacIGN/micmac", "max_forks_repo_head_hexsha": "558a0d104bc07150b2ff1fe2d5fb952b8f70088d", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2016-12-02T10:26:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T19:40:29.000Z", "avg_line_length": 27.9746136865, "max_line_length": 128, "alphanum_fraction": 0.6159794831, "num_tokens": 9035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.257774190440236}}
{"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_GN_SINU_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_GN_SINU_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#include <boost/geometry/srs/projections/impl/aasincos.hpp>\n#include <boost/geometry/srs/projections/impl/pj_mlfn.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace gn_sinu\n    {\n\n            static const double epsilon10 = 1e-10;\n            static const int max_iter = 8;\n            static const double loop_tol = 1e-7;\n\n            template <typename T>\n            struct par_gn_sinu\n            {\n                detail::en<T> en;\n                T    m, n, C_x, C_y;\n            };\n\n            /* Ellipsoidal Sinusoidal only */\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename T, typename Parameters>\n            struct base_gn_sinu_ellipsoid\n                : public base_t_fi<base_gn_sinu_ellipsoid<T, Parameters>, T, Parameters>\n            {\n                par_gn_sinu<T> m_proj_parm;\n\n                inline base_gn_sinu_ellipsoid(const Parameters& par)\n                    : base_t_fi<base_gn_sinu_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 s, c;\n\n                    xy_y = pj_mlfn(lp_lat, s = sin(lp_lat), c = cos(lp_lat), this->m_proj_parm.en);\n                    xy_x = lp_lon * c / sqrt(1. - this->m_par.es * s * s);\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 const& xy_y, T& lp_lon, T& lp_lat) const\n                {\n                    static const T half_pi = detail::half_pi<T>();\n\n                    T s;\n\n                    if ((s = fabs(lp_lat = pj_inv_mlfn(xy_y, this->m_par.es, this->m_proj_parm.en))) < half_pi) {\n                        s = sin(lp_lat);\n                        lp_lon = xy_x * sqrt(1. - this->m_par.es * s * s) / cos(lp_lat);\n                    } else if ((s - epsilon10) < half_pi)\n                        lp_lon = 0.;\n                    else\n                        BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\n                }\n                /* General spherical sinusoidals */\n\n                static inline std::string get_name()\n                {\n                    return \"gn_sinu_ellipsoid\";\n                }\n\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename T, typename Parameters>\n            struct base_gn_sinu_spheroid\n                : public base_t_fi<base_gn_sinu_spheroid<T, Parameters>, T, Parameters>\n            {\n                par_gn_sinu<T> m_proj_parm;\n\n                inline base_gn_sinu_spheroid(const Parameters& par)\n                    : base_t_fi<base_gn_sinu_spheroid<T, Parameters>, T, Parameters>(*this, par)\n                {}\n\n                // FORWARD(s_forward)  sphere\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(T const& lp_lon, T lp_lat, T& xy_x, T& xy_y) const\n                {\n                    if (this->m_proj_parm.m == 0.0)\n                        lp_lat = this->m_proj_parm.n != 1. ? aasin(this->m_proj_parm.n * sin(lp_lat)): lp_lat;\n                    else {\n                        T k, V;\n                        int i;\n\n                        k = this->m_proj_parm.n * sin(lp_lat);\n                        for (i = max_iter; i ; --i) {\n                            lp_lat -= V = (this->m_proj_parm.m * lp_lat + sin(lp_lat) - k) /\n                                (this->m_proj_parm.m + cos(lp_lat));\n                            if (fabs(V) < loop_tol)\n                                break;\n                        }\n                        if (!i) {\n                            BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\n                        }\n                    }\n                    xy_x = this->m_proj_parm.C_x * lp_lon * (this->m_proj_parm.m + cos(lp_lat));\n                    xy_y = this->m_proj_parm.C_y * lp_lat;\n                }\n\n                // INVERSE(s_inverse)  sphere\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                    xy_y /= this->m_proj_parm.C_y;\n                    lp_lat = (this->m_proj_parm.m != 0.0) ? aasin((this->m_proj_parm.m * xy_y + sin(xy_y)) / this->m_proj_parm.n) :\n                        ( this->m_proj_parm.n != 1. ? aasin(sin(xy_y) / this->m_proj_parm.n) : xy_y );\n                    lp_lon = xy_x / (this->m_proj_parm.C_x * (this->m_proj_parm.m + cos(xy_y)));\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"gn_sinu_spheroid\";\n                }\n\n            };\n\n            template <typename Parameters, typename T>\n            inline void setup(Parameters& par, par_gn_sinu<T>& proj_parm) \n            {\n                par.es = 0;\n\n                proj_parm.C_x = (proj_parm.C_y = sqrt((proj_parm.m + 1.) / proj_parm.n))/(proj_parm.m + 1.);\n            }\n\n\n            // General Sinusoidal Series\n            template <typename Params, typename Parameters, typename T>\n            inline void setup_gn_sinu(Params const& params, Parameters& par, par_gn_sinu<T>& proj_parm)\n            {\n                if (pj_param_f<srs::spar::n>(params, \"n\", srs::dpar::n, proj_parm.n)\n                 && pj_param_f<srs::spar::m>(params, \"m\", srs::dpar::m, proj_parm.m)) {\n                    if (proj_parm.n <= 0 || proj_parm.m < 0)\n                        BOOST_THROW_EXCEPTION( projection_exception(error_invalid_m_or_n) );\n                } else\n                    BOOST_THROW_EXCEPTION( projection_exception(error_invalid_m_or_n) );\n\n                setup(par, proj_parm);\n            }\n\n            // Sinusoidal (Sanson-Flamsteed)\n            template <typename Parameters, typename T>\n            inline void setup_sinu(Parameters& par, par_gn_sinu<T>& proj_parm)\n            {\n                proj_parm.en = pj_enfn<T>(par.es);\n\n                if (par.es != 0.0) {\n                    /* empty */\n                } else {\n                    proj_parm.n = 1.;\n                    proj_parm.m = 0.;\n                    setup(par, proj_parm);\n                }\n            }\n\n            // Eckert VI\n            template <typename Parameters, typename T>\n            inline void setup_eck6(Parameters& par, par_gn_sinu<T>& proj_parm)\n            {\n                proj_parm.m = 1.;\n                proj_parm.n = 2.570796326794896619231321691;\n                setup(par, proj_parm);\n            }\n\n            // McBryde-Thomas Flat-Polar Sinusoidal\n            template <typename Parameters, typename T>\n            inline void setup_mbtfps(Parameters& par, par_gn_sinu<T>& proj_parm)\n            {\n                proj_parm.m = 0.5;\n                proj_parm.n = 1.785398163397448309615660845;\n                setup(par, proj_parm);\n            }\n\n    }} // namespace detail::gn_sinu\n    #endif // doxygen\n\n    /*!\n        \\brief General Sinusoidal Series 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         - m (real)\n         - n (real)\n        \\par Example\n        \\image html ex_gn_sinu.gif\n    */\n    template <typename T, typename Parameters>\n    struct gn_sinu_spheroid : public detail::gn_sinu::base_gn_sinu_spheroid<T, Parameters>\n    {\n        template <typename Params>\n        inline gn_sinu_spheroid(Params const& params, Parameters const& par)\n            : detail::gn_sinu::base_gn_sinu_spheroid<T, Parameters>(par)\n        {\n            detail::gn_sinu::setup_gn_sinu(params, this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Sinusoidal (Sanson-Flamsteed) 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         - Ellipsoid\n        \\par Example\n        \\image html ex_sinu.gif\n    */\n    template <typename T, typename Parameters>\n    struct sinu_ellipsoid : public detail::gn_sinu::base_gn_sinu_ellipsoid<T, Parameters>\n    {\n        template <typename Params>\n        inline sinu_ellipsoid(Params const& , Parameters const& par)\n            : detail::gn_sinu::base_gn_sinu_ellipsoid<T, Parameters>(par)\n        {\n            detail::gn_sinu::setup_sinu(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Sinusoidal (Sanson-Flamsteed) 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         - Ellipsoid\n        \\par Example\n        \\image html ex_sinu.gif\n    */\n    template <typename T, typename Parameters>\n    struct sinu_spheroid : public detail::gn_sinu::base_gn_sinu_spheroid<T, Parameters>\n    {\n        template <typename Params>\n        inline sinu_spheroid(Params const& , Parameters const& par)\n            : detail::gn_sinu::base_gn_sinu_spheroid<T, Parameters>(par)\n        {\n            detail::gn_sinu::setup_sinu(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Eckert VI 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 Example\n        \\image html ex_eck6.gif\n    */\n    template <typename T, typename Parameters>\n    struct eck6_spheroid : public detail::gn_sinu::base_gn_sinu_spheroid<T, Parameters>\n    {\n        template <typename Params>\n        inline eck6_spheroid(Params const& , Parameters const& par)\n            : detail::gn_sinu::base_gn_sinu_spheroid<T, Parameters>(par)\n        {\n            detail::gn_sinu::setup_eck6(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief McBryde-Thomas Flat-Polar 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 Example\n        \\image html ex_mbtfps.gif\n    */\n    template <typename T, typename Parameters>\n    struct mbtfps_spheroid : public detail::gn_sinu::base_gn_sinu_spheroid<T, Parameters>\n    {\n        template <typename Params>\n        inline mbtfps_spheroid(Params const& , Parameters const& par)\n            : detail::gn_sinu::base_gn_sinu_spheroid<T, Parameters>(par)\n        {\n            detail::gn_sinu::setup_mbtfps(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_gn_sinu, gn_sinu_spheroid, gn_sinu_spheroid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::spar::proj_sinu, sinu_spheroid, sinu_ellipsoid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::spar::proj_eck6, eck6_spheroid, eck6_spheroid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::spar::proj_mbtfps, mbtfps_spheroid, mbtfps_spheroid)\n\n        // Factory entry(s)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(gn_sinu_entry, gn_sinu_spheroid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI2(sinu_entry, sinu_spheroid, sinu_ellipsoid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(eck6_entry, eck6_spheroid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(mbtfps_entry, mbtfps_spheroid)\n        \n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_BEGIN(gn_sinu_init)\n        {\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(gn_sinu, gn_sinu_entry);\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(sinu, sinu_entry);\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(eck6, eck6_entry);\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(mbtfps, mbtfps_entry);\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n} // namespace projections\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_GN_SINU_HPP\n\n", "meta": {"hexsha": "b4218cc839d65cd50cdfefc10e6b80289941920c", "size": 15300, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/boost/geometry/srs/projections/proj/gn_sinu.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/geometry/srs/projections/proj/gn_sinu.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/geometry/srs/projections/proj/gn_sinu.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": 39.7402597403, "max_line_length": 131, "alphanum_fraction": 0.5980392157, "num_tokens": 3633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.257714699844236}}
{"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/*\n Copyright (C) 2008 Roland Stamm\n Copyright (C) 2009 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 <qle/instruments/cdsoption.hpp>\n#include <qle/pricingengines/blackcdsoptionengine.hpp>\n\n#include <ql/exercise.hpp>\n#include <ql/instruments/payoffs.hpp>\n#include <ql/math/distributions/normaldistribution.hpp>\n#include <ql/math/solvers1d/brent.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/termstructures/volatility/equityfx/blackconstantvol.hpp>\n#include <ql/termstructures/yieldtermstructure.hpp>\n\n#include <boost/make_shared.hpp>\n\nnamespace QuantExt {\n\nnamespace {\n\nclass ImpliedVolHelper {\npublic:\n    ImpliedVolHelper(const CdsOption& cdsoption, const Handle<DefaultProbabilityTermStructure>& probability,\n                     Real recoveryRate, const Handle<YieldTermStructure>& termStructure, Real targetValue)\n        : targetValue_(targetValue) {\n\n        vol_ = boost::shared_ptr<SimpleQuote>(new SimpleQuote(0.0));\n        Handle<BlackVolTermStructure> h(\n            boost::make_shared<BlackConstantVol>(0, NullCalendar(), Handle<Quote>(vol_), Actual365Fixed()));\n        engine_ = boost::shared_ptr<PricingEngine>(\n            new QuantExt::BlackCdsOptionEngine(probability, recoveryRate, termStructure, h));\n        cdsoption.setupArguments(engine_->getArguments());\n\n        results_ = dynamic_cast<const Instrument::results*>(engine_->getResults());\n    }\n    Real operator()(Volatility x) const {\n        vol_->setValue(x);\n        engine_->calculate();\n        return results_->value - targetValue_;\n    }\n\nprivate:\n    boost::shared_ptr<PricingEngine> engine_;\n    Real targetValue_;\n    boost::shared_ptr<SimpleQuote> vol_;\n    const Instrument::results* results_;\n};\n} // namespace\n\nCdsOption::CdsOption(const boost::shared_ptr<CreditDefaultSwap>& swap, const boost::shared_ptr<Exercise>& exercise,\n                     bool knocksOut, const Real strike, const StrikeType strikeType)\n    : Option(boost::shared_ptr<Payoff>(new NullPayoff), exercise), swap_(swap), knocksOut_(knocksOut),\n      strike_(strike == Null<Real>() ? swap_->runningSpread() : strike), strikeType_(strikeType) {\n    registerWith(swap_);\n}\n\nbool CdsOption::isExpired() const { return detail::simple_event(exercise_->dates().back()).hasOccurred(); }\n\nvoid CdsOption::setupExpired() const {\n    Instrument::setupExpired();\n    riskyAnnuity_ = 0.0;\n}\n\nvoid CdsOption::setupArguments(PricingEngine::arguments* args) const {\n    swap_->setupArguments(args);\n    Option::setupArguments(args);\n\n    CdsOption::arguments* arguments = dynamic_cast<CdsOption::arguments*>(args);\n\n    QL_REQUIRE(arguments != 0, \"wrong argument type\");\n\n    arguments->swap = swap_;\n    arguments->knocksOut = knocksOut_;\n    arguments->strike = strike_;\n    arguments->strikeType = strikeType_;\n}\n\nvoid CdsOption::fetchResults(const PricingEngine::results* r) const {\n    Option::fetchResults(r);\n    const CdsOption::results* results = dynamic_cast<const CdsOption::results*>(r);\n    QL_ENSURE(results != 0, \"wrong results type\");\n    riskyAnnuity_ = results->riskyAnnuity;\n}\n\nRate CdsOption::atmRate() const { return swap_->fairSpread(); }\n\nReal CdsOption::riskyAnnuity() const {\n    calculate();\n    QL_REQUIRE(riskyAnnuity_ != Null<Real>(), \"risky annuity not provided\");\n    return riskyAnnuity_;\n}\n\nVolatility CdsOption::impliedVolatility(Real targetValue, const Handle<YieldTermStructure>& termStructure,\n                                        const Handle<DefaultProbabilityTermStructure>& probability, Real recoveryRate,\n                                        Real accuracy, Size maxEvaluations, Volatility minVol,\n                                        Volatility maxVol) const {\n    calculate();\n    QL_REQUIRE(!isExpired(), \"instrument expired\");\n\n    Volatility guess = 0.10;\n\n    ImpliedVolHelper f(*this, probability, recoveryRate, termStructure, targetValue);\n    Brent solver;\n    solver.setMaxEvaluations(maxEvaluations);\n    return solver.solve(f, accuracy, guess, minVol, maxVol);\n}\n\nvoid CdsOption::arguments::validate() const {\n    CreditDefaultSwap::arguments::validate();\n    Option::arguments::validate();\n    QL_REQUIRE(swap, \"CDS not set\");\n    QL_REQUIRE(exercise, \"exercise not set\");\n}\n\nvoid CdsOption::results::reset() {\n    Option::results::reset();\n    riskyAnnuity = Null<Real>();\n}\n} // namespace QuantExt\n", "meta": {"hexsha": "0feb254fd010d6e524bd9816ea09b8b68166c24a", "size": 5730, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/instruments/cdsoption.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/cdsoption.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/cdsoption.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": 37.4509803922, "max_line_length": 118, "alphanum_fraction": 0.7226876091, "num_tokens": 1318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2576146930703864}}
{"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/Tensor/Tensor.hpp\"\n#include \"DataStructures/Variables.hpp\"\n#include \"Domain/Structure/Direction.hpp\"\n#include \"Domain/Structure/Element.hpp\"\n#include \"Domain/Structure/ElementId.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/WenoGridHelpers.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/WenoHelpers.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/WenoOscillationIndicator.hpp\"\n#include \"NumericalAlgorithms/Interpolation/RegularGridInterpolant.hpp\"\n#include \"NumericalAlgorithms/LinearOperators/MeanValue.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"Utilities/Gsl.hpp\"\n\nnamespace Limiters::Weno_detail {\n\n// Compute the Simple WENO solution for one tensor component\n//\n// This interface is intended for use in limiters that check the troubled-cell\n// indicator independently for each tensor component. These limiters generally\n// need to limit only a subset of the tensor components.\n//\n// When calling `simple_weno_impl`,\n// - `interpolator_buffer` may be empty\n// - `modified_neighbor_solution_buffer` should contain one DataVector for each\n//   neighboring element (i.e. for each entry in `neighbor_data`)\ntemplate <typename Tag, size_t VolumeDim, typename PackagedData>\nvoid simple_weno_impl(\n    const gsl::not_null<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    const gsl::not_null<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    const gsl::not_null<typename Tag::type*> tensor,\n    const double neighbor_linear_weight, const size_t tensor_storage_index,\n    const Mesh<VolumeDim>& mesh, const Element<VolumeDim>& element,\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) noexcept {\n  // Check that basis is LGL or LG\n  // Note that the SimpleWeno implementation should generalize well to other\n  // bases beyond LGL or LG, once the oscillation_indicator function has been\n  // generalized.\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  ASSERT(\n      modified_neighbor_solution_buffer->size() == neighbor_data.size(),\n      \"modified_neighbor_solution_buffer->size() = \"\n          << modified_neighbor_solution_buffer->size()\n          << \"\\nneighbor_data.size() = \" << neighbor_data.size()\n          << \"\\nmodified_neighbor_solution_buffer was incorrectly initialized \"\n             \"before calling simple_weno_impl.\");\n\n  // Compute the modified neighbor solutions.\n  // First extrapolate neighbor data onto local grid points, then shift the\n  // extrapolated data so its mean matches the local mean.\n  DataVector& component_to_limit = (*tensor)[tensor_storage_index];\n  const double local_mean = mean_value(component_to_limit, mesh);\n  for (const auto& neighbor_and_data : neighbor_data) {\n    const auto& neighbor = neighbor_and_data.first;\n    const auto& data = neighbor_and_data.second;\n\n    if (interpolator_buffer->find(neighbor) == interpolator_buffer->end()) {\n      // No interpolator found => create one\n      const auto& direction = neighbor.first;\n      const auto& source_mesh = data.mesh;\n      const auto target_1d_logical_coords =\n          Weno_detail::local_grid_points_in_neighbor_logical_coords(\n              mesh, source_mesh, element, direction);\n      interpolator_buffer->insert(std::make_pair(\n          neighbor, intrp::RegularGrid<VolumeDim>(source_mesh, mesh,\n                                                  target_1d_logical_coords)));\n    }\n\n    // Avoid allocations by working directly in the preallocated buffer\n    DataVector& buffer = modified_neighbor_solution_buffer->at(neighbor);\n\n    interpolator_buffer->at(neighbor).interpolate(\n        make_not_null(&buffer),\n        get<Tag>(data.volume_data)[tensor_storage_index]);\n    const double neighbor_mean = mean_value(buffer, mesh);\n    buffer += (local_mean - neighbor_mean);\n  }\n\n  // Sum local and modified neighbor polynomials for the WENO reconstruction\n  Weno_detail::reconstruct_from_weighted_sum(\n      make_not_null(&component_to_limit), neighbor_linear_weight,\n      Weno_detail::DerivativeWeight::PowTwoEll, mesh,\n      *modified_neighbor_solution_buffer);\n}\n\n// Compute the Simple WENO solution for one tensor\n//\n// This interface is intended for use in limiters that check the troubled-cell\n// indicator for the whole cell, and apply the limiter to all fields.\n//\n// When calling `simple_weno_impl`,\n// - `interpolator_buffer` may be empty\n// - `modified_neighbor_solution_buffer` should contain one DataVector for each\n//   neighboring element (i.e. for each entry in `neighbor_data`)\ntemplate <typename Tag, size_t VolumeDim, typename PackagedData>\nvoid simple_weno_impl(\n    const gsl::not_null<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    const gsl::not_null<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    const gsl::not_null<typename Tag::type*> tensor,\n    const double neighbor_linear_weight, const Mesh<VolumeDim>& mesh,\n    const Element<VolumeDim>& element,\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) noexcept {\n  for (size_t tensor_storage_index = 0; tensor_storage_index < tensor->size();\n       ++tensor_storage_index) {\n    simple_weno_impl<Tag>(interpolator_buffer,\n                          modified_neighbor_solution_buffer, tensor,\n                          neighbor_linear_weight, tensor_storage_index, mesh,\n                          element, neighbor_data);\n  }\n}\n\n}  // namespace Limiters::Weno_detail\n", "meta": {"hexsha": "8815bbc67214eeb8094d722dd1b09dc849eb6fad", "size": 6962, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/DiscontinuousGalerkin/Limiters/SimpleWenoImpl.hpp", "max_stars_repo_name": "macedo22/spectre", "max_stars_repo_head_hexsha": "97b2b7ae356cf86830258cb5f689f1191fdb6ddd", "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/SimpleWenoImpl.hpp", "max_issues_repo_name": "macedo22/spectre", "max_issues_repo_head_hexsha": "97b2b7ae356cf86830258cb5f689f1191fdb6ddd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-06-04T20:26:40.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-27T14:54:55.000Z", "max_forks_repo_path": "src/Evolution/DiscontinuousGalerkin/Limiters/SimpleWenoImpl.hpp", "max_forks_repo_name": "macedo22/spectre", "max_forks_repo_head_hexsha": "97b2b7ae356cf86830258cb5f689f1191fdb6ddd", "max_forks_repo_licenses": ["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.5032679739, "max_line_length": 80, "alphanum_fraction": 0.7230680839, "num_tokens": 1558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.257469187222381}}
{"text": "#ifndef FSTCRITERIONNORMALDIVERGENCE_H\n#define FSTCRITERIONNORMALDIVERGENCE_H\n\n/*!======================================================================\n   Feature Selection Toolbox 3 source code\n   ---------------------------------------\n\t\n   \\file    criterion_normal_divergence.hpp\n   \\brief   Implements Divergence (distance) based on normal (gaussian) model to serve as feature selection criterion\n   \\author  Petr Somol (somol@utia.cas.cz) with collaborators, see Contacts at http://fst.utia.cz\n   \\date    October 2010\n   \\version 3.0.0.beta\n   \\note    FST3 was developed using gcc 4.3 and requires\n   \\note    \\li Boost library (http://www.boost.org/, tested with versions 1.33.1 and 1.44),\n   \\note    \\li (\\e optionally) LibSVM (http://www.csie.ntu.edu.tw/~cjlin/libsvm/, \n                tested with version 3.00)\n   \\note    Note that LibSVM is required for SVM related tools only,\n            as demonstrated in demo12t.cpp, demo23.cpp, demo25t.cpp, demo32t.cpp, etc.\n\n*/ /* \n=========================================================================\nCopyright:\n  * FST3 software (with exception of any externally linked libraries) \n    is copyrighted by Institute of Information Theory and Automation (UTIA), \n    Academy of Sciences of the Czech Republic.\n  * FST3 source codes as presented here do not contain code of third parties. \n    FST3 may need linkage to external libraries to exploit its functionality\n    in full. For details on obtaining and possible usage restrictions \n    of external libraries follow their original sources (referenced from\n    FST3 documentation wherever applicable).\n  * FST3 software is available free of charge for non-commercial use. \n    Please address all inquires concerning possible commercial use \n    of FST3, or if in doubt, to FST3 maintainer (see http://fst.utia.cz)\n  * Derivative works based on FST3 are permitted as long as they remain\n    non-commercial only.\n  * Re-distribution of FST3 software is not allowed without explicit\n    consent of the copyright holder.\nDisclaimer of Warranty:\n  * FST3 software is presented \"as is\", without warranty of any kind, \n    either expressed or implied, including, but not limited to, the implied \n    warranties of merchantability and fitness for a particular purpose. \n    The entire risk as to the quality and performance of the program \n    is with you. Should the program prove defective, you assume the cost \n    of all necessary servicing, repair or correction.\nLimitation of Liability:\n  * The copyright holder will in no event be liable to you for damages, \n    including any general, special, incidental or consequential damages \n    arising out of the use or inability to use the code (including but not \n    limited to loss of data or data being rendered inaccurate or losses \n    sustained by you or third parties or a failure of the program to operate \n    with any other programs).\n========================================================================== */\n\n#include <boost/smart_ptr.hpp>\n#include <iostream>\n#include <cmath>\n#include \"error.hpp\"\n#include \"global.hpp\"\n#include \"criterion_normal.hpp\"\n#include \"indexed_vector.hpp\"\n#include \"indexed_matrix.hpp\"\n\n/*============== Template parameter type naming conventions ==============\n--------- Numeric types: -------------------------------------------------\nDATATYPE - data sample values - usually real numbers (but may be integers\n          in text processing etc.)\nREALTYPE - must be real numbers - for representing intermediate results of \n          calculations like mean, covariance etc.\nIDXTYPE - index values for enumeration of data samples - (nonnegative) integers, \n          extent depends on numbers of samples in data\nDIMTYPE - index values for enumeration of features (dimensions), or classes (not \n          class sizes) - (nonnegative) integers, usually lower extent than IDXTYPE, \n          but be aware of expressions like _classes*_features*_features ! \n          in linearized representations of feature matrices for all classes\nBINTYPE - feature selection marker type - represents ca. <10 different feature \n          states (selected, deselected, sel./desel. temporarily 1st nested loop, 2nd...)\nRETURNTYPE - criterion value: real value, but may be extended in future to support \n          multiple values \n--------- Class types: ---------------------------------------------------\nSUBSET       - class of class type Subset \nCLASSIFIER   - class implementing interface defined in abstract class Classifier \nEVALUATOR    - class implementing interface defined in abstract class Sequential_Step \nDISTANCE     - class implementing interface defined in abstract class Distance \nDATAACCESSOR - class implementing interface defined in abstract class Data_Accessor \nINTERVALCONTAINER - class of class type TIntervaller \nCONTAINER    - STL container of class type TInterval  \n========================================================================== */\n\nnamespace FST {\n\n/*! \\brief Implements Divergence (distance) based on normal (gaussian) model to serve as feature selection criterion \n    \\note Defined for two-class problems only */\ntemplate<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nclass Criterion_Normal_Divergence : public Criterion_Normal<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR> {\npublic:\n\ttypedef Criterion_Normal<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR> parent;\n\ttypedef boost::shared_ptr<DATAACCESSOR> PDataAccessor;\n\ttypedef boost::shared_ptr<SUBSET> PSubset;\n\tCriterion_Normal_Divergence() {notify(\"Criterion_Normal_Divergence constructor.\");}\n\tvirtual ~Criterion_Normal_Divergence() {notify(\"Criterion_Normal_Divergence destructor.\");}\n\n\tvirtual bool evaluate(RETURNTYPE &result, const PSubset sub);\n\tvirtual bool initialize(PDataAccessor da); \n\n\tCriterion_Normal_Divergence* clone() const;\n\tCriterion_Normal_Divergence* sharing_clone() const {throw fst_error(\"Criterion_Normal_Divergence::sharing_clone() not supported, use Criterion_Normal_Divergence::clone() instead.\");}\n\tCriterion_Normal_Divergence* stateless_clone() const {throw fst_error(\"Criterion_Normal_Divergence::stateless_clone() not supported, use Criterion_Normal_Divergence::clone() instead.\");}\n\t\n\tvirtual std::ostream& print(std::ostream& os) const {os << \"Criterion_Normal_Divergence()\"; return os;}\nprivate:\n\tCriterion_Normal_Divergence(const Criterion_Normal_Divergence& cnd); // copy-constructor\nprivate:\n\tboost::scoped_ptr<Indexed_Vector<DATATYPE,DIMTYPE,SUBSET> > _meandif; // to store mean[i]-mean[j]\n\tboost::scoped_ptr<Indexed_Vector<DATATYPE,DIMTYPE,SUBSET> > _diag; // \n\tboost::scoped_ptr<Indexed_Matrix<REALTYPE,DIMTYPE,SUBSET> > _invbuf1; // to store matrix inversions\n\tboost::scoped_ptr<Indexed_Matrix<REALTYPE,DIMTYPE,SUBSET> > _invbuf2; // to store matrix inversions\n\tboost::scoped_ptr<Indexed_Matrix<REALTYPE,DIMTYPE,SUBSET> > _LUtemp; // to store matrix LU decomposition\n};\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nCriterion_Normal_Divergence<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::Criterion_Normal_Divergence(const Criterion_Normal_Divergence& cnd) :\n\tCriterion_Normal<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>(cnd)\n{\n\tnotify(\"Criterion_Normal_Divergence copy-constructor.\");\n\tif(cnd._meandif) _meandif.reset(new Indexed_Vector<DATATYPE,DIMTYPE,SUBSET>(*cnd._meandif));\n\tif(cnd._diag) _diag.reset(new Indexed_Vector<DATATYPE,DIMTYPE,SUBSET>(*cnd._diag));\n\tif(cnd._invbuf1) _invbuf1.reset(new Indexed_Matrix<DATATYPE,DIMTYPE,SUBSET>(*cnd._invbuf1));\n\tif(cnd._invbuf2) _invbuf2.reset(new Indexed_Matrix<DATATYPE,DIMTYPE,SUBSET>(*cnd._invbuf2));\n\tif(cnd._LUtemp) _LUtemp.reset(new Indexed_Matrix<DATATYPE,DIMTYPE,SUBSET>(*cnd._LUtemp));\n}\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nCriterion_Normal_Divergence<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>* Criterion_Normal_Divergence<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::clone() const\n{\n\tCriterion_Normal_Divergence<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR> *clone=new Criterion_Normal_Divergence<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>(*this);\n\tclone->set_cloned();\n\treturn clone;\n}\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nbool Criterion_Normal_Divergence<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::evaluate(RETURNTYPE &result, PSubset sub)\n{\n\tnotify(\"Criterion_Normal_Divergence::evaluate().\");\n\tassert(parent::_model);\n\tassert(parent::get_n()>0);\n\tassert(_meandif);\n\tassert(_diag);\n\tassert(_invbuf1);\n\tassert(_invbuf2);\n\tassert(_LUtemp);\n\tassert(parent::get_n()==_meandif->get_n());\n\tassert(parent::get_n()==_diag->get_n());\n\tassert(parent::get_n()<=_invbuf1->get_n_max());\n\tassert(parent::get_n()<=_invbuf2->get_n_max());\n\tassert(parent::get_n()<=_LUtemp->get_n_max());\n\tassert(sub);\n\t\n\tif(sub->get_d_raw()==0) return false;\n\n\tparent::_model->narrow_to(sub);\n\t_meandif->narrow_to(sub);\n\t\n\t_invbuf1->redim(parent::get_d());\n\t_invbuf2->redim(parent::get_d());\n\t_LUtemp->redim(parent::get_d());\n\n\tIndexed_Matrix<REALTYPE,DIMTYPE,SUBSET> &_cov1=(parent::_model->get_cov()[0]);\n\tIndexed_Matrix<REALTYPE,DIMTYPE,SUBSET> &_cov2=(parent::_model->get_cov()[1]);\n\n\t_cov1.LUdecompose(*_LUtemp);\n\t_cov1.invert(*_invbuf1,*_LUtemp);\t\n\t_cov2.LUdecompose(*_LUtemp);\n\t_cov2.invert(*_invbuf2,*_LUtemp);\n\n\tRETURNTYPE left=0.0;\n\tRETURNTYPE pom;\n\tfor(DIMTYPE j=0;j<parent::get_d();j++)\n\t{\n\t\tpom=0.0;\n\t\tfor(DIMTYPE i=0;i<parent::get_d();i++)\n\t\t{\n\t\t\tpom+=_meandif->at(i)*(_invbuf1->at_raw(i,j)+_invbuf2->at_raw(i,j));\n\t\t}\n\t\tleft+=pom*_meandif->at(j);\n\t}\n\n\tRETURNTYPE right=0.0;\n\tfor(DIMTYPE i=0;i<parent::get_d();i++)\n\t{\n\t\t_diag->at_raw(i)=0.0;\n\t\tfor(DIMTYPE k=0;k<parent::get_d();k++)\n\t\t{\n\t\t\t_diag->at_raw(i)+=_invbuf1->at_raw(i,k)*_cov2.at(k,i);\n\t\t}\n\t}\n\tfor(DIMTYPE i=0;i<parent::get_d();i++)\n\t{\n\t\tfor(DIMTYPE k=0;k<parent::get_d();k++)\n\t\t{\n\t\t\t_diag->at_raw(i)+=_invbuf2->at_raw(i,k)*_cov1.at(k,i);\n\t\t}\n\t}\n\tfor(DIMTYPE i=0;i<parent::get_d();i++) right+=_diag->at_raw(i)-2.0;\n\n\tresult=0.5*left+0.5*right;\n\treturn true;\n}\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nbool Criterion_Normal_Divergence<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::initialize(PDataAccessor da)\n{\n\tif(da->getNoOfClasses()!=2) throw fst_error(\"Criterion_Normal_Divergence() defined for two-class problems only.\");\n\tnotify(\"Criterion_Normal_Divergence::initialize().\");\n\tparent::initialize(da);\n\t\t\n\tif(!_meandif) _meandif.reset(new Indexed_Vector<DATATYPE,DIMTYPE,SUBSET>);\n\tif(parent::get_n()>_meandif->get_n()) _meandif->reset(parent::get_n());\n\tif(!_diag) _diag.reset(new Indexed_Vector<DATATYPE,DIMTYPE,SUBSET>);\n\tif(parent::get_n()>_diag->get_n()) _diag->reset(parent::get_n());\n\tif(!_invbuf1) _invbuf1.reset(new Indexed_Matrix<REALTYPE,DIMTYPE,SUBSET>(parent::get_n()));\n\tif(parent::get_n()>_invbuf1->get_n()) _invbuf1->reset(parent::get_n());\n\tif(!_invbuf2) _invbuf2.reset(new Indexed_Matrix<REALTYPE,DIMTYPE,SUBSET>(parent::get_n()));\n\tif(parent::get_n()>_invbuf2->get_n()) _invbuf2->reset(parent::get_n());\n\tif(!_LUtemp) _LUtemp.reset(new Indexed_Matrix<REALTYPE,DIMTYPE,SUBSET>(parent::get_n(),true));\n\tif(parent::get_n()>_LUtemp->get_n()) _LUtemp->reset(parent::get_n(),true);\n\n\t_meandif->copy_raw(parent::_model->get_mean()[0]);\n\t_meandif->subtract_raw(parent::_model->get_mean()[1]);\n\t\t\n\treturn true; }\n\n\n} // namespace\n#endif // FSTCRITERIONNORMALDIVERGENCE_H ///:~\n", "meta": {"hexsha": "153ae7f4db2889624c34413bde54ffedd29ee0ca", "size": 11888, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "extern/FST3lib/_src_criteria/criterion_normal_divergence.hpp", "max_stars_repo_name": "boussaffawalid/FeatureSelection", "max_stars_repo_head_hexsha": "9768a044c0c0dc2c4a2dc0f6e65413d19e92766c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-07-07T20:18:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-23T06:46:02.000Z", "max_issues_repo_path": "extern/FST3lib/_src_criteria/criterion_normal_divergence.hpp", "max_issues_repo_name": "boussaffawalid/FeatureSelection", "max_issues_repo_head_hexsha": "9768a044c0c0dc2c4a2dc0f6e65413d19e92766c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T08:35:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-10T08:57:35.000Z", "max_forks_repo_path": "extern/FST3lib/_src_criteria/criterion_normal_divergence.hpp", "max_forks_repo_name": "boussaffawalid/FeatureSelection", "max_forks_repo_head_hexsha": "9768a044c0c0dc2c4a2dc0f6e65413d19e92766c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-04-13T13:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-02-26T08:18:47.000Z", "avg_line_length": 50.5872340426, "max_line_length": 207, "alphanum_fraction": 0.7290545087, "num_tokens": 3121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2574691811441767}}
{"text": "/* -*- c++ -*- */\n/*\n * Copyright 2015 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#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include <gnuradio/io_signature.h>\n#include <gnuradio/math.h>\n#include \"corr_est_cc_impl.h\"\n#include <volk/volk.h>\n#include <boost/format.hpp>\n#include <boost/math/special_functions/round.hpp>\n#include <gnuradio/filter/pfb_arb_resampler.h>\n#include <gnuradio/filter/firdes.h>\n\nnamespace gr {\n  namespace digital {\n\n    corr_est_cc::sptr\n    corr_est_cc::make(const std::vector<gr_complex> &symbols,\n                      float sps, unsigned int mark_delay,\n                      float threshold)\n    {\n      return gnuradio::get_initial_sptr\n        (new corr_est_cc_impl(symbols, sps, mark_delay, threshold));\n    }\n\n    corr_est_cc_impl::corr_est_cc_impl(const std::vector<gr_complex> &symbols,\n                                       float sps, unsigned int mark_delay,\n                                       float threshold)\n      : sync_block(\"corr_est_cc\",\n                   io_signature::make(1, 1, sizeof(gr_complex)),\n                   io_signature::make(1, 2, sizeof(gr_complex))),\n        d_src_id(pmt::intern(alias()))\n    {\n      d_sps = sps;\n\n      // In order to easily support the optional second output,\n      // don't deal with an unbounded max number of output items.\n      // For the common case of not using the optional second output,\n      // this ensures we optimally call the volk routines.\n      const size_t nitems = 24*1024;\n      set_max_noutput_items(nitems);\n      d_corr = (gr_complex *)\n               volk_malloc(sizeof(gr_complex)*nitems, volk_get_alignment());\n      d_corr_mag = (float *)\n                   volk_malloc(sizeof(float)*nitems, volk_get_alignment());\n\n      // Create time-reversed conjugate of symbols\n      d_symbols = symbols;\n      for(size_t i=0; i < d_symbols.size(); i++) {\n          d_symbols[i] = conj(d_symbols[i]);\n      }\n      std::reverse(d_symbols.begin(), d_symbols.end());\n\n      set_mark_delay(mark_delay);\n      set_threshold(threshold);\n\n      // Correlation filter\n      d_filter = new kernel::fft_filter_ccc(1, d_symbols);\n\n      // Per comments in gr-filter/include/gnuradio/filter/fft_filter.h,\n      // set the block output multiple to the FFT filter kernel's internal,\n      // assumed \"nsamples\", to ensure the scheduler always passes a\n      // proper number of samples.\n      int nsamples;\n      nsamples = d_filter->set_taps(d_symbols);\n      set_output_multiple(nsamples);\n\n      // It looks like the kernel::fft_filter_ccc stashes a tail between\n      // calls, so that contains our filtering history (I think).  The\n      // fft_filter_ccc block (which calls the kernel::fft_filter_ccc) sets\n      // the history to 1 (0 history items), so let's follow its lead.\n      //set_history(1);\n\n      // We'll (ab)use the history for our own purposes of tagging back in time.\n      // Keep a history of the length of the sync word to delay for tagging.\n      set_history(d_symbols.size()+1);\n\n      declare_sample_delay(1, 0);\n      declare_sample_delay(0, d_symbols.size());\n\n      // Setting the alignment multiple for volk causes problems with the\n      // expected behavior of setting the output multiple for the FFT filter.\n      // Don't set the alignment multiple.\n      //const int alignment_multiple =\n      //  volk_get_alignment() / sizeof(gr_complex);\n      //set_alignment(std::max(1,alignment_multiple));\n\n      d_scale = 1.0f;\n    }\n\n    corr_est_cc_impl::~corr_est_cc_impl()\n    {\n      delete d_filter;\n      volk_free(d_corr);\n      volk_free(d_corr_mag);\n    }\n\n    std::vector<gr_complex>\n    corr_est_cc_impl::symbols() const\n    {\n      return d_symbols;\n    }\n\n    void\n    corr_est_cc_impl::set_symbols(const std::vector<gr_complex> &symbols)\n    {\n      gr::thread::scoped_lock lock(d_setlock);\n\n      d_symbols = symbols;\n\n      // Per comments in gr-filter/include/gnuradio/filter/fft_filter.h,\n      // set the block output multiple to the FFT filter kernel's internal,\n      // assumed \"nsamples\", to ensure the scheduler always passes a\n      // proper number of samples.\n      int nsamples;\n      nsamples = d_filter->set_taps(d_symbols);\n      set_output_multiple(nsamples);\n\n      // It looks like the kernel::fft_filter_ccc stashes a tail between\n      // calls, so that contains our filtering history (I think).  The\n      // fft_filter_ccc block (which calls the kernel::fft_filter_ccc) sets\n      // the history to 1 (0 history items), so let's follow its lead.\n      //set_history(1);\n\n      // We'll (ab)use the history for our own purposes of tagging back in time.\n      // Keep a history of the length of the sync word to delay for tagging.\n      set_history(d_symbols.size()+1);\n\n      declare_sample_delay(1, 0);\n      declare_sample_delay(0, d_symbols.size());\n\n      _set_mark_delay(d_stashed_mark_delay);\n      _set_threshold(d_stashed_threshold);\n    }\n\n    unsigned int\n    corr_est_cc_impl::mark_delay() const\n    {\n      return d_mark_delay;\n    }\n\n    void\n    corr_est_cc_impl::_set_mark_delay(unsigned int mark_delay)\n    {\n      d_stashed_mark_delay = mark_delay;\n\n      if(mark_delay >= d_symbols.size()) {\n        d_mark_delay = d_symbols.size()-1;\n        GR_LOG_WARN(d_logger, boost::format(\"set_mark_delay: asked for %1% but due \"\n                                            \"to the symbol size constraints, \"\n                                            \"mark delay set to %2%.\") \\\n                    % mark_delay % d_mark_delay);\n      }\n      else {\n        d_mark_delay = mark_delay;\n      }\n    }\n\n    void\n    corr_est_cc_impl::set_mark_delay(unsigned int mark_delay)\n    {\n      gr::thread::scoped_lock lock(d_setlock);\n      _set_mark_delay(mark_delay);\n    }\n\n    float\n    corr_est_cc_impl::threshold() const\n    {\n      return d_thresh;\n    }\n\n    void\n    corr_est_cc_impl::_set_threshold(float threshold)\n    {\n      d_stashed_threshold = threshold;\n      d_pfa = -logf(1.0f-threshold);\n    }\n\n    void\n    corr_est_cc_impl::set_threshold(float threshold)\n    {\n      gr::thread::scoped_lock lock(d_setlock);\n      _set_threshold(threshold);\n    }\n\n    int\n    corr_est_cc_impl::work(int noutput_items,\n                           gr_vector_const_void_star &input_items,\n                           gr_vector_void_star &output_items)\n    {\n      gr::thread::scoped_lock lock(d_setlock);\n\n      const gr_complex *in = (gr_complex *)input_items[0];\n      gr_complex *out = (gr_complex*)output_items[0];\n      gr_complex *corr;\n      if (output_items.size() > 1)\n          corr = (gr_complex *) output_items[1];\n      else\n          corr = d_corr;\n\n      // Our correlation filter length\n      unsigned int hist_len = history() - 1;\n\n      // Calculate the correlation of the non-delayed input with the\n      // known symbols.\n      d_filter->filter(noutput_items, &in[hist_len], corr);\n\n      // Find the magnitude squared of the correlation\n      volk_32fc_magnitude_squared_32f(&d_corr_mag[0], corr, noutput_items);\n\n      float detection = 0;\n      for(int i = 0; i < noutput_items; i++) {\n        detection += d_corr_mag[i];\n      }\n      detection /= static_cast<float>(noutput_items);\n      detection *= d_pfa;\n\n      int isps = (int)(d_sps + 0.5f);\n      int i = 0;\n      while(i < noutput_items) {\n        // Look for the correlator output to cross the threshold.\n        // Sum power over two consecutive symbols in case we're offset\n        // in time. If off by 1/2 a symbol, the peak of any one point\n        // is much lower.\n        float corr_mag = d_corr_mag[i] + d_corr_mag[i+1];\n        if(corr_mag <= 4*detection) {\n          i++;\n          continue;\n        }\n\n        // Go to (just past) the current correlator output peak\n        while ((i < (noutput_items-1)) &&\n               (d_corr_mag[i] < d_corr_mag[i+1])) {\n          i++;\n        }\n        // Delaying the primary signal output by the matched filter\n        // length using history(), means that the the peak output of\n        // the matched filter aligns with the start of the desired\n        // sync word in the primary signal output.  This corr_start\n        // tag is not offset to another sample, so that downstream\n        // data-aided blocks (like adaptive equalizers) know exactly\n        // where the start of the correlated symbols are.\n        add_item_tag(0, nitems_written(0) + i, pmt::intern(\"corr_start\"),\n                     pmt::from_double(d_corr_mag[i]), d_src_id);\n\n#if 0\n        // Use Parabolic interpolation to estimate a fractional\n        // sample delay. There are more accurate methods as\n        // the sample delay estimate using this method is biased.\n        // But this method is simple and fast.\n        // center between [-0.5,0.5] units of samples\n        // Paper Reference: \"Discrete Time Techniques for Time Delay\n        // Estimation\" G. Jacovitti and G. Scarano\n        double center = 0.0;\n        if( i > 0 && i < (noutput_items - 1 )){\n          double nom = d_corr_mag[i-1]-d_corr_mag[i+1];\n          double denom = 2*(d_corr_mag[i-1]-2*d_corr_mag[i]+d_corr_mag[i+1]);\n          center = nom/denom;\n        }\n#else\n        // Calculates the center of mass between the three points around the peak.\n        // Estimate is linear.\n        double nom = 0, den = 0;\n        nom = d_corr_mag[i-1] + 2*d_corr_mag[i] + 3*d_corr_mag[i+1];\n        den = d_corr_mag[i-1] + d_corr_mag[i] + d_corr_mag[i+1];\n        double center = nom / den;\n        center = (center - 2.0); // adjust for bias in center of mass calculation\n#endif\n\n        // Estimated scaling factor for the input stream to normalize\n        // the output to +/-1.\n        uint32_t maxi;\n        volk_32fc_index_max_32u_manual(&maxi, (gr_complex*)in, noutput_items, \"generic\");\n        d_scale = 1 / std::abs(in[maxi]);\n\n        // Calculate the phase offset of the incoming signal.\n        //\n        // The analytic cross-correlation is:\n        //\n        // 2A*e_bb(t-t_d)*exp(-j*2*pi*f*(t-t_d) - j*phi_bb(t-t_d) - j*theta_c)\n        //\n\n        // The analytic auto-correlation's envelope, e_bb(), has its\n        // peak at the \"group delay\" time, t = t_d.  The analytic\n        // cross-correlation's center frequency phase shift, theta_c,\n        // is determined from the argument of the analytic\n        // cross-correlation at the \"group delay\" time, t = t_d.\n        //\n        // Taking the argument of the analytic cross-correlation at\n        // any other time will include the baseband auto-correlation's\n        // phase term, phi_bb(t-t_d), and a frequency dependent term\n        // of the cross-correlation, which I don't believe maps simply\n        // to expected symbol phase differences.\n        float phase = fast_atan2f(corr[i].imag(), corr[i].real());\n        int index = i + d_mark_delay;\n\n        add_item_tag(0, nitems_written(0) + index, pmt::intern(\"phase_est\"),\n                     pmt::from_double(phase), d_src_id);\n        add_item_tag(0, nitems_written(0) + index, pmt::intern(\"time_est\"),\n                     pmt::from_double(center), d_src_id);\n        // N.B. the appropriate d_corr_mag[] index is \"i\", not \"index\".\n        add_item_tag(0, nitems_written(0) + index, pmt::intern(\"corr_est\"),\n                     pmt::from_double(d_corr_mag[i]), d_src_id);\n        add_item_tag(0, nitems_written(0) + index, pmt::intern(\"amp_est\"),\n                     pmt::from_double(d_scale), d_src_id);\n\n        if (output_items.size() > 1) {\n          // N.B. these debug tags are not offset to avoid walking off out buf\n          add_item_tag(1, nitems_written(0) + i, pmt::intern(\"phase_est\"),\n                       pmt::from_double(phase), d_src_id);\n          add_item_tag(1, nitems_written(0) + i, pmt::intern(\"time_est\"),\n                       pmt::from_double(center), d_src_id);\n          add_item_tag(1, nitems_written(0) + i, pmt::intern(\"corr_est\"),\n                       pmt::from_double(d_corr_mag[i]), d_src_id);\n          add_item_tag(1, nitems_written(0) + i, pmt::intern(\"amp_est\"),\n                       pmt::from_double(d_scale), d_src_id);\n        }\n\n        // Skip ahead to the next potential symbol peak\n        // (for non-offset/interleaved symbols)\n        i += isps;\n      }\n\n      //if (output_items.size() > 1)\n      //  add_item_tag(1, nitems_written(0) + noutput_items - 1,\n      //               pmt::intern(\"ce_eow\"), pmt::from_uint64(noutput_items),\n      //               d_src_id);\n\n      // Delay the output by our correlation filter length so we can\n      // tag backwards in time\n      memcpy(out, &in[0], sizeof(gr_complex)*noutput_items);\n\n      return noutput_items;\n    }\n\n  } /* namespace digital */\n} /* namespace gr */\n", "meta": {"hexsha": "5157f8f6dee4d52a274e5d8649d65dd00a0dc7e7", "size": 13401, "ext": "cc", "lang": "C++", "max_stars_repo_path": "gnuradio-3.7.13.4/gr-digital/lib/corr_est_cc_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-digital/lib/corr_est_cc_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-digital/lib/corr_est_cc_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": 37.225, "max_line_length": 89, "alphanum_fraction": 0.6206253265, "num_tokens": 3300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.42632159254749025, "lm_q1q2_score": 0.2574691811441766}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\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#ifndef BOOST_GEOMETRY_PROJECTIONS_FACTORY_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_FACTORY_HPP\n\n#include <map>\n#include <string>\n\n#include <boost/shared_ptr.hpp>\n\n#include <boost/geometry/extensions/gis/projections/impl/factory_entry.hpp>\n#include <boost/geometry/extensions/gis/projections/parameters.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/aea.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/aeqd.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/airy.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/aitoff.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/august.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/bacon.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/bipc.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/boggs.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/bonne.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/cass.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/cc.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/cea.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/chamb.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/collg.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/crast.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/denoy.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/eck1.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/eck2.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/eck3.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/eck4.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/eck5.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/eqc.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/eqdc.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/etmerc.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/fahey.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/fouc_s.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/gall.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/geocent.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/geos.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/gins8.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/gn_sinu.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/gnom.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/goode.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/gstmerc.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/hammer.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/hatano.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/healpix.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/krovak.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/igh.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/imw_p.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/isea.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/laea.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/labrd.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/lagrng.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/larr.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/lask.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/latlong.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/lcc.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/lcca.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/loxim.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/lsat.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/mbtfpp.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/mbtfpq.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/mbt_fps.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/merc.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/mill.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/mod_ster.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/moll.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/natearth.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/nell.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/nell_h.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/nocol.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/nsper.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/nzmg.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/ob_tran.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/ocea.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/oea.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/omerc.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/ortho.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/qsc.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/poly.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/putp2.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/putp3.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/putp4p.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/putp5.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/putp6.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/robin.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/rouss.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/rpoly.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/sconics.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/somerc.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/stere.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/sterea.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/sts.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/tcc.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/tcea.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/tmerc.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/tpeqd.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/urm5.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/urmfps.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/vandg.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/vandg2.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/vandg4.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/wag2.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/wag3.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/wag7.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/wink1.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/wink2.hpp>\n\nnamespace boost { namespace geometry { namespace projections\n{\n\ntemplate <typename LatLong, typename Cartesian, typename Parameters = parameters>\nclass factory : public detail::base_factory<LatLong, Cartesian, Parameters>\n{\nprivate:\n\n    typedef std::map\n        <\n            std::string,\n            boost::shared_ptr\n                <\n                    detail::factory_entry\n                        <\n                            LatLong,\n                            Cartesian,\n                            Parameters\n                        >\n                >\n        > prj_registry;\n    prj_registry m_registry;\n\npublic:\n\n    factory()\n    {\n        detail::aea_init(*this);\n        detail::aeqd_init(*this);\n        detail::airy_init(*this);\n        detail::aitoff_init(*this);\n        detail::august_init(*this);\n        detail::bacon_init(*this);\n        detail::bipc_init(*this);\n        detail::boggs_init(*this);\n        detail::bonne_init(*this);\n        detail::cass_init(*this);\n        detail::cc_init(*this);\n        detail::cea_init(*this);\n        detail::chamb_init(*this);\n        detail::collg_init(*this);\n        detail::crast_init(*this);\n        detail::denoy_init(*this);\n        detail::eck1_init(*this);\n        detail::eck2_init(*this);\n        detail::eck3_init(*this);\n        detail::eck4_init(*this);\n        detail::eck5_init(*this);\n        detail::eqc_init(*this);\n        detail::eqdc_init(*this);\n        detail::etmerc_init(*this);\n        detail::fahey_init(*this);\n        detail::fouc_s_init(*this);\n        detail::gall_init(*this);\n        detail::geocent_init(*this);\n        detail::geos_init(*this);\n        detail::gins8_init(*this);\n        detail::gn_sinu_init(*this);\n        detail::gnom_init(*this);\n        detail::goode_init(*this);\n        detail::gstmerc_init(*this);\n        detail::hammer_init(*this);\n        detail::hatano_init(*this);\n        detail::healpix_init(*this);\n        detail::krovak_init(*this);\n        detail::igh_init(*this);\n        detail::imw_p_init(*this);\n        detail::isea_init(*this);\n        detail::labrd_init(*this);\n        detail::laea_init(*this);\n        detail::lagrng_init(*this);\n        detail::larr_init(*this);\n        detail::lask_init(*this);\n        detail::latlong_init(*this);\n        detail::lcc_init(*this);\n        detail::lcca_init(*this);\n        detail::loxim_init(*this);\n        detail::lsat_init(*this);\n        detail::mbtfpp_init(*this);\n        detail::mbtfpq_init(*this);\n        detail::mbt_fps_init(*this);\n        detail::merc_init(*this);\n        detail::mill_init(*this);\n        detail::mod_ster_init(*this);\n        detail::moll_init(*this);\n        detail::natearth_init(*this);\n        detail::nell_init(*this);\n        detail::nell_h_init(*this);\n        detail::nocol_init(*this);\n        detail::nsper_init(*this);\n        detail::nzmg_init(*this);\n        detail::ob_tran_init(*this);\n        detail::ocea_init(*this);\n        detail::oea_init(*this);\n        detail::omerc_init(*this);\n        detail::ortho_init(*this);\n        detail::qsc_init(*this);\n        detail::poly_init(*this);\n        detail::putp2_init(*this);\n        detail::putp3_init(*this);\n        detail::putp4p_init(*this);\n        detail::putp5_init(*this);\n        detail::putp6_init(*this);\n        detail::robin_init(*this);\n        detail::rouss_init(*this);\n        detail::rpoly_init(*this);\n        detail::sconics_init(*this);\n        detail::somerc_init(*this);\n        detail::stere_init(*this);\n        detail::sterea_init(*this);\n        detail::sts_init(*this);\n        detail::tcc_init(*this);\n        detail::tcea_init(*this);\n        detail::tmerc_init(*this);\n        detail::tpeqd_init(*this);\n        detail::urm5_init(*this);\n        detail::urmfps_init(*this);\n        detail::vandg_init(*this);\n        detail::vandg2_init(*this);\n        detail::vandg4_init(*this);\n        detail::wag2_init(*this);\n        detail::wag3_init(*this);\n        detail::wag7_init(*this);\n        detail::wink1_init(*this);\n        detail::wink2_init(*this);\n    }\n\n    virtual ~factory() {}\n\n    virtual void add_to_factory(std::string const& name,\n                    detail::factory_entry<LatLong, Cartesian, Parameters>* sub)\n    {\n        m_registry[name].reset(sub);\n    }\n\n    inline projection<LatLong, Cartesian>* create_new(Parameters const& parameters)\n    {\n        typename prj_registry::iterator it = m_registry.find(parameters.name);\n        if (it != m_registry.end())\n        {\n            return it->second->create_new(parameters);\n        }\n\n        return 0;\n    }\n};\n\n}}} // namespace boost::geometry::projections\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_FACTORY_HPP\n", "meta": {"hexsha": "6f5ff26bd0d50cb90641b58868ed3dd0f1fe1b70", "size": 11964, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/factory.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/factory.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/factory.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.6417910448, "max_line_length": 83, "alphanum_fraction": 0.7204948178, "num_tokens": 2933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710085, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.25746013542237667}}
{"text": "#include <string>\n#include <vector>\n#include <sstream>\n#include <iostream>\n#include <random>\n#include <boost/ref.hpp>\n#include <boost/python.hpp>\n#include <boost/python/numpy.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/adapted/c_array.hpp>\n#include <glog/logging.h>\n#include <hdf5_hl.h>\n#include \"streamer/streamer.h\"\nnamespace py = boost::python;\nnamespace np = boost::python::numpy;\n\nnamespace {\n    using std::istringstream;\n    using std::ostringstream;\n    using std::string;\n    using std::runtime_error;\n    using std::cerr;\n    using std::endl;\n    using std::vector;\n\n    typedef boost::geometry::model::d2::point_xy<float> point_xy;\n    typedef boost::geometry::model::polygon<point_xy> Polygon;\n\n    static int PARAMS = 8;\n    int random_seed = 2019;\n    static float constexpr PIx2 = M_PI * 2;\n\n    // sanity check np::ndarray to make sure they are dense and continuous\n    template <typename T=float>\n    void check_dense (np::ndarray array, int nd = 0) {\n        CHECK(array.get_dtype() == np::dtype::get_builtin<T>());\n        if (nd > 0) CHECK(array.get_nd() == nd);\n        else nd = array.get_nd();\n        int stride = sizeof(T);\n        for (int i = 0, off=nd-1; i < nd; ++i, --off) {\n            CHECK(array.strides(off) == stride);\n            stride *= array.shape(off);\n        }\n    }\n\n    // allocate an ndarray of given shape, return the pointer to firt element\n    template <typename T=float>\n    T *alloc_ndarray (py::tuple shape, np::ndarray **ptr) {\n        np::ndarray *array = new np::ndarray(np::zeros(shape, np::dtype::get_builtin<T>()));\n        check_dense<T>(*array);\n        *ptr = array;\n        return reinterpret_cast<T *>(array->get_data());\n    }\n\n    // Lidar point, xyz and reflectance\n    struct __attribute__((__packed__)) Point {\n        static int constexpr DIM = 4;\n        union {\n            float data[4];\n            struct {\n                float x, y, z, r;\n            };\n        };\n    };\n\n    struct __attribute__((__packed__)) Prior {\n        static int constexpr DIM = 5;\n        union {\n            float data[5];\n            struct {\n                float l, w, h, z, qt; // length is along x, width is along y\n            };\n        };\n\n        float t () const {\n            return qt * M_PI / 2;\n        }\n        // qt = 0 1 2 -1\n    };\n\n    static float intersect (float min1, float max1, float min2, float max2) {\n        // intersection length of range [min1, max1] and [min2, max2]\n        float a = std::max(min1, min2);\n        float b = std::min(max1, max2);\n        if (a <= b) return b-a;\n        return 0;\n    }\n\n    float norm_angle (float d) {\n        if (d >= PIx2) d -= PIx2;\n        else if (d <= -PIx2) d += PIx2;\n        float ad = d >= 0 ? (d - PIx2) : (d + PIx2);\n        if (abs(ad) < abs(d)) return ad;\n        return d;\n    }\n\n    // 3D rotated box\n    struct __attribute__((__packed__)) Box {\n        static int constexpr DIM = 8;\n        union {\n            float data[8];\n            struct {\n                float x, y, z, h, w, l, t, s;\n            };\n        };\n    public:\n        bool sanity_check (Prior const &p, float ax, float ay) const {\n            do {\n                if (h <= 0) break;\n                if (w <= 0) break;\n                if (l <= 0) break;\n                if (h > 2) break;\n                if (w > 2) break;\n                if (l > 5) break;\n                float d = sqrt(w * w + l * l);\n                float dist = sqrt((x-ax)*(x-ax) + (y-ay)*(y-ay));\n                if (d < dist) break;\n                return true;\n            } while (false);\n            std::cerr << \"BAD \" << ax << ' ' << ay << ' ' << h << ' ' << w << ' ' << l << std::endl;\n            return false;\n        }\n\n        void from_prior (Prior const &p, float ax, float ay) {\n            x = ax;\n            y = ay;\n            z = p.z;\n            h = p.h;\n            w = p.w;\n            l = p.l;\n            t = p.t();\n            s = 0;\n        }\n\n        void augment (float sc, float dx, float dy, float dz, float dt, float s, float c) {\n            // s: sin(dt)\n            // c: cos(dt)\n            float tx = x * sc + dx;\n            float ty = y * sc + dy;\n            x = c * tx - s * ty;\n            y = s * tx + c * ty;\n            z = z * sc + dz;\n            h *= sc;\n            w *= sc;\n            l *= sc;\n            t += dt;\n        }\n\n        void load (float const *params) {\n            std::copy(params, params + DIM, data);\n        }\n\n        void store (float *params) {\n            std::copy(data, data + DIM, params);\n        }\n\n        py::tuple make_tuple () const {\n            return py::make_tuple(x, y, z, h, w, l, t, s);\n        }\n\n        void from_tuple (py::tuple box) {\n            x = py::extract<float>(box[0]);\n            y = py::extract<float>(box[1]);\n            z = py::extract<float>(box[2]);\n            h = py::extract<float>(box[3]);\n            w = py::extract<float>(box[4]);\n            l = py::extract<float>(box[5]);\n            t = py::extract<float>(box[6]);\n            s = py::extract<float>(box[7]);\n        }\n\n        void to_residual (float ax, float ay, Prior const &prior, float *params) const {\n            // residual is the regression target\n            float d = sqrt(prior.l * prior.l + prior.w * prior.w);\n\n            params[0] = (x - ax);\n            params[1] = (y - ay);\n            CHECK(abs(params[1]) < 8);\n            params[2] = (z - prior.z) / prior.z;\n            params[3] = (h - prior.h) / prior.h;\n            params[4] = (w - prior.w) / prior.w;\n            params[5] = (l - prior.l) / prior.l;\n            params[6] = norm_angle(t - prior.t()) / M_PI;\n            params[7] = 0;\n        }\n\n        void from_residual (float ax, float ay, Prior const &prior, float const *params) {\n            float d = sqrt(prior.l * prior.l + prior.w * prior.w);\n            CHECK(d < 10);\n\n            x = params[0] + ax;\n            y = params[1] + ay;\n            z = params[2] * prior.z + prior.z;\n            h = params[3] * prior.h + prior.h;\n            w = params[4] * prior.w + prior.w;\n            l = params[5] * prior.l + prior.l;\n            t = params[6] * M_PI + prior.t();\n        }\n\n#if 0\n        float score_anchor (float ax, float ay, Prior const &prior) const {\n            // approximate\n            float a = l * l + w * w;\n            float d = sqrt(a)/2;\n            float a2 = prior.l * prior.l + prior.w * prior.w;\n            float d2 = sqrt(a2)/2;\n            float i = intersect(x-d, x+d, ax-d2, ax+d2)   // intersection area\n                     * intersect(y-d, y+d, ay-d2, ay+d2);\n            return i / (a + a2 - i + 0.00001);\n        }\n#endif\n\n\t\tvoid polygon (Polygon *poly) const {\n\t\t\tnamespace bl = boost::numeric::ublas;\n\t\t\tusing namespace boost::geometry;\n\t\t\tbl::matrix<float> mref(2, 2);\n            // we are using -t to calculate the matrix\n            // this is determined by visualization\n\t\t\tmref(0, 0) = cos(t); mref(0, 1) = -sin(t);\n\t\t\tmref(1, 0) = sin(t); mref(1, 1) = cos(t);\n\n\t\t\tbl::matrix<float> corners(2, 4);\n\t\t\tfloat data[] = {w / 2, w / 2, -w / 2, -w / 2,\n\t\t\t\t\t\t\tl / 2, -l / 2, -l / 2, l / 2};\n\t\t\tstd::copy(data, data + 8, corners.data().begin());\n\t\t\tbl::matrix<float> gc = prod(mref, corners);\n\t\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\t\tgc(0, i) += x;\n\t\t\t\tgc(1, i) += y;\n\t\t\t}\n\n\t\t\tfloat points[][2] = {{gc(0, 0), gc(1, 0)},{gc(0, 1), gc(1, 1)},{gc(0, 2), gc(1, 2)},{gc(0, 3), gc(1, 3)},{gc(0, 0), gc(1, 0)}};\n\t\t\tboost::geometry::append(*poly, points);\n\t\t}\n    };\n\n#if 0\n    float iou (Box const &a, Box const &b) {\n        // approximate\n        float aa = a.x * a.x + a.y * a.y;\n        float ab = b.x * b.x + b.y * b.y;   // area\n        float ra = sqrt(aa)/2;\n        float rb = sqrt(ab)/2;\n        float i = intersect(a.x-ra, a.x+ra, b.x-rb, b.x+rb)\n                * intersect(a.y-ra, a.y+ra, b.y-rb, b.y+rb);\n        return i / (aa + ab - i + 0.00001);\n    }\n#endif\n\n    float iou (Polygon const &p1, Polygon const &p2) {\n        vector<Polygon> in, un;\n        boost::geometry::intersection(p1, p2, in);\n        boost::geometry::union_(p1, p2, un);\n        float inter_area = in.empty() ? 0 : boost::geometry::area(in.front());\n        float union_area = boost::geometry::area(un.front());\n        return inter_area / union_area;\n    }\n\n    // Give unmanaged memory an array-like accessment interface.\n    template <typename T>\n    class View {\n        T *data;\n        size_t sz;\n    public:\n        View (void *p, size_t s): data(reinterpret_cast<T *>(p)), sz(s) {\n        }\n\n        View (np::ndarray array) {\n\t\t\tcheck_dense<float>(array, 2);\n\t\t\tCHECK(array.shape(1) * sizeof(float) == sizeof(T));\n\t\t\tdata = reinterpret_cast<T *>(array.get_data());\n\t\t\tsz = array.shape(0);\n        }\n\n        View (vector<T> &v) {\n            data = &v[0];\n            sz = v.size();\n        }\n\n        T &operator [] (size_t i) {\n            return data[i];\n        }\n\n        T const &operator [] (size_t i) const {\n            return data[i];\n        }\n        size_t size () const { return sz; }\n\n        bool empty () const { return sz == 0; }\n\n        T const *begin () const { return data; }\n        T const *end () const { return data + sz; }\n        T *begin () { return data; }\n        T *end () { return data + sz; }\n    };\n\n    class H5File {\n        hid_t hid;\n    public:\n        H5File (string const &path) {\n            hid = H5Fopen(path.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);\n            CHECK(hid >= 0);\n        }\n\n        template <typename T>\n        void load (char const *name, vector<T> *buffer) {\n            herr_t e = H5LTfind_dataset(hid, name);\n            int rank;\n            e = H5LTget_dataset_ndims(hid, name, &rank);\n            CHECK(e >= 0);\n            CHECK(rank == 2);\n            vector<hsize_t> dims(rank);\n            H5T_class_t class_id;\n            size_t type_size;\n            e = H5LTget_dataset_info(hid, name, &dims[0], &class_id, &type_size);\n            CHECK(class_id == H5T_FLOAT);\n            CHECK(type_size == sizeof(float));\n            CHECK(dims[1] * sizeof(float) == sizeof(T));\n            buffer->resize(dims[0]);\n            if (buffer->size() > 0) {\n                e = H5LTread_dataset_float(hid, name, buffer->at(0).data);\n            }\n            CHECK(e >= 0);\n        }\n\n        ~H5File () {\n            herr_t e = H5Fclose(hid);\n            CHECK(e >= 0);\n        }\n    };\n\n    class Voxelizer {\n        float x_min, x_max, x_factor;\n        float y_min, y_max, y_factor;\n        float z_min, z_max, z_factor;\n        int nx, ny, nz;\n    protected:\n        std::default_random_engine rng;\n    public:\n        Voxelizer (np::ndarray ranges, np::ndarray shape): rng(random_seed) {\n            // ranges is a 3 * 2 arrange\n            {\n                check_dense<float>(ranges, 2);\n                CHECK(ranges.shape(0) == 3);\n                CHECK(ranges.shape(1) == 2);\n                float const *ptr = (float const *)ranges.get_data();\n                x_min = *ptr++; x_max = *ptr++;\n                y_min = *ptr++; y_max = *ptr++;\n                z_min = *ptr++; z_max = *ptr++;\n            }\n            {\n                check_dense<int>(shape, 1);\n                CHECK(shape.shape(0) == 3);\n                int32_t const *ptr = (int32_t const *)shape.get_data();\n                nx = *ptr++; ny = *ptr++; nz = *ptr++;\n            }\n\n            float x_range = x_max - x_min;\n            float y_range = y_max - y_min;\n            float z_range = z_max - z_min;\n\n            // quantization method\n            // [min, max], range   -->   [0, n-1]\n            // q(x) = round(((x - min)/range) * (n-1))\n            //      = round((x - min) * factor)\n            x_factor = (nx - 1) / x_range;\n            y_factor = (ny - 1) / y_range;\n            z_factor = (nz - 1) / z_range;\n        }\n\n        void augment_helper (vector<View<Point>> &points_batch, vector<View<Box>> &boxes_batch, int seed) {\n            // TODO: per-box rotation\n            CHECK(points_batch.size() == boxes_batch.size());\n            std::default_random_engine rng1(seed);\n            std::uniform_real_distribution<float> shiftxy(-0.5, 0.5);\n            std::uniform_real_distribution<float> shiftz(-0.2, 0.2);\n            std::uniform_real_distribution<float> shift2(-0.05, 0.05);\n            std::uniform_real_distribution<float> scale(0.95, 1.05);\n            std::uniform_real_distribution<float> rotate(-M_PI/4, M_PI/4);\n            //vector<float> r;\n            for (unsigned i = 0; i < points_batch.size(); ++i) {\n                float sc = scale(rng);\n                float dx = shiftxy(rng), dy = shiftxy(rng), dz = shiftz(rng);\n                float dt = rotate(rng);\n\n                View<Point> &points = points_batch[i];\n                View<Box> &boxes = boxes_batch[i];\n                //r.resize(points.size());\n                float s = sin(dt), c = cos(dt);\n\n                for (unsigned j = 0; j < points.size(); ++j) {\n                    Point &point = points[j];\n                    float x = point.x * sc + dx + shift2(rng);\n                    float y = point.y * sc + dy + shift2(rng);\n                    point.x = c * x - s * y;\n                    point.y = s * x + c * y;\n                    point.z = point.z * sc + dz + shift2(rng);\n                }\n\n                for (Box &box: boxes) {\n                    box.augment(sc, dx, dy, dz, dt, s, c);\n                }\n            }\n        }\n\n        void augment (py::list points_batch, py::list boxes_batch) {\n            int batch = py::len(boxes_batch);\n            CHECK(batch == py::len(points_batch));\n            vector<View<Point>> points_views;\n            vector<View<Box>> boxes_views;\n            for (int i = 0; i < batch; ++i) {\n                np::ndarray points = py::extract<np::ndarray>(points_batch[i]);\n                check_dense<float>(points, 2);\n                CHECK(points.shape(1) == 4);\n                points_views.emplace_back(points);\n\n                // foreach batch\n                np::ndarray boxes = py::extract<np::ndarray>(boxes_batch[i]);\n                check_dense<float>(boxes, 2);\n                CHECK(boxes.shape(1) == 8);\n                boxes_views.emplace_back(boxes);\n            }\n            augment_helper(points_views, boxes_views, rng());\n        }\n\n        static int quantize (float v, float min, float factor) {\n            return int(round((v-min)*factor));\n        }\n\n        // group point by voxels in the grid nx * ny * nz\n        // This is the helper function that do the real work.\n        void voxelize_points_helper (vector<View<Point>> const &points_batch, int T, bool lock,\n                // the return arrays, P for points, M for masks and I for voxel indexes\n                np::ndarray **V, np::ndarray **M, np::ndarray **I) {\n            // Input:\n            //  points_batch:    a batch of point clouds; each as View<Point>.\n            //  T:      maximal points in each voxel\n            //  lock:   when allocating ndarray, should python thread be locked\n            // Output:\n            //  *V:     pointer to voxel array,  N * T * C\n            //          N non-empty voxels, each voxel has T points, each point has C channels\n            //  *M:     pointer to voxel mask,   N * T\n            //          For each non empty voxel, T 0/1 values.  1 for those with valid points.\n            //  *I:     flatten voxel index,     N\n            //          We use this index to put the voxels back into a dense 3D grid\n\n            int batch = points_batch.size();\n            int Cin = 4;\n            int C = Cin + 3;\n            int nv = nx * ny * nz;\n\n            vector<vector<Point const *>> voxels(batch * nv);\n            for (int i = 0; i < batch; ++i) {\n                // foreach batch\n                auto const &points = points_batch[i];\n\n                // we need to drop points from over-crowded voxels in randomm\n                // and we do this by shuffling the points before adding them to voxels\n                vector<unsigned> index(points.size());\n                for (unsigned j = 0; j < index.size(); ++j) index[j] = j;\n                std::random_shuffle(index.begin(), index.end());\n\n                for (unsigned j: index) {\n                    Point const &point = points[j];\n\n                    // TODO:\n                    //      some points may be around the voxel boundary\n                    //      we might want to added in those close to boundary as well\n                    int ix = quantize(point.x, x_min, x_factor);\n                    if (ix < 0 || ix >= nx) continue;\n                    int iy = quantize(point.y, y_min, y_factor);\n                    if (iy < 0 || iy >= ny) continue;\n                    int iz = quantize(point.z, z_min, z_factor);\n                    if (iz < 0 || iz >= nz) continue;\n\n                    int cell = i * nv + (ix * ny + iy) * nz + iz;\n                    auto &voxel = voxels[cell];\n                    if (int(voxel.size()) < T) {\n                        voxel.push_back(&point);\n                    }\n                }\n            }\n\n            int N = 0; // non-empty entries\n            for (auto const &v: voxels) if (v.size() > 0) ++N;\n\n            float *V_buf, *M_buf;\n            int32_t *I_buf;\n\n            {   // allocate ndarrays for return values\n                streamer::ScopedGState _(lock);\n                V_buf = alloc_ndarray<>(py::make_tuple(N, T, C), V);\n                M_buf = alloc_ndarray<>(py::make_tuple(N, T, 1), M);\n                I_buf = alloc_ndarray<int32_t>(py::make_tuple(N, 1), I);\n            }\n            // fill points into voxels\n            for (unsigned j = 0; j < voxels.size(); ++j) {\n                auto const &voxel = voxels[j];\n                if (voxel.empty()) continue;\n                *I_buf++ = j;\n\n                float *p = V_buf, *m = M_buf;\n                V_buf += T * C; M_buf += T;\n\n                float cx = 0, cy = 0, cz = 0;   // centroid of points in voxel\n                for (Point const *point: voxel) {\n                    cx += point->x;\n                    cy += point->y;\n                    cz += point->z;\n                }\n                cx /= voxel.size();     // we only handle non-empty voxels here\n                cy /= voxel.size();     // so we can directly divide\n                cz /= voxel.size();\n                for (Point const *point: voxel) {\n                    *p++ = point->x;    *p++ = point->y;    *p++ = point->z;\n                    *p++ = point->r;\n                    *p++ = point->x-cx;   *p++ = point->y-cy;   *p++ = point->z-cz;\n                    *m++ = 1.0;\n                }\n            }\n        }\n\n        // group point by voxels\n        py::tuple voxelize_points (py::list points_batch, int T) {\n            int batch = py::len(points_batch);\n            CHECK(batch > 0);\n            vector<View<Point>> views;\n            for (int i = 0; i < batch; ++i) {\n                np::ndarray points = py::extract<np::ndarray>(points_batch[i]);\n                check_dense<float>(points, 2);\n                CHECK(points.shape(1) == 4);\n                views.emplace_back(points);\n            }\n            np::ndarray *V, *M, *I;\n            voxelize_points_helper(views, T, false, &V, &M, &I);\n            py::tuple tuple = py::make_tuple(*V, *M, *I);\n            delete V; delete M; delete I;\n            return tuple;\n        }\n\n        // Generate one batch of label arrays\n        // This is the helper function that do the real work.\n        void voxelize_labels_helper (vector<View<Box>> const &boxes_batch, View<Prior> priors,\n                int downsize, float lower_th, float upper_th, bool lock,\n                np::ndarray **A, np::ndarray **AW, np::ndarray **P, np::ndarray **PW) {\n\n            int batch = boxes_batch.size();\n\n            CHECK(nz % downsize == 0);\n            CHECK(ny % downsize == 0);\n            CHECK(nx % downsize == 0);\n            int lx = nx / downsize;\n            int ly = ny / downsize;\n\n            // anchors and masks\n            float *pa, *paw, *pp, *ppw;\n            {   // allocate returned ndarrays\n                streamer::ScopedGState _(lock);\n                pa = alloc_ndarray<>(py::make_tuple(batch, lx, ly, priors.size()), A);\n                paw = alloc_ndarray<>(py::make_tuple(batch, lx, ly, priors.size()), AW);\n                **AW += 1.0;\n                pp = alloc_ndarray(py::make_tuple(batch, lx, ly, priors.size() * PARAMS), P);\n                ppw = alloc_ndarray(py::make_tuple(batch, lx, ly, priors.size()), PW);\n            }\n\n            int count = 0;\n            for (auto const &boxes: boxes_batch) {\n                vector<Polygon> box_polygons(boxes.size());\n                for (unsigned i = 0; i < boxes.size(); ++i) {\n                    boxes[i].polygon(&box_polygons[i]);\n                }\n                for (int x = 0; x < lx; ++x) { for (int y = 0; y < ly; ++y) {\n                    float ax(x*downsize/x_factor+x_min), ay(y*downsize/y_factor+y_min);\n                    for (auto const &prior: priors) {\n                        Box prior_box;\n                        Polygon prior_polygon;\n                        prior_box.from_prior(prior, ax, ay);\n                        prior_box.polygon(&prior_polygon);\n                        Box const *best_box = nullptr;\n                        float best_d = 0;\n                        for (unsigned j = 0; j < boxes.size(); ++j) {\n                            float d = iou(prior_polygon, box_polygons[j]);\n                            float dt = abs(norm_angle(boxes[j].t - prior.t()));\n                            if (dt > 3 * M_PI/8) d = 0;\n                            if (d > best_d) {   // find best circle\n                                best_d = d;\n                                best_box = &boxes[j];\n                            }\n                        }\n                        if (best_box && best_d >= lower_th) {\n                            best_box->to_residual(ax, ay, prior, pp);\n                            ppw[0] = 1.0; //best_c->weight;\n                            ++count;\n                            if (best_d < upper_th) {\n                                paw[0] = 0;\n                            }\n                            else {\n                                pa[0] = 1;      // to class label\n                            }\n                        }\n                        pa += 1, paw +=1, pp += PARAMS, ppw += 1;\n                }}} // prior, y, x\n            } // batch\n        }\n\n        py::tuple voxelize_labels (py::list boxes_batch, np::ndarray priors, int downsize, float lower_th, float upper_th) {\n            vector<View<Box>> views;\n            int batch = py::len(boxes_batch);\n            CHECK(batch > 0);\n            for (int i = 0; i < batch; ++i) {\n                // foreach batch\n                np::ndarray boxes = py::extract<np::ndarray>(boxes_batch[i]);\n                check_dense<float>(boxes, 2);\n                CHECK(boxes.shape(1) == 8);\n                views.emplace_back(boxes);\n            }\n            View<Prior> priors_view(priors);\n            np::ndarray *A, *AW, *P, *PW;\n            voxelize_labels_helper(views, priors_view, downsize, lower_th, upper_th, false, &A, &AW, &P, &PW);\n            py::tuple tuple = make_tuple(*A, *AW, *P, *PW);\n            delete A; delete AW; delete P; delete PW;\n            return tuple;\n        }\n\n        py::list generate_boxes (np::ndarray probs, np::ndarray params, np::ndarray priors, float anchor_th) {\n            check_dense<float>(probs, 4);\n            check_dense<float>(params, 4);\n            check_dense<float>(priors, 2);\n            int batch = probs.shape(0);\n            int lx = probs.shape(1);\n            int ly = probs.shape(2);\n            CHECK(nx % lx == 0);\n            CHECK(ny % ly == 0);\n            int downsize = nx / lx;\n            CHECK(ny / ly == downsize);\n            CHECK(params.shape(1) == lx);\n            CHECK(params.shape(2) == ly);\n            CHECK(params.shape(3) % probs.shape(3) == 0);\n            CHECK(probs.shape(3) == priors.shape(0));\n            CHECK(params.shape(3) / probs.shape(3) == PARAMS);\n\n            View<Prior> priors_view(priors);\n\n            py::list list;\n            float *pa = (float *)(probs.get_data());\n            float *pp = (float *)(params.get_data());\n            for (int i = 0; i < batch; ++i) {\n                py::list boxes;\n                for (int x = 0; x < lx; ++x) { for (int y = 0; y < ly; ++y) {\n                    float ax(x*downsize/x_factor+x_min);    // anchor location\n                    float ay(y*downsize/y_factor+y_min);\n                    // check all the priors\n                    for (auto const &prior: priors_view) {\n                        float prob = pa[0];\n                        if (prob >= anchor_th) {\n                            Box box;\n                            box.from_residual(ax, ay, prior, pp);\n                            box.s = prob;\n                            if (box.sanity_check(prior, ax, ay)) {\n                                boxes.append(box.make_tuple());\n                            }\n                        }\n                        pa += 1, pp += PARAMS;\n                    } // prior\n                }} // x, y\n                list.append(boxes);\n            } // batch\n            return list;\n        }\n\n        py::list box2polygon (py::tuple b) {\n            Box box;\n            box.from_tuple(b);\n            Polygon poly;\n            box.polygon(&poly);\n            py::list list;\n            for (auto const &p: poly.outer()) {\n                float x = (p.x() - x_min) * x_factor;\n                float y = (p.y() - y_min) * y_factor;\n                list.append(py::make_tuple(x, y));\n            }\n            return list;\n        }\n    };\n\n    py::list nms (py::list inputs, float nms_th) {\n        py::list outputs;\n        for (int i = 0; i < len(inputs); ++i) {\n            vector<Box> boxes;\n            {\n                py::list list = py::extract<py::list>(inputs[i]);\n                for (int j = 0; j < len(list); ++j) {\n                    Box box;\n                    box.from_tuple(py::extract<py::tuple>(list[j]));\n                    boxes.push_back(box);\n                }\n            }\n            std::sort(boxes.begin(), boxes.end(), [](Box const &a, Box const &b) { return a.s > b.s; });\n\n            vector<Box> keep;\n            vector<Polygon> polygons;\n            for (auto const &box: boxes) {\n                Polygon polygon;\n                box.polygon(&polygon);\n                bool good = true;\n                for (auto const &polygon2: polygons) {\n\n                    if (iou(polygon, polygon2) >= nms_th) {\n                        good = false;\n                        break;\n                    }\n                }\n                if (good) {\n                    keep.push_back(box);\n                    polygons.push_back(polygon);\n                }\n            }\n\n            {\n                py::list list;\n                for (auto const &box: keep) {\n                    list.append(box.make_tuple());\n                }\n                outputs.append(list);\n            }\n        } \n        return outputs;\n    }\n\n    struct Task {\n        py::object *inputs;\n        vector<string> paths;\n        int seed;\n    };\n\n    class Streamer: public streamer::Streamer<Task>, Voxelizer {\n\n        View<Prior> priors;\n        int downsize, T;\n        float lower_th, upper_th;\n\n        Task *stage1 (py::object *obj) {\n            Task *task = new Task;\n            task->seed = rng();\n            task->inputs = obj;\n            {\n                streamer::ScopedGState _;\n                int len = py::len(*obj);\n                for (int i = 0; i < len; ++i) {\n                    task->paths.push_back(py::extract<string>((*obj)[i]));\n                }\n            }\n            return task;\n        }\n\n        py::object *stage2 (Task *task) {\n            // load from H5\n            vector<vector<Point>> points;\n            vector<vector<Box>> boxes;\n            vector<View<Point>> points_views;\n            vector<View<Box>> boxes_views;\n            // load data from H5 files\n            for (string const &path: task->paths) {\n                H5File file(path);\n                points.emplace_back();\n                boxes.emplace_back();\n                file.load(\"points\", &points.back());\n                file.load(\"boxes\", &boxes.back());\n                points_views.emplace_back(points.back());\n                boxes_views.emplace_back(boxes.back());\n            }\n            augment_helper(points_views, boxes_views, task->seed);\n            /*\n                if (boxes_views.back().size()) {\n                float min_z = boxes_views.back()[0].z;\n                float max_z = min_z;\n                for (Box const &b: boxes_views.back()) {\n                    min_z = std::min(min_z, b.z);\n                    max_z = std::max(max_z, b.z);\n                }\n                std::cerr << \"MINMAX \" << min_z << \" \" << max_z << std::endl;\n                }\n            */\n\n            np::ndarray *V, *M, *I;\n            np::ndarray *A, *AW, *P, *PW;\n            // voxelelize\n            voxelize_points_helper(points_views, T, true, &V, &M, &I);\n            voxelize_labels_helper(boxes_views, priors, downsize, lower_th, upper_th, true, &A, &AW, &P, &PW);\n            py::object *tuple;\n            {\n                streamer::ScopedGState _;\n                tuple = new py::tuple(py::make_tuple(*task->inputs, *V, *M, *I, *A, *AW, *P, *PW));\n                delete task->inputs;\n                delete V; delete M; delete I; delete A; delete AW; delete P; delete PW;\n            }\n            delete task;\n            return tuple;\n        }\n    public:\n        Streamer (py::object gen,  np::ndarray ranges, np::ndarray shape, np::ndarray priors_, int downsize_, int T_, float lower_th_, float upper_th_, int seed)\n            : streamer::Streamer<Task>(gen, 6),\n            Voxelizer(ranges, shape),\n            priors(priors_),\n            downsize(downsize_),\n            T(T_),\n            lower_th(lower_th_),\n            upper_th(upper_th_)\n        {\n            if (seed > 0) {\n                rng = std::default_random_engine(seed);\n            }\n        }\n    };\n}\n\nBOOST_PYTHON_MODULE(cpp)\n{\n    np::initialize();\n    py::class_<Voxelizer, boost::noncopyable>(\"Voxelizer\", py::init<np::ndarray, np::ndarray>())\n        .def(\"voxelize_points\", &Voxelizer::voxelize_points)\n        .def(\"voxelize_labels\", &Voxelizer::voxelize_labels)\n        .def(\"generate_boxes\", &Voxelizer::generate_boxes)\n        .def(\"box2polygon\", &Voxelizer::box2polygon)\n        .def(\"augment\", &Voxelizer::augment)\n    ;\n\n    py::class_<Streamer, boost::noncopyable>(\"Streamer\",\n                py::init<py::object, np::ndarray, np::ndarray, np::ndarray, int, int, float, float, int>())\n        .def(\"next\", &Streamer::next)\n    ;\n\n    def(\"nms\", ::nms);\n}\n\n", "meta": {"hexsha": "a27abccf270ce105aaf33e629d24e487a894ead5", "size": 31136, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "python-api.cpp", "max_stars_repo_name": "aaalgo/kitti_dl", "max_stars_repo_head_hexsha": "4ae15495b40d1f06acb50f365f19702c22a6c493", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-17T04:59:11.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-17T04:59:11.000Z", "max_issues_repo_path": "python-api.cpp", "max_issues_repo_name": "aaalgo/kitti_dl", "max_issues_repo_head_hexsha": "4ae15495b40d1f06acb50f365f19702c22a6c493", "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": "python-api.cpp", "max_forks_repo_name": "aaalgo/kitti_dl", "max_forks_repo_head_hexsha": "4ae15495b40d1f06acb50f365f19702c22a6c493", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-11-29T21:33:20.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-10T19:03:46.000Z", "avg_line_length": 37.0666666667, "max_line_length": 161, "alphanum_fraction": 0.4584725077, "num_tokens": 7925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.25746013034107273}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_GEOMETRY_POLICIES_RELATE_INTERSECTION_POINTS_HPP\n#define BOOST_GEOMETRY_GEOMETRY_POLICIES_RELATE_INTERSECTION_POINTS_HPP\n\n\n#include <algorithm>\n#include <string>\n\n#include <boost/concept_check.hpp>\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <boost/geometry/algorithms/detail/assign_indexed_point.hpp>\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/assert.hpp>\n#include <boost/geometry/strategies/side_info.hpp>\n#include <boost/geometry/util/promote_integral.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n#include <boost/geometry/util/select_most_precise.hpp>\n#include <boost/geometry/util/math.hpp>\n\nnamespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry\n{\n\nnamespace policies { namespace relate\n{\n\n\n/*!\n\\brief Policy calculating the intersection points themselves\n */\ntemplate\n<\n    typename ReturnType\n>\nstruct segments_intersection_points\n{\n    typedef ReturnType return_type;\n\n    template\n    <\n        typename Point,\n        typename Segment,\n        typename SegmentRatio,\n        typename T\n    >\n    static inline void assign(Point& point,\n                Segment const& segment,\n                SegmentRatio const& ratio,\n                T const& dx, T const& dy)\n    {\n        typedef typename geometry::coordinate_type<Point>::type coordinate_type;\n\n        // Calculate the intersection point based on segment_ratio\n        // Up to now, division was postponed. Here we divide using numerator/\n        // denominator. In case of integer this results in an integer\n        // division.\n        BOOST_GEOMETRY_ASSERT(ratio.denominator() != 0);\n\n        typedef typename promote_integral<coordinate_type>::type promoted_type;\n\n        promoted_type const numerator\n            = geofeatures_boost::numeric_cast<promoted_type>(ratio.numerator());\n        promoted_type const denominator\n            = geofeatures_boost::numeric_cast<promoted_type>(ratio.denominator());\n        promoted_type const dx_promoted = geofeatures_boost::numeric_cast<promoted_type>(dx);\n        promoted_type const dy_promoted = geofeatures_boost::numeric_cast<promoted_type>(dy);\n\n        set<0>(point, get<0, 0>(segment) + geofeatures_boost::numeric_cast\n            <\n                coordinate_type\n            >(numerator * dx_promoted / denominator));\n        set<1>(point, get<0, 1>(segment) + geofeatures_boost::numeric_cast\n            <\n                coordinate_type\n            >(numerator * dy_promoted / denominator));\n    }\n\n    template\n    <\n        typename Segment1,\n        typename Segment2,\n        typename SegmentIntersectionInfo\n    >\n    static inline return_type segments_crosses(side_info const&,\n                    SegmentIntersectionInfo const& sinfo,\n                    Segment1 const& s1, Segment2 const& s2)\n    {\n        return_type result;\n        result.count = 1;\n\n        bool use_a = true;\n\n        // Prefer one segment if one is on or near an endpoint\n        bool const a_near_end = sinfo.robust_ra.near_end();\n        bool const b_near_end = sinfo.robust_rb.near_end();\n        if (a_near_end && ! b_near_end)\n        {\n            use_a = true;\n        }\n        else if (b_near_end && ! a_near_end)\n        {\n            use_a = false;\n        }\n        else\n        {\n            // Prefer shorter segment\n            typedef typename SegmentIntersectionInfo::promoted_type ptype;\n            ptype const len_a = sinfo.dx_a * sinfo.dx_a + sinfo.dy_a * sinfo.dy_a;\n            ptype const len_b = sinfo.dx_b * sinfo.dx_b + sinfo.dy_b * sinfo.dy_b;\n            if (len_b < len_a)\n            {\n                use_a = false;\n            }\n            // else use_a is true but was already assigned like that\n        }\n\n        if (use_a)\n        {\n            assign(result.intersections[0], s1, sinfo.robust_ra,\n                sinfo.dx_a, sinfo.dy_a);\n        }\n        else\n        {\n            assign(result.intersections[0], s2, sinfo.robust_rb,\n                sinfo.dx_b, sinfo.dy_b);\n        }\n\n        result.fractions[0].assign(sinfo);\n\n        return result;\n    }\n\n    template <typename Segment1, typename Segment2, typename Ratio>\n    static inline return_type segments_collinear(\n        Segment1 const& a, Segment2 const& b, bool /*opposite*/,\n        int a1_wrt_b, int a2_wrt_b, int b1_wrt_a, int b2_wrt_a,\n        Ratio const& ra_from_wrt_b, Ratio const& ra_to_wrt_b,\n        Ratio const& rb_from_wrt_a, Ratio const& rb_to_wrt_a)\n    {\n        return_type result;\n        unsigned int index = 0, count_a = 0, count_b = 0;\n        Ratio on_a[2];\n\n        // The conditions \"index < 2\" are necessary for non-robust handling,\n        // if index would be 2 this indicate an (currently uncatched) error\n\n        // IMPORTANT: the order of conditions is different as in direction.hpp\n        if (a1_wrt_b >= 1 && a1_wrt_b <= 3 // ra_from_wrt_b.on_segment()\n            && index < 2)\n        {\n            //     a1--------->a2\n            // b1----->b2\n            //\n            // ra1 (relative to b) is between 0/1:\n            // -> First point of A is intersection point\n            detail::assign_point_from_index<0>(a, result.intersections[index]);\n            result.fractions[index].assign(Ratio::zero(), ra_from_wrt_b);\n            on_a[index] = Ratio::zero();\n            index++;\n            count_a++;\n        }\n        if (b1_wrt_a == 2 //rb_from_wrt_a.in_segment()\n            && index < 2)\n        {\n            // We take the first intersection point of B\n            // a1--------->a2\n            //         b1----->b2\n            // But only if it is not located on A\n            // a1--------->a2\n            // b1----->b2      rb_from_wrt_a == 0/1 -> a already taken\n\n            detail::assign_point_from_index<0>(b, result.intersections[index]);\n            result.fractions[index].assign(rb_from_wrt_a, Ratio::zero());\n            on_a[index] = rb_from_wrt_a;\n            index++;\n            count_b++;\n        }\n\n        if (a2_wrt_b >= 1 && a2_wrt_b <= 3 //ra_to_wrt_b.on_segment()\n            && index < 2)\n        {\n            // Similarly, second IP (here a2)\n            // a1--------->a2\n            //         b1----->b2\n            detail::assign_point_from_index<1>(a, result.intersections[index]);\n            result.fractions[index].assign(Ratio::one(), ra_to_wrt_b);\n            on_a[index] = Ratio::one();\n            index++;\n            count_a++;\n        }\n        if (b2_wrt_a == 2 // rb_to_wrt_a.in_segment()\n            && index < 2)\n        {\n            detail::assign_point_from_index<1>(b, result.intersections[index]);\n            result.fractions[index].assign(rb_to_wrt_a, Ratio::one());\n            on_a[index] = rb_to_wrt_a;\n            index++;\n            count_b++;\n        }\n\n        // TEMPORARY\n        // If both are from b, and b is reversed w.r.t. a, we swap IP's\n        // to align them w.r.t. a\n        // get_turn_info still relies on some order (in some collinear cases)\n        if (index == 2 && on_a[1] < on_a[0])\n        {\n            std::swap(result.fractions[0], result.fractions[1]);\n            std::swap(result.intersections[0], result.intersections[1]);\n        }\n\n        result.count = index;\n\n        return result;\n    }\n\n    static inline return_type disjoint()\n    {\n        return return_type();\n    }\n    static inline return_type error(std::string const&)\n    {\n        return return_type();\n    }\n\n    // Both degenerate\n    template <typename Segment>\n    static inline return_type degenerate(Segment const& segment, bool)\n    {\n        return_type result;\n        result.count = 1;\n        set<0>(result.intersections[0], get<0, 0>(segment));\n        set<1>(result.intersections[0], get<0, 1>(segment));\n        return result;\n    }\n\n    // One degenerate\n    template <typename Segment, typename Ratio>\n    static inline return_type one_degenerate(Segment const& degenerate_segment,\n            Ratio const& ratio, bool a_degenerate)\n    {\n        return_type result;\n        result.count = 1;\n        set<0>(result.intersections[0], get<0, 0>(degenerate_segment));\n        set<1>(result.intersections[0], get<0, 1>(degenerate_segment));\n        if (a_degenerate)\n        {\n            // IP lies on ratio w.r.t. segment b\n            result.fractions[0].assign(Ratio::zero(), ratio);\n        }\n        else\n        {\n            result.fractions[0].assign(ratio, Ratio::zero());\n        }\n        return result;\n    }\n};\n\n\n}} // namespace policies::relate\n\n}} // namespace geofeatures_boost::geometry\n\n#endif // BOOST_GEOMETRY_GEOMETRY_POLICIES_RELATE_INTERSECTION_POINTS_HPP\n", "meta": {"hexsha": "cd40e72cb4924625fce409e1baa0a29e246a3180", "size": 8972, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/policies/relate/intersection_points.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/policies/relate/intersection_points.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/policies/relate/intersection_points.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": 33.1070110701, "max_line_length": 116, "alphanum_fraction": 0.5990860455, "num_tokens": 2151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.2574064547476038}}
{"text": "#ifndef NFP_HPP_\n#define NFP_HPP_\n\n#include <iostream>\n#include <list>\n#include <string>\n#include <fstream>\n#include <streambuf>\n#include <vector>\n#include <set>\n#include <exception>\n#include <random>\n#include <limits>\n\n#ifdef LIBNFP_USE_RATIONAL\n#include <boost/multiprecision/gmp.hpp>\n#include <boost/multiprecision/number.hpp>\n#endif\n#include <boost/geometry.hpp>\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n#include <boost/geometry/io/svg/svg_mapper.hpp>\n#include <boost/geometry/algorithms/intersects.hpp>\n#include <boost/geometry/geometries/register/point.hpp>\n\n#ifdef LIBNFP_USE_RATIONAL\nnamespace bm = boost::multiprecision;\n#endif\nnamespace bg = boost::geometry;\nnamespace trans = boost::geometry::strategy::transform;\n\n\nnamespace libnfp {\n#ifdef NFP_DEBUG\n#define DEBUG_VAL(x) std::cerr << x << std::endl;\n#define DEBUG_MSG(title, value) std::cerr << title << \":\" << value << std::endl;\n#else\n#define DEBUG_VAL(x)\n#define DEBUG_MSG(title, value)\n#endif\n\nusing std::string;\n\nstatic constexpr long double NFP_EPSILON=0.00000001;\n\nclass LongDouble {\nprivate:\n\tlong double val_;\npublic:\n\tLongDouble() : val_(0) {\n\t}\n\n\tLongDouble(const long double& val) : val_(val) {\n\t}\n\n\tvoid setVal(const long double& v) {\n\t\tval_ = v;\n\t}\n\n\tlong double val() const {\n\t\treturn val_;\n\t}\n\n\tLongDouble operator/(const LongDouble& other) const {\n\t\treturn this->val_ / other.val_;\n\t}\n\n\tLongDouble operator*(const LongDouble& other) const {\n\t\treturn this->val_ * other.val_;\n\t}\n\n\tLongDouble operator-(const LongDouble& other) const {\n\t\treturn this->val_ - other.val_;\n\t}\n\n\tLongDouble operator-() const {\n\t\treturn this->val_ * -1;\n\t}\n\n\tLongDouble operator+(const LongDouble& other) const {\n\t\treturn this->val_ + other.val_;\n\t}\n\n\tvoid operator/=(const LongDouble& other) {\n\t\tthis->val_ = this->val_ / other.val_;\n\t}\n\n\tvoid operator*=(const LongDouble& other) {\n\t\tthis->val_ = this->val_ * other.val_;\n\t}\n\n\tvoid operator-=(const LongDouble& other) {\n\t\tthis->val_ = this->val_ - other.val_;\n\t}\n\n\tvoid operator+=(const LongDouble& other) {\n\t\tthis->val_ = this->val_ + other.val_;\n\t}\n\n\tbool operator==(const int& other) const {\n\t\treturn this->operator ==(static_cast<long double>(other));\n\t}\n\n\tbool operator==(const LongDouble& other) const {\n\t\treturn this->operator ==(other.val());\n\t}\n\n\tbool operator==(const long double& other) const {\n\t\treturn this->val() == other;\n\t}\n\n\tbool operator!=(const int& other) const {\n\t\treturn !this->operator ==(other);\n\t}\n\n\tbool operator!=(const LongDouble& other) const {\n\t\treturn !this->operator ==(other);\n\t}\n\n\tbool operator!=(const long double& other) const {\n\t\treturn !this->operator ==(other);\n\t}\n\n\tbool operator<(const int& other) const {\n\t\treturn this->operator <(static_cast<long double>(other));\n\t}\n\n\tbool operator<(const LongDouble& other) const {\n\t\treturn this->operator <(other.val());\n\t}\n\n\tbool operator<(const long double& other) const {\n\t\treturn this->val() < other;\n\t}\n\n\tbool operator>(const int& other) const {\n\t\treturn this->operator >(static_cast<long double>(other));\n\t}\n\n\tbool operator>(const LongDouble& other) const {\n\t\treturn this->operator >(other.val());\n\t}\n\n\tbool operator>(const long double& other) const {\n\t\treturn this->val() > other;\n\t}\n\n\tbool operator>=(const int& other) const {\n\t\treturn this->operator >=(static_cast<long double>(other));\n\t}\n\n\tbool operator>=(const LongDouble& other) const {\n\t\treturn this->operator >=(other.val());\n\t}\n\n\tbool operator>=(const long double& other) const {\n\t\treturn this->val() >= other;\n\t}\n\n\tbool operator<=(const int& other) const {\n\t\treturn this->operator <=(static_cast<long double>(other));\n\t}\n\n\tbool operator<=(const LongDouble& other) const {\n\t\treturn this->operator <=(other.val());\n\t}\n\n\tbool operator<=(const long double& other) const {\n\t\treturn this->val() <= other;\n\t}\n};\n}\n\nnamespace std {\ntemplate<>\n   struct numeric_limits<libnfp::LongDouble>\n   {\n     static constexpr bool is_specialized = true;\n\n     static constexpr long double\n     min() noexcept { return std::numeric_limits<long double>::min(); }\n\n     static constexpr long double\n     max() noexcept { return std::numeric_limits<long double>::max(); }\n\n#if __cplusplus >= 201103L\n     static constexpr long double\n     lowest() noexcept { return -std::numeric_limits<long double>::lowest(); }\n#endif\n\n\t static constexpr int digits = std::numeric_limits<long double>::digits;\n     static constexpr int digits10 = std::numeric_limits<long double>::digits10;\n#if __cplusplus >= 201103L\n     static constexpr int max_digits10\n\t = std::numeric_limits<long double>::max_digits10;\n#endif\n     static constexpr bool is_signed = true;\n     static constexpr bool is_integer = false;\n     static constexpr bool is_exact = false;\n     static constexpr int radix = std::numeric_limits<long double>::radix;\n\n     static constexpr long double\n     epsilon() noexcept { return libnfp::NFP_EPSILON; }\n\n     static constexpr long double\n     round_error() noexcept { return 0.5L; }\n\n     static constexpr int min_exponent = std::numeric_limits<long double>::min_exponent;\n     static constexpr int min_exponent10 = std::numeric_limits<long double>::min_exponent10;\n     static constexpr int max_exponent = std::numeric_limits<long double>::max_exponent;\n     static constexpr int max_exponent10 = std::numeric_limits<long double>::max_exponent10;\n\n\t \n     static constexpr bool has_infinity = std::numeric_limits<long double>::has_infinity;\n     static constexpr bool has_quiet_NaN = std::numeric_limits<long double>::has_quiet_NaN;\n     static constexpr bool has_signaling_NaN = has_quiet_NaN;\n\t static constexpr float_denorm_style has_denorm\n\t\t = std::numeric_limits<long double>::has_denorm;\n     static constexpr bool has_denorm_loss\n\t     = std::numeric_limits<long double>::has_denorm_loss;\n\t \n\n     static constexpr long double\n\t\tinfinity() noexcept { return std::numeric_limits<long double>::infinity(); }\n\n     static constexpr long double\n\t\t quiet_NaN() noexcept { return std::numeric_limits<long double>::quiet_NaN(); }\n\n     static constexpr long double\n\t\t signaling_NaN() noexcept { return std::numeric_limits<long double>::signaling_NaN(); }\n\n\t \n     static constexpr long double\n\t\t denorm_min() noexcept { return std::numeric_limits<long double>::denorm_min(); }\n\n     static constexpr bool is_iec559\n\t = has_infinity && has_quiet_NaN && has_denorm == denorm_present;\n\t \n     static constexpr bool is_bounded = true;\n     static constexpr bool is_modulo = false;\n\n     static constexpr bool traps = std::numeric_limits<long double>::traps;\n     static constexpr bool tinyness_before =\n    \t\t std::numeric_limits<long double>::tinyness_before;\n     static constexpr float_round_style round_style =\n\t\t\t\t\t\t      round_to_nearest;\n   };\n}\n\nnamespace boost {\nnamespace numeric {\n\ttemplate<>\n\tstruct raw_converter<boost::numeric::conversion_traits<double, libnfp::LongDouble>>\n\t{\n\t\ttypedef typename boost::numeric::conversion_traits<double, libnfp::LongDouble>::result_type   result_type   ;\n\t\ttypedef typename boost::numeric::conversion_traits<double, libnfp::LongDouble>::argument_type argument_type ;\n\n\t\tstatic result_type low_level_convert ( argument_type s ) { return s.val() ; }\n\t} ;\n}\n}\n\nnamespace libnfp {\n\n#ifndef LIBNFP_USE_RATIONAL\ntypedef LongDouble coord_t;\n#else\ntypedef bm::number<bm::gmp_rational, bm::et_off> rational_t;\ntypedef rational_t coord_t;\n#endif\n\nbool equals(const LongDouble& lhs, const LongDouble& rhs);\n#ifdef LIBNFP_USE_RATIONAL\nbool equals(const rational_t& lhs, const rational_t& rhs);\n#endif\nbool equals(const long double& lhs, const long double& rhs);\n\nconst coord_t MAX_COORD = 999999999999999999;\nconst coord_t MIN_COORD = std::numeric_limits<coord_t>::min();\n\nclass point_t {\npublic:\n\tpoint_t() : x_(0), y_(0) {\n\t}\n\tpoint_t(coord_t x, coord_t y) : x_(x), y_(y) {\n\t}\n\tbool marked_ = false;\n\tcoord_t x_;\n\tcoord_t y_;\n\n\tpoint_t operator-(const point_t& other) const {\n\t\tpoint_t result = *this;\n\t\tbg::subtract_point(result, other);\n\t\treturn result;\n\t}\n\n\tpoint_t operator+(const point_t& other) const {\n\t\tpoint_t result = *this;\n\t\tbg::add_point(result, other);\n\t\treturn result;\n\t}\n\n\tbool operator==(const point_t&  other) const {\n\t\t\treturn bg::equals(this, other);\n  }\n\n  bool operator!=(const point_t&  other) const {\n      return !this->operator ==(other);\n  }\n\n\tbool operator<(const point_t&  other) const {\n      return  boost::geometry::math::smaller(this->x_, other.x_) || (equals(this->x_, other.x_) && boost::geometry::math::smaller(this->y_, other.y_));\n  }\n};\n\n\n\n\ninline long double toLongDouble(const LongDouble& c) {\n\treturn c.val();\n}\n\n#ifdef LIBNFP_USE_RATIONAL\ninline long double toLongDouble(const rational_t& c) {\n\treturn bm::numerator(c).convert_to<long double>() / bm::denominator(c).convert_to<long double>();\n}\n#endif\n\nstd::ostream& operator<<(std::ostream& os, const coord_t& p)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tos << toLongDouble(p);\n\treturn os;\n}\n#endif\n\nstd::istream& operator>>(std::istream& is, LongDouble& c)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tlong double val;\n\tis >> val;\n\tc.setVal(val);\n\treturn is;\n}\n#endif\n\nstd::ostream& operator<<(std::ostream& os, const point_t& p)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tos << \"{\" << toLongDouble(p.x_) << \",\" << toLongDouble(p.y_) << \"}\";\n\treturn os;\n}\n#endif\n\nconst point_t INVALID_POINT = {MAX_COORD, MAX_COORD};\n\ntypedef bg::model::segment<point_t> segment_t;\n  \n}\n\n#ifdef LIBNFP_USE_RATIONAL\ninline long double acos(const libnfp::rational_t& r) {\n\treturn acos(libnfp::toLongDouble(r));\n}\n#endif\n\ninline long double acos(const libnfp::LongDouble& ld) {\n\treturn acos(libnfp::toLongDouble(ld));\n}\n\n#ifdef LIBNFP_USE_RATIONAL\ninline long double sqrt(const libnfp::rational_t& r) {\n\treturn sqrt(libnfp::toLongDouble(r));\n}\n#endif\n\ninline long double sqrt(const libnfp::LongDouble& ld) {\n\treturn sqrt(libnfp::toLongDouble(ld));\n}\n\nnamespace libnfp {\n#ifdef LIBNFP_USE_RATIONAL\ninline long double cos(const rational_t& r) {\n  return std::cos(toLongDouble(r));\n}\n#endif\n\ninline long double cos(const LongDouble& ld) {\n  return std::cos(libnfp::toLongDouble(ld));\n}\n\n#ifdef LIBNFP_USE_RATIONAL\ninline long double sin(const rational_t& r) {\n  return std::sin(toLongDouble(r));\n}\n#endif\n\ninline long double sin(const LongDouble& ld) {\n  return std::sin(ld.val());\n}\n  \n}\n\n  \nBOOST_GEOMETRY_REGISTER_POINT_2D(libnfp::point_t, libnfp::coord_t, cs::cartesian, x_, y_)\n\n\nnamespace boost {\nnamespace geometry {\nnamespace math {\nnamespace detail {\n\ntemplate <>\nstruct square_root<libnfp::LongDouble>\n{\n  typedef libnfp::LongDouble return_type;\n\n\tstatic inline libnfp::LongDouble apply(libnfp::LongDouble const& a)\n  {\n        return std::sqrt(a.val());\n  }\n};\n\n#ifdef LIBNFP_USE_RATIONAL\ntemplate <>\nstruct square_root<libnfp::rational_t>\n{\n  typedef libnfp::rational_t return_type;\n\n\tstatic inline libnfp::rational_t apply(libnfp::rational_t const& a)\n  {\n        return std::sqrt(libnfp::toLongDouble(a));\n  }\n};\n#endif\n\ntemplate<>\nstruct abs<libnfp::LongDouble>\n\t{\n\tstatic libnfp::LongDouble apply(libnfp::LongDouble const& value)\n\t\t\t{\n\t\t\t\tlibnfp::LongDouble const zero = libnfp::LongDouble();\n\t\t\t\t\treturn value.val() < zero.val() ? -value.val() : value.val();\n\t\t\t}\n\t};\n\ntemplate <>\nstruct equals<libnfp::LongDouble, false>\n{\n\ttemplate<typename Policy>\n\tstatic inline bool apply(libnfp::LongDouble const& lhs, libnfp::LongDouble const& rhs, Policy const& policy)\n  {\n\t\tif(lhs.val() == rhs.val())\n\t\t\treturn true;\n\n\t  return bg::math::detail::abs<libnfp::LongDouble>::apply(lhs.val() - rhs.val()) <=  policy.apply(lhs.val(), rhs.val()) * libnfp::NFP_EPSILON;\n  }\n};\n\ntemplate <>\nstruct smaller<libnfp::LongDouble>\n{\n\tstatic inline bool apply(libnfp::LongDouble const& lhs, libnfp::LongDouble const& rhs)\n  {\n\t\tif(lhs.val() == rhs.val() || bg::math::detail::abs<libnfp::LongDouble>::apply(lhs.val() - rhs.val()) <=  libnfp::NFP_EPSILON * std::max(lhs.val(), rhs.val()))\n\t\t\treturn false;\n\n\t  return lhs < rhs;\n  }\n};\n}\n}\n}\n}\n\nnamespace libnfp {\ninline bool smaller(const LongDouble& lhs, const LongDouble& rhs) {\n\treturn boost::geometry::math::detail::smaller<LongDouble>::apply(lhs, rhs);\n}\n\ninline bool larger(const LongDouble& lhs, const LongDouble& rhs) {\n  return smaller(rhs, lhs);\n}\n\nbool equals(const LongDouble& lhs, const LongDouble& rhs)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n\t;\n#else\n{\n\tif(lhs.val() == rhs.val())\n\t\treturn true;\n\n  return bg::math::detail::abs<libnfp::LongDouble>::apply(lhs.val() - rhs.val()) <=  libnfp::NFP_EPSILON * std::max(lhs.val(), rhs.val());\n}\n#endif\n\n#ifdef LIBNFP_USE_RATIONAL\ninline bool smaller(const rational_t& lhs, const rational_t& rhs) {\n\treturn lhs < rhs;\n}\n\ninline bool larger(const rational_t& lhs, const rational_t& rhs) {\n  return smaller(rhs, lhs);\n}\n\nbool equals(const rational_t& lhs, const rational_t& rhs) {\n\treturn lhs == rhs;\n}\n#endif\n\ninline bool smaller(const long double& lhs, const long double& rhs) {\n\treturn lhs < rhs;\n}\n\ninline bool larger(const long double& lhs, const long double& rhs) {\n  return smaller(rhs, lhs);\n}\n\n\nbool equals(const long double& lhs, const long double& rhs)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\treturn lhs == rhs;\n}\n#endif\n\ntypedef bg::model::polygon<point_t, false, true> polygon_t;\ntypedef std::vector<polygon_t::ring_type> nfp_t;\ntypedef bg::model::linestring<point_t> linestring_t;\n\ntypedef typename polygon_t::ring_type::size_type psize_t;\n\ntypedef bg::model::d2::point_xy<long double> pointf_t;\ntypedef bg::model::segment<pointf_t> segmentf_t;\ntypedef bg::model::polygon<pointf_t, false, true> polygonf_t;\n\npolygonf_t::ring_type convert(const polygon_t::ring_type& r)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tpolygonf_t::ring_type rf;\n\tfor(const auto& pt : r) {\n\t\trf.push_back(pointf_t(toLongDouble(pt.x_), toLongDouble(pt.y_)));\n\t}\n\treturn rf;\n}\n#endif\n\npolygonf_t convert(polygon_t p) \n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tpolygonf_t pf;\n\tpf.outer() = convert(p.outer());\n\n\tfor(const auto& r : p.inners()) {\n\t\tpf.inners().push_back(convert(r));\n\t}\n\n\treturn pf;\n}\n#endif\n\npolygon_t nfpRingsToNfpPoly(const nfp_t& nfp) \n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tpolygon_t nfppoly;\n\tfor (const auto& pt : nfp.front()) {\n\t\tnfppoly.outer().push_back(pt);\n\t}\n\n\tfor (size_t i = 1; i < nfp.size(); ++i) {\n\t\tnfppoly.inners().push_back({});\n\t\tfor (const auto& pt : nfp[i]) {\n\t\t\tnfppoly.inners().back().push_back(pt);\n\t\t}\n\t}\n\n\treturn nfppoly;\n}\n#endif\n\nvoid write_svg(std::string const& filename,const std::vector<segment_t>& segments)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n    std::ofstream svg(filename.c_str());\n\n    boost::geometry::svg_mapper<pointf_t> mapper(svg, 100, 100, \"width=\\\"200mm\\\" height=\\\"200mm\\\" viewBox=\\\"-250 -250 500 500\\\"\");\n    for(const auto& seg : segments) {\n    \tsegmentf_t segf({toLongDouble(seg.first.x_), toLongDouble(seg.first.y_)}, {toLongDouble(seg.second.x_), toLongDouble(seg.second.y_)});\n    \tmapper.add(segf);\n    \tmapper.map(segf, \"fill-opacity:0.5;fill:rgb(153,204,0);stroke:rgb(153,204,0);stroke-width:2\");\n    }\n}\n#endif\n\nvoid write_svg(std::string const& filename,\tconst polygon_t& p, const polygon_t::ring_type& ring)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tstd::ofstream svg(filename.c_str());\n\n\tboost::geometry::svg_mapper<pointf_t> mapper(svg, 100, 100,\t\"width=\\\"200mm\\\" height=\\\"200mm\\\" viewBox=\\\"-250 -250 500 500\\\"\");\n\tauto pf = convert(p);\n\tauto rf = convert(ring);\n\n\tmapper.add(pf);\n\tmapper.map(pf, \"fill-opacity:0.5;fill:rgb(153,204,0);stroke:rgb(153,204,0);stroke-width:2\");\n\tmapper.add(rf);\n\tmapper.map(rf, \"fill-opacity:0.5;fill:rgb(153,204,0);stroke:rgb(153,204,0);stroke-width:2\");\n}\n#endif\n\nvoid write_svg(std::string const& filename,\ttypename std::vector<polygon_t> const& polygons)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tstd::ofstream svg(filename.c_str());\n\n\tboost::geometry::svg_mapper<pointf_t> mapper(svg, 100, 100, \"width=\\\"200mm\\\" height=\\\"200mm\\\" viewBox=\\\"-250 -250 500 500\\\"\");\n\tfor (auto p : polygons) {\n\t\tauto pf  = convert(p);\n\t\tmapper.add(pf);\n\t\tmapper.map(pf, \"fill-opacity:0.5;fill:rgb(153,204,0);stroke:rgb(153,204,0);stroke-width:2\");\n\t}\n}\n#endif\n\nvoid write_svg(std::string const& filename,\ttypename std::vector<polygon_t> const& polygons, const nfp_t& nfp)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tpolygon_t nfppoly;\n\tfor (const auto& pt : nfp.front()) {\n\t\tnfppoly.outer().push_back(pt);\n\t}\n\n\tfor (size_t i = 1; i < nfp.size(); ++i) {\n\t\tnfppoly.inners().push_back({});\n\t\tfor (const auto& pt : nfp[i]) {\n\t\t\tnfppoly.inners().back().push_back(pt);\n\t\t}\n\t}\n\tstd::ofstream svg(filename.c_str());\n\n\tboost::geometry::svg_mapper<pointf_t> mapper(svg, 100, 100,\t\"width=\\\"200mm\\\" height=\\\"200mm\\\" viewBox=\\\"-250 -250 500 500\\\"\");\n\tfor (auto p : polygons) {\n\t\tauto pf  = convert(p);\n\t\tmapper.add(pf);\n\t\tmapper.map(pf, \"fill-opacity:0.5;fill:rgb(153,204,0);stroke:rgb(153,204,0);stroke-width:2\");\n\t}\n\tbg::correct(nfppoly);\n\tauto nfpf = convert(nfppoly);\n\tmapper.add(nfpf);\n\tmapper.map(nfpf, \"fill-opacity:0.5;fill:rgb(204,153,0);stroke:rgb(204,153,0);stroke-width:2\");\n\n\tfor(auto& r: nfpf.inners()) {\n\t\tif(r.size() == 1) {\n\t\t\tmapper.add(r.front());\n\t\t\tmapper.map(r.front(), \"fill-opacity:0.5;fill:rgb(204,153,0);stroke:rgb(204,153,0);stroke-width:2\");\n\t\t} else if(r.size() == 2) {\n\t\t\tsegmentf_t seg(r.front(), *(r.begin()+1));\n\t\t\tmapper.add(seg);\n\t\t\tmapper.map(seg, \"fill-opacity:0.5;fill:rgb(204,153,0);stroke:rgb(204,153,0);stroke-width:2\");\n\t\t}\n\t}\n}\n#endif\n\nstd::ostream& operator<<(std::ostream& os, const segment_t& seg)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tos << \"{\" << seg.first << \",\" << seg.second << \"}\";\n\treturn os;\n}\n#endif\n\ninline bool operator<(const segment_t& lhs, const segment_t& rhs) {\n\treturn lhs.first < rhs.first || ((lhs.first == rhs.first) && (lhs.second < rhs.second));\n}\n\ninline bool operator==(const segment_t& lhs, const segment_t& rhs) {\n\treturn (lhs.first == rhs.first && lhs.second == rhs.second) || (lhs.first == rhs.second && lhs.second == rhs.first);\n}\n\ninline bool operator!=(const segment_t& lhs, const segment_t& rhs) {\n\treturn !operator==(lhs,rhs);\n}\n\nenum Alignment {\n\tLEFT,\n\tRIGHT,\n\tON\n};\n\npoint_t normalize(const point_t& pt)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tpoint_t norm = pt;\n\tcoord_t len = bg::length(segment_t{{0,0},pt});\n\n\tif(len == 0.0L)\n\t\treturn {0,0};\n\n\tnorm.x_ /= len;\n\tnorm.y_ /= len;\n\n\treturn norm;\n}\n#endif\n\nAlignment get_alignment(const segment_t& seg, const point_t& pt)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tcoord_t res = ((seg.second.x_ - seg.first.x_)*(pt.y_ - seg.first.y_)\n\t\t\t- (seg.second.y_ - seg.first.y_)*(pt.x_ - seg.first.x_));\n\n\tif(equals(res, 0)) {\n\t\treturn ON;\n\t} else\tif(larger(res,0)) {\n\t\treturn LEFT;\n\t} else {\n\t\treturn RIGHT;\n\t}\n}\n#endif\n\nlong double get_inner_angle(const point_t& joint, const point_t& end1, const point_t& end2) \n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tcoord_t dx21 = end1.x_-joint.x_;\n\tcoord_t dx31 = end2.x_-joint.x_;\n\tcoord_t dy21 = end1.y_-joint.y_;\n\tcoord_t dy31 = end2.y_-joint.y_;\n\tcoord_t m12 = sqrt((dx21*dx21 + dy21*dy21));\n\tcoord_t m13 = sqrt((dx31*dx31 + dy31*dy31));\n\tif(m12 == 0.0L || m13 == 0.0L)\n\t\treturn 0;\n\treturn acos( (dx21*dx31 + dy21*dy31) / (m12 * m13) );\n}\n#endif\n\nstruct TouchingPoint {\n\tenum Type {\n\t\tVERTEX,\n\t\tA_ON_B,\n\t\tB_ON_A\n\t};\n\tType type_;\n\tpsize_t A_;\n\tpsize_t B_;\n};\n\nstruct TranslationVector {\n\tpoint_t vector_;\n\tsegment_t edge_;\n\tbool fromA_;\n\tstring name_;\n\n\tbool operator<(const TranslationVector& other) const {\n\t\treturn this->vector_ < other.vector_ || ((this->vector_ == other.vector_) && (this->edge_ < other.edge_));\n\t}\n};\n\nstd::ostream& operator<<(std::ostream& os, const TranslationVector& tv) \n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tos << \"{\" << tv.edge_ << \" -> \" << tv.vector_ << \"} = \" << tv.name_;\n\treturn os;\n}\n#endif\n\n\nvoid read_wkt_polygon(const string& filename, polygon_t& p)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tstd::ifstream t(filename);\n\n\tstd::string str;\n\tt.seekg(0, std::ios::end);\n\tstr.reserve(t.tellg());\n\tt.seekg(0, std::ios::beg);\n\n\tstr.assign((std::istreambuf_iterator<char>(t)),\n\t\t\t\t\t\t\tstd::istreambuf_iterator<char>());\n\n\tstr.pop_back();\n\tbg::read_wkt(str, p);\n\tbg::correct(p);\n}\n#endif\n\nstd::vector<psize_t> find_minimum_y(const polygon_t& p)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tstd::vector<psize_t> result;\n\tcoord_t min = MAX_COORD;\n\tauto& po = p.outer();\n\tfor(psize_t i = 0; i < p.outer().size() - 1; ++i) {\n\t\tif(smaller(po[i].y_, min)) {\n\t\t\tresult.clear();\n\t\t\tmin = po[i].y_;\n\t\t\tresult.push_back(i);\n\t\t} else if (equals(po[i].y_, min)) {\n\t\t\tresult.push_back(i);\n\t\t}\n\t}\n\treturn result;\n}\n#endif\n\nstd::vector<psize_t> find_maximum_y(const polygon_t& p)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tstd::vector<psize_t> result;\n\tcoord_t max = MIN_COORD;\n\tauto& po = p.outer();\n\tfor(psize_t i = 0; i < p.outer().size() - 1; ++i) {\n\t\tif(larger(po[i].y_, max)) {\n\t\t\tresult.clear();\n\t\t\tmax = po[i].y_;\n\t\t\tresult.push_back(i);\n\t\t} else if (equals(po[i].y_, max)) {\n\t\t\tresult.push_back(i);\n\t\t}\n\t}\n\treturn result;\n}\n#endif\n\npsize_t find_point(const polygon_t::ring_type& ring, const point_t& pt)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tfor(psize_t i = 0; i < ring.size(); ++i) {\n\t\tif(ring[i] == pt)\n\t\t\treturn i;\n\t}\n\treturn std::numeric_limits<psize_t>::max();\n}\n#endif\n\nstd::vector<TouchingPoint> findTouchingPoints(const polygon_t::ring_type& ringA, const polygon_t::ring_type& ringB)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tstd::vector<TouchingPoint> touchers;\n\tfor(psize_t i = 0; i < ringA.size() - 1; i++) {\n\t\tpsize_t nextI = i+1;\n\t\tfor(psize_t j = 0; j < ringB.size() - 1; j++) {\n\t\t\tpsize_t nextJ = j+1;\n\t\t\tif(ringA[i] == ringB[j]) {\n\t\t\t\ttouchers.push_back({TouchingPoint::VERTEX, i, j});\n\t\t\t} else if (ringA[nextI] != ringB[j] && bg::intersects(segment_t(ringA[i],ringA[nextI]), ringB[j])) {\n\t\t\t\ttouchers.push_back({TouchingPoint::B_ON_A, nextI, j});\n\t\t\t} else if (ringB[nextJ] != ringA[i] && bg::intersects(segment_t(ringB[j],ringB[nextJ]), ringA[i])) {\n\t\t\t\ttouchers.push_back({TouchingPoint::A_ON_B, i, nextJ});\n\t\t\t}\n\t\t}\n\t}\n\treturn touchers;\n}\n#endif\n\n//TODO deduplicate code\nTranslationVector trimVector(const polygon_t::ring_type& rA, const polygon_t::ring_type& rB, const TranslationVector& tv)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tcoord_t shortest = bg::length(tv.edge_);\n\tTranslationVector trimmed = tv;\n\tfor(const auto& ptA : rA) {\n\t\tpoint_t translated;\n\t\t//for polygon A we invert the translation\n\t\ttrans::translate_transformer<coord_t, 2, 2> translate(-tv.vector_.x_, -tv.vector_.y_);\n\t\tboost::geometry::transform(ptA, translated, translate);\n\t\tlinestring_t projection;\n\t\tsegment_t segproj(ptA, translated);\n\t\tprojection.push_back(ptA);\n\t\tprojection.push_back(translated);\n\t\tstd::vector<point_t> intersections;\n\t\tbg::intersection(rB, projection, intersections);\n\t\tif(bg::touches(projection, rB) && intersections.size() < 2) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t//find shortest intersection\n\t\tcoord_t len;\n\t\tsegment_t segi;\n\t\tfor(const auto& pti : intersections) {\n\t\t\tsegi = segment_t(ptA,pti);\n\t\t\tlen = bg::length(segi);\n\t\t\tif(smaller(len, shortest)) {\n\t\t\t\ttrimmed.vector_ = ptA - pti;\n\t\t\t\ttrimmed.edge_ = segi;\n\t\t\t\tshortest = len;\n\t\t\t}\n\t\t}\n\t}\n\n\tfor(const auto& ptB : rB) {\n\t\tpoint_t translated;\n\n\t\ttrans::translate_transformer<coord_t, 2, 2> translate(tv.vector_.x_, tv.vector_.y_);\n\t\tboost::geometry::transform(ptB, translated, translate);\n\t\tlinestring_t projection;\n\t\tsegment_t segproj(ptB, translated);\n\t\tprojection.push_back(ptB);\n\t\tprojection.push_back(translated);\n\t\tstd::vector<point_t> intersections;\n\t\tbg::intersection(rA, projection, intersections);\n\t\tif(bg::touches(projection, rA) && intersections.size() < 2) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t//find shortest intersection\n\t\tcoord_t len;\n\t\tsegment_t segi;\n\t\tfor(const auto& pti : intersections) {\n\n\t\t\tsegi = segment_t(ptB,pti);\n\t\t\tlen = bg::length(segi);\n\t\t\tif(smaller(len, shortest)) {\n\t\t\t\ttrimmed.vector_ = pti - ptB;\n\t\t\t\ttrimmed.edge_ = segi;\n\t\t\t\tshortest = len;\n\t\t\t}\n\t\t}\n\t}\n \treturn trimmed;\n}\n#endif\n\nstd::vector<TranslationVector> findFeasibleTranslationVectors(polygon_t::ring_type& ringA, polygon_t::ring_type& ringB, const std::vector<TouchingPoint>& touchers) \n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\t//use a set to automatically filter duplicate vectors\n\tstd::vector<TranslationVector> potentialVectors;\n\tstd::vector<std::pair<segment_t,segment_t>> touchEdges;\n\n\tfor (psize_t i = 0; i < touchers.size(); i++) {\n\t\tpoint_t& vertexA = ringA[touchers[i].A_];\n\t\tvertexA.marked_ = true;\n\n\t\t// adjacent A vertices\n\t\tsigned long prevAindex = touchers[i].A_ - 1;\n\t\tsigned long nextAindex = touchers[i].A_ + 1;\n\n\t\tprevAindex = (prevAindex < 0) ? ringA.size() - 2 : prevAindex; // loop\n\t\tnextAindex = (static_cast<psize_t>(nextAindex) >= ringA.size()) ? 1 : nextAindex; // loop\n\n\t\tpoint_t& prevA = ringA[prevAindex];\n\t\tpoint_t& nextA = ringA[nextAindex];\n\n\t\t// adjacent B vertices\n\t\tpoint_t& vertexB = ringB[touchers[i].B_];\n\n\t\tsigned long prevBindex = touchers[i].B_ - 1;\n\t\tsigned long nextBindex = touchers[i].B_ + 1;\n\n\t\tprevBindex = (prevBindex < 0) ? ringB.size() - 2 : prevBindex; // loop\n\t\tnextBindex = (static_cast<psize_t>(nextBindex) >= ringB.size()) ? 1 : nextBindex; // loop\n\n\t\tpoint_t& prevB = ringB[prevBindex];\n\t\tpoint_t& nextB = ringB[nextBindex];\n\n\t\tif (touchers[i].type_ == TouchingPoint::VERTEX) {\n\t\t\tsegment_t a1 = { vertexA, nextA };\n\t\t\tsegment_t a2 = { vertexA, prevA };\n\t\t\tsegment_t b1 = { vertexB, nextB };\n\t\t\tsegment_t b2 = { vertexB, prevB };\n\n\t\t\t//swap the segment elements so that always the first point is the touching point\n\t\t\t//also make the second segment always a segment of ringB\n\t\t\ttouchEdges.push_back({a1, b1});\n\t\t\ttouchEdges.push_back({a1, b2});\n\t\t\ttouchEdges.push_back({a2, b1});\n\t\t\ttouchEdges.push_back({a2, b2});\n#ifdef NFP_DEBUG\n\t\t\twrite_svg(\"touchersV\" + std::to_string(i) + \".svg\", {a1,a2,b1,b2});\n#endif\n\n\t\t\t//TODO test parallel edges for floating point stability\n\t\t\tAlignment al;\n\t\t\t//a1 and b1 meet at start vertex\n\t\t\tal = get_alignment(a1, b1.second);\n\t\t\tif(al == LEFT) {\n\t\t\t\tpotentialVectors.push_back({b1.first - b1.second, b1, false, \"vertex1\"});\n\t\t\t} else if(al == RIGHT) {\n\t\t\t\tpotentialVectors.push_back({a1.second - a1.first, a1, true, \"vertex2\"});\n\t\t\t} else {\n\t\t\t\tpotentialVectors.push_back({a1.second - a1.first, a1, true, \"vertex3\"});\n\t\t\t}\n\n\t\t\t//a1 and b2 meet at start and end\n\t\t\tal = get_alignment(a1, b2.second);\n\t\t\tif(al == LEFT) {\n\t\t\t\t//no feasible translation\n\t\t\t} else if(al == RIGHT) {\n\t\t\t\tpotentialVectors.push_back({a1.second - a1.first, a1, true, \"vertex4\"});\n\t\t\t} else {\n\t\t\t\tpotentialVectors.push_back({a1.second - a1.first, a1, true, \"vertex5\"});\n\t\t\t}\n\n\t\t\t//a2 and b1 meet at end and start\n\t\t\tal = get_alignment(a2, b1.second);\n\t\t\tif(al == LEFT) {\n\t\t\t\t//no feasible translation\n\t\t\t} else if(al == RIGHT) {\n\t\t\t\tpotentialVectors.push_back({b1.first - b1.second, b1, false, \"vertex6\"});\n\t\t\t} else {\n\t\t\t\tpotentialVectors.push_back({b1.first - b1.second, b1, false, \"vertex7\"});\n\t\t\t}\n\t\t} else if (touchers[i].type_ == TouchingPoint::B_ON_A) {\n\t\t\tsegment_t a1 = {vertexB, vertexA};\n\t\t\tsegment_t a2 = {vertexB, prevA};\n\t\t\tsegment_t b1 = {vertexB, prevB};\n\t\t\tsegment_t b2 = {vertexB, nextB};\n\n\t\t\ttouchEdges.push_back({a1, b1});\n\t\t\ttouchEdges.push_back({a1, b2});\n\t\t\ttouchEdges.push_back({a2, b1});\n\t\t\ttouchEdges.push_back({a2, b2});\n#ifdef NFP_DEBUG\n\t\t\twrite_svg(\"touchersB\" + std::to_string(i) + \".svg\", {a1,a2,b1,b2});\n#endif\n\t\t\tpotentialVectors.push_back({vertexA - vertexB, {vertexB, vertexA}, true, \"bona\"});\n\t\t} else if (touchers[i].type_ == TouchingPoint::A_ON_B) {\n\t\t\t//TODO testme\n\t\t\tsegment_t a1 = {vertexA, prevA};\n\t\t\tsegment_t a2 = {vertexA, nextA};\n\t\t\tsegment_t b1 = {vertexA, vertexB};\n\t\t\tsegment_t b2 = {vertexA, prevB};\n#ifdef NFP_DEBUG\n\t\t\twrite_svg(\"touchersA\" + std::to_string(i) + \".svg\", {a1,a2,b1,b2});\n#endif\n\t\t\ttouchEdges.push_back({a1, b1});\n\t\t\ttouchEdges.push_back({a2, b1});\n\t\t\ttouchEdges.push_back({a1, b2});\n\t\t\ttouchEdges.push_back({a2, b2});\n\t\t\tpotentialVectors.push_back({vertexA - vertexB, {vertexA, vertexB}, false, \"aonb\"});\n\t\t}\n\t}\n\n\t//discard immediately intersecting translations\n\tstd::vector<TranslationVector> vectors;\n\tfor(const auto& v : potentialVectors) {\n\t\tbool discarded = false;\n\t\tfor(const auto& sp : touchEdges) {\n\t\t\tpoint_t normEdge = normalize(v.edge_.second - v.edge_.first);\n\t\t\tpoint_t normFirst = normalize(sp.first.second - sp.first.first);\n\t\t\tpoint_t normSecond = normalize(sp.second.second - sp.second.first);\n\n\t\t\tAlignment a1 = get_alignment({{0,0},normEdge}, normFirst);\n\t\t\tAlignment a2 = get_alignment({{0,0},normEdge}, normSecond);\n\n\t\t\tif(a1 == a2 && a1 != ON) {\n\t\t\t\tlong double df = get_inner_angle({0,0},normEdge, normFirst);\n\t\t\t\tlong double ds = get_inner_angle({0,0},normEdge, normSecond);\n\n\t\t\t\tpoint_t normIn = normalize(v.edge_.second - v.edge_.first);\n\t\t\t\tif (equals(df, ds)) {\n\t\t\t\t\tTranslationVector trimmed = trimVector(ringA,ringB, v);\n\t\t\t\t\tpolygon_t::ring_type translated;\n\t\t\t\t\ttrans::translate_transformer<coord_t, 2, 2> translate(trimmed.vector_.x_,\ttrimmed.vector_.y_);\n\t\t\t\t\tboost::geometry::transform(ringB, translated, translate);\n\t\t\t\t\tif (!(bg::intersects(translated, ringA) && !bg::overlaps(translated, ringA) && !bg::covered_by(translated, ringA) && !bg::covered_by(ringA, translated))) {\n\t\t\t\t\t\tdiscarded = true;\n\t\t\t\t\t\tstd::cerr << \"discarded\" << std::endl;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\n\t\t\t\t\tif (normIn == normalize(v.vector_)) {\n\t\t\t\t\t\tif (larger(ds, df)) {\n\t\t\t\t\t\t\tdiscarded = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (smaller(ds, df)) {\n\t\t\t\t\t\t\tdiscarded = true;\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}\n\t\t\t}\n\t\t}\n\t\tif(!discarded)\n\t\t\tvectors.push_back(v);\n\t}\n\treturn vectors;\n}\n#endif\n\nbool find(const std::vector<TranslationVector>& h, const TranslationVector& tv)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tfor(const auto& htv : h) {\n\t\tif(htv.edge_ == tv.edge_)\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n#endif\n\nTranslationVector getLongest(const std::vector<TranslationVector>& tvs)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tcoord_t len;\n\tcoord_t maxLen = MIN_COORD;\n\tTranslationVector longest;\n\tlongest.vector_ = INVALID_POINT;\n\n\tfor(auto& tv : tvs) {\n\t\tlen = bg::length(segment_t{{0,0},tv.vector_});\n\t\tif(larger(len, maxLen)) {\n\t\t\tmaxLen = len;\n\t\t\tlongest = tv;\n\t\t}\n\t}\n\treturn longest;\n}\n#endif\n\nTranslationVector selectNextTranslationVector(const polygon_t& pA, const polygon_t::ring_type& rA,\tconst polygon_t::ring_type& rB, const std::vector<TranslationVector>& tvs, const std::vector<TranslationVector>& history)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tif(!history.empty()) {\n\t\tTranslationVector last = history.back();\n\t\tstd::vector<TranslationVector> historyCopy = history;\n\t\tif(historyCopy.size() >= 2) {\n\t\t\thistoryCopy.erase(historyCopy.end() - 1);\n\t\t\thistoryCopy.erase(historyCopy.end() - 1);\n\t\t\tif(historyCopy.size() > 4) {\n\t\t\t\thistoryCopy.erase(historyCopy.begin(), historyCopy.end() - 4);\n\t\t\t}\n\n\t\t} else {\n\t\t\thistoryCopy.clear();\n\t\t}\n\t\tDEBUG_MSG(\"last\", last);\n\n\t\tpsize_t laterI = std::numeric_limits<psize_t>::max();\n\t\tpoint_t previous = rA[0];\n\t\tpoint_t next;\n\n\t\tif(last.fromA_) {\n\t\t\tfor (psize_t i = 1; i < rA.size() + 1; ++i) {\n\t\t\t\tif (i >= rA.size())\n\t\t\t\t\tnext = rA[i % rA.size() + 1];\n\t\t\t\telse\n\t\t\t\t\tnext = rA[i];\n\n\t\t\t\tsegment_t candidate( previous, next );\n\t\t\t\tif(candidate == last.edge_) {\n\t\t\t\t\tlaterI = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tprevious = next;\n\t\t\t}\n\n\t\t\tif (laterI == std::numeric_limits<psize_t>::max()) {\n\t\t\t\tpoint_t later;\n\t\t\t\tif (last.vector_ == (last.edge_.second - last.edge_.first)) {\n\t\t\t\t\tlater = last.edge_.second;\n\t\t\t\t} else {\n\t\t\t\t\tlater = last.edge_.first;\n\t\t\t\t}\n\n\t\t\t\tlaterI = find_point(rA, later);\n\t\t\t}\n\t\t} else {\n\t\t\tpoint_t later;\n\t\t\tif (last.vector_ == (last.edge_.second - last.edge_.first)) {\n\t\t\t\tlater = last.edge_.second;\n\t\t\t} else {\n\t\t\t\tlater = last.edge_.first;\n\t\t\t}\n\n\t\t\tlaterI = find_point(rA, later);\n\t\t}\n\n\t\tif (laterI == std::numeric_limits<psize_t>::max()) {\n\t\t\tthrow std::runtime_error(\n\t\t\t\t\t\"Internal error: Can't find later point of last edge\");\n\t\t}\n\n\t\tstd::vector<segment_t> viableEdges;\n\t\tprevious = rA[laterI];\n\t\tfor(psize_t i = laterI + 1; i < rA.size() + laterI + 1; ++i) {\n\t\t\tif(i >= rA.size())\n\t\t\t\tnext = rA[i % rA.size() + 1];\n\t\t\telse\n\t\t\t\tnext = rA[i];\n\n\t\t\tviableEdges.push_back({previous, next});\n\t\t\tprevious = next;\n\t\t}\n\n//\t\tauto rng = std::default_random_engine {};\n//\t\tstd::shuffle(std::begin(viableEdges), std::end(viableEdges), rng);\n\n\t\t//search with consulting the history to prevent oscillation\n\t\tstd::vector<TranslationVector> viableTrans;\n\t\tfor(const auto& ve: viableEdges) {\n\t\t\tfor(const auto& tv : tvs) {\n\t\t\t\tif((tv.fromA_ && (normalize(tv.vector_) == normalize(ve.second - ve.first))) && (tv.edge_.first != last.edge_.first || tv.edge_.second != last.edge_.second) && !find(historyCopy, tv)) {\n\t\t\t\t\tviableTrans.push_back(tv);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const auto& tv : tvs) {\n\t\t\t\tif (!tv.fromA_) {\n\t\t\t\t\tpoint_t later;\n\t\t\t\t\tif (tv.vector_ == (tv.edge_.second - tv.edge_.first) && (tv.edge_.first != last.edge_.first || tv.edge_.second != last.edge_.second)) {\n\t\t\t\t\t\tlater = tv.edge_.second;\n\t\t\t\t\t} else if (tv.vector_ == (tv.edge_.first - tv.edge_.second)) {\n\t\t\t\t\t\tlater = tv.edge_.first;\n\t\t\t\t\t} else\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tif (later == ve.first || later == ve.second) {\n\t\t\t\t\t\tviableTrans.push_back(tv);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif(!viableTrans.empty())\n\t\t\treturn getLongest(viableTrans);\n\n\t\t//search again without the history\n\t\tfor(const auto& ve: viableEdges) {\n\t\t\tfor(const auto& tv : tvs) {\n\t\t\t\tif((tv.fromA_ && (normalize(tv.vector_) == normalize(ve.second - ve.first))) && (tv.edge_.first != last.edge_.first || tv.edge_.second != last.edge_.second)) {\n\t\t\t\t\tviableTrans.push_back(tv);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const auto& tv : tvs) {\n\t\t\t\tif (!tv.fromA_) {\n\t\t\t\t\tpoint_t later;\n\t\t\t\t\tif (tv.vector_ == (tv.edge_.second - tv.edge_.first) && (tv.edge_.first != last.edge_.first || tv.edge_.second != last.edge_.second)) {\n\t\t\t\t\t\tlater = tv.edge_.second;\n\t\t\t\t\t} else if (tv.vector_ == (tv.edge_.first - tv.edge_.second)) {\n\t\t\t\t\t\tlater = tv.edge_.first;\n\t\t\t\t\t} else\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tif (later == ve.first || later == ve.second) {\n\t\t\t\t\t\tviableTrans.push_back(tv);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(!viableTrans.empty())\n\t\t\treturn getLongest(viableTrans);\n\n\t\t/*\n\t\t//search again without the history and without checking last edge\n\t\tfor(const auto& ve: viableEdges) {\n\t\t\tfor(const auto& tv : tvs) {\n\t\t\t\tif((tv.fromA_ && (normalize(tv.vector_) == normalize(ve.second - ve.first)))) {\n\t\t\t\t\treturn tv;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const auto& tv : tvs) {\n\t\t\t\tif (!tv.fromA_) {\n\t\t\t\t\tpoint_t later;\n\t\t\t\t\tif (tv.vector_ == (tv.edge_.second - tv.edge_.first)) {\n\t\t\t\t\t\tlater = tv.edge_.second;\n\t\t\t\t\t} else if (tv.vector_ == (tv.edge_.first - tv.edge_.second)) {\n\t\t\t\t\t\tlater = tv.edge_.first;\n\t\t\t\t\t} else\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tif (later == ve.first || later == ve.second) {\n\t\t\t\t\t\treturn tv;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}*/\n\n\t\tif(tvs.size() == 1)\n\t\t\treturn *tvs.begin();\n\n\t\tTranslationVector tv;\n\t\ttv.vector_ = INVALID_POINT;\n\t\treturn tv;\n\t} else {\n\t\treturn getLongest(tvs);\n\t}\n}\n#endif\n\nbool inNfp(const point_t& pt, const nfp_t& nfp)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tfor(const auto& r : nfp) {\n\t\tif(bg::touches(pt, r))\n\t\t\treturn true;\n\t}\n\n\treturn false;\n}\n#endif\n\nenum SearchStartResult {\n\tFIT,\n\tFOUND,\n\tNOT_FOUND\n};\n\nSearchStartResult searchStartTranslation(polygon_t::ring_type& rA, const polygon_t::ring_type& rB, const nfp_t& nfp,const bool& inside, point_t& result)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tfor(psize_t i = 0; i < rA.size() - 1; i++) {\n\t\tpsize_t index;\n\t\tif (i >= rA.size())\n\t\t\tindex = i % rA.size() + 1;\n\t\telse\n\t\t\tindex = i;\n\n\t\tauto& ptA = rA[index];\n\n\t\tif(ptA.marked_)\n\t\t\tcontinue;\n\n\t\tptA.marked_ = true;\n\n\t\tfor(const auto& ptB: rB) {\n\t\t\tpoint_t testTranslation = ptA - ptB;\n\t\t\tpolygon_t::ring_type translated;\n\t\t\tboost::geometry::transform(rB, translated, trans::translate_transformer<coord_t, 2, 2>(testTranslation.x_, testTranslation.y_));\n\n\t\t\t//check if the translated rB is identical to rA\n\t\t\tbool identical = false;\n\t\t\tfor(const auto& ptT: translated) {\n\t\t\t\tidentical = false;\n\t\t\t\tfor(const auto& ptA: rA) {\n\t\t\t\t\tif(ptT == ptA) {\n\t\t\t\t\t\tidentical = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(!identical)\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif(identical) {\n\t\t\t\tresult = testTranslation;\n\t\t\t\treturn FIT;\n\t\t\t}\n\n\t\t\tbool bInside = false;\n\t\t\tfor(const auto& ptT: translated) {\n\t\t\t\tif(bg::within(ptT, rA)) {\n\t\t\t\t\tbInside = true;\n\t\t\t\t\tbreak;\n\t\t\t\t} else if(!bg::touches(ptT, rA)) {\n\t\t\t\t\tbInside = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(((bInside && inside) || (!bInside && !inside)) && (!bg::overlaps(translated, rA) && !bg::covered_by(translated, rA) && !bg::covered_by(rA, translated)) && !inNfp(translated.front(), nfp)){\n\t\t\t\tresult = testTranslation;\n\t\t\t\treturn FOUND;\n\t\t\t}\n\n\t\t\tpoint_t nextPtA = rA[index + 1];\n\t\t\tTranslationVector slideVector;\n\t\t\tslideVector.vector_ = nextPtA - ptA;\n\t\t\tslideVector.edge_ = {ptA, nextPtA};\n\t\t\tslideVector.fromA_ = true;\n\t\t\tTranslationVector trimmed = trimVector(rA, translated, slideVector);\n\t\t\tpolygon_t::ring_type translated2;\n\t\t\ttrans::translate_transformer<coord_t, 2, 2> trans(trimmed.vector_.x_, trimmed.vector_.y_);\n\t\t\tboost::geometry::transform(translated, translated2, trans);\n\n\t\t\t//check if the translated rB is identical to rA\n\t\t\tidentical = false;\n\t\t\tfor(const auto& ptT: translated) {\n\t\t\t\tidentical = false;\n\t\t\t\tfor(const auto& ptA: rA) {\n\t\t\t\t\tif(ptT == ptA) {\n\t\t\t\t\t\tidentical = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(!identical)\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif(identical) {\n\t\t\t\tresult = trimmed.vector_ + testTranslation;\n\t\t\t\treturn FIT;\n\t\t\t}\n\n\t\t\tbInside = false;\n\t\t\tfor(const auto& ptT: translated2) {\n\t\t\t\tif(bg::within(ptT, rA)) {\n\t\t\t\t\tbInside = true;\n\t\t\t\t\tbreak;\n\t\t\t\t} else if(!bg::touches(ptT, rA)) {\n\t\t\t\t\tbInside = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(((bInside && inside) || (!bInside && !inside)) && (!bg::overlaps(translated2, rA) && !bg::covered_by(translated2, rA) && !bg::covered_by(rA, translated2)) && !inNfp(translated2.front(), nfp)){\n\t\t\t\tresult = trimmed.vector_ + testTranslation;\n\t\t\t\treturn FOUND;\n\t\t\t}\n\t\t}\n\t}\n\treturn NOT_FOUND;\n}\n#endif\n\nenum SlideResult {\n\tLOOP,\n\tNO_LOOP,\n\tNO_TRANSLATION\n};\n\nSlideResult slide(polygon_t& pA, polygon_t::ring_type& rA, polygon_t::ring_type& rB, nfp_t& nfp, const point_t& transB, bool inside)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tpolygon_t::ring_type rifsB;\n\tboost::geometry::transform(rB, rifsB, trans::translate_transformer<coord_t, 2, 2>(transB.x_, transB.y_));\n\trB = std::move(rifsB);\n\n#ifdef NFP_DEBUG\n\twrite_svg(\"ifs.svg\", pA, rB);\n#endif\n\n\tbool startAvailable = true;\n\tpsize_t cnt = 0;\n\tpoint_t referenceStart = rB.front();\n\tstd::vector<TranslationVector> history;\n\n\t//generate the nfp for the ring\n\twhile(startAvailable) {\n\t\tDEBUG_VAL(cnt);\n\t\t//use first point of rB as reference\n\t\tnfp.back().push_back(rB.front());\n\t\tif(cnt == 15)\n\t\t\tstd::cerr << \"\";\n\n\t\tstd::vector<TouchingPoint> touchers = findTouchingPoints(rA, rB);\n\n#ifdef NFP_DEBUG\n\t\tDEBUG_MSG(\"touchers\", touchers.size());\n\t\tfor(auto t : touchers) {\n\t\t\tDEBUG_VAL(t.type_);\n\t\t}\n#endif\n\t\tif(touchers.empty()) {\n\t\t\tthrow std::runtime_error(\"Internal error: No touching points found\");\n\t\t}\n\t\tstd::vector<TranslationVector> transVectors = findFeasibleTranslationVectors(rA, rB, touchers);\n\n#ifdef NFP_DEBUG\n\t\tDEBUG_MSG(\"collected vectors\", transVectors.size());\n\t\tfor(auto pt : transVectors) {\n\t\t\tDEBUG_VAL(pt);\n\t\t}\n#endif\n\n\t\tif(transVectors.empty()) {\n\t\t\treturn NO_LOOP;\n\t\t}\n\n\t\tTranslationVector next = selectNextTranslationVector(pA, rA, rB, transVectors, history);\n\n\t\tif(next.vector_ == INVALID_POINT)\n\t\t\treturn NO_TRANSLATION;\n\n\t\tDEBUG_MSG(\"next\", next);\n\n\t\tTranslationVector trimmed = trimVector(rA, rB, next);\n\t\tDEBUG_MSG(\"trimmed\", trimmed);\n\n\t\thistory.push_back(next);\n\n\t\tpolygon_t::ring_type nextRB;\n\t\tboost::geometry::transform(rB, nextRB, trans::translate_transformer<coord_t, 2, 2>(trimmed.vector_.x_, trimmed.vector_.y_));\n\t\trB = std::move(nextRB);\n\n#ifdef NFP_DEBUG\n\t\twrite_svg(\"next\" + std::to_string(cnt) + \".svg\", pA,rB);\n#endif\n\n\t\t++cnt;\n\t\tif(referenceStart == rB.front() || (inside && bg::touches(rB.front(), nfp.front()))) {\n\t\t\tstartAvailable = false;\n\t\t}\n\t}\n\treturn LOOP;\n}\n#endif\n\nvoid removeCoLinear(polygon_t::ring_type& r)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tassert(r.size() > 2);\n\tpsize_t nextI;\n\tpsize_t prevI = 0;\n\tsegment_t segment(r[r.size() - 2], r[0]);\n\tpolygon_t::ring_type newR;\n\n\tfor (psize_t i = 1; i < r.size() + 1; ++i) {\n\t\tif (i >= r.size())\n\t\t\tnextI = i % r.size() + 1;\n\t\telse\n\t\t\tnextI = i;\n\n\t\tif (get_alignment(segment, r[nextI]) != ON) {\n\t\t\tnewR.push_back(r[prevI]);\n\t\t}\n\t\tsegment = {segment.second, r[nextI]};\n\t\tprevI = nextI;\n\t}\n\n\tr = newR;\n}\n#endif\n\nvoid removeCoLinear(polygon_t& p)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tremoveCoLinear(p.outer());\n\tfor (auto& r : p.inners())\n\t\tremoveCoLinear(r);\n}\n#endif\n\nnfp_t generateNFP(polygon_t& pA, polygon_t& pB, const bool checkValidity = true)\n#ifndef LIBNFP_PROTOTYPES_IMPLEMENTATION\n;\n#else\n{\n\tremoveCoLinear(pA);\n\tremoveCoLinear(pB);\n\n\tif(checkValidity)  {\n\t\tstd::string reason;\n\t\tif(!bg::is_valid(pA, reason))\n\t\t\tthrow std::runtime_error(\"Polygon A is invalid: \" + reason);\n\n\t\tif(!bg::is_valid(pB, reason))\n\t\t\tthrow std::runtime_error(\"Polygon B is invalid: \" + reason);\n\t}\n\n\tnfp_t nfp;\n\n#ifdef NFP_DEBUG\n\twrite_svg(\"start.svg\", {pA, pB});\n#endif\n\n\tDEBUG_VAL(bg::wkt(pA))\n\tDEBUG_VAL(bg::wkt(pB));\n\n\t//prevent double vertex connections at start because we might come back the same way we go which would end the nfp prematurely\n\tstd::vector<psize_t> ptyaminI = find_minimum_y(pA);\n\tstd::vector<psize_t> ptybmaxI = find_maximum_y(pB);\n\n\tpoint_t pAstart;\n\tpoint_t pBstart;\n\n\tif(ptyaminI.size() > 1 || ptybmaxI.size() > 1) {\n\t\t//find right-most of A and left-most of B to prevent double connection at start\n\t\tcoord_t maxX = MIN_COORD;\n\t\tpsize_t iRightMost = 0;\n\t\tfor(psize_t& ia : ptyaminI) {\n\t\t\tconst point_t& candidateA = pA.outer()[ia];\n\t\t\tif(larger(candidateA.x_, maxX)) {\n\t\t\t\tmaxX = candidateA.x_;\n\t\t\t\tiRightMost = ia;\n\t\t\t}\n\t\t}\n\n\t\tcoord_t minX = MAX_COORD;\n\t\tpsize_t iLeftMost = 0;\n\t\tfor(psize_t& ib : ptybmaxI) {\n\t\t\tconst point_t& candidateB = pB.outer()[ib];\n\t\t\tif(smaller(candidateB.x_, minX)) {\n\t\t\t\tminX = candidateB.x_;\n\t\t\t\tiLeftMost = ib;\n\t\t\t}\n\t\t}\n\t\tpAstart = pA.outer()[iRightMost];\n\t\tpBstart = pB.outer()[iLeftMost];\n\t} else {\n\t\tpAstart = pA.outer()[ptyaminI.front()];\n\t\tpBstart = pB.outer()[ptybmaxI.front()];\n\t}\n\n\tnfp.push_back({});\n\tpoint_t transB = {pAstart - pBstart};\n\n\tif(slide(pA, pA.outer(), pB.outer(), nfp, transB, false) != LOOP) {\n\t\t\tthrow std::runtime_error(\"Unable to complete outer nfp loop\");\n\t}\n\n\tDEBUG_VAL(\"##### outer #####\");\n\tpoint_t startTrans;\n  while(true) {\n  \tSearchStartResult res = searchStartTranslation(pA.outer(), pB.outer(), nfp, false, startTrans);\n  \tif(res == FOUND) {\n\t\t\tnfp.push_back({});\n\t\t\tDEBUG_VAL(\"##### interlock start #####\")\n\t\t\tpolygon_t::ring_type rifsB;\n\t\t\tboost::geometry::transform(pB.outer(), rifsB, trans::translate_transformer<coord_t, 2, 2>(startTrans.x_, startTrans.y_));\n\t\t\tif(inNfp(rifsB.front(), nfp)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tSlideResult sres = slide(pA, pA.outer(), pB.outer(), nfp, startTrans, true);\n\t\t\tif(sres != LOOP) {\n\t\t\t\tif(sres == NO_TRANSLATION) {\n\t\t\t\t\t//no initial slide found -> jiggsaw\n\t\t\t\t\tif(!inNfp(pB.outer().front(),nfp)) {\n\t\t\t\t\t\tnfp.push_back({});\n\t\t\t\t\t\tnfp.back().push_back(pB.outer().front());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tDEBUG_VAL(\"##### interlock end #####\");\n  \t} else if(res == FIT) {\n  \t\tpoint_t reference = pB.outer().front();\n  \t\tpoint_t translated;\n\t\t\ttrans::translate_transformer<coord_t, 2, 2> translate(startTrans.x_, startTrans.y_);\n\t\t\tboost::geometry::transform(reference, translated, translate);\n\t\t\tif(!inNfp(translated,nfp)) {\n\t\t\t\tnfp.push_back({});\n\t\t\t\tnfp.back().push_back(translated);\n\t\t\t}\n\t\t\tbreak;\n  \t} else\n  \t\tbreak;\n\t}\n\n\n\tfor(auto& rA : pA.inners()) {\n\t\twhile(true) {\n\t\t\tSearchStartResult res = searchStartTranslation(rA, pB.outer(), nfp, true, startTrans);\n\t\t\tif(res == FOUND) {\n\t\t\t\tnfp.push_back({});\n\t\t\t\tDEBUG_VAL(\"##### hole start #####\");\n\t\t\t\tslide(pA, rA, pB.outer(), nfp, startTrans, true);\n\t\t\t\tDEBUG_VAL(\"##### hole end #####\");\n\t\t\t} else if(res == FIT) {\n\t  \t\tpoint_t reference = pB.outer().front();\n\t  \t\tpoint_t translated;\n\t\t\t\ttrans::translate_transformer<coord_t, 2, 2> translate(startTrans.x_, startTrans.y_);\n\t\t\t\tboost::geometry::transform(reference, translated, translate);\n\t\t\t\tif(!inNfp(translated,nfp)) {\n\t\t\t\t\tnfp.push_back({});\n\t\t\t\t\tnfp.back().push_back(translated);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t} else\n\t\t\t\tbreak;\n\t\t}\n  }\n\n#ifdef NFP_DEBUG\n  write_svg(\"nfp.svg\", {pA,pB}, nfp);\n#endif\n\n  return nfp;\n}\n#endif\n\n}\n\n\n#endif\n", "meta": {"hexsha": "ed9d942d943b7d4b4b8ac65c1c3e9693ee2f969e", "size": 44705, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libnfporb/libnfp.hpp", "max_stars_repo_name": "martinhansdk/Flatpack", "max_stars_repo_head_hexsha": "297386ab53d8ff8462b6978d2144770afdddfdea", "max_stars_repo_licenses": ["BSL-1.0", "MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-04-24T22:38:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-19T02:00:06.000Z", "max_issues_repo_path": "libnfporb/libnfp.hpp", "max_issues_repo_name": "martinhansdk/Flatpack", "max_issues_repo_head_hexsha": "297386ab53d8ff8462b6978d2144770afdddfdea", "max_issues_repo_licenses": ["BSL-1.0", "MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-11T12:08:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-11T12:08:40.000Z", "max_forks_repo_path": "libnfporb/libnfp.hpp", "max_forks_repo_name": "martinhansdk/Flatpack", "max_forks_repo_head_hexsha": "297386ab53d8ff8462b6978d2144770afdddfdea", "max_forks_repo_licenses": ["BSL-1.0", "MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-03-31T00:33:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T12:55:30.000Z", "avg_line_length": 25.7814302191, "max_line_length": 220, "alphanum_fraction": 0.6726540655, "num_tokens": 13227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.25729124801816966}}
{"text": "// Boost.Geometry Index\r\n//\r\n// R-tree R*-tree split algorithm implementation\r\n//\r\n// Copyright (c) 2011-2013 Adam Wulkiewicz, Lodz, Poland.\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_INDEX_DETAIL_RTREE_RSTAR_REDISTRIBUTE_ELEMENTS_HPP\r\n#define BOOST_GEOMETRY_INDEX_DETAIL_RTREE_RSTAR_REDISTRIBUTE_ELEMENTS_HPP\r\n\r\n#include <boost/geometry/index/detail/algorithms/intersection_content.hpp>\r\n#include <boost/geometry/index/detail/algorithms/union_content.hpp>\r\n#include <boost/geometry/index/detail/algorithms/margin.hpp>\r\n\r\n#include <boost/geometry/index/detail/rtree/node/node.hpp>\r\n#include <boost/geometry/index/detail/rtree/visitors/insert.hpp>\r\n#include <boost/geometry/index/detail/rtree/visitors/is_leaf.hpp>\r\n\r\nnamespace boost { namespace geometry { namespace index {\r\n\r\nnamespace detail { namespace rtree {\r\n\r\nnamespace rstar {\r\n\r\ntemplate <typename Element, typename Translator, typename Tag, size_t Corner, size_t AxisIndex>\r\nclass element_axis_corner_less\r\n{\r\n    BOOST_MPL_ASSERT_MSG(false, NOT_IMPLEMENTED_FOR_THIS_TAG, (Tag));\r\n};\r\n\r\ntemplate <typename Element, typename Translator, size_t Corner, size_t AxisIndex>\r\nclass element_axis_corner_less<Element, Translator, box_tag, Corner, AxisIndex>\r\n{\r\npublic:\r\n    element_axis_corner_less(Translator const& tr)\r\n        : m_tr(tr)\r\n    {}\r\n\r\n    bool operator()(Element const& e1, Element const& e2) const\r\n    {\r\n        return geometry::get<Corner, AxisIndex>(rtree::element_indexable(e1, m_tr))\r\n            < geometry::get<Corner, AxisIndex>(rtree::element_indexable(e2, m_tr));\r\n    }\r\n\r\nprivate:\r\n    Translator const& m_tr;\r\n};\r\n\r\ntemplate <typename Element, typename Translator, size_t Corner, size_t AxisIndex>\r\nclass element_axis_corner_less<Element, Translator, point_tag, Corner, AxisIndex>\r\n{\r\npublic:\r\n    element_axis_corner_less(Translator const& tr)\r\n        : m_tr(tr)\r\n    {}\r\n\r\n    bool operator()(Element const& e1, Element const& e2) const\r\n    {\r\n        return geometry::get<AxisIndex>(rtree::element_indexable(e1, m_tr))\r\n            < geometry::get<AxisIndex>(rtree::element_indexable(e2, m_tr));\r\n    }\r\n\r\nprivate:\r\n    Translator const& m_tr;\r\n};\r\n\r\ntemplate <typename Parameters, typename Box, size_t Corner, size_t AxisIndex>\r\nstruct choose_split_axis_and_index_for_corner\r\n{\r\n    typedef typename index::detail::default_margin_result<Box>::type margin_type;\r\n    typedef typename index::detail::default_content_result<Box>::type content_type;\r\n\r\n    template <typename Elements, typename Translator>\r\n    static inline void apply(Elements const& elements,\r\n                             size_t & choosen_index,\r\n                             margin_type & sum_of_margins,\r\n                             content_type & smallest_overlap,\r\n                             content_type & smallest_content,\r\n                             Parameters const& parameters,\r\n                             Translator const& translator)\r\n    {\r\n        typedef typename Elements::value_type element_type;\r\n        typedef typename rtree::element_indexable_type<element_type, Translator>::type indexable_type;\r\n        typedef typename tag<indexable_type>::type indexable_tag;\r\n\r\n        BOOST_GEOMETRY_INDEX_ASSERT(elements.size() == parameters.get_max_elements() + 1, \"wrong number of elements\");\r\n\r\n        // copy elements\r\n        Elements elements_copy(elements);                                                                       // MAY THROW, STRONG (alloc, copy)\r\n        \r\n        // sort elements\r\n        element_axis_corner_less<element_type, Translator, indexable_tag, Corner, AxisIndex> elements_less(translator);\r\n        std::sort(elements_copy.begin(), elements_copy.end(), elements_less);                                   // MAY THROW, BASIC (copy)\r\n\r\n        // init outputs\r\n        choosen_index = parameters.get_min_elements();\r\n        sum_of_margins = 0;\r\n        smallest_overlap = (std::numeric_limits<content_type>::max)();\r\n        smallest_content = (std::numeric_limits<content_type>::max)();\r\n\r\n        // calculate sum of margins for all distributions\r\n        size_t index_last = parameters.get_max_elements() - parameters.get_min_elements() + 2;\r\n        for ( size_t i = parameters.get_min_elements() ; i < index_last ; ++i )\r\n        {\r\n            // TODO - awulkiew: may be optimized - box of group 1 may be initialized with\r\n            // box of min_elems number of elements and expanded for each iteration by another element\r\n\r\n            Box box1 = rtree::elements_box<Box>(elements_copy.begin(), elements_copy.begin() + i, translator);\r\n            Box box2 = rtree::elements_box<Box>(elements_copy.begin() + i, elements_copy.end(), translator);\r\n            \r\n            sum_of_margins += index::detail::comparable_margin(box1) + index::detail::comparable_margin(box2);\r\n\r\n            content_type ovl = index::detail::intersection_content(box1, box2);\r\n            content_type con = index::detail::content(box1) + index::detail::content(box2);\r\n\r\n            // TODO - shouldn't here be < instead of <= ?\r\n            if ( ovl < smallest_overlap || (ovl == smallest_overlap && con <= smallest_content) )\r\n            {\r\n                choosen_index = i;\r\n                smallest_overlap = ovl;\r\n                smallest_content = con;\r\n            }\r\n        }\r\n\r\n        ::boost::ignore_unused_variable_warning(parameters);\r\n    }\r\n};\r\n\r\ntemplate <typename Parameters, typename Box, size_t AxisIndex, typename ElementIndexableTag>\r\nstruct choose_split_axis_and_index_for_axis\r\n{\r\n    BOOST_MPL_ASSERT_MSG(false, NOT_IMPLEMENTED_FOR_THIS_TAG, (ElementIndexableTag));\r\n};\r\n\r\ntemplate <typename Parameters, typename Box, size_t AxisIndex>\r\nstruct choose_split_axis_and_index_for_axis<Parameters, Box, AxisIndex, box_tag>\r\n{\r\n    typedef typename index::detail::default_margin_result<Box>::type margin_type;\r\n    typedef typename index::detail::default_content_result<Box>::type content_type;\r\n\r\n    template <typename Elements, typename Translator>\r\n    static inline void apply(Elements const& elements,\r\n                             size_t & choosen_corner,\r\n                             size_t & choosen_index,\r\n                             margin_type & sum_of_margins,\r\n                             content_type & smallest_overlap,\r\n                             content_type & smallest_content,\r\n                             Parameters const& parameters,\r\n                             Translator const& translator)\r\n    {\r\n        size_t index1 = 0;\r\n        margin_type som1 = 0;\r\n        content_type ovl1 = (std::numeric_limits<content_type>::max)();\r\n        content_type con1 = (std::numeric_limits<content_type>::max)();\r\n\r\n        choose_split_axis_and_index_for_corner<Parameters, Box, min_corner, AxisIndex>::\r\n            apply(elements, index1,\r\n                  som1, ovl1, con1,\r\n                  parameters, translator);                                                                  // MAY THROW, STRONG\r\n\r\n        size_t index2 = 0;\r\n        margin_type som2 = 0;\r\n        content_type ovl2 = (std::numeric_limits<content_type>::max)();\r\n        content_type con2 = (std::numeric_limits<content_type>::max)();\r\n\r\n        choose_split_axis_and_index_for_corner<Parameters, Box, max_corner, AxisIndex>::\r\n            apply(elements, index2,\r\n                  som2, ovl2, con2,\r\n                  parameters, translator);                                                                  // MAY THROW, STRONG\r\n\r\n        sum_of_margins = som1 + som2;\r\n\r\n        if ( ovl1 < ovl2 || (ovl1 == ovl2 && con1 <= con2) )\r\n        {\r\n            choosen_corner = min_corner;\r\n            choosen_index = index1;\r\n            smallest_overlap = ovl1;\r\n            smallest_content = con1;\r\n        }\r\n        else\r\n        {\r\n            choosen_corner = max_corner;\r\n            choosen_index = index2;\r\n            smallest_overlap = ovl2;\r\n            smallest_content = con2;\r\n        }\r\n    }\r\n};\r\n\r\ntemplate <typename Parameters, typename Box, size_t AxisIndex>\r\nstruct choose_split_axis_and_index_for_axis<Parameters, Box, AxisIndex, point_tag>\r\n{\r\n    typedef typename index::detail::default_margin_result<Box>::type margin_type;\r\n    typedef typename index::detail::default_content_result<Box>::type content_type;\r\n\r\n    template <typename Elements, typename Translator>\r\n    static inline void apply(Elements const& elements,\r\n                             size_t & choosen_corner,\r\n                             size_t & choosen_index,\r\n                             margin_type & sum_of_margins,\r\n                             content_type & smallest_overlap,\r\n                             content_type & smallest_content,\r\n                             Parameters const& parameters,\r\n                             Translator const& translator)\r\n    {\r\n        choose_split_axis_and_index_for_corner<Parameters, Box, min_corner, AxisIndex>::\r\n            apply(elements, choosen_index,\r\n                  sum_of_margins, smallest_overlap, smallest_content,\r\n                  parameters, translator);                                                                  // MAY THROW, STRONG\r\n\r\n        choosen_corner = min_corner;\r\n    }\r\n};\r\n\r\ntemplate <typename Parameters, typename Box, size_t Dimension>\r\nstruct choose_split_axis_and_index\r\n{\r\n    BOOST_STATIC_ASSERT(0 < Dimension);\r\n\r\n    typedef typename index::detail::default_margin_result<Box>::type margin_type;\r\n    typedef typename index::detail::default_content_result<Box>::type content_type;\r\n\r\n    template <typename Elements, typename Translator>\r\n    static inline void apply(Elements const& elements,\r\n                             size_t & choosen_axis,\r\n                             size_t & choosen_corner,\r\n                             size_t & choosen_index,\r\n                             margin_type & smallest_sum_of_margins,\r\n                             content_type & smallest_overlap,\r\n                             content_type & smallest_content,\r\n                             Parameters const& parameters,\r\n                             Translator const& translator)\r\n    {\r\n        typedef typename rtree::element_indexable_type<typename Elements::value_type, Translator>::type element_indexable_type;\r\n\r\n        choose_split_axis_and_index<Parameters, Box, Dimension - 1>::\r\n            apply(elements, choosen_axis, choosen_corner, choosen_index,\r\n                  smallest_sum_of_margins, smallest_overlap, smallest_content,\r\n                  parameters, translator);                                                                  // MAY THROW, STRONG\r\n\r\n        margin_type sum_of_margins = 0;\r\n\r\n        size_t corner = min_corner;\r\n        size_t index = 0;\r\n\r\n        content_type overlap_val = (std::numeric_limits<content_type>::max)();\r\n        content_type content_val = (std::numeric_limits<content_type>::max)();\r\n\r\n        choose_split_axis_and_index_for_axis<\r\n            Parameters,\r\n            Box,\r\n            Dimension - 1,\r\n            typename tag<element_indexable_type>::type\r\n        >::apply(elements, corner, index, sum_of_margins, overlap_val, content_val, parameters, translator); // MAY THROW, STRONG\r\n\r\n        if ( sum_of_margins < smallest_sum_of_margins )\r\n        {\r\n            choosen_axis = Dimension - 1;\r\n            choosen_corner = corner;\r\n            choosen_index = index;\r\n            smallest_sum_of_margins = sum_of_margins;\r\n            smallest_overlap = overlap_val;\r\n            smallest_content = content_val;\r\n        }\r\n    }\r\n};\r\n\r\ntemplate <typename Parameters, typename Box>\r\nstruct choose_split_axis_and_index<Parameters, Box, 1>\r\n{\r\n    typedef typename index::detail::default_margin_result<Box>::type margin_type;\r\n    typedef typename index::detail::default_content_result<Box>::type content_type;\r\n\r\n    template <typename Elements, typename Translator>\r\n    static inline void apply(Elements const& elements,\r\n                             size_t & choosen_axis,\r\n                             size_t & choosen_corner,\r\n                             size_t & choosen_index,\r\n                             margin_type & smallest_sum_of_margins,\r\n                             content_type & smallest_overlap,\r\n                             content_type & smallest_content,\r\n                             Parameters const& parameters,\r\n                             Translator const& translator)\r\n    {\r\n        typedef typename rtree::element_indexable_type<typename Elements::value_type, Translator>::type element_indexable_type;\r\n\r\n        choosen_axis = 0;\r\n\r\n        choose_split_axis_and_index_for_axis<\r\n            Parameters,\r\n            Box,\r\n            0,\r\n            typename tag<element_indexable_type>::type\r\n        >::apply(elements, choosen_corner, choosen_index, smallest_sum_of_margins, smallest_overlap, smallest_content, parameters, translator); // MAY THROW\r\n    }\r\n};\r\n\r\ntemplate <size_t Corner, size_t Dimension>\r\nstruct partial_sort\r\n{\r\n    BOOST_STATIC_ASSERT(0 < Dimension);\r\n\r\n    template <typename Elements, typename Translator>\r\n    static inline void apply(Elements & elements, const size_t axis, const size_t index, Translator const& tr)\r\n    {\r\n        if ( axis < Dimension - 1 )\r\n        {\r\n            partial_sort<Corner, Dimension - 1>::apply(elements, axis, index, tr);                          // MAY THROW, BASIC (copy)\r\n        }\r\n        else\r\n        {\r\n            BOOST_GEOMETRY_INDEX_ASSERT(axis == Dimension - 1, \"unexpected axis value\");\r\n\r\n            typedef typename Elements::value_type element_type;\r\n            typedef typename rtree::element_indexable_type<element_type, Translator>::type indexable_type;\r\n            typedef typename tag<indexable_type>::type indexable_tag;\r\n\r\n            element_axis_corner_less<element_type, Translator, indexable_tag, Corner, Dimension - 1> less(tr);\r\n            std::partial_sort(elements.begin(), elements.begin() + index, elements.end(), less);            // MAY THROW, BASIC (copy)\r\n        }\r\n    }\r\n};\r\n\r\ntemplate <size_t Corner>\r\nstruct partial_sort<Corner, 1>\r\n{\r\n    template <typename Elements, typename Translator>\r\n    static inline void apply(Elements & elements,\r\n                             const size_t BOOST_GEOMETRY_INDEX_ASSERT_UNUSED_PARAM(axis),\r\n                             const size_t index,\r\n                             Translator const& tr)\r\n    {\r\n        BOOST_GEOMETRY_INDEX_ASSERT(axis == 0, \"unexpected axis value\");\r\n\r\n        typedef typename Elements::value_type element_type;\r\n        typedef typename rtree::element_indexable_type<element_type, Translator>::type indexable_type;\r\n        typedef typename tag<indexable_type>::type indexable_tag;\r\n\r\n        element_axis_corner_less<element_type, Translator, indexable_tag, Corner, 0> less(tr);\r\n        std::partial_sort(elements.begin(), elements.begin() + index, elements.end(), less);                // MAY THROW, BASIC (copy)\r\n    }\r\n};\r\n\r\n} // namespace rstar\r\n\r\ntemplate <typename Value, typename Options, typename Translator, typename Box, typename Allocators>\r\nstruct redistribute_elements<Value, Options, Translator, Box, Allocators, rstar_tag>\r\n{\r\n    typedef typename rtree::node<Value, typename Options::parameters_type, Box, Allocators, typename Options::node_tag>::type node;\r\n    typedef typename rtree::internal_node<Value, typename Options::parameters_type, Box, Allocators, typename Options::node_tag>::type internal_node;\r\n    typedef typename rtree::leaf<Value, typename Options::parameters_type, Box, Allocators, typename Options::node_tag>::type leaf;\r\n\r\n    typedef typename Options::parameters_type parameters_type;\r\n\r\n    static const size_t dimension = geometry::dimension<Box>::value;\r\n\r\n    typedef typename index::detail::default_margin_result<Box>::type margin_type;\r\n    typedef typename index::detail::default_content_result<Box>::type content_type;\r\n\r\n    template <typename Node>\r\n    static inline void apply(\r\n        Node & n,\r\n        Node & second_node,\r\n        Box & box1,\r\n        Box & box2,\r\n        parameters_type const& parameters,\r\n        Translator const& translator,\r\n        Allocators & allocators)\r\n    {\r\n        typedef typename rtree::elements_type<Node>::type elements_type;\r\n        \r\n        elements_type & elements1 = rtree::elements(n);\r\n        elements_type & elements2 = rtree::elements(second_node);\r\n\r\n        size_t split_axis = 0;\r\n        size_t split_corner = 0;\r\n        size_t split_index = parameters.get_min_elements();\r\n        margin_type smallest_sum_of_margins = (std::numeric_limits<margin_type>::max)();\r\n        content_type smallest_overlap = (std::numeric_limits<content_type>::max)();\r\n        content_type smallest_content = (std::numeric_limits<content_type>::max)();\r\n\r\n        rstar::choose_split_axis_and_index<\r\n            typename Options::parameters_type,\r\n            Box,\r\n            dimension\r\n        >::apply(elements1,\r\n                 split_axis, split_corner, split_index,\r\n                 smallest_sum_of_margins, smallest_overlap, smallest_content,\r\n                 parameters, translator);                                                               // MAY THROW, STRONG\r\n\r\n        // TODO: awulkiew - get rid of following static_casts?\r\n\r\n        BOOST_GEOMETRY_INDEX_ASSERT(split_axis < dimension, \"unexpected value\");\r\n        BOOST_GEOMETRY_INDEX_ASSERT(split_corner == static_cast<size_t>(min_corner) || split_corner == static_cast<size_t>(max_corner), \"unexpected value\");\r\n        BOOST_GEOMETRY_INDEX_ASSERT(parameters.get_min_elements() <= split_index && split_index <= parameters.get_max_elements() - parameters.get_min_elements() + 1, \"unexpected value\");\r\n        \r\n        // copy original elements\r\n        elements_type elements_copy(elements1);                                                         // MAY THROW, STRONG\r\n        elements_type elements_backup(elements1);                                                       // MAY THROW, STRONG\r\n\r\n        // TODO: awulkiew - check if std::partial_sort produces the same result as std::sort\r\n        if ( split_corner == static_cast<size_t>(min_corner) )\r\n            rstar::partial_sort<min_corner, dimension>\r\n                ::apply(elements_copy, split_axis, split_index, translator);                            // MAY THROW, BASIC (copy)\r\n        else\r\n            rstar::partial_sort<max_corner, dimension>\r\n                ::apply(elements_copy, split_axis, split_index, translator);                            // MAY THROW, BASIC (copy)\r\n\r\n        BOOST_TRY\r\n        {\r\n            // copy elements to nodes\r\n            elements1.assign(elements_copy.begin(), elements_copy.begin() + split_index);               // MAY THROW, BASIC\r\n            elements2.assign(elements_copy.begin() + split_index, elements_copy.end());                 // MAY THROW, BASIC\r\n\r\n            // calculate boxes\r\n            box1 = rtree::elements_box<Box>(elements1.begin(), elements1.end(), translator);\r\n            box2 = rtree::elements_box<Box>(elements2.begin(), elements2.end(), translator);\r\n        }\r\n        BOOST_CATCH(...)\r\n        {\r\n            //elements_copy.clear();\r\n            elements1.clear();\r\n            elements2.clear();\r\n\r\n            rtree::destroy_elements<Value, Options, Translator, Box, Allocators>::apply(elements_backup, allocators);\r\n            //elements_backup.clear();\r\n\r\n            BOOST_RETHROW                                                                                 // RETHROW, BASIC\r\n        }\r\n        BOOST_CATCH_END\r\n    }\r\n};\r\n\r\n}} // namespace detail::rtree\r\n\r\n}}} // namespace boost::geometry::index\r\n\r\n#endif // BOOST_GEOMETRY_INDEX_DETAIL_RTREE_RSTAR_REDISTRIBUTE_ELEMENTS_HPP\r\n", "meta": {"hexsha": "c49a3deebe2f48d1081307f75ff37d787ac2428f", "size": 19859, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "BoostSharp/include/boost/geometry/index/detail/rtree/rstar/redistribute_elements.hpp", "max_stars_repo_name": "Icenium/BoostSharp", "max_stars_repo_head_hexsha": "1dd31065fcd65ae6304b182c558bac7c7a738ad5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-05-11T05:30:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-24T05:41:33.000Z", "max_issues_repo_path": "src/third_party/boost/boost/geometry/index/detail/rtree/rstar/redistribute_elements.hpp", "max_issues_repo_name": "wugh7125/installwizard", "max_issues_repo_head_hexsha": "42f8aeb78026ff81838528968b1503e73f6c2864", "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/third_party/boost/boost/geometry/index/detail/rtree/rstar/redistribute_elements.hpp", "max_forks_repo_name": "wugh7125/installwizard", "max_forks_repo_head_hexsha": "42f8aeb78026ff81838528968b1503e73f6c2864", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-26T17:00:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T17:00:08.000Z", "avg_line_length": 44.9298642534, "max_line_length": 187, "alphanum_fraction": 0.6140289038, "num_tokens": 3849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543457, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.25710339273643673}}
{"text": "\n/******************************************************************************\n\n  Non-trivial node types (class lables) for MRF models.\n\n  Copyright (c) 2012, 2013\n  Alexander Rukletsov <rukletsov@gmail.com>\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  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\n  THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS \"AS IS\" AND\n  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 AUTHOR 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\n  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\n  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n  SUCH DAMAGE.\n\n*******************************************************************************/\n\n#ifndef NODE_TYPES_HPP_6CF0A0E1_8AE9_4951_A785_9339B90FB976\n#define NODE_TYPES_HPP_6CF0A0E1_8AE9_4951_A785_9339B90FB976\n\n#include <cmath>\n#include <iostream>\n#include <boost/tuple/tuple.hpp>\n#include <boost/operators.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/make_shared.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n\nnamespace bo {\nnamespace mrf {\n\ntemplate <typename P>\nclass ParametricNodeType: boost::equality_comparable1<ParametricNodeType<P> >\n{\npublic:\n    typedef boost::shared_ptr<P> ClassParamsPtr;\n\n    ParametricNodeType(ClassParamsPtr class_params): class_params_(class_params)\n    { }\n\n    //  Generated copy c-tor and assignment operator are fine.\n\n    virtual ~ParametricNodeType()\n    { }\n\n    // Classes are equal when their parameters are equal.\n    virtual bool operator==(const ParametricNodeType<P>& other) const\n    { return (class_params_ == other.class_params_); }\n\nprotected:\n    ClassParamsPtr class_params_;\n};\n\n// A class representing a value (class label) with associated Gauss distribution\n// parameters. Parameters structure is represented as a tuple with 4 elements:\n// class label, mean, standard deviation, and additional item a = ln(sigma * sqrt(2 pi)).\ntemplate <typename RealType>\nclass GaussDistrClasses: public ParametricNodeType<\n        boost::tuples::tuple<int, RealType, RealType, RealType> >\n{\npublic:\n    typedef GaussDistrClasses<RealType> SelfType;\n\n    typedef boost::tuples::tuple<int, RealType, RealType, RealType> ClassParams;\n    typedef ParametricNodeType<ClassParams> BaseType;\n    typedef typename BaseType::ClassParamsPtr ClassParamsPtr;\n\npublic:\n    GaussDistrClasses(ClassParamsPtr class_params): BaseType(class_params)\n    { }\n\n    static GaussDistrClasses CreateInstance(int idx, RealType mean, RealType sigma)\n    { return (SelfType(boost::make_shared<ClassParams>(idx, mean, sigma, compute_a(sigma)))); }\n\n    // Accessors for class label and class parameters.\n    int label() const\n    { return this->class_params_->template get<0>(); }\n\n    RealType mean() const\n    { return this->class_params_->template get<1>(); }\n\n    RealType sigma() const\n    { return this->class_params_->template get<2>(); }\n\n    RealType a() const\n    { return this->class_params_->template get<3>(); }\n\n    // 2.5 is precomputed sqrt(2 pi).\n    static RealType compute_a(RealType sigma)\n    { return (std::log(sigma * RealType(2.5))); }\n};\n\n// A class representing a value (class label) with associated Gamma distribution\n// parameters. Parameters structure is represented as a tuple with 4 elements:\n// class label and a set of Gamma distribution parameters (k, theta, a), where\n// a = ln(G(k)) + k ln(theta) and G(t) is the Gamma function.\ntemplate <typename RealType>\nclass GammaDistrClasses: public ParametricNodeType<\n        boost::tuples::tuple<int, RealType, RealType, RealType> >\n{\npublic:\n    typedef GammaDistrClasses<RealType> SelfType;\n\n    typedef boost::tuples::tuple<int, RealType, RealType, RealType> ClassParams;\n    typedef ParametricNodeType<ClassParams> BaseType;\n    typedef typename BaseType::ClassParamsPtr ClassParamsPtr;\n\npublic:\n    GammaDistrClasses(ClassParamsPtr class_params): BaseType(class_params)\n    { }\n\n    static GammaDistrClasses CreateInstance(int idx, RealType k, RealType theta)\n    { return (SelfType(boost::make_shared<ClassParams>(idx, k, theta, compute_a(k, theta)))); }\n\n    // Accessors for class label and class parameters.\n    int label() const\n    { return this->class_params_->template get<0>(); }\n\n    RealType k() const\n    { return this->class_params_->template get<1>(); }\n\n    RealType theta() const\n    { return this->class_params_->template get<2>(); }\n\n    RealType a() const\n    { return this->class_params_->template get<3>(); }\n\n    RealType mean() const\n    { return (k() * theta()); }\n\n    static RealType compute_a(RealType k, RealType theta)\n    { return (boost::math::lgamma(k) + k * std::log(theta)); }\n};\n\ntemplate <typename T>\nstd::ostream& operator<<(std::ostream& os, const GaussDistrClasses<T>& obj)\n{\n    os << obj.label() << \" (mean: \" << obj.mean() << \", sigma: \" << obj.sigma() << \")\";\n    return os;\n}\n\ntemplate <typename T>\nstd::ostream& operator<<(std::ostream& os, const GammaDistrClasses<T>& obj)\n{\n    os << obj.label() << \" (k: \" << obj.k() << \", theta: \" << obj.theta() << \")\";\n    return os;\n}\n\n} // namespace mrf\n} // namespace bo\n\n#endif // NODE_TYPES_HPP_6CF0A0E1_8AE9_4951_A785_9339B90FB976\n", "meta": {"hexsha": "99f1823edf754ed7a3e2ec853997ac759fc527b4", "size": 6027, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Bo/mrf/node_types.hpp", "max_stars_repo_name": "rukletsov/bo", "max_stars_repo_head_hexsha": "bfece9e8f910b0c8f522733854405bf0a801b0e8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T03:30:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T10:53:32.000Z", "max_issues_repo_path": "Bo/mrf/node_types.hpp", "max_issues_repo_name": "rukletsov/bo", "max_issues_repo_head_hexsha": "bfece9e8f910b0c8f522733854405bf0a801b0e8", "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": "Bo/mrf/node_types.hpp", "max_forks_repo_name": "rukletsov/bo", "max_forks_repo_head_hexsha": "bfece9e8f910b0c8f522733854405bf0a801b0e8", "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.875, "max_line_length": 95, "alphanum_fraction": 0.7079807533, "num_tokens": 1439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.25710338561202667}}
{"text": "#ifndef BSPLINEFITTERIMPL_HPP_\n#define BSPLINEFITTERIMPL_HPP_\n\n#include \"DiffManifoldBSplineTools.hpp\"\n#include \"../DynamicOrTemplateInt.hpp\"\n#include \"../DiffManifoldBSpline.hpp\"\n\n#include <memory>\n#include <map>\n#include <Eigen/Cholesky>\n#include <Eigen/LU>\n#include <Eigen/QR>\n#include <sparse_block_matrix/linear_solver_cholmod.h>\n\nnamespace bsplines{\n#define _TEMPLATE template <typename TSpline>\n#define _CLASS BSplineFitter <TSpline>\n\n//TODO improve : support different containers of times and points\n_TEMPLATE\ninline void _CLASS::initUniformSpline(TSpline & spline, const std::vector<time_t> & times, const std::vector<point_t> & points, int numSegments, double lambda, FittingBackend backend){\n\tSM_ASSERT_GE(Exception, times.size(), 2, \"There must be at least two time point pairs\");\n\tinitUniformSpline(spline, times.front(), times.back(), times, points, numSegments, lambda, backend);\n}\n\n_TEMPLATE\ninline void _CLASS::initUniformSpline(TSpline & spline, time_t minT, time_t maxT, const std::vector<time_t> & times, const std::vector<point_t> & points, int numSegments, double lambda, FittingBackend backend){\n\tspline.assertConstructing();\n\tSM_ASSERT_GE(Exception, times.front(), minT, \"Times must all be >= minT\");\n\tSM_ASSERT_LE(Exception, times.back(), maxT, \"Times must all be <= maxT\");\n\tIntervalUniformKnotGenerator<TimePolicy> knotGenerator(spline.getSplineOrder(), minT, maxT, numSegments);\n\tinitSpline(spline, knotGenerator, times, points, lambda, backend);\n}\n\n_TEMPLATE\ninline DeltaUniformKnotGenerator<typename _CLASS::TimePolicy> _CLASS::initUniformSplineWithKnotDelta(TSpline & spline, const std::vector<time_t> & times, const std::vector<point_t> & points, const duration_t knotDelta, double lambda, FittingBackend backend){\n\tspline.assertConstructing();\n\tSM_ASSERT_GE(Exception, times.size(), 2, \"There must be at least two time point pairs\");\n\tDeltaUniformKnotGenerator<TimePolicy> knotGenerator(spline.getSplineOrder(), *times.begin(), *--times.end(), knotDelta);\n\tinitSpline(spline, knotGenerator, times, points, lambda, backend);\n\treturn knotGenerator;\n}\n\nnamespace internal{\n\ttemplate<typename T>\n\tclass PointerGuard {\n\t\tbool _deleteIt;\n\t\tT * _ptr;\n\t public:\n\t\tPointerGuard() : _deleteIt(false), _ptr(nullptr) {}\n\t\tinline void init(T* ptr, bool deleteIt = true) {\n\t\t\t_deleteIt = deleteIt;\n\t\t\t_ptr = ptr;\n\t\t}\n\t\tinline ~PointerGuard(){\n\t\t\tif(_deleteIt) delete _ptr;\n\t\t}\n\t\tinline T& operator *(){\n\t\t\treturn *_ptr;\n\t\t}\n\t};\n\n\ttemplate<typename TTime>\n\tstruct MapKnotIndexResolver : public KnotIndexResolver<TTime>{\n\t\tstd::map<TTime, int> knots;\n\t\tinline int getKnotIndexAtTime(TTime t) const { return (--knots.upper_bound(t))->second; };\n\t};\n\n\ttemplate <typename TException, typename TTime>\n\tinline void checkTimesBounds(const std::vector<TTime>& times)\n\t{\n\t\tif(times.size() > 1){\n\t\t\tTTime min = *times.begin(), max=*--times.end();\n\t\t\tfor(TTime t : times){\n\t\t\t\tSM_ASSERT_LE(TException, min, t, \"The time sequence must be bounded by its bounding elements. But \" << t << \" is smaller than the first element :\" << min);\n\t\t\t\tSM_ASSERT_LE(TException, t, max, \"The time sequence must be bounded by its bounding elements. But \" << t << \" is bigger than the last element :\" << max);\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\t_TEMPLATE\n\tvoid _CLASS::initSpline(TSpline & spline, KnotGenerator<time_t> & knotGenerator, const std::vector<time_t> & times, const std::vector<point_t> & points, double lambda, FittingBackend fittingBackend){\n\t\tspline.assertConstructing();\n\t\tconst size_t numPoints = points.size();\n\n\t\tSM_ASSERT_EQ(Exception, times.size(), numPoints, \"The number of times and the number of points must be equal\");\n\t\tSM_ASSERT_GE(Exception, numPoints, 2, \"There must be at least two time point pairs\");\n\t\tinternal::checkTimesBounds<Exception>(times);\n\n\t\tinternal::PointerGuard<const KnotIndexResolver<time_t> > resolverPtr;\n\n\t\tif(knotGenerator.hasKnotIndexResolver()){\n\t\t\tfor(size_t i = 0; knotGenerator.hasNextKnot(); i++){\n\t\t\t\tspline.addKnot(knotGenerator.getNextKnot());\n\t\t\t}\n\t\t\tresolverPtr.init(&knotGenerator.getKnotIndexResolver(), false);\n\t\t}else{\n\t\t\tauto mapResolver = new internal::MapKnotIndexResolver<time_t>();\n\t\t\tresolverPtr.init(mapResolver, true);\n\t\t\tfor(size_t i = 0; knotGenerator.hasNextKnot(); i++){\n\t\t\t\ttime_t nextKnot = knotGenerator.getNextKnot();\n\t\t\t\tspline.addKnot(nextKnot);\n\t\t\t\tmapResolver->knots.insert(std::make_pair(nextKnot, i));\n\t\t\t}\n\t\t}\n\n\t\tspline.init();\n\n\t\tcalcFittedControlVertices(spline, *resolverPtr, times, points, std::function<scalar_t(int) > (), lambda, 0, fittingBackend);\n\t}\n\n\t_TEMPLATE\n\tvoid _CLASS::fitSpline(TSpline & spline, const std::vector<time_t> & times, const std::vector<point_t> & points, double lambda, int fixNFirstRelevantControlVertices, std::function<scalar_t(int i) > weights, FittingBackend fittingBackend, const bool calculateControlVertexOffsets){\n\t\tspline.assertEvaluable();\n\t\tconst size_t numPoints = points.size();\n\t\tSM_ASSERT_GE(Exception, numPoints, 1, \"The must be at least one time point pair!\");\n\t\tSM_ASSERT_EQ(Exception, times.size(), numPoints, \"The number of times and the number of points must be equal\");\n\t\tinternal::checkTimesBounds<Exception>(times);\n\n\t\tauto lastTime = times[numPoints - 1];\n\t\tSM_ASSERT_GE(Exception, times[0], spline.getMinTime(), \"The values in times may not exceed the time domain of the spline.\");\n\t\tSM_ASSERT_LE(Exception, lastTime, spline.getMaxTime(), \"The values in times may not exceed the time domain of the spline.\");\n\n\t\tinternal::MapKnotIndexResolver<time_t> mapResolver;\n\t\tint i = 0;\n\t\tfor(auto it = spline.getFirstRelevantSegmentByLast(spline.getSegmentIterator(times[0])), end = spline.getAbsoluteEnd(); it != end; ++it){\n\t\t\ttime_t nextKnot = it->getKnot();\n\t\t\tif(nextKnot > lastTime) break;\n\t\t\tspline.addKnot(nextKnot);\n\t\t\tmapResolver.knots.insert(std::make_pair(nextKnot, i++));\n\t\t}\n\n\t\tcalcFittedControlVertices(spline, mapResolver, times, points, weights, lambda, fixNFirstRelevantControlVertices, fittingBackend, calculateControlVertexOffsets);\n\t}\n\nnamespace internal{\n\ttemplate<typename TSpline>\n\tunsigned int getNumberOfRelevantControlVertices(TSpline& spline, typename TSpline::time_t startTime, const typename TSpline::time_t& upToTime, std::function<void(typename TSpline::SegmentIterator it)> apply = std::function<void(typename TSpline::SegmentIterator it)>())\n\t{\n\t\tunsigned int fixFirstVertices = 0;\n\t\tfor (auto it = spline.getFirstRelevantSegmentByLast(spline.getSegmentIterator(startTime));it->getKnot() < upToTime;fixFirstVertices++, it++) {\n\t\t\tif(apply) apply(it);\n\t\t}\n\t\treturn fixFirstVertices;\n\t}\n}\n\n\t_TEMPLATE\n\tvoid _CLASS::extendAndFitSpline(TSpline & spline, KnotGenerator<time_t> & knotGenerator, const std::vector<time_t> & times, const std::vector<point_t> & points, double lambda, unsigned char honorCurrentValuePercentage, FittingBackend fittingBackend, const bool calculateControlVertexOffsets){\n\t\tconst size_t numPoints = points.size();\n\t\tSM_ASSERT_TRUE(Exception, knotGenerator.supportsAppending(), \"The knot generator must support appending!\");\n\t\tSM_ASSERT_GE(Exception, numPoints, 1, \"The must be at least one time point pair!\");\n\t\tSM_ASSERT_EQ(Exception, times.size(), numPoints, \"The number of times and the number of points must be equal\");\n\t\tSM_ASSERT_LE(Exception, honorCurrentValuePercentage, 100, \"honorCurrentValuePercentage must be in [0, 100]\");\n\n\t\t// first we get the time to which to extend the spline.\n\t\tconst time_t lastTime = times[times.size() - 1];\n\n\t\tconst time_t oldMaxTime = spline.getMaxTime();\n\t\tif(lastTime > oldMaxTime){\n\t\t\tknotGenerator.extendBeyondTime(lastTime);\n\t\t\tspline.appendSegments(knotGenerator, -1, nullptr);\n\t\t}\n\n\t\tif(honorCurrentValuePercentage == 0 || honorCurrentValuePercentage == 100){\n\t\t\tunsigned int fixFirstVertices;\n\t\t\tif(honorCurrentValuePercentage) {\n\t\t\t\tif(lastTime > oldMaxTime){\n\t\t\t\t\tfixFirstVertices = internal::getNumberOfRelevantControlVertices(spline, times[0], oldMaxTime);\n\t\t\t\t} else {\n\t\t\t\t\t// no new vertices but old should not be touched\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{// ignore former values\n\t\t\t\tfixFirstVertices = 0;\n\t\t\t}\n\t\t\tfitSpline(spline, times, points, lambda, (int)fixFirstVertices, std::function<scalar_t(int i) >(), fittingBackend, calculateControlVertexOffsets);\n\t\t}else{\n\t\t\tstd::vector<scalar_t> weights;\n\t\t\tscalar_t baseWeight = scalar_t(honorCurrentValuePercentage) / scalar_t(100 - honorCurrentValuePercentage);\n\n\t\t\tstd::vector<time_t> newTimes;\n\t\t\tstd::vector<point_t> newPoints;\n\t\t\tconst time_t minTime = spline.getMinTime();\n\n\t\t\tconst unsigned int relevantOldVCs = internal::getNumberOfRelevantControlVertices<TSpline>(spline, times[0], oldMaxTime,\n\t\t\t\t[&](typename TSpline::SegmentIterator it)\n\t\t\t\t{\n\t\t\t\t\tit++;\n\t\t\t\t\ttime_t t(it->getKnot());\n\t\t\t\t\tif(t >= minTime){\n\t\t\t\t\t\tnewTimes.push_back(t);\n\t\t\t\t\t\tnewPoints.push_back(spline.template getEvaluatorAt<0>(t).eval());\n\t\t\t\t\t\tweights.push_back(baseWeight); //TODO improve: normalize the weight base on the amount of points given per segment.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\t\t\t//TODO optimize: use better ways to concatenate times and points.\n\t\t\tSM_ASSERT_EQ_DBG(std::runtime_error, newTimes.size(), relevantOldVCs, \"BUG in \"  << __FILE__ << \":\" << __LINE__);\n\t\t\tSM_ASSERT_EQ_DBG(std::runtime_error, newPoints.size(), relevantOldVCs, \"BUG in \"  << __FILE__ << \":\" << __LINE__);\n\n\t\t\tnewTimes.resize(times.size() + relevantOldVCs);\n\t\t\tcopy(times.begin(), times.end(), newTimes.begin() + relevantOldVCs);\n\t\t\tnewPoints.resize(points.size() + relevantOldVCs);\n\t\t\tcopy(points.begin(), points.end(), newPoints.begin() + relevantOldVCs);\n\n\t\t\tfitSpline(spline, newTimes, newPoints, lambda, 0, [relevantOldVCs, &weights](int i){ return i < (int)relevantOldVCs ? weights[i]: scalar_t(1.0);}, fittingBackend, calculateControlVertexOffsets);\n\t\t}\n\t}\n\n\t_TEMPLATE\n\tvoid _CLASS::calcFittedControlVertices(TSpline & spline, const KnotIndexResolver<time_t> & knotIndexResolver, const std::vector<time_t> & times, const std::vector<point_t> & points, std::function<scalar_t(int i) > weights, double lambda, int fixNFirstRelevantControlVertices, FittingBackend fittingBackend, const bool calculateControlVertexOffsets){\n\t\tswitch(fittingBackend){\n\t\t\tcase FittingBackend::DENSE:\n\t\t\t\tcalcFittedControlVertices<FittingBackend::DENSE>(spline, knotIndexResolver, times, points, weights, lambda, fixNFirstRelevantControlVertices, calculateControlVertexOffsets);\n\t\t\t\tbreak;\n\t\t\tcase FittingBackend::SPARSE:\n\t\t\t\tcalcFittedControlVertices<FittingBackend::SPARSE>(spline, knotIndexResolver, times, points, weights, lambda, fixNFirstRelevantControlVertices, calculateControlVertexOffsets);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tnamespace internal {\n\t\ttemplate< enum FittingBackend FittingBackend_> struct FittingBackendFunctions {\n\t\t};\n\n\t\ttemplate<> struct FittingBackendFunctions<FittingBackend::DENSE> {\n\t\t\ttypedef typename FittingBackendTraits<FittingBackend::DENSE>::Matrix Matrix;\n\t\t\ttypedef typename FittingBackendTraits<FittingBackend::DENSE>::Vector Vector;\n\n\t\t\tinline static Matrix createA(unsigned int constraintSize, unsigned int coefficientDim, unsigned int /* D */) {\n\t\t\t\treturn Matrix::Zero(constraintSize, coefficientDim);\n\t\t\t}\n\t\t\tinline static Vector createB(int constraintSize) {\n\t\t\t\treturn Vector::Zero(constraintSize);\n\t\t\t}\n\n\t\t\tinline static auto blockA(Matrix & A, int row, int col, int D, int size = 1) -> decltype(A.block(0, 0, 0, 0)){\n\t\t\t\treturn A.block(row * D, col * D, size * D, size * D);\n\t\t\t}\n\t\t\tinline static typename Vector::SegmentReturnType segmentB(Vector & b, int row, int D){\n\t\t\t\treturn b.segment(row * D, D);\n\t\t\t}\n\t\t\ttemplate <typename DERIVED, typename DERIVED2>\n\t\t\tinline static void addBlockToBlock(Eigen::MatrixBase<DERIVED> & A, int aRow, int aCol, const Eigen::MatrixBase<DERIVED2> & Q, int qRow, int qCol, int rows, int cols, int D, bool segmentInRowVector){\n\t\t\t\trows *= D;\n\t\t\t\tif(segmentInRowVector){\n\t\t\t\t\tcols = 1;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tcols *= D;\n\t\t\t\t}\n\t\t\t\tA.block(aRow * D, aCol * D, rows, cols) += Q.block(qRow * D, qCol * D, rows, cols);\n\t\t\t}\n\n\t\t\tinline static Eigen::VectorXd solve(Matrix & A, Vector & b){\n\t\t\t\treturn A.ldlt().solve(b);\n\t\t\t}\n\t\t};\n\n\n\t\ttemplate<> struct FittingBackendFunctions<FittingBackend::SPARSE> {\n\t\t\ttypedef typename FittingBackendTraits<FittingBackend::SPARSE>::Matrix Matrix;\n\t\t\ttypedef typename FittingBackendTraits<FittingBackend::SPARSE>::Vector Vector;\n\n\t\t\tstd::vector<int> rows;\n\t\t\tstd::vector<int> cols;\n\n\t\t\tconst static bool allocateBlock = true;\n\n\t\t\tinline Matrix createA(unsigned int constraintSize, unsigned int coefficientDim, unsigned int D) {\n\t\t\t\tfor(unsigned int i = D; i <= constraintSize; i+=D) rows.push_back(i);\n\t\t\t\tfor(unsigned int i = D; i <= coefficientDim; i+=D) cols.push_back(i);\n\t\t\t\treturn Matrix(rows,cols, true);\n\t\t\t}\n\n\t\t\tinline Vector createB(int /* constraintSize */) {\n\t\t\t\tstd::vector<int> bcols(1);\n\t\t\t\tbcols[0] = 1;\n\t\t\t\treturn Vector(rows,bcols, true);\n\t\t\t}\n\n\t\t\tinline static typename Matrix::SparseMatrixBlock & blockA(Matrix & A, int row, int col, int /* D */, int size = 1){\n\t\t\t\tSM_ASSERT_EQ(std::runtime_error, 1, size, \"This function should does not support size != 1\");\n\t\t\t\treturn *A.block(row, col, allocateBlock);\n\t\t\t}\n\t\t\tinline static typename Vector::SparseMatrixBlock & segmentB(Vector & b, int row, int /* D */){\n\t\t\t\treturn *b.block(row, 0, allocateBlock);\n\t\t\t}\n\t\t\ttemplate <typename DERIVED>\n\t\t\tinline static void addBlockToBlock(Matrix & A, int aRow, int aCol, const Eigen::MatrixBase<DERIVED> & Q, int qRow, int qCol, int rows, int cols, int D, bool segmentInRowVector){\n\t\t\t\tfor(int i = 0; i < rows; ++i){\n\t\t\t\t\tfor(int j = 0; j < cols; ++j){\n\t\t\t\t\t\t*A.block(aRow + i, aCol + j, true) += Q.block((qRow + i) * D, (qCol + j) * D, D, segmentInRowVector ? 1 : D);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tinline static Eigen::VectorXd solve(Matrix & A, Vector & b){\n\t\t\t\t// solve:\n\t\t\t\tsparse_block_matrix::LinearSolverCholmod<Eigen::MatrixXd> solver;\n\t\t\t\tsolver.init();\n\n\t\t\t\tEigen::VectorXd c(A.rows());\n\t\t\t\tc.setZero();\n\t\t\t\tEigen::VectorXd b_dense = b.toDense();\n\t\t\t\tbool result = solver.solve(A,&c[0],&b_dense[0]);\n\t\t\t\tif(!result) {\n\t\t\t\t\tc.setZero();\n\t\t\t\t\t// fallback => use nonsparse solver:\n\t\t\t\t\tstd::cout << \"Fallback to Dense Solver\" << std::endl;\n\t\t\t\t\tEigen::MatrixXd Adense = A.toDense();\n\t\t\t\t\tc = Adense.ldlt().solve(b_dense);\n\t\t\t\t}\n\t\t\t\treturn c;\n\t\t\t}\n\t\t};\n\t}\n\n\t_TEMPLATE\n\ttemplate <enum FittingBackend FittingBackend_>\n\tvoid _CLASS::calcFittedControlVertices(TSpline & spline, const KnotIndexResolver<time_t> & knotIndexResolver, const std::vector<time_t> & times, const std::vector<point_t> & points, std::function<scalar_t(int i) > weights, double lambda, int fixNFirstRelevantControlVertices, const bool calculateControlVertexOffsets)\n\t{\n\t\tif(calculateControlVertexOffsets){\n\t\t\t//TODO implement : support calculateControlVertexOffsets in addCurveQuadraticIntegralDiagTo and remove this check!\n\t\t\tSM_ASSERT_EQ(Exception, 0.0, lambda, \"control vertex offsets aren't supported together with lambda != 0, yet!\");\n\t\t}\n\n\t\tSM_ASSERT_GE_DBG(Exception, fixNFirstRelevantControlVertices, 0, \"fixNFirstRelevantControlVertices must be nonnegative.\");\n\t\tconst time_t splineMaxTime = spline.getMaxTime(), lastTime = times[times.size() - 1];\n\t\tconst int splineOrder = spline.getSplineOrder();\n\t\tconst int minKnotIndex = knotIndexResolver.getKnotIndexAtTime(times[0]) - (splineOrder - 1) - (times[0] == splineMaxTime ? 1 : 0); // get minimal relevant knot's index //TODO improve: remove this irregularity\n\t\tconst int controlVertexIndexOffset = minKnotIndex + fixNFirstRelevantControlVertices;\n\t\tconst int numToFitControlVertices = knotIndexResolver.getKnotIndexAtTime(lastTime) - controlVertexIndexOffset + 1 - (lastTime == splineMaxTime ? 1 : 0);//TODO improve: remove this irregularity\n\n\t\tif(numToFitControlVertices <= 0){\n\t\t\tSM_THROW_DBG(Exception, \"No control vertices are left over to be optimized.\")\n\t\t\treturn;\n\t\t}\n\n\t\tconst int capturedCurrentControlVertices = calculateControlVertexOffsets ? fixNFirstRelevantControlVertices + numToFitControlVertices : fixNFirstRelevantControlVertices;\n\t\tconst typename TSpline::point_t* currentControlVertices[capturedCurrentControlVertices];\n\t\tif(capturedCurrentControlVertices){\n\t\t\tauto it = spline.getFirstRelevantSegmentByLast(spline.getSegmentIterator(times[0]));\n\t\t\tfor(int i = 0; i < capturedCurrentControlVertices; ++i){\n\t\t\t\tcurrentControlVertices[i] = &it->getControlVertex();\n\t\t\t\t++it;\n\t\t\t}\n\t\t}\n\n\t\tconst size_t numPoints = points.size();\n\n\t\t// What is the vector coefficient dimension\n\t\tconst size_t D = spline.getPointSize();\n\n\t\t// Now we have to solve an Ax = b linear system to determine the correct coefficient vectors.\n\t\tsize_t coefficientDim = (size_t) numToFitControlVertices * D;\n\n\t\tconst int constraintSize = numPoints * D;\n\n\t\tinternal::FittingBackendFunctions<FittingBackend_> backend;\n\n\t\tauto A = backend.createA(constraintSize, coefficientDim, D);\n\t\tauto b = backend.createB(constraintSize);\n\n\t\tint brow = 0;\n\n\t\t// Add the position constraints.\n\t\tfor(size_t i = 0; i < numPoints; i++)\n\t\t{\n\t\t\ttime_t time = times[i];\n\t\t\tscalar_t weight = weights? weights(i) : scalar_t(1.0);\n\t\t\tint knotIndex = knotIndexResolver.getKnotIndexAtTime(time) - controlVertexIndexOffset;\n\t\t\t//TODO optimize : a uniform time spline evaluator could be much faster here!\n\t\t\ttypename TSpline::SplineOrderVector bi = spline.template getEvaluatorAt<1>(times[i]).getLocalBi();\n\n\t\t\tif(weight != scalar_t(1.0)){\n\t\t\t\tbi *= weight;\n\t\t\t}\n\n\t\t\tknotIndex -= splineOrder - 1; // get first relevant knot's index\n\t\t\tif(time == splineMaxTime){ //TODO improve: remove this irregularity\n\t\t\t\tknotIndex --;\n\t\t\t}\n\n\t\t\tfor(int j = 0; j < splineOrder; j ++){\n\t\t\t\tconst int col = knotIndex + j;\n\t\t\t\tif(col >= 0){ // this control vertex is not fixed\n\t\t\t\t\tif(bi[j] != 0.0)\n\t\t\t\t\t\tbackend.blockA(A, brow, col, D).diagonal().setConstant(bi[j]);\n\t\t\t\t}\n\t\t\t\tif(col < 0 || calculateControlVertexOffsets){\n\t\t\t\t\tconst int vertexIndex = fixNFirstRelevantControlVertices + col;\n\t\t\t\t\tSM_ASSERT_GE_DBG(std::runtime_error, vertexIndex, 0, \"BUG in BSplineFitter\");\n\t\t\t\t\tSM_ASSERT_LT_DBG(std::runtime_error, vertexIndex, capturedCurrentControlVertices, \"BUG in BSplineFitter\");\n\t\t\t\t\tbackend.segmentB(b, brow, D) -= (*currentControlVertices[vertexIndex]) * bi[j];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(knotIndex >= 0 && ! calculateControlVertexOffsets)\n\t\t\t\tbackend.segmentB(b, brow, D) = points[i] * weight;\n\t\t\telse{\n\t\t\t\tbackend.segmentB(b, brow, D) += points[i] * weight;\n\t\t\t}\n\t\t\t++brow;\n\t\t}\n\n\t\tb = A.transpose() * b;\n\t\tA = A.transpose() * A;\n\n\t\tif(lambda != 0.0){\n\t\t\t// Add the motion constraint.\n\t\t\tpoint_t W = point_t::Constant(D, lambda);\n\t\t\tauto start = spline.getSegmentIterator(times[0]);\n\t\t\tauto end = spline.getSegmentIterator(lastTime);\n\t\t\tconst int moveCount = fixNFirstRelevantControlVertices - (splineOrder - 1);\n\t\t\tconst int movedCount = moveIterator(start, moveCount < 0 ? spline.begin() : end, moveCount);\n\t\t\tconst int moveEndCount = splineOrder;\n\t\t\tmoveIterator(end, spline.end(), moveEndCount);\n\t\t\tif(moveCount - movedCount <= 0){ // did we not reach end?\n\t\t\t\taddCurveQuadraticIntegralDiagTo<FittingBackend_>(spline, start, end, movedCount, W, 2, A, b);\n\t\t\t}\n\t\t}\n\n\t\t// Solve for the coefficient vector.\n\t\tEigen::VectorXd c = backend.solve(A, b);\n\n\t\tif(calculateControlVertexOffsets){\n\t\t\tconst auto & manifold = spline.getManifold();\n\t\t\tspline.manipulateControlVertices([&c, D, &manifold](int i, point_t & v) {\n\t\t\t\t\tv += c.block(i * D, 0, D, 1);\n\t\t\t\t\tmanifold.projectIntoManifold(v);\n\t\t\t\t}, numToFitControlVertices, times[0], fixNFirstRelevantControlVertices);\n\t\t}\n\t\telse{\n\t\t\tspline.setControlVertices(c, times[0], fixNFirstRelevantControlVertices);\n\t\t}\n\t}\n\n\t_TEMPLATE\n\ttemplate <enum FittingBackend FittingBackend_>\n\tvoid _CLASS::addCurveQuadraticIntegralDiagTo(const TSpline & spline, typename TSpline::SegmentConstIterator start, typename TSpline::SegmentConstIterator end, int startIndex, const point_t & Wdiag, int derivativeOrder, typename internal::FittingBackendTraits<FittingBackend_>::Matrix & toMatrix, typename internal::FittingBackendTraits<FittingBackend_>::Vector & toB)\n\t{\n\t\tSM_ASSERT_EQ(Exception,Wdiag.rows(), (int)spline.getPointSize(), \"Wdiag must be of control point size\");\n\t\tSM_ASSERT_EQ(Exception, toMatrix.rows(), toB.rows(), \"Wdiag must be of control point size\");\n\n\t\ttypedef internal::FittingBackendFunctions<FittingBackend_> Backend;\n\n\t\tconst int D = spline.getPointSize();\n\t\tconst int blocksInQ = spline.getSplineOrder();\n\t\tSM_ASSERT_EQ(Exception,Wdiag.rows(), D, \"Wdiag must be of control point size\");\n\n\t\tconst auto qiSize = spline.getSplineOrder() * spline.getPointSize();\n\t\ttypedef decltype(qiSize) QiSize;\n\t\ttypedef Eigen::Matrix<double, QiSize::VALUE, QiSize::VALUE> Q_T;\n\t\tQ_T Q((int)qiSize, (int)qiSize);\n\n\t\tint blockRow = startIndex;\n\t\tconst int blockRows = toMatrix.rows() / D;\n\t\tfor(typename TSpline::SegmentConstIterator sIt = start; sIt != end; sIt++)\n\t\t{\n\t\t\tif(FittingBackend_ == FittingBackend::DENSE && blockRow >= 0 && blockRow <= blockRows - blocksInQ){ // all splineOrder many diagonal blocks are contained in the toMatrix\n\t\t\t\taddOrSetSegmentQuadraticIntegralDiag(spline, Wdiag, sIt, derivativeOrder, Backend::blockA(toMatrix, blockRow, blockRow, D, blocksInQ), true);\n\t\t\t} else { // we have to assign sub blocks individually\n\t\t\t\taddOrSetSegmentQuadraticIntegralDiag<Q_T &>(spline, Wdiag, sIt, derivativeOrder, Q, false);\n\t\t\t\t/*\n\t\t\t\t * Q and toMatrix (=:M) (both square) have shifted block index space. i_Q + brow = i_M.\n\t\t\t\t * Lets x denote the coefficients of all non fixed control vertices\n\t\t\t\t * first we need the overlapping region:\n\t\t\t\t * its left most index in M is : max(0, 0 + brow).\n\t\t\t\t * its right most index in M is : min(cols(M) - 1, cols(Q) - 1 + brow).\n\t\t\t\t */\n\t\t\t\tconst int overlappingBlocksLeftIndex = std::max(0, blockRow);\n\t\t\t\tconst int overlappingBlocksRightIndex = std::min(blockRows, blocksInQ + blockRow) - 1;\n\t\t\t\tconst int numOverlappingBlocks = overlappingBlocksRightIndex - overlappingBlocksLeftIndex + 1;\n\t\t\t\tif(numOverlappingBlocks > 0){\n\t\t\t\t\tBackend::addBlockToBlock(toMatrix, overlappingBlocksLeftIndex, overlappingBlocksLeftIndex, Q, overlappingBlocksLeftIndex - blockRow, overlappingBlocksLeftIndex - blockRow, numOverlappingBlocks, numOverlappingBlocks, D, false);\n\t\t\t\t\tif(numOverlappingBlocks != blocksInQ){\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Now we have to subtract the effect of the fixed control vertices on the acceleration term.\n\t\t\t\t\t\t *\n\t\t\t\t\t\t * [Q_l  Q_x  Q_r]  * [ c_l; x; c_r] = b_x\n\t\t\t\t\t\t * <=> Q_x * x  = b_x - Q_l * c_l - Q_r * c_r\n\t\t\t\t\t\t *\n\t\t\t\t\t\t * We start with c_r because sIt corresponds to its bottom at the moment.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tauto constantVertexIt = sIt;\n\t\t\t\t\t\tconst int Q_r_LeftColumnIndex = overlappingBlocksRightIndex - blockRow + 1;\n\t\t\t\t\t\tconst int Q_l_RightColumnIndex = - blockRow - 1;\n\t\t\t\t\t\tfor(int i = blocksInQ-1; i >= 0; i--) {\n\t\t\t\t\t\t\tif(i >= Q_r_LeftColumnIndex || i <= Q_l_RightColumnIndex){ // then vertex is fixed and we have to subtract its effect on the right hand side\n\t\t\t\t\t\t\t\tBackend::addBlockToBlock(toB, overlappingBlocksLeftIndex, 0, (-Q.block((overlappingBlocksLeftIndex - blockRow) * D, i * D, numOverlappingBlocks * D, D) * constantVertexIt->getControlVertex()).eval(), 0, 0, numOverlappingBlocks, 1, D, true);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconstantVertexIt--;\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\tblockRow ++;\n\t\t}\n\t}\n\n\t_TEMPLATE\n\ttemplate<typename M_T>\n\tinline void _CLASS::addOrSetSegmentQuadraticIntegralDiag(const TSpline & spline, const point_t & Wdiag, typename TSpline::SegmentConstIterator segmentIt, int derivativeOrder, M_T toMatrix, bool add)\n\t{\n\t\tconst int D = spline.getPointSize();\n\t\tconst int splineOrder = spline.getSplineOrder();\n\t\tSM_ASSERT_GE_LT(Exception, segmentIt.getKnot(), spline.getMinTime(), spline.getMaxTime(), \"Out of range\");\n\t\tSM_ASSERT_EQ(Exception, Wdiag.rows(), D, \"Wdiag must be of control point size\");\n\n\t\ttypename TSpline::SplineOrderSquareMatrix Dm(splineOrder, splineOrder);\n\t\tDm.setZero(splineOrder, splineOrder);\n\t\tspline.computeDiiInto(segmentIt, Dm);\n\t\ttypename TSpline::SplineOrderSquareMatrix V(splineOrder, splineOrder);\n\t\tV.setZero(splineOrder, splineOrder);\n\t\tspline.computeViInto(segmentIt, V);\n\n\t\t// Calculate the appropriate derivative version of V\n\t\t// using the matrix multiplication version of the derivative.\n\t\tfor(int i = 0; i < derivativeOrder; i++)\n\t\t{\n\t\t\tV = (Dm.transpose() * V * Dm).eval();\n\t\t}\n\n\t\tconst auto splineOrderTimesPointSize = spline.getSplineOrder() * spline.getPointSize();\n\t\ttypedef decltype(splineOrderTimesPointSize) SplineOrderTimesPointSize;\n\t\ttypedef Eigen::Matrix<double, SplineOrderTimesPointSize::VALUE, SplineOrderTimesPointSize::VALUE> MType;\n\n\t\tMType WV((int)splineOrderTimesPointSize, (int)splineOrderTimesPointSize);\n\n\t\tWV.setZero(splineOrderTimesPointSize, splineOrderTimesPointSize);\n\n\t\tfor(int d = 0; d < D; d++)\n\t\t{\n\t\t\tWV.block(splineOrder*d, splineOrder*d, splineOrder, splineOrder) = Wdiag(d) * V;\n\t\t}\n\n\t\tMType M((int)splineOrderTimesPointSize, (int)splineOrderTimesPointSize);\n\t\tcomputeMiInto(spline, segmentIt, M);\n\n\t\tif(add) toMatrix += M.transpose() * WV * M;\n\t\telse toMatrix = M.transpose() * WV * M;\n\t}\n\n\t_TEMPLATE\n\ttemplate <typename M_T>\n\tvoid _CLASS::computeBijInto(const TSpline & spline, const typename TSpline::SegmentConstIterator & segmentIndex, int columnIndex, M_T B)\n\t{\n\t\tconst int D = spline.getPointSize();\n\t\tconst int splineOrder = spline.getSplineOrder();\n\n\t\tfor(int i = 0; i < D; i++)\n\t\t{\n\t\t\tB.block(i*splineOrder,i,splineOrder,1) = segmentIndex->getBasisMatrix().col(columnIndex);\n\t\t}\n\t}\n\n\t_TEMPLATE\n\ttemplate <typename M_T>\n\tvoid _CLASS::computeMiInto(const TSpline & spline, const typename TSpline::SegmentConstIterator & segmentIndex, M_T & M)\n\t{\n\t\tconst int D = spline.getPointSize();\n\t\tconst int splineOrder = spline.getSplineOrder();\n\t\tconst int splineOrderTimesPointSize = splineOrder * D;\n\t\tM.setZero();\n\n\t\tfor(int j = 0; j < splineOrder; j++)\n\t\t{\n\t\t\tcomputeBijInto(spline, segmentIndex, j, M.block(0, j*D, splineOrderTimesPointSize, D));\n\t\t}\n\t}\n}\n\n#undef _TEMPLATE\n#undef _CLASS\n\n\n#endif /* BSPLINEFITTERIMPL_HPP_ */\n", "meta": {"hexsha": "b28fb1be010fcc5836e124666819efd1ddff9d74", "size": 25814, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "bsplines/include/bsplines/implementation/BSplineFitterImpl.hpp", "max_stars_repo_name": "Curium-sg/aslam_splines", "max_stars_repo_head_hexsha": "d2c8c69d28d2f742b1d96a6a4e43a5c5112497af", "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": "bsplines/include/bsplines/implementation/BSplineFitterImpl.hpp", "max_issues_repo_name": "Curium-sg/aslam_splines", "max_issues_repo_head_hexsha": "d2c8c69d28d2f742b1d96a6a4e43a5c5112497af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bsplines/include/bsplines/implementation/BSplineFitterImpl.hpp", "max_forks_repo_name": "Curium-sg/aslam_splines", "max_forks_repo_head_hexsha": "d2c8c69d28d2f742b1d96a6a4e43a5c5112497af", "max_forks_repo_licenses": ["BSD-3-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.2778730703, "max_line_length": 368, "alphanum_fraction": 0.7247230185, "num_tokens": 6940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.25699151989250296}}
{"text": "//    Copyright 2017 Rainer Gemulla\n// \n//    Licensed under the Apache License, Version 2.0 (the \"License\");\n//    you may not use this file except in compliance with the License.\n//    You may obtain a copy of the License at\n// \n//        http://www.apache.org/licenses/LICENSE-2.0\n// \n//    Unless required by applicable law or agreed to in writing, software\n//    distributed under the License is distributed on an \"AS IS\" BASIS,\n//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//    See the License for the specific language governing permissions and\n//    limitations under the License.\n/** \\file\n *\n * Illustrates matrix factorization with parallel SGD. We first create factors and then a data matrix\n * from these factors. This process ensures that we know the best factorization of the input.\n * These matrices are distributed across a cluster. We then try to reconstruct the factors\n * using PSGD.\n *\n * Run with: psgd\n * (make sure to use a production build, otherwise it will be slow)\n */\n#include <iostream>\n#include <sstream>\n\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <mf/matrix/io/generateDistributedMatrix.h>\n#include <mpi2/mpi2.h>\n#include <mf/mf.h>\n\n\nlog4cxx::LoggerPtr logger(log4cxx::Logger::getLogger(\"main\"));\n\nusing namespace std;\nusing namespace mf;\nusing namespace mpi2;\nusing namespace rg;\nusing namespace boost::numeric::ublas;\n\n// type of SGD\ntypedef UpdateTruncate<UpdateNzslNzl2> Update;\ntypedef UpdateLock<Update> UpdateL;\ntypedef RegularizeNone Regularize;\ntypedef SumLoss<NzslLoss, Nzl2Loss> Loss;\ntypedef NzslLoss TestLoss;\n\n\nstruct TrainingPoint {\n\n\tTrainingPoint(){}\n\tTrainingPoint (mf_size_type i , mf_size_type j, double x):i_(i), j_(j), x_(x){}\n\n\tmf_size_type i_;\n\tmf_size_type j_;\n\tdouble x_;\n\n};\n\n\n//global variables\nmf_size_type size1;\nmf_size_type size2;\nmf_size_type b1;\nmf_size_type b2;\n\nmf_size_type minSize1;\nmf_size_type minSize2;\nmf_size_type remainder1;\nmf_size_type remainder2;\n\nint calculateBlocking(double size1, double size2, double nnz, double rank, double cache){\n\n\tint SizeOfInt = 8;\n\tdouble alpha = cache * 1024;\n\tdouble beta = (-1)*(size1+size2)*rank*SizeOfInt;\n\tdouble gamma = (-1)*nnz*3*SizeOfInt;\n\n\tdouble delta = beta*beta-4*alpha*gamma;\n\n\tint b = ((-1)*beta+sqrt(delta))/(2*alpha);\n\n\treturn b;  \n}\n\n\n// compare function for sort\ninline bool compFunction (TrainingPoint point1, TrainingPoint point2) {\n\n\tmf_size_type block1_i = min ((mf_size_type)floor(point1.i_/minSize1), b1 -1);\n\tmf_size_type block2_i = min ((mf_size_type)floor(point2.i_/minSize1), b1 -1);\n\tmf_size_type block1_j = min ((mf_size_type)floor(point1.j_/minSize2), b2 -1);\n\tmf_size_type block2_j = min ((mf_size_type)floor(point2.j_/minSize2), b2 -1);\n\tbool result = false;\n\tif (block1_i < block2_i) {\n\t\tresult = true;\n\t} else if (block1_i == block2_i) {\n\t\tif (block1_j < block2_j) {\n\t\t\tresult = true;\n\t\t} else {\n\t\t\tresult =false;\n\t\t}\n\t}\n\treturn result;\n}\n\n\nint main(int argc, char* argv[]) {\n  \n\tusing namespace boost::program_options;\n\t// initialize mf library and mpi2\n\tboost::mpi::communicator& world = mfInit(argc, argv);\n\n\n\n\t// parameters for the factorization\n\tmf_size_type rank = 10;\n\tint tasks = 4;\n\tmf_size_type epochs = 10;\n\tSgdOrder order = SGD_ORDER_WOR;\n\tBalanceType balanceType = BALANCE_NONE;\n\tBalanceMethod balanceMethod = BALANCE_OPTIMAL;\n\tdouble lambda = 0.05;\n\tdouble eps0 = 0.0125;\n\tmf_size_type cache = 256;\n\tstring traceFile,traceVar;\n\t\n\t// start mf library\n\tmfStart();\n\n\tif (world.rank() == 0)\n\t{\n#ifndef NDEBUG\n\t\tLOG4CXX_WARN(logger, \"Warning: Debug mode activated (runtimes may be slow).\");\n#endif\n\n\t\tstring inputMatrixFile;\n\t\tstring inputRowFacFile;\n\t\tstring inputColFacFile;\n\t\tstring outputRowFacFile;\n\t\tstring outputColFacFile;\n\t\tstring inputTestMatrixFile;\n\t\tstring traceFile,traceVar;\n\n\n\n\t\toptions_description desc(\"Options\");\n\t\tdesc.add_options()\n\t\t\t\t(\"help\", \"produce help message\")\n\t\t\t\t(\"epochs\", value<mf_size_type>(&epochs)->default_value(10), \"number of epochs to run [10]\")\n\t\t\t\t(\"rank\", value<mf_size_type>(&rank)->default_value(10), \"rank of factorization [10]\")\n\t\t\t\t(\"cache\", value<mf_size_type>(&cache)->default_value(256), \"last level cache (in KB) available per core [256]\")\n\t\t\t\t(\"lambda\", value<double>(&lambda)->default_value(0.05), \"lambda\")\n\t\t\t\t(\"eps0\", value<double>(&eps0)->default_value(0.01), \"initial step size for BoldDriver\")\n\t\t\t\t(\"tasks-per-rank\", value<int>(&tasks)->default_value(1), \"number of concurrent tasks [1]\")\n\t\t\t\t(\"trace\", value<string>(&traceFile)->default_value(\"trace.R\"), \"filename of trace [trace]\")\n\t\t\t\t(\"traceVar\", value<string>(&traceVar)->default_value(\"trace\"), \"variable name for trace [traceVar]\")\n\t\t\t\t(\"input-file\", value<string>(&inputMatrixFile), \"input matrix\")\n\t\t\t\t(\"input-test-file\", value<string>(&inputTestMatrixFile), \"input test matrix\")\n\t\t\t    (\"input-row-file\", value<string>(&inputRowFacFile), \"input initial row factor\")\n\t\t\t    (\"input-col-file\", value<string>(&inputColFacFile), \"input initial column factor\")\n\t\t\t    (\"output-row-file\", value<string>(&outputRowFacFile), \"output initial row factor\")\n\t\t\t    (\"output-col-file\", value<string>(&outputColFacFile), \"output initial column factor\")\n\t\t\t\t;\n\n\t\tpositional_options_description pdesc;\n\t\tpdesc.add(\"input-file\", 1);\n\t\tpdesc.add(\"input-test-file\", 2);\n\t\tpdesc.add(\"input-row-file\", 3);\n\t\tpdesc.add(\"input-col-file\", 4);\n\n\t\tvariables_map vm;\n\t\tstore(command_line_parser(argc, argv).options(desc).positional(pdesc).run(), vm);\n\t\tnotify(vm);\n\n\t\tif (vm.count(\"help\") || vm.count(\"input-file\")==0) {\n\t\t\tcout << \"CSGD with NZL2  [options] <input-file> \" << endl << endl;\n\t\t\tcout << desc << endl;\n\t\t\treturn 1;\n\t\t}\n\n\t\tif (vm.count(\"output-row-file\") == 0) { outputRowFacFile = \"\"; }\n\t\tif (vm.count(\"output-col-file\") == 0) { outputColFacFile = \"\"; }\n\n\t\tLOG4CXX_INFO(logger, \"Using \" << tasks << \" parallel tasks\");\n\t\t\n\t\t\n\t\t///////////////////////////////////////\n\t\t\n\n\n\t\tRandom32 random; // note: this takes a default seed (not randomized!)\n\n// \t\tSparseMatrix v;\n// \t\treadMatrix(inputMatrixFile, v, MM_COORD);\n\n\t\t\n// \t\tSparseMatrix vTest;\n// \t\treadMatrix(inputTestMatrixFile, vTest, MM_COORD);\n// \n// \t\tDenseMatrix w;\n// \t\treadMatrix(inputRowFacFile, w, MM_ARRAY);\n// \t\tDenseMatrixCM h;\n// \t\treadMatrix(inputColFacFile, h, MM_ARRAY);\n\t\t\n\t\tTimer t;\n\t\tt.start();\n\t\tstd::vector<DistributedSparseMatrix> dataVector=getDataMatrices<SparseMatrix>(inputMatrixFile,\"V\",true,\n\t\t\t\ttasks, 1, 1, 1, true, false, &inputTestMatrixFile);\n\n\t\tSparseMatrix& v = *mpi2::env().get<SparseMatrix>(dataVector[0].blocks()(0,0).var());\n\t\tSparseMatrix& vTest = *mpi2::env().get<SparseMatrix>(dataVector[1].blocks()(0,0).var());\n\n\t  \t\n\t\tstd::pair<DistributedDenseMatrix, DistributedDenseMatrixCM> factorsPair= getFactors(inputRowFacFile,\n\t\t\tinputColFacFile,  tasks, 1, 1, 1, true);\n\t\tDenseMatrix w = *mpi2::env().get<DenseMatrix>(factorsPair.first.blocks()(0,0).var());\n\t\tDenseMatrixCM h = *mpi2::env().get<DenseMatrixCM>(factorsPair.second.blocks()(0,0).var());\n\t\tt.stop();\n\t\tLOG4CXX_INFO(logger, \"Total time for loading matrices: \" << t);\n\t\t\n\t\tmf_size_type nnz = v.nnz();\n\t\tSparseMatrix::index_array_type& vIndex1 = rowIndexData(v);\n\t\tSparseMatrix::index_array_type& vIndex2 = columnIndexData(v);\n\t\tSparseMatrix::value_array_type& vValues = v.value_data();\n\t\t\n\t\t\n\n\t\t// global variables\n\t\tsize1 = v.size1();\n\t\tsize2 = v.size2();\n\t\tint b = calculateBlocking(size1, size2, nnz, rank, cache);\n\t\tb1 = b;\n\t\tb2 = b;\n\t\t\n\t\tLOG4CXX_INFO(logger, \"Using a \" << b << \" x \"<< b<<\" stratification\");\n\t\t\n\t\t\n\t\tminSize1 = floor(size1/b1);\n\t\tminSize2 = floor(size2/b2);\n\t\tremainder1 = size1 % b1;\n\t\tremainder2 = size2 % b2;\n\n\t\tLOG4CXX_INFO(logger, \"Data matrix: \"\n\t\t\t<< size1 << \" x \" << size2 << \", \" << nnz << \" nonzeros\");\n\t\tLOG4CXX_INFO(logger, \"minSize1: \" << minSize1 << \" remainder1: \" << remainder1);\n\t\tLOG4CXX_INFO(logger, \"minSize2: \" << minSize2 << \" remainder2: \" << remainder2);\n\n\t\t// sort v\n\t\tLOG4CXX_INFO(logger, \"Sorting v ... \");\n\t\tstd::vector<TrainingPoint> points;\n\t\tfor (mf_size_type i = 0; i < v.nnz(); i++) {\n\t\t\tTrainingPoint point = TrainingPoint(vIndex1[i], vIndex2[i], vValues[i]);\n\t\t\tpoints.push_back(point);\n\t\t}\n\t\tsort(points.begin(), points.end(), compFunction);\n\n\t\t// compute nnz per block\n\t\tLOG4CXX_INFO(logger, \"Computing nnz per block ... \");\n\t\tstd::vector<mf_size_type> nnzPerBlock;\n\t\tfor (mf_size_type i = 0; i < (b1*b2); i++) nnzPerBlock.push_back(0);\n\t\tfor (mf_size_type i = 0; i < points.size(); i++) {\n\t\t\tvIndex1[i] = points.at(i).i_;\n\t\t\tvIndex2[i] = points.at(i).j_;\n\t\t\tvValues[i] = points.at(i).x_;\n\n\t\t\tmf_size_type block_i = min ((mf_size_type)floor(points.at(i).i_/minSize1), b1 -1);\n\t\t\tmf_size_type block_j = min ((mf_size_type)floor(points.at(i).j_/minSize2), b2 -1);\n\t\t\tmf_size_type blockId = (b2 * block_i) + block_j;\n\n\t\t\tif ((block_i > b1) || (block_j > b2)) {\n\t\t\t\tLOG4CXX_INFO(logger, \"block_i \" << block_i << \" = floor( \" << points.at(i).i_ << \" / \" << minSize1);\n\t\t\t\tLOG4CXX_INFO(logger, \"block_j \" << block_j << \" = floor( \" << points.at(i).j_ << \" / \" << minSize2);\n\t\t\t}\n\t\t\tnnzPerBlock[blockId]++;\n\t\t}\n\t\tLOG4CXX_INFO(logger, \"nnzPerBlock of size: \" << nnzPerBlock.size());\n\n\t\t// compute permutation\n\t\tLOG4CXX_INFO(logger, \"Computing permutation ... \");\n\t\tstd::vector<mf_size_type> permutation;\n\t\tfor (mf_size_type i = 0; i < v.nnz(); i++) {\n\t\t\tpermutation.push_back(i);\n\t\t}\n\n\t\t// compute offsets\n\t\tLOG4CXX_INFO(logger, \"Computing offsets ... \");\n\t\tstd::vector<mf_size_type> offsets((b1*b2)+1); offsets.clear();\n\t\tmf_size_type offset = 0;\n\t\toffsets.push_back(offset);\n\t\tfor (mf_size_type i = 1; i < (b1*b2)+1; i++) {\n\t\t\toffset += nnzPerBlock[i-1];\n\t\t\toffsets.push_back(offset);\n\t\t}\n\n\n\t\tUpdate update = Update(UpdateNzslNzl2(lambda), -100, 100); // truncate for numerical stability\n\t\tRegularize regularize;\n\t\tLoss loss((NzslLoss()), Nzl2Loss(lambda));\n\t\tTestLoss testLoss;\n\t\t\n\t\tFactorizationData<> testData(vTest, w, h);\n\t\tLOG4CXX_INFO(logger, \"Initial test loss: \" << testLoss(testData));\n\n\t\t// initialize\n\t\t\n\t\tStratifiedPsgdRunner stratifiedPsgdRunner (random, permutation, offsets);\n\t\tStratifiedPsgdJob<Update,Regularize> stratifiedPsgdJob(v, w, h, update, regularize, order, tasks);\n\t\tBoldDriver decay(eps0);\n\t\tTrace trace;\n\n\t\tt.start();\n\t\tstratifiedPsgdRunner.run(stratifiedPsgdJob, loss, epochs, decay, trace, balanceType, balanceMethod, &testData, &testLoss);\n\t\tt.stop();\n\t\tLOG4CXX_INFO(logger, \"Total time: \" << t);\n\n\t\t// write trace to an R file\n\t\tLOG4CXX_INFO(logger, \"Writing trace to \" << traceFile);\n\t\ttrace.toRfile(traceFile, traceVar);\n\t\t\n\t\t\t\t\t// write computed factors to file\n\t\t\t\tif (outputRowFacFile.length() > 0) {\n\t\t\t\t\tLOG4CXX_INFO(logger, \"Writing row factors to \" << outputRowFacFile);\n\t\t\t\t\t//DenseMatrix w0;\n\t\t\t\t\t//unblock(dw, w0);\n\t\t\t\t\twriteMatrix(outputRowFacFile, w);\n\t\t\t\t}\n\t\t\t\tif (outputColFacFile.length() > 0) {\n\t\t\t\t\tLOG4CXX_INFO(logger, \"Writing column factors to \" << outputColFacFile);\n\t\t\t\t\t//DenseMatrixCM h0;\n\t\t\t\t\t//unblock(dh, h0);\n\t\t\t\t\twriteMatrix(outputColFacFile, h);\n\t\t\t\t}\n\t\t/**/\n\t}\n\n\tmfStop();\n\tmfFinalize();\n\n\treturn 0;\n}\n", "meta": {"hexsha": "10ea8e4a208e6d2c410099978bac7b40e045bc7f", "size": 11179, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tools/stratified-psgd.cc", "max_stars_repo_name": "wangshusen/DSGDpp", "max_stars_repo_head_hexsha": "d2b037f64f91e89800d12baff3c5d5aa57dbaa29", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2017-01-10T11:39:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-02T23:03:55.000Z", "max_issues_repo_path": "tools/stratified-psgd.cc", "max_issues_repo_name": "uma-pi1/DSGDpp", "max_issues_repo_head_hexsha": "d2b037f64f91e89800d12baff3c5d5aa57dbaa29", "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": "tools/stratified-psgd.cc", "max_forks_repo_name": "uma-pi1/DSGDpp", "max_forks_repo_head_hexsha": "d2b037f64f91e89800d12baff3c5d5aa57dbaa29", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-10-27T18:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T15:10:56.000Z", "avg_line_length": 32.1235632184, "max_line_length": 124, "alphanum_fraction": 0.6841399052, "num_tokens": 3311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2568684352445127}}
{"text": "/* buckets.cc\n   Jeremy Barnes, 12 September 2011\n   Copyright (c) 2011 Jeremy Barnes.  All rights reserved.\n   This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.\n\n   Refactored out buckets code.\n*/\n\n#include \"mldb/utils/buckets.h\"\n#include <iostream>\n#include <boost/utility.hpp>\n#include \"mldb/arch/format.h\"\n#include \"mldb/utils/floating_point.h\"\n#include \"mldb/utils/pair_utils.h\"\n#include \"mldb/arch/exception.h\"\n\nusing namespace std;\n\nnamespace MLDB {\n\nvoid\nbucket_dist_full(vector<float> & result, const BucketFreqs & freqs)\n{\n    bool debug = false;\n    \n    result.clear();\n    result.reserve(std::max<unsigned>(freqs.size() - 1, 0));\n    \n    /* We want the split points, which are half way in between the\n       current value and the next one. */\n    for (int i = 0;  i < (int)freqs.size() - 1;  ++i)\n        result.push_back(((freqs.begin() + i)->first\n                          + (freqs.begin() + i + 1)->first) * 0.5);\n\n    if (debug) {\n        for (BucketFreqs::const_iterator it = freqs.begin();  it != freqs.end();\n             ++it)\n            cerr << \"freqs[\" << it->first << \"] = \" << it->second << endl;\n\n        for (unsigned i = 0;  i < result.size();  ++i)\n            cerr << \"  bucket \" << i << \" has value \" << result[i]\n                 << \", \\t\" << (freqs.begin() + i)->second << \" values\" << endl;\n    }\n}\n\nvoid \nbucket_dist_reduced(vector<float> & result,\n                    const BucketFreqs & freqs,\n                    size_t num_buckets)\n{\n    bool debug = false;\n    //debug = (feature.type() == 22);\n\n    /* NOTE: this algorithm tends to overcluster well-distributed data.\n       It should probably be re-done to produce a number of buckets\n       closer to the required number.\n    */\n\n    /* Find good split points. */\n    double total = freqs.total();\n\n    vector<float> bucket_sizes;\n    result.clear();\n    result.reserve(num_buckets);\n\n    double num = 0;\n    float per_bucket = total / num_buckets;\n\n    /* Go through and look for the really big buckets.  We take these\n       out of the bucket size calculation as otherwise we end up with\n       too few buckets.  Note that this calculation is not exact\n       (since the bucket size becomes smaller after), but it should\n       fix up the most problematic cases.\n    */\n    int num_big_buckets = 0;\n    double num_in_big_buckets = 0.0;\n    for (BucketFreqs::const_iterator it = freqs.begin();\n         it != freqs.end();  ++it) {\n        float n = it->second;\n        if (n >= per_bucket) {\n            num_in_big_buckets += n;\n            num_big_buckets += 1;\n        }\n    }\n\n    if (num_buckets != num_big_buckets)\n        per_bucket = (total - num_in_big_buckets) /\n            (num_buckets - num_big_buckets);\n    \n    if (debug) {\n        cerr << \"  per_bucket before = \"\n             << total / num_buckets << endl;\n        cerr << \"  per_bucket = \" << per_bucket << endl;\n        cerr << \"  num_buckets = \" << num_buckets << endl;\n        cerr << \"  num_big_buckets = \" << num_big_buckets << endl;\n        cerr << \"  num_in_big_buckets = \" << num_in_big_buckets << endl;\n    }\n\n    //cerr << \"freqs.size() = \" << freqs.size() << endl;\n    int i = 0;\n    for (BucketFreqs::const_iterator it = freqs.begin();\n         it != freqs.end();  ++it, ++i) {\n        float n = it->second;\n        float v = it->first;\n        num += n;\n\n        if (debug && false)\n            cerr << \"i = \" << i << \" n = \" << n << \" v = \" << v\n                 << \" num = \" << num << endl;\n\n        /* We split if we have enough in our bucket, or if the next one\n           would have enough by itself. */\n        if (n >= per_bucket && num > n) {\n            /* Extra split, since this one had enough by itself. */\n            float val = (v + boost::prior(it)->first) / 2.0;\n            result.push_back(val);\n            bucket_sizes.push_back(num - n);\n            if (debug) \n                cerr << \"i = \" << i << \": split [1] at \"\n                     << format(\"val: %16.9f 0x%08x \", val,\n                               reinterpret_as_int(val))\n                     << format(\"v: %16.9f 0x%08x \", v,\n                               reinterpret_as_int(v))\n                     << format(\"prior: %16.9f 0x%08x \", boost::prior(it)->first,\n                               reinterpret_as_int(boost::prior(it)->first))\n                     << \" with \" << num - n\n                     << \" examples.\" << endl;\n            num -= n;\n        }\n        if (i < (int)freqs.size() - 1\n            && (num >= per_bucket || boost::next(it)->second >= per_bucket)) {\n            float val = (v + boost::next(it)->first) * 0.5f;\n\n            // If the two values are one ulp apart, then we need to make sure\n            // that it gets rounded up otherwise we will have two buckets\n            // with the same split value\n            if (val == v)\n                val = boost::next(it)->first;\n\n            result.push_back(val);\n            bucket_sizes.push_back(num);\n            if (debug)\n                cerr << \"i = \" << i << \": split [2] at \"\n                     << format(\"val: %16.9f 0x%08x \", val,\n                               reinterpret_as_int(val))\n                     << format(\"v: %16.9f 0x%08x \", v,\n                               reinterpret_as_int(v))\n                     << format(\"next: %16.9f 0x%08x \", boost::next(it)->first,\n                               reinterpret_as_int(boost::next(it)->first))\n                     << \" with \" << num\n                     << \" examples.\" << endl;\n            num = 0;\n        }\n    }\n\n    for (unsigned i = 1;  i < result.size();  ++i)\n        if (result[i] == result[i - 1])\n            throw Exception(\"two buckets with the same split point\");\n    \n    if (debug) {\n        for (unsigned i = 0;  i < result.size();  ++i)\n            cerr << format(\"  bucket %5d has value %16.9f 0x%08x, %8.1f values\",\n                           i, result[i], reinterpret_as_int(result[i]),\n                           bucket_sizes[i]) << endl;\n    }\n}\n\n#if 0\nconst Dataset_Index::Index_Entry::Bucket_Info &\nDataset_Index::Index_Entry::\ncreate_buckets(size_t num_buckets)\n{\n    check_used();\n    Guard guard(lock);\n\n    //cerr << \"create_buckets(\" << num_buckets << \")\" << endl;\n\n}\n#endif\n\nvoid get_freqs(BucketFreqs & result, std::vector<float> values)\n{\n    std::sort(values.begin(), values.end(), MLDB::safe_less<float>());\n\n    vector<pair<float, float> > freqs2;\n    freqs2.reserve(values.size());\n    \n    float last = -INFINITY;\n    int count = 0;\n            \n    for (unsigned i = 0;  i < values.size();  ++i) {\n        if (isnan(values[i]))\n            throw Exception(\"NaN in values\");\n            \n        if (i == 0) {\n            last = values[i];\n            count += 1;\n        }\n        else if (bit_equal(last, values[i]))\n            count += 1;\n        else {\n            freqs2.push_back(make_pair(last, count));\n            count = 1;\n            last = values[i];\n        }\n    }\n    freqs2.push_back(make_pair(last, count));\n\n    std::sort(freqs2.begin(), freqs2.end());\n    \n    result = BucketFreqs(freqs2.begin(), freqs2.end());\n} // namespace MLDB\n\nvoid bucket_dist(std::vector<float> & result,\n                 const BucketFreqs & freqs,\n                 size_t num_buckets)\n{\n    if (num_buckets >= freqs.size())\n        bucket_dist_full(result, freqs);\n    else\n        bucket_dist_reduced(result, freqs, num_buckets);\n}\n\nBucket_Info create_buckets(const std::vector<float> & values,\n                           size_t num_buckets)\n{\n    BucketFreqs freqs;\n    get_freqs(freqs, values);\n\n    Bucket_Info result;\n    bucket_dist(result.splits, freqs, num_buckets);\n\n    vector<int> bucket_count(result.splits.size() + 1);\n        \n    for (unsigned i = 0;  i < values.size();  ++i) {\n        float value = values[i];\n        int bucket = std::upper_bound(result.splits.begin(),\n                                      result.splits.end(), value)\n            - result.splits.begin();\n\n        bucket_count[bucket] += 1;\n\n        result.buckets.push_back(bucket);\n    }\n\n    return result;\n}\n\n} // namespace MLDB\n\n", "meta": {"hexsha": "4a5651aeed96f0b87ad11bb8120b3ea46b3285bd", "size": 8089, "ext": "cc", "lang": "C++", "max_stars_repo_path": "utils/buckets.cc", "max_stars_repo_name": "kstepanmpmg/mldb", "max_stars_repo_head_hexsha": "f78791cd34d01796705c0f173a14359ec1b2e021", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T12:39:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-29T12:39:34.000Z", "max_issues_repo_path": "utils/buckets.cc", "max_issues_repo_name": "tomzhang/mldb", "max_issues_repo_head_hexsha": "a09cf2d9ca454d1966b9e49ae69f2fe6bf571494", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-20T05:52:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-15T17:52:54.000Z", "max_forks_repo_path": "utils/buckets.cc", "max_forks_repo_name": "matebestek/mldb", "max_forks_repo_head_hexsha": "f78791cd34d01796705c0f173a14359ec1b2e021", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-23T20:03:38.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-23T20:03:38.000Z", "avg_line_length": 32.2270916335, "max_line_length": 80, "alphanum_fraction": 0.5189763877, "num_tokens": 2029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.25674588965443235}}
{"text": "/** em.cc                                                          -*- C++ -*-\n    Mathieu Marquis Bolduc, October 28th, 2015\n    Copyright (c) 2015 mldb.ai inc.  All rights reserved.\n\n    This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.\n\n    Guassian clustering procedure and functions.\n*/\n\n#include \"em_interface.h\"\n#include \"mldb/plugins/jml/em.h\"\n#include \"mldb/builtin/matrix.h\"\n#include \"mldb/core/mldb_engine.h\"\n#include \"mldb/engine/procedure_collection.h\"\n#include \"mldb/engine/function_collection.h\"\n#include \"mldb/utils/distribution.h\"\n#include <boost/multi_array.hpp>\n#include \"base/parallel.h\"\n#include \"mldb/utils/pair_utils.h\"\n#include \"mldb/arch/timers.h\"\n#include \"mldb/types/optional_description.h\"\n#include \"mldb/utils/vector_utils.h\"\n#include \"mldb/types/basic_value_descriptions.h\"\n#include \"mldb/sql/sql_expression.h\"\n#include \"mldb/core/analytics.h\"\n#include \"mldb/types/any_impl.h\"\n#include \"mldb/utils/smart_ptr_utils.h\"\n#include \"mldb/vfs/fs_utils.h\"\n#include \"mldb/builtin/sql_config_validator.h\"\n#include \"mldb/utils/log.h\"\n\n\nusing namespace std;\n\n\n\nnamespace MLDB {\n\nstd::vector<double> tovector(boost::multi_array<double, 2>& m)\n{\n    std::vector<double> embedding;\n    for(int i = 0; i < m.shape()[0]; i++)\n    {\n        for(int j = 0; j < m.shape()[1]; j++) {\n             embedding.push_back(m[i][j]); // multiply by elements on diagonal\n        }\n    }\n\n    return embedding;\n}\n\nDEFINE_STRUCTURE_DESCRIPTION(EMConfig);\n\nEMConfigDescription::\nEMConfigDescription()\n{\n    Optional<PolyConfigT<Dataset> > optional;\n    optional.emplace(PolyConfigT<Dataset>().\n                     withType(EMConfig::defaultOutputDatasetType));\n\n    addField(\"trainingData\", &EMConfig::trainingData,\n             \"Specification of the data for input to the 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\", &EMConfig::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\", &EMConfig::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             PolyConfigT<Dataset>().withType(\"embedding\"));\n    addField(\"modelFileUrl\", &EMConfig::modelFileUrl,\n             \"URL where the model file (with extension '.gs') should be saved. \"\n             \"This file can be loaded by a function of type 'gaussianclustering' to apply \"\n             \"the trained model to new data. \"\n             \"If someone is only interested in how the training input is clustered \"\n             \"then the parameter can be omitted and the outputDataset param can \"\n             \"be provided instead.\");\n    addField(\"numInputDimensions\", &EMConfig::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\", &EMConfig::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\", &EMConfig::maxIterations,\n             \"Maximum number of iterations to perform.  If no convergance is \"\n             \"reached within this number of iterations, the current clustering \"\n             \"will be returned.\", 100);\n    addField(\"functionName\", &EMConfig::functionName,\n             \"If specified, a function of this name will be created using \"\n             \"the training result.\");\n    addParent<ProcedureConfig>();\n\n    onPostValidate = validateFunction<EMConfig>();\n}\n\n/*****************************************************************************/\n/* EM PROCEDURE                                                           */\n/*****************************************************************************/\n\nEMProcedure::\nEMProcedure(MldbEngine * owner,\n               PolyConfig config,\n               const std::function<bool (const Json::Value &)> & onProgress)\n    : Procedure(owner)\n{\n    this->emConfig = config.params.convert<EMConfig>();\n}\n\nAny\nEMProcedure::\ngetStatus() const\n{\n    return Any();\n\n}\n\nRunOutput\nEMProcedure::\nrun(const ProcedureRunConfig & run,\n    const std::function<bool (const Json::Value &)> & onProgress) const\n{\n    auto runProcConf = applyRunConfOverProcConf(emConfig, run);\n\n    auto onProgress2 = [&] (const Json::Value & progress)\n        {\n            Json::Value value;\n            value[\"dataset\"] = progress;\n            return onProgress(value);\n        };\n\n    if (!runProcConf.modelFileUrl.empty()) {\n        checkWritability(runProcConf.modelFileUrl.toDecodedString(),\n                         \"modelFileUrl\");\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    auto rows = embeddingOutput.first;\n    std::vector<KnownColumn> & vars = embeddingOutput.second;\n\n    std::vector<distribution<double> > vecs;\n\n    for (unsigned i = 0;  i < rows.size();  ++i) {\n        vecs.emplace_back(distribution<double>(std::get<2>(rows[i]).begin(),\n                                                   std::get<2>(rows[i]).end()));\n    }\n\n    if (vecs.size() == 0)\n        throw AnnotatedException(400, \"Gaussian clustering 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::EstimationMaximisation em;\n    vector<int> inCluster;\n\n    int numClusters = emConfig.numClusters;\n    int numIterations = emConfig.maxIterations;\n\n    DEBUG_MSG(logger) << \"EM training start\";\n    em.train(vecs, inCluster, numClusters, numIterations, 0);\n    DEBUG_MSG(logger) << \"EM training end\";\n\n    // Let the model know about its column names\n    std::vector<ColumnPath> columnNames;\n    for (auto & v: vars) {\n        columnNames.push_back(v.columnName);\n        em.columnNames.push_back(v.columnName.toUtf8String());\n    }\n\n    // output\n\n    bool saved = false;\n    if (!runProcConf.modelFileUrl.empty()) {\n        try {\n            makeUriDirectory(\n                runProcConf.modelFileUrl.toDecodedString());\n            em.save(runProcConf.modelFileUrl.toDecodedString());\n            saved = true;\n        }\n        catch (const std::exception & exc) {\n            throw AnnotatedException(400, \"Error saving gaussian clustering model 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 = EMConfig::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.type != \"\" || emConfig.centroids.id != \"\") {\n\n        auto centroids = createDataset(engine, runProcConf.centroids, onProgress2, true /*overwrite*/);\n\n        Date applyDate = Date::now();\n\n        for (unsigned i = 0;  i < em.clusters.size();  ++i) {\n            auto & cluster = em.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            auto flatmatrix = tovector(cluster.covarianceMatrix);\n\n            for (unsigned j = 0;  j < flatmatrix.size();  ++j) {\n                cols.emplace_back(ColumnPath(MLDB::format(\"c%02d\", j)), flatmatrix[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            EMFunctionConfig funcConf;\n            funcConf.modelFileUrl = runProcConf.modelFileUrl;\n            \n            PolyConfig emPC;\n            emPC.type = \"gaussianclustering\";\n            emPC.id = runProcConf.functionName;\n            emPC.params = funcConf;\n            obtainFunction(engine, emPC, onProgress);\n        } else {\n            throw AnnotatedException(400, \"Can't create gaussian clustering 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(EMFunctionConfig);\n\nEMFunctionConfigDescription::\nEMFunctionConfigDescription()\n{\n    addField(\"modelFileUrl\", &EMFunctionConfig::modelFileUrl,\n             \"URL of the model file (with extension '.gs') to load. \"\n             \"This file is created by a procedure of type 'gaussianclustering.train'.\");\n\n    onPostValidate = [] (EMFunctionConfig * 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/* EM FUNCTION                                                               */\n/*****************************************************************************/\n\nDEFINE_STRUCTURE_DESCRIPTION(EMInput);\n\nEMInputDescription::EMInputDescription()\n{\n    addField(\"embedding\", &EMInput::embedding,\n             \"Values to be assigned to a cluster.\");\n}\n\nDEFINE_STRUCTURE_DESCRIPTION(EMOutput);\n\nEMOutputDescription::EMOutputDescription()\n{\n    addField(\"cluster\", &EMOutput::cluster,\n             \"Cluster corresponding to the input values.\");\n}\n\n\nstruct EMFunction::Impl {\n    ML::EstimationMaximisation em;\n    std::vector<ColumnPath> columnNames;\n\n    Impl(const Url & modelFileUrl) {\n        em.load(modelFileUrl.toDecodedString());\n        for (auto & c: em.columnNames)\n            this->columnNames.push_back(PathElement(c));\n    }\n};\n\nEMFunction::\nEMFunction(MldbEngine * owner,\n            PolyConfig config,\n            const std::function<bool (const Json::Value &)> & onProgress)\n    : BaseT(owner, config)\n{  \n\n    functionConfig = config.params.convert<EMFunctionConfig>();\n\n    impl.reset(new Impl(functionConfig.modelFileUrl));\n\n    dimension = impl->em.clusters[0].centroid.size();\n\n    auto logger = MLDB::getMldbLog<EMFunction>();\n    DEBUG_MSG(logger) << \"got \" << impl->em.clusters.size()\n         << \" clusters with \" << dimension\n         << \"values\";\n}\n\nstruct EMFunctionApplier: public FunctionApplierT<EMInput, EMOutput> {\n    EMFunctionApplier(const EMFunction * owner,\n                      const std::shared_ptr<ExpressionValueInfo> & input)\n        : FunctionApplierT<EMInput, EMOutput>(owner)\n    {\n        info = owner->getFunctionInfo();\n        extract = input->extractDoubleEmbedding(owner->impl->columnNames);\n    }\n\n    ExpressionValueInfo::ExtractDoubleEmbeddingFunction extract;\n};\n\nstd::unique_ptr<FunctionApplierT<EMInput, EMOutput> >\nEMFunction::\nbindT(SqlBindingScope & outerContext,\n      const std::vector<std::shared_ptr<ExpressionValueInfo> > & input) const\n{\n    if (input.size() != 1)\n        throw AnnotatedException(400, \"EM function requires a single input\");\n    return std::unique_ptr<EMFunctionApplier>\n        (new EMFunctionApplier(this, input.at(0)));\n}\n\nEMOutput \nEMFunction::\napplyT(const ApplierT & applier_, EMInput input_) const\n{\n    // Extract an embedding with the given column names\n    ExpressionValue storage;\n\n    const auto * downcast\n            = dynamic_cast<const EMFunctionApplier *>(&applier_);\n\n    distribution<double> input = downcast->extract(input_.embedding);\n    Date ts = input_.embedding.getEffectiveTimestamp();\n\n    int bestCluster = impl->em.assign(input);\n\n    return {ExpressionValue(bestCluster, ts)};\n}\n\nnamespace {\n\nRegisterProcedureType<EMProcedure, EMConfig>\nregEM(builtinPackage(),\n      \"Gaussian clustering algorithm using Estimation Maximization on Gaussian Mixture Models\",\n      \"procedures/EMProcedure.md.html\",\n      nullptr /* static route */,\n      { MldbEntity::INTERNAL_ENTITY });\n\nRegisterFunctionType<EMFunction, EMFunctionConfig>\nregEMFunction(builtinPackage(), \"gaussianclustering\",\n              \"Apply an gaussian clustering to new data\",\n              \"functions/EM.md.html\",\n              nullptr /* static route */,\n              { MldbEntity::INTERNAL_ENTITY });\n\n} // file scope\n\n} // namespace MLDB\n\n", "meta": {"hexsha": "1509bcc1c52470b6b695b5055a8175aa7af2a7b4", "size": 14036, "ext": "cc", "lang": "C++", "max_stars_repo_path": "plugins/jml/em_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/em_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/em_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.0024937656, "max_line_length": 103, "alphanum_fraction": 0.604445711, "num_tokens": 3024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.25674050566027795}}
{"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#include \"slha_io.hpp\"\n#include \"wrappers.hpp\"\n#include \"lowe.h\"\n#include \"linalg.h\"\n#include \"ew_input.hpp\"\n#include \"physical_input.hpp\"\n#include \"spectrum_generator_settings.hpp\"\n\n#include <fstream>\n#include <algorithm>\n#include <string>\n#include <boost/bind.hpp>\n\nnamespace flexiblesusy {\n\nSLHA_io::SLHA_io()\n   : data()\n   , modsel()\n{\n}\n\nvoid SLHA_io::clear()\n{\n   data.clear();\n   modsel.clear();\n}\n\nvoid SLHA_io::convert_symmetric_fermion_mixings_to_slha(double&,\n                                                        Eigen::Matrix<double, 1, 1>&)\n{\n}\n\n/**\n * @param m mass\n * @param z 1x1 mixing matrix\n */\nvoid SLHA_io::convert_symmetric_fermion_mixings_to_slha(double& m,\n                                                        Eigen::Matrix<std::complex<double>, 1, 1>& z)\n{\n   // check if 1st row contains non-zero imaginary parts\n   if (!is_zero(Abs(Im(z(0,0))))) {\n      z(0,0) *= std::complex<double>(0.0,1.0);\n      m *= -1;\n#ifdef ENABLE_DEBUG\n      if (!is_zero(Abs(Im(z(0,0))))) {\n         WARNING(\"Element (0,0) of the following fermion mixing matrix\"\n                 \" contains entries which have non-zero real and imaginary\"\n                 \" parts:\\nZ = \" << z);\n      }\n#endif\n   }\n}\n\nvoid SLHA_io::convert_symmetric_fermion_mixings_to_hk(double&,\n                                                      Eigen::Matrix<double, 1, 1>&)\n{\n}\n\n/**\n * @param m mass\n * @param z 1x1 mixing matrix\n */\nvoid SLHA_io::convert_symmetric_fermion_mixings_to_hk(double& m,\n                                                      Eigen::Matrix<std::complex<double>, 1, 1>& z)\n{\n   if (m < 0.) {\n      z(0,0) *= std::complex<double>(0.0,1.0);\n      m *= -1;\n   }\n}\n\nbool SLHA_io::block_exists(const std::string& block_name) const\n{\n   return data.find(block_name) != data.cend();\n}\n\nstd::string SLHA_io::to_lower(const std::string& str)\n{\n   std::string lower(str.size(), ' ');\n   std::transform(str.begin(), str.end(), lower.begin(), ::tolower);\n   return lower;\n}\n\n/**\n * @brief reads from source\n *\n * If source is \"-\", then read_from_stream() is called.  Otherwise,\n * read_from_file() is called.\n *\n * @param source string that specifies the source\n */\nvoid SLHA_io::read_from_source(const std::string& source)\n{\n   if (source == \"-\")\n      read_from_stream(std::cin);\n   else\n      read_from_file(source);\n}\n\n/**\n * @brief opens SLHA input file and reads the content\n * @param file_name SLHA input file name\n */\nvoid SLHA_io::read_from_file(const std::string& file_name)\n{\n   std::ifstream ifs(file_name);\n   if (ifs.good()) {\n      data.clear();\n      data.read(ifs);\n   } else {\n      std::ostringstream msg;\n      msg << \"cannot read SLHA file: \\\"\" << file_name << \"\\\"\";\n      throw ReadError(msg.str());\n   }\n}\n\n/**\n * @brief reads SLHA data from a stream\n * @param istr input stream\n */\nvoid SLHA_io::read_from_stream(std::istream& istr)\n{\n   data.read(istr);\n}\n\nvoid SLHA_io::read_modsel()\n{\n   SLHA_io::Tuple_processor modsel_processor\n      = boost::bind(&SLHA_io::process_modsel_tuple, boost::ref(modsel), _1, _2);\n\n   read_block(\"MODSEL\", modsel_processor);\n}\n\nvoid SLHA_io::fill(softsusy::QedQcd& qedqcd) const\n{\n   CKM_wolfenstein ckm_wolfenstein;\n   PMNS_parameters pmns_parameters;\n\n   SLHA_io::Tuple_processor sminputs_processor\n      = boost::bind(&SLHA_io::process_sminputs_tuple, boost::ref(qedqcd), _1, _2);\n\n   read_block(\"SMINPUTS\", sminputs_processor);\n\n   if (modsel.quark_flavour_violated) {\n      SLHA_io::Tuple_processor vckmin_processor\n         = boost::bind(&SLHA_io::process_vckmin_tuple, boost::ref(ckm_wolfenstein), _1, _2);\n\n      read_block(\"VCKMIN\", vckmin_processor);\n   }\n\n   if (modsel.lepton_flavour_violated) {\n      SLHA_io::Tuple_processor upmnsin_processor\n         = boost::bind(&SLHA_io::process_upmnsin_tuple, boost::ref(pmns_parameters), _1, _2);\n\n      read_block(\"UPMNSIN\", upmnsin_processor);\n   }\n\n   // fill CKM parameters in qedqcd\n   CKM_parameters ckm_parameters;\n   ckm_parameters.set_from_wolfenstein(\n      ckm_wolfenstein.lambdaW,\n      ckm_wolfenstein.aCkm,\n      ckm_wolfenstein.rhobar,\n      ckm_wolfenstein.etabar);\n   qedqcd.setCKM(ckm_parameters);\n\n   // fill PMNS parameters in qedqcd\n   qedqcd.setPMNS(pmns_parameters);\n}\n\n/**\n * Fill struct of extra physical input parameters from SLHA object\n * (FlexibleSUSYInput block)\n *\n * @param input struct of physical input parameters\n */\nvoid SLHA_io::fill(Physical_input& input) const\n{\n   SLHA_io::Tuple_processor processor\n      = boost::bind(&SLHA_io::process_flexiblesusyinput_tuple, boost::ref(input), _1, _2);\n\n   read_block(\"FlexibleSUSYInput\", processor);\n}\n\n/**\n * Fill struct of spectrum generator settings from SLHA object\n * (FlexibleSUSY block)\n *\n * @param settings struct of spectrum generator settings\n */\nvoid SLHA_io::fill(Spectrum_generator_settings& settings) const\n{\n   SLHA_io::Tuple_processor flexiblesusy_processor\n      = boost::bind(&SLHA_io::process_flexiblesusy_tuple, boost::ref(settings), _1, _2);\n\n   read_block(\"FlexibleSUSY\", flexiblesusy_processor);\n}\n\n/**\n * Applies processor to each (key, value) pair of a SLHA block.\n * Non-data lines are ignored.\n *\n * @param block_name block name\n * @param processor tuple processor to be applied\n *\n * @return scale (or 0 if no scale is defined)\n */\ndouble SLHA_io::read_block(const std::string& block_name, const Tuple_processor& processor) const\n{\n   SLHAea::Coll::const_iterator block =\n      data.find(data.cbegin(), data.cend(), block_name);\n\n   double scale = 0.;\n\n   while (block != data.cend()) {\n      for (SLHAea::Block::const_iterator line = block->cbegin(),\n              end = block->cend(); line != end; ++line) {\n         if (!line->is_data_line()) {\n            // read scale from block definition\n            if (line->size() > 3 &&\n                to_lower((*line)[0]) == \"block\" && (*line)[2] == \"Q=\")\n               scale = convert_to<double>((*line)[3]);\n            continue;\n         }\n\n         if (line->size() >= 2) {\n            const int key = convert_to<int>((*line)[0]);\n            const double value = convert_to<double>((*line)[1]);\n            processor(key, value);\n         }\n      }\n\n      ++block;\n      block = data.find(block, data.cend(), block_name);\n   }\n\n   return scale;\n}\n\n/**\n * Fills an entry from a SLHA block\n *\n * @param block_name block name\n * @param entry entry to be filled\n *\n * @return scale (or 0 if no scale is defined)\n */\ndouble SLHA_io::read_block(const std::string& block_name, double& entry) const\n{\n   SLHAea::Coll::const_iterator block =\n      data.find(data.cbegin(), data.cend(), block_name);\n\n   double scale = 0.;\n\n   while (block != data.cend()) {\n      for (SLHAea::Block::const_iterator line = block->cbegin(),\n              end = block->cend(); line != end; ++line) {\n         if (!line->is_data_line()) {\n            // read scale from block definition\n            if (line->size() > 3 &&\n                to_lower((*line)[0]) == \"block\" && (*line)[2] == \"Q=\")\n               scale = convert_to<double>((*line)[3]);\n            continue;\n         }\n\n         if (line->size() >= 1)\n            entry = convert_to<double>((*line)[0]);\n      }\n\n      ++block;\n      block = data.find(block, data.cend(), block_name);\n   }\n\n   return scale;\n}\n\ndouble SLHA_io::read_entry(const std::string& block_name, int key) const\n{\n   SLHAea::Coll::const_iterator block =\n      data.find(data.cbegin(), data.cend(), block_name);\n\n   double entry = 0.;\n   const SLHAea::Block::key_type keys(1, ToString(key));\n   SLHAea::Block::const_iterator line;\n\n   while (block != data.cend()) {\n      line = block->find(keys);\n\n      if (line != block->end() && line->is_data_line() && line->size() > 1)\n         entry = convert_to<double>(line->at(1));\n\n      ++block;\n      block = data.find(block, data.cend(), block_name);\n   }\n\n   return entry;\n}\n\n/**\n * Reads scale definition from SLHA block.\n *\n * @param block_name block name\n *\n * @return scale (or 0 if no scale is defined)\n */\ndouble SLHA_io::read_scale(const std::string& block_name) const\n{\n   if (!block_exists(block_name))\n      return 0.;\n\n   double scale = 0.;\n\n   for (SLHAea::Block::const_iterator line = data.at(block_name).cbegin(),\n        end = data.at(block_name).cend(); line != end; ++line) {\n      if (!line->is_data_line()) {\n         if (line->size() > 3 &&\n             to_lower((*line)[0]) == \"block\" && (*line)[2] == \"Q=\")\n            scale = convert_to<double>((*line)[3]);\n         break;\n      }\n   }\n\n   return scale;\n}\n\nvoid SLHA_io::set_block(const std::ostringstream& lines, Position position)\n{\n   SLHAea::Block block;\n   block.str(lines.str());\n   data.erase(block.name());\n   if (position == front)\n      data.push_front(block);\n   else\n      data.push_back(block);\n}\n\nvoid SLHA_io::set_block(const std::string& lines, Position position)\n{\n   set_block(std::ostringstream(lines), position);\n}\n\nvoid SLHA_io::set_blocks(const std::vector<std::string>& blocks, Position position)\n{\n   for (std::vector<std::string>::const_iterator it = blocks.begin(),\n           end = blocks.end(); it != end; it++)\n      set_block(*it, position);\n}\n\n/**\n * This function treats a given scalar as 1x1 matrix.  Such a case is\n * not defined in the SLHA standard, but we still handle it to avoid\n * problems.\n */\nvoid SLHA_io::set_block(const std::string& name, double value,\n                        const std::string& symbol, double scale)\n{\n   std::ostringstream ss;\n   ss << \"Block \" << name;\n   if (scale != 0.)\n      ss << \" Q= \" << FORMAT_SCALE(scale);\n   ss << '\\n'\n      << boost::format(mixing_matrix_formatter) % 1 % 1 % value % symbol;\n\n   set_block(ss);\n}\n\nvoid SLHA_io::set_block(const std::string& name, const softsusy::DoubleMatrix& matrix,\n                        const std::string& symbol, double scale)\n{\n   std::ostringstream ss;\n   ss << \"Block \" << name;\n   if (scale != 0.)\n      ss << \" Q= \" << FORMAT_SCALE(scale);\n   ss << '\\n';\n\n   for (int i = 1; i <= matrix.displayRows(); ++i)\n      for (int k = 1; k <= matrix.displayCols(); ++k) {\n         ss << boost::format(mixing_matrix_formatter) % i % k % matrix(i,k)\n            % (symbol + \"(\" + ToString(i) + \",\" + ToString(k) + \")\");\n      }\n\n   set_block(ss);\n}\n\nvoid SLHA_io::set_block(const std::string& name, const softsusy::ComplexMatrix& matrix,\n                        const std::string& symbol, double scale)\n{\n   std::ostringstream ss;\n   ss << \"Block \" << name;\n   if (scale != 0.)\n      ss << \" Q= \" << FORMAT_SCALE(scale);\n   ss << '\\n';\n\n   for (int i = 1; i <= matrix.displayRows(); ++i)\n      for (int k = 1; k <= matrix.displayCols(); ++k) {\n         ss << boost::format(mixing_matrix_formatter) % i % k\n            % Re(matrix(i,k))\n            % (\"Re(\" + symbol + \"(\" + ToString(i) + \",\" + ToString(k) + \"))\");\n      }\n\n   set_block(ss);\n}\n\nvoid SLHA_io::set_sminputs(const softsusy::QedQcd& qedqcd_)\n{\n   using namespace softsusy;\n   softsusy::QedQcd qedqcd(qedqcd_);\n   std::ostringstream ss;\n\n   const double alphaEmInv = 1./qedqcd.displayAlpha(ALPHA);\n\n   ss << \"Block SMINPUTS\\n\";\n   ss << FORMAT_ELEMENT( 1, alphaEmInv                   , \"alpha^(-1) SM MSbar(MZ)\");\n   ss << FORMAT_ELEMENT( 2, qedqcd.displayFermiConstant(), \"G_Fermi\");\n   ss << FORMAT_ELEMENT( 3, qedqcd.displayAlpha(ALPHAS)  , \"alpha_s(MZ) SM MSbar\");\n   ss << FORMAT_ELEMENT( 4, qedqcd.displayPoleMZ()       , \"MZ(pole)\");\n   ss << FORMAT_ELEMENT( 5, qedqcd.displayMbMb()         , \"mb(mb) SM MSbar\");\n   ss << FORMAT_ELEMENT( 6, qedqcd.displayPoleMt()       , \"mtop(pole)\");\n   ss << FORMAT_ELEMENT( 7, qedqcd.displayPoleMtau()     , \"mtau(pole)\");\n   ss << FORMAT_ELEMENT( 8, qedqcd.displayNeutrinoPoleMass(3), \"mnu3(pole)\");\n   ss << FORMAT_ELEMENT( 9, qedqcd.displayPoleMW()       , \"MW(pole)\");\n   ss << FORMAT_ELEMENT(11, qedqcd.displayPoleMel()      , \"melectron(pole)\");\n   ss << FORMAT_ELEMENT(12, qedqcd.displayNeutrinoPoleMass(1), \"mnu1(pole)\");\n   ss << FORMAT_ELEMENT(13, qedqcd.displayPoleMmuon()    , \"mmuon(pole)\");\n   ss << FORMAT_ELEMENT(14, qedqcd.displayNeutrinoPoleMass(2), \"mnu2(pole)\");\n\n   // recalculate mc(mc)^MS-bar\n   double mc = qedqcd.displayMass(mCharm);\n   qedqcd.runto(mc);\n   mc = qedqcd.displayMass(mCharm);\n\n   // recalculate mu(2 GeV)^MS-bar, md(2 GeV)^MS-bar, ms^MS-bar(2 GeV)\n   qedqcd.runto(2.0);\n   ss << FORMAT_ELEMENT(21, qedqcd.displayMass(mDown)    , \"md\");\n   ss << FORMAT_ELEMENT(22, qedqcd.displayMass(mUp)      , \"mu\");\n   ss << FORMAT_ELEMENT(23, qedqcd.displayMass(mStrange) , \"ms\");\n   ss << FORMAT_ELEMENT(24, mc                           , \"mc\");\n\n   set_block(ss);\n}\n\nvoid SLHA_io::write_to_file(const std::string& file_name)\n{\n   std::ofstream ofs(file_name);\n   write_to_stream(ofs);\n}\n\nvoid SLHA_io::write_to_stream(std::ostream& ostr)\n{\n   if (ostr.good())\n      ostr << data;\n   else\n      ERROR(\"cannot write SLHA file\");\n}\n\n/**\n * fill Modsel struct from given key - value pair\n *\n * @param modsel MODSEL data\n * @param key SLHA key in MODSEL\n * @param value value corresponding to key\n */\nvoid SLHA_io::process_modsel_tuple(Modsel& modsel, int key, double value)\n{\n   switch (key) {\n   case 1: // SUSY breaking model (defined in FlexibleSUSY model file)\n   case 3: // SUSY model (defined in SARAH model file)\n   case 4: // R-parity violation (defined in SARAH model file)\n   case 5: // CP-parity violation (defined in SARAH model file)\n   case 11:\n   case 21:\n      WARNING(\"Key \" << key << \" in Block MODSEL currently not supported\");\n      break;\n   case 6: // Flavour violation (defined in SARAH model file)\n   {\n      const int ivalue = Round(value);\n\n      if (ivalue < 0 || ivalue > 3)\n         WARNING(\"Value \" << ivalue << \" in MODSEL block entry 6 out of range\");\n\n      modsel.quark_flavour_violated = ivalue & 0x1;\n      modsel.lepton_flavour_violated = ivalue & 0x2;\n   }\n      break;\n   case 12:\n      modsel.parameter_output_scale = value;\n      break;\n   default:\n      WARNING(\"Unrecognized entry in block MODSEL: \" << key);\n      break;\n   }\n}\n\n/**\n * fill qedqcd from given key - value pair\n *\n * @param qedqcd low-energy data set\n * @param key SLHA key in SMINPUTS\n * @param value value corresponding to key\n */\nvoid SLHA_io::process_sminputs_tuple(softsusy::QedQcd& qedqcd, int key, double value)\n{\n   using namespace softsusy;\n\n   switch (key) {\n   case 1:\n      qedqcd.setAlpha(ALPHA, 1.0 / value);\n      qedqcd.setAlphaEmInput(1.0 / value);\n      break;\n   case 2:\n      qedqcd.setFermiConstant(value);\n      break;\n   case 3:\n      qedqcd.setAlpha(ALPHAS, value);\n      qedqcd.setAlphaSInput(value);\n      break;\n   case 4:\n      qedqcd.setPoleMZ(value);\n      qedqcd.setMu(value);\n      softsusy::MZ = value;\n      break;\n   case 5:\n      qedqcd.setMass(mBottom, value);\n      qedqcd.setMbMb(value);\n      break;\n   case 6:\n      qedqcd.setPoleMt(value);\n      break;\n   case 7:\n      qedqcd.setMass(mTau, value);\n      qedqcd.setPoleMtau(value);\n      break;\n   case 8:\n      qedqcd.setNeutrinoPoleMass(3, value);\n      break;\n   case 9:\n      qedqcd.setPoleMW(value);\n      break;\n   case 11:\n      qedqcd.setMass(mElectron, value);\n      qedqcd.setPoleMel(value);\n      break;\n   case 12:\n      qedqcd.setNeutrinoPoleMass(1, value);\n      break;\n   case 13:\n      qedqcd.setMass(mMuon, value);\n      qedqcd.setPoleMmuon(value);\n      break;\n   case 14:\n      qedqcd.setNeutrinoPoleMass(2, value);\n      break;\n   case 21:\n      qedqcd.setMass(mDown, value);\n      qedqcd.setMd2GeV(value);\n      break;\n   case 22:\n      qedqcd.setMass(mUp, value);\n      qedqcd.setMu2GeV(value);\n      break;\n   case 23:\n      qedqcd.setMass(mStrange, value);\n      qedqcd.setMs2GeV(value);\n      break;\n   case 24:\n      qedqcd.setMass(mCharm, value);\n      qedqcd.setMcMc(value);\n      break;\n   default:\n      WARNING(\"Unrecognized entry in block SMINPUTS: \" << key);\n      break;\n   }\n}\n\nvoid SLHA_io::process_flexiblesusy_tuple(Spectrum_generator_settings& settings,\n                                         int key, double value)\n{\n   if (0 <= key && key < static_cast<int>(Spectrum_generator_settings::NUMBER_OF_OPTIONS)) {\n      settings.set((Spectrum_generator_settings::Settings)key, value);\n   } else {\n      WARNING(\"Unrecognized entry in block FlexibleSUSY: \" << key);\n   }\n}\n\nvoid SLHA_io::process_flexiblesusyinput_tuple(\n   Physical_input& input,\n   int key, double value)\n{\n   if (0 <= key && key < static_cast<int>(Physical_input::NUMBER_OF_INPUT_PARAMETERS)) {\n      input.set((Physical_input::Input)key, value);\n   } else {\n      WARNING(\"Unrecognized entry in block FlexibleSUSYInput: \" << key);\n   }\n}\n\n/**\n * fill CKM_wolfenstein from given key - value pair\n *\n * @param ckm_wolfenstein Wolfenstein parameters\n * @param key SLHA key in SMINPUTS\n * @param value value corresponding to key\n */\nvoid SLHA_io::process_vckmin_tuple(CKM_wolfenstein& ckm_wolfenstein, int key, double value)\n{\n   switch (key) {\n   case 1:\n      ckm_wolfenstein.lambdaW = value;\n      break;\n   case 2:\n      ckm_wolfenstein.aCkm = value;\n      break;\n   case 3:\n      ckm_wolfenstein.rhobar = value;\n      break;\n   case 4:\n      ckm_wolfenstein.etabar = value;\n      break;\n   default:\n      WARNING(\"Unrecognized entry in block VCKMIN: \" << key);\n      break;\n   }\n}\n\n/**\n * fill PMNS_parameters from given key - value pair\n *\n * @param pmns_parameters PMNS matrix parameters\n * @param key SLHA key in SMINPUTS\n * @param value value corresponding to key\n */\nvoid SLHA_io::process_upmnsin_tuple(PMNS_parameters& pmns_parameters, int key, double value)\n{\n   switch (key) {\n   case 1:\n      pmns_parameters.theta_12 = value;\n      break;\n   case 2:\n      pmns_parameters.theta_23 = value;\n      break;\n   case 3:\n      pmns_parameters.theta_13 = value;\n      break;\n   case 4:\n      pmns_parameters.delta = value;\n      break;\n   case 5:\n      pmns_parameters.alpha_1 = value;\n   case 6:\n      pmns_parameters.alpha_2 = value;\n      break;\n   default:\n      WARNING(\"Unrecognized entry in block UPMNSIN: \" << key);\n      break;\n   }\n}\n\n} // namespace flexiblesusy\n", "meta": {"hexsha": "6f5f1a0fa974b883b8637407c2404c4088eee4de", "size": 18761, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/src/slha_io.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/src/slha_io.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/src/slha_io.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": 27.7529585799, "max_line_length": 101, "alphanum_fraction": 0.6184105325, "num_tokens": 5229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2566025040195623}}
{"text": "/*\n    Copyright 2016 Emanuele Vespa, Imperial College London\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#ifndef OCTANT_OPS_HPP\n#define OCTANT_OPS_HPP\n#include \"octree_defines.h\"\n#include \"utils/math_utils.h\"\n#include \"utils/morton_utils.hpp\"\n\n#include <supereight/shared/commons.h>\n\n#include <Eigen/Dense>\n#include <bitset>\n#include <iostream>\n\nnamespace se {\nnamespace keyops {\n\nSE_DEVICE_FUNC\ninline se::key_t code(const se::key_t key) { return key & ~SCALE_MASK; }\n\nSE_DEVICE_FUNC\ninline int level(const se::key_t key) { return key & SCALE_MASK; }\n\nSE_DEVICE_ONLY_FUNC\ninline se::key_t encode(const int x, const int y, const int z, const int level,\n    const int max_depth) {\n    const int offset = MAX_BITS - max_depth + level - 1;\n    return (compute_morton(x, y, z) & MASK[offset] & ~SCALE_MASK) | level;\n}\n\nSE_DEVICE_FUNC\ninline Eigen::Vector3i decode(const se::key_t key) {\n    return unpack_morton(key & ~SCALE_MASK);\n}\n} // namespace keyops\n\n/*\n * Algorithm 5 of p4est paper: https://epubs.siam.org/doi/abs/10.1137/100791634\n */\nSE_DEVICE_FUNC\ninline Eigen::Vector3i face_neighbour(const se::key_t o,\n    const unsigned int face, const unsigned int l,\n    const unsigned int max_depth) {\n    Eigen::Vector3i coords  = se::keyops::decode(o);\n    const unsigned int side = 1 << (max_depth - l);\n    coords(0) = coords(0) + ((face == 0) ? -side : (face == 1) ? side : 0);\n    coords(1) = coords(1) + ((face == 2) ? -side : (face == 3) ? side : 0);\n    coords(2) = coords(2) + ((face == 4) ? -side : (face == 5) ? side : 0);\n    return {coords(0), coords(1), coords(2)};\n}\n\n/*\n * \\brief Return true if octant is a descendant of ancestor\n * \\param octant\n * \\param ancestor\n * \\param max_depth max depth of the tree on which the octant lives\n */\nSE_DEVICE_ONLY_FUNC\ninline bool descendant(\n    se::key_t octant, se::key_t ancestor, const int max_depth) {\n    const int level = se::keyops::level(ancestor);\n    const int idx   = MAX_BITS - max_depth + level - 1;\n    ancestor        = se::keyops::code(ancestor);\n    octant          = se::keyops::code(octant) & MASK[idx];\n    return (ancestor ^ octant) == 0;\n}\n\n/*\n * \\brief Computes the parent's morton code of a given octant\n * \\param octant\n * \\param max_depth max depth of the tree on which the octant lives\n */\nSE_DEVICE_ONLY_FUNC\ninline se::key_t parent(const se::key_t& octant, const int max_depth) {\n    const int level = se::keyops::level(octant) - 1;\n    const int idx   = MAX_BITS - max_depth + level - 1;\n    return (octant & MASK[idx]) | level;\n}\n\n/*\n * \\brief Computes the octants's id in its local brotherhood\n * \\param octant\n * \\param level of octant\n * \\param max_depth max depth of the tree on which the octant lives\n */\nSE_DEVICE_FUNC\ninline int child_id(se::key_t octant, const int level, const int max_depth) {\n    int shift = max_depth - level;\n    octant    = se::keyops::code(octant) >> shift * 3;\n    int idx   = (octant & 0x01) | (octant & 0x02) | (octant & 0x04);\n    return idx;\n}\n\n/*\n * \\brief Computes the octants's corner which is not shared with its siblings\n * \\param octant\n * \\param level of octant\n * \\param max_depth max depth of the tree on which the octant lives\n */\nSE_DEVICE_FUNC\ninline Eigen::Vector3i far_corner(\n    const se::key_t octant, const int level, const int max_depth) {\n    const unsigned int side           = 1 << (max_depth - level);\n    const int idx                     = child_id(octant, level, max_depth);\n    const Eigen::Vector3i coordinates = se::keyops::decode(octant);\n    return Eigen::Vector3i(coordinates(0) + (idx & 1) * side,\n        coordinates(1) + ((idx & 2) >> 1) * side,\n        coordinates(2) + ((idx & 4) >> 2) * side);\n}\n\n/*\n * \\brief Computes the non-sibling neighbourhood around an octants. In the\n * special case in which the octant lies on an edge, neighbour are duplicated\n * as movement outside the enclosing cube is forbidden.\n * \\param result 7-vector containing the neighbours\n * \\param octant\n * \\param level of octant\n * \\param max_depth max depth of the tree on which the octant lives\n */\nSE_DEVICE_ONLY_FUNC\ninline void exterior_neighbours(se::key_t result[7], const se::key_t octant,\n    const int level, const int max_depth) {\n    const int idx       = child_id(octant, level, max_depth);\n    Eigen::Vector3i dir = Eigen::Vector3i(\n        (idx & 1) ? 1 : -1, (idx & 2) ? 1 : -1, (idx & 4) ? 1 : -1);\n    Eigen::Vector3i base = far_corner(octant, level, max_depth);\n    dir(0) =\n        se::math::in(base(0) + dir(0), 0, (1 << max_depth) - 1) ? dir(0) : 0;\n    dir(1) =\n        se::math::in(base(1) + dir(1), 0, (1 << max_depth) - 1) ? dir(1) : 0;\n    dir(2) =\n        se::math::in(base(2) + dir(2), 0, (1 << max_depth) - 1) ? dir(2) : 0;\n\n    result[0] = se::keyops::encode(\n        base(0) + dir(0), base(1) + 0, base(2) + 0, level, max_depth);\n    result[1] = se::keyops::encode(\n        base(0) + 0, base(1) + dir(1), base(2) + 0, level, max_depth);\n    result[2] = se::keyops::encode(\n        base(0) + dir(0), base(1) + dir(1), base(2) + 0, level, max_depth);\n    result[3] = se::keyops::encode(\n        base(0) + 0, base(1) + 0, base(2) + dir(2), level, max_depth);\n    result[4] = se::keyops::encode(\n        base(0) + dir(0), base(1) + 0, base(2) + dir(2), level, max_depth);\n    result[5] = se::keyops::encode(\n        base(0) + 0, base(1) + dir(1), base(2) + dir(2), level, max_depth);\n    result[6] = se::keyops::encode(\n        base(0) + dir(0), base(1) + dir(1), base(2) + dir(2), level, max_depth);\n}\n\n/*\n * \\brief Computes the six face neighbours of an octant. These are stored in an\n * 4x6 matrix in which each column represents the homogeneous coordinates of a\n * neighbouring octant. The neighbours along the x axis come first, followed by\n * neighbours along the y axis and finally along the z axis. All coordinates are\n * clamped to be in the range between [0, max_size] where max size is given\n * by pow(2, max_depth).\n * \\param res 4x6 matrix containing the neighbours\n * \\param octant octant coordinates\n * \\param level level of the octant\n * \\param max_depth max depth of the tree on which the octant lives\n */\nSE_DEVICE_FUNC\nstatic inline void one_neighbourhood(Eigen::Ref<Eigen::Matrix<int, 4, 6>> res,\n    const Eigen::Vector3i& octant, const int level, const int max_depth) {\n    const Eigen::Vector3i base = octant;\n    const int size             = 1 << max_depth;\n    const int step             = 1 << (max_depth - level);\n    Eigen::Matrix<int, 4, 6> cross;\n    res << -step, step, 0, 0, 0, 0, 0, 0, -step, step, 0, 0, 0, 0, 0, 0, -step,\n        step, 0, 0, 0, 0, 0, 0;\n    res.colwise() += base.homogeneous();\n    res = res.unaryExpr(\n        [size](const int a) { return std::max(std::min(a, size - 1), 0); });\n}\n\n/*\n * \\brief Computes the six face neighbours of an octant. These are stored in an\n * 4x6 matrix in which each column represents the homogeneous coordinates of a\n * neighbouring octant. The neighbours along the x axis come first, followed by\n * neighbours along the y axis and finally along the z axis. All coordinates are\n * clamped to be in the range between [0, max_size] where max size is given\n * by pow(2, max_depth).\n * \\param res 4x6 matrix containing the neighbours\n * \\param octant octant key\n * \\param max_depth max depth of the tree on which the octant lives\n */\nSE_DEVICE_FUNC\nstatic inline void one_neighbourhood(Eigen::Ref<Eigen::Matrix<int, 4, 6>> res,\n    const se::key_t octant, const int max_depth) {\n    one_neighbourhood(\n        res, se::keyops::decode(octant), se::keyops::level(octant), max_depth);\n}\n\n/*\n * \\brief Computes the morton number of all siblings around an octant,\n * including itself.\n * \\param result 8-vector containing the neighbours\n * \\param octant\n * \\param max_depth max depth of the tree on which the octant lives\n */\nSE_DEVICE_ONLY_FUNC\ninline void siblings(\n    se::key_t result[8], const se::key_t octant, const int max_depth) {\n    const int level   = (octant & SCALE_MASK);\n    const int shift   = 3 * (max_depth - level);\n    const se::key_t p = parent(octant, max_depth) + 1; // set-up next level\n    for (int i = 0; i < 8; ++i) { result[i] = p | (i << shift); }\n}\n} // namespace se\n#endif\n", "meta": {"hexsha": "6b7d17614b3fb81052cc7f7e250d19a09ee0674c", "size": 9599, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "core/include/supereight/octant_ops.hpp", "max_stars_repo_name": "bozbez/supereight", "max_stars_repo_head_hexsha": "4bf8848dd062ba0fb51004e3f9f8b45e930113f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-07-24T20:35:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T17:08:53.000Z", "max_issues_repo_path": "core/include/supereight/octant_ops.hpp", "max_issues_repo_name": "bozbez/supereight", "max_issues_repo_head_hexsha": "4bf8848dd062ba0fb51004e3f9f8b45e930113f2", "max_issues_repo_licenses": ["MIT"], "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/supereight/octant_ops.hpp", "max_forks_repo_name": "bozbez/supereight", "max_forks_repo_head_hexsha": "4bf8848dd062ba0fb51004e3f9f8b45e930113f2", "max_forks_repo_licenses": ["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.3319327731, "max_line_length": 80, "alphanum_fraction": 0.673090947, "num_tokens": 2783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2566025040195623}}
{"text": "#include \"MeshCuboidNonLinearSolver.h\"\n\n#include <bitset>\n\n#include <Eigen/Eigenvalues> \n\n\nMeshCuboidNonLinearSolver::MeshCuboidNonLinearSolver(\n\tconst std::vector<MeshCuboid *>& _cuboids,\n\tconst std::vector<MeshCuboidReflectionSymmetryGroup *>& _reflection_symmetry_groups,\n\tconst std::vector<MeshCuboidRotationSymmetryGroup *>& _rotation_symmetry_groups,\n\tconst Real _squared_neighbor_distance,\n\tconst unsigned int _min_num_symmetry_point_pairs,\n\tconst Real _symmetry_energy_term_weight)\n\t: cuboids_(_cuboids)\n\t, reflection_symmetry_groups_(_reflection_symmetry_groups)\n\t, rotation_symmetry_groups_(_rotation_symmetry_groups)\n\t, squared_neighbor_distance_(_squared_neighbor_distance)\n\t, min_num_symmetric_point_pairs_(_min_num_symmetry_point_pairs)\n\t, symmetry_energy_term_weight_(_symmetry_energy_term_weight)\n\t, num_cuboid_corner_variables_(MeshCuboidAttributes::k_num_attributes)\n\t, num_cuboid_axis_variables_(3 * 3)\n\t, num_reflection_symmetry_group_variables_(MeshCuboidReflectionSymmetryGroup::num_axis_parameters())\n\t, num_rotation_symmetry_group_variables_(MeshCuboidRotationSymmetryGroup::num_axis_parameters())\n{\n\tnum_cuboids_ = _cuboids.size();\n\t//assert(num_cuboids_ > 0);\n\n\tnum_reflection_symmetry_groups_ = _reflection_symmetry_groups.size();\n\t//assert(num_reflection_symmetry_groups_ > 0);\n\tnum_rotation_symmetry_groups_ = _rotation_symmetry_groups.size();\n\t//assert(num_rotation_symmetry_groups_ > 0);\n\n\tcuboid_corner_variable_start_index_ = 0;\n\tcuboid_axis_variable_start_index_ = cuboid_corner_variable_start_index_\n\t\t+ num_total_cuboid_corner_variables();\n\treflection_symmetry_group_variable_start_index_ = cuboid_axis_variable_start_index_\n\t\t+ num_total_cuboid_axis_variables();\n\trotation_symmetry_group_variable_start_index_ = reflection_symmetry_group_variable_start_index_\n\t\t+ num_total_reflection_symmetry_group_variables();\n}\n\nMeshCuboidNonLinearSolver::~MeshCuboidNonLinearSolver()\n{\n\n}\n\nunsigned int MeshCuboidNonLinearSolver::num_total_cuboid_corner_variables() const\n{\n\treturn num_cuboid_corner_variables_ * num_cuboids_;\n}\n\nunsigned int MeshCuboidNonLinearSolver::num_total_cuboid_axis_variables() const\n{\n\treturn num_cuboid_axis_variables_ * num_cuboids_;\n}\n\nunsigned int MeshCuboidNonLinearSolver::num_total_reflection_symmetry_group_variables() const\n{\n\treturn num_reflection_symmetry_groups_ * num_reflection_symmetry_group_variables_;\n}\n\nunsigned int MeshCuboidNonLinearSolver::num_total_rotation_symmetry_group_variables() const\n{\n\treturn num_rotation_symmetry_groups_ * num_rotation_symmetry_group_variables_;\n}\n\nunsigned int MeshCuboidNonLinearSolver::num_total_variables() const\n{\n\treturn num_total_cuboid_corner_variables()\n\t\t+ num_total_cuboid_axis_variables()\n\t\t+ num_total_reflection_symmetry_group_variables()\n\t\t+ num_total_rotation_symmetry_group_variables();\n}\n\nNLPVectorExpression MeshCuboidNonLinearSolver::create_vector_variable(\n\tconst std::pair<Index, Index>& _index_size_pair)\n{\n\tassert(_index_size_pair.second > 0);\n\tNLPVectorExpression variable(_index_size_pair.second);\n\tfor (unsigned int i = 0; i < _index_size_pair.second; ++i)\n\t\tvariable[i] = NLPExpression(1.0, _index_size_pair.first + i);\n\treturn variable;\n}\n\nstd::pair<Index, Index> MeshCuboidNonLinearSolver::get_cuboid_corner_variable_index_size(\n\tunsigned int _cuboid_index, unsigned int _corner_index) const\n{\n\tconst unsigned int dimension = 3;\n\tassert(_corner_index < MeshCuboid::k_num_corners);\n\t\n\tunsigned int index = cuboid_corner_variable_start_index_\n\t\t+ num_cuboid_corner_variables_ * _cuboid_index\n\t\t+ dimension * _corner_index;\n\treturn std::make_pair(index, dimension);\n}\n\nstd::pair<Index, Index> MeshCuboidNonLinearSolver::get_cuboid_axis_variable_index_size(\n\tunsigned int _cuboid_index, unsigned int _axis_index) const\n{\n\tconst unsigned int dimension = 3;\n\tassert(_axis_index < dimension);\n\t\n\tunsigned int index = cuboid_axis_variable_start_index_\n\t\t+ num_cuboid_axis_variables_ * _cuboid_index\n\t\t+ dimension * _axis_index;\n\treturn std::make_pair(index, dimension);\n}\n\nstd::pair<Index, Index> MeshCuboidNonLinearSolver::get_reflection_symmetry_group_variable_n_index_size(\n\tunsigned int _symmetry_group_index) const\n{\n\tconst unsigned int dimension = 3;\n\tassert(_symmetry_group_index < num_reflection_symmetry_groups_);\n\n\tunsigned int index = reflection_symmetry_group_variable_start_index_\n\t\t+ num_reflection_symmetry_group_variables_ * _symmetry_group_index\n\t\t+ 0;\n\treturn std::make_pair(index, dimension);\n}\n\nstd::pair<Index, Index> MeshCuboidNonLinearSolver::get_reflection_symmetry_group_variable_t_index_size(\n\tunsigned int _symmetry_group_index) const\n{\n\tconst unsigned int dimension = 3;\n\tassert(_symmetry_group_index < num_reflection_symmetry_groups_);\n\n\tunsigned int index = reflection_symmetry_group_variable_start_index_\n\t\t+ num_reflection_symmetry_group_variables_ * _symmetry_group_index\n\t\t+ dimension;\n\treturn std::make_pair(index, 1);\n}\n\nstd::pair<Index, Index> MeshCuboidNonLinearSolver::get_rotation_symmetry_group_variable_n_index_size(\n\tunsigned int _symmetry_group_index) const\n{\n\tconst unsigned int dimension = 3;\n\tassert(_symmetry_group_index < num_rotation_symmetry_groups_);\n\n\tunsigned int index = rotation_symmetry_group_variable_start_index_\n\t\t+ num_rotation_symmetry_group_variables_ * _symmetry_group_index\n\t\t+ 0;\n\treturn std::make_pair(index, dimension);\n}\n\nstd::pair<Index, Index> MeshCuboidNonLinearSolver::get_rotation_symmetry_group_variable_t_index_size(\n\tunsigned int _symmetry_group_index) const\n{\n\tconst unsigned int dimension = 3;\n\tassert(_symmetry_group_index < num_rotation_symmetry_groups_);\n\n\tunsigned int index = rotation_symmetry_group_variable_start_index_\n\t\t+ num_rotation_symmetry_group_variables_ * _symmetry_group_index\n\t\t+ dimension;\n\treturn std::make_pair(index, dimension);\n}\n\nNLPVectorExpression MeshCuboidNonLinearSolver::create_cuboid_corner_variable(\n\tunsigned int _cuboid_index, unsigned int _corner_index) const\n{\n\treturn create_vector_variable(get_cuboid_corner_variable_index_size(\n\t\t_cuboid_index, _corner_index));\n}\n\nNLPVectorExpression MeshCuboidNonLinearSolver::create_cuboid_axis_variable(\n\tunsigned int _cuboid_index, unsigned int _axis_index) const\n{\n\treturn create_vector_variable(get_cuboid_axis_variable_index_size(\n\t\t_cuboid_index, _axis_index));\n}\n\nNLPVectorExpression MeshCuboidNonLinearSolver::create_reflection_symmetry_group_variable_n(\n\tunsigned int _symmetry_group_index) const\n{\n\treturn create_vector_variable(get_reflection_symmetry_group_variable_n_index_size(\n\t\t_symmetry_group_index));\n}\n\nNLPVectorExpression MeshCuboidNonLinearSolver::create_reflection_symmetry_group_variable_t(\n\tunsigned int _symmetry_group_index) const\n{\n\treturn create_vector_variable(get_reflection_symmetry_group_variable_t_index_size(\n\t\t_symmetry_group_index));\n}\n\nNLPVectorExpression MeshCuboidNonLinearSolver::create_rotation_symmetry_group_variable_n(\n\tunsigned int _symmetry_group_index) const\n{\n\treturn create_vector_variable(get_rotation_symmetry_group_variable_n_index_size(\n\t\t_symmetry_group_index));\n}\n\nNLPVectorExpression MeshCuboidNonLinearSolver::create_rotation_symmetry_group_variable_t(\n\tunsigned int _symmetry_group_index) const\n{\n\treturn create_vector_variable(get_rotation_symmetry_group_variable_t_index_size(\n\t\t_symmetry_group_index));\n}\n\nvoid MeshCuboidNonLinearSolver::create_energy_functions(\n\tconst Eigen::MatrixXd &_cuboid_quadratic_term,\n\tconst Eigen::VectorXd &_cuboid_linear_term,\n\tconst double _cuboid_constant_term,\n\tstd::vector<NLPFunction *> &_functions)\n{\n\tif (_cuboid_quadratic_term.rows() != num_total_cuboid_corner_variables()\n\t\t|| _cuboid_quadratic_term.cols() != num_total_cuboid_corner_variables()\n\t\t|| _cuboid_linear_term.rows() != num_total_cuboid_corner_variables())\n\t{\n\t\tstd::cerr << \"Error: \" << std::endl;\n\t\tassert(false);\n\t}\n\n\t_functions.clear();\n\n\tEigen::MatrixXd quadratic_term = Eigen::MatrixXd::Zero(num_total_variables(), num_total_variables());\n\tEigen::VectorXd linear_term = Eigen::VectorXd::Zero(num_total_variables());\n\tdouble constant_term = _cuboid_constant_term;\n\n\tquadratic_term.block(0, 0,\n\t\tnum_total_cuboid_corner_variables(), num_total_cuboid_corner_variables()) = _cuboid_quadratic_term;\n\tlinear_term.segment(0, num_total_cuboid_corner_variables()) = _cuboid_linear_term;\n\n\tNLPFunction *function_1 = new NLPEigenQuadFunction(quadratic_term, linear_term, constant_term);\n\t_functions.push_back(function_1);\n\n\t//\n\tNLPFunction *fuction_2 = create_reflection_symmetry_group_energy_function();\n\tassert(fuction_2);\n\t_functions.push_back(fuction_2);\n\n\tNLPFunction *fuction_3 = create_rotation_symmetry_group_energy_function();\n\tassert(fuction_3);\n\t_functions.push_back(fuction_3);\n\t//\n}\n\nNLPFunction *MeshCuboidNonLinearSolver::create_reflection_symmetry_group_energy_function()\n{\n\tEigen::MatrixXd quadratic_term = Eigen::MatrixXd::Zero(num_total_variables(), num_total_variables());\n\tEigen::VectorXd linear_term = Eigen::VectorXd::Zero(num_total_variables());\n\tdouble constant_term = 0;\n\n\tstd::vector<ANNpointArray> cuboid_ann_points;\n\tstd::vector<ANNkd_tree *> cuboid_ann_kd_tree;\n\n\tcreate_cuboid_sample_point_ann_trees(cuboid_ann_points, cuboid_ann_kd_tree);\n\n\tfor (unsigned int symmetry_group_index = 0; symmetry_group_index < num_reflection_symmetry_groups_;\n\t\t++symmetry_group_index)\n\t{\n\t\tcreate_reflection_symmetry_group_energy_function(symmetry_group_index,\n\t\t\tcuboid_ann_points, cuboid_ann_kd_tree,\n\t\t\tquadratic_term, linear_term, constant_term);\n\t}\n\n\tdelete_cuboid_sample_point_ann_trees(cuboid_ann_points, cuboid_ann_kd_tree);\n\n\tNLPFunction *function = new NLPEigenQuadFunction(quadratic_term, linear_term, constant_term);\n\treturn function;\n}\n\nvoid MeshCuboidNonLinearSolver::create_reflection_symmetry_group_energy_function(\n\tconst unsigned int _symmetry_group_index,\n\tconst std::vector<ANNpointArray>& _cuboid_ann_points,\n\tconst std::vector<ANNkd_tree *>& _cuboid_ann_kd_tree,\n\tEigen::MatrixXd& _quadratic_term,\n\tEigen::VectorXd& _linear_term,\n\tdouble &_constant_term)\n{\n\tconst MeshCuboidSymmetryGroup* symmetry_group = reflection_symmetry_groups_[_symmetry_group_index];\n\tassert(symmetry_group);\n\n\tstd::list<MeshCuboidSymmetryGroup::WeightedPointPair> sample_point_pairs;\n\tsymmetry_group->get_symmetric_sample_point_pairs(cuboids_,\n\t\t_cuboid_ann_points, _cuboid_ann_kd_tree, squared_neighbor_distance_,\n\t\tsample_point_pairs);\n\n\tif (sample_point_pairs.size() < min_num_symmetric_point_pairs_)\n\t\treturn;\n\n\t// Eq (1):\n\t// min {(I - nn^T)(x - y)}^2. Let d = (x - y).\n\t// Since (I - nn^T)^2 = (I - nn^T),\n\t// => min d^T(I - nn^T)d = d^Td - d^Tnn^Td = d^Td - n^Tdd^Tn.\n\n\t// Eq (2):\n\t// min {n^T(x + y) - 2t}^2.\n\n\tEigen::Matrix3d A1 = Eigen::Matrix3d::Zero();\n\tEigen::MatrixXd A2 = Eigen::MatrixXd::Zero(3 + 1, 3 + 1);\n\tReal c = 0;\n\n\tReal sum_weight = 0.0;\n\tfor (std::list<MeshCuboidSymmetryGroup::WeightedPointPair>::iterator it = sample_point_pairs.begin();\n\t\tit != sample_point_pairs.end(); ++it)\n\t{\n\t\tassert((*it).weight_ >= 0);\n\t\tsum_weight += (*it).weight_;\n\t}\n\n\tif (sum_weight == 0)\n\t\treturn;\n\n\tfor (std::list<MeshCuboidSymmetryGroup::WeightedPointPair>::iterator it = sample_point_pairs.begin();\n\t\tit != sample_point_pairs.end(); ++it)\n\t{\n\t\tReal weight = (*it).weight_ / sum_weight;\n\n\t\tEigen::Vector3d sum_p, diff_p;\n\t\tfor (int i = 0; i < 3; ++i)\n\t\t{\n\t\t\tsum_p[i] = (*it).p1_[i] + (*it).p2_[i];\n\t\t\tdiff_p[i] = (*it).p1_[i] - (*it).p2_[i];\n\t\t}\n\n\t\tA1 += (weight * (-1) * diff_p * diff_p.transpose());\n\t\tc += (weight * diff_p.transpose() * diff_p);\n\n\t\tEigen::VectorXd b(3 + 1);\n\t\tb << sum_p, -2;\n\t\tA2 += (weight * b * b.transpose());\n\t}\n\n\tstd::pair<Index, Index> index_size_pair;\n\tindex_size_pair = get_reflection_symmetry_group_variable_n_index_size(_symmetry_group_index);\n\n\t_quadratic_term.block<3, 3>(index_size_pair.first, index_size_pair.first) +=\n\t\tsymmetry_energy_term_weight_ * A1;\n\t\n\t// NOTE:\n\t// Variables 'n' and 't' are adjacent in the variable list.\n\t_quadratic_term.block<3 + 1, 3 + 1>(index_size_pair.first, index_size_pair.first) +=\n\t\tsymmetry_energy_term_weight_ * A2;\n\n\t_constant_term += symmetry_energy_term_weight_ * c;\n}\n\nNLPFunction *MeshCuboidNonLinearSolver::create_rotation_symmetry_group_energy_function()\n{\n\tNLPExpression expression;\n\n\tstd::vector<ANNpointArray> cuboid_ann_points;\n\tstd::vector<ANNkd_tree *> cuboid_ann_kd_tree;\n\n\tcreate_cuboid_sample_point_ann_trees(cuboid_ann_points, cuboid_ann_kd_tree);\n\n\tfor (unsigned int symmetry_group_index = 0; symmetry_group_index < num_rotation_symmetry_groups_;\n\t\t++symmetry_group_index)\n\t{\n\t\t// Minimize \\| t \\|_2^2.\n\t\tNLPVectorExpression t_variable = create_rotation_symmetry_group_variable_t(symmetry_group_index);\n\t\texpression += NLPVectorExpression::dot_product(t_variable, t_variable);\n\n\t\tcreate_rotation_symmetry_group_energy_function(symmetry_group_index,\n\t\t\tcuboid_ann_points, cuboid_ann_kd_tree, expression);\n\t}\n\n\tdelete_cuboid_sample_point_ann_trees(cuboid_ann_points, cuboid_ann_kd_tree);\n\n\texpression *= symmetry_energy_term_weight_;\n\n\tNLPFunction *function = new NLPSparseFunction(num_total_variables(), expression);\n\treturn function;\n}\n\nvoid MeshCuboidNonLinearSolver::create_rotation_symmetry_group_energy_function(\n\tconst unsigned int _symmetry_group_index,\n\tconst std::vector<ANNpointArray>& _cuboid_ann_points,\n\tconst std::vector<ANNkd_tree *>& _cuboid_ann_kd_tree,\n\tNLPExpression &_expression)\n{\n\tconst MeshCuboidRotationSymmetryGroup* symmetry_group = rotation_symmetry_groups_[_symmetry_group_index];\n\tassert(symmetry_group);\n\n\tNLPVectorExpression n_variable = create_rotation_symmetry_group_variable_n(_symmetry_group_index);\n\tNLPVectorExpression t_variable = create_rotation_symmetry_group_variable_t(_symmetry_group_index);\n\n\n\tstd::list<MeshCuboidSymmetryGroup::WeightedPointPair> sample_point_pairs;\n\tsymmetry_group->get_symmetric_sample_point_pairs(cuboids_,\n\t\t_cuboid_ann_points, _cuboid_ann_kd_tree, squared_neighbor_distance_,\n\t\tsample_point_pairs);\n\n\tif (sample_point_pairs.size() < min_num_symmetric_point_pairs_)\n\t\treturn;\n\n\tReal sum_weight = 0.0;\n\tfor (std::list<MeshCuboidSymmetryGroup::WeightedPointPair>::iterator it = sample_point_pairs.begin();\n\t\tit != sample_point_pairs.end(); ++it)\n\t{\n\t\tassert((*it).weight_ >= 0);\n\t\tsum_weight += (*it).weight_;\n\t}\n\n\tfor (std::list<MeshCuboidSymmetryGroup::WeightedPointPair>::iterator it = sample_point_pairs.begin();\n\t\tit != sample_point_pairs.end(); ++it)\n\t{\n\t\tReal weight = (*it).weight_ / sum_weight;\n\n\t\tMyMesh::Normal n; MyMesh::Point t;\n\t\tsymmetry_group->get_rotation_axis(n, t);\n\n\t\tint symmetry_order = static_cast<int>(std::round((*it).angle_ / symmetry_group->get_rotation_angle()));\n\t\tMyMesh::Point symmetry_point_1 = symmetry_group->get_symmetric_point((*it).p1_, symmetry_order);\n\n\t\tEigen::Vector3d x_vec, y_vec;\n\t\tfor (int i = 0; i < 3; ++i)\n\t\t{\n\t\t\tx_vec[i] = (*it).p1_[i];\n\t\t\ty_vec[i] = (*it).p2_[i];\n\t\t}\n\n\t\t// Debug.\n\t\t//Eigen::Vector3d n_vec, t_vec, symm_x_vec;\n\t\t//for (int i = 0; i < 3; ++i)\n\t\t//{\n\t\t//\tn_vec[i] = n[i];\n\t\t//\tt_vec[i] = t[i];\n\t\t//\tsymm_x_vec[i] = symmetry_point_1[i];\n\t\t//}\n\n\t\t//Eigen::AngleAxisd axis_rotation((*it).angle_, n_vec);\n\t\t//Eigen::VectorXd transf_x_vec = axis_rotation.toRotationMatrix() * (x_vec - t_vec) + t_vec;\n\n\t\t//Eigen::VectorXd diff_1 = transf_x_vec - symm_x_vec;\n\t\t//if (diff_1.norm() > 1.0E-8)\n\t\t//{\n\t\t//\tstd::cout << \"distance = \" << diff_1.norm() << std::endl;\n\t\t//\tstd::cout << \"angle = \" << (*it).angle_ << std::endl;\n\t\t//\tstd::cout << \"symmetry_order = \" << symmetry_order << std::endl;\n\t\t//\tstd::cout << symm_x_vec.transpose() << std::endl;\n\t\t//\tstd::cout << transf_x_vec.transpose() << std::endl;\n\t\t//\tsystem(\"pause\");\n\t\t//}\n\n\t\t//Eigen::VectorXd diff_2 = transf_x_vec - y_vec;\n\t\t//if (diff_2.norm() > neighbor_distance_)\n\t\t//{\n\t\t//\tstd::cout << \"distance = \" << diff_2.norm() << std::endl;\n\t\t//\tstd::cout << \"neighbor_distance = \" << neighbor_distance_ << std::endl;\n\t\t//\tstd::cout << \"weight = \" << (neighbor_distance_ - sqrt((*it).weight_)) << std::endl;\n\t\t//\tstd::cout << symm_x_vec.transpose() << std::endl;\n\t\t//\tstd::cout << transf_x_vec.transpose() << std::endl;\n\t\t//\tsystem(\"pause\");\n\t\t//}\n\n\t\tReal sin_angle = std::sin((*it).angle_);\n\t\tReal cos_angle = std::cos((*it).angle_);\n\n\t\tNLPVectorExpression x_minus_t = (x_vec - t_variable);\n\t\tNLPVectorExpression y_minus_t = (y_vec - t_variable);\n\n\t\tNLPVectorExpression term_1 = x_minus_t * cos_angle;\n\t\tNLPVectorExpression term_2 = NLPVectorExpression::cross_product(n_variable, x_minus_t) * sin_angle;\n\t\tNLPVectorExpression term_3 = n_variable * NLPVectorExpression::dot_product(n_variable, x_minus_t) * (1 - cos_angle);\n\t\tNLPVectorExpression all_terms = term_1 + term_2 + term_3 - y_minus_t;\n\t\tNLPExpression squared_all_terms = NLPVectorExpression::dot_product(all_terms, all_terms);\n\n\t\t// Debug.\n\t\t//Number *x = new Number[num_total_variables()];\n\t\t//std::pair<Index, Index> n_index_size = get_rotation_symmetry_group_variable_n_index_size(_symmetry_group_index);\n\t\t//std::pair<Index, Index> t_index_size = get_rotation_symmetry_group_variable_t_index_size(_symmetry_group_index);\n\t\t//for (Index i = 0; i < n_index_size.second; ++i)\n\t\t//\tx[n_index_size.first + i] = n[i];\n\t\t//for (Index i = 0; i < t_index_size.second; ++i)\n\t\t//\tx[t_index_size.first + i] = t[i];\n\t\t//std::cout << \"eval = \" << squared_all_terms.eval(x) << std::endl;\n\n\t\t//Eigen::Vector3d term_1_vec = cos_angle * (x_vec - t_vec);\n\t\t//Eigen::Vector3d term_2_vec = sin_angle * n_vec.cross(x_vec - t_vec);\n\t\t//Eigen::Vector3d term_3_vec = (1 - cos_angle) * n_vec.dot(x_vec - t_vec) * n_vec;\n\t\t//Eigen::Vector3d term_4_vec = -(y_vec - t_vec);\n\t\t//Eigen::Vector3d all_terms_vec = term_1_vec + term_2_vec + term_3_vec + term_4_vec;\n\t\t//std::cout << \"eval = \" << all_terms_vec.squaredNorm() << std::endl;\n\n\t\t//delete[] x;\n\t\t//system(\"pause\");\n\t\t//\n\n\t\t_expression += squared_all_terms;\n\t}\n}\n\n\nvoid MeshCuboidNonLinearSolver::add_constraints(NLPFormulation &_formulation)\n{\n\tadd_cuboid_constraints(_formulation);\n\tadd_reflection_symmetry_group_constraints(_formulation);\n\tadd_rotation_symmetry_group_constraints(_formulation);\n}\n\nvoid MeshCuboidNonLinearSolver::add_cuboid_constraints(NLPFormulation &_formulation)\n{\n\tfor (unsigned int cuboid_index = 0; cuboid_index < num_cuboids_; ++cuboid_index)\n\t{\n\t\tadd_cuboid_constraints(cuboid_index, _formulation);\n\t}\n}\n\nvoid MeshCuboidNonLinearSolver::add_reflection_symmetry_group_constraints(NLPFormulation &_formulation)\n{\n\tfor (unsigned int symmetry_group_index = 0; symmetry_group_index < num_reflection_symmetry_groups_;\n\t\t++symmetry_group_index)\n\t{\n\t\tadd_reflection_symmetry_group_constraints(symmetry_group_index, _formulation);\n\t}\n}\n\nvoid MeshCuboidNonLinearSolver::add_rotation_symmetry_group_constraints(NLPFormulation &_formulation)\n{\n\tfor (unsigned int symmetry_group_index = 0; symmetry_group_index < num_rotation_symmetry_groups_;\n\t\t++symmetry_group_index)\n\t{\n\t\tadd_rotation_symmetry_group_constraints(symmetry_group_index, _formulation);\n\t}\n}\n\nvoid MeshCuboidNonLinearSolver::add_cuboid_constraints(\n\tconst unsigned int _cuboid_index,\n\tNLPFormulation &_formulation)\n{\n\tconst unsigned int dimension = 3;\n\t\n\tfor (unsigned int axis_index = 0; axis_index < dimension; ++axis_index)\n\t{\n\t\tNLPVectorExpression axis_variable_1 = create_cuboid_axis_variable(_cuboid_index, axis_index);\n\n\t\t// Unit vector constraint.\n\t\t_formulation.add_constraint(NLPVectorExpression::dot_product(\n\t\t\taxis_variable_1, axis_variable_1), 1, 1);\n\n\t\t// Orthogonality constraint.\n\t\tif (dimension >= 2)\n\t\t{\n\t\t\tNLPVectorExpression axis_variable_2 = create_cuboid_axis_variable(_cuboid_index,\n\t\t\t\t(axis_index + 1) % dimension);\n\t\t\tassert(axis_variable_1.dimension() == axis_variable_2.dimension());\n\n\t\t\t// NOTE:\n\t\t\t// Relaxing equality constraint.\n\t\t\t// The equality constraints cause \"too few degrees\" errors.\n\t\t\t_formulation.add_constraint(NLPVectorExpression::dot_product(\n\t\t\t\taxis_variable_1, axis_variable_2), -1.0E-12, 1.0E-12);\n\t\t}\n\t}\n\n\tfor (int axis_index = 0; axis_index < dimension; ++axis_index)\n\t{\n\t\t// NOTE:\n\t\t// Implemented only for 3 dimension.\n\t\tassert(dimension == 3);\n\n\t\tfor (int axis_1 = 0; axis_1 < 2; ++axis_1)\n\t\t{\n\t\t\tfor (int axis_2 = 0; axis_2 < 2; ++axis_2)\n\t\t\t{\n\t\t\t\tstd::bitset<3> bits;\n\t\t\t\tbits[(axis_index + 1) % 3] = axis_1;\n\t\t\t\tbits[(axis_index + 2) % 3] = axis_2;\n\n\t\t\t\tbits[axis_index] = false;\n\t\t\t\tint corner_index_1 = bits.to_ulong();\n\n\t\t\t\tbits[axis_index] = true;\n\t\t\t\tint corner_index_2 = bits.to_ulong();\n\n\t\t\t\tNLPVectorExpression corner_variable_1 = create_cuboid_corner_variable(_cuboid_index, corner_index_1);\n\t\t\t\tNLPVectorExpression corner_variable_2 = create_cuboid_corner_variable(_cuboid_index, corner_index_2);\n\n\t\t\t\t// A cuboid edge is orthogonal with two axes.\n\t\t\t\tfor (int other_axis_index = 0; other_axis_index < dimension; ++other_axis_index)\n\t\t\t\t{\n\t\t\t\t\tif (other_axis_index == axis_index) continue;\n\t\t\t\t\tNLPVectorExpression other_axis_variable = create_cuboid_axis_variable(_cuboid_index, other_axis_index);\n\n\t\t\t\t\t// n^T(x - y) = 0.\n\t\t\t\t\tNLPExpression expression = NLPVectorExpression::dot_product(other_axis_variable,\n\t\t\t\t\t\tcorner_variable_1 - corner_variable_2);\n\n\t\t\t\t\t// NOTE:\n\t\t\t\t\t// Relaxing equality constraint.\n\t\t\t\t\t// The equality constraints cause \"too few degrees\" errors.\n\t\t\t\t\t_formulation.add_constraint(expression, -1.0E-12, 1.0E-12);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid MeshCuboidNonLinearSolver::add_reflection_symmetry_group_constraints(\n\tconst unsigned int _symmetry_group_index,\n\tNLPFormulation &_formulation)\n{\n\tconst MeshCuboidReflectionSymmetryGroup *symmetry_group = reflection_symmetry_groups_[_symmetry_group_index];\n\tassert(symmetry_group);\n\n\tNLPVectorExpression n_variable = create_reflection_symmetry_group_variable_n(_symmetry_group_index);\n\n\tstd::vector< unsigned int > single_cuboid_indices;\n\tsymmetry_group->get_single_cuboid_indices(cuboids_, single_cuboid_indices);\n\n\tfor (std::vector< unsigned int >::const_iterator it = single_cuboid_indices.begin();\n\t\tit != single_cuboid_indices.end(); ++it)\n\t{\n\t\tunsigned int cuboid_index = (*it);\n\t\t\n\t\tadd_single_cuboid_reflection_constraints(\n\t\t\tcuboid_index,\n\t\t\t_symmetry_group_index,\n\t\t\tsymmetry_group->get_aligned_global_axis_index(),\n\t\t\t_formulation);\n\t}\n\n\tstd::vector< std::pair<unsigned int, unsigned int> > pair_cuboid_indices;\n\tsymmetry_group->get_pair_cuboid_indices(cuboids_, pair_cuboid_indices);\n\n\tfor (std::vector< std::pair<unsigned int, unsigned int> >::const_iterator it = pair_cuboid_indices.begin();\n\t\tit != pair_cuboid_indices.end(); ++it)\n\t{\n\t\tadd_pair_cuboid_reflection_constraints(\n\t\t\t(*it).first, (*it).second,\n\t\t\t_symmetry_group_index,\n\t\t\tsymmetry_group->get_aligned_global_axis_index(),\n\t\t\t_formulation);\n\t}\n\n\t// Unit vector constraint.\n\tNLPExpression expression = NLPVectorExpression::dot_product(\n\t\tn_variable, n_variable);\n\t_formulation.add_constraint(expression, 1, 1);\n}\n\nvoid MeshCuboidNonLinearSolver::add_reflection_constraints(\n\tconst NLPVectorExpression& _x_variable,\n\tconst NLPVectorExpression& _y_variable,\n\tconst NLPVectorExpression& _n_variable,\n\tconst NLPVectorExpression& _t_variable,\n\tNLPFormulation &_formulation)\n{\n\tconst unsigned int dimension = _x_variable.dimension();\n\tassert(_y_variable.dimension() == dimension);\n\tassert(_n_variable.dimension() == dimension);\n\tassert(_t_variable.dimension() == 1);\n\n\t// n^T(x + y) - 2t = 0.\n\tNLPExpression expression_1 = NLPVectorExpression::dot_product(_n_variable,\n\t\t_x_variable + _y_variable)\n\t\t+ (_t_variable[0] * -2);\n\n\t// NOTE:\n\t// Relaxing equality constraint.\n\t// The equality constraints cause \"too few degrees\" errors.\n\t_formulation.add_constraint(expression_1, -1.0E-12, 1.0E-12);\n\n\n\t// n^T(x - y).\n\tNLPExpression temp = NLPVectorExpression::dot_product(_n_variable,\n\t\t_x_variable - _y_variable);\n\n\t// (I - nn^T)(x - y) = (x - y) - n(n^T(x - y)) = 0.\n\tNLPVectorExpression expression_2 = (_x_variable - _y_variable) - (_n_variable * temp);\n\n\t// NOTE:\n\t// Relaxing equality constraint.\n\t// The equality constraints cause \"too few degrees\" errors.\n\t_formulation.add_constraint(expression_2, -1.0E-12, 1.0E-12);\n}\n\nvoid MeshCuboidNonLinearSolver::add_single_cuboid_reflection_constraints(\n\tconst unsigned int _cuboid_index,\n\tconst unsigned int _symmetry_group_index,\n\tconst unsigned int _reflection_axis_index,\n\tNLPFormulation &_formulation)\n{\n\tconst unsigned int dimension = 3;\n\tassert(_reflection_axis_index < dimension);\n\n\tbool *is_corner_visited = new bool[MeshCuboid::k_num_corners];\n\tmemset(is_corner_visited, false, MeshCuboid::k_num_corners * sizeof(bool));\n\n\tfor (unsigned int corner_index_1 = 0; corner_index_1 < MeshCuboid::k_num_corners; ++corner_index_1)\n\t{\n\t\tif (is_corner_visited[corner_index_1])\n\t\t\tcontinue;\n\n\t\tstd::bitset<3> bits(corner_index_1);\n\t\tbits[_reflection_axis_index].flip();\n\t\tunsigned int corner_index_2 = bits.to_ulong();\n\n\t\tassert(!is_corner_visited[corner_index_2]);\n\n\t\tadd_reflection_constraints(\n\t\t\tcreate_cuboid_corner_variable(_cuboid_index, corner_index_1),\n\t\t\tcreate_cuboid_corner_variable(_cuboid_index, corner_index_2),\n\t\t\tcreate_reflection_symmetry_group_variable_n(_symmetry_group_index),\n\t\t\tcreate_reflection_symmetry_group_variable_t(_symmetry_group_index),\n\t\t\t_formulation);\n\n\t\tis_corner_visited[corner_index_1] = is_corner_visited[corner_index_2] = true;\n\t}\n\n\tdelete[] is_corner_visited;\n}\n\nvoid MeshCuboidNonLinearSolver::add_pair_cuboid_reflection_constraints(\n\tconst unsigned int _cuboid_index_1,\n\tconst unsigned int _cuboid_index_2,\n\tconst unsigned int _symmetry_group_index,\n\tconst unsigned int _reflection_axis_index,\n\tNLPFormulation &_formulation)\n{\n\tconst unsigned int dimension = 3;\n\tassert(_reflection_axis_index < dimension);\n\n\tfor (unsigned int corner_index_1 = 0; corner_index_1 < MeshCuboid::k_num_corners; ++corner_index_1)\n\t{\n\t\tstd::bitset<3> bits(corner_index_1);\n\t\tbits[_reflection_axis_index].flip();\n\t\tunsigned int corner_index_2 = bits.to_ulong();\n\n\t\tadd_reflection_constraints(\n\t\t\tcreate_cuboid_corner_variable(_cuboid_index_1, corner_index_1),\n\t\t\tcreate_cuboid_corner_variable(_cuboid_index_2, corner_index_2),\n\t\t\tcreate_reflection_symmetry_group_variable_n(_symmetry_group_index),\n\t\t\tcreate_reflection_symmetry_group_variable_t(_symmetry_group_index),\n\t\t\t_formulation);\n\t}\n}\n\nvoid MeshCuboidNonLinearSolver::add_rotation_symmetry_group_constraints(\n\tconst unsigned int _symmetry_group_index,\n\tNLPFormulation &_formulation)\n{\n\tconst MeshCuboidRotationSymmetryGroup *symmetry_group = rotation_symmetry_groups_[_symmetry_group_index];\n\tassert(symmetry_group);\n\n\tconst unsigned int dimension = 3;\n\tNLPVectorExpression n_variable = create_rotation_symmetry_group_variable_n(_symmetry_group_index);\n\tNLPVectorExpression t_variable = create_rotation_symmetry_group_variable_t(_symmetry_group_index);\n\n\n\tstd::vector< unsigned int > single_cuboid_indices;\n\tsymmetry_group->get_single_cuboid_indices(cuboids_, single_cuboid_indices);\n\n\tfor (std::vector< unsigned int >::const_iterator it = single_cuboid_indices.begin();\n\t\tit != single_cuboid_indices.end(); ++it)\n\t{\n\t\tunsigned int cuboid_index = (*it);\n\n\t\tNLPVectorExpression axis_variable = create_cuboid_axis_variable(cuboid_index,\n\t\t\tsymmetry_group->get_aligned_global_axis_index());\n\n\t\t// The symmetry axis should be the same direction with the cuboid axis.\n\t\tNLPVectorExpression expression_1 = n_variable - axis_variable;\n\t\t_formulation.add_constraint(NLPVectorExpression::dot_product(expression_1, expression_1), 0, 0);\n\n\t\tNLPVectorExpression cuboid_center_variable(dimension);\n\t\tfor (unsigned int corner_index = 0; corner_index < MeshCuboid::k_num_corners; ++corner_index)\n\t\t\tcuboid_center_variable += create_cuboid_corner_variable(cuboid_index, corner_index);\n\t\tcuboid_center_variable *= (1.0 / MeshCuboid::k_num_corners);\n\n\t\t//  cross(n, (c - t)) = 0.\n\t\tNLPVectorExpression expression_2 = NLPVectorExpression::cross_product(\n\t\t\tn_variable, cuboid_center_variable - t_variable);\n\t\t_formulation.add_constraint(NLPVectorExpression::dot_product(expression_2, expression_2), 0, 0);\n\t}\n\n\t// Ignore pairs of cuboids.\n\n\n\t// Unit vector constraint.\n\tNLPExpression expression = NLPVectorExpression::dot_product(\n\t\tn_variable, n_variable);\n\t_formulation.add_constraint(expression, 1, 1);\n}\n\nvoid MeshCuboidNonLinearSolver::fix_cuboid(\n\tconst unsigned int _cuboid_index,\n\tNLPFormulation &_formulation)\n{\n\tconst MeshCuboid* cuboid = cuboids_[_cuboid_index];\n\tassert(cuboid);\n\n\tconst unsigned int dimension = 3;\n\n\tfor (unsigned int corner_index = 0; corner_index < dimension; ++corner_index)\n\t{\n\t\tNLPVectorExpression axis_variable = create_cuboid_axis_variable(_cuboid_index, corner_index);\n\t\tMyMesh::Normal axis = cuboid->get_bbox_axis(corner_index);\n\t\tEigen::Vector3d axis_vec;\n\t\tfor (unsigned int i = 0; i < 3; ++i)\n\t\t\taxis_vec[i] = axis[i];\n\n\t\taxis_variable -= axis_vec;\n\t\t_formulation.add_constraint(NLPVectorExpression::dot_product(axis_variable, axis_variable), 0, 0);\n\t}\n\n\tfor (unsigned int corner_index = 0; corner_index < MeshCuboid::k_num_corners; ++corner_index)\n\t{\n\t\tNLPVectorExpression corner_variable = create_cuboid_corner_variable(_cuboid_index, corner_index);\n\t\tMyMesh::Normal corner = cuboid->get_bbox_corner(corner_index);\n\t\tEigen::Vector3d corner_vec;\n\t\tfor (unsigned int i = 0; i < 3; ++i)\n\t\t\tcorner_vec[i] = corner[i];\n\n\t\tcorner_variable -= corner_vec;\n\t\t_formulation.add_constraint(NLPVectorExpression::dot_product(corner_variable, corner_variable), 0, 0);\n\t}\n}\n\nbool MeshCuboidNonLinearSolver::compute_initial_values(const Eigen::VectorXd &_input,\n\tEigen::VectorXd &_output)\n{\n\tif (_input.rows() != num_total_cuboid_corner_variables())\n\t{\n\t\tstd::cerr << \"Error: \" << std::endl;\n\t\treturn false;\n\t}\n\n\t_output = Eigen::VectorXd::Zero(num_total_variables());\n\t_output.segment(0, num_total_cuboid_corner_variables()) = _input;\n\n\tcompute_cuboid_axis_values(_output);\n\tcompute_reflection_symmetry_group_values(_output);\n\tcompute_rotation_symmetry_group_values(_output);\n\n\t// DEBUG.\n\tfor (int i = 0; i < num_total_variables(); ++i)\n\t{\n\t\tif (isnan(_output[i]) || isinf(_output[i]))\n\t\t{\n\t\t\tassert(false);\n\t\t}\n\t}\n\n\treturn true;\n}\n\nvoid MeshCuboidNonLinearSolver::compute_cuboid_axis_values(Eigen::VectorXd &_values)\n{\n\tassert(_values.rows() >= num_total_variables());\n\n\tfor (unsigned int cuboid_index = 0; cuboid_index < num_cuboids_; ++cuboid_index)\n\t{\n\t\tconst MeshCuboid* cuboid = cuboids_[cuboid_index];\n\t\tassert(cuboid);\n\t\tfor (unsigned int axis_index = 0; axis_index < 3; ++axis_index)\n\t\t{\n\t\t\tconst MyMesh::Normal &axis = cuboid->get_bbox_axis(axis_index);\n\n\t\t\tstd::pair<Index, Index> index_size_pair = get_cuboid_axis_variable_index_size(cuboid_index, axis_index);\n\t\t\tassert(index_size_pair.second == 3);\n\t\t\tfor (unsigned int i = 0; i < index_size_pair.second; ++i)\n\t\t\t\t_values[index_size_pair.first + i] = axis[i];\n\t\t}\n\t}\n}\n\nvoid MeshCuboidNonLinearSolver::compute_reflection_symmetry_group_values(Eigen::VectorXd &_values)\n{\n\tassert(_values.rows() >= num_total_variables());\n\n\tfor (unsigned int symmetry_group_index = 0; symmetry_group_index < num_reflection_symmetry_groups_;\n\t\t++symmetry_group_index)\n\t{\n\t\tconst MeshCuboidReflectionSymmetryGroup* symmetry_group = reflection_symmetry_groups_[symmetry_group_index];\n\t\tassert(symmetry_group);\n\n\t\tMyMesh::Normal n; double t;\n\t\tsymmetry_group->get_reflection_plane(n, t);\n\n\t\tstd::pair<Index, Index> index_size_pair;\n\t\tindex_size_pair = get_reflection_symmetry_group_variable_n_index_size(symmetry_group_index);\n\t\tassert(index_size_pair.second == 3);\n\t\tfor (unsigned int i = 0; i < index_size_pair.second; ++i)\n\t\t\t_values[index_size_pair.first + i] = n[i];\n\n\t\tindex_size_pair = get_reflection_symmetry_group_variable_t_index_size(symmetry_group_index);\n\t\tassert(index_size_pair.second == 1);\n\t\t_values[index_size_pair.first] = t;\n\t}\n}\n\nvoid MeshCuboidNonLinearSolver::compute_rotation_symmetry_group_values(Eigen::VectorXd &_values)\n{\n\tassert(_values.rows() >= num_total_variables());\n\n\tfor (unsigned int symmetry_group_index = 0; symmetry_group_index < num_rotation_symmetry_groups_;\n\t\t++symmetry_group_index)\n\t{\n\t\tconst MeshCuboidRotationSymmetryGroup* symmetry_group = rotation_symmetry_groups_[symmetry_group_index];\n\t\tassert(symmetry_group);\n\n\t\tMyMesh::Normal n; MyMesh::Point t;\n\t\tsymmetry_group->get_rotation_axis(n, t);\n\n\t\tstd::pair<Index, Index> index_size_pair;\n\t\tindex_size_pair = get_rotation_symmetry_group_variable_n_index_size(symmetry_group_index);\n\t\tassert(index_size_pair.second == 3);\n\t\tfor (unsigned int i = 0; i < index_size_pair.second; ++i)\n\t\t\t_values[index_size_pair.first + i] = n[i];\n\n\t\tindex_size_pair = get_rotation_symmetry_group_variable_t_index_size(symmetry_group_index);\n\t\tassert(index_size_pair.second == 3);\n\t\tfor (unsigned int i = 0; i < index_size_pair.second; ++i)\n\t\t\t_values[index_size_pair.first + i] = t[i];\n\t}\n}\n\nvoid MeshCuboidNonLinearSolver::optimize(\n\tconst Eigen::MatrixXd& _cuboid_quadratic_term,\n\tconst Eigen::VectorXd& _cuboid_linear_term,\n\tconst double _cuboid_constant_term,\n\tEigen::VectorXd* _init_values_vec,\n\tconst std::vector<unsigned int> *_fixed_cuboid_indices)\n{\n\t// Update rotation angle.\n\tfor (unsigned int symmetry_group_index = 0; symmetry_group_index < num_rotation_symmetry_groups_;\n\t\t++symmetry_group_index)\n\t{\n\t\tMeshCuboidRotationSymmetryGroup* symmetry_group = rotation_symmetry_groups_[symmetry_group_index];\n\t\tassert(symmetry_group);\n\t\tsymmetry_group->compute_rotation_angle(cuboids_);\n\t}\n\n\tstd::vector<NLPFunction *> functions;\n\tcreate_energy_functions(_cuboid_quadratic_term, _cuboid_linear_term, _cuboid_constant_term, functions);\n\tNLPFormulation formulation(functions);\n\tadd_constraints(formulation);\n\n\tif (_fixed_cuboid_indices)\n\t{\n\t\tfor (std::vector<unsigned int>::const_iterator it = (*_fixed_cuboid_indices).begin();\n\t\t\tit != (*_fixed_cuboid_indices).end(); ++it)\n\t\t{\n\t\t\tassert((*it) < cuboids_.size());\n\t\t\tfix_cuboid((*it), formulation);\n\t\t}\n\t}\n\n\n\tif (_init_values_vec)\n\t{\n\t\tEigen::VectorXd all_init_values_vec;\n\t\tbool ret = compute_initial_values(*_init_values_vec, all_init_values_vec);\n\t\tassert(ret);\n\t\tformulation.set_values(all_init_values_vec.data());\n\n\t\tstd::vector< Number > all_init_values(all_init_values_vec.rows());\n\t\tfor (int i = 0; i < all_init_values_vec.rows(); ++i)\n\t\t\tall_init_values[i] = all_init_values_vec[i];\n\n\t\tstd::cout << \"Initial error = \";\n\t\tfor (int i = 0; i < functions.size(); ++i)\n\t\t\tstd::cout << functions[i]->eval(&all_init_values[0]) << \", \";\n\t\tstd::cout << std::endl;\n\t}\n\n\n\t// ---- //\n\t// Create a new instance of your nlp\n\t//  (use a SmartPtr, not raw)\n\tSmartPtr<TNLP> mynlp = new IPOPTSolver(&formulation);\n\t//SmartPtr<TNLP> mynlp = new HS071_NLP();\n\n\t// Create a new instance of IpoptApplication\n\t//  (use a SmartPtr, not raw)\n\t// We are using the factory, since this allows us to compile this\n\t// example with an Ipopt Windows DLL\n\tSmartPtr<IpoptApplication> app = IpoptApplicationFactory();\n\t//app->RethrowNonIpoptException(true);\n\n\t// Change some options\n\t// Note: The following choices are only examples, they might not be\n\t//       suitable for your optimization problem.\n\tapp->Options()->SetNumericValue(\"tol\", 1e-8);\n\tapp->Options()->SetStringValue(\"mu_strategy\", \"adaptive\");\n\tapp->Options()->SetIntegerValue(\"print_level\", 0);\n\tapp->Options()->SetStringValue(\"fixed_variable_treatment\", \"relax_bounds\");\n\t// app->Options()->SetStringValue(\"output_file\", \"ipopt.out\");\n\t// The following overwrites the default name (ipopt.opt) of the\n\t// options file\n\t// app->Options()->SetStringValue(\"option_file_name\", \"ipopt.opt\");\n\n\t// Initialize the IpoptApplication and process the options\n\tApplicationReturnStatus status;\n\tstatus = app->Initialize();\n\tif (status != Solve_Succeeded) {\n\t\tstd::cout << std::endl << std::endl << \"*** Error during initialization!\" << std::endl;\n\t\tassert(false);\n\t}\n\n\t// Ask Ipopt to solve the problem\n\tstatus = app->OptimizeTNLP(mynlp);\n\n\tif (status == Solve_Succeeded) {\n\t\t//std::cout << std::endl << std::endl << \"*** The problem solved!\" << std::endl;\n\t}\n\telse {\n\t\tstd::cout << std::endl << std::endl << \"*** The problem FAILED!\"\n\t\t\t<< \" (\" << static_cast<int>(status) << \")\" << std::endl;\n\t\t//assert(false);\n\t}\n\n\t// As the SmartPtrs go out of scope, the reference count\n\t// will be decremented and the objects will automatically\n\t// be deleted.\n\t// ---- //\n\n\n\t// DEBUG.\n\t//formulation.print_constraint_evaluations();\n\n\tstd::vector< Number > output;\n\tformulation.get_values(output);\n\tassert(output.size() == num_total_variables());\n\t//std::cout << \"final = \" << formulation.eval_function(&(output[0])) << \")\" << std::endl;\n\n\tstd::cout << \"Final error = \";\n\tfor (int i = 0; i < functions.size(); ++i)\n\t\tstd::cout << functions[i]->eval(&output[0]) << \", \";\n\tstd::cout << std::endl;\n\n\n\t// Update symmetry groups.\n\tupdate(output);\n}\n\nvoid MeshCuboidNonLinearSolver::update(const std::vector< Number >& _values)\n{\n\tupdate_cuboids(_values);\n\tupdate_reflection_symmetry_groups(_values);\n\tupdate_rotation_symmetry_groups(_values);\n}\n\nvoid MeshCuboidNonLinearSolver::update_cuboids(const std::vector< Number >& _values)\n{\n\tconst unsigned int dimension = 3;\n\n\tfor (unsigned int cuboid_index = 0; cuboid_index < num_cuboids_; ++cuboid_index)\n\t{\n\t\tMeshCuboid *cuboid = cuboids_[cuboid_index];\n\t\tassert(cuboid);\n\n\t\tMyMesh::Point new_bbox_center(0.0);\n\t\tstd::array<MyMesh::Point, MeshCuboid::k_num_corners> new_bbox_corners;\n\t\tstd::array<MyMesh::Normal, dimension> new_bbox_axes;\n\n\t\tfor (unsigned int corner_index = 0; corner_index < MeshCuboid::k_num_corners; ++corner_index)\n\t\t{\n\t\t\tstd::pair<Index, Index> index_size_pair;\n\t\t\tindex_size_pair = get_cuboid_corner_variable_index_size(cuboid_index, corner_index);\n\t\t\tassert(index_size_pair.second == dimension);\n\t\t\tfor (unsigned int i = 0; i < index_size_pair.second; ++i)\n\t\t\t\tnew_bbox_corners[corner_index][i] = _values[index_size_pair.first + i];\n\n\t\t\tnew_bbox_center += new_bbox_corners[corner_index];\n\t\t}\n\t\tnew_bbox_center = new_bbox_center / MeshCuboid::k_num_corners;\n\n\t\tfor (unsigned int axis_index = 0; axis_index < dimension; ++axis_index)\n\t\t{\n\t\t\tstd::pair<Index, Index> index_size_pair;\n\t\t\tindex_size_pair = get_cuboid_axis_variable_index_size(cuboid_index, axis_index);\n\t\t\tassert(index_size_pair.second == dimension);\n\t\t\tfor (unsigned int i = 0; i < index_size_pair.second; ++i)\n\t\t\t\tnew_bbox_axes[axis_index][i] = _values[index_size_pair.first + i];\n\n\t\t\tnew_bbox_axes[axis_index].normalize();\n\n\n\t\t\t// Flip axes.\n\t\t\tMyMesh::Point minus_axis_direction(0.0), plus_axis_direction(0.0);\n\n\t\t\tfor (int axis_1 = 0; axis_1 < 2; ++axis_1)\n\t\t\t{\n\t\t\t\tfor (int axis_2 = 0; axis_2 < 2; ++axis_2)\n\t\t\t\t{\n\t\t\t\t\tstd::bitset<3> bits;\n\t\t\t\t\tbits[(axis_index + 1) % 3] = axis_1;\n\t\t\t\t\tbits[(axis_index + 2) % 3] = axis_2;\n\n\t\t\t\t\tbits[axis_index] = false;\n\t\t\t\t\tint minus_corner_index = bits.to_ulong();\n\t\t\t\t\tminus_axis_direction += new_bbox_corners[minus_corner_index];\n\n\t\t\t\t\tbits[axis_index] = true;\n\t\t\t\t\tint plus_corner_index = bits.to_ulong();\n\t\t\t\t\tplus_axis_direction += new_bbox_corners[plus_corner_index];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Compare the axis with the direction from the center to the average of corner points on +/- side.\n\t\t\tminus_axis_direction = (minus_axis_direction / 4.0 - new_bbox_center).normalized();\n\t\t\tplus_axis_direction = (plus_axis_direction / 4.0 - new_bbox_center).normalized();\n\n\t\t\t//if (dot(new_bbox_axes[axis_index], minus_axis_direction)\n\t\t\t//\t> dot(new_bbox_axes[axis_index], plus_axis_direction))\n\t\t\tif (dot(new_bbox_axes[axis_index], cuboid->get_bbox_axis(axis_index)) < 0)\n\t\t\t{\n\t\t\t\t// Flip.\n\t\t\t\tnew_bbox_axes[axis_index] = -new_bbox_axes[axis_index];\n\t\t\t}\n\t\t}\n\n\t\tcuboid->set_bbox_center(new_bbox_center);\n\t\tcuboid->set_bbox_corners(new_bbox_corners);\n\t\tcuboid->set_bbox_axes(new_bbox_axes, false);\n\n\t\t// Update cuboid surface points.\n\t\tfor (unsigned int point_index = 0; point_index < cuboid->num_cuboid_surface_points();\n\t\t\t++point_index)\n\t\t{\n\t\t\tMeshCuboidSurfacePoint *cuboid_surface_point = cuboid->get_cuboid_surface_point(point_index);\n\n\t\t\tMyMesh::Point new_point(0.0);\n\t\t\tfor (unsigned int corner_index = 0; corner_index < MeshCuboid::k_num_corners; ++corner_index)\n\t\t\t\tnew_point += cuboid_surface_point->corner_weights_[corner_index] * new_bbox_corners[corner_index];\n\n\t\t\tcuboid_surface_point->point_ = new_point;\n\t\t}\n\t}\n}\n\nvoid MeshCuboidNonLinearSolver::update_reflection_symmetry_groups(const std::vector< Number >& _values)\n{\n\tconst unsigned int dimension = 3;\n\n\tfor (unsigned int symmetry_group_index = 0; symmetry_group_index < num_reflection_symmetry_groups_;\n\t\t++symmetry_group_index)\n\t{\n\t\tMyMesh::Normal n; double t;\n\n\t\tstd::pair<Index, Index> index_size_pair;\n\t\tindex_size_pair = get_reflection_symmetry_group_variable_n_index_size(symmetry_group_index);\n\t\tassert(index_size_pair.second == dimension);\n\t\tfor (unsigned int i = 0; i < index_size_pair.second; ++i)\n\t\t\tn[i] = _values[index_size_pair.first + i];\n\n\t\tindex_size_pair = get_reflection_symmetry_group_variable_t_index_size(symmetry_group_index);\n\t\tassert(index_size_pair.second == 1);\n\t\tt = _values[index_size_pair.first];\n\n\t\treflection_symmetry_groups_[symmetry_group_index]->set_reflection_plane(n, t);\n\t}\n}\n\nvoid MeshCuboidNonLinearSolver::update_rotation_symmetry_groups(const std::vector< Number >& _values)\n{\n\tconst unsigned int dimension = 3;\n\n\tfor (unsigned int symmetry_group_index = 0; symmetry_group_index < num_rotation_symmetry_groups_;\n\t\t++symmetry_group_index)\n\t{\n\t\tMyMesh::Normal n; MyMesh::Point t;\n\n\t\tstd::pair<Index, Index> index_size_pair;\n\t\tindex_size_pair = get_rotation_symmetry_group_variable_n_index_size(symmetry_group_index);\n\t\tassert(index_size_pair.second == dimension);\n\t\tfor (unsigned int i = 0; i < index_size_pair.second; ++i)\n\t\t\tn[i] = _values[index_size_pair.first + i];\n\n\t\tindex_size_pair = get_rotation_symmetry_group_variable_t_index_size(symmetry_group_index);\n\t\tassert(index_size_pair.second == dimension);\n\t\tfor (unsigned int i = 0; i < index_size_pair.second; ++i)\n\t\t\tt[i] = _values[index_size_pair.first + i];\n\n\t\trotation_symmetry_groups_[symmetry_group_index]->set_rotation_axis(n, t);\n\t}\n}\n\nvoid MeshCuboidNonLinearSolver::create_cuboid_sample_point_ann_trees(\n\tstd::vector<ANNpointArray>& _cuboid_ann_points,\n\tstd::vector<ANNkd_tree *>& _cuboid_ann_kd_tree) const\n{\n\tdelete_cuboid_sample_point_ann_trees(_cuboid_ann_points, _cuboid_ann_kd_tree);\n\t_cuboid_ann_points.resize(num_cuboids_);\n\t_cuboid_ann_kd_tree.resize(num_cuboids_);\n\n\tfor (unsigned int cuboid_index = 0; cuboid_index < num_cuboids_; ++cuboid_index)\n\t{\n\t\t_cuboid_ann_kd_tree[cuboid_index] = NULL;\n\t\t_cuboid_ann_points[cuboid_index] = NULL;\n\n\t\tMeshCuboid *cuboid = cuboids_[cuboid_index];\n\t\tunsigned int num_cuboid_sample_points = cuboid->num_sample_points();\n\t\tif (num_cuboid_sample_points == 0)\n\t\t\tcontinue;\n\n\t\tEigen::MatrixXd cuboid_sample_points(3, num_cuboid_sample_points);\n\n\t\tfor (unsigned int point_index = 0; point_index < num_cuboid_sample_points; ++point_index)\n\t\t{\n\t\t\tfor (unsigned int i = 0; i < 3; ++i)\n\t\t\t\tcuboid_sample_points.col(point_index)(i) =\n\t\t\t\tcuboid->get_sample_point(point_index)->point_[i];\n\t\t}\n\n\t\t_cuboid_ann_kd_tree[cuboid_index] = ICP::create_kd_tree(cuboid_sample_points,\n\t\t\t_cuboid_ann_points[cuboid_index]);\n\t\tassert(_cuboid_ann_points[cuboid_index]);\n\t\tassert(_cuboid_ann_kd_tree[cuboid_index]);\n\t}\n}\n\nvoid MeshCuboidNonLinearSolver::delete_cuboid_sample_point_ann_trees(\n\tstd::vector<ANNpointArray>& _cuboid_ann_points,\n\tstd::vector<ANNkd_tree *>& _cuboid_ann_kd_tree) const\n{\n\tif (_cuboid_ann_points.empty() && _cuboid_ann_kd_tree.empty())\n\t\treturn;\n\n\tassert(_cuboid_ann_points.size() == num_cuboids_);\n\tassert(_cuboid_ann_kd_tree.size() == num_cuboids_);\n\n\tfor (unsigned int cuboid_index = 0; cuboid_index < num_cuboids_; ++cuboid_index)\n\t{\n\t\tif (_cuboid_ann_points[cuboid_index]) annDeallocPts(_cuboid_ann_points[cuboid_index]);\n\t\tif (_cuboid_ann_kd_tree[cuboid_index]) delete _cuboid_ann_kd_tree[cuboid_index];\n\t}\n\n\t_cuboid_ann_points.clear();\n\t_cuboid_ann_kd_tree.clear();\n}\n", "meta": {"hexsha": "3c82ba18f054007ab25b3f7cf639be5dce2cea17", "size": 43473, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MeshCuboidNonLinearSolver.cpp", "max_stars_repo_name": "mhsung/cuboid-prediction", "max_stars_repo_head_hexsha": "23eec356dcd32da62b20e96c9ebf0913dadb6921", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2015-12-27T10:57:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T09:50:02.000Z", "max_issues_repo_path": "src/MeshCuboidNonLinearSolver.cpp", "max_issues_repo_name": "mhsung/cuboid-prediction", "max_issues_repo_head_hexsha": "23eec356dcd32da62b20e96c9ebf0913dadb6921", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-01T01:07:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-01T01:07:33.000Z", "max_forks_repo_path": "src/MeshCuboidNonLinearSolver.cpp", "max_forks_repo_name": "mhsung/cuboid-prediction", "max_forks_repo_head_hexsha": "23eec356dcd32da62b20e96c9ebf0913dadb6921", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-10-29T06:14:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-05T18:38:40.000Z", "avg_line_length": 35.4592169657, "max_line_length": 118, "alphanum_fraction": 0.7696501277, "num_tokens": 11837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521105, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2565722522998844}}
{"text": "// [[Rcpp::plugins(openmp)]]\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n#include <Rcpp.h>\n#include <RcppEigen.h>\n#include <Eigen/Core>\n#include <random>\n#include \"distributions.h\"\n#include \"concurrentqueue.h\"\n// [[Rcpp::depends(RcppEigen)]]\nusing namespace Rcpp;\nusing namespace RcppEigen;\nusing namespace Eigen;\nusing Eigen::Matrix;\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing Eigen::SparseVector;\nusing Eigen::LLT;\nusing Eigen::Lower;\nusing Eigen::Map;\nusing Eigen::Upper;\ntypedef Map<MatrixXd> MapMatd;\n\ninline void initialize_file( std::ofstream& outFile,int M,int N,int groups, int F){\n  bool queueFull;\n  queueFull=0;\n\n\n  outFile<< \"iteration,\"<<\"mu,\";\n  for(unsigned int i = 0; i < M; ++i){\n    outFile << \"beta[\" << (i+1) << \"],\";\n\n  }\n  outFile<<\"sigmaE,\";\n  for(unsigned int i = 0; i < M; ++i){\n    outFile << \"comp[\" << (i+1) << \"],\";\n  }\n  for(unsigned int i = 0; i < groups; ++i){\n    outFile << \"sigmaG[\" << (i+1) << \"],\";\n  }\n  unsigned int i;\n  for(i = 0; i < (N-1);i++){\n    outFile << \"epsilon[\" << (i+1) << \"],\";\n  }\n\n  outFile << \"epsilon[\" << (i+1) << \"],\";\n\n  for(i = 0; i < F; i ++){\n    outFile << \"alpha[\" << (i+1) << \"],\";\n  }\n  outFile << \"sigmaF\";\n  outFile<<\"\\n\";\n}\n\n\n//' BayesRR sampler\n//' @param outputFile The file in which the samples aftare burnin will be stored\n//' @param seed random seed\n//' @param max_iterations total of number of samples taken.\n//' @param burn_in integer leq than max_iterations, number of samples used for burn in, after which, al samples will  be stored in the outputFile\n//' @param thinning thinning regime, not implemented\n//' @param X matrix of snp markers, or covariates of interest\n//' @param Y vector of response variates, must have the same number of rows as X\n//' @param sigma0 variance of the zero-centered normal prior over the intercept\n//' @param v0E degrees of  freedom of the prior inverse scaled chi-squared distribution over residues variance\n//' @param s02E scale parameter of the prior inverse scaled chi-squared distribution over residues variance\n//' @param v0G degrees of freedom of the prior inverse scaled chi-squared distribution over genetic effects variance\n//' @param s02G scale parameter of the prior inverse scaled chi-squared distribution over genetic effects variance\n//' @param cva Matrix of mixture variances for groups, rows must be the same as number of groups, columns the same as number of mixtures.\n//' @param groups number of groups\n//' @param gAssign Vector of the same size as the number of columns of X, containing group assignments for each column(starting with group 0).\n//' @param fixed Matrxi with same rows as X and Y , contains the fixed effects, those whose prior is always different than zero\n// [[Rcpp::export]]\nvoid BayesRSamplerV2Groups(std::string outputFile, int seed, int max_iterations, int burn_in, int thinning, Eigen::MatrixXd X, Eigen::VectorXd Y,double sigma0, double v0E, double s02E, double v0G, double s02G,Eigen::MatrixXd cva,int groups, Eigen::VectorXi gAssign, Eigen::MatrixXd fixed) {\n  int flag;\n  moodycamel::ConcurrentQueue<Eigen::VectorXd> q;\n  flag=0;\n  int N(Y.size());\n  int M(X.cols());\n  int F(fixed.cols());\n  VectorXd components(M);\n  std::ofstream outFile;\n\n  outFile.open(outputFile);\n  int K(cva.cols()+1);\n  VectorXd sampleq(2*M+3+groups+ N + F+ 1);\n  IOFormat CommaInitFmt(StreamPrecision, DontAlignCols, \", \", \", \", \"\", \"\", \"\", \"\");\n  ////////////validate inputs\n\n  if(max_iterations < burn_in || max_iterations<1 || burn_in<1) //validations related to mcmc burnin and iterations\n  {\n    Rcpp::Rcerr<<\"error: burn_in has to be a positive integer and smaller than the maximum number of iterations \";\n    return;\n  }\n  if(sigma0 < 0 || v0E < 0 || s02E < 0 || v0G < 0||  s02G < 0 )//validations related to hyperparameters\n  {\n    Rcpp::Rcerr<<\"error: hyper parameters have to be positive\";\n    //return;\n  }\n  if((cva.array()==0).any() )//validations related to hyperparameters\n  {\n    Rcpp::Rcerr<<\"error: the zero component is already included in the model by default\";\n    //return;\n  }\n  if((cva.array()<0).any() )//validations related to hyperparameters\n  {\n    Rcpp::Rcerr<<\"error: the variance of the components should be positive\";\n    //return;\n  }\n  /////end of declarations//////\n\n  initialize_file(outFile,M,N,groups,F);\n // Eigen::initParallel();\n//  Eigen::setNbThreads(10);\n  //double sum_beta_sqr;\n#ifdef _OPENMP\n  omp_set_num_threads(2);\n#endif\n#pragma omp parallel num_threads(2) shared(flag,q,M,N,F)\n{\n#pragma omp sections\n{\n  //producer\n  {\n\n    //mean and residual variables\n    double mu; // mean or intercept\n    double sigmaG; //genetic variance\n    double sigmaE; // residuals variance\n    VectorXd sigmaGG(groups);\n    double sigmaF; // fixed effects variance\n\n    //component variables\n    MatrixXd priorPi(groups,K); // prior probabilities for each component\n    MatrixXd pi(groups,K); // mixture probabilities\n    VectorXd cVa(K); //component-specific variance\n    VectorXd logL(K); // log likelihood of component\n    VectorXd muk(K); // mean of k-th component marker effect size\n    VectorXd denom(K-1); // temporal variable for computing the inflation of the effect variance for a given non-zero componnet\n    int m0; // total num ber of markes in model\n    MatrixXd v(groups,K); //variable storing the component assignment\n    VectorXd cVaI(K);// inverse of the component variances\n\n    //linear model variables\n    MatrixXd beta(M,1); // effect sizes\n    VectorXd alpha(F); // fixed effects\n    VectorXd y_tilde(N); // variable containing the adjusted residuals to exclude the effects of a given marker\n    VectorXd epsilon(N); // variable containing the residuals\n\n    //sampler variables\n    VectorXd sample(2*M+3+groups+ N + F+ 1); // varible containg a sambple of all variables in the model, M marker effects, M component assigned to markers, sigmaE, sigmaG, mu, iteration number and Explained variance\n    std::vector<int> markerI;\n    for (int i=0; i<M; ++i) {\n      markerI.push_back(i);\n    }\n    std::vector<int> fixedI;\n    for(int j=0; j<F; ++j){\n      fixedI.push_back(j);\n    }\n    VectorXd xsquared(M);\n    double num;\n\n    int marker;\n    double acum;\n    VectorXd betaAcum(groups);\n\n\n\n        for(int i=0; i < groups; i++){\n        \tpriorPi.row(i)(0)=0.5;\n        \tfor(int k=1;k<K;k++){\n        \tpriorPi.row(i)(k)=0.5/K;\n        \t}\n        }\n    y_tilde.setZero();\n    //cVa[0] = 0;\n    //cVa.segment(1,(K-1))=cva;\n\n    //cVaI[0] = 0;\n    //cVaI.segment(1,(K-1))=cVa.segment(1,(K-1)).cwiseInverse();\n    //beta=beta.setRandom();\n\n    //beta=(beta.array().abs() > 1e-6  ).select(beta, MatrixXd::Zero(M,1));\n    beta.setZero();\n    alpha.setZero();\n\n    //mu=norm_rng(0,1);\n    mu=0;\n\n\n    betaAcum.setZero();\n    // sigmaG=(1*cVa).sum()/M;\n    for(int i=0; i<groups;i++)\n      sigmaGG[i]=beta_rng(1,1);\n\n    sigmaF= (double)R::runif(0,1);\n\n    pi=priorPi;\n\n    components.setZero();\n    std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();\n    epsilon= Y.array() - mu;\n    sigmaE=epsilon.squaredNorm()/N*0.5;\n    xsquared=X.colwise().squaredNorm();\n    for(int iteration=0; iteration < max_iterations; iteration++){\n\n      if(iteration>0)\n        if( iteration % (int)std::ceil(max_iterations/10) ==0)\n          Rcpp::Rcout << \"iteration: \"<<iteration <<\"\\n\";\n\n        epsilon= epsilon.array()+mu;//  we substract previous value\n        mu = norm_rng(epsilon.sum()/(double)N, sigmaE/(double)N); //update mu\n        epsilon= epsilon.array()-mu;// we substract again now epsilon =Y-mu-X*beta\n\n        std::random_shuffle(fixedI.begin(), fixedI.end());\n        for(int cur_fix=0; cur_fix < F; cur_fix++){\n          int cur = fixedI[cur_fix];\n          auto cur_alpha = alpha[cur];\n          y_tilde= epsilon.array()+(fixed.col(cur)*cur_alpha).array();\n          auto denom_f = (N-1) + (sigmaE/sigmaF);\n          auto num_f = (fixed.col(cur).cwiseProduct(y_tilde)).sum();\n          alpha[cur] = norm_rng(num_f/denom_f,sigmaE/denom_f);\n          epsilon = y_tilde - fixed.col(cur)*alpha[cur];\n        }\n\n        std::random_shuffle(markerI.begin(), markerI.end());\n\n        m0=0;\n        v.setZero();\n        betaAcum.setZero();\n        for(int j=0; j < M; j++){\n\n          marker= markerI[j];\n          sigmaG=sigmaGG[gAssign(marker)];\n\n          cVa[0]=0;\n          cVaI[0]=0;\n          cVa.segment(1,(K-1))=cva.row(gAssign(marker));\n          cVaI.segment(1,(K-1))=(cVa.segment(1,(K-1))).cwiseInverse();\n\n\n          y_tilde= epsilon.array()+(X.col(marker)*beta(marker,0)).array();//now y_tilde= Y-mu-X*beta+ X.col(marker)*beta(marker)_old\n\n\n\n\n          muk[0]=0.0;//muk for the zeroth component=0\n\n          // Rcpp::Rcout<< muk;\n          //we compute the denominator in the variance expression to save computations\n          denom=xsquared(marker)+(sigmaE/sigmaG)*cVaI.segment(1,(K-1)).array();\n          //muk for the other components is computed according to equaitons\n          num=(X.col(marker).cwiseProduct(y_tilde)).sum();\n          muk.segment(1,(K-1))= num/denom.array();\n\n\n\n          logL= pi.row(gAssign(marker)).array().log();//first component probabilities remain unchanged\n\n\n          // Here we reproduce the fortran code\n          logL.segment(1,(K-1))=logL.segment(1,(K-1)).array() - 0.5*((((sigmaG/sigmaE)*(xsquared(marker))*cVa.segment(1,(K-1)).array() + 1).array().log()))+\n            0.5*( muk.segment(1,(K-1)).array()*num)/sigmaE;\n\n          double p((double)R::runif( 0.0, 1.0 ));//\n\n          if(((logL.segment(1,(K-1)).array()-logL[0]).abs().array() >700 ).any() ){\n            acum=0;\n          }else{\n            acum=1.0/((logL.array()-logL[0]).exp().sum());\n          }\n\n          for(int k=0;k<K;k++){\n            if(p<=acum){\n              if(k==0){\n                beta(marker,0)=0;\n              }else{\n                beta(marker,0)=norm_rng(muk[k],sigmaE/denom[k-1]);\n                betaAcum(gAssign(marker))+= pow(beta(marker,0),2);\n                // beta(marker,0)=norm_rng(rhs/denom[k-1],sigmaE/denom[k-1]);\n              }\n              v.row(gAssign(marker))(k)+=1.0;\n              components[marker]=k;\n              break;\n            }else{\n              if(((logL.segment(1,(K-1)).array()-logL[k+1]).abs().array() >700 ).any() ){\n                acum+=0;\n              }\n              else{\n                acum+=1.0/((logL.array()-logL[k+1]).exp().sum());\n              }\n            }\n          }\n          epsilon=y_tilde-X.col(marker)*beta(marker,0);//now epsilon contains Y-mu - X*beta+ X.col(marker)*beta(marker)_old- X.col(marker)*beta(marker)_new\n\n\n        }\n\n\n        sigmaF = inv_scaled_chisq_rng(v0E+F,(alpha.squaredNorm()+v0E*s02E)/(v0E+F));\n        // Rcpp::Rcout << sigmaF;\n\n        sigmaE=inv_scaled_chisq_rng(v0E+N,((epsilon).squaredNorm()+v0E*s02E)/(v0E+N));\n\n\n        for(int i=0; i<groups; i++){\n          m0=v.row(i).sum()-v.row(i)(0);\n          sigmaGG[i]=inv_scaled_chisq_rng(v0G+m0,(betaAcum(i)*m0+v0G*s02G)/(v0G+m0));\n          pi.row(i)=dirichilet_rng(v.row(i).array() + 1.0);\n\n        }\n\n        if(iteration >= burn_in)\n        {\n          if(iteration % thinning == 0){\n            sample<< iteration,mu,beta,sigmaE,components,sigmaGG,epsilon,alpha,sigmaF;\n\n            q.enqueue(sample);\n            //here we have the consumer\n#ifdef _OPENMP\n\n#else\n            if(q.try_dequeue(sampleq)){\n\n              outFile<< sampleq.transpose().format(CommaInitFmt) << \"\\n\";\n            }\n#endif\n          }\n\n        }\n\n    }\n\n    std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();\n    auto duration = std::chrono::duration_cast<std::chrono::seconds>( t2 - t1 ).count();\n    Rcpp::Rcout << \"duration: \"<<duration << \"s\\n\";\n    flag=1;\n  }//end producer\n  //consumer\n    #ifdef _OPENMP\n    #pragma omp section\n    {\n\n\n      while(!flag ){\n        if(q.try_dequeue(sampleq)){\n          outFile<< sampleq.transpose().format(CommaInitFmt) << \"\\n\";\n        }\n      }//while\n\n\n\n    }// endconsumer\n    #endif\n}\n\n}\n\n}\n\n", "meta": {"hexsha": "20908f416d66d27a5f24d54a36bda227966f46a3", "size": 11959, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BayesRv2Groups.cpp", "max_stars_repo_name": "ctggroup/BayesRRcpp", "max_stars_repo_head_hexsha": "23381fcc5db93916f875c005529c8b8cba6fd78a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-14T16:05:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T16:05:16.000Z", "max_issues_repo_path": "src/BayesRv2Groups.cpp", "max_issues_repo_name": "ctggroup/BayesRRcpp", "max_issues_repo_head_hexsha": "23381fcc5db93916f875c005529c8b8cba6fd78a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BayesRv2Groups.cpp", "max_forks_repo_name": "ctggroup/BayesRRcpp", "max_forks_repo_head_hexsha": "23381fcc5db93916f875c005529c8b8cba6fd78a", "max_forks_repo_licenses": ["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.0359116022, "max_line_length": 290, "alphanum_fraction": 0.6125094071, "num_tokens": 3366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961016, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.25655460727394686}}
{"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#ifndef SAMPLER_HH\n#define SAMPLER_HH\n\n#include \"random.hh\"\n#include <functional>\n#include <boost/mpl/if.hpp>\n\nnamespace graph_tool\n{\nusing namespace std;\nusing namespace boost;\n\n// Discrete sampling via vose's alias method.\n\n// See http://www.keithschwarz.com/darts-dice-coins/ for a very clear\n// explanation.\n\ntemplate <class Value, class KeepReference = mpl::true_>\nclass Sampler\n{\npublic:\n    Sampler(const vector<Value>& items,\n            const vector<double>& probs)\n        : _items(items), _probs(probs), _alias(items.size())\n    {\n        double S = 0;\n        for (size_t i = 0; i < _probs.size(); ++i)\n            S += _probs[i];\n\n        for (size_t i = 0; i < _probs.size(); ++i)\n        {\n            _probs[i] *= _probs.size() / S;\n            if (_probs[i] < 1)\n                _small.push_back(i);\n            else\n                _large.push_back(i);\n        }\n\n        while (!(_small.empty() || _large.empty()))\n        {\n            size_t l = _small.back();\n            size_t g = _large.back();\n            _small.pop_back();\n            _large.pop_back();\n\n            _alias[l] = g;\n            _probs[g] = (_probs[l] + _probs[g]) - 1;\n            if (_probs[g] < 1)\n                _small.push_back(g);\n            else\n                _large.push_back(g);\n        }\n\n        // fix numerical instability\n        for (size_t i = 0; i < _large.size(); ++i)\n            _probs[_large[i]] = 1;\n        for (size_t i = 0; i < _small.size(); ++i)\n            _probs[_small[i]] = 1;\n        _large.clear();\n        _small.clear();\n    }\n\n    Sampler() {}\n\n    template <class RNG>\n    const Value& sample(RNG& rng)\n    {\n        uniform_int_distribution<size_t> sample(0, _probs.size() - 1);\n        size_t i = sample(rng);\n\n        bernoulli_distribution coin(_probs[i]);\n        if (coin(rng))\n            return _items[i];\n        else\n            return _items[_alias[i]];\n    }\n\n    size_t size() const { return _items.size(); }\n\nprivate:\n\n    typedef typename mpl::if_<KeepReference,\n                              const vector<Value>&,\n                              vector<Value> >::type items_t;\n    items_t _items;\n    vector<double> _probs;\n    vector<size_t> _alias;\n    vector<size_t> _small;\n    vector<size_t> _large;\n};\n\n// uniform sampling from containers\n\ntemplate <class Container, class RNG>\nconst typename Container::value_type& uniform_sample(const Container& v, RNG& rng)\n{\n    std::uniform_int_distribution<size_t> i_rand(0, v.size() - 1);\n    return v[i_rand(rng)];\n}\n\n\n} // namespace graph_tool\n\n#endif // SAMPLER_HH\n", "meta": {"hexsha": "3330f37f99143eb53606230b8e35d33f1daa265e", "size": 3353, "ext": "hh", "lang": "C++", "max_stars_repo_path": "graph-tool/src/graph/generation/sampler.hh", "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/generation/sampler.hh", "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/generation/sampler.hh", "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": 27.4836065574, "max_line_length": 82, "alphanum_fraction": 0.5937966001, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2565282264357828}}
{"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 MSSM_TWOLOOPHIGGS_H\n#define MSSM_TWOLOOPHIGGS_H\n\n#include <Eigen/Core>\n\n/**\n * @file mssm_twoloophiggs.hpp\n * @brief function declarations for 2-loop MSSM Higgs self-energies\n *        and tadpoles\n *\n * Notation:\n *\n * mt2    : squared DR-bar top mass in the MSSM\n * mb2    : squared DR-bar bottom mass in the MSSM\n * mtau2  : squared DR-bar tau mass in the MSSM\n * mg     : DR-bar gluino mass in the MSSM\n * mA2    : squared DR-bar CP-odd Higgs mass in the MSSM\n * mst12  : squared DR-bar lightest stop mass\n * mst22  : squared DR-bar heaviest stop mass\n * msb12  : squared DR-bar lightest sbottom mass\n * msb22  : squared DR-bar heaviest sbottom mass\n * mstau12: squared DR-bar lightest stau mass\n * mstau22: squared DR-bar heaviest stau mass\n * msv2   : squared DR-bar tau sneutrino mass\n *\n * sxt    : sine of DR-bar stop mixing angle in the MSSM\n * cxt    : cosine of DR-bar stop mixing angle in the MSSM\n * sxb    : sine of DR-bar sbottom mixing angle in the MSSM\n * cxb    : cosine of DR-bar sbottom mixing angle in the MSSM\n * sintau : sine of DR-bar stau mixing angle in the MSSM\n * costau : cosine of DR-bar stau mixing angle in the MSSM\n *\n * gs     : DR-bar strong gauge coupling g3 in the MSSM\n * mu     : DR-bar mu-parameter in the MSSM (arXiv:0907.4682)\n * tanb   : DR-bar tan(beta) = vu/vd in the MSSM\n * cotb   : DR-bar 1/tan(beta) in the MSSM\n * vev2   : squared DR-bar vev^2 = (vu^2 + vd^2) in the MSSM\n *\n * scheme : DR-bar scheme (0) or on-shell scheme (1)\n */\n\nnamespace flexiblesusy {\nnamespace mssm_twoloophiggs {\n\n// tadpoles\n\nEigen::Matrix<double, 2, 1> tadpole_higgs_2loop_at_as_mssm(\n   double mt2, double mg, double mst12, double mst22,\n   double sxt, double cxt, double scale2,\n   double mu, double tanb, double vev2, double gs);\n\nEigen::Matrix<double, 2, 1> tadpole_higgs_2loop_at_at_mssm(\n   double mt2, double mb2, double mA2, double mst12,\n   double mst22, double msb12, double msb22,\n   double sxt, double cxt, double sxb, double cxb,\n   double scale2, double mu, double tanb, double vev2);\n\nEigen::Matrix<double, 2, 1> tadpole_higgs_2loop_ab_as_mssm(\n   double mb2, double mg, double msb12, double msb22,\n   double sxb, double cxb, double scale2,\n   double mu, double cotb, double vev2, double gs);\n\nEigen::Matrix<double, 2, 1> tadpole_higgs_2loop_atau_atau_mssm(\n   double mtau2, double mA2, double msv2, double mstau12,\n   double mstau22, double sintau, double costau, double scale2,\n   double mu, double tanb, double vev2);\n\n// self-energies\n\nEigen::Matrix<double, 2, 2> self_energy_higgs_2loop_at_as_mssm(\n   double mt2, double mg, double mst12, double mst22,\n   double sxt, double cxt, double scale2, double mu,\n   double tanb, double vev2, double gs, int scheme = 0);\n\nEigen::Matrix<double, 2, 2> self_energy_higgs_2loop_at_at_mssm(\n   double mt2, double mb2, double mA2, double mst12,\n   double mst22, double msb12, double msb22,\n   double sxt, double cxt, double sxb, double cxb,\n   double scale2, double mu, double tanb, double vev2);\n\nEigen::Matrix<double, 2, 2> self_energy_higgs_2loop_ab_as_mssm(\n   double mb2, double mg, double msb12, double msb22,\n   double sxb, double cxb, double scale2, double mu,\n   double cotb, double vev2, double gs, int scheme = 0);\n\nEigen::Matrix<double, 2, 2> self_energy_higgs_2loop_atau_atau_mssm(\n   double mtau2, double mA2, double msv2, double mstau12,\n   double mstau22, double sintau, double costau, double scale2,\n   double mu, double tanb, double vev2, int scheme = 0);\n\n\nEigen::Matrix<double, 2, 2> self_energy_pseudoscalar_2loop_at_as_mssm(\n   double mt2, double mg, double mst12, double mst22,\n   double sxt, double cxt, double scale2, double mu,\n   double tanb, double vev2, double gs);\n\nEigen::Matrix<double, 2, 2> self_energy_pseudoscalar_2loop_at_at_mssm(\n   double mt2, double mb2, double mA2, double mst12,\n   double mst22, double msb12, double msb22,\n   double sxt, double cxt, double sxb, double cxb,\n   double scale2, double mu, double tanb, double vev2);\n\nEigen::Matrix<double, 2, 2> self_energy_pseudoscalar_2loop_ab_as_mssm(\n   double mb2, double mg, double msb12, double msb22,\n   double sxb, double cxb, double scale2, double mu,\n   double cotb, double vev2, double gs);\n\nEigen::Matrix<double, 2, 2> self_energy_pseudoscalar_2loop_atau_atau_mssm(\n   double mtau2, double mA2, double msv2, double mstau12,\n   double mstau22, double sintau, double costau, double scale2,\n   double mu, double tanb, double vev2);\n\n// self-energies with tadpoles added\n\nEigen::Matrix<double, 2, 2> self_energy_higgs_2loop_at_as_mssm_with_tadpoles(\n   double mt2, double mg, double mst12, double mst22,\n   double sxt, double cxt, double scale2, double mu,\n   double tanb, double vev2, double gs, int scheme = 0);\n\nEigen::Matrix<double, 2, 2> self_energy_higgs_2loop_at_at_mssm_with_tadpoles(\n   double mt2, double mb2, double mA2, double mst12,\n   double mst22, double msb12, double msb22,\n   double sxt, double cxt, double sxb, double cxb,\n   double scale2, double mu, double tanb, double vev2);\n\nEigen::Matrix<double, 2, 2> self_energy_higgs_2loop_ab_as_mssm_with_tadpoles(\n   double mb2, double mg, double msb12, double msb22,\n   double sxb, double cxb, double scale2, double mu,\n   double cotb, double vev2, double gs, int scheme = 0);\n\nEigen::Matrix<double, 2, 2> self_energy_higgs_2loop_atau_atau_mssm_with_tadpoles(\n   double mtau2, double mA2, double msv2, double mstau12,\n   double mstau22, double sintau, double costau, double scale2,\n   double mu, double tanb, double vev2, int scheme = 0);\n\n\ndouble self_energy_pseudoscalar_2loop_at_as_mssm_with_tadpoles(\n   double mt2, double mg, double mst12, double mst22,\n   double sxt, double cxt, double scale2, double mu,\n   double tanb, double vev2, double gs);\n\ndouble self_energy_pseudoscalar_2loop_at_at_mssm_with_tadpoles(\n   double mt2, double mb2, double mA2, double mst12,\n   double mst22, double msb12, double msb22,\n   double sxt, double cxt, double sxb, double cxb,\n   double scale2, double mu, double tanb, double vev2);\n\ndouble self_energy_pseudoscalar_2loop_ab_as_mssm_with_tadpoles(\n   double mb2, double mg, double msb12, double msb22,\n   double sxb, double cxb, double scale2, double mu,\n   double cotb, double vev2, double gs);\n\ndouble self_energy_pseudoscalar_2loop_atau_atau_mssm_with_tadpoles(\n   double mtau2, double mA2, double msv2, double mstau12,\n   double mstau22, double sintau, double costau, double scale2,\n   double mu, double tanb, double vev2);\n\n} // namespace mssm_twoloophiggs\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "6de40c062a04819fb780182af93c4059790fa988", "size": 7327, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/src/mssm_twoloophiggs.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/mssm_twoloophiggs.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/mssm_twoloophiggs.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.7055555556, "max_line_length": 81, "alphanum_fraction": 0.7236249488, "num_tokens": 2331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.25639424623464}}
{"text": "// This will be an interface for meshing service and blueberry extension point etc.\n\n#include <numeric>\n#include <thread>\n#include <valarray>\n\n// #define CGAL_EIGEN3_ENABLED\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Surface_mesh.h>\n#include <CGAL/Polygon_mesh_processing/remesh.h>\n#include <CGAL/Polygon_mesh_processing/border.h>\n#include <boost/function_output_iterator.hpp>\n\n// #include <CGAL/Polyhedron_3.h>\n// #include <CGAL/extract_mean_curvature_flow_skeleton.h>\n// #include <CGAL/boost/graph/split_graph_into_polylines.h>\n\n#include <fstream>\n\n#include \"IMeshingKernel.h\"\n\n#include <VesselPathAbstractData.h>\n\n#include <SolidData.h>\n//#include <DiscreteSolidData.h>\n#include <OCCBRepData.h>\n#include <MeshData.h>\n\n#include <TopoDS_Shape.hxx>\n#include <TopoDS_Vertex.hxx>\n#include <TopoDS_Edge.hxx>\n#include <TopExp_Explorer.hxx>\n#include <TopoDS.hxx>\n#include <gp_Pnt.hxx>\n#include <gp_Pln.hxx>\n#include <BRep_Tool.hxx>\n#include <BRep_Builder.hxx>\n#include <BRepTools_WireExplorer.hxx>\n#include <BRepAdaptor_Curve.hxx>\n#include <BRepAdaptor_Surface.hxx>\n\n#include <Geom_Curve.hxx>\n#include <Geom_BSplineCurve.hxx>\n#include <Geom_BSplineSurface.hxx>\n#include <Geom_Plane.hxx>\n#include <GeomConvert.hxx>\n#include <Geom_Line.hxx>\n\n#include <TColStd_Array1OfReal.hxx>\n\n#include <BSplCLib.hxx>\n\n#include <BRepBuilderAPI_MakeFace.hxx>\n#include <BRepBuilderAPI_NurbsConvert.hxx>\n#include <BRepLib_FindSurface.hxx>\n\n#include <boost/regex.hpp>\n#include <boost/scope_exit.hpp>\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <vtkPointData.h>\n#include <vtkDoubleArray.h>\n#include <vtkNew.h>\n#include <vtkProbeFilter.h>\n#include <vtkUnstructuredGridBase.h>\n#include <vtkIdTypeArray.h>\n#include <vtkXMLPolyDataWriter.h>\n#include <vtkXMLUnstructuredGridWriter.h>\n#include <vtkUnstructuredGrid.h>\n#include <vtkCleanPolyData.h>\n#include <vtkvmtkPolyDataSurfaceRemeshing.h>\n#include <vtkvmtkBoundaryLayerGenerator.h>\n#include <vtkvmtkTetGenWrapper.h>\n#include \"crimsonTetGenWrapper.h\"\n#include <vtkvmtkPolyDataToUnstructuredGridFilter.h>\n#include <vtkvmtkPolyDataSizingFunction.h>\n#include <vtkvmtkSurfaceProjection.h>\n#include <vtkCellData.h>\n#include <vtkPolyDataNormals.h>\n#include <vtkGeometryFilter.h>\n#include <vtkvmtkSimpleCapPolyData.h>\n#include <vtkTriangleFilter.h>\n#include <vtkAppendFilter.h>\n#include <vtkvmtkUnstructuredGridTetraFilter.h>\n#include <vtkThreshold.h>\n#include <vtkIntArray.h>\n#include <vtkMath.h>\n#include <vtkMeshQuality.h>\n#include <vtkTriangle.h>\n#include <vtkCellLocator.h>\n#include <vtkExtractCells.h>\n#include <vtkFeatureEdges.h>\n\n#include <Wm5ContMinSphere3.h>\n#include <Wm5ApprPlaneFit3.h>\n\n#include <boost/format.hpp>\n#include <qstandardpaths.h>\n\n#include <gsl.h>\n\n#include <unordered_set>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::Point_3 Point;\ntypedef CGAL::Surface_mesh<Point> Mesh;\ntypedef Mesh::Vertex_index Vertex_index;\ntypedef boost::graph_traits<Mesh>::halfedge_descriptor halfedge_descriptor;\ntypedef boost::graph_traits<Mesh>::edge_descriptor     edge_descriptor;\ntypedef boost::graph_traits<Mesh>::face_descriptor     face_descriptor;\ntypedef boost::graph_traits<Mesh>::vertex_descriptor   vertex_descriptor;\nnamespace PMP = CGAL::Polygon_mesh_processing;\n\n// typedef CGAL::Mean_curvature_flow_skeletonization<Mesh>       Skeletonization;\n// typedef Skeletonization::Skeleton                             Skeleton;\n// typedef Skeleton::vertex_descriptor                           Skeleton_vertex;\n// typedef Skeleton::edge_descriptor                             Skeleton_edge;\n\nnamespace crimson\n{\n\tclass MeshingTask : public crimson::async::TaskWithResult<mitk::BaseData::Pointer>\n\t{\n\tpublic:\n\t\tMeshingTask(const mitk::BaseData::Pointer& solid, const IMeshingKernel::GlobalMeshingParameters& params,\n\t\t\tconst std::map<FaceIdentifier, IMeshingKernel::LocalMeshingParameters>& localParams,\n\t\t\tconst std::map<VesselPathAbstractData::VesselPathUIDType, std::string>& vesselUIDtoNameMap)\n\t\t\t: solid(solid)\n\t\t\t, params(params)\n\t\t\t, localParams(localParams)\n\t\t\t, vesselUIDtoNameMap(vesselUIDtoNameMap)\n\t\t{\n\t\t}\n\t\t~MeshingTask() { }\n\n\t\tvoid cancel() override\n\t\t{\n\t\t\tcrimson::async::TaskWithResult<mitk::BaseData::Pointer>::cancel();\n\t\t}\n\n\tprotected:\n\t\tmitk::BaseData::Pointer solid;\n\t\tIMeshingKernel::GlobalMeshingParameters params;\n\t\tstd::map<FaceIdentifier, IMeshingKernel::LocalMeshingParameters> localParams;\n\t\tstd::map<VesselPathAbstractData::VesselPathUIDType, std::string> vesselUIDtoNameMap;\n\t};\n\n\n\tclass OCCMeshingTask : public crimson::MeshingTask\n\t{\n\tpublic:\n\t\tOCCMeshingTask(const mitk::BaseData::Pointer& solid, const IMeshingKernel::GlobalMeshingParameters& params,\n\t\t\tconst std::map<FaceIdentifier, IMeshingKernel::LocalMeshingParameters>& localParams,\n\t\t\tconst std::map<VesselPathAbstractData::VesselPathUIDType, std::string>& vesselUIDtoNameMap)\n\t\t\t:MeshingTask(solid, params, localParams, vesselUIDtoNameMap) {}\n\n\t\t~OCCMeshingTask(){}\n\n\t\tstd::tuple<State, std::string> runTask() override\n\t\t{\n            static const bool debug = false;\n            auto writeVTU = [](vtkUnstructuredGrid* ug, const char* fn) {\n                if (!debug) return;\n                MITK_INFO << \"writing \" << fn;\n                vtkNew<vtkXMLUnstructuredGridWriter> ugw;\n                ugw->SetFileName((std::string(\"d:/kcl/\") + fn + \".vtu\").c_str());\n                ugw->SetInputData(ug);\n                ugw->Write();\n            };\n            auto writeVTP = [](vtkPolyData* pd, const char* fn) {\n                if (!debug) return;\n                MITK_INFO << \"writing \" << fn;\n                vtkNew<vtkXMLPolyDataWriter> pdw;\n                pdw->SetFileName((std::string(\"d:/kcl/\") + fn + \".vtp\").c_str());\n                pdw->SetInputData(pd);\n                pdw->Write();\n            };\n            auto coordsToVector = [](double* c) {\n                return Wm5::Vector3d(c[0], c[1], c[2]);\n            };\n\n            auto brep = dynamic_cast<SolidData*>(solid.GetPointer());\n\n            if (!brep) {\n                return std::make_tuple(State_Failed, std::string(\"Cannot use solids defined not as OpenCASCADE data\"));\n            }\n\n            stepsAddedSignal(1 + brep->getFaceIdentifierMap().getNumberOfFaceIdentifiers());\n\n            auto faceEdgeSize = [&](int faceId) {\n                const FaceIdentifier& identifier = brep->getFaceIdentifierMap().getFaceIdentifier(faceId);\n                auto it = localParams.find(identifier);\n\n                double targetLength = it == localParams.end() || !it->second.size ? *params.defaultLocalParameters.size : *it->second.size;\n                if (it == localParams.end() || !it->second.sizeRelative ? *params.defaultLocalParameters.sizeRelative : *it->second.sizeRelative) {\n                    targetLength *= sqrt(brep->GetGeometry()->GetBoundingBox()->GetDiagonalLength2());\n                }\n                return targetLength;\n            };\n\n            vtkNew<vtkPolyData> cpy;\n            cpy->DeepCopy(brep->getSurfaceRepresentation()->GetVtkPolyData());\n            auto pd = cpy.Get();\n            //auto pd = brep->getSurfaceRepresentation()->GetVtkPolyData();\n\n            vtkNew<vtkPolyData> remeshedPd;\n            vtkNew<vtkPoints> points;\n\n            vtkNew<vtkIntArray> faceIdArray;\n            faceIdArray->Allocate(1);\n            faceIdArray->SetName(\"Face IDs\");\n\n            remeshedPd->SetPoints(points.GetPointer());\n            remeshedPd->GetCellData()->AddArray(faceIdArray.GetPointer());\n            remeshedPd->Allocate();\n\n            // Compute normals\n            vtkNew<vtkCleanPolyData> c;\n            c->SetInputData(pd);\n            c->Update();\n\n            vtkNew<vtkFeatureEdges> fe;\n            fe->SetInputData(c->GetOutput());\n            fe->FeatureEdgesOff();\n            fe->Update();\n\n            if (fe->GetOutput()->GetNumberOfCells() != 0) {\n                return std::make_tuple(State_Failed, std::string(\"Could not achieve a watertight surface mesh. Try different fillet sizes.\"));\n            }\n\n            vtkNew<vtkPolyDataNormals> n;\n            n->SetInputConnection(c->GetOutputPort());\n            n->SetComputeCellNormals(1);\n            n->SetComputePointNormals(0);\n            n->SetAutoOrientNormals(1);\n            n->SetFlipNormals(0);\n            n->SetConsistency(1);\n            n->SplittingOff();\n            n->Update();\n\n            // Remesh the surface using CGAL\n            vtkPolyData* remeshInput = n->GetOutput();\n            writeVTP(remeshInput, \"remeshInput\");\n            {\n                Mesh mesh;\n\n                for (int j = 0; j < remeshInput->GetPoints()->GetNumberOfPoints(); ++j) {\n                    double* coords = remeshInput->GetPoints()->GetPoint(j);\n                    mesh.add_vertex(Point(coords[0], coords[1], coords[2]));\n                }\n\n                auto fimap = mesh.add_property_map<face_descriptor, int>(\"f:id\").first;\n\n                std::unordered_set<int> faceIdSet;\n\n                auto arr = remeshInput->GetCellData()->GetArray(\"Face IDs\");\n                for (int k = 0; k < remeshInput->GetNumberOfCells(); ++k) {\n                    vtkSmartPointer<vtkCell> cell = remeshInput->GetCell(k);\n                    if (cell->GetCellType() != VTK_TRIANGLE) {\n                        continue;\n                    }\n\n                    // Ensure that all faces are passed into CGAL with consistent ordering\n                    Vertex_index ids[] = {Vertex_index(cell->GetPointId(0)), Vertex_index(cell->GetPointId(1)), Vertex_index(cell->GetPointId(2))};\n\n                    Wm5::Vector3d coords[3];\n                    boost::transform(ids, coords, \n                        [&](Vertex_index id) { \n                            return coordsToVector(remeshInput->GetPoint(id));\n                        }\n                    );\n\n                    Wm5::Vector3d normal = coordsToVector(remeshInput->GetCellData()->GetNormals()->GetTuple(k));\n                    if (normal.Dot((coords[1] - coords[0]).Cross(coords[2] - coords[1])) < 0) {\n                        std::swap(ids[0], ids[1]);\n                    }\n\n                    int faceId = arr->GetTuple1(k);\n                    fimap[mesh.add_face(ids[0], ids[1], ids[2])] = faceId;\n                    faceIdSet.insert(faceId);\n                }\n\n                // Arrange the order of remeshing from largest edge size to smallest\n                struct FaceEdgeSize {\n                    int id;\n                    double edgeSize;\n                };\n                \n                std::vector<FaceEdgeSize> edgeSizes(faceIdSet.size());\n                boost::transform(faceIdSet, edgeSizes.begin(), [&](int faceId) { return FaceEdgeSize{faceId, faceEdgeSize(faceId)}; });\n\n                boost::sort(edgeSizes, [](const FaceEdgeSize& lhs, const FaceEdgeSize& rhs) { return lhs.edgeSize > rhs.edgeSize; });\n\n                // Do the remeshing\n//                int xx = 0;\n                // Map to constrain the edges between different face IDs\n\n                for (const FaceEdgeSize& edgeSize : edgeSizes) {\n                    // Map to constrain the edges between different face IDs\n                    auto cstmap = mesh.add_property_map<edge_descriptor, bool>(\"e:cst\", false).first;\n\n                    // Find all faces for this face Id\n                    std::unordered_set<face_descriptor> facesForId;\n                    boost::copy(\n                        faces(mesh) | boost::adaptors::filtered([&](face_descriptor d) { return fimap[d] == edgeSize.id; }), \n                        std::inserter(facesForId, facesForId.end())\n                    );\n\n                    // Add a layer of faces around the edges of this faceId so that the edge is remeshed well\n                    std::unordered_set<face_descriptor> additionalFacesForId;\n                    for (auto he : mesh.halfedges()) {\n//                         if (mesh.is_border(mesh.edge(he))) {\n//                             continue;\n//                         }\n\n                        int f1Count = facesForId.count(mesh.face(he));\n                        int f2Count = facesForId.count(mesh.face(mesh.opposite(he)));\n                        if (f1Count + f2Count == 1) { // One of the faces is in our faceId, another one is not\n                            cstmap[mesh.edge(he)] = true; // Constrain the edge\n\n                            boost::copy(\n                                mesh.faces_around_target(he) | \n                                    boost::adaptors::filtered([&](face_descriptor d) { return fimap[d] != edgeSize.id; }),\n                                std::inserter(additionalFacesForId, additionalFacesForId.end())\n                            );\n                        }\n                    }\n\n                    // Build the full list of faces to remesh\n                    boost::copy(additionalFacesForId, std::inserter(facesForId, facesForId.end()));\n\n//                     std::ostringstream oss;\n//                     oss << \"d:/kcl/reminput\" << xx++ << \".off\";\n//                     std::ofstream os(oss.str().c_str());\n//                     os << mesh;\n//                     os.close();\n\n                    MITK_INFO << \"Start remeshing of model face \" << edgeSize.id << \" (\" << facesForId.size() << \" faces)...\";\n                    PMP::isotropic_remeshing(\n                        facesForId,\n                        edgeSize.edgeSize,\n                        mesh,\n                        PMP::parameters::number_of_iterations(params.surfaceOptimizationLevel)\n                        .edge_is_constrained_map(cstmap)\n                        .face_patch_map(fimap)\n                        .relax_constraints(true)\n                    );\n                    mesh.collect_garbage();\n                    progressMadeSignal(1);\n\n                    mesh.remove_property_map(cstmap);\n                }\n                MITK_INFO << \"Done remeshing - \" << mesh.number_of_vertices() << \" vertices, \" << mesh.number_of_faces() << \" faces.\";\n\n//                 MITK_INFO << \"Skeletonizing\";\n// \n//                 Skeleton skeleton;\n//                 //CGAL::extract_mean_curvature_flow_skeleton(mesh, skeleton);\n//                 Skeletonization skelMaker(mesh);\n//                 skelMaker.set_quality_speed_tradeoff(0.5);\n//                 skelMaker(skeleton);\n// \n//                 MITK_INFO << \"Done\";\n// \n//                 {\n//                     vtkNew<vtkPolyData> pd;\n//                     vtkNew<vtkPoints> points;\n//                     pd->SetPoints(points.GetPointer());\n//                     pd->Allocate();\n// \n//                     BOOST_FOREACH (Skeleton_vertex v, vertices(skeleton))\n//                         for (vertex_descriptor vd : skeleton[v].vertices) {\n//                             auto p = get(CGAL::vertex_point, mesh, vd);\n//                             points->InsertNextPoint(p[0], p[1], p[2]);\n//                             \n//                             auto p2 = skeleton[v].point;\n//                             points->InsertNextPoint(p2[0], p2[1], p2[2]);\n// \n//                             vtkIdType ids[2] = {points->GetNumberOfPoints() - 2, points->GetNumberOfPoints() - 1};\n// \n//                             pd->InsertNextCell(VTK_LINE, 2, ids);\n// \n//                             auto blSizeForFaceId = [&](int faceId) {\n//                                 const FaceIdentifier& identifier = brep->getFaceIdentifierMap().getFaceIdentifier(faceId);\n//                                 auto it = localParams.find(identifier);\n// \n//                                 return it == localParams.end() || !it->second.propagationDistance ? *params.defaultLocalParameters.propagationDistance : *it->second.propagationDistance;\n//                             };\n// \n//                             double blSize = 0;\n//                             int count = 0;\n//                             for (face_descriptor fd : mesh.faces_around_target(mesh.halfedge(vd))) {\n//                                 blSize += blSizeForFaceId(fimap[fd]);\n//                                 ++count;\n//                             }\n//                             blSize /= count;\n// \n// \n// \n//                             Wm5::Vector3d surfPoint(p[0], p[1], p[2]);\n//                             Wm5::Vector3d skelPoint(p2[0], p2[1], p2[2]);\n// \n//                             Wm5::Vector3d newSurfPoint = skelPoint - surfPoint;\n//                             newSurfPoint.Normalize();\n//                             newSurfPoint *= blSize;\n//                             newSurfPoint += surfPoint;\n//                             decltype(p) newP(newSurfPoint[0], newSurfPoint[1], newSurfPoint[2]);\n// \n//                             put(CGAL::vertex_point, mesh, vd, newP);\n//                         }\n// \n//                     writeVTP(pd.Get(), \"Skeleton directions\");\n//                 }\n\n                // Build the VTK data structure from CGAL\n                for (auto vi : mesh.vertices()) {\n                    Point p = mesh.point(vi);\n                    points->InsertNextPoint(p[0], p[1], p[2]);\n                }\n\n                for (auto fi : mesh.faces()) {\n                    vtkIdType ids[3];\n\n                    boost::copy(vertices_around_face(mesh.halfedge(fi), mesh), ids);\n\n                    remeshedPd->InsertNextCell(VTK_TRIANGLE, 3, ids);\n                    faceIdArray->InsertNextTuple1(fimap[fi]);\n                }\n            }\n\n            writeVTP(remeshedPd.GetPointer(), \"00 - remeshed\");\n\n            vtkSmartPointer<vtkUnstructuredGrid> finalResult;\n\n            if (params.meshSurfaceOnly) {\n                vtkNew<vtkvmtkPolyDataToUnstructuredGridFilter> surfaceToMesh;\n                surfaceToMesh->SetInputData(remeshedPd.GetPointer());\n                surfaceToMesh->Update();\n\n                finalResult = surfaceToMesh->GetOutput();\n            } else {\n                bool boundaryLayers = params.defaultLocalParameters.useBoundaryLayers;\n                stepsAddedSignal(boundaryLayers ? 100 : 25);\n\n                auto runTetGen = [&](vtkPolyData* input) {\n                    // *******\n                    MITK_INFO << \"Computing sizing function.\";\n                    vtkNew<vtkvmtkPolyDataSizingFunction> sizer;\n                    sizer->SetSizingFunctionArrayName(\"VolumeSizingFunction\");\n                    sizer->SetInputData(input);\n                    sizer->Update();\n\n                    vtkNew<vtkvmtkPolyDataToUnstructuredGridFilter> surf2Mesh;\n                    surf2Mesh->SetInputConnection(sizer->GetOutputPort());\n                    surf2Mesh->Update();\n\n                    MITK_INFO << \"Running 3D mesher.\";\n                    vtkNew<crimsonTetGenWrapper> mesher;\n                    mesher->SetInputConnection(surf2Mesh->GetOutputPort());\n                    mesher->SetCellEntityIdsArrayName(\"Face IDs\");\n                    mesher->SetSizingFunctionArrayName(\"VolumeSizingFunction\");\n                    mesher->SetUseSizingFunction(1);\n                    mesher->SetOrder(1);\n                    mesher->SetQuality(1);\n                    mesher->SetPLC(1);\n                    mesher->SetNoBoundarySplit(boundaryLayers ? 1 : 0);\n                    mesher->SetRemoveSliver(0);\n                    mesher->SetOutputSurfaceElements(boundaryLayers ? 0 : 1);\n                    mesher->SetOutputVolumeElements(1);\n                    mesher->SetVerbose(1);\n                    mesher->SetOptimizationLevel(params.volumeOptimizationLevel);\n                    mesher->SetMinDihedral(params.minDihedralAngle);\n                    mesher->SetMaxDihedral(params.maxDihedralAngle);\n                    mesher->SetMaxRatio(params.maxRadiusEdgeRatio);\n                    mesher->Update();\n\n                    writeVTU(mesher->GetOutput(), \"06 - mesh result\");\n\n                    return vtkSmartPointer<vtkUnstructuredGrid>(mesher->GetOutput());\n                };\n\n                ///////////////////\n                if (!boundaryLayers) {\n                    // Remove duplicate points produced when caps are removed\n                    vtkNew<vtkCleanPolyData> cleaner;\n                    cleaner->SetInputData(remeshedPd.GetPointer());\n                    cleaner->Update();\n\n                    finalResult = runTetGen(cleaner->GetOutput());\n                    if (finalResult->GetNumberOfCells() == 0) {\n                        return std::make_pair(State_Failed, std::string(\"TetGen failed, see log for details.\"));\n                    }\n                    vtkDataArray* faceIdArray = finalResult->GetCellData()->GetArray(\"Face IDs\");\n                    for (int faceId = 0; faceId < finalResult->GetNumberOfCells(); ++faceId) {\n                        vtkSmartPointer<vtkCell> cell = finalResult->GetCell(faceId);\n                        if (cell->GetCellDimension() == 3) {\n                            faceIdArray->SetTuple1(faceId, -1);\n                        }\n                    }\n                    progressMadeSignal(25);\n                } else {\n                    // We will remove caps to generate boundary layers. \n\n                    // Assign thickness before removing caps\n                    vtkNew<vtkDoubleArray> thicknessArray;\n                    thicknessArray->SetNumberOfTuples(remeshedPd->GetNumberOfPoints());\n                    thicknessArray->SetName(\"BL thickness\");\n                    remeshedPd->GetPointData()->AddArray(thicknessArray.Get());\n\n                    auto faceBLThickness = [&](int faceId) {\n                        const FaceIdentifier& identifier = brep->getFaceIdentifierMap().getFaceIdentifier(faceId);\n                        auto it = localParams.find(identifier);\n\n                        return (it == localParams.end() || !it->second.thickness\n                                ? *params.defaultLocalParameters.thickness\n                                : *it->second.thickness);\n                    };\n\n                    vtkNew<vtkIdList> ptIdList;\n                    ptIdList->SetNumberOfIds(1);\n                    vtkNew<vtkIdList> cellIdList;\n                    for (int i = 0; i < remeshedPd->GetNumberOfPoints(); ++i) {\n                        ptIdList->SetId(0, i);\n                        remeshedPd->GetCellNeighbors(-1, ptIdList.Get(), cellIdList.Get());\n\n                        double averageThickness = 0;\n                        for (int cellId = 0; cellId < cellIdList->GetNumberOfIds(); ++cellId) {\n                            averageThickness += faceBLThickness(remeshedPd->GetCellData()->GetArray(\"Face IDs\")->GetTuple1(cellIdList->GetId(cellId)));\n                        }\n\n                        thicknessArray->SetTuple1(i, averageThickness / cellIdList->GetNumberOfIds());\n                    }\n\n                    writeVTP(remeshedPd.Get(), \"bl thickness\");\n\n\n                    // Record the plane information for restoration of ids and normal constraints.\n                    struct PlaneInfo {\n                        Wm5::Plane3d plane;\n                        Wm5::Sphere3d sphere;\n\n                        bool inPlane(double* coords, double tol = 0.01) const {\n                            Wm5::Vector3d p(coords[0], coords[1], coords[2]);\n                            return plane.DistanceTo(p) < tol && (sphere.Center - p).Length() < sphere.Radius + tol;\n                        }\n\n                        Wm5::Vector3d project(double* vec) const {\n                            Wm5::Vector3d p(vec[0], vec[1], vec[2]);\n                            Wm5::Vector3d projected = p - p.Dot(plane.Normal) * plane.Normal;\n                            projected.Normalize();\n                            return projected;\n                        }\n                    };\n\n                    std::map<int, PlaneInfo> flowFacePlanes;\n\n                    auto removeCaps = [&](vtkPolyData* polyData) {\n                        polyData->BuildLinks();\n\n                        // Find all cap triangles\n                        std::unordered_set<int> capIds;\n                        const FaceIdentifierMap& faceIdMap = brep->getFaceIdentifierMap();\n                        for (int i = 0; i < faceIdMap.getNumberOfFaceIdentifiers(); ++i) {\n                            FaceIdentifier::FaceType faceType = faceIdMap.getFaceIdentifier(i).faceType;\n                            if (faceType == FaceIdentifier::ftCapInflow || faceType == FaceIdentifier::ftCapOutflow) {\n                                capIds.insert(i);\n                            }\n                        }\n\n                        // Remove the triangles while recording the points that belong to them\n                        std::map<int, std::set<int>> pointIds;\n                        vtkDataArray* faceIdArray = polyData->GetCellData()->GetArray(\"Face IDs\");\n                        for (int cellId = 0; cellId < polyData->GetNumberOfCells(); ++cellId) {\n                            if (polyData->GetCell(cellId)->GetCellType() != VTK_TRIANGLE) {\n                                polyData->DeleteCell(cellId);\n                                continue;\n                            }\n                            int faceId = static_cast<int>(faceIdArray->GetTuple1(cellId) + 0.5);\n                            if (capIds.count(faceId) != 0) {\n                                for (int i = 0; i < polyData->GetCell(cellId)->GetNumberOfPoints(); ++i) {\n                                    pointIds[faceId].insert(polyData->GetCell(cellId)->GetPointId(i));\n                                }\n\n                                polyData->DeleteCell(cellId);\n                            }\n                        }\n\n                        // Fit the planes to the points of caps\n                        for (const auto& faceIdToPointIds : pointIds) {\n                            std::vector<Wm5::Vector3d> points(faceIdToPointIds.second.size());\n                            boost::transform(faceIdToPointIds.second, points.begin(), [&](int ptId) { return coordsToVector(polyData->GetPoint(ptId)); });\n\n                            PlaneInfo planeInfo;\n                            planeInfo.plane = Wm5::OrthogonalPlaneFit3(points.size(), points.data());\n                            Wm5::MinSphere3d(points.size(), points.data(), planeInfo.sphere);\n\n                            flowFacePlanes[faceIdToPointIds.first] = planeInfo;\n                        }\n\n                        // Finally, remove the cells completely\n                        polyData->RemoveDeletedCells();\n                    };\n\n                    MITK_INFO << \"Removing caps before boundary layer creation\";\n\n                    removeCaps(remeshedPd.GetPointer());\n                    writeVTP(remeshedPd.GetPointer(), \"01 - noCaps\");\n\n\n                    progressMadeSignal(5);\n                    if (isCancelling()) {\n                        return std::make_tuple(State_Cancelled, std::string(\"Operation cancelled.\"));\n                    }\n                    MITK_INFO << \"Computing normals\";\n\n                    // Remove duplicate points produced when caps are removed\n                    vtkNew<vtkCleanPolyData> cleaner;\n                    cleaner->SetInputData(remeshedPd.GetPointer());\n                    cleaner->Update();\n\n                    // Recompute normals on the remeshed surface\n                    vtkNew<vtkPolyDataNormals> normals;\n                    normals->SetInputConnection(cleaner->GetOutputPort());\n                    normals->SetComputeCellNormals(0);\n                    normals->SetAutoOrientNormals(1);\n                    normals->SetFlipNormals(0);\n                    normals->SetConsistency(1);\n                    normals->SplittingOff();\n                    normals->Update();\n                    normals->GetOutput()->GetPointData()->GetNormals()->SetName(\"Normals\");\n\n                    // Ensure normals are in original planes for flow faces\n                    for (int ptId = 0; ptId < normals->GetOutput()->GetNumberOfPoints(); ++ptId) {\n                        double* coords = normals->GetOutput()->GetPoint(ptId);\n                        for (const auto& faceIdToPlaneInfo : flowFacePlanes) {\n                            if (faceIdToPlaneInfo.second.inPlane(coords)) {\n                                double* n = normals->GetOutput()->GetPointData()->GetNormals()->GetTuple3(ptId);\n                                Wm5::Vector3d projected = faceIdToPlaneInfo.second.project(n);\n                                normals->GetOutput()->GetPointData()->GetNormals()->SetTuple3(ptId, projected.X(), projected.Y(), projected.Z());\n                            }\n                        }\n                    }\n\n                    writeVTP(normals->GetOutput(), \"02 - normals\");\n\n                    progressMadeSignal(5);\n                    if (isCancelling()) {\n                        return std::make_tuple(State_Cancelled, std::string(\"Operation cancelled.\"));\n                    }\n                    MITK_INFO << \"Generating boundary layers\";\n\n                    vtkNew<vtkvmtkPolyDataToUnstructuredGridFilter> surfaceToMesh;\n                    surfaceToMesh->SetInputConnection(normals->GetOutputPort());\n                    surfaceToMesh->Update();\n\n                    const int InnerSurfId = surfaceToMesh->GetOutput()->GetCellData()->GetArray(\"Face IDs\")->GetRange()[1] + 10;\n                    const int SidewallId = InnerSurfId + 1;\n                    const int VolumeId = SidewallId + 1;\n\n                    vtkNew<vtkvmtkBoundaryLayerGenerator> boundaryLayer;\n                    boundaryLayer->SetInputData(surfaceToMesh->GetOutput());\n                    boundaryLayer->SetWarpVectorsArrayName(\"Normals\");\n                    boundaryLayer->SetCellEntityIdsArrayName(\"Face IDs\");\n                    boundaryLayer->NegateWarpVectorsOn();\n                    boundaryLayer->IncludeSurfaceCellsOff();\n                    boundaryLayer->IncludeSidewallCellsOn();\n                    boundaryLayer->SetInnerSurfaceCellEntityId(InnerSurfId);\n                    boundaryLayer->SetSidewallCellEntityId(SidewallId);\n                    boundaryLayer->SetVolumeCellEntityId(VolumeId);\n\n                    // Common boundary layer parameters\n                    boundaryLayer->SetNumberOfSubLayers(params.defaultLocalParameters.numSubLayers);\n                    boundaryLayer->SetSubLayerRatio(params.defaultLocalParameters.subLayerRatio);\n\n                    boundaryLayer->SetNumberOfSubsteps(2000);\n                    boundaryLayer->SetRelaxation(0.01);\n                    boundaryLayer->SetLocalCorrectionFactor(0.45);\n                    boundaryLayer->SetLayerThicknessArrayName(\"BL thickness\");\n                    boundaryLayer->SetConstantThickness(0);\n                    boundaryLayer->SetLayerThicknessRatio(1); // Just a multiplier\n\n                    boundaryLayer->Update();\n\n                    writeVTU(boundaryLayer->GetOutput(), \"03 - bl\");\n\n                    progressMadeSignal(25);\n                    if (isCancelling()) {\n                        return std::make_tuple(State_Cancelled, std::string(\"Operation cancelled.\"));\n                    }\n                    MITK_INFO << \"Capping the internal surface of boundary layer result\";\n\n                    // Extract volume cells\n                    vtkNew<vtkThreshold> blVolumeCells;\n                    blVolumeCells->SetInputData(boundaryLayer->GetOutput());\n                    blVolumeCells->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_CELLS, \"Face IDs\");\n                    blVolumeCells->ThresholdBetween(VolumeId, VolumeId);\n                    blVolumeCells->Update();\n\n                    // Extract sidewall cells\n                    vtkNew<vtkThreshold> blSidewallCells;\n                    blSidewallCells->SetInputData(boundaryLayer->GetOutput());\n                    blSidewallCells->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_CELLS, \"Face IDs\");\n                    blSidewallCells->ThresholdBetween(SidewallId, SidewallId);\n                    blSidewallCells->Update();\n\n                    // Cap the inner surface\n                    vtkNew<vtkGeometryFilter> meshToSurfaceInner;\n                    meshToSurfaceInner->SetInputData(boundaryLayer->GetInnerSurface());\n                    meshToSurfaceInner->Update();\n\n                    const int FirstCapId = VolumeId + 10;\n                    vtkNew<vtkvmtkSimpleCapPolyData> capper;\n                    capper->SetInputData(meshToSurfaceInner->GetOutput());\n                    capper->SetCellEntityIdsArrayName(\"Face IDs\");\n                    capper->SetCellEntityIdOffset(FirstCapId);\n                    capper->Update();\n\n                    vtkNew<vtkTriangleFilter> triangulator;\n                    triangulator->SetInputData(capper->GetOutput());\n                    triangulator->Update();\n\n                    writeVTP(triangulator->GetOutput(), \"04 - capped\");\n\n                    progressMadeSignal(5);\n                    if (isCancelling()) {\n                        return std::make_tuple(State_Cancelled, std::string(\"Operation cancelled.\"));\n                    }\n                    MITK_INFO << \"Remesing caps\";\n\n                    // Remesh caps\n                    // Assign mesh sizes for caps\n                    auto assignFlowFaceMeshSizes = [&](vtkPolyData* pd, const char* arrayName) {\n                        vtkNew<vtkDoubleArray> sizeArray;\n                        sizeArray->SetName(arrayName);\n                        sizeArray->SetNumberOfTuples(pd->GetNumberOfPoints());\n                        sizeArray->FillComponent(0, 0);\n                        pd->GetPointData()->AddArray(sizeArray.GetPointer());\n\n                        vtkDataArray* faceIdArray = pd->GetCellData()->GetArray(\"Face IDs\");\n                        for (int faceId = 0; faceId < pd->GetNumberOfCells(); ++faceId) {\n                            vtkSmartPointer<vtkCell> cell = pd->GetCell(faceId);\n                            double cellId = faceIdArray->GetTuple1(faceId);\n\n                            if (cellId >= FirstCapId) {\n                                for (const auto& faceIdToPlaneInfo : flowFacePlanes) {\n                                    if (faceIdToPlaneInfo.second.inPlane(cell->GetPoints()->GetPoint(0))) {\n                                        double edgeSize = faceEdgeSize(faceIdToPlaneInfo.first);\n                                        double targetArea = sqrt(3) / 4 * edgeSize * edgeSize;\n\n                                        for (int ptId = 0; ptId < cell->GetNumberOfPoints(); ++ptId) {\n                                            sizeArray->SetTuple1(cell->GetPointId(ptId), targetArea);\n                                        }\n                                    }\n                                }\n                            } \n                        }\n                    };\n\n                    assignFlowFaceMeshSizes(triangulator->GetOutput(), \"Cap edge size\");\n\n                    vtkNew<vtkvmtkPolyDataSurfaceRemeshing> remeshCaps;\n                    remeshCaps->SetInputData(triangulator->GetOutput());\n                    remeshCaps->SetCellEntityIdsArrayName(\"Face IDs\");\n                    remeshCaps->SetPreserveBoundaryEdges(1);\n                    remeshCaps->SetTargetAreaArrayName(\"Cap edge size\");\n                    remeshCaps->SetElementSizeModeToTargetAreaArray();\n                    vtkNew<vtkIdList> idList;\n                    idList->InsertNextId(InnerSurfId);\n                    remeshCaps->SetExcludedEntityIds(idList.GetPointer());\n                    remeshCaps->Update();\n\n                    writeVTP(remeshCaps->GetOutput(), \"05 - cap-remesh\");\n\n                    progressMadeSignal(25);\n                    if (isCancelling()) {\n                        return std::make_tuple(State_Cancelled, std::string(\"Operation cancelled.\"));\n                    }\n\n                    // Remove duplicated points after cap remeshing\n                    vtkNew<vtkCleanPolyData> cleaner2;\n                    cleaner2->SetInputData(remeshCaps->GetOutput());\n                    cleaner2->Update();\n\n                    // Extract remeshed caps\n                    vtkNew<vtkThreshold> remeshedCapCells;\n                    remeshedCapCells->SetInputData(cleaner2->GetOutput());\n                    remeshedCapCells->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_CELLS, \"Face IDs\");\n                    remeshedCapCells->ThresholdByUpper(FirstCapId);\n                    remeshedCapCells->Update();\n\n                    vtkNew<vtkGeometryFilter> meshToSurface;\n                    meshToSurface->SetInputData(cleaner2->GetOutput());\n                    meshToSurface->Update();\n\n                    vtkSmartPointer<vtkUnstructuredGrid> result = runTetGen(meshToSurface->GetOutput());\n                    if (result->GetNumberOfCells() == 0) {\n                        return std::make_pair(State_Failed, std::string(\"TetGen failed, see log for details.\"));\n                    }\n\n                    progressMadeSignal(25);\n                    if (isCancelling()) {\n                        return std::make_tuple(State_Cancelled, std::string(\"Operation cancelled.\"));\n                    }\n                    MITK_INFO << \"Assembling final result\";\n\n                    vtkNew<vtkAppendFilter> appender;\n                    appender->SetMergePoints(1);\n                    appender->AddInputData(result);\n                    appender->AddInputData(blVolumeCells->GetOutput());\n                    appender->AddInputData(blSidewallCells->GetOutput());\n                    appender->AddInputData(remeshedCapCells->GetOutput());\n                    appender->AddInputData(surfaceToMesh->GetOutput()); // For surface IDs\n                    appender->Update();\n\n                    if (!appender->GetOutput()->GetCellData()->GetArray(\"Face IDs\")) {\n                        return std::make_pair(State_Failed, std::string(\"Please reloft/reblend before meshing.\"));\n                    }\n\n                    auto restoreMoreFlowFaceIds = [&](vtkUnstructuredGrid* ug) {\n                        vtkDataArray* faceIdArray = ug->GetCellData()->GetArray(\"Face IDs\");\n                        for (int faceId = 0; faceId < ug->GetNumberOfCells(); ++faceId) {\n                            vtkSmartPointer<vtkCell> cell = ug->GetCell(faceId);\n                            double cellId = faceIdArray->GetTuple1(faceId);\n\n                            if (cell->GetCellDimension() == 3) {\n                                faceIdArray->SetTuple1(faceId, -1);\n                                continue;\n                            }\n\n                            if (cellId >= FirstCapId || cellId == SidewallId) {\n                                for (const auto& faceIdToPlaneInfo : flowFacePlanes) {\n                                    if (faceIdToPlaneInfo.second.inPlane(cell->GetPoints()->GetPoint(0))) {\n                                        faceIdArray->SetTuple1(faceId, faceIdToPlaneInfo.first);\n                                        break;\n                                    }\n                                }\n                            }\n                        }\n                    };\n                    restoreMoreFlowFaceIds(appender->GetOutput());\n\n                    writeVTU(appender->GetOutput(), \"07 - full mesh\");\n\n                    vtkNew<vtkvmtkUnstructuredGridTetraFilter> tetrahedralizer;\n                    tetrahedralizer->SetInputData(appender->GetOutput());\n                    tetrahedralizer->Update();\n\n                    writeVTU(tetrahedralizer->GetOutput(), \"08 - tetrahedralized\");\n                    finalResult = tetrahedralizer->GetOutput();\n\n                    progressMadeSignal(10);\n                }\n            }\n\n            auto ug = mitk::UnstructuredGrid::New();\n            ug->SetVtkUnstructuredGrid(finalResult);\n            auto result = MeshData::New();\n            result->setFaceIdentifierMap(brep->getFaceIdentifierMap());\n            result->setUnstructuredGrid(ug, true);\n            this->setResult(result.GetPointer());\n\n            progressMadeSignal(1);\n\n            return std::make_tuple(State_Finished, std::string());\n\t\t}\n\n\t};\n\n\tclass DiscreteMeshingTask : public crimson::MeshingTask\n\t{\n\tpublic:\n\t\tDiscreteMeshingTask(const mitk::BaseData::Pointer& solid, const IMeshingKernel::GlobalMeshingParameters& params,\n\t\t\tconst std::map<FaceIdentifier, IMeshingKernel::LocalMeshingParameters>& localParams,\n\t\t\tconst std::map<VesselPathAbstractData::VesselPathUIDType, std::string>& vesselUIDtoNameMap)\n\t\t\t:MeshingTask(solid, params, localParams, vesselUIDtoNameMap) {}\n\n\t\t~DiscreteMeshingTask(){}\n\n\t\tstd::tuple<State, std::string> runTask() override\n\t\t{\n\t\t\tstepsAddedSignal(1);\n        }\n\t};\n\n\n    std::shared_ptr<async::TaskWithResult<mitk::BaseData::Pointer>>\n\t\tIMeshingKernel::createMeshSolidTask(const mitk::BaseData::Pointer& solid, const GlobalMeshingParameters& params,\n\t\tconst std::map<FaceIdentifier, LocalMeshingParameters>& localParams,\n\t\tconst std::map<VesselPathAbstractData::VesselPathUIDType, std::string>& vesselUIDtoNameMap)\n\t{\n\t\treturn std::static_pointer_cast<crimson::async::TaskWithResult<mitk::BaseData::Pointer>>(\n\t\t\tstd::make_shared<OCCMeshingTask>(solid, params, localParams, vesselUIDtoNameMap));\n\t}\n\n\n    class AdaptMeshTask : public crimson::async::TaskWithResult<mitk::BaseData::Pointer>\n\t{\n\t\tusing GradientType = Eigen::Vector3d;\n\t\tusing HessianType = Eigen::Matrix<double, 6, 1>;\n\n\tpublic:\n\t\tAdaptMeshTask(const mitk::BaseData::Pointer& originalMesh, double factor, double hmin, double hmax,\n\t\t\tconst std::string& errorIndicatorArrayName)\n\t\t\t: originalMesh(dynamic_cast<MeshData*>(originalMesh.GetPointer()))\n\t\t\t, factor(factor)\n\t\t\t, hmax(hmax)\n\t\t\t, hmin(hmin)\n\t\t\t, errorIndicatorArrayName(errorIndicatorArrayName)\n\t\t{\n\t\t}\n\t\t~AdaptMeshTask() { }\n\n\t\tvoid cancel() override\n\t\t{\n\t\t\tcrimson::async::TaskWithResult<mitk::BaseData::Pointer>::cancel();\n\t\t}\n\n\t\tstd::tuple<State, std::string> runTask() override\n\t\t{\n            stepsAddedSignal(6);\n\n\t\t\tif (originalMesh.IsNull()) {\n\t\t\t\treturn std::make_tuple(State_Failed,\n\t\t\t\t\tstd::string(\"Original mesh was not created with the meshing kernel other than .\"));\n\t\t\t}\n\n\t\t\ttry {\n                MITK_INFO << \"Computing size field\";\n                setSizeFieldUsingHessians();\n\n                progressMadeSignal(1);\n                if (isCancelling()) {\n                    return std::make_tuple(State_Cancelled, std::string(\"Operation cancelled.\"));\n                }\n\n                auto runTetGen = [&](vtkUnstructuredGridBase* input) {\n                    // *******\n                    vtkNew<crimsonTetGenWrapper> mesher;\n                    mesher->SetInputData(input);\n                    mesher->SetCellEntityIdsArrayName(\"Face IDs\");\n                    mesher->SetSizingFunctionArrayName(\"Target size\");\n                    mesher->SetUseSizingFunction(1);\n                    mesher->SetOrder(1);\n                    mesher->SetQuality(1);\n                    mesher->SetRefine(1);\n                    mesher->SetCoarsen(0); // TetGen sometimes crashes when coarsening the outer surface.\n                    mesher->SetNoBoundarySplit(0); \n                    mesher->SetRemoveSliver(0);\n                    mesher->SetOutputSurfaceElements(1);\n                    mesher->SetOutputVolumeElements(1);\n                    mesher->SetVerbose(1);\n                    mesher->Update();\n\n                    return vtkSmartPointer<vtkUnstructuredGrid>(mesher->GetOutput());\n                };\n\n                progressMadeSignal(1);\n                if (isCancelling()) {\n                    return std::make_tuple(State_Cancelled, std::string(\"Operation cancelled.\"));\n                }\n                MITK_INFO << \"Adapting mesh\";\n\n                auto newUnstructuredGrid = runTetGen(originalMesh->getUnstructuredGridRepresentation()->GetVtkUnstructuredGrid());\n                originalMesh->getUnstructuredGridRepresentation()->GetVtkUnstructuredGrid()->GetPointData()->RemoveArray(\"Target size\");\n\n\n                if (newUnstructuredGrid->GetNumberOfCells() == 0) {\n                    return std::make_pair(State_Failed, std::string(\"TetGen failed, see log for details.\"));\n                }\n\n\t\t\t\tint timeStep = 0;\n\t\t\t\toriginalMesh->GetPropertyList()->GetIntProperty(\"timeStep\", timeStep);\n\n                progressMadeSignal(1);\n                if (isCancelling()) {\n                    return std::make_tuple(State_Cancelled, std::string(\"Operation cancelled.\"));\n                }\n                MITK_INFO << \"Transferring the solution\";\n\n\t\t\t\t// Transfer solution\n\t\t\t\tvtkUnstructuredGridBase* originalUnstructuredGrid =\n\t\t\t\t\toriginalMesh->getUnstructuredGridRepresentation()->GetVtkUnstructuredGrid();\n\n\t\t\t\tvtkNew<vtkProbeFilter> solutionTransferFilter;\n\t\t\t\tsolutionTransferFilter->SetSourceData(originalUnstructuredGrid);\n\t\t\t\tsolutionTransferFilter->SetInputData(newUnstructuredGrid);\n\t\t\t\tsolutionTransferFilter->Update();\n\n                progressMadeSignal(1);\n                if (isCancelling()) {\n                    return std::make_tuple(State_Cancelled, std::string(\"Operation cancelled.\"));\n                }\n                MITK_INFO << \"Transferring the solution for nodes outside original mesh domain\";\n\n\t\t\t\t// For nodes that were snapped to the model surface that are outside of original mesh - just find closest points\n\t\t\t\tvtkPointData* transferredPointData = solutionTransferFilter->GetOutput()->GetPointData();\n\t\t\t\tvtkDataArray* validPointMaskArray =\n\t\t\t\t\ttransferredPointData->GetArray(solutionTransferFilter->GetValidPointMaskArrayName());\n\t\t\t\tfor (int i = 0; i < newUnstructuredGrid->GetNumberOfPoints(); ++i) {\n\t\t\t\t\tif (validPointMaskArray->GetComponent(i, 0) != 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t// Failed the solution transfer - find the closest point\n\t\t\t\t\tint closestPointId = originalUnstructuredGrid->FindPoint(newUnstructuredGrid->GetPoint(i));\n\n\t\t\t\t\tfor (int arrayIndex = 0; arrayIndex < originalUnstructuredGrid->GetPointData()->GetNumberOfArrays();\n\t\t\t\t\t\t++arrayIndex) {\n\t\t\t\t\t\ttransferredPointData->GetArray(arrayIndex)\n\t\t\t\t\t\t\t->SetTuple(i, originalUnstructuredGrid->GetPointData()->GetArray(arrayIndex)->GetTuple(closestPointId));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ttransferredPointData->RemoveArray(solutionTransferFilter->GetValidPointMaskArrayName());\n\n                for (int i = 0; i < originalUnstructuredGrid->GetCellData()->GetNumberOfArrays(); ++i) {\n                    transferredPointData->RemoveArray(originalUnstructuredGrid->GetCellData()->GetArrayName(i));\n                }\n\n                newUnstructuredGrid->GetPointData()->ShallowCopy(transferredPointData);\n\n                progressMadeSignal(1);\n                if (isCancelling()) {\n                    return std::make_tuple(State_Cancelled, std::string(\"Operation cancelled.\"));\n                }\n                MITK_INFO << \"Transferring original face identifiers\";\n\n                vtkSmartPointer<vtkPolyData> pd = originalMesh->getSurfaceRepresentation()->GetVtkPolyData();\n\n                vtkDataArray* outArray = newUnstructuredGrid->GetCellData()->GetArray(\"Face IDs\");\n\n                for (int i = 0; i < newUnstructuredGrid->GetNumberOfCells(); ++i) {\n                    if (newUnstructuredGrid->GetCellType(i) == VTK_TETRA) {\n                        outArray->SetComponent(i, 0, -1);\n                    } else if (outArray->GetComponent(i, 0) == -1) {\n                        outArray->SetComponent(i, 0, 0);\n                    }\n                }\n\n                // Finally, create the output MITK object\n                auto ug = mitk::UnstructuredGrid::New();\n                ug->SetVtkUnstructuredGrid(newUnstructuredGrid);\n                auto result = MeshData::New();\n                result->setFaceIdentifierMap(originalMesh->getFaceIdentifierMap());\n                result->setUnstructuredGrid(ug, true);\n                this->setResult(result.GetPointer());\n\n                progressMadeSignal(1);\n\n\t\t\t\tMITK_INFO << \"Adaptation complete\";\n\n\t\t\t\tsetResult(result.GetPointer());\n\t\t\t\treturn std::make_tuple(State_Finished, std::string(\"Adaptation complete.\"));\n\t\t\t}\n\t\t\tcatch (...) {\n\t\t\t\treturn std::make_tuple(State_Failed, std::string(\"Unhandled exception caught\"));\n\t\t\t}\n\t\t}\n\n\t\t// Build a linear system using the coordinates of the nodes\n\t\tEigen::Matrix4d buildSystem(vtkCell* cell)\n\t\t{\n            auto ug = originalMesh->getUnstructuredGridRepresentation()->GetVtkUnstructuredGrid();\n            Eigen::Matrix4d m;\n\n\t\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\t\tdouble X[3];\n                ug->GetPoint(cell->GetPointId(i), X);\n\n\t\t\t\tm(i, 0) = 1;\n\t\t\t\tfor (int j = 0; j < 3; ++j) {\n\t\t\t\t\tm(i, j + 1) = X[j];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn m;\n\t\t}\n\n\t\t// reconstruct the element gradient\n\t\tGradientType elementGradient(vtkCell* tet)\n\t\t{\n\t\t\t// build the linear system\n\t\t\tEigen::Matrix4d matrix = buildSystem(tet);\n\n\t\t\t// get the field vals\n\t\t\tEigen::Vector4d rhs;\n\t\t\tauto errorIndicatorData =\n\t\t\t\tstatic_cast<vtkDoubleArray*>(originalMesh->getPointData()->GetArray(errorIndicatorArrayName.c_str()));\n\t\t\tfor (int i = 0; i < 4; i++) {\n\t\t\t\trhs(i) = errorIndicatorData->GetComponent(tet->GetPointId(i), 0);\n\t\t\t}\n\n\t\t\treturn matrix.colPivHouseholderQr()\n\t\t\t\t.solve(rhs)\n\t\t\t\t.tail<3>(); // Solve the system and take the solution from the last 3 elements\n\t\t}\n\n\t\t// compute the element gradient\n\t\tHessianType elementHessian(vtkCell* tet)\n\t\t{\n\t\t\t// build the linear system\n\t\t\tEigen::Matrix4d matrix = buildSystem(tet);\n\n\t\t\tauto solverMethod = matrix.colPivHouseholderQr();\n\n\t\t\t// get the field vals\n\t\t\tEigen::Vector4d hessianComponents[3];\n            for (int gradientCoord = 0; gradientCoord < 3; ++gradientCoord) {\n\t\t\t\tEigen::Vector4d rhs;\n\t\t\t\tfor (int i = 0; i < 4; i++) {\n\t\t\t\t\trhs(i) = nodalGradients[tet->GetPointId(i)](gradientCoord); // speed component\n\t\t\t\t}\n\t\t\t\thessianComponents[gradientCoord] = solverMethod.solve(rhs);\n\t\t\t}\n\n\t\t\tHessianType hessian;\n\t\t\thessian(0) = hessianComponents[0](1); // xx\n\t\t\thessian(1) = hessianComponents[0](2); // xy\n\t\t\thessian(2) = hessianComponents[0](3); // xz\n\t\t\thessian(3) = hessianComponents[1](2); // yy\n\t\t\thessian(4) = hessianComponents[1](3); // yz\n\t\t\thessian(5) = hessianComponents[2](3); // zz\n\n\t\t\treturn hessian;\n\t\t}\n\n\t\t// Compute values for all elements in the mesh\n\t\ttemplate <typename DataType, typename Functor>\n\t\tvoid computeElementValues(std::vector<DataType>& outputElementValues, Functor&& computeFunction)\n\t\t{\n\t\t\toutputElementValues.resize(originalMesh->getNElements());\n            auto ug = originalMesh->getUnstructuredGridRepresentation()->GetVtkUnstructuredGrid();\n            for (int i = 0; i < originalMesh->getNElements(); ++i) {\n                vtkSmartPointer<vtkCell> tet = ug->GetCell(i);\n                Expects(tet->GetCellType() == VTK_TETRA);\n\n                outputElementValues[i] = computeFunction(tet.GetPointer());\n            }\n\t\t}\n\n\t\t// Compute values at nodes using element values using volume-wieghted averaging\n\t\ttemplate <typename DataType>\n\t\tvoid computeNodalValuesFromElementValues(std::vector<DataType>& outputNodalValues,\n\t\t\tconst std::vector<DataType>& elementValues)\n\t\t{\n\t\t\toutputNodalValues.resize(originalMesh->getNNodes());\n            auto ug = originalMesh->getUnstructuredGridRepresentation()->GetVtkUnstructuredGrid();\n            Expects(ug->GetNumberOfPoints() == originalMesh->getNNodes());\n\n\t\t\t// loop over vertices and get patch of elements\n            vtkNew<vtkIdList> pointIdList;\n            pointIdList->SetNumberOfIds(1);\n\n            vtkNew<vtkIdList> neighborCells;\n            for (int vertexId = 0; vertexId < ug->GetNumberOfPoints(); ++vertexId) {\n                pointIdList->SetId(0, vertexId);\n                ug->GetCellNeighbors(-1, pointIdList.Get(), neighborCells.Get());\n\n                double patchVolume = 0;\n\n                DataType patchValue;\n                patchValue.fill(0);\n\n                // loop over elements and recover gradient at vertex\n                for (int cellId = 0; cellId < neighborCells->GetNumberOfIds(); cellId++) {\n                    vtkSmartPointer<vtkCell> cell = ug->GetCell(neighborCells->GetId(cellId));\n                    if (cell->GetCellType() != VTK_TETRA) {\n                        continue;\n                    }\n\n                    double tetVolume = vtkMeshQuality::TetVolume(cell);\n                    patchVolume += tetVolume;\n\n                    // get element gradient or hessian for each element in the patch at vertex\n                    patchValue += elementValues[neighborCells->GetId(cellId)] * tetVolume;\n                }\n\n                // attach the recovered gradient to the vertex\n                outputNodalValues[vertexId] = patchValue / patchVolume;\n            }\n\t\t}\n\n\t\t// simple average over a patch surrounding the vertex\n\t\tvoid smoothHessians()\n\t\t{\n\t\t\tstd::vector<HessianType> smoothedHessians(nodalHessians.size());\n\n\t\t\t// keep the vals in memory before finally setting them\n            auto ug = originalMesh->getUnstructuredGridRepresentation()->GetVtkUnstructuredGrid();\n\n            // loop over vertices and get patch of elements\n            vtkNew<vtkIdList> pointIdList;\n            pointIdList->SetNumberOfIds(1);\n\n            vtkNew<vtkIdList> neighborCells;\n            for (int vertexId = 0; vertexId < ug->GetNumberOfPoints(); ++vertexId) {\n                pointIdList->SetId(0, vertexId);\n                ug->GetCellNeighbors(-1, pointIdList.Get(), neighborCells.Get());\n\n                std::unordered_set<vtkIdType> allIds;\n                std::unordered_set<vtkIdType> surfaceIds;\n\n                allIds.insert(vertexId);\n                for (int cellId = 0; cellId < neighborCells->GetNumberOfIds(); cellId++) {\n                    vtkSmartPointer<vtkCell> cell = ug->GetCell(neighborCells->GetId(cellId));\n                    for (int neighVertexId = 0; neighVertexId < cell->GetNumberOfPoints(); ++neighVertexId) {\n                        (cell->GetCellType() == VTK_TETRA ? allIds : surfaceIds).insert(cell->GetPointId(neighVertexId));\n                    }\n                }\n\n                for (vtkIdType id : surfaceIds) {\n                    allIds.erase(id);\n                }\n\n                if (allIds.empty()) {\n// \t\t\t\t\tMITK_WARN << \"\\nerror in SmoothHessians: there is a boundary vertex whose\\n\"\n// \t\t\t\t\t\t<< \"neighbors are exclusively classified on model faces/edges/vertices\\n\"\n// \t\t\t\t\t\t<< \"and NOT in the interior.\\n\";\n\t\t\t\t\tsmoothedHessians[vertexId] = nodalHessians[vertexId];\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n                HessianType averageHessian;\n                averageHessian.fill(0);\n\n                for (vtkIdType id : allIds) {\n                    averageHessian += nodalHessians[id];\n                }\n\n                smoothedHessians[vertexId] = averageHessian / allIds.size();\n\t\t\t}\n\n\t\t\tnodalHessians = smoothedHessians;\n\t\t}\n\n\t\t// relative interpolation error along an edge\n\t\tdouble E_error(vtkIdType v1, vtkIdType v2, const Eigen::Matrix3d& H)\n\t\t{\n\t\t\tEigen::Vector3d vertexCoords[2];\n\n            auto ug = originalMesh->getUnstructuredGridRepresentation()->GetVtkUnstructuredGrid();\n\n            ug->GetPoint(v1, &vertexCoords[0](0));\n            ug->GetPoint(v2, &vertexCoords[1](0));\n\n\t\t\tEigen::Vector3d edgeVector = vertexCoords[1] - vertexCoords[0];\n\n\t\t\tdouble localError = 0;\n\t\t\tfor (int i = 0; i < 3; i++) {\n\t\t\t\tfor (int j = 0; j < 3; j++) {\n\t\t\t\t\tlocalError += H(i, j) * edgeVector(i) * edgeVector(j);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn abs(localError);\n\t\t}\n\n\t\t// max relative interpolation error at a vertex\n\t\tdouble maxLocalError(vtkIdType vertexId, const Eigen::Matrix3d& H)\n\t\t{\n\t\t\tdouble maxLocE = 0;\n\n            auto ug = originalMesh->getUnstructuredGridRepresentation()->GetVtkUnstructuredGrid();\n\n            vtkNew<vtkIdList> pointIdList;\n            pointIdList->SetNumberOfIds(1);\n\n            vtkNew<vtkIdList> neighborCells;\n\n            pointIdList->SetId(0, vertexId);\n            ug->GetCellNeighbors(-1, pointIdList.Get(), neighborCells.Get());\n\n            std::unordered_set<vtkIdType> allIds;\n            for (int cellId = 0; cellId < neighborCells->GetNumberOfIds(); cellId++) {\n                vtkSmartPointer<vtkCell> cell = ug->GetCell(neighborCells->GetId(cellId));\n                for (int otherVertexId = 0; otherVertexId < cell->GetNumberOfPoints(); ++otherVertexId) {\n                    allIds.insert(cell->GetPointId(otherVertexId));\n                }\n            }\n            allIds.erase(vertexId);\n\n\t\t\tfor (vtkIdType otherId : allIds) {\n\t\t\t\tmaxLocE = std::max(maxLocE, E_error(vertexId, otherId, H));\n\t\t\t}\n\n\t\t\treturn maxLocE;\n\t\t}\n\n\t\tvoid setSizeFieldUsingHessians()\n\t\t{\n\t\t\tMITK_INFO << \"Computing per-element Hessians\";\n\t\t\tcomputeHessians();\n\n\t\t\tdouble tol = 1.e-12;\n\t\t\tdouble totalError = 0;                                     // total error for all vertices\n\t\t\tdouble localErrorMax = 0.;                                 // max local error\n\t\t\tdouble localErrorMin = std::numeric_limits<double>::max(); // min local error\n\n\t\t\tint hminCount = 0;\n\t\t\tint hmaxCount = 0;\n\t\t\tint bothHminHmaxCount = 0;\n\t\t\tint bdryNumNodes = 0;\n\n\t\t\tstd::vector<std::tuple<Eigen::Vector3d, Eigen::Matrix3d>> eigenValuesVectors(nodalHessians.size());\n\n            auto ug = originalMesh->getUnstructuredGridRepresentation()->GetVtkUnstructuredGrid();\n\n            vtkNew<vtkDoubleArray> arr;\n            arr->SetNumberOfTuples(ug->GetNumberOfPoints());\n            arr->SetName(\"Target size\");\n\n            for (int vertexIndex = 0; vertexIndex < ug->GetNumberOfPoints(); ++vertexIndex) {\n                // Hessian in the symmetric matrix form\n                Eigen::Matrix3d hessian;\n\n                hessian(0, 0) = nodalHessians[vertexIndex](0);\n                hessian(0, 1) = hessian(1, 0) = nodalHessians[vertexIndex](1);\n                hessian(0, 2) = hessian(2, 0) = nodalHessians[vertexIndex](2);\n                hessian(1, 1) = nodalHessians[vertexIndex](3);\n                hessian(1, 2) = hessian(2, 1) = nodalHessians[vertexIndex](4);\n                hessian(2, 2) = nodalHessians[vertexIndex](5);\n\n                // compute eigen values and eigen vectors\n                Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigensolver(hessian);\n\n                if (eigensolver.info() != Eigen::Success) {\n                    MITK_WARN << \"Failed to find eigenvectors for the hessian for node \" << vertexIndex;\n                    continue;\n                }\n\n                auto eigenValuesAbsolute = eigensolver.eigenvalues().cwiseAbs();\n\n                if (eigenValuesAbsolute.maxCoeff() < tol) {\n                    eigenValuesVectors[vertexIndex] = std::make_tuple(eigenValuesAbsolute, Eigen::Matrix3d::Zero());\n\n                    MITK_WARN << \"Zero maximum eigenvalue for node \" << vertexIndex;\n                    continue;\n                }\n\n                eigenValuesVectors[vertexIndex] = std::make_tuple(eigenValuesAbsolute, eigensolver.eigenvectors());\n\n                // estimate relative interpolation error\n                // needed for scaling metric field (mesh size field)\n                // to get an idea refer Appendix A in Li's thesis\n                double localError = maxLocalError(vertexIndex, hessian);\n                totalError += localError;\n                localErrorMax = std::max(localErrorMax, localError);\n                localErrorMin = std::min(localErrorMin, localError);\n            }\n\n            originalMesh->getPointData()->AddArray(arr.GetPointer());\n\n\t\t\tdouble averageError = totalError / originalMesh->getNNodes();\n\t\t\tMITK_INFO << \"Info on relative interpolation error: \";\n\t\t\tMITK_INFO << \"   total: \" << totalError;\n\t\t\tMITK_INFO << \"   mean:  \" << averageError;\n\t\t\tMITK_INFO << \"   max local: \" << localErrorMax;\n\t\t\tMITK_INFO << \"   min local: \" << localErrorMin;\n\n\t\t\tdouble targetLocalError = averageError * factor;\n\n\t\t\tMITK_INFO << \" towards uniform local error distribution of \" << targetLocalError;\n\t\t\tMITK_INFO << \"   with max edge length=\" << hmax << \" min edge length=\" << hmin;\n\n            for (int vertexIndex = 0; vertexIndex < ug->GetNumberOfPoints(); ++vertexIndex) {\n\t\t\t\tdouble tol2 = 0.01 * hmax;\n\t\t\t\tdouble tol3 = 0.01 * hmin;\n\n\t\t\t\tEigen::Vector3d eigenValues;\n\t\t\t\tEigen::Matrix3d eigenVectors;\n\t\t\t\tstd::tie(eigenValues, eigenVectors) = eigenValuesVectors[vertexIndex];\n\n\t\t\t\tdouble directionalSize[3];\n\n\t\t\t\tfor (int j = 0; j < 3; j++) {\n\t\t\t\t\tif (eigenValues(j) < tol)\n\t\t\t\t\t\tdirectionalSize[j] = hmax;\n\t\t\t\t\telse {\n\t\t\t\t\t\tdirectionalSize[j] = std::max(hmin, std::min(hmax, sqrt(targetLocalError / eigenValues(j))));\n\t\t\t\t\t}\n\t\t\t\t}\n\n                arr->SetTuple1(vertexIndex, *std::min_element(directionalSize, directionalSize + 3));\n\n\t\t\t\tbool foundHmin = false;\n\t\t\t\tbool foundHmax = false;\n\t\t\t\tfor (int j = 0; j < 3; j++) {\n\t\t\t\t\tif (abs(directionalSize[j] - hmax) <= tol2) {\n\t\t\t\t\t\tfoundHmax = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (abs(directionalSize[j] - hmin) <= tol3) {\n\t\t\t\t\t\tfoundHmin = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (foundHmin) {\n\t\t\t\t\thminCount++;\n\t\t\t\t}\n\t\t\t\tif (foundHmax) {\n\t\t\t\t\thmaxCount++;\n\t\t\t\t}\n\t\t\t\tif (foundHmin && foundHmax) {\n\t\t\t\t\tbothHminHmaxCount++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tMITK_INFO << \"Nodes with hmin into effect : \" << hminCount << endl;\n\t\t\tMITK_INFO << \"Nodes with hmax into effect : \" << hmaxCount << endl;\n\t\t\tMITK_INFO << \"Nodes with both hmin/hmax into effect : \" << bothHminHmaxCount << endl;\n\t\t\tMITK_INFO << \"(No nodes are ignored in boundary layer for CGALVMTK mesher)\" << endl << endl;\n\n\t\t\tnodalHessians.clear();\n\t\t}\n\n\t\tvoid computeHessians()\n\t\t{\n\t\t\tstd::vector<GradientType> elementGradients;\n\t\t\tcomputeElementValues<GradientType>(elementGradients, [this](vtkCell* r) { return elementGradient(r); });\n\t\t\tcomputeNodalValuesFromElementValues(nodalGradients, elementGradients);\n\t\t\telementGradients.clear(); // Element gradients are no longer needed\n\n            // vtkNew<vtkDoubleArray> arr;\n            // arr->SetNumberOfComponents(3);\n            // arr->SetNumberOfTuples(nodalGradients.size());\n            // arr->SetName(\"grad\");\n            // \n            // for (int i = 0; i < nodalGradients.size(); ++i) {\n            //     for (int j = 0; j < 3; ++j) {\n            //         arr->SetComponent(i, j, nodalGradients[i](j));\n            //     }\n            // }\n            // originalMesh->getPointData()->AddArray(arr.GetPointer());\n\n\t\t\tstd::vector<HessianType> elementHessians;\n\t\t\tcomputeElementValues<HessianType>(elementHessians, [this](vtkCell* r) { return elementHessian(r); });\n\t\t\tcomputeNodalValuesFromElementValues(nodalHessians, elementHessians);\n\t\t\telementHessians.clear(); // Element hessians are no longer needed\n\t\t\tnodalGradients.clear();  // Nodal gradients are no longer needed\n\n\t\t\tsmoothHessians();\n\n\t\t\t// Now the nodal hessians are ready to use in the adaptation procedure\n\t\t}\n\tprivate:\n\t\tMeshData::Pointer originalMesh;\n\n\t\tdouble factor;\n\t\tdouble hmax;\n\t\tdouble hmin;\n\t\tstd::string errorIndicatorArrayName;\n\n\t\tstd::vector<GradientType> nodalGradients;\n\t\tstd::vector<HessianType> nodalHessians;\n\t};\n\n    std::shared_ptr<async::TaskWithResult<mitk::BaseData::Pointer>>\n\t\tIMeshingKernel::createAdaptMeshTask(const mitk::BaseData::Pointer& originalMesh, double factor, double hmin, double hmax,\n\t\tconst std::string& errorIndicatorArrayName)\n\t{\n    \treturn std::static_pointer_cast<crimson::async::TaskWithResult<mitk::BaseData::Pointer>>(\n\t\t    std::make_shared<AdaptMeshTask>(originalMesh, factor, hmin, hmax, errorIndicatorArrayName));\n\t}\n\n} // namespace crimson\n", "meta": {"hexsha": "60ac62a245524eeaaa5d5537d894f37832c89c75", "size": 63425, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/CGALVMTKMeshingKernel/ExtensionPoint/IMeshingKernel.cpp", "max_stars_repo_name": "carthurs/CRIMSONGUI", "max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-09-17T18:55:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T02:52:38.000Z", "max_issues_repo_path": "Modules/CGALVMTKMeshingKernel/ExtensionPoint/IMeshingKernel.cpp", "max_issues_repo_name": "carthurs/CRIMSONGUI", "max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/CGALVMTKMeshingKernel/ExtensionPoint/IMeshingKernel.cpp", "max_forks_repo_name": "carthurs/CRIMSONGUI", "max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z", "avg_line_length": 43.3823529412, "max_line_length": 188, "alphanum_fraction": 0.5624753646, "num_tokens": 14284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.3665897363221598, "lm_q1q2_score": 0.2563394938380348}}
{"text": "/*\n   For more information, please see: http://software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2020 Scientific Computing and Imaging Institute,\n   University of Utah.\n\n   Permission is hereby granted, free of charge, to any person obtaining a\n   copy of this software and associated documentation files (the \"Software\"),\n   to deal in the Software without restriction, including without limitation\n   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n   and/or sell copies of the Software, and to permit persons to whom the\n   Software is furnished to do so, subject to the following conditions:\n\n   The above copyright notice and this permission notice shall be included\n   in all copies or substantial portions of the Software.\n\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n   DEALINGS IN THE SOFTWARE.\n*/\n\n\n#include <Core/Algorithms/Legacy/FiniteElements/BuildMatrix/BuildFEMatrix.h>\n\n#include <Core/Datatypes/DenseMatrix.h>\n#include <Core/Datatypes/SparseRowMatrix.h>\n\n#include <Core/Thread/Barrier.h>\n#include <Core/Thread/Parallel.h>\n\n#include <Core/Datatypes/Legacy/Field/Mesh.h>\n#include <Core/Datatypes/Legacy/Field/VMesh.h>\n#include <Core/Datatypes/Legacy/Field/Field.h>\n#include <Core/Datatypes/Legacy/Field/VField.h>\n#include <Core/GeometryPrimitives/Tensor.h>\n#include <Core/Algorithms/Base/AlgorithmPreconditions.h>\n#include <Core/Algorithms/Base/AlgorithmVariableNames.h>\n#include <Core/Logging/Log.h>\n\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <boost/shared_array.hpp>\n\nusing namespace SCIRun;\nusing namespace SCIRun::Core::Geometry;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Thread;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core::Algorithms::FiniteElements;\nusing namespace SCIRun::Core::Logging;\n\nnamespace SCIRun {\n\tnamespace Core {\n\t\tnamespace Algorithms {\n\t\t\tnamespace FiniteElements {\n\n        template <typename T>\n        using matrix_type = Datatypes::SparseRowMatrixGeneric<T>;\n        template <typename T>\n        using matrix_pointer_type = SharedPointer<matrix_type<T>>;\n\ntemplate <typename T>\nclass BuildFEMatrixAlgoImpl\n{\npublic:\n  explicit BuildFEMatrixAlgoImpl(const AlgorithmBase* algo) : algo_(algo) {}\n  bool run(FieldHandle input, Datatypes::DenseMatrixHandle ctable, matrix_pointer_type<T>& output) const;\nprivate:\n  const AlgorithmBase* algo_;\n  mutable int generation_ = 0;\n  mutable std::vector<std::vector<T>> basis_values_;\n  mutable matrix_pointer_type<T> basis_fematrix_;\n};\n\n// Helper class\ntemplate <typename T>\nclass FEMBuilder\n{\npublic:\n  explicit FEMBuilder(const AlgorithmBase* algo) :\n    algo_(algo), numprocessors_(Parallel::NumCores()),\n    barrier_(\"FEMBuilder Barrier\", numprocessors_),\n    mesh_(nullptr), field_(nullptr),\n    domain_dimension(0), local_dimension_nodes(0),\n    local_dimension_add_nodes(0),\n    local_dimension_derivatives(0),\n    local_dimension(0),\n    global_dimension_nodes(0),\n    global_dimension_add_nodes(0),\n    global_dimension_derivatives(0),\n    global_dimension(0)\n  {\n  }\n\n  bool build_matrix(FieldHandle input,\n                    DenseMatrixHandle ctable,\n                    matrix_pointer_type<T>& output);\n\nprivate:\n  const AlgorithmBase* algo_;\n  int numprocessors_;\n  Barrier barrier_;\n\n  VMesh* mesh_;\n  VField *field_;\n\n  matrix_pointer_type<T> fematrix_;\n\n  std::vector<bool> success_;\n\n  boost::shared_array<index_type> rows_;\n  boost::shared_array<index_type> allcols_;\n  std::vector<index_type> colidx_;\n\n  index_type domain_dimension;\n\n  index_type local_dimension_nodes;\n  index_type local_dimension_add_nodes;\n  index_type local_dimension_derivatives;\n  index_type local_dimension;\n\n  index_type global_dimension_nodes;\n  index_type global_dimension_add_nodes;\n  index_type global_dimension_derivatives;\n  index_type global_dimension;\n\n  // A copy of the tensors list that was generated by SetConductivities\n  std::vector<std::pair<std::string, Tensor> > tensors_;\n  std::vector<std::pair<std::string, T> > scalars_;\n\n  // Entry point for the parallel version\n  void parallel(int proc);\n\n  void add_lcl_gbl(index_type row, const std::vector<index_type> &cols, const std::vector<T> &lcl_a)\n  {\n    for (size_t i = 0; i < lcl_a.size(); i++)\n      fematrix_->coeffRef(row, cols[i]) += lcl_a[i];\n  }\n\n  void create_numerical_integration(std::vector<VMesh::coords_type>& p,\n                                    std::vector<double>& w,\n                                    std::vector<std::vector<double>>& d);\n  bool build_local_matrix(VMesh::Elem::index_type c_ind,\n                          index_type row,\n                          std::vector<T>& l_stiff,\n                          std::vector<VMesh::coords_type>& p,\n                          std::vector<double>& w,\n                          std::vector<std::vector<double>>& d);\n  bool build_local_matrix_regular(VMesh::Elem::index_type c_ind,\n                                  index_type row,\n                                  std::vector<T>& l_stiff,\n                                  std::vector<VMesh::coords_type>& p,\n                                  std::vector<double>& w,\n                                  std::vector<std::vector<double>>& d,\n                                  std::vector<std::vector<T>>& precompute);\n  bool setup();\n\n};\n}}}}\n\ntemplate <typename T>\nbool\nFEMBuilder<T>::build_matrix(FieldHandle input,\n                         DenseMatrixHandle ctable,\n                         matrix_pointer_type<T>& output)\n{\n  // Get virtual interface to data\n  field_ = input->vfield();\n  mesh_  = input->vmesh();\n\n#ifdef SCIRUN4_CODE_TO_BE_ENABLED_LATER\n  // If we have the Conductivity property use it, if not we assume the values on\n  // the data to be the actual tensors.\n  field_->get_property(\"conductivity_table\",tensors_);\n#endif\n\n  // We added a second system of adding a conductivity table, using a matrix\n  // Convert that matrix into the conductivity table\n  if (ctable)\n  {\n    tensors_.clear();\n    auto mat = ctable;\n    // Only if we can convert it into a dense matrix, otherwise skip it\n    if (mat)\n    {\n      auto data = mat->data();\n      size_type m = mat->nrows();\n      size_type n = mat->ncols();\n      Tensor tensor;\n\n      // Case the table has isotropic conductivities\n      if (mat->ncols() == 1)\n      {\n        for (size_type p=0; p<m;p++)\n        {\n          // Set the diagonals to the proper version.\n          tensor.val(0,0) = data[p*n+0];\n          tensor.val(1,0) = 0.0;\n          tensor.val(2,0) = 0.0;\n          tensor.val(0,1) = 0.0;\n          tensor.val(1,1) = data[p*n+0];\n          tensor.val(2,1) = 0.0;\n          tensor.val(0,2) = 0.0;\n          tensor.val(1,2) = 0.0;\n          tensor.val(2,2) = data[p*n+0];\n          tensors_.push_back(std::make_pair(\"\",tensor));\n        }\n      }\n\n      // Use our compressed way of storing tensors\n      if (mat->ncols() == 6)\n      {\n        for (size_type p=0; p<m;p++)\n        {\n          tensor.val(0,0) = data[0+p*n];\n          tensor.val(1,0) = data[1+p*n];\n          tensor.val(2,0) = data[2+p*n];\n          tensor.val(0,1) = data[1+p*n];\n          tensor.val(1,1) = data[3+p*n];\n          tensor.val(2,1) = data[4+p*n];\n          tensor.val(0,2) = data[2+p*n];\n          tensor.val(1,2) = data[4+p*n];\n          tensor.val(2,2) = data[5+p*n];\n          tensors_.push_back(std::make_pair(\"\",tensor));\n        }\n      }\n\n      // Use the full symmetric tensor. We will make the tensor symmetric here.\n      if (mat->ncols() == 9)\n      {\n        for (size_type p=0; p<m;p++)\n        {\n          tensor.val(0,0) = data[0+p*n];\n          tensor.val(1,0) = data[1+p*n];\n          tensor.val(2,0) = data[2+p*n];\n          tensor.val(0,1) = data[1+p*n];\n          tensor.val(1,1) = data[4+p*n];\n          tensor.val(2,1) = data[5+p*n];\n          tensor.val(0,2) = data[2+p*n];\n          tensor.val(1,2) = data[5+p*n];\n          tensor.val(2,2) = data[8+p*n];\n          tensors_.push_back(std::make_pair(\"\",tensor));\n        }\n      }\n    }\n  }\n\n  success_.resize(numprocessors_,true);\n\n  // Start the multi threaded FE matrix builder.\n  Parallel::RunTasks([this](int i) { parallel(i); }, numprocessors_);\n  for (size_t j=0; j<success_.size(); j++)\n  {\n    if (!success_[j])\n    {\n      std::ostringstream oss;\n      oss << \"Algorithm failed in thread \" << j;\n      algo_->error(oss.str());\n      return false;\n    }\n  }\n\n  // Make sure it is symmetric\n  if (algo_->get(BuildFEMatrixAlgo::ForceSymmetry).toBool())\n  {\n    // Make sure the matrix is fully symmetric, this compensates for round off\n    // errors\n    matrix_type<T> transpose = fematrix_->transpose();\n    output.reset(new matrix_type<T>(0.5*(transpose + *fematrix_)));\n  }\n  else\n  {\n    // Assume that the builder did a good job and the matrix is numerically almost\n    // symmetric\n    output = fematrix_;\n  }\n  return true;\n}\n\ntemplate <typename T>\nvoid\nFEMBuilder<T>::create_numerical_integration(std::vector<VMesh::coords_type> &p,\n                                         std::vector<double> &w,\n                                         std::vector<std::vector<double> > &d)\n{\n  //ScopedTimeLogger s1(\"FEMBuilder::create_numerical_integration\");\n  int int_basis = 1;\n  if (mesh_->is_quad_element() ||\n      mesh_->is_hex_element() ||\n      mesh_->is_prism_element())\n  {\n    int_basis = 2;\n  }\n\n  mesh_->get_gaussian_scheme(p,w,int_basis);\n  d.resize(p.size());\n  for (size_t j=0; j<p.size();j++)\n  {\n    mesh_->get_derivate_weights(p[j],d[j],1);\n    size_t pad_size = ( 3 - p[ j ].size() ) * d[ j ].size();\n\n    if (pad_size > 0)\n      d[j].resize(pad_size + d[j].size(), 0.0);\n  }\n}\n\n/// build line of the local stiffness matrix\ntemplate <typename T>\nbool\nFEMBuilder<T>::build_local_matrix(VMesh::Elem::index_type c_ind,\n                               index_type row,\n                               std::vector<T> &l_stiff,\n                               std::vector<VMesh::coords_type> &p,\n                               std::vector<double> &w,\n                               std::vector<std::vector<double>>  &d)\n{\n  Tensor tensor;\n\n  if (tensors_.empty())\n  {\n    field_->get_value(tensor,c_ind);\n  }\n  else\n  {\n    int tensor_index;\n    field_->get_value(tensor_index,c_ind);\n    tensor = tensors_[tensor_index].second;\n  }\n\n  auto Ca = tensor.val(0,0);\n  auto Cb = tensor.val(0,1);\n  auto Cc = tensor.val(0,2);\n  auto Cd = tensor.val(1,1);\n  auto Ce = tensor.val(1,2);\n  auto Cf = tensor.val(2,2);\n\n  if ( (Ca==0) && (Cb==0) && (Cc==0) && (Cd==0) && (Ce==0) && (Cf==0) )\n  {\n    for (int j = 0; j<local_dimension; j++)\n    {\n      l_stiff[j] = 0.0;\n    }\n  }\n  else\n  {\n    /// @todo: replace with std::fill\n    for (int i=0; i<local_dimension; i++)\n      l_stiff[i] = 0.0;\n\n    auto local_dimension2=2*local_dimension;\n\n    // These calls are direct lookups in the base of the VMesh\n    // The compiler should optimize these well\n    auto vol = mesh_->get_element_size();\n    const int dim = mesh_->dimensionality();\n\n    if (dim < 1 || dim > 3)\n    {\n      algo_->error(\"Mesh dimension is 0 or larger than 3, for which no FE implementation is available\");\n      return false;\n    }\n    for (size_t i = 0; i < d.size(); i++)\n    {\n      double Ji[9];\n      auto detJ = mesh_->inverse_jacobian(p[i],c_ind,Ji);\n\n      // If Jacobian is negative there is a problem with the mesh\n      if (detJ <= 0.0)\n      {\n        algo_->error(\"Mesh has elements with negative jacobians, check the order of the nodes that define an element\");\n        return false;\n      }\n\n      // Volume associated with the local Gaussian Quadrature point:\n      // weightfactor * Volume Unit element * Volume ratio (real element/unit element)\n      detJ *= w[i] * vol;\n\n      // Build local stiffness matrix\n      // Get the local derivatives of the basis functions in the basis element\n      // They are all the same and are thus precomputed in matrix d\n      auto Nxi = &d[i][0];\n      auto Nyi = &d[i][local_dimension];\n      auto Nzi = &d[i][local_dimension2];\n      // Gradients associated with the node we are calculating\n      const auto& Nxip = Nxi[row];\n      const auto &Nyip = Nyi[row];\n      const auto &Nzip = Nzi[row];\n      // Calculating gradient shape function * inverse Jacobian * volume scaling factor\n      const auto uxp = detJ*(Nxip*Ji[0] + Nyip*Ji[1] + Nzip*Ji[2]);\n      const auto uyp = detJ*(Nxip*Ji[3] + Nyip*Ji[4] + Nzip*Ji[5]);\n      const auto uzp = detJ*(Nxip*Ji[6] + Nyip*Ji[7] + Nzip*Ji[8]);\n      // Matrix multiplication with conductivity tensor :\n      const auto uxyzpabc = uxp*Ca + uyp*Cb + uzp*Cc;\n      const auto uxyzpbde = uxp*Cb + uyp*Cd + uzp*Ce;\n      const auto uxyzpcef = uxp*Cc + uyp*Ce + uzp*Cf;\n\n      // The above is constant for this node. Now multiply with the weight function\n      // We assume the weight factors are the same as the local gradients\n      // Galerkin approximation:\n\n      for (int j = 0; j<local_dimension; j++)\n      {\n        const auto &Nxj = Nxi[j];\n        const auto &Nyj = Nyi[j];\n        const auto &Nzj = Nzi[j];\n\n        // Matrix multiplication Gradient with inverse Jacobian:\n        const auto ux = Nxj*Ji[0] + Nyj*Ji[1] + Nzj*Ji[2];\n        const auto uy = Nxj*Ji[3] + Nyj*Ji[4] + Nzj*Ji[5];\n        const auto uz = Nxj*Ji[6] + Nyj*Ji[7] + Nzj*Ji[8];\n\n        // Add everything together into one coefficient of the matrix\n        l_stiff[j] += ux*uxyzpabc+uy*uxyzpbde+uz*uxyzpcef;\n      }\n    }\n  }\n  return true;\n}\n\ntemplate <typename T>\nbool\nFEMBuilder<T>::build_local_matrix_regular(VMesh::Elem::index_type c_ind,\n                                       index_type row,\n                                       std::vector<T> &l_stiff,\n                                       std::vector<VMesh::coords_type> &p,\n                                       std::vector<double> &w,\n                                       std::vector<std::vector<double>> &d,\n                                       std::vector<std::vector<T>> &precompute)\n{\n  Tensor tensor;\n\n  if (tensors_.empty())\n  {\n    // Call to virtual interface. Get the tensor value. Actually this call relies\n    // on the automatic casting feature of the virtual interface to convert scalar\n    // values into a tensor.\n    field_->get_value(tensor,c_ind);\n  }\n  else\n  {\n    int tensor_index;\n    field_->get_value(tensor_index,c_ind);\n    tensor = tensors_[tensor_index].second;\n  }\n\n  auto Ca = tensor.val(0,0);\n  auto Cb = tensor.val(0,1);\n  auto Cc = tensor.val(0,2);\n  auto Cd = tensor.val(1,1);\n  auto Ce = tensor.val(1,2);\n  auto Cf = tensor.val(2,2);\n\n  if ( (Ca==0) && (Cb==0) && (Cc==0) && (Cd==0) && (Ce==0) && (Cf==0) )\n  {\n    for (int j = 0; j<local_dimension; j++)\n    {\n      l_stiff[j] = 0.0;\n    }\n  }\n  else\n  {\n\n    if (precompute.empty())\n    {\n      precompute.resize(d.size());\n      for (int m=0; m < static_cast<int>(d.size()); m++)\n      {\n        precompute[m].resize(10);\n      }\n\n      for(int i=0; i<local_dimension; i++)\n        l_stiff[i] = 0.0;\n\n      auto local_dimension2=2*local_dimension;\n\n      auto vol = mesh_->get_element_size();\n\n      for (size_t i = 0; i < d.size(); i++)\n      {\n        auto& pc = precompute[i];\n\n        double Ji[9];\n        auto detJ = mesh_->inverse_jacobian(p[i], c_ind, Ji);\n\n        // Volume elements can return negative determinants if the order of elements\n        // is put in a different order\n        /// @todo: It seems to be that a negative determinant is not necessarily bad,\n        // we should be more flexible on this point\n        if (detJ <= 0.0)\n        {\n          algo_->error(\"Mesh has elements with negative jacobians, check the order of the nodes that define an element\");\n          return false;\n        }\n        // Volume associated with the local Gaussian Quadrature point:\n        // weightfactor * Volume Unit element * Volume ratio (real element/unit element)\n        detJ*=w[i]*vol;\n\n        pc[0] = Ji[0];\n        pc[1] = Ji[1];\n        pc[2] = Ji[2];\n        pc[3] = Ji[3];\n        pc[4] = Ji[4];\n        pc[5] = Ji[5];\n        pc[6] = Ji[6];\n        pc[7] = Ji[7];\n        pc[8] = Ji[8];\n        pc[9] = detJ;\n\n        // Build local stiffness matrix\n        // Get the local derivatives of the basis functions in the basis element\n        // They are all the same and are thus precomputed in matrix d\n        auto Nxi = &d[i][0];\n        auto Nyi = &d[i][local_dimension];\n        auto Nzi = &d[i][local_dimension2];\n        // Gradients associated with the node we are calculating\n        const auto &Nxip = Nxi[row];\n        const auto &Nyip = Nyi[row];\n        const auto &Nzip = Nzi[row];\n        // Calculating gradient shape function * inverse Jacobian * volume scaling factor\n        const auto uxp = pc[9]*(Nxip*pc[0]+Nyip*pc[1]+Nzip*pc[2]);\n        const auto uyp = pc[9]*(Nxip*pc[3]+Nyip*pc[4]+Nzip*pc[5]);\n        const auto uzp = pc[9]*(Nxip*pc[6]+Nyip*pc[7]+Nzip*pc[8]);\n        // Matrix multiplication with conductivity tensor :\n        const auto uxyzpabc = uxp*Ca+uyp*Cb+uzp*Cc;\n        const auto uxyzpbde = uxp*Cb+uyp*Cd+uzp*Ce;\n        const auto uxyzpcef = uxp*Cc+uyp*Ce+uzp*Cf;\n\n        // The above is constant for this node. Now multiply with the weight function\n        // We assume the weight factors are the same as the local gradients\n        // Galerkin approximation:\n\n        for (int j = 0; j<local_dimension; j++)\n        {\n          const auto &Nxj = Nxi[j];\n          const auto &Nyj = Nyi[j];\n          const auto &Nzj = Nzi[j];\n\n          // Matrix multiplication Gradient with inverse Jacobian:\n          const auto ux = Nxj*pc[0]+Nyj*pc[1]+Nzj*pc[2];\n          const auto uy = Nxj*pc[3]+Nyj*pc[4]+Nzj*pc[5];\n          const auto uz = Nxj*pc[6]+Nyj*pc[7]+Nzj*pc[8];\n\n          // Add everything together into one coefficient of the matrix\n          l_stiff[j] += ux*uxyzpabc+uy*uxyzpbde+uz*uxyzpcef;\n        }\n      }\n    }\n    else\n    {\n      for(int i=0; i<local_dimension; i++)\n        l_stiff[i] = 0.0;\n\n      auto local_dimension2=2*local_dimension;\n\n      for (size_t i = 0; i < d.size(); i++)\n      {\n        auto& pc = precompute[i];\n\n        // Build local stiffness matrix\n        // Get the local derivatives of the basis functions in the basis element\n        // They are all the same and are thus precomputed in matrix d\n        auto Nxi = &d[i][0];\n        auto Nyi = &d[i][local_dimension];\n        auto Nzi = &d[i][local_dimension2];\n        // Gradients associated with the node we are calculating\n        const auto &Nxip = Nxi[row];\n        const auto &Nyip = Nyi[row];\n        const auto &Nzip = Nzi[row];\n        // Calculating gradient shape function * inverse Jacobian * volume scaling factor\n        const auto uxp = pc[9]*(Nxip*pc[0]+Nyip*pc[1]+Nzip*pc[2]);\n        const auto uyp = pc[9]*(Nxip*pc[3]+Nyip*pc[4]+Nzip*pc[5]);\n        const auto uzp = pc[9]*(Nxip*pc[6]+Nyip*pc[7]+Nzip*pc[8]);\n        // Matrix multiplication with conductivity tensor :\n        const auto uxyzpabc = uxp*Ca+uyp*Cb+uzp*Cc;\n        const auto uxyzpbde = uxp*Cb+uyp*Cd+uzp*Ce;\n        const auto uxyzpcef = uxp*Cc+uyp*Ce+uzp*Cf;\n\n        // The above is constant for this node. Now multiply with the weight function\n        // We assume the weight factors are the same as the local gradients\n        // Galerkin approximation:\n\n        for (int j = 0; j<local_dimension; j++)\n        {\n          const auto &Nxj = Nxi[j];\n          const auto &Nyj = Nyi[j];\n          const auto &Nzj = Nzi[j];\n\n          // Matrix multiplication Gradient with inverse Jacobian:\n          const auto ux = Nxj*pc[0]+Nyj*pc[1]+Nzj*pc[2];\n          const auto uy = Nxj*pc[3]+Nyj*pc[4]+Nzj*pc[5];\n          const auto uz = Nxj*pc[6]+Nyj*pc[7]+Nzj*pc[8];\n\n          // Add everything together into one coefficient of the matrix\n          l_stiff[j] += ux*uxyzpabc+uy*uxyzpbde+uz*uxyzpcef;\n        }\n      }\n    }\n  }\n  return true;\n}\n\ntemplate <typename T>\nbool\nFEMBuilder<T>::setup()\n{\n  // The domain dimension\n  domain_dimension = mesh_->dimensionality();\n  if (domain_dimension < 1)\n  {\n    algo_->error(\"This mesh type cannot be used for FE computations\");\n    return false;\n  }\n\n  local_dimension_nodes = mesh_->num_nodes_per_elem();\n  if (field_->basis_order() == 2)\n  {\n    local_dimension_add_nodes = mesh_->num_enodes_per_elem();\n  }\n  else\n  {\n    local_dimension_add_nodes = 0;\n  }\n\n  local_dimension_derivatives = 0;\n\n  // Local degrees of freedom per element\n  local_dimension = local_dimension_nodes +\n  local_dimension_add_nodes +\n  local_dimension_derivatives; ///< degrees of freedom (dofs) of system\n\n  VMesh::Node::size_type mns;\n  mesh_->size(mns);\n\n  // Number of mesh points (not necessarily number of nodes)\n  global_dimension_nodes = mns;\n  if (field_->basis_order() == 2) // quadratic\n  {\n    mesh_->synchronize(Mesh::ENODES_E);\n    global_dimension_add_nodes = mesh_->num_enodes();\n  }\n  else\n  {\n    global_dimension_add_nodes = 0;\n  }\n\n  global_dimension_derivatives = 0;\n  global_dimension = global_dimension_nodes+\n  global_dimension_add_nodes+\n  global_dimension_derivatives;\n\n  if (mns > 0)\n  {\n    // We only need edges for the higher order basis in case of quartic Lagrangian\n    // Hence we should only synchronize it for this case\n    if (global_dimension_add_nodes > 0)\n      mesh_->synchronize(Mesh::EDGES_E|Mesh::NODE_NEIGHBORS_E);\n    else\n      mesh_->synchronize(Mesh::NODE_NEIGHBORS_E);\n  }\n  else\n  {\n    algo_->error(\"Mesh size < 0\");\n    success_[0] = false;\n  }\n  LOG_DEBUG(\"Allocating buffer for nonzero row indices of size: {}\", global_dimension+1);\n  rows_.reset(new index_type[global_dimension+1]);\n\n  colidx_.resize(numprocessors_+1);\n  return true;\n}\n\n// -- callback routine to execute in parallel\ntemplate <typename T>\nvoid\nFEMBuilder<T>::parallel(int proc_num)\n{\n  success_[proc_num] = true;\n\n  if (proc_num == 0)\n  {\n    try\n    {\n      success_[proc_num] = setup();\n    }\n    catch (...)\n    {\n      algo_->error(\"BuildFEMatrix could not setup FE Stiffness computation\");\n      success_[proc_num] = false;\n    }\n  }\n\n  barrier_.wait();\n\n  // In case one of the threads fails, we should have them fail all\n  for (int q = 0; q < numprocessors_; q++)\n  {\n    if (!success_[q])\n    {\n      std::ostringstream oss;\n      oss << \"FEMBuilder::setup failed in thread \" << q;\n      algo_->error(oss.str());\n      return;\n    }\n  }\n\n  /// distributing dofs among processors\n  const index_type start_gd = (global_dimension * proc_num)/numprocessors_;\n  const index_type end_gd  = (global_dimension * (proc_num+1))/numprocessors_;\n\n  /// creating sparse matrix structure\n  std::vector<index_type> mycols;\n\n  VMesh::Elem::array_type ca;\n  VMesh::Node::array_type na;\n  VMesh::Edge::array_type ea;\n  std::vector<index_type> neib_dofs;\n\n  /// loop over system dofs for this thread\n  int cnt = 0;\n  size_type size_gd = end_gd-start_gd;\n  auto updateFrequency = 2*size_gd / 100;\n  try\n  {\n    mycols.reserve((end_gd - start_gd)*local_dimension*8);  //<! rough estimate\n\n    for (VMesh::Node::index_type i = start_gd; i<end_gd; ++i)\n    {\n      rows_[i] = mycols.size();\n\n      neib_dofs.clear();\n      /// check for nodes\n      if (i < global_dimension_nodes)\n      {\n        /// get neighboring cells for node\n        mesh_->get_elems(ca, i);\n      }\n      else if (i < global_dimension_nodes+global_dimension_add_nodes)\n      {\n        /// check for additional nodes at edges\n        /// get neighboring cells for node\n        VMesh::Edge::index_type ii(i-global_dimension_nodes);\n        mesh_->get_elems(ca,ii);\n      }\n      else\n      {\n        // There is some functionality implemented for higher order basis functions,\n        // but it seems not to be accessible, entirely implemented nor validated.\n        algo_->warning(\"BuildFEMatrix only supports linear basis functions.\");\n      }\n\n      for(size_t j = 0; j < ca.size(); j++)\n      {\n        /// get neighboring nodes\n        mesh_->get_nodes(na, ca[j]);\n\n        for(size_t k = 0; k < na.size(); k++)\n        {\n          neib_dofs.push_back(static_cast<index_type>(na[k]));\n        }\n\n        /// check for additional nodes at edges\n        if (global_dimension_add_nodes)\n        {\n          /// get neighboring edges\n          mesh_->get_edges(ea, ca[j]);\n\n          for(size_t k = 0; k < ea.size(); k++)\n            neib_dofs.push_back(global_dimension + ea[k]);\n        }\n      }\n\n      std::sort(neib_dofs.begin(), neib_dofs.end());\n\n      for (size_t j=0; j<neib_dofs.size(); j++)\n      {\n        if (j == 0 || neib_dofs[j] != mycols.back())\n        {\n          mycols.push_back(neib_dofs[j]);\n        }\n      }\n      if (proc_num == 0)\n      {\n        cnt++;\n        if (cnt == updateFrequency)\n        {\n          cnt = 0;\n          algo_->update_progress_max(i,2*size_gd);\n        }\n      }\n    }\n\n    colidx_[proc_num] = mycols.size();\n    success_[proc_num] = true;\n  }\n  catch (...)\n  {\n    algo_->error(\"BuildFEMatrix crashed mapping out stiffness matrix\");\n    success_[proc_num] = false;\n  }\n\n  /// check point\n  barrier_.wait();\n\n  // Bail out if one of the processes failed\n  for (int q=0; q<numprocessors_;q++)\n  {\n    if (!success_[q])\n    {\n      return;\n    }\n  }\n\n  std::vector<std::vector<T>> precompute;\n  index_type st = 0;\n\n  if (proc_num == 0)\n    allcols_.reset();\n\n  try\n  {\n    if (proc_num == 0)\n    {\n      for(int i=0; i<numprocessors_; i++)\n      {\n        const index_type ns = colidx_[i];\n        colidx_[i] = st;\n        st += ns;\n      }\n\n      colidx_[numprocessors_] = st;\n      allcols_.reset(new index_type[st]);\n    }\n    success_[proc_num] = true;\n  }\n  catch (...)\n  {\n    if (proc_num == 0)\n      allcols_.reset();\n\n    algo_->error(\"Could not allocate enough memory\");\n    success_[proc_num] = false;\n  }\n\n  /// check point\n  barrier_.wait();\n\n  // Bail out if one of the processes failed\n  for (int q=0; q<numprocessors_;q++)\n  {\n    if (! success_[q])\n      return;\n  }\n\n  try\n  {\n    /// updating global column by each of the processors\n    const index_type s = colidx_[proc_num];\n    const size_t n = mycols.size();\n\n    for(size_t i=0; i<n; i++)\n      allcols_[i+s] = mycols[i];\n\n    for(index_type i = start_gd; i<end_gd; i++)\n      rows_[i] += s;\n\n    success_[proc_num] = true;\n  }\n  catch (...)\n  {\n    algo_->error(\"BuildFEMatrix crashed while setting up row compression\");\n    success_[proc_num] = false;\n  }\n\n  /// check point\n  barrier_.wait();\n\n  // Bail out if one of the processes failed\n  for (auto q=0; q<numprocessors_; q++)\n  {\n    if (!success_[q])\n      return;\n  }\n\n  try\n  {\n    /// the main thread makes the matrix\n    if (proc_num == 0)\n    {\n      rows_[global_dimension] = st;\n      algo_->remark(\"Creating fematrix on main thread.\");\n      fematrix_ = makeShared<matrix_type<T>>(global_dimension, global_dimension, rows_.get(), allcols_.get(), st);\n      rows_.reset();\n      allcols_.reset();\n    }\n    success_[proc_num] = true;\n  }\n  catch (...)\n  {\n    algo_->error(\"BuildFEMatrix crashed while creating final stiffness matrix\");\n    success_[proc_num] = false;\n  }\n\n  /// check point\n  barrier_.wait();\n\n  // Bail out if one of the processes failed\n  for (auto q=0; q<numprocessors_;q++)\n  {\n    if (!success_[q])\n      return;\n  }\n\n  try\n  {\n    /// zeroing in parallel\n    const auto ns = colidx_[proc_num];\n    const auto ne = colidx_[proc_num+1];\n    auto a = &(fematrix_->valuePtr()[ns]), ae=&(fematrix_->valuePtr()[ne]);\n    while (a<ae) *a++=0.0;\n\n    std::vector<VMesh::coords_type> ni_points;\n    std::vector<double> ni_weights;\n    std::vector<std::vector<double>> ni_derivatives;\n\n    create_numerical_integration(ni_points, ni_weights, ni_derivatives);\n\n    std::vector<T> lsml; ///< line of local stiffnes matrix\n    lsml.resize(local_dimension);\n\n    /// loop over system dofs for this thread\n    cnt = 0;\n    size_gd = end_gd-start_gd;\n    for (VMesh::Node::index_type i = start_gd; i<end_gd; ++i)\n    {\n      if (i < global_dimension_nodes)\n      {\n        /// check for nodes\n        /// get neighboring cells for node\n        mesh_->get_elems(ca,i);\n      }\n      else if (i < global_dimension_nodes + global_dimension_add_nodes)\n      {\n        /// check for additional nodes at edges\n        /// get neighboring cells for additional nodes\n        VMesh::Edge::index_type ii(i-global_dimension_nodes);\n        mesh_->get_elems(ca,ii);\n      }\n      else\n      {\n        // There is some functionality implemented for higher order basis functions,\n        // but it seems not to be accessible, entirely implemented nor validated.\n        algo_->warning(\"BuildFEMatrix only supports linear basis functions.\");\n      }\n\n      /// loop over elements attributed elements\n\n      if (mesh_->is_regularmesh())\n      {\n        for (size_t j = 0; j < ca.size(); j++)\n        {\n          mesh_->get_nodes(na, ca[j]); ///< get neighboring nodes\n          neib_dofs.resize(na.size());\n          for(size_t k = 0; k < na.size(); k++)\n          {\n            neib_dofs[k] = na[k]; // Must cast to (int) for SGI compiler :-(\n          }\n\n          for(size_t k = 0; k < na.size(); k++)\n          {\n            if (na[k] == i)\n            {\n              auto successLocal = build_local_matrix_regular(ca[j], k , lsml, ni_points, ni_weights, ni_derivatives,precompute);\n\t\t\t\t\t\t\tif (!successLocal)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsuccess_[proc_num] = false;\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n              add_lcl_gbl(i, neib_dofs, lsml);\n            }\n          }\n        }\n      }\n      else\n      {\n        for (size_t j = 0; j < ca.size(); j++)\n        {\n          neib_dofs.clear();\n          mesh_->get_nodes(na, ca[j]); ///< get neighboring nodes\n          for(size_t k = 0; k < na.size(); k++)\n          {\n            neib_dofs.push_back(na[k]); // Must cast to (int) for SGI compiler :-(\n          }\n          /// check for additional nodes at edges\n          if (global_dimension_add_nodes)\n          {\n            mesh_->get_edges(ea, ca[j]); ///< get neighboring edges\n            for(size_t k = 0; k < ea.size(); k++)\n            {\n              neib_dofs.push_back(global_dimension + ea[k]);\n            }\n          }\n\n          ASSERT(static_cast<int>(neib_dofs.size()) == local_dimension);\n\n          for(size_t k = 0; k < na.size(); k++)\n          {\n            if (na[k] == i)\n            {\n              auto successLocal = build_local_matrix(ca[j], k , lsml, ni_points, ni_weights, ni_derivatives);\n\t\t\t\t\t\t\tif (!successLocal)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsuccess_[proc_num] = false;\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n              add_lcl_gbl(i, neib_dofs, lsml);\n            }\n          }\n\n          if (global_dimension_add_nodes)\n          {\n            for (size_t k = 0; k < ea.size(); k++)\n            {\n              if (global_dimension + static_cast<int>(ea[k]) == i)\n              {\n                auto successLocal = build_local_matrix(ca[j], k+na.size(), lsml, ni_points, ni_weights, ni_derivatives);\n\t\t\t\t\t\t\t\tif (!successLocal)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tsuccess_[proc_num] = false;\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n                add_lcl_gbl(i, neib_dofs, lsml);\n              }\n            }\n          }\n        }\n      }\n\n      if (proc_num == 0)\n      {\n        cnt++;\n        if (cnt == updateFrequency)\n        {\n          cnt = 0;\n          algo_->update_progress_max(i+size_gd,2*size_gd);\n        }\n      }\n    }\n    success_[proc_num] = true;\n  }\n  catch (...)\n  {\n    algo_->error(\"BuildFEMatrix crashed while filling out stiffness matrix\");\n    success_[proc_num] = false;\n  }\n\n  barrier_.wait();\n\n  // Bail out if one of the processes failed\n  for (int q=0; q<numprocessors_; q++)\n  {\n    if (!success_[q])\n      return;\n  }\n}\n\nconst AlgorithmParameterName BuildFEMatrixAlgo::ForceSymmetry(\"ForceSymmetry\");\nconst AlgorithmParameterName BuildFEMatrixAlgo::GenerateBasis(\"GenerateBasis\");\n\ntemplate <typename T>\nbool\nBuildFEMatrixAlgoImpl<T>::run(FieldHandle input, DenseMatrixHandle ctable, matrix_pointer_type<T>& output) const\n{\n  ScopedAlgorithmStatusReporter s(algo_, \"BuildFEMatrix\");\n\n  if (!input)\n  {\n    algo_->error(\"Could not obtain input field\");\n    return false;\n  }\n\n  if (input->vfield()->is_vector())\n  {\n    algo_->error(\"This function has not yet been defined for elements with vector data\");\n    return false;\n  }\n\n  if (input->vfield()->basis_order()!=0)\n  {\n    algo_->error(\"This function has only been defined for data that is located at the elements\");\n    return false;\n  }\n\n  if (ctable)\n  {\n    if ((ctable->ncols() != 1)&&(ctable->ncols() != 6)&&(ctable->ncols() != 9))\n    {\n      algo_->error(\"Conductivity table needs to have 1, 6, or 9 columns\");\n      return false;\n    }\n    if (ctable->nrows() == 0)\n    {\n      algo_->error(\"ConductivityTable is empty\");\n      return false;\n    }\n  }\n\n  FEMBuilder<T> builder(algo_);\n\n  if (algo_->get(BuildFEMatrixAlgo::GenerateBasis).toBool())\n  {\n    if (!ctable)\n    {\n      std::vector<std::pair<std::string,Tensor> > tens;\n\n      input->properties().get_property(\"conductivity_table\",tens);\n\n      if (!tens.empty())\n      {\n        ctable.reset(new DenseMatrix(tens.size(), 1));\n        auto data = ctable->data();\n        for (size_t i=0; i<tens.size();i++)\n        {\n          auto t = tens[i].second.val(0,0);\n          data[i] = t;\n        }\n      }\n    }\n\n    if (ctable)\n    {\n      auto nconds = ctable->nrows();\n      if ( (input->vmesh()->generation() != generation_) ||\n          (!basis_fematrix_) )\n      {\n        auto con = makeShared<DenseMatrix>(nconds, 1, 0.0);\n        auto data = con->data();\n\n        if (!builder.build_matrix(input, con, basis_fematrix_) )\n        {\n          algo_->error(\"Build matrix method failed when building FEMatrix structure\");\n          return false;\n        }\n\n        if (!basis_fematrix_)\n        {\n          algo_->error(\"Failed to build FEMatrix structure\");\n          return false;\n        }\n\n        basis_values_.resize(nconds);\n        for (size_type i=0; i < nconds; i++)\n        {\n          matrix_pointer_type<T> stiffness;\n          /// @todo: can initialize array using std::fill\n          data[i] = 1.0;\n\n          if (!builder.build_matrix(input, con, stiffness) )\n          {\n            algo_->error(\"Build matrix method failed for one of the tissue types\");\n            return false;\n          }\n\n          if (!stiffness)\n          {\n            algo_->error(\"Failed to build FEMatrix component for one of the tissue types\");\n            return false;\n          }\n\n          basis_values_[i].resize(stiffness->nonZeros());\n          for (size_type p=0; p< stiffness->nonZeros(); p++)\n          {\n            basis_values_[i][p] = stiffness->valuePtr()[p];\n          }\n          data[i] = 0.0;\n        }\n\n        generation_ = input->vmesh()->generation();\n      }\n\n      output.reset(basis_fematrix_->clone());\n\n      auto sum = output->valuePtr();\n      auto cdata = ctable->data();\n      auto n = ctable->ncols();\n\n      if (!basis_values_.empty())\n      {\n        for (size_t p=0; p < basis_values_[0].size(); p++)\n          sum[p] = 0.0;\n      }\n\n      for (auto i=0; i<nconds; i++)\n      {\n        auto weight = cdata[i*n];\n        for (size_t p=0; p < basis_values_[i].size(); p++)\n        {\n          sum[p] += weight * basis_values_[i][p];\n        }\n      }\n\n    }\n    else\n    {\n      algo_->error(\"No conductivity table present: The generate_basis option only works for indexed conductivities\");\n      return false;\n    }\n  }\n\n  if (!builder.build_matrix(input,ctable,output) )\n  {\n    algo_->error(\"Build matrix method failed to build output matrix\");\n    return false;\n  }\n\n  if (!output)\n  {\n    algo_->error(\"Could not build output matrix\");\n    return false;\n  }\n\n  return true;\n}\n\nconst AlgorithmInputName BuildFEMatrixAlgo::Conductivity_Table(\"Conductivity_Table\");\nconst AlgorithmOutputName BuildFEMatrixAlgo::Stiffness_Matrix(\"Stiffness_Matrix\");\nconst AlgorithmOutputName BuildFEMatrixAlgo::Stiffness_Matrix_Complex(\"Stiffness_Matrix_Complex\");\n\nAlgorithmOutput BuildFEMatrixAlgo::run(const AlgorithmInput& input) const\n{\n  auto field = input.get<Field>(Variables::InputField);\n  auto ctable = input.get<DenseMatrix>(Conductivity_Table);\n\n\tAlgorithmOutput output;\n  if (field && field->vfield() && field->vfield()->is_complex_double())\n\t{\n\t\tmatrix_pointer_type<complex> stiffness;\n\t  BuildFEMatrixAlgoImpl<complex> impl(this);\n\t  if (!impl.run(field, ctable, stiffness))\n\t    THROW_ALGORITHM_PROCESSING_ERROR(\"False returned on legacy run call.--complex detected\t\");\n\t\toutput[Stiffness_Matrix_Complex] = stiffness;\n\t}\n\telse\n\t{\n\t\tmatrix_pointer_type<double> stiffness;\n\t  BuildFEMatrixAlgoImpl<double> impl(this);\n\t  if (!impl.run(field, ctable, stiffness))\n\t    THROW_ALGORITHM_PROCESSING_ERROR(\"False returned on legacy run call.\");\n\t\toutput[Stiffness_Matrix] = stiffness;\n\t}\n\n\n\n  return output;\n}\n", "meta": {"hexsha": "f54b311cd5ce8d0002ed5ddeb0e0e28eea918023", "size": 37028, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Algorithms/Legacy/FiniteElements/BuildMatrix/BuildFEMatrix.cc", "max_stars_repo_name": "kimjohn1/SCIRun", "max_stars_repo_head_hexsha": "62ae6cb632100371831530c755ef0b133fb5c978", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 92.0, "max_stars_repo_stars_event_min_datetime": "2015-02-09T22:42:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T09:14:50.000Z", "max_issues_repo_path": "src/Core/Algorithms/Legacy/FiniteElements/BuildMatrix/BuildFEMatrix.cc", "max_issues_repo_name": "kimjohn1/SCIRun", "max_issues_repo_head_hexsha": "62ae6cb632100371831530c755ef0b133fb5c978", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1618.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T19:39:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T20:28:45.000Z", "max_forks_repo_path": "src/Core/Algorithms/Legacy/FiniteElements/BuildMatrix/BuildFEMatrix.cc", "max_forks_repo_name": "kimjohn1/SCIRun", "max_forks_repo_head_hexsha": "62ae6cb632100371831530c755ef0b133fb5c978", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 64.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T17:51:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-19T07:08:08.000Z", "avg_line_length": 29.3407290016, "max_line_length": 128, "alphanum_fraction": 0.5946580966, "num_tokens": 9967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2561710346690169}}
{"text": "#ifndef AIKIDO_CONSTRAINT_DART_TSR_HPP_\n#define AIKIDO_CONSTRAINT_DART_TSR_HPP_\n\n#include <Eigen/Dense>\n#include <dart/math/MathTypes.hpp>\n\n#include \"aikido/constraint/Differentiable.hpp\"\n#include \"aikido/constraint/Projectable.hpp\"\n#include \"aikido/constraint/Sampleable.hpp\"\n#include \"aikido/constraint/Testable.hpp\"\n#include \"aikido/statespace/SE3.hpp\"\n\nnamespace aikido {\nnamespace constraint {\nnamespace dart {\n\nAIKIDO_DECLARE_POINTERS(TSR)\n\n/// TSRs describe end-effector constraint sets as subsets of SE(3).\n/// A TSR consists of three parts:\n///     T0_w: transform from the origin to the TSR frame w\n///     B_w: 6 × 2 matrix of bounds in the coordinates of w.\n///     Tw_e: end-effector offset transform in the coordinates of w\n/// See:\n/// Berenson, Dmitry, Siddhartha S. Srinivasa, and James Kuffner.\n/// \"Task space regions: A framework for pose-constrained manipulation\n/// planning.\" IJRR 2001:\n/// http://repository.cmu.edu/cgi/viewcontent.cgi?article=2024&context=robotics\nclass TSR\n  : public Sampleable\n  , public Differentiable\n  , public Testable\n  , public Projectable\n{\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  using Differentiable::getValueAndJacobian;\n\n  /// Constructor.\n  /// \\param _rng Random number generator used by SampleGenerators for this TSR.\n  /// \\param _T0_w transform from the origin to the TSR frame w\n  /// \\param _Bw 6 × 2 matrix of bounds in the coordinates of w.\n  ///        Top three rows bound translation, and bottom three rows\n  ///        bound rotation following Roll-Pitch-Yaw convention.\n  ///        _Bw(i, 0) should be less than or equal to _Bw(i, 1).\n  /// \\param _Tw_e end-effector offset transform in the coordinates of w\n  /// \\param _testableTolerance tolerance used in isSatisfiable as testable\n  TSR(std::unique_ptr<common::RNG> _rng,\n      const Eigen::Isometry3d& _T0_w = Eigen::Isometry3d::Identity(),\n      const Eigen::Matrix<double, 6, 2>& _Bw\n      = Eigen::Matrix<double, 6, 2>::Zero(),\n      const Eigen::Isometry3d& _Tw_e = Eigen::Isometry3d::Identity(),\n      double _testableTolerance = 1e-6);\n\n  /// Constructor with default random seed generator.\n  /// \\param _T0_w transform from the origin to the TSR frame w\n  /// \\param _Bw 6 × 2 matrix of bounds in the coordinates of w.\n  ///        Top three rows bound translation, and bottom three rows\n  ///        bound rotation following Roll-Pitch-Yaw convention.\n  ///        _Bw(i, 0) should be less than or equal to _Bw(i, 1).\n  /// \\param _Tw_e end-effector offset transform in the coordinates of w\n  /// \\param _testableTolerance tolerance used in isSatisfiable as testable\n  TSR(const Eigen::Isometry3d& _T0_w = Eigen::Isometry3d::Identity(),\n      const Eigen::Matrix<double, 6, 2>& _Bw\n      = Eigen::Matrix<double, 6, 2>::Zero(),\n      const Eigen::Isometry3d& _Tw_e = Eigen::Isometry3d::Identity(),\n      double _testableTolerance = 1e-6);\n\n  TSR(const TSR& other);\n  TSR(TSR&& other);\n\n  TSR& operator=(const TSR& other);\n  TSR& operator=(TSR&& other);\n\n  virtual ~TSR() = default;\n\n  // Documentation inherited.\n  statespace::ConstStateSpacePtr getStateSpace() const override;\n\n  /// Returns the SE3 which this TSR operates in.\n  std::shared_ptr<statespace::SE3> getSE3() const;\n\n  // Documentation inherited.\n  std::unique_ptr<SampleGenerator> createSampleGenerator() const override;\n\n  // Documentation inherited.\n  bool isSatisfied(\n      const statespace::StateSpace::State* _s,\n      TestableOutcome* outcome = nullptr) const override;\n\n  /// Return an instance of DefaultTestableOutcome, since this class doesn't\n  /// have a more specialized TestableOutcome derivative assigned to it.\n  std::unique_ptr<TestableOutcome> createOutcome() const override;\n\n  /// Throws an invalid_argument exception if this TSR is invalid.\n  /// For a TSR to be valid, mBw(i, 0) <= mBw(i, 1).\n  void validate() const;\n\n  /// Set the random number generator used by SampleGenerators for this TSR.\n  void setRNG(std::unique_ptr<common::RNG> rng);\n\n  // Documentation inherited.\n  std::size_t getConstraintDimension() const override;\n\n  // Documentation inherited.\n  void getValue(const statespace::StateSpace::State* _s, Eigen::VectorXd& _out)\n      const override;\n\n  /// Jacobian of TSR with respect to the se(3) tangent vector of _s.\n  /// The jacobian is w.r.t. the origin frame.\n  /// se(3) tangent vector follows dart convention:\n  ///   top 3 rows is the angle-axis representation of _s's rotation.\n  ///   bottom 3 rows represent the translation.\n  /// \\param _s State to be evaluated at.\n  /// \\param[out] _out Jacobian, 6 x 6 matrix.\n  void getJacobian(\n      const statespace::StateSpace::State* _s,\n      Eigen::MatrixXd& _out) const override;\n\n  // Documentation inherited.\n  std::vector<ConstraintType> getConstraintTypes() const override;\n\n  // Documentation inherited.\n  bool project(\n      const statespace::StateSpace::State* _s,\n      statespace::StateSpace::State* _out) const override;\n\n  /// Get the testable tolerance used in isSatisfiable.\n  double getTestableTolerance();\n\n  /// Set the testable tolerance used in isSatisfiable.\n  /// \\param _testableTolerance Testable tolerance to set.\n  void setTestableTolerance(double _testableTolerance);\n\n  /// Transformation from origin frame into the TSR frame \"w\".\n  /// \"w\" is usually centered at the origin of an object held by the hand\n  ///  or at a location on an object that is useful for grasping.\n  Eigen::Isometry3d mT0_w;\n\n  /// Bounds on \"wiggling\" in `x, y, z, roll, pitch, yaw`.\n  Eigen::Matrix<double, 6, 2> mBw;\n\n  /// Transformation from \"w\" frame into end frame.\n  /// This often represent an offset from \"w\" to the origin of the end-effector.\n  Eigen::Isometry3d mTw_e;\n\nprivate:\n  /// Tolerance used in isSatisfied as a testable\n  double mTestableTolerance;\n  std::unique_ptr<common::RNG> mRng;\n  std::shared_ptr<statespace::SE3> mStateSpace;\n};\n\n} // namespace dart\n} // namespace constraint\n} // namespace aikido\n\n#endif // AIKIDO_CONSTRAINT_DART_TSR_HPP_\n", "meta": {"hexsha": "b7f18c57adc7f02d9cd71ff533188c3d3d6388bf", "size": 5968, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/aikido/constraint/dart/TSR.hpp", "max_stars_repo_name": "personalrobotics/r3", "max_stars_repo_head_hexsha": "1303e3f3ef99a0c2249abc7415d19113f0026565", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 181.0, "max_stars_repo_stars_event_min_datetime": "2016-04-22T15:11:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T12:51:08.000Z", "max_issues_repo_path": "include/aikido/constraint/dart/TSR.hpp", "max_issues_repo_name": "personalrobotics/r3", "max_issues_repo_head_hexsha": "1303e3f3ef99a0c2249abc7415d19113f0026565", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 514.0, "max_issues_repo_issues_event_min_datetime": "2016-04-20T04:29:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T19:46:21.000Z", "max_forks_repo_path": "include/aikido/constraint/dart/TSR.hpp", "max_forks_repo_name": "personalrobotics/r3", "max_forks_repo_head_hexsha": "1303e3f3ef99a0c2249abc7415d19113f0026565", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2017-03-17T09:53:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T10:35:05.000Z", "avg_line_length": 37.3, "max_line_length": 80, "alphanum_fraction": 0.7159852547, "num_tokens": 1610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2560875842757364}}
{"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/methods/multipathgeneratorbase.hpp>\n\n#include <boost/make_shared.hpp>\n\nusing namespace QuantLib;\n\nnamespace QuantExt {\n\nMultiPathGeneratorMersenneTwister::MultiPathGeneratorMersenneTwister(\n    const boost::shared_ptr<StochasticProcess>& process, const TimeGrid& grid, BigNatural seed, bool antitheticSampling)\n    : process_(process), grid_(grid), seed_(seed), antitheticSampling_(antitheticSampling), antitheticVariate_(true) {\n    reset();\n}\n\nvoid MultiPathGeneratorMersenneTwister::reset() {\n    PseudoRandom::rsg_type rsg = PseudoRandom::make_sequence_generator(process_->size() * (grid_.size() - 1), seed_);\n    pg_ = boost::make_shared<MultiPathGenerator<PseudoRandom::rsg_type> >(process_, grid_, rsg, false);\n    antitheticVariate_ = true;\n}\n\nMultiPathGeneratorSobol::MultiPathGeneratorSobol(const boost::shared_ptr<StochasticProcess>& process,\n                                                 const TimeGrid& grid, BigNatural seed,\n                                                 SobolRsg::DirectionIntegers directionIntegers)\n    : process_(process), grid_(grid), seed_(seed), directionIntegers_(directionIntegers) {\n    reset();\n}\n\nvoid MultiPathGeneratorSobol::reset() {\n    pg_ = boost::make_shared<MultiPathGenerator<InverseCumulativeRsg<SobolRsg, InverseCumulativeNormal> > >(\n        process_, grid_,\n        InverseCumulativeRsg<SobolRsg, InverseCumulativeNormal>(\n            SobolRsg(process_->size() * (grid_.size() - 1), seed_, directionIntegers_)));\n}\n\nMultiPathGeneratorSobolBrownianBridge::MultiPathGeneratorSobolBrownianBridge(\n    const boost::shared_ptr<StochasticProcess>& process, const TimeGrid& grid,\n    SobolBrownianGenerator::Ordering ordering, BigNatural seed, SobolRsg::DirectionIntegers directionIntegers)\n    : process_(process), grid_(grid), ordering_(ordering), seed_(seed), directionIntegers_(directionIntegers),\n      next_(MultiPath(process->size(), grid), 1.0) {\n    reset();\n}\n\nvoid MultiPathGeneratorSobolBrownianBridge::reset() {\n    gen_ = boost::make_shared<SobolBrownianGenerator>(process_->size(), grid_.size() - 1, ordering_, seed_,\n                                                      directionIntegers_);\n}\n\nconst Sample<MultiPath>& MultiPathGeneratorSobolBrownianBridge::next() const {\n    Array asset = process_->initialValues();\n    MultiPath& path = next_.value;\n    for (Size j = 0; j < asset.size(); ++j) {\n        path[j].front() = asset[j];\n    }\n    next_.weight = gen_->nextPath();\n    std::vector<Real> output(asset.size());\n    for (Size i = 1; i < grid_.size(); ++i) {\n        Real t = grid_[i - 1];\n        Real dt = grid_.dt(i - 1);\n        gen_->nextStep(output);\n        Array tmp(output.begin(), output.end());\n        asset = process_->evolve(t, asset, dt, tmp);\n        for (Size j = 0; j < asset.size(); ++j) {\n            path[j][i] = asset[j];\n        }\n    }\n    return next_;\n}\n\nboost::shared_ptr<MultiPathGeneratorBase> makeMultiPathGenerator(const SequenceType s,\n                                                                 const boost::shared_ptr<StochasticProcess>& process,\n                                                                 const TimeGrid& timeGrid, const BigNatural seed,\n                                                                 const SobolBrownianGenerator::Ordering ordering,\n                                                                 const SobolRsg::DirectionIntegers directionIntegers) {\n    switch (s) {\n    case MersenneTwister:\n        return boost::make_shared<QuantExt::MultiPathGeneratorMersenneTwister>(process, timeGrid, seed, false);\n    case MersenneTwisterAntithetic:\n        return boost::make_shared<QuantExt::MultiPathGeneratorMersenneTwister>(process, timeGrid, seed, true);\n    case Sobol:\n        return boost::make_shared<QuantExt::MultiPathGeneratorSobol>(process, timeGrid, seed, directionIntegers);\n    case SobolBrownianBridge:\n        return boost::make_shared<QuantExt::MultiPathGeneratorSobolBrownianBridge>(process, timeGrid, ordering, seed,\n                                                                                   directionIntegers);\n    default:\n        QL_FAIL(\"Unknown sequence type\");\n    }\n}\n\nstd::ostream& operator<<(std::ostream& out, const SequenceType s) {\n    switch (s) {\n    case MersenneTwister:\n        return out << \"MersenneTwister\";\n    case MersenneTwisterAntithetic:\n        return out << \"MersenneTwisterAntithetic\";\n    case Sobol:\n        return out << \"Sobol\";\n    case SobolBrownianBridge:\n        return out << \"SobolBrownianBridge\";\n    default:\n        return out << \"Unknown sequence type\";\n    }\n}\n\n} // namespace QuantExt\n", "meta": {"hexsha": "b7141b13d3ea6959f6d82016b3e39681413bdb10", "size": 5379, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/methods/multipathgeneratorbase.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/methods/multipathgeneratorbase.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/methods/multipathgeneratorbase.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.7317073171, "max_line_length": 120, "alphanum_fraction": 0.6609035137, "num_tokens": 1259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.25598374265404206}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation>\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 <iostream>\n\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n\n#include \"detail/r1cs_examples.hpp\"\n#include \"detail/sha256_component.hpp\"\n\n#include <nil/crypto3/algebra/curves/bls12.hpp>\n#include <nil/crypto3/algebra/fields/bls12/base_field.hpp>\n#include <nil/crypto3/algebra/fields/bls12/scalar_field.hpp>\n#include <nil/crypto3/algebra/fields/arithmetic_params/bls12.hpp>\n#include <nil/crypto3/algebra/curves/params/multiexp/bls12.hpp>\n#include <nil/crypto3/algebra/curves/params/wnaf/bls12.hpp>\n\n#include <nil/crypto3/zk/components/blueprint.hpp>\n#include <nil/crypto3/zk/components/blueprint_variable.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 <nil/crypto3/zk/snark/algorithms/generate.hpp>\n#include <nil/crypto3/zk/snark/algorithms/verify.hpp>\n#include <nil/crypto3/zk/snark/algorithms/prove.hpp>\n\n#include <nil/marshalling/status_type.hpp>\n\nusing namespace nil::crypto3;\nusing namespace nil::crypto3::zk;\n\ntypedef algebra::curves::bls12<381> curve_type;\ntypedef typename curve_type::scalar_field_type field_type;\n\ntypedef zk::snark::r1cs_gg_ppzksnark<curve_type> scheme_type;\n\nint main(int argc, char *argv[]) {\n    boost::filesystem::path pout, pkout, vkout, piout, viout;\n    boost::program_options::options_description options(\n        \"R1CS Generic Group PreProcessing Zero-Knowledge Succinct Non-interactive ARgument of Knowledge \"\n        \"(https://eprint.iacr.org/2016/260.pdf) CLI Proof Generator\");\n    // clang-format off\n    options.add_options()(\"help,h\", \"Display help message\")\n    (\"version,v\", \"Display version\")\n    (\"generate\", \"Generate proofs and/or keys\")\n    (\"verify\", \"verify proofs and/or keys\")\n    (\"proof-output,po\", boost::program_options::value<boost::filesystem::path>(&pout)->default_value(\"proof\"))\n    (\"primary-input-output,pio\", boost::program_options::value<boost::filesystem::path>(&piout)->default_value\n(\"pinput\"))\n    (\"proving-key-output,pko\", boost::program_options::value<boost::filesystem::path>(&pkout)->default_value(\"pkey\"))\n    (\"verifying-key-output,vko\", boost::program_options::value<boost::filesystem::path>(&viout)->default_value(\"vkey\"))\n    (\"verifier-input-output,vio\", boost::program_options::value<boost::filesystem::path>(&vkout)->default_value(\"vio\"));\n    // clang-format on\n\n    boost::program_options::variables_map vm;\n    boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(options).run(), vm);\n    boost::program_options::notify(vm);\n\n    if (vm.count(\"help\") || argc < 2) {\n        std::cout << options << std::endl;\n        return 0;\n    }\n\n    std::cout << \"SHA2-256 blueprint generation started.\" << std::endl;\n\n    components::blueprint<field_type> bp = sha2_two_to_one_bp<field_type>();\n\n    std::cout << \"SHA2-256 blueprint generation finished.\" << std::endl;\n\n    std::cout << \"R1CS generation started.\" << std::endl;\n\n    r1cs_example<field_type> example =\n        r1cs_example<field_type>(bp.get_constraint_system(), bp.primary_input(), bp.auxiliary_input());\n\n    std::cout << \"R1CS generation finished.\" << std::endl;\n\n    // const bool bit = run_r1cs_gg_ppzksnark<curve_type>(example);\n\n    // zk::snark::detail::r1cs_example<field_type> example =\n    //     zk::snark::detail::r1cs_example<field_type>(bp.get_constraint_system(), bp.primary_input(),\n    //     bp.auxiliary_input());\n\n    // zk::snark::r1cs_constraint_system<field_type> constraint_system = bp.get_constraint_system();\n\n    std::cout << \"Starting generator\" << std::endl;\n\n    typename scheme_type::keypair_type keypair = zk::snark::generate<scheme_type>(example.constraint_system);\n\n    std::cout << \"Starting prover\" << std::endl;\n\n    const typename scheme_type::proof_type proof =\n        prove<scheme_type>(keypair.first, example.primary_input, example.auxiliary_input);\n\n    // std::cout << \"Starting verifier\" << std::endl;\n\n    // const bool ans = verify<basic_proof_system>(keypair.second, example.primary_input, proof);\n\n    // std::cout << \"Verifier finished, result: \" << ans << std::endl;\n\n    std::vector<std::uint8_t> proving_key_byteblob =\n        nil::marshalling::verifier_input_serializer_tvm<scheme_type>::process(keypair.first);\n    std::vector<std::uint8_t> verification_key_byteblob =\n        nil::marshalling::verifier_input_serializer_tvm<scheme_type>::process(keypair.second);\n    std::vector<std::uint8_t> proof_byteblob =\n        nil::marshalling::verifier_input_serializer_tvm<scheme_type>::process(proof);\n    std::vector<std::uint8_t> primary_input_byteblob =\n        nil::marshalling::verifier_input_serializer_tvm<scheme_type>::process(example.primary_input);\n\n    if (vm.count(\"proving-key-output\")) {\n        boost::filesystem::ofstream out(pkout);\n        for (const auto &v : proving_key_byteblob) {\n            out << v;\n        }\n        out.close();\n    }\n\n    if (vm.count(\"verifying-key-output\")) {\n        boost::filesystem::ofstream out(vkout);\n        for (const auto &v : verification_key_byteblob) {\n            out << v;\n        }\n        out.close();\n    }\n\n    if (vm.count(\"proof-output\")) {\n        boost::filesystem::ofstream out(pout);\n        for (const auto &v : proof_byteblob) {\n            out << v;\n        }\n        out.close();\n    }\n\n    if (vm.count(\"primary-input-output\")) {\n        boost::filesystem::ofstream out(piout);\n        for (const auto &v : primary_input_byteblob) {\n            out << v;\n        }\n        out.close();\n    }\n\n    // nil::marshalling::status_type provingProcessingStatus = nil::marshalling::status_type::success;\n    // typename scheme_type::proving_key_type other =\n    //             nil::marshalling::verifier_input_deserializer_tvm<scheme_type>::proving_key_process(\n    //                 proving_key_byteblob.cbegin(),\n    //                 proving_key_byteblob.cend(),\n    //                 provingProcessingStatus);\n\n    // assert(keypair.first == other);\n\n    if (vm.count(\"verifier-input-output\")) {\n        std::vector<std::uint8_t> verifier_input_output_byteblob(proof_byteblob.begin(), proof_byteblob.end());\n\n        verifier_input_output_byteblob.insert(verifier_input_output_byteblob.end(), primary_input_byteblob.begin(),\n                                              primary_input_byteblob.end());\n        verifier_input_output_byteblob.insert(verifier_input_output_byteblob.end(), verification_key_byteblob.begin(),\n                                              verification_key_byteblob.end());\n\n        boost::filesystem::ofstream poutf(pout);\n        for (const auto &v : verifier_input_output_byteblob) {\n            poutf << v;\n        }\n        poutf.close();\n    }\n\n    return 0;\n}", "meta": {"hexsha": "fa5090510d81639258ab951b2a0d00bef2b73b46", "size": 7604, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/zk/r1cs_gg_ppzksnark.cpp", "max_stars_repo_name": "NilFoundation/crypto3-marshalling", "max_stars_repo_head_hexsha": "e146a03448b1e6f49490ecb9ae54280211597d22", "max_stars_repo_licenses": ["MIT"], "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/zk/r1cs_gg_ppzksnark.cpp", "max_issues_repo_name": "NilFoundation/crypto3-marshalling", "max_issues_repo_head_hexsha": "e146a03448b1e6f49490ecb9ae54280211597d22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-07-04T18:29:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-05T18:49:38.000Z", "max_forks_repo_path": "test/zk/r1cs_gg_ppzksnark.cpp", "max_forks_repo_name": "NilFoundation/crypto3-marshalling", "max_forks_repo_head_hexsha": "e146a03448b1e6f49490ecb9ae54280211597d22", "max_forks_repo_licenses": ["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.7802197802, "max_line_length": 120, "alphanum_fraction": 0.6739873751, "num_tokens": 1829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.25587326324589693}}
{"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//   IR = infrared\n//   SFG = sum-frequency generation\n\n#include <complex>\n#include <cmath>\n#include <armadillo>\n#include \"z_histogram.hpp\"\n#include \"z_atom_group.hpp\"\n#include \"z_molecule_group.hpp\"\n#include \"z_cx_tcf.hpp\"\n#include \"z_conversions.hpp\"\n#ifndef _Z_FREQUENCY_MAP_HPP_\n#define _Z_FREQUENCY_MAP_HPP_\n\nenum Chromophore {kOH, kOD};\nenum ModelType {kThreeSite, kFourSite};\n\nclass FrequencyMap {\n public:\n  inline FrequencyMap(const MoleculeGroup& water_group,\n                      const Chromophore chromophore, const double timestep,\n                      const int correlation_length = 200)\n      : step_(0), correlation_length_(correlation_length),\n        num_chromophores_(2*water_group.num_molecules()),\n        chromophore_(chromophore), timestep_(timestep), frequency_bins_(4000),\n        min_frequency_(chromophore == kOH ? 1650.0 : 850.0),\n        max_frequency_(chromophore == kOH ? 4950.0 : 4150.0),\n        frequency_distribution_(frequency_bins_, min_frequency_,\n                                max_frequency_),\n        spectral_density_(frequency_bins_, min_frequency_, max_frequency_),\n        spectra_tcf_(correlation_length,timestep_, 1,\n                    (4096+2)/2-correlation_length) {\n    steps_guess_ = 1000;\n    omega_01_ = arma::zeros<arma::mat>(num_chromophores_, steps_guess_);\n\n    switch(chromophore) {\n      case kOH:\n        SetupOH();\n        break;\n      case kOD:\n        SetupOD();\n        break;\n      default:\n        assert(false && \"Unrecognized chromophore option.\");\n        break;\n    }\n    switch(water_group.size()/water_group.num_molecules()) {\n      case 3:\n        model_type_ = kThreeSite;\n        break;\n      case 4:\n        model_type_ = kFourSite;\n        break;\n      default:\n        assert(false && \"Number of atoms in water model is not one 3 or 4.\");\n        break;\n    }\n  }\n\n  inline void CalculateFrequencies(const MoleculeGroup& hydrogen_group,\n                                   const AtomGroup& oxygen_group,\n                                   const arma::rowvec& box) {\n    if(step_ == steps_guess_) {\n      steps_guess_ += kStepsGuessIncrement_;\n      ResizeArrays();\n    }\n    for (int i_chrom = 0; i_chrom < hydrogen_group.size(); ++i_chrom) {\n      int i_oxygen = i_chrom/2;\n      oh_vector_ =\n          hydrogen_group.position(i_chrom) - oxygen_group.position(i_oxygen);\n      oh_unit_vector_ = arma::normalise(oh_vector_);\n      field_projection_ =\n          arma::dot(oh_vector_, hydrogen_group.electric_field(i_chrom))*\n          AU_TO_NM*AU_TO_NM;\n      transition_dipole_position_ = oxygen_group.position(i_oxygen) +\n                                    transition_dipole_shift_*oh_vector_;\n      UseMapping(i_chrom, box);\n      frequency_distribution_.Add(omega_01_(i_chrom));\n      double spectral_density_weight = SpectralDensityWeight(i_chrom);\n      spectral_density_.Add(omega_01_(i_chrom), spectral_density_weight);\n    }\n    step_++;\n  }\n\n  inline void CalculateSpectra() {\n    // Two mean functions needed because of armadillo convention.\n    avg_frequency_ = arma::mean(arma::mean(omega_01_));\n    omega_01_ -= avg_frequency_;\n    int num_corr = spectra_tcf_.CalculateNumCorr(step_);\n    std::complex<double> exp_argument, exp_omega;\n    for (int i_chrom = 0; i_chrom < num_chromophores_; ++i_chrom) {\n      for (int i_num = 0; i_num < num_corr; ++i_num) {\n        int corr_start = i_num*spectra_tcf_.interval();\n        double omega_integral = 0.0;\n        exp_argument = -1.0i*omega_integral;\n        exp_omega = std::exp(exp_argument);\n        double mu_or_alpha_product =\n            MuOrAlphaProduct(i_chrom, corr_start, 0);\n        spectra_tcf_.AddTCF(0,mu_or_alpha_product*exp_omega);\n        for (int i_corr = 1; i_corr < correlation_length_; ++i_corr) {\n          omega_integral += timestep_/2.0*TWO_PI_C *\n                            (omega_01_(i_chrom,corr_start+i_corr)\n                             +omega_01_(i_chrom,corr_start));\n          exp_argument = -1.0i*omega_integral;\n          exp_omega = std::exp(exp_argument);\n          mu_or_alpha_product =\n              MuOrAlphaProduct(i_chrom, corr_start, i_corr);\n          spectra_tcf_.AddTCF(i_corr,mu_or_alpha_product*exp_omega);\n        }\n      }\n    }\n    for (int i_corr = 0; i_corr < correlation_length_; ++i_corr)\n      spectra_tcf_.MultiplyTCF(std::exp(-i_corr*timestep_/2.0/lifetime_));\n    spectra_tcf_.FourierPlus();\n  }\n\n  inline void PrintSpectra(const std::string& filename) {\n    spectra_tcf_.PrintFTReal(filename, avg_frequency_);\n  }\n\n  //accessors\n  inline int num_chromophores() const { return num_chromophores_; }\n\n protected:\n  int step_;\n  static const double mu_prime_0_ = 0.1646;\n  static const double mu_prime_1_ = 11.39;\n  static const double mu_prime_2_ = 63.41;\n  int steps_guess_;\n  static const int kStepsGuessIncrement_ = 1000;\n  arma::mat omega_01_;\n  arma::cube mu_01_;\n  arma::rowvec transition_dipole_position_;\n  arma::rowvec oh_unit_vector_;\n  double field_projection_;\n  double omega_01_0_;\n  double omega_01_1_;\n  double omega_01_2_;\n  double chi_01_0_;\n  double chi_01_1_;\n\n  inline double SpectralDensityWeight(const int chromophore) {\n    return MuOrAlphaProduct(chromophore, step_, 0);\n  }\n\n private:\n  double avg_frequency_;\n  double lifetime_;\n  int correlation_length_;\n  double num_chromophores_;\n  static const double transition_dipole_shift_ = 0.067; // Formerly dipPos\n  Chromophore chromophore_;\n  double timestep_;\n  int frequency_bins_;\n  double min_frequency_;\n  double max_frequency_;\n  ModelType model_type_;\n  arma::mat alpha_;\n  arma::mat switcher_;\n  //arma::cube u; // needed for coupled spectra\n  arma::rowvec oh_vector_;\n  Histogram frequency_distribution_;\n  Histogram spectral_density_;\n  CxTCF spectra_tcf_;\n\n  virtual void ResizeArrays() = 0;\n\n  virtual double MuOrAlphaProduct(const int chromophore, const int corr_start,\n                                  const int i_corr) = 0;\n\n  inline void SetupOH() {\n    lifetime_ = 0.700; //TODO(Zak): change this for coupled spectra\n    omega_01_0_ = 3760.2;\n    omega_01_1_ = -3541.7;\n    omega_01_2_ = -152677.0;\n    chi_01_0_ = 0.19285;\n    chi_01_1_ = -1.7261E-5;\n  }\n\n  inline void SetupOD() {\n    lifetime_ = 1.800; //TODO(Zak): change this for coupled spectra\n    omega_01_0_ = 2767.8;\n    omega_01_1_ = -2630.3;\n    omega_01_2_ = -102601.0;\n    chi_01_0_ = 0.16593;\n    chi_01_1_ = -2.0632E-5;\n  }\n\n  // Calculates omega and mu/alpha using the frequency maps.\r\n  virtual void UseMapping(const int chromophore,\n                  const arma::rowvec& box) = 0;\n\n  // TODO(Zak): Move this to a coupled spectra class\n  // Calculates the intramolecular coupling between OH groups for inclusion\n  // in the system Hamiltonian needed for coupled spectra calculations\r\n  //extern double IntraCouple();\n\n  // TODO(Zak): Move this to a coupled spectra class\n  // Calculates the intermolecular coupling between OH groups for inclusion\n  // in the system Hamiltonian needed for coupled spectra calculations\r\n  //extern void InterCouple(arma::rowvec& omega, const arma::mat& xdipole,\n  //                        const arma::rowvec& chi01, const arma::rowvec& muprime,\n  //                        const arma::mat& u, const arma::rowvec& box,\n  //                        const arma::icube& shift, const int numMols,\n  //                        const int numChromos);\n};\n#endif\n", "meta": {"hexsha": "ee3dc9ea5301e12f13615f3f2f1ec9f3598849b3", "size": 8823, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/z_frequency_map.hpp", "max_stars_repo_name": "thekannman/z_sfg", "max_stars_repo_head_hexsha": "312b04283b10c8c32e5b0adeed6d9e5959faa1c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-06-11T19:36:58.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-28T12:58:31.000Z", "max_issues_repo_path": "include/z_frequency_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_frequency_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": 37.0714285714, "max_line_length": 83, "alphanum_fraction": 0.680494163, "num_tokens": 2277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.25587325714827586}}
{"text": "/*\n * This file is part of a C++ interface to the Radiative Transfer for Energetics (RTE)\n * and Rapid Radiative Transfer Model for GCM applications Parallel (RRTMGP).\n *\n * The original code is found at https://github.com/RobertPincus/rte-rrtmgp.\n *\n * Contacts: Robert Pincus and Eli Mlawer\n * email: rrtmgp@aer.com\n *\n * Copyright 2015-2020,  Atmospheric and Environmental Research and\n * Regents of the University of Colorado.  All right reserved.\n *\n * This C++ interface can be downloaded from https://github.com/Chiil/rrtmgp_cpp\n *\n * Contact: Chiel van Heerwaarden\n * email: chiel.vanheerwaarden@wur.nl\n *\n * Copyright 2020, Wageningen University & Research.\n *\n * Use and duplication is permitted under the terms of the\n * BSD 3-clause license, see http://opensource.org/licenses/BSD-3-Clause\n *\n */\n\n#include <cmath>\n#include <numeric>\n#include <boost/algorithm/string.hpp>\n// #include <xtensor/xarray.hpp>\n// #include <xtensor/xadapt.hpp>\n// #include \"xtensor/xnoalias.hpp\"\n\n#include \"Gas_concs.h\"\n#include \"Gas_optics.h\"\n#include \"Array.h\"\n#include \"Optical_props.h\"\n#include \"Source_functions.h\"\n\n#include \"rrtmgp_kernels.h\"\n#define restrict __restrict__\n\nnamespace\n{\n    int find_index(\n            const Array<std::string,1>& data, const std::string& value)\n    {\n        auto it = std::find(data.v().begin(), data.v().end(), value);\n        if (it == data.v().end())\n            return -1;\n        else\n            return it - data.v().begin() + 1;\n    }\n\n    template<typename TF>\n    void reduce_minor_arrays(\n                const Gas_concs<TF>& available_gases,\n                const Array<std::string,1>& gas_names,\n                const Array<std::string,1>& gas_minor,\n                const Array<std::string,1>& identifier_minor,\n                const Array<TF,3>& kminor_atm,\n                const Array<std::string,1>& minor_gases_atm,\n                const Array<int,2>& minor_limits_gpt_atm,\n                const Array<int,1>& minor_scales_with_density_atm, // CvH: logical bool or int?\n                const Array<std::string,1>& scaling_gas_atm,\n                const Array<int,1>& scale_by_complement_atm, // CvH: bool or int\n                const Array<int,1>& kminor_start_atm,\n\n                Array<TF,3>& kminor_atm_red,\n                Array<std::string,1>& minor_gases_atm_red,\n                Array<int,2>& minor_limits_gpt_atm_red,\n                Array<int,1>& minor_scales_with_density_atm_red, // CvH bool or int\n                Array<std::string,1>& scaling_gas_atm_red,\n                Array<int,1>& scale_by_complement_atm_red,\n                Array<int,1>& kminor_start_atm_red)\n    {\n        int nm = minor_gases_atm.dim(1);\n        int tot_g = 0;\n\n        Array<int,1> gas_is_present({nm});\n\n        for (int i=1; i<=nm; ++i)\n        {\n            const int idx_mnr = find_index(identifier_minor, minor_gases_atm({i}));\n\n            // Search for\n            std::string gas_minor_trimmed = gas_minor({idx_mnr});\n            boost::trim(gas_minor_trimmed);\n\n            gas_is_present({i}) = available_gases.exists(gas_minor_trimmed);\n            if (gas_is_present({i}))\n                tot_g += minor_limits_gpt_atm({2,i}) - minor_limits_gpt_atm({1,i}) + 1;\n        }\n\n        const int red_nm = std::accumulate(gas_is_present.v().begin(), gas_is_present.v().end(), 0);\n\n        if (red_nm == nm)\n        {\n            kminor_atm_red = kminor_atm;\n            minor_gases_atm_red = minor_gases_atm;\n            minor_limits_gpt_atm_red = minor_limits_gpt_atm;\n            minor_scales_with_density_atm_red = minor_scales_with_density_atm;\n            scaling_gas_atm_red = scaling_gas_atm;\n            scale_by_complement_atm_red = scale_by_complement_atm;\n            kminor_start_atm_red = kminor_start_atm;\n        }\n        else\n        {\n            // Use a lambda function as the operation has to be repeated many times.\n            auto resize_and_set = [&](auto& a_red, const auto& a)\n            {\n                a_red.set_dims({red_nm});\n                int counter = 1;\n                for (int i=1; i<=gas_is_present.dim(1); ++i)\n                {\n                    if (gas_is_present({i}))\n                    {\n                       a_red({counter}) = a({i});\n                       ++counter;\n                    }\n                }\n            };\n\n            resize_and_set(minor_gases_atm_red, minor_gases_atm);\n            resize_and_set(minor_scales_with_density_atm_red, minor_scales_with_density_atm);\n            resize_and_set(scaling_gas_atm_red, scaling_gas_atm);\n            resize_and_set(scale_by_complement_atm_red, scale_by_complement_atm);\n            resize_and_set(kminor_start_atm_red, kminor_start_atm);\n\n            minor_limits_gpt_atm_red.set_dims({2, red_nm});\n            kminor_atm_red.set_dims({tot_g, kminor_atm.dim(2), kminor_atm.dim(3)});\n\n            int icnt = 0;\n            int n_elim = 0;\n            for (int i=1; i<=nm; ++i)\n            {\n                int ng = minor_limits_gpt_atm({2,i}) - minor_limits_gpt_atm({1,i}) + 1;\n                if (gas_is_present({i}))\n                {\n                    ++icnt;\n                    minor_limits_gpt_atm_red({1,icnt}) = minor_limits_gpt_atm({1,i});\n                    minor_limits_gpt_atm_red({2,icnt}) = minor_limits_gpt_atm({2,i});\n                    kminor_start_atm_red({icnt}) = kminor_start_atm({i}) - n_elim;\n\n                    for (int j=1; j<=ng; ++j)\n                        for (int i2=1; i2<=kminor_atm.dim(2); ++i2)\n                            for (int i3=1; i3<=kminor_atm.dim(3); ++i3)\n                                kminor_atm_red({kminor_start_atm_red({icnt})+j-1,i2,i3}) =\n                                        kminor_atm({kminor_start_atm({i})+j-1,i2,i3});\n                }\n                else\n                    n_elim += ng;\n            }\n        }\n    }\n\n    void create_idx_minor(\n            const Array<std::string,1>& gas_names,\n            const Array<std::string,1>& gas_minor,\n            const Array<std::string,1>& identifier_minor,\n            const Array<std::string,1>& minor_gases_atm,\n            Array<int,1>& idx_minor_atm)\n    {\n        Array<int,1> idx_minor_atm_out({minor_gases_atm.dim(1)});\n\n        for (int imnr=1; imnr<=minor_gases_atm.dim(1); ++imnr)\n        {\n            // Find identifying string for minor species in list of possible identifiers (e.g. h2o_slf)\n            const int idx_mnr = find_index(identifier_minor, minor_gases_atm({imnr}));\n\n            // Find name of gas associated with minor species identifier (e.g. h2o)\n            idx_minor_atm_out({imnr}) = find_index(gas_names, gas_minor({idx_mnr}));\n        }\n\n        idx_minor_atm = idx_minor_atm_out;\n    }\n\n    void create_idx_minor_scaling(\n            const Array<std::string,1>& gas_names,\n            const Array<std::string,1>& scaling_gas_atm,\n            Array<int,1>& idx_minor_scaling_atm)\n    {\n        Array<int,1> idx_minor_scaling_atm_out({scaling_gas_atm.dim(1)});\n\n        for (int imnr=1; imnr<=scaling_gas_atm.dim(1); ++imnr)\n            idx_minor_scaling_atm_out({imnr}) = find_index(gas_names, scaling_gas_atm({imnr}));\n\n        idx_minor_scaling_atm = idx_minor_scaling_atm_out;\n    }\n\n    void create_key_species_reduce(\n            const Array<std::string,1>& gas_names,\n            const Array<std::string,1>& gas_names_red,\n            const Array<int,3>& key_species,\n            Array<int,3>& key_species_red,\n            Array<int,1>& key_species_present_init)\n    {\n        const int np = key_species.dim(1);\n        const int na = key_species.dim(2);\n        const int nt = key_species.dim(3);\n\n        key_species_red.set_dims({key_species.dim(1), key_species.dim(2), key_species.dim(3)});\n        key_species_present_init.set_dims({gas_names.dim(1)});\n\n        for (int i=1; i<=key_species_present_init.dim(1); ++i)\n            key_species_present_init({i}) = 1;\n\n        for (int ip=1; ip<=np; ++ip)\n            for (int ia=1; ia<=na; ++ia)\n                for (int it=1; it<=nt; ++it)\n                {\n                    const int ks = key_species({ip,ia,it});\n                    if (ks != 0)\n                    {\n                        const int ksr = find_index(gas_names_red, gas_names({ks}));\n                        key_species_red({ip,ia,it}) = ksr;\n                        if (ksr == -1)\n                            key_species_present_init({ks}) = 0;\n                    }\n                    else\n                        key_species_red({ip,ia,it}) = ks;\n                }\n    }\n\n    void check_key_species_present_init(\n            const Array<std::string,1>& gas_names,\n            const Array<int,1>& key_species_present_init\n            )\n    {\n        for (int i=1; i<=key_species_present_init.dim(1); ++i)\n        {\n            if (key_species_present_init({i}) == 0)\n            {\n                std::string error_message = \"Gas optics: required gas \" + gas_names({i}) + \" is missing\";\n                throw std::runtime_error(error_message);\n            }\n        }\n    }\n\n    void create_flavor(\n            const Array<int,3>& key_species,\n            Array<int,2>& flavor)\n    {\n        Array<int,2> key_species_list({2, key_species.dim(3)*2});\n\n        // Prepare list of key species.\n        int i = 1;\n        for (int ibnd=1; ibnd<=key_species.dim(3); ++ibnd)\n            for (int iatm=1; iatm<=key_species.dim(1); ++iatm)\n            {\n                key_species_list({1,i}) = key_species({1,iatm,ibnd});\n                key_species_list({2,i}) = key_species({2,iatm,ibnd});\n                ++i;\n            }\n\n        // Rewrite single key_species pairs.\n        for (int i=1; i<=key_species_list.dim(2); ++i)\n        {\n            if ( key_species_list({1,i}) == 0 && key_species_list({2,i}) == 0 )\n            {\n                key_species_list({1,i}) = 2;\n                key_species_list({2,i}) = 2;\n            }\n        }\n\n        // Count unique key species pairs.\n        int iflavor = 0;\n        for (int i=1; i<=key_species_list.dim(2); ++i)\n        {\n            bool pair_exists = false;\n            for (int ii=1; ii<=i-1; ++ii)\n            {\n                if ( (key_species_list({1,i}) == key_species_list({1,ii})) &&\n                     (key_species_list({2,i}) == key_species_list({2,ii})) )\n                {\n                    pair_exists = true;\n                    break;\n                }\n            }\n            if (!pair_exists)\n                ++iflavor;\n        }\n\n        // Fill flavors.\n        flavor.set_dims({2,iflavor});\n        iflavor = 0;\n        for (int i=1; i<=key_species_list.dim(2); ++i)\n        {\n            bool pair_exists = false;\n            for (int ii=1; ii<=i-1; ++ii)\n            {\n                if ( (key_species_list({1,i}) == key_species_list({1,ii})) &&\n                     (key_species_list({2,i}) == key_species_list({2,ii})) )\n                {\n                    pair_exists = true;\n                    break;\n                }\n            }\n            if (!pair_exists)\n            {\n                ++iflavor;\n                flavor({1,iflavor}) = key_species_list({1,i});\n                flavor({2,iflavor}) = key_species_list({2,i});\n            }\n        }\n    }\n\n    int key_species_pair2flavor(\n            const Array<int,2>& flavor,\n            const Array<int,1>& key_species_pair)\n    {\n        // Search for match.\n        for (int iflav=1; iflav<=flavor.dim(2); ++iflav)\n        {\n            if ( key_species_pair({1}) == flavor({1, iflav}) &&\n                 key_species_pair({2}) == flavor({2, iflav}) )\n                return iflav;\n        }\n\n        // No match found.\n        return -1;\n    }\n\n    void create_gpoint_flavor(\n            const Array<int,3>& key_species,\n            const Array<int,1>& gpt2band,\n            const Array<int,2>& flavor,\n            Array<int,2>& gpoint_flavor)\n    {\n        const int ngpt = gpt2band.dim(1);\n        gpoint_flavor.set_dims({2,ngpt});\n\n        for (int igpt=1; igpt<=ngpt; ++igpt)\n            for (int iatm=1; iatm<=2; ++iatm)\n            {\n                int pair_1 = key_species( {1, iatm, gpt2band({igpt})} );\n                int pair_2 = key_species( {2, iatm, gpt2band({igpt})} );\n\n                // Rewrite species pair.\n                Array<int,1> rewritten_pair({2});\n                if (pair_1 == 0 && pair_2 == 0)\n                {\n                    rewritten_pair({1}) = 2;\n                    rewritten_pair({2}) = 2;\n                }\n                else\n                {\n                    rewritten_pair({1}) = pair_1;\n                    rewritten_pair({2}) = pair_2;\n                }\n\n                // Write the output.\n                gpoint_flavor({iatm,igpt}) = key_species_pair2flavor(\n                        flavor, rewritten_pair);\n            }\n    }\n\n    /*\n    template<typename TF>\n    inline void reorder123x321_test(\n            TF* restrict out, const TF* restrict in,\n            const int d1, const int d2, const int d3)\n    {\n        const int jj_in = d1;\n        const int kk_in = d1*d2;\n\n        const int ii_out = d3*d2;\n        const int jj_out = d3;\n\n        for (int i=0; i<d1; ++i)\n            for (int j=0; j<d2; ++j)\n                #pragma GCC ivdep\n                for (int k=0; k<d3; ++k)\n                {\n                    const int ijk_in  = i + j*jj_in  + k*kk_in ;\n                    const int ijk_out = k + j*jj_out + i*ii_out;\n                    out[ijk_out] = in[ijk_in];\n                }\n    }\n\n    template<typename TF>\n    inline void reorder123x321_test(\n            TF* out, const TF* in,\n            const size_t d1, const size_t d2, const size_t d3)\n    {\n        const size_t size = d1*d2*d3;\n        const std::array<size_t, 3> in_shape = { d1, d2, d3 };\n        const std::array<size_t, 3> out_shape = { d3, d2, d1 };\n\n        const auto a_in = xt::adapt<xt::layout_type::column_major>(in, size, xt::no_ownership(), in_shape);\n        auto a_out = xt::adapt<xt::layout_type::column_major>(out, size, xt::no_ownership(), out_shape);\n\n        xt::noalias(a_out) = xt::transpose(a_out);\n    }\n    */\n}\n\n// IMPLEMENTATION OF CLASS FUNCTIONS.\n// Constructor of longwave variant.\ntemplate<typename TF>\nGas_optics<TF>::Gas_optics(\n        const Gas_concs<TF>& available_gases,\n        const Array<std::string,1>& gas_names,\n        const Array<int,3>& key_species,\n        const Array<int,2>& band2gpt,\n        const Array<TF,2>& band_lims_wavenum,\n        const Array<TF,1>& press_ref,\n        const TF press_ref_trop,\n        const Array<TF,1>& temp_ref,\n        const TF temp_ref_p,\n        const TF temp_ref_t,\n        const Array<TF,3>& vmr_ref,\n        const Array<TF,4>& kmajor,\n        const Array<TF,3>& kminor_lower,\n        const Array<TF,3>& kminor_upper,\n        const Array<std::string,1>& gas_minor,\n        const Array<std::string,1>& identifier_minor,\n        const Array<std::string,1>& minor_gases_lower,\n        const Array<std::string,1>& minor_gases_upper,\n        const Array<int,2>& minor_limits_gpt_lower,\n        const Array<int,2>& minor_limits_gpt_upper,\n        const Array<int,1>& minor_scales_with_density_lower,\n        const Array<int,1>& minor_scales_with_density_upper,\n        const Array<std::string,1>& scaling_gas_lower,\n        const Array<std::string,1>& scaling_gas_upper,\n        const Array<int,1>& scale_by_complement_lower,\n        const Array<int,1>& scale_by_complement_upper,\n        const Array<int,1>& kminor_start_lower,\n        const Array<int,1>& kminor_start_upper,\n        const Array<TF,2>& totplnk,\n        const Array<TF,4>& planck_frac,\n        const Array<TF,3>& rayl_lower,\n        const Array<TF,3>& rayl_upper) :\n            Optical_props<TF>(band_lims_wavenum, band2gpt),\n            totplnk(totplnk),\n            planck_frac(planck_frac)\n{\n    // Initialize the absorption coefficient array, including Rayleigh scattering\n    // tables if provided.\n    init_abs_coeffs(\n            available_gases,\n            gas_names, key_species,\n            band2gpt, band_lims_wavenum,\n            press_ref, temp_ref,\n            press_ref_trop, temp_ref_p, temp_ref_t,\n            vmr_ref,\n            kmajor, kminor_lower, kminor_upper,\n            gas_minor,identifier_minor,\n            minor_gases_lower, minor_gases_upper,\n            minor_limits_gpt_lower,\n            minor_limits_gpt_upper,\n            minor_scales_with_density_lower,\n            minor_scales_with_density_upper,\n            scaling_gas_lower, scaling_gas_upper,\n            scale_by_complement_lower,\n            scale_by_complement_upper,\n            kminor_start_lower,\n            kminor_start_upper,\n            rayl_lower, rayl_upper);\n\n    // Temperature steps for Planck function interpolation.\n    // Assumes that temperature minimum and max are the same for the absorption coefficient grid and the\n    // Planck grid and the Planck grid is equally spaced.\n    totplnk_delta = (temp_ref_max - temp_ref_min) / (totplnk.dim(1)-1);\n}\n\n// Constructor of the shortwave variant.\ntemplate<typename TF>\nGas_optics<TF>::Gas_optics(\n        const Gas_concs<TF>& available_gases,\n        const Array<std::string,1>& gas_names,\n        const Array<int,3>& key_species,\n        const Array<int,2>& band2gpt,\n        const Array<TF,2>& band_lims_wavenum,\n        const Array<TF,1>& press_ref,\n        const TF press_ref_trop,\n        const Array<TF,1>& temp_ref,\n        const TF temp_ref_p,\n        const TF temp_ref_t,\n        const Array<TF,3>& vmr_ref,\n        const Array<TF,4>& kmajor,\n        const Array<TF,3>& kminor_lower,\n        const Array<TF,3>& kminor_upper,\n        const Array<std::string,1>& gas_minor,\n        const Array<std::string,1>& identifier_minor,\n        const Array<std::string,1>& minor_gases_lower,\n        const Array<std::string,1>& minor_gases_upper,\n        const Array<int,2>& minor_limits_gpt_lower,\n        const Array<int,2>& minor_limits_gpt_upper,\n        const Array<int,1>& minor_scales_with_density_lower,\n        const Array<int,1>& minor_scales_with_density_upper,\n        const Array<std::string,1>& scaling_gas_lower,\n        const Array<std::string,1>& scaling_gas_upper,\n        const Array<int,1>& scale_by_complement_lower,\n        const Array<int,1>& scale_by_complement_upper,\n        const Array<int,1>& kminor_start_lower,\n        const Array<int,1>& kminor_start_upper,\n        const Array<TF,1>& solar_source_quiet,\n        const Array<TF,1>& solar_source_facular,\n        const Array<TF,1>& solar_source_sunspot,\n        const TF tsi_default,\n        const TF mg_default,\n        const TF sb_default,\n        const Array<TF,3>& rayl_lower,\n        const Array<TF,3>& rayl_upper) :\n            Optical_props<TF>(band_lims_wavenum, band2gpt)\n{\n    // Initialize the absorption coefficient array, including Rayleigh scattering\n    // tables if provided.\n    init_abs_coeffs(\n            available_gases,\n            gas_names, key_species,\n            band2gpt, band_lims_wavenum,\n            press_ref, temp_ref,\n            press_ref_trop, temp_ref_p, temp_ref_t,\n            vmr_ref,\n            kmajor, kminor_lower, kminor_upper,\n            gas_minor,identifier_minor,\n            minor_gases_lower, minor_gases_upper,\n            minor_limits_gpt_lower,\n            minor_limits_gpt_upper,\n            minor_scales_with_density_lower,\n            minor_scales_with_density_upper,\n            scaling_gas_lower, scaling_gas_upper,\n            scale_by_complement_lower,\n            scale_by_complement_upper,\n            kminor_start_lower,\n            kminor_start_upper,\n            rayl_lower, rayl_upper);\n\n    // Compute the solar source.\n    this->solar_source_quiet = solar_source_quiet;\n    this->solar_source_facular = solar_source_facular;\n    this->solar_source_sunspot = solar_source_sunspot;\n\n    this->solar_source.set_dims(solar_source_quiet.get_dims());\n\n    set_solar_variability(mg_default, sb_default);\n}\n\ntemplate<typename TF>\nvoid Gas_optics<TF>::init_abs_coeffs(\n        const Gas_concs<TF>& available_gases,\n        const Array<std::string,1>& gas_names,\n        const Array<int,3>& key_species,\n        const Array<int,2>& band2gpt,\n        const Array<TF,2>& band_lims_wavenum,\n        const Array<TF,1>& press_ref,\n        const Array<TF,1>& temp_ref,\n        const TF press_ref_trop,\n        const TF temp_ref_p,\n        const TF temp_ref_t,\n        const Array<TF,3>& vmr_ref,\n        const Array<TF,4>& kmajor,\n        const Array<TF,3>& kminor_lower,\n        const Array<TF,3>& kminor_upper,\n        const Array<std::string,1>& gas_minor,\n        const Array<std::string,1>& identifier_minor,\n        const Array<std::string,1>& minor_gases_lower,\n        const Array<std::string,1>& minor_gases_upper,\n        const Array<int,2>& minor_limits_gpt_lower,\n        const Array<int,2>& minor_limits_gpt_upper,\n        const Array<int,1>& minor_scales_with_density_lower,\n        const Array<int,1>& minor_scales_with_density_upper,\n        const Array<std::string,1>& scaling_gas_lower,\n        const Array<std::string,1>& scaling_gas_upper,\n        const Array<int,1>& scale_by_complement_lower,\n        const Array<int,1>& scale_by_complement_upper,\n        const Array<int,1>& kminor_start_lower,\n        const Array<int,1>& kminor_start_upper,\n        const Array<TF,3>& rayl_lower,\n        const Array<TF,3>& rayl_upper)\n{\n    // Which gases known to the gas optics are present in the host model (available_gases)?\n    std::vector<std::string> gas_names_to_use;\n\n    for (const std::string &s : gas_names.v())\n    {\n        if (available_gases.exists(s))\n            gas_names_to_use.push_back(s);\n    }\n\n    // Now the number of gases is the union of those known to the k-distribution and provided\n    // by the host model.\n    const int n_gas = gas_names_to_use.size();\n    Array<std::string,1> gas_names_this(std::move(gas_names_to_use), {n_gas});\n    this->gas_names = gas_names_this;\n\n    // Initialize the gas optics object, keeping only those gases known to the\n    // gas optics and also present in the host model.\n    // Add an offset to the indexing to interface the negative ranging of fortran.\n    Array<TF,3> vmr_ref_red({vmr_ref.dim(1), n_gas + 1, vmr_ref.dim(3)});\n    vmr_ref_red.set_offsets({0, -1, 0});\n\n    // Gas 0 is used in single-key species method, set to 1.0 (col_dry)\n    for (int i1=1; i1<=vmr_ref_red.dim(1); ++i1)\n        for (int i3=1; i3<=vmr_ref_red.dim(3); ++i3)\n            vmr_ref_red({i1, 0, i3}) = vmr_ref({i1, 1, i3});\n\n    for (int i=1; i<=n_gas; ++i)\n    {\n        int idx = find_index(gas_names, this->gas_names({i}));\n        for (int i1=1; i1<=vmr_ref_red.dim(1); ++i1)\n            for (int i3=1; i3<=vmr_ref_red.dim(3); ++i3)\n                vmr_ref_red({i1, i, i3}) = vmr_ref({i1, idx+1, i3}); // CvH: why +1?\n    }\n\n    this->vmr_ref = std::move(vmr_ref_red);\n\n    // Reduce minor arrays so variables only contain minor gases that are available.\n    // Reduce size of minor Arrays.\n    Array<std::string, 1> minor_gases_lower_red;\n    Array<std::string, 1> scaling_gas_lower_red;\n    Array<std::string, 1> minor_gases_upper_red;\n    Array<std::string, 1> scaling_gas_upper_red;\n\n    reduce_minor_arrays(\n            available_gases,\n            gas_names,\n            gas_minor, identifier_minor,\n            kminor_lower,\n            minor_gases_lower,\n            minor_limits_gpt_lower,\n            minor_scales_with_density_lower,\n            scaling_gas_lower,\n            scale_by_complement_lower,\n            kminor_start_lower,\n            this->kminor_lower,\n            minor_gases_lower_red,\n            this->minor_limits_gpt_lower,\n            this->minor_scales_with_density_lower,\n            scaling_gas_lower_red,\n            this->scale_by_complement_lower,\n            this->kminor_start_lower);\n\n    reduce_minor_arrays(\n            available_gases,\n            gas_names,\n            gas_minor,\n            identifier_minor,\n            kminor_upper,\n            minor_gases_upper,\n            minor_limits_gpt_upper,\n            minor_scales_with_density_upper,\n            scaling_gas_upper,\n            scale_by_complement_upper,\n            kminor_start_upper,\n            this->kminor_upper,\n            minor_gases_upper_red,\n            this->minor_limits_gpt_upper,\n            this->minor_scales_with_density_upper,\n            scaling_gas_upper_red,\n            this->scale_by_complement_upper,\n            this->kminor_start_upper);\n\n    // Arrays not reduced by the presence, or lack thereof, of a gas\n    this->press_ref = press_ref;\n    this->temp_ref = temp_ref;\n    this->kmajor = kmajor;\n\n    // Create a new vector that consists of rayl_lower and rayl_upper stored in one variable.\n    if (rayl_lower.size() > 0)\n    {\n        this->krayl.set_dims({rayl_lower.dim(1), rayl_lower.dim(2), rayl_lower.dim(3), 2});\n        for (int i=0; i<rayl_lower.size(); ++i)\n        {\n            this->krayl.v()[i                    ] = rayl_lower.v()[i];\n            this->krayl.v()[i + rayl_lower.size()] = rayl_upper.v()[i];\n        }\n    }\n\n    // ---- post processing ----\n    //  creates log reference pressure\n    this->press_ref_log = this->press_ref;\n    for (int i1=1; i1<=this->press_ref_log.dim(1); ++i1)\n        this->press_ref_log({i1}) = std::log(this->press_ref_log({i1}));\n\n    // log scale of reference pressure\n    this->press_ref_trop_log = std::log(press_ref_trop);\n\n    // Get index of gas (if present) for determining col_gas\n    create_idx_minor(\n            this->gas_names, gas_minor, identifier_minor, minor_gases_lower_red, this->idx_minor_lower);\n    create_idx_minor(\n            this->gas_names, gas_minor, identifier_minor, minor_gases_upper_red, this->idx_minor_upper);\n\n    // Get index of gas (if present) that has special treatment in density scaling\n    create_idx_minor_scaling(\n            this->gas_names, scaling_gas_lower_red, this->idx_minor_scaling_lower);\n    create_idx_minor_scaling(\n            this->gas_names, scaling_gas_upper_red, this->idx_minor_scaling_upper);\n\n    // Create flavor list.\n    // Reduce (remap) key_species list; checks that all key gases are present in incoming\n    Array<int, 3> key_species_red;\n    Array<int, 1> key_species_present_init; // CvH bool or int?\n\n    create_key_species_reduce(\n            gas_names, this->gas_names, key_species, key_species_red, key_species_present_init);\n\n    check_key_species_present_init(gas_names, key_species_present_init);\n\n    // create flavor list\n    create_flavor(key_species_red, this->flavor);\n\n    // create gpoint flavor list\n    create_gpoint_flavor(\n            key_species_red, this->get_gpoint_bands(), this->flavor, this->gpoint_flavor);\n\n    // minimum, maximum reference temperature, pressure -- assumes low-to-high ordering\n    // for T, high-to-low ordering for p\n    this->temp_ref_min = this->temp_ref({1});\n    this->temp_ref_max = this->temp_ref({temp_ref.dim(1)});\n    this->press_ref_min = this->press_ref({press_ref.dim(1)});\n    this->press_ref_max = this->press_ref({1});\n\n    // creates press_ref_log, temp_ref_delta\n    this->press_ref_log_delta =\n            (std::log(this->press_ref_min) - std::log(this->press_ref_max)) / (this->press_ref.dim(1) - 1);\n    this->temp_ref_delta = (this->temp_ref_max - this->temp_ref_min) / (this->temp_ref.dim(1) - 1);\n\n    // Which species are key in one or more bands?\n    // this->flavor is an index into this->gas_names\n    // if (allocated(this%is_key)) deallocate(this%is_key) ! Shouldn't ever happen...\n    Array<int,1> is_key({get_ngas()}); // CvH bool, defaults to 0.?\n\n    for (int j=1; j<=this->flavor.dim(2); ++j)\n        for (int i=1; i<=this->flavor.dim(1); ++i)\n        {\n            if (this->flavor({i, j}) != 0)\n                is_key({this->flavor({i, j})}) = true;\n        }\n\n    this->is_key = is_key;\n}\n\ntemplate<typename TF>\nvoid Gas_optics<TF>::set_solar_variability(\n        const TF mg_index, const TF sb_index)\n{\n    constexpr TF a_offset = TF(0.1495954);\n    constexpr TF b_offset = TF(0.00066696);\n\n    for (int igpt=1; igpt<=this->solar_source_quiet.dim(1); ++igpt)\n    {\n        this->solar_source({igpt}) = this->solar_source_quiet({igpt})\n                + (mg_index - a_offset) * this->solar_source_facular({igpt})\n                + (sb_index - b_offset) * this->solar_source_sunspot({igpt});\n    }\n\n    // Scale solar source to input TSI value\n    // if (present(tsi)) error_msg = this%set_tsi(tsi)\n}\n\n\n// Calculate the molecules of dry air.\ntemplate<typename TF>\nvoid Gas_optics<TF>::get_col_dry(\n        Array<TF,2>& col_dry, const Array<TF,2>& vmr_h2o,\n        const Array<TF,2>& plev)\n{\n    // CvH: RRTMGP uses more accurate method based on latitude.\n    constexpr TF g0 = 9.80665;\n\n    constexpr TF avogad = 6.02214076e23;\n    constexpr TF m_dry = 0.028964;\n    constexpr TF m_h2o = 0.018016;\n\n    Array<double,2> delta_plev({col_dry.dim(1), col_dry.dim(2)});\n    Array<double,2> m_air     ({col_dry.dim(1), col_dry.dim(2)});\n\n    for (int ilay=1; ilay<=col_dry.dim(2); ++ilay)\n        for (int icol=1; icol<=col_dry.dim(1); ++icol)\n            delta_plev({icol, ilay}) = std::abs(plev({icol, ilay}) - plev({icol, ilay+1}));\n\n    for (int ilay=1; ilay<=col_dry.dim(2); ++ilay)\n        for (int icol=1; icol<=col_dry.dim(1); ++icol)\n            m_air({icol, ilay}) = (m_dry + m_h2o * vmr_h2o({icol, ilay})) / (1. + vmr_h2o({icol, ilay}));\n\n    for (int ilay=1; ilay<=col_dry.dim(2); ++ilay)\n        for (int icol=1; icol<=col_dry.dim(1); ++icol)\n        {\n            col_dry({icol, ilay}) = TF(10.) * delta_plev({icol, ilay}) * avogad / (TF(1000.)*m_air({icol, ilay})*TF(100.)*g0);\n            col_dry({icol, ilay}) /= (TF(1.) + vmr_h2o({icol, ilay}));\n        }\n}\n\n// Gas optics solver longwave variant.\ntemplate<typename TF>\nvoid Gas_optics<TF>::gas_optics(\n        const Array<TF,2>& play,\n        const Array<TF,2>& plev,\n        const Array<TF,2>& tlay,\n        const Array<TF,1>& tsfc,\n        const Gas_concs<TF>& gas_desc,\n        std::unique_ptr<Optical_props_arry<TF>>& optical_props,\n        Source_func_lw<TF>& sources,\n        const Array<TF,2>& col_dry,\n        const Array<TF,2>& tlev) const\n{\n    const int ncol = play.dim(1);\n    const int nlay = play.dim(2);\n    const int ngpt = this->get_ngpt();\n    const int nband = this->get_nband();\n\n    Array<int,2> jtemp({play.dim(1), play.dim(2)});\n    Array<int,2> jpress({play.dim(1), play.dim(2)});\n    Array<int,2> tropo({play.dim(1), play.dim(2)});\n    Array<TF,6> fmajor({2, 2, 2, this->get_nflav(), play.dim(1), play.dim(2)});\n    Array<int,4> jeta({2, this->get_nflav(), play.dim(1), play.dim(2)});\n\n    // Gas optics.\n    compute_gas_taus(\n            ncol, nlay, ngpt, nband,\n            play, plev, tlay, gas_desc,\n            optical_props,\n            jtemp, jpress, jeta, tropo, fmajor,\n            col_dry);\n\n    // External sources.\n    source(\n            ncol, nlay, nband, ngpt,\n            play, plev, tlay, tsfc,\n            jtemp, jpress, jeta, tropo, fmajor,\n            sources, tlev);\n}\n\n// Gas optics solver shortwave variant.\ntemplate<typename TF>\nvoid Gas_optics<TF>::gas_optics(\n        const Array<TF,2>& play,\n        const Array<TF,2>& plev,\n        const Array<TF,2>& tlay,\n        const Gas_concs<TF>& gas_desc,\n        std::unique_ptr<Optical_props_arry<TF>>& optical_props,\n        Array<TF,2>& toa_src,\n        const Array<TF,2>& col_dry) const\n{\n    const int ncol = play.dim(1);\n    const int nlay = play.dim(2);\n    const int ngpt = this->get_ngpt();\n    const int nband = this->get_nband();\n\n    Array<int,2> jtemp({play.dim(1), play.dim(2)});\n    Array<int,2> jpress({play.dim(1), play.dim(2)});\n    Array<int,2> tropo({play.dim(1), play.dim(2)});\n    Array<TF,6> fmajor({2, 2, 2, this->get_nflav(), play.dim(1), play.dim(2)});\n    Array<int,4> jeta({2, this->get_nflav(), play.dim(1), play.dim(2)});\n\n    // Gas optics.\n    compute_gas_taus(\n            ncol, nlay, ngpt, nband,\n            play, plev, tlay, gas_desc,\n            optical_props,\n            jtemp, jpress, jeta, tropo, fmajor,\n            col_dry);\n\n    // External source function is constant.\n    for (int igpt=1; igpt<=ngpt; ++igpt)\n        for (int icol=1; icol<=ncol; ++icol)\n            toa_src({icol, igpt}) = this->solar_source({igpt});\n}\n\nnamespace rrtmgp_kernel_launcher\n{\n    template<typename TF> void zero_array(\n            int ni, int nj, int nk, Array<TF,3>& array)\n    {\n        rrtmgp_kernels::zero_array_3D(&ni, &nj, &nk, array.ptr());\n    }\n\n    template<typename TF> void zero_array(\n            int ni, int nj, int nk, int nl, Array<TF,4>& array)\n    {\n        rrtmgp_kernels::zero_array_4D(&ni, &nj, &nk, &nl, array.ptr());\n    }\n\n    template<typename TF>\n    void interpolation(\n            int ncol, int nlay,\n            int ngas, int nflav, int neta, int npres, int ntemp,\n            const Array<int,2>& flavor,\n            const Array<TF,1>& press_ref_log,\n            const Array<TF,1>& temp_ref,\n            TF press_ref_log_delta,\n            TF temp_ref_min,\n            TF temp_ref_delta,\n            TF press_ref_trop_log,\n            const Array<TF,3>& vmr_ref,\n            const Array<TF,2>& play,\n            const Array<TF,2>& tlay,\n            Array<TF,3>& col_gas,\n            Array<int,2>& jtemp,\n            Array<TF,6>& fmajor, Array<TF,5>& fminor,\n            Array<TF,4>& col_mix,\n            Array<int,2>& tropo,\n            Array<int,4>& jeta,\n            Array<int,2>& jpress)\n    {\n        rrtmgp_kernels::interpolation(\n                &ncol, &nlay,\n                &ngas, &nflav, &neta, &npres, &ntemp,\n                const_cast<int*>(flavor.ptr()),\n                const_cast<TF*>(press_ref_log.ptr()),\n                const_cast<TF*>(temp_ref.ptr()),\n                &press_ref_log_delta,\n                &temp_ref_min,\n                &temp_ref_delta,\n                &press_ref_trop_log,\n                const_cast<TF*>(vmr_ref.ptr()),\n                const_cast<TF*>(play.ptr()),\n                const_cast<TF*>(tlay.ptr()),\n                col_gas.ptr(),\n                jtemp.ptr(),\n                fmajor.ptr(), fminor.ptr(),\n                col_mix.ptr(),\n                tropo.ptr(),\n                jeta.ptr(),\n                jpress.ptr());\n    }\n\n    template<typename TF>\n    void compute_tau_absorption(\n            int ncol, int nlay, int nband, int ngpt,\n            int ngas, int nflav, int neta, int npres, int ntemp,\n            int nminorlower, int nminorklower,\n            int nminorupper, int nminorkupper,\n            int idx_h2o,\n            const Array<int,2>& gpoint_flavor,\n            const Array<int,2>& band_lims_gpt,\n            const Array<TF,4>& kmajor,\n            const Array<TF,3>& kminor_lower,\n            const Array<TF,3>& kminor_upper,\n            const Array<int,2>& minor_limits_gpt_lower,\n            const Array<int,2>& minor_limits_gpt_upper,\n            const Array<int,1>& minor_scales_with_density_lower,\n            const Array<int,1>& minor_scales_with_density_upper,\n            const Array<int,1>& scale_by_complement_lower,\n            const Array<int,1>& scale_by_complement_upper,\n            const Array<int,1>& idx_minor_lower,\n            const Array<int,1>& idx_minor_upper,\n            const Array<int,1>& idx_minor_scaling_lower,\n            const Array<int,1>& idx_minor_scaling_upper,\n            const Array<int,1>& kminor_start_lower,\n            const Array<int,1>& kminor_start_upper,\n            Array<int,2>& tropo,\n            Array<TF,4>& col_mix, Array<TF,6>& fmajor, Array<TF,5>& fminor,\n            const Array<TF,2>& play, const Array<TF,2>& tlay, Array<TF,3>& col_gas,\n            Array<int,4>& jeta, Array<int,2>& jtemp, Array<int,2>& jpress,\n            Array<TF,3>& tau)\n    {\n        rrtmgp_kernels::compute_tau_absorption(\n            &ncol, &nlay, &nband, &ngpt,\n            &ngas, &nflav, &neta, &npres, &ntemp,\n            &nminorlower, &nminorklower,\n            &nminorupper, &nminorkupper,\n            &idx_h2o,\n            const_cast<int*>(gpoint_flavor.ptr()),\n            const_cast<int*>(band_lims_gpt.ptr()),\n            const_cast<TF*>(kmajor.ptr()),\n            const_cast<TF*>(kminor_lower.ptr()),\n            const_cast<TF*>(kminor_upper.ptr()),\n            const_cast<int*>(minor_limits_gpt_lower.ptr()),\n            const_cast<int*>(minor_limits_gpt_upper.ptr()),\n            const_cast<int*>(minor_scales_with_density_lower.ptr()),\n            const_cast<int*>(minor_scales_with_density_upper.ptr()),\n            const_cast<int*>(scale_by_complement_lower.ptr()),\n            const_cast<int*>(scale_by_complement_upper.ptr()),\n            const_cast<int*>(idx_minor_lower.ptr()),\n            const_cast<int*>(idx_minor_upper.ptr()),\n            const_cast<int*>(idx_minor_scaling_lower.ptr()),\n            const_cast<int*>(idx_minor_scaling_upper.ptr()),\n            const_cast<int*>(kminor_start_lower.ptr()),\n            const_cast<int*>(kminor_start_upper.ptr()),\n            tropo.ptr(),\n            col_mix.ptr(), fmajor.ptr(), fminor.ptr(),\n            const_cast<TF*>(play.ptr()), const_cast<TF*>(tlay.ptr()), col_gas.ptr(),\n            jeta.ptr(), jtemp.ptr(), jpress.ptr(),\n            tau.ptr());\n    }\n\n    template<typename TF>\n    void compute_tau_rayleigh(\n            int ncol, int nlay, int nband, int ngpt,\n            int ngas, int nflav, int neta, int npres, int ntemp,\n            const Array<int,2>& gpoint_flavor,\n            const Array<int,2>& band_lims_gpt,\n            const Array<TF,4>& krayl,\n            int idx_h2o, const Array<TF,2>& col_dry, const Array<TF,3>& col_gas,\n            const Array<TF,5>& fminor, const Array<int,4>& jeta,\n            const Array<int,2>& tropo, const Array<int,2>& jtemp,\n            Array<TF,3>& tau_rayleigh)\n    {\n        rrtmgp_kernels::compute_tau_rayleigh(\n                &ncol, &nlay, &nband, &ngpt,\n                &ngas, &nflav, &neta, &npres, &ntemp,\n                const_cast<int*>(gpoint_flavor.ptr()),\n                const_cast<int*>(band_lims_gpt.ptr()),\n                const_cast<TF*>(krayl.ptr()),\n                &idx_h2o,\n                const_cast<TF*>(col_dry.ptr()), const_cast<TF*>(col_gas.ptr()),\n                const_cast<TF*>(fminor.ptr()), const_cast<int*>(jeta.ptr()),\n                const_cast<int*>(tropo.ptr()), const_cast<int*>(jtemp.ptr()),\n                tau_rayleigh.ptr());\n    }\n\n    template<typename TF>\n    void reorder123x321(\n            const Array<TF,3>& data,\n            Array<TF,3>& data_out)\n    {\n        int dim1 = data.dim(1);\n        int dim2 = data.dim(2);\n        int dim3 = data.dim(3);\n        rrtmgp_kernels::reorder_123x321_kernel(\n                &dim1, &dim2, &dim3,\n                const_cast<TF*>(data.ptr()),\n                data_out.ptr());\n    }\n\n    template<typename TF>\n    void combine_and_reorder_2str(\n            int ncol, int nlay, int ngpt,\n            const Array<TF,3>& tau_local, const Array<TF,3>& tau_rayleigh,\n            Array<TF,3>& tau, Array<TF,3>& ssa, Array<TF,3>& g)\n    {\n        rrtmgp_kernels::combine_and_reorder_2str(\n                &ncol, &nlay, &ngpt,\n                const_cast<TF*>(tau_local.ptr()), const_cast<TF*>(tau_rayleigh.ptr()),\n                tau.ptr(), ssa.ptr(), g.ptr());\n    }\n\n    template<typename TF>\n    void compute_Planck_source(\n            int ncol, int nlay, int nbnd, int ngpt,\n            int nflav, int neta, int npres, int ntemp, int nPlanckTemp,\n            const Array<TF,2>& tlay, const Array<TF,2>& tlev, const Array<TF,1>& tsfc, int sfc_lay,\n            const Array<TF,6>& fmajor, const Array<int,4>& jeta, const Array<int,2>& tropo, const Array<int,2>& jtemp, const Array<int,2>& jpress,\n            const Array<int,1>& gpoint_bands, const Array<int,2>& band_lims_gpt, const Array<TF,4>& pfracin, TF temp_ref_min,\n            TF totplnk_delta, const Array<TF,2>& totplnk, const Array<int,2>& gpoint_flavor,\n            Array<TF,2>& sfc_src, Array<TF,3>& lay_src, Array<TF,3>& lev_src_inc, Array<TF,3>& lev_src_dec,\n            Array<TF,2>& sfc_src_jac)\n    {\n        rrtmgp_kernels::compute_Planck_source(\n                &ncol, &nlay, &nbnd, &ngpt,\n                &nflav, &neta, &npres, &ntemp, &nPlanckTemp,\n                const_cast<TF*>(tlay.ptr()),\n                const_cast<TF*>(tlev.ptr()),\n                const_cast<TF*>(tsfc.ptr()),\n                &sfc_lay,\n                const_cast<TF*>(fmajor.ptr()),\n                const_cast<int*>(jeta.ptr()),\n                const_cast<int*>(tropo.ptr()),\n                const_cast<int*>(jtemp.ptr()),\n                const_cast<int*>(jpress.ptr()),\n                const_cast<int*>(gpoint_bands.ptr()), const_cast<int*>(band_lims_gpt.ptr()), const_cast<TF*>(pfracin.ptr()), &temp_ref_min,\n                &totplnk_delta, const_cast<TF*>(totplnk.ptr()), const_cast<int*>(gpoint_flavor.ptr()),\n                sfc_src.ptr(), lay_src.ptr(), lev_src_inc.ptr(), lev_src_dec.ptr(),\n                sfc_src_jac.ptr());\n    }\n}\n\ntemplate<typename TF>\nvoid Gas_optics<TF>::compute_gas_taus(\n        const int ncol, const int nlay, const int ngpt, const int nband,\n        const Array<TF,2>& play,\n        const Array<TF,2>& plev,\n        const Array<TF,2>& tlay,\n        const Gas_concs<TF>& gas_desc,\n        std::unique_ptr<Optical_props_arry<TF>>& optical_props,\n        Array<int,2>& jtemp, Array<int,2>& jpress,\n        Array<int,4>& jeta,\n        Array<int,2>& tropo,\n        Array<TF,6>& fmajor,\n        const Array<TF,2>& col_dry) const\n{\n    Array<TF,3> tau({ngpt, nlay, ncol});\n    Array<TF,3> tau_rayleigh({ngpt, nlay, ncol});\n    Array<TF,3> vmr({ncol, nlay, this->get_ngas()});\n    Array<TF,3> col_gas({ncol, nlay, this->get_ngas()+1});\n    col_gas.set_offsets({0, 0, -1});\n    Array<TF,4> col_mix({2, this->get_nflav(), ncol, nlay});\n    Array<TF,5> fminor({2, 2, this->get_nflav(), ncol, nlay});\n\n    // CvH add all the checking...\n    const int ngas = this->get_ngas();\n    const int nflav = this->get_nflav();\n    const int neta = this->get_neta();\n    const int npres = this->get_npres();\n    const int ntemp = this->get_ntemp();\n\n    const int nminorlower = this->minor_scales_with_density_lower.dim(1);\n    const int nminorklower = this->kminor_lower.dim(1);\n    const int nminorupper = this->minor_scales_with_density_upper.dim(1);\n    const int nminorkupper = this->kminor_upper.dim(1);\n\n    for (int igas=1; igas<=ngas; ++igas)\n    {\n        const Array<TF,2>& vmr_2d = gas_desc.get_vmr(this->gas_names({igas}));\n\n        // Fill array with constant value.\n        if (vmr_2d.dim(1) == 1 && vmr_2d.dim(2) == 1)\n        {\n            const TF vmr_c = vmr_2d({1, 1});\n            for (int ilay=1; ilay<=nlay; ++ilay)\n                for (int icol=1; icol<=ncol; ++icol)\n                    vmr({icol, ilay, igas}) = vmr_c;\n        }\n        // Fill array with constant profile.\n        else if (vmr_2d.dim(1) == 1)\n        {\n            for (int ilay=1; ilay<=nlay; ++ilay)\n            {\n                const TF vmr_lay = vmr_2d({1, ilay});\n                for (int icol=1; icol<=ncol; ++icol)\n                    vmr({icol, ilay, igas}) = vmr_lay;\n            }\n        }\n        // Fill array with full 2d data.\n        else\n        {\n            for (int ilay=1; ilay<=nlay; ++ilay)\n                for (int icol=1; icol<=ncol; ++icol)\n                    vmr({icol, ilay, igas}) = vmr_2d({icol, ilay});\n        }\n    }\n\n    // CvH: Assume that col_dry is provided.\n    for (int ilay=1; ilay<=nlay; ++ilay)\n        for (int icol=1; icol<=ncol; ++icol)\n            col_gas({icol, ilay, 0}) = col_dry({icol, ilay});\n\n    for (int igas=1; igas<=ngas; ++igas)\n        for (int ilay=1; ilay<=nlay; ++ilay)\n            for (int icol=1; icol<=ncol; ++icol)\n                col_gas({icol, ilay, igas}) = vmr({icol, ilay, igas}) * col_dry({icol, ilay});\n\n    // Call the fortran kernels\n    rrtmgp_kernel_launcher::zero_array(ngpt, nlay, ncol, tau);\n\n    rrtmgp_kernel_launcher::interpolation(\n            ncol, nlay,\n            ngas, nflav, neta, npres, ntemp,\n            this->flavor,\n            this->press_ref_log,\n            this->temp_ref,\n            this->press_ref_log_delta,\n            this->temp_ref_min,\n            this->temp_ref_delta,\n            this->press_ref_trop_log,\n            this->vmr_ref,\n            play,\n            tlay,\n            col_gas,\n            jtemp,\n            fmajor, fminor,\n            col_mix,\n            tropo,\n            jeta, jpress);\n\n    int idx_h2o = -1;\n    for (int i=1; i<=this->gas_names.dim(1); ++i)\n        if (gas_names({i}) == \"h2o\")\n        {\n            idx_h2o = i;\n            break;\n        }\n\n    if (idx_h2o == -1)\n        throw std::runtime_error(\"idx_h2o cannot be found\");\n\n    rrtmgp_kernel_launcher::compute_tau_absorption(\n            ncol, nlay, nband, ngpt,\n            ngas, nflav, neta, npres, ntemp,\n            nminorlower, nminorklower,\n            nminorupper, nminorkupper,\n            idx_h2o,\n            this->gpoint_flavor,\n            this->get_band_lims_gpoint(),\n            this->kmajor,\n            this->kminor_lower,\n            this->kminor_upper,\n            this->minor_limits_gpt_lower,\n            this->minor_limits_gpt_upper,\n            this->minor_scales_with_density_lower,\n            this->minor_scales_with_density_upper,\n            this->scale_by_complement_lower,\n            this->scale_by_complement_upper,\n            this->idx_minor_lower,\n            this->idx_minor_upper,\n            this->idx_minor_scaling_lower,\n            this->idx_minor_scaling_upper,\n            this->kminor_start_lower,\n            this->kminor_start_upper,\n            tropo,\n            col_mix, fmajor, fminor,\n            play, tlay, col_gas,\n            jeta, jtemp, jpress,\n            tau);\n\n    bool has_rayleigh = (this->krayl.size() > 0);\n\n    if (has_rayleigh)\n    {\n        rrtmgp_kernel_launcher::compute_tau_rayleigh(\n                ncol, nlay, nband, ngpt,\n                ngas, nflav, neta, npres, ntemp,\n                this->gpoint_flavor,\n                this->get_band_lims_gpoint(),\n                this->krayl,\n                idx_h2o, col_dry, col_gas,\n                fminor, jeta, tropo, jtemp,\n                tau_rayleigh);\n    }\n\n    combine_and_reorder(tau, tau_rayleigh, has_rayleigh, optical_props);\n}\n\ntemplate<typename TF>\nvoid Gas_optics<TF>::combine_and_reorder(\n        const Array<TF,3>& tau,\n        const Array<TF,3>& tau_rayleigh,\n        const bool has_rayleigh,\n        std::unique_ptr<Optical_props_arry<TF>>& optical_props) const\n{\n    int ncol = tau.dim(3);\n    int nlay = tau.dim(2);\n    int ngpt = tau.dim(1);\n\n    if (!has_rayleigh)\n    {\n        // CvH for 2 stream and n-stream zero the g and ssa\n        rrtmgp_kernel_launcher::reorder123x321(tau, optical_props->get_tau());\n        // reorder123x321_test(optical_props->get_tau().ptr(), tau.ptr(), ngpt, nlay, ncol);\n\n        // rrtmgp_kernel_launcher::zero_array(ngpt, nlay, ncol, optical_props->get_ssa());\n        // rrtmgp_kernel_launcher::zero_array(ngpt, nlay, ncol, optical_props->get_g  ());\n    }\n    else\n    {\n        // In case of 1scl type\n        // rrtmgp_kernel_launcher::reorder123x321(tau, optical_props->get_tau());\n\n        // In case of 2str type\n        rrtmgp_kernel_launcher::combine_and_reorder_2str(\n                ncol, nlay, ngpt,\n                tau, tau_rayleigh,\n                optical_props->get_tau(), optical_props->get_ssa(), optical_props->get_g());\n    }\n}\n\ntemplate<typename TF>\nvoid Gas_optics<TF>::source(\n        const int ncol, const int nlay, const int nbnd, const int ngpt,\n        const Array<TF,2>& play, const Array<TF,2>& plev,\n        const Array<TF,2>& tlay, const Array<TF,1>& tsfc,\n        const Array<int,2>& jtemp, const Array<int,2>& jpress,\n        const Array<int,4>& jeta, const Array<int,2>& tropo,\n        const Array<TF,6>& fmajor,\n        Source_func_lw<TF>& sources,\n        const Array<TF,2>& tlev) const\n{\n    // CvH Assume tlev is available.\n    // Compute internal (Planck) source functions at layers and levels,\n    // which depend on mapping from spectral space that creates k-distribution.\n    const int nflav = this->get_nflav();\n    const int neta = this->get_neta();\n    const int npres = this->get_npres();\n    const int ntemp = this->get_ntemp();\n    const int nPlanckTemp = this->get_nPlanckTemp();\n    auto gpoint_bands = this->get_gpoint_bands();\n    auto band_lims_gpoint = this->get_band_lims_gpoint();\n\n    Array<TF,3> lay_source_t({ngpt, nlay, ncol});\n    Array<TF,3> lev_source_inc_t({ngpt, nlay, ncol});\n    Array<TF,3> lev_source_dec_t({ngpt, nlay, ncol});\n    Array<TF,2> sfc_source_t({ngpt, ncol});\n    Array<TF,2> sfc_source_jac({ngpt, ncol});\n\n    int sfc_lay = play({1, 1}) > play({1, nlay}) ? 1 : nlay;\n    rrtmgp_kernel_launcher::compute_Planck_source(\n            ncol, nlay, nbnd, ngpt,\n            nflav, neta, npres, ntemp, nPlanckTemp,\n            tlay, tlev, tsfc, sfc_lay,\n            fmajor, jeta, tropo, jtemp, jpress,\n            gpoint_bands, band_lims_gpoint, this->planck_frac, this->temp_ref_min,\n            this->totplnk_delta, this->totplnk, this->gpoint_flavor,\n            sfc_source_t, lay_source_t, lev_source_inc_t, lev_source_dec_t,\n            sfc_source_jac);\n\n    // CvH this transpose is super slow.\n    for (int j=1; j<=sfc_source_t.dim(2); ++j)\n        for (int i=1; i<=sfc_source_t.dim(1); ++i)\n        {\n            sources.get_sfc_source    ()({j, i}) = sfc_source_t  ({i, j});\n            sources.get_sfc_source_jac()({j, i}) = sfc_source_jac({i, j});\n        }\n\n    rrtmgp_kernel_launcher::reorder123x321(lay_source_t, sources.get_lay_source());\n    rrtmgp_kernel_launcher::reorder123x321(lev_source_inc_t, sources.get_lev_source_inc());\n    rrtmgp_kernel_launcher::reorder123x321(lev_source_dec_t, sources.get_lev_source_dec());\n    // reorder123x321_test(sources.get_lay_source    ().ptr(), lay_source_t    .ptr(), ngpt, nlay, ncol);\n    // reorder123x321_test(sources.get_lev_source_inc().ptr(), lev_source_inc_t.ptr(), ngpt, nlay, ncol);\n    // reorder123x321_test(sources.get_lev_source_dec().ptr(), lev_source_dec_t.ptr(), ngpt, nlay, ncol);\n}\n\n#ifdef FLOAT_SINGLE_RRTMGP\ntemplate class Gas_optics<float>;\n#else\ntemplate class Gas_optics<double>;\n#endif\n", "meta": {"hexsha": "6523a7e5c85fbb685e8addeec8fb37b3fc05c320", "size": 50163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Gas_optics.cpp", "max_stars_repo_name": "Chiil/rte-rrtmgp-cpp", "max_stars_repo_head_hexsha": "b39b130c733b8a9633753398b57849826818b8c6", "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/Gas_optics.cpp", "max_issues_repo_name": "Chiil/rte-rrtmgp-cpp", "max_issues_repo_head_hexsha": "b39b130c733b8a9633753398b57849826818b8c6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Gas_optics.cpp", "max_forks_repo_name": "Chiil/rte-rrtmgp-cpp", "max_forks_repo_head_hexsha": "b39b130c733b8a9633753398b57849826818b8c6", "max_forks_repo_licenses": ["BSD-3-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.2923664122, "max_line_length": 146, "alphanum_fraction": 0.578135279, "num_tokens": 13729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.25587325714827586}}
{"text": "#ifndef STAN_MATH_REV_MAT_FUN_QUAD_FORM_HPP\n#define STAN_MATH_REV_MAT_FUN_QUAD_FORM_HPP\n\n#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits.hpp>\n#include <stan/math/rev/core.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/prim/mat/fun/typedefs.hpp>\n#include <stan/math/rev/mat/fun/typedefs.hpp>\n#include <stan/math/prim/mat/fun/value_of.hpp>\n#include <stan/math/prim/mat/fun/quad_form.hpp>\n#include <stan/math/prim/mat/err/check_multiplicable.hpp>\n#include <stan/math/prim/mat/err/check_square.hpp>\n#include <stan/math/prim/mat/err/check_symmetric.hpp>\n\nnamespace stan {\nnamespace math {\n\nnamespace {\ntemplate <typename Ta, int Ra, int Ca, typename Tb, int Rb, int Cb>\nclass quad_form_vari_alloc : public chainable_alloc {\n private:\n  inline void compute(const Eigen::Matrix<double, Ra, Ca>& A,\n                      const Eigen::Matrix<double, Rb, Cb>& B) {\n    Eigen::Matrix<double, Cb, Cb> Cd(B.transpose() * A * B);\n    for (int j = 0; j < C_.cols(); j++) {\n      for (int i = 0; i < C_.rows(); i++) {\n        if (sym_) {\n          C_(i, j) = var(new vari(0.5 * (Cd(i, j) + Cd(j, i)), false));\n        } else {\n          C_(i, j) = var(new vari(Cd(i, j), false));\n        }\n      }\n    }\n  }\n\n public:\n  quad_form_vari_alloc(const Eigen::Matrix<Ta, Ra, Ca>& A,\n                       const Eigen::Matrix<Tb, Rb, Cb>& B,\n                       bool symmetric = false)\n      : A_(A), B_(B), C_(B_.cols(), B_.cols()), sym_(symmetric) {\n    compute(value_of(A), value_of(B));\n  }\n\n  Eigen::Matrix<Ta, Ra, Ca> A_;\n  Eigen::Matrix<Tb, Rb, Cb> B_;\n  Eigen::Matrix<var, Cb, Cb> C_;\n  bool sym_;\n};\n\ntemplate <typename Ta, int Ra, int Ca, typename Tb, int Rb, int Cb>\nclass quad_form_vari : public vari {\n protected:\n  inline void chainA(Eigen::Matrix<double, Ra, Ca>& A,\n                     const Eigen::Matrix<double, Rb, Cb>& Bd,\n                     const Eigen::Matrix<double, Cb, Cb>& adjC) {}\n  inline void chainB(Eigen::Matrix<double, Rb, Cb>& B,\n                     const Eigen::Matrix<double, Ra, Ca>& Ad,\n                     const Eigen::Matrix<double, Rb, Cb>& Bd,\n                     const Eigen::Matrix<double, Cb, Cb>& adjC) {}\n\n  inline void chainA(Eigen::Matrix<var, Ra, Ca>& A,\n                     const Eigen::Matrix<double, Rb, Cb>& Bd,\n                     const Eigen::Matrix<double, Cb, Cb>& adjC) {\n    Eigen::Matrix<double, Ra, Ca> adjA(Bd * adjC * Bd.transpose());\n    for (int j = 0; j < A.cols(); j++) {\n      for (int i = 0; i < A.rows(); i++) {\n        A(i, j).vi_->adj_ += adjA(i, j);\n      }\n    }\n  }\n  inline void chainB(Eigen::Matrix<var, Rb, Cb>& B,\n                     const Eigen::Matrix<double, Ra, Ca>& Ad,\n                     const Eigen::Matrix<double, Rb, Cb>& Bd,\n                     const Eigen::Matrix<double, Cb, Cb>& adjC) {\n    Eigen::Matrix<double, Ra, Ca> adjB(Ad * Bd * adjC.transpose()\n                                       + Ad.transpose() * Bd * adjC);\n    for (int j = 0; j < B.cols(); j++)\n      for (int i = 0; i < B.rows(); i++)\n        B(i, j).vi_->adj_ += adjB(i, j);\n  }\n\n  inline void chainAB(Eigen::Matrix<Ta, Ra, Ca>& A,\n                      Eigen::Matrix<Tb, Rb, Cb>& B,\n                      const Eigen::Matrix<double, Ra, Ca>& Ad,\n                      const Eigen::Matrix<double, Rb, Cb>& Bd,\n                      const Eigen::Matrix<double, Cb, Cb>& adjC) {\n    chainA(A, Bd, adjC);\n    chainB(B, Ad, Bd, adjC);\n  }\n\n public:\n  quad_form_vari(const Eigen::Matrix<Ta, Ra, Ca>& A,\n                 const Eigen::Matrix<Tb, Rb, Cb>& B, bool symmetric = false)\n      : vari(0.0) {\n    impl_ = new quad_form_vari_alloc<Ta, Ra, Ca, Tb, Rb, Cb>(A, B, symmetric);\n  }\n\n  virtual void chain() {\n    Eigen::Matrix<double, Cb, Cb> adjC(impl_->C_.rows(), impl_->C_.cols());\n\n    for (int j = 0; j < impl_->C_.cols(); j++)\n      for (int i = 0; i < impl_->C_.rows(); i++)\n        adjC(i, j) = impl_->C_(i, j).vi_->adj_;\n\n    chainAB(impl_->A_, impl_->B_, value_of(impl_->A_), value_of(impl_->B_),\n            adjC);\n  }\n\n  quad_form_vari_alloc<Ta, Ra, Ca, Tb, Rb, Cb>* impl_;\n};\n}  // namespace\n\ntemplate <typename Ta, int Ra, int Ca, typename Tb, int Rb, int Cb>\ninline typename boost::enable_if_c<boost::is_same<Ta, var>::value\n                                       || boost::is_same<Tb, var>::value,\n                                   Eigen::Matrix<var, Cb, Cb> >::type\nquad_form(const Eigen::Matrix<Ta, Ra, Ca>& A,\n          const Eigen::Matrix<Tb, Rb, Cb>& B) {\n  check_square(\"quad_form\", \"A\", A);\n  check_multiplicable(\"quad_form\", \"A\", A, \"B\", B);\n\n  quad_form_vari<Ta, Ra, Ca, Tb, Rb, Cb>* baseVari\n      = new quad_form_vari<Ta, Ra, Ca, Tb, Rb, Cb>(A, B);\n\n  return baseVari->impl_->C_;\n}\n\ntemplate <typename Ta, int Ra, int Ca, typename Tb, int Rb>\ninline typename boost::enable_if_c<\n    boost::is_same<Ta, var>::value || boost::is_same<Tb, var>::value, var>::type\nquad_form(const Eigen::Matrix<Ta, Ra, Ca>& A,\n          const Eigen::Matrix<Tb, Rb, 1>& B) {\n  check_square(\"quad_form\", \"A\", A);\n  check_multiplicable(\"quad_form\", \"A\", A, \"B\", B);\n\n  quad_form_vari<Ta, Ra, Ca, Tb, Rb, 1>* baseVari\n      = new quad_form_vari<Ta, Ra, Ca, Tb, Rb, 1>(A, B);\n\n  return baseVari->impl_->C_(0, 0);\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "9c377299c04dcd805053824806060adaf02caccb", "size": 5257, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/rev/mat/fun/quad_form.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/rev/mat/fun/quad_form.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/rev/mat/fun/quad_form.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": 36.0068493151, "max_line_length": 80, "alphanum_fraction": 0.5630587788, "num_tokens": 1630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.25587290981687844}}
{"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_BNC_BADER_HPP__\n#define __PLATO_ALGO_BNC_BADER_HPP__\n\n#include <cstdint>\n#include <cstdlib>\n#include <unordered_map>\n#include <algorithm>\n#include <utility>\n#include <vector>\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\n#include \"cgm.hpp\"\n\nnamespace plato { namespace algo {\n/**\n * @brief bader option\n */\nstruct bader_opts_t {\n  vid_t max_iteration_ = 0;\n  int chosen_ = -1;\n  float constant_ = 2;\n};\n\n/**\n * @brief\n * @tparam INCOMING\n * @tparam OUTGOING\n * @tparam T\n */\ntemplate <typename INCOMING, typename OUTGOING, typename T>\nclass bader_betweenness_t {\npublic:\n  using partition_t = typename dualmode_detail::partition_traits<INCOMING, OUTGOING>::type;\n  using betweenness_state_t  = dense_state_t<T, partition_t>;\n  using label_state_t = dense_state_t<vid_t, partition_t>;\n  using active_subset_t = bitmap_t<>;\n  struct bader_msg_type_t {\n    vid_t src_;\n    T value_;\n  };\n\n  /**\n   * @brief\n   * @param engine\n   * @param graph_info\n   * @param opts\n   */\n  explicit bader_betweenness_t (\n    dualmode_engine_t<INCOMING, OUTGOING> * engine,\n    const graph_info_t &graph_info, const bader_opts_t& opts = bader_opts_t());\n  /// \\brief\n  ~bader_betweenness_t();\n\n  // return the betweenness centrality of a given vertex\n  T get_betweenness_of(vid_t v_i) const;\n\n  // compute the betweenness of all vertices\n  void compute();\n  /**\n   * @brief\n   * @tparam Callback\n   * @param streams\n   */\n  template <typename Callback>\n  void save(Callback&& callback);\n\n  /**\n   * @brief\n   * @return\n   */\n  vid_t get_chosen() const { return chosen_; }\n\n  /**\n   * @brief\n   * @return\n   */\n  std::unordered_set<vid_t>* get_samples() { return &samples_; }\n\n  /**\n   * @brief\n   * @return\n   */\n  vid_t get_major_componnent_vertices() const { return major_component_vertices_; }\n\nprivate:\n  /**\n   * @brief\n   * @param root\n   * @param post_proc\n   */\n  void epoch(vid_t root, std::function<void(const betweenness_state_t*, vid_t)> post_proc);\n\nprivate:\n  dualmode_engine_t<INCOMING, OUTGOING> * engine_;\n  graph_info_t graph_info_;\n  betweenness_state_t betweenness_;\n  betweenness_state_t num_paths_;\n  betweenness_state_t dependencies_;\n  T sum_dependence_;\n  T sum_dependence_max_;\n  vid_t chosen_;\n  float constant_;\n  vid_t max_iteration_;\n  std::unordered_set<vid_t> samples_;\n  connected_component_t<INCOMING, OUTGOING> *cc_;\n  label_state_t global_labels_;\n  vid_t major_component_label_;\n  vid_t major_component_vertices_;\n  active_subset_t active_all_;\n};\n\ntemplate <typename INCOMING, typename OUTGOING, typename T>\nbader_betweenness_t<INCOMING, OUTGOING, T>::bader_betweenness_t(\n  dualmode_engine_t<INCOMING, OUTGOING>* engine, const graph_info_t &graph_info,\n  const bader_opts_t& opts)\n  : engine_(engine),\n    graph_info_(graph_info),\n    betweenness_(graph_info.max_v_i_, engine->in_edges()->partitioner()),\n    num_paths_(graph_info.max_v_i_, engine->in_edges()->partitioner()),\n    dependencies_(graph_info.max_v_i_, engine->in_edges()->partitioner()),\n    sum_dependence_(0),\n    global_labels_(graph_info.max_v_i_, engine->in_edges()->partitioner()),\n    active_all_(graph_info.max_v_i_ + 1) {\n  cc_ = new connected_component_t<INCOMING, OUTGOING>(engine, graph_info);\n  cc_->compute();\n  major_component_label_ = cc_->get_major_label();\n  major_component_vertices_ = cc_->get_major_vertices();\n  constant_ = opts.constant_;\n  sum_dependence_max_ = constant_ * major_component_vertices_;\n  if (opts.max_iteration_ == 0) {\n    max_iteration_ = major_component_vertices_;\n  } else {\n    max_iteration_ = opts.max_iteration_;\n  }\n\n  active_all_.fill();\n\n  //init label\n  auto local_label = cc_->get_labels();\n\n  auto active_view_all = plato::create_active_v_view(engine_->out_edges()->partitioner()->self_v_view(), active_all_);\n  active_view_all.template foreach<vid_t>([&](vid_t v_i){\n    global_labels_[v_i] = (*local_label)[v_i];\n    return 0;\n  });\n\n  auto& cluster_info = plato::cluster_info_t::get_instance();\n  if (cluster_info.partition_id_ != 0) {\n    vid_t v_begin = engine_->out_edges()->partitioner()->offset_[cluster_info.partition_id_];\n    vid_t v_end = engine_->out_edges()->partitioner()->offset_[cluster_info.partition_id_+1];\n    MPI_Send(&(global_labels_[v_begin]), v_end - v_begin, get_mpi_data_type<vid_t>(), 0, 0, MPI_COMM_WORLD);\n  }\n  else {\n    for (int i = 1; i < cluster_info.partitions_; ++i ) {\n      MPI_Status recv_status;\n      vid_t v_begin = engine_->out_edges()->partitioner()->offset_[i];\n      vid_t v_end = engine_->out_edges()->partitioner()->offset_[i+1];\n      MPI_Recv(&(global_labels_[v_begin]), v_end - v_begin, get_mpi_data_type<vid_t>(), i, 0, MPI_COMM_WORLD, &recv_status);\n    }\n  }\n\n  //get chosen vertex\n  if (opts.chosen_ == -1) {\n    if (cluster_info.partition_id_ == 0) {\n      do {\n        chosen_ = rand() % graph_info.vertices_;\n      } while (global_labels_[chosen_] != major_component_label_);\n    }\n    MPI_Bcast(&chosen_, 1, get_mpi_data_type<vid_t>(), 0, MPI_COMM_WORLD);\n    LOG(INFO) << \"chosen: \"  << chosen_ << std::endl;\n  }\n  else {\n    chosen_ = opts.chosen_;\n  }\n\n}\n\ntemplate <typename INCOMING, typename OUTGOING, typename T>\nbader_betweenness_t<INCOMING, OUTGOING, T>::~bader_betweenness_t() {\n  delete cc_;\n}\n\ntemplate <typename INCOMING, typename OUTGOING, typename T>\nvoid bader_betweenness_t<INCOMING, OUTGOING, T>::compute() {\n  auto continue_iterating = [&](vid_t iter) {\n    return iter < max_iteration_ && sum_dependence_ < sum_dependence_max_;\n  };\n\n  // pick a new random vertex that is not used before\n  // we use a set to record the vertices that are used.\n  auto& cluster_info = plato::cluster_info_t::get_instance();\n  auto gen_next_vertex = [&]() {\n    vid_t nxt;\n    if (cluster_info.partition_id_ == 0) {\n      size_t curr_size = samples_.size();\n      do {\n        nxt = std::rand() % graph_info_.vertices_;\n        if (global_labels_[nxt] == major_component_label_) {\n          samples_.insert(nxt);\n        }\n      } while (curr_size == samples_.size());\n    }\n    MPI_Bcast(&nxt, 1, get_mpi_data_type<vid_t>(), 0, MPI_COMM_WORLD);\n    if (cluster_info.partition_id_ != 0) samples_.insert(nxt);\n    return nxt;\n  };\n  auto active_view_all = plato::create_active_v_view(engine_->out_edges()->partitioner()->self_v_view(), active_all_);\n  auto accumulate = [&](const betweenness_state_t* dependencies, vid_t root) {\n    active_view_all.template foreach<vid_t>([&](vid_t v_i){\n      if (v_i != root) {\n        T d = (*dependencies)[v_i];\n        betweenness_[v_i] += d;\n        if (v_i == chosen_) {\n          sum_dependence_ += d;\n        }\n      }\n      return 1;\n    });\n\n    int chosen_partition = engine_->out_edges()->partitioner()->get_partition_id(chosen_);\n    MPI_Bcast(&sum_dependence_, 1, get_mpi_data_type<T>(), chosen_partition,MPI_COMM_WORLD);\n    LOG(INFO) << \"sum_deppendece: \" << sum_dependence_ << \" sum_dependence_max: \" << sum_dependence_max_ << std::endl;\n  };\n\n  auto update_betweenness = [&](vid_t sample_size) {\n    active_view_all.template foreach<vid_t>([&](vid_t v_i) {\n      betweenness_[v_i] = major_component_vertices_ * betweenness_[v_i] / sample_size;\n      if (std::isnan(betweenness_[v_i])) {\n        betweenness_[v_i] = 0;\n      }\n      return 1;\n    });\n  };\n\n  for (vid_t iter = 0; continue_iterating(iter); ++iter) {\n    auto root = gen_next_vertex();\n    LOG(INFO) << \"next root: \" << root << std::endl;\n    epoch(root, accumulate);\n    LOG_IF(INFO, !cluster_info.partition_id_ && (iter + 1) % 10 == 0)\n    << boost::format(\"iter=%u/%u, sum_dependence[%u]=%.1f/%.1f\\n\") % (iter + 1) % max_iteration_ % chosen_ % sum_dependence_ % sum_dependence_max_;\n  }\n\n  vid_t sample_size = samples_.size();\n  MPI_Bcast(&sample_size, 1, get_mpi_data_type<vid_t>(), 0, MPI_COMM_WORLD);\n\n  update_betweenness(sample_size);\n}\n\ntemplate <typename INCOMING, typename OUTGOING, typename T>\nT bader_betweenness_t<INCOMING, OUTGOING, T>::get_betweenness_of(vid_t v_i) const {\n  auto& cluster_info = plato::cluster_info_t::get_instance();\n  int vtx_partition = engine_->out_edges()->partitioner()->get_partition_id(v_i);\n  T ret = cluster_info.partition_id_ == vtx_partition ? betweenness_[v_i] : 0;\n  MPI_Bcast(&ret, 1, get_mpi_data_type<T>(), vtx_partition, MPI_COMM_WORLD);\n  return ret;\n}\n\ntemplate <typename INCOMING, typename OUTGOING, typename T>\nvoid bader_betweenness_t<INCOMING, OUTGOING, T>::epoch(\n  vid_t root, std::function<void(const betweenness_state_t*, vid_t)> post_proc) {\n  std::vector<active_subset_t*> levels;\n  auto active_current = new active_subset_t(graph_info_.max_v_i_ + 1);\n  auto visited = engine_->alloc_v_subset();\n  vid_t actives = 1;\n  visited.clear();\n  visited.set_bit(root);\n  active_current->clear();\n  active_current->set_bit(root);\n  levels.push_back(active_current);\n  num_paths_.fill((T)0.0);\n  num_paths_[root] = 1.0;\n\n  using adj_unit_list_spec_t = typename INCOMING::adj_unit_list_spec_t;\n  using pull_context_t = plato::template mepa_ag_context_t<bader_msg_type_t>;\n  using pull_message_t = plato::template mepa_ag_message_t<bader_msg_type_t>;\n  using push_context_t = plato::template mepa_bc_context_t<bader_msg_type_t>;\n  for (int epoch_i = 0; actives > 0; ++epoch_i) {\n    auto active_next = new active_subset_t(graph_info_.max_v_i_ + 1);\n    active_next->clear();\n    engine_->template foreach_edges<bader_msg_type_t, vid_t> (\n      [&](const push_context_t& context, vid_t v_i) {\n        context.send(bader_msg_type_t{ v_i, num_paths_[v_i] });\n      },\n      [&](int /*p_i*/, bader_msg_type_t& msg) {\n        auto neighbours = engine_->out_edges()->neighbours(msg.src_);\n        for (auto it = neighbours.begin_; neighbours.end_ != it; ++it) {\n          vid_t dst = it->neighbour_;\n          if (!visited.get_bit(dst)) {\n            if (num_paths_[dst] == 0) {\n              active_next->set_bit(dst);\n            }\n            write_add(&(num_paths_[dst]), msg.value_);\n          }\n        }\n        return 0;\n      },\n      [&](const pull_context_t& context, vid_t v_i, const adj_unit_list_spec_t& adjs) {\n        if (visited.get_bit(v_i)) return;\n        T sum = 0;\n        for (auto it = adjs.begin_; adjs.end_ != it; ++it) {\n          vid_t src = it->neighbour_;\n          if (active_current->get_bit(src)) {\n            sum += num_paths_[src];\n          }\n        }\n        if (sum > 0) {\n          context.send(pull_message_t{ v_i, bader_msg_type_t{ v_i, sum } });\n        }\n      },\n      [&](int, pull_message_t& msg) {\n        if (!visited.get_bit(msg.v_i_)) {\n          active_next->set_bit(msg.v_i_);\n          write_add(&(num_paths_[msg.v_i_]), msg.message_.value_);\n        }\n        return 0;\n      },\n      *active_current\n    );\n    auto active_view = plato::create_active_v_view(engine_->out_edges()->partitioner()->self_v_view(), *active_next);\n    actives = active_view.template foreach<vid_t> ([&](vid_t v_i) {\n      visited.set_bit(v_i); return 1;\n    });\n    if (actives > 0) levels.push_back(active_next);\n    active_current = active_next;\n  }\n\n  dependencies_.fill((T)0.0);\n  visited.clear();\n  while (levels.size() > 0) {\n    auto active_view = plato::create_active_v_view(engine_->out_edges()->partitioner()->self_v_view(), *(levels.back()));\n    actives = active_view.template foreach<vid_t> ([&](vid_t v_i) {\n      visited.set_bit(v_i); return 1;\n    });\n    engine_->template foreach_edges<bader_msg_type_t, vid_t> (\n      [&](const push_context_t& context, vid_t v_i) {\n        T value = (dependencies_[v_i] + 1.0) / num_paths_[v_i];\n        context.send(bader_msg_type_t{ v_i, value });\n      },\n      [&](int /*p_i*/, bader_msg_type_t& msg) {\n        auto neighbours = engine_->out_edges()->neighbours(msg.src_);\n        for (auto it = neighbours.begin_; neighbours.end_ != it; ++it) {\n          vid_t dst = it->neighbour_;\n          if (!visited.get_bit(dst)) {\n            write_add(&(dependencies_[dst]), msg.value_ * num_paths_[dst]);\n          }\n        }\n        return 0;\n      },\n      [&](const pull_context_t& context, vid_t v_i, const adj_unit_list_spec_t& adjs) {\n        if (visited.get_bit(v_i)) return;\n        T sum = 0;\n        for (auto it = adjs.begin_; adjs.end_ != it; ++it) {\n          vid_t src = it->neighbour_;\n          if (levels.back()->get_bit(src)) {\n            sum += (dependencies_[src] + 1.0) / num_paths_[src];\n          }\n        }\n        if (sum > 0) {\n          context.send(pull_message_t{ v_i, bader_msg_type_t{ v_i, sum } });\n        }\n      },\n      [&](int, pull_message_t& msg) {\n        if (!visited.get_bit(msg.v_i_)) {\n          write_add(&(dependencies_[msg.v_i_]), msg.message_.value_ * num_paths_[msg.v_i_]);\n        }\n        return 0;\n      },\n      *(levels.back())\n    );\n    delete levels.back();\n    levels.pop_back();\n  }\n\n  post_proc(&dependencies_, root);\n}\n\ntemplate <typename INCOMING, typename OUTGOING, typename T>\ntemplate <typename Callback>\nvoid bader_betweenness_t<INCOMING, OUTGOING, T>::save(Callback&& callback) {\n  // traverse\n  auto active_view_all = plato::create_active_v_view(engine_->out_edges()->partitioner()->self_v_view(), active_all_);\n  active_view_all.template foreach<vid_t>([&] (vid_t v_i) {\n    callback(v_i, betweenness_[v_i]);\n    return 1;\n  });\n}\n\n}\n}\n#endif\n", "meta": {"hexsha": "8109ae11c4ecd1ef04efd3bafc2e21bd5b03d74f", "size": 14145, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "plato/algo/bnc/bader.hpp", "max_stars_repo_name": "ustcyu/plato", "max_stars_repo_head_hexsha": "e4b3ae644f74acb4b57e3150b6f3b50546dce9da", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-14T13:10:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-14T13:10:28.000Z", "max_issues_repo_path": "plato/algo/bnc/bader.hpp", "max_issues_repo_name": "ustcyu/plato", "max_issues_repo_head_hexsha": "e4b3ae644f74acb4b57e3150b6f3b50546dce9da", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/bnc/bader.hpp", "max_forks_repo_name": "ustcyu/plato", "max_forks_repo_head_hexsha": "e4b3ae644f74acb4b57e3150b6f3b50546dce9da", "max_forks_repo_licenses": ["BSD-3-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.5985748219, "max_line_length": 147, "alphanum_fraction": 0.6714740191, "num_tokens": 3857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2558583023520827}}
{"text": "/**\n * @file\n * @copyright This code is licensed under the 3-clause BSD license.\\n\n *            Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\\n\n *            See LICENSE.txt for details.\n */\n\n#include <Utils/GeometricDerivatives/AdiabaticModeLocalizer.h>\n#include <pybind11/eigen.h>\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n#include <boost/optional.hpp>\n\nusing namespace Scine::Utils;\n\nvoid init_adiabatic_mode_localizer(pybind11::module& m) {\n  pybind11::class_<AdiabaticModesContainer> adiabaticModesContainer(m, \"AdiabaticModesContainer\", R\"delim(\n    A class storing the localized adiabatic properties.\n    This class is an extension of the standard normal mode container, with modes being accessed by specifying the\n    internal coordinate of interest.\n    Note: Currently only interatomic stretching coordinates, e.g., bonds, are supported as internal coordinates.\n    )delim\");\n\n  adiabaticModesContainer.def(\"add_mode\", &AdiabaticModesContainer::addMode, pybind11::arg(\"internal_coordinate\"),\n                              pybind11::arg(\"mode\"), pybind11::arg(\"force_constant\"), R\"delim(\n    Adds a mode to the container.\n\n    :param internal_coordinate: The internal coordinate to which this mode corresponds.\n    :param mode: The mode to be added.\n    :param force_constant: The adiabatic force constant of the mode.\n    )delim\");\n\n  adiabaticModesContainer.def(\"get_mode\", &AdiabaticModesContainer::getMode, pybind11::arg(\"internal_coordinate\"), R\"delim(\n    Returns the localized vibrational mode corresponding to the given internal coordinate.\n\n    :param: internal_coordinate The internal coordinate of interest.\n    :return: The localized mode.\n    )delim\");\n\n  adiabaticModesContainer.def(\"get_mode_as_molecular_trajectory\", &AdiabaticModesContainer::getModeAsMolecularTrajectory,\n                              pybind11::arg(\"internal_coordinate\"), pybind11::arg(\"atoms\"),\n                              pybind11::arg(\"scaling_factor\"), R\"delim(\n    Returns a molecular trajectory corresponding to a vibrational mode.\n\n    :param internal_coordinate: The internal coordinate of interest.\n    :param atoms: The atom collection of interest.\n    :param scaling_factor: The scaling factor applied to the mode to obtain the maximum displacement.\n    :return: The molecular trajectory representing the mode.\n    )delim\");\n\n  adiabaticModesContainer.def(\"get_wave_numbers\", &AdiabaticModesContainer::getWaveNumbers, R\"delim(\n    Gets the wave numbers corresponding to the localized modes.\n    \n    :return: Mapping between internal coordinates and adiabatic wave numbers.\n    )delim\");\n\n  adiabaticModesContainer.def(\"get_force_constants\", &AdiabaticModesContainer::getForceConstants, R\"delim(\n    Gets the force constants corresponding to the localized modes.\n    \n    :return: Mapping between internal coordinates and adiabatic force constants.\n    )delim\");\n\n  pybind11::class_<AdiabaticModeLocalizer> adiabaticModeLocalizer(m, \"AdiabaticModeLocalizer\", R\"delim(\n    This class calculates the localized vibrational modes and adiabatic force constants corresponding to internal\n    coordinates based on the local vibrational mode theory by Konkoli and Cremer. Adiabatic force constants are\n    equivalent to the relaxed force constants derived from Decius' compliance matrix.\n  \n    Konkoli, Z.; Cremer, D. Int. J. Quantum Chem. 1998, 67 (1), 1–9.\n    https://doi.org/10.1002/(SICI)1097-461X(1998)67:1<1::AID-QUA1>3.0.CO;2-Z.\n  \n    Implemented after:\n    Kraka, E.; Zou, W.; Tao, Y. Wiley Interdiscip. Rev. Comput. Mol. Sci. 2020, e1480. https://doi.org/10.1002/wcms.1480.\n\n    Note: Currently only interatomic stretching coordinates, e.g., bonds, are supported as internal coordinates.\n    )delim\");\n\n  adiabaticModeLocalizer.def(pybind11::init<Eigen::MatrixXd, AtomCollection, BondOrderCollection, double>(),\n                             pybind11::arg(\"hessian\"), pybind11::arg(\"atoms\"), pybind11::arg(\"bond_orders\"),\n                             pybind11::arg(\"bonding_threshold\") = 0.5, R\"delim(\n    Constructor for the AdiabaticModeLocalizer class processing a bond order collection.\n    All bonds with a bond order larger than bonding_threshold will be used as internal coordinates.\n   \n    :param hessian: The cartesian, not mass-weighted Hessian matrix.\n    :param atoms: The atom collection of interest.\n    :param bond_orders: The bond order collection of the structure of interest.\n    :param: bonding_threshold The bond order threshold beyond which bonds are analyzed in terms of localized modes. (default: 0.5)\n    )delim\");\n\n  adiabaticModeLocalizer.def(pybind11::init<Eigen::MatrixXd, AtomCollection, const std::vector<std::pair<int, int>>>(),\n                             pybind11::arg(\"hessian\"), pybind11::arg(\"atoms\"), pybind11::arg(\"internal_coordinates\"), R\"delim(\n    Constructor for the AdiabaticModeLocalizer class processing indices of atom pairs as internal coordinates.\n    \n    :param hessian: The cartesian, not mass-weighted Hessian matrix.\n    :param atoms: The atom collection of interest.\n    :param internal_coordinates:  The internal coordinates of interest.\n    )delim\");\n\n  adiabaticModeLocalizer.def(\"localize_modes\", &AdiabaticModeLocalizer::localizeModes, R\"delim(\n    Calculates the adiabatic localized modes corresponding to the given internal coordinates.\n   \n    References:\n    Konkoli, Z.; Cremer, D. Int. J. Quantum Chem. 1998, 67 (1), 1–9.\n    https://doi.org/10.1002/(SICI)1097-461X(1998)67:1<1::AID-QUA1>3.0.CO;2-Z.\n   \n    Kraka, E.; Zou, W.; Tao, Y. Wiley Interdiscip. Rev. Comput. Mol. Sci. 2020, e1480.\n    https://doi.org/10.1002/wcms.1480.\n   \n    :return: A container with the localized adiabatic modes, force constants and wavenumbers.\n    )delim\");\n}\n", "meta": {"hexsha": "c2f09ed2b5a7d1505ab2587e74afceec18814768", "size": 5762, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Python/AdiabaticModeLocalizerPython.cpp", "max_stars_repo_name": "qcscine/utilities", "max_stars_repo_head_hexsha": "493b8db45772b231bc0296535a09905b8e292f77", "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/Python/AdiabaticModeLocalizerPython.cpp", "max_issues_repo_name": "qcscine/utilities", "max_issues_repo_head_hexsha": "493b8db45772b231bc0296535a09905b8e292f77", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-06-19T14:34:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:07:18.000Z", "max_forks_repo_path": "src/Utils/Python/AdiabaticModeLocalizerPython.cpp", "max_forks_repo_name": "qcscine/utilities", "max_forks_repo_head_hexsha": "493b8db45772b231bc0296535a09905b8e292f77", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-06-14T16:44:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-19T20:48:19.000Z", "avg_line_length": 51.9099099099, "max_line_length": 130, "alphanum_fraction": 0.7278722666, "num_tokens": 1473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.2557958585425036}}
{"text": "#pragma once\n#include <trajopt_utils/macros.h>\nTRAJOPT_IGNORE_WARNINGS_PUSH\n#include <Eigen/Dense>\n#include <functional>\n#include <memory>\nTRAJOPT_IGNORE_WARNINGS_POP\n\n/*\n * Numerical derivatives\n */\n\nnamespace sco\n{\nclass ScalarOfVector;\nclass VectorOfVector;\nclass MatrixOfVector;\ntypedef std::shared_ptr<ScalarOfVector> ScalarOfVectorPtr;\ntypedef std::shared_ptr<VectorOfVector> VectorOfVectorPtr;\ntypedef std::shared_ptr<MatrixOfVector> MatrixOfVectorPtr;\n\nclass ScalarOfVector\n{\npublic:\n  virtual double operator()(const Eigen::VectorXd& x) const = 0;\n  double call(const Eigen::VectorXd& x) const\n  {\n    return operator()(x);\n  }\n  virtual ~ScalarOfVector()\n  {\n  }\n  typedef std::function<double(Eigen::VectorXd)> func;\n  static ScalarOfVectorPtr construct(const func&);\n  //  typedef VectorXd (*c_func)(const VectorXd&);\n  //  static ScalarOfVectorPtr construct(const c_func&);\n};\nclass VectorOfVector\n{\npublic:\n  virtual Eigen::VectorXd operator()(const Eigen::VectorXd& x) const = 0;\n  Eigen::VectorXd call(const Eigen::VectorXd& x) const\n  {\n    return operator()(x);\n  }\n  virtual ~VectorOfVector()\n  {\n  }\n  typedef std::function<Eigen::VectorXd(Eigen::VectorXd)> func;\n  static VectorOfVectorPtr construct(const func&);\n  //  typedef VectorXd (*c_func)(const VectorXd&);\n  //  static VectorOfVectorPtr construct(const c_func&);\n};\nclass MatrixOfVector\n{\npublic:\n  virtual Eigen::MatrixXd operator()(const Eigen::VectorXd& x) const = 0;\n  Eigen::MatrixXd call(const Eigen::VectorXd& x) const\n  {\n    return operator()(x);\n  }\n  virtual ~MatrixOfVector()\n  {\n  }\n  typedef std::function<Eigen::MatrixXd(Eigen::VectorXd)> func;\n  static MatrixOfVectorPtr construct(const func&);\n  //  typedef VectorMatrixXd (*c_func)(const VectorXd&);\n  //  static MatrixOfVectorPtr construct(const c_func&);\n};\n\nEigen::VectorXd calcForwardNumGrad(const ScalarOfVector& f, const Eigen::VectorXd& x, double epsilon);\nEigen::MatrixXd calcForwardNumJac(const VectorOfVector& f, const Eigen::VectorXd& x, double epsilon);\nvoid calcGradAndDiagHess(const ScalarOfVector& f, const Eigen::VectorXd& x, double epsilon, double& y,\n                         Eigen::VectorXd& grad, Eigen::VectorXd& hess);\nvoid calcGradHess(ScalarOfVectorPtr f, const Eigen::VectorXd& x, double epsilon, double& y, Eigen::VectorXd& grad,\n                  Eigen::MatrixXd& hess);\nVectorOfVectorPtr forwardNumGrad(ScalarOfVectorPtr f, double epsilon);\nMatrixOfVectorPtr forwardNumJac(VectorOfVectorPtr f, double epsilon);\n}\n", "meta": {"hexsha": "388d30562f13d76d70477a1e18ca10714117d0eb", "size": 2489, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "moveit_planners/trajopt/trajopt_sco/include/trajopt_sco/num_diff.hpp", "max_stars_repo_name": "adam-vonderviszt/moveit", "max_stars_repo_head_hexsha": "b18b8c66963907aa6d03cbee4450fc3d6e740162", "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_planners/trajopt/trajopt_sco/include/trajopt_sco/num_diff.hpp", "max_issues_repo_name": "adam-vonderviszt/moveit", "max_issues_repo_head_hexsha": "b18b8c66963907aa6d03cbee4450fc3d6e740162", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "moveit_planners/trajopt/trajopt_sco/include/trajopt_sco/num_diff.hpp", "max_forks_repo_name": "adam-vonderviszt/moveit", "max_forks_repo_head_hexsha": "b18b8c66963907aa6d03cbee4450fc3d6e740162", "max_forks_repo_licenses": ["BSD-3-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.1125, "max_line_length": 114, "alphanum_fraction": 0.7392527119, "num_tokens": 616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2557022309188039}}
{"text": "/**\n    anest.cc\n    Purpose: Perform the Displacement Method of Analysis\n    for structural analysis.\n\n    @author Adolfo Correa\n    @version 0.1 02/03/20\n*/\n\n#include<iostream>\n#include<vector>\n#include <armadillo>\n#include <fstream>\n#include <string>\n\nusing namespace std;\nusing namespace arma;\n\nvoid preparq(int, int, int, int, int);\n// void nos(int nno, int nnv, vector<double> x);\n\nvoid nos(int nno, int nnv, vector<double> x, \\\nvector<double> y, vector<vector<double>> fa, \\\nvector<vector<int>> d, vector<vector<int>> v, \\\nvector<int> nv, int gln);\n\nvoid testing_armadillo(void);\n\nint main(int argc, char* argv[])\n{\n\tint nno, nel, ngl, nnv, gln, nelt, nelp, \\\n\tnll, ntc = nno = nel = ngl = nnv = gln = nelt \\\n\t= nelp = nll = 0;\t\n\n\tvector<int> nv, te, nc;\n\n\t/// Vector 2D\n\tvector<vector<int>> no, g, v, d, il;\n\tvector<double> x, y, e, a, iz, ra, fp, f, u, \\\n\tqx, qy;\n\t/// Vector 2D\n\tvector<vector<double>> fa, sg, esf;\n\n/// Read input files\n\tpreparq(nno, nel, ntc, ngl, gln);\n\n\tnno = nel = 4; ntc = 3; gln = 3; ngl = gln * nno;\n\n// Dimensionar vetores e matrizes\n// matrix.resize(M, vector<int>(N, default_value));\n\n/**\n* \\brief Initialize the variables\n*/\n\td.resize(nno, vector<int>(gln, 0));\n\tv.resize(nno, vector<int>(gln, 0));\n\tno.resize(2, vector<int>(nel, 0));\n\tg.resize(nel, vector<int>(2*gln, 0));\n\til.resize(nel, vector<int>(2*gln, 0));\n\n\tfa.resize(nno, vector<double>(gln, 0));\n\tesf.resize(6, vector<double>(nel, 0));\n\tx.resize(nno, 0);\n\ty.resize(nno, 0);\n\tnv.resize(nno, 0);\n\tte.resize(nel, 0);\n\tqx.resize(nel, 0);\n\tqy.resize(nel, 0);\n\te.resize(ntc, 0);\n\ta.resize(ntc, 0);\n\tiz.resize(ntc, 0);\n\tfp.resize(nel, 0);\n\tnc.resize(nel, 0);\n\n\n//\tnos(nno, nnv, x);\n\tnos(nno, nnv, x, y, fa, d, v, nv, gln);\n\t\n\t/// Testing Armadillo library\n\ttesting_armadillo();\n\n\t\n\n\treturn 0;\n}\n\nvoid preparq(int nno, int nel, int ntc, int ngl, int gln)\n{\n\tcout<<\"Reading input files\"<<endl;\n\tifstream file;\n\tofstream auxFile;\n\tstring line, filename = \"exemplo\";\n\tfile.open(filename);\n\tauxFile.open(\"anest.dat\");\n\n\t// Read lines of input file\n\tfor(int i = 0; !file.eof(); i++)\n\t{\n\t\t//file.get(line);\t\n\t\tgetline(file, line);\n\t\tcout<<line<<endl;\n\t\tif(line.substr(0,1) != \";\") auxFile<<line<<endl;\n\t}\n\n\tfile.close();\n\tauxFile.close();\n\n}\n\n/**\n * Read the nodes coordinates of the structure from\n * the input file.\n *\n * @param[in] nno number of nodes\n * @param[in] gln degree of freedom per node\n * @param[out] x x-coordinates of the nodes\n * @param[out] y y-coordinates of the nodes\n */\nvoid nos(int nno, int nnv, vector<double> x, \\\nvector<double> y, vector<vector<double>> fa, \\\nvector<vector<int>> d, vector<vector<int>> v, \\\nvector<int> nv, int gln)\n{\n\tcout<<\"Reading nos\"<<endl;\n} \n\n/**\n * Create two matrices with random values \n * and multiply them\n *\n * @param void.\n * @return none, only print on the screen.\n */\nvoid testing_armadillo(void)\n{\n\tcout<<endl<<\"Testing armadillo::mat\"<<endl<<endl;\n\n\tmat A(4, 5, fill::randu); ///< matrix A filled with random unsigned integers\n\tmat B(4, 5, fill::randn); ///< matrix B filled with randoms integers\n\n\tcout<<\"A = \"<<A<<endl;\n\tcout<<\"B = \"<<B<<endl;\n\n\t/**\n\t  \\f[\n  \t    C = A \\cross B^T\n\t  \\f]\n\t*/\n\tcout<<\"A*B.t() = \"<<A*B.t()<<endl; ///< Plot the product of the two matrices\n\n}\n\n", "meta": {"hexsha": "82e185eaa8b4ea29c18561278479588b66dc855d", "size": 3221, "ext": "cc", "lang": "C++", "max_stars_repo_path": "anest.cc", "max_stars_repo_name": "fit087/displacement_method_of_analysis", "max_stars_repo_head_hexsha": "37e35c7387ddedbb0a4f3ba3f5a4bcfa3af2d215", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-28T22:57:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-28T22:57:25.000Z", "max_issues_repo_path": "anest.cc", "max_issues_repo_name": "fit087/displacement_method_of_analysis", "max_issues_repo_head_hexsha": "37e35c7387ddedbb0a4f3ba3f5a4bcfa3af2d215", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T00:16:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-22T09:23:32.000Z", "max_forks_repo_path": "anest.cc", "max_forks_repo_name": "fit087/displacement_method_of_analysis", "max_forks_repo_head_hexsha": "37e35c7387ddedbb0a4f3ba3f5a4bcfa3af2d215", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0522875817, "max_line_length": 77, "alphanum_fraction": 0.6280658181, "num_tokens": 1061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2557022309188039}}
{"text": "/**************************************************************************\\\n *   This file is part of CaSPER.                                          *\n *                                                                         *\n *   Copyright:                                                            *\n *   2009-2009 - Marco Correia <marco.v.correia@gmail.com>           *\n *                                                                         *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");       * \n *   you may not use this file except in compliance with the License.      * \n *   You may obtain a copy of the License at                               * \n *            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                    * \n *   \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,          * \n *   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/xpressive/xpressive.hpp>\n#include <libxml++/libxml++.h>\n#include <bindings/cpp/cpp.h>\n#include <bindings/cpp/print.h>\n\n#include <iostream>\n\n#include \"exprparser.h\"\n\nusing namespace boost::xpressive;\nusing namespace regex_constants;\nusing namespace Casperbind::cpp;\n\nExprParser::ExprParser()\n{\n\tinteger\t= +digit;\n\tboolean\t= as_xpr(\"true\") | \"false\";\n\tid\t\t= alpha >> *alnum;\n\n\teNeg = \"neg(\" >> by_ref(integerExpr) >> \")\";\n\teAbs = \"abs(\" >> by_ref(integerExpr) >> \")\";\n\teAdd = \"add(\" >> by_ref(integerExpr) >> \",\"\n\t\t\t\t\t\t\t\t\t >> by_ref(integerExpr) >> \")\";\n\teSub\t= \"sub(\" >> by_ref(integerExpr) >> \",\"\n\t\t\t\t\t\t\t\t\t >> by_ref(integerExpr) >> \")\";\n\teMul\t= \"mul(\" >> by_ref(integerExpr) >> \",\"\n\t\t\t\t\t\t\t\t\t >> by_ref(integerExpr) >> \")\";\n\teDiv\t= \"div(\" >> by_ref(integerExpr) >> \",\"\n\t\t\t\t\t\t\t\t\t >> by_ref(integerExpr) >> \")\";\n\teMod\t= \"mod(\" >> by_ref(integerExpr) >> \",\"\n\t\t\t\t\t\t\t\t\t >> by_ref(integerExpr) >> \")\";\n\tePow\t= \"pow(\" >> by_ref(integerExpr) >> \",\"\n\t\t\t\t\t\t\t\t\t >> by_ref(integerExpr) >> \")\";\n\teMin\t= \"min(\" >> by_ref(integerExpr) >> \",\"\n\t\t\t\t\t\t\t\t\t >> by_ref(integerExpr) >> \")\";\n\teMax\t= \"max(\" >> by_ref(integerExpr) >> \",\"\n\t\t\t\t\t\t\t\t\t >> by_ref(integerExpr) >> \")\";\n\teIf\t= \"if(\" >>  by_ref(boolExpr) >> \",\"\n\t\t\t\t\t\t\t\t\t>> by_ref(integerExpr) >> \",\"\n\t\t\t\t\t\t\t\t\t>> by_ref(integerExpr)>> \")\";\n\n\tintegerExpr = integer | id | eNeg | eAbs | eAdd | eSub\n\t\t\t| eMul | eDiv | eMod | ePow | eMin | eMax | eIf;\n\n\tpNot= \"not(\" >> by_ref(boolExpr) >> \")\";\n\tpAnd= \"and(\" >> by_ref(boolExpr) >> \",\" >> by_ref(boolExpr) >> \")\";\n\tpOr\t= \"or(\" >> by_ref(boolExpr) >> \",\" >> by_ref(boolExpr) >> \")\";\n\tpXOr= \"xor(\" >> by_ref(boolExpr) >> \",\"\t>> by_ref(boolExpr) >> \")\";\n\tpIff= \"iff(\" >> by_ref(boolExpr) >> \",\"\t>> by_ref(boolExpr) >> \")\";\n\tpEq\t= \"eq(\" >> integerExpr >> \",\" >> integerExpr >> \")\";\n\tpNe\t= \"ne(\" >> integerExpr >> \",\" >> integerExpr >> \")\";\n\tpGe\t= \"ge(\" >> integerExpr >> \",\" >> integerExpr >> \")\";\n\tpGt\t= \"gt(\" >> integerExpr >> \",\" >> integerExpr >> \")\";\n\tpLe\t= \"le(\" >> integerExpr >> \",\" >> integerExpr >> \")\";\n\tpLt\t= \"lt(\" >> integerExpr >> \",\" >> integerExpr >> \")\";\n\n\tboolExpr = boolean | pNot | pAnd | pOr | pXOr | pIff | pEq\n\t\t\t| pNe | pGe | pGt | pLe | pLt;\n}\n\nSharedSymbol ExprParser::parse(const std::string& s,\n\t\tconst std::map<std::string,casperbind::cpp::SharedSymbol>& mpars) const\n{\n\tsmatch what;\n    if (!regex_match( s, what, boolExpr))\n      throw xmlpp::validity_error(\"expected boolean expression or predicate : \"+s);\n\n    assert(what.nested_results().size()==1);\n\n    return parseBoolExpression(what,mpars);\n}\n\nSharedSymbol ExprParser::parseBoolExpression(const smatch& what,\n\t\tconst std::map<std::string,casperbind::cpp::SharedSymbol>& mpars) const\n{\n\tassert(what.nested_results().size()==1);\n\n\tsmatch::nested_results_type::const_iterator begin = what.nested_results().begin();\n\tsmatch::nested_results_type::const_iterator end = what.nested_results().end();\n\n\tif (begin->regex_id() == boolean.regex_id())\n\t{\n\t\tif (begin->str() == \"true\")\n\t\t\treturn int(1);\n\t\telse\n\t\tif (begin->str() == \"false\")\n\t\t\treturn int(0);\n\t\tassert(0);\n\t}\n\telse\n\tif (begin->regex_id() == pNot.regex_id())\n\t{\n\t\tSymbolArray pars(1);\n\t\tpars[0] = parseBoolExpression(*begin->nested_results().begin(),mpars);\n\t\treturn Predicate(Predicate::pNot,pars);\n\t}\n\telse\n\tif (begin->regex_id() == pAnd.regex_id() or\n\t\tbegin->regex_id() == pOr.regex_id() or\n\t\tbegin->regex_id() == pXOr.regex_id() or\n\t\tbegin->regex_id() == pIff.regex_id())\n\t{\n\t\tSymbolArray pars(2);\n\t\tpars[0] = parseBoolExpression(*begin->nested_results().begin(),mpars);\n\t\tpars[1] = parseBoolExpression(*++begin->nested_results().begin(),mpars);\n\t\tif (begin->regex_id() == pAnd.regex_id())\n\t\t\treturn Predicate(Predicate::pAnd,pars);\n\t\telse\n\t\tif (begin->regex_id() == pOr.regex_id())\n\t\t\treturn Predicate(Predicate::pOr,pars);\n\t\telse\n\t\tif (begin->regex_id() == pXOr.regex_id())\n\t\t\treturn Predicate(Predicate::pXOr,pars);\n\t\telse\n\t\tif (begin->regex_id() == pIff.regex_id())\n\t\t\treturn Predicate(Predicate::pIff,pars);\n\t}\n\telse\n\tif (begin->regex_id() == pEq.regex_id() or\n\t\tbegin->regex_id() == pNe.regex_id() or\n\t\tbegin->regex_id() == pGe.regex_id() or\n\t\tbegin->regex_id() == pGt.regex_id() or\n\t\tbegin->regex_id() == pLe.regex_id() or\n\t\tbegin->regex_id() == pLt.regex_id())\n\t{\n\t\tSymbolArray pars(2);\n\t\tpars[0] = parseIntExpression(*begin->nested_results().begin(),mpars);\n\t\tpars[1] = parseIntExpression(*++begin->nested_results().begin(),mpars);\n\t\tif (begin->regex_id() == pEq.regex_id())\n\t\t\treturn Predicate(Predicate::pEqual,pars);\n\t\telse\n\t\tif (begin->regex_id() == pNe.regex_id())\n\t\t\treturn Predicate(Predicate::pDistinct,pars);\n\t\telse\n\t\tif (begin->regex_id() == pGe.regex_id())\n\t\t\treturn Predicate(Predicate::pGreaterEqual,pars);\n\t\telse\n\t\tif (begin->regex_id() == pGt.regex_id())\n\t\t\treturn Predicate(Predicate::pGreater,pars);\n\t\telse\n\t\tif (begin->regex_id() == pLe.regex_id())\n\t\t\treturn Predicate(Predicate::pLessEqual,pars);\n\t\telse\n\t\tif (begin->regex_id() == pLt.regex_id())\n\t\t\treturn Predicate(Predicate::pLess,pars);\n\t}\n\tassert(0);\n}\n\n\nSharedSymbol ExprParser::parseIntExpression(const smatch& what,\n\t\tconst std::map<std::string,casperbind::cpp::SharedSymbol>& mpars) const\n{\n\tassert(what.nested_results().size()==1);\n\n\tsmatch::nested_results_type::const_iterator begin = what.nested_results().begin();\n\tsmatch::nested_results_type::const_iterator end = what.nested_results().end();\n\n\tassert(what.nested_results().size()==1);\n\n\tif (begin->regex_id() == integer.regex_id())\n\t\treturn int(atoi(begin->str().c_str()));\n\telse\n\tif (begin->regex_id() == id.regex_id())\n\t{\n\t\tstd::map<std::string,casperbind::cpp::SharedSymbol>::const_iterator\n\t\t\t\tit = mpars.find(begin->str());\n\t\tif (it==mpars.end())\n\t\t\tthrow xmlpp::validity_error(\"undeclared variable appearing in expression : \"+begin->str());\n\t\treturn it->second;\n\t}\n\telse\n\tif (begin->regex_id() == eNeg.regex_id() or\n\t\tbegin->regex_id() == eAbs.regex_id())\n\t{\n\t\tSymbolArray pars(1);\n\t\tpars[0] = parseIntExpression(*begin->nested_results().begin(),mpars);\n\t\tif (begin->regex_id() == eNeg.regex_id())\n\t\t\treturn Expression(Expression::eSym,pars);\n\t\telse\n\t\tif (begin->regex_id() == eAbs.regex_id())\n\t\t\treturn Expression(Expression::eAbs,pars);\n\t}\n\telse\n\tif (begin->regex_id() == eAdd.regex_id() or\n\t\tbegin->regex_id() == eSub.regex_id() or\n\t\tbegin->regex_id() == eMul.regex_id() or\n\t\tbegin->regex_id() == eDiv.regex_id() or\n\t\tbegin->regex_id() == eMod.regex_id() or\n\t\tbegin->regex_id() == ePow.regex_id() or\n\t\tbegin->regex_id() == eMin.regex_id() or\n\t\tbegin->regex_id() == eMax.regex_id())\n\t{\n\t\tSymbolArray pars(2);\n\t\tpars[0] = parseIntExpression(*begin->nested_results().begin(),mpars);\n\t\tpars[1] = parseIntExpression(*++begin->nested_results().begin(),mpars);\n\t\tif (begin->regex_id() == eAdd.regex_id())\n\t\t\treturn Expression(Expression::eAdd,pars);\n\t\telse\n\t\tif (begin->regex_id() == eSub.regex_id())\n\t\t\treturn Expression(Expression::eSub,pars);\n\t\telse\n\t\tif (begin->regex_id() == eMul.regex_id())\n\t\t\treturn Expression(Expression::eMul,pars);\n\t\telse\n\t\tif (begin->regex_id() == eDiv.regex_id())\n\t\t\treturn Expression(Expression::eDiv,pars);\n\t\telse\n\t\tif (begin->regex_id() == eMod.regex_id())\n\t\t\treturn Expression(Expression::eMod,pars);\n\t\telse\n\t\tif (begin->regex_id() == ePow.regex_id())\n\t\t\treturn Expression(Expression::ePow,pars);\n\t\telse\n\t\tif (begin->regex_id() == eMin.regex_id())\n\t\t\treturn Expression(Expression::eMin,pars);\n\t\telse\n\t\tif (begin->regex_id() == eMax.regex_id())\n\t\t\treturn Expression(Expression::eMax,pars);\n\t}\n\telse\n\tif (begin->regex_id() == eIf.regex_id())\n\t{\n\t\tSymbolArray pars(3);\n\t\tpars[0] = parseBoolExpression(*begin->nested_results().begin(),mpars);\n\t\tpars[1] = parseIntExpression(*++begin->nested_results().begin(),mpars);\n\t\tpars[2] = parseIntExpression(*++(++begin->nested_results().begin()),mpars);\n\t\treturn Expression(Expression::eIfThenElse,pars);\n\t}\n\n\tassert(0);\n}\n\n#if 0\nint main(int argc, char** argv)\n{\n\tstd::map<std::string,casperbind::cpp::SharedSymbol> mpars;\n\tmpars[\"V0\"] = casperbind::cpp::Variable(casperbind::cpp::IntDomain(casperbind::cpp::IntRange(1,10)));\n\tmpars[\"V1\"] = casperbind::cpp::Variable(casperbind::cpp::IntDomain(casperbind::cpp::IntRange(2,4)));\n\n\tstd::string s(argv[1]);\n\tstd::cout << \"input string is [\" << s << \"]\" << std::endl;\n\tExprParser e;\n\tSharedSymbol o = e.parse(s,mpars);\n\tstd::cout << o << std::endl;\n}\n#endif\n", "meta": {"hexsha": "8e428d4fe9a00824ef2041c687ebf40647e3fb3d", "size": 9572, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bindings/xcsp/exprparser.cpp", "max_stars_repo_name": "marcovc/casper", "max_stars_repo_head_hexsha": "752ad1c9ecb9408b0a3719a2c8727b87e2d158cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-20T17:04:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-20T17:04:06.000Z", "max_issues_repo_path": "bindings/xcsp/exprparser.cpp", "max_issues_repo_name": "marcovc/casper", "max_issues_repo_head_hexsha": "752ad1c9ecb9408b0a3719a2c8727b87e2d158cf", "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": "bindings/xcsp/exprparser.cpp", "max_forks_repo_name": "marcovc/casper", "max_forks_repo_head_hexsha": "752ad1c9ecb9408b0a3719a2c8727b87e2d158cf", "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.984962406, "max_line_length": 102, "alphanum_fraction": 0.603113247, "num_tokens": 2657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.25562338723615996}}
{"text": "/*\n * Copyright (c) 2020 Andrew Price\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 * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its\n *    contributors may be used to endorse or promote products derived from\n *    this software without specific prior written permission.\n *\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\n#include <Eigen/Eigenvalues>\n#include <Eigen/SparseCore>\n//#include <Spectra/GenEigsSolver.h>\n//#include <Spectra/MatOp/SparseGenMatProd.h>\n//#include <Spectra/SymEigsSolver.h>\n//#include <Spectra/MatOp/SparseSymMatProd.h>\n\n#include \"mps_voxels/video_graph.h\"\n#include \"mps_voxels/graph_matrix_utils.h\"\n#include <mps_msgs/SegmentGraph.h>\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/graphviz.hpp>\n\n#include <ros/ros.h>\n\n\ntemplate <class WeightMap>\nclass edge_writer {\npublic:\n\tedge_writer(WeightMap w) : wm(w) {}\n\ttemplate <class Edge>\n\tvoid operator()(std::ostream &out, const Edge& e) const {\n\t\tout << \"[penwidth=\\\"\" << wm[e]*4.0 << \"\\\"]\";\n\t}\nprivate:\n\tWeightMap wm;\n};\n\ntemplate <class WeightMap>\ninline edge_writer<WeightMap>\nmake_edge_writer(WeightMap w) {\n\treturn edge_writer<WeightMap>(w);\n}\n\nstd::string node_name(const NodeProperties& np) {return \"f\" + std::to_string(np.t.toSec()) + \"c\" + std::to_string(np.leafID);}\n\nvoid print(std::ostream& out, const VideoSegmentationGraph& G)\n{\n\tout << \"graph G {\\n\";\n\n\tstd::map<ros::Time, std::vector<VideoSegmentationGraph::vertex_descriptor>> frames;\n\tfor (VideoSegmentationGraph::vertex_descriptor vd : make_range(boost::vertices(G)))\n\t{\n\t\tframes[G[vd].t].push_back(vd);\n\t}\n\n\tfor (const auto& frame : frames)\n\t{\n\t\tout << \"subgraph cluster_\" << frame.first << \" {\\n\";\n\t\tout << \"label=\\\"Frame \" << frame.first << \"\\\";\\n\";\n\t\tfor (const VideoSegmentationGraph::vertex_descriptor vd : frame.second)\n\t\t{\n\t\t\tconst NodeProperties& np = G[vd];\n\t\t\tout << node_name(np) << \" [label=\\\"\" << np.leafID << \"\\\"];\\n\";\n\t\t}\n\t\tout << \"}\\n\";\n\t}\n\n\tfor (VideoSegmentationGraph::edge_descriptor ed : make_range(boost::edges(G)))\n\t{\n\t\tVideoSegmentationGraph::vertex_descriptor u = boost::source(ed, G);\n\t\tVideoSegmentationGraph::vertex_descriptor v = boost::target(ed, G);\n\n\t\tconst EdgeProperties& ep = G[ed];\n\t\tconst NodeProperties& npu = G[u];\n\t\tconst NodeProperties& npv = G[v];\n\t\tout << node_name(npu) << \"--\" << node_name(npv) << \" [penwidth=\\\"\" << 4.0*ep.affinity << \"\\\"];\\n\";\n\t}\n\n\tout << \"}\\n\";\n}\n\nint main(int argc, char* argv[])\n{\n\tros::init(argc, argv, \"test_graph_segmentation\");\n\tros::NodeHandle nh, pnh(\"~\");\n\n\tros::ServiceClient segmentClient = nh.serviceClient<mps_msgs::SegmentGraph>(\"/segment_graph\");\n\tif (!segmentClient.waitForExistence(ros::Duration(3)))\n\t{\n\t\tROS_ERROR(\"Segmentation server not connected.\");\n\t\treturn -1;\n\t}\n\n\tVideoSegmentationGraph G;\n\n\tstd::map<std::pair<ros::Time, int>, VideoSegmentationGraph::vertex_descriptor> segmentToNode;\n\tstd::vector<NodeProperties> nps{NodeProperties({ros::Time(0), 0}), NodeProperties({ros::Time(0), 1}), NodeProperties({ros::Time(0), 2}), NodeProperties({ros::Time(1), 0}), NodeProperties({ros::Time(1), 1})};\n\tfor (const auto& np : nps)\n\t{\n\t\t// Add leaf i to graph\n\t\t// NB: labels start from 1, as 0 is background, so tree[0] = labels[1]\n\t\tVideoSegmentationGraph::vertex_descriptor v = boost::add_vertex(np, G);\n\t\tsegmentToNode.insert({{np.t, np.leafID}, v});\n\t}\n\n\tboost::add_edge(segmentToNode[{ros::Time(0), 0}], segmentToNode[{ros::Time(0), 1}], {1.0/1.0}, G);\n\tboost::add_edge(segmentToNode[{ros::Time(0), 0}], segmentToNode[{ros::Time(0), 2}], {1.0/10.0}, G);\n\tboost::add_edge(segmentToNode[{ros::Time(0), 1}], segmentToNode[{ros::Time(0), 2}], {1.0/10.0}, G);\n\tboost::add_edge(segmentToNode[{ros::Time(1), 0}], segmentToNode[{ros::Time(1), 1}], {1.0/15.0}, G);\n\tboost::add_edge(segmentToNode[{ros::Time(0), 2}], segmentToNode[{ros::Time(1), 1}], {1.0/2.0}, G);\n\tboost::add_edge(segmentToNode[{ros::Time(0), 0}], segmentToNode[{ros::Time(1), 0}], {1.0/2.0}, G);\n\tboost::add_edge(segmentToNode[{ros::Time(0), 1}], segmentToNode[{ros::Time(1), 0}], {1.0/2.0}, G);\n\n\tprint(std::cerr, G);//, boost::make_label_writer(boost::get(&NodeProperties::leafID, G)), make_edge_writer(boost::get(&EdgeProperties::affinity, G)));\n\n\t{\n\t\tEigen::MatrixXd laplacian = getLaplacianNormalized(G);\n\t\tconst int numCells = laplacian.rows();\n\t\tstd::cerr << \"Segmenting subgraph with \" << numCells << \" vertices (out of \" << boost::num_vertices(G) << \").\"\n\t\t          << std::endl;\n\t\tEigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver;\n\t\tsolver.compute(laplacian, Eigen::ComputeEigenvectors);\n\t\tEigen::VectorXd eigenvalues = solver.eigenvalues();\n\t\tEigen::MatrixXd eigenvectors = solver.eigenvectors();\n\t\tstd::cerr << eigenvalues.transpose() << std::endl;\n\t\tstd::cerr << eigenvectors << std::endl;\n\t}\n\n//\t{\n//\t\tEigen::SparseMatrix<double> laplacian = getLaplacianSparseNormalized(G);\n//\t\tusing SparseMatProd = Spectra::SparseGenMatProd<double>; // Spectra::SparseSymMatProd<double>\n//\t\tSparseMatProd op(laplacian);\n//\t\tSpectra::GenEigsSolver<double, Spectra::LARGEST_MAGN, SparseMatProd> eigs(&op, 3, 5);\n//\t\teigs.init();\n//\t\tint nconv = eigs.compute();\n//\t\tif (eigs.info() == Spectra::SUCCESSFUL)\n//\t\t{\n//\t\t\tstd::cerr << nconv << \"\\n\" << eigs.eigenvectors() << std::endl;\n//\t\t}\n//\t\telse\n//\t\t{\n//\t\t\tROS_WARN(\"Failed to compute eigenvectors. Clusterign aborted.\");\n//\t\t}\n//\t}\n\n\t{\n\t\tEigen::SparseMatrix<double> adj = getAdjacencySparse(G);\n\t\tmps_msgs::SegmentGraphRequest req;\n\t\tfor (const auto& triplet : to_triplets(adj))\n\t\t{\n\t\t\tstd::cerr << triplet.row() << \",\" << triplet.col() << \",\" << triplet.value() << std::endl;\n\t\t\treq.adjacency.row_index.push_back(triplet.row());\n\t\t\treq.adjacency.col_index.push_back(triplet.col());\n\t\t\treq.adjacency.value.push_back(triplet.value());\n\t\t}\n\t\treq.num_labels = 2;\n\n\t\tfor (const std::string& alg : std::vector<std::string>{\"spectral\", \"dbscan\"})\n\t\t{\n\t\t\treq.algorithm = alg;\n\n\t\t\tmps_msgs::SegmentGraphResponse resp;\n\t\t\tsegmentClient.call(req, resp);\n\t\t\tstd::cerr << resp << std::endl;\n\n\t\t}\n\t}\n\n\treturn 0;\n}", "meta": {"hexsha": "0601fa2b0c1925837bb8d21ff21e62d219c5d855", "size": 7264, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mps_voxels/src/test_graph_segmentation.cpp", "max_stars_repo_name": "UM-ARM-Lab/multihypothesis_segmentation_tracking", "max_stars_repo_head_hexsha": "801d460afbf028100374c880bc684187ec8b909f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-10-31T21:42:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T12:56:02.000Z", "max_issues_repo_path": "mps_voxels/src/test_graph_segmentation.cpp", "max_issues_repo_name": "UM-ARM-Lab/multihypothesis_segmentation_tracking", "max_issues_repo_head_hexsha": "801d460afbf028100374c880bc684187ec8b909f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-11-11T03:46:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-11T03:46:08.000Z", "max_forks_repo_path": "mps_voxels/src/test_graph_segmentation.cpp", "max_forks_repo_name": "UM-ARM-Lab/multihypothesis_segmentation_tracking", "max_forks_repo_head_hexsha": "801d460afbf028100374c880bc684187ec8b909f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-02T12:32:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T12:32:21.000Z", "avg_line_length": 37.8333333333, "max_line_length": 208, "alphanum_fraction": 0.6928689427, "num_tokens": 2074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2555669675777183}}
{"text": "#ifndef STAN_MATH_PRIM_PROB_FRECHET_CDF_HPP\n#define STAN_MATH_PRIM_PROB_FRECHET_CDF_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/err.hpp>\n#include <stan/math/prim/fun/constants.hpp>\n#include <stan/math/prim/fun/exp.hpp>\n#include <stan/math/prim/fun/log.hpp>\n#include <stan/math/prim/fun/log1m.hpp>\n#include <stan/math/prim/fun/max_size.hpp>\n#include <stan/math/prim/fun/multiply_log.hpp>\n#include <stan/math/prim/fun/scalar_seq_view.hpp>\n#include <stan/math/prim/fun/size.hpp>\n#include <stan/math/prim/fun/size_zero.hpp>\n#include <stan/math/prim/fun/to_ref.hpp>\n#include <stan/math/prim/fun/value_of.hpp>\n#include <boost/random/weibull_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <stan/math/prim/functor/operands_and_partials.hpp>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\n\ntemplate <typename T_y, typename T_shape, typename T_scale,\n          require_all_not_nonscalar_prim_or_rev_kernel_expression_t<\n              T_y, T_shape, T_scale>* = nullptr>\nreturn_type_t<T_y, T_shape, T_scale> frechet_cdf(const T_y& y,\n                                                 const T_shape& alpha,\n                                                 const T_scale& sigma) {\n  using T_partials_return = partials_return_t<T_y, T_shape, T_scale>;\n  using T_y_ref = ref_type_t<T_y>;\n  using T_alpha_ref = ref_type_t<T_shape>;\n  using T_sigma_ref = ref_type_t<T_scale>;\n  using std::pow;\n  static const char* function = \"frechet_cdf\";\n  T_y_ref y_ref = y;\n  T_alpha_ref alpha_ref = alpha;\n  T_sigma_ref sigma_ref = sigma;\n\n  check_positive(function, \"Random variable\", y_ref);\n  check_positive_finite(function, \"Shape parameter\", alpha_ref);\n  check_positive_finite(function, \"Scale parameter\", sigma_ref);\n\n  if (size_zero(y_ref, alpha_ref, sigma_ref)) {\n    return 1.0;\n  }\n\n  T_partials_return cdf(1.0);\n  operands_and_partials<T_y_ref, T_alpha_ref, T_sigma_ref> ops_partials(\n      y_ref, alpha_ref, sigma_ref);\n\n  scalar_seq_view<T_y> y_vec(y_ref);\n  scalar_seq_view<T_scale> sigma_vec(sigma_ref);\n  scalar_seq_view<T_shape> alpha_vec(alpha_ref);\n  size_t N = max_size(y_ref, sigma_ref, alpha_ref);\n\n  for (size_t n = 0; n < N; n++) {\n    const T_partials_return y_dbl = y_vec.val(n);\n    const T_partials_return sigma_dbl = sigma_vec.val(n);\n    const T_partials_return alpha_dbl = alpha_vec.val(n);\n    const T_partials_return pow_n = pow(sigma_dbl / y_dbl, alpha_dbl);\n    const T_partials_return cdf_n = exp(-pow_n);\n\n    cdf *= cdf_n;\n\n    if (!is_constant_all<T_y>::value) {\n      ops_partials.edge1_.partials_[n] += pow_n * alpha_dbl / y_dbl;\n    }\n    if (!is_constant_all<T_shape>::value) {\n      ops_partials.edge2_.partials_[n] += pow_n * log(y_dbl / sigma_dbl);\n    }\n    if (!is_constant_all<T_scale>::value) {\n      ops_partials.edge3_.partials_[n] -= pow_n * alpha_dbl / sigma_dbl;\n    }\n  }\n\n  if (!is_constant_all<T_y>::value) {\n    for (size_t n = 0; n < stan::math::size(y); ++n) {\n      ops_partials.edge1_.partials_[n] *= cdf;\n    }\n  }\n  if (!is_constant_all<T_shape>::value) {\n    for (size_t n = 0; n < stan::math::size(alpha); ++n) {\n      ops_partials.edge2_.partials_[n] *= cdf;\n    }\n  }\n  if (!is_constant_all<T_scale>::value) {\n    for (size_t n = 0; n < stan::math::size(sigma); ++n) {\n      ops_partials.edge3_.partials_[n] *= cdf;\n    }\n  }\n  return ops_partials.build(cdf);\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "a6545afed46a9511266aa6d9a0a5e8dfffa6e603", "size": 3404, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/prob/frechet_cdf.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stan/math/prim/prob/frechet_cdf.hpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/prob/frechet_cdf.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3838383838, "max_line_length": 73, "alphanum_fraction": 0.6903642773, "num_tokens": 974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.25542162203524116}}
{"text": "//  Copyright John Maddock 2006.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_STATS_WEIBULL_HPP\r\n#define BOOST_STATS_WEIBULL_HPP\r\n\r\n// http://www.itl.nist.gov/div898/handbook/eda/section3/eda3668.htm\r\n// http://mathworld.wolfram.com/WeibullDistribution.html\r\n\r\n#include <boost/math/distributions/fwd.hpp>\r\n#include <boost/math/special_functions/gamma.hpp>\r\n#include <boost/math/special_functions/log1p.hpp>\r\n#include <boost/math/special_functions/expm1.hpp>\r\n#include <boost/math/distributions/detail/common_error_handling.hpp>\r\n#include <boost/math/distributions/complement.hpp>\r\n\r\n#include <utility>\r\n\r\nnamespace boost{ namespace math\r\n{\r\nnamespace detail{\r\n\r\ntemplate <class RealType, class Policy>\r\ninline bool check_weibull_shape(\r\n      const char* function,\r\n      RealType shape,\r\n      RealType* result, const Policy& pol)\r\n{\r\n   if((shape < 0) || !(boost::math::isfinite)(shape))\r\n   {\r\n      *result = policies::raise_domain_error<RealType>(\r\n         function,\r\n         \"Shape parameter is %1%, but must be > 0 !\", shape, pol);\r\n      return false;\r\n   }\r\n   return true;\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline bool check_weibull_x(\r\n      const char* function,\r\n      RealType const& x,\r\n      RealType* result, const Policy& pol)\r\n{\r\n   if((x < 0) || !(boost::math::isfinite)(x))\r\n   {\r\n      *result = policies::raise_domain_error<RealType>(\r\n         function,\r\n         \"Random variate is %1% but must be >= 0 !\", x, pol);\r\n      return false;\r\n   }\r\n   return true;\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline bool check_weibull(\r\n      const char* function,\r\n      RealType scale,\r\n      RealType shape,\r\n      RealType* result, const Policy& pol)\r\n{\r\n   return check_scale(function, scale, result, pol) && check_weibull_shape(function, shape, result, pol);\r\n}\r\n\r\n} // namespace detail\r\n\r\ntemplate <class RealType = double, class Policy = policies::policy<> >\r\nclass weibull_distribution\r\n{\r\npublic:\r\n   typedef RealType value_type;\r\n   typedef Policy policy_type;\r\n\r\n   weibull_distribution(RealType shape, RealType scale = 1)\r\n      : m_shape(shape), m_scale(scale)\r\n   {\r\n      RealType result;\r\n      detail::check_weibull(\"boost::math::weibull_distribution<%1%>::weibull_distribution\", scale, shape, &result, Policy());\r\n   }\r\n\r\n   RealType shape()const\r\n   {\r\n      return m_shape;\r\n   }\r\n\r\n   RealType scale()const\r\n   {\r\n      return m_scale;\r\n   }\r\nprivate:\r\n   //\r\n   // Data members:\r\n   //\r\n   RealType m_shape;     // distribution shape\r\n   RealType m_scale;     // distribution scale\r\n};\r\n\r\ntypedef weibull_distribution<double> weibull;\r\n\r\ntemplate <class RealType, class Policy>\r\ninline const std::pair<RealType, RealType> range(const weibull_distribution<RealType, Policy>& /*dist*/)\r\n{ // Range of permissible values for random variable x.\r\n   using boost::math::tools::max_value;\r\n   return std::pair<RealType, RealType>(0, max_value<RealType>());\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline const std::pair<RealType, RealType> support(const weibull_distribution<RealType, Policy>& /*dist*/)\r\n{ // Range of supported values for random variable x.\r\n   // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.\r\n   using boost::math::tools::max_value;\r\n   using boost::math::tools::min_value;\r\n   return std::pair<RealType, RealType>(min_value<RealType>(),  max_value<RealType>());\r\n   // A discontinuity at x == 0, so only support down to min_value.\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType pdf(const weibull_distribution<RealType, Policy>& dist, const RealType& x)\r\n{\r\n   BOOST_MATH_STD_USING  // for ADL of std functions\r\n\r\n   static const char* function = \"boost::math::pdf(const weibull_distribution<%1%>, %1%)\";\r\n\r\n   RealType shape = dist.shape();\r\n   RealType scale = dist.scale();\r\n\r\n   RealType result;\r\n   if(false == detail::check_weibull(function, scale, shape, &result, Policy()))\r\n      return result;\r\n   if(false == detail::check_weibull_x(function, x, &result, Policy()))\r\n      return result;\r\n\r\n   if(x == 0)\r\n   { // Special case, but x == min, pdf = 1 for shape = 1, \r\n      return 0;\r\n   }\r\n   result = exp(-pow(x / scale, shape));\r\n   result *= pow(x / scale, shape) * shape / x;\r\n\r\n   return result;\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType cdf(const weibull_distribution<RealType, Policy>& dist, const RealType& x)\r\n{\r\n   BOOST_MATH_STD_USING  // for ADL of std functions\r\n\r\n   static const char* function = \"boost::math::cdf(const weibull_distribution<%1%>, %1%)\";\r\n\r\n   RealType shape = dist.shape();\r\n   RealType scale = dist.scale();\r\n\r\n   RealType result;\r\n   if(false == detail::check_weibull(function, scale, shape, &result, Policy()))\r\n      return result;\r\n   if(false == detail::check_weibull_x(function, x, &result, Policy()))\r\n      return result;\r\n\r\n   result = -boost::math::expm1(-pow(x / scale, shape), Policy());\r\n\r\n   return result;\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType quantile(const weibull_distribution<RealType, Policy>& dist, const RealType& p)\r\n{\r\n   BOOST_MATH_STD_USING  // for ADL of std functions\r\n\r\n   static const char* function = \"boost::math::quantile(const weibull_distribution<%1%>, %1%)\";\r\n\r\n   RealType shape = dist.shape();\r\n   RealType scale = dist.scale();\r\n\r\n   RealType result;\r\n   if(false == detail::check_weibull(function, scale, shape, &result, Policy()))\r\n      return result;\r\n   if(false == detail::check_probability(function, p, &result, Policy()))\r\n      return result;\r\n\r\n   if(p == 1)\r\n      return policies::raise_overflow_error<RealType>(function, 0, Policy());\r\n\r\n   result = scale * pow(-boost::math::log1p(-p, Policy()), 1 / shape);\r\n\r\n   return result;\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType cdf(const complemented2_type<weibull_distribution<RealType, Policy>, RealType>& c)\r\n{\r\n   BOOST_MATH_STD_USING  // for ADL of std functions\r\n\r\n   static const char* function = \"boost::math::cdf(const weibull_distribution<%1%>, %1%)\";\r\n\r\n   RealType shape = c.dist.shape();\r\n   RealType scale = c.dist.scale();\r\n\r\n   RealType result;\r\n   if(false == detail::check_weibull(function, scale, shape, &result, Policy()))\r\n      return result;\r\n   if(false == detail::check_weibull_x(function, c.param, &result, Policy()))\r\n      return result;\r\n\r\n   result = exp(-pow(c.param / scale, shape));\r\n\r\n   return result;\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType quantile(const complemented2_type<weibull_distribution<RealType, Policy>, RealType>& c)\r\n{\r\n   BOOST_MATH_STD_USING  // for ADL of std functions\r\n\r\n   static const char* function = \"boost::math::quantile(const weibull_distribution<%1%>, %1%)\";\r\n\r\n   RealType shape = c.dist.shape();\r\n   RealType scale = c.dist.scale();\r\n   RealType q = c.param;\r\n\r\n   RealType result;\r\n   if(false == detail::check_weibull(function, scale, shape, &result, Policy()))\r\n      return result;\r\n   if(false == detail::check_probability(function, q, &result, Policy()))\r\n      return result;\r\n\r\n   if(q == 0)\r\n      return policies::raise_overflow_error<RealType>(function, 0, Policy());\r\n\r\n   result = scale * pow(-log(q), 1 / shape);\r\n\r\n   return result;\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType mean(const weibull_distribution<RealType, Policy>& dist)\r\n{\r\n   BOOST_MATH_STD_USING  // for ADL of std functions\r\n\r\n   static const char* function = \"boost::math::mean(const weibull_distribution<%1%>)\";\r\n\r\n   RealType shape = dist.shape();\r\n   RealType scale = dist.scale();\r\n\r\n   RealType result;\r\n   if(false == detail::check_weibull(function, scale, shape, &result, Policy()))\r\n      return result;\r\n\r\n   result = scale * boost::math::tgamma(1 + 1 / shape, Policy());\r\n   return result;\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType variance(const weibull_distribution<RealType, Policy>& dist)\r\n{\r\n   RealType shape = dist.shape();\r\n   RealType scale = dist.scale();\r\n\r\n   static const char* function = \"boost::math::variance(const weibull_distribution<%1%>)\";\r\n\r\n   RealType result;\r\n   if(false == detail::check_weibull(function, scale, shape, &result, Policy()))\r\n   {\r\n      return result;\r\n   }\r\n   result = boost::math::tgamma(1 + 1 / shape, Policy());\r\n   result *= -result;\r\n   result += boost::math::tgamma(1 + 2 / shape, Policy());\r\n   result *= scale * scale;\r\n   return result;\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType mode(const weibull_distribution<RealType, Policy>& dist)\r\n{\r\n   BOOST_MATH_STD_USING  // for ADL of std function pow.\r\n\r\n   static const char* function = \"boost::math::mode(const weibull_distribution<%1%>)\";\r\n\r\n   RealType shape = dist.shape();\r\n   RealType scale = dist.scale();\r\n\r\n   RealType result;\r\n   if(false == detail::check_weibull(function, scale, shape, &result, Policy()))\r\n   {\r\n      return result;\r\n   }\r\n   if(shape <= 1)\r\n      return 0;\r\n   result = scale * pow((shape - 1) / shape, 1 / shape);\r\n   return result;\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType median(const weibull_distribution<RealType, Policy>& dist)\r\n{\r\n   BOOST_MATH_STD_USING  // for ADL of std function pow.\r\n\r\n   static const char* function = \"boost::math::median(const weibull_distribution<%1%>)\";\r\n\r\n   RealType shape = dist.shape(); // Wikipedia k\r\n   RealType scale = dist.scale(); // Wikipedia lambda\r\n\r\n   RealType result;\r\n   if(false == detail::check_weibull(function, scale, shape, &result, Policy()))\r\n   {\r\n      return result;\r\n   }\r\n   using boost::math::constants::ln_two;\r\n   result = scale * pow(ln_two<RealType>(), 1 / shape);\r\n   return result;\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType skewness(const weibull_distribution<RealType, Policy>& dist)\r\n{\r\n   BOOST_MATH_STD_USING  // for ADL of std functions\r\n\r\n   static const char* function = \"boost::math::skewness(const weibull_distribution<%1%>)\";\r\n\r\n   RealType shape = dist.shape();\r\n   RealType scale = dist.scale();\r\n\r\n   RealType result;\r\n   if(false == detail::check_weibull(function, scale, shape, &result, Policy()))\r\n   {\r\n      return result;\r\n   }\r\n   RealType g1, g2, g3, d;\r\n\r\n   g1 = boost::math::tgamma(1 + 1 / shape, Policy());\r\n   g2 = boost::math::tgamma(1 + 2 / shape, Policy());\r\n   g3 = boost::math::tgamma(1 + 3 / shape, Policy());\r\n   d = pow(g2 - g1 * g1, RealType(1.5));\r\n\r\n   result = (2 * g1 * g1 * g1 - 3 * g1 * g2 + g3) / d;\r\n   return result;\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType kurtosis_excess(const weibull_distribution<RealType, Policy>& dist)\r\n{\r\n   BOOST_MATH_STD_USING  // for ADL of std functions\r\n\r\n   static const char* function = \"boost::math::kurtosis_excess(const weibull_distribution<%1%>)\";\r\n\r\n   RealType shape = dist.shape();\r\n   RealType scale = dist.scale();\r\n\r\n   RealType result;\r\n   if(false == detail::check_weibull(function, scale, shape, &result, Policy()))\r\n      return result;\r\n\r\n   RealType g1, g2, g3, g4, d, g1_2, g1_4;\r\n\r\n   g1 = boost::math::tgamma(1 + 1 / shape, Policy());\r\n   g2 = boost::math::tgamma(1 + 2 / shape, Policy());\r\n   g3 = boost::math::tgamma(1 + 3 / shape, Policy());\r\n   g4 = boost::math::tgamma(1 + 4 / shape, Policy());\r\n   g1_2 = g1 * g1;\r\n   g1_4 = g1_2 * g1_2;\r\n   d = g2 - g1_2;\r\n   d *= d;\r\n\r\n   result = -6 * g1_4 + 12 * g1_2 * g2 - 3 * g2 * g2 - 4 * g1 * g3 + g4;\r\n   result /= d;\r\n   return result;\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType kurtosis(const weibull_distribution<RealType, Policy>& dist)\r\n{\r\n   return kurtosis_excess(dist) + 3;\r\n}\r\n\r\n} // namespace math\r\n} // namespace boost\r\n\r\n// This include must be at the end, *after* the accessors\r\n// for this distribution have been defined, in order to\r\n// keep compilers that support two-phase lookup happy.\r\n#include <boost/math/distributions/detail/derived_accessors.hpp>\r\n\r\n#endif // BOOST_STATS_WEIBULL_HPP\r\n\r\n\r\n", "meta": {"hexsha": "c8eb20cefdd4faa89b621808597eb30078377afb", "size": 11981, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Compiler/boost/boost/math/distributions/weibull.hpp", "max_stars_repo_name": "davidov541/MiniC", "max_stars_repo_head_hexsha": "d3b16a1568b97a4d801880b110a8be04fe848adb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-12-29T07:21:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-29T10:47:38.000Z", "max_issues_repo_path": "LibsExternes/Includes/boost/math/distributions/weibull.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": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LibsExternes/Includes/boost/math/distributions/weibull.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": 30.8788659794, "max_line_length": 126, "alphanum_fraction": 0.6584592271, "num_tokens": 3130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2552347774852795}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n///   Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand\n///   Copyright 2009 and onward LRI    UMR 8623 CNRS/Univ Paris Sud XI\n///\n///          Distributed under the Boost Software License, Version 1.0\n///                 See accompanying file LICENSE.txt or copy at\n///                     http://www.boost.org/LICENSE_1_0.txt\n//////////////////////////////////////////////////////////////////////////////\n#ifndef NT2_TOOLBOX_ARITHMETIC_FUNCTION_SIMD_COMMON_RDIVIDE_HPP_INCLUDED\n#define NT2_TOOLBOX_ARITHMETIC_FUNCTION_SIMD_COMMON_RDIVIDE_HPP_INCLUDED\n#include <nt2/sdk/meta/upgrade.hpp>\n#include <nt2/sdk/constant/digits.hpp>\n#include <boost/fusion/tuple.hpp>\n#include <nt2/sdk/meta/strip.hpp>\n#include <nt2/include/functions/is_eqz.hpp>\n#include <nt2/include/functions/group.hpp>\n#include <nt2/include/functions/split.hpp>\n#include <nt2/include/functions/toint.hpp>\n#include <nt2/include/functions/tofloat.hpp>\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is arithmetic_\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::rdivide_, tag::cpu_,\n                          (A0)(X),\n                          ((simd_<arithmetic_<A0>,X>))\n                          ((simd_<arithmetic_<A0>,X>))\n                         );\n\nnamespace nt2 { namespace ext\n{\n  template<class X, class Dummy>\n  struct call<tag::rdivide_(tag::simd_<tag::arithmetic_, X> ,\n                            tag::simd_<tag::arithmetic_, X> ),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0>\n    struct result<This(A0,A0)>\n      : meta::strip<A0>{};//\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      const A0 iseqza1 = is_eqz(a1);\n      return (a0-(iseqza1&a0))/(a1+(iseqza1&One<A0>()));\n    }\n  };\n} }\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is int8_\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::rdivide_, tag::cpu_,\n                          (A0)(X),\n                          ((simd_<int8_<A0>,X>))\n                          ((simd_<int8_<A0>,X>))\n                         );\n\nnamespace nt2 { namespace ext\n{\n  template<class X, class Dummy>\n  struct call<tag::rdivide_(tag::simd_<tag::int8_, X> ,\n                            tag::simd_<tag::int8_, X> ),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0>\n    struct result<This(A0,A0)>\n      : meta::strip<A0>{};//\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      typedef typename meta::scalar_of<A0>::type              stype;\n      typedef typename meta::upgrade<stype>::type             itype;\n      typedef simd::native<itype, X>                 ivtype;\n      ivtype a0l, a0h, a1l, a1h;\n      boost::fusion::tie(a0l, a0h) = split(a0);\n      boost::fusion::tie(a1l, a1h) = split(a1);\n      return simd::native_cast<A0>(group(nt2::rdivide(a0l, a1l),\n                               nt2::rdivide(a0h, a1h) ));\n    }\n  };\n} }\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is int16_\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::rdivide_, tag::cpu_,\n                          (A0)(X),\n                          ((simd_<int16_<A0>,X>))\n                          ((simd_<int16_<A0>,X>))\n                         );\n\nnamespace nt2 { namespace ext\n{\n  template<class X, class Dummy>\n  struct call<tag::rdivide_(tag::simd_<tag::int16_, X> ,\n                            tag::simd_<tag::int16_, X> ),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0>\n    struct result<This(A0,A0)>\n      : meta::strip<A0>{};//\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      typedef typename meta::scalar_of<A0>::type             stype;\n      typedef typename meta::upgrade<stype>::type            itype;\n      typedef simd::native<itype,X>                 ivtype;\n      ivtype a0l, a0h, a1l, a1h;\n      boost::fusion::tie(a0l, a0h) = split(a0);\n      boost::fusion::tie(a1l, a1h) = split(a1);\n//       std::cout << type_id < ivtype > () << std::endl;\n//       std::cout << a1l << std::endl;\n//       std::cout << a1h << std::endl;\n//       std::cout << a0l << std::endl;\n//       std::cout << a0h << std::endl;\n      return sel(is_eqz(a1),\n\t\t Zero<A0>(),\n\t\t simd::native_cast<A0>(group(toint(tofloat(a0l)/tofloat(a1l)),\n\t\t\t\t\t     toint(tofloat(a0h)/tofloat(a1h)))));\n    }\n  };\n} }\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is real_\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::rdivide_, tag::cpu_,\n                          (A0)(X),\n                          ((simd_<real_<A0>,X>))\n                          ((simd_<real_<A0>,X>))\n                         );\n\nnamespace nt2 { namespace ext\n{\n  template<class X, class Dummy>\n  struct call<tag::rdivide_(tag::simd_<tag::real_, X> ,\n                            tag::simd_<tag::real_, X> ),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0>\n    struct result<This(A0,A0)>\n      : meta::strip<A0>{};//\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      return b_or(b_and(is_eqz(a0), is_eqz(a1)), a0/a1);\n    }\n  };\n} }\n\n#endif\n// modified by jt the 04/01/2011\n", "meta": {"hexsha": "09fb0e8bb0198154199d31a804ce0d60b7ae73b6", "size": 5634, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/arithmetic/include/nt2/toolbox/arithmetic/function/simd/common/rdivide.hpp", "max_stars_repo_name": "brycelelbach/nt2", "max_stars_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T03:35:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:35:10.000Z", "max_issues_repo_path": "modules/arithmetic/include/nt2/toolbox/arithmetic/function/simd/common/rdivide.hpp", "max_issues_repo_name": "brycelelbach/nt2", "max_issues_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/arithmetic/include/nt2/toolbox/arithmetic/function/simd/common/rdivide.hpp", "max_forks_repo_name": "brycelelbach/nt2", "max_forks_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8853503185, "max_line_length": 78, "alphanum_fraction": 0.4776357827, "num_tokens": 1362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.25523176910663636}}
{"text": "#include <cstring>\n#include <fstream>\n#include <unistd.h>\n#include <sys/types.h>\n#include <dirent.h>\n#include <errno.h>\n#include <cstring>\n\n#include <NTL/ZZX.h>\n#include <NTL/vector.h>\n\n#include \"FHE.h\"\n#include \"timing.h\"\n#include \"EncryptedArray.h\"\n\n// https://www.linuxquestions.org/questions/programming-9/c-list-files-in-directory-379323/\n// get Dir file names\nint getdir(string dir, vector <string> &files) {\n    DIR *dp;\n    struct dirent *dirp;\n    if ((dp = opendir(dir.c_str())) == NULL) {\n        cout << \"Error(\" << errno << \") opening \" << dir << endl;\n        return errno;\n    }\n\n    int checkIndex = 0;\n    while ((dirp = readdir(dp)) != NULL) {\n        if(checkIndex++ < 2) continue;\n        string fileName = string(dirp->d_name);\n        files.push_back(string(dirp->d_name));\n    }\n    closedir(dp);\n    return 0;\n}\n\nint main(int argc, char *argv[]) {\n    ArgMapping amap;\n\n    long numberOfCandidates = 4;\n    string owner = \"owner\";\n    string directoryPath = \"data\";\n\n    amap.arg(\"n\", numberOfCandidates, \"number of candidates\");\n    amap.arg(\"o\", owner, \"owner's address\");\n    amap.arg(\"dir\", directoryPath, \"data directory Path\");\n    amap.parse(argc, argv);\n\n    // setting directory path with Ctxt files\n    string directoryPathWithCtxt = directoryPath + \"/result/\" + owner;\n\n    // files name vector list\n    vector<string> fileNames = vector<string>();\n\n    // set resultFile\n    const string resultFilePath = directoryPath + \"/result/\" + owner + \".txt\";\n    ofstream resultFile(resultFilePath.c_str(), ios::binary);\n    assert(resultFile.is_open());\n\n    // get Ctxt files\n    getdir(directoryPathWithCtxt, fileNames);\n    const long sizeOfCtxtFile = fileNames.size();\n    if(sizeOfCtxtFile == 0) {\n        string res = \"[\";\n        for (int i = 0; i < numberOfCandidates; i++) {\n            res.append(to_string(i));\n            if(i != numberOfCandidates-1) res.append(\",\");\n        }\n        res.append(\"]\");\n\n        resultFile << res;\n        return 0;\n    }\n\n    // get public key\n    const string secretKeyBinaryFilePath = directoryPath + \"/secretKey/\" + owner + \".bin\";\n    ifstream secretBinFile(secretKeyBinaryFilePath.c_str(), ios::binary);\n    assert(secretBinFile.is_open());\n\n    // make stream of Ctxt Files\n    fstream CtxtFiles[sizeOfCtxtFile];\n    for (long i = 0;i < sizeOfCtxtFile;i++) {\n        string fileName = directoryPathWithCtxt + \"/\" + fileNames[i];\n        CtxtFiles[i] = fstream(fileName.c_str(), fstream::in);\n        assert(CtxtFiles[i].is_open());\n    }\n\n    // Read context in secret bin file\n    std::unique_ptr <FHEcontext> context = buildContextFromBinary(secretBinFile);\n    readContextBinary(secretBinFile, *context);\n\n    // Read in SecKey and PubKey.\n    // Got to insert pubKey into seckey obj first.\n    std::unique_ptr <FHESecKey> secKey(new FHESecKey(*context));\n    FHEPubKey *pubKey = (FHEPubKey *) secKey.get();\n\n    // read publicKey\n    readPubKeyBinary(secretBinFile, *pubKey);\n    readSecKeyBinary(secretBinFile, *secKey);\n\n    // close secreyKey file\n    secretBinFile.close();\n\n    cout << \"read PublicKey & SecretKey successful.\\n\" << flush;\n\n\n    // ready to add two Ctxts\n    // get Ctxt to file\n    Ctxt resultCtxt(*pubKey), secondCtxt(*pubKey), tempCtxt(*pubKey);\n\n    // fill 1 to tempCtxt\n    Vec <ZZ> tempPoly;\n    tempPoly.SetLength(numberOfCandidates);\n\n    // set poly\n    for (long i = 0; i < numberOfCandidates; i++) tempPoly[i] = 1;\n\n    // encrypt poly\n    pubKey->Encrypt(tempCtxt, to_ZZX(tempPoly));\n\n    // add files\n    ZZX tempCtxtZZX;\n    ostringstream cTxtStream;\n\n\n    CtxtFiles[0] >> resultCtxt;\n    cTxtStream << resultCtxt;\n    secKey->Decrypt(tempCtxtZZX, resultCtxt);\n\n    cout << \"\\n\" << fileNames[0] << endl;\n    cout << \"CypherText: \" << cTxtStream.str().substr(0, 20)\n        << \" ... \" << cTxtStream.str().substr(cTxtStream.str().size() - 63, 50) << endl;\n    cout << \"PlainText: \" << tempCtxtZZX << endl;\n    cout << \"\\n+\\n\" << endl;\n\n    for (long i = 1; i < sizeOfCtxtFile; i++) {\n        CtxtFiles[i] >> secondCtxt;\n        resultCtxt += secondCtxt;\n        cTxtStream << secondCtxt;\n        secKey->Decrypt(tempCtxtZZX, secondCtxt);\n\n        cout << fileNames[i] << endl;\n        cout << \"CypherText: \" << cTxtStream.str().substr(0, 20)\n             << \" ...\" << cTxtStream.str().substr(cTxtStream.str().size() - 63, 50) << endl;\n        cout << \"PlainText:\" << tempCtxtZZX << endl;\n        if(i != sizeOfCtxtFile-1) cout << \"\\n+\\n\" << endl;\n    }\n    cout << \"\\n=\\n\" << endl;\n\n    // save result\n    ZZX ptSum;\n    cTxtStream << resultCtxt;\n    secKey->Decrypt(ptSum, resultCtxt);\n\n    cout << \" [ tally result ]\" << endl;\n    cout << \"CypherText: \" << cTxtStream.str().substr(0, 20)\n         << \" ...\" << cTxtStream.str().substr(cTxtStream.str().size() - 63, 50) << endl;\n    cout << \"PlainText: \" << ptSum << endl;\n\n    // last elements +1\n    resultCtxt += tempCtxt;\n    secKey->Decrypt(ptSum, resultCtxt);\n\n    // save result to file\n    resultFile << ptSum;\n}", "meta": {"hexsha": "ce51330f15736e1a2ab2606c5c22bd038e81793e", "size": 4989, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/hec/src/tally.cpp", "max_stars_repo_name": "HanBae/prototype", "max_stars_repo_head_hexsha": "62b1d86d21d845001b16f3561447181cc23d8429", "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": "app/hec/src/tally.cpp", "max_issues_repo_name": "HanBae/prototype", "max_issues_repo_head_hexsha": "62b1d86d21d845001b16f3561447181cc23d8429", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-02-20T15:25:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-19T15:29:31.000Z", "max_forks_repo_path": "app/hec/src/tally.cpp", "max_forks_repo_name": "HanBae/prototype", "max_forks_repo_head_hexsha": "62b1d86d21d845001b16f3561447181cc23d8429", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-11-11T23:39:17.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-06T05:12:37.000Z", "avg_line_length": 30.2363636364, "max_line_length": 92, "alphanum_fraction": 0.6111445179, "num_tokens": 1405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2551992413172257}}
{"text": "#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n#include <Eigen/Core>\n\n#include \"george/hodlr.h\"\n#include \"george/kernels.h\"\n#include \"george/parser.h\"\n#include \"george/exceptions.h\"\n\nnamespace py = pybind11;\n\nusing RowMatrixXd = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\nclass SolverMatrix {\n  public:\n    SolverMatrix (george::kernels::Kernel* kernel)\n      : kernel_(kernel) {};\n    void set_input_coordinates (RowMatrixXd x) {\n      if (size_t(x.cols()) != kernel_->get_ndim()) {\n        throw george::dimension_mismatch();\n      }\n      t_ = x;\n    };\n    double get_value (const int i, const int j) {\n      if (i < 0 || i >= t_.rows() || j < 0 || j >= t_.rows()) {\n        throw std::out_of_range(\"attempting to index outside of the dimension of the input coordinates\");\n      }\n      return kernel_->value(t_.row(i).data(), t_.row(j).data());\n    };\n\n  private:\n    george::kernels::Kernel* kernel_;\n    RowMatrixXd t_;\n};\n\nclass Solver {\npublic:\n\n  Solver () {\n    solver_ = NULL;\n    kernel_ = NULL;\n    matrix_ = NULL;\n    computed_ = 0;\n  };\n  ~Solver () {\n    if (solver_ != NULL) delete solver_;\n    if (matrix_ != NULL) delete matrix_;\n    if (kernel_ != NULL) delete kernel_;\n  };\n\n  int get_status () const { return 0; };\n  int get_computed () const { return computed_; };\n  double log_determinant () const { return log_det_; };\n\n  int compute (\n      const py::object& kernel_spec,\n      const py::array_t<double>& x,\n      const py::array_t<double>& yerr,\n      int min_size = 100, double tol = 0.1, int seed = 0\n  ) {\n    computed_ = 0;\n    kernel_ = george::parse_kernel_spec(kernel_spec);\n    matrix_ = new SolverMatrix(kernel_);\n\n    // Random number generator for reproducibility\n    std::random_device r;\n    std::mt19937 random(r());\n    random.seed(seed);\n\n    // Extract the data from the numpy arrays\n    py::detail::unchecked_reference<double, 2L> x_p = x.unchecked<2>();\n    py::detail::unchecked_reference<double, 1L> yerr_p = yerr.unchecked<1>();\n    size_t n = x_p.shape(0), ndim = x_p.shape(1);\n    RowMatrixXd X(n, ndim);\n    Eigen::VectorXd diag(n);\n    for (size_t i = 0; i < n; ++i) {\n      diag(i) = yerr_p(i) * yerr_p(i);\n      for (size_t j = 0; j < ndim; ++j) X(i, j) = x_p(i, j);\n    }\n\n    matrix_->set_input_coordinates(X);\n\n    // Set up the solver object.\n    if (solver_ != NULL) delete solver_;\n    solver_ = new george::hodlr::Node<SolverMatrix> (\n        diag, matrix_, 0, n, min_size, tol, random);\n    solver_->compute();\n    log_det_ = solver_->log_determinant();\n\n    // Update the bookkeeping flags.\n    computed_ = 1;\n    size_ = n;\n    return 0;\n  };\n\n  template <typename Derived>\n  void apply_inverse (Eigen::MatrixBase<Derived>& x) {\n    if (!computed_) throw george::not_computed();\n    solver_->solve(x);\n  };\n\n  int size () const { return size_; };\n\nprivate:\n  double log_det_;\n  int size_;\n  int computed_;\n\n  george::kernels::Kernel* kernel_;\n  SolverMatrix* matrix_;\n  george::hodlr::Node<SolverMatrix>* solver_;\n};\n\n\nPYBIND11_MODULE(_hodlr, m) {\n  py::class_<Solver> solver(m, \"HODLRSolver\", R\"delim(\nA solver using `Sivaram Amambikasaran's HODLR algorithm\n<http://arxiv.org/abs/1403.6015>`_ to approximately solve the GP linear\nalgebra in :math:`\\mathcal{O}(N\\,\\log^2 N)`.\n\n)delim\");\n  solver.def(py::init());\n  solver.def_property_readonly(\"computed\", &Solver::get_computed);\n  solver.def_property_readonly(\"log_determinant\", &Solver::log_determinant);\n  solver.def(\"compute\", &Solver::compute, R\"delim(\nCompute and factorize the covariance matrix.\n\nArgs:\n    kernel (george.kernels.Kernel): A subclass of :class:`Kernel` specifying\n        the kernel function.\n    x (ndarray[nsamples, ndim]): The independent coordinates of the data\n        points.\n    yerr (ndarray[nsamples]): The Gaussian uncertainties on the data points at\n        coordinates ``x``. These values will be added in quadrature to the\n        diagonal of the covariance matrix.\n    min_size (Optional[int]): The block size where the solver switches to a\n        general direct factorization algorithm. This can be tuned for platform\n        and problem specific performance and accuracy. As a general rule,\n        larger values will be more accurate and slower, but there is some\n        overhead for very small values, so we recommend choosing values in the\n        hundreds. (default: ``100``)\n    tol (Optional[float]): The precision tolerance for the low-rank\n        approximation. This value is used as an approximate limit on the\n        Frobenius norm between the low-rank approximation and the true matrix\n        when reconstructing the off-diagonal blocks. Smaller values of ``tol``\n        will generally give more accurate results with higher computational\n        cost. (default: ``0.1``)\n    seed (Optional[int]): The low-rank approximation method within the HODLR\n        algorithm is not deterministic and, without a fixed seed, the method\n        can give different results for the same matrix. Therefore, we require\n        that the user provide a seed for the random number generator.\n        (default: ``42``, obviously)\n)delim\",\n    py::arg(\"kernel_spec\"), py::arg(\"x\"), py::arg(\"yerr\"), py::arg(\"min_size\") = 100, py::arg(\"tol\") = 0.1, py::arg(\"seed\") = 42\n  );\n  solver.def(\"apply_inverse\", [](Solver& self, Eigen::MatrixXd& x, bool in_place = false){\n    if (in_place) {\n      self.apply_inverse(x);\n      return x;\n    }\n    Eigen::MatrixXd alpha = x;\n    self.apply_inverse(alpha);\n    return alpha;\n  }, py::arg(\"x\"), py::arg(\"in_place\") = false, R\"delim(\nApply the inverse of the covariance matrix to the input by solving\n\n.. math::\n\n    K\\,x = y\n\nArgs:\n    y (ndarray[nsamples] or ndadrray[nsamples, nrhs]): The vector or matrix\n        :math:`y`.\n    in_place (Optional[bool]): Should the data in ``y`` be overwritten with\n        the result :math:`x`? (default: ``False``)\n)delim\");\n\n  solver.def(\"dot_solve\", [](Solver& self, const Eigen::VectorXd& x){\n    Eigen::VectorXd alpha = x;\n    self.apply_inverse(alpha);\n    return double(x.transpose() * alpha);\n  }, R\"delim(\nCompute the inner product of a vector with the inverse of the covariance\nmatrix applied to itself:\n\n.. math::\n\n    y\\,K^{-1}\\,y\n\nArgs:\n    y (ndarray[nsamples]): The vector :math:`y`.\n)delim\");\n\n  solver.def(\"get_inverse\", [](Solver& self){\n    int n = self.size();\n    Eigen::MatrixXd eye(n, n);\n    eye.setIdentity();\n    self.apply_inverse(eye);\n    return eye;\n  }, R\"delim(\nGet the dense inverse covariance matrix. This is used for computing gradients,\nbut it is not recommended in general.\n)delim\");\n}\n", "meta": {"hexsha": "2774654cc1fd628198dff6e848a879ab43aae508", "size": 6595, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "george/solvers/_hodlr.cpp", "max_stars_repo_name": "rychallener/george", "max_stars_repo_head_hexsha": "98eae39ae453c31afac530c49f178f66c0013c5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 379.0, "max_stars_repo_stars_event_min_datetime": "2015-01-08T15:35:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:01:03.000Z", "max_issues_repo_path": "george/solvers/_hodlr.cpp", "max_issues_repo_name": "rychallener/george", "max_issues_repo_head_hexsha": "98eae39ae453c31afac530c49f178f66c0013c5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 136.0, "max_issues_repo_issues_event_min_datetime": "2015-01-06T17:36:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T20:12:17.000Z", "max_forks_repo_path": "george/solvers/_hodlr.cpp", "max_forks_repo_name": "rychallener/george", "max_forks_repo_head_hexsha": "98eae39ae453c31afac530c49f178f66c0013c5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 119.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T09:27:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T17:54:48.000Z", "avg_line_length": 32.1707317073, "max_line_length": 128, "alphanum_fraction": 0.6548900682, "num_tokens": 1782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.25516399886104907}}
{"text": "#ifndef VIENNACL_LINALG_DETAIL_AMG_AMG_INTERPOL_HPP\n#define VIENNACL_LINALG_DETAIL_AMG_AMG_INTERPOL_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 amg_interpol.hpp\n    @brief Implementations of several variants of the AMG interpolation operators (setup phase). Experimental.\n*/\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <cmath>\n#include \"viennacl/linalg/detail/amg/amg_base.hpp\"\n\n#include <map>\n#ifdef VIENNACL_WITH_OPENMP\n#include <omp.h>\n#endif\n\n#include \"viennacl/linalg/detail/amg/amg_debug.hpp\"\n\nnamespace viennacl\n{\nnamespace linalg\n{\nnamespace detail\n{\nnamespace amg\n{\n\n/** @brief Calls the right function to build interpolation matrix\n * @param level        Coarse level identifier\n * @param A            Operator matrix on all levels\n * @param P            Prolongation matrices. P[level] is constructed\n * @param pointvector  Vector of points on all levels\n * @param tag          AMG preconditioner tag\n*/\ntemplate<typename InternalT1, typename InternalT2>\nvoid amg_interpol(unsigned int level, InternalT1 & A, InternalT1 & P, InternalT2 & pointvector, amg_tag & tag)\n{\n  switch (tag.get_interpol())\n  {\n  case VIENNACL_AMG_INTERPOL_DIRECT:  amg_interpol_direct (level, A, P, pointvector, tag); break;\n  case VIENNACL_AMG_INTERPOL_CLASSIC: amg_interpol_classic(level, A, P, pointvector, tag); break;\n  case VIENNACL_AMG_INTERPOL_AG:      amg_interpol_ag     (level, A, P, pointvector, tag); break;\n  case VIENNACL_AMG_INTERPOL_SA:      amg_interpol_sa     (level, A, P, pointvector, tag); break;\n  }\n}\n\n/** @brief Direct interpolation. Multi-threaded! (VIENNACL_AMG_INTERPOL_DIRECT)\n * @param level        Coarse level identifier\n * @param A            Operator matrix on all levels\n * @param P            Prolongation matrices. P[level] is constructed\n * @param pointvector  Vector of points on all levels\n * @param tag          AMG preconditioner tag\n*/\ntemplate<typename InternalT1, typename InternalT2>\nvoid amg_interpol_direct(unsigned int level, InternalT1 & A, InternalT1 & P, InternalT2 & pointvector, amg_tag & tag)\n{\n  typedef typename InternalT1::value_type         SparseMatrixType;\n  //typedef typename InternalType2::value_type    PointVectorType;\n  typedef typename SparseMatrixType::value_type   ScalarType;\n  typedef typename SparseMatrixType::iterator1    InternalRowIterator;\n  typedef typename SparseMatrixType::iterator2    InternalColIterator;\n\n  unsigned int c_points = pointvector[level].get_cpoints();\n\n  // Setup Prolongation/Interpolation matrix\n  P[level] = SparseMatrixType(static_cast<unsigned int>(A[level].size1()), c_points);\n  P[level].clear();\n\n  // Assign indices to C points\n  pointvector[level].build_index();\n\n  // Direct Interpolation (Yang, p.14)\n#ifdef VIENNACL_WITH_OPENMP\n  #pragma omp parallel for\n#endif\n  for (long x=0; x < static_cast<long>(pointvector[level].size()); ++x)\n  {\n    amg_point *pointx = pointvector[level][static_cast<unsigned int>(x)];\n    /*if (A[level](x,x) > 0)\n      diag_sign = 1;\n    else\n      diag_sign = -1;*/\n\n    // When the current line corresponds to a C point then the diagonal coefficient is 1 and the rest 0\n    if (pointx->is_cpoint())\n      P[level](static_cast<unsigned int>(x),pointx->get_coarse_index()) = 1;\n\n    // When the current line corresponds to a F point then the diagonal is 0 and the rest has to be computed (Yang, p.14)\n    if (pointx->is_fpoint())\n    {\n      // Jump to row x\n      InternalRowIterator row_iter = A[level].begin1();\n      row_iter += vcl_size_t(x);\n\n      // Row sum of coefficients (without diagonal) and sum of influencing C point coefficients has to be computed\n      ScalarType row_sum = 0;\n      ScalarType c_sum   = 0;\n      ScalarType diag    = 0;\n      for (InternalColIterator col_iter = row_iter.begin(); col_iter != row_iter.end(); ++col_iter)\n      {\n        long y = static_cast<long>(col_iter.index2());\n        if (x == y)// || *col_iter * diag_sign > 0)\n        {\n          diag += *col_iter;\n          continue;\n        }\n\n        // Sum all other coefficients in line x\n        row_sum += *col_iter;\n\n        amg_point *pointy = pointvector[level][static_cast<unsigned int>(y)];\n        // Sum all coefficients that correspond to a strongly influencing C point\n        if (pointy->is_cpoint())\n          if (pointx->is_influencing(pointy))\n            c_sum += *col_iter;\n      }\n      ScalarType temp_res = -row_sum/(c_sum*diag);\n\n      // Iterate over all strongly influencing points of point x\n      for (amg_point::iterator iter = pointx->begin_influencing(); iter != pointx->end_influencing(); ++iter)\n      {\n        amg_point *pointy = *iter;\n        // The value is only non-zero for columns that correspond to a C point\n        if (pointy->is_cpoint())\n        {\n          if (temp_res > 0 || temp_res < 0)\n            P[level](static_cast<unsigned int>(x), pointy->get_coarse_index()) = temp_res * A[level](static_cast<unsigned int>(x),pointy->get_index());\n        }\n      }\n\n      //Truncate interpolation if chosen\n      if (tag.get_interpolweight() > 0)\n        amg_truncate_row(P[level], static_cast<unsigned int>(x), tag);\n    }\n  }\n\n  // P test\n  //test_interpolation(A[level], P[level], Pointvector[level]);\n\n  #ifdef VIENNACL_AMG_DEBUG\n  std::cout << \"Prolongation Matrix:\" << std::endl;\n  printmatrix (P[level]);\n  #endif\n}\n\n/** @brief Classical interpolation. Don't use with onepass classical coarsening or RS0 (Yang, p.14)! Multi-threaded! (VIENNACL_AMG_INTERPOL_CLASSIC)\n * @param level        Coarse level identifier\n * @param A            Operator matrix on all levels\n * @param P            Prolongation matrices. P[level] is constructed\n * @param pointvector  Vector of points on all levels\n * @param tag          AMG preconditioner tag\n*/\ntemplate<typename InternalT1, typename InternalT2>\nvoid amg_interpol_classic(unsigned int level, InternalT1 & A, InternalT1 & P, InternalT2 & pointvector, amg_tag & tag)\n{\n  typedef typename InternalT1::value_type           SparseMatrixType;\n  //typedef typename InternalType2::value_type      PointVectorType;\n  typedef typename SparseMatrixType::value_type     ScalarType;\n  typedef typename SparseMatrixType::iterator1      InternalRowIterator;\n  typedef typename SparseMatrixType::iterator2      InternalColIterator;\n\n  unsigned int c_points = pointvector[level].get_cpoints();\n\n  // Setup Prolongation/Interpolation matrix\n  P[level] = SparseMatrixType(static_cast<unsigned int>(A[level].size1()), c_points);\n  P[level].clear();\n\n  // Assign indices to C points\n  pointvector[level].build_index();\n\n  // Classical Interpolation (Yang, p.13-14)\n#ifdef VIENNACL_WITH_OPENMP\n  #pragma omp parallel for\n#endif\n  for (long x=0; x < static_cast<long>(pointvector[level].size()); ++x)\n  {\n    amg_point *pointx = pointvector[level][static_cast<unsigned int>(x)];\n    int diag_sign = (A[level](static_cast<unsigned int>(x),static_cast<unsigned int>(x)) > 0) ? 1 : -1;\n\n    // When the current line corresponds to a C point then the diagonal coefficient is 1 and the rest 0\n    if (pointx->is_cpoint())\n      P[level](static_cast<unsigned int>(x),pointx->get_coarse_index()) = 1;\n\n    // When the current line corresponds to a F point then the diagonal is 0 and the rest has to be computed (Yang, p.14)\n    if (pointx->is_fpoint())\n    {\n      // Jump to row x\n      InternalRowIterator row_iter = A[level].begin1();\n      row_iter += vcl_size_t(x);\n\n      ScalarType weak_sum = 0;\n      amg_sparsevector<ScalarType> c_sum_row(static_cast<unsigned int>(A[level].size1()));\n      c_sum_row.clear();\n      for (InternalColIterator col_iter = row_iter.begin(); col_iter != row_iter.end(); ++col_iter)\n      {\n        long k = static_cast<unsigned int>(col_iter.index2());\n        amg_point *pointk = pointvector[level][static_cast<unsigned int>(k)];\n\n        // Sum of weakly influencing neighbors + diagonal coefficient\n        if (x == k || !pointx->is_influencing(pointk))// || *col_iter * diag_sign > 0)\n        {\n          weak_sum += *col_iter;\n          continue;\n        }\n\n        // Sums of coefficients in row k (strongly influening F neighbors) of C point neighbors of x are calculated\n        if (pointk->is_fpoint() && pointx->is_influencing(pointk))\n        {\n          for (amg_point::iterator iter = pointx->begin_influencing(); iter != pointx->end_influencing(); ++iter)\n          {\n            amg_point *pointm = *iter;\n            long m = pointm->get_index();\n\n            if (pointm->is_cpoint())\n              // Only use coefficients that have opposite sign of diagonal.\n              if (A[level](static_cast<unsigned int>(k),static_cast<unsigned int>(m)) * ScalarType(diag_sign) < 0)\n                c_sum_row[static_cast<unsigned int>(k)] += A[level](static_cast<unsigned int>(k), static_cast<unsigned int>(m));\n          }\n          continue;\n        }\n      }\n\n      // Iterate over all strongly influencing points of point x\n      for (amg_point::iterator iter = pointx->begin_influencing(); iter != pointx->end_influencing(); ++iter)\n      {\n        amg_point *pointy = *iter;\n        long y = pointy->get_index();\n\n        // The value is only non-zero for columns that correspond to a C point\n        if (pointy->is_cpoint())\n        {\n          ScalarType strong_sum = 0;\n          // Calculate term for strongly influencing F neighbors\n          for (typename amg_sparsevector<ScalarType>::iterator iter2 = c_sum_row.begin(); iter2 != c_sum_row.end(); ++iter2)\n          {\n            long k = iter2.index();\n            // Only use coefficients that have opposite sign of diagonal.\n            if (A[level](static_cast<unsigned int>(k),static_cast<unsigned int>(y)) * ScalarType(diag_sign) < 0)\n              strong_sum += (A[level](static_cast<unsigned int>(x),static_cast<unsigned int>(k)) * A[level](static_cast<unsigned int>(k),static_cast<unsigned int>(y))) / (*iter2);\n          }\n\n          // Calculate coefficient\n          ScalarType temp_res = - (A[level](static_cast<unsigned int>(x),static_cast<unsigned int>(y)) + strong_sum) / (weak_sum);\n          if (temp_res < 0 || temp_res > 0)\n            P[level](static_cast<unsigned int>(x),pointy->get_coarse_index()) = temp_res;\n        }\n      }\n\n      //Truncate iteration if chosen\n      if (tag.get_interpolweight() > 0)\n        amg_truncate_row(P[level], static_cast<unsigned int>(x), tag);\n    }\n  }\n\n  #ifdef VIENNACL_AMG_DEBUG\n  std::cout << \"Prolongation Matrix:\" << std::endl;\n  printmatrix (P[level]);\n  #endif\n}\n\n/** @brief Interpolation truncation (for VIENNACL_AMG_INTERPOL_DIRECT and VIENNACL_AMG_INTERPOL_CLASSIC)\n*\n* @param P    Interpolation matrix\n* @param row  Row which has to be truncated\n* @param tag  AMG preconditioner tag\n*/\ntemplate<typename SparseMatrixT>\nvoid amg_truncate_row(SparseMatrixT & P, unsigned int row, amg_tag & tag)\n{\n  typedef typename SparseMatrixT::value_type   ScalarType;\n  typedef typename SparseMatrixT::iterator1    InternalRowIterator;\n  typedef typename SparseMatrixT::iterator2    InternalColIterator;\n\n  ScalarType row_max, row_min, row_sum_pos, row_sum_neg, row_sum_pos_scale, row_sum_neg_scale;\n\n  InternalRowIterator row_iter = P.begin1();\n  row_iter += row;\n\n  row_max = 0;\n  row_min = 0;\n  row_sum_pos = 0;\n  row_sum_neg = 0;\n\n  // Truncate interpolation by making values to zero that are a lot smaller than the biggest value in a row\n  // Determine max entry and sum of row (seperately for negative and positive entries)\n  for (InternalColIterator col_iter = row_iter.begin(); col_iter != row_iter.end(); ++col_iter)\n  {\n    if (*col_iter > row_max)\n      row_max = *col_iter;\n    if (*col_iter < row_min)\n      row_min = *col_iter;\n    if (*col_iter > 0)\n      row_sum_pos += *col_iter;\n    if (*col_iter < 0)\n      row_sum_neg += *col_iter;\n  }\n\n  row_sum_pos_scale = row_sum_pos;\n  row_sum_neg_scale = row_sum_neg;\n\n  // Make certain values to zero (seperately for negative and positive entries)\n  for (InternalColIterator col_iter = row_iter.begin(); col_iter != row_iter.end(); ++col_iter)\n  {\n    if (*col_iter > 0 && *col_iter < tag.get_interpolweight() * row_max)\n    {\n      row_sum_pos_scale -= *col_iter;\n      *col_iter = 0;\n    }\n    if (*col_iter < 0 && *col_iter > tag.get_interpolweight() * row_min)\n    {\n      row_sum_pos_scale -= *col_iter;\n      *col_iter = 0;\n    }\n  }\n\n  // Scale remaining values such that row sum is unchanged\n  for (InternalColIterator col_iter = row_iter.begin(); col_iter != row_iter.end(); ++col_iter)\n  {\n    if (*col_iter > 0)\n      *col_iter = *col_iter *(row_sum_pos/row_sum_pos_scale);\n    if (*col_iter < 0)\n      *col_iter = *col_iter *(row_sum_neg/row_sum_neg_scale);\n  }\n}\n\n/** @brief AG (aggregation based) interpolation. Multi-Threaded! (VIENNACL_INTERPOL_SA)\n * @param level        Coarse level identifier\n * @param A            Operator matrix on all levels\n * @param P            Prolongation matrices. P[level] is constructed\n * @param pointvector  Vector of points on all levels\n*/\ntemplate<typename InternalT1, typename InternalT2>\nvoid amg_interpol_ag(unsigned int level, InternalT1 & A, InternalT1 & P, InternalT2 & pointvector, amg_tag)\n{\n  typedef typename InternalT1::value_type SparseMatrixType;\n  //typedef typename InternalType2::value_type PointVectorType;\n  //typedef typename SparseMatrixType::value_type ScalarType;\n  //typedef typename SparseMatrixType::iterator1 InternalRowIterator;\n  //typedef typename SparseMatrixType::iterator2 InternalColIterator;\n\n  unsigned int c_points = pointvector[level].get_cpoints();\n\n  P[level] = SparseMatrixType(static_cast<unsigned int>(A[level].size1()), c_points);\n  P[level].clear();\n\n  // Assign indices to C points\n  pointvector[level].build_index();\n\n  // Set prolongation such that F point is interpolated (weight=1) by the aggregate it belongs to (Vanek et al p.6)\n#ifdef VIENNACL_WITH_OPENMP\n  #pragma omp parallel for\n#endif\n  for (long x=0; x<static_cast<long>(pointvector[level].size()); ++x)\n  {\n    amg_point *pointx = pointvector[level][static_cast<unsigned int>(x)];\n    amg_point *pointy = pointvector[level][pointx->get_aggregate()];\n    // Point x belongs to aggregate y.\n    P[level](static_cast<unsigned int>(x), pointy->get_coarse_index()) = 1;\n  }\n\n  #ifdef VIENNACL_AMG_DEBUG\n  std::cout << \"Aggregation based Prolongation:\" << std::endl;\n  printmatrix(P[level]);\n  #endif\n}\n\n/** @brief SA (smoothed aggregate) interpolation. Multi-Threaded! (VIENNACL_INTERPOL_SA)\n * @param level        Coarse level identifier\n * @param A            Operator matrix on all levels\n * @param P            Prolongation matrices. P[level] is constructed\n * @param pointvector  Vector of points on all levels\n * @param tag          AMG preconditioner tag\n*/\ntemplate<typename InternalT1, typename InternalT2>\nvoid amg_interpol_sa(unsigned int level, InternalT1 & A, InternalT1 & P, InternalT2 & pointvector, amg_tag & tag)\n{\n  typedef typename InternalT1::value_type         SparseMatrixType;\n  //typedef typename InternalType2::value_type    PointVectorType;\n  typedef typename SparseMatrixType::value_type   ScalarType;\n  typedef typename SparseMatrixType::iterator1    InternalRowIterator;\n  typedef typename SparseMatrixType::iterator2    InternalColIterator;\n\n  unsigned int c_points = pointvector[level].get_cpoints();\n\n  InternalT1 P_tentative = InternalT1(P.size());\n  SparseMatrixType Jacobi = SparseMatrixType(static_cast<unsigned int>(A[level].size1()), static_cast<unsigned int>(A[level].size2()));\n  Jacobi.clear();\n  P[level] = SparseMatrixType(static_cast<unsigned int>(A[level].size1()), c_points);\n  P[level].clear();\n\n  // Build Jacobi Matrix via filtered A matrix (Vanek et al. p.6)\n#ifdef VIENNACL_WITH_OPENMP\n  #pragma omp parallel for\n#endif\n  for (long x=0; x<static_cast<long>(A[level].size1()); ++x)\n  {\n    ScalarType diag = 0;\n    InternalRowIterator row_iter = A[level].begin1();\n    row_iter += vcl_size_t(x);\n    for (InternalColIterator col_iter = row_iter.begin(); col_iter != row_iter.end(); ++col_iter)\n    {\n      long y = static_cast<long>(col_iter.index2());\n      // Determine the structure of the Jacobi matrix by using a filtered matrix of A:\n      // The diagonal consists of the diagonal coefficient minus all coefficients of points not in the neighborhood of x.\n      // All other coefficients are the same as in A.\n      // Already use Jacobi matrix to save filtered A matrix to speed up computation.\n      if (x == y)\n        diag += *col_iter;\n      else if (!pointvector[level][static_cast<unsigned int>(x)]->is_influencing(pointvector[level][static_cast<unsigned int>(y)]))\n        diag += -*col_iter;\n      else\n        Jacobi (static_cast<unsigned int>(x), static_cast<unsigned int>(y)) = *col_iter;\n    }\n    InternalRowIterator row_iter2 = Jacobi.begin1();\n    row_iter2 += vcl_size_t(x);\n    // Traverse through filtered A matrix and compute the Jacobi filtering\n    for (InternalColIterator col_iter2 = row_iter2.begin(); col_iter2 != row_iter2.end(); ++col_iter2)\n    {\n        *col_iter2 = - static_cast<ScalarType>(tag.get_interpolweight())/diag * *col_iter2;\n    }\n    // Diagonal can be computed seperately.\n    Jacobi (static_cast<unsigned int>(x), static_cast<unsigned int>(x)) = 1 - static_cast<ScalarType>(tag.get_interpolweight());\n  }\n\n  #ifdef VIENNACL_AMG_DEBUG\n  std::cout << \"Jacobi Matrix:\" << std::endl;\n  printmatrix(Jacobi);\n  #endif\n\n  // Use AG interpolation as tentative prolongation\n  amg_interpol_ag(level, A, P_tentative, pointvector, tag);\n\n  #ifdef VIENNACL_AMG_DEBUG\n  std::cout << \"Tentative Prolongation:\" << std::endl;\n  printmatrix(P_tentative[level]);\n  #endif\n\n  // Multiply Jacobi matrix with tentative prolongation to get actual prolongation\n  amg_mat_prod(Jacobi,P_tentative[level],P[level]);\n\n  #ifdef VIENNACL_AMG_DEBUG\n  std::cout << \"Prolongation Matrix:\" << std::endl;\n  printmatrix(P[level]);\n  #endif\n}\n\n} //namespace amg\n} //namespace detail\n} //namespace linalg\n} //namespace viennacl\n\n#endif\n", "meta": {"hexsha": "8dc01689dd99bfac53dccf4b299ec58477078ab1", "size": 18612, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "viennacl/linalg/detail/amg/amg_interpol.hpp", "max_stars_repo_name": "ddemidov/viennacl-dev", "max_stars_repo_head_hexsha": "0f7de9cd28e54a5ca8f7c2ab03263bc56bf004ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-08-23T17:05:21.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-23T17:06:24.000Z", "max_issues_repo_path": "viennacl/linalg/detail/amg/amg_interpol.hpp", "max_issues_repo_name": "ddemidov/viennacl-dev", "max_issues_repo_head_hexsha": "0f7de9cd28e54a5ca8f7c2ab03263bc56bf004ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "viennacl/linalg/detail/amg/amg_interpol.hpp", "max_forks_repo_name": "ddemidov/viennacl-dev", "max_forks_repo_head_hexsha": "0f7de9cd28e54a5ca8f7c2ab03263bc56bf004ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6, "max_line_length": 179, "alphanum_fraction": 0.6748871696, "num_tokens": 4737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.25506411369900805}}
{"text": "#pragma once\n#ifndef _INITIALIZER_HPP_\n#define _INITIALIZER_HPP_\n\n#include <list>\n#include <set>\n#include <vector>\n#include <algorithm>\n#include <string>\n#include <cassert>\n\n#include <Eigen/Dense>\n#include <Eigen/StdVector>\n\n#include <petsctime.h>\n\n#include \"Grid.hpp\"\n#include \"Interface.hpp\"\n#include \"BoundingBox.hpp\"\n#include \"TriangleElement.hpp\"\n#include \"Geometry.hpp\"\n\n#include \"tictoc.hpp\"\n#include \"utility.h\"\n\n\n\n/// compares two signed distances\n/// the signed distance and also prepedicular distance is compared\nvoid sdfMin(cDistance* in, cDistance* inout, int len, MPI_Datatype* dptr) {\n\tint i = 0;\n\tfor(i = 0; i < len; ++i) {\n\t\tdouble ax  = fabs(in[i].signedDistance), ay = fabs(inout[i].signedDistance);\n\t\tdouble eps = my_eps;\n\t\tif ( fabs(ax - ay) < eps ) {\n\t\t\tif (in[i].pDistance > inout[i].pDistance) {\n\t\t\t\tinout[i] = in[i];\n\t\t\t}\n\t\t} else if (ax > ay) {\n\t\t\tinout[i] = in[i];\n\t\t}\n\t}\n}\n\n\nclass Initializer {\npublic:\n\tInitializer() {};\n\n\t// This is where the magic happens and the initializator puts the data in\n\ttemplate <typename type, int dim>\n\tvoid operator() (Geometry& geom, Interface<type, dim>& interface, int groupID, int nGroups);\n\n\nprivate:\n\t// some states here and utility functions needed to do the jolb\n\n\tMPI_Datatype mpi_cDist_type;\n\tMPI_Op mpi_sdfmin;\n\n\tvoid createTypes();\n\ttemplate <typename type, int dim>\n\tvoid initAll(const Grid<type, dim>& gr, Geometry& geom, double*** data_ptr);\n\ttemplate <typename type, int dim>\n\tvoid initBoundaries_nlb(const Grid<type, dim>& gr, Geometry& geom, double*** data_ptr, int boundaries);\n\ttemplate <typename type, int dim>\n\tvoid initBoundaries_lb(const Grid<type, dim>& gr, Geometry& geom, double*** data_ptr, int boundaries, int groupID, int nGroups);\n\n\tint selectBoundaries(const Box<double, 3>& geometryAABB, const Box<double, 3>& procAABB);\n\n\ttemplate <typename type, int dim>\n\tvoid putDataToBoundaries(const Grid<type, dim>& gr, double*** data_ptr, cDistance* distanceData, int cellNum, int boundaries);\n\n\ttemplate <typename type, int dim>\n\tvoid putLocalDataInside(const Grid<type, dim>& gr, double*** data_ptr, const std::vector<int>& localTriangles, const Geometry& geom, double*** perpendicualDistance);\n\n};\n\n///\n/// Main routine\n///\n\n\nvoid Initializer::createTypes() {\n\t// TODO this should be rewritten as create type placed in cDistance and create minFcn\n\t// define according data type for cDistance in MPI\n\tconst int    nitems = 2;\n\tint          blocklengths[2] = {1, 1};\n\tMPI_Datatype types[2] = {MPI_DOUBLE, MPI_DOUBLE};\n\tMPI_Aint     offsets[2];\n\n\toffsets[0] = offsetof(cDistance, signedDistance);\n\toffsets[1] = offsetof(cDistance, pDistance);\n\n\tMPI_Type_create_struct(nitems, blocklengths, offsets, types, &mpi_cDist_type);\n\tMPI_Type_commit(&mpi_cDist_type);\n\t// end type definition\n\n\t// commit custom mpi reduce operation\n\tMPI_Op_create((MPI_User_function *) sdfMin, 1, &mpi_sdfmin);\n\t// end custom reduce operation commit\n}\n\ntemplate <typename type, int dim>\nvoid Initializer::initAll(const Grid<type, dim>& gr, Geometry& geom, double*** data_ptr) {\n\n\tDM cda;\n\tVec gc;\n\tDMDACoor3d ***coors;\n\n\tDMGetCoordinatesLocal(gr.getDA() ,&gc);\n\tDMGetCoordinateDM(gr.getDA(), &cda);\n\tDMDAVecGetArray(cda, gc, &coors);\n\n\n\tint       x, y, z, m, n, p;\n\tint       cellCounter = 0, gh = 1;\n\n\tDMDAGetGhostCorners(gr.getDA(), &x, &y, &z, &m, &n, &p);\n\tdouble data_ref = 0.0, data_acc = 0.0;\n\tfor (int i = x; i < x+m; ++i) {\n\t\tfor (int j = y; j < y+n; ++j) {\n\t\t\tfor (int k = z; k < z+p; ++k) {\n\t\t\t\tdata_acc =\n\t\t\t\t\t\tgeom.computeDistance(\n\t\t\t\t\t\t\tEigen::Vector3d(coors[k][j][i].x,\n\t\t\t\t\t\t\t\t\t\t\tcoors[k][j][i].y,\n\t\t\t\t\t\t\t\t\t\t\tcoors[k][j][i].z),\n\t\t\t\t\t\t\ttrue\n\t\t\t\t\t\t);\n\n\t\t\t\tdata_ref = geom.computeDistance(\n\t\t\t\t\t\t\tEigen::Vector3d(coors[k][j][i].x,\n\t\t\t\t\t\t\t\t\t\t\tcoors[k][j][i].y,\n\t\t\t\t\t\t\t\t\t\t\tcoors[k][j][i].z),\n\t\t\t\t\t\t\tfalse\n\t\t\t\t\t\t);\n\n\t\t\t}\n\t\t}\n\t}\n\n}\n\ntemplate <typename type, int dim>\nvoid Initializer::initBoundaries_nlb(const Grid<type, dim>& gr, Geometry& geom, double*** data_ptr, int boundaries) {\n\n\tDM cda;\n\tVec gc;\n\tDMDACoor3d ***coors;\n\n\tDMGetCoordinatesLocal(gr.getDA() ,&gc);\n\tDMGetCoordinateDM(gr.getDA(), &cda);\n\tDMDAVecGetArray(cda, gc, &coors);\n\n\n\tint       x, y, z, m, n, p;\n\tint       cellCounter = 0, gh = 1;\n\n\tDMDAGetGhostCorners(gr.getDA(), &x, &y, &z, &m, &n, &p);\n\n\tint tmpSum = 0;\n\tif ( boundaries & 1 ) {\n\t\ttmpSum+= gh*n*p;\n\t\t// this means lets initialize left side\n\t\tfor (int i = x; i < x+gh; ++i) {\n\t\t\tfor (int j = y; j < y+n; ++j) {\n\t\t\t\tfor (int k = z; k < z+p; ++k) {\n\t\t\t\t\tdata_ptr[k][j][i] =\n\t\t\t\t\t\t\tgeom.computeDistance(\n\t\t\t\t\t\t\t\tEigen::Vector3d(coors[k][j][i].x,\n\t\t\t\t\t\t\t\t\t\t\t\tcoors[k][j][i].y,\n\t\t\t\t\t\t\t\t\t\t\t\tcoors[k][j][i].z),\n\t\t\t\t\t\t\t\ttrue\n\t\t\t\t\t\t\t);\n\t\t\t\t\tcellCounter++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif ( boundaries & 2 ) {\n\t\ttmpSum += gh*n*p;\n\t\t// this means lets initialize right side\n\t\tfor (int i = x+m-1; i > x+m-1-gh; --i) {\n\t\t\tfor (int j = y; j < y+n; ++j) {\n\t\t\t\tfor (int k = z; k < z+p; ++k) {\n\t\t\t\t\tdata_ptr[k][j][i] =\n\t\t\t\t\t\t\tgeom.computeDistance(\n\t\t\t\t\t\t\t\tEigen::Vector3d(coors[k][j][i].x,\n\t\t\t\t\t\t\t\t\t\t\t\tcoors[k][j][i].y,\n\t\t\t\t\t\t\t\t\t\t\t\tcoors[k][j][i].z),\n\t\t\t\t\t\t\t\ttrue\n\t\t\t\t\t\t\t);\n\t\t\t\t\tcellCounter++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif ( boundaries & 4 ) {\n\t\ttmpSum += gh*m*p;\n\t\t// this means initialize the bottom side\n\t\tfor (int j = y; j < y+gh; ++j) {\n\t\t\tfor (int i = x; i < x+m; ++i) {\n\t\t\t\tfor (int k = z; k < z+p; ++k) {\n\t\t\t\t\tdata_ptr[k][j][i] =\n\t\t\t\t\t\t\tgeom.computeDistance(\n\t\t\t\t\t\t\t\tEigen::Vector3d(coors[k][j][i].x,\n\t\t\t\t\t\t\t\t\t\t\t\tcoors[k][j][i].y,\n\t\t\t\t\t\t\t\t\t\t\t\tcoors[k][j][i].z),\n\t\t\t\t\t\t\t\ttrue\n\t\t\t\t\t\t\t);\n\t\t\t\t\tcellCounter++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif ( boundaries & 8 ) {\n\t\ttmpSum += gh*m*p;\n\t\t// this means initialize the top side\n\t\tfor (int j = y+n-1; j > y+n-1-gh; --j) {\n\t\t\tfor (int i = x; i < x+m; ++i) {\n\t\t\t\tfor (int k = z; k < z+p; ++k) {\n\t\t\t\t\tdata_ptr[k][j][i] =\n\t\t\t\t\t\t\tgeom.computeDistance(\n\t\t\t\t\t\t\t\tEigen::Vector3d(coors[k][j][i].x,\n\t\t\t\t\t\t\t\t\t\t\t\tcoors[k][j][i].y,\n\t\t\t\t\t\t\t\t\t\t\t\tcoors[k][j][i].z),\n\t\t\t\t\t\t\t\ttrue\n\t\t\t\t\t\t\t);\n\t\t\t\t\tcellCounter++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif ( boundaries & 16 ) {\n\t\ttmpSum += gh*m*n;\n\t\t// this means initialize the front side\n\t\tfor (int k = z; k < z+gh; ++k) {\n\t\t\tfor (int i = x; i < x+m; ++i) {\n\t\t\t\tfor (int j = y; j < y+n; ++j) {\n\t\t\t\t\tdata_ptr[k][j][i] =\n\t\t\t\t\t\t\tgeom.computeDistance(\n\t\t\t\t\t\t\t\tEigen::Vector3d(coors[k][j][i].x,\n\t\t\t\t\t\t\t\t\t\t\t\tcoors[k][j][i].y,\n\t\t\t\t\t\t\t\t\t\t\t\tcoors[k][j][i].z),\n\t\t\t\t\t\t\t\ttrue\n\t\t\t\t\t\t\t);\n\t\t\t\t\tcellCounter++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif ( boundaries & 32 ) {\n\t\ttmpSum += gh*m*n;\n\t\t// this means initialize the far side\n\t\tfor (int k = z+p-1; k > z+p-1-gh; --k) {\n\t\t\tfor (int i = x; i < x+m; ++i) {\n\t\t\t\tfor (int j = y; j < y+n; ++j) {\n\t\t\t\t\tdata_ptr[k][j][i] =\n\t\t\t\t\t\t\tgeom.computeDistance(\n\t\t\t\t\t\t\t\tEigen::Vector3d(coors[k][j][i].x,\n\t\t\t\t\t\t\t\t\t\t\t\tcoors[k][j][i].y,\n\t\t\t\t\t\t\t\t\t\t\t\tcoors[k][j][i].z),\n\t\t\t\t\t\t\t\ttrue\n\t\t\t\t\t\t\t);\n\t\t\t\t\tcellCounter++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n}\n\n/* \ntemplate <typename type, int dim>\nvoid Initializer::initBoundaries_lb(const Grid<type, dim>& gr,\n\t\tGeometry& geom,\n\t\tdouble*** data_ptr,\n\t\tint boundaries,\n\t\tint groupID, int nGroups) {\n\n\ttictoc tick;\n\tint myWorldRank, nProcsInWorld;\n\tint myBegin, myEnd;   // local indices start, local indices stop\n\tint myBoundaries;\n\tMPI_Comm_rank(MPI_COMM_WORLD, &myWorldRank);\n\tMPI_Comm_size(MPI_COMM_WORLD, &nProcsInWorld);\n\n\ttick.tic();\n\t// prepare memory to store the list of all boundary cells\n\tstd::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > boundaryCellList;\n\tboundaryCellList.reserve( nProcsInWorld * 4 * gr.getM(0)*gr.getM(1) );\n\n\t// this is where the results go (final results)\n\tstd::vector<cDistance> vDistance;\n\t// create the fucking list\n\tfor (int p = 0; p < nProcsInWorld; ++p) {\n\t\t// loop through the processes and get the proc bounding box\n\t\tBox<double, 3> procBB    = gr.getNodeSpan(p);\n\t\tint boundariesToInit     = selectBoundaries(geom.aabb, procBB);\n\n\t\tstd::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > l =\n\t\t\t\tgr.getNodeBoundaryCells(p, boundariesToInit);\n\n\t\t// ok I need to remember what part of the boundary is mine, otherwise I am screwed\n\t\tif (myWorldRank == p) {\n\t\t\tmyBegin      = boundaryCellList.size();\n\t\t\tmyEnd        = myBegin + l.size();\n\t\t\tmyBoundaries = boundariesToInit;\n\t\t}\n\n\t\tboundaryCellList.insert( boundaryCellList.end(), l.begin(), l.end() );\n\t}\n\n\ttick.toc(myWorldRank, MAKECELLLIST, \"Create boundary list\");\n\n\t// number of cells in the boundary list for the WHOLE FUCKING BOUNDARY\n\tint nBCells = boundaryCellList.size();\n\tstd::cout << \"ncells: \" << nBCells << std::endl;\n\ttick.tic();\n\t// loadbalance the problem.\n\t// first create groups for the problem\n\tMPI_Comm groupCommunicator = MPI_COMM_WORLD;\n\tint nProcsInGroup;\n\tint myGroupRank;\n\tif ( nGroups > 1 ) {\n\t\t// but if the number of groups is larger than one we need to create the right communicator.\n\t\t// luckily the group assigment is already sorted in setup phase.\n\t\tMPI_Comm_split(MPI_COMM_WORLD, groupID, myWorldRank, &groupCommunicator);\n\t}\n\tMPI_Comm_rank(groupCommunicator, &myGroupRank);\n\tMPI_Comm_size(groupCommunicator, &nProcsInGroup);\n\t// now each group will split its workload of boundary cells and start doing stuff\n\n\tint numberOfCellsPerTask     = geom.getNumberOfCellsPerDomainLocal();\n\tassert( numberOfCellsPerTask >= 0 );\n\n\tint max_numberOfCellsPerTask = -std::numeric_limits<int>::max();\n\tsize_t totalCellsToFillTheGaps  = 0;\n\tint exchangedNumberOfCellsPerTask[nProcsInGroup];\n\n\tMPI_Allgather(&numberOfCellsPerTask, 1, MPI_INT, exchangedNumberOfCellsPerTask, nProcsInGroup, MPI_INT, groupCommunicator);\n\n\tmax_numberOfCellsPerTask = *std::max_element(exchangedNumberOfCellsPerTask, exchangedNumberOfCellsPerTask + nProcsInGroup);\n\tassert( max_numberOfCellsPerTask >= 0 ); // maximum should not be negative\n\n\tdouble diffs[nProcsInGroup];// diffs is the number of cells going to be added as balance for\n\tfor (int p = 0 ; p < nProcsInGroup; ++p) {\n\t\tdiffs[p] = max_numberOfCellsPerTask - exchangedNumberOfCellsPerTask[p];\n\t\tassert( diffs[p] >= 0 );\n\t\ttotalCellsToFillTheGaps += size_t(max_numberOfCellsPerTask - exchangedNumberOfCellsPerTask[p]);\n\t\t if (myWorldRank == 0)\n\t\t\t std::cout << \"DIFFS : \" << (size_t)diffs[p] << \"; MAX : \" << max_numberOfCellsPerTask << \"; EXCHANGED: \" << exchangedNumberOfCellsPerTask[p] << std::endl;\n\t}\n\tif (myWorldRank == 0)\n\t\t std::cout << \"SUM: \" << totalCellsToFillTheGaps << std::endl;\n\tsize_t tmpSum = 0; double pSum = 0.0;\n\t\n\tif ( totalCellsToFillTheGaps > 0 ) {\n\t\tfor (int p = 0 ; p < nProcsInGroup; ++p) {\n\t\t\tpSum += diffs[p]/double(totalCellsToFillTheGaps);\n\t\t\ttmpSum += size_t(diffs[p]);\n\n\t\t\t if (myWorldRank == 0)\n\t\t\t\t std::cout << \"PROC: \" << p << \" DIFF: \" << double(diffs[p])  << \" / \" << double(totalCellsToFillTheGaps) << \" - \" << diffs[p]/double(totalCellsToFillTheGaps) << \" - \" << pSum\n\t\t\t\t << \" - \" << tmpSum << std::endl;\n\t\t\t\n\t\t\tdiffs[p] = double(diffs[p]) / double(totalCellsToFillTheGaps);\n\t\t}\n\t\t if (myWorldRank == 0)\n\t\t\t std::cout << \"TMPSUM: \" << tmpSum << std::endl;\n\t\tassert( tmpSum == totalCellsToFillTheGaps ); // the percentage is not allowed to be greater then 100%\n\t}\n\n\tint theRest = nBCells - totalCellsToFillTheGaps;\n\tif ( theRest < 0 ) {\n\t\t// to make sure that assigment of negative shit is not happening\n\t\ttheRest                 = 0;\n\t\ttotalCellsToFillTheGaps = nBCells;\n\t}\n\t\n\tint start = 0, finish = 0;\n\tint send_offsets[nProcsInGroup];\n\tint send_lens[nProcsInGroup];\n\tint debugSum = 0;\n\n\n\tfor (int p = 0; p < nProcsInGroup; ++p) {\n\t\tstart  = finish;\n\n\t\tfinish = (p == nProcsInGroup-1) ? nBCells : start + int( diffs[p]*double(totalCellsToFillTheGaps) ) + int( double(theRest)/double(nProcsInGroup) );\n\t\t \n\t\tsend_offsets[p] = start;\n\t\tsend_lens[p]    = finish - start;\n\t\tdebugSum += send_lens[p];\n\t}\n\ttick.toc(myWorldRank, SETUPGROUPS, \"Setup groups\");\n\tassert( debugSum <= nBCells );\n\tassert( send_lens[nProcsInGroup-1] + send_offsets[nProcsInGroup-1] == nBCells );\t\n\n\n\ttick.tic();\n\t// std::cout << \"send_offsets = \" << send_offsets[myGroupRank] << \", send_lens = \" << send_lens[myGroupRank] << \", nBCells = \" << nBCells << std::endl;\n\tassert( send_lens[myGroupRank] >= 0 );\n\tassert( send_offsets[myGroupRank] >= 0 );\n\tassert( (send_offsets[myGroupRank] + send_lens[myGroupRank]) <= nBCells );\n//\tstd::vector<cDistance> localDistances; localDistances.reserve( send_lens[myGroupRank] );\n\tcDistance localDistances[ send_lens[myGroupRank] ];\n\t// compute the distance within the group\n\n\n\tstd::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> >::const_iterator begin_range = boundaryCellList.begin() + send_offsets[myGroupRank];\n\tstd::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> >::const_iterator end_range = boundaryCellList.begin() + send_offsets[myGroupRank] + send_lens[myGroupRank];\n\tstd::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > subList(begin_range, end_range);\n\tstd::cout << \"allocated for locality check\" << std::endl;\n\n\n\n\tgeom.computeDistance(subList, localDistances);\n\ttick.toc(myWorldRank, COMPUTEDIST, \"Compute bval dist\");\n\n\tboundaryCellList.clear();\n\t\n\n\t// put data together. That means call allgatherv and synchronize the shit.\n\n\ttick.tic();\n\tassert( nBCells > 0 );\n\tvDistance.resize( nBCells );\n\tMPI_Allgatherv(&localDistances[0], send_lens[myGroupRank], mpi_cDist_type,  &vDistance[0], send_lens, send_offsets, mpi_cDist_type, groupCommunicator);\n\n\ttick.toc(myWorldRank, ALLGATHER, \"Allgatherv vector\");\n\t// now the data is placed together in one nice vector\n\tstd::cout << \"dumping vDistance: \" << std::endl;\n\tfor (auto d: vDistance) {\n\t\tstd::cout << d.signedDistance << \", \";\n\t} \n\tstd::cout << std::endl;\n\n\t// synchronize the groups by reduce operation. This is only needed when you have more then one group\n\n\ttick.tic();\n\tif ( nGroups > 1 ) {\n//\t\tmpi::all_reduce(world, &vDistance[0], nBCells, &vDistance[0], sdfMinimum<cDistance>());\n\t\tMPI_Allreduce(&vDistance[0], &vDistance[0], nBCells, mpi_cDist_type, mpi_sdfmin, MPI_COMM_WORLD);\n\t}\n\ttick.toc(myWorldRank, REDUCE, \"Reduce between groups\");\n\n\ttick.tic();\n\t// step THREE put into the grid\n\tassert( myBegin >= 0 );\n\tassert( (myEnd-myBegin) < nBCells );\n\tputDataToBoundaries(gr, data_ptr, &vDistance[myBegin], (myEnd-myBegin), myBoundaries);\n\n\tvDistance.clear();\n\ttick.toc(myWorldRank, PUTTOBOUNDARIES, \"Place to boundaries\");\n\n}\n*/\n\ntemplate <typename type, int dim>\nvoid Initializer::operator ()(Geometry& geom, Interface<type, dim>& interface, int groupID, int nGroups) {\n\n\n\tstd::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > boundaryCells;    // xyz coordinated to compute the distance to\n\n\tint                        myBoundaries;     // local boundaries to init\n\n\tMPI_Group worldGroup;\n\tMPI_Comm_group(MPI_COMM_WORLD, &worldGroup);\n\t// perpendicular distance computed towards the triangle, it is used when we are no longer sure, which normal shall we use\n\n\tdouble*** perpendicualDistance;\n\n\n\t// initialize the data\n\n\tVec       localData = interface.getLocalData();\n\tdouble*** data_ptr;\n\tint       x, y, z, m, n, p;\n\tint       vecSize;\n\n\tVecGetLocalSize(localData, &vecSize);\n\tassert( vecSize > 0 );\n\n\tint myWorldRank;\n\tint nProcsInWorld;\n\n\tMPI_Comm_rank(MPI_COMM_WORLD, &myWorldRank);\n\tMPI_Comm_size(MPI_COMM_WORLD, &nProcsInWorld);\n\n\n\tconst Grid<type, dim>& gr = interface.getGrid();\n\n\tDMDAVecGetArray(gr.getDA(), localData, &data_ptr);\n\tDMDAGetArray(gr.getDA(), PETSC_TRUE, &perpendicualDistance);\n\tDMDAGetGhostCorners(gr.getDA(), &x, &y, &z, &m, &n, &p);\n\n\tassert( vecSize == m*n*p );\n\n\tfor (int k = z, pk = 0; k < z+p; ++k, ++pk) {\n\t\tfor (int j = y, pj = 0; j < y+n; ++j, ++pj) {\n\t\t\tfor (int i = x, pi = 0; i < x+m; ++i, ++pi) {\n\t\t\t\tdata_ptr[k][j][i]             =  std::numeric_limits<double>::max();\n\t\t\t\tperpendicualDistance[k][j][i] = -std::numeric_limits<double>::max();\n\t\t\t}\n\t\t}\n\t}\n\n\t// step FIVE compute triangle distance inside the narrowband\n\n\tputLocalDataInside(gr, data_ptr, geom.localElements, geom, perpendicualDistance);\n\n\tDMDARestoreArray(gr.getDA(), PETSC_TRUE, &perpendicualDistance);\n\n\t// =====================================================================================================\n\n\tif ( nProcsInWorld == 1 ) {\n//\t\tDMDAGetGhostCorners(gr.getDA(), &x, &y, &z, &m, &n, &p);\n//\t\tfor (int k = z; k < z+p; ++k) {\n//\t\t\tfor (int j = y; j < y+n; ++j) {\n//\t\t \t\tfor (int i = x; i < x+m; ++i) {\n//\t\t \t\t\tif ( data_ptr[k][j][i] >= 10E+5 )\n//\t\t \t\t\t\tdata_ptr[k][j][i] = -10;\n//\t\t\t\t}\n//\t\t\t}\n//\t\t}\n\t\tDMDAVecRestoreArray(gr.getDA(), localData, &data_ptr);\n\t\treturn;\n\t}\n\n\tint boundariesToInit = selectBoundaries(geom.aabb, gr.getNodeSpan(myWorldRank));\n\tinitBoundaries_nlb(gr, geom, data_ptr, boundariesToInit);\n\t// initAll(gr, geom, data_ptr);\n\n//=======================================================================================\n//\t  DMDAGetGhostCorners(gr.getDA(), &x, &y, &z, &m, &n, &p);\n//\t  for (int k = z; k < z+p; ++k) {\n//\t  \tfor (int j = y; j < y+n; ++j) {\n//\t  \t\tfor (int i = x; i < x+m; ++i) {\n//\t  \t\t\tif ( data_ptr[k][j][i] >= 10E+5 ) {\n//\t  \t\t\t\tdata_ptr[k][j][i] = -10;\n//\t  \t\t\t}\n//\t  \t\t}\n//\t  \t}\n//\t  }\n//=======================================================================================\n\n\tDMDAVecRestoreArray(gr.getDA(), localData, &data_ptr);\n\n}\n\n\nint Initializer::selectBoundaries(const Box<double, 3>& geometryAABB, const Box<double, 3>& procAABB) {\n\t// chooses which boundaries of the domain have to be initialized\n\t// ordering : [left, right, bottom, top, front, back]\n\n\tint selectedBoundaries_int = 0;\n\n\tfor (int i = 0; i < 3; ++i) {\n\t\t//gr->getLocalGhostedMax(i) <= dataProvider->getMaxX(i)\n\t\tif ( procAABB.maxX(i) <= geometryAABB.maxX(i) ) {\n\t\t\tselectedBoundaries_int |= ( 1 << (i*2 + 1) );\n\t\t}\n\t\t// gr->getLocalGhostedMin(i) >= dataProvider->getMinX(i)\n\t\tif ( procAABB.minX(i) >= geometryAABB.minX(i) ) {\n\t\t\tselectedBoundaries_int |= ( 1 << (i*2) );\n\t\t}\n\t}\n\n\treturn selectedBoundaries_int;\n\n}\n\n\ntemplate <typename type, int dim>\nvoid Initializer::putDataToBoundaries(const Grid<type, dim>& gr, double*** data_ptr, cDistance* distanceData, int cellNum, int boundaries) {\n\n\tint       x, y, z, m, n, p;\n\tint       cellCounter = 0, gh = 1;\n\n\tDMDAGetGhostCorners(gr.getDA(), &x, &y, &z, &m, &n, &p);\n//\tDMDAGetCorners(gr.getDA(), &x, &y, &z, &m, &n, &p);\n\tint tmpSum = 0;\n\tif ( boundaries & 1 ) {\n\t\ttmpSum+= gh*n*p;\n\t\t// this means lets initialize left side\n\t\tfor (int i = x; i < x+gh; ++i) {\n\t\t\tfor (int j = y; j < y+n; ++j) {\n\t\t\t\tfor (int k = z; k < z+p; ++k) {\n\t\t\t\t\tdata_ptr[k][j][i+1] = distanceData[cellCounter].signedDistance;\n\t\t\t\t\tcellCounter++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif ( boundaries & 2 ) {\n\t\ttmpSum += gh*n*p;\n\t\t// this means lets initialize right side\n\t\tfor (int i = x+m-1; i > x+m-1-gh; --i) {\n\t\t\tfor (int j = y; j < y+n; ++j) {\n\t\t\t\tfor (int k = z; k < z+p; ++k) {\n\t\t\t\t\tdata_ptr[k][j][i-1] = distanceData[cellCounter].signedDistance;\n\t\t\t\t\tcellCounter++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif ( boundaries & 4 ) {\n\t\ttmpSum += gh*m*p;\n\t\t// this means initialize the bottom side\n\t\tfor (int j = y; j < y+gh; ++j) {\n\t\t\tfor (int i = x; i < x+m; ++i) {\n\t\t\t\tfor (int k = z; k < z+p; ++k) {\n\t\t\t\t\tdata_ptr[k][j+1][i] = distanceData[cellCounter].signedDistance;\n\t\t\t\t\tcellCounter++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif ( boundaries & 8 ) {\n\t\ttmpSum += gh*m*p;\n\t\t// this means initialize the top side\n\t\tfor (int j = y+n-1; j > y+n-1-gh; --j) {\n\t\t\tfor (int i = x; i < x+m; ++i) {\n\t\t\t\tfor (int k = z; k < z+p; ++k) {\n\t\t\t\t\tdata_ptr[k][j-1][i] = distanceData[cellCounter].signedDistance;\n\t\t\t\t\tcellCounter++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif ( boundaries & 16 ) {\n\t\ttmpSum += gh*m*n;\n\t\t// this means initialize the front side\n\t\tfor (int k = z; k < z+gh; ++k) {\n\t\t\tfor (int i = x; i < x+m; ++i) {\n\t\t\t\tfor (int j = y; j < y+n; ++j) {\n\t\t\t\t\tdata_ptr[k+1][j][i] = distanceData[cellCounter].signedDistance;\n\t\t\t\t\tcellCounter++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif ( boundaries & 32 ) {\n\t\ttmpSum += gh*m*n;\n\t\t// this means initialize the far side\n\t\tfor (int k = z+p-1; k > z+p-1-gh; --k) {\n\t\t\tfor (int i = x; i < x+m; ++i) {\n\t\t\t\tfor (int j = y; j < y+n; ++j) {\n\t\t\t\t\tdata_ptr[k-1][j][i] = distanceData[cellCounter].signedDistance;\n\t\t\t\t\tcellCounter++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tassert( cellNum == tmpSum );\n\n}\n\ntemplate <typename type, int dim>\nvoid Initializer::putLocalDataInside(const Grid<type, dim>& gr, double*** data_ptr, const std::vector<int>& localTriangles, const Geometry& geom, double*** perpendicualDistance) {\n\tint       x, y, z, m, n, p;\n\tdouble    narrowBand = gr.getDx(0) * 3;\n\tdouble    minDX      = Eigen::Array3d(gr.getDx(0), gr.getDx(1), gr.getDx(2)).minCoeff();\n\tdouble    eps        = my_eps;\n\n\tDMDAGetGhostCorners(gr.getDA(), &x, &y, &z, &m, &n, &p);\n\n//\t std::cout << \"number of triangles = \" << localTriangles.size() << std::endl;\n//\t for (auto i: localTriangles) {\n//\t\t std::cout << i << \", \";\n//\t }\n//\t std::cout << std::endl;\n\n\tif ( localTriangles.size() == 0 )\n\t\treturn;\n\n\n\tfor (auto index: localTriangles) {\n\t\tTriangleElement<double> currentElement = geom.getElement(index);\n\n//\t\tstd::cout << currentElement << std::endl;\n//\t\tstd::cout << currentElement.getBoundingBox() << std::endl;\n\n\t\tBox<int, 3> ind = gr.getGlobalBoxIndices( currentElement.getBoundingBox() );\n\n//\t\tstd::cout << ind << std::endl;\n\n\n\t\tauto bl = ind.bl();\n\t\tauto tr = ind.tr();\n\n\t\tfor ( int k = bl[2]; k <= tr[2]; ++k ) {\n\n\t\t\tif ( k < z || k >= (z+p) )\n\t\t\t\tcontinue;\n\n\t\t\tfor ( int j = bl[1]; j <= tr[1]; ++j ) {\n\t\t\t\t\n\t\t\t\tif ( j < y || j >= (y+n) )\n\t\t\t\t\tcontinue;\n\n\t\t\t\tfor ( int i = bl[0]; i <= tr[0]; ++i ) {\n\n\t\t\t\t\tif ( i < x || i >= (x+m) ) \n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tEigen::Vector3d        p       = gr.getCoord( Eigen::Vector3i(i,j,k) );\n\n\t\t\t\t\tSignedDistance<double> v       = TriangleElement<double>::computeDistance(currentElement, p);\n\t\t\t\t\tdouble                 pd      = TriangleElement<double>::computePerpendicularDistance(currentElement, p);\n\n\n\t\t\t\t\tif ( v.dist > narrowBand ) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( v.dist < eps ) {\n\n\t\t\t\t\t\tdata_ptr[k][j][i]             = eps * v.sign;\n\t\t\t\t\t\tperpendicualDistance[k][j][i] = eps;\n\n\t\t\t\t\t}  else if ( fabs( v.dist - fabs(data_ptr[k][j][i]) ) < eps ) {\n\n\t\t\t\t\t\t// equal not funny\n\t\t\t\t\t\tif ( perpendicualDistance[k][j][i] <= pd ) {\n\t\t\t\t\t\t\tdata_ptr[k][j][i]             = v.sign * v.dist;\n\t\t\t\t\t\t\tperpendicualDistance[k][j][i] = pd;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else if ( v.dist < fabs(data_ptr[k][j][i]) ) {\n\n\t\t\t\t\t\t// less so ok than\n\t\t\t\t\t\tdata_ptr[k][j][i]             = v.sign * v.dist;\n\t\t\t\t\t\tperpendicualDistance[k][j][i] = pd;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n}\n\n\n#endif\n", "meta": {"hexsha": "d18d327654267a2cea07e5c4d0b2709bcadb08ba", "size": 22190, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Initializer.hpp", "max_stars_repo_name": "petrkotas/libLS", "max_stars_repo_head_hexsha": "eb57365bfb0be486a4e8c564ff831ad358993268", "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/Initializer.hpp", "max_issues_repo_name": "petrkotas/libLS", "max_issues_repo_head_hexsha": "eb57365bfb0be486a4e8c564ff831ad358993268", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Initializer.hpp", "max_forks_repo_name": "petrkotas/libLS", "max_forks_repo_head_hexsha": "eb57365bfb0be486a4e8c564ff831ad358993268", "max_forks_repo_licenses": ["BSD-3-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.5866666667, "max_line_length": 180, "alphanum_fraction": 0.6114916629, "num_tokens": 7043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.25481315970232027}}
{"text": "/*\n * L2RightHandSide.cc\n *\n *  Created on: 29.06.2017\n *      Author: thies\n */\n\n#include <deal.II/base/exceptions.h>\n#include <deal.II/base/work_stream.h>\n#include <deal.II/fe/fe_update_flags.h>\n#include <deal.II/numerics/vector_tools.h>\n\n#include <base/DiscretizedFunction.h>\n#include <forward/L2RightHandSide.h>\n\n#include <functional>\n\nnamespace wavepi {\nnamespace forward {\nusing namespace dealii;\nusing namespace wavepi::base;\n\ntemplate <int dim>\nL2RightHandSide<dim>::L2RightHandSide(std::shared_ptr<Function<dim>> f) : base_rhs(f) {}\n\ntemplate <int dim>\nL2RightHandSide<dim>::AssemblyScratchData::AssemblyScratchData(const FiniteElement<dim> &fe,\n                                                               const Quadrature<dim> &quad)\n    : fe_values(fe, quad, update_values | update_quadrature_points | update_JxW_values) {}\n\ntemplate <int dim>\nL2RightHandSide<dim>::AssemblyScratchData::AssemblyScratchData(const AssemblyScratchData &scratch_data)\n    : fe_values(scratch_data.fe_values.get_fe(), scratch_data.fe_values.get_quadrature(),\n                update_values | update_quadrature_points | update_JxW_values) {}\n\ntemplate <int dim>\nvoid L2RightHandSide<dim>::copy_local_to_global(Vector<double> &result, const AssemblyCopyData &copy_data) {\n  for (unsigned int i = 0; i < copy_data.local_dof_indices.size(); ++i)\n    result(copy_data.local_dof_indices[i]) += copy_data.cell_rhs(i);\n}\n\ntemplate <int dim>\nstd::shared_ptr<Function<dim>> L2RightHandSide<dim>::get_base_rhs() const {\n  return base_rhs;\n}\n\ntemplate <int dim>\nvoid L2RightHandSide<dim>::set_base_rhs(std::shared_ptr<Function<dim>> base_rhs) {\n  this->base_rhs = base_rhs;\n}\n\ntemplate <int dim>\nvoid L2RightHandSide<dim>::local_assemble(const Vector<double> &f,\n                                          const typename DoFHandler<dim>::active_cell_iterator &cell,\n                                          AssemblyScratchData &scratch_data, AssemblyCopyData &copy_data) {\n  const unsigned int dofs_per_cell = scratch_data.fe_values.get_fe().dofs_per_cell;\n  const unsigned int n_q_points    = scratch_data.fe_values.get_quadrature().size();\n\n  copy_data.cell_rhs.reinit(dofs_per_cell);\n  copy_data.local_dof_indices.resize(dofs_per_cell);\n  scratch_data.fe_values.reinit(cell);\n\n  cell->get_dof_indices(copy_data.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      for (unsigned int k = 0; k < dofs_per_cell; ++k)\n        copy_data.cell_rhs(i) += f[copy_data.local_dof_indices[k]] * scratch_data.fe_values.shape_value(k, q_point) *\n                                 scratch_data.fe_values.shape_value(i, q_point) * scratch_data.fe_values.JxW(q_point);\n}\n\ntemplate <int dim>\nvoid L2RightHandSide<dim>::create_right_hand_side(const DoFHandler<dim> &dof, const Quadrature<dim> &quad,\n                                                  Vector<double> &rhs) const {\n  AssertThrow(base_rhs, ExcInternalError());\n  base_rhs->set_time(this->get_time());\n\n  auto base_rhs_d = std::dynamic_pointer_cast<DiscretizedFunction<dim>>(base_rhs);\n\n  if (base_rhs_d) {\n    Vector<double> coeffs = base_rhs_d->get_function_coefficients(base_rhs_d->get_time_index());\n    Assert(coeffs.size() == dof.n_dofs(), ExcDimensionMismatch(coeffs.size(), dof.n_dofs()));\n\n    WorkStream::run(dof.begin_active(), dof.end(),\n                    std::bind(&L2RightHandSide<dim>::local_assemble, *this, std::ref(coeffs), std::placeholders::_1,\n                              std::placeholders::_2, std::placeholders::_3),\n                    std::bind(&L2RightHandSide<dim>::copy_local_to_global, *this, std::ref(rhs), std::placeholders::_1),\n                    AssemblyScratchData(dof.get_fe(), quad), AssemblyCopyData());\n  } else\n    VectorTools::create_right_hand_side(dof, quad, *base_rhs.get(), rhs);\n}\n\ntemplate class L2RightHandSide<1>;\ntemplate class L2RightHandSide<2>;\ntemplate class L2RightHandSide<3>;\n\n} /* namespace forward */\n} /* namespace wavepi */\n", "meta": {"hexsha": "a833ada487f3d23d052f1c115826a6a84716a217", "size": 4007, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/forward/L2RightHandSide.cpp", "max_stars_repo_name": "thiesgerken/wavepi", "max_stars_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "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/forward/L2RightHandSide.cpp", "max_issues_repo_name": "thiesgerken/wavepi", "max_issues_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/forward/L2RightHandSide.cpp", "max_forks_repo_name": "thiesgerken/wavepi", "max_forks_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_forks_repo_licenses": ["BSD-3-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.4747474747, "max_line_length": 120, "alphanum_fraction": 0.6935363115, "num_tokens": 992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2548131597023202}}
{"text": "// Copyright (c) 2020, The Evolution Network\n// Copyright (c) 2018-2019, The Arqma Network\n// Copyright (c) 2017-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// Adapted from Java code by Sarang Noether\n\n#include <stdlib.h>\n#include <openssl/ssl.h>\n#include <boost/thread/mutex.hpp>\n#include <boost/thread/lock_guard.hpp>\n#include \"misc_log_ex.h\"\n#include \"common/perf_timer.h\"\nextern \"C\"\n{\n#include \"crypto/crypto-ops.h\"\n}\n#include \"rctOps.h\"\n#include \"multiexp.h\"\n#include \"bulletproofs.h\"\n\n#undef EVOLUTION_DEFAULT_LOG_CATEGORY\n#define EVOLUTION_DEFAULT_LOG_CATEGORY \"bulletproofs_legacy\"\n\n//#define DEBUG_BP\n\n#define PERF_TIMER_START_BP(x) PERF_TIMER_START_UNIT(x, 1000000)\n\nnamespace rct\n{\n\nstatic rct::key vector_exponent(const rct::keyV &a, const rct::keyV &b);\nstatic rct::keyV vector_powers(const rct::key &x, size_t n);\nstatic rct::keyV vector_dup(const rct::key &x, size_t n);\nstatic rct::key inner_product(const rct::keyV &a, const rct::keyV &b);\n\nstatic constexpr size_t maxN = 64;\nstatic constexpr size_t maxM = 16;\nstatic rct::key Hi[maxN*maxM], Gi[maxN*maxM];\nstatic ge_p3 Hi_p3[maxN*maxM], Gi_p3[maxN*maxM];\nstatic ge_dsmp Gprecomp[maxN*maxM], Hprecomp[maxN*maxM];\nstatic std::shared_ptr<straus_cached_data> HiGi_cache;\nstatic const rct::key TWO = { {0x02, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00  } };\nstatic const rct::keyV oneN = vector_dup(rct::identity(), maxN);\nstatic const rct::keyV twoN = vector_powers(TWO, maxN);\nstatic const rct::key ip12 = inner_product(oneN, twoN);\nstatic boost::mutex init_mutex;\n\nstatic inline rct::key multiexp(const std::vector<MultiexpData> &data, bool HiGi)\n{\n  static const size_t STEP = getenv(\"STRAUS_STEP\") ? atoi(getenv(\"STRAUS_STEP\")) : 0;\n  if (HiGi || data.size() < 1000)\n    return straus(data, HiGi ? HiGi_cache: NULL, STEP);\n  else\n    return bos_coster_heap_conv_robust(data);\n}\n\n//addKeys3acc_p3\n//aAbB += a*A + b*B where a, b are scalars, A, B are curve points\n//A and B must be input after applying \"precomp\"\nstatic void addKeys3acc_p3(ge_p3 *aAbB, const key &a, const ge_dsmp A, const key &b, const ge_dsmp B)\n{\n    ge_p3 rv;\n    ge_p1p1 p1;\n    ge_p2 p2;\n    ge_double_scalarmult_precomp_vartime2_p3(&rv, a.bytes, A, b.bytes, B);\n    ge_cached cached;\n    ge_p3_to_cached(&cached, aAbB);\n    ge_add(&p1, &rv, &cached);\n    ge_p1p1_to_p3(aAbB, &p1);\n}\n\nstatic void addKeys_acc_p3(ge_p3 *acc_p3, const rct::key &a, const rct::key &point)\n{\n    ge_p3 p3;\n    CHECK_AND_ASSERT_THROW_MES(ge_frombytes_vartime(&p3, point.bytes) == 0, \"ge_frombytes_vartime failed\");\n    ge_scalarmult_p3(&p3, a.bytes, &p3);\n    ge_cached cached;\n    ge_p3_to_cached(&cached, acc_p3);\n    ge_p1p1 p1;\n    ge_add(&p1, &p3, &cached);\n    ge_p1p1_to_p3(acc_p3, &p1);\n}\n\nstatic rct::key get_exponent(const rct::key &base, size_t idx)\n{\n  static const std::string salt(\"bulletproof\");\n  std::string hashed = std::string((const char*)base.bytes, sizeof(base)) + salt + tools::get_varint_data(idx);\n  return rct::hashToPoint(rct::hash2rct(crypto::cn_fast_hash(hashed.data(), hashed.size())));\n}\n\nstatic void init_exponents()\n{\n  boost::lock_guard<boost::mutex> lock(init_mutex);\n\n  static bool init_done = false;\n  if (init_done)\n    return;\n  std::vector<MultiexpData> data;\n  for (size_t i = 0; i < maxN*maxM; ++i)\n  {\n    Hi[i] = get_exponent(rct::H, i * 2);\n    rct::precomp(Hprecomp[i], Hi[i]);\n    CHECK_AND_ASSERT_THROW_MES(ge_frombytes_vartime(&Hi_p3[i], Hi[i].bytes) == 0, \"ge_frombytes_vartime failed\");\n    Gi[i] = get_exponent(rct::H, i * 2 + 1);\n    rct::precomp(Gprecomp[i], Gi[i]);\n    CHECK_AND_ASSERT_THROW_MES(ge_frombytes_vartime(&Gi_p3[i], Gi[i].bytes) == 0, \"ge_frombytes_vartime failed\");\n\n    data.push_back({rct::zero(), Gi[i]});\n    data.push_back({rct::zero(), Hi[i]});\n  }\n  HiGi_cache = straus_init_cache(data);\n  size_t cache_size = (sizeof(Hi)+sizeof(Hprecomp)+sizeof(Hi_p3))*2 + straus_get_cache_size(HiGi_cache);\n  MINFO(\"cache size: \" << cache_size/1024 << \" kB\");\n  init_done = true;\n}\n\n/* Given two scalar arrays, construct a vector commitment */\nstatic rct::key vector_exponent(const rct::keyV &a, const rct::keyV &b)\n{\n  CHECK_AND_ASSERT_THROW_MES(a.size() == b.size(), \"Incompatible sizes of a and b\");\n  CHECK_AND_ASSERT_THROW_MES(a.size() <= maxN*maxM, \"Incompatible sizes of a and maxN\");\n\n  std::vector<MultiexpData> multiexp_data;\n  multiexp_data.reserve(a.size()*2);\n  for (size_t i = 0; i < a.size(); ++i)\n  {\n    multiexp_data.emplace_back(a[i], Gi_p3[i]);\n    multiexp_data.emplace_back(b[i], Hi_p3[i]);\n  }\n  return multiexp(multiexp_data, true);\n}\n\n/* Compute a custom vector-scalar commitment */\nstatic rct::key vector_exponent_custom(const rct::keyV &A, const rct::keyV &B, const rct::keyV &a, const rct::keyV &b)\n{\n  CHECK_AND_ASSERT_THROW_MES(A.size() == B.size(), \"Incompatible sizes of A and B\");\n  CHECK_AND_ASSERT_THROW_MES(a.size() == b.size(), \"Incompatible sizes of a and b\");\n  CHECK_AND_ASSERT_THROW_MES(a.size() == A.size(), \"Incompatible sizes of a and A\");\n  CHECK_AND_ASSERT_THROW_MES(a.size() <= maxN*maxM, \"Incompatible sizes of a and maxN\");\n\n  std::vector<MultiexpData> multiexp_data;\n  multiexp_data.reserve(a.size()*2);\n  for (size_t i = 0; i < a.size(); ++i)\n  {\n    multiexp_data.resize(multiexp_data.size() + 1);\n    multiexp_data.back().scalar = a[i];\n    CHECK_AND_ASSERT_THROW_MES(ge_frombytes_vartime(&multiexp_data.back().point, A[i].bytes) == 0, \"ge_frombytes_vartime failed\");\n    multiexp_data.resize(multiexp_data.size() + 1);\n    multiexp_data.back().scalar = b[i];\n    CHECK_AND_ASSERT_THROW_MES(ge_frombytes_vartime(&multiexp_data.back().point, B[i].bytes) == 0, \"ge_frombytes_vartime failed\");\n  }\n  return multiexp(multiexp_data, false);\n}\n\n/* Given a scalar, construct a vector of powers */\nstatic rct::keyV vector_powers(const rct::key &x, size_t n)\n{\n  rct::keyV res(n);\n  if (n == 0)\n    return res;\n  res[0] = rct::identity();\n  if (n == 1)\n    return res;\n  res[1] = x;\n  for (size_t i = 2; i < n; ++i)\n  {\n    sc_mul(res[i].bytes, res[i-1].bytes, x.bytes);\n  }\n  return res;\n}\n\n/* Given a scalar, return the sum of its powers from 0 to n-1 */\nstatic rct::key vector_power_sum(const rct::key &x, size_t n)\n{\n  if (n == 0)\n    return rct::zero();\n  rct::key res = rct::identity();\n  if (n == 1)\n    return res;\n  rct::key prev = x;\n  for (size_t i = 1; i < n; ++i)\n  {\n    if (i > 1)\n      sc_mul(prev.bytes, prev.bytes, x.bytes);\n    sc_add(res.bytes, res.bytes, prev.bytes);\n  }\n  return res;\n}\n\n/* Given two scalar arrays, construct the inner product */\nstatic rct::key inner_product(const rct::keyV &a, const rct::keyV &b)\n{\n  CHECK_AND_ASSERT_THROW_MES(a.size() == b.size(), \"Incompatible sizes of a and b\");\n  rct::key res = rct::zero();\n  for (size_t i = 0; i < a.size(); ++i)\n  {\n    sc_muladd(res.bytes, a[i].bytes, b[i].bytes, res.bytes);\n  }\n  return res;\n}\n\n/* Given two scalar arrays, construct the Hadamard product */\nstatic rct::keyV hadamard(const rct::keyV &a, const rct::keyV &b)\n{\n  CHECK_AND_ASSERT_THROW_MES(a.size() == b.size(), \"Incompatible sizes of a and b\");\n  rct::keyV res(a.size());\n  for (size_t i = 0; i < a.size(); ++i)\n  {\n    sc_mul(res[i].bytes, a[i].bytes, b[i].bytes);\n  }\n  return res;\n}\n\n/* Given two curvepoint arrays, construct the Hadamard product */\nstatic rct::keyV hadamard2(const rct::keyV &a, const rct::keyV &b)\n{\n  CHECK_AND_ASSERT_THROW_MES(a.size() == b.size(), \"Incompatible sizes of a and b\");\n  rct::keyV res(a.size());\n  for (size_t i = 0; i < a.size(); ++i)\n  {\n    rct::addKeys(res[i], a[i], b[i]);\n  }\n  return res;\n}\n\n/* Add two vectors */\nstatic rct::keyV vector_add(const rct::keyV &a, const rct::keyV &b)\n{\n  CHECK_AND_ASSERT_THROW_MES(a.size() == b.size(), \"Incompatible sizes of a and b\");\n  rct::keyV res(a.size());\n  for (size_t i = 0; i < a.size(); ++i)\n  {\n    sc_add(res[i].bytes, a[i].bytes, b[i].bytes);\n  }\n  return res;\n}\n\n/* Subtract two vectors */\nstatic rct::keyV vector_subtract(const rct::keyV &a, const rct::keyV &b)\n{\n  CHECK_AND_ASSERT_THROW_MES(a.size() == b.size(), \"Incompatible sizes of a and b\");\n  rct::keyV res(a.size());\n  for (size_t i = 0; i < a.size(); ++i)\n  {\n    sc_sub(res[i].bytes, a[i].bytes, b[i].bytes);\n  }\n  return res;\n}\n\n/* Multiply a scalar and a vector */\nstatic rct::keyV vector_scalar(const rct::keyV &a, const rct::key &x)\n{\n  rct::keyV res(a.size());\n  for (size_t i = 0; i < a.size(); ++i)\n  {\n    sc_mul(res[i].bytes, a[i].bytes, x.bytes);\n  }\n  return res;\n}\n\n/* Create a vector from copies of a single value */\nstatic rct::keyV vector_dup(const rct::key &x, size_t N)\n{\n  return rct::keyV(N, x);\n}\n\n/* Exponentiate a curve vector by a scalar */\nstatic rct::keyV vector_scalar2(const rct::keyV &a, const rct::key &x)\n{\n  rct::keyV res(a.size());\n  for (size_t i = 0; i < a.size(); ++i)\n  {\n    rct::scalarmultKey(res[i], a[i], x);\n  }\n  return res;\n}\n\n/* Get the sum of a vector's elements */\nstatic rct::key vector_sum(const rct::keyV &a)\n{\n  rct::key res = rct::zero();\n  for (size_t i = 0; i < a.size(); ++i)\n  {\n    sc_add(res.bytes, res.bytes, a[i].bytes);\n  }\n  return res;\n}\n\nstatic rct::key switch_endianness(rct::key k)\n{\n  std::reverse(k.bytes, k.bytes + sizeof(k));\n  return k;\n}\n\n/* Compute the inverse of a scalar, the stupid way */\nstatic rct::key invert(const rct::key &x)\n{\n  rct::key inv;\n\n  BN_CTX *ctx = BN_CTX_new();\n  BIGNUM *X = BN_new();\n  BIGNUM *L = BN_new();\n  BIGNUM *I = BN_new();\n\n  BN_bin2bn(switch_endianness(x).bytes, sizeof(rct::key), X);\n  BN_bin2bn(switch_endianness(rct::curveOrder()).bytes, sizeof(rct::key), L);\n\n  CHECK_AND_ASSERT_THROW_MES(BN_mod_inverse(I, X, L, ctx), \"Failed to invert\");\n\n  const int len = BN_num_bytes(I);\n  CHECK_AND_ASSERT_THROW_MES((size_t)len <= sizeof(rct::key), \"Invalid number length\");\n  inv = rct::zero();\n  BN_bn2bin(I, inv.bytes);\n  std::reverse(inv.bytes, inv.bytes + len);\n\n  BN_free(I);\n  BN_free(L);\n  BN_free(X);\n  BN_CTX_free(ctx);\n\n#ifdef DEBUG_BP\n  rct::key tmp;\n  sc_mul(tmp.bytes, inv.bytes, x.bytes);\n  CHECK_AND_ASSERT_THROW_MES(tmp == rct::identity(), \"invert failed\");\n#endif\n  return inv;\n}\n\n/* Compute the slice of a vector */\nstatic rct::keyV slice(const rct::keyV &a, size_t start, size_t stop)\n{\n  CHECK_AND_ASSERT_THROW_MES(start < a.size(), \"Invalid start index\");\n  CHECK_AND_ASSERT_THROW_MES(stop <= a.size(), \"Invalid stop index\");\n  CHECK_AND_ASSERT_THROW_MES(start < stop, \"Invalid start/stop indices\");\n  rct::keyV res(stop - start);\n  for (size_t i = start; i < stop; ++i)\n  {\n    res[i - start] = a[i];\n  }\n  return res;\n}\n\nstatic rct::key hash_cache_mash(rct::key &hash_cache, const rct::key &mash0, const rct::key &mash1)\n{\n  rct::keyV data;\n  data.reserve(3);\n  data.push_back(hash_cache);\n  data.push_back(mash0);\n  data.push_back(mash1);\n  return hash_cache = rct::hash_to_scalar(data);\n}\n\nstatic rct::key hash_cache_mash(rct::key &hash_cache, const rct::key &mash0, const rct::key &mash1, const rct::key &mash2)\n{\n  rct::keyV data;\n  data.reserve(4);\n  data.push_back(hash_cache);\n  data.push_back(mash0);\n  data.push_back(mash1);\n  data.push_back(mash2);\n  return hash_cache = rct::hash_to_scalar(data);\n}\n\nstatic rct::key hash_cache_mash(rct::key &hash_cache, const rct::key &mash0, const rct::key &mash1, const rct::key &mash2, const rct::key &mash3)\n{\n  rct::keyV data;\n  data.reserve(5);\n  data.push_back(hash_cache);\n  data.push_back(mash0);\n  data.push_back(mash1);\n  data.push_back(mash2);\n  data.push_back(mash3);\n  return hash_cache = rct::hash_to_scalar(data);\n}\n\n/* Given a value v (0..2^N-1) and a mask gamma, construct a range proof */\nBulletproof bulletproof_PROVE_old(const rct::key &sv, const rct::key &gamma)\n{\n  init_exponents();\n\n  PERF_TIMER_UNIT(PROVE, 1000000);\n\n  constexpr size_t logN = 6; // log2(64)\n  constexpr size_t N = 1<<logN;\n\n  rct::key V;\n  rct::keyV aL(N), aR(N);\n\n  PERF_TIMER_START_BP(PROVE_v);\n  rct::addKeys2(V, gamma, sv, rct::H);\n  PERF_TIMER_STOP(PROVE_v);\n\n  PERF_TIMER_START_BP(PROVE_aLaR);\n  for (size_t i = N; i-- > 0; )\n  {\n    if (sv[i/8] & (((uint64_t)1)<<(i%8)))\n    {\n      aL[i] = rct::identity();\n    }\n    else\n    {\n      aL[i] = rct::zero();\n    }\n    sc_sub(aR[i].bytes, aL[i].bytes, rct::identity().bytes);\n  }\n  PERF_TIMER_STOP(PROVE_aLaR);\n\n  rct::key hash_cache = rct::hash_to_scalar(V);\n\n  // DEBUG: Test to ensure this recovers the value\n#ifdef DEBUG_BP\n  uint64_t test_aL = 0, test_aR = 0;\n  for (size_t i = 0; i < N; ++i)\n  {\n    if (aL[i] == rct::identity())\n      test_aL += ((uint64_t)1)<<i;\n    if (aR[i] == rct::zero())\n      test_aR += ((uint64_t)1)<<i;\n  }\n  uint64_t v_test = 0;\n  for (int n = 0; n < 8; ++n) v_test |= (((uint64_t)sv[n]) << (8*n));\n  CHECK_AND_ASSERT_THROW_MES(test_aL == v_test, \"test_aL failed\");\n  CHECK_AND_ASSERT_THROW_MES(test_aR == v_test, \"test_aR failed\");\n#endif\n\n  PERF_TIMER_START_BP(PROVE_step1);\n  // PAPER LINES 38-39\n  rct::key alpha = rct::skGen();\n  rct::key ve = vector_exponent(aL, aR);\n  rct::key A;\n  rct::addKeys(A, ve, rct::scalarmultBase(alpha));\n\n  // PAPER LINES 40-42\n  rct::keyV sL = rct::skvGen(N), sR = rct::skvGen(N);\n  rct::key rho = rct::skGen();\n  ve = vector_exponent(sL, sR);\n  rct::key S;\n  rct::addKeys(S, ve, rct::scalarmultBase(rho));\n\n  // PAPER LINES 43-45\n  rct::key y = hash_cache_mash(hash_cache, A, S);\n  rct::key z = hash_cache = rct::hash_to_scalar(y);\n\n  // Polynomial construction before PAPER LINE 46\n  rct::key t0 = rct::zero();\n  rct::key t1 = rct::zero();\n  rct::key t2 = rct::zero();\n\n  const auto yN = vector_powers(y, N);\n\n  rct::key ip1y = vector_sum(yN);\n  rct::key tmp;\n  sc_muladd(t0.bytes, z.bytes, ip1y.bytes, t0.bytes);\n\n  rct::key zsq;\n  sc_mul(zsq.bytes, z.bytes, z.bytes);\n  sc_muladd(t0.bytes, zsq.bytes, sv.bytes, t0.bytes);\n\n  rct::key k = rct::zero();\n  sc_mulsub(k.bytes, zsq.bytes, ip1y.bytes, k.bytes);\n\n  rct::key zcu;\n  sc_mul(zcu.bytes, zsq.bytes, z.bytes);\n  sc_mulsub(k.bytes, zcu.bytes, ip12.bytes, k.bytes);\n  sc_add(t0.bytes, t0.bytes, k.bytes);\n\n  // DEBUG: Test the value of t0 has the correct form\n#ifdef DEBUG_BP\n  rct::key test_t0 = rct::zero();\n  rct::key iph = inner_product(aL, hadamard(aR, yN));\n  sc_add(test_t0.bytes, test_t0.bytes, iph.bytes);\n  rct::key ips = inner_product(vector_subtract(aL, aR), yN);\n  sc_muladd(test_t0.bytes, z.bytes, ips.bytes, test_t0.bytes);\n  rct::key ipt = inner_product(twoN, aL);\n  sc_muladd(test_t0.bytes, zsq.bytes, ipt.bytes, test_t0.bytes);\n  sc_add(test_t0.bytes, test_t0.bytes, k.bytes);\n  CHECK_AND_ASSERT_THROW_MES(t0 == test_t0, \"t0 check failed\");\n#endif\n  PERF_TIMER_STOP(PROVE_step1);\n\n  PERF_TIMER_START_BP(PROVE_step2);\n  const auto HyNsR = hadamard(yN, sR);\n  const auto vpIz = vector_dup(z, N);\n  const auto vp2zsq = vector_scalar(twoN, zsq);\n  const auto aL_vpIz = vector_subtract(aL, vpIz);\n  const auto aR_vpIz = vector_add(aR, vpIz);\n\n  rct::key ip1 = inner_product(aL_vpIz, HyNsR);\n  sc_add(t1.bytes, t1.bytes, ip1.bytes);\n\n  rct::key ip2 = inner_product(sL, vector_add(hadamard(yN, aR_vpIz), vp2zsq));\n  sc_add(t1.bytes, t1.bytes, ip2.bytes);\n\n  rct::key ip3 = inner_product(sL, HyNsR);\n  sc_add(t2.bytes, t2.bytes, ip3.bytes);\n\n  // PAPER LINES 47-48\n  rct::key tau1 = rct::skGen(), tau2 = rct::skGen();\n\n  rct::key T1 = rct::addKeys(rct::scalarmultKey(rct::H, t1), rct::scalarmultBase(tau1));\n  rct::key T2 = rct::addKeys(rct::scalarmultKey(rct::H, t2), rct::scalarmultBase(tau2));\n\n  // PAPER LINES 49-51\n  rct::key x = hash_cache_mash(hash_cache, z, T1, T2);\n\n  // PAPER LINES 52-53\n  rct::key taux = rct::zero();\n  sc_mul(taux.bytes, tau1.bytes, x.bytes);\n  rct::key xsq;\n  sc_mul(xsq.bytes, x.bytes, x.bytes);\n  sc_muladd(taux.bytes, tau2.bytes, xsq.bytes, taux.bytes);\n  sc_muladd(taux.bytes, gamma.bytes, zsq.bytes, taux.bytes);\n  rct::key mu;\n  sc_muladd(mu.bytes, x.bytes, rho.bytes, alpha.bytes);\n\n  // PAPER LINES 54-57\n  rct::keyV l = vector_add(aL_vpIz, vector_scalar(sL, x));\n  rct::keyV r = vector_add(hadamard(yN, vector_add(aR_vpIz, vector_scalar(sR, x))), vp2zsq);\n  PERF_TIMER_STOP(PROVE_step2);\n\n  PERF_TIMER_START_BP(PROVE_step3);\n  rct::key t = inner_product(l, r);\n\n  // DEBUG: Test if the l and r vectors match the polynomial forms\n#ifdef DEBUG_BP\n  rct::key test_t;\n  sc_muladd(test_t.bytes, t1.bytes, x.bytes, t0.bytes);\n  sc_muladd(test_t.bytes, t2.bytes, xsq.bytes, test_t.bytes);\n  CHECK_AND_ASSERT_THROW_MES(test_t == t, \"test_t check failed\");\n#endif\n\n  // PAPER LINES 32-33\n  rct::key x_ip = hash_cache_mash(hash_cache, x, taux, mu, t);\n\n  // These are used in the inner product rounds\n  size_t nprime = N;\n  rct::keyV Gprime(N);\n  rct::keyV Hprime(N);\n  rct::keyV aprime(N);\n  rct::keyV bprime(N);\n  const rct::key yinv = invert(y);\n  rct::key yinvpow = rct::identity();\n  for (size_t i = 0; i < N; ++i)\n  {\n    Gprime[i] = Gi[i];\n    Hprime[i] = scalarmultKey(Hi[i], yinvpow);\n    sc_mul(yinvpow.bytes, yinvpow.bytes, yinv.bytes);\n    aprime[i] = l[i];\n    bprime[i] = r[i];\n  }\n  rct::keyV L(logN);\n  rct::keyV R(logN);\n  int round = 0;\n  rct::keyV w(logN); // this is the challenge x in the inner product protocol\n  PERF_TIMER_STOP(PROVE_step3);\n\n  PERF_TIMER_START_BP(PROVE_step4);\n  // PAPER LINE 13\n  while (nprime > 1)\n  {\n    // PAPER LINE 15\n    nprime /= 2;\n\n    // PAPER LINES 16-17\n    rct::key cL = inner_product(slice(aprime, 0, nprime), slice(bprime, nprime, bprime.size()));\n    rct::key cR = inner_product(slice(aprime, nprime, aprime.size()), slice(bprime, 0, nprime));\n\n    // PAPER LINES 18-19\n    L[round] = vector_exponent_custom(slice(Gprime, nprime, Gprime.size()), slice(Hprime, 0, nprime), slice(aprime, 0, nprime), slice(bprime, nprime, bprime.size()));\n    sc_mul(tmp.bytes, cL.bytes, x_ip.bytes);\n    rct::addKeys(L[round], L[round], rct::scalarmultKey(rct::H, tmp));\n    R[round] = vector_exponent_custom(slice(Gprime, 0, nprime), slice(Hprime, nprime, Hprime.size()), slice(aprime, nprime, aprime.size()), slice(bprime, 0, nprime));\n    sc_mul(tmp.bytes, cR.bytes, x_ip.bytes);\n    rct::addKeys(R[round], R[round], rct::scalarmultKey(rct::H, tmp));\n\n    // PAPER LINES 21-22\n    w[round] = hash_cache_mash(hash_cache, L[round], R[round]);\n\n    // PAPER LINES 24-25\n    const rct::key winv = invert(w[round]);\n    Gprime = hadamard2(vector_scalar2(slice(Gprime, 0, nprime), winv), vector_scalar2(slice(Gprime, nprime, Gprime.size()), w[round]));\n    Hprime = hadamard2(vector_scalar2(slice(Hprime, 0, nprime), w[round]), vector_scalar2(slice(Hprime, nprime, Hprime.size()), winv));\n\n    // PAPER LINES 28-29\n    aprime = vector_add(vector_scalar(slice(aprime, 0, nprime), w[round]), vector_scalar(slice(aprime, nprime, aprime.size()), winv));\n    bprime = vector_add(vector_scalar(slice(bprime, 0, nprime), winv), vector_scalar(slice(bprime, nprime, bprime.size()), w[round]));\n\n    ++round;\n  }\n  PERF_TIMER_STOP(PROVE_step4);\n\n  // PAPER LINE 58 (with inclusions from PAPER LINE 8 and PAPER LINE 20)\n  return Bulletproof(V, A, S, T1, T2, taux, mu, L, R, aprime[0], bprime[0], t);\n}\n\nBulletproof bulletproof_PROVE_old(uint64_t v, const rct::key &gamma)\n{\n  // vG + gammaH\n  PERF_TIMER_START_BP(PROVE_v);\n  rct::key sv = rct::zero();\n  sv.bytes[0] = v & 255;\n  sv.bytes[1] = (v >> 8) & 255;\n  sv.bytes[2] = (v >> 16) & 255;\n  sv.bytes[3] = (v >> 24) & 255;\n  sv.bytes[4] = (v >> 32) & 255;\n  sv.bytes[5] = (v >> 40) & 255;\n  sv.bytes[6] = (v >> 48) & 255;\n  sv.bytes[7] = (v >> 56) & 255;\n  PERF_TIMER_STOP(PROVE_v);\n  return bulletproof_PROVE_old(sv, gamma);\n}\n\n/* Given a set of values v (0..2^N-1) and masks gamma, construct a range proof */\nBulletproof bulletproof_PROVE_old(const rct::keyV &sv, const rct::keyV &gamma)\n{\n  CHECK_AND_ASSERT_THROW_MES(sv.size() == gamma.size(), \"Incompatible sizes of sv and gamma\");\n  CHECK_AND_ASSERT_THROW_MES(!sv.empty(), \"sv is empty\");\n\n  init_exponents();\n\n  PERF_TIMER_UNIT(PROVE, 1000000);\n\n  constexpr size_t logN = 6; // log2(64)\n  constexpr size_t N = 1<<logN;\n  size_t M, logM;\n  for (logM = 0; (M = 1<<logM) <= maxM && M < sv.size(); ++logM);\n  CHECK_AND_ASSERT_THROW_MES(M <= maxM, \"sv/gamma are too large\");\n  const size_t logMN = logM + logN;\n  const size_t MN = M * N;\n\n  rct::keyV V(sv.size());\n  rct::keyV aL(MN), aR(MN);\n  rct::key tmp;\n\n  PERF_TIMER_START_BP(PROVE_v);\n  for (size_t i = 0; i < sv.size(); ++i)\n    rct::addKeys2(V[i], gamma[i], sv[i], rct::H);\n  PERF_TIMER_STOP(PROVE_v);\n\n  PERF_TIMER_START_BP(PROVE_aLaR);\n  for (size_t j = 0; j < M; ++j)\n  {\n    for (size_t i = N; i-- > 0; )\n    {\n      if (j >= sv.size())\n      {\n        aL[j*N+i] = rct::zero();\n      }\n      else if (sv[j][i/8] & (((uint64_t)1)<<(i%8)))\n      {\n        aL[j*N+i] = rct::identity();\n      }\n      else\n      {\n        aL[j*N+i] = rct::zero();\n      }\n      sc_sub(aR[j*N+i].bytes, aL[j*N+i].bytes, rct::identity().bytes);\n    }\n  }\n  PERF_TIMER_STOP(PROVE_aLaR);\n\n  rct::key hash_cache = rct::hash_to_scalar(V);\n\n  // DEBUG: Test to ensure this recovers the value\n#ifdef DEBUG_BP\n  for (size_t j = 0; j < M; ++j)\n  {\n    uint64_t test_aL = 0, test_aR = 0;\n    for (size_t i = 0; i < N; ++i)\n    {\n      if (aL[j*N+i] == rct::identity())\n        test_aL += ((uint64_t)1)<<i;\n      if (aR[j*N+i] == rct::zero())\n        test_aR += ((uint64_t)1)<<i;\n    }\n    uint64_t v_test = 0;\n    if (j < sv.size())\n      for (int n = 0; n < 8; ++n) v_test |= (((uint64_t)sv[j][n]) << (8*n));\n    CHECK_AND_ASSERT_THROW_MES(test_aL == v_test, \"test_aL failed\");\n    CHECK_AND_ASSERT_THROW_MES(test_aR == v_test, \"test_aR failed\");\n  }\n#endif\n\n  PERF_TIMER_START_BP(PROVE_step1);\n  // PAPER LINES 38-39\n  rct::key alpha = rct::skGen();\n  rct::key ve = vector_exponent(aL, aR);\n  rct::key A;\n  rct::addKeys(A, ve, rct::scalarmultBase(alpha));\n\n  // PAPER LINES 40-42\n  rct::keyV sL = rct::skvGen(MN), sR = rct::skvGen(MN);\n  rct::key rho = rct::skGen();\n  ve = vector_exponent(sL, sR);\n  rct::key S;\n  rct::addKeys(S, ve, rct::scalarmultBase(rho));\n\n  // PAPER LINES 43-45\n  rct::key y = hash_cache_mash(hash_cache, A, S);\n  rct::key z = hash_cache = rct::hash_to_scalar(y);\n\n  // Polynomial construction by coefficients\n  const auto zMN = vector_dup(z, MN);\n  rct::keyV l0 = vector_subtract(aL, zMN);\n  const rct::keyV &l1 = sL;\n\n  // This computes the ugly sum/concatenation from PAPER LINE 65\n  rct::keyV zero_twos(MN);\n  const rct::keyV zpow = vector_powers(z, M+2);\n  for (size_t i = 0; i < MN; ++i)\n  {\n    zero_twos[i] = rct::zero();\n    for (size_t j = 1; j <= M; ++j)\n    {\n      if (i >= (j-1)*N && i < j*N)\n      {\n        CHECK_AND_ASSERT_THROW_MES(1+j < zpow.size(), \"invalid zpow index\");\n        CHECK_AND_ASSERT_THROW_MES(i-(j-1)*N < twoN.size(), \"invalid twoN index\");\n        sc_muladd(zero_twos[i].bytes, zpow[1+j].bytes, twoN[i-(j-1)*N].bytes, zero_twos[i].bytes);\n      }\n    }\n  }\n\n  rct::keyV r0 = vector_add(aR, zMN);\n  const auto yMN = vector_powers(y, MN);\n  r0 = hadamard(r0, yMN);\n  r0 = vector_add(r0, zero_twos);\n  rct::keyV r1 = hadamard(yMN, sR);\n\n  // Polynomial construction before PAPER LINE 46\n  rct::key t1_1 = inner_product(l0, r1);\n  rct::key t1_2 = inner_product(l1, r0);\n  rct::key t1;\n  sc_add(t1.bytes, t1_1.bytes, t1_2.bytes);\n  rct::key t2 = inner_product(l1, r1);\n\n  PERF_TIMER_STOP(PROVE_step1);\n\n  PERF_TIMER_START_BP(PROVE_step2);\n  // PAPER LINES 47-48\n  rct::key tau1 = rct::skGen(), tau2 = rct::skGen();\n\n  rct::key T1 = rct::addKeys(rct::scalarmultKey(rct::H, t1), rct::scalarmultBase(tau1));\n  rct::key T2 = rct::addKeys(rct::scalarmultKey(rct::H, t2), rct::scalarmultBase(tau2));\n\n  // PAPER LINES 49-51\n  rct::key x = hash_cache_mash(hash_cache, z, T1, T2);\n\n  // PAPER LINES 52-53\n  rct::key taux;\n  sc_mul(taux.bytes, tau1.bytes, x.bytes);\n  rct::key xsq;\n  sc_mul(xsq.bytes, x.bytes, x.bytes);\n  sc_muladd(taux.bytes, tau2.bytes, xsq.bytes, taux.bytes);\n  for (size_t j = 1; j <= sv.size(); ++j)\n  {\n    CHECK_AND_ASSERT_THROW_MES(j+1 < zpow.size(), \"invalid zpow index\");\n    sc_muladd(taux.bytes, zpow[j+1].bytes, gamma[j-1].bytes, taux.bytes);\n  }\n  rct::key mu;\n  sc_muladd(mu.bytes, x.bytes, rho.bytes, alpha.bytes);\n\n  // PAPER LINES 54-57\n  rct::keyV l = l0;\n  l = vector_add(l, vector_scalar(l1, x));\n  rct::keyV r = r0;\n  r = vector_add(r, vector_scalar(r1, x));\n  PERF_TIMER_STOP(PROVE_step2);\n\n  PERF_TIMER_START_BP(PROVE_step3);\n  rct::key t = inner_product(l, r);\n\n  // DEBUG: Test if the l and r vectors match the polynomial forms\n#ifdef DEBUG_BP\n  rct::key test_t;\n  const rct::key t0 = inner_product(l0, r0);\n  sc_muladd(test_t.bytes, t1.bytes, x.bytes, t0.bytes);\n  sc_muladd(test_t.bytes, t2.bytes, xsq.bytes, test_t.bytes);\n  CHECK_AND_ASSERT_THROW_MES(test_t == t, \"test_t check failed\");\n#endif\n\n  // PAPER LINES 32-33\n  rct::key x_ip = hash_cache_mash(hash_cache, x, taux, mu, t);\n\n  // These are used in the inner product rounds\n  size_t nprime = MN;\n  rct::keyV Gprime(MN);\n  rct::keyV Hprime(MN);\n  rct::keyV aprime(MN);\n  rct::keyV bprime(MN);\n  const rct::key yinv = invert(y);\n  rct::key yinvpow = rct::identity();\n  for (size_t i = 0; i < MN; ++i)\n  {\n    Gprime[i] = Gi[i];\n    Hprime[i] = scalarmultKey(Hi[i], yinvpow);\n    sc_mul(yinvpow.bytes, yinvpow.bytes, yinv.bytes);\n    aprime[i] = l[i];\n    bprime[i] = r[i];\n  }\n  rct::keyV L(logMN);\n  rct::keyV R(logMN);\n  int round = 0;\n  rct::keyV w(logMN); // this is the challenge x in the inner product protocol\n  PERF_TIMER_STOP(PROVE_step3);\n\n  PERF_TIMER_START_BP(PROVE_step4);\n  // PAPER LINE 13\n  while (nprime > 1)\n  {\n    // PAPER LINE 15\n    nprime /= 2;\n\n    // PAPER LINES 16-17\n    rct::key cL = inner_product(slice(aprime, 0, nprime), slice(bprime, nprime, bprime.size()));\n    rct::key cR = inner_product(slice(aprime, nprime, aprime.size()), slice(bprime, 0, nprime));\n\n    // PAPER LINES 18-19\n    L[round] = vector_exponent_custom(slice(Gprime, nprime, Gprime.size()), slice(Hprime, 0, nprime), slice(aprime, 0, nprime), slice(bprime, nprime, bprime.size()));\n    sc_mul(tmp.bytes, cL.bytes, x_ip.bytes);\n    rct::addKeys(L[round], L[round], rct::scalarmultKey(rct::H, tmp));\n    R[round] = vector_exponent_custom(slice(Gprime, 0, nprime), slice(Hprime, nprime, Hprime.size()), slice(aprime, nprime, aprime.size()), slice(bprime, 0, nprime));\n    sc_mul(tmp.bytes, cR.bytes, x_ip.bytes);\n    rct::addKeys(R[round], R[round], rct::scalarmultKey(rct::H, tmp));\n\n    // PAPER LINES 21-22\n    w[round] = hash_cache_mash(hash_cache, L[round], R[round]);\n\n    // PAPER LINES 24-25\n    const rct::key winv = invert(w[round]);\n    Gprime = hadamard2(vector_scalar2(slice(Gprime, 0, nprime), winv), vector_scalar2(slice(Gprime, nprime, Gprime.size()), w[round]));\n    Hprime = hadamard2(vector_scalar2(slice(Hprime, 0, nprime), w[round]), vector_scalar2(slice(Hprime, nprime, Hprime.size()), winv));\n\n    // PAPER LINES 28-29\n    aprime = vector_add(vector_scalar(slice(aprime, 0, nprime), w[round]), vector_scalar(slice(aprime, nprime, aprime.size()), winv));\n    bprime = vector_add(vector_scalar(slice(bprime, 0, nprime), winv), vector_scalar(slice(bprime, nprime, bprime.size()), w[round]));\n\n    ++round;\n  }\n  PERF_TIMER_STOP(PROVE_step4);\n\n  // PAPER LINE 58 (with inclusions from PAPER LINE 8 and PAPER LINE 20)\n  return Bulletproof(V, A, S, T1, T2, taux, mu, L, R, aprime[0], bprime[0], t);\n}\n\nBulletproof bulletproof_PROVE_old(const std::vector<uint64_t> &v, const rct::keyV &gamma)\n{\n  CHECK_AND_ASSERT_THROW_MES(v.size() == gamma.size(), \"Incompatible sizes of v and gamma\");\n\n  // vG + gammaH\n  PERF_TIMER_START_BP(PROVE_v);\n  rct::keyV sv(v.size());\n  for (size_t i = 0; i < v.size(); ++i)\n  {\n    sv[i] = rct::zero();\n    sv[i].bytes[0] = v[i] & 255;\n    sv[i].bytes[1] = (v[i] >> 8) & 255;\n    sv[i].bytes[2] = (v[i] >> 16) & 255;\n    sv[i].bytes[3] = (v[i] >> 24) & 255;\n    sv[i].bytes[4] = (v[i] >> 32) & 255;\n    sv[i].bytes[5] = (v[i] >> 40) & 255;\n    sv[i].bytes[6] = (v[i] >> 48) & 255;\n    sv[i].bytes[7] = (v[i] >> 56) & 255;\n  }\n  PERF_TIMER_STOP(PROVE_v);\n  return bulletproof_PROVE_old(sv, gamma);\n}\n\n/* Given a range proof, determine if it is valid */\nbool bulletproof_VERIFY_old(const std::vector<const Bulletproof*> &proofs)\n{\n  init_exponents();\n\n  PERF_TIMER_START_BP(VERIFY);\n\n  // sanity and figure out which proof is longest\n  size_t max_length = 0;\n  for (const Bulletproof *p: proofs)\n  {\n    const Bulletproof &proof = *p;\n    CHECK_AND_ASSERT_MES(proof.V.size() >= 1, false, \"V does not have at least one element\");\n    CHECK_AND_ASSERT_MES(proof.L.size() == proof.R.size(), false, \"Mismatched L and R sizes\");\n    CHECK_AND_ASSERT_MES(proof.L.size() > 0, false, \"Empty proof\");\n\n    max_length = std::max(max_length, proof.L.size());\n  }\n  CHECK_AND_ASSERT_MES(max_length < 32, false, \"At least one proof is too large\");\n  size_t maxMN = 1u << max_length;\n\n  const size_t logN = 6;\n  const size_t N = 1 << logN;\n  rct::key tmp;\n\n  // setup weighted aggregates\n  rct::key Z0 = rct::identity();\n  rct::key z1 = rct::zero();\n  rct::key Z2 = rct::identity();\n  rct::key z3 = rct::zero();\n  rct::keyV z4(maxMN, rct::zero()), z5(maxMN, rct::zero());\n  for (const Bulletproof *p: proofs)\n  {\n    const Bulletproof &proof = *p;\n\n    size_t M, logM;\n    for (logM = 0; (M = 1<<logM) <= maxM && M < proof.V.size(); ++logM);\n    CHECK_AND_ASSERT_MES(proof.L.size() == 6+logM, false, \"Proof is not the expected size\");\n    const size_t MN = M*N;\n    rct::key weight = rct::skGen();\n\n    // Reconstruct the challenges\n    PERF_TIMER_START_BP(VERIFY_start);\n    rct::key hash_cache = rct::hash_to_scalar(proof.V);\n    rct::key y = hash_cache_mash(hash_cache, proof.A, proof.S);\n    rct::key z = hash_cache = rct::hash_to_scalar(y);\n    rct::key x = hash_cache_mash(hash_cache, z, proof.T1, proof.T2);\n    rct::key x_ip = hash_cache_mash(hash_cache, x, proof.taux, proof.mu, proof.t);\n    PERF_TIMER_STOP(VERIFY_start);\n\n    PERF_TIMER_START_BP(VERIFY_line_61);\n    // PAPER LINE 61\n    rct::key L61Left, L61Right;\n    rct::addKeys2(L61Left, proof.taux, proof.t, rct::H);\n\n    const rct::keyV zpow = vector_powers(z, M+3);\n\n    rct::key k;\n    const rct::key ip1y = vector_power_sum(y, MN);\n    sc_mulsub(k.bytes, zpow[2].bytes, ip1y.bytes, rct::zero().bytes);\n    for (size_t j = 1; j <= M; ++j)\n    {\n      CHECK_AND_ASSERT_MES(j+2 < zpow.size(), false, \"invalid zpow index\");\n      sc_mulsub(k.bytes, zpow[j+2].bytes, ip12.bytes, k.bytes);\n    }\n    PERF_TIMER_STOP(VERIFY_line_61);\n\n    // bos coster is slower for small numbers of calcs, straus seems not\n    if (1)\n    {\n      PERF_TIMER_START_BP(VERIFY_line_61rl_new);\n      sc_muladd(tmp.bytes, z.bytes, ip1y.bytes, k.bytes);\n      std::vector<MultiexpData> multiexp_data;\n      multiexp_data.reserve(3+proof.V.size());\n      multiexp_data.emplace_back(tmp, rct::H);\n      for (size_t j = 0; j < proof.V.size(); j++)\n      {\n        multiexp_data.emplace_back(zpow[j+2], proof.V[j]);\n      }\n      multiexp_data.emplace_back(x, proof.T1);\n      rct::key xsq;\n      sc_mul(xsq.bytes, x.bytes, x.bytes);\n      multiexp_data.emplace_back(xsq, proof.T2);\n      L61Right = multiexp(multiexp_data, false);\n      PERF_TIMER_STOP(VERIFY_line_61rl_new);\n    }\n    else\n    {\n      PERF_TIMER_START_BP(VERIFY_line_61rl_old);\n      sc_muladd(tmp.bytes, z.bytes, ip1y.bytes, k.bytes);\n      L61Right = rct::scalarmultKey(rct::H, tmp);\n      ge_p3 L61Right_p3;\n      CHECK_AND_ASSERT_THROW_MES(ge_frombytes_vartime(&L61Right_p3, L61Right.bytes) == 0, \"ge_frombytes_vartime failed\");\n      for (size_t j = 0; j+1 < proof.V.size(); j += 2)\n      {\n        CHECK_AND_ASSERT_MES(j+2+1 < zpow.size(), false, \"invalid zpow index\");\n        ge_dsmp precomp0, precomp1;\n        rct::precomp(precomp0, j < proof.V.size() ? proof.V[j] : rct::identity());\n        rct::precomp(precomp1, j+1 < proof.V.size() ? proof.V[j+1] : rct::identity());\n        rct::addKeys3acc_p3(&L61Right_p3, zpow[j+2], precomp0, zpow[j+2+1], precomp1);\n      }\n      for (size_t j = proof.V.size() & 0xfffffffe; j < M; j++)\n      {\n        CHECK_AND_ASSERT_MES(j+2 < zpow.size(), false, \"invalid zpow index\");\n        // faster equivalent to:\n        // tmp = rct::scalarmultKey(j < proof.V.size() ? proof.V[j] : rct::identity(), zpow[j+2]);\n        // rct::addKeys(L61Right, L61Right, tmp);\n        if (j < proof.V.size())\n          addKeys_acc_p3(&L61Right_p3, zpow[j+2], proof.V[j]);\n      }\n\n      addKeys_acc_p3(&L61Right_p3, x, proof.T1);\n\n      rct::key xsq;\n      sc_mul(xsq.bytes, x.bytes, x.bytes);\n      addKeys_acc_p3(&L61Right_p3, xsq, proof.T2);\n      ge_p3_tobytes(L61Right.bytes, &L61Right_p3);\n      PERF_TIMER_STOP(VERIFY_line_61rl_old);\n    }\n\n    if (!(L61Right == L61Left))\n    {\n      MERROR(\"Verification failure at step 1\");\n      return false;\n    }\n\n    PERF_TIMER_START_BP(VERIFY_line_62);\n    // PAPER LINE 62\n    rct::addKeys(Z0, Z0, rct::scalarmultKey(rct::addKeys(proof.A, rct::scalarmultKey(proof.S, x)), weight));\n    PERF_TIMER_STOP(VERIFY_line_62);\n\n    // Compute the number of rounds for the inner product\n    const size_t rounds = logM+logN;\n    CHECK_AND_ASSERT_MES(rounds > 0, false, \"Zero rounds\");\n\n    PERF_TIMER_START_BP(VERIFY_line_21_22);\n    // PAPER LINES 21-22\n    // The inner product challenges are computed per round\n    rct::keyV w(rounds);\n    for (size_t i = 0; i < rounds; ++i)\n    {\n      w[i] = hash_cache_mash(hash_cache, proof.L[i], proof.R[i]);\n    }\n    PERF_TIMER_STOP(VERIFY_line_21_22);\n\n    PERF_TIMER_START_BP(VERIFY_line_24_25);\n    // Basically PAPER LINES 24-25\n    // Compute the curvepoints from G[i] and H[i]\n    rct::key yinvpow = rct::identity();\n    rct::key ypow = rct::identity();\n\n    PERF_TIMER_START_BP(VERIFY_line_24_25_invert);\n    const rct::key yinv = invert(y);\n    rct::keyV winv(rounds);\n    for (size_t i = 0; i < rounds; ++i)\n      winv[i] = invert(w[i]);\n    PERF_TIMER_STOP(VERIFY_line_24_25_invert);\n\n    for (size_t i = 0; i < MN; ++i)\n    {\n      // Convert the index to binary IN REVERSE and construct the scalar exponent\n      rct::key g_scalar = proof.a;\n      rct::key h_scalar;\n      sc_mul(h_scalar.bytes, proof.b.bytes, yinvpow.bytes);\n\n      for (size_t j = rounds; j-- > 0; )\n      {\n        size_t J = w.size() - j - 1;\n\n        if ((i & (((size_t)1)<<j)) == 0)\n        {\n          sc_mul(g_scalar.bytes, g_scalar.bytes, winv[J].bytes);\n          sc_mul(h_scalar.bytes, h_scalar.bytes, w[J].bytes);\n        }\n        else\n        {\n          sc_mul(g_scalar.bytes, g_scalar.bytes, w[J].bytes);\n          sc_mul(h_scalar.bytes, h_scalar.bytes, winv[J].bytes);\n        }\n      }\n\n      // Adjust the scalars using the exponents from PAPER LINE 62\n      sc_add(g_scalar.bytes, g_scalar.bytes, z.bytes);\n      CHECK_AND_ASSERT_MES(2+i/N < zpow.size(), false, \"invalid zpow index\");\n      CHECK_AND_ASSERT_MES(i%N < twoN.size(), false, \"invalid twoN index\");\n      sc_mul(tmp.bytes, zpow[2+i/N].bytes, twoN[i%N].bytes);\n      sc_muladd(tmp.bytes, z.bytes, ypow.bytes, tmp.bytes);\n      sc_mulsub(h_scalar.bytes, tmp.bytes, yinvpow.bytes, h_scalar.bytes);\n\n      sc_muladd(z4[i].bytes, g_scalar.bytes, weight.bytes, z4[i].bytes);\n      sc_muladd(z5[i].bytes, h_scalar.bytes, weight.bytes, z5[i].bytes);\n\n      if (i != MN-1)\n      {\n        sc_mul(yinvpow.bytes, yinvpow.bytes, yinv.bytes);\n        sc_mul(ypow.bytes, ypow.bytes, y.bytes);\n      }\n    }\n\n    PERF_TIMER_STOP(VERIFY_line_24_25);\n\n    // PAPER LINE 26\n    PERF_TIMER_START_BP(VERIFY_line_26_new);\n    std::vector<MultiexpData> multiexp_data;\n    multiexp_data.reserve(2*rounds);\n\n    sc_muladd(z1.bytes, proof.mu.bytes, weight.bytes, z1.bytes);\n    for (size_t i = 0; i < rounds; ++i)\n    {\n      sc_mul(tmp.bytes, w[i].bytes, w[i].bytes);\n      multiexp_data.emplace_back(tmp, proof.L[i]);\n      sc_mul(tmp.bytes, winv[i].bytes, winv[i].bytes);\n      multiexp_data.emplace_back(tmp, proof.R[i]);\n    }\n    rct::key acc = multiexp(multiexp_data, false);\n    rct::addKeys(Z2, Z2, rct::scalarmultKey(acc, weight));\n    sc_mulsub(tmp.bytes, proof.a.bytes, proof.b.bytes, proof.t.bytes);\n    sc_mul(tmp.bytes, tmp.bytes, x_ip.bytes);\n    sc_muladd(z3.bytes, tmp.bytes, weight.bytes, z3.bytes);\n    PERF_TIMER_STOP(VERIFY_line_26_new);\n  }\n\n  // now check all proofs at once\n  PERF_TIMER_START_BP(VERIFY_step2_check);\n  rct::key Y = Z0;\n  sc_sub(tmp.bytes, rct::zero().bytes, z1.bytes);\n  rct::addKeys(Y, Y, rct::scalarmultBase(tmp));\n  rct::addKeys(Y, Y, Z2);\n  rct::addKeys(Y, Y, rct::scalarmultKey(rct::H, z3));\n\n  std::vector<MultiexpData> multiexp_data;\n  multiexp_data.reserve(2 * maxMN);\n  for (size_t i = 0; i < maxMN; ++i)\n  {\n    sc_sub(tmp.bytes, rct::zero().bytes, z4[i].bytes);\n    multiexp_data.emplace_back(tmp, Gi_p3[i]);\n    sc_sub(tmp.bytes, rct::zero().bytes, z5[i].bytes);\n    multiexp_data.emplace_back(tmp, Hi_p3[i]);\n  }\n  rct::addKeys(Y, Y, multiexp(multiexp_data, true));\n  PERF_TIMER_STOP(VERIFY_step2_check);\n\n  if (!(Y == rct::identity()))\n  {\n    MERROR(\"Verification failure at step 2\");\n    return false;\n  }\n\n  PERF_TIMER_STOP(VERIFY);\n  return true;\n}\n\nbool bulletproof_VERIFY_old(const std::vector<Bulletproof> &proofs)\n{\n  std::vector<const Bulletproof*> proof_pointers;\n  for (const Bulletproof &proof: proofs)\n    proof_pointers.push_back(&proof);\n  return bulletproof_VERIFY_old(proof_pointers);\n}\n\nbool bulletproof_VERIFY_old(const Bulletproof &proof)\n{\n  std::vector<const Bulletproof*> proofs;\n  proofs.push_back(&proof);\n  return bulletproof_VERIFY_old(proofs);\n}\n\n}\n", "meta": {"hexsha": "29d0753e083a19695da11b01dd71074a25ded66d", "size": 38805, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/ringct/bp_legacy.cc", "max_stars_repo_name": "88plug/babycoin", "max_stars_repo_head_hexsha": "7d6de522e82285128ab8ef596489287b395d1bb1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-07-22T07:08:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T21:51:54.000Z", "max_issues_repo_path": "src/ringct/bp_legacy.cc", "max_issues_repo_name": "88plug/babycoin", "max_issues_repo_head_hexsha": "7d6de522e82285128ab8ef596489287b395d1bb1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-11-03T09:09:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-30T21:31:34.000Z", "max_forks_repo_path": "src/ringct/bp_legacy.cc", "max_forks_repo_name": "88plug/babycoin", "max_forks_repo_head_hexsha": "7d6de522e82285128ab8ef596489287b395d1bb1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-03-12T08:24:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T10:29:56.000Z", "avg_line_length": 33.3662940671, "max_line_length": 226, "alphanum_fraction": 0.6544002062, "num_tokens": 13047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.3593641451601019, "lm_q1q2_score": 0.2547960549148359}}
{"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#ifndef THERMAL_PHYSICS_HH\n#define THERMAL_PHYSICS_HH\n\n#include <Geometry.hh>\n#include <HeatSource.hh>\n#include <ImplicitOperator.hh>\n#include <Physics.hh>\n#include <ThermalOperatorBase.hh>\n\n#include <deal.II/base/time_stepping.h>\n#include <deal.II/base/time_stepping.templates.h>\n#include <deal.II/hp/fe_collection.h>\n\n#include <boost/property_tree/ptree.hpp>\n\nnamespace adamantine\n{\n/**\n * This class takes care of building the linear operator and the\n * right-hand-side. Also used to evolve the system in time.\n */\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\nclass ThermalPhysics : public Physics<dim, MemorySpaceType>\n{\npublic:\n  /**\n   * Constructor.\n   * \\param[in] database requires the following entries:\n   *   - <B>materials</B>: property tree\n   *   - <B>sources</B>: property tree\n   *   - <B>sources.n_beams</B>: unsigned int in \\f$[0,\\infty)\\f$\n   *   - <B>sources.beam_X</B>: property tree with X the number associated to\n   *   the heat source\n   *   - <B>time_stepping</B>: property tree\n   *   - <B>time_stepping.method</B>: string\n   *   - <B>time_stepping.coarsening_parameter</B>: double in \\f$[0,\\infty)\\f$\n   *   [optional, default value of 1.2]\n   *   - <B>time_stepping.refining_parameter</B>: double in \\f$(0,1)\\f$\n   *   [optional, default value of 0.8]\n   *   - <B>time_stepping.min_time_step</B>: double in \\f$[0,\\infty)\\f$\n   *   [optional, default value of 1e-14]\n   *   - <B>time_stepping.max_time_step</B>: double in \\f$(0,\\infty)\\f$\n   *   [optional, default value of 1e100]\n   *   - <B>time_stepping.refining_tolerance</B>: double in \\f$(0,\\infty)\\f$\n   *   [optional, default value of 1e-8]\n   *   - <B>time_stepping.coarsening_tolerance</B>: double in \\f$(0, \\infty)\\f$\n   *   [optional, default value of 1e-12]\n   *   - <B>time_stepping.max_iteration</B>: unsigned int \\f$[0,\\infty)\\f$\n   *   [optional, default value of 1000]\n   *   - <B>time_stepping.right_preconditioning</B>: boolean [optional, default\n   *   value is false]\n   *   - <B>time_stepping.n_tmp_vectors</B>: unsigned int in \\f$[0,\\infty)\\f$\n   *   [optional, default of 30]\n   *   - <B>time_stepping.newton_max_iteration</B>: unsigned int in\n   *   \\f$[0,\\infty)\\f$ [optional, default valie of 100]\n   *   - <B>time_stepping.newton_tolerance</B>: double in \\f$(0,\\infty)\\f$\n   *   [optional, default of 1e-6]\n   *   - <B>time_stepping.jfnk</B>: boolean [optional, default value of false]\n   */\n  ThermalPhysics(MPI_Comm const &communicator,\n                 boost::property_tree::ptree const &database,\n                 Geometry<dim> &geometry);\n\n  void setup_dofs() override;\n\n  void compute_inverse_mass_matrix() override;\n\n  void add_material(\n      std::vector<typename dealii::DoFHandler<dim>::active_cell_iterator> const\n          &elements_to_activate,\n      double initial_temperature,\n      dealii::LA::distributed::Vector<double, MemorySpaceType> &solution)\n      override;\n\n  double evolve_one_time_step(\n      double t, double delta_t,\n      dealii::LA::distributed::Vector<double, MemorySpaceType> &solution,\n      std::vector<Timer> &timers) override;\n\n  double get_delta_t_guess() const override;\n\n  void initialize_dof_vector(\n      dealii::LA::distributed::Vector<double, MemorySpaceType> &vector)\n      const override;\n\n  /**\n   * Initialize the given vector. The value is assumed to be a temperature.\n   */\n  void\n  initialize_dof_vector(double const value,\n                        dealii::LA::distributed::Vector<double, MemorySpaceType>\n                            &vector) const override;\n\n  void get_state_from_material_properties() override;\n\n  void set_state_to_material_properties() override;\n\n  dealii::DoFHandler<dim> &get_dof_handler() override;\n\n  dealii::AffineConstraints<double> &get_affine_constraints() override;\n\n  std::shared_ptr<MaterialProperty<dim>> get_material_property() override;\n\n  /**\n   * Return the heat sources.\n   */\n  std::vector<std::shared_ptr<HeatSource<dim>>> &get_heat_sources();\n\n  /**\n   * Return the current height of the heat source.\n   */\n  double get_current_source_height() const;\n\nprivate:\n  using LA_Vector =\n      typename dealii::LA::distributed::Vector<double, MemorySpaceType>;\n\n  /**\n   * Compute the right-hand side and apply the TermalOperator.\n   */\n  LA_Vector evaluate_thermal_physics(double const t, LA_Vector const &y,\n                                     std::vector<Timer> &timers) const;\n\n  /**\n   * Compute the inverse of the ImplicitOperator.\n   */\n  LA_Vector id_minus_tau_J_inverse(double const t, double const tau,\n                                   LA_Vector const &y,\n                                   std::vector<Timer> &timers) const;\n\n  /**\n   * This flag is true if the time stepping method is embedded.\n   */\n  bool _embedded_method = false;\n  /**\n   * This flag is true if the time stepping method is implicit.\n   */\n  bool _implicit_method = false;\n  /**\n   * This flag is true if right preconditioning is used to invert the\n   * ImplicitOperator.\n   */\n  bool _right_preconditioning;\n  /**\n   * Maximum number of iterations to invert the ImplicitOperator.\n   */\n  unsigned int _max_iter;\n  /**\n   * Maximum number of temporary vectors when inverting the ImplicitOperator.\n   */\n  unsigned int _max_n_tmp_vectors;\n  /**\n   * Guess of the next time step.\n   */\n  double _delta_t_guess;\n  /**\n   * Tolerance to inverte the ImplicitOperator.\n   */\n  double _tolerance;\n  /**\n   * Current height of the object.\n   */\n  double _current_source_height = 0.;\n  /**\n   * Type of boundary.\n   */\n  BoundaryType _boundary_type;\n  /**\n   * Associated geometry.\n   */\n  Geometry<dim> &_geometry;\n  /**\n   * Associated Lagrange finite elements.\n   */\n  dealii::hp::FECollection<dim> _fe_collection;\n  /**\n   * Associated DoFHandler.\n   */\n  dealii::DoFHandler<dim> _dof_handler;\n  /**\n   * Associated AffineConstraints<double>.\n   */\n  dealii::AffineConstraints<double> _affine_constraints;\n  /**\n   * Associated quadature, either Gauss or Gauss-Lobatto.\n   */\n  dealii::hp::QCollection<1> _q_collection;\n  /**\n   * Shared pointer to the material properties associated to the domain.\n   */\n  std::shared_ptr<MaterialProperty<dim>> _material_properties;\n  /**\n   * Vector of heat sources.\n   */\n  std::vector<std::shared_ptr<HeatSource<dim>>> _heat_sources;\n  /**\n   * Shared pointer to the underlying ThermalOperator.\n   */\n  std::shared_ptr<ThermalOperatorBase<dim, MemorySpaceType>> _thermal_operator;\n  /**\n   * Unique pointer to the underlying ImplicitOperator.\n   */\n  std::unique_ptr<ImplicitOperator<MemorySpaceType>> _implicit_operator;\n  /**\n   * Shared pointer to the underlying time stepping scheme.\n   */\n  std::unique_ptr<dealii::TimeStepping::RungeKutta<LA_Vector>> _time_stepping;\n};\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\ninline double ThermalPhysics<dim, fe_degree, MemorySpaceType,\n                             QuadratureType>::get_delta_t_guess() const\n{\n  return _delta_t_guess;\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\ninline dealii::DoFHandler<dim> &\nThermalPhysics<dim, fe_degree, MemorySpaceType,\n               QuadratureType>::get_dof_handler()\n{\n  return _dof_handler;\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\ninline dealii::AffineConstraints<double> &\nThermalPhysics<dim, fe_degree, MemorySpaceType,\n               QuadratureType>::get_affine_constraints()\n{\n  return _affine_constraints;\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\ninline std::shared_ptr<MaterialProperty<dim>>\nThermalPhysics<dim, fe_degree, MemorySpaceType,\n               QuadratureType>::get_material_property()\n{\n  return _material_properties;\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\ninline std::vector<std::shared_ptr<HeatSource<dim>>> &\nThermalPhysics<dim, fe_degree, MemorySpaceType,\n               QuadratureType>::get_heat_sources()\n{\n  return _heat_sources;\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\ninline double ThermalPhysics<dim, fe_degree, MemorySpaceType,\n                             QuadratureType>::get_current_source_height() const\n{\n  return _current_source_height;\n}\n} // namespace adamantine\n\n#endif\n", "meta": {"hexsha": "ce30833c715d05cb3d5d1fc7922ab0f8b763d3b2", "size": 8672, "ext": "hh", "lang": "C++", "max_stars_repo_path": "source/ThermalPhysics.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/ThermalPhysics.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/ThermalPhysics.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": 31.8823529412, "max_line_length": 80, "alphanum_fraction": 0.6856549815, "num_tokens": 2200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2546923271429772}}
{"text": "// Compile with cmake (CMakeLists.txt is provided) or with the following lines in bash:\n// g++ -c -fPIC libautosim.cpp -o libautosim.o\n// g++ -shared -Wl,-soname,libautosim.so -o libautosim.so libautosim.o\n\n\n#include <string>\n#include <sstream>\n#include <iostream>\n#include <list>\n#include <vector>\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n#include <algorithm>\n#include <float.h>\n#include <limits>\n#include <cmath>\n#include <limits>\n\n\n#include <bitset>\n#include <boost/math/distributions/binomial.hpp>\n#include \"cpp_libs/libOrsa/orsa_fundamental.hpp\"\n#include \"cpp_libs/libOrsa/orsa_homography.hpp\"\n\n#define FullDescDim 6272\n#define VecDescDim 128 // as in (x,x,128) output of the network\n#define SameKPThres 4\n\n\nstruct TargetNode\n{\n  const int TargetIdx; float sim_with_query;\n  TargetNode(int Idx, float sim):TargetIdx(Idx){ this->sim_with_query = sim; };\n  bool operator >(const TargetNode & kp) {return ( this->sim_with_query>kp.sim_with_query );};\n  bool operator ==(const TargetNode & kp) {return ( this->sim_with_query==kp.sim_with_query );};\n};\n\nstruct QueryNode\n{\n  const int QueryIdx;\n  std::list<QueryNode>::iterator thisQueryNodeOnList; //pointer on list\n  float first_sim, last_sim;\n  std::list<TargetNode> MostSimilar_TargetNodes;\n\n  void Add_TargetNode(int it, float sim, int MaxTnodes_num)\n  {\n    TargetNode tn(it,sim);\n    std::list<TargetNode>::iterator target_iter;\n    for(target_iter = MostSimilar_TargetNodes.begin(); target_iter != MostSimilar_TargetNodes.end(); ++target_iter)\n      if ( tn > *target_iter )\n        break;\n\n    MostSimilar_TargetNodes.insert( target_iter, tn );\n    if (MaxTnodes_num>0 && MostSimilar_TargetNodes.size()>MaxTnodes_num)\n      MostSimilar_TargetNodes.pop_back();\n      last_sim = (--MostSimilar_TargetNodes.end())->sim_with_query;\n    first_sim = MostSimilar_TargetNodes.begin()->sim_with_query;  \n  };\n\n  QueryNode(int Idx):QueryIdx(Idx){ first_sim = -1; last_sim = -1; };\n};\n\nstruct DescStatsClass\n{\n  float norm, max, min, mean, sigma;\n  std::bitset<FullDescDim> AID;\n  std::bitset<VecDescDim> AIDbyVec [FullDescDim/VecDescDim];\n\n  DescStatsClass()\n  {\n    norm = 0.0f, mean = 0.0f, sigma = 0.0f;\n    max = -std::numeric_limits<float>::infinity();\n    min = std::numeric_limits<float>::infinity();\n  };\n};\n\n\nint CountItFast(const DescStatsClass & q, const DescStatsClass & t, int thres)\n{\n  int xor_opp = 0;\n  for (int v = 0; (v < FullDescDim/VecDescDim && (xor_opp < thres)); v++)\n    xor_opp +=  (q.AIDbyVec[v] ^ t.AIDbyVec[v]).count();\n  return(xor_opp);\n}\n\n\nfloat FastSimi(int iq, float* DescsQuery, DescStatsClass* QueryStats, int it, float* DescsTarget, DescStatsClass* TargetStats, float simi_thres)\n{\n  float m_sq = QueryStats[iq].max * TargetStats[it].max;\n  float norms_prod = QueryStats[iq].norm * TargetStats[it].norm;\n  float dynamic_thres = (simi_thres * norms_prod) - FullDescDim * m_sq;\n  float SP = 0.0;\n  int qpos = iq*FullDescDim, tpos = it*FullDescDim;\n  for (int i = 0; (i < FullDescDim); i++)\n  {\n    SP +=  DescsQuery[qpos + i] * DescsTarget[tpos + i];\n  }\n  return(SP/norms_prod);\n};\n\nDescStatsClass LoadInfo(int iq, float* DescsQuery)\n{\n  DescStatsClass ds;\n  float val;\n  int qpos = iq*FullDescDim;\n  for (int i = 0; (i < FullDescDim); i++)\n  {\n    val = DescsQuery[qpos + i];\n    ds.norm += val * val;\n  }\n  \n  for (int i = 0; (i < FullDescDim); i++)\n    if (DescsQuery[qpos + i]>=0)\n    {\n      ds.AID.set(i);\n    }\n\n  for (int v = 0; (v < FullDescDim/VecDescDim); v++)\n  {\n    int vpos = VecDescDim*v;\n    for (int i = 0; (i < VecDescDim); i++)\n      {\n        if (DescsQuery[qpos + vpos + i]>=0)\n          ds.AIDbyVec[v].set(i);\n      }\n  }\n\n  ds.norm = std::sqrt(ds.norm);\n  return(ds);\n};\n\n// this gives P(X>=k) when X is a binomial distribution of parameters N and p\nfloat* BinomialSurvivals(int N, float p)\n{\n  float * survivals = new float[N+1];\n  // binomial distribution object:\n  boost::math::binomial bino(N,p);\n  // survival values\n  for (int x=0; x<=N; x++)\n    survivals[x] = cdf(complement(bino, x));\n  return(survivals);\n}\n\n\nstruct KeypointClass{\n  float x,y;\n};\n\n\nstruct MatchersClass\n{\n  std::list<QueryNode> QueryNodes;\n  const int k; // k as in knn, if <=0 then we store all matches having a sim above sim_thres\n  const float sim_thres;\n  const int Nvec;\n  std::vector<KeypointClass> QueryKPs, TargetKPs;\n  \n  int* FilteredIdxMatches;\n  int N_FilteredMatches;\n\n\n  int BinDesc_GetAlarmThreshold(int Nt)\n  {\n    float *survivals = BinomialSurvivals(VecDescDim, 0.5);\n    int alarmThres = 0.0;\n    for (int i = 0; i <= VecDescDim; i++)\n      if (Nt * survivals[i] <= 1)\n      {\n        alarmThres = (int)(i * Nvec);\n        break;\n      }\n    return (alarmThres);\n  }\n\n  MatchersClass(int knn_num, float sim_thres) : k(knn_num), sim_thres(sim_thres), Nvec((int)(FullDescDim / VecDescDim)){};\n\n  void KnnMatcher(float *DescsQuery, int Nquery, float *DescsTarget, int Ntarget, int FastCode)\n  {\n    DescStatsClass *QueryStats = new DescStatsClass[Nquery], *TargetStats = new DescStatsClass[Ntarget];\n#pragma omp parallel for default(shared)\n    for (int iq = 0; iq < Nquery; iq++)\n      QueryStats[iq] = LoadInfo(iq, DescsQuery);\n#pragma omp parallel for default(shared)\n    for (int it = 0; it < Ntarget; it++)\n      TargetStats[it] = LoadInfo(it, DescsTarget);\n\n    switch (FastCode)\n    {\n      case 0:\n      { // BigAID\n        // std::cout<<\"---> Brute Force Angle Comparisons\"<<std::endl;\n  #pragma omp parallel for default(shared)\n        for (int iq = 0; iq < Nquery; iq++)\n        {\n          QueryNode qn(iq);\n          for (int it = 0; it < Ntarget; it++)\n          {\n            float updated_sim_thres = (this->k > 0 && qn.last_sim > sim_thres) ? qn.last_sim : sim_thres;\n            float simi = FastSimi(iq, DescsQuery, QueryStats, it, DescsTarget, TargetStats, updated_sim_thres);\n            if (simi > updated_sim_thres)\n              qn.Add_TargetNode(it, simi, this->k);\n          }\n          if (qn.first_sim > sim_thres)\n  #pragma omp critical\n          {\n            QueryNodes.push_back(qn);\n            std::list<QueryNode>::iterator itqn = --QueryNodes.end();\n            itqn->thisQueryNodeOnList = itqn;\n          }\n        }\n        break;\n      } // end of BigAID\n      case 1:\n      { // model new AID\n        // std::cout << \"---> Full sign comparisons with bitset!!!\" << std::endl;\n  #pragma omp parallel for default(shared)\n        for (int iq = 0; iq < Nquery; iq++)\n        {\n          QueryNode qn(iq);\n          float updated_sim_thres;\n          for (int it = 0; it < Ntarget; it++)\n          {\n            // This is like counting bits after an XNOR opperation on both binary descriptors\n            updated_sim_thres = (this->k > 0 && qn.last_sim > sim_thres) ? qn.last_sim : sim_thres;\n            float simi = (float) ( FullDescDim - CountItFast(QueryStats[iq], TargetStats[it], FullDescDim - updated_sim_thres) );\n            if (simi > updated_sim_thres)\n              qn.Add_TargetNode(it, simi, this->k);\n          }\n          if (qn.first_sim > sim_thres)\n          {\n  #pragma omp critical\n            {\n              QueryNodes.push_back(qn);\n              std::list<QueryNode>::iterator itqn = --QueryNodes.end();\n              itqn->thisQueryNodeOnList = itqn;\n            }\n          }\n        }\n        break;\n      } // end of AID\n      case 2:\n      { // model AID\n        // std::cout << \"---> Full sign comparisons with bitset!!!\" << std::endl;\n  #pragma omp parallel for default(shared)\n        for (int iq = 0; iq < Nquery; iq++)\n        {\n          QueryNode qn(iq);\n          for (int it = 0; it < Ntarget; it++)\n          {\n            // This is like counting bits after an XNOR opperation on both binary descriptors\n            int concor = FullDescDim - (QueryStats[iq].AID ^ TargetStats[it].AID).count();\n            float updated_sim_thres = (this->k > 0 && qn.last_sim > sim_thres) ? qn.last_sim : sim_thres;\n            float simi = (float)concor;\n            if (simi > updated_sim_thres)\n              qn.Add_TargetNode(it, simi, this->k);\n          }\n          if (qn.first_sim > sim_thres)\n          {\n  #pragma omp critical\n            {\n              QueryNodes.push_back(qn);\n              std::list<QueryNode>::iterator itqn = --QueryNodes.end();\n              itqn->thisQueryNodeOnList = itqn;\n            }\n          }\n        }\n        break;\n      } // end of AID\n    } // end of the switch\n  }\n\nprivate:\n  MatchersClass() : k(0), sim_thres(0.0), Nvec(0){};\n};\n\nfloat max_euclidean_dist(const Match & m1, const Match & m2)\n{\n  float left_dist = std::sqrt( std::pow(m1.x1-m2.x1,2.0) + std::pow(m1.y1-m2.y1,2.0) );\n  float right_dist = std::sqrt( std::pow(m1.x2-m2.x2,2.0) + std::pow(m1.y2-m2.y2,2.0) );\n  if (left_dist>right_dist)\n    return left_dist;\n  else\n    return right_dist;\n}\n\nstd::vector<Match> UniqueFilter(const std::vector<Match>& matches)\n{\n  std::vector<Match> uniqueM;\n  bool *duplicatedM = new bool[matches.size()];\n  float best_sim;\n  int bestidx;\n  for (int i =0; i<matches.size(); i++)\n    duplicatedM[i] = false;\n  for (int i =0; i<matches.size(); i++)\n  {\n    if (duplicatedM[i])\n      continue;\n    best_sim = matches[i].similarity;\n    bestidx = i;\n    for(int j=i+1; j<matches.size();j++)\n    {\n      // std::cout<< max_euclidean_dist(matches[i],matches[j])<<std::endl;\n      if ( !duplicatedM[j] && max_euclidean_dist(matches[i],matches[j])<SameKPThres )\n      {\n        duplicatedM[j] = true;\n        if (best_sim<matches[j].similarity)\n        {\n          bestidx = j;\n          best_sim = matches[j].similarity;\n        }\n      }\n    }\n    uniqueM.push_back(matches[bestidx]);\n  }\n  return uniqueM;\n}\n\nvoid ORSA_Filter(std::vector<Match>& matches, bool* MatchMask, float* T, int w1,int h1,int w2,int h2, bool Fundamental, const double & precision, bool verb)\n{\n  libNumerics::matrix<double> H(3,3);\n  std::vector<int> vec_inliers;\n  double nfa;\n  const float nfa_max = -2;\n  const int ITER_ORSA=10000;\n  if (Fundamental)\n    orsa::orsa_fundamental(matches, w1,h1,w2,h2, precision, ITER_ORSA,H, vec_inliers,nfa,verb);\n  else\n     orsa::ORSA_homography(matches, w1,h1,w2,h2, precision, ITER_ORSA,H, vec_inliers,nfa,verb);\n\n  for (int cc = 0; cc < matches.size(); cc++ )\n    MatchMask[cc] = false;\n\n  if ( nfa < nfa_max )\n  {\n    for (int vi = 0; vi < vec_inliers.size(); vi++ )\n      MatchMask[vec_inliers[vi]] = true;\n    H /= H(2,2);\n\n    int t = 0;\n    for(int i = 0; i < H.nrow(); ++i)\n        for (int j = 0; j < H.ncol(); ++j)\n            T[t++] = H(i,j);\n    if (verb)\n    {\n        printf(\"The two images match! %d matchings are identified. log(nfa)=%.2f.\\n\", (int) vec_inliers.size(), nfa);\n        if (Fundamental)\n          std::cout << \"*************** Fundamental **************\"<< std::endl;\n        else\n          std::cout << \"*************** Homography ***************\"<< std::endl;\n        std::cout << H <<std::endl;\n        std::cout << \"******************************************\"<< std::endl;\n    }\n  }\n  else\n  {\n    if (verb)\n        printf(\"The two images do not match. The matching is not significant:  log(nfa)=%.2f.\\n\", nfa);\n  }\n}\n\n\n// Define C functions for the C++ class - as ctypes can only talk to C...\nextern \"C\"\n{\n\n\n  int NumberOfFilteredMatches(MatchersClass* M)\n  {\n    return M->N_FilteredMatches;\n  }\n\n  void ArrayOfFilteredMatches(MatchersClass* M, int* arr)\n  {\n    for (int i=0; i<3*M->N_FilteredMatches;i++)\n      arr[i] = M->FilteredIdxMatches[i];\n  }\n\n  void GeometricFilterFromNodes(MatchersClass* M, float* T, int w1,int h1,int w2,int h2, int type, float precision, bool verb)\n  {\n    std::vector<Match> matches;    \n    for(std::list<QueryNode>::const_iterator iq = M->QueryNodes.begin(); iq != M->QueryNodes.end(); ++iq) \n      for(std::list<TargetNode>::const_iterator it = iq->MostSimilar_TargetNodes.begin(); it != iq->MostSimilar_TargetNodes.end(); ++it) \n    {\n      Match match1;      \n      match1.x1 = M->QueryKPs[iq->QueryIdx].x;\n      match1.y1 = M->QueryKPs[iq->QueryIdx].y;\n      match1.x2 = M->TargetKPs[it->TargetIdx].x;\n      match1.y2 = M->TargetKPs[it->TargetIdx].y;\n      match1.similarity = it->sim_with_query;\n      match1.Qidx = iq->QueryIdx;\n      match1.Tidx = it->TargetIdx;\n      matches.push_back(match1);\n    }\n    \n    matches = UniqueFilter(matches);\n    bool* MatchMask = new bool[matches.size()];\n    switch (type)\n    {\n      case 0: //Homography\n      {\n        ORSA_Filter(matches, MatchMask, T, w1, h1, w2, h2, false, (double)precision, verb);\n        break;\n      }\n      case 1: // Fundamental\n      {\n        ORSA_Filter(matches, MatchMask, T, w1, h1, w2, h2, true, (double)precision, verb);\n        break;\n      }\n    }\n\n    M->N_FilteredMatches = 0;\n    for (int cc = 0; cc < matches.size(); cc++ )\n      if (MatchMask[cc])\n        M->N_FilteredMatches++;\n    M->FilteredIdxMatches = new int[3*M->N_FilteredMatches];\n    int fcc = 0;\n    for (int cc = 0; cc < matches.size(); cc++ )\n      if (MatchMask[cc])\n        {\n          M->FilteredIdxMatches[3*fcc] = matches[cc].Qidx;\n          M->FilteredIdxMatches[3*fcc+1] = matches[cc].Tidx;\n          M->FilteredIdxMatches[3*fcc+2] = matches[cc].similarity;\n          fcc++;\n        }\n  }\n\n  void GeometricFilter(float* scr_pts, float* dts_pts, bool* MatchMask, float* T, int N, int w1,int h1,int w2,int h2, int type, float precision, bool verb)\n  {\n    std::vector<Match> matches;\n    for (int cc = 0; cc < N; cc++ )\n    {\n        Match match1;\n        match1.x1 = scr_pts[cc*2];\n        match1.y1 = scr_pts[cc*2+1];\n        match1.x2 = dts_pts[cc*2];\n        match1.y2 = dts_pts[cc*2+1];\n\n        matches.push_back(match1);\n    }\n\n    switch (type)\n    {\n      case 0: //Homography\n      {\n        ORSA_Filter(matches, MatchMask, T, w1, h1, w2, h2, false, (double)precision, verb);\n        break;\n      }\n      case 1: // Fundamental\n      {\n        ORSA_Filter(matches, MatchMask, T, w1, h1, w2, h2, true, (double)precision, verb);\n        break;\n      }\n    }\n  }\n\n  MatchersClass* newMatcher(int k, int full_desc_dim, float sim_thres)\n  {\n    if (full_desc_dim!=FullDescDim)\n      std::cout<<\"Desc dims don't match (\"<<full_desc_dim<<\"!=\"<<FullDescDim<<\")\"<<std::endl;\n    return ( new MatchersClass(k, (float) sim_thres) );\n  }\n\n  void KnnMatcher(MatchersClass* M, float* Query_pts, float* DescsQuery, int Nquery, float* Target_pts, float* DescsTarget, int Ntarget, int FastCode)\n  {\n    M->QueryNodes.clear();\n    M->QueryKPs.clear();\n    M->TargetKPs.clear();\n    KeypointClass kp;\n    for (int cc = 0; cc < Nquery; cc++ ){ \n      kp.x = Query_pts[cc*2]; kp.y = Query_pts[cc*2+1];\n      M->QueryKPs.push_back( kp );\n    }\n    for (int cc = 0; cc < Ntarget; cc++ ){ \n      kp.x = Target_pts[cc*2]; kp.y = Target_pts[cc*2+1];\n      M->TargetKPs.push_back( kp );\n    }\n    \n    M->KnnMatcher(DescsQuery, Nquery, DescsTarget, Ntarget, FastCode);\n  }\n\n  int GetQueryNodeLength(QueryNode* qn)\n  {\n    return(qn->MostSimilar_TargetNodes.size());\n  }\n\n  QueryNode* LastQueryNode(MatchersClass* M)\n  {\n    if (M->QueryNodes.begin()!=M->QueryNodes.end())\n      return(&*(--M->QueryNodes.end()));\n    else\n      return(0);\n  }\n\n  QueryNode* FirstQueryNode(MatchersClass* M)\n  {\n    if (M->QueryNodes.begin()!=M->QueryNodes.end())\n      return(&*M->QueryNodes.begin());\n    else\n      return(0);\n  }\n\n  QueryNode* NextQueryNode(MatchersClass* M, QueryNode* qn)\n  {\n    if (qn!=0 && ++qn->thisQueryNodeOnList!=M->QueryNodes.end())\n      return(&*(++qn->thisQueryNodeOnList));\n    else\n      return(0);\n  }\n\n  QueryNode* PrevQueryNode(MatchersClass* M, QueryNode* qn)\n  {\n    if (qn!=0 && qn->thisQueryNodeOnList!=M->QueryNodes.begin())\n      return(&*(--qn->thisQueryNodeOnList));\n    else\n      return(0);\n  }\n\n  void GetData_from_QueryNode(QueryNode* qn, int* QueryIdx, int *TargetIdxes, float* simis)\n  {\n    QueryIdx[0] = qn->QueryIdx;\n    int i = 0;\n    for(std::list<TargetNode>::const_iterator it = qn->MostSimilar_TargetNodes.begin(); it != qn->MostSimilar_TargetNodes.end(); ++it)\n    {\n      TargetIdxes[i] = it->TargetIdx;\n      simis[i] = it->sim_with_query;\n      i++;\n    }\n  }\n\n\n\n\n  void FastMatCombi(int N, float* bP, int* i1_list, int *i2_list, float *patches1, float *patches2, int MemStepImg, int* last_i1_list, int *last_i2_list)\n  {\n    int MemStepBlock = 2*MemStepImg;\n    #pragma omp parallel for firstprivate(MemStepImg, MemStepBlock, N)\n    for (int k = 0; k<N; k++)\n    {\n      int i1 = i1_list[k];\n      int i2 = i2_list[k];\n\n      if (last_i1_list[k]!=i1)\n        for (int i = 0; i<MemStepImg;i++)\n          bP[k*MemStepBlock + 2*i] = patches1[i1*MemStepImg + i];\n\n      if (last_i2_list[k]!=i2)\n        for (int i = 0; i<MemStepImg;i++)\n          bP[k*MemStepBlock + 2*i+1] = patches2[i2*MemStepImg + i];\n    }\n  }\n}\n", "meta": {"hexsha": "80e60dbdd871b908110d3c166b81e74a871be6f7", "size": 16721, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libDA.cpp", "max_stars_repo_name": "rdguez-mariano/sift-aid", "max_stars_repo_head_hexsha": "18952630a19b38a5f0efa1b43453b7b05f0f6a77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-02-19T14:57:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T16:50:58.000Z", "max_issues_repo_path": "libDA.cpp", "max_issues_repo_name": "rdguez-mariano/sift-aid", "max_issues_repo_head_hexsha": "18952630a19b38a5f0efa1b43453b7b05f0f6a77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-01-17T18:09:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T23:29:30.000Z", "max_forks_repo_path": "libDA.cpp", "max_forks_repo_name": "rdguez-mariano/sift-aid", "max_forks_repo_head_hexsha": "18952630a19b38a5f0efa1b43453b7b05f0f6a77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-02-23T14:12:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-11T11:48:42.000Z", "avg_line_length": 30.1823104693, "max_line_length": 156, "alphanum_fraction": 0.601758268, "num_tokens": 5115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421276, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2545038973004133}}
{"text": "//\n//   Copyright 2019 University of Sheffield\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 \"elasticregistration.hpp\"\n\n#include <boost/format.hpp>\n\n#include \"basewriter.hpp\"\n#include \"exceptions.hpp\"\n#include \"file_utils.hpp\"\n#include \"image.hpp\"\n#include \"mapmanager.hpp\"\n#include \"mask.hpp\"\n#include \"math_utils.hpp\"\n#include \"tmatrix.hpp\"\n\nElasticRegistration::ElasticRegistration(std::shared_ptr<Image> fixed, std::shared_ptr<Image> moved,\n                                         std::shared_ptr<Mask> mask, const intcoord& target_spacing,\n                                         const ConfigurationBase& config)\n  : _comm(fixed->comm()), _fixed(std::move(fixed)), _moved(std::move(moved)), _mask(std::move(mask)),\n    _target_spacing(target_spacing), _configuration(config),\n    _mapmanager(std::make_unique<MapManager>(target_spacing, *_mask)),\n    _registered(GridVariable::copy(*_moved))\n{\n}\n\nvoid ElasticRegistration::set_initial_guess(const MapBase& initial_guess __attribute__((unused)))\n{\n  // Query manager for map closest in shape to initial_guess\n  // Set Mapmanager index to that shape\n  // Interpolate initial_guess to current map\n  // Carry on from there...\n  throw InternalError(\"Not yet implemented\");\n}\n\nvoid ElasticRegistration::autoregister(integer max_iterations)\n{\n  for (_current_map = _mapmanager->get_current_map(); _current_map != nullptr;\n       _current_map = _mapmanager->get_next_map())\n  {\n    registration_inner_loop(max_iterations);\n  }\n  _current_map = _mapmanager->get_current_map(); // Replace nullptr with final valid map\n}\n\nvoid ElasticRegistration::registration_inner_loop(integer max_iterations)\n{\n  integer iteration = 0;\n  if (_configuration.grab<bool>(\"save_intermediate_frames\"))\n  {\n    save_debug_frame(iteration);\n  }\n  for (iteration = 1; iteration <= max_iterations; iteration++)\n  {\n    this->_previous_mis.push_back(this->_fixed->mutual_information(*this->_moved));\n\n    // Do solver step, recalculating lambda if it is the first iteration of the loop\n    Vec_unique map_delta = solver_step(iteration, iteration == 1);\n\n    if (this->is_converged(*map_delta))\n    {\n      break;\n    }\n  }\n  if (iteration == max_iterations)\n  {\n    PetscPrintf(_comm, \"Warning: Maximum iteration limit reached (%d)\\n\", max_iterations);\n  }\n}\n\nVec_unique ElasticRegistration::solver_step(floating iternum, bool recalculate_lambda)\n{\n  auto tmat2_and_tmatfm = build_tmat2_and_tmatfm(*this->_fixed, *_registered, *this->_current_map);\n  Mat_unique tmat2 = std::move(tmat2_and_tmatfm.first);\n  Vec_unique tmatfm = std::move(tmat2_and_tmatfm.second);\n\n  floating lapl2_diag_sum = diagonal_sum(_current_map->laplacian2());\n  floating tmat2_diag_sum = diagonal_sum(*tmat2);\n  floating lapl_premult = tmat2_diag_sum / lapl2_diag_sum;\n  PetscPrintf(_comm, \"lapl_mult = %f, laplsum= %f, tmatsum = %f\\n\", lapl_premult, lapl2_diag_sum,\n              tmat2_diag_sum);\n\n\n  // Recalculate lambda if requested\n  if (recalculate_lambda)\n  {\n    _lambda = approximate_optimum_lambda(*tmat2, _current_map->laplacian2(), lapl_premult, _lambda,\n                                         _initial_search_width, _lambda_search_maxiter, _lambda_min);\n    PetscPrintf(_comm, \"Calculated lambda = %f\\n\", _lambda);\n  }\n\n  // Add lambda*L^tL to T^t T\n  PetscErrorCode perr = MatAXPY(*tmat2, _lambda * lapl_premult, _current_map->laplacian2(),\n                                DIFFERENT_NONZERO_PATTERN);\n  CHKERRXX(perr);\n\n  // Subtract lambda*L^tL*a from T^t(f-m)\n  Vec_unique lambda_l2_a = create_unique_vec();\n  perr = VecDuplicate(*tmatfm, lambda_l2_a.get());\n  CHKERRXX(perr);\n  perr = MatMult(_current_map->laplacian2(), _current_map->displacement_vector(), *lambda_l2_a);\n  CHKERRXX(perr);\n  //  perr = VecAXPY(*tmatfm, -_lambda * lapl_premult, *lambda_l2_a);\n  // CHKERRXX(perr);\n\n  // Co-opt now defunct lambda_l2_a as solution vector\n  Vec_unique delta = std::move(lambda_l2_a);\n\n  // Now do actual solve\n  KSP_unique m_ksp = create_unique_ksp();\n  perr = KSPCreate(_comm, m_ksp.get());\n  CHKERRXX(perr);\n  perr = KSPSetOperators(*m_ksp, *tmat2, *tmat2);\n  CHKERRXX(perr);\n  perr = KSPSetUp(*m_ksp);\n  CHKERRXX(perr);\n  perr = KSPSetFromOptions(*m_ksp);\n  CHKERRXX(perr);\n  perr = KSPSetUp(*m_ksp);\n  CHKERRXX(perr);\n  perr = KSPSolve(*m_ksp, *tmatfm, *delta);\n  CHKERRXX(perr);\n\n  // update map\n  _current_map->update(*delta);\n\n  // warp image\n  _registered = _moved->warp(*_current_map);\n  _registered->normalize();\n\n  floating mutinf = _registered->mutual_information(*_fixed);\n  _previous_mis.push_back(mutinf);\n  PetscPrintf(_comm, \"Mutual information: %f\\n\", mutinf);\n\n  if (_configuration.grab<bool>(\"save_intermediate_frames\"))\n  {\n    save_debug_frame(iternum);\n  }\n\n  return delta;\n}\n\nbool ElasticRegistration::is_converged(const Vec& map_delta, floating threshold)\n{\n  // Roll our own because we need to avoid intensity values\n  std::array<floating, 2> avg_data;\n  auto& avg_sum = avg_data[0];\n  auto& avg_num = avg_data[1];\n\n  floating localmax = PETSC_MIN_REAL;\n  integer local_lo, local_hi;\n  PetscErrorCode perr = VecGetOwnershipRange(map_delta, &local_lo, &local_hi);\n  CHKERRXX(perr);\n  avg_num = local_hi - local_lo;\n\n  const floating* delta_data;\n  perr = VecGetArrayRead(map_delta, &delta_data);\n  CHKERRXX(perr);\n  for (integer iidx = local_lo; iidx < local_hi; iidx++)\n  {\n    if (iidx % _current_map->ndof() == 0) // skip intensity values\n    {\n      continue;\n    }\n    floating absval = std::abs(delta_data[iidx]);\n    localmax = absval > localmax ? absval : localmax;\n    avg_sum += absval;\n  }\n  perr = VecRestoreArrayRead(map_delta, &delta_data);\n  CHKERRXX(perr);\n\n  MPI_Allreduce(MPI_IN_PLACE, &localmax, 1, MPIU_SCALAR, MPI_MAX, _comm);\n  MPI_Allreduce(MPI_IN_PLACE, avg_data.data(), 2, MPIU_SCALAR, MPI_SUM, _comm);\n\n  floating average = avg_sum / avg_num;\n\n  PetscPrintf(_comm, \"Displacement delta: %f / %f (avg / max)\\n\", average, localmax);\n\n  bool disp_conv = average < threshold;\n\n  // Now calculate gradient of MI over last n iterations\n  // First check if we need to discard values\n  while (this->_previous_mis.size() > this->_mi_window)\n  {\n    this->_previous_mis.pop_front();\n  }\n\n  // Now calculate simple linear regression\n  intvector xpoints(this->_previous_mis.size());\n  std::iota(xpoints.begin(), xpoints.end(), 1);\n  floating num_points = static_cast<double>(xpoints.size());\n\n  floating s_x = 0.5 * num_points * (num_points + 1);\n  floating s_xx = (1.0 / 6.0) * (num_points * (num_points + 1) * (2 * num_points + 1));\n  floating s_y = std::accumulate(this->_previous_mis.cbegin(), this->_previous_mis.cend(), 0.);\n  floating s_xy = accumulate(xpoints.cbegin(), xpoints.cend(), this->_previous_mis.cbegin(), 0.,\n                             [](floating x, integer y, floating z) -> floating { return x + y * z; });\n\n  floating mi_grad = (num_points*s_xy - s_x*s_y)/(num_points*s_xx - s_x*s_x);\n\n  PetscPrintf(_comm, \"Mutual Information gradient: %f\\n\", mi_grad);\n\n  bool mi_conv = false;\n  if(this->_previous_mis.size() >= this->_mi_window)\n  {\n    mi_conv = mi_grad < 0;\n  }\n\n  return disp_conv || mi_conv;\n}\n\nvoid ElasticRegistration::save_debug_frame(integer iteration_num)\n{\n  integer outer_count = _mapmanager->step_number();\n  std::ostringstream outname;\n  std::string file_str(_configuration.grab<std::string>(\"intermediate_template\"));\n  bf::path registered_path(_configuration.grab<std::string>(\"registered\"));\n\n  boost::format pad2(\"%02d\");\n  replace_token(file_str, ConfigurationBase::k_outer_token, (pad2 % outer_count).str());\n\n  boost::format pad3(\"%03d\");\n  replace_token(file_str, ConfigurationBase::k_inner_token, (pad3 % iteration_num).str());\n\n  replace_token(file_str, ConfigurationBase::k_stem_token, registered_path.filename().stem().string());\n\n  replace_token(file_str, ConfigurationBase::k_extension_token, registered_path.extension().string());\n\n  bf::path output_path(registered_path.parent_path());\n\n  bf::path intermediates_path(_configuration.grab<std::string>(\"intermediate_directory\"));\n  if (intermediates_path.is_absolute())\n  {\n    if (!bf::exists(intermediates_path))\n    {\n      std::ostringstream errss;\n      errss << \"Intermediate frame output path \" << intermediates_path << \" does not exist.\";\n      throw std::runtime_error(errss.str());\n    }\n    output_path = intermediates_path;\n  }\n  else\n  {\n    // Don't create directories we don't say we will, error instead\n    // (Pre-flight checks mean this should never throw)\n    if (!output_path.empty() && !bf::exists(output_path))\n    {\n      std::ostringstream errss;\n      errss << \"Output path \" << output_path << \" does not exist.\";\n      throw std::runtime_error(errss.str());\n    }\n\n    // Append intermediates dir\n    output_path /= _configuration.grab<std::string>(\"intermediate_directory\");\n\n    // Create intermediates dir as needed\n    bf::create_directories(output_path);\n  }\n\n  // Finally append filename and any group extension\n  output_path /= file_str;\n  std::string output_path_str(output_path.string());\n  output_path_str.append(\":\");\n  output_path_str.append(_configuration.grab<std::string>(\"registered_h5_path\"));\n\n  BaseWriter_unique wtr = BaseWriter::get_writer_for_filename(output_path_str, _comm);\n  wtr->write_image(*_registered);\n}\n\nfloating ElasticRegistration::approximate_optimum_lambda(const Mat& mat_a, const Mat& mat_b,\n                                                         floating lambda_mult, floating initial_guess,\n                                                         floating search_width, uinteger max_iter,\n                                                         floating lambda_min)\n{\n  floating x_lo = initial_guess - search_width;\n  x_lo = x_lo > lambda_min ? x_lo : lambda_min;\n  floating x_mid = initial_guess;\n  x_mid = x_mid > x_lo ? x_mid : x_lo + search_width/2;\n  floating x_hi = initial_guess + search_width;\n  x_hi = x_hi > x_mid ? x_hi : x_mid + search_width;\n\n  floating y_lo(0), y_mid(0), y_hi(0);\n  for (uinteger iter = 0; iter < max_iter; iter++)\n  {\n    Mat_unique mat_c = create_unique_mat();\n    PetscErrorCode perr = MatDuplicate(mat_a, MAT_COPY_VALUES, mat_c.get());\n\n    // calculate at lower value\n    perr = MatAXPY(*mat_c, lambda_mult * x_lo, mat_b, DIFFERENT_NONZERO_PATTERN);\n    CHKERRXX(perr);\n    y_lo = get_condnum_by_poweriter(*mat_c, 0.01, 100);\n\n    // Calculate at initial guess\n    perr = MatAXPY(*mat_c, lambda_mult * x_mid, mat_b, DIFFERENT_NONZERO_PATTERN);\n    CHKERRXX(perr);\n    y_mid = get_condnum_by_poweriter(*mat_c, 0.01, 100);\n\n    // calculate at higher value\n    perr = MatAXPY(*mat_c, lambda_mult * x_hi, mat_b, DIFFERENT_NONZERO_PATTERN);\n    CHKERRXX(perr);\n    y_hi = get_condnum_by_poweriter(*mat_c, 0.01, 100);\n\n    PetscPrintf(_comm, \" lo: %g(%g) mid: %g(%g) hi: %g(%g)\\n\", x_lo, y_lo, x_mid, y_mid, x_hi, y_hi);\n\n    // check initial lower than either side\n    if (y_lo >= y_mid)\n    {\n      // two options, either close to a minimum or need to search to higher x\n      if (y_hi < y_mid)\n      {\n        // All points are negative gradient: keep searching to higher values of x:\n        x_mid *= 2;\n        x_hi *= 2;\n        continue;\n      }\n      // Otherwise we are close to a local minimum and are done\n      break;\n    }\n\n    // If we already reached lambda_min we need to be done at that\n    if (x_lo == lambda_min)\n    {\n      break;\n    }\n\n    // Otherwise it is a positive gradient so keep searching left\n    x_lo = x_lo >= 2.0 * lambda_min ? x_lo / 2 : 1.0 * lambda_min;\n    x_mid = x_mid >= 2.0 * x_lo ? x_mid / 2 : x_lo + 1.0;\n    x_hi = x_hi >= 2.0 * x_mid ? x_hi / 2 : x_mid + 1.0;\n  }\n  // fit quadratic and return minimum\n  floating a, b, c;\n  quadratic_from_points(x_lo, x_mid, x_hi, y_lo, y_mid, y_hi, a, b, c);\n\n  if (a < 0)\n  {\n    PetscPrintf(_comm, \"Warning: convex function in smoothing parameter estimation.\\n\");\n    return lambda_min;\n  }\n\n  floating x, y;\n  quadratic_vertex(a, b, c, x, y);\n\n  if (x < lambda_min)\n  {\n    return lambda_min;\n  }\n\n  return x;\n}\n", "meta": {"hexsha": "f844941efb82a2c168425ac400c1ac76cc4dd0e4", "size": 12494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/elasticregistration.cpp", "max_stars_repo_name": "willfurnass/pFIRE", "max_stars_repo_head_hexsha": "251cac173f2337f504dfde122851b834fe3e77be", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-02-14T09:03:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T16:03:32.000Z", "max_issues_repo_path": "src/elasticregistration.cpp", "max_issues_repo_name": "willfurnass/pFIRE", "max_issues_repo_head_hexsha": "251cac173f2337f504dfde122851b834fe3e77be", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 64.0, "max_issues_repo_issues_event_min_datetime": "2019-01-29T16:22:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-07T07:54:28.000Z", "max_forks_repo_path": "src/elasticregistration.cpp", "max_forks_repo_name": "tartarini/pFIRE", "max_forks_repo_head_hexsha": "406fdbb188a17b6413edcd0a229213464628ab15", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-01-29T15:32:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-19T10:24:42.000Z", "avg_line_length": 34.4187327824, "max_line_length": 103, "alphanum_fraction": 0.6846486313, "num_tokens": 3361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2545038920652993}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2007-2015 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Copyright (c) 2008-2015 Bruno Lalande, Paris, France.\r\n// Copyright (c) 2009-2015 Mateusz Loskot, London, UK.\r\n\r\n// This file was modified by Oracle on 2015, 2017, 2018.\r\n// Modifications copyright (c) 2015-2018, Oracle and/or its affiliates.\r\n\r\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\r\n\r\n// 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_CARTESIAN_SIDE_BY_TRIANGLE_HPP\r\n#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_SIDE_BY_TRIANGLE_HPP\r\n\r\n#include <boost/mpl/if.hpp>\r\n#include <boost/type_traits/is_integral.hpp>\r\n#include <boost/type_traits/is_void.hpp>\r\n\r\n#include <boost/geometry/arithmetic/determinant.hpp>\r\n#include <boost/geometry/core/access.hpp>\r\n#include <boost/geometry/util/select_coordinate_type.hpp>\r\n\r\n#include <boost/geometry/strategies/cartesian/disjoint_segment_box.hpp>\r\n#include <boost/geometry/strategies/cartesian/envelope.hpp>\r\n#include <boost/geometry/strategies/cartesian/point_in_point.hpp>\r\n#include <boost/geometry/strategies/compare.hpp>\r\n#include <boost/geometry/strategies/side.hpp>\r\n\r\n#include <boost/geometry/algorithms/detail/equals/point_point.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace strategy { namespace side\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 CalculationType \\tparam_calculation\r\n */\r\ntemplate <typename CalculationType = void>\r\nclass side_by_triangle\r\n{\r\n    template <typename Policy>\r\n    struct eps_policy\r\n    {\r\n        eps_policy() {}\r\n        template <typename Type>\r\n        eps_policy(Type const& a, Type const& b, Type const& c, Type const& d)\r\n            : policy(a, b, c, d)\r\n        {}\r\n        Policy policy;\r\n    };\r\n\r\n    struct eps_empty\r\n    {\r\n        eps_empty() {}\r\n        template <typename Type>\r\n        eps_empty(Type const&, Type const&, Type const&, Type const&) {}\r\n    };\r\n\r\npublic :\r\n    typedef strategy::envelope::cartesian<CalculationType> envelope_strategy_type;\r\n\r\n    static inline envelope_strategy_type get_envelope_strategy()\r\n    {\r\n        return envelope_strategy_type();\r\n    }\r\n\r\n    typedef strategy::disjoint::segment_box disjoint_strategy_type;\r\n\r\n    static inline disjoint_strategy_type get_disjoint_strategy()\r\n    {\r\n        return disjoint_strategy_type();\r\n    }\r\n\r\n    typedef strategy::within::cartesian_point_point equals_point_point_strategy_type;\r\n    static inline equals_point_point_strategy_type get_equals_point_point_strategy()\r\n    {\r\n        return equals_point_point_strategy_type();\r\n    }\r\n\r\n    // Template member function, because it is not always trivial\r\n    // or convenient to explicitly mention the typenames in the\r\n    // strategy-struct itself.\r\n\r\n    // Types can be all three different. Therefore it is\r\n    // not implemented (anymore) as \"segment\"\r\n\r\n    template\r\n    <\r\n        typename CoordinateType,\r\n        typename PromotedType,\r\n        typename P1,\r\n        typename P2,\r\n        typename P,\r\n        typename EpsPolicy\r\n    >\r\n    static inline\r\n    PromotedType side_value(P1 const& p1, P2 const& p2, P const& p, EpsPolicy & eps_policy)\r\n    {\r\n        CoordinateType const x = get<0>(p);\r\n        CoordinateType const y = get<1>(p);\r\n\r\n        CoordinateType const sx1 = get<0>(p1);\r\n        CoordinateType const sy1 = get<1>(p1);\r\n        CoordinateType const sx2 = get<0>(p2);\r\n        CoordinateType const sy2 = get<1>(p2);\r\n\r\n        PromotedType const dx = sx2 - sx1;\r\n        PromotedType const dy = sy2 - sy1;\r\n        PromotedType const dpx = x - sx1;\r\n        PromotedType const dpy = y - sy1;\r\n\r\n        eps_policy = EpsPolicy(dx, dy, dpx, dpy);\r\n\r\n        return geometry::detail::determinant<PromotedType>\r\n                (\r\n                    dx, dy,\r\n                    dpx, dpy\r\n                );\r\n\r\n    }\r\n\r\n    template\r\n    <\r\n        typename CoordinateType,\r\n        typename PromotedType,\r\n        typename P1,\r\n        typename P2,\r\n        typename P\r\n    >\r\n    static inline\r\n    PromotedType side_value(P1 const& p1, P2 const& p2, P const& p)\r\n    {\r\n        eps_empty dummy;\r\n        return side_value<CoordinateType, PromotedType>(p1, p2, p, dummy);\r\n    }\r\n\r\n\r\n    template\r\n    <\r\n        typename CoordinateType,\r\n        typename PromotedType,\r\n        bool AreAllIntegralCoordinates\r\n    >\r\n    struct compute_side_value\r\n    {\r\n        template <typename P1, typename P2, typename P, typename EpsPolicy>\r\n        static inline PromotedType apply(P1 const& p1, P2 const& p2, P const& p, EpsPolicy & epsp)\r\n        {\r\n            return side_value<CoordinateType, PromotedType>(p1, p2, p, epsp);\r\n        }\r\n    };\r\n\r\n    template <typename CoordinateType, typename PromotedType>\r\n    struct compute_side_value<CoordinateType, PromotedType, false>\r\n    {\r\n        template <typename P1, typename P2, typename P, typename EpsPolicy>\r\n        static inline PromotedType apply(P1 const& p1, P2 const& p2, P const& p, EpsPolicy & epsp)\r\n        {\r\n            // For robustness purposes, first check if any two points are\r\n            // the same; in this case simply return that the points are\r\n            // collinear\r\n            if (equals_point_point(p1, p2)\r\n                || equals_point_point(p1, p)\r\n                || equals_point_point(p2, p))\r\n            {\r\n                return PromotedType(0);\r\n            }\r\n\r\n            // The side_by_triangle strategy computes the signed area of\r\n            // the point triplet (p1, p2, p); as such it is (in theory)\r\n            // invariant under cyclic permutations of its three arguments.\r\n            //\r\n            // In the context of numerical errors that arise in\r\n            // floating-point computations, and in order to make the strategy\r\n            // consistent with respect to cyclic permutations of its three\r\n            // arguments, we cyclically permute them so that the first\r\n            // argument is always the lexicographically smallest point.\r\n\r\n            typedef compare::cartesian<compare::less> less;\r\n\r\n            if (less::apply(p, p1))\r\n            {\r\n                if (less::apply(p, p2))\r\n                {\r\n                    // p is the lexicographically smallest\r\n                    return side_value<CoordinateType, PromotedType>(p, p1, p2, epsp);\r\n                }\r\n                else\r\n                {\r\n                    // p2 is the lexicographically smallest\r\n                    return side_value<CoordinateType, PromotedType>(p2, p, p1, epsp);\r\n                }\r\n            }\r\n\r\n            if (less::apply(p1, p2))\r\n            {\r\n                // p1 is the lexicographically smallest\r\n                return side_value<CoordinateType, PromotedType>(p1, p2, p, epsp);\r\n            }\r\n            else\r\n            {\r\n                // p2 is the lexicographically smallest\r\n                return side_value<CoordinateType, PromotedType>(p2, p, p1, epsp);\r\n            }\r\n        }\r\n    };\r\n\r\n\r\n    template <typename P1, typename P2, typename P>\r\n    static inline int apply(P1 const& p1, P2 const& p2, P const& p)\r\n    {\r\n        typedef typename coordinate_type<P1>::type coordinate_type1;\r\n        typedef typename coordinate_type<P2>::type coordinate_type2;\r\n        typedef typename coordinate_type<P>::type coordinate_type3;\r\n\r\n        typedef typename boost::mpl::if_c\r\n            <\r\n                boost::is_void<CalculationType>::type::value,\r\n                typename select_most_precise\r\n                    <\r\n                        typename select_most_precise\r\n                            <\r\n                                coordinate_type1, coordinate_type2\r\n                            >::type,\r\n                        coordinate_type3\r\n                    >::type,\r\n                CalculationType\r\n            >::type coordinate_type;\r\n\r\n        // Promote float->double, small int->int\r\n        typedef typename select_most_precise\r\n            <\r\n                coordinate_type,\r\n                double\r\n            >::type promoted_type;\r\n\r\n        bool const are_all_integral_coordinates =\r\n            boost::is_integral<coordinate_type1>::value\r\n            && boost::is_integral<coordinate_type2>::value\r\n            && boost::is_integral<coordinate_type3>::value;\r\n\r\n        eps_policy< math::detail::equals_factor_policy<promoted_type> > epsp;\r\n        promoted_type s = compute_side_value\r\n            <\r\n                coordinate_type, promoted_type, are_all_integral_coordinates\r\n            >::apply(p1, p2, p, epsp);\r\n\r\n        promoted_type const zero = promoted_type();\r\n        return math::detail::equals_by_policy(s, zero, epsp.policy) ? 0\r\n            : s > zero ? 1\r\n            : -1;\r\n    }\r\n\r\nprivate:\r\n    template <typename P1, typename P2>\r\n    static inline bool equals_point_point(P1 const& p1, P2 const& p2)\r\n    {\r\n        typedef equals_point_point_strategy_type strategy_t;\r\n        return geometry::detail::equals::equals_point_point(p1, p2, strategy_t());\r\n    }\r\n};\r\n\r\n\r\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\nnamespace services\r\n{\r\n\r\ntemplate <typename CalculationType>\r\nstruct default_strategy<cartesian_tag, CalculationType>\r\n{\r\n    typedef side_by_triangle<CalculationType> type;\r\n};\r\n\r\n}\r\n#endif\r\n\r\n}} // namespace strategy::side\r\n\r\n}} // namespace boost::geometry\r\n\r\n\r\n#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_SIDE_BY_TRIANGLE_HPP\r\n", "meta": {"hexsha": "8b2ca1d663390d7ccb799913e96bd3acda061ba3", "size": 9924, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dep/win/include/boost/geometry/strategies/cartesian/side_by_triangle.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/strategies/cartesian/side_by_triangle.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/strategies/cartesian/side_by_triangle.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": 33.4141414141, "max_line_length": 99, "alphanum_fraction": 0.6117492946, "num_tokens": 2212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2544892256250065}}
{"text": "/**\n * \\file\n * \\copyright\n * Copyright (c) 2012-2020, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/project/license\n *\n */\n\n#include \"BHE_2U.h\"\n\n#include <boost/math/constants/constants.hpp>\n#include \"FlowAndTemperatureControl.h\"\n#include \"Physics.h\"\n#include \"ThermoMechanicalFlowProperties.h\"\n\nnamespace ProcessLib\n{\nnamespace HeatTransportBHE\n{\nnamespace BHE\n{\nBHE_2U::BHE_2U(BoreholeGeometry const& borehole,\n               RefrigerantProperties const& refrigerant,\n               GroutParameters const& grout,\n               FlowAndTemperatureControl const& flowAndTemperatureControl,\n               PipeConfigurationUType const& pipes,\n               bool const use_python_bcs)\n    : BHECommonUType{borehole, refrigerant,   grout, flowAndTemperatureControl,\n                     pipes,    use_python_bcs}\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_2U::number_of_unknowns> BHE_2U::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 {{/*i1*/ rho_r * specific_heat_capacity,\n             /*i2*/ rho_r * specific_heat_capacity,\n             /*o1*/ rho_r * specific_heat_capacity,\n             /*o2*/ rho_r * specific_heat_capacity,\n             /*g1*/ (1.0 - porosity_g) * rho_g * heat_cap_g,\n             /*g2*/ (1.0 - porosity_g) * rho_g * heat_cap_g,\n             /*g3*/ (1.0 - porosity_g) * rho_g * heat_cap_g,\n             /*g4*/ (1.0 - porosity_g) * rho_g * heat_cap_g}};\n}\n\nstd::array<double, BHE_2U::number_of_unknowns> BHE_2U::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 = _pipes.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 BHE. These governing equations can be found in\n    // 1) Diersch (2013) FEFLOW book on page 952, M.120-122, or\n    // 2) Diersch (2011) Comp & Geosci 37:1122-1135, Eq. 19-22.\n    return {{// pipe i1\n             (lambda_r + rho_r * Cp_r * alpha_L * _flow_velocity),\n             // pipe i2\n             (lambda_r + rho_r * Cp_r * alpha_L * _flow_velocity),\n             // pipe o1\n             (lambda_r + rho_r * Cp_r * alpha_L * _flow_velocity),\n             // pipe o2\n             (lambda_r + rho_r * Cp_r * alpha_L * _flow_velocity),\n             // pipe g1\n             (1.0 - porosity_g) * lambda_g,\n             // pipe g2\n             (1.0 - porosity_g) * lambda_g,\n             // pipe g3\n             (1.0 - porosity_g) * lambda_g,\n             // pipe g4\n             (1.0 - porosity_g) * lambda_g}};\n}\n\nstd::array<Eigen::Vector3d, BHE_2U::number_of_unknowns>\nBHE_2U::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\n    return {{// pipe i1\n             {0, 0, -rho_r * Cp_r * _flow_velocity},\n             // pipe i2\n             {0, 0, -rho_r * Cp_r * _flow_velocity},\n             // pipe o1\n             {0, 0, rho_r * Cp_r * _flow_velocity},\n             // pipe o2\n             {0, 0, rho_r * Cp_r * _flow_velocity},\n             // grout g1\n             {0, 0, 0},\n             // grout g2\n             {0, 0, 0},\n             // grout g3\n             {0, 0, 0},\n             // grout g4\n             {0, 0, 0}}};\n}\n\ndouble compute_R_gs_2U(double const chi, double const R_g)\n{\n    return (1 - chi) * R_g;\n}\n\ndouble compute_R_gg_2U(double const chi, double const R_gs, double const R_ar,\n                       double const R_g)\n{\n    double const R_gg = 2.0 * R_gs * (R_ar - 2.0 * chi * R_g) /\n                        (2.0 * R_gs - R_ar + 2.0 * chi * R_g);\n    if (!std::isfinite(R_gg))\n    {\n        OGS_FATAL(\n            \"Error!!! Grout Thermal Resistance is an infinite number! The \"\n            \"simulation will be stopped!\");\n    }\n\n    return R_gg;\n}\n\n/// Thermal resistances due to grout-soil exchange.\n///\n/// Check if constraints regarding negative thermal resistances are violated\n/// apply correction procedure.\n/// Section (1.5.5) in FEFLOW White Papers Vol V.\nstd::vector<double> thermalResistancesGroutSoil2U(double chi,\n                                                  double const R_ar_1,\n                                                  double const R_ar_2,\n                                                  double const R_g)\n{\n    double R_gs = compute_R_gs_2U(chi, R_g);\n    double R_gg_1 = compute_R_gg_2U(chi, R_gs, R_ar_1, R_g);\n    double R_gg_2 = compute_R_gg_2U(chi, R_gs, R_ar_2,\n                                    R_g);  // Resulting thermal resistances.\n\n    auto constraint = [&]() {\n        return 1.0 / ((1.0 / R_gg_1) + (1.0 / (2.0 * R_gs)));\n    };\n\n    std::array<double, 3> const multiplier{chi * 0.66, chi * 0.5 * 0.66, 0.0};\n    for (double m_chi : multiplier)\n    {\n        if (constraint() >= 0)\n        {\n            break;\n        }\n        DBUG(\n            \"Warning! Correction procedure was applied due to negative thermal \"\n            \"resistance! Chi = {:f}.\\n\",\n            m_chi);\n        R_gs = compute_R_gs_2U(m_chi, R_g);\n        R_gg_1 = compute_R_gg_2U(m_chi, R_gs, R_ar_1, R_g);\n        R_gg_2 = compute_R_gg_2U(m_chi, R_gs, R_ar_2, R_g);\n    }\n\n    return {R_gg_1, R_gg_2, R_gs};\n}\n\nvoid BHE_2U::updateHeatTransferCoefficients(double const flow_rate)\n\n{\n    auto const tm_flow_properties = calculateThermoMechanicalFlowPropertiesPipe(\n        _pipes.inlet, 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_2U::number_of_unknowns> BHE_2U::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 = _pipes.inlet.wall_thermal_conductivity;\n\n    // thermal resistances due to advective flow of refrigerant in the _pipes\n    // Eq. 36 in Diersch_2011_CG\n    double const R_adv_i = 1.0 / (Nu * lambda_r * pi);\n    double const R_adv_o = 1.0 / (Nu * lambda_r * pi);\n\n    // thermal resistance due to thermal conductivity of the pipe wall material\n    // Eq. 49\n    double const R_con_a =\n        std::log(_pipes.inlet.outsideDiameter() / _pipes.inlet.diameter) /\n        (2.0 * pi * lambda_p);\n\n    // the average outer diameter of the _pipes\n    double const d0 = _pipes.outlet.outsideDiameter();\n    double const D = borehole_geometry.diameter;\n    // Eq. 38\n    double const chi =\n        std::log(std::sqrt(D * D + 4 * d0 * d0) / 2 / std::sqrt(2) / d0) /\n        std::log(D / 2 / d0);\n    // Eq. 39\n    // thermal resistances of the grout\n    double const R_g =\n        std::acosh((D * D + d0 * d0 - 2 * _pipes.distance * _pipes.distance) /\n                   (2 * D * d0)) /\n        (2 * pi * lambda_g) *\n        (3.098 - 4.432 * std::sqrt(2) * _pipes.distance / D +\n         2.364 * 2 * _pipes.distance * _pipes.distance / D / D);\n    // thermal resistance due to the grout transition.\n    double const R_con_b = chi * R_g;\n\n    // Eq. 29 and 30\n    double const R_fig = 2 * R_adv_i + 2 * R_con_a + R_con_b;\n    double const R_fog = 2 * R_adv_o + 2 * R_con_a + R_con_b;\n\n    // thermal resistance due to inter-grout exchange\n    double const R_ar_1 =\n        std::acosh((2.0 * _pipes.distance * _pipes.distance - d0 * d0) / d0 /\n                   d0) /\n        (2.0 * pi * lambda_g);\n\n    double const R_ar_2 =\n        std::acosh((2.0 * 2.0 * _pipes.distance * _pipes.distance - d0 * d0) /\n                   d0 / d0) /\n        (2.0 * pi * lambda_g);\n\n    std::vector<double> _intergrout_thermal_exchange;\n    _intergrout_thermal_exchange =\n        thermalResistancesGroutSoil2U(chi, R_ar_1, R_ar_2, R_g);\n\n    return {{R_fig, R_fog, _intergrout_thermal_exchange[0],\n             _intergrout_thermal_exchange[1], _intergrout_thermal_exchange[2]}};\n\n    // keep the following lines------------------------------------------------\n    // when debugging the code, printing the R and phi values are needed--------\n    // std::cout << \"Rfig =\" << R_fig << \" Rfog =\" << R_fog << \" Rgg =\" <<\n    // R_gg << \" Rgs =\" << R_gs << \"\\n\"; double phi_fig = 1.0 / (R_fig *\n    // S_i); double phi_fog = 1.0 / (R_fog * S_o); double phi_gg = 1.0 / (R_gg\n    // * S_g1); double phi_gs = 1.0 / (R_gs * S_gs); std::cout << \"phi_fig =\"\n    // << phi_fig << \" phi_fog =\" << phi_fog << \" phi_gg =\" << phi_gg << \"\n    // phi_gs =\" << phi_gs << \"\\n\";\n    // -------------------------------------------------------------------------\n}\n\nstd::array<std::pair<std::size_t /*node_id*/, int /*component*/>, 2>\nBHE_2U::getBHEInflowDirichletBCNodesAndComponents(\n    std::size_t const top_node_id,\n    std::size_t const /*bottom_node_id*/,\n    int const in_component_id) const\n{\n    return {std::make_pair(top_node_id, in_component_id),\n            std::make_pair(top_node_id, in_component_id + 2)};\n}\n\nstd::optional<\n    std::array<std::pair<std::size_t /*node_id*/, int /*component*/>, 2>>\nBHE_2U::getBHEBottomDirichletBCNodesAndComponents(\n    std::size_t const bottom_node_id,\n    int const in_component_id,\n    int const out_component_id) const\n{\n    return {{std::make_pair(bottom_node_id, in_component_id),\n             std::make_pair(bottom_node_id, out_component_id)}};\n}\n\nstd::array<double, BHE_2U::number_of_unknowns> BHE_2U::crossSectionAreas() const\n{\n    return {{\n        _pipes.inlet.area(),\n        _pipes.inlet.area(),\n        _pipes.outlet.area(),\n        _pipes.outlet.area(),\n        borehole_geometry.area() / 4 - _pipes.inlet.outsideArea(),\n        borehole_geometry.area() / 4 - _pipes.inlet.outsideArea(),\n        borehole_geometry.area() / 4 - _pipes.outlet.outsideArea(),\n        borehole_geometry.area() / 4 - _pipes.outlet.outsideArea(),\n    }};\n}\n\ndouble BHE_2U::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": "3cdcb2bfaeba4bb93d22f25d9c8002dc5d828369", "size": 11255, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ProcessLib/HeatTransportBHE/BHE/BHE_2U.cpp", "max_stars_repo_name": "fwitte/ogs", "max_stars_repo_head_hexsha": "0b367872fc58ecd4e1dbfe1dcebbc847da6639d7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-13T01:58:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-13T01:58:38.000Z", "max_issues_repo_path": "ProcessLib/HeatTransportBHE/BHE/BHE_2U.cpp", "max_issues_repo_name": "fwitte/ogs", "max_issues_repo_head_hexsha": "0b367872fc58ecd4e1dbfe1dcebbc847da6639d7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2015-01-09T13:08:57.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-25T12:56:17.000Z", "max_forks_repo_path": "ProcessLib/HeatTransportBHE/BHE/BHE_2U.cpp", "max_forks_repo_name": "fwitte/ogs", "max_forks_repo_head_hexsha": "0b367872fc58ecd4e1dbfe1dcebbc847da6639d7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-13T13:37:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-01T10:19:03.000Z", "avg_line_length": 36.5422077922, "max_line_length": 80, "alphanum_fraction": 0.5998223012, "num_tokens": 3168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2544266851885184}}
{"text": "/***************************************************************************\n                          graphalgs.cc  -  description\n                             -------------------\n    begin                : Tue Feb 28 2006\n    copyright            : (C) 2005 by Knut-Helge Vik\n    email                : knuthelv@ifi.uio.no\n ***************************************************************************/\n#include \"graphalgs.h\"\n#include \"../boostprop.h\"\n//#include \"../simtime.h\"\n//#include \"../treealgs/treealgs.h\"\n//#include \"../treealgs/dijkstra_sp.h\"\n//#include \"../boostprop.h\"\n//#include \"../network/node_base.h\"\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/reverse_graph.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <functional>\n#include <iostream>\n#include <fstream>\n#include <cmath>\n\nusing namespace std;\nusing namespace boost;\nusing namespace TreeAlgorithms;\n\nnamespace GraphAlgorithms\n{\n\n/*-----------------------------------------------------------------------\n\t\t\t\t\t\tgenerate\n------------------------------------------------------------------------- */\nint generateRandomNumber(double max)\n{ \n\treturn (int) (max * rand() / (RAND_MAX + 1.0));\n}\n\nint generateSizeOfSteinerSet(int members)\n{\n\tint numToAdd = 0;\n\n\t// if fixed then return number\n\tif(GlobalSimArgs::getSteinerMemberSize() > 0) return GlobalSimArgs::getSteinerMemberSize();\n\n\t// else calculate with regards to degree limit and number of members\n\tif(ADD_CORE_LINKS_OPTIMIZED == GlobalSimArgs::getSimPruneAlgo())\n\t{\n\t\tif(isSteinerAlgo(GlobalSimArgs::getSimTreeAlgo()) || (GlobalSimArgs::getSimGraphAlgo() != COMPLETE_MEMBER_GRAPH))\n\t\t{\t\t\t\n\t\t\tnumToAdd = (int) (ceil( (double) members/ (double) GlobalSimArgs::getDegreeConstraintSP())); // - 2) * 2) + 2;\n\t\t\t//numToAdd = numToAdd + (int) (ceil( (double) ((numToAdd * 2) + 2)/ (double) GlobalSimArgs::getDegreeConstraintSP()));\n\t\t\tnumToAdd = numToAdd + (int) (ceil( (double) (numToAdd + 2)/ (double) GlobalSimArgs::getDegreeConstraintSP()));\n\t\t}\n\t\telse // not steiner algo\n\t\t{\n\t\t\t//cerr << WRITE_FUNCTION << \" ERRORRERRORREERRRROROROEOREOREOREORO!!!!!!!! -> wrongly calculated steiner ste size \" << endl;\n\t\t\tnumToAdd = (int) (ceil( (double) members/ (double) GlobalSimArgs::getDegreeConstraint())); // - 2) * 2) + 2;\n\t\t\tnumToAdd = numToAdd + (int) (ceil( (double) (numToAdd + 2)/ (double) GlobalSimArgs::getDegreeConstraint()));\n\t\t}\n\t}\n\telse // K_BEST_LINKS ...\n\t{\n\t\tif((GlobalSimArgs::getSteinerMemberRatio() > 0) && ((isSteinerAlgo(GlobalSimArgs::getSimTreeAlgo()) || (GlobalSimArgs::getSimGraphAlgo() != COMPLETE_MEMBER_GRAPH))))\n\t\t{\n\t\t\tnumToAdd = int(members * GlobalSimArgs::getSteinerMemberRatio());\n\t\t}\n\t\telse if(isSteinerAlgo(GlobalSimArgs::getSimTreeAlgo()) || (GlobalSimArgs::getSimGraphAlgo() != COMPLETE_MEMBER_GRAPH))\n\t\t{\n\t\t\t//cerr << WRITE_FUNCTION << \" ERRORRERRORREERRRROROROEOREOREOREORO!!!!!!!! -> wrongly calculated steiner ste size \" << endl;\n\t\t\tnumToAdd = (int) (ceil( (double) members/ (double) GlobalSimArgs::getDegreeConstraintSP())); // - 2) * 2) + 2;\n\t\t\tnumToAdd = numToAdd + (int) (ceil( (double) (numToAdd + 2)/ (double) GlobalSimArgs::getDegreeConstraintSP()));\n\t\t\t//numToAdd = numToAdd + (int) (ceil( (double) ((numToAdd * 2) + 2)/ (double) GlobalSimArgs::getDegreeConstraintSP()));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tnumToAdd = (int) (ceil( (double) members/ (double) GlobalSimArgs::getDegreeConstraint())); // - 2) * 2) + 2;\n\t\t\tnumToAdd = numToAdd + (int) (ceil( (double) (numToAdd + 2)/ (double) GlobalSimArgs::getDegreeConstraint()));\n\t\t}\n\t}\n\t//cerr << WRITE_FUNCTION << \" num sp to add \" << numToAdd << endl;\n\t\n\tif(numToAdd <= 1) numToAdd = 2;\n\treturn numToAdd;\n}\n\nint generateSizeOfSteinerSet(int members, int steiner)\n{\n\treturn max((generateSizeOfSteinerSet(members) - steiner), 0);\n}\n\nint generateSizeNonSteiner(int members)\n{\n\t// if fixed then return number\n\tif(GlobalSimArgs::getSteinerMemberSize() > 0) return GlobalSimArgs::getSteinerMemberSize();\n\n\tint numToAdd = (int) (ceil( (double) members/ (double) GlobalSimArgs::getDegreeConstraint())); // - 2) * 2) + 2;\n\tnumToAdd = numToAdd + (int) (ceil( (double) ((numToAdd * 2) + 2)/ (double) GlobalSimArgs::getDegreeConstraint()));\n\treturn numToAdd;\n}\n\ndouble generateDelayLimit(int members)\n{\n\tdouble delayLimit = (members + generateSizeOfSteinerSet(members) ) * 0.75;\n\tASSERTING(delayLimit > 0);\n\t\n\treturn delayLimit; \n}\n\n/*-----------------------------------------------------------------------\nObservation: Minimum number of edges to avoid partitioning a graph is:\n\tpartitions = 2;\n\t(|V|/|partitions|) = n;\n\tnC2 = |e|; // w/ 2 partitions\n\t|min_edges| = |e| + 1; // w/ no partitions\n------------------------------------------------------------------------- */\n\nint generateMinEdgeCountNoPartition(int num_vertices)\n{\n\tint partitions = 2; \t\t// minimum partitions in a graph\n\t\n\tint n = (int) (num_vertices/partitions) + 1;\n\tcerr << \"n \" << n << endl;\n\t\n\tint r = 2;\n\tint nfac = n;\n\tfor(int i = nfac-1; i > 0; i--)\n\t\tnfac = nfac * i;\n\t\n\tcerr << \"nfac \" << nfac << endl;\n\t\n\tint nminrfac = (n-r);\n\tfor(int i = nminrfac - 1; i > 0; i--)\n\t\tnminrfac = nminrfac * i;\n\t\n\tcerr << \"nminrfac \" << nminrfac << endl;\n\t\n\tint e = nfac/(r * nminrfac);\n\t\n\tcerr << WRITE_FUNCTION  << num_vertices << \" vertices needs \" << (e + 1) << \" edges \" << endl;\n\treturn (e + 1);\n\t\n\t//int numberV = generateSizeOfSteinerSet(groupInfo.vertexMap_.size()) + groupInfo.vertexMap_.size();\n\t//int minEdgeCount = generateMinEdgeCountNoPartition(numberV);\n\t//double kfloat = (double) (minEdgeCount/numberV);\n\t//double integer;\n\t//double frac = modf( (double) kfloat, &integer);\n\t//double k = ceil(kfloat);\n\t//cerr << \"minEdgeCount \" << minEdgeCount << \" kfloat \" << kfloat << \" frac \" << frac << \" integer \" << integer << \" k \" << k << endl;\n\t//char c = getchar();\n}\n\n\n/*-----------------------------------------------------------------------\n\tProduces a graph tha only has vertices with out edges, and,\n\tthe vertex/edge index != vertex/edge id\n------------------------------------------------------------------------- */\nvoid densifyGraph(const GraphN &g, GraphN& dg)\n{\n\t//cerr << WRITE_FUNCTION << endl; print_graph(g_in, get(&VertexProp::id, g_in));\n\n\t// Old sparse Graph\n\t//iVertexMap idmap_g \t\t= get(&VertexProp::id, &g);\n\t//vsVertexMap vsmap_g     = get(&VertexProp::vertexState, &g);\n\t\t\n\t// new Dense Graph\n\tiVertexMap \tidmap_dg\t= get(&VertexProp::id, dg);\n    vertex_iteratorN vit, vit_end, vit_in, vit_in_end;\n    \n\t// -- Adding vertices and properties --\n    for(boost::tuples::tie(vit, vit_end) = vertices(g); vit != vit_end; ++vit)\n    {\n\t\tif(getOutDegree(g, *vit) > 0)\n    \t{\n    \t\tvertex_descriptorN u = add_vertex(g[*vit], dg);\n    \t\t//cerr << \"Added: \"  << u << \" id: \" << idmap_dg[u] << \" VertexState: \" << dg[u].vertexState << endl;\n    \t\t//ASSERTING(dg[u].vertexState == GROUP_MEMBER || dg[u].vertexState == STEINER_POINT);\n    \t}\n    }\n    \n    // -- Adding edges and properties --\n    boost::tuples::tie(vit_in, vit_in_end) = vertices(dg);\n    boost::tuples::tie(vit, vit_end) = vertices(dg);\n    for(  ; vit != vit_end; ++vit)\n    {\n    \t//cerr << \"u: \" << *vit ;\n   \t\tfor( vit_in = vit; vit_in != vit_in_end; ++vit_in)\n\t\t{\n\t\t\tif(*vit != *vit_in)\n\t\t\t{\n\t\t\t\tpair<edge_descriptorN, bool> ep = edge(idmap_dg[*vit], idmap_dg[*vit_in], g);\n\t\t\t\tif(ep.second)\n\t\t\t\t{\n\t\t\t\t\tASSERTING(ep.second);\n\t\t\t\t\tpair<edge_descriptorN, bool> e = add_edge(*vit, *vit_in, dg);\n\t\t\t\t\tASSERTING(e.second);\n\t\t\t\t\tdg[e.first] = g[ep.first];\n\t\t\t\n\t\t\t\t\t// -- debug --\n\t\t\t\t\t//cerr << \" v: \" << *vit_in << endl;\n\t\t\t\t\t//cerr << \"Found e(g): \"  << ep.first << \" (\" << g[ep.first].id.first << \",\" << g[ep.first].id.second << \")\" << endl;\t\t\t\t\t\n\t\t\t\t\t//cerr << \"Added e(dg): \"  << e.first << \" (\" << dg[e.first].id.first << \",\" << dg[e.first].id.second << \")\" << endl;\t\t\t\t\t\n\t\t\t\t\t// -- debug end --\n\t\t\t\t}\n\t\t\t}\n\t\t}\n    }\n\t\n\t// -- debug --\n\tcerr << WRITE_FUNCTION << endl; \n\t//print_graph(dg, get(&VertexProp::id, dg));\n\t//dumpGraph(dg);\n\tcheckGraph(dg);\t\n\t//char c = getchar();\n}\n\nvoid densifyGraph(const TreeStructure &T, GraphN& dg)\n{\n\t// -- Adding vertices and properties --\n\tfor(VertexSet::iterator vit = T.V.begin(), vit_end = T.V.end(); vit != vit_end; ++vit)\n\t\tif(getOutDegree(T.g, *vit) > 0)\n    \t\tvertex_descriptorN u = add_vertex(T.g[*vit], dg);\n    \n    // -- Adding edges and properties --\n\tiVertexMap \tidmap_dg\t= get(&VertexProp::id, dg);\n\tvertex_iteratorN vit, vit_end, vit_in, vit_in_end;\n    \n    boost::tuples::tie(vit_in, vit_in_end) = vertices(dg);\n    boost::tuples::tie(vit, vit_end) = vertices(dg);\n    for(  ; vit != vit_end; ++vit)\n    {\n    \t//cerr << \"u: \" << *vit ;\n   \t\tfor( vit_in = vit; vit_in != vit_in_end; ++vit_in)\n\t\t{\n\t\t\tif(*vit != *vit_in)\n\t\t\t{\n\t\t\t\tpair<edge_descriptorN, bool> ep = edge(idmap_dg[*vit], idmap_dg[*vit_in], T.g);\n\t\t\t\tif(ep.second)\n\t\t\t\t{\n\t\t\t\t\tASSERTING(ep.second);\n\t\t\t\t\tpair<edge_descriptorN, bool> e = add_edge(*vit, *vit_in, dg);\n\t\t\t\t\tASSERTING(e.second);\n\t\t\t\t\tdg[e.first] = T.g[ep.first];\n\t\t\t\n\t\t\t\t\t// -- debug --\n\t\t\t\t\t//cerr << \" v: \" << *vit_in << endl;\n\t\t\t\t\t//cerr << \"Found e(T.g): \"  << ep.first << \" (\" << T.g[ep.first].id.first << \",\" << T.g[ep.first].id.second << \")\" << endl;\t\t\t\t\t\n\t\t\t\t\t//cerr << \"Added e(dg): \"  << e.first << \" (\" << dg[e.first].id.first << \",\" << dg[e.first].id.second << \")\" << endl;\t\t\t\t\t\n\t\t\t\t\t// -- debug end --\n\t\t\t\t}\n\t\t\t}\n\t\t}\n    }\n\t\n\t// -- debug --\n\t//cerr << WRITE_FUNCTION << endl; \n\t//dumpGraph(dg);\n\tcheckGraph(dg);\t\n}\n\n/*-----------------------------------------------------------------------\n\tProduces a graph that may have vertices with no out-edges, and,\n\tthat has vertex/edge index == vertex/edge id\n------------------------------------------------------------------------- */\nvoid sparsifyGraph(const GraphN &g, GraphN& dg)\n{\n\t//cerr << WRITE_FUNCTION << endl; print_graph(g_in, get(&VertexProp::id, g_in));\n\n\t// Old dense Graph\n\tiVertexMapConst idmap_g \t\t= get(&VertexProp::id, g);\n\tvsVertexMapConst vsmap_g     = get(&VertexProp::vertexState, g);\n\t\t\n\t// new sparse Graph\n\tiVertexMap \tidmap_dg\t= get(&VertexProp::id, dg);\n    vertex_iteratorN vit, vit_end, vit_in, vit_in_end;\n    \n    // -- Adding vertices, edges and properties --\n    boost::tuples::tie(vit_in, vit_in_end) = vertices(g);\n    boost::tuples::tie(vit, vit_end) = vertices(g);\n    for(  ; vit != vit_end; ++vit)\n    {\n    \t//cerr << \"u: \" << *vit ;\n   \t\tfor( vit_in = vit; vit_in != vit_in_end; ++vit_in)\n\t\t{\n\t\t\tif(*vit != *vit_in)\n\t\t\t{\n\t\t\t\t//pair<edge_descriptorN, bool> ep = edge(idmap_dg[*vit], idmap_dg[*vit_in], g);\n\t\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, *vit_in, g);\n\t\t\t\tif(ep.second)\n\t\t\t\t{\n\t\t\t\t\tASSERTING(ep.second);\n\t\t\t\t\tpair<edge_descriptorN, bool> e = add_edge(idmap_g[*vit], idmap_g[*vit_in], dg);\n\t\t\t\t\tASSERTING(e.second);\n\t\t\t\t\tdg[e.first] = g[ep.first];\n\t\t\t\n\t\t\t\t\t// adding vertex properties\n\t\t\t\t\tdg[idmap_g[*vit]] = g[*vit];\n\t\t\t\t\tdg[idmap_g[*vit_in]] = g[*vit_in];\n\t\t\t\n\t\t\t\t\t// -- debug --\n\t\t\t\t\t//cerr << \" v: \" << *vit_in << endl;\n\t\t\t\t\t//cerr << \"Found v(g): \" << *vit << \", \" << *vit_in << endl;\n\t\t\t\t\t//cerr << \"Added v(dg): \" << idmap_g[*vit] << \", \" << idmap_g[*vit_in] << endl;\n\t\t\t\t\t//cerr << \"Found e(g): \"  << ep.first << \" (\" << g[ep.first].id.first << \",\" << g[ep.first].id.second << \")\" << endl;\n\t\t\t\t\t//cerr << \"Added e(dg): \"  << e.first << \" (\" << dg[e.first].id.first << \",\" << dg[e.first].id.second << \")\" << endl;\t\t\t\t\t\n\t\t\t\t\t// -- debug end --\n\t\t\t\t}\n\t\t\t}\n\t\t}\n    }\n\t\n\t// -- debug --\n\t//cerr << WRITE_FUNCTION << endl; \n\t//print_graph(dg, get(&VertexProp::id, dg));\n\t//dumpGraph(dg);\n\tcheckGraph(dg);\t\n\t//char c = getchar();\n}\n/*-----------------------------------------------------------------------\n\t\t\t\tchecks the validity of the graph\n------------------------------------------------------------------------- */\nvoid checkGraph(const GraphN &g)\n{\n\n#ifndef NDEBUG\n\n\tASSERTING(num_edges(g) > 0);\n\tASSERTING(num_vertices(g) > 1);\n\n\tvertex_iteratorN vit, vit_end;\n    for(boost::tuples::tie(vit, vit_end) = vertices(g); vit != vit_end; ++vit)\n\t{\n\t\tif(getOutDegree(g, *vit) > 0)\n\t\t{\n\t\t\tif(g[*vit].vertexFunction == NO_FUNCTION || g[*vit].vertexState == VERTEX_STATE_ERROR)\n\t\t\t{\n\t\t\t\tcerr << WRITE_FUNCTION << \"Node : \" << *vit << \" \" << g[*vit] << endl;\n\t\t\t\t//dumpGraph(g); \n\t\t\t}\n\t\t\tASSERTING(g[*vit].vertexState != VERTEX_STATE_ERROR);\n\t\t\tASSERTING(g[*vit].vertexFunction != NO_FUNCTION);\n\t\t\tASSERTING(g[*vit].id > -1);\n\n\t\t\tout_edge_iteratorN oit, oit_end;\n            for(boost::tuples::tie(oit, oit_end) = out_edges(*vit, g); oit != oit_end; ++oit)\n\t\t\t{\n\t\t\t\tif(g[*oit].weight <= 0 ||\n\t\t\t\t\tg[*oit].cost <= 0 ||\n\t\t\t\t\tg[*oit].delay <= 0 ||\n\t\t\t\t\tg[*oit].id.first == g[*oit].id.second)\n\t\t\t\t\t//g[*oit].weight > GlobalSimArgs::maxEdgeDelay_)\n\t\t\t\t{\n\n\t\t\t\t\tvertex_descriptorN src = source(*oit, g), targ = target(*oit, g);\n\t\t\t\t\tpair<edge_descriptorN, bool> ep = edge(src, targ, g);\n\t\t\t\t\tif(ep.second) cerr << \"(\" << src << \",\" << targ << \") edge prop : \" << g[ep.first] << endl;\n\n\t\t\t\t\t//dumpGraph(g); \n\t\t\t\t\tcerr << WRITE_FUNCTION << \"node: \" << *vit << g[*vit] << \" edge : \" << *oit << \" : \" <<  g[*oit] << endl;\n\t\t\t\t\tcerr << WRITE_FUNCTION << \" out degree : \" << getOutDegree(*vit, g) << \" edges : \" << endl;\n\t\t\t\n\t\t\t\t\tout_edge_iteratorN oit_in, oit_in_end;\n                    for(boost::tuples::tie(oit_in, oit_in_end) = out_edges(*vit, g); oit_in != oit_in_end; ++oit_in)\n\t\t\t\t\t\tcerr << \"(\" << *oit_in << \",\" << g[*oit_in] << \") \" ;\n\n\t\t\t\t\tcerr << endl;\n\t\t\t\t}\n\t\t\t\tASSERTING(g[*oit].weight > 0);\n\t\t\t\tASSERTING(g[*oit].cost  > 0);\n\t\t\t\tASSERTING(g[*oit].delay > 0);\n\t\t\t\tASSERTING(g[*oit].id.first != g[*oit].id.second);\n\t\t\t\tASSERTING(g[*oit].weight <= GlobalSimArgs::maxEdgeDelay_);\n\t\t\t}\n\n\t\t\t/*if(g[*vit].obj != NULL)\n\t\t\t{\n\t\t\t\tNodeBase *nob = g[*vit].obj;\n\t\t\t\tif(nob->getId() != *vit)\n\t\t\t\t{\n\t\t\t\t\tcerr << WRITE_FUNCTION << \"Node : \" << g[*vit] << endl;\n\t\t\t\t}\n\n\t\t\t\tASSERTING(nob->getId() == *vit);\n\t\t\t}*/\n\t\t}\n\t\telse if(getOutDegree(g, *vit) <= 0)\n\t\t{\n\t\t\tif(g[*vit].vertexState == STEINER_POINT || g[*vit].vertexState == GROUP_MEMBER)\n\t\t\t{\n\t\t\t\tcerr << WRITE_FUNCTION << \"Node : \" << g[*vit] << endl;\n\t\t\t\t//dumpGraph(g); \n\t\t\t}\t\t\t\n\t\t\tASSERTING(g[*vit].vertexState != STEINER_POINT);\n\t\t\tASSERTING(g[*vit].vertexState != GROUP_MEMBER);\n\t\t}\n\t}\n\t\n\tcheckIsPartitioned(g);\n\t//checkMaxDistance(g);\n#endif\n\n}\n\nvoid checkGraphEqualSP(const GraphN &g)\n{\n#ifndef NDEBUG\n\tASSERTING(num_edges(g) > 0);\n\tASSERTING(num_vertices(g) > 1);\n\n\tvertex_iteratorN vit, vit_end, vit_in, vit_in_end;\n    for(boost::tuples::tie(vit, vit_end) = vertices(g); vit != vit_end; ++vit)\n\t{\t\t\t\n\t\tout_edge_iteratorN oit, oit_end;\n        for(boost::tuples::tie(oit, oit_end) = out_edges(*vit, g); oit != oit_end; ++oit)\n\t\t{\n\t\t\tdouble shortest_path_weight = g[*oit].weight;\n\t\t\tunsigned int targ = target(*oit, g);\n\n            for(boost::tuples::tie(vit_in, vit_in_end) = vertices(g); vit_in != vit_in_end; ++vit_in)\n\t\t\t{\t\n\t\t\t\tif(*vit_in == *vit) continue;\n\t\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, *vit_in, g);\n\t\t\t\tASSERTING(ep.second);\n\t\n\t\t\t\tif(*vit_in == targ) continue;\n\t\t\t\t\n\t\t\t\tpair<edge_descriptorN, bool> ep_in = edge(*vit_in, targ, g);\n\t\t\t\tASSERTING(ep_in.second);\n\t\t\t\t\n\t\t\t\t// (*vit -> targ) == (*vit -> *vit_in -> targ)?\n\t\t\t\tdouble indirect_path_weight = g[ep.first].weight + g[ep_in.first].weight;\n\t\t\t\tif(shortest_path_weight == indirect_path_weight)\n\t\t\t\t{\n\t\t\t\t\tcerr << WRITE_PRETTY_FUNCTION << \" shortest_path_weight : \" << shortest_path_weight << \" == indirect_path_weight \" << indirect_path_weight << \" Edge : \" << g[*oit] << \" == path: \" << g[ep.first] << \" \" << g[ep_in.first] << endl;\n\t\t\t\t}\n\t\t\t\telse if(shortest_path_weight > indirect_path_weight)\n\t\t\t\t{\n\t\t\t\t\tcerr << WRITE_PRETTY_FUNCTION << \"ERROR!! shortest_path_weight : \" << shortest_path_weight << \" > indirect_path_weight \" << indirect_path_weight << \" Edge : \" << g[*oit] << \" == path: \" << g[ep.first] << \" \" << g[ep_in.first] << endl;\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n#endif\n}\n\nint cntSPViolations(const GraphN &g)\n{\n\tASSERTING(num_edges(g) > 0);\n\tASSERTING(num_vertices(g) > 1);\n\n\tint num_of_violations = 0;\n\t\n\tvertex_iteratorN vit, vit_end, vit_in, vit_in_end;\n    for(boost::tuples::tie(vit, vit_end) = vertices(g); vit != vit_end; ++vit)\n\t{\t\t\t\n\t\tout_edge_iteratorN oit, oit_end;\n        for(boost::tuples::tie(oit, oit_end) = out_edges(*vit, g); oit != oit_end; ++oit)\n\t\t{\n\t\t\tdouble shortest_path_weight = (double)g[*oit].weight;\n\t\t\tunsigned int targ = target(*oit, g);\n\n            //for(boost::tuples::tie(vit_in, vit_in_end) = vertices(g); vit_in != vit_in_end; ++vit_in)\n\t\t\tfor(vit_in = vit, vit_in_end = vit_end; vit_in != vit_in_end; ++vit_in)\n\t\t\t{\t\n\t\t\t\tif(*vit_in == *vit) continue;\n\t\t\t\tif(*vit_in == targ) continue;\n\t\t\t\t\n\t\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, *vit_in, g);\n\t\t\t\tif(!ep.second) continue;\n\t\t\t\t\t\n\t\t\t\tpair<edge_descriptorN, bool> ep_in = edge(*vit_in, targ, g);\n\t\t\t\tif(!ep_in.second) continue;\n\t\t\t\t\n\t\t\t\t// (*vit -> targ) == (*vit -> *vit_in -> targ)?\n\t\t\t\tdouble indirect_path_weight = (double) g[ep.first].weight + (double) g[ep_in.first].weight;\n\t\t\t\t\n\t\t\t\t//if((float) indirect_path_weight < (float) shortest_path_weight)\n\t\t\t\tif(shortest_path_weight - indirect_path_weight > 0.0001 && shortest_path_weight < 2)\n\t\t\t\t{\n\t\t\t\t\tdouble diff = (float)indirect_path_weight - (float)shortest_path_weight;\n\n\t\t\t\t\tnum_of_violations++;\n\t\t\t\t\t//cerr << WRITE_PRETTY_FUNCTION << \"not sp edge: \" << *oit << \" sp weight : \" << shortest_path_weight << \" > indirect \" << indirect_path_weight << \" Edge : \" << g[*oit] << \" > path: \" << g[ep.first] << \" \" << g[ep_in.first] << endl;\n\t\t\t\t\t//printf(\" shortest_path_weight : %f indirect_path_weight %f\\n\", shortest_path_weight,  indirect_path_weight);\n\t\t\t\t\t//ASSERTING( indirect_path_weight < shortest_path_weight );\n\t\t\t\t\t//ASSERTING( indirect_path_weight == shortest_path_weight );\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn num_of_violations;\n}\n\nint cntInvalidEdgeWeights(const GraphN &g, int invalid_weight)\n{\n\tint counter = 0;\n\tedge_iteratorN eit, eit_end;\n    for(boost::tuples::tie(eit, eit_end) = edges(g); eit !=eit_end; ++eit)\n\t\tif(g[*eit].weight >= invalid_weight) counter++;\n\t\t\n\treturn counter;\n}\n\nint cntInvalidEdgeWeights(const GraphN &g, const VertexSet &invalidV, int invalid_weight)\n{\n\tint counter = 0;\n\tedge_iteratorN eit, eit_end;\n    for(boost::tuples::tie(eit, eit_end) = edges(g); eit !=eit_end; ++eit)\n\t{\n\t\tint src = source(*eit, g), targ = target(*eit, g);\n\t\tif(invalidV.contains(src) || invalidV.contains(targ)) continue;\n\n\t\tif(g[*eit].weight >= invalid_weight) counter++;\n\t}\n\t\t\n\treturn counter;\n}\n\n\nint cntInvalidVertices(const GraphN &g, VertexSet &invalidVertices, int invalid_weight)\n{\n\tint counter = 0;\n\tvertex_iteratorN vit, vit_end;\n    for(boost::tuples::tie(vit, vit_end) = vertices(g); vit != vit_end; ++vit)\n\t{\n\t\tint cnt_invalid = 0;\n\t\tout_edge_iteratorN oit, oit_end;\n        for(boost::tuples::tie(oit, oit_end) = out_edges(*vit, g); oit != oit_end; ++oit)\n\t\t{\n\t\t\tif(g[*oit].weight >= invalid_weight)\n\t\t\t\tcnt_invalid++;\n\t\t}\n\n\t\tif(cnt_invalid >= (out_degree(*vit, g) - 4)) \n\t\t{\n\t\t\tcounter++;\n\t\t\tinvalidVertices.insert(*vit);\n\t\t}\n\t}\n\n\treturn counter;\n}\n\n/*-----------------------------------------------------------------------\n\tconnects a partitioned graph through shortest paths\n------------------------------------------------------------------------- */\nvoid connectPartitionedGraph(const TreeStructure &inputT, TreeStructure &newT)\n{\n\t// ensure graph is connected\n\tVertexSet partV;\n\twhile(findPartition(newT.g, partV))\n\t{\n\t\tbool inserted_edge = false;\n\t\tfor(VertexSet::const_iterator vi = partV.begin(), vi_end = partV.end(); vi != vi_end; ++vi)\n\t\t{\n\t\t\tint src = *vi;\n\t\t\tstd::multimap<double, edge_descriptorN> addEdges;\n\t\t\tout_edge_iteratorN oit, oit_end;  \n            for(boost::tuples::tie(oit, oit_end) = out_edges(src, inputT.g); oit != oit_end; ++oit)\n\t\t\t\taddEdges.insert(pair<double, edge_descriptorN>(get(&EdgeProp::weight, inputT.g)[*oit], *oit));\n\t\n\t\t\tfor(std::multimap<double, edge_descriptorN>::iterator mit = addEdges.begin(), mit_end = addEdges.end(); mit != mit_end; ++mit)\n\t\t\t{\n\t\t\t\tint targ = target(mit->second, inputT.g);\n\t\t\t\tASSERTING(src != targ);\n\n\t\t\t\tif(partV.contains(targ)) continue;\n\t\n\t\t\t\tif(newT.isEdge(src, targ) == false) \n\t\t\t\t{\n\t\t\t\t\tnewT.insertEdge(src, targ, inputT.g);\n\t\t\t\t\tinserted_edge = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(inserted_edge == true) break;\n\t\t}\n\t\t\n\t\tpartV.clear();\n\t}\n}\n\n/*-----------------------------------------------------------------------\n\tfinds out whether the graph is partitioned\n------------------------------------------------------------------------- */\nbool findPartition(const GraphN &g, VertexSet &partV)\n{\n\tvector<bool> visited(num_vertices(g));\n\t\n\t// init\n\tvertex_iteratorN vit, vit_end;\n    for(boost::tuples::tie(vit, vit_end) = vertices(g); vit != vit_end; ++vit)\n\t{\n\t\tvisited[*vit] = false;\t\n\t}\n\t\n\t// start walk \n    for(boost::tuples::tie(vit, vit_end) = vertices(g); vit != vit_end; ++vit)\n\t{\n\t\tif(getOutDegree(g, *vit) > 0)\n\t\t{\n\t\t\twalkGraph(g, *vit, visited);\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\t// check\n\tbool partition = false;\n    for(boost::tuples::tie(vit, vit_end) = vertices(g); vit != vit_end; ++vit)\n\t{\n\t\tif(g[*vit].id > -1 && visited[*vit] == false)\n\t\t{\n\t\t\t//if(!partition) cerr << WRITE_FUNCTION << \" Partition (\" << *vit ;\n\t\t\t//else cerr << \", \" << *vit;\n\n\t\t\tpartV.insert(*vit);\n\t\t\tpartition = true;\n\t\t}\n\t}\n\t\n\t//if(partition) cerr << \")\" << endl;\n\t\n\treturn partition;\n}\n\n/*-----------------------------------------------------------------------\n\tfinds out whether the graph is partitioned\n------------------------------------------------------------------------- */\nbool checkIsPartitioned(const GraphN &g)\n{\n\tvector<bool> visited(num_vertices(g));\n\t\n\t// init\n\tvertex_iteratorN vit, vit_end;\n    for(boost::tuples::tie(vit, vit_end) = vertices(g); vit != vit_end; ++vit)\n\t{\n\t\tvisited[*vit] = false;\t\n\t}\n\t\n\t// start walk \n    for(boost::tuples::tie(vit, vit_end) = vertices(g); vit != vit_end; ++vit)\n\t{\n\t\tif(getOutDegree(g, *vit) > 0)\n\t\t{\n\t\t\twalkGraph(g, *vit, visited);\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\t// check\n\tbool connected = true;\n    for(boost::tuples::tie(vit, vit_end) = vertices(g); vit != vit_end; ++vit)\n\t{\n\t\t//if(getOutDegree(*vit, g) > 0)\n\t\t//{\n\t\t\tif(g[*vit].id > -1 && visited[*vit] == false)\n\t\t\t{\n\t\t\t\tif(connected) cerr << WRITE_FUNCTION << \" Partition (\" << *vit ;\n\t\t\t\telse cerr << \", \" << *vit;\n\t\t\t\t\n\t\t\t\tconnected = false;\n\t\t\t}\n\t\t\t//ASSERTING(visited[*vit] == true);\n\t\t//}\n\t}\n\t\n\tif(!connected)\n\t\tcerr << \")\" << endl;\n\t\n\treturn connected;\n}\n\nvoid walkGraph(const GraphN &g, vertex_descriptorN u, vector<bool> &visited)\n{\n\tout_edge_iteratorN oit, oit_end;\n    for(boost::tuples::tie(oit, oit_end) = out_edges(u, g); oit != oit_end; ++oit)\n\t{\n\t\tvertex_descriptorN v = target(*oit, g);\n\t\tASSERTING(u != v);\n\t\tif(visited[v] == false)\n\t\t{\n\t\t\tvisited[v] = true;\n\t\t\twalkGraph(g, v, visited);\t\n\t\t}\t\t\n\t}\t\t\n}\n\nvoid checkMaxDistance(const GraphN &g)\n{\n#ifndef NDEBUG\n\tdouble maxDistance = 0;\n\tdEdgeMapConst wmap = get(&EdgeProp::weight, g);\n\t\t\n\tvertex_iteratorN vit, vit_end;\n    for(boost::tuples::tie(vit, vit_end) = vertices(g); vit != vit_end; ++vit)\n\t{\n\t\tout_edge_iteratorN oit, oit_end;\n        for(boost::tuples::tie(oit, oit_end) = out_edges(*vit, g); oit != oit_end; ++oit)\n\t\t{\n\t\t\tif(wmap[*oit] > maxDistance) maxDistance = wmap[*oit];\n\t\t\t//if(g[*oit].weight > maxDistance) maxDistance = g[*oit].weight;\n\n\t\t}\n\t}\t\n\t\n\t//cerr << \"Max Distance \" << maxDistance << endl;\n\tGlobalSimArgs::maxEdgeDelay_ = maxDistance;\n#endif // NDEBUG\n}\n\n\n\n}; // namespace GraphAlgorithms\n\n\n", "meta": {"hexsha": "2cdbb2057c64727eb65555873094f511c3ad4db3", "size": 23299, "ext": "cc", "lang": "C++", "max_stars_repo_path": "GraphLib/graphalgs/graphalgs.cc", "max_stars_repo_name": "intact-software-systems/cpp-software-patterns", "max_stars_repo_head_hexsha": "e463fc7eeba4946b365b5f0b2eecf3da0f4c895b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-03T07:23:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-03T07:23:11.000Z", "max_issues_repo_path": "GraphLib/graphalgs/graphalgs.cc", "max_issues_repo_name": "intact-software-systems/cpp-software-patterns", "max_issues_repo_head_hexsha": "e463fc7eeba4946b365b5f0b2eecf3da0f4c895b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GraphLib/graphalgs/graphalgs.cc", "max_forks_repo_name": "intact-software-systems/cpp-software-patterns", "max_forks_repo_head_hexsha": "e463fc7eeba4946b365b5f0b2eecf3da0f4c895b", "max_forks_repo_licenses": ["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.3597222222, "max_line_length": 239, "alphanum_fraction": 0.5754753423, "num_tokens": 6935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2543645606876603}}
{"text": "#include \"rbfcore.h\"\n#include \"utility.h\"\n#include \"Solver.h\"\n#include <armadillo>\n#include <fstream>\n#include <limits>\n#include <unordered_map>\n#include <ctime>\n#include <chrono>\n#include <iomanip>\n#include <algorithm>\n#include <queue>\n#include \"readers.h\"\n//#include \"mymesh/UnionFind.h\"\n//#include \"mymesh/tinyply.h\"\n\ntypedef std::chrono::high_resolution_clock Clock;\ndouble randomdouble() {return static_cast <double> (rand()) / static_cast <double> (RAND_MAX);}\ndouble randomdouble(double be,double ed) {return be + randomdouble()*(ed-be);\t}\n\nvoid RBF_Core::NormalRecification(double maxlen, vector<double>&nors){\n\n\n    double maxlen_r = -1;\n    auto p_vn = nors.data();\n    int  np = nors.size()/3;\n    if(1){\n        for(int i=0;i<np;++i){\n            maxlen_r = max(maxlen_r,MyUtility::normVec(p_vn+i*3));\n        }\n\n        cout<<\"maxlen_r: \"<<maxlen_r<<endl;\n        double ratio = maxlen / maxlen_r;\n        for(auto &a:nors)a*=ratio;\n    }else{\n        for(int i=0;i<np;++i){\n            MyUtility::normalize(p_vn+i*3);\n        }\n\n    }\n\n\n\n\n}\n\nbool RBF_Core::Write_Hermite_NormalPrediction(string fname, int mode){\n\n\n//    vector<uchar>labelcolor(npt*4);\n//    vector<uint>f2v;\n//    uchar red[] = {255,0,0, 255};\n//    uchar green[] = {0,255,0, 255};\n//    uchar blue[] = {0,0,255, 255};\n//    for(int i=0;i<labels.size();++i){\n//        uchar *pcolor;\n//        if(labels[i]==0)pcolor = green;\n//        else if(labels[i]==-1)pcolor = blue;\n//        else if(labels[i]==1)pcolor = red;\n//        for(int j=0;j<4;++j)labelcolor[i*4+j] = pcolor[j];\n//    }\n    //fname += mp_RBF_METHOD[curMethod];\n\n//    for(int i=0;i<npt;++i){\n//        uchar *pcolor = green;\n//        for(int j=0;j<4;++j)labelcolor[i*4+j] = pcolor[j];\n//    }\n\n    vector<double>nors;\n    if(mode ==0)nors=initnormals;\n    else if(mode == 1)nors=newnormals;\n    else if(mode == 2)nors = initnormals_uninorm;\n    NormalRecification(1.,nors);\n\n    //for(int i=0;i<npt;++i)if(randomdouble()<0.5)MyUtility::negVec(nors.data()+i*3);\n    //cout<<pts.size()<<' '<<f2v.size()<<' '<<nors.size()<<' '<<labelcolor.size()<<endl;\n    //writePLYFile(fname,pts,f2v,nors,labelcolor);\n\n//    writeObjFile_vn(fname,pts,nors);\n    writePLYFile_VN(fname,pts,nors);\n\n    return 1;\n}\n\n\n\nvoid RBF_Core::Set_HermiteRBF(vector<double>&pts){\n\n    cout<<\"Set_HermiteRBF\"<<endl;\n    //for(auto a:pts)cout<<a<<' ';cout<<endl;\n    isHermite = true;\n\n    a.set_size(npt*4);\n    M.set_size(npt*4,npt*4);\n    double *p_pts = pts.data();\n    for(int i=0;i<npt;++i){\n        for(int j=i;j<npt;++j){\n            M(i,j) = M(j,i) = Kernal_Function_2p(p_pts+i*3, p_pts+j*3);\n        }\n    }\n\n\n    //if(User_Lamnbda!=0)for(int i=0;i<npt;++i)M(i,i) += User_Lamnbda;\n\n\n    double G[3];\n    for(int i=0;i<npt;++i){\n        for(int j=0;j<npt;++j){\n\n            Kernal_Gradient_Function_2p(p_pts+i*3, p_pts+j*3, G);\n            //            int jind = j*3+npt;\n            //            for(int k=0;k<3;++k)M(i,jind+k) = -G[k];\n            //            for(int k=0;k<3;++k)M(jind+k,i) = G[k];\n\n            for(int k=0;k<3;++k)M(i,npt+j+k*npt) = G[k];\n            for(int k=0;k<3;++k)M(npt+j+k*npt,i) = G[k];\n\n        }\n    }\n\n    double H[9];\n    for(int i=0;i<npt;++i){\n        for(int j=i;j<npt;++j){\n\n            Kernal_Hessian_Function_2p(p_pts+i*3, p_pts+j*3, H);\n            //            int iind = i*3+npt;\n            //            int jind = j*3+npt;\n            //            for(int k=0;k<3;++k)\n            //                for(int l=0;l<3;++l)\n            //                    M(jind+l,iind+k) = M(iind+k,jind+l) = -H[k*3+l];\n\n            for(int k=0;k<3;++k)\n                for(int l=0;l<3;++l)\n                    M(npt+j+l*npt,npt+i+k*npt) = M(npt+i+k*npt,npt+j+l*npt) = -H[k*3+l];\n        }\n    }\n\n    //cout<<std::setprecision(5)<<std::fixed<<M<<endl;\n\n    bsize= 4;\n    N.zeros(npt*4,4);\n    b.set_size(4);\n\n    for(int i=0;i<npt;++i){\n        N(i,0) = 1;\n        for(int j=0;j<3;++j)N(i,j+1) = pts[i*3+j];\n    }\n    for(int i=0;i<npt;++i){\n        //        int ind = i*3+npt;\n        //        for(int j=0;j<3;++j)N(ind+j,j+1) = 1;\n\n        for(int j=0;j<3;++j)N(npt+i+j*npt,j+1) = -1;\n    }\n\n    //cout<<N<<endl;\n    //arma::vec eigval = eig_sym( M ) ;\n    //cout<<eigval.t()<<endl;\n\n\n    if(!isnewformula){\n        cout<<\"start solve M: \"<<endl;\n        auto t1 = Clock::now();\n        if(isinv)Minv = inv(M);\n        else {\n            arma::mat Eye;\n            Eye.eye(npt*4,npt*4);\n            Minv = solve(M,Eye);\n        }\n        cout<<\"solved M: \"<<(invM_time = std::chrono::nanoseconds(Clock::now() - t1).count()/1e9)<<endl;\n\n        t1 = Clock::now();\n        if(isinv)bprey = inv_sympd(N.t() * Minv * N) * N.t() * Minv;\n        else {\n            arma::mat Eye2;\n            Eye2.eye(bsize,bsize);\n            bprey = solve(N.t() * Minv * N, Eye2) * N.t() * Minv;\n        }\n        cout<<\"solved bprey \"<<std::chrono::nanoseconds(Clock::now() - t1).count()/1e9<<endl;\n    }else{\n\n\n\n    }\n}\n\n\ndouble Gaussian_2p(const double *p1, const double *p2, double sigma){\n\n    return exp(-MyUtility::vecSquareDist(p1,p2)/(2*sigma*sigma));\n}\n\n\n\nvoid RBF_Core::Set_Actual_User_LSCoef(double user_ls){\n\n    User_Lamnbda = User_Lamnbda_inject = user_ls > 0 ?  user_ls : 0;\n\n}\n\nvoid RBF_Core::Set_Actual_Hermite_LSCoef(double hermite_ls){\n\n    ls_coef = Hermite_ls_weight_inject = hermite_ls > 0?hermite_ls:0;\n}\n\nvoid RBF_Core::Set_SparsePara(double spa){\n    sparse_para = spa;\n}\n\nvoid RBF_Core::Set_User_Lamnda_ToMatrix(double user_ls){\n\n\n    {\n        Set_Actual_User_LSCoef(user_ls);\n        auto t1 = Clock::now();\n        cout<<\"setting K, HermiteApprox_Lamnda\"<<endl;\n        if(User_Lamnbda>0){\n            arma::sp_mat eye;\n            eye.eye(npt,npt);\n\n            dI = inv(eye + User_Lamnbda*K00);\n            saveK_finalH = K = K11 - (User_Lamnbda)*(K01.t()*dI*K01);\n\n        }else saveK_finalH = K = K11;\n        cout<<\"solved: \"<<(std::chrono::nanoseconds(Clock::now() - t1).count()/1e9)<<endl;\n    }\n\n    finalH = saveK_finalH;\n\n}\n\nvoid RBF_Core::Set_HermiteApprox_Lamnda(double hermite_ls){\n\n\n    {\n        Set_Actual_Hermite_LSCoef(hermite_ls);\n        auto t1 = Clock::now();\n        cout<<\"setting K, HermiteApprox_Lamnda\"<<endl;\n        if(ls_coef>0){\n            arma::sp_mat eye;\n            eye.eye(npt,npt);\n\n            if(ls_coef > 0){\n                arma:: mat tmpdI = inv(eye + (ls_coef+User_Lamnbda)*K00);\n                K = K11 - (ls_coef+User_Lamnbda)*(K01.t()*tmpdI*K01);\n            }else{\n                K = saveK_finalH;\n            }\n        }\n        cout<<\"solved: \"<<(std::chrono::nanoseconds(Clock::now() - t1).count()/1e9)<<endl;    \n    }\n\n\n}\n\n\n\nvoid RBF_Core::Set_Hermite_PredictNormal(vector<double>&pts){\n\n\n\n    Set_HermiteRBF(pts);\n\n    auto t1 = Clock::now();\n    cout<<\"setting K\"<<endl;\n\n\n    if(!isnewformula){\n        arma::mat D = N.t()*Minv;\n        K = Minv - D.t()*inv(D*N)*D;\n        K = K.submat( npt, npt, npt*4-1, npt*4-1 );\n        finalH = saveK_finalH = K;\n\n    }else{\n        cout<<\"using new formula\"<<endl;\n        bigM.zeros((npt+1)*4,(npt+1)*4);\n        bigM.submat(0,0,npt*4-1,npt*4-1) = M;\n        bigM.submat(0,npt*4,(npt)*4-1, (npt+1)*4-1) = N;\n        bigM.submat(npt*4,0,(npt+1)*4-1, (npt)*4-1) = N.t();\n\n        //for(int i=0;i<4;++i)bigM(i+(npt)*4,i+(npt)*4) = 1;\n\n        auto t2 = Clock::now();\n        bigMinv = inv(bigM);\n        cout<<\"bigMinv: \"<<(setK_time= std::chrono::nanoseconds(Clock::now() - t2).count()/1e9)<<endl;\n\t\tbigM.clear();\n        Minv = bigMinv.submat(0,0,npt*4-1,npt*4-1);\n        Ninv = bigMinv.submat(0,npt*4,(npt)*4-1, (npt+1)*4-1);\n\n        bigMinv.clear();\n        //K = Minv - Ninv *(N.t()*Minv);\n        K = Minv;\n        K00 = K.submat(0,0,npt-1,npt-1);\n        K01 = K.submat(0,npt,npt-1,npt*4-1);\n        K11 = K.submat( npt, npt, npt*4-1, npt*4-1 );\n\n        M.clear();N.clear();\n        cout<<\"K11: \"<<K11.n_cols<<endl;\n\n\n        //Set_Hermite_DesignedCurve();\n\n        Set_User_Lamnda_ToMatrix(User_Lamnbda_inject);\n\n\t\t\n//\t\tarma::vec eigval, ny;\n//\t\tarma::mat eigvec;\n//\t\tny = eig_sym( eigval, eigvec, K);\n//\t\tcout<<ny<<endl;\n\n        cout<<\"K: \"<<K.n_cols<<endl;\n    }\n\n\n\n\n    //K = ( K.t() + K )/2;\n    cout<<\"solve K total: \"<<(setK_time= std::chrono::nanoseconds(Clock::now() - t1).count()/1e9)<<endl;\n    return;\n\n}\n\n\n\nvoid RBF_Core::SetInitnormal_Uninorm(){\n\n    initnormals_uninorm = initnormals;\n    for(int i=0;i<npt;++i)MyUtility::normalize(initnormals_uninorm.data()+i*3);\n\n}\n\nint RBF_Core::Solve_Hermite_PredictNormal_UnitNorm(){\n\n    arma::vec eigval, ny;\n    arma::mat eigvec;\n\n    if(!isuse_sparse){\n        ny = eig_sym( eigval, eigvec, K);\n    }else{\n//\t\tcout<<\"use sparse eigen\"<<endl;\n//        int k = 4;\n//        do{\n//            ny = eigs_sym( eigval, eigvec, sp_K, k, \"sa\" );\n//            k+=4;\n//        }while(ny(0)==0);\n    }\n\n\n    cout<<\"eigval(0): \"<<eigval(0)<<endl;\n\n    int smalleig = 0;\n\n    initnormals.resize(npt*3);\n    arma::vec y(npt*4);\n    for(int i=0;i<npt;++i)y(i) = 0;\n    for(int i=0;i<npt*3;++i)y(i+npt) = eigvec(i,smalleig);\n    for(int i=0;i<npt;++i){\n        initnormals[i*3]   = y(npt+i);\n        initnormals[i*3+1] = y(npt+i+npt);\n        initnormals[i*3+2] = y(npt+i+npt*2);\n        //MyUtility::normalize(normals.data()+i*3);\n    }\n\n\n    SetInitnormal_Uninorm();\n    cout<<\"Solve_Hermite_PredictNormal_UnitNorm finish\"<<endl;\n    return 1;\n}\n\n\n\n/***************************************************************************************************/\n/***************************************************************************************************/\ndouble acc_time;\n\nstatic int countopt = 0;\ndouble optfunc_Hermite(const vector<double>&x, vector<double>&grad, void *fdata){\n\n    auto t1 = Clock::now();\n    RBF_Core *drbf = reinterpret_cast<RBF_Core*>(fdata);\n    int n = drbf->npt;\n    arma::vec arma_x(n*3);\n\n    //(  sin(a)cos(b), sin(a)sin(b), cos(a)  )  a =>[0, pi], b => [-pi, pi];\n    vector<double>sina_cosa_sinb_cosb(n * 4);\n    for(int i=0;i<n;++i){\n        int ind = i*4;\n        sina_cosa_sinb_cosb[ind] = sin(x[i*2]);\n        sina_cosa_sinb_cosb[ind+1] = cos(x[i*2]);\n        sina_cosa_sinb_cosb[ind+2] = sin(x[i*2+1]);\n        sina_cosa_sinb_cosb[ind+3] = cos(x[i*2+1]);\n    }\n\n    for(int i=0;i<n;++i){\n        auto p_scsc = sina_cosa_sinb_cosb.data()+i*4;\n        //        int ind = i*3;\n        //        arma_x(ind) = p_scsc[0] * p_scsc[3];\n        //        arma_x(ind+1) = p_scsc[0] * p_scsc[2];\n        //        arma_x(ind+2) = p_scsc[1];\n        arma_x(i) = p_scsc[0] * p_scsc[3];\n        arma_x(i+n) = p_scsc[0] * p_scsc[2];\n        arma_x(i+n*2) = p_scsc[1];\n    }\n\n    arma::vec a2;\n    //if(drbf->isuse_sparse)a2 = drbf->sp_H * arma_x;\n    //else\n    a2 = drbf->finalH * arma_x;\n\n\n    if (!grad.empty()) {\n\n        grad.resize(n*2);\n\n        for(int i=0;i<n;++i){\n            auto p_scsc = sina_cosa_sinb_cosb.data()+i*4;\n\n            //            int ind = i*3;\n            //            grad[i*2] = a2(ind) * p_scsc[1] * p_scsc[3] + a2(ind+1) * p_scsc[1] * p_scsc[2] - a2(ind+2) * p_scsc[0];\n            //            grad[i*2+1] = -a2(ind) * p_scsc[0] * p_scsc[2] + a2(ind+1) * p_scsc[0] * p_scsc[3];\n\n            grad[i*2] = a2(i) * p_scsc[1] * p_scsc[3] + a2(i+n) * p_scsc[1] * p_scsc[2] - a2(i+n*2) * p_scsc[0];\n            grad[i*2+1] = -a2(i) * p_scsc[0] * p_scsc[2] + a2(i+n) * p_scsc[0] * p_scsc[3];\n\n        }\n    }\n\n    double re = arma::dot( arma_x, a2 );\n    countopt++;\n\n    acc_time+=(std::chrono::nanoseconds(Clock::now() - t1).count()/1e9);\n\n    //cout<<countopt++<<' '<<re<<endl;\n    return re;\n\n}\n\n\n\nint RBF_Core::Opt_Hermite_PredictNormal_UnitNormal(){\n\n\n    sol.solveval.resize(npt * 2);\n\n    for(int i=0;i<npt;++i){\n        double *veccc = initnormals.data()+i*3;\n        {\n            //MyUtility::normalize(veccc);\n            sol.solveval[i*2] = atan2(sqrt(veccc[0]*veccc[0]+veccc[1]*veccc[1]),veccc[2] );\n            sol.solveval[i*2 + 1] = atan2( veccc[1], veccc[0]   );\n        }\n\n    }\n    //cout<<\"smallvec: \"<<smallvec<<endl;\n\n    if(1){\n        vector<double>upper(npt*2);\n        vector<double>lower(npt*2);\n        for(int i=0;i<npt;++i){\n            upper[i*2] = 2 * my_PI;\n            upper[i*2 + 1] = 2 * my_PI;\n\n            lower[i*2] = -2 * my_PI;\n            lower[i*2 + 1] = -2 * my_PI;\n        }\n\n        countopt = 0;\n        acc_time = 0;\n\n        //LocalIterativeSolver(sol,kk==0?normals:newnormals,300,1e-7);\n        Solver::nloptwrapper(lower,upper,optfunc_Hermite,this,1e-7,3000,sol);\n        cout<<\"number of call: \"<<countopt<<\" t: \"<<acc_time<<\" ave: \"<<acc_time/countopt<<endl;\n        callfunc_time = acc_time;\n        solve_time = sol.time;\n        //for(int i=0;i<npt;++i)cout<< sol.solveval[i]<<' ';cout<<endl;\n\n    }\n    newnormals.resize(npt*3);\n    arma::vec y(npt*4);\n    for(int i=0;i<npt;++i)y(i) = 0;\n    for(int i=0;i<npt;++i){\n\n        double a = sol.solveval[i*2], b = sol.solveval[i*2+1];\n        newnormals[i*3]   = y(npt+i) = sin(a) * cos(b);\n        newnormals[i*3+1] = y(npt+i+npt) = sin(a) * sin(b);\n        newnormals[i*3+2] = y(npt+i+npt*2) = cos(a);\n        MyUtility::normalize(newnormals.data()+i*3);\n    }\n\n    Set_RBFCoef(y);\n\n    //sol.energy = arma::dot(a,M*a);\n    cout<<\"Opt_Hermite_PredictNormal_UnitNormal\"<<endl;\n    return 1;\n}\n\nvoid RBF_Core::Set_RBFCoef(arma::vec &y){\n    cout<<\"Set_RBFCoef\"<<endl;\n    if(curMethod==HandCraft){\n        cout<<\"HandCraft, not RBF\"<<endl;\n        return;\n    }\n    if(!isnewformula){\n        b = bprey * y;\n        a = Minv * (y - N*b);\n    }else{\n\n        if(User_Lamnbda>0)y.subvec(0,npt-1) = -User_Lamnbda*dI*K01*y.subvec(npt,npt*4-1);\n\n        a = Minv*y;\n        b = Ninv.t()*y;\n\n    }\n\n\n}\n\n\n\nint RBF_Core::Lamnbda_Search_GlobalEigen(){\n\n    vector<double>lamnbda_list({0, 0.001, 0.01, 0.1, 1});\n    //vector<double>lamnbda_list({  0.5,0.6,0.7,0.8,0.9,1,1.1,1.5,2,3});\n    //lamnbda_list.clear();\n    //for(double i=1.5;i<2.5;i+=0.1)lamnbda_list.push_back(i);\n    //vector<double>lamnbda_list({0});\n    vector<double>initen_list(lamnbda_list.size());\n    vector<double>finalen_list(lamnbda_list.size());\n    vector<vector<double>>init_normallist;\n    vector<vector<double>>opt_normallist;\n\n    lamnbda_list_sa = lamnbda_list;\n    for(int i=0;i<lamnbda_list.size();++i){\n\n        Set_HermiteApprox_Lamnda(lamnbda_list[i]);\n\n        if(curMethod==Hermite_UnitNormal){\n            Solve_Hermite_PredictNormal_UnitNorm();\n        }\n\n        //Solve_Hermite_PredictNormal_UnitNorm();\n        OptNormal(1);\n\n        initen_list[i] = sol.init_energy;\n        finalen_list[i] = sol.energy;\n\n        init_normallist.emplace_back(initnormals);\n        opt_normallist.emplace_back(newnormals);\n    }\n\n    lamnbdaGlobal_Be.emplace_back(initen_list);\n    lamnbdaGlobal_Ed.emplace_back(finalen_list);\n\n    cout<<std::setprecision(8);\n    for(int i=0;i<initen_list.size();++i){\n        cout<<lamnbda_list[i]<<\": \"<<initen_list[i]<<\" -> \"<<finalen_list[i]<<endl;\n    }\n\n    int minind = min_element(finalen_list.begin(),finalen_list.end()) - finalen_list.begin();\n    cout<<\"min energy: \"<<endl;\n    cout<<lamnbda_list[minind]<<\": \"<<initen_list[minind]<<\" -> \"<<finalen_list[minind]<<endl;\n\n\n    initnormals = init_normallist[minind];\n    SetInitnormal_Uninorm();\n    newnormals = opt_normallist[minind];\n\treturn 1;\n}\n\n\n\n\nvoid RBF_Core::Print_LamnbdaSearchTest(string fname){\n\n\n    cout<<setprecision(7);\n    cout<<\"Print_LamnbdaSearchTest\"<<endl;\n    for(int i=0;i<lamnbda_list_sa.size();++i)cout<<lamnbda_list_sa[i]<<' ';cout<<endl;\n    cout<<lamnbdaGlobal_Be.size()<<endl;\n    for(int i=0;i<lamnbdaGlobal_Be.size();++i){\n        for(int j=0;j<lamnbdaGlobal_Be[i].size();++j){\n            cout<<lamnbdaGlobal_Be[i][j]<<\"\\t\"<<lamnbdaGlobal_Ed[i][j]<<\"\\t\";\n        }\n        cout<<gtBe[i]<<\"\\t\"<<gtEd[i]<<endl;\n    }\n\n    ofstream fout(fname);\n    fout<<setprecision(7);\n    if(!fout.fail()){\n        for(int i=0;i<lamnbda_list_sa.size();++i)fout<<lamnbda_list_sa[i]<<' ';fout<<endl;\n        fout<<lamnbdaGlobal_Be.size()<<endl;\n        for(int i=0;i<lamnbdaGlobal_Be.size();++i){\n            for(int j=0;j<lamnbdaGlobal_Be[i].size();++j){\n                fout<<lamnbdaGlobal_Be[i][j]<<\"\\t\"<<lamnbdaGlobal_Ed[i][j]<<\"\\t\";\n            }\n            fout<<gtBe[i]<<\"\\t\"<<gtEd[i]<<endl;\n        }\n    }\n    fout.close();\n\n}\n\n\n", "meta": {"hexsha": "ff210feb7b30b23fa6cf141d9f445444be48901f", "size": 16298, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vipss/src/rbf_Hermite.cpp", "max_stars_repo_name": "jpanetta/VIPSS", "max_stars_repo_head_hexsha": "34491070a49047f8071f1670139ffe01d38598a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2019-05-18T05:22:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T15:40:11.000Z", "max_issues_repo_path": "vipss/src/rbf_Hermite.cpp", "max_issues_repo_name": "jpanetta/VIPSS", "max_issues_repo_head_hexsha": "34491070a49047f8071f1670139ffe01d38598a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-25T01:34:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-29T15:15:31.000Z", "max_forks_repo_path": "vipss/src/rbf_Hermite.cpp", "max_forks_repo_name": "jpanetta/VIPSS", "max_forks_repo_head_hexsha": "34491070a49047f8071f1670139ffe01d38598a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-05-18T05:22:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-19T11:50:58.000Z", "avg_line_length": 27.0281923715, "max_line_length": 130, "alphanum_fraction": 0.533746472, "num_tokens": 5549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2543645606876603}}
{"text": "#ifndef ODESOLVER_HPP_INCLUDED\n#define ODESOLVER_HPP_INCLUDED\n\n#include <petscts.h>\n#include <string>\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <assert.h>\n#include <boost/circular_buffer.hpp>\n#include \"integratorContextEx.hpp\"\n#include \"genFuncs.hpp\"\n\nusing namespace std;\n/*\n * Provides a set of algorithms to solve a system of ODEs of\n * the form y' = f(t,y) using EXPLICIT time stepping.\n *\n * SOLVER TYPE      ALGORITHM\n *  FEuler        forward Euler\n *  RK32          explicit Runge-Kutta (2,3)\n *  RK43          explicit Runge-Kutta (3,4)\n *\n * To obtain solutions at user-specified times, use FEuler and call setStepSize\n * in the routine f(t,y).\n *\n * y is represented as an array of one or more Vecs (PETSc data type).\n *\n * At minimum, the user must specify:\n *     QUANTITY               FUNCTION\n *  max number of steps      constructor\n *  solver type              constructor\n *  initial conditions       setInitialConds     Note: this array will be modified during integration\n *  initial step size        constructor\n *  step size alg            constructor (this is only used by the adaptive time-stepping algorithm)\n *  f(t,y)                   object passed to integrate must have member function d_dt(PetscScalar, PetscScalar*,PetscScalar*)\n *  final time               constructor and setTimeRange\n *  timeMonitor              object passed to integrate must have member function timeMonitor\n *\n *\n * Optional fields that can also be specified:\n *     QUANTITY               FUNCTION\n *  tolerance                setTolerance\n *  maximum step size        setStepSize\n *  minimum step size        setTimeStepBounds\n *  initial step size        setTimeStepBounds\n *\n * Once the odeSolver context is set, call integrate() to perform\n * the integration.\n *\n * y(t = final_time) is stored in the initial conditions array. Summary output\n * information is provided by viewSolver. Users can obtain information at\n * each time step within a user-defined monitor function.\n *\n */\n\nclass OdeSolver\n{\npublic:\n\n  PetscReal          _initT,_finalT,_currT,_deltaT;\n  PetscReal          _newDeltaT; // stores future deltaT for access by outside classes, primarily for checkpointing\n  PetscInt           _maxNumSteps,_stepCount;\n  map<string,Vec>    _var,_dvar; // integration variable and rate\n  vector<string>     _errInds; // which keys of _var to use for error control\n  vector<double>     _scale; // scale factor for entries in _errInds\n  double             _runTime;\n  string             _controlType;\n  string             _normType;\n\n  // for PID error control\n  boost::circular_buffer<double> _errA;\n  map<string,Vec> _y2,_y3,_y4;\n\n  OdeSolver(PetscInt maxNumSteps,PetscReal finalT,PetscReal deltaT,string controlType);\n  virtual ~OdeSolver() {};\n\n  PetscErrorCode setTimeRange(const PetscReal initT,const PetscReal finalT);\n  PetscErrorCode setInitialStepCount(const PetscReal stepCount);\n  PetscErrorCode setStepSize(const PetscReal deltaT);\n  PetscErrorCode setToleranceType(const string normType); // type of norm used for error control\n\n  virtual PetscErrorCode setTolerance(const PetscReal tol) = 0;\n  virtual PetscErrorCode setTimeStepBounds(const PetscReal minDeltaT, const PetscReal maxDeltaT) = 0;\n  virtual PetscErrorCode setInitialConds(map<string,Vec>& var){return 1;};\n  virtual PetscErrorCode setErrInds(vector<string>& errInds) = 0;\n  virtual PetscErrorCode setErrInds(vector<string>& errInds, vector<double> scale) = 0;\n  virtual PetscErrorCode view() = 0;\n  virtual PetscErrorCode integrate(IntegratorContextEx *obj) = 0;\n};\n\n\n// FEuler is a derived class from OdeSolver\nclass FEuler : public OdeSolver\n{\npublic:\n  FEuler(PetscInt maxNumSteps,PetscReal finalT,PetscReal deltaT,string controlType);\n  ~FEuler();\n  PetscErrorCode view();\n\n  PetscErrorCode setTolerance(const PetscReal tol){return 0;};\n  PetscErrorCode setTimeStepBounds(const PetscReal minDeltaT, const PetscReal maxDeltaT){ return 0;};\n  PetscErrorCode setInitialConds(map<string,Vec>& var);\n  PetscErrorCode setErrInds(vector<string>& errInds) {return 0;};\n  PetscErrorCode setErrInds(vector<string>& errInds, vector<double> scale) {return 0;};\n  PetscErrorCode integrate(IntegratorContextEx *obj);\n};\n\n\n// Runge-kutta time-stepping, 3rd-order\n// Based on algorithm from Hairer et al.\nclass RK32 : public OdeSolver\n{\npublic:\n\n  PetscReal   _minDeltaT,_maxDeltaT;\n  PetscReal   _totTol; // total tolerance, might be atol, or rtol, or a combination of both\n  PetscReal   _kappa,_ord; // safety factor in step size determinance, order of accuracy of method\n  PetscInt    _numRejectedSteps,_numMinSteps,_numMaxSteps;\n\n  PetscReal   _totErr;\n\n  map<string,Vec> _k1,_f1,_k2,_f2,_y2,_y3;\n\n  PetscReal computeStepSize(const PetscReal totErr);\n  PetscReal computeError();\n\n  // constructor and destructor\n  RK32(PetscInt maxNumSteps,PetscReal finalT,PetscReal deltaT,string controlType);\n  ~RK32();\n\n  // member functions of this class\n  PetscErrorCode setTolerance(const PetscReal tol);\n  PetscErrorCode setTimeStepBounds(const PetscReal minDeltaT, const PetscReal maxDeltaT);\n  PetscErrorCode setInitialConds(map<string,Vec>& var);\n  PetscErrorCode setErrInds(vector<string>& errInds);\n  PetscErrorCode setErrInds(vector<string>& errInds, vector<double> scale);\n  PetscErrorCode view();\n  PetscErrorCode integrate(IntegratorContextEx *obj);\n};\n\n\n// Based on \"ARK4(3)6L[2]SA-ERK\" algorithm from Kennedy and Carpenter (2003):\n// \"Additive Runge-Kutta schemes for convection-diffusion-reaction equations\"\n// Runge-Kutta time-stepping, 4th order\n// Note: Has matching IMEX equivalent\nclass RK43 : public OdeSolver\n{\npublic:\n\n  PetscReal   _minDeltaT,_maxDeltaT;\n  PetscReal   _atol,_rtol;\n  PetscReal   _totTol;\n  PetscReal   _kappa,_ord;\n  PetscInt    _numRejectedSteps,_numMinSteps,_numMaxSteps;\n  PetscReal   _totErr;\n\n  map<string,Vec> _k1,_k2,_k3,_k4,_k5,_k6,_y3,_y4;\n  map<string,Vec> _f1,_f2,_f3,_f4,_f5,_f6;\n\n  PetscReal computeStepSize(const PetscReal totErr);\n  PetscReal computeError();\n\n  // constructor and destructor\n  RK43(PetscInt maxNumSteps,PetscReal finalT,PetscReal deltaT,string controlType);\n  ~RK43();\n\n  // various member functions\n  PetscErrorCode setTolerance(const PetscReal tol);\n  PetscErrorCode setTimeStepBounds(const PetscReal minDeltaT, const PetscReal maxDeltaT);\n  PetscErrorCode setInitialConds(map<string,Vec>& var);\n  PetscErrorCode setErrInds(vector<string>& errInds);\n  PetscErrorCode setErrInds(vector<string>& errInds, vector<double> scale);\n  PetscErrorCode view();\n  PetscErrorCode integrate(IntegratorContextEx *obj);\n};\n\n#endif\n", "meta": {"hexsha": "e8eab2510cf3e916af93e6f1ac026ad0d9d82c61", "size": 6585, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "source/odeSolver.hpp", "max_stars_repo_name": "kali-allison/SCycle", "max_stars_repo_head_hexsha": "0a81edfae8730acb44531e2c2b3f51f25ea193d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-04-12T16:36:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:35:03.000Z", "max_issues_repo_path": "source/odeSolver.hpp", "max_issues_repo_name": "kali-allison/SCycle", "max_issues_repo_head_hexsha": "0a81edfae8730acb44531e2c2b3f51f25ea193d2", "max_issues_repo_licenses": ["MIT"], "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/odeSolver.hpp", "max_forks_repo_name": "kali-allison/SCycle", "max_forks_repo_head_hexsha": "0a81edfae8730acb44531e2c2b3f51f25ea193d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-07-22T23:53:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T03:30:50.000Z", "avg_line_length": 36.7877094972, "max_line_length": 126, "alphanum_fraction": 0.7380410023, "num_tokens": 1702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.25417941912038805}}
{"text": "/* -*- c++ -*- */\n/* \n * Copyright 2014 Communications Engineering Lab, KIT.\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 by\n * the Free Software Foundation; either version 3, or (at your option)\n * 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 <gnuradio/io_signature.h>\n#include <boost/circular_buffer.hpp>\n#include \"estimator_rcs_impl.h\"\n#include <numeric>\n\nnamespace gr {\n  namespace radar {\n\n    estimator_rcs::sptr\n    estimator_rcs::make(int num_mean, float center_freq, float antenna_gain_tx, float antenna_gain_rx, float usrp_gain_rx, float power_tx, float corr_factor, float exponent)\n    {\n      return gnuradio::get_initial_sptr\n        (new estimator_rcs_impl(num_mean, center_freq, antenna_gain_tx, antenna_gain_rx, usrp_gain_rx, power_tx, corr_factor, exponent));\n    }\n\n    /*\n     * The private constructor\n     */\n    estimator_rcs_impl::estimator_rcs_impl(int num_mean, float center_freq, float antenna_gain_tx, float antenna_gain_rx, float usrp_gain_rx, float power_tx, float corr_factor, float exponent)\n      : gr::block(\"estimator_rcs\",\n              gr::io_signature::make(0,0,0),\n              gr::io_signature::make(0,0,0))\n    {\n        d_num_mean = num_mean;\n        d_center_freq = center_freq;\n        d_antenna_gain_tx = antenna_gain_tx;\n        d_antenna_gain_rx = antenna_gain_rx;\n        d_usrp_gain_rx = usrp_gain_rx;\n        d_power_tx = power_tx; // needs to be calibrated for every usage\n        d_corr_factor = corr_factor;\n        d_exponent = exponent;\n\n        d_rcs_vals.resize(d_num_mean);\n\n        // Register input message port\n        d_port_id_in = pmt::mp(\"Msg in\");\n        message_port_register_in(d_port_id_in);\n        set_msg_handler(d_port_id_in, boost::bind(&estimator_rcs_impl::handle_msg, this, _1));\n        \n        // Register output message port\n        d_port_id_out = pmt::mp(\"Msg out\");\n        message_port_register_out(d_port_id_out);\n\n        d_loop_counter = 0;\n\n        // constant factors in radar equation\n        d_antenna_gain_abs_rx = pow(10, d_antenna_gain_rx/10);\n        d_antenna_gain_abs_tx = pow(10, d_antenna_gain_tx/10);\n        d_lambda = c_light/d_center_freq;\n        d_fak = pow(4.0*M_PI, 3) / (d_antenna_gain_abs_rx * d_antenna_gain_abs_tx * pow(d_lambda, 2));\n\n    }\n\n    /*\n     * Our virtual destructor.\n     */\n    estimator_rcs_impl::~estimator_rcs_impl()\n    {\n    }\n\n    void\n    estimator_rcs_impl::set_num_mean(int val){\n      d_num_mean = val;\n      d_rcs_vals.clear();\n      d_rcs_vals.resize(d_num_mean);\n      d_loop_counter = 0;\n    }\n\n    void\n    estimator_rcs_impl::set_center_freq(float val){\n      d_center_freq = val;\n      d_lambda = c_light/d_center_freq;\n      d_fak = pow(4.0*M_PI, 3) / (d_antenna_gain_abs_rx * d_antenna_gain_abs_tx * pow(d_lambda, 2));\n    }\n\n    void\n    estimator_rcs_impl::set_antenna_gain_tx(float val){\n      d_antenna_gain_tx = val;\n      d_antenna_gain_abs_tx = pow(10, d_antenna_gain_tx/10);\n      d_fak = pow(4.0*M_PI, 3) / (d_antenna_gain_abs_rx * d_antenna_gain_abs_tx * pow(d_lambda, 2));\n    }\n\n    void\n    estimator_rcs_impl::set_antenna_gain_rx(float val){\n      d_antenna_gain_rx = val;\n      d_antenna_gain_abs_rx = pow(10, d_antenna_gain_rx/10);\n      d_fak = pow(4.0*M_PI, 3) / (d_antenna_gain_abs_rx * d_antenna_gain_abs_tx * pow(d_lambda, 2));\n    }\n\n    void\n    estimator_rcs_impl::set_usrp_gain_rx(float val){\n      d_usrp_gain_rx = val;\n    }\n\n    void\n    estimator_rcs_impl::set_power_tx(float val){\n      d_power_tx = val;\n    }\n\n    void\n    estimator_rcs_impl::set_corr_factor(float val){\n      d_corr_factor = val;\n    }\n\n    float\n    estimator_rcs_impl::calculate_vector_mean(boost::circular_buffer<float>* rcs_vals) {\n      float sum_of_elems = 0;\n      for(int k=0; k<rcs_vals->size(); k++){\n        sum_of_elems += (*rcs_vals)[k];\n      }\n      return sum_of_elems/rcs_vals->size();\n    }\n\n    float\n    estimator_rcs_impl::calculate_rcs() {\n      // catch errors\n\t\t\tif(d_range.size() == 0) throw std::runtime_error(\"range vector has size zero\");\n\t\t\tif(d_power.size() == 0) throw std::runtime_error(\"power vector has size zero\");\n\n      // regard usrp gain and signal path\n\t\t\tfloat power_rx = pow(d_power[0], d_exponent) / d_power_tx / pow(10, d_usrp_gain_rx/10);\n\t\t\t\n\t\t\tfloat fak = d_fak * pow(d_range[0], 4);\n\n      // debug output\n      // std::cout << \"PowerTx: \" << d_power_tx << std::endl;\n      // std::cout << \"PowerRx: \" << power_rx << std::endl;\n      // std::cout << \"Lambda: \" << d_lambda << std::endl;\n      // std::cout << \"GainRx: \" << d_antenna_gain_rx << std::endl;\n      // std::cout << \"GainTx: \" << d_antenna_gain_tx << std::endl;\n      // std::cout << \"fak: \" << fak << std::endl;\n\n\t\t\treturn power_rx/d_power_tx * fak * d_corr_factor;\n    }\n\n    void\n    estimator_rcs_impl::handle_msg(pmt::pmt_t msg)\n    {\n        // Read msg from peak detector\n        d_msg_hold.clear();\n        pmt::pmt_t msg_part;\n        bool found_range = false;\n        bool found_power = false;\n        for(int k=0; k<pmt::length(msg); k++){\n          msg_part = pmt::nth(k,msg);\n          if(pmt::symbol_to_string(pmt::nth(0,msg_part))==\"range\"){\n            d_prange = pmt::nth(1,msg_part);\n            d_msg_hold.push_back(msg_part);\n            found_range = true;\n          }\n          else if(pmt::symbol_to_string(pmt::nth(0,msg_part))==\"power\"){\n            d_ppower = pmt::nth(1,msg_part);\n            found_power = true;\n          }\n          else{\n            d_msg_hold.push_back(msg_part);\n          }\n        }\n\n        if(not(found_range&&found_power)) throw std::runtime_error(\"range or power identifier (symbol) not found\");\n\n        d_range = pmt::f32vector_elements(d_prange);\n        d_power = pmt::f32vector_elements(d_ppower);\n        d_rcs.clear();\n\n        if(d_range.size()!=d_power.size()) throw std::runtime_error(\"range and power vectors do not have same size\");\n\n        // Calculate RCS\n        float rcs_mean = 0.0;\n        if(d_range.size() == 0 && d_power.size() == 0){\n          //std::cout << \"ERROR: No target detected for RCS calculation\" << std::endl;\n        }\n        else {\n          d_rcs_vals.push_back(calculate_rcs());\n        }\n        //std::cout << \"RCS_TEMP: \" << calculate_rcs() << std::endl;\n\n        if(d_loop_counter+1 >= d_num_mean) {\n            rcs_mean = calculate_vector_mean(&d_rcs_vals);\n        }\n        else {\n            d_loop_counter++;\n        }\n\n        for(int k=0; k<d_range.size(); k++){\n            d_rcs.push_back(rcs_mean);\n        }\n        \n        // Push pmt to output msg port\n        d_rcs_key = pmt::string_to_symbol(\"rcs\"); // identifier velocity\n        d_rcs_value = pmt::init_f32vector(d_rcs.size(), d_rcs); // vector to pmt\n        d_rcs_pack = pmt::list2(d_rcs_key, d_rcs_value); // make list for velocity information\n        \n        d_value = pmt::list1(d_rcs_pack);\n        for(int k=0; k<d_msg_hold.size(); k++){\n            d_value = pmt::list_add(d_value, d_msg_hold[k]);\n        }\n        \n        message_port_pub(d_port_id_out,d_value); // publish message\n    }\n\n  } /* namespace radar */\n} /* namespace gr */\n\n", "meta": {"hexsha": "45caeae6035601045cec478fca764fbba251360e", "size": 7683, "ext": "cc", "lang": "C++", "max_stars_repo_path": "WirelessMonitoringModule/gr-radar/lib/estimator_rcs_impl.cc", "max_stars_repo_name": "Aekai/Wi-Mind", "max_stars_repo_head_hexsha": "a02a2f4cd10fc362e6a17d3c67c2662c90b1a980", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-14T13:49:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-14T13:49:51.000Z", "max_issues_repo_path": "WirelessMonitoringModule/gr-radar/lib/estimator_rcs_impl.cc", "max_issues_repo_name": "Aekai/Wi-Mind", "max_issues_repo_head_hexsha": "a02a2f4cd10fc362e6a17d3c67c2662c90b1a980", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WirelessMonitoringModule/gr-radar/lib/estimator_rcs_impl.cc", "max_forks_repo_name": "Aekai/Wi-Mind", "max_forks_repo_head_hexsha": "a02a2f4cd10fc362e6a17d3c67c2662c90b1a980", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-18T08:39:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-18T08:39:58.000Z", "avg_line_length": 33.5502183406, "max_line_length": 192, "alphanum_fraction": 0.6312638292, "num_tokens": 2067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982043529716, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2541550940837896}}
{"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/indexes/iborindex.hpp>\n#include <ql/math/solvers1d/brent.hpp>\n#include <qle/pricingengines/analyticlgmswaptionengine.hpp>\n\n#include <boost/bind.hpp>\n\nnamespace QuantExt {\n\nAnalyticLgmSwaptionEngine::AnalyticLgmSwaptionEngine(const boost::shared_ptr<LinearGaussMarkovModel>& model,\n                                                     const Handle<YieldTermStructure>& discountCurve,\n                                                     const FloatSpreadMapping floatSpreadMapping)\n    : GenericEngine<Swaption::arguments, Swaption::results>(), p_(model->parametrization()),\n      c_(discountCurve.empty() ? p_->termStructure() : discountCurve), floatSpreadMapping_(floatSpreadMapping) {\n    registerWith(model);\n    registerWith(c_);\n}\n\nAnalyticLgmSwaptionEngine::AnalyticLgmSwaptionEngine(const boost::shared_ptr<CrossAssetModel>& model, const Size ccy,\n                                                     const Handle<YieldTermStructure>& discountCurve,\n                                                     const FloatSpreadMapping floatSpreadMapping)\n    : GenericEngine<Swaption::arguments, Swaption::results>(), p_(model->irlgm1f(ccy)),\n      c_(discountCurve.empty() ? p_->termStructure() : discountCurve), floatSpreadMapping_(floatSpreadMapping) {\n    registerWith(model);\n    registerWith(c_);\n}\n\nAnalyticLgmSwaptionEngine::AnalyticLgmSwaptionEngine(const boost::shared_ptr<IrLgm1fParametrization> irlgm1f,\n                                                     const Handle<YieldTermStructure>& discountCurve,\n                                                     const FloatSpreadMapping floatSpreadMapping)\n    : GenericEngine<Swaption::arguments, Swaption::results>(), p_(irlgm1f),\n      c_(discountCurve.empty() ? p_->termStructure() : discountCurve), floatSpreadMapping_(floatSpreadMapping) {\n    registerWith(c_);\n}\n\nvoid AnalyticLgmSwaptionEngine::calculate() const {\n\n    QL_REQUIRE(arguments_.settlementType == Settlement::Physical, \"cash-settled swaptions are not supported ...\");\n\n    Date reference = p_->termStructure()->referenceDate();\n\n    Date expiry = arguments_.exercise->dates().back();\n\n    if (expiry <= reference) {\n        // swaption is expired, possibly generated swap is not\n        // valued by this engine, so we set the npv to zero\n        results_.value = 0.0;\n        return;\n    }\n\n    VanillaSwap swap = *arguments_.swap;\n    Option::Type type = arguments_.type == VanillaSwap::Payer ? Option::Call : Option::Put;\n    Schedule fixedSchedule = swap.fixedSchedule();\n    Schedule floatSchedule = swap.floatingSchedule();\n\n    j1_ = std::lower_bound(fixedSchedule.dates().begin(), fixedSchedule.dates().end(), expiry) -\n          fixedSchedule.dates().begin();\n    k1_ = std::lower_bound(floatSchedule.dates().begin(), floatSchedule.dates().end(), expiry) -\n          floatSchedule.dates().begin();\n\n    // compute S_i, i.e. equivalent fixed rate spreads compensating for\n    // a) a possibly non-zero float spread and\n    // b) a spread between the ibor indices forwarding curve and the\n    //     discounting curve\n    // here, we do not work with a spread corrections directly, but\n    // with this multiplied by the nominal and accrual basis,\n    // so S_i is really an amount correction.\n\n    S_.resize(arguments_.fixedCoupons.size() - j1_);\n    for (Size i = 0; i < S_.size(); ++i) {\n        S_[i] = 0.0;\n    }\n    S_m1 = 0.0;\n    Size ratio = static_cast<Size>(\n        static_cast<Real>(arguments_.floatingCoupons.size()) / static_cast<Real>(arguments_.fixedCoupons.size()) + 0.5);\n    QL_REQUIRE(ratio >= 1, \"floating leg's payment frequency must be equal or \"\n                           \"higher than fixed leg's payment frequency in \"\n                           \"analytic lgm swaption engine\");\n\n    Size k = k1_;\n    boost::shared_ptr<IborIndex> flatIbor = swap.iborIndex()->clone(c_);\n    for (Size j = j1_; j < arguments_.fixedCoupons.size(); ++j) {\n        Real sum1 = 0.0, sum2 = 0.0;\n        for (Size rr = 0; rr < ratio && k < arguments_.floatingCoupons.size(); ++rr, ++k) {\n            Real amount = arguments_.floatingCoupons[k];\n            Real lambda1 = 0.0, lambda2 = 1.0;\n            if (floatSpreadMapping_ == proRata) {\n                // we do not use the exact pay dates but the ratio to determine\n                // the distance to the adjacent payment dates\n                lambda2 = static_cast<Real>(rr + 1) / static_cast<Real>(ratio);\n                lambda1 = 1.0 - lambda2;\n            }\n            if (amount != Null<Real>()) {\n                Real flatAmount = flatIbor->fixing(arguments_.floatingFixingDates[k]) *\n                                  arguments_.floatingAccrualTimes[k] * arguments_.nominal;\n                Real correction = (amount - flatAmount) * c_->discount(arguments_.floatingPayDates[k]);\n                sum1 += lambda1 * correction;\n                sum2 += lambda2 * correction;\n            } else {\n                // if no amount is given, we do not need a spread correction\n                // due to different forward / discounting curves since then\n                // no curve is attached to the swap's ibor index and so we\n                // assume a one curve setup;\n                // but we can still have a float spread that has to be converted\n                // into a fixed leg's payment\n                Real correction = arguments_.nominal * arguments_.floatingSpreads[k] *\n                                  arguments_.floatingAccrualTimes[k] * c_->discount(arguments_.floatingPayDates[k]);\n                sum1 += lambda1 * correction;\n                sum2 += lambda2 * correction;\n            }\n        }\n        if (j > j1_) {\n            S_[j - j1_ - 1] += sum1 / c_->discount(arguments_.fixedPayDates[j - 1]);\n        } else {\n            S_m1 += sum1 / c_->discount(arguments_.floatingResetDates[k1_]);\n        }\n        S_[j - j1_] += sum2 / c_->discount(arguments_.fixedPayDates[j]);\n    }\n\n    Real w = type == Option::Call ? -1.0 : 1.0;\n\n    // it is a requirement that H' does not change its sign,\n    // with u = -1.0 we handle the case H' < 0\n    Real u = p_->Hprime(0.0) > 0.0 ? 1.0 : -1.0;\n\n    // do the actual pricing\n\n    zetaex_ = p_->zeta(p_->termStructure()->timeFromReference(expiry));\n    H0_ = p_->H(p_->termStructure()->timeFromReference(arguments_.floatingResetDates[k1_]));\n    D0_ = c_->discount(arguments_.floatingResetDates[k1_]);\n    Hj_.resize(arguments_.fixedCoupons.size() - j1_);\n    Dj_.resize(arguments_.fixedCoupons.size() - j1_);\n    for (Size j = j1_; j < arguments_.fixedCoupons.size(); ++j) {\n        Hj_[j - j1_] = p_->H(p_->termStructure()->timeFromReference(arguments_.fixedPayDates[j]));\n        Dj_[j - j1_] = c_->discount(arguments_.fixedPayDates[j - j1_]);\n    }\n\n    Brent b;\n    Real yStar;\n    try {\n        yStar = b.solve(boost::bind(&AnalyticLgmSwaptionEngine::yStarHelper, this, _1), 1.0E-6, 0.0, 0.01);\n    } catch (const std::exception& e) {\n        QL_FAIL(\"AnalyticLgmSwaptionEngine, failed to compute yStar, \" << e.what());\n    }\n\n    CumulativeNormalDistribution N;\n    Real sqrt_zetaex = std::sqrt(zetaex_);\n    Real sum = 0.0;\n    for (Size j = j1_; j < arguments_.fixedCoupons.size(); ++j) {\n        sum += w * (arguments_.fixedCoupons[j] - S_[j - j1_]) * Dj_[j - j1_] *\n               N(u * w * (yStar + (Hj_[j - j1_] - H0_) * zetaex_) / sqrt_zetaex);\n    }\n    sum += -w * S_m1 * D0_ * N(u * w * yStar / sqrt_zetaex);\n    sum += w * (arguments_.nominal * Dj_.back() * N(u * w * (yStar + (Hj_.back() - H0_) * zetaex_) / sqrt_zetaex) -\n                arguments_.nominal * D0_ * N(u * w * yStar / sqrt_zetaex));\n    results_.value = sum;\n\n    results_.additionalResults[\"fixedAmountCorrectionSettlement\"] = S_m1;\n    results_.additionalResults[\"fixedAmountCorrections\"] = S_;\n\n} // calculate\n\nReal AnalyticLgmSwaptionEngine::yStarHelper(const Real y) const {\n    Real sum = 0.0;\n    for (Size j = j1_; j < arguments_.fixedCoupons.size(); ++j) {\n        sum += (arguments_.fixedCoupons[j] - S_[j - j1_]) * Dj_[j - j1_] *\n               std::exp(-(Hj_[j - j1_] - H0_) * y - 0.5 * (Hj_[j - j1_] - H0_) * (Hj_[j - j1_] - H0_) * zetaex_);\n    }\n    sum += -S_m1 * D0_;\n    sum += Dj_.back() * arguments_.nominal *\n           std::exp(-(Hj_.back() - H0_) * y - 0.5 * (Hj_.back() - H0_) * (Hj_.back() - H0_) * zetaex_);\n    sum -= D0_ * arguments_.nominal;\n    return sum;\n}\n\n} // namespace QuantExt\n", "meta": {"hexsha": "4c06c393eead2b68d37463c7df01cad60c96e909", "size": 9133, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/pricingengines/analyticlgmswaptionengine.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/pricingengines/analyticlgmswaptionengine.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/pricingengines/analyticlgmswaptionengine.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": 47.0773195876, "max_line_length": 120, "alphanum_fraction": 0.6208255776, "num_tokens": 2371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.25392306223906136}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n    This example shows how to train a CNN based object detector using dlib's \n    loss_mmod loss layer.  This loss layer implements the Max-Margin Object\n    Detection loss as described in the paper:\n        Max-Margin Object Detection by Davis E. King (http://arxiv.org/abs/1502.00046).\n    This is the same loss used by the popular SVM+HOG object detector in dlib\n    (see fhog_object_detector_ex.cpp) except here we replace the HOG features\n    with a CNN and train the entire detector end-to-end.  This allows us to make\n    much more powerful detectors.\n\n    It would be a good idea to become familiar with dlib's DNN tooling before reading this\n    example.  So you should read dnn_introduction_ex.cpp and dnn_introduction2_ex.cpp\n    before reading this example program.  You should also read the introductory DNN+MMOD\n    example dnn_mmod_ex.cpp as well before proceeding.\n    \n\n    This example is essentially a more complex version of dnn_mmod_ex.cpp.  In it we train\n    a detector that finds the rear ends of motor vehicles.  I will also discuss some\n    aspects of data preparation useful when training this kind of detector.  \n    \n*/\n\n\n#include <iostream>\n#include <dlib/dnn.h>\n#include <dlib/data_io.h>\n\nusing namespace std;\nusing namespace dlib;\n\n\n\ntemplate <long num_filters, typename SUBNET> using con5d = con<num_filters,5,5,2,2,SUBNET>;\ntemplate <long num_filters, typename SUBNET> using con5  = con<num_filters,5,5,1,1,SUBNET>;\ntemplate <typename SUBNET> using downsampler  = relu<bn_con<con5d<32, relu<bn_con<con5d<32, relu<bn_con<con5d<16,SUBNET>>>>>>>>>;\ntemplate <typename SUBNET> using rcon5  = relu<bn_con<con5<55,SUBNET>>>;\nusing net_type = loss_mmod<con<1,9,9,1,1,rcon5<rcon5<rcon5<downsampler<input_rgb_image_pyramid<pyramid_down<6>>>>>>>>;\n\n\n// ----------------------------------------------------------------------------------------\n\nint ignore_overlapped_boxes(\n    std::vector<mmod_rect>& boxes,\n    const test_box_overlap& overlaps\n)\n/*!\n    ensures\n        - Whenever two rectangles in boxes overlap, according to overlaps(), we set the\n          smallest box to ignore.\n        - returns the number of newly ignored boxes.\n!*/\n{\n    int num_ignored = 0;\n    for (size_t i = 0; i < boxes.size(); ++i)\n    {\n        if (boxes[i].ignore)\n            continue;\n        for (size_t j = i+1; j < boxes.size(); ++j)\n        {\n            if (boxes[j].ignore)\n                continue;\n            if (overlaps(boxes[i], boxes[j]))\n            {\n                ++num_ignored;\n                if(boxes[i].rect.area() < boxes[j].rect.area())\n                    boxes[i].ignore = true;\n                else\n                    boxes[j].ignore = true;\n            }\n        }\n    }\n    return num_ignored;\n}\n\n// ----------------------------------------------------------------------------------------\n\nint main(int argc, char** argv) try\n{\n    if (argc != 2)\n    {\n        cout << \"Give the path to a folder containing training.xml and testing.xml files.\" << endl;\n        cout << \"This example program is specifically designed to run on the dlib vehicle \" << endl;\n        cout << \"detection dataset, which is available at this URL: \" << endl;\n        cout << \"   http://dlib.net/files/data/dlib_rear_end_vehicles_v1.tar\" << endl;\n        cout << endl;\n        cout << \"So download that dataset, extract it somewhere, and then run this program\" << endl;\n        cout << \"with the dlib_rear_end_vehicles folder as an argument.  E.g. if you extract\" << endl;\n        cout << \"the dataset to the current folder then you should run this example program\" << endl;\n        cout << \"by typing: \" << endl;\n        cout << \"   ./dnn_mmod_train_find_cars_ex dlib_rear_end_vehicles\" << endl;\n        cout << endl;\n        cout << \"It takes about a day to finish if run on a high end GPU like a 1080ti.\" << endl;\n        cout << endl;\n        return 0;\n    }\n    const std::string data_directory = argv[1];\n\n\n    std::vector<matrix<rgb_pixel>> images_train, images_test;\n    std::vector<std::vector<mmod_rect>> boxes_train, boxes_test;\n    load_image_dataset(images_train, boxes_train, data_directory+\"/training.xml\");\n    load_image_dataset(images_test,  boxes_test,  data_directory+\"/testing.xml\");\n\n    // When I was creating the dlib vehicle detection dataset I had to label all the cars\n    // in each image.  MMOD requires all cars to be labeled, since any unlabeled part of an\n    // image is implicitly assumed to be not a car, and the algorithm will use it as\n    // negative training data.  So every car must be labeled, either with a normal\n    // rectangle or an \"ignore\" rectangle that tells MMOD to simply ignore it (i.e. neither\n    // treat it as a thing to detect nor as negative training data).  \n    // \n    // In our present case, many images contain very tiny cars in the distance, ones that\n    // are essentially just dark smudges.  It's not reasonable to expect the CNN\n    // architecture we defined to detect such vehicles.  However, I erred on the side of\n    // having more complete annotations when creating the dataset.  So when I labeled these\n    // images I labeled many of these really difficult cases as vehicles to detect.   \n    //\n    // So the first thing we are going to do is clean up our dataset a little bit.  In\n    // particular, we are going to mark boxes smaller than 35*35 pixels as ignore since\n    // only really small and blurry cars appear at those sizes.  We will also mark boxes\n    // that are heavily overlapped by another box as ignore.  We do this because we want to\n    // allow for stronger non-maximum suppression logic in the learned detector, since that\n    // will help make it easier to learn a good detector. \n    // \n    // To explain this non-max suppression idea further it's important to understand how\n    // the detector works.  Essentially, sliding window detectors scan all image locations\n    // and ask \"is there a care here?\".  If there really is a car in a specific location in\n    // an image then usually many slightly different sliding window locations will produce\n    // high detection scores, indicating that there is a car at those locations.  If we\n    // just stopped there then each car would produce multiple detections.  But that isn't\n    // what we want.  We want each car to produce just one detection.  So it's common for\n    // detectors to include \"non-maximum suppression\" logic which simply takes the\n    // strongest detection and then deletes all detections \"close to\" the strongest.  This\n    // is a simple post-processing step that can eliminate duplicate detections.  However,\n    // we have to define what \"close to\" means.  We can do this by looking at your training\n    // data and checking how close the closest target boxes are to each other, and then\n    // picking a \"close to\" measure that doesn't suppress those target boxes but is\n    // otherwise as tight as possible.  This is exactly what the mmod_options object does\n    // by default.\n    //\n    // Importantly, this means that if your training dataset contains an image with two\n    // target boxes that really overlap a whole lot, then the non-maximum suppression\n    // \"close to\" measure will be configured to allow detections to really overlap a whole\n    // lot.  On the other hand, if your dataset didn't contain any overlapped boxes at all,\n    // then the non-max suppression logic would be configured to filter out any boxes that\n    // overlapped at all, and thus would be performing a much stronger non-max suppression.  \n    //\n    // Why does this matter?  Well, remember that we want to avoid duplicate detections.\n    // If non-max suppression just kills everything in a really wide area around a car then\n    // the CNN doesn't really need to learn anything about avoiding duplicate detections.\n    // However, if non-max suppression only suppresses a tiny area around each detection\n    // then the CNN will need to learn to output small detection scores for those areas of\n    // the image not suppressed.  The smaller the non-max suppression region the more the\n    // CNN has to learn and the more difficult the learning problem will become.  This is\n    // why we remove highly overlapped objects from the training dataset.  That is, we do\n    // it so the non-max suppression logic will be able to be reasonably effective.  Here\n    // we are ensuring that any boxes that are entirely contained by another are\n    // suppressed.  We also ensure that boxes with an intersection over union of 0.5 or\n    // greater are suppressed.  This will improve the resulting detector since it will be\n    // able to use more aggressive non-max suppression settings.\n\n    int num_overlapped_ignored_test = 0;\n    for (auto& v : boxes_test)\n        num_overlapped_ignored_test += ignore_overlapped_boxes(v, test_box_overlap(0.50, 0.95));\n\n    int num_overlapped_ignored = 0;\n    int num_additional_ignored = 0;\n    for (auto& v : boxes_train)\n    {\n        num_overlapped_ignored += ignore_overlapped_boxes(v, test_box_overlap(0.50, 0.95));\n        for (auto& bb : v)\n        {\n            if (bb.rect.width() < 35 && bb.rect.height() < 35)\n            {\n                if (!bb.ignore)\n                {\n                    bb.ignore = true;\n                    ++num_additional_ignored;\n                }\n            }\n\n            // The dlib vehicle detection dataset doesn't contain any detections with\n            // really extreme aspect ratios.  However, some datasets do, often because of\n            // bad labeling.  So it's a good idea to check for that and either eliminate\n            // those boxes or set them to ignore.  Although, this depends on your\n            // application.  \n            // \n            // For instance, if your dataset has boxes with an aspect ratio\n            // of 10 then you should think about what that means for the network\n            // architecture.  Does the receptive field even cover the entirety of the box\n            // in those cases?  Do you care about these boxes?  Are they labeling errors?\n            // I find that many people will download some dataset from the internet and\n            // just take it as given.  They run it through some training algorithm and take\n            // the dataset as unchallengeable truth.  But many datasets are full of\n            // labeling errors.  There are also a lot of datasets that aren't full of\n            // errors, but are annotated in a sloppy and inconsistent way.  Fixing those\n            // errors and inconsistencies can often greatly improve models trained from\n            // such data.  It's almost always worth the time to try and improve your\n            // training dataset.   \n            //\n            // In any case, my point is that there are other types of dataset cleaning you\n            // could put here.  What exactly you need depends on your application.  But you\n            // should carefully consider it and not take your dataset as a given.  The work\n            // of creating a good detector is largely about creating a high quality\n            // training dataset.  \n        }\n    }\n\n    // When modifying a dataset like this, it's a really good idea to print a log of how\n    // many boxes you ignored.  It's easy to accidentally ignore a huge block of data, so\n    // you should always look and see that things are doing what you expect.\n    cout << \"num_overlapped_ignored: \"<< num_overlapped_ignored << endl;\n    cout << \"num_additional_ignored: \"<< num_additional_ignored << endl;\n    cout << \"num_overlapped_ignored_test: \"<< num_overlapped_ignored_test << endl;\n\n\n    cout << \"num training images: \" << images_train.size() << endl;\n    cout << \"num testing images: \" << images_test.size() << endl;\n\n\n    // Our vehicle detection dataset has basically 3 different types of boxes.  Square\n    // boxes, tall and skinny boxes (e.g. semi trucks), and short and wide boxes (e.g.\n    // sedans).  Here we are telling the MMOD algorithm that a vehicle is recognizable as\n    // long as the longest box side is at least 70 pixels long and the shortest box side is\n    // at least 30 pixels long.  mmod_options will use these parameters to decide how large\n    // each of the sliding windows needs to be so as to be able to detect all the vehicles.\n    // Since our dataset has basically these 3 different aspect ratios, it will decide to\n    // use 3 different sliding windows.  This means the final con layer in the network will\n    // have 3 filters, one for each of these aspect ratios. \n    //\n    // Another thing to consider when setting the sliding window size is the \"stride\" of\n    // your network.  The network we defined above downsamples the image by a factor of 8x\n    // in the first few layers.  So when the sliding windows are scanning the image, they\n    // are stepping over it with a stride of 8 pixels.  If you set the sliding window size\n    // too small then the stride will become an issue.  For instance, if you set the\n    // sliding window size to 4 pixels, then it means a 4x4 window will be moved by 8\n    // pixels at a time when scanning. This is obviously a problem since 75% of the image\n    // won't even be visited by the sliding window.  So you need to set the window size to\n    // be big enough relative to the stride of your network.  In our case, the windows are\n    // at least 30 pixels in length, so being moved by 8 pixel steps is fine. \n    mmod_options options(boxes_train, 70, 30);\n\n\n    // This setting is very important and dataset specific.  The vehicle detection dataset\n    // contains boxes that are marked as \"ignore\", as we discussed above.  Some of them are\n    // ignored because we set ignore to true in the above code.  However, the xml files\n    // also contained a lot of ignore boxes.  Some of them are large boxes that encompass\n    // large parts of an image and the intention is to have everything inside those boxes\n    // be ignored.  Therefore, we need to tell the MMOD algorithm to do that, which we do\n    // by setting options.overlaps_ignore appropriately.  \n    // \n    // But first, we need to understand exactly what this option does.  The MMOD loss\n    // is essentially counting the number of false alarms + missed detections produced by\n    // the detector for each image.  During training, the code is running the detector on\n    // each image in a mini-batch and looking at its output and counting the number of\n    // mistakes.  The optimizer tries to find parameters settings that minimize the number\n    // of detector mistakes.\n    // \n    // This overlaps_ignore option allows you to tell the loss that some outputs from the\n    // detector should be totally ignored, as if they never happened.  In particular, if a\n    // detection overlaps a box in the training data with ignore==true then that detection\n    // is ignored.  This overlap is determined by calling\n    // options.overlaps_ignore(the_detection, the_ignored_training_box).  If it returns\n    // true then that detection is ignored.\n    // \n    // You should read the documentation for test_box_overlap, the class type for\n    // overlaps_ignore for full details.  However, the gist is that the default behavior is\n    // to only consider boxes as overlapping if their intersection over union is > 0.5.\n    // However, the dlib vehicle detection dataset contains large boxes that are meant to\n    // mask out large areas of an image.  So intersection over union isn't an appropriate\n    // way to measure \"overlaps with box\" in this case.  We want any box that is contained\n    // inside one of these big regions to be ignored, even if the detection box is really\n    // small.  So we set overlaps_ignore to behave that way with this line.\n    options.overlaps_ignore = test_box_overlap(0.5, 0.95);\n\n    net_type net(options);\n\n    // The final layer of the network must be a con layer that contains \n    // options.detector_windows.size() filters.  This is because these final filters are\n    // what perform the final \"sliding window\" detection in the network.  For the dlib\n    // vehicle dataset, there will be 3 sliding window detectors, so we will be setting\n    // num_filters to 3 here.\n    net.subnet().layer_details().set_num_filters(options.detector_windows.size());\n\n\n    dnn_trainer<net_type> trainer(net,sgd(0.0001,0.9));\n    trainer.set_learning_rate(0.1);\n    trainer.be_verbose();\n\n\n    // While training, we are going to use early stopping.  That is, we will be checking\n    // how good the detector is performing on our test data and when it stops getting\n    // better on the test data we will drop the learning rate.  We will keep doing that\n    // until the learning rate is less than 1e-4.   These two settings tell the trainer to\n    // do that.  Essentially, we are setting the first argument to infinity, and only the\n    // test iterations without progress threshold will matter.  In particular, it says that\n    // once we observe 1000 testing mini-batches where the test loss clearly isn't\n    // decreasing we will lower the learning rate.\n    trainer.set_iterations_without_progress_threshold(50000);\n    trainer.set_test_iterations_without_progress_threshold(1000);\n\n    const string sync_filename = \"mmod_cars_sync\";\n    trainer.set_synchronization_file(sync_filename, std::chrono::minutes(5));\n\n\n\n\n    std::vector<matrix<rgb_pixel>> mini_batch_samples;\n    std::vector<std::vector<mmod_rect>> mini_batch_labels; \n    random_cropper cropper;\n    cropper.set_seed(time(0));\n    cropper.set_chip_dims(350, 350);\n    // Usually you want to give the cropper whatever min sizes you passed to the\n    // mmod_options constructor, or very slightly smaller sizes, which is what we do here.\n    cropper.set_min_object_size(69,28); \n    cropper.set_max_rotation_degrees(2);\n    dlib::rand rnd;\n\n    // Log the training parameters to the console\n    cout << trainer << cropper << endl;\n\n    int cnt = 1;\n    // Run the trainer until the learning rate gets small.  \n    while(trainer.get_learning_rate() >= 1e-4)\n    {\n        // Every 30 mini-batches we do a testing mini-batch.  \n        if (cnt%30 != 0 || images_test.size() == 0)\n        {\n            cropper(87, images_train, boxes_train, mini_batch_samples, mini_batch_labels);\n            // We can also randomly jitter the colors and that often helps a detector\n            // generalize better to new images.\n            for (auto&& img : mini_batch_samples)\n                disturb_colors(img, rnd);\n\n            // It's a good idea to, at least once, put code here that displays the images\n            // and boxes the random cropper is generating.  You should look at them and\n            // think about if the output makes sense for your problem.  Most of the time\n            // it will be fine, but sometimes you will realize that the pattern of cropping\n            // isn't really appropriate for your problem and you will need to make some\n            // change to how the mini-batches are being generated.  Maybe you will tweak\n            // some of the cropper's settings, or write your own entirely separate code to\n            // create mini-batches.  But either way, if you don't look you will never know.\n            // An easy way to do this is to create a dlib::image_window to display the\n            // images and boxes.\n\n            trainer.train_one_step(mini_batch_samples, mini_batch_labels);\n        }\n        else\n        {\n            cropper(87, images_test, boxes_test, mini_batch_samples, mini_batch_labels);\n            // We can also randomly jitter the colors and that often helps a detector\n            // generalize better to new images.\n            for (auto&& img : mini_batch_samples)\n                disturb_colors(img, rnd);\n\n            trainer.test_one_step(mini_batch_samples, mini_batch_labels);\n        }\n        ++cnt;\n    }\n    // wait for training threads to stop\n    trainer.get_net();\n    cout << \"done training\" << endl;\n\n    // Save the network to disk\n    net.clean();\n    serialize(\"mmod_rear_end_vehicle_detector.dat\") << net;\n\n\n    // It's a really good idea to print the training parameters.  This is because you will\n    // invariably be running multiple rounds of training and should be logging the output\n    // to a file.  This print statement will include many of the training parameters in\n    // your log.\n    cout << trainer << cropper << endl;\n\n    cout << \"\\nsync_filename: \" << sync_filename << endl;\n    cout << \"num training images: \"<< images_train.size() << endl;\n    cout << \"training results: \" << test_object_detection_function(net, images_train, boxes_train, test_box_overlap(), 0, options.overlaps_ignore);\n    // Upsampling the data will allow the detector to find smaller cars.  Recall that \n    // we configured it to use a sliding window nominally 70 pixels in size.  So upsampling\n    // here will let it find things nominally 35 pixels in size.  Although we include a\n    // limit of 1800*1800 here which means \"don't upsample an image if it's already larger\n    // than 1800*1800\".  We do this so we don't run out of RAM, which is a concern because\n    // some of the images in the dlib vehicle dataset are really high resolution.\n    upsample_image_dataset<pyramid_down<2>>(images_train, boxes_train, 1800*1800);\n    cout << \"training upsampled results: \" << test_object_detection_function(net, images_train, boxes_train, test_box_overlap(), 0, options.overlaps_ignore);\n\n\n    cout << \"num testing images: \"<< images_test.size() << endl;\n    cout << \"testing results: \" << test_object_detection_function(net, images_test, boxes_test, test_box_overlap(), 0, options.overlaps_ignore);\n    upsample_image_dataset<pyramid_down<2>>(images_test, boxes_test, 1800*1800);\n    cout << \"testing upsampled results: \" << test_object_detection_function(net, images_test, boxes_test, test_box_overlap(), 0, options.overlaps_ignore);\n\n    /*\n        This program takes many hours to execute on a high end GPU.  It took about a day to\n        train on a NVIDIA 1080ti.  The resulting model file is available at\n            http://dlib.net/files/mmod_rear_end_vehicle_detector.dat.bz2\n        It should be noted that this file on dlib.net has a dlib::shape_predictor appended\n        onto the end of it (see dnn_mmod_find_cars_ex.cpp for an example of its use).  This\n        explains why the model file on dlib.net is larger than the\n        mmod_rear_end_vehicle_detector.dat output by this program.\n\n        You can see some videos of this vehicle detector running on YouTube:\n            https://www.youtube.com/watch?v=4B3bzmxMAZU\n            https://www.youtube.com/watch?v=bP2SUo5vSlc\n\n        Also, the training and testing accuracies were:\n            num training images: 2217\n            training results: 0.990738 0.736431 0.736073 \n            training upsampled results: 0.986837 0.937694 0.936912 \n            num testing images: 135\n            testing results: 0.988827 0.471372 0.470806 \n            testing upsampled results: 0.987879 0.651132 0.650399 \n    */\n\n    return 0;\n\n}\ncatch(std::exception& e)\n{\n    cout << e.what() << endl;\n}\n\n\n\n\n", "meta": {"hexsha": "16419477ab6fb71f73ea09a7473e3a2535f8905d", "size": 23188, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/dnn_mmod_train_find_cars_ex.cpp", "max_stars_repo_name": "andriy-gerasika/dlib", "max_stars_repo_head_hexsha": "f750268801c43538af337c8ee63f0d0569ad2ee4", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-21T15:36:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-21T15:36:32.000Z", "max_issues_repo_path": "examples/dnn_mmod_train_find_cars_ex.cpp", "max_issues_repo_name": "andriy-gerasika/dlib", "max_issues_repo_head_hexsha": "f750268801c43538af337c8ee63f0d0569ad2ee4", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/dnn_mmod_train_find_cars_ex.cpp", "max_forks_repo_name": "andriy-gerasika/dlib", "max_forks_repo_head_hexsha": "f750268801c43538af337c8ee63f0d0569ad2ee4", "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": 54.4319248826, "max_line_length": 157, "alphanum_fraction": 0.6817319303, "num_tokens": 5416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.25392142869728274}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2021.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef FCPPT_MAKE_LITERAL_BOOST_UNITS_HPP_INCLUDED\n#define FCPPT_MAKE_LITERAL_BOOST_UNITS_HPP_INCLUDED\n\n#include <fcppt/check_literal_conversion.hpp>\n#include <fcppt/make_literal_fwd.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/units/dimensionless_type.hpp>\n#include <boost/units/quantity.hpp>\n#include <boost/units/unit.hpp>\n#include <fcppt/config/external_end.hpp>\n\nnamespace fcppt\n{\n/**\n\\brief Literal specialization for boost.units\n\n\\ingroup fcpptboost\n*/\ntemplate <typename Unit, typename Type>\nstruct make_literal<boost::units::quantity<Unit, Type>>\n{\n  using decorated_type = boost::units::quantity<\n      boost::units::unit<boost::units::dimensionless_type, typename Unit::system_type>,\n      Type>;\n\n  template <typename Fundamental>\n  static decorated_type get(Fundamental const _fundamental)\n  {\n    FCPPT_CHECK_LITERAL_CONVERSION(Type, Fundamental);\n\n    return decorated_type::from_value(static_cast<Type>(_fundamental));\n  }\n};\n\n}\n\n#endif\n", "meta": {"hexsha": "1acc18b7c3c705c62861d33c39c3f373f41e1c2f", "size": 1194, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/boost/include/fcppt/make_literal_boost_units.hpp", "max_stars_repo_name": "freundlich/fcppt", "max_stars_repo_head_hexsha": "17df1b1ad08bf2435f6902d5465e3bc3fe5e3022", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2015-02-21T18:35:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-29T14:08:29.000Z", "max_issues_repo_path": "libs/boost/include/fcppt/make_literal_boost_units.hpp", "max_issues_repo_name": "cpreh/fcppt", "max_issues_repo_head_hexsha": "17df1b1ad08bf2435f6902d5465e3bc3fe5e3022", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-08-27T07:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-21T10:55:34.000Z", "max_forks_repo_path": "libs/boost/include/fcppt/make_literal_boost_units.hpp", "max_forks_repo_name": "freundlich/fcppt", "max_forks_repo_head_hexsha": "17df1b1ad08bf2435f6902d5465e3bc3fe5e3022", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-01-10T09:22:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-01T08:31:12.000Z", "avg_line_length": 27.7674418605, "max_line_length": 87, "alphanum_fraction": 0.7638190955, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.25392142869728274}}
{"text": "#ifndef STAN_MATH_TORSTEN_SOLVE_ODE_HPP\n#define STAN_MATH_TORSTEN_SOLVE_ODE_HPP\n\n#include <Eigen/Dense>\n#include <stan/math/torsten/to_array_2d.hpp>\n#include <stan/math/torsten/ev_manager.hpp>\n#include <stan/math/torsten/pmx_population_check.hpp>\n#include <stan/math/torsten/ev_solver.hpp>\n#include <stan/math/torsten/pmx_ode_model.hpp>\n#include <stan/math/torsten/pmx_check.hpp>\n#include <vector>\n\nnamespace torsten {\n/**\n * simpily pmx function declare\n * \n */\n#define TORSTEN_PMX_FUNC_EVENTS_ARGS 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\n  template<typename integrator_type>\n  struct PMXSolveODE {\n    \n    /// default tolerances & max steps for\n    /// differential eq(DE) and algebra solver(AS)\n    static constexpr double RTOL_DE = 1.e-6;\n    static constexpr double ATOL_DE = 1.e-6;\n    static constexpr int MAXSTEP_DE = 1e6;\n    static constexpr double RTOL_AS = 1.e-6;\n    static constexpr double ATOL_AS = 1.e-6;\n    static constexpr int MAXSTEP_AS = 1e2;\n\n    /**\n     * Computes the predicted amounts in each compartment at each event\n     * for a general compartment model, defined by a system of ordinary\n     * differential equations. \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 that defines \n     *            compartment model.\n     * @param[in] nCmt number of compartments in model\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     * @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     * @param[in] as_rel_tol relative tolerance for the algebra solver\n     * @param[in] as_abs_tol absolute tolerance for the algebra solver\n     * @param[in] as_max_num_steps maximal number of steps to take within \n     *            the algebra solver\n     * @return a matrix with predicted amount in each compartment \n     *         at each event. \n     *\n     * FIX ME: currently have a dummy msgs argument. Makes it easier\n     * to expose to stan grammar files, because I can follow more closely\n     * what was done for the ODE integrator. Not ideal.\n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename T5, typename T6, typename F>\n    static stan::matrix_return_t<T0, T1, T2, T3, T4, T5, T6>\n    solve(const F& f,\n          const int nCmt,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\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          double rel_tol,\n          double abs_tol,\n          long int max_num_steps,\n          double as_rel_tol,\n          double as_abs_tol,\n          long int as_max_num_steps,\n          std::ostream* msgs) {\n      using std::vector;\n      using Eigen::Dynamic;\n      using Eigen::Matrix;\n\n      // check arguments\n      static const char* function(\"PMX SOLVE ODE\");\n      torsten::pmx_check(time, amt, rate, ii, evid, cmt, addl, ss, pMatrix, function);\n      torsten::pmx_check(time.size(), nCmt, biovar, tlag);\n\n      using ER = NONMENEventsRecord<T0, T1, T2, T3>;\n      using EM = EventsManager<ER, NonEventParameters<T0, T4, std::vector, std::tuple<T5, T6> >>;\n      const ER events_rec(nCmt, time, amt, rate, ii, evid, cmt, addl, ss);\n\n      Matrix<typename EM::T_scalar, -1, -1> pred(EM::nCmt(events_rec), events_rec.num_event_times());\n\n      using model_type = torsten::PKODEModel<typename EM::T_par, F>;\n\n      integrator_type integrator(rel_tol, abs_tol, max_num_steps, as_rel_tol, as_abs_tol, as_max_num_steps, msgs);\n      EventSolver<model_type, EM> pr;\n\n      pr.pred(0, events_rec, pred, integrator, pMatrix, biovar, tlag, nCmt, f);\n      return pred;\n    }\n\n    /*\n     * Overload with default ODE & algebra solver controls \n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename T5, typename T6, typename F>\n    static stan::matrix_return_t<T0, T1, T2, T3, T4, T5, T6>\n    solve(const F& f,\n               const int nCmt,\n               TORSTEN_PMX_FUNC_EVENTS_ARGS,\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               std::ostream* msgs) {\n      return solve(f, nCmt,\n                   time, amt, rate, ii, evid, cmt, addl, ss,\n                   pMatrix, biovar, tlag,\n                   RTOL_DE, ATOL_DE, MAXSTEP_DE,\n                   RTOL_AS, ATOL_AS, MAXSTEP_AS,\n                   msgs);\n    }\n\n    /*\n     * Overload with default algebra solver controls \n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename T5, typename T6, typename F>\n    static stan::matrix_return_t<T0, T1, T2, T3, T4, T5, T6>\n    solve(const F& f,\n               const int nCmt,\n               TORSTEN_PMX_FUNC_EVENTS_ARGS,\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               double rel_tol,\n               double abs_tol,\n               long int max_num_steps,\n               std::ostream* msgs) {\n      return solve(f, nCmt,\n                   time, amt, rate, ii, evid, cmt, addl, ss,\n                   pMatrix, biovar, tlag,\n                   rel_tol, abs_tol, max_num_steps,\n                   RTOL_AS, ATOL_AS, MAXSTEP_AS,\n                   msgs);\n    }\n\n    /**\n     * Overload function to allow user to pass an std::vector for \n     * pMatrix/bioavailability/tlag\n     */\n    template <typename T0, typename T1, typename T2, typename T3,\n              typename T_par, typename T_biovar, typename T_tlag,\n              typename F,\n              typename... Ts,\n              typename = require_any_not_std_vector_t<T_par, T_biovar, T_tlag>,\n              typename = require_all_not_std_vector_t<Ts...> >\n    static stan::matrix_return_t<T0, T1, T2, T3, T_par, T_biovar, T_tlag>\n    solve(const F& f,\n          const int nCmt,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\n          const std::vector<T_par>& pMatrix,\n          const std::vector<T_biovar>& biovar,\n          const std::vector<T_tlag>& tlag,\n          Ts... solver_ctrl) {\n      return solve(f, nCmt,\n                   time, amt, rate, ii, evid, cmt, addl, ss,\n                   torsten::to_array_2d(pMatrix),\n                   torsten::to_array_2d(biovar),\n                   torsten::to_array_2d(tlag),\n                   solver_ctrl...);\n    }\n\n    /** \n     * Overload: omitting lag time, with full tolerance spec\n     * \n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename T5, typename F>\n    static stan::matrix_return_t<T0, T1, T2, T3, T4, T5>\n    solve(const F& f,\n               const int nCmt,\n               TORSTEN_PMX_FUNC_EVENTS_ARGS,\n               const std::vector<std::vector<T4> >& pMatrix,\n               const std::vector<std::vector<T5> >& biovar,\n               double rel_tol,\n               double abs_tol,\n               long int max_num_steps,\n               double as_rel_tol,\n               double as_abs_tol,\n               long int as_max_num_steps,\n               std::ostream* msgs) {\n      static const char* function(\"solve\");\n      torsten::pmx_check(time, amt, rate, ii, evid, cmt, addl, ss, pMatrix, function);\n      torsten::pmx_check(time.size(), nCmt, biovar);\n\n      using ER = NONMENEventsRecord<T0, T1, T2, T3>;\n      using EM = EventsManager<ER, NonEventParameters<T0, T4, std::vector, std::tuple<T5>>>;\n      const ER events_rec(nCmt, time, amt, rate, ii, evid, cmt, addl, ss);\n\n      Matrix<typename EM::T_scalar, -1, -1> pred(EM::nCmt(events_rec), events_rec.num_event_times());\n\n      using model_type = torsten::PKODEModel<typename EM::T_par, F>;\n\n      integrator_type integrator(rel_tol, abs_tol, max_num_steps, as_rel_tol, as_abs_tol, as_max_num_steps, msgs);\n      EventSolver<model_type, EM> pr;\n\n      pr.pred(0, events_rec, pred, integrator, pMatrix, biovar, nCmt, f);\n      return pred;\n    }\n\n    /** \n     * Overload: omitting lag time, with default ode & algebra solver spec\n     * \n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename T5, typename F>\n    static stan::matrix_return_t<T0, T1, T2, T3, T4, T5>\n    solve(const F& f,\n          const int nCmt,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\n          const std::vector<std::vector<T4> >& pMatrix,\n          const std::vector<std::vector<T5> >& biovar,\n          std::ostream* msgs) {\n      return solve(f, nCmt,\n                   time, amt, rate, ii, evid, cmt, addl, ss,\n                   pMatrix, biovar,\n                   RTOL_DE, ATOL_DE, MAXSTEP_DE,\n                   RTOL_AS, ATOL_AS, MAXSTEP_AS,                        \n                   msgs);\n    }\n\n    /** \n     * Overload: omitting lag time, with default algebra solver spec\n     * \n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename T5, typename F>\n    static stan::matrix_return_t<T0, T1, T2, T3, T4, T5>\n    solve(const F& f,\n          const int nCmt,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\n          const std::vector<std::vector<T4> >& pMatrix,\n          const std::vector<std::vector<T5> >& biovar,\n          double rel_tol,\n          double abs_tol,\n          long int max_num_steps,\n          std::ostream* msgs) {\n      return solve(f, nCmt,\n                   time, amt, rate, ii, evid, cmt, addl, ss,\n                   pMatrix, biovar,\n                   rel_tol, abs_tol, max_num_steps,\n                   RTOL_AS, ATOL_AS, MAXSTEP_AS,                        \n                   msgs);\n    }\n\n    /** \n     * Overload: omitting lag time, allow population-wise 1d array,\n     * with full ode & algebra solver spec\n     * \n     */\n    template <typename T0, typename T1, typename T2, typename T3,\n              typename T_par, typename T_biovar, typename F,\n              typename... Ts,\n              typename = require_any_not_std_vector_t<T_par, T_biovar>,\n              typename = require_all_not_std_vector_t<Ts...> >\n    static stan::matrix_return_t<T0, T1, T2, T3, T_par, T_biovar>\n    solve(const F& f,\n          const int nCmt,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\n          const std::vector<T_par>& pMatrix,\n          const std::vector<T_biovar>& biovar,\n          Ts... solver_ctrl) {\n      return solve(f, nCmt,\n                   time, amt, rate, ii, evid, cmt, addl, ss,\n                   torsten::to_array_2d(pMatrix), torsten::to_array_2d(biovar),\n                   solver_ctrl...);\n    }\n\n    /** \n     * Overload: omitting bioavailability & lag time,\n     * with full ode & algebra solver spec\n     * \n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename F>\n    static stan::matrix_return_t<T0, T1, T2, T3, T4>\n    solve(const F& f,\n               const int nCmt,\n               TORSTEN_PMX_FUNC_EVENTS_ARGS,\n               const std::vector<std::vector<T4> >& pMatrix,\n               double rel_tol,\n               double abs_tol,\n               long int max_num_steps,\n               double as_rel_tol,\n               double as_abs_tol,\n               long int as_max_num_steps,\n               std::ostream* msgs) {\n      // check arguments\n      static const char* function(\"solve\");\n      torsten::pmx_check(time, amt, rate, ii, evid, cmt, addl, ss, pMatrix, function);\n\n      using ER = NONMENEventsRecord<T0, T1, T2, T3>;\n      using EM = EventsManager<ER, NonEventParameters<T0, T4, std::vector, std::tuple<>>>;\n      const ER events_rec(nCmt, time, amt, rate, ii, evid, cmt, addl, ss);\n\n      Matrix<typename EM::T_scalar, -1, -1> pred(EM::nCmt(events_rec), events_rec.num_event_times());\n\n      using model_type = torsten::PKODEModel<typename EM::T_par, F>;\n\n      integrator_type integrator(rel_tol, abs_tol, max_num_steps, as_rel_tol, as_abs_tol, as_max_num_steps, msgs);\n      EventSolver<model_type, EM> pr;\n\n      pr.pred(0, events_rec, pred, integrator, pMatrix, nCmt, f);\n      return pred;\n    }\n\n    /** \n     * Overload: omitting bioavailability & lag time,\n     * with default ode & algebra solver spec\n     * \n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename F>\n    static stan::matrix_return_t<T0, T1, T2, T3, T4>\n    solve(const F& f,\n          const int nCmt,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\n          const std::vector<std::vector<T4> >& pMatrix,\n          std::ostream* msgs) {\n      return solve(f, nCmt,\n                   time, amt, rate, ii, evid, cmt, addl, ss,\n                   pMatrix,\n                   RTOL_DE, ATOL_DE, MAXSTEP_DE,\n                   RTOL_AS, ATOL_AS, MAXSTEP_AS,                        \n                   msgs);\n    }\n\n    /** \n     * Overload: omitting bioavailability & lag time,\n     * with default algebra solver spec\n     * \n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename F>\n    static stan::matrix_return_t<T0, T1, T2, T3, T4>\n    solve(const F& f,\n          const int nCmt,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\n          const std::vector<std::vector<T4> >& pMatrix,\n          double rel_tol,\n          double abs_tol,\n          long int max_num_steps,\n          std::ostream* msgs) {\n      return solve(f, nCmt,\n                   time, amt, rate, ii, evid, cmt, addl, ss,\n                   pMatrix,\n                   rel_tol, abs_tol, max_num_steps,\n                   RTOL_AS, ATOL_AS, MAXSTEP_AS,                        \n                   msgs);\n    }\n\n    /** \n     * Overload: omitting bioavailability & lag time, allow\n     * population-wise 1d array,\n     * with full algebra solver spec\n     * \n     */\n    template <typename T0, typename T1, typename T2, typename T3,\n              typename T_par, typename F,\n              typename... Ts,\n              typename = require_any_not_std_vector_t<T_par>,\n              typename = require_all_not_std_vector_t<Ts...> >\n    static stan::matrix_return_t<T0, T1, T2, T3, T_par>\n    solve(const F& f,\n          const int nCmt,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\n          const std::vector<T_par>& pMatrix,\n          Ts... solver_ctrl) {\n      return solve(f, nCmt,\n                   time, amt, rate, ii, evid, cmt, addl, ss,\n                   torsten::to_array_2d(pMatrix),\n                   solver_ctrl...);\n    }\n\n    /** \n     * Overload: additional real data for ODE, with full ode & algebra\n     * solver spec\n     * \n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename T5, typename T6, typename F>\n    static stan::matrix_return_t<T0, T1, T2, T3, T4, T5, T6>\n    solve(const F& f,\n          const int nCmt,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\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          const std::vector<std::vector<double> >& x_r,\n          double rel_tol,\n          double abs_tol,\n          long int max_num_steps,\n          double as_rel_tol,\n          double as_abs_tol,\n          long int as_max_num_steps,\n          std::ostream* msgs) {\n      // check arguments\n      static const char* function(\"solve\");\n      torsten::pmx_check(time, amt, rate, ii, evid, cmt, addl, ss, pMatrix, function);\n      torsten::pmx_check(time.size(), nCmt, biovar, tlag);\n\n      using ER = NONMENEventsRecord<T0, T1, T2, T3>;\n      using EM = EventsManager<ER, NonEventParameters<T0, T4, std::vector, std::tuple<T5, T6>, double>>;\n      const ER events_rec(nCmt, time, amt, rate, ii, evid, cmt, addl, ss);\n\n      Matrix<typename EM::T_scalar, -1, -1> pred(EM::nCmt(events_rec), events_rec.num_event_times());\n\n      using model_type = torsten::PKODEModel<typename EM::T_par, F>;\n\n      integrator_type integrator(rel_tol, abs_tol, max_num_steps, as_rel_tol, as_abs_tol, as_max_num_steps, msgs);\n      EventSolver<model_type, EM> pr;\n\n      pr.pred(0, events_rec, pred, integrator, pMatrix, biovar, tlag, x_r, nCmt, f);\n      return pred;\n    }\n\n    /** \n     * Overload: additional real data for ODE, with default ode & algebra \n     * solver spec\n     * \n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename T5, typename T6, typename F>\n    static stan::matrix_return_t<T0, T1, T2, T3, T4, T5, T6>\n    solve(const F& f,\n          const int nCmt,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\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          const std::vector<std::vector<double> >& x_r,\n          std::ostream* msgs) {\n      return solve(f, nCmt,\n                   time, amt, rate, ii, evid, cmt, addl, ss,\n                   pMatrix, biovar, tlag, x_r,\n                   RTOL_DE, ATOL_DE, MAXSTEP_DE,\n                   RTOL_AS, ATOL_AS, MAXSTEP_AS,\n                   msgs);\n    }\n\n    /** \n     * Overload: additional real data for ODE, with default algebra \n     * solver spec\n     * \n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename T5, typename T6, typename F>\n    static stan::matrix_return_t<T0, T1, T2, T3, T4, T5, T6>\n    solve(const F& f,\n          const int nCmt,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\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          const std::vector<std::vector<double> >& x_r,\n          double rel_tol,\n          double abs_tol,\n          long int max_num_steps,\n          std::ostream* msgs) {\n      return solve(f, nCmt,\n                   time, amt, rate, ii, evid, cmt, addl, ss,\n                   pMatrix, biovar, tlag, x_r,\n                   rel_tol, abs_tol, max_num_steps,\n                   RTOL_AS, ATOL_AS, MAXSTEP_AS,\n                   msgs);\n    }\n\n    // Overload: with real data, PMX params can be either 1d or 2d arrays.\n    template <typename T0, typename T1, typename T2, typename T3,\n              typename T_par, typename T_biovar, typename T_tlag,\n              typename F,\n              typename... Ts,\n              typename = require_any_not_std_vector_t<T_par, T_biovar, T_tlag>,\n              typename = require_all_not_std_vector_t<Ts...> >\n    static stan::matrix_return_t<T0, T1, T2, T3, T_par, T_biovar, T_tlag>\n    solve(const F& f,\n          const int nCmt,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\n          const std::vector<T_par>& pMatrix,\n          const std::vector<T_biovar>& biovar,\n          const std::vector<T_tlag>& tlag,\n          const std::vector<std::vector<double> >& x_r,\n          Ts... solver_ctrl) {\n      return solve(f, nCmt,\n                   time, amt, rate, ii, evid, cmt, addl, ss,\n                   torsten::to_array_2d(pMatrix),\n                   torsten::to_array_2d(biovar),\n                   torsten::to_array_2d(tlag), x_r,\n                   solver_ctrl...);\n    }\n\n    /** \n     * Overload: additional real & int data for ODE, with full ode & algebra\n     * solver spec\n     * \n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename T5, typename T6, typename F>\n    static stan::matrix_return_t<T0, T1, T2, T3, T4, T5, T6>\n    solve(const F& f,\n          const int nCmt,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\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          const std::vector<std::vector<double> >& x_r,\n          const std::vector<std::vector<int> >& x_i,\n          double rel_tol,\n          double abs_tol,\n          long int max_num_steps,\n          double as_rel_tol,\n          double as_abs_tol,\n          long int as_max_num_steps,\n          std::ostream* msgs) {\n      // check arguments\n      static const char* function(\"solve\");\n      torsten::pmx_check(time, amt, rate, ii, evid, cmt, addl, ss, pMatrix, function);\n      torsten::pmx_check(time.size(), nCmt, biovar, tlag);\n\n      using ER = NONMENEventsRecord<T0, T1, T2, T3>;\n      using EM = EventsManager<ER, NonEventParameters<T0, T4, std::vector, std::tuple<T5, T6>, double, int>>;\n      const ER events_rec(nCmt, time, amt, rate, ii, evid, cmt, addl, ss);\n\n      Matrix<typename EM::T_scalar, -1, -1> pred(EM::nCmt(events_rec), events_rec.num_event_times());\n\n      using model_type = torsten::PKODEModel<typename EM::T_par, F>;\n\n      integrator_type integrator(rel_tol, abs_tol, max_num_steps, as_rel_tol, as_abs_tol, as_max_num_steps, msgs);\n      EventSolver<model_type, EM> pr;\n\n      pr.pred(0, events_rec, pred, integrator, pMatrix, biovar, tlag, x_r, x_i, nCmt, f);\n      return pred;\n    }\n\n    /** \n     * Overload: additional real & int data for ODE, with default ode & algebra\n     * solver spec\n     * \n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename T5, typename T6, typename F>\n    static stan::matrix_return_t<T0, T1, T2, T3, T4, T5, T6>\n    solve(const F& f,\n          const int nCmt,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\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          const std::vector<std::vector<double> >& x_r,\n          const std::vector<std::vector<int> >& x_i,\n          std::ostream* msgs) {\n      return solve(f, nCmt,\n                   time, amt, rate, ii, evid, cmt, addl, ss,\n                   pMatrix, biovar, tlag, x_r, x_i,\n                   RTOL_DE, ATOL_DE, MAXSTEP_DE,\n                   RTOL_AS, ATOL_AS, MAXSTEP_AS,\n                   msgs);\n    }\n\n    /** \n     * Overload: additional real & int data for ODE, with default algebra \n     * solver spec\n     * \n     */\n    template <typename T0, typename T1, typename T2, typename T3, typename T4,\n              typename T5, typename T6, typename F>\n    static stan::matrix_return_t<T0, T1, T2, T3, T4, T5, T6>\n    solve(const F& f,\n               const int nCmt,\n               TORSTEN_PMX_FUNC_EVENTS_ARGS,\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               const std::vector<std::vector<double> >& x_r,\n               const std::vector<std::vector<int> >& x_i,\n               double rel_tol,\n               double abs_tol,\n               long int max_num_steps,\n               std::ostream* msgs) {\n      return solve(f, nCmt,\n                   time, amt, rate, ii, evid, cmt, addl, ss,\n                   pMatrix, biovar, tlag, x_r, x_i,\n                   rel_tol, abs_tol, max_num_steps,\n                   RTOL_AS, ATOL_AS, MAXSTEP_AS,\n                   msgs);\n    }\n\n    // Overload: with real & int data, PMX params can be either 1d or 2d arrays.\n    template <typename T0, typename T1, typename T2, typename T3,\n              typename T_par, typename T_biovar, typename T_tlag,\n              typename F,\n              typename... Ts,\n              typename = require_any_not_std_vector_t<T_par, T_biovar, T_tlag>,\n              typename = require_all_not_std_vector_t<Ts...> >\n    static stan::matrix_return_t<T0, T1, T2, T3, T_par, T_biovar, T_tlag>\n    solve(const F& f,\n          const int nCmt,\n          TORSTEN_PMX_FUNC_EVENTS_ARGS,\n          const std::vector<T_par>& pMatrix,\n          const std::vector<T_biovar>& biovar,\n          const std::vector<T_tlag>& tlag,\n          const std::vector<std::vector<double> >& x_r,\n          const std::vector<std::vector<int> >& x_i,\n          Ts... solver_ctrl) {\n      return solve(f, nCmt,\n                   time, amt, rate, ii, evid, cmt, addl, ss,\n                   torsten::to_array_2d(pMatrix),\n                   torsten::to_array_2d(biovar),\n                   torsten::to_array_2d(tlag), x_r, x_i,\n                   solver_ctrl...);\n    }\n  };\n}  \n#endif\n", "meta": {"hexsha": "3cb9e097c5dcc0513777822aec44ac4e3c853d2f", "size": 25995, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pmx_solve_ode.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": "pmx_solve_ode.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": "pmx_solve_ode.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": 40.0539291217, "max_line_length": 114, "alphanum_fraction": 0.5748413156, "num_tokens": 6958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.3665897363221598, "lm_q1q2_score": 0.2539154419630208}}
{"text": "// starting month is fixed to dec\r\n\r\n#include<stdio.h>\r\n#include <stdlib.h>\r\n#include <string>\r\n#include <math.h>\r\n#include <iostream>\r\n#include <fstream>\r\n#include <sstream>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <cassert>\r\n#include <omp.h>\r\n#include \"ANIMALS.h\"\r\n#include \"Misc.h\"\r\n#include \"DefineParameters.h\"\r\n#include \"DefinePriors.h\"\r\n#include \"eigenmvn.h\"\r\n#include <ctime>\r\n#include \"Dist.h\"\r\n#include<sys/types.h>\r\n#include <random>\r\n#include <thread>\r\n#include <vector>\r\n#include \"ProcessHeader.h\"\r\n#include <boost/uuid/seed_rng.hpp>\r\n#include <boost/random/mersenne_twister.hpp>\r\n\r\nusing namespace std;\r\n\r\n//typedef boost::lagged_fibonacci607 base_generator_type;\r\n\r\n\r\nconst int get_int(const string& s) {\r\n\tstringstream ss(s);\r\n\tint ret;\r\n\tss >> ret;\r\n\treturn ret;\r\n}\r\n\r\nint count_Data(ifstream &filename)// struct weatherdata *enviroData)\r\n{\r\n\tint numrec = 0;\r\n\tstring lines;\r\n\tif (filename){\r\n\t\tgetline(filename, lines); //get rid of the first line, \r\n\t\t// ------------ read and store data into enviroData-------------\r\n\t\twhile (getline(filename, lines))\r\n\t\t{\r\n\t\t\tnumrec++;\r\n\t\t}\r\n\r\n\t}\r\n\telse{ cout << \"Problem in opening file.\\n\"; exit(0); }\r\n\r\n\treturn numrec;\r\n}\r\n\r\ndouble get_double(const string& s) {\r\n\tstringstream ss(s);\r\n\tdouble ret;\r\n\tss >> ret;\r\n\treturn  ret;\r\n}\r\n\r\n/*\r\nvoid get_chlo_legth_dat(ifstream &filename, struct chlo_length *data){\r\n\r\nint i = 0;\r\nstring lines;\r\n\r\nif (filename){\r\ngetline(filename, lines);\r\ni = 0;\r\nwhile (getline(filename, lines)){\r\nstringstream ss(lines);\r\nvector<std::string> dat;\r\nstring field;\r\nwhile (getline(ss, field, ',')) {\r\nif (field.empty()){\r\nfield = \"-9999\";// missing value\r\n}\r\ndat.push_back(field);\r\n}\r\ndata[i].chro = get_double(dat[0]);\r\ndata[i].p_len = roundf(get_double(dat[1]) * 100) / 100;;\r\nvector<string>().swap(dat);\r\ni++;\r\n}\r\n}\r\nelse{ cout << \"Problem in opening CHLOROPHYLL BASED LENGTH file\\n\"; exit(0); }\r\n}\r\n*/\r\n\r\nvoid get_old_params(ifstream &filename, struct parameters *params, vector<double> &rho){\r\n\t// update to mixute on 07/09\r\n\tint i = 0;\r\n\tstring lines;\r\n\r\n\tif (filename){\r\n\t\tgetline(filename, lines);\r\n\t\ti = 0;\r\n\t\twhile (getline(filename, lines)){\r\n\t\t\tstringstream ss(lines);\r\n\t\t\tvector<std::string> dat;\r\n\t\t\tstring field;\r\n\t\t\twhile (getline(ss, field, '\\t')) {\r\n\t\t\t\tif (field.empty()){\r\n\t\t\t\t\tcout << \"There is missing value in param.txt\" << endl;\r\n\t\t\t\t\texit(0);\r\n\t\t\t\t}\r\n\t\t\t\tdat.push_back(field);\r\n\t\t\t}\r\n\r\n\t\t\trho[i] = get_double(dat[1]);\r\n\t\t\tparams[i].alpha[0] = get_double(dat[2]);\r\n\t\t\tparams[i].alpha[1] = get_double(dat[3]);\r\n\t\t\tparams[i].alpha[2] = get_double(dat[4]);\r\n\t\t\tparams[i].beta = get_double(dat[5]);\r\n\t\t\tparams[i].beta_sigma = get_double(dat[6]);\r\n\t\t\tparams[i].detect[0] = get_double(dat[7]);\r\n\t\t\tparams[i].detect[1] = get_double(dat[8]);\r\n\t\t\tparams[i].detect[2] = get_double(dat[9]);\r\n\t\t\tparams[i].error_N = get_double(dat[10]);\r\n\t\t\tparams[i].jv_sur = get_double(dat[11]);\r\n\t\t\tparams[i].k = get_double(dat[12]);\r\n\t\t\tparams[i].larv_mor = get_double(dat[13]);\r\n\t\t\tparams[i].x0 = get_double(dat[14]);\r\n\t\t\tvector<string>().swap(dat);\r\n\t\t\ti++;\r\n\t\t}\r\n\t}\r\n\telse{ cout << \"Problem in opeing params.txt .\\n\"; exit(0); }\r\n}\r\n\r\n\r\nvoid get_ini_leng_dat(ifstream &filename, struct ini_length *ini_leng){\r\n\t// update to mixute on 07/09\r\n\tint i = 0;\r\n\tstring lines;\r\n\r\n\tif (filename){\r\n\t\tgetline(filename, lines);\r\n\t\ti = 0;\r\n\t\twhile (getline(filename, lines)){\r\n\t\t\tstringstream ss(lines);\r\n\t\t\tvector<std::string> dat;\r\n\t\t\tstring field;\r\n\t\t\twhile (getline(ss, field, ' ')) {\r\n\t\t\t\tif (field.empty()){\r\n\t\t\t\t\tfield = \"-9999\";// missing value\r\n\t\t\t\t}\r\n\t\t\t\tdat.push_back(field);\r\n\t\t\t}\r\n\t\t\tini_leng[i].prop = get_double(dat[0]);\r\n\t\t\tini_leng[i].mean = get_double(dat[1]);\r\n\t\t\tini_leng[i].std = get_double(dat[2]);\r\n\t\t\tvector<string>().swap(dat);\r\n\t\t\ti++;\r\n\t\t}\r\n\t}\r\n\telse{ cout << \"Problem in relative frequency among reefs file.\\n\"; exit(0); }\r\n}\r\nvoid get_ini_dist(ifstream &filename, struct reef_month *out){\r\n\r\n\tint i = 0;\r\n\tstring lines;\r\n\r\n\tif (filename){\r\n\t\tgetline(filename, lines);\r\n\t\ti = 0;\r\n\t\twhile (getline(filename, lines)){\r\n\t\t\tstringstream ss(lines);\r\n\t\t\tvector<std::string> dat;\r\n\t\t\tstring field;\r\n\t\t\twhile (getline(ss, field, ' ')) {\r\n\t\t\t\tif (field.empty()){\r\n\t\t\t\t\tfield = \"-9999\";// missing value\r\n\t\t\t\t}\r\n\t\t\t\tdat.push_back(field);\r\n\t\t\t}\r\n\t\t\tout[i].REEF_ID = dat[0];\r\n\t\t\tout[i].shelf = dat[1];\r\n\t\t\tout[i].lat = get_double(dat[2]);\r\n\t\t\tout[i].longi = get_double(dat[3]);\r\n\t\t\tout[i].rel = get_double(dat[4]);\r\n\t\t\tout[i].ini_obs = get_int(dat[5]);\r\n\t\t\tvector<string>().swap(dat);\r\n\t\t\ti++;\r\n\t\t}\r\n\t}\r\n\telse{ cout << \"Problem in relative frequency among reefs file.\\n\"; exit(0); }\r\n\r\n}\r\nvoid get_coral_coverage(ifstream &filename, struct coral_cov *out, int s_yr, int s_mth){\r\n\r\n\tint i = 0;\r\n\tstring lines;\r\n\r\n\tif (filename){\r\n\t\tgetline(filename, lines);\r\n\t\ti = 0;\r\n\t\twhile (getline(filename, lines)){\r\n\t\t\tstringstream ss(lines);\r\n\t\t\tvector<std::string> dat;\r\n\t\t\tstring field;\r\n\t\t\twhile (getline(ss, field, ' ')) {\r\n\t\t\t\tif (field.empty()){\r\n\t\t\t\t\tfield = \"-9999\";// missing value\r\n\t\t\t\t}\r\n\t\t\t\tdat.push_back(field);\r\n\t\t\t}\r\n\t\t\tout[i].REEF_ID = dat[0];\r\n\t\t\tout[i].s_day = convert_yr_mth_time(s_yr, s_mth, get_int(dat[1]), get_int(dat[2]));\r\n\t\t\tout[i].cov = get_double(dat[3]);\r\n\t\t\tvector<string>().swap(dat);\r\n\t\t\ti++;\r\n\t\t}\r\n\t}\r\n\telse{ cout << \"Problem in opening coral coverage.\\n\"; exit(0); }\r\n\r\n}\r\nvoid get_chlorophyll_dat(ifstream &filename, struct chloro_ori *out, int s_yr, int s_mth){\r\n\r\n\tint i = 0;\r\n\tstring lines;\r\n\r\n\tif (filename){\r\n\t\tgetline(filename, lines);\r\n\t\ti = 0;\r\n\t\twhile (getline(filename, lines)){\r\n\t\t\tstringstream ss(lines);\r\n\t\t\tvector<std::string> dat;\r\n\t\t\tstring field;\r\n\t\t\twhile (getline(ss, field, ' ')) {\r\n\t\t\t\tif (field.empty()){\r\n\t\t\t\t\tfield = \"-9999\";// missing value\r\n\t\t\t\t}\r\n\t\t\t\tdat.push_back(field);\r\n\t\t\t}\r\n\t\t\tout[i].REEF_ID = dat[0];\r\n\t\t\tout[i].s_day = convert_yr_mth_time(s_yr, s_mth, get_int(dat[1]), get_int(dat[2]));\r\n\t\t\tout[i].chlo = get_double(dat[3]);\r\n\t\t\tvector<string>().swap(dat);\r\n\t\t\ti++;\r\n\t\t}\r\n\t}\r\n\telse{ cout << \"Problem in opening chlorophyll data.\\n\"; exit(0); }\r\n\r\n}\r\nvoid get_connect_dat(ifstream &filename, struct connect_ori *out){\r\n\r\n\tint i = 0;\r\n\tstring lines;\r\n\r\n\tif (filename){\r\n\t\tgetline(filename, lines);\r\n\t\ti = 0;\r\n\t\twhile (getline(filename, lines)){\r\n\t\t\tstringstream ss(lines);\r\n\t\t\tvector<std::string> dat;\r\n\t\t\tstring field;\r\n\t\t\twhile (getline(ss, field, ' ')) {\r\n\t\t\t\tif (field.empty()){\r\n\t\t\t\t\tfield = \"-9999\";// missing value\r\n\t\t\t\t}\r\n\t\t\t\tdat.push_back(field);\r\n\t\t\t}\r\n\t\t\tout[i].year = get_int(dat[0]);\r\n\t\t\tout[i].from = dat[1];\r\n\t\t\tout[i].to = dat[2];\r\n\t\t\tout[i].connect = get_double(dat[3]);\r\n\t\t\tvector<string>().swap(dat);\r\n\t\t\ti++;\r\n\t\t}\r\n\t}\r\n\telse{ cout << \"Problem in opening connectivity data.\\n\"; exit(0); }\r\n\r\n}\r\nvoid get_obs_dat(ifstream &filename, struct obs_abund *out){\r\n\r\n\tint i = 0;\r\n\tstring lines;\r\n\r\n\tif (filename){\r\n\t\tgetline(filename, lines);\r\n\t\ti = 0;\r\n\t\twhile (getline(filename, lines)){\r\n\t\t\tstringstream ss(lines);\r\n\t\t\tvector<std::string> dat;\r\n\t\t\tstring field;\r\n\t\t\twhile (getline(ss, field, ' ')) {\r\n\t\t\t\tif (field == \"NA\"){\r\n\t\t\t\t\tfield = \"-9999\";// missing value\r\n\t\t\t\t}\r\n\t\t\t\tdat.push_back(field);\r\n\t\t\t}\r\n\r\n\t\t\tout[i].reef_ID = dat[0];\r\n\t\t\tout[i].year = get_int(dat[1]);\r\n\t\t\tout[i].mth = get_int(dat[2]);\r\n\t\t\tout[i].pz = get_double(dat[3]);\r\n\t\t\tout[i].CPUE = get_double(dat[4]);\r\n\t\t\tvector<string>().swap(dat);\r\n\t\t\ti++;\r\n\t\t}\r\n\t}\r\n\telse{ cout << \"Problem in opening COTS abundance data.\\n\"; exit(0); }\r\n\r\n}\r\nvoid get_reef_size_dat(ifstream &filename, struct reef_size *out){\r\n\r\n\tint i = 0;\r\n\tstring lines;\r\n\r\n\tif (filename){\r\n\t\tgetline(filename, lines);\r\n\t\ti = 0;\r\n\t\twhile (getline(filename, lines)){\r\n\t\t\tstringstream ss(lines);\r\n\t\t\tvector<std::string> dat;\r\n\t\t\tstring field;\r\n\t\t\twhile (getline(ss, field, '\\t')) {\r\n\t\t\t\tif (field == \"NA\"){\r\n\t\t\t\t\tfield = \"-9999\";// missing value\r\n\t\t\t\t}\r\n\t\t\t\tdat.push_back(field);\r\n\t\t\t}\r\n\r\n\t\t\tout[i].reef_ID = dat[1];\r\n\t\t\tout[i].size = get_double(dat[5]);\r\n\r\n\t\t\tvector<string>().swap(dat);\r\n\t\t\ti++;\r\n\t\t}\r\n\t}\r\n\telse{ cout << \"Problem in opening REEF SIZE data.\\n\"; exit(0); }\r\n\r\n}\r\nvoid get_wtemp_dat(ifstream &filename, struct w_temp *out, int s_yr, int s_mth){\r\n\r\n\tint i = 0;\r\n\tstring lines;\r\n\r\n\tif (filename){\r\n\t\tgetline(filename, lines);\r\n\t\ti = 0;\r\n\t\twhile (getline(filename, lines)){\r\n\t\t\tstringstream ss(lines);\r\n\t\t\tvector<std::string> dat;\r\n\t\t\tstring field;\r\n\t\t\twhile (getline(ss, field, ' ')) {\r\n\t\t\t\tif (field == \"NA\"){\r\n\t\t\t\t\tfield = \"-9999\";// missing value\r\n\t\t\t\t}\r\n\t\t\t\tdat.push_back(field);\r\n\t\t\t}\r\n\r\n\t\t\tout[i].sim = convert_yr_mth_time(s_yr, s_mth, get_int(dat[0]), get_int(dat[1]));\r\n\t\t\tout[i].wTemp = get_int(dat[2]);\r\n\t\t\tvector<string>().swap(dat);\r\n\t\t\ti++;\r\n\t\t}\r\n\t}\r\n\telse{ cout << \"Problem in opening WATER temperature data.\\n\"; exit(0); }\r\n\r\n}\r\nvoid usage()\r\n{\r\n\tprintf(\"Command line should have \\n 1) simulation period (unit: Years) \\n 2) starting population size  \\n 3) Initial Sex ratio \\n 4) Starting Year \\n 5)Minimum tolerance value \\n 6)Proportion of particles dropped per iteration \\n 7) Number of total particles \\n 8) Starting Tolerance value \\n 9) Option (0:start new, 1:Continue) \\n\");\r\n\texit(1);\r\n}\r\n\r\n\r\nint main(int argc, char **argv)\r\n{\r\n\tifstream aFile, bFile, cFile;\r\n\tofstream myFile;\r\n\tint no_chl_rec, bins, bins_zero, coral_cov_rec;\r\n\tint i, p;\r\n\tint j, k, l;\r\n\tint chlo_rec;\r\n\tint n_conn; // number of connecticity records\r\n\tint no_loc;\r\n\tint SIM_LENGTH, INI_POP_SIZE, START_YR, SIM_YEARS;\r\n\tdouble INI_SEX_RAT;\r\n\tint DIM;\r\n\r\n\tdouble RATE;\r\n\tint PARTICLE_SIZE;\r\n\tdouble TOLERANCE_S, START_S;\r\n\tint OPTION;\r\n\t///---------------------------------------end very temp\r\n\tif (argc != 10) usage();\r\n\tSIM_YEARS = get_int(argv[1]);\r\n\tSIM_LENGTH = SIM_YEARS * 12;\r\n\tINI_POP_SIZE = get_int(argv[2]);\r\n\tINI_SEX_RAT = get_double(argv[3]);\r\n\tSTART_YR = get_int(argv[4]);\r\n\tTOLERANCE_S = get_double(argv[5]);// miniMUM TOLERANCE\r\n\tRATE = get_double(argv[6]);// Proportion of samples to be dropped\r\n\tPARTICLE_SIZE = get_int(argv[7]);// Number of particles to keep\r\n\tSTART_S = get_double(argv[8]);// miniMUM TOLERANCE\r\n\tOPTION = get_int(argv[9]); // 0: start from new; 1: provide the keep\r\n\t// store the parameters\r\n\r\n\r\n\tauto start = std::chrono::system_clock::now();\r\n\r\n\r\n\t// read in \r\n\t//1) annual manta-tow data\r\n\t//2) AMPTO data \r\n\t//-------------------Begin read in data--------------------------------------\r\n\r\n\t///////////////////////////////////////////\r\n\t/*\taFile.open(\"predlengthchro.txt\", ios::in);\r\n\t\tno_chl_rec = count_Data(aFile);\r\n\t\tcout << \"Nrow Chlorophyll Length data \" << no_chl_rec << endl;\r\n\t\taFile.clear();\r\n\t\taFile.seekg(0);\r\n\t\tstruct chlo_length *chlo_length;\r\n\t\tchlo_length = new struct chlo_length[no_chl_rec];\r\n\t\tget_chlo_legth_dat(aFile, &(*chlo_length));\r\n\t\taFile.close();\r\n\t\t*/\r\n\r\n\t// for location where no COTS were seen on the first two years. \r\n\t/*\r\n\tcFile.open(\"ini_size_stru_fisk_zero.txt\", ios::in);\r\n\tbins_zero = count_Data(cFile);\r\n\tcout << \"Number of Length bin: \" << bins_zero << endl;\r\n\tcFile.clear();\r\n\tcFile.seekg(0);\r\n\r\n\tstruct ini_length * ini_leng_zero;\r\n\tini_leng_zero = new struct ini_length[bins_zero];\r\n\tget_ini_leng_dat(cFile, ini_leng_zero);\r\n\tcFile.close();\r\n\t*/\r\n\r\n\t//////////////////////////////////////////////\r\n\tbFile.open(\"initial_length_v2.txt\", ios::in);\r\n\tbins = count_Data(bFile);\r\n\tcout << \"Number of Length bin: \" << bins << endl;\r\n\tbFile.clear();\r\n\tbFile.seekg(0);\r\n\r\n\tstruct ini_length * ini_leng;\r\n\tini_leng = new struct ini_length[bins];\r\n\tget_ini_leng_dat(bFile, ini_leng);\r\n\tbFile.close();\r\n\r\n\t// Read in Locations and relative abundance\r\n\taFile.open(\"starting_wt.txt\", ios::in);\r\n\tno_loc = count_Data(aFile);\r\n\taFile.clear();\r\n\taFile.seekg(0);\r\n\tstruct reef_month *temp_mth_reef;\r\n\ttemp_mth_reef = new struct reef_month[no_loc];\r\n\tget_ini_dist(aFile, temp_mth_reef);\r\n\taFile.close();\r\n\r\n\taFile.open(\"MonthlyCoralAdjCycle.txt\", ios::in);\r\n\tcoral_cov_rec = count_Data(aFile);\r\n\taFile.clear();\r\n\taFile.seekg(0);\r\n\tstruct coral_cov *CC;\r\n\tCC = new struct coral_cov[coral_cov_rec];\r\n\tget_coral_coverage(aFile, CC, START_YR, START_MTH);\r\n\taFile.close();\r\n\r\n\t// assign CC to mth_reef\r\n\tconvert_coralcover_foo(CC, temp_mth_reef, no_loc, SIM_LENGTH, coral_cov_rec);\r\n\tdelete[] CC;\r\n\tCC = nullptr;\r\n\r\n\tbFile.open(\"chlorophylldata_all.txt\", ios::in);\r\n\tchlo_rec = count_Data(bFile);\r\n\tcout << \"Chlorophyll data \" << chlo_rec << endl;\r\n\tbFile.clear();\r\n\tbFile.seekg(0);\r\n\tstruct chloro_ori *chlo_temp;\r\n\tchlo_temp = new struct chloro_ori[chlo_rec];\r\n\tget_chlorophyll_dat(bFile, chlo_temp, START_YR, START_MTH);\r\n\tbFile.close();\r\n\r\n\tstruct chlorophyll *chlo_dat;\r\n\tchlo_dat = new struct chlorophyll[no_loc];\r\n\r\n\tfor (i = 0; i < no_loc; i++){\r\n\t\tchlo_dat[i].REEF_ID = temp_mth_reef[i].REEF_ID;\r\n\t}\r\n\r\n\tformat_chloro(chlo_temp, chlo_dat, no_loc, SIM_LENGTH, chlo_rec);\r\n\r\n\tdelete[] chlo_temp;\r\n\tchlo_temp = nullptr;\r\n\r\n\taFile.open(\"Connect_09.txt\", ios::in);\r\n\tn_conn = count_Data(aFile);\r\n\taFile.clear();\r\n\taFile.seekg(0);\r\n\tstruct connect_ori *con_temp = new struct connect_ori[n_conn];\r\n\tget_connect_dat(aFile, con_temp);\r\n\taFile.close();\r\n\r\n\t// convert struct of connect_ori to \r\n\tstruct con *connect = new struct con[no_loc];\r\n\r\n\tint ctr1, yr;\r\n\tint s_yr;\r\n\r\n\t// assign soucing reef\r\n\tfor (i = 0; i < no_loc; i++){\r\n\t\ts_yr = START_YR + 1; // recruitment starts in the following year\r\n\t\tconnect[i].REEF_ID = temp_mth_reef[i].REEF_ID;\r\n\t\tctr1 = 0;\r\n\t\tfor (j = 0; j < (no_loc - 1)*(SIM_YEARS + 1); j++){\r\n\t\t\tconnect[i].year[j] = s_yr;\r\n\t\t\tif (j == ((no_loc - 1) * (ctr1 + 1) - 1)){\r\n\t\t\t\ts_yr++;\r\n\t\t\t\tctr1++;\r\n\t\t\t}\r\n\r\n\t\t}\r\n\t\t// assign sinking reefs\r\n\t\tl = 0;\r\n\t\tfor (yr = 0; yr < SIM_YEARS + 1; yr++){\r\n\t\t\tfor (k = 0; k < no_loc; k++){\r\n\t\t\t\tif (connect[i].REEF_ID != temp_mth_reef[k].REEF_ID){\r\n\t\t\t\t\tconnect[i].to[l] = temp_mth_reef[k].REEF_ID;\r\n\t\t\t\t\tl++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tfomat_connect(con_temp, connect, no_loc, n_conn, SIM_YEARS);\r\n\r\n\tdelete[] con_temp;\r\n\tcon_temp = nullptr;\r\n\r\n\t// read in reef size\r\n\r\n\tint nr;\r\n\t/*aFile.open(\"areaofReef.txt\", ios::in);\r\n\tnr = count_Data(aFile);\r\n\tstruct reef_size *size = new struct reef_size[nr];\r\n\taFile.clear();\r\n\taFile.seekg(0);\r\n\tget_reef_size_dat(aFile, size);\r\n\taFile.close();\r\n\r\n\tfor (i = 0; i < nr; i++){\r\n\tfor (j = 0; j < no_loc; j++){\r\n\tif (temp_mth_reef[j].REEF_ID == size[i].reef_ID){\r\n\ttemp_mth_reef[j].size = size[i].size;\r\n\t}\r\n\t}\r\n\t}\r\n\r\n\tdelete[] size;\r\n\tsize = nullptr;\r\n\t*/\r\n\t///---- read water temp data------\r\n\tbFile.open(\"Complete Pooled water temp.txt\", ios::in);\r\n\tnr = count_Data(bFile);\r\n\tstruct w_temp *wat_temp = new struct w_temp[nr];\r\n\tbFile.clear();\r\n\tbFile.seekg(0);\r\n\tget_wtemp_dat(bFile, wat_temp, START_YR, START_MTH);\r\n\tbFile.close();\r\n\r\n\t///// ---------------------- read the catch data\r\n\r\n\tint no_obs_rec;\r\n\r\n\t/*change to distribution on 08/09/2015\r\n\taFile.open(\"LTMP_abun.txt\", ios::in);\r\n\tno_obs_rec = count_Data(aFile);\r\n\taFile.clear();\r\n\taFile.seekg(0);\r\n\tstruct obs_abund *obs_abundance = new struct obs_abund[no_obs_rec];\r\n\tget_obs_dat(aFile, obs_abundance);\r\n\taFile.close();\r\n\t*/\r\n\taFile.open(\"COT_abund_dis_cpue.txt\", ios::in);\r\n\tno_obs_rec = count_Data(aFile);\r\n\taFile.clear();\r\n\taFile.seekg(0);\r\n\tstruct obs_abund *obs_abundance = new struct obs_abund[no_obs_rec];\r\n\tget_obs_dat(aFile, obs_abundance);\r\n\taFile.close();\r\n\t//-------------------------------end read in data--------------------------------\r\n\r\n\t///------ remove data\r\n\r\n\t// remove files\r\n\tremove(\"res_out.txt\");\r\n\tremove(\"pop_str.txt\");\r\n\tremove(\"rho_out.txt\");\r\n\tremove(\"walltime.txt\");\r\n\tremove(\"params.txt\");\r\n\tremove(\"acc_rat.txt\");\r\n\t//remove(\"annual.txt\");\r\n\r\n\r\n\t/// assign universal initial structure\r\n\t// out put sort\r\n\tmyFile.open(\"res_out.txt\", ios::app);\r\n\t// just checking if struct2mat works\r\n\tmyFile << \"particle\" << \"\\t\" << \"Loc\" << \"\\t\" << \"Year\" << \"\\t\" << \"Mth\" << \"\\t\" << \"n_cots\" << \"\\t\" << \"no_female\" << \"\\t\" << \"no_male\" << \"\\t\" << \"L15\" << \"\\t\" << \"L1525\" << \"\\t\" << \"L2540\" << \"\\t\" << \"L40p\" << endl;\r\n\tmyFile.close();\r\n\r\n\r\n\t// Of a fixed number of COTS the follow functiond distribute COTS number according to the relative weight\r\n\tini_pop_distribution(temp_mth_reef, no_loc, INI_POP_SIZE);\r\n\r\n\tmyFile.open(\"params.txt\", ios::app);\r\n\t//myFile << \"ITI\" << \"\\t\" << \"Par\" << \"\\t\" << \"Summary_stat\" << \"\\t\" << \"Beta\" << \"\\t\" << \"detect\" << \"\\t\" << \"jv_sur\" << \"\\t\" << \"k\" << \"\\t\" << \"larv_mor\" << \"\\t\" << \"x0\" << endl;\r\n\tmyFile << \"Par\" << \"\\t\" << \"Summary_stat\" << \"\\t\";\r\n\tfor (i = 0; i < no_loc; i++){\r\n\t\tmyFile << \"alpha_\" << i << \"\\t\";\r\n\t}\r\n\tmyFile << \"Beta\" << \"\\t\" << \"Beta_sigma\" << \"\\t\";\r\n\tfor (i = 0; i < no_loc; i++){\r\n\t\tmyFile << \"detect_\" << i << \"\\t\";\r\n\t}\r\n\tmyFile << \"Error\" << \"\\t\" << \"jv_sur\" << \"\\t\" << \"k\" << \"\\t\" << \"larv_mor\" << \"\\t\" << \"x0\" << \"\\t\" << endl;\r\n\tmyFile.close();\r\n\r\n\tmyFile.open(\"acc_rat.txt\", ios::app);\r\n\tmyFile << \"ITI ratio i_acc R p_acc RN\" << endl;\r\n\tmyFile.close();\r\n\r\n\t///////////OMP////////////////////\r\n\tomp_set_dynamic(2);\r\n\tunsigned short max_thread = omp_get_max_threads();\r\n\tbase_generator_type eng[max_thread];\r\n\tomp_set_num_threads(max_thread);\r\n\r\n\r\n\r\n\tstruct parameters *params = new struct parameters[PARTICLE_SIZE];\r\n\r\n\t// add two elements to parameters\r\n\r\n\t// first runs\r\n\tContext dist;\r\n\tvector<double> rho(PARTICLE_SIZE);\r\n\r\n\tdouble e_max; // first epi_max\r\n\tint N_drop = (int)round(PARTICLE_SIZE* RATE); // numebr of partcles to be dropped\r\n\tstruct parameters *param_keepers = new struct parameters[PARTICLE_SIZE - N_drop];\r\n\r\n\tif (OPTION == 0){\r\n\r\n#pragma omp parallel for schedule(dynamic, 3) private(i, j, p) shared(rho,params, START_YR, no_loc, obs_abundance, PARTICLE_SIZE, bins, no_obs_rec,  temp_mth_reef,ini_leng, SIM_LENGTH, INI_SEX_RAT, eng) \r\n\t\tfor (p = 0; p < PARTICLE_SIZE; p++){\r\n\r\n\t\t\tdouble sum_stats = 100000;\r\n\t\t\tint flg = 1; // flag ==1 means population extinct\r\n\t\t\tint seed = boost::uuids::detail::seed_rng()();\r\n\t\t\tstruct mth_out *out = new struct mth_out[SIM_LENGTH*no_loc]; // store the monthly records\r\n\r\n\r\n\t\t\teng[omp_get_thread_num()].seed(seed);\r\n\t\t\twhile ((sum_stats >= START_S) || (flg == 1)){\r\n\t\t\t\t//eng[omp_get_thread_num()].seed(static_cast<unsigned int>((seed++)*p + time(0))*max_thread*getpid());\r\n\t\t\t\tint inini;\r\n\t\t\t\tdo{\r\n\t\t\t\t\tparams[p].beta = dist.uniform_real_dis(BETA_MIN, BETA_MAX, eng[omp_get_thread_num()]);\r\n\t\t\t\t\tparams[p].beta_sigma = dist.lognormal_dis(BETA_SIG_MEAN, BETA_SIG_STD, eng[omp_get_thread_num()]);\r\n\t\t\t\t\tparams[p].jv_sur = dist.lognormal_dis(JUV_SUR_MEAN, JUV_SUR_STD, eng[omp_get_thread_num()]);\r\n\t\t\t\t\tparams[p].k = dist.lognormal_dis(ADULT_MOR_K_MEAN, ADULT_MOR_K_STD, eng[omp_get_thread_num()]);\r\n\t\t\t\t\tparams[p].larv_mor = 1 - dist.lognormal_dis(LAR_DAILY_MOR_MEAN, LAR_DAILY_MOR_STD, eng[omp_get_thread_num()]);\r\n\t\t\t\t\tparams[p].x0 = dist.lognormal_dis(ADULT_MOR_X0_MEAN, ADULT_MOR_X0_STD, eng[omp_get_thread_num()]);\r\n\t\t\t\t\tparams[p].error_N = dist.uniform_real_dis(VAR_ERROR_MIN, VAR_ERROR_MAX, eng[omp_get_thread_num()]);\r\n\r\n\t\t\t\t\tfor (j = 0; j < no_loc; j++){\r\n\t\t\t\t\t\tparams[p].detect[j] = dist.uniform_real_dis(DETECT_LO, DETECT_HI, eng[omp_get_thread_num()]);\r\n\t\t\t\t\t\tparams[p].alpha[j] = dist.lognormal_dis(DIS_MEAN, DIS_STD, eng[omp_get_thread_num()]);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tinini= check_ini_para(params, p, DIM, no_loc);\r\n\r\n\t\t\t\t} while (inini == 0);\r\n \r\n\t\t\t\t\t//----------------------------------call the process model here!!\r\n\t\t\t\t\t//setting up starting reef matrix\r\n\t\t\t\tstruct reef_month *mth_reef = new struct reef_month[no_loc];\r\n\r\n\t\t\t\tfor (i = 0; i < no_loc; i++){\r\n\t\t\t\t\tmth_reef[i] = temp_mth_reef[i];\r\n\t\t\t\t\tmth_reef[i].yr = START_YR;\r\n\t\t\t\t\tmth_reef[i].mth = START_MTH;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tProcessModel(&params[p], mth_reef, ini_leng, obs_abundance, bins, no_loc, SIM_LENGTH, INI_SEX_RAT, max_thread, no_obs_rec, sum_stats, flg, eng[omp_get_thread_num()], START_S, START_S, TOLERANCE_S, out);\r\n\r\n\t\t\t\tdelete[]mth_reef;\r\n\t\t\t\tmth_reef = nullptr;\r\n\r\n\t\t\t}\r\n\t\t\trho[p] = sum_stats;\r\n\t\t\tcout << p << \" \" << rho[p] << \" flag \" << flg << endl;\r\n\r\n\t\t}// end particles of the first iteration\r\n\r\n\t\te_max = *max_element(rho.begin(), rho.end()); // first epi_max\r\n\r\n\t\tcout << \"First e max \" << e_max << endl;\r\n\r\n\t\t/*myFile.open(\"params.txt\", ios::app);\r\n\r\n\t\tfor (p = 0; p < PARTICLE_SIZE; p++){\r\n\t\tmyFile << p << \"\\t\" << rho[p] << \"\\t\" << params[p].beta << \"\\t\" << params[p].beta_sigma << \"\\t\" << params[p].jv_sur << \"\\t\" << params[p].k << \"\\t\" << params[p].larv_mor << \"\\t\" << params[p].x0 << \"\\t\" << params[p].error_N << \"\\t\";\r\n\t\tfor (i = 0; i < no_loc; i++){\r\n\t\tmyFile << params[p].alpha[i] << \"\\t\" << params[p].detect[i] << \"\\t\";\r\n\t\t}\r\n\t\tmyFile << endl;\r\n\t\t}\r\n\t\tmyFile.close();\r\n\t\t*/\r\n\t}\r\n\r\n\telse{ // read in the params[p] data\r\n\r\n\t\taFile.open(\"params_old.txt\", ios::in);\r\n\t\tget_old_params(aFile, params, rho);\r\n\t\taFile.close();\r\n\t\te_max = *max_element(rho.begin(), rho.end()); // first epi_max\r\n\r\n\t\tcout << \"First e max \" << e_max << endl;\r\n\t}\r\n\r\n\tdouble e_next;\r\n\tlong long R, RN;\r\n\tR = INITIAL_R;\r\n\tlong double p_acc;\r\n\tint tck;\r\n\tint u = 0;\r\n\t\r\n\tdo{// et to e_max\r\n\t\tint ctr = 0;\r\n\t\t// ----- adaptive design\r\n\t\tRN = R* N_drop;\r\n\t\tint i_acc = 0;\r\n\t\ttck = 0;\r\n\t\t// --- adaptive\r\n\t\t// assign the rank to params\r\n\t\tfor (auto i : sort_indexes(rho)) {\r\n\t\t\tparams[i].rank = ctr;\r\n\t\t\t//cout << i << \" \" << rho[i] << \" \" << params[i].rank << endl; // this is just to show values from largest to smallest; and the location of value (i) in the vector  \r\n\t\t\tctr++;\r\n\t\t}\r\n\t\t//for checking if the code works\r\n\t\t/*for (p = 0; p < PARTICLE_SIZE; p++){\r\n\t\tcout << rho[p] << \" \" << params[p].rank << endl;\r\n\t\t}*/\r\n\t\t// next step-replenish\r\n\t\t//----------------- keeppers\r\n\r\n\t\tint ctr_cc = 0;\r\n\r\n\r\n\t\tfor (p = 0; p < PARTICLE_SIZE; p++){\r\n\t\t\tif (params[p].rank >= N_drop){\r\n\t\t\t\tparam_keepers[ctr_cc] = params[p];\r\n\t\t\t\tctr_cc++;\r\n\t\t\t}\r\n\t\t\tif (params[p].rank == N_drop){\r\n\t\t\t\te_next = rho[p];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tcout << \"next \" << e_next << endl;\r\n\t\t/*\r\n\t\tmyFile.open(\"params.txt\", ios::app);\r\n\r\n\t\tfor (i = 0; i < ctr_cc; i++){\r\n\t\tmyFile << i << \"\\t\" << param_keepers[i].rank << \"\\t\" << param_keepers[i].beta << \"\\t\" << param_keepers[i].beta_sigma << \"\\t\" << param_keepers[i].jv_sur << \"\\t\" << param_keepers[i].k << \"\\t\" << param_keepers[i].larv_mor << \"\\t\" << param_keepers[i].x0 << \"\\t\" << param_keepers[i].error_N << \"\\t\";\r\n\t\tfor (j = 0; j < no_loc; j++){\r\n\t\tmyFile << param_keepers[i].alpha[j] << \"\\t\" << param_keepers[i].detect[j] << \"\\t\";\r\n\t\t}\r\n\t\tmyFile << endl;\r\n\t\t}\r\n\t\tmyFile.close();\r\n\t\t*/\r\n\t\t// replensihing\r\n\r\n\t\t// parallel this part\r\n\t\tDIM = 13;\r\n\r\n\t\t// variance-covariance of\r\n\r\n\t\tMatrixXd S(DIM, DIM);\r\n\t\tMatrixXd temp_mat(PARTICLE_SIZE - N_drop, DIM);\r\n\t\tstruct2mat(param_keepers, temp_mat, PARTICLE_SIZE - N_drop);\r\n\r\n\t\tMatrixXd x_bar = temp_mat.rowwise() - temp_mat.colwise().mean();\r\n\t\tS = 2 * (x_bar.adjoint() * x_bar) / double(temp_mat.rows());\r\n\t\t// end of mean and variance-cov matrix\r\n\r\n\t\t// code is fine to here\r\n#pragma omp parallel for schedule(dynamic, 1) private(i,p) firstprivate(ctr_cc)shared(START_YR, no_loc, chlo_dat, obs_abundance, PARTICLE_SIZE, bins, no_obs_rec, temp_mth_reef,ini_leng, SIM_LENGTH, INI_SEX_RAT, DIM, S, N_drop, param_keepers, params, e_max, e_next, tck, RN,i_acc, rho, eng)\r\n\t\tfor (p = 0; p < PARTICLE_SIZE; p++){\r\n\r\n\t\t\tdouble sum_stats;\r\n\t\t\tint flg = 0; // flg ==1 means population extinct\r\n\t\t\tstruct parameters *temp_params = new struct parameters[1];\r\n\t\t\tstruct mth_out *out = new struct mth_out[SIM_LENGTH*no_loc]; // store the monthly records\r\n\r\n\t\t\t//cout << \"bf \" << rho[p] << endl;\r\n\t\t\t//int seed = boost::uuids::detail::seed_rng()();\r\n\r\n\t\t\t//eng[omp_get_thread_num()].seed(seed);\r\n\r\n\t\t\tif (params[p].rank <= N_drop){// && tck< RN){ // replenish N_drop\r\n\t\t\t\tint flag = 0;\r\n\t\t\t\tint k = 0; \r\n\r\n\t\t\t\tdo{// line 2.5 to 2.12\r\n#pragma omp atomic\r\n\t\t\t\t\tk++; \r\n#pragma omp atomic\r\n\t\t\t\t\ttck++;\r\n\t\t\t\t\t// step 1: select from keepers\r\n\t\t\t\t\tint oo;\r\n\t\t\t\t\t// q(.|theta)- line 2.4 \r\n\t\t\t\t\t// mean vector\r\n\t\t\t\t\t// draws - equal probability\r\n\t\t\t\t\tVectorXd mean(DIM);\r\n\r\n\t\t\t\t\too = dist.uniform_int_dis(0, ctr_cc - 1, eng[omp_get_thread_num()]);// ctr-1 is total number of particles kept\r\n\t\t\t\t\t//#pragma omp critical\r\n\t\t\t\t\tstruct2array(param_keepers, mean, oo);\r\n\r\n\t\t\t\t\t// draw theta **\r\n\r\n\t\t\t\t\tEigenMultivariateNormal<double> normX(mean, S, boost::uuids::detail::seed_rng()());\r\n\t\t\t\t\tint flgg = 0;\r\n\t\t\t\t\tMatrixXd temp(DIM, 1);\r\n\t\t\t\t\twhile (flgg == 0){\r\n\t\t\t\t\t\ttemp = normX.samples(1);\r\n\t\t\t\t\t\tflgg = check_array(temp, DIM);\r\n\t\t\t\t\t}\r\n\t\t\t\t\t/*\r\n#pragma omp critical\r\n\t\t\t\t\t{\r\n\t\t\t\t\tcout << \"p \" << p << \" prop \" << temp << endl;\r\n\t\t\t\t\tcout << \"oo \" << oo << \"mean\" << mean << endl;\r\n\t\t\t\t\t}\r\n\t\t\t\t\t*/\r\n\r\n\t\t\t\t\t//cout << \"mean\" <<  mean << \"\\t\" << \"temp\" << temp << endl;\r\n\t\t\t\t\t// work out the MH ratio\r\n\t\t\t\t\tdouble MH;\r\n\t\t\t\t\t// order is extremely important \r\n\r\n\r\n\t\t\t\t\tdouble top = lognormal_pdf_ln(DIS_MEAN, DIS_STD, temp(0)) + lognormal_pdf_ln(DIS_MEAN, DIS_STD, temp(1)) + lognormal_pdf_ln(DIS_MEAN, DIS_STD, temp(2)) + unif_pdf_ln(BETA_MIN, BETA_MAX, temp(3)) + lognormal_pdf_ln(BETA_SIG_MEAN, BETA_SIG_STD, temp(4)) - 3 * log(DETECT_HI - DETECT_LO) + unif_pdf_ln(VAR_ERROR_MIN, VAR_ERROR_MAX, temp(8)) + lognormal_pdf_ln(JUV_SUR_MEAN, JUV_SUR_STD, temp(9)) + lognormal_pdf_ln(ADULT_MOR_K_MEAN, ADULT_MOR_K_STD, temp(10)) + lognormal_pdf_ln(LAR_DAILY_MOR_MEAN, LAR_DAILY_MOR_STD, 1 - temp(11)) + lognormal_pdf_ln(ADULT_MOR_X0_MEAN, ADULT_MOR_X0_STD, temp(12)) + multivariate_normal_ln_pdf(temp, S, mean);\r\n\r\n\t\t\t\t\tdouble bot = lognormal_pdf_ln(DIS_MEAN, DIS_STD, mean(0)) + lognormal_pdf_ln(DIS_MEAN, DIS_STD, mean(1)) + lognormal_pdf_ln(DIS_MEAN, DIS_STD, mean(2)) + unif_pdf_ln(BETA_MIN, BETA_MAX, mean(3)) + lognormal_pdf_ln(BETA_SIG_MEAN, BETA_SIG_STD, mean(4)) - 3 * log(DETECT_HI - DETECT_LO) + unif_pdf_ln(VAR_ERROR_MIN, VAR_ERROR_MAX, mean(8)) + lognormal_pdf_ln(JUV_SUR_MEAN, JUV_SUR_STD, mean(9)) + lognormal_pdf_ln(ADULT_MOR_K_MEAN, ADULT_MOR_K_STD, mean(10)) + lognormal_pdf_ln(LAR_DAILY_MOR_MEAN, LAR_DAILY_MOR_STD, 1 - mean(11)) + lognormal_pdf_ln(ADULT_MOR_X0_MEAN, ADULT_MOR_X0_STD, mean(12)) + multivariate_normal_ln_pdf(mean, S, temp);\r\n\r\n\t\t\t\t\tMH = exp(top - bot);\r\n\t\t\t\t\t/*\r\n#pragma omp critical\r\n\t\t\t\t\t{\r\n\t\t\t\t\tcout << \" t \" << top << \" b \" << bot;\r\n\t\t\t\t\tcout << \" p \" << p << \" MH \" << MH << endl;\r\n\t\t\t\t\t}\r\n\t\t\t\t\t*/\r\n\r\n\t\t\t\t\tif (MH > 1){ MH = 1; }// else MH is MH\r\n\r\n\t\t\t\t\tif (MH > dist.uniform_real_dis(0, 1, eng[omp_get_thread_num()])){\r\n\t\t\t\t\t\tarray2struct(temp_params, temp, 0);\r\n\t\t\t\t\t\t// simulate data\r\n\t\t\t\t\t\tstruct reef_month *mth_reef = new struct reef_month[no_loc];\r\n\r\n\t\t\t\t\t\tfor (i = 0; i < no_loc; i++){\r\n\t\t\t\t\t\t\tmth_reef[i] = temp_mth_reef[i];\r\n\t\t\t\t\t\t\tmth_reef[i].yr = START_YR;\r\n\t\t\t\t\t\t\tmth_reef[i].mth = START_MTH;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t/*\r\n#pragma omp critical\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\tcout << params[p].beta << \" \" << params[p].beta_sigma << \" \" << params[p].error_N << \" \" << params[p].jv_sur << \" \" << params[p].k << \" \" << params[p].larv_mor << \" \" << params[p].rank << \" \";\r\n\r\n\t\t\t\t\t\tfor (j = 0; j < no_loc; j++){\r\n\t\t\t\t\t\tcout << params[p].detect[j] << \" \" << params[p].alpha[j] << \" \";\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tcout << endl;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t*/\r\n\t\t\t\t\t\tProcessModel(&temp_params[0], mth_reef, ini_leng, obs_abundance, bins, no_loc, SIM_LENGTH, INI_SEX_RAT, max_thread, no_obs_rec, sum_stats, flg, eng[omp_get_thread_num()], e_max, e_next, TOLERANCE_S, out);\r\n\r\n\t\t\t\t\t\t// if summary stat is less than E_Max\r\n\t\t\t\t\t\tif (sum_stats < e_next && flg == 0){\r\n#pragma omp critical\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tcout << \" p \" << p << \" sum_stat \" << sum_stats << \" flag \" << flg << endl;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tif (e_next < TOLERANCE_S){\r\n#pragma omp critical\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tmyFile.open(\"res_out.txt\", ios::app);\r\n\t\t\t\t\t\t\t\t\tfor (j = 0; j < no_loc*SIM_LENGTH; j++){\r\n\t\t\t\t\t\t\t\t\t\tmyFile << p << \"\\t\" << out[j].reef_ID << \"\\t\" << out[j].year << \"\\t\" << out[j].mth << \"\\t\" << out[j].pop_size << \"\\t\" << out[j].no_female << \"\\t\" << out[j].no_male << \"\\t\" << out[j].l15 << \"\\t\" << out[j].l1525 << \"\\t\" << out[j].l2540 << \"\\t\" << out[j].l40p << endl;\r\n\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\tmyFile.close();\r\n\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tflag = 1;\r\n\t\t\t\t\t\t\tarray2struct(params, temp, p);\r\n\t\t\t\t\t\t\trho[p] = sum_stats;\r\n#pragma omp atomic\r\n\t\t\t\t\t\t\ti_acc++;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse{\r\n\t\t\t\t\t\t\tflag = 0;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tdelete[]mth_reef;\r\n\t\t\t\t\t\tmth_reef = nullptr;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse{ // MH else\r\n\t\t\t\t\t\tflag = 0;\r\n\t\t\t\t\t}\r\n\t\t\t\t}while(flag == 0 && k < R);\r\n\r\n\t\t\t} // end if: replenish N_drop\r\n\r\n\t\t\tdelete[] temp_params;\r\n\t\t\ttemp_params = nullptr;\r\n\t\t\tdelete[] out;\r\n\t\t\tout = nullptr;\r\n\t\t} // end of p iteration- replenishing \r\n\t\tcout << \" icc \" << i_acc << endl;\r\n\r\n\t\tp_acc = (double)i_acc / RN;\r\n\t\tR = log(0.1) / log(1 - p_acc);\r\n\r\n\t\t// update e_max;\r\n\t\tcout << \"acceptance ratio \" << p_acc << endl;\r\n\t\tcout << \" R \" << R << endl;\r\n\t\tcout << endl;\r\n\t\tu++;\r\n\t\tdouble uu = (double)i_acc / tck;\r\n\t\tmyFile.open(\"acc_rat.txt\", ios::app);\r\n\t\tmyFile << u << \" \" << uu << \" \" << i_acc << \" \" << R << \" \" << p_acc << \" \"<< RN << endl;\r\n\t\tmyFile.close();\r\n\r\n\t\te_max = *max_element(rho.begin(), rho.end());\r\n\t\tcout << \"e_max\" << e_max << endl;\r\n\r\n\t} while (e_max > TOLERANCE_S);// && tck < RN);\r\n\r\n\r\n\tauto end = std::chrono::system_clock::now();\r\n\tauto elapsed = end - start;\r\n\tmyFile.open(\"walltime.txt\", ios::app);\r\n\tmyFile << elapsed.count() << '\\n';\r\n\tmyFile.close();\r\n\r\n\r\n\t////-----------------\r\n\tmyFile.open(\"params.txt\", ios::app);\r\n\r\n\tfor (p = 0; p < PARTICLE_SIZE; p++){\r\n\t\tmyFile << p << \"\\t\" << rho[p] << \"\\t\";\r\n\r\n\t\tfor (i = 0; i < no_loc; i++){\r\n\t\t\tmyFile << params[p].alpha[i] << \"\\t\";\r\n\t\t}\r\n\r\n\t\tmyFile << params[p].beta << \"\\t\" << params[p].beta_sigma << \"\\t\";\r\n\t\tfor (i = 0; i < no_loc; i++){\r\n\t\t\tmyFile << params[p].detect[i] << \"\\t\";\r\n\t\t}\r\n\t\tmyFile << params[p].error_N << \"\\t\" << params[p].jv_sur << \"\\t\" << params[p].k << \"\\t\" << params[p].larv_mor << \"\\t\" << params[p].x0 << \"\\t\" << endl;\r\n\t}\r\n\tmyFile.close();\r\n\r\n\tcout << \"Congratulations XXOO!!\" << endl;\r\n\r\n\tdelete[] ini_leng;\r\n\tdelete[] temp_mth_reef;\r\n\tdelete[] params;\r\n\tdelete[] wat_temp;\r\n\tdelete[] connect;\r\n\tdelete[] chlo_dat;\r\n\tdelete[] obs_abundance;\r\n\tdelete[] param_keepers;\r\n\r\n\tparam_keepers = nullptr;\r\n\tobs_abundance = nullptr;\r\n\tchlo_dat = nullptr;\r\n\r\n\tconnect = nullptr;\r\n\twat_temp = nullptr;\r\n\tparams = nullptr;\r\n\r\n\tini_leng = nullptr;\r\n\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "96aeb44b18453690dc6e12e008d0f682f7e5fc8a", "size": 29842, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "COTSmodel.cpp", "max_stars_repo_name": "cewels/Bayesian-CoTS-model-", "max_stars_repo_head_hexsha": "13db64cbe510c1a9f8533adf839b5a8cae1b1eff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "COTSmodel.cpp", "max_issues_repo_name": "cewels/Bayesian-CoTS-model-", "max_issues_repo_head_hexsha": "13db64cbe510c1a9f8533adf839b5a8cae1b1eff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "COTSmodel.cpp", "max_forks_repo_name": "cewels/Bayesian-CoTS-model-", "max_forks_repo_head_hexsha": "13db64cbe510c1a9f8533adf839b5a8cae1b1eff", "max_forks_repo_licenses": ["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.5173095945, "max_line_length": 645, "alphanum_fraction": 0.5955029824, "num_tokens": 9131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.2538594500315461}}
{"text": "/*\r\n *\r\n * Copyright (C) 2015 Mohammad Javad Dousti, Qing Xie, and Massoud Pedram, SPORT lab,\r\n * University of Southern California. All rights reserved.\r\n *\r\n * Please refer to the LICENSE file for terms of use.\r\n *\r\n*/\r\n#include \"headers/rc_utils.h\"\r\n#include <omp.h>\r\n//#include <boost/numeric/odeint/external/openmp/openmp.hpp>\r\n//#include <thrust/device_vector.h>\r\n//#include <boost/numeric/odeint/external/thrust/thrust_algebra.hpp>\r\n//#include <boost/numeric/odeint/external/thrust/thrust_operations.hpp>\r\n//#include <boost/numeric/odeint/external/mkl/mkl_operations.hpp>\r\n\r\n//double **RCutils::matrix;\r\n//double *RCutils::invC_vector;\r\n//double **RCutils::A_matrix;\r\n\r\ndouble *RCutils::P_vector;\r\nint RCutils::n;\r\nint** RCutils::a_matrix_indices;\r\ndouble** RCutils::a_matrix_values;\r\n\r\n/* For Eigen */\r\n//SparseMatrix<double> RCutils::a_matrix;\r\n//VectorXd RCutils::p_vector;\r\n\r\n\r\n#if USE_GPU==1\r\nvoid RCutils::checkGPUStatus(culaStatus status){\r\n    char buf[256];\r\n\r\n    if(!status)\r\n        return;\r\n\r\n    culaGetErrorInfoString(status, culaGetErrorInfo(), buf, sizeof(buf));\r\n    cout<<buf<<endl;\r\n\r\n    culaShutdown();\r\n    exit(-1);\r\n}\r\n\r\nvoid RCutils::gpuSolveSteady(double **matrix, int N, double* P_vector, double *T_vector){\r\n    int NRHS = 1;\r\n\r\n    culaStatus status;\r\n\r\n    culaDouble* A = NULL;\r\n    culaInt* IPIV = NULL;\r\n\r\n\r\n    cout<<\"--------------------\"<<endl;\r\n    cout<<\" Calling GPU Solver\"<<endl;\r\n    cout<<\"--------------------\"<<endl;\r\n\r\n    cout<<\"Allocating Matrices...\"<<endl;\r\n    A = (culaDouble*)malloc(N*N*sizeof(culaDouble));\r\n    IPIV = (culaInt*)malloc(N*sizeof(culaInt));\r\n    if(!A || !IPIV){\r\n        cerr<<\"Cannot allocate contiguous memory for solving the linear set of equations using GPU.\"<<endl;\r\n    \texit(-1);\r\n    }\r\n\r\n    cout<<\"Initializing CULA...\"<<endl;\r\n    status = culaInitialize();\r\n    RCutils::checkGPUStatus(status);\r\n\r\n\tfor (int i = 0; i < N; i++){\r\n\t    memmove(&A[i*N], matrix[i], sizeof(double) * N);\r\n\t}\r\n\r\n    //Making a copy of P_vector into T_vector; This is required per specification\r\n    memcpy(T_vector, P_vector, N*sizeof(culaDouble));\r\n\r\n    //memset(IPIV, 0, N*sizeof(culaInt));\r\n\r\n    cout<<\"Calling the solver...\"<<endl;\r\n    //General Solver\r\n//\tstatus = culaDgesv(N, NRHS, A, N, IPIV, T_vector, N);\r\n    //Assuming that A is a positive-definite matrix\r\n    status = culaDposv('U', N, NRHS, A, N, T_vector, N);\r\n    if(status == culaInsufficientComputeCapability){\r\n        cout<<\"No Double precision support available.\"<<endl;\r\n        delete(A);\r\n        delete(IPIV);\r\n        culaShutdown();\r\n        return;\r\n    }\r\n    RCutils::checkGPUStatus(status);\r\n\r\n\r\n    cout<<\"Shutting down CULA...\"<<endl<<endl;\r\n    culaShutdown();\r\n\r\n    delete(A);\r\n    delete(IPIV);\r\n}\r\n#else\r\n\r\n/**\r\n * This solver uses Eigen library to solve the linear set of equations\r\n */\r\nvoid RCutils::cpuSolveSteady(double **matrix, int N, double* P_vector, vector<double>& T_vector){\r\n//\tEigen::setNbThreads(8);\r\n//\tMatrixXd A = MatrixXd(N,N);\r\n\r\n\tSparseMatrix<double> A(N,N);\r\n\tvector<Triplet<double> > triplet;\r\n\r\n\tVectorXd b = VectorXd(N);\r\n\t//SparseVector<double> b(N);\r\n\tfor (int i = 0; i < N; i++){\r\n\t\tfor(int j=0; j<N; j++){\r\n\t\t\t//A(i,j)=matrix[i][j];\r\n\t\t\tif (matrix[i][j]!=0)\r\n\t\t\t\ttriplet.push_back(Triplet<double> (i,j,matrix[i][j]));\r\n\t\t}\r\n\t\tb(i)=P_vector[i];\r\n\t}\r\n\tA.setFromTriplets(triplet.begin(), triplet.end());\r\n\t\r\n\tcout<<\"Calling the solver...\"<<endl;\r\n\tSimplicialCholesky<SparseMatrix<double> > chol(A);\r\n\r\n\tb = chol.solve(b);\r\n\r\n\t//b=A.llt().solve(b);\r\n//\tVectorXd x =  b;\r\n\r\n\tfor (int i = 0; i < N; i++){\r\n\t\tT_vector[i]=b(i);\r\n\t}\r\n}\r\n\r\n\r\nvoid RCutils::thermEq(const state_type &T_vector, state_type &dTdt, double t){\r\n// Code written for Eigen\r\n//   const double *PtState = &T_vector[0];\r\n//   double *PtChange = &dTdt[0];\r\n//\r\n//   typedef Map<const VectorXd> MapTypeConst; // a read-only map\r\n//   typedef Map<VectorXd> MapType;\r\n//\r\n//\r\n//   MapTypeConst States(PtState, n);\r\n//   MapType Changes(PtChange, n);\r\n//\r\n//   Changes = p_vector - (a_matrix * States);\r\n\r\n\r\n\t#pragma omp parallel for schedule(auto) num_threads(4)\r\n//\t#pragma omp parallel for schedule(runtime)\r\n\tfor(int i=0; i<n; i++){\r\n\t\tdTdt[i]=(P_vector[i]);\r\n\r\n\t\tfor(int j=0; j<n; j++){\r\n\t\t\tif (a_matrix_indices[i][j]!=-1){\r\n\t\t\t\tdTdt[i]-= a_matrix_values[i][j] * T_vector[a_matrix_indices[i][j]];\r\n\t\t\t}else\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\r\n\t}\r\n\t/*\r\n\t * GPU:\r\n\t *  \ttypedef thrust::device_vector<double> state_type;\r\n\t * \t\trunge_kutta4< state_type , double , state_type , double , thrust_algebra ,\tthrust_operations > rk4;\r\n\t *\r\n\t */\r\n\r\n\r\n\r\n\r\n\t//\t\tfor(int j=0; j<n; j++){\r\n\t//\t\t\tif (A_matrix[i][j]!=0){\r\n\t//\t\t\t\tdTdt[i]-=(A_matrix[i][j]*T_vector[j]);\r\n\t//\t\t\t}\r\n\t//\t\t}\r\n\r\n\r\n}\r\n\r\nvoid RCutils::writeTemp( const state_type &T_vector , const double t ){\r\n\tcout<<t<<\":\\t\"<<T_vector[0]-273.15<<\" C\"<<\"\\n\";\r\n}\r\n\r\n\r\n//template<std::size_t element_no>\r\nvoid RCutils::cpuSolveTransient(int n, double ** A_matrix, int** a_matrix_indices, double** a_matrix_values,\r\n\t\tdouble *invC_vector, double* P_vector, vector<double> &T_vector, double time_start, double time_end){\r\n\r\n\tRCutils::a_matrix_indices=a_matrix_indices;\r\n\tRCutils::a_matrix_values=a_matrix_values;\r\n\tRCutils::n = n;\r\n\r\n\t/* Calculating P' = C^-1 * P  */\r\n\tRCutils::P_vector = Utils::vectorAlloc(n);\r\n\tUtils::diagmatvectmult(RCutils::P_vector, invC_vector, &P_vector[0], n);\r\n\r\n\r\n\tcout<<T_vector[0]-273.15<<\" C\"<<endl;\r\n\r\n\r\n\t// For Eigen\r\n//\ta_matrix=SparseMatrix<double>(n,n);\r\n//\tp_vector = VectorXd(n);\r\n//\r\n//\tvector<Triplet<double> > triplet;\r\n//\tfor (int i = 0; i < n; i++){\r\n//\t\tfor(int j=0; j<n; j++){\r\n//\t\t\tif (A_matrix[i][j]!=0){\r\n//\t\t\t\ttriplet.push_back(Triplet<double> (i, j, A_matrix[i][j]));\r\n//\t\t\t}\r\n//\t\t}\r\n//\t\tp_vector(i)=RCutils::P_vector[i];\r\n//\t}\r\n//\ta_matrix.setFromTriplets(triplet.begin(), triplet.end());\r\n\r\n\r\n\r\n\t//integrate( system , x0 , t0 , t1 , dt )\r\n\t//http://headmyshoulder.github.io/odeint-v2/doc/boost_numeric_odeint/odeint_in_detail/integrate_functions.html\r\n\r\n\t/* use the scratch pad vector to find (inv_A)*POWER */\r\n\t//vdMul(n, &P_vector[0], invC_vector, &P_vector[0]);\r\n\r\n\tdouble dt = 0.00001;\r\n\r\n//\trunge_kutta_cash_karp54 is better than runge_kutta_dopri5\r\n\ttypedef  runge_kutta_cash_karp54 < state_type > error_stepper_type;\r\n\ttypedef controlled_runge_kutta< error_stepper_type > controlled_stepper_type;\r\n\tcontrolled_stepper_type controlled_stepper;\r\n\r\n//    adams_bashforth_moulton< 2 , state_type, double, state_type, double, openmp_range_algebra > stepper_adams;\r\n\r\n//    int chunk_size = T_vector.size()/omp_get_max_threads();\r\n//    omp_set_schedule( omp_sched_static , chunk_size );\r\n\r\n\tstruct timespec start, end;\r\n\r\n\tcout<<\"Calling the solver...\"<<endl;\r\n\tclock_gettime(CLOCK_MONOTONIC, &start);\r\n\r\n    integrate_adaptive( make_controlled( 5E-1 , 1E-1 , error_stepper_type() ) , thermEq , T_vector , time_start, time_end , dt);\r\n\r\n\r\n//\tintegrate_adaptive(stepper_adams , thermEq , T_vector , time_start, time_end , dt);\r\n\r\n//\tintegrate_adaptive( make_controlled<error_stepper_type>( 1E-3 , 1E-3) , thermEq , T_vector , time_start, time_end , dt);\r\n//  integrate_adaptive(stepper_mew , thermEq , T_vector , time_start, time_end , dt);\r\n//\tintegrate_adaptive(controlled_stepper, thermEq , T_vector , time_start, time_end , dt);\r\n\r\n\tclock_gettime(CLOCK_MONOTONIC, &end);\r\n\tdouble elapsed = (end.tv_sec - start.tv_sec);\r\n\telapsed += (end.tv_nsec - start.tv_nsec) / 1e9;\r\n\tcout<<endl<<\"ODE runtime: \"<<elapsed<<\" s\"<<endl;\r\n\r\n\tcout<<T_vector[0]-273.15<<\" C\"<<endl;\r\n\r\n\tUtils::vectorDealloc(RCutils::P_vector);\r\n\r\n//\tBaseline: HotSpot code\r\n//\tdouble *power = Utils::vectorAlloc(n);\r\n//\t/* use the scratch pad vector to find (inv_A)*POWER */\r\n//    diagmatvectmult(power, invC_vector, &P_vector[0], n);\r\n//\r\n//    /* Obtain temp at time (t+time_elapsed).\r\n//     * Instead of getting the temperature at t+time_elapsed directly, we do it\r\n//     * in multiple steps with the correct step size at each time\r\n//     * provided by rk4\r\n//     */\r\n//\tint i=0;\r\n//\tdouble h, time_elapsed = 0.1;\r\n//\r\n//\tfor (double t = 0, new_h = 1e-7 ; t < time_elapsed && new_h >= 1e-7*1.0e-6; t+=h) {\r\n//        h = new_h;\r\n//\r\n//        /* the slope function callback is typecast accordingly */\r\n//        new_h = rk4(A_matrix, &T_vector[0], &P_vector[0], n, &h, &T_vector[0], (slope_fn_ptr) slope_fn_block);\r\n//        new_h = std::min(new_h, time_elapsed-t-h);\r\n//    \tcout << t << \":\\t\" << T_vector[0]-273.15<<\" C\"<<endl;\r\n//        i++;\r\n//    }\r\n}\r\n\r\n\r\n#endif\r\ndouble RCutils::calcThermalConductivity(double k, double thickness, double area){\r\n\tif (thickness==0){\r\n\t\tcerr<<\"The thickness of an element cannot be zero.\"<<endl;\r\n\t\texit(-1);\r\n\t}\r\n\treturn k * area / thickness;\r\n}\r\n\r\n\r\ndouble RCutils::calcSubComponentCapacitance(SubComponent *sc){\r\n\tdouble volume = sc->getLength() * sc->getWidth() * sc->getHeight();\r\n\r\n\tif (volume==0)\r\n\t\tcout<<sc->getName() << \" has nil volume.\"<<endl;\r\n\r\n\telse if (sc->getComponent()->getMaterial()->getSpecificHeat()==0)\r\n\t\tcout<<sc->getName() << \" has nil specific heat.\"<<endl;\r\n\r\n\telse if (sc->getComponent()->getMaterial()->getDensity()==0)\r\n\t\tcout<<sc->getName() << \" has nil density.\"<<endl;\r\n\r\n\r\n\treturn C_FACTOR * sc->getComponent()->getMaterial()->getSpecificHeat() *\r\n\t\t\tsc->getComponent()->getMaterial()->getDensity() * volume;\r\n}\r\n\r\n\r\ndouble RCutils::calcAmbientResistance(double h, double area){\r\n\treturn 1/(h * area);\r\n}\r\n\r\ndouble RCutils::overallParallelConductivity(double k1, double k2){\r\n\treturn (k1 * k2)/( k1 + k2 );\r\n}\r\n\r\n\r\nbool RCutils::touchesAirInXDir(SubComponent *sc, Device* device){\r\n\tif (Utils::eq(sc->getX(), device->getX()) ||\r\n\t\t\tUtils::eq(sc->getX() +  sc->getLength(), device->getX() +  device->getLength()))\r\n\t\treturn true;\r\n\telse\r\n\t\treturn false;\r\n}\r\n\r\nbool RCutils::touchesAirInYDir(SubComponent *sc, Device* device){\r\n\tif (Utils::eq(sc->getY(), device->getY()) ||\r\n\t\t\tUtils::eq(sc->getY() +  sc->getWidth(), device->getY() +  device->getWidth())){\r\n\t\treturn true;\r\n\t}else{\r\n\t\treturn false;\r\n\t}\r\n}\r\n\r\nbool RCutils::touchesAirFromTopBot(SubComponent *sc, Device* device){\r\n\tif (Utils::eq(sc->getZ() , device->getZ()) ||\r\n\t\t\tUtils::eq(sc->getZ() + sc->getHeight() , device->getZ() +  device->getHeight()))\r\n\t\treturn true;\r\n\telse\r\n\t\treturn false;\r\n}\r\n\r\ndouble RCutils::calcConductanceToAmbient(SubComponent *sc, Device* device){\r\n\tdouble commonArea;\r\n\tdouble t1=0;\r\n\tdouble k;\r\n\tdouble K=0;\r\n\tdouble Kx=0, Ky=0, Kz=0, Rx, Ry, Rz;\r\n//\tdouble h = 10 * 1.15; //\tW/m^2/K, from <http://www.engineeringtoolbox.com/convective-heat-transfer-d_430.html>\r\n\tdouble h = 10 * 1.15;\r\n\tif (touchesAirFromTopBot(sc, device)){\t//Touches air from top or bottom\r\n\t\tt1 = sc->getHeight() / 2;\r\n\t\tcommonArea = sc->getLength() * sc->getWidth();\r\n//\t\tcout<<p1->getName() << \" and \"<<\" have XY common area to ambient: \"<<commonArea<<endl;\r\n\r\n\t\tk = sc->getComponent()->getMaterial()->getNormalConductivity();\r\n\r\n\t\tKz= RCutils::calcThermalConductivity(k, t1, commonArea);\r\n//\t\tcout<<RCutils::calcThermalConductivity(k1, t1, commonArea)<<endl;\r\n\t\tRz = RCutils::calcAmbientResistance(h, commonArea);\r\n\t\tKz = RCutils::overallParallelConductivity(Kz, 1/Rz);\r\n\t}\r\n\tif (touchesAirInXDir(sc, device)){\t//Touches air from the X side\r\n\t\tt1 = sc->getLength() / 2;\r\n\t\tcommonArea = sc->getWidth() * sc->getHeight();\r\n//\t\tcout<<p1->getName() << \" and \"<<\" have YZ common area to ambient: \"<<commonArea<<endl;\r\n\r\n\t\t//Setting the k1 value to the proper value if the planar conductivity differs from the normal conductivity\r\n\t\tif (sc->getComponent()->getMaterial()->hasPlanarConductivity())\r\n\t\t\tk = sc->getComponent()->getMaterial()->getPlanarConductivity();\r\n\t\telse\r\n\t\t\tk = sc->getComponent()->getMaterial()->getNormalConductivity();\r\n\r\n\r\n\t\tKx = RCutils::calcThermalConductivity(k, t1, commonArea);\r\n\t\tRx = RCutils::calcAmbientResistance(h, commonArea);\r\n\t\tKx = RCutils::overallParallelConductivity(Kx, 1/Rx);\r\n\t}\r\n\tif (touchesAirInYDir(sc , device)){\t\t//Touches air from the Y side\r\n\r\n\t\tt1 = sc->getWidth() / 2;\r\n\t\tcommonArea = sc->getLength() * sc->getHeight();\r\n//\t\tcout<<p1->getName() << \" and \"<<\" have XZ common area to ambient: \"<<commonArea<<endl;\r\n\r\n\t\t//Setting the k1 value to the proper value if the planar conductivity differs from the normal conductivity\r\n\t\tif (sc->getComponent()->getMaterial()->hasPlanarConductivity())\r\n\t\t\tk = sc->getComponent()->getMaterial()->getPlanarConductivity();\r\n\t\telse\r\n\t\t\tk = sc->getComponent()->getMaterial()->getNormalConductivity();\r\n\r\n\t\tKy = RCutils::calcThermalConductivity(k, t1, commonArea);\r\n\t\tRy = RCutils::calcAmbientResistance(h, commonArea);\r\n\t\tKy = RCutils::overallParallelConductivity(Ky, 1/Ry);\r\n\t}\r\n\treturn K= Kx + Ky + Kz;\r\n}\r\n\r\ndouble RCutils::calcCommonConductance(SubComponent *sc1, SubComponent *sc2){\r\n\tdouble commonArea;\r\n\tdouble t1=0, t2=0;\r\n\tdouble k1, k2;\r\n\r\n\t// common area in the Y & Z planes\r\n\tdouble commonX, commonY, commonZ;\r\n\r\n\tcommonX= min(sc1->getX()+sc1->getLength() , sc2->getX()+sc2->getLength()) - max(sc1->getX() , sc2->getX());\r\n\tcommonY= min(sc1->getY()+sc1->getWidth() , sc2->getY()+sc2->getWidth()) - max(sc1->getY() , sc2->getY());\r\n\tcommonZ= min(sc1->getZ()+sc1->getHeight() , sc2->getZ()+sc2->getHeight()) - max(sc1->getZ() , sc2->getZ());\r\n\r\n\r\n\tif ((Utils::eq(sc1->getX() + sc1->getLength() , sc2->getX()) ||\r\n\t\tUtils::eq(sc2->getX() + sc2->getLength() , sc1->getX())) && commonZ>0 && commonY>0){\r\n\t\tcommonArea = commonY * commonZ;\r\n\t\t t1 = sc1->getLength() / 2;\r\n\t\t t2 = sc2->getLength() / 2;\r\n\r\n\t\t //using planar thermal conductivity if the material has different value for it\r\n\t\t if (sc1->getComponent()->getMaterial()->hasPlanarConductivity()){\r\n\t\t\t k1 = sc1->getComponent()->getMaterial()->getPlanarConductivity();\r\n\t\t }else{\r\n\t\t\t k1 = sc1->getComponent()->getMaterial()->getNormalConductivity();\r\n\t\t }\r\n\t\t if (sc2->getComponent()->getMaterial()->hasPlanarConductivity()){\r\n\t\t\t k2 = sc2->getComponent()->getMaterial()->getPlanarConductivity();\r\n\t\t }else{\r\n\t\t\t k2 = sc2->getComponent()->getMaterial()->getNormalConductivity();\r\n\t\t }\r\n//\t\t cout<<\"Common area (YZ) btn \"<<p1->getName()<<\" and \"<<p2->getName()<<\" is \"<<commonArea<<endl;\r\n\t}else if ((Utils::eq(sc1->getY() + sc1->getWidth() , sc2->getY()) ||\r\n\t\t\tUtils::eq(sc2->getY() + sc2->getWidth() , sc1->getY())) && commonX>0 && commonZ>0){\r\n\t\tcommonArea = commonX * commonZ;\r\n\t\t t1 = sc1->getWidth() / 2;\r\n\t\t t2 = sc2->getWidth() / 2;\r\n\r\n\t\t //using planar thermal conductivity if the material has different value for it\r\n\t\t if (sc1->getComponent()->getMaterial()->hasPlanarConductivity()){\r\n\t\t\t k1 = sc1->getComponent()->getMaterial()->getPlanarConductivity();\r\n\t\t }else{\r\n\t\t\t k1 = sc1->getComponent()->getMaterial()->getNormalConductivity();\r\n\t\t }\r\n\t\t if (sc2->getComponent()->getMaterial()->hasPlanarConductivity()){\r\n\t\t\t k2 = sc2->getComponent()->getMaterial()->getPlanarConductivity();\r\n\t\t }else{\r\n\t\t\t k2 = sc2->getComponent()->getMaterial()->getNormalConductivity();\r\n\t\t }\r\n//\t\t cout<<\"Common area (XZ) btn \"<<p1->getName()<<\" and \"<<p2->getName()<<\" is \"<<commonArea<<endl;\r\n\t}else if ((Utils::eq(sc1->getZ() + sc1->getHeight() , sc2->getZ()) ||\r\n\t\t\tUtils::eq(sc2->getZ() + sc2->getHeight(), sc1->getZ())) && commonX>0 && commonY>0){\r\n\t\tcommonArea = commonX * commonY;\r\n\t\tt1 = sc1->getHeight() / 2;\r\n\t\tt2 = sc2->getHeight() / 2;\r\n\r\n\t\t//using normal conductivity since it is in the vertical direction\r\n\t\t k1 = sc1->getComponent()->getMaterial()->getNormalConductivity();\r\n\t\t k2 = sc2->getComponent()->getMaterial()->getNormalConductivity();\r\n\r\n//\t\t cout<<\"Common area (XY) btn \"<<p1->getName()<<\" and \"<<p2->getName()<<\" is \"<<commonArea<<endl;\r\n\t}else{\r\n\t\tcommonArea = 0;\r\n\t\treturn 0;\r\n\t}\r\n\t//cout<<p1->getName() << \" and \"<<p2->getName() <<\" have common area: \"<<commonArea<<endl;\r\n\r\n\tdouble K1 = RCutils::calcThermalConductivity(k1, t1, commonArea);\r\n\tdouble K2 = RCutils::calcThermalConductivity(k2, t2, commonArea);\r\n\r\n\treturn RCutils::overallParallelConductivity(K1,K2);\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n/* compute the slope vector dy for the transient equation\r\n * dy + cy = p. useful in the transient solver\r\n */\r\nvoid slope_fn_block(double *y, double *p, double *dy, double **c, int n)\r\n{\r\n    /* for our equation, dy = p - cy */\r\n    int i;\r\n    double *t = Utils::vectorAlloc(n);\r\n    Utils::matvectmult(t, c, y, n);\r\n    for (i = 0; i < n; i++)\r\n        dy[i] = p[i]-t[i];\r\n    Utils::vectorDealloc(t);\r\n}\r\n\r\n\r\n/* slope function pointer - used as a call back by the transient solver */\r\ntypedef void (*slope_fn_ptr)(void *y, void *p, void *dy, double **c, int n);\r\n\r\n/* core of the 4th order Runge-Kutta method, where the Euler step\r\n * (y(n+1) = y(n) + h * k1 where k1 = dydx(n)) is provided as an input.\r\n * to evaluate dydx at different points, a call back function f (slope\r\n * function) is also passed as a parameter. Given values for y, and k1,\r\n * this function advances the solution over an interval h, and returns\r\n * the solution in yout. For details, see the discussion in \"Numerical\r\n * Recipes in C\", Chapter 16, from\r\n * http://www.nrbook.com/a/bookcpdf/c16-1.pdf\r\n */\r\nvoid rk4_core(double **c, double *y, double *k1, void *p, int n, double h, double *yout, slope_fn_ptr f)\r\n{\r\n\tint i;\r\n\tdouble *t, *k2, *k3, *k4;\r\n\tk2 = Utils::vectorAlloc(n);\r\n\tk3 = Utils::vectorAlloc(n);\r\n\tk4 = Utils::vectorAlloc(n);\r\n\tt = Utils::vectorAlloc(n);\r\n\r\n\t/* k2 is the slope at the trial midpoint (t) found using\r\n\t * slope k1 (which is at the starting point).\r\n\t */\r\n\t/* t = y + h/2 * k1 (t = y; t += h/2 * k1) */\r\n\tfor(i=0; i < n; i++)\r\n\t\tt[i] = y[i] + h/2.0 * k1[i];\r\n\t/* k2 = slope at t */\r\n\t(*f)(t, p, k2, c, n);\r\n\r\n\t/* k3 is the slope at the trial midpoint (t) found using\r\n\t * slope k2 found above.\r\n\t */\r\n\t/* t =  y + h/2 * k2 (t = y; t += h/2 * k2) */\r\n\tfor(i=0; i < n; i++)\r\n\t\tt[i] = y[i] + h/2.0 * k2[i];\r\n\t/* k3 = slope at t */\r\n\t(*f)(t, p, k3, c, n);\r\n\r\n\t/* k4 is the slope at trial endpoint (t) found using\r\n\t * slope k3 found above.\r\n\t */\r\n\t/* t =  y + h * k3 (t = y; t += h * k3) */\r\n\tfor(i=0; i < n; i++)\r\n\t\tt[i] = y[i] + h * k3[i];\r\n\t/* k4 = slope at t */\r\n\t(*f)(t, p, k4, c, n);\r\n\r\n\t/* yout = y + h*(k1/6 + k2/3 + k3/3 + k4/6)\t*/\r\n\r\n\tfor (i =0; i < n; i++)\r\n\t\tyout[i] = y[i] + h * (k1[i] + 2*k2[i] + 2*k3[i] + k4[i])/6.0;\r\n\r\n\tUtils::vectorDealloc(k2);\r\n\tUtils::vectorDealloc(k3);\r\n\tUtils::vectorDealloc(k4);\r\n\tUtils::vectorDealloc(t);\r\n}\r\n\r\nvoid copy_dvector (double *dst, double *src, int n){\r\n    memmove(dst, src, sizeof(double) * n);\r\n}\r\n\r\n#define RK4_SAFETY      0.95\r\n#define RK4_MAXUP       5.0\r\n#define RK4_MAXDOWN     10.0\r\n#define RK4_PRECISION   0.01\r\ndouble rk4(double **c, double *y, void *p, int n, double *h, double *yout, slope_fn_ptr f)\r\n{\r\n    int i;\r\n    double *k1, *t1, *t2, *ytemp, max, new_h = (*h);\r\n\r\n    k1 = Utils::vectorAlloc(n);\r\n    t1 = Utils::vectorAlloc(n);\r\n    t2 = Utils::vectorAlloc(n);\r\n    ytemp = Utils::vectorAlloc(n);\r\n\r\n    /* evaluate the slope k1 at the beginning */\r\n    (*f)(y, p, k1, c, n);\r\n\r\n    /* try until accuracy is achieved   */\r\n    do {\r\n        (*h) = new_h;\r\n\r\n        /* try RK4 once with normal step size   */\r\n        rk4_core(c, y, k1, p, n, (*h), ytemp, f);\r\n\r\n        /* repeat it with two half-steps    */\r\n        rk4_core(c, y, k1, p, n, (*h)/2.0, t1, f);\r\n\r\n        /* y after 1st half-step is in t1. re-evaluate k1 for this  */\r\n        (*f)(t1, p, k1, c, n);\r\n\r\n        /* get output of the second half-step in t2 */\r\n        rk4_core(c, t1, k1, p, n, (*h)/2.0, t2, f);\r\n\r\n        /* find the max diff between these two results:\r\n         * use t1 to store the diff\r\n         */\r\n\t\tfor(i=0; i < n; i++)\r\n\t\t\tt1[i] = fabs(ytemp[i] - t2[i]);\r\n\t\tmax = t1[0];\r\n\t\tfor(i=1; i < n; i++)\r\n\t\t\tif (max < t1[i])\r\n\t\t\t\tmax = t1[i];\r\n\r\n\t       /*\r\n\t         * compute the correct step size: see equation\r\n\t         * 16.2.10  in chapter 16 of \"Numerical Recipes\r\n\t         * in C\"\r\n\t         */\r\n\t        /* accuracy OK. increase step size  */\r\n\t        if (max <= RK4_PRECISION) {\r\n\t            new_h = RK4_SAFETY * (*h) * pow(fabs(RK4_PRECISION/max), 0.2);\r\n\t            if (new_h > RK4_MAXUP * (*h))\r\n\t                new_h = RK4_MAXUP * (*h);\r\n\t        /* inaccuracy error. decrease step size and compute again */\r\n\t        } else {\r\n\t            new_h = RK4_SAFETY * (*h) * pow(fabs(RK4_PRECISION/max), 0.25);\r\n\t            if (new_h < (*h) / RK4_MAXDOWN)\r\n\t                new_h = (*h) / RK4_MAXDOWN;\r\n\t        }\r\n\r\n\t    } while (new_h < (*h));\r\n\r\n\t    /* commit ytemp to yout */\r\n\t    copy_dvector(yout, ytemp, n);\r\n\r\n\t    /* clean up */\r\n\t    Utils::vectorDealloc(k1);\r\n\t    Utils::vectorDealloc(t1);\r\n\t    Utils::vectorDealloc(t2);\r\n\t    Utils::vectorDealloc(ytemp);\r\n\r\n\r\n\t    /* return the step-size */\r\n\t    return new_h;\r\n}\r\n\r\n\r\n\r\n/*\r\n * LUP decomposition from the pseudocode given in the CLRS book\r\n * ('Introduction to Algorithms'). The matrix 'a' is\r\n * transformed into an in-place lower/upper triangular matrix\r\n * and the vector'p' carries the permutation vector such that\r\n * Pa = lu, where 'P' is the matrix form of 'p'.\r\n */\r\n\r\nvoid RCutils::lupdcmp(double**a, int n, int *p){\r\n\tint i, j, k, pivot=0;\r\n\tdouble max = 0;\r\n\r\n\t/* start with identity permutation\t*/\r\n\tfor (i=0; i < n; i++)\r\n\t\tp[i] = i;\r\n\r\n\tfor (k=0; k < n; k++)\t {\r\n\t\tmax = 0;\r\n\t\tfor (i = k; i < n; i++)\t{\r\n\t\t\tif (fabs(a[i][k]) > max) {\r\n\t\t\t\tmax = fabs(a[i][k]);\r\n\t\t\t\tpivot = i;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (Utils::eq (max, 0)){\r\n\t\t\tcerr<<\"Singular matrix in lupdcmp.\"<<endl;\r\n\t\t\texit (-1);\r\n\t\t}\r\n\r\n\t\t/* bring pivot element to position\t*/\r\n\t\tswap(p[k], p[pivot]);\r\n\t\tfor (i=0; i < n; i++){\r\n\t\t\tswap(a[k][i], a[pivot][i]);\r\n\t\t}\r\n\r\n\t\tfor (i=k+1; i < n; i++) {\r\n\t\t\ta[i][k] /= a[k][k];\r\n\t\t\tfor (j=k+1; j < n; j++)\r\n\t\t\t\ta[i][j] -= a[i][k] * a[k][j];\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/*\r\n * the matrix a is an in-place lower/upper triangular matrix\r\n * the following macros split them into their constituents\r\n */\r\n\r\n#define LOWER(a, i, j)\t\t((i > j) ? a[i][j] : 0)\r\n#define UPPER(a, i, j)\t\t((i <= j) ? a[i][j] : 0)\r\n\r\n\r\n/*\r\n * LU forward and backward substitution from the pseudocode given\r\n * in the CLRS book ('Introduction to Algorithms'). It solves ax = b\r\n * where, 'a' is an in-place lower/upper triangular matrix. The vector\r\n * 'x' carries the solution vector. 'p' is the permutation vector.\r\n */\r\n\r\nvoid RCutils::lusolve(double **a, int n, int *p, double *b, double *x){\r\n\tint i, j;\r\n\tdouble *y = new double[n];\r\n\tdouble sum;\r\n\r\n\t/* forward substitution\t- solves ly = pb\t*/\r\n\tfor (i=0; i < n; i++) {\r\n\t\tfor (j=0, sum=0; j < i; j++)\r\n\t\t\tsum += y[j] * LOWER(a, i, j);\r\n\t\ty[i] = b[p[i]] - sum;\r\n\t}\r\n\r\n\t/* backward substitution - solves ux = y\t*/\r\n\tfor (i=n-1; i >= 0; i--) {\r\n\t\tfor (j=i+1, sum=0; j < n; j++)\r\n\t\t\tsum += x[j] * UPPER(a, i, j);\r\n\t\tx[i] = (y[i] - sum) / UPPER(a, i, i);\r\n\t}\r\n\r\n\tdelete[] y;\r\n}\r\n", "meta": {"hexsha": "af5df13f5edb2a6e467191b2e438f785fbbcb1c8", "size": 22630, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Therminator-v2/src/rc_utils.cpp", "max_stars_repo_name": "mjdousti/thermtap", "max_stars_repo_head_hexsha": "0ab903483689424f2ae97f558a1d9c1eaa1f25fd", "max_stars_repo_licenses": ["Intel"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-05T07:58:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-05T07:58:03.000Z", "max_issues_repo_path": "Therminator-v2/src/rc_utils.cpp", "max_issues_repo_name": "mjdousti/thermtap", "max_issues_repo_head_hexsha": "0ab903483689424f2ae97f558a1d9c1eaa1f25fd", "max_issues_repo_licenses": ["Intel"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Therminator-v2/src/rc_utils.cpp", "max_forks_repo_name": "mjdousti/thermtap", "max_forks_repo_head_hexsha": "0ab903483689424f2ae97f558a1d9c1eaa1f25fd", "max_forks_repo_licenses": ["Intel"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-12-23T03:43:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-23T01:40:46.000Z", "avg_line_length": 31.3434903047, "max_line_length": 129, "alphanum_fraction": 0.6059213433, "num_tokens": 6948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117165898111866, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.25385944264323124}}
{"text": "#include <iostream>\n#include <fstream>\n#include <Eigen/Dense>\n#include \"Graph.h\"\n\nnamespace GraphLib\n{\n#ifdef GRAPH_ENABLE_DEBUG\n\tsize_t Graph::instanceCount = 0;\n#endif\n\n\tdouble Graph::dampingFactor = 0.85;\n\n\tGraph::Graph(bool directed) \n\t{\n\t\tthis->directed = directed;\n\t\tadjMatrix = NULL;\n\t\tcomment = NULL;\n#ifdef GRAPH_ENABLE_DEBUG\n\t\tstd::cout << \"Creating an instance of Graph\\n\";\n\t\tinstanceCount++;\n#endif\n\t}\n\n\tGraph::~Graph()\n\t{\n\t\tfor(std::size_t i=0; i<vertexes.size(); i++)\n\t\t{\n\t\t\tNode* n = vertexes[i];\n\t\t\tdelete n;\n\t\t}\n\n\t\tdelete adjMatrix;\n\n\t\tvertexes.clear();\n\t\tedges.clear();\n\n#ifdef GRAPH_ENABLE_DEBUG\n\t\tstd::cout << \"Removing an instance of Graph\\n\";\n\t\tinstanceCount--;\n#endif\n\t}\n\n\tGraph::EdgeSet Graph::getEdges()\n\t{\n\t\treturn edges;\n\t}\n\n\t/* number of nodes */\n\tstd::size_t Graph::getNodesCount()const\n\t{\n\t\treturn vertexes.size();\n\t}\n\n\t/* number of edges */\n\tstd::size_t Graph::getEdgesCount()const\n\t{\n\t\treturn edges.size();\n\t}\n\n\tsize_t& Graph::createNode()\n\t{\n\t\tNode* n = new Node();\n\t\taddNode(n);\n\t\treturn n->getIndex();\n\t}\n\n\t\n\tNode* Graph::nodeAt(std::size_t n)\n\t{\n\t\tassert(n<vertexes.size());\n\t\treturn vertexes[n];\n\t}\n\n\tbool Graph::link(std::size_t n1, std::size_t n2)\n\t{\n\t\tassert((n1<vertexes.size()) && (n2<vertexes.size()));\n\t\tassert(n1!=n2);\n\n\t\tNode *node1 = vertexes[n1], *node2 = vertexes[n2];\n\t\tEdge *e = NULL;\n\n\t\te = new Edge(node1, node2);\n\n\t\tif(!addEdge(e))\n\t\t{\n\t\t\tdelete e;\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tbool Graph::unlink(std::size_t n1, std::size_t n2)\n\t{\n\t\tassert(n1<vertexes.size());\n\t\tassert(n2<vertexes.size());\n\t\tassert(n1!=n2);\n\n\t\tNode *node1 = vertexes[n1], *node2 = vertexes[n2];\n\n\t\tEdge *e = NULL;\n\n\t\te = new Edge(vertexes[n1], vertexes[n2]);\n\n\t\tEdgeSet::const_iterator it = edges.find(e);\n\n\t\t//std::cout << (it==edges.end()) << \" X\\n\";\n\n\t\tif(it == edges.end())\n\t\t\treturn false;\n\n\t\tedges.erase(e);\n\t\tdelete e;\n\n\t\treturn true;\n\t}\n\n\tbool Graph::areLinked(std::size_t n1, std::size_t n2)\n\t{\n\t\tassert(n1<vertexes.size());\n\t\tassert(n2<vertexes.size());\n\t\tassert(n1!=n2);\n\n\t\tEdge *e = NULL;\n\n\t\te = new Edge(vertexes[n1], vertexes[n2]);\n\n\t\tEdgeSet::const_iterator it = edges.find(e);\n\t\tif(it == edges.end())\n\t\t\treturn false;\n\n\t\treturn true;\n\n\n\t}\n\n\tvoid Graph::removeNode(size_t ref)\n\t{\n\t\tassert(ref<vertexes.size());\n\t\tNode *n = vertexes[ref];\n\t\tremoveNode(n);\n\t}\n\n\t/* Add a node to the graph, used internally */\n\tbool Graph::addNode(Node *node)\n\t{\n\t\tnode->setIndex(vertexes.size());\n\t\tfor( std::size_t i = 0; i < vertexes.size(); i++)\n\t\t\tif (node == vertexes[i])\n\t\t\t\treturn false;\n\n\t\tvertexes.push_back(node);\n\t\treturn true;\n\t}\n\n\t/* Removes a node from the graph, used internally  */\n\tvoid Graph::removeNode(Node *node)\n\t{\n\t\tstd::size_t size = vertexes.size();\n\t\tstd::size_t pos = node->getIndex();\n\n\t\tvertexes.erase(vertexes.begin()+pos);\n\n\t\tstd::vector<Edge*> toRemove;\n\n\t\tfor(auto e: edges)\n\t\t{\n\t\t\tif(e->contains(node))\n\t\t\t\ttoRemove.push_back(e);\n\t\t}\n\n\t\tstd::size_t s = toRemove.size();\n\n\t\tfor(std::size_t i=0; i<s; i++)\n\t\t{\n\t\t\tEdge *e  = toRemove[i];\n\t\t\tedges.erase(e);\n\t\t\tdelete e;\n\t\t}\n\n\t\t/* Update other nodes indexes */\n\t\tfor(std::size_t i=pos; i<size-1; i++)\n\t\t\tvertexes[i]->setIndex(i);\n\n\t\tnode->setIndex(-1);\n\t\tdelete node;\n\t}\n\n\tbool Graph::addEdge(Edge *edge)\n\t{\n\t\tEdgeSet::const_iterator e = edges.find(edge);\n\n\t\tif(e != edges.end())\n\t\t\treturn false;\n\n\t\tstd::size_t start = edge->start->getIndex();\n\t\tstd::size_t end   = edge->end->getIndex();\n\n\t\tif (start == -1 || end == -1)\n\t\t\treturn false;\n\n\t\tedges.insert(edge);\n\t\treturn true;\n\t}\n\n\tbool Graph::removeEdge(Edge *edge)\n\t{\n\t\tEdgeSet::const_iterator e = edges.find(edge);\n\t\tif(e == edges.end())\n\t\t\treturn false;\n\n\t\tedges.erase(edge);\n\t\treturn true;\n\t}\n\n\tvoid Graph::calculateAjdMatrix()\n\t{\n\t\tstd::size_t SIZE = vertexes.size();\n\n\t\tadjMatrix = new MatrixXb(SIZE, SIZE);\n\n\t\tfor(std::size_t i = 0; i < SIZE; i++)\n\t\t{\n\t\t\tfor(std::size_t j = 0; j < SIZE; j++)\n\t\t\t{\n\t\t\t\t(*adjMatrix)(i, j) = false;\n\t\t\t}\n\t\t}\n\n\t\tfor(const auto& e: edges)\n\t\t{\n\t\t\tstd::size_t i1 = e->start->getIndex();\n\t\t\tstd::size_t i2 = e->end->getIndex();\n\t\t\t(*adjMatrix)(i1, i2) = true;\n\t\t\tif(!this->directed)\n\t\t\t\t(*adjMatrix)(i2, i1) = true;\n\t\t}\n\t}\n\n\tvoid Graph::printAdjMatrix()\n\t{\n\t\tassert(adjMatrix != NULL);\n\n\t\tauto adjMat = *adjMatrix;\n\n\t\tstd::size_t SIZE = vertexes.size();\n\t\tfor( std::size_t i = 0; i < SIZE; i++)\n\t\t{\n\t\t\tfor(std::size_t j = 0; j < SIZE; j++)\n\t\t\t{\n\t\t\t\tstd::cout << \"\\t\" << adjMat(i, j);\n\t\t\t}\n\t\t\tstd::cout << \"\\n\";\n\t\t}\n\t}\n\n\tbool Graph::get(std::size_t n1, std::size_t n2)\n\t{\n\t\tassert(adjMatrix != NULL);\n\t\tassert(n1<vertexes.size());\n\t\tassert(n2<vertexes.size());\n\n\t\treturn (*adjMatrix)(n1, n2);\n\t}\n\n\t/* Initializes every node with a rank value 1/numberOfNodes */\n\n\tvoid Graph::calculatePageRank()\n\t{\n\t\tassert(adjMatrix != NULL);\n\n\t\tauto adjMat = *adjMatrix;\n\n\t\t/* initial value */\n\t\tdouble ival = 1.f/vertexes.size();\n\n\n\t\t/* This vector will contain the number of edges in which each node participates */\n\t\tstd::vector <std::size_t> nodeEdgesCount;\n\n\t\t/* Step 0 (Optimisation) */\n\t\tfor(std::size_t i = 0; i < vertexes.size(); i++)\n\t\t{\n\t\t\tnodeEdgesCount.push_back(0);\n\n\t\t\tfor(std::size_t j = 0; j < vertexes.size(); j++)\n\t\t\t{\n\t\t\t\tif (adjMat(i, j)){\n\t\t\t\t\tnodeEdgesCount[i] ++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/* Step 1 Initialize all nodes PR to 1/numberOfNodes */\n\t\tfor(std::size_t i = 0; i < vertexes.size(); i++)\n\t\t{\n\t\t\tvertexes[i]->setRank(ival);\n\t\t}\n\n\n\t\t/* Step 2 Loop 100x to get a good page rank value. */\n\t\tfor(std::size_t k = 0; k <100; k++)\n\t\t{\n\t\t\t/* Calculate PR of all nodes */\n\t\t\tfor(std::size_t i = 0; i < vertexes.size(); i++)\n\t\t\t{\n\n\t\t\t\tdouble sum = 0;\n\n\t\t\t\t/* calculate the sum of RP(Ti)/L(Ti) where Ti links to the current node */\n\t\t\t\tfor(std::size_t j = 0; j < vertexes.size(); j++)\n\t\t\t\t{\n\t\t\t\t\t/* node i must be targeted not the source */\n\t\t\t\t\tif (adjMat(j, i))\n\t\t\t\t\t{\n\t\t\t\t\t\tsum += vertexes[j]->getRank()/nodeEdgesCount[j];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvertexes[i]->setRank( (1-dampingFactor) + dampingFactor * sum );\n\t\t\t}\n\n\t\t}\n\t}\n\n\tvoid Graph::calculatePageRankMatrix()\n\t{\n\t\tassert(adjMatrix != NULL);\n\n\t\tauto adjMat = *adjMatrix;\n\n\t\tstd::vector<double> R;\n\t\tstd::size_t SIZE = vertexes.size();\n\t\tEigen::MatrixXd M(SIZE, SIZE);\n\n\t\t/* This vector will contain the number of edges in which each node participates */\n\t\tstd::vector <std::size_t> nodeEdgesCount;\n\n\t\t/* Step 0 (Optimisation) */\n\t\tfor(std::size_t i = 0; i < SIZE; i++)\n\t\t{\n\t\t\tnodeEdgesCount.push_back(0);\n\n\t\t\tfor(std::size_t j = 0; j < SIZE; j++)\n\t\t\t{\n\t\t\t\tif (adjMat(i, j)){\n\t\t\t\t\tnodeEdgesCount[i] ++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/* Creating M matrix */\n\t\tfor(std::size_t i = 0; i < SIZE; i++)\n\t\t{\n\t\t\tfor(std::size_t j = 0; j < SIZE; j++)\n\t\t\t{\n\t\t\t\tM(i, j) = 0;\n\t\t\t\tif(adjMat(j,i))\n\t\t\t\t\tM(i, j) = (1.0f/nodeEdgesCount[j]);\n\t\t\t}\n\t\t}\n\n\t\t/* Creating R matrix */\n\t\tfor(std::size_t i = 0; i < SIZE; i++)\n\t\t{\n\t\t\tR.push_back(1./SIZE);\n\t\t}\n\n\t\tfor(std::size_t k = 0; k < 100; k++)\n\t\t{\n\t\t\tstd::vector<double> tmp(SIZE);\n\n\t\t\tfor(std::size_t i = 0; i < SIZE; i++)\n\t\t\t{\n\t\t\t\tdouble value = 0;\n\t\t\t\tfor(std::size_t j = 0; j < SIZE; j++)\n\t\t\t\t{\n\t\t\t\t\tvalue += M(i, j) * R[j];\n\t\t\t\t}\n\t\t\t\ttmp[i] = value *dampingFactor +(1.0f-dampingFactor);\n\t\t\t}\n\t\t\tR = tmp;\n\t\t}\n\n\n\t\tfor(std::size_t i = 0; i < R.size(); i++)\n\t\t{\n\t\t\tvertexes[i]->setRank(R[i]);\n\t\t}\n\n\t}\n\n\tdouble Graph::getRank(std::size_t n)\n\t{\n\t\tassert(n<vertexes.size());\n\t\tdouble rank = vertexes[n]->getRank();\n\t\t/* To make sure this is called after calculating PR */\n\t\tassert(rank >= 0);\n\t\treturn rank;\n\t}\n\n\tvoid Graph::printPageRank() const\n\t{\n\t\tdouble sum = 0;\n\t\tfor( std::size_t i = 0; i < vertexes.size(); i++)\n\t\t{\n\t\t\tstd::cout << \"\\tNode \" << i << \":\\t\\t\" << vertexes[i]->getRank() << \"\\n\";\n\t\t\tsum += vertexes[i]->getRank();\n\t\t}\n\t\tstd::cout << \"\\n\\n\\tTotal PR: \" << sum << \"\\n\\n\";\n\t}\n\t\n\tvoid Graph::saveGML(wchar_t *url)\n\t{\n\t\tstd::cout << \"\\n\\tSaving GML to \\\"\"<< url << \"\\\"...\\n\";\n\t\tstd::ofstream out;\n\t\tout.open(url);\n\t\tout << \"graph [\";\n\n\t\tif(comment != NULL)\n\t\t\tout << \"\\tcomment \\\"\" << comment << \"\\\"\\n\";\n\t\tout << \"\\tdirected 0\\n\";\n\n\n\t\tfor(std::size_t i = 0; i < vertexes.size(); i++)\n\t\t{\n\t\t\tout << \"\\tnode [\";\n\t\t\tout << \"\\t\\tid \" << i << '\\n';\n\t\t\tout << \"\\t\\tlabel \\\"\" << i << \"\\\"\\n\";\n\t\t\tout << \"\\t]\\n\";\n\t\t}\n\t\t\n\t\tfor(auto e: edges)\n\t\t{\n\t\t\tout << \"\\tedge [\";\n\t\t\tout << \"\\t\\tsource \" << e->start->getIndex() << '\\n';\n\t\t\tout << \"\\t\\ttarget \" << e->end->getIndex() << '\\n';\n\t\t\tout << \"\\t]\\n\";\n\t\t}\n\n\t\tout << \"]\";\n\n\t\tout.close();\n\t}\n\n\tvoid Graph::saveDOT(wchar_t *url)\n\t{\n\t\tstd::cout << \"\\n\\tSaving DOT to \\\"\"<< url << \"\\\"...\\n\";\n\t\tstd::ofstream out;\n\t\tout.open(url);\n\t\tout << \"graph g{\\n\";\n\t\tfor(auto e: edges)\n\t\t{\n\t\t\tout << \"\\t\" << e->start->getIndex() << \" -- \" << e->end->getIndex() << \";\\n\";\n\t\t}\n\n\t\tout << \"}\";\n\n\t\tout.close();\n\t}\n\n\tvoid Graph::saveCSV(wchar_t *url)\n\t{\n\t\tstd::cout << \"saving file\\n\";\n\t\tstd::ofstream out;\n\t\tout.open(url);\n\t\tout << \"X, \";\n\t\tfor(std::size_t i = 0; i < vertexes.size(); i++)\n\t\t{\n\t\t\tout << \"Node \" << i << ',';\n\t\t}\n\n\t\tfor(std::size_t i = 0; i < vertexes.size(); i++)\n\t\t{\n\t\t\tout << \"\\nNode \" << i << ',';\n\t\t\tfor(std::size_t j = 0; j < vertexes.size(); j++)\n\t\t\t{\n\t\t\t\tout << (*adjMatrix)(i, j) << ',';\n\t\t\t}\n\t\t}\n\t\tout << \"\\n\\n\";\n\n\t\tdouble sum = 0;\n\t\tfor( std::size_t i = 0; i < vertexes.size(); i++)\n\t\t{\n\t\t\tout << \"Node \" << i << ',' << vertexes[i]->getRank() << '\\n';\n\t\t\tsum += vertexes[i]->getRank();\n\t\t}\n\n\t\tout << \"\\n\\nTotal PR,\" << sum << \"\\n\\n\";\n\n\t\tout.close();\n\t}\n\n}", "meta": {"hexsha": "6f73bf509b87dc35d7574d9eb6b800f1f7197c10", "size": 9272, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "project/SGA/Graph.cpp", "max_stars_repo_name": "sorakun/SGA", "max_stars_repo_head_hexsha": "892ed7f902ef0725507060b117132145f748fdf0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-08-20T23:49:23.000Z", "max_stars_repo_stars_event_max_datetime": "2016-06-26T00:07:17.000Z", "max_issues_repo_path": "project/SGA/Graph.cpp", "max_issues_repo_name": "sorakun/SGA", "max_issues_repo_head_hexsha": "892ed7f902ef0725507060b117132145f748fdf0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project/SGA/Graph.cpp", "max_forks_repo_name": "sorakun/SGA", "max_forks_repo_head_hexsha": "892ed7f902ef0725507060b117132145f748fdf0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.7692307692, "max_line_length": 84, "alphanum_fraction": 0.5613675582, "num_tokens": 3112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.2537820050602248}}
{"text": "/*\n * Copyright (c) 2019, 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// Check whether or not a particular set of strategies is a local Nash\n// equilibrium.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include <ilqgames/cost/player_cost.h>\n#include <ilqgames/dynamics/multi_player_flat_system.h>\n#include <ilqgames/dynamics/multi_player_integrable_system.h>\n#include <ilqgames/utils/compute_strategy_costs.h>\n#include <ilqgames/utils/operating_point.h>\n#include <ilqgames/utils/quadratic_cost_approximation.h>\n#include <ilqgames/utils/strategy.h>\n#include <ilqgames/utils/types.h>\n\n#include <glog/logging.h>\n#include <Eigen/Dense>\n#include <random>\n#include <vector>\n\nnamespace ilqgames {\n\nbool NumericalCheckLocalNashEquilibrium(\n    const std::vector<PlayerCost>& player_costs,\n    const std::vector<Strategy>& strategies,\n    const OperatingPoint& operating_point,\n    const MultiPlayerIntegrableSystem& dynamics, const VectorXf& x0,\n    Time time_step, float max_perturbation, bool open_loop) {\n  CHECK_EQ(strategies.size(), player_costs.size());\n  CHECK_EQ(strategies.size(), dynamics.NumPlayers());\n  CHECK_EQ(x0.size(), dynamics.XDim());\n\n  const size_t num_time_steps = strategies[0].Ps.size();\n  CHECK_EQ(num_time_steps, strategies[0].alphas.size());\n\n  // Compute nominal equilibrium cost and be sure to use only 1-step Euler\n  // integration.\n  const bool was_integrating_using_euler =\n      MultiPlayerIntegrableSystem::IntegrationUsesEuler();\n  if (!was_integrating_using_euler)\n    MultiPlayerIntegrableSystem::IntegrateUsingEuler();\n  const std::vector<float> nominal_costs =\n      ComputeStrategyCosts(player_costs, strategies, operating_point, dynamics,\n                           x0, time_step, open_loop);\n\n  // For each player, perturb strategies with Gaussian noise a bunch of times\n  // and if cost decreases then return false.\n  std::vector<Strategy> perturbed_strategies_lower(strategies);\n  std::vector<Strategy> perturbed_strategies_upper(strategies);\n  for (PlayerIndex ii = 0; ii < dynamics.NumPlayers(); ii++) {\n    for (size_t kk = 0; kk < num_time_steps - 1; kk++) {\n      VectorXf& alphak_lower = perturbed_strategies_lower[ii].alphas[kk];\n      VectorXf& alphak_upper = perturbed_strategies_upper[ii].alphas[kk];\n\n      for (size_t jj = 0; jj < alphak_lower.size(); jj++) {\n        alphak_lower(jj) -= max_perturbation;\n        alphak_upper(jj) += max_perturbation;\n\n        // Compute new costs.\n        const std::vector<float> perturbed_costs_lower = ComputeStrategyCosts(\n            player_costs, perturbed_strategies_lower, operating_point, dynamics,\n            x0, time_step, open_loop);\n        const std::vector<float> perturbed_costs_upper = ComputeStrategyCosts(\n            player_costs, perturbed_strategies_upper, operating_point, dynamics,\n            x0, time_step, open_loop);\n\n        // Check Nash condition.\n        if (std::min(perturbed_costs_lower[ii], perturbed_costs_upper[ii]) <\n            nominal_costs[ii]) {\n          // std::printf(\n          //     \"player %hu, timestep %zu: nominal %f > perturbed %f\\n \", ii,\n          //     kk, nominal_costs[ii], std::min(perturbed_costs_lower[ii],\n          //     perturbed_costs_lower[ii]));\n          // std::cout << \"nominal u: \" <<\n          // operating_point.us[kk][ii].transpose()\n          //           << \", alpha original: \"\n          //           << strategies[ii].alphas[kk].transpose()\n          //           << \", vs. perturbed \" << alphak_lower.transpose()\n          //           << std::endl;\n\n          // Other users will likely want RK4 integration.\n          if (!was_integrating_using_euler)\n            MultiPlayerIntegrableSystem::IntegrateUsingRK4();\n          return false;\n        }\n\n        // Reset this alpha.\n        alphak_lower = strategies[ii].alphas[kk];\n        alphak_upper = strategies[ii].alphas[kk];\n      }\n    }\n  }\n\n  // Other users will likely want RK4 integration.\n  MultiPlayerIntegrableSystem::IntegrateUsingRK4();\n  return true;\n}\n\nbool CheckSufficientLocalNashEquilibrium(\n    const std::vector<PlayerCost>& player_costs,\n    const OperatingPoint& operating_point, Time time_step,\n    const std::shared_ptr<const MultiPlayerFlatSystem>& dynamics) {\n  // Unpack number of players and number of time steps.\n  const PlayerIndex num_players = player_costs.size();\n  const size_t num_time_steps = operating_point.xs.size();\n  const Dimension xdim = operating_point.xs[0].size();\n\n  // Set up quadratic cost approximations.\n  std::vector<QuadraticCostApproximation> quadraticization(\n      num_players, QuadraticCostApproximation(xdim));\n\n  // Quadraticize costs and check PSD conditions.\n  for (size_t kk = 0; kk < num_time_steps; kk++) {\n    const Time t = operating_point.t0 + static_cast<Time>(kk) * time_step;\n    VectorXf x = operating_point.xs[kk];\n    std::vector<VectorXf> us = operating_point.us[kk];\n\n    if (dynamics.get()) {\n      // Previous x, us are actually xi, vs.\n      x = dynamics->FromLinearSystemState(x.eval());\n      us = dynamics->LinearizingControls(x, std::vector<VectorXf>(us));\n    }\n\n    std::transform(player_costs.begin(), player_costs.end(),\n                   quadraticization.begin(),\n                   [&t, &x, &us](const PlayerCost& cost) {\n                     return cost.Quadraticize(t, x, us);\n                   });\n\n    // Check if Q, Rs PSD.\n    constexpr float kErrorMargin = 1e-4;\n    for (const auto& q : quadraticization) {\n      const auto eig_Q = Eigen::SelfAdjointEigenSolver<MatrixXf>(q.state.hess);\n      if (eig_Q.eigenvalues().minCoeff() < -kErrorMargin) {\n        // std::cout << \"Failed at timestep \" << kk << std::endl;\n        // std::cout << \"Q is: \\n\" << q.Q << std::endl;\n        // std::cout << \"Q evals are: \" << eig_Q.eigenvalues().transpose()\n        //           << std::endl;\n        return false;\n      }\n\n      for (const auto& entry : q.control) {\n        const auto eig_R =\n            Eigen::SelfAdjointEigenSolver<MatrixXf>(entry.second.hess);\n        if (eig_R.eigenvalues().minCoeff() < -kErrorMargin) return false;\n      }\n    }\n  }\n\n  return true;\n}\n\n}  // namespace ilqgames\n", "meta": {"hexsha": "dcb3cedee40f7fd3e3357c7b3305c2fde98e4690", "size": 7957, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/check_local_nash_equilibrium.cpp", "max_stars_repo_name": "johnathanchiu/ilqgames", "max_stars_repo_head_hexsha": "77bb54c64e0ebd34ad9bf947702a37e8eddf2965", "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/check_local_nash_equilibrium.cpp", "max_issues_repo_name": "johnathanchiu/ilqgames", "max_issues_repo_head_hexsha": "77bb54c64e0ebd34ad9bf947702a37e8eddf2965", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/check_local_nash_equilibrium.cpp", "max_forks_repo_name": "johnathanchiu/ilqgames", "max_forks_repo_head_hexsha": "77bb54c64e0ebd34ad9bf947702a37e8eddf2965", "max_forks_repo_licenses": ["BSD-3-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.6596858639, "max_line_length": 80, "alphanum_fraction": 0.667085585, "num_tokens": 1854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2537820050602248}}
{"text": "#ifndef STAN_MCMC_HMC_HAMILTONIANS_DIAG_E_METRIC_HPP\r\n#define STAN_MCMC_HMC_HAMILTONIANS_DIAG_E_METRIC_HPP\r\n\r\n#include <stan/callbacks/logger.hpp>\r\n#include <stan/mcmc/hmc/hamiltonians/base_hamiltonian.hpp>\r\n#include <stan/mcmc/hmc/hamiltonians/diag_e_point.hpp>\r\n#include <boost/random/variate_generator.hpp>\r\n#include <boost/random/normal_distribution.hpp>\r\n\r\nnamespace stan {\r\n  namespace mcmc {\r\n\r\n    // Euclidean manifold with diagonal metric\r\n    template <class Model, class BaseRNG>\r\n    class diag_e_metric: public base_hamiltonian<Model, diag_e_point, BaseRNG> {\r\n    public:\r\n      explicit diag_e_metric(const Model& model)\r\n        : base_hamiltonian<Model, diag_e_point, BaseRNG>(model) {}\r\n\r\n      double T(diag_e_point& z) {\r\n        return 0.5 * z.p.dot( z.inv_e_metric_.cwiseProduct(z.p) );\r\n      }\r\n\r\n      double tau(diag_e_point& z) {\r\n        return T(z);\r\n      }\r\n\r\n      double phi(diag_e_point& z) {\r\n        return this->V(z);\r\n      }\r\n\r\n      double dG_dt(diag_e_point& z, callbacks::logger& logger) {\r\n        return 2 * T(z) - z.q.dot(z.g);\r\n      }\r\n\r\n      Eigen::VectorXd dtau_dq(diag_e_point& z, callbacks::logger& logger) {\r\n        return Eigen::VectorXd::Zero(this->model_.num_params_r());\r\n      }\r\n\r\n      Eigen::VectorXd dtau_dp(diag_e_point& z) {\r\n        return z.inv_e_metric_.cwiseProduct(z.p);\r\n      }\r\n\r\n      Eigen::VectorXd dphi_dq(diag_e_point& z, callbacks::logger& logger) {\r\n        return z.g;\r\n      }\r\n\r\n      void sample_p(diag_e_point& z, BaseRNG& rng) {\r\n        boost::variate_generator<BaseRNG&, boost::normal_distribution<> >\r\n          rand_diag_gaus(rng, boost::normal_distribution<>());\r\n\r\n        for (int i = 0; i < z.p.size(); ++i)\r\n          z.p(i) = rand_diag_gaus() / sqrt(z.inv_e_metric_(i));\r\n      }\r\n    };\r\n\r\n  }  // mcmc\r\n}  // stan\r\n#endif\r\n", "meta": {"hexsha": "f5525f231eba64e06c75e1c908886011776768ab", "size": 1822, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "archive/stan/src/stan/mcmc/hmc/hamiltonians/diag_e_metric.hpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "archive/stan/src/stan/mcmc/hmc/hamiltonians/diag_e_metric.hpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "archive/stan/src/stan/mcmc/hmc/hamiltonians/diag_e_metric.hpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3666666667, "max_line_length": 81, "alphanum_fraction": 0.6317233809, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.25358236354895974}}
{"text": "// *****************************************************************************\n//\n// Copyright (c) 2014, Southwest Research Institute® (SwRI®)\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 Southwest Research Institute® (SwRI®) nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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\n#include <swri_image_util/geometry_util.h>\n\n#include <cmath>\n#include <limits>\n#include <vector>\n\n#include <QPolygonF>\n#include <QPointF>\n\n#include <opencv2/imgproc/imgproc.hpp>\n\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n\n#include <swri_math_util/constants.h>\n\nnamespace swri_image_util\n{\n  bool Intersects(const BoundingBox& box1, const BoundingBox& box2)\n  {\n    return (box1 & box2).area() > 0;\n  }\n\n  double GetOverlappingArea(const cv::Rect& rect, const cv::Mat& rigid_transform)\n  {\n    // List of points corresponding to the input rectangle.\n    std::vector<cv::Vec2f> points;\n\n    // List of points correspondng to the transformed rectangle.\n    std::vector<cv::Vec2f> points_t;\n\n    // Create a point for each corner of the input rectangle.\n    points.push_back(cv::Vec2f(rect.x, rect.y));\n    points.push_back(cv::Vec2f(rect.x + rect.width, rect.y));\n    points.push_back(cv::Vec2f(rect.x + rect.width, rect.y + rect.height));\n    points.push_back(cv::Vec2f(rect.x, rect.y + rect.height));\n\n    // Transform the input points to the transformed points using the rigid\n    // transform.\n    cv::transform(cv::InputArray(points), cv::OutputArray(points_t), rigid_transform);\n\n    // Use the QPolygon object to get the intersecting area of the input\n    // rectangle and the transformed rectangle.\n\n    // Build the polygon corresponding to the input rectangle.\n    QPolygonF polygon;\n    polygon << QPointF(points[0][0], points[0][1]);\n    polygon << QPointF(points[1][0], points[1][1]);\n    polygon << QPointF(points[2][0], points[2][1]);\n    polygon << QPointF(points[3][0], points[3][1]);\n    polygon << QPointF(points[0][0], points[0][1]);\n\n    // Build the polygon corresponding to the transformed rectangle.\n    QPolygonF transformed_polygon;\n    transformed_polygon << QPointF(points_t[0][0], points_t[0][1]);\n    transformed_polygon << QPointF(points_t[1][0], points_t[1][1]);\n    transformed_polygon << QPointF(points_t[2][0], points_t[2][1]);\n    transformed_polygon << QPointF(points_t[3][0], points_t[3][1]);\n    transformed_polygon << QPointF(points_t[0][0], points_t[0][1]);\n\n    // Get the polygon representing the intersection of the input rectangle and\n    // the transformed rectangle.\n    QPolygonF intersection = polygon.intersected(transformed_polygon);\n\n    // If the intersection is empty, then just return 0 area.\n    if (intersection.size() == 0)\n    {\n      return 0;\n    }\n\n    // Build an OpenCV contour to measure the area of the intersection.\n    std::vector<cv::Point2f> contour;\n    for (int i = 0; i < intersection.size(); i++)\n    {\n      contour.push_back(cv::Point2f(intersection[i].x(), intersection[i].y()));\n    }\n\n    // Scale the area based on the scale factor to get the correct value.\n    return cv::contourArea(contour);\n  }\n\n  cv::Mat ProjectEllipsoid(const cv::Mat& ellipsoid)\n  {\n    cv::Mat ellipse;\n\n    if (ellipsoid.rows == 3 && ellipsoid.cols == 3 && ellipsoid.type() == CV_32FC1)\n    {\n      if (ellipsoid.at<float>(2, 2) >= std::numeric_limits<double>::max() * 0.5)\n      {\n        ellipse.create(2, 2, CV_32FC1);\n        ellipse.at<float>(0, 0) = ellipsoid.at<float>(0, 0);\n        ellipse.at<float>(0, 1) = ellipsoid.at<float>(0, 1);\n        ellipse.at<float>(1, 0) = ellipsoid.at<float>(1, 0);\n        ellipse.at<float>(1, 1) = ellipsoid.at<float>(1, 1);\n\n        return ellipse;\n      }\n\n      Eigen::Matrix3d A;\n      for (size_t r = 0; r < 3; r++)\n      {\n        for (size_t c = 0; c < 3; c++)\n        {\n          A(r, c) = ellipsoid.at<float>(r, c);\n        }\n      }\n\n      // Specify the main vector directions (x and y)\n      Eigen::Vector3d ax1;\n      Eigen::Vector3d ax2;\n      ax1 << 1, 0, 0;\n      ax2 << 0, 1, 0;\n\n      // Initialize the normal vector (here the normal vector, in the state\n      // space is in the theta direction).\n      Eigen::Vector3d n_ax;\n      n_ax << 0, 0, 1;\n\n      ///////////////////////\n      // Calculate A prime //\n      ///////////////////////\n\n      Eigen::Matrix3d A_sym_temp = A.transpose() + A;\n\n      // N_ax_temp = (n_ax*n_ax')\n      Eigen::Matrix3d N_ax_temp = n_ax * n_ax.transpose();\n\n      // A_prime_1 = A_sym_temp*N_ax_temp\n      //           = (A+A')*(n_ax*n_ax')\n      Eigen::Matrix3d A_prime_1 = A_sym_temp * N_ax_temp;\n\n      // A_prime_2 = A_prime_1*A_sym_temp\n      //           = (A+A')*(n_ax*n_ax')*(A+A')\n      Eigen::Matrix3d A_prime_2 = A_prime_1 * A_sym_temp;\n\n      // scale_1 = n_ax'*A\n      Eigen::RowVector3d scale_1 = n_ax.transpose() * A;\n\n      // scale_2 = (scale_1*n_ax)*-4\n      //         = (n_ax'*A*n_ax)*-4\n      double scale = (scale_1 * n_ax)(0,0) * -4.0;\n\n      // A_temp = scale*A_temp\n      //        = scale_2*A = -4*(n_ax'*A*n_ax)*A\n      Eigen::Matrix3d A_temp = A * scale;\n\n      // Aprime = A_prime_2 + A_temp\n      //        = (A+A')*(n_ax*n_ax')*(A+A') - 4*(n_ax'*A*n_ax)*A\n      Eigen::Matrix3d Aprime = A_prime_2 + A_temp;\n\n      ///////////////////////\n      // Calculate C prime //\n      ///////////////////////\n\n      // C_temp = n_ax'*A\n      Eigen::RowVector3d C_temp = n_ax.transpose() * A;\n\n      // Cprime = -4.0*C_temp*n_ax\n      //        = -4.0*n_ax'*A*n_ax\n      double cp = (-4.0 * C_temp) * n_ax;\n\n      // Bprime = Aprime/Cprime;\n      Eigen::Matrix3d Bprime = Aprime / cp;\n\n      // Jp = axes_def;\n      //    = [ax1(:),ax2(:)] = [1,0;0,1;0,0];\n      Eigen::Matrix<double, 3, 2> Jp;\n      Jp << 1, 0,\n            0, 1,\n            0, 0;\n\n      ///////////////////////\n      // Calculate D prime //\n      ///////////////////////\n\n      // Dprime_temp = Jp'*Bprime\n      Eigen::Matrix<double, 2, 3> Dprime_temp = Jp.transpose() * Bprime;\n\n      // Dprime = Dprime_temp * Jp\n      //        = Jp'*Bprime*Jp\n      Eigen::Matrix2d Dprime = Dprime_temp * Jp;\n\n      for (size_t r = 0; r < 2; r++)\n      {\n        for (size_t c = 0; c < 2; c++)\n        {\n          if (Dprime(r, c) != Dprime(r, c))\n          {\n            return ellipse;\n          }\n        }\n      }\n\n      ellipse.create(2, 2, CV_32FC1);\n      ellipse.at<float>(0, 0) = Dprime(0, 0);\n      ellipse.at<float>(0, 1) = Dprime(0, 1);\n      ellipse.at<float>(1, 0) = Dprime(1, 0);\n      ellipse.at<float>(1, 1) = Dprime(1, 1);\n    }\n\n    return ellipse;\n  }\n\n  std::vector<tf::Vector3> GetEllipsePoints(\n      const cv::Mat& ellipse,\n      const tf::Vector3& center,\n      double scale,\n      int32_t num_points)\n  {\n    std::vector<tf::Vector3> perimeter;\n\n    if (ellipse.rows == 2 && ellipse.cols == 2 && ellipse.type() == CV_32FC1 &&\n        num_points > 2)\n    {\n      Eigen::Matrix2d Dprime;\n      Dprime(0, 0) = ellipse.at<float>(0, 0);\n      Dprime(0, 1) = ellipse.at<float>(0, 1);\n      Dprime(1, 0) = ellipse.at<float>(1, 0);\n      Dprime(1, 1) = ellipse.at<float>(1, 1);\n\n      Eigen::JacobiSVD<Eigen::Matrix2d> svd(Dprime, Eigen::ComputeFullV);\n\n      Eigen::Vector2d Sigma = svd.singularValues();\n      Eigen::Matrix2d Vt = svd.matrixV().transpose();\n\n      double xprime_scale = std::sqrt(Sigma(0));\n      double yprime_scale = std::sqrt(Sigma(1));\n\n      if (xprime_scale <= 0 || yprime_scale <= 0)\n      {\n        return perimeter;\n      }\n\n      Eigen::MatrixX2d Xp1(num_points, 2);\n      for (int32_t i = 0; i < num_points; i++)\n      {\n        double phi =\n            (static_cast<double>(i) / static_cast<double>(num_points))\n            * swri_math_util::_2pi;\n\n        Xp1(i, 0) = xprime_scale * std::cos(phi) * scale;\n        Xp1(i, 1) = yprime_scale * std::sin(phi) * scale;\n      }\n\n      // Xell = Xp1*(V')'\n      Eigen::MatrixX2d Xell = Xp1 * Vt;\n\n      perimeter.resize(num_points);\n      for (int32_t i = 0; i < num_points; i++)\n      {\n        perimeter[i].setX(Xell(i, 0) + center.x());\n        perimeter[i].setY(Xell(i, 1) + center.y());\n      }\n    }\n\n    return perimeter;\n  }\n}\n", "meta": {"hexsha": "c80b05b9d686dcdc25fd2e5237418668ca29d674", "size": 9531, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "swri_image_util/src/geometry_util.cpp", "max_stars_repo_name": "pjreed/marti_common", "max_stars_repo_head_hexsha": "0e50cc34adc63164fbd941f1a596e9dbe634c310", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-17T08:36:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-17T08:36:19.000Z", "max_issues_repo_path": "swri_image_util/src/geometry_util.cpp", "max_issues_repo_name": "pjreed/marti_common", "max_issues_repo_head_hexsha": "0e50cc34adc63164fbd941f1a596e9dbe634c310", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "swri_image_util/src/geometry_util.cpp", "max_forks_repo_name": "pjreed/marti_common", "max_forks_repo_head_hexsha": "0e50cc34adc63164fbd941f1a596e9dbe634c310", "max_forks_repo_licenses": ["BSD-3-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.09375, "max_line_length": 86, "alphanum_fraction": 0.5875563949, "num_tokens": 2669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.25353439273006523}}
{"text": "/* ============================================================================\n\n   recurrences_ntl.cpp:  recurrences solved via NTL polynomial arithmetic\n\n   This file is part of hypellfrob (version 2.1.1).\n\n   Copyright (C) 2007, 2008, David Harvey\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\n\n#include <NTL/ZZ_pX.h>\n#include <NTL/mat_ZZ_p.h>\n#include <NTL/lzz_pX.h>\n#include <NTL/mat_lzz_p.h>\n#include <cassert>\n#include \"recurrences_ntl.h\"\n\n\nNTL_CLIENT\n\n\nnamespace hypellfrob {\n\n\n/* ============================================================================\n\n   Some template stuff\n\nThe matrix evaluation code is templated so that it can work over either ZZ_p\nor zz_p. There are several template parameters, which can have two settings:\n\n   SCALAR:       ZZ_p           zz_p\n   POLY:         ZZ_pX          zz_pX\n   VECTOR:       vec_ZZ_p       vec_zz_p\n   MATRIX:       mat_ZZ_p       mat_zz_p\n   POLYMODULUS:  ZZ_pXModulus   zz_pXModulus\n   FFTREP:       FFTRep         fftRep\n\nFor the most part NTL uses the same function names for both columns, which\nmakes life easy, but there's a few I needed to define explicitly:\n\n   to_scalar() convert a ZZ or int into a SCALAR\n   forward_fft() runs a forward FFT (either ToFFTRep() or TofftRep())\n   inverse_fft() runs an inverse FFT (either FromFFTRep() or FromfftRep())\n\n============================================================================ */\n\n\n// to_scalar(ZZ)\n\ntemplate <typename SCALAR> SCALAR to_scalar(const ZZ& input);\n\ntemplate<> inline ZZ_p to_scalar<ZZ_p>(const ZZ& input)\n{\n   return to_ZZ_p(input);\n}\n\ntemplate<> inline zz_p to_scalar<zz_p>(const ZZ& input)\n{\n   return to_zz_p(input);\n}\n\n\n// to_scalar(int)\n\ntemplate <typename SCALAR> SCALAR to_scalar(int input);\n\ntemplate<> inline ZZ_p to_scalar<ZZ_p>(int input)\n{\n   return to_ZZ_p(input);\n}\n\ntemplate<> inline zz_p to_scalar<zz_p>(int input)\n{\n   return to_zz_p(input);\n}\n\n\n// forward_fft\n\ntemplate <typename POLY, typename FFTREP>\nvoid forward_fft(FFTREP& y, const POLY& x, long k, long lo, long hi);\n\ntemplate<> inline void\nforward_fft<ZZ_pX, FFTRep>(FFTRep& y, const ZZ_pX& x, long k, long lo, long hi)\n{\n   ToFFTRep(y, x, k, lo, hi);\n}\n\ntemplate<> inline void\nforward_fft<zz_pX, fftRep>(fftRep& y, const zz_pX& x, long k, long lo, long hi)\n{\n   TofftRep(y, x, k, lo, hi);\n}\n\n\n// inverse_fft\n\ntemplate <typename POLY, typename FFTREP>\nvoid inverse_fft(POLY& x, FFTREP& y, long lo, long hi);\n\ntemplate<> inline void\ninverse_fft<ZZ_pX, FFTRep>(ZZ_pX& x, FFTRep& y, long lo, long hi)\n{\n   FromFFTRep(x, y, lo, hi);\n}\n\ntemplate<> inline void\ninverse_fft<zz_pX, fftRep>(zz_pX& x, fftRep& y, long lo, long hi)\n{\n   FromfftRep(x, y, lo, hi);\n}\n\n\n\n/* ============================================================================\n\n   Dyadic evaluation stuff\n\nThis section essentially implements Theorem 8 of [BGS], for the particular\ncase of the parameters that are used in Theorem 15.\n\n============================================================================ */\n\n\n/*\nAssume that f has degree d = 2^n and that g has degree 2d.\n\nThis function computes a polynomial h whose x^d through x^{2d} coefficients\n(inclusive) are the same as those of f*g. The bottom d coefficients of h\nwill be junk.\n\nThe parameter g_fft should be the precomputed length 2d FFT of g.\n\nThe algorithm in this function is based on the paper \"The middle product\nalgorithm\" by Hanrot, Quercia and Zimmermann. (Many thanks to Victor Shoup\nfor writing such wonderfully modular FFT code. It really made my day.)\n\n*/\ntemplate <typename SCALAR, typename POLY, typename FFTREP>\nvoid middle_product(POLY& h, const POLY& f,\n                    const POLY& g, const FFTREP& g_fft, int n)\n{\n   int d = 1 << n;\n   h.rep.SetLength(2*d + 1);\n\n   FFTREP f_fft(INIT_SIZE, n+1);\n\n   // Compute length 2d cyclic convolutions of f and g, letting the top\n   // third of f*g \"wrap around\" to the bottom half of the output.\n   forward_fft<POLY, FFTREP>(f_fft, f, n+1, 0, 2*d);\n   mul(f_fft, f_fft, g_fft);\n   inverse_fft<POLY, FFTREP>(h, f_fft, 0, 2*d);\n\n   // Need to correct for the x^{2d} term of g which got wrapped around to the\n   // constant term.\n   h.rep[d] -= g.rep[2*d] * f.rep[d];\n\n   // Now h contains terms x^d through x^{2d-1} of f*g.\n   // To finish off, we just need the x^{2d} term.\n   SCALAR temp;\n   SCALAR& sum = h.rep[2*d];\n   sum = 0;\n   for (int i = 0; i <= d; i++)\n   {\n      mul(temp, f.rep[i], g.rep[2*d-i]);\n      add(sum, sum, temp);\n   }\n}\n\n\n\n/*\nThis struct stores precomputed information that can then be used to shift\nevaluation values of a polynomial F(x) of degree d = 2^n.\n\nSpecifically, given the values\n  F(0), F(b), F(2*b), ..., F(d*b),\nthe shift() method computes\n  F(a), F(a + b), F(a + 2*b), ..., F(a + d*b).\n\nPRECONDITIONS:\n   n >= 1\n   1, 2, ..., d + 1 are invertible\n   a + i*b are invertible for -d <= i <= d\n\n*/\ntemplate <typename SCALAR, typename POLY, typename VECTOR, typename FFTREP>\nstruct DyadicShifter\n{\n   int d, n;\n\n   // input_twist is a vector of length d/2 + 1.\n   // The i-th entry is \\prod_{0 <= j <= d, j != i} (i-j)^(-1).\n   VECTOR input_twist;\n\n   // output_twist is a vector of length d+1.\n   // The i-th entry is b^(-d) \\prod_{0 <= j <= d} (a + (i-j)*b).\n   VECTOR output_twist;\n\n   // kernel is a polynomial of degree 2d.\n   // The coefficients are (a + k*b)^(-1) for -d <= k <= d.\n   // We also store its length 2d FFT.\n   POLY kernel;\n   FFTREP kernel_fft;\n\n   // Polynomials for scratch space in shift()\n   POLY scratch, scratch2;\n\n   // Constructor (performs various precomputations)\n   DyadicShifter(int n, const SCALAR& a, const SCALAR& b)\n   {\n      assert(n >= 1);\n      this->n = n;\n      d = 1 << n;\n\n      // ------------------------ compute input_twist -------------------------\n\n      input_twist.SetLength(d/2 + 1);\n\n      // prod = (d!)^(-1)\n      SCALAR prod;\n      prod = 1;\n      for (int i = 2; i <= d; i++)\n         mul(prod, prod, i);\n      prod = 1 / prod;\n\n      // input_twist[i] = ((d-i)!)^(-1)\n      input_twist[0] = prod;\n      for (int i = 1; i <= d/2; i++)\n         mul(input_twist[i], input_twist[i-1], d-(i-1));\n\n      // input_twist[i] = ((d-i)!*i!)^(-1)\n      prod = input_twist[d/2];\n      for (int i = d/2; i >= 0; i--)\n      {\n         mul(input_twist[i], input_twist[i], prod);\n         mul(prod, prod, i);\n      }\n\n      // input_twist[i] = \\prod_{0 <= j <= d, j != i} (i-j)^(-1)    :-)\n      for (int i = 1; i <= d/2; i += 2)\n         NTL::negate(input_twist[i], input_twist[i]);\n\n      // ----------------- compute output_twist and kernel --------------------\n\n      output_twist.SetLength(d+1);\n\n      // c[i] = c_i = a + (i-d)*b     for 0 <= i <= 2d\n      VECTOR c;\n      c.SetLength(2*d+1);\n      c[0] = a - d*b;\n      for (int i = 1; i <= 2*d; i++)\n         add(c[i], c[i-1], b);\n\n      // accum[i] = c_0 * c_1 * ... * c_i    for 0 <= i <= 2d\n      VECTOR accum;\n      accum.SetLength(2*d+1);\n      accum[0] = c[0];\n      for (int i = 1; i <= 2*d; i++)\n         mul(accum[i], accum[i-1], c[i]);\n\n      // accum_inv[i] = (c_0 * c_1 * ... * c_i)^(-1)    for 0 <= i <= 2d\n      VECTOR accum_inv;\n      accum_inv.SetLength(2*d+1);\n      accum_inv[2*d] = 1 / accum[2*d];\n      for (int i = 2*d-1; i >= 0; i--)\n         mul(accum_inv[i], accum_inv[i+1], c[i+1]);\n\n      // kernel[i] = (c_i)^(-1)    for 0 <= i <= 2d\n      kernel.rep.SetLength(2*d+1);\n      kernel.rep[0] = accum_inv[0];\n      for (int i = 1; i <= 2*d; i++)\n         mul(kernel.rep[i], accum_inv[i], accum[i-1]);\n\n      // precompute transform of kernel\n      forward_fft<POLY, FFTREP>(kernel_fft, kernel, n+1, 0, 2*d);\n\n      // output_twist[i] = b^{-d} * c_i * c_{i+1} * ... * c_{i+d}\n      // for 0 <= i <= d\n      SCALAR factor = power(b, -d);\n      SCALAR temp;\n      output_twist.SetLength(d+1);\n      output_twist[0] = factor * accum[d];\n      for (int i = 1; i <= d; i++)\n      {\n         mul(temp, factor, accum[i+d]);\n         mul(output_twist[i], temp, accum_inv[i-1]);\n      }\n   }\n\n\n   // Shifts evaluation values as described above.\n   // Assumes both output and input have length d + 1.\n   void shift(VECTOR& output, const VECTOR& input)\n   {\n      assert(input.length() == d+1);\n      assert(output.length() == d+1);\n\n      // multiply inputs pointwise by input_twist\n      scratch.rep.SetLength(d+1);\n      for (int i = 0; i <= d/2; i++)\n         mul(scratch.rep[i], input[i], input_twist[i]);\n      for (int i = 1; i <= d/2; i++)\n         mul(scratch.rep[i+d/2], input[i+d/2], input_twist[d/2-i]);\n\n      middle_product<SCALAR, POLY, FFTREP>(scratch2, scratch, kernel,\n                                           kernel_fft, n);\n\n      // multiply outputs pointwise by output_twist\n      for (int i = 0; i <= d; i++)\n         mul(output[i], scratch2.rep[i+d], output_twist[i]);\n   }\n};\n\n\n\n/*\nLet M0 and M1 be square matrices of size n*n. Let M(x) = M0 + x*M1; this is a\nmatrix of linear polys in x. Let P(x) = M(x+1) M(x+2) ... M(x+2^s); this is a\nmatrix of polynomials of degree 2^s. This function computes the values\n    P(a), P(a + 2^t), P(a + 2*2^t), ..., P(a + 2^s*2^t).\n\nThe output array should have length n^2. Each entry should be a vector of\nlength 2^s+1, pre-initialised to all zeroes. The (y*n + x)-th vector will be\nthe values of the (y, x) entries of the above list of matrices. (This data\nformat is optimised for the case that 2^s+1 is much larger than n.)\n\nPRECONDITIONS:\n   0 <= s <= t\n   2, 3, ..., 2^t + 1 must be invertible\n\n*/\ntemplate <typename SCALAR, typename POLY, typename VECTOR,\n          typename MATRIX, typename FFTREP>\nvoid dyadic_evaluation(vector<VECTOR>& output,\n                       const MATRIX& M0, const MATRIX& M1,\n                       int s, int t, const SCALAR& a)\n{\n   int n = M0.NumRows();\n\n   // base cases; just evaluate naively\n   if (s <= 1)\n   {\n      MATRIX X[3];\n\n      if (s == 0)\n      {\n         X[0] = M0 + (a+1) * M1;\n         X[1] = M0 + (a+1 + (1 << t)) * M1;\n      }\n      else\n      {\n         for (int i = 0; i <= 2; i++)\n            X[i] = (M0 + (a+1 + (i << t)) * M1) * (M0 + (a+2 + (i << t)) * M1);\n      }\n\n      for (int x = 0; x < n; x++)\n      for (int y = 0; y < n; y++)\n      for (int i = 0; i < output[0].length(); i++)\n         output[y*n + x][i] = X[i][y][x];\n\n      return;\n   }\n\n   // General case.\n   // Let Q(x) = M(x+1) M(x+2) ... M(x+2^(s-1)).\n\n   // Recursively compute Q(a), Q(a + 2^t), ..., Q(a + 2^(s-1)*2^t).\n   vector<VECTOR> X(n*n);\n   for (int i = 0; i < n*n; i++)\n      X[i].SetLength((1 << (s-1)) + 1);\n   dyadic_evaluation<SCALAR, POLY, VECTOR, MATRIX, FFTREP>\n                           (X, M0, M1, s-1, t, a);\n\n   // Do precomputations for shifting by 2^(s-1) and by (2^(s-1)+1)*2^t\n   SCALAR c, b;\n   c = 1 << (s-1);\n   b = 1 << t;\n   DyadicShifter<SCALAR, POLY, VECTOR, FFTREP> shifter1(s-1, c, b);\n   DyadicShifter<SCALAR, POLY, VECTOR, FFTREP> shifter2(s-1, (c + 1) * b, b);\n\n   // Shift by 2^(s-1) to obtain\n   // Q(a + 2^(s-1)), Q(a + 2^t + 2^(s-1)), ..., Q(a + 2^(s-1)*2^t + 2^(s-1))\n   vector<VECTOR> Y(n*n);\n   for (int i = 0; i < n*n; i++)\n   {\n      Y[i].SetLength((1 << (s-1)) + 1);\n      shifter1.shift(Y[i], X[i]);\n   }\n\n   // Multiply matrices to obtain\n   // P(a), P(a + 2^t), ..., P(a + 2^(s-1)*2^t).\n   SCALAR temp;\n   for (int i = 0; i <= (1 << (s-1)); i++)\n   for (int x = 0; x < n; x++)\n   for (int y = 0; y < n; y++)\n   for (int z = 0; z < n; z++)\n   {\n      mul(temp, X[y*n + z][i], Y[z*n + x][i]);\n      output[y*n + x][i] += temp;\n   }\n\n   // Shift original sequence by (2^(s-1)+1)*2^t to obtain\n   // Q(a + (2^(s-1)+1)*2^t), Q(a + (2^(s-1)+2)*2^t), ..., Q(a + (2^s+1)*2^t).\n   for (int i = 0; i < n*n; i++)\n      shifter2.shift(Y[i], X[i]);\n\n   // Shift again by 2^(s-1) to obtain\n   // Q(a + (2^(s-1)+1)*2^t + 2^(s-1)), Q(a + (2^(s-1)+2)*2^t + 2^(s-1)), ...,\n   //                                             Q(a + (2^s+1)*2^t + 2^(s-1)).\n   for (int i = 0; i < n*n; i++)\n      shifter1.shift(X[i], Y[i]);\n\n   // Multiply matrices to obtain\n   // P(a + (2^(s-1)+1)*2^t), P(a + (2^(s-1)+2)*2^t), ..., P(a + (2^s+1)*2^t).\n   // (we throw out the last one since it's surplus to requirements)\n   for (int i = 0; i < (1 << (s-1)); i++)\n   for (int x = 0; x < n; x++)\n   for (int y = 0; y < n; y++)\n   for (int z = 0; z < n; z++)\n   {\n      mul(temp, Y[y*n + z][i], X[z*n + x][i]);\n      output[y*n + x][i + (1 << (s-1)) + 1] += temp;\n   }\n}\n\n\n\n/* ============================================================================\n\n   General evaluation stuff\n\nThis section essentially implements Corollary 10 of [BGS].\n\n============================================================================ */\n\n\n/*\nThis struct stores the product tree associated to a vector a[0], ..., a[n-1].\n\nThe top node stores the polynomial product\n     (x - a[0]) ... (x - a[n-1]).\nThe two children nodes store\n     (x - a[0]) ... (x - a[m-1])\nand\n     (x - a[m]) ... (x - a[n-1])\nwhere m = floor(n/2). This continues recursively until we reach n = 1,\nin which case just the polynomial x - a[0] is stored, and no children.\n\n*/\ntemplate <typename SCALAR, typename POLY, typename VECTOR>\nstruct ProductTree\n{\n   // polynomial product stored at this node\n   POLY poly;\n\n   // children for left and right halves, if deg(poly) > 1\n   ProductTree* child1;\n   ProductTree* child2;\n\n   // These are temp polys used by the Evaluator and Interpolator classes.\n   // It's not very hygienic to keep them here... but it makes things more\n   // efficient, because we need two temps for each node, and this prevent\n   // unnecessary reallocations. (The lengths will be the same on repeated\n   // calls to evaluate() and interpolate().)\n   POLY scratch1, scratch2;\n\n   // Constructs product tree for the supplied vector.\n   ProductTree(const VECTOR& points)\n   {\n      build(points, 0, points.length());\n   }\n\n   ProductTree(const VECTOR& points, int start, int end)\n   {\n      build(points, start, end);\n   }\n\n   // Constructs product tree recursively for the subset [start, end) of\n   // the supplied vector.\n   void build(const VECTOR& points, int start, int end)\n   {\n      assert(end - start >= 1);\n      assert(start >= 0);\n      assert(end <= points.length());\n\n      if (end - start == 1)\n      {\n         SetCoeff(poly, 1, 1);\n         SetCoeff(poly, 0, -points[start]);\n      }\n      else\n      {\n         int m = (end - start) / 2;\n         child1 = new ProductTree(points, start, start + m);\n         child2 = new ProductTree(points, start + m, end);\n         mul(poly, child1->poly, child2->poly);\n      }\n   }\n\n   ~ProductTree()\n   {\n      if (deg(poly) > 1)\n      {\n         delete child1;\n         delete child2;\n      }\n   }\n};\n\n\n\n/*\nGiven a list of evaluation points a[0], ..., a[n-1], this struct stores some\nprecomputed information to permit evaluating an arbitrary polynomial at those\npoints.\n*/\ntemplate <typename SCALAR, typename POLY,\n          typename POLYMODULUS, typename VECTOR>\nstruct Evaluator\n{\n   // The product tree for the evaluation points\n   ProductTree<SCALAR, POLY, VECTOR>* tree;\n\n   // A list of NTL ZZ_pXModulus/zz_pXModulus objects corresponding to the\n   // polynomials in the product tree, in the order that they get used as the\n   // tree is traversed in recursive_evaluate().\n   vector<POLYMODULUS> moduli;\n\n   // Constructs evaluator object for the given list of evaluation points\n   Evaluator(const VECTOR& points)\n   {\n      assert(points.length() >= 1);\n      tree = new ProductTree<SCALAR, POLY, VECTOR>(points);\n      moduli.reserve(2*points.length());\n      build(tree);\n      assert(moduli.size() <= static_cast<size_t>(2*points.length()));\n   }\n\n   // Compute modulus objects for each polynomial under the supplied node of\n   // the product tree; appends them in traversal order to \"moduli\".\n   void build(const ProductTree<SCALAR, POLY, VECTOR>* node)\n   {\n      if (deg(node->poly) > 1)\n      {\n         moduli.push_back(POLYMODULUS(node->poly));\n         build(node->child1);\n         build(node->child2);\n      }\n   }\n\n   ~Evaluator()\n   {\n      delete tree;\n   }\n\n   // Evaluates the input polynomial at the evaluation points, writes the\n   // results to output. The output array must have the correct length.\n   void evaluate(VECTOR& output, const POLY& input)\n   {\n      recursive_evaluate(output, input, tree, 0, 0);\n   }\n\n   // Evaluates the input polynomial at the subset [start, end) of the\n   // evaluation points, which should correspond to the supplied product tree\n   // node. (The length of the interval is implied by the degree of the poly\n   // at that node.) Writes the output to the subset [start, end) of the\n   // output array. The index parameter indicates which modulus in \"moduli\"\n   // to use for this node of the tree. The return value is the index for\n   // the modulus that should be used immediately after this call.\n   int recursive_evaluate(VECTOR& output, const POLY& input,\n                          ProductTree<SCALAR, POLY, VECTOR>* node,\n                          int start, int index)\n   {\n      if (deg(node->poly) == 1)\n      {\n         eval(output[start], input, -coeff(node->poly, 0));\n      }\n      else\n      {\n         rem(node->scratch1, input, moduli[index++]);\n         index = recursive_evaluate(output, node->scratch1, node->child1,\n                                    start, index);\n         index = recursive_evaluate(output, node->scratch1, node->child2,\n                                    start + deg(node->child1->poly), index);\n      }\n      return index;\n   }\n};\n\n\n/*\nGiven an integer L >= 1, this struct does some precomputations to permit\ninterpolating a polynomial whose values at 0, 1, ..., L are known.\n\nPRECONDITIONS:\n   1, 2, ..., L must be invertible.\n\n*/\ntemplate <typename SCALAR, typename POLY, typename VECTOR>\nstruct Interpolator\n{\n   ProductTree<SCALAR, POLY, VECTOR>* tree;\n   int L;\n\n   // input_twist is a vector of length L+1.\n   // The i-th entry is \\prod_{0 <= j <= L, j != i} (i-j)^(-1).\n   VECTOR input_twist;\n\n   // vector of length L+1, used in interpolate()\n   VECTOR temp;\n\n   // Performs various precomputations for the given L.\n   Interpolator(int L)\n   {\n      this->L = L;\n      temp.SetLength(L+1);\n\n      // Build a product tree for the evaluation points\n      for (int i = 0; i <= L; i++)\n         temp[i] = i;\n      tree = new ProductTree<SCALAR, POLY, VECTOR>(temp);\n\n      // prod = (L!)^(-1)\n      SCALAR prod;\n      prod = 1;\n      for (int i = 2; i <= L; i++)\n         mul(prod, prod, i);\n      prod = 1 / prod;\n\n      // input_twist[i] = (i!)^(-1),   0 <= i <= L\n      input_twist.SetLength(L+1);\n      input_twist[L] = prod;\n      for (int i = L; i >= 1; i--)\n         mul(input_twist[i-1], input_twist[i], i);\n\n      // input_twist[i] = \\prod_{0 <= j <= L, j != i} (i-j)^(-1).\n      for (int i = 0; i <= L/2; i++)\n      {\n         mul(input_twist[i], input_twist[i], input_twist[L-i]);\n         input_twist[L-i] = input_twist[i];\n      }\n      for (int i = L-1; i >= 0; i -= 2)\n         NTL::negate(input_twist[i], input_twist[i]);\n   }\n\n   ~Interpolator()\n   {\n      delete tree;\n   }\n\n\n   // Returns the polynomial\n   //    \\sum_{i=start}^{end-1} values[i] * (x-start) (x-start+1) ... (x-end-1)\n   // where [start, end) is the interval associated to the supplied product\n   // tree node, and where the (x-i) term is omitted in each product.\n   void combine(POLY& output, const VECTOR& values,\n                ProductTree<SCALAR, POLY, VECTOR>* node, int start)\n   {\n      if (deg(node->poly) == 1)\n      {\n         // base case\n         clear(output);\n         SetCoeff(output, 0, values[start]);\n      }\n      else\n      {\n         // recursively build up from two halves\n         // i.e. if f1, f2 are the results of \"combine\" for the two halves,\n         // and if p1, p2 are the associated product tree polys, we compute\n         // f1*p2 + f2*p1\n\n         combine(node->scratch1, values, node->child1, start);\n         mul(output, node->scratch1, node->child2->poly);\n\n         combine(node->scratch1, values, node->child2,\n                 start + deg(node->child1->poly));\n         mul(node->scratch2, node->scratch1, node->child1->poly);\n\n         add(output, output, node->scratch2);\n      }\n   }\n\n   // Returns a polynomial F(x) of degree at most L such that F(i) = values[i]\n   // for each 0 <= i <= L.\n   void interpolate(POLY& output, const VECTOR& values)\n   {\n      assert(values.length() == L+1);\n\n      // multiply input values pointwise by input_twist; this corrects for\n      // the factor (i-0) (i-1) ... (i-L) (where the i-i factor is omitted).\n      for (int i = 0; i <= L; i++)\n         mul(temp[i], values[i], input_twist[i]);\n\n      // do the interpolation\n      combine(output, temp, tree, 0);\n   }\n};\n\n\n\n/* ============================================================================\n\n   Matrix products over arbitrary, relatively short intervals\n\nThis section implements something similar to steps 1, 2, ... and the final\nrefining step of Theorem 15 of [BGS].\n\n============================================================================ */\n\n\n/*\nLet M0 and M1 be matrices of constants. This function evaluates\n   M(x) = M0 + x*M1\nat x = a.\n\nThe output matrix must already have the correct dimensions.\n\n*/\ntemplate <typename SCALAR, typename MATRIX>\nvoid eval_matrix(MATRIX& output, const MATRIX& M0, const MATRIX& M1,\n                 const SCALAR& a)\n{\n   int n = M0.NumRows();\n   for (int x = 0; x < n; x++)\n   for (int y = 0; y < n; y++)\n   {\n      mul(output[x][y], a, M1[x][y]);\n      add(output[x][y], output[x][y], M0[x][y]);\n   }\n}\n\n\n\n/*\nSimilar to ntl_interval_products. This is used as a subroutine of\nntl_interval_products() to handle the smaller \"refining\" subintervals.\nIts asymptotic complexity theoretically has an extra logarithmic factor\nover that of ntl_interval_products().\n\nPRECONDITIONS:\n   Let d = sum of lengths of intervals. Then 2, 3, ... 1 + floor(sqrt(d)) must\n   all be invertible.\n\n*/\ntemplate <typename SCALAR, typename POLY, typename POLYMODULUS,\n          typename VECTOR, typename MATRIX>\nvoid ntl_short_interval_products(vector<MATRIX>& output,\n                                 const MATRIX& M0, const MATRIX& M1,\n                                 const vector<ZZ>& target)\n{\n   output.clear();\n\n   if (target.size() == 0)\n      return;\n\n   int dim = M0.NumRows();\n   int num_intervals = target.size() / 2;\n\n   // Determine maximum target interval length\n   int max_length = -1;\n   for (size_t i = 0; i < target.size(); i += 2)\n   {\n      int temp = to_ulong(target[i+1] - target[i]);\n      if (temp > max_length)\n         max_length = temp;\n   }\n\n   // Select an appropriate length for the matrix products we'll use\n   int L, max_eval_points;\n   if (max_length > 2*num_intervals)\n   {\n      // The intervals are still pretty long relative to the number of\n      // intervals, so we're only going to do a single multipoint\n      // evaluation.\n      L = 1 + to_ulong(SqrRoot(num_intervals * to_ZZ(max_length)));\n      max_eval_points = L;\n   }\n   else\n   {\n      // The intervals are getting pretty short, so we probably will need\n      // to do several shorter multipoint evaluations.\n      L = 1 + max_length/2;\n      max_eval_points = num_intervals;\n   }\n\n   // =========================================================================\n   // Step 1: compute entries of M(X, X+L) as polynomials in X.\n\n   vector<POLY> polys(dim*dim);\n   {\n      // left_accum[i]  = M(L-i-1, L)  for 0 <= i <= L-1\n      // right_accum[i] = M(L, L+i+1)  for 0 <= i <= L-1\n      vector<MATRIX> left_accum(L), right_accum(L);\n\n      MATRIX temp;\n      temp.SetDims(dim, dim);\n\n      left_accum[0].SetDims(dim, dim);\n      eval_matrix<SCALAR, MATRIX>(left_accum[0], M0, M1, to_scalar<SCALAR>(L));\n      for (int i = L-1; i >= 1; i--)\n      {\n         eval_matrix<SCALAR, MATRIX>(temp, M0, M1, to_scalar<SCALAR>(i));\n         mul(left_accum[L-i], temp, left_accum[L-i-1]);\n      }\n\n      right_accum[0].SetDims(dim, dim);\n      eval_matrix<SCALAR, MATRIX>(right_accum[0], M0, M1,\n                                  to_scalar<SCALAR>(L+1));\n      for (int i = 1; i <= L-1; i++)\n      {\n         eval_matrix<SCALAR, MATRIX>(temp, M0, M1, to_scalar<SCALAR>(L+1+i));\n         mul(right_accum[i], right_accum[i-1], temp);\n      }\n\n      // Use left_accum and right_accum to compute:\n      // initial[i] = M(i, L+i)    for 0 <= i <= L\n      // i.e. initial[i] are the values of M(X, X+L) at X = 0, 1, ..., L.\n      vector<MATRIX> initial(L+1);\n      initial[0] = left_accum.back();\n      initial[L] = right_accum.back();\n      for (int i = 1; i <= L-1; i++)\n         mul(initial[i], left_accum[L-1-i], right_accum[i-1]);\n\n      // Now interpolate entries of initial[i] to get entries of M(X, X+L)\n      // as polynomials of degree L.\n      Interpolator<SCALAR, POLY, VECTOR> interpolator(L);\n      VECTOR values;\n      values.SetLength(L+1);\n      for (int x = 0; x < dim; x++)\n      for (int y = 0; y < dim; y++)\n      {\n         for (int j = 0; j <= L; j++)\n            values[j] = initial[j][y][x];\n         interpolator.interpolate(polys[y*dim + x], values);\n      }\n   }\n\n   // =========================================================================\n   // Step 2: decompose intervals into subintervals of length L which we'll\n   // attack by direct multipoint evaluation, plus leftover pieces that we'll\n   // handle with a recursive call to ntl_short_interval_products().\n\n   // eval_points holds all the values of X for which we want to\n   // evaluate M(X, X+L)\n   VECTOR eval_points;\n   eval_points.SetMaxLength(max_eval_points);\n\n   // leftover_target is the list of leftover intervals that we're going to\n   // later do recursively\n   vector<ZZ> leftover_target;\n   leftover_target.reserve(target.size());\n\n   ZZ current, next;\n   for (size_t i = 0; i < target.size(); i += 2)\n   {\n      current = target[i];\n      next = current + L;\n      while (next <= target[i+1])\n      {\n         // [current, next) fits inside this interval, so peel it off into\n         // eval_points\n         append(eval_points, to_scalar<SCALAR>(current));\n         swap(current, next);\n         next = current + L;\n      }\n      if (current < target[i+1])\n      {\n         // the rest of this interval is too short to handle with M(X, X+L),\n         // so put it in the leftover bin\n         leftover_target.push_back(current);\n         leftover_target.push_back(target[i+1]);\n      }\n   }\n\n   // =========================================================================\n   // Step 3: recursively handle leftover pieces\n\n   // leftover_matrices[i] holds the matrix for leftover interval #i\n   vector<MATRIX> leftover_matrices;\n   ntl_short_interval_products<SCALAR, POLY, POLYMODULUS, VECTOR, MATRIX>\n                    (leftover_matrices, M0, M1, leftover_target);\n\n   // =========================================================================\n   // Step 4: evaluate M(X, X+L) at each of the evaluation points. We do this\n   // by breaking up the list of evaluation points into blocks of length at\n   // most L+1, and using multipoint evaluation on each block.\n\n   // main_matrices[i] will hold M(X, X+L) for the i-th evaluation point X.\n   vector<MATRIX> main_matrices(eval_points.length());\n   for (size_t i = 0; i < main_matrices.size(); i++)\n      main_matrices[i].SetDims(dim, dim);\n\n   VECTOR block, values;\n   block.SetMaxLength(L+1);\n   values.SetMaxLength(L+1);\n\n   // for each block...\n   for (int i = 0; i < eval_points.length(); i += (L+1))\n   {\n      // determine length of this block, which is at most L+1\n      int length = eval_points.length() - i;\n      if (length >= (L+1))\n         length = (L+1);\n      block.SetLength(length);\n\n      // construct Evaluator object for evaluating at these points\n      for (int j = 0; j < length; j++)\n         block[j] = eval_points[i+j];\n      Evaluator<SCALAR, POLY, POLYMODULUS, VECTOR> evaluator(block);\n\n      // evaluate each entry of M(X, X+L) at those points\n      for (int x = 0; x < dim; x++)\n      for (int y = 0; y < dim; y++)\n      {\n         evaluator.evaluate(values, polys[y*dim + x]);\n         for (int k = 0; k < length; k++)\n            main_matrices[i+k][y][x] = values[k];\n      }\n   }\n\n   // =========================================================================\n   // Step 5: merge together the matrices obtained from the multipoint\n   // evaluation step and the recursive leftover interval step.\n\n   output.clear();\n   output.resize(target.size() / 2);\n   for (size_t i = 0; i < target.size()/2; i++)\n      output[i].SetDims(dim, dim);\n\n   int main_index = 0;       // index into main_matrices\n   int leftover_index = 0;   // index into leftover_matrices\n\n   MATRIX temp;\n   temp.SetDims(dim, dim);\n\n   for (size_t i = 0; i < target.size(); i += 2)\n   {\n      current = target[i];\n      next = current + L;\n      ident(output[i/2], dim);\n\n      while (next <= target[i+1])\n      {\n         // merge in a matrix from multipoint evaluation step\n         mul(temp, output[i/2], main_matrices[main_index++]);\n         swap(temp, output[i/2]);\n         swap(current, next);\n         next = current + L;\n      }\n      if (current < target[i+1])\n      {\n         // merge in a matrix from leftover interval step\n         mul(temp, output[i/2], leftover_matrices[leftover_index++]);\n         swap(temp, output[i/2]);\n      }\n   }\n}\n\n\n/* ============================================================================\n\n   Matrix products over arbitrary, long intervals\n\nThis section implements an algorithm similar to Theorem 15 of [BGS].\n\n============================================================================ */\n\n\n/*\nSee interval_products_wrapper().\n\nNOTE:\n   This algorithm works best if the intervals are very long and don't have\n   much space between them. The case where the gaps are relatively large is\n   best handled by ntl_short_interval_products().\n\n*/\ntemplate <typename SCALAR, typename POLY, typename POLYMODULUS,\n          typename VECTOR, typename MATRIX, typename FFTREP>\nvoid ntl_interval_products(vector<MATRIX>& output,\n                           const MATRIX& M0, const MATRIX& M1,\n                           const vector<ZZ>& target)\n{\n   assert(target.size() % 2 == 0);\n   output.resize(target.size() / 2);\n\n   int dim = M0.NumRows();\n   assert(dim == M0.NumCols());\n   assert(dim == M1.NumRows());\n   assert(dim == M1.NumCols());\n\n   // =========================================================================\n   // Step 0: get as many intervals as possible using dyadic_evaluation().\n\n   // step0_matrix[i] is the transition matrix between step0_index[2*i]\n   // and step0_index[2*i+1].\n   vector<MATRIX> step0_matrix;\n   vector<ZZ> step0_index;\n   // preallocate the maximum number of matrices that could arise (plus safety)\n   size_t reserve_size = target.size() +\n                      4*NumBits(target.back() - target.front());\n   step0_matrix.reserve(reserve_size);\n   step0_index.reserve(2 * reserve_size);\n\n   ZZ current_index = target.front();\n   size_t next_target = 0;   // index into \"target\" array\n\n   // This flag indicates whether the last entry of step0_matrix is\n   // still accumulating matrices (in which the right endpoint of the\n   // corresponding interval hasn't been written to step0_index yet).\n   int active = 0;\n\n   MATRIX temp_mat;\n   temp_mat.SetDims(dim, dim);\n\n   while (current_index < target.back() - 3)\n   {\n      // find largest t such that 2^t*(2^t + 1) <= remaining distance to go\n      ZZ remaining = target.back() - current_index;\n      int t = 0;\n      while ((to_ZZ(1) << (2*t)) + (1 << t) <= remaining)\n         t++;\n      t--;\n\n      // evaluate matrices for 2^t+1 intervals of length 2^t\n      vector<VECTOR> dyadic_output(dim*dim);\n      for (int i = 0; i < dim*dim; i++)\n         dyadic_output[i].SetLength((1 << t) + 1);\n      dyadic_evaluation<SCALAR, POLY, VECTOR, MATRIX, FFTREP>\n               (dyadic_output, M0, M1, t, t, to_scalar<SCALAR>(current_index));\n\n      // Walk through the intervals we just computed. Find maximal subsequences\n      // of intervals none of which contain any target endpoints. Merge them\n      // together (by multiplying the appropriate matrices) and store results\n      // in step0_matrix, step0_index.\n\n      SCALAR scratch;\n\n      for (int i = 0; i <= (1 << t); i++, current_index += (1 << t))\n      {\n         assert(next_target == target.size() ||\n                target[next_target] >= current_index);\n\n         // Skip over target endpoints which are exactly at the beginning\n         // of this interval\n         while ((next_target < target.size()) &&\n                (target[next_target] == current_index))\n         {\n            // if there's an active matrix, don't forget to close it off\n            if (active)\n            {\n               step0_index.push_back(current_index);\n               active = 0;\n            }\n            next_target++;\n         }\n\n         // Test if any target endpoints are strictly within this interval.\n         if ((next_target == target.size()) ||\n             (target[next_target] >= current_index + (1 << t)))\n         {\n            // There are no target endpoints in this interval.\n            if (active)\n            {\n               // Merge this matrix with the active one\n               MATRIX& active_mat = step0_matrix.back();\n               for (int y = 0; y < dim; y++)\n               for (int x = 0; x < dim; x++)\n               {\n                  SCALAR& accum = temp_mat[y][x];\n                  accum = 0;\n                  for (int z = 0; z < dim; z++)\n                  {\n                     mul(scratch, active_mat[y][z],\n                                  dyadic_output[z*dim + x][i]);\n                     add(accum, accum, scratch);\n                  }\n               }\n\n               swap(temp_mat, active_mat);\n            }\n            else\n            {\n               // Make this matrix into a new active one\n               step0_index.push_back(current_index);\n               step0_matrix.resize(step0_matrix.size() + 1);\n               MATRIX& X = step0_matrix.back();\n               X.SetDims(dim, dim);\n               for (int y = 0; y < dim; y++)\n               for (int x = 0; x < dim; x++)\n                  X[y][x] = dyadic_output[y*dim + x][i];\n               active = 1;\n            }\n         }\n         else\n         {\n            // There are target endpoints in this interval.\n            if (active)\n            {\n               // If there is still an active matrix, close it off.\n               step0_index.push_back(current_index);\n               active = 0;\n            }\n\n            // skip over any other endpoints in this interval\n            while ((next_target < target.size()) &&\n                   (target[next_target] < current_index + (1 << t)))\n            {\n               next_target++;\n            }\n         }\n      }\n   }\n\n   // If there is still an active matrix, close it off.\n   if (active)\n      step0_index.push_back(current_index);\n\n   assert(step0_index.size() == 2*step0_matrix.size());\n\n   // =========================================================================\n   // Step 1: Make a list of all subintervals that we are going to need in\n   // the refining steps.\n\n   size_t next_step0 = 0;        // index into step0_index\n   vector<ZZ> step1_index;    // list of pairs of endpoints of needed intervals\n   step1_index.reserve(2*target.size());\n\n   // add sentinel endpoints to make the next loop simpler:\n   step0_index.push_back(target.back() + 10);\n   step0_index.push_back(target.back() + 20);\n\n   for (next_target = 0; next_target < target.size(); next_target += 2)\n   {\n      // skip dyadic intervals that come before this target interval\n      while (step0_index[next_step0+1] <= target[next_target])\n         next_step0 += 2;\n\n      if (step0_index[next_step0] < target[next_target+1])\n      {\n         // The next dyadic interval starts before the end of this target\n         // interval.\n         if (step0_index[next_step0] > target[next_target])\n         {\n            // The next dyadic interval starts strictly within this target\n            // interval, so we need to create a refining subinterval for the\n            // initial segment of this target interval.\n            step1_index.push_back(target[next_target]);\n            step1_index.push_back(step0_index[next_step0]);\n         }\n\n         // Skip over dyadic intervals to find the last one still contained\n         // within this target interval.\n         while (step0_index[next_step0+3] <= target[next_target+1])\n            next_step0 += 2;\n\n         if (step0_index[next_step0+1] < target[next_target+1])\n         {\n            // The next dyadic interval finishes strictly within this target\n            // interval, so we need to create a refining subinterval for the\n            // final segment of this target interval.\n            step1_index.push_back(step0_index[next_step0+1]);\n            step1_index.push_back(target[next_target+1]);\n         }\n\n         // Move on to next dyadic interval\n         next_step0 += 2;\n      }\n      else\n      {\n         // The next dyadic interval starts beyond (or just at the end of)\n         // this target interval, so we need to create a refining subinterval\n         // for this *whole* target interval.\n         step1_index.push_back(target[next_target]);\n         step1_index.push_back(target[next_target+1]);\n      }\n   }\n\n   // remove sentinels for my sanity\n   step0_index.pop_back();\n   step0_index.pop_back();\n\n   // Step 1b: Compute matrix products over those refining subintervals.\n   vector<MATRIX> step1_matrix;\n   ntl_short_interval_products<SCALAR, POLY, POLYMODULUS, VECTOR, MATRIX>\n                                   (step1_matrix, M0, M1, step1_index);\n\n   assert(step1_index.size() == 2 * step1_matrix.size());\n\n   // =========================================================================\n   // Step 2: Merge together the dyadic intervals and refining intervals into\n   // a single list, in sorted order.\n\n   vector<MATRIX> step2_matrix(step0_matrix.size() + step1_matrix.size());\n   vector<ZZ> step2_index(step0_index.size() + step1_index.size());\n\n   // add sentinels to make the next loop simpler\n   step0_index.push_back(target.back() + 10);\n   step0_index.push_back(target.back() + 20);\n   step1_index.push_back(target.back() + 10);\n   step1_index.push_back(target.back() + 20);\n\n   next_step0 = 0;       // index into step0_matrix\n   size_t next_step1 = 0;   // index into step1_matrix\n\n   for (size_t next_step2 = 0; next_step2 < step2_matrix.size(); next_step2++)\n   {\n      if (step0_index[2*next_step0] < step1_index[2*next_step1])\n      {\n         // grab a matrix and pair of indices from step0\n         swap(step2_matrix[next_step2], step0_matrix[next_step0]);\n         step2_index[2*next_step2] = step0_index[2*next_step0];\n         step2_index[2*next_step2+1] = step0_index[2*next_step0+1];\n         next_step0++;\n      }\n      else\n      {\n         // grab a matrix and pair of indices from step1\n         swap(step2_matrix[next_step2], step1_matrix[next_step1]);\n         step2_index[2*next_step2] = step1_index[2*next_step1];\n         step2_index[2*next_step2+1] = step1_index[2*next_step1+1];\n         next_step1++;\n      }\n   }\n\n   // remove sentinels for my sanity\n   step0_index.pop_back();\n   step0_index.pop_back();\n   step1_index.pop_back();\n   step1_index.pop_back();\n\n   assert(step2_index.size() == 2*step2_matrix.size());\n\n   // =========================================================================\n   // Step 3: Walk through target intervals, and merge together appropriate\n   // intervals from step2 to get those target intervals.\n\n   size_t next_step2 = 0;    // index into step2_matrix\n\n   // add sentinels to make the next loop simpler\n   step2_index.push_back(target.back() + 1);\n   step2_index.push_back(target.back() + 2);\n\n   for (size_t next_target = 0; next_target < target.size(); next_target += 2)\n   {\n      // search for step2 interval matching the start of this target interval\n      while (step2_index[2*next_step2] < target[next_target])\n         next_step2++;\n\n      assert(step2_index[2*next_step2] == target[next_target]);\n\n      // merge together matrices for step2 intervals contained in this target\n      // interval\n      swap(step2_matrix[next_step2++], output[next_target/2]);\n      while (step2_index[2*next_step2+1] <= target[next_target+1])\n      {\n         mul(temp_mat, output[next_target/2], step2_matrix[next_step2]);\n         swap(temp_mat, output[next_target/2]);\n         next_step2++;\n      }\n   }\n}\n\n\n// explicit instantiations for zz_p and ZZ_p versions:\n\n\ntemplate void ntl_interval_products\n      <ZZ_p, ZZ_pX, ZZ_pXModulus, vec_ZZ_p, mat_ZZ_p, FFTRep>\n      (vector<mat_ZZ_p>& output, const mat_ZZ_p& M0, const mat_ZZ_p& M1,\n                             const vector<ZZ>& target);\n\n\ntemplate void ntl_interval_products\n      <zz_p, zz_pX, zz_pXModulus, vec_zz_p, mat_zz_p, fftRep>\n      (vector<mat_zz_p>& output, const mat_zz_p& M0, const mat_zz_p& M1,\n                             const vector<ZZ>& target);\n\n\n};    // namespace hypellfrob\n\n\n// ----------------------- end of file\n", "meta": {"hexsha": "ba6ecaf3e3b50b01adaf7550f2f2f401733a09e9", "size": 41781, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sage/schemes/hyperelliptic_curves/hypellfrob/recurrences_ntl.cpp", "max_stars_repo_name": "hsm207/sage", "max_stars_repo_head_hexsha": "020bd59ec28717bfab9af44d2231c53da1ff99f1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1742.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T07:06:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:32:52.000Z", "max_issues_repo_path": "src/sage/schemes/hyperelliptic_curves/hypellfrob/recurrences_ntl.cpp", "max_issues_repo_name": "hsm207/sage", "max_issues_repo_head_hexsha": "020bd59ec28717bfab9af44d2231c53da1ff99f1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T19:17:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T11:59:30.000Z", "max_forks_repo_path": "src/sage/schemes/hyperelliptic_curves/hypellfrob/recurrences_ntl.cpp", "max_forks_repo_name": "dimpase/sage", "max_forks_repo_head_hexsha": "468f23815ade42a2192b0a9cd378de8fdc594dcd", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 495.0, "max_forks_repo_forks_event_min_datetime": "2015-01-10T10:23:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T22:06:11.000Z", "avg_line_length": 32.1145272867, "max_line_length": 79, "alphanum_fraction": 0.563413992, "num_tokens": 11470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.25353439273006523}}
{"text": "/*********************************************************************\n* Software License Agreement (BSD License)\n*\n*  Copyright (c) 2010, 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 the 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: Mark Moll */\n\n#include <ompl/base/spaces/ReedsSheppStateSpace.h>\n#include <ompl/base/spaces/DubinsStateSpace.h>\n#include <ompl/base/spaces/ClothoidStateSpace.h>\n#include <ompl/base/ScopedState.h>\n#include <ompl/geometric/SimpleSetup.h>\n#include <ompl/geometric/planners/rrt/RRT.h>\n#include <ompl/geometric/planners/rrt/RRTstar.h>\n#include <ompl/geometric/planners/rrt/DORRTstar.h>\n#include <boost/program_options.hpp>\n#include <Eigen/Core> \n\nusing namespace std;\nusing namespace Eigen;\nnamespace ob = ompl::base;\nnamespace og = ompl::geometric;\nnamespace po = boost::program_options;\n\nvoid magneticVectorForce(double x, double y, double theta,\n        VectorXd& ret)\n{\n    /*\n\tdouble ln = 60.0; \t// Length of conductors\n\tdouble d = 1.61/2.0;\t\t// Distance between the conductors m & n\n\tint m = 1; \t\t// Direction of current through the conductor, m(Right) 1(INTO), -1(OUT)\n\tint n = -1; \t\t// Direction of current through the conductor, n(Left) 1(INTO), -1(OUT)\n\tint N = 12; \t\t// Number sections/elements in the conductors\n\tint dl = ln/N; \t\t// Length of each element\n\t\n\t// XYZ coordinates/Location of each element from the origin (0,0,0), i.e 'd/2' is taken as origin..\n    MatrixXd xCm = (d/2.0)*MatrixXd::Ones(1,N); \n    MatrixXd xCn = (-d/2.0)*MatrixXd::Ones(1,N);\n\t\n\t// Y Coordinate of each element from origin, half on +Y & other half on -Y and also sam for both conductors\n\tVectorXd yC = VectorXd::LinSpaced(N, -ln/2.0+dl/2.0, ln/2.0-dl/2.0);\n\n\t// zC remains 0 throughout the length, as conductors are lying on XY plane\n\tMatrixXd zC = MatrixXd::Zero(1,N);\n\t\n\t// Length(Projection) 7 Direction of each current element in Vector form\n\tMatrixXd Lx = MatrixXd::Zero(1,N);\t// Length of each element is zero on X axis\n\tMatrixXd Ly = dl*MatrixXd::Ones(1,N);\t// Length of each element is dl on Y axis\n\tMatrixXd Lz = MatrixXd::Zero(1,N);\t// Length of each element is zero on Z axis\n\t\t\n\t// Points/Locations in space (here XZ plane) where B is to be computed\n\tint NP = 96;\t//Detector points..\n\tint xPmax = 12;\t//Dimensions of detector space.., arbitrary..\n\tint zPmax = 12;\n\n\tMatrixXd resVec_x = MatrixXd::Zero(NP,NP);\n\tMatrixXd resVec_y = MatrixXd::Zero(NP,NP);\n\tMatrixXd resPos_x = MatrixXd::Zero(NP,NP);\n\tMatrixXd resPos_y = MatrixXd::Zero(NP,NP);\n\t\n\t//Divide space with NP points..\n\tRowVectorXd xP = RowVectorXd::LinSpaced(NP, -xPmax, xPmax);\t\n\tVectorXd zP = VectorXd::LinSpaced(NP, -zPmax, zPmax);\n\n\t// Creating the Mesh..\n\tMatrixXd xxP = xP.replicate(NP,1); \n\tMatrixXd zzP = zP.replicate(1,NP);\n\n\t//Initialize B..\n\tMatrixXd Bx = MatrixXd::Zero(NP,NP);\n\tMatrixXd By = MatrixXd::Zero(NP,NP);\n\tMatrixXd Bz = MatrixXd::Zero(NP,NP);\n\n\t// Computation of Magnetic Field (B) using Superposition principle..\n\t// Compute B at each detector points due to each small cond elements & integrate them..\n\tfor( int q=0; q<N; q++ )\n\t{\n\t\tMatrixXd rxm = xxP.array() - xCm(0,q); // Displacement Vector along X direction, from cond m..\n\t\tMatrixXd rxn = xxP.array() - xCn(0,q); // Displacement Vector along X direction, from cond n..\n\t\t\n\t\tdouble ry = yC(q,0);\t// Same for m & n, no detector points on Y direction..\n\t\t\n\t\tMatrixXd rz = zzP.array() - zC(0,q); // Same for m & n..\n\t\t\n\t\tMatrixXd rm = (rxm.array()*rxm.array()+ry*ry+rz.array()*rz.array()).sqrt();\t// Displacement Magnitude for an element on cond m..\n\t\tMatrixXd rn = (rxn.array()*rxn.array()+ry*ry+rz.array()*rz.array()).sqrt();\t// Displacement Magnitude for an element on cond n..\n\t\t\n\t\tMatrixXd r3m = rm.array()*rm.array()*rm.array();\n\t\tMatrixXd r3n = rn.array()*rn.array()*rn.array();\n\t\t\n\t\tBx = Bx.array() + m*Ly(0,q)*rz.array()/r3m.array() + n*Ly(0,q)*rz.array()/r3n.array();\t// m & n, direction of current element..\n\t\t// By = 0;\n\t\tBz = Bz.array() - m*Ly(0,q)*rxm.array()/r3m.array() - n*Ly(0,q)*rxn.array()/r3n.array();\n\t}\n\t\t\n\tMatrixXd Rot(2,2);\n\tRot << cos(_theta), -sin(_theta),\n\t       sin(_theta),  cos(_theta);\n\n\tMatrixXd tmpMat(2, NP);\n\tfor(int i=0; i<NP; i++)\n\t{\n\t\t//tmpMat << Bx.row(i)+xxP.row(i),\n\t\t//\t\tBz.row(i)+zzP.row(i);\n\t\ttmpMat << Bx.row(i),\n\t\t\t\tBz.row(i);\n\t\ttmpMat = Rot * tmpMat;\n\t\t\n\t\t// Block Operation\n\t\tresVec_x.block(i,0,1,NP)  = tmpMat.block(0,0,1,NP).array();\n\t\tresVec_y.block(i,0,1,NP)  = tmpMat.block(1,0,1,NP).array();\n\t\t\n\t\ttmpMat << xxP.row(i),\n\t\t\t\tzzP.row(i);\n\t\ttmpMat = Rot * tmpMat;\n\t\t\n\t\t// Block Operation\n\t\tresPos_x.block(i,0,1,NP)  = (tmpMat.block(0,0,1,NP)).array()+_x;\n\t\tresPos_y.block(i,0,1,NP)  = (tmpMat.block(1,0,1,NP)).array()+_y;\n\t}\n\n\t///////////////////////////////////////////////////////////////////\n\tgeometry_msgs::PoseArray poseArray;\n\t\n    double grid_offset=grid_dim_/2.0*m_per_cell_;\n    double K_rep_mag = 100.0f; \n    \n\tfor(int i=0; i<NP; i++)\n\t{\n\t\tfor( int j=0; j<NP; j++)\n\t\t{\n\t\t\tint i_ = int((resPos_x(i,j) + grid_offset - m_per_cell_/2.0) / m_per_cell_);\n\t\t\tint j_ = int((resPos_y(i,j) + grid_offset - m_per_cell_/2.0) / m_per_cell_);\n\t\t\t\n\t\t\tif( i_ >= 0 && j_ >= 0 && i_ < NP && j_ < NP )\n\t\t\t{\n\t\t\t\tPotentialMap[i_][j_].bInit = true;\n\t\t\t\t\n\t\t\t\tdouble vSize = sqrtf(resVec_x(i,j)*resVec_x(i,j) + resVec_y(i,j)*resVec_y(i,j));\n\t\t\t\tdouble vDist = sqrtf((_x-resPos_x(i,j))*(_x-resPos_x(i,j)) + (_y-resPos_y(i,j))*(_y-resPos_y(i,j)));\n\t\t\t\tif( vDist < 0.1 ) vDist = 0.1;\n\t\t\t\tPotentialMap[i_][j_].F_sum.x += K_rep_mag*resVec_x(i,j)/vSize/vDist;\n\t\t\t\tPotentialMap[i_][j_].F_sum.y += K_rep_mag*resVec_y(i,j)/vSize/vDist;\n\t\t\t}\n\t\t}\n\t}\n\t*/\n}\ndouble computeRepulsiveForce(double K, double dist, double range, double x, double tar_x)\n{\n    // cout <<\"A \"<< dist << \" \" << range <<\" \" << x << \" \" << tar_x << \" \" << K*((1.0f/dist)-(1.0f/range))*(1.0f/(dist*dist*dist))*(x-tar_x) << endl;\n\n    return K*((1.0f/dist)-(1.0f/range))*(1.0f/(dist*dist*dist))*(x-tar_x);\n\n}\n\ndouble computeAttractiveForce(double K, double x, double tar_x)\n{\n    return -1.0f * K * (x - tar_x);\n}\n/** Basic unit-norm rotation field. */\nVectorXd vectorfield(const ob::State *from,const ob::State *to)\n{\n//    const ob::RealVectorStateSpace::StateType &x = *state->as<ob::RealVectorStateSpace::StateType>();\n    VectorXd v(2);\n  //  v[0] = x[1];\n   // v[1] = -x[0];\n   // v.normalize();\n    return v;\n}\n\n/** Basic unit-norm rotation field. */\nVectorXd magneticfield(const ob::State *from,const ob::State *to)\n{\n    //const ob::RealVectorStateSpace::StateType &x = *state->as<ob::RealVectorStateSpace::StateType>();\n    VectorXd v(2);\n   // v[0] = x[1];\n   // v[1] = -x[0];\n   // v.normalize();\n    return v;\n}\n\n// The easy problem is the standard narrow passage problem: two big open\n// spaces connected by a narrow passage. The hard problem is essentially\n// one long narrow passage with the robot facing towards the long walls\n// in both the start and goal configurations.\n\nbool isStateValid(const ob::SpaceInformation *si, const ob::State *state)\n{\n    const ob::SE2StateSpace::StateType *s = state->as<ob::SE2StateSpace::StateType>();\n    double x=s->getX(), y=s->getY(), yaw=s->getYaw();\n\n\t// 1. Collision Checking\n\t// CollisionChecking(x, y);\n\n\t//bool isFreeSpace = (x<40|| x>60 || (y>10.0 && y<12.0));\n\tbool isFreeSpace = (x<40|| x>60 || (y>10.8 && y<11.2));\n    return si->satisfiesBounds(s) && isFreeSpace;\n}\n\nbool isStateValid_Clothoid(const ob::SpaceInformation *si, const ob::State *state)\n{\n    const ob::ClothoidStateSpace::StateType *s = state->as<ob::ClothoidStateSpace::StateType>();\n    double x=s->getX(), y=s->getY(), yaw=s->getYaw();\n\n\t// 1. Collision Checking\n\t// CollisionChecking(x, y);\n\n\t//bool isFreeSpace = (x<40|| x>60 || (y>10.0 && y<12.0));\n\tbool isFreeSpace = (x<40|| x>60 || (y>10.8 && y<11.2));\n    return si->satisfiesBounds(s) && isFreeSpace;\n}\n\nvoid plan(ob::StateSpacePtr space,double time, bool isClothoid)\n{\n\n\n    // 0. Build KdTree\n\t// =BuildTree()\n\n\tob::ScopedState<> start(space), goal(space);\n    ob::RealVectorBounds bounds(2);\n    bounds.low[0] = 0;\n    bounds.high[0] = 100.0;\n\t\n    bounds.low[1] = 0;\n    bounds.high[1] = 50.0;\n\n\t//bounds.setLow(0);\n    //bounds.setHigh(100);\n    \n\tif( isClothoid )\n    \tspace->as<ob::ClothoidStateSpace>()->setBounds(bounds);\n\telse\n    \tspace->as<ob::SE2StateSpace>()->setBounds(bounds);\n\n    // define a simple setup class\n    og::SimpleSetup ss(space);\n\n    // set state validity checking for this space\n    ob::SpaceInformationPtr si(ss.getSpaceInformation());\n    \n\tss.setStateValidityChecker(std::bind(\n        isClothoid ? &isStateValid_Clothoid : &isStateValid, si.get(), std::placeholders::_1));\n\n    // set the start and goal states\n\tstart[0] =85.0;\n\tstart[1] = 8.0; \n\tstart[2] = 0.99*boost::math::constants::pi<double>();\n\tgoal[0] = 50.0;\n\tgoal[1] = 11.0; \n\t//goal[2] = 0.99*boost::math::constants::pi<double>();\n\tgoal[2] = 0.0*boost::math::constants::pi<double>();\n\tif( isClothoid )\n\t{\n\t\tstart[3] = 0.0;\n\t\tgoal[3] = 0.0;\n\t}\n    \n\tss.setStartAndGoalStates(start, goal);\n\n    ///////////////////////////////////////////////////////////////////\n    // 1. Potential Field\n\n    double m_per_cell_ = 0.25;\n    int grid_dim_x = ceil((bounds.high[0] - bounds.low[0])/m_per_cell_);\n    int grid_dim_y = ceil((bounds.high[1] - bounds.low[1])/m_per_cell_);\n\t\n    double num_obs[grid_dim_x][grid_dim_y];\n    \n    for (int x = 0; x < grid_dim_x; x++) {\n        for (int y = 0; y < grid_dim_y; y++) {\n            num_obs[x][y]=0;\n        }\n    }\n    \n    vector<Vector2d> obs;\n    for (unsigned int i=0; i<obs.size(); i++)\n    {\n        int x = ((grid_dim_x/2)+obs[i](0)/m_per_cell_);\n        int y = ((grid_dim_y/2)+obs[i](1)/m_per_cell_);\n        if( x >= 0 && x < grid_dim_x && y >= 0 && y < grid_dim_y )\n        {\n            num_obs[x][y]++;\n        }\n    }\n    \n    vector<vector<VectorXd> > VectorMap;\n\t// Initialize Potential Map\n    for (int x = 0; x < grid_dim_x; x++)\n    {\n\t\tvector<VectorXd> v;\n\t\tVectorMap.push_back(v);\n\t\t\n        for (int y = 0; y < grid_dim_y; y++)\n        {\n            VectorXd vec = VectorXd::Zero(3);\n            VectorMap[x].push_back(vec);\n        }\n    }\n\n    // Parameters\n    double grid_offset_x=grid_dim_x/2.0*m_per_cell_;\n    double grid_offset_y=grid_dim_y/2.0*m_per_cell_;\n    double Range_obs = 10.0;  \n    double K_rep_obs = 1.3f;\n\n    double Range_rep=180.0;\n    double K_rep = 50.0;\n    \n    double K_att = 30.0;\n\t\n    for (int i = 0; i<grid_dim_x; i++)\n    {\n        for (int j = 0; j<grid_dim_y; j++)\n        {\n            // transform index to local coordinate (x,y)\n            double x = -grid_offset_x + (i*m_per_cell_+m_per_cell_/2.0);\n            double y = -grid_offset_y + (j*m_per_cell_+m_per_cell_/2.0);\n\n            // Generate obstacle potential\n            for (unsigned int k = 0; k <= obs.size(); k++)\n            {\n                double obs_x = obs[k](0);\n                double obs_y = obs[k](1);\n\n                if(obs_x == 0.0 && obs_y == 0.0)\n                    continue;\n\n                double obs_dist = sqrt(((x - obs_x) * (x - obs_x))\n                        + ((y - obs_y) * (y - obs_y)));\n\n                if (obs_dist > 0.0 && obs_dist < Range_obs)\n                {\n                    VectorMap[i][j](2) = 1;\n                    VectorMap[i][j](0) += computeRepulsiveForce(K_rep_obs, obs_dist, Range_obs, x, obs_x);\n                    VectorMap[i][j](1) += computeRepulsiveForce(K_rep_obs, obs_dist, Range_obs, y, obs_y);\n                }\n            }\n\n            // Summation of attractive and repulsive potential values\n            if( VectorMap[i][j](2) == 1)\n            {\t\n\n                double x_att = computeAttractiveForce(K_att, x, goal[0]);\n                double y_att = computeAttractiveForce(K_att, y, goal[1]);\n\n                double start_dist = sqrt(((x - start[0]) * (x - start[0]))\n                        + ((y - start[1]) * (y - start[1])));\n                double x_rep = computeRepulsiveForce(K_rep, start_dist,\n                        Range_rep, x, start[0]);\n                double y_rep = computeRepulsiveForce(K_rep, start_dist,\n                        Range_rep, y, start[1]);\n\n                // Vector Force (Unit Vector)\n                VectorMap[i][j](0) +=(x_att + x_rep);\n                VectorMap[i][j](1) +=(y_att + y_rep);\n            }\n\n        }\n    }\n    //////////////////////////////////////////////////////////////////\n\n//    ss.setPlanner(std::make_shared<ompl::geometric::RRTstar>(ss.getSpaceInformation()));\n    ss.setPlanner(std::make_shared<ompl::geometric::DORRTstar>(ss.getSpaceInformation()\n                ,vectorfield, magneticfield));\n\t//b, l::base::PlannerPtr(new ompl::geometric::KPIECE1(ss.getiSpaceInformation())), range);\n    // this call is optional, but we put it in to get more output information\n    ss.getSpaceInformation()->setStateValidityCheckingResolution(0.005);\n    ss.setup();\n    ss.print();\n\n    // attempt to solve the problem within 30 seconds of planning time\n    ob::PlannerStatus solved = ss.solve(time);\n\n    if (solved)\n    {\n        std::vector<double> reals;\n\n        std::cout << \"Found solution:\" << std::endl;\n        ss.simplifySolution();\n        og::PathGeometric path = ss.getSolutionPath();\n        path.interpolate(1000);\n        path.printAsMatrix(std::cout);\n    }\n    else\n        std::cout << \"No solution found\" << std::endl;\n}\n\nvoid printTrajectory(ob::StateSpacePtr space, const std::vector<double>& pt)\n{\n    if (pt.size()!=3) throw ompl::Exception(\"3 arguments required for trajectory option\");\n    const unsigned int num_pts = 50;\n    ob::ScopedState<> from(space), to(space), s(space);\n    std::vector<double> reals;\n\n    from[0] = from[1] = from[2] = 0.;\n\n    to[0] = pt[0];\n    to[1] = pt[1];\n    to[2] = pt[2];\n\n    std::cout << \"distance: \" << space->distance(from(), to()) << \"\\npath:\\n\";\n    for (unsigned int i=0; i<=num_pts; ++i)\n    {\n        space->interpolate(from(), to(), (double)i/num_pts, s());\n        reals = s.reals();\n        std::cout << \"path \" << reals[0] << ' ' << reals[1] << ' ' << reals[2] << ' ' << std::endl;\n    }\n}\n\nvoid printDistanceGrid(ob::StateSpacePtr space)\n{\n    // print the distance for (x,y,theta) for all points in a 3D grid in SE(2)\n    // over [-5,5) x [-5, 5) x [-pi,pi).\n    //\n    // The output should be redirected to a file, say, distance.txt. This\n    // can then be read and plotted in Matlab like so:\n    //     x = reshape(load('distance.txt'),200,200,200);\n    //     for i=1:200,\n    //         contourf(squeeze(x(i,:,:)),30);\n    //         axis equal; axis tight; colorbar; pause;\n    //     end;\n    const unsigned int num_pts = 200;\n    ob::ScopedState<> from(space), to(space);\n    from[0] = from[1] = from[2] = 0.;\n\n    for (unsigned int i=0; i<num_pts; ++i)\n        for (unsigned int j=0; j<num_pts; ++j)\n            for (unsigned int k=0; k<num_pts; ++k)\n            {\n                to[0] = 5. * (2. * (double)i/num_pts - 1.);\n                to[1] = 5. * (2. * (double)j/num_pts - 1.);\n                to[2] = boost::math::constants::pi<double>() * (2. * (double)k/num_pts - 1.);\n                std::cout << space->distance(from(), to()) << '\\n';\n            }\n\n}\n\nint main(int argc, char* argv[])\n{\n    try\n    {\n        po::options_description desc(\"Options\");\n        desc.add_options()\n            (\"help\", \"show help message\")\n            (\"clothoid\", \"use Clothoid state space\")\n            (\"clothoidrev\", \"use reverse Clothoid state space\")\n            (\"dubins\", \"use Dubins state space\")\n            (\"dubinssym\", \"use symmetrized Dubins state space\")\n            (\"reedsshepp\", \"use Reeds-Shepp state space (default)\")\n            (\"time\", po::value<double>(),\"plannig time\")\n            (\"trajectory\", po::value<std::vector<double > >()->multitoken(),\n                \"print trajectory from (0,0,0) to a user-specified x, y, and theta\")\n            (\"distance\", \"print distance grid\")\n        ;\n\n        po::variables_map vm;\n        po::store(po::parse_command_line(argc, argv, desc,\n            po::command_line_style::unix_style ^ po::command_line_style::allow_short), vm);\n        po::notify(vm);\n\n        if (vm.count(\"help\") || argc==1)\n        {\n            std::cout << desc << \"\\n\";\n            return 1;\n        }\n\n        ob::StateSpacePtr space(new ob::ReedsSheppStateSpace(5.88));\n\n\t\tbool isClothoid = false;\n\n        if (vm.count(\"clothoidrev\"))\n\t\t{\n            space = ob::StateSpacePtr(new ob::ClothoidStateSpace(0.17, true));\n\t\t\tisClothoid = true;\n\t\t}\n\t\t\n\t\tif (vm.count(\"clothoid\"))\n\t\t{\n\t\t\tspace = ob::StateSpacePtr(new ob::ClothoidStateSpace(0.17, false));\n\t\t\tisClothoid = true;\n\t\t}\n\t\t\n\t\tif (vm.count(\"dubins\"))\n            space = ob::StateSpacePtr(new ob::DubinsStateSpace(5.88, false));\n        if (vm.count(\"dubinssym\"))\n            space = ob::StateSpacePtr(new ob::DubinsStateSpace(5.88, true));\n    \n\t\tdouble time = 30.0;\n\n\t\tif (vm.count(\"time\"))\n\t\t\ttime = vm[\"time\"].as<double>();\n\n\t\tplan(space,time,isClothoid);\n\n        if (vm.count(\"trajectory\"))\n            printTrajectory(space, vm[\"trajectory\"].as<std::vector<double> >());\n        if (vm.count(\"distance\"))\n            printDistanceGrid(space);\n    }\n    catch(std::exception& e) {\n        std::cerr << \"error: \" << e.what() << \"\\n\";\n        return 1;\n    }\n    catch(...) {\n        std::cerr << \"Exception of unknown type!\\n\";\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "c54aa637348ba277e1ed484df6e8d005126d3a1f", "size": 18811, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/GeometricCarPlanning_tmp.cpp", "max_stars_repo_name": "Insightque/DesiredOrientationRRT", "max_stars_repo_head_hexsha": "2e7a3e7cbcd30d6d9fa5bf0b53998bc5d0bda248", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-08T11:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-14T12:14:35.000Z", "max_issues_repo_path": "demos/GeometricCarPlanning_tmp.cpp", "max_issues_repo_name": "Insightque/DesiredOrientationRRT", "max_issues_repo_head_hexsha": "2e7a3e7cbcd30d6d9fa5bf0b53998bc5d0bda248", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-03T03:42:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-03T03:42:55.000Z", "max_forks_repo_path": "demos/GeometricCarPlanning_tmp.cpp", "max_forks_repo_name": "Insightque/DesiredOrientationRRT", "max_forks_repo_head_hexsha": "2e7a3e7cbcd30d6d9fa5bf0b53998bc5d0bda248", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-06-11T00:49:39.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-03T07:09:30.000Z", "avg_line_length": 34.7707948244, "max_line_length": 150, "alphanum_fraction": 0.5927914518, "num_tokens": 5629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.25346880792982424}}
{"text": "/*    Copyright (c) 2010-2015, Delft University of Technology\n *    All rights reserved.\n *\n *    Redistribution and use in source and binary forms, with or without modification, are\n *    permitted provided that the following conditions are met:\n *      - Redistributions of source code must retain the above copyright notice, this list of\n *        conditions and the following disclaimer.\n *      - Redistributions in binary form must reproduce the above copyright notice, this list of\n *        conditions and the following disclaimer in the documentation and/or other materials\n *        provided with the distribution.\n *      - Neither the name of the Delft University of Technology nor the names of its contributors\n *        may be used to endorse or promote products derived from this software without specific\n *        prior written permission.\n *\n *    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS\n *    OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n *    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *    COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n *    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n *    GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n *    AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n *    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n *    OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *    Changelog\n *      YYMMDD    Author            Comment\n *      111103    S. Billemont      File created.\n *      111205    T. Secretin       Added functionalities to previous shell code.\n *      120813    P. Musegaas       Changed code to new root finding structure.\n *      130317    K. Kumar          Updated allocation of Vector6d to fix problem with Eigen types.\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/exception/all.hpp>\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.\nboost::shared_ptr< basic_mathematics::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 basic_mathematics::Vector6d;\n\n    // Create a new KeplerianElements object.\n    boost::shared_ptr< Vector6d > keplerianElements\n            = boost::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        boost::throw_exception( boost::enable_error_info(\n                                    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        boost::throw_exception( boost::enable_error_info(\n                                    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        boost::throw_exception( boost::enable_error_info(\n                                    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        boost::throw_exception( boost::enable_error_info(\n                                    std::runtime_error(\n                                        \"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        boost::throw_exception( boost::enable_error_info(\n                                    std::runtime_error(\n                                        \"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        boost::throw_exception( boost::enable_error_info(\n                                    std::runtime_error(\n                                        \"No true anomaly or mean anomaly entries found.\" ) ) );\n    }\n\n    return keplerianElements;\n}\n\n} // namespace ephemerides\n} // namespace tudat\n", "meta": {"hexsha": "7ec9e72740ebf560f0f29704a9fafbac01817d1f", "size": 8314, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Ephemerides/keplerStateExtractor.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/Astrodynamics/Ephemerides/keplerStateExtractor.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/Astrodynamics/Ephemerides/keplerStateExtractor.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": 43.5287958115, "max_line_length": 99, "alphanum_fraction": 0.6489054607, "num_tokens": 1759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2533782729429767}}
{"text": "/*\n * CSIGadget.cpp\n *\n *  Created on: Nov 11, 2014\n *      Author: dch\n */\n\n#include \"CSIGadget.h\"\n#include <ismrmrd/xml.h>\n#include \"cudaDeviceManager.h\"\n#include \"cuNDArray_utils.h\"\n#include \"cuNlcgSolver.h\"\n#include \"eigenTester.h\"\n#include \"CSfreqOperator.h\"\n#include \"cuPartialDerivativeOperator.h\"\n#include \"cuDWTOperator.h\"\n#include <boost/make_shared.hpp>\nnamespace Gadgetron {\n\nCSIGadget::CSIGadget() {\n\t// TODO Auto-generated constructor stub\n\n}\n\nCSIGadget::~CSIGadget() {\n\t// TODO Auto-generated destructor stub\n}\n\n\nint CSIGadget::process_config(ACE_Message_Block *mb){\n\t//GDEBUG(\"gpuCgSenseGadget::process_config\\n\");\n\n        device_number_ = deviceno.value();\n\n\tint number_of_devices = cudaDeviceManager::Instance()->getTotalNumberOfDevice();\n\tif (number_of_devices == 0) {\n\t\tGDEBUG( \"Error: No available CUDA devices.\\n\" );\n\t\treturn GADGET_FAIL;\n\t}\n\n\tif (device_number_ >= number_of_devices) {\n\t\tGDEBUG(\"Adjusting device number from %d to %d\\n\", device_number_,  (device_number_%number_of_devices));\n\t\tdevice_number_ = (device_number_%number_of_devices);\n\t}\n\n\tif (cudaSetDevice(device_number_)!= cudaSuccess) {\n\t\tGDEBUG( \"Error: unable to set CUDA device.\\n\" );\n\t\treturn GADGET_FAIL;\n\t}\n\n\tcg_limit_ = cg_limit.value();\n\toversampling_factor_ = oversampling_factor.value();\n\tkernel_width_ = kernel_width.value();\n\toutput_convergence_ = output_convergence.value();\n\tnumber_of_sb_iterations_ = number_of_sb_iterations.value();\n\tnumber_of_cg_iterations_ = number_of_cg_iterations.value();\n\n\tuse_compressed_sensing_ = compressed_sensing.value();\n\n\tmu_ = mu.value();\n\n\t// Get the Ismrmrd header\n\t//\n\tISMRMRD::IsmrmrdHeader h;\n\tISMRMRD::deserialize(mb->rd_ptr(),h);\n\n\n\n\tif (h.encoding.size() != 1) {\n\t\tGDEBUG(\"This Gadget only supports one encoding space\\n\");\n\t\treturn GADGET_FAIL;\n\t}\n\n\t// Get the encoding space and trajectory description\n\tISMRMRD::EncodingSpace e_space = h.encoding[0].encodedSpace;\n\tISMRMRD::EncodingSpace r_space = h.encoding[0].reconSpace;\n\tISMRMRD::EncodingLimits e_limits = h.encoding[0].encodingLimits;\n\n\timg_dims_ = {r_space.matrixSize.x,r_space.matrixSize.y,r_space.matrixSize.z};\n\n\tmatrix_size_ = vector_td<uint64_t,2>{r_space.matrixSize.x,r_space.matrixSize.y};\n\n\tunsigned int warp_size = cudaDeviceManager::Instance()->warp_size(device_number_);\n\n\tmatrix_size_os_ =\n\t\t\tuint64d2(((static_cast<unsigned int>(std::ceil(matrix_size_[0]*oversampling_factor_))+warp_size-1)/warp_size)*warp_size,\n\t\t\t\t\t((static_cast<unsigned int>(std::ceil(matrix_size_[1]*oversampling_factor_))+warp_size-1)/warp_size)*warp_size);\n\n\n\t\tif (h.acquisitionSystemInformation) {\n\t\t\tchannels_ = h.acquisitionSystemInformation->receiverChannels ? *h.acquisitionSystemInformation->receiverChannels : 1;\n\t\t} else {\n\t\t\tchannels_ = 1;\n\t\t}\n\n\n\t\t/*if (~h.userParameters.is_present()){\n\t\t\tGDEBUG(\"CSI gadget requires userparameters to be set to obtain timesteps.\");\n\t\t\treturn GADGET_FAIL;\n\t\t}*/\n\n\n\t\tauto parameters = h.userParameters->userParameterDouble;\n\t\tauto bw = std::find_if(parameters.begin(),parameters.end(), [](ISMRMRD::UserParameterDouble d) { return d.name==\"bw\";});\n\n\t\tif (bw->name != \"bw\"){\n\t\t\tGDEBUG(\"CSI gadget: User parameter bw is missing.\");\n\t\t\treturn GADGET_FAIL;\n\t\t}\n\n\n\t\tauto dte = std::find_if(parameters.begin(),parameters.end(), [](ISMRMRD::UserParameterDouble d) { return d.name==\"dte\";});\n\t\tif (dte->name != \"dte\"){\n\t\t\tGDEBUG(\"CSI gadget: User parameter dte is missing.\");\n\t\t\treturn GADGET_FAIL;\n\t\t}\n\n// Allocate encoding operator for non-Cartesian Sense\n\t\tE_ = boost::make_shared< CSIOperator<float> >(1/bw->value, dte->value);\n\t\tE_->set_weight(mu_);\n\n\t\tstd::vector<float> freqs = frequencies.value();\n\n\t\tif (freqs.empty()){\n\t\t\tfor (float f = frequency_min.value(); f <= frequency_max.value(); f+= frequency_step.value())\n\t\t\t\tfreqs.push_back(f);\n\t\t}\n\n\n\t\tif (freqs.size() == 0)\n\t\t\tthrow std::runtime_error(\"CSIGadget: Frequencies not set!\");\n\n\t\tstd::stringstream ss;\n\t\tss << \"Frequencies set: \";\n\t\tfor (auto f : freqs)\n\t\t\t\tss << f << \" \";\n\t\tGDEBUG(ss.str().c_str());\n\n\t\tE_->set_frequencies(freqs);\n\n\t\timg_dims_[2]=freqs.size();\n\n\t\tS_ = boost::make_shared<cuNonCartesianSenseOperator<float,2>>();\n\n\t\tE_->set_senseOp(S_);\n\n\n\t\tauto idOp = boost::make_shared<identityOperator<cuNDArray<float_complext>>>();\n\t\tidOp->set_domain_dimensions(&img_dims_);\n\t\tidOp->set_codomain_dimensions(&img_dims_);\n\t\tidOp->set_weight(2*mu_);\n\t\tsolver_.add_regularization_operator(idOp);\n\n\t\tauto dX = boost::make_shared<cuPartialDerivativeOperator<float_complext,3>>(0);\n\t\tdX->set_domain_dimensions(&img_dims_);\n\t\tdX->set_codomain_dimensions(&img_dims_);\n\t\tdX->set_weight(2*mu_);\n\t\tauto dY = boost::make_shared<cuPartialDerivativeOperator<float_complext,3>>(1);\n\t\tdY->set_domain_dimensions(&img_dims_);\n\t\tdY->set_codomain_dimensions(&img_dims_);\n\t\tdY->set_weight(2*mu_);\n\t\tauto dZ = boost::make_shared<cuPartialDerivativeOperator<float_complext,3>>(2);\n\t\tdZ->set_domain_dimensions(&img_dims_);\n\t\tdZ->set_codomain_dimensions(&img_dims_);\n\t\tdZ->set_weight(2*mu_);\n\n\n\t\tsolver_.add_regularization_group_operator(dX);\n\t\tsolver_.add_regularization_group_operator(dY);\n\n\t\t//solver_.add_regularization_group_operator(dZ);\n\t\tsolver_.add_group();\n/*\n\t\tauto W = boost::make_shared<cuDWTOperator<float_complext,3>>();\n\t\tW->set_domain_dimensions(&img_dims_);\n\t\tW->set_codomain_dimensions(&img_dims_);\n\t\tW->set_weight(2*mu_);\n\n\n\t\tauto W2 = boost::make_shared<cuDWTOperator<float_complext,3>>();\n\t\tW2->set_shift(2);\n\t\tW2->set_domain_dimensions(&img_dims_);\n\t\tW2->set_codomain_dimensions(&img_dims_);\n\t\tW2->set_weight(2*mu_);\n\t\tsolver_.add_regularization_operator(W);\n\t\tsolver_.add_regularization_operator(W2);\n\t\t*/\n\t\t// Setup solver\n\t\tsolver_.set_encoding_operator( E_ );        // encoding matrix\n\t\tsolver_.set_max_outer_iterations( number_of_sb_iterations_ );\n\t\tsolver_.set_max_inner_iterations(1);\n\t\tsolver_.get_inner_solver()->set_max_iterations(number_of_cg_iterations_);\n\t\tsolver_.get_inner_solver()->set_tc_tolerance( cg_limit_ );\n\t\tsolver_.set_output_mode( (output_convergence_) ? cuCgSolver<float_complext>::OUTPUT_VERBOSE : cuCgSolver<float_complext>::OUTPUT_SILENT);\n\t\tis_configured_ = true;\n\treturn GADGET_OK;\n\n}\n\nint CSIGadget::process(GadgetContainerMessage<cuSenseData>* m1){\n\n\n\tif (!is_configured_) {\n\t\tGDEBUG(\"\\nData received before configuration complete\\n\");\n\t\treturn GADGET_FAIL;\n\t}\n\n\n\tGDEBUG(\"CSI is on the job\\n\");\n\n\n\n\tauto traj = m1->getObjectPtr()->traj;\n\n\tauto trajdims2 = std::vector<size_t>{traj->get_size(0),1};\n\t//Extract initial trajectory\n\tcuNDArray<floatd2> traj2(trajdims2,traj->get_data_ptr());\n\n\tauto data = m1->getObjectPtr()->data;\n\tauto csm =m1->getObjectPtr()->csm;\n\tauto dcw = m1->getObjectPtr()->dcw;\n\t//dcw.reset();\n\n\n\n\n\tif (dcw)\n\t\tsqrt_inplace(dcw.get());\n\n\n\tE_->set_domain_dimensions(&img_dims_);\n\tE_->set_codomain_dimensions(data->get_dimensions().get());\n\n\tstd::vector<size_t> sense_dims = *data->get_dimensions();\n\tsense_dims[1] = img_dims_[2];\n\n\n\n\tS_->set_domain_dimensions(&img_dims_);\n\tS_->set_codomain_dimensions(&sense_dims);\n/*\n\t{\n\t\tGDEBUG(\"Removing CSM maps\");\n\t\tauto csm_dims = *csm->get_dimensions();\n\t\tcsm_dims.pop_back();\n\t\tcuNDArray<float_complext> csm_view(csm_dims,csm->get_data_ptr());\n\t\tfill(&csm_view,complext<float>(1,0));\n\t\tsize_t nelements = csm_view.get_number_of_elements();\n\t\tfor (int  i = 1; i< csm->get_size(2); i++){\n\t\t\tcuNDArray<float_complext> csm_view2(csm_dims,csm->get_data_ptr()+i*nelements);\n\t\t\tclear(&csm_view2);\n\t\t}\n\t}\n*/\n\tS_->set_csm(csm);\n\tS_->set_dcw(dcw);\n\tS_->setup( matrix_size_, matrix_size_os_, kernel_width_ );\n\tS_->preprocess(&traj2);\n\n\tGDEBUG(\"Setup done, solving....\\n\");\n\t/*\n\teigenTester<cuNDArray<float_complext>> tester;\n\tstd::vector<float> freqs{  -575.1223,-450.1223,-360.1223,  -183.1223,140.8777};\n\tauto T_ = boost::make_shared<CSfreqOperator>(E_->get_pointtime(),E_->get_echotime());\n\tT_->set_frequencies(freqs);\n\tT_->set_codomain_dimensions(data->get_dimensions().get());\n\n\tstd::vector<size_t> tim_dims = *data->get_dimensions();\n\ttim_dims[2] = freqs.size();\n\tT_->set_domain_dimensions(&tim_dims);\n\n\ttester.add_encoding_operator(E_);\n\n\tfloat_complext eigVal = tester.get_smallest_eigenvalue();\n\n\tGDEBUG(\"Smallest eigenvalue: %f %f /n\",real(eigVal),imag(eigVal));\n*/\n\t/*\n\tcuNlcgSolver<float_complext> solv;\n\t//cuCgSolver<float_complext> solv;\n\tsolv.set_output_mode(cuCgSolver<float_complext>::OUTPUT_VERBOSE);\n\tsolv.set_max_iterations(10);\n\tsolv.set_encoding_operator(E_);\n\tsolv.set_tc_tolerance(1e-8f);\n\t*/\n\tboost::shared_ptr<cuNDArray<float_complext>> result;\n\tif (use_compressed_sensing_)\n\t\tresult = solver_.solve(data.get());\n\telse {\n\t\tcgSolver<cuNDArray<float_complext>> cgsolver;\n\t\tcgsolver.set_max_iterations(solver_.get_inner_solver()->get_max_iterations());\n\t\tcgsolver.set_encoding_operator(E_);\n\t\tresult = cgsolver.solve(data.get());\n\t}\n\t//auto result = solv.solve(data.get());\n\n\t//E_->mult_MH(data.get(),result.get(),false);\n\n\tGDEBUG(\"Image sum: %f \\n\",asum(result.get()));\n\tm1->release();\n\n\tGDEBUG(\"Solver done, next patient...\");\n\n\tGadgetContainerMessage< hoNDArray< std::complex<float> > > *cm =\n\t\t\tnew GadgetContainerMessage< hoNDArray< std::complex<float> > >();\n\n\tGadgetContainerMessage<ISMRMRD::ImageHeader> *m =\n\t\t\tnew GadgetContainerMessage<ISMRMRD::ImageHeader>();\n\n\n\tm->cont(cm);\n\n\n\n\tresult->to_host((hoNDArray<float_complext>*)cm->getObjectPtr());\n\n\tGDEBUG(\"Result size: %i %i %i \\n\",result->get_size(0),result->get_size(1),result->get_size(2));\n\n\tm->getObjectPtr()->matrix_size[0] = img_dims_[0];\n\tm->getObjectPtr()->matrix_size[1] = img_dims_[1];\n\tm->getObjectPtr()->matrix_size[2] = img_dims_[2];\n\tm->getObjectPtr()->channels       = 1;\n\tm->getObjectPtr()->image_index    = 1;\n\tm->getObjectPtr()->data_type = ISMRMRD::ISMRMRD_CXFLOAT;\n\n\n\tif (!this->next()->putq(m)){\n\t\tGDEBUG(\"Failed to put image on que\");\n\t\treturn GADGET_FAIL;\n\t}\n\n\n\treturn GADGET_OK;\n}\n\n  GADGET_FACTORY_DECLARE(CSIGadget)\n\n} /* namespace Gadgetron */\n", "meta": {"hexsha": "158c36f5d423a30f868f6e0277d6a8448f9eaf5c", "size": 9834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gadgets/hyper/CSIGadget.cpp", "max_stars_repo_name": "roopchansinghv/gadgetron", "max_stars_repo_head_hexsha": "fb6c56b643911152c27834a754a7b6ee2dd912da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T21:06:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T21:06:36.000Z", "max_issues_repo_path": "gadgets/hyper/CSIGadget.cpp", "max_issues_repo_name": "apd47/gadgetron", "max_issues_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gadgets/hyper/CSIGadget.cpp", "max_forks_repo_name": "apd47/gadgetron", "max_forks_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_forks_repo_licenses": ["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.0088495575, "max_line_length": 139, "alphanum_fraction": 0.7269676632, "num_tokens": 2833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2533782729429767}}
{"text": "#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/tensor_shape.h\"\n#include \"tensorflow/core/platform/default/logging.h\"\n#include \"tensorflow/core/framework/shape_inference.h\"\n\n#include <Eigen/Core>\n\n#include \"celerite.h\"\n\nusing namespace tensorflow;\n\nREGISTER_OP(\"CeleriteFactorGrad\")\n  .Attr(\"T: {float, double}\")\n  .Input(\"u: T\")\n  .Input(\"p: T\")\n  .Input(\"d: T\")\n  .Input(\"w: T\")\n  .Input(\"s: T\")\n  .Input(\"bd: T\")\n  .Input(\"bw: T\")\n  .Output(\"ba: T\")\n  .Output(\"bu: T\")\n  .Output(\"bv: T\")\n  .Output(\"bp: T\")\n  .SetShapeFn([](shape_inference::InferenceContext* c) {\n\n    shape_inference::ShapeHandle u, p, d, w, s, bd, bw;\n\n    TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 2, &u));\n    TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 2, &p));\n    TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 1, &d));\n    TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 2, &w));\n    TF_RETURN_IF_ERROR(c->WithRank(c->input(4), 2, &s));\n    TF_RETURN_IF_ERROR(c->WithRank(c->input(5), 1, &bd));\n    TF_RETURN_IF_ERROR(c->WithRank(c->input(6), 2, &bw));\n\n    TF_RETURN_IF_ERROR(c->Merge(u, w, &u));\n    TF_RETURN_IF_ERROR(c->Merge(u, bw, &u));\n    TF_RETURN_IF_ERROR(c->Merge(d, bd, &d));\n\n    c->set_output(0, c->input(2));\n    c->set_output(1, c->input(0));\n    c->set_output(2, c->input(0));\n    c->set_output(3, c->input(1));\n\n    return Status::OK();\n  });\n\ntemplate <typename T>\nclass CeleriteFactorGradOp : public OpKernel {\n public:\n  explicit CeleriteFactorGradOp(OpKernelConstruction* context) : OpKernel(context) {}\n\n  void Compute(OpKernelContext* context) override {\n    typedef Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, 1>> c_vector_t;\n    typedef Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> c_matrix_t;\n    typedef Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, 1>> vector_t;\n    typedef Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> matrix_t;\n\n    const Tensor& U_t = context->input(0);\n    const Tensor& P_t = context->input(1);\n    const Tensor& d_t = context->input(2);\n    const Tensor& W_t = context->input(3);\n    const Tensor& S_t = context->input(4);\n    const Tensor& bd_t = context->input(5);\n    const Tensor& bW_t = context->input(6);\n\n    OP_REQUIRES(context, U_t.dims() == 2, errors::InvalidArgument(\"U should be a matrix\"));\n    int64 N = U_t.dim_size(0),\n          J = U_t.dim_size(1);\n\n    OP_REQUIRES(context, ((P_t.dims() == 2) &&\n                          (P_t.dim_size(0) == N-1) &&\n                          (P_t.dim_size(1) == J)),\n          errors::InvalidArgument(\"P should have shape (N-1, J)\"));\n\n    OP_REQUIRES(context, ((d_t.dims() == 1) && (d_t.dim_size(0) == N)),\n        errors::InvalidArgument(\"d should have shape (N)\"));\n\n    OP_REQUIRES(context, ((W_t.dims() == 2) &&\n                          (W_t.dim_size(0) == N) &&\n                          (W_t.dim_size(1) == J)),\n          errors::InvalidArgument(\"W should have shape (N, J)\"));\n\n    OP_REQUIRES(context, ((S_t.dims() == 2) &&\n                          (S_t.dim_size(0) == N) &&\n                          (S_t.dim_size(1) == J*J)),\n          errors::InvalidArgument(\"S should have shape (N, J*J)\"));\n\n    OP_REQUIRES(context, ((bd_t.dims() == 1) && (bd_t.dim_size(0) == N)),\n        errors::InvalidArgument(\"bd should have shape (N)\"));\n\n    OP_REQUIRES(context, ((bW_t.dims() == 2) &&\n                          (bW_t.dim_size(0) == N) &&\n                          (bW_t.dim_size(1) == J)),\n          errors::InvalidArgument(\"bW should have shape (N, J)\"));\n\n    const auto U = c_matrix_t(U_t.template flat<T>().data(), N, J);\n    const auto P = c_matrix_t(P_t.template flat<T>().data(), N-1, J);\n    const auto d = c_vector_t(d_t.template flat<T>().data(), N);\n    const auto W = c_matrix_t(W_t.template flat<T>().data(), N, J);\n    const auto S = c_matrix_t(S_t.template flat<T>().data(), N, J*J);\n    const auto bd = c_vector_t(bd_t.template flat<T>().data(), N);\n    const auto bW = c_matrix_t(bW_t.template flat<T>().data(), N, J);\n\n    // Create the outputs\n    Tensor* ba_t = NULL;\n    Tensor* bU_t = NULL;\n    Tensor* bV_t = NULL;\n    Tensor* bP_t = NULL;\n    OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape({N}), &ba_t));\n    OP_REQUIRES_OK(context, context->allocate_output(1, TensorShape({N, J}), &bU_t));\n    OP_REQUIRES_OK(context, context->allocate_output(2, TensorShape({N, J}), &bV_t));\n    OP_REQUIRES_OK(context, context->allocate_output(3, TensorShape({N-1, J}), &bP_t));\n\n    auto ba = vector_t(ba_t->template flat<T>().data(), N);\n    auto bU = matrix_t(bU_t->template flat<T>().data(), N, J);\n    auto bV = matrix_t(bV_t->template flat<T>().data(), N, J);\n    auto bP = matrix_t(bP_t->template flat<T>().data(), N-1, J);\n\n    bU.setZero();\n    bP.setZero();\n    ba = bd;\n    bV = bW;\n    celerite::factor_grad(U, P, d, W, S, bU, bP, ba, bV);\n  }\n};\n\n#define REGISTER_KERNEL(type)                                              \\\n  REGISTER_KERNEL_BUILDER(                                                 \\\n      Name(\"CeleriteFactorGrad\").Device(DEVICE_CPU).TypeConstraint<type>(\"T\"), \\\n      CeleriteFactorGradOp<type>)\n\nREGISTER_KERNEL(float);\nREGISTER_KERNEL(double);\n\n#undef REGISTER_KERNEL\n", "meta": {"hexsha": "5ac2e5c9944b6e2c440edc8ea8ad89c1e0ddcc46", "size": 5228, "ext": "cc", "lang": "C++", "max_stars_repo_path": "celeriteflow/ops/celerite_factor_grad_op.cc", "max_stars_repo_name": "mirca/celeriteflow", "max_stars_repo_head_hexsha": "ed09a178df05856097552a9081b6eb6d537216ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "celeriteflow/ops/celerite_factor_grad_op.cc", "max_issues_repo_name": "mirca/celeriteflow", "max_issues_repo_head_hexsha": "ed09a178df05856097552a9081b6eb6d537216ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "celeriteflow/ops/celerite_factor_grad_op.cc", "max_forks_repo_name": "mirca/celeriteflow", "max_forks_repo_head_hexsha": "ed09a178df05856097552a9081b6eb6d537216ee", "max_forks_repo_licenses": ["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.884057971, "max_line_length": 107, "alphanum_fraction": 0.5960214231, "num_tokens": 1559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.25337826650444567}}
{"text": "#include <iostream>\n\n#include <boost/filesystem.hpp>\n\n#include \"pagmo/algorithms/de1220.hpp\"\n#include \"pagmo/algorithms/pso.hpp\"\n#include \"pagmo/algorithms/de.hpp\"\n#include \"pagmo/algorithms/bee_colony.hpp\"\n#include \"pagmo/algorithms/sga.hpp\"\n#include \"pagmo/algorithms/sea.hpp\"\n#include \"pagmo/algorithms/sade.hpp\"\n#include \"pagmo/algorithms/simulated_annealing.hpp\"\n#include \"pagmo/algorithms/bee_colony.hpp\"\n#include \"pagmo/algorithms/cmaes.hpp\"\n#include \"pagmo/algorithms/nlopt.hpp\"\n#include \"pagmo/algorithms/nsga2.hpp\"\n#include \"pagmo/algorithms/moead.hpp\"\n#include \"pagmo/problems/griewank.hpp\"\n#include \"pagmo/problems/schwefel.hpp\"\n#include \"pagmo/problems/rosenbrock.hpp\"\n#include \"pagmo/problems/cec2013.hpp\"\n#include \"pagmo/problems/zdt.hpp\"\n#include \"pagmo/island.hpp\"\n#include \"pagmo/problem.hpp\"\n#include \"Problems/himmelblau.h\"\n\ntemplate< typename OutputStream, typename ScalarType,\n          int NumberOfRows, int NumberOfColumns, int Options, int MaximumRows, int MaximumCols >\nvoid writeValueToStream( OutputStream& stream, const Eigen::Matrix< ScalarType,\n                         NumberOfRows, NumberOfColumns, Options,\n                         MaximumRows, MaximumCols >& value,\n                         const int precision, const std::string& delimiter,\n                         const bool endLineAfterRow  = 0 )\n{\n    for ( int i = 0; i < value.rows( ); i++ )\n    {\n        for ( int j = 0; j < value.cols( ); j++ )\n        {\n            stream << delimiter << \" \"\n                   << std::setprecision( precision ) << std::left\n                   << std::setw( precision + 1 )\n                   << value( i, j );\n\n\n        }\n        if( endLineAfterRow )\n        {\n            stream << std::endl;\n        }\n    }\n    stream << std::endl;\n}\n\ntemplate< typename ScalarType, int NumberOfRows, int NumberOfColumns >\nvoid writeMatrixToFile( Eigen::Matrix< ScalarType, NumberOfRows, NumberOfColumns > matrixToWrite,\n                        const std::string& outputFilename,\n                        const int precisionOfMatrixEntries = 16,\n                        const boost::filesystem::path& outputDirectory =\n        \"/home/dominic/Software/optimizationBundle/tudatBundle/tudatExampleApplications/libraryExamples/Pagmo2/bin/applications/\",\n                        const std::string& delimiter = \"\\t\",\n                        const std::string& header = \"\" )\n{\n    // Check if output directory exists; create it if it doesn't.\n    if ( !boost::filesystem::exists( outputDirectory ) )\n    {\n        boost::filesystem::create_directories( outputDirectory );\n    }\n\n    // Open output file.\n    std::string outputDirectoryAndFilename = outputDirectory.string( ) + \"/\" + outputFilename;\n    std::ofstream outputFile_( outputDirectoryAndFilename.c_str( ) );\n\n    // Write header\n    outputFile_ << header;\n\n    writeValueToStream( outputFile_, matrixToWrite, precisionOfMatrixEntries,\n                        delimiter, true );\n\n    outputFile_.close( );\n}\n\npagmo::algorithm getAlgorithm( const int index )\n{\n    switch( index )\n    {\n    case 0:\n    {\n        pagmo::algorithm algo{ pagmo::nsga2( ) };\n        return algo;\n        break;\n    }\n    case 1:\n    {\n        pagmo::algorithm algo{ pagmo::moead( ) };\n        return algo;\n        break;\n    }\n    case 2:\n    {\n        pagmo::algorithm algo{ pagmo::ihs( ) };\n        return algo;\n        break;\n    }\n    }\n}\n\nvoid printPopulationToFile( const int problemIndex, const int iterationIndex,\n                            const std::vector< pagmo::vector_double >& population,\n                            const bool isFitness )\n{\n    Eigen::MatrixXd matrixToPrint( population.size( ), population.at( 0 ).size( ) );\n    for( unsigned int i = 0; i < population.size( ); i++ )\n    {\n        for( unsigned int j = 0; j < population.at( 0 ).size( ); j++ )\n        {\n            matrixToPrint( i, j ) = population.at( i ).at( j );\n        }\n    }\n\n    if( !isFitness )\n    {\n        writeMatrixToFile( matrixToPrint, \"population_mo_\" + std::to_string( problemIndex ) + \"_\" + std::to_string( iterationIndex ) + \".dat\" );\n    }\n    else\n    {\n        writeMatrixToFile( matrixToPrint, \"fitness_mo_\" + std::to_string( problemIndex ) + \"_\" + std::to_string( iterationIndex ) + \".dat\" );\n    }\n}\n\nint main( )\n{\n    pagmo::random_device::set_seed( 12345 );\n\n    for( unsigned int i = 0; i < 3; i++ )\n    {\n        pagmo::problem prob{ pagmo::zdt( 3, 2 ) };//my_problem( 0, 5, 0, 5) };\n\n        pagmo::algorithm algo = getAlgorithm( i );\n\n        pagmo::island isl = pagmo::island{ algo, prob, 64 };\n\n        for( int j = 1; j <= 64; j++ )\n        {\n\n            isl.evolve( );\n\n            //isl.get_population( ).get_f()\n\n            printPopulationToFile( i, j, isl.get_population( ).get_x( ), false );\n            printPopulationToFile( i, j, isl.get_population( ).get_f( ), true );\n\n            //std::cout << \"Best x: \" << isl.get_population().champion_x()[0] << std::endl;\n            //std::cout << \"Best y: \" << isl.get_population().champion_x()[1] << std::endl;\n            while( isl.status()!=pagmo::evolve_status::idle )\n                isl.wait();\n\n        }\n        std::cout<<i<<\" done\"<<std::endl;\n    }\n    return 0;\n}\n", "meta": {"hexsha": "0e25e4d5b2fce829d998e9b9cc76eb1b9ba3a859", "size": 5201, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/pagmo/zdtMultiObjectiveOptimizerComparison.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/pagmo/zdtMultiObjectiveOptimizerComparison.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/pagmo/zdtMultiObjectiveOptimizerComparison.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": 32.1049382716, "max_line_length": 144, "alphanum_fraction": 0.5885406653, "num_tokens": 1300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2533643460662327}}
{"text": "#ifndef STAN_MATH_TORSTEN_GENERALODEMODEL_BDF_HPP\n#define STAN_MATH_TORSTEN_GENERALODEMODEL_BDF_HPP\n\n#include <Eigen/Dense>\n#include <stan/math/torsten/PKModel/functors/general_functor.hpp>\n#include <stan/math/torsten/PKModel/PKModel.hpp>\n#include <stan/math/torsten/PKModel/Pred/Pred1_general.hpp>\n#include <stan/math/torsten/PKModel/Pred/PredSS_general.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <vector>\n\nnamespace torsten {\n\n/**\n * Computes the predicted amounts in each compartment at each event\n * for a general compartment model, defined by a system of ordinary\n * differential equations. Uses the stan::math::integrate_ode_bdf \n * function. \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 that defines \n *            compartment model.\n * @param[in] nCmt number of compartments in model\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 * @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: currently have a dummy msgs argument. Makes it easier\n * to expose to stan grammar files, because I can follow more closely\n * what was done for the ODE integrator. Not ideal.\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>\ngeneralOdeModel_bdf(const F& f,\n                    const int nCmt,\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> >& pMatrix,\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-10,\n                    double abs_tol = 1e-10,\n                    long int max_num_steps = 1e8) {  // NOLINT(runtime/int)\n  using std::vector;\n  using Eigen::Dynamic;\n  using Eigen::Matrix;\n  using boost::math::tools::promote_args;\n\n  // check arguments\n  static const char* function(\"generalOdeModel_bdf\");\n  torsten::pmetricsCheck(time, amt, rate, ii, evid, cmt, addl, ss,\n                pMatrix, biovar, tlag, function);\n\n  // Construct dummy matrix for last argument of pred\n  Matrix<T4, Dynamic, Dynamic> dummy_system;\n  vector<Matrix<T4, Dynamic, Dynamic> >\n    dummy_systems(1, dummy_system);\n\n  typedef general_functor<F> F0;\n\n  return Pred(time, amt, rate, ii, evid, cmt, addl, ss,\n              pMatrix, biovar, tlag, nCmt, dummy_systems,\n              Pred1_general<F0>(F0(f), rel_tol, abs_tol,\n                                max_num_steps, msgs, \"bdf\"),\n              PredSS_general<F0>(F0(f), rel_tol, abs_tol,\n                                 max_num_steps, msgs, \"bdf\", nCmt));\n\n  // // check arguments\n  // static const char* function(\"generalOdeModel_bdf\");\n  // pmetricsCheck(time, amt, rate, ii, evid, cmt, addl, ss,\n  //               pMatrix, biovar, tlag, function);\n  //\n  // // Construct dummy matrix for last argument of pred\n  // Matrix<T4, Dynamic, Dynamic> dummy_system;\n  // vector<Matrix<T4, Dynamic, Dynamic> >\n  //   dummy_systems(1, dummy_system);\n  //\n  // typedef general_functor<F> F0;\n  //\n  // return Pred(time, amt, rate, ii, evid, cmt, addl, ss,\n  //             pMatrix, biovar, tlag, nCmt, dummy_systems,\n  //             Pred1_general<F0>(F0(f), rel_tol, abs_tol,\n  //                               max_num_steps, msgs, \"rk45\"),\n  //             PredSS_general<F0>(F0(f), rel_tol, abs_tol,\n  //                                max_num_steps, msgs, \"bdf\", nCmt));\n}\n\n/**\n * Overload function to allow user to pass an std::vector for \n * pMatrix.\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>\ngeneralOdeModel_bdf(const F& f,\n                     const int nCmt,\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>& pMatrix,\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_pMatrix(1, pMatrix);\n\n  return generalOdeModel_bdf(f, nCmt,\n                              time, amt, rate, ii, evid, cmt, addl, ss,\n                              vec_pMatrix, 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* pMatrix 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>\ngeneralOdeModel_bdf(const F& f,\n                     const int nCmt,\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>& pMatrix,\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_pMatrix(1, pMatrix);\n  std::vector<std::vector<T5> > vec_biovar(1, biovar);\n\n  return generalOdeModel_bdf(f, nCmt,\n                              time, amt, rate, ii, evid, cmt, addl, ss,\n                              vec_pMatrix, 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* pMatrix, 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>\ngeneralOdeModel_bdf(const F& f,\n                     const int nCmt,\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>& pMatrix,\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_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 generalOdeModel_bdf(f, nCmt,\n                              time, amt, rate, ii, evid, cmt, addl, ss,\n                              vec_pMatrix, 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* pMatrix 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>\ngeneralOdeModel_bdf(const F& f,\n                     const int nCmt,\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>& pMatrix,\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_pMatrix(1, pMatrix);\n  std::vector<std::vector<T6> > vec_tlag(1, tlag);\n\n  return generalOdeModel_bdf(f, nCmt,\n                              time, amt, rate, ii, evid, cmt, addl, ss,\n                              vec_pMatrix, 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>\ngeneralOdeModel_bdf(const F& f,\n                     const int nCmt,\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> >& pMatrix,\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 generalOdeModel_bdf(f, nCmt,\n                              time, amt, rate, ii, evid, cmt, addl, ss,\n                              pMatrix, 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>\ngeneralOdeModel_bdf(const F& f,\n                     const int nCmt,\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> >& pMatrix,\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 generalOdeModel_bdf(f, nCmt,\n                              time, amt, rate, ii, evid, cmt, addl, ss,\n                              pMatrix, 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 * 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>\ngeneralOdeModel_bdf(const F& f,\n                     const int nCmt,\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> >& pMatrix,\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 generalOdeModel_bdf(f, nCmt,\n                              time, amt, rate, ii, evid, cmt, addl, ss,\n                              pMatrix, biovar, vec_tlag,\n                              msgs, rel_tol, abs_tol, max_num_steps);\n}\n\n}\n\n#endif\n", "meta": {"hexsha": "b9c01e48191c5cf83a098b96de02462ad8180f7f", "size": 16358, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/torsten/generalOdeModel_bdf.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/generalOdeModel_bdf.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/generalOdeModel_bdf.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.2108108108, "max_line_length": 77, "alphanum_fraction": 0.54737743, "num_tokens": 4157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.25324480231597646}}
{"text": "/*\nsystem.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 \"system.h\"\n#include \"fcs_phonon.h\"\n#include \"error.h\"\n#include \"memory.h\"\n#include \"constants.h\"\n#include \"symmetry_core.h\"\n#include <string>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include \"mathfunctions.h\"\n#include \"xml_parser.h\"\n#include <sstream>\n#include <map>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/xml_parser.hpp>\n#include <boost/foreach.hpp>\n#include <boost/optional.hpp>\n#include <boost/lexical_cast.hpp>\n\nusing namespace PHON_NS;\n\nSystem::System(PHON *phon): Pointers(phon) {}\n\nSystem::~System() {\n    memory->deallocate(xr_p);\n    memory->deallocate(xr_s);\n    memory->deallocate(xr_s_anharm);\n    memory->deallocate(kd);\n    memory->deallocate(kd_anharm);\n    memory->deallocate(xc);\n    memory->deallocate(mass);\n    memory->deallocate(map_p2s);\n    memory->deallocate(map_p2s_anharm);\n    memory->deallocate(map_s2p);\n    memory->deallocate(map_s2p_anharm);\n    memory->deallocate(mass_kd);\n    memory->deallocate(magmom);\n}\n\nvoid System::setup()\n{\n    using namespace std;\n\n    unsigned int i, j;\n    double vec_tmp[3][3];\n    unsigned int *kd_prim;\n    double **xtmp;\n\n    load_system_info_from_XML();\n\n    recips(lavec_s, rlavec_s);\n    recips(lavec_s_anharm, rlavec_s_anharm);\n    recips(lavec_p, rlavec_p);\n\n    memory->allocate(xr_p, nat, 3);\n    memory->allocate(xc, nat, 3);\n\n    for (i = 0; i < nat; ++i){\n        rotvec(xc[i], xr_s[i], lavec_s);\n        rotvec(xr_p[i], xc[i], rlavec_p);\n        for(j = 0; j < 3; ++j){\n            xr_p[i][j] /=  2.0 * pi;\n        }\n    }\n\n    if (mympi->my_rank == 0) {\n        cout << \" ------------------------------------------------------------\" << endl;\n        cout << endl;\n        cout << \" Crystal structure\" << endl;\n        cout << \" =================\" << endl << endl;\n        cout << \" Lattice Vectors:\" << endl << endl;\n        cout.setf(ios::scientific);\n\n        cout << \" * Supercell (from \" << fcs_phonon->file_fcs << \" )\" << endl << endl;\n        cout << setw(16) << lavec_s_anharm[0][0] << setw(15) << lavec_s_anharm[1][0] << setw(15) << lavec_s_anharm[2][0] << \" : a1\" << endl;\n        cout << setw(16) << lavec_s_anharm[0][1] << setw(15) << lavec_s_anharm[1][1] << setw(15) << lavec_s_anharm[2][1] << \" : a2\" << endl;\n        cout << setw(16) << lavec_s_anharm[0][2] << setw(15) << lavec_s_anharm[1][2] << setw(15) << lavec_s_anharm[2][2] << \" : a3\" << endl;\n        cout << endl;\n\n        cout << setw(16) << rlavec_s_anharm[0][0] << setw(15) << rlavec_s_anharm[0][1] << setw(15) << rlavec_s_anharm[0][2] << \" : b1\" << endl;\n        cout << setw(16) << rlavec_s_anharm[1][0] << setw(15) << rlavec_s_anharm[1][1] << setw(15) << rlavec_s_anharm[1][2] << \" : b2\" << endl;\n        cout << setw(16) << rlavec_s_anharm[2][0] << setw(15) << rlavec_s_anharm[2][1] << setw(15) << rlavec_s_anharm[2][2] << \" : b3\" << endl;\n        cout << endl;\n\n        cout << \" * Primitive cell \" << endl << endl;\n        cout << setw(16) << lavec_p[0][0] << setw(15) << lavec_p[1][0] << setw(15) << lavec_p[2][0] << \" : a1\" << endl;\n        cout << setw(16) << lavec_p[0][1] << setw(15) << lavec_p[1][1] << setw(15) << lavec_p[2][1] << \" : a2\" << endl;\n        cout << setw(16) << lavec_p[0][2] << setw(15) << lavec_p[1][2] << setw(15) << lavec_p[2][2] << \" : a3\" << endl;\n        cout << endl;\n\n        cout << setw(16) << rlavec_p[0][0] << setw(15) << rlavec_p[0][1] << setw(15) << rlavec_p[0][2] << \" : b1\" << endl;\n        cout << setw(16) << rlavec_p[1][0] << setw(15) << rlavec_p[1][1] << setw(15) << rlavec_p[1][2] << \" : b2\" << endl;\n        cout << setw(16) << rlavec_p[2][0] << setw(15) << rlavec_p[2][1] << setw(15) << rlavec_p[2][2] << \" : b3\" << endl;\n        cout << endl << endl;\n\n\n        for (i = 0; i < 3; ++i){\n            for (j = 0; j < 3; ++j){\n                vec_tmp[i][j] = lavec_p[j][i];\n            }\n        }\n        volume_p = volume(vec_tmp[0], vec_tmp[1], vec_tmp[2]);\n\n        cout << \"  Volume of the primitive cell : \" << volume_p << \" (a.u.)^3\" << endl << endl;\n        cout << \"  Number of atoms in the supercell     : \" << nat_anharm << endl;\n        cout << \"  Number of atoms in the primitive cell: \" << natmin << endl << endl;\n\n        if (fcs_phonon->update_fc2) {\n            cout << endl;\n            cout << \"  FC2XML is given: Harmonic IFCs will be replaced by the values in \" << fcs_phonon->file_fc2 << endl;\n            cout << endl;\n\n            cout << \" * Supercell for HARMONIC (from \" << fcs_phonon->file_fc2 << \" )\" << endl << endl;\n            cout << setw(16) << lavec_s[0][0] << setw(15) << lavec_s[1][0] << setw(15) << lavec_s[2][0] << \" : a1\" << endl;\n            cout << setw(16) << lavec_s[0][1] << setw(15) << lavec_s[1][1] << setw(15) << lavec_s[2][1] << \" : a2\" << endl;\n            cout << setw(16) << lavec_s[0][2] << setw(15) << lavec_s[1][2] << setw(15) << lavec_s[2][2] << \" : a3\" << endl;\n            cout << endl;\n\n            cout << setw(16) << rlavec_s[0][0] << setw(15) << rlavec_s[0][1] << setw(15) << rlavec_s[0][2] << \" : b1\" << endl;\n            cout << setw(16) << rlavec_s[1][0] << setw(15) << rlavec_s[1][1] << setw(15) << rlavec_s[1][2] << \" : b2\" << endl;\n            cout << setw(16) << rlavec_s[2][0] << setw(15) << rlavec_s[2][1] << setw(15) << rlavec_s[2][2] << \" : b3\" << endl;\n            cout << endl;\n\n            cout << \"  Number of atoms in the supercell (HARMONIC)   : \" << nat << endl;\n            cout << endl;\n        }\n\n        memory->allocate(xtmp, natmin, 3);\n\n        for (i = 0; i < natmin; ++i) {\n            rotvec(xtmp[i], xr_s[map_p2s[i][0]], lavec_s);\n            rotvec(xtmp[i], xtmp[i], rlavec_p);\n            for (j = 0; j < 3; ++j) xtmp[i][j] /= 2.0 * pi;\n        }\n\n        cout << \"  Atomic positions in the primitive cell (fractional):\" << endl;\n        for (i = 0; i < natmin; ++i){\n            cout << setw(4) << i + 1 << \":\";\n            for (j = 0; j < 3; ++j) {\n                cout << setw(15) << xtmp[i][j];\n            }\n            cout << setw(4) << symbol_kd[kd[map_p2s[i][0]]] << endl;\n        }\n        cout << endl;\n\n        memory->deallocate(xtmp);\n\n        if (lspin) {\n            cout << \"  MagneticMoments entry found in the XML file. \" << endl;\n            cout << \"  Magnetic moment in Cartesian coordinates: \" << endl;\n            for (i = 0; i < natmin; ++i) {\n                cout << setw(4) << i + 1 << \":\";\n                for (j = 0; j < 3; ++j) {\n                    cout << setw(15) << magmom[i][j];\n                }\n                cout << endl;\n            }\n            cout << endl;\n            if (noncollinear == 0) {\n                cout << \"  Collinear calculation: magnetic moments are considered as scalar variables.\" << endl;\n            } else if (noncollinear == 1) {\n                cout << \"  Noncollinear calculation: magnetic moments are considered as vector variables.\" << endl;\n                if (symmetry->trev_sym_mag) {\n                    cout << \"  Time-reversal symmetry will be considered for generating magnetic space group\" << endl;\n                } else {\n                    cout << \"  Time-reversal symmetry will NOT be considered for generating magnetic space group\" << endl;\n                }\n            }\n            cout << endl;\n        }\n\n        cout << \"  Mass of atomic species (u):\" << endl;\n        for (i = 0; i < nkd; ++i) {\n            cout << setw(4) << symbol_kd[i] << \":\";\n            cout << fixed << setw(12) << mass_kd[i] << endl;\n        }\n        cout << endl << endl;\n    }\n\n    // Atomic masses in Rydberg unit\n\n    memory->allocate(mass, nat);\n    memory->allocate(mass_anharm, nat_anharm);\n    for (i = 0; i < nat; ++i){\n        mass[i] = mass_kd[kd[i]]*amu_ry;\n    }\n    for (i = 0; i < nat_anharm; ++i) {\n        mass_anharm[i] = mass_kd[kd_anharm[i]]*amu_ry;\n    }\n    MPI_Bcast(&Tmin, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&Tmax, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&dT, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&volume_p, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n\n    memory->allocate(kd_prim, natmin);\n\n    for (i = 0; i < natmin; ++i) {\n        kd_prim[i] = kd[map_p2s[i][0]];\n    }\n    MPI_Bcast(&lspin, 1, MPI_LOGICAL, 0, MPI_COMM_WORLD);\n    if (mympi->my_rank > 0) {\n        memory->allocate(magmom, natmin, 3);\n    }\n    MPI_Bcast(&magmom[0][0], 3*natmin, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&noncollinear, 1, MPI_INT, 0, MPI_COMM_WORLD);\n\n    setup_atomic_class(natmin, kd_prim, magmom);\n\n    memory->deallocate(kd_prim);\n}\n\nvoid System::load_system_info_from_XML()\n{\n    if (mympi->my_rank == 0) {\n\n        int i;\n        using namespace boost::property_tree;\n        ptree pt;\n        int nkd_tmp;\n\n        std::map<std::string, int> dict_atomic_kind;\n\n        try {\n            read_xml(fcs_phonon->file_fcs, pt);\n        } \n        catch (std::exception &e) {\n            std::string str_error = \"Cannot open file FCSXML ( \" + fcs_phonon->file_fcs + \" )\";\n            error->exit(\"load_system_info_from_XML\", str_error.c_str());\n        }\n\n        // Parse nat and ntran\n\n        nat = boost::lexical_cast<unsigned int>(get_value_from_xml(pt, \"Data.Structure.NumberOfAtoms\"));\n        nkd_tmp = boost::lexical_cast<unsigned int>(get_value_from_xml(pt, \"Data.Structure.NumberOfElements\"));\n\n        if (nkd != nkd_tmp) error->exit(\"load_system_info_from_XML\", \n            \"NKD in the FCSXML file is not consistent with that given in the input file.\");\n\n        ntran = boost::lexical_cast<unsigned int>(get_value_from_xml(pt, \"Data.Symmetry.NumberOfTranslations\"));\n\n        natmin = nat / ntran;\n\n        // Parse lattice vectors\n\n        std::stringstream ss;\n\n        for (i = 0; i < 3; ++i) {\n            ss.str(\"\");\n            ss.clear();\n            ss << get_value_from_xml(pt, \n                \"Data.Structure.LatticeVector.a\" + boost::lexical_cast<std::string>(i + 1));\n            ss >> lavec_s[0][i] >> lavec_s[1][i] >> lavec_s[2][i];\n        }\n\n        // Parse atomic elements and coordinates\n\n        memory->allocate(xr_s, nat, 3);\n        memory->allocate(kd, nat);\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<std::string>(child_.second.data())] = icount_kd - 1;\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 std::string str_index = child.get<std::string>(\"<xmlattr>.index\");\n            const std::string str_element = child.get<std::string>(\"<xmlattr>.element\");\n\n            ss.str(\"\");\n            ss.clear();\n            ss << child.data();\n\n            index = boost::lexical_cast<unsigned int>(str_index) - 1;\n\n            if (index >= nat) error->exit(\"load_system_info_xml\", \"index is out of range\");\n\n            kd[index] = dict_atomic_kind[str_element];\n            ss >> 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        memory->allocate(map_p2s, natmin, ntran);\n        memory->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 std::string str_tran = child.get<std::string>(\"<xmlattr>.tran\");\n            const std::string str_atom = child.get<std::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                error->exit(\"load_system_info_xml\", \"index is out of range\");\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        // Parse magnetic moments\n\n        double **magmom_tmp;\n        memory->allocate(magmom_tmp, nat, 3);\n        memory->allocate(magmom, natmin, 3);\n\n        lspin = true;\n        try {\n            BOOST_FOREACH (const ptree::value_type& child_, pt.get_child(\"Data.MagneticMoments\")) {\n                if (child_.first == \"mag\") {\n                    const ptree& child = child_.second;\n                    const std::string str_index = child.get<std::string>(\"<xmlattr>.index\");\n\n                    ss.str(\"\");\n                    ss.clear();\n                    ss << child.data();\n\n                    index = boost::lexical_cast<unsigned int>(str_index) - 1;\n\n                    if (index >= nat) error->exit(\"load_system_info_xml\", \"index is out of range\");\n\n                    ss >> magmom_tmp[index][0] >> magmom_tmp[index][1] >> magmom_tmp[index][2];\n                }\n            }\n\n        } catch(...) {\n            lspin = false;\n        }\n\n        if (lspin) {\n            for (i = 0; i < natmin; ++i) {\n                for (int j = 0; j < 3; ++j) {\n                    magmom[i][j] = magmom_tmp[map_p2s[i][0]][j];\n                }\n            }\n\n            try {\n                noncollinear = boost::lexical_cast<int>(get_value_from_xml(pt, \"Data.MagneticMoments.Noncollinear\"));\n            } catch(...) {\n                noncollinear = 0;\n            }\n\n            try {\n                symmetry->trev_sym_mag = boost::lexical_cast<int>(get_value_from_xml(pt, \"Data.MagneticMoments.TimeReversalSymmetry\"));\n            } catch(...) {\n                symmetry->trev_sym_mag = true;\n            }\n        } else {\n            for (i = 0; i < natmin; ++i) {\n                for (int j = 0; j < 3; ++j) {\n                    magmom[i][j] = 0.0;\n                }\n            }\n            noncollinear = 0;\n            symmetry->trev_sym_mag = true;\n        }\n        memory->deallocate(magmom_tmp);\n\n        // Now, replicate the information for anharmonic terms.\n\n        int j;\n        nat_anharm = nat;\n        ntran_anharm = ntran;\n        memory->allocate(xr_s_anharm, nat_anharm, 3);\n        memory->allocate(kd_anharm, nat_anharm);\n        memory->allocate(map_p2s_anharm, natmin, ntran_anharm);\n        memory->allocate(map_s2p_anharm, nat_anharm);\n\n        for (i = 0; i < 3; ++i) {\n            for (j = 0; j < 3; ++j) lavec_s_anharm[i][j] = lavec_s[i][j];\n        }\n        for (i = 0; i < nat_anharm; ++i) {\n            for (j = 0; j < 3; ++j) xr_s_anharm[i][j] = xr_s[i][j];\n            kd_anharm[i] = kd[i];\n            map_s2p_anharm[i] = map_s2p[i];\n        }\n        for (i = 0; i < natmin; ++i) {\n            for (j = 0; j < ntran_anharm; ++j) {\n                map_p2s_anharm[i][j] = map_p2s[i][j];\n            }\n        }\n\n        if (fcs_phonon->update_fc2) {\n\n            // When FC2XML is given, structural information is updated only for harmonic terms.\n\n            int natmin_tmp;\n\n            try {\n                read_xml(fcs_phonon->file_fc2, pt);\n            } \n            catch (std::exception &e) {\n                std::string str_error = \"Cannot open file FC2XML ( \" + fcs_phonon->file_fc2 + \" )\";\n                error->exit(\"load_system_info_from_XML\", str_error.c_str());\n            }\n\n            // Parse nat and ntran\n\n            nat = boost::lexical_cast<unsigned int>(get_value_from_xml(pt, \"Data.Structure.NumberOfAtoms\"));\n            nkd_tmp = boost::lexical_cast<unsigned int>(get_value_from_xml(pt, \"Data.Structure.NumberOfElements\"));\n\n            if (nkd != nkd_tmp) error->exit(\"load_system_info_from_XML\", \n                \"NKD in the FC2XML file is not consistent with that given in the input file.\");\n\n            ntran = boost::lexical_cast<unsigned int>(get_value_from_xml(pt, \"Data.Symmetry.NumberOfTranslations\"));\n\n            natmin_tmp = nat / ntran;\n\n            if (natmin_tmp != natmin) error->exit(\"load_system_info_from_XML\",\n                \"Number of atoms in a primitive cell is different in FCSXML and FC2XML.\");\n\n            memory->deallocate(xr_s);\n            memory->deallocate(kd);\n            memory->deallocate(map_p2s);\n            memory->deallocate(map_s2p);\n\n\n            // Parse lattice vectors\n\n            std::stringstream ss;\n\n            for (i = 0; i < 3; ++i) {\n                ss.str(\"\");\n                ss.clear();\n                ss << get_value_from_xml(pt, \n                    \"Data.Structure.LatticeVector.a\" + boost::lexical_cast<std::string>(i + 1));\n                ss >> lavec_s[0][i] >> lavec_s[1][i] >> lavec_s[2][i];\n            }\n\n            // Parse atomic elements and coordinates\n\n            memory->allocate(xr_s, nat, 3);\n            memory->allocate(kd, nat);\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<std::string>(child_.second.data())] = icount_kd - 1;\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 std::string str_index = child.get<std::string>(\"<xmlattr>.index\");\n                const std::string str_element = child.get<std::string>(\"<xmlattr>.element\");\n\n                ss.str(\"\");\n                ss.clear();\n                ss << child.data();\n\n                index = boost::lexical_cast<unsigned int>(str_index) - 1;\n\n                if (index >= nat) error->exit(\"load_system_info_xml\", \"index is out of range\");\n\n                kd[index] = dict_atomic_kind[str_element];\n                ss >> 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            memory->allocate(map_p2s, natmin, ntran);\n            memory->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 std::string str_tran = child.get<std::string>(\"<xmlattr>.tran\");\n                const std::string str_atom = child.get<std::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                    error->exit(\"load_system_info_xml\", \"index is out of range\");\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\n    MPI_Bcast(&lavec_s[0][0], 9, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&lavec_p[0][0], 9, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&lavec_s_anharm[0][0], 9, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n\n    MPI_Bcast(&nkd, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&nat, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&nat_anharm, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&natmin, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&ntran, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&ntran_anharm, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&lspin, 1, MPI_LOGICAL, 0, MPI_COMM_WORLD);\n\n    if (mympi->my_rank > 0){\n        memory->allocate(mass_kd, nkd);\n        memory->allocate(xr_s, nat, 3);\n        memory->allocate(xr_s_anharm, nat_anharm, 3);\n        memory->allocate(kd, nat);\n        memory->allocate(kd_anharm, nat_anharm);\n        memory->allocate(map_p2s, natmin, ntran);\n        memory->allocate(map_p2s_anharm, natmin, ntran_anharm);\n        memory->allocate(map_s2p, nat);\n        memory->allocate(map_s2p_anharm, nat_anharm);\n        if (lspin) {\n            memory->allocate(magmom, natmin, 3);\n        }\n    }\n\n    MPI_Bcast(&mass_kd[0], nkd, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&xr_s[0][0], 3*nat, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&xr_s_anharm[0][0], 3*nat_anharm, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&kd[0], nat, MPI_UNSIGNED, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&kd_anharm[0], nat_anharm, MPI_UNSIGNED, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&map_p2s[0][0], natmin*ntran, MPI_UNSIGNED, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&map_p2s_anharm[0][0], natmin*ntran_anharm, MPI_UNSIGNED, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&map_s2p[0], nat*sizeof(map_s2p[0]), MPI_BYTE, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&map_s2p_anharm[0], nat_anharm*sizeof(map_s2p_anharm[0]), MPI_BYTE, 0, MPI_COMM_WORLD);\n    if (lspin) MPI_Bcast(&magmom[0][0], 3*natmin, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n\n}\n\n\nvoid System::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(std::abs(det) < eps12) {\n        error->exit(\"recips\", \"Lattice Vector is singular\");\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\ndouble System::volume(double vec1[3], double vec2[3], double vec3[3])\n{\n    double vol;\n\n    vol = std::abs(vec1[0]*(vec2[1]*vec3[2] - vec2[2]*vec3[1]) \n        + vec1[1]*(vec2[2]*vec3[0] - vec2[0]*vec3[2]) \n        + vec1[2]*(vec2[0]*vec3[1] - vec2[1]*vec3[0]));\n\n    return vol;\n}\n\n\nvoid System::setup_atomic_class(unsigned int N, unsigned int *kd, double **magmom_in) {\n\n\n    // In the case of collinear calculation, spin moments are considered as scalar\n    // variables. Therefore, the same elements with different magnetic moments are\n    // considered as different types. In noncollinear calculations, \n    // magnetic moments are not considered in this stage. They will be treated\n    // separately in symmetry.cpp where spin moments will be rotated and flipped \n    // using time-reversal symmetry.\n\n    unsigned int i;\n    AtomType type_tmp;\n    std::set<AtomType> set_type;\n    set_type.clear();\n\n    for (i = 0; i < N; ++i) {\n        type_tmp.element = kd[i];\n\n        if (noncollinear == 0) {\n            type_tmp.magmom = magmom_in[i][2];\n        } else {\n            type_tmp.magmom = 0.0;\n        }\n        set_type.insert(type_tmp);\n    }\n\n    nclassatom = set_type.size();\n\n    memory->allocate(atomlist_class, nclassatom);\n\n    for (i = 0; i < N; ++i) {\n        int count = 0;\n        for (std::set<AtomType>::iterator it = set_type.begin(); it != set_type.end(); ++it) {\n            if (noncollinear) {\n                if (kd[i] == (*it).element) {\n                    atomlist_class[count].push_back(i);\n                }\n            } else {\n                if (kd[i] == (*it).element && std::abs(magmom[i][2] - (*it).magmom) < eps6) {\n                    atomlist_class[count].push_back(i);\n                }\n            }\n            ++count;\n        }\n    }\n    set_type.clear();\n}\n", "meta": {"hexsha": "8d016168f3293b865a89df2df0afb111dee21cc0", "size": 24394, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "anphon/system.cpp", "max_stars_repo_name": "dlnguyen/alamode", "max_stars_repo_head_hexsha": "f99d333262489f28a3ef4838dfbe3147dc239261", "max_stars_repo_licenses": ["MIT"], "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/system.cpp", "max_issues_repo_name": "dlnguyen/alamode", "max_issues_repo_head_hexsha": "f99d333262489f28a3ef4838dfbe3147dc239261", "max_issues_repo_licenses": ["MIT"], "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/system.cpp", "max_forks_repo_name": "dlnguyen/alamode", "max_forks_repo_head_hexsha": "f99d333262489f28a3ef4838dfbe3147dc239261", "max_forks_repo_licenses": ["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.0561622465, "max_line_length": 143, "alphanum_fraction": 0.5388620152, "num_tokens": 7307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2531282369315523}}
{"text": "//  (C) Copyright John Maddock 2005.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_COMPLEX_DETAILS_INCLUDED\n#define BOOST_MATH_COMPLEX_DETAILS_INCLUDED\n//\n// This header contains all the support code that is common to the\n// inverse trig complex functions, it also contains all the includes\n// that we need to implement all these functions.\n//\n\n#include <cmath>\n#include <complex>\n#include <limits>\n#include <boost/math/special_functions/sign.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/math/special_functions/sign.hpp>\n#include <boost/math/constants/constants.hpp>\n\nnamespace boost{ namespace math{ namespace detail{\n\ntemplate <class T>\ninline T mult_minus_one(const T& t)\n{\n   return (boost::math::isnan)(t) ? t : (boost::math::changesign)(t);\n}\n\ntemplate <class T>\ninline std::complex<T> mult_i(const std::complex<T>& t)\n{\n   return std::complex<T>(mult_minus_one(t.imag()), t.real());\n}\n\ntemplate <class T>\ninline std::complex<T> mult_minus_i(const std::complex<T>& t)\n{\n   return std::complex<T>(t.imag(), mult_minus_one(t.real()));\n}\n\ntemplate <class T>\ninline T safe_max(T t)\n{\n   return std::sqrt((std::numeric_limits<T>::max)()) / t;\n}\ninline long double safe_max(long double t)\n{\n   // long double sqrt often returns infinity due to\n   // insufficient internal precision:\n   return std::sqrt((std::numeric_limits<double>::max)()) / t;\n}\n\ntemplate <class T>\ninline T safe_min(T t)\n{\n   return std::sqrt((std::numeric_limits<T>::min)()) * t;\n}\ninline long double safe_min(long double t)\n{\n   // long double sqrt often returns zero due to\n   // insufficient internal precision:\n   return std::sqrt((std::numeric_limits<double>::min)()) * t;\n}\n\n} } } // namespaces\n\n#endif // BOOST_MATH_COMPLEX_DETAILS_INCLUDED\n\n", "meta": {"hexsha": "f439085107c904f1cf9455da6d8df24b4f5033e4", "size": 1916, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/complex/details.hpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "include/boost/math/complex/details.hpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "include/boost/math/complex/details.hpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 27.3714285714, "max_line_length": 69, "alphanum_fraction": 0.7223382046, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2530683252493278}}
{"text": "// $Id$\n/*\n * This is an extensive modification by Greg Landrum of\n * pieces from several files in the vflib-2.0 distribution\n *\n * The initial version of the modifications was completed\n *   in April 2009.\n *\n * the original author of the vflib files is:\n *    Author: P. Foggia\n *  http://amalfi.dis.unina.it/graph/db/vflib-2.0/doc/vflib.html\n *\n */\n#include <boost/graph/adjacency_list.hpp>\n#include <vector>\n#include <algorithm>\n#include <cstring>\n\n#ifndef __BGL_VF2_SUB_STATE_H__\n#define __BGL_VF2_SUB_STATE_H__\n//#define RDK_VF2_PRUNING\n#define RDK_ADJ_ITER typename Graph::adjacency_iterator\n\nnamespace boost{\n  namespace detail {\n    typedef unsigned short node_id;\n    const node_id NULL_NODE=0xFFFF;\n    struct NodeInfo {\n      node_id id;\n      node_id in;\n      node_id out;\n    };\n    \n    template <class Graph>\n    struct Pair {\n      node_id n1, n2;\n      bool hasiter;\n      RDK_ADJ_ITER nbrbeg, nbrend;\n      \n      Pair() : n1(NULL_NODE), n2(NULL_NODE), hasiter(false) {\n      }\n    };\n\n    /**\n     * The ordering by in/out degree\n     */\n    static bool nodeInfoComp1(const NodeInfo &a, const NodeInfo &b) {\n      if(a.out < b.out) return true;\n      if(a.out > b.out) return false;\n      if(a.in < b.in) return true;\n      if(a.in > b.in) return false;\n      return false;\n    }\n\n    /**\n     * The ordering by frequency/valence.\n     * The frequency is in the out field, the valence in `in'.\n     */\n    static int nodeInfoComp2(const NodeInfo &a, const NodeInfo &b) {\n      if (!a.in && b.in ) return 1;\n      if (a.in && !b.in) return -1;\n      if (a.out < b.out) return -1;\n      if (a.out > b.out) return 1;\n      if( a.in < b.in ) return -1;\n      if (a.in > b.in) return 1;\n      return 0;\n    }\n\n    template <class Graph,class VertexDescr,class EdgeDescr> \n    VertexDescr getOtherIdx(const Graph &g,const EdgeDescr &edge,const VertexDescr &vertex) {\n      VertexDescr tmp=boost::source(edge,g);\n      if(tmp==vertex){\n        tmp=boost::target(edge,g);\n      }\n      return tmp;\n    }\n  \n    /*----------------------------------------------------\n     * Sorts the nodes of a graphs, returning a \n     * heap-allocated vector (using new) with the node ids\n     * in the proper orders.\n     * The sorting criterion takes into account:\n     *    1 - The number of nodes with the same in/out \n     *        degree.\n     *    2 - The valence of the nodes.\n     * The nodes at the beginning of the vector are\n     * the most singular, from which the matching should\n     * start.\n     *--------------------------------------------------*/\n    template <class Graph>\n    node_id* SortNodesByFrequency(const Graph *g) {\n      std::vector<NodeInfo> vect;\n      vect.reserve(boost::num_vertices(*g));\n      typename Graph::vertex_iterator bNode,eNode;\n      boost::tie(bNode,eNode) = boost::vertices(*g);\n      while(bNode!=eNode){\n        NodeInfo t;\n        t.id=vect.size();\n        t.in=boost::out_degree(*bNode,*g);// <- assuming undirected graph\n        t.out=boost::out_degree(*bNode,*g); \n        vect.push_back(t);\n        ++bNode;\n      }\n      std::sort(vect.begin(),vect.end(),nodeInfoComp1);\n    \n      unsigned int run=1;\n      for(unsigned int i=0; i<vect.size(); i+=run){\n        for(run=1; i+run<vect.size() && \n              vect[i+run].in==vect[i].in && \n              vect[i+run].out==vect[i].out;\n            ++run) \n          ;\n        for(unsigned int j=0; j<run; ++j) {\n          vect[i+j].in += vect[i+j].out;\n          vect[i+j].out=run;\n        }\n      }\n      std::sort(vect.begin(),vect.end(),nodeInfoComp2);\n    \n      node_id *nodes=new node_id[vect.size()];\n      for(unsigned int i=0; i<vect.size(); ++i){\n        nodes[i]=vect[i].id;\n      }\n    \n      return nodes;\n    }\n\n    /*----------------------------------------------------------\n     * class VF2SubState\n     * A representation of the SSS current state\n     ---------------------------------------------------------*/\n    template <class Graph,class VertexCompatible,class EdgeCompatible,class MatchChecking >\n    class VF2SubState\n    { \n    private:\n      Graph *g1, *g2;\n      VertexCompatible &vc;\n      EdgeCompatible &ec;\n      MatchChecking &mc;\n      unsigned int n1, n2;\n\n      unsigned int core_len;\n      unsigned int t1_len;\n      unsigned int t2_len; // Core nodes are also counted by these...\n      node_id *core_1;\n      node_id *core_2;\n      node_id *term_1;\n      node_id *term_2;\n\n      node_id *order;\n\n      long *share_count;\n      int *vs_compared;\n    \n    public:\n      VF2SubState(Graph *ag1, Graph *ag2,\n                  VertexCompatible &avc,\n                  EdgeCompatible &aec,\n                  MatchChecking &amc,\n                  bool sortNodes=false) : g1(ag1), g2(ag2), vc(avc), ec(aec), mc(amc),\n                                          n1(num_vertices(*ag1)),n2(num_vertices(*ag2)) {\n        if (sortNodes){\n          order = SortNodesByFrequency(ag1);\n        } else {\n          order = NULL;\n        }\n\n        core_len=0;\n        t1_len=0;\n        t2_len=0;\n\n        core_1=new node_id[n1];\n        core_2=new node_id[n2];\n        term_1=new node_id[n1];\n        term_2=new node_id[n2];\n        share_count = new long;\n\n        for(unsigned int i=0; i<n1; i++){\n          core_1[i]=NULL_NODE;\n          term_1[i]=0;\n        }\n        for(unsigned int i=0; i<n2; i++){\n          core_2[i]=NULL_NODE;\n          term_2[i]=0;\n        }\n        vs_compared=0;\n        //vs_compared = new int[n1*n2];\n        //memset((void *)vs_compared,0,n1*n2*sizeof(int));\n        \n        //es_compared = new std::map<unsigned int,bool>();\n        *share_count = 1;\n      };\n\n      VF2SubState(const VF2SubState &state) :\n        g1(state.g1), g2(state.g2), vc(state.vc), ec(state.ec), mc(state.mc),\n        n1(state.n1),n2(state.n2), order(state.order),vs_compared(state.vs_compared)\n        //es_compared(state.es_compared)\n      {\n\n        core_len=state.core_len;\n        t1_len=state.t1_len;\n        t2_len=state.t2_len;\n\n        core_1=state.core_1;\n        core_2=state.core_2;\n        term_1=state.term_1;\n        term_2=state.term_2;\n        share_count=state.share_count;\n\n        ++(*share_count);\n      };\n\n      ~VF2SubState(){\n        if (-- *share_count == 0) {\n          delete [] core_1;\n          delete [] core_2;\n          delete [] term_1;\n          delete [] term_2;\n          delete share_count;\n          delete [] order;\n          //delete [] vs_compared;\n          //delete es_compared;\n        }\n      }; \n\n      bool IsGoal() { return core_len==n1 ; };\n      bool MatchChecks(const node_id c1[],const node_id c2[]){\n        return mc(c1,c2);\n      };\n      bool IsDead() { return n1>n2  || \n          t1_len>t2_len;\n      };\n      unsigned int CoreLen() { return core_len; }\n      Graph *GetGraph1() { return g1; }\n      Graph *GetGraph2() { return g2; }\n\n      bool NextPair(Pair<Graph> &pair){\n        if (pair.n1==NULL_NODE)\n          pair.n1=0;\n        if (pair.n2==NULL_NODE)\n          pair.n2=0;\n        else\n          pair.n2++;\n\n#if 0\n    std::cerr<<\" **** np: \"<< prev_n1<<\",\"<<prev_n2<<std::endl;\n    std::cerr<<\"in_1 \";\n    for(unsigned int i=0;i<n1;++i){\n      std::cerr<<\"(\"<<in_1[i]<<\",\"<<out_1[i]<<\"), \";\n    } \n    std::cerr<<std::endl;\n    std::cerr<<\"in_2 \";\n    for(unsigned int i=0;i<n2;++i){\n      std::cerr<<\"(\"<<in_2[i]<<\",\"<<out_2[i]<<\"), \";\n    } \n    std::cerr<<std::endl;\n#endif\n        if (t1_len>core_len && t2_len>core_len) {\n          while (pair.n1<n1 &&\n                 (core_1[pair.n1]!=NULL_NODE || term_1[pair.n1]==0) ) {\n            pair.n1++;\n            pair.n2=0;\n          }\n          \n          /* Initialize VF2 Plus neighbor iterator.\n           * The next query node (pair.n1) has been selected from the terminal\n           * set and is therefore adjacent to an already mapped atom (in\n           * core_1). Rather than select pair.n2 from all atoms (0...n2) we can\n           * select it from the neighbors of this mapped atom (0...deg(nbor))\n           * since it must also be adajcent to this mapped atom!\n           */\n          if (!pair.hasiter) {\n            RDK_ADJ_ITER n1iter_beg, n1iter_end;\n            boost::tie(n1iter_beg, n1iter_end)\n            = boost::adjacent_vertices(pair.n1,*g1);\n\n            while (n1iter_beg!=n1iter_end && core_1[*n1iter_beg]==NULL_NODE)\n              ++n1iter_beg;\n\n            assert(n1iter_beg!=n1iter_end);\n\n            boost::tie(pair.nbrbeg, pair.nbrend)\n              = boost::adjacent_vertices(core_1[*n1iter_beg],*g2);\n            pair.hasiter = true;\n          }\n        }\n        else if (pair.n1==0 && order!=NULL) {\n          // Optimisation: if the order vector is laid out in a DFS/BFS then this\n          // loop can be replaced with:\n          //   pair.n1=order[core_len];\n          // :)\n          unsigned int i=0;\n          while (i<n1 && core_1[pair.n1=order[i]] != NULL_NODE)\n            i++;\n          if (i==n1)\n            pair.n1=n1;\n        }\n        else {\n          while (pair.n1<n1 && core_1[pair.n1]!=NULL_NODE ){\n            pair.n1++;\n            pair.n2=0;\n          }\n        }\n        \n        /* VF2 Plus iterator available? */\n        if (pair.hasiter) {\n          while (pair.nbrbeg < pair.nbrend && core_2[*pair.nbrbeg]!=NULL_NODE) {\n            ++pair.nbrbeg;\n          }\n          \n          if (pair.nbrbeg < pair.nbrend) {\n              pair.n2 = *pair.nbrbeg;\n              ++pair.nbrbeg;\n          }\n          else {\n              pair.n2 = n2;\n          }\n        }\n        else if (t1_len>core_len && t2_len>core_len) {\n          while (pair.n2<n2 &&\n                 (core_2[pair.n2]!=NULL_NODE || term_2[pair.n2]==0) ) {\n            pair.n2++;\n          }\n        }\n        else {\n          while (pair.n2<n2 && core_2[pair.n2]!=NULL_NODE ){\n            pair.n2++;\n          }\n        }\n        return pair.n1 < n1 && pair.n2 < n2;\n      };\n      bool IsFeasiblePair(node_id node1, node_id node2){\n        assert(node1 < n1);\n        assert(node2 < n2);\n        assert(core_1[node1] == NULL_NODE);\n        assert(core_2[node2] == NULL_NODE);\n\n        //std::cerr<<\"  ifp:\"<<node1<<\"-\"<<node2<<\" \"<<vs_compared->size()<<std::endl;\n        // int &isCompat=vs_compared[node1*n2+node2];\n        // if(isCompat==0){\n        //   isCompat=vc(node1,node2)?1:-1;\n        // }\n        // if( isCompat<0 ){\n        //   //std::cerr<<\"  short1\"<<std::endl;\n        //   return false;\n        // }\n        \n        // O(1) check for adjacency list\n        if (boost::out_degree(node1,*g1)>boost::out_degree(node2,*g2))\n          return false;\n        if(!vc(node1,node2)) return false;\n\n        unsigned int other1, other2;\n#ifdef RDK_VF2_PRUNING\n        unsigned int term1 = 0, term2 = 0;\n        unsigned int new1 = 0, new2 = 0;\n#endif\n\n        // Check the out edges of node1\n        typename Graph::out_edge_iterator bNbrs,eNbrs;\n        boost::tie(bNbrs,eNbrs) = boost::out_edges(node1,*g1);\n        while(bNbrs!=eNbrs){\n          other1=getOtherIdx(*g1,*bNbrs,node1);\n          if (core_1[other1] != NULL_NODE) {\n            other2 = core_1[other1];\n            typename Graph::edge_descriptor oEdge;\n            bool found;\n            boost::tie(oEdge,found) = boost::edge(node2,other2,*g2);\n            if(!found || !ec(*bNbrs,oEdge) ){\n              //std::cerr<<\"  short2\"<<std::endl;\n              return false;\n            }\n          }\n#ifdef RDK_VF2_PRUNING\n          else {\n            if (term_1[other1]) ++term1;\n            if (!term_1[other1]) ++new1;\n          }\n#endif\n          ++bNbrs;\n        }\n\n#ifdef RDK_VF2_PRUNING\n        // Check the out edges of node2\n        boost::tie(bNbrs,eNbrs) = boost::out_edges(node2,*g2);\n        while(bNbrs!=eNbrs){\n          other2=getOtherIdx(*g2,*bNbrs,node2);\n          if (core_2[other2] != NULL_NODE) {\n            // do nothing\n          } else {\n            if (term_2[other2]) ++term2;\n            if (!term_2[other2]) ++new2;\n          }\n          ++bNbrs;\n        }\n        //std::cerr<<(termin1 <= termin2 && termout1 <= termout2 && (termin1+termout1+new1)<=(termin2+termout2+new2))<<std::endl;\n\n        // n.b. term1+new1 == boost::out_degree(node1) and\n        //      term2+new2 == boost::out_degree(node2)\n        return term1 <= term2 && (term1+new1)<=(term2+new2);\n#else\n        return true;\n#endif\n      };\n      void AddPair(node_id node1, node_id node2){\n        assert(node1 < n1);\n        assert(node2 < n2);\n        assert(core_len < n1);\n        assert(core_len < n2);\n\n        ++core_len;\n        if (!term_1[node1]) {\n          term_1[node1] = core_len;\n          ++t1_len;\n        }\n\n        if (!term_2[node2]) {\n          term_2[node2] = core_len;\n          ++t2_len;\n        }\n        \n        core_1[node1] = node2;\n        core_2[node2] = node1;\n\n        typename Graph::out_edge_iterator bNbrs,eNbrs;\n        // FIX: this is explicitly ignoring directionality\n        boost::tie(bNbrs,eNbrs) = boost::out_edges(node1,*g1);\n        while(bNbrs!=eNbrs){\n          unsigned int other = getOtherIdx(*g1,*bNbrs,node1);\n          if (!term_1[other]) {\n            term_1[other] = core_len;\n            ++t1_len;\n          }\n          ++bNbrs;\n        }\n\n        // FIX: this is explicitly ignoring directionality\n        boost::tie(bNbrs,eNbrs) = boost::out_edges(node2,*g2);\n        while(bNbrs!=eNbrs){\n          unsigned int other = getOtherIdx(*g2,*bNbrs,node2);\n          if (!term_2[other]) {\n            term_2[other] = core_len;\n            ++t2_len;\n          }\n          ++bNbrs;\n        }\n      };\n      void GetCoreSet(node_id c1[], node_id c2[]){\n        unsigned int i, j;\n        for (i = 0, j = 0; i < n1; ++i){\n          if (core_1[i] != NULL_NODE) {\n            c1[j] = i;\n            c2[j] = core_1[i];\n            ++j;\n          }\n        }\n    \n      };\n      VF2SubState *Clone(){\n        return new VF2SubState(*this);\n      };\n      void BackTrack(node_id node1, node_id node2){\n        if (term_1[node1] == core_len) {\n          term_1[node1] = 0;\n          --t1_len;\n        }\n\n        typename Graph::out_edge_iterator bNbrs,eNbrs;\n        boost::tie(bNbrs,eNbrs) = boost::out_edges(node1,*g1);\n        while(bNbrs!=eNbrs){\n          unsigned int other = getOtherIdx(*g1,*bNbrs,node1);\n          if (term_1[other] == core_len) {\n            term_1[other] = 0;\n            --t1_len;\n          }\n          ++bNbrs;\n        }\n\n        if (term_2[node2] == core_len) {\n          term_2[node2] = 0;\n          --t2_len;\n        }\n\n        boost::tie(bNbrs,eNbrs) = boost::out_edges(node2,*g2);\n        while(bNbrs!=eNbrs){\n          unsigned int other = getOtherIdx(*g2,*bNbrs,node2);\n          if (term_2[other] == core_len) {\n            term_2[other] = 0;\n            --t2_len;\n          }\n          ++bNbrs;\n        }\n\n        core_1[node1] = NULL_NODE;\n        core_2[node2] = NULL_NODE;\n        --core_len;\n      };\n      bool Match(node_id c1[], node_id c2[])\n      {\n        if (IsGoal()) {\n          GetCoreSet(c1, c2);\n          if(MatchChecks(c1,c2))\n            return true;\n        }\n        \n        if (IsDead())\n          return false;\n        \n        Pair<Graph> pair;\n        while (NextPair(pair)) {\n          if (IsFeasiblePair(pair.n1, pair.n2)){\n            AddPair(pair.n1, pair.n2);\n            if (Match(c1, c2)) // recurse\n              return true;\n            BackTrack(pair.n1, pair.n2);\n          }\n        }\n        return false;\n      }\n      \n      template <class DoubleBackInsertionSequence>\n      bool MatchAll(node_id c1[], node_id c2[],\n                    DoubleBackInsertionSequence &res, unsigned int lim=0)\n      {\n        if (IsGoal()) {\n          GetCoreSet(c1, c2);\n          if(MatchChecks(c1,c2)) {\n            typename DoubleBackInsertionSequence::value_type newSeq;\n            for(unsigned int i=0;i<core_len;++i){\n              newSeq.push_back(std::pair<int,int>(c1[i],c2[i]));\n            }\n            res.push_back(newSeq);\n            return lim && res.size() >= lim;\n          }\n        }\n        \n        if (IsDead())\n          return false;\n        \n        Pair<Graph> pair;\n        while (NextPair(pair)) {\n          if (IsFeasiblePair(pair.n1, pair.n2)){\n            AddPair(pair.n1, pair.n2);\n            if (MatchAll(c1, c2, res, lim)) // recurse\n              return true;\n            BackTrack(pair.n1, pair.n2);\n          }\n        }\n        return false;\n      }\n    };\n\n    /*-------------------------------------------------------------\n     * static bool match(pn, c1, c2, s)\n     * Finds a matching between two graphs, if it exists, starting\n     * from state s.\n     * Returns true a match has been found.\n     * *pn is assigned the numbero of matched nodes, and\n     * c1 and c2 will contain the ids of the corresponding nodes \n     * in the two graphs.\n     ------------------------------------------------------------*/\n    template <class SubState>\n    bool match(int *pn, node_id c1[], node_id c2[], SubState &s)\n    {\n      if (s.Match(c1, c2)) {\n        // not needed, pn = num query atoms (n1)...\n        *pn=s.CoreLen();\n        return true;\n      }\n      return false;\n    }\n\n    /*-------------------------------------------------------------\n     * static bool match(c1, c2, vis, usr_data, pcount)\n     * Visits all the matchings between two graphs,  starting\n     * from state s.\n     * Returns true if the caller must stop the visit.\n     * Stops when max_results is reached, set max_results to 0 to\n     * keep going until there are no more matches\n     *\n     ------------------------------------------------------------*/\n    template <class SubState,class DoubleBackInsertionSequence>\n    bool match(node_id c1[], node_id c2[], SubState &s, DoubleBackInsertionSequence &res,\n               unsigned int max_results) {\n      s.MatchAll(c1, c2, res, max_results);\n      return !res.empty();\n    }\n  }; //end of namespace detail\n\n  template <  class Graph\n              , class VertexLabeling    // binary predicate\n              , class EdgeLabeling      // binary predicate\n              , class MatchChecking      // binary predicate\n              , class BackInsertionSequence   // contains std::pair<vertex_descriptor,vertex_descriptor>\n              >\n  bool vf2(const Graph &g1,const Graph &g2,\n           VertexLabeling& vertex_labeling,\n           EdgeLabeling& edge_labeling,\n           MatchChecking& match_checking,\n           BackInsertionSequence& F){\n    detail::VF2SubState<const Graph,VertexLabeling,EdgeLabeling,MatchChecking> s0(&g1,&g2,vertex_labeling,\n                                                                                  edge_labeling,match_checking,false);\n    detail::node_id *ni1 = new detail::node_id[num_vertices(g1)];\n    detail::node_id *ni2 = new detail::node_id[num_vertices(g2)];\n    int n=0;\n    \n    F.clear();\n    F.resize(0);\n    if(match(&n,ni1,ni2,s0)){\n      for(unsigned int i=0;i<num_vertices(g1);i++){\n        F.push_back(std::pair<int,int>(ni1[i],ni2[i]));\n      }\n    }\n    delete [] ni1;\n    delete [] ni2;\n    \n    return !F.empty();\n  };\n  template <  class Graph\n              , class VertexLabeling    // binary predicate\n              , class EdgeLabeling      // binary predicate\n              , class MatchChecking      // binary predicate\n              , class DoubleBackInsertionSequence   // contains a back insertion sequence\n              >\n  bool vf2_all(const Graph& g1, const Graph& g2,\n               VertexLabeling& vertex_labeling,\n               EdgeLabeling& edge_labeling,\n               MatchChecking& match_checking,\n               DoubleBackInsertionSequence& F,\n               unsigned int max_results=1000) {\n    detail::VF2SubState<const Graph,VertexLabeling,EdgeLabeling,MatchChecking> s0(&g1,&g2,vertex_labeling,\n                                                                                  edge_labeling,match_checking,false);\n    detail::node_id *ni1 = new detail::node_id[num_vertices(g1)];\n    detail::node_id *ni2 = new detail::node_id[num_vertices(g2)];\n    \n    F.clear();\n    F.resize(0);\n\n    match(ni1,ni2,s0,F,max_results);\n\n    delete [] ni1;\n    delete [] ni2;\n    \n    return !F.empty();\n  };\n} // end of namespace boost\n#endif\n\n#undef RDK_VF2_PRUNING\n#undef RDK_ADJ_ITER\n", "meta": {"hexsha": "16b91bb3dfd57586efcfa82b5ad272d555d6e92a", "size": 20176, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Code/GraphMol/Substruct/vf2.hpp", "max_stars_repo_name": "hryknkgw/rdkit", "max_stars_repo_head_hexsha": "f01f819a1f800aeef3fa4999e247e9d665d99761", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/GraphMol/Substruct/vf2.hpp", "max_issues_repo_name": "hryknkgw/rdkit", "max_issues_repo_head_hexsha": "f01f819a1f800aeef3fa4999e247e9d665d99761", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/Substruct/vf2.hpp", "max_forks_repo_name": "hryknkgw/rdkit", "max_forks_repo_head_hexsha": "f01f819a1f800aeef3fa4999e247e9d665d99761", "max_forks_repo_licenses": ["BSD-3-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.9923195084, "max_line_length": 129, "alphanum_fraction": 0.5157613006, "num_tokens": 5490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543457, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.25293219258618216}}
{"text": "// ----------------------------------------------------------------------------\n// -                        Open3D: www.open3d.org                            -\n// ----------------------------------------------------------------------------\n// The MIT License (MIT)\n//\n// Copyright (c) 2019 www.open3d.org\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\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n// ----------------------------------------------------------------------------\n\n#include \"open3d/geometry/TriangleMesh.h\"\n\n#include <Eigen/Dense>\n#include <queue>\n#include <tuple>\n\n#include \"open3d/utility/Console.h\"\n\nnamespace open3d {\nnamespace geometry {\n\nstd::shared_ptr<TriangleMesh> TriangleMesh::SubdivideMidpoint(\n        int number_of_iterations) const {\n    if (HasTriangleUvs()) {\n        utility::LogWarning(\n                \"[SubdivideMidpoint] This mesh contains triangle uvs that are \"\n                \"not handled in this function\");\n    }\n    auto mesh = std::make_shared<TriangleMesh>();\n    mesh->vertices_ = vertices_;\n    mesh->vertex_colors_ = vertex_colors_;\n    mesh->vertex_normals_ = vertex_normals_;\n    mesh->triangles_ = triangles_;\n\n    bool has_vert_normal = HasVertexNormals();\n    bool has_vert_color = HasVertexColors();\n\n    // Compute and return midpoint.\n    // Also adds edge - new vertex refrence to new_verts map.\n    auto SubdivideEdge =\n            [&](std::unordered_map<Eigen::Vector2i, int,\n                                   utility::hash_eigen::hash<Eigen::Vector2i>>&\n                        new_verts,\n                int vidx0, int vidx1) {\n                int min = std::min(vidx0, vidx1);\n                int max = std::max(vidx0, vidx1);\n                Eigen::Vector2i edge(min, max);\n                if (new_verts.count(edge) == 0) {\n                    mesh->vertices_.push_back(0.5 * (mesh->vertices_[min] +\n                                                     mesh->vertices_[max]));\n                    if (has_vert_normal) {\n                        mesh->vertex_normals_.push_back(\n                                0.5 * (mesh->vertex_normals_[min] +\n                                       mesh->vertex_normals_[max]));\n                    }\n                    if (has_vert_color) {\n                        mesh->vertex_colors_.push_back(\n                                0.5 * (mesh->vertex_colors_[min] +\n                                       mesh->vertex_colors_[max]));\n                    }\n                    int vidx01 = int(mesh->vertices_.size()) - 1;\n                    new_verts[edge] = vidx01;\n                    return vidx01;\n                } else {\n                    return new_verts[edge];\n                }\n            };\n    for (int iter = 0; iter < number_of_iterations; ++iter) {\n        std::unordered_map<Eigen::Vector2i, int,\n                           utility::hash_eigen::hash<Eigen::Vector2i>>\n                new_verts;\n        std::vector<Eigen::Vector3i> new_triangles(4 * mesh->triangles_.size());\n        for (size_t tidx = 0; tidx < mesh->triangles_.size(); ++tidx) {\n            const auto& triangle = mesh->triangles_[tidx];\n            int vidx0 = triangle(0);\n            int vidx1 = triangle(1);\n            int vidx2 = triangle(2);\n            int vidx01 = SubdivideEdge(new_verts, vidx0, vidx1);\n            int vidx12 = SubdivideEdge(new_verts, vidx1, vidx2);\n            int vidx20 = SubdivideEdge(new_verts, vidx2, vidx0);\n            new_triangles[tidx * 4 + 0] =\n                    Eigen::Vector3i(vidx0, vidx01, vidx20);\n            new_triangles[tidx * 4 + 1] =\n                    Eigen::Vector3i(vidx01, vidx1, vidx12);\n            new_triangles[tidx * 4 + 2] =\n                    Eigen::Vector3i(vidx12, vidx2, vidx20);\n            new_triangles[tidx * 4 + 3] =\n                    Eigen::Vector3i(vidx01, vidx12, vidx20);\n        }\n        mesh->triangles_ = new_triangles;\n    }\n\n    if (HasTriangleNormals()) {\n        mesh->ComputeTriangleNormals();\n    }\n\n    return mesh;\n}\n\nstd::shared_ptr<TriangleMesh> TriangleMesh::SubdivideLoop(\n        int number_of_iterations) const {\n    if (HasTriangleUvs()) {\n        utility::LogWarning(\n                \"[SubdivideLoop] This mesh contains triangle uvs that are not \"\n                \"handled in this function\");\n    }\n    typedef std::unordered_map<Eigen::Vector2i, int,\n                               utility::hash_eigen::hash<Eigen::Vector2i>>\n            EdgeNewVertMap;\n    typedef std::unordered_map<Eigen::Vector2i, std::unordered_set<int>,\n                               utility::hash_eigen::hash<Eigen::Vector2i>>\n            EdgeTrianglesMap;\n    typedef std::vector<std::unordered_set<int>> VertexNeighbours;\n\n    bool has_vert_normal = HasVertexNormals();\n    bool has_vert_color = HasVertexColors();\n\n    auto UpdateVertex = [&](int vidx,\n                            const std::shared_ptr<TriangleMesh>& old_mesh,\n                            std::shared_ptr<TriangleMesh>& new_mesh,\n                            const std::unordered_set<int>& nbs,\n                            const EdgeTrianglesMap& edge_to_triangles) {\n        // check if boundary edge and get nb vertices in that case\n        std::unordered_set<int> boundary_nbs;\n        for (int nb : nbs) {\n            const Eigen::Vector2i edge = GetOrderedEdge(vidx, nb);\n            if (edge_to_triangles.at(edge).size() == 1) {\n                boundary_nbs.insert(nb);\n            }\n        }\n\n        // in manifold meshes this should not happen\n        if (boundary_nbs.size() > 2) {\n            utility::LogWarning(\n                    \"[SubdivideLoop] boundary edge with > 2 neighbours, maybe \"\n                    \"mesh is not manifold.\");\n        }\n\n        double beta, alpha;\n        if (boundary_nbs.size() >= 2) {\n            beta = 1. / 8.;\n            alpha = 1. - boundary_nbs.size() * beta;\n        } else if (nbs.size() == 3) {\n            beta = 3. / 16.;\n            alpha = 1. - nbs.size() * beta;\n        } else {\n            beta = 3. / (8. * nbs.size());\n            alpha = 1. - nbs.size() * beta;\n        }\n\n        new_mesh->vertices_[vidx] = alpha * old_mesh->vertices_[vidx];\n        if (has_vert_normal) {\n            new_mesh->vertex_normals_[vidx] =\n                    alpha * old_mesh->vertex_normals_[vidx];\n        }\n        if (has_vert_color) {\n            new_mesh->vertex_colors_[vidx] =\n                    alpha * old_mesh->vertex_colors_[vidx];\n        }\n\n        auto Update = [&](int nb) {\n            new_mesh->vertices_[vidx] += beta * old_mesh->vertices_[nb];\n            if (has_vert_normal) {\n                new_mesh->vertex_normals_[vidx] +=\n                        beta * old_mesh->vertex_normals_[nb];\n            }\n            if (has_vert_color) {\n                new_mesh->vertex_colors_[vidx] +=\n                        beta * old_mesh->vertex_colors_[nb];\n            }\n        };\n        if (boundary_nbs.size() >= 2) {\n            for (int nb : boundary_nbs) {\n                Update(nb);\n            }\n        } else {\n            for (int nb : nbs) {\n                Update(nb);\n            }\n        }\n    };\n\n    auto SubdivideEdge = [&](int vidx0, int vidx1,\n                             const std::shared_ptr<TriangleMesh>& old_mesh,\n                             std::shared_ptr<TriangleMesh>& new_mesh,\n                             EdgeNewVertMap& new_verts,\n                             const EdgeTrianglesMap& edge_to_triangles) {\n        Eigen::Vector2i edge = GetOrderedEdge(vidx0, vidx1);\n        if (new_verts.count(edge) == 0) {\n            Eigen::Vector3d new_vert =\n                    old_mesh->vertices_[vidx0] + old_mesh->vertices_[vidx1];\n            Eigen::Vector3d new_normal;\n            if (has_vert_normal) {\n                new_normal = old_mesh->vertex_normals_[vidx0] +\n                             old_mesh->vertex_normals_[vidx1];\n            }\n            Eigen::Vector3d new_color;\n            if (has_vert_color) {\n                new_color = old_mesh->vertex_colors_[vidx0] +\n                            old_mesh->vertex_colors_[vidx1];\n            }\n\n            const auto& edge_triangles = edge_to_triangles.at(edge);\n            if (edge_triangles.size() < 2) {\n                new_vert *= 0.5;\n                if (has_vert_normal) {\n                    new_normal *= 0.5;\n                }\n                if (has_vert_color) {\n                    new_color *= 0.5;\n                }\n            } else {\n                new_vert *= 3. / 8.;\n                if (has_vert_normal) {\n                    new_normal *= 3. / 8.;\n                }\n                if (has_vert_color) {\n                    new_color *= 3. / 8.;\n                }\n                size_t n_adjacent_trias = edge_triangles.size();\n                double scale = 1. / (4. * n_adjacent_trias);\n                for (int tidx : edge_triangles) {\n                    const auto& tria = old_mesh->triangles_[tidx];\n                    int vidx2 =\n                            (tria(0) != vidx0 && tria(0) != vidx1)\n                                    ? tria(0)\n                                    : ((tria(1) != vidx0 && tria(1) != vidx1)\n                                               ? tria(1)\n                                               : tria(2));\n                    new_vert += scale * old_mesh->vertices_[vidx2];\n                    if (has_vert_normal) {\n                        new_normal += scale * old_mesh->vertex_normals_[vidx2];\n                    }\n                    if (has_vert_color) {\n                        new_color += scale * old_mesh->vertex_colors_[vidx2];\n                    }\n                }\n            }\n\n            int vidx01 = int(old_mesh->vertices_.size() + new_verts.size());\n\n            new_mesh->vertices_[vidx01] = new_vert;\n            if (has_vert_normal) {\n                new_mesh->vertex_normals_[vidx01] = new_normal;\n            }\n            if (has_vert_color) {\n                new_mesh->vertex_colors_[vidx01] = new_color;\n            }\n\n            new_verts[edge] = vidx01;\n            return vidx01;\n        } else {\n            int vidx01 = new_verts[edge];\n            return vidx01;\n        }\n    };\n\n    auto InsertTriangle = [&](int tidx, int vidx0, int vidx1, int vidx2,\n                              std::shared_ptr<TriangleMesh>& mesh,\n                              EdgeTrianglesMap& edge_to_triangles,\n                              VertexNeighbours& vertex_neighbours) {\n        mesh->triangles_[tidx] = Eigen::Vector3i(vidx0, vidx1, vidx2);\n        edge_to_triangles[GetOrderedEdge(vidx0, vidx1)].insert(tidx);\n        edge_to_triangles[GetOrderedEdge(vidx1, vidx2)].insert(tidx);\n        edge_to_triangles[GetOrderedEdge(vidx2, vidx0)].insert(tidx);\n        vertex_neighbours[vidx0].insert(vidx1);\n        vertex_neighbours[vidx0].insert(vidx2);\n        vertex_neighbours[vidx1].insert(vidx0);\n        vertex_neighbours[vidx1].insert(vidx2);\n        vertex_neighbours[vidx2].insert(vidx0);\n        vertex_neighbours[vidx2].insert(vidx1);\n    };\n\n    EdgeTrianglesMap edge_to_triangles;\n    VertexNeighbours vertex_neighbours(vertices_.size());\n    for (size_t tidx = 0; tidx < triangles_.size(); ++tidx) {\n        const auto& tria = triangles_[tidx];\n        Eigen::Vector2i e0 = GetOrderedEdge(tria(0), tria(1));\n        edge_to_triangles[e0].insert(int(tidx));\n        Eigen::Vector2i e1 = GetOrderedEdge(tria(1), tria(2));\n        edge_to_triangles[e1].insert(int(tidx));\n        Eigen::Vector2i e2 = GetOrderedEdge(tria(2), tria(0));\n        edge_to_triangles[e2].insert(int(tidx));\n\n        if (edge_to_triangles[e0].size() > 2 ||\n            edge_to_triangles[e1].size() > 2 ||\n            edge_to_triangles[e2].size() > 2) {\n            utility::LogWarning(\"[SubdivideLoop] non-manifold edge.\");\n        }\n\n        vertex_neighbours[tria(0)].insert(tria(1));\n        vertex_neighbours[tria(0)].insert(tria(2));\n        vertex_neighbours[tria(1)].insert(tria(0));\n        vertex_neighbours[tria(1)].insert(tria(2));\n        vertex_neighbours[tria(2)].insert(tria(0));\n        vertex_neighbours[tria(2)].insert(tria(1));\n    }\n\n    auto old_mesh = std::make_shared<TriangleMesh>();\n    old_mesh->vertices_ = vertices_;\n    old_mesh->vertex_colors_ = vertex_colors_;\n    old_mesh->vertex_normals_ = vertex_normals_;\n    old_mesh->triangles_ = triangles_;\n\n    for (int iter = 0; iter < number_of_iterations; ++iter) {\n        size_t n_new_vertices =\n                old_mesh->vertices_.size() + edge_to_triangles.size();\n        size_t n_new_triangles = 4 * old_mesh->triangles_.size();\n        auto new_mesh = std::make_shared<TriangleMesh>();\n        new_mesh->vertices_.resize(n_new_vertices);\n        if (has_vert_normal) {\n            new_mesh->vertex_normals_.resize(n_new_vertices);\n        }\n        if (has_vert_color) {\n            new_mesh->vertex_colors_.resize(n_new_vertices);\n        }\n        new_mesh->triangles_.resize(n_new_triangles);\n\n        EdgeNewVertMap new_verts;\n        EdgeTrianglesMap new_edge_to_triangles;\n        VertexNeighbours new_vertex_neighbours(n_new_vertices);\n\n        for (size_t vidx = 0; vidx < old_mesh->vertices_.size(); ++vidx) {\n            UpdateVertex(int(vidx), old_mesh, new_mesh, vertex_neighbours[vidx],\n                         edge_to_triangles);\n        }\n\n        for (size_t tidx = 0; tidx < old_mesh->triangles_.size(); ++tidx) {\n            const auto& triangle = old_mesh->triangles_[tidx];\n            int vidx0 = triangle(0);\n            int vidx1 = triangle(1);\n            int vidx2 = triangle(2);\n\n            int vidx01 = SubdivideEdge(vidx0, vidx1, old_mesh, new_mesh,\n                                       new_verts, edge_to_triangles);\n            int vidx12 = SubdivideEdge(vidx1, vidx2, old_mesh, new_mesh,\n                                       new_verts, edge_to_triangles);\n            int vidx20 = SubdivideEdge(vidx2, vidx0, old_mesh, new_mesh,\n                                       new_verts, edge_to_triangles);\n\n            InsertTriangle(int(tidx) * 4 + 0, vidx0, vidx01, vidx20, new_mesh,\n                           new_edge_to_triangles, new_vertex_neighbours);\n            InsertTriangle(int(tidx) * 4 + 1, vidx01, vidx1, vidx12, new_mesh,\n                           new_edge_to_triangles, new_vertex_neighbours);\n            InsertTriangle(int(tidx) * 4 + 2, vidx12, vidx2, vidx20, new_mesh,\n                           new_edge_to_triangles, new_vertex_neighbours);\n            InsertTriangle(int(tidx) * 4 + 3, vidx01, vidx12, vidx20, new_mesh,\n                           new_edge_to_triangles, new_vertex_neighbours);\n        }\n\n        old_mesh = std::move(new_mesh);\n        edge_to_triangles = std::move(new_edge_to_triangles);\n        vertex_neighbours = std::move(new_vertex_neighbours);\n    }\n\n    if (HasTriangleNormals()) {\n        old_mesh->ComputeTriangleNormals();\n    }\n\n    return old_mesh;\n}\n\n}  // namespace geometry\n}  // namespace open3d\n", "meta": {"hexsha": "447a93b5b7c9ab0549a9e6992ccdea8424a95bbe", "size": 15909, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/open3d/geometry/TriangleMeshSubdivide.cpp", "max_stars_repo_name": "appliedinnovation/Open3D", "max_stars_repo_head_hexsha": "2c33a864fe1241f54a96f720b0f46ebd780c3d3d", "max_stars_repo_licenses": ["MIT"], "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/open3d/geometry/TriangleMeshSubdivide.cpp", "max_issues_repo_name": "appliedinnovation/Open3D", "max_issues_repo_head_hexsha": "2c33a864fe1241f54a96f720b0f46ebd780c3d3d", "max_issues_repo_licenses": ["MIT"], "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/open3d/geometry/TriangleMeshSubdivide.cpp", "max_forks_repo_name": "appliedinnovation/Open3D", "max_forks_repo_head_hexsha": "2c33a864fe1241f54a96f720b0f46ebd780c3d3d", "max_forks_repo_licenses": ["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.7559055118, "max_line_length": 80, "alphanum_fraction": 0.5331573323, "num_tokens": 3751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4726834766204329, "lm_q1q2_score": 0.2529321855773573}}
{"text": "#include <scitbx/array_family/boost_python/flex_fwd.h>\n\n#if defined(SCITBX_LBFGS_HAVE_LBFGS_FEM)\n#include <scitbx/lbfgs_fem.hpp>\n#endif\n#include <algorithm>\n#include <stdexcept>\n#include <cstdio>\n#include <cmath>\n#include <scitbx/error.h>\n#include <scitbx/lbfgs.h>\n#include <scitbx/lbfgs/drop_convergence_test.h>\n#include <scitbx/lbfgs/raw.h>\n#include <scitbx/lbfgs/raw_reference.h>\n#include <scitbx/array_family/flex_types.h>\n#include <scitbx/array_family/boost_python/utils.h>\n#include <boost/python/module.hpp>\n#include <boost/python/def.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/args.hpp>\n\nnamespace scitbx { namespace lbfgs { namespace ext {\n  int\n  fortran(\n    int n,\n    int m,\n    af::ref<double> const& x,\n    double f,\n    af::const_ref<double> const& g,\n    int diagco,\n    af::ref<double> const& diag,\n    af::tiny<int, 2> const& iprint,\n    double eps,\n    double xtol,\n    af::ref<double> const& w,\n    int iflag)\n  {\n    SCITBX_ASSERT(n > 0);\n    SCITBX_ASSERT(m > 0);\n    std::size_t n_ = static_cast<std::size_t>(n);\n    std::size_t m_ = static_cast<std::size_t>(m);\n    SCITBX_ASSERT(x.size() == n_);\n    SCITBX_ASSERT(g.size() == n_);\n    SCITBX_ASSERT(diagco == 0 || diagco == 1);\n    SCITBX_ASSERT(diag.size() == n_);\n    SCITBX_ASSERT(w.size() == n_*(2*m_+1)+2*m_);\n#if defined(SCITBX_LBFGS_HAVE_LBFGS_FEM)\n    static lbfgs_fem::common cmn(0, 0);\n    lbfgs_fem::blockdata_lb2(cmn);\n    lbfgs_fem::lbfgs(\n      cmn,\n      n,\n      m,\n      x[0],\n      f,\n      g[0],\n      diagco,\n      diag[0],\n      iprint[0],\n      eps,\n      xtol,\n      w[0],\n      iflag);\n#else\n    throw std::runtime_error(\"lbfgs_fem is not available.\");\n#endif\n    return iflag;\n  }\n\n  int\n  raw_reference(\n    int n,\n    int m,\n    af::ref<double> const& x,\n    double f,\n    af::const_ref<double> const& g,\n    int diagco,\n    af::ref<double> const& diag,\n    af::tiny<int, 2> const& iprint,\n    double eps,\n    double xtol,\n    af::ref<double> const& w,\n    int iflag)\n  {\n    SCITBX_ASSERT(n > 0);\n    SCITBX_ASSERT(m > 0);\n    std::size_t n_ = static_cast<std::size_t>(n);\n    std::size_t m_ = static_cast<std::size_t>(m);\n    SCITBX_ASSERT(x.size() == n_);\n    SCITBX_ASSERT(g.size() == n_);\n    SCITBX_ASSERT(diagco == 0 || diagco == 1);\n    SCITBX_ASSERT(diag.size() == n_);\n    SCITBX_ASSERT(w.size() == n_*(2*m_+1)+2*m_);\n    using scitbx::lbfgs::raw_reference::const_ref1; // fully-qualified\n    using scitbx::lbfgs::raw_reference::ref1;       // to work around\n    scitbx::lbfgs::raw_reference::lbfgs(            // gcc 3.2 bug\n      n,\n      m,\n      ref1<double>(x.begin(), n),\n      f,\n      const_ref1<double>(g.begin(), n),\n      diagco,\n      ref1<double>(diag.begin(), n),\n      const_ref1<int>(iprint.begin(), 2),\n      eps,\n      xtol,\n      ref1<double>(w.begin(), static_cast<int>(w.size())),\n      iflag);\n    return iflag;\n  }\n\nstruct raw_lbfgs : boost::noncopyable {\n\n  scitbx::lbfgs::raw::lbfgs lbfgs_obj;\n\n  int\n  operator()(\n    int n,\n    int m,\n    af::ref<double> const& x,\n    double f,\n    af::const_ref<double> const& g,\n    int diagco,\n    af::ref<double> const& diag,\n    af::tiny<int, 2> const& iprint,\n    double eps,\n    double xtol,\n    af::ref<double> const& w,\n    int iflag)\n  {\n    SCITBX_ASSERT(n > 0);\n    SCITBX_ASSERT(m > 0);\n    std::size_t n_ = static_cast<std::size_t>(n);\n    std::size_t m_ = static_cast<std::size_t>(m);\n    SCITBX_ASSERT(x.size() == n_);\n    SCITBX_ASSERT(g.size() == n_);\n    SCITBX_ASSERT(diagco >= 0);\n    SCITBX_ASSERT(diagco <= 3);\n    SCITBX_ASSERT(diag.size() == n_);\n    SCITBX_ASSERT(w.size() == n_*(2*m_+1)+2*m_);\n    using scitbx::lbfgs::raw::const_ref1; // fully-qualified\n    using scitbx::lbfgs::raw::ref1;       // to work around\n    lbfgs_obj(                            // gcc 3.2 bug\n      n,\n      m,\n      ref1<double>(x.begin(), n),\n      f,\n      const_ref1<double>(g.begin(), n),\n      diagco,\n      ref1<double>(diag.begin(), n),\n      const_ref1<int>(iprint.begin(), 2),\n      eps,\n      xtol,\n      ref1<double>(w.begin(), static_cast<int>(w.size())),\n      iflag);\n    return iflag;\n  }\n\n  int\n  nfun() const { return lbfgs_obj.nfun; }\n\n  int\n  iter() const { return lbfgs_obj.iter; }\n\n  double\n  stp() const { return lbfgs_obj.stp; }\n\n  void\n  set_stp(double value) { lbfgs_obj.stp = value; }\n\n  af::shared<double>\n  current_search_direction() const\n  {\n    return af::shared<double>(\n      lbfgs_obj.current_search_direction.begin(),\n      lbfgs_obj.current_search_direction.end());\n  }\n};\n\nstruct raw_lbfgs_wrappers\n{\n  typedef raw_lbfgs w_t;\n\n  static\n  void\n  wrap()\n  {\n    using namespace boost::python;\n    class_<w_t, boost::noncopyable>(\"raw_lbfgs\", no_init)\n      .def(init<>())\n      .def(\"__call__\", &w_t::operator(), (\n        arg(\"n\"),\n        arg(\"m\"),\n        arg(\"x\"),\n        arg(\"f\"),\n        arg(\"g\"),\n        arg(\"diagco\"),\n        arg(\"diag\"),\n        arg(\"iprint\"),\n        arg(\"eps\"),\n        arg(\"xtol\"),\n        arg(\"w\"),\n        arg(\"iflag\")))\n      .def(\"nfun\", &w_t::nfun)\n      .def(\"iter\", &w_t::iter)\n      .def(\"stp\", &w_t::stp)\n      .def(\"set_stp\", &w_t::set_stp, (arg(\"value\")))\n      .def(\"current_search_direction\", &w_t::current_search_direction)\n    ;\n  }\n};\n\n  struct minimizer_wrappers\n  {\n    typedef minimizer<double> w_t;\n\n    static bool\n    run_4(\n      w_t& minimizer,\n      af::flex_double& x,\n      double f,\n      af::flex_double const& g,\n      af::flex_double const& diag)\n    {\n      using namespace scitbx::af::boost_python;\n      SCITBX_ASSERT(flex_as_base_array(x).size() == minimizer.n());\n      SCITBX_ASSERT(flex_as_base_array(g).size() == minimizer.n());\n      SCITBX_ASSERT(flex_as_base_array(diag).size() == minimizer.n());\n      return minimizer.run(x.begin(), f, g.begin(), diag.begin());\n    }\n\n    static bool\n    run_3(\n      w_t& minimizer,\n      af::flex_double& x,\n      double f,\n      af::flex_double const& g)\n    {\n      using namespace scitbx::af::boost_python;\n      SCITBX_ASSERT(flex_as_base_array(x).size() == minimizer.n());\n      SCITBX_ASSERT(flex_as_base_array(g).size() == minimizer.n());\n      return minimizer.run(x.begin(), f, g.begin());\n    }\n\n    //---> Insertion starts\n    static bool\n    run_6(\n      w_t& minimizer,\n      af::flex_double& x,\n      double f,\n      af::flex_double const& g,\n      af::flex_double const& diag,\n      bool gradient_only,\n      bool line_search)\n    {\n      using namespace scitbx::af::boost_python;\n      SCITBX_ASSERT(flex_as_base_array(x).size() == minimizer.n());\n      SCITBX_ASSERT(flex_as_base_array(g).size() == minimizer.n());\n      SCITBX_ASSERT(flex_as_base_array(diag).size() == minimizer.n());\n      return minimizer.run(x.begin(), f, g.begin(), diag.begin(), gradient_only,line_search);\n    }\n\n    static bool\n    run_5(\n      w_t& minimizer,\n      af::flex_double& x,\n      double f,\n      af::flex_double const& g,\n      bool gradient_only,\n      bool line_search)\n    {\n      using namespace scitbx::af::boost_python;\n      SCITBX_ASSERT(flex_as_base_array(x).size() == minimizer.n());\n      SCITBX_ASSERT(flex_as_base_array(g).size() == minimizer.n());\n      return minimizer.run(x.begin(), f, g.begin(), gradient_only,line_search);\n    }\n    //<--- Insertion ends\n\n    static double\n    euclidean_norm(\n      w_t const& minimizer,\n      af::flex_double const& a)\n    {\n      using namespace scitbx::af::boost_python;\n      SCITBX_ASSERT(flex_as_base_array(a).size() == minimizer.n());\n      return minimizer.euclidean_norm(a.begin());\n    }\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"minimizer\", no_init)\n        .def(init<optional<std::size_t, std::size_t, std::size_t,\n          double, double, double, double> >())\n        //---> Insertion starts\n        .def(\"run\", run_6)\n        .def(\"run\", run_5)\n        //<--- Insertion ends\n        .def(\"run\", run_4)\n        .def(\"run\", run_3)\n        .def(\"n\", &w_t::n)\n        .def(\"m\", &w_t::m)\n        .def(\"maxfev\", &w_t::maxfev)\n        .def(\"gtol\", &w_t::gtol)\n        .def(\"xtol\", &w_t::xtol)\n        .def(\"stpmin\", &w_t::stpmin)\n        .def(\"stpmax\", &w_t::stpmax)\n        .def(\"requests_f_and_g\", &w_t::requests_f_and_g)\n        .def(\"requests_diag\", &w_t::requests_diag)\n        .def(\"iter\", &w_t::iter)\n        .def(\"nfun\", &w_t::nfun)\n        .def(\"euclidean_norm\", euclidean_norm)\n        .def(\"stp\", &w_t::stp)\n      ;\n    }\n  };\n\n  struct traditional_convergence_test_wrappers\n  {\n    typedef traditional_convergence_test<double> w_t;\n\n    static bool\n    call(\n      w_t const& is_converged,\n      af::flex_double const& x,\n      af::flex_double const& g)\n    {\n      using namespace scitbx::af::boost_python;\n      SCITBX_ASSERT(flex_as_base_array(x).size() == is_converged.n());\n      SCITBX_ASSERT(flex_as_base_array(g).size() == is_converged.n());\n      return is_converged(x.begin(), g.begin());\n    }\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"traditional_convergence_test\")\n        .def(init<std::size_t, optional<double> >((\n          arg(\"n\"),\n          arg(\"eps\")=1.e-5)))\n        .def(\"n\", &w_t::n)\n        .def(\"eps\", &w_t::eps)\n        .def(\"__call__\", call)\n      ;\n    }\n  };\n\n  struct drop_convergence_test_wrappers\n  {\n    typedef drop_convergence_test<double> w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"drop_convergence_test\", no_init)\n        .def(init<optional<std::size_t, double, double> >((\n          arg(\"n_test_points\")=5,\n          arg(\"max_drop_eps\")=1.e-5,\n          arg(\"iteration_coefficient\")=2)))\n        .def(\"n_test_points\", &w_t::n_test_points)\n        .def(\"max_drop_eps\", &w_t::max_drop_eps)\n        .def(\"iteration_coefficient\", &w_t::iteration_coefficient)\n        .def(\"__call__\", &w_t::operator())\n        .def(\"objective_function_values\", &w_t::objective_function_values, (\n          arg(\"f\")))\n        .def(\"max_drop\", &w_t::max_drop)\n      ;\n    }\n  };\n\n  void init_module()\n  {\n    using namespace boost::python;\n\n    scope().attr(\"have_lbfgs_fem\") =\n#if defined(SCITBX_LBFGS_HAVE_LBFGS_FEM)\n      true;\n#else\n      false;\n#endif\n    def(\"fortran\", fortran, (\n      arg(\"n\"),\n      arg(\"m\"),\n      arg(\"x\"),\n      arg(\"f\"),\n      arg(\"g\"),\n      arg(\"diagco\"),\n      arg(\"diag\"),\n      arg(\"iprint\"),\n      arg(\"eps\"),\n      arg(\"xtol\"),\n      arg(\"w\"),\n      arg(\"iflag\")));\n    def(\"raw_reference\", raw_reference, (\n      arg(\"n\"),\n      arg(\"m\"),\n      arg(\"x\"),\n      arg(\"f\"),\n      arg(\"g\"),\n      arg(\"diagco\"),\n      arg(\"diag\"),\n      arg(\"iprint\"),\n      arg(\"eps\"),\n      arg(\"xtol\"),\n      arg(\"w\"),\n      arg(\"iflag\")));\n    raw_lbfgs_wrappers::wrap();\n\n    minimizer_wrappers::wrap();\n    traditional_convergence_test_wrappers::wrap();\n    drop_convergence_test_wrappers::wrap();\n  }\n\n}}} // namespace scitbx::lbfgs::ext\n\nBOOST_PYTHON_MODULE(scitbx_lbfgs_ext)\n{\n  scitbx::lbfgs::ext::init_module();\n}\n", "meta": {"hexsha": "bb5f8fbff386185fb6c1ab86991ca6c1317b62d7", "size": 10928, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/lbfgs/ext.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "scitbx/lbfgs/ext.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "scitbx/lbfgs/ext.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 25.8345153664, "max_line_length": 93, "alphanum_fraction": 0.5828147877, "num_tokens": 3300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.25267028176721046}}
{"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 \"bdd_utils.hpp\"\n\n#include <functional>\n#include <unordered_map>\n#include <unordered_set>\n\n#include <boost/range/adaptors.hpp>\n#include <boost/range/algorithm.hpp>\n#include <boost/range/algorithm_ext/iota.hpp>\n#include <boost/range/numeric.hpp>\n\n#include <cudd.h>\n#include <cuddInt.h>\n\n#include <core/utils/range_utils.hpp>\n\nnamespace cirkit\n{\n\n/******************************************************************************\n * Types                                                                      *\n ******************************************************************************/\n\n/******************************************************************************\n * Functions                                                                  *\n ******************************************************************************/\n\nBDD make_cube( Cudd& manager, const std::vector<BDD>& vars )\n{\n  return boost::accumulate( vars, manager.bddOne(), []( const BDD& x1, const BDD& x2 ) { return x1 & x2; } );\n}\n\nBDD make_cube( Cudd& manager, const std::string& cube )\n{\n  std::vector<BDD> vars;\n\n  for ( auto i = 0u; i < cube.size(); ++i )\n  {\n    if ( cube[i] == '0' )\n    {\n      vars.push_back( ~manager.bddVar( i ) );\n    }\n    else if ( cube[i] == '1' )\n    {\n      vars.push_back( manager.bddVar( i ) );\n    }\n    else\n    {\n      assert( cube[i] == '-' );\n    }\n  }\n  return make_cube( manager, vars );\n}\n\nbool is_selfdual( const Cudd& manager, const BDD& f )\n{\n  /* negative literals */\n  std::vector<BDD> lits( manager.ReadSize() );\n  for ( auto i = 0u; i < lits.size(); ++i )\n  {\n    lits[i] = !manager.bddVar( i );\n  }\n\n  return f.VectorCompose( lits ) == !f;\n}\n\nbool is_monotone( const Cudd& manager, const BDD& f )\n{\n  for ( auto i = 0; i < manager.ReadSize(); ++i )\n  {\n    if ( !f.Increasing( i ) ) { return false; }\n  }\n  return true;\n}\n\n/*\n * Implementation according to\n * Knuth TAOCP Exercise 7.1.4-106\n * [T. Horiyama and T. Ibaraki, Artificial Intelligence 136 (2002), 189-213]\n */\nbool is_horn( const Cudd& manager, const BDD& f, const BDD& g, const BDD& h )\n{\n  if ( f > g ) { return is_horn( manager, g, f, h ); }\n  if ( f == manager.bddZero() || h == manager.bddOne() ) { return true; }\n  if ( g == manager.bddOne() || h == manager.bddZero() ) { return false; }\n\n  assert( f != manager.bddOne() );\n  assert( g != manager.bddZero() );\n\n  BDD fl( manager, cuddE( f.getRegularNode() ) );\n  BDD fh( manager, cuddT( f.getRegularNode() ) );\n  BDD gl( manager, cuddE( g.getRegularNode() ) );\n  BDD gh( manager, cuddT( g.getRegularNode() ) );\n  BDD hl( manager, cuddE( h.getRegularNode() ) );\n  BDD hh( manager, cuddT( h.getRegularNode() ) );\n\n  return is_horn( manager, fl, gl, hl ) && is_horn( manager, fl, gh, hl ) && is_horn( manager, fh, gl, hl ) && is_horn( manager, fh, gh, hh );\n}\n\nbool is_horn( const Cudd& manager, const BDD& f )\n{\n  return is_horn( manager, f, f, f );\n}\n\n#define EXTRA_BDD_COMPARE_TAG 0x96\n#define EXTRA_BDD_COMPARE_EQ ((DdNode*)1)\n#define EXTRA_BDD_COMPARE_IC ((DdNode*)2)\n#define EXTRA_BDD_COMPARE_LT ((DdNode*)3)\n#define EXTRA_BDD_COMPARE_GT ((DdNode*)4)\n\nDdNode * Extra_bddCompare( DdManager * dd, DdNode * f, DdNode * g )\n{\n  DdNode * one = DD_ONE( dd );\n  DdNode * zero = Cudd_Not( one );\n\n  if ( f == g ) { return EXTRA_BDD_COMPARE_EQ; }\n  if ( f == zero || g == one ) { return EXTRA_BDD_COMPARE_LT; }\n  if ( f == one || g == zero ) { return EXTRA_BDD_COMPARE_GT; }\n\n  DdNode * r = nullptr;\n  /*if ( ( r = cuddConstantLookup( dd, EXTRA_BDD_COMPARE_TAG, f, g, nullptr ) ) )\n  {\n    return r;\n  }*/\n\n  auto fl = Cudd_NotCond( Cudd_E( Cudd_Regular( f ) ), Cudd_IsComplement( f ) );\n  auto fh = Cudd_NotCond( Cudd_T( Cudd_Regular( f ) ), Cudd_IsComplement( f ) );\n  auto gl = Cudd_NotCond( Cudd_E( Cudd_Regular( g ) ), Cudd_IsComplement( g ) );\n  auto gh = Cudd_NotCond( Cudd_T( Cudd_Regular( g ) ), Cudd_IsComplement( g ) );\n\n  auto rl = Extra_bddCompare( dd, fl, gl );\n  if ( rl == EXTRA_BDD_COMPARE_IC ) { r = EXTRA_BDD_COMPARE_IC; }\n  else\n  {\n    auto rh = Extra_bddCompare( dd, fh, gh );\n    if ( rh == EXTRA_BDD_COMPARE_IC ) { r = EXTRA_BDD_COMPARE_IC; }\n    else if ( rl == EXTRA_BDD_COMPARE_EQ ) { r = rh; }\n    else if ( rh == EXTRA_BDD_COMPARE_EQ ) { r = rl; }\n    else if ( rl == rh ) { r = rl; }\n    else { r = EXTRA_BDD_COMPARE_IC; }\n  }\n\n  //cuddCacheInsert( dd, EXTRA_BDD_COMPARE_TAG, f, g, nullptr, r );\n  return r;\n}\n\nbool Extra_bddUnate( DdManager * dd, DdNode * f, std::vector<int>& ps )\n{\n  /* Initialize */\n  ps.resize( Cudd_ReadSize( dd ) );\n  boost::fill( ps, 0 );\n\n  if ( Cudd_IsConstant( f ) ) return true;\n\n  auto fr = Cudd_Regular( f );\n\n  auto fl = Cudd_NotCond( Cudd_E( fr ), Cudd_IsComplement( f ) );\n  auto fh = Cudd_NotCond( Cudd_T( fr ), Cudd_IsComplement( f ) );\n\n  if ( !Extra_bddUnate( dd, fl, ps ) || !Extra_bddUnate( dd, fh, ps ) ) { return false; }\n\n  auto r = Extra_bddCompare( dd, fl, fh );\n  if ( r == EXTRA_BDD_COMPARE_IC ) { return false; }\n\n  if ( r == EXTRA_BDD_COMPARE_LT )\n  {\n    if ( ps[fr->index] < 0 ) { return false; }\n    ps[fr->index] = 1;\n    return true;\n  }\n  if ( r == EXTRA_BDD_COMPARE_GT )\n  {\n    if ( ps[fr->index] > 0 ) { return false; }\n    ps[fr->index] = -1;\n    return true;\n  }\n\n  /* this should not happen */\n  assert( r == EXTRA_BDD_COMPARE_EQ );\n  assert( false );\n  return false;\n}\n\nbool is_unate( const Cudd& manager, const BDD& f, std::vector<int>& ps )\n{\n  return Extra_bddUnate( manager.getManager(), f.getNode(), ps );\n}\n\nvoid collect_nodes( DdNode * f, std::unordered_set<DdNode*>& visited )\n{\n  assert( f );\n  assert( !Cudd_IsComplement( f ) );\n\n  /* node visited before? */\n  if ( visited.find( f ) != visited.end() ) { return; }\n\n  /* mark node as visited */\n  visited.insert( f );\n\n  /* terminate? */\n  if cuddIsConstant( f ) { return; }\n\n  /* recur */\n  collect_nodes( cuddT( f ), visited );\n  collect_nodes( Cudd_Regular( cuddE( f ) ), visited );\n}\n\nvoid collect_nodes_and_count( DdNode * f, std::unordered_map<DdNode*, unsigned>& visited )\n{\n  assert( f );\n  assert( !Cudd_IsComplement( f ) );\n\n  /* node visited before? */\n  auto it = visited.find( f );\n  if ( it != visited.end() )\n  {\n    /* visited once more */\n    it->second++;\n    return;\n  }\n\n  /* mark node as visited */\n  visited.insert( {f, 1u} );\n\n  /* terminate? */\n  if cuddIsConstant( f ) { return; }\n\n  /* recur */\n  collect_nodes_and_count( cuddT( f ), visited );\n  collect_nodes_and_count( Cudd_Regular( cuddE( f ) ), visited );\n}\n\nvoid collect_nodes_and_count_ignore_complemented( const DdNode * f, std::unordered_map<DdNode*, unsigned>& visited )\n{\n  assert( f );\n\n  auto fr = Cudd_Regular( f );\n\n  /* node visited before? */\n  auto it = visited.find( fr );\n  if ( it != visited.end() )\n  {\n    /* visited once more */\n    if ( !Cudd_IsComplement( f ) )\n    {\n      it->second++;\n    }\n    return;\n  }\n\n  /* mark node as visited */\n  visited.insert( {fr, (Cudd_IsComplement( f ) ? 0u : 1u)} );\n\n  /* terminate? */\n  if cuddIsConstant( fr ) { return; }\n\n  /* recur */\n  collect_nodes_and_count_ignore_complemented( cuddT( fr ), visited );\n  collect_nodes_and_count_ignore_complemented( cuddE( fr ), visited );\n}\n\nstd::vector<unsigned> level_sizes( DdManager * dd, const std::vector<DdNode*>& fs )\n{\n  using namespace std::placeholders;\n\n  std::vector<unsigned> sizes( Cudd_ReadSize( dd ) );\n\n  /* collect all nodes in the BDDs */\n  std::unordered_set<DdNode*> visited;\n  for ( const auto* f : fs )\n  {\n    collect_nodes( Cudd_Regular( f ), visited );\n  }\n\n  for ( const auto* node : visited )\n  {\n    if ( !cuddIsConstant( node ) )\n    {\n      sizes[node->index]++;\n    }\n  }\n\n  return sizes;\n}\n\nstd::vector<unsigned> level_sizes( const Cudd& manager, const std::vector<BDD>& fs )\n{\n  using namespace std::placeholders;\n  using boost::adaptors::transformed;\n\n  std::vector<DdNode*> fs_native( fs.size() );\n  boost::copy( fs | transformed( std::bind( &BDD::getRegularNode, _1 ) ), fs_native.begin() );\n\n  return level_sizes( manager.getManager(), fs_native );\n}\n\nunsigned maximum_fanout( DdManager* manager, const std::vector<DdNode*>& fs )\n{\n  using boost::adaptors::map_values;\n\n  /* collect all nodes in the BDDs and count */\n  std::unordered_map<DdNode*, unsigned> visited;\n  for ( const auto* f : fs )\n  {\n    collect_nodes_and_count_ignore_complemented( f, visited );\n  }\n\n  /* erase constant nodes from visited list */\n  visited.erase( DD_ONE( manager ) );\n  visited.erase( Cudd_Not( DD_ONE( manager ) ) );\n\n  if ( visited.empty() )\n  {\n    return 0u;\n  }\n  else\n  {\n    return *boost::max_element( visited | map_values );\n  }\n}\n\nunsigned maximum_fanout( const Cudd& manager, const std::vector<BDD>& fs )\n{\n  using namespace std::placeholders;\n  using boost::adaptors::transformed;\n\n  std::vector<DdNode*> fs_native( fs.size() );\n  boost::copy( fs | transformed( std::bind( &BDD::getNode, _1 ) ), fs_native.begin() );\n\n  return maximum_fanout( manager.getManager(), fs_native );\n}\n\nvoid count_complement_edges_rec( DdManager* manager, DdNode* f, unsigned& count, std::unordered_set<DdNode*>& visited )\n{\n  if ( visited.find( f ) != visited.end() )\n  {\n    return;\n  }\n\n  if ( Cudd_IsComplement( f ) )\n  {\n    ++count;\n  }\n\n  if ( Cudd_IsConstant( f ) )\n  {\n    return;\n  }\n\n  const auto fr = Cudd_Regular( f );\n\n  count_complement_edges_rec( manager, cuddT( fr ), count, visited );\n  count_complement_edges_rec( manager, cuddE( fr ), count, visited );\n\n  visited.insert( f );\n}\n\nunsigned count_complement_edges( DdManager* manager, const std::vector<DdNode*>& fs )\n{\n  std::unordered_set<DdNode*> visited;\n\n  auto count = 0u;\n\n  for ( const auto& f : fs )\n  {\n    count_complement_edges_rec( manager, f, count, visited );\n  }\n\n  return count;\n}\n\nunsigned count_complement_edges( const Cudd& manager, const std::vector<BDD>& fs )\n{\n  using namespace std::placeholders;\n  using boost::adaptors::transformed;\n\n  std::vector<DdNode*> fs_native( fs.size() );\n  boost::copy( fs | transformed( std::bind( &BDD::getNode, _1 ) ), fs_native.begin() );\n\n  return count_complement_edges( manager.getManager(), fs_native );\n}\n\nBDD make_eq_rec( const Cudd& manager, const std::vector<BDD>& vars, unsigned pos, int k, std::map<std::pair<unsigned, int>, BDD>& visited )\n{\n  /* terminal */\n  if ( pos == vars.size() )\n  {\n    return ( k == 0 ) ? manager.bddOne() : manager.bddZero();\n  }\n\n  /* cannot be 1 anymore */\n  if ( ( k < 0 ) || ( k > static_cast<int>( vars.size() - pos ) ) )\n  {\n    return manager.bddZero();\n  }\n\n  /* cached? */\n  const auto it = visited.find( {pos, k} );\n  if ( it != visited.end() ) { return it->second; }\n\n  const auto f = ( vars[pos] & make_eq_rec( manager, vars, pos + 1, k - 1, visited ) ) |\n                 ( ~vars[pos] & make_eq_rec( manager, vars, pos + 1, k, visited ) );\n\n  visited.insert( {{pos, k}, f} );\n\n  return f;\n}\n\nBDD make_eq( const Cudd& manager, const std::vector<BDD>& vars, unsigned k )\n{\n  std::map<std::pair<unsigned, int>, BDD> visited;\n  return make_eq_rec( manager, vars, 0, (int)k, visited );\n}\n\nDdNode * bdd_copy_rec( DdManager* mgr_from, DdNode* from, DdManager* mgr_to, std::map<DdNode*, DdNode*>& visited, const std::vector<unsigned>& index_map )\n{\n  assert( !Cudd_IsComplement( from ) );\n\n  if ( Cudd_IsConstant( from ) )\n  {\n    if ( from == DD_ONE( mgr_from ) )\n    {\n      return DD_ONE( mgr_to );\n    }\n    else\n    {\n      return Cudd_Not( DD_ONE( mgr_to ) );\n    }\n  }\n\n  /* visited table */\n  const auto it = visited.find( from );\n  if ( it != visited.end() ) { return it->second; }\n\n  auto * var = Cudd_bddIthVar( mgr_to, index_map.at( from->index ) );\n\n  auto * high = Cudd_NotCond( bdd_copy_rec( mgr_from, Cudd_Regular( cuddT( from ) ), mgr_to, visited, index_map ), Cudd_IsComplement( cuddT( from ) ) );\n  auto * low  = Cudd_NotCond( bdd_copy_rec( mgr_from, Cudd_Regular( cuddE( from ) ), mgr_to, visited, index_map ), Cudd_IsComplement( cuddE( from ) ) );\n\n  /* create new node */\n  auto* node = Cudd_bddIte( mgr_to, var, high, low );\n\n  visited.insert( {from, node} );\n  return node;\n}\n\nstd::vector<DdNode*> bdd_copy( DdManager* mgr_from, const std::vector<DdNode*>& from, DdManager* mgr_to, std::vector<unsigned>& index_map )\n{\n  if ( index_map.empty() )\n  {\n    index_map.resize( Cudd_ReadSize( mgr_from ) );\n    boost::iota( index_map, 0u );\n  }\n\n  std::map<DdNode*, DdNode*> visited;\n\n  std::vector<DdNode*> ret;\n\n  for ( auto* node : from )\n  {\n    ret.push_back( Cudd_NotCond( bdd_copy_rec( mgr_from, Cudd_Regular( node ), mgr_to, visited, index_map ), Cudd_IsComplement( node ) ) );\n  }\n\n  return ret;\n}\n\nstd::vector<BDD> bdd_copy( const Cudd& mgr_from, const std::vector<BDD>& from, const Cudd& mgr_to, std::vector<unsigned>& index_map )\n{\n  using namespace std::placeholders;\n  using boost::adaptors::transformed;\n\n  std::vector<DdNode*> from_native( from.size() );\n  boost::copy( from | transformed( std::bind( &BDD::getNode, _1 ) ), from_native.begin() );\n\n  auto orig = bdd_copy( mgr_from.getManager(), from_native, mgr_to.getManager(), index_map );\n  std::vector<BDD> ret;\n\n  for ( auto* node : orig )\n  {\n    ret.push_back( BDD( mgr_to, node ) );\n  }\n\n  return ret;\n}\n\nbdd_function_t compute_characteristic( const bdd_function_t& bdd, bool inputs_first )\n{\n  const auto& mgr_from = bdd.first;\n  const auto& from     = bdd.second;\n\n  Cudd mgr;\n  ntimes( mgr_from.ReadSize() + from.size(), [&]() { mgr.bddVar(); } );\n\n  std::vector<unsigned> index_map( mgr_from.ReadSize() );\n  boost::iota( index_map, inputs_first ? 0u : from.size() );\n\n  const auto fs = bdd_copy( mgr_from, from, mgr, index_map );\n\n  auto f = mgr.bddOne();\n\n  const auto offset = inputs_first ? mgr_from.ReadSize() : 0u;\n  for ( auto i = 0u; i < fs.size(); ++i )\n  {\n    f &= mgr.bddVar( offset + i ).Xnor( fs[i] );\n  }\n\n  return {mgr, {f}};\n}\n\ncube_vec_t bdd_to_cubes( DdManager* manager, DdNode* f )\n{\n  DdGen * gen;\n  int * ddcube;\n  CUDD_VALUE_TYPE value;\n\n  cube_vec_t cubes;\n\n  Cudd_ForeachCube( manager, f, gen, ddcube, value )\n  {\n    boost::dynamic_bitset<> bits( manager->size ), care( manager->size );\n    for ( auto i = 0; i < manager->size; ++i )\n    {\n      switch ( ddcube[i] )\n      {\n      case 0:\n        care[i] = true;\n        break;\n      case 1:\n        bits[i] = true;\n        care[i] = true;\n        break;\n      default:\n        break;\n      }\n    }\n    cubes.push_back( cube( bits, care ) );\n  }\n\n  return cubes;\n}\n\ncube_vec_t bdd_to_cubes( const Cudd& manager, BDD f )\n{\n  return bdd_to_cubes( manager.getManager(), f.getNode() );\n}\n\n/******************************************************************************\n * new BDD operations                                                         *\n ******************************************************************************/\n\nDdNode* bdd_up_rec( DdManager* manager, DdNode* f )\n{\n  /* terminal case */\n  if ( Cudd_IsConstant( f ) ) { return f; }\n\n  const auto* F = Cudd_Regular( f );\n\n  if ( F->ref != 1 )\n  {\n    auto* r = cuddCacheLookup1( manager, bdd_up_rec, f );\n    if ( r )\n    {\n      return r;\n    }\n  }\n\n  const auto top = manager->perm[F->index];\n\n  auto* fl = Cudd_NotCond( cuddE( F ), Cudd_IsComplement( f ) );\n  auto* fh = Cudd_NotCond( cuddT( F ), Cudd_IsComplement( f ) );\n  auto* t1 = Cudd_bddOr( manager, fl, fh );\n  if ( !t1 )\n  {\n    return nullptr;\n  }\n  cuddRef( t1 );\n\n  auto* rh = bdd_up_rec( manager, t1 );\n  if ( !rh )\n  {\n    Cudd_IterDerefBdd( manager, t1 );\n    return nullptr;\n  }\n  cuddRef( rh );\n\n  auto* rl = bdd_up_rec( manager, fl );\n  if ( !rl )\n  {\n    Cudd_IterDerefBdd( manager, t1 );\n    Cudd_IterDerefBdd( manager, rh );\n  }\n  cuddRef( rl );\n\n  DdNode* r;\n  if ( rl == rh )\n  {\n    r = rh;\n  }\n  else\n  {\n    if ( Cudd_IsComplement( rh ) )\n    {\n      r = cuddUniqueInter( manager, (int)top, Cudd_Not( rh ), Cudd_Not( rl ) );\n      if ( !r )\n      {\n        Cudd_IterDerefBdd( manager, t1 );\n        Cudd_IterDerefBdd( manager, rh );\n        Cudd_IterDerefBdd( manager, rl );\n        return nullptr;\n      }\n      r = Cudd_Not( r );\n    }\n    else\n    {\n      r = cuddUniqueInter( manager, (int)top, rh, rl );\n      if ( !r )\n      {\n        Cudd_IterDerefBdd( manager, t1 );\n        Cudd_IterDerefBdd( manager, rh );\n        Cudd_IterDerefBdd( manager, rl );\n        return nullptr;\n      }\n    }\n  }\n  cuddDeref( t1 );\n  cuddDeref( rh );\n  cuddDeref( rl );\n  if ( F->ref != 1 )\n  {\n    cuddCacheInsert1( manager, bdd_up, f, r );\n  }\n  return r;\n}\n\nDdNode* bdd_up( DdManager *manager, DdNode *f )\n{\n  DdNode *res;\n\n  do\n  {\n    manager->reordered = 0;\n    res = bdd_up_rec( manager, f );\n  }\n  while ( manager->reordered == 1 );\n  return res;\n}\n\nBDD bdd_up( Cudd& manager, const BDD& f )\n{\n  auto* r = bdd_up( f.manager(), f.getNode() );\n  return BDD( manager, r );\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": "e02e2c3fb5fcc5529fb82bd2b3ca0c32a31874cf", "size": 17976, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/utils/bdd_utils.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/core/utils/bdd_utils.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/core/utils/bdd_utils.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": 26.1659388646, "max_line_length": 154, "alphanum_fraction": 0.6024143302, "num_tokens": 5358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.25267028176721046}}
{"text": "/*ckwg +29\n * Copyright 2015, 2019 by Kitware, 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 *  * 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 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 name of Kitware, Inc. nor the names of any contributors may be used\n *    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''\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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR\n * 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/**\n * \\file\n * \\brief core homography template implementations\n */\n\n#include \"homography.h\"\n\n#include <cmath>\n\n#include <vital/exceptions/math.h>\n\n#include <Eigen/LU>\n\nnamespace kwiver {\nnamespace vital {\n\nnamespace //anonymous\n{\n\n/// Private helper method for point transformation via homography matrix\ntemplate < typename T >\nEigen::Matrix< T, 2, 1 >\nh_map_point( Eigen::Matrix< T, 3, 3 > const& h, Eigen::Matrix< T, 2, 1 > const& p )\n{\n  Eigen::Matrix< T, 3, 1 > out_pt = h * Eigen::Matrix< T, 3, 1 > ( p[0], p[1], 1.0 );\n\n  if ( fabs( out_pt[2] ) <= Eigen::NumTraits< T >::dummy_precision() )\n  {\n    throw point_maps_to_infinity();\n  }\n  return Eigen::Matrix< T, 2, 1 > ( out_pt[0] / out_pt[2], out_pt[1] / out_pt[2] );\n}\n\n} // end anonymous namespace\n\n\n/// Construct an identity homography\ntemplate < typename T >\nhomography_< T >\n::homography_()\n  : h_( matrix_t::Identity() )\n{\n}\n\n\n/// Construct from a provided transformation matrix\ntemplate < typename T >\nhomography_< T >\n::homography_( Eigen::Matrix< T, 3, 3 > const& mat )\n  : h_( mat )\n{\n}\n\n\n/// Conversion Copy constructor -- float specialization\ntemplate < >\ntemplate < >\nhomography_< float >\n::homography_( homography_< float > const& other )\n  : h_( other.get_matrix() )\n{\n}\n\n\n/// Conversion Copy constructor -- double specialization\ntemplate < >\ntemplate < >\nhomography_< double >\n::homography_( homography_< double > const& other )\n  : h_( other.get_matrix() )\n{\n}\n\n\n/// Construct from a generic homography\ntemplate < typename T >\nhomography_< T >\n::homography_( homography const& base )\n  : h_( base.matrix().template cast< T > () )\n{\n}\n\n\n/// Construct from a generic homography -- double specialization\ntemplate < >\nhomography_< double >\n::homography_( homography const& base )\n  : h_( base.matrix() )\n{\n}\n\n\n/// Create a clone of outself as a shared pointer\ntemplate < typename T >\ntransform_2d_sptr\nhomography_< T >\n::clone() const\n{\n  return std::make_shared< homography_< T > >( *this );\n}\n\n\n/// Get a double-typed copy of the underlying matrix transformation\ntemplate < typename T >\nEigen::Matrix< double, 3, 3 >\nhomography_< T >\n::matrix() const\n{\n  return this->h_.template cast< double > ();\n}\n\n\n/// Specialization for homographies with native double type\ntemplate < >\nEigen::Matrix< double, 3, 3 >\nhomography_< double >\n::matrix() const\n{\n  return this->h_;\n}\n\n\n/// Normalize homography transformation in-place\ntemplate < typename T >\nhomography_sptr\nhomography_< T >\n::normalize() const\n{\n  matrix_t norm = this->get_matrix();\n\n  if ( fabs( norm( 2, 2 ) ) >= Eigen::NumTraits< T >::dummy_precision() )\n  {\n    norm /= norm( 2, 2 );\n  }\n  return homography_sptr( new homography_< T > ( norm ) );\n}\n\n\n/// Inverse the homography transformation returning a new transformation\ntemplate < typename T >\nhomography_sptr\nhomography_< T >\n::inverse() const\n{\n  matrix_t inv;\n  bool isvalid;\n\n  this->h_.computeInverseWithCheck( inv, isvalid );\n  if ( ! isvalid )\n  {\n    throw non_invertible_matrix();\n  }\n  return homography_sptr( new homography_< T > ( inv ) );\n}\n\n\n/// Map a 2D double-type point using this homography\ntemplate < typename T >\nEigen::Matrix< double, 2, 1 >\nhomography_< T >\n::map( Eigen::Matrix< double, 2, 1 > const& p ) const\n{\n  // Explicitly refer to templated version of method so as to not infinitely\n  // recurse.\n  Eigen::Matrix< double, 3, 3 > m = h_.template cast< double > ();\n\n  return h_map_point( m, p );\n}\n\n\n/// Map a 2D double-type point using this homography -- double specialization\ntemplate < >\nEigen::Matrix< double, 2, 1 >\nhomography_< double >\n::map( Eigen::Matrix< double, 2, 1 > const& p ) const\n{\n  return h_map_point( h_, p );\n}\n\n\n/// Get the underlying matrix transformation\ntemplate < typename T >\ntypename homography_< T >::matrix_t &\nhomography_< T >\n::get_matrix()\n{\n  return this->h_;\n}\n\n\n/// Get a const new copy of the underlying matrix transformation.\ntemplate < typename T >\ntypename homography_< T >::matrix_t const &\nhomography_< T >\n::get_matrix() const\n{\n  return this->h_;\n}\n\n\n/// Map a 2D point using this homography -- generic version\ntemplate < typename T >\nEigen::Matrix< T, 2, 1 >\nhomography_< T >\n::map_point( Eigen::Matrix< T, 2, 1 > const& p ) const\n{\n  return h_map_point< T > ( h_.template cast< T > (), p );\n}\n\n\n/// Map a 2D point using this homography -- float specialization\ntemplate < >\nEigen::Matrix< float, 2, 1 >\nhomography_< float >\n::map_point( Eigen::Matrix< float, 2, 1 > const& p ) const\n{\n  return h_map_point( h_, p );\n}\n\n\n/// Map a 2D point using this homography -- double specialization\ntemplate < >\nEigen::Matrix< double, 2, 1 >\nhomography_< double >\n::map_point( Eigen::Matrix< double, 2, 1 > const& p ) const\n{\n  return h_map_point( h_, p );\n}\n\n\n/// Custom f2f_homography multiplication operator.\ntemplate < typename T >\nhomography_< T >\nhomography_< T >\n::operator*( homography_< T > const& rhs ) const\n{\n  return homography_< T > ( h_ * rhs.h_ );\n}\n\n\n// ===========================================================================\n// Other Functions\n// ---------------------------------------------------------------------------\n\n/// homography_<T> output stream operator\ntemplate < typename T >\nstd::ostream&\noperator<<( std::ostream& s, homography_< T > const& h )\n{\n  s << h.get_matrix();\n  return s;\n}\n\n\n/// Output stream operator for \\p homography instances\nstd::ostream&\noperator<<( std::ostream& s, homography const& h )\n{\n  s << h.matrix();\n  return s;\n}\n\n\n// ===========================================================================\n// Template class instantiation\n// ---------------------------------------------------------------------------\n/// \\cond DoxygenSuppress\n#define INSTANTIATE_HOMOGRAPHY( T )              \\\n  template class homography_< T >;               \\\n  template VITAL_EXPORT std::ostream&            \\\n  operator<<( std::ostream&,                     \\\n              homography_< T > const& )\n\nINSTANTIATE_HOMOGRAPHY( float );\nINSTANTIATE_HOMOGRAPHY( double );\n#undef INSTANTIATE_HOMOGRAPHY\n/// \\endcond\n\n} } // end vital namespace\n", "meta": {"hexsha": "28d025c664a829c2527a95b77a3ea727c2bdc053", "size": 7602, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "vital/types/homography.cxx", "max_stars_repo_name": "abutaufique/my_kwiver", "max_stars_repo_head_hexsha": "5e2fdba15a8f3362c811f004bd6c309df54d470d", "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": "vital/types/homography.cxx", "max_issues_repo_name": "abutaufique/my_kwiver", "max_issues_repo_head_hexsha": "5e2fdba15a8f3362c811f004bd6c309df54d470d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-03-19T00:52:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T23:48:06.000Z", "max_forks_repo_path": "vital/types/homography.cxx", "max_forks_repo_name": "abutaufique/my_kwiver", "max_forks_repo_head_hexsha": "5e2fdba15a8f3362c811f004bd6c309df54d470d", "max_forks_repo_licenses": ["BSD-3-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.5225806452, "max_line_length": 85, "alphanum_fraction": 0.6568008419, "num_tokens": 1907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2526702748241491}}
{"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_FACTORIZATIONS_GENEIG_HPP_INCLUDED\n#define NT2_LINALG_FUNCTIONS_FACTORIZATIONS_GENEIG_HPP_INCLUDED\n\n#include <nt2/linalg/functions/geneig.hpp>\n#include <nt2/include/functions/divides.hpp>\n#include <nt2/include/functions/ggev_w.hpp>\n#include <nt2/include/functions/ggev_wvr.hpp>\n#include <nt2/include/functions/ggev_wvrvl.hpp>\n#include <nt2/include/functions/height.hpp>\n#include <nt2/include/functions/from_diag.hpp>\n#include <nt2/include/functions/of_size.hpp>\n#include <nt2/include/functions/resize.hpp>\n#include <nt2/include/functions/tie.hpp>\n#include <nt2/linalg/details/utility/lapack_verify.hpp>\n#include <nt2/linalg/options.hpp>\n#include <nt2/core/container/table/table.hpp>\n#include <nt2/core/utility/assign_swap.hpp>\n#include <nt2/core/container/dsl/as_terminal.hpp>\n#include <nt2/sdk/meta/as_real.hpp>\n#include <boost/dispatch/attributes.hpp>\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( geneig_, tag::cpu_\n                            , (A0)\n                            , (scalar_<unspecified_<A0> >)\n                              (scalar_<unspecified_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE result_type operator()(const A0& a0, const A0& a1) const\n    {\n      return a1/a0;\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( geneig_, tag::cpu_\n                            , (A0)(A1)\n                            , (scalar_<unspecified_<A0> >)\n                              (scalar_<unspecified_<A0> >)\n                              (unspecified_<A1>)\n                            )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE result_type operator()(const A0& a0, const A0& a1, const A1&) const\n    {\n      return a1/a0;\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( geneig_, tag::cpu_\n                            , (A0)(A1)(A2)\n                            , (scalar_<unspecified_<A0> >)\n                              (scalar_<unspecified_<A0> >)\n                              (unspecified_<A1>)\n                              (unspecified_<A2>)\n                            )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE result_type operator()(const A0& a0, const A0& a1, const A1&, const A2&) const\n    {\n      return a1/a0;\n    }\n  };\n\n  //============================================================================\n  //Geneig computations\n  //============================================================================\n  BOOST_DISPATCH_IMPLEMENT  ( geneig_, tag::cpu_\n                            , (A0)(N0)(A1)(N1)\n                            , ((node_<A0, nt2::tag::geneig_\n                                    , N0, nt2::container::domain\n                                      >\n                              ))\n                              ((node_<A1, nt2::tag::tie_\n                                    , N1, nt2::container::domain\n                                     >\n                              ))\n                            )\n  {\n    typedef void  result_type;\n    typedef typename boost::proto::result_of::child_c<A0&,0>::value_type child0;\n    typedef typename child0::value_type                                  type_t;\n    typedef typename nt2::meta::as_real<type_t>::type                   rtype_t;\n    typedef typename nt2::meta::as_complex<rtype_t>::type               ctype_t;\n    typedef rtype_t T;\n    typedef nt2::memory::container<tag::table_,  type_t, nt2::_2D>   o_semantic;\n    typedef nt2::memory::container<tag::table_, rtype_t, nt2::_2D>   r_semantic;\n    typedef nt2::memory::container<tag::table_, ctype_t, nt2::_2D>   c_semantic;\n\n    BOOST_FORCEINLINE result_type operator()( A0& a0, A1& a1 ) const\n    {\n      eval(a0, a1, N0(), N1());\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - W = GENEIG(A)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<2> const&\n              , boost::mpl::long_<1> const&\n              ) const\n    {\n      eval1_3(a0, a1\n             , nt2::policy<ext::vector_>());\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - W = GENEIG(A, B, matrix_/vector_)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<3> const&\n              , boost::mpl::long_<1> const&\n              ) const\n    {\n      eval1_3(a0, a1\n             , boost::proto::value(boost::proto::child_c<2>(a0)));\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [VR, W]= GENEIG(A, B)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<2> const&\n              , boost::mpl::long_<2> const&\n              ) const\n    {\n      eval2_3(a0, a1\n             , nt2::policy<ext::matrix_>());\n    }\n\n    /// INTERNAL ONLY: 1o 3i\n    BOOST_FORCEINLINE\n    void eval1_3 ( A0& a0, A1& a1\n                 , nt2::policy<ext::vector_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> wa, wb;\n      NT2_AS_TERMINAL_INOUT(o_semantic, a\n                           , boost::proto::child_c<0>(a0), wa);\n      NT2_AS_TERMINAL_INOUT(o_semantic, b\n                           , boost::proto::child_c<1>(a0), wb);\n      NT2_AS_TERMINAL_OUT  (c_semantic, w\n                           , boost::proto::child_c<0>(a1));\n      size_t n = height(a);\n      container::table <type_t>  beta(nt2::of_size(n,1));\n      w.resize(nt2::of_size(n,1)); ;\n      NT2_LAPACK_VERIFY(nt2::ggev_w( boost::proto::value(a)\n                                   , boost::proto::value(b)\n                                   , boost::proto::value(w)\n                                   , boost::proto::value(beta)));\n      assign_swap(boost::proto::child_c<0>(a1), w);\n      boost::proto::child_c<0>(a1) /= beta;\n    }\n\n\n    /// INTERNAL ONLY: 1o 3i\n    BOOST_FORCEINLINE\n    void eval1_3 ( A0& a0, A1& a1\n                 , nt2::policy<ext::matrix_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> wa, wb;\n      NT2_AS_TERMINAL_INOUT(o_semantic, a\n                           , boost::proto::child_c<0>(a0), wa);\n      NT2_AS_TERMINAL_INOUT(o_semantic, b\n                           , boost::proto::child_c<1>(a0), wb);\n      size_t n = height(a);\n      container::table <type_t> beta(nt2::of_size(n,1));\n      container::table <ctype_t> alpha(nt2::of_size(n,1));\n\n      NT2_LAPACK_VERIFY(nt2::ggev_w( boost::proto::value(a)\n                                   , boost::proto::value(b)\n                                   , boost::proto::value(alpha)\n                                   , boost::proto::value(beta)));\n      boost::proto::child_c<0>(a1) = from_diag(alpha/beta);\n      //currently from_diag doesnt support aliasing\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [alpha, beta] = GENEIG(A, B, alphabeta_) or\n    ///                 [vr, w]       = GENEIG(A, B, matrix_/vector_)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<3> const&\n              , boost::mpl::long_<2> const&\n              ) const\n    {\n      eval2_3(a0, a1\n             , boost::proto::value(boost::proto::child_c<2>(a0)));\n    }\n\n    /// INTERNAL ONLY: 2o 3i\n    BOOST_FORCEINLINE\n    void eval2_3 ( A0& a0, A1& a1\n                 , nt2::policy<ext::alphabeta_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> wa, wb;\n      NT2_AS_TERMINAL_INOUT(o_semantic, a\n                           , boost::proto::child_c<0>(a0), wa);\n      NT2_AS_TERMINAL_INOUT(o_semantic, b\n                           , boost::proto::child_c<1>(a0), wb);\n      NT2_AS_TERMINAL_OUT  (c_semantic, alpha\n                           , boost::proto::child_c<0>(a1));\n      NT2_AS_TERMINAL_OUT  (o_semantic, beta\n                           , boost::proto::child_c<1>(a1));\n      size_t n = height(a);\n      beta.resize(nt2::of_size(n,1));\n      alpha.resize(nt2::of_size(n,1)); ;\n      NT2_LAPACK_VERIFY(nt2::ggev_w( boost::proto::value(a)\n                                   , boost::proto::value(b)\n                                   , boost::proto::value(alpha)\n                                   , boost::proto::value(beta)));\n      assign_swap(boost::proto::child_c<0>(a1), alpha);\n      assign_swap(boost::proto::child_c<1>(a1), beta);\n\n    }\n\n    /// INTERNAL ONLY: 2o 3i\n    BOOST_FORCEINLINE\n    void eval2_3 ( A0& a0, A1& a1\n                 , nt2::policy<ext::vector_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> wa, wb;\n      NT2_AS_TERMINAL_INOUT(o_semantic, a\n                           , boost::proto::child_c<0>(a0), wa);\n      NT2_AS_TERMINAL_INOUT(o_semantic, b\n                           , boost::proto::child_c<1>(a0), wb);\n      NT2_AS_TERMINAL_OUT  (c_semantic, w\n                           , boost::proto::child_c<1>(a1));\n      NT2_AS_TERMINAL_OUT  (c_semantic, vr\n                           , boost::proto::child_c<0>(a1));\n      size_t n = height(a);\n      w.resize(nt2::of_size(n,1));\n      vr.resize(nt2::of_size(n,n));\n      container::table <type_t>  beta(nt2::of_size(n,1));\n      NT2_LAPACK_VERIFY(nt2::ggev_wvr( boost::proto::value(a)\n                                     , boost::proto::value(b)\n                                     , boost::proto::value(w)\n                                     , boost::proto::value(beta)\n                                     , boost::proto::value(vr)));\n      assign_swap(boost::proto::child_c<1>(a1), w);\n      boost::proto::child_c<1>(a1) /= beta;\n      assign_swap(boost::proto::child_c<0>(a1), vr);\n    }\n\n    /// INTERNAL ONLY: 2o 3i\n    BOOST_FORCEINLINE\n    void eval2_3 ( A0& a0, A1& a1\n                 , nt2::policy<ext::matrix_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> wa, wb;\n      NT2_AS_TERMINAL_INOUT(o_semantic, a\n                           , boost::proto::child_c<0>(a0), wa);\n      NT2_AS_TERMINAL_INOUT(o_semantic, b\n                           , boost::proto::child_c<1>(a0), wb);\n      NT2_AS_TERMINAL_OUT  (c_semantic, vr\n                           , boost::proto::child_c<0>(a1));\n      size_t n = height(a);\n      container::table <type_t> beta(nt2::of_size(n,1));\n      container::table <ctype_t> alpha(nt2::of_size(n,1));\n      vr.resize(nt2::of_size(n,n));\n      NT2_LAPACK_VERIFY(nt2::ggev_wvr( boost::proto::value(a)\n                                     , boost::proto::value(b)\n                                     , boost::proto::value(alpha)\n                                     , boost::proto::value(beta)\n                                     , boost::proto::value(vr)));\n      boost::proto::child_c<1>(a1) = from_diag(alpha/beta);\n      assign_swap(boost::proto::child_c<0>(a1), vr);\n      //from_diag doesnt support aliasing currently\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [alpha, beta] = GENEIG(A, B, alphabeta_, matrix_/vectors)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<4> const&\n              , boost::mpl::long_<2> const&\n              ) const\n    {\n      eval2_4(a0, a1\n             , boost::proto::value(boost::proto::child_c<3>(a0)));\n    }\n\n    /// INTERNAL ONLY: 2o 4i\n    BOOST_FORCEINLINE\n    void eval2_4 ( A0& a0, A1& a1\n                 , nt2::policy<ext::vector_> const &\n                 ) const\n    {\n      eval2_3(a0, a1\n             , nt2::policy<ext::alphabeta_>());\n    }\n\n    /// INTERNAL ONLY: 2o 4i\n    BOOST_FORCEINLINE\n    void eval2_4 ( A0& a0, A1& a1\n                 , nt2::policy<ext::matrix_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> wa, wb;\n      NT2_AS_TERMINAL_INOUT(o_semantic, a\n                           , boost::proto::child_c<0>(a0), wa);\n      NT2_AS_TERMINAL_INOUT(o_semantic, b\n                           , boost::proto::child_c<1>(a0), wb);\n      size_t n = height(a);\n      container::table <type_t> beta(nt2::of_size(n,1));\n      container::table <ctype_t> alpha(nt2::of_size(n,1));\n      NT2_LAPACK_VERIFY(nt2::ggev_w( boost::proto::value(a)\n                                   , boost::proto::value(b)\n                                   , boost::proto::value(alpha)\n                                   , boost::proto::value(beta)\n                                   ));\n      boost::proto::child_c<0>(a1) = from_diag(alpha);\n      boost::proto::child_c<1>(a1) = from_diag(beta);\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [vr, w, vl] = GENEIG(A, B)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<2> const&\n              , boost::mpl::long_<3> const&\n              ) const\n    {\n      eval3_3(a0, a1, nt2::policy<ext::matrix_>());\n    }\n\n  //==========================================================================\n    /// INTERNAL ONLY - [vr, alpha, beta] = GENEIG(A, B, alphabeta_) or\n    ///                 [vr, w, vl]       = GENEIG(A, B, matrix_/vectors)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<3> const&\n              , boost::mpl::long_<3> const&\n              ) const\n    {\n      eval3_3(a0, a1, boost::proto::value(boost::proto::child_c<2>(a0)));\n    }\n\n    /// INTERNAL ONLY: 3o 3i\n    BOOST_FORCEINLINE\n    void eval3_3 ( A0& a0, A1& a1\n                 , nt2::policy<ext::alphabeta_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> wa, wb;\n      NT2_AS_TERMINAL_INOUT(o_semantic, a\n                           , boost::proto::child_c<0>(a0), wa);\n      NT2_AS_TERMINAL_INOUT(o_semantic, b\n                           , boost::proto::child_c<1>(a0), wb);\n      NT2_AS_TERMINAL_OUT  (c_semantic, vr\n                           , boost::proto::child_c<0>(a1));\n      size_t n = height(a);\n      nt2::container::table <type_t> beta(nt2::of_size(n,1));\n      nt2::container::table <ctype_t> alpha(nt2::of_size(n,1));\n      vr.resize(nt2::of_size(n,n));\n      NT2_LAPACK_VERIFY(nt2::ggev_wvr( boost::proto::value(a)\n                                     , boost::proto::value(b)\n                                     , boost::proto::value(alpha)\n                                     , boost::proto::value(beta)\n                                     , boost::proto::value(vr)\n                                     ));\n      boost::proto::child_c<1>(a1) = nt2::from_diag(alpha);\n      boost::proto::child_c<2>(a1) = nt2::from_diag(beta);\n      assign_swap(boost::proto::child_c<0>(a1), vr);\n    }\n\n    /// INTERNAL ONLY: 3o 3i\n    BOOST_FORCEINLINE\n    void eval3_3 ( A0& a0, A1& a1\n                 , nt2::policy<ext::vector_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> wa, wb;\n      NT2_AS_TERMINAL_INOUT(o_semantic, a\n                           , boost::proto::child_c<0>(a0), wa);\n      NT2_AS_TERMINAL_INOUT(o_semantic, b\n                           , boost::proto::child_c<1>(a0), wb);\n      NT2_AS_TERMINAL_OUT  (c_semantic, alpha\n                           , boost::proto::child_c<1>(a1));\n      NT2_AS_TERMINAL_OUT  (c_semantic, vr\n                           , boost::proto::child_c<0>(a1));\n      NT2_AS_TERMINAL_OUT  (c_semantic, vl\n                           , boost::proto::child_c<2>(a1));\n      size_t n = height(a);\n      alpha.resize(nt2::of_size(n,1));\n      vr.resize(nt2::of_size(n,n));\n      container::table <type_t>  beta(nt2::of_size(n,1));\n      NT2_LAPACK_VERIFY(nt2::ggev_wvrvl( boost::proto::value(a)\n                                       , boost::proto::value(b)\n                                       , boost::proto::value(alpha)\n                                       , boost::proto::value(beta)\n                                       , boost::proto::value(vr)\n                                       , boost::proto::value(vl)\n                                       ));\n      assign_swap(boost::proto::child_c<1>(a1), alpha);\n      boost::proto::child_c<1>(a1) /= beta;\n      assign_swap(boost::proto::child_c<0>(a1), vr);\n      assign_swap(boost::proto::child_c<2>(a1), vl);\n    }\n\n    /// INTERNAL ONLY: 3o 3i\n    BOOST_FORCEINLINE\n    void eval3_3 ( A0& a0, A1& a1\n                 , nt2::policy<ext::matrix_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> wa, wb;\n      NT2_AS_TERMINAL_INOUT(o_semantic, a\n                           , boost::proto::child_c<0>(a0), wa);\n      NT2_AS_TERMINAL_INOUT(o_semantic, b\n                           , boost::proto::child_c<1>(a0), wb);\n      NT2_AS_TERMINAL_OUT  (c_semantic, vr\n                           , boost::proto::child_c<0>(a1));\n      NT2_AS_TERMINAL_OUT  (c_semantic, vl\n                           , boost::proto::child_c<2>(a1));\n      size_t n = height(a);\n      container::table <type_t> beta(nt2::of_size(n,1));\n      container::table <ctype_t> alpha(nt2::of_size(n,1));\n      vr.resize(nt2::of_size(n,n));\n      vl.resize(nt2::of_size(n,n));\n      NT2_LAPACK_VERIFY(nt2::ggev_wvrvl( boost::proto::value(a)\n                                       , boost::proto::value(b)\n                                       , boost::proto::value(alpha)\n                                       , boost::proto::value(beta)\n                                       , boost::proto::value(vr)\n                                       , boost::proto::value(vl)\n                                       ));\n      boost::proto::child_c<1>(a1) = from_diag(alpha/beta);\n      assign_swap(boost::proto::child_c<0>(a1), vr);\n      assign_swap(boost::proto::child_c<2>(a1), vl);\n      //from_diag doesnt support aliasing currently\n    }\n\n   //==========================================================================\n    /// INTERNAL ONLY - [vr, alpha, beta, vl] = GENEIG(A, B) or\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<2> const&\n              , boost::mpl::long_<4> const&\n              ) const\n    {\n      eval4_3(a0, a1\n             , nt2::policy<ext::matrix_>());\n    }\n    //==========================================================================\n    /// INTERNAL ONLY - [vr, alpha, beta] = GENEIG(A, B, alphabeta_, matrix_/vectors) or\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<4> const&\n              , boost::mpl::long_<3> const&\n              ) const\n    {\n      eval3_4(a0, a1\n             , boost::proto::value(boost::proto::child_c<2>(a0))\n             , boost::proto::value(boost::proto::child_c<3>(a0)));\n    }\n\n\n   /// INTERNAL ONLY: 3o 4i\n    BOOST_FORCEINLINE\n    void eval3_4 ( A0& a0, A1& a1\n                 , nt2::policy<ext::alphabeta_> const &\n                 , nt2::policy<ext::matrix_>  const &\n                 ) const\n    {\n      eval3_3(a0, a1, nt2::policy<ext::alphabeta_>());\n    }\n\n   /// INTERNAL ONLY: 3o 4i\n    BOOST_FORCEINLINE\n    void eval3_4 ( A0& a0, A1& a1\n                 , nt2::policy<ext::alphabeta_> const &\n                 , nt2::policy<ext::vector_>  const &\n                 ) const\n    {\n      nt2::container::table<type_t> wa, wb;\n      NT2_AS_TERMINAL_INOUT(o_semantic, a\n                           , boost::proto::child_c<0>(a0), wa);\n      NT2_AS_TERMINAL_INOUT(o_semantic, b\n                           , boost::proto::child_c<1>(a0), wb);\n      NT2_AS_TERMINAL_OUT  (c_semantic, vr\n                           , boost::proto::child_c<0>(a1));\n      NT2_AS_TERMINAL_OUT  (c_semantic, alpha\n                           , boost::proto::child_c<1>(a1));\n      NT2_AS_TERMINAL_OUT  (o_semantic, beta\n                           , boost::proto::child_c<2>(a1));\n      size_t n = height(a);\n      beta.resize(nt2::of_size(n,1));\n      alpha.resize(nt2::of_size(n,1));\n      vr.resize(nt2::of_size(n,n));\n      NT2_LAPACK_VERIFY(nt2::ggev_wvr( boost::proto::value(a)\n                                     , boost::proto::value(b)\n                                     , boost::proto::value(alpha)\n                                     , boost::proto::value(beta)\n                                     , boost::proto::value(vr)\n                                     ));\n      assign_swap(boost::proto::child_c<1>(a1), alpha);\n      assign_swap(boost::proto::child_c<2>(a1), beta);\n      assign_swap(boost::proto::child_c<0>(a1), vr);\n\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [vr, alpha, beta, vl] = GENEIG(A, B, matrix_/vectors) or\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<3> const&\n              , boost::mpl::long_<4> const&\n              ) const\n    {\n      eval4_3(a0, a1\n             , boost::proto::value(boost::proto::child_c<2>(a0)));\n    }\n\n    /// INTERNAL ONLY: 4o 3i\n    BOOST_FORCEINLINE\n    void eval4_3 ( A0& a0, A1& a1\n                 , nt2::policy<ext::vector_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> wa, wb;\n      NT2_AS_TERMINAL_INOUT(o_semantic, a\n                           , boost::proto::child_c<0>(a0), wa);\n      NT2_AS_TERMINAL_INOUT(o_semantic, b\n                           , boost::proto::child_c<1>(a0), wb);\n      NT2_AS_TERMINAL_OUT  (c_semantic, alpha\n                           , boost::proto::child_c<1>(a1));\n      NT2_AS_TERMINAL_OUT  (o_semantic, beta\n                           , boost::proto::child_c<2>(a1));\n      NT2_AS_TERMINAL_OUT  (c_semantic, vr\n                           , boost::proto::child_c<0>(a1));\n      NT2_AS_TERMINAL_OUT  (c_semantic, vl\n                           , boost::proto::child_c<3>(a1));\n      size_t n = height(a);\n      alpha.resize(nt2::of_size(n,1));\n      beta.resize(nt2::of_size(n,1));\n      vr.resize(nt2::of_size(n,n));\n      vl.resize(nt2::of_size(n,n));\n      NT2_LAPACK_VERIFY(nt2::ggev_wvrvl( boost::proto::value(a)\n                                       , boost::proto::value(b)\n                                       , boost::proto::value(alpha)\n                                       , boost::proto::value(beta)\n                                       , boost::proto::value(vr)\n                                       , boost::proto::value(vl)\n                                       ));\n      assign_swap(boost::proto::child_c<0>(a1), vr);\n      assign_swap(boost::proto::child_c<3>(a1), vl);\n      assign_swap(boost::proto::child_c<1>(a1), alpha);\n      assign_swap(boost::proto::child_c<2>(a1), beta);\n    }\n\n     /// INTERNAL ONLY: 4o 3i\n    BOOST_FORCEINLINE\n    void eval4_3 ( A0& a0, A1& a1\n                 , nt2::policy<ext::matrix_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> wa, wb;\n      NT2_AS_TERMINAL_INOUT(o_semantic, a\n                           , boost::proto::child_c<0>(a0), wa);\n      NT2_AS_TERMINAL_INOUT(o_semantic, b\n                           , boost::proto::child_c<1>(a0), wb);\n      NT2_AS_TERMINAL_OUT  (c_semantic, vr\n                           , boost::proto::child_c<0>(a1));\n      NT2_AS_TERMINAL_OUT  (c_semantic, vl\n                           , boost::proto::child_c<3>(a1));\n      size_t n = height(a);\n      nt2::container::table <type_t> beta(nt2::of_size(n,1));\n      nt2::container::table <ctype_t> alpha(nt2::of_size(n,1));\n      vr.resize(nt2::of_size(n,n));\n      vl.resize(nt2::of_size(n,n));\n      NT2_LAPACK_VERIFY(nt2::ggev_wvrvl( boost::proto::value(a)\n                                       , boost::proto::value(b)\n                                       , boost::proto::value(alpha)\n                                       , boost::proto::value(beta)\n                                       , boost::proto::value(vr)\n                                       , boost::proto::value(vl)\n                                       ));\n      assign_swap(boost::proto::child_c<0>(a1), vr);\n      assign_swap(boost::proto::child_c<3>(a1), vl);\n      boost::proto::child_c<1>(a1) = from_diag(alpha);\n      boost::proto::child_c<2>(a1) = from_diag(beta);\n      //from_diag doesnt support aliasing currently\n    }\n\n     /// INTERNAL ONLY: 4o 3i\n    template < class T > BOOST_FORCEINLINE\n    void eval4_3 ( A0& a0, A1& a1\n                 , T const &\n                 ) const\n    {\n      eval4_3(a0, a1\n             , boost::proto::value(boost::proto::child_c<2>(a0)));\n    }\n\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "8151846f3978d641e6ca16b393361f23af9d8d9c", "size": 24720, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/functions/factorizations/geneig.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/factorizations/geneig.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/factorizations/geneig.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.1298701299, "max_line_length": 100, "alphanum_fraction": 0.4711165049, "num_tokens": 6532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.25237798651115223}}
{"text": "// boost\\math\\distributions\\geometric.hpp\r\n\r\n// Copyright John Maddock 2010.\r\n// Copyright Paul A. Bristow 2010.\r\n\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// geometric distribution is a discrete probability distribution.\r\n// It expresses the probability distribution of the number (k) of\r\n// events, occurrences, failures or arrivals before the first success.\r\n// supported on the set {0, 1, 2, 3...}\r\n\r\n// Note that the set includes zero (unlike some definitions that start at one).\r\n\r\n// The random variate k is the number of events, occurrences or arrivals.\r\n// k argument may be integral, signed, or unsigned, or floating point.\r\n// If necessary, it has already been promoted from an integral type.\r\n\r\n// Note that the geometric distribution\r\n// (like others including the binomial, geometric & Bernoulli)\r\n// is strictly defined as a discrete function:\r\n// only integral values of k are envisaged.\r\n// However because the method of calculation uses a continuous gamma function,\r\n// it is convenient to treat it as if a continuous function,\r\n// and permit non-integral values of k.\r\n// To enforce the strict mathematical model, users should use floor or ceil functions\r\n// on k outside this function to ensure that k is integral.\r\n\r\n// See http://en.wikipedia.org/wiki/geometric_distribution\r\n// http://documents.wolfram.com/v5/Add-onsLinks/StandardPackages/Statistics/DiscreteDistributions.html\r\n// http://mathworld.wolfram.com/GeometricDistribution.html\r\n\r\n#ifndef BOOST_MATH_SPECIAL_GEOMETRIC_HPP\r\n#define BOOST_MATH_SPECIAL_GEOMETRIC_HPP\r\n\r\n#include <boost/math/distributions/fwd.hpp>\r\n#include <boost/math/special_functions/beta.hpp> // for ibeta(a, b, x) == Ix(a, b).\r\n#include <boost/math/distributions/complement.hpp> // complement.\r\n#include <boost/math/distributions/detail/common_error_handling.hpp> // error checks domain_error & logic_error.\r\n#include <boost/math/special_functions/fpclassify.hpp> // isnan.\r\n#include <boost/math/tools/roots.hpp> // for root finding.\r\n#include <boost/math/distributions/detail/inv_discrete_quantile.hpp>\r\n\r\n#include <boost/type_traits/is_floating_point.hpp>\r\n#include <boost/type_traits/is_integral.hpp>\r\n#include <boost/type_traits/is_same.hpp>\r\n#include <boost/mpl/if.hpp>\r\n\r\n#include <limits> // using std::numeric_limits;\r\n#include <utility>\r\n\r\n#if defined (BOOST_MSVC)\r\n#  pragma warning(push)\r\n// This believed not now necessary, so commented out.\r\n//#  pragma warning(disable: 4702) // unreachable code.\r\n// in domain_error_imp in error_handling.\r\n#endif\r\n\r\nnamespace boost\r\n{\r\n  namespace math\r\n  {\r\n    namespace geometric_detail\r\n    {\r\n      // Common error checking routines for geometric distribution function:\r\n      template <class RealType, class Policy>\r\n      inline bool check_success_fraction(const char* function, const RealType& p, RealType* result, const Policy& pol)\r\n      {\r\n        if( !(boost::math::isfinite)(p) || (p < 0) || (p > 1) )\r\n        {\r\n          *result = policies::raise_domain_error<RealType>(\r\n            function,\r\n            \"Success fraction argument is %1%, but must be >= 0 and <= 1 !\", p, pol);\r\n          return false;\r\n        }\r\n        return true;\r\n      }\r\n\r\n      template <class RealType, class Policy>\r\n      inline bool check_dist(const char* function, const RealType& p, RealType* result, const Policy& pol)\r\n      {\r\n        return check_success_fraction(function, p, result, pol);\r\n      }\r\n\r\n      template <class RealType, class Policy>\r\n      inline bool check_dist_and_k(const char* function,  const RealType& p, RealType k, RealType* result, const Policy& pol)\r\n      {\r\n        if(check_dist(function, p, result, pol) == false)\r\n        {\r\n          return false;\r\n        }\r\n        if( !(boost::math::isfinite)(k) || (k < 0) )\r\n        { // Check k failures.\r\n          *result = policies::raise_domain_error<RealType>(\r\n            function,\r\n            \"Number of failures argument is %1%, but must be >= 0 !\", k, pol);\r\n          return false;\r\n        }\r\n        return true;\r\n      } // Check_dist_and_k\r\n\r\n      template <class RealType, class Policy>\r\n      inline bool check_dist_and_prob(const char* function, RealType p, RealType prob, RealType* result, const Policy& pol)\r\n      {\r\n        if((check_dist(function, p, result, pol) && detail::check_probability(function, prob, result, pol)) == false)\r\n        {\r\n          return false;\r\n        }\r\n        return true;\r\n      } // check_dist_and_prob\r\n    } //  namespace geometric_detail\r\n\r\n    template <class RealType = double, class Policy = policies::policy<> >\r\n    class geometric_distribution\r\n    {\r\n    public:\r\n      typedef RealType value_type;\r\n      typedef Policy policy_type;\r\n\r\n      geometric_distribution(RealType p) : m_p(p)\r\n      { // Constructor stores success_fraction p.\r\n        RealType result;\r\n        geometric_detail::check_dist(\r\n          \"geometric_distribution<%1%>::geometric_distribution\",\r\n          m_p, // Check success_fraction 0 <= p <= 1.\r\n          &result, Policy());\r\n      } // geometric_distribution constructor.\r\n\r\n      // Private data getter class member functions.\r\n      RealType success_fraction() const\r\n      { // Probability of success as fraction in range 0 to 1.\r\n        return m_p;\r\n      }\r\n      RealType successes() const\r\n      { // Total number of successes r = 1 (for compatibility with negative binomial?).\r\n        return 1;\r\n      }\r\n\r\n      // Parameter estimation.\r\n      // (These are copies of negative_binomial distribution with successes = 1).\r\n      static RealType find_lower_bound_on_p(\r\n        RealType trials,\r\n        RealType alpha) // alpha 0.05 equivalent to 95% for one-sided test.\r\n      {\r\n        static const char* function = \"boost::math::geometric<%1%>::find_lower_bound_on_p\";\r\n        RealType result = 0;  // of error checks.\r\n        RealType successes = 1;\r\n        RealType failures = trials - successes;\r\n        if(false == detail::check_probability(function, alpha, &result, Policy())\r\n          && geometric_detail::check_dist_and_k(\r\n          function, RealType(0), failures, &result, Policy()))\r\n        {\r\n          return result;\r\n        }\r\n        // Use complement ibeta_inv function for lower bound.\r\n        // This is adapted from the corresponding binomial formula\r\n        // here: http://www.itl.nist.gov/div898/handbook/prc/section2/prc241.htm\r\n        // This is a Clopper-Pearson interval, and may be overly conservative,\r\n        // see also \"A Simple Improved Inferential Method for Some\r\n        // Discrete Distributions\" Yong CAI and K. KRISHNAMOORTHY\r\n        // http://www.ucs.louisiana.edu/~kxk4695/Discrete_new.pdf\r\n        //\r\n        return ibeta_inv(successes, failures + 1, alpha, static_cast<RealType*>(0), Policy());\r\n      } // find_lower_bound_on_p\r\n\r\n      static RealType find_upper_bound_on_p(\r\n        RealType trials,\r\n        RealType alpha) // alpha 0.05 equivalent to 95% for one-sided test.\r\n      {\r\n        static const char* function = \"boost::math::geometric<%1%>::find_upper_bound_on_p\";\r\n        RealType result = 0;  // of error checks.\r\n        RealType successes = 1;\r\n        RealType failures = trials - successes;\r\n        if(false == geometric_detail::check_dist_and_k(\r\n          function, RealType(0), failures, &result, Policy())\r\n          && detail::check_probability(function, alpha, &result, Policy()))\r\n        {\r\n          return result;\r\n        }\r\n        if(failures == 0)\r\n        {\r\n           return 1;\r\n        }// Use complement ibetac_inv function for upper bound.\r\n        // Note adjusted failures value: *not* failures+1 as usual.\r\n        // This is adapted from the corresponding binomial formula\r\n        // here: http://www.itl.nist.gov/div898/handbook/prc/section2/prc241.htm\r\n        // This is a Clopper-Pearson interval, and may be overly conservative,\r\n        // see also \"A Simple Improved Inferential Method for Some\r\n        // Discrete Distributions\" Yong CAI and K. Krishnamoorthy\r\n        // http://www.ucs.louisiana.edu/~kxk4695/Discrete_new.pdf\r\n        //\r\n        return ibetac_inv(successes, failures, alpha, static_cast<RealType*>(0), Policy());\r\n      } // find_upper_bound_on_p\r\n\r\n      // Estimate number of trials :\r\n      // \"How many trials do I need to be P% sure of seeing k or fewer failures?\"\r\n\r\n      static RealType find_minimum_number_of_trials(\r\n        RealType k,     // number of failures (k >= 0).\r\n        RealType p,     // success fraction 0 <= p <= 1.\r\n        RealType alpha) // risk level threshold 0 <= alpha <= 1.\r\n      {\r\n        static const char* function = \"boost::math::geometric<%1%>::find_minimum_number_of_trials\";\r\n        // Error checks:\r\n        RealType result = 0;\r\n        if(false == geometric_detail::check_dist_and_k(\r\n          function, p, k, &result, Policy())\r\n          && detail::check_probability(function, alpha, &result, Policy()))\r\n        {\r\n          return result;\r\n        }\r\n        result = ibeta_inva(k + 1, p, alpha, Policy());  // returns n - k\r\n        return result + k;\r\n      } // RealType find_number_of_failures\r\n\r\n      static RealType find_maximum_number_of_trials(\r\n        RealType k,     // number of failures (k >= 0).\r\n        RealType p,     // success fraction 0 <= p <= 1.\r\n        RealType alpha) // risk level threshold 0 <= alpha <= 1.\r\n      {\r\n        static const char* function = \"boost::math::geometric<%1%>::find_maximum_number_of_trials\";\r\n        // Error checks:\r\n        RealType result = 0;\r\n        if(false == geometric_detail::check_dist_and_k(\r\n          function, p, k, &result, Policy())\r\n          &&  detail::check_probability(function, alpha, &result, Policy()))\r\n        { \r\n          return result;\r\n        }\r\n        result = ibetac_inva(k + 1, p, alpha, Policy());  // returns n - k\r\n        return result + k;\r\n      } // RealType find_number_of_trials complemented\r\n\r\n    private:\r\n      //RealType m_r; // successes fixed at unity.\r\n      RealType m_p; // success_fraction\r\n    }; // template <class RealType, class Policy> class geometric_distribution\r\n\r\n    typedef geometric_distribution<double> geometric; // Reserved name of type double.\r\n\r\n    template <class RealType, class Policy>\r\n    inline const std::pair<RealType, RealType> range(const geometric_distribution<RealType, Policy>& /* dist */)\r\n    { // Range of permissible values for random variable k.\r\n       using boost::math::tools::max_value;\r\n       return std::pair<RealType, RealType>(static_cast<RealType>(0), max_value<RealType>()); // max_integer?\r\n    }\r\n\r\n    template <class RealType, class Policy>\r\n    inline const std::pair<RealType, RealType> support(const geometric_distribution<RealType, Policy>& /* dist */)\r\n    { // Range of supported values for random variable k.\r\n       // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.\r\n       using boost::math::tools::max_value;\r\n       return std::pair<RealType, RealType>(static_cast<RealType>(0),  max_value<RealType>()); // max_integer?\r\n    }\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType mean(const geometric_distribution<RealType, Policy>& dist)\r\n    { // Mean of geometric distribution = (1-p)/p.\r\n      return (1 - dist.success_fraction() ) / dist.success_fraction();\r\n    } // mean\r\n\r\n    // median implemented via quantile(half) in derived accessors.\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType mode(const geometric_distribution<RealType, Policy>&)\r\n    { // Mode of geometric distribution = zero.\r\n      BOOST_MATH_STD_USING // ADL of std functions.\r\n      return 0;\r\n    } // mode\r\n    \r\n    template <class RealType, class Policy>\r\n    inline RealType variance(const geometric_distribution<RealType, Policy>& dist)\r\n    { // Variance of Binomial distribution = (1-p) / p^2.\r\n      return  (1 - dist.success_fraction())\r\n        / (dist.success_fraction() * dist.success_fraction());\r\n    } // variance\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType skewness(const geometric_distribution<RealType, Policy>& dist)\r\n    { // skewness of geometric distribution = 2-p / (sqrt(r(1-p))\r\n      BOOST_MATH_STD_USING // ADL of std functions.\r\n      RealType p = dist.success_fraction();\r\n      return (2 - p) / sqrt(1 - p);\r\n    } // skewness\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType kurtosis(const geometric_distribution<RealType, Policy>& dist)\r\n    { // kurtosis of geometric distribution\r\n      // http://en.wikipedia.org/wiki/geometric is kurtosis_excess so add 3\r\n      RealType p = dist.success_fraction();\r\n      return 3 + (p*p - 6*p + 6) / (1 - p);\r\n    } // kurtosis\r\n\r\n     template <class RealType, class Policy>\r\n    inline RealType kurtosis_excess(const geometric_distribution<RealType, Policy>& dist)\r\n    { // kurtosis excess of geometric distribution\r\n      // http://mathworld.wolfram.com/Kurtosis.html table of kurtosis_excess\r\n      RealType p = dist.success_fraction();\r\n      return (p*p - 6*p + 6) / (1 - p);\r\n    } // kurtosis_excess\r\n\r\n    // RealType standard_deviation(const geometric_distribution<RealType, Policy>& dist)\r\n    // standard_deviation provided by derived accessors.\r\n    // RealType hazard(const geometric_distribution<RealType, Policy>& dist)\r\n    // hazard of geometric distribution provided by derived accessors.\r\n    // RealType chf(const geometric_distribution<RealType, Policy>& dist)\r\n    // chf of geometric distribution provided by derived accessors.\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType pdf(const geometric_distribution<RealType, Policy>& dist, const RealType& k)\r\n    { // Probability Density/Mass Function.\r\n      BOOST_FPU_EXCEPTION_GUARD\r\n      BOOST_MATH_STD_USING  // For ADL of math functions.\r\n      static const char* function = \"boost::math::pdf(const geometric_distribution<%1%>&, %1%)\";\r\n\r\n      RealType p = dist.success_fraction();\r\n      RealType result = 0;\r\n      if(false == geometric_detail::check_dist_and_k(\r\n        function,\r\n        p,\r\n        k,\r\n        &result, Policy()))\r\n      {\r\n        return result;\r\n      }\r\n      if (k == 0)\r\n      {\r\n        return p; // success_fraction\r\n      }\r\n      RealType q = 1 - p;  // Inaccurate for small p?\r\n      // So try to avoid inaccuracy for large or small p.\r\n      // but has little effect > last significant bit.\r\n      //cout << \"p *  pow(q, k) \" << result << endl; // seems best whatever p\r\n      //cout << \"exp(p * k * log1p(-p)) \" << p * exp(k * log1p(-p)) << endl;\r\n      //if (p < 0.5)\r\n      //{\r\n      //  result = p *  pow(q, k);\r\n      //}\r\n      //else\r\n      //{\r\n      //  result = p * exp(k * log1p(-p));\r\n      //}\r\n      result = p * pow(q, k);\r\n      return result;\r\n    } // geometric_pdf\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType cdf(const geometric_distribution<RealType, Policy>& dist, const RealType& k)\r\n    { // Cumulative Distribution Function of geometric.\r\n      static const char* function = \"boost::math::cdf(const geometric_distribution<%1%>&, %1%)\";\r\n\r\n      // k argument may be integral, signed, or unsigned, or floating point.\r\n      // If necessary, it has already been promoted from an integral type.\r\n      RealType p = dist.success_fraction();\r\n      // Error check:\r\n      RealType result = 0;\r\n      if(false == geometric_detail::check_dist_and_k(\r\n        function,\r\n        p,\r\n        k,\r\n        &result, Policy()))\r\n      {\r\n        return result;\r\n      }\r\n      if(k == 0)\r\n      {\r\n        return p; // success_fraction\r\n      }\r\n      //RealType q = 1 - p;  // Bad for small p\r\n      //RealType probability = 1 - std::pow(q, k+1);\r\n\r\n      RealType z = boost::math::log1p(-p, Policy()) * (k + 1);\r\n      RealType probability = -boost::math::expm1(z, Policy());\r\n\r\n      return probability;\r\n    } // cdf Cumulative Distribution Function geometric.\r\n\r\n      template <class RealType, class Policy>\r\n      inline RealType cdf(const complemented2_type<geometric_distribution<RealType, Policy>, RealType>& c)\r\n      { // Complemented Cumulative Distribution Function geometric.\r\n      BOOST_MATH_STD_USING\r\n      static const char* function = \"boost::math::cdf(const geometric_distribution<%1%>&, %1%)\";\r\n      // k argument may be integral, signed, or unsigned, or floating point.\r\n      // If necessary, it has already been promoted from an integral type.\r\n      RealType const& k = c.param;\r\n      geometric_distribution<RealType, Policy> const& dist = c.dist;\r\n      RealType p = dist.success_fraction();\r\n      // Error check:\r\n      RealType result = 0;\r\n      if(false == geometric_detail::check_dist_and_k(\r\n        function,\r\n        p,\r\n        k,\r\n        &result, Policy()))\r\n      {\r\n        return result;\r\n      }\r\n      RealType z = boost::math::log1p(-p, Policy()) * (k+1);\r\n      RealType probability = exp(z);\r\n      return probability;\r\n    } // cdf Complemented Cumulative Distribution Function geometric.\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType quantile(const geometric_distribution<RealType, Policy>& dist, const RealType& x)\r\n    { // Quantile, percentile/100 or Percent Point geometric function.\r\n      // Return the number of expected failures k for a given probability p.\r\n\r\n      // Inverse cumulative Distribution Function or Quantile (percentile / 100) of geometric Probability.\r\n      // k argument may be integral, signed, or unsigned, or floating point.\r\n\r\n      static const char* function = \"boost::math::quantile(const geometric_distribution<%1%>&, %1%)\";\r\n      BOOST_MATH_STD_USING // ADL of std functions.\r\n\r\n      RealType success_fraction = dist.success_fraction();\r\n      // Check dist and x.\r\n      RealType result = 0;\r\n      if(false == geometric_detail::check_dist_and_prob\r\n        (function, success_fraction, x, &result, Policy()))\r\n      {\r\n        return result;\r\n      }\r\n\r\n      // Special cases.\r\n      if (x == 1)\r\n      {  // Would need +infinity failures for total confidence.\r\n        result = policies::raise_overflow_error<RealType>(\r\n            function,\r\n            \"Probability argument is 1, which implies infinite failures !\", Policy());\r\n        return result;\r\n       // usually means return +std::numeric_limits<RealType>::infinity();\r\n       // unless #define BOOST_MATH_THROW_ON_OVERFLOW_ERROR\r\n      }\r\n      if (x == 0)\r\n      { // No failures are expected if P = 0.\r\n        return 0; // Total trials will be just dist.successes.\r\n      }\r\n      // if (P <= pow(dist.success_fraction(), 1))\r\n      if (x <= success_fraction)\r\n      { // p <= pdf(dist, 0) == cdf(dist, 0)\r\n        return 0;\r\n      }\r\n      if (x == 1)\r\n      {\r\n        return 0;\r\n      }\r\n   \r\n      // log(1-x) /log(1-success_fraction) -1; but use log1p in case success_fraction is small\r\n      result = boost::math::log1p(-x, Policy()) / boost::math::log1p(-success_fraction, Policy()) - 1;\r\n      // Subtract a few epsilons here too?\r\n      // to make sure it doesn't slip over, so ceil would be one too many.\r\n      return result;\r\n    } // RealType quantile(const geometric_distribution dist, p)\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType quantile(const complemented2_type<geometric_distribution<RealType, Policy>, RealType>& c)\r\n    {  // Quantile or Percent Point Binomial function.\r\n       // Return the number of expected failures k for a given\r\n       // complement of the probability Q = 1 - P.\r\n       static const char* function = \"boost::math::quantile(const geometric_distribution<%1%>&, %1%)\";\r\n       BOOST_MATH_STD_USING\r\n       // Error checks:\r\n       RealType x = c.param;\r\n       const geometric_distribution<RealType, Policy>& dist = c.dist;\r\n       RealType success_fraction = dist.success_fraction();\r\n       RealType result = 0;\r\n       if(false == geometric_detail::check_dist_and_prob(\r\n          function,\r\n          success_fraction,\r\n          x,\r\n          &result, Policy()))\r\n       {\r\n          return result;\r\n       }\r\n\r\n       // Special cases:\r\n       if(x == 1)\r\n       {  // There may actually be no answer to this question,\r\n          // since the probability of zero failures may be non-zero,\r\n          return 0; // but zero is the best we can do:\r\n       }\r\n       if (-x <= boost::math::powm1(dist.success_fraction(), dist.successes(), Policy()))\r\n       {  // q <= cdf(complement(dist, 0)) == pdf(dist, 0)\r\n          return 0; //\r\n       }\r\n       if(x == 0)\r\n       {  // Probability 1 - Q  == 1 so infinite failures to achieve certainty.\r\n          // Would need +infinity failures for total confidence.\r\n          result = policies::raise_overflow_error<RealType>(\r\n             function,\r\n             \"Probability argument complement is 0, which implies infinite failures !\", Policy());\r\n          return result;\r\n          // usually means return +std::numeric_limits<RealType>::infinity();\r\n          // unless #define BOOST_MATH_THROW_ON_OVERFLOW_ERROR\r\n       }\r\n       // log(x) /log(1-success_fraction) -1; but use log1p in case success_fraction is small\r\n       result = log(x) / boost::math::log1p(-success_fraction, Policy()) - 1;\r\n      return result;\r\n\r\n    } // quantile complement\r\n\r\n } // namespace math\r\n} // namespace boost\r\n\r\n// This include must be at the end, *after* the accessors\r\n// for this distribution have been defined, in order to\r\n// keep compilers that support two-phase lookup happy.\r\n#include <boost/math/distributions/detail/derived_accessors.hpp>\r\n\r\n#if defined (BOOST_MSVC)\r\n# pragma warning(pop)\r\n#endif\r\n\r\n#endif // BOOST_MATH_SPECIAL_GEOMETRIC_HPP\r\n", "meta": {"hexsha": "4f31c2b31f9c0cc3a8f7bf7899762bb0ffca5047", "size": 21672, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/math/distributions/geometric.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/distributions/geometric.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/distributions/geometric.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": 41.918762089, "max_line_length": 126, "alphanum_fraction": 0.6309985234, "num_tokens": 5038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2522747730686923}}
{"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_DARCY_HH\n#define DUNE_GDT_OPERATORS_DARCY_HH\n\n#include <limits>\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <dune/geometry/quadraturerules.hh>\n\n#include <dune/stuff/common/exceptions.hh>\n#include <dune/stuff/common/type_utils.hh>\n#include <dune/stuff/functions/interfaces.hh>\n#include <dune/stuff/la/container.hh>\n#include <dune/stuff/la/solver.hh>\n\n#include <dune/gdt/discretefunction/default.hh>\n#include <dune/gdt/exceptions.hh>\n#include <dune/gdt/spaces/cg/interface.hh>\n#include <dune/gdt/spaces/rt/interface.hh>\n\n#include \"interfaces.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace Exceptions {\n\n\nclass darcy_operator_error : public operator_error {};\n\n\n} // namespace Exceptions\nnamespace Operators {\n\n\n// forward, to be used in the traits\ntemplate< class GridViewImp, class FunctionImp >\nclass Darcy;\n\n\nnamespace internal {\n\n\ntemplate< class GridViewImp, class FunctionImp >\nclass DarcyTraits\n{\n  static_assert(Stuff::is_localizable_function< FunctionImp >::value,\n                \"FunctionImp has to be derived from Stuff::IsLocalizableFunction!\");\n  static_assert(std::is_same< typename GridViewImp::ctype, typename FunctionImp::DomainFieldType >::value,\n                \"Types do not match!\");\n  static_assert(GridViewImp::dimension == FunctionImp::dimDomain, \"Dimensions do not match!\");\npublic:\n  typedef Darcy< GridViewImp, FunctionImp >    derived_type;\n  typedef GridViewImp                          GridViewType;\n  typedef typename FunctionImp::RangeFieldType FieldType;\n}; // class DarcyTraits\n\n\n} // namespace internal\n\n\n/**\n  * \\note Only works for scalar valued function atm.\n  **/\ntemplate< class GridViewImp, class FunctionImp >\nclass Darcy\n  : public OperatorInterface< internal::DarcyTraits< GridViewImp, FunctionImp > >\n{\npublic:\n  typedef internal::DarcyTraits< GridViewImp, FunctionImp >  Traits;\n  typedef typename Traits::GridViewType                      GridViewType;\n  typedef typename Traits::FieldType                         FieldType;\n  typedef typename GridViewType::template Codim< 0 >::Entity EntityType;\n  typedef typename GridViewType::ctype                       DomainFieldType;\n  static const size_t                                        dimDomain = GridViewType::dimension;\n\n  Darcy(const GridViewType& grd_vw, const FunctionImp& function)\n    : grid_view_(grd_vw)\n    , function_(function)\n  {}\n\n  /**\n   * \\brief Applies the operator.\n   * \\note  See redirect_apply for the implementation (depending on the type of the range space).\n   * \\sa    redirect_apply\n   */\n  template< class S, class V, size_t r, size_t rC >\n  void apply(const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, FieldType, r, rC >& source,\n             DiscreteFunction< S, V >& range) const\n  {\n    redirect_apply(range.space(), source, range);\n  }\n\nprivate:\n  /**\n   * \\brief Does an L2 projection of '- function * \\gradient source' onto range.\n   */\n  template< class T, class S, class V >\n  void redirect_apply(const Spaces::CGInterface< T, dimDomain, dimDomain, 1 >& /*space*/,\n                      const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, FieldType, 1, 1 >& source,\n                      DiscreteFunction< S, V >& range) const\n  {\n    typedef typename Stuff::LA::Container< FieldType >::MatrixType MatrixType;\n    typedef typename Stuff::LA::Container< FieldType >::VectorType VectorType;\n    MatrixType lhs(range.space().mapper().size(),\n                   range.space().mapper().size(),\n                   range.space().compute_volume_pattern());\n    VectorType rhs(range.space().mapper().size());\n\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 >(); entity_it != entity_it_end; ++entity_it) {\n      const auto& entity = *entity_it;\n      const auto local_function = function_.local_function(entity);\n      const auto local_source = source.local_function(entity);\n      const auto basis = range.space().base_function_set(entity);\n      // do a volume quadrature\n      const size_t integrand_order = std::max(local_function->order() + ssize_t(local_source->order()) - 1,\n                                              basis.order())\n                                     + basis.order();\n      const auto& quadrature = QuadratureRules< DomainFieldType, dimDomain >::rule(entity.type(),\n                                                                                   boost::numeric_cast< int >(integrand_order));\n      const auto quadrature_it_end = quadrature.end();\n      for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) {\n        const auto xx = quadrature_it->position();\n        const auto quadrature_weight = quadrature_it->weight();\n        const auto integration_element = entity.geometry().integrationElement(xx);\n        const auto function_value = local_function->evaluate(xx);\n        const auto source_gradient = local_source->jacobian(xx);\n        const auto basis_value = basis.evaluate(xx);\n        for (size_t ii = 0; ii < basis.size(); ++ii) {\n          const size_t global_ii = range.space().mapper().mapToGlobal(entity, ii);\n          rhs.add_to_entry(global_ii,\n                           integration_element * quadrature_weight\n                           * -1.0 * function_value * (source_gradient[0] * basis_value[ii]));\n          for (size_t jj = 0; jj < basis.size(); ++jj) {\n            const size_t global_jj = range.space().mapper().mapToGlobal(entity, jj);\n            lhs.add_to_entry(global_ii,\n                             global_jj,\n                             integration_element * quadrature_weight * (basis_value[ii] * basis_value[jj]));\n          }\n        }\n      } // do a volume quadrature\n    } // walk the grid\n\n    // solve\n    try {\n      Stuff::LA::Solver< MatrixType >(lhs).apply(rhs, range.vector());\n    } catch (Stuff::Exceptions::linear_solver_failed& ee) {\n      DUNE_THROW(Exceptions::darcy_operator_error,\n                 \"Application of the Darcy operator failed because a matrix could not be inverted!\\n\\n\"\n                 << \"This was the original error: \" << ee.what());\n    }\n  } // ... redirect_apply(...)\n\n  template< class T, class S, class V >\n  void redirect_apply(const Spaces::RTInterface< T, dimDomain, dimDomain, 1 >& /*space*/,\n                      const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, FieldType, 1 >& source,\n                      DiscreteFunction< S, V >& range) const\n  {\n    static_assert(Spaces::RTInterface< T, dimDomain, 1 >::polOrder == 0, \"Untested!\");\n    const auto& rtn0_space = range.space();\n    auto& range_vector = range.vector();\n    const auto infinity = std::numeric_limits< FieldType >::infinity();\n    for (size_t ii = 0; ii < range_vector.size(); ++ii)\n      range_vector[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 >(); entity_it != entity_it_end; ++entity_it) {\n      const auto& entity = *entity_it;\n      const auto local_DoF_indices = rtn0_space.local_DoF_indices(entity);\n      const auto global_DoF_indices = rtn0_space.mapper().globalIndices(entity);\n      assert(global_DoF_indices.size() == local_DoF_indices.size());\n      const auto local_function = function_.local_function(entity);\n      const auto local_source = source.local_function(entity);\n      const auto local_basis = rtn0_space.base_function_set(entity);\n      // walk the intersections\n      const auto intersection_it_end = grid_view_.iend(entity);\n      for (auto intersection_it = grid_view_.ibegin(entity);\n           intersection_it != intersection_it_end;\n           ++intersection_it) {\n        const auto& intersection = *intersection_it;\n        if (intersection.neighbor() && !intersection.boundary()) {\n          const auto neighbor_ptr = intersection.outside();\n          const auto& neighbor = *neighbor_ptr;\n          if (grid_view_.indexSet().index(entity) < grid_view_.indexSet().index(neighbor)) {\n            const auto local_function_neighbor = function_.local_function(neighbor);\n            const auto local_source_neighbor = source.local_function(neighbor);\n            const size_t local_intersection_index = intersection.indexInInside();\n            const size_t local_DoF_index = local_DoF_indices[local_intersection_index];\n            // do a face quadrature\n            FieldType lhs = 0;\n            FieldType rhs = 0;\n            const size_t integrand_order = local_function->order();\n            const auto& quadrature = QuadratureRules< DomainFieldType, dimDomain - 1 >::rule(intersection.type(),\n                                                                                             boost::numeric_cast< int >(integrand_order));\n            const auto quadrature_it_end = quadrature.end();\n            for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) {\n              const auto xx_intersection = quadrature_it->position();\n              const auto normal = intersection.unitOuterNormal(xx_intersection);\n              const FieldType integration_factor = intersection.geometry().integrationElement(xx_intersection);\n              const FieldType weigth = quadrature_it->weight();\n              const auto xx_entity = intersection.geometryInInside().global(xx_intersection);\n              const auto xx_neighbor = intersection.geometryInOutside().global(xx_intersection);\n              // evaluate\n              auto function_value = local_function->evaluate(xx_entity);\n              function_value *= 0.5;\n              auto function_value_neighbor = local_function_neighbor->evaluate(xx_neighbor);\n              function_value_neighbor *= 0.5;\n              function_value += function_value_neighbor;\n              auto source_gradient = local_source->jacobian(xx_entity);\n              source_gradient *= 0.5;\n              auto source_gradient_neighbor = local_source_neighbor->jacobian(xx_neighbor);\n              source_gradient_neighbor *= 0.5;\n              source_gradient += source_gradient_neighbor;\n              const auto basis_values = local_basis.evaluate(xx_entity);\n              const auto basis_value = basis_values[local_DoF_index];\n              // compute integrals\n              lhs += integration_factor * weigth * (basis_value * normal);\n              rhs += integration_factor * weigth * -1.0 * function_value * (source_gradient[0] * normal);\n            } // do a face quadrature\n            // set DoF\n            const size_t global_DoF_index = global_DoF_indices[local_DoF_index];\n            assert(!(range_vector[global_DoF_index] < infinity));\n            range_vector[global_DoF_index] = rhs / lhs;\n          }\n        } else if (intersection.boundary() && !intersection.neighbor()) {\n          const size_t local_intersection_index = intersection.indexInInside();\n          const size_t local_DoF_index = local_DoF_indices[local_intersection_index];\n          // do a face quadrature\n          FieldType lhs = 0;\n          FieldType rhs = 0;\n          const size_t integrand_order = local_function->order();\n          const auto& quadrature = QuadratureRules< DomainFieldType, dimDomain - 1 >::rule(intersection.type(),\n                                                                                           boost::numeric_cast< int >(integrand_order));\n          const auto quadrature_it_end = quadrature.end();\n          for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) {\n            const auto xx_intersection = quadrature_it->position();\n            const auto normal = intersection.unitOuterNormal(xx_intersection);\n            const auto integration_factor = intersection.geometry().integrationElement(xx_intersection);\n            const auto weigth = quadrature_it->weight();\n            const auto xx_entity = intersection.geometryInInside().global(xx_intersection);\n            // evalaute\n            const auto function_value = local_function->evaluate(xx_entity);\n            const auto source_gradient = local_source->jacobian(xx_entity);\n            const auto basis_values = local_basis.evaluate(xx_entity);\n            const auto basis_value = basis_values[local_DoF_index];\n            // compute integrals\n            lhs += integration_factor * weigth * (basis_value * normal);\n            rhs += integration_factor * weigth * -1.0 * function_value * (source_gradient[0] * normal);\n          } // do a face quadrature\n          // set DoF\n          const size_t global_DoF_index = global_DoF_indices[local_DoF_index];\n          assert(!(range_vector[global_DoF_index] < infinity));\n          range_vector[global_DoF_index] = rhs / lhs;\n        } else\n          DUNE_THROW(Stuff::Exceptions::internal_error, \"Unknown intersection type!\");\n      } // walk the intersections\n    } // walk the grid\n  } // ... redirect_apply(...)\n\n  const GridViewType& grid_view_;\n  const FunctionImp& function_;\n}; // class Darcy\n\n\n} // namespace Operators\n} // namespace GDT\n} // namespace Dune\n\n#endif // DUNE_GDT_OPERATORS_DARCY_HH\n", "meta": {"hexsha": "46d19ed697af701a3cf455d65d310ae1800b4553", "size": 13438, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/gdt/operators/darcy.hh", "max_stars_repo_name": "ftalbrecht/dune-gdt", "max_stars_repo_head_hexsha": "574bc4a3b28d2a6a6195a6b4df6727c61f0d73c9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-08T04:12:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-08T04:12:08.000Z", "max_issues_repo_path": "dune/gdt/operators/darcy.hh", "max_issues_repo_name": "dune-community/dune-gdt-archive", "max_issues_repo_head_hexsha": "08c0167b2761f8263514189be2dcdf0e21a055dc", "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/darcy.hh", "max_forks_repo_name": "dune-community/dune-gdt-archive", "max_forks_repo_head_hexsha": "08c0167b2761f8263514189be2dcdf0e21a055dc", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-08T04:12:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T04:12:11.000Z", "avg_line_length": 48.6884057971, "max_line_length": 138, "alphanum_fraction": 0.6500223248, "num_tokens": 2845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.25227476047701264}}
{"text": "// smooth: Lie Theory for Robotics\n// https://github.com/pettni/smooth\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef SMOOTH__CONCEPTS_HPP_\n#define SMOOTH__CONCEPTS_HPP_\n\n/**\n * @file concepts.hpp Library concept definitions.\n */\n\n#include <concepts>\n\n#include <Eigen/Core>\n\n\nnamespace smooth\n{\n\n/**\n * @brief A concept defining a (smooth) manifold.\n *\n * - `M::Scalar` scalar type\n * - `M::SizeAtCompileTime` tangent space dimension (compile time, -1 if dynamic)\n * - `M.size()` : tangent space dimension (runtime)\n * - `M + T -> M` : geodesic addition\n * - `M - M -> T` : inverse of geodesic addition (in practice only used for infinitesimal values)\n *\n * Where `T = Eigen::Matrix<Scalar, SizeAtCompileTime, 1>` is the tangent type\n */\ntemplate<typename M>\nconcept Manifold =\nrequires\n{\n  typename M::Scalar;\n  typename M::PlainObject;\n  {M::SizeAtCompileTime}->std::convertible_to<Eigen::Index>;  // degrees of freedom at compile time\n} &&\nrequires(const M & m1, const M & m2, const Eigen::Matrix<typename M::Scalar, M::SizeAtCompileTime, 1> & a)\n{\n  {m1.size()}->std::convertible_to<Eigen::Index>;             // degrees of freedom at runtime\n  {m1 + a}->std::convertible_to<typename M::PlainObject>;\n  {m1 - m2}->std::convertible_to<Eigen::Matrix<typename M::Scalar, M::SizeAtCompileTime, 1>>;\n  {m1.template cast<double>()};\n};\n\n/**\n * @brief Lie group concept.\n *\n * Requires the exp and log maps, and the upper and lowercase adjoints.\n */\ntemplate<typename G>\nconcept LieGroup = Manifold<G> &&\n// static constants\nrequires {\n  typename G::Tangent;\n  {G::Dof}->std::convertible_to<Eigen::Index>;\n} &&\n(G::Dof >= 1) &&\n(G::SizeAtCompileTime == G::Dof) &&\n(G::Tangent::SizeAtCompileTime == G::Dof) &&\n// member methods\nrequires(const G & g1, const G & g2)\n{\n  {g1.inverse()}->std::convertible_to<typename G::PlainObject>;\n  {g1 * g2}->std::convertible_to<typename G::PlainObject>;\n  {g1.log()}->std::convertible_to<Eigen::Matrix<typename G::Scalar, G::Dof, 1>>;\n  {g1.Ad()}->std::convertible_to<Eigen::Matrix<typename G::Scalar, G::Dof, G::Dof>>;\n} &&\n// static methods\nrequires(const Eigen::Matrix<typename G::Scalar, G::Dof, 1> & a)\n{\n  {G::Identity()}->std::convertible_to<typename G::PlainObject>;\n  {G::exp(a)}->std::convertible_to<typename G::PlainObject>;\n  {G::ad(a)}->std::convertible_to<Eigen::Matrix<typename G::Scalar, G::Dof, G::Dof>>;\n};\n\n} // namespace smooth\n\n#endif  // SMOOTH__CONCEPTS_HPP_\n", "meta": {"hexsha": "1a96baf02aa0c36322f01366ffea84a79b889f9d", "size": 3566, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/concepts.hpp", "max_stars_repo_name": "NamDinhRobotics/smooth", "max_stars_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T10:28:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T10:28:18.000Z", "max_issues_repo_path": "include/smooth/concepts.hpp", "max_issues_repo_name": "NamDinhRobotics/smooth", "max_issues_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/smooth/concepts.hpp", "max_forks_repo_name": "NamDinhRobotics/smooth", "max_forks_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9607843137, "max_line_length": 106, "alphanum_fraction": 0.704711161, "num_tokens": 950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2521779748096991}}
{"text": "#include \"utils.h\"\n#include \"ps/ps.h\"\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <iostream>\n#include <fstream>\n#include <iterator>\n#include <vector>\n#include <thread>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/timer/timer.hpp>\n#include <boost/generator_iterator.hpp>\n#include <boost/program_options.hpp>\n#include <boost/algorithm/string.hpp>\n#include <limits>\n#include <sstream>\n#include <string>\n#include <iostream>\n#include <unistd.h>\n#include <bitset>\n#include <Eigen/Dense>\n#include <Eigen/SparseCore>\n#include \"mf/update.h\"\n#include \"mf/data.h\"\n#include \"mf/io.h\"\n\nusing namespace ps;\nusing namespace std;\n\ntypedef double ValT;\ntypedef DefaultColoServerHandle<ValT> HandleT;\ntypedef ColoKVServer<ValT, HandleT> ServerT;\ntypedef ColoKVWorker<ValT, HandleT> WorkerT;\n\ntypedef Eigen::VectorXd vect;\ntypedef Eigen::SparseMatrix<ValT,Eigen::RowMajor> SpMatrixRM;\ntypedef Eigen::SparseMatrix<ValT,Eigen::ColMajor> SpMatrixCM;\ntypedef Eigen::Matrix<ValT, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> DeMatrixRM;\ntypedef Eigen::Matrix<ValT, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> DeMatrixCM;\n\n\n// Matrix factorization config\nstring dataset;\nuint mf_rank;\nuint param_len;\nint epochs;\ndouble initial_step_size;\ndouble lambda;\ndouble increase_step_factor;\ndouble decrease_step_factor;\nbool use_wor_block_schedule;\nbool use_wor_point_schedule;\nbool compute_loss;\nbool bold_driver;\n\n// System config\nuint num_workers;\nint  num_threads;\nlong num_cols;\nlong num_rows;\nAlg algorithm;\nbool   signal_intent_rows;\nsize_t signal_intent_cols;\nint init_parameters;\nbool enforce_random_keys;\nunsigned long early_stop;\nbool sync_push;\nlong max_runtime;\nbool prevent_full_model_pull;\nstd::string write_generated_factors;\nbool enforce_full_replication;\n\n// set by system\nKey first_col_key;\nKey num_keys;\nstd::vector<Key> key_assignment;\nunsigned model_seed;\n\n// Shared data\nstd::vector<Key> full_h_keys;\nstd::vector<ValT> full_h;\nstd::vector<ValT> local_w_shared {};\n\ninline Key row_key(size_t i) {\n  return enforce_random_keys ? key_assignment[i] : i;\n}\ninline Key col_key(size_t j) {\n  return enforce_random_keys ? key_assignment[first_col_key+j] : first_col_key+j;\n}\n\n#include \"mf/loss.h\"\n\n// Calculate loss on training and test data\ndouble calculate_loss(const int epoch, std::vector<Key>& local_w_keys,\n                      mf::DataPart& train_data, mf::DataPart& test_data,\n                      WorkerT& kv, const int worker_id, const int num_workers, const int customer_id) {\n\n  // key and vector for aggregation (in PS)\n  std::vector<Key> loss_key { num_keys-1 };\n  std::vector<ValT> agg_vec (param_len);\n  assert(param_len >= 3); // need two elements to aggregate train and test loss\n\n\n  // reset aggregation\n  if (worker_id == 0) {\n    kv.Wait(kv.Pull(loss_key, &agg_vec));\n    for(size_t i=0; i!=agg_vec.size(); ++i) {\n      agg_vec[i] = -agg_vec[i];\n    }\n    kv.Wait(kv.Push(loss_key, agg_vec));\n  }\n  kv.WaitSync();\n  kv.Barrier();\n\n  // wait for sync\n  kv.WaitSync();\n\n  // in columnwise SGD, multiple threads hold the same part of w\n  // we calculate l2 for this block only in the first of these threads\n  bool add_w_l2 = (algorithm == Alg::columnwise && customer_id != 0 ? false : true);\n\n  // calculate local loss\n  double local_train_loss = 0;\n  double local_test_loss = 0;\n  double local_train_reg = 0;\n  if (!prevent_full_model_pull) {\n    if (worker_id == 0) ADLOG(\"Pull model for loss calc\");\n\n    // pull local part of W\n    std::vector<ValT> local_w_worker {};\n    std::vector<ValT>* local_w;\n    if (algorithm != Alg::columnwise) {\n      // normally, each worker has its dedicated local part of w (i.e., no sharing possible)\n      local_w_worker.resize(local_w_keys.size() * param_len);\n      kv.Wait(kv.Pull(local_w_keys, &local_w_worker)); // fetch local part of w\n      local_w = &local_w_worker;\n    } else {\n      // in the columnwise alg, the workers of one process work on the same part\n      // of W, so we share W within a process to save memory and bandwidth\n      if (customer_id == 0) {\n        local_w_shared.resize(local_w_keys.size() * param_len);\n        kv.Wait(kv.Pull(local_w_keys, &local_w_shared));\n      }\n      kv.Barrier();\n      local_w = &local_w_shared;\n    }\n\n    // pull (full) H (once per process)\n    if (customer_id == 0) { // fetch full h once per process\n      full_h.resize(num_cols * param_len);\n      kv.Wait(kv.Pull(full_h_keys, &full_h));\n    }\n    kv.Barrier();\n\n    // calculate loss (with a copy of the model)\n    std::tie(local_train_loss, local_train_reg) = loss_Nzsl_L2(train_data, *local_w, full_h, lambda, worker_id, add_w_l2);\n    std::tie(local_test_loss, std::ignore)      = loss_Nzsl_L2(test_data,  *local_w, full_h, 0.0,    worker_id, add_w_l2);\n  } else {\n    // calculate loss (pulling necessary factors on demand)\n    if (worker_id == 0) ADLOG(\"No full model pull for eval. Pull factors on demand.\");\n    std::tie(local_train_loss, local_train_reg) = loss_Nzsl_L2_pull(train_data, kv, local_w_keys, lambda, worker_id, add_w_l2);\n    std::tie(local_test_loss, std::ignore)      = loss_Nzsl_L2_pull(test_data,  kv, local_w_keys, 0.0,    worker_id, add_w_l2);\n  }\n  // ADLOG(\"Local training loss (worker \" << worker_id << \"): \" << local_train_loss);\n  // ADLOG(\"Local test loss (worker \" << worker_id << \"): \" << local_test_loss);\n\n  // aggregate local losses to global loss (using the PS)\n  agg_vec[0] = local_train_loss;\n  agg_vec[1] = local_train_reg;\n  agg_vec[2] = local_test_loss;\n  kv.Wait(kv.Push(loss_key, agg_vec));\n  kv.Barrier();\n  kv.Wait(kv.Pull(loss_key, &agg_vec));\n\n  auto train_loss = (agg_vec[0] + agg_vec[1]) / train_data.total_nnz();\n  auto test_loss = (agg_vec[2]) / test_data.total_nnz();\n\n  if (worker_id == 0) {\n    ADLOG(\"(Ep.\" << epoch << \") Train loss: \" << train_loss << \" (\" << agg_vec[0] / train_data.total_nnz() << \" + \" << agg_vec[1] / train_data.total_nnz() << \")\");\n    ADLOG(\"(Ep.\" << epoch << \") Test loss:  \" << test_loss);\n  }\n\n  return train_loss;\n}\n\nvoid RunWorker(int customer_id, ServerT* server=nullptr) {\n  WorkerT kv(customer_id, *server);\n\n  boost::random::mt19937 rng(static_cast<unsigned int>(std::time(0)));\n  std::unordered_map<std::string, util::Stopwatch> sw {};\n  util::Trace trace {\"./measurements/mf/mf_trace.csv\"};\n\n  UpdateNsqlL2Adagrad update_fun {mf_rank, param_len, initial_step_size, lambda};\n  int worker_id = ps::MyRank()*num_threads+customer_id; // a unique id for this worker thread\n  Eigen::MatrixXi block_schedule = mf::initBlockSchedule(num_workers);\n\n\n  /* Load data, factors, and allocate memory */\n\n  // Load train data\n  sw[\"read_data\"].start();\n  mf::DataPart data =      read_sparse_matrix_part(dataset + string(\"train.mmc\"), true, num_workers, worker_id, Postoffice::Get()->num_servers(), ps::MyRank(), num_rows, num_cols, customer_id, algorithm, kv);\n  mf::DataPart data_test = read_sparse_matrix_part(dataset + string(\"test.mmc\"),  true, num_workers, worker_id, Postoffice::Get()->num_servers(), ps::MyRank(), num_rows, num_cols, customer_id, algorithm, kv);\n  sw[\"read_data\"].stop();\n  ALOG(\"Finished reading train data in worker \" << worker_id << \" (\" << sw[\"read_data\"] << \")\");\n\n  // allocate memory for factors in training loop\n  std::vector<Key> factors_keys ( 2 );\n  std::vector<ValT> factors ( factors_keys.size() * param_len );\n  std::vector<ValT> factors_update ( factors.size() );\n\n  // allocate memory for factors in loss computation (once per process)\n  if (customer_id == 0) {\n    full_h_keys.resize(num_cols);\n    for(size_t j=0; j!=full_h_keys.size(); ++j) {\n      full_h_keys[j] = col_key(j);\n    }\n  }\n\n  std::vector<Key> local_h_keys ( data.num_cols_per_block() );\n  std::vector<Key> local_w_keys ( data.num_rows_per_block() );\n  int my_block = (algorithm == Alg::columnwise ? ps::MyRank() : worker_id); // per-process blocks in columnwise\n  for(size_t z=0; z!=data.num_rows_per_block(); ++z) {\n    local_w_keys[z] = row_key(data.num_rows_per_block() * my_block + z);\n  }\n\n  boost::random::normal_distribution<> factor_generator (0, 1/sqrt(sqrt(mf_rank)));\n\n  // push factors into the parameter servers\n  kv.BeginSetup();\n  if (worker_id == 0 && init_parameters > 0) {\n    // read and send H\n    sw[\"read_factors\"].start();\n    std::vector<ValT> init_h {};\n    if (init_parameters == 1) {\n      // read factors from file\n      init_h = read_dense_matrix<std::vector<ValT>>(dataset + \"H.mma\", false);\n    } else if (init_parameters == 2) {\n      // init model randomly\n      ALOG(\"Init H randomly (seed \" << model_seed << \")\");\n      init_h.resize(num_cols * param_len);\n      boost::random::mt19937 rng_H (model_seed+133273);\n      for (long col=0; col!=num_cols ; ++col) {\n          for (long r=0; r!=mf_rank; ++r) {\n            init_h[col*param_len+r] = factor_generator(rng_H);\n          }\n          // leave 0's for AdaGrad values (pos mf_rank..param_len)\n      }\n    }\n    kv.Wait(kv.StaggeredPush(full_h_keys, init_h));\n    sw[\"read_factors\"].stop();\n\n    // optional: write out initial random factors\n    if (!write_generated_factors.empty()) {\n      std::ofstream out (write_generated_factors + \"H.mma\");\n      if (!out.is_open()) {\n        ALOG(\"Cannot open file to write initial factors: \" << write_generated_factors << \"H.mma\");\n        abort();\n      }\n\n      out << \"%%MatrixMarket matrix array real general\" << std::endl;\n      out << \"% First line: ROWS COLUMNS\" << std::endl;\n      out << \"% Subsequent lines: entries in column-major order\" << std::endl;\n      out << mf_rank << \" \" << num_cols << std::endl;\n      for (size_t z=0; z!=init_h.size(); ++z) {\n        out << init_h[z] << \"\\n\";\n      }\n      out.close();\n    }\n\n    ALOG(\"Initialized H (\" << sw[\"read_factors\"] << \"): \" << init_h[0] << \" \" << init_h[1] << \" \" << init_h[2] << \" ..\");\n  }\n\n  if (init_parameters > 0 && static_cast<uint>(worker_id) == num_workers-1) {\n    // read and send W\n    sw[\"read_factors\"].start();\n    ValT first, second;\n    if (init_parameters == 1) {\n      // read factors from files\n      vector<Key> full_w_keys (num_rows);\n      for(size_t i = 0; i!=full_w_keys.size(); ++i) full_w_keys[i] = row_key(i);\n      std::vector<ValT> full_w;\n      full_w = read_dense_matrix<std::vector<ValT>>(dataset + \"W.mma\", true);\n      kv.Wait(kv.StaggeredPush(full_w_keys, full_w));\n      first = full_w[0];\n      second = full_w[1];\n    } else if (init_parameters == 2) {\n      // init model randomly\n      ALOG(\"Init W randomly (seed \" << model_seed << \")\");\n      boost::random::mt19937 rng_W (model_seed);\n\n      // optional: write out initial random factors\n      std::ofstream out {};\n      if (!write_generated_factors.empty()) {\n        out.open(write_generated_factors + \"W.mma\");\n        if (!out.is_open()) {\n          ALOG(\"Cannot open file to write initial factors: \" << write_generated_factors << \"W.mma\");\n          abort();\n        }\n\n        // write header\n        out << \"%%MatrixMarket matrix array real general\" << std::endl;\n        out << \"% First line: ROWS COLUMNS\" << std::endl;\n        out << \"% Subsequent lines: entries in row-major order\" << std::endl;\n        out << num_rows << \" \" << mf_rank << std::endl;\n      }\n\n      // use (more complicated) batched implementation so we can run large models on a single machine\n      size_t batch_size = 10000;\n      vector<Key> partial_w_keys {};\n      std::vector<ValT> partial_w {};\n      vector<int> tss {};\n      size_t gen = 0;\n      for (int i=0; i!=num_rows; ++i) {\n        partial_w_keys.push_back(row_key(i));\n\n        // generate\n        for (size_t z=0; z!=mf_rank; ++z) {\n          auto r = factor_generator(rng_W);\n          if (gen == 0) first = r;\n          if (gen == 1) second = r;\n          ++gen;\n          partial_w.push_back(r);\n\n          if (!write_generated_factors.empty()) {\n            out << r << \"\\n\";\n          }\n        }\n\n        // initialize AdaGrad values with 0\n        for (size_t z=mf_rank; z!=param_len; ++z) {\n          partial_w.push_back(0);\n        }\n\n        // push\n        if (i % batch_size == batch_size-1) {\n          tss.push_back(kv.Push(partial_w_keys, partial_w));\n          partial_w_keys.resize(0);\n          partial_w.resize(0);\n        }\n      }\n      tss.push_back(kv.Push(partial_w_keys, partial_w));\n      for (auto ts : tss) kv.Wait(ts);\n\n      if (!write_generated_factors.empty()) {\n        out.close();\n      }\n    }\n    sw[\"read_factors\"].stop();\n    ALOG(\"Initialized W (\" << sw[\"read_factors\"] << \"): \" << first << \" \" << second << \" ..\");\n  }\n  kv.EndSetup(); // waits for sync and does barrier\n\n  // replicate all keys on all nodes throughout training\n  // (sensible only in ablation experiments)\n  if (enforce_full_replication && customer_id == 0) {\n  \tstd::vector<Key> keys (num_keys);\n    std::iota(keys.begin(), keys.end(), 0);\n    kv.Intent(keys, 0, CLOCK_MAX);\n  }\n  kv.WaitSync();\n  kv.Barrier();\n  kv.WaitSync();\n\n  // Signal intent for the parameters of the (statically partitioned) rows\n  if (signal_intent_rows) {\n    kv.Intent(local_w_keys, 0, CLOCK_MAX);\n    kv.WaitSync();\n  }\n\n  // prep for column-wise access\n  std::vector<size_t> my_columns {};\n  if (algorithm == Alg::columnwise) {\n    for (long j=0; j!=num_cols; ++j) {\n      if (data.block_has_nnz(j)) {\n        my_columns.push_back(j);\n      }\n    }\n\n    srand(worker_id ^ 13 * 17); // make sure workers have unique column permutations\n    if (use_wor_block_schedule) std::random_shuffle(my_columns.begin(), my_columns.end());\n  }\n\n  // Compute initial loss\n  ValT previous_train_loss=0;\n  if (compute_loss) {\n    auto train_loss = calculate_loss(0, local_w_keys, data, data_test,\n                                     kv, worker_id, num_workers, customer_id);\n    previous_train_loss = train_loss;\n  }\n\n  kv.Barrier(); // make sure all workers start training at the same time\n\n  /* Training loop */\n  for(int epoch = 1; epoch != epochs+1; ++epoch) {\n    if (worker_id == 0) ADLOG(\"(Ep.\" << epoch << \") Starting epoch \" << epoch);\n    sw[\"epoch.worker\"].start();\n    sw[\"epoch\"].start();\n    sw[\"runtime\"].resume();\n\n    // create WOR block schedule for this epoch, if desired (WOR = random, without replacement)\n    if (use_wor_block_schedule) mf::newWorSchedule(block_schedule, epoch, rng);\n\n    long updates = 0;\n\n    if (algorithm == Alg::dsgd) { // use DSGD to create locality in parameter accesses\n      for(uint subepoch = 0; subepoch != num_workers; ++subepoch) {\n        if (worker_id == 0) ADLOG(\"Subepoch \" << epoch << \".\" << subepoch);\n\n        // get the block this workers works on in this epoch\n        sw[\"comm\"].resume();\n        int h_block = block_schedule(subepoch, worker_id);\n        if (signal_intent_cols != 0) {\n          for (size_t z = 0; z!=local_h_keys.size(); ++z) {\n            local_h_keys[z] = col_key(h_block * data.num_cols_per_block() + z);\n          }\n          kv.Intent(local_h_keys, kv.currentClock());\n        }\n        sw[\"comm\"].stop();\n\n        // permute training points (WOR training schedule)\n        sw[\"perm\"].resume();\n        if (use_wor_point_schedule) data.permuteBlock(h_block);\n        sw[\"perm\"].stop();\n\n        // train on this block\n\n        // iterate over the nonzeros in this block\n        sw[\"comp\"].resume();\n        for (unsigned long z=data.block_start(h_block); z!=data.block_end(h_block); ++z) {\n          const mf::DataPoint& dp = data.data()[data.permutation()[z]];\n\n          // get factors\n          factors_keys[0] = row_key(dp.i);\n          factors_keys[1] = col_key(dp.j);\n          kv.Wait(kv.Pull(factors_keys, &factors));\n\n          // run update\n          update_fun(dp.i, dp.j, factors, factors_update, dp.x, data.row_nnz(dp.i), data.col_nnz(dp.j));\n          ++updates;\n\n          // send factor updates\n          auto ts = kv.Push(factors_keys, factors_update);\n          if (sync_push) kv.Wait(ts);\n        }\n\n        sw[\"comp\"].stop();\n\n        kv.advanceClock();\n\n        // wait for all workers to finish the subepoch\n        sw[\"barrier\"].resume();\n        kv.Barrier();\n        sw[\"barrier\"].stop();\n\n        // ADLOG(\"Subepoch \" << epoch << \".\" << subepoch << \" took \" << sw[\"subepoch\"]);\n      }\n    } else if (algorithm == Alg::columnwise) { // columnwise\n      // permute columns\n      sw[\"perm\"].resume();\n      ADLOG(\"Permute columns\");\n      if(use_wor_block_schedule) std::random_shuffle(my_columns.begin(), my_columns.end());\n      sw[\"perm\"].stop();\n\n      // iterate over the nonzeros that are partitioned to this worker\n      sw[\"comp\"].resume();\n      long col_future=0;\n      long z_epoch=0;\n      long z_future=0;\n      for (unsigned long col=0; col!=my_columns.size(); ++col) {\n        auto j = my_columns[col];\n\n        // permute data points of this column\n        if (use_wor_point_schedule) data.permuteBlock(j);\n\n        // signal intent for column parameters\n        if (signal_intent_cols != 0) {\n          while (col_future < static_cast<long>(col + signal_intent_cols) &&\n                 col_future < static_cast<long>(my_columns.size())) {\n            Clock futureClock = kv.currentClock() + z_future - z_epoch;\n            auto col_datapoints = data.block_size(my_columns[col_future]);\n            kv.Intent(col_key(my_columns[col_future]), futureClock, futureClock+col_datapoints);\n            z_future += col_datapoints;\n            ++col_future;\n          }\n        }\n\n        for (unsigned long z=data.block_start(j); z!=data.block_end(j); ++z, ++z_epoch) {\n          const mf::DataPoint& dp = data.data()[data.permutation()[z]];\n\n          // get factors\n          factors_keys[0] = row_key(dp.i);\n          factors_keys[1] = col_key(dp.j);\n          kv.Wait(kv.Pull(factors_keys, &factors));\n\n          // run update\n          update_fun(dp.i, dp.j, factors, factors_update, dp.x, data.row_nnz(dp.i), data.col_nnz(dp.j));\n          ++updates;\n\n          // send factor updates\n          auto ts = kv.Push(factors_keys, factors_update);\n          if (sync_push) kv.Wait(ts);\n\n          kv.advanceClock();\n\n          // early stopping (for debugging)\n          if(early_stop != 0 && z == early_stop) {\n            ALOG(\"Worker \" << worker_id << \" stops the epoch early after \" << early_stop << \" of \" << data.num_nnz() << \" data points\");\n            goto endepoch;\n          }\n        }\n      }\n    endepoch:\n      sw[\"comp\"].stop();\n      sw[\"epoch.worker\"].stop();\n      ALOG(\"Worker \" << worker_id << \" is through its \" << data.num_nnz() << \" data points (\" << sw[\"epoch.worker\"] << \")\");\n\n      // wait for all workers to finish the epoch\n      sw[\"barrier\"].resume();\n      kv.Barrier();\n      sw[\"barrier\"].stop();\n\n    } else { // plain SGD: access the data points in fully random order (i.e., no blocks and no columnwise access)\n\n      // permute training data points (WOR training schedule)\n      sw[\"perm\"].resume();\n      if (worker_id == 0) ADLOG(\"Permute ...\");\n      if (use_wor_point_schedule) data.permuteData();\n      sw[\"perm\"].stop();\n\n      // iterate over the nonzeros that are partitioned to this worker\n      sw[\"comp\"].resume();\n      if (worker_id == 0) ADLOG(\"Compute ...\");\n      unsigned long z_future=0;\n      for (unsigned long z=0; z!=data.num_nnz(); ++z) {\n        const mf::DataPoint& dp = data.data()[data.permutation()[z]];\n\n        // early stopping (for debugging)\n        if(early_stop != 0 && z == early_stop) {\n          ALOG(\"Worker \" << worker_id << \" stops the epoch early after \" << early_stop << \" of \" << data.num_nnz() << \" data points\");\n          break;\n        }\n\n        // signal intent for column parameters\n        if (signal_intent_cols != 0) {\n          while (z_future < z + signal_intent_cols &&\n                 z_future < data.num_nnz()) {\n            Clock futureClock = kv.currentClock() + z_future - z;\n            const mf::DataPoint& dp_future = data.data()[data.permutation()[z_future]];\n            kv.Intent(col_key(dp_future.j), futureClock);\n            ++z_future;\n          }\n        }\n\n        // get factors\n        factors_keys[0] = row_key(dp.i);\n        factors_keys[1] = col_key(dp.j);\n        kv.Wait(kv.Pull(factors_keys, &factors));\n\n        // run update\n        update_fun(dp.i, dp.j, factors, factors_update, dp.x, data.row_nnz(dp.i), data.col_nnz(dp.j));\n        ++updates;\n\n        // send factor updates\n        auto ts = kv.Push(factors_keys, factors_update);\n        if (sync_push) kv.Wait(ts);\n\n        kv.advanceClock();\n      }\n      sw[\"comp\"].stop();\n      sw[\"epoch.worker\"].stop();\n      ALOG(\"Worker \" << worker_id << \" is through its \" << data.num_nnz() << \" data points (\" << sw[\"epoch.worker\"] << \")\");\n\n      // wait for all workers to finish the epoch\n      sw[\"barrier\"].resume();\n      kv.Barrier();\n      sw[\"barrier\"].stop();\n\n    }\n    sw[\"epoch\"].stop();\n    sw[\"runtime\"].stop();\n    ADLOG(\"(Ep.\" << epoch << \") Worker \" << worker_id << \" finished epoch \" << epoch <<\" (\" << sw[\"epoch\"] << \": \" << sw[\"comm\"] << \" comm, \"  << sw[\"comp\"] << \" comp, \" << sw[\"barrier\"] << \" barrier, updates: \" << updates <<\")\");\n    if (worker_id == 0) {\n      ALOG(\"All workers finished epoch \" << epoch << \" (epoch: \" << sw[\"epoch\"] << \", total: \" << sw[\"runtime\"] << \").\");\n    }\n    sw[\"comm\"].reset(); sw[\"comp\"].reset(); sw[\"perm\"].reset(); sw[\"barrier\"].reset();\n\n    if (compute_loss) {\n      auto train_loss = calculate_loss(epoch, local_w_keys, data, data_test,\n                                       kv, worker_id, num_workers, customer_id);\n\n      // bold driver: adapt step size\n      if (bold_driver) {\n        if (train_loss < previous_train_loss) {\n          update_fun.update_step_size(increase_step_factor); // good epoch. increase step size slightly\n          if (worker_id == 0) {\n            ADLOG(\"Bold driver: Increase step size to \" << update_fun.current_step_size() << \" (Train loss: \" << previous_train_loss << \" -> \" << train_loss << \")\");\n          }\n        } else {\n          update_fun.update_step_size(decrease_step_factor); // bad epoch. reduce step size\n          if (worker_id == 0) {\n            ADLOG(\"Bold driver: Decrease step size to \" << update_fun.current_step_size() << \" (Train loss: \" << previous_train_loss << \" -> \" << train_loss << \")\");\n          }\n        }\n      }\n\n      previous_train_loss = train_loss;\n    }\n\n    // maximum time\n    if (sw[\"runtime\"].elapsed_s() > max_runtime ||\n        sw[\"runtime\"].elapsed_s() + sw[\"epoch\"].elapsed_s() > max_runtime * 1.05) {\n      ADLOG(\"Worker \" << worker_id << \" stops after epoch \" << epoch << \" because max. time is reached: \" << sw[\"runtime\"].elapsed_s() << \"s (+1 epoch) > \" << max_runtime << \"s (epoch: \" << sw[\"epoch\"].elapsed_s() << \"s)\");\n      break;\n    }\n  }\n\n  // make sure all workers finished\n  LLOG(\"Worker \" << worker_id << \" done.\");\n  kv.Finalize();\n}\n\n\nint process_program_options(const int argc, const char *const argv[]) {\n  namespace po = boost::program_options;\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()\n    (\"help,h\", \"produce help message\")\n    (\"dataset,d\", po::value<std::string>(&dataset), \"Dataset to train from\")\n    (\"num_rows\", po::value<long>(&num_rows), \"number of rows in the dataset\")\n    (\"num_cols\", po::value<long>(&num_cols), \"number of columns in the dataset\")\n    (\"rank,r\", po::value<uint>(&mf_rank), \"Rank of matrix factorization\")\n    (\"epochs,e\", po::value<int>(&epochs), \"Number of epochs to run\")\n    (\"lambda,l\", po::value<double>(&lambda)->default_value(0.05), \"Regularization parameter lambda\")\n    (\"eps\", po::value<double>(&initial_step_size)->default_value(0.001), \"Initial step size\")\n    (\"bold_driver\", po::value<bool>(&bold_driver)->default_value(true), \"Use bold driver for step size selection\")\n    (\"increase_step_factor\", po::value<double>(&increase_step_factor)->default_value(1.05), \"Factor to increase step size after successful epoch\")\n    (\"decrease_step_factor\", po::value<double>(&decrease_step_factor)->default_value(0.5), \"Factor to decrease step size after unsuccessful epoch\")\n    (\"algorithm\", po::value<Alg>(&algorithm)->default_value(Alg::dsgd), \"which algorithm to use. options: (1) dsgd = DSGD, (2) columnwise = access data points by column, (3) plain_sgd\")\n    (\"signal_intent_rows\", po::value<bool>(&signal_intent_rows)->default_value(true), \"whether to signal intent for row parameters (default: on, i.e., do localize row parameters)\")\n    (\"signal_intent_cols\", po::value<size_t>(&signal_intent_cols)->default_value(1000), \"whether to signal intent for column parameters (0: no signal, N>0 for dsgd: signal at block start, N>0 for colwise+plain: signal N data points ahead of time)\")\n    (\"num_threads,t\", po::value<int>(&num_threads)->default_value(1), \"number of worker threads to run\")\n    (\"wor_blocks\", po::value<bool>(&use_wor_block_schedule)->default_value(true), \"use WOR schedule for blocks\")\n    (\"wor_points\", po::value<bool>(&use_wor_point_schedule)->default_value(true), \"use WOR schedule for data points\")\n    (\"sync_push\", po::value<bool>(&sync_push)->default_value(false), \"synchronous or asynchronous (default) pushes\")\n    (\"compute_loss\", po::value<bool>(&compute_loss)->default_value(true), \"compute loss\")\n    (\"init_parameters\", po::value<int>(&init_parameters)->default_value(2), \"how to initialize parameters. 0: no init, 1: read factors from files, 2: draw random factors\")\n    (\"model_seed\", po::value<unsigned>(&model_seed)->default_value(134827), \"seed for model generation\")\n    (\"enforce_random_keys\", po::value<bool>(&enforce_random_keys)->default_value(false), \"enforce that keys are assigned randomly\")\n    (\"enforce_full_replication\", po::value<bool>(&enforce_full_replication)->default_value(false), \"manually enforce full model replication\")\n    (\"early_stop\", po::value<unsigned long>(&early_stop)->default_value(0), \"stop an epoch early after N data points (for debugging)\")\n    (\"max_runtime\", po::value<long>(&max_runtime)->default_value(std::numeric_limits<long>::max()), \"set a maximum run tim, after which the job will be terminated (in seconds)\")\n    (\"prevent_full_model_pull\", po::value<bool>(&prevent_full_model_pull)->default_value(false), \"prevent a full model pull (slower, but makes it possible to run large models in memory constrained settings)\")\n    (\"write_generated_factors\", po::value<std::string>(&write_generated_factors)->default_value(\"\"), \"Whether and to which path to write generated initial factors (default: empty, i.e., don't write factors)\")\n    ;\n\n  // add system options\n  ServerT::AddSystemOptions(desc);\n\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\")) {\n    cout << desc << \"\\n\";\n    return 1;\n  }\n\n  if (!vm.count(\"dataset\") || !vm.count(\"rank\") || !vm.count(\"epochs\")) {\n    cout << \"Either the dataset, the MF rank, or the number of epochs to run was not specified. Usage:\\n\\n\";\n    cout << desc << \"\\n\";\n    return 1;\n  }\n\n  return 0;\n}\n\nint main(int argc, char *argv[]) {\n  // Read cmd arguments\n  int po_error = process_program_options(argc, argv);\n  if(po_error) return 1;\n  num_keys = num_cols + num_rows + 50000;\n\n  Setup(num_keys, num_threads);\n\n  std::string role = std::string(getenv(\"DMLC_ROLE\"));\n  ALOG(\"mf. \" << role << \": \" << epochs << \" epochs on \" << dataset <<\n       \"\\nsignal intent rows \" << signal_intent_rows <<\n       \", cols \" << signal_intent_cols);\n\n  // calculate H key offset\n  num_workers = atoi(Environment::Get()->find(\"DMLC_NUM_SERVER\")) * num_threads;\n  first_col_key = round(ceil(1.0*num_rows/num_workers)) * num_workers;\n\n  // we store parameters and AdaGrad values in the same vector.\n  // 0..mf_rank: parameters; mf_rank..param_len: AdaGrad values\n  param_len = mf_rank * 2;\n\n  // enforce random parameter allocation\n  if (enforce_random_keys) {\n    key_assignment.resize(num_keys-1); // exclude the loss key\n    iota(key_assignment.begin(), key_assignment.end(), 0);\n    srand(2); // enforce same seed among different ranks\n    random_shuffle(key_assignment.begin(), key_assignment.end());\n  }\n\n  if (role.compare(\"scheduler\") == 0) {\n    Scheduler();\n  } else if (role.compare(\"server\") == 0) { // worker+server\n\n    // Start the server system\n    auto server = new ServerT(param_len);\n    RegisterExitCallback([server](){ delete server; });\n\n    // make sure all servers are set up\n    server->Barrier();\n\n    // run worker(s)\n    std::vector<std::thread> workers {};\n    for (int i=0; i!=num_threads; ++i) {\n      workers.push_back(std::thread(RunWorker, i, server));\n      std::string name = std::to_string(ps::MyRank())+\"-worker-\"+std::to_string(ps::MyRank()*num_threads + i);\n      SET_THREAD_NAME((&workers[workers.size()-1]), name.c_str());\n    }\n\n    // wait for the workers to finish\n    for (auto & w : workers)\n      w.join();\n\n    // stop the server\n    server->shutdown();\n  }\n}\n", "meta": {"hexsha": "18f2fc7a498e57b8d10c874deca5907911ca58cb", "size": 28897, "ext": "cc", "lang": "C++", "max_stars_repo_path": "apps/matrix_factorization.cc", "max_stars_repo_name": "alexrenz/NuPS", "max_stars_repo_head_hexsha": "6eebebf72b5440eaa755d052372e0cb24ed93de8", "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": "apps/matrix_factorization.cc", "max_issues_repo_name": "alexrenz/NuPS", "max_issues_repo_head_hexsha": "6eebebf72b5440eaa755d052372e0cb24ed93de8", "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": "apps/matrix_factorization.cc", "max_forks_repo_name": "alexrenz/NuPS", "max_forks_repo_head_hexsha": "6eebebf72b5440eaa755d052372e0cb24ed93de8", "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.1028416779, "max_line_length": 248, "alphanum_fraction": 0.6311035748, "num_tokens": 7496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.25217797480969906}}
{"text": "/**\n * Copyright (c) 2012 Andrew Prock. All rights reserved.\n * $Id: CardSet.cpp 2649 2012-06-30 04:53:24Z prock $\n */\n#include <cstdio>\n#include <cassert>\n#include <algorithm>\n#include <iostream>\n#include <limits>\n#include <vector>\n#include <set>\n#include <boost/array.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/format.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n#include <pokerstove/util/combinations.h>\n#include \"Rank.h\"\n#include \"Suit.h\"\n#include \"Card.h\"\n#include \"CardSet.h\"\n#include \"PokerEvaluation.h\"\n#include \"PokerEvaluationTables.h\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace pokerstove;\nusing namespace pokerstove;\n\n// some suit mask macros\n#define SMASK(n)   (static_cast<int>(_cardmask >> (n)*Rank::NUM_RANK) & 0x1FFF)\n\n#if 1\n#define C()        (static_cast<int>(_cardmask >> (0)*Rank::NUM_RANK) & 0x1FFF)\n#define D()        (static_cast<int>(_cardmask >> (1)*Rank::NUM_RANK) & 0x1FFF)\n#define H()        (static_cast<int>(_cardmask >> (2)*Rank::NUM_RANK) & 0x1FFF)\n#define S()        (static_cast<int>(_cardmask >> (3)*Rank::NUM_RANK) & 0x1FFF)\n#else\n#define C()        SMASK(0)\n#define D()        SMASK(1)\n#define H()        SMASK(2)\n#define S()        SMASK(3)\n#endif\n\n#define RMASK()    (C() | D() | H() | S())\n\n#define LOWBALL_ROTATE_RANKS(ranks)             \\\n  ((((ranks) & ~(1 << Rank::AceVal())) << 1)    \\\n   | (((ranks) >> Rank::AceVal()) & 0x01))\n\n/**\n * ctors\n */\n\nCardSet::CardSet()\n    : _cardmask(0)\n{}\n\nCardSet::CardSet(const CardSet& cs)\n    : _cardmask(cs._cardmask)\n{}\n\nCardSet::CardSet(const Card& c)\n    : _cardmask(ONE64 << c._card)\n{}\n\nCardSet::CardSet(const string& c)\n    : _cardmask(0)\n{\n    fromString(c);\n}\n\nstring CardSet::str() const\n{\n    string out = \"\";\n    uint64_t v = _cardmask;\n    while (v) {\n        Card card(lastbit64(v));\n        out += card.str();\n        v &= v - 1; // clear the least significant bit set\n    }\n    return out;\n}\n\n// TODO: use same loop as in ::str()\nstring CardSet::rankstr() const\n{\n    string out = \"\";\n    for (size_t i=0; i<STANDARD_DECK_SIZE; i++)\n    {\n        uint64_t mask = ONE64 << i;\n        if (_cardmask & mask)\n        {\n            Card c(i);\n            out += c.rank().str();\n        }\n    }\n    sort(out.begin(), out.end());\n    return out;\n}\n\nstring CardSet::toRankBitString() const\n{\n    string out = \"\";\n    for (size_t i=0; i<STANDARD_DECK_SIZE; i++)\n    {\n        if (_cardmask & ONE64 << i)\n            out += \"1\";\n        else\n            out += \".\";\n        if (((i+1)%Rank::NUM_RANK) == 0)\n            out += \" \";\n    }\n    return out;\n}\n\nsize_t CardSet::countSuits() const\n{\n    int ns = 0;\n    for (size_t i=0; i<Suit::NUM_SUIT; i++)\n        if (SMASK(i) > 0)\n            ns++;\n    return ns;\n}\n\nsize_t CardSet::countMaxSuit() const\n{\n    vector<size_t> suit(Suit::NUM_SUIT);\n    suit[0] = (nRanksTable[SMASK(0)]);\n    suit[1] = (nRanksTable[SMASK(1)]);\n    suit[2] = (nRanksTable[SMASK(2)]);\n    suit[3] = (nRanksTable[SMASK(3)]);\n\n    return *std::max_element(suit.begin(),suit.end());\n}\n\nsize_t CardSet::size() const\n{\n    uint64_t v = _cardmask;\n    size_t c;\n    for (c = 0; v; c++)\n    {\n        v &= v - 1; // clear the least significant bit set\n    }\n    return c;\n}\n\nvoid CardSet::fromString(const string& instr)\n{\n\tclear ();\n\n\tfor (size_t i=0; i<instr.size(); i+=2) {\n        // skip whitespace\n        if (instr[i] == ' ') {\n            i -= 1;\n            continue;\n        }\n        int code = Rank::rank_code(instr[i]) + Suit::suit_code(instr[i+1]) * Rank::NUM_RANK;\n        uint64_t mask = (ONE64 << code);\n\t\tif (_cardmask & mask) {\n\t\t\tclear();  // card duplication is an error, no hand parsed\n\t\t\treturn;\n\t\t}\n        _cardmask |= mask;\n    }\n}\n\nCardSet& CardSet::insert(const CardSet& c) {\n  _cardmask |= c._cardmask;\n  return *this;\n}\n\nCardSet CardSet::rotateSuits(int c, int d, int h, int s) const {\n  return CardSet(\n          static_cast<uint64_t>(suitMask(Suit::Clubs())) << Rank::NUM_RANK * c |\n          static_cast<uint64_t>(suitMask(Suit::Diamonds())) << Rank::NUM_RANK * d |\n          static_cast<uint64_t>(suitMask(Suit::Hearts())) << Rank::NUM_RANK * h |\n          static_cast<uint64_t>(suitMask(Suit::Spades())) << Rank::NUM_RANK * s);\n}\n\nvoid CardSet::flipSuits() {\n  *this = rotateSuits(3, 2, 1, 0);\n}\n\nCardSet CardSet::canonize() const {\n  int smasks[Suit::NUM_SUIT];\n  int i = 0;\n  for (Suit s = Suit::begin(); s < Suit::end(); ++s)\n    smasks[i++] = suitMask(s);\n\n  sort(smasks, smasks + Suit::NUM_SUIT);\n\n  return CardSet(\n          static_cast<uint64_t>(smasks[3]) |\n          static_cast<uint64_t>(smasks[2]) << Rank::NUM_RANK |\n          static_cast<uint64_t>(smasks[1]) << Rank::NUM_RANK * 2 |\n          static_cast<uint64_t>(smasks[0]) << Rank::NUM_RANK * 3);\n}\n\nCardSet CardSet::canonize(const CardSet& other) const\n{\n    CardSet cother = other.canonize();\n    vector<int> perms = findSuitPermutation(other, cother);\n    CardSet hand = *this;\n    CardSet chand = hand.rotateSuits(perms[0],perms[1],perms[2],perms[3]);\n    return chand;\n}\n\n// This is super slow, make it faster\nbool CardSet::insertRanks(const CardSet& rset)\n{\n    // try the fastest way first\n    if ((_cardmask & rset._cardmask) == 0)\n    {\n        _cardmask |= rset._cardmask;\n        return true;\n    }\n\n    // now try shifting by flipping around suits\n    for (size_t s=1; s< Suit::NUM_SUIT; s++)\n    {\n        CardSet flipped(rset);\n        flipped.flipSuits();\n        if ((_cardmask & flipped._cardmask) == 0)\n        {\n            _cardmask |= flipped._cardmask;\n            return true;\n        }\n    }\n\n    // ok, just do it the slow way\n    for (Rank r=Rank::Two(); r<=Rank::Ace(); ++r)\n    {\n        size_t nrin = rset.count(r);\n        if (nrin == 0)\n            continue;\n\n        if (count(r) + nrin > Suit::NUM_SUIT)\n            return false;\n\n        for (Suit s=Suit::Clubs(); s<=Suit::Spades(); ++s)\n            //for (Suit s=Suit::Spades(); s>=Suit::Spades(); --s)\n        {\n            Card c(r,s);\n            if (!contains(c))\n            {\n                insert(c);\n                nrin--;\n            }\n            if (nrin == 0)\n                break;\n        }\n    }\n    return true;\n}\n\nCardSet CardSet::canonizeRanks() const {\n    // this is very slow, optimize if it winds up in an inner loop\n    CardSet ret;\n    string ranks = rankstr();\n    for (size_t i = 0; i < ranks.size(); i++) {\n        for (Suit s = Suit::Clubs(); s <= Suit::Spades(); ++s) {\n            Card candidate(Rank(ranks.substr(i, 1)), s);\n            if (!ret.contains(candidate)) {\n                ret.insert(candidate);\n                break;\n            }\n        }\n    }\n    return ret;\n}\n\nCardSet& CardSet::insert(const Card& c)\n{\n    _cardmask |= (ONE64 << c.code());\n    return *this;\n}\n\nvector<Card> CardSet::cards() const\n{\n    vector<Card> out(size());\n    size_t n = 0;\n    for (size_t i=0; i<STANDARD_DECK_SIZE; i++)\n        if (_cardmask & (ONE64 << i))\n            out[n++] = Card(i);\n    return out;\n}\n\nvector<CardSet> CardSet::cardSets() const\n{\n    vector<CardSet> out(size());\n    size_t n = 0;\n    for (size_t i=0; i<STANDARD_DECK_SIZE; i++)\n        if (_cardmask & (ONE64 << i))\n            out[n++] = CardSet(ONE64<<i);\n    return out;\n}\n\nCardSet& CardSet::remove(const CardSet& c)\n{\n    _cardmask ^= c._cardmask;\n    return *this;\n}\n\nCardSet& CardSet::remove(const Card& c)\n{\n    _cardmask ^= ONE64<<c.code();\n    return *this;\n}\n\nbool CardSet::contains(const CardSet& c) const\n{\n    return (c._cardmask == (_cardmask & c._cardmask));\n}\n\nbool CardSet::contains(const Card& c) const\n{\n    uint64_t bit = ONE64 << c.code();\n    return ((bit & _cardmask) != 0);\n}\n\nbool CardSet::contains(const Rank& r) const\n{\n    return (RMASK() & r.rankBit()) > 0;\n}\n\nCard CardSet::find(const Rank& r) const\n{\n    for (uint8_t i=0; i<Suit::NUM_SUIT; i++)\n    {\n        if (SMASK(i) & r.rankBit())\n            return Card(r, Suit(i));\n    }\n    return Card();\n}\n\nbool CardSet::contains(const Suit& s) const\n{\n    if (SMASK(s.code()) > 0)\n        return true;\n    return false;\n}\n\nint CardSet::rankMask() const\n{\n    return RMASK();\n}\n\nsize_t CardSet::countRanks() const\n{\n    return nRanksTable[C() | D() | H() | S()];\n}\n\nint CardSet::suitMask(const Suit& s) const\n{\n    return SMASK(s.code());\n}\n\nsize_t CardSet::count(const Rank& r) const\n{\n#if 1\n    // this version is faster, if less obvious\n    int c = C();\n    int d = D();\n    int h = H();\n    int s = S();\n\n    int four_mask = c & d & h & s;\n    if (four_mask & r.rankBit())\n        return 4;\n\n    int three_mask =\n        ((c&d)|(h&s)) &\n        ((c&h)|(d&s));\n    if (three_mask & r.rankBit())\n        return 3;\n\n    int rankmask = c | d | h | s;\n    int two_mask = rankmask ^(c ^ d ^ h ^ s);\n    if (two_mask & r.rankBit())\n        return 2;\n\n    if (rankmask & r.rankBit())\n        return 1;\n\n    return 0;\n#else\n    size_t ret = 0;\n    for (size_t i=0; i<Suit::NUM_SUIT; i++)\n        if (r.rankBit() & SMASK(i))\n            ret++;\n    return ret;\n#endif\n}\n\n\nbool CardSet::hasStraight() const\n{\n    if (straightTable[RMASK()] > 0)\n        return true;\n    return false;\n}\n\n// this is a rough draft of the evaluateHigh routine, the idea is that\n// it should be AFAP.  However, this is a general 1-7 card evaluator, so\n// it cannot be too fast.  We could unwrap the method calls here for the\n// PokerHand, maybe it would speed things up.\n//\n// note, there are no function calls in this function\nPokerEvaluation CardSet::evaluateHigh() const\n{\n    // first the easy stuff\n    int c = C();\n    int d = D();\n    int h = H();\n    int s = S();\n    int rankmask = c | d | h | s;\n\n    if (nRanksTable[rankmask] >= 5)\n    {\n        int sranks = 0;\n        int suitindex=-1;\n        if (nRanksTable[c] >= 5)\n        {\n            suitindex = Suit::ClubVal();\n            sranks = c;\n        }\n        else if (nRanksTable[d] >= 5)\n        {\n            suitindex = Suit::DiamondVal();\n            sranks = d;\n        }\n        else if (nRanksTable[h] >= 5)\n        {\n            suitindex = Suit::HeartVal();\n            sranks = h;\n        }\n        else if (nRanksTable[s] >= 5)\n        {\n            suitindex = Suit::SpadeVal();\n            sranks = s;\n        }\n        if (suitindex >= 0)\n        {\n            int strval = straightTable[sranks];\n            if (strval > 0)\n                return PokerEvaluation((STRAIGHT_FLUSH<<VSHIFT) ^ strval<<MAJOR_SHIFT);\n            else\n                return PokerEvaluation((FLUSH<<VSHIFT) ^ topFiveRanksTable[sranks]);\n        }\n        int strval = straightTable[rankmask];\n        if (strval > 0)\n            return PokerEvaluation((STRAIGHT<<VSHIFT) ^(strval<<MAJOR_SHIFT));\n    }\n\n    int ncards = nRanksTable[c] + nRanksTable[d] + nRanksTable[h] + nRanksTable[s];\n    int ndups = ncards - nRanksTable[rankmask];\n\n    switch (ndups)\n    {\n        case 0:     // no pair\n        {\n            return PokerEvaluation((NO_PAIR<<VSHIFT) ^ topFiveRanksTable[rankmask]);\n        }\n        break;\n\n        case 1:     // one pair\n        {\n            int two_mask = rankmask ^(c ^ d ^ h ^ s);\n            int topind = topRankTable[two_mask];\n            int kickers = topThreeRanksTable[rankmask ^(0x01<<topind)];\n            return PokerEvaluation((ONE_PAIR<<VSHIFT) ^(topind << MAJOR_SHIFT) ^ kickers);\n        }\n        break;\n\n        case 2:\n        {\n            int two_mask = rankmask ^(c ^ d ^ h ^ s);\n\n            if (two_mask)   // two pair\n            {\n                int topind = topRankTable[two_mask];\n                int botind = botRankTable[two_mask];\n                int kicker = topRankTable[rankmask ^ two_mask];\n                if (kicker >= 0)\n                    return PokerEvaluation((TWO_PAIR<<VSHIFT) ^(topind << MAJOR_SHIFT) ^(botind << MINOR_SHIFT) ^(0x01<<kicker));\n                else\n                    return PokerEvaluation((TWO_PAIR<<VSHIFT) ^(topind << MAJOR_SHIFT) ^(botind << MINOR_SHIFT));\n            }\n            else\n            {\n                int three_mask =\n                    ((c&d)|(h&s)) &\n                    ((c&h)|(d&s));\n                int topind = topRankTable[three_mask];\n                int kickers = rankmask ^(0x01<<topind);\n                int kbits = 0;\n                if (kickers > 0)\n                    kbits   = 0x01<<topRankTable[kickers];\n                if (kbits >= 0 && ((kickers^kbits) > 0))\n                    kbits      ^= 0x01<<topRankTable[kickers^kbits];\n                return PokerEvaluation((THREE_OF_A_KIND<<VSHIFT) ^(topind << MAJOR_SHIFT) ^ kbits);\n            }\n        }\n        break;\n\n        default:\n        {\n            int four_mask = c & d & h & s;\n            if (four_mask)\n            {\n                int topind = topRankTable[four_mask];\n                int kicker = rankmask;\n                kicker ^= (0x01<<topind);\n                kicker  = topRankTable[kicker];\n                if (kicker >= 0)\n                    return PokerEvaluation((FOUR_OF_A_KIND<<VSHIFT) ^(topind<<MAJOR_SHIFT) ^(0x01<<kicker));\n                else\n                    return PokerEvaluation((FOUR_OF_A_KIND<<VSHIFT) ^(topind<<MAJOR_SHIFT));\n            }\n\n            int two_mask = rankmask ^(c ^ d ^ h ^ s);\n            if (nRanksTable[two_mask] != ndups)\n            {\n                int three_mask =\n                    ((c&d)|(h&s)) &\n                    ((c&h)|(d&s));\n                int topind = topRankTable[three_mask];\n                if (two_mask > 0)\n                {\n                    int botind = topRankTable[two_mask];\n                    return PokerEvaluation((FULL_HOUSE<<VSHIFT) ^(topind<<MAJOR_SHIFT) ^(botind << MINOR_SHIFT));\n                }\n                else\n                {\n                    int botind = topRankTable[three_mask ^ 0x01<<topind];\n                    return PokerEvaluation((FULL_HOUSE<<VSHIFT) ^(topind<<MAJOR_SHIFT) ^(botind << MINOR_SHIFT));\n                }\n            }\n\n            int topind = topRankTable[two_mask];\n            int botind = topRankTable[two_mask ^ 0x01<<topind];\n            int kicker = rankmask ^ 0x01<<topind ^ 0x01<<botind;\n            kicker  = topRankTable[kicker];\n            if (kicker >= 0)\n                return PokerEvaluation((TWO_PAIR<<VSHIFT) ^(topind << MAJOR_SHIFT) ^(botind << MINOR_SHIFT) ^(0x01<<kicker));\n            else\n                return PokerEvaluation((TWO_PAIR<<VSHIFT) ^(topind << MAJOR_SHIFT) ^(botind << MINOR_SHIFT));\n        }\n        break;\n    }\n\n    cerr << \"oops\\n\";\n    return PokerEvaluation(0);\n}\n\n\n// same as evaluateHigh, but with the non-flush logic\n// elided\nPokerEvaluation CardSet::evaluateHighFlush() const\n{\n    // first the easy stuff\n    int c = C();\n    int d = D();\n    int h = H();\n    int s = S();\n    int rankmask = c | d | h | s;\n\n    if (nRanksTable[rankmask] >= 5)\n    {\n        int sranks = 0;\n        int suitindex=-1;\n        if (nRanksTable[c] >= 5)\n        {\n            suitindex = Suit::ClubVal();\n            sranks = c;\n        }\n        else if (nRanksTable[d] >= 5)\n        {\n            suitindex = Suit::DiamondVal();\n            sranks = d;\n        }\n        else if (nRanksTable[h] >= 5)\n        {\n            suitindex = Suit::HeartVal();\n            sranks = h;\n        }\n        else if (nRanksTable[s] >= 5)\n        {\n            suitindex = Suit::SpadeVal();\n            sranks = s;\n        }\n        if (suitindex >= 0)\n        {\n            int strval = straightTable[sranks];\n            if (strval > 0)\n                return PokerEvaluation((STRAIGHT_FLUSH<<VSHIFT) ^ strval<<MAJOR_SHIFT);\n            else\n                return PokerEvaluation((FLUSH<<VSHIFT) ^ topFiveRanksTable[sranks]);\n        }\n    }\n    return PokerEvaluation(0);\n}\n\n// evaluteHighRanks, same as evaluateHigh, but with the flush logic\n// elided\nPokerEvaluation CardSet::evaluateHighRanks() const\n{\n    // first the easy stuff\n    int c = C();\n    int d = D();\n    int h = H();\n    int s = S();\n    int rankmask = c | d | h | s;\n\n    if (nRanksTable[rankmask] >= 5)\n    {\n        int strval = straightTable[rankmask];\n        if (strval > 0)\n            return PokerEvaluation((STRAIGHT<<VSHIFT) ^(strval<<MAJOR_SHIFT));\n    }\n\n    int ncards = nRanksTable[c] + nRanksTable[d] + nRanksTable[h] + nRanksTable[s];\n    int ndups = ncards - nRanksTable[rankmask];\n\n    switch (ndups)\n    {\n        case 0:     // no pair\n        {\n            return PokerEvaluation((NO_PAIR<<VSHIFT) ^ topFiveRanksTable[rankmask]);\n        }\n        break;\n\n        case 1:     // one pair\n        {\n            int two_mask = rankmask ^(c ^ d ^ h ^ s);\n            int topind = topRankTable[two_mask];\n            int kickers = topThreeRanksTable[rankmask ^(0x01<<topind)];\n            return PokerEvaluation((ONE_PAIR<<VSHIFT) ^(topind << MAJOR_SHIFT) ^ kickers);\n        }\n        break;\n\n        case 2:\n        {\n            int two_mask = rankmask ^(c ^ d ^ h ^ s);\n\n            if (two_mask)   // two pair\n            {\n                int topind = topRankTable[two_mask];\n                int botind = botRankTable[two_mask];\n                int kicker = topRankTable[rankmask ^ two_mask];\n                if (kicker >= 0)\n                    return PokerEvaluation((TWO_PAIR<<VSHIFT) ^(topind << MAJOR_SHIFT) ^(botind << MINOR_SHIFT) ^(0x01<<kicker));\n                else\n                    return PokerEvaluation((TWO_PAIR<<VSHIFT) ^(topind << MAJOR_SHIFT) ^(botind << MINOR_SHIFT));\n            }\n            else\n            {\n                int three_mask =\n                    ((c&d)|(h&s)) &\n                    ((c&h)|(d&s));\n                int topind = topRankTable[three_mask];\n                int kickers = rankmask ^(0x01<<topind);\n                int kbits = 0;\n                if (kickers > 0)\n                    kbits   = 0x01<<topRankTable[kickers];\n                if (kbits >= 0 && ((kickers^kbits) > 0))\n                    kbits      ^= 0x01<<topRankTable[kickers^kbits];\n                return PokerEvaluation((THREE_OF_A_KIND<<VSHIFT) ^(topind << MAJOR_SHIFT) ^ kbits);\n            }\n        }\n        break;\n\n        default:\n        {\n            int four_mask = c & d & h & s;\n            if (four_mask)\n            {\n                int topind = topRankTable[four_mask];\n                int kicker = rankmask;\n                kicker ^= (0x01<<topind);\n                kicker  = topRankTable[kicker];\n                if (kicker >= 0)\n                    return PokerEvaluation((FOUR_OF_A_KIND<<VSHIFT) ^(topind<<MAJOR_SHIFT) ^(0x01<<kicker));\n                else\n                    return PokerEvaluation((FOUR_OF_A_KIND<<VSHIFT) ^(topind<<MAJOR_SHIFT));\n            }\n\n            int two_mask = rankmask ^(c ^ d ^ h ^ s);\n            if (nRanksTable[two_mask] != ndups)\n            {\n                int three_mask =\n                    ((c&d)|(h&s)) &\n                    ((c&h)|(d&s));\n                int topind = topRankTable[three_mask];\n                if (two_mask > 0)\n                {\n                    int botind = topRankTable[two_mask];\n                    return PokerEvaluation((FULL_HOUSE<<VSHIFT) ^(topind<<MAJOR_SHIFT) ^(botind << MINOR_SHIFT));\n                }\n                else\n                {\n                    int botind = topRankTable[three_mask ^ 0x01<<topind];\n                    return PokerEvaluation((FULL_HOUSE<<VSHIFT) ^(topind<<MAJOR_SHIFT) ^(botind << MINOR_SHIFT));\n                }\n            }\n\n            int topind = topRankTable[two_mask];\n            int botind = topRankTable[two_mask ^ 0x01<<topind];\n            int kicker = rankmask ^ 0x01<<topind ^ 0x01<<botind;\n            kicker  = topRankTable[kicker];\n            if (kicker >= 0)\n                return PokerEvaluation((TWO_PAIR<<VSHIFT) ^(topind << MAJOR_SHIFT) ^(botind << MINOR_SHIFT) ^(0x01<<kicker));\n            else\n                return PokerEvaluation((TWO_PAIR<<VSHIFT) ^(topind << MAJOR_SHIFT) ^(botind << MINOR_SHIFT));\n        }\n        break;\n    }\n\n    cerr << \"oops\\n\";\n    return PokerEvaluation(0);\n}\n\n// this is just evaluateHigh without the straight or flush code\nPokerEvaluation CardSet::evaluatePairing() const\n{\n    // first the easy stuff\n    int c = C();\n    int d = D();\n    int h = H();\n    int s = S();\n    int rankmask = c | d | h | s;\n    int ncards = nRanksTable[c] + nRanksTable[d] + nRanksTable[h] + nRanksTable[s];\n    int ndups = ncards - nRanksTable[rankmask];\n\n    switch (ndups)\n    {\n        case 0:     // no pair\n        {\n            return PokerEvaluation((NO_PAIR<<VSHIFT) ^ topFiveRanksTable[rankmask]);\n        }\n        break;\n\n        case 1:     // one pair\n        {\n            int two_mask = rankmask ^(c ^ d ^ h ^ s);\n            int topind = topRankTable[two_mask];\n            int kickers = topThreeRanksTable[rankmask ^(0x01<<topind)];\n            return PokerEvaluation((ONE_PAIR<<VSHIFT) ^(topind << MAJOR_SHIFT) ^ kickers);\n        }\n        break;\n\n        case 2:\n        {\n            int two_mask = rankmask ^(c ^ d ^ h ^ s);\n\n            if (two_mask)   // two pair\n            {\n                int topind = topRankTable[two_mask];\n                int botind = botRankTable[two_mask];\n                int kicker = topRankTable[rankmask ^ two_mask];\n                if (kicker >= 0)\n                    return PokerEvaluation((TWO_PAIR<<VSHIFT) ^(topind << MAJOR_SHIFT) ^(botind << MINOR_SHIFT) ^(0x01<<kicker));\n                else\n                    return PokerEvaluation((TWO_PAIR<<VSHIFT) ^(topind << MAJOR_SHIFT) ^(botind << MINOR_SHIFT));\n            }\n            else\n            {\n                int three_mask =\n                    ((c&d)|(h&s)) &\n                    ((c&h)|(d&s));\n                int topind = topRankTable[three_mask];\n                int kickers = rankmask ^(0x01<<topind);\n                int kbits = 0;\n                if (kickers > 0)\n                    kbits   = 0x01<<topRankTable[kickers];\n                if (kbits >= 0 && ((kickers^kbits) > 0))\n                    kbits      ^= 0x01<<topRankTable[kickers^kbits];\n                return PokerEvaluation((THREE_OF_A_KIND<<VSHIFT) ^(topind << MAJOR_SHIFT) ^ kbits);\n            }\n        }\n        break;\n\n        default:\n        {\n            int four_mask = c & d & h & s;\n            if (four_mask)\n            {\n                int topind = topRankTable[four_mask];\n                int kicker = rankmask;\n                kicker ^= (0x01<<topind);\n                kicker  = topRankTable[kicker];\n                if (kicker >= 0)\n                    return PokerEvaluation((FOUR_OF_A_KIND<<VSHIFT) ^(topind<<MAJOR_SHIFT) ^(0x01<<kicker));\n                else\n                    return PokerEvaluation((FOUR_OF_A_KIND<<VSHIFT) ^(topind<<MAJOR_SHIFT));\n            }\n\n            int two_mask = rankmask ^(c ^ d ^ h ^ s);\n            if (nRanksTable[two_mask] != ndups)\n            {\n                int three_mask =\n                    ((c&d)|(h&s)) &\n                    ((c&h)|(d&s));\n                int topind = topRankTable[three_mask];\n                if (two_mask > 0)\n                {\n                    int botind = topRankTable[two_mask];\n                    return PokerEvaluation((FULL_HOUSE<<VSHIFT) ^(topind<<MAJOR_SHIFT) ^(botind << MINOR_SHIFT));\n                }\n                else\n                {\n                    int botind = topRankTable[three_mask ^ 0x01<<topind];\n                    return PokerEvaluation((FULL_HOUSE<<VSHIFT) ^(topind<<MAJOR_SHIFT) ^(botind << MINOR_SHIFT));\n                }\n            }\n\n            int topind = topRankTable[two_mask];\n            int botind = topRankTable[two_mask ^ 0x01<<topind];\n            int kicker = rankmask ^ 0x01<<topind ^ 0x01<<botind;\n            kicker  = topRankTable[kicker];\n            if (kicker >= 0)\n                return PokerEvaluation((TWO_PAIR<<VSHIFT) ^(topind << MAJOR_SHIFT) ^(botind << MINOR_SHIFT) ^(0x01<<kicker));\n            else\n                return PokerEvaluation((TWO_PAIR<<VSHIFT) ^(topind << MAJOR_SHIFT) ^(botind << MINOR_SHIFT));\n        }\n        break;\n    }\n\n    cerr << \"oops\\n\";\n    return PokerEvaluation(0);\n}\n\n// This one is not fully optimized\nPokerEvaluation CardSet::evaluateLow2to7() const\n{\n    PokerEvaluation high;\n\n    // if there are five or fewer cards, we just evaluate the high,\n    // fix the wheel, and take the complement\n    switch (size())\n    {\n        case 0:\n        case 1:\n        case 2:\n        case 3:\n        case 4:\n            high = evaluateHigh();\n            break;\n\n        case 5:\n            high = evaluateHigh();\n            high.fixWheel2to7(rankMask());\n            break;\n\n        default:\n            // this is a slow way to handle the general case.\n            // TODO: specialize the code for the 6 and 7 card cases.\n            vector<Card> cards = this->cards();\n            combinations combo(size(), FULL_HAND_SIZE);\n            PokerEvaluation best;\n            do\n            {\n                CardSet candidate;\n                for (size_t i=0; i<static_cast<size_t>(FULL_HAND_SIZE); i++)\n                    candidate.insert(cards[combo[i]]);\n                PokerEvaluation e = candidate.evaluateLow2to7();\n                if (e > best)\n                    best = e;\n            }\n            while (combo.next());\n            return best;\n\n    }\n\n    high.flip();\n    return high;\n}\n\n// This one is not fully optimized\nPokerEvaluation CardSet::evaluateRanksLow2to7() const\n{\n    PokerEvaluation high;\n    PokerEvaluation h;\n\n    // if there are five or fewer cards, we just evaluate the high,\n    // fix the wheel, and take the complement\n    switch (size())\n    {\n        case 0:\n        case 1:\n        case 2:\n        case 3:\n        case 4:\n            high = evaluateHighRanks();\n            break;\n\n        case 5:\n            high = evaluateHighRanks();\n            high.fixWheel2to7(rankMask());\n            break;\n\n        default:\n            // this is a slow way to handle the general case.\n            // TODO: specialize the code for the 6 and 7 card cases.\n            vector<Card> cards = this->cards();\n            combinations combo(size(), FULL_HAND_SIZE);\n            PokerEvaluation best;\n            do\n            {\n                CardSet candidate;\n                for (size_t i=0; i<static_cast<size_t>(FULL_HAND_SIZE); i++)\n                    candidate.insert(cards[combo[i]]);\n                PokerEvaluation e = candidate.evaluateRanksLow2to7();\n                if (e > best)\n                    best = e;\n            }\n            while (combo.next());\n            return best;\n\n    }\n\n    high.flip();\n    return high;\n}\n\n\n// This one is not fully optimized\nPokerEvaluation CardSet::evaluateSuitsLow2to7() const\n{\n    PokerEvaluation high;\n\n    // if there are five or fewer cards, we just evaluate the high,\n    // fix the wheel, and take the complement\n    switch (size())\n    {\n        case 0:\n        case 1:\n        case 2:\n        case 3:\n        case 4:\n            high = evaluateHighFlush();\n            break;\n\n        case 5:\n            high = evaluateHighFlush();\n            high.fixWheel2to7(rankMask());\n            break;\n\n        default:\n            // this is a slow way to handle the general case.\n            // TODO: specialize the code for the 6 and 7 card cases.\n            vector<Card> cards = this->cards();\n            combinations combo(size(), FULL_HAND_SIZE);\n            PokerEvaluation best;\n            do\n            {\n                CardSet candidate;\n                for (size_t i=0; i<static_cast<size_t>(FULL_HAND_SIZE); i++)\n                    candidate.insert(cards[combo[i]]);\n                PokerEvaluation e = candidate.evaluateSuitsLow2to7();\n                if (e > best)\n                    best = e;\n            }\n            while (combo.next());\n            return best;\n\n    }\n\n    high.flip();\n    return high;\n}\n\n\n\n// This one is not fully optimized\nPokerEvaluation CardSet::evaluateLowA5() const\n{\n    //PokerEvaluation::generateLowballLookupA5();\n\n    // this is a rank only evaluator, so we just get\n    // the rank masks and then fill accordingly.  We\n    // also have to shift the rank mask according to the\n    // the fact that the ace swings low\n    // this could probably be much faster\n\n    int c = C();\n    int d = D();\n    int h = H();\n    int s = S();\n    int rankmask = c | d | h | s;\n\n    int ncards = nRanksTable[c] + nRanksTable[d] + nRanksTable[h] + nRanksTable[s];\n    int ndups = ncards - nRanksTable[rankmask];\n    int nranks = nRanksTable[rankmask];\n\n    // first the easy cases\n    // 1) no duplicate ranks\n    // 2) 5 or more ranks\n    if (ndups == 0 || nranks >= FULL_HAND_SIZE)\n    {\n        PokerEvaluation ret((NO_PAIR<<VSHIFT) ^ lowballA5Ranks[rankmask] ^ ACE_LOW_BIT);\n        ret.flip();\n        return ret;\n    }\n    // another easy case\n    // *) we have five or fewer cards\n    else if (ncards <= FULL_HAND_SIZE)\n    {\n        PokerEvaluation ret = evaluatePairing();\n        ret.playAceLow();\n        ret.flip();\n        return ret;\n    }\n    else\n    {\n        // now the general case\n        // the algorithm is as follows:\n        // cycle through the \"pairing list\" till a total of five\n        // cards are found\n        uint64_t chash = 0;// = rankmask;\n        int rset[4];\n\n        rset[0]  = rankmask;\n        rset[1]  = rankmask ^(c ^ d ^ h ^ s);             // mask of cards with 2/4 ranks\n        rset[2]  = ((c&d)|(h&s)) & ((c&h)|(d&s));         // mask of cards with 3 ranks\n        rset[3]  =  c & d & h & s;                        // fourmask\n        rset[1] |= rset[2];       // add the threes back to teh twos\n\n        rset[0] = LOWBALL_ROTATE_RANKS(rset[0]);\n        rset[1] = LOWBALL_ROTATE_RANKS(rset[1]);\n        rset[2] = LOWBALL_ROTATE_RANKS(rset[2]);\n        rset[3] = LOWBALL_ROTATE_RANKS(rset[3]);\n\n        // we add pairs first, then trips, then quads\n        int nc=0;\n        for (int i=0; i<4; i++)\n        {\n            // do the ace first\n            if (rset[i] & (0x01<<Rank::AceVal()))\n            {\n                chash |= (ONE64<<(Rank::AceVal()+Rank::NUM_RANK*i));\n                nc++;\n            }\n            if (nc == FULL_HAND_SIZE)\n            {\n                break;\n            }\n\n            // now the rest of the ranks\n            for (int r=0; r<11; r++)\n            {\n                if (rset[i] & (0x01<<r))\n                {\n                    chash |= (ONE64<<(r+Rank::NUM_RANK*i));\n                    nc++;\n                }\n                if (nc == FULL_HAND_SIZE)\n                {\n                    break;\n                }\n            }\n            if (nc == FULL_HAND_SIZE)\n            {\n                break;\n            }\n        }\n\n        CardSet paird(chash);\n        PokerEvaluation ret(paird.evaluatePairing().code() | ACE_LOW_BIT);\n        ret.flip();\n        return ret;\n    }\n}\n\nPokerEvaluation CardSet::evaluate8LowA5() const\n{\n    // bits 2-8+A are set here\n    const int LOW_MASK = 0x107F;\n\n    int c = C() & LOW_MASK;\n    int d = D() & LOW_MASK;\n    int h = H() & LOW_MASK;\n    int s = S() & LOW_MASK;\n\n    int rankmask = c | d | h | s;\n    int nranks = nRanksTable[rankmask];\n\n    if (nranks >= FULL_HAND_SIZE)\n    {\n        PokerEvaluation ret(((NO_PAIR<<VSHIFT) ^ lowballA5Ranks[rankmask]) | ACE_LOW_BIT);\n        ret.flip();\n        return ret;\n    }\n\n    PokerEvaluation e;\n    return e;\n}\n\nPokerEvaluation CardSet::evaluate3CP() const\n{\n    int c = C();\n    int d = D();\n    int h = H();\n    int s = S();\n    int rankmask = c | d | h | s;\n\n    int ncards = nRanksTable[c] + nRanksTable[d] + nRanksTable[h] + nRanksTable[s];\n    if (ncards > 3)\n        throw std::invalid_argument(\"3CP evaluator only works on three cards\");\n\n    // check for three flush\n    bool threeflush = countSuits() == 1 ? true : false;\n\n    // then three straight\n    const int THREE_WHEEL = 0x01<<Rank::AceVal() | 0x01<<Rank::TwoVal() | 0x01<<Rank::ThreeVal();\n    int  topr = topRankTable[rankmask];\n    int  botr = botRankTable[rankmask];\n    int  strr = -1;\n    bool threestr = false;\n    if (topr - botr == 2 && nRanksTable[rankmask] == 3)\n    {\n        threestr = true;\n        strr = topr;\n    }\n    else if (rankmask == THREE_WHEEL)\n    {\n        threestr = true;\n        strr = Rank::ThreeVal();\n    }\n\n    if (threeflush)\n    {\n        if (threestr)\n            return PokerEvaluation((THREE_STRAIGHT_FLUSH<<VSHIFT) ^ strr<<MAJOR_SHIFT);\n        else\n            return PokerEvaluation((THREE_FLUSH<<VSHIFT) ^ rankmask);\n    }\n    else if (threestr)\n    {\n        return PokerEvaluation((THREE_STRAIGHT<<VSHIFT) ^(strr<<MAJOR_SHIFT));\n    }\n    else\n    {\n        return evaluatePairing();\n    }\n}\n\n// three card badugis are better than two card badugis\nstatic inline bool badugiless(int c1, int c2)\n{\n    int n1 = nRanksTable[c1];\n    int n2 = nRanksTable[c2];\n    if (n1 == n2)\n        return c1 < c2;\n    return n1 > n2;\n}\n\n\n/**\n * Badugi hand evaluator. To make this faster, I need a\n * bottomRankMask.\n *\n * To do a four card evaluation it suffices to pass through the suits\n * twice, once in each direction.  To do a general evaluation, all\n * suits must be traversed in all orders so that 4*3*2*1=24 suit\n * traversals will be done.  Suits of size zero can be ruled out and\n * those with size one can be ruled in.\n */\nPokerEvaluation CardSet::evaluateBadugi() const\n{\n    // get our ranks orgainzed in lowball order by suit\n    boost::array<int,4> suits =\n    {\n        {\n            LOWBALL_ROTATE_RANKS(C()),\n            LOWBALL_ROTATE_RANKS(D()),\n            LOWBALL_ROTATE_RANKS(H()),\n            LOWBALL_ROTATE_RANKS(S())\n        }\n    };\n\n    // We try to save some time by being smart about which suits we loop\n    // over.  Empty suits are ignored, and suits with one rank are used\n    // as is.  At the end we sort to make next_permutation to work properly.\n    boost::array<int,4> ind;\n    int bmust = 0;\n    size_t k=0;\n    for (size_t i=0; i<suits.size(); i++)\n    {\n        switch (nRanksTable[suits[i]])\n        {\n            case 1:\n                bmust |= suits[i];\n                // fall through\n            case 0:\n                break;\n            default:\n                ind[k++] = suits[i];\n        };\n    }\n    sort(ind.begin(),ind.begin()+k);\n\n    // now enter into the fray to find the best possible badugi.  suit\n    // order in this loop matters, so we cycle through the permutations\n    // of suit order.\n    //\n    // zeroing minbadugi works because it has no ranks and a one rank\n    // badugi is less than a zero rank badugi.\n    int minbadugi = 0;\n    do\n    {\n        // explanation of bit ops, b=current badugi, s=suit being considered\n        // (b|s)-b                    set of ranks in suit s not in the badugi yet\n        // b |= botRankMask[(b|s)-b]  for each relevant suit do this:\n        int branks = bmust;\n        for (size_t i=0; i<k; i++)\n            branks |= bottomRankMask[(branks|ind[i])-branks];\n\n        if (badugiless(branks, minbadugi))\n            minbadugi = branks;\n    }\n    while (next_permutation(ind.begin(),ind.begin()+k));\n\n    // encode the badugi, it's a low hand where aces plays low.  we set\n    // the number of missing suits in the badugi as the \"major rank\". the\n    // value is chosen so that more cards maps to a lower value\n    PokerEvaluation ret(((NO_PAIR<<VSHIFT) ^ minbadugi) | ACE_LOW_BIT);\n    ret.setMajorRank(Suit::NUM_SUIT - nRanksTable[minbadugi]);\n    ret.flip();\n    return ret;\n}\n\nbool CardSet::isPaired() const  // returns true if *any* two cards match rank\n{\n    int c = C();\n    int d = D();\n    int h = H();\n    int s = S();\n    int rankmask = c | d | h | s;\n\n    int two_mask = rankmask ^(c ^ d ^ h ^ s);\n    if (two_mask > 0)\n        return true;\n    return false;\n}\n\nsize_t CardSet::countMaxRank() const         // returns true if trips or quads\n{\n    int c = C();\n    int d = D();\n    int h = H();\n    int s = S();\n\n    int four_mask = c & d & h & s;\n    if (four_mask)\n        return 4;\n\n    int three_mask =\n        ((c&d)|(h&s)) &\n        ((c&h)|(d&s));\n    if (three_mask)\n        return 3;\n\n    int rankmask = c | d | h | s;\n    int two_mask = rankmask ^(c ^ d ^ h ^ s);\n    if (two_mask)\n        return 2;\n\n    if (rankmask > 0)\n        return 1;\n\n    return 0;\n}\n\nbool CardSet::isTripped() const         // returns true if trips or quads\n{\n    int c = C();\n    int d = D();\n    int h = H();\n    int s = S();\n\n    int three_mask =\n        ((c&d)|(h&s)) &\n        ((c&h)|(d&s));\n\n    if (three_mask > 0)\n        return true;\n    return false;\n}\n\nsize_t CardSet::count(const Suit& s) const\n{\n    return nRanksTable[SMASK(s.code())];\n}\n\nRank CardSet::flushRank(const Suit& s) const\n{\n    return Rank(topRankTable[SMASK(s.code())]);\n}\n\nRank CardSet::topRank() const\n{\n    return Rank(topRankTable[RMASK()]);\n}\n\nRank CardSet::bottomRank() const\n{\n    return Rank(botRankTable[RMASK()]);\n}\n\ndouble clampedChoose(int n, int m)\n{\n    if (n < m)\n        return 0;\n    return static_cast<size_t>(boost::math::binomial_coefficient<double>(n,m));\n}\n\nint CardSet::evaluateStraightOuts() const\n{\n    int sval = straightTable[RMASK()];\n    if (sval > 0)         // straight on board, all cards make straight\n        return STANDARD_DECK_SIZE;\n    if (sval == -2)       // open-ended, eight outs\n        return 8;\n    if (sval == -1)       // gut-shot, four outs\n        return 4;\n    if (sval == -3)       // runner-runner, \"1\" out\n        return 1;\n    return 0;\n}\n\n// original version in r2488\nsize_t CardSet::rankColex() const\n{\n    size_t ret  = 0;\n    int slot = 0;\n    int sz   = 1;\n    int c    = C();\n    int d    = D();\n    int h    = H();\n    int s    = S();\n    int rbit = 0x01;\n\n    for (int i=0; i<13; i++)\n    {\n        if (rbit&c) ret += clampedChoose(slot++,sz++);\n        if (rbit&d) ret += clampedChoose(slot++,sz++);\n        if (rbit&h) ret += clampedChoose(slot++,sz++);\n        if (rbit&s) ret += clampedChoose(slot++,sz++);\n        slot++;\n        rbit <<= 1;\n    }\n    return ret;\n}\n\nstd::ostream& operator<<(std::ostream& sout, const pokerstove::CardSet& e)\n{\n    sout << e.str();\n    return sout;\n}\n\nvector<int> pokerstove::findSuitPermutation(const CardSet& source, const CardSet& dest) {\n    vector<int> rot(4, -1);\n    vector<int> taken(4, 0);\n\n    int i = 0;\n    for (Suit s = Suit::begin(); s < Suit::end(); ++s, ++i) {\n        int j = 0;\n        for (Suit t = Suit::begin(); t < Suit::end(); ++t, ++j) {\n            if (source.suitMask(s) == dest.suitMask(t)) {\n                if (taken[j] == 0) {\n                    rot[i] = j;\n                    taken[j] = 1;\n                    break;\n                }\n            }\n        }\n    }\n    return rot;\n}\n\nCardSet pokerstove::canonizeToBoard(const CardSet& board, const CardSet& hand)\n{\n    CardSet cboard = board.canonize();\n    vector<int> perms = findSuitPermutation(board, cboard);\n    CardSet chand = hand.rotateSuits(perms[0],perms[1],perms[2],perms[3]);\n    return chand;\n}\n\n// some suit mask macros\n#undef C\n#undef D\n#undef H\n#undef S\n#undef RMASK\n#undef SUITMASK\n\nsize_t CardSet::colex() const {\n    vector<Card> cards = this->cards();\n    size_t value = 0;\n    for (size_t i = 0; i < cards.size(); i++) {\n        size_t code = cards[i].code();\n#ifdef __AP_MATH__\n        value += tchoose(code, i+1);\n#else\n        if (code >= i + 1)\n            value += static_cast<size_t>(boost::math::binomial_coefficient<double>(code, i + 1));\n#endif\n    }\n    return value;\n}\n", "meta": {"hexsha": "e1a41dca1a81dcf01b46d504ed6d5f0d1bfb9835", "size": 39361, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lib/pokerstove/peval/CardSet.cpp", "max_stars_repo_name": "rakhimov/pokerstove", "max_stars_repo_head_hexsha": "117990ebce4355595d80aa913c137f0f10f17494", "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/pokerstove/peval/CardSet.cpp", "max_issues_repo_name": "rakhimov/pokerstove", "max_issues_repo_head_hexsha": "117990ebce4355595d80aa913c137f0f10f17494", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/pokerstove/peval/CardSet.cpp", "max_forks_repo_name": "rakhimov/pokerstove", "max_forks_repo_head_hexsha": "117990ebce4355595d80aa913c137f0f10f17494", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-02T08:30:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-02T08:30:44.000Z", "avg_line_length": 27.856334041, "max_line_length": 129, "alphanum_fraction": 0.5197530551, "num_tokens": 10807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2521187477968727}}
{"text": "#ifndef DETAIL_VALUE_WITH_ERROR_HPP\n#define DETAIL_VALUE_WITH_ERROR_HPP\n\n#include <cmath>\n#include <iostream>\n#include <iomanip>\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/hypot.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <boost/type_traits/has_less.hpp>\n\n#include \"fwd.hpp\" // for DEFAULT_POLICY_CLASS define\n\n#if __cplusplus >= 201103L\n\n  #include <type_traits>\n  #include <initializer_list>\n\n  // CONST is being mapped to constexpr (C++11) or const (C++98)\n  #ifdef BOOST_NO_CXX11_CONSTEXPR\n    #define CONSTEXPR\n    #define CONST const\n  #else\n    #define CONST constexpr\n    #define CONSTEXPR constexpr\n  #endif\n#else\n  #include <boost/type_traits.hpp>\n  #define CONST const\n  #define CONSTEXPR\n#endif // __cplusplus >= 201103L\n\nnamespace error_propagation {\n  namespace detail {\n\n    using boost::math::tools::promote_args;\n\n    typedef boost::math::policies::policy<\n                                          boost::math::policies::domain_error<boost::math::policies::errno_on_error>,\n                                          boost::math::policies::pole_error<boost::math::policies::errno_on_error>,\n                                          boost::math::policies::overflow_error<boost::math::policies::errno_on_error>,\n                                          boost::math::policies::evaluation_error<boost::math::policies::errno_on_error>\n                                         > policy_errno_on_error;\n\n    // Only use hypot for types which support std::less\n    template<typename T, typename U, bool has_less_op>\n    struct hypot_impl;\n\n    template<typename T, typename U>\n    struct hypot_impl<T, U, false>\n    {\n      CONSTEXPR typename promote_args<T, U>::type\n      operator()(const T& a, const U& b) const\n      {\n        using std::sqrt;\n        return sqrt(a*a + b*b);\n      }\n    };\n\n    template<typename T, typename U>\n    struct hypot_impl<T, U, true>\n    {\n      CONSTEXPR typename promote_args<T, U>::type\n      operator()(const T& a, const U& b) const\n      {\n        // we don't use std::hypot here as that does not know how to work with boost::multiprecision\n        return boost::math::hypot(a,b,policy_errno_on_error());\n      }\n    };\n\n    template<typename T, typename U>\n    CONSTEXPR typename promote_args<T,U>::type\n    hypot(const T& a, const U& b)\n    {\n      return hypot_impl<T, U, boost::has_less<T,U,bool>::value>()(a,b);\n    }\n\n    template<typename T>\n    CONSTEXPR T digamma(const T& a)\n    {\n      return boost::math::digamma(a,policy_errno_on_error());\n    }\n\n  } // namespace detail\n} // namespace error_propagation\n\n#endif // DETAIL_VALUE_WITH_ERROR_HPP\n", "meta": {"hexsha": "e83df5ad129eb598b4c219ed735dad5174c4202c", "size": 2665, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/DetailValueWithError.hpp", "max_stars_repo_name": "t-b/value-with-error", "max_stars_repo_head_hexsha": "ede8325d3572ac53601d0d7aabc09518850c8455", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-09-07T10:58:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T01:09:50.000Z", "max_issues_repo_path": "src/DetailValueWithError.hpp", "max_issues_repo_name": "t-b/value-with-error", "max_issues_repo_head_hexsha": "ede8325d3572ac53601d0d7aabc09518850c8455", "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/DetailValueWithError.hpp", "max_forks_repo_name": "t-b/value-with-error", "max_forks_repo_head_hexsha": "ede8325d3572ac53601d0d7aabc09518850c8455", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2840909091, "max_line_length": 120, "alphanum_fraction": 0.6397748593, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.25205546195511414}}
{"text": "/**\n *  biascorrection.cpp\n *  MetaQuant\n *\n *  Kevin McLoughlin\n *  Based on code from eXpress, created by Adam Roberts in 2011.\n *  Copyright 2014 Kevin McLoughlin, Adam Roberts. All rights reserved.\n *\n */\n\n#include <algorithm>\n#include <boost/assign.hpp>\n#include <cassert>\n\n#include \"biascorrection.h\"\n\n#include \"fragments.h\"\n#include \"frequencymatrix.h\"\n#include \"main.h\"\n#include \"sequence.h\"\n#include \"targets.h\"\n\nusing namespace std;\n\n// size of bias window\nconst int WINDOW = 21;\n// center position in window\nconst int CENTER = 11;\n// number of bases on either side of center\nconst int SURROUND = 10;\n\nSeqWeightTable::SeqWeightTable(size_t window_size, size_t order, double alpha)\n    : _order(order),\n      _observed(order, window_size, window_size, alpha),\n      _expected(order, window_size, order+1, EPSILON) {\n}\n\nSeqWeightTable::SeqWeightTable(size_t window_size, size_t order,\n                               string param_file_name, string identifier)\n    : _order(order),\n      _observed(order, window_size, window_size, 0),\n      _expected(order, window_size, order+1, 0) {\n        \n  //TODO: Allow for orders and window sizes to be read from param file.\n  \n  ifstream infile (param_file_name.c_str());\n  const size_t BUFF_SIZE = 99999;\n  char line_buff[BUFF_SIZE];\n  if (!infile.is_open()) {\n    logger.severe(\"Unable to open parameter file '%s'.\",\n                  param_file_name.c_str());\n  }\n\n  do {\n    infile.getline (line_buff, BUFF_SIZE, '\\n');\n  } while (strncmp(line_buff, identifier.c_str(), identifier.size()));\n  infile.getline (line_buff, BUFF_SIZE, '\\n');\n\n  do {\n    infile.getline (line_buff, BUFF_SIZE, '\\n');\n  } while (strcmp(line_buff, \"\\tObserved Conditional Probabilities\"));\n  infile.getline (line_buff, BUFF_SIZE, '\\n');\n  \n  //FG\n  for (size_t k = 0; k < (size_t)WINDOW; ++k) {\n    infile.getline (line_buff, BUFF_SIZE, '\\n');\n    char *p = strtok(line_buff, \"\\t\");\n    for (size_t i=0; i < pow(4.0, (double)min(order, k)); ++i) {\n      for (size_t j=0; j < NUM_NUCS; ++j) {\n        p = strtok(NULL, \"\\t\");\n        _observed.update(k, i, j, log(strtod(p,NULL)));\n      }\n    }\n  }\n  \n  infile.getline (line_buff, BUFF_SIZE, '\\n');\n  infile.getline (line_buff, BUFF_SIZE, '\\n');\n  //BG\n  for (size_t k = 0; k < order+1; ++k) {\n    infile.getline (line_buff, BUFF_SIZE, '\\n');\n    char *p = strtok(line_buff, \"\\t\");\n    for (size_t i=0; i < pow(4.0, (double)min(order, k)); ++i) {\n      for (size_t j=0; j < NUM_NUCS; ++j) {\n        p = strtok(NULL, \"\\t\");\n        _expected.update(k, i, j, log(strtod(p,NULL)));\n      }\n    }\n  }\n}\n\n\nvoid SeqWeightTable::copy_observed(const SeqWeightTable& other) {\n  _observed = other._observed;\n}\n\nvoid SeqWeightTable::copy_expected(const SeqWeightTable& other) {\n  _expected = other._expected;\n}\n\nvoid SeqWeightTable::increment_expected(const Sequence& seq, double mass,\n                                        const vector<double>& fl_cdf) {\n  _expected.fast_learn(seq, mass, fl_cdf);\n}\n\nvoid SeqWeightTable::normalize_expected() {\n  _expected.calc_marginals();\n}\n\nvoid SeqWeightTable::increment_observed(const Sequence& seq, size_t i,\n                                        double mass) {\n  int left = (int)i - SURROUND;\n  _observed.update(seq, left, mass);\n}\n\ndouble SeqWeightTable::get_weight(const Sequence& seq, size_t i) const {\n  int left = (int)i - SURROUND;\n  return _observed.seq_prob(seq, left) - _expected.seq_prob(seq, left);\n}\n\nvoid SeqWeightTable::append_output(ofstream& outfile) const {\n  char buff[200];\n  string header = \"\";\n  for (int i = 0; i < WINDOW; i++) {\n    sprintf(buff, \"\\t%d\", i-CENTER+1);\n    header += buff;\n  }\n  header += '\\n';\n\n  outfile << \"\\tObserved Marginal Distribution\\n\" << header;\n\n  for (size_t j = 0; j < NUM_NUCS; j++) {\n    outfile << NUCS[j] << \":\\t\";\n    for (int i = 0; i < WINDOW; i++) {\n      outfile << scientific << sexp(_observed.marginal_prob(i,j)) << \"\\t\";\n    }\n    outfile<<endl;\n  }\n\n  outfile << \"\\tObserved Conditional Probabilities\\nPosition\\t\";\n\n  for (size_t j = 0; j < pow((double)NUM_NUCS, (double)_order+1); j++) {\n    string s = \"->\";\n    s += NUCS[j & 3];\n    size_t cond = j >> 2;\n    for (size_t k = 0; k < _order; ++k) {\n      s = NUCS[cond & 3] + s;\n      cond = cond >> 2;\n    }\n    outfile << s << '\\t';\n  }\n  outfile << endl;\n\n  for (int i = 0; i < WINDOW; i++) {\n    outfile << i-SURROUND << \":\\t\";\n    for (size_t j = 0; j < pow((double)NUM_NUCS, (double)_order+1); j++) {\n      outfile << scientific << sexp(_observed.transition_prob(i,j>>2,j&3))\n              << \"\\t\";\n    }\n    outfile<<endl;\n  }\n\n  outfile << \"\\tBackground Conditional Probabilities\\nPosition\\t\";\n\n  for (size_t j = 0; j < pow((double)NUM_NUCS, (double)_order+1); j++) {\n    string s = \"->\";\n    s += NUCS[j & 3];\n    size_t cond = j >> 2;\n    for (size_t k = 0; k < _order; ++k) {\n      s = NUCS[cond & 3] + s;\n      cond = cond >> 2;\n    }\n    outfile << s << '\\t';\n  }\n  outfile << endl;\n\n  for (size_t i = 0; i < _order+1; i++) {\n    outfile << i+1 << \":\\t\";\n    for (size_t j = 0; j <  pow((double)NUM_NUCS, (double)_order+1); j++) {\n      outfile << scientific << sexp(_expected.transition_prob(i,j>>2,j&3))\n              << \"\\t\";\n    }\n    outfile<<endl;\n  }\n}\n\nBiasBoss::BiasBoss(size_t order, double alpha)\n    : _order(order),\n      _5_seq_bias(WINDOW, order, alpha),\n      _3_seq_bias(WINDOW, order, alpha){\n}\n\nBiasBoss::BiasBoss(size_t order, string param_file_name)\n    : _order(order),\n      _5_seq_bias(WINDOW, order, param_file_name, \">5\"),\n      _3_seq_bias(WINDOW, order, param_file_name, \">3\") {\n}\n\nvoid BiasBoss::copy_observations(const BiasBoss& other) {\n  _5_seq_bias.copy_observed(other._5_seq_bias);\n  _3_seq_bias.copy_observed(other._3_seq_bias);\n}\n\nvoid BiasBoss::copy_expectations(const BiasBoss& other) {\n  _5_seq_bias.copy_expected(other._5_seq_bias);\n  _3_seq_bias.copy_expected(other._3_seq_bias);\n}\n\nvoid BiasBoss::update_expectations(const Target& targ, double mass,\n                                   const vector<double>& fl_cdf) {\n  if ((mass == LOG_0) || (mass < LOG_MIN_TARG_RHO)) {\n    return;\n  }\n\n  if (direction != R) {\n    const Sequence& seq_fwd = targ.seq(0);\n    _5_seq_bias.increment_expected(seq_fwd, mass, fl_cdf);\n  }\n  if (direction != F) {\n    const Sequence& seq_rev = targ.seq(1);\n    _3_seq_bias.increment_expected(seq_rev, mass, fl_cdf);\n  }\n}\n\nvoid BiasBoss::normalize_expectations() {\n  _5_seq_bias.normalize_expected();\n  _3_seq_bias.normalize_expected();\n}\n\nvoid BiasBoss::update_observed(const FragHit& hit, double normalized_mass)\n{\n  assert (hit.pair_status() != PAIRED || (int)hit.length() > WINDOW);\n\n  const Sequence& t_seq_fwd = hit.target()->seq(0);\n  const Sequence& t_seq_rev = hit.target()->seq(1);\n\n  if (hit.pair_status() != RIGHT_ONLY) {\n    _5_seq_bias.increment_observed(t_seq_fwd, hit.left(), normalized_mass);\n  }\n  if (hit.pair_status() != LEFT_ONLY) {\n    _3_seq_bias.increment_observed(t_seq_rev, t_seq_rev.length()-hit.right(),\n                                   normalized_mass);\n  }\n}\n\ndouble BiasBoss::get_target_start_bias(const Target& targ, size_t pos) const {\n\n  const Sequence& t_seq_fwd = targ.seq(0);\n  return _5_seq_bias.get_weight(t_seq_fwd, pos);\n}\n\ndouble BiasBoss::get_target_end_bias(const Target& targ, size_t pos) const {\n\n  const Sequence& t_seq_rev = targ.seq(1);\n  return _3_seq_bias.get_weight(t_seq_rev, targ.length()-pos-1);\n}\n\ndouble BiasBoss::get_average_target_bias(std::map<const size_t, float>& start_bias,\n                                         std::map<const size_t, float>& end_bias,\n                                         const Target& targ) const {\n  double tot_start = LOG_0;\n  double tot_end = LOG_0;\n\n  for (size_t i = 0; i < targ.length(); ++i) {\n    double start_bias_i;\n    double end_bias_i;\n    try {\n      start_bias_i = start_bias.at(i);\n    } catch (out_of_range) {\n      start_bias_i = get_target_start_bias(targ, i);\n    }\n    try {\n      end_bias_i = end_bias.at(i);\n    } catch (out_of_range) {\n      end_bias_i = get_target_end_bias(targ, i);\n    }\n    tot_start = log_add(tot_start, start_bias_i);\n    tot_end = log_add(tot_end, end_bias_i);\n  }\n\n  //double avg_start_bias = (tot_start ) - (log((double)targ.length()));\n  //double avg_end_bias = (tot_end) - (log((double)targ.length()));\n  double avg_bias = (tot_start + tot_end) - (2*log((double)targ.length()));\n  //logger.info(\"Target %s avg biases: start = %f, end = %f, total = %f\", targ.name().c_str(),\n  //   avg_start_bias, avg_end_bias, avg_bias);\n  assert(!isnan(avg_bias));\n  return avg_bias;\n}\n\nvoid BiasBoss::update_target_bias(std::map<const size_t, float>& start_bias,\n                                 std::map<const size_t, float>& end_bias,\n                                 const Target& targ) const {\n\n  const Sequence& t_seq_fwd = targ.seq(0);\n  const Sequence& t_seq_rev = targ.seq(1);\n\n  for (std::map<const size_t, float>::iterator it = start_bias.begin();\n       it != start_bias.end(); ++it) {\n    //=-=TODO: Shouldn't this be it->first???\n    size_t pos = it->second;\n    start_bias[pos] = _5_seq_bias.get_weight(t_seq_fwd, pos);\n  }\n  for (std::map<const size_t, float>::iterator it = end_bias.begin();\n       it != end_bias.end(); ++it) {\n    size_t pos = it->second;\n    end_bias[targ.length()-pos-1] = _3_seq_bias.get_weight(t_seq_rev, pos);\n  }\n}\n\nvoid BiasBoss::append_output(ofstream& outfile) const {\n  outfile << \">5' Sequence-Specific Bias\\n\";\n  _5_seq_bias.append_output(outfile);\n  outfile << \">3' Sequence-Specific Bias\\n\";\n  _3_seq_bias.append_output(outfile);\n}\n", "meta": {"hexsha": "b44789849a25248cf3da8e069fbcf222dba00321", "size": 9522, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/biascorrection.cpp", "max_stars_repo_name": "kmclough/MetaQuant_1.0", "max_stars_repo_head_hexsha": "2df1d823856cd2204c022cdba82aa2177cf921e0", "max_stars_repo_licenses": ["Artistic-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/biascorrection.cpp", "max_issues_repo_name": "kmclough/MetaQuant_1.0", "max_issues_repo_head_hexsha": "2df1d823856cd2204c022cdba82aa2177cf921e0", "max_issues_repo_licenses": ["Artistic-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/biascorrection.cpp", "max_forks_repo_name": "kmclough/MetaQuant_1.0", "max_forks_repo_head_hexsha": "2df1d823856cd2204c022cdba82aa2177cf921e0", "max_forks_repo_licenses": ["Artistic-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2285714286, "max_line_length": 94, "alphanum_fraction": 0.6251837849, "num_tokens": 2716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2519957747152347}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2009-2010 Gael Guennebaud <gael.guennebaud@inria.fr>\n//\n// This Source Code Form is subject to the terms of the Mozilla\n// Public License v. 2.0. If a copy of the MPL was not distributed\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n#include <Eigen/Core>\n#include <Eigen/Jacobi>\n\n\n#define NOTR    0\n#define TR      1\n#define ADJ     2\n\n#define LEFT    0\n#define RIGHT   1\n\n#define UP      0\n#define LO      1\n\n#define NUNIT   0\n#define UNIT    1\n\n#define INVALID 0xff\n\n#define OP(X)   (   ((X)=='N' || (X)=='n') ? NOTR   \\\n                  : ((X)=='T' || (X)=='t') ? TR     \\\n                  : ((X)=='C' || (X)=='c') ? ADJ    \\\n                  : INVALID)\n\n#define SIDE(X) (   ((X)=='L' || (X)=='l') ? LEFT   \\\n                  : ((X)=='R' || (X)=='r') ? RIGHT  \\\n                  : INVALID)\n\n#define UPLO(X) (   ((X)=='U' || (X)=='u') ? UP     \\\n                  : ((X)=='L' || (X)=='l') ? LO     \\\n                  : INVALID)\n\n#define DIAG(X) (   ((X)=='N' || (X)=='n') ? NUNIT  \\\n                  : ((X)=='U' || (X)=='u') ? UNIT   \\\n                  : INVALID)\n\n\ninline bool check_op(const char* op)\n{\n  return OP(*op)!=0xff;\n}\n\ninline bool check_side(const char* side)\n{\n  return SIDE(*side)!=0xff;\n}\n\ninline bool check_uplo(const char* uplo)\n{\n  return UPLO(*uplo)!=0xff;\n}\n\nusing namespace Eigen;\n\ntypedef float Scalar;\ntypedef NumTraits<Scalar>::Real RealScalar;\ntypedef std::complex<RealScalar> Complex;\n\nenum\n{\n  IsComplex = Eigen::NumTraits<float>::IsComplex,\n  Conj = IsComplex\n};\n\ntypedef Matrix<Scalar,Dynamic,Dynamic,ColMajor> PlainMatrixType;\ntypedef Map<Matrix<Scalar,Dynamic,Dynamic,ColMajor>, 0, OuterStride<> > MatrixType;\ntypedef Map<Matrix<Scalar,Dynamic,1>, 0, InnerStride<Dynamic> > StridedVectorType;\ntypedef Map<Matrix<Scalar,Dynamic,1> > CompactVectorType;\n\ntemplate<typename T>\nMap<Matrix<T,Dynamic,Dynamic,ColMajor>, 0, OuterStride<> >\nmatrix(T* data, int rows, int cols, int stride)\n{\n  return Map<Matrix<T,Dynamic,Dynamic,ColMajor>, 0, OuterStride<> >(data, rows, cols, OuterStride<>(stride));\n}\n\ntemplate<typename T>\nMap<Matrix<T,Dynamic,1>, 0, InnerStride<Dynamic> > vector(T* data, int size, int incr)\n{\n  return Map<Matrix<T,Dynamic,1>, 0, InnerStride<Dynamic> >(data, size, InnerStride<Dynamic>(incr));\n}\n\ntemplate<typename T>\nMap<Matrix<T,Dynamic,1> > vector(T* data, int size)\n{\n  return Map<Matrix<T,Dynamic,1> >(data, size);\n}\n\ntemplate<typename T>\nT* get_compact_vector(T* x, int n, int incx)\n{\n  if(incx==1)\n    return x;\n\n  T* ret = new Scalar[n];\n  if(incx<0) vector(ret,n) = vector(x,n,-incx).reverse();\n  else       vector(ret,n) = vector(x,n, incx);\n  return ret;\n}\n\ntemplate<typename T>\nT* copy_back(T* x_cpy, T* x, int n, int incx)\n{\n  if(x_cpy==x)\n    return 0;\n\n  if(incx<0) vector(x,n,-incx).reverse() = vector(x_cpy,n);\n  else       vector(x,n, incx)           = vector(x_cpy,n);\n  return x_cpy;\n}\n\n#define EIGEN_BLAS_FUNC(X) EIGEN_CAT(eigen_,X)\n\nstatic inline int EIGEN_BLAS_FUNC(gemm)(char *opa, char *opb, int *m, int *n, int *k, RealScalar *palpha, RealScalar *pa, int *lda, RealScalar *pb, int *ldb, RealScalar *pbeta, RealScalar *pc, int *ldc)\n{\n//   std::cerr << \"in gemm \" << *opa << \" \" << *opb << \" \" << *m << \" \" << *n << \" \" << *k << \" \" << *lda << \" \" << *ldb << \" \" << *ldc << \" \" << *palpha << \" \" << *pbeta << \"\\n\";\n  typedef void (*functype)(DenseIndex, DenseIndex, DenseIndex, const Scalar *, DenseIndex, const Scalar *, DenseIndex, Scalar *, DenseIndex, Scalar, internal::level3_blocking<Scalar,Scalar>&, Eigen::internal::GemmParallelInfo<DenseIndex>*);\n  static functype func[12];\n\n  static bool init = false;\n  if(!init)\n  {\n    for(int kk=0; kk<12; ++kk)\n      func[kk] = 0;\n    func[NOTR  | (NOTR << 2)] = (internal::general_matrix_matrix_product<DenseIndex,Scalar,ColMajor,false,Scalar,ColMajor,false,ColMajor>::run);\n    func[TR    | (NOTR << 2)] = (internal::general_matrix_matrix_product<DenseIndex,Scalar,RowMajor,false,Scalar,ColMajor,false,ColMajor>::run);\n    func[ADJ   | (NOTR << 2)] = (internal::general_matrix_matrix_product<DenseIndex,Scalar,RowMajor,Conj, Scalar,ColMajor,false,ColMajor>::run);\n    func[NOTR  | (TR   << 2)] = (internal::general_matrix_matrix_product<DenseIndex,Scalar,ColMajor,false,Scalar,RowMajor,false,ColMajor>::run);\n    func[TR    | (TR   << 2)] = (internal::general_matrix_matrix_product<DenseIndex,Scalar,RowMajor,false,Scalar,RowMajor,false,ColMajor>::run);\n    func[ADJ   | (TR   << 2)] = (internal::general_matrix_matrix_product<DenseIndex,Scalar,RowMajor,Conj, Scalar,RowMajor,false,ColMajor>::run);\n    func[NOTR  | (ADJ  << 2)] = (internal::general_matrix_matrix_product<DenseIndex,Scalar,ColMajor,false,Scalar,RowMajor,Conj, ColMajor>::run);\n    func[TR    | (ADJ  << 2)] = (internal::general_matrix_matrix_product<DenseIndex,Scalar,RowMajor,false,Scalar,RowMajor,Conj, ColMajor>::run);\n    func[ADJ   | (ADJ  << 2)] = (internal::general_matrix_matrix_product<DenseIndex,Scalar,RowMajor,Conj, Scalar,RowMajor,Conj, ColMajor>::run);\n    init = true;\n  }\n\n  Scalar* a = reinterpret_cast<Scalar*>(pa);\n  Scalar* b = reinterpret_cast<Scalar*>(pb);\n  Scalar* c = reinterpret_cast<Scalar*>(pc);\n  Scalar alpha  = *reinterpret_cast<Scalar*>(palpha);\n  Scalar beta   = *reinterpret_cast<Scalar*>(pbeta);\n\n  if(beta!=Scalar(1))\n  {\n    if(beta==Scalar(0)) matrix(c, *m, *n, *ldc).setZero();\n    else                matrix(c, *m, *n, *ldc) *= beta;\n  }\n\n  internal::gemm_blocking_space<ColMajor,Scalar,Scalar,Dynamic,Dynamic,Dynamic> blocking(*m,*n,*k, 1, false);\n\n  int code = OP(*opa) | (OP(*opb) << 2);\n  func[code](*m, *n, *k, a, *lda, b, *ldb, c, *ldc, alpha, blocking, 0);\n  return 0;\n}\n\n", "meta": {"hexsha": "38101f4f688f677f6299d2f8389171837824d3b1", "size": 5750, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "BlasLibrary/Source/Eigen/BlasHeader.hpp", "max_stars_repo_name": "DoDoENT/jtorch", "max_stars_repo_head_hexsha": "2f92d397c8dc6fd7f17fe682cb7ce38314086c8e", "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": "BlasLibrary/Source/Eigen/BlasHeader.hpp", "max_issues_repo_name": "DoDoENT/jtorch", "max_issues_repo_head_hexsha": "2f92d397c8dc6fd7f17fe682cb7ce38314086c8e", "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": "BlasLibrary/Source/Eigen/BlasHeader.hpp", "max_forks_repo_name": "DoDoENT/jtorch", "max_forks_repo_head_hexsha": "2f92d397c8dc6fd7f17fe682cb7ce38314086c8e", "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.8484848485, "max_line_length": 240, "alphanum_fraction": 0.6276521739, "num_tokens": 1797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.25199576865361295}}
{"text": "/* Copyright (C) 2013 Ion Torrent Systems, Inc. All Rights Reserved */\n\n#include <iostream>\n#include <algorithm>\n#include \"DfcCompr.h\"\n//#include \"Utils.h\"\n#include <malloc.h>\n#include <cmath>\n// DFC doesn't use anything from the Eigen library\n//#define EIGEN_USE_MKL_ALL 1\n//#include <Eigen/Dense>\n//#include <Eigen/LU>\n\nusing namespace std;\n//using namespace Eigen;\n\n\n/***\n The DFT engine needs to be kept in sync with any changes to the number of frames.\n*/\nint DfcCompr::SetNumFrames(int frames)\n{\n    if ((frames > 0) && (frames != n_frames))\n    {\n        n_frames = frames;\n        DFT.SetPts(frames);\n    }\n\n    return n_frames;\n}\n\n\n/***\n Range check the new window length value and generate the new window coefficients.\n Window lengths should be relatively short.\n*/\nint DfcCompr::SetWindowLength(int length)\n{\n    if ((length >= 0) && (length < (n_frames/4)) && (length != winParamLen))\n    {\n        winParamLen = length;\n        GenerateWindow();\n    }\n\n    return winParamLen;\n}\n\n\n/***\n Range check the new window alpha value and generat the new window coefficients.\n*/\nfloat DfcCompr::SetWindowAlpha(float alpha)\n{\n    if ((alpha >= 0.0f) && (alpha <= 3.0f) && (alpha != winParamAlpha))\n    {\n        winParamAlpha = alpha;\n        GenerateWindow();\n    }\n\n    return winParamAlpha;\n}\n\n\n/***\n Generate a new set of Gaussian window coefficients based on the current set of\n window length and alpha configuration parameters.\n*/\nvoid DfcCompr::GenerateWindow()\n{\n    // setup vectors to store compression and decompression windows\n    windowCompress.resize(winParamLen*2);\n    windowExpand.resize(winParamLen*2);\n\n    float halfN = static_cast<float>(winParamLen);\n    float n     = 0.5f-halfN;  // starting at -(N-1)/2\n    int   idx, maxIdx;\n    float an_sq, val, oneOnVal;\n\n    maxIdx = (winParamLen * 2) - 1;\n    for (idx = 0; idx < winParamLen; ++idx)\n    {\n        an_sq    = winParamAlpha * (n / halfN);\n        val      = exp((-0.5f) * (an_sq * an_sq));\n        oneOnVal = 1.0f / val;\n        n       += 1.0f;  // setup n for next loop iteration\n        windowCompress[idx]        = val;\n        windowCompress[maxIdx-idx] = val;  // exploit window symmetry\n        windowExpand[idx]          = oneOnVal;\n        windowExpand[maxIdx-idx]   = oneOnVal;\n    }\n\n}\n\n\n/***\n  Decompose the image data into a set of basis vectors and each well's projection\n  onto them.\n  @param n_wells - number of wells in the image patch\n  @param n_frame - number of frames in this image patch.\n  @param image - Same order as RawImage structure. Individual wells of data in frame, row, col major order so\n                 value(row_i,col_j,frame_k) = image[row_i * ncol + col_j + (nrow * ncol * frame_k)]\n  @param n_sample_wells - number of wells in the sample of the patch\n  @param image_sample - sample of image above for vectors and such\n  @param compressed - output of a lossy compressed patch\n*/\nvoid DfcCompr::LossyCompress(float *image)\n{\n    //////////////////////////////////////////\n    // Temporary scratch_pad memory allocation\n    if (scratch_pad == NULL) scratch_pad = new float[n_wells*n_basis*2];\n    //////////////////////////////////////////\n\n    int wellIdx, frameIdx;\n    float tmpWell[n_frames];\n    register float tmpSum;\n    register int offset, winIdx;\n    float * __restrict dftPtrI = &scratch_pad[0];\n    float * __restrict dftPtrQ = &scratch_pad[n_wells*n_basis];\n    float deltaMagI[n_basis];\n    float deltaMagQ[n_basis];\n\n    // Initialize keyframe\n    for (frameIdx = 0; frameIdx < n_basis; ++frameIdx)\n    {\n        keyFrameI[frameIdx] = 0.0f;\n        keyFrameQ[frameIdx] = 0.0f;\n    }\n\n    for (wellIdx = 0, offset = 0; wellIdx < n_wells; ++wellIdx)\n    {\n        // Step 1a - extract the next well from the image cube\n        tmpSum = 0.0f;\n        winIdx = 0;\n        for (frameIdx = 0; frameIdx < n_frames; ++frameIdx)\n        {\n            tmpWell[frameIdx] = image[(frameIdx*n_wells)+wellIdx];\n            tmpSum           += image[(frameIdx*n_wells)+wellIdx];\n        }\n        // Step 1b - remove DC offset and apply windowing to each well\n        tmpSum /= static_cast<float>(n_frames);  // DC offset\n        // Apply front part of window\n        for (frameIdx = 0; frameIdx < winParamLen; ++frameIdx)\n        {\n            tmpWell[frameIdx] -= tmpSum;\n            tmpWell[frameIdx] *= windowCompress[winIdx++];\n        }\n        // Middle part (window is unity)\n        for (; frameIdx < (n_frames-winParamLen); ++frameIdx)\n            tmpWell[frameIdx] -= tmpSum;\n        // Apply back part of window\n        for (; frameIdx < n_frames; ++frameIdx)\n        {\n            tmpWell[frameIdx] -= tmpSum;\n            tmpWell[frameIdx] *= windowCompress[winIdx++];\n        }\n        // Step 2 - Compute partial DFT\n        // store for deltas and accumulate for keyframe\n        winIdx = n_basis * wellIdx;\n        DFT.PartialDFT(1, static_cast<unsigned int>(n_basis), &tmpWell[0], &dftPtrI[winIdx], &dftPtrQ[winIdx]);\n        for (frameIdx = 0; frameIdx < n_basis; ++frameIdx, ++offset)\n        {\n            keyFrameI[frameIdx] += dftPtrI[offset];\n            keyFrameQ[frameIdx] += dftPtrQ[offset];\n        }\n    }\n\n    // Step 3 - Convert accumulated spectrum into mean keyframe and initialize\n    // maximum delta magnitude vector\n    for (frameIdx = 0; frameIdx < n_basis; ++frameIdx)\n    {\n        keyFrameI[frameIdx] /= static_cast<float>(n_wells);\n        keyFrameQ[frameIdx] /= static_cast<float>(n_wells);\n        deltaMagI[frameIdx]  = 0.0f;\n        deltaMagQ[frameIdx]  = 0.0f;\n    }\n\n    // Step 4 - Calculate the correlation statistics and emphasis vector needed to\n    // populate the bits per frequency element vector\n    Emphasis();\n\n    // Step 5 - Convert DFT data from absolute to raw delta, keeping maximum\n    // component magnitude observed for each frequency component along the way\n    for (wellIdx = 0, offset = 0; wellIdx < n_wells; ++wellIdx)\n        // May be able to use SSE/AVX vector acceleration here to process multiple frequency elements in parallel\n        for (frameIdx = 0; frameIdx < n_basis; ++frameIdx, ++offset)\n        {\n            dftPtrI[offset] -= keyFrameI[frameIdx];\n            dftPtrQ[offset] -= keyFrameQ[frameIdx];\n            if (deltaMagI[frameIdx] < abs(dftPtrI[offset])) deltaMagI[frameIdx] = abs(dftPtrI[offset]);  // update maximum observed real magnitude vector\n            if (deltaMagQ[frameIdx] < abs(dftPtrQ[offset])) deltaMagQ[frameIdx] = abs(dftPtrQ[offset]);  // update maximum observed imaginary magnitude vector\n        }\n\n    // Populate the scale vectors\n    for (frameIdx = 0; frameIdx < n_basis; ++frameIdx)\n    {\n        tmpSum = static_cast<float>((1<<static_cast<int>(bitsPerFreq[frameIdx]-1))-1);\n        scaleVectorI[frameIdx] = deltaMagI[frameIdx] / tmpSum;\n        scaleVectorQ[frameIdx] = deltaMagQ[frameIdx] / tmpSum;\n    }\n\n    // Step 6 - Quantize the spectrum delta values and pack into output vectors\n    for (wellIdx = 0, offset = 0; wellIdx < n_wells; ++wellIdx)\n        // May be able to use SSE/AVX vector acceleration here to process multiple frequency elements in parallel\n        for (frameIdx = 0; frameIdx < n_basis; ++frameIdx, ++offset)\n        {\n            deltaI[offset] = static_cast<short>(round(dftPtrI[offset]/scaleVectorI[frameIdx]));\n            deltaQ[offset] = static_cast<short>(round(dftPtrQ[offset]/scaleVectorQ[frameIdx]));\n        }\n\n    ////////////////////////////////////////////\n    // Temporary scratch_pad memory deallocation\n    delete[] scratch_pad; scratch_pad = NULL;\n    ////////////////////////////////////////////\n}\n\n\n/***\n*/\nvoid DfcCompr::Emphasis()\n{\n    float kernelI[n_basis];\n    float kernelQ[n_basis];\n    float *dftPtrI = &scratch_pad[0];\n    float *dftPtrQ = &scratch_pad[n_wells*n_basis];\n    float *corrI = new float[n_wells*n_basis];  // probably a good idea to make this static or semi-static\n    float *corrQ = new float[n_wells*n_basis];  // probably a good idea to make this static or semi-static\n    register int offset, freqIdx;\n    int   wellIdx;\n    float meanMag[n_basis];\n    float meanAng[n_basis];\n    float varMag[n_basis];\n    float varAng[n_basis];\n    register float delta;\n    float emphasisVector[n_basis];\n    register int bitVal;\n\n    // Generate correlation kernel from keyframe and initialize statistics vectors\n    for (freqIdx = 0; freqIdx < n_basis; ++freqIdx)\n    {\n        kernelI[freqIdx] = keyFrameI[freqIdx];\n        kernelQ[freqIdx] = -keyFrameQ[freqIdx];\n        meanMag[freqIdx] = 0.0f;\n        meanAng[freqIdx] = 0.0f;\n        varMag[freqIdx]  = 0.0f;\n        varAng[freqIdx]  = 0.0f;\n    }\n\n    // Correlate each well spectrum with the complex conjugate of the mean well spectrum\n    for (wellIdx = 0, offset = 0; wellIdx < n_wells; ++wellIdx)\n        // May be able to vectorize the correlation process\n        for (freqIdx = 0; freqIdx < n_basis; ++freqIdx, ++offset)\n        {\n            // DFT data        ==> (a+ib)\n            // kernel          ==> (x+ib)\n            // correlated data ==> (a+ib)(x+iy) = ax+iay+ibx-by = (ax-by)+i(ay+bx)\n            corrI[offset] = dftPtrI[offset]*kernelI[freqIdx]-dftPtrQ[offset]*kernelQ[freqIdx];  // (ax-by)\n            corrQ[offset] = dftPtrI[offset]*kernelQ[freqIdx]+dftPtrQ[offset]*kernelI[freqIdx];  // (ay+bx)\n        }\n\n    // Find mean of magnitude and angle of each frequency element\n    for (wellIdx = 0, offset = 0; wellIdx < n_wells; ++wellIdx)\n        // May be able to vectorize the frequency elements\n        for (freqIdx = 0; freqIdx < n_basis; ++freqIdx, ++offset)\n        {\n            meanMag[freqIdx] += sqrt((corrI[offset]*corrI[offset])+(corrQ[offset]*corrQ[offset]));\n            meanAng[freqIdx] += atan2(corrQ[offset], corrI[offset]);\n        }\n    for (freqIdx = 0; freqIdx < n_basis; ++freqIdx)\n    {\n        meanMag[freqIdx] /= static_cast<float>(n_wells);\n        meanAng[freqIdx] /= static_cast<float>(n_wells);\n    }\n\n    // Find standard deviation (now that we have the mean)\n    for (wellIdx = 0, offset = 0; wellIdx < n_wells; ++wellIdx)\n        // May be able to vectorize the frequency elements\n        for (freqIdx = 0; freqIdx < n_basis; ++freqIdx, ++offset)\n        {\n            delta = sqrt((corrI[offset]*corrI[offset])+(corrQ[offset]*corrQ[offset])) - meanMag[freqIdx];\n            varMag[freqIdx] += delta * delta;  // accumulate magnitude variance\n            delta = atan2(corrQ[offset], corrI[offset]) - meanAng[freqIdx];\n            varAng[freqIdx] += delta * delta;  // accumulate angle variance\n        }\n\n    // Finished with correlation data (don't need to release once we make this block of memory static/semi-static)\n    delete[] corrI;\n    delete[] corrQ;\n\n    // Convert accumulated variance to raw emphasis (original Matlab calculation\n    // uses standard deviation rather than variance, but that uses an additional\n    // sqrt step that has been optimized out here)\n    for (freqIdx = 0, delta = 0.0f; freqIdx < n_basis; ++freqIdx)\n    {\n        emphasisVector[freqIdx] = sqrt((varMag[freqIdx]*varAng[freqIdx])/static_cast<float>(n_wells));\n        if (emphasisVector[freqIdx] > delta)\n            delta = emphasisVector[freqIdx];  // keep the maximum value for normalization\n    }\n    \n    // Normalize the emphasis vector and convert it to bits per frequency element\n    for (freqIdx = 0; freqIdx < n_basis; ++freqIdx)\n    {\n        // calculate the number of magnitude bits to allocate (log will always return zero or a negative value)\n        bitVal = static_cast<int>(static_cast<float>(n_maxBits)+ceil(log2(emphasisVector[freqIdx]/delta)));\n        if (bitVal < n_minBits) bitVal = n_minBits;  // ensure at least the minimum number of magnitude bits are allocated\n        ++bitVal;  // add the sign bit\n        bitsPerFreq[freqIdx] = static_cast<unsigned char>(bitVal);\n    }\n}\n\n\n/***\n Reconstruct the image data from the compressed frequency domain vectors.\n @param n_wells - number of wells in the image patch\n @param n_frame - number of frames in this image patch.\n @param image   - Same order as RawImage structure. Individual wells of data in frame, row, col major order so\n                  value(row_i,col_j,frame_k) = image[row_i * ncol + col_j + (nrow * ncol * frame_k)]\n*/\nvoid DfcCompr::LossyUncompress(float *image)\n{\n    float wellBufI[n_basis];\n    float wellBufQ[n_basis];\n    float tmpBuf[n_frames];\n    int   wellIdx, frameIdx;\n    register int offset, winIdx;\n\n    for (wellIdx = 0, offset = 0; wellIdx < n_wells; ++wellIdx)\n    {\n        // Reconstruct partial spectrum from keyframe, delta and scale information\n        for (frameIdx = 0; frameIdx < n_basis; ++frameIdx, ++offset)\n        {\n            wellBufI[frameIdx] = keyFrameI[frameIdx] + scaleVectorI[frameIdx]*static_cast<float>(deltaI[offset]);\n            wellBufQ[frameIdx] = keyFrameQ[frameIdx] + scaleVectorQ[frameIdx]*static_cast<float>(deltaQ[offset]);\n        }\n        // Reconstruct time domain signal from partial spectrum using IDFT\n        DFT.PartialIDFT(1, n_basis, &tmpBuf[0], &wellBufI[0], &wellBufQ[0]);\n        // Store reconstructed values into the image cube\n        for (frameIdx = 0, winIdx = 0; frameIdx < winParamLen; ++frameIdx)\n            image[(frameIdx*n_wells)+wellIdx] = tmpBuf[frameIdx] * windowExpand[winIdx++];\n        for (; frameIdx < (n_frames-winParamLen); ++frameIdx)\n            image[(frameIdx*n_wells)+wellIdx] = tmpBuf[frameIdx];\n        for (; frameIdx < n_frames; ++frameIdx)\n            image[(frameIdx*n_wells)+wellIdx] = tmpBuf[frameIdx] * windowExpand[winIdx++];\n    }\n}\n\n\n/*****************************************************************************/\n\n/***\n Map the memory blocks and call LossyCompress.\n*/\nvoid DfcComprWrapper::LossyCompress(float *image)\n{\n    SetupPointers();\n    dfc.LossyCompress(image);\n};\n\n\n/***\n Map the memory blocks and call LossyUncompress.\n*/\nvoid DfcComprWrapper::LossyUncompress(float *image)\n{\n    SetupPointers();\n    dfc.LossyUncompress(image);\n};\n\n\n/***\n Do some evil pointer arithmetic to map the DFC header and payload data vectors\n into the basis_vectors and coefficients memory blocks.\n*/\nvoid DfcComprWrapper::SetupPointers()\n{\n    void *hdrPtr = reinterpret_cast<void *>(basis_vectors);\n    void *dtrPtr = reinterpret_cast<void *>(coefficients);\n    int   offset = sizeof(float) * dfc.n_basis;\n\n    // Map the header vectors into the basis_vectors memory block\n    dfc.keyFrameI    = reinterpret_cast<float *>(hdrPtr);\n    dfc.keyFrameQ    = reinterpret_cast<float *>(hdrPtr) + offset;\n    dfc.scaleVectorI = reinterpret_cast<float *>(hdrPtr) + 2*offset;\n    dfc.scaleVectorQ = reinterpret_cast<float *>(hdrPtr) + 3*offset;\n    dfc.bitsPerFreq  = reinterpret_cast<unsigned char *>(hdrPtr) + 4*offset;\n\n    // Map the delta data into the coefficients memory block\n    offset     = sizeof(short) * dfc.n_basis * dfc.n_wells;\n    dfc.deltaI = reinterpret_cast<short *>(dtrPtr);\n    dfc.deltaQ = reinterpret_cast<short *>(dtrPtr) + offset;\n}\n", "meta": {"hexsha": "6d2860c2d1b94e21bdd084a7ed4df8aae73a40ff", "size": 14929, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Analysis/Image/DfcCompr.cpp", "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/Image/DfcCompr.cpp", "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/Image/DfcCompr.cpp", "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": 38.1815856777, "max_line_length": 158, "alphanum_fraction": 0.6332641168, "num_tokens": 3969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2519957686536129}}
{"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//   IR = 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_SFG_MAP_HPP_\n#define _Z_SFG_MAP_HPP_\n\nclass SfgMap:\n  public FrequencyMap {\n public:\n  inline SfgMap(const MoleculeGroup& group, const Chromophore chromophore,\n                const double timestep, const int correlation_length = 200,\n                const double slab_center_z = 0.0)\n      : FrequencyMap(group, chromophore, timestep, correlation_length),\n        slab_center_z_(slab_center_z) {\n    mu_01_ = arma::zeros<arma::mat>(num_chromophores(), steps_guess_);\n    alpha_01_ = arma::zeros<arma::mat>(num_chromophores(), steps_guess_);\n  }\n\n private:\n  arma::mat mu_01_;\n  arma::mat alpha_01_;\n  double slab_center_z_;\n  static const double r_switch_ = 0.4;\n  static const double r_switch_squared_ = 0.16;\n  static const double r_switch_cubed_ = 0.064;\n\n  inline void ResizeArrays() {\n    omega_01_.resize(num_chromophores(), steps_guess_);\n    mu_01_.resize(num_chromophores(), steps_guess_);\n    alpha_01_.resize(num_chromophores(), steps_guess_);\n  }\n\n  inline double MuOrAlphaProduct(const int chromophore, const int corr_start,\n                                 const int i_corr) {\n    return mu_01_(chromophore,corr_start)*mu_01_(chromophore,corr_start+i_corr);\n  }\n\n  // Calculates switching function needed for SFG calculations in slab geometry.\n  // Allows smooth switching between contribution to upper and lower surface as\n  // one moves through the slab.\n  double SwitchingFunction(const arma::rowvec& box);\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": "807bf9e29ede5331ddc7ed3cce68df129cdc79d2", "size": 3269, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/z_sfg_map.hpp", "max_stars_repo_name": "thekannman/z_sfg", "max_stars_repo_head_hexsha": "312b04283b10c8c32e5b0adeed6d9e5959faa1c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-06-11T19:36:58.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-28T12:58:31.000Z", "max_issues_repo_path": "include/z_sfg_map.hpp", "max_issues_repo_name": "thekannman/z_sfg", "max_issues_repo_head_hexsha": "312b04283b10c8c32e5b0adeed6d9e5959faa1c5", "max_issues_repo_licenses": ["MIT"], "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_sfg_map.hpp", "max_forks_repo_name": "thekannman/z_sfg", "max_forks_repo_head_hexsha": "312b04283b10c8c32e5b0adeed6d9e5959faa1c5", "max_forks_repo_licenses": ["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.9166666667, "max_line_length": 80, "alphanum_fraction": 0.73875803, "num_tokens": 791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.25199576259199097}}
{"text": "#include \"teca_ar_detect.h\"\n\n#include \"teca_cartesian_mesh.h\"\n#include \"teca_variant_array.h\"\n#include \"teca_table.h\"\n#include \"teca_calendar.h\"\n#include \"teca_cartesian_mesh_util.h\"\n\n#include <iostream>\n#include <sstream>\n#include <limits>\n#include <algorithm>\n#include <cmath>\n\n#if defined(TECA_HAS_BOOST)\n#include <boost/program_options.hpp>\n#endif\n\nusing std::ostream;\nusing std::vector;\nusing std::string;\nusing std::ostringstream;\nusing std::cerr;\nusing std::endl;\n\n#define TECA_DEBUG 0\n#if TECA_DEBUG > 0 && defined(TECA_HAS_VTK)\n#include \"teca_vtk_cartesian_mesh_writer.h\"\n#include \"teca_programmable_source.h\"\nint write_mesh(\n    const const_p_teca_cartesian_mesh &mesh,\n    const const_p_teca_variant_array &vapor,\n    const const_p_teca_variant_array &thres,\n    const const_p_teca_variant_array &ccomp,\n    const const_p_teca_variant_array &lsmask,\n    const std::string &base_name);\n#endif\n\n// a description of the atmospheric river\nstruct atmospheric_river\n{\n    atmospheric_river() :\n        pe(false), length(0.0),\n        min_width(0.0), max_width(0.0),\n        end_top_lat(0.0), end_top_lon(0.0),\n        end_bot_lat(0.0), end_bot_lon(0.0)\n    {}\n\n    bool pe;\n    double length;\n    double min_width;\n    double max_width;\n    double end_top_lat;\n    double end_top_lon;\n    double end_bot_lat;\n    double end_bot_lon;\n};\n\nostream &operator<<(ostream &os, const atmospheric_river &ar)\n{\n    os << \" type=\" << (ar.pe ? \"PE\" : \"AR\")\n        << \" length=\" << ar.length\n        << \" width=\" << ar.min_width << \", \" << ar.max_width\n        << \" bounds=\" << ar.end_bot_lon << \", \" << ar.end_bot_lat << \", \"\n        << ar.end_top_lon << \", \" << ar.end_top_lat;\n    return os;\n}\n\nunsigned sauf(const unsigned nrow, const unsigned ncol, unsigned int *image);\n\nbool ar_detect(\n    const_p_teca_variant_array lat,\n    const_p_teca_variant_array lon,\n    const_p_teca_variant_array land_sea_mask,\n    const_p_teca_unsigned_int_array con_comp,\n    unsigned long n_comp,\n    double river_start_lat,\n    double river_start_lon,\n    double river_end_lat_low,\n    double river_end_lon_low,\n    double river_end_lat_high,\n    double river_end_lon_high,\n    double percent_in_mesh,\n    double river_width,\n    double river_length,\n    double land_threshold_low,\n    double land_threshold_high,\n    atmospheric_river &ar);\n\n// set locations in the output where the input array\n// has values within the low high range.\ntemplate <typename T>\nvoid threshold(\n    const T *input, unsigned int *output,\n    size_t n_vals, T low, T high)\n{\n    for (size_t i = 0; i < n_vals; ++i)\n        output[i] = ((input[i] >= low) && (input[i] <= high)) ? 1 : 0;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n// --------------------------------------------------------------------------\nteca_ar_detect::teca_ar_detect() :\n    water_vapor_variable(\"prw\"),\n    land_sea_mask_variable(\"\"),\n    low_water_vapor_threshold(20),\n    high_water_vapor_threshold(75),\n    search_lat_low(19.0),\n    search_lon_low(180.0),\n    search_lat_high(56.0),\n    search_lon_high(250.0),\n    river_start_lat_low(18.0),\n    river_start_lon_low(180.0),\n    river_end_lat_low(29.0),\n    river_end_lon_low(233.0),\n    river_end_lat_high(56.0),\n    river_end_lon_high(238.0),\n    percent_in_mesh(5.0),\n    river_width(1250.0),\n    river_length(2000.0),\n    land_threshold_low(1.0),\n    land_threshold_high(std::numeric_limits<double>::max())\n{\n    this->set_number_of_input_connections(1);\n    this->set_number_of_output_ports(1);\n}\n\n// --------------------------------------------------------------------------\nteca_ar_detect::~teca_ar_detect()\n{}\n\n#if defined(TECA_HAS_BOOST)\n\n// --------------------------------------------------------------------------\nvoid teca_ar_detect::get_properties_description(\n    const string &prefix, options_description &opts)\n{\n    options_description ard_opts(\"Options for \" + prefix + \"(teca_ar_detect)\");\n\n    ard_opts.add_options()\n        TECA_POPTS_GET(string, prefix, water_vapor_variable, \"name of variable containing water vapor values\")\n        TECA_POPTS_GET(double, prefix, low_water_vapor_threshold, \"low water vapor threshold\")\n        TECA_POPTS_GET(double, prefix, high_water_vapor_threshold, \"high water vapor threshold\")\n        TECA_POPTS_GET(double, prefix, search_lat_low, \"search space low latitude\")\n        TECA_POPTS_GET(double, prefix, search_lon_low, \"search space low longitude\")\n        TECA_POPTS_GET(double, prefix, search_lat_high, \"search space high latitude\")\n        TECA_POPTS_GET(double, prefix, search_lon_high, \"search space high longitude\")\n        TECA_POPTS_GET(double, prefix, river_start_lat_low, \"latitude used to classify as AR or PE\")\n        TECA_POPTS_GET(double, prefix, river_start_lon_low, \"longitude used to classify as AR or PE\")\n        TECA_POPTS_GET(double, prefix, river_end_lat_low, \"CA coastal region low latitude\")\n        TECA_POPTS_GET(double, prefix, river_end_lon_low, \"CA coastal region low longitude\")\n        TECA_POPTS_GET(double, prefix, river_end_lat_high, \"CA coastal region high latitude\")\n        TECA_POPTS_GET(double, prefix, river_end_lon_high, \"CA coastal region high longitude\")\n        TECA_POPTS_GET(double, prefix, percent_in_mesh, \"size of river in relation to search space area\")\n        TECA_POPTS_GET(double, prefix, river_width, \"river width\")\n        TECA_POPTS_GET(double, prefix, river_length, \"river length\")\n        TECA_POPTS_GET(string, prefix, land_sea_mask_variable, \"name of variable containing land-sea mask values\")\n        TECA_POPTS_GET(double, prefix, land_threshold_low, \"low land value\")\n        TECA_POPTS_GET(double, prefix, land_threshold_high, \"high land value\")\n        ;\n\n    opts.add(ard_opts);\n}\n\n// --------------------------------------------------------------------------\nvoid teca_ar_detect::set_properties(\n    const string &prefix, variables_map &opts)\n{\n    TECA_POPTS_SET(opts, string, prefix, water_vapor_variable)\n    TECA_POPTS_SET(opts, double, prefix, low_water_vapor_threshold)\n    TECA_POPTS_SET(opts, double, prefix, high_water_vapor_threshold)\n    TECA_POPTS_SET(opts, double, prefix, search_lat_low)\n    TECA_POPTS_SET(opts, double, prefix, search_lon_low)\n    TECA_POPTS_SET(opts, double, prefix, search_lat_high)\n    TECA_POPTS_SET(opts, double, prefix, search_lon_high)\n    TECA_POPTS_SET(opts, double, prefix, river_start_lat_low)\n    TECA_POPTS_SET(opts, double, prefix, river_start_lon_low)\n    TECA_POPTS_SET(opts, double, prefix, river_end_lat_low)\n    TECA_POPTS_SET(opts, double, prefix, river_end_lon_low)\n    TECA_POPTS_SET(opts, double, prefix, river_end_lat_high)\n    TECA_POPTS_SET(opts, double, prefix, river_end_lon_high)\n    TECA_POPTS_SET(opts, double, prefix, percent_in_mesh)\n    TECA_POPTS_SET(opts, double, prefix, river_width)\n    TECA_POPTS_SET(opts, double, prefix, river_length)\n    TECA_POPTS_SET(opts, string, prefix, land_sea_mask_variable)\n    TECA_POPTS_SET(opts, double, prefix, land_threshold_low)\n    TECA_POPTS_SET(opts, double, prefix, land_threshold_high)\n}\n\n#endif\n\n// --------------------------------------------------------------------------\nteca_metadata teca_ar_detect::get_output_metadata(\n    unsigned int port,\n    const std::vector<teca_metadata> &input_md)\n{\n#if TECA_DEBUG > 1\n    cerr << teca_parallel_id()\n        << \"teca_ar_detect::get_output_metadata\" << endl;\n#endif\n    (void)port;\n\n    teca_metadata output_md(input_md[0]);\n    return output_md;\n}\n\n// --------------------------------------------------------------------------\nint teca_ar_detect::get_active_extent(\n    p_teca_variant_array lat,\n    p_teca_variant_array lon,\n    std::vector<unsigned long> &extent) const\n{\n    extent.resize(6, 0l);\n\n    TEMPLATE_DISPATCH_FP(\n        teca_variant_array_impl,\n        lat.get(),\n\n        unsigned long high_j = lat->size() - 1;\n        NT *p_lat = std::dynamic_pointer_cast<TT>(lat)->get();\n\n        unsigned long high_i = lon->size() - 1;\n        NT *p_lon = std::dynamic_pointer_cast<TT>(lon)->get();\n\n        if (index_of(p_lon, 0, high_i, static_cast<NT>(this->search_lon_low), false, extent[0])\n            || index_of(p_lon, 0, high_i, static_cast<NT>(this->search_lon_high), true, extent[1])\n            || index_of(p_lat, 0, high_j, static_cast<NT>(this->search_lat_low), false, extent[2])\n            || index_of(p_lat, 0, high_j, static_cast<NT>(this->search_lat_high), true, extent[3]))\n        {\n            TECA_ERROR(\n                << \"search space [\"\n                << this->search_lon_low << \", \" << this->search_lon_high << \", \"\n                << this->search_lat_low << \", \" << this->search_lat_high\n                << \"] is not contained in the current dataset bounds [\"\n                << p_lon[0] << \", \" << p_lon[high_i] << \", \"\n                << p_lat[0] << \", \" << p_lat[high_j] << \"]\")\n            return -1;\n        }\n        return 0;\n        )\n\n    TECA_ERROR(\"invalid coordinate array type\")\n    return -1;\n}\n\n// --------------------------------------------------------------------------\nstd::vector<teca_metadata> teca_ar_detect::get_upstream_request(\n    unsigned int port,\n    const std::vector<teca_metadata> &input_md,\n    const teca_metadata &request)\n{\n#if TECA_DEBUG > 1\n    cerr << teca_parallel_id()\n        << \"teca_ar_detect::get_upstream_request\" << endl;\n#endif\n    (void)port;\n\n    vector<teca_metadata> up_reqs;\n\n    teca_metadata md = input_md[0];\n\n    // locate the extents of the user supplied region of\n    // interest\n    teca_metadata coords;\n    if (md.get(\"coordinates\", coords))\n    {\n        TECA_ERROR(\"metadata is missing \\\"coordinates\\\"\")\n        return up_reqs;\n    }\n\n    p_teca_variant_array lat;\n    p_teca_variant_array lon;\n    if (!(lat = coords.get(\"y\")) || !(lon = coords.get(\"x\")))\n    {\n        TECA_ERROR(\"metadata missing lat lon coordinates\")\n        return up_reqs;\n    }\n\n    vector<unsigned long> extent(6, 0l);\n    if (this->get_active_extent(lat, lon, extent))\n    {\n        TECA_ERROR(\"failed to determine the active extent\")\n        return up_reqs;\n    }\n\n#if TECA_DEBUG > 1\n    cerr << teca_parallel_id() << \"active_bound = \"\n        << this->search_lon_low<< \", \" << this->search_lon_high\n        << \", \" << this->search_lat_low << \", \" << this->search_lat_high\n        << endl;\n    cerr << teca_parallel_id() << \"active_extent = \"\n        << extent[0] << \", \" << extent[1] << \", \" << extent[2] << \", \"\n        << extent[3] << \", \" << extent[4] << \", \" << extent[5] << endl;\n#endif\n\n    // build the request\n    vector<string> arrays;\n    request.get(\"arrays\", arrays);\n    arrays.push_back(this->water_vapor_variable);\n    if (!this->land_sea_mask_variable.empty())\n        arrays.push_back(this->land_sea_mask_variable);\n\n    teca_metadata up_req(request);\n    up_req.insert(\"arrays\", arrays);\n    up_req.insert(\"extent\", extent);\n\n    up_reqs.push_back(up_req);\n    return up_reqs;\n}\n\n// --------------------------------------------------------------------------\nconst_p_teca_dataset teca_ar_detect::execute(\n    unsigned int port,\n    const std::vector<const_p_teca_dataset> &input_data,\n    const teca_metadata &request)\n{\n#if TECA_DEBUG > 1\n    cerr << teca_parallel_id() << \"teca_ar_detect::execute\";\n    this->to_stream(cerr);\n    cerr << endl;\n#endif\n    (void)port;\n    (void)request;\n\n    // get the input dataset\n    const_p_teca_cartesian_mesh mesh\n        = std::dynamic_pointer_cast<const teca_cartesian_mesh>(input_data[0]);\n    if (!mesh)\n    {\n        TECA_ERROR(\"invalid input. teca_cartesian_mesh is required\")\n        return nullptr;\n    }\n\n    // get coordinate arrays\n    const_p_teca_variant_array lat = mesh->get_y_coordinates();\n    const_p_teca_variant_array lon = mesh->get_x_coordinates();\n\n    if (!lon || !lat)\n    {\n        TECA_ERROR(\"invalid mesh. missing lat lon coordinates\")\n        return nullptr;\n    }\n\n    // get land sea mask\n    const_p_teca_variant_array land_sea_mask;\n    if (this->land_sea_mask_variable.empty() ||\n        !(land_sea_mask = mesh->get_point_arrays()->get(this->land_sea_mask_variable)))\n    {\n        // input doesn't have it, generate a stand in such\n        // that land fall criteria will evaluate true\n        size_t n = lat->size()*lon->size();\n        p_teca_double_array lsm = teca_double_array::New(n, this->land_threshold_low);\n        land_sea_mask = lsm;\n    }\n\n    // get time step\n    unsigned long time_step;\n    mesh->get_time_step(time_step);\n\n    // get units\n    std::string units;\n    mesh->get_time_units(units);\n    if ((units.find(\"days since\") == string::npos) || (units.size() < 21))\n    {\n        TECA_ERROR(\"invalid time units\" << endl << units)\n        return nullptr;\n    }\n\n    // base/origin date\n    long base_y = atoi(units.c_str() + 11);\n    long base_m = atoi(units.c_str() + 16);\n    long base_d = atoi(units.c_str() + 19);\n\n    // get calendar\n    std::string calendar;\n    mesh->get_calendar(calendar);\n\n    // compute the current date\n    long curr_y = 0;\n    long curr_m = 0;\n    long curr_d = 0;\n\n    if ((calendar == \"standard\") || (calendar == \"gregorian\"))\n    {\n        // assume units format is \"days since YYYY-MM-DD\"\n        if (!valid_gregorian_date(base_y, base_m, base_d))\n        {\n            TECA_ERROR(\"CF time:units convert to an invalid date\" << endl\n                << units << \" -> \" << base_y << \"-\" << base_m << \"-\" << base_d)\n            return nullptr;\n        }\n        long base_g = gregorian_number(base_y, base_m, base_d);\n\n        // get offset of the current timestep\n        double curr_g = 0.0;\n        mesh->get_time(curr_g);\n\n        // make date calc\n        date_from_gregorian_number(\n            static_cast<long>(curr_g) + base_g, curr_y, curr_m, curr_d);\n    }\n\n#if TECA_DEBUG > 1\n    cerr << teca_parallel_id()\n        << \" \" << time_step << \" \"\n        << curr_y << \"/\" << curr_m << \"/\" << curr_d << endl;\n#endif\n\n    // get water vapor data\n    vector<unsigned long> extent;\n    mesh->get_extent(extent);\n\n    unsigned long num_rows = extent[3] - extent[2] + 1;\n    unsigned long num_cols = extent[1] - extent[0] + 1;\n    unsigned long num_rc = num_rows*num_cols;\n\n    const_p_teca_variant_array water_vapor\n        = mesh->get_point_arrays()->get(this->water_vapor_variable);\n\n    if (!water_vapor)\n    {\n        TECA_ERROR(\n            << \"Dataset missing water vapor variable \\\"\"\n            << this->water_vapor_variable << \"\\\"\")\n        return nullptr;\n    }\n\n    p_teca_table event = teca_table::New();\n\n    event->declare_columns(\n        \"year\", int(), \"month\", int(), \"day\", int(),\n        \"time_step\", long(), \"length\", double(),\n        \"min width\", double(), \"max width\", double(),\n        \"end_top_lat\", double(), \"end_top_lon\", double(),\n        \"end_bot_lat\", double(), \"end_bot_lon\", double(),\n        \"type\", std::string());\n\n    TEMPLATE_DISPATCH(\n        const teca_variant_array_impl,\n        water_vapor.get(),\n\n        const NT *p_wv = dynamic_cast<TT*>(water_vapor.get())->get();\n\n        // threshold\n        p_teca_unsigned_int_array con_comp\n            = teca_unsigned_int_array::New(num_rc, 0);\n\n        unsigned int *p_con_comp = con_comp->get();\n\n        threshold(p_wv, p_con_comp, num_rc,\n            static_cast<NT>(this->low_water_vapor_threshold),\n            static_cast<NT>(this->high_water_vapor_threshold));\n\n#if TECA_DEBUG > 0 && defined(TECA_HAS_VTK)\n        p_teca_variant_array thresh = con_comp->new_copy();\n#endif\n\n        // label\n        int num_comp = sauf(num_rows, num_cols, p_con_comp);\n\n#if TECA_DEBUG > 0 && defined(TECA_HAS_VTK)\n        write_mesh(mesh, water_vapor, thresh, con_comp, land_sea_mask, \"ar_mesh\");\n#endif\n\n        // detect ar\n        atmospheric_river ar;\n        if (num_comp\n            && ar_detect(lat, lon, land_sea_mask, con_comp, num_comp,\n            this->river_start_lat_low, this->river_start_lon_low,\n            this->river_end_lat_low, this->river_end_lon_low,\n            this->river_end_lat_high, this->river_end_lon_high,\n            this->percent_in_mesh, this->river_width,\n            this->river_length, this->land_threshold_low,\n            this->land_threshold_high, ar))\n        {\n#if TECA_DEBUG > 0\n            cerr << teca_parallel_id() << \" event detected \" << time_step\n                << \" \" << curr_y << \"/\" << curr_m << \"/\" << curr_d << endl;\n#endif\n            event << curr_y << curr_m << curr_d << time_step\n                << ar.length << ar.min_width << ar.max_width\n                << ar.end_top_lat << ar.end_top_lon\n                << ar.end_bot_lat << ar.end_bot_lon\n                << std::string(ar.pe ? \"PE\" : \"AR\");\n        }\n        )\n\n    return event;\n}\n\n// --------------------------------------------------------------------------\nvoid teca_ar_detect::to_stream(ostream &os) const\n{\n    os << \" water_vapor_variable=\" << this->water_vapor_variable\n        << \" land_sea_mask_variable=\" << this->land_sea_mask_variable\n        << \" low_water_vapor_threshold=\" << this->low_water_vapor_threshold\n        << \" high_water_vapor_threshold=\" << this->high_water_vapor_threshold\n        << \" river_start_lon_low=\" << this->river_start_lon_low\n        << \" river_start_lat_low=\" << this->river_start_lat_low\n        << \" river_end_lon_low=\" << this->river_end_lon_low\n        << \" river_end_lat_low=\" << this->river_end_lat_low\n        << \" river_end_lon_high=\" << this->river_end_lon_high\n        << \" river_end_lat_high=\" << this->river_end_lat_high\n        << \" percent_in_mesh=\" << this->percent_in_mesh\n        << \" river_width=\" << this->river_width\n        << \" river_length=\" << this->river_length\n        << \" land_threshodl_low=\" << this->land_threshold_low\n        << \" land_threshodl_high=\" << this->land_threshold_high;\n}\n\n\n// Code borrowed from John Wu's sauf.cpp\n// Find the minimal value starting @arg ind.\ninline unsigned afind(const std::vector<unsigned>& equiv,\n              const unsigned ind)\n{\n    unsigned ret = ind;\n    while (equiv[ret] < ret)\n    {\n        ret = equiv[ret];\n    }\n    return ret;\n}\n\n// Set the values starting with @arg ind.\ninline void aset(std::vector<unsigned>& equiv,\n         const unsigned ind, const unsigned val)\n{\n    unsigned i = ind;\n    while (equiv[i] < i)\n    {\n        unsigned j = equiv[i];\n        equiv[i] = val;\n        i = j;\n    }\n    equiv[i] = val;\n}\n\n/*\n* Purpose:        Scan with Array-based Union-Find\n* Return vals:    Number of connected components\n* Description:    SAUF -- Scan with Array-based Union-Find.\n* This is an implementation that follows the decision try to minimize\n* number of neighbors visited and uses the array-based union-find\n* algorithms to minimize work on the union-find data structure.  It works\n* with each pixel/cell of the 2D binary image individually.\n* The 2D binary image is passed to sauf as a unsigned*.  On input, the\n* zero value is treated as the background, and non-zero is treated as\n* object.  On successful completion of this function, the non-zero values\n* in array image is replaced by its label.\n* The return value is the number of components found.\n*/\nunsigned sauf(const unsigned nrow, const unsigned ncol, unsigned *image)\n{\n    const unsigned ncells = ncol * nrow;\n    const unsigned ncp1 = ncol + 1;\n    const unsigned ncm1 = ncol - 1;\n    std::vector<unsigned int> equiv;    // equivalence array\n    unsigned nextLabel = 1;\n\n    equiv.reserve(ncol);\n    equiv.push_back(0);\n\n    // the first cell of the first line\n    if (*image != 0)\n    {\n    *image = nextLabel;\n    equiv.push_back(nextLabel);\n    ++ nextLabel;\n    }\n    // first row of cells\n    for (unsigned i = 1; i < ncol; ++ i)\n    {\n    if (image[i] != 0)\n    {\n        if (image[i-1] != 0)\n        {\n        image[i] = image[i-1];\n        }\n        else\n        {\n        equiv.push_back(nextLabel);\n        image[i] = nextLabel;\n        ++ nextLabel;\n        }\n    }\n    }\n\n    // scan the rest of lines, check neighbor b first\n    for (unsigned j = ncol; j < ncells; j += ncol)\n    {\n    unsigned nc, nd, k, l;\n\n    // the first point of the line has two neighbors, and the two\n    // neighbors must have at most one label (recorded as nc)\n    if (image[j] != 0)\n    {\n        if (image[j-ncm1] != 0)\n        nc = image[j-ncm1];\n        else if (image[j-ncol] != 0)\n        nc = image[j-ncol];\n        else\n        nc = nextLabel;\n        if (nc != nextLabel) { // use existing label\n        nc = equiv[nc];\n        image[j] = nc;\n        }\n        else { // need a new label\n        equiv.push_back(nc);\n        image[j] = nc;\n        ++ nextLabel;\n        }\n    }\n\n    // the rest of the line\n    for (unsigned i = j+1; i < j+ncol; ++ i)\n    {\n        if (image[i] != 0) {\n        if (image[i-ncol] != 0) {\n            nc = image[i-ncol];\n            l = afind(equiv, nc);\n            aset(equiv, nc, l);\n            image[i] = l;\n        }\n        else if (i-ncm1<j && image[i-ncm1] != 0) {\n            nc = image[i-ncm1];\n\n            if (image[i-1] != 0)\n            nd = image[i-1];\n            else if (image[i-ncp1] != 0)\n            nd = image[i-ncp1];\n            else\n            nd = nextLabel;\n            if (nd < nextLabel) {\n            k = afind(equiv, nc);\n            l = afind(equiv, nd);\n            if (l <= k) {\n                aset(equiv, nc, l);\n                aset(equiv, nd, l);\n            }\n            else {\n                l = k;\n                aset(equiv, nc, k);\n                aset(equiv, nd, k);\n            }\n            image[i] = l;\n            }\n            else {\n            l = afind(equiv, nc);\n            aset(equiv, nc, l);\n            image[i] = l;\n            }\n        }\n        else if (image[i-1] != 0) {\n            nc = image[i-1];\n            l = afind(equiv, nc);\n            aset(equiv, nc, l);\n            image[i] = l;\n        }\n        else if (image[i-ncp1] != 0) {\n            nc = image[i-ncp1];\n            l = afind(equiv, nc);\n            aset(equiv, nc, l);\n            image[i] = l;\n        }\n        else { // need a new label\n            equiv.push_back(nextLabel);\n            image[i] = nextLabel;\n            ++ nextLabel;\n        }\n        }\n    }\n    } // for (unsigned j ...\n\n    // phase II: re-number the labels to be consecutive\n    nextLabel = 0;\n    const unsigned nequiv = equiv.size();\n    for (unsigned i = 0; i < nequiv;  ++ i) {\n    if (equiv[i] < i) { // chase one more time\n#if defined(_DEBUG) || defined(DEBUG)\n        std::cout << i << \" final \" << equiv[i] << \" ==> \"\n              << equiv[equiv[i]] << std::endl;\n#endif\n        equiv[i] = equiv[equiv[i]];\n    }\n    else { // change to the next smallest unused label\n#if defined(_DEBUG) || defined(DEBUG)\n        std::cout << i << \" final \" << equiv[i] << \" ==> \"\n              << nextLabel << std::endl;\n#endif\n        equiv[i] = nextLabel;\n        ++ nextLabel;\n    }\n    }\n\n    if (nextLabel < nequiv) {// relabel all cells to their minimal labels\n    for (unsigned i = 0; i < ncells; ++ i)\n        image[i] = equiv[image[i]];\n    }\n\n#if defined(_DEBUG) || defined(DEBUG)\n    std::cout << \"sauf(\" << nrow << \", \" << ncol << \") assigned \"\n          << nextLabel-1 << \" label\" << (nextLabel>2?\"s\":\"\")\n          << \", used \" << nequiv << \" provisional labels\"\n          << std::endl;\n#endif\n    return nextLabel-1;\n}\n\n// do any of the detected points meet the river start\n// criteria. retrun true if so.\ntemplate<typename T>\nbool river_start_criteria_lat(\n    const vector<int> &con_comp_r,\n    const T *p_lat,\n    T river_start_lat)\n{\n    unsigned long n = con_comp_r.size();\n    for (unsigned long q = 0; q < n; ++q)\n    {\n        if (p_lat[con_comp_r[q]] >= river_start_lat)\n            return true;\n    }\n    return false;\n}\n\n// do any of the detected points meet the river start\n// criteria. retrun true if so.\ntemplate<typename T>\nbool river_start_criteria_lon(\n    const vector<int> &con_comp_c,\n    const T *p_lon,\n    T river_start_lon)\n{\n    unsigned long n = con_comp_c.size();\n    for (unsigned long q = 0; q < n; ++q)\n    {\n        if (p_lon[con_comp_c[q]] >= river_start_lon)\n            return true;\n    }\n    return false;\n}\n\n// helper return true if the start criteria is\n// met, and classifies the ar as PE if it starts\n// in the bottom boundary.\ntemplate<typename T>\nbool river_start_criteria(\n    const vector<int> &con_comp_r,\n    const vector<int> &con_comp_c,\n    const T *p_lat,\n    const T *p_lon,\n    T start_lat,\n    T start_lon,\n    atmospheric_river &ar)\n{\n    return\n         ((ar.pe = river_start_criteria_lat(con_comp_r, p_lat, start_lat))\n         || river_start_criteria_lon(con_comp_c, p_lon, start_lon));\n}\n\n// do any of the detected points meet the river end\n// criteria? (ie. does it hit the west coasts?) if so\n// store a bounding box covering the river and return\n// true.\ntemplate<typename T>\nbool river_end_criteria(\n    const vector<int> &con_comp_r,\n    const vector<int> &con_comp_c,\n    const T *p_lat,\n    const T *p_lon,\n    T river_end_lat_low,\n    T river_end_lon_low,\n    T river_end_lat_high,\n    T river_end_lon_high,\n    atmospheric_river &ar)\n{\n    bool end_criteria = false;\n\n    vector<int> end_col_idx;\n\n    unsigned int count = con_comp_r.size();\n    for (unsigned int i = 0; i < count; ++i)\n    {\n        // approximate land mask boundaries for the western coast of the US,\n        T lon_val = p_lon[con_comp_c[i]];\n        if ((lon_val >= river_end_lon_low) && (lon_val <= river_end_lon_high))\n            end_col_idx.push_back(i);\n    }\n\n    // look for rows that fall between lat boundaries\n    T top_lat = T();\n    T top_lon = T();\n    T bot_lat = T();\n    T bot_lon = T();\n\n    bool top_touch = false;\n    unsigned int end_col_count = end_col_idx.size();\n    for (unsigned int i = 0; i < end_col_count; ++i)\n    {\n        // approximate land mask boundaries for the western coast of the US,\n        T lat_val = p_lat[con_comp_r[end_col_idx[i]]];\n        if ((lat_val >= river_end_lat_low) && (lat_val <= river_end_lat_high))\n        {\n            T lon_val = p_lon[con_comp_c[end_col_idx[i]]];\n            end_criteria = true;\n            if (!top_touch)\n            {\n                top_touch = true;\n                top_lat = lat_val;\n                top_lon = lon_val;\n            }\n            bot_lat = lat_val;\n            bot_lon = lon_val;\n        }\n    }\n\n    ar.end_top_lat = top_lat;\n    ar.end_top_lon = top_lon;\n    ar.end_bot_lat = bot_lat;\n    ar.end_bot_lon = bot_lon;\n\n    return end_criteria;\n}\n\n/*\n* Calculate geodesic distance between two lat, long pairs\n* CODE borrowed from: from http://www.geodatasource.com/developers/c\n* from http://osiris.tuwien.ac.at/~wgarn/gis-gps/latlong.html\n* from http://www.codeproject.com/KB/cpp/Distancecplusplus.aspx\n*/\ntemplate<typename T>\nT geodesic_distance(T lat1, T lon1, T lat2, T lon2)\n{\n    T deg_to_rad = T(M_PI/180.0);\n\n    T dlat1 = lat1*deg_to_rad;\n    T dlon1 = lon1*deg_to_rad;\n    T dlat2 = lat2*deg_to_rad;\n    T dlon2 = lon2*deg_to_rad;\n\n    T dLon = dlon1 - dlon2;\n    T dLat = dlat1 - dlat2;\n\n    T sin_dLat_half_sq = sin(dLat/T(2.0));\n    sin_dLat_half_sq *= sin_dLat_half_sq;\n\n    T sin_dLon_half_sq = sin(dLon/T(2.0));\n    sin_dLon_half_sq *= sin_dLon_half_sq;\n\n    T aHarv = sin_dLat_half_sq\n        + cos(dlat1)*cos(dlat2)*sin_dLon_half_sq;\n\n    T cHarv = T(2.0)*atan2(sqrt(aHarv), sqrt(T(1.0) - aHarv));\n\n    T R = T(6371.0);\n    T distance = R*cHarv;\n\n    return distance;\n}\n\n/*\n* This function calculates the average geodesic width\n* As each pixel represents certain area, the total area\n* is the product of the number of pixels and the area of\n* one pixel. The average width is: the total area divided\n* by the medial axis length\n* We are calculating the average width, since we are not\n* determining where exactly to cut off the tropical region\n* to calculate the real width of an atmospheric river\n*/\ntemplate <typename T>\nT avg_width(\n    const vector<int> &con_comp_r,\n    const vector<int> &con_comp_c,\n    T ar_len,\n    const T *p_lat,\n    const T *p_lon)\n{\n/*\n    // TODO -- need bounds checking when doing things like\n    // p_lat[con_comp_r[0] + 1]. also because it's potentially\n    // a stretched cartesian mesh need to compute area of\n    // individual cells\n\n    // length of cell in lat direction\n    T lat_val[2] = {p_lat[con_comp_r[0]], p_lat[con_comp_r[0] + 1]};\n    T lon_val[2] = {p_lon[con_comp_c[0]], p_lon[con_comp_c[0]]};\n    T dlat = geodesic_distance(lat_val[0], lon_val[0], lat_val[1], lon_val[1]);\n\n    // length of cell in lon direction\n    lat_val[1] = lat_val[0];\n    lon_val[1] = p_lon[con_comp_c[0] + 1];\n    T dlon = geodesic_distance(lat_val[0], lon_val[0], lat_val[1], lon_val[1]);\n*/\n    (void)con_comp_c;\n    // compute area of the first cell in the input mesh\n    // length of cell in lat direction\n    T lat_val[2] = {p_lat[0], p_lat[1]};\n    T lon_val[2] = {p_lon[0], p_lon[0]};\n    T dlat = geodesic_distance(lat_val[0], lon_val[0], lat_val[1], lon_val[1]);\n\n    // length of cell in lon direction\n    lat_val[1] = lat_val[0];\n    lon_val[1] = p_lon[1];\n    T dlon = geodesic_distance(lat_val[0], lon_val[0], lat_val[1], lon_val[1]);\n\n    // area\n    T pixel_area = dlat*dlon;\n    T total_area = pixel_area*con_comp_r.size();\n\n    // avg width\n    T avg_width = total_area/ar_len;\n    return avg_width;\n}\n\n/*\n* Find the middle point between two pairs of lat and lon values\n* http://stackoverflow.com/questions/4164830/geographic-midpoint-between-two-coordinates\n*/\ntemplate<typename T>\nvoid geodesic_midpoint(T lat1, T lon1, T lat2, T lon2, T &mid_lat, T &mid_lon)\n{\n    T deg_to_rad = T(M_PI/180.0);\n    T dLon = (lon2 - lon1) * deg_to_rad;\n    T dLat1 = lat1 * deg_to_rad;\n    T dLat2 = lat2 * deg_to_rad;\n    T dLon1 = lon1 * deg_to_rad;\n\n    T Bx = cos(dLat2) * cos(dLon);\n    T By = cos(dLat2) * sin(dLon);\n\n    mid_lat = atan2(sin(dLat1)+sin(dLat2),\n        sqrt((cos(dLat1)+Bx)*(cos(dLat1)+Bx)+By*By));\n\n    mid_lon = dLon1 + atan2(By, (cos(dLat1)+Bx));\n\n    T rad_to_deg = T(180.0/M_PI);\n    mid_lat *= rad_to_deg;\n    mid_lon *= rad_to_deg;\n}\n\n/*\n* Find the length along the medial axis of a connected component\n* Medial length is the sum of the distances between the medial\n* points in the connected component\n*/\ntemplate<typename T>\nT medial_length(\n    const vector<int> &con_comp_r,\n    const vector<int> &con_comp_c,\n    const T *p_lat,\n    const T *p_lon)\n{\n    vector<int> jb_r1;\n    vector<int> jb_c1;\n    vector<int> jb_c2;\n\n    long row_track = -1;\n\n    unsigned long count = con_comp_r.size();\n    for (unsigned long i = 0; i < count; ++i)\n    {\n        if (row_track != con_comp_r[i])\n        {\n            jb_r1.push_back(con_comp_r[i]);\n            jb_c1.push_back(con_comp_c[i]);\n\n            jb_c2.push_back(con_comp_c[i]);\n\n            row_track = con_comp_r[i];\n        }\n        else\n        {\n            jb_c2.back() = con_comp_c[i];\n        }\n    }\n\n    T total_dist = T();\n\n    long b_count = jb_r1.size() - 1;\n    for (long i = 0; i < b_count; ++i)\n    {\n        T lat_val[2];\n        T lon_val[2];\n\n        lat_val[0] = p_lat[jb_r1[i]];\n        lat_val[1] = p_lat[jb_r1[i]];\n\n        lon_val[0] = p_lon[jb_c1[i]];\n        lon_val[1] = p_lon[jb_c2[i]];\n\n        T mid_lat1;\n        T mid_lon1;\n\n        geodesic_midpoint(\n            lat_val[0], lon_val[0], lat_val[1], lon_val[1],\n            mid_lat1, mid_lon1);\n\n        lat_val[0] = p_lat[jb_r1[i+1]];\n        lat_val[1] = p_lat[jb_r1[i+1]];\n\n        lon_val[0] = p_lon[jb_c1[i+1]];\n        lon_val[1] = p_lon[jb_c2[i+1]];\n\n        T mid_lat2;\n        T mid_lon2;\n\n        geodesic_midpoint(\n            lat_val[0], lon_val[0], lat_val[1], lon_val[1],\n            mid_lat2, mid_lon2);\n\n        total_dist\n            += geodesic_distance(mid_lat1, mid_lon1, mid_lat2, mid_lon2);\n    }\n\n    return total_dist;\n}\n\n/*\n// Suren's function\n// helper return true if the geometric conditions\n// on an ar are satisfied. also stores the length\n// and width of the river.\ntemplate <typename T>\nbool river_geometric_criteria(\n    const vector<int> &con_comp_r,\n    const vector<int> &con_comp_c,\n    const T *p_lat,\n    const T *p_lon,\n    double river_length,\n    double river_width,\n    atmospheric_river &ar)\n{\n    ar.length = medial_length(con_comp_r, con_comp_c, p_lat, p_lon);\n\n    ar.width = avg_width(con_comp_r, con_comp_c,\n        static_cast<T>(ar.length), p_lat, p_lon);\n\n    return (ar.length >= river_length) && (ar.width <= river_width);\n}\n*/\n\n// Junmin's function for height of a triangle\ntemplate<typename T>\nT triangle_height(T base, T s1, T s2)\n{\n    // area from Heron's fomula\n    T p = (base + s1 + s2)/T(2);\n    T area = p*(p - base)*(p - s1)*(p - s2);\n    // detect impossible triangle\n    if (area < T())\n        return std::min(s1, s2);\n    // height from A = 1/2 b h\n    return T(2)*sqrt(area)/base;\n}\n\n// TDataProcessor::check_geodesic_width_top_down\n// Junmin's function for detecting river based on\n// it's geometric properties\ntemplate <typename T>\nbool river_geometric_criteria(\n    const vector<int> &con_comp_r,\n    const vector<int> &con_comp_c,\n    const T *p_lat,\n    const T *p_lon,\n    double river_length,\n    double river_width,\n    atmospheric_river &ar)\n{\n    vector<int> distinct_rows;\n    vector<int> leftmost_col;\n    vector<int> rightmost_col;\n\n    int row_track = -1;\n    size_t count = con_comp_r.size();\n    for (size_t i = 0; i < count; ++i)\n    {\n        if (row_track != con_comp_r[i])\n        {\n            row_track = con_comp_r[i];\n\n            distinct_rows.push_back(con_comp_r[i]);\n            leftmost_col.push_back(con_comp_c[i]);\n            rightmost_col.push_back(con_comp_c[i]);\n        }\n        else\n        {\n            rightmost_col.back() = con_comp_c[i];\n        }\n    }\n\n    // river metrics\n    T length_from_top = T();\n    T min_width = std::numeric_limits<T>::max();\n    T max_width = std::numeric_limits<T>::lowest();\n\n    for (long i = distinct_rows.size() - 2; i >= 0; --i)\n    {\n        // for each row w respect to row above it. triangulate\n        // a quadrilateral composed of left and right most points\n        // in this and the above rows. ccw ordering from lower\n        // left corner is A,B,D,C.\n\n        // low left-right distance\n        T AB = geodesic_distance(\n            p_lat[distinct_rows[i]], p_lon[leftmost_col[i]],\n            p_lat[distinct_rows[i]], p_lon[rightmost_col[i]]);\n\n        // left side bottom-top distance\n        T AC = geodesic_distance(\n            p_lat[distinct_rows[i]], p_lon[leftmost_col[i]],\n            p_lat[distinct_rows[i+1]], p_lon[leftmost_col[i]]);\n\n        // distance from top left to bottom right, across\n        T BC = geodesic_distance(\n            p_lat[distinct_rows[i]], p_lon[rightmost_col[i]],\n            p_lat[distinct_rows[i+1]], p_lon[leftmost_col[i+1]]);\n\n        // high left-right distance\n        T CD = geodesic_distance(\n            p_lat[distinct_rows[i+1]], p_lon[leftmost_col[i+1]],\n            p_lat[distinct_rows[i+1]], p_lon[rightmost_col[i+1]]);\n\n        // right side bottom-top distance\n        T BD = geodesic_distance(\n            p_lat[distinct_rows[i]], p_lon[rightmost_col[i]],\n            p_lat[distinct_rows[i+1]], p_lon[rightmost_col[i+1]]);\n\n        T height_from_b = triangle_height(AC, AB, BC);\n        T height_from_c = triangle_height(BD, BC, CD);\n\n        T curr_min = std::min(height_from_b, height_from_c);\n\n        // test width criteria\n        if (curr_min > river_width)\n        {\n            // TODO -- first time through the loop length == 0. is it intentional\n            // to discard the detection or should length calc take place before this test?\n            // note: first time through loop none of the event details have been recoreded\n            if (length_from_top <= river_length)\n            {\n                 // too short to be a river\n                return false;\n            }\n            else\n            {\n                 // part of a connected region is AR\n                ar.min_width = static_cast<double>(min_width);\n                ar.max_width = static_cast<double>(max_width);\n                ar.length = static_cast<double>(length_from_top);\n                return true;\n            }\n        }\n\n        // update width\n        min_width = std::min(min_width, curr_min);\n        max_width = std::max(max_width, curr_min);\n\n        // update length\n        T mid_bot_lat;\n        T mid_bot_lon;\n        geodesic_midpoint(\n            p_lat[distinct_rows[i]], p_lon[leftmost_col[i]],\n            p_lat[distinct_rows[i]], p_lon[rightmost_col[i]],\n            mid_bot_lat, mid_bot_lon);\n\n        T mid_top_lat;\n        T mid_top_lon;\n        geodesic_midpoint(\n            p_lat[distinct_rows[i+1]], p_lon[leftmost_col[i+1]],\n            p_lat[distinct_rows[i+1]], p_lon[rightmost_col[i+1]],\n            mid_top_lat, mid_top_lon);\n\n        length_from_top += geodesic_distance(\n            mid_bot_lat, mid_bot_lon, mid_top_lat, mid_top_lon);\n    }\n\n    // check the length criteria.\n    // TODO: if we are here the widtrh critera was not met\n    // so the following detection is based solely on the length?\n    if (length_from_top > river_length)\n    {\n        // AR\n        ar.min_width = static_cast<double>(min_width);\n        ar.max_width = static_cast<double>(max_width);\n        ar.length = static_cast<double>(length_from_top);\n        return true;\n    }\n\n    return false;\n}\n\n\n\n// Junmin's function checkRightBoundary\n// note: if land sea mask is not available land array\n// must all be true.\ntemplate<typename T>\nbool river_end_criteria(\n    const vector<int> &con_comp_r,\n    const vector<int> &con_comp_c,\n    const vector<bool> &land,\n    const T *p_lat,\n    const T *p_lon,\n    T river_end_lat_low,\n    T river_end_lon_low,\n    T river_end_lat_high,\n    T river_end_lon_high,\n    atmospheric_river &ar)\n{\n    // locate component points within shoreline\n    // box\n    bool first_crossing = false;\n    bool event_detected = false;\n\n    T top_lat = T();\n    T top_lon = T();\n    T bot_lat = T();\n    T bot_lon = T();\n\n    std::vector<int> right_bound_col_idx;\n    size_t count = con_comp_c.size();\n    for (size_t i = 0; i < count; ++i)\n    {\n        T lat = p_lat[con_comp_r[i]];\n        T lon = p_lon[con_comp_c[i]];\n\n        if ((lat >= river_end_lat_low) && (lat <= river_end_lat_high)\n            && (lon >= river_end_lon_low) && (lon <= river_end_lon_high))\n        {\n            if (!event_detected)\n                event_detected = land[i];\n\n            if (!first_crossing)\n            {\n                first_crossing = true;\n                top_lat = lat;\n                top_lon = lon;\n            }\n            bot_lat = lat;\n            bot_lon = lon;\n        }\n    }\n\n    ar.end_top_lat = top_lat;\n    ar.end_top_lon = top_lon;\n    ar.end_bot_lat = bot_lat;\n    ar.end_bot_lon = bot_lon;\n\n    return event_detected;\n}\n\n// Junmin's function\ntemplate<typename T>\nvoid classify_event(\n    const vector<int> &con_comp_r,\n    const vector<int> &con_comp_c,\n    const T *p_lat,\n    const T *p_lon,\n    T start_lat,\n    T start_lon,\n    atmospheric_river &ar)\n{\n    // classification determined by first detected point in event\n    // is closer to left or to bottom\n    T lat = p_lat[con_comp_r[0]];\n    T lon = p_lon[con_comp_c[0]];\n\n    ar.pe = false;\n    if ((lat - start_lat) < (lon - start_lon))\n        ar.pe = true; // PE\n}\n\n/*\n* The main function that checks whether an AR event exists in\n* given sub-plane of data. This currently applies only to the Western\n* coast of the USA. return true if an ar is found.\n*/\nbool ar_detect(\n    const_p_teca_variant_array lat,\n    const_p_teca_variant_array lon,\n    const_p_teca_variant_array land_sea_mask,\n    const_p_teca_unsigned_int_array con_comp,\n    unsigned long n_comp,\n    double river_start_lat,\n    double river_start_lon,\n    double river_end_lat_low,\n    double river_end_lon_low,\n    double river_end_lat_high,\n    double river_end_lon_high,\n    double percent_in_mesh,\n    double river_width,\n    double river_length,\n    double land_threshold_low,\n    double land_threshold_high,\n    atmospheric_river &ar)\n{\n    NESTED_TEMPLATE_DISPATCH_FP(\n        const teca_variant_array_impl,\n        lat.get(),\n        1,\n\n        NESTED_TEMPLATE_DISPATCH(\n            const teca_variant_array_impl,\n            land_sea_mask.get(),\n            2,\n\n            const NT1 *p_lat = dynamic_cast<TT1*>(lat.get())->get();\n            const NT1 *p_lon = dynamic_cast<TT1*>(lon.get())->get();\n\n            const NT2 *p_land_sea_mask\n                = dynamic_cast<TT2*>(land_sea_mask.get())->get();\n\n            NT1 start_lat = static_cast<NT1>(river_start_lat);\n            NT1 start_lon = static_cast<NT1>(river_start_lon);\n            NT1 end_lat_low = static_cast<NT1>(river_end_lat_low);\n            NT1 end_lon_low = static_cast<NT1>(river_end_lon_low);\n            NT1 end_lat_high = static_cast<NT1>(river_end_lat_high);\n            NT1 end_lon_high = static_cast<NT1>(river_end_lon_high);\n\n            unsigned long num_rows = lat->size();\n            unsigned long num_cols = lon->size();\n\n            // # in PE is % of points in regious mesh\n            unsigned long num_rc = num_rows*num_cols;\n            unsigned long thr_count = num_rc*percent_in_mesh/100.0;\n\n            unsigned int *p_labels = con_comp->get();\n            for (unsigned int i = 1; i <= n_comp; ++i)\n            {\n                // for all discrete connected component labels\n                // verify if there exists an AR\n                vector<int> con_comp_r;\n                vector<int> con_comp_c;\n                vector<bool> land;\n\n                for (unsigned long r = 0, q = 0; r < num_rows; ++r)\n                {\n                    for (unsigned long c = 0; c < num_cols; ++c, ++q)\n                    {\n                        if (p_labels[q] == i)\n                        {\n                            // gather points of this connected component\n                            con_comp_r.push_back(r);\n                            con_comp_c.push_back(c);\n\n                            // identify them as land or not\n                            land.push_back(\n                                (p_land_sea_mask[q] >= land_threshold_low)\n                                && (p_land_sea_mask[q] < land_threshold_high));\n                        }\n                    }\n                }\n\n                // check for ar criteria\n                unsigned long count = con_comp_r.size();\n                if ((count > thr_count)\n                    && river_end_criteria(\n                        con_comp_r, con_comp_c, land,\n                        p_lat, p_lon,\n                        end_lat_low, end_lon_low,\n                        end_lat_high, end_lon_high,\n                        ar)\n                    && river_geometric_criteria(\n                        con_comp_r, con_comp_c, p_lat, p_lon,\n                        river_length, river_width, ar))\n                {\n                    // determine if PE or AR\n                    classify_event(\n                        con_comp_r, con_comp_c, p_lat, p_lon,\n                        start_lat, start_lon, ar);\n                    return true;\n                }\n            }\n            )\n        )\n    return false;\n}\n\n#if TECA_DEBUG > 0 && defined(TECA_HAS_VTK)\n// helper to dump a dataset for debugging\nint write_mesh(\n    const const_p_teca_cartesian_mesh &mesh,\n    const const_p_teca_variant_array &vapor,\n    const const_p_teca_variant_array &thresh,\n    const const_p_teca_variant_array &ccomp,\n    const const_p_teca_variant_array &lsmask,\n    const std::string &base_name)\n{\n    p_teca_cartesian_mesh m = teca_cartesian_mesh::New();\n    m->copy_metadata(mesh);\n\n    p_teca_array_collection pac = m->get_point_arrays();\n    pac->append(\"vapor\", std::const_pointer_cast<teca_variant_array>(vapor));\n    pac->append(\"thresh\", std::const_pointer_cast<teca_variant_array>(thresh));\n    pac->append(\"ccomp\", std::const_pointer_cast<teca_variant_array>(ccomp));\n    pac->append(\"lsmask\", std::const_pointer_cast<teca_variant_array>(lsmask));\n\n    p_teca_programmable_source s = teca_programmable_source::New();\n    s->set_execute_function(\n        [m] (const teca_metadata &) -> const_p_teca_dataset\n        { return m; }\n        );\n\n    p_teca_vtk_cartesian_mesh_writer w\n        = teca_vtk_cartesian_mesh_writer::New();\n\n    w->set_base_file_name(base_name);\n    w->set_input_connection(s->get_output_port());\n    w->update();\n\n    return 0;\n}\n#endif\n\n/* some of the datasets have date array with calcs already made!\n    // get date\n    // TODO -- handle date in a unform manner\n    long YYYY = 0;\n    long MM = 0;\n    long DD = 0;\n    const_p_teca_variant_array date\n        = mesh->get_information_arrays()->get(\"date\");\n\n    if (date)\n    {\n        TEMPLATE_DISPATCH(\n            const teca_variant_array_impl,\n            date.get(),\n\n            NT d = dynamic_cast<TT*>(date.get())->get()[0];\n            YYYY = static_cast<long>(d)/10000l;\n            MM = (static_cast<long>(d) - YYYY*10000l)/100l;\n            DD = static_cast<long>(d) - YYYY*10000l - MM*100l;\n            )\n    }\n*/\n", "meta": {"hexsha": "226a4774f21c38847d17550cc6bfb5bf473c5017", "size": 44905, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "alg/teca_ar_detect.cxx", "max_stars_repo_name": "burlen/teca_arch", "max_stars_repo_head_hexsha": "6e2d6b607b0ab4a354969e0bd5e24ceb3a57bcf4", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "alg/teca_ar_detect.cxx", "max_issues_repo_name": "burlen/teca_arch", "max_issues_repo_head_hexsha": "6e2d6b607b0ab4a354969e0bd5e24ceb3a57bcf4", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "alg/teca_ar_detect.cxx", "max_forks_repo_name": "burlen/teca_arch", "max_forks_repo_head_hexsha": "6e2d6b607b0ab4a354969e0bd5e24ceb3a57bcf4", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9903381643, "max_line_length": 114, "alphanum_fraction": 0.5971049994, "num_tokens": 11701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2519530852645403}}
{"text": "/*\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2010, AASS Research Center, Orebro 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 Willow Garage, Inc. 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 CEVENT_COUNTER_DATA_H\n#define CEVENT_COUNTER_DATA_H\n#include<cmath>\n#include <iostream>\n#include <cstdio>\n#include <Eigen/Dense>\n#include <inttypes.h>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n///Defines for presets\n#define EVENTMAP_OCCU  255\n#define EVENTMAP_UNKNOWN  127\n#define EVENTMAP_FREE  0\n#define EVENTMAP_NUMBER_OF_EVENTS_STORED 128\n\n\n///Recency filtering stuff\n#define EVENTMAP_USE_RECENCY_FILTERING\n#define EVENTMAP_OBSERVATION_LIMIT 30000.0\n#define Wforget (5000.0/5001.0)\n\n/**\n* Structure in the map\n**/\nstruct TEventData\n{\n  uint8_t \toccval; \t\t\t///<Occupancy value\n  float \t\ta_exit_event; ///Number of exit events ( OCC 2 EMP)\n  float  \t\tb_exit_event; ///Number of times the cell is perceived as occupied\n\n  float \t\ta_entry_event;\n  float  \t\tb_entry_event; ///Number of times the cell is perceived as empty\n  uint64_t  events;        /// A storage for the last 64 events (as bits)\n\n  TEventData():\n    occval(127),\n    a_exit_event(1.0),\n    b_exit_event(1.0),\n    a_entry_event(1.0),\n    b_entry_event(1.0),\n    events(0)\n  {\n  };\n\n  ~TEventData()\n  {\n  }\n\n\n  const TEventData &operator =(const TEventData &copy)\n  {\n    occval = copy.occval;\n    a_exit_event = copy.a_exit_event;\n    b_exit_event = copy.b_exit_event;\n    a_entry_event = copy.a_entry_event;\n    b_entry_event = copy.b_entry_event;\n    events = copy.events;\n\n    return *this;\n  }\n\n  TEventData(const TEventData& copy):\n    occval(copy.occval),\n    a_exit_event(copy.a_exit_event),\n    b_exit_event(copy.b_exit_event),\n    a_entry_event(copy.a_entry_event),\n    b_entry_event(copy.b_entry_event),\n    events( copy.events)\n  {\n  }\n\n\n  void Reset()\n  {\n    occval = 127;\n    a_exit_event = 1;\n    b_exit_event = 1;\n    a_entry_event = 1;\n    b_entry_event = 1;\n  }\n\n  bool getBit(int ind)\n  {\n    if((events & (1<<ind))>0) return true;\n    return false;\n  }\n\n\n  float computeShortTermOccupancy()\n  {\n    static float OCC_LOG_PROP = log(0.6/0.4);\n    static float EMP_LOG_PROP = log(0.3/0.7);\n    uint bs=0;\n\n    if( (b_entry_event+b_exit_event-2) > 63) bs=64;\n    else bs = b_entry_event+b_exit_event-2;\n    uint cnt=0;\n    float log_ogg_prob  = 0 ;\n    for(uint i = 0; i<bs; i++)\n    {\n      if(getBit(i))\n      {\n        log_ogg_prob += OCC_LOG_PROP;\n        cnt++;\n      }\n      else\n      {\n        log_ogg_prob += EMP_LOG_PROP;\n      }\n    }\n    return (1.0- 1.0/(1.0+exp(log_ogg_prob)));\n  }\n\n  int getObservations()\n  {\n    return (b_entry_event+b_exit_event);\n  }\n\n  /**\n    * Updates a new measurement\n    */\n  void updateSimple(uint8_t meas)\n  {\n    events = events<<1;\n    if(meas > EVENTMAP_UNKNOWN)  ///OCC\n    {\n      events |= 1;\n    }\n    if(occval > EVENTMAP_UNKNOWN)  ///cell is considered Occupied\n    {\n      updateExitEvent(meas, 1.0);\n    }\n    else if(occval < EVENTMAP_UNKNOWN)\n    {\n      updateEntryEvent(meas,1.0);\n    }\n    else\n    {\n      occval = meas; ///Just update\n    }\n  }\n\n  /**\n    * Updates a new measurement\n    */\n  void updateSimple(uint8_t meas, float w)\n  {\n    events = events<<1;\n    if(meas > EVENTMAP_UNKNOWN)  ///OCC\n    {\n      events |= 1;\n    }\n    if(occval > EVENTMAP_UNKNOWN)  ///cell is considered Occupied\n    {\n      updateExitEvent(meas, w);\n    }\n    else if(occval < EVENTMAP_UNKNOWN)\n    {\n      updateEntryEvent(meas,w);\n    }\n    else\n    {\n      occval = meas; ///Just update\n    }\n#ifdef EVENTMAP_USE_RECENCY_FILTERING\n    performRecencyFiltering();\n#endif\n  }\n\n  void performRecencyFiltering()\n  {\n    if(occval > EVENTMAP_UNKNOWN)  ///We are in Exit state\n    {\n      if(b_exit_event>EVENTMAP_OBSERVATION_LIMIT)\n      {\n        float w = EVENTMAP_OBSERVATION_LIMIT / b_exit_event;\n        b_exit_event *= w;\n        a_exit_event *= w;\n      }\n      a_entry_event = 1.0 + (a_entry_event-1.0) * Wforget;\n      b_entry_event = 1.0 + (b_entry_event-1.0) * Wforget;\n    }\n    else\n    {\n      if(b_entry_event>EVENTMAP_OBSERVATION_LIMIT)\n      {\n        float w = EVENTMAP_OBSERVATION_LIMIT / b_entry_event;\n        b_entry_event *= w;\n        a_entry_event *= w;\n      }\n      a_exit_event = 1.0 + (a_exit_event-1.0) * Wforget;\n      b_exit_event = 1.0 + (b_exit_event-1.0) * Wforget;\n    }\n  }\n\n\n  /**\n    * Update Exit event (cell is OCC)\n    */\n  void updateExitEvent(uint8_t meas, float w)\n  {\n    if(meas>EVENTMAP_UNKNOWN)  ///OCC\n    {\n      b_exit_event+=1.0;\n    }\n    else\n    {\n      if(w>1.0) fprintf(stderr,\"EXIT W larger that one = %f\\n \",w);\n      a_exit_event+=w;\n      b_exit_event+=1.0;\n      occval = EVENTMAP_FREE;\n    }\n  }\n  /**\n    * Update Entry event (Cell is Free)\n    */\n  void updateEntryEvent(uint8_t meas, float w)\n  {\n    if(meas>EVENTMAP_UNKNOWN)  ///OCC\n    {\n      b_entry_event+=1.0;\n      if(w>1.0) fprintf(stderr,\"W larger that one = %f\\n \",w);\n      a_entry_event+=w;\n      occval = EVENTMAP_OCCU;\n    }\n    else\n    {\n      b_entry_event+=1.0;\n    }\n  }\n\n  ///Expected number of observations/event\n  int getEntryN()\n  {\n    return (int)((float)b_entry_event/(float)a_entry_event +0.5);\n  }\n  ///Expected number of observations/event\n  int getExitN()\n  {\n    return (int)((float)b_exit_event/(float)a_exit_event +0.5);\n  }\n\n\n  double entryL()\n  {\n    if(b_entry_event == 0) fprintf(stderr,\"B Zero, which is not possible!!\\n\");\n    return ((double)a_entry_event/(double)b_entry_event );\n  }\n  double exitL()\n  {\n    if(b_exit_event == 0) fprintf(stderr,\"B Zero, which is not possible!!\\n\");\n    return ((double)a_exit_event/(double)b_exit_event);\n  }\n  double L()\n  {\n    if(b_exit_event == 0) fprintf(stderr,\"B Zero, which is not possible!!\\n\");\n    return ((double)(a_exit_event+a_entry_event)/(double)(b_exit_event+b_entry_event));\n  }\n\n  double fac(int n)\n  {\n    double t=1;\n    for (int i=n; i>1; i--)\n      t*=i;\n    return t;\n  }\n\n  double Bin(int n,double p,int r)\n  {\n    return fac(n)/(fac(n-r)*fac(r))*pow(p,r)*pow(1-p,n-r);\n  }\n\n  float binaryBayesUpdate(float Pold, float P)\n  {\n    return (( Pold*P) / ( Pold*P + (1.0f-Pold)*(1.0f-P))); \t///< Updated probability\n  }\n\n  /**\n    * To prevent numerical difficulties\n    */\n  void normalizeProb(float &p)\n  {\n    if(p>0.999) p = 0.999;\n    if(p<0.001) p = 0.001;\n\n  }\n  /////////////////////////////////////////////////////////////////////////////////////////////77\n  /// Compute different probabilities for the cell\n  /////////////////////////////////////////////////////////////////////////////////////////////77\n  /////////////////////////////////////////////////////////////////////////////////////////////77\n  /**\n    * Compute the probability of this cell being Static occupied.\n    */\n  float getOccStaticLikelihood()\n  {\n    if( (b_entry_event + b_exit_event)<20.0 )\n    {\n      return 0.5f;\n    }\n    Eigen::Matrix2f P;\n    Eigen::Vector2f u1(0.5, 0.5);\n    Eigen::Vector2f P0;\n    float Lex = exitL();\n    float Len = entryL();\n    P(0,0) = (1.0-Len);\n    P(0,1) =  Len;\n    P(1,0)\t = Lex;\n    P(1,1) = (1-Lex);\n\n    P0 = u1.transpose() * P;\n    return (P0(1));\n  }\n\n  /**\n    * Returns the probability of static empty\n    */\n  float getFreeStaticLikelihood()\n  {\n    if( (b_entry_event + b_exit_event)<20.0 )\n    {\n      return 0.5f;\n    }\n    Eigen::Matrix2f P;\n    Eigen::Vector2f P0;\n    Eigen::Vector2f u1(0.5, 0.5);\n    float Lex = exitL();\n    float Len = entryL();\n    P(0,0) = (1.0-Len);\n    P(0,1) =  Len;\n    P(1,0)\t = Lex;\n    P(1,1) = (1-Lex);\n\n    P0 = u1.transpose() * P;\n    return (P0(0));\n  }\n\n  /**\n    * Returns the probability of the cell having dynamics after 2^N\n    * Observations. The larger the N, and higher the value, the more \"Semi-static\"\n    * is the cell. Note that the filter returns\n    * 0.5 >= P <=1.0 and P = 0.0 only if there is not enough evidence about the\n    * Behaviour\n    */\n  float computeSemiStaticLikelihood(int N)\n  {\n    if( (b_entry_event + b_exit_event)<20.0 )\n    {\n      return 0.0f;\n    }\n\n\n    Eigen::Matrix2f P;\n    Eigen::Vector2f u2(0, 1.0);\n    Eigen::Vector2f u3(1.0, 0);\n    float Lex = exitL();\n    float Len = entryL();\n    Eigen::Vector2f P2,P3;\n    P(0,0) = (1.0-Len);\n    P(0,1) =  Len;\n    P(1,0)\t = Lex;\n    P(1,1) = (1-Lex);\n    for(int i=0; i<N; i++) P = P*P;\n    P2 = u2.transpose() * P;\n    P3 = u3.transpose() * P;\n\n    float Po = P2(1);\n    float Pu = binaryBayesUpdate(Po, P3(0));\n    normalizeProb(Pu);\n\n    return Pu;\n  }\n\n  float getOccupancyNow()\n  {\n    if( (b_entry_event + b_exit_event)<50.0)\n    {\n      return 0.5f;\n    }\n    float Po = 0;\n\n\n    Po = computeShortTermOccupancy();\n    float Lex = exitL();\n    float Len = entryL();\n    Eigen::Matrix2f P;\n    P(0,0) = (1.0-Len);\n    P(0,1) =  Len;\n    P(1,0)\t = Lex;\n    P(1,1) = (1-Lex);\n    Eigen::Vector2f u1(1.0-Po, Po);\n    Eigen::Vector2f u = u1.transpose() *P;\n    return u(1);\n  }\n\n  /////////////////////////////////////////////////////////////////////////////////////////////77\n  /////////////////////////////////////////////////////////////////////////////////////////////77\n  ///Predict\n  /////////////////////////////////////////////////////////////////////////////////////////////77\n  /////////////////////////////////////////////////////////////////////////////////////////////77\n\n  float predictOccupancy(int N)\n  {\n    if( (b_entry_event + b_exit_event)<20.0)\n    {\n      return 0.5f;\n    }\n    ///Testing\n    float ps = getOccStaticLikelihood();\n    if(ps>0.6) return 0.9;\n    ///end testing\n\n\n    float Po = computeShortTermOccupancy();\n    float Lex = exitL();\n    float Len = entryL();\n    Eigen::Matrix2f P;\n    P(0,0) = (1.0-Len);\n    P(0,1) =  Len;\n    P(1,0)\t = Lex;\n    P(1,1) = (1-Lex);\n    Eigen::Vector2f u1(1.0-Po, Po);\n    for(int i=0; i<N; i++) P = P*P;\n    Eigen::Vector2f u = u1.transpose() *P;\n\n    return u(1);\n  }\n\n\n};\nnamespace boost {\nnamespace serialization {\n\ntemplate<class Archive>\nvoid serialize(Archive & ar, TEventData & g, const unsigned int version)\n{\n  ar & \tg.occval; \t\t\t///<Occupancy value\n  ar &  g.a_exit_event; ///Number of exit events ( OCC 2 EMP)\n  ar &  g.b_exit_event; ///Number of times the cell is perceived as occupied\n  ar & \tg.a_entry_event;\n  ar & \tg.b_entry_event; ///Number of times the cell is perceived as empty\n  ar &  g.events;\n}\n\n} // namespace serialization\n} // namespace boost\n#endif\n\n", "meta": {"hexsha": "9cb5bef7a3fe6375385701c09d8f2c561611b2b2", "size": 11890, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "perception_oru-port-kinetic/ndt_map/include/ndt_map/impl/EventCounterData.hpp", "max_stars_repo_name": "lllray/ndt-loam", "max_stars_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-14T08:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-14T08:21:13.000Z", "max_issues_repo_path": "perception_oru-port-kinetic/ndt_map/include/ndt_map/impl/EventCounterData.hpp", "max_issues_repo_name": "lllray/ndt-loam", "max_issues_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-28T04:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T04:47:56.000Z", "max_forks_repo_path": "perception_oru-port-kinetic/ndt_map/include/ndt_map/impl/EventCounterData.hpp", "max_forks_repo_name": "lllray/ndt-loam", "max_forks_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-18T11:25:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T12:59:59.000Z", "avg_line_length": 24.6680497925, "max_line_length": 97, "alphanum_fraction": 0.5837678722, "num_tokens": 3453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.25192233240103734}}
{"text": "/*********************************************************************\n* Software License Agreement (BSD License)\n*\n* Copyright (c) 2019, WVU Interactive Robotics Laboratory\n*                       https://web.statler.wvu.edu/~irl/\n* All rights reserved.\n*\n*  Redistribution and use in source and binary forms, with or without\n*  modification, are permitted provided that the following conditions\n*  are met:\n*\n*   * Redistributions of source code must retain the above copyright\n*     notice, this list of conditions and the following disclaimer.\n*   * Redistributions in binary form must reproduce the above\n*     copyright notice, this list of conditions and the following\n*     disclaimer in the documentation and/or other materials provided\n*     with the distribution.\n*   * Neither the name of the Willow Garage 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#include <stdio.h>\n#include <math.h>\n#include <boost/array.hpp>\n#include <ros/ros.h>\n#include <ros/time.h>\n#include <vicon_bridge/Markers.h>\n#include <vicon_bridge/Marker.h>\n#include <geometry_msgs/TransformStamped.h>\n#include <tf2_ros/transform_listener.h>\n#include <tf2_ros/buffer_interface.h>\n#include <tf2/convert.h>\n#include <tf2_geometry_msgs/tf2_geometry_msgs.h>\n#include <visualization_msgs/Marker.h>\n#include <visualization_msgs/MarkerArray.h>\n#include <wvu_swarm_std_msgs/vicon_bot.h>\n#include <wvu_swarm_std_msgs/vicon_bot_array.h>\n#include <wvu_swarm_std_msgs/robot_command.h>\n#include <wvu_swarm_std_msgs/robot_command_array.h>\n#include <wvu_swarm_std_msgs/vicon_point.h>\n#include <wvu_swarm_std_msgs/vicon_points.h>\n\nvoid msgCallback(const wvu_swarm_std_msgs::vicon_bot_array &msg) {}\n\n// Method to find distance between two points\ndouble getDist(const geometry_msgs::Point first, const geometry_msgs::Point second);\n\n// Method to populate a vector with a Gerono Lemniscate\n//   Params: a vector to fill with the points, a value 'a' defining the curve,\n//   and a value for an increment in degrees to iterate through 360 degrees\nvoid genGeronoLemn(std::vector<geometry_msgs::Point> &target, const double a, const double incr);\n\nint main(int argc, char **argv)\n{\n    // Initialize a node\n    ros::init(argc, argv, \"tracker\");\n    \n    // Generates nodehandle, publisher, subscribers\n    ros::NodeHandle n;\n    ros::NodeHandle n_priv(\"~\"); // private handle\n    ros::Publisher pub;\n    ros::Subscriber sub;\n    \n    //  Where to get the array of bots, what topic to advertise, where to get transform of target\n    std::string viconArrayTopic, advertiseTopic, transformPrefix;\n    \n    //  Value of 'a' in formula in cm, value to iterate degrees, distance to \"find\" points at\n    int lemniscateConstant, lemniscateInterval, cutoffRadius;\n    \n    // Import parameters from launchfile\n    n_priv.param<std::string>(\"vicon_array_topic\", viconArrayTopic, \"/viconArray\");\n    n_priv.param<std::string>(\"advertise_topic\", advertiseTopic, \"target\");\n    n_priv.param<std::string>(\"transform_prefix\", transformPrefix, \"cardbot_\");\n    n_priv.param<int>(\"lemniscate_constant\", lemniscateConstant, 50);\n    n_priv.param<int>(\"lemniscate_interval\", lemniscateInterval, 10);\n    n_priv.param<int>(\"cutoff_radius\", cutoffRadius, 10);\n    \n    // Sets loop rate at 100Hz\n    ros::Rate rate(10);\n    \n    // Subscribe to tracker's vicon topic, advertise result vector\n    sub = n.subscribe(viconArrayTopic, 10, &msgCallback);\n    pub = n.advertise<wvu_swarm_std_msgs::vicon_points>(advertiseTopic, 1000);\n    \n    // Set up transform buffer\n    tf2_ros::Buffer tfBuffer;\n    \n    // Set up transform listener\n    tf2_ros::TransformListener tfListener(tfBuffer);\n    \n    // Generate a Gerono Lemniscate (figure 8) as discrete points\n    std::vector<geometry_msgs::Point> path;\n    genGeronoLemn(path, lemniscateConstant, lemniscateInterval);\n    \n    // Pick one point out of the path\n    geometry_msgs::Point currentPoint = path.at(0);\n    int currentIndex = 0;\n    ROS_INFO(\"Point initialized at %f, %f\\n\", currentPoint.x, currentPoint.y);\n    \n    // Run while ros functions\n    while(ros::ok())\n    {\n        // Get the information of the vicon array\n        wvu_swarm_std_msgs::vicon_bot_array viconArray =\n                *(ros::topic::waitForMessage<wvu_swarm_std_msgs::vicon_bot_array>(viconArrayTopic));\n        \n        double minimumPointDistance = 10000.0; // Trivially large number, in cm\n        \n        // Iterate through all bots\n        for(wvu_swarm_std_msgs::vicon_bot iteratorBot : viconArray.poseVect)\n        {\n            // Find this bot's point\n            geometry_msgs::Point botPt;\n            botPt.x = iteratorBot.botPose.transform.translation.x;\n            botPt.y = iteratorBot.botPose.transform.translation.y;\n            botPt.z = 0;\n            \n            // Find distance from this bot to the point\n            double thisDist = getDist(botPt, currentPoint);\n            \n            // Change minimum if necessary\n            if(thisDist < minimumPointDistance) minimumPointDistance = thisDist;\n        }\n        \n        // Move the point if any bot has come too close\n        if(minimumPointDistance < cutoffRadius)\n        {\n            // Rotate through vector if needed\n            if(currentIndex + 1 >= path.size())\n                currentIndex = 0;\n            else\n                currentIndex++;\n            \n            currentPoint = path.at(currentIndex);\n        \n            ROS_INFO(\"Point moved to %f, %f\\n\", currentPoint.x, currentPoint.y);\n        }\n        \n        // Publish target point to be grabbed by the Processor\n        wvu_swarm_std_msgs::vicon_points output;\n        wvu_swarm_std_msgs::vicon_point outputPt;\n        outputPt.x = currentPoint.x;\n        outputPt.y = currentPoint.y;\n        output.point.push_back(outputPt);\n        wvu_swarm_std_msgs::vicon_point dummyPt;\n        dummyPt.x = 30.0;\n        dummyPt.y = 30.0;\n        output.point.push_back(dummyPt);\n        pub.publish(output);\n        \n        ros::spinOnce();\n        rate.sleep();\n    }\n}\n\ndouble getDist(const geometry_msgs::Point first, const geometry_msgs::Point second)\n{\n    double xDiff = first.x - second.x;\n    double yDiff = first.y - second.y;\n    double zDiff = first.z - second.z;\n    \n    return sqrt(xDiff*xDiff + yDiff*yDiff + zDiff*zDiff);\n}\n\nvoid genGeronoLemn(std::vector<geometry_msgs::Point> &target, const double a, const double incr)\n{\n    // Iterate across 360 degrees\n    for(int t = 0; t < 360; t += incr)\n    {\n        // Create a point\n        geometry_msgs::Point temp;\n        \n        double rads = t * 3.14156265 / 180;\n        \n        // Do math to find its location\n        //   This lemniscate is rotated 90 deg\n        temp.x = a * cos(rads) * sin(rads);\n        temp.y = a * sin(rads);\n        temp.z = 0; //flatworld\n        \n        // Add to vector\n        target.push_back(temp);\n        \n        ROS_INFO(\"Added point at %d degrees, or %f rads, at %f, %f, 0\\n\", t, rads, temp.x, temp.y);\n    }\n}\n", "meta": {"hexsha": "4defdbb8b1803603ea6027481f63abc0502ac444", "size": 7921, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "swarm_ws/src/vicon_demo/src/alicetrack_demo.cpp", "max_stars_repo_name": "wvu-irl/reu-swarm-ros", "max_stars_repo_head_hexsha": "d63c9c4435cd22d8eca5414bf1a4602dd892c3af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-11T11:44:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-11T11:44:49.000Z", "max_issues_repo_path": "swarm_ws/src/vicon_demo/src/alicetrack_demo.cpp", "max_issues_repo_name": "wvu-irl/reu-swarm-ros", "max_issues_repo_head_hexsha": "d63c9c4435cd22d8eca5414bf1a4602dd892c3af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "swarm_ws/src/vicon_demo/src/alicetrack_demo.cpp", "max_forks_repo_name": "wvu-irl/reu-swarm-ros", "max_forks_repo_head_hexsha": "d63c9c4435cd22d8eca5414bf1a4602dd892c3af", "max_forks_repo_licenses": ["BSD-3-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.407960199, "max_line_length": 100, "alphanum_fraction": 0.6653200353, "num_tokens": 1895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2518608416867184}}
{"text": "#include <armadillo>\n#include <imcmc/imcmc.hpp>\n#include <imcmc/parser++.hpp>\n#include \"ClassEngine.hh\"\n#include \"CosmoTheory.hpp\"\n#include \"CMB.hpp\"\n#include \"class.h\"\n\nusing namespace std;\nusing namespace imcmc;\nusing namespace imcmc::parser;\n\nData_CMB_Dist::Data_CMB_Dist(){\n    // do nothing\n    use_Hu_fitting = true;\n}\n\nData_CMB_Dist::~Data_CMB_Dist(){\n    // do nothing\n}\n\n\nvoid Data_CMB_Dist::Init( string& CMB_dist_prior_dataset ){\n\n    data_info.GetInfo(CMB_dist_prior_dataset);\n\n    string dist_prior_file = \"\";\n    string inv_covmat_file = \"\";\n\tstring dist_prior_std_file = \"\"; // used only for Planck distance prior\n\tformat = -1;\t// 0--WMAP; 1--Planck\n\n\tif( Read::Has_Key_in_File(CMB_dist_prior_dataset,\"format\") ){\n\t\tformat = Read::Read_Int_from_File(CMB_dist_prior_dataset,\"format\");\n\t\tif( format != 0 && format != 1 ){\n\t\t\tMPI_ClassMC_ERROR(\"format can only take 0 or 1 !\");\n\t\t}\n\t}\n\telse{\n\t\tMPI_ClassMC_ERROR(\"the key \\'format\\' can not be found in file: \"+CMB_dist_prior_dataset);\n\t}\n\n    if( Read::Has_Key_in_File(CMB_dist_prior_dataset,\"use_Hu_fitting\") )\n        use_Hu_fitting = Read::Read_Bool_from_File(CMB_dist_prior_dataset,\"use_Hu_fitting\");\n    else{\n        MPI_ClassMC_WARNING(\"use_Hu_fitting is not found, so use default value \\'true\\'.\");\n        // exit(0);\n    }\n\n    if( Read::Has_Key_in_File(CMB_dist_prior_dataset,\"dist_prior_file\") )\n        dist_prior_file = Read::Read_String_from_File(CMB_dist_prior_dataset,\"dist_prior_file\");\n    else\n        MPI_ClassMC_ERROR(\"dist_prior_file not set in: \"+CMB_dist_prior_dataset);\n\n\n    if( Read::Has_Key_in_File(CMB_dist_prior_dataset,\"inv_covmat_file\") )\n        inv_covmat_file = Read::Read_String_from_File(CMB_dist_prior_dataset,\"inv_covmat_file\");\n    else\n        MPI_ClassMC_ERROR(\"inv_covmat_file not set in: \"+CMB_dist_prior_dataset);\n\n\tif( format == 0 ){\n    \tdistance_prior  = arma::zeros(1,3);\n    \tcovmat_inv      = arma::zeros(3,3);\n\n    \tdistance_prior.load(dist_prior_file,arma::auto_detect); // loading CMB distance prior {lA,R,z_rec}\n    \tcovmat_inv.load(inv_covmat_file,arma::auto_detect);     // loading covariance matrix\n\t}\n\telse if( format == 1 ){\n//\t\tcout << \"loading Planck distance prior data ...\\n\";\n\t\tarma::rowvec tmp = arma::zeros(1,3);\n\t\tstring std_file = Read::Read_String_from_File(CMB_dist_prior_dataset,\"dist_prior_std_file\");\n\t\ttmp.load(std_file,arma::auto_detect);\n\t\tstd_R \t= tmp(0);\n\t\tstd_lA\t= tmp(1);\n\t\tstd_Obh2= tmp(2);\n\n\t\tdistance_prior_plk = arma::zeros(1,3);\n\t\tcovmat_inv_plk     = arma::zeros(3,3);\n\n    //  read Planck distance prior data\n\t\tdistance_prior_plk.load(dist_prior_file,arma::auto_detect);\n\n    //  read the normalized covariance matrix\n\t\tcovmat_inv_plk.load(inv_covmat_file,arma::auto_detect);\n\n    //  convert to the original covariance matrix\n        covmat_inv_plk(0,0) *= std_R*std_R;\n        covmat_inv_plk(0,1) *= std_R*std_lA;\n        covmat_inv_plk(0,2) *= std_R*std_Obh2;\n\n\t\tcovmat_inv_plk(1,0) *= std_lA*std_R;\n\t\tcovmat_inv_plk(1,1) *= std_lA*std_lA;\n\t\tcovmat_inv_plk(1,2) *= std_lA*std_Obh2;\n\n\t\tcovmat_inv_plk(2,0) *= std_Obh2*std_R;\n\t\tcovmat_inv_plk(2,1) *= std_Obh2*std_lA;\n\t\tcovmat_inv_plk(2,2) *= std_Obh2*std_Obh2;\n\n        covmat_inv_plk = covmat_inv_plk.i();\n\t}\n\n}\n\n\ndouble Prior_CMB_Dist(  imcmc_double&   param,\n                        double&         lndet,\n                        double&         chisq,\n                        void*           model,\n                        void*           data,\n                        istate&         state ){\n\n    chisq = lndet = 0.0;\n    CosmoTheory *cosmo = static_cast<CosmoTheory*>(model);\n    CMB_Dist    *cmbdist = static_cast<CMB_Dist*>(data);\n\n    double lA, R, z_rec; // this format matches WMAP7/9 distance prior data\n\n    double H0   = cosmo->engine->get_H0();\n    double Om0  = cosmo->engine->get_Omega_m();\n    double ra_rec, rs_rec;\n\n    if( cmbdist->use_Hu_fitting ){\n        z_rec  = cosmo->engine->z_rec_Hu();\n        ra_rec = cosmo->engine->get_Da(z_rec)*(1.+z_rec)/cosmo->engine->get_a_today();\n        rs_rec = cosmo->engine->get_rs(z_rec);\n    }\n    else{\n        z_rec  = cosmo->engine->z_rec();\n        ra_rec = cosmo->engine->ra_rec();\n        rs_rec = cosmo->engine->rs_rec();\n    }\n\n    lA = _PI_*ra_rec/rs_rec;\n    R  = sqrt(Om0)*H0*ra_rec/(_c_*1e-3);\n\n    arma::rowvec residual = arma::zeros(1,3);\n\n    switch (cmbdist->format){\n        case 0:\n        // for WMAP distance prior\n            residual(0) = lA;\n            residual(1) = R;\n            residual(2)\t= z_rec;\n            residual = residual - cmbdist->distance_prior;\n            chisq = arma::as_scalar( residual * cmbdist->covmat_inv * residual.t() );\n            break;\n        case 1:\n        // for Planck distance prior\n            residual(0) = R;\n            residual(1) = lA;\n            residual(2)\t= cosmo->engine->get_Omega_b()*(H0/100)*(H0/100);\n            residual = residual - cmbdist->distance_prior_plk;\n            chisq = arma::as_scalar( residual * cmbdist->covmat_inv_plk * residual.t() );\n            break;\n        default:\n            break;\n    }\n\n    return lndet - 0.5*chisq;\n}\n", "meta": {"hexsha": "f39923dc69a43bdbe54242ca8fab7425d920ca06", "size": 5089, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/priors/CMB_Dist_Prior.cpp", "max_stars_repo_name": "LBJ-Wade/ClassMC_DE_EoS", "max_stars_repo_head_hexsha": "eaf9e92fcf867377be622d7627ebdba514fe2bac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-04-26T07:17:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-31T02:41:06.000Z", "max_issues_repo_path": "source/priors/CMB_Dist_Prior.cpp", "max_issues_repo_name": "xyh-cosmo/ClassMC", "max_issues_repo_head_hexsha": "eaf9e92fcf867377be622d7627ebdba514fe2bac", "max_issues_repo_licenses": ["MIT"], "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/priors/CMB_Dist_Prior.cpp", "max_forks_repo_name": "xyh-cosmo/ClassMC", "max_forks_repo_head_hexsha": "eaf9e92fcf867377be622d7627ebdba514fe2bac", "max_forks_repo_licenses": ["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.80625, "max_line_length": 103, "alphanum_fraction": 0.6362743172, "num_tokens": 1512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2517912246389341}}
{"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/LevenbergMarquardt.h>\n#include <vw/Math/Matrix.h>\n#include <vw/Camera/CameraModel.h>\n#include <asp/IsisIO/IsisInterfaceLineScan.h>\n\n#include <algorithm>\n#include <vector>\n\n#include <Camera.h>\n#include <CameraDetectorMap.h>\n#include <CameraDistortionMap.h>\n#include <CameraFocalPlaneMap.h>\n#include <iTime.h>\n\n#include <boost/smart_ptr/scoped_ptr.hpp>\n\nusing namespace vw;\nusing namespace asp;\nusing namespace asp::isis;\n\n// Construct\nIsisInterfaceLineScan::IsisInterfaceLineScan(std::string const& filename): IsisInterface(filename), m_alphacube(*m_cube) {\n\n  // Gutting Isis::Camera\n  m_distortmap = m_camera->DistortionMap();\n  m_focalmap   = m_camera->FocalPlaneMap();\n  m_detectmap  = m_camera->DetectorMap();\n}\n\n// Custom Function to help avoid over invoking the deeply buried\n// functions of Isis::Sensor\nvoid IsisInterfaceLineScan::SetTime(Vector2 const& px, bool calc_pose) const {\n  if (px != m_c_location) {\n    m_c_location = px;\n    m_detectmap->SetParent(m_alphacube.AlphaSample(px[0]),\n                           m_alphacube.AlphaLine(px[1]));\n\n    if (calc_pose) {\n      // Calculating the spacecraft position and orientation (hence pose)\n      m_camera->instrumentPosition(&m_center[0]);\n      m_center *= 1000;\n\n      std::vector<double> rot_inst = m_camera->instrumentRotation()->Matrix();\n      std::vector<double> rot_body = m_camera->bodyRotation()->Matrix();\n      MatrixProxy<double,3,3> R_inst(&(rot_inst[0]));\n      MatrixProxy<double,3,3> R_body(&(rot_body[0]));\n      m_pose = Quat(R_body*transpose(R_inst));\n    }\n  }\n}\n\nclass EphemerisLMA : public vw::math::LeastSquaresModelBase<EphemerisLMA> {\n  vw::Vector3 m_point;\n  Isis::Camera* m_camera;\n  Isis::CameraDistortionMap *m_distortmap;\n  Isis::CameraFocalPlaneMap *m_focalmap;\npublic:\n  typedef vw::Vector<double> result_type; // Back project result\n  typedef vw::Vector<double> domain_type; // Ephemeris time\n  typedef vw::Matrix<double> jacobian_type;\n\n  inline EphemerisLMA(vw::Vector3 const& point,\n                      Isis::Camera* camera,\n                      Isis::CameraDistortionMap* distortmap,\n                      Isis::CameraFocalPlaneMap* focalmap) : m_point(point), m_camera(camera), m_distortmap(distortmap), m_focalmap(focalmap) {}\n\n  inline result_type operator()(domain_type const& x) const;\n};\n\n\n// LMA for projecting point to linescan camera\nEphemerisLMA::result_type\nEphemerisLMA::operator()(EphemerisLMA::domain_type const& x) const {\n\n  // Setting Ephemeris Time\n  m_camera->setTime(Isis::iTime(x[0]));\n\n  // Calculating the look direction in camera frame\n  Vector3 instru;\n  m_camera->instrumentPosition(&instru[0]);\n  instru *= 1000;  // Spice gives in km\n  Vector3 lookB = normalize(m_point - instru);\n  std::vector<double> lookB_copy(3);\n  std::copy(lookB.begin(), lookB.end(), lookB_copy.begin());\n  std::vector<double> lookJ = m_camera->bodyRotation()->J2000Vector(lookB_copy);\n  std::vector<double> lookC = m_camera->instrumentRotation()->ReferenceVector(lookJ);\n  Vector3 look;\n  std::copy(lookC.begin(), lookC.end(), look.begin());\n\n  // Projecting to mm focal plane\n  look = m_camera->FocalLength() * (look / look[2]);\n  m_distortmap->SetUndistortedFocalPlane(look[0], look[1]);\n  m_focalmap->SetFocalPlane(m_distortmap->FocalPlaneX(),\n                            m_distortmap->FocalPlaneY());\n  result_type result(1);\n  // Not exactly sure about lineoffset .. but ISIS does it\n  result[0] = m_focalmap->DetectorLineOffset() - m_focalmap->DetectorLine();\n\n  return result;\n}\n\nVector2\nIsisInterfaceLineScan::point_to_pixel(Vector3 const& point) const {\n\n  // First seed LMA with an ephemeris time in the middle of the image\n  double middle = lines() / 2;\n  m_detectmap->SetParent(1, m_alphacube.AlphaLine(middle));\n  double start_e = m_camera->time().Et();\n\n  // Build LMA\n  EphemerisLMA model(point, m_camera.get(), m_distortmap, m_focalmap);\n  int status;\n  Vector<double> objective(1), start(1);\n  start[0] = start_e;\n  Vector<double> solution_e = math::levenberg_marquardt(model,\n                                                        start,\n                                                        objective,\n                                                        status);\n\n  // Make sure we found ideal time\n  VW_ASSERT(status > 0, vw::camera::PointToPixelErr() << \" Unable to project point into ISIS linescan camera \");\n\n  // Converting now to pixel\n  m_camera->setTime(Isis::iTime(solution_e[0]));\n\n  // Working out pointing\n  m_camera->instrumentPosition(&m_center[0]);\n  m_center *= 1000;\n  Vector3 look = normalize(point-m_center);\n\n  // Calculating rotation to camera frame\n  std::vector<double> rot_inst = m_camera->instrumentRotation()->Matrix();\n  std::vector<double> rot_body = m_camera->bodyRotation()->Matrix();\n  MatrixProxy<double,3,3> R_inst(&(rot_inst[0]));\n  MatrixProxy<double,3,3> R_body(&(rot_body[0]));\n  m_pose = Quat(R_body*transpose(R_inst));\n\n  look = inverse(m_pose).rotate(look);\n  look = m_camera->FocalLength() * (look / look[2]);\n  m_distortmap->SetUndistortedFocalPlane(look[0], look[1]);\n  m_focalmap->SetFocalPlane(m_distortmap->FocalPlaneX(),\n                            m_distortmap->FocalPlaneY());\n  m_detectmap->SetDetector(m_focalmap->DetectorSample(),\n                           m_focalmap->DetectorLine());\n  Vector2 pixel(m_detectmap->ParentSample(),\n                m_detectmap->ParentLine());\n  pixel[0] = m_alphacube.BetaSample(pixel[0]);\n  pixel[1] = m_alphacube.BetaLine(pixel[1]);\n  SetTime(pixel, false);\n\n  pixel -= Vector2(1,1);\n  return pixel;\n}\n\nVector3\nIsisInterfaceLineScan::pixel_to_vector(Vector2 const& pix) const {\n  Vector2 px = pix + Vector2(1,1);\n  SetTime(px, true);\n\n  // Projecting to get look direction\n  Vector3 result;\n  m_focalmap->SetDetector(m_detectmap->DetectorSample(),\n                          m_detectmap->DetectorLine());\n  m_distortmap->SetFocalPlane(m_focalmap->FocalPlaneX(),\n                              m_focalmap->FocalPlaneY());\n  result[0] = m_distortmap->UndistortedFocalPlaneX();\n  result[1] = m_distortmap->UndistortedFocalPlaneY();\n  result[2] = m_distortmap->UndistortedFocalPlaneZ();\n  result = normalize(result);\n  result = m_pose.rotate(result);\n  return result;\n}\n\nVector3\nIsisInterfaceLineScan::camera_center(Vector2 const& pix) const {\n  Vector2 px = pix + Vector2(1,1);\n  SetTime(px, true);\n  return m_center;\n}\n\nQuat\nIsisInterfaceLineScan::camera_pose(Vector2 const& pix) const {\n  Vector2 px = pix + Vector2(1,1);\n  SetTime(px, true);\n  return m_pose;\n}\n", "meta": {"hexsha": "ad8c459a715b1cc219ded9913f3152e9312eb44f", "size": 7292, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/asp/IsisIO/IsisInterfaceLineScan.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/IsisIO/IsisInterfaceLineScan.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/IsisIO/IsisInterfaceLineScan.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": 35.7450980392, "max_line_length": 144, "alphanum_fraction": 0.6903455842, "num_tokens": 1961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.2517912246389341}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_NATEARTH_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_NATEARTH_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// 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 Boost.Geometry by Barend Gehrels\n\n// Last updated version of proj: 4.9.1\n\n// Original copyright notice:\n\n// The Natural Earth projection was designed by Tom Patterson, US National Park\n// Service, in 2007, using Flex Projector. The shape of the original projection\n// was defined at every 5 degrees and piece-wise cubic spline interpolation was\n// used to compute the complete graticule.\n// The code here uses polynomial functions instead of cubic splines and\n// is therefore much simpler to program. The polynomial approximation was\n// developed by Bojan Savric, in collaboration with Tom Patterson and Bernhard\n// Jenny, Institute of Cartography, ETH Zurich. It slightly deviates from\n// Patterson's original projection by adding additional curvature to meridians\n// where they meet the horizontal pole line. This improvement is by intention\n// and designed in collaboration with Tom Patterson.\n// Port to PROJ.4 by Bernhard Jenny, 6 June 2011\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/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 natearth {};\n\n}} //namespace srs::par4\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace natearth\n    {\n\n            static const double A0 = 0.8707;\n            static const double A1 = -0.131979;\n            static const double A2 = -0.013791;\n            static const double A3 = 0.003971;\n            static const double A4 = -0.001529;\n            static const double B0 = 1.007226;\n            static const double B1 = 0.015085;\n            static const double B2 = -0.044475;\n            static const double B3 = 0.028874;\n            static const double B4 = -0.005916;\n            static const double C0 = B0;\n            static const double C1 = (3 * B1);\n            static const double C2 = (7 * B2);\n            static const double C3 = (9 * B3);\n            static const double C4 = (11 * B4);\n            static const double EPS = 1e-11;\n            //static const double MAX_Y = (0.8707 * 0.52 * geometry::math::pi<double>());\n\n            template <typename T>\n            inline T MAX_Y() { return (0.8707 * 0.52 * detail::ONEPI<T>()); }\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename CalculationType, typename Parameters>\n            struct base_natearth_spheroid : public base_t_fi<base_natearth_spheroid<CalculationType, Parameters>,\n                     CalculationType, Parameters>\n            {\n\n                typedef CalculationType geographic_type;\n                typedef CalculationType cartesian_type;\n\n\n                inline base_natearth_spheroid(const Parameters& par)\n                    : base_t_fi<base_natearth_spheroid<CalculationType, Parameters>,\n                     CalculationType, 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                    CalculationType phi2, phi4;\n\n                    phi2 = lp_lat * lp_lat;\n                    phi4 = phi2 * phi2;\n                    xy_x = lp_lon * (A0 + phi2 * (A1 + phi2 * (A2 + phi4 * phi2 * (A3 + phi2 * A4))));\n                    xy_y = lp_lat * (B0 + phi2 * (B1 + phi4 * (B2 + B3 * phi2 + B4 * phi4)));\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                    static const CalculationType MAX_Y = natearth::MAX_Y<CalculationType>();\n\n                    CalculationType yc, tol, y2, y4, f, fder;\n\n                    /* make sure y is inside valid range */\n                    if (xy_y > MAX_Y) {\n                        xy_y = MAX_Y;\n                    } else if (xy_y < -MAX_Y) {\n                        xy_y = -MAX_Y;\n                    }\n\n                    /* latitude */\n                    yc = xy_y;\n                        for (;;) { /* Newton-Raphson */\n                        y2 = yc * yc;\n                        y4 = y2 * y2;\n                        f = (yc * (B0 + y2 * (B1 + y4 * (B2 + B3 * y2 + B4 * y4)))) - xy_y;\n                        fder = C0 + y2 * (C1 + y4 * (C2 + C3 * y2 + C4 * y4));\n                        yc -= tol = f / fder;\n                        if (fabs(tol) < EPS) {\n                            break;\n                        }\n                    }\n                    lp_lat = yc;\n\n                    /* longitude */\n                    y2 = yc * yc;\n                    lp_lon = xy_x / (A0 + y2 * (A1 + y2 * (A2 + y2 * y2 * y2 * (A3 + y2 * A4))));\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"natearth_spheroid\";\n                }\n\n            };\n\n            // Natural Earth\n            template <typename Parameters>\n            inline void setup_natearth(Parameters& par)\n            {\n                par.es = 0;\n            }\n\n    }} // namespace detail::natearth\n    #endif // doxygen\n\n    /*!\n        \\brief Natural Earth 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 Example\n        \\image html ex_natearth.gif\n    */\n    template <typename CalculationType, typename Parameters>\n    struct natearth_spheroid : public detail::natearth::base_natearth_spheroid<CalculationType, Parameters>\n    {\n        inline natearth_spheroid(const Parameters& par) : detail::natearth::base_natearth_spheroid<CalculationType, Parameters>(par)\n        {\n            detail::natearth::setup_natearth(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::natearth, natearth_spheroid, natearth_spheroid)\n\n        // Factory entry(s)\n        template <typename CalculationType, typename Parameters>\n        class natearth_entry : public detail::factory_entry<CalculationType, Parameters>\n        {\n            public :\n                virtual base_v<CalculationType, Parameters>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<natearth_spheroid<CalculationType, Parameters>, CalculationType, Parameters>(par);\n                }\n        };\n\n        template <typename CalculationType, typename Parameters>\n        inline void natearth_init(detail::base_factory<CalculationType, Parameters>& factory)\n        {\n            factory.add_to_factory(\"natearth\", new natearth_entry<CalculationType, Parameters>);\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n} // namespace projections\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_NATEARTH_HPP\n\n", "meta": {"hexsha": "dcd259d9d1e6dc39d05965e0b6a074a990bd58fe", "size": 9334, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost_1_67_0/boost/geometry/srs/projections/proj/natearth.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/proj/natearth.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/proj/natearth.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": 40.7598253275, "max_line_length": 132, "alphanum_fraction": 0.6155988858, "num_tokens": 2162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.25179121908261876}}
{"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 MINIMIZER_H\n#define MINIMIZER_H\n\n#include <iostream>\n#include <cassert>\n#include <utility>\n#include <Eigen/Core>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_multimin.h>\n\n#include \"error.hpp\"\n#include \"ewsb_solver.hpp\"\n#include \"logger.hpp\"\n#include \"gsl_utils.hpp\"\n#include \"gsl_vector.hpp\"\n\nnamespace flexiblesusy {\n\n/**\n * @class Minimizer\n * @brief Function minimizer\n *\n * The user has to provide the function to be minimized of the type\n * Function_t.  This function gets as arguments an Eigen vector of\n * lenght `dimension' and returns a double.\n *\n * Example:\n * @code\n * auto parabola = [](const Eigen::Matrix<double,2,1>& x) -> double {\n *    const double y = x(0);\n *    const double z = x(1);\n *    return Sqr(y - 5.0) + Sqr(z - 1.0);\n * };\n *\n * Minimizer<2> minimizer(parabola, 100, 1.0e-5);\n * const double start[2] = { 10, 10 };\n * const int status = minimizer.minimize(start);\n * @endcode\n */\ntemplate <std::size_t dimension>\nclass Minimizer : public EWSB_solver {\npublic:\n   using Vector_t = Eigen::Matrix<double,dimension,1>;\n   using Function_t = std::function<double(const Vector_t&)>;\n   enum Solver_type { GSLSimplex, GSLSimplex2, GSLSimplex2Rand };\n\n   Minimizer() = default;\n   template <typename F>\n   Minimizer(F&&, std::size_t, double, Solver_type solver_type_ = GSLSimplex2);\n   virtual ~Minimizer() = default;\n\n   double get_minimum_value() const { return minimum_value; }\n   template <typename F>\n   void set_function(F&& f) { function = std::forward<F>(f); }\n   void set_precision(double p) { precision = p; }\n   void set_max_iterations(std::size_t n) { max_iterations = n; }\n   void set_solver_type(Solver_type t) { solver_type = t; }\n   int minimize(const Vector_t&);\n\n   // EWSB_solver interface methods\n   virtual std::string name() const override { return \"Minimizer\"; }\n   virtual int solve(const Eigen::VectorXd&) override;\n   virtual Eigen::VectorXd get_solution() const override { return minimum_point; }\n\nprivate:\n   std::size_t max_iterations{100};     ///< maximum number of iterations\n   double precision{1.e-2};             ///< precision goal\n   double minimum_value{0.};            ///< minimum function value found\n   Vector_t minimum_point{Vector_t::Zero()}; ///< vector of minimum point\n   Function_t function{nullptr};        ///< function to minimize\n   Solver_type solver_type{GSLSimplex2};///< solver type\n\n   void print_state(gsl_multimin_fminimizer*, std::size_t) const;\n   static double gsl_function(const gsl_vector*, void*);\n   const gsl_multimin_fminimizer_type* solver_type_to_gsl_pointer() const;\n};\n\n/**\n * Constructor\n *\n * @param function_ pointer to the function to minimize\n * @param max_iterations_ maximum number of iterations\n * @param precision_ precision goal\n * @param solver_type_ GSL multimin minimizer type\n */\ntemplate <std::size_t dimension>\ntemplate <typename F>\nMinimizer<dimension>::Minimizer(\n   F&& function_,\n   std::size_t max_iterations_,\n   double precision_,\n   Solver_type solver_type_\n)\n   : max_iterations(max_iterations_)\n   , precision(precision_)\n   , function(std::forward<F>(function_))\n   , solver_type(solver_type_)\n{\n}\n\n/**\n * Start the minimization\n *\n * @param start starting point\n *\n * @return GSL error code (GSL_SUCCESS if minimum found)\n */\ntemplate <std::size_t dimension>\nint Minimizer<dimension>::minimize(const Vector_t& start)\n{\n   if (!function)\n      throw SetupError(\"Minimizer: function not callable\");\n\n   gsl_multimin_fminimizer *minimizer;\n   gsl_multimin_function minex_func;\n\n   GSL_vector min_point = to_GSL_vector(start);\n\n   // Set initial step sizes\n   GSL_vector step_size(dimension);\n   step_size.set_all(1.0);\n\n   // Initialize method and iterate\n   minex_func.n = dimension;\n   minex_func.f = gsl_function;\n   minex_func.params = &function;\n\n   minimizer = gsl_multimin_fminimizer_alloc(solver_type_to_gsl_pointer(), dimension);\n   gsl_multimin_fminimizer_set(minimizer, &minex_func, min_point.raw(), step_size.raw());\n\n   size_t iter = 0;\n   int status;\n\n   do {\n      iter++;\n      status = gsl_multimin_fminimizer_iterate(minimizer);\n\n      if (status)\n         break;\n\n      const double size = gsl_multimin_fminimizer_size(minimizer);\n      status = gsl_multimin_test_size(size, precision);\n\n#ifdef ENABLE_VERBOSE\n      print_state(minimizer, iter);\n#endif\n   } while (status == GSL_CONTINUE && iter < max_iterations);\n\n   VERBOSE_MSG(\"\\t\\t\\tMinimization status = \" << gsl_strerror(status));\n\n   // save minimum point and function value\n   minimum_point = to_eigen_vector_fixed<dimension>(minimizer->x);\n   minimum_value = minimizer->fval;\n\n   gsl_multimin_fminimizer_free(minimizer);\n\n   return status;\n}\n\n/**\n * Print state of the minimizer\n *\n * @param minimizer minimizer\n * @param iteration iteration number\n */\ntemplate <std::size_t dimension>\nvoid Minimizer<dimension>::print_state(gsl_multimin_fminimizer* minimizer,\n                                               std::size_t iteration) const\n{\n   VERBOSE_MSG(\"\\t\\t\\tIteration \" << iteration\n               << \": x = \" << GSL_vector(minimizer->x)\n               << \", f(x) = \" << minimizer->fval);\n}\n\ntemplate <std::size_t dimension>\nint Minimizer<dimension>::solve(const Eigen::VectorXd& start)\n{\n   return (minimize(start) == GSL_SUCCESS ?\n           EWSB_solver::SUCCESS : EWSB_solver::FAIL);\n}\n\ntemplate <std::size_t dimension>\ndouble Minimizer<dimension>::gsl_function(const gsl_vector* x, void* params)\n{\n   if (!is_finite(x))\n      return std::numeric_limits<double>::max();\n\n   Function_t* fun = static_cast<Function_t*>(params);\n   const Vector_t arg(to_eigen_vector_fixed<dimension>(x));\n   double result = std::numeric_limits<double>::max();\n\n   try {\n      result = (*fun)(arg);\n   } catch (const flexiblesusy::Error&) {\n   }\n\n   return result;\n}\n\ntemplate <std::size_t dimension>\nconst gsl_multimin_fminimizer_type* Minimizer<dimension>::solver_type_to_gsl_pointer() const\n{\n   switch (solver_type) {\n   case GSLSimplex     : return gsl_multimin_fminimizer_nmsimplex;\n   case GSLSimplex2    : return gsl_multimin_fminimizer_nmsimplex2;\n   case GSLSimplex2Rand: return gsl_multimin_fminimizer_nmsimplex2rand;\n   default:\n      throw SetupError(\"Unknown minimizer solver type: \"\n                       + std::to_string(solver_type));\n   }\n\n   return nullptr;\n}\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "460befbb2a644a4af691b9216ede9231b946c540", "size": 7146, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/src/minimizer.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/minimizer.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/minimizer.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": 30.2796610169, "max_line_length": 92, "alphanum_fraction": 0.6893366919, "num_tokens": 1762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.25170283659973186}}
{"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 {\n  namespace detail {\n\n    template <class Graph, class UblasMatrix, class BackInsertionSequence, class EdgeLabeling>\n    bool forward_checking(const Graph& g1, const Graph& g2,\n                          UblasMatrix& M, size_t count, BackInsertionSequence& F, size_t num_vert_g1,\n                          size_t num_vert_g2, EdgeLabeling& edge_labeling){\n      typedef std::pair<typename graph_traits<Graph>::edge_descriptor,bool> 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 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            }\n            else if ( !flag1_1 && !flag2_1 ) { // or both edges are not present\n              M(k,l)=1;\n            }\n            else 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 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)) break;\n          else ++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\n    template <class Graph, class EdgeLabeling, class UblasMatrix, class BackInsertionSequence>\n    bool backtrack(const Graph& g1, const Graph& g2, size_t count,\n                   const UblasMatrix& M, BackInsertionSequence& F, const size_t num_vert_g1,\n                   const size_t num_vert_g2, 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,edge_labeling)){\n            if(backtrack(g1,g2,count+1,M_prime,F,num_vert_g1,num_vert_g2,edge_labeling)){\n              return true;\n            }\n          }\n          F.erase(std::remove(F.begin(),F.end(),std::make_pair(count,i)), F.end());\n        }\n      }\n      return false;\n    }\n\n    template <class Graph, class EdgeLabeling, class UblasMatrix, class DoubleBackInsertionSequence>\n    void backtrack_all(const Graph& g1, const Graph& g2, size_t count,\n                       const UblasMatrix& M, DoubleBackInsertionSequence& FF, const size_t num_vert_g1,\n                       const size_t num_vert_g2, 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=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,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,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,edge_labeling);\n          if(tFF.size()){\n            for(typename DoubleBackInsertionSequence::const_iterator iter=tFF.begin();\n                iter!=tFF.end();++iter){\n              FF.push_back(*iter);\n            }\n          }\n        }\n      }\n    }\n\n    template <  class Graph\n                , class VertexLabeling    // binary predicate\n                ,  class UblasMatrix\n                >\n    void prepareM(const Graph& g1, const Graph& g2,\n                  VertexLabeling& vertex_labeling,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          }\n          else M(i,j)=0;\n        }\n      }\n    }\n  }  // namespace detail\n\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!\n  template <  class Graph\n              , class VertexLabeling    // binary predicate\n              , class EdgeLabeling      // binary predicate\n              , class BackInsertionSequence   // contains std::pair<vertex_descriptor,vertex_descriptor>\n              >\n  bool ullmann(const Graph& g1, const Graph& g2,\n               VertexLabeling& vertex_labeling, 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\n  template <  class Graph\n              , class VertexLabeling    // binary predicate\n              , class EdgeLabeling      // binary predicate\n              , class DoubleBackInsertionSequence   // contains a back insertion sequence\n              >\n  bool ullmann_all(const Graph& g1, const Graph& g2,\n                   VertexLabeling& vertex_labeling, EdgeLabeling& edge_labeling, 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\n#endif // MORPHO_CDL_BGL_EXP_ULLMANN_HPP\n\n\n", "meta": {"hexsha": "dbf89b49251acdcff80a067e553ffbf9ee5963ce", "size": 9958, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Code/GraphMol/Substruct/ullmann.hpp", "max_stars_repo_name": "jungb-basf/rdkit", "max_stars_repo_head_hexsha": "5d0eb77c655b6ba91f0891e7dc51e658aced3d00", "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/Substruct/ullmann.hpp", "max_issues_repo_name": "jungb-basf/rdkit", "max_issues_repo_head_hexsha": "5d0eb77c655b6ba91f0891e7dc51e658aced3d00", "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/Substruct/ullmann.hpp", "max_forks_repo_name": "jungb-basf/rdkit", "max_forks_repo_head_hexsha": "5d0eb77c655b6ba91f0891e7dc51e658aced3d00", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-04T07:21:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-04T07:21:45.000Z", "avg_line_length": 40.6448979592, "max_line_length": 114, "alphanum_fraction": 0.5974091183, "num_tokens": 2453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.25168853333604696}}
{"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//#pragma optimize( \"\", off )\n#include <boost/foreach.hpp>\n#include \"sfa/Point.h\"\n#include \"lmfit/lmmin.h\"\n#include \"sfa/PlaneFitter.h\"\n\n//#define PLANEFIT_DEBUG_OUTPUT\n\nnamespace sfa\n{\n    struct PlaneFitter::PlaneFitterData\n    {\n        lm_control_struct   control_struct;\n        lm_status_struct    status_struct;\n        Point plane[3];\n        PointList points;\n        std::vector<bool> constrainedIndices;\n        bool forceBelow;\n        typedef std::pair<int, int> intpair_t;\n        //Pairs of indices into the point list\n        //each pair should be the same Z (to keep roads flat for instance)\n        std::vector<intpair_t> samePoints;\n\n        //Interpolate Z from a plane\n        bool interpolatePointInPlane(sfa::Point *pt, double &z)\n        {\n            plane[0].setZ(plane[0].Z() + plane[0].M());\n            plane[1].setZ(plane[1].Z() + plane[1].M());\n            plane[2].setZ(plane[2].Z() + plane[2].M());\n            sfa::Point P = *pt - plane[0];\n            sfa::Point U = plane[1] - plane[0];\n            sfa::Point V = plane[2] - plane[0];\n            double denom = V.X() * U.Y() - V.Y() * U.X();\n            double v = (P.X() * U.Y() - P.Y() * U.X()) / denom;\n            double u = (P.Y() * V.X() - P.X() * V.Y()) / denom;\n            z = (plane[0].Z() + (u * U.Z()) + (v * V.Z()));\n            if (z != z)\n                return false;\n            return true;\n\n        }\n    };\n\n    void PlaneFitter::constrainPair(int a, int b)\n    {\n        intpair_t ipair;\n        ipair.first = a;\n        ipair.second = b;\n        data->samePoints.push_back(ipair);\n    }\n    void PlaneFitter::constrainPoint(size_t idx)\n    {\n        data->constrainedIndices[idx] = true;\n    }\n\n    PlaneFitter::~PlaneFitter()\n    {\n        delete data;\n    }\n\n    PlaneFitter::PlaneFitter(const sfa::PointList points, bool forceBelowPoints)\n    {\n        log.init(\"PlaneFitter\", this);\n        validFit = false;\n        data = new PlaneFitterData;\n        data->control_struct = lm_control_double;\n        //data->control_struct.printflags = 3;\n        data->points = points;\n        data->forceBelow = forceBelowPoints;\n        data->constrainedIndices.resize(points.size());\n        for (size_t i = 0, ic = points.size(); i < ic; i++)\n        {\n            data->constrainedIndices[i] = false;\n        }\n        if (points.size() > 0)\n        {\n            //Use the first point as the origin, and two other points to form a right triangle as the plane's basis\n            data->plane[0] = *points.at(0);\n            data->plane[0].clearM();\n            data->plane[1] = data->plane[0];\n            data->plane[1].setX(data->plane[1].X() + 10);\n            data->plane[2] = data->plane[0];\n            data->plane[2].setY(data->plane[0].Y() + 10);\n        }\n    }\n\n    void PlaneFitter::setInitialBasis(sfa::Point pt, int idx)\n    {\n        if (idx < 0 || idx > 2)\n            return;\n        data->plane[idx] = pt;\n    }\n\n    bool PlaneFitter::Fit()\n    {\n        double par[3];\n        if (data->points.size() < 3)\n            return true;        \n\n        // Use the first point's Z as the initial guess of a flat plane\n        par[0] = data->plane[0].Z();\n        par[1] = data->plane[1].Z();\n        par[2] = data->plane[2].Z();\n\n        data->status_struct.outcome = 0;\n        data->control_struct.patience = 100;\n        \n        //the three parameters are our three Z values for the plane\n        lmmin(3, par, data->points.size(), (void*)data, PlaneFitter::Callback, &data->control_struct, &data->status_struct);\n        \n        //If we ran out of patience, use the average of the constrained points.\n        if (data->status_struct.outcome == 5)\n        {\n            int num_constrained = 0;\n            double constrained_sum = 0;\n            for (size_t i = 0, ic = data->points.size(); i < ic; i++)\n            {\n                if (data->constrainedIndices[i])\n                {\n                    num_constrained++;\n                    constrained_sum += data->points[i]->Z();\n                }\n            }\n            if (num_constrained)\n            {\n                double constrained_avg = constrained_sum/num_constrained;\n\n#ifdef PLANEFIT_DEBUG_OUTPUT\n                log << ccl::LERR << \"Too many constraints (\" << num_constrained << \"), ran out of patience. Using average of (\" << constrained_avg << \") contraints Z to create a flat plane\" << log.endl;\n                for (size_t i = 0, ic = data->points.size(); i < ic; i++)\n                {\n                    bool constrained = data->constrainedIndices.at(i);\n                    \n                    log << ccl::LERR << \"\\tPoint: \" << data->points[i]->X() << \" , \" << data->points[i]->Y() << \" , \" << data->points[i]->Z() << \" , \" << data->points[i]->M();\n                    if (constrained)\n                        log << \" (C)\";\n                    log << log.endl;\n                }\n                log << \"\\tPlane\" << log.endl;\n                for (size_t i = 0, ic = 3; i < ic; i++)\n                {\n                    log << ccl::LERR << \"\\t\\tPoint: \" << data->plane[i].X() << \" , \" << data->plane[i].Y() << \" , \" << data->plane[i].Z() << \" , \" << data->plane[i].M() << log.endl;\n                }\n#endif\n                data->plane[0].setZ(constrained_avg);\n                data->plane[1].setZ(constrained_avg);\n                data->plane[2].setZ(constrained_avg);\n                validFit = true;\n                return true;\n            }\n            else\n            {\n#ifdef PLANEFIT_DEBUG_OUTPUT\n                log << ccl::LERR << \"Ran out of patience fitting a plane for \" << log.endl;\n                for (size_t i = 0, ic = data->points.size(); i < ic; i++)\n                {\n                    log << ccl::LERR << \"\\tPoint: \" << data->points[i]->X() << \" , \" << data->points[i]->Y() << \" , \" << data->points[i]->Z() << \" , \" << data->points[i]->M() << log.endl;\n                }\n                log << \"\\tPlane\" << log.endl;\n                for (size_t i = 0, ic = 3; i < ic; i++)\n                {\n                    log << ccl::LERR << \"\\t\\tPoint: \" << data->plane[i].X() << \" , \" << data->plane[i].Y() << \" , \" << data->plane[i].Z() << \" , \" << data->plane[i].M() << log.endl;\n                }\n#endif\n            }\n\n        }\n\n        if (data->status_struct.outcome!=5  && data->status_struct.outcome > 3)\n        {\n            validFit = false;\n            if (data->status_struct.outcome > 12 || data->status_struct.outcome < 0)\n                log << ccl::LERR << \"Unable to fit plane. lmmin returns an invalid info message\" << log.endl;\n            else\n                log << ccl::LERR << \"Unable to fit plane. lmmin returns \" << lm_infmsg[data->status_struct.outcome] << log.endl;\n            return false;\n        }\n        validFit = true;\n        return true;\n    }\n       \n\n    void PlaneFitter::Callback(const double *par, int m_dat, const void *data, double *fvec, int *info)\n    {\n        PlaneFitterData* mfd = (PlaneFitterData*)(data);\n        mfd->plane[0].setZ(par[0]);\n        mfd->plane[1].setZ(par[1]);\n        mfd->plane[2].setZ(par[2]);\n        double *deltas = new double[mfd->points.size()];\n        size_t num_points = mfd->points.size();\n        for (size_t i = 0; i < num_points; i++)\n        {\n            sfa::Point *pt = mfd->points.at(i);\n            double z = 0;\n            if (mfd->interpolatePointInPlane(pt, z))\n            {\n                //printf(\"idx=%d error=%f\\n\", i, pt->Z() - z);\n                double delta = abs(pt->Z() - z);\n                deltas[i] = delta;\n                fvec[i] = exp(delta);\n                if (mfd->forceBelow && (z > pt->Z()))\n                    fvec[i] = fvec[i] * mfd->points.size();\n                if (mfd->constrainedIndices[i])\n                {\n                    fvec[i] = fvec[i] * mfd->points.size();//Constraints scale proportionally to the number of points\n                }\n            }            \n        }\n        for (int j = 0, jc = mfd->samePoints.size(); j < jc; j++)\n        {\n            int idxa = mfd->samePoints[j].first;\n            int idxb = mfd->samePoints[j].second;\n            if (idxa < mfd->points.size())\n            {\n                if (idxb < mfd->points.size())\n                {\n                    double pairdelta = abs(deltas[idxa] - deltas[idxb]);\n                    fvec[idxa] += ((1 + pairdelta) * (1 + pairdelta))* mfd->points.size();\n                    fvec[idxb] += ((1 + pairdelta) * (1 + pairdelta))* mfd->points.size();\n                }\n            }\n        }\n\n        delete[] deltas;\n        \n\n    }\n\n    bool PlaneFitter::getPlane(sfa::Point &p1, sfa::Point &p2, sfa::Point &p3)\n    {\n        PlaneFitterData* mfd = (PlaneFitterData*)(data);\n        p1 = mfd->plane[0];\n        p2 = mfd->plane[1];\n        p3 = mfd->plane[2];\n        if (!validFit)\n        {\n#ifdef PLANEFIT_DEBUG_OUTPUT\n            log << ccl::LERR << \"Unable to fit plane, using average Z to form a flat plane.\" << log.endl;\n#endif\n            double sum = 0;\n            PointList::iterator iter = data->points.begin();\n            while (iter != data->points.end())\n            {\n                sfa::Point *pt = *iter++;\n                sum += pt->Z();\n            }\n            double flatz = sum / data->points.size();\n            p1.setZ(flatz);\n            p2.setZ(flatz);\n            p3.setZ(flatz);\n        }\n        return true;\n    }\n\n\n}", "meta": {"hexsha": "7d7f2075d8bee7382622abe5ae6f99e1d0ed5573", "size": 10596, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cognitics/src/sfa/PlaneFitter.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/PlaneFitter.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/PlaneFitter.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": 38.2527075812, "max_line_length": 202, "alphanum_fraction": 0.4994337486, "num_tokens": 2724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2516797101350363}}
{"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: $\n// --------------------------------------------------------------------------\n\n#include <OpenMS/CONCEPT/Macros.h>\n#include <OpenMS/MATH/STATISTICS/LinearRegression.h>\n#include <OpenMS/MATH/STATISTICS/StatisticFunctions.h>\n\n#include \"Wm5Vector2.h\"\n#include \"Wm5ApprLineFit2.h\"\n#include \"Wm5LinearSystem.h\"\n\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/math/distributions.hpp>\n\nusing boost::math::detail::inverse_students_t;\n\nnamespace OpenMS::Math\n{\n    double LinearRegression::getIntercept() const\n    {\n      return intercept_;\n    }\n\n    double LinearRegression::getSlope() const\n    {\n      return slope_;\n    }\n\n    double LinearRegression::getXIntercept() const\n    {\n      return x_intercept_;\n    }\n\n    double LinearRegression::getLower() const\n    {\n      return lower_;\n    }\n\n    double LinearRegression::getUpper() const\n    {\n      return upper_;\n    }\n\n    double LinearRegression::getTValue() const\n    {\n      return t_star_;\n    }\n\n    double LinearRegression::getRSquared() const\n    {\n      return r_squared_;\n    }\n\n    double LinearRegression::getStandDevRes() const\n    {\n      return stand_dev_residuals_;\n    }\n\n    double LinearRegression::getMeanRes() const\n    {\n      return mean_residuals_;\n    }\n\n    double LinearRegression::getStandErrSlope() const\n    {\n      return stand_error_slope_;\n    }\n\n    double LinearRegression::getChiSquared() const\n    {\n      return chi_squared_;\n    }\n\n    double LinearRegression::getRSD() const\n    {\n      return rsd_;\n    }\n\n    void LinearRegression::computeGoodness_(const std::vector<Wm5::Vector2d>& points, double confidence_interval_P)\n    {\n      OPENMS_PRECONDITION(static_cast<unsigned>(points.size()) > 2, \n          \"Cannot compute goodness of fit for regression with less than 3 data points\");\n      // specifically, boost throws an exception for a t-distribution with zero df\n\n      unsigned N = static_cast<unsigned>(points.size());\n      std::vector<double> X; X.reserve(N);\n      std::vector<double> Y; Y.reserve(N);\n      for (unsigned i = 0; i < N; ++i)\n      {\n        X.push_back(points[i].X());\n        Y.push_back(points[i].Y());\n      }\n\n      // Mean of abscissa and ordinate values\n      double x_mean = Math::mean(X.begin(), X.end());\n      double y_mean = Math::mean(Y.begin(), Y.end());\n\n      // Variance and Covariances\n      double var_X = Math::variance(X.begin(), X.end(), x_mean);\n      double var_Y = Math::variance(Y.begin(), Y.end(), y_mean);\n      double cov_XY = Math::covariance(X.begin(), X.end(), Y.begin(), Y.end());\n\n      // S_xx\n      double s_XX = var_X * (N-1);\n      /*for (unsigned i = 0; i < N; ++i)\n      {\n        double d = (X[i] - x_mean);\n        s_XX += d * d;\n      }*/\n\n      // Compute the squared Pearson coefficient\n      r_squared_ = (cov_XY * cov_XY) / (var_X * var_Y);\n\n      // The standard deviation of the residuals\n      double sum = 0;\n      for (unsigned i = 0; i < N; ++i)\n      {\n        double x_i = fabs(Y[i] - (intercept_ + slope_ * X[i]));\n        sum += x_i;\n      }\n      mean_residuals_       = sum / N;\n      stand_dev_residuals_ = sqrt((chi_squared_ - (sum * sum) / N) / (N - 1));\n\n      // The Standard error of the slope\n      stand_error_slope_ = stand_dev_residuals_ / sqrt(s_XX);\n\n      // and the intersection of Y_hat with the x-axis\n      x_intercept_ = -(intercept_ / slope_);\n\n      double P = 1 - (1 - confidence_interval_P) / 2;\n      boost::math::students_t tdist(N - 2);\n      t_star_ = boost::math::quantile(tdist, P);\n\n      //Compute the asymmetric 95% confidence interval of around the X-intercept\n      double g = (t_star_ / (slope_ / stand_error_slope_));\n      g *= g;\n      double left = (x_intercept_ - x_mean) * g;\n      double bottom = 1 - g;\n      double d = (x_intercept_ - x_mean);\n      double right = t_star_ * (stand_dev_residuals_ / slope_) * sqrt((d * d) / s_XX + (bottom / N));\n\n      // Confidence interval lower_ <= X_intercept <= upper_\n      lower_ = x_intercept_ + (left + right) / bottom;\n      upper_ = x_intercept_ + (left - right) / bottom;\n\n      if (lower_ > upper_)\n      {\n        std::swap(lower_, upper_);\n      }\n\n      double tmp = 0;\n      for (unsigned i = 0; i < N; ++i)\n      {\n        tmp += (X[i] - x_mean) * (X[i] - x_mean);\n      }\n\n      //            cout << \"100.0 / abs( x_intercept_ ) \" << (100.0 / fabs( x_intercept_ )) << endl;\n      //            cout << \"tmp : \" << tmp << endl;\n      //            cout << \"slope_ \" << slope_ << endl;\n      //            cout << \"y_mean \" << y_mean << endl;\n      //            cout << \"N \" << N << endl;\n      //            cout << \"stand_dev_residuals_ \" << stand_dev_residuals_ << endl;\n      //            cout << \" (1.0/ (double) N)  \" <<  (1.0/ (double) N)  << endl;\n      //            cout << \"sx hat \" << (stand_dev_residuals_ / slope_) * sqrt(  (1.0/ (double) N) * (y_mean / (slope_ * slope_ * tmp ) ) ) << endl;\n\n      // compute relative standard deviation (non-standard formula, taken from Mayr et al. (2006) )\n      rsd_ = (100.0 / fabs(x_intercept_)) * (stand_dev_residuals_ / slope_) * sqrt((1.0 / (double) N) * (y_mean / (slope_ * slope_ * tmp)));\n\n      if (rsd_ < 0.0)\n      {\n        std::cout << \"rsd < 0.0 \" << std::endl;\n        std::cout << \"Intercept                                  \" << intercept_\n                  << \"\\nSlope                                    \" << slope_\n                  << \"\\nSquared pearson coefficient              \" << r_squared_\n                  << \"\\nValue of the t-distribution              \" << t_star_\n                  << \"\\nStandard deviation of the residuals      \" << stand_dev_residuals_\n                  << \"\\nStandard error of the slope              \" << stand_error_slope_\n                  << \"\\nThe X intercept                          \" << x_intercept_\n                  << \"\\nThe lower border of confidence interval  \" << lower_\n                  << \"\\nThe higher border of confidence interval \" << upper_\n                  << \"\\nChi squared value                        \" << chi_squared_\n                  << \"\\nx mean                                   \" << x_mean\n                  << \"\\nstand_error_slope/slope_                 \" << (stand_dev_residuals_ / slope_)\n                  << \"\\nCoefficient of Variation                 \" << (stand_dev_residuals_ / slope_) / x_mean * 100  << std::endl\n                  << \"=========================================\"\n                  << std::endl;\n      }\n    }\n\n    void LinearRegression::computeRegression(double confidence_interval_P,\n        std::vector<double>::const_iterator x_begin,\n        std::vector<double>::const_iterator x_end,\n        std::vector<double>::const_iterator y_begin,\n        bool compute_goodness)\n    {\n      std::vector<Wm5::Vector2d> points;\n      for(std::vector<double>::const_iterator xIter = x_begin, yIter = y_begin; xIter!=x_end; ++xIter, ++yIter)\n      {\n        points.emplace_back(*xIter, *yIter);\n      }\n\n      // Compute the unweighted linear fit.\n      // Get the intercept and the slope of the regression Y_hat=intercept_+slope_*X\n      // and the value of Chi squared (sum( (y - evel(x))^2)\n      bool pass = Wm5::HeightLineFit2<double>(static_cast<int>(points.size()), &points.front(), slope_, intercept_);\n      chi_squared_ = computeChiSquare(x_begin, x_end, y_begin, slope_, intercept_);\n\n      if (!pass)\n      {\n        throw Exception::UnableToFit(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, \"UnableToFit-LinearRegression\", String(\"Could not fit a linear model to the data (\") + points.size() + \" points).\");\n      }\n\n      if (compute_goodness && points.size() > 2)\n      {\n        computeGoodness_(points, confidence_interval_P);\n      }\n    }\n\n    void LinearRegression::computeRegressionWeighted(double confidence_interval_P, \n        std::vector<double>::const_iterator x_begin, \n        std::vector<double>::const_iterator x_end, \n        std::vector<double>::const_iterator y_begin, \n        std::vector<double>::const_iterator w_begin, \n        bool compute_goodness)    \n     {\n      // Compute the weighted linear fit.\n      // Get the intercept and the slope of the regression Y_hat=intercept_+slope_*X\n      // and the value of Chi squared, the covariances of the intercept and the slope\n      std::vector<Wm5::Vector2d> points;\n      for(std::vector<double>::const_iterator xIter = x_begin, yIter = y_begin; xIter!=x_end; ++xIter, ++yIter)\n      {\n        points.emplace_back(*xIter, *yIter);\n      }\n\n      // Compute sums for linear system. copy&paste from GeometricTools Wm5ApprLineFit2.cpp\n      // and modified to allow weights\n      int numPoints = static_cast<int>(points.size());\n      double sumX = 0, sumY = 0;\n      double sumXX = 0, sumXY = 0;\n      double sumW = 0;\n      auto wIter = w_begin;\n\n      for (int i = 0; i < numPoints; ++i, ++wIter)\n      {\n        sumX += (*wIter) * points[i].X();\n        sumY += (*wIter) * points[i].Y();\n        sumXX += (*wIter) * points[i].X() * points[i].X();\n        sumXY += (*wIter) * points[i].X() * points[i].Y();\n        sumW += (*wIter);\n      }\n      //create matrices to solve Ax = B\n      double A[2][2] =\n      {\n        {sumXX, sumX},\n        {sumX, sumW}\n      };\n      double B[2] =\n      {\n        sumXY,\n        sumY\n      };\n      double X[2];\n\n      bool nonsingular = Wm5::LinearSystem<double>().Solve2(A, B, X);\n      if (nonsingular)\n      {\n        slope_ = X[0];\n        intercept_ = X[1];\n      }\n      chi_squared_ = computeWeightedChiSquare(x_begin, x_end, y_begin, w_begin, slope_, intercept_);\n\n      if (nonsingular)\n      {\n        if (compute_goodness && points.size() > 2) computeGoodness_(points, confidence_interval_P);\n      }\n      else\n      {\n        throw Exception::UnableToFit(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,\n            \"UnableToFit-LinearRegression\", \"Could not fit a linear model to the data\");\n      }\n    }\n\n} // OpenMS //Math\n\n", "meta": {"hexsha": "c88ccd9f61a5a318a80968c9ac81d83a7f2c81fb", "size": 11980, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openms/source/MATH/STATISTICS/LinearRegression.cpp", "max_stars_repo_name": "Amit0617/OpenMS", "max_stars_repo_head_hexsha": "70ef98e32b02721f45fe72bd4de4b4833755a66f", "max_stars_repo_licenses": ["BSL-1.0", "Zlib", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-23T09:45:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T09:45:02.000Z", "max_issues_repo_path": "src/openms/source/MATH/STATISTICS/LinearRegression.cpp", "max_issues_repo_name": "Amit0617/OpenMS", "max_issues_repo_head_hexsha": "70ef98e32b02721f45fe72bd4de4b4833755a66f", "max_issues_repo_licenses": ["BSL-1.0", "Zlib", "Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-04-02T18:07:10.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-02T18:07:10.000Z", "max_forks_repo_path": "src/openms/source/MATH/STATISTICS/LinearRegression.cpp", "max_forks_repo_name": "Amit0617/OpenMS", "max_forks_repo_head_hexsha": "70ef98e32b02721f45fe72bd4de4b4833755a66f", "max_forks_repo_licenses": ["BSL-1.0", "Zlib", "Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-01-10T19:50:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-12T15:56:13.000Z", "avg_line_length": 37.7917981073, "max_line_length": 197, "alphanum_fraction": 0.5741235392, "num_tokens": 2947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.25167971013503626}}
{"text": "#ifndef DXF_TYPES_HPP\n#define DXF_TYPES_HPP\n\n/// SYSTEM\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/segment.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/strategies/transform/matrix_transformers.hpp>\n#include <boost/geometry/strategies/transform/inverse_transformer.hpp>\n\n#include <cmath>\n\n#include <vector>\n#include <algorithm>\n\nnamespace cslibs_boost_geometry {\nnamespace types {\n\nclass Mask {\npublic:\n    Mask(const unsigned int _size) :\n        mask(new bool[_size]),\n        size(_size)\n    {\n        std::fill(mask, mask + _size, true);\n    }\n\n    bool& operator[](const unsigned int i)\n    {\n        return mask[i];\n    }\n\n    void resize(const unsigned int _size)\n    {\n        if(mask != nullptr) {\n            delete [] mask;\n            mask = new bool[_size];\n        }\n\n        size = _size;\n        std::fill(mask, mask + _size, true);\n    }\n\n    virtual ~Mask()\n    {\n        if(mask != nullptr)\n            delete [] mask;\n    }\n\nprivate:\n    bool        *mask;\n    unsigned int size;\n};\n\n/**\n * @brief Type definition for point sets.\n */\ntemplate<typename PointT>\nstruct PointSet {\n    typedef std::vector<PointT>\n    type;\n};\n/**\n * @brief Type definition of a polygon.\n */\ntemplate<typename PointT>\nstruct Polygon {\n    typedef boost::geometry::model::polygon<PointT>\n    type;\n};\n\n/**\n * @brief Type definition for a line.\n */\ntemplate<typename PointT>\nstruct Line {\n    typedef boost::geometry::model::segment<PointT>\n    type;\n};\n/**\n * @brief Type definition for a line set.\n */\ntemplate<typename PointT>\nstruct LineSet {\n    typedef std::vector<boost::geometry::model::segment<PointT> >\n    type;\n\n    static const boost::geometry::model::segment<PointT>& getSegment(const typename type::const_iterator& it) {\n        return *it;\n    }\n\n    static boost::geometry::model::segment<PointT>& getSegment(const typename type::iterator& it) {\n        return *it;\n    }\n};\n/**\n * @brief Type definition for an indexed line set.\n */\ntemplate<typename PointT>\nstruct IndexedLineSet {\n    typedef std::vector<const boost::geometry::model::segment<PointT>* >\n    type;\n\n    static const boost::geometry::model::segment<PointT>& getSegment(const typename type::const_iterator& it) {\n        return **it;\n    }\n};\n\n/**\n * @brief Type definition for a box.\n */\ntemplate<typename PointT>\nstruct Box {\n    typedef boost::geometry::model::box<PointT>\n    type;\n};\n\n/**\n * @brief Type definition for point sets that\n *        can be declared invalid.\n */\ntemplate<typename PointT>\nstruct IntersectionResult {\n    typedef IntersectionResult<PointT>\n    type;\n\n    IntersectionResult() :\n        valid(false)\n    {\n    }\n\n    typename PointSet<PointT>::type result;\n    bool                            valid;\n};\n/**\n * @brief Type definition for a set of\n *        invalidatable point sets.\n */\ntemplate<typename PointT>\nstruct IntersectionResultSet {\n    typedef std::vector<IntersectionResult<PointT> >\n    type;\n};\n\n\n/**\n * @brief Type defintion for a translation.\n */\ntemplate<typename PointT>\nstruct Translation {\n#if BOOST_VERSION >= 105500\n    typedef boost::geometry::strategy::transform::translate_transformer<double, 2, 2>\n#else\n    typedef boost::geometry::strategy::transform::translate_transformer<PointT, PointT>\n#endif\n    type;\n};\n\ntemplate<typename PointT>\nstruct Rotation {\n#if BOOST_VERSION >= 105500\n    typedef boost::geometry::strategy::transform::rotate_transformer<boost::geometry::radian, double, 2, 2>\n#else\n    typedef boost::geometry::strategy::transform::rotate_transformer<PointT, PointT,\n                                                                     boost::geometry::radian>\n#endif\n    type;\n};\n\n/**\n * @brief Invert a translation.\n * @param translation   the translation to be inverted\n * @return              the inverted translation\n */\ntemplate<typename PointT, typename TransT>\nTransT invert(const TransT &translation)\n{\n#if BOOST_VERSION >= 105500\n    return boost::geometry::strategy::transform::inverse_transformer<double, 2, 2>::inverse_transformer(translation);\n#else\n    return boost::geometry::strategy::transform::inverse_transformer<PointT, PointT>::inverse_transformer(translation);\n#endif\n}\n\n\nstruct periodic {\n    inline static double sin(const double rad)\n    {\n        return std::sin(rad);\n    }\n\n    inline static double cos(const double rad)\n    {\n        return std::cos(rad);\n    }\n\n    inline static void sin_cos(const double x,\n                               double &sinx,\n                               double &cosx)\n    {\n        sinx = std::sin(x);\n        cosx = std::cos(x);\n    }\n};\n\n\nstruct periodicApprox {\n    inline static double angleClamp(const double rad)\n    {\n        double rad_(rad);\n        while (rad_ < -M_PI)\n            rad_ += 2*M_PI;\n\n        while (rad_ >= M_PI)\n            rad_ -= 2*M_PI;\n\n        return rad_;\n    }\n\n    inline static double sin(const double rad)\n    {\n        double angle = angleClamp(rad);\n        return fastersinfull(angle);\n\n    }\n\n    inline static double cos(const double rad)\n    {\n        double angle = angleClamp(rad);\n        return fastercosfull(angle);\n    }\n\n    inline static void sin_cos(const double rad,\n                               double &sinx,\n                               double &cosx)\n    {\n        double angle = angleClamp(rad);\n        sinx = fastersinfull(angle);\n        cosx = fastercosfull(angle);\n    }\n\n    ///__________________ FAST MATH _________________///\n\n    static inline float\n    fastsin (float x)\n    {\n      static const float fouroverpi = 1.2732395447351627f;\n      static const float fouroverpisq = 0.40528473456935109f;\n      static const float q = 0.78444488374548933f;\n      union { float f; uint32_t i; } p = { 0.20363937680730309f };\n      union { float f; uint32_t i; } r = { 0.015124940802184233f };\n      union { float f; uint32_t i; } s = { -0.0032225901625579573f };\n\n      union { float f; uint32_t i; } vx = { x };\n      uint32_t sign = vx.i & 0x80000000;\n      vx.i = vx.i & 0x7FFFFFFF;\n\n      float qpprox = fouroverpi * x - fouroverpisq * x * vx.f;\n      float qpproxsq = qpprox * qpprox;\n\n      p.i |= sign;\n      r.i |= sign;\n      s.i ^= sign;\n\n      return q * qpprox + qpproxsq * (p.f + qpproxsq * (r.f + qpproxsq * s.f));\n    }\n\n    static inline float\n    fastersin (float x)\n    {\n      static const float fouroverpi = 1.2732395447351627f;\n      static const float fouroverpisq = 0.40528473456935109f;\n      static const float q = 0.77633023248007499f;\n      union { float f; uint32_t i; } p = { 0.22308510060189463f };\n\n      union { float f; uint32_t i; } vx = { x };\n      uint32_t sign = vx.i & 0x80000000;\n      vx.i &= 0x7FFFFFFF;\n\n      float qpprox = fouroverpi * x - fouroverpisq * x * vx.f;\n\n      p.i |= sign;\n\n      return qpprox * (q + p.f * qpprox);\n    }\n\n    static inline float\n    fastsinfull (float x)\n    {\n      static const float twopi = 6.2831853071795865f;\n      static const float invtwopi = 0.15915494309189534f;\n\n      int k = x * invtwopi;\n      float half = (x < 0) ? -0.5f : 0.5f;\n      return fastsin ((half + k) * twopi - x);\n    }\n\n    static inline float\n    fastersinfull (float x)\n    {\n      static const float twopi = 6.2831853071795865f;\n      static const float invtwopi = 0.15915494309189534f;\n\n      int k = x * invtwopi;\n      float half = (x < 0) ? -0.5f : 0.5f;\n      return fastersin ((half + k) * twopi - x);\n    }\n\n    static inline float\n    fastcosfull (float x)\n    {\n      static const float halfpi = 1.5707963267948966f;\n      return fastsinfull (x + halfpi);\n    }\n\n    static inline float\n    fastercosfull (float x)\n    {\n      static const float halfpi = 1.5707963267948966f;\n      return fastersinfull (x + halfpi);\n    }\n};\n\n/// PREDEFINED TYPES\ntypedef boost::geometry::model::d2::point_xy<double> Point2d;\ntypedef boost::geometry::model::d2::point_xy<float>  Point2f;\ntypedef boost::geometry::model::d2::point_xy<int>    Point2i;\ntypedef Point2i                                      Dim2i;\ntypedef Point2f                                      Dim2f;\ntypedef Point2d                                      Dim2d;\ntypedef Point2i                                      Vec2i;\ntypedef Point2f                                      Vec2f;\ntypedef Point2d                                      Vec2d;\ntypedef Line<Point2d>::type                          Line2d;\ntypedef Line<Point2f>::type                          Line2f;\ntypedef Line<Point2i>::type                          Line2i;\ntypedef Box<Point2d>::type                           Box2d;\ntypedef Box<Point2f>::type                           Box2f;\ntypedef Box<Point2i>::type                           Box2i;\ntypedef PointSet<Point2i>::type                      PointSet2i;\ntypedef PointSet<Point2f>::type                      PointSet2f;\ntypedef PointSet<Point2d>::type                      PointSet2d;\ntypedef Polygon<Point2i>::type                       Polygon2i;\ntypedef Polygon<Point2f>::type                       Polygon2f;\ntypedef Polygon<Point2d>::type                       Polygon2d;\ntypedef IntersectionResultSet<Point2i>::type         Intersection2iResultSet;\ntypedef IntersectionResultSet<Point2f>::type         Intersection2fResultSet;\ntypedef IntersectionResultSet<Point2d>::type         Intersection2dResultSet;\ntypedef IntersectionResult<Point2i>::type            Intersection2iResult;\ntypedef IntersectionResult<Point2f>::type            Intersection2fResult;\ntypedef IntersectionResult<Point2d>::type            Intersection2dResult;\ntypedef LineSet<Point2i>::type                       Line2iSet;\ntypedef LineSet<Point2f>::type                       Line2fSet;\ntypedef LineSet<Point2d>::type                       Line2dSet;\ntypedef Translation<Point2i>::type                   Translation2i;\ntypedef Translation<Point2f>::type                   Translation2f;\ntypedef Translation<Point2d>::type                   Translation2d;\ntypedef Rotation<Point2i>::type                      Rotation2i;\ntypedef Rotation<Point2f>::type                      Rotation2f;\ntypedef Rotation<Point2d>::type                      Rotation2d;\ntypedef std::vector<const Line2i*>                   Line2iPtrSet;\ntypedef std::vector<const Line2f*>                   Line2fPtrSet;\ntypedef std::vector<const Line2d*>                   Line2dPtrSet;\n}\n}\n#endif // DXF_TYPES_HPP\n", "meta": {"hexsha": "0d9e4de06e2db3f67b5b96daa1897f37848dea67", "size": 10387, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cslibs_boost_geometry/types.hpp", "max_stars_repo_name": "cogsys-tuebingen/cslibs_boost_geometry", "max_stars_repo_head_hexsha": "a6438e6ef62afb2699173c75430b7f97e0cc451f", "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/cslibs_boost_geometry/types.hpp", "max_issues_repo_name": "cogsys-tuebingen/cslibs_boost_geometry", "max_issues_repo_head_hexsha": "a6438e6ef62afb2699173c75430b7f97e0cc451f", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/cslibs_boost_geometry/types.hpp", "max_forks_repo_name": "cogsys-tuebingen/cslibs_boost_geometry", "max_forks_repo_head_hexsha": "a6438e6ef62afb2699173c75430b7f97e0cc451f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-16T09:43:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-16T09:43:15.000Z", "avg_line_length": 28.2255434783, "max_line_length": 119, "alphanum_fraction": 0.6052758256, "num_tokens": 2547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2514923244642807}}
{"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/**\n   \\file\n\n   Feature expectations for the expectation semiring.\n\n   the relationship between FeatureWeight (with nonnegative feature values only)\n   and ExpectationWeight is, for a linear derivation (single path):\n\n   FeatureWeight(cost, [1=val1,...])\n\n   is the same as\n\n   ExpectationWeight(cost=-log(prob), [1=-log(val1*prob)=-log(val1)+cost,...])\n\n   times in both cases adds the costs, and the values accumulate in the same way\n   modulo the above isomorphism (exception: FeatureWeight with allowed negative\n   values would not be isomorphic; we would need to introduce a sign bit to the\n   ExpectationWeight's feature values)\n\n   we could have kept the interpretations the same, but this way is more\n   computationally efficient (because FeatureWeight plus selects the best path,\n   while ExpectationWeight sums probabilities/expectations of things)\n\n   think of ExpectationWeight as representing disjoint events.\n\n   the sum of two ExpectationWeight is then a more probable single event.\n\n   the feature vectors' values are -log(p(event)*E[count of feature|event]) - joint, not conditional\n\n   (the overall probability is also a float value that's -log(prob))\n\n   so adding two ExpectationWeight just separately (-LogPlus) adds the probs and\n   expectation vectors\n\n   further, the default value for weight[feature_id] is +infinity, not 0 as it\n   is for featureweight\n\n   the times (product) simply concatenates the events together (multiplying the\n   two probabilities), and the resulting expectations are counts of features over\n   the event (so the product event is less likely, but has more features on it, so\n   higher conditional expectation)\n\n   but because we don't store expectations conditional on the event, but rather\n   the joint expectation in the overall probability distribution, this means that\n   we have (a*b)[i]=-log(prob(a)*prob(b)*E[feature i|a*b]\n\n   where E[feature i|a*b]) := E[feature i|a]+E[feature i|b])\n\n   Now, times in detail:\n\n   the algorithm for C=A*B is:\n\n   costC = costA+costB\n   fC[i] = costA+costB+logplus(fA[i]-costA, fB[i]-costB)\n   =(probs)probA*probB*(pA[i]/probA+pB[i]/probB) = pA[i]*probB + pB[i]*probA\n   = logplus(fA[i]+costB, fB[i]+costA)\n\n   or to add C += B\n\n   fC[i] = logplus(costB + fC[i], costC + fB[i])\n\n   in case fC[i] = fB[i] (same map)\n\n   fC[i] = logplus(costB + fC[i], costC + fC[i]) =(prob) probB*pC[i] + probC*pC[i] = (probB+probC)*pC[i]\n   = logplus(costB, costC) + fC[i]\n\n   in case C==B (so further costB == costC), you can take logplus(costC, costC) = costC-log(2)\n\n\n   graehl thinks it really simplifies thinking about expectations if we use\n   conditional (log) expectations in the feature values map. however, it's\n   currently correct so don't touch it.\n\n   \\author Markus Dreyer\n\n*/\n\n#ifndef HYP__HYPERGRAPH_EXPECTATION_WEIGHT_HPP\n#define HYP__HYPERGRAPH_EXPECTATION_WEIGHT_HPP\n#pragma once\n\n#include <sdl/Hypergraph/FeatureWeight.hpp>\n#include <sdl/Hypergraph/Weight.hpp>\n#include <sdl/Util/Constants.hpp>\n#include <sdl/Util/LogHelper.hpp>\n#include <sdl/Util/LogMath.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <cassert>\n#include <iostream>\n#include <stdexcept>\n#include <string>\n\nnamespace sdl {\nnamespace Hypergraph {\n\n\n/// ExpectationWeight is a type of FeatureWeight, where we take the\n/// sum of values rather than the min:\ntypedef FeatureWeightTpl<FeatureValue, Features, Expectation> ExpectationWeight;\n\n/**\n   Adds another weight to this weight (using semiring\n   plus). This is the version for Expectation policy.\n*/\ntemplate <class FloatT, class MapT, class SumPolicy>\nvoid FeatureWeightTpl<FloatT, MapT, SumPolicy>::plusBy(FeatureWeightTpl<FloatT, MapT, Expectation> const& b) {\n  checkSumPolicy<Expectation>();\n  if (b.isZero()) {\n    // adding zero to this means do nothing. the expectations must all be zero too.\n  } else if (isZero()) {\n    *this = b;\n  } else if (&b == this) {\n    // initially, I thought the pmap equal by pointer case would handle this, but\n    // i was wrong. ownMap() only copies if pointer wasn't unique. but the\n    // pointer will be unique if the objects are identical.\n    const FloatT neglog2 = -std::log((FloatT)2);\n    this->value_ += neglog2;\n    if (pMap_) {\n      ownMap();\n      for (iterator i = pMap_->begin(), e = pMap_->end(); i != e; ++i)\n        i->second += neglog2;  // in prob space, we're adding p1+p2\n    }\n  } else {\n    Util::neglogPlusBy(b.value_, this->value_);\n    assert(!isZero());  // adding two nonzero things can never give a zero result\n    if (pMap_ == b.pMap_) {  // maps equal by pointer. doesn't imply probabilities are the same too\n      if (pMap_) {\n        ownMap();\n        const FloatT neglog2 = -std::log((FloatT)2);\n        for (iterator i = pMap_->begin(), e = pMap_->end(); i != e; ++i)\n          i->second += neglog2;  // in prob space, we're adding p1+p2\n        // by multiplying by 2 (since the maps are the same, the joint probs are all the same)\n      }\n    } else {\n      // add (joint) expectations:\n      if (!b.empty()) {\n        ownMap();\n        MapT& thismap = *pMap_;\n        MapT* bmap = b.pMap_.get();\n        assert(&thismap != bmap);\n        if (bmap)\n          for (typename MapT::const_iterator i = bmap->begin(), e = bmap->end(); i != e; ++i)\n            Util::mapAddNeglogPlus(thismap, i->first, i->second);\n      }\n    }\n  }\n}\n\n/**\n   Multiplies this weight by another weight (using semiring\n   times). This is the version for Expectation policy.\n*/\ntemplate <class FloatT, class MapT, class SumPolicy>\nvoid FeatureWeightTpl<FloatT, MapT, SumPolicy>::timesBy(FeatureWeightTpl<FloatT, MapT, Expectation> const& b) {\n  checkSumPolicy<Expectation>();\n  if (isZero()) {\n  } else if (b.isZero()) {\n    setZero();\n  } else if (b.isOne()) {\n  } else if (isOne()) {\n    *this = b;\n  } else {\n    FloatT const aval = this->value_;\n    FloatT const bval = b.value_;\n    this->value_ = aval + bval;  // pa' = pa*pb\n    if (pMap_ == b.pMap_) {  // special (rare) case to avoid modifying map while reading from it\n      ownMap();  // note: this must occur after the test above\n      // fC[i] <= logplus(costB + fC[i], costC + fB[i]) = logplus(costB, costC) + fC[i]\n      FloatT const aplusbval = Util::neglogPlus(aval, bval);  // we're setting (in prob space) v'=v*(pa+pb)\n      SDL_DEBUG_ALWAYS(Hypergraph.ExpectationWeight, \"same map for a*b; result[i] = a[i] + neglogplus(\"\n                                                         << aval << \", \" << bval << \") = \" << aplusbval);\n      for (typename MapT::iterator i = pMap_->begin(), e = pMap_->end(); i != e; ++i)\n        i->second += aplusbval;  // *=(pa+pb)\n    } else {\n      assert(this != &b);\n      ownMap();\n      // fC[i] = logplus(costB + fC[i], costC + fB[i])\n      // multiply A expectations by probB\n      for (typename MapT::iterator i = pMap_->begin(), e = pMap_->end(); i != e; ++i) i->second += bval;\n      // then add (B expectations multiplied by probA).\n      if (!b.empty()) {\n        MapT& thismap = *pMap_;\n        MapT const* bmap = b.pMap_.get();\n        assert(&thismap != bmap);\n        if (bmap)\n          for (typename MapT::const_iterator i = bmap->begin(), e = bmap->end(); i != e; ++i)\n            Util::mapAddNeglogPlus(thismap, i->first, i->second + aval);\n      }\n    }\n    assert(!isZero());  // we shouldn't ever underflow by adding two non-zero probs in logspace\n  }\n}\n\n\ntemplate <class FloatT, class MapT>\ninline FeatureWeightTpl<FloatT, MapT, Expectation> plus(FeatureWeightTpl<FloatT, MapT, Expectation> const& w1,\n                                                        FeatureWeightTpl<FloatT, MapT, Expectation> const& w2) {\n  FeatureWeightTpl<FloatT, MapT, Expectation> w3(w1, true);\n  w3.plusBy(w2);\n  return w3;\n}\n\n\n/// result has p=w1.p*w2.p and feats=w1.p*w2.feats+w2.p*w1.feats\ntemplate <class FloatT, class MapT>\ninline FeatureWeightTpl<FloatT, MapT, Expectation> times(FeatureWeightTpl<FloatT, MapT, Expectation> const& w1,\n                                                         FeatureWeightTpl<FloatT, MapT, Expectation> const& w2) {\n  FeatureWeightTpl<FloatT, MapT, Expectation> w3(w1, true);\n  w3.timesBy(w2);\n  return w3;\n}\n\n\n}}\n\n#endif\n", "meta": {"hexsha": "56fce1e0e1aa0df11bc5f7445e4421f078755b73", "size": 8755, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdl/Hypergraph/ExpectationWeight.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/ExpectationWeight.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/ExpectationWeight.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": 38.399122807, "max_line_length": 113, "alphanum_fraction": 0.6588235294, "num_tokens": 2430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2514923173202992}}
{"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_EULERANGLESXYZ_HPP_\n#define KINDR_ROTATIONS_EIGEN_EULERANGLESXYZ_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 EulerAnglesXyz\n *  \\brief Implementation of Euler angles (X-Y'-Z'' / roll-pitch-yaw) rotation based on Eigen::Matrix<Scalar,3,1>\n *\n *  The following typedefs are provided for convenience:\n *   - \\ref eigen_impl::EulerAnglesXyzAD \"EulerAnglesXyzAD\" for active rotation and double primitive type\n *   - \\ref eigen_impl::EulerAnglesXyzAF \"EulerAnglesXyzAF\" for active rotation and float primitive type\n *   - \\ref eigen_impl::EulerAnglesXyzPD \"EulerAnglesXyzPD\" for passive rotation and double primitive type\n *   - \\ref eigen_impl::EulerAnglesXyzPF \"EulerAnglesXyzPF\" for passive rotation and float primitive type\n *   - EulerAnglesRpyAD = EulerAnglesXyzAD\n *   - EulerAnglesRpyAF = EulerAnglesXyzAF\n *   - EulerAnglesRpyPD = EulerAnglesXyzPD\n *   - EulerAnglesRpyPF = EulerAnglesXyzPF\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 EulerAnglesXyz : public EulerAnglesXyzBase<EulerAnglesXyz<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 [roll; pitch; yaw]\n   */\n  Base xyz_;\n\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 Rotation Vector as 3x1-matrix\n   */\n  typedef Base Vector;\n\n  /*! \\brief Default constructor using identity rotation.\n   */\n  EulerAnglesXyz()\n    : xyz_(Base::Zero()) {\n  }\n\n  /*! \\brief Constructor using three scalars.\n   *  \\param roll     first rotation angle around X axis\n   *  \\param pitch    second rotation angle around Y' axis\n   *  \\param yaw      third rotation angle around Z'' axis\n   */\n  EulerAnglesXyz(Scalar roll, Scalar pitch, Scalar yaw)\n    : xyz_(roll,pitch,yaw) {\n  }\n\n  /*! \\brief Constructor using Eigen::Matrix.\n   *  \\param other   Eigen::Matrix<PrimType_,3,1> [roll; pitch; yaw]\n   */\n  explicit EulerAnglesXyz(const Base& other)\n  : xyz_(other) {\n  }\n\n  /*! \\brief Constructor using another rotation.\n   *  \\param other   other rotation\n   */\n  template<typename OtherDerived_>\n  inline explicit EulerAnglesXyz(const RotationBase<OtherDerived_, Usage_>& other)\n    : xyz_(internal::ConversionTraits<EulerAnglesXyz, 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  EulerAnglesXyz& operator =(const RotationBase<OtherDerived_, Usage_>& other) {\n    this->toImplementation() = internal::ConversionTraits<EulerAnglesXyz, 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  EulerAnglesXyz& operator ()(const RotationBase<OtherDerived_, Usage_>& other) {\n    this->toImplementation() = internal::ConversionTraits<EulerAnglesXyz, 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  EulerAnglesXyz inverted() const {\n    return EulerAnglesXyz(eigen_internal::getInverseRpy<PrimType_, PrimType_>(this->toImplementation()));\n  }\n\n  /*! \\brief Inverts the rotation.\n   *  \\returns reference\n   */\n  EulerAnglesXyz& 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&>(xyz_);\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&>(xyz_);\n  }\n\n  /*! \\brief Returns roll (X) angle.\n   *  \\returns roll angle (scalar)\n   */\n  inline Scalar roll() const {\n    return xyz_(0);\n  }\n\n  /*! \\brief Returns pitch (Y') angle.\n   *  \\returns pitch angle (scalar)\n   */\n  inline Scalar pitch() const {\n    return xyz_(1);\n  }\n\n  /*! \\brief Returns yaw (Z'') angle.\n   *  \\returns yaw angle (scalar)\n   */\n  inline Scalar yaw() const {\n    return xyz_(2);\n  }\n\n  /*! \\brief Sets roll (X) angle.\n   */\n  inline void setRoll(Scalar roll) {\n    xyz_(0) = roll;\n  }\n\n  /*! \\brief Sets pitch (Y') angle.\n   */\n  inline void setPitch(Scalar pitch) {\n    xyz_(1) = pitch;\n  }\n\n  /*! \\brief Sets yaw (Z'') angle.\n   */\n  inline void setYaw(Scalar yaw) {\n    xyz_(2) = yaw;\n  }\n\n  /*! \\brief Gets roll (X) angle.\n   *  \\returns roll angle (scalar)\n   */\n  inline Scalar x() const {\n    return xyz_(0);\n  }\n\n  /*! \\brief Gets pitch (Y') angle.\n   *  \\returns pitch angle (scalar)\n   */\n  inline Scalar y() const {\n    return xyz_(1);\n  }\n\n  /*! \\brief Gets yaw (Z'') angle.\n   *  \\returns yaw angle (scalar)\n   */\n  inline Scalar z() const {\n    return xyz_(2);\n  }\n\n  /*! \\brief Sets roll (X) angle.\n   */\n  inline void setX(Scalar x) {\n    xyz_(0) = x;\n  }\n\n  /*! \\brief Sets pitch (Y') angle.\n   */\n  inline void setY(Scalar y) {\n    xyz_(1) = y;\n  }\n\n  /*! \\brief Sets yaw (Z'') angle.\n   */\n  inline void setZ(Scalar z) {\n    xyz_(2) = z;\n  }\n\n  /*! \\brief Sets the rotation to identity.\n   *  \\returns reference\n   */\n  EulerAnglesXyz& setIdentity() {\n    xyz_.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  EulerAnglesXyz getUnique() const {\n    Base xyz(kindr::common::floatingPointModulo(x()+M_PI,2*M_PI)-M_PI,\n             kindr::common::floatingPointModulo(y()+M_PI,2*M_PI)-M_PI,\n             kindr::common::floatingPointModulo(z()+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(xyz.y() < -M_PI/2 - tol)\n    {\n      if(xyz.x() < 0) {\n        xyz.x() = xyz.x() + M_PI;\n      } else {\n        xyz.x() = xyz.x() - M_PI;\n      }\n\n      xyz.y() = -(xyz.y() + M_PI);\n\n      if(xyz.z() < 0) {\n        xyz.z() = xyz.z() + M_PI;\n      } else {\n        xyz.z() = xyz.z() - M_PI;\n      }\n    }\n    else if(-M_PI/2 - tol <= xyz.y() && xyz.y() <= -M_PI/2 + tol)\n    {\n      xyz.x() -= xyz.z();\n      xyz.z() = 0;\n    }\n    else if(-M_PI/2 + tol < xyz.y() && xyz.y() < M_PI/2 - tol)\n    {\n      // ok\n    }\n    else if(M_PI/2 - tol <= xyz.y() && xyz.y() <= M_PI/2 + tol)\n    {\n      // todo: M_PI/2 should not be in range, other formula?\n      xyz.x() += xyz.z();\n      xyz.z() = 0;\n    }\n    else // M_PI/2 + tol < xyz.y()\n    {\n      if(xyz.x() < 0) {\n        xyz.x() = xyz.x() + M_PI;\n      } else {\n        xyz.x() = xyz.x() - M_PI;\n      }\n\n      xyz.y() = -(xyz.y() - M_PI);\n\n      if(xyz.z() < 0) {\n        xyz.z() = xyz.z() + M_PI;\n      } else {\n        xyz.z() = xyz.z() - M_PI;\n      }\n    }\n\n    return EulerAnglesXyz(xyz);\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  EulerAnglesXyz& setUnique() {\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 EulerAnglesXyzBase<EulerAnglesXyz<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 EulerAnglesXyzBase<EulerAnglesXyz<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 EulerAnglesXyz& xyz) {\n    out << xyz.toImplementation().transpose();\n    return out;\n  }\n};\n\n//! \\brief Active Euler angles rotation (X,Y',Z'' / roll,pitch,yaw) with double primitive type\ntypedef EulerAnglesXyz<double, RotationUsage::ACTIVE>  EulerAnglesXyzAD;\n//! \\brief Active Euler angles rotation (X,Y',Z'' / roll,pitch,yaw) with float primitive type\ntypedef EulerAnglesXyz<float,  RotationUsage::ACTIVE>  EulerAnglesXyzAF;\n//! \\brief Passive Euler angles rotation (X,Y',Z'' / roll,pitch,yaw) with double primitive type\ntypedef EulerAnglesXyz<double, RotationUsage::PASSIVE> EulerAnglesXyzPD;\n//! \\brief Passive Euler angles rotation (X,Y',Z'' / roll,pitch,yaw) with float primitive type\ntypedef EulerAnglesXyz<float,  RotationUsage::PASSIVE> EulerAnglesXyzPF;\n\n//! \\brief Equivalent Euler angles rotation (X,Y',Z'' / roll,pitch,yaw) class\ntemplate <typename PrimType_, enum RotationUsage Usage_>\nusing EulerAnglesRpy = EulerAnglesXyz<PrimType_, Usage_>;\n\n//! \\brief Active Euler angles rotation (X,Y',Z'' / roll,pitch,yaw) with double primitive type\ntypedef EulerAnglesRpy<double, RotationUsage::ACTIVE>  EulerAnglesRpyAD;\n//! \\brief Active Euler angles rotation (X,Y',Z'' / roll,pitch,yaw) with float primitive type\ntypedef EulerAnglesRpy<float,  RotationUsage::ACTIVE>  EulerAnglesRpyAF;\n//! \\brief Passive Euler angles rotation (X,Y',Z'' / roll,pitch,yaw) with double primitive type\ntypedef EulerAnglesRpy<double, RotationUsage::PASSIVE> EulerAnglesRpyPD;\n//! \\brief Passive Euler angles rotation (X,Y',Z'' / roll,pitch,yaw) with float primitive type\ntypedef EulerAnglesRpy<float,  RotationUsage::PASSIVE> EulerAnglesRpyPF;\n\n\n} // namespace eigen_impl\n\n\nnamespace internal {\n\ntemplate<typename PrimType_, enum RotationUsage Usage_>\nclass get_scalar<eigen_impl::EulerAnglesXyz<PrimType_, Usage_>> {\n public:\n  typedef PrimType_ Scalar;\n};\n\ntemplate<typename PrimType_, enum RotationUsage Usage_>\nclass get_matrix3X<eigen_impl::EulerAnglesXyz<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::EulerAnglesXyz<PrimType_, RotationUsage::ACTIVE>> {\n public:\n  typedef eigen_impl::EulerAnglesXyz<PrimType_, RotationUsage::PASSIVE> OtherUsage;\n};\n\ntemplate<typename PrimType_>\nclass get_other_usage<eigen_impl::EulerAnglesXyz<PrimType_, RotationUsage::PASSIVE>> {\n public:\n  typedef eigen_impl::EulerAnglesXyz<PrimType_, RotationUsage::ACTIVE> OtherUsage;\n};\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Conversion Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::EulerAnglesXyz<DestPrimType_, Usage_>, eigen_impl::AngleAxis<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::EulerAnglesXyz<DestPrimType_, Usage_> convert(const eigen_impl::AngleAxis<SourcePrimType_, Usage_>& aa) {\n//    return eigen_impl::EulerAnglesXyz<DestPrimType_, Usage_>(eigen_impl::getRpyFromAngleAxis<SourcePrimType_, DestPrimType_>(aa.toImplementation()));\n    return eigen_impl::EulerAnglesXyz<DestPrimType_, Usage_>(eigen_impl::RotationQuaternion<DestPrimType_, Usage_>(aa));\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::EulerAnglesXyz<DestPrimType_, Usage_>, eigen_impl::RotationVector<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::EulerAnglesXyz<DestPrimType_, Usage_> convert(const eigen_impl::RotationVector<SourcePrimType_, Usage_>& rotationVector) {\n    return eigen_impl::EulerAnglesXyz<DestPrimType_, Usage_>(eigen_impl::AngleAxis<SourcePrimType_, Usage_>(rotationVector));\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::EulerAnglesXyz<DestPrimType_, Usage_>, eigen_impl::RotationQuaternion<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::EulerAnglesXyz<DestPrimType_, Usage_> convert(const eigen_impl::RotationQuaternion<SourcePrimType_, Usage_>& q) {\n    return eigen_impl::EulerAnglesXyz<DestPrimType_, Usage_>(eigen_impl::eigen_internal::getRpyFromQuaternion<SourcePrimType_, DestPrimType_>(q.toImplementation()));\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::EulerAnglesXyz<DestPrimType_, Usage_>, eigen_impl::RotationMatrix<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::EulerAnglesXyz<DestPrimType_, Usage_> convert(const eigen_impl::RotationMatrix<SourcePrimType_, Usage_>& R) {\n    return eigen_impl::EulerAnglesXyz<DestPrimType_, Usage_>(eigen_impl::eigen_internal::getRpyFromRotationMatrix<SourcePrimType_, DestPrimType_>(R.toImplementation()));\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::EulerAnglesXyz<DestPrimType_, Usage_>, eigen_impl::EulerAnglesXyz<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::EulerAnglesXyz<DestPrimType_, Usage_> convert(const eigen_impl::EulerAnglesXyz<SourcePrimType_, Usage_>& xyz) {\n    return eigen_impl::EulerAnglesXyz<DestPrimType_, Usage_>(xyz.toImplementation().template cast<DestPrimType_>());\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::EulerAnglesXyz<DestPrimType_, Usage_>, eigen_impl::EulerAnglesZyx<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::EulerAnglesXyz<DestPrimType_, Usage_> convert(const eigen_impl::EulerAnglesZyx<SourcePrimType_, Usage_>& zyx) {\n    return eigen_impl::EulerAnglesXyz<DestPrimType_, Usage_>(eigen_impl::eigen_internal::getRpyFromYpr<SourcePrimType_, DestPrimType_>(zyx.toImplementation()));\n  }\n};\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Multiplication Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\n\n//template<typename PrimType_>\n//class MultiplicationTraits<RotationBase<eigen_impl::EulerAnglesXyz<PrimType_, RotationUsage::ACTIVE>, RotationUsage::ACTIVE>, RotationBase<eigen_impl::EulerAnglesXyz<PrimType_, RotationUsage::ACTIVE>, RotationUsage::ACTIVE>> {\n// public:\n//  inline static eigen_impl::EulerAnglesXyz<PrimType_, RotationUsage::ACTIVE> mult(const eigen_impl::EulerAnglesXyz<PrimType_, RotationUsage::ACTIVE>& a, const eigen_impl::EulerAnglesXyz<PrimType_, RotationUsage::ACTIVE>& b) {\n//    return eigen_impl::EulerAnglesXyz<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::EulerAnglesXyz<PrimType_, RotationUsage::PASSIVE>, RotationUsage::PASSIVE>, RotationBase<eigen_impl::EulerAnglesXyz<PrimType_, RotationUsage::PASSIVE>, RotationUsage::PASSIVE>> {\n// public:\n//  inline static eigen_impl::EulerAnglesXyz<PrimType_, RotationUsage::PASSIVE> mult(const eigen_impl::EulerAnglesXyz<PrimType_, RotationUsage::PASSIVE>& a, const eigen_impl::EulerAnglesXyz<PrimType_, RotationUsage::PASSIVE>& b) {\n//    return eigen_impl::EulerAnglesXyz<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::EulerAnglesXyz<PrimType_, Usage_>, Usage_>, RotationBase<eigen_impl::EulerAnglesXyz<PrimType_, Usage_>, Usage_>> {\n// public:\n//  inline static eigen_impl::EulerAnglesXyz<PrimType_, Usage_> mult(const eigen_impl::EulerAnglesXyz<PrimType_, Usage_>& a, const eigen_impl::EulerAnglesXyz<PrimType_, Usage_>& b) {\n//    return eigen_impl::EulerAnglesXyz<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 * Rotation Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\n\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Comparison Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\n\n\n\n} // namespace internal\n} // namespace rotations\n} // namespace kindr\n\n\n#endif /* KINDR_ROTATIONS_EIGEN_EULERANGLESXYZ_HPP_ */\n", "meta": {"hexsha": "431f6e69d878cbe627ef0127189211cec1b18e48", "size": 21063, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "IHMCPerception/third-party/kindr/include/kindr/rotations/eigen/EulerAnglesXyz.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/EulerAnglesXyz.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/EulerAnglesXyz.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.138671875, "max_line_length": 232, "alphanum_fraction": 0.645634525, "num_tokens": 5034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.2514923173202992}}
{"text": "#include <boost/math/distributions/chi_squared.hpp>\n#include <Eigen/Eigen>\n//#include <ros/ros.h>\n\n//using boost::math::chi_squared;\n//using boost::math::cdf;\n\nnamespace perception_oru\n{\n\ntemplate <typename PointT>\nvoid AdaptiveOctTree<PointT>::setParameters(bool _useDornikHansen,\n        bool _useFlatness,\n        double _RSS_THRESHOLD,\n        double _DH_SIGNIFICANCE_LVL,\n        double _MIN_CELL_SIZE,\n        double _FLAT_FACTOR,\n        double _BIG_CELL_SIZE,\n        double _SMALL_CELL_SIZE\n                                           )\n{\n\n    this->BIG_CELL_SIZE = _BIG_CELL_SIZE;\n    this->SMALL_CELL_SIZE = _SMALL_CELL_SIZE;\n\n    useDornikHansen      = _useDornikHansen;\n    useFlatness          = _useFlatness;\n    RSS_THRESHOLD        = _RSS_THRESHOLD;\n    DH_SIGNIFICANCE_LVL  = _DH_SIGNIFICANCE_LVL;\n    MIN_CELL_SIZE        = _MIN_CELL_SIZE;\n    FLAT_FACTOR          = _FLAT_FACTOR;\n\n    parametersSet = true;\n}\n/** empty! default constructor\n  */\ntemplate <typename PointT>\nAdaptiveOctTree<PointT>::AdaptiveOctTree() : OctTree<PointT>()\n{\n    if(!parametersSet)\n    {\n        setParameters();\n    }\n}\n\n/** constructor, calls parent OctTree constructor\n  */\ntemplate <typename PointT>\nAdaptiveOctTree<PointT>::AdaptiveOctTree(pcl::PointXYZ center, double xsize, double ysize,\n        double zsize, NDTCell<PointT>* type, OctTree<PointT> *_parent, unsigned int _depth) :\n    OctTree<PointT>(center,xsize,ysize,zsize,type,_parent,_depth)\n{\n    if(!parametersSet)\n    {\n        setParameters();\n    }\n}\n\n/** empty destructor, all data are deallocated by parent class\n  */\ntemplate <typename PointT>\nAdaptiveOctTree<PointT>::~AdaptiveOctTree()\n{\n}\n\n/**\n  finds all leafs of this tree and fills the vector of pointers to the leafs\n  */\ntemplate <typename PointT>\nvoid AdaptiveOctTree<PointT>::computeTreeLeafs()\n{\n    if(this->isLeaf())\n    {\n        myTreeLeafs.push_back(this);\n        return;\n    }\n\n    myTreeLeafs.clear();\n    std::vector<OctTree<PointT>*> next;\n    next.push_back(this);\n\n    while(next.size()>0)\n    {\n        OctTree<PointT> *cur = next.front();\n        if(cur!=NULL)\n        {\n            if(cur->isLeaf())\n            {\n                myTreeLeafs.push_back(cur);\n            }\n            else\n            {\n                for(int i=0; i<8; i++)\n                {\n                    OctTree<PointT>* tmp = cur->getChild(i);\n                    if(tmp!=NULL)\n                    {\n                        next.push_back(tmp);\n                    }\n                }\n            }\n        }\n        next.erase(next.begin());\n    }\n}\n\n/**\ngo through all leafs and split the ones with high residuals\n  */\ntemplate <typename PointT>\nvoid AdaptiveOctTree<PointT>::postProcessPoints()\n{\n\n    //compute leafs as OctTree*\n    computeTreeLeafs();\n    //cout<<\"leafs :\"<<myTreeLeafs.size()<<endl;\n\n    for(unsigned int i=0; i<myTreeLeafs.size(); i++)\n    {\n        NDTCell<PointT> * nd = dynamic_cast<NDTCell<PointT>*>((myTreeLeafs[i])->myCell_);\n        if(nd == NULL) continue;\n        if(useDornikHansen)\n        {\n            double significance = computeDornikHansen(nd);\n            if(significance < 0)\n            {\n                //there were not enough points, let's clear the cell!\n                //(myTreeLeafs[i])->myCell->points.clear();\n                continue;\n            }\n            if(significance < DH_SIGNIFICANCE_LVL)\n            {\n                //split the leafs\n                std::vector<OctTree<PointT>*> newLeafs = splitTree(myTreeLeafs[i]);\n                myTreeLeafs.insert(myTreeLeafs.end(),newLeafs.begin(),newLeafs.end());\n            }\n        }\n        else if(useFlatness)\n        {\n            nd->computeGaussian();\n            if(!nd->hasGaussian_)\n            {\n                continue;\n            }\n\n            Eigen::Vector3d evals = nd->getEvals();\n            int idMin, idMax;\n            double minEval = evals.minCoeff(&idMin);\n            double maxEval = evals.maxCoeff(&idMax);\n            int idMiddle = -1;\n            for(int j=0; j<3; j++)\n            {\n                if(j!=idMin && j!=idMax)\n                {\n                    idMiddle =  j;\n                }\n            }\n            if(idMiddle < 0) continue;\n\n            if(minEval*FLAT_FACTOR > evals(idMiddle))\n            {\n                std::vector<OctTree<PointT>*> newLeafs = splitTree(myTreeLeafs[i]);\n                myTreeLeafs.insert(myTreeLeafs.end(),newLeafs.begin(),newLeafs.end());\n            }\n\n\n        }\n        else\n        {\n            double rss = computeResidualSquare(nd);\n            if(rss > RSS_THRESHOLD)\n            {\n                //split the leafs\n                std::vector<OctTree<PointT>*> newLeafs = splitTree(myTreeLeafs[i]);\n                myTreeLeafs.insert(myTreeLeafs.end(),newLeafs.begin(),newLeafs.end());\n            }\n        }\n    }\n\n    this->leafsCached_ = false;\n}\n\n/**\n  performs the Dornik-Hansen Omnibus normality test\n*/\ntemplate <typename PointT>\ndouble AdaptiveOctTree<PointT>::computeDornikHansen(NDTCell<PointT> *cell)\n{\n    double pval = 1;\n    double Ep = 0;\n    //test statistics breaks down for n<=7\n    if(cell->points_.size() <= 7) return -1;\n    cell->computeGaussian();\n\n    //degree is 2*number_of_dimensions\n    boost::math::chi_squared dist(6);\n\n    Eigen::Vector3d mean = cell->getMean();\n    Eigen::Matrix3d C = cell->getCov();\n\n    Eigen::MatrixXd Xhat(cell->points_.size(),3); //, tmpMat;\n\n    for(unsigned int i=0; i< cell->points_.size(); i++)\n    {\n        Xhat(i,0) = cell->points_[i].x - mean(0);\n        Xhat(i,1) = cell->points_[i].y - mean(1);\n        Xhat(i,2) = cell->points_[i].z - mean(2);\n    }\n\n    //Compute transform for observed points\n    Eigen::Matrix3d V;\n    Eigen::Matrix3d H;\n    Eigen::Vector3d lambda;\n    Eigen::Matrix3d L;\n    Eigen::Matrix3d R1;\n\n    Eigen::MatrixXd R;\n\n    V(0,0) = 1/sqrt(C(0,0));\n    V(1,1) = 1/sqrt(C(1,1));\n    V(2,2) = 1/sqrt(C(2,2));\n\n    C = V*C*V;\n    Eigen::EigenSolver<Eigen::Matrix3d> eig(C);\n    H = eig.eigenvectors().real();\n    lambda = eig.eigenvalues().real();\n\n    //covariance is not positive semidefinate\n    if(lambda.minCoeff() <= 0) return -1;\n\n    L(0,0) = 1/sqrt(lambda(0));\n    L(1,1) = 1/sqrt(lambda(1));\n    L(2,2) = 1/sqrt(lambda(2));\n\n    //transform observations\n    R1 = H*L*H.transpose()*V;\n    R = R1*Xhat.transpose();\n\n    //compute skewness and kurtois of new observations (in each dimension)\n    //samples are zero mean, compute for each dimension standard deviation\n    Ep = 0.0;\n    double n = R.cols();\n    for(unsigned int dim = 0; dim < 3; dim ++)\n    {\n        double m2 = 0, m3 = 0, m4 =0;\n        double b1 = 0, b2;\n        double beta, omega2, gamma, y;\n        double gamma2, a,c, k, alpha, chi;\n        double z1,z2;\n\n        for(unsigned int i=0; i<R.cols(); i++)\n        {\n            m2 += pow(R(dim,i),2);\n            m3 += pow(R(dim,i),3);\n            m4 += pow(R(dim,i),4);\n        }\n        m2 /= R.cols();\n        m3 /= R.cols();\n        m4 /= R.cols();\n//\tcout <<\"dim \"<<dim<<\" m2 \"<<m2<<\" m3 \"<<m3<<\" m4 \"<<m4<<endl;\n        b1 = m3/(pow(m2,1.5));\n        b2 = m4/(pow(m2,2));\n\n//\tcout<<\"b1 \"<<b1<<\" b2 \"<<b2<<endl;\n\n        //compute Z1 and Z2\n        beta = 3*(n*n + 27*n -70)*(n+1)*(n+3)/((n-2)*(n+5)*(n+7)*(n+9));\n        omega2 = -1+sqrt(2*(beta-1));\n        gamma = 1/sqrt(log(sqrt(omega2)));\n        y = b1*sqrt((omega2-1)*(n+1)*(n+3)/(12*(n-2)));\n        z1 = gamma*log(y+sqrt(y*y+1));\n\n        gamma2 = (n-3)*(n+1)*(n*n+15*n-4);\n        a = (n-2)*(n+5)*(n+7)*(n*n+27*n-70)/(6*gamma2);\n        c = (n-7)*(n+5)*(n+7)*(n*n+2*n-5)/(6*gamma2);\n        k = (n+5)*(n+7)*(pow(n,3)+37*n*n+11*n-313)/(12*gamma2);\n        alpha = a + b1*b1*c;\n        chi = (b2-1-b1*b1)*2*k;\n        z2 = (pow((chi/(2*alpha)),(1./3.))-1+(1./(9*alpha)))*sqrt(9*alpha);\n\n//\tcout<<\"z1: \"<<z1<<\" z2: \"<<z2<<endl;\n\n        //compute Ep\n        Ep += z1*z1 + z2*z2;\n    }\n\n    //compute probability from chi square cdf\n    pval = 1-boost::math::cdf(dist,Ep);\n\n//    cout<<\"Ep \"<<Ep<<endl;\n//    cout<<\"P: \"<<pval<<endl;\n    if(pval>DH_SIGNIFICANCE_LVL)\n    {\n        double dx,dy,dz;\n        cell->getDimensions(dx,dy,dz);\n        std::cout<<\"final split was at (\"<<dx<<\",\"<<dy<<\",\"<<dz<<\"); pval is \"<<pval<<std::endl;\n    }\n    return 0;\n\n}\n/**\nfits a 3d gaussian in the cell and computes the residual squares sum\n*/\ntemplate <typename PointT>\ndouble AdaptiveOctTree<PointT>::computeResidualSquare(NDTCell<PointT> *cell)\n{\n    double rss = 0; //residual sum squared\n    double meanResidual = 0;\n    double residualVar = 0;\n    if(cell->points_.size() <= 3) return 0;\n\n    cell->computeGaussian();\n\n    Eigen::Vector3d cur, curProd;\n    Eigen::Matrix3d cov = cell->getCov();\n    Eigen::Vector3d mean = cell->getMean();\n    //Eigen::LLT<Eigen::Matrix3d> lltOfCov = cov.llt();\n\n    for(unsigned int i=0; i< cell->points_.size(); i++)\n    {\n\n        cur(0) = cell->points_[i].x - mean(0);\n        cur(1) = cell->points_[i].y - mean(1);\n        cur(2) = cell->points_[i].z - mean(2);\n\n        //lltOfCov.solve(cur,&curProd);\n        //rss += cur.dot(curProd);\n        rss += cur.dot(cur);\n        meanResidual += cur.norm()/cell->points_.size();\n    }\n\n    for(unsigned int i=0; i< cell->points_.size(); i++)\n    {\n        cur(0) = cell->points_[i].x - mean(0);\n        cur(1) = cell->points_[i].y - mean(1);\n        cur(2) = cell->points_[i].z - mean(2);\n\n        residualVar += pow(cur.norm()-meanResidual,2)/(cell->points_.size()-1);\n    }\n    double bic = rss/residualVar + log(cell->points_.size());\n//    ROS_INFO(\"rss %lf mean %lf var %lf bic %lf\",rss,meanResidual,residualVar,bic);\n    return bic;\n}\n\n/**\n  splits a cell and returns a vector of the newly created children\n  iterates points downwards\n  */\ntemplate <typename PointT>\nstd::vector<OctTree<PointT>*> AdaptiveOctTree<PointT>::splitTree(OctTree<PointT> *octLeaf)\n{\n    std::vector<OctTree<PointT>*> newLeafs;\n\n    if(octLeaf->isLeaf())\n    {\n        double xs,ys,zs;\n        octLeaf->myCell_->getDimensions(xs,ys,zs);\n\n        double cellSize = (xs+ys+zs)/3.; //average for now\n\n        if(octLeaf->depth_ > this->MAX_DEPTH || cellSize <= this->MIN_CELL_SIZE )\n        {\n            //just store point, we can't split any more\n            return newLeafs;\n        }\n\n        pcl::PointXYZ myCenter = octLeaf->myCell_->getCenter();\n\n        //branch leaf\n        for(unsigned int it=0; it<8; it++)\n        {\n\n            pcl::PointXYZ newCenter;\n\n            //computes the center of the it'th child\n            newCenter.x = (myCenter.x + pow(-1.,it/4)*xs/4.);\n            newCenter.y = (myCenter.y + pow(-1.,it/2)*ys/4.);\n            newCenter.z = (myCenter.z + pow(-1.,(it+1)/2)*zs/4.);\n\n            octLeaf->children_[it] = new OctTree<PointT>(newCenter,xs/2,ys/2,\n                    zs/2, octLeaf->myCell_, this, this->depth_+1);\n            newLeafs.push_back(octLeaf->children_[it]);\n        }\n        //add current points\n        for(unsigned int jt=0; jt<octLeaf->myCell_->points_.size(); jt++)\n        {\n            size_t ind = octLeaf->getIndexForPoint(octLeaf->myCell_->points_[jt]);\n            octLeaf->children_[ind]->addPoint(octLeaf->myCell_->points_[jt]);\n        }\n        octLeaf->leaf_=false;\n        octLeaf->myCell_->points_.clear();\n    }\n\n    return newLeafs;\n}\n\n/**\n  creates an oct tree with the same parameters.\n  \\note the points are not copied in teh returned instance\n  */\ntemplate <typename PointT>\nSpatialIndex<PointT>* AdaptiveOctTree<PointT>::clone()\n{\n    if(this->myCell_ == NULL)\n    {\n        return new AdaptiveOctTree();\n    }\n    double sx,sy,sz;\n    this->myCell_->getDimensions(sx,sy,sz);\n    AdaptiveOctTree<PointT> *tr = new AdaptiveOctTree<PointT>(this->myCell_->getCenter(),sx,sy,sz,this->myCell_);\n    return tr;\n}\n\n}\n", "meta": {"hexsha": "ef160b523df0d4b8841e673e6d981ac20b627e35", "size": 11745, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "perception_oru-port-kinetic/ndt_map/src/adaptive_oc_tree.cpp", "max_stars_repo_name": "lllray/ndt-loam", "max_stars_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-14T08:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-14T08:21:13.000Z", "max_issues_repo_path": "perception_oru-port-kinetic/ndt_map/src/adaptive_oc_tree.cpp", "max_issues_repo_name": "lllray/ndt-loam", "max_issues_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-28T04:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T04:47:56.000Z", "max_forks_repo_path": "perception_oru-port-kinetic/ndt_map/include/ndt_map/deprecated/impl/adaptive_oc_tree.hpp", "max_forks_repo_name": "lllray/ndt-loam", "max_forks_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-18T11:25:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T12:59:59.000Z", "avg_line_length": 28.3012048193, "max_line_length": 113, "alphanum_fraction": 0.5504469987, "num_tokens": 3416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.25144920998354203}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// Materials.hh\n////////////////////////////////////////////////////////////////////////////////\n/*! @file\n//      Parametrized materials that can be used with MaterialField for purposes\n//      of material optimization. Each material provides getETensorDerivative,\n//      which gives the derivative of the elasticity tensor with respect to one\n//      material parameter.\n//\n//      The exception is ConstantMaterial, which is intended to be read from a\n//      file and which doesn't support material optimization.\n*/\n//  Author:  Julian Panetta (jpanetta), julian.panetta@gmail.com\n//  Company:  New York University\n//  Created:  07/11/2014 15:48:34\n////////////////////////////////////////////////////////////////////////////////\n#ifndef MATERIAL_HH\n#define MATERIAL_HH\n\n#include <MeshFEM/Types.hh>\n#include <MeshFEM/Flattening.hh>\n#include <MeshFEM/ElasticityTensor.hh>\n#include <nlohmann/json.hpp>\n#include <fstream>\n#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\n#define BOOST_PARSER 1\n#if BOOST_PARSER\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n#endif\n\n#include <MeshFEM_export.h>\n\nnamespace Materials {\n\n// Material parameter bounds\nstruct Bounds {\n    struct Bound {\n        Bound(size_t _var, Real _val) : var(_var), value(_val) { }\n        size_t var; Real value;\n    };\n\n    Bounds() { }\n    Bounds(const std::vector<Bound> &l, const std::vector<Bound> &u)\n        : m_lower(l), m_upper(u) { }\n\n    void MESHFEM_EXPORT setFromJson(const nlohmann::json &entry);\n\n    const std::vector<Bound> &lower() const { return m_lower; }\n    const std::vector<Bound> &upper() const { return m_upper; }\n\n    void setLower(const std::vector<Bound> &l) { m_lower = l; }\n    void setUpper(const std::vector<Bound> &u) { m_upper = u; }\nprivate:\n    std::vector<Bound> m_lower, m_upper;\n};\n\n// Base class for variable materials\ntemplate<size_t _N, template<size_t> class _Mat, size_t _NVars>\nstruct VariableMaterial {\n    typedef ElasticityTensor<Real, _N> ETensor;\n    static constexpr size_t numVars = _NVars;\n\n    virtual void getETensorDerivative(size_t p, ETensor &d) const = 0;\n    virtual void getTensor(ETensor &tensor) const = 0;\n\n    static const std::vector<Bounds::Bound> &upperBounds() { return _Mat<_N>::g_bounds.upper(); }\n    static const std::vector<Bounds::Bound> &lowerBounds() { return _Mat<_N>::g_bounds.lower(); }\n\n    static void setUpperBounds(const std::vector<Bounds::Bound> &u) { _Mat<_N>::g_bounds.setUpper(u); }\n    static void setLowerBounds(const std::vector<Bounds::Bound> &l) { _Mat<_N>::g_bounds.setLower(l); }\n\n    static void setBoundsFromFile(const std::string &path) {\n        std::ifstream is(path);\n        if (!is.is_open()) {\n            throw std::runtime_error(\"Couldn't open bounds \" + path);\n        }\n        nlohmann::json config;\n        is >> config;\n        setBoundsFromJson(config);\n    }\n\n    static void setBoundsFromJson(const nlohmann::json &config) {\n        _Mat<_N>::g_bounds.setFromJson(config);\n        // Validate bounds.\n        std::runtime_error indexError(\"Bounds variable index out-of-bounds.\");\n        for (const auto &b : _Mat<_N>::g_bounds.lower()) if (b.var >= numVars) throw indexError;\n        for (const auto &b : _Mat<_N>::g_bounds.upper()) if (b.var >= numVars) throw indexError;\n    }\n\n    virtual ~VariableMaterial() { }\n\n    Real vars[numVars];\n};\n\n// Var 0: Young's modulus, var 1: Poisson ratio\ntemplate<size_t _N>\nstruct Isotropic : public VariableMaterial<_N, Isotropic, 2> {\n    static constexpr size_t N = _N;\n    typedef ElasticityTensor<Real, _N> ETensor;\n    typedef Eigen::Matrix<Real, flatLen(_N), 1> FlattenedSymmetricMatrix;\n    typedef VariableMaterial<N, Materials::Isotropic, 2> Base;\n    using Base::vars;\n\n    // WARNING: bounds are shared by all isotropic materials! (static)\n    struct IsotropicBounds : Bounds {\n        IsotropicBounds() {\n            // Default Bounds\n            // Upper: Upper bounds should be based on base material's moduli.\n            //        Poisson ratio can't be greater than or equal 0.5\n            //        (at 0.5, 3D lambda becomes Inf)\n            // Lower: Young's modulus must be positive and is hard to make\n            //        small--this minimum should be set based on homogenization results\n            //        Poisson ratio can't be less than -1, and for robustness we\n            //        limit it to -0.75\n            Bounds::setUpper({ Bounds::Bound(0, 292), Bounds::Bound(1, 0.6) });\n            Bounds::setLower({ Bounds::Bound(0, 25),  Bounds::Bound(1, 0.1) });\n        }\n    };\n\n    Isotropic() {\n        // Default Parameters: midway between bounds (if they exist)\n        const auto &lb = this->lowerBounds();\n        const auto &ub = this->upperBounds();\n        if ((lb.size() == 2) && (ub.size() == 2)) {\n            for (auto &bd : lb) vars[bd.var]  = 0.5 * bd.value;\n            for (auto &bd : ub) vars[bd.var] += 0.5 * bd.value;\n        }\n        else {\n            vars[0] = 50.0;\n            vars[1] = 0.3;\n        }\n    }\n\n    static const std::string &variableName(size_t i) {\n        static const std::vector<std::string> names = { \"E\", \"nu\" };\n        return names.at(i);\n    }\n\n    // Used for adjoint method gradient-based optimization\n    void getETensorDerivative(size_t p, ETensor &d) const {\n        assert(p == 0 || p == 1);\n        d.clear();\n        Real E = vars[0], nu = vars[1];\n        Real dL, dmu;\n        if (_N == 2) {\n            // 2D Lambda = (nu * E) / (1.0 - nu * nu);\n            //    mu = E / (2.0 + 2.0 * nu);\n            dL = (p == 0) ? nu / (1 - nu * nu)\n                          : E * (1 + nu * nu) / ((1 - nu * nu) * (1 - nu * nu));\n        }\n        if (_N == 3) {\n            // 3D Lambda = (nu * E) / ((1.0 + nu) * (1.0 - 2.0 * nu));\n            Real denSqrt = 1 - nu - 2 * nu * nu;\n            dL = (p == 0) ? nu / ((1.0 + nu) * (1.0 - 2 * nu)) : E * (1 + 2 * nu * nu) / (denSqrt * denSqrt);\n        }\n\n        // 2D and 3D mu: E / (2 (1 + nu))\n        dmu = (p == 0) ? 1 / (2 * (1 + nu))\n                       : -E / (2 * (1 + nu) * (1 + nu));\n        for (size_t i = 0; i < flatLen(_N); ++i) {\n            for (size_t j = i; j < _N; ++j)\n                d.D(i, j) = dL;\n            d.D(i, i) += (i < _N) ? 2 * dmu : dmu;\n        }\n    }\n\n    void getTensor(ETensor &tensor) const {\n        tensor.setIsotropic(vars[0], vars[1]);\n    }\n\n    // Ceres-compatible cost function to fit Young's modulus, Y, and Poisson\n    // ratio, nu, to best achieve:\n    //      s ~= E(Y, nu) : e\n    // Where Y and nu are Young's modulus and Poisson ratio. In 2D, the\n    // condition s = E(Y, nu) : e can be written in a linear form:\n    //  [s_00]   [e_00,  s_11][Y ]\n    //  [s_11] = [e_11,  s_00][nu]\n    //  [s_01]   [e_01, -s_01]\n    // We solve this in a least squares sense to get ``optimal'' Y and nu. This\n    // is a slightly strange formulation in which the residual is harder to\n    // interpret, but it's nice because the optimization variables are Y and nu\n    // directly.\n    //\n    // Other options are to use Lame coefficients, which appear linearly in the\n    // stress-strain relationship, or variables 1/Y and nu/Y (which also appear\n    // linearly), but then E and nu are nonlinear functions of the variables\n    // (and bounds/penalties/etc. on them must be transformed accordingly).\n    // In 3D the corresponding condition is:\n    //  [s_00]   [e_00,  s_11 + s_22]\n    //  [s_11]   [e_11,  s_00 + s_22]\n    //  [s_22] = [e_22,  s_00 + s_11][Y ]\n    //  [s_12]   [e_12,        -s_12][nu]\n    //  [s_02]   [e_02,        -s_02]\n    //  [s_01]   [e_01,        -s_01]\n    template<class SMatrix>\n    struct StressStrainFitCostFunction {\n        StressStrainFitCostFunction(const SMatrix &e, const SMatrix &s, Real vol)\n            : strain(e), stress(s) {\n            if (vol <= 0) throw std::runtime_error(\"Volume must be positive\");\n            volSqrt = sqrt(vol);\n        }\n\n        template<typename T>\n        bool operator()(const T *x, T *e) const {\n            // Nonlinear version\n            if (_N == 3) {\n                e[0] = T(stress[0]) - x[1] * T(stress[1] + stress[2]);\n                e[1] = T(stress[1]) - x[1] * T(stress[0] + stress[2]);\n                e[2] = T(stress[2]) - x[1] * T(stress[0] + stress[1]);\n                e[3] = (T(1) + x[1]) * T(stress[3]);\n                e[4] = (T(1) + x[1]) * T(stress[4]);\n                e[5] = (T(1) + x[1]) * T(stress[5]);\n            }\n            else {\n                e[0] = T(stress[0]) - x[1] * T(stress[1]);\n                e[1] = T(stress[1]) - x[1] * T(stress[0]);\n                e[2] = (T(1) + x[1]) * T(stress[2]);\n            }\n            for (size_t i = 0; i < flatLen(_N); ++i) {\n                e[i] /= x[0];\n                e[i] -= T(strain[i]);\n                if (i >= _N) e[i] *= T(sqrt(2.0));\n                e[i] *= T(volSqrt);\n            }\n\n            // // Linear version\n            // if (_N == 3) {\n            //     e[0] = T(strain[0]) * x[0] + T(stress[1] + stress[2]) * x[1];\n            //     e[1] = T(strain[1]) * x[0] + T(stress[0] + stress[2]) * x[1];\n            //     e[2] = T(strain[2]) * x[0] + T(stress[0] + stress[1]) * x[1];\n            //     e[3] = T(strain[3]) * x[0] - T(stress[3]) * x[1];\n            //     e[4] = T(strain[4]) * x[0] - T(stress[4]) * x[1];\n            //     e[5] = T(strain[5]) * x[0] - T(stress[5]) * x[1];\n            // }\n            // else {\n            //     e[0] = T(strain[0]) * x[0] + T(stress[1]) * x[1];\n            //     e[1] = T(strain[1]) * x[0] + T(stress[0]) * x[1];\n            //     e[2] = T(strain[2]) * x[0] - T(stress[2]) * x[1];\n            // }\n            // for (size_t i = 0; i < flatLen(_N); ++i) {\n            //     e[i] -= T(stress[i]);\n            // }\n\n            return true;\n        }\n\n        SMatrix strain, stress;\n        Real volSqrt;\n    };\nprivate:\n    friend Base;\n    static IsotropicBounds g_bounds;\n};\n\n// Static variable needs to be explicitly defined...\ntemplate<size_t _N>\ntypename Isotropic<_N>::IsotropicBounds Isotropic<_N>::g_bounds;\n\n// Axis-aligned orthotropic material.\n// 2D: 4 variables\n// Vars 0..1: Young's moduli,\n// Var     2: Poisson ratio (YX)\n// Var     3: Shear modulus\n// 3D: 9 variables\n// Vars 0..2: Young's moduli,\n// Vars 3..5: Poisson ratios (YX, ZX, ZY)\n// Vars 6..8: Shear ratios   (YZ, ZX, XY)\nsize_t constexpr nOrthotropicVars(size_t n) { return (n == 3) ? 9 : 4; }\ntemplate<size_t _N>\nstruct Orthotropic : public VariableMaterial<_N, Orthotropic, nOrthotropicVars(_N)> {\n    static constexpr size_t N = _N;\n    typedef ElasticityTensor<Real, _N> ETensor;\n    typedef Eigen::Matrix<Real, flatLen(_N), 1> FlattenedSymmetricMatrix;\n\n    typedef VariableMaterial<N, Materials::Orthotropic, nOrthotropicVars(N)> Base;\n    using Base::vars;\n\n    // WARNING: bounds are shared by all orthotropic materials! (static)\n    struct OrthotropicBounds : Bounds {\n        OrthotropicBounds() {\n            // Default Bounds\n            // Upper: Upper bounds should be based on base material's moduli.\n            //        Poisson ratios can't be greater than 0.5\n            //        (at 0.5, 3D isotropic lambda becomes Inf, so we avoid it\n            //        here too)\n            // Lower: Young's and shear moduli must be positive and are hard to make\n            //        small--this minimum should be set based on homogenization results\n            //        Poisson ratios can't be less than -1, and for robustness we\n            //        limit them to -0.75\n            if (_N == 3) Base::setUpperBounds({ Bound(3, 0.45), Bound(4, 0.45), Bound(5, 0.45) });\n            else         Base::setUpperBounds({ Bound(0,  384), Bound(1,  384), Bound(2, 0.45), Bound(3, 102) });\n            if (_N == 3) {\n                Base::setLowerBounds({ Bound(0,  0.01), Bound(1,  0.01), Bound(2,  0.01),\n                                       Bound(3, -0.75), Bound(4, -0.75), Bound(5, -0.75),\n                                       Bound(6,  0.01), Bound(7,  0.01), Bound(8,  0.01) });\n            }\n            else Base::setLowerBounds({ Bound(0,  18), Bound(1,  18),\n                                        Bound(2, 0.0), Bound(3,  2) });\n        }\n    };\n\n    Orthotropic() {\n        // Default Parameters\n        if (_N == 3) {\n            vars[0] = vars[1] = vars[2] = 1.0;\n            vars[3] = vars[4] = vars[5] = 0.3;\n            vars[6] = vars[7] = vars[8] = 1 / (2.0 * (1 + 0.3));\n        }\n        else {\n            vars[0] = vars[1] = 200.0;\n            vars[2] = 0.3;\n            vars[3] = 200.0 / (2.0 * (1 + 0.3));\n        }\n    }\n\n    static const std::string &variableName(size_t i) {\n        if (_N == 3) {\n            static const std::vector<std::string> names3D = {\n                \"E_x\", \"E_y\", \"E_z\",\n                \"nu_yx\", \"nu_zx\", \"nu_zy\",\n                \"mu_yz\", \"mu_zx\", \"mu_xy\" };\n            return names3D.at(i);\n        }\n        else {\n            static const std::vector<std::string> names2D = {\n                \"E_x\", \"E_y\", \"nu_yx\", \"mu\" };\n            return names2D.at(i);\n        }\n    }\n\n    // Used for adjoint method gradient-based optimization\n    void getETensorDerivative(size_t p, ETensor &d) const;\n\n    void getTensor(ETensor &tensor) const {\n        if (_N == 3) {\n            tensor.setOrthotropic3D(vars[0], vars[1], vars[2],\n                                    vars[3], vars[4], vars[5],\n                                    vars[6], vars[7], vars[8]);\n        }\n        else {\n            tensor.setOrthotropic2D(vars[0], vars[1], vars[2], vars[3]);\n        }\n    }\n\n    // Ceres-compatible cost function to fit orthotropic material parameters to\n    // best achieve:\n    //      e ~= E^(-1)(Y_x, Y_y, ...) : s\n    template<class SMatrix>\n    struct StressStrainFitCostFunction {\n        StressStrainFitCostFunction(const SMatrix &e, const SMatrix &s, Real vol)\n            : strain(e), stress(s) {\n            if (vol <= 0) throw std::runtime_error(\"Volume must be positive\");\n            volSqrt = sqrt(vol);\n        }\n\n        template<typename T>\n        bool operator()(const T *x, T *e) const {\n            if (_N == 3) {\n                T D01 =  -x[3] / x[1], // -nu_yx / E_y\n                  D02 =  -x[4] / x[2], // -nu_zx / E_z\n                  D12 =  -x[5] / x[2]; // -nu_zy / E_z\n                e[0] = T(stress[0]) / x[0] + T(stress[1]) *  D01 + T(stress[2]) *  D02;\n                e[1] = T(stress[0]) *  D01 + T(stress[1]) / x[1] + T(stress[2]) *  D12;\n                e[2] = T(stress[0]) *  D02 + T(stress[1]) *  D12 + T(stress[2]) / x[2];\n                e[3] = T(0.5 * stress[3]) / x[6];\n                e[4] = T(0.5 * stress[4]) / x[7];\n                e[5] = T(0.5 * stress[5]) / x[8];\n            }\n            else {\n                T D01 = -x[2] / x[1]; // -nu_yx / E_y\n                e[0] = T(stress[0]) / x[0] + T(stress[1]) *  D01;\n                e[1] = T(stress[0]) *  D01 + T(stress[1]) / x[1];\n                e[2] = T(0.5 * stress[2]) / x[3];\n            }\n\n            for (size_t i = 0; i < flatLen(_N); ++i) {\n                e[i] -= T(strain[i]);\n                if (i >= _N) e[i] *= T(sqrt(2.0));\n                e[i] *= T(volSqrt);\n            }\n\n            return true;\n        }\n\n        Real volSqrt;\n        SMatrix strain, stress;\n    };\nprivate:\n    friend Base;\n    static OrthotropicBounds g_bounds;\n};\n\n// Static variable needs to be explicitly defined...\ntemplate<size_t _N>\ntypename Orthotropic<_N>::OrthotropicBounds Orthotropic<_N>::g_bounds;\n\ntemplate<size_t _N>\nstruct Constant {\n    static constexpr size_t N = _N;\n    static constexpr size_t numVars = 0;\n    typedef ElasticityTensor<Real, _N> ETensor;\n\n    Constant() { m_E.setIsotropic(1.0, 0.3); }\n    Constant(const std::string &materialFile) { setFromFile(materialFile); }\n\n\n    void setFromFile(const std::string &materialFile);\n    void setFromJson(const nlohmann::json &config);\n#if BOOST_PARSER\n    void setFromPTree(const boost::property_tree::ptree &pt);\n#endif\n\n    // Used for adjoint method gradient-based optimization\n    void getETensorDerivative(size_t /* p */, ETensor &/* d */) const {\n        throw std::runtime_error(\"Constant material can't be optimized\\n\");\n    }\n\n    const ETensor &getTensor()      const { return m_E; }\n    void getTensor(ETensor &tensor) const { tensor = m_E; }\n    void setTensor(const ETensor &tensor) { m_E = tensor; }\n\n    void setIsotropic(Real E, Real nu) { m_E.setIsotropic(E, nu); }\n\n    nlohmann::json getJson() const;\n\n    // \"type\": \"anisotropic\",\n    // \"dim\": 3,\n    // \"material_matrix\": [[C_00, C_01, C02, C03, C04, C05],\n    //                     [C_10, C_11, C12, C13, C14, C15],\n    //                     [C_20, C_21, C22, C23, C24, C25],\n    //                     [C_30, C_31, C32, C33, C34, C35],\n    //                     [C_40, C_41, C42, C43, C44, C45],\n    //                     [C_50, C_51, C52, C53, C54, C55]]\n    friend std::ostream &operator<<(std::ostream &os, const Constant &cmat) {\n        os << cmat.getJson().dump(4);\n        return os;\n        // os << \"{ \\\"type\\\": \\\"anisotropic\\\",\" << std::endl;\n        // os << \"\\\"material_matrix\\\": [\";\n        // for (size_t i = 0; i < flatLen(N); ++i) {\n        //     for (size_t j = 0; j < flatLen(N); ++j) {\n        //         os << (j ? \", \" : \"[\") << cmat.m_E.D(i, j);\n        //     }\n        //     os << (i == flatLen(N) - 1 ? \"]]\" : \"],\") << std::endl;\n        // }\n        // os << \"}\";\n        // return os;\n    }\n\nprivate:\n    ETensor m_E;\n};\n\n} // Materials\n\n#endif /* end of include guard: MATERIAL_HH */\n", "meta": {"hexsha": "3e7316225f5786a1b90f23f5aa39c61b1d845d78", "size": 17679, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/lib/MeshFEM/Materials.hh", "max_stars_repo_name": "MeshFEM/MeshFEM", "max_stars_repo_head_hexsha": "9b3619fa450d83722879bfd0f5a3fe69d927bd63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2020-10-21T10:05:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:41:50.000Z", "max_issues_repo_path": "src/lib/MeshFEM/Materials.hh", "max_issues_repo_name": "MeshFEM/MeshFEM", "max_issues_repo_head_hexsha": "9b3619fa450d83722879bfd0f5a3fe69d927bd63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-01-01T15:58:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-19T03:31:09.000Z", "max_forks_repo_path": "src/lib/MeshFEM/Materials.hh", "max_forks_repo_name": "MeshFEM/MeshFEM", "max_forks_repo_head_hexsha": "9b3619fa450d83722879bfd0f5a3fe69d927bd63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-10-05T09:01:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T03:02:39.000Z", "avg_line_length": 38.3492407809, "max_line_length": 113, "alphanum_fraction": 0.5107189321, "num_tokens": 5385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2513457744738366}}
{"text": "#include \"../include/franka_emulator/model.h\"\n#include <Eigen/Geometry>\n#include <pinocchio/parsers/urdf.hpp>\n#include <pinocchio/algorithm/kinematics.hpp>\n#include <pinocchio/algorithm/frames.hpp>\n#include <pinocchio/algorithm/crba.hpp>\n#include <pinocchio/algorithm/rnea.hpp>\n#include <pinocchio/algorithm/jacobian.hpp>\n#ifndef _GNU_SOURCE\n    #define _GNU_SOURCE\n#endif\n#include <link.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n\nFRANKA_EMULATOR::Frame FRANKA_EMULATOR::operator++(Frame& frame, int /* dummy */) noexcept\n{\n    Frame result = frame;\n    frame = static_cast<Frame>(static_cast<unsigned int>(result) + 1);\n    return result;\n}\n\nFRANKA_EMULATOR::Model::Model(FRANKA_EMULATOR::Network&)\n{\n    //Searching for urdf file\n    struct LibrarySearchCallbackData\n    {\n        bool found              = false;\n        std::string directory   = \"\";\n    } library_search_callback_data;\n    auto library_search_callback = [](struct dl_phdr_info *info, size_t size, void *data) -> int\n    {\n        const char *library_name = \"libfranka_emulator_model.so\";\n        if (strstr(info->dlpi_name, library_name) != nullptr)\n        {\n            LibrarySearchCallbackData *library_search_callback_data = (LibrarySearchCallbackData*)data;\n            library_search_callback_data->found = true;\n            library_search_callback_data->directory.assign(info->dlpi_name);\n            library_search_callback_data->directory.erase(library_search_callback_data->directory.find(library_name), strlen(library_name));\n        }\n        return 0;\n    };\n    dl_iterate_phdr(library_search_callback, &library_search_callback_data);\n    if (!library_search_callback_data.found) throw std::runtime_error(\"franka_emulator::Model::Model: Could not find library path\");\n    struct stat model_stat;\n    if (stat((library_search_callback_data.directory + \"model/franka_emulator.urdf\").c_str(), &model_stat) == 0)\n        pinocchio::urdf::buildModel(library_search_callback_data.directory + \"model/franka_emulator.urdf\", _model);\n    if (stat((library_search_callback_data.directory + \"../model/franka_emulator.urdf\").c_str(), &model_stat) == 0)\n        pinocchio::urdf::buildModel(library_search_callback_data.directory + \"../model/franka_emulator.urdf\", _model);\n    else if (stat((library_search_callback_data.directory + \"../share/franka_emulator/model/franka_emulator.urdf\").c_str(), &model_stat) == 0)\n        pinocchio::urdf::buildModel(library_search_callback_data.directory + \"../share/franka_emulator/model/franka_emulator.urdf\", _model);\n    else throw std::runtime_error(\"franka_emulator::Model::Model: Could not find model file\");\n\n    //Other initialization\n    _data = pinocchio::Data(_model);\n    for (size_t joint = 0; joint < 8; joint++)\n    {\n        std::string name = \"panda_joint\" + std::to_string(joint + 1);\n        if (!_model.existFrame(name)) throw std::runtime_error(\"Joint frame not found\");\n        _joint_frame_id[joint] = _model.getFrameId(name);\n    }\n    for (size_t link = 0; link < 8; link++)\n    {\n        std::string name = \"panda_link\" + std::to_string(link + 1);\n        if (!_model.existFrame(name)) throw std::runtime_error(\"Link frame not found\");\n        _link_frame_id[link] = _model.getFrameId(name);\n    }\n}\n\nFRANKA_EMULATOR::Model::Model(Model &&other) noexcept\n{\n    _model = other._model;\n    _data = other._data;\n    for (size_t i = 0; i < 8; i++) _joint_frame_id[i] = other._joint_frame_id[i];\n    for (size_t i = 0; i < 8; i++) _link_frame_id[i] = other._link_frame_id[i];\n}\n\nFRANKA_EMULATOR::Model& FRANKA_EMULATOR::Model::operator=(Model&&) noexcept\n{\n    return *this;\n}\n\nFRANKA_EMULATOR::Model::~Model() noexcept\n{}\n\nstd::array<double, 16> FRANKA_EMULATOR::Model::pose(Frame frame, const FRANKA_EMULATOR::RobotState& robot_state) const\n{\n    return pose(frame, robot_state.q, robot_state.F_T_EE, robot_state.EE_T_K);\n}\n\nstd::array<double, 16> FRANKA_EMULATOR::Model::pose(\n    Frame frame,\n    const std::array<double, 7>& q,\n    const std::array<double, 16>& F_T_EE,\n    const std::array<double, 16>& EE_T_K) const\n{\n    \n    pinocchio::forwardKinematics(_model, _data, Eigen::Matrix<double, 7, 1>::Map(&q[0]));\n    pinocchio::SE3 placement;\n    if (static_cast<size_t>(frame) >= static_cast<size_t>(Frame::kJoint1) && static_cast<size_t>(frame) <= static_cast<size_t>(Frame::kJoint7))\n    {\n        placement = _data.oMi[static_cast<size_t>(frame) + 1];\n    }\n    else if (frame == Frame::kFlange || frame == Frame::kEndEffector || frame == Frame::kStiffness)\n    {\n        placement = pinocchio::updateFramePlacement(_model, _data, _joint_frame_id[7]);\n        if (frame == Frame::kEndEffector || frame == Frame::kStiffness) placement = placement.act_impl(pinocchio::SE3(Eigen::Matrix4d::Map(&F_T_EE[0])));\n        if (frame == Frame::kStiffness) placement = placement.act_impl(pinocchio::SE3(Eigen::Matrix4d::Map(&EE_T_K[0])));\n    }\n    else throw std::runtime_error(\"franka_emulator::Model::pose: Invalid frame\");\n\n    Eigen::Affine3d transform;\n    transform.linear() = placement.rotation_impl();\n    transform.translation() = placement.translation_impl();    \n    std::array<double, 16> result;\n    Eigen::Matrix4d::Map(&result[0]) = transform.matrix();\n    return result;\n}\n\nstd::array<double, 42> FRANKA_EMULATOR::Model::bodyJacobian(Frame frame, const FRANKA_EMULATOR::RobotState& robot_state) const\n{\n    return bodyJacobian(frame, robot_state.q, robot_state.F_T_EE, robot_state.EE_T_K);\n}\n\nstd::array<double, 42> FRANKA_EMULATOR::Model::bodyJacobian(\n    Frame frame,\n    const std::array<double, 7>& q,\n    const std::array<double, 16>& F_T_EE,\n    const std::array<double, 16>& EE_T_K) const\n{\n    Eigen::Matrix<double, 6, 7> result_matrix = Eigen::Matrix<double, 6, 7>::Zero();\n    if (static_cast<size_t>(frame) >= static_cast<size_t>(Frame::kJoint1) && static_cast<size_t>(frame) <= static_cast<size_t>(Frame::kJoint7))\n    {\n        pinocchio::computeJointJacobian(_model, _data, Eigen::Matrix<double, 7, 1>::Map(&q[0]), static_cast<size_t>(frame) + 1, result_matrix);\n    }\n    else if (frame == Frame::kFlange)\n    {\n        pinocchio::computeFrameJacobian(_model, _data, Eigen::Matrix<double, 7, 1>::Map(&q[0]), _joint_frame_id[7], result_matrix);\n    }\n    else if (frame == Frame::kEndEffector || frame == Frame::kStiffness)\n    {\n        pinocchio::SE3 placement = pinocchio::updateFramePlacement(_model, _data, _joint_frame_id[7]).act_impl(pinocchio::SE3(Eigen::Matrix4d::Map(&F_T_EE[0])));\n        if (frame == Frame::kStiffness) placement = placement.act_impl(pinocchio::SE3(Eigen::Matrix4d::Map(&EE_T_K[0])));\n        for (size_t i = 0; i < 7; i++)\n        {\n            result_matrix.block<3, 1>(0, i) = placement.rotation_impl().transpose() * (_data.oMi[i+1].rotation_impl().col(2).cross(placement.translation_impl() - _data.oMi[1+i].translation_impl()));\n            result_matrix.block<3, 1>(3, i) = placement.rotation_impl().transpose() * _data.oMi[i+1].rotation_impl().col(2);\n        }\n    }\n    else throw std::runtime_error(\"franka_emulator::Model::bodyJacobian: Invalid frame\");\n    \n    std::array<double, 42> result;\n    Eigen::Matrix<double, 6, 7>::Map(&result[0]) = result_matrix;\n    return result;\n}\n\nstd::array<double, 42> FRANKA_EMULATOR::Model::zeroJacobian(Frame frame, const FRANKA_EMULATOR::RobotState& robot_state) const\n{\n    return zeroJacobian(frame, robot_state.q, robot_state.F_T_EE, robot_state.EE_T_K);\n}\n\nstd::array<double, 42> FRANKA_EMULATOR::Model::zeroJacobian(\n    Frame frame,\n    const std::array<double, 7>& q,\n    const std::array<double, 16>& F_T_EE,\n    const std::array<double, 16>& EE_T_K) const\n{\n    Eigen::Matrix<double, 6, 7> result_matrix = Eigen::Matrix<double, 6, 7>::Zero();\n    if (static_cast<size_t>(frame) >= static_cast<size_t>(Frame::kJoint1) && static_cast<size_t>(frame) <= static_cast<size_t>(Frame::kJoint7))\n    {\n        pinocchio::forwardKinematics(_model, _data, Eigen::Matrix<double, 7, 1>::Map(&q[0]));\n        pinocchio::computeJointJacobian(_model, _data, Eigen::Matrix<double, 7, 1>::Map(&q[0]), static_cast<size_t>(frame) + 1, result_matrix);\n        result_matrix.block<3, 7>(0,0) = _data.oMi[static_cast<size_t>(frame) + 1].rotation_impl() * result_matrix.block<3, 7>(0,0);\n        result_matrix.block<3, 7>(3,0) = _data.oMi[static_cast<size_t>(frame) + 1].rotation_impl() * result_matrix.block<3, 7>(3,0);\n    }\n    else if (frame == Frame::kFlange)\n    {\n        pinocchio::SE3 placement = pinocchio::updateFramePlacement(_model, _data, _joint_frame_id[7]);\n        pinocchio::computeFrameJacobian(_model, _data, Eigen::Matrix<double, 7, 1>::Map(&q[0]), _joint_frame_id[7], result_matrix);\n        result_matrix.block<3, 7>(0,0) = placement.rotation_impl() * result_matrix.block<3, 7>(0,0);\n        result_matrix.block<3, 7>(3,0) = placement.rotation_impl() * result_matrix.block<3, 7>(3,0);\n    }\n    else if (frame == Frame::kEndEffector || frame == Frame::kStiffness)\n    {\n        pinocchio::SE3 placement = pinocchio::updateFramePlacement(_model, _data, _joint_frame_id[7]).act_impl(pinocchio::SE3(Eigen::Matrix4d::Map(&F_T_EE[0])));\n        if (frame == Frame::kStiffness) placement = placement.act_impl(pinocchio::SE3(Eigen::Matrix4d::Map(&EE_T_K[0])));\n        for (size_t i = 0; i < 7; i++)\n        {\n            result_matrix.block<3, 1>(0, i) = _data.oMi[i+1].rotation_impl().col(2).cross(placement.translation_impl() - _data.oMi[i+1].translation_impl());\n            result_matrix.block<3, 1>(3, i) = _data.oMi[i+1].rotation_impl().col(2);\n        }\n    }\n    else throw std::runtime_error(\"franka_emulator::Model::zeroJacobian: Invalid frame\");\n\n    std::array<double, 42> result;\n    Eigen::Matrix<double, 6, 7>::Map(&result[0]) = result_matrix;\n    return result;\n}\n\nstd::array<double, 49> FRANKA_EMULATOR::Model::mass(const FRANKA_EMULATOR::RobotState& robot_state) const noexcept\n{\n    return mass(robot_state.q, robot_state.I_total, robot_state.m_total, robot_state.F_x_Ctotal);\n}\n\nstd::array<double, 49> FRANKA_EMULATOR::Model::mass(\n    const std::array<double, 7>& q,\n    const std::array<double, 9>& I_total,\n    double m_total,\n    const std::array<double, 3>& F_x_Ctotal) const noexcept\n{\n    pinocchio::Inertia initial_end_inertia = _model.inertias[7];\n    _model.inertias[7].mass() += m_total;\n    _model.inertias[7].inertia().data()[0] += I_total[0];                    //xx\n    _model.inertias[7].inertia().data()[1] += (I_total[1] + I_total[3]) / 2; //xy\n    _model.inertias[7].inertia().data()[2] += I_total[4];                    //yy\n    _model.inertias[7].inertia().data()[3] += (I_total[2] + I_total[6]) / 2; //xz\n    _model.inertias[7].inertia().data()[4] += (I_total[5] + I_total[7]) / 2; //yz\n    _model.inertias[7].inertia().data()[5] += I_total[8];                    //zz\n    Eigen::Matrix<double, 7, 7> result_matrix = pinocchio::crba(_model, _data, Eigen::Matrix<double, 7, 1>::Map(&q[0]));\n    _model.inertias[7] = initial_end_inertia;\n    result_matrix.triangularView<Eigen::StrictlyLower>() = result_matrix.transpose().triangularView<Eigen::StrictlyLower>();\n    std::array<double, 49> result;\n    Eigen::Matrix<double, 7, 7>::Map(&result[0]) = result_matrix;\n    return result;\n}\n\nstd::array<double, 7> FRANKA_EMULATOR::Model::coriolis(const FRANKA_EMULATOR::RobotState& robot_state) const noexcept\n{\n    return coriolis(robot_state.q, robot_state.dq, robot_state.I_total, robot_state.m_total, robot_state.F_x_Ctotal);\n}\n\nstd::array<double, 7> FRANKA_EMULATOR::Model::coriolis(\n    const std::array<double, 7>& q,\n    const std::array<double, 7>& dq,\n    const std::array<double, 9>& I_total,\n    double m_total,\n    const std::array<double, 3>& F_x_Ctotal) const noexcept\n{\n    pinocchio::Inertia initial_end_inertia = _model.inertias[7];\n    _model.inertias[7].mass() += m_total;\n    _model.inertias[7].inertia().data()[0] += I_total[0];                    //xx\n    _model.inertias[7].inertia().data()[1] += (I_total[1] + I_total[3]) / 2; //xy\n    _model.inertias[7].inertia().data()[2] += I_total[4];                    //yy\n    _model.inertias[7].inertia().data()[3] += (I_total[2] + I_total[6]) / 2; //xz\n    _model.inertias[7].inertia().data()[4] += (I_total[5] + I_total[7]) / 2; //yz\n    _model.inertias[7].inertia().data()[5] += I_total[8];                    //zz\n    Eigen::Matrix<double, 7, 7> result_matrix = pinocchio::computeCoriolisMatrix(_model, _data, Eigen::Matrix<double, 7, 1>::Map(&q[0]), Eigen::Matrix<double, 7, 1>::Map(&dq[0]));\n    _model.inertias[7] = initial_end_inertia;\n    std::array<double, 7> result;\n    Eigen::Matrix<double, 7, 1>::Map(&result[0]) = result_matrix * Eigen::Matrix<double, 7, 1>::Map(&dq[0]);\n    return result;\n}\n\nstd::array<double, 7> FRANKA_EMULATOR::Model::gravity(\n    const std::array<double, 7>& q,\n    double m_total,\n    const std::array<double, 3>& F_x_Ctotal,\n    const std::array<double, 3>& gravity_earth) const noexcept\n{\n    _model.gravity.linear_impl() = Eigen::Matrix<double, 3, 1>::Map(&gravity_earth[0]);\n    double initial_end_mass = _model.inertias[7].mass();\n    _model.inertias[7].mass() += m_total;\n    std::array<double, 7> result;\n    Eigen::Matrix<double, 7, 1>::Map(&result[0]) = pinocchio::computeGeneralizedGravity(_model, _data, Eigen::Matrix<double, 7, 1>::Map(&q[0]));\n    _model.inertias[7].mass() = initial_end_mass;\n    return result;\n}\n\nstd::array<double, 7> FRANKA_EMULATOR::Model::gravity(\n    const FRANKA_EMULATOR::RobotState& robot_state,\n    const std::array<double, 3>& gravity_earth) const noexcept\n{\n    return gravity(robot_state.q, robot_state.m_total, robot_state.F_x_Ctotal, gravity_earth);\n}", "meta": {"hexsha": "b61143b6c61290eb370d298d54f7fa6310927e3f", "size": 13607, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/model.cpp", "max_stars_repo_name": "Data-Science-in-Mechanical-Engineering/franka_emulator", "max_stars_repo_head_hexsha": "7cd228b4329d7cefcba5afa95dca449408ce4c46", "max_stars_repo_licenses": ["MIT"], "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/model.cpp", "max_issues_repo_name": "Data-Science-in-Mechanical-Engineering/franka_emulator", "max_issues_repo_head_hexsha": "7cd228b4329d7cefcba5afa95dca449408ce4c46", "max_issues_repo_licenses": ["MIT"], "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/model.cpp", "max_forks_repo_name": "Data-Science-in-Mechanical-Engineering/franka_emulator", "max_forks_repo_head_hexsha": "7cd228b4329d7cefcba5afa95dca449408ce4c46", "max_forks_repo_licenses": ["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.48, "max_line_length": 198, "alphanum_fraction": 0.6751671934, "num_tokens": 4071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.25134504596303486}}
{"text": "#include <MeshFEM/MeshIO.hh>\n#include <MeshFEM/MSHFieldWriter.hh>\n#include <MeshFEM/LinearElasticity.hh>\n#include <MeshFEM/Materials.hh>\n#include <MeshFEM/PeriodicHomogenization.hh>\n#include <MeshFEM/OrthotropicHomogenization.hh>\n#include <MeshFEM/GlobalBenchmark.hh>\n#include <MeshFEM/TensorProjection.hh>\n#include <vector>\n\n#include <queue>\n#include <iostream>\n#include <iomanip>\n#include <memory>\n#include <cmath>\n\n#include <boost/program_options.hpp>\n#include <boost/filesystem.hpp>\n\nnamespace po = boost::program_options;\nusing namespace std;\nusing namespace PeriodicHomogenization;\n\n[[ noreturn ]] void usage(int exitVal, const po::options_description &visible_opts) {\n    cout << \"Usage: OpenLinkage output_name [options] mesh\" << endl;\n    cout << visible_opts << endl;\n    exit(exitVal);\n}\n\npo::variables_map parseCmdLine(int argc, const char *argv[])\n{\n    po::options_description hidden_opts(\"Hidden Arguments\");\n    hidden_opts.add_options()\n        (\"name\",       po::value<string>(),                     \"name of experiment\")\n        (\"mesh\",       po::value<string>(),                     \"input mesh\")\n        ;\n    po::positional_options_description p;\n    p.add(\"name\",                1);\n    p.add(\"mesh\",                1);\n\n    po::options_description visible_opts;\n    visible_opts.add_options()(\"help\", \"Produce this help message\")\n        (\"material,m\", po::value<string>(),                 \"base material\")\n        (\"degree,d\",   po::value<int>()->default_value(1), \"degree of finite elements\")\n        (\"ignorePeriodicMismatch\",                         \"Ignore mismatched nodes on the periodic faces (useful for voxel grids)\")\n        (\"manualPeriodicVertices\", po::value<string>(),    \"Manually specify identified periodic vertices using a hacky file format (see PeriodicCondition constructor)\")\n        (\"orthotropicCell,O\",                              \"Analyze the orthotropic symmetry base cell only\")\n        (\"openingSpeed,s\", po::value<Real>()->default_value(0.01), \"Opening step length\")\n        (\"numSteps,n\", po::value<size_t>()->default_value(20), \"Number of opening iterations to run\")\n        (\"outputFreq\", po::value<size_t>()->default_value(100), \"How many iterations between output frames\")\n        ;\n\n    po::options_description cli_opts;\n    cli_opts.add(visible_opts).add(hidden_opts);\n\n    po::variables_map vm;\n    try {\n        po::store(po::command_line_parser(argc, argv).\n                  options(cli_opts).positional(p).run(), vm);\n        po::notify(vm);\n    }\n    catch (std::exception &e) {\n        cout << \"Error: \" << e.what() << endl << endl;\n        usage(1, visible_opts);\n    }\n\n    bool fail = false;\n    if (vm.count(\"mesh\") == 0) {\n        cout << \"Error: must specify input mesh\" << endl;\n        fail = true;\n    }\n\n    int d = vm[\"degree\"].as<int>();\n    if (d < 1 || d > 2) {\n        cout << \"Error: FEM Degree must be 1 or 2\" << endl;\n        fail = true;\n    }\n\n    if (fail || vm.count(\"help\"))\n        usage(fail, visible_opts);\n\n    return vm;\n}\n\n// Sum the values appearing on periodically-identified vertices.\n// First sum onto the reduced DoFs, then redistribute.\ntemplate<class Sim, class VField>\nVField sumIdentifiedValues(const Sim &sim, VField v) {\n    const auto &mesh = sim.mesh();\n    if (v.domainSize() != mesh.numNodes())\n        throw std::runtime_error(\"Expected per-node vector field\");\n\n    VField dofField(sim.numDoFs());\n    dofField.clear();\n    for (size_t i = 0; i < mesh.numNodes(); ++i)\n        dofField(sim.DoF(i)) +=  v(i);\n    for (size_t i = 0; i < mesh.numNodes(); ++i)\n        v(i) = dofField(sim.DoF(i));\n\n    return v;\n}\n\ntemplate<size_t _N>\nusing HMG = LinearElasticity::HomogenousMaterialGetter<Materials::Constant>::template Getter<_N>;\n\ntemplate<size_t _N, size_t _FEMDegree>\nvoid execute(const po::variables_map &args,\n             const vector<MeshIO::IOVertex> &inVertices,\n             const vector<MeshIO::IOElement> &inElements) {\n    auto &mat = HMG<_N>::material;\n    if (args.count(\"material\")) mat.setFromFile(args[\"material\"].as<string>());\n\n    typedef LinearElasticity::Mesh<_N, _FEMDegree, HMG> Mesh;\n    typedef LinearElasticity::Simulator<Mesh> Simulator;\n    Simulator sim(inElements, inVertices);\n    typedef typename Simulator::ETensor ETensor;\n    typedef typename Simulator::VField  VField;\n\n    BENCHMARK_START_TIMER_SECTION(\"Cell Problems\");\n    std::vector<VField> w_ij;\n    std::unique_ptr<PeriodicCondition<_N>> pc;\n    ETensor Eh;\n\n    auto &mesh = sim.mesh();\n\n    std::vector<Real> origLengths;\n    for (auto he : mesh.halfEdges())\n        origLengths.push_back((he.tip().node()->p - he.tail().node()->p).norm());\n\n    std::cout.precision(19);\n\n    auto name = args[\"name\"].as<string>();\n    ofstream eigenvalueFile(name + \"_minEigenvalue.txt\");\n    ofstream ellipseFile(name + \"_openingStrain_ellipse.txt\");\n\n    Real maxRelDiff = 0;\n    for (size_t it = 0; it < args[\"numSteps\"].as<size_t>(); ++it) {\n        if (args.count(\"manualPeriodicVertices\"))\n            pc = Future::make_unique<PeriodicCondition<_N>>(mesh, args[\"manualPeriodicVertices\"].as<string>());\n        if (args.count(\"orthotropicCell\") == 0) {\n            solveCellProblems(w_ij, sim, 1e-7, args.count(\"ignorePeriodicMismatch\"), std::move(pc));\n        }\n        else {\n            auto systems = PeriodicHomogenization::Orthotropic::solveCellProblems(w_ij, sim, 1e-7);\n            cout << systems.size() << endl;\n        }\n\n        BENCHMARK_STOP_TIMER_SECTION(\"Cell Problems\");\n\n        BENCHMARK_START_TIMER_SECTION(\"Compute Tensor\");\n        // ETensor Eh = homogenizedElasticityTensor(w_ij, sim);\n        if (args.count(\"orthotropicCell\") == 0)   Eh = homogenizedElasticityTensorDisplacementForm(w_ij, sim);\n        else Eh = PeriodicHomogenization::Orthotropic::homogenizedElasticityTensorDisplacementForm(w_ij, sim);\n        BENCHMARK_STOP_TIMER_SECTION(\"Compute Tensor\");\n\n        // cout << setprecision(16);\n        // cout << \"Homogenized elasticity tensor:\" << endl;\n        // cout << Eh << endl << endl;\n\n        auto eigs = Eh.computeEigenstrains();\n        // Make all eigenstrains positive\n        if (eigs.strains(0, 0) < 0) eigs.strains.col(0) *= -1;\n        if (eigs.strains(0, 1) < 0) eigs.strains.col(1) *= -1;\n        if (eigs.strains(0, 2) < 0) eigs.strains.col(2) *= -1;\n\n        // cout << \"Minimum Eh eigenvalue \" << eigs.lambdas[0] << \" for eigenstrain:\\t\"\n        //      << eigs.strains.col(0).transpose() << endl;\n\n        SymmetricMatrixValue<Real, _N> minEigenstrain(eigs.strains.col(0));\n        SymmetricMatrixValue<Real, _N> midEigenstrain(eigs.strains.col(1));\n        SymmetricMatrixValue<Real, _N> maxEigenstrain(eigs.strains.col(2));\n        auto openingStrain = minEigenstrain;\n\n        eigenvalueFile << eigs.lambdas[0] << std::endl;\n\n        auto bbox = mesh.boundingBox();\n        VectorND<_N> center = bbox.center();\n        VField cstrainDisp(mesh.numNodes());\n        for (auto n : mesh.nodes())\n            cstrainDisp(n.index()) = openingStrain.contract(n->p - center);\n\n        // Remove rigid translation of fluctuation displacements relative to the\n        // base cell (i.e. try to keep the fluctuation-displaced microstructure\n        // \"within\" the base cell):\n        // The no-rigid-motion constraint on fluctuation displacements\n        // ensures the microstructure's center of mass doesn't move, but\n        // this is not what we need. Instead, we need to ensure vertices on\n        // periodic boundary do not move off the boundary. We enforce this in an\n        // average sense for each cell face by translating so that the\n        // corresponding displacement component's average over all vertices on\n        // the face is zero.\n        for (auto &w : w_ij) {\n            VectorND<_N> translation(VectorND<_N>::Zero());\n            vector<int> numAveraged(_N);\n\n            for (size_t bni = 0; bni < mesh.numBoundaryNodes(); ++bni) {\n                auto n = mesh.boundaryNode(bni).volumeNode();\n                for (size_t d = 0; d < _N; ++d) {\n                    if (std::abs(n->p[d] - bbox.minCorner[d]) < 1e-9) {\n                        translation[d] += w(n.index())[d];\n                        ++numAveraged[d];\n                    }\n                }\n            }\n            for (size_t d = 0; d < _N; ++d)\n                translation[d] /= numAveraged[d];\n            for (size_t n = 0; n < w.domainSize(); ++n)\n                w(n) -= translation;\n        }\n\n        for (size_t i = 0; i < w_ij.size(); ++i) {\n            VField tmp(w_ij[i]);\n            tmp *= (((i < _N) ? 1.0 : 2.0) * openingStrain[i]);\n            cstrainDisp += tmp;\n        }\n\n        VField descentStep = cstrainDisp;\n        descentStep.maxColumnNormalize();\n        descentStep *= args[\"openingSpeed\"].as<Real>();\n        std::vector<MeshIO::IOVertex> pts(mesh.numVertices());\n        for (auto v : mesh.vertices()) {\n            pts[v.index()].point  = padTo3D(v.node()->p);\n            pts[v.index()].point += padTo3D(PointND<_N>(descentStep(v.index())));\n        }\n\n        sim.updateMeshNodePositions(pts);\n\n        if ((it % args[\"outputFreq\"].as<size_t>()) == 0) {\n            MSHFieldWriter writer(name + \"open_it_\" + std::to_string(it) + \".msh\", sim.mesh());\n            writer.addField(\"opening direction\", descentStep, DomainType::PER_NODE);\n\n            auto principalStrains = openingStrain.eigenvalueScaledEigenvectors();\n            Real theta = -atan2(principalStrains(1, 0), principalStrains(0, 0));\n            Real w = 100 * principalStrains.col(0).norm();\n            Real h = 100 * principalStrains.col(1).norm();\n            ellipseFile << \"push graphic-context translate 100,100 rotate \" << 180 * theta / M_PI << \" fill purple stroke black \"\n                        << \"ellipse 0,0 \" << w << ',' << h << \" 0,360 pop graphic-context\" << std::endl;\n        }\n\n        for (auto he : mesh.halfEdges()) {\n            Real len = (he.tip() .node()->p -\n                        he.tail().node()->p).norm();\n            Real ol = origLengths.at(he.index());\n            maxRelDiff = std::max(maxRelDiff, std::abs(len - ol) / ol);\n        }\n\n    }\n    std::cout << \"Maximum relative edge length change: \" << maxRelDiff << std::endl;\n    MSHFieldWriter writer(\"opened.msh\", sim.mesh());\n\n    BENCHMARK_REPORT();\n}\n\n////////////////////////////////////////////////////////////////////////////////\n/*! Program entry point\n//  @param[in]  argc    Number of arguments\n//  @param[in]  argv    Argument strings\n//  @return     status  (0 on success)\n*///////////////////////////////////////////////////////////////////////////////\nint main(int argc, const char *argv[])\n{\n    po::variables_map args = parseCmdLine(argc, argv);\n\n    vector<MeshIO::IOVertex>  inVertices;\n    vector<MeshIO::IOElement> inElements;\n    string meshPath = args[\"mesh\"].as<string>();\n    auto type = load(meshPath, inVertices, inElements, MeshIO::FMT_GUESS,\n                     MeshIO::MESH_GUESS);\n\n    // Infer dimension from mesh type.\n    if (type != MeshIO::MESH_TRI) throw std::runtime_error(\"Only support triangle meshes\");\n\n    // Look up and run appropriate homogenizer instantiation.\n    int deg = args[\"degree\"].as<int>();\n    auto exec = ((deg == 2) ? execute<2, 2> : execute<2, 1>);\n\n    exec(args, inVertices, inElements);\n\n    return 0;\n}\n", "meta": {"hexsha": "896e080111f9ed5b9a544ec33a3c4bb3e2de8802", "size": 11305, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/bin/mechanisms/OpenLinkage.cc", "max_stars_repo_name": "pbedenbaugh/MeshFEM", "max_stars_repo_head_hexsha": "742d609d4851582ffb9c5616774fc2ef489e2f88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2020-10-21T10:05:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:41:50.000Z", "max_issues_repo_path": "src/bin/mechanisms/OpenLinkage.cc", "max_issues_repo_name": "pbedenbaugh/MeshFEM", "max_issues_repo_head_hexsha": "742d609d4851582ffb9c5616774fc2ef489e2f88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-01-01T15:58:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-19T03:31:09.000Z", "max_forks_repo_path": "src/bin/mechanisms/OpenLinkage.cc", "max_forks_repo_name": "pbedenbaugh/MeshFEM", "max_forks_repo_head_hexsha": "742d609d4851582ffb9c5616774fc2ef489e2f88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-10-05T09:01:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T03:02:39.000Z", "avg_line_length": 40.231316726, "max_line_length": 169, "alphanum_fraction": 0.5964617426, "num_tokens": 2851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.25134504057928136}}
{"text": "﻿////////////////////////////////////////////\n/////A* Algorithm (最優先探索アルゴリズム)///////\n////////////////////////////////////////////\n//#define debug//★\n\n#ifdef _DEBUG\n#include <boost/timer/timer.hpp>\n#endif\n\n#include \"slide_algorithm/algorithm_2.hpp\"\n#include <iostream>\n\n//コンストラクタ\nheap::heap(){\n}\n//デストラクタ\nheap::~heap(){\n}\n\nvoid heap::setup(const int *in_y, const int *in_x){\n\ty = *in_y;\n\tx = *in_x;\n\tyx = y*x;\n\t//配列のリサイズ☆おおよそ\n\tcost.resize(1000000);\n\thistory.resize(1000000);\n\thistory_limit.resize(1000000);\n\ttable.resize(1000000, std::vector<int>(yx));\n\theaptable.resize(1000000);\n\tLIST_OC.resize(1000000);\n}\nvoid heap::pop(int *in_cost, std::vector<int> &in_table, std::vector<int> &in_history, int *in_history_limit){\n\n\tint i;\n\tint me;\n\tint top = pos;\n\n\tif (size > 1000000 * sizemaxcount - 1){\n\t\tsizemaxcount++;\n\t\tcost.resize(1000000 * sizemaxcount);\n\t\thistory.resize(1000000 * sizemaxcount);\n\t\thistory_limit.resize(1000000 * sizemaxcount);\n\t\ttable.resize(1000000 * sizemaxcount, std::vector<int>(yx));\n\t\theaptable.resize(1000000 * sizemaxcount);\n\t\tLIST_OC.resize(1000000 * sizemaxcount);\n\t\tstd::cout << \">< heap.cpp vector pass1,000,000\" << std::endl;\n\t}\n\t//重複確認2\n\tbool ok = true;\n\tint sizepos;\n\tauto match_pos = NODE_.find(NODE{in_table,0});//TEの第二引数は関係ない\n\tif (match_pos != NODE_.end()){ //テーブルが一致した\n\t\tsizepos = match_pos->pos;\n\t\tok = false;\n\t\tif (*in_cost < cost[sizepos]){\n\t\t\t//このノードがiのテーブルよりコストが低い\n\t\t\t//ラベルつけてあとで消したほうがいいかも？←その必要はなさそう\n\t\t\tif (LIST_OC[sizepos] == true){\n\t\t\t\t//このノードと同じテーブルがOpenリストに含まれている\n\t\t\t\t//◆書き換え\n\t\t\t\tcost[sizepos] = *in_cost;\n\t\t\t\thistory_limit[sizepos] = *in_history_limit;\n\t\t\t\thistory[sizepos].resize(history_limit[sizepos]);\n\t\t\t\tfor (int m = 0; m < history_limit[sizepos]; m++){\n\t\t\t\t\thistory[sizepos][m] = in_history[m];\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\t//このノードと同じテーブルがCloseリストに含まれている\n\t\t\t\t//◆書き換え\n\t\t\t\tLIST_OC[sizepos] = true;\n\t\t\t\tcost[sizepos] = *in_cost;\n\t\t\t\thistory_limit[sizepos] = *in_history_limit;\n\t\t\t\thistory[sizepos].resize(history_limit[sizepos]);\n\t\t\t\tfor (int m = 0; m < history_limit[sizepos]; m++){\n\t\t\t\t\thistory[sizepos][m] = in_history[m];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif (ok == true){\n\t\t//コスト挿入\n\t\tcost[size] = *in_cost;\n\n\t\t//履歴挿入\n\t\thistory[size].resize(*in_history_limit);\n\t\tfor (i = 0; i < *in_history_limit; i++){\n\t\t\thistory[size][i] = in_history[i];\n\t\t}\n\t\thistory_limit[size] = *in_history_limit;\n\n\t\t//テーブル挿入\n\t\tfor (i = 0; i < yx; i++){\n\t\t\ttable[size][i] = in_table[i];\n\t\t}\n\n\t\t//NODEに挿入\n\t\tNODE_.insert(NODE(table[size], size));\n\n\t\t//OPEN_LIST挿入\n\t\tLIST_OC[size] = true;\n\n\t\t//ヒープ配列挿入\n\t\twhile (1){\n\t\t\tme = top;\n\t\t\ttop = (top - 1) / 2;\n\t\t\tif (me == top){\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if (cost[heaptable[top]] > *in_cost){\n\t\t\t\theaptable[me] = heaptable[top];\n\t\t\t}\n\t\t\telse{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\theaptable[me] = size;\n\n\t\tpos++;\n\t\tsize++;\n\t}\n}\n\nvoid heap::push(int *out_cost, std::vector<int> &out_table, std::vector<int> &out_history, int *out_history_limit){\n\tconst int out = heaptable[0];\n\tint i = 0;\n\tint me = 0;\n\tint bottom = 0;\n\n\tpos--;\n\n\t//OPENからCLOSE_LISTに移動\n\tLIST_OC[out] = false;\n\n\t//コスト挿入\n\t*out_cost = cost[out];\n\n\t//履歴挿入\n\ti = 0;\n\t*out_history_limit = history_limit[out];\n\twhile (i < *out_history_limit){\n\t\tout_history[i] = history[out][i];\n\t\ti++;\n\t}\n\n\t//テーブル挿入\n\tfor (i = 0; i < yx; i++){\n\t\tout_table[i] = table[out][i];\n\t}\n\n\t//ヒープ配列挿入\n\twhile (1){\n\t\tme = bottom;\n\t\tbottom = (bottom * 2);\n\t\tif (pos>bottom + 2){\n\t\t\tif (cost[heaptable[bottom + 1]] < cost[heaptable[bottom + 2]]){\n\t\t\t\tif (cost[heaptable[pos]] > cost[heaptable[bottom + 1]]){\n\t\t\t\t\tbottom += 1;\n\t\t\t\t\theaptable[me] = heaptable[bottom];\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\tif (cost[heaptable[pos]] > cost[heaptable[bottom + 2]]){\n\t\t\t\t\tbottom += 2;\n\t\t\t\t\theaptable[me] = heaptable[bottom];\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (pos>bottom + 1){\n\t\t\tif (cost[heaptable[pos]] > cost[heaptable[bottom + 1]]){\n\t\t\t\tbottom += 1;\n\t\t\t\theaptable[me] = heaptable[bottom];\n\t\t\t}\n\t\t\telse{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tbreak;\n\t\t}\n\t}\n\n\theaptable[me] = heaptable[pos];\n\theaptable.erase(heaptable.end() - 1);\n}\n\nvoid heap::end(){\n\tstd::vector<int>().swap(cost);\n\tstd::vector<int>().swap(heaptable);\n\tstd::vector<bool>().swap(LIST_OC);\n\tstd::vector<int>().swap(cost);\n\tstd::vector<std::vector<int>>().swap(table);\n\tstd::vector<std::vector<int>>().swap(history);\n\tstd::vector<int>().swap(history_limit);\n}\n//コンストラクタ\nalgorithm_2::algorithm_2()\n{\n}\n\n//デストラクタ\nalgorithm_2::~algorithm_2()\n{\n}\n\n//初期化\nvoid algorithm_2::reset(question_data const& data)\n{\n\t// データのクローン\n\tdata_ = data.clone();\n\n\t// 幅と高さ\n\tsize_y = data_->size.second;\n\tsize_x = data_->size.first;\n\tsize = size_y * size_x;\n\n\t// コストとレート\n\tcost_s = data_->cost_select;\n\tcost_c = data_->cost_change;\n\tcost_slimit = data_->selectable;\n\n\t// テーブル\n\t//tableによそから貰ってきたマトリクスを整理して挿入\n\ttable.resize(size);\n\tfor (int y = 0; size_y > y; y++){\n\t\tfor (int x = 0; size_x > x; x++){\n\t\t\ttable[y * size_x + x] = data_->block[y][x].y * size_x + data_->block[y][x].x;\n\t\t}\n\t}\n\t//初期化\n\tharray.setup(&size_y, &size_x);\n\n\n\thistory.resize(10000);\n\tkeiro.resize(1024);\n\tsub_history.resize(10000);\n\troot1.resize(1024);\n\troot2.resize(1024);\n#ifdef _DEBUG_incost\n\tstd::cout << \"\\ngoal=\";\n\tstd::cin >> goal;\n\tstd::cout << \"sentaku=\";\n\tstd::cin >> sentaku;\n\tstd::cout << \"coukan=\";\n\tstd::cin >> coukan;\n#endif\n}\nbool algorithm_2::overlimitcheck(){\n\tif (OVER_LIMIT == true){\n\t\treturn false;\n\t}\n\telse{\n\t\treturn true;\n\t}\n}\n\nauto algorithm_2::get() -> boost::optional<return_type>\n{\n\tint i, count;\n\tstd::cout << \"algorythm_2 start\" << std::endl;\n\tstd::cout << \"size_y=\" << size_y << \",size_x=\" << size_x << std::endl;\n#ifdef _DEBUG\n\tfor (int y = 0; size_y > y; y++){\n\t\tfor (int x = 0; size_x > x; x++){\n\t\t\tstd::cout << std::setw(3) << table[y * size_x + x] << \",\";\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n\t//パズルスタート\n\tstd::cout << \"start\" << std::endl;\n\tboost::timer::cpu_timer timer; // 時間計測を開始\n#endif\n\n\twhile (1){\n\t\t//探索\n\t\talgorithm_2::prescanning();\n\t\t//取得\n\t\tharray.push(&cost, table, history, &history_limit);\n\t\t//完成判定\n\t\tcount = 0;\n\t\tfor (i = 0; i<size; i++){\n\t\t\tif (table[i] == i) count++;\n\t\t}\n\t\tif (count == size){\n\t\t\tstd::cout << \"algorithm_2 finish\" << std::endl;\n\t\t\tint ANSWER_S = 0, ANSWER_C = 0;\n\t\t\tfor (int i = 0; i < history_limit; i++){\n\t\t\t\tif (history[i] < 16){\n\t\t\t\t\tANSWER_S += 1;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tANSWER_C += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tANSWER_S /= 2;\n\t\t\tif (ANSWER_S > cost_slimit){\n\t\t\t\t//最大選択回数を超えた\n\t\t\t\tOVER_LIMIT = true;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tfor (int i = 0; i < history_limit; i++){\n\t\t\t\t\tswitch (history[i]){\n\t\t\t\t\tcase 16:\n\t\t\t\t\tcase 20:\n\t\t\t\t\t\tstd::cout << \",U\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 17:\n\t\t\t\t\tcase 21:\n\t\t\t\t\t\tstd::cout << \",R\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 18:\n\t\t\t\t\tcase 22:\n\t\t\t\t\t\tstd::cout << \",D\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 19:\n\t\t\t\t\tcase 23:\n\t\t\t\t\t\tstd::cout << \",L\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tstd::cout << \",\" << history[i];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::cout << std::endl;\n            std::cout << \"選択コスト=\" << cost_s << \",交換コスト=\" << cost_c << std::endl;\n\t\t\tstd::cout << \"cost=\" << ANSWER_S * cost_s + ANSWER_C * cost_c << \" S: \" << ANSWER_S << \" C: \" << ANSWER_C << std::endl;\n#ifdef _DEBUG\n\t\t\t//完成☆後で消したりなんたり\n\t\t\tstd::string result = timer.format();\n\t\t\tstd::cout << \"end\" << std::endl;\n\t\t\tstd::cout << \"処理時間:\" << result << std::endl;\n\t\t\tfor (int i = 0; i < history_limit; i++){\n\t\t\t\tswitch (history[i]){\n\t\t\t\tcase 16:\n\t\t\t\tcase 20:\n\t\t\t\t\tstd::cout << \",U\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase 17:\n\t\t\t\tcase 21:\n\t\t\t\t\tstd::cout << \",R\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase 18:\n\t\t\t\tcase 22:\n\t\t\t\t\tstd::cout << \",D\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase 19:\n\t\t\t\tcase 23:\n\t\t\t\t\tstd::cout << \",L\";\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tstd::cout << \",\" << history[i];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::cout << std::endl;\n\t\t\tint _DEBUG_S = 0, _DEBUG_C = 0;\n\t\t\tfor (int i = 0; i < history_limit; i++){\n\t\t\t\tif (history[i] < 16){\n\t\t\t\t\t_DEBUG_S += 1;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\t_DEBUG_C += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\t_DEBUG_S /= 2;\n\t\t\tstd::cout << \"選択コスト=\" << cost_s << \",交換コスト=\" << cost_c << std::endl;\n\t\t\tstd::cout << \"cost=\" << _DEBUG_S * cost_s + _DEBUG_C * cost_c << \" S: \" << _DEBUG_S << \" C: \" << _DEBUG_C << std::endl;\n#endif\n\t\t\tharray.end();\n\t\t\t//解をanswer_typeにして返す\n\t\t\tanswer_type answerlist;\n\t\t\tpoint_type position;\n\t\t\tstd::ostringstream stream;\n\t\t\tint pos = 0;\n\t\t\tfor (int count = 0; pos < history_limit; count++){\n\t\t\t\tposition.y = history[pos];\n\t\t\t\tpos++;\n\t\t\t\tposition.x = history[pos];\n\t\t\t\tpos++;\n\t\t\t\twhile (pos < history_limit && 16 <= history[pos]){\n\t\t\t\t\tswitch (history[pos]){\n\t\t\t\t\tcase 16:\n\t\t\t\t\tcase 20:\n\t\t\t\t\t\tstream << \"U\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 17:\n\t\t\t\t\tcase 21:\n\t\t\t\t\t\tstream << \"R\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 18:\n\t\t\t\t\tcase 22:\n\t\t\t\t\t\tstream << \"D\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 19:\n\t\t\t\t\tcase 23:\n\t\t\t\t\t\tstream << \"L\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tpos++;\n\t\t\t\t}\n\t\t\t\tanswerlist.list.push_back({ position, stream.str() });\n\t\t\t\tstream.str(\"\");\n\t\t\t}\n\t\t\treturn answerlist;\n\t\t}\n\t}\n}\n\n//走査準備(全てのマスを一つづつscaningで調べる)\nvoid algorithm_2::prescanning(){\n\tfor (int y = 0; y < size_y; y++){\n\t\tfor (int x = 0; x < size_x; x++){\n\t\t\tkeiro[0] = y;\n\t\t\tkeiro[1] = x;\n\t\t\tkeiro_count = 2;\n\t\t\tscanning(y, x, y, x, -1);\n\t\t}\n\t}\n}\n\n//走査\nvoid algorithm_2::scanning(int y, int x, int y_before, int x_before, int URDL){\n\tint i, buff;\n\tbool feel, feeled;\n\n\t//最初だけ上下左右を通りあとは再帰的に来て保存する（ちょっと無駄だけど直す時間がなかった）\n\n\tif ((y == y_before && x == x_before)){\n\t\t//進む(上右下左の順)\n\t\t//上\n\t\tif (y > 0 && URDL != 2){\n\t\t\tif (table[y * size_x + x] / size_x < y){\n\t\t\t\tfeel = true;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tfeel = false;\n\t\t\t}\n\t\t\tif (table[(y - 1) * size_x + x] / size_x > y - 1)\n\t\t\t{\n\t\t\t\tfeeled = true;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tfeeled = false;\n\t\t\t}\n\t\t\tif (feel == true/* || feeled==true*/){\n\t\t\t\tif (feel == true && feeled == true){\n\t\t\t\t\tkeiro[keiro_count] = 16;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tkeiro[keiro_count] = 20;\n\t\t\t\t}\n\t\t\t\tkeiro_count += 1;\n\t\t\t\t//交換\n\t\t\t\tbuff = table[y * size_x + x];\n\t\t\t\ttable[y * size_x + x] = table[(y - 1) * size_x + x];\n\t\t\t\ttable[(y - 1) * size_x + x] = buff;\n\t\t\t\tscanning(y - 1, x, y, x, 0);\n\t\t\t}\n\t\t}\n\t\t//右\n\t\tif (x < size_x - 1 && URDL != 3){\n\t\t\tif (table[y * size_x + x] % size_x > x){\n\t\t\t\tfeel = true;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tfeel = false;\n\t\t\t}\n\t\t\tif (table[y * size_x + (x + 1)] % size_x < x + 1)\n\t\t\t{\n\t\t\t\tfeeled = true;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tfeeled = false;\n\t\t\t}\n\t\t\tif (feel == true/* || feeled==true*/){\n\t\t\t\tif (feel == true && feeled == true){\n\t\t\t\t\tkeiro[keiro_count] = 17;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tkeiro[keiro_count] = 21;\n\t\t\t\t}\n\t\t\t\tkeiro_count += 1;\n\t\t\t\t//交換\n\t\t\t\tbuff = table[y * size_x + x];\n\t\t\t\ttable[y * size_x + x] = table[y * size_x + (x + 1)];\n\t\t\t\ttable[y * size_x + (x + 1)] = buff;\n\t\t\t\tscanning(y, x + 1, y, x, 1);\n\t\t\t}\n\t\t}\n\t\t//下\n\t\tif (y < size_y - 1 && URDL != 0){\n\t\t\tif (table[y * size_x + x] / size_x > y){\n\t\t\t\tfeel = true;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tfeel = false;\n\t\t\t}\n\t\t\tif (table[(y + 1) * size_x + x] / size_x < y + 1)\n\t\t\t{\n\t\t\t\tfeeled = true;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tfeeled = false;\n\t\t\t}\n\t\t\tif (feel == true/* || bbuff2==true*/){\n\t\t\t\tif (feel == true && feeled == true){\n\t\t\t\t\tkeiro[keiro_count] = 18;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tkeiro[keiro_count] = 22;\n\t\t\t\t}\n\t\t\t\tkeiro_count += 1;\n\t\t\t\t//交換\n\t\t\t\tbuff = table[y * size_x + x];\n\t\t\t\ttable[y * size_x + x] = table[(y + 1) * size_x + x];\n\t\t\t\ttable[(y + 1) * size_x + x] = buff;\n\t\t\t\tscanning(y + 1, x, y, x, 2);\n\t\t\t}\n\t\t}\n\t\t//左\n\t\tif (x > 0 && URDL != 1){\n\t\t\tif (table[y * size_x + x] % size_x < x){\n\t\t\t\tfeel = true;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tfeel = false;\n\t\t\t}\n\t\t\tif (table[y * size_x + (x - 1)] % size_x > x - 1)\n\t\t\t{\n\t\t\t\tfeeled = true;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tfeeled = false;\n\t\t\t}\n\t\t\tif (feel == true/* || bbuff2==true*/){\n\t\t\t\tif (feel == true && feeled == true){\n\t\t\t\t\tkeiro[keiro_count] = 19;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tkeiro[keiro_count] = 23;\n\t\t\t\t}\n\t\t\t\tkeiro_count += 1;\n\t\t\t\t//交換\n\t\t\t\tbuff = table[y * size_x + x];\n\t\t\t\ttable[y * size_x + x] = table[y * size_x + (x - 1)];\n\t\t\t\ttable[y * size_x + (x - 1)] = buff;\n\t\t\t\tscanning(y, x - 1, y, x, 3);\n\t\t\t}\n\t\t}\n\t}\n\tif ((y != y_before || x != x_before)) //一番最初以外\n\t{\n\t\tif (history_limit > 10000 * sizemaxhistory - 2){\n\t\t\tsizemaxhistory++;\n\t\t\thistory.resize(10000 * sizemaxhistory);\n\t\t\tsub_history.resize(10000 * sizemaxhistory);\n#ifdef _DEBUG\n\t\t\tstd::cout << \">< search.cpp history vector pass10,000\" << std::endl;\n#endif\n\t\t}\n\t\t//パターン配列(経路)に保存\n\t\tfor (i = 0; i < keiro_count; i++){\n\t\t\thistory[history_limit + i] = keiro[i];\n\t\t}\n\t\thistory_limit += keiro_count;\n\t\t//■■■■shorting■■■■\n\t\tsub_history_limit = history_limit;\n\t\tfor (i = 0; i < sub_history_limit; i++){\n\t\t\tsub_history[i] = history[i];\n\t\t}\n\t\tshorting();\n\t\t//■■■■■■■■■■■■\n\t\t//cost = 選択コスト+交換コスト+ゴールまでの距離;\n\t\tG = 0;\n\t\tS = 0;\n\t\tC = 0;\n\t\t//ゴールまでの距離\n\t\tfor (i = 0; i < size; i++){\n\t\t\tG += abs(table[i] / size_x - i / size_x) + abs(table[i] % size_x - i % size_x);\n\t\t}\n\t\t//交換コストと選択コストも入れる\n\t\tfor (i = 0; i < sub_history_limit; i++){\n\t\t\tif (sub_history[i] < 16){\n\t\t\t\tS++;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tC++;\n\t\t\t}\n\t\t}\n\t\tG *= goal;\n\t\tS *= sentaku;\n\t\tC *= coukan;\n\t\tcost = G + S + C;\n\n#ifdef test2\n\t\t//@@@重要：：ここやらなきゃ←やらなくてもいいかも\n\t\t//最大選択回数より大きいならやめる\n\t\tif (S / 15 < 3){\n\t\t\tharray.pop(&cost, table, subhistory, &subhistory_limit);\n\t\t}\n#else\n\t\t//登録\n\t\tharray.pop(&cost, table, sub_history, &sub_history_limit);\n#endif\n\t\thistory_limit -= keiro_count;\n\t}\n\t//全部見終わったらtableを元通りにして返す\n\tbuff = table[y * size_x + x];\n\ttable[y * size_x + x] = table[y_before * size_x + x_before];\n\ttable[y_before * size_x + x_before] = buff;\n\n\t//うち経路消すん\n\tkeiro[keiro_count] = 0;\n\tif (keiro_count>2) keiro_count -= 1;\n\n\ty = y_before;\n\tx = x_before;\n\t//最初の階層に上がる\n}\nvoid algorithm_2::shorting(){\n\t//経路をまとめて短縮する\n\tint i;\n\tint x1_head, y1_head, root1_count, y1_tail, x1_tail;\n\tint x2_head, y2_head, root2_count, y2_tail, x2_tail;\n\tint start, count = 0, end;\n\n\twhile (count + 5<sub_history_limit){\n\n\t\troot1_count = 0;\n\t\troot2_count = 0;\n\t\tstart = count;\n\t\ty1_head = sub_history[count];\n\t\tcount++;\n\t\tx1_head = sub_history[count];\n\t\tcount++;\n\t\twhile (1){\n\t\t\tif (!(count<sub_history_limit && sub_history[count] >= 16 && sub_history[count] <= 23)) break;\n\t\t\tif (root1_count > 1024 * sizemaxroot1 - 1){\n\t\t\t\tsizemaxroot1++;\n\t\t\t\troot1.resize(1024 * sizemaxroot1);\n#ifdef _DEBUG\n\t\t\t\tstd::cout << \">< search.cpp root1 vector pass1,024\" << std::endl;\n#endif\n\t\t\t}\n\t\t\troot1[root1_count] = sub_history[count];\n\t\t\troot1_count++;\n\t\t\tcount++;\n\t\t}\n\t\tif (!(count<sub_history_limit)){\n\t\t\tbreak;\n\t\t}\n\t\tend = count;\n\t\ty2_head = sub_history[end];\n\t\tend++;\n\t\tx2_head = sub_history[end];\n\t\tend++;\n\t\twhile (1){\n\t\t\tif (!(end < sub_history_limit && sub_history[end] >= 16 && sub_history[end] <= 23)) break;\n\t\t\tif (root2_count > 1024 * sizemaxroot2 - 1){\n\t\t\t\tsizemaxroot2++;\n\t\t\t\troot2.resize(1024 * sizemaxroot2);\n#ifdef _DEBUG\n\t\t\t\tstd::cout << \">< search.cpp root2 vector pass10,000\" << std::endl;\n#endif\n\t\t\t}\n\t\t\troot2[root2_count] = sub_history[end];\n\t\t\troot2_count++;\n\t\t\tend++;\n\t\t}\n\t\t//get tail\n\t\ty1_tail = y1_head;\n\t\tx1_tail = x1_head;\n\t\tfor (i = 0; i < root1_count; i++){\n\t\t\tswitch (root1[i]){\n\t\t\tcase 16:\n\t\t\t\ty1_tail -= 1;\n\t\t\t\tbreak;\n\t\t\tcase 17:\n\t\t\t\tx1_tail += 1;\n\t\t\t\tbreak;\n\t\t\tcase 18:\n\t\t\t\ty1_tail += 1;\n\t\t\t\tbreak;\n\t\t\tcase 19:\n\t\t\t\tx1_tail -= 1;\n\t\t\t\tbreak;\n\t\t\tcase 20:\n\t\t\t\ty1_tail -= 1;\n\t\t\t\tbreak;\n\t\t\tcase 21:\n\t\t\t\tx1_tail += 1;\n\t\t\t\tbreak;\n\t\t\tcase 22:\n\t\t\t\ty1_tail += 1;\n\t\t\t\tbreak;\n\t\t\tcase 23:\n\t\t\t\tx1_tail -= 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\ty2_tail = y2_head;\n\t\tx2_tail = x2_head;\n\t\tfor (i = 0; i < root2_count; i++){\n\t\t\tswitch (root2[i]){\n\t\t\tcase 16:\n\t\t\t\ty2_tail -= 1;\n\t\t\t\tbreak;\n\t\t\tcase 17:\n\t\t\t\tx2_tail += 1;\n\t\t\t\tbreak;\n\t\t\tcase 18:\n\t\t\t\ty2_tail += 1;\n\t\t\t\tbreak;\n\t\t\tcase 19:\n\t\t\t\tx2_tail -= 1;\n\t\t\t\tbreak;\n\t\t\tcase 20:\n\t\t\t\ty2_tail -= 1;\n\t\t\t\tbreak;\n\t\t\tcase 21:\n\t\t\t\tx2_tail += 1;\n\t\t\t\tbreak;\n\t\t\tcase 22:\n\t\t\t\ty2_tail += 1;\n\t\t\t\tbreak;\n\t\t\tcase 23:\n\t\t\t\tx2_tail -= 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t//Rule1\n\t\tif (y1_tail == y2_head && x1_tail == x2_head){\n\t\t\tfor (i = 0; i < root2_count; i++){\n\t\t\t\tsub_history[count] = root2[i];\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\tfor (i = 0; i + end < sub_history_limit; i++){\n\t\t\t\tsub_history[count + i] = sub_history[end + i];\n\t\t\t}\n\t\t\tsub_history_limit = count + i;\n\t\t\tcount = 0;\n\t\t}\n\t\t//Rule2\n\t\telse if (y1_tail == y2_tail && x1_tail == x2_tail && root2_count == 1){\n\t\t\t//root2の各方向を反転\n\t\t\treverse(&root2[0]);\n\t\t\tsub_history[count] = root2[0];\n\t\t\tcount++;\n\t\t\tfor (i = 0; i + end < sub_history_limit; i++){\n\t\t\t\tsub_history[count + i] = sub_history[end + i];\n\t\t\t}\n\t\t\tsub_history_limit = count + i;\n\t\t\tcount = 0;\n\t\t}\n\t\t//Rule3\n\t\telse if (y1_head == y2_head && x1_head == x2_head && root1_count == 1){\n\t\t\t//root1の各方向を反転\n\t\t\treverse(&root1[0]);\n\t\t\tsub_history[start] = y1_tail;\n\t\t\tstart++;\n\t\t\tsub_history[start] = x1_tail;\n\t\t\tstart++;\n\t\t\tsub_history[start] = root1[0];\n\t\t\tstart++;\n\t\t\tfor (i = 0; i < root2_count; i++){\n\t\t\t\tsub_history[start] = root2[i];\n\t\t\t\tstart++;\n\t\t\t}\n\t\t\tfor (i = 0; i + end < sub_history_limit; i++){\n\t\t\t\tsub_history[start + i] = sub_history[end + i];\n\t\t\t}\n\t\t\tsub_history_limit = start + i;\n\t\t\tcount = 0;\n\t\t}\n\t\t//Rule4\n\t\telse if (y1_head == y2_tail && x1_head == x2_tail && root1_count == 1 && root2_count == 1){\n\t\t\t//root1の各方向を反転\n\t\t\treverse(&root1[0]);\n\t\t\t//root2の各方向を反転\n\t\t\treverse(&root2[0]);\n\t\t\tsub_history[start] = y1_tail;\n\t\t\tsub_history[start + 1] = x1_tail;\n\t\t\tsub_history[start + 2] = root1[0];\n\t\t\tsub_history[start + 3] = root2[0];\n\t\t\tfor (i = 0; i + end < sub_history_limit; i++){\n\t\t\t\tsub_history[start + 4 + i] = sub_history[end + i];\n\t\t\t}\n\t\t\tsub_history_limit = start + 4 + i;\n\t\t\tcount = 0;\n\t\t}\n\t}\n}\nvoid algorithm_2::reverse(int *x){\n\tswitch (*x){\n\tcase 16:\n\t\t*x = 18;\n\t\tbreak;\n\tcase 17:\n\t\t*x = 19;\n\t\tbreak;\n\tcase 18:\n\t\t*x = 16;\n\t\tbreak;\n\tcase 19:\n\t\t*x = 17;\n\t\tbreak;\n\tcase 20:\n\t\t*x = 22;\n\t\tbreak;\n\tcase 21:\n\t\t*x = 23;\n\t\tbreak;\n\tcase 22:\n\t\t*x = 20;\n\t\tbreak;\n\tcase 23:\n\t\t*x = 21;\n\t\tbreak;\n\t}\n\treturn;\n}\n", "meta": {"hexsha": "f9e23d56f66f26a8c21045eeda366a4b1ae5cbf2", "size": 17331, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "clammbon/src/slide_algorithm/algorithm_2.cpp", "max_stars_repo_name": "tnct-spc/procon2014", "max_stars_repo_head_hexsha": "c2df3257675db2adb9caa882b9026145801c6e4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-02T08:42:05.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-02T08:42:05.000Z", "max_issues_repo_path": "clammbon/src/slide_algorithm/algorithm_2.cpp", "max_issues_repo_name": "tnct-spc/procon2014", "max_issues_repo_head_hexsha": "c2df3257675db2adb9caa882b9026145801c6e4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "clammbon/src/slide_algorithm/algorithm_2.cpp", "max_forks_repo_name": "tnct-spc/procon2014", "max_forks_repo_head_hexsha": "c2df3257675db2adb9caa882b9026145801c6e4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8807228916, "max_line_length": 122, "alphanum_fraction": 0.5527090185, "num_tokens": 6656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2513203076179137}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2012 Zuse Institute Berlin                                 */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#ifndef TCG_HH\n#define TCG_HH\n\n#include <numeric>\n\n#include <boost/circular_buffer.hpp>\n\n#include \"dune/common/timer.hh\"\n#include \"dune/istl/istlexception.hh\"\n#include \"dune/istl/operators.hh\"\n#include \"dune/istl/preconditioners.hh\"\n#include \"dune/istl/scalarproducts.hh\"\n#include \"dune/istl/solvers.hh\"\n\n#include \"utilities/geometric_sequence.hh\"\n#include \"utilities/scalar.hh\"\n#include \"utilities/duneInterface.hh\"\n\n#include \"linalg/apcg.hh\"\n\nnamespace Kaskade\n{\n  struct NoRegularization\n  {\n    template <class X, class Xstar>\n    void operator()(const X&, Xstar&){}\n  };\n\n  template <class Linearization, class VariableSet>\n  struct DoRegularization\n  {\n    DoRegularization(Linearization const& lin_, typename VariableSet::Descriptions const& description) : lin(lin_), v(description)\n    {}\n\n    template <class X, class Xstar>\n    void operator()(const X& x, Xstar& r)\n    {\n      v = x; //\n      Bridge::Vector<VariableSet> y(v), z(v);\n      y *= 0;\n      lin.ddxpy(y,z,0,2,2,3);\n      y *= -1;\n      v = r; //\n\n      boost::fusion::at_c<0>(v.data) += boost::fusion::at_c<0>(y.get().data);\n      boost::fusion::at_c<1>(v.data) += boost::fusion::at_c<1>(y.get().data);\n\n      r = v; //\n    }\n\n    private:\n      Linearization const& lin;\n      VariableSet v;\n  };\n\n  /**\n   * \\ingroup linalgsolution\n   * \\brief preconditioned conjugate gradient method\n   *\n   * This implements a preconditioned IterateType::CG iteration for an operator \\f$ A: X\\to x^* \\f$, preconditioned by a\n   * preconditioner \\f$ B^{-1}: X^* \\to X \\f$. The termination is based on an estimate of the absolute energy error.\n   *\n   * The implementation follows Deuflhard/Weiser, Section 5.3.3.\n   *\n   */\n  template<class X, class Xstar, class Regularization=NoRegularization>\n  class TCG : public Dune::InverseOperator<X,Xstar> {\n  public:\n    enum class Result { Converged, Failed, EncounteredNonConvexity };\n    /**\n     * \\brief the real field type corresponding to X::field_type\n     */\n    typedef typename ScalarTraits<typename GetScalar<X>::type >::Real Real;\n\n    /** \n     * \\brief Set up conjugate gradient solver with absolute energy error termination criterion.\n     * \n     * \\param verbose\n     */\n    template <class Int=int, class enable = typename std::enable_if<!std::is_same<Regularization,NoRegularization>::value && std::is_same<Int,int>::value>::type>\n    TCG(Dune::LinearOperator<X,Xstar>& op_, Dune::Preconditioner<X,Xstar>& prec_, DualPairing<X,Xstar> const& dp_,\n        Regularization& regularization_, double relTol_=1e-3, size_t maxSteps_=100, Int verbose_=0) :\n          op(op_), prec(prec_), dp(dp_), regularization(regularization_), relTol(relTol_), absTol(1e-9), maxSteps(maxSteps_), verbose(verbose_)\n    {\n      // Do we need this in Kaskade7?\n      //         dune_static_assert( static_cast<int>(L::category) == static_cast<int>(P::category),\n      //                             \"L and P must have the same category!\");\n      //         dune_static_assert( static_cast<int>(L::category) == static_cast<int>(SolverCategory::sequential),\n      //                             \"L must be sequential!\");\n    }\n\n    /**\n     * \\brief Set up conjugate gradient solver with absolute energy error termination criterion.\n     *\n     * \\param verbose\n     */\n    template <class Int=int, class enable = typename std::enable_if<std::is_same<Regularization,NoRegularization>::value && std::is_same<Int,int>::value>::type>\n    TCG(Dune::LinearOperator<X,Xstar>& op_, Dune::Preconditioner<X,Xstar>& prec_, DualPairing<X,Xstar> const& dp_,\n        double relTol_=1e-3, size_t maxSteps_=100, Int verbose_=0) :\n          op(op_), prec(prec_), dp(dp_), relTol(relTol_), absTol(1e-9), maxSteps(maxSteps_), verbose(verbose_)\n    {\n      // Do we need this in Kaskade7?\n      //         dune_static_assert( static_cast<int>(L::category) == static_cast<int>(P::category),\n      //                             \"L and P must have the same category!\");\n      //         dune_static_assert( static_cast<int>(L::category) == static_cast<int>(SolverCategory::sequential),\n      //                             \"L must be sequential!\");\n    }\n\n    /**\n     * \\brief Apply inverse operator.\n     * \n     * \\param u the initial value (starting iterate)\n     * \\param b the right hand side\n     */\n    virtual int apply (X& u, X& q, Xstar& b, Dune::InverseOperatorResult& res) \n    {\n      result = Result::Failed;\n      int numberOfResults = 1;\n      res.clear();                // clear solver statistics\n      //terminate.clear();          // clear termination criterion\n      Dune::Timer watch;          // start a timer\n\n      prec.pre(u,b);\n\n      Xstar r(b); \n      op.applyscaleadd(-1.0,u,r);  // r = b-Au\n      regularization(u,r);\n\n      X rq(u), du(u); rq = 0;\n\n      prec.apply(rq,r); // rq = B^{-1} r\n\n      q = rq;\n\n      X Aq(b);\n\n\n      // some local variables\n      Real alpha,beta,sigma,gamma;\n      sigma = dp(rq,r); // preconditioned residual norm squared\n\n      //terminate.residual(sigma);\n      double const sigma0 = std::abs(sigma);\n\n      if (verbose>0) {            // printing\n        std::cout << \"=== Kaskade7 TCG\" << std::endl;\n        if (verbose>1) {\n          this->printHeader(std::cout);\n          this->printOutput(std::cout,0,sigma0);\n        }\n      }\n\n      // the loop\n      int i=0;\n      while(true)\n      {\n        ++i;\n        // minimize in given search direction p\n        op.apply(q,Aq);             // h = Aq\n        Real qAq = dp(q,Aq);\n\n        if(qAq <=0)\n        {\n          result = Result::EncounteredNonConvexity;\n          if(verbose > 0) std::cout << \"Nonconvexity at iteration \" << i << \", qAq=\" << qAq << \", ||q||=\" << sqrt(q*q) << std::endl;\n          if(i==1)\n          {\n            u.axpy(1.0,q);\n            break;\n          }\n          numberOfResults = 2;\n          break;      // Abbruch wg. fehlender Konvexität\n        }\n\n        alpha = sigma/qAq;\n        u.axpy(alpha,q);\n        du = q;\n        du *= 1./alpha;\n        if(dp(du,du) < absTol)\n        {\n          result = Result::Converged;\n          break;\n        }\n\n        gamma = sigma*alpha;\n        //terminate.step(ScalarTraits<Real>::real(gamma));\n        resDebug.push_back(std::sqrt(sigma));\n\n        // convergence test\n        //if (terminate)\n          //break;\n\n        r.axpy(-alpha,Aq); // r = r - alpha*A*q\n        regularization(u,r);\n        rq = 0;\n        prec.apply(rq,r); // rq = B^{-1}r\n\n        // determine new search direction\n        double sigmaNew = dp(rq,r); \n        //terminate.residual(ScalarTraits<Real>::real(sigmaNew));\n        if (verbose>1)             // print\n          this->printOutput(std::cout,i,std::abs(sigmaNew),std::abs(sigma));\n\n        // convergence check to prevent division by zero if we obtained an exact solution\n        // (which may happen for low dimensional systems)\n        if (std::abs(sigmaNew) < relTol*sigma0)\n        {\n          result = Result::Converged;\n          break;\n        }\n        beta = sigmaNew/sigma;\n        if(verbose > 0) std::cout << \"step reduction: \" << (sigmaNew/sigma) << \", overall reduction: \" << (sigmaNew/sigma0) << std::endl;\n        sigma = sigmaNew;\n        q *= beta;                  // scale old search direction\n        q += rq;                     // orthogonalization with correction\n        \n        if(i > maxSteps) break;\n      }\n\n      res.iterations = i;               // fill statistics\n      res.reduction = std::sqrt(std::abs(sigma)/sigma0);\n      res.conv_rate  = pow(res.reduction,1.0/i);\n      res.elapsed = watch.elapsed();\n\n      if (verbose>0)                 // final print \n      {\n        std::cout << \"=== rate=\" << res.conv_rate\n            << \", time=\" << res.elapsed\n            << \", iterations=\" << i << std::endl;\n      } \n\n      prec.post(u);\n\n      return numberOfResults;\n    }\n\n    /**\n     * \\brief Apply tcg and possibly forget second descent direction\n     */\n    virtual void apply (X& u, Xstar& b, Dune::InverseOperatorResult& res) {\n      X q(u);\n      apply(u,q,b,res);\n    }\n\n    void apply (X& u, Xstar& b)\n    {\n      Dune::InverseOperatorResult res;\n      apply(u,b,res);\n    }\n\n    /** \n     * \\brief Apply inverse operator with given absolute tolerance.\n     */\n    virtual void apply (X& x, X& b, double relTol, Dune::InverseOperatorResult& res) {\n      //terminate.relTol(relTol);\n      (*this).apply(x,b,res);\n    }\n\n    void setRelativeAccuracy(double relTol_) { relTol = relTol_; }\n\n    void setMaxSteps(size_t maxSteps_) { maxSteps = maxSteps_; }\n    \n    bool localConvergenceLikely() const { return result == Result::Converged; }\n\n    bool encounteredNonConvexity() const { return result == Result::EncounteredNonConvexity; }\n\n  private:\n    Dune::LinearOperator<X,Xstar>& op;\n    Dune::Preconditioner<X,Xstar>& prec;\n    DualPairing<X,Xstar> const& dp;\n    typename std::conditional<std::is_same<Regularization,NoRegularization>::value,NoRegularization,Regularization&>::type regularization;\n    double relTol, absTol;\n    size_t maxSteps;\n    int verbose;\n    std::vector<double> resDebug;\n    Result result;\n  };\n\n  template <class X, class Xstar, class Regularization = NoRegularization> using TPCG = TCG<X,Xstar,Regularization>;\n} // namespace Kaskade\n#endif\n", "meta": {"hexsha": "f70bd31fdf980cd85e76de9136384898d3efee15", "size": 10101, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/linalg/tcg.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/linalg/tcg.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:33.000Z", "max_forks_repo_path": "Kaskade/linalg/tcg.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 34.3571428571, "max_line_length": 161, "alphanum_fraction": 0.5547965548, "num_tokens": 2611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2513203076179137}}
{"text": "/*******************************************************************************\n#      ____               __          __  _      _____ _       _               #\n#     / __ \\              \\ \\        / / | |    / ____| |     | |              #\n#    | |  | |_ __   ___ _ __ \\  /\\  / /__| |__ | |  __| | ___ | |__   ___      #\n#    | |  | | '_ \\ / _ \\ '_ \\ \\/  \\/ / _ \\ '_ \\| | |_ | |/ _ \\| '_ \\ / _ \\     #\n#    | |__| | |_) |  __/ | | \\  /\\  /  __/ |_) | |__| | | (_) | |_) |  __/     #\n#     \\____/| .__/ \\___|_| |_|\\/  \\/ \\___|_.__/ \\_____|_|\\___/|_.__/ \\___|     #\n#           | |                                                                #\n#           |_|                                                                #\n#                                                                              #\n#                                (c) 2011 by                                   #\n#           University of Applied Sciences Northwestern Switzerland            #\n#                     Institute of Geomatics Engineering                       #\n#                           martin.christen@fhnw.ch                            #\n********************************************************************************\n*     Licensed under MIT License. Read the file LICENSE for more information   *\n*******************************************************************************/\n\n//------------------------------------------------------------------------------\n\n#include \"og.h\"\n#include \"ogprocess.h\"\n#include \"geo/MercatorQuadtree.h\"\n#include \"geo/CoordinateTransformation.h\"\n#include \"geo/PointCloudReader.h\"\n#include \"math/Octocode.h\"\n#include \"string/FilenameUtils.h\"\n#include \"string/StringUtils.h\"\n#include \"io/FileSystem.h\"\n#include <float.h>\n#include <iostream>\n#include <ctime>\n#include <boost/program_options.hpp>\n\n\nint _frominput(const std::vector<std::string>& vecFiles, const std::string& srs, bool bVerbose, bool bPointCloud);\nvoid _calcfromwgs84(int, double, double, double, double);\n//------------------------------------------------------------------------------\n\nnamespace po = boost::program_options;\n\nint main(int argc, char *argv[])\n{\n   po::options_description desc(\"Program-Options\");\n   desc.add_options()\n       (\"maxlod\", po::value<int>(), \"desired level of detail (integer)\")\n       (\"wgs84\", po::value< std::vector<double> >()->multitoken(), \"wgs84 coordinates lng0 lat0 lng1 lat1\")\n       (\"srs\", po::value<std::string>(), \"spatial reference system for input files\")\n       (\"input\", po::value< std::vector<std::string> >()->multitoken(), \"list input files\")\n       (\"verbose\", \"display additional information\")\n       (\"inputdir\", po::value<std::string>(), \"input directory\")\n       (\"filetype\",  po::value<std::string>(), \"file type\")\n       (\"point\", \"for point cloud\")\n       ;\n\n   po::variables_map vm;\n\n   try\n   {\n      po::store(po::parse_command_line(argc, argv, desc), vm);\n      po::notify(vm);\n   }\n   catch (std::exception&)\n   {\n      std::cout << desc;\n      return 4;\n   }\n\n   bool bVerbose = false;\n   bool bPointCloud = false;\n\n   if (vm.count(\"verbose\"))\n   {\n      bVerbose = true;\n   }\n\n   if (vm.count(\"point\"))\n   {\n      bPointCloud = true;\n   }\n\n   if ((vm.count(\"wgs84\") && !vm.count(\"maxlod\")) || (!vm.count(\"wgs84\") && vm.count(\"maxlod\")))\n   {\n      std::cout << \"ERROR: option --wgs84 and --maxlod must be used together\\n\";\n      return 1;\n   }\n\n   if (vm.count(\"wgs84\") && vm.count(\"maxlod\"))\n   {\n      int lod = vm[\"maxlod\"].as<int>();\n      if (lod < 0 || lod>23)\n      {\n         std::cout << \"ERROR: lod value in wrong range\\n\";\n         return 1;\n      }\n\n      double lng0, lat0, lng1, lat1;\n\n      std::vector<double> vecCoords= vm[\"wgs84\"].as< std::vector<double> >();\n      if (vecCoords.size() != 4)\n      {\n         std::cout << \"ERROR: wrong number of wgs84 coordinates\\n\";\n         return 1;\n      }\n      \n      lng0 = vecCoords[0];\n      lat0 = vecCoords[1];\n      lng1 = vecCoords[2];\n      lat1 = vecCoords[3];\n      \n      if (lng0 >= lng1) { std::cout << \"error: lng1 must be greater than lng0\\n\"; return 0; }\n      if (lat0 >= lat1) { std::cout << \"error: lat1 must be greater than lat0\\n\"; return 0; }\n      if (lod < 4) { std::cout << \"error: level of detail must be atleast 4\\n\"; return 0; }\n\n\n      _calcfromwgs84(lod, lng0, lat0, lng1, lat1);\n\n      return 0;\n   }\n   else if (vm.count(\"srs\") && vm.count(\"input\"))\n   {\n      std::vector<std::string> vecFiles = vm[\"input\"].as< std::vector<std::string> >();\n      std::string srs = vm[\"srs\"].as<std::string>();\n\n      return _frominput(vecFiles, srs, bVerbose, bPointCloud);\n   }\n   else if (vm.count(\"srs\") && vm.count(\"inputdir\") && vm.count(\"filetype\"))\n   {\n      std::string srs = vm[\"srs\"].as<std::string>();\n      std::string inputdir = vm[\"inputdir\"].as<std::string>();\n      std::string filetype = vm[\"filetype\"].as<std::string>();\n\n      std::vector<std::string> vecFiles = FileSystem::GetFilesInDirectory(inputdir, filetype);\n\n      if (vecFiles.size() == 0)\n      {\n         std::cout << \"No files found!\\n\";\n         return 1;\n      }\n\n      return _frominput(vecFiles, srs, bVerbose, bPointCloud);\n   }\n   else\n   {\n      std::cout << desc << \"\\n\";\n      std::cout << \"From input files: use --srs and --input together\\n\";\n      std::cout << \"From wgs84 coord: use --wgs84 and --maxlod together\\n\";\n      return 1;\n   }\n\n   return 0;\n}\n\n//------------------------------------------------------------------------------\n\n//------------------------------------------------------------------------------\n\nint _frominput(const std::vector<std::string>& vecFiles, const std::string& srs, bool bVerbose, bool bPointCloud)\n{\n\n   if (StringUtils::Left(srs, 5) != \"EPSG:\")\n   {\n      std::cout << \"Error: only srs starting with EPSG: are currently supported\";\n      return 1;\n   }\n\n   int epsg = atoi(srs.c_str()+5);\n   std::cout << \"SRS epsg-code: \" << epsg << \"\\n\";\n\n   if (!ProcessingUtils::init_gdal())\n   {\n      std::cout << \"Warning: gdal-data directory not found. Ouput may be wrong!\\n\";\n   }   \n\n   boost::shared_ptr<CoordinateTransformation> qCT;\n   \n   if (bPointCloud)\n   {\n      qCT = boost::shared_ptr<CoordinateTransformation>(new CoordinateTransformation(epsg, 4326));\n      clock_t t0,t1;\n      t0 = clock();\n\n      // vecfiles contains xyz (or xyzi or xyzirgb) ASCII files.\n      // a) find the center of the dataset\n      // b) find extent (max,min of x,y and z component)\n\n      double xmin, ymin, zmin;\n      double xmax, ymax, zmax;\n      double xcenter, ycenter, zcenter;\n\n      xmin=ymin=zmin=1e20;\n      xmax=ymax=zmax=-1e20;\n\n      size_t numpts = 0;\n\n      CloudPoint pt;\n      for (size_t i = 0; i< vecFiles.size();++i)\n      {\n         PointCloudReader pr;\n\n         if (pr.Open(vecFiles[i]))\n         {\n            while (pr.ReadPoint(pt))\n            {\n               qCT->Transform(&pt.x, &pt.y);\n               xmin = math::Min<double>(xmin, pt.x);\n               ymin = math::Min<double>(ymin, pt.y);\n               zmin = math::Min<double>(zmin, pt.elevation);\n               xmax = math::Max<double>(xmax, pt.x);\n               ymax = math::Max<double>(ymax, pt.y);\n               zmax = math::Max<double>(zmax, pt.elevation);\n\n               numpts++;\n            }\n         }\n      }\n\n      xcenter = xmin+ fabs(0.5*(xmax-xmin));\n      ycenter = ymin+fabs(0.5*(ymax-ymin));\n      zcenter = zmin+fabs(0.5*(zmax-zmin));\n\n      std::cout.precision(15);\n  \n      for (int i=1;i<23;i++)\n      {\n         std::cout << \"LEVEL OF DETAIL \" << i << \": \";\n         _calcfromwgs84(i, xmin, ymin, xmax, ymax);\n      }\n\n      t1 = clock();\n      std::cout << \"calculated in: \" << double(t1-t0)/double(CLOCKS_PER_SEC) << \" s \\n\";\n\n      std::cout << \"There are \" << numpts << \" points...\\n\";\n      //std::cout << \"Point Cloud Center (WGS84): (\" << xcenter << \", \" << ycenter << \", \" << zcenter <<\")\\n\";\n      std::cout << \"Required for ogCreateLayer:\\n\";\n      std::cout << \"-------------------------------------------------------------------------------\\n\";\n      std::cout << \"Extent (WGS84): (\" << xmin << \", \" << ymin << \", \" << zmin << \")-(\" << xmax << \", \" << ymax << \", \" << zmax << \")\\n\";\n      std::cout << \"-------------------------------------------------------------------------------\\n\";\n\n      return 0;\n   }\n   else\n   {\n\n      qCT = boost::shared_ptr<CoordinateTransformation>(new CoordinateTransformation(epsg, 3785));\n\n      // create an array of Dataset info for parallel access.\n      DataSetInfo* pDataset = new DataSetInfo[vecFiles.size()];\n\n  \n      clock_t t0,t1;\n      t0 = clock();\n\n      for (int i=0;i<(int)vecFiles.size();i++)\n      {\n         ProcessingUtils::RetrieveDatasetInfo(vecFiles[i], qCT.get(), &pDataset[i], bVerbose);\n      }\n\n      // at this point we finished calculating all the boundaries of all datasets, now\n      // calculate the min/max\n\n      double total_dest_ulx = 1e20;\n      double total_dest_lry = 1e20;\n      double total_dest_lrx = -1e20;\n      double total_dest_uly = -1e20;\n      double pixelsize = 1e20;\n\n      for (size_t i=0;i<vecFiles.size();i++)\n      {\n         if (pDataset[i].bGood)\n         {\n            total_dest_ulx = math::Min<double>(pDataset[i].dest_ulx, total_dest_ulx);\n            total_dest_lry = math::Min<double>(pDataset[i].dest_lry, total_dest_lry);\n            total_dest_lrx = math::Max<double>(pDataset[i].dest_lrx, total_dest_lrx);\n            total_dest_uly = math::Max<double>(pDataset[i].dest_uly, total_dest_uly);\n            pixelsize      = math::Min<double>(pDataset[i].pixelsize, pixelsize);\n         }\n      }\n\n      double pixelsize_m = pixelsize * 6378137.0;\n\n      t1 = clock();\n\n      std::cout << \"GATHERED BOUNDARY (Mercator):\\n\";\n      std::cout.precision(16);\n      std::cout << \"        ulx: \" << total_dest_ulx << \"\\n\";\n      std::cout << \"        lry: \" << total_dest_lry << \"\\n\";\n      std::cout << \"        lrx: \" << total_dest_lrx << \"\\n\";\n      std::cout << \"        uly: \" << total_dest_uly << \"\\n\";\n      std::cout << \"BOUNDARY in WGS84:\\n\";\n\n\n      MercatorQuadtree* pQuadtree = new MercatorQuadtree();\n      double x,y;\n      \n\n      double lng0, lat0, lng1, lat1;\n      x = total_dest_ulx; y = total_dest_lry;\n      pQuadtree->MercatorToWGS84(x, y); \n      lng0 = x; lat0 = y;\n      std::cout << \"       lng0: \" << x << \"\\n\";  \n      std::cout << \"       lat0: \" << y << \"\\n\";\n      x = total_dest_lrx; y = total_dest_uly;\n      pQuadtree->MercatorToWGS84(x, y);\n      lng1 = x; lat1 = y;\n      std::cout << \"       lng1: \" << x << \"\\n\";\n      std::cout << \"       lat1: \" << y << \"\\n\";\n      std::cout << \" pixelsize: \" << pixelsize_m << \" m\\n\";\n\n      double lat_avg = 0.5*(lat1 - lat0);\n\n      double resolution_elevation[21];\n      double resolution_image[21];\n\n\n      for (int lod = 0; lod<21;lod++)\n      {\n         double v = cos(lat_avg*3.14159265358979/180)*2*3.14159265358979*6378137.0/pow(2.0,lod);\n         resolution_elevation[lod] = v / 22.0; // ~500 points per tile\n         resolution_image[lod] = v / 256;\n      }\n\n      int recommended_lod_elv = 0;\n      int recommended_lod_img = 0;\n      for (int lod = 0; lod<20;lod++)\n      {\n         if (pixelsize_m < resolution_elevation[lod] && pixelsize_m > resolution_elevation[lod+1])\n         {  \n            recommended_lod_elv = lod;\n         }\n         if (pixelsize_m < resolution_image[lod] && pixelsize_m > resolution_image[lod+1])\n         {  \n            recommended_lod_img = lod;\n         }\n      }\n\n      for (int i=1;i<23;i++)\n      {\n         std::cout << \"LEVEL OF DETAIL \" << i << \": \";\n         _calcfromwgs84(i, lng0, lat0, lng1, lat1);\n      }\n\n\n      std::cout << \"****************************************\\n\";\n      std::cout << \"RECOMMENDATION (MINIMUM LOD):\\n\";\n      if (recommended_lod_elv != 0)\n      {\n         std::cout << \"IF THIS IS ELEVATION: LOD=\" << recommended_lod_elv << \": \";\n         _calcfromwgs84(recommended_lod_elv, lng0, lat0, lng1, lat1);\n      }\n      if (recommended_lod_img != 0)\n      {\n         std::cout << \"\\nIF THIS IS IMAGE: LOD=\" << recommended_lod_img << \": \";\n         _calcfromwgs84(recommended_lod_img, lng0, lat0, lng1, lat1);\n      }\n      if (recommended_lod_img == 0 && recommended_lod_elv==0)\n      {\n         std::cout << \"recommendation is not possible.\\n\";\n      }\n      std::cout << \"****************************************\\n\";\n\n      delete pQuadtree;\n\n      //std::cout << \"calculated in: \" << double(t1-t0)/double(CLOCKS_PER_SEC) << \" s \\n\";\n\n      delete[] pDataset;\n\n      ProcessingUtils::exit_gdal();\n\n      return 0;\n   }\n}\n\n//------------------------------------------------------------------------------\n\nvoid _calcfromwgs84(int lod, double lng0, double lat0, double lng1, double lat1)\n{\n   MercatorQuadtree* pQuadtree = new MercatorQuadtree();\n   \n   int64 px0, py0, px1, py1, tx0, ty0, tx1, ty1;\n   pQuadtree->WGS84ToPixel(lng0, lat0, lod, px0, py1);\n   pQuadtree->WGS84ToPixel(lng1, lat1, lod, px1, py0);\n   \n   //std::cout << \"Number of pixels in specified range: \" << (px1-px0+1)*(py1-py0+1) << \"\\n\";\n   \n   pQuadtree->PixelToTileCoord(px0, py0, tx0, ty0);\n   pQuadtree->PixelToTileCoord(px1, py1, tx1, ty1);\n   \n   std::cout << \"Tile Coords: (\" << tx0 << \", \" << ty0 << \")-(\" << tx1 << \", \" << ty1 << \")\\n\";\n   \n   delete pQuadtree;\n\n}", "meta": {"hexsha": "cf2632870812f537ae732d488054f90f8dc6b6b6", "size": 13255, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/apps/calcextent/main.cpp", "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": "source/apps/calcextent/main.cpp", "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": "source/apps/calcextent/main.cpp", "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": 33.727735369, "max_line_length": 137, "alphanum_fraction": 0.4921161826, "num_tokens": 3640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2512970110535084}}
{"text": "/**\n * Copyright (c) 2017 Melown Technologies SE\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * *  Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n *\n * *  Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n#include <vector>\n#include <map>\n\n#include <boost/multi_index_container.hpp>\n#include <boost/multi_index/ordered_index.hpp>\n#include <boost/multi_index/member.hpp>\n\n#include \"dbglog/dbglog.hpp\"\n\n#include \"utility/expect.hpp\"\n\n#include \"../meshop.hpp\"\n\nnamespace vtslibs { namespace vts {\n\nnamespace {\n\nnamespace bmi = boost::multi_index;\n\ntemplate <typename PointType>\nstruct Segment_ {\n    const PointType &p1;\n    const PointType &p2;\n\n    PointType point(double t) const {\n        return ((1.0 - t) * p1) + (t * p2);\n    }\n\n    Segment_(const PointType &p1, const PointType &p2) : p1(p1), p2(p2) {}\n};\n\ntypedef Segment_<math::Point2d> Segment2;\ntypedef Segment_<math::Point3d> Segment3;\n\n/** Plane defined as dot(p, normal) + c = 0\n */\nstruct ClipPlane {\n    math::Point3d normal;\n    double d;\n\n    ClipPlane(double a, double b, double c, double d)\n        : normal(a, b, c), d(d) {}\n    ClipPlane() : d() {}\n\n    double signedDistance(const math::Point3d &p) const {\n        return boost::numeric::ublas::inner_prod(p, normal) + d;\n    }\n\n    double intersect(const math::Point3d &p1, const math::Point3d &p2) const {\n        double dot1(boost::numeric::ublas::inner_prod(p1, normal));\n        double dot2(boost::numeric::ublas::inner_prod(p2, normal));\n        double den(dot1 - dot2);\n\n        // line parallel with plane, return the midpoint\n        if (std::abs(den) < 1e-10) {\n            return 0.5;\n        }\n        return (dot1 + d) / den;\n    }\n\n    double intersect(const Segment3 &segment) const {\n        return intersect(segment.p1, segment.p2);\n    }\n\n    typedef std::pair<const ClipPlane*, const ClipPlane*> const_range;\n};\n\ntemplate <std::size_t N>\nClipPlane::const_range const_range(const ClipPlane (&planes)[N])\n{\n    return ClipPlane::const_range(std::begin(planes), std::end(planes));\n}\n\nconst ClipPlane* begin(const ClipPlane::const_range &cr) { return cr.first; }\nconst ClipPlane* end(const ClipPlane::const_range &cr) { return cr.second; }\n\ntemplate<typename CharT, typename Traits>\ninline std::basic_ostream<CharT, Traits>&\noperator<<(std::basic_ostream<CharT, Traits> &os, const ClipPlane &cl)\n{\n    return os << \"ClipPlane(\" << cl.normal << \", \" << cl.d << \")\";\n}\n\ntemplate<typename CharT, typename Traits, typename PointType>\ninline std::basic_ostream<CharT, Traits>&\noperator<<(std::basic_ostream<CharT, Traits> &os, const Segment_<PointType> &s)\n{\n    return os << \"Segment(\" << s.p1 << \" -> \" << s.p2 << \")\";\n}\n\ntypedef boost::optional<Face> OFace;\n\nstruct ClipFace {\n    Face face;\n    OFace faceTc;\n    unsigned int origin;\n\n    typedef std::vector<ClipFace> list;\n\n    ClipFace() : origin() {}\n    ClipFace(const ClipFace&) = default;\n    ClipFace(const Face &face, unsigned int origin = 0)\n        : face(face), origin(origin) {}\n    ClipFace(Face::value_type a, Face::value_type b, Face::value_type c\n             , unsigned int origin = 0)\n        : face(a, b, c), origin(origin)\n    {}\n};\n\n/** Maps point coordinates into list of points (one point is held only once)\n *  generated\n */\ntemplate <typename PointType>\nclass PointMapper {\npublic:\n    template <typename Container>\n    PointMapper(const Container &container)\n        : points_(container.begin(), container.end())\n    {}\n\n    std::size_t add(const PointType &point)\n    {\n        auto res(mapping_.insert\n                 (typename Mapping::value_type\n                  (point, points_.size())));\n        if (res.second) {\n            // new point -> insert\n            points_.push_back(point);\n        }\n        return res.first->second;\n    }\n\n    const std::vector<PointType>& points() const { return points_; }\n\n    double distance(int v1, int v2) const {\n        return boost::numeric::ublas::norm_2(points_[v1] - points_[v2]);\n    }\n\nprivate:\n    typedef std::map<PointType, std::size_t> Mapping;\n    std::vector<PointType> points_;\n    Mapping mapping_;\n};\n\nclass Clipper {\npublic:\n    Clipper(const EnhancedSubMesh &mesh, const VertexMask &mask)\n        : mesh_(mesh.mesh), fpmap_(mesh.projected), ftpmap_(mesh_.tc)\n    {\n        extractFaces();\n        // TODO: apply mask\n        (void) mask;\n    }\n\n    Clipper(const SubMesh &mesh, const VertexMask &mask)\n        : mesh_(mesh), fpmap_(mesh.vertices), ftpmap_(mesh_.tc)\n    {\n        extractFaces();\n        // TODO: apply mask\n        (void) mask;\n    }\n\n    Clipper(const SubMesh &mesh, const math::Points3d &projected\n            , const VertexMask &mask)\n        : mesh_(mesh), fpmap_(projected), ftpmap_(mesh_.tc)\n    {\n        extractFaces();\n        // TODO: apply mask\n        (void) mask;\n    }\n\n    void refine(std::size_t faceCount);\n\n    void clip(const ClipPlane &line);\n\n    EnhancedSubMesh mesh(const MeshVertexConvertor *convertor = nullptr\n                         , FaceOriginList * = nullptr);\n\n    std::size_t faceCount() const { return faces_.size(); }\n\nprivate:\n    void extractFaces() {\n        bool hasTc(!mesh_.facesTc.empty());\n        for (std::size_t i(0), e(mesh_.faces.size()); i != e; ++i) {\n            faces_.emplace_back(mesh_.faces[i], i);\n            if (hasTc) { faces_.back().faceTc = mesh_.facesTc[i]; }\n        }\n    }\n\n    const SubMesh &mesh_;\n\n    ClipFace::list faces_;\n\n    // face points map\n    PointMapper<math::Point3d> fpmap_;\n\n    // face texture points map\n    PointMapper<math::Point2d> ftpmap_;\n};\n\n/** Use to uniformly map face vertices to fixed names.\n */\nstruct VMap {\n    int a, b, c;\n\n    template <typename Check>\n    VMap(const bool (&inside)[3], Check check) {\n        if (check(inside[0])) { a = 0; b = 1; c = 2; }\n        else if (check(inside[1])) { a = 1; b = 2; c = 0; }\n        else { a = 2; b = 0; c = 1; }\n    }\n};\n\nvoid Clipper::clip(const ClipPlane &line)\n{\n    // LOG(debug) << \"clip: \" << line;\n    ClipFace::list out;\n\n    const auto &vertices(fpmap_.points());\n    const auto &tc(ftpmap_.points());\n\n    for (const auto cf : faces_) {\n        const math::Point3d tri[3] = {\n            vertices[cf.face[0]]\n            , vertices[cf.face[1]]\n            , vertices[cf.face[2]]\n        };\n\n        const bool inside[3] = {\n            (line.signedDistance(tri[0]) >= .0)\n            , (line.signedDistance(tri[1]) >= .0)\n            , (line.signedDistance(tri[2]) >= .0)\n        };\n\n        // LOG(debug) << std::fixed << \"cutting face \" << tri << \":\"\n        //            << \"\\n    \" << tri[0] << \", \" << inside[0]\n        //            << \"\\n    \" << tri[1] << \", \" << inside[1]\n        //            << \"\\n    \" << tri[2] << \", \" << inside[2];\n\n        int count(inside[0] + inside[1] + inside[2]);\n        if (!count) {\n            // LOG(debug) << \"    -> fully outside\";\n            // whole face is outside\n            continue;\n        }\n\n        if (count == 3) {\n            // whole face is inside\n            // LOG(debug) << \"    -> fully inside\";\n            out.push_back(cf);\n            continue;\n        }\n\n        // oneInside: true: one inside, false: one outside\n        bool oneInside(count == 1);\n\n        VMap vm(inside, (oneInside ? ([](bool i) { return i; })\n                         : ([](bool i) { return !i; })));\n\n        double t1, t2;\n\n        /* mesh face */ {\n            Segment3 s1(tri[vm.a], tri[vm.b]);\n            Segment3 s2(tri[vm.c], tri[vm.a]);\n\n            // intersect segments with both lines\n            t1 = line.intersect(s1);\n            t2 = line.intersect(s2);\n\n            // calculate new point\n            auto p1(s1.point(t1));\n            auto p2(s2.point(t2));\n\n            // LOG(debug) << \"    \" << s1 << \" -> \" << t1 << \" -> \" << p1;\n            // LOG(debug) << \"    \" << s2 << \" -> \" << t2 << \" -> \" << p2;\n\n            // and new (projected) vertices\n            auto vi1(fpmap_.add(p1));\n            auto vi2(fpmap_.add(p2));\n\n            if (oneInside) {\n                // one vertex inside: just one face:\n                out.emplace_back(cf.face[vm.a], vi1, vi2, cf.origin);\n\n                // LOG(debug)\n                //     << std::fixed\n                //     << \"    -> one vertex inside, new face:\"\n                //     << \"\\n    \" << tri[vm.a]\n                //     << \"\\n    \" << p1\n                //     << \"\\n    \" << p2;\n\n            } else {\n                // one vertex outside: two new faces\n                out.emplace_back(vi1, cf.face[vm.b], cf.face[vm.c]\n                                 , cf.origin);\n                out.emplace_back(vi1, cf.face[vm.c], vi2, cf.origin);\n\n                // LOG(debug)\n                //     << std::fixed\n                //     << \"\\n    -> one vertex outside, new faces:\"\n                //     << \"\\n    \" << p1\n                //     << \"\\n    \" << tri[vm.b]\n                //     << \"\\n    \" << tri[vm.c]\n                //     << \"\\n    \" << p1\n                //     << \"\\n    \" << tri[vm.c]\n                //     << \"\\n    \" << p2;\n            }\n        }\n\n        if (cf.faceTc) {\n            // texture face\n            auto face(*cf.faceTc);\n\n            // LOG(debug) << \"cutting texture face \" << face << \":\";\n            // LOG(debug)\n            //     << std::fixed << \"    \" << tc[face[0]] << \", \" << inside[0];\n            // LOG(debug)\n            //     << std::fixed << \"    \" << tc[face[1]] << \", \" << inside[1];\n            // LOG(debug)\n            //     << std::fixed << \"    \" << tc[face[2]] << \", \" << inside[2];\n\n            // calculate new point\n            auto tp1(Segment2(tc[face[vm.a]], tc[face[vm.b]]).point(t1));\n            auto tp2(Segment2(tc[face[vm.c]], tc[face[vm.a]]).point(t2));\n\n            auto ti1(ftpmap_.add(tp1));\n            auto ti2(ftpmap_.add(tp2));\n\n            if (oneInside) {\n                // one vertex inside: just one face:\n                out.back().faceTc = Face(face[vm.a], ti1, ti2);\n\n                // LOG(debug)\n                //     << std::fixed\n                //     << \"    -> one vertex inside, new face \"\n                //     << *out.back().faceTc << \":\"\n                //     << \"\\n    \" << tc[face[vm.a]]\n                //     << \"\\n    \" << tp1\n                //     << \"\\n    \" << tp2;\n            } else {\n                // one vertex outside: two new faces\n                out[out.size() - 2].faceTc = Face(ti1, face[vm.b], face[vm.c]);\n                out[out.size() - 1].faceTc = Face(ti1, face[vm.c], ti2);\n\n                // LOG(debug)\n                //     << std::fixed\n                //     << \"    -> one vertex outside, new faces \"\n                //     << *out[out.size() - 2].faceTc << \", \"\n                //     << *out[out.size() - 1].faceTc << \":\"\n                //     << \"\\n    \" << tp1\n                //     << \"\\n    \" << tc[face[vm.b]]\n                //     << \"\\n    \" << tc[face[vm.c]]\n                //     << \"\\n    \" << tp1\n                //     << \"\\n    \" << tc[face[vm.c]]\n                //     << \"\\n    \" << tp2;\n            }\n        }\n    }\n\n    out.swap(faces_);\n}\n\nvoid Clipper::refine(std::size_t faceCount)\n{\n    if (faceCount <= faces_.size()) { return; }\n    LOG(info2) << \"Refining \" << faces_.size() << \" faces to \" << faceCount\n               << \" faces.\";\n\n#if 0\n    typedef PointMapper<math::Point3d> Vertices;\n#endif\n\n    /** Edge key, keys is held automatically sorted.\n     */\n    struct EdgeKey {\n        int v1;\n        int v2;\n\n        EdgeKey(int v1, int v2)\n            : v1(std::min(v1, v2))\n            , v2(std::max(v1, v2))\n        {}\n\n        bool operator<(const EdgeKey &o) const {\n            if (v1 < o.v1) {\n                return true;\n            } else if (o.v1 < v1) {\n                return false;\n            }\n            return v2 < o.v2;\n        }\n    };\n\n    struct EdgeFace {\n        int face;\n        int i1;\n\n        EdgeFace(int face, int i1) : face(face), i1(i1) {}\n\n        typedef std::vector<EdgeFace> list;\n    };\n\n    struct Edge {\n        EdgeKey key;\n        double length;\n        EdgeFace::list faces;\n\n        Edge() = default;\n\n        Edge(const EdgeKey &key, double length)\n            : key(key), length(length)\n        {}\n\n        std::tuple<Edge, Edge> split(int vh) const {\n            return std::tuple<Edge, Edge>\n                (Edge(EdgeKey(key.v1, vh), length / 2.0)\n                 , Edge(EdgeKey(vh, key.v2), length / 2.0));\n        }\n\n        bool operator<(const Edge &o) const {\n            return key < o.key;\n        }\n\n        bool has(int v) const {\n            return (key.v1 == v) || (key.v2 == v);\n        }\n    };\n\n    struct KeyIdx {};\n    struct LengthIdx {};\n    typedef boost::multi_index_container<\n        Edge\n        , bmi::indexed_by<\n              bmi::ordered_unique<\n                    bmi::tag<KeyIdx>\n                    , BOOST_MULTI_INDEX_MEMBER(Edge, EdgeKey, key)\n                  >\n\n              , bmi::ordered_non_unique<\n                    bmi::tag<LengthIdx>\n                    , BOOST_MULTI_INDEX_MEMBER(Edge, double, length)\n                    , std::greater<double>\n                    >\n              >\n\n        > Edges;\n\n    ClipFace::list &faces(faces_);\n    Edges edges;\n\n    auto addEdge([&](const EdgeKey &key, int findex, int i1\n                     , int oldFindex)\n    {\n        auto fedges(edges.find(key));\n        if (fedges == edges.end()) {\n            // adding new edge\n            fedges = edges.insert\n                (Edge(key, fpmap_.distance(key.v1, key.v2))).first;\n            const_cast<EdgeFace::list&>\n                (fedges->faces).emplace_back(findex, i1);\n            return;\n        }\n\n        // updating existing edge\n        auto &faces(const_cast<EdgeFace::list&>(fedges->faces));\n        if (oldFindex >= 0) {\n            auto ffaces(std::find_if(faces.begin(), faces.end()\n                                     , [&](const EdgeFace &ef)\n            {\n                return (ef.face == oldFindex);\n            }));\n\n            if (ffaces != faces.end()) {\n                // LOG(debug) << \"    replacing face (\" << ffaces->face\n                //            << \", \" << ffaces->i1\n                //            << \") with face (\" << findex << \", \" << i1\n                //            << \")\";\n                // found -> replace\n                ffaces->face = findex;\n                ffaces->i1 = i1;\n                return;\n            }\n\n            // not found -> fall through\n        }\n\n        // not found or not replacing -> add\n        faces.emplace_back(findex, i1);\n    });\n\n    {\n        std::size_t findex(0);\n\n        for (const auto &cf : faces) {\n            const auto &face(cf.face);\n\n            auto addEdgeFrom([&](int i1)\n            {\n                addEdge(EdgeKey(face[i1], face[(i1 + 1) % 3])\n                        , findex, i1, -1);\n            });\n\n            addEdgeFrom(0);\n            addEdgeFrom(1);\n            addEdgeFrom(2);\n            ++findex;\n        }\n    }\n\n    const auto &tc(ftpmap_.points());\n    const auto &vertices(fpmap_.points());\n\n    auto &idx(edges.get<LengthIdx>());\n    while (faces.size() < faceCount) {\n        auto iedges(idx.begin());\n\n        const auto &edge(*iedges);\n\n        // split edge in half and remember index\n        auto vh(fpmap_.add\n                ((vertices[edge.key.v1] + vertices[edge.key.v2]) / 2.0));\n\n        // generate half edges\n        auto halves(edge.split(vh));\n        auto &e1(std::get<0>(halves));\n        auto &e2(std::get<1>(halves));\n\n        // LOG(debug) << \"Splitting (\" << edge.key.v1 << \", \" << edge.key.v2\n        //            << \") into (\" << e1.key.v1 << \", \" << e1.key.v2\n        //            << \") and (\" <<  e2.key.v1 << \", \" << e2.key.v2 << \").\";\n\n        for (const auto &ef : edge.faces) {\n            // get old and new face index\n            int fi1(ef.face);\n            int fi2(faces.size());\n\n            // clone face to second face\n            faces.push_back(faces[fi1]);\n\n            // get reference to first face\n            Face &face1(faces[fi1].face);\n            // get reference to new (second) face\n            Face &face2(faces.back().face);\n\n            int i1(ef.i1);\n            int i2((ef.i1 + 1) % 3);\n            int i3((ef.i1 + 2) % 3);\n\n            // LOG(debug) << \"    before split: \" << face1 << \", \" << face2\n            //            << \" (\" << i1 << \")\";\n            // replace end edge vertices with half-way vertex\n            face1(i2) = vh;\n            face2(i1) = vh;\n            // LOG(debug) << \"    after split: \" << face1 << \", \" << face2;\n\n            // add new faces to half-edges (since edge is oriented from lower to\n            // higher index we have to check which way the edge is)\n            if (e1.has(face1[i1])) {\n                e1.faces.emplace_back(fi1, i1);\n                e2.faces.emplace_back(fi2, i1);\n            } else {\n                e1.faces.emplace_back(fi2, i1);\n                e2.faces.emplace_back(fi1, i1);\n            }\n\n            auto v2(face2(i2));\n            auto v3(face2(i3));\n\n            // create 3rd new edge that is shared between two new triangles\n            {\n                EdgeKey e3key(vh, v3);\n                Edge e3(e3key, fpmap_.distance(e3key.v1, e3key.v2));\n                // LOG(debug) << \"    added edge (\"\n                           // << e3key.v1 << \", \" << e3key.v2 << \")\";\n                e3.faces.emplace_back(fi1, i2);\n                e3.faces.emplace_back(fi2, i3);\n                edges.insert(e3);\n            }\n\n            // replace fi1 with fi2 in edge(i2, i3)\n            // LOG(debug) << \"    remapping edge (\"\n            //            << v2 << \", \" << v3 << \") from \" << fi1\n            //            << \" to \" << fi2;\n            addEdge(EdgeKey(v2, v3), fi2, i2, fi1);\n\n            if (!tc.empty()) {\n                // split texturing face as well\n                Face &tf1(*faces[fi1].faceTc);\n                Face &tf2(*faces[fi2].faceTc);\n\n                // split edge\n                auto th(ftpmap_.add((tc[tf1(i1)] + tc[tf1(i2)]) / 2.0));\n\n                // assign\n                tf1(i2) = th;\n                tf2(i1) = th;\n            }\n        }\n\n        // add new edges\n        edges.insert(e1);\n        edges.insert(e2);\n\n        // and finally remove original edge\n        idx.erase(iedges);\n    }\n}\n\nEnhancedSubMesh Clipper::mesh(const MeshVertexConvertor *convertor\n                              , FaceOriginList *faceOrigin)\n{\n    /** Generate new mesh.\n     */\n    struct Filter {\n        const SubMesh &original;\n        const ClipFace::list &faces;\n        const math::Points3d &vertices;\n        const math::Points3d &projected;\n        const math::Points2d &tc;\n        const MeshVertexConvertor *convertor;\n        FaceOriginList *faceOrigin;\n\n        std::vector<int> vertexMap;\n        std::vector<int> tcMap;\n\n        EnhancedSubMesh emesh;\n        SubMesh &mesh;\n\n        Filter(const SubMesh &original, const ClipFace::list &faces\n               , const math::Points3d &projected\n               , const math::Points2d &tc\n               , const MeshVertexConvertor *convertor\n               , FaceOriginList *faceOrigin)\n            : original(original), faces(faces), vertices(original.vertices)\n            , projected(projected), tc(tc), convertor(convertor)\n            , faceOrigin(faceOrigin)\n            , vertexMap(projected.size(), -1)\n            , tcMap(tc.size(), -1)\n            , mesh(emesh.mesh)\n        {\n            // clone metadata into output mesh\n            original.cloneMetadataInto(mesh);\n            for (const auto &cf : faces) {\n                addFace(cf);\n            }\n        }\n\n        void addFace(const ClipFace &cf) {\n            mesh.faces.emplace_back(addVertex(cf.face(0))\n                                    , addVertex(cf.face(1))\n                                    , addVertex(cf.face(2)));\n            // LOG(debug) << \"Added tc face: \" << cf.face << \" -> \"\n            //            << mesh.faces.back();\n\n            if (cf.faceTc) {\n                mesh.facesTc.emplace_back(addTc((*cf.faceTc)(0))\n                                          , addTc((*cf.faceTc)(1))\n                                          , addTc((*cf.faceTc)(2)));\n                // LOG(debug) << \"Added tc face: \" << *cf.faceTc << \" -> \"\n                //            << mesh.facesTc.back();\n            }\n\n            if (faceOrigin) { faceOrigin->push_back(cf.origin); }\n        }\n\n        std::size_t addVertex(std::size_t i) {\n            auto &m(vertexMap[i]);\n            if (m < 0) {\n                // new vertex\n                m = mesh.vertices.size();\n\n                const auto newPoint(i >= vertices.size());\n                const auto generateEtc(convertor && !original.etc.empty());\n                const auto &v(projected[i]);\n\n                if (newPoint) {\n                    // must unproject\n                    mesh.vertices.push_back(convertor\n                                            ? convertor->vertex(v)\n                                            : v);\n\n                    // etc\n                    if (generateEtc) {\n                        mesh.etc.push_back(convertor->etc(v));\n                        // LOG(debug) << v << \": etc from vertex: \" << v << \" -> \"\n                        //            << mesh.etc.back();\n                    }\n                } else {\n                    // use original\n                    mesh.vertices.push_back(vertices[i]);\n\n                    if (generateEtc) {\n                        mesh.etc.push_back(convertor->etc(original.etc[i]));\n                        // LOG(debug) << v << \": etc from old: \"\n                        //            << original.etc[i]\n                        //            << \" -> \" << mesh.etc.back();\n                    }\n                }\n\n                // remember projected vertex\n                emesh.projected.push_back(v);\n            }\n            return m;\n        }\n\n        int addTc(int i) {\n            auto &m(tcMap[i]);\n            if (m < 0) {\n                // new vertex\n                m = mesh.tc.size();\n                mesh.tc.push_back(tc[i]);\n            }\n            return m;\n        }\n    };\n\n    // run the machinery\n    return Filter(mesh_, faces_, fpmap_.points()\n                  , ftpmap_.points()\n                  , convertor, faceOrigin).emesh;\n}\n\n} // namespace\n\nEnhancedSubMesh clipAndRefine(const EnhancedSubMesh &mesh\n                              , const math::Extents2 &projectedExtents\n                              , const MeshVertexConvertor &convertor\n                              , const VertexMask &mask)\n{\n    LOG(debug) << std::fixed << \"Clipping mesh to: \" << projectedExtents;\n    const ClipPlane clipPlanes[4] = {\n        { 1.,  .0, .0, -projectedExtents.ll(0) }\n        , { -1., .0, .0, projectedExtents.ur(0) }\n        , { .0,  1., .0, -projectedExtents.ll(1) }\n        , { 0., -1., .0, projectedExtents.ur(1) }\n    };\n\n    Clipper clipper(mesh, mask);\n\n    // clip by clipping planes\n    for (const auto &cp : clipPlanes) { clipper.clip(cp); }\n\n    // refine clipped mesh to requested number of faces\n    clipper.refine(convertor.refineToFaceCount(clipper.faceCount()));\n\n    return clipper.mesh(&convertor);\n}\n\nSubMesh clip(const SubMesh &mesh, const math::Points3d &projected\n             , const ClipPlane::const_range &clipPlanes\n             , const VertexMask &mask, FaceOriginList *faceOrigin)\n{\n    Clipper clipper(mesh, projected, mask);\n\n    for (const auto &cp : clipPlanes) { clipper.clip(cp); }\n\n    // extract enhanced mesh from clipper (use no convertor)\n    auto emesh(clipper.mesh(nullptr, faceOrigin));\n    (void) faceOrigin;\n    // swap vertices with projected vertices (we are working in local system\n    emesh.mesh.vertices.swap(emesh.projected);\n\n    // get output mesh\n    const auto &out(emesh.mesh);\n\n    LOG(debug) << \"Mesh clipped: vertices=\"\n               << projected.size() << \"->\" << out.vertices.size()\n               << \", tc=\" << mesh.tc.size() << \"->\" << out.tc.size()\n               << \", etc=\" << mesh.etc.size()\n               << \"->\" << out.etc.size()\n               << \", faces=\" << mesh.faces.size()\n               << \"->\" << out.faces.size()\n               << \", facesTc=\" << mesh.facesTc.size()\n               << \"->\" << out.facesTc.size()\n               << \".\";\n\n    // and return\n    return out;\n}\n\nSubMesh clip(const SubMesh &mesh, const math::Points3d &projected\n             , const math::Extents2 &projectedExtents\n             , const VertexMask &mask, FaceOriginList *faceOrigin)\n{\n    LOG(debug) << std::fixed << \"Clipping mesh to: \" << projectedExtents;\n    const ClipPlane clipPlanes[4] = {\n        { 1.,  .0, .0, -projectedExtents.ll(0) }\n        , { -1., .0, .0, projectedExtents.ur(0) }\n        , { .0,  1., .0, -projectedExtents.ll(1) }\n        , { 0., -1., .0, projectedExtents.ur(1) }\n    };\n    return clip(mesh, projected, const_range(clipPlanes), mask, faceOrigin);\n}\n\nSubMesh clip(const SubMesh &mesh, const math::Points3d &projected\n             , const math::Extent &projectedVerticalExtent\n             , const VertexMask &mask, FaceOriginList *faceOrigin)\n{\n    LOG(debug)\n        << std::fixed << \"Clipping mesh to: \" << projectedVerticalExtent;\n    const ClipPlane clipPlanes[4] = {\n        { 0.,  .0, 1., -projectedVerticalExtent.l }\n        , { 0.,  .0, -1., projectedVerticalExtent.r }\n    };\n    return clip(mesh, projected, const_range(clipPlanes), mask, faceOrigin);\n}\n\nEnhancedSubMesh clip(const SubMesh &mesh, const math::Points3d &projected\n                     , const math::Extents2 &projectedExtents\n                     , const MeshVertexConvertor &convertor\n                     , const VertexMask &mask\n                     , FaceOriginList *faceOrigin)\n{\n    LOG(debug) << std::fixed << \"Clipping mesh to: \" << projectedExtents;\n    const ClipPlane clipPlanes[4] = {\n        { 1.,  .0, .0, -projectedExtents.ll(0) }\n        , { -1., .0, .0, projectedExtents.ur(0) }\n        , { .0,  1., .0, -projectedExtents.ll(1) }\n        , { 0., -1., .0, projectedExtents.ur(1) }\n    };\n\n    Clipper clipper(mesh, projected, mask);\n\n    for (const auto &cp : clipPlanes) { clipper.clip(cp); }\n\n    return clipper.mesh(&convertor, faceOrigin);\n}\n\nnamespace {\n\ntemplate <typename Container>\nconst Container* nonempty(const Container &c)\n{\n    return c.empty() ? nullptr : &c;\n}\n\n} // namespace\n\n/** Compute enhanced submesh area.\n */\nSubMeshArea area(const EnhancedSubMesh &submesh, const VertexMask &mask)\n{\n    return area(submesh.projected, submesh.mesh.faces\n                , nonempty(submesh.mesh.tc)\n                , nonempty(submesh.mesh.facesTc)\n                , nonempty(submesh.mesh.etc)\n                , &mask);\n}\n\n/** Compute enhanced mesh area.\n */\nMeshArea area(const EnhancedSubMesh::list &mesh, const VertexMasks &masks)\n{\n    utility::expect((mesh.size() == masks.size())\n                    , \"Number of submeshes (%d) different \"\n                    \"from number of masks (%d).\"\n                    , mesh.size(), masks.size());\n\n    MeshArea out;\n    auto imask(masks.begin());\n    for (const auto &sm : mesh) {\n        out.submeshes.push_back(area(sm, *imask++));\n        out.mesh += out.submeshes.back().mesh;\n    }\n    return out;\n}\n\n} } // namespace vtslibs::vts\n", "meta": {"hexsha": "ef85684b420b532f77e3e675064213c7d7f84417", "size": 28429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vts-libs/vts/meshop/refineandclip.cpp", "max_stars_repo_name": "melowntech/vts-libs", "max_stars_repo_head_hexsha": "ffbf889b6603a8f95d3c12a2602232ff9c5d2236", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-04-20T01:44:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T06:54:51.000Z", "max_issues_repo_path": "externals/browser/externals/browser/externals/vts-libs/vts-libs/vts/meshop/refineandclip.cpp", "max_issues_repo_name": "HanochZhu/vts-browser-unity-plugin", "max_issues_repo_head_hexsha": "32a22d41e21b95fb015326f95e401d87756d0374", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-01-29T16:30:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-03T15:21:29.000Z", "max_forks_repo_path": "externals/browser/externals/browser/externals/vts-libs/vts-libs/vts/meshop/refineandclip.cpp", "max_forks_repo_name": "HanochZhu/vts-browser-unity-plugin", "max_forks_repo_head_hexsha": "32a22d41e21b95fb015326f95e401d87756d0374", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-25T05:10:07.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-25T05:10:07.000Z", "avg_line_length": 31.7997762864, "max_line_length": 82, "alphanum_fraction": 0.493404622, "num_tokens": 7188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.2512195523847125}}
{"text": "#pragma warning( disable : 4477 4018 4267 4244 4838)\n#include \"Polycube_Flattening.h\"\n#include \"omp.h\"\n#include \"Sparse_Matrix.h\"\n#include \"Sparse_Solver.h\"\n#include \"ConvexQuadOptimization.h\"\n#include \"cholmod.h\"\n#include \"SmallMat.h\"\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include \"mosek.h\"\n#include <Queue>\n#include <fstream>\n#include \"permutohedral.h\"\n#include \"adjust_orientation_LBFGS.h\"\n#include \"Polycube_Boundary_Map_IVF.h\"\n#include \"fmath.hpp\"\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/property_map/property_map.hpp>\n#include \"Helper.h\"\n#define MIN_EDGE_DIST 1e-6\nusing namespace boost;\nusing ig::CVec;\npolycube_flattening_interface::polycube_flattening_interface()\n{\n    prepare_ok = false;\n    is_auto_deformation = true;\n    deformation_v_id.clear(); deformation_new_p.clear(); deformation_ok.clear();\n    handles_region_id.clear(); region_handles.clear();\n    dis_th = 5.0;\n    sigma_s = 1.0; sigma_r = 10; \n    asimptotic_epsilon = 1e-8;\n    EpsSafetyFactor = 1.0e6;\n    meps = 2.220446e-13;\n    EpsilonEfectivo = meps * EpsSafetyFactor;\n    umbral_factor = 1e-5;\n    AABB_Tree = NULL;\n    cut_to_chart_pair.clear();\n    cut_to_chart_pair_neighbor.clear();\n    cut_types.clear();\n    cut_common_verts_idx.clear();\n    vert_pairs_map.clear();\n    equal_triangles.clear();\n    three_cut_common_vert.clear();\n    three_cut_vert.clear();\n    three_cut_vert_flag.clear();\n    three_cut_adjacent_one_cut_index.clear();\n    hex_meshing_flag = true;\n    update_updownchart_flag = false;\n}\npolycube_flattening_interface::~polycube_flattening_interface()\n{\n    if (AABB_Tree)\n    {\n        delete AABB_Tree;\n    }\n}\nvoid polycube_flattening_interface::load_boundary_face_label(const std::vector<int> &label, const std::vector<int> &chart, TetStructure<double>* tet_mesh_)\n{\n    polycube_edges.clear();\n    polycube_edge_distortion_iso.clear();\n    polycube_edge_distortion_conf.clear();\n    polycube_edge_distortion_vol.clear();\n    polycube_edge_face_distortion.clear();\n    polycube_edge_layer_distortion.clear();\n    polycube_edge_length.clear();\n    polycube_short_edges.clear();\n    int nc = tet_mesh_->tetras.size();\n    const std::vector<Tetrahedron<double>*> &tetras = tet_mesh_->tetras;\n    const std::vector<TetVertex<double>*> &tetra_vertices = tet_mesh_->tetra_vertices;\n    target_bfn.resize(nc, OpenVolumeMesh::Geometry::Vec3d(0, 0, 0));\n    bf_chart.clear(); bf_chart.resize(nc, -1);\n    std::vector<int> chart_xyz(nc, -1);\n    int max_chart_id = 0;\n    assert(label.size() == chart.size());\n    if (label.size() == 0 || chart.size() == 0)\n        return;\n    for (size_t i = 0; i < label.size(); i++)\n    {\n        int l = label[i]; int cid = i;\n        switch (l)\n        {\n        case 0:\n            target_bfn[cid][0] = 1.0;\n            chart_xyz[cid] = 0;\n            break;\n        case 1:\n            target_bfn[cid][1] = 1.0;\n            chart_xyz[cid] = 2;\n            break;\n        case 2:\n            target_bfn[cid][2] = 1.0;\n            chart_xyz[cid] = 4;\n            break;\n        case 3:\n            target_bfn[cid][0] = -1.0;\n            chart_xyz[cid] = 1;\n            break;\n        case 4:\n            target_bfn[cid][1] = -1.0;\n            chart_xyz[cid] = 3;\n            break;\n        case 5:\n            target_bfn[cid][2] = -1.0;\n            chart_xyz[cid] = 5;\n            break;\n        default:\n            break;\n        }\n        bf_chart[cid] = chart[i];\n        if (bf_chart[cid] > max_chart_id)\n        {\n            max_chart_id = bf_chart[cid];\n        }\n    }\n    polycube_chart.clear(); polycube_chart.resize(max_chart_id + 1);\n    polycube_chart_label.clear(); polycube_chart_label.resize(max_chart_id + 1);\n    chart_mean_value.clear(); chart_mean_value.resize(max_chart_id + 1, 0.0);\n    for (int i = 0; i < nc; ++i)\n    {\n        int chart_id = bf_chart[i];\n        if (chart_id < 0) continue;\n        polycube_chart[chart_id].push_back(i);\n        polycube_chart_label[chart_id] = chart_xyz[i];\n    }\n    int nv = bvf_id.size();\n    vertex_type.clear(); vertex_type.resize(nv, OpenVolumeMesh::Geometry::Vec3i(-1, -1, -1));\n    for (int i = 0; i < nv; ++i)\n    {\n        std::vector<int>& one_vf_id = bvf_id[i];\n        int bvf_size = one_vf_id.size();\n        if (bvf_size > 0)\n        {\n            for (int j = 0; j < bvf_size; ++j)\n            {\n                vertex_type[i][chart_xyz[one_vf_id[j]] / 2] = bf_chart[one_vf_id[j]];\n            }\n        }\n    }\n    int ne = bef_id.size();\n    std::vector<OpenVolumeMesh::Geometry::Vec3i> edge_two_chart;\n    for (int i = 0; i < ne; ++i)\n    {\n        std::vector<int>& one_ef_id = bef_id[i];\n        int bef_size = one_ef_id.size();\n        if (bef_size == 2)\n        {\n            if (bf_chart[one_ef_id[0]] != bf_chart[one_ef_id[1]] && bf_chart[one_ef_id[1]] >= 0 && bf_chart[one_ef_id[0]] >= 0)\n            {\n                int l0 = bf_chart[one_ef_id[0]]; int l1 = bf_chart[one_ef_id[1]];\n                if (l0 < l1)\n                {\n                    edge_two_chart.push_back(OpenVolumeMesh::Geometry::Vec3i(l0, l1, i));\n                }\n                else\n                {\n                    edge_two_chart.push_back(OpenVolumeMesh::Geometry::Vec3i(l1, l0, i));\n                }\n            }\n        }\n        else if (bef_size != 0)\n        {\n            printf(\"Error boundary edge face %d\\n\", bef_size);\n        }\n    }\n    std::vector<int> empty_(1);\n    std::vector<OpenVolumeMesh::Geometry::Vec2i> two_label;\n    edge_with_same_label.clear();\n    polycube_edge_idx2same_label_idx.clear();\n    for (int i = 0; i < edge_two_chart.size(); ++i)\n    {\n        OpenVolumeMesh::Geometry::Vec3i& two_chart = edge_two_chart[i];\n        int inserted_id = -1;\n        for (int j = 0; j < two_label.size(); ++j)\n        {\n            if (two_chart[0] == two_label[j][0] && two_chart[1] == two_label[j][1])\n            {\n                inserted_id = j;\n                edge_with_same_label[j].push_back(two_chart[2]);\n            }\n        }\n        if (inserted_id < 0)\n        {\n            two_label.push_back(OpenVolumeMesh::Geometry::Vec2i(two_chart[0], two_chart[1]));\n            int label1 = polycube_chart_label[two_chart[0]];\n            int label2 = polycube_chart_label[two_chart[1]];\n            if (label1 / 2 == label2 / 2)\n            {\n                std::cout << \"!!!!!!!!!!!!!!!!!Error: illegal label!!!!!!!!!!!!!!!!!!!\" << std::endl;\n                std::cout << \"Chart info: \" << two_chart[0] << \" \" << two_chart[1] << std::endl;\n                std::cout << \"Label info: \" << label1 << \" \" << label2 << std::endl;\n                return;\n            }\n            empty_[0] = two_chart[2];\n            edge_with_same_label.push_back(empty_);\n        }\n    }\n    up_chart_id.clear(); down_chart_id.clear(); diff_up_down.clear();\n    key_edges.clear();\n    key_edges = edge_with_same_label;\n    get_chart_distortion();\n    for (int i = 0; i < edge_with_same_label.size(); ++i)\n    {\n        std::vector<int> two_corner;\n        double edge_distortion = 0.0;\n        double edge_distortion_conf = 0.0;\n        double edge_distortion_vol = 0.0;\n        for (int j = 0; j < edge_with_same_label[i].size(); ++j)\n        {\n            int edge_id = edge_with_same_label[i][j];\n            std::pair<int, int> temp_pair = id2edge[edge_id];\n            int fv = temp_pair.first; int tv = temp_pair.second;\n            if (vertex_type[fv][0] >= 0 && vertex_type[fv][1] >= 0 && vertex_type[fv][2] >= 0)\n            {\n                two_corner.push_back(fv);\n            }\n            if (vertex_type[tv][0] >= 0 && vertex_type[tv][1] >= 0 && vertex_type[tv][2] >= 0)\n            {\n                two_corner.push_back(tv);\n            }\n            int face1 = bef_id[edge_id][0];\n            int face2 = bef_id[edge_id][1];\n            edge_distortion += all_iso_d[face1];\n            edge_distortion += all_iso_d[face2];\n            edge_distortion_vol += all_vol_d[face1];\n            edge_distortion_vol += all_vol_d[face2];\n            edge_distortion_conf += all_con_d[face1];\n            edge_distortion_conf += all_con_d[face2];\n        }\n        edge_distortion = edge_distortion / edge_with_same_label[i].size();\n        edge_distortion_vol = edge_distortion_vol / edge_with_same_label[i].size();\n        edge_distortion_conf = edge_distortion_conf / edge_with_same_label[i].size();\n        std::vector<OpenVolumeMesh::Geometry::Vec2i> final_tc;\n        std::vector<std::pair<int, int>> final_tc_chart;\n        if (two_corner.size() != 2)\n        {\n            std::vector<int> visited(two_corner.size(), -1);\n            for (int ijk = 0; ijk < two_corner.size(); ++ijk)\n            {\n                if (visited[ijk] == 1) continue;\n                visited[ijk] = 1; int seed_v = two_corner[ijk]; int last_v = -1;\n                std::vector<int>& one_vv = bvv_id[seed_v]; int label_count = 0;\n                for (int j = 0; j < one_vv.size(); ++j)\n                {\n                    label_count = 0;\n                    for (int k = 0; k < 3; ++k)\n                    {\n                        if (vertex_type[one_vv[j]][k] == two_label[i][0] || vertex_type[one_vv[j]][k] == two_label[i][1])\n                        {\n                            ++label_count;\n                        }\n                    }\n                    if (label_count == 2)\n                    {\n                        last_v = seed_v;\n                        seed_v = one_vv[j];\n                        break;\n                    }\n                }\n                if (vertex_type[seed_v][0] >= 0 && vertex_type[seed_v][1] >= 0 && vertex_type[seed_v][2] >= 0)\n                {\n                    std::pair<int, int> temp_edge;\n                    temp_edge.first = two_corner[ijk] < seed_v ? two_corner[ijk] : seed_v;\n                    temp_edge.second = two_corner[ijk] + seed_v - temp_edge.first;\n                    int edge_id = edge2id[temp_edge];\n                    if (edge_id >= 0)\n                    {\n                        int l0 = bf_chart[bef_id[edge_id][0]]; int l1 = bf_chart[bef_id[edge_id][1]];\n                        if (l0 > l1)\n                        {\n                            int temp = l0;\n                            l0 = l1;\n                            l1 = temp;\n                        }\n                        if (l0 == two_label[i][0] && l1 == two_label[i][1])\n                        {\n                            final_tc.push_back(OpenVolumeMesh::Geometry::Vec2i(two_corner[ijk], seed_v));\n                            for (int kj = 0; kj < two_corner.size(); ++kj)\n                            {\n                                if (two_corner[kj] == seed_v) visited[kj] = 1;\n                            }\n                        }\n                    }\n                }\n                else\n                {\n                    while (1)\n                    {\n                        one_vv = bvv_id[seed_v];\n                        for (int j = 0; j < one_vv.size(); ++j)\n                        {\n                            label_count = 0;\n                            for (int k = 0; k < 3; ++k)\n                            {\n                                if (vertex_type[one_vv[j]][k] == two_label[i][0] || vertex_type[one_vv[j]][k] == two_label[i][1])\n                                {\n                                    ++label_count;\n                                }\n                            }\n                            if (label_count == 2 && one_vv[j] != last_v)\n                            {\n                                last_v = seed_v;\n                                seed_v = one_vv[j];\n                                break;\n                            }\n                        }\n                        if (vertex_type[seed_v][0] >= 0 && vertex_type[seed_v][1] >= 0 && vertex_type[seed_v][2] >= 0)\n                        {\n                            final_tc.push_back(OpenVolumeMesh::Geometry::Vec2i(two_corner[ijk], seed_v));\n                            for (int kj = 0; kj < two_corner.size(); ++kj)\n                            {\n                                if (two_corner[kj] == seed_v) visited[kj] = 1;\n                            }\n                            break;\n                        }\n                    }\n                }\n            }\n        }\n        else\n        {\n            final_tc.push_back(OpenVolumeMesh::Geometry::Vec2i(two_corner[0], two_corner[1]));\n        }\n        for (size_t j = 0; j < final_tc.size(); j++)\n        {\n            std::vector<int> one_edge;\n            one_edge.push_back(final_tc[j][0]);\n            one_edge.push_back(final_tc[j][1]);\n            one_edge.push_back(two_label[i][0]);\n            one_edge.push_back(two_label[i][1]);\n            polycube_edges.push_back(one_edge);\n            polycube_edge_idx2same_label_idx.push_back(i);\n            polycube_edge_distortion_iso.push_back(edge_distortion);\n            polycube_edge_distortion_conf.push_back(edge_distortion_conf);\n            polycube_edge_distortion_vol.push_back(edge_distortion_vol);\n            polycube_edge_face_distortion.push_back(chart_iso_d[two_label[i][0]] + chart_iso_d[two_label[i][1]]);\n            double length = (dpx[final_tc[j][0]] - dpx[final_tc[j][1]]) * (dpx[final_tc[j][0]] - dpx[final_tc[j][1]]);\n            length += (dpy[final_tc[j][0]] - dpy[final_tc[j][1]]) * (dpy[final_tc[j][0]] - dpy[final_tc[j][1]]);\n            length += (dpz[final_tc[j][0]] - dpz[final_tc[j][1]]) * (dpz[final_tc[j][0]] - dpz[final_tc[j][1]]);\n            length = sqrt(length);\n            polycube_edge_length.push_back(length);\n        }\n        if (final_tc.size() == 1)\n        {\n            polycube_short_edges.push_back(edge_with_same_label[i]);\n        }\n        else\n        {\n            std::vector<std::vector<int>> local_bve(bvf_id.size());\n            for (size_t j = 0; j < edge_with_same_label[i].size(); j++)\n            {\n                int edgeid = edge_with_same_label[i][j];\n                int v0 = id2edge[edgeid].first;\n                int v1 = id2edge[edgeid].second;\n                local_bve[v0].push_back(edgeid);\n                local_bve[v1].push_back(edgeid);\n            }\n            for (size_t j = 0; j < final_tc.size(); j++)\n            {\n                std::vector<int> one_long_edge;\n                int beginp = final_tc[j][0];\n                int endp = final_tc[j][1];\n                assert(local_bve[beginp].size() == 1 && local_bve[endp].size() == 1);\n                int prev_edge(-1), next_edge(local_bve[beginp][0]);\n                int cur_p(beginp), next_p(-1);\n                while (next_edge != -1)\n                {\n                    one_long_edge.push_back(next_edge);\n                    std::pair<int, int> tmp_pair = id2edge[next_edge];\n                    if (tmp_pair.first == cur_p)\n                    {\n                        next_p = tmp_pair.second;\n                    }\n                    else\n                    {\n                        next_p = tmp_pair.first;\n                    }\n                    cur_p = next_p;\n                    prev_edge = next_edge;\n                    if (cur_p == endp)\n                    {\n                        next_edge = -1;\n                    }\n                    else\n                    {\n                        int e0 = local_bve[cur_p][0];\n                        int e1 = local_bve[cur_p][1];\n                        if (prev_edge == e0)\n                        {\n                            next_edge = e1;\n                        }\n                        else\n                        {\n                            next_edge = e0;\n                        }\n                    }\n                }\n                polycube_short_edges.push_back(one_long_edge);\n            }\n        }\n        for (int j = 0; j < final_tc.size(); ++j)\n        {\n            int v0 = final_tc[j][0]; int v1 = final_tc[j][1];\n            int l0 = -1; int l1 = -1; int k0 = -1; int k1 = -1;\n            int two_label_axis0 = polycube_chart_label[two_label[i][0]] / 2;\n            int two_label_axis1 = polycube_chart_label[two_label[i][1]] / 2;\n            for (int j = 0; j < 3; ++j)\n            {\n                int v0_axis = polycube_chart_label[vertex_type[v0][j]] / 2;\n                int v1_axis = polycube_chart_label[vertex_type[v1][j]] / 2;\n                if (two_label_axis0 != v0_axis && two_label_axis1 != v0_axis)\n                {\n                    l0 = vertex_type[v0][j]; k0 = j;\n                }\n                if (two_label_axis0 != v1_axis && two_label_axis1 != v1_axis)\n                {\n                    l1 = vertex_type[v1][j]; k1 = j;\n                }\n            }\n            if (k0 != k1)\n            {\n                printf(\"Error corner label %d %d %d %d\\n\", v0, k0, v1, k1);\n            }\n            CVec<double, 3> p0 = tetra_vertices[v0]->pos;\n            CVec<double, 3> p1 = tetra_vertices[v1]->pos;\n            if (p0[k0] > p1[k1])\n            {\n                up_chart_id.push_back(l0); down_chart_id.push_back(l1); diff_up_down.push_back(p0[k0] - p1[k1]);\n            }\n            else\n            {\n                up_chart_id.push_back(l1); down_chart_id.push_back(l0); diff_up_down.push_back(p1[k1] - p0[k0]);\n            }\n        }\n    }\n    assert(polycube_edges.size() == polycube_short_edges.size());\n}\nvoid polycube_flattening_interface::load_feature_edges_vtk(const std::vector<std::pair<int, int>> &feature_edge_array)\n{\n    if (feature_edge_array.empty()) return;\n    feature_edge_flag_ori.clear();\n    feature_edge_flag_ori.resize(id2edge.size(), false);\n    feature_v2v.resize(bvf_id.size());\n    feature_v2e.resize(bvf_id.size());\n    for (size_t i = 0; i < feature_edge_array.size(); i++)\n    {\n        int v0 = feature_edge_array[i].first;\n        int v1 = feature_edge_array[i].second;\n        if (v0 > v1)\n        {\n            int tmp = v0;\n            v0 = v1;\n            v1 = tmp;\n        }\n        auto it = edge2id.find(std::pair<int, int>(v0, v1));\n        assert(it != edge2id.end());\n        feature_edge_flag_ori[it->second] = true;\n        feature_v2e[v0].push_back(it->second);\n        feature_v2e[v1].push_back(it->second);\n        feature_v2v[v0].push_back(v1);\n        feature_v2v[v1].push_back(v0);\n    }\n    pqedge_v2e.clear();\n    pqedge_v2e.resize(bvf_id.size());\n    pqedge_v2v.clear();\n    pqedge_v2v.resize(bvf_id.size());\n    for (size_t i = 0; i < polycube_short_edges.size(); i++)\n    {\n        for (size_t j = 0; j < polycube_short_edges[i].size(); j++)\n        {\n            int eid = polycube_short_edges[i][j];\n            int v0 = id2edge[eid].first;\n            int v1 = id2edge[eid].second;\n            pqedge_v2e[v0].push_back(eid);\n            pqedge_v2e[v1].push_back(eid);\n            pqedge_v2v[v0].push_back(v1);\n            pqedge_v2v[v1].push_back(v0);\n        }\n    }\n}\nbool polycube_flattening_interface::feature_extraction(double select_ratio, int min_feature_length)\n{\n    if (feature_edge_flag_ori.empty()) return false;\n    feature_polycube_edge.clear();\n    group_feature_edge.clear();\n    feature_edge_flag_final.clear();\n    feature_edge_flag_final.resize(id2edge.size(), false);\n    std::vector<int> one_feature_edge;\n    bool success_flag = true;\n    for (size_t i = 0; i < polycube_short_edges.size(); i++)\n    {\n        one_feature_edge.clear();\n        for (size_t j = 0; j < polycube_short_edges[i].size(); j++)\n        {\n            int eid = polycube_short_edges[i][j];\n            if (feature_edge_flag_ori[eid] == true)\n                one_feature_edge.push_back(eid);\n        }\n        double ratio = one_feature_edge.size() * 1.0 / polycube_short_edges[i].size();\n        if (one_feature_edge.size() == polycube_short_edges[i].size())\n        {\n            feature_polycube_edge.push_back(i);\n            feature_polycube_edge_segm.push_back(std::pair<double, double>(0.0, 1.0));\n            group_feature_edge.push_back(one_feature_edge);\n            group_feature_edge_start.push_back(polycube_edges[i][0]);\n            for (size_t j = 0; j < one_feature_edge.size(); j++)\n            {\n                feature_edge_flag_final[one_feature_edge[j]] = true;\n            }\n        }\n        else\n        {\n            if (ratio > select_ratio)\n                success_flag = false;\n            std::set<int> one_feature_edge_set;\n            for (size_t j = 0; j < one_feature_edge.size(); j++)\n            {\n                one_feature_edge_set.insert(one_feature_edge[j]);\n            }\n            std::vector<int> leftpart_eid, rightpart_eid;\n            std::vector<std::pair<int, int>> pq_left, pq_right;\n            for (size_t j = 0; j < polycube_short_edges[i].size(); j++)\n            {\n                int eid = polycube_short_edges[i][j];\n                pq_left.push_back(id2edge[eid]);\n            }\n            pq_right = pq_left;\n            reorder_edge(pq_left, polycube_edges[i][0]);\n            reorder_edge(pq_right, polycube_edges[i][1]);\n            int right_end_id = -1;\n            for (size_t j = 0; j < pq_left.size(); j++)\n            {\n                int minid = std::min(pq_left[j].first, pq_left[j].second);\n                int maxid = std::max(pq_left[j].first, pq_left[j].second);\n                auto it = edge2id.find(std::pair<int, int>(minid, maxid));\n                assert(it != edge2id.end());\n                int eid = it->second;\n                auto feait = one_feature_edge_set.find(eid);\n                if (feait != one_feature_edge_set.end())\n                {\n                    leftpart_eid.push_back(eid);\n                }\n                else\n                {\n                    break;\n                }\n            }\n            for (size_t j = 0; j < pq_right.size(); j++)\n            {\n                int minid = std::min(pq_right[j].first, pq_right[j].second);\n                int maxid = std::max(pq_right[j].first, pq_right[j].second);\n                auto it = edge2id.find(std::pair<int, int>(minid, maxid));\n                assert(it != edge2id.end());\n                int eid = it->second;\n                auto feait = one_feature_edge_set.find(eid);\n                if (feait != one_feature_edge_set.end())\n                {\n                    rightpart_eid.push_back(eid);\n                    right_end_id = pq_right[j].second;\n                }\n                else\n                {\n                    break;\n                }\n            }\n            if (leftpart_eid.size() > min_feature_length)\n            {\n                group_feature_edge.push_back(leftpart_eid);\n                group_feature_edge_start.push_back(polycube_edges[i][0]);\n                feature_polycube_edge.push_back(i);\n                std::vector<std::pair<int, int>> shortlongedge;\n                shortlongedge.push_back(std::pair<int, int>(polycube_edges[i][0], pq_left[leftpart_eid.size() - 1].second));\n                shortlongedge.push_back(std::pair<int, int>(polycube_edges[i][0], polycube_edges[i][1]));\n                std::vector<double> shortlonglength;\n                get_edge_length(shortlongedge, shortlonglength);\n                double ratio = shortlonglength[0] / shortlonglength[1];\n                feature_polycube_edge_segm.push_back(std::pair<double, double>(0.0, ratio));\n                for (size_t j = 0; j < leftpart_eid.size(); j++)\n                {\n                    feature_edge_flag_final[leftpart_eid[j]] = true;\n                }\n            }\n            if (rightpart_eid.size() > min_feature_length)\n            {\n                group_feature_edge.push_back(rightpart_eid);\n                assert(right_end_id != -1);\n                group_feature_edge_start.push_back(right_end_id);\n                feature_polycube_edge.push_back(i);\n                std::vector<std::pair<int, int>> shortlongedge;\n                shortlongedge.push_back(std::pair<int, int>(polycube_edges[i][1], pq_right[rightpart_eid.size() - 1].second));\n                shortlongedge.push_back(std::pair<int, int>(polycube_edges[i][1], polycube_edges[i][0]));\n                std::vector<double> shortlonglength;\n                get_edge_length(shortlongedge, shortlonglength);\n                double ratio = shortlonglength[0] / shortlonglength[1];\n                feature_polycube_edge_segm.push_back(std::pair<double, double>(1.0 - ratio, 1.0));\n                for (size_t j = 0; j < rightpart_eid.size(); j++)\n                {\n                    feature_edge_flag_final[rightpart_eid[j]] = true;\n                }\n            }\n        }\n    }\n    return success_flag;\n}\nvoid polycube_flattening_interface::get_edge_length(const std::vector<std::pair<int, int>> &edgearray, std::vector<double> &edge_length)\n{\n    assert(dpx.size() != 0);\n    edge_length.clear();\n    for (size_t i = 0; i < edgearray.size(); i++)\n    {\n        int id0 = edgearray[i].first, id1 = edgearray[i].second;\n        double len2 = (dpx[id0] - dpx[id1]) * (dpx[id0] - dpx[id1]) + (dpy[id0] - dpy[id1]) * (dpy[id0] - dpy[id1]) + (dpz[id0] - dpz[id1]) * (dpz[id0] - dpz[id1]);\n        edge_length.push_back(std::sqrt(len2));\n    }\n}\nbool polycube_flattening_interface::repair_chartlabel_feature(int max_line_length, int max_area_size)\n{\n    std::vector<double> edgelength;\n    get_edge_length(id2edge, edgelength);\n    std::vector<bool> pqe_flag(bef_id.size(), false);\n    for (size_t i = 0; i < polycube_short_edges.size(); i++)\n    {\n        for (size_t j = 0; j < polycube_short_edges[i].size(); j++)\n        {\n            pqe_flag[polycube_short_edges[i][j]] = true;\n        }\n    }\n    bool corner_correct = true;\n    std::set<int> iso_edges;\n    for (int i = 0; i < feature_edge_flag_ori.size(); i++)\n    {\n        if (feature_edge_flag_ori[i])\n        {\n            if (!pqe_flag[i]) iso_edges.insert(i);\n        }\n    }\n    std::vector<std::vector<int>> bfe(bfv_id.size());\n    for (size_t i = 0; i < bef_id.size(); i++)\n    {\n        if (bef_id[i].empty()) continue;\n        assert(bef_id[i].size() == 2);\n        int f0 = bef_id[i][0];\n        int f1 = bef_id[i][1];\n        bfe[f0].push_back(i);\n        bfe[f1].push_back(i);\n    }\n    std::vector<std::vector<int>> grouped_iso_edges;\n    while (!iso_edges.empty())\n    {\n        auto first = iso_edges.begin();\n        std::vector<int> one_edge;\n        std::vector<bool> color(bef_id.size(), false);\n        color[*first] = true;\n        std::queue<int> q;\n        q.push(*first);\n        while (!q.empty())\n        {\n            int front = q.front();\n            one_edge.push_back(front);\n            q.pop();\n            int twovert[] = { id2edge[front].first, id2edge[front].second };\n            for (size_t i = 0; i < 2; i++)\n            {\n                for (size_t j = 0; j < feature_v2e[twovert[i]].size(); j++)\n                {\n                    int eid = feature_v2e[twovert[i]][j];\n                    if (eid == front) continue;\n                    if (iso_edges.find(eid) != iso_edges.end() && color[eid] == false)\n                    {\n                        color[eid] = true;\n                        q.push(eid);\n                    }\n                }\n            }\n        }\n        grouped_iso_edges.push_back(one_edge);\n        for (size_t i = 0; i < one_edge.size(); i++)\n        {\n            iso_edges.erase(one_edge[i]);\n        }\n    }\n    std::vector<std::vector<std::pair<int, int>>> grouped_edges_reordered;\n    std::vector<int> valence_three_case_id;\n    for (size_t i = 0; i < grouped_iso_edges.size(); i++)\n    {\n        if (grouped_iso_edges[i].size() > max_line_length) continue;\n        std::map<int, std::vector<int>> local_v2e;\n        for (size_t j = 0; j < grouped_iso_edges[i].size(); j++)\n        {\n            int eid = grouped_iso_edges[i][j];\n            local_v2e[id2edge[eid].first].push_back(eid);\n            local_v2e[id2edge[eid].second].push_back(eid);\n        }\n        std::vector<int> endpoints;\n        bool valence_three_flag = false;\n        for (auto it : local_v2e)\n        {\n            if (it.second.size() >= 3)\n            {\n                valence_three_flag = true;\n                corner_correct = false;\n                valence_three_error_feature_pt_id.push_back(it.first);\n                valence_three_case_id.push_back(i);\n            }\n            if (it.second.size() == 1) endpoints.push_back(it.first);\n        }\n        if (valence_three_flag || endpoints.size() != 2) continue;\n        bool legal_endpoint_flag = true;\n        for (size_t j = 0; j < endpoints.size(); j++)\n        {\n            int vid = endpoints[j];\n            if (feature_v2e[vid].size() == 1) legal_endpoint_flag = false;\n            if (pqedge_v2e[vid].empty()) legal_endpoint_flag = false;\n        }\n        if (!legal_endpoint_flag) continue;\n        std::vector<std::pair<int, int>> one_order_edge;\n        for (size_t j = 0; j < grouped_iso_edges[i].size(); j++)\n        {\n            int eid = grouped_iso_edges[i][j];\n            one_order_edge.push_back(id2edge[eid]);\n        }\n        reorder_edge(one_order_edge, endpoints[0]);\n        grouped_edges_reordered.push_back(one_order_edge);\n    }\n    std::vector<std::vector<std::pair<int, int>>> grouped_edges_reordered_split;\n    for (size_t i = 0; i < grouped_edges_reordered.size(); i++)\n    {\n        std::vector<int> split_id;\n        for (int j = 1; j < grouped_edges_reordered[i].size(); j++)\n        {\n            int vid = grouped_edges_reordered[i][j].first;\n            if (pqedge_v2e[vid].size() != 0) split_id.push_back(j);\n        }\n        split_id.push_back(grouped_edges_reordered[i].size());\n        if (split_id.size() == 1)\n        {\n            grouped_edges_reordered_split.push_back(grouped_edges_reordered[i]);\n        }\n        else\n        {\n            int start = 0;\n            for (size_t j = 0; j < split_id.size(); j++)\n            {\n                int end = split_id[j];\n                std::vector<std::pair<int, int>> one_edge;\n                for (size_t k = start; k < end; k++)\n                {\n                    one_edge.push_back(grouped_edges_reordered[i][k]);\n                }\n                grouped_edges_reordered_split.push_back(one_edge);\n                start = end;\n            }\n        }\n    }\n    std::vector<std::vector<std::pair<int, int>>> grouped_loop;\n    typedef adjacency_list < listS, vecS, undirectedS,\n        no_property, property < edge_weight_t, double > > graph_t;\n    typedef graph_traits < graph_t >::vertex_descriptor vertex_descriptor;\n    typedef std::pair<int, int> Edge;\n    int n_pqv = 0;\n    for (size_t i = 0; i < pqedge_v2e.size(); i++)\n    {\n        if (!pqedge_v2e[i].empty()) n_pqv++;\n    }\n    std::vector<Edge> edge_array;\n    std::vector<double> weights;\n    for (size_t i = 0; i < polycube_short_edges.size(); i++)\n    {\n        for (size_t j = 0; j < polycube_short_edges[i].size(); j++)\n        {\n            int first = id2edge[polycube_short_edges[i][j]].first;\n            int second = id2edge[polycube_short_edges[i][j]].second;\n            edge_array.push_back(Edge(first, second));\n            double d2 = (dpx[first] - dpx[second]) * (dpx[first] - dpx[second]) + (dpy[first] - dpy[second]) * (dpy[first] - dpy[second]) + (dpz[first] - dpz[second]) * (dpz[first] - dpz[second]);\n            weights.push_back(std::sqrt(d2));\n        }\n    }\n    graph_t g(edge_array.begin(), edge_array.end(), weights.begin(), n_pqv);\n    property_map<graph_t, edge_weight_t>::type weightmap = get(edge_weight, g);\n    for (size_t i = 0; i < grouped_edges_reordered_split.size(); i++)\n    {\n        grouped_loop.push_back(grouped_edges_reordered_split[i]);\n        int end = grouped_edges_reordered_split[i].back().second;\n        int start = grouped_edges_reordered_split[i].front().first;\n        std::vector<vertex_descriptor> p(num_vertices(g));\n        std::vector<double> d(num_vertices(g));\n        vertex_descriptor s = vertex(start, g);\n        dijkstra_shortest_paths(g, s,\n            predecessor_map(boost::make_iterator_property_map(p.begin(), get(boost::vertex_index, g))).\n            distance_map(boost::make_iterator_property_map(d.begin(), get(boost::vertex_index, g))));\n        vertex_descriptor t = vertex(end, g);\n        vertex_descriptor par = p[t];\n        if (d[t] < DBL_MAX)\n        {\n            while (t != s)\n            {\n                grouped_loop.back().push_back(std::pair<int, int>(t, par));\n                t = par;\n                par = p[t];\n            }\n            assert(grouped_loop.back().front().first == grouped_loop.back().back().second);\n        }\n        else\n        {\n            grouped_loop.pop_back();\n            continue;\n        }\n        if (grouped_loop.back().size() > 3 * grouped_edges_reordered_split[i].size())\n        {\n            grouped_loop.pop_back();\n            continue;\n        }\n    }\n    for (size_t i = 0; i < grouped_loop.size(); i++)\n    {\n        std::vector<bool> sel_face_flag(bfv_id.size(), false);\n        std::set<int> one_loop_edge;\n        for (size_t j = 0; j < grouped_loop[i].size(); j++)\n        {\n            int first = grouped_loop[i][j].first;\n            int second = grouped_loop[i][j].second;\n            if (first > second) std::swap(first, second);\n            auto it = edge2id.find(std::pair<int, int>(first, second));\n            assert(it != edge2id.end());\n            one_loop_edge.insert(it->second);\n        }\n        bool all_feature_flag = true;\n        for (auto e : one_loop_edge)\n        {\n            if (!feature_edge_flag_ori[e])\n                all_feature_flag = false;\n        }\n        if (all_feature_flag) continue;\n        std::vector<int> sel_faces;\n        int seedface = bef_id[*one_loop_edge.begin()][0];\n        sel_face_flag[seedface] = true;\n        std::queue<int> q;\n        q.push(seedface);\n        while (!q.empty())\n        {\n            int front = q.front();\n            sel_faces.push_back(q.front());\n            q.pop();\n            for (size_t j = 0; j < bfe[front].size(); j++)\n            {\n                int eid = bfe[front][j];\n                if (one_loop_edge.find(eid) == one_loop_edge.end())\n                {\n                    int otherface = bef_id[eid][0];\n                    if (otherface == front) otherface = bef_id[eid][1];\n                    if (!sel_face_flag[otherface])\n                    {\n                        sel_face_flag[otherface] = true;\n                        q.push(otherface);\n                    }\n                }\n            }\n        }\n        int sel_face_count = sel_faces.size();\n        if (sel_face_count > boundary_face_number - sel_face_count)\n        {\n            sel_faces.clear();\n            for (size_t j = 0; j < sel_face_flag.size(); j++)\n            {\n                if (!sel_face_flag[j] && bfv_id[j][0] != -1)\n                {\n                    sel_faces.push_back(j);\n                }\n            }\n            assert(sel_faces.size() == boundary_face_number - sel_face_count);\n            sel_face_count = sel_faces.size();\n        }\n        if (sel_face_count > max_area_size || sel_face_count == 0) continue;\n        std::set<int> sel_face_charts;\n        for (size_t j = 0; j < sel_faces.size(); j++)\n        {\n            sel_face_charts.insert(bf_chart[sel_faces[j]]);\n        }\n        if (sel_face_charts.size() >= 3) continue;\n        std::vector<double> loop_chart_count(polycube_chart_label.size(), 0.0);\n        for (auto e : one_loop_edge)\n        {\n            int f0 = bef_id[e][0];\n            int f1 = bef_id[e][1];\n            loop_chart_count[bf_chart[f0]] += edgelength[e];\n            loop_chart_count[bf_chart[f1]] += edgelength[e];\n        }\n        int final_chart = -1;\n        double max_chart_count = -1;\n        for (size_t j = 0; j < polycube_chart_label.size(); j++)\n        {\n            int chart = j;\n            if (sel_face_charts.find(chart) == sel_face_charts.end())\n            {\n                if (max_chart_count < loop_chart_count[chart])\n                {\n                    max_chart_count = loop_chart_count[chart];\n                    final_chart = chart;\n                }\n            }\n        }\n        assert(final_chart != -1 && max_chart_count != 0);\n        for (size_t j = 0; j < sel_faces.size(); j++)\n        {\n            bf_chart[sel_faces[j]] = final_chart;\n        }\n    }\n    for (size_t i = 0; i < valence_three_case_id.size(); i++)\n    {\n        std::map<int, std::vector<int>> local_v2e;\n        int id = valence_three_case_id[i];\n        for (size_t j = 0; j < grouped_iso_edges[id].size(); j++)\n        {\n            int eid = grouped_iso_edges[id][j];\n            local_v2e[id2edge[eid].first].push_back(eid);\n            local_v2e[id2edge[eid].second].push_back(eid);\n        }\n        for (auto it : local_v2e)\n        {\n            if (it.second.size() >= 3)\n            {\n                std::vector<std::set<int>> split_face_id;\n                std::set<int> one_ring_face(bvf_id[it.first].begin(), bvf_id[it.first].end());\n                std::map<int, bool> visited;\n                for (auto f : one_ring_face)\n                    visited[f] = false;\n                while (!one_ring_face.empty())\n                {\n                    std::set<int> selected;\n                    std::map<int, bool> cur_visited = visited;\n                    auto first = one_ring_face.begin();\n                    cur_visited[*first] = true;\n                    std::queue<int> q;\n                    q.push(*first);\n                    while (!q.empty())\n                    {\n                        int front = q.front();\n                        q.pop();\n                        selected.insert(front);\n                        for (size_t j = 0; j < bfe[front].size(); j++)\n                        {\n                            int eid = bfe[front][j];\n                            if (feature_edge_flag_ori[eid]) continue;\n                            int otherface = bef_id[eid][0];\n                            if (otherface == front) otherface = bef_id[eid][1];\n                            if (one_ring_face.find(otherface) != one_ring_face.end() && visited[otherface] != true)\n                            {\n                                q.push(otherface);\n                                visited[otherface] = true;\n                            }\n                        }\n                    }\n                    split_face_id.push_back(selected);\n                    for (auto f : selected)\n                    {\n                        one_ring_face.erase(f);\n                    }\n                }\n                assert(split_face_id.size() == it.second.size());\n                for (size_t j = 0; j < split_face_id.size(); j++)\n                {\n                    std::set<int> outsideface = split_face_id[j];\n                    int n_search_layer = 6;\n                    for (size_t k = 0; k < n_search_layer; k++)\n                    {\n                        std::set<int> added_face;\n                        for (auto f : outsideface)\n                        {\n                            for (auto e : bfe[f])\n                            {\n                                if (!feature_edge_flag_ori[e])\n                                {\n                                    int otherface = bef_id[e][0];\n                                    if (otherface == f) otherface = bef_id[e][1];\n                                    if (outsideface.find(otherface) == outsideface.end())\n                                    {\n                                        added_face.insert(otherface);\n                                    }\n                                }\n                            }\n                        }\n                        for (auto f : added_face)\n                            split_face_id[j].insert(f);\n                        outsideface = added_face;\n                    }\n                }\n                for (size_t j = 0; j < split_face_id.size(); j++)\n                {\n                    int max_chart = -1;\n                    int max_chart_count = -1;\n                    std::vector<int> chart_count(polycube_chart_label.size(), 0);\n                    for (auto f : split_face_id[j])\n                    {\n                        chart_count[bf_chart[f]]++;\n                    }\n                    for (size_t k = 0; k < polycube_chart_label.size(); k++)\n                    {\n                        if (max_chart_count == -1 || max_chart_count < chart_count[k])\n                        {\n                            max_chart_count = chart_count[k];\n                            max_chart = k;\n                        }\n                    }\n                    assert(max_chart != -1);\n                    for (auto f : split_face_id[j])\n                    {\n                        bf_chart[f] = max_chart;\n                    }\n                }\n            }\n        }\n    }\n    return corner_correct;\n}\nbool polycube_flattening_interface::save_chartlabel(const char* filename)\n{\n    static int normalmap[] = { 0, 1, 2, 3, 4, 5 };\n    std::ofstream ofs(filename);\n    for (size_t i = 0; i < bf_chart.size(); i++)\n    {\n        if (bf_chart[i] < 0)\n            ofs << i << \" -1 -1\\n\";\n        else\n        {\n            ofs << i << \" \" << bf_chart[i] << \" \" << normalmap[polycube_chart_label[bf_chart[i]]] << std::endl;\n        }\n    }\n    ofs.close();\n    return true;\n}\nvoid polycube_flattening_interface::reorder_edge(std::vector<std::pair<int, int>> &one_edge, int start)\n{\n    std::map<int, std::vector<int>> vert2edgeid;\n    for (int i = 0; i < one_edge.size(); i++)\n    {\n        vert2edgeid[one_edge[i].first].push_back(i);\n        vert2edgeid[one_edge[i].second].push_back(i);\n    }\n    auto findstart = vert2edgeid.find(start);\n    assert(findstart != vert2edgeid.end());\n    assert(findstart->second.size() == 1);\n    if (findstart == vert2edgeid.end() || findstart->second.size() != 1)\n    {\n        return;\n    }\n    int start_eid = findstart->second[0];\n    std::vector<std::pair<int, int>> one_edge_new;\n    int cur = start, prev = -1, next = one_edge[start_eid].first;\n    next = next == cur ? one_edge[start_eid].second : next;\n    while (next != -1)\n    {\n        one_edge_new.push_back(std::pair<int, int>(cur, next));\n        prev = cur;\n        cur = next;\n        next = -1;\n        auto it = vert2edgeid.find(cur);\n        assert(it != vert2edgeid.end());\n        for (size_t i = 0; i < it->second.size(); i++)\n        {\n            int eid = it->second[i];\n            int diffv = one_edge[eid].first == cur ? one_edge[eid].second : one_edge[eid].first;\n            if (diffv != prev)\n            {\n                next = diffv;\n                break;\n            }\n        }\n    }\n    assert(one_edge_new.size() == one_edge.size());\n    one_edge = one_edge_new;\n}\nvoid polycube_flattening_interface::save_feature_edges_vtk_feaformat(const char* filename)\n{\n    if (group_feature_edge.empty()) return;\n    std::ofstream ofs(filename);\n    std::vector<std::pair<int, int>> long_feature;\n    for (size_t i = 0; i < group_feature_edge.size(); i++)\n    {\n        std::vector<std::pair<int, int>> one_short_edge_pair;\n        for (size_t j = 0; j < group_feature_edge[i].size(); j++)\n        {\n            int eid = group_feature_edge[i][j];\n            one_short_edge_pair.push_back(std::pair<int, int>(id2edge[eid].first, id2edge[eid].second));\n        }\n        long_feature.insert(long_feature.end(), one_short_edge_pair.begin(), one_short_edge_pair.end());\n    }\n    ofs << long_feature.size() << std::endl;\n    for (size_t i = 0; i < long_feature.size(); i++)\n    {\n        ofs << long_feature[i].first << \" \" << long_feature[i].second << std::endl;\n    }\n    assert(!feature_polycube_edge_segm.empty());\n    ofs << \"Feature PolyCube Edge\" << std::endl;\n    int useful_edge_count = 0;\n    for (size_t i = 0; i < feature_polycube_edge.size(); i++)\n    {\n        int eid = feature_polycube_edge[i];\n        if (feature_polycube_edge_segm[i].first < DBL_EPSILON && 1.0 - feature_polycube_edge_segm[i].second < DBL_EPSILON)\n        {\n            useful_edge_count++;\n        }\n    }\n    ofs << useful_edge_count << std::endl;\n    for (size_t i = 0; i < feature_polycube_edge.size(); i++)\n    {\n        int eid = feature_polycube_edge[i];\n        if (feature_polycube_edge_segm[i].first < DBL_EPSILON && 1.0 - feature_polycube_edge_segm[i].second < DBL_EPSILON)\n        {\n            ofs << polycube_edges[eid][0] << \" \" << polycube_edges[eid][1] << std::endl;\n        }\n    }\n    ofs.close();\n}\nvoid polycube_flattening_interface::save_feature_edges_vtk_tfeformat(const char* filename, TetStructure<double>* tet_mesh_ori)\n{\n    if (group_feature_edge.empty()) return;\n    std::ofstream ofs(filename);\n    ofs << \"Tet Feature Line\" << std::endl;\n    ofs << group_feature_edge.size() << std::endl;\n    for (size_t i = 0; i < group_feature_edge.size(); i++)\n    {\n        ofs << group_feature_edge[i].size() + 1 << std::endl;\n        std::vector<std::pair<int, int>> one_short_edge_pair;\n        for (size_t j = 0; j < group_feature_edge[i].size(); j++)\n        {\n            int eid = group_feature_edge[i][j];\n            one_short_edge_pair.push_back(std::pair<int, int>(id2edge[eid].first, id2edge[eid].second));\n        }\n        reorder_edge(one_short_edge_pair, group_feature_edge_start[i]);\n        ofs << tet_mesh_ori->tetra_vertices[one_short_edge_pair[0].first]->pos << \" \";\n        for (size_t j = 0; j < one_short_edge_pair.size(); j++)\n        {\n            int vid = one_short_edge_pair[j].second;\n            ofs << tet_mesh_ori->tetra_vertices[vid]->pos << \" \";\n        }\n        ofs << std::endl;\n    }\n    ofs.close();\n}\nvoid polycube_flattening_interface::save_error_feature_ptid_ptsformat(const char* filename)\n{\n    std::ofstream ofs(filename);\n    ofs << valence_three_error_feature_pt_id.size() << std::endl;\n    for (size_t i = 0; i < valence_three_error_feature_pt_id.size(); i++)\n    {\n        ofs << valence_three_error_feature_pt_id[i] << std::endl;\n    }\n    ofs.close();\n}\nvoid polycube_flattening_interface::save_feature_edges_vtk_vtkformat(const char* filename)\n{\n    if ((feature_edge_flag_final).empty()) return;\n    std::vector<int> feature_edge_array;\n    for (size_t i = 0; i < (feature_edge_flag_final).size(); i++)\n    {\n        if ((feature_edge_flag_final)[i] == true) feature_edge_array.push_back(i);\n    }\n    std::ofstream outputfile(filename);\n    outputfile << \"# vtk DataFile Version 3.0\\n\"\n        << \"mesh vtk data\\n\"\n        << \"ASCII\\n\"\n        << \"DATASET POLYDATA\\n\";\n    int n_point = dpx.size();\n    outputfile << \"POINTS \" << n_point << \" double\" << std::endl;\n    for (size_t i = 0; i < n_point; i++)\n    {\n        outputfile << dpx[i] << \" \" << dpy[i] << \" \" << dpz[i] << std::endl;\n    }\n    std::vector<int> feature_point_color(n_point, 0);\n    outputfile << \"LINES \" << feature_edge_array.size() << \" \" << 3 * feature_edge_array.size() << std::endl;\n    for (size_t i = 0; i < feature_edge_array.size(); i++)\n    {\n        int id0 = id2edge[feature_edge_array[i]].first;\n        int id1 = id2edge[feature_edge_array[i]].second;\n        feature_point_color[id0] = 1;\n        feature_point_color[id1] = 1;\n        outputfile << \"2 \" << id0 << \" \" << id1 << std::endl;\n    }\n    outputfile << \"POINT_DATA \" << n_point << \"\\n\"\n        << \"SCALARS V_Scalars int\\nLOOKUP_TABLE V_Table\" << std::endl;\n    for (size_t i = 0; i < n_point; i++)\n    {\n        outputfile << feature_point_color[i] << std::endl;\n    }\n    outputfile.close();\n}\nvoid polycube_flattening_interface::save_feature_long_edges_vtk_vtkformat(const char* filename)\n{\n    std::vector<bool> polycube_vertex_flag(dpx.size(), false);\n    for (size_t i = 0; i < polycube_edges.size(); i++)\n    {\n        polycube_vertex_flag[polycube_edges[i][0]] = true;\n        polycube_vertex_flag[polycube_edges[i][1]] = true;\n    }\n    std::vector<int> vert_o2n(dpx.size(), -1);\n    int count = 0;\n    for (size_t i = 0; i < dpx.size(); i++)\n    {\n        if (polycube_vertex_flag[i])\n            vert_o2n[i] = count++;\n    }\n    std::ofstream outputfile(filename);\n    outputfile << \"# vtk DataFile Version 3.0\\n\"\n        << \"mesh vtk data\\n\"\n        << \"ASCII\\n\"\n        << \"DATASET POLYDATA\\n\";\n    outputfile << \"POINTS \" << count << \" double\" << std::endl;\n    for (size_t i = 0; i < dpx.size(); i++)\n    {\n        if (polycube_vertex_flag[i])\n            outputfile << dpx[i] << \" \" << dpy[i] << \" \" << dpz[i] << std::endl;\n    }\n    std::vector<int> feature_point_color(count, 0);\n    outputfile << \"LINES \" << feature_polycube_edge.size() << \" \" << 3 * feature_polycube_edge.size() << std::endl;\n    for (size_t i = 0; i < feature_polycube_edge.size(); i++)\n    {\n        int id0 = vert_o2n[polycube_edges[feature_polycube_edge[i]][0]];\n        int id1 = vert_o2n[polycube_edges[feature_polycube_edge[i]][1]];\n        feature_point_color[id0] = 1;\n        feature_point_color[id1] = 1;\n        outputfile << \"2 \" << id0 << \" \" << id1 << std::endl;\n    }\n    outputfile << \"POINT_DATA \" << count << \"\\n\"\n        << \"SCALARS V_Scalars int\\nLOOKUP_TABLE V_Table\" << std::endl;\n    for (size_t i = 0; i < count; i++)\n    {\n        outputfile << feature_point_color[i] << std::endl;\n    }\n    outputfile.close();\n}\nvoid polycube_flattening_interface::save_feature_long_edges_vtk_psfeformat(const char* filename)\n{\n    std::vector<bool> polycube_vertex_flag(dpx.size(), false);\n    for (size_t i = 0; i < polycube_edges.size(); i++)\n    {\n        polycube_vertex_flag[polycube_edges[i][0]] = true;\n        polycube_vertex_flag[polycube_edges[i][1]] = true;\n    }\n    std::vector<int> vert_o2n(dpx.size(), -1);\n    int count = 0;\n    for (size_t i = 0; i < dpx.size(); i++)\n    {\n        if (polycube_vertex_flag[i])\n            vert_o2n[i] = count++;\n    }\n    std::ofstream outputfile(filename);\n    outputfile << \"POINTS \" << count << std::endl;\n    for (size_t i = 0; i < dpx.size(); i++)\n    {\n        if (polycube_vertex_flag[i])\n            outputfile << dpx[i] << \" \" << dpy[i] << \" \" << dpz[i] << std::endl;\n    }\n    assert(feature_polycube_edge_segm.size() == feature_polycube_edge.size());\n    outputfile << \"EDGES \" << feature_polycube_edge.size() << \" \" << std::endl;\n    for (size_t i = 0; i < feature_polycube_edge.size(); i++)\n    {\n        int id0 = vert_o2n[polycube_edges[feature_polycube_edge[i]][0]];\n        int id1 = vert_o2n[polycube_edges[feature_polycube_edge[i]][1]];\n        outputfile << id0 << \" \" << id1 << \" \";\n        outputfile << feature_polycube_edge_segm[i].first << \" \" << feature_polycube_edge_segm[i].second << std::endl;\n    }\n    outputfile.close();\n}\nvoid polycube_flattening_interface::prepare_for_deformation(TetStructure<double> *tet_mesh_, const std::vector<double> &x_ori, const std::vector<double> &y_ori, const std::vector<double> &z_ori)\n{\n    std::vector<OpenVolumeMesh::VertexHandle> hfv_vec(3);\n    std::vector<int> hfv_vec_id(3);\n    std::vector<OpenVolumeMesh::HalfFaceHandle> cell_hfh_vec(4);\n    unsigned nv = tet_mesh_->tetra_vertices.size(); unsigned nc = tet_mesh_->tetras.size();\n    vertex_cell.clear(); cell_vertex.clear();\n    vertex_cell.resize(nv); cell_vertex.resize(nc);\n    cell_vertex_vertex.clear(); S.clear(); S_v.clear(); cell_S.resize(nc);\n    cell_vertex_vertex.resize(nc); S.resize(nc); S_v.resize(nc);\n    vertex_cell_vertex.clear(); vertex_cell_vertex.resize(nv);\n    vcv_S.clear(); vcv_S.resize(nv);\n    cell_volume.clear(); cell_volume.resize(nc, 0.0);\n    Eigen::Matrix3d VS, IS; std::vector<double> S_(9);\n    vertex_move_d.clear(); vertex_move_d.resize(nv, 1.0e30);\n    static int s_tet_id[4][3] = { { 1, 2, 3}, {2, 0, 3}, {0, 1, 3}, {1, 0, 2} };\n    const std::vector<Tetrahedron<double>*> &tetras = tet_mesh_->tetras;\n    const std::vector<TetVertex<double>*> &tetra_vertices = tet_mesh_->tetra_vertices;\n    for (size_t c_id = 0; c_id < nc; ++c_id)\n    {\n        double cv_count = 0.0;\n        TetVertex<double> **tet_vert_ = tet_mesh_->tetras[c_id]->vertex;\n        cell_vertex[c_id].clear();\n        for (unsigned i = 0; i < 4; ++i)\n        {\n            int v_id = tet_vert_[i]->id;\n            cell_vertex[c_id].push_back(v_id);\n        }\n        int id0, id1, id2, id3;\n        id0 = tet_vert_[0]->id;\n        id1 = tet_vert_[1]->id;\n        id2 = tet_vert_[2]->id;\n        id3 = tet_vert_[3]->id;\n        CVec<double, 3> cp;\n        CVec<double, 3> cr;\n        CVec<double, 3> cs;\n        CVec<double, 3> ct;\n        cp[0] = x_ori[id0]; cp[1] = y_ori[id0]; cp[2] = z_ori[id0];\n        cr[0] = x_ori[id1]; cr[1] = y_ori[id1]; cr[2] = z_ori[id1];\n        cs[0] = x_ori[id2]; cs[1] = y_ori[id2]; cs[2] = z_ori[id2];\n        ct[0] = x_ori[id3]; ct[1] = y_ori[id3]; ct[2] = z_ori[id3];\n        cr = cr - cp;\n        cs = cs - cp;\n        ct = ct - cp;\n        VS(0, 0) = cr[0]; VS(1, 0) = cr[1]; VS(2, 0) = cr[2];\n        VS(0, 1) = cs[0]; VS(1, 1) = cs[1]; VS(2, 1) = cs[2];\n        VS(0, 2) = ct[0]; VS(1, 2) = ct[1]; VS(2, 2) = ct[2];\n        IS = VS.inverse();\n        cell_S[c_id] = IS;\n        S[c_id].resize(4); S_v[c_id].resize(4);\n        for (unsigned i = 0; i < 4; ++i)\n        {\n            S_v[c_id][i].reserve(9);\n            int v_id = tet_vert_[i]->id;\n            if (vertex_cell[v_id].size() == 0) vertex_cell[v_id].reserve(15);\n            vertex_cell[v_id].push_back(c_id);\n            hfv_vec_id[0] = tetras[c_id]->vertex[s_tet_id[i][0]]->id;\n            hfv_vec_id[1] = tetras[c_id]->vertex[s_tet_id[i][1]]->id;\n            hfv_vec_id[2] = tetras[c_id]->vertex[s_tet_id[i][2]]->id;\n            cell_vertex_vertex[c_id].push_back(hfv_vec_id);\n            vertex_cell_vertex[v_id].push_back(hfv_vec_id);\n            CVec<double, 3> p;\n            CVec<double, 3> r;\n            CVec<double, 3> s;\n            CVec<double, 3> t;\n            id0 = tetras[c_id]->vertex[i]->id;\n            id1 = hfv_vec_id[0];\n            id2 = hfv_vec_id[1];\n            id3 = hfv_vec_id[2];\n            p[0] = x_ori[id0]; p[1] = y_ori[id0]; p[2] = z_ori[id0];\n            r[0] = x_ori[id1]; r[1] = y_ori[id1]; r[2] = z_ori[id1];\n            s[0] = x_ori[id2]; s[1] = y_ori[id2]; s[2] = z_ori[id2];\n            t[0] = x_ori[id3]; t[1] = y_ori[id3]; t[2] = z_ori[id3];\n            r = r - p;\n            s = s - p;\n            t = t - p;\n            VS(0, 0) = r[0]; VS(1, 0) = r[1]; VS(2, 0) = r[2];\n            VS(0, 1) = s[0]; VS(1, 1) = s[1]; VS(2, 1) = s[2];\n            VS(0, 2) = t[0]; VS(1, 2) = t[1]; VS(2, 2) = t[2];\n            cell_volume[c_id] = -VS.determinant();\n            IS = VS.inverse();\n            S_[0] = IS(0, 0); S_[1] = IS(0, 1); S_[2] = IS(0, 2);\n            S_[3] = IS(1, 0); S_[4] = IS(1, 1); S_[5] = IS(1, 2);\n            S_[6] = IS(2, 0); S_[7] = IS(2, 1); S_[8] = IS(2, 2);\n            S[c_id][i] = IS;\n            S_v[c_id][i] = S_;\n            vcv_S[v_id].push_back(S_);\n        }\n    }\n    alpha = 100.0; mu_A = 1e3;\n    is_deformation_constraint.clear(); is_deformation_constraint.resize(nv, 0);\n    deformation_handle_id.clear(); deformation_handle_id.resize(nv, -1);\n    for (unsigned i = 0; i < deformation_v_id.size(); ++i)\n    {\n        is_deformation_constraint[deformation_v_id[i]] = 1;\n        deformation_handle_id[deformation_v_id[i]] = i;\n    }\n    dpx.resize(nv); dpy.resize(nv); dpz.resize(nv); max_vc_size = 0; src_pos.resize(nv);\n    for (int i = 0; i < nv; i++)\n    {\n        int v_id = i;\n        CVec<double, 3> p = tetra_vertices[i]->pos;\n        dpx[v_id] = p[0]; dpy[v_id] = p[1]; dpz[v_id] = p[2];\n        OpenVolumeMesh::Geometry::Vec3d p_temp;\n        p_temp[0] = x_ori[i]; p_temp[1] = y_ori[i]; p_temp[2] = z_ori[i];\n        src_pos[v_id] = p_temp;\n        int vc_size = vertex_cell[v_id].size();\n        if (vc_size > max_vc_size)\n        {\n            max_vc_size = vc_size;\n        }\n    }\n    bfv_id.clear(); bfv_id.resize(nc, OpenVolumeMesh::Geometry::Vec3i(-1, -1, -1));\n    bvf_id.clear(); bvf_id.resize(nv); boundary_face_number = 0; avg_boundary_edge_length = 0.0;\n    int edge_count = 0;\n    edge2id.clear();\n    id2edge.clear();\n    std::map<std::pair<int, int>, int>::iterator edge_it;\n    for (size_t i = 0; i < nc; i++)\n    {\n        if (!tetras[i]->is_onboundary())\n        {\n            continue;\n        }\n        int bf_id = -1;\n        for (size_t j = 0; j < 4; j++)\n        {\n            if (!tetras[i]->vertex[j]->boundary)\n            {\n                bf_id = j;\n                break;\n            }\n        }\n        if (bf_id == -1)\n        {\n            std::cout << \"four verts on boundary!\" << std::endl;\n            return;\n        }\n        int idx0, idx1, idx2;\n        idx0 = tetras[i]->vertex[s_tet_id[bf_id][0]]->id;\n        idx1 = tetras[i]->vertex[s_tet_id[bf_id][1]]->id;\n        idx2 = tetras[i]->vertex[s_tet_id[bf_id][2]]->id;\n        std::pair<int, int> edge0(idx0, idx1), edge1(idx1, idx2), edge2(idx2, idx0);\n        if (idx0 < idx1)\n        {\n            edge2id.insert(std::pair<std::pair<int, int>, int>(edge0, edge_count));\n            id2edge.push_back(edge0);\n            edge_count++;\n        }\n        if (idx1 < idx2)\n        {\n            edge2id.insert(std::pair<std::pair<int, int>, int>(edge1, edge_count));\n            id2edge.push_back(edge1);\n            edge_count++;\n        }\n        if (idx2 < idx0)\n        {\n            edge2id.insert(std::pair<std::pair<int, int>, int>(edge2, edge_count));\n            id2edge.push_back(edge2);\n            edge_count++;\n        }\n    }\n    bef_id.clear(); bef_id.resize(edge_count);\n    for (size_t i = 0; i < nc; i++)\n    {\n        if (!tetras[i]->is_onboundary())\n        {\n            continue;\n        }\n        int bf_id = -1;\n        for (size_t j = 0; j < 4; j++)\n        {\n            if (!tetras[i]->vertex[j]->boundary)\n            {\n                bf_id = j;\n                break;\n            }\n        }\n        if (bf_id == -1)\n        {\n            std::cout << \"four verts on boundary!\" << std::endl;\n            return;\n        }\n        ++boundary_face_number;\n        int idx0, idx1, idx2;\n        idx0 = tetras[i]->vertex[s_tet_id[bf_id][0]]->id;\n        idx1 = tetras[i]->vertex[s_tet_id[bf_id][1]]->id;\n        idx2 = tetras[i]->vertex[s_tet_id[bf_id][2]]->id;\n        bfv_id[i][0] = idx0;\n        bfv_id[i][1] = idx1;\n        bfv_id[i][2] = idx2;\n        bvf_id[idx0].push_back(i);\n        bvf_id[idx1].push_back(i);\n        bvf_id[idx2].push_back(i);\n        int min_id, mid_id, max_id;\n        min_id = std::min(std::min(idx0, idx1), idx2);\n        max_id = std::max(std::max(idx0, idx1), idx2);\n        mid_id = idx0 + idx1 + idx2 - min_id - max_id;\n        std::pair<int, int> edge0(min_id, mid_id), edge1(min_id, max_id), edge2(mid_id, max_id);\n        int e_id0 = edge2id[edge0];\n        bef_id[e_id0].push_back(i);\n        int e_id1 = edge2id[edge1];\n        bef_id[e_id1].push_back(i);\n        int e_id2 = edge2id[edge2];\n        bef_id[e_id2].push_back(i);\n    }\n    bvv_id.clear(); bvv_id.resize(nv);\n    for (int i = 0; i < nv; ++i)\n    {\n        if (bvf_id[i].size() > 0)\n        {\n            std::vector<int>& one_ring_f_id = bvf_id[i]; int one_ring_size = one_ring_f_id.size();\n            std::vector<int> one_ring_v_id(one_ring_size); std::vector<int> one_ring_v_f_id(one_ring_size);\n            std::vector<int> one_ring_order(one_ring_size);\n            for (int j = 0; j < one_ring_size; ++j)\n            {\n                OpenVolumeMesh::Geometry::Vec3i& fv_id = bfv_id[one_ring_f_id[j]];\n                for (int k = 0; k < 3; ++k)\n                {\n                    if (i == fv_id[k])\n                    {\n                        one_ring_order[j] = k;\n                        break;\n                    }\n                }\n            }\n            OpenVolumeMesh::Geometry::Vec3i& fv_id = bfv_id[one_ring_f_id[0]];\n            int start_v = fv_id[(one_ring_order[0] + 1) % 3];\n            int v2 = start_v; one_ring_v_id[0] = v2; one_ring_v_f_id[0] = one_ring_f_id[0];\n            int v3 = fv_id[(one_ring_order[0] + 2) % 3];\n            for (int j = 1; j < one_ring_size; ++j)\n            {\n                v2 = v3;\n                if (v2 == start_v) break;\n                one_ring_v_id[j] = v2;\n                for (int k = 1; k < one_ring_size; ++k)\n                {\n                    OpenVolumeMesh::Geometry::Vec3i& fv_id = bfv_id[one_ring_f_id[k]];\n                    if (fv_id[(one_ring_order[k] + 1) % 3] == v2)\n                    {\n                        v3 = fv_id[(one_ring_order[k] + 2) % 3];\n                        one_ring_v_f_id[j] = one_ring_f_id[k];\n                        break;\n                    }\n                }\n            }\n            bvv_id[i] = one_ring_v_id;\n            bvf_id[i] = one_ring_v_f_id;\n        }\n    }\n    avg_boundary_edge_length = 0.0; OpenVolumeMesh::Geometry::Vec3d p0, p1, p2; double count = 0.0;\n    for (int i = 0; i < bfv_id.size(); ++i)\n    {\n        OpenVolumeMesh::Geometry::Vec3i& one_bfv_id = bfv_id[i];\n        if (one_bfv_id[0] < 0) continue;\n        p0[0] = dpx[one_bfv_id[0]]; p0[1] = dpy[one_bfv_id[0]]; p0[2] = dpz[one_bfv_id[0]];\n        p1[0] = dpx[one_bfv_id[1]]; p1[1] = dpy[one_bfv_id[1]]; p1[2] = dpz[one_bfv_id[1]];\n        p2[0] = dpx[one_bfv_id[2]]; p2[1] = dpy[one_bfv_id[2]]; p2[2] = dpz[one_bfv_id[2]];\n        avg_boundary_edge_length += (p0 - p1).norm();\n        avg_boundary_edge_length += (p1 - p2).norm();\n        avg_boundary_edge_length += (p2 - p0).norm();\n        count += 3.0;\n    }\n    avg_boundary_edge_length /= count;\n    rest_v_id.clear(); rotate_v_id.clear(); rotate_radius.clear(); rotate_angle.clear();\n#if 0\n    deformation_v_id.clear(); deformation_new_p.clear(); deformation_ok.clear();\n    is_deformation_constraint.clear(); is_deformation_constraint.resize(nv, 0);\n    for (OpenVolumeMesh::VertexIter v_it = mesh_->vertices_begin(); v_it != mesh_->vertices_end(); ++v_it)\n    {\n        int v_id = v_it->idx();\n        OpenVolumeMesh::Geometry::Vec3d p = mesh_->vertex(*v_it);\n#if 1\n        if (std::abs(p[2] + 19.5) < 1e-6)\n        {\n            rest_v_id.push_back(v_id);\n            deformation_v_id.push_back(v_id); deformation_new_p.push_back(p); deformation_ok.push_back(1);\n            is_deformation_constraint[v_id] = 1;\n        }\n#else\n        if (std::abs(p[2] + 19.5) < 1e-6 && std::abs(std::abs(p[1]) - 5) < 1e-6 && std::abs(std::abs(p[0]) - 5) < 1e-6)\n        {\n            rest_v_id.push_back(v_id);\n            deformation_v_id.push_back(v_id); deformation_new_p.push_back(p); deformation_ok.push_back(1);\n            is_deformation_constraint[v_id] = 1;\n        }\n        else if (std::abs(p[2] + 19.5) < 1e-6 && std::abs(p[1]) < 1e-6 && std::abs(p[0]) < 1e-6)\n        {\n            rest_v_id.push_back(v_id);\n            deformation_v_id.push_back(v_id); deformation_new_p.push_back(p); deformation_ok.push_back(1);\n            is_deformation_constraint[v_id] = 1;\n        }\n#endif\n        else if (std::abs(p[2] - 19.5) < 1e-6)\n        {\n            if (std::abs(p[1]) < 1e-6 && std::abs(p[0]) < 1e-6)\n            {\n                rest_v_id.push_back(v_id);\n                deformation_v_id.push_back(v_id); deformation_new_p.push_back(p); deformation_ok.push_back(1);\n            }\n#if 1\n            else\n#else\n            else if (std::abs(std::abs(p[1]) - 5) < 1e-6 && std::abs(std::abs(p[0]) - 5) < 1e-6)\n#endif\n            {\n                rotate_v_id.push_back(v_id);\n                rotate_radius.push_back(std::sqrt(p[1] * p[1] + p[0] * p[0]));\n                rotate_angle.push_back(std::atan2(p[1], p[0]));\n                deformation_v_id.push_back(v_id); deformation_new_p.push_back(p); deformation_ok.push_back(1);\n            }\n            is_deformation_constraint[v_id] = 1;\n        }\n    }\n#endif\n    prepare_ok = true;\n}\nvoid polycube_flattening_interface::build_AABB_Tree()\n{\n    if (AABB_Tree) { delete AABB_Tree; AABB_Tree = NULL; }\n    unsigned nf = bfv_id.size();\n    if (nf == 0) return;\n    triangle_vectors.clear(); triangle_vectors.reserve(nf);\n    OpenVolumeMesh::Geometry::Vec3d p0, p1, p2;\n    for (int i = 0; i < nf; ++i)\n    {\n        OpenVolumeMesh::Geometry::Vec3i& fv_id = bfv_id[i];\n        if (fv_id[0] >= 0)\n        {\n            p0 = OpenVolumeMesh::Geometry::Vec3d(dpx[fv_id[0]], dpy[fv_id[0]], dpz[fv_id[0]]);\n            p1 = OpenVolumeMesh::Geometry::Vec3d(dpx[fv_id[1]], dpy[fv_id[1]], dpz[fv_id[1]]);\n            p2 = OpenVolumeMesh::Geometry::Vec3d(dpx[fv_id[2]], dpy[fv_id[2]], dpz[fv_id[2]]);\n            CGAL_double_3_Point q0(p0[0], p0[1], p0[2]);\n            CGAL_double_3_Point q1(p1[0], p1[1], p1[2]);\n            CGAL_double_3_Point q2(p2[0], p2[1], p2[2]);\n            triangle_vectors.push_back(CGAL_3_Triangle(q0, q1, q2));\n        }\n    }\n    AABB_Tree = new CGAL_AABB_Tree(triangle_vectors.begin(), triangle_vectors.end());\n    AABB_Tree->accelerate_distance_queries();\n    printf(\"Finish Constructing AABB Tree.\\n\");\n    tan_smooth = true;\n}\nvoid polycube_flattening_interface::project_on_ref_mesh(OpenVolumeMesh::Geometry::Vec3d& p)\n{\n    CGAL_double_3_Point pos = AABB_Tree->closest_point(CGAL_double_3_Point(p[0], p[1], p[2]));\n    p = OpenVolumeMesh::Geometry::Vec3d(pos.x(), pos.y(), pos.z());\n}\nvoid polycube_flattening_interface::project_on_ref_mesh(double& px, double& py, double& pz)\n{\n    CGAL_double_3_Point pos = AABB_Tree->closest_point(CGAL_double_3_Point(px, py, pz));\n    px = pos.x(); py = pos.y(); pz = pos.z();\n}\nvoid polycube_flattening_interface::assign_pos_mesh(TetStructure<double>* tet_mesh_, bool r_order)\n{\n    if (r_order)\n    {\n        int nv = tet_mesh_->tetra_vertices.size();\n        const std::vector<TetVertex<double>*> &tetra_vertices = tet_mesh_->tetra_vertices;\n        for (size_t i = 0; i < nv; i++)\n        {\n            CVec<double, 3> p = tetra_vertices[i]->pos;\n            dpx[i] = p[0]; dpy[i] = p[1]; dpz[i] = p[2];\n        }\n    }\n    else\n    {\n        int nv = tet_mesh_->tetra_vertices.size();\n        std::vector<TetVertex<double>*> &tetra_vertices = tet_mesh_->tetra_vertices;\n        for (size_t i = 0; i < nv; i++)\n        {\n            CVec<double, 3> p(dpx[i], dpy[i], dpz[i]);\n            tetra_vertices[i]->pos = p;\n        }\n    }\n}\nvoid polycube_flattening_interface::get_coord(const std::vector<int>& all_vert, std::vector<double> &coord_x, std::vector<double> &coord_y, std::vector<double> &coord_z)\n{\n    coord_x.clear();\n    coord_y.clear();\n    coord_z.clear();\n    for (size_t i = 0; i < all_vert.size(); i++)\n    {\n        int v_id = all_vert[i];\n        coord_x.push_back(dpx[v_id]);\n        coord_y.push_back(dpy[v_id]);\n        coord_z.push_back(dpz[v_id]);\n    }\n}\nig::CVec<double, 3> polycube_flattening_interface::compute_volumetric_distortion(TetStructure<double>* tet_mesh_)\n{\n    Eigen::Matrix3d VS, A; Eigen::Vector3d a;\n    double max_cd = 0.0; double min_cd = 1e30; double avg_cd = 0.0; int max_cd_cell_id = -1;\n    double max_iso = 0.0; double min_iso = 1e30; double avg_iso = 0.0; int max_iso_cell_id = -1;\n    double max_vol = 0.0; double min_vol = 1e30; double avg_vol = 0.0; int max_vol_cell_id = -1;\n    double cd_count = 0.0; int flip_count = 0; flipped_cell.clear();\n    double volume_count = 0.0;\n    std::vector<double> all_iso_d; std::vector<double> all_con_d; std::vector<double> all_vol_d;\n    int nc = tet_mesh_->tetras.size();\n    for (int c_id = 0; c_id < nc; ++c_id)\n    {\n        TetVertex<double> **tet_vert_ = tet_mesh_->tetras[c_id]->vertex;\n        bool boundary_flag = false;\n        for (unsigned i = 0; i < 4; ++i)\n        {\n            if (tet_vert_[i]->boundary)\n                boundary_flag = true;\n        }\n        std::vector<int>& cv_id = cell_vertex[c_id];\n        double cpx = dpx[cv_id[0]]; double cpy = dpy[cv_id[0]]; double cpz = dpz[cv_id[0]];\n        VS(0, 0) = dpx[cv_id[1]] - cpx; VS(1, 0) = dpy[cv_id[1]] - cpy; VS(2, 0) = dpz[cv_id[1]] - cpz;\n        VS(0, 1) = dpx[cv_id[2]] - cpx; VS(1, 1) = dpy[cv_id[2]] - cpy; VS(2, 1) = dpz[cv_id[2]] - cpz;\n        VS(0, 2) = dpx[cv_id[3]] - cpx; VS(1, 2) = dpy[cv_id[3]] - cpy; VS(2, 2) = dpz[cv_id[3]] - cpz;\n        A = VS * cell_S[c_id];\n        if (A.determinant() < 0)\n        {\n            ++flip_count;\n            flipped_cell.push_back(OpenVolumeMesh::CellHandle(c_id));\n            all_iso_d.push_back(-1);\n            all_con_d.push_back(-1);\n            all_vol_d.push_back(-1);\n        }\n        else\n        {\n            double volume = tet_mesh_->tetras[c_id]->compute_tet_volume();\n            Eigen::JacobiSVD<Eigen::Matrix3d> svd(A);\n            a = svd.singularValues();\n            double cd = a(0) / a(2);\n            if (cd > max_cd) { max_cd = cd; max_cd_cell_id = c_id; }\n            if (cd < min_cd) min_cd = cd;\n            avg_cd += volume * cd;\n            cd_count += 1.0;\n            all_con_d.push_back(volume * cd);\n            double iso_d = a(0) > 1.0 / a(2) ? a(0) : 1.0 / a(2);\n            if (iso_d > max_iso) { max_iso = iso_d; max_iso_cell_id = c_id; }\n            if (iso_d < min_iso) min_iso = iso_d;\n            avg_iso += volume * iso_d;\n            all_iso_d.push_back(volume * iso_d);\n            volume_count += volume;\n            double dJ = a(0)*a(1)*a(2);\n            double vol_d = dJ > 1.0 / dJ ? dJ : 1.0 / dJ;\n            if (vol_d > max_vol) { max_vol = vol_d; max_vol_cell_id = c_id; }\n            if (vol_d < min_vol) min_vol = vol_d;\n            avg_vol += volume * vol_d;\n            all_vol_d.push_back(volume * vol_d);\n        }\n    }\n    avg_cd /= volume_count;\n    avg_iso /= volume_count;\n    avg_vol /= volume_count;\n    double std_id = 0.0; double std_cd = 0.0; double std_vd = 0.0;\n    for (int i = 0; i < all_iso_d.size(); ++i)\n    {\n        if (all_iso_d[i] > 0)\n        {\n            std_cd += (avg_cd - all_con_d[i])*(avg_cd - all_con_d[i]);\n            std_id += (avg_iso - all_iso_d[i])*(avg_iso - all_iso_d[i]);\n            std_vd += (avg_vol - all_vol_d[i])*(avg_vol - all_vol_d[i]);\n        }\n    }\n    std_id = std::sqrt(std_id / (cd_count - 1)); std_cd = std::sqrt(std_cd / (cd_count - 1)); std_vd = std::sqrt(std_vd / (cd_count - 1));\n    printf(\"---------------------------------------------------------\\n\");\n    printf(\"Volumetric Weighted Isometric Distortion: %f/%f/%f/%f\\n\", max_iso, min_iso, avg_iso, std_id);\n    printf(\"Volumetric Weighted conformal Distortion: %f/%f/%f/%f\\n\", max_cd, min_cd, avg_cd, std_cd);\n    printf(\"Volumetric Weighted volume Distortion: %f/%f/%f/%f\\n\", max_vol, min_vol, avg_vol, std_vd);\n    return ig::CVec<double, 3>(avg_iso, avg_cd, avg_vol);\n}\nig::CVec<double, 3> polycube_flattening_interface::compute_distortion(TetStructure<double>* tet_mesh_)\n{\n    Eigen::Matrix3d VS, A; Eigen::Vector3d a;\n    double max_cd = 0.0; double min_cd = 1e30; double avg_cd = 0.0; int max_cd_cell_id = -1;\n    double max_iso = 0.0; double min_iso = 1e30; double avg_iso = 0.0; int max_iso_cell_id = -1;\n    double max_vol = 0.0; double min_vol = 1e30; double avg_vol = 0.0; int max_vol_cell_id = -1;\n    double cd_count = 0.0; int flip_count = 0; flipped_cell.clear();\n    int nc = tet_mesh_->tetras.size();\n    all_iso_d.clear(); all_con_d.clear(); all_vol_d.clear();\n    for (int c_id = 0; c_id < nc; ++c_id)\n    {\n        std::vector<int>& cv_id = cell_vertex[c_id];\n        double cpx = dpx[cv_id[0]]; double cpy = dpy[cv_id[0]]; double cpz = dpz[cv_id[0]];\n        VS(0, 0) = dpx[cv_id[1]] - cpx; VS(1, 0) = dpy[cv_id[1]] - cpy; VS(2, 0) = dpz[cv_id[1]] - cpz;\n        VS(0, 1) = dpx[cv_id[2]] - cpx; VS(1, 1) = dpy[cv_id[2]] - cpy; VS(2, 1) = dpz[cv_id[2]] - cpz;\n        VS(0, 2) = dpx[cv_id[3]] - cpx; VS(1, 2) = dpy[cv_id[3]] - cpy; VS(2, 2) = dpz[cv_id[3]] - cpz;\n        A = VS * cell_S[c_id];\n        if (A.determinant() < 0)\n        {\n            ++flip_count;\n            flipped_cell.push_back(OpenVolumeMesh::CellHandle(c_id));\n            all_iso_d.push_back(-1);\n            all_con_d.push_back(-1);\n            all_vol_d.push_back(-1);\n        }\n        else\n        {\n            Eigen::JacobiSVD<Eigen::Matrix3d> svd(A);\n            a = svd.singularValues();\n            double cd = a(0) / a(2);\n            if (cd > max_cd) { max_cd = cd; max_cd_cell_id = c_id; }\n            if (cd < min_cd) min_cd = cd;\n            avg_cd += cd; cd_count += 1.0;\n            all_con_d.push_back(cd);\n            double iso_d = a(0) > 1.0 / a(2) ? a(0) : 1.0 / a(2);\n            if (iso_d > max_iso) { max_iso = iso_d; max_iso_cell_id = c_id; }\n            if (iso_d < min_iso) min_iso = iso_d;\n            avg_iso += iso_d;\n            all_iso_d.push_back(iso_d);\n            double dJ = a(0)*a(1)*a(2);\n            double vol_d = dJ > 1.0 / dJ ? dJ : 1.0 / dJ;\n            if (vol_d > max_vol) { max_vol = vol_d; max_vol_cell_id = c_id; }\n            if (vol_d < min_vol) min_vol = vol_d;\n            avg_vol += vol_d;\n            all_vol_d.push_back(vol_d);\n        }\n    }\n    avg_cd /= cd_count; avg_iso /= cd_count; avg_vol /= cd_count;\n    double std_id = 0.0; double std_cd = 0.0; double std_vd = 0.0;\n    for (int i = 0; i < all_iso_d.size(); ++i)\n    {\n        if (all_iso_d[i] > 0)\n        {\n            std_cd += (avg_cd - all_con_d[i])*(avg_cd - all_con_d[i]);\n            std_id += (avg_iso - all_iso_d[i])*(avg_iso - all_iso_d[i]);\n            std_vd += (avg_vol - all_vol_d[i])*(avg_vol - all_vol_d[i]);\n        }\n    }\n    std_id = std::sqrt(std_id / (cd_count - 1)); std_cd = std::sqrt(std_cd / (cd_count - 1)); std_vd = std::sqrt(std_vd / (cd_count - 1));\n    printf(\"---------------------------------------------------------\\n\");\n    printf(\"Flip Count : %d\\n\", flip_count);\n    printf(\"Isometric Distortion: %f/%f/%f/%f\\n\", max_iso, min_iso, avg_iso, std_id);\n    printf(\"conformal Distortion: %f/%f/%f/%f\\n\", max_cd, min_cd, avg_cd, std_cd);\n    printf(\"volume Distortion: %f/%f/%f/%f\\n\", max_vol, min_vol, avg_vol, std_vd);\n    return ig::CVec<double, 3>(avg_iso, avg_cd, avg_vol);\n}\nvoid polycube_flattening_interface::get_chart_distortion()\n{\n    chart_iso_d.clear();\n    chart_iso_d.resize(polycube_chart.size());\n    chart_con_d.clear();\n    chart_con_d.resize(polycube_chart.size());\n    chart_vol_d.clear();\n    chart_vol_d.resize(polycube_chart.size());\n    if (all_iso_d.size() == 0)\n    {\n        std::cout << \"distortion not computed yet!\" << std::endl;\n        return;\n    }\n    for (size_t i = 0; i < polycube_chart.size(); i++)\n    {\n        double count = 0.0;\n        double all_distortion = 0.0;\n        double con_distortion = 0.0;\n        double vol_distortion = 0.0;\n        for (size_t j = 0; j < polycube_chart[i].size(); j++)\n        {\n            if (all_iso_d[polycube_chart[i][j]] > 0)\n            {\n                all_distortion += all_iso_d[polycube_chart[i][j]];\n                con_distortion += all_con_d[polycube_chart[i][j]];\n                vol_distortion += all_vol_d[polycube_chart[i][j]];\n                count = count + 1.0;\n            }\n        }\n        chart_iso_d[i] = all_distortion / count;\n        chart_con_d[i] = con_distortion / count;\n        chart_vol_d[i] = vol_distortion / count;\n    }\n}\nvoid polycube_flattening_interface::get_polycube_edge_layer_distortion(int n_layer, TetStructure<double> *tet_mesh_)\n{\n    if (edge_with_same_label.size() == 0)\n        return;\n    std::vector<double> tmp_distortion(edge_with_same_label.size(), 0);\n    polycube_edge_layer_distortion.clear();\n    polycube_edge_layer_distortion.resize(polycube_edges.size());\n    const std::vector<Tetrahedron<double>*> &tetras = tet_mesh_->tetras;\n    const std::vector<TetVertex<double>*> &tetra_vertices = tet_mesh_->tetra_vertices;\n    std::map<Tetrahedron<double>*, int> tet2id;\n    int nc = tet_mesh_->tetras.size();\n    for (size_t i = 0; i < nc; i++)\n    {\n        tet2id[tetras[i]] = i;\n    }\n    for (size_t i = 0; i < edge_with_same_label.size(); i++)\n    {\n        std::vector<int> edge_layer_flag;\n        edge_layer_flag.resize(nc, -1);\n        std::vector<int> edge_layer_idx;\n        for (int j = 0; j < edge_with_same_label[i].size(); ++j)\n        {\n            int edge_id = edge_with_same_label[i][j];\n            int face1 = bef_id[edge_id][0];\n            int face2 = bef_id[edge_id][1];\n            edge_layer_flag[face1] = 1;\n            edge_layer_flag[face2] = 1;\n            edge_layer_idx.push_back(face1);\n            edge_layer_idx.push_back(face2);\n        }\n        for (size_t iter = 0; iter < n_layer; iter++)\n        {\n            std::vector<int> added_idx;\n            for (size_t j = 0; j < edge_layer_idx.size(); j++)\n            {\n                const Tetrahedron<double>* temp_tet = tetras[edge_layer_idx[j]];\n                for (size_t k = 0; k < 4; k++)\n                {\n                    Tetrahedron<double>* neighbor = temp_tet->neighborTet[k];\n                    if (neighbor != NULL)\n                    {\n                        int idx = tet2id[neighbor];\n                        if (edge_layer_flag[idx] < 0)\n                        {\n                            added_idx.push_back(idx);\n                        }\n                    }\n                }\n            }\n            edge_layer_idx.insert(edge_layer_idx.begin(), added_idx.begin(), added_idx.end());\n            for (size_t j = 0; j < added_idx.size(); j++)\n            {\n                edge_layer_flag[added_idx[j]] = 1;\n            }\n        }\n        double chart_distortion = 0.0;\n        double count = 0.0;\n        for (size_t j = 0; j < edge_layer_idx.size(); j++)\n        {\n            int idx = edge_layer_idx[j];\n            if (all_iso_d[idx] > 0)\n            {\n                chart_distortion += all_iso_d[idx];\n                count = count + 1;\n            }\n        }\n        tmp_distortion[i] = chart_distortion / count;\n    }\n    for (size_t i = 0; i < polycube_edges.size(); i++)\n    {\n        int tmp_idx = polycube_edge_idx2same_label_idx[i];\n        polycube_edge_layer_distortion[i] = tmp_distortion[tmp_idx];\n    }\n}\nvoid polycube_flattening_interface::compute_triangle_area()\n{\n    double max_diff = 0.0;\n    double ave_diff = 0.0;\n    for (size_t i = 0; i < equal_triangles.size(); i++)\n    {\n        double x[6], y[6], z[6];\n        for (size_t j = 0; j < 6; j++)\n        {\n            x[j] = dpx[equal_triangles[i][j]];\n            y[j] = dpy[equal_triangles[i][j]];\n            z[j] = dpz[equal_triangles[i][j]];\n        }\n        Eigen::Vector3d vec1(x[1] - x[0], y[1] - y[0], z[1] - z[0]);\n        Eigen::Vector3d vec2(x[2] - x[0], y[2] - y[0], z[2] - z[0]);\n        double area1 = vec1.cross(vec2).norm();\n        Eigen::Vector3d vec3(x[4] - x[3], y[4] - y[3], z[4] - z[3]);\n        Eigen::Vector3d vec4(x[5] - x[3], y[5] - y[3], z[5] - z[3]);\n        double area2 = vec3.cross(vec4).norm();\n        double diff = abs(area1 - area2);\n        if (max_diff < diff)\n            max_diff = diff;\n        ave_diff += diff;\n    }\n    ave_diff = ave_diff / (equal_triangles.size() + 1e-8);\n}\n\nvoid polycube_flattening_interface::find_all_corner(TetStructure<double>* tet_mesh_)\n{\n    int chart_size = polycube_chart_label.size();\n    std::vector<int> with_big_diff_chart; std::vector<double> max_chart; std::vector<int> min_chart;\n    const std::vector<TetVertex<double>*> &tetra_vertices = tet_mesh_->tetra_vertices;\n    for (int i = 0; i < chart_size; ++i)\n    {\n        int chart_label = polycube_chart_label[i] / 2; double sum = 0.0;\n        std::vector<int>& one_chart = polycube_chart[i]; double max_value = -1e30; double min_value = 1e30;\n        for (int j = 0; j < one_chart.size(); ++j)\n        {\n            int bf_id = one_chart[j]; double one_face_sum = 0.0;\n            for (int k = 0; k < 3; ++k)\n            {\n                one_face_sum += tetra_vertices[bfv_id[bf_id][k]]->pos[chart_label];\n            }\n            double xyz_value = one_face_sum / 3.0;\n            sum += xyz_value;\n            if (max_value < xyz_value) max_value = xyz_value;\n            if (min_value > xyz_value) min_value = xyz_value;\n        }\n        double max_diff = max_value - min_value;\n        chart_mean_value[i] = 0.5*(max_value + min_value);\n        if (max_diff > 0.001)\n        {\n            with_big_diff_chart.push_back(i); max_chart.push_back(max_value); min_chart.push_back(min_value);\n        }\n    }\n}\nbool polycube_flattening_interface::find_all_chart_value_equal_face_mine(TetStructure<double> *tet_mesh_, double offset)\n{\n    find_all_corner(tet_mesh_);\n    std::vector<MSKboundkeye> bkc; std::vector<double> blc; std::vector<double> buc;\n    std::vector<MSKboundkeye> bkx; std::vector<double> blx; std::vector<double> bux;\n    std::vector<MSKlidxt> aptrb; std::vector<MSKidxt> asub; std::vector<double> aval;\n    std::vector<MSKidxt> qsubi; std::vector<MSKidxt> qsubj; std::vector<double> qval;\n    double ratio_diff = 0.8;\n    std::vector< Eigen::Triplet<double> > coef;\n    int up_down_chart_count = up_chart_id.size();\n    int chart_number = chart_mean_value.size();\n    double diff_u_d; int up_chart, down_chart;\n    for (int i = 0; i < up_down_chart_count; ++i)\n    {\n        up_chart = up_chart_id[i];\n        down_chart = down_chart_id[i];\n        diff_u_d = diff_up_down[i] * ratio_diff;\n        if (hex_meshing_flag)\n        {\n            if (diff_u_d < cube_len)\n            {\n                diff_u_d = cube_len;\n            }\n            coef.push_back(Eigen::Triplet<double>(i, up_chart, +1.0));\n            coef.push_back(Eigen::Triplet<double>(i, down_chart, -1.0));\n            bkc.push_back(MSK_BK_LO); blc.push_back(diff_u_d / cube_len); buc.push_back(+MSK_INFINITY);\n        }\n        else\n        {\n            coef.push_back(Eigen::Triplet<double>(i, up_chart, +1.0));\n            coef.push_back(Eigen::Triplet<double>(i, down_chart, -1.0));\n            bkc.push_back(MSK_BK_LO); blc.push_back(diff_u_d); buc.push_back(+MSK_INFINITY);\n        }\n    }\n    int cut_num = 0;\n    cut_num = cut_to_chart_pair.size();\n    for (size_t i = 0; i < cut_num; i++)\n    {\n        int chart1 = cut_to_chart_pair[i].first;\n        int chart2 = cut_to_chart_pair[i].second;\n        if (cut_to_chart_pair_neighbor.size() == 0)\n        {\n            std::vector<int> chart1_idx, chart2_idx;\n            for (size_t j = 0; j < polycube_edges.size(); j++)\n            {\n                if ((polycube_edges[j][2] == chart1 && polycube_edges[j][3] != chart2)\n                    || (polycube_edges[j][3] == chart1 && polycube_edges[j][2] != chart2))\n                    chart1_idx.push_back(j);\n                if ((polycube_edges[j][2] == chart2 && polycube_edges[j][3] != chart1)\n                    || (polycube_edges[j][3] == chart2 && polycube_edges[j][2] != chart1))\n                    chart2_idx.push_back(j);\n            }\n            int final_idx1(-1), final_idx2(-1);\n            for (size_t j = 0; j < chart1_idx.size(); j++)\n            {\n                if (up_chart_id[chart1_idx[j]] == chart2 || down_chart_id[chart1_idx[j]] == chart2)\n                {\n                    final_idx1 = chart1_idx[j];\n                    break;\n                }\n            }\n            for (size_t j = 0; j < chart2_idx.size(); j++)\n            {\n                if (up_chart_id[chart2_idx[j]] == chart1 || down_chart_id[chart2_idx[j]] == chart1)\n                {\n                    final_idx2 = chart2_idx[j];\n                    break;\n                }\n            }\n            coef.push_back(Eigen::Triplet<double>(i + up_down_chart_count, up_chart_id[final_idx1], +1.0));\n            coef.push_back(Eigen::Triplet<double>(i + up_down_chart_count, down_chart_id[final_idx1], -1.0));\n            coef.push_back(Eigen::Triplet<double>(i + up_down_chart_count, up_chart_id[final_idx2], -1.0));\n            coef.push_back(Eigen::Triplet<double>(i + up_down_chart_count, down_chart_id[final_idx2], +1.0));\n            bkc.push_back(MSK_BK_FX); blc.push_back(0.0); buc.push_back(0.0);\n        }\n        else\n        {\n            int up1, up2, down1, down2;\n            up1 = cut_to_chart_pair_neighbor[i].first;\n            down1 = cut_to_chart_pair[i].second;\n            up2 = cut_to_chart_pair[i].first;\n            down2 = cut_to_chart_pair_neighbor[i].second;\n            if (chart_mean_value[up1] < chart_mean_value[down1])\n            {\n                int temp = up1;\n                up1 = down1;\n                down1 = temp;\n            }\n            if (chart_mean_value[up2] < chart_mean_value[down2])\n            {\n                int temp = up2;\n                up2 = down2;\n                down2 = temp;\n            }\n            coef.push_back(Eigen::Triplet<double>(i + up_down_chart_count, up1, +1.0));\n            coef.push_back(Eigen::Triplet<double>(i + up_down_chart_count, down1, -1.0));\n            coef.push_back(Eigen::Triplet<double>(i + up_down_chart_count, up2, -1.0));\n            coef.push_back(Eigen::Triplet<double>(i + up_down_chart_count, down2, +1.0));\n            bkc.push_back(MSK_BK_FX); blc.push_back(0.0); buc.push_back(0.0);\n        }\n    }\n    int three_cut_num = 0;\n    three_cut_num = three_cut_adjacent_one_cut_index.size();\n    for (size_t i = 0; i < three_cut_num; i++)\n    {\n        std::vector<int> six_chart, chart_x, chart_y, chart_z;\n        for (size_t j = 0; j < 3; j++)\n        {\n            six_chart.push_back(cut_to_chart_pair[three_cut_adjacent_one_cut_index[i][j]].first);\n            six_chart.push_back(cut_to_chart_pair[three_cut_adjacent_one_cut_index[i][j]].second);\n        }\n        for (size_t j = 0; j < 6; j++)\n        {\n            int temp_label = polycube_chart_label[six_chart[j]] / 2;\n            if (temp_label == 0)\n                chart_x.push_back(six_chart[j]);\n            else if (temp_label == 1)\n                chart_y.push_back(six_chart[j]);\n            else if (temp_label == 2)\n                chart_z.push_back(six_chart[j]);\n        }\n        assert(chart_x.size() == 2);\n        assert(chart_y.size() == 2);\n        assert(chart_z.size() == 2);\n        coef.push_back(Eigen::Triplet<double>(3 * i + up_down_chart_count + cut_num, chart_x[0], +1.0));\n        coef.push_back(Eigen::Triplet<double>(3 * i + up_down_chart_count + cut_num, chart_x[1], -1.0));\n        bkc.push_back(MSK_BK_FX); blc.push_back(0.0); buc.push_back(0.0);\n        coef.push_back(Eigen::Triplet<double>(3 * i + 1 + up_down_chart_count + cut_num, chart_y[0], +1.0));\n        coef.push_back(Eigen::Triplet<double>(3 * i + 1 + up_down_chart_count + cut_num, chart_y[1], -1.0));\n        bkc.push_back(MSK_BK_FX); blc.push_back(0.0); buc.push_back(0.0);\n        coef.push_back(Eigen::Triplet<double>(3 * i + 2 + up_down_chart_count + cut_num, chart_z[0], +1.0));\n        coef.push_back(Eigen::Triplet<double>(3 * i + 2 + up_down_chart_count + cut_num, chart_z[1], -1.0));\n        bkc.push_back(MSK_BK_FX); blc.push_back(0.0); buc.push_back(0.0);\n    }\n    int n_valence_six_constraint = 0;\n    std::map<int, std::set<int>> vert2chart;\n    for (size_t i = 0; i < polycube_edges.size(); i++)\n    {\n        int id0 = polycube_edges[i][0];\n        int id1 = polycube_edges[i][1];\n        int chart0 = polycube_edges[i][2];\n        int chart1 = polycube_edges[i][3];\n        vert2chart[id0].insert(chart0);\n        vert2chart[id0].insert(chart1);\n        vert2chart[id1].insert(chart0);\n        vert2chart[id1].insert(chart1);\n    }\n    for (auto vc : vert2chart)\n    {\n        if (vc.second.size() == 6)\n        {\n            std::vector<int> xchart, ychart, zchart;\n            for (auto chart : vc.second)\n            {\n                int axis = polycube_chart_label[chart] / 2;\n                switch (axis)\n                {\n                case 0:\n                    xchart.push_back(chart);\n                    break;\n                case 1:\n                    ychart.push_back(chart);\n                    break;\n                case 2:\n                    zchart.push_back(chart);\n                    break;\n                default:\n                    break;\n                }\n            }\n            assert(xchart.size() == 2 && ychart.size() == 2 && zchart.size() == 2);\n            coef.push_back(Eigen::Triplet<double>(up_down_chart_count + n_valence_six_constraint, xchart[0], +1.0));\n            coef.push_back(Eigen::Triplet<double>(up_down_chart_count + n_valence_six_constraint, xchart[1], -1.0));\n            bkc.push_back(MSK_BK_FX); blc.push_back(0.0); buc.push_back(0.0);\n            coef.push_back(Eigen::Triplet<double>(up_down_chart_count + n_valence_six_constraint + 1, ychart[0], +1.0));\n            coef.push_back(Eigen::Triplet<double>(up_down_chart_count + n_valence_six_constraint + 1, ychart[1], -1.0));\n            bkc.push_back(MSK_BK_FX); blc.push_back(0.0); buc.push_back(0.0);\n            coef.push_back(Eigen::Triplet<double>(up_down_chart_count + n_valence_six_constraint + 2, zchart[0], +1.0));\n            coef.push_back(Eigen::Triplet<double>(up_down_chart_count + n_valence_six_constraint + 2, zchart[1], -1.0));\n            bkc.push_back(MSK_BK_FX); blc.push_back(0.0); buc.push_back(0.0);\n            n_valence_six_constraint += 3;\n        }\n    }\n    Eigen::SparseMatrix<double> A(3 * three_cut_num + up_down_chart_count + cut_num + n_valence_six_constraint, chart_number);\n    A.setFromTriplets(coef.begin(), coef.end());\n    int size = A.nonZeros(); int cols = A.cols();\n    aptrb.resize(cols + 1); asub.resize(size); aval.resize(size);\n    aptrb[cols] = size;\n    int ind = 0;\n    for (int k = 0; k < cols; ++k)\n    {\n        aptrb[k] = ind;\n        for (Eigen::SparseMatrix<double>::InnerIterator it(A, k); it; ++it)\n        {\n            aval[ind] = it.value();\n            asub[ind] = it.row();\n            ++ind;\n        }\n    }\n    std::vector<double> c(chart_number, 0.0);\n    for (int i = 0; i < chart_number; ++i)\n    {\n        qsubi.push_back(i); qsubj.push_back(i); qval.push_back(2.0);\n        if (hex_meshing_flag)\n        {\n            c[i] = -2.0 * chart_mean_value[i] / cube_len;\n        }\n        else\n        {\n            c[i] = -2.0 * chart_mean_value[i];\n        }\n    }\n    bkx.resize(chart_number, MSK_BK_FR); blx.resize(chart_number, -MSK_INFINITY); bux.resize(chart_number, +MSK_INFINITY);\n    std::vector<double> x(chart_number, 0.0); int mosek_count = 0;\n    bool solve_success;\n    if (hex_meshing_flag)\n    {\n        solve_success = solveConvexQuadPorgramming_mosek_integer(bkc, blc, buc, bkx, blx, bux, aptrb, asub, aval, qsubi, qsubj, qval, c, x);\n    }\n    else\n    {\n        solve_success = solveConvexQuadPorgramming_mosek(bkc, blc, buc, bkx, blx, bux, aptrb, asub, aval, qsubi, qsubj, qval, c, x);\n    }\n    while (!solve_success)\n    {\n        ratio_diff *= 0.8;\n        for (int i = 0; i < up_down_chart_count; ++i)\n        {\n            diff_u_d = diff_up_down[i] * ratio_diff;\n            if (hex_meshing_flag)\n            {\n                if (diff_u_d < cube_len)\n                {\n                    diff_u_d = cube_len;\n                }\n                blc[i] = diff_u_d / cube_len;\n            }\n            else\n            {\n                blc[i] = diff_u_d;\n            }\n        }\n        if (hex_meshing_flag)\n        {\n            solve_success = solveConvexQuadPorgramming_mosek_integer(bkc, blc, buc, bkx, blx, bux, aptrb, asub, aval, qsubi, qsubj, qval, c, x);\n        }\n        else\n        {\n            solve_success = solveConvexQuadPorgramming_mosek(bkc, blc, buc, bkx, blx, bux, aptrb, asub, aval, qsubi, qsubj, qval, c, x);\n        }\n        ++mosek_count;\n        if (mosek_count > 20) break;\n    }\n    if (mosek_count > 20)\n    {\n        printf(\"-------------------------------------------\\nNo Solution!!!!!\\n\");\n        return false;\n    }\n    else\n    {\n        for (int i = 0; i < chart_number; ++i)\n        {\n            if (hex_meshing_flag)\n            {\n                chart_mean_value[i] = cube_len * x[i];\n                double offset_ratio = offset;\n                if (polycube_chart_label[i] % 2 == 0)\n                {\n                    chart_mean_value[i] += cube_len * offset_ratio;\n                }\n                else\n                {\n                    chart_mean_value[i] -= cube_len * offset_ratio;\n                }\n            }\n            else\n            {\n                chart_mean_value[i] = x[i];\n            }\n        }\n        if (hex_meshing_flag)\n        {\n            for (size_t i = 0; i < cut_num; i++)\n            {\n                int chart1 = cut_to_chart_pair[i].first;\n                int chart2 = cut_to_chart_pair[i].second;\n                chart_mean_value[chart1] = cube_len * x[chart1];\n                chart_mean_value[chart2] = cube_len * x[chart2];\n            }\n        }\n    }\n    return true;\n}\nbool polycube_flattening_interface::find_all_chart_value_equal_face_mine(TetStructure<double> *tet_mesh_, const std::vector<double>& chart_mean_value_ori, double lambda, bool add_constraint, bool set_min_diff, double offset)\n{\n    find_all_corner(tet_mesh_);\n    if (add_constraint)\n    {\n        update_updownchart(tet_mesh_);\n    }\n    std::vector<MSKboundkeye> bkc; std::vector<double> blc; std::vector<double> buc;\n    std::vector<MSKboundkeye> bkx; std::vector<double> blx; std::vector<double> bux;\n    std::vector<MSKlidxt> aptrb; std::vector<MSKidxt> asub; std::vector<double> aval;\n    std::vector<MSKidxt> qsubi; std::vector<MSKidxt> qsubj; std::vector<double> qval;\n    double ratio_diff = 0.8;\n    std::vector< Eigen::Triplet<double> > coef;\n    int up_down_chart_count = up_chart_id.size();\n    int chart_number = chart_mean_value.size();\n    double diff_u_d; int up_chart, down_chart;\n    for (int i = 0; i < up_down_chart_count; ++i)\n    {\n        up_chart = up_chart_id[i];\n        down_chart = down_chart_id[i];\n        diff_u_d = diff_up_down[i] * ratio_diff;\n        if (set_min_diff)\n        {\n            if (diff_u_d < cube_len)\n            {\n                diff_u_d = cube_len;\n            }\n        }\n        if (hex_meshing_flag)\n        {\n            if (diff_u_d < cube_len)\n            {\n                diff_u_d = cube_len;\n            }\n            coef.push_back(Eigen::Triplet<double>(i, up_chart, +1.0));\n            coef.push_back(Eigen::Triplet<double>(i, down_chart, -1.0));\n            bkc.push_back(MSK_BK_LO); blc.push_back(diff_u_d / cube_len); buc.push_back(+MSK_INFINITY);\n        }\n        else\n        {\n            coef.push_back(Eigen::Triplet<double>(i, up_chart, +1.0));\n            coef.push_back(Eigen::Triplet<double>(i, down_chart, -1.0));\n            bkc.push_back(MSK_BK_LO); blc.push_back(diff_u_d); buc.push_back(+MSK_INFINITY);\n        }\n    }\n    int cut_num = 0;\n    cut_num = cut_to_chart_pair.size();\n    for (size_t i = 0; i < cut_num; i++)\n    {\n        int chart1 = cut_to_chart_pair[i].first;\n        int chart2 = cut_to_chart_pair[i].second;\n        if (cut_to_chart_pair_neighbor.size() == 0)\n        {\n            std::vector<int> chart1_idx, chart2_idx;\n            for (size_t j = 0; j < polycube_edges.size(); j++)\n            {\n                if ((polycube_edges[j][2] == chart1 && polycube_edges[j][3] != chart2)\n                    || (polycube_edges[j][3] == chart1 && polycube_edges[j][2] != chart2))\n                    chart1_idx.push_back(j);\n                if ((polycube_edges[j][2] == chart2 && polycube_edges[j][3] != chart1)\n                    || (polycube_edges[j][3] == chart2 && polycube_edges[j][2] != chart1))\n                    chart2_idx.push_back(j);\n            }\n            int final_idx1(-1), final_idx2(-1);\n            for (size_t j = 0; j < chart1_idx.size(); j++)\n            {\n                if (up_chart_id[chart1_idx[j]] == chart2 || down_chart_id[chart1_idx[j]] == chart2)\n                {\n                    final_idx1 = chart1_idx[j];\n                    break;\n                }\n            }\n            for (size_t j = 0; j < chart2_idx.size(); j++)\n            {\n                if (up_chart_id[chart2_idx[j]] == chart1 || down_chart_id[chart2_idx[j]] == chart1)\n                {\n                    final_idx2 = chart2_idx[j];\n                    break;\n                }\n            }\n            coef.push_back(Eigen::Triplet<double>(i + up_down_chart_count, up_chart_id[final_idx1], +1.0));\n            coef.push_back(Eigen::Triplet<double>(i + up_down_chart_count, down_chart_id[final_idx1], -1.0));\n            coef.push_back(Eigen::Triplet<double>(i + up_down_chart_count, up_chart_id[final_idx2], -1.0));\n            coef.push_back(Eigen::Triplet<double>(i + up_down_chart_count, down_chart_id[final_idx2], +1.0));\n            bkc.push_back(MSK_BK_FX); blc.push_back(0.0); buc.push_back(0.0);\n        }\n        else\n        {\n            int up1, up2, down1, down2;\n            up1 = cut_to_chart_pair_neighbor[i].first;\n            down1 = cut_to_chart_pair[i].second;\n            up2 = cut_to_chart_pair[i].first;\n            down2 = cut_to_chart_pair_neighbor[i].second;\n            if (chart_mean_value[up1] < chart_mean_value[down1])\n            {\n                int temp = up1;\n                up1 = down1;\n                down1 = temp;\n            }\n            if (chart_mean_value[up2] < chart_mean_value[down2])\n            {\n                int temp = up2;\n                up2 = down2;\n                down2 = temp;\n            }\n            coef.push_back(Eigen::Triplet<double>(i + up_down_chart_count, up1, +1.0));\n            coef.push_back(Eigen::Triplet<double>(i + up_down_chart_count, down1, -1.0));\n            coef.push_back(Eigen::Triplet<double>(i + up_down_chart_count, up2, -1.0));\n            coef.push_back(Eigen::Triplet<double>(i + up_down_chart_count, down2, +1.0));\n            bkc.push_back(MSK_BK_FX); blc.push_back(0.0); buc.push_back(0.0);\n        }\n    }\n    int three_cut_num = 0;\n    three_cut_num = three_cut_adjacent_one_cut_index.size();\n    for (size_t i = 0; i < three_cut_num; i++)\n    {\n        std::vector<int> six_chart, chart_x, chart_y, chart_z;\n        for (size_t j = 0; j < 3; j++)\n        {\n            six_chart.push_back(cut_to_chart_pair[three_cut_adjacent_one_cut_index[i][j]].first);\n            six_chart.push_back(cut_to_chart_pair[three_cut_adjacent_one_cut_index[i][j]].second);\n        }\n        for (size_t j = 0; j < 6; j++)\n        {\n            int temp_label = polycube_chart_label[six_chart[j]] / 2;\n            if (temp_label == 0)\n                chart_x.push_back(six_chart[j]);\n            else if (temp_label == 1)\n                chart_y.push_back(six_chart[j]);\n            else if (temp_label == 2)\n                chart_z.push_back(six_chart[j]);\n        }\n        assert(chart_x.size() == 2);\n        assert(chart_y.size() == 2);\n        assert(chart_z.size() == 2);\n        coef.push_back(Eigen::Triplet<double>(3 * i + up_down_chart_count + cut_num, chart_x[0], +1.0));\n        coef.push_back(Eigen::Triplet<double>(3 * i + up_down_chart_count + cut_num, chart_x[1], -1.0));\n        bkc.push_back(MSK_BK_FX); blc.push_back(0.0); buc.push_back(0.0);\n        coef.push_back(Eigen::Triplet<double>(3 * i + 1 + up_down_chart_count + cut_num, chart_y[0], +1.0));\n        coef.push_back(Eigen::Triplet<double>(3 * i + 1 + up_down_chart_count + cut_num, chart_y[1], -1.0));\n        bkc.push_back(MSK_BK_FX); blc.push_back(0.0); buc.push_back(0.0);\n        coef.push_back(Eigen::Triplet<double>(3 * i + 2 + up_down_chart_count + cut_num, chart_z[0], +1.0));\n        coef.push_back(Eigen::Triplet<double>(3 * i + 2 + up_down_chart_count + cut_num, chart_z[1], -1.0));\n        bkc.push_back(MSK_BK_FX); blc.push_back(0.0); buc.push_back(0.0);\n    }\n    int n_valence_six_constraint = 0;\n    std::map<int, std::set<int>> vert2chart;\n    for (size_t i = 0; i < polycube_edges.size(); i++)\n    {\n        int id0 = polycube_edges[i][0];\n        int id1 = polycube_edges[i][1];\n        int chart0 = polycube_edges[i][2];\n        int chart1 = polycube_edges[i][3];\n        vert2chart[id0].insert(chart0);\n        vert2chart[id0].insert(chart1);\n        vert2chart[id1].insert(chart0);\n        vert2chart[id1].insert(chart1);\n    }\n    for (auto vc : vert2chart)\n    {\n        if (vc.second.size() == 6)\n        {\n            std::vector<int> xchart, ychart, zchart;\n            for (auto chart : vc.second)\n            {\n                int axis = polycube_chart_label[chart] / 2;\n                switch (axis)\n                {\n                case 0:\n                    xchart.push_back(chart);\n                    break;\n                case 1:\n                    ychart.push_back(chart);\n                    break;\n                case 2:\n                    zchart.push_back(chart);\n                    break;\n                default:\n                    break;\n                }\n            }\n            assert(xchart.size() == 2 && ychart.size() == 2 && zchart.size() == 2);\n            coef.push_back(Eigen::Triplet<double>(up_down_chart_count + n_valence_six_constraint, xchart[0], +1.0));\n            coef.push_back(Eigen::Triplet<double>(up_down_chart_count + n_valence_six_constraint, xchart[1], -1.0));\n            bkc.push_back(MSK_BK_FX); blc.push_back(0.0); buc.push_back(0.0);\n            coef.push_back(Eigen::Triplet<double>(up_down_chart_count + n_valence_six_constraint + 1, ychart[0], +1.0));\n            coef.push_back(Eigen::Triplet<double>(up_down_chart_count + n_valence_six_constraint + 1, ychart[1], -1.0));\n            bkc.push_back(MSK_BK_FX); blc.push_back(0.0); buc.push_back(0.0);\n            coef.push_back(Eigen::Triplet<double>(up_down_chart_count + n_valence_six_constraint + 2, zchart[0], +1.0));\n            coef.push_back(Eigen::Triplet<double>(up_down_chart_count + n_valence_six_constraint + 2, zchart[1], -1.0));\n            bkc.push_back(MSK_BK_FX); blc.push_back(0.0); buc.push_back(0.0);\n            n_valence_six_constraint += 3;\n        }\n    }\n    Eigen::SparseMatrix<double> A(3 * three_cut_num + up_down_chart_count + cut_num + n_valence_six_constraint, chart_number);\n    A.setFromTriplets(coef.begin(), coef.end());\n    int size = A.nonZeros(); int cols = A.cols();\n    aptrb.resize(cols + 1); asub.resize(size); aval.resize(size);\n    aptrb[cols] = size;\n    int ind = 0;\n    for (int k = 0; k < cols; ++k)\n    {\n        aptrb[k] = ind;\n        for (Eigen::SparseMatrix<double>::InnerIterator it(A, k); it; ++it)\n        {\n            aval[ind] = it.value();\n            asub[ind] = it.row();\n            ++ind;\n        }\n    }\n    std::vector<double> c(chart_number, 0.0);\n    for (int i = 0; i < chart_number; ++i)\n    {\n        qsubi.push_back(i); qsubj.push_back(i); qval.push_back(2.0);\n        if (hex_meshing_flag)\n        {\n            c[i] = -2.0 * chart_mean_value[i] / cube_len;\n        }\n        else\n        {\n            c[i] = -2.0 * chart_mean_value[i];\n        }\n    }\n    assert(chart_mean_value_ori.size() <= chart_mean_value.size());\n    for (size_t i = 0; i < chart_mean_value_ori.size(); i++)\n    {\n        qval[i] = 2.0 + 2.0 * lambda;\n        if (hex_meshing_flag)\n        {\n            c[i] += -2.0 * chart_mean_value_ori[i] * lambda / cube_len;\n        }\n        else\n        {\n            c[i] += -2.0 * chart_mean_value_ori[i] * lambda;\n        }\n    }\n    bkx.resize(chart_number, MSK_BK_FR); blx.resize(chart_number, -MSK_INFINITY); bux.resize(chart_number, +MSK_INFINITY);\n    std::vector<double> x(chart_number, 0.0); int mosek_count = 0;\n    bool solve_success;\n    if (hex_meshing_flag)\n        solve_success = solveConvexQuadPorgramming_mosek_integer(bkc, blc, buc, bkx, blx, bux, aptrb, asub, aval, qsubi, qsubj, qval, c, x);\n    else\n        solve_success = solveConvexQuadPorgramming_mosek(bkc, blc, buc, bkx, blx, bux, aptrb, asub, aval, qsubi, qsubj, qval, c, x);\n    while (!solve_success)\n    {\n        ratio_diff *= 0.8;\n        for (int i = 0; i < up_down_chart_count; ++i)\n        {\n            diff_u_d = diff_up_down[i] * ratio_diff;\n            if (set_min_diff)\n            {\n                if (diff_u_d < cube_len)\n                {\n                    diff_u_d = cube_len;\n                }\n            }\n            if (hex_meshing_flag)\n            {\n                if (diff_u_d < cube_len)\n                {\n                    diff_u_d = cube_len;\n                }\n                blc[i] = diff_u_d / cube_len;\n            }\n            else\n            {\n                blc[i] = diff_u_d;\n            }\n        }\n        if (hex_meshing_flag)\n            solve_success = solveConvexQuadPorgramming_mosek_integer(bkc, blc, buc, bkx, blx, bux, aptrb, asub, aval, qsubi, qsubj, qval, c, x);\n        else\n            solve_success = solveConvexQuadPorgramming_mosek(bkc, blc, buc, bkx, blx, bux, aptrb, asub, aval, qsubi, qsubj, qval, c, x);\n        ++mosek_count;\n        if (mosek_count > 20) break;\n    }\n    if (mosek_count > 20)\n    {\n        printf(\"-------------------------------------------\\nNo Solution!!!!!\\n\");\n        return false;\n    }\n    else\n    {\n        for (int i = 0; i < chart_number; ++i)\n        {\n            if (hex_meshing_flag)\n            {\n                chart_mean_value[i] = cube_len * x[i];\n                double offset_ratio = offset;\n                if (polycube_chart_label[i] % 2 == 0)\n                {\n                    chart_mean_value[i] += cube_len * offset_ratio;\n                }\n                else\n                {\n                    chart_mean_value[i] -= cube_len * offset_ratio;\n                }\n            }\n            else\n            {\n                chart_mean_value[i] = x[i];\n            }\n        }\n        if (hex_meshing_flag)\n            for (size_t i = 0; i < cut_num; i++)\n            {\n                int chart1 = cut_to_chart_pair[i].first;\n                int chart2 = cut_to_chart_pair[i].second;\n                chart_mean_value[chart1] = cube_len * x[chart1];\n                chart_mean_value[chart2] = cube_len * x[chart2];\n            }\n    }\n    return true;\n}\nbool polycube_flattening_interface::find_all_chart_value_preprocessing(TetStructure<double> *tet_mesh_)\n{\n    find_all_corner(tet_mesh_);\n    std::vector<MSKboundkeye> bkc; std::vector<double> blc; std::vector<double> buc;\n    std::vector<MSKboundkeye> bkx; std::vector<double> blx; std::vector<double> bux;\n    std::vector<MSKlidxt> aptrb; std::vector<MSKidxt> asub; std::vector<double> aval;\n    std::vector<MSKidxt> qsubi; std::vector<MSKidxt> qsubj; std::vector<double> qval;\n    double ratio_diff = 0.8;\n    std::vector< Eigen::Triplet<double> > coef;\n    int up_down_chart_count = up_chart_id.size();\n    int chart_number = chart_mean_value.size();\n    double diff_u_d; int up_chart, down_chart;\n    for (int i = 0; i < up_down_chart_count; ++i)\n    {\n        up_chart = up_chart_id[i];\n        down_chart = down_chart_id[i];\n        coef.push_back(Eigen::Triplet<double>(i, up_chart, +1.0));\n        coef.push_back(Eigen::Triplet<double>(i, down_chart, -1.0));\n        bkc.push_back(MSK_BK_LO); blc.push_back(cube_len); buc.push_back(+MSK_INFINITY);\n    }\n    int n_valence_six_constraint = 0;\n    std::map<int, std::set<int>> vert2chart;\n    for (size_t i = 0; i < polycube_edges.size(); i++)\n    {\n        int id0 = polycube_edges[i][0];\n        int id1 = polycube_edges[i][1];\n        int chart0 = polycube_edges[i][2];\n        int chart1 = polycube_edges[i][3];\n        vert2chart[id0].insert(chart0);\n        vert2chart[id0].insert(chart1);\n        vert2chart[id1].insert(chart0);\n        vert2chart[id1].insert(chart1);\n    }\n    for (auto vc : vert2chart)\n    {\n        if (vc.second.size() == 6)\n        {\n            std::vector<int> xchart, ychart, zchart;\n            for (auto chart : vc.second)\n            {\n                int axis = polycube_chart_label[chart] / 2;\n                switch (axis)\n                {\n                case 0:\n                    xchart.push_back(chart);\n                    break;\n                case 1:\n                    ychart.push_back(chart);\n                    break;\n                case 2:\n                    zchart.push_back(chart);\n                    break;\n                default:\n                    break;\n                }\n            }\n            assert(xchart.size() == 2 && ychart.size() == 2 && zchart.size() == 2);\n            coef.push_back(Eigen::Triplet<double>(up_down_chart_count + n_valence_six_constraint, xchart[0], +1.0));\n            coef.push_back(Eigen::Triplet<double>(up_down_chart_count + n_valence_six_constraint, xchart[1], -1.0));\n            bkc.push_back(MSK_BK_FX); blc.push_back(0.0); buc.push_back(0.0);\n            coef.push_back(Eigen::Triplet<double>(up_down_chart_count + n_valence_six_constraint + 1, ychart[0], +1.0));\n            coef.push_back(Eigen::Triplet<double>(up_down_chart_count + n_valence_six_constraint + 1, ychart[1], -1.0));\n            bkc.push_back(MSK_BK_FX); blc.push_back(0.0); buc.push_back(0.0);\n            coef.push_back(Eigen::Triplet<double>(up_down_chart_count + n_valence_six_constraint + 2, zchart[0], +1.0));\n            coef.push_back(Eigen::Triplet<double>(up_down_chart_count + n_valence_six_constraint + 2, zchart[1], -1.0));\n            bkc.push_back(MSK_BK_FX); blc.push_back(0.0); buc.push_back(0.0);\n            n_valence_six_constraint += 3;\n        }\n    }\n    Eigen::SparseMatrix<double> A(up_down_chart_count + n_valence_six_constraint, chart_number);\n    A.setFromTriplets(coef.begin(), coef.end());\n    int size = A.nonZeros(); int cols = A.cols();\n    aptrb.resize(cols + 1); asub.resize(size); aval.resize(size);\n    aptrb[cols] = size;\n    int ind = 0;\n    for (int k = 0; k < cols; ++k)\n    {\n        aptrb[k] = ind;\n        for (Eigen::SparseMatrix<double>::InnerIterator it(A, k); it; ++it)\n        {\n            aval[ind] = it.value();\n            asub[ind] = it.row();\n            ++ind;\n        }\n    }\n    std::vector<double> c(chart_number, 0.0);\n    for (int i = 0; i < chart_number; ++i)\n    {\n        qsubi.push_back(i); qsubj.push_back(i); qval.push_back(2.0);\n        c[i] = -2.0 * chart_mean_value[i];\n    }\n    bkx.resize(chart_number, MSK_BK_FR); blx.resize(chart_number, -MSK_INFINITY); bux.resize(chart_number, +MSK_INFINITY);\n    std::vector<double> x(chart_number, 0.0); int mosek_count = 0;\n    bool solve_success;\n    solve_success = solveConvexQuadPorgramming_mosek(bkc, blc, buc, bkx, blx, bux, aptrb, asub, aval, qsubi, qsubj, qval, c, x);\n    while (!solve_success)\n    {\n        ratio_diff *= 0.8;\n        for (int i = 0; i < up_down_chart_count; ++i)\n        {\n            diff_u_d = diff_up_down[i] * ratio_diff;\n            blc[i] = diff_u_d;\n        }\n        solve_success = solveConvexQuadPorgramming_mosek(bkc, blc, buc, bkx, blx, bux, aptrb, asub, aval, qsubi, qsubj, qval, c, x);\n        ++mosek_count;\n        if (mosek_count > 20) break;\n    }\n    if (mosek_count > 20)\n    {\n        printf(\"-------------------------------------------\\nNo Solution!!!!!\\n\");\n        return false;\n    }\n    else\n    {\n        for (int i = 0; i < chart_number; ++i)\n        {\n            chart_mean_value[i] = x[i];\n        }\n    }\n    return true;\n}\nvoid polycube_flattening_interface::update_updownchart(TetStructure<double> *tet_mesh_)\n{\n    if (update_updownchart_flag)\n        return;\n    update_updownchart_flag = true;\n    std::cout << \"--------------------Adding Constraints for Flattening------------------------\" << std::endl;\n    if (bd_pts.empty()) get_bd_face_chart_label(tet_mesh_);\n    std::set<std::pair<int, int>> updown_array, updown_array_ori;\n    for (size_t i = 0; i < up_chart_id.size(); i++)\n    {\n        updown_array.insert(std::pair<int, int>(up_chart_id[i], down_chart_id[i]));\n        updown_array_ori.insert(std::pair<int, int>(up_chart_id[i], down_chart_id[i]));\n    }\n    CVec<double, 3> axis_dir[3] = { CVec<double, 3>(1.0, 0.0, 0.0), CVec<double, 3>(0.0, 1.0, 0.0), CVec<double, 3>(0.0, 0.0, 1.0) };\n    CVec<double, 3> leftdownpt = bd_pts[0];\n    for (size_t i = 1; i < bd_pts.size(); i++)\n    {\n        for (size_t j = 0; j < 3; j++)\n        {\n            if (leftdownpt[j] > bd_pts[i][j])\n                leftdownpt[j] = bd_pts[i][j];\n        }\n    }\n    std::vector<std::vector<int>> axis2pqedgeid(3), axis2chart(3);\n    std::vector<int> pqedge2axis(polycube_edges.size());\n    std::vector<std::vector<int>> chart2bd_faceid(polycube_chart_label.size());\n    assert(bd_chart.size() == bd_faces.size() / 3);\n    for (size_t i = 0; i < bd_faces.size() / 3; i++)\n    {\n        chart2bd_faceid[bd_chart[i]].push_back(i);\n    }\n    for (size_t i = 0; i < polycube_edges.size(); i++)\n    {\n        int chart0 = polycube_edges[i][2];\n        int chart1 = polycube_edges[i][3];\n        int axis0 = polycube_chart_label[chart0] / 2;\n        int axis1 = polycube_chart_label[chart1] / 2;\n        int select_axis = 3 - axis0 - axis1;\n        axis2pqedgeid[select_axis].push_back(i);\n        pqedge2axis[i] = select_axis;\n    }\n    for (size_t i = 0; i < polycube_chart_label.size(); i++)\n    {\n        int axis = polycube_chart_label[i] / 2;\n        axis2chart[axis].push_back(i);\n    }\n    for (int i = 0; i < 3; i++)\n    {\n        int curaxis = i;\n        int otheraxis[2];\n        otheraxis[0] = (i + 1) % 3;\n        otheraxis[1] = (i + 2) % 3;\n        std::vector<unsigned> cur_faces;\n        std::vector<int> face_c2o;\n        std::vector<double> coord[2];\n        for (size_t j = 0; j < axis2chart[i].size(); j++)\n        {\n            int chartid = axis2chart[i][j];\n            for (size_t k = 0; k < chart2bd_faceid[chartid].size(); k++)\n            {\n                int fid = chart2bd_faceid[chartid][k];\n                cur_faces.push_back(bd_faces[3 * fid]);\n                cur_faces.push_back(bd_faces[3 * fid + 1]);\n                cur_faces.push_back(bd_faces[3 * fid + 2]);\n                face_c2o.push_back(fid);\n            }\n        }\n        for (size_t j = 0; j < 2; j++)\n        {\n            int axis = otheraxis[j];\n            for (size_t k = 0; k < axis2pqedgeid[axis].size(); k++)\n            {\n                int pqid = axis2pqedgeid[axis][k];\n                int vid[2];\n                vid[0] = polycube_edges[pqid][0];\n                vid[1] = polycube_edges[pqid][1];\n                for (size_t iter = 0; iter < 2; iter++)\n                {\n                    switch (axis)\n                    {\n                    case 0:\n                        coord[j].push_back(dpx[vid[iter]]);\n                        break;\n                    case 1:\n                        coord[j].push_back(dpy[vid[iter]]);\n                        break;\n                    case 2:\n                        coord[j].push_back(dpz[vid[iter]]);\n                        break;\n                    }\n                }\n            }\n        }\n        std::sort(coord[0].begin(), coord[0].end());\n        std::sort(coord[1].begin(), coord[1].end());\n        std::vector<double> coord_final[2];\n        for (size_t j = 0; j < 2; j++)\n        {\n            for (size_t k = 0; k < coord[j].size(); k++)\n            {\n                if (k == 0 || std::abs(coord[j][k] - coord[j][k - 1]) > MIN_EDGE_DIST)\n                {\n                    coord_final[j].push_back(coord[j][k]);\n                }\n            }\n        }\n        std::vector<std::pair<CVec<double, 3>, CVec<double, 3>>> rays;\n        std::vector<std::set<unsigned>> ignored_faces;\n        std::vector<CVec<double, 3>> first_intersection_pts;\n        std::vector<std::vector<int>> all_intersection_face_id_cur, all_intersection_face_id_ori;\n        for (size_t j = 0; j < coord_final[0].size() - 1; j++)\n        {\n            for (size_t k = 0; k < coord_final[1].size() - 1; k++)\n            {\n                CVec<double, 3> begin_pt;\n                begin_pt[curaxis] = leftdownpt[curaxis] - 1.0;\n                begin_pt[otheraxis[0]] = (coord_final[0][j] + coord_final[0][j + 1]) / 2.0;\n                begin_pt[otheraxis[1]] = (coord_final[1][k] + coord_final[1][k + 1]) / 2.0;\n                rays.push_back(std::pair<CVec<double, 3>, CVec<double, 3>>(begin_pt, axis_dir[curaxis]));\n            }\n        }\n        ig::CGALHelper::rays_triangles_intersection(rays, bd_pts, cur_faces, ignored_faces, first_intersection_pts, &all_intersection_face_id_cur);\n        all_intersection_face_id_ori.resize(all_intersection_face_id_cur.size());\n        for (size_t j = 0; j < all_intersection_face_id_cur.size(); j++)\n        {\n            for (size_t k = 0; k < all_intersection_face_id_cur[j].size(); k++)\n            {\n                all_intersection_face_id_ori[j].push_back(face_c2o[all_intersection_face_id_cur[j][k]]);\n            }\n            std::vector<std::pair<int, double>> intersection_chart_value_sorted_all, intersection_chart_value_sorted;\n            std::vector<int> intersection_label_sorted;\n            std::vector<bool> intersection_dir_sorted;\n            for (size_t k = 0; k < all_intersection_face_id_ori[j].size(); k++)\n            {\n                if (k == 0 || bd_chart[all_intersection_face_id_ori[j][k]] != bd_chart[all_intersection_face_id_ori[j][k - 1]])\n                {\n                    int axis = bd_label[all_intersection_face_id_ori[j][k]] / 2;\n                    if (axis == curaxis)\n                    {\n                        int chart = bd_chart[all_intersection_face_id_ori[j][k]];\n                        intersection_chart_value_sorted_all.push_back(std::pair<int, double>(chart, chart_mean_value[chart]));\n                    }\n                }\n            }\n            std::sort(intersection_chart_value_sorted_all.begin(), intersection_chart_value_sorted_all.end(), [](std::pair<int, double>p1, std::pair<int, double>p2) {\n                return p1.second < p2.second;\n                });\n            for (size_t k = 0; k < intersection_chart_value_sorted_all.size(); k++)\n            {\n                int chart = intersection_chart_value_sorted_all[k].first;\n                int label = polycube_chart_label[chart];\n                intersection_label_sorted.push_back(label);\n                intersection_dir_sorted.push_back((bool)(1 - label % 2));\n            }\n            if (!intersection_dir_sorted.empty())\n            {\n                for (size_t k = 0; k < intersection_dir_sorted.size() - 1; k++)\n                {\n                    bool cur_dir = intersection_dir_sorted[k];\n                    int next_id = -1;\n                    for (int iter = k + 1; iter < intersection_dir_sorted.size(); iter++)\n                    {\n                        if (intersection_dir_sorted[iter] != cur_dir)\n                        {\n                            next_id = iter;\n                            break;\n                        }\n                    }\n                    if (next_id != -1)\n                    {\n                        updown_array.insert(std::pair<int, int>(intersection_chart_value_sorted_all[next_id].first, intersection_chart_value_sorted_all[k].first));\n                    }\n                }\n            }\n        }\n    }\n    std::vector<std::vector<int>> edges_with_same_chart;\n    edges_with_same_chart.resize(polycube_chart_label.size());\n    for (size_t i = 0; i < polycube_edges.size(); i++)\n    {\n        int chart_idx1 = polycube_edges[i][2];\n        int chart_idx2 = polycube_edges[i][3];\n        edges_with_same_chart[chart_idx1].push_back(i);\n        edges_with_same_chart[chart_idx2].push_back(i);\n    }\n    for (size_t i = 0; i < polycube_chart_label.size(); i++)\n    {\n        if (i == 35)\n        {\n            int a = 1;\n        }\n        int curchart = i;\n        int chartaxis = polycube_chart_label[curchart] / 2;\n        std::map<int, std::vector<int>> local_a2p;\n        for (size_t j = 0; j < edges_with_same_chart[curchart].size(); j++)\n        {\n            int eid = edges_with_same_chart[curchart][j];\n            local_a2p[pqedge2axis[eid]].push_back(eid);\n        }\n        CVec<double, 3> center(0.0, 0.0, 0.0);\n        center[chartaxis] = chart_mean_value[curchart];\n        assert(local_a2p.size() == 2);\n        for (auto a2p : local_a2p)\n        {\n            int axis = a2p.first;\n            std::vector<std::pair<int, std::pair<double, double>>> pqidsegm;\n            for (size_t j = 0; j < a2p.second.size(); j++)\n            {\n                int eid = a2p.second[j];\n                int v0 = polycube_edges[eid][0];\n                int v1 = polycube_edges[eid][1];\n                CVec<double, 3> p0(dpx[v0], dpy[v0], dpz[v0]), p1(dpx[v1], dpy[v1], dpz[v1]);\n                double s0 = (p0 - center).Dot(axis_dir[axis]);\n                double s1 = (p1 - center).Dot(axis_dir[axis]);\n                if (s0 > s1) std::swap(s0, s1);\n                pqidsegm.push_back(std::pair<int, std::pair<double, double>>(eid, std::pair<double, double>(s0, s1)));\n            }\n            for (size_t i1 = 0; i1 < pqidsegm.size() - 1; i1++)\n            {\n                for (size_t i2 = i1 + 1; i2 < pqidsegm.size(); i2++)\n                {\n                    bool overlap = ig::CGALHelper::line_segm_intersection<double>(pqidsegm[i1].second, pqidsegm[i2].second);\n                    if (overlap)\n                    {\n                        int eid1 = pqidsegm[i1].first, eid2 = pqidsegm[i2].first;\n                        int otherchart1 = polycube_edges[eid1][2], otherchart2 = polycube_edges[eid2][2];\n                        if (otherchart1 == curchart) otherchart1 = polycube_edges[eid1][3];\n                        if (otherchart2 == curchart) otherchart2 = polycube_edges[eid2][3];\n                        if (chart_mean_value[otherchart1] < chart_mean_value[otherchart2]) std::swap(otherchart1, otherchart2);\n                        updown_array.insert(std::pair<int, int>(otherchart1, otherchart2));\n                    }\n                }\n            }\n        }\n    }\n    for (auto it : updown_array)\n    {\n        auto it_find = updown_array_ori.find(it);\n        if (it_find == updown_array_ori.end())\n        {\n            up_chart_id.push_back(it.first);\n            down_chart_id.push_back(it.second);\n            diff_up_down.push_back(cube_len);\n        }\n    }\n}\nbool polycube_flattening_interface::find_all_chart_value_equal_face_rounding(TetStructure<double> *tet_mesh_, double offset)\n{\n    find_all_corner(tet_mesh_);\n    std::vector<MSKboundkeye> bkc; std::vector<double> blc; std::vector<double> buc;\n    std::vector<MSKboundkeye> bkx; std::vector<double> blx; std::vector<double> bux;\n    std::vector<MSKlidxt> aptrb; std::vector<MSKidxt> asub; std::vector<double> aval;\n    std::vector<MSKidxt> qsubi; std::vector<MSKidxt> qsubj; std::vector<double> qval;\n    double ratio_diff = 0.8;\n    std::vector< Eigen::Triplet<double> > coef;\n    int up_down_chart_count = up_chart_id.size();\n    int chart_number = chart_mean_value.size();\n    double diff_u_d; int up_chart, down_chart;\n    for (int i = 0; i < up_down_chart_count; ++i)\n    {\n        up_chart = up_chart_id[i];\n        down_chart = down_chart_id[i];\n        diff_u_d = diff_up_down[i] * ratio_diff;\n        if (hex_meshing_flag)\n        {\n            if (diff_u_d < cube_len)\n            {\n                diff_u_d = cube_len;\n            }\n        }\n        coef.push_back(Eigen::Triplet<double>(i, up_chart, +1.0));\n        coef.push_back(Eigen::Triplet<double>(i, down_chart, -1.0));\n        bkc.push_back(MSK_BK_LO); blc.push_back(diff_u_d); buc.push_back(+MSK_INFINITY);\n    }\n    int cut_num = 0;\n    cut_num = cut_to_chart_pair.size();\n    for (size_t i = 0; i < cut_to_chart_pair.size(); i++)\n    {\n        int chart1 = cut_to_chart_pair[i].first;\n        int chart2 = cut_to_chart_pair[i].second;\n        std::vector<int> chart1_idx, chart2_idx;\n        for (size_t j = 0; j < polycube_edges.size(); j++)\n        {\n            if ((polycube_edges[j][2] == chart1 && polycube_edges[j][3] != chart2)\n                || (polycube_edges[j][3] == chart1 && polycube_edges[j][2] != chart2))\n                chart1_idx.push_back(j);\n            if ((polycube_edges[j][2] == chart2 && polycube_edges[j][3] != chart1)\n                || (polycube_edges[j][3] == chart2 && polycube_edges[j][2] != chart1))\n                chart2_idx.push_back(j);\n        }\n        int final_idx1(-1), final_idx2(-1);\n        for (size_t j = 0; j < chart1_idx.size(); j++)\n        {\n            if (up_chart_id[chart1_idx[j]] == chart2 || down_chart_id[chart1_idx[j]] == chart2)\n            {\n                final_idx1 = chart1_idx[j];\n                break;\n            }\n        }\n        for (size_t j = 0; j < chart2_idx.size(); j++)\n        {\n            if (up_chart_id[chart2_idx[j]] == chart1 || down_chart_id[chart2_idx[j]] == chart1)\n            {\n                final_idx2 = chart2_idx[j];\n                break;\n            }\n        }\n        coef.push_back(Eigen::Triplet<double>(i + up_down_chart_count, up_chart_id[final_idx1], +1.0));\n        coef.push_back(Eigen::Triplet<double>(i + up_down_chart_count, down_chart_id[final_idx1], -1.0));\n        coef.push_back(Eigen::Triplet<double>(i + up_down_chart_count, up_chart_id[final_idx2], -1.0));\n        coef.push_back(Eigen::Triplet<double>(i + up_down_chart_count, down_chart_id[final_idx2], +1.0));\n        bkc.push_back(MSK_BK_FX); blc.push_back(0.0); buc.push_back(0.0);\n    }\n    int n_valence_six_constraint = 0;\n    std::map<int, std::set<int>> vert2chart;\n    for (size_t i = 0; i < polycube_edges.size(); i++)\n    {\n        int id0 = polycube_edges[i][0];\n        int id1 = polycube_edges[i][1];\n        int chart0 = polycube_edges[i][2];\n        int chart1 = polycube_edges[i][3];\n        vert2chart[id0].insert(chart0);\n        vert2chart[id0].insert(chart1);\n        vert2chart[id1].insert(chart0);\n        vert2chart[id1].insert(chart1);\n    }\n    for (auto vc : vert2chart)\n    {\n        if (vc.second.size() == 6)\n        {\n            std::vector<int> xchart, ychart, zchart;\n            for (auto chart : vc.second)\n            {\n                int axis = polycube_chart_label[chart] / 2;\n                switch (axis)\n                {\n                case 0:\n                    xchart.push_back(chart);\n                    break;\n                case 1:\n                    ychart.push_back(chart);\n                    break;\n                case 2:\n                    zchart.push_back(chart);\n                    break;\n                default:\n                    break;\n                }\n            }\n            assert(xchart.size() == 2 && ychart.size() == 2 && zchart.size() == 2);\n            coef.push_back(Eigen::Triplet<double>(up_down_chart_count + n_valence_six_constraint, xchart[0], +1.0));\n            coef.push_back(Eigen::Triplet<double>(up_down_chart_count + n_valence_six_constraint, xchart[1], -1.0));\n            bkc.push_back(MSK_BK_FX); blc.push_back(0.0); buc.push_back(0.0);\n            coef.push_back(Eigen::Triplet<double>(up_down_chart_count + n_valence_six_constraint + 1, ychart[0], +1.0));\n            coef.push_back(Eigen::Triplet<double>(up_down_chart_count + n_valence_six_constraint + 1, ychart[1], -1.0));\n            bkc.push_back(MSK_BK_FX); blc.push_back(0.0); buc.push_back(0.0);\n            coef.push_back(Eigen::Triplet<double>(up_down_chart_count + n_valence_six_constraint + 2, zchart[0], +1.0));\n            coef.push_back(Eigen::Triplet<double>(up_down_chart_count + n_valence_six_constraint + 2, zchart[1], -1.0));\n            bkc.push_back(MSK_BK_FX); blc.push_back(0.0); buc.push_back(0.0);\n            n_valence_six_constraint += 3;\n        }\n    }\n    Eigen::SparseMatrix<double> A(up_down_chart_count + cut_num + n_valence_six_constraint, chart_number);\n    A.setFromTriplets(coef.begin(), coef.end());\n    int size = A.nonZeros(); int cols = A.cols();\n    aptrb.resize(cols + 1); asub.resize(size); aval.resize(size);\n    aptrb[cols] = size;\n    int ind = 0;\n    for (int k = 0; k < cols; ++k)\n    {\n        aptrb[k] = ind;\n        for (Eigen::SparseMatrix<double>::InnerIterator it(A, k); it; ++it)\n        {\n            aval[ind] = it.value();\n            asub[ind] = it.row();\n            ++ind;\n        }\n    }\n    std::vector<double> c(chart_number, 0.0);\n    for (int i = 0; i < chart_number; ++i)\n    {\n        qsubi.push_back(i); qsubj.push_back(i); qval.push_back(2.0);\n        c[i] = -2.0 * chart_mean_value[i];\n    }\n    bkx.resize(chart_number, MSK_BK_FR); blx.resize(chart_number, -MSK_INFINITY); bux.resize(chart_number, +MSK_INFINITY);\n    std::vector<double> x(chart_number, 0.0); int mosek_count = 0;\n    bool solve_success = solveConvexQuadPorgramming_mosek(bkc, blc, buc, bkx, blx, bux, aptrb, asub, aval, qsubi, qsubj, qval, c, x);\n    while (!solve_success)\n    {\n        ratio_diff *= 0.8;\n        for (int i = 0; i < up_down_chart_count; ++i)\n        {\n            diff_u_d = diff_up_down[i] * ratio_diff;\n            if (hex_meshing_flag)\n                if (diff_u_d < cube_len)\n                {\n                    diff_u_d = cube_len;\n                }\n            blc[i] = diff_u_d;\n        }\n        solve_success = solveConvexQuadPorgramming_mosek(bkc, blc, buc, bkx, blx, bux, aptrb, asub, aval, qsubi, qsubj, qval, c, x);\n        ++mosek_count;\n        if (mosek_count > 20) break;\n    }\n    if (mosek_count > 20)\n    {\n        printf(\"-------------------------------------------\\nNo Solution!!!!!\\n\");\n        return false;\n    }\n    else\n    {\n        for (int i = 0; i < chart_number; ++i)\n        {\n            if (hex_meshing_flag)\n            {\n                chart_mean_value[i] = cube_len * std::floor(x[i] / cube_len + 0.5);\n                std::cout << \"solution: \" << chart_mean_value[i] / cube_len << std::endl;\n                double offset_ratio = offset;\n                if (polycube_chart_label[i] % 2 == 0)\n                {\n                    chart_mean_value[i] += cube_len * offset_ratio;\n                }\n                else\n                {\n                    chart_mean_value[i] -= cube_len * offset_ratio;\n                }\n            }\n            else\n            {\n                chart_mean_value[i] = x[i];\n                std::cout << \"solution: \" << chart_mean_value[i] << std::endl;\n            }\n        }\n    }\n    return true;\n}\nvoid polycube_flattening_interface::boundary_mapping_polycube_equal_face(TetStructure<double>* tet_mesh_)\n{\n    const std::vector<Tetrahedron<double>*> &tetras = tet_mesh_->tetras;\n    std::vector<TetVertex<double>*> &tetra_vertices = tet_mesh_->tetra_vertices;\n    int nv = tetra_vertices.size();\n    int nc = tetras.size();\n    std::vector<int> map_v(nv, -1); std::vector<int> map_c(nc, -1);\n    int chart_size = polycube_chart_label.size();\n    int chart_pair_size = cut_to_chart_pair.size();\n    for (size_t i = 0; i < chart_pair_size; i++)\n    {\n        int matrix_type = cut_types[i];\n        int chart1 = cut_to_chart_pair[i].first;\n        int chart2 = cut_to_chart_pair[i].second;\n        int var_v_count = 0; int var_c_count = 0;\n        std::vector<int>& one_chart = polycube_chart[chart1];\n        std::vector<int> chart_boundary_flag;\n        chart_boundary_flag.resize(nv, -1);\n        for (int j = 0; j < one_chart.size(); ++j)\n        {\n            int bf_id = one_chart[j];\n            for (int k = 0; k < 3; ++k)\n            {\n                int v_id = bfv_id[bf_id][k];\n                bool fixed = ((is_polycube_handles[3 * v_id + 0] == 1) && (is_polycube_handles[3 * v_id + 1] == 1) && (is_polycube_handles[3 * v_id + 2] == 1));\n                if (!fixed)\n                {\n                    if (map_v[v_id] < 0)\n                    {\n                        map_v[v_id] = var_v_count; ++var_v_count;\n                    }\n                    if (map_c[bf_id] < 0)\n                    {\n                        map_c[bf_id] = var_c_count; ++var_c_count;\n                    }\n                }\n                else\n                {\n                    chart_boundary_flag[v_id] = 1;\n                }\n            }\n        }\n        int chart_label = polycube_chart_label[chart1];\n        int chart_label_pair = polycube_chart_label[chart2];\n        polycube_boundary_mapping_IVF pbm;\n        pbm.optimize_IVF(tet_mesh_, chart_label, src_pos, bfv_id, bvf_id, map_v, var_v_count, map_c, var_c_count);\n        int common_vert_idx = cut_common_verts_idx[i];\n        CVec<double, 3> np_common = tetra_vertices[common_vert_idx]->pos;\n        for (size_t j = 0; j < nv; j++)\n        {\n            if (map_v[j] >= 0 || chart_boundary_flag[j] > 0)\n            {\n                if (three_cut_vert_flag.size() > 0)\n                {\n                    if (three_cut_vert_flag[j] > 0)\n                        continue;\n                }\n                if (j == common_vert_idx)\n                    continue;\n                int pair_idx = vert_pairs_map[j];\n                if (pair_idx < 0)\n                {\n                }\n                CVec<double, 3> np = tetra_vertices[j]->pos;\n                CVec<double, 3> np_pair;\n                double rot_vec[3];\n                double ori_vec[3] = { np[0] - np_common[0], np[1] - np_common[1], np[2] - np_common[2] };\n                for (size_t b = 0; b < 3; b++)\n                {\n                    rot_vec[b] = 0.0;\n                    for (size_t c = 0; c < 3; c++)\n                    {\n                        rot_vec[b] += type_matrix[matrix_type][b][c] * ori_vec[c];\n                    }\n                }\n                np_pair[0] = np_common[0] + rot_vec[0];\n                np_pair[1] = np_common[1] + rot_vec[1];\n                np_pair[2] = np_common[2] + rot_vec[2];\n                tetra_vertices[pair_idx]->pos = np_pair;\n            }\n        }\n        for (int j = 0; j < nv; ++j)\n        {\n            if (map_v[j] >= 0 || chart_boundary_flag[j] > 0)\n            {\n                is_polycube_handles[3 * j + 0] = 1; is_polycube_handles[3 * j + 1] = 1; is_polycube_handles[3 * j + 2] = 1;\n                int pair_idx = vert_pairs_map[j];\n                is_polycube_handles[3 * pair_idx + 0] = 1; is_polycube_handles[3 * pair_idx + 1] = 1; is_polycube_handles[3 * pair_idx + 2] = 1;\n            }\n            map_v[j] = -1;\n        }\n        for (int j = 0; j < nc; ++j)\n        {\n            map_c[j] = -1;\n        }\n    }\n    for (int i = 0; i < chart_size; ++i)\n    {\n        bool cut_flag = false;\n        for (size_t j = 0; j < cut_to_chart_pair.size(); j++)\n        {\n            if (i == cut_to_chart_pair[j].first)\n            {\n                cut_flag = true;\n                break;\n            }\n            if (i == cut_to_chart_pair[j].second)\n            {\n                cut_flag = true;\n                break;\n            }\n        }\n        if (cut_flag)\n        {\n            continue;\n        }\n        int var_v_count = 0; int var_c_count = 0;\n        std::vector<int>& one_chart = polycube_chart[i];\n        for (int j = 0; j < one_chart.size(); ++j)\n        {\n            int bf_id = one_chart[j];\n            for (int k = 0; k < 3; ++k)\n            {\n                int v_id = bfv_id[bf_id][k];\n                bool fixed = ((is_polycube_handles[3 * v_id + 0] == 1) && (is_polycube_handles[3 * v_id + 1] == 1) && (is_polycube_handles[3 * v_id + 2] == 1));\n                if (!fixed)\n                {\n                    if (map_v[v_id] < 0)\n                    {\n                        map_v[v_id] = var_v_count; ++var_v_count;\n                    }\n                    if (map_c[bf_id] < 0)\n                    {\n                        map_c[bf_id] = var_c_count; ++var_c_count;\n                    }\n                }\n            }\n        }\n        int chart_label = polycube_chart_label[i];\n        polycube_boundary_mapping_IVF pbm;\n        pbm.optimize_IVF(tet_mesh_, chart_label, src_pos, bfv_id, bvf_id, map_v, var_v_count, map_c, var_c_count);\n        for (int j = 0; j < nv; ++j)\n        {\n            if (map_v[j] >= 0)\n            {\n                is_polycube_handles[3 * j + 0] = 1; is_polycube_handles[3 * j + 1] = 1; is_polycube_handles[3 * j + 2] = 1;\n            }\n            map_v[j] = -1;\n        }\n        for (int j = 0; j < nc; ++j)\n        {\n            map_c[j] = -1;\n        }\n    }\n}\nbool polycube_flattening_interface::deform_ARAP_polycube_equal_face(TetStructure<double>* tet_mesh_, bool int_solver_flag, bool add_constraint, bool set_min_diff, double offset, bool double_cube_length_flag)\n{\n    find_all_corner(tet_mesh_);\n    if (add_constraint)\n    {\n        update_updownchart(tet_mesh_);\n    }\n    bool find_chart_flag;\n    if (double_cube_length_flag)\n        cube_len = cube_len * 2;\n    if (!hex_meshing_flag)\n    {\n        if (set_min_diff)\n        {\n            find_chart_flag = find_all_chart_value_preprocessing(tet_mesh_);\n        }\n        else\n        {\n            find_chart_flag = find_all_chart_value_equal_face_mine(tet_mesh_, offset);\n        }\n    }\n    else\n    {\n        if (int_solver_flag)\n        {\n            find_chart_flag = find_all_chart_value_equal_face_mine(tet_mesh_, offset);\n        }\n        else\n        {\n            find_chart_flag = find_all_chart_value_equal_face_rounding(tet_mesh_, offset);\n        }\n    }\n    if (double_cube_length_flag)\n        cube_len = cube_len / 2;\n    if (!find_chart_flag)\n        return false;\n    int nv = vertex_type.size();\n    is_polycube_handles.clear(); is_polycube_handles.resize(3 * nv, -1);\n    std::vector<int> polycube_edge_v; std::vector<int> polycube_edge_v_neighbor;\n    std::vector<int> polycube_edge_v_type;\n    const std::vector<Tetrahedron<double>*> &tetras = tet_mesh_->tetras;\n    std::vector<TetVertex<double>*> &tetra_vertices = tet_mesh_->tetra_vertices;\n    std::vector<int> corner_pts_idx;\n    std::vector<std::vector<int>> corner_faces;\n    std::map<int, ig::CVec<double, 3>> idx2coord;\n    corner_faces.resize(chart_mean_value.size());\n    for (int i = 0; i < nv; i++)\n    {\n        OpenVolumeMesh::Geometry::Vec3i& v_type = vertex_type[i];\n        if (v_type[0] >= 0 && v_type[1] >= 0 && v_type[2] >= 0)\n        {\n            corner_pts_idx.push_back(i);\n            CVec<double, 3> np = tetra_vertices[i]->pos;\n            idx2coord.insert(std::pair<int, ig::CVec<double, 3>>(i, np));\n            corner_faces[v_type[0]].push_back(i);\n            corner_faces[v_type[1]].push_back(i);\n            corner_faces[v_type[2]].push_back(i);\n        }\n    }\n    for (int i = 0; i < nv; ++i)\n    {\n        OpenVolumeMesh::Geometry::Vec3i& v_type = vertex_type[i];\n        CVec<double, 3> np = tetra_vertices[i]->pos;\n        if (v_type[0] >= 0)\n        {\n            np[0] = chart_mean_value[v_type[0]];\n            dpx[i] = np[0];\n            is_polycube_handles[3 * i + 0] = 1;\n        }\n        if (v_type[1] >= 0)\n        {\n            np[1] = chart_mean_value[v_type[1]];\n            dpy[i] = np[1];\n            is_polycube_handles[3 * i + 1] = 1;\n        }\n        if (v_type[2] >= 0)\n        {\n            np[2] = chart_mean_value[v_type[2]];\n            dpz[i] = np[2];\n            is_polycube_handles[3 * i + 2] = 1;\n        }\n        tetra_vertices[i]->pos = np;\n        if (v_type[0] >= 0 && v_type[1] >= 0 && v_type[2] < 0)\n        {\n            polycube_edge_v.push_back(i);\n            polycube_edge_v_type.push_back(2);\n            is_polycube_handles[3 * i + 2] = 1;\n        }\n        else if (v_type[0] < 0 && v_type[1] >= 0 && v_type[2] >= 0)\n        {\n            polycube_edge_v.push_back(i);\n            polycube_edge_v_type.push_back(0);\n            is_polycube_handles[3 * i + 0] = 1;\n        }\n        else if (v_type[0] >= 0 && v_type[1] < 0 && v_type[2] >= 0)\n        {\n            polycube_edge_v.push_back(i);\n            polycube_edge_v_type.push_back(1);\n            is_polycube_handles[3 * i + 1] = 1;\n        }\n    }\n    bool flag_translation = true;\n    if (flag_translation)\n    {\n        std::vector<ig::CVec<double, 3>> chart_translation;\n        for (size_t i = 0; i < chart_mean_value.size(); i++)\n        {\n            int face_size = corner_faces[i].size();\n            ig::CVec<double, 3> tmp_translation(0.0, 0.0, 0.0);\n            for (size_t j = 0; j < face_size; j++)\n            {\n                int tmp_idx = corner_faces[i][j];\n                tmp_translation = tmp_translation + tetra_vertices[tmp_idx]->pos - idx2coord[tmp_idx];\n            }\n            tmp_translation = tmp_translation / (double)face_size;\n            int ignore_label = polycube_chart_label[i];\n            tmp_translation[ignore_label / 2] = 0.0;\n            chart_translation.push_back(tmp_translation);\n        }\n        for (size_t i = 0; i < nv; i++)\n        {\n            std::vector<int> tmp_vert_belong_chart;\n            OpenVolumeMesh::Geometry::Vec3i& v_type = vertex_type[i];\n            if (v_type[0] >= 0)\n                tmp_vert_belong_chart.push_back(v_type[0]);\n            if (v_type[1] >= 0)\n                tmp_vert_belong_chart.push_back(v_type[1]);\n            if (v_type[2] >= 0)\n                tmp_vert_belong_chart.push_back(v_type[2]);\n            if (tmp_vert_belong_chart.size() == 1)\n            {\n                int tmp_chart = tmp_vert_belong_chart[0];\n                CVec<double, 3> np = tetra_vertices[i]->pos;\n                np = np + chart_translation[tmp_chart];\n                tetra_vertices[i]->pos = np;\n            }\n        }\n    }\n    for (int i = 0; i < polycube_edge_v.size(); ++i)\n    {\n        int v_id = polycube_edge_v[i];\n        CVec<double, 3> np = tetra_vertices[v_id]->pos;\n        std::vector<int>& one_vv = bvv_id[v_id];\n        int vv_size = one_vv.size(); int add_nv = 0;\n        for (int j = 0; j < vv_size; ++j)\n        {\n            int vj_id = one_vv[j];\n            OpenVolumeMesh::Geometry::Vec3i& vj_type = vertex_type[vj_id]; int chart_count = 0; bool can_add = false;\n            if (vj_type[0] >= 0) ++chart_count;\n            if (vj_type[1] >= 0) ++chart_count;\n            if (vj_type[2] >= 0) ++chart_count;\n            if (chart_count == 3)\n            {\n                can_add = true;\n            }\n            else if (chart_count == 2)\n            {\n                if (vj_type[polycube_edge_v_type[i]] < 0)\n                {\n                    can_add = true;\n                }\n            }\n            if (can_add)\n            {\n                CVec<double, 3> npj = tetra_vertices[vj_id]->pos;\n                bool nv_ok = true;\n                for (int k = 0; k < 3; ++k)\n                {\n                    if (k != polycube_edge_v_type[i])\n                    {\n                        if (std::abs(npj[k] - np[k]) > 1e-10) nv_ok = false;\n                    }\n                }\n                if (nv_ok)\n                {\n                    polycube_edge_v_neighbor.push_back(vj_id);\n                    ++add_nv;\n                }\n            }\n        }\n        if (add_nv > 0 && add_nv != 2)\n        {\n            if (add_nv > 2)\n            {\n                int pevn_size = polycube_edge_v_neighbor.size();\n                std::vector<int> delete_v;\n                std::vector<int> visited_f(tetras.size(), 0);\n                std::vector<int>& one_vf = bvf_id[v_id];\n                for (int j = 0; j < one_vf.size(); ++j)\n                {\n                    visited_f[one_vf[j]] += 1;\n                }\n                for (int j = pevn_size - add_nv; j < pevn_size; ++j)\n                {\n                    int vj_id = polycube_edge_v_neighbor[j];\n                    std::vector<int>& one_vj_f = bvf_id[vj_id];\n                    int two_f[2]; int two_count = 0;\n                    for (int k = 0; k < one_vj_f.size(); ++k)\n                    {\n                        if (visited_f[one_vj_f[k]] == 1)\n                        {\n                            two_f[two_count] = one_vj_f[k]; ++two_count;\n                        }\n                    }\n                    if (bf_chart[two_f[0]] == bf_chart[two_f[1]])\n                    {\n                        delete_v.push_back(j);\n                    }\n                }\n                for (int j = 0; j < delete_v.size(); ++j)\n                {\n                    polycube_edge_v_neighbor.erase(polycube_edge_v_neighbor.begin() + delete_v[delete_v.size() - 1 - j]);\n                }\n            }\n        }\n    }\n    if (true)\n    {\n        if (polycube_edge_v_neighbor.size() == 2 * polycube_edge_v.size())\n        {\n            for (int i = 0; i < 20; ++i)\n            {\n                for (int j = 0; j < polycube_edge_v.size(); ++j)\n                {\n                    int v_id = polycube_edge_v[j];\n                    CVec<double, 3> np = tetra_vertices[v_id]->pos;\n                    CVec<double, 3> p0 = tetra_vertices[polycube_edge_v_neighbor[2 * j + 0]]->pos;\n                    CVec<double, 3> p1 = tetra_vertices[polycube_edge_v_neighbor[2 * j + 1]]->pos;\n                    int edge_type = polycube_edge_v_type[j];\n                    np[edge_type] = 0.5*(p0[edge_type] + p1[edge_type]);\n                    tetra_vertices[v_id]->pos = np;\n                    dpx[v_id] = np[0]; dpy[v_id] = np[1]; dpz[v_id] = np[2];\n                }\n            }\n        }\n    }\n    if (true)\n    {\n        assert(three_cut_common_vert.size() == three_cut_vert.size());\n        for (size_t i = 0; i < three_cut_common_vert.size(); i++)\n        {\n            int common_vert = three_cut_common_vert[i];\n            int n_segment = three_cut_vert[i].size();\n            int end_idx[3];\n            end_idx[0] = three_cut_vert[i][0][0];\n            end_idx[1] = three_cut_vert[i][0][1];\n            end_idx[2] = three_cut_vert[i][0][2];\n            CVec<double, 3> common_pos = tetra_vertices[common_vert]->pos;\n            CVec<double, 3> end_pos[3];\n            end_pos[0] = tetra_vertices[end_idx[0]]->pos;\n            end_pos[1] = tetra_vertices[end_idx[1]]->pos;\n            end_pos[2] = tetra_vertices[end_idx[2]]->pos;\n            CVec<double, 3> seg[3];\n            seg[0] = (common_pos - end_pos[0]) / n_segment;\n            seg[1] = (common_pos - end_pos[1]) / n_segment;\n            seg[2] = (common_pos - end_pos[2]) / n_segment;\n            for (int j = 1; j < three_cut_vert[i].size(); j++)\n            {\n                for (int k = 0; k < 3; k++)\n                {\n                    int v_id = three_cut_vert[i][j][k];\n                    CVec<double, 3> np = tetra_vertices[v_id]->pos;\n                    np = end_pos[k] + j * seg[k];\n                    tetra_vertices[v_id]->pos = np;\n                    dpx[v_id] = np[0]; dpy[v_id] = np[1]; dpz[v_id] = np[2];\n                }\n            }\n        }\n    }\n    boundary_mapping_polycube_equal_face(tet_mesh_);\n    double min_singular_value = 0.001;\n    int nc = tetras.size();\n    Eigen::Matrix3d VS, Q, U, V, R;\n    std::vector < std::vector < double >> Cell_R(nc);\n    for (int c_id = 0; c_id < nc; ++c_id)\n    {\n        Cell_R[c_id].resize(9);\n    }\n    for (int iter = 0; iter < 3; ++iter)\n    {\n        for (int c_id = 0; c_id < nc; ++c_id)\n        {\n            std::vector<int>& cv_id = cell_vertex[c_id];\n            double cpx = dpx[cv_id[0]]; double cpy = dpy[cv_id[0]]; double cpz = dpz[cv_id[0]];\n            VS(0, 0) = dpx[cv_id[1]] - cpx; VS(1, 0) = dpy[cv_id[1]] - cpy; VS(2, 0) = dpz[cv_id[1]] - cpz;\n            VS(0, 1) = dpx[cv_id[2]] - cpx; VS(1, 1) = dpy[cv_id[2]] - cpy; VS(2, 1) = dpz[cv_id[2]] - cpz;\n            VS(0, 2) = dpx[cv_id[3]] - cpx; VS(1, 2) = dpy[cv_id[3]] - cpy; VS(2, 2) = dpz[cv_id[3]] - cpz;\n            Q = VS * cell_S[c_id];\n            Eigen::JacobiSVD<Eigen::Matrix3d> svd(Q, Eigen::ComputeFullU | Eigen::ComputeFullV);\n            U = svd.matrixU(); V = svd.matrixV();\n            double sig0 = svd.singularValues()[0];\n            double sig1 = svd.singularValues()[1];\n            double sig2 = svd.singularValues()[2];\n            if (Q.determinant() > 0)\n            {\n                R = V * U.transpose();\n            }\n            else\n            {\n                U(0, 2) = -U(0, 2); U(1, 2) = -U(1, 2); U(2, 2) = -U(2, 2);\n                R = V * U.transpose();\n            }\n            Cell_R[c_id][0] = R(0, 0); Cell_R[c_id][1] = R(0, 1); Cell_R[c_id][2] = R(0, 2);\n            Cell_R[c_id][3] = R(1, 0); Cell_R[c_id][4] = R(1, 1); Cell_R[c_id][5] = R(1, 2);\n            Cell_R[c_id][6] = R(2, 0); Cell_R[c_id][7] = R(2, 1); Cell_R[c_id][8] = R(2, 2);\n        }\n        for (int i = 0; i < 3; ++i)\n        {\n            int var_count = 0; std::vector<int> map_v(nv, -1);\n            for (int j = 0; j < nv; ++j)\n            {\n                if (is_polycube_handles[3 * j + i] != 1)\n                {\n                    map_v[j] = var_count;\n                    ++var_count;\n                }\n            }\n            Sparse_Matrix A = new Sparse_Matrix(nc * 3, var_count, NOSYM, CCS, 1);\n            std::vector<double> cs(4);\n            for (int c_id = 0; c_id < nc; ++c_id)\n            {\n                double cv = std::sqrt(std::abs(cell_volume[c_id])) * 100;\n                std::vector<int>& cv_id = cell_vertex[c_id];\n                Eigen::Matrix3d& CS = cell_S[c_id];\n                std::vector<double>& CR = Cell_R[c_id];\n                for (int j = 0; j < 3; ++j)\n                {\n                    cs[1] = CS(0, j)*cv; cs[2] = CS(1, j)*cv; cs[3] = CS(2, j)*cv;\n                    cs[0] = -(cs[1] + cs[2] + cs[3]);\n                    for (int k = 0; k < 4; ++k)\n                    {\n                        int var_id = map_v[cv_id[k]];\n                        if (var_id < 0)\n                        {\n                            A.fill_rhs_entry(3 * c_id + j, -cs[k] * tetra_vertices[cv_id[k]]->pos[i]);\n                        }\n                        else\n                        {\n                            A.fill_entry(3 * c_id + j, var_id, cs[k]);\n                        }\n                    }\n                    A.fill_rhs_entry(3 * c_id + j, cv*CR[i + 3 * j]);\n                }\n            }\n            Sparse_Matrix* D = TransposeTimesSelf(&A, CCS, SYM_LOWER, true);\n            solve_by_CHOLMOD(D);\n            const std::vector<double>& xyz = D->get_solution();\n            for (int j = 0; j < nv; ++j)\n            {\n                if (is_polycube_handles[3 * j + i] != 1)\n                {\n                    int var_id = map_v[j];\n                    CVec<double, 3> np = tetra_vertices[j]->pos;\n                    np[i] = xyz[var_id];\n                    tetra_vertices[j]->pos = np;\n                }\n            }\n            delete D;\n        }\n        for (int j = 0; j < nv; ++j)\n        {\n            CVec<double, 3> np = tetra_vertices[j]->pos;\n            dpx[j] = np[0]; dpy[j] = np[1]; dpz[j] = np[2];\n        }\n    }\n    for (int j = 0; j < nv; ++j)\n    {\n        CVec<double, 3> np = tetra_vertices[j]->pos;\n        dpx[j] = np[0]; dpy[j] = np[1]; dpz[j] = np[2];\n    }\n    return true;\n}\nbool polycube_flattening_interface::deform_ARAP_polycube_equal_face(TetStructure<double>* tet_mesh_, const std::vector<double>& chart_mean_value_ori, double lambda, bool add_constraint, bool set_min_diff, double offset, bool double_cube_length_flag)\n{\n    if (add_constraint)\n    {\n        update_updownchart(tet_mesh_);\n    }\n    bool find_chart_flag;\n    if (double_cube_length_flag)\n        cube_len = cube_len * 2;\n    if (!hex_meshing_flag)\n    {\n        if (set_min_diff)\n        {\n            find_chart_flag = find_all_chart_value_preprocessing(tet_mesh_);\n        }\n        else\n        {\n            find_chart_flag = find_all_chart_value_equal_face_mine(tet_mesh_, chart_mean_value_ori, lambda, add_constraint, set_min_diff, offset);\n        }\n    }\n    else\n    {\n        find_chart_flag = find_all_chart_value_equal_face_mine(tet_mesh_, chart_mean_value_ori, lambda, add_constraint, set_min_diff, offset);\n    }\n    if (double_cube_length_flag)\n        cube_len = cube_len / 2;\n    if (!find_chart_flag)\n        return false;\n    int nv = vertex_type.size();\n    is_polycube_handles.clear(); is_polycube_handles.resize(3 * nv, -1);\n    std::vector<int> polycube_edge_v; std::vector<int> polycube_edge_v_neighbor;\n    std::vector<int> polycube_edge_v_type;\n    const std::vector<Tetrahedron<double>*> &tetras = tet_mesh_->tetras;\n    std::vector<TetVertex<double>*> &tetra_vertices = tet_mesh_->tetra_vertices;\n    std::vector<int> corner_pts_idx;\n    std::vector<std::vector<int>> corner_faces;\n    std::map<int, ig::CVec<double, 3>> idx2coord;\n    corner_faces.resize(chart_mean_value.size());\n    for (int i = 0; i < nv; i++)\n    {\n        OpenVolumeMesh::Geometry::Vec3i& v_type = vertex_type[i];\n        if (v_type[0] >= 0 && v_type[1] >= 0 && v_type[2] >= 0)\n        {\n            corner_pts_idx.push_back(i);\n            CVec<double, 3> np = tetra_vertices[i]->pos;\n            idx2coord.insert(std::pair<int, ig::CVec<double, 3>>(i, np));\n            corner_faces[v_type[0]].push_back(i);\n            corner_faces[v_type[1]].push_back(i);\n            corner_faces[v_type[2]].push_back(i);\n        }\n    }\n    for (int i = 0; i < nv; ++i)\n    {\n        OpenVolumeMesh::Geometry::Vec3i& v_type = vertex_type[i];\n        CVec<double, 3> np = tetra_vertices[i]->pos;\n        if (v_type[0] >= 0)\n        {\n            np[0] = chart_mean_value[v_type[0]];\n            dpx[i] = np[0];\n            is_polycube_handles[3 * i + 0] = 1;\n        }\n        if (v_type[1] >= 0)\n        {\n            np[1] = chart_mean_value[v_type[1]];\n            dpy[i] = np[1];\n            is_polycube_handles[3 * i + 1] = 1;\n        }\n        if (v_type[2] >= 0)\n        {\n            np[2] = chart_mean_value[v_type[2]];\n            dpz[i] = np[2];\n            is_polycube_handles[3 * i + 2] = 1;\n        }\n        tetra_vertices[i]->pos = np;\n        if (v_type[0] >= 0 && v_type[1] >= 0 && v_type[2] < 0)\n        {\n            polycube_edge_v.push_back(i);\n            polycube_edge_v_type.push_back(2);\n            is_polycube_handles[3 * i + 2] = 1;\n        }\n        else if (v_type[0] < 0 && v_type[1] >= 0 && v_type[2] >= 0)\n        {\n            polycube_edge_v.push_back(i);\n            polycube_edge_v_type.push_back(0);\n            is_polycube_handles[3 * i + 0] = 1;\n        }\n        else if (v_type[0] >= 0 && v_type[1] < 0 && v_type[2] >= 0)\n        {\n            polycube_edge_v.push_back(i);\n            polycube_edge_v_type.push_back(1);\n            is_polycube_handles[3 * i + 1] = 1;\n        }\n    }\n    bool flag_translation = true;\n    if (flag_translation)\n    {\n        std::vector<ig::CVec<double, 3>> chart_translation;\n        for (size_t i = 0; i < chart_mean_value.size(); i++)\n        {\n            int face_size = corner_faces[i].size();\n            ig::CVec<double, 3> tmp_translation(0.0, 0.0, 0.0);\n            for (size_t j = 0; j < face_size; j++)\n            {\n                int tmp_idx = corner_faces[i][j];\n                tmp_translation = tmp_translation + tetra_vertices[tmp_idx]->pos - idx2coord[tmp_idx];\n            }\n            tmp_translation = tmp_translation / (double)face_size;\n            int ignore_label = polycube_chart_label[i];\n            tmp_translation[ignore_label / 2] = 0.0;\n            chart_translation.push_back(tmp_translation);\n        }\n        for (size_t i = 0; i < nv; i++)\n        {\n            std::vector<int> tmp_vert_belong_chart;\n            OpenVolumeMesh::Geometry::Vec3i& v_type = vertex_type[i];\n            if (v_type[0] >= 0)\n                tmp_vert_belong_chart.push_back(v_type[0]);\n            if (v_type[1] >= 0)\n                tmp_vert_belong_chart.push_back(v_type[1]);\n            if (v_type[2] >= 0)\n                tmp_vert_belong_chart.push_back(v_type[2]);\n            if (tmp_vert_belong_chart.size() == 1)\n            {\n                int tmp_chart = tmp_vert_belong_chart[0];\n                CVec<double, 3> np = tetra_vertices[i]->pos;\n                np = np + chart_translation[tmp_chart];\n                tetra_vertices[i]->pos = np;\n            }\n        }\n    }\n    for (int i = 0; i < polycube_edge_v.size(); ++i)\n    {\n        int v_id = polycube_edge_v[i];\n        CVec<double, 3> np = tetra_vertices[v_id]->pos;\n        std::vector<int>& one_vv = bvv_id[v_id];\n        int vv_size = one_vv.size(); int add_nv = 0;\n        for (int j = 0; j < vv_size; ++j)\n        {\n            int vj_id = one_vv[j];\n            OpenVolumeMesh::Geometry::Vec3i& vj_type = vertex_type[vj_id]; int chart_count = 0; bool can_add = false;\n            if (vj_type[0] >= 0) ++chart_count;\n            if (vj_type[1] >= 0) ++chart_count;\n            if (vj_type[2] >= 0) ++chart_count;\n            if (chart_count == 3)\n            {\n                can_add = true;\n            }\n            else if (chart_count == 2)\n            {\n                if (vj_type[polycube_edge_v_type[i]] < 0)\n                {\n                    can_add = true;\n                }\n            }\n            if (can_add)\n            {\n                CVec<double, 3> npj = tetra_vertices[vj_id]->pos;\n                bool nv_ok = true;\n                for (int k = 0; k < 3; ++k)\n                {\n                    if (k != polycube_edge_v_type[i])\n                    {\n                        if (std::abs(npj[k] - np[k]) > 1e-10) nv_ok = false;\n                    }\n                }\n                if (nv_ok)\n                {\n                    polycube_edge_v_neighbor.push_back(vj_id);\n                    ++add_nv;\n                }\n            }\n        }\n        if (add_nv > 0 && add_nv != 2)\n        {\n            if (add_nv > 2)\n            {\n                int pevn_size = polycube_edge_v_neighbor.size();\n                std::vector<int> delete_v;\n                std::vector<int> visited_f(tetras.size(), 0);\n                std::vector<int>& one_vf = bvf_id[v_id];\n                for (int j = 0; j < one_vf.size(); ++j)\n                {\n                    visited_f[one_vf[j]] += 1;\n                }\n                for (int j = pevn_size - add_nv; j < pevn_size; ++j)\n                {\n                    int vj_id = polycube_edge_v_neighbor[j];\n                    std::vector<int>& one_vj_f = bvf_id[vj_id];\n                    int two_f[2]; int two_count = 0;\n                    for (int k = 0; k < one_vj_f.size(); ++k)\n                    {\n                        if (visited_f[one_vj_f[k]] == 1)\n                        {\n                            two_f[two_count] = one_vj_f[k]; ++two_count;\n                        }\n                    }\n                    if (bf_chart[two_f[0]] == bf_chart[two_f[1]])\n                    {\n                        delete_v.push_back(j);\n                    }\n                }\n                for (int j = 0; j < delete_v.size(); ++j)\n                {\n                    polycube_edge_v_neighbor.erase(polycube_edge_v_neighbor.begin() + delete_v[delete_v.size() - 1 - j]);\n                }\n            }\n        }\n    }\n    printf(\"polycube edge information: \\n\");\n    printf(\"%d %d\\n\", polycube_edge_v.size(), polycube_edge_v_neighbor.size());\n    if (true)\n    {\n        if (polycube_edge_v_neighbor.size() == 2 * polycube_edge_v.size())\n        {\n            for (int i = 0; i < 20; ++i)\n            {\n                for (int j = 0; j < polycube_edge_v.size(); ++j)\n                {\n                    int v_id = polycube_edge_v[j];\n                    CVec<double, 3> np = tetra_vertices[v_id]->pos;\n                    CVec<double, 3> p0 = tetra_vertices[polycube_edge_v_neighbor[2 * j + 0]]->pos;\n                    CVec<double, 3> p1 = tetra_vertices[polycube_edge_v_neighbor[2 * j + 1]]->pos;\n                    int edge_type = polycube_edge_v_type[j];\n                    np[edge_type] = 0.5*(p0[edge_type] + p1[edge_type]);\n                    tetra_vertices[v_id]->pos = np;\n                    dpx[v_id] = np[0]; dpy[v_id] = np[1]; dpz[v_id] = np[2];\n                }\n            }\n        }\n    }\n    if (true)\n    {\n        assert(three_cut_common_vert.size() == three_cut_vert.size());\n        for (size_t i = 0; i < three_cut_common_vert.size(); i++)\n        {\n            int common_vert = three_cut_common_vert[i];\n            int n_segment = three_cut_vert[i].size();\n            int end_idx[3];\n            end_idx[0] = three_cut_vert[i][0][0];\n            end_idx[1] = three_cut_vert[i][0][1];\n            end_idx[2] = three_cut_vert[i][0][2];\n            CVec<double, 3> common_pos = tetra_vertices[common_vert]->pos;\n            CVec<double, 3> end_pos[3];\n            end_pos[0] = tetra_vertices[end_idx[0]]->pos;\n            end_pos[1] = tetra_vertices[end_idx[1]]->pos;\n            end_pos[2] = tetra_vertices[end_idx[2]]->pos;\n            CVec<double, 3> seg[3];\n            seg[0] = (common_pos - end_pos[0]) / n_segment;\n            seg[1] = (common_pos - end_pos[1]) / n_segment;\n            seg[2] = (common_pos - end_pos[2]) / n_segment;\n            for (int j = 1; j < three_cut_vert[i].size(); j++)\n            {\n                for (int k = 0; k < 3; k++)\n                {\n                    int v_id = three_cut_vert[i][j][k];\n                    CVec<double, 3> np = tetra_vertices[v_id]->pos;\n                    np = end_pos[k] + j * seg[k];\n                    tetra_vertices[v_id]->pos = np;\n                    dpx[v_id] = np[0]; dpy[v_id] = np[1]; dpz[v_id] = np[2];\n                }\n            }\n        }\n    }\n    boundary_mapping_polycube_equal_face(tet_mesh_);\n    if (false)\n    {\n        is_polycube_handles.clear(); is_polycube_handles.resize(3 * nv, -1);\n        for (int i = 0; i < nv; ++i)\n        {\n            OpenVolumeMesh::Geometry::Vec3i& v_type = vertex_type[i];\n            if (v_type[0] >= 0)\n            {\n                is_polycube_handles[3 * i + 0] = 1;\n            }\n            if (v_type[1] >= 0)\n            {\n                is_polycube_handles[3 * i + 1] = 1;\n            }\n            if (v_type[2] >= 0)\n            {\n                is_polycube_handles[3 * i + 2] = 1;\n            }\n        }\n    }\n    double min_singular_value = 0.001;\n    int nc = tetras.size();\n    Eigen::Matrix3d VS, Q, U, V, R;\n    std::vector < std::vector < double >> Cell_R(nc);\n    for (int c_id = 0; c_id < nc; ++c_id)\n    {\n        Cell_R[c_id].resize(9);\n    }\n    for (int iter = 0; iter < 3; ++iter)\n    {\n        for (int c_id = 0; c_id < nc; ++c_id)\n        {\n            std::vector<int>& cv_id = cell_vertex[c_id];\n            double cpx = dpx[cv_id[0]]; double cpy = dpy[cv_id[0]]; double cpz = dpz[cv_id[0]];\n            VS(0, 0) = dpx[cv_id[1]] - cpx; VS(1, 0) = dpy[cv_id[1]] - cpy; VS(2, 0) = dpz[cv_id[1]] - cpz;\n            VS(0, 1) = dpx[cv_id[2]] - cpx; VS(1, 1) = dpy[cv_id[2]] - cpy; VS(2, 1) = dpz[cv_id[2]] - cpz;\n            VS(0, 2) = dpx[cv_id[3]] - cpx; VS(1, 2) = dpy[cv_id[3]] - cpy; VS(2, 2) = dpz[cv_id[3]] - cpz;\n            Q = VS * cell_S[c_id];\n            Eigen::JacobiSVD<Eigen::Matrix3d> svd(Q, Eigen::ComputeFullU | Eigen::ComputeFullV);\n            U = svd.matrixU(); V = svd.matrixV();\n            double sig0 = svd.singularValues()[0];\n            double sig1 = svd.singularValues()[1];\n            double sig2 = svd.singularValues()[2];\n            if (Q.determinant() > 0)\n            {\n                R = V * U.transpose();\n            }\n            else\n            {\n                U(0, 2) = -U(0, 2); U(1, 2) = -U(1, 2); U(2, 2) = -U(2, 2);\n                R = V * U.transpose();\n            }\n            Cell_R[c_id][0] = R(0, 0); Cell_R[c_id][1] = R(0, 1); Cell_R[c_id][2] = R(0, 2);\n            Cell_R[c_id][3] = R(1, 0); Cell_R[c_id][4] = R(1, 1); Cell_R[c_id][5] = R(1, 2);\n            Cell_R[c_id][6] = R(2, 0); Cell_R[c_id][7] = R(2, 1); Cell_R[c_id][8] = R(2, 2);\n        }\n        for (int i = 0; i < 3; ++i)\n        {\n            int var_count = 0; std::vector<int> map_v(nv, -1);\n            for (int j = 0; j < nv; ++j)\n            {\n                if (is_polycube_handles[3 * j + i] != 1)\n                {\n                    map_v[j] = var_count;\n                    ++var_count;\n                }\n            }\n            Sparse_Matrix A = new Sparse_Matrix(nc * 3, var_count, NOSYM, CCS, 1);\n            std::vector<double> cs(4);\n            for (int c_id = 0; c_id < nc; ++c_id)\n            {\n                double cv = std::sqrt(std::abs(cell_volume[c_id])) * 100;\n                std::vector<int>& cv_id = cell_vertex[c_id];\n                Eigen::Matrix3d& CS = cell_S[c_id];\n                std::vector<double>& CR = Cell_R[c_id];\n                for (int j = 0; j < 3; ++j)\n                {\n                    cs[1] = CS(0, j)*cv; cs[2] = CS(1, j)*cv; cs[3] = CS(2, j)*cv;\n                    cs[0] = -(cs[1] + cs[2] + cs[3]);\n                    for (int k = 0; k < 4; ++k)\n                    {\n                        int var_id = map_v[cv_id[k]];\n                        if (var_id < 0)\n                        {\n                            A.fill_rhs_entry(3 * c_id + j, -cs[k] * tetra_vertices[cv_id[k]]->pos[i]);\n                        }\n                        else\n                        {\n                            A.fill_entry(3 * c_id + j, var_id, cs[k]);\n                        }\n                    }\n                    A.fill_rhs_entry(3 * c_id + j, cv*CR[i + 3 * j]);\n                }\n            }\n            Sparse_Matrix* D = TransposeTimesSelf(&A, CCS, SYM_LOWER, true);\n            solve_by_CHOLMOD(D);\n            const std::vector<double>& xyz = D->get_solution();\n            for (int j = 0; j < nv; ++j)\n            {\n                if (is_polycube_handles[3 * j + i] != 1)\n                {\n                    int var_id = map_v[j];\n                    CVec<double, 3> np = tetra_vertices[j]->pos;\n                    np[i] = xyz[var_id];\n                    tetra_vertices[j]->pos = np;\n                }\n            }\n            delete D;\n        }\n        for (int j = 0; j < nv; ++j)\n        {\n            CVec<double, 3> np = tetra_vertices[j]->pos;\n            dpx[j] = np[0]; dpy[j] = np[1]; dpz[j] = np[2];\n        }\n    }\n    for (int j = 0; j < nv; ++j)\n    {\n        CVec<double, 3> np = tetra_vertices[j]->pos;\n        dpx[j] = np[0]; dpy[j] = np[1]; dpz[j] = np[2];\n    }\n    return true;\n}\nvoid polycube_flattening_interface::save_polycube_para(const char* filename, TetStructure<double>* tet_mesh_)\n{\n    const std::vector<Tetrahedron<double>*> &tetras = tet_mesh_->tetras;\n    const std::vector<TetVertex<double>*> &tetra_vertices = tet_mesh_->tetra_vertices;\n    FILE* f_der = fopen(filename, \"w\");\n    fprintf(f_der, \"%d\\n\", tetras.size() * 12);\n    int nc = tetras.size();\n    for (size_t i = 0; i < nc; i++)\n    {\n        for (size_t j = 0; j < 4; j++)\n        {\n            CVec<double, 3> p = tetras[i]->vertex[j]->pos;\n            CVec<double, 3> q = p / cube_len;\n            for (size_t k = 0; k < 3; k++)\n            {\n                int tmp = (int)q[k];\n                if (abs(tmp - q[k]) < ROUNDING_TH)\n                    q[k] = (double)tmp;\n            }\n            fprintf(f_der, \"%.19f \", (q[0]));\n            fprintf(f_der, \"%.19f \", (q[1]));\n            fprintf(f_der, \"%.19f \", (q[2]));\n            fprintf(f_der, \"\\n\");\n        }\n    }\n    fclose(f_der);\n}\nbool polycube_flattening_interface::compute_eps(VolumeMesh* mesh_)\n{\n    Eigen::Matrix3d VS, A; Eigen::Vector3d a;\n    eps = 1e-3;\n    double min_det = 1e30; double avg_det = 0.0;\n    int d_count = 0.0;\n    Eigen::Matrix3d IS;\n    IS << 1.0, -0.57735026918962576450914878050196, -0.40824829046386301636621401245098,\n        0, 0, 1.2247448713915890490986420373529,\n        0, 1.1547005383792515290182975610039, -0.4082482904638630163662140124509;\n    for (OpenVolumeMesh::CellIter c_it = mesh_->cells_begin(); c_it != mesh_->cells_end(); ++c_it)\n    {\n        int c_id = c_it->idx(); OpenVolumeMesh::CellHandle ch = c_it.cur_handle();\n        OpenVolumeMesh::VertexHandle pvh(cell_vertex[c_id][0]);\n        OpenVolumeMesh::VertexHandle rvh(cell_vertex_vertex[c_id][0][0]);\n        OpenVolumeMesh::VertexHandle svh(cell_vertex_vertex[c_id][0][1]);\n        OpenVolumeMesh::VertexHandle tvh(cell_vertex_vertex[c_id][0][2]);\n        OpenVolumeMesh::Geometry::Vec3d p = mesh_->vertex(pvh);\n        OpenVolumeMesh::Geometry::Vec3d r = mesh_->vertex(rvh) - p;\n        OpenVolumeMesh::Geometry::Vec3d s = mesh_->vertex(svh) - p;\n        OpenVolumeMesh::Geometry::Vec3d t = mesh_->vertex(tvh) - p;\n        VS(0, 0) = r[0]; VS(1, 0) = r[1]; VS(2, 0) = r[2];\n        VS(0, 1) = s[0]; VS(1, 1) = s[1]; VS(2, 1) = s[2];\n        VS(0, 2) = t[0]; VS(1, 2) = t[1]; VS(2, 2) = t[2];\n        A = VS * S[c_id][0];\n        double det = A.determinant();\n        if (det < min_det) min_det = det;\n        avg_det += std::abs(det);\n        if (det < 0) ++d_count;\n    }\n    avg_det /= mesh_->n_cells();\n    double umbral = umbral_factor * avg_det;\n    double radicando = EpsilonEfectivo * (EpsilonEfectivo - min_det);\n    if (radicando <= 0.0)\n        min_det = 0.0;\n    else\n        min_det = std::sqrt(radicando);\n    eps = (min_det >= umbral) ? min_det : umbral;\n    eps = eps * eps;\n    printf(\"Flip Count : %d, %e\\n\", d_count, eps);\n    return (d_count == 0);\n}\n\nvoid polycube_flattening_interface::set_bd_face_chart_label(const std::vector<CVec<double, 3>> &bd_pts_data, const std::vector<unsigned> &bd_faces_data, const std::vector<int> &bd_chart_data, const std::vector<int> &bd_label_data)\n{\n    bd_pts = bd_pts_data;\n    bd_faces = bd_faces_data;\n    bd_chart = bd_chart_data;\n    bd_label = bd_label_data;\n}\nvoid polycube_flattening_interface::get_bd_face_chart_label(TetStructure<double> *tet_mesh_)\n{\n    if (!bd_pts.empty()) return;\n    assert(!polycube_edges.empty());\n    bd_pts.clear();\n    bd_faces.clear();\n    bd_chart.clear();\n    bd_label.clear();\n    bool cur_hex_flag = hex_meshing_flag;\n    set_hex_meshing_flag(false);\n    bool find_chart_flag = find_all_chart_value_equal_face_mine(tet_mesh_);\n    set_hex_meshing_flag(cur_hex_flag);\n    std::map<int, CVec<double, 3>> id2cornerpt;\n    for (int i = 0; i < tet_mesh_->tetra_vertices.size(); i++)\n    {\n        OpenVolumeMesh::Geometry::Vec3i& v_type = vertex_type[i];\n        if (v_type[0] >= 0 && v_type[1] >= 0 && v_type[2] >= 0)\n        {\n            CVec<double, 3> pt(chart_mean_value[v_type[0]], chart_mean_value[v_type[1]], chart_mean_value[v_type[2]]);\n            id2cornerpt[i] = pt;\n            dpx[i] = chart_mean_value[v_type[0]];\n            dpy[i] = chart_mean_value[v_type[1]];\n            dpz[i] = chart_mean_value[v_type[2]];\n        }\n    }\n    std::map<std::pair<int, int>, int> pq_edge2idx;\n    for (int i = 0; i < polycube_edges.size(); i++)\n    {\n        std::pair<int, int> point_pair1(polycube_edges[i][0], polycube_edges[i][1]);\n        std::pair<int, int> point_pair2(polycube_edges[i][1], polycube_edges[i][0]);\n        pq_edge2idx[point_pair1] = i;\n        pq_edge2idx[point_pair2] = i;\n    }\n    std::vector<std::vector<std::pair<int, int>>> edges_with_same_chart;\n    int max_chart_idx = 0;\n    for (size_t i = 0; i < polycube_edges.size(); i++)\n    {\n        if (max_chart_idx < polycube_edges[i][2])\n            max_chart_idx = polycube_edges[i][2];\n        if (max_chart_idx < polycube_edges[i][3])\n            max_chart_idx = polycube_edges[i][3];\n    }\n    edges_with_same_chart.resize(max_chart_idx + 1);\n    for (size_t i = 0; i < polycube_edges.size(); i++)\n    {\n        int chart_idx1 = polycube_edges[i][2];\n        int chart_idx2 = polycube_edges[i][3];\n        std::pair<int, int> point_pair(polycube_edges[i][0], polycube_edges[i][1]);\n        edges_with_same_chart[chart_idx1].push_back(point_pair);\n        edges_with_same_chart[chart_idx2].push_back(point_pair);\n    }\n    std::vector<std::vector<std::vector<int>>> chart2loops;\n    for (size_t i = 0; i < edges_with_same_chart.size(); i++)\n    {\n        std::vector<std::pair<int, int>> &one_chart = edges_with_same_chart[i];\n        std::list<std::pair<int, int>> one_chart_list(one_chart.begin(), one_chart.end());\n        std::vector<int> one_loop;\n        std::vector<std::vector<int>> onechart_loops;\n        int next_idx;\n        while (!one_chart_list.empty())\n        {\n            one_loop.clear();\n            one_loop.push_back(one_chart_list.front().first);\n            one_loop.push_back(one_chart_list.front().second);\n            one_chart_list.pop_front();\n            next_idx = -1;\n            int max_try_time = one_chart_list.size();\n            int try_time = 0;\n            while (!one_chart_list.empty() && try_time < max_try_time && next_idx != one_loop[0])\n            {\n                for (std::list<std::pair<int, int>>::iterator it = one_chart_list.begin(); it != one_chart_list.end(); ++it)\n                {\n                    if ((*it).first == one_loop.back())\n                    {\n                        next_idx = (*it).second;\n                        one_chart_list.erase(it);\n                        break;\n                    }\n                    if ((*it).second == one_loop.back())\n                    {\n                        next_idx = (*it).first;\n                        one_chart_list.erase(it);\n                        break;\n                    }\n                }\n                try_time++;\n                if (next_idx != one_loop.back() && next_idx != -1)\n                    one_loop.push_back(next_idx);\n            }\n            assert(one_loop[0] == one_loop.back());\n            if (one_loop[0] == one_loop.back())\n            {\n                onechart_loops.push_back(one_loop);\n            }\n        }\n        chart2loops.push_back(onechart_loops);\n    }\n    for (size_t i = 0; i < chart2loops.size(); i++)\n    {\n        std::vector<double> face_coord_x, face_coord_y, face_coord_z;\n        for (size_t k = 0; k < chart2loops[i].size(); k++)\n        {\n            chart2loops[i][k].erase(chart2loops[i][k].begin() + chart2loops[i][k].size() - 1);\n            int face_size = chart2loops[i][k].size();\n            for (size_t j = 0; j < face_size; j++)\n            {\n                auto it = id2cornerpt.find(chart2loops[i][k][j]);\n                assert(it != id2cornerpt.end());\n                face_coord_x.push_back(id2cornerpt[chart2loops[i][k][j]][0]);\n                face_coord_y.push_back(id2cornerpt[chart2loops[i][k][j]][1]);\n                face_coord_z.push_back(id2cornerpt[chart2loops[i][k][j]][2]);\n            }\n        }\n        std::vector<std::vector<int>> new_faces;\n        if (ig::SimpleTriangulation::sortface_area(face_coord_x, face_coord_y, face_coord_z, chart2loops[i]))\n        {\n            face_coord_x.clear();\n            face_coord_y.clear();\n            face_coord_z.clear();\n            for (size_t k = 0; k < chart2loops[i].size(); k++)\n            {\n                int face_size = chart2loops[i][k].size();\n                for (size_t j = 0; j < face_size; j++)\n                {\n                    face_coord_x.push_back(id2cornerpt[chart2loops[i][k][j]][0]);\n                    face_coord_y.push_back(id2cornerpt[chart2loops[i][k][j]][1]);\n                    face_coord_z.push_back(id2cornerpt[chart2loops[i][k][j]][2]);\n                }\n            }\n        }\n        bool triangulation_success = ig::SimpleTriangulation::triangulation(face_coord_x, face_coord_y, face_coord_z, chart2loops[i], new_faces);\n        for (size_t j = 0; j < new_faces.size(); j++)\n        {\n            for (size_t k = 0; k < 3; k++)\n            {\n                bd_faces.push_back(new_faces[j][k]);\n            }\n            bd_chart.push_back(i);\n            bd_label.push_back(polycube_chart_label[i]);\n        }\n    }\n    std::map<int, int> ido2n;\n    int count = 0;\n    for (auto p : id2cornerpt)\n    {\n        bd_pts.push_back(p.second);\n        ido2n[p.first] = count++;\n    }\n    for (size_t i = 0; i < bd_faces.size(); i++)\n    {\n        bd_faces[i] = ido2n[bd_faces[i]];\n    }\n}\nvoid polycube_flattening_interface::load_deformation_result(const std::vector<double> &coord_ori, TetStructure<double> *tet_mesh_)\n{\n    int nv = tet_mesh_->tetra_vertices.size();\n    dpx_ori.resize(nv);\n    dpy_ori.resize(nv);\n    dpz_ori.resize(nv);\n    for (size_t i = 0; i < nv; i++)\n    {\n        dpx_ori[i] = coord_ori[3 * i];\n        dpy_ori[i] = coord_ori[3 * i + 1];\n        dpz_ori[i] = coord_ori[3 * i + 2];\n    }\n    prepare_for_deformation(tet_mesh_, dpx_ori, dpy_ori, dpz_ori);\n    printf(\"Loading deformation result.............\\n\");\n    build_AABB_Tree();\n#if 1\n    for (int i = 0; i < deformation_v_id.size(); ++i)\n    {\n        deformation_new_p[i][0] = dpx[deformation_v_id[i]];\n        deformation_new_p[i][1] = dpy[deformation_v_id[i]];\n        deformation_new_p[i][2] = dpz[deformation_v_id[i]];\n    }\n#endif\n    compute_distortion(tet_mesh_);\n}\nvoid polycube_flattening_interface::set_equal_faces(const std::vector<std::vector<std::vector<int>>> &faces_array, const std::vector<int>& common_verts_idx, const std::vector<int>& cut_types_array, int n_vert, const std::vector<std::pair<int, int>> &chart_pair, const std::vector<std::pair<int, int>> &chart_pair_neighbor, const std::vector<int> &three_cut_common_vert_array, const std::vector<std::vector<std::array<unsigned int, 3>>> &three_cut_vert_array, const std::vector<std::array<int, 3>> &three_cut_adjacent_one_cut_index_array)\n{\n    assert(faces_array.size() == (common_verts_idx.size() >> 1) && faces_array.size() == cut_types_array.size());\n    if (faces_array.size() == 0)\n        return;\n    vert_update_type.clear();\n    vert_belong_cut_array.clear();\n    cut_types.clear();\n    cut_common_verts_idx.clear();\n    cut_to_chart_pair.clear();\n    vert_pairs_map.clear();\n    equal_triangles.clear();\n    vert_update_type.resize(n_vert, 0);\n    vert_belong_cut_array.resize(n_vert, -1);\n    cut_types = cut_types_array;\n    for (size_t i = 0; i < common_verts_idx.size() / 2; i++)\n    {\n        cut_common_verts_idx.push_back(common_verts_idx[2 * i]);\n    }\n    for (size_t i = 0; i < faces_array.size(); i++)\n    {\n        equal_triangles.insert(equal_triangles.end(), faces_array[i].begin(), faces_array[i].end());\n    }\n    for (size_t i = 0; i < faces_array.size(); i++)\n    {\n        for (size_t j = 0; j < faces_array[i].size(); j++)\n        {\n            int id1, id2, id3, id4, id5, id0;\n            id0 = faces_array[i][j][0];\n            id1 = faces_array[i][j][1];\n            id2 = faces_array[i][j][2];\n            id3 = faces_array[i][j][3];\n            id4 = faces_array[i][j][4];\n            id5 = faces_array[i][j][5];\n            vert_update_type[id0] = 1;\n            vert_update_type[id1] = 1;\n            vert_update_type[id2] = 1;\n            vert_update_type[id3] = 2;\n            vert_update_type[id4] = 2;\n            vert_update_type[id5] = 2;\n            vert_belong_cut_array[id0] = i;\n            vert_belong_cut_array[id1] = i;\n            vert_belong_cut_array[id2] = i;\n            vert_belong_cut_array[id3] = i;\n            vert_belong_cut_array[id4] = i;\n            vert_belong_cut_array[id5] = i;\n            vert_pairs_map[id0] = id3;\n            vert_pairs_map[id1] = id4;\n            vert_pairs_map[id2] = id5;\n            vert_pairs_map[id3] = id0;\n            vert_pairs_map[id4] = id1;\n            vert_pairs_map[id5] = id2;\n        }\n    }\n    cut_to_chart_pair = chart_pair;\n    cut_to_chart_pair_neighbor = chart_pair_neighbor;\n    three_cut_common_vert = three_cut_common_vert_array;\n    three_cut_vert = three_cut_vert_array;\n    three_cut_adjacent_one_cut_index = three_cut_adjacent_one_cut_index_array;\n    three_cut_vert_flag.clear();\n    three_cut_vert_flag.resize(n_vert, -1);\n    assert(three_cut_common_vert.size() == three_cut_vert.size());\n    for (size_t i = 0; i < three_cut_common_vert.size(); i++)\n    {\n        three_cut_vert_flag[three_cut_common_vert[i]] = 1;\n        for (size_t j = 0; j < three_cut_vert[i].size(); j++)\n        {\n            for (size_t k = 0; k < 3; k++)\n            {\n                three_cut_vert_flag[three_cut_vert[i][j][k]] = 1;\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "5fbae96afdf46fb9b98438264cd190c90306220a", "size": 179248, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ScissorPoly/Polycube_Flattening.cpp", "max_stars_repo_name": "msraig/CE-PolyCube", "max_stars_repo_head_hexsha": "e46aff6e0594b711735118bfa902a91bc3d392ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2020-08-13T05:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:51:29.000Z", "max_issues_repo_path": "ScissorPoly/Polycube_Flattening.cpp", "max_issues_repo_name": "xh-liu-tech/CE-PolyCube", "max_issues_repo_head_hexsha": "86d4ed0023215307116b6b3245e2dbd82907cbb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-09-08T07:03:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T05:43:27.000Z", "max_forks_repo_path": "ScissorPoly/Polycube_Flattening.cpp", "max_forks_repo_name": "xh-liu-tech/CE-PolyCube", "max_forks_repo_head_hexsha": "86d4ed0023215307116b6b3245e2dbd82907cbb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2020-08-06T02:37:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-01T09:12:06.000Z", "avg_line_length": 41.0272373541, "max_line_length": 537, "alphanum_fraction": 0.5175008926, "num_tokens": 50128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.25120395387135785}}
{"text": "#include <iostream>\n#include <NTL/ZZ.h>\n#include <memory>\n\n#include <boost/program_options.hpp>\n\n#include \"Lenstra.h\"\n#include \"Options.h\"\n#include \"EdwardsModel.h\"\n#include \"WeierstrassModel.h\"\n\nnamespace po = boost::program_options;\n\nint main(int argc, char **argv) {\n    std::shared_ptr<Options> options = std::make_shared<Options>();\n\n    po::options_description desc(\"OPTIONS\");\n    po::variables_map vm;\n    desc.add_options()\n            (\"help,h\", \"produce help message\")\n            (\"weierstrass_model,w\", po::bool_switch(&options->weierstrass), \"set Weierstrass model\")\n            (\"edwards_model,e\", po::bool_switch(&options->edwards), \"set Edwards model\")\n            (\"timer,t\", po::bool_switch(&options->timer), \"time measurement\")\n            (\"parallel,p\", po::bool_switch(&options->parallel), \"start parallel\")\n            (\"bound,b\", po::value<NTL::ZZ>(options->bound.get()), \"Maximal bound for iterations (Default square root of composite number)\")\n            (\"composite-number,n\", po::value<NTL::ZZ>(options->composite_number.get())->required(), \"Positive integer bigger than 1 to factorize\");\n    try {\n        po::store(po::parse_command_line(argc, argv, desc), vm);\n        if (vm.count(\"help\")) {\n            std::cout << argv[0] << \" [OPTIONS] --composite-number/-n COMPOSITE NUMBER\\n\";\n            std::cout << desc << \"\\n\";\n            return 1;\n        }\n        po::notify(vm);\n    } catch (std::exception &exception) {\n        std::cout << exception.what() << \"\\n\";\n        return 1;\n    }\n\n    if (options->weierstrass && options->edwards) {\n        std::cerr << \"Only one model can be specified!\\n\";\n        return 2;\n    }\n\n    options->weierstrass = !options->edwards;\n\n    if (*options->composite_number < 2) {\n        std::cerr << \"Composite number must be positive integer bigger than 1!\\n\";\n        return 3;\n    }\n\n    std::cout << \"Factorizing number: \" << *options->composite_number << '\\n';\n    std::cout << \"Using model: \" << (options->edwards ? \"Edwards\" : \"Weierstrass\") << '\\n';\n    std::cout << \"Using timer: \" << (options->timer ? \"yes\" : \"no\") << '\\n';\n    double start_time = 0.0, end_time;\n    std::shared_ptr<AbstractModel> model;\n    if (options->weierstrass) {\n        model = std::make_shared<WeierstrassModel>(options);\n    } else {\n        model = std::make_shared<EdwardsModel>(options);\n    }\n    Lenstra ecm(options, model);\n    if (options->timer) {\n        start_time = NTL::GetTime();\n    }\n    NTL::ZZ factor;\n    if (!options->parallel) {\n        factor = ecm.factorize();\n    } else {\n        factor = ecm.factorize_parallel(argc, argv);\n    }\n\n    end_time = NTL::GetTime();\n    if (options->timer && !options->parallel) {\n        std::cout << \"time = \" << end_time - start_time << \" s\\n\";\n    }\n\n    if (factor != 0)\n        std::cout << \"Factor = \" << factor << \"\\n\";\n\n    return 0;\n}\n", "meta": {"hexsha": "e41b1904f156fffdffcc49c2f398c67e86e42e33", "size": 2858, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "implementation/src/main.cpp", "max_stars_repo_name": "dvorakj31/diploma-thesis", "max_stars_repo_head_hexsha": "f2c0b250491d9ce9f2534c3c1656682757053ed7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "implementation/src/main.cpp", "max_issues_repo_name": "dvorakj31/diploma-thesis", "max_issues_repo_head_hexsha": "f2c0b250491d9ce9f2534c3c1656682757053ed7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "implementation/src/main.cpp", "max_forks_repo_name": "dvorakj31/diploma-thesis", "max_forks_repo_head_hexsha": "f2c0b250491d9ce9f2534c3c1656682757053ed7", "max_forks_repo_licenses": ["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.4337349398, "max_line_length": 147, "alphanum_fraction": 0.5874737579, "num_tokens": 762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2511698877171207}}
{"text": "// Copyright 2014 BVLC and contributors.\n\n#include <algorithm>\n#include <vector>\n#include <cmath>\n#include <stdio.h>\n\n#include \"google/protobuf/descriptor.h\"\n#include \"google/protobuf/descriptor.h\"\n#include \"caffe/layer.hpp\"\n#include \"caffe/layers/flow_warp_layer.hpp\"\n#include \"caffe/util/rng.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/highgui/highgui.hpp>\n\n#include <boost/random.hpp>\n#include <boost/random/normal_distribution.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <omp.h>\n\nusing std::max;\n\nnamespace caffe {\n\ntemplate <typename Dtype>\nvoid FlowWarpLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top) {\n}\n\ntemplate <typename Dtype>\nvoid FlowWarpLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top) {\n  CHECK_EQ(bottom.size(), 2) << \"FlowWarpLayer takes two input blobs: image and flow.\";\n  CHECK_EQ(top.size(), 1) << \"FlowWarpLayer outputs one blob.\";\n  \n  const int num = bottom[0]->num();\n  const int channels = bottom[0]->channels();\n  const int height = bottom[0]->height();\n  const int width = bottom[0]->width();\n  \n  CHECK_EQ(num, bottom[1]->num()) << \"Num of the inputs should be the same\";\n  CHECK_EQ(2, bottom[1]->channels()) << \"Flow should have 2 channels: x-flow and y-flow\";\n  CHECK_EQ(width, bottom[1]->width()) << \"Width of the inputs should be the same\";\n  CHECK_EQ(height, bottom[1]->height()) << \"Height of the inputs should be the same\";  \n  \n  top[0]->Reshape(num, channels, height, width);  \n  transposed_image_.Reshape(num, height, width, channels);\n}\n\n#define min(a,b) ((a<b)?(a):(b))\n#define max(a,b) ((a>b)?(a):(b))\n\ntemplate <typename Dtype>\nvoid FlowWarpLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,\n    const vector<Blob<Dtype>*>& top)\n{\n    int width = top[0]->width();\n    int height = top[0]->height();\n    int channels = top[0]->channels();\n    int num = top[0]->num();\n    const int wh_size = width * height;\n    const int whc_size = width * height * channels;\n\n    Dtype* warped_data = top[0]->mutable_cpu_data(); // dest\n    const Dtype* image_data = bottom[0]->cpu_data(); // source image\n    const Dtype* flow_data = bottom[1]->cpu_data(); // source flow\n\n    Dtype fillValue = this->layer_param().flow_warp_param().fill_value() == FlowWarpParameter_FillParameter_ZERO ? 0 : NAN;\n\n    for(int n=0; n<num; n++)\n    {\n        int off = whc_size * n;\n        for(int x=0; x<width; x++)\n            for(int y=0; y<height; y++)\n            {\n                float fx = flow_data[2*wh_size*n + y*width + x];\n                float fy = flow_data[2*wh_size*n + wh_size + y*width + x];\n\n                float x2 = float(x) + fx;\n                float y2 = float(y) + fy;\n\n                if(x2>=0 && y2>=0 && x2<width && y2<height)\n                {\n                    int ix2_L = int(x2);\n                    int iy2_T = int(y2);\n                    int ix2_R = min(ix2_L+1, width-1);\n                    int iy2_B = min(iy2_T+1, height-1);\n\n                    float alpha=x2-ix2_L;\n                    float beta=y2-iy2_T;\n\n                    for(int c=0; c<channels; c++)\n                    {\n                        float TL = image_data[off + c*wh_size + iy2_T*width + ix2_L];\n                        float TR = image_data[off + c*wh_size + iy2_T*width + ix2_R];\n                        float BL = image_data[off + c*wh_size + iy2_B*width + ix2_L];\n                        float BR = image_data[off + c*wh_size + iy2_B*width + ix2_R];\n\n                        warped_data[off + c*wh_size + y*width + x] =\n                            (1-alpha)*(1-beta)*TL +\n                            alpha*(1-beta)*TR +\n                            (1-alpha)*beta*BL +\n                            alpha*beta*BR;\n                    }\n                }\n                else\n                {\n                    for(int c=0; c<channels; c++)\n                        warped_data[off + c*wh_size + y*width + x] = fillValue;\n                }\n            }\n    }\n}\n\ntemplate <typename Dtype>\nvoid FlowWarpLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,\n      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom)\n{\n    int width = top[0]->width();\n    int height = top[0]->height();\n    int channels = top[0]->channels();\n    int num = top[0]->num();\n    const int wh_size = width * height;\n    const int whc_size = width * height * channels;\n\n    const Dtype* warped_data = top[0]->cpu_data(); // dest\n    const Dtype* warped_diff = top[0]->cpu_diff(); // dest\n    const Dtype* image_data = bottom[0]->cpu_data(); // source image\n    Dtype* image_diff = bottom[0]->mutable_cpu_diff(); // source image\n    const Dtype* flow_data = bottom[1]->cpu_data(); // source flow\n    Dtype* flow_diff = bottom[1]->mutable_cpu_diff(); // source flow\n\n    for(int i=0; i<num*whc_size; i++)\n        image_diff[i] = 0 ;\n\n    for(int n=0; n<num; n++)\n    {\n        int off = whc_size * n;\n        for(int x=0; x<width; x++)\n            for(int y=0; y<height; y++)\n            {\n                float fx = flow_data[2*wh_size*n + y*width + x];\n                float fy = flow_data[2*wh_size*n + wh_size + y*width + x];\n\n                float x2 = float(x) + fx;\n                float y2 = float(y) + fy;\n\n                if(x2>=0 && y2>=0 && x2<width && y2<height)\n                {\n                    int ix2_L = int(x2);\n                    int iy2_T = int(y2);\n                    int ix2_R = min(ix2_L+1, width-1);\n                    int iy2_B = min(iy2_T+1, height-1);\n\n                    float alpha=x2-ix2_L;\n                    float beta=y2-iy2_T;\n                    for(int c=0; c<channels; c++)\n                    {\n                        float warped_diff_value = warped_diff[off + c*wh_size + y*width + x];\n                        image_diff[off + c*wh_size + iy2_T*width + ix2_L] += warped_diff_value * (1-alpha)*(1-beta);\n                        image_diff[off + c*wh_size + iy2_T*width + ix2_R] += warped_diff_value * alpha*(1-beta);\n                        image_diff[off + c*wh_size + iy2_B*width + ix2_L] += warped_diff_value * (1-alpha)*beta;\n                        image_diff[off + c*wh_size + iy2_B*width + ix2_R] += warped_diff_value * alpha*beta;\n                    }\n\n                    float gamma = iy2_B - y2;\n                    float bot_diff = 0;\n                    for(int c=0; c<channels; c++)\n                    {\n                        float temp = 0;\n                        temp += gamma *     (image_data[off + c*wh_size + iy2_T*width + ix2_R] - image_data[off + c*wh_size + iy2_T*width + ix2_L]);\n                        temp += (1-gamma) * (image_data[off + c*wh_size + iy2_B*width + ix2_R] - image_data[off + c*wh_size + iy2_B*width + ix2_L]);\n\n                        bot_diff += warped_diff[off + c*wh_size + y*width + x] * temp;\n                    }\n                    flow_diff[2*wh_size*n + y*width + x] = bot_diff;\n\n                    gamma = ix2_R - x2;\n                    bot_diff = 0;\n                    for(int c=0; c<channels; c++)\n                    {\n                        float temp = 0;\n                        temp += gamma *     (image_data[off + c*wh_size + iy2_B*width + ix2_L] - image_data[off + c*wh_size + iy2_T*width + ix2_L]);\n                        temp += (1-gamma) * (image_data[off + c*wh_size + iy2_B*width + ix2_R] - image_data[off + c*wh_size + iy2_T*width + ix2_R]);\n\n                        bot_diff += warped_diff[off + c*wh_size + y*width + x] * temp;\n                    }\n                    flow_diff[2*wh_size*n + wh_size + y*width + x] = bot_diff;\n                }\n            }\n    }\n\n    if(!propagate_down[0]) caffe_memset(bottom[0]->count()*sizeof(Dtype), 0, image_diff);\n    if(!propagate_down[1]) caffe_memset(bottom[1]->count()*sizeof(Dtype), 0, flow_diff);\n\n\n//    {\n//        printf(\"cpu flow u:\\n\");\n//        for(int y=0; y<height; y++)\n//        {\n//            for(int x=0; x<width; x++)\n//            {\n//                printf(\"%f \", bottom[1]->data_at(0, 0, y, x));\n//            }\n//            printf(\"\\n\");\n//        }\n//        printf(\"cpu flow v:\\n\");\n//        for(int y=0; y<height; y++)\n//        {\n//            for(int x=0; x<width; x++)\n//            {\n//                printf(\"%f \", bottom[1]->data_at(0, 1, y, x));\n//            }\n//            printf(\"\\n\");\n//        }\n//        printf(\"cpu image:\\n\");\n//        for(int y=0; y<height; y++)\n//        {\n//            for(int x=0; x<width; x++)\n//            {\n//                printf(\"%f \", bottom[0]->data_at(0, 0, y, x));\n//            }\n//            printf(\"\\n\");\n//        }\n//        printf(\"cpu flow diff u:\\n\");\n//        for(int y=0; y<height; y++)\n//        {\n//            for(int x=0; x<width; x++)\n//            {\n//                printf(\"%f \", bottom[1]->diff_at(0, 0, y, x));\n//            }\n//            printf(\"\\n\");\n//        }\n//        printf(\"cpu flow diff v:\\n\");\n//        for(int y=0; y<height; y++)\n//        {\n//            for(int x=0; x<width; x++)\n//            {\n//                printf(\"%f \", bottom[1]->diff_at(0, 1, y, x));\n//            }\n//            printf(\"\\n\");\n//        }\n//        printf(\"cpu image diff:\\n\");\n//        for(int y=0; y<height; y++)\n//        {\n//            for(int x=0; x<width; x++)\n//            {\n//                printf(\"%f \", bottom[0]->diff_at(0, 0, y, x));\n//            }\n//            printf(\"\\n\");\n//        }\n//    }\n}\n\nINSTANTIATE_CLASS(FlowWarpLayer);\nREGISTER_LAYER_CLASS(FlowWarp);\n\n\n}  // namespace caffe\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//        for(int x=0; x<width; x++)\n//            for(int y=0; y<height; y++)\n//            {\n//                float fx = flow_data[off + y*width + x];\n//                float fy = flow_data[off + wh_size + y*width + x];\n\n//                float x2 = float(x) + fx;\n//                float y2 = float(y) + fy;\n\n//                if(x2>=0 && y2>=0 && x2<width && y2<height)\n//                {\n//                    int ix2_L = int(x2);\n//                    int iy2_T = int(y2);\n//                    int ix2_R = min(ix2_L+1, width-1);\n//                    int iy2_B = min(iy2_T+1, height-1);\n", "meta": {"hexsha": "093eef796a9579d3466000177c4cc1f5ff353453", "size": 10272, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/layers/flow_warp_layer.cpp", "max_stars_repo_name": "AyaLotfy/flownet2", "max_stars_repo_head_hexsha": "e3e3dd043d9a65bc8727429938a0d88539f906fd", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": 1081.0, "max_stars_repo_stars_event_min_datetime": "2017-04-25T11:46:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T03:24:45.000Z", "max_issues_repo_path": "src/caffe/layers/flow_warp_layer.cpp", "max_issues_repo_name": "AyaLotfy/flownet2", "max_issues_repo_head_hexsha": "e3e3dd043d9a65bc8727429938a0d88539f906fd", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": 220.0, "max_issues_repo_issues_event_min_datetime": "2017-04-28T04:47:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-27T09:49:43.000Z", "max_forks_repo_path": "src/caffe/layers/flow_warp_layer.cpp", "max_forks_repo_name": "AyaLotfy/flownet2", "max_forks_repo_head_hexsha": "e3e3dd043d9a65bc8727429938a0d88539f906fd", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": 361.0, "max_forks_repo_forks_event_min_datetime": "2017-04-26T02:16:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T04:21:09.000Z", "avg_line_length": 33.2427184466, "max_line_length": 148, "alphanum_fraction": 0.4789719626, "num_tokens": 2776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2511698877171206}}
{"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::Vector3 g = this->getWorldGravity();\n\t\t\t\n\t\t\t::rl::math::Vector tmp = ::rl::math::Vector::Zero(this->getDof());\n\t\t\t\n\t\t\tthis->setAcceleration(tmp);\n\t\t\tthis->setWorldGravity(::rl::math::Vector3::Zero());\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 = ::rl::math::Vector::Zero(this->getDof());\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::Vector3 g = this->getWorldGravity();\n\t\t\t\n\t\t\t::rl::math::Vector tmp = ::rl::math::Vector::Zero(this->getDof());\n\t\t\t\n\t\t\tthis->setVelocity(tmp);\n\t\t\tthis->setWorldGravity(::rl::math::Vector3::Zero());\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::Vector3 g = this->getWorldGravity();\n\t\t\t\n\t\t\t::rl::math::Vector tmp = ::rl::math::Vector::Zero(this->getDof());\n\t\t\t\n\t\t\tthis->setVelocity(tmp);\n\t\t\tthis->setWorldGravity(::rl::math::Vector3::Zero());\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();\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::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::update()\n\t\t{\n\t\t\tKinematic::update();\n\t\t\t\n\t\t\tthis->M = ::rl::math::Matrix::Identity(this->getDof(), this->getDof());\n\t\t\tthis->V = ::rl::math::Vector::Zero(this->getDof());\n\t\t\tthis->G = ::rl::math::Vector::Zero(this->getDof());\n\t\t\tthis->invM = ::rl::math::Matrix::Identity(this->getDof(), this->getDof());\n\t\t\tthis->invMx = ::rl::math::Matrix::Identity(6 * this->getOperationalDof(), 6 * this->getOperationalDof());\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "3bdaee78870c0867d6258081f66ae6a003f50ce3", "size": 6365, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rl/mdl/Dynamic.cpp", "max_stars_repo_name": "omerulutas/rl", "max_stars_repo_head_hexsha": "b65fef1716b1b4eb3e0ad0314e0a93963d98c7fc", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-30T22:17:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-30T22:17:44.000Z", "max_issues_repo_path": "src/rl/mdl/Dynamic.cpp", "max_issues_repo_name": "jencureboy/rl", "max_issues_repo_head_hexsha": "658cdd8387397261ebf0f52d3bde74aae0379e24", "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": "jencureboy/rl", "max_forks_repo_head_hexsha": "658cdd8387397261ebf0f52d3bde74aae0379e24", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4807692308, "max_line_length": 142, "alphanum_fraction": 0.6296936371, "num_tokens": 1893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.25105614591093994}}
{"text": "// Copyright (c) 2016, Monea Research Labs\n//\n// Author: Shen Noether <shen.noether@gmx.com>\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/lexical_cast.hpp>\n#include \"misc_log_ex.h\"\n#include \"rctOps.h\"\nusing namespace crypto;\nusing namespace std;\n\n#undef MONEA_DEFAULT_LOG_CATEGORY\n#define MONEA_DEFAULT_LOG_CATEGORY \"ringct\"\n\n#define CHECK_AND_ASSERT_THROW_MES_L1(expr, message) {if(!(expr)) {MWARNING(message); throw std::runtime_error(message);}}\n\nnamespace rct {\n\n    //Various key initialization functions\n\n    //initializes a key matrix;\n    //first parameter is rows,\n    //second is columns\n    keyM keyMInit(size_t rows, size_t cols) {\n        keyM rv(cols);\n        size_t i = 0;\n        for (i = 0 ; i < cols ; i++) {\n            rv[i] = keyV(rows);\n        }\n        return rv;\n    }\n\n\n\n\n    //Various key generation functions\n\n    //generates a random scalar which can be used as a secret key or mask\n    void skGen(key &sk) {\n        sk = crypto::rand<key>();\n        sc_reduce32(sk.bytes);\n    }\n\n    //generates a random scalar which can be used as a secret key or mask\n    key skGen() {\n        key sk = crypto::rand<key>();\n        sc_reduce32(sk.bytes);\n        return sk;\n    }\n\n    //Generates a vector of secret key\n    //Mainly used in testing\n    keyV skvGen(size_t rows ) {\n        CHECK_AND_ASSERT_THROW_MES(rows > 0, \"0 keys requested\");\n        keyV rv(rows);\n        size_t i = 0;\n        crypto::rand(rows * sizeof(key), (uint8_t*)&rv[0]);\n        for (i = 0 ; i < rows ; i++) {\n            sc_reduce32(rv[i].bytes);\n        }\n        return rv;\n    }\n\n    //generates a random curve point (for testing)\n    key  pkGen() {\n        key sk = skGen();\n        key pk = scalarmultBase(sk);\n        return pk;\n    }\n\n    //generates a random secret and corresponding public key\n    void skpkGen(key &sk, key &pk) {\n        skGen(sk);\n        scalarmultBase(pk, sk);\n    }\n\n    //generates a random secret and corresponding public key\n    tuple<key, key>  skpkGen() {\n        key sk = skGen();\n        key pk = scalarmultBase(sk);\n        return make_tuple(sk, pk);\n    }\n\n    //generates C =aG + bH from b, a is given..\n    void genC(key & C, const key & a, xmr_amount amount) {\n        key bH = scalarmultH(d2h(amount));\n        addKeys1(C, a, bH);\n    }\n\n    //generates a <secret , public> / Pedersen commitment to the amount\n    tuple<ctkey, ctkey> ctskpkGen(xmr_amount amount) {\n        ctkey sk, pk;\n        skpkGen(sk.dest, pk.dest);\n        skpkGen(sk.mask, pk.mask);\n        key am = d2h(amount);\n        key bH = scalarmultH(am);\n        addKeys(pk.mask, pk.mask, bH);\n        return make_tuple(sk, pk);\n    }\n    \n    \n    //generates a <secret , public> / Pedersen commitment but takes bH as input \n    tuple<ctkey, ctkey> ctskpkGen(const key &bH) {\n        ctkey sk, pk;\n        skpkGen(sk.dest, pk.dest);\n        skpkGen(sk.mask, pk.mask);\n        addKeys(pk.mask, pk.mask, bH);\n        return make_tuple(sk, pk);\n    }\n    \n    key zeroCommit(xmr_amount amount) {\n        key mask = identity();\n        mask = scalarmultBase(mask);\n        key am = d2h(amount);\n        key bH = scalarmultH(am);\n        addKeys(mask, mask, bH);\n        return mask;\n    }\n\n    key commit(xmr_amount amount, const key &mask) {\n        key c = scalarmultBase(mask);\n        key am = d2h(amount);\n        key bH = scalarmultH(am);\n        addKeys(c, c, bH);\n        return c;\n    }\n\n    //generates a random uint long long (for testing)\n    xmr_amount randXmrAmount(xmr_amount upperlimit) {\n        return h2d(skGen()) % (upperlimit);\n    }\n\n    //Scalar multiplications of curve points\n\n    //does a * G where a is a scalar and G is the curve basepoint\n    void scalarmultBase(key &aG,const key &a) {\n        ge_p3 point;\n        sc_reduce32copy(aG.bytes, a.bytes); //do this beforehand!\n        ge_scalarmult_base(&point, aG.bytes);\n        ge_p3_tobytes(aG.bytes, &point);\n    }\n\n    //does a * G where a is a scalar and G is the curve basepoint\n    key scalarmultBase(const key & a) {\n        ge_p3 point;\n        key aG;\n        sc_reduce32copy(aG.bytes, a.bytes); //do this beforehand\n        ge_scalarmult_base(&point, aG.bytes);\n        ge_p3_tobytes(aG.bytes, &point);\n        return aG;\n    }\n\n    //does a * P where a is a scalar and P is an arbitrary point\n    void scalarmultKey(key & aP, const key &P, const key &a) {\n        ge_p3 A;\n        ge_p2 R;\n        CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&A, P.bytes) == 0, \"ge_frombytes_vartime failed at \"+boost::lexical_cast<std::string>(__LINE__));\n        ge_scalarmult(&R, a.bytes, &A);\n        ge_tobytes(aP.bytes, &R);\n    }\n\n    //does a * P where a is a scalar and P is an arbitrary point\n    key scalarmultKey(const key & P, const key & a) {\n        ge_p3 A;\n        ge_p2 R;\n        CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&A, P.bytes) == 0, \"ge_frombytes_vartime failed at \"+boost::lexical_cast<std::string>(__LINE__));\n        ge_scalarmult(&R, a.bytes, &A);\n        key aP;\n        ge_tobytes(aP.bytes, &R);\n        return aP;\n    }\n\n\n    //Computes aH where H= toPoint(cn_fast_hash(G)), G the basepoint\n    key scalarmultH(const key & a) {\n        ge_p3 A;\n        ge_p2 R;\n        CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&A, H.bytes) == 0, \"ge_frombytes_vartime failed at \"+boost::lexical_cast<std::string>(__LINE__));\n        ge_scalarmult(&R, a.bytes, &A);\n        key aP;\n        ge_tobytes(aP.bytes, &R);\n        return aP;\n    }\n\n    //Curve addition / subtractions\n\n    //for curve points: AB = A + B\n    void addKeys(key &AB, const key &A, const key &B) {\n        ge_p3 B2, A2;\n        CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&B2, B.bytes) == 0, \"ge_frombytes_vartime failed at \"+boost::lexical_cast<std::string>(__LINE__));\n        CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&A2, A.bytes) == 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.bytes, &A2);\n    }\n\n    rct::key addKeys(const key &A, const key &B) {\n      key k;\n      addKeys(k, A, B);\n      return k;\n    }\n\n    //addKeys1\n    //aGB = aG + B where a is a scalar, G is the basepoint, and B is a point\n    void addKeys1(key &aGB, const key &a, const key & B) {\n        key aG = scalarmultBase(a);\n        addKeys(aGB, aG, B);\n    }\n\n    //addKeys2\n    //aGbB = aG + bB where a, b are scalars, G is the basepoint and B is a point\n    void addKeys2(key &aGbB, const key &a, const key &b, const key & B) {\n        ge_p2 rv;\n        ge_p3 B2;\n        CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&B2, B.bytes) == 0, \"ge_frombytes_vartime failed at \"+boost::lexical_cast<std::string>(__LINE__));\n        ge_double_scalarmult_base_vartime(&rv, b.bytes, &B2, a.bytes);\n        ge_tobytes(aGbB.bytes, &rv);\n    }\n\n    //Does some precomputation to make addKeys3 more efficient\n    // input B a curve point and output a ge_dsmp which has precomputation applied\n    void precomp(ge_dsmp rv, const key & B) {\n        ge_p3 B2;\n        CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&B2, B.bytes) == 0, \"ge_frombytes_vartime failed at \"+boost::lexical_cast<std::string>(__LINE__));\n        ge_dsm_precomp(rv, &B2);\n    }\n\n    //addKeys3\n    //aAbB = a*A + b*B where a, b are scalars, A, B are curve points\n    //B must be input after applying \"precomp\"\n    void addKeys3(key &aAbB, const key &a, const key &A, const key &b, const ge_dsmp B) {\n        ge_p2 rv;\n        ge_p3 A2;\n        CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&A2, A.bytes) == 0, \"ge_frombytes_vartime failed at \"+boost::lexical_cast<std::string>(__LINE__));\n        ge_double_scalarmult_precomp_vartime(&rv, a.bytes, &A2, b.bytes, B);\n        ge_tobytes(aAbB.bytes, &rv);\n    }\n\n    //addKeys3\n    //aAbB = a*A + b*B where a, b are scalars, A, B are curve points\n    //A and B must be input after applying \"precomp\"\n    void addKeys3(key &aAbB, const key &a, const ge_dsmp A, const key &b, const ge_dsmp B) {\n        ge_p2 rv;\n        ge_double_scalarmult_precomp_vartime2(&rv, a.bytes, A, b.bytes, B);\n        ge_tobytes(aAbB.bytes, &rv);\n    }\n\n\n    //subtract Keys (subtracts curve points)\n    //AB = A - B where A, B are curve points\n    void subKeys(key & AB, const key &A, const key &B) {\n        ge_p3 B2, A2;\n        CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&B2, B.bytes) == 0, \"ge_frombytes_vartime failed at \"+boost::lexical_cast<std::string>(__LINE__));\n        CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&A2, A.bytes) == 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_sub(&tmp3, &A2, &tmp2);\n        ge_p1p1_to_p3(&A2, &tmp3);\n        ge_p3_tobytes(AB.bytes, &A2);\n    }\n\n    //checks if A, B are equal in terms of bytes (may say no if one is a non-reduced scalar)\n    //without doing curve operations\n    bool equalKeys(const key & a, const key & b) {\n        bool rv = true;\n        for (int i = 0; i < 32; ++i) {\n          if (a.bytes[i] != b.bytes[i]) {\n            rv = false;\n          }\n        }\n        return rv;\n    }\n\n    //Hashing - cn_fast_hash\n    //be careful these are also in crypto namespace\n    //cn_fast_hash for arbitrary multiples of 32 bytes\n    void cn_fast_hash(key &hash, const void * data, const std::size_t l) {\n        keccak((const uint8_t *)data, l, hash.bytes, 32);\n    }\n    \n    void hash_to_scalar(key &hash, const void * data, const std::size_t l) {\n        cn_fast_hash(hash, data, l);\n        sc_reduce32(hash.bytes);\n    }\n\n    //cn_fast_hash for a 32 byte key\n    void cn_fast_hash(key & hash, const key & in) {\n        keccak((const uint8_t *)in.bytes, 32, hash.bytes, 32);\n    }\n    \n    void hash_to_scalar(key & hash, const key & in) {\n        cn_fast_hash(hash, in);\n        sc_reduce32(hash.bytes);\n    }\n\n    //cn_fast_hash for a 32 byte key\n    key cn_fast_hash(const key & in) {\n        key hash;\n        keccak((const uint8_t *)in.bytes, 32, hash.bytes, 32);\n        return hash;\n    }\n    \n     key hash_to_scalar(const key & in) {\n        key hash = cn_fast_hash(in);\n        sc_reduce32(hash.bytes);\n        return hash;\n     }\n    \n    //cn_fast_hash for a 128 byte unsigned char\n    key cn_fast_hash128(const void * in) {\n        key hash;\n        keccak((const uint8_t *)in, 128, hash.bytes, 32);\n        return hash;\n    }\n    \n    key hash_to_scalar128(const void * in) {\n        key hash = cn_fast_hash128(in);\n        sc_reduce32(hash.bytes);\n        return hash;\n    }\n    \n    //cn_fast_hash for multisig purpose\n    //This takes the outputs and commitments\n    //and hashes them into a 32 byte sized key\n    key cn_fast_hash(const ctkeyV &PC) {\n        if (PC.empty()) return rct::hash2rct(crypto::cn_fast_hash(\"\", 0));\n        key rv;\n        cn_fast_hash(rv, &PC[0], 64*PC.size());\n        return rv;\n    }\n    \n    key hash_to_scalar(const ctkeyV &PC) {\n        key rv = cn_fast_hash(PC);\n        sc_reduce32(rv.bytes);\n        return rv;\n    }\n    \n   //cn_fast_hash for a key-vector of arbitrary length\n   //this is useful since you take a number of keys\n   //put them in the key vector and it concatenates them\n   //and then hashes them\n   key cn_fast_hash(const keyV &keys) {\n       if (keys.empty()) return rct::hash2rct(crypto::cn_fast_hash(\"\", 0));\n       key rv;\n       cn_fast_hash(rv, &keys[0], keys.size() * sizeof(keys[0]));\n       //dp(rv);\n       return rv;\n   }\n   \n   key hash_to_scalar(const keyV &keys) {\n       key rv = cn_fast_hash(keys);\n       sc_reduce32(rv.bytes);\n       return rv;\n   }\n\n   key cn_fast_hash(const key64 keys) {\n      key rv;\n      cn_fast_hash(rv, &keys[0], 64 * sizeof(keys[0]));\n      //dp(rv);\n      return rv;\n   }\n\n   key hash_to_scalar(const key64 keys) {\n       key rv = cn_fast_hash(keys);\n       sc_reduce32(rv.bytes);\n       return rv;\n   }\n\n    key hashToPointSimple(const key & hh) {\n        key pointk;\n        ge_p1p1 point2;\n        ge_p2 point;\n        ge_p3 res;\n        key h = cn_fast_hash(hh); \n        CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&res, h.bytes) == 0, \"ge_frombytes_vartime failed at \"+boost::lexical_cast<std::string>(__LINE__));\n        ge_p3_to_p2(&point, &res);\n        ge_mul8(&point2, &point);\n        ge_p1p1_to_p3(&res, &point2);\n        ge_p3_tobytes(pointk.bytes, &res);\n        return pointk;\n    }    \n    \n    key hashToPoint(const key & hh) {\n        key pointk;\n        ge_p2 point;\n        ge_p1p1 point2;\n        ge_p3 res;\n        key h = cn_fast_hash(hh); \n        ge_fromfe_frombytes_vartime(&point, h.bytes);\n        ge_mul8(&point2, &point);\n        ge_p1p1_to_p3(&res, &point2);        \n        ge_p3_tobytes(pointk.bytes, &res);\n        return pointk;\n    }\n\n    void hashToPoint(key & pointk, const key & hh) {\n        ge_p2 point;\n        ge_p1p1 point2;\n        ge_p3 res;\n        key h = cn_fast_hash(hh); \n        ge_fromfe_frombytes_vartime(&point, h.bytes);\n        ge_mul8(&point2, &point);\n        ge_p1p1_to_p3(&res, &point2);        \n        ge_p3_tobytes(pointk.bytes, &res);\n    }    \n\n    //sums a vector of curve points (for scalars use sc_add)\n    void sumKeys(key & Csum, const keyV &  Cis) {\n        identity(Csum);\n        size_t i = 0;\n        for (i = 0; i < Cis.size(); i++) {\n            addKeys(Csum, Csum, Cis[i]);\n        }\n    }\n\n    //Elliptic Curve Diffie Helman: encodes and decodes the amount b and mask a\n    // where C= aG + bH\n    void ecdhEncode(ecdhTuple & unmasked, const key & sharedSec) {\n        key sharedSec1 = hash_to_scalar(sharedSec);\n        key sharedSec2 = hash_to_scalar(sharedSec1);\n        //encode\n        sc_add(unmasked.mask.bytes, unmasked.mask.bytes, sharedSec1.bytes);\n        sc_add(unmasked.amount.bytes, unmasked.amount.bytes, sharedSec2.bytes);\n    }\n    void ecdhDecode(ecdhTuple & masked, const key & sharedSec) {\n        key sharedSec1 = hash_to_scalar(sharedSec);\n        key sharedSec2 = hash_to_scalar(sharedSec1);\n        //decode\n        sc_sub(masked.mask.bytes, masked.mask.bytes, sharedSec1.bytes);\n        sc_sub(masked.amount.bytes, masked.amount.bytes, sharedSec2.bytes);\n    }\n}\n", "meta": {"hexsha": "f67f5817bbd2d6a55e4d79c2e5bd1dd058af9815", "size": 15806, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ringct/rctOps.cpp", "max_stars_repo_name": "Dietr1ch/monea", "max_stars_repo_head_hexsha": "2a4fc1d38b38454f6aa937b54ed0fe083e48ab4c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-12-27T16:25:06.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-28T14:33:13.000Z", "max_issues_repo_path": "src/ringct/rctOps.cpp", "max_issues_repo_name": "Dietr1ch/monea", "max_issues_repo_head_hexsha": "2a4fc1d38b38454f6aa937b54ed0fe083e48ab4c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ringct/rctOps.cpp", "max_forks_repo_name": "Dietr1ch/monea", "max_forks_repo_head_hexsha": "2a4fc1d38b38454f6aa937b54ed0fe083e48ab4c", "max_forks_repo_licenses": ["BSD-3-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.2121212121, "max_line_length": 158, "alphanum_fraction": 0.6200177148, "num_tokens": 4521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.3812195803163618, "lm_q1q2_score": 0.2510016381267034}}
{"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_TRIGONOMETRIC_FUNCTIONS_SCALAR_IMPL_TRIGO_F_TRIG_REDUCTION_HPP_INCLUDED\n#define NT2_TRIGONOMETRIC_FUNCTIONS_SCALAR_IMPL_TRIGO_F_TRIG_REDUCTION_HPP_INCLUDED\n\n#include <nt2/sdk/meta/upgrade.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/meta/upgrade.hpp>\n#include <nt2/include/functions/simd/rem_pio2_medium.hpp>\n#include <nt2/include/functions/simd/rem_pio2_cephes.hpp>\n#include <nt2/include/functions/simd/rem_pio2_straight.hpp>\n#include <nt2/include/functions/simd/rem_pio2.hpp>\n#include <nt2/include/functions/toint.hpp>\n#include <nt2/include/functions/abs.hpp>\n#include <nt2/include/functions/round.hpp>\n#include <nt2/include/functions/is_odd.hpp>\n#include <nt2/include/functions/if_else.hpp>\n#include <nt2/include/functions/if_else_allbits.hpp>\n#include <nt2/include/functions/is_not_less.hpp>\n#include <nt2/include/functions/is_not_greater.hpp>\n#include <nt2/include/functions/is_greater_equal.hpp>\n#include <nt2/include/functions/is_less_equal.hpp>\n#include <nt2/include/functions/is_greater_equal.hpp>\n#include <nt2/include/functions/is_nez.hpp>\n#include <nt2/include/functions/multiplies.hpp>\n#include <nt2/include/functions/is_inf.hpp>\n#include <nt2/include/functions/bitwise_andnot.hpp>\n#include <nt2/include/functions/is_invalid.hpp>\n#include <nt2/include/functions/is_flint.hpp>\n#include <nt2/include/functions/rec.hpp>\n#include <nt2/include/functions/all.hpp>\n#include <nt2/include/constants/false.hpp>\n#include <nt2/include/constants/true.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/pi.hpp>\n#include <nt2/include/constants/pio_2.hpp>\n#include <nt2/include/constants/pio_4.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/include/constants/two.hpp>\n#include <boost/mpl/not.hpp>\n#include <boost/type_traits/is_same.hpp>\n\nnamespace nt2 { namespace details { namespace internal\n{\n  template< class A0\n            , class unit_tag\n            , class style\n            , class mode\n            , class base_A0 = typename meta::scalar_of<A0>::type\n  >\n  struct trig_reduction;\n\n  // This class exposes the public static member:\n  // reduce:                to provide range reduction\n  //\n  // unit_tag allows to choose statically the scaling  among radian_tag, pi_tag, degree_tag\n  // meaning that the cosa function will (for example) define respectively\n  // x-->cos(x)          (radian_tag),\n  // x-->cos(p*x)        (pi_tag)\n  // x-->cos((pi/180)*x) (degree_tag)\n  //\n  // precision_tag allows to choose policies among accuracy and speed\n  // are defined:\n  //   trig_tag\n  //   fast_tag\n  // fast_tag doe not mean that functions are returning stupid values\n  //    but that the range is very restricted.\n  // accu_tag does not mean that functions are ever slow,  but that they are\n  //    slower and slower with increased range, but they are speedier than\n  //    standard ones except for really big_ parameters values, because they return\n  //    quite accurate values even in these cases\n  //\n  // for each trigonometric function, xxx\n  //   xxx_\n  //   fast_xxx_\n  // NT2 functors are provided.\n\n  // trigonometric reduction strategies to the [-pi/4, pi/4] range.\n  // these reductions are used in the normal and fast\n  // trigonometric functions with different policies\n\n  template<class A0, class mode>\n  struct trig_reduction < A0, radian_tag,  tag::not_simd_type, mode, float>\n  {\n    typedef typename meta::as_integer<A0, signed>::type int_type;\n\n    static inline bool isalreadyreduced(const A0&a0) { return nt2::le(a0, nt2::Pio_4<A0>()); }\n    static inline bool ismedium (const A0&a0)        { return nt2::le(a0,single_constant<A0,0x43490fdb>()); }\n    static inline bool issmall  (const A0&a0)        { return nt2::le(a0,single_constant<A0,0x427b53d1>()); }\n    static inline bool islessthanpi_2  (const A0&a0) { return nt2::le(a0,nt2::Pio_2<A0>()); }\n    static inline bool conversion_allowed(){\n      typedef typename meta::upgrade<A0>::type uA0;\n      return boost::mpl::not_<boost::is_same<A0,uA0> >::value;\n    }\n\n    static inline bool cot_invalid(const A0& ) { return false; }\n    static inline bool tan_invalid(const A0& ) { return false; }\n\n    static inline int_type reduce(const A0& x, A0& xr){ return inner_reduce(x, xr, mode()); }\n  private:\n    static inline int_type inner_reduce(const A0& x, A0& xr, const big_&)\n    {\n      // x is always positive here\n      if (isalreadyreduced(x)) // all of x are in [0, pi/4], no reduction\n      {\n        xr = x;\n        return Zero<int_type>();\n      }\n      else if (islessthanpi_2(x)) // all of x are in [0, pi/2],  straight algorithm is sufficient for 1 ulp\n        return nt2::rem_pio2_straight(x, xr);\n      else if (issmall(x)) // all of x are in [0, 20*pi],  cephes algorithm is sufficient for 1 ulp\n        return nt2::rem_pio2_cephes(x, xr);\n      else if (ismedium(x)) // all of x are in [0, 2^7*pi/2],  fdlibm medium_ way\n        return nt2::rem_pio2_medium(x, xr);\n      else if (conversion_allowed())  // all of x are in [0, 2^18*pi],  conversion to double is used to reduce if available\n      {\n        typedef typename meta::upgrade<A0>::type uA0;\n        typedef trig_reduction< uA0, radian_tag,  tag::not_simd_type, mode, double> aux_reduction;\n        uA0 ux = x, uxr;\n        int_type n = static_cast<int_type>(aux_reduction::reduce(ux, uxr));\n        xr = static_cast<A0>(uxr);\n        return n;\n      }\n      else  // all of x are in [0, inf],  standard big_ way // too long\n      {\n        return nt2::rem_pio2(x, xr);\n      }\n\n    }\n\n    static inline int_type inner_reduce(const A0& x, A0& xr, const medium_&)\n    {\n      // x is always positive here\n      if (isalreadyreduced(x)) // all of x are in [0, pi/4], no reduction\n      {\n        xr = x;\n        return nt2::Zero<int_type>();\n      }\n      else if (islessthanpi_2(x)) // all of x are in [0, pi/2],  straight algorithm is sufficient for 1 ulp\n        return nt2::rem_pio2_straight(x, xr);\n      else if (issmall(x)) // all of x are in [0, 20*pi],  cephes algorithm is sufficient for 1 ulp\n        return nt2::rem_pio2_cephes(x, xr);\n      else  // correct only if all of x are in [0, 2^7*pi/2],  fdlibm medium_ way\n        return nt2::rem_pio2_medium(x, xr);\n    }\n\n    static inline int_type inner_reduce(const A0& x, A0& xr, const small_&)\n    {\n      // x is always positive here\n      if (isalreadyreduced(x)) // all of x are in [0, pi/4], no reduction\n      {\n        xr = x;\n        return Zero<int_type>();\n      }\n      else if (islessthanpi_2(x)) // all of x are in [0, pi/2],  straight algorithm is sufficient for 1 ulp\n        return nt2::rem_pio2_straight(x, xr);\n      else  // correct only if all of x are in [0, 20*pi],  cephes algorithm is sufficient for 1 ulp\n        return nt2::rem_pio2_cephes(x, xr);\n    }\n\n    static inline int_type inner_reduce(const A0& x, A0& xr, const direct_small_&)\n    {\n      return nt2::rem_pio2_cephes(x, xr);\n    }\n\n    static inline int_type inner_reduce(const A0& x, A0& xr, const direct_medium_&)\n    {\n      return nt2::rem_pio2_medium(x, xr);\n    }\n\n    static inline int_type inner_reduce(const A0& x, A0& xr, const direct_big_&)\n    {\n      if (conversion_allowed()) // conversion to double is used to reduce time, if available\n      {\n        typedef typename meta::upgrade<A0>::type uA0;\n        typedef trig_reduction< uA0, radian_tag,  tag::not_simd_type, mode, double> aux_reduction;\n        uA0 ux = x, uxr;\n        int_type n = aux_reduction::reduce(ux, uxr);\n        xr = uxr;\n        return n;\n      }\n      else\n      {\n        return nt2::rem_pio2(x, xr);\n      }\n    }\n\n    static inline int_type inner_reduce(const A0& x, A0& xr, const clipped_pio4_&)\n    {\n      xr = nt2::if_else(isalreadyreduced(x), x, Nan<A0>());\n      return nt2::Zero<int_type>();\n    }\n\n    static inline int_type inner_reduce(const A0& x, A0& xr, const clipped_small_&)\n    {\n      xr = nt2::if_else(issmall(x), x, nt2::Nan<A0>());\n      return inner_reduce(xr, xr, small_());\n    }\n    static inline int_type inner_reduce(const A0& x, A0& xr, const clipped_medium_&)\n    {\n      xr = nt2::if_else(ismedium(x), x, Nan<A0>());\n      return inner_reduce(xr, xr, medium_());\n    }\n  };\n\n  template<class A0>\n  struct trig_reduction<A0,degree_tag, tag::not_simd_type,big_, float>\n  {\n    typedef typename meta::as_integer<A0, signed>::type int_type;\n\n    static inline bool cot_invalid(const A0& x) { return nt2::is_nez(x)&&is_flint(x/_180<A0>()); }\n    static inline bool tan_invalid(const A0& x) { return nt2::is_flint((x-nt2::_90<A0>())/nt2::_180<A0>()); }\n\n    static inline int_type reduce(const A0& x, A0& xr)\n    {\n      A0 xi = nt2::round(x*single_constant<A0,0x3c360b61>()); //  1.111111111111111e-02f\n      A0 x2 = x - xi * nt2::_90<A0>();\n\n      xr =  x2*single_constant<A0,0x3c8efa35>(); //0.0174532925199432957692f\n      return nt2::toint(xi);\n    }\n\n    static inline int_type inner_reduce(const A0& x, A0& xr, const clipped_pio4_&)\n    {\n      xr = nt2::if_else_nan(isalreadyreduced(nt2::abs(x)), x);\n      return nt2::Zero<int_type>();\n    }\n    static inline int_type inner_reduce(const A0& x, A0& xr, const clipped_small_&)\n    {\n      x = nt2::if_else_nan(issmall(nt2::abs(x)), x);\n      return inner_reduce(x, xr, small_());\n    }\n    static inline int_type inner_reduce(const A0& x, A0& xr, const clipped_medium_&)\n    {\n      x = nt2::if_else_nan(ismedium(nt2::abs(x)), x);\n      return inner_reduce(x, xr, medium_());\n    }\n  };\n\n  template < class A0>\n  struct trig_reduction < A0, pi_tag,  tag::not_simd_type, big_, float>\n  {\n    typedef typename meta::as_integer<A0, signed>::type int_type;\n\n    static inline bool cot_invalid(const A0& x) { return nt2::is_nez(x)&&nt2::is_flint(x); }\n    static inline bool tan_invalid(const A0& x) { return nt2::is_flint(x-nt2::Half<A0>()) ; }\n\n    static inline int_type reduce(const A0& x,  A0& xr)\n    {\n      A0 xi = nt2::round(x*nt2::Two<A0>());\n      A0 x2 = x - xi * nt2::Half<A0>();\n      xr = x2*nt2::Pi<A0>();\n      return nt2::toint(xi);\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "c1740c61d6e5cd79e99467cacb336b407204b9cd", "size": 10564, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/functions/scalar/impl/trigo/f_trig_reduction.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/functions/scalar/impl/trigo/f_trig_reduction.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/trigonometric/include/nt2/trigonometric/functions/scalar/impl/trigo/f_trig_reduction.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7142857143, "max_line_length": 123, "alphanum_fraction": 0.6490912533, "num_tokens": 3015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2509080454825103}}
{"text": "/**\n * Copyright (c) 2016  Zubax Robotics OU  <info@zubax.com>\n *\n * 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 * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n *    following disclaimer in the documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote\n *    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 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 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, 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 WAY OUT OF THE\n * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#pragma once\n\n#include <Eigen/Eigen>\n#include <algorithm>\n#include <utility>\n#include <cassert>\n#include <type_traits>\n#include <cmath>\n#include <cstdint>\n#include <zubax_chibios/util/heapless.hpp>\n\n\nnamespace math\n{\n\nusing Scalar = float;\nusing Const = const Scalar;\n\ntemplate <int Rows, int Cols>\nusing Matrix = Eigen::Matrix<Scalar, Rows, Cols>;\n\ntemplate <int Rows>\nusing DiagonalMatrix = Eigen::DiagonalMatrix<Scalar, Rows>;\n\ntemplate <int Size>\nusing Vector = Matrix<Size, 1>;\n\n\nconstexpr inline Scalar convertKelvinToCelsius(Const kelvin)\n{\n    return kelvin - 273.15F;\n}\n\nconstexpr inline Scalar convertCelsiusToKelvin(Const kelvin)\n{\n    return kelvin + 273.15F;\n}\n\n/**\n * Constants\n */\nconstexpr auto Pi  = Scalar(3.141592653589793);\nconstexpr auto Pi2 = Scalar(6.283185307179586);\n\n/**\n * Constrains the angle within [0, Pi*2]\n */\ninline Scalar normalizeAngle(Scalar x)\n{\n    if (x >= Pi2)\n    {\n        return x - Pi2;\n    }\n    else if (x < 0)\n    {\n        return x + Pi2;\n    }\n    else\n    {\n        return x;\n    }\n}\n\n/**\n * Inclusive range of the form [min, max].\n */\ntemplate <typename T = Scalar>\nstruct Range\n{\n    T min = T(0);\n    T max = T(0);\n\n    constexpr Range() { }\n\n    constexpr Range(const T min, const T max) :\n        min(min),\n        max(max)\n    {\n        assert(min < max);\n    }\n\n    constexpr T constrain(const T value) const\n    {\n        return std::min(std::max(value, min), max);\n    }\n\n    constexpr bool contains(const T value) const\n    {\n        return (value >= min) && (value <= max);\n    }\n\n    auto toString() const\n    {\n        return os::heapless::concatenate(\"[\", min, \", \", max, \"]\");\n    }\n};\n\n/**\n * Simple moving average of arbitrary depth.\n */\ntemplate <unsigned Depth, typename T>\nclass SimpleMovingAverageFilter\n{\n    T history_[Depth] = {};\n    T sum_;\n    unsigned next_index_ = 0;\n\npublic:\n    SimpleMovingAverageFilter() :\n        sum_(T() * Depth)\n    {\n        std::fill_n(std::begin(history_), Depth, T());\n    }\n\n    explicit SimpleMovingAverageFilter(const T& initial_value) :\n        sum_(initial_value * Depth)\n    {\n        std::fill_n(std::begin(history_), Depth, initial_value);\n    }\n\n    void update(const T& value)\n    {\n        sum_ -= history_[next_index_];\n        history_[next_index_] = value;\n        sum_ += history_[next_index_];\n\n        next_index_++;\n        if (next_index_ >= Depth)\n        {\n            next_index_ = 0;\n        }\n    }\n\n    void reset(const T& initial_value)\n    {\n        sum_ = initial_value * Depth;\n        std::fill_n(std::begin(history_), Depth, initial_value);\n    }\n\n    T getValue() const\n    {\n        return sum_ / Depth;\n    }\n};\n\n/**\n * Copmutes average over the entire collected dataset.\n * Useful for calibration and other batch measurements, e.g. motor identification.\n */\ntemplate <typename T = double>\nclass CumulativeAverageComputer\n{\n    std::uint32_t num_samples_ = 0;\n    T accumulator_{};\n\n    using FloatingPointScalar = typename std::conditional<std::is_floating_point<T>::value, T, Scalar>::type;\n\npublic:\n    CumulativeAverageComputer() :\n        accumulator_()\n    { }\n\n    explicit CumulativeAverageComputer(const T& init) :\n        accumulator_(init)\n    { }\n\n    void addSample(const T& x)\n    {\n        num_samples_++;\n        accumulator_ += x;\n    }\n\n    T getAverage() const\n    {\n        if (num_samples_ > 0)\n        {\n            return T(accumulator_ / FloatingPointScalar(num_samples_));\n        }\n        else\n        {\n            assert(false);\n            return T();\n        }\n    }\n\n    auto getNumSamples() const { return num_samples_; }\n};\n\n\ninline Vector<2> sincos(Scalar x)\n{\n    // Normally this should be replaced with a call to sincos(), but this is not a part of C++ standard library.\n    // However, the compiler should be able to replace the two separate but localized calls to\n    // sin()/cos() with one sincos().\n    return { std::sin(x), std::cos(x) };\n}\n\n/**\n * Implementation details, do not use directly.\n */\nnamespace impl_\n{\n\ntemplate <typename Scalar, int Size>\nusing RowVector = Eigen::Matrix<Scalar, 1, Size, Eigen::RowMajor>;\n\ntemplate <typename Scalar, int Size, typename Head>\ninline void fillVector(RowVector<Scalar, Size>& vector,\n                       int next_index,\n                       Head head)\n{\n    vector[next_index] = static_cast<Scalar>(head);\n}\n\ntemplate <typename Scalar, int Size, typename Head, typename... Tail>\ninline void fillVector(RowVector<Scalar, Size>& vector,\n                       int next_index,\n                       Head head,\n                       Tail... tail)\n{\n    vector[next_index] = static_cast<Scalar>(head);\n    fillVector(vector, next_index + 1, tail...);\n}\n\ntemplate <typename Scalar, int Rows, int Columns>\ninline void fillMatrix(Eigen::Matrix<Scalar, Rows, Columns>& matrix,\n                       int next_row,\n                       const impl_::RowVector<Scalar, Columns>& head)\n{\n    matrix.row(next_row) = head;\n}\n\ntemplate <typename Scalar, int Rows, int Columns, typename... Tail>\ninline void fillMatrix(Eigen::Matrix<Scalar, Rows, Columns>& matrix,\n                       int next_row,\n                       const impl_::RowVector<Scalar, Columns>& head,\n                       Tail... tail)\n{\n    matrix.row(next_row) = head;\n    fillMatrix(matrix, next_row + 1, tail...);\n}\n\ntemplate <typename Scalar, int DiagonalSize>\ninline void fillDiagonalMatrix(Eigen::DiagonalMatrix<Scalar, DiagonalSize>& matrix,\n                               int next_position,\n                               Scalar head)\n{\n    matrix.diagonal()[next_position] = static_cast<Scalar>(head);\n}\n\ntemplate <typename Scalar, int DiagonalSize, typename... Tail>\ninline void fillDiagonalMatrix(Eigen::DiagonalMatrix<Scalar, DiagonalSize>& matrix,\n                               int next_position,\n                               Scalar head,\n                               Tail... tail)\n{\n    matrix.diagonal()[next_position] = static_cast<Scalar>(head);\n    fillDiagonalMatrix<Scalar, DiagonalSize>(matrix, next_position + 1, tail...);\n}\n\n} // namespace impl_\n\n/**\n * Creates a row vector of arbitrary length, represented as a static row vector Eigen::Matrix<>.\n * Scalar type can be overriden.\n * See also @ref makeMatrix().\n */\ntemplate <typename Scalar = Scalar, typename... Tail>\ninline impl_::RowVector<Scalar, sizeof...(Tail)>\nmakeRow(Tail... tail)\n{\n    impl_::RowVector<Scalar, sizeof...(Tail)> vector;\n    impl_::fillVector(vector, 0, tail...);\n    return vector;\n}\n\n/**\n * Creates a static matrix (Eigen::Matrix<>) of arbitrary size from a set of row vectors.\n * The matrix will use default layout, which is columnn-major for Eigen.\n * Note that row vectors of unequal size trigger a compile-time error.\n * Scalar type will be deduced automatically from the first row.\n * This function is totally type safe.\n * Usage:\n *      makeMatrix(makeRow(1, 2),\n *                 makeRow(3, 4))  // Produces a 2x2 matrix\n */\ntemplate <typename Scalar, int Columns, typename... Tail>\ninline Eigen::Matrix<Scalar, sizeof...(Tail) + 1, Columns>\nmakeMatrix(const impl_::RowVector<Scalar, Columns>& head,\n           Tail... tail)\n{\n    Eigen::Matrix<Scalar, sizeof...(Tail) + 1, Columns> matrix;\n    matrix.setZero();\n    impl_::fillMatrix(matrix, 0, head, tail...);\n    return matrix;\n}\n\n/**\n * A helper like @ref makeMatrix() that creates diagonal matrix.\n * Size is dereved from the argument list.\n * Scalar type can be overriden.\n */\ntemplate <typename Scalar = Scalar, typename... Diagonal>\ninline Eigen::DiagonalMatrix<Scalar, sizeof...(Diagonal)>\nmakeDiagonalMatrix(Diagonal... diag)\n{\n    Eigen::DiagonalMatrix<Scalar, sizeof...(Diagonal)> matrix;\n    matrix.setZero();\n    impl_::fillDiagonalMatrix<Scalar, sizeof...(Diagonal)>(matrix, 0, diag...);\n    return matrix;\n}\n\n/**\n * Printing helpers\n * @{\n */\nenum class StringRepresentation\n{\n    SingleLine,\n    MultiLine\n};\n\ntemplate <typename Scalar, int Rows, int Columns>\ninline auto toString(const Eigen::Matrix<Scalar, Rows, Columns>& matrix,\n                     const StringRepresentation representation = StringRepresentation::SingleLine)\n{\n    os::heapless::String<Rows * Columns * 20> s;\n\n    for (int row = 0; row < Rows; row++)\n    {\n        if (row > 0)\n        {\n            s.append((representation == StringRepresentation::MultiLine) ? \"\\n\" : \"; \");\n        }\n        for (int column = 0; column < Columns; column++)\n        {\n            if (column > 0)\n            {\n                s.append(\", \");\n            }\n            s.append(matrix(row, column));\n        }\n    }\n\n    return s;\n}\n/**\n * @}\n */\n\n}\n", "meta": {"hexsha": "a07d9dd1c398ce1dc81ad906e7db6564e20ab428", "size": 10171, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "firmware/src/math/math.hpp", "max_stars_repo_name": "zenglongGH/px4esc", "max_stars_repo_head_hexsha": "b12adc96a180503c75856220cfe8539cb24204cc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-07T22:27:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-07T22:27:54.000Z", "max_issues_repo_path": "firmware/src/math/math.hpp", "max_issues_repo_name": "zenglongGH/px4esc", "max_issues_repo_head_hexsha": "b12adc96a180503c75856220cfe8539cb24204cc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "firmware/src/math/math.hpp", "max_forks_repo_name": "zenglongGH/px4esc", "max_forks_repo_head_hexsha": "b12adc96a180503c75856220cfe8539cb24204cc", "max_forks_repo_licenses": ["BSD-3-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.0505319149, "max_line_length": 118, "alphanum_fraction": 0.637892046, "num_tokens": 2347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.25084912766258755}}
{"text": "/**\n * \\file\n * \\author Thomas Fischer\n * \\date   2010-06-21\n * \\brief  Implementation of the Polygon class.\n *\n * \\copyright\n * Copyright (c) 2012-2019, 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 \"Polygon.h\"\n\n#include <logog/include/logog.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include \"BaseLib/quicksort.h\"\n\n#include \"AnalyticalGeometry.h\"\n\nnamespace GeoLib\n{\nPolygon::Polygon(const Polyline &ply, bool init) :\n    Polyline(ply), _aabb(ply.getPointsVec(), ply._ply_pnt_ids)\n{\n    if (init)\n    {\n        initialise();\n    }\n    _simple_polygon_list.push_back(this);\n}\n\nPolygon::Polygon(Polygon const& other)\n    : Polyline(other), _aabb(other._aabb)\n{\n    _simple_polygon_list.push_back(this);\n    auto sub_polygon_it(other._simple_polygon_list.begin());\n    for (sub_polygon_it++;  // the first entry is the polygon itself, skip the\n                            // entry\n         sub_polygon_it != other._simple_polygon_list.end();\n         ++sub_polygon_it)\n    {\n        _simple_polygon_list.emplace_back(new Polygon(*(*sub_polygon_it)));\n    }\n}\n\nPolygon::~Polygon()\n{\n    // remove polygons from list\n    for (auto& polygon : _simple_polygon_list)\n    {\n        // the first entry of the list can be a pointer the object itself\n        if (polygon != this)\n        {\n            delete polygon;\n        }\n    }\n}\n\nbool Polygon::initialise ()\n{\n    if (this->isClosed()) {\n        ensureCCWOrientation();\n        return true;\n    }\n    WARN(\"Polygon::initialise(): base polyline is not closed.\");\n    return false;\n}\n\nbool Polygon::isPntInPolygon(GeoLib::Point const& pnt) const\n{\n    MathLib::Point3d const& min_aabb_pnt(_aabb.getMinPoint());\n    MathLib::Point3d const& max_aabb_pnt(_aabb.getMaxPoint());\n\n    if (pnt[0] < min_aabb_pnt[0] || max_aabb_pnt[0] < pnt[0] ||\n        pnt[1] < min_aabb_pnt[1] || max_aabb_pnt[1] < pnt[1])\n    {\n        return false;\n    }\n\n    if (_simple_polygon_list.size() == 1)\n    {\n        std::size_t n_intersections(0);\n        const std::size_t n_nodes(getNumberOfPoints() - 1);\n        for (std::size_t k(0); k < n_nodes; k++)\n        {\n            if (((*(getPoint(k)))[1] <= pnt[1] &&\n                 pnt[1] <= (*(getPoint(k + 1)))[1]) ||\n                ((*(getPoint(k + 1)))[1] <= pnt[1] &&\n                 pnt[1] <= (*(getPoint(k)))[1]))\n            {\n                switch (getEdgeType(k, pnt))\n                {\n                    case EdgeType::TOUCHING:\n                        return true;\n                    case EdgeType::CROSSING:\n                        n_intersections++;\n                        break;\n                    case EdgeType::INESSENTIAL:\n                        break;\n                    default:\n                        // do nothing\n                        ;\n                }\n            }\n        }\n        if (n_intersections % 2 == 1)\n        {\n            return true;\n        }\n    }\n    else\n    {\n        for (auto it(_simple_polygon_list.begin()++);\n             it != _simple_polygon_list.end();\n             ++it)\n        {\n            if ((*it)->isPntInPolygon(pnt))\n            {\n                return true;\n            }\n        }\n    }\n    return false;\n}\n\nbool Polygon::isPntInPolygon(double x, double y, double z) const\n{\n    const GeoLib::Point pnt(x,y,z);\n    return isPntInPolygon(pnt);\n}\n\nstd::vector<GeoLib::Point> Polygon::getAllIntersectionPoints(\n        GeoLib::LineSegment const& segment) const\n{\n    std::vector<GeoLib::Point> intersections;\n    GeoLib::Point s;\n    for (auto&& seg_it : *this)\n    {\n        if (GeoLib::lineSegmentIntersect(seg_it, segment, s)) {\n            intersections.push_back(s);\n        }\n    }\n\n    return intersections;\n}\n\nbool Polygon::containsSegment(GeoLib::LineSegment const& segment) const\n{\n    std::vector<GeoLib::Point> s(getAllIntersectionPoints(segment));\n\n    GeoLib::Point const& a{segment.getBeginPoint()};\n    GeoLib::Point const& b{segment.getEndPoint()};\n    // no intersections -> check if at least one point of segment is in polygon\n    if (s.empty()) {\n        return (isPntInPolygon(a));\n    }\n\n    const double tol(std::numeric_limits<float>::epsilon());\n\n    // one intersection, intersection in line segment end point\n    if (s.size() == 1) {\n        const double sqr_dist_as(MathLib::sqrDist(a,s[0]));\n        if (sqr_dist_as < tol) {\n            return (isPntInPolygon(b));\n        }\n\n        const double sqr_dist_bs(MathLib::sqrDist(b,s[0]));\n        if (sqr_dist_bs < tol) {\n            return (isPntInPolygon(a));\n        }\n    }\n\n    // Sorting the intersection with respect to the distance to the point a.\n    // This induces a partition of the line segment into sub segments.\n    std::sort(s.begin(), s.end(),\n        [&a] (GeoLib::Point const& p0, GeoLib::Point const& p1) {\n            return MathLib::sqrDist(a, p0) < MathLib::sqrDist(a, p1);\n        }\n    );\n\n    // remove sub segments with almost zero length\n    for (std::size_t k(0); k<s.size()-1; ) {\n        if (MathLib::sqrDist(s[k], s[k+1]) < tol) {\n            s.erase(s.begin()+k+1);\n        } else {\n            k++;\n        }\n    }\n\n    // Check if all sub segments are within the polygon.\n    if (!isPntInPolygon(GeoLib::Point(0.5 * (a[0] + s[0][0]),\n                                      0.5 * (a[1] + s[0][1]),\n                                      0.5 * (a[2] + s[0][2]))))\n    {\n        return false;\n    }\n    const std::size_t n_sub_segs(s.size()-1);\n    for (std::size_t k(0); k<n_sub_segs; k++) {\n        if (!isPntInPolygon(GeoLib::Point(0.5 * (s[k][0] + s[k + 1][0]),\n                                          0.5 * (s[k][1] + s[k + 1][1]),\n                                          0.5 * (s[k][2] + s[k + 1][2]))))\n        {\n            return false;\n        }\n    }\n    return isPntInPolygon(GeoLib::Point(0.5 * (s[0][0] + b[0]),\n                                        0.5 * (s[0][1] + b[1]),\n                                        0.5 * (s[0][2] + b[2])));\n}\n\nbool Polygon::isPolylineInPolygon(const Polyline& ply) const\n{\n    for (auto segment : ply) {\n        if (!containsSegment(segment)) {\n            return false;\n        }\n    }\n    return true;\n}\n\nbool Polygon::isPartOfPolylineInPolygon(const Polyline& ply) const\n{\n    const std::size_t ply_size (ply.getNumberOfPoints());\n    // check points\n    for (std::size_t k(0); k < ply_size; k++) {\n        if (isPntInPolygon (*(ply.getPoint(k)))) {\n            return true;\n        }\n    }\n\n    GeoLib::Point s;\n    for (auto polygon_seg : *this) {\n        for (auto polyline_seg : ply) {\n            if (GeoLib::lineSegmentIntersect(polyline_seg, polygon_seg, s)) {\n                return true;\n            }\n        }\n    }\n\n    return false;\n}\n\nbool Polygon::getNextIntersectionPointPolygonLine(\n    GeoLib::LineSegment const& seg, GeoLib::Point & intersection,\n    std::size_t& seg_num) const\n{\n    if (_simple_polygon_list.size() == 1) {\n        for (auto seg_it(begin()+seg_num); seg_it != end(); ++seg_it) {\n            if (GeoLib::lineSegmentIntersect(*seg_it, seg, intersection)) {\n                seg_num = seg_it.getSegmentNumber();\n                return true;\n            }\n        }\n    } else {\n        for (auto polygon : _simple_polygon_list)\n        {\n            for (auto seg_it(polygon->begin()); seg_it != polygon->end();\n                 ++seg_it)\n            {\n                if (GeoLib::lineSegmentIntersect(*seg_it, seg, intersection)) {\n                    seg_num = seg_it.getSegmentNumber();\n                    return true;\n                }\n            }\n        }\n    }\n    return false;\n}\n\nEdgeType Polygon::getEdgeType(std::size_t k, GeoLib::Point const& pnt) const\n{\n    switch (getLocationOfPoint(k, pnt))\n    {\n    case Location::LEFT: {\n        const GeoLib::Point & v (*(getPoint(k)));\n        const GeoLib::Point & w (*(getPoint(k + 1)));\n        if (v[1] < pnt[1] && pnt[1] <= w[1])\n        {\n            return EdgeType::CROSSING;\n        }\n\n        return EdgeType::INESSENTIAL;\n    }\n    case Location::RIGHT: {\n        const GeoLib::Point & v (*(getPoint(k)));\n        const GeoLib::Point & w (*(getPoint(k + 1)));\n        if (w[1] < pnt[1] && pnt[1] <= v[1])\n        {\n            return EdgeType::CROSSING;\n        }\n\n        return EdgeType::INESSENTIAL;\n    }\n    case Location::BETWEEN:\n    case Location::SOURCE:\n    case Location::DESTINATION:\n        return EdgeType::TOUCHING;\n    default:\n        return EdgeType::INESSENTIAL;\n    }\n}\n\nvoid Polygon::ensureCCWOrientation ()\n{\n    // *** pre processing: rotate points to xy-plan\n    // *** copy points to vector - last point is identical to the first\n    std::size_t n_pnts (this->getNumberOfPoints() - 1);\n    std::vector<GeoLib::Point*> tmp_polygon_pnts;\n    for (std::size_t k(0); k < n_pnts; k++)\n    {\n        tmp_polygon_pnts.push_back(new GeoLib::Point(*(this->getPoint(k))));\n    }\n\n    // rotate copied points into x-y-plane\n    GeoLib::rotatePointsToXY(tmp_polygon_pnts);\n\n    for (auto& tmp_polygon_pnt : tmp_polygon_pnts)\n    {\n        (*tmp_polygon_pnt)[2] =\n            0.0;  // should be -= d but there are numerical errors\n    }\n\n    // *** get the left most upper point\n    std::size_t min_x_max_y_idx (0); // for orientation check\n    for (std::size_t k(0); k < n_pnts; k++)\n    {\n        if ((*(tmp_polygon_pnts[k]))[0] <= (*(tmp_polygon_pnts[min_x_max_y_idx]))[0])\n        {\n            if ((*(tmp_polygon_pnts[k]))[0] <\n                (*(tmp_polygon_pnts[min_x_max_y_idx]))[0])\n            {\n                min_x_max_y_idx = k;\n            }\n            else if ((*(tmp_polygon_pnts[k]))[1] >\n                     (*(tmp_polygon_pnts[min_x_max_y_idx]))[1])\n            {\n                min_x_max_y_idx = k;\n            }\n        }\n    }\n    // *** determine orientation\n    GeoLib::Orientation orient;\n    if (0 < min_x_max_y_idx && min_x_max_y_idx < n_pnts - 2)\n    {\n        orient = GeoLib::getOrientation(*tmp_polygon_pnts[min_x_max_y_idx - 1],\n                                        *tmp_polygon_pnts[min_x_max_y_idx],\n                                        *tmp_polygon_pnts[min_x_max_y_idx + 1]);\n    }\n    else\n    {\n        if (0 == min_x_max_y_idx)\n        {\n            orient = GeoLib::getOrientation(*tmp_polygon_pnts[n_pnts - 1],\n                                            *tmp_polygon_pnts[0],\n                                            *tmp_polygon_pnts[1]);\n        }\n        else\n        {\n            orient = GeoLib::getOrientation(*tmp_polygon_pnts[n_pnts - 2],\n                                            *tmp_polygon_pnts[n_pnts - 1],\n                                            *tmp_polygon_pnts[0]);\n        }\n    }\n\n    if (orient != GeoLib::CCW)\n    {\n        // switch orientation\n        std::size_t tmp_n_pnts (n_pnts);\n        tmp_n_pnts++; // include last point of polygon (which is identical to the first)\n        for (std::size_t k(0); k < tmp_n_pnts / 2; k++)\n        {\n            std::swap(_ply_pnt_ids[k], _ply_pnt_ids[tmp_n_pnts - 1 - k]);\n        }\n    }\n\n    for (std::size_t k(0); k < n_pnts; k++)\n    {\n        delete tmp_polygon_pnts[k];\n    }\n}\n\n#if __GNUC__ <= 4 && (__GNUC_MINOR__ < 9)\nvoid Polygon::splitPolygonAtIntersection(\n    const std::list<Polygon*>::iterator& polygon_it)\n#else\nvoid Polygon::splitPolygonAtIntersection(\n    const std::list<Polygon*>::const_iterator& polygon_it)\n#endif\n{\n    GeoLib::Polyline::SegmentIterator seg_it0((*polygon_it)->begin());\n    GeoLib::Polyline::SegmentIterator seg_it1((*polygon_it)->begin());\n    GeoLib::Point intersection_pnt;\n    if (!GeoLib::lineSegmentsIntersect(*polygon_it, seg_it0, seg_it1,\n                                       intersection_pnt))\n    {\n        return;\n    }\n\n    std::size_t idx0(seg_it0.getSegmentNumber());\n    std::size_t idx1(seg_it1.getSegmentNumber());\n    // adding intersection point to pnt_vec\n    std::size_t const intersection_pnt_id (_ply_pnts.size());\n    const_cast<std::vector<Point*>&>(_ply_pnts)\n        .push_back(new GeoLib::Point(intersection_pnt));\n\n    // split Polygon\n    if (idx0 > idx1)\n    {\n        std::swap(idx0, idx1);\n    }\n\n    GeoLib::Polyline polyline0{(*polygon_it)->getPointsVec()};\n    for (std::size_t k(0); k <= idx0; k++)\n    {\n        polyline0.addPoint((*polygon_it)->getPointID(k));\n    }\n    polyline0.addPoint(intersection_pnt_id);\n    for (std::size_t k(idx1 + 1); k < (*polygon_it)->getNumberOfPoints(); k++)\n    {\n        polyline0.addPoint((*polygon_it)->getPointID(k));\n    }\n\n    GeoLib::Polyline polyline1{(*polygon_it)->getPointsVec()};\n    polyline1.addPoint(intersection_pnt_id);\n    for (std::size_t k(idx0 + 1); k <= idx1; k++)\n    {\n        polyline1.addPoint((*polygon_it)->getPointID(k));\n    }\n    polyline1.addPoint(intersection_pnt_id);\n\n    // remove the polygon except the first\n    if (*polygon_it != this)\n    {\n        delete *polygon_it;\n    }\n    // erase polygon_it and add two new polylines\n    auto polygon1_it = _simple_polygon_list.insert(\n        _simple_polygon_list.erase(polygon_it), new GeoLib::Polygon(polyline1));\n    auto polygon0_it = _simple_polygon_list.insert(\n        polygon1_it, new GeoLib::Polygon(polyline0));\n\n    splitPolygonAtIntersection(polygon0_it);\n    splitPolygonAtIntersection(polygon1_it);\n}\n\nvoid Polygon::splitPolygonAtPoint (const std::list<GeoLib::Polygon*>::iterator& polygon_it)\n{\n    std::size_t const n((*polygon_it)->getNumberOfPoints() - 1);\n    std::vector<std::size_t> id_vec(n);\n    std::vector<std::size_t> perm(n);\n    for (std::size_t k(0); k < n; k++)\n    {\n        id_vec[k] = (*polygon_it)->getPointID (k);\n        perm[k] = k;\n    }\n\n    BaseLib::quicksort (id_vec, 0, n, perm);\n\n    for (std::size_t k(0); k < n - 1; k++)\n    {\n        if (id_vec[k] == id_vec[k + 1])\n        {\n            std::size_t idx0 = perm[k];\n            std::size_t idx1 = perm[k + 1];\n\n            if (idx0 > idx1)\n            {\n                std::swap(idx0, idx1);\n            }\n\n            // create two closed polylines\n            GeoLib::Polyline polyline0{*(*polygon_it)};\n            for (std::size_t j(0); j <= idx0; j++)\n            {\n                polyline0.addPoint((*polygon_it)->getPointID(j));\n            }\n            for (std::size_t j(idx1 + 1);\n                 j < (*polygon_it)->getNumberOfPoints();\n                 j++)\n            {\n                polyline0.addPoint((*polygon_it)->getPointID(j));\n            }\n\n            GeoLib::Polyline polyline1{*(*polygon_it)};\n            for (std::size_t j(idx0); j <= idx1; j++)\n            {\n                polyline1.addPoint((*polygon_it)->getPointID(j));\n            }\n\n            // remove the polygon except the first\n            if (*polygon_it != this)\n            {\n                delete *polygon_it;\n            }\n            // erase polygon_it and add two new polygons\n            auto polygon1_it = _simple_polygon_list.insert(\n                _simple_polygon_list.erase(polygon_it), new Polygon(polyline1));\n            auto polygon0_it = _simple_polygon_list.insert(\n                polygon1_it, new Polygon(polyline0));\n\n            splitPolygonAtPoint(polygon0_it);\n            splitPolygonAtPoint(polygon1_it);\n\n            return;\n        }\n    }\n}\n\nbool operator==(Polygon const& lhs, Polygon const& rhs)\n{\n    if (lhs.getNumberOfPoints() != rhs.getNumberOfPoints())\n    {\n        return false;\n    }\n\n    const std::size_t n(lhs.getNumberOfPoints());\n    const std::size_t start_pnt(lhs.getPointID(0));\n\n    // search start point of first polygon in second polygon\n    bool nfound(true);\n    std::size_t k(0);\n    for (; k < n-1 && nfound; k++) {\n        if (start_pnt == rhs.getPointID(k)) {\n            nfound = false;\n            break;\n        }\n    }\n\n    // case: start point not found in second polygon\n    if (nfound)\n    {\n        return false;\n    }\n\n    // *** determine direction\n    // opposite direction\n    if (k == n-2) {\n        for (k=1; k<n-1; k++) {\n            if (lhs.getPointID(k) != rhs.getPointID(n-1-k)) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    // same direction - start point of first polygon at arbitrary position in second polygon\n    if (lhs.getPointID(1) == rhs.getPointID(k+1)) {\n        std::size_t j(k+2);\n        for (; j<n-1; j++) {\n            if (lhs.getPointID(j-k) != rhs.getPointID(j)) {\n                return false;\n            }\n        }\n        j=0; // new start point at second polygon\n        for (; j<k+1; j++) {\n            if (lhs.getPointID(n-(k+2)+j+1) != rhs.getPointID(j)) {\n                return false;\n            }\n        }\n        return true;\n    }\n    // opposite direction with start point of first polygon at arbitrary\n    // position\n    // *** ATTENTION\n    WARN(\n        \"operator==(Polygon const& lhs, Polygon const& rhs) - not tested case \"\n        \"(implementation is probably buggy) - please contact \"\n        \"thomas.fischer@ufz.de mentioning the problem.\");\n    // in second polygon\n    if (lhs.getPointID(1) == rhs.getPointID(k - 1))\n    {\n        std::size_t j(k - 2);\n        for (; j > 0; j--)\n        {\n            if (lhs.getPointID(k - 2 - j) != rhs.getPointID(j))\n            {\n                return false;\n            }\n        }\n        // new start point at second polygon - the point n-1 of a polygon is\n        // equal to the first point of the polygon (for this reason: n-2)\n        j = n - 2;\n        for (; j > k - 1; j--)\n        {\n            if (lhs.getPointID(n - 2 + j + k - 2) != rhs.getPointID(j))\n            {\n                return false;\n            }\n        }\n        return true;\n    }\n    return false;\n}\n\n} // end namespace GeoLib\n", "meta": {"hexsha": "2975a07484c4587b51a5870fa525236ee672dca5", "size": 17747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GeoLib/Polygon.cpp", "max_stars_repo_name": "zhangning737/ogs", "max_stars_repo_head_hexsha": "53a892f4ce2f133e4d00534d33ad4329e5c0ccb2", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-25T13:43:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-25T13:43:06.000Z", "max_issues_repo_path": "GeoLib/Polygon.cpp", "max_issues_repo_name": "kosakowski/OGS6-MP-LT-Drum", "max_issues_repo_head_hexsha": "01d8ef8839e5dbe50d09621393cb137d278eeb7e", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-09T12:13:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-09T12:13:22.000Z", "max_forks_repo_path": "GeoLib/Polygon.cpp", "max_forks_repo_name": "zhangning737/ogs", "max_forks_repo_head_hexsha": "53a892f4ce2f133e4d00534d33ad4329e5c0ccb2", "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": 29.5783333333, "max_line_length": 92, "alphanum_fraction": 0.5314137601, "num_tokens": 4635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.25062227818932004}}
{"text": "#define NDEBUG\n#include \"pca.hh\"\n#include \"pcaoptions.hh\"\n#include <cctype>\n#include <cfloat>\n#include <fstream>\n#include <iostream>\n#include <Eigen/Eigenvalues>\n\n#define FUDGE 10\n\nnamespace\n{\n  using namespace hashpca;\n  using veedubparse::HashAll;\n  using veedubparse::HashString;\n\n  // http://www0.cs.ucl.ac.uk/staff/d.jones/GoodPracticeRNG.pdf\n\n  /* Implementation of a 32-bit KISS generator which uses no multiply instructions */\n  unsigned int JKISS32 ()\n  {\n    static uint32_t x=123456789,y=234567891,z=345678912,w=456789123,c=0;\n    int32_t t;\n    y ^= (y<<5); y ^= (y>>7); y ^= (y<<22); \n    t = z+w+c; z = w; c = t < 0; w = t&2147483647;\n    x += 1411392427;\n    return x + y + w;\n  }\n\n  double urandom ()\n    {\n      return .0000000002328306089594001 * JKISS32() + FLT_EPSILON;\n    }\n\n  //This is faster than Box-Muller but not benchmarked against inverse cdf\n  double\n  gensample (double)\n    {\n      double u,v,x,x2;\n\n      do\n        {\n          u = urandom();\n          v = 1.71552776992141359294*urandom()-.85776388496070679647;\n          x = v/u;\n          x2 = x*x;\n        }\n      while(x2>6-8*u+2*u*u && (x2>2/u-2*u || x2>-4*log(u)));\n\n      return x;\n    }\n\n  void\n  orthonormalize (hashpca::MatrixXd& Y)\n    {\n      // // http://forum.kde.org/viewtopic.php?f=74&t=91271\n      // // Unfortunately this appears memory intensive :(\n      // Eigen::HouseholderQR<hashpca::MatrixXd> qr (Y);\n      // Y = qr.householderQ () * hashpca::MatrixXd::Identity (Y.rows (), Y.cols ());\n\n      Y.transposeInPlace ();\n\n      // Gram-Schmidt has no space overhead\n      for (unsigned int j = 0; j < Y.rows (); ++j)\n        {\n          for (unsigned int i = 0; i < j; ++i)\n            Y.row (j) -= Y.row (i).dot (Y.row (j)) * Y.row (i);\n\n          for (unsigned int i = 0; i < j; ++i)\n            Y.row (j) -= Y.row (i).dot (Y.row (j)) * Y.row (i);\n\n          Y.row (j).normalize ();\n        }\n\n      Y.transposeInPlace ();\n    }\n\n  Eigen::VectorXd\n  smallsvd (const hashpca::MatrixXd& Z,\n            hashpca::MatrixXd&       V)\n    {\n      hashpca::MatrixXd ZtZ = Z.transpose () * Z;\n      Eigen::SelfAdjointEigenSolver<hashpca::MatrixXd> es (ZtZ);\n      Eigen::VectorXd s = es.eigenvalues ();\n      hashpca::MatrixXd Upsilon = es.eigenvectors ();\n\n      s = s.unaryExpr ([] (double x) { return x <= 0.0 ? 0.0 : sqrt (x); });\n\n      Eigen::VectorXd pinv = s.unaryExpr ([] (double x) { return 1.0 / (1e-6 + x); });\n\n      V.noalias () = Z * Upsilon * pinv.asDiagonal ();\n\n      s = s.unaryExpr ([] (double x) { return x <= 0.0 ? 0.0 : sqrt (x); });\n\n      return s;\n    }\n\n  int  \n  writemodel (PcaOptions                options,\n              std::ostream&             model,\n              const hashpca::MatrixXd&  V,\n              const Eigen::VectorXd&    s,\n              const Eigen::VectorXd&    sum,\n              double                    n)\n    {\n      std::cerr << \"Writing model ... \";\n\n      model << V.rows () << \" \" << V.cols () - FUDGE << \" \" << options.hashall << std::endl;\n      model \n        << (options.dashq ? static_cast<unsigned char> (options.dashq[0]) : -1) \n        << \" \"\n        << (options.dashq ? static_cast<unsigned char> (options.dashq[1]) : -1) \n        << std::endl;\n\n      Eigen::IOFormat HeavyFmt (Eigen::FullPrecision);\n      model << s.reverse ().topRows (s.rows () - FUDGE).format (HeavyFmt) << std::endl;\n\n      Eigen::VectorXd mean;\n\n      if (options.center)\n        mean = (1.0 / n) * V.transpose () * sum;\n      else\n        mean = Eigen::VectorXd::Zero (V.cols ());\n\n      mean = mean.reverse ().eval ();\n\n      // http://forum.kde.org/viewtopic.php?f=74&t=107161\n\n      model.write ((char*) & mean (0), sizeof (double) * (mean.rows () - FUDGE));\n\n      for (unsigned int i = 0; i < V.rows (); ++i)\n        {\n          Eigen::VectorXd tmp = V.row (i).reverse ();\n          model.write ((char*) & tmp (0),\n                       sizeof (double) * (V.cols () - FUDGE));\n        }\n\n      std::cerr << \"done.\" << std::endl;\n\n      return 0;\n    }\n\n  char* \n  make_dashq (int a,\n              int b)\n    {\n      static char buf[3];\n\n      buf[0] = a;\n      buf[1] = b;\n      buf[2] = 0;\n\n      return buf;\n    }\n\n  int  \n  readmodel (PcaOptions&        options,\n             std::istream&      model,\n             hashpca::MatrixXd& V,\n             Eigen::VectorXd&   s,\n             Eigen::VectorXd&   mean)\n    {\n      model >> options.hashsize >> options.rank >> options.hashall;\n\n      int a;\n      int b;\n\n      model >> a >> b;\n\n      if (a >= 0 && b >= 0)\n        options.dashq = make_dashq (a, b);\n      else\n        options.dashq = 0;\n\n      s.resize (options.rank);\n      for (unsigned int i = 0; i < options.rank; ++i)\n        model >> s (i);\n\n      char newline;\n      model.read (&newline, 1);\n\n      mean.resize (options.rank);\n      model.read ((char*) & mean (0), sizeof (double) * options.rank);\n\n      Eigen::VectorXd tmp (options.rank);\n      V.resize (options.hashsize, options.rank);\n\n      for (unsigned int i = 0; i < V.rows (); ++i)\n        {\n          model.read ((char*) & tmp (0), sizeof (double) * options.rank);\n          V.row (i) = tmp;\n        }\n\n      return 0;\n    }\n\n  int\n  do_project_two (std::istream& in,\n                  PcaOptions    options,\n                  int           argc,\n                  char*         argv[])\n    {\n      (void) argc;\n\n      if (! in.good ())\n        {\n          std::cerr << \"ERROR: input is not good\" << std::endl;\n\n          return 1;\n        }\n\n      std::ifstream model (options.model);\n\n      if (! model.good ())\n        {\n          std::cerr << \"ERROR: failed to open file '\" \n                    << options.model << \"' for reading: \" \n                    << strerror (errno) << std::endl;\n          return 1;\n        }\n\n      hashpca::MatrixXd V;\n      Eigen::VectorXd s;\n      Eigen::VectorXd mean;\n\n      if (readmodel (options, model, V, s, mean))\n        {\n          std::cerr << \"ERROR: model file is corrupt or invalid.\" << std::endl;\n          return 1;\n        }\n\n      Eigen::VectorXd pinv = s.unaryExpr ([] (double x) { return 1.0 / (1e-6 + x); });\n\n      if (options.dashq)\n        {\n          BiLinearIterator it (options.hashsize,\n                               static_cast<unsigned char> (options.dashq[0]),\n                               static_cast<unsigned char> (options.dashq[1]));\n\n          return (options.hashall) \n            ? computeu<HashAll> (in, std::cout, V, mean, pinv, it, options)\n            : computeu<HashString> (in, std::cout, V, mean, pinv, it, options);\n        }\n      else\n        {\n          LinearIterator it (options.hashsize);\n\n          return (options.hashall)\n            ? computeu<HashAll> (in, std::cout, V, mean, pinv, it, options)\n            : computeu<HashString> (in, std::cout, V, mean, pinv, it, options);\n        }\n    }\n\n  int\n  do_project (PcaOptions    options,\n              int           argc,\n              char*         argv[])\n    {\n      if (argc < 1)\n        {\n          return do_project_two (std::cin, options, argc, argv);\n        }\n      else\n        {\n          std::ifstream in (argv[0]);\n\n          if (! in.good ())\n            {\n              std::cerr << \"ERROR: failed to open file '\" \n                        << argv[0] << \"' for reading: \" \n                        << strerror (errno) << std::endl;\n              return 1;\n            }\n\n          return do_project_two (in, options, argc, argv);\n        }\n    }\n\n  int\n  do_pca (PcaOptions    options,\n          int           argc,\n          char*         argv[])\n    {\n      std::ifstream in (argv[0]);\n\n      if (! in.good ())\n        {\n          std::cerr << \"ERROR: failed to open file '\" \n                    << argv[0] << \"' for reading: \" \n                    << strerror (errno) << std::endl;\n          return 1;\n        }\n\n      std::ifstream in2 (argv[argc > 1 ? 1 : 0]);\n\n      if (! in2.good ())\n        {\n          std::cerr << \"ERROR: failed to open file '\" \n                    << argv[argc > 1 ? 1 : 0] << \"' for reading: \" \n                    << strerror (errno) << std::endl;\n          return 1;\n        }\n\n      std::ofstream model (options.model);\n\n      if (! model.good ())\n        {\n          std::cerr << \"ERROR: failed to open file '\" \n                    << options.model << \"' for writing: \" \n                    << strerror (errno) << std::endl;\n          return 1;\n        }\n\n      options.rank += FUDGE;\n\n      hashpca::MatrixXd Y; Y.setZero (options.hashsize, options.rank);\n      hashpca::MatrixXd Omega =\n        hashpca::MatrixXd::Zero (options.hashsize, options.rank)\n          .unaryExpr (std::ptr_fun (gensample));\n      Eigen::VectorXd sum;\n\n      std::cerr << \"Processing examples ... \";\n      std::pair<double, uint64_t> lines1;\n\n      if (options.dashq)\n        {\n          BiLinearIterator it (options.hashsize,\n                               static_cast<unsigned char> (options.dashq[0]),\n                               static_cast<unsigned char> (options.dashq[1]));\n\n          lines1 = (options.hashall)\n            ? pca_accumulate<HashAll> (in, Y, Omega, it, options.center, sum)\n            : pca_accumulate<HashString> (in, Y, Omega, it, options.center, sum);\n        }\n      else\n        {\n          LinearIterator it (options.hashsize);\n\n          lines1 = (options.hashall)\n            ? pca_accumulate<HashAll> (in, Y, Omega, it, options.center, sum)\n            : pca_accumulate<HashString> (in, Y, Omega, it, options.center, sum);\n        }\n\n      std::cerr << \"(\" << lines1.first << \", \" \n                << lines1.second << \") done.\" << std::endl;\n\n      std::cerr << \"Orthogonalizing ... \";\n      orthonormalize (Y);\n      std::cerr << \"done.\" << std::endl;\n\n      std::cerr << \"Reprocessing examples ... \";\n      hashpca::MatrixXd& Z (Omega);\n      Z.setZero (Z.rows (), Z.cols ());\n\n      std::pair<double, uint64_t> lines2;\n\n      if (options.dashq)\n        {\n          BiLinearIterator it (options.hashsize,\n                               static_cast<unsigned char> (options.dashq[0]),\n                               static_cast<unsigned char> (options.dashq[1]));\n\n          lines2 = (options.hashall)\n            ? pca_accumulate<HashAll> (in2, Z, Y, it, options.center, sum)\n            : pca_accumulate<HashString> (in2, Z, Y, it, options.center, sum);\n        }\n      else\n        {\n          LinearIterator it (options.hashsize);\n\n          lines2 = (options.hashall)\n            ? pca_accumulate<HashAll> (in2, Z, Y, it, options.center, sum)\n            : pca_accumulate<HashString> (in2, Z, Y, it, options.center, sum);\n        }\n\n      std::cerr << \"(\" << lines2.first << \", \" \n                << lines2.second << \") done.\" << std::endl;\n\n      std::cerr << \"Small svding + postprocessing ... \";\n      hashpca::MatrixXd& V (Y);\n      Eigen::VectorXd s = smallsvd (Z, V);\n      std::cerr << \"done.\" << std::endl;\n\n      options.rank -= FUDGE;\n      return writemodel (options, model, V, s, sum, lines2.first);\n    }\n}\n\nint \nmain (int   argc,\n      char* argv[])\n{\n  std::ios::sync_with_stdio (false);\n\n  if (argc < 2)\n    {\n      std::cerr << help << std::endl;\n      return 1;\n    }\n\n  PcaOptions options = parse_pca_options (argc, argv);\n\n  if (! options.project && argc < 1)\n    {\n      std::cerr << \"ERROR: did not specify input file\\n\" << std::endl;\n      std::cerr << help << std::endl;\n      return 1;\n    }\n\n  if (! options.model)\n    {\n      std::cerr << \"ERROR: did not specify model file\\n\" << std::endl;\n      std::cerr << help << std::endl;\n      return 1;\n    }\n\n  return options.project ? do_project (options, argc, argv)\n                         : do_pca (options, argc, argv);\n}\n", "meta": {"hexsha": "ee7f329834737146c2117c28f33905452318552f", "size": 11628, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pca.cc", "max_stars_repo_name": "pmineiro/hashpca", "max_stars_repo_head_hexsha": "2cbe596d26bb38fae17a2c89ab9966c38ad569ee", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-04-01T10:28:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-02T12:22:45.000Z", "max_issues_repo_path": "pca.cc", "max_issues_repo_name": "pmineiro/hashpca", "max_issues_repo_head_hexsha": "2cbe596d26bb38fae17a2c89ab9966c38ad569ee", "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": "pca.cc", "max_forks_repo_name": "pmineiro/hashpca", "max_forks_repo_head_hexsha": "2cbe596d26bb38fae17a2c89ab9966c38ad569ee", "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.6199524941, "max_line_length": 92, "alphanum_fraction": 0.4939800482, "num_tokens": 3170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.25057414624159413}}
{"text": "/* Copyright (C) 2017 IBM Corp.\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, \n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n * either express or implied. See the License for the specific\n * language governing permissions and limitations under the License. \n */\n/*****************************************************************************\n * DGaussSampler.cpp - Sampling from non-spherical discrete Gaussian.\n *   A vector x is sampled one entry at a time, each entry sampled from\n *   the marginal distribution, conditioned on all previous entries.\n ******************************************************************************/\n#include <NTL/ZZ.h>\n#include <NTL/mat_lzz_p.h>\n#include <limits>\n#include <NTL/BasicThreadPool.h>\n#include <NTL/ZZ.h>\n#include <NTL/FFT.h>\n#include <NTL/SmartPtr.h>\n\nNTL_CLIENT\n#include \"mat_l.h\"\n#include \"vec_l.h\"\n#include \"DGaussSampler.h\"\n#include \"Gaussian1Dsampler.h\"\n#include \"utils/tools.h\"\n\n\n#ifdef NTL_HAVE_AVX\n#warning \"HAVE_AVX\"\n\n#include <immintrin.h>\n\n#ifdef NTL_HAVE_FMA\n#define MUL_ADD(a, b, c) a = _mm256_fmadd_pd(b, c, a)\n#else\n#define MUL_ADD(a, b, c) a = _mm256_add_pd(a, _mm256_mul_pd(b, c))\n#endif\n#endif\n\n// Choose a small dimension-n integer vector\nvoid setSmall(vec_l& u, long n, double sigma)\n{\n    FHE_TIMER_START;\n    u.SetLength(n);\n    NTL::Pair<bool,long> extra(false,0);\n\n    // Choose a small noise vector\n    Gaussian1Dsampler gSampler(sigma);\n    for (long i=0; i<n; i++)\n      u[i] = gSampler.getSample(/*mu=*/0.0, extra);\n}\n\n\n// Choose a small n-by-m integer matrix\nvoid setSmall(mat_l& E, long n, long m, double sigma)\n{\n    FHE_TIMER_START;\n    E.SetDims(n, m); // the noise n-by-m matrix E\n\n    // Choose a small noise matrix\n    Gaussian1Dsampler gSampler(sigma);\n\n    EXEC_RANGE(m, first, last)\n\n    NTL::Pair<bool,long> extra(false,0);\n    for (long j=first; j<last; j++)\n    for (long i=0; i<n; i++){\n        //for (long j=0; j<m; j++){\n\tE[i][j] = gSampler.getSample(/*mu=*/0.0, extra);\n      }\n      EXEC_RANGE_END\n}\n\n\n// Initialize to a convariance matrix, returns false on failure. The i'th\n// vector in condSigmaV is the top row of the conditional covariance matrix\n// of entries i,...,n ocnditioned on 1,...,i-1. Also initializes a 1D sample\n// with variance condSigmaV[i][i] for each entry i.\n\n\n#ifdef NTL_HAVE_AVX\n// ******* AVX code\n// Most of this was taken verbatim from NTL's mat_lzz_p.c\n\n#define MAT_BLK_SZ (32)\n\n\n#define PAR_THRESH_SQ (200)\n#define PAR_THRESH (40000)\n\n\n// MUL_ADD(a, b, c): a += b*c\n#ifdef NTL_HAVE_FMA\n#define MUL_ADD(a, b, c) a = _mm256_fmadd_pd(b, c, a)\n#else\n#define MUL_ADD(a, b, c) a = _mm256_add_pd(a, _mm256_mul_pd(b, c))\n#endif\n\n\n\nstatic\nvoid muladd1_by_32(double *x, const double *a, const double *b, long n)\n{\n   __m256d acc0=_mm256_load_pd(x + 0*4);\n   __m256d acc1=_mm256_load_pd(x + 1*4);\n   __m256d acc2=_mm256_load_pd(x + 2*4);\n   __m256d acc3=_mm256_load_pd(x + 3*4);\n   __m256d acc4=_mm256_load_pd(x + 4*4);\n   __m256d acc5=_mm256_load_pd(x + 5*4);\n   __m256d acc6=_mm256_load_pd(x + 6*4);\n   __m256d acc7=_mm256_load_pd(x + 7*4);\n\n   long i = 0;\n   for (; i <= n-4; i +=4) {\n\n      // the following code sequences are a bit faster than\n      // just doing 4 _mm256_broadcast_sd's\n      // it requires a to point to aligned storage, however\n\n     // this one seems slightly faster\n      __m256d a0101 = _mm256_broadcast_pd((const __m128d*)(a+0));\n      __m256d a2323 = _mm256_broadcast_pd((const __m128d*)(a+2));\n\n\n      __m256d avec0 = _mm256_permute_pd(a0101, 0);\n      __m256d avec1 = _mm256_permute_pd(a0101, 0xf);\n      __m256d avec2 = _mm256_permute_pd(a2323, 0);\n      __m256d avec3 = _mm256_permute_pd(a2323, 0xf);\n\n      a += 4;\n\n      __m256d bvec;\n\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc0, avec0, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc1, avec0, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc2, avec0, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc3, avec0, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc4, avec0, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc5, avec0, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc6, avec0, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc7, avec0, bvec);\n\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc0, avec1, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc1, avec1, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc2, avec1, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc3, avec1, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc4, avec1, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc5, avec1, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc6, avec1, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc7, avec1, bvec);\n\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc0, avec2, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc1, avec2, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc2, avec2, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc3, avec2, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc4, avec2, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc5, avec2, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc6, avec2, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc7, avec2, bvec);\n\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc0, avec3, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc1, avec3, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc2, avec3, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc3, avec3, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc4, avec3, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc5, avec3, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc6, avec3, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc7, avec3, bvec);\n   }\n\n   for (; i < n; i++) {\n      __m256d avec = _mm256_broadcast_sd(a); a++;\n      __m256d bvec;\n\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc0, avec, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc1, avec, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc2, avec, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc3, avec, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc4, avec, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc5, avec, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc6, avec, bvec);\n      bvec = _mm256_load_pd(b); b += 4; MUL_ADD(acc7, avec, bvec);\n   }\n\n\n   _mm256_store_pd(x + 0*4, acc0);\n   _mm256_store_pd(x + 1*4, acc1);\n   _mm256_store_pd(x + 2*4, acc2);\n   _mm256_store_pd(x + 3*4, acc3);\n   _mm256_store_pd(x + 4*4, acc4);\n   _mm256_store_pd(x + 5*4, acc5);\n   _mm256_store_pd(x + 6*4, acc6);\n   _mm256_store_pd(x + 7*4, acc7);\n}\n\n// experiment: process two rows at a time\n#ifndef NTL_HAVE_FMA\nstatic\nvoid muladd2_by_32(double *x, const double *a, const double *b, long n)\n{\n   __m256d avec0, avec1, bvec;\n   __m256d acc00, acc01, acc02, acc03;\n   __m256d acc10, acc11, acc12, acc13;\n\n   // round 0\n\n   acc00=_mm256_load_pd(x + 0*4 + 0*MAT_BLK_SZ);\n   acc01=_mm256_load_pd(x + 1*4 + 0*MAT_BLK_SZ);\n   acc02=_mm256_load_pd(x + 2*4 + 0*MAT_BLK_SZ);\n   acc03=_mm256_load_pd(x + 3*4 + 0*MAT_BLK_SZ);\n\n   acc10=_mm256_load_pd(x + 0*4 + 1*MAT_BLK_SZ);\n   acc11=_mm256_load_pd(x + 1*4 + 1*MAT_BLK_SZ);\n   acc12=_mm256_load_pd(x + 2*4 + 1*MAT_BLK_SZ);\n   acc13=_mm256_load_pd(x + 3*4 + 1*MAT_BLK_SZ);\n\n   for (long i = 0; i < n; i++) {\n      avec0 = _mm256_broadcast_sd(&a[i]);\n      avec1 = _mm256_broadcast_sd(&a[i+MAT_BLK_SZ]);\n\n      bvec = _mm256_load_pd(&b[i*MAT_BLK_SZ+0*4]); MUL_ADD(acc00, avec0, bvec); MUL_ADD(acc10, avec1, bvec);\n      bvec = _mm256_load_pd(&b[i*MAT_BLK_SZ+1*4]); MUL_ADD(acc01, avec0, bvec); MUL_ADD(acc11, avec1, bvec);\n      bvec = _mm256_load_pd(&b[i*MAT_BLK_SZ+2*4]); MUL_ADD(acc02, avec0, bvec); MUL_ADD(acc12, avec1, bvec);\n      bvec = _mm256_load_pd(&b[i*MAT_BLK_SZ+3*4]); MUL_ADD(acc03, avec0, bvec); MUL_ADD(acc13, avec1, bvec);\n   }\n\n\n   _mm256_store_pd(x + 0*4 + 0*MAT_BLK_SZ, acc00);\n   _mm256_store_pd(x + 1*4 + 0*MAT_BLK_SZ, acc01);\n   _mm256_store_pd(x + 2*4 + 0*MAT_BLK_SZ, acc02);\n   _mm256_store_pd(x + 3*4 + 0*MAT_BLK_SZ, acc03);\n\n   _mm256_store_pd(x + 0*4 + 1*MAT_BLK_SZ, acc10);\n   _mm256_store_pd(x + 1*4 + 1*MAT_BLK_SZ, acc11);\n   _mm256_store_pd(x + 2*4 + 1*MAT_BLK_SZ, acc12);\n   _mm256_store_pd(x + 3*4 + 1*MAT_BLK_SZ, acc13);\n\n   // round 1\n\n   acc00=_mm256_load_pd(x + 4*4 + 0*MAT_BLK_SZ);\n   acc01=_mm256_load_pd(x + 5*4 + 0*MAT_BLK_SZ);\n   acc02=_mm256_load_pd(x + 6*4 + 0*MAT_BLK_SZ);\n   acc03=_mm256_load_pd(x + 7*4 + 0*MAT_BLK_SZ);\n\n   acc10=_mm256_load_pd(x + 4*4 + 1*MAT_BLK_SZ);\n   acc11=_mm256_load_pd(x + 5*4 + 1*MAT_BLK_SZ);\n   acc12=_mm256_load_pd(x + 6*4 + 1*MAT_BLK_SZ);\n   acc13=_mm256_load_pd(x + 7*4 + 1*MAT_BLK_SZ);\n\n   for (long i = 0; i < n; i++) {\n      avec0 = _mm256_broadcast_sd(&a[i]);\n      avec1 = _mm256_broadcast_sd(&a[i+MAT_BLK_SZ]);\n\n      bvec = _mm256_load_pd(&b[i*MAT_BLK_SZ+0*4+MAT_BLK_SZ/2]); MUL_ADD(acc00, avec0, bvec); MUL_ADD(acc10, avec1, bvec);\n      bvec = _mm256_load_pd(&b[i*MAT_BLK_SZ+1*4+MAT_BLK_SZ/2]); MUL_ADD(acc01, avec0, bvec); MUL_ADD(acc11, avec1, bvec);\n      bvec = _mm256_load_pd(&b[i*MAT_BLK_SZ+2*4+MAT_BLK_SZ/2]); MUL_ADD(acc02, avec0, bvec); MUL_ADD(acc12, avec1, bvec);\n      bvec = _mm256_load_pd(&b[i*MAT_BLK_SZ+3*4+MAT_BLK_SZ/2]); MUL_ADD(acc03, avec0, bvec); MUL_ADD(acc13, avec1, bvec);\n   }\n\n\n   _mm256_store_pd(x + 4*4 + 0*MAT_BLK_SZ, acc00);\n   _mm256_store_pd(x + 5*4 + 0*MAT_BLK_SZ, acc01);\n   _mm256_store_pd(x + 6*4 + 0*MAT_BLK_SZ, acc02);\n   _mm256_store_pd(x + 7*4 + 0*MAT_BLK_SZ, acc03);\n\n   _mm256_store_pd(x + 4*4 + 1*MAT_BLK_SZ, acc10);\n   _mm256_store_pd(x + 5*4 + 1*MAT_BLK_SZ, acc11);\n   _mm256_store_pd(x + 6*4 + 1*MAT_BLK_SZ, acc12);\n   _mm256_store_pd(x + 7*4 + 1*MAT_BLK_SZ, acc13);\n\n}\n#endif\n\n// experiment: process three rows at a time\n// NOTE: this makes things slower on an AVX1 platform --- not enough registers\n// it could be faster on AVX2/FMA, where there should be enough registers\n\nstatic\nvoid muladd3_by_32(double *x, const double *a, const double *b, long n)\n{\n   __m256d avec0, avec1, avec2, bvec;\n   __m256d acc00, acc01, acc02, acc03;\n   __m256d acc10, acc11, acc12, acc13;\n   __m256d acc20, acc21, acc22, acc23;\n\n\n   // round 0\n\n   acc00=_mm256_load_pd(x + 0*4 + 0*MAT_BLK_SZ);\n   acc01=_mm256_load_pd(x + 1*4 + 0*MAT_BLK_SZ);\n   acc02=_mm256_load_pd(x + 2*4 + 0*MAT_BLK_SZ);\n   acc03=_mm256_load_pd(x + 3*4 + 0*MAT_BLK_SZ);\n\n   acc10=_mm256_load_pd(x + 0*4 + 1*MAT_BLK_SZ);\n   acc11=_mm256_load_pd(x + 1*4 + 1*MAT_BLK_SZ);\n   acc12=_mm256_load_pd(x + 2*4 + 1*MAT_BLK_SZ);\n   acc13=_mm256_load_pd(x + 3*4 + 1*MAT_BLK_SZ);\n\n   acc20=_mm256_load_pd(x + 0*4 + 2*MAT_BLK_SZ);\n   acc21=_mm256_load_pd(x + 1*4 + 2*MAT_BLK_SZ);\n   acc22=_mm256_load_pd(x + 2*4 + 2*MAT_BLK_SZ);\n   acc23=_mm256_load_pd(x + 3*4 + 2*MAT_BLK_SZ);\n\n   for (long i = 0; i < n; i++) {\n      avec0 = _mm256_broadcast_sd(&a[i]);\n      avec1 = _mm256_broadcast_sd(&a[i+MAT_BLK_SZ]);\n      avec2 = _mm256_broadcast_sd(&a[i+2*MAT_BLK_SZ]);\n\n      bvec = _mm256_load_pd(&b[i*MAT_BLK_SZ+0*4]); MUL_ADD(acc00, avec0, bvec); MUL_ADD(acc10, avec1, bvec); MUL_ADD(acc20, avec2, bvec);\n      bvec = _mm256_load_pd(&b[i*MAT_BLK_SZ+1*4]); MUL_ADD(acc01, avec0, bvec); MUL_ADD(acc11, avec1, bvec); MUL_ADD(acc21, avec2, bvec);\n      bvec = _mm256_load_pd(&b[i*MAT_BLK_SZ+2*4]); MUL_ADD(acc02, avec0, bvec); MUL_ADD(acc12, avec1, bvec); MUL_ADD(acc22, avec2, bvec);\n      bvec = _mm256_load_pd(&b[i*MAT_BLK_SZ+3*4]); MUL_ADD(acc03, avec0, bvec); MUL_ADD(acc13, avec1, bvec); MUL_ADD(acc23, avec2, bvec);\n   }\n\n\n   _mm256_store_pd(x + 0*4 + 0*MAT_BLK_SZ, acc00);\n   _mm256_store_pd(x + 1*4 + 0*MAT_BLK_SZ, acc01);\n   _mm256_store_pd(x + 2*4 + 0*MAT_BLK_SZ, acc02);\n   _mm256_store_pd(x + 3*4 + 0*MAT_BLK_SZ, acc03);\n\n   _mm256_store_pd(x + 0*4 + 1*MAT_BLK_SZ, acc10);\n   _mm256_store_pd(x + 1*4 + 1*MAT_BLK_SZ, acc11);\n   _mm256_store_pd(x + 2*4 + 1*MAT_BLK_SZ, acc12);\n   _mm256_store_pd(x + 3*4 + 1*MAT_BLK_SZ, acc13);\n\n   _mm256_store_pd(x + 0*4 + 2*MAT_BLK_SZ, acc20);\n   _mm256_store_pd(x + 1*4 + 2*MAT_BLK_SZ, acc21);\n   _mm256_store_pd(x + 2*4 + 2*MAT_BLK_SZ, acc22);\n   _mm256_store_pd(x + 3*4 + 2*MAT_BLK_SZ, acc23);\n\n   // round 1\n\n   acc00=_mm256_load_pd(x + 4*4 + 0*MAT_BLK_SZ);\n   acc01=_mm256_load_pd(x + 5*4 + 0*MAT_BLK_SZ);\n   acc02=_mm256_load_pd(x + 6*4 + 0*MAT_BLK_SZ);\n   acc03=_mm256_load_pd(x + 7*4 + 0*MAT_BLK_SZ);\n\n   acc10=_mm256_load_pd(x + 4*4 + 1*MAT_BLK_SZ);\n   acc11=_mm256_load_pd(x + 5*4 + 1*MAT_BLK_SZ);\n   acc12=_mm256_load_pd(x + 6*4 + 1*MAT_BLK_SZ);\n   acc13=_mm256_load_pd(x + 7*4 + 1*MAT_BLK_SZ);\n\n   acc20=_mm256_load_pd(x + 4*4 + 2*MAT_BLK_SZ);\n   acc21=_mm256_load_pd(x + 5*4 + 2*MAT_BLK_SZ);\n   acc22=_mm256_load_pd(x + 6*4 + 2*MAT_BLK_SZ);\n   acc23=_mm256_load_pd(x + 7*4 + 2*MAT_BLK_SZ);\n\n   for (long i = 0; i < n; i++) {\n      avec0 = _mm256_broadcast_sd(&a[i]);\n      avec1 = _mm256_broadcast_sd(&a[i+MAT_BLK_SZ]);\n      avec2 = _mm256_broadcast_sd(&a[i+2*MAT_BLK_SZ]);\n\n      bvec = _mm256_load_pd(&b[i*MAT_BLK_SZ+0*4+MAT_BLK_SZ/2]); MUL_ADD(acc00, avec0, bvec); MUL_ADD(acc10, avec1, bvec); MUL_ADD(acc20, avec2, bvec);\n      bvec = _mm256_load_pd(&b[i*MAT_BLK_SZ+1*4+MAT_BLK_SZ/2]); MUL_ADD(acc01, avec0, bvec); MUL_ADD(acc11, avec1, bvec); MUL_ADD(acc21, avec2, bvec);\n      bvec = _mm256_load_pd(&b[i*MAT_BLK_SZ+2*4+MAT_BLK_SZ/2]); MUL_ADD(acc02, avec0, bvec); MUL_ADD(acc12, avec1, bvec); MUL_ADD(acc22, avec2, bvec);\n      bvec = _mm256_load_pd(&b[i*MAT_BLK_SZ+3*4+MAT_BLK_SZ/2]); MUL_ADD(acc03, avec0, bvec); MUL_ADD(acc13, avec1, bvec); MUL_ADD(acc23, avec2, bvec);\n   }\n\n\n   _mm256_store_pd(x + 4*4 + 0*MAT_BLK_SZ, acc00);\n   _mm256_store_pd(x + 5*4 + 0*MAT_BLK_SZ, acc01);\n   _mm256_store_pd(x + 6*4 + 0*MAT_BLK_SZ, acc02);\n   _mm256_store_pd(x + 7*4 + 0*MAT_BLK_SZ, acc03);\n\n   _mm256_store_pd(x + 4*4 + 1*MAT_BLK_SZ, acc10);\n   _mm256_store_pd(x + 5*4 + 1*MAT_BLK_SZ, acc11);\n   _mm256_store_pd(x + 6*4 + 1*MAT_BLK_SZ, acc12);\n   _mm256_store_pd(x + 7*4 + 1*MAT_BLK_SZ, acc13);\n\n   _mm256_store_pd(x + 4*4 + 2*MAT_BLK_SZ, acc20);\n   _mm256_store_pd(x + 5*4 + 2*MAT_BLK_SZ, acc21);\n   _mm256_store_pd(x + 6*4 + 2*MAT_BLK_SZ, acc22);\n   _mm256_store_pd(x + 7*4 + 2*MAT_BLK_SZ, acc23);\n\n}\n\n\nstatic inline\nvoid muladd_all_by_32(long first, long last, double *x, const double *a, const double *b, long n)\n{\n   long i = first;\n#ifdef NTL_HAVE_FMA\n   // processing three rows at a time is faster\n   for (; i <= last-3; i+=3)\n      muladd3_by_32(x + i*MAT_BLK_SZ, a + i*MAT_BLK_SZ, b, n);\n   for (; i < last; i++)\n      muladd1_by_32(x + i*MAT_BLK_SZ, a + i*MAT_BLK_SZ, b, n);\n#else\n   // process only two rows at a time: not enough registers :-(\n   for (; i <= last-2; i+=2)\n      muladd2_by_32(x + i*MAT_BLK_SZ, a + i*MAT_BLK_SZ, b, n);\n   for (; i < last; i++)\n      muladd1_by_32(x + i*MAT_BLK_SZ, a + i*MAT_BLK_SZ, b, n);\n#endif\n}\n\n// this assumes n is a multiple of 16\nstatic inline\nvoid muladd_interval(double * NTL_RESTRICT x, double * NTL_RESTRICT y, double c, long n)\n{\n   __m256d xvec0, xvec1, xvec2, xvec3;\n   __m256d yvec0, yvec1, yvec2, yvec3;\n\n   __m256d cvec = _mm256_broadcast_sd(&c);\n\n   for (long i = 0; i < n; i += 16, x += 16, y += 16) {\n      xvec0 = _mm256_load_pd(x+0*4);\n      xvec1 = _mm256_load_pd(x+1*4);\n      xvec2 = _mm256_load_pd(x+2*4);\n      xvec3 = _mm256_load_pd(x+3*4);\n\n      yvec0 = _mm256_load_pd(y+0*4);\n      yvec1 = _mm256_load_pd(y+1*4);\n      yvec2 = _mm256_load_pd(y+2*4);\n      yvec3 = _mm256_load_pd(y+3*4);\n\n      MUL_ADD(xvec0, yvec0, cvec);\n      MUL_ADD(xvec1, yvec1, cvec);\n      MUL_ADD(xvec2, yvec2, cvec);\n      MUL_ADD(xvec3, yvec3, cvec);\n\n      _mm256_store_pd(x + 0*4, xvec0);\n      _mm256_store_pd(x + 1*4, xvec1);\n      _mm256_store_pd(x + 2*4, xvec2);\n      _mm256_store_pd(x + 3*4, xvec3);\n   }\n}\n\n\nstatic\nbool Alt_sampler(Vec< Vec<double> >& X, const Mat<long>& A)\n{\n   FHE_TIMER_START;\n\n   long n = A.NumRows();\n\n   if (A.NumCols() != n)\n      LogicError(\"sampler: nonsquare matrix\");\n\n   if (NTL_OVERFLOW(n, MAT_BLK_SZ, 0)) ResourceError(\"dimension too large\");\n\n   long npanels = (n+MAT_BLK_SZ-1)/MAT_BLK_SZ;\n\n   Vec< AlignedArray<double> > M;\n   M.SetLength(npanels);\n   for (long panel = 0; panel < npanels; panel++) {\n      M[panel].SetLength(n*MAT_BLK_SZ);\n      double *panelp = &M[panel][0];\n\n      for (long r = 0; r < n*MAT_BLK_SZ; r++) panelp[r] = 0;\n   }\n\n   // copy A into panels\n   for (long jj = 0, panel = 0; jj < n; jj += MAT_BLK_SZ, panel++) {\n      long j_max = min(jj+MAT_BLK_SZ, n);\n      double *panelp = &M[panel][0];\n\n      for (long i = 0; i < n; i++, panelp += MAT_BLK_SZ) {\n         const long *ap = A[i].elts() + jj;\n\n         for (long j = jj; j < j_max; j++)\n            panelp[j-jj] = ap[j-jj];\n      }\n   }\n\n   X.SetLength(n);\n\n   for (long kk = 0, kpanel = 0; kk < n; kk += MAT_BLK_SZ, kpanel++) {\n      long k_max = min(kk+MAT_BLK_SZ, n);\n\n      double * NTL_RESTRICT kpanelp = &M[kpanel][0];\n\n      for (long k = kk; k < k_max; k++) {\n\n         X[k].SetLength(n-k);\n         double * NTL_RESTRICT Xk = X[k].elts();\n         for (long i = k; i < n; i++)\n            Xk[i-k] = kpanelp[i*MAT_BLK_SZ + (k-kk)];\n\n         double * NTL_RESTRICT y = &kpanelp[k*MAT_BLK_SZ];\n         double pivot = y[k-kk];\n         y[k-kk] = 1;\n\n         if (pivot <= 0) {\n            return false;\n         }\n\n         double pivot_inv = 1/pivot;\n\n         for (long i = k+1; i < n; i++) {\n            double * NTL_RESTRICT x = &kpanelp[i*MAT_BLK_SZ];\n            double t1 = -x[k-kk]*pivot_inv;\n            x[k-kk] = 0;\n            muladd_interval(x, y, t1, MAT_BLK_SZ);\n         }\n\n         for (long j = k; j < k_max; j++) y[j-kk] = 0;\n      }\n\n\n      // finished processing current kpanel\n      // next, reduce and apply to all other kpanels\n\n      bool seq = double(npanels-(kpanel+1))*double(n)*double(MAT_BLK_SZ)*double(MAT_BLK_SZ) < PAR_THRESH;\n\n      NTL_GEXEC_RANGE(seq, npanels-(kpanel+1), first, last)\n      NTL_IMPORT(n)\n      NTL_IMPORT(kpanel)\n      NTL_IMPORT(kpanelp)\n      NTL_IMPORT(kk)\n      NTL_IMPORT(k_max)\n\n      AlignedArray<double> buf_store;\n      buf_store.SetLength(MAT_BLK_SZ*MAT_BLK_SZ);\n      double *buf = &buf_store[0];\n\n      for (long index = first; index < last; index++) {\n         long jpanel = index + kpanel+1;\n\n         double * NTL_RESTRICT jpanelp = &M[jpanel][0];\n\n         // copy block number kpanel (the one on the diagonal)  into buf\n\n         for (long i = 0; i < (k_max-kk)*MAT_BLK_SZ; i++)\n            buf[i] = jpanelp[kk*MAT_BLK_SZ+i];\n\n         // jpanel += kpanel*buf\n\n         muladd_all_by_32(kk, n, jpanelp, kpanelp, buf, k_max-kk);\n      }\n\n      NTL_GEXEC_RANGE_END\n\n   }\n\n   return true;\n\n}\n#endif\n\n//create the nested covariance matrices\nstatic\nbool Plain_sampler(Vec< Vec<double> >& X, const Mat<long>& A)\n{\n    FHE_TIMER_START;\n\n    if (A[0][0] < 0)   //sigma too small\n    {\n        return false; // failed, variance cannot be negative\n    }\n\n    long n = A.NumRows();\n\n    if (A.NumCols() != n)\n       LogicError(\"sampler: nonsquare matrix\");\n\n    X.SetLength(n); // allocate space for n vectors\n\n    Mat<double> M;\n    conv(M, A); // convert to floating point\n\n    // 1st vector of the conditional covariance = 1st column of covariance\n    X[0].SetLength(n);\n    for (long k = 0; k < n; k++)\n        X[0][k] = M[k][0];\n\n    // Compute the rest of the conditional covariance, one vector at a time\n\n\n    for (long k = 1; k<n; k++)\n    {\n        // create the new covariance: sig y|x = sig_yy - sig_yx *sig_xx^{-1} *sig_xy\n\n\n        //get the subset covariance matrix\n\n        NTL_GEXEC_RANGE(n-k < 100, n-k, first, last)\n\n        NTL_IMPORT(n)\n        NTL_IMPORT(k)\n\n        double * NTL_RESTRICT M_0 = &M[k-1][0];\n        double pivot = M_0[k-1];\n        double pivot_inv = 1.0/pivot;\n\n        for (long row = first; row < last; row++) {\n            double * NTL_RESTRICT M_r = &M[k+row][0];\n            double fac = -M_r[k-1]*pivot_inv;\n\n            for (long col = k; col < n; col++) {\n                M_r[col] += fac * (M_0[col]);\n            }\n        }\n\n        NTL_GEXEC_RANGE_END\n\n        if (M[k][k] < 0)\n        {\n            return false; //failed, sigma too small\n        }\n\n        // copy the result to the next conditional covariance vector\n        X[k].SetLength(n-k);\n        for (long i = 0; i < n-k; i++)\n            X[k][i] = M[k+i][k];\n    }\n\n    return true;\n}\n\n\n\nbool DiscreteGaussianSampler::InitSampler(const Mat<long> &covMat)\n{\n    FHE_TIMER_START;\n\n    n = covMat.NumRows();\n\n    bool res = false;\n\n#ifdef NTL_HAVE_AVX\n#warning \"using AVX code\"\n   if (n >= 512) {\n      res = Alt_sampler(condSigmaV, covMat);\n   }\n   else\n#endif\n   {\n      res = Plain_sampler(condSigmaV, covMat);\n   }\n\n   if (!res) return false;\n\n    //clear if there are previous 1D-samplers\n    for (long i = 0; i < oneDsamplers.length(); i++)\n        if (oneDsamplers[i] != NULL) delete oneDsamplers[i];\n\n    // create table of 1D-samplers\n    oneDsamplers.SetLength(n);\n\n    for (long iVar=0; iVar<n; iVar++)\n    {\n        if (condSigmaV[iVar][0] < 0)\n        {\n            cout << \"conditional sigma too small\" << endl;\n            return false; //conditional sigma too small\n            }\n\n        oneDsamplers[iVar] =            //create a 1D sampler for this sigma\n        (Gaussian1Dsampler*) new Gaussian1Dsampler(sqrt(condSigmaV[iVar][0]));\n\n    }\n\n    return true;\n}\n\n\n\n// FIXME: better to use UniquePtr or something to manage the entries\n// in oneDsamplers, rather than new/delete\n\n\n//delete the array of sampler instances\nDiscreteGaussianSampler::~DiscreteGaussianSampler()\n{\n    FHE_TIMER_START;\n    for (long i = 0; i < oneDsamplers.length(); i++)\n        if (oneDsamplers[i]) delete oneDsamplers[i];\n}\n\n// Discrete sampling according to the conditional variance and mean. Choose\n//each entry in x depending on the conditioned distribution of previous ones.\n\nvoid DiscreteGaussianSampler::SampleDiscreteGaussian(vec_l& xOut, const Vec<double>& meanVec) const\n{\n    FHE_TIMER_START;\n\n    //for this val, find the rest of the values\n\n    //x,y are matrices\n    //m y|x = m_y + sig_yx * sig ^-1_xx (x - m_x)\n    //multiple matrices\n\n    // scratch variables for internal computation\n    Vec<double> marginalMeanVec = meanVec;\n    Vec<double> nextMarginalMeanVec;\n\n    // work with pointers for easier swapping\n    Vec<double>* curMeanVec = &marginalMeanVec;\n    Vec<double>* nextMeanVec = &nextMarginalMeanVec;\n\n    //find marginal distribution for each variable\n\n    xOut.SetLength(n);\n    for (long iVar = 0; iVar<n; iVar++)\n    {\n        //get the next sample\n        double mean = (*curMeanVec)[0];\n        xOut[iVar] = oneDsamplers[iVar]->getSample(mean);\n\n        // update the mean vector:\n        //    m(i|j) = m(i) + sigma(i,j)*sigma(j,j)^-1*(x(j) - m(j))\n        // only need the first element for the next item\n\n        // Next mean vector has one dimension less\n        nextMeanVec->SetLength(curMeanVec->length() -1);\n\n        double diff = xOut[iVar] - mean;  // deviation from mean\n\n        // Look at the next vector from the conditional covariance\n        const Vec<double>& covVec = condSigmaV[iVar];\n\n        // newMean = curMean[1..n-1] + covVec * diff / sigma_XX\n\n        double invSig = 1.0 / covVec[0]; // 1/sigma_XX\n        for (long row = 0; row<nextMeanVec->length(); row++)\n            (*nextMeanVec)[row]\n                = (*curMeanVec)[row+1] + (covVec[row+1] *invSig) *diff;\n\n        // Set the updated mean vector as the current one\n        swap(nextMeanVec,curMeanVec); // pointer swap\n    }\n}\n\n\n\nlong DiscreteGaussianSampler::writeToFile(FILE* handle)\n{\n    FHE_TIMER_START;\n    long count = fwrite(&n,sizeof(long),1,handle); // write dimension\n\n    long nConvSig = condSigmaV.length();\n    count += fwrite(&nConvSig,sizeof(long),1,handle);\n\n    for (long i = 0; i < nConvSig; i++)\n    {\n    long nconvSigmaVi = condSigmaV[i].length();\n    count += fwrite(&nconvSigmaVi,sizeof(long),1,handle);\n    count += fwrite(condSigmaV[i].elts(),condSigmaV[i].length()*sizeof(double),1,handle);\n    }\n\n    long oLength = oneDsamplers.length();\n    count += fwrite(&oLength,sizeof(long),1,handle);\n\n\n    for (long i = 0; i < oLength; i++)\n        count+= oneDsamplers[i]->writeToFile(handle);\n\n    return count;\n}\n\nlong DiscreteGaussianSampler::readFromFile(FILE* handle)\n{\n    FHE_TIMER_START;\n    long count = fread(&n,sizeof(long),1,handle); // read dimension\n\n    long nConvSig;\n    count += fread(&nConvSig,sizeof(long),1,handle);\n\n    condSigmaV.SetLength(nConvSig);\n\n    for (long i = 0; i < nConvSig; i++)\n    {\n    long nconvSigmaVi;\n    count += fread(&nconvSigmaVi,sizeof(long),1,handle);\n    condSigmaV[i].SetLength(nconvSigmaVi);\n    count += fread(condSigmaV[i].elts(),nconvSigmaVi*sizeof(double),1,handle);\n    }\n\n    long oLength;\n    count += fread(&oLength,sizeof(long),1,handle);\n    oneDsamplers.SetLength(oLength);\n\n    for (long iVar=0; iVar<oLength; iVar++)\n    {\n        oneDsamplers[iVar] =            //create a 1D sampler for this sigma\n            (Gaussian1Dsampler*) new Gaussian1Dsampler(sqrt(condSigmaV[iVar][0]));\n    }\n\n    for (long i = 0; i < oLength; i++)\n        count+= oneDsamplers[i]->readFromFile(handle);\n\n    return count;\n}\n", "meta": {"hexsha": "671fbc25bb2e909ea8460d5b24221391f2b6e29b", "size": 25588, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DGaussSampler.cpp", "max_stars_repo_name": "shaih/BPobfus", "max_stars_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-09-25T14:37:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-11T03:19:43.000Z", "max_issues_repo_path": "DGaussSampler.cpp", "max_issues_repo_name": "shaih/BPobfus", "max_issues_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "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": "DGaussSampler.cpp", "max_forks_repo_name": "shaih/BPobfus", "max_forks_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-12-23T04:03:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-12T07:42:29.000Z", "avg_line_length": 32.3898734177, "max_line_length": 150, "alphanum_fraction": 0.6236907926, "num_tokens": 9028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.250574139356132}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_OB_TRAN_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_OB_TRAN_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 <boost/shared_ptr.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#include <boost/geometry/extensions/gis/projections/impl/aasincos.hpp>\n\nnamespace boost { namespace geometry { namespace projections\n{\n\n    template <typename Geographic, typename Cartesian, typename Parameters> class factory;\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace ob_tran\n    {\n\n            static const double TOL = 1e-10;\n\n            template <typename Geographic, typename Cartesian>\n            struct par_ob_tran\n            {\n                boost::shared_ptr<projection<Geographic, Cartesian> > link;\n                double    lamp;\n                double    cphip, sphip;\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename Geographic, typename Cartesian, typename Parameters>\n            struct base_ob_tran_oblique : public base_t_fi<base_ob_tran_oblique<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>\n            {\n\n                 typedef double geographic_type;\n                 typedef double cartesian_type;\n\n                par_ob_tran<Geographic, Cartesian> m_proj_parm;\n\n                inline base_ob_tran_oblique(const Parameters& par)\n                    : base_t_fi<base_ob_tran_oblique<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>(*this, par) {}\n\n                // FORWARD(o_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 coslam, sinphi, cosphi;\n\n\n                    coslam = cos(lp_lon);\n                    sinphi = sin(lp_lat);\n                    cosphi = cos(lp_lat);\n                    lp_lon = adjlon(aatan2(cosphi * sin(lp_lon), this->m_proj_parm.sphip * cosphi * coslam +\n                        this->m_proj_parm.cphip * sinphi) + this->m_proj_parm.lamp);\n                    lp_lat = aasin(this->m_proj_parm.sphip * sinphi - this->m_proj_parm.cphip * cosphi * coslam);\n                    m_proj_parm.link->fwd(lp_lon, lp_lat, xy_x, xy_y);\n                }\n\n                // INVERSE(o_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 coslam, sinphi, cosphi;\n\n                    m_proj_parm.link->inv(xy_x, xy_y, lp_lon, lp_lat);\n                    if (lp_lon != HUGE_VAL) {\n                        coslam = cos(lp_lon -= this->m_proj_parm.lamp);\n                        sinphi = sin(lp_lat);\n                        cosphi = cos(lp_lat);\n                        lp_lat = aasin(this->m_proj_parm.sphip * sinphi + this->m_proj_parm.cphip * cosphi * coslam);\n                        lp_lon = aatan2(cosphi * sin(lp_lon), this->m_proj_parm.sphip * cosphi * coslam -\n                            this->m_proj_parm.cphip * sinphi);\n                    }\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"ob_tran_oblique\";\n                }\n\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename Geographic, typename Cartesian, typename Parameters>\n            struct base_ob_tran_transverse : public base_t_fi<base_ob_tran_transverse<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>\n            {\n\n                 typedef double geographic_type;\n                 typedef double cartesian_type;\n\n                par_ob_tran<Geographic, Cartesian> m_proj_parm;\n\n                inline base_ob_tran_transverse(const Parameters& par)\n                    : base_t_fi<base_ob_tran_transverse<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>(*this, par) {}\n\n                // FORWARD(t_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 cosphi, coslam;\n\n\n                    cosphi = cos(lp_lat);\n                    coslam = cos(lp_lon);\n                    lp_lon = adjlon(aatan2(cosphi * sin(lp_lon), sin(lp_lat)) + this->m_proj_parm.lamp);\n                    lp_lat = aasin(- cosphi * coslam);\n                    m_proj_parm.link->fwd(lp_lon, lp_lat, xy_x, xy_y);\n                }\n\n                // INVERSE(t_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 cosphi, t;\n\n                    m_proj_parm.link->inv(xy_x, xy_y, lp_lon, lp_lat);\n                    if (lp_lon != HUGE_VAL) {\n                        cosphi = cos(lp_lat);\n                        t = lp_lon - this->m_proj_parm.lamp;\n                        lp_lon = aatan2(cosphi * sin(t), - sin(lp_lat));\n                        lp_lat = aasin(cosphi * cos(t));\n                    }\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"ob_tran_transverse\";\n                }\n\n            };\n\n            // General Oblique Transformation\n            template <typename Geographic, typename Cartesian, typename Parameters>\n            double setup_ob_tran(Parameters& par, par_ob_tran<Geographic, Cartesian>& proj_parm, bool create = true)\n            {\n                double phip;\n                Parameters pj;\n\n                /* get name of projection to be translated */\n                pj.name = pj_param(par.params, \"so_proj\").s;\n                /* copy existing header into new */\n                par.es = 0.; /* force to spherical */\n                pj.params = par.params;\n                pj.over = par.over;\n                pj.geoc = par.geoc;\n                pj.a = par.a;\n                pj.es = par.es;\n                pj.ra = par.ra;\n                pj.lam0 = par.lam0;\n                pj.phi0 = par.phi0;\n                pj.x0 = par.x0;\n                pj.y0 = par.y0;\n                pj.k0 = par.k0;\n                /* force spherical earth */\n                pj.one_es = pj.rone_es = 1.;\n                pj.es = pj.e = 0.;\n\n                if (create)\n                {\n                    factory<Geographic, Cartesian, Parameters> fac;\n                    proj_parm.link.reset(fac.create_new(pj));\n                    if (! proj_parm.link.get()) throw proj_exception(-26);\n                }\n                if (pj_param(par.params, \"to_alpha\").i) {\n                    double lamc, phic, alpha;\n\n                    lamc    = pj_param(par.params, \"ro_lon_c\").f;\n                    phic    = pj_param(par.params, \"ro_lat_c\").f;\n                    alpha    = pj_param(par.params, \"ro_alpha\").f;\n            /*\n                    if (fabs(phic) <= TOL ||\n                        fabs(fabs(phic) - geometry::math::half_pi<double>()) <= TOL ||\n                        fabs(fabs(alpha) - geometry::math::half_pi<double>()) <= TOL)\n            */\n                    if (fabs(fabs(phic) - geometry::math::half_pi<double>()) <= TOL)\n                        throw proj_exception(-32);\n                    proj_parm.lamp = lamc + aatan2(-cos(alpha), -sin(alpha) * sin(phic));\n                    phip = aasin(cos(phic) * sin(alpha));\n                } else if (pj_param(par.params, \"to_lat_p\").i) { /* specified new pole */\n                    proj_parm.lamp = pj_param(par.params, \"ro_lon_p\").f;\n                    phip = pj_param(par.params, \"ro_lat_p\").f;\n                } else { /* specified new \"equator\" points */\n                    double lam1, lam2, phi1, phi2, con;\n\n                    lam1 = pj_param(par.params, \"ro_lon_1\").f;\n                    phi1 = pj_param(par.params, \"ro_lat_1\").f;\n                    lam2 = pj_param(par.params, \"ro_lon_2\").f;\n                    phi2 = pj_param(par.params, \"ro_lat_2\").f;\n                    if (fabs(phi1 - phi2) <= TOL ||\n                        (con = fabs(phi1)) <= TOL ||\n                        fabs(con - geometry::math::half_pi<double>()) <= TOL ||\n                        fabs(fabs(phi2) - geometry::math::half_pi<double>()) <= TOL) throw proj_exception(-33);\n                    proj_parm.lamp = atan2(cos(phi1) * sin(phi2) * cos(lam1) -\n                        sin(phi1) * cos(phi2) * cos(lam2),\n                        sin(phi1) * cos(phi2) * sin(lam2) -\n                        cos(phi1) * sin(phi2) * sin(lam1));\n                    phip = atan(-cos(proj_parm.lamp - lam1) / tan(phi1));\n                }\n                if (fabs(phip) > TOL) { /* oblique */\n                    proj_parm.cphip = cos(phip);\n                    proj_parm.sphip = sin(phip);\n                } else { /* transverse */\n                }\n                // return phip to choose model\n                return phip;\n            }\n\n        }} // namespace detail::ob_tran\n    #endif // doxygen\n\n    /*!\n        \\brief General Oblique Transformation 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 Projection parameters\n         - o_proj (string)\n         - Plus projection parameters\n         - o_lat_p (degrees)\n         - o_lon_p (degrees)\n         - New pole\n         - o_alpha: Alpha (degrees)\n         - o_lon_c (degrees)\n         - o_lat_c (degrees)\n         - o_lon_1 (degrees)\n         - o_lat_1: Latitude of first standard parallel (degrees)\n         - o_lon_2 (degrees)\n         - o_lat_2: Latitude of second standard parallel (degrees)\n        \\par Example\n        \\image html ex_ob_tran.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct ob_tran_oblique : public detail::ob_tran::base_ob_tran_oblique<Geographic, Cartesian, Parameters>\n    {\n        inline ob_tran_oblique(const Parameters& par) : detail::ob_tran::base_ob_tran_oblique<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::ob_tran::setup_ob_tran(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief General Oblique Transformation 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 Projection parameters\n         - o_proj (string)\n         - Plus projection parameters\n         - o_lat_p (degrees)\n         - o_lon_p (degrees)\n         - New pole\n         - o_alpha: Alpha (degrees)\n         - o_lon_c (degrees)\n         - o_lat_c (degrees)\n         - o_lon_1 (degrees)\n         - o_lat_1: Latitude of first standard parallel (degrees)\n         - o_lon_2 (degrees)\n         - o_lat_2: Latitude of second standard parallel (degrees)\n        \\par Example\n        \\image html ex_ob_tran.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct ob_tran_transverse : public detail::ob_tran::base_ob_tran_transverse<Geographic, Cartesian, Parameters>\n    {\n        inline ob_tran_transverse(const Parameters& par) : detail::ob_tran::base_ob_tran_transverse<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::ob_tran::setup_ob_tran(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 ob_tran_entry : public detail::factory_entry<Geographic, Cartesian, Parameters>\n        {\n            public :\n                virtual projection<Geographic, Cartesian>* create_new(const Parameters& par) const\n                {\n                    detail::ob_tran::par_ob_tran<Geographic, Cartesian> proj_parm;\n                    Parameters p = par;\n                    double phip = setup_ob_tran(p, proj_parm, false);\n\n                    if (fabs(phip) > detail::ob_tran::TOL)\n                        return new base_v_fi<ob_tran_oblique<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                    else\n                        return new base_v_fi<ob_tran_transverse<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        inline void ob_tran_init(detail::base_factory<Geographic, Cartesian, Parameters>& factory)\n        {\n            factory.add_to_factory(\"ob_tran\", new ob_tran_entry<Geographic, Cartesian, Parameters>);\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n}}} // namespace boost::geometry::projections\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_OB_TRAN_HPP\n\n", "meta": {"hexsha": "1769a1fd5cb69f77aeca0cc8667079fb0ba84a6c", "size": 15582, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/ob_tran.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/ob_tran.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/ob_tran.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.7696629213, "max_line_length": 140, "alphanum_fraction": 0.5732255166, "num_tokens": 3378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.25054582751431925}}
{"text": "/*\nCopyright 2009-2021 Nicolas Colombe\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 <gen/poissonsampling.hpp>\n#include <math/geometrytraits.hpp>\n#include <math/vector2.hpp>\n#include <math/aabb2d.hpp>\n\n#include <core/random.hpp>\n#include <core/heapobject.hpp>\n\n#include <boost/random.hpp>\n//#include <boost/pool/pool_alloc.hpp>\n#include <boost/geometry/index/rtree.hpp>\n\ntypedef std::pair<eXl::Vector2d, unsigned int> value;\ntypedef boost::geometry::index::rtree< value, boost::geometry::index::rstar<16, 4> > PointIndex;\n\nnamespace eXl\n{\n\n  static const unsigned int k_BootstrapLimit = 30;\n  static const unsigned int k_GeneratedPoints = 30;\n\n  //typedef boost::fast_pool_allocator<Vector2d,\n  //  boost::default_user_allocator_new_delete,\n  //  boost::details::pool::default_mutex,\n  //  64, 128> allocator;\n\n  typedef std::list<Vector2d/*, allocator*/> PointsStack;\n\n  struct PoissonDiskSampling_Impl : public HeapObject\n  {\n    PoissonDiskSampling_Impl(Polygoni const& iPoly, Random& iGen) : m_PrecisePoly(iPoly), m_Gen(iGen)\n    {\n      //m_Stack.reserve(1024);\n    }\n\n    void AddPoint(Vector2d const& iPoint, float iCovering)\n    {\n\n      for(unsigned int i = 0; i < m_PointsIndex.size(); ++i)\n      {\n        double checkRadius = (m_Covering[i] + iCovering);\n        AABB2Dd box = AABB2Dd::FromCenterAndSize(iPoint, Vector2d::ONE * checkRadius * 2);\n        PointIndex const& index = m_PointsIndex[i];\n        std::vector<value> returned_values;\n        index.query(boost::geometry::index::within(box), std::back_inserter(returned_values));\n        for(auto val : returned_values)\n        {\n          if((iPoint - val.first).Length() < checkRadius)\n          {\n            m_PointsValid[i][val.second] = false;\n          }\n        }\n      }\n      \n      m_Stack.push_back(iPoint);\n    }\n\n    PointsStack m_Stack;\n\n    std::vector<PointIndex>             m_PointsIndex;\n    std::vector<std::vector<bool> >     m_PointsValid;\n    std::vector<std::vector<Vector2d> > m_Points;\n    std::vector<float>                  m_Covering;\n\n    Polygond              m_PrecisePoly;\n    Random&               m_Gen;\n  };\n\n  PoissonDiskSampling::PoissonDiskSampling(Polygoni const& iPoly, Random& iGen)\n    :m_Impl(eXl_NEW PoissonDiskSampling_Impl(iPoly, iGen))\n  {\n    \n  }\n\n  PoissonDiskSampling::~PoissonDiskSampling()\n  {\n    eXl_DELETE m_Impl;\n  }\n\n  void PoissonDiskSampling::Sample(float iRadius, float iCovering, unsigned int iMaxPts)\n  {\n    Vector<Polygond> shrinkedPoly;\n    {\n      m_Impl->m_PrecisePoly.Shrink(iCovering, shrinkedPoly);\n      if(shrinkedPoly.empty())\n      {\n        return;\n      }\n    }\n\n    PointIndex curIndex;\n    std::vector<Vector2d> curPoints;\n\n    unsigned int numPts = 0;\n    RandomWrapper rand(&m_Impl->m_Gen);\n\n    for(auto poly : shrinkedPoly)\n    {\n      boost::random::uniform_real_distribution<double> distribX(poly.GetAABB().m_Data[0].X(), poly.GetAABB().m_Data[1].X());\n      boost::random::uniform_real_distribution<double> distribY(poly.GetAABB().m_Data[0].Y(), poly.GetAABB().m_Data[1].Y());\n\n      for(unsigned int i = 0; i<k_BootstrapLimit; ++i)\n      {\n        Vector2d origPt(distribX(rand),distribY(rand));\n        if(poly.ContainsPoint(origPt))\n        {\n          m_Impl->AddPoint(origPt, iCovering);          \n          curIndex.insert(std::make_pair(origPt, numPts));\n          curPoints.push_back(origPt);\n          ++numPts;\n          break;\n        }\n      }\n      \n      while(!m_Impl->m_Stack.empty()\n      && (iMaxPts == 0 || numPts < iMaxPts))\n      {\n        boost::random::uniform_real_distribution<double> distribTheta(-Mathd::PI, Mathd::PI);\n        Vector2d origPt = m_Impl->m_Stack.front();\n        m_Impl->m_Stack.pop_front();\n\n        for(unsigned int i = 0; i<k_GeneratedPoints; ++i)\n        {\n          double angle = distribTheta(rand);\n          Vector2d point = origPt + Vector2d(Mathd::Cos(angle), Mathd::Sin(angle)) * iRadius * 2;\n          if(poly.ContainsPoint(point))\n          {\n            AABB2Dd box = AABB2Dd::FromCenterAndSize(point, Vector2d(iRadius, iRadius) * 4);\n            bool validPoint = true;\n            std::vector<value> returned_values;\n            curIndex.query(boost::geometry::index::within(box), std::back_inserter(returned_values));\n\n            for(auto val : returned_values)\n            {\n              if((point - val.first).Length() < 2*iRadius)\n              {\n                validPoint = false;\n                break;\n              }\n            }\n            if(validPoint)\n            {\n              m_Impl->AddPoint(point, iCovering);\n              curIndex.insert(std::make_pair(point, numPts));\n              curPoints.push_back(point);\n              ++numPts;\n            }\n          }\n        }\n      }\n    }\n\n    m_Impl->m_Covering.push_back(iCovering);\n    m_Impl->m_Points.push_back(std::vector<Vector2d>());\n    m_Impl->m_PointsValid.push_back(std::vector<bool>());\n    m_Impl->m_PointsIndex.push_back(PointIndex());\n\n    m_Impl->m_Points.back().swap(curPoints);\n    m_Impl->m_PointsIndex.back().swap(curIndex);\n    m_Impl->m_PointsValid.back().resize(numPts, true);\n    \n  }\n\n  unsigned int PoissonDiskSampling::GetNumLayers() const\n  {\n    return m_Impl->m_PointsIndex.size();\n  }\n\n  void PoissonDiskSampling::GetLayer(unsigned int iLayer, Vector<Vector2d>& oPoints) const\n  {\n    oPoints.clear();\n    if(iLayer < m_Impl->m_PointsIndex.size())\n    {\n      for(unsigned int i = 0; i<m_Impl->m_Points[iLayer].size(); ++i)\n      {\n        if(m_Impl->m_PointsValid[iLayer][i])\n        {\n          oPoints.push_back(m_Impl->m_Points[iLayer][i]);\n        }\n      }\n    }\n  }\n\n}", "meta": {"hexsha": "d87765d23138cb7e0810f39e0f187bd3ab5ab74b", "size": 6586, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gen/poissonsampling.cpp", "max_stars_repo_name": "eXl-Nic/eXl", "max_stars_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gen/poissonsampling.cpp", "max_issues_repo_name": "eXl-Nic/eXl", "max_issues_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gen/poissonsampling.cpp", "max_forks_repo_name": "eXl-Nic/eXl", "max_forks_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_forks_repo_licenses": ["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.9484536082, "max_line_length": 460, "alphanum_fraction": 0.6437898573, "num_tokens": 1682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.25040438538016085}}
{"text": "//=============================================================================\n// Copyright (C) 2011-2018 The pmp-library developers\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// * 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 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\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 <pmp/algorithms/SurfaceFairing.h>\n#include <pmp/algorithms/DifferentialGeometry.h>\n\n#include <utility>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n//=============================================================================\n\nnamespace pmp {\n\n//=============================================================================\n\nusing SparseMatrix = Eigen::SparseMatrix<double>;\nusing Triplet = Eigen::Triplet<double>;\n\n//=============================================================================\n\nSurfaceFairing::SurfaceFairing(SurfaceMesh& mesh) : m_mesh(mesh)\n{\n    // get & add properties\n    m_points = m_mesh.vertexProperty<Point>(\"v:point\");\n    m_vselected = m_mesh.getVertexProperty<bool>(\"v:selected\");\n    m_vlocked = m_mesh.addVertexProperty<bool>(\"fairing:locked\");\n    m_vweight = m_mesh.addVertexProperty<double>(\"fairing:vweight\");\n    m_eweight = m_mesh.addEdgeProperty<double>(\"fairing:eweight\");\n    m_idx = m_mesh.addVertexProperty<int>(\"fairing:idx\", -1);\n}\n\n//-----------------------------------------------------------------------------\n\nSurfaceFairing::~SurfaceFairing()\n{\n    // remove properties\n    m_mesh.removeVertexProperty(m_vlocked);\n    m_mesh.removeVertexProperty(m_vweight);\n    m_mesh.removeEdgeProperty(m_eweight);\n    m_mesh.removeVertexProperty(m_idx);\n}\n\n//-----------------------------------------------------------------------------\n\nvoid SurfaceFairing::fair(unsigned int k)\n{\n    // compute cotan weights\n    for (auto v : m_mesh.vertices())\n    {\n        m_vweight[v] = 0.5 / voronoiArea(m_mesh, v);\n    }\n    for (auto e : m_mesh.edges())\n    {\n        m_eweight[e] = std::max(0.0, cotanWeight(m_mesh, e));\n    }\n\n    // check whether some vertices are selected\n    bool noSelection = true;\n    if (m_vselected)\n    {\n        for (auto v : m_mesh.vertices())\n        {\n            if (m_vselected[v])\n            {\n                noSelection = false;\n                break;\n            }\n        }\n    }\n\n    // lock k locked boundary rings\n    for (auto v : m_mesh.vertices())\n    {\n        // lock boundary\n        if (m_mesh.isSurfaceBoundary(v))\n        {\n            m_vlocked[v] = true;\n\n            // lock one-ring of boundary\n            if (k > 1)\n            {\n                for (auto vv : m_mesh.vertices(v))\n                {\n                    m_vlocked[vv] = true;\n\n                    // lock two-ring of boundary\n                    if (k > 2)\n                    {\n                        for (auto vvv : m_mesh.vertices(vv))\n                        {\n                            m_vlocked[vvv] = true;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    // lock un-selected and isolated vertices\n    for (auto v : m_mesh.vertices())\n    {\n        if (!noSelection && !m_vselected[v])\n        {\n            m_vlocked[v] = true;\n        }\n\n        if (m_mesh.isIsolated(v))\n        {\n            m_vlocked[v] = true;\n        }\n    }\n\n    // collect free vertices\n    std::vector<SurfaceMesh::Vertex> vertices;\n    vertices.reserve(m_mesh.nVertices());\n    for (auto v : m_mesh.vertices())\n    {\n        if (!m_vlocked[v])\n        {\n            m_idx[v] = vertices.size();\n            vertices.push_back(v);\n        }\n    }\n\n    // construct matrix & rhs\n    const unsigned int n = vertices.size();\n    SparseMatrix A(n, n);\n    Eigen::MatrixXd B(n, 3);\n\n    std::map<SurfaceMesh::Vertex, double> row;\n    std::vector<Triplet> triplets;\n\n    for (unsigned int i = 0; i < n; ++i)\n    {\n        B(i, 0) = 0.0;\n        B(i, 1) = 0.0;\n        B(i, 2) = 0.0;\n\n        setupMatrixRow(vertices[i], m_vweight, m_eweight, k, row);\n\n        for (auto r : row)\n        {\n            auto v = r.first;\n            auto w = r.second;\n\n            if (m_idx[v] != -1)\n            {\n                triplets.emplace_back(i, m_idx[v], w);\n            }\n            else\n            {\n                B(i, 0) -= w * m_points[v][0];\n                B(i, 1) -= w * m_points[v][1];\n                B(i, 2) -= w * m_points[v][2];\n            }\n        }\n    }\n\n    A.setFromTriplets(triplets.begin(), triplets.end());\n\n    // solve A*X = B\n    Eigen::SimplicialLDLT<SparseMatrix> solver(A);\n    Eigen::MatrixXd X = solver.solve(B);\n\n    if (solver.info() != Eigen::Success)\n    {\n        std::cerr << \"SurfaceFairing: Could not solve linear system\\n\";\n    }\n    else\n    {\n        for (unsigned int i = 0; i < n; ++i)\n        {\n            auto v = vertices[i];\n            m_points[v] = Point(X(m_idx[v], 0), X(m_idx[v], 1), X(m_idx[v], 2));\n        }\n    }\n}\n\n//-----------------------------------------------------------------------------\n\nstruct Triple\n{\n    Triple() = default;\n\n    Triple(SurfaceMesh::Vertex v, double weight, unsigned int degree)\n        : m_v(std::move(v)), m_weight(weight), m_degree(degree)\n    {\n    }\n\n    SurfaceMesh::Vertex m_v;\n    double m_weight;\n    unsigned int m_degree;\n};\n\n//-----------------------------------------------------------------------------\n\nvoid SurfaceFairing::setupMatrixRow(const SurfaceMesh::Vertex v,\n                                    SurfaceMesh::VertexProperty<double> vweight,\n                                    SurfaceMesh::EdgeProperty<double> eweight,\n                                    unsigned int laplaceDegree,\n                                    std::map<SurfaceMesh::Vertex, double>& row)\n{\n    Triple t(v, 1.0, laplaceDegree);\n\n    // init\n    static std::vector<Triple> todo;\n    todo.reserve(50);\n    todo.push_back(t);\n    row.clear();\n\n    while (!todo.empty())\n    {\n        t = todo.back();\n        todo.pop_back();\n        auto v = t.m_v;\n        auto d = t.m_degree;\n\n        if (d == 0)\n        {\n            row[v] += t.m_weight;\n        }\n\n        // else if (d == 1 && m_mesh.isSurfaceBoundary(v))\n        // {\n        //     // ignore?\n        // }\n\n        else\n        {\n            auto ww = 0.0;\n\n            for (auto h : m_mesh.halfedges(v))\n            {\n                auto e = m_mesh.edge(h);\n                auto vv = m_mesh.toVertex(h);\n                auto w = eweight[e];\n\n                if (d < laplaceDegree)\n                    w *= vweight[v];\n\n                w *= t.m_weight;\n                ww -= w;\n\n                todo.emplace_back(vv, w, d - 1);\n            }\n\n            todo.emplace_back(v, ww, d - 1);\n        }\n    }\n}\n\n//=============================================================================\n} // namespace pmp\n//=============================================================================\n", "meta": {"hexsha": "2a3c9119c011e50c547a657f1f7ee3bd9176ea8d", "size": 8243, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pmp/algorithms/SurfaceFairing.cpp", "max_stars_repo_name": "choyfung/pmp-library", "max_stars_repo_head_hexsha": "4a72c918494dac92f5e77545b71c7a327dafe71e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-21T04:15:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-21T04:15:44.000Z", "max_issues_repo_path": "src/pmp/algorithms/SurfaceFairing.cpp", "max_issues_repo_name": "choyfung/pmp-library", "max_issues_repo_head_hexsha": "4a72c918494dac92f5e77545b71c7a327dafe71e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pmp/algorithms/SurfaceFairing.cpp", "max_forks_repo_name": "choyfung/pmp-library", "max_forks_repo_head_hexsha": "4a72c918494dac92f5e77545b71c7a327dafe71e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-21T04:15:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-21T04:15:52.000Z", "avg_line_length": 29.2304964539, "max_line_length": 80, "alphanum_fraction": 0.4919325488, "num_tokens": 1791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2504043793006021}}
{"text": "#pragma once\n\n#include <deque>\n#include <stdexcept>\n#include <unordered_map>\n\n#include <boost/pending/disjoint_sets.hpp>\n#include <boost/functional/hash.hpp>\n#include \"xtensor/xtensor.hpp\"\n#include \"xtensor/xarray.hpp\"\n\n#include \"affogato/util.hxx\"\n\nnamespace affogato {\nnamespace segmentation {\n\n\ntemplate<class EDGE_WEIGHTS, class NODE_WEIGHTS>\ninline void get_node_weights(const xt::xexpression<EDGE_WEIGHTS> & edge_weights_exp,\n                             const double lower_threshold,\n                             xt::xexpression<NODE_WEIGHTS> & node_weights_exp,\n                             const bool ignore_border = false) {\n\n    typedef typename EDGE_WEIGHTS::value_type ValueType;\n    const auto & edge_weights = edge_weights_exp.derived_cast();\n    auto & node_weights = node_weights_exp.derived_cast();\n\n    xt::xindex shape(node_weights.shape().begin(), node_weights.shape().end());\n    const unsigned ndim = shape.size();\n\n    // ValueType infinity = *std::max_element(edge_weights.begin(), edge_weights.end()) + .1;\n    const ValueType infinity = 1.1;\n    // iterate over all spatial coordinates. for each node, find all weigths that are connected to it\n    util::for_each_coordinate(shape, [&](const xt::xindex coord){\n\n        ValueType weight = 0;\n        // get the weights connecting this node to other nodes\n        for(unsigned d = 0; d < ndim; ++d) {\n            // NOTE this assumes affinity offset conventions [[-1, 0], [0, -1]] etc.\n            for(auto dir : {0, 1}) {\n                // get the corresponding affi\n                xt::xindex aff_coord(ndim + 1);\n                std::copy(coord.begin(), coord.end(), aff_coord.begin() + 1);\n                aff_coord[0] = d;\n                aff_coord[d + 1] += dir;\n                ValueType curr_weight;\n                if(aff_coord[d + 1] > 0 && aff_coord[d + 1] < shape[d]) {\n                    curr_weight = edge_weights[aff_coord];\n                } else {\n                    continue;\n                }\n                if(curr_weight > weight) {\n                    weight = curr_weight;\n                }\n            }\n        }\n        node_weights[coord] = (weight > lower_threshold) ? infinity : weight;\n\n        if(ignore_border) {\n            bool at_border = false;\n            for(unsigned d = 0; d < ndim; ++d) {\n                if(coord[d] == 0 || coord[d] == shape[d] - 1) {\n                    at_border = true;\n                    break;\n                }\n            }\n            if(at_border) {\n                node_weights[coord] = infinity;\n            }\n        }\n    });\n}\n\n\ntemplate<class EDGE_WEIGHTS, class NODE_WEIGHTS, class LABELS>\ninline uint64_t stream(const xt::xindex & start_coord,\n                       const xt::xexpression<EDGE_WEIGHTS> & edge_weights_exp,\n                       const xt::xexpression<NODE_WEIGHTS> & node_weights_exp,\n                       const xt::xexpression<LABELS> & labels_exp,\n                       const double upper_threshold,\n                       std::vector<xt::xindex> & stream_coordinates\n                       /*,std::ofstream debug*/ ) {\n\n    typedef typename EDGE_WEIGHTS::value_type ValueType;\n    // add pixel to the stream coordinates\n    stream_coordinates.emplace_back(start_coord);\n    const unsigned ndim = start_coord.size();\n\n    const auto & edge_weights = edge_weights_exp.derived_cast();\n    const auto & node_weights = node_weights_exp.derived_cast();\n    const auto & labels = labels_exp.derived_cast();\n\n    xt::xindex shape(labels.shape().begin(), labels.shape().end());\n\n    // initialize pixel queue\n    std::deque<xt::xindex> queue;\n    queue.push_back(start_coord);\n\n    const ValueType infinity = 1.1;\n\n    while(!queue.empty()) {\n\n        const auto & coord = queue.front();\n        queue.pop_front();\n\n        ValueType w_max = node_weights[coord];\n\n        // iterate over the connection to neighbors for this coordinate\n        for(unsigned d = 0; d < ndim; ++d) {\n            // NOTE this assumes affinity offset conventions [[-1, 0], [0, -1]] etc.\n            for(auto dir : {0, 1}) {\n                // get the corresponding affinity coordinate and neighbor coordinate\n                xt::xindex ngb_coord(ndim), aff_coord(ndim + 1);\n\n                std::copy(coord.begin(), coord.end(), aff_coord.begin() + 1);\n                aff_coord[0] = d;\n                aff_coord[d + 1] += dir;\n\n                std::copy(coord.begin(), coord.end(), ngb_coord.begin());\n                ngb_coord[d] += (dir == 0) ? -1 : 1;\n\n                // range check\n                if(ngb_coord[d] <= 0 || ngb_coord[d] >= shape[d]) {\n                    continue;\n                }\n\n                ValueType weight = edge_weights[aff_coord];\n                weight = (weight > upper_threshold) ? infinity : weight;\n\n                // only consider neighbor if its weight is equal to the nodes max-weight\n                if(fabs(weight - w_max) > std::numeric_limits<ValueType>::epsilon()) {\n                    continue;\n                }\n\n                // only consider neighbor if it's coordinate is not already in the stream\n                if(std::find(stream_coordinates.begin(), stream_coordinates.end(), ngb_coord) != stream_coordinates.end()) {\n                    continue;\n                }\n\n                // if we hit a labeled coordinate, return it's label\n                if(labels[ngb_coord] != 0 ) {\n                    return labels[ngb_coord];\n                }\n\n                // if the node weight of the considered pixel is smaller, we start depth first search from it\n                else if(node_weights[ngb_coord] < w_max ) {\n                    stream_coordinates.emplace_back(ngb_coord);\n                    queue.clear();\n                    queue.push_back(ngb_coord);\n                    // break looping over the current neighbors and go to new pix\n                    break;\n                }\n                else {\n                    stream_coordinates.push_back(ngb_coord);\n                    queue.push_back(ngb_coord);\n                }\n            }\n        }\n    }\n    // return 0, if we have not found a labeled pixel in the stream\n    return 0;\n}\n\n\ntemplate<class EDGE_WEIGHTS, class NODE_WEIGHTS, class LABELS>\ninline size_t run_zws(const xt::xexpression<EDGE_WEIGHTS> & edge_weights_exp,\n                      const xt::xexpression<NODE_WEIGHTS> & node_weights_exp,\n                      const double upper_threshold,\n                      xt::xexpression<LABELS> & labels_exp,\n                      bool const ignore_border=false) {\n    typedef typename LABELS::value_type LabelType;\n    LabelType next_label = 1;\n\n    const auto & edge_weights = edge_weights_exp.derived_cast();\n    const auto & node_weights = node_weights_exp.derived_cast();\n    auto & labels = labels_exp.derived_cast();\n\n    // ofstream for debug output\n    //std::ofstream debug;\n    //debug.open(\"run_wsgraph_debug.txt\")\n    //\n    //\n    const xt::xindex shape(node_weights.shape().begin(), node_weights.shape().end());\n    const unsigned ndim = shape.size();\n\n    util::for_each_coordinate(shape, [&](const xt::xindex & coord){\n        if(ignore_border) {\n            bool is_border = false;\n            for(unsigned d = 0; d < ndim; ++d) {\n                if(coord[d] == 0 || coord[d] == shape[d] - 1) {\n                    is_border = true;\n                    break;\n                }\n            }\n            if(is_border) {\n                return;\n            }\n        }\n\n        auto label = labels[coord];\n        // continue if the pixel is already labeled\n        if(label != 0) {\n            return;\n        }\n\n        // call stream -> finds the stream belonging to the current label and pixel coordinates belonging to the stream\n        std::vector<xt::xindex> stream_coordinates;\n        label = stream(coord, edge_weights, node_weights, labels,\n                       upper_threshold, stream_coordinates); //debug\n\n        // if stream returns 0, we found a new stream\n        if(label == 0) {\n            label = next_label++;\n        }\n\n        // write the new label to all coordinates in the stream\n        for(const auto & coord : stream_coordinates) {\n            labels[coord] = label;\n        }\n\n    });\n    //debug.close();\n    return next_label;\n}\n\n\ntemplate<class EDGE_WEIGHTS, class LABELS, class LINK>\ninline void get_region_weights(const xt::xexpression<EDGE_WEIGHTS> & edge_weights_exp,\n                               const xt::xexpression<LABELS> & labels_exp,\n                               const double upper_threshold,\n                               std::unordered_map<LINK, typename EDGE_WEIGHTS::value_type, boost::hash<LINK>> & links) {\n\n    typedef LINK Link;\n    typedef typename EDGE_WEIGHTS::value_type ValueType;\n\n    const ValueType infinity = 1.1;\n\n    const auto & edge_weights = edge_weights_exp.derived_cast();\n    const auto & labels = labels_exp.derived_cast();\n    xt::xindex shape(labels.shape().begin(), labels.shape().end());\n    const unsigned ndim = shape.size();\n\n    util::for_each_coordinate(shape, [&](const xt::xindex & coord) {\n        const auto label = labels[coord];\n        for(unsigned d = 0; d < ndim ;++d) {\n\n            // range check\n            if(coord[d] > 0) {\n                continue;\n            }\n\n            xt::xindex ngb_coord(coord);\n            ngb_coord[d] -= 1;\n\n            const auto ngb_label = labels[ngb_coord];\n            if(ngb_label != label) {\n                Link link(std::min(ngb_label, label),\n                          std::max(ngb_label, label));\n                xt::xindex aff_coord(ndim + 1);\n                std::copy(coord.begin(), coord.end(), aff_coord.begin() + 1);\n                aff_coord[0] = d;\n                ValueType weight = edge_weights[aff_coord];\n                weight = (weight > upper_threshold) ? infinity : weight;\n\n                auto link_it = links.find(link);\n                if(link_it != links.end()) {\n                    link_it->second = std::max(weight, link_it->second);\n                } else {\n                    links.emplace(link, weight);\n                }\n            }\n        }\n    });\n}\n\n\ntemplate<class LINK, class WEIGHT, class LABELS>\ninline size_t apply_size_filter(const std::unordered_map<LINK, WEIGHT, boost::hash<LINK>> & region_weights,\n                                const size_t n_labels,\n                                const size_t size_threshold,\n                                const double merge_threshold,\n                                xt::xexpression<LABELS> & labels_exp) {\n    typedef typename LABELS::value_type LabelType;\n    auto & labels = labels_exp.derived_cast();\n\n    // dump map into a vector and sort it by value\n    std::vector<std::pair<LINK, WEIGHT>> rw_vec(region_weights.begin(),\n                                                region_weights.end());\n\n    std::sort(rw_vec.begin(), rw_vec.end(), [](const std::pair<LINK, WEIGHT> & a,\n                                               const std::pair<LINK, WEIGHT> & b){return a.second < b.second;});\n\n    xt::xindex shape(labels.shape().begin(), labels.shape().end());\n\n    // find sizes of labels\n    std::vector<size_t> sizes(n_labels);\n    util::for_each_coordinate(shape, [&](const xt::xindex & coord){\n        ++sizes[labels[coord]];\n    });\n\n    // make ufd\n    std::vector<LabelType> ranks(n_labels);\n    std::vector<LabelType> parents(n_labels);\n    boost::disjoint_sets<LabelType*, LabelType*> ufd(&ranks[0], &parents[0]);\n    for(LabelType label = 0; label < n_labels; ++label) {\n        ufd.make_set(label);\n    }\n\n    // merge regions\n    for(const auto & e_and_w : rw_vec) {\n\n        // if we have reached the value threshold, we stop filtering\n        if(e_and_w.second < merge_threshold) {\n            break;\n        }\n        const auto & edge = e_and_w.first;\n\n        const LabelType s1 = ufd.find_set(edge.first);\n        const LabelType s2 = ufd.find_set(edge.second);\n\n        // merge two regions, if at least one of them is below the size threshold\n        if(s1 != s2 && (sizes[s1] < size_threshold || sizes[s2] < size_threshold)) {\n            const size_t size = sizes[s1] + sizes[s2];\n            sizes[s1] = 0;\n            sizes[s2] = 0;\n            ufd.link(s1, s2);\n            sizes[ufd.find_set(s1)] = size;\n        }\n    }\n\n    std::vector<LabelType> new_labels(n_labels);\n    LabelType next_label = 1;\n    for(LabelType label = 0; label < n_labels; ++label) {\n        const auto repr = ufd.find_set(label);\n        if(sizes[repr] < size_threshold) {\n            new_labels[label] = 0;\n        } else {\n            new_labels[label] = next_label++;\n        }\n    }\n\n    // write the new labels\n    util::for_each_coordinate(shape, [&](const xt::xindex & coord){\n        labels[coord] = new_labels[labels[coord]];\n    });\n\n    return next_label;\n}\n\n\n// z-watershed, implementation based on\n// http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=4564470&tag=1\n// and http://dspace.mit.edu/handle/1721.1/66820\ntemplate<class WEIGHTS, class LABELS>\nsize_t compute_zws_segmentation(const xt::xexpression<WEIGHTS> & edge_weights_exp,\n\t\t\t\t\t\t\t    const double lower_threshold,\n        \t\t\t\t\t    const double upper_threshold,\n\t\t\t\t\t\t\t    const double merge_threshold,\n        \t\t\t\t\t    const size_t size_threshold,\n                                xt::xexpression<LABELS> & labels_exp) {\n\n    typedef typename WEIGHTS::value_type ValueType;\n    typedef typename LABELS::value_type LabelType;\n    if(lower_threshold > upper_threshold) {\n        throw std::runtime_error(\"Thresholds inverted!\");\n    }\n\n    const auto & edge_weights = edge_weights_exp.derived_cast();\n    // initialize the node weights, which are one dimension less than the edge weights\n    typedef typename xt::xarray<ValueType>::shape_type ShapeType;\n    ShapeType shape(edge_weights.shape().begin() + 1, edge_weights.shape().end());\n    xt::xarray<ValueType> node_weights = xt::zeros<ValueType>(shape);\n\n    // std::cout << \"computing node weights from edge weights\" << std::endl;\n    get_node_weights(edge_weights, lower_threshold, node_weights);\n\n    // threshold_edge_weights(edge_weights, upper_threshold);\n    // std::cout << \"run zws\" << std::endl;\n    size_t n_labels = run_zws(edge_weights, node_weights, upper_threshold, labels_exp);\n    // std::cout << n_labels << \" labels after zws\" << std::endl;\n\n    // if we don't do merging or size filtering, we can return here already\n    if(merge_threshold == 0 && size_threshold == 0) {\n        return n_labels;\n    }\n\n    typedef std::pair<LabelType, LabelType> Link;\n    std::unordered_map<Link, ValueType, boost::hash<Link>> region_weights;\n    // std::cout << \"get region weights\" << std::endl;\n    get_region_weights(edge_weights, labels_exp, upper_threshold, region_weights);\n\n    // std::cout << \"apply size filter\" << std::endl;\n    n_labels = apply_size_filter(region_weights, n_labels,\n                                 size_threshold, merge_threshold,\n                                 labels_exp);\n\n    return n_labels;\n}\n\n\n}\n}\n", "meta": {"hexsha": "5df6175370841253eebd6e6071eeb008bc0481eb", "size": 15013, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "include/affogato/segmentation/zwatershed.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/zwatershed.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/zwatershed.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": 37.253101737, "max_line_length": 124, "alphanum_fraction": 0.5705721708, "num_tokens": 3324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.542863297964157, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.25026908923429775}}
{"text": "#ifndef ABSTRACT_INTERFACE_HH\n#define ABSTRACT_INTERFACE_HH\n\n#include <memory>\n#include <iostream>\n#include <boost/signals2.hpp>\n#include <string>\n#include <cmath>\n#include <vector>\n\n#include <dune/grid/config.h>\n#include \"linalg/triplet.hh\"\n\nnamespace Kaskade\n{\n  /**\n   * @file\n   * @brief  Interfaces for function space oriented algorithms\n   * @author Anton Schiela\n   */\n  /** \\addtogroup abstract*/\n  /**@{*/\n\n  /// Abstract Vector for function space algorithms\n  class AbstractFunctionSpaceElement\n  {\n  public:\n    // No copy constructor.\n    AbstractFunctionSpaceElement(AbstractFunctionSpaceElement const &) = delete;\n\n    virtual ~AbstractFunctionSpaceElement() {}\n\n    /// *this += alpha*l\n    AbstractFunctionSpaceElement& axpy(double alpha, AbstractFunctionSpaceElement const& l, int component)\n    {\n      if(this==&l)\n      {\n        std::vector<double> alphaV(nComponents(),alpha+1.0);\n        return doscale(alphaV);\n      }\n      else\n        return doaxpy(alpha, l, component);\n    }\n\n    AbstractFunctionSpaceElement& axpy(double alpha, AbstractFunctionSpaceElement const&l, std::string const role)\n    {\n      return axpy_role(alpha,l,role);\n    }\n\n    AbstractFunctionSpaceElement& axpy_role(double alpha, AbstractFunctionSpaceElement const&l, std::string const role)\n    {\n      for(int i=0; i<nComponents(); ++i)\n      {\n        if(getRole(i)==role) axpy(alpha,l,i);\n      }\n      return *this;\n    }\n\n    /// *this += alpha*l\n    AbstractFunctionSpaceElement& axpy(double alpha, AbstractFunctionSpaceElement const& l)\n    {\n      if(this==&l)\n      {\n        std::vector<double> alphaV(nComponents(),alpha+1.0);\n        return doscale(alphaV);\n      }\n      else\n        return doaxpy_(alpha, l);\n    }\n\n\n    /// Assignment\n    AbstractFunctionSpaceElement& operator=(AbstractFunctionSpaceElement const& v)\n    {\n      if(this!=&v) return doassign(v);\n      return *this;\n    }\n\n    /// Basic vector arithmetic\n    AbstractFunctionSpaceElement& operator+=(AbstractFunctionSpaceElement const& v) { return doaxpy_(1.0,v); }\n    /// Basic vector arithmetic\n    AbstractFunctionSpaceElement& operator-=(AbstractFunctionSpaceElement const& v) { return doaxpy_(-1.0,v); }\n    /// Basic vector arithmetic\n    AbstractFunctionSpaceElement& operator*=(double lambda)\n    {\n      std::vector<double> lambdaV(nComponents(),lambda);\n      return doscale(lambdaV);\n    }\n\n    /// Scaling each component of the vector separately\n    AbstractFunctionSpaceElement& operator*=(std::vector<double>const& lambda)\n    {\n      return doscale(lambda);\n    }\n\n    /// Interpret *this as a dual vector, and apply it to v\n    /** Duality is currently not represented by types, hence users have to make\n  sure that the dual pairing <*this,v> is mathematically meaningful. The standard \n implementation of the dual pairing in Bridge::Vector is\n the dot-product between the coordinate representations of *this and v. \n For that *this should be the result of AbstractLinearization::evald\n     */\n    double applyAsDualTo(AbstractFunctionSpaceElement const& v, int component) const\n    {\n      return doapplyAsDualTo(v,component,component+1);\n    }\n\n    double applyAsDualTo(AbstractFunctionSpaceElement const& v) const\n    {\n      return doapplyAsDualTo(v,0,nComponents());\n    }\n\n    double applyAsDualTo(AbstractFunctionSpaceElement const& v, std::string const& role) const\n    {\n      return applyAsDualTo_role(v,role);\n    }\n\n    double applyAsDualTo_role(AbstractFunctionSpaceElement const&v, std::string const role) const\n    {\n      double res(0.0);\n      for(int i=0; i<nComponents(); ++i)\n      {\n        if(getRole(i)==role) res+=applyAsDualTo(v,i);\n      }\n      return res;\n    }\n\n    virtual std::string getRole(int component) const = 0;\n\n    /// Shallow swap\n    void swap(AbstractFunctionSpaceElement& v) { doswap(v); }\n\n    virtual int nComponents() const = 0;\n\n    /// Optional output\n    virtual void writeToFile(std::string const& file, bool append, int order=1) const {}\n\n    /// Optional output\n    virtual void print(std::string const& message=\"\") const { std::cout << \"AbstractFunctionSpaceElement: No printing available!\" << std::endl;}\n\n    /// Construction of a vector of the same type\n    virtual std::unique_ptr<AbstractFunctionSpaceElement> clone() const = 0;\n\n    /// Construction of a vector of the same type\n    virtual std::unique_ptr<AbstractFunctionSpaceElement> initZeroVector() const = 0;\n\n  private:\n    /// Interface for implementation\n    virtual AbstractFunctionSpaceElement& doaxpy(double alpha, AbstractFunctionSpaceElement const& l, int component) = 0;\n    virtual AbstractFunctionSpaceElement& doaxpy_(double alpha, AbstractFunctionSpaceElement const& l) = 0;\n    /// Interface for implementation\n    virtual AbstractFunctionSpaceElement& doscale(std::vector<double> const& lambda) = 0;\n    /// Interface for implementation\n    virtual AbstractFunctionSpaceElement& doassign(AbstractFunctionSpaceElement const& l) = 0;\n    /// Interface for implementation\n    virtual void doswap(AbstractFunctionSpaceElement& l) = 0;\n    virtual double doapplyAsDualTo(AbstractFunctionSpaceElement const& v,int vbegin, int vend) const = 0;\n\n  protected:\n    AbstractFunctionSpaceElement() {}\n  };\n  \n  /// Abstract linearization.\n  /** Given a nonlinear functional, this class represents second order information at the point of linearization\n   */\n  class AbstractLinearization\n  {\n  public:\n    /// Evaluate functional\n    virtual double eval() const = 0;\n    /// Evaluate L1 norm of integrand\n    virtual double evalL1norm() const = 0;\n    /// Evaluate derivative\n    virtual void evald(AbstractFunctionSpaceElement &g, int rbegin=0, int rend=-1) const = 0;\n    /// Evaluate hessian times second argument: y = y+ddf*x\n    void ddxpy(AbstractFunctionSpaceElement& y, AbstractFunctionSpaceElement const& x, int rbegin=0, int rend=-1, int cbegin=0, int cend=-1) const\n    {\n      d2axpy(1.0,y,x,rbegin,rend,cbegin,cend);\n    }\n    /// Evaluate hessian times second argument: y = y+ddf*x\n    void ddtxpy(AbstractFunctionSpaceElement& y, AbstractFunctionSpaceElement const& x, int rbegin=0, int rend=-1, int cbegin=0, int cend=-1) const\n    {\n      d2taxpy(1.0,y,x,rbegin,rend,cbegin,cend);\n    }\n    /// Evaluate hessian times second argument: y = y+a*ddf*x\n    virtual void d2axpy(double a, AbstractFunctionSpaceElement& y, AbstractFunctionSpaceElement const& x, int rbegin=0, int rend=-1, int cbegin=0, int cend=-1) const = 0;\n    /// Evaluate hessian times second argument: y = y+a*ddf*x\n    virtual void d2taxpy(double a, AbstractFunctionSpaceElement& y, AbstractFunctionSpaceElement const& x, int rbegin=0, int rend=-1, int cbegin=0, int cend=-1) const = 0;\n    /// Access matrix representation if available.\n    virtual void getMatrixBlocks(MatrixAsTriplet<double>& mat, int rbegin=0, int rend=-1, int cbegin=0, int cend=-1) const = 0;//{ assert(!\"not implemented\"); }\n    /// Get point of linearization\n    virtual AbstractFunctionSpaceElement const& getOrigin() const = 0;\n\n    virtual void precompute() = 0;\n\n    virtual void flush() = 0;\n\n    virtual ~AbstractLinearization() {}\n  };\n\n  class AbstractPreconditioner\n  {\n  public:\n    virtual void setLinearization(AbstractLinearization&) = 0;\n    virtual void apply(AbstractFunctionSpaceElement const& x, AbstractFunctionSpaceElement& Px) = 0;\n  };\n\n  /// Abstract connection.\n  /**\n   * Connect signal to flush() (in general for invalidating assembled data on grid refinement)\n   */\n  class AbstractFlushConnection\n  {\n  public:\n    virtual ~AbstractFlushConnection(){}\n    virtual void connectToSignalForFlush(boost::signals2::signal<void()>&) = 0;\n  };\n\n  class AbstractConnectedLinearization : public AbstractLinearization, public AbstractFlushConnection\n  {};\n\n  /// Representation of a nonlinear functional\n  class AbstractFunctional\n  {\n  public:\n    virtual double evaluate(AbstractFunctionSpaceElement const& x) const { assert(!\"not implemented\"); return 0; }\n    virtual std::unique_ptr<AbstractLinearization> getLinearization(AbstractFunctionSpaceElement const& x) const = 0;\n    virtual std::unique_ptr<AbstractFunctionSpaceElement> getImageVector(AbstractFunctionSpaceElement const& x) const = 0;\n    virtual bool inDomain(AbstractFunctionSpaceElement const& x) const { return true; }\n    virtual ~AbstractFunctional() {}\n  };\n\n  /// Representation of parameters\n  class AbstractParameters\n  {\n  public:\n    virtual ~AbstractParameters() {}\n  };\n\n\n  /// ...for parameter dependent functionals, implements AbstractParameters\n  template<typename ParameterType>\n  class Parameters : public AbstractParameters\n  {\n  public:\n    explicit Parameters(ParameterType const& p) : pref(p) {}\n    ParameterType const& getPars() const {return pref;}\n  private:\n    ParameterType const& pref;\n  };\n\n  ///\n  template<class ParameterType>\n  Parameters<ParameterType> makePars(ParameterType const& p) { return Parameters<ParameterType>(p); }\n\n\n  /// Creates a functional from a homotopy of functionals by inserting a parameter\n  class AbstractParameterFunctional\n  {\n  public:\n    virtual std::unique_ptr<AbstractFunctional> getFunctional(AbstractParameters const&) const = 0;\n    virtual std::unique_ptr<AbstractFunctional> getParameterLinFunctional(AbstractParameters const& p) const\n          { assert(!\"ParameterFunctional: Linearization not Implemented\"); return getFunctional(p);}\n    virtual std::unique_ptr<AbstractFunctional> getLinFunctionValue(AbstractParameters const& p) const\n          { assert(!\"ParameterFunctional: Linearization not Implemented\"); return getFunctional(p);}\n    virtual ~AbstractParameterFunctional() {}\n  };\n\n  /// Class that models the functionality of a (possibly inexact) linear solver\n  class AbstractNewtonDirection\n  {\n  public:\n    /** This method is not const, since the internal state of the solver may be modified */\n    /** Computes an undamped ordinary Newton step, i.e., \\f$correction=-F'(x)^{-1}F(x)\\f$*/\n    void ordinary(AbstractFunctionSpaceElement& correction, AbstractLinearization& linearization)\n    {  doSolve(correction, linearization);\n    correction *= -1.0;\n    }\n    /** Computes an undamped simplified Newton step, i.e., correction=-F'(xold)^{-1}F(x)*/\n    void simplified(AbstractFunctionSpaceElement& correction, AbstractLinearization const& linearization, AbstractLinearization const& oldlinearization) const\n    {  doResolve(correction, linearization, oldlinearization);\n    correction *= -1.0;\n    }\n\n    /** Computes an undamped simplified Newton step, i.e., correction=-F'(xold)^{-1}F(x)*/\n    /** where F'(xold)^{-1} has been kept from an earlier ordinary() call */\n    void simplified(AbstractFunctionSpaceElement& correction, AbstractLinearization const& linearization) const\n    {  doResolve(correction, linearization);\n    correction *= -1.0;\n    }\n\n    /// Specify accuracy that should be achieved\n    virtual void setRelativeAccuracy(double accuracy) = 0;\n    /// Specify accuracy that should be achieved\n    virtual void setAbsoluteAccuracy(double) {}\n    /// Get accuracy that was actually achieved\n    virtual double getRelativeAccuracy() = 0;\n    /// Get accuracy that was actually achieved\n    virtual double getAbsoluteAccuracy() = 0;\n\n    virtual bool improvementPossible() = 0;\n\n    virtual bool changedGrid() { return false; }\n\n    virtual ~AbstractNewtonDirection() {}\n\n    /// Solve Newton System: correction = +F'(iterate)^{-1}F(iterate)\n    virtual void doSolve(AbstractFunctionSpaceElement& correction,\n        AbstractLinearization& lin) = 0;\n    /// Solve simplified Newton system: scorrection = +F'(iterate)^{-1}F(trialIterate)\n    virtual void doResolve(AbstractFunctionSpaceElement& correction,\n        AbstractLinearization const& lin,\n        AbstractLinearization const& olin) const = 0;\n\n    /// Solve simplified Newton system: scorrection = +F'(iterate)^{-1}F(trialIterate)\n    virtual void doResolve(AbstractFunctionSpaceElement& correction,\n        AbstractLinearization const& lin) const = 0;\n\n    mutable boost::signals2::signal<void()> changed;\n  };\n\n\n  class AbstractChart\n  {\n  public:\n    virtual void addPerturbation\n    (AbstractFunctionSpaceElement& newIterate,\n        AbstractFunctionSpaceElement const& perturbation,\n        AbstractLinearization const& lin,\n        std::vector<std::shared_ptr<AbstractFunctionSpaceElement> > basis = std::vector<std::shared_ptr<AbstractFunctionSpaceElement> >()) const = 0;\n\n    virtual std::unique_ptr<AbstractChart> clone() const = 0;\n  };\n\n\n  class AbstractNorm\n  {\n  public:\n    virtual ~AbstractNorm(){}\n    virtual double operator()(AbstractFunctionSpaceElement const&) const = 0;\n    virtual void setOrigin(AbstractLinearization const&) {}\n  };\n\n  class AbstractScalarProduct : public AbstractNorm\n  {\n  public:\n    virtual double operator()(AbstractFunctionSpaceElement const&, AbstractFunctionSpaceElement const&) const = 0;\n    double operator()(AbstractFunctionSpaceElement const& v) const\n    {\n      double sc = this->operator()(v,v);\n      if(sc < 0) std::cout << \"Warning: scalar product not positive definite! Taking absolute value\" << std::endl;\n      return sqrt(std::fabs(sc));\n    }\n  };\n\n  ///Representation of an error estimate, i.e. the output of an error estimator\n  class AbstractErrorEstimate\n  {\n  public:\n    virtual double absoluteError() const = 0;\n    virtual ~AbstractErrorEstimate() {}\n  };\n\n  /// Representation of an error estimator\n  class AbstractErrorEstimator\n  {\n  public:\n    virtual std::unique_ptr<AbstractErrorEstimate> createEstimate(AbstractFunctionSpaceElement const& correction,\n        AbstractLinearization const& lin) const = 0;\n    virtual ~AbstractErrorEstimator() {}\n  };\n\n  ///Representation of an adaptive grid and a simple set of operations thereon\n  class AbstractAdaptiveGrid\n  {\n  public:\n    /// Change grid according to marked elements\n    virtual void adapt() = 0;\n    /// Mark elements, using an error estimate that hold error indicators\n    virtual void mark(AbstractErrorEstimate&, double portion) = 0;\n    /// Remove all marks in the grid\n    virtual void flushMarks() = 0;\n    /// Number of patches\n    virtual int size() = 0;\n    virtual ~AbstractAdaptiveGrid() {}\n\n    virtual int getNMarked() = 0;\n\n    /// Inform others that the grid will change\n    mutable boost::signals2::signal<void()> gridWillChange;\n  };\n\n  class AbstractHierarchicalErrorEstimator\n  {\n  public:\n    virtual ~AbstractHierarchicalErrorEstimator(){}\n\n    virtual void operator()(AbstractLinearization const& lin, AbstractFunctionSpaceElement const& x, AbstractFunctionSpaceElement const& dx, int, AbstractFunctionSpaceElement const& rhs) = 0;\n\n    virtual void refineGrid() = 0;\n\n    virtual double estimatedAbsoluteError() const = 0;\n\n    virtual size_t gridSize() const = 0;\n\n//    virtual void setNorm(AbstractNorm const&) = 0;\n  };\n\n  class ContinuousScalarFunction\n  {\n  public:\n    virtual ~ContinuousScalarFunction() {}\n    virtual double d0(std::vector<double> const&) const = 0;\n  };\n\n  class DifferentiableScalarFunction : public ContinuousScalarFunction\n  {\n  public:\n    virtual ~DifferentiableScalarFunction() {}\n\n    virtual std::vector<double> d1(std::vector<double> const&) const = 0;\n  };\n\n/** @}*/\n\n}  // namespace Kaskade\n#endif\n", "meta": {"hexsha": "5ed36249d603e76b90fff5306c6077defeb75c7d", "size": 15221, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/algorithm/abstract_interface.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/algorithm/abstract_interface.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/algorithm/abstract_interface.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 35.5630841121, "max_line_length": 191, "alphanum_fraction": 0.710203009, "num_tokens": 3619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2502690824150981}}
{"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 EIGEN_UTILS_H\n#define EIGEN_UTILS_H\n\n#include <Eigen/Core>\n#include <cassert>\n#include <complex>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <limits>\n\nnamespace flexiblesusy {\n\ntemplate <typename Derived>\nint closest_index(double mass, const Eigen::ArrayBase<Derived>& v)\n{\n   int pos;\n   typename Derived::PlainObject tmp;\n   tmp.setConstant(mass);\n\n   (v - tmp).abs().minCoeff(&pos);\n\n   return pos;\n}\n\ntemplate <class BinaryOp, class Derived>\nDerived binary_map(\n   const Eigen::DenseBase<Derived>& a, const Eigen::DenseBase<Derived>& b, BinaryOp op)\n{\n   typename Derived::PlainObject result(a.rows(), b.cols());\n\n   assert(a.rows() == b.rows());\n   assert(a.cols() == b.cols());\n\n   for (int k = 0; k < a.cols(); k++)\n      for (int i = 0; i < a.rows(); i++)\n         result(i,k) = op(a(i,k), b(i,k));\n\n   return result;\n}\n\n/**\n * Divides a by b element wise.  If the quotient is not finite, it is\n * set to zero.\n *\n * @param a numerator\n * @param b denominator\n */\ntemplate <class Derived>\nDerived div_safe(\n   const Eigen::DenseBase<Derived>& a, const Eigen::DenseBase<Derived>& b)\n{\n   using Scalar = typename Derived::Scalar;\n\n   return binary_map(a, b, [](Scalar x, Scalar y){\n         const Scalar q = x / y;\n         return std::isfinite(q) ? q : Scalar{};\n      });\n}\n\n/**\n * Calls eval() on any Eigen expression.  If the argument is not an\n * Eigen expression, the argument is returned.\n *\n * @param expr expression\n *\n * @return evaluated expression or argument\n */\ntemplate <class Derived>\nauto Eval(const Eigen::DenseBase<Derived>& expr) -> decltype(expr.eval())\n{\n   return expr.eval();\n}\n\ninline char                 Eval(char                        expr) { return expr; }\ninline short                Eval(short                       expr) { return expr; }\ninline int                  Eval(int                         expr) { return expr; }\ninline long                 Eval(long                        expr) { return expr; }\ninline unsigned short       Eval(unsigned short              expr) { return expr; }\ninline unsigned int         Eval(unsigned int                expr) { return expr; }\ninline unsigned long        Eval(unsigned long               expr) { return expr; }\ninline double               Eval(double                      expr) { return expr; }\ninline std::complex<double> Eval(const std::complex<double>& expr) { return expr; }\n\n/**\n * The element of v, which is closest to mass, is moved to the\n * position idx.\n *\n * @param idx new index of the mass eigenvalue\n * @param mass mass to compare against\n * @param v vector of masses\n * @param z corresponding mixing matrix\n */\ntemplate <typename DerivedArray, typename DerivedMatrix>\nvoid move_goldstone_to(int idx, double mass, Eigen::ArrayBase<DerivedArray>& v,\n                       Eigen::MatrixBase<DerivedMatrix>& z)\n{\n   int pos = closest_index(mass, v);\n   if (pos == idx)\n      return;\n\n   const int sign = (idx - pos) < 0 ? -1 : 1;\n   int steps = std::abs(idx - pos);\n\n   // now we shuffle the states\n   while (steps--) {\n      const int new_pos = pos + sign;\n      v.row(new_pos).swap(v.row(pos));\n      z.row(new_pos).swap(z.row(pos));\n      pos = new_pos;\n   }\n}\n\n/**\n * Normalize each element of the given real matrix to be within the\n * interval [min, max].  Values < min are set to min.  Values > max\n * are set to max.\n *\n * @param m matrix\n * @param min minimum\n * @param max maximum\n */\ntemplate <int M, int N>\nvoid normalize_to_interval(Eigen::Matrix<double,M,N>& m, double min = -1., double max = 1.)\n{\n   auto data = m.data();\n   const auto size = m.size();\n\n   for (int i = 0; i < size; i++) {\n      if (data[i] < min)\n         data[i] = min;\n      else if (data[i] > max)\n         data[i] = max;\n   }\n}\n\n/**\n * Normalize each element of the given complex matrix to have a\n * magnitude within the interval [0, max].  If the magnitude of a\n * matrix element is > max, then the magnitude is set to max.  The\n * phase angles are not modified.\n *\n * @param m matrix\n * @param max_mag maximum magnitude\n */\ntemplate <int M, int N>\nvoid normalize_to_interval(Eigen::Matrix<std::complex<double>,M,N>& m, double max_mag = 1.)\n{\n   auto data = m.data();\n   const auto size = m.size();\n\n   for (int i = 0; i < size; i++) {\n      if (std::abs(data[i]) > max_mag)\n         data[i] = std::polar(max_mag, std::arg(data[i]));\n   }\n}\n\nnamespace {\ntemplate <class T>\nstruct Is_not_finite {\n   bool operator()(T x) const noexcept { return !std::isfinite(x); }\n};\n} // anonymous namespace\n\n/**\n * Returns all elements from src, which are not close to the elements\n * in cmp.  The returned vector will have the length (src.size() -\n * cmp.size()).\n *\n * @param src source vector\n * @param cmp vector with elements to compare against\n * @return vector with elements of src not close to cmp\n */\ntemplate<class Real, int Nsrc, int Ncmp>\nEigen::Array<Real,Nsrc - Ncmp,1> remove_if_equal(\n   const Eigen::Array<Real,Nsrc,1>& src,\n   const Eigen::Array<Real,Ncmp,1>& cmp)\n{\n   Eigen::Array<Real,Nsrc,1> non_equal(src);\n   Eigen::Array<Real,Nsrc - Ncmp,1> dst;\n\n   for (int i = 0; i < Ncmp; i++) {\n      const int idx = closest_index(cmp(i), non_equal);\n      non_equal(idx) = std::numeric_limits<double>::infinity();\n   }\n\n   std::remove_copy_if(non_equal.data(), non_equal.data() + Nsrc,\n                       dst.data(), Is_not_finite<Real>());\n\n   return dst;\n}\n\n/**\n * @brief reorders vector v according to ordering in vector v2\n * @param v vector with elementes to be reordered\n * @param v2 vector with reference ordering\n */\ntemplate<class Real, int N>\nvoid reorder_vector(\n   Eigen::Array<Real,N,1>& v,\n   const Eigen::Array<Real,N,1>& v2)\n{\n   Eigen::PermutationMatrix<N> p;\n   p.setIdentity();\n   std::sort(p.indices().data(), p.indices().data() + p.indices().size(),\n             [&v2] (int i, int j) { return v2[i] < v2[j]; });\n\n#if EIGEN_VERSION_AT_LEAST(3,1,4)\n   v.matrix().transpose() *= p.inverse();\n#else\n   Eigen::Map<Eigen::Matrix<Real,N,1> >(v.data()).transpose() *= p.inverse();\n#endif\n}\n\n/**\n * @brief reorders vector v according to ordering of diagonal elements in mass_matrix\n * @param v vector with elementes to be reordered\n * @param matrix matrix with diagonal elements with reference ordering\n */\ntemplate<class Derived>\nvoid reorder_vector(\n   Eigen::Array<double,Eigen::MatrixBase<Derived>::RowsAtCompileTime,1>& v,\n   const Eigen::MatrixBase<Derived>& matrix)\n{\n   reorder_vector(v, matrix.diagonal().array().eval());\n}\n\ntemplate<class Derived>\nstd::string print_scientific(const Eigen::DenseBase<Derived>& v,\n                             int number_of_digits = std::numeric_limits<typename Derived::Scalar>::digits10 + 1)\n{\n   std::ostringstream sstr;\n\n   for (int k = 0; k < v.cols(); k++) {\n      for (int i = 0; i < v.rows(); i++) {\n         sstr << std::setprecision(number_of_digits)\n              << std::scientific << v(i,k) << ' ';\n      }\n      sstr << '\\n';\n   }\n\n   return sstr.str();\n}\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "a8fc1cca02dc4d59797cc6cbf51073977ead7e64", "size": 7815, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/src/eigen_utils.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/eigen_utils.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/eigen_utils.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": 29.3796992481, "max_line_length": 112, "alphanum_fraction": 0.6208573257, "num_tokens": 1967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2502690824150981}}
{"text": "#include \"CALPHADFreeEnergyFunctionsBinaryThreePhase.h\"\n#include \"CALPHADConcSolverBinaryThreePhase.h\"\n#include \"CALPHADFunctions.h\"\n#include \"PhysicalConstants.h\"\n#include \"functions.h\"\n#include \"well_functions.h\"\n\n#include <boost/property_tree/json_parser.hpp>\n\n#include <iomanip>\n#include <string>\n\nnamespace pt = boost::property_tree;\n\nnamespace Thermo4PFM\n{\n\nCALPHADFreeEnergyFunctionsBinaryThreePhase::\n    CALPHADFreeEnergyFunctionsBinaryThreePhase(pt::ptree& calphad_db,\n        boost::optional<pt::ptree&> newton_db,\n        const EnergyInterpolationType energy_interp_func_type,\n        const ConcInterpolationType conc_interp_func_type)\n    : energy_interp_func_type_(energy_interp_func_type),\n      conc_interp_func_type_(conc_interp_func_type),\n      newton_tol_(1.e-8),\n      newton_alpha_(1.),\n      newton_maxits_(20),\n      newton_verbose_(false)\n{\n    std::string fenergy_diag_filename(\"energy.vtk\");\n    fenergy_diag_filename_ = new char[fenergy_diag_filename.length() + 1];\n    strcpy(fenergy_diag_filename_, fenergy_diag_filename.c_str());\n\n    readParameters(calphad_db);\n\n    if (newton_db) readNewtonparameters(newton_db.get());\n}\n\n//=======================================================================\nvoid CALPHADFreeEnergyFunctionsBinaryThreePhase::readNewtonparameters(\n    pt::ptree& newton_db)\n{\n    newton_tol_     = newton_db.get<double>(\"tol\", newton_tol_);\n    newton_alpha_   = newton_db.get<double>(\"alpha\", newton_alpha_);\n    newton_maxits_  = newton_db.get<int>(\"max_its\", newton_maxits_);\n    newton_verbose_ = newton_db.get<bool>(\"verbose\", newton_verbose_);\n}\n\n//=======================================================================\nvoid CALPHADFreeEnergyFunctionsBinaryThreePhase::readParameters(\n    pt::ptree& calphad_db)\n{\n    // print database to be read\n    // std::clog << \"CALPHAD database...\" << std::endl;\n    // pt::write_json(std::clog, calphad_db);\n\n    pt::ptree& speciesA_db = calphad_db.get_child(\"SpeciesA\");\n    std::string dbnameL(\"PhaseL\");\n    g_species_phaseL_[0].initialize(\"L0\", speciesA_db.get_child(dbnameL));\n    // assert(checkSingleSublattice(speciesA_db.get_child(dbnameL)));\n    std::string dbnameA(\"PhaseA\");\n    g_species_phaseA_[0].initialize(\"A0\", speciesA_db.get_child(dbnameA));\n    // assert(checkSingleSublattice(speciesA_db.get_child(dbnameA)));\n    std::string dbnameB(\"PhaseB\");\n    g_species_phaseB_[0].initialize(\"B0\", speciesA_db.get_child(dbnameB));\n    // assert(checkSingleSublattice(speciesA_db.get_child(dbnameB)));\n\n    pt::ptree& speciesB_db = calphad_db.get_child(\"SpeciesB\");\n    g_species_phaseL_[1].initialize(\"L1\", speciesB_db.get_child(dbnameL));\n    g_species_phaseA_[1].initialize(\"A1\", speciesB_db.get_child(dbnameA));\n    g_species_phaseB_[1].initialize(\"B1\", speciesB_db.get_child(dbnameB));\n\n    // read Lmix coefficients\n    std::string dbnamemixL(\"LmixPhaseL\");\n    pt::ptree Lmix0_db = calphad_db.get_child(dbnamemixL);\n    readLmixBinary(Lmix0_db, LmixPhaseL_);\n\n    std::string dbnamemixA(\"LmixPhaseA\");\n    pt::ptree Lmix1_db = calphad_db.get_child(dbnamemixA);\n    readLmixBinary(Lmix1_db, LmixPhaseA_);\n\n    std::string dbnamemixB(\"LmixPhaseB\");\n    pt::ptree Lmix2_db = calphad_db.get_child(dbnamemixB);\n    readLmixBinary(Lmix2_db, LmixPhaseB_);\n}\n\n//-----------------------------------------------------------------------\n#ifdef HAVE_OPENMP_OFFLOAD\n#pragma omp declare target\n#endif\ndouble CALPHADFreeEnergyFunctionsBinaryThreePhase::computeFreeEnergy(\n    const double temperature, const double* const conc, const PhaseIndex pi,\n    const bool gp)\n{\n    const CalphadDataType l0 = lmixPhase(0, pi, temperature);\n    const CalphadDataType l1 = lmixPhase(1, pi, temperature);\n    const CalphadDataType l2 = lmixPhase(2, pi, temperature);\n    const CalphadDataType l3 = lmixPhase(3, pi, temperature);\n\n    CALPHADSpeciesPhaseGibbsEnergy* g_species;\n\n    switch (pi)\n    {\n        case PhaseIndex::phaseL:\n            g_species = &g_species_phaseL_[0];\n            break;\n        case PhaseIndex::phaseA:\n            g_species = &g_species_phaseA_[0];\n            break;\n        case PhaseIndex::phaseB:\n            g_species = &g_species_phaseB_[0];\n            break;\n        default:\n            //            std::cerr << \"CALPHADFreeEnergyFunctionsBinary::\"\n            //                         \"computeFreeEnergy(), undefined phase\"\n            //                      << \"!!!\" << std::endl;\n            // abort();\n            return 0.;\n    }\n\n    double fe = conc[0] * g_species[0].fenergy(temperature)\n                + (1. - conc[0]) * g_species[1].fenergy(temperature)\n                + CALPHADcomputeFMixBinary(l0, l1, l2, l3, conc[0])\n                + CALPHADcomputeFIdealMixBinary(\n                      gas_constant_R_JpKpmol * temperature, conc[0]);\n\n    // subtract -mu*c to get grand potential\n    if (gp)\n    {\n        double deriv;\n        computeDerivFreeEnergy(temperature, conc, pi, &deriv);\n        fe -= deriv * conc[0];\n    }\n\n    return fe;\n}\n\n//=======================================================================\n\nvoid CALPHADFreeEnergyFunctionsBinaryThreePhase::computeDerivFreeEnergy(\n    const double temperature, const double* const conc, const PhaseIndex pi,\n    double* deriv)\n{\n    const CalphadDataType l0 = lmixPhase(0, pi, temperature);\n    const CalphadDataType l1 = lmixPhase(1, pi, temperature);\n    const CalphadDataType l2 = lmixPhase(2, pi, temperature);\n    const CalphadDataType l3 = lmixPhase(3, pi, temperature);\n\n    CALPHADSpeciesPhaseGibbsEnergy* g_species;\n\n    switch (pi)\n    {\n        case PhaseIndex::phaseL:\n            g_species = &g_species_phaseL_[0];\n            break;\n        case PhaseIndex::phaseA:\n            g_species = &g_species_phaseA_[0];\n            break;\n        case PhaseIndex::phaseB:\n            g_species = &g_species_phaseB_[0];\n            break;\n        default:\n            //            std::cerr << \"CALPHADFreeEnergyFunctionsBinary::\"\n            //                         \"computeFreeEnergy(), undefined phase!!!\"\n            //                      << std::endl;\n            // abort();\n            return;\n    }\n\n    double mu = (g_species[0].fenergy(temperature)\n                    - g_species[1].fenergy(temperature))\n                + CALPHADcomputeFMix_derivBinary(l0, l1, l2, l3, conc[0])\n                + CALPHADcomputeFIdealMix_derivBinary(\n                      gas_constant_R_JpKpmol * temperature, conc[0]);\n\n    deriv[0] = mu;\n}\n\n//=======================================================================\n\nvoid CALPHADFreeEnergyFunctionsBinaryThreePhase::\n    computeSecondDerivativeFreeEnergy(const double temp,\n        const double* const conc, const PhaseIndex pi, double* d2fdc2)\n{\n    // assert(conc[0] >= 0.);\n    // assert(conc[0] <= 1.);\n\n    const CalphadDataType l0 = lmixPhase(0, pi, temp);\n    const CalphadDataType l1 = lmixPhase(1, pi, temp);\n    const CalphadDataType l2 = lmixPhase(2, pi, temp);\n    const CalphadDataType l3 = lmixPhase(3, pi, temp);\n    const double rt          = gas_constant_R_JpKpmol * temp;\n\n    d2fdc2[0] = (CALPHADcomputeFMix_deriv2Binary(l0, l1, l2, l3, conc[0])\n                 + CALPHADcomputeFIdealMix_deriv2Binary(rt, conc[0]));\n}\n\n//=======================================================================\n\nvoid CALPHADFreeEnergyFunctionsBinaryThreePhase::computeTdependentParameters(\n    const double temperature, CalphadDataType* Lmix_L, CalphadDataType* Lmix_A,\n    CalphadDataType* Lmix_B, CalphadDataType* fA, CalphadDataType* fB)\n{\n    fA[0]     = g_species_phaseL_[0].fenergy(temperature);\n    fB[0]     = g_species_phaseL_[1].fenergy(temperature);\n    Lmix_L[0] = lmixPhase(0, PhaseIndex::phaseL, temperature);\n    Lmix_L[1] = lmixPhase(1, PhaseIndex::phaseL, temperature);\n    Lmix_L[2] = lmixPhase(2, PhaseIndex::phaseL, temperature);\n    Lmix_L[3] = lmixPhase(3, PhaseIndex::phaseL, temperature);\n\n    fA[1]     = g_species_phaseA_[0].fenergy(temperature);\n    fB[1]     = g_species_phaseA_[1].fenergy(temperature);\n    Lmix_A[0] = lmixPhase(0, PhaseIndex::phaseA, temperature);\n    Lmix_A[1] = lmixPhase(1, PhaseIndex::phaseA, temperature);\n    Lmix_A[2] = lmixPhase(2, PhaseIndex::phaseA, temperature);\n    Lmix_A[3] = lmixPhase(3, PhaseIndex::phaseA, temperature);\n\n    fA[2]     = g_species_phaseB_[0].fenergy(temperature);\n    fB[2]     = g_species_phaseB_[1].fenergy(temperature);\n    Lmix_B[0] = lmixPhase(0, PhaseIndex::phaseB, temperature);\n    Lmix_B[1] = lmixPhase(1, PhaseIndex::phaseB, temperature);\n    Lmix_B[2] = lmixPhase(2, PhaseIndex::phaseB, temperature);\n    Lmix_B[3] = lmixPhase(3, PhaseIndex::phaseB, temperature);\n}\n\n//=======================================================================\n\n// compute equilibrium concentrations in various phases for given temperature\n\nbool CALPHADFreeEnergyFunctionsBinaryThreePhase::computeCeqT(\n    const double temperature, double* ceq, const int maxits, const bool verbose)\n{\n    // Not used since the three phases are only in equilibrium at the eutectic\n    // point\n    return false;\n}\n\n//=======================================================================\n\nvoid CALPHADFreeEnergyFunctionsBinaryThreePhase::computePhasesFreeEnergies(\n    const double temperature, const double* const hphi, const double conc,\n    double& fl, double& fa, double& fb)\n{\n    // std::cout<<\"CALPHADFreeEnergyFunctionsBinary::computePhasesFreeEnergies()\"<<endl;\n\n    double c[3] = { conc, conc, conc };\n\n    // evaluate temperature dependent parameters\n    CalphadDataType fA[3];\n    CalphadDataType fB[3];\n\n    CalphadDataType Lmix_L[4];\n    CalphadDataType Lmix_A[4];\n    CalphadDataType Lmix_B[4];\n\n    computeTdependentParameters(temperature, Lmix_L, Lmix_A, Lmix_B, fA, fB);\n\n    double RTinv = 1.0 / (gas_constant_R_JpKpmol * temperature);\n\n    CALPHADConcSolverBinaryThreePhase solver;\n    solver.setup(\n        conc, hphi[0], hphi[1], hphi[2], RTinv, Lmix_L, Lmix_A, Lmix_B, fA, fB);\n    int ret = solver.ComputeConcentration(\n        c, newton_tol_, newton_maxits_, newton_alpha_);\n    if (ret < 0)\n    {\n#if 0\n        std::cerr << \"ERROR in \"\n                     \"CALPHADFreeEnergyFunctionsBinaryThreePhase::\"\n                     \"computePhasesFreeEnergies()\"\n                     \" ---\"\n                  << \"conc=\" << conc << \", hphi=\" << hphi[0] << std::endl;\n        abort();\n#endif\n    }\n\n    // assert(c[0] >= 0.);\n    fl = computeFreeEnergy(temperature, &c[0], PhaseIndex::phaseL, false);\n\n    // assert(c[1] >= 0.);\n    fa = computeFreeEnergy(temperature, &c[1], PhaseIndex::phaseA, false);\n\n    // assert(c[1] >= 0.);\n    fb = computeFreeEnergy(temperature, &c[2], PhaseIndex::phaseB, false);\n}\n\n//-----------------------------------------------------------------------\n\nint CALPHADFreeEnergyFunctionsBinaryThreePhase::computePhaseConcentrations(\n    const double temperature, const double* const conc, const double* const phi,\n    double* x)\n{\n    // assert(x[0] >= 0.);\n    // assert(x[1] >= 0.);\n    // assert(x[0] <= 1.);\n    // assert(x[1] <= 1.);\n\n    const double RTinv = 1.0 / (gas_constant_R_JpKpmol * temperature);\n\n    CalphadDataType fA[3];\n    CalphadDataType fB[3];\n    CalphadDataType Lmix_L[4];\n    CalphadDataType Lmix_A[4];\n    CalphadDataType Lmix_B[4];\n\n    computeTdependentParameters(temperature, Lmix_L, Lmix_A, Lmix_B, fA, fB);\n\n    const double hphi0 = interp_func(conc_interp_func_type_, phi[0]);\n    const double hphi1 = interp_func(conc_interp_func_type_, phi[1]);\n    const double hphi2 = interp_func(conc_interp_func_type_, phi[2]);\n\n    // conc could be outside of [0.,1.] in a trial step\n    double c0 = conc[0] >= 0. ? conc[0] : 0.;\n    c0        = c0 <= 1. ? c0 : 1.;\n    // solve system of equations to find (cl,cs) given c0 and hphi\n    // x: initial guess and solution\n    CALPHADConcSolverBinaryThreePhase solver;\n    solver.setup(\n        c0, hphi0, hphi1, hphi2, RTinv, Lmix_L, Lmix_A, Lmix_B, fA, fB);\n    int ret = solver.ComputeConcentration(\n        x, newton_tol_, newton_maxits_, newton_alpha_);\n#if 0\n    if (ret == -1)\n    {\n        std::cerr << \"ERROR, \"\n                     \"CALPHADFreeEnergyFunctionsBinary::\"\n                     \"computePhaseConcentrations() \"\n                     \"failed for conc=\"\n                  << conc[0] << \", hphi0=\" << hphi0 << \", hphi1=\" << hphi1 << \", hphi2=\" << hphi2 << std::endl;\n        abort();\n    }\n#endif\n\n    return ret;\n}\n#ifdef HAVE_OPENMP_OFFLOAD\n#pragma omp end declare target\n#endif\n\n//-----------------------------------------------------------------------\nvoid CALPHADFreeEnergyFunctionsBinaryThreePhase::energyVsPhiAndC(\n    const double temperature, const double* const ceq, const bool found_ceq,\n    const double phi_well_scale, const int npts_phi, const int npts_c)\n{\n    // Not implemented because it is ill-defined for a three-phase system.\n}\n\n// Print out free energy as a function of phase\n// for given composition and temperature\n// File format: ASCII VTK, readble with Visit\nvoid CALPHADFreeEnergyFunctionsBinaryThreePhase::printEnergyVsPhiHeader(\n    const double temperature, const int nphi, const int nc, const double cmin,\n    const double cmax, const double slopec, std::ostream& os) const\n{\n    // Not implemented because it is ill-defined for a three-phase system\n}\n\n//=======================================================================\nvoid CALPHADFreeEnergyFunctionsBinaryThreePhase::printEnergyVsPhi(\n    const double* const conc, const double temperature,\n    const double phi_well_scale, const int npts, const double slopec,\n    std::ostream& os)\n{\n    // Not implemented because it is ill-defined for a three-phase system\n}\n\n//=======================================================================\n// compute free energy in [J/mol]\n\ndouble CALPHADFreeEnergyFunctionsBinaryThreePhase::fchem(\n    const double* const phi, const double* const conc, const double temperature)\n{\n    double hcphi[3];\n    hcphi[0] = interp_func(conc_interp_func_type_, phi[0]);\n    hcphi[1] = interp_func(conc_interp_func_type_, phi[1]);\n    hcphi[2] = interp_func(conc_interp_func_type_, phi[2]);\n\n    const double tol = 1.e-8;\n    double fl        = 0.;\n    double fa        = 0.;\n    double fb        = 0.;\n\n    bool pure_phase_0 = phi[0] > tol;\n    bool pure_phase_1 = phi[1] > tol;\n    bool pure_phase_2 = phi[2] > tol;\n\n    if ((1.0 - phi[0] > tol) && (1.0 - phi[1] > tol) && (1.0 - phi[2] > tol))\n    {\n        computePhasesFreeEnergies(temperature, hcphi, conc[0], fl, fa, fb);\n    }\n    else\n    {\n        if (1.0 - phi[0] <= tol)\n        {\n            fl = computeFreeEnergy(temperature, conc, PhaseIndex::phaseL);\n        }\n        else if (1.0 - phi[1] <= tol)\n        {\n            fa = computeFreeEnergy(temperature, conc, PhaseIndex::phaseA);\n        }\n        else\n        {\n            fb = computeFreeEnergy(temperature, conc, PhaseIndex::phaseB);\n        }\n    }\n\n    double hfphi[3];\n    hfphi[0] = interp_func(energy_interp_func_type_, phi[0]);\n    hfphi[1] = interp_func(energy_interp_func_type_, phi[1]);\n    hfphi[2] = interp_func(energy_interp_func_type_, phi[2]);\n\n    double e = hfphi[0] * fl + hfphi[1] * fa + hfphi[2];\n\n    return e;\n}\n\n//=======================================================================\n\nvoid CALPHADFreeEnergyFunctionsBinaryThreePhase::printEnergyVsComposition(\n    const double temperature, std::ostream& os, const int npts)\n{\n    const double dc = 1.0 / (double)(npts - 1);\n\n    os << \"#phi0=1\" << std::endl;\n    for (int i = 0; i < npts; i++)\n    {\n        const double conc = i * dc;\n\n        const double phi[3] = { 1., 0., 0. };\n\n        double e = fchem(phi, &conc, temperature);\n        os << conc << \"\\t\" << e << std::endl;\n    }\n    os << std::endl << std::endl;\n\n    os << \"#phi1=1\" << std::endl;\n    for (int i = 0; i < npts; i++)\n    {\n        const double conc = i * dc;\n\n        const double phi[3] = { 0., 1., 0. };\n        double e            = fchem(phi, &conc, temperature);\n        os << conc << \"\\t\" << e << std::endl;\n    }\n\n    os << \"#phi2=1\" << std::endl;\n    for (int i = 0; i < npts; i++)\n    {\n        const double conc = i * dc;\n\n        const double phi[3] = { 0., 0., 0. };\n        double e            = fchem(phi, &conc, temperature);\n        os << conc << \"\\t\" << e << std::endl;\n    }\n}\n\n//=======================================================================\n\nvoid CALPHADFreeEnergyFunctionsBinaryThreePhase::preRunDiagnostics(\n    const double T0, const double T1)\n{\n    std::ofstream os1(\"FlC0vsT.dat\", std::ios::out);\n    os1 << \"#Species 0, Phase L\" << std::endl;\n    g_species_phaseL_[0].plotFofT(os1, T0, T1);\n\n    std::ofstream os2(\"FlC1vsT.dat\", std::ios::out);\n    os2 << \"#Species 1, Phase L\" << std::endl;\n    g_species_phaseL_[1].plotFofT(os2, T0, T1);\n\n    std::ofstream os3(\"FsC0vsT.dat\", std::ios::out);\n    os3 << \"#Species 0, Phase A\" << std::endl;\n    g_species_phaseA_[0].plotFofT(os3, T0, T1);\n\n    std::ofstream os4(\"FsC1vsT.dat\", std::ios::out);\n    os4 << \"#Species 1, Phase A\" << std::endl;\n    g_species_phaseA_[1].plotFofT(os4, T0, T1);\n}\n}\n", "meta": {"hexsha": "8dc30ef54692d406b43761f3c251e55e5ffee6f9", "size": 17020, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/CALPHADFreeEnergyFunctionsBinaryThreePhase.cc", "max_stars_repo_name": "stvdwtt/Thermo4PFM", "max_stars_repo_head_hexsha": "5308b7c58c4b67ed98d2bd50469226b7d89da2b8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2022-01-21T17:39:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T21:00:24.000Z", "max_issues_repo_path": "src/CALPHADFreeEnergyFunctionsBinaryThreePhase.cc", "max_issues_repo_name": "stvdwtt/Thermo4PFM", "max_issues_repo_head_hexsha": "5308b7c58c4b67ed98d2bd50469226b7d89da2b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-21T16:51:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T16:51:52.000Z", "max_forks_repo_path": "src/CALPHADFreeEnergyFunctionsBinaryThreePhase.cc", "max_forks_repo_name": "stvdwtt/Thermo4PFM", "max_forks_repo_head_hexsha": "5308b7c58c4b67ed98d2bd50469226b7d89da2b8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-12-13T14:29:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T18:12:51.000Z", "avg_line_length": 35.5323590814, "max_line_length": 111, "alphanum_fraction": 0.6064042303, "num_tokens": 4681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710085, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.25007816701485164}}
{"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 \"qp.h\"\n#include \"util.h\"\n#include <Eigen/Dense>\n\n// #define VERBOSE\n#ifdef VERBOSE\n#include <iostream>\n#endif\n\nconst int MAX_ITER = 1000;\n\nstruct ActiveSet {\n\tint n;       // Current size\n\tArrayXb in; // in(i) : Is variable i in the active set\n\tArrayXi A;  // All variables in the active set\n\tActiveSet( int max_n=0 ):n(0),in(ArrayXb::Zero(max_n)),A(-ArrayXi::Ones(max_n)){}\n\tint add( int i ) { // Add variable i to the active set\n\t\teassert( !in[i] );\n\t\tin[i] = true;\n\t\tA(n) = i;\n\t\treturn n++;\n\t}\n\tvoid removeLast() { // Remove the last entry from the active set\n\t\teassert( n > 0 );\n\t\t--n;\n\t\teassert( in[A(n)] );\n\t\tin[A(n)] = false;\n\t\tA(n) = -1;\n\t}\n};\n\ntemplate<typename T>\nT dist( T a, T b ) {\n\ta = std::abs(a);\n\tb = std::abs(b);\n\tif (a > b) return a*std::sqrt(1 + (b/a)*(b/a));\n\tif (a < b) return b*std::sqrt(1 + (a/b)*(a/b));\n\treturn a*std::sqrt(2.0);\n}\n\ntemplate<typename T>\nbool addConstraint( RMatrixX<T> & R, RMatrixX<T> & J, VectorX<T> d, ActiveSet & active_set, int l ) {\n\tconst int n = R.rows();\n\tconst int na = active_set.n;\n\t/* Givens rotation Vodoo */\n\tfor( int j=n-1; j>na; j-- ) {\n\t\tT cc = d[j-1], ss = d[j];\n\t\tT h = dist( cc, ss );\n\t\tif( h == 0 )\n\t\t\tcontinue;\n\t\td[j] = 0;\n\t\tss /= h;\n\t\tcc /= h;\n\t\tif( cc < 0 ){\n\t\t\tcc =-cc;\n\t\t\tss =-ss;\n\t\t\td[j-1] = -h;\n\t\t}\n\t\telse\n\t\t\td[j-1] = h;\n\t\tT xny = ss / (1. + cc);\n\t\tRowVectorX<T> t1 = J.row(j-1);\n\t\tRowVectorX<T> t2 = J.row(j);\n\t\tJ.row(j-1) = t1*cc + t2*ss;\n\t\tJ.row(j)   = xny * (t1 + J.row(j-1)) - t2;\n\t}\n\tactive_set.add( l );\n\tR.col(na).head(na+1) = d.head(na+1);\n\tif( na > 0 && std::abs(d[na]) <= std::numeric_limits<T>::epsilon() * R.diagonal().head(na).array().abs().maxCoeff() )\n\t\t// Degenerate R\n\t\treturn false;\n\treturn true;\n}\n\ntemplate<typename T>\nvoid deleteConstraint( RMatrixX<T> & R, RMatrixX<T> & J, VectorX<T> & u, ActiveSet & active_set, int l ) {\n\tconst int n = active_set.n;\n\t// Find the element to remove\n\tint qq = -1;\n\tfor( int i=0; i<n; i++ )\n\t\tif( active_set.A[i] == l ){\n\t\t\tqq = i;\n\t\t\tbreak;\n\t\t}\n\teassert( qq >= 0 );\n\t\n\t// Move all elements that follow down by ones and update the QR factorization\n\tfor( int i=qq; i < n-1; i++ ) {\n\t\tu[i] = u[i+1];\n\t\tR.col(i) = R.col(i+1);\n\t\tactive_set.A[i] = active_set.A[i+1];\n\t}\n\t// And remove the last element from the active set\n\tR.col(n-1).setZero();\n\tu[n-1] = 0;\n\tactive_set.A[n-1] = l;\n\tactive_set.removeLast();\n\t/* Some more givens rotation Vodoo to restore R and J */\n\tfor( int j = qq; j < n-1; j++ ) {\n\t\tT cc = R(j,j), ss = R(j+1,j);\n\t\tT h = dist( cc, ss );\n\t\tif( h == 0 )\n\t\t\tcontinue;\n\t\tR(j+1,j) = 0;\n\t\tss /= h;\n\t\tcc /= h;\n\t\tif( cc < 0 ){\n\t\t\tcc =-cc;\n\t\t\tss =-ss;\n\t\t\tR(j,j) = -h;\n\t\t}\n\t\telse\n\t\t\tR(j,j) = h;\n\t\tT xny = ss / (1. + cc);\n\t\tconst int nr = n-j-1;\n\t\tif( nr>0 ) {\n\t\t\tRowVectorX<T> t1 = R.row(j).segment(j+1,nr);\n\t\t\tRowVectorX<T> t2 = R.row(j+1).segment(j+1,nr);\n\t\t\tR.row(j).segment(j+1,nr)   = t1*cc + t2*ss;\n\t\t\tR.row(j+1).segment(j+1,nr) = xny * (t1 + R.row(j).segment(j+1,nr)) - t2;\n\t\t}\n\t\t{\n\t\t\tRowVectorX<T> t1 = J.row(j);\n\t\t\tRowVectorX<T> t2 = J.row(j+1);\n\t\t\tJ.row(j)   = t1*cc + t2*ss;\n\t\t\tJ.row(j+1) = xny * (t1 + J.row(j)) - t2;\n\t\t}\n\t}\n}\n\n// Solves a strictly convex QP of the form\n//  minimize_x  x' Q x  +  c' x\n//  subject to  A x <= b\ntemplate<typename T>\nVectorX<T> qp( const RMatrixX<T> & Q, const VectorX<T> & c, const RMatrixX<T> & A, const VectorX<T> & b ) {\n#ifdef VERBOSE\n\tprintf(\"=================== SOLVING THE QP ===================\\n\" );\n#endif\n\tconst int n = c.size(), m = b.size();\n\tconst T inf = std::numeric_limits<T>::infinity();\n\t\n\tif( Q.cols() != n || Q.rows() != n )\n\t\tthrow std::invalid_argument( \"Expected quadratic matrix Q of size n x n, where n=|c|!\" );\n\tif( A.cols() != n || A.rows() != m )\n\t\tthrow std::invalid_argument( \"Expected inequality constraint matrix A of size |b| x n!\" );\n\t\n\tRMatrixX<T> R = RMatrixX<T>::Zero(n,n), J = RMatrixX<T>::Zero(n,n);\n\tActiveSet active_set(m);\n\tVectorX<T> x = VectorX<T>::Zero(n), s = VectorX<T>::Zero(m), u = VectorX<T>::Zero(m);\n\t\n\t/*\n\t * Preprocessing phase\n\t */\n\t\n\t/* decompose the matrix Q in the form LL^T */\n\tLLT<RMatrixX<T>,Lower> chol(Q);\n\t\n\t/* compute the inverse of the factorized matrix Q^-1, this is the initial value for J */\n\t// J = L^-1\n\tJ = chol.matrixL().solve(RMatrixX<T>::Identity(n,n));\n\n\t/*\n\t * Find the unconstrained minimizer x, which is a feasible point in the dual space\n\t * x = -Q^-1 * c\n\t */\n\tx = -chol.solve(c);\n\tfor( int iter=0; iter < MAX_ITER; iter++ ) {\n\t\t\n\t\t/* step 1: choose a violated constraint */\n\t\t\n\t\t/* compute s(x) = - A * x + b for all elements of K \\ A */\n\t\ts = -A * x + b;\n\t\t\n#ifdef VERBOSE\n\t\tprintf(\"Iteration %d   %f %f\\n\", iter, std::abs(s.array().min(0.f).sum())/m, std::numeric_limits<T>::epsilon() );\n#endif\n\t\t\n\t\t/* Are there any more infeasibilities? |s|_1 < EPS*cond*100 */\n\t\tif ( -s.minCoeff() <= 100*std::numeric_limits<T>::epsilon() )\n\t\t\treturn x;\n\t\t\n\t\t/* Step 2: check for feasibility and determine a new S-pair */\n\t\tint new_constraint = 0;\n\t\tT ss = VectorX<T>(s.array() * ((T)1-active_set.in.cast<T>())).minCoeff( &new_constraint );\n\t\t\n\t\t/* Are all constraints feasible? */\n\t\tif (ss >= 0.0) return x;\n\t\t\n\t\t/* Get the new constraint */\n\t\tVectorX<T> np = -A.row(new_constraint).transpose();\n\t\t\n#ifdef VERBOSE\n\t\tprintf(\"New constraint %d / %d\\n\", new_constraint, m);\n#endif\n\t\t/* Step 2a: determine step direction and take partial steps */\n\t\t/* compute z = H np: the step direction in the primal space (through J, see the paper) */\n\t\tT unA = 0; // u(nA)\n\t\twhile(1) {\n\t\t\t/* Get the number of active constraints */\n\t\t\tconst int nA = active_set.n;\n\t\t\t\n\t\t\tVectorX<T> d = J * np;\n\t\t\tVectorX<T> z = J.bottomRows(d.size()-nA).transpose() * d.tail(d.size()-nA);\n\t\t\t\n\t\t\t/* compute N* np (if q > 0): the negative of the step direction in the dual space */\n\t\t\tVectorX<T> r = R.topLeftCorner(nA,nA).template triangularView<Upper>().solve(d.head(nA));\n\t\t\t\n\t\t\t/* Step 2b: compute step length t1 before violating dual feasibility */\n\t\t\tint l = -1;\n\t\t\tT t1 = inf;\n\t\t\tif( r.size() > 0 ) {\n\t\t\t\tt1 = (r.array() > 0).select( u.head(nA).array() / r.array(), inf ).minCoeff( &l );\n\t\t\t\tl = active_set.A[l];\n\t\t\t}\n\t\t\t\n\t\t\t/* Compute t2: full step length (minimum step in primal space such that the constraint ip becomes feasible */\n\t\t\tT t2 = inf;\n\t\t\tif (std::abs(z.dot(z)) > std::numeric_limits<T>::epsilon()) // i.e. z != 0\n\t\t\t\tt2 = -ss / z.dot(np);\n\t\t\t\n\t\t\t/* the step is chosen as the minimum of t1 and t2 */\n\t\t\tT t = std::min<T>(t1, t2);\n\t\t\t\n// #ifdef VERBOSE\n// \t\t\tprintf(\"  t = %f  %f %f    l = %d\\n\", t, t1, t2, l );\n// \t\t\tstd::cout<<\"  ss = \"<<ss<<\"  z'np = \"<<z.dot(np)<<std::endl;\n// \t\t\tstd::cout<<\"  x = \"<<x.transpose()<<std::endl;\n// \t\t\tstd::cout<<\"  s = \"<<s.transpose()<<std::endl;\n// \t\t\tstd::cout<<\"  np = \"<<np.transpose()<<std::endl;\n// \t\t\tstd::cout<<\"  u = \"<<u.head(nA).transpose()<<std::endl;\n// \t\t\tstd::cout<<\"  r = \"<<r.transpose()<<std::endl;\n// \t\t\tstd::cout<<\"  z = \"<<z.transpose()<<std::endl;\n// \t\t\tstd::cout<<\"  d = \"<<d.transpose()<<std::endl;\n// \t\t\tstd::cout<<\"  R = \"<<R.topLeftCorner(nA,nA)<<std::endl;\n// \t\t\tstd::cout<<\"  J = \"<<J<<std::endl;\n// #endif\n\t\t\t\n\t\t\t/* Step 2c: determine new S-pair and take step: */\n\t\t\t\n\t\t\t/* case (i): no step in primal or dual space */\n\t\t\tif (t >= inf) /* QPP is infeasible */\n\t\t\t\treturn VectorX<T>::Constant( n, inf );\n\t\t\t\n\t\t\t// Dual step\n\t\t\tu.head(nA) -= t * r;\n\t\t\tunA += t;\n\t\t\t\n\t\t\t// Primal step\n\t\t\tif( t2 < inf ) {\n\t\t\t\tx += t * z;\n\t\t\t\tss = -A.row(new_constraint) * x + b(new_constraint);\n\t\t\t}\n\t\t\t\n\t\t\t/* case (ii): a patial step has taken */\n\t\t\tif (t2 > t1) {\n#ifdef VERBOSE\n\t\t\t\tprintf(\"  * delete %d\\n\", l );\n#endif\n\t\t\t\t/* drop constraint l from the active set A */\n\t\t\t\tdeleteConstraint<T>(R, J, u, active_set, l);\n\t\t\t}\n\t\t\telse \n\t\t\t\tbreak;\n\t\t}\n\t\t/* case (iii): step in primal and dual space */\n\t\t/* full step has been taken */\n\t\t/* add constraint ip to the active set*/\n#ifdef VERBOSE\n\t\tprintf(\"  * add %d\\n\", new_constraint );\n#endif\n\t\tif (!addConstraint<T>(R, J, J*np, active_set, new_constraint))\n\t\t\tthrow std::invalid_argument( \"Degenerate R matrix, going to give up!\" );\n\t\tu[active_set.n-1] = unA; // Update the lagrangian variable\n\t}\n\treturn x;\n}\n\n\n// Solves a strictly convex sparse QP of the form\n//  minimize_x  x' diag(Q) x  +  c' x\n//  subject to  A x <= b\ntemplate<typename T>\nVectorX<T> sparseQp( const VectorX<T> & Q, const VectorX<T> & c, const SRMatrixX<T> & A, const VectorX<T> & b ) {\n\tconst int n = c.size(), m = b.size();\n\tconst T inf = std::numeric_limits<T>::infinity();\n\t\n\tif( Q.size() != n )\n\t\tthrow std::invalid_argument( \"Expected vector Q of size n=|c|!\" );\n\tif( A.cols() != n || A.rows() != m )\n\t\tthrow std::invalid_argument( \"Expected inequality constraint matrix A of size |b| x n!\" );\n\t\n\tRMatrixX<T> R = RMatrixX<T>::Zero(n,n), J = RMatrixX<T>::Zero(n,n);\n\tActiveSet active_set(m);\n\tVectorX<T> x = VectorX<T>::Zero(n), s = VectorX<T>::Zero(m), u = VectorX<T>::Zero(m);\n\t\n\t/*\n\t * Preprocessing phase\n\t */\n\t\n\t/* decompose the matrix Q in the form LL^T */\n\tconst VectorX<T> L_inv = 1.0 / Q.array().sqrt();\n\t\n\t/* compute the inverse of the factorized matrix Q^-1, this is the initial value for J */\n\t// J = L^-1\n\tJ = L_inv.asDiagonal();\n\t\n\t/*\n\t * Find the unconstrained minimizer x, which is a feasible point in the dual space\n\t * x = -Q^-1 * c\n\t */\n\tx = -c.array() / Q.array();\n\tfor( int iter=0; iter < MAX_ITER; iter++ ) {\n\t\t\n\t\t/* step 1: choose a violated constraint */\n\t\t\n\t\t/* compute s(x) = - A * x + b for all elements of K \\ A */\n\t\ts = -A * x + b;\n\t\t\n#ifdef VERBOSE\n\t\tprintf(\"Iteration %d  %f %f\\n\", iter, std::abs(s.array().min(0.f).sum())/m, std::numeric_limits<T>::epsilon());\n#endif\n\t\t\n\t\t/* Are there any more infeasibilities? |s|_1 < EPS*cond*100 */\n\t\tif ( -s.minCoeff() <= std::numeric_limits<T>::epsilon() )\n\t\t\treturn x;\n\t\t\n\t\t/* Step 2: check for feasibility and determine a new S-pair */\n\t\tint new_constraint = 0;\n\t\tT ss = VectorX<T>(s.array() * ((T)1-active_set.in.cast<T>())).minCoeff( &new_constraint );\n\t\t\n\t\t/* Are all constraints feasible? */\n\t\tif (ss >= 0.0) return x;\n\t\t\n\t\t/* Get the new constraint */\n\t\tVectorX<T> np = -RowVectorX<T>(A.row(new_constraint)).transpose();\n\t\t\n#ifdef VERBOSE\n\t\tprintf(\"New constraint %d / %d\\n\", new_constraint, m);\n#endif\n\t\t/* Step 2a: determine step direction and take partial steps */\n\t\t/* compute z = H np: the step direction in the primal space (through J, see the paper) */\n\t\tT unA = 0; // u(nA)\n\t\twhile(1) {\n\t\t\t/* Get the number of active constraints */\n\t\t\tconst int nA = active_set.n;\n\t\t\t\n\t\t\tVectorX<T> d = J * np;\n\t\t\tVectorX<T> z = J.bottomRows(d.size()-nA).transpose() * d.tail(d.size()-nA);\n\t\t\t\n\t\t\t/* compute N* np (if q > 0): the negative of the step direction in the dual space */\n\t\t\tVectorX<T> r = R.topLeftCorner(nA,nA).template triangularView<Upper>().solve(d.head(nA));\n\t\t\t\n\t\t\t/* Step 2b: compute step length t1 before violating dual feasibility */\n\t\t\tint l = -1;\n\t\t\tT t1 = inf;\n\t\t\tif( r.size() > 0 ) {\n\t\t\t\tt1 = (r.array() > 0).select( u.head(nA).array() / r.array(), inf ).minCoeff( &l );\n\t\t\t\tl = active_set.A[l];\n\t\t\t}\n\t\t\t\n\t\t\t/* Compute t2: full step length (minimum step in primal space such that the constraint ip becomes feasible */\n\t\t\tT t2 = inf;\n\t\t\tif (std::abs(z.dot(z)) > std::numeric_limits<T>::epsilon()) // i.e. z != 0\n\t\t\t\tt2 = -ss / z.dot(np);\n\t\t\t\n\t\t\t/* the step is chosen as the minimum of t1 and t2 */\n\t\t\tT t = std::min<T>(t1, t2);\n\t\t\t\n#ifdef VERBOSE\n\t\t\tprintf(\"  t = %f  %f %f    l = %d\\n\", t, t1, t2, l );\n\t\t\tstd::cout<<\"  ss = \"<<ss<<\"  z'np = \"<<z.dot(np)<<std::endl;\n\t\t\tstd::cout<<\"  x = \"<<x.transpose()<<std::endl;\n\t\t\tstd::cout<<\"  s = \"<<s.transpose()<<std::endl;\n\t\t\tstd::cout<<\"  np = \"<<np.transpose()<<std::endl;\n\t\t\tstd::cout<<\"  u = \"<<u.head(nA).transpose()<<std::endl;\n\t\t\tstd::cout<<\"  r = \"<<r.transpose()<<std::endl;\n\t\t\tstd::cout<<\"  z = \"<<z.transpose()<<std::endl;\n\t\t\tstd::cout<<\"  d = \"<<d.transpose()<<std::endl;\n\t\t\tstd::cout<<\"  R = \"<<R.topLeftCorner(nA,nA)<<std::endl;\n\t\t\tstd::cout<<\"  J = \"<<J<<std::endl;\n#endif\n\t\t\t\n\t\t\t/* Step 2c: determine new S-pair and take step: */\n\t\t\t\n\t\t\t/* case (i): no step in primal or dual space */\n\t\t\tif (t >= inf) /* QPP is infeasible */\n\t\t\t\treturn VectorX<T>::Constant( n, inf );\n\t\t\t\n\t\t\t// Dual step\n\t\t\tu.head(nA) -= t * r;\n\t\t\tunA += t;\n\t\t\t\n\t\t\t// Primal step\n\t\t\tif( t2 < inf ) {\n\t\t\t\tx += t * z;\n\t\t\t\tss = np.dot( x ) + b(new_constraint);\n\t\t\t}\n\t\t\t\n\t\t\t/* case (ii): a patial step has taken */\n\t\t\tif (t2 > t1) {\n#ifdef VERBOSE\n\t\t\t\tprintf(\"  * delete %d\\n\", l );\n#endif\n\t\t\t\t/* drop constraint l from the active set A */\n\t\t\t\tdeleteConstraint<T>(R, J, u, active_set, l);\n\t\t\t}\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\t\t/* case (iii): step in primal and dual space */\n\t\t/* full step has been taken */\n\t\t/* add constraint ip to the active set*/\n#ifdef VERBOSE\n\t\tprintf(\"  * add %d\\n\", new_constraint );\n#endif\n\t\tif (!addConstraint<T>(R, J, J*np, active_set, new_constraint))\n\t\t\tthrow std::invalid_argument( \"Degenerate R matrix, going to give up!\" );\n\t\tu[active_set.n-1] = unA; // Update the lagrangian variable\n\t}\n\treturn x;\n}\n\nVectorXf qp( const RMatrixXf & Q, const VectorXf & c, const RMatrixXf & A, const VectorXf & b ) {\n\treturn qp<float>( Q, c, A, b );\n}\nVectorXd qp( const RMatrixXd & Q, const VectorXd & c, const RMatrixXd & A, const VectorXd & b ) {\n\treturn qp<double>( Q, c, A, b );\n}\nVectorXf sparseQp( const VectorXf & Q, const VectorXf & c, const SRMatrixXf & A, const VectorXf & b ) {\n\treturn sparseQp<float>( Q, c, A, b );\n}\nVectorXd sparseQp( const VectorXd & Q, const VectorXd & c, const SRMatrixXd & A, const VectorXd & b ) {\n\treturn sparseQp<double>( Q, c, A, b );\n}\n\n", "meta": {"hexsha": "f2f0272131ac8a98cfea5e44d6b24c4347e91e26", "size": 14998, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sd_maskrcnn/gop/lib/util/qp.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/util/qp.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/util/qp.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": 32.4632034632, "max_line_length": 118, "alphanum_fraction": 0.5933457794, "num_tokens": 4885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.25004598316540727}}
{"text": "\n#include <general/nmspc_tensor_extra.h>\n#include <general/nmspc_tensor_omp.h>\n#include <tools/common/contraction.h>\n#include <tools/common/fmt.h>\n\n\n\n#include <iostream>\n#include <Eigen/IterativeLinearSolvers>\n#include <unsupported/Eigen/IterativeSolvers>\n\ntemplate<typename Scalar_> class MatrixReplacement;\ntemplate<typename T> using DenseMatrix = Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>;\n\nnamespace Eigen {\n    namespace internal {\n// MatrixReplacement looks-like a SparseMatrix, so let's inherits its traits:\n        template<typename Scalar_>\n        struct traits<MatrixReplacement<Scalar_>> :  public Eigen::internal::traits<DenseMatrix<Scalar_> >\n        {};\n    }\n}\n\n// Example of a matrix-free wrapper from a user type to Eigen's compatible type\n// For the sake of simplicity, this example simply wrap a Eigen::Matrix.\ntemplate<typename Scalar_>\nclass MatrixReplacement : public Eigen::EigenBase<MatrixReplacement<Scalar_>> {\n    public:\n    // Required typedefs, constants, and method:\n    typedef Scalar_ Scalar;\n    typedef double RealScalar;\n    typedef int StorageIndex;\n    enum {\n        ColsAtCompileTime = Eigen::Dynamic,\n        MaxColsAtCompileTime = Eigen::Dynamic,\n        IsRowMajor = false\n    };\n\n\n    const Scalar_ *     envL = nullptr;\n    const Scalar_ *     envR = nullptr;\n    const Scalar_ *     mpo = nullptr;\n    std::array<long, 3> shape_mps;\n    std::array<long, 4> shape_mpo;\n    std::array<long, 3> shape_envL;\n    std::array<long, 3> shape_envR;\n    std::vector<Scalar> shift_mpo;\n    long                mps_size;\n//    eig::Form           form = eig::Form::SYMM;\n//    eig::Side           side = eig::Side::R;\n    // Profiling\n//    std::unique_ptr<class_tic_toc> t_multAx;\n    mutable int         counter = 0;\n    mutable std::vector<Scalar> tmp;\n\n\n    [[nodiscard]] Eigen::Index rows() const { return static_cast<int>(mps_size); }; /*!< Linear size\\f$d^2 \\times \\chi_L \\times \\chi_R \\f$  */\n    [[nodiscard]] Eigen::Index cols() const { return static_cast<int>(mps_size); }; /*!< Linear size\\f$d^2 \\times \\chi_L \\times \\chi_R \\f$  */\n\n    template<typename Rhs>\n    Eigen::Product<MatrixReplacement,Rhs,Eigen::AliasFreeProduct> operator*(const Eigen::MatrixBase<Rhs>& x) const {\n        return Eigen::Product<MatrixReplacement,Rhs,Eigen::AliasFreeProduct>(*this, x.derived());\n    }\n\n    // Custom API:\n    MatrixReplacement()  = default;\n\n    void attachTensors(\n        const Scalar_ *     envL_,      /*!< The left block tensor.  */\n        const Scalar_ *     envR_,      /*!< The right block tensor.  */\n        const Scalar_ *     mpo_,       /*!< The Hamiltonian MPO's  */\n        std::array<long, 3> shape_mps_, /*!< An array containing the shapes of the mps  */\n        std::array<long, 4> shape_mpo_  /*!< An array containing the shapes of the mpo  */\n    ){\n        envL       = envL_;\n        envR       = envR_;\n        mpo        = mpo_;\n        shape_mps  = shape_mps_;\n        shape_mpo  = shape_mpo_;\n        shape_envL = {shape_mps_[1], shape_mps_[1], shape_mpo_[0]};\n        shape_envR = {shape_mps_[2], shape_mps_[2], shape_mpo_[1]};\n        if(envL == nullptr) throw std::runtime_error(\"Lblock is a nullptr!\");\n        if(envR == nullptr) throw std::runtime_error(\"Rblock is a nullptr!\");\n        if(mpo == nullptr) throw std::runtime_error(\"mpo is a nullptr!\");\n        mps_size = shape_mps[0] * shape_mps[1] * shape_mps[2];\n//        t_multAx = std::make_unique<class_tic_toc>(true, 5, \"Time MultAx\");\n    }\n\n};\n\n\n// Implementation of MatrixReplacement * Eigen::DenseVector though a specialization of internal::generic_product_impl:\nnamespace Eigen {\n    namespace internal {\n\n        template<typename Rhs, typename ReplScalar>\n        struct generic_product_impl<MatrixReplacement<ReplScalar>, Rhs, DenseShape, DenseShape, GemvProduct> // GEMV stands for matrix-vector\n            : generic_product_impl_base<MatrixReplacement<ReplScalar>,Rhs,generic_product_impl<MatrixReplacement<ReplScalar>,Rhs> >\n        {\n            typedef typename Product<MatrixReplacement<ReplScalar>,Rhs>::Scalar Scalar;\n\n            template<typename Dest>\n            static void scaleAndAddTo(Dest& dst, const MatrixReplacement<ReplScalar>& mat, const Rhs& rhs, const Scalar& alpha)\n            {\n                // This method should implement \"dst += alpha * lhs * rhs\" inplace,\n                // however, for iterative solvers, alpha is always equal to 1, so let's not worry about it.\n                assert(alpha==Scalar(1) && \"scaling is not implemented\");\n                EIGEN_ONLY_USED_FOR_DEBUG(alpha);\n\n//                auto token = mat.t_multAx->tic_token();\n                mat.tmp.resize(static_cast<size_t>(dst.size()));\n                Eigen::Map<Dest> tmp_map (mat.tmp.data(), dst.size());\n//                std::cout << \"dst size \" << dst.size() << \" | rhs size \" << rhs.size() << std::endl;\n//                if(dst.size() != rhs.size())\n//                    dst.conservativeResize(rhs.size());\n\n                tools::common::contraction::matrix_vector_product(tmp_map.data(), rhs.data(), mat.shape_mps,\n                                                                  mat.mpo,  mat.shape_mpo,\n                                                                  mat.envL, mat.shape_envL,\n                                                                  mat.envR, mat.shape_envR);\n\n                dst.noalias() += tmp_map;\n                mat.counter++;\n//\n//                // Here we could simply call dst.noalias() += lhs.my_matrix() * rhs,\n//                // but let's do something fancier (and less efficient):\n//                for(Index i=0; i<lhs.cols(); ++i)\n//                    dst += rhs(i) * lhs.my_matrix().col(i);\n            }\n        };\n\n    }\n}\n\n\n\n\n\n\n/* clang-format off */\ntemplate<typename Scalar>\nvoid tools::common::contraction::matrix_inverse_vector_product(Scalar * res_ptr,\n                                                       const Scalar * const mps_ptr, std::array<long,3> mps_dims,\n                                                       const Scalar * const mpo_ptr, std::array<long,4> mpo_dims,\n                                                       const Scalar * const envL_ptr, std::array<long,3> envL_dims,\n                                                       const Scalar * const envR_ptr, std::array<long,3> envR_dims){\n\n\n        // Here we return x <-- A^-1 * b\n        // Where A^-1 * b is obtained by solving\n        //       A*x = b\n        // using an iterative matrix-free solver.\n        {\n            auto mps = Eigen::TensorMap<const Eigen::Tensor<const Scalar,3>>(mps_ptr,mps_dims);\n            auto mpo = Eigen::TensorMap<const Eigen::Tensor<const Scalar,4>>(mpo_ptr,mpo_dims);\n            auto envL = Eigen::TensorMap<const Eigen::Tensor<const Scalar,3>>(envL_ptr,envL_dims);\n            auto envR = Eigen::TensorMap<const Eigen::Tensor<const Scalar,3>>(envR_ptr,envR_dims);\n\n            if(mps.dimension(1) != envL.dimension(0))\n                throw std::runtime_error(fmt::format(\"Dimension mismatch mps {} and envL {}\", mps.dimensions(), envL.dimensions()));\n            if(mps.dimension(2) != envR.dimension(0))\n                throw std::runtime_error(fmt::format(\"Dimension mismatch mps {} and envR {}\", mps.dimensions(), envR.dimensions()));\n            if(mps.dimension(0) != mpo.dimension(2)) throw std::runtime_error(fmt::format(\"Dimension mismatch mps {} and mpo {}\", mps.dimensions(), mpo.dimensions()));\n            if(envL.dimension(2) != mpo.dimension(0))\n                throw std::runtime_error(fmt::format(\"Dimension mismatch envL {} and mpo {}\", envL.dimensions(), mpo.dimensions()));\n            if(envR.dimension(2) != mpo.dimension(1))\n                throw std::runtime_error(fmt::format(\"Dimension mismatch envR {} and mpo {}\", envR.dimensions(), mpo.dimensions()));\n        }\n\n        // Define the \"matrix-free\" matrix replacement.\n        MatrixReplacement<Scalar> matRepl;\n        matRepl.attachTensors(envL_ptr, envR_ptr, mpo_ptr, mps_dims, mpo_dims);\n\n        Eigen::Index MaxIters = 200000;\n        double tolerance = 1e-14;\n        Eigen::Map<Textra::VectorType<Scalar>> res(res_ptr, matRepl.rows());\n        Eigen::Map<const Textra::VectorType<Scalar>> mps(mps_ptr, matRepl.rows());\n        if constexpr (std::is_same_v<Scalar,std::complex<double>>){\n\n            Eigen::BiCGSTAB<MatrixReplacement<Scalar>, Eigen::IdentityPreconditioner> bicg;\n            bicg.compute(matRepl);\n            bicg.setMaxIterations(MaxIters);\n            bicg.setTolerance(tolerance);\n            res = bicg.solve(mps);\n//            std::cout << \"BiCGSTAB: #iterations: \" << bicg.iterations()\n//                << \", #count: \" << matRepl.counter\n//                << \", estimated error: \" << bicg.error()\n//                << std::endl;\n\n        }\n//        {\n//            Eigen::ConjugateGradient<MatrixReplacement<Scalar>, Eigen::Lower|Eigen::Upper, Eigen::IdentityPreconditioner> cg;\n//            cg.setMaxIterations(20000);\n//            cg.compute(matRepl);\n//            res = cg.solve(mps);\n//            std::cout << \"CG      : #iterations: \" << cg.iterations()\n//                      << \", #count: \" << matRepl.counter\n//                      << \", estimated error: \" << cg.error()\n//                      << std::endl;\n//        }\n        if constexpr (std::is_same_v<Scalar,double>){\n            Eigen::MINRES<MatrixReplacement<Scalar>, Eigen::Lower|Eigen::Upper, Eigen::IdentityPreconditioner> minres;\n            minres.setMaxIterations(MaxIters);\n            minres.setTolerance(tolerance);\n            minres.compute(matRepl);\n            res = minres.solve(mps);\n            std::cout << \"MINRES:   #iterations: \" << minres.iterations()\n                      << \", #count: \" << matRepl.counter\n                      << \", norm: \" << res.norm()\n                      << \", estimated error: \" << minres.error()\n                      << std::endl;\n    //    std::cout << \"x: \\n\" << x << std::endl;\n        }\n\n//        {\n//            Eigen::ConjugateGradient<MatrixReplacement<Scalar>, Eigen::Lower|Eigen::Upper, Eigen::IdentityPreconditioner> cg;\n//            cg.setMaxIterations(20000);\n//            cg.compute(matRepl);\n//            res = cg.solve(mps);\n//            std::cout << \"CG      : #iterations: \" << cg.iterations()\n//                      << \", #count: \" << matRepl.counter\n//                      << \", estimated error: \" << cg.error()\n//                      << std::endl;\n//        }\n\n\n\n\n}\nusing namespace tools::common::contraction;\ntemplate void tools::common::contraction::matrix_inverse_vector_product(\n    real * res_ptr,\n    const real * const mps_ptr, std::array<long,3> mps_dims,\n    const real * const mpo_ptr, std::array<long,4> mpo_dims,\n    const real * const envL_ptr, std::array<long,3> envL_dims,\n    const real * const envR_ptr, std::array<long,3> envR_dims);\ntemplate void tools::common::contraction::matrix_inverse_vector_product(\n    cplx * res_ptr,\n    const cplx * const mps_ptr, std::array<long,3> mps_dims,\n    const cplx * const mpo_ptr, std::array<long,4> mpo_dims,\n    const cplx * const envL_ptr, std::array<long,3> envL_dims,\n    const cplx * const envR_ptr, std::array<long,3> envR_dims);\n/* clang-format on */\n", "meta": {"hexsha": "9c9103b4950a496b04c785d3472eaf64f3f66e4a", "size": 11226, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/tools/common/contraction/matrix_inverse_vector_product.cpp", "max_stars_repo_name": "DavidAce/DMRG", "max_stars_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-10-31T22:50:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T15:45:27.000Z", "max_issues_repo_path": "source/tools/common/contraction/matrix_inverse_vector_product.cpp", "max_issues_repo_name": "DavidAce/DMRG", "max_issues_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332", "max_issues_repo_licenses": ["MIT"], "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/tools/common/contraction/matrix_inverse_vector_product.cpp", "max_forks_repo_name": "DavidAce/DMRG", "max_forks_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-16T00:27:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-16T00:27:56.000Z", "avg_line_length": 45.8204081633, "max_line_length": 167, "alphanum_fraction": 0.5814181365, "num_tokens": 2697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2500459831654072}}
